{"task_id": "Java_0", "language": "Java", "task_type": "method_signature", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.ejbcontainer.cdi_fat/test-applications/EJB31JCDIBean.jar/src/com/ibm/ws/ejbcontainer/cdi/jcdi/ejb/MultiLocalStatelessBean.java", "mask_start_position": 965, "mask_end_position": 989, "canonical_solution": "public String getName() ", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.ejbcontainer.cdi.jcdi.ejb;\n\nimport java.util.logging.Logger;\nimport javax.annotation.Resource;\nimport javax.ejb.Local;\nimport javax.ejb.Stateless;\n\n/**\n * Stateless bean with multiple local interfaces that should be able to lookup a BeanManager.\n */\n@Stateless(name = \"MultiLocalStateless\")\n@Local({ MultiLocalStatelessOne.class, MultiLocalStatelessTwo.class })\npublic class MultiLocalStatelessBean {\n\n private static final String CLASS_NAME = MultiLocalStatelessBean.class.getName();\n\n private static final Logger svLogger = Logger.getLogger(CLASS_NAME);\n\n @Resource(name = \"EJBName\")\n private String ivEJBName = \"MultiLocalStateless\";\n\n /**\n * Returns the EJB name.\n */\n ", "post_mask_code": "{\n svLogger.info(\"- \" + ivEJBName + \".getName() : ivEJBName\");\n return ivEJBName;\n }\n\n /**\n * Returns the EJB name.\n */\n public String getEjbName() {\n svLogger.info(\"- \" + ivEJBName + \".getEjbName() : ivEJBName\");\n return ivEJBName;\n }\n}\n"} {"task_id": "Java_1", "language": "Java", "task_type": "method_body", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.ejbcontainer.cdi_fat/test-applications/EJB31JCDIBean.jar/src/com/ibm/ws/ejbcontainer/cdi/jcdi/ejb/MultiLocalStatelessBean.java", "mask_start_position": 989, "mask_end_position": 1090, "canonical_solution": "{\n svLogger.info(\"- \" + ivEJBName + \".getName() : ivEJBName\");\n return ivEJBName;\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.ejbcontainer.cdi.jcdi.ejb;\n\nimport java.util.logging.Logger;\nimport javax.annotation.Resource;\nimport javax.ejb.Local;\nimport javax.ejb.Stateless;\n\n/**\n * Stateless bean with multiple local interfaces that should be able to lookup a BeanManager.\n */\n@Stateless(name = \"MultiLocalStateless\")\n@Local({ MultiLocalStatelessOne.class, MultiLocalStatelessTwo.class })\npublic class MultiLocalStatelessBean {\n\n private static final String CLASS_NAME = MultiLocalStatelessBean.class.getName();\n\n private static final Logger svLogger = Logger.getLogger(CLASS_NAME);\n\n @Resource(name = \"EJBName\")\n private String ivEJBName = \"MultiLocalStateless\";\n\n /**\n * Returns the EJB name.\n */\n public String getName() ", "post_mask_code": "\n\n /**\n * Returns the EJB name.\n */\n public String getEjbName() {\n svLogger.info(\"- \" + ivEJBName + \".getEjbName() : ivEJBName\");\n return ivEJBName;\n }\n}\n"} {"task_id": "Java_2", "language": "Java", "task_type": "single_line", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.ejbcontainer.cdi_fat/test-applications/EJB31JCDIBean.jar/src/com/ibm/ws/ejbcontainer/cdi/jcdi/ejb/MultiLocalStatelessBean.java", "mask_start_position": 1072, "mask_end_position": 1084, "canonical_solution": "n ivEJBName;", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.ejbcontainer.cdi.jcdi.ejb;\n\nimport java.util.logging.Logger;\nimport javax.annotation.Resource;\nimport javax.ejb.Local;\nimport javax.ejb.Stateless;\n\n/**\n * Stateless bean with multiple local interfaces that should be able to lookup a BeanManager.\n */\n@Stateless(name = \"MultiLocalStateless\")\n@Local({ MultiLocalStatelessOne.class, MultiLocalStatelessTwo.class })\npublic class MultiLocalStatelessBean {\n\n private static final String CLASS_NAME = MultiLocalStatelessBean.class.getName();\n\n private static final Logger svLogger = Logger.getLogger(CLASS_NAME);\n\n @Resource(name = \"EJBName\")\n private String ivEJBName = \"MultiLocalStateless\";\n\n /**\n * Returns the EJB name.\n */\n public String getName() {\n svLogger.info(\"- \" + ivEJBName + \".getName() : ivEJBName\");\n retur", "post_mask_code": "\n }\n\n /**\n * Returns the EJB name.\n */\n public String getEjbName() {\n svLogger.info(\"- \" + ivEJBName + \".getEjbName() : ivEJBName\");\n return ivEJBName;\n }\n}\n"} {"task_id": "Java_3", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.ejbcontainer.cdi_fat/test-applications/EJB31JCDIBean.jar/src/com/ibm/ws/ejbcontainer/cdi/jcdi/ejb/MultiLocalStatelessBean.java", "mask_start_position": 965, "mask_end_position": 1090, "canonical_solution": "public String getName() {\n svLogger.info(\"- \" + ivEJBName + \".getName() : ivEJBName\");\n return ivEJBName;\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.ejbcontainer.cdi.jcdi.ejb;\n\nimport java.util.logging.Logger;\nimport javax.annotation.Resource;\nimport javax.ejb.Local;\nimport javax.ejb.Stateless;\n\n/**\n * Stateless bean with multiple local interfaces that should be able to lookup a BeanManager.\n */\n@Stateless(name = \"MultiLocalStateless\")\n@Local({ MultiLocalStatelessOne.class, MultiLocalStatelessTwo.class })\npublic class MultiLocalStatelessBean {\n\n private static final String CLASS_NAME = MultiLocalStatelessBean.class.getName();\n\n private static final Logger svLogger = Logger.getLogger(CLASS_NAME);\n\n @Resource(name = \"EJBName\")\n private String ivEJBName = \"MultiLocalStateless\";\n\n /**\n * Returns the EJB name.\n */\n ", "post_mask_code": "\n\n /**\n * Returns the EJB name.\n */\n public String getEjbName() {\n svLogger.info(\"- \" + ivEJBName + \".getEjbName() : ivEJBName\");\n return ivEJBName;\n }\n}\n"} {"task_id": "Java_4", "language": "Java", "task_type": "empty", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.ejbcontainer.cdi_fat/test-applications/EJB31JCDIBean.jar/src/com/ibm/ws/ejbcontainer/cdi/jcdi/ejb/MultiLocalStatelessBean.java", "mask_start_position": 56, "mask_end_position": 56, "canonical_solution": "", "pre_mask_code": "/**\n * *************************************************", "post_mask_code": "***************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.ejbcontainer.cdi.jcdi.ejb;\n\nimport java.util.logging.Logger;\nimport javax.annotation.Resource;\nimport javax.ejb.Local;\nimport javax.ejb.Stateless;\n\n/**\n * Stateless bean with multiple local interfaces that should be able to lookup a BeanManager.\n */\n@Stateless(name = \"MultiLocalStateless\")\n@Local({ MultiLocalStatelessOne.class, MultiLocalStatelessTwo.class })\npublic class MultiLocalStatelessBean {\n\n private static final String CLASS_NAME = MultiLocalStatelessBean.class.getName();\n\n private static final Logger svLogger = Logger.getLogger(CLASS_NAME);\n\n @Resource(name = \"EJBName\")\n private String ivEJBName = \"MultiLocalStateless\";\n\n /**\n * Returns the EJB name.\n */\n public String getName() {\n svLogger.info(\"- \" + ivEJBName + \".getName() : ivEJBName\");\n return ivEJBName;\n }\n\n /**\n * Returns the EJB name.\n */\n public String getEjbName() {\n svLogger.info(\"- \" + ivEJBName + \".getEjbName() : ivEJBName\");\n return ivEJBName;\n }\n}\n"} {"task_id": "Java_5", "language": "Java", "task_type": "method_signature", "source_file": "java/github/kawhii/sso/sso-support/sso-support-validate/src/main/java/com/carl/sso/support/validate/configuration/MailProperties.java", "mask_start_position": 716, "mask_end_position": 755, "canonical_solution": "public void setContent(String content) ", "pre_mask_code": "package com.carl.sso.support.validate.configuration;\n\nimport java.io.Serializable;\n\n/**\n * @author Carl\n * @date 2017/11/2\n * @since\n */\npublic class MailProperties implements Serializable {\n\n private boolean enable = true;\n\n // 有效期,十分钟有效\n private long effective = 60 * 10;\n\n // 邮件内容,例如:你的验证码为%s\n private String content = \"欢迎注册,你的验证码为:%s(统一登录门户)\";\n\n private String subject = \"统一门户注册验证码\";\n\n // 来自哪个用户发送\n private String from;\n\n // 验证码长度\n private int codeLen = 6;\n\n public long getEffective() {\n return effective;\n }\n\n public void setEffective(long effective) {\n this.effective = effective;\n }\n\n public String getContent() {\n return content;\n }\n\n ", "post_mask_code": "{\n this.content = content;\n }\n\n public boolean isEnable() {\n return enable;\n }\n\n public void setEnable(boolean enable) {\n this.enable = enable;\n }\n\n public String getSubject() {\n return subject;\n }\n\n public void setSubject(String subject) {\n this.subject = subject;\n }\n\n public String getFrom() {\n return from;\n }\n\n public void setFrom(String from) {\n this.from = from;\n }\n\n public int getCodeLen() {\n return codeLen;\n }\n\n public void setCodeLen(int codeLen) {\n this.codeLen = codeLen;\n }\n}\n"} {"task_id": "Java_6", "language": "Java", "task_type": "method_body", "source_file": "java/github/kawhii/sso/sso-support/sso-support-validate/src/main/java/com/carl/sso/support/validate/configuration/MailProperties.java", "mask_start_position": 900, "mask_end_position": 937, "canonical_solution": "{\n this.enable = enable;\n }", "pre_mask_code": "package com.carl.sso.support.validate.configuration;\n\nimport java.io.Serializable;\n\n/**\n * @author Carl\n * @date 2017/11/2\n * @since\n */\npublic class MailProperties implements Serializable {\n\n private boolean enable = true;\n\n // 有效期,十分钟有效\n private long effective = 60 * 10;\n\n // 邮件内容,例如:你的验证码为%s\n private String content = \"欢迎注册,你的验证码为:%s(统一登录门户)\";\n\n private String subject = \"统一门户注册验证码\";\n\n // 来自哪个用户发送\n private String from;\n\n // 验证码长度\n private int codeLen = 6;\n\n public long getEffective() {\n return effective;\n }\n\n public void setEffective(long effective) {\n this.effective = effective;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public boolean isEnable() {\n return enable;\n }\n\n public void setEnable(boolean enable) ", "post_mask_code": "\n\n public String getSubject() {\n return subject;\n }\n\n public void setSubject(String subject) {\n this.subject = subject;\n }\n\n public String getFrom() {\n return from;\n }\n\n public void setFrom(String from) {\n this.from = from;\n }\n\n public int getCodeLen() {\n return codeLen;\n }\n\n public void setCodeLen(int codeLen) {\n this.codeLen = codeLen;\n }\n}\n"} {"task_id": "Java_7", "language": "Java", "task_type": "single_line", "source_file": "java/github/kawhii/sso/sso-support/sso-support-validate/src/main/java/com/carl/sso/support/validate/configuration/MailProperties.java", "mask_start_position": 1205, "mask_end_position": 1209, "canonical_solution": "rom;", "pre_mask_code": "package com.carl.sso.support.validate.configuration;\n\nimport java.io.Serializable;\n\n/**\n * @author Carl\n * @date 2017/11/2\n * @since\n */\npublic class MailProperties implements Serializable {\n\n private boolean enable = true;\n\n // 有效期,十分钟有效\n private long effective = 60 * 10;\n\n // 邮件内容,例如:你的验证码为%s\n private String content = \"欢迎注册,你的验证码为:%s(统一登录门户)\";\n\n private String subject = \"统一门户注册验证码\";\n\n // 来自哪个用户发送\n private String from;\n\n // 验证码长度\n private int codeLen = 6;\n\n public long getEffective() {\n return effective;\n }\n\n public void setEffective(long effective) {\n this.effective = effective;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public boolean isEnable() {\n return enable;\n }\n\n public void setEnable(boolean enable) {\n this.enable = enable;\n }\n\n public String getSubject() {\n return subject;\n }\n\n public void setSubject(String subject) {\n this.subject = subject;\n }\n\n public String getFrom() {\n return from;\n }\n\n public void setFrom(String from) {\n this.from = f", "post_mask_code": "\n }\n\n public int getCodeLen() {\n return codeLen;\n }\n\n public void setCodeLen(int codeLen) {\n this.codeLen = codeLen;\n }\n}\n"} {"task_id": "Java_8", "language": "Java", "task_type": "empty", "source_file": "java/github/kawhii/sso/sso-support/sso-support-validate/src/main/java/com/carl/sso/support/validate/configuration/MailProperties.java", "mask_start_position": 252, "mask_end_position": 252, "canonical_solution": "", "pre_mask_code": "package com.carl.sso.support.validate.configuration;\n\nimport java.io.Serializable;\n\n/**\n * @author Carl\n * @date 2017/11/2\n * @since\n */\npublic class MailProperties implements Serializable {\n\n private boolean enable = true;\n\n // 有效期,十分钟有效\n pri", "post_mask_code": "vate long effective = 60 * 10;\n\n // 邮件内容,例如:你的验证码为%s\n private String content = \"欢迎注册,你的验证码为:%s(统一登录门户)\";\n\n private String subject = \"统一门户注册验证码\";\n\n // 来自哪个用户发送\n private String from;\n\n // 验证码长度\n private int codeLen = 6;\n\n public long getEffective() {\n return effective;\n }\n\n public void setEffective(long effective) {\n this.effective = effective;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public boolean isEnable() {\n return enable;\n }\n\n public void setEnable(boolean enable) {\n this.enable = enable;\n }\n\n public String getSubject() {\n return subject;\n }\n\n public void setSubject(String subject) {\n this.subject = subject;\n }\n\n public String getFrom() {\n return from;\n }\n\n public void setFrom(String from) {\n this.from = from;\n }\n\n public int getCodeLen() {\n return codeLen;\n }\n\n public void setCodeLen(int codeLen) {\n this.codeLen = codeLen;\n }\n}\n"} {"task_id": "Java_9", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ibm-messaging/mq-dev-patterns/Spring-JMS/src/main/java/com/ibm/mq/samples/jms/spring/globals/utils/MessageUtils.java", "mask_start_position": 539, "mask_end_position": 592, "canonical_solution": "public static void checkMessageType(Message message) ", "pre_mask_code": "package com.ibm.mq.samples.jms.spring.globals.utils;\n\nimport com.ibm.mq.samples.jms.spring.globals.Constants;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurData;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurOtherData;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport javax.jms.*;\nimport java.io.Serializable;\nimport java.util.Map;\n\npublic class MessageUtils {\n\n protected static final Log logger = LogFactory.getLog(MessageUtils.class);\n\n private MessageUtils() {\n }\n\n ", "post_mask_code": "{\n try {\n if (message instanceof TextMessage) {\n logger.info(\"Message matches TextMessage\");\n logger.info(\"message payload is \" + ((TextMessage) message).getText());\n } else if (message instanceof BytesMessage) {\n logger.info(\"Message matches BytesMessage\");\n } else if (message instanceof MapMessage) {\n logger.info(\"Message matches MapMessage\");\n } else if (message instanceof StreamMessage) {\n logger.info(\"Message matches StreamMessage\");\n } else if (message instanceof ObjectMessage) {\n checkForObject((ObjectMessage) message);\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to process JMS message\");\n }\n }\n\n public static void logHeaders(Map msgHeaders) {\n if (!msgHeaders.isEmpty()) {\n logger.info(\"\");\n logger.info(\"Headers found\");\n msgHeaders.forEach((k, v) -> {\n logger.info(k + \": is of type\" + v.getClass());\n });\n }\n }\n\n private static void checkForObject(ObjectMessage message) {\n try {\n int typeValue = message.getIntProperty(Constants.DATATYPE);\n if (Constants.DataTypes.OURDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our objects\");\n Serializable serObj = message.getObject();\n OurData data = (OurData) serObj;\n logger.info(data);\n } else if (Constants.DataTypes.OUROTHERDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our other objects\");\n Serializable serObj = message.getObject();\n OurOtherData data = (OurOtherData) serObj;\n logger.info(data);\n } else {\n logger.warn(\"It is not one of our objects\");\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to retrieve message data\");\n } catch (ClassCastException e2) {\n logger.warn(\"Not the object we were expecting\");\n }\n }\n}\n"} {"task_id": "Java_10", "language": "Java", "task_type": "method_body", "source_file": "java/github/ibm-messaging/mq-dev-patterns/Spring-JMS/src/main/java/com/ibm/mq/samples/jms/spring/globals/utils/MessageUtils.java", "mask_start_position": 1467, "mask_end_position": 1715, "canonical_solution": "{\n if (!msgHeaders.isEmpty()) {\n logger.info(\"\");\n logger.info(\"Headers found\");\n msgHeaders.forEach((k, v) -> {\n logger.info(k + \": is of type\" + v.getClass());\n });\n }\n }", "pre_mask_code": "package com.ibm.mq.samples.jms.spring.globals.utils;\n\nimport com.ibm.mq.samples.jms.spring.globals.Constants;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurData;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurOtherData;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport javax.jms.*;\nimport java.io.Serializable;\nimport java.util.Map;\n\npublic class MessageUtils {\n\n protected static final Log logger = LogFactory.getLog(MessageUtils.class);\n\n private MessageUtils() {\n }\n\n public static void checkMessageType(Message message) {\n try {\n if (message instanceof TextMessage) {\n logger.info(\"Message matches TextMessage\");\n logger.info(\"message payload is \" + ((TextMessage) message).getText());\n } else if (message instanceof BytesMessage) {\n logger.info(\"Message matches BytesMessage\");\n } else if (message instanceof MapMessage) {\n logger.info(\"Message matches MapMessage\");\n } else if (message instanceof StreamMessage) {\n logger.info(\"Message matches StreamMessage\");\n } else if (message instanceof ObjectMessage) {\n checkForObject((ObjectMessage) message);\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to process JMS message\");\n }\n }\n\n public static void logHeaders(Map msgHeaders) ", "post_mask_code": "\n\n private static void checkForObject(ObjectMessage message) {\n try {\n int typeValue = message.getIntProperty(Constants.DATATYPE);\n if (Constants.DataTypes.OURDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our objects\");\n Serializable serObj = message.getObject();\n OurData data = (OurData) serObj;\n logger.info(data);\n } else if (Constants.DataTypes.OUROTHERDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our other objects\");\n Serializable serObj = message.getObject();\n OurOtherData data = (OurOtherData) serObj;\n logger.info(data);\n } else {\n logger.warn(\"It is not one of our objects\");\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to retrieve message data\");\n } catch (ClassCastException e2) {\n logger.warn(\"Not the object we were expecting\");\n }\n }\n}\n"} {"task_id": "Java_11", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/ibm-messaging/mq-dev-patterns/Spring-JMS/src/main/java/com/ibm/mq/samples/jms/spring/globals/utils/MessageUtils.java", "mask_start_position": 1468, "mask_end_position": 1468, "canonical_solution": "", "pre_mask_code": "package com.ibm.mq.samples.jms.spring.globals.utils;\n\nimport com.ibm.mq.samples.jms.spring.globals.Constants;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurData;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurOtherData;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport javax.jms.*;\nimport java.io.Serializable;\nimport java.util.Map;\n\npublic class MessageUtils {\n\n protected static final Log logger = LogFactory.getLog(MessageUtils.class);\n\n private MessageUtils() {\n }\n\n public static void checkMessageType(Message message) {\n try {\n if (message instanceof TextMessage) {\n logger.info(\"Message matches TextMessage\");\n logger.info(\"message payload is \" + ((TextMessage) message).getText());\n } else if (message instanceof BytesMessage) {\n logger.info(\"Message matches BytesMessage\");\n } else if (message instanceof MapMessage) {\n logger.info(\"Message matches MapMessage\");\n } else if (message instanceof StreamMessage) {\n logger.info(\"Message matches StreamMessage\");\n } else if (message instanceof ObjectMessage) {\n checkForObject((ObjectMessage) message);\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to process JMS message\");\n }\n }\n\n public static void logHeaders(Map msgHeaders) {", "post_mask_code": "\n if (!msgHeaders.isEmpty()) {\n logger.info(\"\");\n logger.info(\"Headers found\");\n msgHeaders.forEach((k, v) -> {\n logger.info(k + \": is of type\" + v.getClass());\n });\n }\n }\n\n private static void checkForObject(ObjectMessage message) {\n try {\n int typeValue = message.getIntProperty(Constants.DATATYPE);\n if (Constants.DataTypes.OURDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our objects\");\n Serializable serObj = message.getObject();\n OurData data = (OurData) serObj;\n logger.info(data);\n } else if (Constants.DataTypes.OUROTHERDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our other objects\");\n Serializable serObj = message.getObject();\n OurOtherData data = (OurOtherData) serObj;\n logger.info(data);\n } else {\n logger.warn(\"It is not one of our objects\");\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to retrieve message data\");\n } catch (ClassCastException e2) {\n logger.warn(\"Not the object we were expecting\");\n }\n }\n}\n"} {"task_id": "Java_12", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/ibm-messaging/mq-dev-patterns/Spring-JMS/src/main/java/com/ibm/mq/samples/jms/spring/globals/utils/MessageUtils.java", "mask_start_position": 1477, "mask_end_position": 1709, "canonical_solution": "if (!msgHeaders.isEmpty()) {\n logger.info(\"\");\n logger.info(\"Headers found\");\n msgHeaders.forEach((k, v) -> {\n logger.info(k + \": is of type\" + v.getClass());\n });\n }", "pre_mask_code": "package com.ibm.mq.samples.jms.spring.globals.utils;\n\nimport com.ibm.mq.samples.jms.spring.globals.Constants;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurData;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurOtherData;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport javax.jms.*;\nimport java.io.Serializable;\nimport java.util.Map;\n\npublic class MessageUtils {\n\n protected static final Log logger = LogFactory.getLog(MessageUtils.class);\n\n private MessageUtils() {\n }\n\n public static void checkMessageType(Message message) {\n try {\n if (message instanceof TextMessage) {\n logger.info(\"Message matches TextMessage\");\n logger.info(\"message payload is \" + ((TextMessage) message).getText());\n } else if (message instanceof BytesMessage) {\n logger.info(\"Message matches BytesMessage\");\n } else if (message instanceof MapMessage) {\n logger.info(\"Message matches MapMessage\");\n } else if (message instanceof StreamMessage) {\n logger.info(\"Message matches StreamMessage\");\n } else if (message instanceof ObjectMessage) {\n checkForObject((ObjectMessage) message);\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to process JMS message\");\n }\n }\n\n public static void logHeaders(Map msgHeaders) {\n ", "post_mask_code": "\n }\n\n private static void checkForObject(ObjectMessage message) {\n try {\n int typeValue = message.getIntProperty(Constants.DATATYPE);\n if (Constants.DataTypes.OURDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our objects\");\n Serializable serObj = message.getObject();\n OurData data = (OurData) serObj;\n logger.info(data);\n } else if (Constants.DataTypes.OUROTHERDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our other objects\");\n Serializable serObj = message.getObject();\n OurOtherData data = (OurOtherData) serObj;\n logger.info(data);\n } else {\n logger.warn(\"It is not one of our objects\");\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to retrieve message data\");\n } catch (ClassCastException e2) {\n logger.warn(\"Not the object we were expecting\");\n }\n }\n}\n"} {"task_id": "Java_13", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/ibm-messaging/mq-dev-patterns/Spring-JMS/src/main/java/com/ibm/mq/samples/jms/spring/globals/utils/MessageUtils.java", "mask_start_position": 1714, "mask_end_position": 1715, "canonical_solution": "}", "pre_mask_code": "package com.ibm.mq.samples.jms.spring.globals.utils;\n\nimport com.ibm.mq.samples.jms.spring.globals.Constants;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurData;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurOtherData;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport javax.jms.*;\nimport java.io.Serializable;\nimport java.util.Map;\n\npublic class MessageUtils {\n\n protected static final Log logger = LogFactory.getLog(MessageUtils.class);\n\n private MessageUtils() {\n }\n\n public static void checkMessageType(Message message) {\n try {\n if (message instanceof TextMessage) {\n logger.info(\"Message matches TextMessage\");\n logger.info(\"message payload is \" + ((TextMessage) message).getText());\n } else if (message instanceof BytesMessage) {\n logger.info(\"Message matches BytesMessage\");\n } else if (message instanceof MapMessage) {\n logger.info(\"Message matches MapMessage\");\n } else if (message instanceof StreamMessage) {\n logger.info(\"Message matches StreamMessage\");\n } else if (message instanceof ObjectMessage) {\n checkForObject((ObjectMessage) message);\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to process JMS message\");\n }\n }\n\n public static void logHeaders(Map msgHeaders) {\n if (!msgHeaders.isEmpty()) {\n logger.info(\"\");\n logger.info(\"Headers found\");\n msgHeaders.forEach((k, v) -> {\n logger.info(k + \": is of type\" + v.getClass());\n });\n }\n ", "post_mask_code": "\n\n private static void checkForObject(ObjectMessage message) {\n try {\n int typeValue = message.getIntProperty(Constants.DATATYPE);\n if (Constants.DataTypes.OURDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our objects\");\n Serializable serObj = message.getObject();\n OurData data = (OurData) serObj;\n logger.info(data);\n } else if (Constants.DataTypes.OUROTHERDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our other objects\");\n Serializable serObj = message.getObject();\n OurOtherData data = (OurOtherData) serObj;\n logger.info(data);\n } else {\n logger.warn(\"It is not one of our objects\");\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to retrieve message data\");\n } catch (ClassCastException e2) {\n logger.warn(\"Not the object we were expecting\");\n }\n }\n}\n"} {"task_id": "Java_14", "language": "Java", "task_type": "if_statement", "source_file": "java/github/ibm-messaging/mq-dev-patterns/Spring-JMS/src/main/java/com/ibm/mq/samples/jms/spring/globals/utils/MessageUtils.java", "mask_start_position": 825, "mask_end_position": 1290, "canonical_solution": "if (message instanceof BytesMessage) {\n logger.info(\"Message matches BytesMessage\");\n } else if (message instanceof MapMessage) {\n logger.info(\"Message matches MapMessage\");\n } else if (message instanceof StreamMessage) {\n logger.info(\"Message matches StreamMessage\");\n } else if (message instanceof ObjectMessage) {\n checkForObject((ObjectMessage) message);\n }", "pre_mask_code": "package com.ibm.mq.samples.jms.spring.globals.utils;\n\nimport com.ibm.mq.samples.jms.spring.globals.Constants;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurData;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurOtherData;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport javax.jms.*;\nimport java.io.Serializable;\nimport java.util.Map;\n\npublic class MessageUtils {\n\n protected static final Log logger = LogFactory.getLog(MessageUtils.class);\n\n private MessageUtils() {\n }\n\n public static void checkMessageType(Message message) {\n try {\n if (message instanceof TextMessage) {\n logger.info(\"Message matches TextMessage\");\n logger.info(\"message payload is \" + ((TextMessage) message).getText());\n } else ", "post_mask_code": "\n } catch (JMSException e) {\n logger.warn(\"Unable to process JMS message\");\n }\n }\n\n public static void logHeaders(Map msgHeaders) {\n if (!msgHeaders.isEmpty()) {\n logger.info(\"\");\n logger.info(\"Headers found\");\n msgHeaders.forEach((k, v) -> {\n logger.info(k + \": is of type\" + v.getClass());\n });\n }\n }\n\n private static void checkForObject(ObjectMessage message) {\n try {\n int typeValue = message.getIntProperty(Constants.DATATYPE);\n if (Constants.DataTypes.OURDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our objects\");\n Serializable serObj = message.getObject();\n OurData data = (OurData) serObj;\n logger.info(data);\n } else if (Constants.DataTypes.OUROTHERDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our other objects\");\n Serializable serObj = message.getObject();\n OurOtherData data = (OurOtherData) serObj;\n logger.info(data);\n } else {\n logger.warn(\"It is not one of our objects\");\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to retrieve message data\");\n } catch (ClassCastException e2) {\n logger.warn(\"Not the object we were expecting\");\n }\n }\n}\n"} {"task_id": "Java_15", "language": "Java", "task_type": "empty", "source_file": "java/github/ibm-messaging/mq-dev-patterns/Spring-JMS/src/main/java/com/ibm/mq/samples/jms/spring/globals/utils/MessageUtils.java", "mask_start_position": 1082, "mask_end_position": 1082, "canonical_solution": "", "pre_mask_code": "package com.ibm.mq.samples.jms.spring.globals.utils;\n\nimport com.ibm.mq.samples.jms.spring.globals.Constants;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurData;\nimport com.ibm.mq.samples.jms.spring.globals.data.OurOtherData;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport javax.jms.*;\nimport java.io.Serializable;\nimport java.util.Map;\n\npublic class MessageUtils {\n\n protected static final Log logger = LogFactory.getLog(MessageUtils.class);\n\n private MessageUtils() {\n }\n\n public static void checkMessageType(Message message) {\n try {\n if (message instanceof TextMessage) {\n logger.info(\"Message matches TextMessage\");\n logger.info(\"message payload is \" + ((TextMessage) message).getText());\n } else if (message instanceof BytesMessage) {\n logger.info(\"Message matches BytesMessage\");\n } else if (message instanceof MapMessage) {\n logger.info(\"Message matches MapMessage\");\n } else if (message instanceof ", "post_mask_code": "StreamMessage) {\n logger.info(\"Message matches StreamMessage\");\n } else if (message instanceof ObjectMessage) {\n checkForObject((ObjectMessage) message);\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to process JMS message\");\n }\n }\n\n public static void logHeaders(Map msgHeaders) {\n if (!msgHeaders.isEmpty()) {\n logger.info(\"\");\n logger.info(\"Headers found\");\n msgHeaders.forEach((k, v) -> {\n logger.info(k + \": is of type\" + v.getClass());\n });\n }\n }\n\n private static void checkForObject(ObjectMessage message) {\n try {\n int typeValue = message.getIntProperty(Constants.DATATYPE);\n if (Constants.DataTypes.OURDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our objects\");\n Serializable serObj = message.getObject();\n OurData data = (OurData) serObj;\n logger.info(data);\n } else if (Constants.DataTypes.OUROTHERDATATYPE.getValue() == typeValue) {\n logger.info(\"It is one of our other objects\");\n Serializable serObj = message.getObject();\n OurOtherData data = (OurOtherData) serObj;\n logger.info(data);\n } else {\n logger.warn(\"It is not one of our objects\");\n }\n } catch (JMSException e) {\n logger.warn(\"Unable to retrieve message data\");\n } catch (ClassCastException e2) {\n logger.warn(\"Not the object we were expecting\");\n }\n }\n}\n"} {"task_id": "Java_16", "language": "Java", "task_type": "method_signature", "source_file": "java/github/linagora/linshare-core/src/main/java/org/linagora/linshare/core/domain/entities/StringValueFunctionality.java", "mask_start_position": 2058, "mask_end_position": 2152, "canonical_solution": "@Override\n public boolean businessEquals(AbstractFunctionality obj, boolean checkPolicies) ", "pre_mask_code": "/*\n * LinShare is an open source filesharing software developed by LINAGORA.\n * \n * \n * notably (i) retain the display in the interface of the “LinShare™”\n * trademark/logo, the \"Libre & Free\" mention, the words “You are using the Free\n * Contribute to Linshare R&D by subscribing to an Enterprise offer!”. You must\n * also retain the latter notice in all asynchronous messages such as e-mails\n * sent with the Program, (ii) retain all hypertext links between LinShare and\n * http://www.linshare.org, between linagora.com and Linagora, and (iii) refrain\n * from infringing Linagora intellectual property rights over its trademarks and\n * commercial brands. Other Additional Terms apply, see\n * version 3 and\n * for the\n * Additional Terms applicable to LinShare software.\n */\npackage org.linagora.linshare.core.domain.entities;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.linagora.linshare.core.domain.constants.FunctionalityType;\nimport org.linagora.linshare.core.facade.webservice.admin.dto.FunctionalityAdminDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.StringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.nested.NestedStringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.common.dto.ParameterDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityStringDto;\n\npublic class StringValueFunctionality extends OneValueFunctionality {\n\n public StringValueFunctionality() {\n super();\n }\n\n public StringValueFunctionality(String identifier, boolean system, Policy activationPolicy, Policy configurationPolicy, AbstractDomain domain, String value) {\n super(identifier, system, activationPolicy, configurationPolicy, domain, value);\n }\n\n @Override\n public FunctionalityType getType() {\n return FunctionalityType.STRING;\n }\n\n ", "post_mask_code": "{\n if (super.businessEquals(obj, checkPolicies)) {\n StringValueFunctionality o = (StringValueFunctionality) obj;\n if (value.equals(o.getValue())) {\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is equal to StringValueFunctionality \" + obj.toString());\n return true;\n }\n }\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is not equal to StringValueFunctionality \" + obj.toString());\n return false;\n }\n\n @Override\n public void updateFunctionalityFrom(AbstractFunctionality functionality) {\n super.updateFunctionalityFrom(functionality);\n this.updateFunctionalityValuesOnlyFrom(functionality);\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFrom(AbstractFunctionality functionality) {\n StringValueFunctionality f = (StringValueFunctionality) functionality;\n this.value = f.getValue();\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFromDto(Integer version, FunctionalityAdminDto functionality) {\n List parameters = functionality.getParameters();\n if (parameters != null && !parameters.isEmpty()) {\n ParameterDto parameterDto = parameters.get(0);\n this.value = parameterDto.getString();\n }\n }\n\n @Override\n public List getParameters(Integer version) {\n List res = new ArrayList();\n res.add(new ParameterDto(this.getValue()));\n return res;\n }\n\n @Override\n protected FunctionalityDto getUserDto(boolean enable, Integer version) {\n FunctionalityStringDto f = new FunctionalityStringDto();\n if (enable) {\n f.setValue(value);\n }\n return f;\n }\n\n @Override\n public org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.ParameterDto getParameter() {\n // there is no default value for functionality parameters. sad.\n String parentValue = this.value;\n if (this.ancestorFunc != null) {\n parentValue = ((StringValueFunctionality) this.ancestorFunc).getValue();\n }\n NestedStringParameterDto defaut = new NestedStringParameterDto(this.value, parentValue);\n return new StringParameterDto(this.system, !this.getParentAllowParametersUpdate(), defaut);\n }\n}\n"} {"task_id": "Java_17", "language": "Java", "task_type": "method_body", "source_file": "java/github/linagora/linshare-core/src/main/java/org/linagora/linshare/core/domain/entities/StringValueFunctionality.java", "mask_start_position": 4094, "mask_end_position": 4547, "canonical_solution": "{\n // there is no default value for functionality parameters. sad.\n String parentValue = this.value;\n if (this.ancestorFunc != null) {\n parentValue = ((StringValueFunctionality) this.ancestorFunc).getValue();\n }\n NestedStringParameterDto defaut = new NestedStringParameterDto(this.value, parentValue);\n return new StringParameterDto(this.system, !this.getParentAllowParametersUpdate(), defaut);\n }", "pre_mask_code": "/*\n * LinShare is an open source filesharing software developed by LINAGORA.\n * \n * \n * notably (i) retain the display in the interface of the “LinShare™”\n * trademark/logo, the \"Libre & Free\" mention, the words “You are using the Free\n * Contribute to Linshare R&D by subscribing to an Enterprise offer!”. You must\n * also retain the latter notice in all asynchronous messages such as e-mails\n * sent with the Program, (ii) retain all hypertext links between LinShare and\n * http://www.linshare.org, between linagora.com and Linagora, and (iii) refrain\n * from infringing Linagora intellectual property rights over its trademarks and\n * commercial brands. Other Additional Terms apply, see\n * version 3 and\n * for the\n * Additional Terms applicable to LinShare software.\n */\npackage org.linagora.linshare.core.domain.entities;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.linagora.linshare.core.domain.constants.FunctionalityType;\nimport org.linagora.linshare.core.facade.webservice.admin.dto.FunctionalityAdminDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.StringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.nested.NestedStringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.common.dto.ParameterDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityStringDto;\n\npublic class StringValueFunctionality extends OneValueFunctionality {\n\n public StringValueFunctionality() {\n super();\n }\n\n public StringValueFunctionality(String identifier, boolean system, Policy activationPolicy, Policy configurationPolicy, AbstractDomain domain, String value) {\n super(identifier, system, activationPolicy, configurationPolicy, domain, value);\n }\n\n @Override\n public FunctionalityType getType() {\n return FunctionalityType.STRING;\n }\n\n @Override\n public boolean businessEquals(AbstractFunctionality obj, boolean checkPolicies) {\n if (super.businessEquals(obj, checkPolicies)) {\n StringValueFunctionality o = (StringValueFunctionality) obj;\n if (value.equals(o.getValue())) {\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is equal to StringValueFunctionality \" + obj.toString());\n return true;\n }\n }\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is not equal to StringValueFunctionality \" + obj.toString());\n return false;\n }\n\n @Override\n public void updateFunctionalityFrom(AbstractFunctionality functionality) {\n super.updateFunctionalityFrom(functionality);\n this.updateFunctionalityValuesOnlyFrom(functionality);\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFrom(AbstractFunctionality functionality) {\n StringValueFunctionality f = (StringValueFunctionality) functionality;\n this.value = f.getValue();\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFromDto(Integer version, FunctionalityAdminDto functionality) {\n List parameters = functionality.getParameters();\n if (parameters != null && !parameters.isEmpty()) {\n ParameterDto parameterDto = parameters.get(0);\n this.value = parameterDto.getString();\n }\n }\n\n @Override\n public List getParameters(Integer version) {\n List res = new ArrayList();\n res.add(new ParameterDto(this.getValue()));\n return res;\n }\n\n @Override\n protected FunctionalityDto getUserDto(boolean enable, Integer version) {\n FunctionalityStringDto f = new FunctionalityStringDto();\n if (enable) {\n f.setValue(value);\n }\n return f;\n }\n\n @Override\n public org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.ParameterDto getParameter() ", "post_mask_code": "\n}\n"} {"task_id": "Java_18", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/linagora/linshare-core/src/main/java/org/linagora/linshare/core/domain/entities/StringValueFunctionality.java", "mask_start_position": 2153, "mask_end_position": 2520, "canonical_solution": "\n if (super.businessEquals(obj, checkPolicies)) {\n StringValueFunctionality o = (StringValueFunctionality) obj;\n if (value.equals(o.getValue())) {\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is equal to StringValueFunctionality \" + obj.toString());\n return true;\n }\n }", "pre_mask_code": "/*\n * LinShare is an open source filesharing software developed by LINAGORA.\n * \n * \n * notably (i) retain the display in the interface of the “LinShare™”\n * trademark/logo, the \"Libre & Free\" mention, the words “You are using the Free\n * Contribute to Linshare R&D by subscribing to an Enterprise offer!”. You must\n * also retain the latter notice in all asynchronous messages such as e-mails\n * sent with the Program, (ii) retain all hypertext links between LinShare and\n * http://www.linshare.org, between linagora.com and Linagora, and (iii) refrain\n * from infringing Linagora intellectual property rights over its trademarks and\n * commercial brands. Other Additional Terms apply, see\n * version 3 and\n * for the\n * Additional Terms applicable to LinShare software.\n */\npackage org.linagora.linshare.core.domain.entities;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.linagora.linshare.core.domain.constants.FunctionalityType;\nimport org.linagora.linshare.core.facade.webservice.admin.dto.FunctionalityAdminDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.StringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.nested.NestedStringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.common.dto.ParameterDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityStringDto;\n\npublic class StringValueFunctionality extends OneValueFunctionality {\n\n public StringValueFunctionality() {\n super();\n }\n\n public StringValueFunctionality(String identifier, boolean system, Policy activationPolicy, Policy configurationPolicy, AbstractDomain domain, String value) {\n super(identifier, system, activationPolicy, configurationPolicy, domain, value);\n }\n\n @Override\n public FunctionalityType getType() {\n return FunctionalityType.STRING;\n }\n\n @Override\n public boolean businessEquals(AbstractFunctionality obj, boolean checkPolicies) {", "post_mask_code": "\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is not equal to StringValueFunctionality \" + obj.toString());\n return false;\n }\n\n @Override\n public void updateFunctionalityFrom(AbstractFunctionality functionality) {\n super.updateFunctionalityFrom(functionality);\n this.updateFunctionalityValuesOnlyFrom(functionality);\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFrom(AbstractFunctionality functionality) {\n StringValueFunctionality f = (StringValueFunctionality) functionality;\n this.value = f.getValue();\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFromDto(Integer version, FunctionalityAdminDto functionality) {\n List parameters = functionality.getParameters();\n if (parameters != null && !parameters.isEmpty()) {\n ParameterDto parameterDto = parameters.get(0);\n this.value = parameterDto.getString();\n }\n }\n\n @Override\n public List getParameters(Integer version) {\n List res = new ArrayList();\n res.add(new ParameterDto(this.getValue()));\n return res;\n }\n\n @Override\n protected FunctionalityDto getUserDto(boolean enable, Integer version) {\n FunctionalityStringDto f = new FunctionalityStringDto();\n if (enable) {\n f.setValue(value);\n }\n return f;\n }\n\n @Override\n public org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.ParameterDto getParameter() {\n // there is no default value for functionality parameters. sad.\n String parentValue = this.value;\n if (this.ancestorFunc != null) {\n parentValue = ((StringValueFunctionality) this.ancestorFunc).getValue();\n }\n NestedStringParameterDto defaut = new NestedStringParameterDto(this.value, parentValue);\n return new StringParameterDto(this.system, !this.getParentAllowParametersUpdate(), defaut);\n }\n}\n"} {"task_id": "Java_19", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/linagora/linshare-core/src/main/java/org/linagora/linshare/core/domain/entities/StringValueFunctionality.java", "mask_start_position": 2529, "mask_end_position": 2655, "canonical_solution": "logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is not equal to StringValueFunctionality \" + obj.toString());", "pre_mask_code": "/*\n * LinShare is an open source filesharing software developed by LINAGORA.\n * \n * \n * notably (i) retain the display in the interface of the “LinShare™”\n * trademark/logo, the \"Libre & Free\" mention, the words “You are using the Free\n * Contribute to Linshare R&D by subscribing to an Enterprise offer!”. You must\n * also retain the latter notice in all asynchronous messages such as e-mails\n * sent with the Program, (ii) retain all hypertext links between LinShare and\n * http://www.linshare.org, between linagora.com and Linagora, and (iii) refrain\n * from infringing Linagora intellectual property rights over its trademarks and\n * commercial brands. Other Additional Terms apply, see\n * version 3 and\n * for the\n * Additional Terms applicable to LinShare software.\n */\npackage org.linagora.linshare.core.domain.entities;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.linagora.linshare.core.domain.constants.FunctionalityType;\nimport org.linagora.linshare.core.facade.webservice.admin.dto.FunctionalityAdminDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.StringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.nested.NestedStringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.common.dto.ParameterDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityStringDto;\n\npublic class StringValueFunctionality extends OneValueFunctionality {\n\n public StringValueFunctionality() {\n super();\n }\n\n public StringValueFunctionality(String identifier, boolean system, Policy activationPolicy, Policy configurationPolicy, AbstractDomain domain, String value) {\n super(identifier, system, activationPolicy, configurationPolicy, domain, value);\n }\n\n @Override\n public FunctionalityType getType() {\n return FunctionalityType.STRING;\n }\n\n @Override\n public boolean businessEquals(AbstractFunctionality obj, boolean checkPolicies) {\n if (super.businessEquals(obj, checkPolicies)) {\n StringValueFunctionality o = (StringValueFunctionality) obj;\n if (value.equals(o.getValue())) {\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is equal to StringValueFunctionality \" + obj.toString());\n return true;\n }\n }\n ", "post_mask_code": "\n return false;\n }\n\n @Override\n public void updateFunctionalityFrom(AbstractFunctionality functionality) {\n super.updateFunctionalityFrom(functionality);\n this.updateFunctionalityValuesOnlyFrom(functionality);\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFrom(AbstractFunctionality functionality) {\n StringValueFunctionality f = (StringValueFunctionality) functionality;\n this.value = f.getValue();\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFromDto(Integer version, FunctionalityAdminDto functionality) {\n List parameters = functionality.getParameters();\n if (parameters != null && !parameters.isEmpty()) {\n ParameterDto parameterDto = parameters.get(0);\n this.value = parameterDto.getString();\n }\n }\n\n @Override\n public List getParameters(Integer version) {\n List res = new ArrayList();\n res.add(new ParameterDto(this.getValue()));\n return res;\n }\n\n @Override\n protected FunctionalityDto getUserDto(boolean enable, Integer version) {\n FunctionalityStringDto f = new FunctionalityStringDto();\n if (enable) {\n f.setValue(value);\n }\n return f;\n }\n\n @Override\n public org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.ParameterDto getParameter() {\n // there is no default value for functionality parameters. sad.\n String parentValue = this.value;\n if (this.ancestorFunc != null) {\n parentValue = ((StringValueFunctionality) this.ancestorFunc).getValue();\n }\n NestedStringParameterDto defaut = new NestedStringParameterDto(this.value, parentValue);\n return new StringParameterDto(this.system, !this.getParentAllowParametersUpdate(), defaut);\n }\n}\n"} {"task_id": "Java_20", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/linagora/linshare-core/src/main/java/org/linagora/linshare/core/domain/entities/StringValueFunctionality.java", "mask_start_position": 2664, "mask_end_position": 2683, "canonical_solution": "return false;\n }", "pre_mask_code": "/*\n * LinShare is an open source filesharing software developed by LINAGORA.\n * \n * \n * notably (i) retain the display in the interface of the “LinShare™”\n * trademark/logo, the \"Libre & Free\" mention, the words “You are using the Free\n * Contribute to Linshare R&D by subscribing to an Enterprise offer!”. You must\n * also retain the latter notice in all asynchronous messages such as e-mails\n * sent with the Program, (ii) retain all hypertext links between LinShare and\n * http://www.linshare.org, between linagora.com and Linagora, and (iii) refrain\n * from infringing Linagora intellectual property rights over its trademarks and\n * commercial brands. Other Additional Terms apply, see\n * version 3 and\n * for the\n * Additional Terms applicable to LinShare software.\n */\npackage org.linagora.linshare.core.domain.entities;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.linagora.linshare.core.domain.constants.FunctionalityType;\nimport org.linagora.linshare.core.facade.webservice.admin.dto.FunctionalityAdminDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.StringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.nested.NestedStringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.common.dto.ParameterDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityStringDto;\n\npublic class StringValueFunctionality extends OneValueFunctionality {\n\n public StringValueFunctionality() {\n super();\n }\n\n public StringValueFunctionality(String identifier, boolean system, Policy activationPolicy, Policy configurationPolicy, AbstractDomain domain, String value) {\n super(identifier, system, activationPolicy, configurationPolicy, domain, value);\n }\n\n @Override\n public FunctionalityType getType() {\n return FunctionalityType.STRING;\n }\n\n @Override\n public boolean businessEquals(AbstractFunctionality obj, boolean checkPolicies) {\n if (super.businessEquals(obj, checkPolicies)) {\n StringValueFunctionality o = (StringValueFunctionality) obj;\n if (value.equals(o.getValue())) {\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is equal to StringValueFunctionality \" + obj.toString());\n return true;\n }\n }\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is not equal to StringValueFunctionality \" + obj.toString());\n ", "post_mask_code": "\n\n @Override\n public void updateFunctionalityFrom(AbstractFunctionality functionality) {\n super.updateFunctionalityFrom(functionality);\n this.updateFunctionalityValuesOnlyFrom(functionality);\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFrom(AbstractFunctionality functionality) {\n StringValueFunctionality f = (StringValueFunctionality) functionality;\n this.value = f.getValue();\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFromDto(Integer version, FunctionalityAdminDto functionality) {\n List parameters = functionality.getParameters();\n if (parameters != null && !parameters.isEmpty()) {\n ParameterDto parameterDto = parameters.get(0);\n this.value = parameterDto.getString();\n }\n }\n\n @Override\n public List getParameters(Integer version) {\n List res = new ArrayList();\n res.add(new ParameterDto(this.getValue()));\n return res;\n }\n\n @Override\n protected FunctionalityDto getUserDto(boolean enable, Integer version) {\n FunctionalityStringDto f = new FunctionalityStringDto();\n if (enable) {\n f.setValue(value);\n }\n return f;\n }\n\n @Override\n public org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.ParameterDto getParameter() {\n // there is no default value for functionality parameters. sad.\n String parentValue = this.value;\n if (this.ancestorFunc != null) {\n parentValue = ((StringValueFunctionality) this.ancestorFunc).getValue();\n }\n NestedStringParameterDto defaut = new NestedStringParameterDto(this.value, parentValue);\n return new StringParameterDto(this.system, !this.getParentAllowParametersUpdate(), defaut);\n }\n}\n"} {"task_id": "Java_21", "language": "Java", "task_type": "single_line", "source_file": "java/github/linagora/linshare-core/src/main/java/org/linagora/linshare/core/domain/entities/StringValueFunctionality.java", "mask_start_position": 3620, "mask_end_position": 3646, "canonical_solution": "ArrayList();", "pre_mask_code": "/*\n * LinShare is an open source filesharing software developed by LINAGORA.\n * \n * \n * notably (i) retain the display in the interface of the “LinShare™”\n * trademark/logo, the \"Libre & Free\" mention, the words “You are using the Free\n * Contribute to Linshare R&D by subscribing to an Enterprise offer!”. You must\n * also retain the latter notice in all asynchronous messages such as e-mails\n * sent with the Program, (ii) retain all hypertext links between LinShare and\n * http://www.linshare.org, between linagora.com and Linagora, and (iii) refrain\n * from infringing Linagora intellectual property rights over its trademarks and\n * commercial brands. Other Additional Terms apply, see\n * version 3 and\n * for the\n * Additional Terms applicable to LinShare software.\n */\npackage org.linagora.linshare.core.domain.entities;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.linagora.linshare.core.domain.constants.FunctionalityType;\nimport org.linagora.linshare.core.facade.webservice.admin.dto.FunctionalityAdminDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.StringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.nested.NestedStringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.common.dto.ParameterDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityStringDto;\n\npublic class StringValueFunctionality extends OneValueFunctionality {\n\n public StringValueFunctionality() {\n super();\n }\n\n public StringValueFunctionality(String identifier, boolean system, Policy activationPolicy, Policy configurationPolicy, AbstractDomain domain, String value) {\n super(identifier, system, activationPolicy, configurationPolicy, domain, value);\n }\n\n @Override\n public FunctionalityType getType() {\n return FunctionalityType.STRING;\n }\n\n @Override\n public boolean businessEquals(AbstractFunctionality obj, boolean checkPolicies) {\n if (super.businessEquals(obj, checkPolicies)) {\n StringValueFunctionality o = (StringValueFunctionality) obj;\n if (value.equals(o.getValue())) {\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is equal to StringValueFunctionality \" + obj.toString());\n return true;\n }\n }\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is not equal to StringValueFunctionality \" + obj.toString());\n return false;\n }\n\n @Override\n public void updateFunctionalityFrom(AbstractFunctionality functionality) {\n super.updateFunctionalityFrom(functionality);\n this.updateFunctionalityValuesOnlyFrom(functionality);\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFrom(AbstractFunctionality functionality) {\n StringValueFunctionality f = (StringValueFunctionality) functionality;\n this.value = f.getValue();\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFromDto(Integer version, FunctionalityAdminDto functionality) {\n List parameters = functionality.getParameters();\n if (parameters != null && !parameters.isEmpty()) {\n ParameterDto parameterDto = parameters.get(0);\n this.value = parameterDto.getString();\n }\n }\n\n @Override\n public List getParameters(Integer version) {\n List res = new ", "post_mask_code": "\n res.add(new ParameterDto(this.getValue()));\n return res;\n }\n\n @Override\n protected FunctionalityDto getUserDto(boolean enable, Integer version) {\n FunctionalityStringDto f = new FunctionalityStringDto();\n if (enable) {\n f.setValue(value);\n }\n return f;\n }\n\n @Override\n public org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.ParameterDto getParameter() {\n // there is no default value for functionality parameters. sad.\n String parentValue = this.value;\n if (this.ancestorFunc != null) {\n parentValue = ((StringValueFunctionality) this.ancestorFunc).getValue();\n }\n NestedStringParameterDto defaut = new NestedStringParameterDto(this.value, parentValue);\n return new StringParameterDto(this.system, !this.getParentAllowParametersUpdate(), defaut);\n }\n}\n"} {"task_id": "Java_22", "language": "Java", "task_type": "if_statement", "source_file": "java/github/linagora/linshare-core/src/main/java/org/linagora/linshare/core/domain/entities/StringValueFunctionality.java", "mask_start_position": 2162, "mask_end_position": 2520, "canonical_solution": "if (super.businessEquals(obj, checkPolicies)) {\n StringValueFunctionality o = (StringValueFunctionality) obj;\n if (value.equals(o.getValue())) {\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is equal to StringValueFunctionality \" + obj.toString());\n return true;\n }\n }", "pre_mask_code": "/*\n * LinShare is an open source filesharing software developed by LINAGORA.\n * \n * \n * notably (i) retain the display in the interface of the “LinShare™”\n * trademark/logo, the \"Libre & Free\" mention, the words “You are using the Free\n * Contribute to Linshare R&D by subscribing to an Enterprise offer!”. You must\n * also retain the latter notice in all asynchronous messages such as e-mails\n * sent with the Program, (ii) retain all hypertext links between LinShare and\n * http://www.linshare.org, between linagora.com and Linagora, and (iii) refrain\n * from infringing Linagora intellectual property rights over its trademarks and\n * commercial brands. Other Additional Terms apply, see\n * version 3 and\n * for the\n * Additional Terms applicable to LinShare software.\n */\npackage org.linagora.linshare.core.domain.entities;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.linagora.linshare.core.domain.constants.FunctionalityType;\nimport org.linagora.linshare.core.facade.webservice.admin.dto.FunctionalityAdminDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.StringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.nested.NestedStringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.common.dto.ParameterDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityStringDto;\n\npublic class StringValueFunctionality extends OneValueFunctionality {\n\n public StringValueFunctionality() {\n super();\n }\n\n public StringValueFunctionality(String identifier, boolean system, Policy activationPolicy, Policy configurationPolicy, AbstractDomain domain, String value) {\n super(identifier, system, activationPolicy, configurationPolicy, domain, value);\n }\n\n @Override\n public FunctionalityType getType() {\n return FunctionalityType.STRING;\n }\n\n @Override\n public boolean businessEquals(AbstractFunctionality obj, boolean checkPolicies) {\n ", "post_mask_code": "\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is not equal to StringValueFunctionality \" + obj.toString());\n return false;\n }\n\n @Override\n public void updateFunctionalityFrom(AbstractFunctionality functionality) {\n super.updateFunctionalityFrom(functionality);\n this.updateFunctionalityValuesOnlyFrom(functionality);\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFrom(AbstractFunctionality functionality) {\n StringValueFunctionality f = (StringValueFunctionality) functionality;\n this.value = f.getValue();\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFromDto(Integer version, FunctionalityAdminDto functionality) {\n List parameters = functionality.getParameters();\n if (parameters != null && !parameters.isEmpty()) {\n ParameterDto parameterDto = parameters.get(0);\n this.value = parameterDto.getString();\n }\n }\n\n @Override\n public List getParameters(Integer version) {\n List res = new ArrayList();\n res.add(new ParameterDto(this.getValue()));\n return res;\n }\n\n @Override\n protected FunctionalityDto getUserDto(boolean enable, Integer version) {\n FunctionalityStringDto f = new FunctionalityStringDto();\n if (enable) {\n f.setValue(value);\n }\n return f;\n }\n\n @Override\n public org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.ParameterDto getParameter() {\n // there is no default value for functionality parameters. sad.\n String parentValue = this.value;\n if (this.ancestorFunc != null) {\n parentValue = ((StringValueFunctionality) this.ancestorFunc).getValue();\n }\n NestedStringParameterDto defaut = new NestedStringParameterDto(this.value, parentValue);\n return new StringParameterDto(this.system, !this.getParentAllowParametersUpdate(), defaut);\n }\n}\n"} {"task_id": "Java_23", "language": "Java", "task_type": "empty", "source_file": "java/github/linagora/linshare-core/src/main/java/org/linagora/linshare/core/domain/entities/StringValueFunctionality.java", "mask_start_position": 1243, "mask_end_position": 1243, "canonical_solution": "", "pre_mask_code": "/*\n * LinShare is an open source filesharing software developed by LINAGORA.\n * \n * \n * notably (i) retain the display in the interface of the “LinShare™”\n * trademark/logo, the \"Libre & Free\" mention, the words “You are using the Free\n * Contribute to Linshare R&D by subscribing to an Enterprise offer!”. You must\n * also retain the latter notice in all asynchronous messages such as e-mails\n * sent with the Program, (ii) retain all hypertext links between LinShare and\n * http://www.linshare.org, between linagora.com and Linagora, and (iii) refrain\n * from infringing Linagora intellectual property rights over its trademarks and\n * commercial brands. Other Additional Terms apply, see\n * version 3 and\n * for the\n * Additional Terms applicable to LinShare software.\n */\npackage org.linagora.linshare.core.domain.entities;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.linagora.linshare.core.domain.constants.FunctionalityType;\nimport org.linagora.linshare.core.facade.webservice.admin.dto.FunctionalityAdminDto;\nimport org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.StringParameterDto;\nimport org.linagora.linshare.core.facade.web", "post_mask_code": "service.adminv5.dto.parameters.nested.NestedStringParameterDto;\nimport org.linagora.linshare.core.facade.webservice.common.dto.ParameterDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityDto;\nimport org.linagora.linshare.core.facade.webservice.user.dto.FunctionalityStringDto;\n\npublic class StringValueFunctionality extends OneValueFunctionality {\n\n public StringValueFunctionality() {\n super();\n }\n\n public StringValueFunctionality(String identifier, boolean system, Policy activationPolicy, Policy configurationPolicy, AbstractDomain domain, String value) {\n super(identifier, system, activationPolicy, configurationPolicy, domain, value);\n }\n\n @Override\n public FunctionalityType getType() {\n return FunctionalityType.STRING;\n }\n\n @Override\n public boolean businessEquals(AbstractFunctionality obj, boolean checkPolicies) {\n if (super.businessEquals(obj, checkPolicies)) {\n StringValueFunctionality o = (StringValueFunctionality) obj;\n if (value.equals(o.getValue())) {\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is equal to StringValueFunctionality \" + obj.toString());\n return true;\n }\n }\n logger.debug(\"StringValueFunctionality : \" + this.toString() + \" is not equal to StringValueFunctionality \" + obj.toString());\n return false;\n }\n\n @Override\n public void updateFunctionalityFrom(AbstractFunctionality functionality) {\n super.updateFunctionalityFrom(functionality);\n this.updateFunctionalityValuesOnlyFrom(functionality);\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFrom(AbstractFunctionality functionality) {\n StringValueFunctionality f = (StringValueFunctionality) functionality;\n this.value = f.getValue();\n }\n\n @Override\n public void updateFunctionalityValuesOnlyFromDto(Integer version, FunctionalityAdminDto functionality) {\n List parameters = functionality.getParameters();\n if (parameters != null && !parameters.isEmpty()) {\n ParameterDto parameterDto = parameters.get(0);\n this.value = parameterDto.getString();\n }\n }\n\n @Override\n public List getParameters(Integer version) {\n List res = new ArrayList();\n res.add(new ParameterDto(this.getValue()));\n return res;\n }\n\n @Override\n protected FunctionalityDto getUserDto(boolean enable, Integer version) {\n FunctionalityStringDto f = new FunctionalityStringDto();\n if (enable) {\n f.setValue(value);\n }\n return f;\n }\n\n @Override\n public org.linagora.linshare.core.facade.webservice.adminv5.dto.parameters.ParameterDto getParameter() {\n // there is no default value for functionality parameters. sad.\n String parentValue = this.value;\n if (this.ancestorFunc != null) {\n parentValue = ((StringValueFunctionality) this.ancestorFunc).getValue();\n }\n NestedStringParameterDto defaut = new NestedStringParameterDto(this.value, parentValue);\n return new StringParameterDto(this.system, !this.getParentAllowParametersUpdate(), defaut);\n }\n}\n"} {"task_id": "Java_24", "language": "Java", "task_type": "method_signature", "source_file": "java/github/AppleCommander/AppleCommander/src/main/java/com/webcodepro/applecommander/ui/swt/filteradapter/TextFilterAdapter.java", "mask_start_position": 891, "mask_end_position": 928, "canonical_solution": "protected String createTextContent() ", "pre_mask_code": "package com.webcodepro.applecommander.ui.swt.filteradapter;\n\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.custom.StyledText;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.graphics.Point;\nimport com.webcodepro.applecommander.ui.swt.FileViewerWindow;\nimport com.webcodepro.applecommander.ui.swt.util.contentadapter.StyledTextAdapter;\n\n/**\n * Provides a view of a simple text file.\n *\n * @author Rob Greene\n */\npublic class TextFilterAdapter extends FilterAdapter {\n\n private String textContent;\n\n public TextFilterAdapter(FileViewerWindow window, String text, String toolTipText, Image image) {\n super(window, text, toolTipText, image);\n }\n\n public void display() {\n if (textContent == null) {\n textContent = createTextContent();\n }\n getCopyToolItem().setEnabled(true);\n createTextWidget(textContent);\n }\n\n ", "post_mask_code": "{\n return new String(getFileFilter().filter(getFileEntry()));\n }\n\n protected void createTextWidget(String textContents) {\n StyledText styledText = new StyledText(getComposite(), SWT.NONE);\n styledText.setText(textContents);\n styledText.setFont(getCourierFont());\n styledText.setEditable(false);\n Point size = styledText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);\n getComposite().setContent(styledText);\n getComposite().setExpandHorizontal(true);\n getComposite().setExpandVertical(true);\n getComposite().setMinWidth(size.x);\n getComposite().setMinHeight(size.y);\n getComposite().getContent().addListener(SWT.KeyUp, getToolbarCommandHandler());\n getToolItem().setSelection(true);\n setContentTypeAdapter(new StyledTextAdapter(styledText, getFileEntry().getFilename()));\n }\n}\n"} {"task_id": "Java_25", "language": "Java", "task_type": "method_body", "source_file": "java/github/AppleCommander/AppleCommander/src/main/java/com/webcodepro/applecommander/ui/swt/filteradapter/TextFilterAdapter.java", "mask_start_position": 928, "mask_end_position": 1002, "canonical_solution": "{\n return new String(getFileFilter().filter(getFileEntry()));\n }", "pre_mask_code": "package com.webcodepro.applecommander.ui.swt.filteradapter;\n\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.custom.StyledText;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.graphics.Point;\nimport com.webcodepro.applecommander.ui.swt.FileViewerWindow;\nimport com.webcodepro.applecommander.ui.swt.util.contentadapter.StyledTextAdapter;\n\n/**\n * Provides a view of a simple text file.\n *\n * @author Rob Greene\n */\npublic class TextFilterAdapter extends FilterAdapter {\n\n private String textContent;\n\n public TextFilterAdapter(FileViewerWindow window, String text, String toolTipText, Image image) {\n super(window, text, toolTipText, image);\n }\n\n public void display() {\n if (textContent == null) {\n textContent = createTextContent();\n }\n getCopyToolItem().setEnabled(true);\n createTextWidget(textContent);\n }\n\n protected String createTextContent() ", "post_mask_code": "\n\n protected void createTextWidget(String textContents) {\n StyledText styledText = new StyledText(getComposite(), SWT.NONE);\n styledText.setText(textContents);\n styledText.setFont(getCourierFont());\n styledText.setEditable(false);\n Point size = styledText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);\n getComposite().setContent(styledText);\n getComposite().setExpandHorizontal(true);\n getComposite().setExpandVertical(true);\n getComposite().setMinWidth(size.x);\n getComposite().setMinHeight(size.y);\n getComposite().getContent().addListener(SWT.KeyUp, getToolbarCommandHandler());\n getToolItem().setSelection(true);\n setContentTypeAdapter(new StyledTextAdapter(styledText, getFileEntry().getFilename()));\n }\n}\n"} {"task_id": "Java_26", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/AppleCommander/AppleCommander/src/main/java/com/webcodepro/applecommander/ui/swt/filteradapter/TextFilterAdapter.java", "mask_start_position": 1062, "mask_end_position": 1263, "canonical_solution": "\n StyledText styledText = new StyledText(getComposite(), SWT.NONE);\n styledText.setText(textContents);\n styledText.setFont(getCourierFont());\n styledText.setEditable(false);", "pre_mask_code": "package com.webcodepro.applecommander.ui.swt.filteradapter;\n\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.custom.StyledText;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.graphics.Point;\nimport com.webcodepro.applecommander.ui.swt.FileViewerWindow;\nimport com.webcodepro.applecommander.ui.swt.util.contentadapter.StyledTextAdapter;\n\n/**\n * Provides a view of a simple text file.\n *\n * @author Rob Greene\n */\npublic class TextFilterAdapter extends FilterAdapter {\n\n private String textContent;\n\n public TextFilterAdapter(FileViewerWindow window, String text, String toolTipText, Image image) {\n super(window, text, toolTipText, image);\n }\n\n public void display() {\n if (textContent == null) {\n textContent = createTextContent();\n }\n getCopyToolItem().setEnabled(true);\n createTextWidget(textContent);\n }\n\n protected String createTextContent() {\n return new String(getFileFilter().filter(getFileEntry()));\n }\n\n protected void createTextWidget(String textContents) {", "post_mask_code": "\n Point size = styledText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);\n getComposite().setContent(styledText);\n getComposite().setExpandHorizontal(true);\n getComposite().setExpandVertical(true);\n getComposite().setMinWidth(size.x);\n getComposite().setMinHeight(size.y);\n getComposite().getContent().addListener(SWT.KeyUp, getToolbarCommandHandler());\n getToolItem().setSelection(true);\n setContentTypeAdapter(new StyledTextAdapter(styledText, getFileEntry().getFilename()));\n }\n}\n"} {"task_id": "Java_27", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/AppleCommander/AppleCommander/src/main/java/com/webcodepro/applecommander/ui/swt/filteradapter/TextFilterAdapter.java", "mask_start_position": 1272, "mask_end_position": 1529, "canonical_solution": "Point size = styledText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);\n getComposite().setContent(styledText);\n getComposite().setExpandHorizontal(true);\n getComposite().setExpandVertical(true);\n getComposite().setMinWidth(size.x);", "pre_mask_code": "package com.webcodepro.applecommander.ui.swt.filteradapter;\n\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.custom.StyledText;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.graphics.Point;\nimport com.webcodepro.applecommander.ui.swt.FileViewerWindow;\nimport com.webcodepro.applecommander.ui.swt.util.contentadapter.StyledTextAdapter;\n\n/**\n * Provides a view of a simple text file.\n *\n * @author Rob Greene\n */\npublic class TextFilterAdapter extends FilterAdapter {\n\n private String textContent;\n\n public TextFilterAdapter(FileViewerWindow window, String text, String toolTipText, Image image) {\n super(window, text, toolTipText, image);\n }\n\n public void display() {\n if (textContent == null) {\n textContent = createTextContent();\n }\n getCopyToolItem().setEnabled(true);\n createTextWidget(textContent);\n }\n\n protected String createTextContent() {\n return new String(getFileFilter().filter(getFileEntry()));\n }\n\n protected void createTextWidget(String textContents) {\n StyledText styledText = new StyledText(getComposite(), SWT.NONE);\n styledText.setText(textContents);\n styledText.setFont(getCourierFont());\n styledText.setEditable(false);\n ", "post_mask_code": "\n getComposite().setMinHeight(size.y);\n getComposite().getContent().addListener(SWT.KeyUp, getToolbarCommandHandler());\n getToolItem().setSelection(true);\n setContentTypeAdapter(new StyledTextAdapter(styledText, getFileEntry().getFilename()));\n }\n}\n"} {"task_id": "Java_28", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/AppleCommander/AppleCommander/src/main/java/com/webcodepro/applecommander/ui/swt/filteradapter/TextFilterAdapter.java", "mask_start_position": 1538, "mask_end_position": 1806, "canonical_solution": "getComposite().setMinHeight(size.y);\n getComposite().getContent().addListener(SWT.KeyUp, getToolbarCommandHandler());\n getToolItem().setSelection(true);\n setContentTypeAdapter(new StyledTextAdapter(styledText, getFileEntry().getFilename()));\n }", "pre_mask_code": "package com.webcodepro.applecommander.ui.swt.filteradapter;\n\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.custom.StyledText;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.graphics.Point;\nimport com.webcodepro.applecommander.ui.swt.FileViewerWindow;\nimport com.webcodepro.applecommander.ui.swt.util.contentadapter.StyledTextAdapter;\n\n/**\n * Provides a view of a simple text file.\n *\n * @author Rob Greene\n */\npublic class TextFilterAdapter extends FilterAdapter {\n\n private String textContent;\n\n public TextFilterAdapter(FileViewerWindow window, String text, String toolTipText, Image image) {\n super(window, text, toolTipText, image);\n }\n\n public void display() {\n if (textContent == null) {\n textContent = createTextContent();\n }\n getCopyToolItem().setEnabled(true);\n createTextWidget(textContent);\n }\n\n protected String createTextContent() {\n return new String(getFileFilter().filter(getFileEntry()));\n }\n\n protected void createTextWidget(String textContents) {\n StyledText styledText = new StyledText(getComposite(), SWT.NONE);\n styledText.setText(textContents);\n styledText.setFont(getCourierFont());\n styledText.setEditable(false);\n Point size = styledText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);\n getComposite().setContent(styledText);\n getComposite().setExpandHorizontal(true);\n getComposite().setExpandVertical(true);\n getComposite().setMinWidth(size.x);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_29", "language": "Java", "task_type": "single_line", "source_file": "java/github/AppleCommander/AppleCommander/src/main/java/com/webcodepro/applecommander/ui/swt/filteradapter/TextFilterAdapter.java", "mask_start_position": 815, "mask_end_position": 840, "canonical_solution": "lItem().setEnabled(true);", "pre_mask_code": "package com.webcodepro.applecommander.ui.swt.filteradapter;\n\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.custom.StyledText;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.graphics.Point;\nimport com.webcodepro.applecommander.ui.swt.FileViewerWindow;\nimport com.webcodepro.applecommander.ui.swt.util.contentadapter.StyledTextAdapter;\n\n/**\n * Provides a view of a simple text file.\n *\n * @author Rob Greene\n */\npublic class TextFilterAdapter extends FilterAdapter {\n\n private String textContent;\n\n public TextFilterAdapter(FileViewerWindow window, String text, String toolTipText, Image image) {\n super(window, text, toolTipText, image);\n }\n\n public void display() {\n if (textContent == null) {\n textContent = createTextContent();\n }\n getCopyToo", "post_mask_code": "\n createTextWidget(textContent);\n }\n\n protected String createTextContent() {\n return new String(getFileFilter().filter(getFileEntry()));\n }\n\n protected void createTextWidget(String textContents) {\n StyledText styledText = new StyledText(getComposite(), SWT.NONE);\n styledText.setText(textContents);\n styledText.setFont(getCourierFont());\n styledText.setEditable(false);\n Point size = styledText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);\n getComposite().setContent(styledText);\n getComposite().setExpandHorizontal(true);\n getComposite().setExpandVertical(true);\n getComposite().setMinWidth(size.x);\n getComposite().setMinHeight(size.y);\n getComposite().getContent().addListener(SWT.KeyUp, getToolbarCommandHandler());\n getToolItem().setSelection(true);\n setContentTypeAdapter(new StyledTextAdapter(styledText, getFileEntry().getFilename()));\n }\n}\n"} {"task_id": "Java_30", "language": "Java", "task_type": "if_statement", "source_file": "java/github/AppleCommander/AppleCommander/src/main/java/com/webcodepro/applecommander/ui/swt/filteradapter/TextFilterAdapter.java", "mask_start_position": 713, "mask_end_position": 796, "canonical_solution": "if (textContent == null) {\n textContent = createTextContent();\n }", "pre_mask_code": "package com.webcodepro.applecommander.ui.swt.filteradapter;\n\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.custom.StyledText;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.graphics.Point;\nimport com.webcodepro.applecommander.ui.swt.FileViewerWindow;\nimport com.webcodepro.applecommander.ui.swt.util.contentadapter.StyledTextAdapter;\n\n/**\n * Provides a view of a simple text file.\n *\n * @author Rob Greene\n */\npublic class TextFilterAdapter extends FilterAdapter {\n\n private String textContent;\n\n public TextFilterAdapter(FileViewerWindow window, String text, String toolTipText, Image image) {\n super(window, text, toolTipText, image);\n }\n\n public void display() {\n ", "post_mask_code": "\n getCopyToolItem().setEnabled(true);\n createTextWidget(textContent);\n }\n\n protected String createTextContent() {\n return new String(getFileFilter().filter(getFileEntry()));\n }\n\n protected void createTextWidget(String textContents) {\n StyledText styledText = new StyledText(getComposite(), SWT.NONE);\n styledText.setText(textContents);\n styledText.setFont(getCourierFont());\n styledText.setEditable(false);\n Point size = styledText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);\n getComposite().setContent(styledText);\n getComposite().setExpandHorizontal(true);\n getComposite().setExpandVertical(true);\n getComposite().setMinWidth(size.x);\n getComposite().setMinHeight(size.y);\n getComposite().getContent().addListener(SWT.KeyUp, getToolbarCommandHandler());\n getToolItem().setSelection(true);\n setContentTypeAdapter(new StyledTextAdapter(styledText, getFileEntry().getFilename()));\n }\n}\n"} {"task_id": "Java_31", "language": "Java", "task_type": "empty", "source_file": "java/github/AppleCommander/AppleCommander/src/main/java/com/webcodepro/applecommander/ui/swt/filteradapter/TextFilterAdapter.java", "mask_start_position": 1427, "mask_end_position": 1427, "canonical_solution": "", "pre_mask_code": "package com.webcodepro.applecommander.ui.swt.filteradapter;\n\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.custom.StyledText;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.graphics.Point;\nimport com.webcodepro.applecommander.ui.swt.FileViewerWindow;\nimport com.webcodepro.applecommander.ui.swt.util.contentadapter.StyledTextAdapter;\n\n/**\n * Provides a view of a simple text file.\n *\n * @author Rob Greene\n */\npublic class TextFilterAdapter extends FilterAdapter {\n\n private String textContent;\n\n public TextFilterAdapter(FileViewerWindow window, String text, String toolTipText, Image image) {\n super(window, text, toolTipText, image);\n }\n\n public void display() {\n if (textContent == null) {\n textContent = createTextContent();\n }\n getCopyToolItem().setEnabled(true);\n createTextWidget(textContent);\n }\n\n protected String createTextContent() {\n return new String(getFileFilter().filter(getFileEntry()));\n }\n\n protected void createTextWidget(String textContents) {\n StyledText styledText = new StyledText(getComposite(), SWT.NONE);\n styledText.setText(textContents);\n styledText.setFont(getCourierFont());\n styledText.setEditable(false);\n Point size = styledText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);\n getComposite().setContent(styledText);\n getComposite().setExpandHorizon", "post_mask_code": "tal(true);\n getComposite().setExpandVertical(true);\n getComposite().setMinWidth(size.x);\n getComposite().setMinHeight(size.y);\n getComposite().getContent().addListener(SWT.KeyUp, getToolbarCommandHandler());\n getToolItem().setSelection(true);\n setContentTypeAdapter(new StyledTextAdapter(styledText, getFileEntry().getFilename()));\n }\n}\n"} {"task_id": "Java_32", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openhab/openhab-addons/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/pchkdiscovery/ExtService.java", "mask_start_position": 712, "mask_end_position": 738, "canonical_solution": "public int getLocalPort() ", "pre_mask_code": "package org.openhab.binding.lcn.internal.pchkdiscovery;\n\nimport org.eclipse.jdt.annotation.NonNullByDefault;\nimport com.thoughtworks.xstream.annotations.XStreamConverter;\nimport com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;\n\n/**\n * Used for deserializing the XML response of the LCN-PCHK discovery protocol.\n *\n * @author Fabian Wolter - Initial contribution\n */\n@NonNullByDefault\n@XStreamConverter(value = ToAttributedValueConverter.class, strings = { \"content\" })\npublic class ExtService {\n\n private final int localPort;\n\n @SuppressWarnings(\"unused\")\n private final String content = \"\";\n\n public ExtService(int localPort) {\n this.localPort = localPort;\n }\n\n ", "post_mask_code": "{\n return localPort;\n }\n}\n"} {"task_id": "Java_33", "language": "Java", "task_type": "method_body", "source_file": "java/github/openhab/openhab-addons/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/pchkdiscovery/ExtService.java", "mask_start_position": 738, "mask_end_position": 771, "canonical_solution": "{\n return localPort;\n }", "pre_mask_code": "package org.openhab.binding.lcn.internal.pchkdiscovery;\n\nimport org.eclipse.jdt.annotation.NonNullByDefault;\nimport com.thoughtworks.xstream.annotations.XStreamConverter;\nimport com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;\n\n/**\n * Used for deserializing the XML response of the LCN-PCHK discovery protocol.\n *\n * @author Fabian Wolter - Initial contribution\n */\n@NonNullByDefault\n@XStreamConverter(value = ToAttributedValueConverter.class, strings = { \"content\" })\npublic class ExtService {\n\n private final int localPort;\n\n @SuppressWarnings(\"unused\")\n private final String content = \"\";\n\n public ExtService(int localPort) {\n this.localPort = localPort;\n }\n\n public int getLocalPort() ", "post_mask_code": "\n}\n"} {"task_id": "Java_34", "language": "Java", "task_type": "single_line", "source_file": "java/github/openhab/openhab-addons/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/pchkdiscovery/ExtService.java", "mask_start_position": 755, "mask_end_position": 765, "canonical_solution": "localPort;", "pre_mask_code": "package org.openhab.binding.lcn.internal.pchkdiscovery;\n\nimport org.eclipse.jdt.annotation.NonNullByDefault;\nimport com.thoughtworks.xstream.annotations.XStreamConverter;\nimport com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;\n\n/**\n * Used for deserializing the XML response of the LCN-PCHK discovery protocol.\n *\n * @author Fabian Wolter - Initial contribution\n */\n@NonNullByDefault\n@XStreamConverter(value = ToAttributedValueConverter.class, strings = { \"content\" })\npublic class ExtService {\n\n private final int localPort;\n\n @SuppressWarnings(\"unused\")\n private final String content = \"\";\n\n public ExtService(int localPort) {\n this.localPort = localPort;\n }\n\n public int getLocalPort() {\n return ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_35", "language": "Java", "task_type": "empty", "source_file": "java/github/openhab/openhab-addons/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/pchkdiscovery/ExtService.java", "mask_start_position": 449, "mask_end_position": 449, "canonical_solution": "", "pre_mask_code": "package org.openhab.binding.lcn.internal.pchkdiscovery;\n\nimport org.eclipse.jdt.annotation.NonNullByDefault;\nimport com.thoughtworks.xstream.annotations.XStreamConverter;\nimport com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;\n\n/**\n * Used for deserializing the XML response of the LCN-PCHK discovery protocol.\n *\n * @author Fabian Wolter - Initial contribution\n */\n@NonNullByDefault\n@XStreamConverter(value = ToAttributedVal", "post_mask_code": "ueConverter.class, strings = { \"content\" })\npublic class ExtService {\n\n private final int localPort;\n\n @SuppressWarnings(\"unused\")\n private final String content = \"\";\n\n public ExtService(int localPort) {\n this.localPort = localPort;\n }\n\n public int getLocalPort() {\n return localPort;\n }\n}\n"} {"task_id": "Java_36", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jreijn/spring-comparing-template-engines/src/main/java/com/jeroenreijn/examples/configuration/WebMvcConfig.java", "mask_start_position": 9593, "mask_end_position": 9644, "canonical_solution": "@Bean\n public ViewResolver rockerViewResolver() ", "pre_mask_code": "package com.jeroenreijn.examples.configuration;\n\nimport java.util.HashMap;\nimport java.util.Locale;\nimport java.util.Map;\nimport com.jeroenreijn.examples.view.*;\nimport org.fusesource.scalate.spring.view.ScalateViewResolver;\nimport org.rythmengine.spring.web.RythmConfigurer;\nimport org.rythmengine.spring.web.RythmViewResolver;\nimport org.springframework.beans.BeansException;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\nimport org.springframework.context.MessageSource;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Scope;\nimport org.springframework.context.support.ReloadableResourceBundleMessageSource;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.servlet.LocaleResolver;\nimport org.springframework.web.servlet.ViewResolver;\nimport org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;\nimport org.springframework.web.servlet.config.annotation.EnableWebMvc;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\nimport org.springframework.web.servlet.i18n.SessionLocaleResolver;\nimport org.springframework.web.servlet.view.InternalResourceViewResolver;\nimport org.springframework.web.servlet.view.JstlView;\nimport org.thymeleaf.spring5.SpringTemplateEngine;\nimport org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;\nimport org.thymeleaf.spring5.view.ThymeleafViewResolver;\nimport org.thymeleaf.templatemode.TemplateMode;\nimport com.github.enpassant.ickenham.springmvc.IckenhamViewResolver;\nimport com.github.jknack.handlebars.springmvc.HandlebarsViewResolver;\nimport com.jeroenreijn.examples.repository.InMemoryPresentationsRepository;\nimport com.jeroenreijn.examples.repository.PresentationsRepository;\nimport com.x5.template.spring.ChunkTemplateView;\nimport de.neuland.jade4j.JadeConfiguration;\nimport de.neuland.jade4j.spring.template.SpringTemplateLoader;\nimport de.neuland.jade4j.spring.view.JadeViewResolver;\nimport httl.web.springmvc.HttlViewResolver;\n\n@Configuration\n@EnableWebMvc\n@ComponentScan(basePackages = { \"com.jeroenreijn.examples.controller\", \"com.jeroenreijn.examples.factory\" })\npublic class WebMvcConfig implements ApplicationContextAware, WebMvcConfigurer {\n\n private ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n }\n\n @Override\n public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {\n configurer.enable();\n }\n\n @Override\n public void addResourceHandlers(ResourceHandlerRegistry registry) {\n registry.addResourceHandler(\"/robots.txt\").addResourceLocations(\"/robots.txt\");\n registry.addResourceHandler(\"/webjars/**\").addResourceLocations(\"/webjars/\");\n registry.addResourceHandler(\"/resources/**\").addResourceLocations(\"/resources/\");\n }\n\n @Bean\n public MessageSource messageSource() {\n ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();\n messageSource.setBasename(\"classpath:/messages\");\n messageSource.setDefaultEncoding(\"UTF-8\");\n return messageSource;\n }\n\n @Bean\n public LocaleResolver localeResolver() {\n SessionLocaleResolver slr = new SessionLocaleResolver();\n slr.setDefaultLocale(Locale.US);\n return slr;\n }\n\n @Bean\n public PresentationsRepository presentationsRepository() {\n PresentationsRepository inMemory = new InMemoryPresentationsRepository();\n return inMemory;\n }\n\n @Bean\n public SpringResourceTemplateResolver thymeleafTemplateResolver() {\n SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();\n templateResolver.setApplicationContext(this.applicationContext);\n templateResolver.setPrefix(\"/WEB-INF/thymeleaf/\");\n templateResolver.setSuffix(\".html\");\n templateResolver.setTemplateMode(TemplateMode.HTML);\n templateResolver.setCacheable(false);\n templateResolver.setCharacterEncoding(\"UTF-8\");\n return templateResolver;\n }\n\n @Bean\n public SpringTemplateEngine thymeleafTemplateEngine() {\n SpringTemplateEngine templateEngine = new SpringTemplateEngine();\n templateEngine.setTemplateResolver(thymeleafTemplateResolver());\n return templateEngine;\n }\n\n @Bean\n public ViewResolver thymeleafViewResolver() {\n ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();\n viewResolver.setViewNames(new String[] { \"*-thymeleaf\" });\n viewResolver.setTemplateEngine(thymeleafTemplateEngine());\n viewResolver.setCharacterEncoding(\"UTF-8\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver handlebarsViewResolver() {\n HandlebarsViewResolver viewResolver = new HandlebarsViewResolver();\n viewResolver.setViewNames(\"*-handlebars\");\n viewResolver.setPrefix(\"/WEB-INF/handlebars/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean(name = \"chunkTemplatesConfig\")\n @Scope(\"prototype\")\n public Map chunkTemplatesConfig() {\n Map config = new HashMap<>();\n config.put(\"default_extension\", \"chtml\");\n config.put(\"cache_minutes\", \"0\");\n config.put(\"layers\", \"\");\n config.put(\"theme_path\", \"\");\n config.put(\"hide_errors\", \"FALSE\");\n config.put(\"error_log\", \"\");\n config.put(\"encoding\", \"UTF-8\");\n config.put(\"locale\", \"\");\n config.put(\"filters\", \"\");\n return config;\n }\n\n @Bean\n public ViewResolver chunkViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(ChunkTemplateView.class);\n viewResolver.setPrefix(\"/WEB-INF/chunk/\");\n viewResolver.setViewNames(\"*-chunk\");\n viewResolver.setSuffix(\".chtml\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver jspViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(JstlView.class);\n viewResolver.setPrefix(\"/WEB-INF/jsp/\");\n viewResolver.setViewNames(\"*-jsp\");\n viewResolver.setSuffix(\".jsp\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver httlViewResolver() {\n HttlViewResolver viewResolver = new HttlViewResolver();\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n viewResolver.setViewNames(\"*-httl\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public SpringTemplateLoader jade4jTemplateLoader() {\n SpringTemplateLoader templateLoader = new SpringTemplateLoader();\n templateLoader.setEncoding(\"UTF-8\");\n return templateLoader;\n }\n\n @Bean\n public JadeConfiguration jadeConfiguration() {\n JadeConfiguration config = new JadeConfiguration();\n config.setPrettyPrint(true);\n config.setCaching(false);\n config.setTemplateLoader(applicationContext.getBean(SpringTemplateLoader.class));\n return config;\n }\n\n @Bean\n public ViewResolver jadeViewResolver() {\n JadeViewResolver viewResolver = new JadeViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/jade/\");\n viewResolver.setSuffix(\".jade\");\n viewResolver.setViewNames(\"*-jade\");\n viewResolver.setRenderExceptions(true);\n viewResolver.setCache(false);\n viewResolver.setConfiguration(applicationContext.getBean(JadeConfiguration.class));\n return viewResolver;\n }\n\n @Bean\n public ViewResolver scalateViewResolver() {\n ScalateViewResolver viewResolver = new ScalateViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/scalate/\");\n viewResolver.setSuffix(\".scaml\");\n viewResolver.setViewNames(\"*-scalate\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver htmlFlowViewResolver() {\n HtmlFlowViewResolver viewResolver = new HtmlFlowViewResolver();\n viewResolver.setViewNames(\"*-htmlFlow\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver trimouViewResolver() {\n MessageSource messageSource = applicationContext.getBean(MessageSource.class);\n TrimouViewResolver viewResolver = new TrimouViewResolver(messageSource);\n viewResolver.setPrefix(\"classpath:/templates/trimou/\");\n viewResolver.setSuffix(\".trimou\");\n viewResolver.setViewNames(\"*-trimou\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n ", "post_mask_code": "{\n RockerViewResolver viewResolver = new RockerViewResolver();\n viewResolver.setViewNames(\"*-rocker\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver ickenhamViewResolver() {\n IckenhamViewResolver viewResolver = new IckenhamViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/ickenham/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setViewNames(\"*-ickenham\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public RythmConfigurer rythmConfigurer() {\n RythmConfigurer conf = new RythmConfigurer();\n conf.setDevMode(true);\n conf.setResourceLoaderPath(\"/WEB-INF/rythm/\");\n conf.setAutoImports(\"com.jeroenreijn.examples.model.*\");\n return conf;\n }\n\n @Bean\n public ViewResolver rythmViewResolver() {\n RythmViewResolver viewResolver = new RythmViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/rythm/\");\n viewResolver.setSuffix(\".html\");\n viewResolver.setViewNames(\"*-rythm\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public LiqpViewResolver liqpViewResolver() {\n LiqpViewResolver viewResolver = new LiqpViewResolver(applicationContext.getBean(MessageSource.class));\n viewResolver.setViewClass(LiqpView.class);\n viewResolver.setPrefix(\"classpath:./templates/liqp/\");\n viewResolver.setSuffix(\".liqp\");\n viewResolver.setViewNames(\"*-liqp\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver kotlinxHtmlViewResolver() {\n KotlinxHtmlViewResolver viewResolver = new KotlinxHtmlViewResolver();\n viewResolver.setViewNames(\"*-kotlinx\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Controller\n static class FaviconController {\n\n @RequestMapping(\"favicon.ico\")\n String favicon() {\n return \"forward:/resources/images/favicon.ico\";\n }\n }\n}\n"} {"task_id": "Java_37", "language": "Java", "task_type": "method_body", "source_file": "java/github/jreijn/spring-comparing-template-engines/src/main/java/com/jeroenreijn/examples/configuration/WebMvcConfig.java", "mask_start_position": 3673, "mask_end_position": 3806, "canonical_solution": "{\n SessionLocaleResolver slr = new SessionLocaleResolver();\n slr.setDefaultLocale(Locale.US);\n return slr;\n }", "pre_mask_code": "package com.jeroenreijn.examples.configuration;\n\nimport java.util.HashMap;\nimport java.util.Locale;\nimport java.util.Map;\nimport com.jeroenreijn.examples.view.*;\nimport org.fusesource.scalate.spring.view.ScalateViewResolver;\nimport org.rythmengine.spring.web.RythmConfigurer;\nimport org.rythmengine.spring.web.RythmViewResolver;\nimport org.springframework.beans.BeansException;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\nimport org.springframework.context.MessageSource;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Scope;\nimport org.springframework.context.support.ReloadableResourceBundleMessageSource;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.servlet.LocaleResolver;\nimport org.springframework.web.servlet.ViewResolver;\nimport org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;\nimport org.springframework.web.servlet.config.annotation.EnableWebMvc;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\nimport org.springframework.web.servlet.i18n.SessionLocaleResolver;\nimport org.springframework.web.servlet.view.InternalResourceViewResolver;\nimport org.springframework.web.servlet.view.JstlView;\nimport org.thymeleaf.spring5.SpringTemplateEngine;\nimport org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;\nimport org.thymeleaf.spring5.view.ThymeleafViewResolver;\nimport org.thymeleaf.templatemode.TemplateMode;\nimport com.github.enpassant.ickenham.springmvc.IckenhamViewResolver;\nimport com.github.jknack.handlebars.springmvc.HandlebarsViewResolver;\nimport com.jeroenreijn.examples.repository.InMemoryPresentationsRepository;\nimport com.jeroenreijn.examples.repository.PresentationsRepository;\nimport com.x5.template.spring.ChunkTemplateView;\nimport de.neuland.jade4j.JadeConfiguration;\nimport de.neuland.jade4j.spring.template.SpringTemplateLoader;\nimport de.neuland.jade4j.spring.view.JadeViewResolver;\nimport httl.web.springmvc.HttlViewResolver;\n\n@Configuration\n@EnableWebMvc\n@ComponentScan(basePackages = { \"com.jeroenreijn.examples.controller\", \"com.jeroenreijn.examples.factory\" })\npublic class WebMvcConfig implements ApplicationContextAware, WebMvcConfigurer {\n\n private ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n }\n\n @Override\n public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {\n configurer.enable();\n }\n\n @Override\n public void addResourceHandlers(ResourceHandlerRegistry registry) {\n registry.addResourceHandler(\"/robots.txt\").addResourceLocations(\"/robots.txt\");\n registry.addResourceHandler(\"/webjars/**\").addResourceLocations(\"/webjars/\");\n registry.addResourceHandler(\"/resources/**\").addResourceLocations(\"/resources/\");\n }\n\n @Bean\n public MessageSource messageSource() {\n ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();\n messageSource.setBasename(\"classpath:/messages\");\n messageSource.setDefaultEncoding(\"UTF-8\");\n return messageSource;\n }\n\n @Bean\n public LocaleResolver localeResolver() ", "post_mask_code": "\n\n @Bean\n public PresentationsRepository presentationsRepository() {\n PresentationsRepository inMemory = new InMemoryPresentationsRepository();\n return inMemory;\n }\n\n @Bean\n public SpringResourceTemplateResolver thymeleafTemplateResolver() {\n SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();\n templateResolver.setApplicationContext(this.applicationContext);\n templateResolver.setPrefix(\"/WEB-INF/thymeleaf/\");\n templateResolver.setSuffix(\".html\");\n templateResolver.setTemplateMode(TemplateMode.HTML);\n templateResolver.setCacheable(false);\n templateResolver.setCharacterEncoding(\"UTF-8\");\n return templateResolver;\n }\n\n @Bean\n public SpringTemplateEngine thymeleafTemplateEngine() {\n SpringTemplateEngine templateEngine = new SpringTemplateEngine();\n templateEngine.setTemplateResolver(thymeleafTemplateResolver());\n return templateEngine;\n }\n\n @Bean\n public ViewResolver thymeleafViewResolver() {\n ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();\n viewResolver.setViewNames(new String[] { \"*-thymeleaf\" });\n viewResolver.setTemplateEngine(thymeleafTemplateEngine());\n viewResolver.setCharacterEncoding(\"UTF-8\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver handlebarsViewResolver() {\n HandlebarsViewResolver viewResolver = new HandlebarsViewResolver();\n viewResolver.setViewNames(\"*-handlebars\");\n viewResolver.setPrefix(\"/WEB-INF/handlebars/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean(name = \"chunkTemplatesConfig\")\n @Scope(\"prototype\")\n public Map chunkTemplatesConfig() {\n Map config = new HashMap<>();\n config.put(\"default_extension\", \"chtml\");\n config.put(\"cache_minutes\", \"0\");\n config.put(\"layers\", \"\");\n config.put(\"theme_path\", \"\");\n config.put(\"hide_errors\", \"FALSE\");\n config.put(\"error_log\", \"\");\n config.put(\"encoding\", \"UTF-8\");\n config.put(\"locale\", \"\");\n config.put(\"filters\", \"\");\n return config;\n }\n\n @Bean\n public ViewResolver chunkViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(ChunkTemplateView.class);\n viewResolver.setPrefix(\"/WEB-INF/chunk/\");\n viewResolver.setViewNames(\"*-chunk\");\n viewResolver.setSuffix(\".chtml\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver jspViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(JstlView.class);\n viewResolver.setPrefix(\"/WEB-INF/jsp/\");\n viewResolver.setViewNames(\"*-jsp\");\n viewResolver.setSuffix(\".jsp\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver httlViewResolver() {\n HttlViewResolver viewResolver = new HttlViewResolver();\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n viewResolver.setViewNames(\"*-httl\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public SpringTemplateLoader jade4jTemplateLoader() {\n SpringTemplateLoader templateLoader = new SpringTemplateLoader();\n templateLoader.setEncoding(\"UTF-8\");\n return templateLoader;\n }\n\n @Bean\n public JadeConfiguration jadeConfiguration() {\n JadeConfiguration config = new JadeConfiguration();\n config.setPrettyPrint(true);\n config.setCaching(false);\n config.setTemplateLoader(applicationContext.getBean(SpringTemplateLoader.class));\n return config;\n }\n\n @Bean\n public ViewResolver jadeViewResolver() {\n JadeViewResolver viewResolver = new JadeViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/jade/\");\n viewResolver.setSuffix(\".jade\");\n viewResolver.setViewNames(\"*-jade\");\n viewResolver.setRenderExceptions(true);\n viewResolver.setCache(false);\n viewResolver.setConfiguration(applicationContext.getBean(JadeConfiguration.class));\n return viewResolver;\n }\n\n @Bean\n public ViewResolver scalateViewResolver() {\n ScalateViewResolver viewResolver = new ScalateViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/scalate/\");\n viewResolver.setSuffix(\".scaml\");\n viewResolver.setViewNames(\"*-scalate\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver htmlFlowViewResolver() {\n HtmlFlowViewResolver viewResolver = new HtmlFlowViewResolver();\n viewResolver.setViewNames(\"*-htmlFlow\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver trimouViewResolver() {\n MessageSource messageSource = applicationContext.getBean(MessageSource.class);\n TrimouViewResolver viewResolver = new TrimouViewResolver(messageSource);\n viewResolver.setPrefix(\"classpath:/templates/trimou/\");\n viewResolver.setSuffix(\".trimou\");\n viewResolver.setViewNames(\"*-trimou\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver rockerViewResolver() {\n RockerViewResolver viewResolver = new RockerViewResolver();\n viewResolver.setViewNames(\"*-rocker\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver ickenhamViewResolver() {\n IckenhamViewResolver viewResolver = new IckenhamViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/ickenham/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setViewNames(\"*-ickenham\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public RythmConfigurer rythmConfigurer() {\n RythmConfigurer conf = new RythmConfigurer();\n conf.setDevMode(true);\n conf.setResourceLoaderPath(\"/WEB-INF/rythm/\");\n conf.setAutoImports(\"com.jeroenreijn.examples.model.*\");\n return conf;\n }\n\n @Bean\n public ViewResolver rythmViewResolver() {\n RythmViewResolver viewResolver = new RythmViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/rythm/\");\n viewResolver.setSuffix(\".html\");\n viewResolver.setViewNames(\"*-rythm\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public LiqpViewResolver liqpViewResolver() {\n LiqpViewResolver viewResolver = new LiqpViewResolver(applicationContext.getBean(MessageSource.class));\n viewResolver.setViewClass(LiqpView.class);\n viewResolver.setPrefix(\"classpath:./templates/liqp/\");\n viewResolver.setSuffix(\".liqp\");\n viewResolver.setViewNames(\"*-liqp\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver kotlinxHtmlViewResolver() {\n KotlinxHtmlViewResolver viewResolver = new KotlinxHtmlViewResolver();\n viewResolver.setViewNames(\"*-kotlinx\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Controller\n static class FaviconController {\n\n @RequestMapping(\"favicon.ico\")\n String favicon() {\n return \"forward:/resources/images/favicon.ico\";\n }\n }\n}\n"} {"task_id": "Java_38", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/jreijn/spring-comparing-template-engines/src/main/java/com/jeroenreijn/examples/configuration/WebMvcConfig.java", "mask_start_position": 9192, "mask_end_position": 9360, "canonical_solution": "\n MessageSource messageSource = applicationContext.getBean(MessageSource.class);\n TrimouViewResolver viewResolver = new TrimouViewResolver(messageSource);", "pre_mask_code": "package com.jeroenreijn.examples.configuration;\n\nimport java.util.HashMap;\nimport java.util.Locale;\nimport java.util.Map;\nimport com.jeroenreijn.examples.view.*;\nimport org.fusesource.scalate.spring.view.ScalateViewResolver;\nimport org.rythmengine.spring.web.RythmConfigurer;\nimport org.rythmengine.spring.web.RythmViewResolver;\nimport org.springframework.beans.BeansException;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\nimport org.springframework.context.MessageSource;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Scope;\nimport org.springframework.context.support.ReloadableResourceBundleMessageSource;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.servlet.LocaleResolver;\nimport org.springframework.web.servlet.ViewResolver;\nimport org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;\nimport org.springframework.web.servlet.config.annotation.EnableWebMvc;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\nimport org.springframework.web.servlet.i18n.SessionLocaleResolver;\nimport org.springframework.web.servlet.view.InternalResourceViewResolver;\nimport org.springframework.web.servlet.view.JstlView;\nimport org.thymeleaf.spring5.SpringTemplateEngine;\nimport org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;\nimport org.thymeleaf.spring5.view.ThymeleafViewResolver;\nimport org.thymeleaf.templatemode.TemplateMode;\nimport com.github.enpassant.ickenham.springmvc.IckenhamViewResolver;\nimport com.github.jknack.handlebars.springmvc.HandlebarsViewResolver;\nimport com.jeroenreijn.examples.repository.InMemoryPresentationsRepository;\nimport com.jeroenreijn.examples.repository.PresentationsRepository;\nimport com.x5.template.spring.ChunkTemplateView;\nimport de.neuland.jade4j.JadeConfiguration;\nimport de.neuland.jade4j.spring.template.SpringTemplateLoader;\nimport de.neuland.jade4j.spring.view.JadeViewResolver;\nimport httl.web.springmvc.HttlViewResolver;\n\n@Configuration\n@EnableWebMvc\n@ComponentScan(basePackages = { \"com.jeroenreijn.examples.controller\", \"com.jeroenreijn.examples.factory\" })\npublic class WebMvcConfig implements ApplicationContextAware, WebMvcConfigurer {\n\n private ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n }\n\n @Override\n public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {\n configurer.enable();\n }\n\n @Override\n public void addResourceHandlers(ResourceHandlerRegistry registry) {\n registry.addResourceHandler(\"/robots.txt\").addResourceLocations(\"/robots.txt\");\n registry.addResourceHandler(\"/webjars/**\").addResourceLocations(\"/webjars/\");\n registry.addResourceHandler(\"/resources/**\").addResourceLocations(\"/resources/\");\n }\n\n @Bean\n public MessageSource messageSource() {\n ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();\n messageSource.setBasename(\"classpath:/messages\");\n messageSource.setDefaultEncoding(\"UTF-8\");\n return messageSource;\n }\n\n @Bean\n public LocaleResolver localeResolver() {\n SessionLocaleResolver slr = new SessionLocaleResolver();\n slr.setDefaultLocale(Locale.US);\n return slr;\n }\n\n @Bean\n public PresentationsRepository presentationsRepository() {\n PresentationsRepository inMemory = new InMemoryPresentationsRepository();\n return inMemory;\n }\n\n @Bean\n public SpringResourceTemplateResolver thymeleafTemplateResolver() {\n SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();\n templateResolver.setApplicationContext(this.applicationContext);\n templateResolver.setPrefix(\"/WEB-INF/thymeleaf/\");\n templateResolver.setSuffix(\".html\");\n templateResolver.setTemplateMode(TemplateMode.HTML);\n templateResolver.setCacheable(false);\n templateResolver.setCharacterEncoding(\"UTF-8\");\n return templateResolver;\n }\n\n @Bean\n public SpringTemplateEngine thymeleafTemplateEngine() {\n SpringTemplateEngine templateEngine = new SpringTemplateEngine();\n templateEngine.setTemplateResolver(thymeleafTemplateResolver());\n return templateEngine;\n }\n\n @Bean\n public ViewResolver thymeleafViewResolver() {\n ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();\n viewResolver.setViewNames(new String[] { \"*-thymeleaf\" });\n viewResolver.setTemplateEngine(thymeleafTemplateEngine());\n viewResolver.setCharacterEncoding(\"UTF-8\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver handlebarsViewResolver() {\n HandlebarsViewResolver viewResolver = new HandlebarsViewResolver();\n viewResolver.setViewNames(\"*-handlebars\");\n viewResolver.setPrefix(\"/WEB-INF/handlebars/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean(name = \"chunkTemplatesConfig\")\n @Scope(\"prototype\")\n public Map chunkTemplatesConfig() {\n Map config = new HashMap<>();\n config.put(\"default_extension\", \"chtml\");\n config.put(\"cache_minutes\", \"0\");\n config.put(\"layers\", \"\");\n config.put(\"theme_path\", \"\");\n config.put(\"hide_errors\", \"FALSE\");\n config.put(\"error_log\", \"\");\n config.put(\"encoding\", \"UTF-8\");\n config.put(\"locale\", \"\");\n config.put(\"filters\", \"\");\n return config;\n }\n\n @Bean\n public ViewResolver chunkViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(ChunkTemplateView.class);\n viewResolver.setPrefix(\"/WEB-INF/chunk/\");\n viewResolver.setViewNames(\"*-chunk\");\n viewResolver.setSuffix(\".chtml\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver jspViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(JstlView.class);\n viewResolver.setPrefix(\"/WEB-INF/jsp/\");\n viewResolver.setViewNames(\"*-jsp\");\n viewResolver.setSuffix(\".jsp\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver httlViewResolver() {\n HttlViewResolver viewResolver = new HttlViewResolver();\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n viewResolver.setViewNames(\"*-httl\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public SpringTemplateLoader jade4jTemplateLoader() {\n SpringTemplateLoader templateLoader = new SpringTemplateLoader();\n templateLoader.setEncoding(\"UTF-8\");\n return templateLoader;\n }\n\n @Bean\n public JadeConfiguration jadeConfiguration() {\n JadeConfiguration config = new JadeConfiguration();\n config.setPrettyPrint(true);\n config.setCaching(false);\n config.setTemplateLoader(applicationContext.getBean(SpringTemplateLoader.class));\n return config;\n }\n\n @Bean\n public ViewResolver jadeViewResolver() {\n JadeViewResolver viewResolver = new JadeViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/jade/\");\n viewResolver.setSuffix(\".jade\");\n viewResolver.setViewNames(\"*-jade\");\n viewResolver.setRenderExceptions(true);\n viewResolver.setCache(false);\n viewResolver.setConfiguration(applicationContext.getBean(JadeConfiguration.class));\n return viewResolver;\n }\n\n @Bean\n public ViewResolver scalateViewResolver() {\n ScalateViewResolver viewResolver = new ScalateViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/scalate/\");\n viewResolver.setSuffix(\".scaml\");\n viewResolver.setViewNames(\"*-scalate\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver htmlFlowViewResolver() {\n HtmlFlowViewResolver viewResolver = new HtmlFlowViewResolver();\n viewResolver.setViewNames(\"*-htmlFlow\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver trimouViewResolver() {", "post_mask_code": "\n viewResolver.setPrefix(\"classpath:/templates/trimou/\");\n viewResolver.setSuffix(\".trimou\");\n viewResolver.setViewNames(\"*-trimou\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver rockerViewResolver() {\n RockerViewResolver viewResolver = new RockerViewResolver();\n viewResolver.setViewNames(\"*-rocker\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver ickenhamViewResolver() {\n IckenhamViewResolver viewResolver = new IckenhamViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/ickenham/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setViewNames(\"*-ickenham\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public RythmConfigurer rythmConfigurer() {\n RythmConfigurer conf = new RythmConfigurer();\n conf.setDevMode(true);\n conf.setResourceLoaderPath(\"/WEB-INF/rythm/\");\n conf.setAutoImports(\"com.jeroenreijn.examples.model.*\");\n return conf;\n }\n\n @Bean\n public ViewResolver rythmViewResolver() {\n RythmViewResolver viewResolver = new RythmViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/rythm/\");\n viewResolver.setSuffix(\".html\");\n viewResolver.setViewNames(\"*-rythm\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public LiqpViewResolver liqpViewResolver() {\n LiqpViewResolver viewResolver = new LiqpViewResolver(applicationContext.getBean(MessageSource.class));\n viewResolver.setViewClass(LiqpView.class);\n viewResolver.setPrefix(\"classpath:./templates/liqp/\");\n viewResolver.setSuffix(\".liqp\");\n viewResolver.setViewNames(\"*-liqp\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver kotlinxHtmlViewResolver() {\n KotlinxHtmlViewResolver viewResolver = new KotlinxHtmlViewResolver();\n viewResolver.setViewNames(\"*-kotlinx\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Controller\n static class FaviconController {\n\n @RequestMapping(\"favicon.ico\")\n String favicon() {\n return \"forward:/resources/images/favicon.ico\";\n }\n }\n}\n"} {"task_id": "Java_39", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/jreijn/spring-comparing-template-engines/src/main/java/com/jeroenreijn/examples/configuration/WebMvcConfig.java", "mask_start_position": 9369, "mask_end_position": 9514, "canonical_solution": "viewResolver.setPrefix(\"classpath:/templates/trimou/\");\n viewResolver.setSuffix(\".trimou\");\n viewResolver.setViewNames(\"*-trimou\");", "pre_mask_code": "package com.jeroenreijn.examples.configuration;\n\nimport java.util.HashMap;\nimport java.util.Locale;\nimport java.util.Map;\nimport com.jeroenreijn.examples.view.*;\nimport org.fusesource.scalate.spring.view.ScalateViewResolver;\nimport org.rythmengine.spring.web.RythmConfigurer;\nimport org.rythmengine.spring.web.RythmViewResolver;\nimport org.springframework.beans.BeansException;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\nimport org.springframework.context.MessageSource;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Scope;\nimport org.springframework.context.support.ReloadableResourceBundleMessageSource;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.servlet.LocaleResolver;\nimport org.springframework.web.servlet.ViewResolver;\nimport org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;\nimport org.springframework.web.servlet.config.annotation.EnableWebMvc;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\nimport org.springframework.web.servlet.i18n.SessionLocaleResolver;\nimport org.springframework.web.servlet.view.InternalResourceViewResolver;\nimport org.springframework.web.servlet.view.JstlView;\nimport org.thymeleaf.spring5.SpringTemplateEngine;\nimport org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;\nimport org.thymeleaf.spring5.view.ThymeleafViewResolver;\nimport org.thymeleaf.templatemode.TemplateMode;\nimport com.github.enpassant.ickenham.springmvc.IckenhamViewResolver;\nimport com.github.jknack.handlebars.springmvc.HandlebarsViewResolver;\nimport com.jeroenreijn.examples.repository.InMemoryPresentationsRepository;\nimport com.jeroenreijn.examples.repository.PresentationsRepository;\nimport com.x5.template.spring.ChunkTemplateView;\nimport de.neuland.jade4j.JadeConfiguration;\nimport de.neuland.jade4j.spring.template.SpringTemplateLoader;\nimport de.neuland.jade4j.spring.view.JadeViewResolver;\nimport httl.web.springmvc.HttlViewResolver;\n\n@Configuration\n@EnableWebMvc\n@ComponentScan(basePackages = { \"com.jeroenreijn.examples.controller\", \"com.jeroenreijn.examples.factory\" })\npublic class WebMvcConfig implements ApplicationContextAware, WebMvcConfigurer {\n\n private ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n }\n\n @Override\n public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {\n configurer.enable();\n }\n\n @Override\n public void addResourceHandlers(ResourceHandlerRegistry registry) {\n registry.addResourceHandler(\"/robots.txt\").addResourceLocations(\"/robots.txt\");\n registry.addResourceHandler(\"/webjars/**\").addResourceLocations(\"/webjars/\");\n registry.addResourceHandler(\"/resources/**\").addResourceLocations(\"/resources/\");\n }\n\n @Bean\n public MessageSource messageSource() {\n ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();\n messageSource.setBasename(\"classpath:/messages\");\n messageSource.setDefaultEncoding(\"UTF-8\");\n return messageSource;\n }\n\n @Bean\n public LocaleResolver localeResolver() {\n SessionLocaleResolver slr = new SessionLocaleResolver();\n slr.setDefaultLocale(Locale.US);\n return slr;\n }\n\n @Bean\n public PresentationsRepository presentationsRepository() {\n PresentationsRepository inMemory = new InMemoryPresentationsRepository();\n return inMemory;\n }\n\n @Bean\n public SpringResourceTemplateResolver thymeleafTemplateResolver() {\n SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();\n templateResolver.setApplicationContext(this.applicationContext);\n templateResolver.setPrefix(\"/WEB-INF/thymeleaf/\");\n templateResolver.setSuffix(\".html\");\n templateResolver.setTemplateMode(TemplateMode.HTML);\n templateResolver.setCacheable(false);\n templateResolver.setCharacterEncoding(\"UTF-8\");\n return templateResolver;\n }\n\n @Bean\n public SpringTemplateEngine thymeleafTemplateEngine() {\n SpringTemplateEngine templateEngine = new SpringTemplateEngine();\n templateEngine.setTemplateResolver(thymeleafTemplateResolver());\n return templateEngine;\n }\n\n @Bean\n public ViewResolver thymeleafViewResolver() {\n ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();\n viewResolver.setViewNames(new String[] { \"*-thymeleaf\" });\n viewResolver.setTemplateEngine(thymeleafTemplateEngine());\n viewResolver.setCharacterEncoding(\"UTF-8\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver handlebarsViewResolver() {\n HandlebarsViewResolver viewResolver = new HandlebarsViewResolver();\n viewResolver.setViewNames(\"*-handlebars\");\n viewResolver.setPrefix(\"/WEB-INF/handlebars/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean(name = \"chunkTemplatesConfig\")\n @Scope(\"prototype\")\n public Map chunkTemplatesConfig() {\n Map config = new HashMap<>();\n config.put(\"default_extension\", \"chtml\");\n config.put(\"cache_minutes\", \"0\");\n config.put(\"layers\", \"\");\n config.put(\"theme_path\", \"\");\n config.put(\"hide_errors\", \"FALSE\");\n config.put(\"error_log\", \"\");\n config.put(\"encoding\", \"UTF-8\");\n config.put(\"locale\", \"\");\n config.put(\"filters\", \"\");\n return config;\n }\n\n @Bean\n public ViewResolver chunkViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(ChunkTemplateView.class);\n viewResolver.setPrefix(\"/WEB-INF/chunk/\");\n viewResolver.setViewNames(\"*-chunk\");\n viewResolver.setSuffix(\".chtml\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver jspViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(JstlView.class);\n viewResolver.setPrefix(\"/WEB-INF/jsp/\");\n viewResolver.setViewNames(\"*-jsp\");\n viewResolver.setSuffix(\".jsp\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver httlViewResolver() {\n HttlViewResolver viewResolver = new HttlViewResolver();\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n viewResolver.setViewNames(\"*-httl\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public SpringTemplateLoader jade4jTemplateLoader() {\n SpringTemplateLoader templateLoader = new SpringTemplateLoader();\n templateLoader.setEncoding(\"UTF-8\");\n return templateLoader;\n }\n\n @Bean\n public JadeConfiguration jadeConfiguration() {\n JadeConfiguration config = new JadeConfiguration();\n config.setPrettyPrint(true);\n config.setCaching(false);\n config.setTemplateLoader(applicationContext.getBean(SpringTemplateLoader.class));\n return config;\n }\n\n @Bean\n public ViewResolver jadeViewResolver() {\n JadeViewResolver viewResolver = new JadeViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/jade/\");\n viewResolver.setSuffix(\".jade\");\n viewResolver.setViewNames(\"*-jade\");\n viewResolver.setRenderExceptions(true);\n viewResolver.setCache(false);\n viewResolver.setConfiguration(applicationContext.getBean(JadeConfiguration.class));\n return viewResolver;\n }\n\n @Bean\n public ViewResolver scalateViewResolver() {\n ScalateViewResolver viewResolver = new ScalateViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/scalate/\");\n viewResolver.setSuffix(\".scaml\");\n viewResolver.setViewNames(\"*-scalate\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver htmlFlowViewResolver() {\n HtmlFlowViewResolver viewResolver = new HtmlFlowViewResolver();\n viewResolver.setViewNames(\"*-htmlFlow\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver trimouViewResolver() {\n MessageSource messageSource = applicationContext.getBean(MessageSource.class);\n TrimouViewResolver viewResolver = new TrimouViewResolver(messageSource);\n ", "post_mask_code": "\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver rockerViewResolver() {\n RockerViewResolver viewResolver = new RockerViewResolver();\n viewResolver.setViewNames(\"*-rocker\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver ickenhamViewResolver() {\n IckenhamViewResolver viewResolver = new IckenhamViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/ickenham/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setViewNames(\"*-ickenham\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public RythmConfigurer rythmConfigurer() {\n RythmConfigurer conf = new RythmConfigurer();\n conf.setDevMode(true);\n conf.setResourceLoaderPath(\"/WEB-INF/rythm/\");\n conf.setAutoImports(\"com.jeroenreijn.examples.model.*\");\n return conf;\n }\n\n @Bean\n public ViewResolver rythmViewResolver() {\n RythmViewResolver viewResolver = new RythmViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/rythm/\");\n viewResolver.setSuffix(\".html\");\n viewResolver.setViewNames(\"*-rythm\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public LiqpViewResolver liqpViewResolver() {\n LiqpViewResolver viewResolver = new LiqpViewResolver(applicationContext.getBean(MessageSource.class));\n viewResolver.setViewClass(LiqpView.class);\n viewResolver.setPrefix(\"classpath:./templates/liqp/\");\n viewResolver.setSuffix(\".liqp\");\n viewResolver.setViewNames(\"*-liqp\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver kotlinxHtmlViewResolver() {\n KotlinxHtmlViewResolver viewResolver = new KotlinxHtmlViewResolver();\n viewResolver.setViewNames(\"*-kotlinx\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Controller\n static class FaviconController {\n\n @RequestMapping(\"favicon.ico\")\n String favicon() {\n return \"forward:/resources/images/favicon.ico\";\n }\n }\n}\n"} {"task_id": "Java_40", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/jreijn/spring-comparing-template-engines/src/main/java/com/jeroenreijn/examples/configuration/WebMvcConfig.java", "mask_start_position": 9523, "mask_end_position": 9587, "canonical_solution": "viewResolver.setCache(false);\n return viewResolver;\n }", "pre_mask_code": "package com.jeroenreijn.examples.configuration;\n\nimport java.util.HashMap;\nimport java.util.Locale;\nimport java.util.Map;\nimport com.jeroenreijn.examples.view.*;\nimport org.fusesource.scalate.spring.view.ScalateViewResolver;\nimport org.rythmengine.spring.web.RythmConfigurer;\nimport org.rythmengine.spring.web.RythmViewResolver;\nimport org.springframework.beans.BeansException;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\nimport org.springframework.context.MessageSource;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Scope;\nimport org.springframework.context.support.ReloadableResourceBundleMessageSource;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.servlet.LocaleResolver;\nimport org.springframework.web.servlet.ViewResolver;\nimport org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;\nimport org.springframework.web.servlet.config.annotation.EnableWebMvc;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\nimport org.springframework.web.servlet.i18n.SessionLocaleResolver;\nimport org.springframework.web.servlet.view.InternalResourceViewResolver;\nimport org.springframework.web.servlet.view.JstlView;\nimport org.thymeleaf.spring5.SpringTemplateEngine;\nimport org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;\nimport org.thymeleaf.spring5.view.ThymeleafViewResolver;\nimport org.thymeleaf.templatemode.TemplateMode;\nimport com.github.enpassant.ickenham.springmvc.IckenhamViewResolver;\nimport com.github.jknack.handlebars.springmvc.HandlebarsViewResolver;\nimport com.jeroenreijn.examples.repository.InMemoryPresentationsRepository;\nimport com.jeroenreijn.examples.repository.PresentationsRepository;\nimport com.x5.template.spring.ChunkTemplateView;\nimport de.neuland.jade4j.JadeConfiguration;\nimport de.neuland.jade4j.spring.template.SpringTemplateLoader;\nimport de.neuland.jade4j.spring.view.JadeViewResolver;\nimport httl.web.springmvc.HttlViewResolver;\n\n@Configuration\n@EnableWebMvc\n@ComponentScan(basePackages = { \"com.jeroenreijn.examples.controller\", \"com.jeroenreijn.examples.factory\" })\npublic class WebMvcConfig implements ApplicationContextAware, WebMvcConfigurer {\n\n private ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n }\n\n @Override\n public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {\n configurer.enable();\n }\n\n @Override\n public void addResourceHandlers(ResourceHandlerRegistry registry) {\n registry.addResourceHandler(\"/robots.txt\").addResourceLocations(\"/robots.txt\");\n registry.addResourceHandler(\"/webjars/**\").addResourceLocations(\"/webjars/\");\n registry.addResourceHandler(\"/resources/**\").addResourceLocations(\"/resources/\");\n }\n\n @Bean\n public MessageSource messageSource() {\n ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();\n messageSource.setBasename(\"classpath:/messages\");\n messageSource.setDefaultEncoding(\"UTF-8\");\n return messageSource;\n }\n\n @Bean\n public LocaleResolver localeResolver() {\n SessionLocaleResolver slr = new SessionLocaleResolver();\n slr.setDefaultLocale(Locale.US);\n return slr;\n }\n\n @Bean\n public PresentationsRepository presentationsRepository() {\n PresentationsRepository inMemory = new InMemoryPresentationsRepository();\n return inMemory;\n }\n\n @Bean\n public SpringResourceTemplateResolver thymeleafTemplateResolver() {\n SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();\n templateResolver.setApplicationContext(this.applicationContext);\n templateResolver.setPrefix(\"/WEB-INF/thymeleaf/\");\n templateResolver.setSuffix(\".html\");\n templateResolver.setTemplateMode(TemplateMode.HTML);\n templateResolver.setCacheable(false);\n templateResolver.setCharacterEncoding(\"UTF-8\");\n return templateResolver;\n }\n\n @Bean\n public SpringTemplateEngine thymeleafTemplateEngine() {\n SpringTemplateEngine templateEngine = new SpringTemplateEngine();\n templateEngine.setTemplateResolver(thymeleafTemplateResolver());\n return templateEngine;\n }\n\n @Bean\n public ViewResolver thymeleafViewResolver() {\n ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();\n viewResolver.setViewNames(new String[] { \"*-thymeleaf\" });\n viewResolver.setTemplateEngine(thymeleafTemplateEngine());\n viewResolver.setCharacterEncoding(\"UTF-8\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver handlebarsViewResolver() {\n HandlebarsViewResolver viewResolver = new HandlebarsViewResolver();\n viewResolver.setViewNames(\"*-handlebars\");\n viewResolver.setPrefix(\"/WEB-INF/handlebars/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean(name = \"chunkTemplatesConfig\")\n @Scope(\"prototype\")\n public Map chunkTemplatesConfig() {\n Map config = new HashMap<>();\n config.put(\"default_extension\", \"chtml\");\n config.put(\"cache_minutes\", \"0\");\n config.put(\"layers\", \"\");\n config.put(\"theme_path\", \"\");\n config.put(\"hide_errors\", \"FALSE\");\n config.put(\"error_log\", \"\");\n config.put(\"encoding\", \"UTF-8\");\n config.put(\"locale\", \"\");\n config.put(\"filters\", \"\");\n return config;\n }\n\n @Bean\n public ViewResolver chunkViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(ChunkTemplateView.class);\n viewResolver.setPrefix(\"/WEB-INF/chunk/\");\n viewResolver.setViewNames(\"*-chunk\");\n viewResolver.setSuffix(\".chtml\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver jspViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(JstlView.class);\n viewResolver.setPrefix(\"/WEB-INF/jsp/\");\n viewResolver.setViewNames(\"*-jsp\");\n viewResolver.setSuffix(\".jsp\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver httlViewResolver() {\n HttlViewResolver viewResolver = new HttlViewResolver();\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n viewResolver.setViewNames(\"*-httl\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public SpringTemplateLoader jade4jTemplateLoader() {\n SpringTemplateLoader templateLoader = new SpringTemplateLoader();\n templateLoader.setEncoding(\"UTF-8\");\n return templateLoader;\n }\n\n @Bean\n public JadeConfiguration jadeConfiguration() {\n JadeConfiguration config = new JadeConfiguration();\n config.setPrettyPrint(true);\n config.setCaching(false);\n config.setTemplateLoader(applicationContext.getBean(SpringTemplateLoader.class));\n return config;\n }\n\n @Bean\n public ViewResolver jadeViewResolver() {\n JadeViewResolver viewResolver = new JadeViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/jade/\");\n viewResolver.setSuffix(\".jade\");\n viewResolver.setViewNames(\"*-jade\");\n viewResolver.setRenderExceptions(true);\n viewResolver.setCache(false);\n viewResolver.setConfiguration(applicationContext.getBean(JadeConfiguration.class));\n return viewResolver;\n }\n\n @Bean\n public ViewResolver scalateViewResolver() {\n ScalateViewResolver viewResolver = new ScalateViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/scalate/\");\n viewResolver.setSuffix(\".scaml\");\n viewResolver.setViewNames(\"*-scalate\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver htmlFlowViewResolver() {\n HtmlFlowViewResolver viewResolver = new HtmlFlowViewResolver();\n viewResolver.setViewNames(\"*-htmlFlow\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver trimouViewResolver() {\n MessageSource messageSource = applicationContext.getBean(MessageSource.class);\n TrimouViewResolver viewResolver = new TrimouViewResolver(messageSource);\n viewResolver.setPrefix(\"classpath:/templates/trimou/\");\n viewResolver.setSuffix(\".trimou\");\n viewResolver.setViewNames(\"*-trimou\");\n ", "post_mask_code": "\n\n @Bean\n public ViewResolver rockerViewResolver() {\n RockerViewResolver viewResolver = new RockerViewResolver();\n viewResolver.setViewNames(\"*-rocker\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver ickenhamViewResolver() {\n IckenhamViewResolver viewResolver = new IckenhamViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/ickenham/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setViewNames(\"*-ickenham\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public RythmConfigurer rythmConfigurer() {\n RythmConfigurer conf = new RythmConfigurer();\n conf.setDevMode(true);\n conf.setResourceLoaderPath(\"/WEB-INF/rythm/\");\n conf.setAutoImports(\"com.jeroenreijn.examples.model.*\");\n return conf;\n }\n\n @Bean\n public ViewResolver rythmViewResolver() {\n RythmViewResolver viewResolver = new RythmViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/rythm/\");\n viewResolver.setSuffix(\".html\");\n viewResolver.setViewNames(\"*-rythm\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public LiqpViewResolver liqpViewResolver() {\n LiqpViewResolver viewResolver = new LiqpViewResolver(applicationContext.getBean(MessageSource.class));\n viewResolver.setViewClass(LiqpView.class);\n viewResolver.setPrefix(\"classpath:./templates/liqp/\");\n viewResolver.setSuffix(\".liqp\");\n viewResolver.setViewNames(\"*-liqp\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver kotlinxHtmlViewResolver() {\n KotlinxHtmlViewResolver viewResolver = new KotlinxHtmlViewResolver();\n viewResolver.setViewNames(\"*-kotlinx\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Controller\n static class FaviconController {\n\n @RequestMapping(\"favicon.ico\")\n String favicon() {\n return \"forward:/resources/images/favicon.ico\";\n }\n }\n}\n"} {"task_id": "Java_41", "language": "Java", "task_type": "single_line", "source_file": "java/github/jreijn/spring-comparing-template-engines/src/main/java/com/jeroenreijn/examples/configuration/WebMvcConfig.java", "mask_start_position": 6883, "mask_end_position": 6897, "canonical_solution": "EB-INF/jsp/\");", "pre_mask_code": "package com.jeroenreijn.examples.configuration;\n\nimport java.util.HashMap;\nimport java.util.Locale;\nimport java.util.Map;\nimport com.jeroenreijn.examples.view.*;\nimport org.fusesource.scalate.spring.view.ScalateViewResolver;\nimport org.rythmengine.spring.web.RythmConfigurer;\nimport org.rythmengine.spring.web.RythmViewResolver;\nimport org.springframework.beans.BeansException;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\nimport org.springframework.context.MessageSource;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Scope;\nimport org.springframework.context.support.ReloadableResourceBundleMessageSource;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.servlet.LocaleResolver;\nimport org.springframework.web.servlet.ViewResolver;\nimport org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;\nimport org.springframework.web.servlet.config.annotation.EnableWebMvc;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\nimport org.springframework.web.servlet.i18n.SessionLocaleResolver;\nimport org.springframework.web.servlet.view.InternalResourceViewResolver;\nimport org.springframework.web.servlet.view.JstlView;\nimport org.thymeleaf.spring5.SpringTemplateEngine;\nimport org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;\nimport org.thymeleaf.spring5.view.ThymeleafViewResolver;\nimport org.thymeleaf.templatemode.TemplateMode;\nimport com.github.enpassant.ickenham.springmvc.IckenhamViewResolver;\nimport com.github.jknack.handlebars.springmvc.HandlebarsViewResolver;\nimport com.jeroenreijn.examples.repository.InMemoryPresentationsRepository;\nimport com.jeroenreijn.examples.repository.PresentationsRepository;\nimport com.x5.template.spring.ChunkTemplateView;\nimport de.neuland.jade4j.JadeConfiguration;\nimport de.neuland.jade4j.spring.template.SpringTemplateLoader;\nimport de.neuland.jade4j.spring.view.JadeViewResolver;\nimport httl.web.springmvc.HttlViewResolver;\n\n@Configuration\n@EnableWebMvc\n@ComponentScan(basePackages = { \"com.jeroenreijn.examples.controller\", \"com.jeroenreijn.examples.factory\" })\npublic class WebMvcConfig implements ApplicationContextAware, WebMvcConfigurer {\n\n private ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n }\n\n @Override\n public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {\n configurer.enable();\n }\n\n @Override\n public void addResourceHandlers(ResourceHandlerRegistry registry) {\n registry.addResourceHandler(\"/robots.txt\").addResourceLocations(\"/robots.txt\");\n registry.addResourceHandler(\"/webjars/**\").addResourceLocations(\"/webjars/\");\n registry.addResourceHandler(\"/resources/**\").addResourceLocations(\"/resources/\");\n }\n\n @Bean\n public MessageSource messageSource() {\n ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();\n messageSource.setBasename(\"classpath:/messages\");\n messageSource.setDefaultEncoding(\"UTF-8\");\n return messageSource;\n }\n\n @Bean\n public LocaleResolver localeResolver() {\n SessionLocaleResolver slr = new SessionLocaleResolver();\n slr.setDefaultLocale(Locale.US);\n return slr;\n }\n\n @Bean\n public PresentationsRepository presentationsRepository() {\n PresentationsRepository inMemory = new InMemoryPresentationsRepository();\n return inMemory;\n }\n\n @Bean\n public SpringResourceTemplateResolver thymeleafTemplateResolver() {\n SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();\n templateResolver.setApplicationContext(this.applicationContext);\n templateResolver.setPrefix(\"/WEB-INF/thymeleaf/\");\n templateResolver.setSuffix(\".html\");\n templateResolver.setTemplateMode(TemplateMode.HTML);\n templateResolver.setCacheable(false);\n templateResolver.setCharacterEncoding(\"UTF-8\");\n return templateResolver;\n }\n\n @Bean\n public SpringTemplateEngine thymeleafTemplateEngine() {\n SpringTemplateEngine templateEngine = new SpringTemplateEngine();\n templateEngine.setTemplateResolver(thymeleafTemplateResolver());\n return templateEngine;\n }\n\n @Bean\n public ViewResolver thymeleafViewResolver() {\n ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();\n viewResolver.setViewNames(new String[] { \"*-thymeleaf\" });\n viewResolver.setTemplateEngine(thymeleafTemplateEngine());\n viewResolver.setCharacterEncoding(\"UTF-8\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver handlebarsViewResolver() {\n HandlebarsViewResolver viewResolver = new HandlebarsViewResolver();\n viewResolver.setViewNames(\"*-handlebars\");\n viewResolver.setPrefix(\"/WEB-INF/handlebars/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean(name = \"chunkTemplatesConfig\")\n @Scope(\"prototype\")\n public Map chunkTemplatesConfig() {\n Map config = new HashMap<>();\n config.put(\"default_extension\", \"chtml\");\n config.put(\"cache_minutes\", \"0\");\n config.put(\"layers\", \"\");\n config.put(\"theme_path\", \"\");\n config.put(\"hide_errors\", \"FALSE\");\n config.put(\"error_log\", \"\");\n config.put(\"encoding\", \"UTF-8\");\n config.put(\"locale\", \"\");\n config.put(\"filters\", \"\");\n return config;\n }\n\n @Bean\n public ViewResolver chunkViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(ChunkTemplateView.class);\n viewResolver.setPrefix(\"/WEB-INF/chunk/\");\n viewResolver.setViewNames(\"*-chunk\");\n viewResolver.setSuffix(\".chtml\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver jspViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(JstlView.class);\n viewResolver.setPrefix(\"/W", "post_mask_code": "\n viewResolver.setViewNames(\"*-jsp\");\n viewResolver.setSuffix(\".jsp\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver httlViewResolver() {\n HttlViewResolver viewResolver = new HttlViewResolver();\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n viewResolver.setViewNames(\"*-httl\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public SpringTemplateLoader jade4jTemplateLoader() {\n SpringTemplateLoader templateLoader = new SpringTemplateLoader();\n templateLoader.setEncoding(\"UTF-8\");\n return templateLoader;\n }\n\n @Bean\n public JadeConfiguration jadeConfiguration() {\n JadeConfiguration config = new JadeConfiguration();\n config.setPrettyPrint(true);\n config.setCaching(false);\n config.setTemplateLoader(applicationContext.getBean(SpringTemplateLoader.class));\n return config;\n }\n\n @Bean\n public ViewResolver jadeViewResolver() {\n JadeViewResolver viewResolver = new JadeViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/jade/\");\n viewResolver.setSuffix(\".jade\");\n viewResolver.setViewNames(\"*-jade\");\n viewResolver.setRenderExceptions(true);\n viewResolver.setCache(false);\n viewResolver.setConfiguration(applicationContext.getBean(JadeConfiguration.class));\n return viewResolver;\n }\n\n @Bean\n public ViewResolver scalateViewResolver() {\n ScalateViewResolver viewResolver = new ScalateViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/scalate/\");\n viewResolver.setSuffix(\".scaml\");\n viewResolver.setViewNames(\"*-scalate\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver htmlFlowViewResolver() {\n HtmlFlowViewResolver viewResolver = new HtmlFlowViewResolver();\n viewResolver.setViewNames(\"*-htmlFlow\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver trimouViewResolver() {\n MessageSource messageSource = applicationContext.getBean(MessageSource.class);\n TrimouViewResolver viewResolver = new TrimouViewResolver(messageSource);\n viewResolver.setPrefix(\"classpath:/templates/trimou/\");\n viewResolver.setSuffix(\".trimou\");\n viewResolver.setViewNames(\"*-trimou\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver rockerViewResolver() {\n RockerViewResolver viewResolver = new RockerViewResolver();\n viewResolver.setViewNames(\"*-rocker\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver ickenhamViewResolver() {\n IckenhamViewResolver viewResolver = new IckenhamViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/ickenham/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setViewNames(\"*-ickenham\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public RythmConfigurer rythmConfigurer() {\n RythmConfigurer conf = new RythmConfigurer();\n conf.setDevMode(true);\n conf.setResourceLoaderPath(\"/WEB-INF/rythm/\");\n conf.setAutoImports(\"com.jeroenreijn.examples.model.*\");\n return conf;\n }\n\n @Bean\n public ViewResolver rythmViewResolver() {\n RythmViewResolver viewResolver = new RythmViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/rythm/\");\n viewResolver.setSuffix(\".html\");\n viewResolver.setViewNames(\"*-rythm\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public LiqpViewResolver liqpViewResolver() {\n LiqpViewResolver viewResolver = new LiqpViewResolver(applicationContext.getBean(MessageSource.class));\n viewResolver.setViewClass(LiqpView.class);\n viewResolver.setPrefix(\"classpath:./templates/liqp/\");\n viewResolver.setSuffix(\".liqp\");\n viewResolver.setViewNames(\"*-liqp\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver kotlinxHtmlViewResolver() {\n KotlinxHtmlViewResolver viewResolver = new KotlinxHtmlViewResolver();\n viewResolver.setViewNames(\"*-kotlinx\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Controller\n static class FaviconController {\n\n @RequestMapping(\"favicon.ico\")\n String favicon() {\n return \"forward:/resources/images/favicon.ico\";\n }\n }\n}\n"} {"task_id": "Java_42", "language": "Java", "task_type": "empty", "source_file": "java/github/jreijn/spring-comparing-template-engines/src/main/java/com/jeroenreijn/examples/configuration/WebMvcConfig.java", "mask_start_position": 11393, "mask_end_position": 11393, "canonical_solution": "", "pre_mask_code": "package com.jeroenreijn.examples.configuration;\n\nimport java.util.HashMap;\nimport java.util.Locale;\nimport java.util.Map;\nimport com.jeroenreijn.examples.view.*;\nimport org.fusesource.scalate.spring.view.ScalateViewResolver;\nimport org.rythmengine.spring.web.RythmConfigurer;\nimport org.rythmengine.spring.web.RythmViewResolver;\nimport org.springframework.beans.BeansException;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\nimport org.springframework.context.MessageSource;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Scope;\nimport org.springframework.context.support.ReloadableResourceBundleMessageSource;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.servlet.LocaleResolver;\nimport org.springframework.web.servlet.ViewResolver;\nimport org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;\nimport org.springframework.web.servlet.config.annotation.EnableWebMvc;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\nimport org.springframework.web.servlet.i18n.SessionLocaleResolver;\nimport org.springframework.web.servlet.view.InternalResourceViewResolver;\nimport org.springframework.web.servlet.view.JstlView;\nimport org.thymeleaf.spring5.SpringTemplateEngine;\nimport org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;\nimport org.thymeleaf.spring5.view.ThymeleafViewResolver;\nimport org.thymeleaf.templatemode.TemplateMode;\nimport com.github.enpassant.ickenham.springmvc.IckenhamViewResolver;\nimport com.github.jknack.handlebars.springmvc.HandlebarsViewResolver;\nimport com.jeroenreijn.examples.repository.InMemoryPresentationsRepository;\nimport com.jeroenreijn.examples.repository.PresentationsRepository;\nimport com.x5.template.spring.ChunkTemplateView;\nimport de.neuland.jade4j.JadeConfiguration;\nimport de.neuland.jade4j.spring.template.SpringTemplateLoader;\nimport de.neuland.jade4j.spring.view.JadeViewResolver;\nimport httl.web.springmvc.HttlViewResolver;\n\n@Configuration\n@EnableWebMvc\n@ComponentScan(basePackages = { \"com.jeroenreijn.examples.controller\", \"com.jeroenreijn.examples.factory\" })\npublic class WebMvcConfig implements ApplicationContextAware, WebMvcConfigurer {\n\n private ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n }\n\n @Override\n public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {\n configurer.enable();\n }\n\n @Override\n public void addResourceHandlers(ResourceHandlerRegistry registry) {\n registry.addResourceHandler(\"/robots.txt\").addResourceLocations(\"/robots.txt\");\n registry.addResourceHandler(\"/webjars/**\").addResourceLocations(\"/webjars/\");\n registry.addResourceHandler(\"/resources/**\").addResourceLocations(\"/resources/\");\n }\n\n @Bean\n public MessageSource messageSource() {\n ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();\n messageSource.setBasename(\"classpath:/messages\");\n messageSource.setDefaultEncoding(\"UTF-8\");\n return messageSource;\n }\n\n @Bean\n public LocaleResolver localeResolver() {\n SessionLocaleResolver slr = new SessionLocaleResolver();\n slr.setDefaultLocale(Locale.US);\n return slr;\n }\n\n @Bean\n public PresentationsRepository presentationsRepository() {\n PresentationsRepository inMemory = new InMemoryPresentationsRepository();\n return inMemory;\n }\n\n @Bean\n public SpringResourceTemplateResolver thymeleafTemplateResolver() {\n SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();\n templateResolver.setApplicationContext(this.applicationContext);\n templateResolver.setPrefix(\"/WEB-INF/thymeleaf/\");\n templateResolver.setSuffix(\".html\");\n templateResolver.setTemplateMode(TemplateMode.HTML);\n templateResolver.setCacheable(false);\n templateResolver.setCharacterEncoding(\"UTF-8\");\n return templateResolver;\n }\n\n @Bean\n public SpringTemplateEngine thymeleafTemplateEngine() {\n SpringTemplateEngine templateEngine = new SpringTemplateEngine();\n templateEngine.setTemplateResolver(thymeleafTemplateResolver());\n return templateEngine;\n }\n\n @Bean\n public ViewResolver thymeleafViewResolver() {\n ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();\n viewResolver.setViewNames(new String[] { \"*-thymeleaf\" });\n viewResolver.setTemplateEngine(thymeleafTemplateEngine());\n viewResolver.setCharacterEncoding(\"UTF-8\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver handlebarsViewResolver() {\n HandlebarsViewResolver viewResolver = new HandlebarsViewResolver();\n viewResolver.setViewNames(\"*-handlebars\");\n viewResolver.setPrefix(\"/WEB-INF/handlebars/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean(name = \"chunkTemplatesConfig\")\n @Scope(\"prototype\")\n public Map chunkTemplatesConfig() {\n Map config = new HashMap<>();\n config.put(\"default_extension\", \"chtml\");\n config.put(\"cache_minutes\", \"0\");\n config.put(\"layers\", \"\");\n config.put(\"theme_path\", \"\");\n config.put(\"hide_errors\", \"FALSE\");\n config.put(\"error_log\", \"\");\n config.put(\"encoding\", \"UTF-8\");\n config.put(\"locale\", \"\");\n config.put(\"filters\", \"\");\n return config;\n }\n\n @Bean\n public ViewResolver chunkViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(ChunkTemplateView.class);\n viewResolver.setPrefix(\"/WEB-INF/chunk/\");\n viewResolver.setViewNames(\"*-chunk\");\n viewResolver.setSuffix(\".chtml\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver jspViewResolver() {\n InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();\n viewResolver.setViewClass(JstlView.class);\n viewResolver.setPrefix(\"/WEB-INF/jsp/\");\n viewResolver.setViewNames(\"*-jsp\");\n viewResolver.setSuffix(\".jsp\");\n viewResolver.setCache(false);\n viewResolver.setRequestContextAttribute(\"rc\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver httlViewResolver() {\n HttlViewResolver viewResolver = new HttlViewResolver();\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n viewResolver.setViewNames(\"*-httl\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public SpringTemplateLoader jade4jTemplateLoader() {\n SpringTemplateLoader templateLoader = new SpringTemplateLoader();\n templateLoader.setEncoding(\"UTF-8\");\n return templateLoader;\n }\n\n @Bean\n public JadeConfiguration jadeConfiguration() {\n JadeConfiguration config = new JadeConfiguration();\n config.setPrettyPrint(true);\n config.setCaching(false);\n config.setTemplateLoader(applicationContext.getBean(SpringTemplateLoader.class));\n return config;\n }\n\n @Bean\n public ViewResolver jadeViewResolver() {\n JadeViewResolver viewResolver = new JadeViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/jade/\");\n viewResolver.setSuffix(\".jade\");\n viewResolver.setViewNames(\"*-jade\");\n viewResolver.setRenderExceptions(true);\n viewResolver.setCache(false);\n viewResolver.setConfiguration(applicationContext.getBean(JadeConfiguration.class));\n return viewResolver;\n }\n\n @Bean\n public ViewResolver scalateViewResolver() {\n ScalateViewResolver viewResolver = new ScalateViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/scalate/\");\n viewResolver.setSuffix(\".scaml\");\n viewResolver.setViewNames(\"*-scalate\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver htmlFlowViewResolver() {\n HtmlFlowViewResolver viewResolver = new HtmlFlowViewResolver();\n viewResolver.setViewNames(\"*-htmlFlow\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver trimouViewResolver() {\n MessageSource messageSource = applicationContext.getBean(MessageSource.class);\n TrimouViewResolver viewResolver = new TrimouViewResolver(messageSource);\n viewResolver.setPrefix(\"classpath:/templates/trimou/\");\n viewResolver.setSuffix(\".trimou\");\n viewResolver.setViewNames(\"*-trimou\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver rockerViewResolver() {\n RockerViewResolver viewResolver = new RockerViewResolver();\n viewResolver.setViewNames(\"*-rocker\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Bean\n public ViewResolver ickenhamViewResolver() {\n IckenhamViewResolver viewResolver = new IckenhamViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/ickenham/\");\n viewResolver.setSuffix(\".hbs\");\n viewResolver.setViewNames(\"*-ickenham\");\n viewResolver.setRequestContextAttribute(\"rc\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public RythmConfigurer rythmConfigurer() {\n RythmConfigurer conf = new RythmConfigurer();\n conf.setDevMode(true);\n conf.setResourceLoaderPath(\"/WEB-INF/rythm/\");\n conf.setAutoImports(\"com.jeroenreijn.examples.model.*\");\n return conf;\n }\n\n @Bean\n public ViewResolver rythmViewResolver() {\n RythmViewResolver viewResolver = new RythmViewResolver();\n viewResolver.setPrefix(\"/WEB-INF/rythm/\");\n viewResolver.setSuffix(\".html\");\n viewResolver.setViewNames(\"*-rythm\");\n viewResolver.setCache(false);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public LiqpViewResolver liqpViewResolver() {\n LiqpViewResolver viewResolver = new LiqpViewResolver(applicationContext.getBean(MessageSource.class));\n viewResolver.setViewClass(LiqpView.class);\n viewResolver.setPrefix(\"classpath:./templates/liqp/\");\n viewResolver.setSuffix(\".liqp\");\n viewResolver.setViewNames(\"*-liqp\");\n viewResolver.setCache(fal", "post_mask_code": "se);\n viewResolver.setContentType(\"text/html;charset=UTF-8\");\n return viewResolver;\n }\n\n @Bean\n public ViewResolver kotlinxHtmlViewResolver() {\n KotlinxHtmlViewResolver viewResolver = new KotlinxHtmlViewResolver();\n viewResolver.setViewNames(\"*-kotlinx\");\n viewResolver.setCache(false);\n return viewResolver;\n }\n\n @Controller\n static class FaviconController {\n\n @RequestMapping(\"favicon.ico\")\n String favicon() {\n return \"forward:/resources/images/favicon.ico\";\n }\n }\n}\n"} {"task_id": "Java_43", "language": "Java", "task_type": "method_signature", "source_file": "java/github/PacktPublishing/JIRA-Development-Cookbook-Third-Edition/Chapter 9/rest-plugin/src/main/java/com/jtricks/rest/CategoryResource.java", "mask_start_position": 1805, "mask_end_position": 2013, "canonical_solution": "@GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n @Path(\"/{id}\")\n public Response getCategoryFromId(@PathParam(\"id\") String id) throws SearchException ", "pre_mask_code": "package com.jtricks.rest;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.QueryParam;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport com.atlassian.jira.issue.search.SearchException;\nimport com.atlassian.jira.project.ProjectCategory;\nimport com.atlassian.jira.project.ProjectManager;\nimport com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;\nimport com.atlassian.plugins.rest.common.security.AnonymousAllowed;\n\n@Path(\"/category\")\n@Named\npublic class CategoryResource {\n\n private final ProjectManager projectManager;\n\n @Inject\n public CategoryResource(@ComponentImport ProjectManager projectManager) {\n this.projectManager = projectManager;\n }\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n public Response getCategories(@QueryParam(\"dummyParam\") String dummyParam) throws SearchException {\n System.out.println(\"This is just a dummyParam to show how parameters can be passed to REST methods:\" + dummyParam);\n Collection categories = this.projectManager.getAllProjectCategories();\n List categoryList = new ArrayList();\n for (ProjectCategory category : categories) {\n categoryList.add(new Category(category.getId(), category.getName()));\n }\n Response.ResponseBuilder responseBuilder = Response.ok(new Categories(categoryList));\n return responseBuilder.build();\n }\n\n ", "post_mask_code": "{\n ProjectCategory category = this.projectManager.getProjectCategoryObject(new Long(id));\n Response.ResponseBuilder responseBuilder = Response.ok(new Category(category.getId(), category.getName()));\n return responseBuilder.build();\n }\n\n @XmlRootElement\n public static class Category {\n\n @XmlElement\n private Long id;\n\n @XmlElement\n private String name;\n\n public Category() {\n }\n\n public Category(Long id, String name) {\n this.id = id;\n this.name = name;\n }\n }\n\n @XmlRootElement\n public static class Categories {\n\n @XmlElement\n private List categories;\n\n public Categories() {\n }\n\n public Categories(List categories) {\n this.categories = categories;\n }\n }\n}\n"} {"task_id": "Java_44", "language": "Java", "task_type": "method_body", "source_file": "java/github/PacktPublishing/JIRA-Development-Cookbook-Third-Edition/Chapter 9/rest-plugin/src/main/java/com/jtricks/rest/CategoryResource.java", "mask_start_position": 2013, "mask_end_position": 2271, "canonical_solution": "{\n ProjectCategory category = this.projectManager.getProjectCategoryObject(new Long(id));\n Response.ResponseBuilder responseBuilder = Response.ok(new Category(category.getId(), category.getName()));\n return responseBuilder.build();\n }", "pre_mask_code": "package com.jtricks.rest;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.QueryParam;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport com.atlassian.jira.issue.search.SearchException;\nimport com.atlassian.jira.project.ProjectCategory;\nimport com.atlassian.jira.project.ProjectManager;\nimport com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;\nimport com.atlassian.plugins.rest.common.security.AnonymousAllowed;\n\n@Path(\"/category\")\n@Named\npublic class CategoryResource {\n\n private final ProjectManager projectManager;\n\n @Inject\n public CategoryResource(@ComponentImport ProjectManager projectManager) {\n this.projectManager = projectManager;\n }\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n public Response getCategories(@QueryParam(\"dummyParam\") String dummyParam) throws SearchException {\n System.out.println(\"This is just a dummyParam to show how parameters can be passed to REST methods:\" + dummyParam);\n Collection categories = this.projectManager.getAllProjectCategories();\n List categoryList = new ArrayList();\n for (ProjectCategory category : categories) {\n categoryList.add(new Category(category.getId(), category.getName()));\n }\n Response.ResponseBuilder responseBuilder = Response.ok(new Categories(categoryList));\n return responseBuilder.build();\n }\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n @Path(\"/{id}\")\n public Response getCategoryFromId(@PathParam(\"id\") String id) throws SearchException ", "post_mask_code": "\n\n @XmlRootElement\n public static class Category {\n\n @XmlElement\n private Long id;\n\n @XmlElement\n private String name;\n\n public Category() {\n }\n\n public Category(Long id, String name) {\n this.id = id;\n this.name = name;\n }\n }\n\n @XmlRootElement\n public static class Categories {\n\n @XmlElement\n private List categories;\n\n public Categories() {\n }\n\n public Categories(List categories) {\n this.categories = categories;\n }\n }\n}\n"} {"task_id": "Java_45", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/PacktPublishing/JIRA-Development-Cookbook-Third-Edition/Chapter 9/rest-plugin/src/main/java/com/jtricks/rest/CategoryResource.java", "mask_start_position": 1228, "mask_end_position": 1448, "canonical_solution": "\n System.out.println(\"This is just a dummyParam to show how parameters can be passed to REST methods:\" + dummyParam);\n Collection categories = this.projectManager.getAllProjectCategories();", "pre_mask_code": "package com.jtricks.rest;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.QueryParam;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport com.atlassian.jira.issue.search.SearchException;\nimport com.atlassian.jira.project.ProjectCategory;\nimport com.atlassian.jira.project.ProjectManager;\nimport com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;\nimport com.atlassian.plugins.rest.common.security.AnonymousAllowed;\n\n@Path(\"/category\")\n@Named\npublic class CategoryResource {\n\n private final ProjectManager projectManager;\n\n @Inject\n public CategoryResource(@ComponentImport ProjectManager projectManager) {\n this.projectManager = projectManager;\n }\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n public Response getCategories(@QueryParam(\"dummyParam\") String dummyParam) throws SearchException {", "post_mask_code": "\n List categoryList = new ArrayList();\n for (ProjectCategory category : categories) {\n categoryList.add(new Category(category.getId(), category.getName()));\n }\n Response.ResponseBuilder responseBuilder = Response.ok(new Categories(categoryList));\n return responseBuilder.build();\n }\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n @Path(\"/{id}\")\n public Response getCategoryFromId(@PathParam(\"id\") String id) throws SearchException {\n ProjectCategory category = this.projectManager.getProjectCategoryObject(new Long(id));\n Response.ResponseBuilder responseBuilder = Response.ok(new Category(category.getId(), category.getName()));\n return responseBuilder.build();\n }\n\n @XmlRootElement\n public static class Category {\n\n @XmlElement\n private Long id;\n\n @XmlElement\n private String name;\n\n public Category() {\n }\n\n public Category(Long id, String name) {\n this.id = id;\n this.name = name;\n }\n }\n\n @XmlRootElement\n public static class Categories {\n\n @XmlElement\n private List categories;\n\n public Categories() {\n }\n\n public Categories(List categories) {\n this.categories = categories;\n }\n }\n}\n"} {"task_id": "Java_46", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/PacktPublishing/JIRA-Development-Cookbook-Third-Edition/Chapter 9/rest-plugin/src/main/java/com/jtricks/rest/CategoryResource.java", "mask_start_position": 1457, "mask_end_position": 1659, "canonical_solution": "List categoryList = new ArrayList();\n for (ProjectCategory category : categories) {\n categoryList.add(new Category(category.getId(), category.getName()));\n }", "pre_mask_code": "package com.jtricks.rest;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.QueryParam;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport com.atlassian.jira.issue.search.SearchException;\nimport com.atlassian.jira.project.ProjectCategory;\nimport com.atlassian.jira.project.ProjectManager;\nimport com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;\nimport com.atlassian.plugins.rest.common.security.AnonymousAllowed;\n\n@Path(\"/category\")\n@Named\npublic class CategoryResource {\n\n private final ProjectManager projectManager;\n\n @Inject\n public CategoryResource(@ComponentImport ProjectManager projectManager) {\n this.projectManager = projectManager;\n }\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n public Response getCategories(@QueryParam(\"dummyParam\") String dummyParam) throws SearchException {\n System.out.println(\"This is just a dummyParam to show how parameters can be passed to REST methods:\" + dummyParam);\n Collection categories = this.projectManager.getAllProjectCategories();\n ", "post_mask_code": "\n Response.ResponseBuilder responseBuilder = Response.ok(new Categories(categoryList));\n return responseBuilder.build();\n }\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n @Path(\"/{id}\")\n public Response getCategoryFromId(@PathParam(\"id\") String id) throws SearchException {\n ProjectCategory category = this.projectManager.getProjectCategoryObject(new Long(id));\n Response.ResponseBuilder responseBuilder = Response.ok(new Category(category.getId(), category.getName()));\n return responseBuilder.build();\n }\n\n @XmlRootElement\n public static class Category {\n\n @XmlElement\n private Long id;\n\n @XmlElement\n private String name;\n\n public Category() {\n }\n\n public Category(Long id, String name) {\n this.id = id;\n this.name = name;\n }\n }\n\n @XmlRootElement\n public static class Categories {\n\n @XmlElement\n private List categories;\n\n public Categories() {\n }\n\n public Categories(List categories) {\n this.categories = categories;\n }\n }\n}\n"} {"task_id": "Java_47", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/PacktPublishing/JIRA-Development-Cookbook-Third-Edition/Chapter 9/rest-plugin/src/main/java/com/jtricks/rest/CategoryResource.java", "mask_start_position": 1668, "mask_end_position": 1799, "canonical_solution": "Response.ResponseBuilder responseBuilder = Response.ok(new Categories(categoryList));\n return responseBuilder.build();\n }", "pre_mask_code": "package com.jtricks.rest;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.QueryParam;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport com.atlassian.jira.issue.search.SearchException;\nimport com.atlassian.jira.project.ProjectCategory;\nimport com.atlassian.jira.project.ProjectManager;\nimport com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;\nimport com.atlassian.plugins.rest.common.security.AnonymousAllowed;\n\n@Path(\"/category\")\n@Named\npublic class CategoryResource {\n\n private final ProjectManager projectManager;\n\n @Inject\n public CategoryResource(@ComponentImport ProjectManager projectManager) {\n this.projectManager = projectManager;\n }\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n public Response getCategories(@QueryParam(\"dummyParam\") String dummyParam) throws SearchException {\n System.out.println(\"This is just a dummyParam to show how parameters can be passed to REST methods:\" + dummyParam);\n Collection categories = this.projectManager.getAllProjectCategories();\n List categoryList = new ArrayList();\n for (ProjectCategory category : categories) {\n categoryList.add(new Category(category.getId(), category.getName()));\n }\n ", "post_mask_code": "\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n @Path(\"/{id}\")\n public Response getCategoryFromId(@PathParam(\"id\") String id) throws SearchException {\n ProjectCategory category = this.projectManager.getProjectCategoryObject(new Long(id));\n Response.ResponseBuilder responseBuilder = Response.ok(new Category(category.getId(), category.getName()));\n return responseBuilder.build();\n }\n\n @XmlRootElement\n public static class Category {\n\n @XmlElement\n private Long id;\n\n @XmlElement\n private String name;\n\n public Category() {\n }\n\n public Category(Long id, String name) {\n this.id = id;\n this.name = name;\n }\n }\n\n @XmlRootElement\n public static class Categories {\n\n @XmlElement\n private List categories;\n\n public Categories() {\n }\n\n public Categories(List categories) {\n this.categories = categories;\n }\n }\n}\n"} {"task_id": "Java_48", "language": "Java", "task_type": "single_line", "source_file": "java/github/PacktPublishing/JIRA-Development-Cookbook-Third-Edition/Chapter 9/rest-plugin/src/main/java/com/jtricks/rest/CategoryResource.java", "mask_start_position": 2249, "mask_end_position": 2265, "canonical_solution": "Builder.build();", "pre_mask_code": "package com.jtricks.rest;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.QueryParam;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport com.atlassian.jira.issue.search.SearchException;\nimport com.atlassian.jira.project.ProjectCategory;\nimport com.atlassian.jira.project.ProjectManager;\nimport com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;\nimport com.atlassian.plugins.rest.common.security.AnonymousAllowed;\n\n@Path(\"/category\")\n@Named\npublic class CategoryResource {\n\n private final ProjectManager projectManager;\n\n @Inject\n public CategoryResource(@ComponentImport ProjectManager projectManager) {\n this.projectManager = projectManager;\n }\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n public Response getCategories(@QueryParam(\"dummyParam\") String dummyParam) throws SearchException {\n System.out.println(\"This is just a dummyParam to show how parameters can be passed to REST methods:\" + dummyParam);\n Collection categories = this.projectManager.getAllProjectCategories();\n List categoryList = new ArrayList();\n for (ProjectCategory category : categories) {\n categoryList.add(new Category(category.getId(), category.getName()));\n }\n Response.ResponseBuilder responseBuilder = Response.ok(new Categories(categoryList));\n return responseBuilder.build();\n }\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n @Path(\"/{id}\")\n public Response getCategoryFromId(@PathParam(\"id\") String id) throws SearchException {\n ProjectCategory category = this.projectManager.getProjectCategoryObject(new Long(id));\n Response.ResponseBuilder responseBuilder = Response.ok(new Category(category.getId(), category.getName()));\n return response", "post_mask_code": "\n }\n\n @XmlRootElement\n public static class Category {\n\n @XmlElement\n private Long id;\n\n @XmlElement\n private String name;\n\n public Category() {\n }\n\n public Category(Long id, String name) {\n this.id = id;\n this.name = name;\n }\n }\n\n @XmlRootElement\n public static class Categories {\n\n @XmlElement\n private List categories;\n\n public Categories() {\n }\n\n public Categories(List categories) {\n this.categories = categories;\n }\n }\n}\n"} {"task_id": "Java_49", "language": "Java", "task_type": "empty", "source_file": "java/github/PacktPublishing/JIRA-Development-Cookbook-Third-Edition/Chapter 9/rest-plugin/src/main/java/com/jtricks/rest/CategoryResource.java", "mask_start_position": 921, "mask_end_position": 921, "canonical_solution": "", "pre_mask_code": "package com.jtricks.rest;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport javax.inject.Inject;\nimport javax.inject.Named;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.QueryParam;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport com.atlassian.jira.issue.search.SearchException;\nimport com.atlassian.jira.project.ProjectCategory;\nimport com.atlassian.jira.project.ProjectManager;\nimport com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;\nimport com.atlassian.plugins.rest.common.security.AnonymousAllowed;\n\n@Path(\"/category\")\n@Named\npublic class CategoryResource {\n\n private final ProjectManager projectManager;\n\n @Inject\n public CategoryResource(@Co", "post_mask_code": "mponentImport ProjectManager projectManager) {\n this.projectManager = projectManager;\n }\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n public Response getCategories(@QueryParam(\"dummyParam\") String dummyParam) throws SearchException {\n System.out.println(\"This is just a dummyParam to show how parameters can be passed to REST methods:\" + dummyParam);\n Collection categories = this.projectManager.getAllProjectCategories();\n List categoryList = new ArrayList();\n for (ProjectCategory category : categories) {\n categoryList.add(new Category(category.getId(), category.getName()));\n }\n Response.ResponseBuilder responseBuilder = Response.ok(new Categories(categoryList));\n return responseBuilder.build();\n }\n\n @GET\n @AnonymousAllowed\n @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })\n @Path(\"/{id}\")\n public Response getCategoryFromId(@PathParam(\"id\") String id) throws SearchException {\n ProjectCategory category = this.projectManager.getProjectCategoryObject(new Long(id));\n Response.ResponseBuilder responseBuilder = Response.ok(new Category(category.getId(), category.getName()));\n return responseBuilder.build();\n }\n\n @XmlRootElement\n public static class Category {\n\n @XmlElement\n private Long id;\n\n @XmlElement\n private String name;\n\n public Category() {\n }\n\n public Category(Long id, String name) {\n this.id = id;\n this.name = name;\n }\n }\n\n @XmlRootElement\n public static class Categories {\n\n @XmlElement\n private List categories;\n\n public Categories() {\n }\n\n public Categories(List categories) {\n this.categories = categories;\n }\n }\n}\n"} {"task_id": "Java_50", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/cayenne/cayenne-xmpp/src/main/java/org/apache/cayenne/event/XMPPModule.java", "mask_start_position": 1047, "mask_end_position": 1123, "canonical_solution": "public static void contributeChatService(Binder binder, String chatService) ", "pre_mask_code": "package org.apache.cayenne.event;\n\nimport org.apache.cayenne.di.Binder;\nimport org.apache.cayenne.di.MapBuilder;\nimport org.apache.cayenne.di.Module;\n\npublic class XMPPModule implements Module {\n\n /**\n * A DI container key for the Map<String, String> storing\n * {@link org.apache.cayenne.event.XMPPBridge} properties\n *\n * @since 4.0\n */\n public static final String XMPP_BRIDGE_PROPERTIES_MAP = \"cayenne.server.xmpp_bridge\";\n\n public static void contributeHost(Binder binder, String host) {\n contributeProperties(binder).put(XMPPBridge.XMPP_HOST_PROPERTY, host);\n }\n\n public static void contributePort(Binder binder, int port) {\n contributeProperties(binder).put(XMPPBridge.XMPP_PORT_PROPERTY, Integer.toString(port));\n }\n\n public static void contributeLogin(Binder binder, String login, String password) {\n contributeProperties(binder).put(XMPPBridge.XMPP_LOGIN_PROPERTY, login);\n contributeProperties(binder).put(XMPPBridge.XMPP_PASSWORD_PROPERTY, password);\n }\n\n ", "post_mask_code": "{\n contributeProperties(binder).put(XMPPBridge.XMPP_CHAT_SERVICE_PROPERTY, chatService);\n }\n\n public static void contributeSecureConnection(Binder binder, boolean secure) {\n contributeProperties(binder).put(XMPPBridge.XMPP_SECURE_CONNECTION_PROPERTY, Boolean.toString(secure));\n }\n\n private static MapBuilder contributeProperties(Binder binder) {\n return binder.bindMap(String.class, XMPP_BRIDGE_PROPERTIES_MAP);\n }\n\n @Override\n public void configure(Binder binder) {\n // init properties' defaults\n contributeChatService(binder, XMPPBridge.DEFAULT_CHAT_SERVICE);\n binder.bind(EventBridge.class).toProvider(XMPPBridgeProvider.class).withoutScope();\n }\n}\n"} {"task_id": "Java_51", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/cayenne/cayenne-xmpp/src/main/java/org/apache/cayenne/event/XMPPModule.java", "mask_start_position": 1639, "mask_end_position": 1847, "canonical_solution": "{\n // init properties' defaults\n contributeChatService(binder, XMPPBridge.DEFAULT_CHAT_SERVICE);\n binder.bind(EventBridge.class).toProvider(XMPPBridgeProvider.class).withoutScope();\n }", "pre_mask_code": "package org.apache.cayenne.event;\n\nimport org.apache.cayenne.di.Binder;\nimport org.apache.cayenne.di.MapBuilder;\nimport org.apache.cayenne.di.Module;\n\npublic class XMPPModule implements Module {\n\n /**\n * A DI container key for the Map<String, String> storing\n * {@link org.apache.cayenne.event.XMPPBridge} properties\n *\n * @since 4.0\n */\n public static final String XMPP_BRIDGE_PROPERTIES_MAP = \"cayenne.server.xmpp_bridge\";\n\n public static void contributeHost(Binder binder, String host) {\n contributeProperties(binder).put(XMPPBridge.XMPP_HOST_PROPERTY, host);\n }\n\n public static void contributePort(Binder binder, int port) {\n contributeProperties(binder).put(XMPPBridge.XMPP_PORT_PROPERTY, Integer.toString(port));\n }\n\n public static void contributeLogin(Binder binder, String login, String password) {\n contributeProperties(binder).put(XMPPBridge.XMPP_LOGIN_PROPERTY, login);\n contributeProperties(binder).put(XMPPBridge.XMPP_PASSWORD_PROPERTY, password);\n }\n\n public static void contributeChatService(Binder binder, String chatService) {\n contributeProperties(binder).put(XMPPBridge.XMPP_CHAT_SERVICE_PROPERTY, chatService);\n }\n\n public static void contributeSecureConnection(Binder binder, boolean secure) {\n contributeProperties(binder).put(XMPPBridge.XMPP_SECURE_CONNECTION_PROPERTY, Boolean.toString(secure));\n }\n\n private static MapBuilder contributeProperties(Binder binder) {\n return binder.bindMap(String.class, XMPP_BRIDGE_PROPERTIES_MAP);\n }\n\n @Override\n public void configure(Binder binder) ", "post_mask_code": "\n}\n"} {"task_id": "Java_52", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/cayenne/cayenne-xmpp/src/main/java/org/apache/cayenne/event/XMPPModule.java", "mask_start_position": 1739, "mask_end_position": 1749, "canonical_solution": "_SERVICE);", "pre_mask_code": "package org.apache.cayenne.event;\n\nimport org.apache.cayenne.di.Binder;\nimport org.apache.cayenne.di.MapBuilder;\nimport org.apache.cayenne.di.Module;\n\npublic class XMPPModule implements Module {\n\n /**\n * A DI container key for the Map<String, String> storing\n * {@link org.apache.cayenne.event.XMPPBridge} properties\n *\n * @since 4.0\n */\n public static final String XMPP_BRIDGE_PROPERTIES_MAP = \"cayenne.server.xmpp_bridge\";\n\n public static void contributeHost(Binder binder, String host) {\n contributeProperties(binder).put(XMPPBridge.XMPP_HOST_PROPERTY, host);\n }\n\n public static void contributePort(Binder binder, int port) {\n contributeProperties(binder).put(XMPPBridge.XMPP_PORT_PROPERTY, Integer.toString(port));\n }\n\n public static void contributeLogin(Binder binder, String login, String password) {\n contributeProperties(binder).put(XMPPBridge.XMPP_LOGIN_PROPERTY, login);\n contributeProperties(binder).put(XMPPBridge.XMPP_PASSWORD_PROPERTY, password);\n }\n\n public static void contributeChatService(Binder binder, String chatService) {\n contributeProperties(binder).put(XMPPBridge.XMPP_CHAT_SERVICE_PROPERTY, chatService);\n }\n\n public static void contributeSecureConnection(Binder binder, boolean secure) {\n contributeProperties(binder).put(XMPPBridge.XMPP_SECURE_CONNECTION_PROPERTY, Boolean.toString(secure));\n }\n\n private static MapBuilder contributeProperties(Binder binder) {\n return binder.bindMap(String.class, XMPP_BRIDGE_PROPERTIES_MAP);\n }\n\n @Override\n public void configure(Binder binder) {\n // init properties' defaults\n contributeChatService(binder, XMPPBridge.DEFAULT_CHAT", "post_mask_code": "\n binder.bind(EventBridge.class).toProvider(XMPPBridgeProvider.class).withoutScope();\n }\n}\n"} {"task_id": "Java_53", "language": "Java", "task_type": "empty", "source_file": "java/github/apache/cayenne/cayenne-xmpp/src/main/java/org/apache/cayenne/event/XMPPModule.java", "mask_start_position": 861, "mask_end_position": 861, "canonical_solution": "", "pre_mask_code": "package org.apache.cayenne.event;\n\nimport org.apache.cayenne.di.Binder;\nimport org.apache.cayenne.di.MapBuilder;\nimport org.apache.cayenne.di.Module;\n\npublic class XMPPModule implements Module {\n\n /**\n * A DI container key for the Map<String, String> storing\n * {@link org.apache.cayenne.event.XMPPBridge} properties\n *\n * @since 4.0\n */\n public static final String XMPP_BRIDGE_PROPERTIES_MAP = \"cayenne.server.xmpp_bridge\";\n\n public static void contributeHost(Binder binder, String host) {\n contributeProperties(binder).put(XMPPBridge.XMPP_HOST_PROPERTY, host);\n }\n\n public static void contributePort(Binder binder, int port) {\n contributeProperties(binder).put(XMPPBridge.XMPP_PORT_PROPERTY, Integer.toString(port));\n }\n\n public static void contributeLogin(Binder binder, String login, String passw", "post_mask_code": "ord) {\n contributeProperties(binder).put(XMPPBridge.XMPP_LOGIN_PROPERTY, login);\n contributeProperties(binder).put(XMPPBridge.XMPP_PASSWORD_PROPERTY, password);\n }\n\n public static void contributeChatService(Binder binder, String chatService) {\n contributeProperties(binder).put(XMPPBridge.XMPP_CHAT_SERVICE_PROPERTY, chatService);\n }\n\n public static void contributeSecureConnection(Binder binder, boolean secure) {\n contributeProperties(binder).put(XMPPBridge.XMPP_SECURE_CONNECTION_PROPERTY, Boolean.toString(secure));\n }\n\n private static MapBuilder contributeProperties(Binder binder) {\n return binder.bindMap(String.class, XMPP_BRIDGE_PROPERTIES_MAP);\n }\n\n @Override\n public void configure(Binder binder) {\n // init properties' defaults\n contributeChatService(binder, XMPPBridge.DEFAULT_CHAT_SERVICE);\n binder.bind(EventBridge.class).toProvider(XMPPBridgeProvider.class).withoutScope();\n }\n}\n"} {"task_id": "Java_54", "language": "Java", "task_type": "method_signature", "source_file": "java/github/USC-CSSL/TACIT/edu.usc.cssl.tacit.topicmodel.onlinelda/src/edu/usc/cssl/tacit/topicmodel/onlinelda/services/OnlineLDAOutput.java", "mask_start_position": 3155, "mask_end_position": 3250, "canonical_solution": "public static > Map reverseSortByValue(Map map) ", "pre_mask_code": "package edu.usc.cssl.tacit.topicmodel.onlinelda.services;\n\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Matrix;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.LinearArray;\nimport edu.usc.cssl.tacit.common.ui.views.ConsoleView;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Documents;\nimport java.io.PrintWriter;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.util.*;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\n\n/*\n * An encapsulating class to hold the results of updateLambda method in the OnlineLda class\n */\npublic class OnlineLDAOutput {\n\n private final Matrix lambda;\n\n private final Matrix gamma;\n\n private final double perplexity;\n\n private final Documents documents;\n\n private final int totalWordCount;\n\n private final int D;\n\n final static NumberFormat NF = new DecimalFormat(\"##.####\");\n\n public OnlineLDAOutput(Matrix lambda, Matrix gamma, double bound, Documents docs, int D) {\n this.D = D;\n this.lambda = lambda;\n this.gamma = gamma;\n this.documents = docs;\n this.totalWordCount = docs.getWordCount();\n double perWordBound = (bound * docs.size()) / (D * totalWordCount);\n this.perplexity = Math.exp(-perWordBound);\n System.out.println(\"Perplexity: \" + perplexity);\n ConsoleView.printlInConsoleln(\"Perplexity: \" + perplexity);\n }\n\n public void printTopics(PrintWriter p1, PrintWriter p2, ArrayList dList, Vocabulary v, int wordsPerTopic, IProgressMonitor monitor) {\n int[][] topicWords = new int[lambda.numOfRows()][wordsPerTopic];\n for (int k = 0; k < lambda.numOfRows(); k++) {\n monitor.subTask(\"Writing Topic \" + k);\n p2.println(\"Topic \" + k);\n ConsoleView.printlInConsoleln(\"Topic \" + k);\n int num = 0;\n LinearArray lambdak = lambda.getRow(k);\n lambdak = lambdak.div(lambdak.sum());\n for (int i = 0; i < lambdak.size(); i++) {\n p1.print(lambdak.values[i] + \" \");\n }\n p1.print(\"\\n\");\n HashMap topicWordsWts = new HashMap();\n for (int i = 0; i < lambdak.size(); i++) {\n double value = lambdak.values[i];\n topicWordsWts.put(i, value);\n }\n Map results = reverseSortByValue(topicWordsWts);\n Iterator i = results.entrySet().iterator();\n while (i.hasNext() && num < wordsPerTopic) {\n Map.Entry me = (Map.Entry) i.next();\n int y = (int) me.getKey();\n p2.print(v.getToken(y) + \"=\" + me.getValue());\n p2.print(\"\\n\");\n ConsoleView.printlInConsoleln(v.getToken(y) + \"=\" + me.getValue());\n num++;\n }\n ConsoleView.printlInConsoleln();\n monitor.worked(50);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n }\n p1.close();\n p2.close();\n }\n\n ", "post_mask_code": "{\n List> list = new LinkedList<>(map.entrySet());\n Collections.sort(list, new Comparator>() {\n\n @Override\n public int compare(Map.Entry e1, Map.Entry e2) {\n return -(e1.getValue()).compareTo(e2.getValue());\n }\n });\n Map result = new LinkedHashMap<>();\n for (Map.Entry entry : list) {\n result.put(entry.getKey(), entry.getValue());\n }\n return result;\n }\n}\n"} {"task_id": "Java_55", "language": "Java", "task_type": "method_body", "source_file": "java/github/USC-CSSL/TACIT/edu.usc.cssl.tacit.topicmodel.onlinelda/src/edu/usc/cssl/tacit/topicmodel/onlinelda/services/OnlineLDAOutput.java", "mask_start_position": 3484, "mask_end_position": 3565, "canonical_solution": "{\n return -(e1.getValue()).compareTo(e2.getValue());\n }", "pre_mask_code": "package edu.usc.cssl.tacit.topicmodel.onlinelda.services;\n\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Matrix;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.LinearArray;\nimport edu.usc.cssl.tacit.common.ui.views.ConsoleView;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Documents;\nimport java.io.PrintWriter;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.util.*;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\n\n/*\n * An encapsulating class to hold the results of updateLambda method in the OnlineLda class\n */\npublic class OnlineLDAOutput {\n\n private final Matrix lambda;\n\n private final Matrix gamma;\n\n private final double perplexity;\n\n private final Documents documents;\n\n private final int totalWordCount;\n\n private final int D;\n\n final static NumberFormat NF = new DecimalFormat(\"##.####\");\n\n public OnlineLDAOutput(Matrix lambda, Matrix gamma, double bound, Documents docs, int D) {\n this.D = D;\n this.lambda = lambda;\n this.gamma = gamma;\n this.documents = docs;\n this.totalWordCount = docs.getWordCount();\n double perWordBound = (bound * docs.size()) / (D * totalWordCount);\n this.perplexity = Math.exp(-perWordBound);\n System.out.println(\"Perplexity: \" + perplexity);\n ConsoleView.printlInConsoleln(\"Perplexity: \" + perplexity);\n }\n\n public void printTopics(PrintWriter p1, PrintWriter p2, ArrayList dList, Vocabulary v, int wordsPerTopic, IProgressMonitor monitor) {\n int[][] topicWords = new int[lambda.numOfRows()][wordsPerTopic];\n for (int k = 0; k < lambda.numOfRows(); k++) {\n monitor.subTask(\"Writing Topic \" + k);\n p2.println(\"Topic \" + k);\n ConsoleView.printlInConsoleln(\"Topic \" + k);\n int num = 0;\n LinearArray lambdak = lambda.getRow(k);\n lambdak = lambdak.div(lambdak.sum());\n for (int i = 0; i < lambdak.size(); i++) {\n p1.print(lambdak.values[i] + \" \");\n }\n p1.print(\"\\n\");\n HashMap topicWordsWts = new HashMap();\n for (int i = 0; i < lambdak.size(); i++) {\n double value = lambdak.values[i];\n topicWordsWts.put(i, value);\n }\n Map results = reverseSortByValue(topicWordsWts);\n Iterator i = results.entrySet().iterator();\n while (i.hasNext() && num < wordsPerTopic) {\n Map.Entry me = (Map.Entry) i.next();\n int y = (int) me.getKey();\n p2.print(v.getToken(y) + \"=\" + me.getValue());\n p2.print(\"\\n\");\n ConsoleView.printlInConsoleln(v.getToken(y) + \"=\" + me.getValue());\n num++;\n }\n ConsoleView.printlInConsoleln();\n monitor.worked(50);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n }\n p1.close();\n p2.close();\n }\n\n public static > Map reverseSortByValue(Map map) {\n List> list = new LinkedList<>(map.entrySet());\n Collections.sort(list, new Comparator>() {\n\n @Override\n public int compare(Map.Entry e1, Map.Entry e2) ", "post_mask_code": "\n });\n Map result = new LinkedHashMap<>();\n for (Map.Entry entry : list) {\n result.put(entry.getKey(), entry.getValue());\n }\n return result;\n }\n}\n"} {"task_id": "Java_56", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/USC-CSSL/TACIT/edu.usc.cssl.tacit.topicmodel.onlinelda/src/edu/usc/cssl/tacit/topicmodel/onlinelda/services/OnlineLDAOutput.java", "mask_start_position": 3251, "mask_end_position": 3577, "canonical_solution": "\n List> list = new LinkedList<>(map.entrySet());\n Collections.sort(list, new Comparator>() {\n\n @Override\n public int compare(Map.Entry e1, Map.Entry e2) {\n return -(e1.getValue()).compareTo(e2.getValue());\n }\n });", "pre_mask_code": "package edu.usc.cssl.tacit.topicmodel.onlinelda.services;\n\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Matrix;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.LinearArray;\nimport edu.usc.cssl.tacit.common.ui.views.ConsoleView;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Documents;\nimport java.io.PrintWriter;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.util.*;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\n\n/*\n * An encapsulating class to hold the results of updateLambda method in the OnlineLda class\n */\npublic class OnlineLDAOutput {\n\n private final Matrix lambda;\n\n private final Matrix gamma;\n\n private final double perplexity;\n\n private final Documents documents;\n\n private final int totalWordCount;\n\n private final int D;\n\n final static NumberFormat NF = new DecimalFormat(\"##.####\");\n\n public OnlineLDAOutput(Matrix lambda, Matrix gamma, double bound, Documents docs, int D) {\n this.D = D;\n this.lambda = lambda;\n this.gamma = gamma;\n this.documents = docs;\n this.totalWordCount = docs.getWordCount();\n double perWordBound = (bound * docs.size()) / (D * totalWordCount);\n this.perplexity = Math.exp(-perWordBound);\n System.out.println(\"Perplexity: \" + perplexity);\n ConsoleView.printlInConsoleln(\"Perplexity: \" + perplexity);\n }\n\n public void printTopics(PrintWriter p1, PrintWriter p2, ArrayList dList, Vocabulary v, int wordsPerTopic, IProgressMonitor monitor) {\n int[][] topicWords = new int[lambda.numOfRows()][wordsPerTopic];\n for (int k = 0; k < lambda.numOfRows(); k++) {\n monitor.subTask(\"Writing Topic \" + k);\n p2.println(\"Topic \" + k);\n ConsoleView.printlInConsoleln(\"Topic \" + k);\n int num = 0;\n LinearArray lambdak = lambda.getRow(k);\n lambdak = lambdak.div(lambdak.sum());\n for (int i = 0; i < lambdak.size(); i++) {\n p1.print(lambdak.values[i] + \" \");\n }\n p1.print(\"\\n\");\n HashMap topicWordsWts = new HashMap();\n for (int i = 0; i < lambdak.size(); i++) {\n double value = lambdak.values[i];\n topicWordsWts.put(i, value);\n }\n Map results = reverseSortByValue(topicWordsWts);\n Iterator i = results.entrySet().iterator();\n while (i.hasNext() && num < wordsPerTopic) {\n Map.Entry me = (Map.Entry) i.next();\n int y = (int) me.getKey();\n p2.print(v.getToken(y) + \"=\" + me.getValue());\n p2.print(\"\\n\");\n ConsoleView.printlInConsoleln(v.getToken(y) + \"=\" + me.getValue());\n num++;\n }\n ConsoleView.printlInConsoleln();\n monitor.worked(50);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n }\n p1.close();\n p2.close();\n }\n\n public static > Map reverseSortByValue(Map map) {", "post_mask_code": "\n Map result = new LinkedHashMap<>();\n for (Map.Entry entry : list) {\n result.put(entry.getKey(), entry.getValue());\n }\n return result;\n }\n}\n"} {"task_id": "Java_57", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/USC-CSSL/TACIT/edu.usc.cssl.tacit.topicmodel.onlinelda/src/edu/usc/cssl/tacit/topicmodel/onlinelda/services/OnlineLDAOutput.java", "mask_start_position": 3586, "mask_end_position": 3740, "canonical_solution": "Map result = new LinkedHashMap<>();\n for (Map.Entry entry : list) {\n result.put(entry.getKey(), entry.getValue());\n }", "pre_mask_code": "package edu.usc.cssl.tacit.topicmodel.onlinelda.services;\n\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Matrix;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.LinearArray;\nimport edu.usc.cssl.tacit.common.ui.views.ConsoleView;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Documents;\nimport java.io.PrintWriter;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.util.*;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\n\n/*\n * An encapsulating class to hold the results of updateLambda method in the OnlineLda class\n */\npublic class OnlineLDAOutput {\n\n private final Matrix lambda;\n\n private final Matrix gamma;\n\n private final double perplexity;\n\n private final Documents documents;\n\n private final int totalWordCount;\n\n private final int D;\n\n final static NumberFormat NF = new DecimalFormat(\"##.####\");\n\n public OnlineLDAOutput(Matrix lambda, Matrix gamma, double bound, Documents docs, int D) {\n this.D = D;\n this.lambda = lambda;\n this.gamma = gamma;\n this.documents = docs;\n this.totalWordCount = docs.getWordCount();\n double perWordBound = (bound * docs.size()) / (D * totalWordCount);\n this.perplexity = Math.exp(-perWordBound);\n System.out.println(\"Perplexity: \" + perplexity);\n ConsoleView.printlInConsoleln(\"Perplexity: \" + perplexity);\n }\n\n public void printTopics(PrintWriter p1, PrintWriter p2, ArrayList dList, Vocabulary v, int wordsPerTopic, IProgressMonitor monitor) {\n int[][] topicWords = new int[lambda.numOfRows()][wordsPerTopic];\n for (int k = 0; k < lambda.numOfRows(); k++) {\n monitor.subTask(\"Writing Topic \" + k);\n p2.println(\"Topic \" + k);\n ConsoleView.printlInConsoleln(\"Topic \" + k);\n int num = 0;\n LinearArray lambdak = lambda.getRow(k);\n lambdak = lambdak.div(lambdak.sum());\n for (int i = 0; i < lambdak.size(); i++) {\n p1.print(lambdak.values[i] + \" \");\n }\n p1.print(\"\\n\");\n HashMap topicWordsWts = new HashMap();\n for (int i = 0; i < lambdak.size(); i++) {\n double value = lambdak.values[i];\n topicWordsWts.put(i, value);\n }\n Map results = reverseSortByValue(topicWordsWts);\n Iterator i = results.entrySet().iterator();\n while (i.hasNext() && num < wordsPerTopic) {\n Map.Entry me = (Map.Entry) i.next();\n int y = (int) me.getKey();\n p2.print(v.getToken(y) + \"=\" + me.getValue());\n p2.print(\"\\n\");\n ConsoleView.printlInConsoleln(v.getToken(y) + \"=\" + me.getValue());\n num++;\n }\n ConsoleView.printlInConsoleln();\n monitor.worked(50);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n }\n p1.close();\n p2.close();\n }\n\n public static > Map reverseSortByValue(Map map) {\n List> list = new LinkedList<>(map.entrySet());\n Collections.sort(list, new Comparator>() {\n\n @Override\n public int compare(Map.Entry e1, Map.Entry e2) {\n return -(e1.getValue()).compareTo(e2.getValue());\n }\n });\n ", "post_mask_code": "\n return result;\n }\n}\n"} {"task_id": "Java_58", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/USC-CSSL/TACIT/edu.usc.cssl.tacit.topicmodel.onlinelda/src/edu/usc/cssl/tacit/topicmodel/onlinelda/services/OnlineLDAOutput.java", "mask_start_position": 3749, "mask_end_position": 3769, "canonical_solution": "return result;\n }", "pre_mask_code": "package edu.usc.cssl.tacit.topicmodel.onlinelda.services;\n\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Matrix;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.LinearArray;\nimport edu.usc.cssl.tacit.common.ui.views.ConsoleView;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Documents;\nimport java.io.PrintWriter;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.util.*;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\n\n/*\n * An encapsulating class to hold the results of updateLambda method in the OnlineLda class\n */\npublic class OnlineLDAOutput {\n\n private final Matrix lambda;\n\n private final Matrix gamma;\n\n private final double perplexity;\n\n private final Documents documents;\n\n private final int totalWordCount;\n\n private final int D;\n\n final static NumberFormat NF = new DecimalFormat(\"##.####\");\n\n public OnlineLDAOutput(Matrix lambda, Matrix gamma, double bound, Documents docs, int D) {\n this.D = D;\n this.lambda = lambda;\n this.gamma = gamma;\n this.documents = docs;\n this.totalWordCount = docs.getWordCount();\n double perWordBound = (bound * docs.size()) / (D * totalWordCount);\n this.perplexity = Math.exp(-perWordBound);\n System.out.println(\"Perplexity: \" + perplexity);\n ConsoleView.printlInConsoleln(\"Perplexity: \" + perplexity);\n }\n\n public void printTopics(PrintWriter p1, PrintWriter p2, ArrayList dList, Vocabulary v, int wordsPerTopic, IProgressMonitor monitor) {\n int[][] topicWords = new int[lambda.numOfRows()][wordsPerTopic];\n for (int k = 0; k < lambda.numOfRows(); k++) {\n monitor.subTask(\"Writing Topic \" + k);\n p2.println(\"Topic \" + k);\n ConsoleView.printlInConsoleln(\"Topic \" + k);\n int num = 0;\n LinearArray lambdak = lambda.getRow(k);\n lambdak = lambdak.div(lambdak.sum());\n for (int i = 0; i < lambdak.size(); i++) {\n p1.print(lambdak.values[i] + \" \");\n }\n p1.print(\"\\n\");\n HashMap topicWordsWts = new HashMap();\n for (int i = 0; i < lambdak.size(); i++) {\n double value = lambdak.values[i];\n topicWordsWts.put(i, value);\n }\n Map results = reverseSortByValue(topicWordsWts);\n Iterator i = results.entrySet().iterator();\n while (i.hasNext() && num < wordsPerTopic) {\n Map.Entry me = (Map.Entry) i.next();\n int y = (int) me.getKey();\n p2.print(v.getToken(y) + \"=\" + me.getValue());\n p2.print(\"\\n\");\n ConsoleView.printlInConsoleln(v.getToken(y) + \"=\" + me.getValue());\n num++;\n }\n ConsoleView.printlInConsoleln();\n monitor.worked(50);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n }\n p1.close();\n p2.close();\n }\n\n public static > Map reverseSortByValue(Map map) {\n List> list = new LinkedList<>(map.entrySet());\n Collections.sort(list, new Comparator>() {\n\n @Override\n public int compare(Map.Entry e1, Map.Entry e2) {\n return -(e1.getValue()).compareTo(e2.getValue());\n }\n });\n Map result = new LinkedHashMap<>();\n for (Map.Entry entry : list) {\n result.put(entry.getKey(), entry.getValue());\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_59", "language": "Java", "task_type": "single_line", "source_file": "java/github/USC-CSSL/TACIT/edu.usc.cssl.tacit.topicmodel.onlinelda/src/edu/usc/cssl/tacit/topicmodel/onlinelda/services/OnlineLDAOutput.java", "mask_start_position": 1619, "mask_end_position": 1678, "canonical_solution": "[] topicWords = new int[lambda.numOfRows()][wordsPerTopic];", "pre_mask_code": "package edu.usc.cssl.tacit.topicmodel.onlinelda.services;\n\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Matrix;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.LinearArray;\nimport edu.usc.cssl.tacit.common.ui.views.ConsoleView;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Documents;\nimport java.io.PrintWriter;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.util.*;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\n\n/*\n * An encapsulating class to hold the results of updateLambda method in the OnlineLda class\n */\npublic class OnlineLDAOutput {\n\n private final Matrix lambda;\n\n private final Matrix gamma;\n\n private final double perplexity;\n\n private final Documents documents;\n\n private final int totalWordCount;\n\n private final int D;\n\n final static NumberFormat NF = new DecimalFormat(\"##.####\");\n\n public OnlineLDAOutput(Matrix lambda, Matrix gamma, double bound, Documents docs, int D) {\n this.D = D;\n this.lambda = lambda;\n this.gamma = gamma;\n this.documents = docs;\n this.totalWordCount = docs.getWordCount();\n double perWordBound = (bound * docs.size()) / (D * totalWordCount);\n this.perplexity = Math.exp(-perWordBound);\n System.out.println(\"Perplexity: \" + perplexity);\n ConsoleView.printlInConsoleln(\"Perplexity: \" + perplexity);\n }\n\n public void printTopics(PrintWriter p1, PrintWriter p2, ArrayList dList, Vocabulary v, int wordsPerTopic, IProgressMonitor monitor) {\n int[]", "post_mask_code": "\n for (int k = 0; k < lambda.numOfRows(); k++) {\n monitor.subTask(\"Writing Topic \" + k);\n p2.println(\"Topic \" + k);\n ConsoleView.printlInConsoleln(\"Topic \" + k);\n int num = 0;\n LinearArray lambdak = lambda.getRow(k);\n lambdak = lambdak.div(lambdak.sum());\n for (int i = 0; i < lambdak.size(); i++) {\n p1.print(lambdak.values[i] + \" \");\n }\n p1.print(\"\\n\");\n HashMap topicWordsWts = new HashMap();\n for (int i = 0; i < lambdak.size(); i++) {\n double value = lambdak.values[i];\n topicWordsWts.put(i, value);\n }\n Map results = reverseSortByValue(topicWordsWts);\n Iterator i = results.entrySet().iterator();\n while (i.hasNext() && num < wordsPerTopic) {\n Map.Entry me = (Map.Entry) i.next();\n int y = (int) me.getKey();\n p2.print(v.getToken(y) + \"=\" + me.getValue());\n p2.print(\"\\n\");\n ConsoleView.printlInConsoleln(v.getToken(y) + \"=\" + me.getValue());\n num++;\n }\n ConsoleView.printlInConsoleln();\n monitor.worked(50);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n }\n p1.close();\n p2.close();\n }\n\n public static > Map reverseSortByValue(Map map) {\n List> list = new LinkedList<>(map.entrySet());\n Collections.sort(list, new Comparator>() {\n\n @Override\n public int compare(Map.Entry e1, Map.Entry e2) {\n return -(e1.getValue()).compareTo(e2.getValue());\n }\n });\n Map result = new LinkedHashMap<>();\n for (Map.Entry entry : list) {\n result.put(entry.getKey(), entry.getValue());\n }\n return result;\n }\n}\n"} {"task_id": "Java_60", "language": "Java", "task_type": "if_statement", "source_file": "java/github/USC-CSSL/TACIT/edu.usc.cssl.tacit.topicmodel.onlinelda/src/edu/usc/cssl/tacit/topicmodel/onlinelda/services/OnlineLDAOutput.java", "mask_start_position": 2996, "mask_end_position": 3093, "canonical_solution": "if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }", "pre_mask_code": "package edu.usc.cssl.tacit.topicmodel.onlinelda.services;\n\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Matrix;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.LinearArray;\nimport edu.usc.cssl.tacit.common.ui.views.ConsoleView;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Documents;\nimport java.io.PrintWriter;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.util.*;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\n\n/*\n * An encapsulating class to hold the results of updateLambda method in the OnlineLda class\n */\npublic class OnlineLDAOutput {\n\n private final Matrix lambda;\n\n private final Matrix gamma;\n\n private final double perplexity;\n\n private final Documents documents;\n\n private final int totalWordCount;\n\n private final int D;\n\n final static NumberFormat NF = new DecimalFormat(\"##.####\");\n\n public OnlineLDAOutput(Matrix lambda, Matrix gamma, double bound, Documents docs, int D) {\n this.D = D;\n this.lambda = lambda;\n this.gamma = gamma;\n this.documents = docs;\n this.totalWordCount = docs.getWordCount();\n double perWordBound = (bound * docs.size()) / (D * totalWordCount);\n this.perplexity = Math.exp(-perWordBound);\n System.out.println(\"Perplexity: \" + perplexity);\n ConsoleView.printlInConsoleln(\"Perplexity: \" + perplexity);\n }\n\n public void printTopics(PrintWriter p1, PrintWriter p2, ArrayList dList, Vocabulary v, int wordsPerTopic, IProgressMonitor monitor) {\n int[][] topicWords = new int[lambda.numOfRows()][wordsPerTopic];\n for (int k = 0; k < lambda.numOfRows(); k++) {\n monitor.subTask(\"Writing Topic \" + k);\n p2.println(\"Topic \" + k);\n ConsoleView.printlInConsoleln(\"Topic \" + k);\n int num = 0;\n LinearArray lambdak = lambda.getRow(k);\n lambdak = lambdak.div(lambdak.sum());\n for (int i = 0; i < lambdak.size(); i++) {\n p1.print(lambdak.values[i] + \" \");\n }\n p1.print(\"\\n\");\n HashMap topicWordsWts = new HashMap();\n for (int i = 0; i < lambdak.size(); i++) {\n double value = lambdak.values[i];\n topicWordsWts.put(i, value);\n }\n Map results = reverseSortByValue(topicWordsWts);\n Iterator i = results.entrySet().iterator();\n while (i.hasNext() && num < wordsPerTopic) {\n Map.Entry me = (Map.Entry) i.next();\n int y = (int) me.getKey();\n p2.print(v.getToken(y) + \"=\" + me.getValue());\n p2.print(\"\\n\");\n ConsoleView.printlInConsoleln(v.getToken(y) + \"=\" + me.getValue());\n num++;\n }\n ConsoleView.printlInConsoleln();\n monitor.worked(50);\n ", "post_mask_code": "\n }\n p1.close();\n p2.close();\n }\n\n public static > Map reverseSortByValue(Map map) {\n List> list = new LinkedList<>(map.entrySet());\n Collections.sort(list, new Comparator>() {\n\n @Override\n public int compare(Map.Entry e1, Map.Entry e2) {\n return -(e1.getValue()).compareTo(e2.getValue());\n }\n });\n Map result = new LinkedHashMap<>();\n for (Map.Entry entry : list) {\n result.put(entry.getKey(), entry.getValue());\n }\n return result;\n }\n}\n"} {"task_id": "Java_61", "language": "Java", "task_type": "for_statement", "source_file": "java/github/USC-CSSL/TACIT/edu.usc.cssl.tacit.topicmodel.onlinelda/src/edu/usc/cssl/tacit/topicmodel/onlinelda/services/OnlineLDAOutput.java", "mask_start_position": 2252, "mask_end_position": 2403, "canonical_solution": "for (int i = 0; i < lambdak.size(); i++) {\n double value = lambdak.values[i];\n topicWordsWts.put(i, value);\n }", "pre_mask_code": "package edu.usc.cssl.tacit.topicmodel.onlinelda.services;\n\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Matrix;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.LinearArray;\nimport edu.usc.cssl.tacit.common.ui.views.ConsoleView;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Documents;\nimport java.io.PrintWriter;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.util.*;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\n\n/*\n * An encapsulating class to hold the results of updateLambda method in the OnlineLda class\n */\npublic class OnlineLDAOutput {\n\n private final Matrix lambda;\n\n private final Matrix gamma;\n\n private final double perplexity;\n\n private final Documents documents;\n\n private final int totalWordCount;\n\n private final int D;\n\n final static NumberFormat NF = new DecimalFormat(\"##.####\");\n\n public OnlineLDAOutput(Matrix lambda, Matrix gamma, double bound, Documents docs, int D) {\n this.D = D;\n this.lambda = lambda;\n this.gamma = gamma;\n this.documents = docs;\n this.totalWordCount = docs.getWordCount();\n double perWordBound = (bound * docs.size()) / (D * totalWordCount);\n this.perplexity = Math.exp(-perWordBound);\n System.out.println(\"Perplexity: \" + perplexity);\n ConsoleView.printlInConsoleln(\"Perplexity: \" + perplexity);\n }\n\n public void printTopics(PrintWriter p1, PrintWriter p2, ArrayList dList, Vocabulary v, int wordsPerTopic, IProgressMonitor monitor) {\n int[][] topicWords = new int[lambda.numOfRows()][wordsPerTopic];\n for (int k = 0; k < lambda.numOfRows(); k++) {\n monitor.subTask(\"Writing Topic \" + k);\n p2.println(\"Topic \" + k);\n ConsoleView.printlInConsoleln(\"Topic \" + k);\n int num = 0;\n LinearArray lambdak = lambda.getRow(k);\n lambdak = lambdak.div(lambdak.sum());\n for (int i = 0; i < lambdak.size(); i++) {\n p1.print(lambdak.values[i] + \" \");\n }\n p1.print(\"\\n\");\n HashMap topicWordsWts = new HashMap();\n ", "post_mask_code": "\n Map results = reverseSortByValue(topicWordsWts);\n Iterator i = results.entrySet().iterator();\n while (i.hasNext() && num < wordsPerTopic) {\n Map.Entry me = (Map.Entry) i.next();\n int y = (int) me.getKey();\n p2.print(v.getToken(y) + \"=\" + me.getValue());\n p2.print(\"\\n\");\n ConsoleView.printlInConsoleln(v.getToken(y) + \"=\" + me.getValue());\n num++;\n }\n ConsoleView.printlInConsoleln();\n monitor.worked(50);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n }\n p1.close();\n p2.close();\n }\n\n public static > Map reverseSortByValue(Map map) {\n List> list = new LinkedList<>(map.entrySet());\n Collections.sort(list, new Comparator>() {\n\n @Override\n public int compare(Map.Entry e1, Map.Entry e2) {\n return -(e1.getValue()).compareTo(e2.getValue());\n }\n });\n Map result = new LinkedHashMap<>();\n for (Map.Entry entry : list) {\n result.put(entry.getKey(), entry.getValue());\n }\n return result;\n }\n}\n"} {"task_id": "Java_62", "language": "Java", "task_type": "while_statement", "source_file": "java/github/USC-CSSL/TACIT/edu.usc.cssl.tacit.topicmodel.onlinelda/src/edu/usc/cssl/tacit/topicmodel/onlinelda/services/OnlineLDAOutput.java", "mask_start_position": 2550, "mask_end_position": 2906, "canonical_solution": "while (i.hasNext() && num < wordsPerTopic) {\n Map.Entry me = (Map.Entry) i.next();\n int y = (int) me.getKey();\n p2.print(v.getToken(y) + \"=\" + me.getValue());\n p2.print(\"\\n\");\n ConsoleView.printlInConsoleln(v.getToken(y) + \"=\" + me.getValue());\n num++;\n }", "pre_mask_code": "package edu.usc.cssl.tacit.topicmodel.onlinelda.services;\n\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Matrix;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.LinearArray;\nimport edu.usc.cssl.tacit.common.ui.views.ConsoleView;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Documents;\nimport java.io.PrintWriter;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.util.*;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\n\n/*\n * An encapsulating class to hold the results of updateLambda method in the OnlineLda class\n */\npublic class OnlineLDAOutput {\n\n private final Matrix lambda;\n\n private final Matrix gamma;\n\n private final double perplexity;\n\n private final Documents documents;\n\n private final int totalWordCount;\n\n private final int D;\n\n final static NumberFormat NF = new DecimalFormat(\"##.####\");\n\n public OnlineLDAOutput(Matrix lambda, Matrix gamma, double bound, Documents docs, int D) {\n this.D = D;\n this.lambda = lambda;\n this.gamma = gamma;\n this.documents = docs;\n this.totalWordCount = docs.getWordCount();\n double perWordBound = (bound * docs.size()) / (D * totalWordCount);\n this.perplexity = Math.exp(-perWordBound);\n System.out.println(\"Perplexity: \" + perplexity);\n ConsoleView.printlInConsoleln(\"Perplexity: \" + perplexity);\n }\n\n public void printTopics(PrintWriter p1, PrintWriter p2, ArrayList dList, Vocabulary v, int wordsPerTopic, IProgressMonitor monitor) {\n int[][] topicWords = new int[lambda.numOfRows()][wordsPerTopic];\n for (int k = 0; k < lambda.numOfRows(); k++) {\n monitor.subTask(\"Writing Topic \" + k);\n p2.println(\"Topic \" + k);\n ConsoleView.printlInConsoleln(\"Topic \" + k);\n int num = 0;\n LinearArray lambdak = lambda.getRow(k);\n lambdak = lambdak.div(lambdak.sum());\n for (int i = 0; i < lambdak.size(); i++) {\n p1.print(lambdak.values[i] + \" \");\n }\n p1.print(\"\\n\");\n HashMap topicWordsWts = new HashMap();\n for (int i = 0; i < lambdak.size(); i++) {\n double value = lambdak.values[i];\n topicWordsWts.put(i, value);\n }\n Map results = reverseSortByValue(topicWordsWts);\n Iterator i = results.entrySet().iterator();\n ", "post_mask_code": "\n ConsoleView.printlInConsoleln();\n monitor.worked(50);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n }\n p1.close();\n p2.close();\n }\n\n public static > Map reverseSortByValue(Map map) {\n List> list = new LinkedList<>(map.entrySet());\n Collections.sort(list, new Comparator>() {\n\n @Override\n public int compare(Map.Entry e1, Map.Entry e2) {\n return -(e1.getValue()).compareTo(e2.getValue());\n }\n });\n Map result = new LinkedHashMap<>();\n for (Map.Entry entry : list) {\n result.put(entry.getKey(), entry.getValue());\n }\n return result;\n }\n}\n"} {"task_id": "Java_63", "language": "Java", "task_type": "empty", "source_file": "java/github/USC-CSSL/TACIT/edu.usc.cssl.tacit.topicmodel.onlinelda/src/edu/usc/cssl/tacit/topicmodel/onlinelda/services/OnlineLDAOutput.java", "mask_start_position": 760, "mask_end_position": 760, "canonical_solution": "", "pre_mask_code": "package edu.usc.cssl.tacit.topicmodel.onlinelda.services;\n\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Matrix;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.LinearArray;\nimport edu.usc.cssl.tacit.common.ui.views.ConsoleView;\nimport edu.usc.cssl.tacit.topicmodel.onlinelda.services.Documents;\nimport java.io.PrintWriter;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.util.*;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\n\n/*\n * An encapsulating class to hold the results of updateLambda method in the OnlineLda class\n */\npublic class OnlineLDAOutput {\n\n private final Matrix lambda;\n\n private final Matrix gamma;\n\n private final double p", "post_mask_code": "erplexity;\n\n private final Documents documents;\n\n private final int totalWordCount;\n\n private final int D;\n\n final static NumberFormat NF = new DecimalFormat(\"##.####\");\n\n public OnlineLDAOutput(Matrix lambda, Matrix gamma, double bound, Documents docs, int D) {\n this.D = D;\n this.lambda = lambda;\n this.gamma = gamma;\n this.documents = docs;\n this.totalWordCount = docs.getWordCount();\n double perWordBound = (bound * docs.size()) / (D * totalWordCount);\n this.perplexity = Math.exp(-perWordBound);\n System.out.println(\"Perplexity: \" + perplexity);\n ConsoleView.printlInConsoleln(\"Perplexity: \" + perplexity);\n }\n\n public void printTopics(PrintWriter p1, PrintWriter p2, ArrayList dList, Vocabulary v, int wordsPerTopic, IProgressMonitor monitor) {\n int[][] topicWords = new int[lambda.numOfRows()][wordsPerTopic];\n for (int k = 0; k < lambda.numOfRows(); k++) {\n monitor.subTask(\"Writing Topic \" + k);\n p2.println(\"Topic \" + k);\n ConsoleView.printlInConsoleln(\"Topic \" + k);\n int num = 0;\n LinearArray lambdak = lambda.getRow(k);\n lambdak = lambdak.div(lambdak.sum());\n for (int i = 0; i < lambdak.size(); i++) {\n p1.print(lambdak.values[i] + \" \");\n }\n p1.print(\"\\n\");\n HashMap topicWordsWts = new HashMap();\n for (int i = 0; i < lambdak.size(); i++) {\n double value = lambdak.values[i];\n topicWordsWts.put(i, value);\n }\n Map results = reverseSortByValue(topicWordsWts);\n Iterator i = results.entrySet().iterator();\n while (i.hasNext() && num < wordsPerTopic) {\n Map.Entry me = (Map.Entry) i.next();\n int y = (int) me.getKey();\n p2.print(v.getToken(y) + \"=\" + me.getValue());\n p2.print(\"\\n\");\n ConsoleView.printlInConsoleln(v.getToken(y) + \"=\" + me.getValue());\n num++;\n }\n ConsoleView.printlInConsoleln();\n monitor.worked(50);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n }\n p1.close();\n p2.close();\n }\n\n public static > Map reverseSortByValue(Map map) {\n List> list = new LinkedList<>(map.entrySet());\n Collections.sort(list, new Comparator>() {\n\n @Override\n public int compare(Map.Entry e1, Map.Entry e2) {\n return -(e1.getValue()).compareTo(e2.getValue());\n }\n });\n Map result = new LinkedHashMap<>();\n for (Map.Entry entry : list) {\n result.put(entry.getKey(), entry.getValue());\n }\n return result;\n }\n}\n"} {"task_id": "Java_64", "language": "Java", "task_type": "method_signature", "source_file": "java/github/zfoo-project/zfoo/net/src/main/java/com/zfoo/net/handler/codec/http/HttpCodecHandler.java", "mask_start_position": 1085, "mask_end_position": 1218, "canonical_solution": "@Override\n protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, List list) ", "pre_mask_code": "package com.zfoo.net.handler.codec.http;\n\nimport com.zfoo.net.packet.common.Message;\nimport com.zfoo.net.packet.model.DecodedPacketInfo;\nimport com.zfoo.net.packet.model.EncodedPacketInfo;\nimport com.zfoo.net.router.attachment.HttpAttachment;\nimport com.zfoo.protocol.IPacket;\nimport com.zfoo.protocol.util.JsonUtils;\nimport com.zfoo.protocol.util.StringUtils;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.handler.codec.MessageToMessageCodec;\nimport io.netty.handler.codec.http.*;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.function.Function;\n\n/**\n * @author jaysunxiao\n * @version 3.0\n */\npublic class HttpCodecHandler extends MessageToMessageCodec {\n\n private static final Logger logger = LoggerFactory.getLogger(HttpCodecHandler.class);\n\n private final Function uriResolver;\n\n public HttpCodecHandler(Function uriResolver) {\n super();\n this.uriResolver = uriResolver;\n }\n\n ", "post_mask_code": "{\n try {\n var decodedPacketInfo = uriResolver.apply(fullHttpRequest);\n list.add(decodedPacketInfo);\n } catch (Exception e) {\n logger.error(\"exception异常\", e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"throwable错误\", t);\n throw t;\n }\n }\n\n @Override\n protected void encode(ChannelHandlerContext channelHandlerContext, EncodedPacketInfo out, List list) {\n try {\n var packet = (IPacket) out.getPacket();\n var attachment = (HttpAttachment) out.getAttachment();\n var protocolVersion = attachment.getFullHttpRequest().protocolVersion();\n var httpResponseStatus = attachment.getHttpResponseStatus();\n if (packet.protocolId() == Message.PROTOCOL_ID) {\n var message = (Message) packet;\n if (message.fail()) {\n httpResponseStatus = HttpResponseStatus.BAD_REQUEST;\n }\n if (StringUtils.isEmpty(message.getMessage())) {\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n byteBuf.writeCharSequence(message.getMessage(), StringUtils.DEFAULT_CHARSET);\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n var jsonStr = JsonUtils.object2String(packet);\n byteBuf.writeBytes(StringUtils.bytes(jsonStr));\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } catch (Exception e) {\n logger.error(\"[{}]编码exception异常\", JsonUtils.object2String(out), e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"[{}]编码throwable错误\", JsonUtils.object2String(out), t);\n throw t;\n }\n }\n}\n"} {"task_id": "Java_65", "language": "Java", "task_type": "method_body", "source_file": "java/github/zfoo-project/zfoo/net/src/main/java/com/zfoo/net/handler/codec/http/HttpCodecHandler.java", "mask_start_position": 1218, "mask_end_position": 1556, "canonical_solution": "{\n try {\n var decodedPacketInfo = uriResolver.apply(fullHttpRequest);\n list.add(decodedPacketInfo);\n } catch (Exception e) {\n logger.error(\"exception异常\", e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"throwable错误\", t);\n throw t;\n }\n }", "pre_mask_code": "package com.zfoo.net.handler.codec.http;\n\nimport com.zfoo.net.packet.common.Message;\nimport com.zfoo.net.packet.model.DecodedPacketInfo;\nimport com.zfoo.net.packet.model.EncodedPacketInfo;\nimport com.zfoo.net.router.attachment.HttpAttachment;\nimport com.zfoo.protocol.IPacket;\nimport com.zfoo.protocol.util.JsonUtils;\nimport com.zfoo.protocol.util.StringUtils;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.handler.codec.MessageToMessageCodec;\nimport io.netty.handler.codec.http.*;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.function.Function;\n\n/**\n * @author jaysunxiao\n * @version 3.0\n */\npublic class HttpCodecHandler extends MessageToMessageCodec {\n\n private static final Logger logger = LoggerFactory.getLogger(HttpCodecHandler.class);\n\n private final Function uriResolver;\n\n public HttpCodecHandler(Function uriResolver) {\n super();\n this.uriResolver = uriResolver;\n }\n\n @Override\n protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, List list) ", "post_mask_code": "\n\n @Override\n protected void encode(ChannelHandlerContext channelHandlerContext, EncodedPacketInfo out, List list) {\n try {\n var packet = (IPacket) out.getPacket();\n var attachment = (HttpAttachment) out.getAttachment();\n var protocolVersion = attachment.getFullHttpRequest().protocolVersion();\n var httpResponseStatus = attachment.getHttpResponseStatus();\n if (packet.protocolId() == Message.PROTOCOL_ID) {\n var message = (Message) packet;\n if (message.fail()) {\n httpResponseStatus = HttpResponseStatus.BAD_REQUEST;\n }\n if (StringUtils.isEmpty(message.getMessage())) {\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n byteBuf.writeCharSequence(message.getMessage(), StringUtils.DEFAULT_CHARSET);\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n var jsonStr = JsonUtils.object2String(packet);\n byteBuf.writeBytes(StringUtils.bytes(jsonStr));\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } catch (Exception e) {\n logger.error(\"[{}]编码exception异常\", JsonUtils.object2String(out), e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"[{}]编码throwable错误\", JsonUtils.object2String(out), t);\n throw t;\n }\n }\n}\n"} {"task_id": "Java_66", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/zfoo-project/zfoo/net/src/main/java/com/zfoo/net/handler/codec/http/HttpCodecHandler.java", "mask_start_position": 1686, "mask_end_position": 1686, "canonical_solution": "", "pre_mask_code": "package com.zfoo.net.handler.codec.http;\n\nimport com.zfoo.net.packet.common.Message;\nimport com.zfoo.net.packet.model.DecodedPacketInfo;\nimport com.zfoo.net.packet.model.EncodedPacketInfo;\nimport com.zfoo.net.router.attachment.HttpAttachment;\nimport com.zfoo.protocol.IPacket;\nimport com.zfoo.protocol.util.JsonUtils;\nimport com.zfoo.protocol.util.StringUtils;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.handler.codec.MessageToMessageCodec;\nimport io.netty.handler.codec.http.*;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.function.Function;\n\n/**\n * @author jaysunxiao\n * @version 3.0\n */\npublic class HttpCodecHandler extends MessageToMessageCodec {\n\n private static final Logger logger = LoggerFactory.getLogger(HttpCodecHandler.class);\n\n private final Function uriResolver;\n\n public HttpCodecHandler(Function uriResolver) {\n super();\n this.uriResolver = uriResolver;\n }\n\n @Override\n protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, List list) {\n try {\n var decodedPacketInfo = uriResolver.apply(fullHttpRequest);\n list.add(decodedPacketInfo);\n } catch (Exception e) {\n logger.error(\"exception异常\", e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"throwable错误\", t);\n throw t;\n }\n }\n\n @Override\n protected void encode(ChannelHandlerContext channelHandlerContext, EncodedPacketInfo out, List list) {", "post_mask_code": "\n try {\n var packet = (IPacket) out.getPacket();\n var attachment = (HttpAttachment) out.getAttachment();\n var protocolVersion = attachment.getFullHttpRequest().protocolVersion();\n var httpResponseStatus = attachment.getHttpResponseStatus();\n if (packet.protocolId() == Message.PROTOCOL_ID) {\n var message = (Message) packet;\n if (message.fail()) {\n httpResponseStatus = HttpResponseStatus.BAD_REQUEST;\n }\n if (StringUtils.isEmpty(message.getMessage())) {\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n byteBuf.writeCharSequence(message.getMessage(), StringUtils.DEFAULT_CHARSET);\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n var jsonStr = JsonUtils.object2String(packet);\n byteBuf.writeBytes(StringUtils.bytes(jsonStr));\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } catch (Exception e) {\n logger.error(\"[{}]编码exception异常\", JsonUtils.object2String(out), e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"[{}]编码throwable错误\", JsonUtils.object2String(out), t);\n throw t;\n }\n }\n}\n"} {"task_id": "Java_67", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/zfoo-project/zfoo/net/src/main/java/com/zfoo/net/handler/codec/http/HttpCodecHandler.java", "mask_start_position": 1695, "mask_end_position": 4448, "canonical_solution": "try {\n var packet = (IPacket) out.getPacket();\n var attachment = (HttpAttachment) out.getAttachment();\n var protocolVersion = attachment.getFullHttpRequest().protocolVersion();\n var httpResponseStatus = attachment.getHttpResponseStatus();\n if (packet.protocolId() == Message.PROTOCOL_ID) {\n var message = (Message) packet;\n if (message.fail()) {\n httpResponseStatus = HttpResponseStatus.BAD_REQUEST;\n }\n if (StringUtils.isEmpty(message.getMessage())) {\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n byteBuf.writeCharSequence(message.getMessage(), StringUtils.DEFAULT_CHARSET);\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n var jsonStr = JsonUtils.object2String(packet);\n byteBuf.writeBytes(StringUtils.bytes(jsonStr));\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } catch (Exception e) {\n logger.error(\"[{}]编码exception异常\", JsonUtils.object2String(out), e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"[{}]编码throwable错误\", JsonUtils.object2String(out), t);\n throw t;\n }", "pre_mask_code": "package com.zfoo.net.handler.codec.http;\n\nimport com.zfoo.net.packet.common.Message;\nimport com.zfoo.net.packet.model.DecodedPacketInfo;\nimport com.zfoo.net.packet.model.EncodedPacketInfo;\nimport com.zfoo.net.router.attachment.HttpAttachment;\nimport com.zfoo.protocol.IPacket;\nimport com.zfoo.protocol.util.JsonUtils;\nimport com.zfoo.protocol.util.StringUtils;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.handler.codec.MessageToMessageCodec;\nimport io.netty.handler.codec.http.*;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.function.Function;\n\n/**\n * @author jaysunxiao\n * @version 3.0\n */\npublic class HttpCodecHandler extends MessageToMessageCodec {\n\n private static final Logger logger = LoggerFactory.getLogger(HttpCodecHandler.class);\n\n private final Function uriResolver;\n\n public HttpCodecHandler(Function uriResolver) {\n super();\n this.uriResolver = uriResolver;\n }\n\n @Override\n protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, List list) {\n try {\n var decodedPacketInfo = uriResolver.apply(fullHttpRequest);\n list.add(decodedPacketInfo);\n } catch (Exception e) {\n logger.error(\"exception异常\", e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"throwable错误\", t);\n throw t;\n }\n }\n\n @Override\n protected void encode(ChannelHandlerContext channelHandlerContext, EncodedPacketInfo out, List list) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_68", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/zfoo-project/zfoo/net/src/main/java/com/zfoo/net/handler/codec/http/HttpCodecHandler.java", "mask_start_position": 4453, "mask_end_position": 4454, "canonical_solution": "}", "pre_mask_code": "package com.zfoo.net.handler.codec.http;\n\nimport com.zfoo.net.packet.common.Message;\nimport com.zfoo.net.packet.model.DecodedPacketInfo;\nimport com.zfoo.net.packet.model.EncodedPacketInfo;\nimport com.zfoo.net.router.attachment.HttpAttachment;\nimport com.zfoo.protocol.IPacket;\nimport com.zfoo.protocol.util.JsonUtils;\nimport com.zfoo.protocol.util.StringUtils;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.handler.codec.MessageToMessageCodec;\nimport io.netty.handler.codec.http.*;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.function.Function;\n\n/**\n * @author jaysunxiao\n * @version 3.0\n */\npublic class HttpCodecHandler extends MessageToMessageCodec {\n\n private static final Logger logger = LoggerFactory.getLogger(HttpCodecHandler.class);\n\n private final Function uriResolver;\n\n public HttpCodecHandler(Function uriResolver) {\n super();\n this.uriResolver = uriResolver;\n }\n\n @Override\n protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, List list) {\n try {\n var decodedPacketInfo = uriResolver.apply(fullHttpRequest);\n list.add(decodedPacketInfo);\n } catch (Exception e) {\n logger.error(\"exception异常\", e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"throwable错误\", t);\n throw t;\n }\n }\n\n @Override\n protected void encode(ChannelHandlerContext channelHandlerContext, EncodedPacketInfo out, List list) {\n try {\n var packet = (IPacket) out.getPacket();\n var attachment = (HttpAttachment) out.getAttachment();\n var protocolVersion = attachment.getFullHttpRequest().protocolVersion();\n var httpResponseStatus = attachment.getHttpResponseStatus();\n if (packet.protocolId() == Message.PROTOCOL_ID) {\n var message = (Message) packet;\n if (message.fail()) {\n httpResponseStatus = HttpResponseStatus.BAD_REQUEST;\n }\n if (StringUtils.isEmpty(message.getMessage())) {\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n byteBuf.writeCharSequence(message.getMessage(), StringUtils.DEFAULT_CHARSET);\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n var jsonStr = JsonUtils.object2String(packet);\n byteBuf.writeBytes(StringUtils.bytes(jsonStr));\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } catch (Exception e) {\n logger.error(\"[{}]编码exception异常\", JsonUtils.object2String(out), e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"[{}]编码throwable错误\", JsonUtils.object2String(out), t);\n throw t;\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_69", "language": "Java", "task_type": "if_statement", "source_file": "java/github/zfoo-project/zfoo/net/src/main/java/com/zfoo/net/handler/codec/http/HttpCodecHandler.java", "mask_start_position": 2104, "mask_end_position": 2216, "canonical_solution": "if (message.fail()) {\n httpResponseStatus = HttpResponseStatus.BAD_REQUEST;\n }", "pre_mask_code": "package com.zfoo.net.handler.codec.http;\n\nimport com.zfoo.net.packet.common.Message;\nimport com.zfoo.net.packet.model.DecodedPacketInfo;\nimport com.zfoo.net.packet.model.EncodedPacketInfo;\nimport com.zfoo.net.router.attachment.HttpAttachment;\nimport com.zfoo.protocol.IPacket;\nimport com.zfoo.protocol.util.JsonUtils;\nimport com.zfoo.protocol.util.StringUtils;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.handler.codec.MessageToMessageCodec;\nimport io.netty.handler.codec.http.*;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.function.Function;\n\n/**\n * @author jaysunxiao\n * @version 3.0\n */\npublic class HttpCodecHandler extends MessageToMessageCodec {\n\n private static final Logger logger = LoggerFactory.getLogger(HttpCodecHandler.class);\n\n private final Function uriResolver;\n\n public HttpCodecHandler(Function uriResolver) {\n super();\n this.uriResolver = uriResolver;\n }\n\n @Override\n protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, List list) {\n try {\n var decodedPacketInfo = uriResolver.apply(fullHttpRequest);\n list.add(decodedPacketInfo);\n } catch (Exception e) {\n logger.error(\"exception异常\", e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"throwable错误\", t);\n throw t;\n }\n }\n\n @Override\n protected void encode(ChannelHandlerContext channelHandlerContext, EncodedPacketInfo out, List list) {\n try {\n var packet = (IPacket) out.getPacket();\n var attachment = (HttpAttachment) out.getAttachment();\n var protocolVersion = attachment.getFullHttpRequest().protocolVersion();\n var httpResponseStatus = attachment.getHttpResponseStatus();\n if (packet.protocolId() == Message.PROTOCOL_ID) {\n var message = (Message) packet;\n ", "post_mask_code": "\n if (StringUtils.isEmpty(message.getMessage())) {\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n byteBuf.writeCharSequence(message.getMessage(), StringUtils.DEFAULT_CHARSET);\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n var jsonStr = JsonUtils.object2String(packet);\n byteBuf.writeBytes(StringUtils.bytes(jsonStr));\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } catch (Exception e) {\n logger.error(\"[{}]编码exception异常\", JsonUtils.object2String(out), e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"[{}]编码throwable错误\", JsonUtils.object2String(out), t);\n throw t;\n }\n }\n}\n"} {"task_id": "Java_70", "language": "Java", "task_type": "try_statement", "source_file": "java/github/zfoo-project/zfoo/net/src/main/java/com/zfoo/net/handler/codec/http/HttpCodecHandler.java", "mask_start_position": 1228, "mask_end_position": 1550, "canonical_solution": "try {\n var decodedPacketInfo = uriResolver.apply(fullHttpRequest);\n list.add(decodedPacketInfo);\n } catch (Exception e) {\n logger.error(\"exception异常\", e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"throwable错误\", t);\n throw t;\n }", "pre_mask_code": "package com.zfoo.net.handler.codec.http;\n\nimport com.zfoo.net.packet.common.Message;\nimport com.zfoo.net.packet.model.DecodedPacketInfo;\nimport com.zfoo.net.packet.model.EncodedPacketInfo;\nimport com.zfoo.net.router.attachment.HttpAttachment;\nimport com.zfoo.protocol.IPacket;\nimport com.zfoo.protocol.util.JsonUtils;\nimport com.zfoo.protocol.util.StringUtils;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.handler.codec.MessageToMessageCodec;\nimport io.netty.handler.codec.http.*;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.function.Function;\n\n/**\n * @author jaysunxiao\n * @version 3.0\n */\npublic class HttpCodecHandler extends MessageToMessageCodec {\n\n private static final Logger logger = LoggerFactory.getLogger(HttpCodecHandler.class);\n\n private final Function uriResolver;\n\n public HttpCodecHandler(Function uriResolver) {\n super();\n this.uriResolver = uriResolver;\n }\n\n @Override\n protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, List list) {\n ", "post_mask_code": "\n }\n\n @Override\n protected void encode(ChannelHandlerContext channelHandlerContext, EncodedPacketInfo out, List list) {\n try {\n var packet = (IPacket) out.getPacket();\n var attachment = (HttpAttachment) out.getAttachment();\n var protocolVersion = attachment.getFullHttpRequest().protocolVersion();\n var httpResponseStatus = attachment.getHttpResponseStatus();\n if (packet.protocolId() == Message.PROTOCOL_ID) {\n var message = (Message) packet;\n if (message.fail()) {\n httpResponseStatus = HttpResponseStatus.BAD_REQUEST;\n }\n if (StringUtils.isEmpty(message.getMessage())) {\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n byteBuf.writeCharSequence(message.getMessage(), StringUtils.DEFAULT_CHARSET);\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n var jsonStr = JsonUtils.object2String(packet);\n byteBuf.writeBytes(StringUtils.bytes(jsonStr));\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } catch (Exception e) {\n logger.error(\"[{}]编码exception异常\", JsonUtils.object2String(out), e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"[{}]编码throwable错误\", JsonUtils.object2String(out), t);\n throw t;\n }\n }\n}\n"} {"task_id": "Java_71", "language": "Java", "task_type": "empty", "source_file": "java/github/zfoo-project/zfoo/net/src/main/java/com/zfoo/net/handler/codec/http/HttpCodecHandler.java", "mask_start_position": 1579, "mask_end_position": 1579, "canonical_solution": "", "pre_mask_code": "package com.zfoo.net.handler.codec.http;\n\nimport com.zfoo.net.packet.common.Message;\nimport com.zfoo.net.packet.model.DecodedPacketInfo;\nimport com.zfoo.net.packet.model.EncodedPacketInfo;\nimport com.zfoo.net.router.attachment.HttpAttachment;\nimport com.zfoo.protocol.IPacket;\nimport com.zfoo.protocol.util.JsonUtils;\nimport com.zfoo.protocol.util.StringUtils;\nimport io.netty.channel.ChannelHandlerContext;\nimport io.netty.handler.codec.MessageToMessageCodec;\nimport io.netty.handler.codec.http.*;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.function.Function;\n\n/**\n * @author jaysunxiao\n * @version 3.0\n */\npublic class HttpCodecHandler extends MessageToMessageCodec {\n\n private static final Logger logger = LoggerFactory.getLogger(HttpCodecHandler.class);\n\n private final Function uriResolver;\n\n public HttpCodecHandler(Function uriResolver) {\n super();\n this.uriResolver = uriResolver;\n }\n\n @Override\n protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, List list) {\n try {\n var decodedPacketInfo = uriResolver.apply(fullHttpRequest);\n list.add(decodedPacketInfo);\n } catch (Exception e) {\n logger.error(\"exception异常\", e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"throwable错误\", t);\n throw t;\n }\n }\n\n @Override\n pro", "post_mask_code": "tected void encode(ChannelHandlerContext channelHandlerContext, EncodedPacketInfo out, List list) {\n try {\n var packet = (IPacket) out.getPacket();\n var attachment = (HttpAttachment) out.getAttachment();\n var protocolVersion = attachment.getFullHttpRequest().protocolVersion();\n var httpResponseStatus = attachment.getHttpResponseStatus();\n if (packet.protocolId() == Message.PROTOCOL_ID) {\n var message = (Message) packet;\n if (message.fail()) {\n httpResponseStatus = HttpResponseStatus.BAD_REQUEST;\n }\n if (StringUtils.isEmpty(message.getMessage())) {\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n byteBuf.writeCharSequence(message.getMessage(), StringUtils.DEFAULT_CHARSET);\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } else {\n var byteBuf = channelHandlerContext.alloc().ioBuffer();\n var jsonStr = JsonUtils.object2String(packet);\n byteBuf.writeBytes(StringUtils.bytes(jsonStr));\n var fullHttpResponse = new DefaultFullHttpResponse(protocolVersion, httpResponseStatus, byteBuf);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);\n fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());\n fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);\n list.add(fullHttpResponse);\n }\n } catch (Exception e) {\n logger.error(\"[{}]编码exception异常\", JsonUtils.object2String(out), e);\n throw e;\n } catch (Throwable t) {\n logger.error(\"[{}]编码throwable错误\", JsonUtils.object2String(out), t);\n throw t;\n }\n }\n}\n"} {"task_id": "Java_72", "language": "Java", "task_type": "method_signature", "source_file": "java/github/prestodb/presto/presto-main/src/main/java/com/facebook/presto/operator/index/IndexLookupSourceFactory.java", "mask_start_position": 4320, "mask_end_position": 4390, "canonical_solution": "@Override\n public OuterPositionIterator getOuterPositionIterator() ", "pre_mask_code": "package com.facebook.presto.operator.index;\n\nimport com.facebook.presto.common.type.Type;\nimport com.facebook.presto.operator.LookupSourceFactory;\nimport com.facebook.presto.operator.LookupSourceProvider;\nimport com.facebook.presto.operator.OuterPositionIterator;\nimport com.facebook.presto.operator.PagesIndex;\nimport com.facebook.presto.operator.StaticLookupSourceProvider;\nimport com.facebook.presto.operator.TaskContext;\nimport com.facebook.presto.spi.relation.VariableReferenceExpression;\nimport com.facebook.presto.sql.gen.JoinCompiler;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.SettableFuture;\nimport io.airlift.units.DataSize;\nimport io.airlift.units.Duration;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.OptionalInt;\nimport java.util.Set;\nimport java.util.function.Supplier;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.util.concurrent.Futures.transform;\nimport static com.google.common.util.concurrent.MoreExecutors.directExecutor;\nimport static java.util.Objects.requireNonNull;\n\npublic class IndexLookupSourceFactory implements LookupSourceFactory {\n\n private final List outputTypes;\n\n private final Map layout;\n\n private final Supplier indexLoaderSupplier;\n\n private TaskContext taskContext;\n\n private final SettableFuture whenTaskContextSet = SettableFuture.create();\n\n public IndexLookupSourceFactory(Set lookupSourceInputChannels, List keyOutputChannels, OptionalInt keyOutputHashChannel, List outputTypes, Map layout, IndexBuildDriverFactoryProvider indexBuildDriverFactoryProvider, DataSize maxIndexMemorySize, IndexJoinLookupStats stats, boolean shareIndexLoading, PagesIndex.Factory pagesIndexFactory, JoinCompiler joinCompiler, Duration indexLoaderTimeout) {\n this.outputTypes = ImmutableList.copyOf(requireNonNull(outputTypes, \"outputTypes is null\"));\n this.layout = ImmutableMap.copyOf(requireNonNull(layout, \"layout is null\"));\n if (shareIndexLoading) {\n IndexLoader shared = new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n this.indexLoaderSupplier = () -> shared;\n } else {\n this.indexLoaderSupplier = () -> new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n }\n }\n\n @Override\n public List getTypes() {\n return outputTypes;\n }\n\n @Override\n public List getOutputTypes() {\n return outputTypes;\n }\n\n @Override\n public Map getLayout() {\n return layout;\n }\n\n @Override\n public void setTaskContext(TaskContext taskContext) {\n this.taskContext = taskContext;\n whenTaskContextSet.set(null);\n }\n\n @Override\n public ListenableFuture createLookupSourceProvider() {\n checkState(taskContext != null, \"taskContext not set\");\n IndexLoader indexLoader = indexLoaderSupplier.get();\n indexLoader.setContext(taskContext);\n return Futures.immediateFuture(new StaticLookupSourceProvider(new IndexLookupSource(indexLoader)));\n }\n\n @Override\n public ListenableFuture whenBuildFinishes() {\n return Futures.transformAsync(whenTaskContextSet, ignored -> transform(this.createLookupSourceProvider(), lookupSourceProvider -> {\n // Close the lookupSourceProvider we just created.\n // The only reason we created it is to wait until lookup source is ready.\n lookupSourceProvider.close();\n return null;\n }, directExecutor()), directExecutor());\n }\n\n @Override\n public int partitions() {\n throw new UnsupportedOperationException();\n }\n\n ", "post_mask_code": "{\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void destroy() {\n // nothing to do\n }\n}\n"} {"task_id": "Java_73", "language": "Java", "task_type": "method_body", "source_file": "java/github/prestodb/presto/presto-main/src/main/java/com/facebook/presto/operator/index/IndexLookupSourceFactory.java", "mask_start_position": 4490, "mask_end_position": 4522, "canonical_solution": "{\n // nothing to do\n }", "pre_mask_code": "package com.facebook.presto.operator.index;\n\nimport com.facebook.presto.common.type.Type;\nimport com.facebook.presto.operator.LookupSourceFactory;\nimport com.facebook.presto.operator.LookupSourceProvider;\nimport com.facebook.presto.operator.OuterPositionIterator;\nimport com.facebook.presto.operator.PagesIndex;\nimport com.facebook.presto.operator.StaticLookupSourceProvider;\nimport com.facebook.presto.operator.TaskContext;\nimport com.facebook.presto.spi.relation.VariableReferenceExpression;\nimport com.facebook.presto.sql.gen.JoinCompiler;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.SettableFuture;\nimport io.airlift.units.DataSize;\nimport io.airlift.units.Duration;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.OptionalInt;\nimport java.util.Set;\nimport java.util.function.Supplier;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.util.concurrent.Futures.transform;\nimport static com.google.common.util.concurrent.MoreExecutors.directExecutor;\nimport static java.util.Objects.requireNonNull;\n\npublic class IndexLookupSourceFactory implements LookupSourceFactory {\n\n private final List outputTypes;\n\n private final Map layout;\n\n private final Supplier indexLoaderSupplier;\n\n private TaskContext taskContext;\n\n private final SettableFuture whenTaskContextSet = SettableFuture.create();\n\n public IndexLookupSourceFactory(Set lookupSourceInputChannels, List keyOutputChannels, OptionalInt keyOutputHashChannel, List outputTypes, Map layout, IndexBuildDriverFactoryProvider indexBuildDriverFactoryProvider, DataSize maxIndexMemorySize, IndexJoinLookupStats stats, boolean shareIndexLoading, PagesIndex.Factory pagesIndexFactory, JoinCompiler joinCompiler, Duration indexLoaderTimeout) {\n this.outputTypes = ImmutableList.copyOf(requireNonNull(outputTypes, \"outputTypes is null\"));\n this.layout = ImmutableMap.copyOf(requireNonNull(layout, \"layout is null\"));\n if (shareIndexLoading) {\n IndexLoader shared = new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n this.indexLoaderSupplier = () -> shared;\n } else {\n this.indexLoaderSupplier = () -> new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n }\n }\n\n @Override\n public List getTypes() {\n return outputTypes;\n }\n\n @Override\n public List getOutputTypes() {\n return outputTypes;\n }\n\n @Override\n public Map getLayout() {\n return layout;\n }\n\n @Override\n public void setTaskContext(TaskContext taskContext) {\n this.taskContext = taskContext;\n whenTaskContextSet.set(null);\n }\n\n @Override\n public ListenableFuture createLookupSourceProvider() {\n checkState(taskContext != null, \"taskContext not set\");\n IndexLoader indexLoader = indexLoaderSupplier.get();\n indexLoader.setContext(taskContext);\n return Futures.immediateFuture(new StaticLookupSourceProvider(new IndexLookupSource(indexLoader)));\n }\n\n @Override\n public ListenableFuture whenBuildFinishes() {\n return Futures.transformAsync(whenTaskContextSet, ignored -> transform(this.createLookupSourceProvider(), lookupSourceProvider -> {\n // Close the lookupSourceProvider we just created.\n // The only reason we created it is to wait until lookup source is ready.\n lookupSourceProvider.close();\n return null;\n }, directExecutor()), directExecutor());\n }\n\n @Override\n public int partitions() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public OuterPositionIterator getOuterPositionIterator() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void destroy() ", "post_mask_code": "\n}\n"} {"task_id": "Java_74", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/prestodb/presto/presto-main/src/main/java/com/facebook/presto/operator/index/IndexLookupSourceFactory.java", "mask_start_position": 3801, "mask_end_position": 3801, "canonical_solution": "", "pre_mask_code": "package com.facebook.presto.operator.index;\n\nimport com.facebook.presto.common.type.Type;\nimport com.facebook.presto.operator.LookupSourceFactory;\nimport com.facebook.presto.operator.LookupSourceProvider;\nimport com.facebook.presto.operator.OuterPositionIterator;\nimport com.facebook.presto.operator.PagesIndex;\nimport com.facebook.presto.operator.StaticLookupSourceProvider;\nimport com.facebook.presto.operator.TaskContext;\nimport com.facebook.presto.spi.relation.VariableReferenceExpression;\nimport com.facebook.presto.sql.gen.JoinCompiler;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.SettableFuture;\nimport io.airlift.units.DataSize;\nimport io.airlift.units.Duration;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.OptionalInt;\nimport java.util.Set;\nimport java.util.function.Supplier;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.util.concurrent.Futures.transform;\nimport static com.google.common.util.concurrent.MoreExecutors.directExecutor;\nimport static java.util.Objects.requireNonNull;\n\npublic class IndexLookupSourceFactory implements LookupSourceFactory {\n\n private final List outputTypes;\n\n private final Map layout;\n\n private final Supplier indexLoaderSupplier;\n\n private TaskContext taskContext;\n\n private final SettableFuture whenTaskContextSet = SettableFuture.create();\n\n public IndexLookupSourceFactory(Set lookupSourceInputChannels, List keyOutputChannels, OptionalInt keyOutputHashChannel, List outputTypes, Map layout, IndexBuildDriverFactoryProvider indexBuildDriverFactoryProvider, DataSize maxIndexMemorySize, IndexJoinLookupStats stats, boolean shareIndexLoading, PagesIndex.Factory pagesIndexFactory, JoinCompiler joinCompiler, Duration indexLoaderTimeout) {\n this.outputTypes = ImmutableList.copyOf(requireNonNull(outputTypes, \"outputTypes is null\"));\n this.layout = ImmutableMap.copyOf(requireNonNull(layout, \"layout is null\"));\n if (shareIndexLoading) {\n IndexLoader shared = new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n this.indexLoaderSupplier = () -> shared;\n } else {\n this.indexLoaderSupplier = () -> new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n }\n }\n\n @Override\n public List getTypes() {\n return outputTypes;\n }\n\n @Override\n public List getOutputTypes() {\n return outputTypes;\n }\n\n @Override\n public Map getLayout() {\n return layout;\n }\n\n @Override\n public void setTaskContext(TaskContext taskContext) {\n this.taskContext = taskContext;\n whenTaskContextSet.set(null);\n }\n\n @Override\n public ListenableFuture createLookupSourceProvider() {\n checkState(taskContext != null, \"taskContext not set\");\n IndexLoader indexLoader = indexLoaderSupplier.get();\n indexLoader.setContext(taskContext);\n return Futures.immediateFuture(new StaticLookupSourceProvider(new IndexLookupSource(indexLoader)));\n }\n\n @Override\n public ListenableFuture whenBuildFinishes() {", "post_mask_code": "\n return Futures.transformAsync(whenTaskContextSet, ignored -> transform(this.createLookupSourceProvider(), lookupSourceProvider -> {\n // Close the lookupSourceProvider we just created.\n // The only reason we created it is to wait until lookup source is ready.\n lookupSourceProvider.close();\n return null;\n }, directExecutor()), directExecutor());\n }\n\n @Override\n public int partitions() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public OuterPositionIterator getOuterPositionIterator() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void destroy() {\n // nothing to do\n }\n}\n"} {"task_id": "Java_75", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/prestodb/presto/presto-main/src/main/java/com/facebook/presto/operator/index/IndexLookupSourceFactory.java", "mask_start_position": 3810, "mask_end_position": 4206, "canonical_solution": "return Futures.transformAsync(whenTaskContextSet, ignored -> transform(this.createLookupSourceProvider(), lookupSourceProvider -> {\n // Close the lookupSourceProvider we just created.\n // The only reason we created it is to wait until lookup source is ready.\n lookupSourceProvider.close();\n return null;\n }, directExecutor()), directExecutor());", "pre_mask_code": "package com.facebook.presto.operator.index;\n\nimport com.facebook.presto.common.type.Type;\nimport com.facebook.presto.operator.LookupSourceFactory;\nimport com.facebook.presto.operator.LookupSourceProvider;\nimport com.facebook.presto.operator.OuterPositionIterator;\nimport com.facebook.presto.operator.PagesIndex;\nimport com.facebook.presto.operator.StaticLookupSourceProvider;\nimport com.facebook.presto.operator.TaskContext;\nimport com.facebook.presto.spi.relation.VariableReferenceExpression;\nimport com.facebook.presto.sql.gen.JoinCompiler;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.SettableFuture;\nimport io.airlift.units.DataSize;\nimport io.airlift.units.Duration;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.OptionalInt;\nimport java.util.Set;\nimport java.util.function.Supplier;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.util.concurrent.Futures.transform;\nimport static com.google.common.util.concurrent.MoreExecutors.directExecutor;\nimport static java.util.Objects.requireNonNull;\n\npublic class IndexLookupSourceFactory implements LookupSourceFactory {\n\n private final List outputTypes;\n\n private final Map layout;\n\n private final Supplier indexLoaderSupplier;\n\n private TaskContext taskContext;\n\n private final SettableFuture whenTaskContextSet = SettableFuture.create();\n\n public IndexLookupSourceFactory(Set lookupSourceInputChannels, List keyOutputChannels, OptionalInt keyOutputHashChannel, List outputTypes, Map layout, IndexBuildDriverFactoryProvider indexBuildDriverFactoryProvider, DataSize maxIndexMemorySize, IndexJoinLookupStats stats, boolean shareIndexLoading, PagesIndex.Factory pagesIndexFactory, JoinCompiler joinCompiler, Duration indexLoaderTimeout) {\n this.outputTypes = ImmutableList.copyOf(requireNonNull(outputTypes, \"outputTypes is null\"));\n this.layout = ImmutableMap.copyOf(requireNonNull(layout, \"layout is null\"));\n if (shareIndexLoading) {\n IndexLoader shared = new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n this.indexLoaderSupplier = () -> shared;\n } else {\n this.indexLoaderSupplier = () -> new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n }\n }\n\n @Override\n public List getTypes() {\n return outputTypes;\n }\n\n @Override\n public List getOutputTypes() {\n return outputTypes;\n }\n\n @Override\n public Map getLayout() {\n return layout;\n }\n\n @Override\n public void setTaskContext(TaskContext taskContext) {\n this.taskContext = taskContext;\n whenTaskContextSet.set(null);\n }\n\n @Override\n public ListenableFuture createLookupSourceProvider() {\n checkState(taskContext != null, \"taskContext not set\");\n IndexLoader indexLoader = indexLoaderSupplier.get();\n indexLoader.setContext(taskContext);\n return Futures.immediateFuture(new StaticLookupSourceProvider(new IndexLookupSource(indexLoader)));\n }\n\n @Override\n public ListenableFuture whenBuildFinishes() {\n ", "post_mask_code": "\n }\n\n @Override\n public int partitions() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public OuterPositionIterator getOuterPositionIterator() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void destroy() {\n // nothing to do\n }\n}\n"} {"task_id": "Java_76", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/prestodb/presto/presto-main/src/main/java/com/facebook/presto/operator/index/IndexLookupSourceFactory.java", "mask_start_position": 4211, "mask_end_position": 4212, "canonical_solution": "}", "pre_mask_code": "package com.facebook.presto.operator.index;\n\nimport com.facebook.presto.common.type.Type;\nimport com.facebook.presto.operator.LookupSourceFactory;\nimport com.facebook.presto.operator.LookupSourceProvider;\nimport com.facebook.presto.operator.OuterPositionIterator;\nimport com.facebook.presto.operator.PagesIndex;\nimport com.facebook.presto.operator.StaticLookupSourceProvider;\nimport com.facebook.presto.operator.TaskContext;\nimport com.facebook.presto.spi.relation.VariableReferenceExpression;\nimport com.facebook.presto.sql.gen.JoinCompiler;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.SettableFuture;\nimport io.airlift.units.DataSize;\nimport io.airlift.units.Duration;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.OptionalInt;\nimport java.util.Set;\nimport java.util.function.Supplier;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.util.concurrent.Futures.transform;\nimport static com.google.common.util.concurrent.MoreExecutors.directExecutor;\nimport static java.util.Objects.requireNonNull;\n\npublic class IndexLookupSourceFactory implements LookupSourceFactory {\n\n private final List outputTypes;\n\n private final Map layout;\n\n private final Supplier indexLoaderSupplier;\n\n private TaskContext taskContext;\n\n private final SettableFuture whenTaskContextSet = SettableFuture.create();\n\n public IndexLookupSourceFactory(Set lookupSourceInputChannels, List keyOutputChannels, OptionalInt keyOutputHashChannel, List outputTypes, Map layout, IndexBuildDriverFactoryProvider indexBuildDriverFactoryProvider, DataSize maxIndexMemorySize, IndexJoinLookupStats stats, boolean shareIndexLoading, PagesIndex.Factory pagesIndexFactory, JoinCompiler joinCompiler, Duration indexLoaderTimeout) {\n this.outputTypes = ImmutableList.copyOf(requireNonNull(outputTypes, \"outputTypes is null\"));\n this.layout = ImmutableMap.copyOf(requireNonNull(layout, \"layout is null\"));\n if (shareIndexLoading) {\n IndexLoader shared = new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n this.indexLoaderSupplier = () -> shared;\n } else {\n this.indexLoaderSupplier = () -> new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n }\n }\n\n @Override\n public List getTypes() {\n return outputTypes;\n }\n\n @Override\n public List getOutputTypes() {\n return outputTypes;\n }\n\n @Override\n public Map getLayout() {\n return layout;\n }\n\n @Override\n public void setTaskContext(TaskContext taskContext) {\n this.taskContext = taskContext;\n whenTaskContextSet.set(null);\n }\n\n @Override\n public ListenableFuture createLookupSourceProvider() {\n checkState(taskContext != null, \"taskContext not set\");\n IndexLoader indexLoader = indexLoaderSupplier.get();\n indexLoader.setContext(taskContext);\n return Futures.immediateFuture(new StaticLookupSourceProvider(new IndexLookupSource(indexLoader)));\n }\n\n @Override\n public ListenableFuture whenBuildFinishes() {\n return Futures.transformAsync(whenTaskContextSet, ignored -> transform(this.createLookupSourceProvider(), lookupSourceProvider -> {\n // Close the lookupSourceProvider we just created.\n // The only reason we created it is to wait until lookup source is ready.\n lookupSourceProvider.close();\n return null;\n }, directExecutor()), directExecutor());\n ", "post_mask_code": "\n\n @Override\n public int partitions() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public OuterPositionIterator getOuterPositionIterator() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void destroy() {\n // nothing to do\n }\n}\n"} {"task_id": "Java_77", "language": "Java", "task_type": "single_line", "source_file": "java/github/prestodb/presto/presto-main/src/main/java/com/facebook/presto/operator/index/IndexLookupSourceFactory.java", "mask_start_position": 4291, "mask_end_position": 4308, "canonical_solution": "ationException();", "pre_mask_code": "package com.facebook.presto.operator.index;\n\nimport com.facebook.presto.common.type.Type;\nimport com.facebook.presto.operator.LookupSourceFactory;\nimport com.facebook.presto.operator.LookupSourceProvider;\nimport com.facebook.presto.operator.OuterPositionIterator;\nimport com.facebook.presto.operator.PagesIndex;\nimport com.facebook.presto.operator.StaticLookupSourceProvider;\nimport com.facebook.presto.operator.TaskContext;\nimport com.facebook.presto.spi.relation.VariableReferenceExpression;\nimport com.facebook.presto.sql.gen.JoinCompiler;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.SettableFuture;\nimport io.airlift.units.DataSize;\nimport io.airlift.units.Duration;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.OptionalInt;\nimport java.util.Set;\nimport java.util.function.Supplier;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.util.concurrent.Futures.transform;\nimport static com.google.common.util.concurrent.MoreExecutors.directExecutor;\nimport static java.util.Objects.requireNonNull;\n\npublic class IndexLookupSourceFactory implements LookupSourceFactory {\n\n private final List outputTypes;\n\n private final Map layout;\n\n private final Supplier indexLoaderSupplier;\n\n private TaskContext taskContext;\n\n private final SettableFuture whenTaskContextSet = SettableFuture.create();\n\n public IndexLookupSourceFactory(Set lookupSourceInputChannels, List keyOutputChannels, OptionalInt keyOutputHashChannel, List outputTypes, Map layout, IndexBuildDriverFactoryProvider indexBuildDriverFactoryProvider, DataSize maxIndexMemorySize, IndexJoinLookupStats stats, boolean shareIndexLoading, PagesIndex.Factory pagesIndexFactory, JoinCompiler joinCompiler, Duration indexLoaderTimeout) {\n this.outputTypes = ImmutableList.copyOf(requireNonNull(outputTypes, \"outputTypes is null\"));\n this.layout = ImmutableMap.copyOf(requireNonNull(layout, \"layout is null\"));\n if (shareIndexLoading) {\n IndexLoader shared = new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n this.indexLoaderSupplier = () -> shared;\n } else {\n this.indexLoaderSupplier = () -> new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n }\n }\n\n @Override\n public List getTypes() {\n return outputTypes;\n }\n\n @Override\n public List getOutputTypes() {\n return outputTypes;\n }\n\n @Override\n public Map getLayout() {\n return layout;\n }\n\n @Override\n public void setTaskContext(TaskContext taskContext) {\n this.taskContext = taskContext;\n whenTaskContextSet.set(null);\n }\n\n @Override\n public ListenableFuture createLookupSourceProvider() {\n checkState(taskContext != null, \"taskContext not set\");\n IndexLoader indexLoader = indexLoaderSupplier.get();\n indexLoader.setContext(taskContext);\n return Futures.immediateFuture(new StaticLookupSourceProvider(new IndexLookupSource(indexLoader)));\n }\n\n @Override\n public ListenableFuture whenBuildFinishes() {\n return Futures.transformAsync(whenTaskContextSet, ignored -> transform(this.createLookupSourceProvider(), lookupSourceProvider -> {\n // Close the lookupSourceProvider we just created.\n // The only reason we created it is to wait until lookup source is ready.\n lookupSourceProvider.close();\n return null;\n }, directExecutor()), directExecutor());\n }\n\n @Override\n public int partitions() {\n throw new UnsupportedOper", "post_mask_code": "\n }\n\n @Override\n public OuterPositionIterator getOuterPositionIterator() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void destroy() {\n // nothing to do\n }\n}\n"} {"task_id": "Java_78", "language": "Java", "task_type": "empty", "source_file": "java/github/prestodb/presto/presto-main/src/main/java/com/facebook/presto/operator/index/IndexLookupSourceFactory.java", "mask_start_position": 2619, "mask_end_position": 2619, "canonical_solution": "", "pre_mask_code": "package com.facebook.presto.operator.index;\n\nimport com.facebook.presto.common.type.Type;\nimport com.facebook.presto.operator.LookupSourceFactory;\nimport com.facebook.presto.operator.LookupSourceProvider;\nimport com.facebook.presto.operator.OuterPositionIterator;\nimport com.facebook.presto.operator.PagesIndex;\nimport com.facebook.presto.operator.StaticLookupSourceProvider;\nimport com.facebook.presto.operator.TaskContext;\nimport com.facebook.presto.spi.relation.VariableReferenceExpression;\nimport com.facebook.presto.sql.gen.JoinCompiler;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.SettableFuture;\nimport io.airlift.units.DataSize;\nimport io.airlift.units.Duration;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.OptionalInt;\nimport java.util.Set;\nimport java.util.function.Supplier;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.util.concurrent.Futures.transform;\nimport static com.google.common.util.concurrent.MoreExecutors.directExecutor;\nimport static java.util.Objects.requireNonNull;\n\npublic class IndexLookupSourceFactory implements LookupSourceFactory {\n\n private final List outputTypes;\n\n private final Map layout;\n\n private final Supplier indexLoaderSupplier;\n\n private TaskContext taskContext;\n\n private final SettableFuture whenTaskContextSet = SettableFuture.create();\n\n public IndexLookupSourceFactory(Set lookupSourceInputChannels, List keyOutputChannels, OptionalInt keyOutputHashChannel, List outputTypes, Map layout, IndexBuildDriverFactoryProvider indexBuildDriverFactoryProvider, DataSize maxIndexMemorySize, IndexJoinLookupStats stats, boolean shareIndexLoading, PagesIndex.Factory pagesIndexFactory, JoinCompiler joinCompiler, Duration indexLoaderTimeout) {\n this.outputTypes = ImmutableList.copyOf(requireNonNull(outputTypes, \"outputTypes is null\"));\n this.layout = ImmutableMap.copyOf(requireNonNull(layout, \"layout is null\"));\n if (shareIndexLoading) {\n IndexLoader shared = new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n this.indexLoaderSupplier = () -> shared;\n ", "post_mask_code": " } else {\n this.indexLoaderSupplier = () -> new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler, indexLoaderTimeout);\n }\n }\n\n @Override\n public List getTypes() {\n return outputTypes;\n }\n\n @Override\n public List getOutputTypes() {\n return outputTypes;\n }\n\n @Override\n public Map getLayout() {\n return layout;\n }\n\n @Override\n public void setTaskContext(TaskContext taskContext) {\n this.taskContext = taskContext;\n whenTaskContextSet.set(null);\n }\n\n @Override\n public ListenableFuture createLookupSourceProvider() {\n checkState(taskContext != null, \"taskContext not set\");\n IndexLoader indexLoader = indexLoaderSupplier.get();\n indexLoader.setContext(taskContext);\n return Futures.immediateFuture(new StaticLookupSourceProvider(new IndexLookupSource(indexLoader)));\n }\n\n @Override\n public ListenableFuture whenBuildFinishes() {\n return Futures.transformAsync(whenTaskContextSet, ignored -> transform(this.createLookupSourceProvider(), lookupSourceProvider -> {\n // Close the lookupSourceProvider we just created.\n // The only reason we created it is to wait until lookup source is ready.\n lookupSourceProvider.close();\n return null;\n }, directExecutor()), directExecutor());\n }\n\n @Override\n public int partitions() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public OuterPositionIterator getOuterPositionIterator() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void destroy() {\n // nothing to do\n }\n}\n"} {"task_id": "Java_79", "language": "Java", "task_type": "empty", "source_file": "java/github/apache/dolphinscheduler/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/enums/DataType.java", "mask_start_position": 87, "mask_end_position": 87, "canonical_solution": "", "pre_mask_code": "package org.apache.dolphinscheduler.common.enums;\n\n/**\n * data types in user define par", "post_mask_code": "ameter\n */\npublic enum DataType {\n\n VARCHAR,\n INTEGER,\n LONG,\n FLOAT,\n DOUBLE,\n DATE,\n TIME,\n TIMESTAMP,\n BOOLEAN,\n LIST\n}\n"} {"task_id": "Java_80", "language": "Java", "task_type": "method_signature", "source_file": "java/github/xinjianteng/Leoric/library/src/main/java/com/tin/leoric/ILeoricProcess.java", "mask_start_position": 824, "mask_end_position": 862, "canonical_solution": "static ILeoricProcess fetchStrategy() ", "pre_mask_code": "package com.tin.leoric;\n\nimport android.content.Context;\nimport android.os.Build;\n\npublic interface ILeoricProcess {\n\n /**\n * Initialization some files or other when 1st time\n */\n boolean onInit(Context context);\n\n /**\n * when Persistent processName create\n */\n void onPersistentCreate(Context context, LeoricConfigs configs);\n\n /**\n * when DaemonAssistant processName create\n */\n void onDaemonAssistantCreate(Context context, LeoricConfigs configs);\n\n /**\n * when watches the processName dead which it watched\n */\n void onDaemonDead();\n\n class Fetcher {\n\n private static volatile ILeoricProcess mDaemonStrategy;\n\n /**\n * fetch the strategy for this device\n *\n * @return the daemon strategy for this device\n */\n ", "post_mask_code": "{\n if (mDaemonStrategy != null) {\n return mDaemonStrategy;\n }\n int sdk = Build.VERSION.SDK_INT;\n mDaemonStrategy = new LeoricProcessImpl();\n return mDaemonStrategy;\n }\n }\n}\n"} {"task_id": "Java_81", "language": "Java", "task_type": "method_body", "source_file": "java/github/xinjianteng/Leoric/library/src/main/java/com/tin/leoric/ILeoricProcess.java", "mask_start_position": 862, "mask_end_position": 1106, "canonical_solution": "{\n if (mDaemonStrategy != null) {\n return mDaemonStrategy;\n }\n int sdk = Build.VERSION.SDK_INT;\n mDaemonStrategy = new LeoricProcessImpl();\n return mDaemonStrategy;\n }", "pre_mask_code": "package com.tin.leoric;\n\nimport android.content.Context;\nimport android.os.Build;\n\npublic interface ILeoricProcess {\n\n /**\n * Initialization some files or other when 1st time\n */\n boolean onInit(Context context);\n\n /**\n * when Persistent processName create\n */\n void onPersistentCreate(Context context, LeoricConfigs configs);\n\n /**\n * when DaemonAssistant processName create\n */\n void onDaemonAssistantCreate(Context context, LeoricConfigs configs);\n\n /**\n * when watches the processName dead which it watched\n */\n void onDaemonDead();\n\n class Fetcher {\n\n private static volatile ILeoricProcess mDaemonStrategy;\n\n /**\n * fetch the strategy for this device\n *\n * @return the daemon strategy for this device\n */\n static ILeoricProcess fetchStrategy() ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_82", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/xinjianteng/Leoric/library/src/main/java/com/tin/leoric/ILeoricProcess.java", "mask_start_position": 863, "mask_end_position": 960, "canonical_solution": "\n if (mDaemonStrategy != null) {\n return mDaemonStrategy;\n }", "pre_mask_code": "package com.tin.leoric;\n\nimport android.content.Context;\nimport android.os.Build;\n\npublic interface ILeoricProcess {\n\n /**\n * Initialization some files or other when 1st time\n */\n boolean onInit(Context context);\n\n /**\n * when Persistent processName create\n */\n void onPersistentCreate(Context context, LeoricConfigs configs);\n\n /**\n * when DaemonAssistant processName create\n */\n void onDaemonAssistantCreate(Context context, LeoricConfigs configs);\n\n /**\n * when watches the processName dead which it watched\n */\n void onDaemonDead();\n\n class Fetcher {\n\n private static volatile ILeoricProcess mDaemonStrategy;\n\n /**\n * fetch the strategy for this device\n *\n * @return the daemon strategy for this device\n */\n static ILeoricProcess fetchStrategy() {", "post_mask_code": "\n int sdk = Build.VERSION.SDK_INT;\n mDaemonStrategy = new LeoricProcessImpl();\n return mDaemonStrategy;\n }\n }\n}\n"} {"task_id": "Java_83", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/xinjianteng/Leoric/library/src/main/java/com/tin/leoric/ILeoricProcess.java", "mask_start_position": 973, "mask_end_position": 1060, "canonical_solution": "int sdk = Build.VERSION.SDK_INT;\n mDaemonStrategy = new LeoricProcessImpl();", "pre_mask_code": "package com.tin.leoric;\n\nimport android.content.Context;\nimport android.os.Build;\n\npublic interface ILeoricProcess {\n\n /**\n * Initialization some files or other when 1st time\n */\n boolean onInit(Context context);\n\n /**\n * when Persistent processName create\n */\n void onPersistentCreate(Context context, LeoricConfigs configs);\n\n /**\n * when DaemonAssistant processName create\n */\n void onDaemonAssistantCreate(Context context, LeoricConfigs configs);\n\n /**\n * when watches the processName dead which it watched\n */\n void onDaemonDead();\n\n class Fetcher {\n\n private static volatile ILeoricProcess mDaemonStrategy;\n\n /**\n * fetch the strategy for this device\n *\n * @return the daemon strategy for this device\n */\n static ILeoricProcess fetchStrategy() {\n if (mDaemonStrategy != null) {\n return mDaemonStrategy;\n }\n ", "post_mask_code": "\n return mDaemonStrategy;\n }\n }\n}\n"} {"task_id": "Java_84", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/xinjianteng/Leoric/library/src/main/java/com/tin/leoric/ILeoricProcess.java", "mask_start_position": 1073, "mask_end_position": 1106, "canonical_solution": "return mDaemonStrategy;\n }", "pre_mask_code": "package com.tin.leoric;\n\nimport android.content.Context;\nimport android.os.Build;\n\npublic interface ILeoricProcess {\n\n /**\n * Initialization some files or other when 1st time\n */\n boolean onInit(Context context);\n\n /**\n * when Persistent processName create\n */\n void onPersistentCreate(Context context, LeoricConfigs configs);\n\n /**\n * when DaemonAssistant processName create\n */\n void onDaemonAssistantCreate(Context context, LeoricConfigs configs);\n\n /**\n * when watches the processName dead which it watched\n */\n void onDaemonDead();\n\n class Fetcher {\n\n private static volatile ILeoricProcess mDaemonStrategy;\n\n /**\n * fetch the strategy for this device\n *\n * @return the daemon strategy for this device\n */\n static ILeoricProcess fetchStrategy() {\n if (mDaemonStrategy != null) {\n return mDaemonStrategy;\n }\n int sdk = Build.VERSION.SDK_INT;\n mDaemonStrategy = new LeoricProcessImpl();\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_85", "language": "Java", "task_type": "single_line", "source_file": "java/github/xinjianteng/Leoric/library/src/main/java/com/tin/leoric/ILeoricProcess.java", "mask_start_position": 1004, "mask_end_position": 1005, "canonical_solution": ";", "pre_mask_code": "package com.tin.leoric;\n\nimport android.content.Context;\nimport android.os.Build;\n\npublic interface ILeoricProcess {\n\n /**\n * Initialization some files or other when 1st time\n */\n boolean onInit(Context context);\n\n /**\n * when Persistent processName create\n */\n void onPersistentCreate(Context context, LeoricConfigs configs);\n\n /**\n * when DaemonAssistant processName create\n */\n void onDaemonAssistantCreate(Context context, LeoricConfigs configs);\n\n /**\n * when watches the processName dead which it watched\n */\n void onDaemonDead();\n\n class Fetcher {\n\n private static volatile ILeoricProcess mDaemonStrategy;\n\n /**\n * fetch the strategy for this device\n *\n * @return the daemon strategy for this device\n */\n static ILeoricProcess fetchStrategy() {\n if (mDaemonStrategy != null) {\n return mDaemonStrategy;\n }\n int sdk = Build.VERSION.SDK_INT", "post_mask_code": "\n mDaemonStrategy = new LeoricProcessImpl();\n return mDaemonStrategy;\n }\n }\n}\n"} {"task_id": "Java_86", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/xinjianteng/Leoric/library/src/main/java/com/tin/leoric/ILeoricProcess.java", "mask_start_position": 194, "mask_end_position": 226, "canonical_solution": "boolean onInit(Context context);", "pre_mask_code": "package com.tin.leoric;\n\nimport android.content.Context;\nimport android.os.Build;\n\npublic interface ILeoricProcess {\n\n /**\n * Initialization some files or other when 1st time\n */\n ", "post_mask_code": "\n\n /**\n * when Persistent processName create\n */\n void onPersistentCreate(Context context, LeoricConfigs configs);\n\n /**\n * when DaemonAssistant processName create\n */\n void onDaemonAssistantCreate(Context context, LeoricConfigs configs);\n\n /**\n * when watches the processName dead which it watched\n */\n void onDaemonDead();\n\n class Fetcher {\n\n private static volatile ILeoricProcess mDaemonStrategy;\n\n /**\n * fetch the strategy for this device\n *\n * @return the daemon strategy for this device\n */\n static ILeoricProcess fetchStrategy() {\n if (mDaemonStrategy != null) {\n return mDaemonStrategy;\n }\n int sdk = Build.VERSION.SDK_INT;\n mDaemonStrategy = new LeoricProcessImpl();\n return mDaemonStrategy;\n }\n }\n}\n"} {"task_id": "Java_87", "language": "Java", "task_type": "if_statement", "source_file": "java/github/xinjianteng/Leoric/library/src/main/java/com/tin/leoric/ILeoricProcess.java", "mask_start_position": 876, "mask_end_position": 960, "canonical_solution": "if (mDaemonStrategy != null) {\n return mDaemonStrategy;\n }", "pre_mask_code": "package com.tin.leoric;\n\nimport android.content.Context;\nimport android.os.Build;\n\npublic interface ILeoricProcess {\n\n /**\n * Initialization some files or other when 1st time\n */\n boolean onInit(Context context);\n\n /**\n * when Persistent processName create\n */\n void onPersistentCreate(Context context, LeoricConfigs configs);\n\n /**\n * when DaemonAssistant processName create\n */\n void onDaemonAssistantCreate(Context context, LeoricConfigs configs);\n\n /**\n * when watches the processName dead which it watched\n */\n void onDaemonDead();\n\n class Fetcher {\n\n private static volatile ILeoricProcess mDaemonStrategy;\n\n /**\n * fetch the strategy for this device\n *\n * @return the daemon strategy for this device\n */\n static ILeoricProcess fetchStrategy() {\n ", "post_mask_code": "\n int sdk = Build.VERSION.SDK_INT;\n mDaemonStrategy = new LeoricProcessImpl();\n return mDaemonStrategy;\n }\n }\n}\n"} {"task_id": "Java_88", "language": "Java", "task_type": "empty", "source_file": "java/github/xinjianteng/Leoric/library/src/main/java/com/tin/leoric/ILeoricProcess.java", "mask_start_position": 975, "mask_end_position": 975, "canonical_solution": "", "pre_mask_code": "package com.tin.leoric;\n\nimport android.content.Context;\nimport android.os.Build;\n\npublic interface ILeoricProcess {\n\n /**\n * Initialization some files or other when 1st time\n */\n boolean onInit(Context context);\n\n /**\n * when Persistent processName create\n */\n void onPersistentCreate(Context context, LeoricConfigs configs);\n\n /**\n * when DaemonAssistant processName create\n */\n void onDaemonAssistantCreate(Context context, LeoricConfigs configs);\n\n /**\n * when watches the processName dead which it watched\n */\n void onDaemonDead();\n\n class Fetcher {\n\n private static volatile ILeoricProcess mDaemonStrategy;\n\n /**\n * fetch the strategy for this device\n *\n * @return the daemon strategy for this device\n */\n static ILeoricProcess fetchStrategy() {\n if (mDaemonStrategy != null) {\n return mDaemonStrategy;\n }\n in", "post_mask_code": "t sdk = Build.VERSION.SDK_INT;\n mDaemonStrategy = new LeoricProcessImpl();\n return mDaemonStrategy;\n }\n }\n}\n"} {"task_id": "Java_89", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/dubbo-samples/dubbo-samples-resilience4j/dubbo-samples-resilience4j-filter/src/main/java/org/apache/dubbo/samples/resilience4j/action/AnnotationAction.java", "mask_start_position": 2817, "mask_end_position": 2853, "canonical_solution": "public String reliable(String name) ", "pre_mask_code": "package org.apache.dubbo.samples.resilience4j.action;\n\nimport org.apache.dubbo.config.annotation.DubboReference;\nimport org.apache.dubbo.samples.resilience4j.api.AnnotationService;\nimport org.apache.dubbo.samples.resilience4j.api.CircuitBreakerService;\nimport org.apache.dubbo.samples.resilience4j.api.RateLimiterService;\nimport org.springframework.stereotype.Component;\n\n@Component(\"annotationAction\")\npublic class AnnotationAction {\n\n @DubboReference(interfaceClass = AnnotationService.class)\n private AnnotationService annotationService;\n\n @DubboReference(interfaceClass = CircuitBreakerService.class)\n private CircuitBreakerService circuitBreakerService;\n\n @DubboReference(interfaceClass = RateLimiterService.class)\n private RateLimiterService rateLimiterService;\n\n public String doSayHello(String name) {\n return annotationService.sayHello(name);\n }\n\n public void sayCircuitBreaker(String name) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n doSayCircuitBreaker(\"off\", name, 20, ++i);\n doSayCircuitBreaker(\"on\", name, 25, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 30, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 15, ++i);\n }\n }\n }).start();\n }\n\n private void doSayCircuitBreaker(String tag, String name, int c, int l) {\n System.out.println(\"--------------------- start to run circuitBreak: \" + tag + name + \"---------------------\");\n for (int i = 0; i < c; i++) {\n try {\n Thread.sleep(20);\n System.out.print(System.currentTimeMillis() + \" - \");\n System.out.println(circuitBreakerService.say(tag + \"-\" + name + \"=\" + l + \":\" + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Throwable t) {\n System.err.println(\"==\" + t.getMessage());\n }\n }\n }\n\n public void sayRateLimiter(String name, String value) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n try {\n Thread.sleep(40);\n System.out.println(rateLimiterService.say(name + (i++), value + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Exception e) {\n System.err.println(\"<<<<<<<<<<<<<<<<<<<<<<<<<< \" + e.getMessage() + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n }\n }\n }\n }).start();\n }\n\n ", "post_mask_code": "{\n return \"hystrix fallback value\";\n }\n}\n"} {"task_id": "Java_90", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/dubbo-samples/dubbo-samples-resilience4j/dubbo-samples-resilience4j-filter/src/main/java/org/apache/dubbo/samples/resilience4j/action/AnnotationAction.java", "mask_start_position": 829, "mask_end_position": 885, "canonical_solution": "{\n return annotationService.sayHello(name);\n }", "pre_mask_code": "package org.apache.dubbo.samples.resilience4j.action;\n\nimport org.apache.dubbo.config.annotation.DubboReference;\nimport org.apache.dubbo.samples.resilience4j.api.AnnotationService;\nimport org.apache.dubbo.samples.resilience4j.api.CircuitBreakerService;\nimport org.apache.dubbo.samples.resilience4j.api.RateLimiterService;\nimport org.springframework.stereotype.Component;\n\n@Component(\"annotationAction\")\npublic class AnnotationAction {\n\n @DubboReference(interfaceClass = AnnotationService.class)\n private AnnotationService annotationService;\n\n @DubboReference(interfaceClass = CircuitBreakerService.class)\n private CircuitBreakerService circuitBreakerService;\n\n @DubboReference(interfaceClass = RateLimiterService.class)\n private RateLimiterService rateLimiterService;\n\n public String doSayHello(String name) ", "post_mask_code": "\n\n public void sayCircuitBreaker(String name) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n doSayCircuitBreaker(\"off\", name, 20, ++i);\n doSayCircuitBreaker(\"on\", name, 25, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 30, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 15, ++i);\n }\n }\n }).start();\n }\n\n private void doSayCircuitBreaker(String tag, String name, int c, int l) {\n System.out.println(\"--------------------- start to run circuitBreak: \" + tag + name + \"---------------------\");\n for (int i = 0; i < c; i++) {\n try {\n Thread.sleep(20);\n System.out.print(System.currentTimeMillis() + \" - \");\n System.out.println(circuitBreakerService.say(tag + \"-\" + name + \"=\" + l + \":\" + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Throwable t) {\n System.err.println(\"==\" + t.getMessage());\n }\n }\n }\n\n public void sayRateLimiter(String name, String value) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n try {\n Thread.sleep(40);\n System.out.println(rateLimiterService.say(name + (i++), value + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Exception e) {\n System.err.println(\"<<<<<<<<<<<<<<<<<<<<<<<<<< \" + e.getMessage() + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n }\n }\n }\n }).start();\n }\n\n public String reliable(String name) {\n return \"hystrix fallback value\";\n }\n}\n"} {"task_id": "Java_91", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/dubbo-samples/dubbo-samples-resilience4j/dubbo-samples-resilience4j-filter/src/main/java/org/apache/dubbo/samples/resilience4j/action/AnnotationAction.java", "mask_start_position": 935, "mask_end_position": 935, "canonical_solution": "", "pre_mask_code": "package org.apache.dubbo.samples.resilience4j.action;\n\nimport org.apache.dubbo.config.annotation.DubboReference;\nimport org.apache.dubbo.samples.resilience4j.api.AnnotationService;\nimport org.apache.dubbo.samples.resilience4j.api.CircuitBreakerService;\nimport org.apache.dubbo.samples.resilience4j.api.RateLimiterService;\nimport org.springframework.stereotype.Component;\n\n@Component(\"annotationAction\")\npublic class AnnotationAction {\n\n @DubboReference(interfaceClass = AnnotationService.class)\n private AnnotationService annotationService;\n\n @DubboReference(interfaceClass = CircuitBreakerService.class)\n private CircuitBreakerService circuitBreakerService;\n\n @DubboReference(interfaceClass = RateLimiterService.class)\n private RateLimiterService rateLimiterService;\n\n public String doSayHello(String name) {\n return annotationService.sayHello(name);\n }\n\n public void sayCircuitBreaker(String name) {", "post_mask_code": "\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n doSayCircuitBreaker(\"off\", name, 20, ++i);\n doSayCircuitBreaker(\"on\", name, 25, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 30, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 15, ++i);\n }\n }\n }).start();\n }\n\n private void doSayCircuitBreaker(String tag, String name, int c, int l) {\n System.out.println(\"--------------------- start to run circuitBreak: \" + tag + name + \"---------------------\");\n for (int i = 0; i < c; i++) {\n try {\n Thread.sleep(20);\n System.out.print(System.currentTimeMillis() + \" - \");\n System.out.println(circuitBreakerService.say(tag + \"-\" + name + \"=\" + l + \":\" + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Throwable t) {\n System.err.println(\"==\" + t.getMessage());\n }\n }\n }\n\n public void sayRateLimiter(String name, String value) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n try {\n Thread.sleep(40);\n System.out.println(rateLimiterService.say(name + (i++), value + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Exception e) {\n System.err.println(\"<<<<<<<<<<<<<<<<<<<<<<<<<< \" + e.getMessage() + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n }\n }\n }\n }).start();\n }\n\n public String reliable(String name) {\n return \"hystrix fallback value\";\n }\n}\n"} {"task_id": "Java_92", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/dubbo-samples/dubbo-samples-resilience4j/dubbo-samples-resilience4j-filter/src/main/java/org/apache/dubbo/samples/resilience4j/action/AnnotationAction.java", "mask_start_position": 944, "mask_end_position": 1465, "canonical_solution": "new Thread(() -> {\n {\n int i = 0;\n while (true) {\n doSayCircuitBreaker(\"off\", name, 20, ++i);\n doSayCircuitBreaker(\"on\", name, 25, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 30, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 15, ++i);\n }\n }\n }).start();", "pre_mask_code": "package org.apache.dubbo.samples.resilience4j.action;\n\nimport org.apache.dubbo.config.annotation.DubboReference;\nimport org.apache.dubbo.samples.resilience4j.api.AnnotationService;\nimport org.apache.dubbo.samples.resilience4j.api.CircuitBreakerService;\nimport org.apache.dubbo.samples.resilience4j.api.RateLimiterService;\nimport org.springframework.stereotype.Component;\n\n@Component(\"annotationAction\")\npublic class AnnotationAction {\n\n @DubboReference(interfaceClass = AnnotationService.class)\n private AnnotationService annotationService;\n\n @DubboReference(interfaceClass = CircuitBreakerService.class)\n private CircuitBreakerService circuitBreakerService;\n\n @DubboReference(interfaceClass = RateLimiterService.class)\n private RateLimiterService rateLimiterService;\n\n public String doSayHello(String name) {\n return annotationService.sayHello(name);\n }\n\n public void sayCircuitBreaker(String name) {\n ", "post_mask_code": "\n }\n\n private void doSayCircuitBreaker(String tag, String name, int c, int l) {\n System.out.println(\"--------------------- start to run circuitBreak: \" + tag + name + \"---------------------\");\n for (int i = 0; i < c; i++) {\n try {\n Thread.sleep(20);\n System.out.print(System.currentTimeMillis() + \" - \");\n System.out.println(circuitBreakerService.say(tag + \"-\" + name + \"=\" + l + \":\" + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Throwable t) {\n System.err.println(\"==\" + t.getMessage());\n }\n }\n }\n\n public void sayRateLimiter(String name, String value) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n try {\n Thread.sleep(40);\n System.out.println(rateLimiterService.say(name + (i++), value + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Exception e) {\n System.err.println(\"<<<<<<<<<<<<<<<<<<<<<<<<<< \" + e.getMessage() + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n }\n }\n }\n }).start();\n }\n\n public String reliable(String name) {\n return \"hystrix fallback value\";\n }\n}\n"} {"task_id": "Java_93", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/dubbo-samples/dubbo-samples-resilience4j/dubbo-samples-resilience4j-filter/src/main/java/org/apache/dubbo/samples/resilience4j/action/AnnotationAction.java", "mask_start_position": 1470, "mask_end_position": 1471, "canonical_solution": "}", "pre_mask_code": "package org.apache.dubbo.samples.resilience4j.action;\n\nimport org.apache.dubbo.config.annotation.DubboReference;\nimport org.apache.dubbo.samples.resilience4j.api.AnnotationService;\nimport org.apache.dubbo.samples.resilience4j.api.CircuitBreakerService;\nimport org.apache.dubbo.samples.resilience4j.api.RateLimiterService;\nimport org.springframework.stereotype.Component;\n\n@Component(\"annotationAction\")\npublic class AnnotationAction {\n\n @DubboReference(interfaceClass = AnnotationService.class)\n private AnnotationService annotationService;\n\n @DubboReference(interfaceClass = CircuitBreakerService.class)\n private CircuitBreakerService circuitBreakerService;\n\n @DubboReference(interfaceClass = RateLimiterService.class)\n private RateLimiterService rateLimiterService;\n\n public String doSayHello(String name) {\n return annotationService.sayHello(name);\n }\n\n public void sayCircuitBreaker(String name) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n doSayCircuitBreaker(\"off\", name, 20, ++i);\n doSayCircuitBreaker(\"on\", name, 25, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 30, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 15, ++i);\n }\n }\n }).start();\n ", "post_mask_code": "\n\n private void doSayCircuitBreaker(String tag, String name, int c, int l) {\n System.out.println(\"--------------------- start to run circuitBreak: \" + tag + name + \"---------------------\");\n for (int i = 0; i < c; i++) {\n try {\n Thread.sleep(20);\n System.out.print(System.currentTimeMillis() + \" - \");\n System.out.println(circuitBreakerService.say(tag + \"-\" + name + \"=\" + l + \":\" + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Throwable t) {\n System.err.println(\"==\" + t.getMessage());\n }\n }\n }\n\n public void sayRateLimiter(String name, String value) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n try {\n Thread.sleep(40);\n System.out.println(rateLimiterService.say(name + (i++), value + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Exception e) {\n System.err.println(\"<<<<<<<<<<<<<<<<<<<<<<<<<< \" + e.getMessage() + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n }\n }\n }\n }).start();\n }\n\n public String reliable(String name) {\n return \"hystrix fallback value\";\n }\n}\n"} {"task_id": "Java_94", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/dubbo-samples/dubbo-samples-resilience4j/dubbo-samples-resilience4j-filter/src/main/java/org/apache/dubbo/samples/resilience4j/action/AnnotationAction.java", "mask_start_position": 854, "mask_end_position": 879, "canonical_solution": "onService.sayHello(name);", "pre_mask_code": "package org.apache.dubbo.samples.resilience4j.action;\n\nimport org.apache.dubbo.config.annotation.DubboReference;\nimport org.apache.dubbo.samples.resilience4j.api.AnnotationService;\nimport org.apache.dubbo.samples.resilience4j.api.CircuitBreakerService;\nimport org.apache.dubbo.samples.resilience4j.api.RateLimiterService;\nimport org.springframework.stereotype.Component;\n\n@Component(\"annotationAction\")\npublic class AnnotationAction {\n\n @DubboReference(interfaceClass = AnnotationService.class)\n private AnnotationService annotationService;\n\n @DubboReference(interfaceClass = CircuitBreakerService.class)\n private CircuitBreakerService circuitBreakerService;\n\n @DubboReference(interfaceClass = RateLimiterService.class)\n private RateLimiterService rateLimiterService;\n\n public String doSayHello(String name) {\n return annotati", "post_mask_code": "\n }\n\n public void sayCircuitBreaker(String name) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n doSayCircuitBreaker(\"off\", name, 20, ++i);\n doSayCircuitBreaker(\"on\", name, 25, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 30, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 15, ++i);\n }\n }\n }).start();\n }\n\n private void doSayCircuitBreaker(String tag, String name, int c, int l) {\n System.out.println(\"--------------------- start to run circuitBreak: \" + tag + name + \"---------------------\");\n for (int i = 0; i < c; i++) {\n try {\n Thread.sleep(20);\n System.out.print(System.currentTimeMillis() + \" - \");\n System.out.println(circuitBreakerService.say(tag + \"-\" + name + \"=\" + l + \":\" + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Throwable t) {\n System.err.println(\"==\" + t.getMessage());\n }\n }\n }\n\n public void sayRateLimiter(String name, String value) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n try {\n Thread.sleep(40);\n System.out.println(rateLimiterService.say(name + (i++), value + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Exception e) {\n System.err.println(\"<<<<<<<<<<<<<<<<<<<<<<<<<< \" + e.getMessage() + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n }\n }\n }\n }).start();\n }\n\n public String reliable(String name) {\n return \"hystrix fallback value\";\n }\n}\n"} {"task_id": "Java_95", "language": "Java", "task_type": "for_statement", "source_file": "java/github/apache/dubbo-samples/dubbo-samples-resilience4j/dubbo-samples-resilience4j-filter/src/main/java/org/apache/dubbo/samples/resilience4j/action/AnnotationAction.java", "mask_start_position": 1679, "mask_end_position": 2134, "canonical_solution": "for (int i = 0; i < c; i++) {\n try {\n Thread.sleep(20);\n System.out.print(System.currentTimeMillis() + \" - \");\n System.out.println(circuitBreakerService.say(tag + \"-\" + name + \"=\" + l + \":\" + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Throwable t) {\n System.err.println(\"==\" + t.getMessage());\n }\n }", "pre_mask_code": "package org.apache.dubbo.samples.resilience4j.action;\n\nimport org.apache.dubbo.config.annotation.DubboReference;\nimport org.apache.dubbo.samples.resilience4j.api.AnnotationService;\nimport org.apache.dubbo.samples.resilience4j.api.CircuitBreakerService;\nimport org.apache.dubbo.samples.resilience4j.api.RateLimiterService;\nimport org.springframework.stereotype.Component;\n\n@Component(\"annotationAction\")\npublic class AnnotationAction {\n\n @DubboReference(interfaceClass = AnnotationService.class)\n private AnnotationService annotationService;\n\n @DubboReference(interfaceClass = CircuitBreakerService.class)\n private CircuitBreakerService circuitBreakerService;\n\n @DubboReference(interfaceClass = RateLimiterService.class)\n private RateLimiterService rateLimiterService;\n\n public String doSayHello(String name) {\n return annotationService.sayHello(name);\n }\n\n public void sayCircuitBreaker(String name) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n doSayCircuitBreaker(\"off\", name, 20, ++i);\n doSayCircuitBreaker(\"on\", name, 25, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 30, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 15, ++i);\n }\n }\n }).start();\n }\n\n private void doSayCircuitBreaker(String tag, String name, int c, int l) {\n System.out.println(\"--------------------- start to run circuitBreak: \" + tag + name + \"---------------------\");\n ", "post_mask_code": "\n }\n\n public void sayRateLimiter(String name, String value) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n try {\n Thread.sleep(40);\n System.out.println(rateLimiterService.say(name + (i++), value + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Exception e) {\n System.err.println(\"<<<<<<<<<<<<<<<<<<<<<<<<<< \" + e.getMessage() + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n }\n }\n }\n }).start();\n }\n\n public String reliable(String name) {\n return \"hystrix fallback value\";\n }\n}\n"} {"task_id": "Java_96", "language": "Java", "task_type": "while_statement", "source_file": "java/github/apache/dubbo-samples/dubbo-samples-resilience4j/dubbo-samples-resilience4j-filter/src/main/java/org/apache/dubbo/samples/resilience4j/action/AnnotationAction.java", "mask_start_position": 2286, "mask_end_position": 2771, "canonical_solution": "while (true) {\n try {\n Thread.sleep(40);\n System.out.println(rateLimiterService.say(name + (i++), value + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Exception e) {\n System.err.println(\"<<<<<<<<<<<<<<<<<<<<<<<<<< \" + e.getMessage() + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n }\n }", "pre_mask_code": "package org.apache.dubbo.samples.resilience4j.action;\n\nimport org.apache.dubbo.config.annotation.DubboReference;\nimport org.apache.dubbo.samples.resilience4j.api.AnnotationService;\nimport org.apache.dubbo.samples.resilience4j.api.CircuitBreakerService;\nimport org.apache.dubbo.samples.resilience4j.api.RateLimiterService;\nimport org.springframework.stereotype.Component;\n\n@Component(\"annotationAction\")\npublic class AnnotationAction {\n\n @DubboReference(interfaceClass = AnnotationService.class)\n private AnnotationService annotationService;\n\n @DubboReference(interfaceClass = CircuitBreakerService.class)\n private CircuitBreakerService circuitBreakerService;\n\n @DubboReference(interfaceClass = RateLimiterService.class)\n private RateLimiterService rateLimiterService;\n\n public String doSayHello(String name) {\n return annotationService.sayHello(name);\n }\n\n public void sayCircuitBreaker(String name) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n doSayCircuitBreaker(\"off\", name, 20, ++i);\n doSayCircuitBreaker(\"on\", name, 25, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 30, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 15, ++i);\n }\n }\n }).start();\n }\n\n private void doSayCircuitBreaker(String tag, String name, int c, int l) {\n System.out.println(\"--------------------- start to run circuitBreak: \" + tag + name + \"---------------------\");\n for (int i = 0; i < c; i++) {\n try {\n Thread.sleep(20);\n System.out.print(System.currentTimeMillis() + \" - \");\n System.out.println(circuitBreakerService.say(tag + \"-\" + name + \"=\" + l + \":\" + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Throwable t) {\n System.err.println(\"==\" + t.getMessage());\n }\n }\n }\n\n public void sayRateLimiter(String name, String value) {\n new Thread(() -> {\n {\n int i = 0;\n ", "post_mask_code": "\n }\n }).start();\n }\n\n public String reliable(String name) {\n return \"hystrix fallback value\";\n }\n}\n"} {"task_id": "Java_97", "language": "Java", "task_type": "try_statement", "source_file": "java/github/apache/dubbo-samples/dubbo-samples-resilience4j/dubbo-samples-resilience4j-filter/src/main/java/org/apache/dubbo/samples/resilience4j/action/AnnotationAction.java", "mask_start_position": 1721, "mask_end_position": 2124, "canonical_solution": "try {\n Thread.sleep(20);\n System.out.print(System.currentTimeMillis() + \" - \");\n System.out.println(circuitBreakerService.say(tag + \"-\" + name + \"=\" + l + \":\" + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Throwable t) {\n System.err.println(\"==\" + t.getMessage());\n }", "pre_mask_code": "package org.apache.dubbo.samples.resilience4j.action;\n\nimport org.apache.dubbo.config.annotation.DubboReference;\nimport org.apache.dubbo.samples.resilience4j.api.AnnotationService;\nimport org.apache.dubbo.samples.resilience4j.api.CircuitBreakerService;\nimport org.apache.dubbo.samples.resilience4j.api.RateLimiterService;\nimport org.springframework.stereotype.Component;\n\n@Component(\"annotationAction\")\npublic class AnnotationAction {\n\n @DubboReference(interfaceClass = AnnotationService.class)\n private AnnotationService annotationService;\n\n @DubboReference(interfaceClass = CircuitBreakerService.class)\n private CircuitBreakerService circuitBreakerService;\n\n @DubboReference(interfaceClass = RateLimiterService.class)\n private RateLimiterService rateLimiterService;\n\n public String doSayHello(String name) {\n return annotationService.sayHello(name);\n }\n\n public void sayCircuitBreaker(String name) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n doSayCircuitBreaker(\"off\", name, 20, ++i);\n doSayCircuitBreaker(\"on\", name, 25, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 30, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 15, ++i);\n }\n }\n }).start();\n }\n\n private void doSayCircuitBreaker(String tag, String name, int c, int l) {\n System.out.println(\"--------------------- start to run circuitBreak: \" + tag + name + \"---------------------\");\n for (int i = 0; i < c; i++) {\n ", "post_mask_code": "\n }\n }\n\n public void sayRateLimiter(String name, String value) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n try {\n Thread.sleep(40);\n System.out.println(rateLimiterService.say(name + (i++), value + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Exception e) {\n System.err.println(\"<<<<<<<<<<<<<<<<<<<<<<<<<< \" + e.getMessage() + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n }\n }\n }\n }).start();\n }\n\n public String reliable(String name) {\n return \"hystrix fallback value\";\n }\n}\n"} {"task_id": "Java_98", "language": "Java", "task_type": "empty", "source_file": "java/github/apache/dubbo-samples/dubbo-samples-resilience4j/dubbo-samples-resilience4j-filter/src/main/java/org/apache/dubbo/samples/resilience4j/action/AnnotationAction.java", "mask_start_position": 691, "mask_end_position": 691, "canonical_solution": "", "pre_mask_code": "package org.apache.dubbo.samples.resilience4j.action;\n\nimport org.apache.dubbo.config.annotation.DubboReference;\nimport org.apache.dubbo.samples.resilience4j.api.AnnotationService;\nimport org.apache.dubbo.samples.resilience4j.api.CircuitBreakerService;\nimport org.apache.dubbo.samples.resilience4j.api.RateLimiterService;\nimport org.springframework.stereotype.Component;\n\n@Component(\"annotationAction\")\npublic class AnnotationAction {\n\n @DubboReference(interfaceClass = AnnotationService.class)\n private AnnotationService annotationService;\n\n @DubboReference(interfaceClass = CircuitBreakerService.class)\n private CircuitBreakerService circuitBreakerService;\n\n @DubboReference", "post_mask_code": "(interfaceClass = RateLimiterService.class)\n private RateLimiterService rateLimiterService;\n\n public String doSayHello(String name) {\n return annotationService.sayHello(name);\n }\n\n public void sayCircuitBreaker(String name) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n doSayCircuitBreaker(\"off\", name, 20, ++i);\n doSayCircuitBreaker(\"on\", name, 25, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 30, ++i);\n doSayCircuitBreaker(\"half\", name, 30, ++i);\n doSayCircuitBreaker(\"off\", name, 15, ++i);\n }\n }\n }).start();\n }\n\n private void doSayCircuitBreaker(String tag, String name, int c, int l) {\n System.out.println(\"--------------------- start to run circuitBreak: \" + tag + name + \"---------------------\");\n for (int i = 0; i < c; i++) {\n try {\n Thread.sleep(20);\n System.out.print(System.currentTimeMillis() + \" - \");\n System.out.println(circuitBreakerService.say(tag + \"-\" + name + \"=\" + l + \":\" + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Throwable t) {\n System.err.println(\"==\" + t.getMessage());\n }\n }\n }\n\n public void sayRateLimiter(String name, String value) {\n new Thread(() -> {\n {\n int i = 0;\n while (true) {\n try {\n Thread.sleep(40);\n System.out.println(rateLimiterService.say(name + (i++), value + i));\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (Exception e) {\n System.err.println(\"<<<<<<<<<<<<<<<<<<<<<<<<<< \" + e.getMessage() + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n }\n }\n }\n }).start();\n }\n\n public String reliable(String name) {\n return \"hystrix fallback value\";\n }\n}\n"} {"task_id": "Java_99", "language": "Java", "task_type": "method_signature", "source_file": "java/github/badoualy/kotlogram/tl/src/main/java/com/github/badoualy/telegram/tl/api/TLApiContext.java", "mask_start_position": 7171, "mask_end_position": 7204, "canonical_solution": "@Override\n public void init() ", "pre_mask_code": "package com.github.badoualy.telegram.tl.api;\n\nimport com.github.badoualy.telegram.tl.TLContext;\nimport com.github.badoualy.telegram.tl.api.account.TLAuthorizations;\nimport com.github.badoualy.telegram.tl.api.account.TLNoPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordInputSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPrivacyRules;\nimport com.github.badoualy.telegram.tl.api.account.TLTmpPassword;\nimport com.github.badoualy.telegram.tl.api.auth.TLCheckedPhone;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.auth.TLExportedAuthorization;\nimport com.github.badoualy.telegram.tl.api.auth.TLPasswordRecovery;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCode;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeApp;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.channels.TLChannelParticipants;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlocked;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlockedSlice;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContactsNotModified;\nimport com.github.badoualy.telegram.tl.api.contacts.TLFound;\nimport com.github.badoualy.telegram.tl.api.contacts.TLImportedContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLLink;\nimport com.github.badoualy.telegram.tl.api.contacts.TLResolvedPeer;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeers;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeersNotModified;\nimport com.github.badoualy.telegram.tl.api.help.TLAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLInviteText;\nimport com.github.badoualy.telegram.tl.api.help.TLNoAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLSupport;\nimport com.github.badoualy.telegram.tl.api.help.TLTermsOfService;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedHistory;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLArchivedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotCallbackAnswer;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotResults;\nimport com.github.badoualy.telegram.tl.api.messages.TLChannelMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLChats;\nimport com.github.badoualy.telegram.tl.api.messages.TLChatsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfig;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfigNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLFoundGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLHighScores;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessageEditData;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessagesSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLPeerDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifsNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedFile;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedMessage;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultArchive;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultSuccess;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentForm;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentReceipt;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentResult;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentVerficationNeeded;\nimport com.github.badoualy.telegram.tl.api.payments.TLSavedInfo;\nimport com.github.badoualy.telegram.tl.api.payments.TLValidatedRequestedInfo;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotos;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotosSlice;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileGif;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileJpeg;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMov;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp3;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp4;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePartial;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePdf;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePng;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileUnknown;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileWebp;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceSlice;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLState;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFileReuploadNeeded;\nimport com.github.badoualy.telegram.tl.api.upload.TLFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLFileCdnRedirect;\nimport com.github.badoualy.telegram.tl.api.upload.TLWebFile;\n\n/**\n * @author Yannick Badoual example@nnthink.com\n * @see http://example.com\n */\n@SuppressWarnings(\"unused\")\npublic class TLApiContext extends TLContext {\n\n private static TLApiContext instance;\n\n public TLApiContext() {\n super(543);\n }\n\n public static TLApiContext getInstance() {\n if (instance == null) {\n instance = new TLApiContext();\n }\n return instance;\n }\n\n ", "post_mask_code": "{\n registerClass(TLAuthorizations.CONSTRUCTOR_ID, TLAuthorizations.class);\n registerClass(TLNoPassword.CONSTRUCTOR_ID, TLNoPassword.class);\n registerClass(TLPassword.CONSTRUCTOR_ID, TLPassword.class);\n registerClass(TLPasswordInputSettings.CONSTRUCTOR_ID, TLPasswordInputSettings.class);\n registerClass(TLPasswordSettings.CONSTRUCTOR_ID, TLPasswordSettings.class);\n registerClass(TLPrivacyRules.CONSTRUCTOR_ID, TLPrivacyRules.class);\n registerClass(TLTmpPassword.CONSTRUCTOR_ID, TLTmpPassword.class);\n registerClass(TLAccountDaysTTL.CONSTRUCTOR_ID, TLAccountDaysTTL.class);\n registerClass(com.github.badoualy.telegram.tl.api.auth.TLAuthorization.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.auth.TLAuthorization.class);\n registerClass(TLCheckedPhone.CONSTRUCTOR_ID, TLCheckedPhone.class);\n registerClass(TLCodeTypeCall.CONSTRUCTOR_ID, TLCodeTypeCall.class);\n registerClass(TLCodeTypeFlashCall.CONSTRUCTOR_ID, TLCodeTypeFlashCall.class);\n registerClass(TLCodeTypeSms.CONSTRUCTOR_ID, TLCodeTypeSms.class);\n registerClass(TLExportedAuthorization.CONSTRUCTOR_ID, TLExportedAuthorization.class);\n registerClass(TLPasswordRecovery.CONSTRUCTOR_ID, TLPasswordRecovery.class);\n registerClass(TLSentCode.CONSTRUCTOR_ID, TLSentCode.class);\n registerClass(TLSentCodeTypeApp.CONSTRUCTOR_ID, TLSentCodeTypeApp.class);\n registerClass(TLSentCodeTypeCall.CONSTRUCTOR_ID, TLSentCodeTypeCall.class);\n registerClass(TLSentCodeTypeFlashCall.CONSTRUCTOR_ID, TLSentCodeTypeFlashCall.class);\n registerClass(TLSentCodeTypeSms.CONSTRUCTOR_ID, TLSentCodeTypeSms.class);\n registerClass(TLAuthorization.CONSTRUCTOR_ID, TLAuthorization.class);\n registerClass(TLBotCommand.CONSTRUCTOR_ID, TLBotCommand.class);\n registerClass(TLBotInfo.CONSTRUCTOR_ID, TLBotInfo.class);\n registerClass(TLBotInlineMediaResult.CONSTRUCTOR_ID, TLBotInlineMediaResult.class);\n registerClass(TLBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLBotInlineMessageMediaAuto.class);\n registerClass(TLBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLBotInlineMessageMediaContact.class);\n registerClass(TLBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLBotInlineMessageMediaGeo.class);\n registerClass(TLBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLBotInlineMessageMediaVenue.class);\n registerClass(TLBotInlineMessageText.CONSTRUCTOR_ID, TLBotInlineMessageText.class);\n registerClass(TLBotInlineResult.CONSTRUCTOR_ID, TLBotInlineResult.class);\n registerClass(TLCdnConfig.CONSTRUCTOR_ID, TLCdnConfig.class);\n registerClass(TLCdnPublicKey.CONSTRUCTOR_ID, TLCdnPublicKey.class);\n registerClass(TLChannel.CONSTRUCTOR_ID, TLChannel.class);\n registerClass(TLChannelForbidden.CONSTRUCTOR_ID, TLChannelForbidden.class);\n registerClass(TLChannelFull.CONSTRUCTOR_ID, TLChannelFull.class);\n registerClass(TLChannelMessagesFilter.CONSTRUCTOR_ID, TLChannelMessagesFilter.class);\n registerClass(TLChannelMessagesFilterEmpty.CONSTRUCTOR_ID, TLChannelMessagesFilterEmpty.class);\n registerClass(TLChannelParticipant.CONSTRUCTOR_ID, TLChannelParticipant.class);\n registerClass(TLChannelParticipantCreator.CONSTRUCTOR_ID, TLChannelParticipantCreator.class);\n registerClass(TLChannelParticipantEditor.CONSTRUCTOR_ID, TLChannelParticipantEditor.class);\n registerClass(TLChannelParticipantKicked.CONSTRUCTOR_ID, TLChannelParticipantKicked.class);\n registerClass(TLChannelParticipantModerator.CONSTRUCTOR_ID, TLChannelParticipantModerator.class);\n registerClass(TLChannelParticipantSelf.CONSTRUCTOR_ID, TLChannelParticipantSelf.class);\n registerClass(TLChannelParticipantsAdmins.CONSTRUCTOR_ID, TLChannelParticipantsAdmins.class);\n registerClass(TLChannelParticipantsBots.CONSTRUCTOR_ID, TLChannelParticipantsBots.class);\n registerClass(TLChannelParticipantsKicked.CONSTRUCTOR_ID, TLChannelParticipantsKicked.class);\n registerClass(TLChannelParticipantsRecent.CONSTRUCTOR_ID, TLChannelParticipantsRecent.class);\n registerClass(TLChannelRoleEditor.CONSTRUCTOR_ID, TLChannelRoleEditor.class);\n registerClass(TLChannelRoleEmpty.CONSTRUCTOR_ID, TLChannelRoleEmpty.class);\n registerClass(TLChannelRoleModerator.CONSTRUCTOR_ID, TLChannelRoleModerator.class);\n registerClass(com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.class);\n registerClass(TLChannelParticipants.CONSTRUCTOR_ID, TLChannelParticipants.class);\n registerClass(TLChat.CONSTRUCTOR_ID, TLChat.class);\n registerClass(TLChatEmpty.CONSTRUCTOR_ID, TLChatEmpty.class);\n registerClass(TLChatForbidden.CONSTRUCTOR_ID, TLChatForbidden.class);\n registerClass(TLChatFull.CONSTRUCTOR_ID, TLChatFull.class);\n registerClass(TLChatInvite.CONSTRUCTOR_ID, TLChatInvite.class);\n registerClass(TLChatInviteAlready.CONSTRUCTOR_ID, TLChatInviteAlready.class);\n registerClass(TLChatInviteEmpty.CONSTRUCTOR_ID, TLChatInviteEmpty.class);\n registerClass(TLChatInviteExported.CONSTRUCTOR_ID, TLChatInviteExported.class);\n registerClass(TLChatParticipant.CONSTRUCTOR_ID, TLChatParticipant.class);\n registerClass(TLChatParticipantAdmin.CONSTRUCTOR_ID, TLChatParticipantAdmin.class);\n registerClass(TLChatParticipantCreator.CONSTRUCTOR_ID, TLChatParticipantCreator.class);\n registerClass(TLChatParticipants.CONSTRUCTOR_ID, TLChatParticipants.class);\n registerClass(TLChatParticipantsForbidden.CONSTRUCTOR_ID, TLChatParticipantsForbidden.class);\n registerClass(TLChatPhoto.CONSTRUCTOR_ID, TLChatPhoto.class);\n registerClass(TLChatPhotoEmpty.CONSTRUCTOR_ID, TLChatPhotoEmpty.class);\n registerClass(TLConfig.CONSTRUCTOR_ID, TLConfig.class);\n registerClass(TLContact.CONSTRUCTOR_ID, TLContact.class);\n registerClass(TLContactBlocked.CONSTRUCTOR_ID, TLContactBlocked.class);\n registerClass(TLContactLinkContact.CONSTRUCTOR_ID, TLContactLinkContact.class);\n registerClass(TLContactLinkHasPhone.CONSTRUCTOR_ID, TLContactLinkHasPhone.class);\n registerClass(TLContactLinkNone.CONSTRUCTOR_ID, TLContactLinkNone.class);\n registerClass(TLContactLinkUnknown.CONSTRUCTOR_ID, TLContactLinkUnknown.class);\n registerClass(TLContactStatus.CONSTRUCTOR_ID, TLContactStatus.class);\n registerClass(TLBlocked.CONSTRUCTOR_ID, TLBlocked.class);\n registerClass(TLBlockedSlice.CONSTRUCTOR_ID, TLBlockedSlice.class);\n registerClass(TLContacts.CONSTRUCTOR_ID, TLContacts.class);\n registerClass(TLContactsNotModified.CONSTRUCTOR_ID, TLContactsNotModified.class);\n registerClass(TLFound.CONSTRUCTOR_ID, TLFound.class);\n registerClass(TLImportedContacts.CONSTRUCTOR_ID, TLImportedContacts.class);\n registerClass(TLLink.CONSTRUCTOR_ID, TLLink.class);\n registerClass(TLResolvedPeer.CONSTRUCTOR_ID, TLResolvedPeer.class);\n registerClass(TLTopPeers.CONSTRUCTOR_ID, TLTopPeers.class);\n registerClass(TLTopPeersNotModified.CONSTRUCTOR_ID, TLTopPeersNotModified.class);\n registerClass(TLDataJSON.CONSTRUCTOR_ID, TLDataJSON.class);\n registerClass(TLDcOption.CONSTRUCTOR_ID, TLDcOption.class);\n registerClass(TLDialog.CONSTRUCTOR_ID, TLDialog.class);\n registerClass(TLDisabledFeature.CONSTRUCTOR_ID, TLDisabledFeature.class);\n registerClass(TLDocument.CONSTRUCTOR_ID, TLDocument.class);\n registerClass(TLDocumentAttributeAnimated.CONSTRUCTOR_ID, TLDocumentAttributeAnimated.class);\n registerClass(TLDocumentAttributeAudio.CONSTRUCTOR_ID, TLDocumentAttributeAudio.class);\n registerClass(TLDocumentAttributeFilename.CONSTRUCTOR_ID, TLDocumentAttributeFilename.class);\n registerClass(TLDocumentAttributeHasStickers.CONSTRUCTOR_ID, TLDocumentAttributeHasStickers.class);\n registerClass(TLDocumentAttributeImageSize.CONSTRUCTOR_ID, TLDocumentAttributeImageSize.class);\n registerClass(TLDocumentAttributeSticker.CONSTRUCTOR_ID, TLDocumentAttributeSticker.class);\n registerClass(TLDocumentAttributeVideo.CONSTRUCTOR_ID, TLDocumentAttributeVideo.class);\n registerClass(TLDocumentEmpty.CONSTRUCTOR_ID, TLDocumentEmpty.class);\n registerClass(TLDraftMessage.CONSTRUCTOR_ID, TLDraftMessage.class);\n registerClass(TLDraftMessageEmpty.CONSTRUCTOR_ID, TLDraftMessageEmpty.class);\n registerClass(TLEncryptedChat.CONSTRUCTOR_ID, TLEncryptedChat.class);\n registerClass(TLEncryptedChatDiscarded.CONSTRUCTOR_ID, TLEncryptedChatDiscarded.class);\n registerClass(TLEncryptedChatEmpty.CONSTRUCTOR_ID, TLEncryptedChatEmpty.class);\n registerClass(TLEncryptedChatRequested.CONSTRUCTOR_ID, TLEncryptedChatRequested.class);\n registerClass(TLEncryptedChatWaiting.CONSTRUCTOR_ID, TLEncryptedChatWaiting.class);\n registerClass(TLEncryptedFile.CONSTRUCTOR_ID, TLEncryptedFile.class);\n registerClass(TLEncryptedFileEmpty.CONSTRUCTOR_ID, TLEncryptedFileEmpty.class);\n registerClass(TLEncryptedMessage.CONSTRUCTOR_ID, TLEncryptedMessage.class);\n registerClass(TLEncryptedMessageService.CONSTRUCTOR_ID, TLEncryptedMessageService.class);\n registerClass(TLExportedMessageLink.CONSTRUCTOR_ID, TLExportedMessageLink.class);\n registerClass(TLFileLocation.CONSTRUCTOR_ID, TLFileLocation.class);\n registerClass(TLFileLocationUnavailable.CONSTRUCTOR_ID, TLFileLocationUnavailable.class);\n registerClass(TLFoundGif.CONSTRUCTOR_ID, TLFoundGif.class);\n registerClass(TLFoundGifCached.CONSTRUCTOR_ID, TLFoundGifCached.class);\n registerClass(TLGame.CONSTRUCTOR_ID, TLGame.class);\n registerClass(TLGeoPoint.CONSTRUCTOR_ID, TLGeoPoint.class);\n registerClass(TLGeoPointEmpty.CONSTRUCTOR_ID, TLGeoPointEmpty.class);\n registerClass(TLAppUpdate.CONSTRUCTOR_ID, TLAppUpdate.class);\n registerClass(TLInviteText.CONSTRUCTOR_ID, TLInviteText.class);\n registerClass(TLNoAppUpdate.CONSTRUCTOR_ID, TLNoAppUpdate.class);\n registerClass(TLSupport.CONSTRUCTOR_ID, TLSupport.class);\n registerClass(TLTermsOfService.CONSTRUCTOR_ID, TLTermsOfService.class);\n registerClass(TLHighScore.CONSTRUCTOR_ID, TLHighScore.class);\n registerClass(TLImportedContact.CONSTRUCTOR_ID, TLImportedContact.class);\n registerClass(TLInlineBotSwitchPM.CONSTRUCTOR_ID, TLInlineBotSwitchPM.class);\n registerClass(TLInputAppEvent.CONSTRUCTOR_ID, TLInputAppEvent.class);\n registerClass(TLInputBotInlineMessageGame.CONSTRUCTOR_ID, TLInputBotInlineMessageGame.class);\n registerClass(TLInputBotInlineMessageID.CONSTRUCTOR_ID, TLInputBotInlineMessageID.class);\n registerClass(TLInputBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaAuto.class);\n registerClass(TLInputBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaContact.class);\n registerClass(TLInputBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaGeo.class);\n registerClass(TLInputBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaVenue.class);\n registerClass(TLInputBotInlineMessageText.CONSTRUCTOR_ID, TLInputBotInlineMessageText.class);\n registerClass(TLInputBotInlineResult.CONSTRUCTOR_ID, TLInputBotInlineResult.class);\n registerClass(TLInputBotInlineResultDocument.CONSTRUCTOR_ID, TLInputBotInlineResultDocument.class);\n registerClass(TLInputBotInlineResultGame.CONSTRUCTOR_ID, TLInputBotInlineResultGame.class);\n registerClass(TLInputBotInlineResultPhoto.CONSTRUCTOR_ID, TLInputBotInlineResultPhoto.class);\n registerClass(TLInputChannel.CONSTRUCTOR_ID, TLInputChannel.class);\n registerClass(TLInputChannelEmpty.CONSTRUCTOR_ID, TLInputChannelEmpty.class);\n registerClass(TLInputChatPhoto.CONSTRUCTOR_ID, TLInputChatPhoto.class);\n registerClass(TLInputChatPhotoEmpty.CONSTRUCTOR_ID, TLInputChatPhotoEmpty.class);\n registerClass(TLInputChatUploadedPhoto.CONSTRUCTOR_ID, TLInputChatUploadedPhoto.class);\n registerClass(TLInputDocument.CONSTRUCTOR_ID, TLInputDocument.class);\n registerClass(TLInputDocumentEmpty.CONSTRUCTOR_ID, TLInputDocumentEmpty.class);\n registerClass(TLInputDocumentFileLocation.CONSTRUCTOR_ID, TLInputDocumentFileLocation.class);\n registerClass(TLInputEncryptedChat.CONSTRUCTOR_ID, TLInputEncryptedChat.class);\n registerClass(TLInputEncryptedFile.CONSTRUCTOR_ID, TLInputEncryptedFile.class);\n registerClass(TLInputEncryptedFileBigUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileBigUploaded.class);\n registerClass(TLInputEncryptedFileEmpty.CONSTRUCTOR_ID, TLInputEncryptedFileEmpty.class);\n registerClass(TLInputEncryptedFileLocation.CONSTRUCTOR_ID, TLInputEncryptedFileLocation.class);\n registerClass(TLInputEncryptedFileUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileUploaded.class);\n registerClass(TLInputFile.CONSTRUCTOR_ID, TLInputFile.class);\n registerClass(TLInputFileBig.CONSTRUCTOR_ID, TLInputFileBig.class);\n registerClass(TLInputFileLocation.CONSTRUCTOR_ID, TLInputFileLocation.class);\n registerClass(TLInputGameID.CONSTRUCTOR_ID, TLInputGameID.class);\n registerClass(TLInputGameShortName.CONSTRUCTOR_ID, TLInputGameShortName.class);\n registerClass(TLInputGeoPoint.CONSTRUCTOR_ID, TLInputGeoPoint.class);\n registerClass(TLInputGeoPointEmpty.CONSTRUCTOR_ID, TLInputGeoPointEmpty.class);\n registerClass(TLInputMediaContact.CONSTRUCTOR_ID, TLInputMediaContact.class);\n registerClass(TLInputMediaDocument.CONSTRUCTOR_ID, TLInputMediaDocument.class);\n registerClass(TLInputMediaDocumentExternal.CONSTRUCTOR_ID, TLInputMediaDocumentExternal.class);\n registerClass(TLInputMediaEmpty.CONSTRUCTOR_ID, TLInputMediaEmpty.class);\n registerClass(TLInputMediaGame.CONSTRUCTOR_ID, TLInputMediaGame.class);\n registerClass(TLInputMediaGeoPoint.CONSTRUCTOR_ID, TLInputMediaGeoPoint.class);\n registerClass(TLInputMediaGifExternal.CONSTRUCTOR_ID, TLInputMediaGifExternal.class);\n registerClass(TLInputMediaInvoice.CONSTRUCTOR_ID, TLInputMediaInvoice.class);\n registerClass(TLInputMediaPhoto.CONSTRUCTOR_ID, TLInputMediaPhoto.class);\n registerClass(TLInputMediaPhotoExternal.CONSTRUCTOR_ID, TLInputMediaPhotoExternal.class);\n registerClass(TLInputMediaUploadedDocument.CONSTRUCTOR_ID, TLInputMediaUploadedDocument.class);\n registerClass(TLInputMediaUploadedPhoto.CONSTRUCTOR_ID, TLInputMediaUploadedPhoto.class);\n registerClass(TLInputMediaUploadedThumbDocument.CONSTRUCTOR_ID, TLInputMediaUploadedThumbDocument.class);\n registerClass(TLInputMediaVenue.CONSTRUCTOR_ID, TLInputMediaVenue.class);\n registerClass(TLInputMessageEntityMentionName.CONSTRUCTOR_ID, TLInputMessageEntityMentionName.class);\n registerClass(TLInputMessagesFilterChatPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterChatPhotos.class);\n registerClass(TLInputMessagesFilterDocument.CONSTRUCTOR_ID, TLInputMessagesFilterDocument.class);\n registerClass(TLInputMessagesFilterEmpty.CONSTRUCTOR_ID, TLInputMessagesFilterEmpty.class);\n registerClass(TLInputMessagesFilterGif.CONSTRUCTOR_ID, TLInputMessagesFilterGif.class);\n registerClass(TLInputMessagesFilterMusic.CONSTRUCTOR_ID, TLInputMessagesFilterMusic.class);\n registerClass(TLInputMessagesFilterPhoneCalls.CONSTRUCTOR_ID, TLInputMessagesFilterPhoneCalls.class);\n registerClass(TLInputMessagesFilterPhotoVideo.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideo.class);\n registerClass(TLInputMessagesFilterPhotoVideoDocuments.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideoDocuments.class);\n registerClass(TLInputMessagesFilterPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterPhotos.class);\n registerClass(TLInputMessagesFilterRoundVideo.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVideo.class);\n registerClass(TLInputMessagesFilterRoundVoice.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVoice.class);\n registerClass(TLInputMessagesFilterUrl.CONSTRUCTOR_ID, TLInputMessagesFilterUrl.class);\n registerClass(TLInputMessagesFilterVideo.CONSTRUCTOR_ID, TLInputMessagesFilterVideo.class);\n registerClass(TLInputMessagesFilterVoice.CONSTRUCTOR_ID, TLInputMessagesFilterVoice.class);\n registerClass(TLInputNotifyAll.CONSTRUCTOR_ID, TLInputNotifyAll.class);\n registerClass(TLInputNotifyChats.CONSTRUCTOR_ID, TLInputNotifyChats.class);\n registerClass(TLInputNotifyPeer.CONSTRUCTOR_ID, TLInputNotifyPeer.class);\n registerClass(TLInputNotifyUsers.CONSTRUCTOR_ID, TLInputNotifyUsers.class);\n registerClass(TLInputPaymentCredentials.CONSTRUCTOR_ID, TLInputPaymentCredentials.class);\n registerClass(TLInputPaymentCredentialsSaved.CONSTRUCTOR_ID, TLInputPaymentCredentialsSaved.class);\n registerClass(TLInputPeerChannel.CONSTRUCTOR_ID, TLInputPeerChannel.class);\n registerClass(TLInputPeerChat.CONSTRUCTOR_ID, TLInputPeerChat.class);\n registerClass(TLInputPeerEmpty.CONSTRUCTOR_ID, TLInputPeerEmpty.class);\n registerClass(TLInputPeerNotifyEventsAll.CONSTRUCTOR_ID, TLInputPeerNotifyEventsAll.class);\n registerClass(TLInputPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLInputPeerNotifyEventsEmpty.class);\n registerClass(TLInputPeerNotifySettings.CONSTRUCTOR_ID, TLInputPeerNotifySettings.class);\n registerClass(TLInputPeerSelf.CONSTRUCTOR_ID, TLInputPeerSelf.class);\n registerClass(TLInputPeerUser.CONSTRUCTOR_ID, TLInputPeerUser.class);\n registerClass(TLInputPhoneCall.CONSTRUCTOR_ID, TLInputPhoneCall.class);\n registerClass(TLInputPhoneContact.CONSTRUCTOR_ID, TLInputPhoneContact.class);\n registerClass(TLInputPhoto.CONSTRUCTOR_ID, TLInputPhoto.class);\n registerClass(TLInputPhotoEmpty.CONSTRUCTOR_ID, TLInputPhotoEmpty.class);\n registerClass(TLInputPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLInputPrivacyKeyChatInvite.class);\n registerClass(TLInputPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLInputPrivacyKeyPhoneCall.class);\n registerClass(TLInputPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLInputPrivacyKeyStatusTimestamp.class);\n registerClass(TLInputPrivacyValueAllowAll.CONSTRUCTOR_ID, TLInputPrivacyValueAllowAll.class);\n registerClass(TLInputPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueAllowContacts.class);\n registerClass(TLInputPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueAllowUsers.class);\n registerClass(TLInputPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowAll.class);\n registerClass(TLInputPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowContacts.class);\n registerClass(TLInputPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowUsers.class);\n registerClass(TLInputReportReasonOther.CONSTRUCTOR_ID, TLInputReportReasonOther.class);\n registerClass(TLInputReportReasonPornography.CONSTRUCTOR_ID, TLInputReportReasonPornography.class);\n registerClass(TLInputReportReasonSpam.CONSTRUCTOR_ID, TLInputReportReasonSpam.class);\n registerClass(TLInputReportReasonViolence.CONSTRUCTOR_ID, TLInputReportReasonViolence.class);\n registerClass(TLInputStickerSetEmpty.CONSTRUCTOR_ID, TLInputStickerSetEmpty.class);\n registerClass(TLInputStickerSetID.CONSTRUCTOR_ID, TLInputStickerSetID.class);\n registerClass(TLInputStickerSetShortName.CONSTRUCTOR_ID, TLInputStickerSetShortName.class);\n registerClass(TLInputStickeredMediaDocument.CONSTRUCTOR_ID, TLInputStickeredMediaDocument.class);\n registerClass(TLInputStickeredMediaPhoto.CONSTRUCTOR_ID, TLInputStickeredMediaPhoto.class);\n registerClass(TLInputUser.CONSTRUCTOR_ID, TLInputUser.class);\n registerClass(TLInputUserEmpty.CONSTRUCTOR_ID, TLInputUserEmpty.class);\n registerClass(TLInputUserSelf.CONSTRUCTOR_ID, TLInputUserSelf.class);\n registerClass(TLInputWebDocument.CONSTRUCTOR_ID, TLInputWebDocument.class);\n registerClass(TLInputWebFileLocation.CONSTRUCTOR_ID, TLInputWebFileLocation.class);\n registerClass(TLInvoice.CONSTRUCTOR_ID, TLInvoice.class);\n registerClass(TLKeyboardButton.CONSTRUCTOR_ID, TLKeyboardButton.class);\n registerClass(TLKeyboardButtonBuy.CONSTRUCTOR_ID, TLKeyboardButtonBuy.class);\n registerClass(TLKeyboardButtonCallback.CONSTRUCTOR_ID, TLKeyboardButtonCallback.class);\n registerClass(TLKeyboardButtonGame.CONSTRUCTOR_ID, TLKeyboardButtonGame.class);\n registerClass(TLKeyboardButtonRequestGeoLocation.CONSTRUCTOR_ID, TLKeyboardButtonRequestGeoLocation.class);\n registerClass(TLKeyboardButtonRequestPhone.CONSTRUCTOR_ID, TLKeyboardButtonRequestPhone.class);\n registerClass(TLKeyboardButtonRow.CONSTRUCTOR_ID, TLKeyboardButtonRow.class);\n registerClass(TLKeyboardButtonSwitchInline.CONSTRUCTOR_ID, TLKeyboardButtonSwitchInline.class);\n registerClass(TLKeyboardButtonUrl.CONSTRUCTOR_ID, TLKeyboardButtonUrl.class);\n registerClass(TLLabeledPrice.CONSTRUCTOR_ID, TLLabeledPrice.class);\n registerClass(TLMaskCoords.CONSTRUCTOR_ID, TLMaskCoords.class);\n registerClass(TLMessage.CONSTRUCTOR_ID, TLMessage.class);\n registerClass(TLMessageActionChannelCreate.CONSTRUCTOR_ID, TLMessageActionChannelCreate.class);\n registerClass(TLMessageActionChannelMigrateFrom.CONSTRUCTOR_ID, TLMessageActionChannelMigrateFrom.class);\n registerClass(TLMessageActionChatAddUser.CONSTRUCTOR_ID, TLMessageActionChatAddUser.class);\n registerClass(TLMessageActionChatCreate.CONSTRUCTOR_ID, TLMessageActionChatCreate.class);\n registerClass(TLMessageActionChatDeletePhoto.CONSTRUCTOR_ID, TLMessageActionChatDeletePhoto.class);\n registerClass(TLMessageActionChatDeleteUser.CONSTRUCTOR_ID, TLMessageActionChatDeleteUser.class);\n registerClass(TLMessageActionChatEditPhoto.CONSTRUCTOR_ID, TLMessageActionChatEditPhoto.class);\n registerClass(TLMessageActionChatEditTitle.CONSTRUCTOR_ID, TLMessageActionChatEditTitle.class);\n registerClass(TLMessageActionChatJoinedByLink.CONSTRUCTOR_ID, TLMessageActionChatJoinedByLink.class);\n registerClass(TLMessageActionChatMigrateTo.CONSTRUCTOR_ID, TLMessageActionChatMigrateTo.class);\n registerClass(TLMessageActionEmpty.CONSTRUCTOR_ID, TLMessageActionEmpty.class);\n registerClass(TLMessageActionGameScore.CONSTRUCTOR_ID, TLMessageActionGameScore.class);\n registerClass(TLMessageActionHistoryClear.CONSTRUCTOR_ID, TLMessageActionHistoryClear.class);\n registerClass(TLMessageActionPaymentSent.CONSTRUCTOR_ID, TLMessageActionPaymentSent.class);\n registerClass(TLMessageActionPaymentSentMe.CONSTRUCTOR_ID, TLMessageActionPaymentSentMe.class);\n registerClass(TLMessageActionPhoneCall.CONSTRUCTOR_ID, TLMessageActionPhoneCall.class);\n registerClass(TLMessageActionPinMessage.CONSTRUCTOR_ID, TLMessageActionPinMessage.class);\n registerClass(TLMessageEmpty.CONSTRUCTOR_ID, TLMessageEmpty.class);\n registerClass(TLMessageEntityBold.CONSTRUCTOR_ID, TLMessageEntityBold.class);\n registerClass(TLMessageEntityBotCommand.CONSTRUCTOR_ID, TLMessageEntityBotCommand.class);\n registerClass(TLMessageEntityCode.CONSTRUCTOR_ID, TLMessageEntityCode.class);\n registerClass(TLMessageEntityEmail.CONSTRUCTOR_ID, TLMessageEntityEmail.class);\n registerClass(TLMessageEntityHashtag.CONSTRUCTOR_ID, TLMessageEntityHashtag.class);\n registerClass(TLMessageEntityItalic.CONSTRUCTOR_ID, TLMessageEntityItalic.class);\n registerClass(TLMessageEntityMention.CONSTRUCTOR_ID, TLMessageEntityMention.class);\n registerClass(TLMessageEntityMentionName.CONSTRUCTOR_ID, TLMessageEntityMentionName.class);\n registerClass(TLMessageEntityPre.CONSTRUCTOR_ID, TLMessageEntityPre.class);\n registerClass(TLMessageEntityTextUrl.CONSTRUCTOR_ID, TLMessageEntityTextUrl.class);\n registerClass(TLMessageEntityUnknown.CONSTRUCTOR_ID, TLMessageEntityUnknown.class);\n registerClass(TLMessageEntityUrl.CONSTRUCTOR_ID, TLMessageEntityUrl.class);\n registerClass(TLMessageFwdHeader.CONSTRUCTOR_ID, TLMessageFwdHeader.class);\n registerClass(TLMessageMediaContact.CONSTRUCTOR_ID, TLMessageMediaContact.class);\n registerClass(TLMessageMediaDocument.CONSTRUCTOR_ID, TLMessageMediaDocument.class);\n registerClass(TLMessageMediaEmpty.CONSTRUCTOR_ID, TLMessageMediaEmpty.class);\n registerClass(TLMessageMediaGame.CONSTRUCTOR_ID, TLMessageMediaGame.class);\n registerClass(TLMessageMediaGeo.CONSTRUCTOR_ID, TLMessageMediaGeo.class);\n registerClass(TLMessageMediaInvoice.CONSTRUCTOR_ID, TLMessageMediaInvoice.class);\n registerClass(TLMessageMediaPhoto.CONSTRUCTOR_ID, TLMessageMediaPhoto.class);\n registerClass(TLMessageMediaUnsupported.CONSTRUCTOR_ID, TLMessageMediaUnsupported.class);\n registerClass(TLMessageMediaVenue.CONSTRUCTOR_ID, TLMessageMediaVenue.class);\n registerClass(TLMessageMediaWebPage.CONSTRUCTOR_ID, TLMessageMediaWebPage.class);\n registerClass(TLMessageRange.CONSTRUCTOR_ID, TLMessageRange.class);\n registerClass(TLMessageService.CONSTRUCTOR_ID, TLMessageService.class);\n registerClass(TLAffectedHistory.CONSTRUCTOR_ID, TLAffectedHistory.class);\n registerClass(TLAffectedMessages.CONSTRUCTOR_ID, TLAffectedMessages.class);\n registerClass(TLAllStickers.CONSTRUCTOR_ID, TLAllStickers.class);\n registerClass(TLAllStickersNotModified.CONSTRUCTOR_ID, TLAllStickersNotModified.class);\n registerClass(TLArchivedStickers.CONSTRUCTOR_ID, TLArchivedStickers.class);\n registerClass(TLBotCallbackAnswer.CONSTRUCTOR_ID, TLBotCallbackAnswer.class);\n registerClass(TLBotResults.CONSTRUCTOR_ID, TLBotResults.class);\n registerClass(TLChannelMessages.CONSTRUCTOR_ID, TLChannelMessages.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLChatFull.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLChatFull.class);\n registerClass(TLChats.CONSTRUCTOR_ID, TLChats.class);\n registerClass(TLChatsSlice.CONSTRUCTOR_ID, TLChatsSlice.class);\n registerClass(TLDhConfig.CONSTRUCTOR_ID, TLDhConfig.class);\n registerClass(TLDhConfigNotModified.CONSTRUCTOR_ID, TLDhConfigNotModified.class);\n registerClass(TLDialogs.CONSTRUCTOR_ID, TLDialogs.class);\n registerClass(TLDialogsSlice.CONSTRUCTOR_ID, TLDialogsSlice.class);\n registerClass(TLFeaturedStickers.CONSTRUCTOR_ID, TLFeaturedStickers.class);\n registerClass(TLFeaturedStickersNotModified.CONSTRUCTOR_ID, TLFeaturedStickersNotModified.class);\n registerClass(TLFoundGifs.CONSTRUCTOR_ID, TLFoundGifs.class);\n registerClass(TLHighScores.CONSTRUCTOR_ID, TLHighScores.class);\n registerClass(TLMessageEditData.CONSTRUCTOR_ID, TLMessageEditData.class);\n registerClass(TLMessages.CONSTRUCTOR_ID, TLMessages.class);\n registerClass(TLMessagesSlice.CONSTRUCTOR_ID, TLMessagesSlice.class);\n registerClass(TLPeerDialogs.CONSTRUCTOR_ID, TLPeerDialogs.class);\n registerClass(TLRecentStickers.CONSTRUCTOR_ID, TLRecentStickers.class);\n registerClass(TLRecentStickersNotModified.CONSTRUCTOR_ID, TLRecentStickersNotModified.class);\n registerClass(TLSavedGifs.CONSTRUCTOR_ID, TLSavedGifs.class);\n registerClass(TLSavedGifsNotModified.CONSTRUCTOR_ID, TLSavedGifsNotModified.class);\n registerClass(TLSentEncryptedFile.CONSTRUCTOR_ID, TLSentEncryptedFile.class);\n registerClass(TLSentEncryptedMessage.CONSTRUCTOR_ID, TLSentEncryptedMessage.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLStickerSet.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLStickerSet.class);\n registerClass(TLStickerSetInstallResultArchive.CONSTRUCTOR_ID, TLStickerSetInstallResultArchive.class);\n registerClass(TLStickerSetInstallResultSuccess.CONSTRUCTOR_ID, TLStickerSetInstallResultSuccess.class);\n registerClass(TLStickers.CONSTRUCTOR_ID, TLStickers.class);\n registerClass(TLStickersNotModified.CONSTRUCTOR_ID, TLStickersNotModified.class);\n registerClass(TLNearestDc.CONSTRUCTOR_ID, TLNearestDc.class);\n registerClass(TLNotifyAll.CONSTRUCTOR_ID, TLNotifyAll.class);\n registerClass(TLNotifyChats.CONSTRUCTOR_ID, TLNotifyChats.class);\n registerClass(TLNotifyPeer.CONSTRUCTOR_ID, TLNotifyPeer.class);\n registerClass(TLNotifyUsers.CONSTRUCTOR_ID, TLNotifyUsers.class);\n registerClass(TLPageBlockAnchor.CONSTRUCTOR_ID, TLPageBlockAnchor.class);\n registerClass(TLPageBlockAuthorDate.CONSTRUCTOR_ID, TLPageBlockAuthorDate.class);\n registerClass(TLPageBlockBlockquote.CONSTRUCTOR_ID, TLPageBlockBlockquote.class);\n registerClass(TLPageBlockChannel.CONSTRUCTOR_ID, TLPageBlockChannel.class);\n registerClass(TLPageBlockCollage.CONSTRUCTOR_ID, TLPageBlockCollage.class);\n registerClass(TLPageBlockCover.CONSTRUCTOR_ID, TLPageBlockCover.class);\n registerClass(TLPageBlockDivider.CONSTRUCTOR_ID, TLPageBlockDivider.class);\n registerClass(TLPageBlockEmbed.CONSTRUCTOR_ID, TLPageBlockEmbed.class);\n registerClass(TLPageBlockEmbedPost.CONSTRUCTOR_ID, TLPageBlockEmbedPost.class);\n registerClass(TLPageBlockFooter.CONSTRUCTOR_ID, TLPageBlockFooter.class);\n registerClass(TLPageBlockHeader.CONSTRUCTOR_ID, TLPageBlockHeader.class);\n registerClass(TLPageBlockList.CONSTRUCTOR_ID, TLPageBlockList.class);\n registerClass(TLPageBlockParagraph.CONSTRUCTOR_ID, TLPageBlockParagraph.class);\n registerClass(TLPageBlockPhoto.CONSTRUCTOR_ID, TLPageBlockPhoto.class);\n registerClass(TLPageBlockPreformatted.CONSTRUCTOR_ID, TLPageBlockPreformatted.class);\n registerClass(TLPageBlockPullquote.CONSTRUCTOR_ID, TLPageBlockPullquote.class);\n registerClass(TLPageBlockSlideshow.CONSTRUCTOR_ID, TLPageBlockSlideshow.class);\n registerClass(TLPageBlockSubheader.CONSTRUCTOR_ID, TLPageBlockSubheader.class);\n registerClass(TLPageBlockSubtitle.CONSTRUCTOR_ID, TLPageBlockSubtitle.class);\n registerClass(TLPageBlockTitle.CONSTRUCTOR_ID, TLPageBlockTitle.class);\n registerClass(TLPageBlockUnsupported.CONSTRUCTOR_ID, TLPageBlockUnsupported.class);\n registerClass(TLPageBlockVideo.CONSTRUCTOR_ID, TLPageBlockVideo.class);\n registerClass(TLPageFull.CONSTRUCTOR_ID, TLPageFull.class);\n registerClass(TLPagePart.CONSTRUCTOR_ID, TLPagePart.class);\n registerClass(TLPaymentCharge.CONSTRUCTOR_ID, TLPaymentCharge.class);\n registerClass(TLPaymentRequestedInfo.CONSTRUCTOR_ID, TLPaymentRequestedInfo.class);\n registerClass(TLPaymentSavedCredentialsCard.CONSTRUCTOR_ID, TLPaymentSavedCredentialsCard.class);\n registerClass(TLPaymentForm.CONSTRUCTOR_ID, TLPaymentForm.class);\n registerClass(TLPaymentReceipt.CONSTRUCTOR_ID, TLPaymentReceipt.class);\n registerClass(TLPaymentResult.CONSTRUCTOR_ID, TLPaymentResult.class);\n registerClass(TLPaymentVerficationNeeded.CONSTRUCTOR_ID, TLPaymentVerficationNeeded.class);\n registerClass(TLSavedInfo.CONSTRUCTOR_ID, TLSavedInfo.class);\n registerClass(TLValidatedRequestedInfo.CONSTRUCTOR_ID, TLValidatedRequestedInfo.class);\n registerClass(TLPeerChannel.CONSTRUCTOR_ID, TLPeerChannel.class);\n registerClass(TLPeerChat.CONSTRUCTOR_ID, TLPeerChat.class);\n registerClass(TLPeerNotifyEventsAll.CONSTRUCTOR_ID, TLPeerNotifyEventsAll.class);\n registerClass(TLPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLPeerNotifyEventsEmpty.class);\n registerClass(TLPeerNotifySettings.CONSTRUCTOR_ID, TLPeerNotifySettings.class);\n registerClass(TLPeerNotifySettingsEmpty.CONSTRUCTOR_ID, TLPeerNotifySettingsEmpty.class);\n registerClass(TLPeerSettings.CONSTRUCTOR_ID, TLPeerSettings.class);\n registerClass(TLPeerUser.CONSTRUCTOR_ID, TLPeerUser.class);\n registerClass(com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.class);\n registerClass(TLPhoneCall.CONSTRUCTOR_ID, TLPhoneCall.class);\n registerClass(TLPhoneCallAccepted.CONSTRUCTOR_ID, TLPhoneCallAccepted.class);\n registerClass(TLPhoneCallDiscardReasonBusy.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonBusy.class);\n registerClass(TLPhoneCallDiscardReasonDisconnect.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonDisconnect.class);\n registerClass(TLPhoneCallDiscardReasonHangup.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonHangup.class);\n registerClass(TLPhoneCallDiscardReasonMissed.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonMissed.class);\n registerClass(TLPhoneCallDiscarded.CONSTRUCTOR_ID, TLPhoneCallDiscarded.class);\n registerClass(TLPhoneCallEmpty.CONSTRUCTOR_ID, TLPhoneCallEmpty.class);\n registerClass(TLPhoneCallProtocol.CONSTRUCTOR_ID, TLPhoneCallProtocol.class);\n registerClass(TLPhoneCallRequested.CONSTRUCTOR_ID, TLPhoneCallRequested.class);\n registerClass(TLPhoneCallWaiting.CONSTRUCTOR_ID, TLPhoneCallWaiting.class);\n registerClass(TLPhoneConnection.CONSTRUCTOR_ID, TLPhoneConnection.class);\n registerClass(TLPhoto.CONSTRUCTOR_ID, TLPhoto.class);\n registerClass(TLPhotoCachedSize.CONSTRUCTOR_ID, TLPhotoCachedSize.class);\n registerClass(TLPhotoEmpty.CONSTRUCTOR_ID, TLPhotoEmpty.class);\n registerClass(TLPhotoSize.CONSTRUCTOR_ID, TLPhotoSize.class);\n registerClass(TLPhotoSizeEmpty.CONSTRUCTOR_ID, TLPhotoSizeEmpty.class);\n registerClass(com.github.badoualy.telegram.tl.api.photos.TLPhoto.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.photos.TLPhoto.class);\n registerClass(TLPhotos.CONSTRUCTOR_ID, TLPhotos.class);\n registerClass(TLPhotosSlice.CONSTRUCTOR_ID, TLPhotosSlice.class);\n registerClass(TLPostAddress.CONSTRUCTOR_ID, TLPostAddress.class);\n registerClass(TLPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLPrivacyKeyChatInvite.class);\n registerClass(TLPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLPrivacyKeyPhoneCall.class);\n registerClass(TLPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLPrivacyKeyStatusTimestamp.class);\n registerClass(TLPrivacyValueAllowAll.CONSTRUCTOR_ID, TLPrivacyValueAllowAll.class);\n registerClass(TLPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLPrivacyValueAllowContacts.class);\n registerClass(TLPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLPrivacyValueAllowUsers.class);\n registerClass(TLPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLPrivacyValueDisallowAll.class);\n registerClass(TLPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLPrivacyValueDisallowContacts.class);\n registerClass(TLPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLPrivacyValueDisallowUsers.class);\n registerClass(TLReceivedNotifyMessage.CONSTRUCTOR_ID, TLReceivedNotifyMessage.class);\n registerClass(TLReplyInlineMarkup.CONSTRUCTOR_ID, TLReplyInlineMarkup.class);\n registerClass(TLReplyKeyboardForceReply.CONSTRUCTOR_ID, TLReplyKeyboardForceReply.class);\n registerClass(TLReplyKeyboardHide.CONSTRUCTOR_ID, TLReplyKeyboardHide.class);\n registerClass(TLReplyKeyboardMarkup.CONSTRUCTOR_ID, TLReplyKeyboardMarkup.class);\n registerClass(TLSendMessageCancelAction.CONSTRUCTOR_ID, TLSendMessageCancelAction.class);\n registerClass(TLSendMessageChooseContactAction.CONSTRUCTOR_ID, TLSendMessageChooseContactAction.class);\n registerClass(TLSendMessageGamePlayAction.CONSTRUCTOR_ID, TLSendMessageGamePlayAction.class);\n registerClass(TLSendMessageGeoLocationAction.CONSTRUCTOR_ID, TLSendMessageGeoLocationAction.class);\n registerClass(TLSendMessageRecordAudioAction.CONSTRUCTOR_ID, TLSendMessageRecordAudioAction.class);\n registerClass(TLSendMessageRecordRoundAction.CONSTRUCTOR_ID, TLSendMessageRecordRoundAction.class);\n registerClass(TLSendMessageRecordVideoAction.CONSTRUCTOR_ID, TLSendMessageRecordVideoAction.class);\n registerClass(TLSendMessageTypingAction.CONSTRUCTOR_ID, TLSendMessageTypingAction.class);\n registerClass(TLSendMessageUploadAudioAction.CONSTRUCTOR_ID, TLSendMessageUploadAudioAction.class);\n registerClass(TLSendMessageUploadDocumentAction.CONSTRUCTOR_ID, TLSendMessageUploadDocumentAction.class);\n registerClass(TLSendMessageUploadPhotoAction.CONSTRUCTOR_ID, TLSendMessageUploadPhotoAction.class);\n registerClass(TLSendMessageUploadRoundAction.CONSTRUCTOR_ID, TLSendMessageUploadRoundAction.class);\n registerClass(TLSendMessageUploadVideoAction.CONSTRUCTOR_ID, TLSendMessageUploadVideoAction.class);\n registerClass(TLShippingOption.CONSTRUCTOR_ID, TLShippingOption.class);\n registerClass(TLStickerPack.CONSTRUCTOR_ID, TLStickerPack.class);\n registerClass(TLStickerSet.CONSTRUCTOR_ID, TLStickerSet.class);\n registerClass(TLStickerSetCovered.CONSTRUCTOR_ID, TLStickerSetCovered.class);\n registerClass(TLStickerSetMultiCovered.CONSTRUCTOR_ID, TLStickerSetMultiCovered.class);\n registerClass(TLFileGif.CONSTRUCTOR_ID, TLFileGif.class);\n registerClass(TLFileJpeg.CONSTRUCTOR_ID, TLFileJpeg.class);\n registerClass(TLFileMov.CONSTRUCTOR_ID, TLFileMov.class);\n registerClass(TLFileMp3.CONSTRUCTOR_ID, TLFileMp3.class);\n registerClass(TLFileMp4.CONSTRUCTOR_ID, TLFileMp4.class);\n registerClass(TLFilePartial.CONSTRUCTOR_ID, TLFilePartial.class);\n registerClass(TLFilePdf.CONSTRUCTOR_ID, TLFilePdf.class);\n registerClass(TLFilePng.CONSTRUCTOR_ID, TLFilePng.class);\n registerClass(TLFileUnknown.CONSTRUCTOR_ID, TLFileUnknown.class);\n registerClass(TLFileWebp.CONSTRUCTOR_ID, TLFileWebp.class);\n registerClass(TLTextBold.CONSTRUCTOR_ID, TLTextBold.class);\n registerClass(TLTextConcat.CONSTRUCTOR_ID, TLTextConcat.class);\n registerClass(TLTextEmail.CONSTRUCTOR_ID, TLTextEmail.class);\n registerClass(TLTextEmpty.CONSTRUCTOR_ID, TLTextEmpty.class);\n registerClass(TLTextFixed.CONSTRUCTOR_ID, TLTextFixed.class);\n registerClass(TLTextItalic.CONSTRUCTOR_ID, TLTextItalic.class);\n registerClass(TLTextPlain.CONSTRUCTOR_ID, TLTextPlain.class);\n registerClass(TLTextStrike.CONSTRUCTOR_ID, TLTextStrike.class);\n registerClass(TLTextUnderline.CONSTRUCTOR_ID, TLTextUnderline.class);\n registerClass(TLTextUrl.CONSTRUCTOR_ID, TLTextUrl.class);\n registerClass(TLTopPeer.CONSTRUCTOR_ID, TLTopPeer.class);\n registerClass(TLTopPeerCategoryBotsInline.CONSTRUCTOR_ID, TLTopPeerCategoryBotsInline.class);\n registerClass(TLTopPeerCategoryBotsPM.CONSTRUCTOR_ID, TLTopPeerCategoryBotsPM.class);\n registerClass(TLTopPeerCategoryChannels.CONSTRUCTOR_ID, TLTopPeerCategoryChannels.class);\n registerClass(TLTopPeerCategoryCorrespondents.CONSTRUCTOR_ID, TLTopPeerCategoryCorrespondents.class);\n registerClass(TLTopPeerCategoryGroups.CONSTRUCTOR_ID, TLTopPeerCategoryGroups.class);\n registerClass(TLTopPeerCategoryPeers.CONSTRUCTOR_ID, TLTopPeerCategoryPeers.class);\n registerClass(TLUpdateBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateBotCallbackQuery.class);\n registerClass(TLUpdateBotInlineQuery.CONSTRUCTOR_ID, TLUpdateBotInlineQuery.class);\n registerClass(TLUpdateBotInlineSend.CONSTRUCTOR_ID, TLUpdateBotInlineSend.class);\n registerClass(TLUpdateBotPrecheckoutQuery.CONSTRUCTOR_ID, TLUpdateBotPrecheckoutQuery.class);\n registerClass(TLUpdateBotShippingQuery.CONSTRUCTOR_ID, TLUpdateBotShippingQuery.class);\n registerClass(TLUpdateBotWebhookJSON.CONSTRUCTOR_ID, TLUpdateBotWebhookJSON.class);\n registerClass(TLUpdateBotWebhookJSONQuery.CONSTRUCTOR_ID, TLUpdateBotWebhookJSONQuery.class);\n registerClass(TLUpdateChannel.CONSTRUCTOR_ID, TLUpdateChannel.class);\n registerClass(TLUpdateChannelMessageViews.CONSTRUCTOR_ID, TLUpdateChannelMessageViews.class);\n registerClass(TLUpdateChannelPinnedMessage.CONSTRUCTOR_ID, TLUpdateChannelPinnedMessage.class);\n registerClass(TLUpdateChannelTooLong.CONSTRUCTOR_ID, TLUpdateChannelTooLong.class);\n registerClass(TLUpdateChannelWebPage.CONSTRUCTOR_ID, TLUpdateChannelWebPage.class);\n registerClass(TLUpdateChatAdmins.CONSTRUCTOR_ID, TLUpdateChatAdmins.class);\n registerClass(TLUpdateChatParticipantAdd.CONSTRUCTOR_ID, TLUpdateChatParticipantAdd.class);\n registerClass(TLUpdateChatParticipantAdmin.CONSTRUCTOR_ID, TLUpdateChatParticipantAdmin.class);\n registerClass(TLUpdateChatParticipantDelete.CONSTRUCTOR_ID, TLUpdateChatParticipantDelete.class);\n registerClass(TLUpdateChatParticipants.CONSTRUCTOR_ID, TLUpdateChatParticipants.class);\n registerClass(TLUpdateChatUserTyping.CONSTRUCTOR_ID, TLUpdateChatUserTyping.class);\n registerClass(TLUpdateConfig.CONSTRUCTOR_ID, TLUpdateConfig.class);\n registerClass(TLUpdateContactLink.CONSTRUCTOR_ID, TLUpdateContactLink.class);\n registerClass(TLUpdateContactRegistered.CONSTRUCTOR_ID, TLUpdateContactRegistered.class);\n registerClass(TLUpdateDcOptions.CONSTRUCTOR_ID, TLUpdateDcOptions.class);\n registerClass(TLUpdateDeleteChannelMessages.CONSTRUCTOR_ID, TLUpdateDeleteChannelMessages.class);\n registerClass(TLUpdateDeleteMessages.CONSTRUCTOR_ID, TLUpdateDeleteMessages.class);\n registerClass(TLUpdateDialogPinned.CONSTRUCTOR_ID, TLUpdateDialogPinned.class);\n registerClass(TLUpdateDraftMessage.CONSTRUCTOR_ID, TLUpdateDraftMessage.class);\n registerClass(TLUpdateEditChannelMessage.CONSTRUCTOR_ID, TLUpdateEditChannelMessage.class);\n registerClass(TLUpdateEditMessage.CONSTRUCTOR_ID, TLUpdateEditMessage.class);\n registerClass(TLUpdateEncryptedChatTyping.CONSTRUCTOR_ID, TLUpdateEncryptedChatTyping.class);\n registerClass(TLUpdateEncryptedMessagesRead.CONSTRUCTOR_ID, TLUpdateEncryptedMessagesRead.class);\n registerClass(TLUpdateEncryption.CONSTRUCTOR_ID, TLUpdateEncryption.class);\n registerClass(TLUpdateInlineBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateInlineBotCallbackQuery.class);\n registerClass(TLUpdateMessageID.CONSTRUCTOR_ID, TLUpdateMessageID.class);\n registerClass(TLUpdateNewChannelMessage.CONSTRUCTOR_ID, TLUpdateNewChannelMessage.class);\n registerClass(TLUpdateNewEncryptedMessage.CONSTRUCTOR_ID, TLUpdateNewEncryptedMessage.class);\n registerClass(TLUpdateNewMessage.CONSTRUCTOR_ID, TLUpdateNewMessage.class);\n registerClass(TLUpdateNewStickerSet.CONSTRUCTOR_ID, TLUpdateNewStickerSet.class);\n registerClass(TLUpdateNotifySettings.CONSTRUCTOR_ID, TLUpdateNotifySettings.class);\n registerClass(TLUpdatePhoneCall.CONSTRUCTOR_ID, TLUpdatePhoneCall.class);\n registerClass(TLUpdatePinnedDialogs.CONSTRUCTOR_ID, TLUpdatePinnedDialogs.class);\n registerClass(TLUpdatePrivacy.CONSTRUCTOR_ID, TLUpdatePrivacy.class);\n registerClass(TLUpdatePtsChanged.CONSTRUCTOR_ID, TLUpdatePtsChanged.class);\n registerClass(TLUpdateReadChannelInbox.CONSTRUCTOR_ID, TLUpdateReadChannelInbox.class);\n registerClass(TLUpdateReadChannelOutbox.CONSTRUCTOR_ID, TLUpdateReadChannelOutbox.class);\n registerClass(TLUpdateReadFeaturedStickers.CONSTRUCTOR_ID, TLUpdateReadFeaturedStickers.class);\n registerClass(TLUpdateReadHistoryInbox.CONSTRUCTOR_ID, TLUpdateReadHistoryInbox.class);\n registerClass(TLUpdateReadHistoryOutbox.CONSTRUCTOR_ID, TLUpdateReadHistoryOutbox.class);\n registerClass(TLUpdateReadMessagesContents.CONSTRUCTOR_ID, TLUpdateReadMessagesContents.class);\n registerClass(TLUpdateRecentStickers.CONSTRUCTOR_ID, TLUpdateRecentStickers.class);\n registerClass(TLUpdateSavedGifs.CONSTRUCTOR_ID, TLUpdateSavedGifs.class);\n registerClass(TLUpdateServiceNotification.CONSTRUCTOR_ID, TLUpdateServiceNotification.class);\n registerClass(TLUpdateShort.CONSTRUCTOR_ID, TLUpdateShort.class);\n registerClass(TLUpdateShortChatMessage.CONSTRUCTOR_ID, TLUpdateShortChatMessage.class);\n registerClass(TLUpdateShortMessage.CONSTRUCTOR_ID, TLUpdateShortMessage.class);\n registerClass(TLUpdateShortSentMessage.CONSTRUCTOR_ID, TLUpdateShortSentMessage.class);\n registerClass(TLUpdateStickerSets.CONSTRUCTOR_ID, TLUpdateStickerSets.class);\n registerClass(TLUpdateStickerSetsOrder.CONSTRUCTOR_ID, TLUpdateStickerSetsOrder.class);\n registerClass(TLUpdateUserBlocked.CONSTRUCTOR_ID, TLUpdateUserBlocked.class);\n registerClass(TLUpdateUserName.CONSTRUCTOR_ID, TLUpdateUserName.class);\n registerClass(TLUpdateUserPhone.CONSTRUCTOR_ID, TLUpdateUserPhone.class);\n registerClass(TLUpdateUserPhoto.CONSTRUCTOR_ID, TLUpdateUserPhoto.class);\n registerClass(TLUpdateUserStatus.CONSTRUCTOR_ID, TLUpdateUserStatus.class);\n registerClass(TLUpdateUserTyping.CONSTRUCTOR_ID, TLUpdateUserTyping.class);\n registerClass(TLUpdateWebPage.CONSTRUCTOR_ID, TLUpdateWebPage.class);\n registerClass(TLUpdates.CONSTRUCTOR_ID, TLUpdates.class);\n registerClass(TLChannelDifference.CONSTRUCTOR_ID, TLChannelDifference.class);\n registerClass(TLChannelDifferenceEmpty.CONSTRUCTOR_ID, TLChannelDifferenceEmpty.class);\n registerClass(TLChannelDifferenceTooLong.CONSTRUCTOR_ID, TLChannelDifferenceTooLong.class);\n registerClass(TLDifference.CONSTRUCTOR_ID, TLDifference.class);\n registerClass(TLDifferenceEmpty.CONSTRUCTOR_ID, TLDifferenceEmpty.class);\n registerClass(TLDifferenceSlice.CONSTRUCTOR_ID, TLDifferenceSlice.class);\n registerClass(TLDifferenceTooLong.CONSTRUCTOR_ID, TLDifferenceTooLong.class);\n registerClass(TLState.CONSTRUCTOR_ID, TLState.class);\n registerClass(TLUpdatesCombined.CONSTRUCTOR_ID, TLUpdatesCombined.class);\n registerClass(TLUpdatesTooLong.CONSTRUCTOR_ID, TLUpdatesTooLong.class);\n registerClass(TLCdnFile.CONSTRUCTOR_ID, TLCdnFile.class);\n registerClass(TLCdnFileReuploadNeeded.CONSTRUCTOR_ID, TLCdnFileReuploadNeeded.class);\n registerClass(TLFile.CONSTRUCTOR_ID, TLFile.class);\n registerClass(TLFileCdnRedirect.CONSTRUCTOR_ID, TLFileCdnRedirect.class);\n registerClass(TLWebFile.CONSTRUCTOR_ID, TLWebFile.class);\n registerClass(TLUser.CONSTRUCTOR_ID, TLUser.class);\n registerClass(TLUserEmpty.CONSTRUCTOR_ID, TLUserEmpty.class);\n registerClass(TLUserFull.CONSTRUCTOR_ID, TLUserFull.class);\n registerClass(TLUserProfilePhoto.CONSTRUCTOR_ID, TLUserProfilePhoto.class);\n registerClass(TLUserProfilePhotoEmpty.CONSTRUCTOR_ID, TLUserProfilePhotoEmpty.class);\n registerClass(TLUserStatusEmpty.CONSTRUCTOR_ID, TLUserStatusEmpty.class);\n registerClass(TLUserStatusLastMonth.CONSTRUCTOR_ID, TLUserStatusLastMonth.class);\n registerClass(TLUserStatusLastWeek.CONSTRUCTOR_ID, TLUserStatusLastWeek.class);\n registerClass(TLUserStatusOffline.CONSTRUCTOR_ID, TLUserStatusOffline.class);\n registerClass(TLUserStatusOnline.CONSTRUCTOR_ID, TLUserStatusOnline.class);\n registerClass(TLUserStatusRecently.CONSTRUCTOR_ID, TLUserStatusRecently.class);\n registerClass(TLWallPaper.CONSTRUCTOR_ID, TLWallPaper.class);\n registerClass(TLWallPaperSolid.CONSTRUCTOR_ID, TLWallPaperSolid.class);\n registerClass(TLWebDocument.CONSTRUCTOR_ID, TLWebDocument.class);\n registerClass(TLWebPage.CONSTRUCTOR_ID, TLWebPage.class);\n registerClass(TLWebPageEmpty.CONSTRUCTOR_ID, TLWebPageEmpty.class);\n registerClass(TLWebPageNotModified.CONSTRUCTOR_ID, TLWebPageNotModified.class);\n registerClass(TLWebPagePending.CONSTRUCTOR_ID, TLWebPagePending.class);\n }\n}\n"} {"task_id": "Java_100", "language": "Java", "task_type": "method_body", "source_file": "java/github/badoualy/kotlogram/tl/src/main/java/com/github/badoualy/telegram/tl/api/TLApiContext.java", "mask_start_position": 7048, "mask_end_position": 7165, "canonical_solution": "{\n if (instance == null) {\n instance = new TLApiContext();\n }\n return instance;\n }", "pre_mask_code": "package com.github.badoualy.telegram.tl.api;\n\nimport com.github.badoualy.telegram.tl.TLContext;\nimport com.github.badoualy.telegram.tl.api.account.TLAuthorizations;\nimport com.github.badoualy.telegram.tl.api.account.TLNoPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordInputSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPrivacyRules;\nimport com.github.badoualy.telegram.tl.api.account.TLTmpPassword;\nimport com.github.badoualy.telegram.tl.api.auth.TLCheckedPhone;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.auth.TLExportedAuthorization;\nimport com.github.badoualy.telegram.tl.api.auth.TLPasswordRecovery;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCode;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeApp;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.channels.TLChannelParticipants;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlocked;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlockedSlice;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContactsNotModified;\nimport com.github.badoualy.telegram.tl.api.contacts.TLFound;\nimport com.github.badoualy.telegram.tl.api.contacts.TLImportedContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLLink;\nimport com.github.badoualy.telegram.tl.api.contacts.TLResolvedPeer;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeers;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeersNotModified;\nimport com.github.badoualy.telegram.tl.api.help.TLAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLInviteText;\nimport com.github.badoualy.telegram.tl.api.help.TLNoAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLSupport;\nimport com.github.badoualy.telegram.tl.api.help.TLTermsOfService;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedHistory;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLArchivedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotCallbackAnswer;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotResults;\nimport com.github.badoualy.telegram.tl.api.messages.TLChannelMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLChats;\nimport com.github.badoualy.telegram.tl.api.messages.TLChatsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfig;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfigNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLFoundGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLHighScores;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessageEditData;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessagesSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLPeerDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifsNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedFile;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedMessage;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultArchive;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultSuccess;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentForm;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentReceipt;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentResult;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentVerficationNeeded;\nimport com.github.badoualy.telegram.tl.api.payments.TLSavedInfo;\nimport com.github.badoualy.telegram.tl.api.payments.TLValidatedRequestedInfo;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotos;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotosSlice;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileGif;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileJpeg;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMov;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp3;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp4;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePartial;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePdf;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePng;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileUnknown;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileWebp;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceSlice;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLState;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFileReuploadNeeded;\nimport com.github.badoualy.telegram.tl.api.upload.TLFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLFileCdnRedirect;\nimport com.github.badoualy.telegram.tl.api.upload.TLWebFile;\n\n/**\n * @author Yannick Badoual example@nnthink.com\n * @see http://example.com\n */\n@SuppressWarnings(\"unused\")\npublic class TLApiContext extends TLContext {\n\n private static TLApiContext instance;\n\n public TLApiContext() {\n super(543);\n }\n\n public static TLApiContext getInstance() ", "post_mask_code": "\n\n @Override\n public void init() {\n registerClass(TLAuthorizations.CONSTRUCTOR_ID, TLAuthorizations.class);\n registerClass(TLNoPassword.CONSTRUCTOR_ID, TLNoPassword.class);\n registerClass(TLPassword.CONSTRUCTOR_ID, TLPassword.class);\n registerClass(TLPasswordInputSettings.CONSTRUCTOR_ID, TLPasswordInputSettings.class);\n registerClass(TLPasswordSettings.CONSTRUCTOR_ID, TLPasswordSettings.class);\n registerClass(TLPrivacyRules.CONSTRUCTOR_ID, TLPrivacyRules.class);\n registerClass(TLTmpPassword.CONSTRUCTOR_ID, TLTmpPassword.class);\n registerClass(TLAccountDaysTTL.CONSTRUCTOR_ID, TLAccountDaysTTL.class);\n registerClass(com.github.badoualy.telegram.tl.api.auth.TLAuthorization.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.auth.TLAuthorization.class);\n registerClass(TLCheckedPhone.CONSTRUCTOR_ID, TLCheckedPhone.class);\n registerClass(TLCodeTypeCall.CONSTRUCTOR_ID, TLCodeTypeCall.class);\n registerClass(TLCodeTypeFlashCall.CONSTRUCTOR_ID, TLCodeTypeFlashCall.class);\n registerClass(TLCodeTypeSms.CONSTRUCTOR_ID, TLCodeTypeSms.class);\n registerClass(TLExportedAuthorization.CONSTRUCTOR_ID, TLExportedAuthorization.class);\n registerClass(TLPasswordRecovery.CONSTRUCTOR_ID, TLPasswordRecovery.class);\n registerClass(TLSentCode.CONSTRUCTOR_ID, TLSentCode.class);\n registerClass(TLSentCodeTypeApp.CONSTRUCTOR_ID, TLSentCodeTypeApp.class);\n registerClass(TLSentCodeTypeCall.CONSTRUCTOR_ID, TLSentCodeTypeCall.class);\n registerClass(TLSentCodeTypeFlashCall.CONSTRUCTOR_ID, TLSentCodeTypeFlashCall.class);\n registerClass(TLSentCodeTypeSms.CONSTRUCTOR_ID, TLSentCodeTypeSms.class);\n registerClass(TLAuthorization.CONSTRUCTOR_ID, TLAuthorization.class);\n registerClass(TLBotCommand.CONSTRUCTOR_ID, TLBotCommand.class);\n registerClass(TLBotInfo.CONSTRUCTOR_ID, TLBotInfo.class);\n registerClass(TLBotInlineMediaResult.CONSTRUCTOR_ID, TLBotInlineMediaResult.class);\n registerClass(TLBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLBotInlineMessageMediaAuto.class);\n registerClass(TLBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLBotInlineMessageMediaContact.class);\n registerClass(TLBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLBotInlineMessageMediaGeo.class);\n registerClass(TLBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLBotInlineMessageMediaVenue.class);\n registerClass(TLBotInlineMessageText.CONSTRUCTOR_ID, TLBotInlineMessageText.class);\n registerClass(TLBotInlineResult.CONSTRUCTOR_ID, TLBotInlineResult.class);\n registerClass(TLCdnConfig.CONSTRUCTOR_ID, TLCdnConfig.class);\n registerClass(TLCdnPublicKey.CONSTRUCTOR_ID, TLCdnPublicKey.class);\n registerClass(TLChannel.CONSTRUCTOR_ID, TLChannel.class);\n registerClass(TLChannelForbidden.CONSTRUCTOR_ID, TLChannelForbidden.class);\n registerClass(TLChannelFull.CONSTRUCTOR_ID, TLChannelFull.class);\n registerClass(TLChannelMessagesFilter.CONSTRUCTOR_ID, TLChannelMessagesFilter.class);\n registerClass(TLChannelMessagesFilterEmpty.CONSTRUCTOR_ID, TLChannelMessagesFilterEmpty.class);\n registerClass(TLChannelParticipant.CONSTRUCTOR_ID, TLChannelParticipant.class);\n registerClass(TLChannelParticipantCreator.CONSTRUCTOR_ID, TLChannelParticipantCreator.class);\n registerClass(TLChannelParticipantEditor.CONSTRUCTOR_ID, TLChannelParticipantEditor.class);\n registerClass(TLChannelParticipantKicked.CONSTRUCTOR_ID, TLChannelParticipantKicked.class);\n registerClass(TLChannelParticipantModerator.CONSTRUCTOR_ID, TLChannelParticipantModerator.class);\n registerClass(TLChannelParticipantSelf.CONSTRUCTOR_ID, TLChannelParticipantSelf.class);\n registerClass(TLChannelParticipantsAdmins.CONSTRUCTOR_ID, TLChannelParticipantsAdmins.class);\n registerClass(TLChannelParticipantsBots.CONSTRUCTOR_ID, TLChannelParticipantsBots.class);\n registerClass(TLChannelParticipantsKicked.CONSTRUCTOR_ID, TLChannelParticipantsKicked.class);\n registerClass(TLChannelParticipantsRecent.CONSTRUCTOR_ID, TLChannelParticipantsRecent.class);\n registerClass(TLChannelRoleEditor.CONSTRUCTOR_ID, TLChannelRoleEditor.class);\n registerClass(TLChannelRoleEmpty.CONSTRUCTOR_ID, TLChannelRoleEmpty.class);\n registerClass(TLChannelRoleModerator.CONSTRUCTOR_ID, TLChannelRoleModerator.class);\n registerClass(com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.class);\n registerClass(TLChannelParticipants.CONSTRUCTOR_ID, TLChannelParticipants.class);\n registerClass(TLChat.CONSTRUCTOR_ID, TLChat.class);\n registerClass(TLChatEmpty.CONSTRUCTOR_ID, TLChatEmpty.class);\n registerClass(TLChatForbidden.CONSTRUCTOR_ID, TLChatForbidden.class);\n registerClass(TLChatFull.CONSTRUCTOR_ID, TLChatFull.class);\n registerClass(TLChatInvite.CONSTRUCTOR_ID, TLChatInvite.class);\n registerClass(TLChatInviteAlready.CONSTRUCTOR_ID, TLChatInviteAlready.class);\n registerClass(TLChatInviteEmpty.CONSTRUCTOR_ID, TLChatInviteEmpty.class);\n registerClass(TLChatInviteExported.CONSTRUCTOR_ID, TLChatInviteExported.class);\n registerClass(TLChatParticipant.CONSTRUCTOR_ID, TLChatParticipant.class);\n registerClass(TLChatParticipantAdmin.CONSTRUCTOR_ID, TLChatParticipantAdmin.class);\n registerClass(TLChatParticipantCreator.CONSTRUCTOR_ID, TLChatParticipantCreator.class);\n registerClass(TLChatParticipants.CONSTRUCTOR_ID, TLChatParticipants.class);\n registerClass(TLChatParticipantsForbidden.CONSTRUCTOR_ID, TLChatParticipantsForbidden.class);\n registerClass(TLChatPhoto.CONSTRUCTOR_ID, TLChatPhoto.class);\n registerClass(TLChatPhotoEmpty.CONSTRUCTOR_ID, TLChatPhotoEmpty.class);\n registerClass(TLConfig.CONSTRUCTOR_ID, TLConfig.class);\n registerClass(TLContact.CONSTRUCTOR_ID, TLContact.class);\n registerClass(TLContactBlocked.CONSTRUCTOR_ID, TLContactBlocked.class);\n registerClass(TLContactLinkContact.CONSTRUCTOR_ID, TLContactLinkContact.class);\n registerClass(TLContactLinkHasPhone.CONSTRUCTOR_ID, TLContactLinkHasPhone.class);\n registerClass(TLContactLinkNone.CONSTRUCTOR_ID, TLContactLinkNone.class);\n registerClass(TLContactLinkUnknown.CONSTRUCTOR_ID, TLContactLinkUnknown.class);\n registerClass(TLContactStatus.CONSTRUCTOR_ID, TLContactStatus.class);\n registerClass(TLBlocked.CONSTRUCTOR_ID, TLBlocked.class);\n registerClass(TLBlockedSlice.CONSTRUCTOR_ID, TLBlockedSlice.class);\n registerClass(TLContacts.CONSTRUCTOR_ID, TLContacts.class);\n registerClass(TLContactsNotModified.CONSTRUCTOR_ID, TLContactsNotModified.class);\n registerClass(TLFound.CONSTRUCTOR_ID, TLFound.class);\n registerClass(TLImportedContacts.CONSTRUCTOR_ID, TLImportedContacts.class);\n registerClass(TLLink.CONSTRUCTOR_ID, TLLink.class);\n registerClass(TLResolvedPeer.CONSTRUCTOR_ID, TLResolvedPeer.class);\n registerClass(TLTopPeers.CONSTRUCTOR_ID, TLTopPeers.class);\n registerClass(TLTopPeersNotModified.CONSTRUCTOR_ID, TLTopPeersNotModified.class);\n registerClass(TLDataJSON.CONSTRUCTOR_ID, TLDataJSON.class);\n registerClass(TLDcOption.CONSTRUCTOR_ID, TLDcOption.class);\n registerClass(TLDialog.CONSTRUCTOR_ID, TLDialog.class);\n registerClass(TLDisabledFeature.CONSTRUCTOR_ID, TLDisabledFeature.class);\n registerClass(TLDocument.CONSTRUCTOR_ID, TLDocument.class);\n registerClass(TLDocumentAttributeAnimated.CONSTRUCTOR_ID, TLDocumentAttributeAnimated.class);\n registerClass(TLDocumentAttributeAudio.CONSTRUCTOR_ID, TLDocumentAttributeAudio.class);\n registerClass(TLDocumentAttributeFilename.CONSTRUCTOR_ID, TLDocumentAttributeFilename.class);\n registerClass(TLDocumentAttributeHasStickers.CONSTRUCTOR_ID, TLDocumentAttributeHasStickers.class);\n registerClass(TLDocumentAttributeImageSize.CONSTRUCTOR_ID, TLDocumentAttributeImageSize.class);\n registerClass(TLDocumentAttributeSticker.CONSTRUCTOR_ID, TLDocumentAttributeSticker.class);\n registerClass(TLDocumentAttributeVideo.CONSTRUCTOR_ID, TLDocumentAttributeVideo.class);\n registerClass(TLDocumentEmpty.CONSTRUCTOR_ID, TLDocumentEmpty.class);\n registerClass(TLDraftMessage.CONSTRUCTOR_ID, TLDraftMessage.class);\n registerClass(TLDraftMessageEmpty.CONSTRUCTOR_ID, TLDraftMessageEmpty.class);\n registerClass(TLEncryptedChat.CONSTRUCTOR_ID, TLEncryptedChat.class);\n registerClass(TLEncryptedChatDiscarded.CONSTRUCTOR_ID, TLEncryptedChatDiscarded.class);\n registerClass(TLEncryptedChatEmpty.CONSTRUCTOR_ID, TLEncryptedChatEmpty.class);\n registerClass(TLEncryptedChatRequested.CONSTRUCTOR_ID, TLEncryptedChatRequested.class);\n registerClass(TLEncryptedChatWaiting.CONSTRUCTOR_ID, TLEncryptedChatWaiting.class);\n registerClass(TLEncryptedFile.CONSTRUCTOR_ID, TLEncryptedFile.class);\n registerClass(TLEncryptedFileEmpty.CONSTRUCTOR_ID, TLEncryptedFileEmpty.class);\n registerClass(TLEncryptedMessage.CONSTRUCTOR_ID, TLEncryptedMessage.class);\n registerClass(TLEncryptedMessageService.CONSTRUCTOR_ID, TLEncryptedMessageService.class);\n registerClass(TLExportedMessageLink.CONSTRUCTOR_ID, TLExportedMessageLink.class);\n registerClass(TLFileLocation.CONSTRUCTOR_ID, TLFileLocation.class);\n registerClass(TLFileLocationUnavailable.CONSTRUCTOR_ID, TLFileLocationUnavailable.class);\n registerClass(TLFoundGif.CONSTRUCTOR_ID, TLFoundGif.class);\n registerClass(TLFoundGifCached.CONSTRUCTOR_ID, TLFoundGifCached.class);\n registerClass(TLGame.CONSTRUCTOR_ID, TLGame.class);\n registerClass(TLGeoPoint.CONSTRUCTOR_ID, TLGeoPoint.class);\n registerClass(TLGeoPointEmpty.CONSTRUCTOR_ID, TLGeoPointEmpty.class);\n registerClass(TLAppUpdate.CONSTRUCTOR_ID, TLAppUpdate.class);\n registerClass(TLInviteText.CONSTRUCTOR_ID, TLInviteText.class);\n registerClass(TLNoAppUpdate.CONSTRUCTOR_ID, TLNoAppUpdate.class);\n registerClass(TLSupport.CONSTRUCTOR_ID, TLSupport.class);\n registerClass(TLTermsOfService.CONSTRUCTOR_ID, TLTermsOfService.class);\n registerClass(TLHighScore.CONSTRUCTOR_ID, TLHighScore.class);\n registerClass(TLImportedContact.CONSTRUCTOR_ID, TLImportedContact.class);\n registerClass(TLInlineBotSwitchPM.CONSTRUCTOR_ID, TLInlineBotSwitchPM.class);\n registerClass(TLInputAppEvent.CONSTRUCTOR_ID, TLInputAppEvent.class);\n registerClass(TLInputBotInlineMessageGame.CONSTRUCTOR_ID, TLInputBotInlineMessageGame.class);\n registerClass(TLInputBotInlineMessageID.CONSTRUCTOR_ID, TLInputBotInlineMessageID.class);\n registerClass(TLInputBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaAuto.class);\n registerClass(TLInputBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaContact.class);\n registerClass(TLInputBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaGeo.class);\n registerClass(TLInputBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaVenue.class);\n registerClass(TLInputBotInlineMessageText.CONSTRUCTOR_ID, TLInputBotInlineMessageText.class);\n registerClass(TLInputBotInlineResult.CONSTRUCTOR_ID, TLInputBotInlineResult.class);\n registerClass(TLInputBotInlineResultDocument.CONSTRUCTOR_ID, TLInputBotInlineResultDocument.class);\n registerClass(TLInputBotInlineResultGame.CONSTRUCTOR_ID, TLInputBotInlineResultGame.class);\n registerClass(TLInputBotInlineResultPhoto.CONSTRUCTOR_ID, TLInputBotInlineResultPhoto.class);\n registerClass(TLInputChannel.CONSTRUCTOR_ID, TLInputChannel.class);\n registerClass(TLInputChannelEmpty.CONSTRUCTOR_ID, TLInputChannelEmpty.class);\n registerClass(TLInputChatPhoto.CONSTRUCTOR_ID, TLInputChatPhoto.class);\n registerClass(TLInputChatPhotoEmpty.CONSTRUCTOR_ID, TLInputChatPhotoEmpty.class);\n registerClass(TLInputChatUploadedPhoto.CONSTRUCTOR_ID, TLInputChatUploadedPhoto.class);\n registerClass(TLInputDocument.CONSTRUCTOR_ID, TLInputDocument.class);\n registerClass(TLInputDocumentEmpty.CONSTRUCTOR_ID, TLInputDocumentEmpty.class);\n registerClass(TLInputDocumentFileLocation.CONSTRUCTOR_ID, TLInputDocumentFileLocation.class);\n registerClass(TLInputEncryptedChat.CONSTRUCTOR_ID, TLInputEncryptedChat.class);\n registerClass(TLInputEncryptedFile.CONSTRUCTOR_ID, TLInputEncryptedFile.class);\n registerClass(TLInputEncryptedFileBigUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileBigUploaded.class);\n registerClass(TLInputEncryptedFileEmpty.CONSTRUCTOR_ID, TLInputEncryptedFileEmpty.class);\n registerClass(TLInputEncryptedFileLocation.CONSTRUCTOR_ID, TLInputEncryptedFileLocation.class);\n registerClass(TLInputEncryptedFileUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileUploaded.class);\n registerClass(TLInputFile.CONSTRUCTOR_ID, TLInputFile.class);\n registerClass(TLInputFileBig.CONSTRUCTOR_ID, TLInputFileBig.class);\n registerClass(TLInputFileLocation.CONSTRUCTOR_ID, TLInputFileLocation.class);\n registerClass(TLInputGameID.CONSTRUCTOR_ID, TLInputGameID.class);\n registerClass(TLInputGameShortName.CONSTRUCTOR_ID, TLInputGameShortName.class);\n registerClass(TLInputGeoPoint.CONSTRUCTOR_ID, TLInputGeoPoint.class);\n registerClass(TLInputGeoPointEmpty.CONSTRUCTOR_ID, TLInputGeoPointEmpty.class);\n registerClass(TLInputMediaContact.CONSTRUCTOR_ID, TLInputMediaContact.class);\n registerClass(TLInputMediaDocument.CONSTRUCTOR_ID, TLInputMediaDocument.class);\n registerClass(TLInputMediaDocumentExternal.CONSTRUCTOR_ID, TLInputMediaDocumentExternal.class);\n registerClass(TLInputMediaEmpty.CONSTRUCTOR_ID, TLInputMediaEmpty.class);\n registerClass(TLInputMediaGame.CONSTRUCTOR_ID, TLInputMediaGame.class);\n registerClass(TLInputMediaGeoPoint.CONSTRUCTOR_ID, TLInputMediaGeoPoint.class);\n registerClass(TLInputMediaGifExternal.CONSTRUCTOR_ID, TLInputMediaGifExternal.class);\n registerClass(TLInputMediaInvoice.CONSTRUCTOR_ID, TLInputMediaInvoice.class);\n registerClass(TLInputMediaPhoto.CONSTRUCTOR_ID, TLInputMediaPhoto.class);\n registerClass(TLInputMediaPhotoExternal.CONSTRUCTOR_ID, TLInputMediaPhotoExternal.class);\n registerClass(TLInputMediaUploadedDocument.CONSTRUCTOR_ID, TLInputMediaUploadedDocument.class);\n registerClass(TLInputMediaUploadedPhoto.CONSTRUCTOR_ID, TLInputMediaUploadedPhoto.class);\n registerClass(TLInputMediaUploadedThumbDocument.CONSTRUCTOR_ID, TLInputMediaUploadedThumbDocument.class);\n registerClass(TLInputMediaVenue.CONSTRUCTOR_ID, TLInputMediaVenue.class);\n registerClass(TLInputMessageEntityMentionName.CONSTRUCTOR_ID, TLInputMessageEntityMentionName.class);\n registerClass(TLInputMessagesFilterChatPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterChatPhotos.class);\n registerClass(TLInputMessagesFilterDocument.CONSTRUCTOR_ID, TLInputMessagesFilterDocument.class);\n registerClass(TLInputMessagesFilterEmpty.CONSTRUCTOR_ID, TLInputMessagesFilterEmpty.class);\n registerClass(TLInputMessagesFilterGif.CONSTRUCTOR_ID, TLInputMessagesFilterGif.class);\n registerClass(TLInputMessagesFilterMusic.CONSTRUCTOR_ID, TLInputMessagesFilterMusic.class);\n registerClass(TLInputMessagesFilterPhoneCalls.CONSTRUCTOR_ID, TLInputMessagesFilterPhoneCalls.class);\n registerClass(TLInputMessagesFilterPhotoVideo.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideo.class);\n registerClass(TLInputMessagesFilterPhotoVideoDocuments.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideoDocuments.class);\n registerClass(TLInputMessagesFilterPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterPhotos.class);\n registerClass(TLInputMessagesFilterRoundVideo.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVideo.class);\n registerClass(TLInputMessagesFilterRoundVoice.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVoice.class);\n registerClass(TLInputMessagesFilterUrl.CONSTRUCTOR_ID, TLInputMessagesFilterUrl.class);\n registerClass(TLInputMessagesFilterVideo.CONSTRUCTOR_ID, TLInputMessagesFilterVideo.class);\n registerClass(TLInputMessagesFilterVoice.CONSTRUCTOR_ID, TLInputMessagesFilterVoice.class);\n registerClass(TLInputNotifyAll.CONSTRUCTOR_ID, TLInputNotifyAll.class);\n registerClass(TLInputNotifyChats.CONSTRUCTOR_ID, TLInputNotifyChats.class);\n registerClass(TLInputNotifyPeer.CONSTRUCTOR_ID, TLInputNotifyPeer.class);\n registerClass(TLInputNotifyUsers.CONSTRUCTOR_ID, TLInputNotifyUsers.class);\n registerClass(TLInputPaymentCredentials.CONSTRUCTOR_ID, TLInputPaymentCredentials.class);\n registerClass(TLInputPaymentCredentialsSaved.CONSTRUCTOR_ID, TLInputPaymentCredentialsSaved.class);\n registerClass(TLInputPeerChannel.CONSTRUCTOR_ID, TLInputPeerChannel.class);\n registerClass(TLInputPeerChat.CONSTRUCTOR_ID, TLInputPeerChat.class);\n registerClass(TLInputPeerEmpty.CONSTRUCTOR_ID, TLInputPeerEmpty.class);\n registerClass(TLInputPeerNotifyEventsAll.CONSTRUCTOR_ID, TLInputPeerNotifyEventsAll.class);\n registerClass(TLInputPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLInputPeerNotifyEventsEmpty.class);\n registerClass(TLInputPeerNotifySettings.CONSTRUCTOR_ID, TLInputPeerNotifySettings.class);\n registerClass(TLInputPeerSelf.CONSTRUCTOR_ID, TLInputPeerSelf.class);\n registerClass(TLInputPeerUser.CONSTRUCTOR_ID, TLInputPeerUser.class);\n registerClass(TLInputPhoneCall.CONSTRUCTOR_ID, TLInputPhoneCall.class);\n registerClass(TLInputPhoneContact.CONSTRUCTOR_ID, TLInputPhoneContact.class);\n registerClass(TLInputPhoto.CONSTRUCTOR_ID, TLInputPhoto.class);\n registerClass(TLInputPhotoEmpty.CONSTRUCTOR_ID, TLInputPhotoEmpty.class);\n registerClass(TLInputPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLInputPrivacyKeyChatInvite.class);\n registerClass(TLInputPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLInputPrivacyKeyPhoneCall.class);\n registerClass(TLInputPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLInputPrivacyKeyStatusTimestamp.class);\n registerClass(TLInputPrivacyValueAllowAll.CONSTRUCTOR_ID, TLInputPrivacyValueAllowAll.class);\n registerClass(TLInputPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueAllowContacts.class);\n registerClass(TLInputPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueAllowUsers.class);\n registerClass(TLInputPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowAll.class);\n registerClass(TLInputPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowContacts.class);\n registerClass(TLInputPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowUsers.class);\n registerClass(TLInputReportReasonOther.CONSTRUCTOR_ID, TLInputReportReasonOther.class);\n registerClass(TLInputReportReasonPornography.CONSTRUCTOR_ID, TLInputReportReasonPornography.class);\n registerClass(TLInputReportReasonSpam.CONSTRUCTOR_ID, TLInputReportReasonSpam.class);\n registerClass(TLInputReportReasonViolence.CONSTRUCTOR_ID, TLInputReportReasonViolence.class);\n registerClass(TLInputStickerSetEmpty.CONSTRUCTOR_ID, TLInputStickerSetEmpty.class);\n registerClass(TLInputStickerSetID.CONSTRUCTOR_ID, TLInputStickerSetID.class);\n registerClass(TLInputStickerSetShortName.CONSTRUCTOR_ID, TLInputStickerSetShortName.class);\n registerClass(TLInputStickeredMediaDocument.CONSTRUCTOR_ID, TLInputStickeredMediaDocument.class);\n registerClass(TLInputStickeredMediaPhoto.CONSTRUCTOR_ID, TLInputStickeredMediaPhoto.class);\n registerClass(TLInputUser.CONSTRUCTOR_ID, TLInputUser.class);\n registerClass(TLInputUserEmpty.CONSTRUCTOR_ID, TLInputUserEmpty.class);\n registerClass(TLInputUserSelf.CONSTRUCTOR_ID, TLInputUserSelf.class);\n registerClass(TLInputWebDocument.CONSTRUCTOR_ID, TLInputWebDocument.class);\n registerClass(TLInputWebFileLocation.CONSTRUCTOR_ID, TLInputWebFileLocation.class);\n registerClass(TLInvoice.CONSTRUCTOR_ID, TLInvoice.class);\n registerClass(TLKeyboardButton.CONSTRUCTOR_ID, TLKeyboardButton.class);\n registerClass(TLKeyboardButtonBuy.CONSTRUCTOR_ID, TLKeyboardButtonBuy.class);\n registerClass(TLKeyboardButtonCallback.CONSTRUCTOR_ID, TLKeyboardButtonCallback.class);\n registerClass(TLKeyboardButtonGame.CONSTRUCTOR_ID, TLKeyboardButtonGame.class);\n registerClass(TLKeyboardButtonRequestGeoLocation.CONSTRUCTOR_ID, TLKeyboardButtonRequestGeoLocation.class);\n registerClass(TLKeyboardButtonRequestPhone.CONSTRUCTOR_ID, TLKeyboardButtonRequestPhone.class);\n registerClass(TLKeyboardButtonRow.CONSTRUCTOR_ID, TLKeyboardButtonRow.class);\n registerClass(TLKeyboardButtonSwitchInline.CONSTRUCTOR_ID, TLKeyboardButtonSwitchInline.class);\n registerClass(TLKeyboardButtonUrl.CONSTRUCTOR_ID, TLKeyboardButtonUrl.class);\n registerClass(TLLabeledPrice.CONSTRUCTOR_ID, TLLabeledPrice.class);\n registerClass(TLMaskCoords.CONSTRUCTOR_ID, TLMaskCoords.class);\n registerClass(TLMessage.CONSTRUCTOR_ID, TLMessage.class);\n registerClass(TLMessageActionChannelCreate.CONSTRUCTOR_ID, TLMessageActionChannelCreate.class);\n registerClass(TLMessageActionChannelMigrateFrom.CONSTRUCTOR_ID, TLMessageActionChannelMigrateFrom.class);\n registerClass(TLMessageActionChatAddUser.CONSTRUCTOR_ID, TLMessageActionChatAddUser.class);\n registerClass(TLMessageActionChatCreate.CONSTRUCTOR_ID, TLMessageActionChatCreate.class);\n registerClass(TLMessageActionChatDeletePhoto.CONSTRUCTOR_ID, TLMessageActionChatDeletePhoto.class);\n registerClass(TLMessageActionChatDeleteUser.CONSTRUCTOR_ID, TLMessageActionChatDeleteUser.class);\n registerClass(TLMessageActionChatEditPhoto.CONSTRUCTOR_ID, TLMessageActionChatEditPhoto.class);\n registerClass(TLMessageActionChatEditTitle.CONSTRUCTOR_ID, TLMessageActionChatEditTitle.class);\n registerClass(TLMessageActionChatJoinedByLink.CONSTRUCTOR_ID, TLMessageActionChatJoinedByLink.class);\n registerClass(TLMessageActionChatMigrateTo.CONSTRUCTOR_ID, TLMessageActionChatMigrateTo.class);\n registerClass(TLMessageActionEmpty.CONSTRUCTOR_ID, TLMessageActionEmpty.class);\n registerClass(TLMessageActionGameScore.CONSTRUCTOR_ID, TLMessageActionGameScore.class);\n registerClass(TLMessageActionHistoryClear.CONSTRUCTOR_ID, TLMessageActionHistoryClear.class);\n registerClass(TLMessageActionPaymentSent.CONSTRUCTOR_ID, TLMessageActionPaymentSent.class);\n registerClass(TLMessageActionPaymentSentMe.CONSTRUCTOR_ID, TLMessageActionPaymentSentMe.class);\n registerClass(TLMessageActionPhoneCall.CONSTRUCTOR_ID, TLMessageActionPhoneCall.class);\n registerClass(TLMessageActionPinMessage.CONSTRUCTOR_ID, TLMessageActionPinMessage.class);\n registerClass(TLMessageEmpty.CONSTRUCTOR_ID, TLMessageEmpty.class);\n registerClass(TLMessageEntityBold.CONSTRUCTOR_ID, TLMessageEntityBold.class);\n registerClass(TLMessageEntityBotCommand.CONSTRUCTOR_ID, TLMessageEntityBotCommand.class);\n registerClass(TLMessageEntityCode.CONSTRUCTOR_ID, TLMessageEntityCode.class);\n registerClass(TLMessageEntityEmail.CONSTRUCTOR_ID, TLMessageEntityEmail.class);\n registerClass(TLMessageEntityHashtag.CONSTRUCTOR_ID, TLMessageEntityHashtag.class);\n registerClass(TLMessageEntityItalic.CONSTRUCTOR_ID, TLMessageEntityItalic.class);\n registerClass(TLMessageEntityMention.CONSTRUCTOR_ID, TLMessageEntityMention.class);\n registerClass(TLMessageEntityMentionName.CONSTRUCTOR_ID, TLMessageEntityMentionName.class);\n registerClass(TLMessageEntityPre.CONSTRUCTOR_ID, TLMessageEntityPre.class);\n registerClass(TLMessageEntityTextUrl.CONSTRUCTOR_ID, TLMessageEntityTextUrl.class);\n registerClass(TLMessageEntityUnknown.CONSTRUCTOR_ID, TLMessageEntityUnknown.class);\n registerClass(TLMessageEntityUrl.CONSTRUCTOR_ID, TLMessageEntityUrl.class);\n registerClass(TLMessageFwdHeader.CONSTRUCTOR_ID, TLMessageFwdHeader.class);\n registerClass(TLMessageMediaContact.CONSTRUCTOR_ID, TLMessageMediaContact.class);\n registerClass(TLMessageMediaDocument.CONSTRUCTOR_ID, TLMessageMediaDocument.class);\n registerClass(TLMessageMediaEmpty.CONSTRUCTOR_ID, TLMessageMediaEmpty.class);\n registerClass(TLMessageMediaGame.CONSTRUCTOR_ID, TLMessageMediaGame.class);\n registerClass(TLMessageMediaGeo.CONSTRUCTOR_ID, TLMessageMediaGeo.class);\n registerClass(TLMessageMediaInvoice.CONSTRUCTOR_ID, TLMessageMediaInvoice.class);\n registerClass(TLMessageMediaPhoto.CONSTRUCTOR_ID, TLMessageMediaPhoto.class);\n registerClass(TLMessageMediaUnsupported.CONSTRUCTOR_ID, TLMessageMediaUnsupported.class);\n registerClass(TLMessageMediaVenue.CONSTRUCTOR_ID, TLMessageMediaVenue.class);\n registerClass(TLMessageMediaWebPage.CONSTRUCTOR_ID, TLMessageMediaWebPage.class);\n registerClass(TLMessageRange.CONSTRUCTOR_ID, TLMessageRange.class);\n registerClass(TLMessageService.CONSTRUCTOR_ID, TLMessageService.class);\n registerClass(TLAffectedHistory.CONSTRUCTOR_ID, TLAffectedHistory.class);\n registerClass(TLAffectedMessages.CONSTRUCTOR_ID, TLAffectedMessages.class);\n registerClass(TLAllStickers.CONSTRUCTOR_ID, TLAllStickers.class);\n registerClass(TLAllStickersNotModified.CONSTRUCTOR_ID, TLAllStickersNotModified.class);\n registerClass(TLArchivedStickers.CONSTRUCTOR_ID, TLArchivedStickers.class);\n registerClass(TLBotCallbackAnswer.CONSTRUCTOR_ID, TLBotCallbackAnswer.class);\n registerClass(TLBotResults.CONSTRUCTOR_ID, TLBotResults.class);\n registerClass(TLChannelMessages.CONSTRUCTOR_ID, TLChannelMessages.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLChatFull.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLChatFull.class);\n registerClass(TLChats.CONSTRUCTOR_ID, TLChats.class);\n registerClass(TLChatsSlice.CONSTRUCTOR_ID, TLChatsSlice.class);\n registerClass(TLDhConfig.CONSTRUCTOR_ID, TLDhConfig.class);\n registerClass(TLDhConfigNotModified.CONSTRUCTOR_ID, TLDhConfigNotModified.class);\n registerClass(TLDialogs.CONSTRUCTOR_ID, TLDialogs.class);\n registerClass(TLDialogsSlice.CONSTRUCTOR_ID, TLDialogsSlice.class);\n registerClass(TLFeaturedStickers.CONSTRUCTOR_ID, TLFeaturedStickers.class);\n registerClass(TLFeaturedStickersNotModified.CONSTRUCTOR_ID, TLFeaturedStickersNotModified.class);\n registerClass(TLFoundGifs.CONSTRUCTOR_ID, TLFoundGifs.class);\n registerClass(TLHighScores.CONSTRUCTOR_ID, TLHighScores.class);\n registerClass(TLMessageEditData.CONSTRUCTOR_ID, TLMessageEditData.class);\n registerClass(TLMessages.CONSTRUCTOR_ID, TLMessages.class);\n registerClass(TLMessagesSlice.CONSTRUCTOR_ID, TLMessagesSlice.class);\n registerClass(TLPeerDialogs.CONSTRUCTOR_ID, TLPeerDialogs.class);\n registerClass(TLRecentStickers.CONSTRUCTOR_ID, TLRecentStickers.class);\n registerClass(TLRecentStickersNotModified.CONSTRUCTOR_ID, TLRecentStickersNotModified.class);\n registerClass(TLSavedGifs.CONSTRUCTOR_ID, TLSavedGifs.class);\n registerClass(TLSavedGifsNotModified.CONSTRUCTOR_ID, TLSavedGifsNotModified.class);\n registerClass(TLSentEncryptedFile.CONSTRUCTOR_ID, TLSentEncryptedFile.class);\n registerClass(TLSentEncryptedMessage.CONSTRUCTOR_ID, TLSentEncryptedMessage.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLStickerSet.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLStickerSet.class);\n registerClass(TLStickerSetInstallResultArchive.CONSTRUCTOR_ID, TLStickerSetInstallResultArchive.class);\n registerClass(TLStickerSetInstallResultSuccess.CONSTRUCTOR_ID, TLStickerSetInstallResultSuccess.class);\n registerClass(TLStickers.CONSTRUCTOR_ID, TLStickers.class);\n registerClass(TLStickersNotModified.CONSTRUCTOR_ID, TLStickersNotModified.class);\n registerClass(TLNearestDc.CONSTRUCTOR_ID, TLNearestDc.class);\n registerClass(TLNotifyAll.CONSTRUCTOR_ID, TLNotifyAll.class);\n registerClass(TLNotifyChats.CONSTRUCTOR_ID, TLNotifyChats.class);\n registerClass(TLNotifyPeer.CONSTRUCTOR_ID, TLNotifyPeer.class);\n registerClass(TLNotifyUsers.CONSTRUCTOR_ID, TLNotifyUsers.class);\n registerClass(TLPageBlockAnchor.CONSTRUCTOR_ID, TLPageBlockAnchor.class);\n registerClass(TLPageBlockAuthorDate.CONSTRUCTOR_ID, TLPageBlockAuthorDate.class);\n registerClass(TLPageBlockBlockquote.CONSTRUCTOR_ID, TLPageBlockBlockquote.class);\n registerClass(TLPageBlockChannel.CONSTRUCTOR_ID, TLPageBlockChannel.class);\n registerClass(TLPageBlockCollage.CONSTRUCTOR_ID, TLPageBlockCollage.class);\n registerClass(TLPageBlockCover.CONSTRUCTOR_ID, TLPageBlockCover.class);\n registerClass(TLPageBlockDivider.CONSTRUCTOR_ID, TLPageBlockDivider.class);\n registerClass(TLPageBlockEmbed.CONSTRUCTOR_ID, TLPageBlockEmbed.class);\n registerClass(TLPageBlockEmbedPost.CONSTRUCTOR_ID, TLPageBlockEmbedPost.class);\n registerClass(TLPageBlockFooter.CONSTRUCTOR_ID, TLPageBlockFooter.class);\n registerClass(TLPageBlockHeader.CONSTRUCTOR_ID, TLPageBlockHeader.class);\n registerClass(TLPageBlockList.CONSTRUCTOR_ID, TLPageBlockList.class);\n registerClass(TLPageBlockParagraph.CONSTRUCTOR_ID, TLPageBlockParagraph.class);\n registerClass(TLPageBlockPhoto.CONSTRUCTOR_ID, TLPageBlockPhoto.class);\n registerClass(TLPageBlockPreformatted.CONSTRUCTOR_ID, TLPageBlockPreformatted.class);\n registerClass(TLPageBlockPullquote.CONSTRUCTOR_ID, TLPageBlockPullquote.class);\n registerClass(TLPageBlockSlideshow.CONSTRUCTOR_ID, TLPageBlockSlideshow.class);\n registerClass(TLPageBlockSubheader.CONSTRUCTOR_ID, TLPageBlockSubheader.class);\n registerClass(TLPageBlockSubtitle.CONSTRUCTOR_ID, TLPageBlockSubtitle.class);\n registerClass(TLPageBlockTitle.CONSTRUCTOR_ID, TLPageBlockTitle.class);\n registerClass(TLPageBlockUnsupported.CONSTRUCTOR_ID, TLPageBlockUnsupported.class);\n registerClass(TLPageBlockVideo.CONSTRUCTOR_ID, TLPageBlockVideo.class);\n registerClass(TLPageFull.CONSTRUCTOR_ID, TLPageFull.class);\n registerClass(TLPagePart.CONSTRUCTOR_ID, TLPagePart.class);\n registerClass(TLPaymentCharge.CONSTRUCTOR_ID, TLPaymentCharge.class);\n registerClass(TLPaymentRequestedInfo.CONSTRUCTOR_ID, TLPaymentRequestedInfo.class);\n registerClass(TLPaymentSavedCredentialsCard.CONSTRUCTOR_ID, TLPaymentSavedCredentialsCard.class);\n registerClass(TLPaymentForm.CONSTRUCTOR_ID, TLPaymentForm.class);\n registerClass(TLPaymentReceipt.CONSTRUCTOR_ID, TLPaymentReceipt.class);\n registerClass(TLPaymentResult.CONSTRUCTOR_ID, TLPaymentResult.class);\n registerClass(TLPaymentVerficationNeeded.CONSTRUCTOR_ID, TLPaymentVerficationNeeded.class);\n registerClass(TLSavedInfo.CONSTRUCTOR_ID, TLSavedInfo.class);\n registerClass(TLValidatedRequestedInfo.CONSTRUCTOR_ID, TLValidatedRequestedInfo.class);\n registerClass(TLPeerChannel.CONSTRUCTOR_ID, TLPeerChannel.class);\n registerClass(TLPeerChat.CONSTRUCTOR_ID, TLPeerChat.class);\n registerClass(TLPeerNotifyEventsAll.CONSTRUCTOR_ID, TLPeerNotifyEventsAll.class);\n registerClass(TLPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLPeerNotifyEventsEmpty.class);\n registerClass(TLPeerNotifySettings.CONSTRUCTOR_ID, TLPeerNotifySettings.class);\n registerClass(TLPeerNotifySettingsEmpty.CONSTRUCTOR_ID, TLPeerNotifySettingsEmpty.class);\n registerClass(TLPeerSettings.CONSTRUCTOR_ID, TLPeerSettings.class);\n registerClass(TLPeerUser.CONSTRUCTOR_ID, TLPeerUser.class);\n registerClass(com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.class);\n registerClass(TLPhoneCall.CONSTRUCTOR_ID, TLPhoneCall.class);\n registerClass(TLPhoneCallAccepted.CONSTRUCTOR_ID, TLPhoneCallAccepted.class);\n registerClass(TLPhoneCallDiscardReasonBusy.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonBusy.class);\n registerClass(TLPhoneCallDiscardReasonDisconnect.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonDisconnect.class);\n registerClass(TLPhoneCallDiscardReasonHangup.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonHangup.class);\n registerClass(TLPhoneCallDiscardReasonMissed.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonMissed.class);\n registerClass(TLPhoneCallDiscarded.CONSTRUCTOR_ID, TLPhoneCallDiscarded.class);\n registerClass(TLPhoneCallEmpty.CONSTRUCTOR_ID, TLPhoneCallEmpty.class);\n registerClass(TLPhoneCallProtocol.CONSTRUCTOR_ID, TLPhoneCallProtocol.class);\n registerClass(TLPhoneCallRequested.CONSTRUCTOR_ID, TLPhoneCallRequested.class);\n registerClass(TLPhoneCallWaiting.CONSTRUCTOR_ID, TLPhoneCallWaiting.class);\n registerClass(TLPhoneConnection.CONSTRUCTOR_ID, TLPhoneConnection.class);\n registerClass(TLPhoto.CONSTRUCTOR_ID, TLPhoto.class);\n registerClass(TLPhotoCachedSize.CONSTRUCTOR_ID, TLPhotoCachedSize.class);\n registerClass(TLPhotoEmpty.CONSTRUCTOR_ID, TLPhotoEmpty.class);\n registerClass(TLPhotoSize.CONSTRUCTOR_ID, TLPhotoSize.class);\n registerClass(TLPhotoSizeEmpty.CONSTRUCTOR_ID, TLPhotoSizeEmpty.class);\n registerClass(com.github.badoualy.telegram.tl.api.photos.TLPhoto.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.photos.TLPhoto.class);\n registerClass(TLPhotos.CONSTRUCTOR_ID, TLPhotos.class);\n registerClass(TLPhotosSlice.CONSTRUCTOR_ID, TLPhotosSlice.class);\n registerClass(TLPostAddress.CONSTRUCTOR_ID, TLPostAddress.class);\n registerClass(TLPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLPrivacyKeyChatInvite.class);\n registerClass(TLPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLPrivacyKeyPhoneCall.class);\n registerClass(TLPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLPrivacyKeyStatusTimestamp.class);\n registerClass(TLPrivacyValueAllowAll.CONSTRUCTOR_ID, TLPrivacyValueAllowAll.class);\n registerClass(TLPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLPrivacyValueAllowContacts.class);\n registerClass(TLPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLPrivacyValueAllowUsers.class);\n registerClass(TLPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLPrivacyValueDisallowAll.class);\n registerClass(TLPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLPrivacyValueDisallowContacts.class);\n registerClass(TLPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLPrivacyValueDisallowUsers.class);\n registerClass(TLReceivedNotifyMessage.CONSTRUCTOR_ID, TLReceivedNotifyMessage.class);\n registerClass(TLReplyInlineMarkup.CONSTRUCTOR_ID, TLReplyInlineMarkup.class);\n registerClass(TLReplyKeyboardForceReply.CONSTRUCTOR_ID, TLReplyKeyboardForceReply.class);\n registerClass(TLReplyKeyboardHide.CONSTRUCTOR_ID, TLReplyKeyboardHide.class);\n registerClass(TLReplyKeyboardMarkup.CONSTRUCTOR_ID, TLReplyKeyboardMarkup.class);\n registerClass(TLSendMessageCancelAction.CONSTRUCTOR_ID, TLSendMessageCancelAction.class);\n registerClass(TLSendMessageChooseContactAction.CONSTRUCTOR_ID, TLSendMessageChooseContactAction.class);\n registerClass(TLSendMessageGamePlayAction.CONSTRUCTOR_ID, TLSendMessageGamePlayAction.class);\n registerClass(TLSendMessageGeoLocationAction.CONSTRUCTOR_ID, TLSendMessageGeoLocationAction.class);\n registerClass(TLSendMessageRecordAudioAction.CONSTRUCTOR_ID, TLSendMessageRecordAudioAction.class);\n registerClass(TLSendMessageRecordRoundAction.CONSTRUCTOR_ID, TLSendMessageRecordRoundAction.class);\n registerClass(TLSendMessageRecordVideoAction.CONSTRUCTOR_ID, TLSendMessageRecordVideoAction.class);\n registerClass(TLSendMessageTypingAction.CONSTRUCTOR_ID, TLSendMessageTypingAction.class);\n registerClass(TLSendMessageUploadAudioAction.CONSTRUCTOR_ID, TLSendMessageUploadAudioAction.class);\n registerClass(TLSendMessageUploadDocumentAction.CONSTRUCTOR_ID, TLSendMessageUploadDocumentAction.class);\n registerClass(TLSendMessageUploadPhotoAction.CONSTRUCTOR_ID, TLSendMessageUploadPhotoAction.class);\n registerClass(TLSendMessageUploadRoundAction.CONSTRUCTOR_ID, TLSendMessageUploadRoundAction.class);\n registerClass(TLSendMessageUploadVideoAction.CONSTRUCTOR_ID, TLSendMessageUploadVideoAction.class);\n registerClass(TLShippingOption.CONSTRUCTOR_ID, TLShippingOption.class);\n registerClass(TLStickerPack.CONSTRUCTOR_ID, TLStickerPack.class);\n registerClass(TLStickerSet.CONSTRUCTOR_ID, TLStickerSet.class);\n registerClass(TLStickerSetCovered.CONSTRUCTOR_ID, TLStickerSetCovered.class);\n registerClass(TLStickerSetMultiCovered.CONSTRUCTOR_ID, TLStickerSetMultiCovered.class);\n registerClass(TLFileGif.CONSTRUCTOR_ID, TLFileGif.class);\n registerClass(TLFileJpeg.CONSTRUCTOR_ID, TLFileJpeg.class);\n registerClass(TLFileMov.CONSTRUCTOR_ID, TLFileMov.class);\n registerClass(TLFileMp3.CONSTRUCTOR_ID, TLFileMp3.class);\n registerClass(TLFileMp4.CONSTRUCTOR_ID, TLFileMp4.class);\n registerClass(TLFilePartial.CONSTRUCTOR_ID, TLFilePartial.class);\n registerClass(TLFilePdf.CONSTRUCTOR_ID, TLFilePdf.class);\n registerClass(TLFilePng.CONSTRUCTOR_ID, TLFilePng.class);\n registerClass(TLFileUnknown.CONSTRUCTOR_ID, TLFileUnknown.class);\n registerClass(TLFileWebp.CONSTRUCTOR_ID, TLFileWebp.class);\n registerClass(TLTextBold.CONSTRUCTOR_ID, TLTextBold.class);\n registerClass(TLTextConcat.CONSTRUCTOR_ID, TLTextConcat.class);\n registerClass(TLTextEmail.CONSTRUCTOR_ID, TLTextEmail.class);\n registerClass(TLTextEmpty.CONSTRUCTOR_ID, TLTextEmpty.class);\n registerClass(TLTextFixed.CONSTRUCTOR_ID, TLTextFixed.class);\n registerClass(TLTextItalic.CONSTRUCTOR_ID, TLTextItalic.class);\n registerClass(TLTextPlain.CONSTRUCTOR_ID, TLTextPlain.class);\n registerClass(TLTextStrike.CONSTRUCTOR_ID, TLTextStrike.class);\n registerClass(TLTextUnderline.CONSTRUCTOR_ID, TLTextUnderline.class);\n registerClass(TLTextUrl.CONSTRUCTOR_ID, TLTextUrl.class);\n registerClass(TLTopPeer.CONSTRUCTOR_ID, TLTopPeer.class);\n registerClass(TLTopPeerCategoryBotsInline.CONSTRUCTOR_ID, TLTopPeerCategoryBotsInline.class);\n registerClass(TLTopPeerCategoryBotsPM.CONSTRUCTOR_ID, TLTopPeerCategoryBotsPM.class);\n registerClass(TLTopPeerCategoryChannels.CONSTRUCTOR_ID, TLTopPeerCategoryChannels.class);\n registerClass(TLTopPeerCategoryCorrespondents.CONSTRUCTOR_ID, TLTopPeerCategoryCorrespondents.class);\n registerClass(TLTopPeerCategoryGroups.CONSTRUCTOR_ID, TLTopPeerCategoryGroups.class);\n registerClass(TLTopPeerCategoryPeers.CONSTRUCTOR_ID, TLTopPeerCategoryPeers.class);\n registerClass(TLUpdateBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateBotCallbackQuery.class);\n registerClass(TLUpdateBotInlineQuery.CONSTRUCTOR_ID, TLUpdateBotInlineQuery.class);\n registerClass(TLUpdateBotInlineSend.CONSTRUCTOR_ID, TLUpdateBotInlineSend.class);\n registerClass(TLUpdateBotPrecheckoutQuery.CONSTRUCTOR_ID, TLUpdateBotPrecheckoutQuery.class);\n registerClass(TLUpdateBotShippingQuery.CONSTRUCTOR_ID, TLUpdateBotShippingQuery.class);\n registerClass(TLUpdateBotWebhookJSON.CONSTRUCTOR_ID, TLUpdateBotWebhookJSON.class);\n registerClass(TLUpdateBotWebhookJSONQuery.CONSTRUCTOR_ID, TLUpdateBotWebhookJSONQuery.class);\n registerClass(TLUpdateChannel.CONSTRUCTOR_ID, TLUpdateChannel.class);\n registerClass(TLUpdateChannelMessageViews.CONSTRUCTOR_ID, TLUpdateChannelMessageViews.class);\n registerClass(TLUpdateChannelPinnedMessage.CONSTRUCTOR_ID, TLUpdateChannelPinnedMessage.class);\n registerClass(TLUpdateChannelTooLong.CONSTRUCTOR_ID, TLUpdateChannelTooLong.class);\n registerClass(TLUpdateChannelWebPage.CONSTRUCTOR_ID, TLUpdateChannelWebPage.class);\n registerClass(TLUpdateChatAdmins.CONSTRUCTOR_ID, TLUpdateChatAdmins.class);\n registerClass(TLUpdateChatParticipantAdd.CONSTRUCTOR_ID, TLUpdateChatParticipantAdd.class);\n registerClass(TLUpdateChatParticipantAdmin.CONSTRUCTOR_ID, TLUpdateChatParticipantAdmin.class);\n registerClass(TLUpdateChatParticipantDelete.CONSTRUCTOR_ID, TLUpdateChatParticipantDelete.class);\n registerClass(TLUpdateChatParticipants.CONSTRUCTOR_ID, TLUpdateChatParticipants.class);\n registerClass(TLUpdateChatUserTyping.CONSTRUCTOR_ID, TLUpdateChatUserTyping.class);\n registerClass(TLUpdateConfig.CONSTRUCTOR_ID, TLUpdateConfig.class);\n registerClass(TLUpdateContactLink.CONSTRUCTOR_ID, TLUpdateContactLink.class);\n registerClass(TLUpdateContactRegistered.CONSTRUCTOR_ID, TLUpdateContactRegistered.class);\n registerClass(TLUpdateDcOptions.CONSTRUCTOR_ID, TLUpdateDcOptions.class);\n registerClass(TLUpdateDeleteChannelMessages.CONSTRUCTOR_ID, TLUpdateDeleteChannelMessages.class);\n registerClass(TLUpdateDeleteMessages.CONSTRUCTOR_ID, TLUpdateDeleteMessages.class);\n registerClass(TLUpdateDialogPinned.CONSTRUCTOR_ID, TLUpdateDialogPinned.class);\n registerClass(TLUpdateDraftMessage.CONSTRUCTOR_ID, TLUpdateDraftMessage.class);\n registerClass(TLUpdateEditChannelMessage.CONSTRUCTOR_ID, TLUpdateEditChannelMessage.class);\n registerClass(TLUpdateEditMessage.CONSTRUCTOR_ID, TLUpdateEditMessage.class);\n registerClass(TLUpdateEncryptedChatTyping.CONSTRUCTOR_ID, TLUpdateEncryptedChatTyping.class);\n registerClass(TLUpdateEncryptedMessagesRead.CONSTRUCTOR_ID, TLUpdateEncryptedMessagesRead.class);\n registerClass(TLUpdateEncryption.CONSTRUCTOR_ID, TLUpdateEncryption.class);\n registerClass(TLUpdateInlineBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateInlineBotCallbackQuery.class);\n registerClass(TLUpdateMessageID.CONSTRUCTOR_ID, TLUpdateMessageID.class);\n registerClass(TLUpdateNewChannelMessage.CONSTRUCTOR_ID, TLUpdateNewChannelMessage.class);\n registerClass(TLUpdateNewEncryptedMessage.CONSTRUCTOR_ID, TLUpdateNewEncryptedMessage.class);\n registerClass(TLUpdateNewMessage.CONSTRUCTOR_ID, TLUpdateNewMessage.class);\n registerClass(TLUpdateNewStickerSet.CONSTRUCTOR_ID, TLUpdateNewStickerSet.class);\n registerClass(TLUpdateNotifySettings.CONSTRUCTOR_ID, TLUpdateNotifySettings.class);\n registerClass(TLUpdatePhoneCall.CONSTRUCTOR_ID, TLUpdatePhoneCall.class);\n registerClass(TLUpdatePinnedDialogs.CONSTRUCTOR_ID, TLUpdatePinnedDialogs.class);\n registerClass(TLUpdatePrivacy.CONSTRUCTOR_ID, TLUpdatePrivacy.class);\n registerClass(TLUpdatePtsChanged.CONSTRUCTOR_ID, TLUpdatePtsChanged.class);\n registerClass(TLUpdateReadChannelInbox.CONSTRUCTOR_ID, TLUpdateReadChannelInbox.class);\n registerClass(TLUpdateReadChannelOutbox.CONSTRUCTOR_ID, TLUpdateReadChannelOutbox.class);\n registerClass(TLUpdateReadFeaturedStickers.CONSTRUCTOR_ID, TLUpdateReadFeaturedStickers.class);\n registerClass(TLUpdateReadHistoryInbox.CONSTRUCTOR_ID, TLUpdateReadHistoryInbox.class);\n registerClass(TLUpdateReadHistoryOutbox.CONSTRUCTOR_ID, TLUpdateReadHistoryOutbox.class);\n registerClass(TLUpdateReadMessagesContents.CONSTRUCTOR_ID, TLUpdateReadMessagesContents.class);\n registerClass(TLUpdateRecentStickers.CONSTRUCTOR_ID, TLUpdateRecentStickers.class);\n registerClass(TLUpdateSavedGifs.CONSTRUCTOR_ID, TLUpdateSavedGifs.class);\n registerClass(TLUpdateServiceNotification.CONSTRUCTOR_ID, TLUpdateServiceNotification.class);\n registerClass(TLUpdateShort.CONSTRUCTOR_ID, TLUpdateShort.class);\n registerClass(TLUpdateShortChatMessage.CONSTRUCTOR_ID, TLUpdateShortChatMessage.class);\n registerClass(TLUpdateShortMessage.CONSTRUCTOR_ID, TLUpdateShortMessage.class);\n registerClass(TLUpdateShortSentMessage.CONSTRUCTOR_ID, TLUpdateShortSentMessage.class);\n registerClass(TLUpdateStickerSets.CONSTRUCTOR_ID, TLUpdateStickerSets.class);\n registerClass(TLUpdateStickerSetsOrder.CONSTRUCTOR_ID, TLUpdateStickerSetsOrder.class);\n registerClass(TLUpdateUserBlocked.CONSTRUCTOR_ID, TLUpdateUserBlocked.class);\n registerClass(TLUpdateUserName.CONSTRUCTOR_ID, TLUpdateUserName.class);\n registerClass(TLUpdateUserPhone.CONSTRUCTOR_ID, TLUpdateUserPhone.class);\n registerClass(TLUpdateUserPhoto.CONSTRUCTOR_ID, TLUpdateUserPhoto.class);\n registerClass(TLUpdateUserStatus.CONSTRUCTOR_ID, TLUpdateUserStatus.class);\n registerClass(TLUpdateUserTyping.CONSTRUCTOR_ID, TLUpdateUserTyping.class);\n registerClass(TLUpdateWebPage.CONSTRUCTOR_ID, TLUpdateWebPage.class);\n registerClass(TLUpdates.CONSTRUCTOR_ID, TLUpdates.class);\n registerClass(TLChannelDifference.CONSTRUCTOR_ID, TLChannelDifference.class);\n registerClass(TLChannelDifferenceEmpty.CONSTRUCTOR_ID, TLChannelDifferenceEmpty.class);\n registerClass(TLChannelDifferenceTooLong.CONSTRUCTOR_ID, TLChannelDifferenceTooLong.class);\n registerClass(TLDifference.CONSTRUCTOR_ID, TLDifference.class);\n registerClass(TLDifferenceEmpty.CONSTRUCTOR_ID, TLDifferenceEmpty.class);\n registerClass(TLDifferenceSlice.CONSTRUCTOR_ID, TLDifferenceSlice.class);\n registerClass(TLDifferenceTooLong.CONSTRUCTOR_ID, TLDifferenceTooLong.class);\n registerClass(TLState.CONSTRUCTOR_ID, TLState.class);\n registerClass(TLUpdatesCombined.CONSTRUCTOR_ID, TLUpdatesCombined.class);\n registerClass(TLUpdatesTooLong.CONSTRUCTOR_ID, TLUpdatesTooLong.class);\n registerClass(TLCdnFile.CONSTRUCTOR_ID, TLCdnFile.class);\n registerClass(TLCdnFileReuploadNeeded.CONSTRUCTOR_ID, TLCdnFileReuploadNeeded.class);\n registerClass(TLFile.CONSTRUCTOR_ID, TLFile.class);\n registerClass(TLFileCdnRedirect.CONSTRUCTOR_ID, TLFileCdnRedirect.class);\n registerClass(TLWebFile.CONSTRUCTOR_ID, TLWebFile.class);\n registerClass(TLUser.CONSTRUCTOR_ID, TLUser.class);\n registerClass(TLUserEmpty.CONSTRUCTOR_ID, TLUserEmpty.class);\n registerClass(TLUserFull.CONSTRUCTOR_ID, TLUserFull.class);\n registerClass(TLUserProfilePhoto.CONSTRUCTOR_ID, TLUserProfilePhoto.class);\n registerClass(TLUserProfilePhotoEmpty.CONSTRUCTOR_ID, TLUserProfilePhotoEmpty.class);\n registerClass(TLUserStatusEmpty.CONSTRUCTOR_ID, TLUserStatusEmpty.class);\n registerClass(TLUserStatusLastMonth.CONSTRUCTOR_ID, TLUserStatusLastMonth.class);\n registerClass(TLUserStatusLastWeek.CONSTRUCTOR_ID, TLUserStatusLastWeek.class);\n registerClass(TLUserStatusOffline.CONSTRUCTOR_ID, TLUserStatusOffline.class);\n registerClass(TLUserStatusOnline.CONSTRUCTOR_ID, TLUserStatusOnline.class);\n registerClass(TLUserStatusRecently.CONSTRUCTOR_ID, TLUserStatusRecently.class);\n registerClass(TLWallPaper.CONSTRUCTOR_ID, TLWallPaper.class);\n registerClass(TLWallPaperSolid.CONSTRUCTOR_ID, TLWallPaperSolid.class);\n registerClass(TLWebDocument.CONSTRUCTOR_ID, TLWebDocument.class);\n registerClass(TLWebPage.CONSTRUCTOR_ID, TLWebPage.class);\n registerClass(TLWebPageEmpty.CONSTRUCTOR_ID, TLWebPageEmpty.class);\n registerClass(TLWebPageNotModified.CONSTRUCTOR_ID, TLWebPageNotModified.class);\n registerClass(TLWebPagePending.CONSTRUCTOR_ID, TLWebPagePending.class);\n }\n}\n"} {"task_id": "Java_101", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/badoualy/kotlogram/tl/src/main/java/com/github/badoualy/telegram/tl/api/TLApiContext.java", "mask_start_position": 7205, "mask_end_position": 23123, "canonical_solution": "\n registerClass(TLAuthorizations.CONSTRUCTOR_ID, TLAuthorizations.class);\n registerClass(TLNoPassword.CONSTRUCTOR_ID, TLNoPassword.class);\n registerClass(TLPassword.CONSTRUCTOR_ID, TLPassword.class);\n registerClass(TLPasswordInputSettings.CONSTRUCTOR_ID, TLPasswordInputSettings.class);\n registerClass(TLPasswordSettings.CONSTRUCTOR_ID, TLPasswordSettings.class);\n registerClass(TLPrivacyRules.CONSTRUCTOR_ID, TLPrivacyRules.class);\n registerClass(TLTmpPassword.CONSTRUCTOR_ID, TLTmpPassword.class);\n registerClass(TLAccountDaysTTL.CONSTRUCTOR_ID, TLAccountDaysTTL.class);\n registerClass(com.github.badoualy.telegram.tl.api.auth.TLAuthorization.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.auth.TLAuthorization.class);\n registerClass(TLCheckedPhone.CONSTRUCTOR_ID, TLCheckedPhone.class);\n registerClass(TLCodeTypeCall.CONSTRUCTOR_ID, TLCodeTypeCall.class);\n registerClass(TLCodeTypeFlashCall.CONSTRUCTOR_ID, TLCodeTypeFlashCall.class);\n registerClass(TLCodeTypeSms.CONSTRUCTOR_ID, TLCodeTypeSms.class);\n registerClass(TLExportedAuthorization.CONSTRUCTOR_ID, TLExportedAuthorization.class);\n registerClass(TLPasswordRecovery.CONSTRUCTOR_ID, TLPasswordRecovery.class);\n registerClass(TLSentCode.CONSTRUCTOR_ID, TLSentCode.class);\n registerClass(TLSentCodeTypeApp.CONSTRUCTOR_ID, TLSentCodeTypeApp.class);\n registerClass(TLSentCodeTypeCall.CONSTRUCTOR_ID, TLSentCodeTypeCall.class);\n registerClass(TLSentCodeTypeFlashCall.CONSTRUCTOR_ID, TLSentCodeTypeFlashCall.class);\n registerClass(TLSentCodeTypeSms.CONSTRUCTOR_ID, TLSentCodeTypeSms.class);\n registerClass(TLAuthorization.CONSTRUCTOR_ID, TLAuthorization.class);\n registerClass(TLBotCommand.CONSTRUCTOR_ID, TLBotCommand.class);\n registerClass(TLBotInfo.CONSTRUCTOR_ID, TLBotInfo.class);\n registerClass(TLBotInlineMediaResult.CONSTRUCTOR_ID, TLBotInlineMediaResult.class);\n registerClass(TLBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLBotInlineMessageMediaAuto.class);\n registerClass(TLBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLBotInlineMessageMediaContact.class);\n registerClass(TLBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLBotInlineMessageMediaGeo.class);\n registerClass(TLBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLBotInlineMessageMediaVenue.class);\n registerClass(TLBotInlineMessageText.CONSTRUCTOR_ID, TLBotInlineMessageText.class);\n registerClass(TLBotInlineResult.CONSTRUCTOR_ID, TLBotInlineResult.class);\n registerClass(TLCdnConfig.CONSTRUCTOR_ID, TLCdnConfig.class);\n registerClass(TLCdnPublicKey.CONSTRUCTOR_ID, TLCdnPublicKey.class);\n registerClass(TLChannel.CONSTRUCTOR_ID, TLChannel.class);\n registerClass(TLChannelForbidden.CONSTRUCTOR_ID, TLChannelForbidden.class);\n registerClass(TLChannelFull.CONSTRUCTOR_ID, TLChannelFull.class);\n registerClass(TLChannelMessagesFilter.CONSTRUCTOR_ID, TLChannelMessagesFilter.class);\n registerClass(TLChannelMessagesFilterEmpty.CONSTRUCTOR_ID, TLChannelMessagesFilterEmpty.class);\n registerClass(TLChannelParticipant.CONSTRUCTOR_ID, TLChannelParticipant.class);\n registerClass(TLChannelParticipantCreator.CONSTRUCTOR_ID, TLChannelParticipantCreator.class);\n registerClass(TLChannelParticipantEditor.CONSTRUCTOR_ID, TLChannelParticipantEditor.class);\n registerClass(TLChannelParticipantKicked.CONSTRUCTOR_ID, TLChannelParticipantKicked.class);\n registerClass(TLChannelParticipantModerator.CONSTRUCTOR_ID, TLChannelParticipantModerator.class);\n registerClass(TLChannelParticipantSelf.CONSTRUCTOR_ID, TLChannelParticipantSelf.class);\n registerClass(TLChannelParticipantsAdmins.CONSTRUCTOR_ID, TLChannelParticipantsAdmins.class);\n registerClass(TLChannelParticipantsBots.CONSTRUCTOR_ID, TLChannelParticipantsBots.class);\n registerClass(TLChannelParticipantsKicked.CONSTRUCTOR_ID, TLChannelParticipantsKicked.class);\n registerClass(TLChannelParticipantsRecent.CONSTRUCTOR_ID, TLChannelParticipantsRecent.class);\n registerClass(TLChannelRoleEditor.CONSTRUCTOR_ID, TLChannelRoleEditor.class);\n registerClass(TLChannelRoleEmpty.CONSTRUCTOR_ID, TLChannelRoleEmpty.class);\n registerClass(TLChannelRoleModerator.CONSTRUCTOR_ID, TLChannelRoleModerator.class);\n registerClass(com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.class);\n registerClass(TLChannelParticipants.CONSTRUCTOR_ID, TLChannelParticipants.class);\n registerClass(TLChat.CONSTRUCTOR_ID, TLChat.class);\n registerClass(TLChatEmpty.CONSTRUCTOR_ID, TLChatEmpty.class);\n registerClass(TLChatForbidden.CONSTRUCTOR_ID, TLChatForbidden.class);\n registerClass(TLChatFull.CONSTRUCTOR_ID, TLChatFull.class);\n registerClass(TLChatInvite.CONSTRUCTOR_ID, TLChatInvite.class);\n registerClass(TLChatInviteAlready.CONSTRUCTOR_ID, TLChatInviteAlready.class);\n registerClass(TLChatInviteEmpty.CONSTRUCTOR_ID, TLChatInviteEmpty.class);\n registerClass(TLChatInviteExported.CONSTRUCTOR_ID, TLChatInviteExported.class);\n registerClass(TLChatParticipant.CONSTRUCTOR_ID, TLChatParticipant.class);\n registerClass(TLChatParticipantAdmin.CONSTRUCTOR_ID, TLChatParticipantAdmin.class);\n registerClass(TLChatParticipantCreator.CONSTRUCTOR_ID, TLChatParticipantCreator.class);\n registerClass(TLChatParticipants.CONSTRUCTOR_ID, TLChatParticipants.class);\n registerClass(TLChatParticipantsForbidden.CONSTRUCTOR_ID, TLChatParticipantsForbidden.class);\n registerClass(TLChatPhoto.CONSTRUCTOR_ID, TLChatPhoto.class);\n registerClass(TLChatPhotoEmpty.CONSTRUCTOR_ID, TLChatPhotoEmpty.class);\n registerClass(TLConfig.CONSTRUCTOR_ID, TLConfig.class);\n registerClass(TLContact.CONSTRUCTOR_ID, TLContact.class);\n registerClass(TLContactBlocked.CONSTRUCTOR_ID, TLContactBlocked.class);\n registerClass(TLContactLinkContact.CONSTRUCTOR_ID, TLContactLinkContact.class);\n registerClass(TLContactLinkHasPhone.CONSTRUCTOR_ID, TLContactLinkHasPhone.class);\n registerClass(TLContactLinkNone.CONSTRUCTOR_ID, TLContactLinkNone.class);\n registerClass(TLContactLinkUnknown.CONSTRUCTOR_ID, TLContactLinkUnknown.class);\n registerClass(TLContactStatus.CONSTRUCTOR_ID, TLContactStatus.class);\n registerClass(TLBlocked.CONSTRUCTOR_ID, TLBlocked.class);\n registerClass(TLBlockedSlice.CONSTRUCTOR_ID, TLBlockedSlice.class);\n registerClass(TLContacts.CONSTRUCTOR_ID, TLContacts.class);\n registerClass(TLContactsNotModified.CONSTRUCTOR_ID, TLContactsNotModified.class);\n registerClass(TLFound.CONSTRUCTOR_ID, TLFound.class);\n registerClass(TLImportedContacts.CONSTRUCTOR_ID, TLImportedContacts.class);\n registerClass(TLLink.CONSTRUCTOR_ID, TLLink.class);\n registerClass(TLResolvedPeer.CONSTRUCTOR_ID, TLResolvedPeer.class);\n registerClass(TLTopPeers.CONSTRUCTOR_ID, TLTopPeers.class);\n registerClass(TLTopPeersNotModified.CONSTRUCTOR_ID, TLTopPeersNotModified.class);\n registerClass(TLDataJSON.CONSTRUCTOR_ID, TLDataJSON.class);\n registerClass(TLDcOption.CONSTRUCTOR_ID, TLDcOption.class);\n registerClass(TLDialog.CONSTRUCTOR_ID, TLDialog.class);\n registerClass(TLDisabledFeature.CONSTRUCTOR_ID, TLDisabledFeature.class);\n registerClass(TLDocument.CONSTRUCTOR_ID, TLDocument.class);\n registerClass(TLDocumentAttributeAnimated.CONSTRUCTOR_ID, TLDocumentAttributeAnimated.class);\n registerClass(TLDocumentAttributeAudio.CONSTRUCTOR_ID, TLDocumentAttributeAudio.class);\n registerClass(TLDocumentAttributeFilename.CONSTRUCTOR_ID, TLDocumentAttributeFilename.class);\n registerClass(TLDocumentAttributeHasStickers.CONSTRUCTOR_ID, TLDocumentAttributeHasStickers.class);\n registerClass(TLDocumentAttributeImageSize.CONSTRUCTOR_ID, TLDocumentAttributeImageSize.class);\n registerClass(TLDocumentAttributeSticker.CONSTRUCTOR_ID, TLDocumentAttributeSticker.class);\n registerClass(TLDocumentAttributeVideo.CONSTRUCTOR_ID, TLDocumentAttributeVideo.class);\n registerClass(TLDocumentEmpty.CONSTRUCTOR_ID, TLDocumentEmpty.class);\n registerClass(TLDraftMessage.CONSTRUCTOR_ID, TLDraftMessage.class);\n registerClass(TLDraftMessageEmpty.CONSTRUCTOR_ID, TLDraftMessageEmpty.class);\n registerClass(TLEncryptedChat.CONSTRUCTOR_ID, TLEncryptedChat.class);\n registerClass(TLEncryptedChatDiscarded.CONSTRUCTOR_ID, TLEncryptedChatDiscarded.class);\n registerClass(TLEncryptedChatEmpty.CONSTRUCTOR_ID, TLEncryptedChatEmpty.class);\n registerClass(TLEncryptedChatRequested.CONSTRUCTOR_ID, TLEncryptedChatRequested.class);\n registerClass(TLEncryptedChatWaiting.CONSTRUCTOR_ID, TLEncryptedChatWaiting.class);\n registerClass(TLEncryptedFile.CONSTRUCTOR_ID, TLEncryptedFile.class);\n registerClass(TLEncryptedFileEmpty.CONSTRUCTOR_ID, TLEncryptedFileEmpty.class);\n registerClass(TLEncryptedMessage.CONSTRUCTOR_ID, TLEncryptedMessage.class);\n registerClass(TLEncryptedMessageService.CONSTRUCTOR_ID, TLEncryptedMessageService.class);\n registerClass(TLExportedMessageLink.CONSTRUCTOR_ID, TLExportedMessageLink.class);\n registerClass(TLFileLocation.CONSTRUCTOR_ID, TLFileLocation.class);\n registerClass(TLFileLocationUnavailable.CONSTRUCTOR_ID, TLFileLocationUnavailable.class);\n registerClass(TLFoundGif.CONSTRUCTOR_ID, TLFoundGif.class);\n registerClass(TLFoundGifCached.CONSTRUCTOR_ID, TLFoundGifCached.class);\n registerClass(TLGame.CONSTRUCTOR_ID, TLGame.class);\n registerClass(TLGeoPoint.CONSTRUCTOR_ID, TLGeoPoint.class);\n registerClass(TLGeoPointEmpty.CONSTRUCTOR_ID, TLGeoPointEmpty.class);\n registerClass(TLAppUpdate.CONSTRUCTOR_ID, TLAppUpdate.class);\n registerClass(TLInviteText.CONSTRUCTOR_ID, TLInviteText.class);\n registerClass(TLNoAppUpdate.CONSTRUCTOR_ID, TLNoAppUpdate.class);\n registerClass(TLSupport.CONSTRUCTOR_ID, TLSupport.class);\n registerClass(TLTermsOfService.CONSTRUCTOR_ID, TLTermsOfService.class);\n registerClass(TLHighScore.CONSTRUCTOR_ID, TLHighScore.class);\n registerClass(TLImportedContact.CONSTRUCTOR_ID, TLImportedContact.class);\n registerClass(TLInlineBotSwitchPM.CONSTRUCTOR_ID, TLInlineBotSwitchPM.class);\n registerClass(TLInputAppEvent.CONSTRUCTOR_ID, TLInputAppEvent.class);\n registerClass(TLInputBotInlineMessageGame.CONSTRUCTOR_ID, TLInputBotInlineMessageGame.class);\n registerClass(TLInputBotInlineMessageID.CONSTRUCTOR_ID, TLInputBotInlineMessageID.class);\n registerClass(TLInputBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaAuto.class);\n registerClass(TLInputBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaContact.class);\n registerClass(TLInputBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaGeo.class);\n registerClass(TLInputBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaVenue.class);\n registerClass(TLInputBotInlineMessageText.CONSTRUCTOR_ID, TLInputBotInlineMessageText.class);\n registerClass(TLInputBotInlineResult.CONSTRUCTOR_ID, TLInputBotInlineResult.class);\n registerClass(TLInputBotInlineResultDocument.CONSTRUCTOR_ID, TLInputBotInlineResultDocument.class);\n registerClass(TLInputBotInlineResultGame.CONSTRUCTOR_ID, TLInputBotInlineResultGame.class);\n registerClass(TLInputBotInlineResultPhoto.CONSTRUCTOR_ID, TLInputBotInlineResultPhoto.class);\n registerClass(TLInputChannel.CONSTRUCTOR_ID, TLInputChannel.class);\n registerClass(TLInputChannelEmpty.CONSTRUCTOR_ID, TLInputChannelEmpty.class);\n registerClass(TLInputChatPhoto.CONSTRUCTOR_ID, TLInputChatPhoto.class);\n registerClass(TLInputChatPhotoEmpty.CONSTRUCTOR_ID, TLInputChatPhotoEmpty.class);\n registerClass(TLInputChatUploadedPhoto.CONSTRUCTOR_ID, TLInputChatUploadedPhoto.class);\n registerClass(TLInputDocument.CONSTRUCTOR_ID, TLInputDocument.class);\n registerClass(TLInputDocumentEmpty.CONSTRUCTOR_ID, TLInputDocumentEmpty.class);\n registerClass(TLInputDocumentFileLocation.CONSTRUCTOR_ID, TLInputDocumentFileLocation.class);\n registerClass(TLInputEncryptedChat.CONSTRUCTOR_ID, TLInputEncryptedChat.class);\n registerClass(TLInputEncryptedFile.CONSTRUCTOR_ID, TLInputEncryptedFile.class);\n registerClass(TLInputEncryptedFileBigUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileBigUploaded.class);\n registerClass(TLInputEncryptedFileEmpty.CONSTRUCTOR_ID, TLInputEncryptedFileEmpty.class);\n registerClass(TLInputEncryptedFileLocation.CONSTRUCTOR_ID, TLInputEncryptedFileLocation.class);\n registerClass(TLInputEncryptedFileUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileUploaded.class);\n registerClass(TLInputFile.CONSTRUCTOR_ID, TLInputFile.class);\n registerClass(TLInputFileBig.CONSTRUCTOR_ID, TLInputFileBig.class);\n registerClass(TLInputFileLocation.CONSTRUCTOR_ID, TLInputFileLocation.class);\n registerClass(TLInputGameID.CONSTRUCTOR_ID, TLInputGameID.class);\n registerClass(TLInputGameShortName.CONSTRUCTOR_ID, TLInputGameShortName.class);\n registerClass(TLInputGeoPoint.CONSTRUCTOR_ID, TLInputGeoPoint.class);\n registerClass(TLInputGeoPointEmpty.CONSTRUCTOR_ID, TLInputGeoPointEmpty.class);\n registerClass(TLInputMediaContact.CONSTRUCTOR_ID, TLInputMediaContact.class);\n registerClass(TLInputMediaDocument.CONSTRUCTOR_ID, TLInputMediaDocument.class);\n registerClass(TLInputMediaDocumentExternal.CONSTRUCTOR_ID, TLInputMediaDocumentExternal.class);\n registerClass(TLInputMediaEmpty.CONSTRUCTOR_ID, TLInputMediaEmpty.class);\n registerClass(TLInputMediaGame.CONSTRUCTOR_ID, TLInputMediaGame.class);\n registerClass(TLInputMediaGeoPoint.CONSTRUCTOR_ID, TLInputMediaGeoPoint.class);\n registerClass(TLInputMediaGifExternal.CONSTRUCTOR_ID, TLInputMediaGifExternal.class);\n registerClass(TLInputMediaInvoice.CONSTRUCTOR_ID, TLInputMediaInvoice.class);\n registerClass(TLInputMediaPhoto.CONSTRUCTOR_ID, TLInputMediaPhoto.class);\n registerClass(TLInputMediaPhotoExternal.CONSTRUCTOR_ID, TLInputMediaPhotoExternal.class);\n registerClass(TLInputMediaUploadedDocument.CONSTRUCTOR_ID, TLInputMediaUploadedDocument.class);\n registerClass(TLInputMediaUploadedPhoto.CONSTRUCTOR_ID, TLInputMediaUploadedPhoto.class);\n registerClass(TLInputMediaUploadedThumbDocument.CONSTRUCTOR_ID, TLInputMediaUploadedThumbDocument.class);\n registerClass(TLInputMediaVenue.CONSTRUCTOR_ID, TLInputMediaVenue.class);\n registerClass(TLInputMessageEntityMentionName.CONSTRUCTOR_ID, TLInputMessageEntityMentionName.class);\n registerClass(TLInputMessagesFilterChatPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterChatPhotos.class);\n registerClass(TLInputMessagesFilterDocument.CONSTRUCTOR_ID, TLInputMessagesFilterDocument.class);\n registerClass(TLInputMessagesFilterEmpty.CONSTRUCTOR_ID, TLInputMessagesFilterEmpty.class);\n registerClass(TLInputMessagesFilterGif.CONSTRUCTOR_ID, TLInputMessagesFilterGif.class);\n registerClass(TLInputMessagesFilterMusic.CONSTRUCTOR_ID, TLInputMessagesFilterMusic.class);\n registerClass(TLInputMessagesFilterPhoneCalls.CONSTRUCTOR_ID, TLInputMessagesFilterPhoneCalls.class);\n registerClass(TLInputMessagesFilterPhotoVideo.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideo.class);\n registerClass(TLInputMessagesFilterPhotoVideoDocuments.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideoDocuments.class);", "pre_mask_code": "package com.github.badoualy.telegram.tl.api;\n\nimport com.github.badoualy.telegram.tl.TLContext;\nimport com.github.badoualy.telegram.tl.api.account.TLAuthorizations;\nimport com.github.badoualy.telegram.tl.api.account.TLNoPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordInputSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPrivacyRules;\nimport com.github.badoualy.telegram.tl.api.account.TLTmpPassword;\nimport com.github.badoualy.telegram.tl.api.auth.TLCheckedPhone;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.auth.TLExportedAuthorization;\nimport com.github.badoualy.telegram.tl.api.auth.TLPasswordRecovery;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCode;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeApp;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.channels.TLChannelParticipants;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlocked;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlockedSlice;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContactsNotModified;\nimport com.github.badoualy.telegram.tl.api.contacts.TLFound;\nimport com.github.badoualy.telegram.tl.api.contacts.TLImportedContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLLink;\nimport com.github.badoualy.telegram.tl.api.contacts.TLResolvedPeer;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeers;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeersNotModified;\nimport com.github.badoualy.telegram.tl.api.help.TLAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLInviteText;\nimport com.github.badoualy.telegram.tl.api.help.TLNoAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLSupport;\nimport com.github.badoualy.telegram.tl.api.help.TLTermsOfService;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedHistory;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLArchivedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotCallbackAnswer;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotResults;\nimport com.github.badoualy.telegram.tl.api.messages.TLChannelMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLChats;\nimport com.github.badoualy.telegram.tl.api.messages.TLChatsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfig;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfigNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLFoundGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLHighScores;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessageEditData;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessagesSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLPeerDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifsNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedFile;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedMessage;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultArchive;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultSuccess;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentForm;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentReceipt;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentResult;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentVerficationNeeded;\nimport com.github.badoualy.telegram.tl.api.payments.TLSavedInfo;\nimport com.github.badoualy.telegram.tl.api.payments.TLValidatedRequestedInfo;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotos;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotosSlice;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileGif;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileJpeg;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMov;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp3;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp4;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePartial;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePdf;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePng;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileUnknown;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileWebp;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceSlice;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLState;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFileReuploadNeeded;\nimport com.github.badoualy.telegram.tl.api.upload.TLFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLFileCdnRedirect;\nimport com.github.badoualy.telegram.tl.api.upload.TLWebFile;\n\n/**\n * @author Yannick Badoual example@nnthink.com\n * @see http://example.com\n */\n@SuppressWarnings(\"unused\")\npublic class TLApiContext extends TLContext {\n\n private static TLApiContext instance;\n\n public TLApiContext() {\n super(543);\n }\n\n public static TLApiContext getInstance() {\n if (instance == null) {\n instance = new TLApiContext();\n }\n return instance;\n }\n\n @Override\n public void init() {", "post_mask_code": "\n registerClass(TLInputMessagesFilterPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterPhotos.class);\n registerClass(TLInputMessagesFilterRoundVideo.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVideo.class);\n registerClass(TLInputMessagesFilterRoundVoice.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVoice.class);\n registerClass(TLInputMessagesFilterUrl.CONSTRUCTOR_ID, TLInputMessagesFilterUrl.class);\n registerClass(TLInputMessagesFilterVideo.CONSTRUCTOR_ID, TLInputMessagesFilterVideo.class);\n registerClass(TLInputMessagesFilterVoice.CONSTRUCTOR_ID, TLInputMessagesFilterVoice.class);\n registerClass(TLInputNotifyAll.CONSTRUCTOR_ID, TLInputNotifyAll.class);\n registerClass(TLInputNotifyChats.CONSTRUCTOR_ID, TLInputNotifyChats.class);\n registerClass(TLInputNotifyPeer.CONSTRUCTOR_ID, TLInputNotifyPeer.class);\n registerClass(TLInputNotifyUsers.CONSTRUCTOR_ID, TLInputNotifyUsers.class);\n registerClass(TLInputPaymentCredentials.CONSTRUCTOR_ID, TLInputPaymentCredentials.class);\n registerClass(TLInputPaymentCredentialsSaved.CONSTRUCTOR_ID, TLInputPaymentCredentialsSaved.class);\n registerClass(TLInputPeerChannel.CONSTRUCTOR_ID, TLInputPeerChannel.class);\n registerClass(TLInputPeerChat.CONSTRUCTOR_ID, TLInputPeerChat.class);\n registerClass(TLInputPeerEmpty.CONSTRUCTOR_ID, TLInputPeerEmpty.class);\n registerClass(TLInputPeerNotifyEventsAll.CONSTRUCTOR_ID, TLInputPeerNotifyEventsAll.class);\n registerClass(TLInputPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLInputPeerNotifyEventsEmpty.class);\n registerClass(TLInputPeerNotifySettings.CONSTRUCTOR_ID, TLInputPeerNotifySettings.class);\n registerClass(TLInputPeerSelf.CONSTRUCTOR_ID, TLInputPeerSelf.class);\n registerClass(TLInputPeerUser.CONSTRUCTOR_ID, TLInputPeerUser.class);\n registerClass(TLInputPhoneCall.CONSTRUCTOR_ID, TLInputPhoneCall.class);\n registerClass(TLInputPhoneContact.CONSTRUCTOR_ID, TLInputPhoneContact.class);\n registerClass(TLInputPhoto.CONSTRUCTOR_ID, TLInputPhoto.class);\n registerClass(TLInputPhotoEmpty.CONSTRUCTOR_ID, TLInputPhotoEmpty.class);\n registerClass(TLInputPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLInputPrivacyKeyChatInvite.class);\n registerClass(TLInputPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLInputPrivacyKeyPhoneCall.class);\n registerClass(TLInputPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLInputPrivacyKeyStatusTimestamp.class);\n registerClass(TLInputPrivacyValueAllowAll.CONSTRUCTOR_ID, TLInputPrivacyValueAllowAll.class);\n registerClass(TLInputPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueAllowContacts.class);\n registerClass(TLInputPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueAllowUsers.class);\n registerClass(TLInputPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowAll.class);\n registerClass(TLInputPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowContacts.class);\n registerClass(TLInputPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowUsers.class);\n registerClass(TLInputReportReasonOther.CONSTRUCTOR_ID, TLInputReportReasonOther.class);\n registerClass(TLInputReportReasonPornography.CONSTRUCTOR_ID, TLInputReportReasonPornography.class);\n registerClass(TLInputReportReasonSpam.CONSTRUCTOR_ID, TLInputReportReasonSpam.class);\n registerClass(TLInputReportReasonViolence.CONSTRUCTOR_ID, TLInputReportReasonViolence.class);\n registerClass(TLInputStickerSetEmpty.CONSTRUCTOR_ID, TLInputStickerSetEmpty.class);\n registerClass(TLInputStickerSetID.CONSTRUCTOR_ID, TLInputStickerSetID.class);\n registerClass(TLInputStickerSetShortName.CONSTRUCTOR_ID, TLInputStickerSetShortName.class);\n registerClass(TLInputStickeredMediaDocument.CONSTRUCTOR_ID, TLInputStickeredMediaDocument.class);\n registerClass(TLInputStickeredMediaPhoto.CONSTRUCTOR_ID, TLInputStickeredMediaPhoto.class);\n registerClass(TLInputUser.CONSTRUCTOR_ID, TLInputUser.class);\n registerClass(TLInputUserEmpty.CONSTRUCTOR_ID, TLInputUserEmpty.class);\n registerClass(TLInputUserSelf.CONSTRUCTOR_ID, TLInputUserSelf.class);\n registerClass(TLInputWebDocument.CONSTRUCTOR_ID, TLInputWebDocument.class);\n registerClass(TLInputWebFileLocation.CONSTRUCTOR_ID, TLInputWebFileLocation.class);\n registerClass(TLInvoice.CONSTRUCTOR_ID, TLInvoice.class);\n registerClass(TLKeyboardButton.CONSTRUCTOR_ID, TLKeyboardButton.class);\n registerClass(TLKeyboardButtonBuy.CONSTRUCTOR_ID, TLKeyboardButtonBuy.class);\n registerClass(TLKeyboardButtonCallback.CONSTRUCTOR_ID, TLKeyboardButtonCallback.class);\n registerClass(TLKeyboardButtonGame.CONSTRUCTOR_ID, TLKeyboardButtonGame.class);\n registerClass(TLKeyboardButtonRequestGeoLocation.CONSTRUCTOR_ID, TLKeyboardButtonRequestGeoLocation.class);\n registerClass(TLKeyboardButtonRequestPhone.CONSTRUCTOR_ID, TLKeyboardButtonRequestPhone.class);\n registerClass(TLKeyboardButtonRow.CONSTRUCTOR_ID, TLKeyboardButtonRow.class);\n registerClass(TLKeyboardButtonSwitchInline.CONSTRUCTOR_ID, TLKeyboardButtonSwitchInline.class);\n registerClass(TLKeyboardButtonUrl.CONSTRUCTOR_ID, TLKeyboardButtonUrl.class);\n registerClass(TLLabeledPrice.CONSTRUCTOR_ID, TLLabeledPrice.class);\n registerClass(TLMaskCoords.CONSTRUCTOR_ID, TLMaskCoords.class);\n registerClass(TLMessage.CONSTRUCTOR_ID, TLMessage.class);\n registerClass(TLMessageActionChannelCreate.CONSTRUCTOR_ID, TLMessageActionChannelCreate.class);\n registerClass(TLMessageActionChannelMigrateFrom.CONSTRUCTOR_ID, TLMessageActionChannelMigrateFrom.class);\n registerClass(TLMessageActionChatAddUser.CONSTRUCTOR_ID, TLMessageActionChatAddUser.class);\n registerClass(TLMessageActionChatCreate.CONSTRUCTOR_ID, TLMessageActionChatCreate.class);\n registerClass(TLMessageActionChatDeletePhoto.CONSTRUCTOR_ID, TLMessageActionChatDeletePhoto.class);\n registerClass(TLMessageActionChatDeleteUser.CONSTRUCTOR_ID, TLMessageActionChatDeleteUser.class);\n registerClass(TLMessageActionChatEditPhoto.CONSTRUCTOR_ID, TLMessageActionChatEditPhoto.class);\n registerClass(TLMessageActionChatEditTitle.CONSTRUCTOR_ID, TLMessageActionChatEditTitle.class);\n registerClass(TLMessageActionChatJoinedByLink.CONSTRUCTOR_ID, TLMessageActionChatJoinedByLink.class);\n registerClass(TLMessageActionChatMigrateTo.CONSTRUCTOR_ID, TLMessageActionChatMigrateTo.class);\n registerClass(TLMessageActionEmpty.CONSTRUCTOR_ID, TLMessageActionEmpty.class);\n registerClass(TLMessageActionGameScore.CONSTRUCTOR_ID, TLMessageActionGameScore.class);\n registerClass(TLMessageActionHistoryClear.CONSTRUCTOR_ID, TLMessageActionHistoryClear.class);\n registerClass(TLMessageActionPaymentSent.CONSTRUCTOR_ID, TLMessageActionPaymentSent.class);\n registerClass(TLMessageActionPaymentSentMe.CONSTRUCTOR_ID, TLMessageActionPaymentSentMe.class);\n registerClass(TLMessageActionPhoneCall.CONSTRUCTOR_ID, TLMessageActionPhoneCall.class);\n registerClass(TLMessageActionPinMessage.CONSTRUCTOR_ID, TLMessageActionPinMessage.class);\n registerClass(TLMessageEmpty.CONSTRUCTOR_ID, TLMessageEmpty.class);\n registerClass(TLMessageEntityBold.CONSTRUCTOR_ID, TLMessageEntityBold.class);\n registerClass(TLMessageEntityBotCommand.CONSTRUCTOR_ID, TLMessageEntityBotCommand.class);\n registerClass(TLMessageEntityCode.CONSTRUCTOR_ID, TLMessageEntityCode.class);\n registerClass(TLMessageEntityEmail.CONSTRUCTOR_ID, TLMessageEntityEmail.class);\n registerClass(TLMessageEntityHashtag.CONSTRUCTOR_ID, TLMessageEntityHashtag.class);\n registerClass(TLMessageEntityItalic.CONSTRUCTOR_ID, TLMessageEntityItalic.class);\n registerClass(TLMessageEntityMention.CONSTRUCTOR_ID, TLMessageEntityMention.class);\n registerClass(TLMessageEntityMentionName.CONSTRUCTOR_ID, TLMessageEntityMentionName.class);\n registerClass(TLMessageEntityPre.CONSTRUCTOR_ID, TLMessageEntityPre.class);\n registerClass(TLMessageEntityTextUrl.CONSTRUCTOR_ID, TLMessageEntityTextUrl.class);\n registerClass(TLMessageEntityUnknown.CONSTRUCTOR_ID, TLMessageEntityUnknown.class);\n registerClass(TLMessageEntityUrl.CONSTRUCTOR_ID, TLMessageEntityUrl.class);\n registerClass(TLMessageFwdHeader.CONSTRUCTOR_ID, TLMessageFwdHeader.class);\n registerClass(TLMessageMediaContact.CONSTRUCTOR_ID, TLMessageMediaContact.class);\n registerClass(TLMessageMediaDocument.CONSTRUCTOR_ID, TLMessageMediaDocument.class);\n registerClass(TLMessageMediaEmpty.CONSTRUCTOR_ID, TLMessageMediaEmpty.class);\n registerClass(TLMessageMediaGame.CONSTRUCTOR_ID, TLMessageMediaGame.class);\n registerClass(TLMessageMediaGeo.CONSTRUCTOR_ID, TLMessageMediaGeo.class);\n registerClass(TLMessageMediaInvoice.CONSTRUCTOR_ID, TLMessageMediaInvoice.class);\n registerClass(TLMessageMediaPhoto.CONSTRUCTOR_ID, TLMessageMediaPhoto.class);\n registerClass(TLMessageMediaUnsupported.CONSTRUCTOR_ID, TLMessageMediaUnsupported.class);\n registerClass(TLMessageMediaVenue.CONSTRUCTOR_ID, TLMessageMediaVenue.class);\n registerClass(TLMessageMediaWebPage.CONSTRUCTOR_ID, TLMessageMediaWebPage.class);\n registerClass(TLMessageRange.CONSTRUCTOR_ID, TLMessageRange.class);\n registerClass(TLMessageService.CONSTRUCTOR_ID, TLMessageService.class);\n registerClass(TLAffectedHistory.CONSTRUCTOR_ID, TLAffectedHistory.class);\n registerClass(TLAffectedMessages.CONSTRUCTOR_ID, TLAffectedMessages.class);\n registerClass(TLAllStickers.CONSTRUCTOR_ID, TLAllStickers.class);\n registerClass(TLAllStickersNotModified.CONSTRUCTOR_ID, TLAllStickersNotModified.class);\n registerClass(TLArchivedStickers.CONSTRUCTOR_ID, TLArchivedStickers.class);\n registerClass(TLBotCallbackAnswer.CONSTRUCTOR_ID, TLBotCallbackAnswer.class);\n registerClass(TLBotResults.CONSTRUCTOR_ID, TLBotResults.class);\n registerClass(TLChannelMessages.CONSTRUCTOR_ID, TLChannelMessages.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLChatFull.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLChatFull.class);\n registerClass(TLChats.CONSTRUCTOR_ID, TLChats.class);\n registerClass(TLChatsSlice.CONSTRUCTOR_ID, TLChatsSlice.class);\n registerClass(TLDhConfig.CONSTRUCTOR_ID, TLDhConfig.class);\n registerClass(TLDhConfigNotModified.CONSTRUCTOR_ID, TLDhConfigNotModified.class);\n registerClass(TLDialogs.CONSTRUCTOR_ID, TLDialogs.class);\n registerClass(TLDialogsSlice.CONSTRUCTOR_ID, TLDialogsSlice.class);\n registerClass(TLFeaturedStickers.CONSTRUCTOR_ID, TLFeaturedStickers.class);\n registerClass(TLFeaturedStickersNotModified.CONSTRUCTOR_ID, TLFeaturedStickersNotModified.class);\n registerClass(TLFoundGifs.CONSTRUCTOR_ID, TLFoundGifs.class);\n registerClass(TLHighScores.CONSTRUCTOR_ID, TLHighScores.class);\n registerClass(TLMessageEditData.CONSTRUCTOR_ID, TLMessageEditData.class);\n registerClass(TLMessages.CONSTRUCTOR_ID, TLMessages.class);\n registerClass(TLMessagesSlice.CONSTRUCTOR_ID, TLMessagesSlice.class);\n registerClass(TLPeerDialogs.CONSTRUCTOR_ID, TLPeerDialogs.class);\n registerClass(TLRecentStickers.CONSTRUCTOR_ID, TLRecentStickers.class);\n registerClass(TLRecentStickersNotModified.CONSTRUCTOR_ID, TLRecentStickersNotModified.class);\n registerClass(TLSavedGifs.CONSTRUCTOR_ID, TLSavedGifs.class);\n registerClass(TLSavedGifsNotModified.CONSTRUCTOR_ID, TLSavedGifsNotModified.class);\n registerClass(TLSentEncryptedFile.CONSTRUCTOR_ID, TLSentEncryptedFile.class);\n registerClass(TLSentEncryptedMessage.CONSTRUCTOR_ID, TLSentEncryptedMessage.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLStickerSet.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLStickerSet.class);\n registerClass(TLStickerSetInstallResultArchive.CONSTRUCTOR_ID, TLStickerSetInstallResultArchive.class);\n registerClass(TLStickerSetInstallResultSuccess.CONSTRUCTOR_ID, TLStickerSetInstallResultSuccess.class);\n registerClass(TLStickers.CONSTRUCTOR_ID, TLStickers.class);\n registerClass(TLStickersNotModified.CONSTRUCTOR_ID, TLStickersNotModified.class);\n registerClass(TLNearestDc.CONSTRUCTOR_ID, TLNearestDc.class);\n registerClass(TLNotifyAll.CONSTRUCTOR_ID, TLNotifyAll.class);\n registerClass(TLNotifyChats.CONSTRUCTOR_ID, TLNotifyChats.class);\n registerClass(TLNotifyPeer.CONSTRUCTOR_ID, TLNotifyPeer.class);\n registerClass(TLNotifyUsers.CONSTRUCTOR_ID, TLNotifyUsers.class);\n registerClass(TLPageBlockAnchor.CONSTRUCTOR_ID, TLPageBlockAnchor.class);\n registerClass(TLPageBlockAuthorDate.CONSTRUCTOR_ID, TLPageBlockAuthorDate.class);\n registerClass(TLPageBlockBlockquote.CONSTRUCTOR_ID, TLPageBlockBlockquote.class);\n registerClass(TLPageBlockChannel.CONSTRUCTOR_ID, TLPageBlockChannel.class);\n registerClass(TLPageBlockCollage.CONSTRUCTOR_ID, TLPageBlockCollage.class);\n registerClass(TLPageBlockCover.CONSTRUCTOR_ID, TLPageBlockCover.class);\n registerClass(TLPageBlockDivider.CONSTRUCTOR_ID, TLPageBlockDivider.class);\n registerClass(TLPageBlockEmbed.CONSTRUCTOR_ID, TLPageBlockEmbed.class);\n registerClass(TLPageBlockEmbedPost.CONSTRUCTOR_ID, TLPageBlockEmbedPost.class);\n registerClass(TLPageBlockFooter.CONSTRUCTOR_ID, TLPageBlockFooter.class);\n registerClass(TLPageBlockHeader.CONSTRUCTOR_ID, TLPageBlockHeader.class);\n registerClass(TLPageBlockList.CONSTRUCTOR_ID, TLPageBlockList.class);\n registerClass(TLPageBlockParagraph.CONSTRUCTOR_ID, TLPageBlockParagraph.class);\n registerClass(TLPageBlockPhoto.CONSTRUCTOR_ID, TLPageBlockPhoto.class);\n registerClass(TLPageBlockPreformatted.CONSTRUCTOR_ID, TLPageBlockPreformatted.class);\n registerClass(TLPageBlockPullquote.CONSTRUCTOR_ID, TLPageBlockPullquote.class);\n registerClass(TLPageBlockSlideshow.CONSTRUCTOR_ID, TLPageBlockSlideshow.class);\n registerClass(TLPageBlockSubheader.CONSTRUCTOR_ID, TLPageBlockSubheader.class);\n registerClass(TLPageBlockSubtitle.CONSTRUCTOR_ID, TLPageBlockSubtitle.class);\n registerClass(TLPageBlockTitle.CONSTRUCTOR_ID, TLPageBlockTitle.class);\n registerClass(TLPageBlockUnsupported.CONSTRUCTOR_ID, TLPageBlockUnsupported.class);\n registerClass(TLPageBlockVideo.CONSTRUCTOR_ID, TLPageBlockVideo.class);\n registerClass(TLPageFull.CONSTRUCTOR_ID, TLPageFull.class);\n registerClass(TLPagePart.CONSTRUCTOR_ID, TLPagePart.class);\n registerClass(TLPaymentCharge.CONSTRUCTOR_ID, TLPaymentCharge.class);\n registerClass(TLPaymentRequestedInfo.CONSTRUCTOR_ID, TLPaymentRequestedInfo.class);\n registerClass(TLPaymentSavedCredentialsCard.CONSTRUCTOR_ID, TLPaymentSavedCredentialsCard.class);\n registerClass(TLPaymentForm.CONSTRUCTOR_ID, TLPaymentForm.class);\n registerClass(TLPaymentReceipt.CONSTRUCTOR_ID, TLPaymentReceipt.class);\n registerClass(TLPaymentResult.CONSTRUCTOR_ID, TLPaymentResult.class);\n registerClass(TLPaymentVerficationNeeded.CONSTRUCTOR_ID, TLPaymentVerficationNeeded.class);\n registerClass(TLSavedInfo.CONSTRUCTOR_ID, TLSavedInfo.class);\n registerClass(TLValidatedRequestedInfo.CONSTRUCTOR_ID, TLValidatedRequestedInfo.class);\n registerClass(TLPeerChannel.CONSTRUCTOR_ID, TLPeerChannel.class);\n registerClass(TLPeerChat.CONSTRUCTOR_ID, TLPeerChat.class);\n registerClass(TLPeerNotifyEventsAll.CONSTRUCTOR_ID, TLPeerNotifyEventsAll.class);\n registerClass(TLPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLPeerNotifyEventsEmpty.class);\n registerClass(TLPeerNotifySettings.CONSTRUCTOR_ID, TLPeerNotifySettings.class);\n registerClass(TLPeerNotifySettingsEmpty.CONSTRUCTOR_ID, TLPeerNotifySettingsEmpty.class);\n registerClass(TLPeerSettings.CONSTRUCTOR_ID, TLPeerSettings.class);\n registerClass(TLPeerUser.CONSTRUCTOR_ID, TLPeerUser.class);\n registerClass(com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.class);\n registerClass(TLPhoneCall.CONSTRUCTOR_ID, TLPhoneCall.class);\n registerClass(TLPhoneCallAccepted.CONSTRUCTOR_ID, TLPhoneCallAccepted.class);\n registerClass(TLPhoneCallDiscardReasonBusy.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonBusy.class);\n registerClass(TLPhoneCallDiscardReasonDisconnect.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonDisconnect.class);\n registerClass(TLPhoneCallDiscardReasonHangup.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonHangup.class);\n registerClass(TLPhoneCallDiscardReasonMissed.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonMissed.class);\n registerClass(TLPhoneCallDiscarded.CONSTRUCTOR_ID, TLPhoneCallDiscarded.class);\n registerClass(TLPhoneCallEmpty.CONSTRUCTOR_ID, TLPhoneCallEmpty.class);\n registerClass(TLPhoneCallProtocol.CONSTRUCTOR_ID, TLPhoneCallProtocol.class);\n registerClass(TLPhoneCallRequested.CONSTRUCTOR_ID, TLPhoneCallRequested.class);\n registerClass(TLPhoneCallWaiting.CONSTRUCTOR_ID, TLPhoneCallWaiting.class);\n registerClass(TLPhoneConnection.CONSTRUCTOR_ID, TLPhoneConnection.class);\n registerClass(TLPhoto.CONSTRUCTOR_ID, TLPhoto.class);\n registerClass(TLPhotoCachedSize.CONSTRUCTOR_ID, TLPhotoCachedSize.class);\n registerClass(TLPhotoEmpty.CONSTRUCTOR_ID, TLPhotoEmpty.class);\n registerClass(TLPhotoSize.CONSTRUCTOR_ID, TLPhotoSize.class);\n registerClass(TLPhotoSizeEmpty.CONSTRUCTOR_ID, TLPhotoSizeEmpty.class);\n registerClass(com.github.badoualy.telegram.tl.api.photos.TLPhoto.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.photos.TLPhoto.class);\n registerClass(TLPhotos.CONSTRUCTOR_ID, TLPhotos.class);\n registerClass(TLPhotosSlice.CONSTRUCTOR_ID, TLPhotosSlice.class);\n registerClass(TLPostAddress.CONSTRUCTOR_ID, TLPostAddress.class);\n registerClass(TLPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLPrivacyKeyChatInvite.class);\n registerClass(TLPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLPrivacyKeyPhoneCall.class);\n registerClass(TLPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLPrivacyKeyStatusTimestamp.class);\n registerClass(TLPrivacyValueAllowAll.CONSTRUCTOR_ID, TLPrivacyValueAllowAll.class);\n registerClass(TLPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLPrivacyValueAllowContacts.class);\n registerClass(TLPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLPrivacyValueAllowUsers.class);\n registerClass(TLPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLPrivacyValueDisallowAll.class);\n registerClass(TLPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLPrivacyValueDisallowContacts.class);\n registerClass(TLPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLPrivacyValueDisallowUsers.class);\n registerClass(TLReceivedNotifyMessage.CONSTRUCTOR_ID, TLReceivedNotifyMessage.class);\n registerClass(TLReplyInlineMarkup.CONSTRUCTOR_ID, TLReplyInlineMarkup.class);\n registerClass(TLReplyKeyboardForceReply.CONSTRUCTOR_ID, TLReplyKeyboardForceReply.class);\n registerClass(TLReplyKeyboardHide.CONSTRUCTOR_ID, TLReplyKeyboardHide.class);\n registerClass(TLReplyKeyboardMarkup.CONSTRUCTOR_ID, TLReplyKeyboardMarkup.class);\n registerClass(TLSendMessageCancelAction.CONSTRUCTOR_ID, TLSendMessageCancelAction.class);\n registerClass(TLSendMessageChooseContactAction.CONSTRUCTOR_ID, TLSendMessageChooseContactAction.class);\n registerClass(TLSendMessageGamePlayAction.CONSTRUCTOR_ID, TLSendMessageGamePlayAction.class);\n registerClass(TLSendMessageGeoLocationAction.CONSTRUCTOR_ID, TLSendMessageGeoLocationAction.class);\n registerClass(TLSendMessageRecordAudioAction.CONSTRUCTOR_ID, TLSendMessageRecordAudioAction.class);\n registerClass(TLSendMessageRecordRoundAction.CONSTRUCTOR_ID, TLSendMessageRecordRoundAction.class);\n registerClass(TLSendMessageRecordVideoAction.CONSTRUCTOR_ID, TLSendMessageRecordVideoAction.class);\n registerClass(TLSendMessageTypingAction.CONSTRUCTOR_ID, TLSendMessageTypingAction.class);\n registerClass(TLSendMessageUploadAudioAction.CONSTRUCTOR_ID, TLSendMessageUploadAudioAction.class);\n registerClass(TLSendMessageUploadDocumentAction.CONSTRUCTOR_ID, TLSendMessageUploadDocumentAction.class);\n registerClass(TLSendMessageUploadPhotoAction.CONSTRUCTOR_ID, TLSendMessageUploadPhotoAction.class);\n registerClass(TLSendMessageUploadRoundAction.CONSTRUCTOR_ID, TLSendMessageUploadRoundAction.class);\n registerClass(TLSendMessageUploadVideoAction.CONSTRUCTOR_ID, TLSendMessageUploadVideoAction.class);\n registerClass(TLShippingOption.CONSTRUCTOR_ID, TLShippingOption.class);\n registerClass(TLStickerPack.CONSTRUCTOR_ID, TLStickerPack.class);\n registerClass(TLStickerSet.CONSTRUCTOR_ID, TLStickerSet.class);\n registerClass(TLStickerSetCovered.CONSTRUCTOR_ID, TLStickerSetCovered.class);\n registerClass(TLStickerSetMultiCovered.CONSTRUCTOR_ID, TLStickerSetMultiCovered.class);\n registerClass(TLFileGif.CONSTRUCTOR_ID, TLFileGif.class);\n registerClass(TLFileJpeg.CONSTRUCTOR_ID, TLFileJpeg.class);\n registerClass(TLFileMov.CONSTRUCTOR_ID, TLFileMov.class);\n registerClass(TLFileMp3.CONSTRUCTOR_ID, TLFileMp3.class);\n registerClass(TLFileMp4.CONSTRUCTOR_ID, TLFileMp4.class);\n registerClass(TLFilePartial.CONSTRUCTOR_ID, TLFilePartial.class);\n registerClass(TLFilePdf.CONSTRUCTOR_ID, TLFilePdf.class);\n registerClass(TLFilePng.CONSTRUCTOR_ID, TLFilePng.class);\n registerClass(TLFileUnknown.CONSTRUCTOR_ID, TLFileUnknown.class);\n registerClass(TLFileWebp.CONSTRUCTOR_ID, TLFileWebp.class);\n registerClass(TLTextBold.CONSTRUCTOR_ID, TLTextBold.class);\n registerClass(TLTextConcat.CONSTRUCTOR_ID, TLTextConcat.class);\n registerClass(TLTextEmail.CONSTRUCTOR_ID, TLTextEmail.class);\n registerClass(TLTextEmpty.CONSTRUCTOR_ID, TLTextEmpty.class);\n registerClass(TLTextFixed.CONSTRUCTOR_ID, TLTextFixed.class);\n registerClass(TLTextItalic.CONSTRUCTOR_ID, TLTextItalic.class);\n registerClass(TLTextPlain.CONSTRUCTOR_ID, TLTextPlain.class);\n registerClass(TLTextStrike.CONSTRUCTOR_ID, TLTextStrike.class);\n registerClass(TLTextUnderline.CONSTRUCTOR_ID, TLTextUnderline.class);\n registerClass(TLTextUrl.CONSTRUCTOR_ID, TLTextUrl.class);\n registerClass(TLTopPeer.CONSTRUCTOR_ID, TLTopPeer.class);\n registerClass(TLTopPeerCategoryBotsInline.CONSTRUCTOR_ID, TLTopPeerCategoryBotsInline.class);\n registerClass(TLTopPeerCategoryBotsPM.CONSTRUCTOR_ID, TLTopPeerCategoryBotsPM.class);\n registerClass(TLTopPeerCategoryChannels.CONSTRUCTOR_ID, TLTopPeerCategoryChannels.class);\n registerClass(TLTopPeerCategoryCorrespondents.CONSTRUCTOR_ID, TLTopPeerCategoryCorrespondents.class);\n registerClass(TLTopPeerCategoryGroups.CONSTRUCTOR_ID, TLTopPeerCategoryGroups.class);\n registerClass(TLTopPeerCategoryPeers.CONSTRUCTOR_ID, TLTopPeerCategoryPeers.class);\n registerClass(TLUpdateBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateBotCallbackQuery.class);\n registerClass(TLUpdateBotInlineQuery.CONSTRUCTOR_ID, TLUpdateBotInlineQuery.class);\n registerClass(TLUpdateBotInlineSend.CONSTRUCTOR_ID, TLUpdateBotInlineSend.class);\n registerClass(TLUpdateBotPrecheckoutQuery.CONSTRUCTOR_ID, TLUpdateBotPrecheckoutQuery.class);\n registerClass(TLUpdateBotShippingQuery.CONSTRUCTOR_ID, TLUpdateBotShippingQuery.class);\n registerClass(TLUpdateBotWebhookJSON.CONSTRUCTOR_ID, TLUpdateBotWebhookJSON.class);\n registerClass(TLUpdateBotWebhookJSONQuery.CONSTRUCTOR_ID, TLUpdateBotWebhookJSONQuery.class);\n registerClass(TLUpdateChannel.CONSTRUCTOR_ID, TLUpdateChannel.class);\n registerClass(TLUpdateChannelMessageViews.CONSTRUCTOR_ID, TLUpdateChannelMessageViews.class);\n registerClass(TLUpdateChannelPinnedMessage.CONSTRUCTOR_ID, TLUpdateChannelPinnedMessage.class);\n registerClass(TLUpdateChannelTooLong.CONSTRUCTOR_ID, TLUpdateChannelTooLong.class);\n registerClass(TLUpdateChannelWebPage.CONSTRUCTOR_ID, TLUpdateChannelWebPage.class);\n registerClass(TLUpdateChatAdmins.CONSTRUCTOR_ID, TLUpdateChatAdmins.class);\n registerClass(TLUpdateChatParticipantAdd.CONSTRUCTOR_ID, TLUpdateChatParticipantAdd.class);\n registerClass(TLUpdateChatParticipantAdmin.CONSTRUCTOR_ID, TLUpdateChatParticipantAdmin.class);\n registerClass(TLUpdateChatParticipantDelete.CONSTRUCTOR_ID, TLUpdateChatParticipantDelete.class);\n registerClass(TLUpdateChatParticipants.CONSTRUCTOR_ID, TLUpdateChatParticipants.class);\n registerClass(TLUpdateChatUserTyping.CONSTRUCTOR_ID, TLUpdateChatUserTyping.class);\n registerClass(TLUpdateConfig.CONSTRUCTOR_ID, TLUpdateConfig.class);\n registerClass(TLUpdateContactLink.CONSTRUCTOR_ID, TLUpdateContactLink.class);\n registerClass(TLUpdateContactRegistered.CONSTRUCTOR_ID, TLUpdateContactRegistered.class);\n registerClass(TLUpdateDcOptions.CONSTRUCTOR_ID, TLUpdateDcOptions.class);\n registerClass(TLUpdateDeleteChannelMessages.CONSTRUCTOR_ID, TLUpdateDeleteChannelMessages.class);\n registerClass(TLUpdateDeleteMessages.CONSTRUCTOR_ID, TLUpdateDeleteMessages.class);\n registerClass(TLUpdateDialogPinned.CONSTRUCTOR_ID, TLUpdateDialogPinned.class);\n registerClass(TLUpdateDraftMessage.CONSTRUCTOR_ID, TLUpdateDraftMessage.class);\n registerClass(TLUpdateEditChannelMessage.CONSTRUCTOR_ID, TLUpdateEditChannelMessage.class);\n registerClass(TLUpdateEditMessage.CONSTRUCTOR_ID, TLUpdateEditMessage.class);\n registerClass(TLUpdateEncryptedChatTyping.CONSTRUCTOR_ID, TLUpdateEncryptedChatTyping.class);\n registerClass(TLUpdateEncryptedMessagesRead.CONSTRUCTOR_ID, TLUpdateEncryptedMessagesRead.class);\n registerClass(TLUpdateEncryption.CONSTRUCTOR_ID, TLUpdateEncryption.class);\n registerClass(TLUpdateInlineBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateInlineBotCallbackQuery.class);\n registerClass(TLUpdateMessageID.CONSTRUCTOR_ID, TLUpdateMessageID.class);\n registerClass(TLUpdateNewChannelMessage.CONSTRUCTOR_ID, TLUpdateNewChannelMessage.class);\n registerClass(TLUpdateNewEncryptedMessage.CONSTRUCTOR_ID, TLUpdateNewEncryptedMessage.class);\n registerClass(TLUpdateNewMessage.CONSTRUCTOR_ID, TLUpdateNewMessage.class);\n registerClass(TLUpdateNewStickerSet.CONSTRUCTOR_ID, TLUpdateNewStickerSet.class);\n registerClass(TLUpdateNotifySettings.CONSTRUCTOR_ID, TLUpdateNotifySettings.class);\n registerClass(TLUpdatePhoneCall.CONSTRUCTOR_ID, TLUpdatePhoneCall.class);\n registerClass(TLUpdatePinnedDialogs.CONSTRUCTOR_ID, TLUpdatePinnedDialogs.class);\n registerClass(TLUpdatePrivacy.CONSTRUCTOR_ID, TLUpdatePrivacy.class);\n registerClass(TLUpdatePtsChanged.CONSTRUCTOR_ID, TLUpdatePtsChanged.class);\n registerClass(TLUpdateReadChannelInbox.CONSTRUCTOR_ID, TLUpdateReadChannelInbox.class);\n registerClass(TLUpdateReadChannelOutbox.CONSTRUCTOR_ID, TLUpdateReadChannelOutbox.class);\n registerClass(TLUpdateReadFeaturedStickers.CONSTRUCTOR_ID, TLUpdateReadFeaturedStickers.class);\n registerClass(TLUpdateReadHistoryInbox.CONSTRUCTOR_ID, TLUpdateReadHistoryInbox.class);\n registerClass(TLUpdateReadHistoryOutbox.CONSTRUCTOR_ID, TLUpdateReadHistoryOutbox.class);\n registerClass(TLUpdateReadMessagesContents.CONSTRUCTOR_ID, TLUpdateReadMessagesContents.class);\n registerClass(TLUpdateRecentStickers.CONSTRUCTOR_ID, TLUpdateRecentStickers.class);\n registerClass(TLUpdateSavedGifs.CONSTRUCTOR_ID, TLUpdateSavedGifs.class);\n registerClass(TLUpdateServiceNotification.CONSTRUCTOR_ID, TLUpdateServiceNotification.class);\n registerClass(TLUpdateShort.CONSTRUCTOR_ID, TLUpdateShort.class);\n registerClass(TLUpdateShortChatMessage.CONSTRUCTOR_ID, TLUpdateShortChatMessage.class);\n registerClass(TLUpdateShortMessage.CONSTRUCTOR_ID, TLUpdateShortMessage.class);\n registerClass(TLUpdateShortSentMessage.CONSTRUCTOR_ID, TLUpdateShortSentMessage.class);\n registerClass(TLUpdateStickerSets.CONSTRUCTOR_ID, TLUpdateStickerSets.class);\n registerClass(TLUpdateStickerSetsOrder.CONSTRUCTOR_ID, TLUpdateStickerSetsOrder.class);\n registerClass(TLUpdateUserBlocked.CONSTRUCTOR_ID, TLUpdateUserBlocked.class);\n registerClass(TLUpdateUserName.CONSTRUCTOR_ID, TLUpdateUserName.class);\n registerClass(TLUpdateUserPhone.CONSTRUCTOR_ID, TLUpdateUserPhone.class);\n registerClass(TLUpdateUserPhoto.CONSTRUCTOR_ID, TLUpdateUserPhoto.class);\n registerClass(TLUpdateUserStatus.CONSTRUCTOR_ID, TLUpdateUserStatus.class);\n registerClass(TLUpdateUserTyping.CONSTRUCTOR_ID, TLUpdateUserTyping.class);\n registerClass(TLUpdateWebPage.CONSTRUCTOR_ID, TLUpdateWebPage.class);\n registerClass(TLUpdates.CONSTRUCTOR_ID, TLUpdates.class);\n registerClass(TLChannelDifference.CONSTRUCTOR_ID, TLChannelDifference.class);\n registerClass(TLChannelDifferenceEmpty.CONSTRUCTOR_ID, TLChannelDifferenceEmpty.class);\n registerClass(TLChannelDifferenceTooLong.CONSTRUCTOR_ID, TLChannelDifferenceTooLong.class);\n registerClass(TLDifference.CONSTRUCTOR_ID, TLDifference.class);\n registerClass(TLDifferenceEmpty.CONSTRUCTOR_ID, TLDifferenceEmpty.class);\n registerClass(TLDifferenceSlice.CONSTRUCTOR_ID, TLDifferenceSlice.class);\n registerClass(TLDifferenceTooLong.CONSTRUCTOR_ID, TLDifferenceTooLong.class);\n registerClass(TLState.CONSTRUCTOR_ID, TLState.class);\n registerClass(TLUpdatesCombined.CONSTRUCTOR_ID, TLUpdatesCombined.class);\n registerClass(TLUpdatesTooLong.CONSTRUCTOR_ID, TLUpdatesTooLong.class);\n registerClass(TLCdnFile.CONSTRUCTOR_ID, TLCdnFile.class);\n registerClass(TLCdnFileReuploadNeeded.CONSTRUCTOR_ID, TLCdnFileReuploadNeeded.class);\n registerClass(TLFile.CONSTRUCTOR_ID, TLFile.class);\n registerClass(TLFileCdnRedirect.CONSTRUCTOR_ID, TLFileCdnRedirect.class);\n registerClass(TLWebFile.CONSTRUCTOR_ID, TLWebFile.class);\n registerClass(TLUser.CONSTRUCTOR_ID, TLUser.class);\n registerClass(TLUserEmpty.CONSTRUCTOR_ID, TLUserEmpty.class);\n registerClass(TLUserFull.CONSTRUCTOR_ID, TLUserFull.class);\n registerClass(TLUserProfilePhoto.CONSTRUCTOR_ID, TLUserProfilePhoto.class);\n registerClass(TLUserProfilePhotoEmpty.CONSTRUCTOR_ID, TLUserProfilePhotoEmpty.class);\n registerClass(TLUserStatusEmpty.CONSTRUCTOR_ID, TLUserStatusEmpty.class);\n registerClass(TLUserStatusLastMonth.CONSTRUCTOR_ID, TLUserStatusLastMonth.class);\n registerClass(TLUserStatusLastWeek.CONSTRUCTOR_ID, TLUserStatusLastWeek.class);\n registerClass(TLUserStatusOffline.CONSTRUCTOR_ID, TLUserStatusOffline.class);\n registerClass(TLUserStatusOnline.CONSTRUCTOR_ID, TLUserStatusOnline.class);\n registerClass(TLUserStatusRecently.CONSTRUCTOR_ID, TLUserStatusRecently.class);\n registerClass(TLWallPaper.CONSTRUCTOR_ID, TLWallPaper.class);\n registerClass(TLWallPaperSolid.CONSTRUCTOR_ID, TLWallPaperSolid.class);\n registerClass(TLWebDocument.CONSTRUCTOR_ID, TLWebDocument.class);\n registerClass(TLWebPage.CONSTRUCTOR_ID, TLWebPage.class);\n registerClass(TLWebPageEmpty.CONSTRUCTOR_ID, TLWebPageEmpty.class);\n registerClass(TLWebPageNotModified.CONSTRUCTOR_ID, TLWebPageNotModified.class);\n registerClass(TLWebPagePending.CONSTRUCTOR_ID, TLWebPagePending.class);\n }\n}\n"} {"task_id": "Java_102", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/badoualy/kotlogram/tl/src/main/java/com/github/badoualy/telegram/tl/api/TLApiContext.java", "mask_start_position": 23132, "mask_end_position": 39305, "canonical_solution": "registerClass(TLInputMessagesFilterPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterPhotos.class);\n registerClass(TLInputMessagesFilterRoundVideo.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVideo.class);\n registerClass(TLInputMessagesFilterRoundVoice.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVoice.class);\n registerClass(TLInputMessagesFilterUrl.CONSTRUCTOR_ID, TLInputMessagesFilterUrl.class);\n registerClass(TLInputMessagesFilterVideo.CONSTRUCTOR_ID, TLInputMessagesFilterVideo.class);\n registerClass(TLInputMessagesFilterVoice.CONSTRUCTOR_ID, TLInputMessagesFilterVoice.class);\n registerClass(TLInputNotifyAll.CONSTRUCTOR_ID, TLInputNotifyAll.class);\n registerClass(TLInputNotifyChats.CONSTRUCTOR_ID, TLInputNotifyChats.class);\n registerClass(TLInputNotifyPeer.CONSTRUCTOR_ID, TLInputNotifyPeer.class);\n registerClass(TLInputNotifyUsers.CONSTRUCTOR_ID, TLInputNotifyUsers.class);\n registerClass(TLInputPaymentCredentials.CONSTRUCTOR_ID, TLInputPaymentCredentials.class);\n registerClass(TLInputPaymentCredentialsSaved.CONSTRUCTOR_ID, TLInputPaymentCredentialsSaved.class);\n registerClass(TLInputPeerChannel.CONSTRUCTOR_ID, TLInputPeerChannel.class);\n registerClass(TLInputPeerChat.CONSTRUCTOR_ID, TLInputPeerChat.class);\n registerClass(TLInputPeerEmpty.CONSTRUCTOR_ID, TLInputPeerEmpty.class);\n registerClass(TLInputPeerNotifyEventsAll.CONSTRUCTOR_ID, TLInputPeerNotifyEventsAll.class);\n registerClass(TLInputPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLInputPeerNotifyEventsEmpty.class);\n registerClass(TLInputPeerNotifySettings.CONSTRUCTOR_ID, TLInputPeerNotifySettings.class);\n registerClass(TLInputPeerSelf.CONSTRUCTOR_ID, TLInputPeerSelf.class);\n registerClass(TLInputPeerUser.CONSTRUCTOR_ID, TLInputPeerUser.class);\n registerClass(TLInputPhoneCall.CONSTRUCTOR_ID, TLInputPhoneCall.class);\n registerClass(TLInputPhoneContact.CONSTRUCTOR_ID, TLInputPhoneContact.class);\n registerClass(TLInputPhoto.CONSTRUCTOR_ID, TLInputPhoto.class);\n registerClass(TLInputPhotoEmpty.CONSTRUCTOR_ID, TLInputPhotoEmpty.class);\n registerClass(TLInputPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLInputPrivacyKeyChatInvite.class);\n registerClass(TLInputPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLInputPrivacyKeyPhoneCall.class);\n registerClass(TLInputPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLInputPrivacyKeyStatusTimestamp.class);\n registerClass(TLInputPrivacyValueAllowAll.CONSTRUCTOR_ID, TLInputPrivacyValueAllowAll.class);\n registerClass(TLInputPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueAllowContacts.class);\n registerClass(TLInputPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueAllowUsers.class);\n registerClass(TLInputPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowAll.class);\n registerClass(TLInputPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowContacts.class);\n registerClass(TLInputPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowUsers.class);\n registerClass(TLInputReportReasonOther.CONSTRUCTOR_ID, TLInputReportReasonOther.class);\n registerClass(TLInputReportReasonPornography.CONSTRUCTOR_ID, TLInputReportReasonPornography.class);\n registerClass(TLInputReportReasonSpam.CONSTRUCTOR_ID, TLInputReportReasonSpam.class);\n registerClass(TLInputReportReasonViolence.CONSTRUCTOR_ID, TLInputReportReasonViolence.class);\n registerClass(TLInputStickerSetEmpty.CONSTRUCTOR_ID, TLInputStickerSetEmpty.class);\n registerClass(TLInputStickerSetID.CONSTRUCTOR_ID, TLInputStickerSetID.class);\n registerClass(TLInputStickerSetShortName.CONSTRUCTOR_ID, TLInputStickerSetShortName.class);\n registerClass(TLInputStickeredMediaDocument.CONSTRUCTOR_ID, TLInputStickeredMediaDocument.class);\n registerClass(TLInputStickeredMediaPhoto.CONSTRUCTOR_ID, TLInputStickeredMediaPhoto.class);\n registerClass(TLInputUser.CONSTRUCTOR_ID, TLInputUser.class);\n registerClass(TLInputUserEmpty.CONSTRUCTOR_ID, TLInputUserEmpty.class);\n registerClass(TLInputUserSelf.CONSTRUCTOR_ID, TLInputUserSelf.class);\n registerClass(TLInputWebDocument.CONSTRUCTOR_ID, TLInputWebDocument.class);\n registerClass(TLInputWebFileLocation.CONSTRUCTOR_ID, TLInputWebFileLocation.class);\n registerClass(TLInvoice.CONSTRUCTOR_ID, TLInvoice.class);\n registerClass(TLKeyboardButton.CONSTRUCTOR_ID, TLKeyboardButton.class);\n registerClass(TLKeyboardButtonBuy.CONSTRUCTOR_ID, TLKeyboardButtonBuy.class);\n registerClass(TLKeyboardButtonCallback.CONSTRUCTOR_ID, TLKeyboardButtonCallback.class);\n registerClass(TLKeyboardButtonGame.CONSTRUCTOR_ID, TLKeyboardButtonGame.class);\n registerClass(TLKeyboardButtonRequestGeoLocation.CONSTRUCTOR_ID, TLKeyboardButtonRequestGeoLocation.class);\n registerClass(TLKeyboardButtonRequestPhone.CONSTRUCTOR_ID, TLKeyboardButtonRequestPhone.class);\n registerClass(TLKeyboardButtonRow.CONSTRUCTOR_ID, TLKeyboardButtonRow.class);\n registerClass(TLKeyboardButtonSwitchInline.CONSTRUCTOR_ID, TLKeyboardButtonSwitchInline.class);\n registerClass(TLKeyboardButtonUrl.CONSTRUCTOR_ID, TLKeyboardButtonUrl.class);\n registerClass(TLLabeledPrice.CONSTRUCTOR_ID, TLLabeledPrice.class);\n registerClass(TLMaskCoords.CONSTRUCTOR_ID, TLMaskCoords.class);\n registerClass(TLMessage.CONSTRUCTOR_ID, TLMessage.class);\n registerClass(TLMessageActionChannelCreate.CONSTRUCTOR_ID, TLMessageActionChannelCreate.class);\n registerClass(TLMessageActionChannelMigrateFrom.CONSTRUCTOR_ID, TLMessageActionChannelMigrateFrom.class);\n registerClass(TLMessageActionChatAddUser.CONSTRUCTOR_ID, TLMessageActionChatAddUser.class);\n registerClass(TLMessageActionChatCreate.CONSTRUCTOR_ID, TLMessageActionChatCreate.class);\n registerClass(TLMessageActionChatDeletePhoto.CONSTRUCTOR_ID, TLMessageActionChatDeletePhoto.class);\n registerClass(TLMessageActionChatDeleteUser.CONSTRUCTOR_ID, TLMessageActionChatDeleteUser.class);\n registerClass(TLMessageActionChatEditPhoto.CONSTRUCTOR_ID, TLMessageActionChatEditPhoto.class);\n registerClass(TLMessageActionChatEditTitle.CONSTRUCTOR_ID, TLMessageActionChatEditTitle.class);\n registerClass(TLMessageActionChatJoinedByLink.CONSTRUCTOR_ID, TLMessageActionChatJoinedByLink.class);\n registerClass(TLMessageActionChatMigrateTo.CONSTRUCTOR_ID, TLMessageActionChatMigrateTo.class);\n registerClass(TLMessageActionEmpty.CONSTRUCTOR_ID, TLMessageActionEmpty.class);\n registerClass(TLMessageActionGameScore.CONSTRUCTOR_ID, TLMessageActionGameScore.class);\n registerClass(TLMessageActionHistoryClear.CONSTRUCTOR_ID, TLMessageActionHistoryClear.class);\n registerClass(TLMessageActionPaymentSent.CONSTRUCTOR_ID, TLMessageActionPaymentSent.class);\n registerClass(TLMessageActionPaymentSentMe.CONSTRUCTOR_ID, TLMessageActionPaymentSentMe.class);\n registerClass(TLMessageActionPhoneCall.CONSTRUCTOR_ID, TLMessageActionPhoneCall.class);\n registerClass(TLMessageActionPinMessage.CONSTRUCTOR_ID, TLMessageActionPinMessage.class);\n registerClass(TLMessageEmpty.CONSTRUCTOR_ID, TLMessageEmpty.class);\n registerClass(TLMessageEntityBold.CONSTRUCTOR_ID, TLMessageEntityBold.class);\n registerClass(TLMessageEntityBotCommand.CONSTRUCTOR_ID, TLMessageEntityBotCommand.class);\n registerClass(TLMessageEntityCode.CONSTRUCTOR_ID, TLMessageEntityCode.class);\n registerClass(TLMessageEntityEmail.CONSTRUCTOR_ID, TLMessageEntityEmail.class);\n registerClass(TLMessageEntityHashtag.CONSTRUCTOR_ID, TLMessageEntityHashtag.class);\n registerClass(TLMessageEntityItalic.CONSTRUCTOR_ID, TLMessageEntityItalic.class);\n registerClass(TLMessageEntityMention.CONSTRUCTOR_ID, TLMessageEntityMention.class);\n registerClass(TLMessageEntityMentionName.CONSTRUCTOR_ID, TLMessageEntityMentionName.class);\n registerClass(TLMessageEntityPre.CONSTRUCTOR_ID, TLMessageEntityPre.class);\n registerClass(TLMessageEntityTextUrl.CONSTRUCTOR_ID, TLMessageEntityTextUrl.class);\n registerClass(TLMessageEntityUnknown.CONSTRUCTOR_ID, TLMessageEntityUnknown.class);\n registerClass(TLMessageEntityUrl.CONSTRUCTOR_ID, TLMessageEntityUrl.class);\n registerClass(TLMessageFwdHeader.CONSTRUCTOR_ID, TLMessageFwdHeader.class);\n registerClass(TLMessageMediaContact.CONSTRUCTOR_ID, TLMessageMediaContact.class);\n registerClass(TLMessageMediaDocument.CONSTRUCTOR_ID, TLMessageMediaDocument.class);\n registerClass(TLMessageMediaEmpty.CONSTRUCTOR_ID, TLMessageMediaEmpty.class);\n registerClass(TLMessageMediaGame.CONSTRUCTOR_ID, TLMessageMediaGame.class);\n registerClass(TLMessageMediaGeo.CONSTRUCTOR_ID, TLMessageMediaGeo.class);\n registerClass(TLMessageMediaInvoice.CONSTRUCTOR_ID, TLMessageMediaInvoice.class);\n registerClass(TLMessageMediaPhoto.CONSTRUCTOR_ID, TLMessageMediaPhoto.class);\n registerClass(TLMessageMediaUnsupported.CONSTRUCTOR_ID, TLMessageMediaUnsupported.class);\n registerClass(TLMessageMediaVenue.CONSTRUCTOR_ID, TLMessageMediaVenue.class);\n registerClass(TLMessageMediaWebPage.CONSTRUCTOR_ID, TLMessageMediaWebPage.class);\n registerClass(TLMessageRange.CONSTRUCTOR_ID, TLMessageRange.class);\n registerClass(TLMessageService.CONSTRUCTOR_ID, TLMessageService.class);\n registerClass(TLAffectedHistory.CONSTRUCTOR_ID, TLAffectedHistory.class);\n registerClass(TLAffectedMessages.CONSTRUCTOR_ID, TLAffectedMessages.class);\n registerClass(TLAllStickers.CONSTRUCTOR_ID, TLAllStickers.class);\n registerClass(TLAllStickersNotModified.CONSTRUCTOR_ID, TLAllStickersNotModified.class);\n registerClass(TLArchivedStickers.CONSTRUCTOR_ID, TLArchivedStickers.class);\n registerClass(TLBotCallbackAnswer.CONSTRUCTOR_ID, TLBotCallbackAnswer.class);\n registerClass(TLBotResults.CONSTRUCTOR_ID, TLBotResults.class);\n registerClass(TLChannelMessages.CONSTRUCTOR_ID, TLChannelMessages.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLChatFull.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLChatFull.class);\n registerClass(TLChats.CONSTRUCTOR_ID, TLChats.class);\n registerClass(TLChatsSlice.CONSTRUCTOR_ID, TLChatsSlice.class);\n registerClass(TLDhConfig.CONSTRUCTOR_ID, TLDhConfig.class);\n registerClass(TLDhConfigNotModified.CONSTRUCTOR_ID, TLDhConfigNotModified.class);\n registerClass(TLDialogs.CONSTRUCTOR_ID, TLDialogs.class);\n registerClass(TLDialogsSlice.CONSTRUCTOR_ID, TLDialogsSlice.class);\n registerClass(TLFeaturedStickers.CONSTRUCTOR_ID, TLFeaturedStickers.class);\n registerClass(TLFeaturedStickersNotModified.CONSTRUCTOR_ID, TLFeaturedStickersNotModified.class);\n registerClass(TLFoundGifs.CONSTRUCTOR_ID, TLFoundGifs.class);\n registerClass(TLHighScores.CONSTRUCTOR_ID, TLHighScores.class);\n registerClass(TLMessageEditData.CONSTRUCTOR_ID, TLMessageEditData.class);\n registerClass(TLMessages.CONSTRUCTOR_ID, TLMessages.class);\n registerClass(TLMessagesSlice.CONSTRUCTOR_ID, TLMessagesSlice.class);\n registerClass(TLPeerDialogs.CONSTRUCTOR_ID, TLPeerDialogs.class);\n registerClass(TLRecentStickers.CONSTRUCTOR_ID, TLRecentStickers.class);\n registerClass(TLRecentStickersNotModified.CONSTRUCTOR_ID, TLRecentStickersNotModified.class);\n registerClass(TLSavedGifs.CONSTRUCTOR_ID, TLSavedGifs.class);\n registerClass(TLSavedGifsNotModified.CONSTRUCTOR_ID, TLSavedGifsNotModified.class);\n registerClass(TLSentEncryptedFile.CONSTRUCTOR_ID, TLSentEncryptedFile.class);\n registerClass(TLSentEncryptedMessage.CONSTRUCTOR_ID, TLSentEncryptedMessage.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLStickerSet.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLStickerSet.class);\n registerClass(TLStickerSetInstallResultArchive.CONSTRUCTOR_ID, TLStickerSetInstallResultArchive.class);\n registerClass(TLStickerSetInstallResultSuccess.CONSTRUCTOR_ID, TLStickerSetInstallResultSuccess.class);\n registerClass(TLStickers.CONSTRUCTOR_ID, TLStickers.class);\n registerClass(TLStickersNotModified.CONSTRUCTOR_ID, TLStickersNotModified.class);\n registerClass(TLNearestDc.CONSTRUCTOR_ID, TLNearestDc.class);\n registerClass(TLNotifyAll.CONSTRUCTOR_ID, TLNotifyAll.class);\n registerClass(TLNotifyChats.CONSTRUCTOR_ID, TLNotifyChats.class);\n registerClass(TLNotifyPeer.CONSTRUCTOR_ID, TLNotifyPeer.class);\n registerClass(TLNotifyUsers.CONSTRUCTOR_ID, TLNotifyUsers.class);\n registerClass(TLPageBlockAnchor.CONSTRUCTOR_ID, TLPageBlockAnchor.class);\n registerClass(TLPageBlockAuthorDate.CONSTRUCTOR_ID, TLPageBlockAuthorDate.class);\n registerClass(TLPageBlockBlockquote.CONSTRUCTOR_ID, TLPageBlockBlockquote.class);\n registerClass(TLPageBlockChannel.CONSTRUCTOR_ID, TLPageBlockChannel.class);\n registerClass(TLPageBlockCollage.CONSTRUCTOR_ID, TLPageBlockCollage.class);\n registerClass(TLPageBlockCover.CONSTRUCTOR_ID, TLPageBlockCover.class);\n registerClass(TLPageBlockDivider.CONSTRUCTOR_ID, TLPageBlockDivider.class);\n registerClass(TLPageBlockEmbed.CONSTRUCTOR_ID, TLPageBlockEmbed.class);\n registerClass(TLPageBlockEmbedPost.CONSTRUCTOR_ID, TLPageBlockEmbedPost.class);\n registerClass(TLPageBlockFooter.CONSTRUCTOR_ID, TLPageBlockFooter.class);\n registerClass(TLPageBlockHeader.CONSTRUCTOR_ID, TLPageBlockHeader.class);\n registerClass(TLPageBlockList.CONSTRUCTOR_ID, TLPageBlockList.class);\n registerClass(TLPageBlockParagraph.CONSTRUCTOR_ID, TLPageBlockParagraph.class);\n registerClass(TLPageBlockPhoto.CONSTRUCTOR_ID, TLPageBlockPhoto.class);\n registerClass(TLPageBlockPreformatted.CONSTRUCTOR_ID, TLPageBlockPreformatted.class);\n registerClass(TLPageBlockPullquote.CONSTRUCTOR_ID, TLPageBlockPullquote.class);\n registerClass(TLPageBlockSlideshow.CONSTRUCTOR_ID, TLPageBlockSlideshow.class);\n registerClass(TLPageBlockSubheader.CONSTRUCTOR_ID, TLPageBlockSubheader.class);\n registerClass(TLPageBlockSubtitle.CONSTRUCTOR_ID, TLPageBlockSubtitle.class);\n registerClass(TLPageBlockTitle.CONSTRUCTOR_ID, TLPageBlockTitle.class);\n registerClass(TLPageBlockUnsupported.CONSTRUCTOR_ID, TLPageBlockUnsupported.class);\n registerClass(TLPageBlockVideo.CONSTRUCTOR_ID, TLPageBlockVideo.class);\n registerClass(TLPageFull.CONSTRUCTOR_ID, TLPageFull.class);\n registerClass(TLPagePart.CONSTRUCTOR_ID, TLPagePart.class);\n registerClass(TLPaymentCharge.CONSTRUCTOR_ID, TLPaymentCharge.class);\n registerClass(TLPaymentRequestedInfo.CONSTRUCTOR_ID, TLPaymentRequestedInfo.class);\n registerClass(TLPaymentSavedCredentialsCard.CONSTRUCTOR_ID, TLPaymentSavedCredentialsCard.class);\n registerClass(TLPaymentForm.CONSTRUCTOR_ID, TLPaymentForm.class);\n registerClass(TLPaymentReceipt.CONSTRUCTOR_ID, TLPaymentReceipt.class);\n registerClass(TLPaymentResult.CONSTRUCTOR_ID, TLPaymentResult.class);\n registerClass(TLPaymentVerficationNeeded.CONSTRUCTOR_ID, TLPaymentVerficationNeeded.class);\n registerClass(TLSavedInfo.CONSTRUCTOR_ID, TLSavedInfo.class);\n registerClass(TLValidatedRequestedInfo.CONSTRUCTOR_ID, TLValidatedRequestedInfo.class);\n registerClass(TLPeerChannel.CONSTRUCTOR_ID, TLPeerChannel.class);\n registerClass(TLPeerChat.CONSTRUCTOR_ID, TLPeerChat.class);\n registerClass(TLPeerNotifyEventsAll.CONSTRUCTOR_ID, TLPeerNotifyEventsAll.class);\n registerClass(TLPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLPeerNotifyEventsEmpty.class);\n registerClass(TLPeerNotifySettings.CONSTRUCTOR_ID, TLPeerNotifySettings.class);\n registerClass(TLPeerNotifySettingsEmpty.CONSTRUCTOR_ID, TLPeerNotifySettingsEmpty.class);", "pre_mask_code": "package com.github.badoualy.telegram.tl.api;\n\nimport com.github.badoualy.telegram.tl.TLContext;\nimport com.github.badoualy.telegram.tl.api.account.TLAuthorizations;\nimport com.github.badoualy.telegram.tl.api.account.TLNoPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordInputSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPrivacyRules;\nimport com.github.badoualy.telegram.tl.api.account.TLTmpPassword;\nimport com.github.badoualy.telegram.tl.api.auth.TLCheckedPhone;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.auth.TLExportedAuthorization;\nimport com.github.badoualy.telegram.tl.api.auth.TLPasswordRecovery;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCode;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeApp;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.channels.TLChannelParticipants;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlocked;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlockedSlice;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContactsNotModified;\nimport com.github.badoualy.telegram.tl.api.contacts.TLFound;\nimport com.github.badoualy.telegram.tl.api.contacts.TLImportedContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLLink;\nimport com.github.badoualy.telegram.tl.api.contacts.TLResolvedPeer;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeers;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeersNotModified;\nimport com.github.badoualy.telegram.tl.api.help.TLAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLInviteText;\nimport com.github.badoualy.telegram.tl.api.help.TLNoAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLSupport;\nimport com.github.badoualy.telegram.tl.api.help.TLTermsOfService;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedHistory;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLArchivedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotCallbackAnswer;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotResults;\nimport com.github.badoualy.telegram.tl.api.messages.TLChannelMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLChats;\nimport com.github.badoualy.telegram.tl.api.messages.TLChatsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfig;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfigNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLFoundGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLHighScores;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessageEditData;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessagesSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLPeerDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifsNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedFile;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedMessage;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultArchive;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultSuccess;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentForm;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentReceipt;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentResult;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentVerficationNeeded;\nimport com.github.badoualy.telegram.tl.api.payments.TLSavedInfo;\nimport com.github.badoualy.telegram.tl.api.payments.TLValidatedRequestedInfo;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotos;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotosSlice;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileGif;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileJpeg;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMov;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp3;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp4;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePartial;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePdf;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePng;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileUnknown;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileWebp;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceSlice;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLState;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFileReuploadNeeded;\nimport com.github.badoualy.telegram.tl.api.upload.TLFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLFileCdnRedirect;\nimport com.github.badoualy.telegram.tl.api.upload.TLWebFile;\n\n/**\n * @author Yannick Badoual example@nnthink.com\n * @see http://example.com\n */\n@SuppressWarnings(\"unused\")\npublic class TLApiContext extends TLContext {\n\n private static TLApiContext instance;\n\n public TLApiContext() {\n super(543);\n }\n\n public static TLApiContext getInstance() {\n if (instance == null) {\n instance = new TLApiContext();\n }\n return instance;\n }\n\n @Override\n public void init() {\n registerClass(TLAuthorizations.CONSTRUCTOR_ID, TLAuthorizations.class);\n registerClass(TLNoPassword.CONSTRUCTOR_ID, TLNoPassword.class);\n registerClass(TLPassword.CONSTRUCTOR_ID, TLPassword.class);\n registerClass(TLPasswordInputSettings.CONSTRUCTOR_ID, TLPasswordInputSettings.class);\n registerClass(TLPasswordSettings.CONSTRUCTOR_ID, TLPasswordSettings.class);\n registerClass(TLPrivacyRules.CONSTRUCTOR_ID, TLPrivacyRules.class);\n registerClass(TLTmpPassword.CONSTRUCTOR_ID, TLTmpPassword.class);\n registerClass(TLAccountDaysTTL.CONSTRUCTOR_ID, TLAccountDaysTTL.class);\n registerClass(com.github.badoualy.telegram.tl.api.auth.TLAuthorization.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.auth.TLAuthorization.class);\n registerClass(TLCheckedPhone.CONSTRUCTOR_ID, TLCheckedPhone.class);\n registerClass(TLCodeTypeCall.CONSTRUCTOR_ID, TLCodeTypeCall.class);\n registerClass(TLCodeTypeFlashCall.CONSTRUCTOR_ID, TLCodeTypeFlashCall.class);\n registerClass(TLCodeTypeSms.CONSTRUCTOR_ID, TLCodeTypeSms.class);\n registerClass(TLExportedAuthorization.CONSTRUCTOR_ID, TLExportedAuthorization.class);\n registerClass(TLPasswordRecovery.CONSTRUCTOR_ID, TLPasswordRecovery.class);\n registerClass(TLSentCode.CONSTRUCTOR_ID, TLSentCode.class);\n registerClass(TLSentCodeTypeApp.CONSTRUCTOR_ID, TLSentCodeTypeApp.class);\n registerClass(TLSentCodeTypeCall.CONSTRUCTOR_ID, TLSentCodeTypeCall.class);\n registerClass(TLSentCodeTypeFlashCall.CONSTRUCTOR_ID, TLSentCodeTypeFlashCall.class);\n registerClass(TLSentCodeTypeSms.CONSTRUCTOR_ID, TLSentCodeTypeSms.class);\n registerClass(TLAuthorization.CONSTRUCTOR_ID, TLAuthorization.class);\n registerClass(TLBotCommand.CONSTRUCTOR_ID, TLBotCommand.class);\n registerClass(TLBotInfo.CONSTRUCTOR_ID, TLBotInfo.class);\n registerClass(TLBotInlineMediaResult.CONSTRUCTOR_ID, TLBotInlineMediaResult.class);\n registerClass(TLBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLBotInlineMessageMediaAuto.class);\n registerClass(TLBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLBotInlineMessageMediaContact.class);\n registerClass(TLBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLBotInlineMessageMediaGeo.class);\n registerClass(TLBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLBotInlineMessageMediaVenue.class);\n registerClass(TLBotInlineMessageText.CONSTRUCTOR_ID, TLBotInlineMessageText.class);\n registerClass(TLBotInlineResult.CONSTRUCTOR_ID, TLBotInlineResult.class);\n registerClass(TLCdnConfig.CONSTRUCTOR_ID, TLCdnConfig.class);\n registerClass(TLCdnPublicKey.CONSTRUCTOR_ID, TLCdnPublicKey.class);\n registerClass(TLChannel.CONSTRUCTOR_ID, TLChannel.class);\n registerClass(TLChannelForbidden.CONSTRUCTOR_ID, TLChannelForbidden.class);\n registerClass(TLChannelFull.CONSTRUCTOR_ID, TLChannelFull.class);\n registerClass(TLChannelMessagesFilter.CONSTRUCTOR_ID, TLChannelMessagesFilter.class);\n registerClass(TLChannelMessagesFilterEmpty.CONSTRUCTOR_ID, TLChannelMessagesFilterEmpty.class);\n registerClass(TLChannelParticipant.CONSTRUCTOR_ID, TLChannelParticipant.class);\n registerClass(TLChannelParticipantCreator.CONSTRUCTOR_ID, TLChannelParticipantCreator.class);\n registerClass(TLChannelParticipantEditor.CONSTRUCTOR_ID, TLChannelParticipantEditor.class);\n registerClass(TLChannelParticipantKicked.CONSTRUCTOR_ID, TLChannelParticipantKicked.class);\n registerClass(TLChannelParticipantModerator.CONSTRUCTOR_ID, TLChannelParticipantModerator.class);\n registerClass(TLChannelParticipantSelf.CONSTRUCTOR_ID, TLChannelParticipantSelf.class);\n registerClass(TLChannelParticipantsAdmins.CONSTRUCTOR_ID, TLChannelParticipantsAdmins.class);\n registerClass(TLChannelParticipantsBots.CONSTRUCTOR_ID, TLChannelParticipantsBots.class);\n registerClass(TLChannelParticipantsKicked.CONSTRUCTOR_ID, TLChannelParticipantsKicked.class);\n registerClass(TLChannelParticipantsRecent.CONSTRUCTOR_ID, TLChannelParticipantsRecent.class);\n registerClass(TLChannelRoleEditor.CONSTRUCTOR_ID, TLChannelRoleEditor.class);\n registerClass(TLChannelRoleEmpty.CONSTRUCTOR_ID, TLChannelRoleEmpty.class);\n registerClass(TLChannelRoleModerator.CONSTRUCTOR_ID, TLChannelRoleModerator.class);\n registerClass(com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.class);\n registerClass(TLChannelParticipants.CONSTRUCTOR_ID, TLChannelParticipants.class);\n registerClass(TLChat.CONSTRUCTOR_ID, TLChat.class);\n registerClass(TLChatEmpty.CONSTRUCTOR_ID, TLChatEmpty.class);\n registerClass(TLChatForbidden.CONSTRUCTOR_ID, TLChatForbidden.class);\n registerClass(TLChatFull.CONSTRUCTOR_ID, TLChatFull.class);\n registerClass(TLChatInvite.CONSTRUCTOR_ID, TLChatInvite.class);\n registerClass(TLChatInviteAlready.CONSTRUCTOR_ID, TLChatInviteAlready.class);\n registerClass(TLChatInviteEmpty.CONSTRUCTOR_ID, TLChatInviteEmpty.class);\n registerClass(TLChatInviteExported.CONSTRUCTOR_ID, TLChatInviteExported.class);\n registerClass(TLChatParticipant.CONSTRUCTOR_ID, TLChatParticipant.class);\n registerClass(TLChatParticipantAdmin.CONSTRUCTOR_ID, TLChatParticipantAdmin.class);\n registerClass(TLChatParticipantCreator.CONSTRUCTOR_ID, TLChatParticipantCreator.class);\n registerClass(TLChatParticipants.CONSTRUCTOR_ID, TLChatParticipants.class);\n registerClass(TLChatParticipantsForbidden.CONSTRUCTOR_ID, TLChatParticipantsForbidden.class);\n registerClass(TLChatPhoto.CONSTRUCTOR_ID, TLChatPhoto.class);\n registerClass(TLChatPhotoEmpty.CONSTRUCTOR_ID, TLChatPhotoEmpty.class);\n registerClass(TLConfig.CONSTRUCTOR_ID, TLConfig.class);\n registerClass(TLContact.CONSTRUCTOR_ID, TLContact.class);\n registerClass(TLContactBlocked.CONSTRUCTOR_ID, TLContactBlocked.class);\n registerClass(TLContactLinkContact.CONSTRUCTOR_ID, TLContactLinkContact.class);\n registerClass(TLContactLinkHasPhone.CONSTRUCTOR_ID, TLContactLinkHasPhone.class);\n registerClass(TLContactLinkNone.CONSTRUCTOR_ID, TLContactLinkNone.class);\n registerClass(TLContactLinkUnknown.CONSTRUCTOR_ID, TLContactLinkUnknown.class);\n registerClass(TLContactStatus.CONSTRUCTOR_ID, TLContactStatus.class);\n registerClass(TLBlocked.CONSTRUCTOR_ID, TLBlocked.class);\n registerClass(TLBlockedSlice.CONSTRUCTOR_ID, TLBlockedSlice.class);\n registerClass(TLContacts.CONSTRUCTOR_ID, TLContacts.class);\n registerClass(TLContactsNotModified.CONSTRUCTOR_ID, TLContactsNotModified.class);\n registerClass(TLFound.CONSTRUCTOR_ID, TLFound.class);\n registerClass(TLImportedContacts.CONSTRUCTOR_ID, TLImportedContacts.class);\n registerClass(TLLink.CONSTRUCTOR_ID, TLLink.class);\n registerClass(TLResolvedPeer.CONSTRUCTOR_ID, TLResolvedPeer.class);\n registerClass(TLTopPeers.CONSTRUCTOR_ID, TLTopPeers.class);\n registerClass(TLTopPeersNotModified.CONSTRUCTOR_ID, TLTopPeersNotModified.class);\n registerClass(TLDataJSON.CONSTRUCTOR_ID, TLDataJSON.class);\n registerClass(TLDcOption.CONSTRUCTOR_ID, TLDcOption.class);\n registerClass(TLDialog.CONSTRUCTOR_ID, TLDialog.class);\n registerClass(TLDisabledFeature.CONSTRUCTOR_ID, TLDisabledFeature.class);\n registerClass(TLDocument.CONSTRUCTOR_ID, TLDocument.class);\n registerClass(TLDocumentAttributeAnimated.CONSTRUCTOR_ID, TLDocumentAttributeAnimated.class);\n registerClass(TLDocumentAttributeAudio.CONSTRUCTOR_ID, TLDocumentAttributeAudio.class);\n registerClass(TLDocumentAttributeFilename.CONSTRUCTOR_ID, TLDocumentAttributeFilename.class);\n registerClass(TLDocumentAttributeHasStickers.CONSTRUCTOR_ID, TLDocumentAttributeHasStickers.class);\n registerClass(TLDocumentAttributeImageSize.CONSTRUCTOR_ID, TLDocumentAttributeImageSize.class);\n registerClass(TLDocumentAttributeSticker.CONSTRUCTOR_ID, TLDocumentAttributeSticker.class);\n registerClass(TLDocumentAttributeVideo.CONSTRUCTOR_ID, TLDocumentAttributeVideo.class);\n registerClass(TLDocumentEmpty.CONSTRUCTOR_ID, TLDocumentEmpty.class);\n registerClass(TLDraftMessage.CONSTRUCTOR_ID, TLDraftMessage.class);\n registerClass(TLDraftMessageEmpty.CONSTRUCTOR_ID, TLDraftMessageEmpty.class);\n registerClass(TLEncryptedChat.CONSTRUCTOR_ID, TLEncryptedChat.class);\n registerClass(TLEncryptedChatDiscarded.CONSTRUCTOR_ID, TLEncryptedChatDiscarded.class);\n registerClass(TLEncryptedChatEmpty.CONSTRUCTOR_ID, TLEncryptedChatEmpty.class);\n registerClass(TLEncryptedChatRequested.CONSTRUCTOR_ID, TLEncryptedChatRequested.class);\n registerClass(TLEncryptedChatWaiting.CONSTRUCTOR_ID, TLEncryptedChatWaiting.class);\n registerClass(TLEncryptedFile.CONSTRUCTOR_ID, TLEncryptedFile.class);\n registerClass(TLEncryptedFileEmpty.CONSTRUCTOR_ID, TLEncryptedFileEmpty.class);\n registerClass(TLEncryptedMessage.CONSTRUCTOR_ID, TLEncryptedMessage.class);\n registerClass(TLEncryptedMessageService.CONSTRUCTOR_ID, TLEncryptedMessageService.class);\n registerClass(TLExportedMessageLink.CONSTRUCTOR_ID, TLExportedMessageLink.class);\n registerClass(TLFileLocation.CONSTRUCTOR_ID, TLFileLocation.class);\n registerClass(TLFileLocationUnavailable.CONSTRUCTOR_ID, TLFileLocationUnavailable.class);\n registerClass(TLFoundGif.CONSTRUCTOR_ID, TLFoundGif.class);\n registerClass(TLFoundGifCached.CONSTRUCTOR_ID, TLFoundGifCached.class);\n registerClass(TLGame.CONSTRUCTOR_ID, TLGame.class);\n registerClass(TLGeoPoint.CONSTRUCTOR_ID, TLGeoPoint.class);\n registerClass(TLGeoPointEmpty.CONSTRUCTOR_ID, TLGeoPointEmpty.class);\n registerClass(TLAppUpdate.CONSTRUCTOR_ID, TLAppUpdate.class);\n registerClass(TLInviteText.CONSTRUCTOR_ID, TLInviteText.class);\n registerClass(TLNoAppUpdate.CONSTRUCTOR_ID, TLNoAppUpdate.class);\n registerClass(TLSupport.CONSTRUCTOR_ID, TLSupport.class);\n registerClass(TLTermsOfService.CONSTRUCTOR_ID, TLTermsOfService.class);\n registerClass(TLHighScore.CONSTRUCTOR_ID, TLHighScore.class);\n registerClass(TLImportedContact.CONSTRUCTOR_ID, TLImportedContact.class);\n registerClass(TLInlineBotSwitchPM.CONSTRUCTOR_ID, TLInlineBotSwitchPM.class);\n registerClass(TLInputAppEvent.CONSTRUCTOR_ID, TLInputAppEvent.class);\n registerClass(TLInputBotInlineMessageGame.CONSTRUCTOR_ID, TLInputBotInlineMessageGame.class);\n registerClass(TLInputBotInlineMessageID.CONSTRUCTOR_ID, TLInputBotInlineMessageID.class);\n registerClass(TLInputBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaAuto.class);\n registerClass(TLInputBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaContact.class);\n registerClass(TLInputBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaGeo.class);\n registerClass(TLInputBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaVenue.class);\n registerClass(TLInputBotInlineMessageText.CONSTRUCTOR_ID, TLInputBotInlineMessageText.class);\n registerClass(TLInputBotInlineResult.CONSTRUCTOR_ID, TLInputBotInlineResult.class);\n registerClass(TLInputBotInlineResultDocument.CONSTRUCTOR_ID, TLInputBotInlineResultDocument.class);\n registerClass(TLInputBotInlineResultGame.CONSTRUCTOR_ID, TLInputBotInlineResultGame.class);\n registerClass(TLInputBotInlineResultPhoto.CONSTRUCTOR_ID, TLInputBotInlineResultPhoto.class);\n registerClass(TLInputChannel.CONSTRUCTOR_ID, TLInputChannel.class);\n registerClass(TLInputChannelEmpty.CONSTRUCTOR_ID, TLInputChannelEmpty.class);\n registerClass(TLInputChatPhoto.CONSTRUCTOR_ID, TLInputChatPhoto.class);\n registerClass(TLInputChatPhotoEmpty.CONSTRUCTOR_ID, TLInputChatPhotoEmpty.class);\n registerClass(TLInputChatUploadedPhoto.CONSTRUCTOR_ID, TLInputChatUploadedPhoto.class);\n registerClass(TLInputDocument.CONSTRUCTOR_ID, TLInputDocument.class);\n registerClass(TLInputDocumentEmpty.CONSTRUCTOR_ID, TLInputDocumentEmpty.class);\n registerClass(TLInputDocumentFileLocation.CONSTRUCTOR_ID, TLInputDocumentFileLocation.class);\n registerClass(TLInputEncryptedChat.CONSTRUCTOR_ID, TLInputEncryptedChat.class);\n registerClass(TLInputEncryptedFile.CONSTRUCTOR_ID, TLInputEncryptedFile.class);\n registerClass(TLInputEncryptedFileBigUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileBigUploaded.class);\n registerClass(TLInputEncryptedFileEmpty.CONSTRUCTOR_ID, TLInputEncryptedFileEmpty.class);\n registerClass(TLInputEncryptedFileLocation.CONSTRUCTOR_ID, TLInputEncryptedFileLocation.class);\n registerClass(TLInputEncryptedFileUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileUploaded.class);\n registerClass(TLInputFile.CONSTRUCTOR_ID, TLInputFile.class);\n registerClass(TLInputFileBig.CONSTRUCTOR_ID, TLInputFileBig.class);\n registerClass(TLInputFileLocation.CONSTRUCTOR_ID, TLInputFileLocation.class);\n registerClass(TLInputGameID.CONSTRUCTOR_ID, TLInputGameID.class);\n registerClass(TLInputGameShortName.CONSTRUCTOR_ID, TLInputGameShortName.class);\n registerClass(TLInputGeoPoint.CONSTRUCTOR_ID, TLInputGeoPoint.class);\n registerClass(TLInputGeoPointEmpty.CONSTRUCTOR_ID, TLInputGeoPointEmpty.class);\n registerClass(TLInputMediaContact.CONSTRUCTOR_ID, TLInputMediaContact.class);\n registerClass(TLInputMediaDocument.CONSTRUCTOR_ID, TLInputMediaDocument.class);\n registerClass(TLInputMediaDocumentExternal.CONSTRUCTOR_ID, TLInputMediaDocumentExternal.class);\n registerClass(TLInputMediaEmpty.CONSTRUCTOR_ID, TLInputMediaEmpty.class);\n registerClass(TLInputMediaGame.CONSTRUCTOR_ID, TLInputMediaGame.class);\n registerClass(TLInputMediaGeoPoint.CONSTRUCTOR_ID, TLInputMediaGeoPoint.class);\n registerClass(TLInputMediaGifExternal.CONSTRUCTOR_ID, TLInputMediaGifExternal.class);\n registerClass(TLInputMediaInvoice.CONSTRUCTOR_ID, TLInputMediaInvoice.class);\n registerClass(TLInputMediaPhoto.CONSTRUCTOR_ID, TLInputMediaPhoto.class);\n registerClass(TLInputMediaPhotoExternal.CONSTRUCTOR_ID, TLInputMediaPhotoExternal.class);\n registerClass(TLInputMediaUploadedDocument.CONSTRUCTOR_ID, TLInputMediaUploadedDocument.class);\n registerClass(TLInputMediaUploadedPhoto.CONSTRUCTOR_ID, TLInputMediaUploadedPhoto.class);\n registerClass(TLInputMediaUploadedThumbDocument.CONSTRUCTOR_ID, TLInputMediaUploadedThumbDocument.class);\n registerClass(TLInputMediaVenue.CONSTRUCTOR_ID, TLInputMediaVenue.class);\n registerClass(TLInputMessageEntityMentionName.CONSTRUCTOR_ID, TLInputMessageEntityMentionName.class);\n registerClass(TLInputMessagesFilterChatPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterChatPhotos.class);\n registerClass(TLInputMessagesFilterDocument.CONSTRUCTOR_ID, TLInputMessagesFilterDocument.class);\n registerClass(TLInputMessagesFilterEmpty.CONSTRUCTOR_ID, TLInputMessagesFilterEmpty.class);\n registerClass(TLInputMessagesFilterGif.CONSTRUCTOR_ID, TLInputMessagesFilterGif.class);\n registerClass(TLInputMessagesFilterMusic.CONSTRUCTOR_ID, TLInputMessagesFilterMusic.class);\n registerClass(TLInputMessagesFilterPhoneCalls.CONSTRUCTOR_ID, TLInputMessagesFilterPhoneCalls.class);\n registerClass(TLInputMessagesFilterPhotoVideo.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideo.class);\n registerClass(TLInputMessagesFilterPhotoVideoDocuments.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideoDocuments.class);\n ", "post_mask_code": "\n registerClass(TLPeerSettings.CONSTRUCTOR_ID, TLPeerSettings.class);\n registerClass(TLPeerUser.CONSTRUCTOR_ID, TLPeerUser.class);\n registerClass(com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.class);\n registerClass(TLPhoneCall.CONSTRUCTOR_ID, TLPhoneCall.class);\n registerClass(TLPhoneCallAccepted.CONSTRUCTOR_ID, TLPhoneCallAccepted.class);\n registerClass(TLPhoneCallDiscardReasonBusy.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonBusy.class);\n registerClass(TLPhoneCallDiscardReasonDisconnect.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonDisconnect.class);\n registerClass(TLPhoneCallDiscardReasonHangup.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonHangup.class);\n registerClass(TLPhoneCallDiscardReasonMissed.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonMissed.class);\n registerClass(TLPhoneCallDiscarded.CONSTRUCTOR_ID, TLPhoneCallDiscarded.class);\n registerClass(TLPhoneCallEmpty.CONSTRUCTOR_ID, TLPhoneCallEmpty.class);\n registerClass(TLPhoneCallProtocol.CONSTRUCTOR_ID, TLPhoneCallProtocol.class);\n registerClass(TLPhoneCallRequested.CONSTRUCTOR_ID, TLPhoneCallRequested.class);\n registerClass(TLPhoneCallWaiting.CONSTRUCTOR_ID, TLPhoneCallWaiting.class);\n registerClass(TLPhoneConnection.CONSTRUCTOR_ID, TLPhoneConnection.class);\n registerClass(TLPhoto.CONSTRUCTOR_ID, TLPhoto.class);\n registerClass(TLPhotoCachedSize.CONSTRUCTOR_ID, TLPhotoCachedSize.class);\n registerClass(TLPhotoEmpty.CONSTRUCTOR_ID, TLPhotoEmpty.class);\n registerClass(TLPhotoSize.CONSTRUCTOR_ID, TLPhotoSize.class);\n registerClass(TLPhotoSizeEmpty.CONSTRUCTOR_ID, TLPhotoSizeEmpty.class);\n registerClass(com.github.badoualy.telegram.tl.api.photos.TLPhoto.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.photos.TLPhoto.class);\n registerClass(TLPhotos.CONSTRUCTOR_ID, TLPhotos.class);\n registerClass(TLPhotosSlice.CONSTRUCTOR_ID, TLPhotosSlice.class);\n registerClass(TLPostAddress.CONSTRUCTOR_ID, TLPostAddress.class);\n registerClass(TLPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLPrivacyKeyChatInvite.class);\n registerClass(TLPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLPrivacyKeyPhoneCall.class);\n registerClass(TLPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLPrivacyKeyStatusTimestamp.class);\n registerClass(TLPrivacyValueAllowAll.CONSTRUCTOR_ID, TLPrivacyValueAllowAll.class);\n registerClass(TLPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLPrivacyValueAllowContacts.class);\n registerClass(TLPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLPrivacyValueAllowUsers.class);\n registerClass(TLPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLPrivacyValueDisallowAll.class);\n registerClass(TLPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLPrivacyValueDisallowContacts.class);\n registerClass(TLPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLPrivacyValueDisallowUsers.class);\n registerClass(TLReceivedNotifyMessage.CONSTRUCTOR_ID, TLReceivedNotifyMessage.class);\n registerClass(TLReplyInlineMarkup.CONSTRUCTOR_ID, TLReplyInlineMarkup.class);\n registerClass(TLReplyKeyboardForceReply.CONSTRUCTOR_ID, TLReplyKeyboardForceReply.class);\n registerClass(TLReplyKeyboardHide.CONSTRUCTOR_ID, TLReplyKeyboardHide.class);\n registerClass(TLReplyKeyboardMarkup.CONSTRUCTOR_ID, TLReplyKeyboardMarkup.class);\n registerClass(TLSendMessageCancelAction.CONSTRUCTOR_ID, TLSendMessageCancelAction.class);\n registerClass(TLSendMessageChooseContactAction.CONSTRUCTOR_ID, TLSendMessageChooseContactAction.class);\n registerClass(TLSendMessageGamePlayAction.CONSTRUCTOR_ID, TLSendMessageGamePlayAction.class);\n registerClass(TLSendMessageGeoLocationAction.CONSTRUCTOR_ID, TLSendMessageGeoLocationAction.class);\n registerClass(TLSendMessageRecordAudioAction.CONSTRUCTOR_ID, TLSendMessageRecordAudioAction.class);\n registerClass(TLSendMessageRecordRoundAction.CONSTRUCTOR_ID, TLSendMessageRecordRoundAction.class);\n registerClass(TLSendMessageRecordVideoAction.CONSTRUCTOR_ID, TLSendMessageRecordVideoAction.class);\n registerClass(TLSendMessageTypingAction.CONSTRUCTOR_ID, TLSendMessageTypingAction.class);\n registerClass(TLSendMessageUploadAudioAction.CONSTRUCTOR_ID, TLSendMessageUploadAudioAction.class);\n registerClass(TLSendMessageUploadDocumentAction.CONSTRUCTOR_ID, TLSendMessageUploadDocumentAction.class);\n registerClass(TLSendMessageUploadPhotoAction.CONSTRUCTOR_ID, TLSendMessageUploadPhotoAction.class);\n registerClass(TLSendMessageUploadRoundAction.CONSTRUCTOR_ID, TLSendMessageUploadRoundAction.class);\n registerClass(TLSendMessageUploadVideoAction.CONSTRUCTOR_ID, TLSendMessageUploadVideoAction.class);\n registerClass(TLShippingOption.CONSTRUCTOR_ID, TLShippingOption.class);\n registerClass(TLStickerPack.CONSTRUCTOR_ID, TLStickerPack.class);\n registerClass(TLStickerSet.CONSTRUCTOR_ID, TLStickerSet.class);\n registerClass(TLStickerSetCovered.CONSTRUCTOR_ID, TLStickerSetCovered.class);\n registerClass(TLStickerSetMultiCovered.CONSTRUCTOR_ID, TLStickerSetMultiCovered.class);\n registerClass(TLFileGif.CONSTRUCTOR_ID, TLFileGif.class);\n registerClass(TLFileJpeg.CONSTRUCTOR_ID, TLFileJpeg.class);\n registerClass(TLFileMov.CONSTRUCTOR_ID, TLFileMov.class);\n registerClass(TLFileMp3.CONSTRUCTOR_ID, TLFileMp3.class);\n registerClass(TLFileMp4.CONSTRUCTOR_ID, TLFileMp4.class);\n registerClass(TLFilePartial.CONSTRUCTOR_ID, TLFilePartial.class);\n registerClass(TLFilePdf.CONSTRUCTOR_ID, TLFilePdf.class);\n registerClass(TLFilePng.CONSTRUCTOR_ID, TLFilePng.class);\n registerClass(TLFileUnknown.CONSTRUCTOR_ID, TLFileUnknown.class);\n registerClass(TLFileWebp.CONSTRUCTOR_ID, TLFileWebp.class);\n registerClass(TLTextBold.CONSTRUCTOR_ID, TLTextBold.class);\n registerClass(TLTextConcat.CONSTRUCTOR_ID, TLTextConcat.class);\n registerClass(TLTextEmail.CONSTRUCTOR_ID, TLTextEmail.class);\n registerClass(TLTextEmpty.CONSTRUCTOR_ID, TLTextEmpty.class);\n registerClass(TLTextFixed.CONSTRUCTOR_ID, TLTextFixed.class);\n registerClass(TLTextItalic.CONSTRUCTOR_ID, TLTextItalic.class);\n registerClass(TLTextPlain.CONSTRUCTOR_ID, TLTextPlain.class);\n registerClass(TLTextStrike.CONSTRUCTOR_ID, TLTextStrike.class);\n registerClass(TLTextUnderline.CONSTRUCTOR_ID, TLTextUnderline.class);\n registerClass(TLTextUrl.CONSTRUCTOR_ID, TLTextUrl.class);\n registerClass(TLTopPeer.CONSTRUCTOR_ID, TLTopPeer.class);\n registerClass(TLTopPeerCategoryBotsInline.CONSTRUCTOR_ID, TLTopPeerCategoryBotsInline.class);\n registerClass(TLTopPeerCategoryBotsPM.CONSTRUCTOR_ID, TLTopPeerCategoryBotsPM.class);\n registerClass(TLTopPeerCategoryChannels.CONSTRUCTOR_ID, TLTopPeerCategoryChannels.class);\n registerClass(TLTopPeerCategoryCorrespondents.CONSTRUCTOR_ID, TLTopPeerCategoryCorrespondents.class);\n registerClass(TLTopPeerCategoryGroups.CONSTRUCTOR_ID, TLTopPeerCategoryGroups.class);\n registerClass(TLTopPeerCategoryPeers.CONSTRUCTOR_ID, TLTopPeerCategoryPeers.class);\n registerClass(TLUpdateBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateBotCallbackQuery.class);\n registerClass(TLUpdateBotInlineQuery.CONSTRUCTOR_ID, TLUpdateBotInlineQuery.class);\n registerClass(TLUpdateBotInlineSend.CONSTRUCTOR_ID, TLUpdateBotInlineSend.class);\n registerClass(TLUpdateBotPrecheckoutQuery.CONSTRUCTOR_ID, TLUpdateBotPrecheckoutQuery.class);\n registerClass(TLUpdateBotShippingQuery.CONSTRUCTOR_ID, TLUpdateBotShippingQuery.class);\n registerClass(TLUpdateBotWebhookJSON.CONSTRUCTOR_ID, TLUpdateBotWebhookJSON.class);\n registerClass(TLUpdateBotWebhookJSONQuery.CONSTRUCTOR_ID, TLUpdateBotWebhookJSONQuery.class);\n registerClass(TLUpdateChannel.CONSTRUCTOR_ID, TLUpdateChannel.class);\n registerClass(TLUpdateChannelMessageViews.CONSTRUCTOR_ID, TLUpdateChannelMessageViews.class);\n registerClass(TLUpdateChannelPinnedMessage.CONSTRUCTOR_ID, TLUpdateChannelPinnedMessage.class);\n registerClass(TLUpdateChannelTooLong.CONSTRUCTOR_ID, TLUpdateChannelTooLong.class);\n registerClass(TLUpdateChannelWebPage.CONSTRUCTOR_ID, TLUpdateChannelWebPage.class);\n registerClass(TLUpdateChatAdmins.CONSTRUCTOR_ID, TLUpdateChatAdmins.class);\n registerClass(TLUpdateChatParticipantAdd.CONSTRUCTOR_ID, TLUpdateChatParticipantAdd.class);\n registerClass(TLUpdateChatParticipantAdmin.CONSTRUCTOR_ID, TLUpdateChatParticipantAdmin.class);\n registerClass(TLUpdateChatParticipantDelete.CONSTRUCTOR_ID, TLUpdateChatParticipantDelete.class);\n registerClass(TLUpdateChatParticipants.CONSTRUCTOR_ID, TLUpdateChatParticipants.class);\n registerClass(TLUpdateChatUserTyping.CONSTRUCTOR_ID, TLUpdateChatUserTyping.class);\n registerClass(TLUpdateConfig.CONSTRUCTOR_ID, TLUpdateConfig.class);\n registerClass(TLUpdateContactLink.CONSTRUCTOR_ID, TLUpdateContactLink.class);\n registerClass(TLUpdateContactRegistered.CONSTRUCTOR_ID, TLUpdateContactRegistered.class);\n registerClass(TLUpdateDcOptions.CONSTRUCTOR_ID, TLUpdateDcOptions.class);\n registerClass(TLUpdateDeleteChannelMessages.CONSTRUCTOR_ID, TLUpdateDeleteChannelMessages.class);\n registerClass(TLUpdateDeleteMessages.CONSTRUCTOR_ID, TLUpdateDeleteMessages.class);\n registerClass(TLUpdateDialogPinned.CONSTRUCTOR_ID, TLUpdateDialogPinned.class);\n registerClass(TLUpdateDraftMessage.CONSTRUCTOR_ID, TLUpdateDraftMessage.class);\n registerClass(TLUpdateEditChannelMessage.CONSTRUCTOR_ID, TLUpdateEditChannelMessage.class);\n registerClass(TLUpdateEditMessage.CONSTRUCTOR_ID, TLUpdateEditMessage.class);\n registerClass(TLUpdateEncryptedChatTyping.CONSTRUCTOR_ID, TLUpdateEncryptedChatTyping.class);\n registerClass(TLUpdateEncryptedMessagesRead.CONSTRUCTOR_ID, TLUpdateEncryptedMessagesRead.class);\n registerClass(TLUpdateEncryption.CONSTRUCTOR_ID, TLUpdateEncryption.class);\n registerClass(TLUpdateInlineBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateInlineBotCallbackQuery.class);\n registerClass(TLUpdateMessageID.CONSTRUCTOR_ID, TLUpdateMessageID.class);\n registerClass(TLUpdateNewChannelMessage.CONSTRUCTOR_ID, TLUpdateNewChannelMessage.class);\n registerClass(TLUpdateNewEncryptedMessage.CONSTRUCTOR_ID, TLUpdateNewEncryptedMessage.class);\n registerClass(TLUpdateNewMessage.CONSTRUCTOR_ID, TLUpdateNewMessage.class);\n registerClass(TLUpdateNewStickerSet.CONSTRUCTOR_ID, TLUpdateNewStickerSet.class);\n registerClass(TLUpdateNotifySettings.CONSTRUCTOR_ID, TLUpdateNotifySettings.class);\n registerClass(TLUpdatePhoneCall.CONSTRUCTOR_ID, TLUpdatePhoneCall.class);\n registerClass(TLUpdatePinnedDialogs.CONSTRUCTOR_ID, TLUpdatePinnedDialogs.class);\n registerClass(TLUpdatePrivacy.CONSTRUCTOR_ID, TLUpdatePrivacy.class);\n registerClass(TLUpdatePtsChanged.CONSTRUCTOR_ID, TLUpdatePtsChanged.class);\n registerClass(TLUpdateReadChannelInbox.CONSTRUCTOR_ID, TLUpdateReadChannelInbox.class);\n registerClass(TLUpdateReadChannelOutbox.CONSTRUCTOR_ID, TLUpdateReadChannelOutbox.class);\n registerClass(TLUpdateReadFeaturedStickers.CONSTRUCTOR_ID, TLUpdateReadFeaturedStickers.class);\n registerClass(TLUpdateReadHistoryInbox.CONSTRUCTOR_ID, TLUpdateReadHistoryInbox.class);\n registerClass(TLUpdateReadHistoryOutbox.CONSTRUCTOR_ID, TLUpdateReadHistoryOutbox.class);\n registerClass(TLUpdateReadMessagesContents.CONSTRUCTOR_ID, TLUpdateReadMessagesContents.class);\n registerClass(TLUpdateRecentStickers.CONSTRUCTOR_ID, TLUpdateRecentStickers.class);\n registerClass(TLUpdateSavedGifs.CONSTRUCTOR_ID, TLUpdateSavedGifs.class);\n registerClass(TLUpdateServiceNotification.CONSTRUCTOR_ID, TLUpdateServiceNotification.class);\n registerClass(TLUpdateShort.CONSTRUCTOR_ID, TLUpdateShort.class);\n registerClass(TLUpdateShortChatMessage.CONSTRUCTOR_ID, TLUpdateShortChatMessage.class);\n registerClass(TLUpdateShortMessage.CONSTRUCTOR_ID, TLUpdateShortMessage.class);\n registerClass(TLUpdateShortSentMessage.CONSTRUCTOR_ID, TLUpdateShortSentMessage.class);\n registerClass(TLUpdateStickerSets.CONSTRUCTOR_ID, TLUpdateStickerSets.class);\n registerClass(TLUpdateStickerSetsOrder.CONSTRUCTOR_ID, TLUpdateStickerSetsOrder.class);\n registerClass(TLUpdateUserBlocked.CONSTRUCTOR_ID, TLUpdateUserBlocked.class);\n registerClass(TLUpdateUserName.CONSTRUCTOR_ID, TLUpdateUserName.class);\n registerClass(TLUpdateUserPhone.CONSTRUCTOR_ID, TLUpdateUserPhone.class);\n registerClass(TLUpdateUserPhoto.CONSTRUCTOR_ID, TLUpdateUserPhoto.class);\n registerClass(TLUpdateUserStatus.CONSTRUCTOR_ID, TLUpdateUserStatus.class);\n registerClass(TLUpdateUserTyping.CONSTRUCTOR_ID, TLUpdateUserTyping.class);\n registerClass(TLUpdateWebPage.CONSTRUCTOR_ID, TLUpdateWebPage.class);\n registerClass(TLUpdates.CONSTRUCTOR_ID, TLUpdates.class);\n registerClass(TLChannelDifference.CONSTRUCTOR_ID, TLChannelDifference.class);\n registerClass(TLChannelDifferenceEmpty.CONSTRUCTOR_ID, TLChannelDifferenceEmpty.class);\n registerClass(TLChannelDifferenceTooLong.CONSTRUCTOR_ID, TLChannelDifferenceTooLong.class);\n registerClass(TLDifference.CONSTRUCTOR_ID, TLDifference.class);\n registerClass(TLDifferenceEmpty.CONSTRUCTOR_ID, TLDifferenceEmpty.class);\n registerClass(TLDifferenceSlice.CONSTRUCTOR_ID, TLDifferenceSlice.class);\n registerClass(TLDifferenceTooLong.CONSTRUCTOR_ID, TLDifferenceTooLong.class);\n registerClass(TLState.CONSTRUCTOR_ID, TLState.class);\n registerClass(TLUpdatesCombined.CONSTRUCTOR_ID, TLUpdatesCombined.class);\n registerClass(TLUpdatesTooLong.CONSTRUCTOR_ID, TLUpdatesTooLong.class);\n registerClass(TLCdnFile.CONSTRUCTOR_ID, TLCdnFile.class);\n registerClass(TLCdnFileReuploadNeeded.CONSTRUCTOR_ID, TLCdnFileReuploadNeeded.class);\n registerClass(TLFile.CONSTRUCTOR_ID, TLFile.class);\n registerClass(TLFileCdnRedirect.CONSTRUCTOR_ID, TLFileCdnRedirect.class);\n registerClass(TLWebFile.CONSTRUCTOR_ID, TLWebFile.class);\n registerClass(TLUser.CONSTRUCTOR_ID, TLUser.class);\n registerClass(TLUserEmpty.CONSTRUCTOR_ID, TLUserEmpty.class);\n registerClass(TLUserFull.CONSTRUCTOR_ID, TLUserFull.class);\n registerClass(TLUserProfilePhoto.CONSTRUCTOR_ID, TLUserProfilePhoto.class);\n registerClass(TLUserProfilePhotoEmpty.CONSTRUCTOR_ID, TLUserProfilePhotoEmpty.class);\n registerClass(TLUserStatusEmpty.CONSTRUCTOR_ID, TLUserStatusEmpty.class);\n registerClass(TLUserStatusLastMonth.CONSTRUCTOR_ID, TLUserStatusLastMonth.class);\n registerClass(TLUserStatusLastWeek.CONSTRUCTOR_ID, TLUserStatusLastWeek.class);\n registerClass(TLUserStatusOffline.CONSTRUCTOR_ID, TLUserStatusOffline.class);\n registerClass(TLUserStatusOnline.CONSTRUCTOR_ID, TLUserStatusOnline.class);\n registerClass(TLUserStatusRecently.CONSTRUCTOR_ID, TLUserStatusRecently.class);\n registerClass(TLWallPaper.CONSTRUCTOR_ID, TLWallPaper.class);\n registerClass(TLWallPaperSolid.CONSTRUCTOR_ID, TLWallPaperSolid.class);\n registerClass(TLWebDocument.CONSTRUCTOR_ID, TLWebDocument.class);\n registerClass(TLWebPage.CONSTRUCTOR_ID, TLWebPage.class);\n registerClass(TLWebPageEmpty.CONSTRUCTOR_ID, TLWebPageEmpty.class);\n registerClass(TLWebPageNotModified.CONSTRUCTOR_ID, TLWebPageNotModified.class);\n registerClass(TLWebPagePending.CONSTRUCTOR_ID, TLWebPagePending.class);\n }\n}\n"} {"task_id": "Java_103", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/badoualy/kotlogram/tl/src/main/java/com/github/badoualy/telegram/tl/api/TLApiContext.java", "mask_start_position": 39314, "mask_end_position": 55189, "canonical_solution": "registerClass(TLPeerSettings.CONSTRUCTOR_ID, TLPeerSettings.class);\n registerClass(TLPeerUser.CONSTRUCTOR_ID, TLPeerUser.class);\n registerClass(com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.class);\n registerClass(TLPhoneCall.CONSTRUCTOR_ID, TLPhoneCall.class);\n registerClass(TLPhoneCallAccepted.CONSTRUCTOR_ID, TLPhoneCallAccepted.class);\n registerClass(TLPhoneCallDiscardReasonBusy.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonBusy.class);\n registerClass(TLPhoneCallDiscardReasonDisconnect.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonDisconnect.class);\n registerClass(TLPhoneCallDiscardReasonHangup.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonHangup.class);\n registerClass(TLPhoneCallDiscardReasonMissed.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonMissed.class);\n registerClass(TLPhoneCallDiscarded.CONSTRUCTOR_ID, TLPhoneCallDiscarded.class);\n registerClass(TLPhoneCallEmpty.CONSTRUCTOR_ID, TLPhoneCallEmpty.class);\n registerClass(TLPhoneCallProtocol.CONSTRUCTOR_ID, TLPhoneCallProtocol.class);\n registerClass(TLPhoneCallRequested.CONSTRUCTOR_ID, TLPhoneCallRequested.class);\n registerClass(TLPhoneCallWaiting.CONSTRUCTOR_ID, TLPhoneCallWaiting.class);\n registerClass(TLPhoneConnection.CONSTRUCTOR_ID, TLPhoneConnection.class);\n registerClass(TLPhoto.CONSTRUCTOR_ID, TLPhoto.class);\n registerClass(TLPhotoCachedSize.CONSTRUCTOR_ID, TLPhotoCachedSize.class);\n registerClass(TLPhotoEmpty.CONSTRUCTOR_ID, TLPhotoEmpty.class);\n registerClass(TLPhotoSize.CONSTRUCTOR_ID, TLPhotoSize.class);\n registerClass(TLPhotoSizeEmpty.CONSTRUCTOR_ID, TLPhotoSizeEmpty.class);\n registerClass(com.github.badoualy.telegram.tl.api.photos.TLPhoto.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.photos.TLPhoto.class);\n registerClass(TLPhotos.CONSTRUCTOR_ID, TLPhotos.class);\n registerClass(TLPhotosSlice.CONSTRUCTOR_ID, TLPhotosSlice.class);\n registerClass(TLPostAddress.CONSTRUCTOR_ID, TLPostAddress.class);\n registerClass(TLPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLPrivacyKeyChatInvite.class);\n registerClass(TLPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLPrivacyKeyPhoneCall.class);\n registerClass(TLPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLPrivacyKeyStatusTimestamp.class);\n registerClass(TLPrivacyValueAllowAll.CONSTRUCTOR_ID, TLPrivacyValueAllowAll.class);\n registerClass(TLPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLPrivacyValueAllowContacts.class);\n registerClass(TLPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLPrivacyValueAllowUsers.class);\n registerClass(TLPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLPrivacyValueDisallowAll.class);\n registerClass(TLPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLPrivacyValueDisallowContacts.class);\n registerClass(TLPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLPrivacyValueDisallowUsers.class);\n registerClass(TLReceivedNotifyMessage.CONSTRUCTOR_ID, TLReceivedNotifyMessage.class);\n registerClass(TLReplyInlineMarkup.CONSTRUCTOR_ID, TLReplyInlineMarkup.class);\n registerClass(TLReplyKeyboardForceReply.CONSTRUCTOR_ID, TLReplyKeyboardForceReply.class);\n registerClass(TLReplyKeyboardHide.CONSTRUCTOR_ID, TLReplyKeyboardHide.class);\n registerClass(TLReplyKeyboardMarkup.CONSTRUCTOR_ID, TLReplyKeyboardMarkup.class);\n registerClass(TLSendMessageCancelAction.CONSTRUCTOR_ID, TLSendMessageCancelAction.class);\n registerClass(TLSendMessageChooseContactAction.CONSTRUCTOR_ID, TLSendMessageChooseContactAction.class);\n registerClass(TLSendMessageGamePlayAction.CONSTRUCTOR_ID, TLSendMessageGamePlayAction.class);\n registerClass(TLSendMessageGeoLocationAction.CONSTRUCTOR_ID, TLSendMessageGeoLocationAction.class);\n registerClass(TLSendMessageRecordAudioAction.CONSTRUCTOR_ID, TLSendMessageRecordAudioAction.class);\n registerClass(TLSendMessageRecordRoundAction.CONSTRUCTOR_ID, TLSendMessageRecordRoundAction.class);\n registerClass(TLSendMessageRecordVideoAction.CONSTRUCTOR_ID, TLSendMessageRecordVideoAction.class);\n registerClass(TLSendMessageTypingAction.CONSTRUCTOR_ID, TLSendMessageTypingAction.class);\n registerClass(TLSendMessageUploadAudioAction.CONSTRUCTOR_ID, TLSendMessageUploadAudioAction.class);\n registerClass(TLSendMessageUploadDocumentAction.CONSTRUCTOR_ID, TLSendMessageUploadDocumentAction.class);\n registerClass(TLSendMessageUploadPhotoAction.CONSTRUCTOR_ID, TLSendMessageUploadPhotoAction.class);\n registerClass(TLSendMessageUploadRoundAction.CONSTRUCTOR_ID, TLSendMessageUploadRoundAction.class);\n registerClass(TLSendMessageUploadVideoAction.CONSTRUCTOR_ID, TLSendMessageUploadVideoAction.class);\n registerClass(TLShippingOption.CONSTRUCTOR_ID, TLShippingOption.class);\n registerClass(TLStickerPack.CONSTRUCTOR_ID, TLStickerPack.class);\n registerClass(TLStickerSet.CONSTRUCTOR_ID, TLStickerSet.class);\n registerClass(TLStickerSetCovered.CONSTRUCTOR_ID, TLStickerSetCovered.class);\n registerClass(TLStickerSetMultiCovered.CONSTRUCTOR_ID, TLStickerSetMultiCovered.class);\n registerClass(TLFileGif.CONSTRUCTOR_ID, TLFileGif.class);\n registerClass(TLFileJpeg.CONSTRUCTOR_ID, TLFileJpeg.class);\n registerClass(TLFileMov.CONSTRUCTOR_ID, TLFileMov.class);\n registerClass(TLFileMp3.CONSTRUCTOR_ID, TLFileMp3.class);\n registerClass(TLFileMp4.CONSTRUCTOR_ID, TLFileMp4.class);\n registerClass(TLFilePartial.CONSTRUCTOR_ID, TLFilePartial.class);\n registerClass(TLFilePdf.CONSTRUCTOR_ID, TLFilePdf.class);\n registerClass(TLFilePng.CONSTRUCTOR_ID, TLFilePng.class);\n registerClass(TLFileUnknown.CONSTRUCTOR_ID, TLFileUnknown.class);\n registerClass(TLFileWebp.CONSTRUCTOR_ID, TLFileWebp.class);\n registerClass(TLTextBold.CONSTRUCTOR_ID, TLTextBold.class);\n registerClass(TLTextConcat.CONSTRUCTOR_ID, TLTextConcat.class);\n registerClass(TLTextEmail.CONSTRUCTOR_ID, TLTextEmail.class);\n registerClass(TLTextEmpty.CONSTRUCTOR_ID, TLTextEmpty.class);\n registerClass(TLTextFixed.CONSTRUCTOR_ID, TLTextFixed.class);\n registerClass(TLTextItalic.CONSTRUCTOR_ID, TLTextItalic.class);\n registerClass(TLTextPlain.CONSTRUCTOR_ID, TLTextPlain.class);\n registerClass(TLTextStrike.CONSTRUCTOR_ID, TLTextStrike.class);\n registerClass(TLTextUnderline.CONSTRUCTOR_ID, TLTextUnderline.class);\n registerClass(TLTextUrl.CONSTRUCTOR_ID, TLTextUrl.class);\n registerClass(TLTopPeer.CONSTRUCTOR_ID, TLTopPeer.class);\n registerClass(TLTopPeerCategoryBotsInline.CONSTRUCTOR_ID, TLTopPeerCategoryBotsInline.class);\n registerClass(TLTopPeerCategoryBotsPM.CONSTRUCTOR_ID, TLTopPeerCategoryBotsPM.class);\n registerClass(TLTopPeerCategoryChannels.CONSTRUCTOR_ID, TLTopPeerCategoryChannels.class);\n registerClass(TLTopPeerCategoryCorrespondents.CONSTRUCTOR_ID, TLTopPeerCategoryCorrespondents.class);\n registerClass(TLTopPeerCategoryGroups.CONSTRUCTOR_ID, TLTopPeerCategoryGroups.class);\n registerClass(TLTopPeerCategoryPeers.CONSTRUCTOR_ID, TLTopPeerCategoryPeers.class);\n registerClass(TLUpdateBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateBotCallbackQuery.class);\n registerClass(TLUpdateBotInlineQuery.CONSTRUCTOR_ID, TLUpdateBotInlineQuery.class);\n registerClass(TLUpdateBotInlineSend.CONSTRUCTOR_ID, TLUpdateBotInlineSend.class);\n registerClass(TLUpdateBotPrecheckoutQuery.CONSTRUCTOR_ID, TLUpdateBotPrecheckoutQuery.class);\n registerClass(TLUpdateBotShippingQuery.CONSTRUCTOR_ID, TLUpdateBotShippingQuery.class);\n registerClass(TLUpdateBotWebhookJSON.CONSTRUCTOR_ID, TLUpdateBotWebhookJSON.class);\n registerClass(TLUpdateBotWebhookJSONQuery.CONSTRUCTOR_ID, TLUpdateBotWebhookJSONQuery.class);\n registerClass(TLUpdateChannel.CONSTRUCTOR_ID, TLUpdateChannel.class);\n registerClass(TLUpdateChannelMessageViews.CONSTRUCTOR_ID, TLUpdateChannelMessageViews.class);\n registerClass(TLUpdateChannelPinnedMessage.CONSTRUCTOR_ID, TLUpdateChannelPinnedMessage.class);\n registerClass(TLUpdateChannelTooLong.CONSTRUCTOR_ID, TLUpdateChannelTooLong.class);\n registerClass(TLUpdateChannelWebPage.CONSTRUCTOR_ID, TLUpdateChannelWebPage.class);\n registerClass(TLUpdateChatAdmins.CONSTRUCTOR_ID, TLUpdateChatAdmins.class);\n registerClass(TLUpdateChatParticipantAdd.CONSTRUCTOR_ID, TLUpdateChatParticipantAdd.class);\n registerClass(TLUpdateChatParticipantAdmin.CONSTRUCTOR_ID, TLUpdateChatParticipantAdmin.class);\n registerClass(TLUpdateChatParticipantDelete.CONSTRUCTOR_ID, TLUpdateChatParticipantDelete.class);\n registerClass(TLUpdateChatParticipants.CONSTRUCTOR_ID, TLUpdateChatParticipants.class);\n registerClass(TLUpdateChatUserTyping.CONSTRUCTOR_ID, TLUpdateChatUserTyping.class);\n registerClass(TLUpdateConfig.CONSTRUCTOR_ID, TLUpdateConfig.class);\n registerClass(TLUpdateContactLink.CONSTRUCTOR_ID, TLUpdateContactLink.class);\n registerClass(TLUpdateContactRegistered.CONSTRUCTOR_ID, TLUpdateContactRegistered.class);\n registerClass(TLUpdateDcOptions.CONSTRUCTOR_ID, TLUpdateDcOptions.class);\n registerClass(TLUpdateDeleteChannelMessages.CONSTRUCTOR_ID, TLUpdateDeleteChannelMessages.class);\n registerClass(TLUpdateDeleteMessages.CONSTRUCTOR_ID, TLUpdateDeleteMessages.class);\n registerClass(TLUpdateDialogPinned.CONSTRUCTOR_ID, TLUpdateDialogPinned.class);\n registerClass(TLUpdateDraftMessage.CONSTRUCTOR_ID, TLUpdateDraftMessage.class);\n registerClass(TLUpdateEditChannelMessage.CONSTRUCTOR_ID, TLUpdateEditChannelMessage.class);\n registerClass(TLUpdateEditMessage.CONSTRUCTOR_ID, TLUpdateEditMessage.class);\n registerClass(TLUpdateEncryptedChatTyping.CONSTRUCTOR_ID, TLUpdateEncryptedChatTyping.class);\n registerClass(TLUpdateEncryptedMessagesRead.CONSTRUCTOR_ID, TLUpdateEncryptedMessagesRead.class);\n registerClass(TLUpdateEncryption.CONSTRUCTOR_ID, TLUpdateEncryption.class);\n registerClass(TLUpdateInlineBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateInlineBotCallbackQuery.class);\n registerClass(TLUpdateMessageID.CONSTRUCTOR_ID, TLUpdateMessageID.class);\n registerClass(TLUpdateNewChannelMessage.CONSTRUCTOR_ID, TLUpdateNewChannelMessage.class);\n registerClass(TLUpdateNewEncryptedMessage.CONSTRUCTOR_ID, TLUpdateNewEncryptedMessage.class);\n registerClass(TLUpdateNewMessage.CONSTRUCTOR_ID, TLUpdateNewMessage.class);\n registerClass(TLUpdateNewStickerSet.CONSTRUCTOR_ID, TLUpdateNewStickerSet.class);\n registerClass(TLUpdateNotifySettings.CONSTRUCTOR_ID, TLUpdateNotifySettings.class);\n registerClass(TLUpdatePhoneCall.CONSTRUCTOR_ID, TLUpdatePhoneCall.class);\n registerClass(TLUpdatePinnedDialogs.CONSTRUCTOR_ID, TLUpdatePinnedDialogs.class);\n registerClass(TLUpdatePrivacy.CONSTRUCTOR_ID, TLUpdatePrivacy.class);\n registerClass(TLUpdatePtsChanged.CONSTRUCTOR_ID, TLUpdatePtsChanged.class);\n registerClass(TLUpdateReadChannelInbox.CONSTRUCTOR_ID, TLUpdateReadChannelInbox.class);\n registerClass(TLUpdateReadChannelOutbox.CONSTRUCTOR_ID, TLUpdateReadChannelOutbox.class);\n registerClass(TLUpdateReadFeaturedStickers.CONSTRUCTOR_ID, TLUpdateReadFeaturedStickers.class);\n registerClass(TLUpdateReadHistoryInbox.CONSTRUCTOR_ID, TLUpdateReadHistoryInbox.class);\n registerClass(TLUpdateReadHistoryOutbox.CONSTRUCTOR_ID, TLUpdateReadHistoryOutbox.class);\n registerClass(TLUpdateReadMessagesContents.CONSTRUCTOR_ID, TLUpdateReadMessagesContents.class);\n registerClass(TLUpdateRecentStickers.CONSTRUCTOR_ID, TLUpdateRecentStickers.class);\n registerClass(TLUpdateSavedGifs.CONSTRUCTOR_ID, TLUpdateSavedGifs.class);\n registerClass(TLUpdateServiceNotification.CONSTRUCTOR_ID, TLUpdateServiceNotification.class);\n registerClass(TLUpdateShort.CONSTRUCTOR_ID, TLUpdateShort.class);\n registerClass(TLUpdateShortChatMessage.CONSTRUCTOR_ID, TLUpdateShortChatMessage.class);\n registerClass(TLUpdateShortMessage.CONSTRUCTOR_ID, TLUpdateShortMessage.class);\n registerClass(TLUpdateShortSentMessage.CONSTRUCTOR_ID, TLUpdateShortSentMessage.class);\n registerClass(TLUpdateStickerSets.CONSTRUCTOR_ID, TLUpdateStickerSets.class);\n registerClass(TLUpdateStickerSetsOrder.CONSTRUCTOR_ID, TLUpdateStickerSetsOrder.class);\n registerClass(TLUpdateUserBlocked.CONSTRUCTOR_ID, TLUpdateUserBlocked.class);\n registerClass(TLUpdateUserName.CONSTRUCTOR_ID, TLUpdateUserName.class);\n registerClass(TLUpdateUserPhone.CONSTRUCTOR_ID, TLUpdateUserPhone.class);\n registerClass(TLUpdateUserPhoto.CONSTRUCTOR_ID, TLUpdateUserPhoto.class);\n registerClass(TLUpdateUserStatus.CONSTRUCTOR_ID, TLUpdateUserStatus.class);\n registerClass(TLUpdateUserTyping.CONSTRUCTOR_ID, TLUpdateUserTyping.class);\n registerClass(TLUpdateWebPage.CONSTRUCTOR_ID, TLUpdateWebPage.class);\n registerClass(TLUpdates.CONSTRUCTOR_ID, TLUpdates.class);\n registerClass(TLChannelDifference.CONSTRUCTOR_ID, TLChannelDifference.class);\n registerClass(TLChannelDifferenceEmpty.CONSTRUCTOR_ID, TLChannelDifferenceEmpty.class);\n registerClass(TLChannelDifferenceTooLong.CONSTRUCTOR_ID, TLChannelDifferenceTooLong.class);\n registerClass(TLDifference.CONSTRUCTOR_ID, TLDifference.class);\n registerClass(TLDifferenceEmpty.CONSTRUCTOR_ID, TLDifferenceEmpty.class);\n registerClass(TLDifferenceSlice.CONSTRUCTOR_ID, TLDifferenceSlice.class);\n registerClass(TLDifferenceTooLong.CONSTRUCTOR_ID, TLDifferenceTooLong.class);\n registerClass(TLState.CONSTRUCTOR_ID, TLState.class);\n registerClass(TLUpdatesCombined.CONSTRUCTOR_ID, TLUpdatesCombined.class);\n registerClass(TLUpdatesTooLong.CONSTRUCTOR_ID, TLUpdatesTooLong.class);\n registerClass(TLCdnFile.CONSTRUCTOR_ID, TLCdnFile.class);\n registerClass(TLCdnFileReuploadNeeded.CONSTRUCTOR_ID, TLCdnFileReuploadNeeded.class);\n registerClass(TLFile.CONSTRUCTOR_ID, TLFile.class);\n registerClass(TLFileCdnRedirect.CONSTRUCTOR_ID, TLFileCdnRedirect.class);\n registerClass(TLWebFile.CONSTRUCTOR_ID, TLWebFile.class);\n registerClass(TLUser.CONSTRUCTOR_ID, TLUser.class);\n registerClass(TLUserEmpty.CONSTRUCTOR_ID, TLUserEmpty.class);\n registerClass(TLUserFull.CONSTRUCTOR_ID, TLUserFull.class);\n registerClass(TLUserProfilePhoto.CONSTRUCTOR_ID, TLUserProfilePhoto.class);\n registerClass(TLUserProfilePhotoEmpty.CONSTRUCTOR_ID, TLUserProfilePhotoEmpty.class);\n registerClass(TLUserStatusEmpty.CONSTRUCTOR_ID, TLUserStatusEmpty.class);\n registerClass(TLUserStatusLastMonth.CONSTRUCTOR_ID, TLUserStatusLastMonth.class);\n registerClass(TLUserStatusLastWeek.CONSTRUCTOR_ID, TLUserStatusLastWeek.class);\n registerClass(TLUserStatusOffline.CONSTRUCTOR_ID, TLUserStatusOffline.class);\n registerClass(TLUserStatusOnline.CONSTRUCTOR_ID, TLUserStatusOnline.class);\n registerClass(TLUserStatusRecently.CONSTRUCTOR_ID, TLUserStatusRecently.class);\n registerClass(TLWallPaper.CONSTRUCTOR_ID, TLWallPaper.class);\n registerClass(TLWallPaperSolid.CONSTRUCTOR_ID, TLWallPaperSolid.class);\n registerClass(TLWebDocument.CONSTRUCTOR_ID, TLWebDocument.class);\n registerClass(TLWebPage.CONSTRUCTOR_ID, TLWebPage.class);\n registerClass(TLWebPageEmpty.CONSTRUCTOR_ID, TLWebPageEmpty.class);\n registerClass(TLWebPageNotModified.CONSTRUCTOR_ID, TLWebPageNotModified.class);\n registerClass(TLWebPagePending.CONSTRUCTOR_ID, TLWebPagePending.class);\n }", "pre_mask_code": "package com.github.badoualy.telegram.tl.api;\n\nimport com.github.badoualy.telegram.tl.TLContext;\nimport com.github.badoualy.telegram.tl.api.account.TLAuthorizations;\nimport com.github.badoualy.telegram.tl.api.account.TLNoPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordInputSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPrivacyRules;\nimport com.github.badoualy.telegram.tl.api.account.TLTmpPassword;\nimport com.github.badoualy.telegram.tl.api.auth.TLCheckedPhone;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.auth.TLExportedAuthorization;\nimport com.github.badoualy.telegram.tl.api.auth.TLPasswordRecovery;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCode;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeApp;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.channels.TLChannelParticipants;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlocked;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlockedSlice;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContactsNotModified;\nimport com.github.badoualy.telegram.tl.api.contacts.TLFound;\nimport com.github.badoualy.telegram.tl.api.contacts.TLImportedContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLLink;\nimport com.github.badoualy.telegram.tl.api.contacts.TLResolvedPeer;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeers;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeersNotModified;\nimport com.github.badoualy.telegram.tl.api.help.TLAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLInviteText;\nimport com.github.badoualy.telegram.tl.api.help.TLNoAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLSupport;\nimport com.github.badoualy.telegram.tl.api.help.TLTermsOfService;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedHistory;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLArchivedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotCallbackAnswer;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotResults;\nimport com.github.badoualy.telegram.tl.api.messages.TLChannelMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLChats;\nimport com.github.badoualy.telegram.tl.api.messages.TLChatsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfig;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfigNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLFoundGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLHighScores;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessageEditData;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessagesSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLPeerDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifsNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedFile;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedMessage;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultArchive;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultSuccess;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentForm;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentReceipt;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentResult;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentVerficationNeeded;\nimport com.github.badoualy.telegram.tl.api.payments.TLSavedInfo;\nimport com.github.badoualy.telegram.tl.api.payments.TLValidatedRequestedInfo;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotos;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotosSlice;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileGif;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileJpeg;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMov;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp3;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp4;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePartial;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePdf;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePng;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileUnknown;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileWebp;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceSlice;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLState;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFileReuploadNeeded;\nimport com.github.badoualy.telegram.tl.api.upload.TLFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLFileCdnRedirect;\nimport com.github.badoualy.telegram.tl.api.upload.TLWebFile;\n\n/**\n * @author Yannick Badoual example@nnthink.com\n * @see http://example.com\n */\n@SuppressWarnings(\"unused\")\npublic class TLApiContext extends TLContext {\n\n private static TLApiContext instance;\n\n public TLApiContext() {\n super(543);\n }\n\n public static TLApiContext getInstance() {\n if (instance == null) {\n instance = new TLApiContext();\n }\n return instance;\n }\n\n @Override\n public void init() {\n registerClass(TLAuthorizations.CONSTRUCTOR_ID, TLAuthorizations.class);\n registerClass(TLNoPassword.CONSTRUCTOR_ID, TLNoPassword.class);\n registerClass(TLPassword.CONSTRUCTOR_ID, TLPassword.class);\n registerClass(TLPasswordInputSettings.CONSTRUCTOR_ID, TLPasswordInputSettings.class);\n registerClass(TLPasswordSettings.CONSTRUCTOR_ID, TLPasswordSettings.class);\n registerClass(TLPrivacyRules.CONSTRUCTOR_ID, TLPrivacyRules.class);\n registerClass(TLTmpPassword.CONSTRUCTOR_ID, TLTmpPassword.class);\n registerClass(TLAccountDaysTTL.CONSTRUCTOR_ID, TLAccountDaysTTL.class);\n registerClass(com.github.badoualy.telegram.tl.api.auth.TLAuthorization.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.auth.TLAuthorization.class);\n registerClass(TLCheckedPhone.CONSTRUCTOR_ID, TLCheckedPhone.class);\n registerClass(TLCodeTypeCall.CONSTRUCTOR_ID, TLCodeTypeCall.class);\n registerClass(TLCodeTypeFlashCall.CONSTRUCTOR_ID, TLCodeTypeFlashCall.class);\n registerClass(TLCodeTypeSms.CONSTRUCTOR_ID, TLCodeTypeSms.class);\n registerClass(TLExportedAuthorization.CONSTRUCTOR_ID, TLExportedAuthorization.class);\n registerClass(TLPasswordRecovery.CONSTRUCTOR_ID, TLPasswordRecovery.class);\n registerClass(TLSentCode.CONSTRUCTOR_ID, TLSentCode.class);\n registerClass(TLSentCodeTypeApp.CONSTRUCTOR_ID, TLSentCodeTypeApp.class);\n registerClass(TLSentCodeTypeCall.CONSTRUCTOR_ID, TLSentCodeTypeCall.class);\n registerClass(TLSentCodeTypeFlashCall.CONSTRUCTOR_ID, TLSentCodeTypeFlashCall.class);\n registerClass(TLSentCodeTypeSms.CONSTRUCTOR_ID, TLSentCodeTypeSms.class);\n registerClass(TLAuthorization.CONSTRUCTOR_ID, TLAuthorization.class);\n registerClass(TLBotCommand.CONSTRUCTOR_ID, TLBotCommand.class);\n registerClass(TLBotInfo.CONSTRUCTOR_ID, TLBotInfo.class);\n registerClass(TLBotInlineMediaResult.CONSTRUCTOR_ID, TLBotInlineMediaResult.class);\n registerClass(TLBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLBotInlineMessageMediaAuto.class);\n registerClass(TLBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLBotInlineMessageMediaContact.class);\n registerClass(TLBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLBotInlineMessageMediaGeo.class);\n registerClass(TLBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLBotInlineMessageMediaVenue.class);\n registerClass(TLBotInlineMessageText.CONSTRUCTOR_ID, TLBotInlineMessageText.class);\n registerClass(TLBotInlineResult.CONSTRUCTOR_ID, TLBotInlineResult.class);\n registerClass(TLCdnConfig.CONSTRUCTOR_ID, TLCdnConfig.class);\n registerClass(TLCdnPublicKey.CONSTRUCTOR_ID, TLCdnPublicKey.class);\n registerClass(TLChannel.CONSTRUCTOR_ID, TLChannel.class);\n registerClass(TLChannelForbidden.CONSTRUCTOR_ID, TLChannelForbidden.class);\n registerClass(TLChannelFull.CONSTRUCTOR_ID, TLChannelFull.class);\n registerClass(TLChannelMessagesFilter.CONSTRUCTOR_ID, TLChannelMessagesFilter.class);\n registerClass(TLChannelMessagesFilterEmpty.CONSTRUCTOR_ID, TLChannelMessagesFilterEmpty.class);\n registerClass(TLChannelParticipant.CONSTRUCTOR_ID, TLChannelParticipant.class);\n registerClass(TLChannelParticipantCreator.CONSTRUCTOR_ID, TLChannelParticipantCreator.class);\n registerClass(TLChannelParticipantEditor.CONSTRUCTOR_ID, TLChannelParticipantEditor.class);\n registerClass(TLChannelParticipantKicked.CONSTRUCTOR_ID, TLChannelParticipantKicked.class);\n registerClass(TLChannelParticipantModerator.CONSTRUCTOR_ID, TLChannelParticipantModerator.class);\n registerClass(TLChannelParticipantSelf.CONSTRUCTOR_ID, TLChannelParticipantSelf.class);\n registerClass(TLChannelParticipantsAdmins.CONSTRUCTOR_ID, TLChannelParticipantsAdmins.class);\n registerClass(TLChannelParticipantsBots.CONSTRUCTOR_ID, TLChannelParticipantsBots.class);\n registerClass(TLChannelParticipantsKicked.CONSTRUCTOR_ID, TLChannelParticipantsKicked.class);\n registerClass(TLChannelParticipantsRecent.CONSTRUCTOR_ID, TLChannelParticipantsRecent.class);\n registerClass(TLChannelRoleEditor.CONSTRUCTOR_ID, TLChannelRoleEditor.class);\n registerClass(TLChannelRoleEmpty.CONSTRUCTOR_ID, TLChannelRoleEmpty.class);\n registerClass(TLChannelRoleModerator.CONSTRUCTOR_ID, TLChannelRoleModerator.class);\n registerClass(com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.class);\n registerClass(TLChannelParticipants.CONSTRUCTOR_ID, TLChannelParticipants.class);\n registerClass(TLChat.CONSTRUCTOR_ID, TLChat.class);\n registerClass(TLChatEmpty.CONSTRUCTOR_ID, TLChatEmpty.class);\n registerClass(TLChatForbidden.CONSTRUCTOR_ID, TLChatForbidden.class);\n registerClass(TLChatFull.CONSTRUCTOR_ID, TLChatFull.class);\n registerClass(TLChatInvite.CONSTRUCTOR_ID, TLChatInvite.class);\n registerClass(TLChatInviteAlready.CONSTRUCTOR_ID, TLChatInviteAlready.class);\n registerClass(TLChatInviteEmpty.CONSTRUCTOR_ID, TLChatInviteEmpty.class);\n registerClass(TLChatInviteExported.CONSTRUCTOR_ID, TLChatInviteExported.class);\n registerClass(TLChatParticipant.CONSTRUCTOR_ID, TLChatParticipant.class);\n registerClass(TLChatParticipantAdmin.CONSTRUCTOR_ID, TLChatParticipantAdmin.class);\n registerClass(TLChatParticipantCreator.CONSTRUCTOR_ID, TLChatParticipantCreator.class);\n registerClass(TLChatParticipants.CONSTRUCTOR_ID, TLChatParticipants.class);\n registerClass(TLChatParticipantsForbidden.CONSTRUCTOR_ID, TLChatParticipantsForbidden.class);\n registerClass(TLChatPhoto.CONSTRUCTOR_ID, TLChatPhoto.class);\n registerClass(TLChatPhotoEmpty.CONSTRUCTOR_ID, TLChatPhotoEmpty.class);\n registerClass(TLConfig.CONSTRUCTOR_ID, TLConfig.class);\n registerClass(TLContact.CONSTRUCTOR_ID, TLContact.class);\n registerClass(TLContactBlocked.CONSTRUCTOR_ID, TLContactBlocked.class);\n registerClass(TLContactLinkContact.CONSTRUCTOR_ID, TLContactLinkContact.class);\n registerClass(TLContactLinkHasPhone.CONSTRUCTOR_ID, TLContactLinkHasPhone.class);\n registerClass(TLContactLinkNone.CONSTRUCTOR_ID, TLContactLinkNone.class);\n registerClass(TLContactLinkUnknown.CONSTRUCTOR_ID, TLContactLinkUnknown.class);\n registerClass(TLContactStatus.CONSTRUCTOR_ID, TLContactStatus.class);\n registerClass(TLBlocked.CONSTRUCTOR_ID, TLBlocked.class);\n registerClass(TLBlockedSlice.CONSTRUCTOR_ID, TLBlockedSlice.class);\n registerClass(TLContacts.CONSTRUCTOR_ID, TLContacts.class);\n registerClass(TLContactsNotModified.CONSTRUCTOR_ID, TLContactsNotModified.class);\n registerClass(TLFound.CONSTRUCTOR_ID, TLFound.class);\n registerClass(TLImportedContacts.CONSTRUCTOR_ID, TLImportedContacts.class);\n registerClass(TLLink.CONSTRUCTOR_ID, TLLink.class);\n registerClass(TLResolvedPeer.CONSTRUCTOR_ID, TLResolvedPeer.class);\n registerClass(TLTopPeers.CONSTRUCTOR_ID, TLTopPeers.class);\n registerClass(TLTopPeersNotModified.CONSTRUCTOR_ID, TLTopPeersNotModified.class);\n registerClass(TLDataJSON.CONSTRUCTOR_ID, TLDataJSON.class);\n registerClass(TLDcOption.CONSTRUCTOR_ID, TLDcOption.class);\n registerClass(TLDialog.CONSTRUCTOR_ID, TLDialog.class);\n registerClass(TLDisabledFeature.CONSTRUCTOR_ID, TLDisabledFeature.class);\n registerClass(TLDocument.CONSTRUCTOR_ID, TLDocument.class);\n registerClass(TLDocumentAttributeAnimated.CONSTRUCTOR_ID, TLDocumentAttributeAnimated.class);\n registerClass(TLDocumentAttributeAudio.CONSTRUCTOR_ID, TLDocumentAttributeAudio.class);\n registerClass(TLDocumentAttributeFilename.CONSTRUCTOR_ID, TLDocumentAttributeFilename.class);\n registerClass(TLDocumentAttributeHasStickers.CONSTRUCTOR_ID, TLDocumentAttributeHasStickers.class);\n registerClass(TLDocumentAttributeImageSize.CONSTRUCTOR_ID, TLDocumentAttributeImageSize.class);\n registerClass(TLDocumentAttributeSticker.CONSTRUCTOR_ID, TLDocumentAttributeSticker.class);\n registerClass(TLDocumentAttributeVideo.CONSTRUCTOR_ID, TLDocumentAttributeVideo.class);\n registerClass(TLDocumentEmpty.CONSTRUCTOR_ID, TLDocumentEmpty.class);\n registerClass(TLDraftMessage.CONSTRUCTOR_ID, TLDraftMessage.class);\n registerClass(TLDraftMessageEmpty.CONSTRUCTOR_ID, TLDraftMessageEmpty.class);\n registerClass(TLEncryptedChat.CONSTRUCTOR_ID, TLEncryptedChat.class);\n registerClass(TLEncryptedChatDiscarded.CONSTRUCTOR_ID, TLEncryptedChatDiscarded.class);\n registerClass(TLEncryptedChatEmpty.CONSTRUCTOR_ID, TLEncryptedChatEmpty.class);\n registerClass(TLEncryptedChatRequested.CONSTRUCTOR_ID, TLEncryptedChatRequested.class);\n registerClass(TLEncryptedChatWaiting.CONSTRUCTOR_ID, TLEncryptedChatWaiting.class);\n registerClass(TLEncryptedFile.CONSTRUCTOR_ID, TLEncryptedFile.class);\n registerClass(TLEncryptedFileEmpty.CONSTRUCTOR_ID, TLEncryptedFileEmpty.class);\n registerClass(TLEncryptedMessage.CONSTRUCTOR_ID, TLEncryptedMessage.class);\n registerClass(TLEncryptedMessageService.CONSTRUCTOR_ID, TLEncryptedMessageService.class);\n registerClass(TLExportedMessageLink.CONSTRUCTOR_ID, TLExportedMessageLink.class);\n registerClass(TLFileLocation.CONSTRUCTOR_ID, TLFileLocation.class);\n registerClass(TLFileLocationUnavailable.CONSTRUCTOR_ID, TLFileLocationUnavailable.class);\n registerClass(TLFoundGif.CONSTRUCTOR_ID, TLFoundGif.class);\n registerClass(TLFoundGifCached.CONSTRUCTOR_ID, TLFoundGifCached.class);\n registerClass(TLGame.CONSTRUCTOR_ID, TLGame.class);\n registerClass(TLGeoPoint.CONSTRUCTOR_ID, TLGeoPoint.class);\n registerClass(TLGeoPointEmpty.CONSTRUCTOR_ID, TLGeoPointEmpty.class);\n registerClass(TLAppUpdate.CONSTRUCTOR_ID, TLAppUpdate.class);\n registerClass(TLInviteText.CONSTRUCTOR_ID, TLInviteText.class);\n registerClass(TLNoAppUpdate.CONSTRUCTOR_ID, TLNoAppUpdate.class);\n registerClass(TLSupport.CONSTRUCTOR_ID, TLSupport.class);\n registerClass(TLTermsOfService.CONSTRUCTOR_ID, TLTermsOfService.class);\n registerClass(TLHighScore.CONSTRUCTOR_ID, TLHighScore.class);\n registerClass(TLImportedContact.CONSTRUCTOR_ID, TLImportedContact.class);\n registerClass(TLInlineBotSwitchPM.CONSTRUCTOR_ID, TLInlineBotSwitchPM.class);\n registerClass(TLInputAppEvent.CONSTRUCTOR_ID, TLInputAppEvent.class);\n registerClass(TLInputBotInlineMessageGame.CONSTRUCTOR_ID, TLInputBotInlineMessageGame.class);\n registerClass(TLInputBotInlineMessageID.CONSTRUCTOR_ID, TLInputBotInlineMessageID.class);\n registerClass(TLInputBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaAuto.class);\n registerClass(TLInputBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaContact.class);\n registerClass(TLInputBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaGeo.class);\n registerClass(TLInputBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaVenue.class);\n registerClass(TLInputBotInlineMessageText.CONSTRUCTOR_ID, TLInputBotInlineMessageText.class);\n registerClass(TLInputBotInlineResult.CONSTRUCTOR_ID, TLInputBotInlineResult.class);\n registerClass(TLInputBotInlineResultDocument.CONSTRUCTOR_ID, TLInputBotInlineResultDocument.class);\n registerClass(TLInputBotInlineResultGame.CONSTRUCTOR_ID, TLInputBotInlineResultGame.class);\n registerClass(TLInputBotInlineResultPhoto.CONSTRUCTOR_ID, TLInputBotInlineResultPhoto.class);\n registerClass(TLInputChannel.CONSTRUCTOR_ID, TLInputChannel.class);\n registerClass(TLInputChannelEmpty.CONSTRUCTOR_ID, TLInputChannelEmpty.class);\n registerClass(TLInputChatPhoto.CONSTRUCTOR_ID, TLInputChatPhoto.class);\n registerClass(TLInputChatPhotoEmpty.CONSTRUCTOR_ID, TLInputChatPhotoEmpty.class);\n registerClass(TLInputChatUploadedPhoto.CONSTRUCTOR_ID, TLInputChatUploadedPhoto.class);\n registerClass(TLInputDocument.CONSTRUCTOR_ID, TLInputDocument.class);\n registerClass(TLInputDocumentEmpty.CONSTRUCTOR_ID, TLInputDocumentEmpty.class);\n registerClass(TLInputDocumentFileLocation.CONSTRUCTOR_ID, TLInputDocumentFileLocation.class);\n registerClass(TLInputEncryptedChat.CONSTRUCTOR_ID, TLInputEncryptedChat.class);\n registerClass(TLInputEncryptedFile.CONSTRUCTOR_ID, TLInputEncryptedFile.class);\n registerClass(TLInputEncryptedFileBigUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileBigUploaded.class);\n registerClass(TLInputEncryptedFileEmpty.CONSTRUCTOR_ID, TLInputEncryptedFileEmpty.class);\n registerClass(TLInputEncryptedFileLocation.CONSTRUCTOR_ID, TLInputEncryptedFileLocation.class);\n registerClass(TLInputEncryptedFileUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileUploaded.class);\n registerClass(TLInputFile.CONSTRUCTOR_ID, TLInputFile.class);\n registerClass(TLInputFileBig.CONSTRUCTOR_ID, TLInputFileBig.class);\n registerClass(TLInputFileLocation.CONSTRUCTOR_ID, TLInputFileLocation.class);\n registerClass(TLInputGameID.CONSTRUCTOR_ID, TLInputGameID.class);\n registerClass(TLInputGameShortName.CONSTRUCTOR_ID, TLInputGameShortName.class);\n registerClass(TLInputGeoPoint.CONSTRUCTOR_ID, TLInputGeoPoint.class);\n registerClass(TLInputGeoPointEmpty.CONSTRUCTOR_ID, TLInputGeoPointEmpty.class);\n registerClass(TLInputMediaContact.CONSTRUCTOR_ID, TLInputMediaContact.class);\n registerClass(TLInputMediaDocument.CONSTRUCTOR_ID, TLInputMediaDocument.class);\n registerClass(TLInputMediaDocumentExternal.CONSTRUCTOR_ID, TLInputMediaDocumentExternal.class);\n registerClass(TLInputMediaEmpty.CONSTRUCTOR_ID, TLInputMediaEmpty.class);\n registerClass(TLInputMediaGame.CONSTRUCTOR_ID, TLInputMediaGame.class);\n registerClass(TLInputMediaGeoPoint.CONSTRUCTOR_ID, TLInputMediaGeoPoint.class);\n registerClass(TLInputMediaGifExternal.CONSTRUCTOR_ID, TLInputMediaGifExternal.class);\n registerClass(TLInputMediaInvoice.CONSTRUCTOR_ID, TLInputMediaInvoice.class);\n registerClass(TLInputMediaPhoto.CONSTRUCTOR_ID, TLInputMediaPhoto.class);\n registerClass(TLInputMediaPhotoExternal.CONSTRUCTOR_ID, TLInputMediaPhotoExternal.class);\n registerClass(TLInputMediaUploadedDocument.CONSTRUCTOR_ID, TLInputMediaUploadedDocument.class);\n registerClass(TLInputMediaUploadedPhoto.CONSTRUCTOR_ID, TLInputMediaUploadedPhoto.class);\n registerClass(TLInputMediaUploadedThumbDocument.CONSTRUCTOR_ID, TLInputMediaUploadedThumbDocument.class);\n registerClass(TLInputMediaVenue.CONSTRUCTOR_ID, TLInputMediaVenue.class);\n registerClass(TLInputMessageEntityMentionName.CONSTRUCTOR_ID, TLInputMessageEntityMentionName.class);\n registerClass(TLInputMessagesFilterChatPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterChatPhotos.class);\n registerClass(TLInputMessagesFilterDocument.CONSTRUCTOR_ID, TLInputMessagesFilterDocument.class);\n registerClass(TLInputMessagesFilterEmpty.CONSTRUCTOR_ID, TLInputMessagesFilterEmpty.class);\n registerClass(TLInputMessagesFilterGif.CONSTRUCTOR_ID, TLInputMessagesFilterGif.class);\n registerClass(TLInputMessagesFilterMusic.CONSTRUCTOR_ID, TLInputMessagesFilterMusic.class);\n registerClass(TLInputMessagesFilterPhoneCalls.CONSTRUCTOR_ID, TLInputMessagesFilterPhoneCalls.class);\n registerClass(TLInputMessagesFilterPhotoVideo.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideo.class);\n registerClass(TLInputMessagesFilterPhotoVideoDocuments.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideoDocuments.class);\n registerClass(TLInputMessagesFilterPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterPhotos.class);\n registerClass(TLInputMessagesFilterRoundVideo.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVideo.class);\n registerClass(TLInputMessagesFilterRoundVoice.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVoice.class);\n registerClass(TLInputMessagesFilterUrl.CONSTRUCTOR_ID, TLInputMessagesFilterUrl.class);\n registerClass(TLInputMessagesFilterVideo.CONSTRUCTOR_ID, TLInputMessagesFilterVideo.class);\n registerClass(TLInputMessagesFilterVoice.CONSTRUCTOR_ID, TLInputMessagesFilterVoice.class);\n registerClass(TLInputNotifyAll.CONSTRUCTOR_ID, TLInputNotifyAll.class);\n registerClass(TLInputNotifyChats.CONSTRUCTOR_ID, TLInputNotifyChats.class);\n registerClass(TLInputNotifyPeer.CONSTRUCTOR_ID, TLInputNotifyPeer.class);\n registerClass(TLInputNotifyUsers.CONSTRUCTOR_ID, TLInputNotifyUsers.class);\n registerClass(TLInputPaymentCredentials.CONSTRUCTOR_ID, TLInputPaymentCredentials.class);\n registerClass(TLInputPaymentCredentialsSaved.CONSTRUCTOR_ID, TLInputPaymentCredentialsSaved.class);\n registerClass(TLInputPeerChannel.CONSTRUCTOR_ID, TLInputPeerChannel.class);\n registerClass(TLInputPeerChat.CONSTRUCTOR_ID, TLInputPeerChat.class);\n registerClass(TLInputPeerEmpty.CONSTRUCTOR_ID, TLInputPeerEmpty.class);\n registerClass(TLInputPeerNotifyEventsAll.CONSTRUCTOR_ID, TLInputPeerNotifyEventsAll.class);\n registerClass(TLInputPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLInputPeerNotifyEventsEmpty.class);\n registerClass(TLInputPeerNotifySettings.CONSTRUCTOR_ID, TLInputPeerNotifySettings.class);\n registerClass(TLInputPeerSelf.CONSTRUCTOR_ID, TLInputPeerSelf.class);\n registerClass(TLInputPeerUser.CONSTRUCTOR_ID, TLInputPeerUser.class);\n registerClass(TLInputPhoneCall.CONSTRUCTOR_ID, TLInputPhoneCall.class);\n registerClass(TLInputPhoneContact.CONSTRUCTOR_ID, TLInputPhoneContact.class);\n registerClass(TLInputPhoto.CONSTRUCTOR_ID, TLInputPhoto.class);\n registerClass(TLInputPhotoEmpty.CONSTRUCTOR_ID, TLInputPhotoEmpty.class);\n registerClass(TLInputPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLInputPrivacyKeyChatInvite.class);\n registerClass(TLInputPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLInputPrivacyKeyPhoneCall.class);\n registerClass(TLInputPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLInputPrivacyKeyStatusTimestamp.class);\n registerClass(TLInputPrivacyValueAllowAll.CONSTRUCTOR_ID, TLInputPrivacyValueAllowAll.class);\n registerClass(TLInputPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueAllowContacts.class);\n registerClass(TLInputPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueAllowUsers.class);\n registerClass(TLInputPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowAll.class);\n registerClass(TLInputPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowContacts.class);\n registerClass(TLInputPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowUsers.class);\n registerClass(TLInputReportReasonOther.CONSTRUCTOR_ID, TLInputReportReasonOther.class);\n registerClass(TLInputReportReasonPornography.CONSTRUCTOR_ID, TLInputReportReasonPornography.class);\n registerClass(TLInputReportReasonSpam.CONSTRUCTOR_ID, TLInputReportReasonSpam.class);\n registerClass(TLInputReportReasonViolence.CONSTRUCTOR_ID, TLInputReportReasonViolence.class);\n registerClass(TLInputStickerSetEmpty.CONSTRUCTOR_ID, TLInputStickerSetEmpty.class);\n registerClass(TLInputStickerSetID.CONSTRUCTOR_ID, TLInputStickerSetID.class);\n registerClass(TLInputStickerSetShortName.CONSTRUCTOR_ID, TLInputStickerSetShortName.class);\n registerClass(TLInputStickeredMediaDocument.CONSTRUCTOR_ID, TLInputStickeredMediaDocument.class);\n registerClass(TLInputStickeredMediaPhoto.CONSTRUCTOR_ID, TLInputStickeredMediaPhoto.class);\n registerClass(TLInputUser.CONSTRUCTOR_ID, TLInputUser.class);\n registerClass(TLInputUserEmpty.CONSTRUCTOR_ID, TLInputUserEmpty.class);\n registerClass(TLInputUserSelf.CONSTRUCTOR_ID, TLInputUserSelf.class);\n registerClass(TLInputWebDocument.CONSTRUCTOR_ID, TLInputWebDocument.class);\n registerClass(TLInputWebFileLocation.CONSTRUCTOR_ID, TLInputWebFileLocation.class);\n registerClass(TLInvoice.CONSTRUCTOR_ID, TLInvoice.class);\n registerClass(TLKeyboardButton.CONSTRUCTOR_ID, TLKeyboardButton.class);\n registerClass(TLKeyboardButtonBuy.CONSTRUCTOR_ID, TLKeyboardButtonBuy.class);\n registerClass(TLKeyboardButtonCallback.CONSTRUCTOR_ID, TLKeyboardButtonCallback.class);\n registerClass(TLKeyboardButtonGame.CONSTRUCTOR_ID, TLKeyboardButtonGame.class);\n registerClass(TLKeyboardButtonRequestGeoLocation.CONSTRUCTOR_ID, TLKeyboardButtonRequestGeoLocation.class);\n registerClass(TLKeyboardButtonRequestPhone.CONSTRUCTOR_ID, TLKeyboardButtonRequestPhone.class);\n registerClass(TLKeyboardButtonRow.CONSTRUCTOR_ID, TLKeyboardButtonRow.class);\n registerClass(TLKeyboardButtonSwitchInline.CONSTRUCTOR_ID, TLKeyboardButtonSwitchInline.class);\n registerClass(TLKeyboardButtonUrl.CONSTRUCTOR_ID, TLKeyboardButtonUrl.class);\n registerClass(TLLabeledPrice.CONSTRUCTOR_ID, TLLabeledPrice.class);\n registerClass(TLMaskCoords.CONSTRUCTOR_ID, TLMaskCoords.class);\n registerClass(TLMessage.CONSTRUCTOR_ID, TLMessage.class);\n registerClass(TLMessageActionChannelCreate.CONSTRUCTOR_ID, TLMessageActionChannelCreate.class);\n registerClass(TLMessageActionChannelMigrateFrom.CONSTRUCTOR_ID, TLMessageActionChannelMigrateFrom.class);\n registerClass(TLMessageActionChatAddUser.CONSTRUCTOR_ID, TLMessageActionChatAddUser.class);\n registerClass(TLMessageActionChatCreate.CONSTRUCTOR_ID, TLMessageActionChatCreate.class);\n registerClass(TLMessageActionChatDeletePhoto.CONSTRUCTOR_ID, TLMessageActionChatDeletePhoto.class);\n registerClass(TLMessageActionChatDeleteUser.CONSTRUCTOR_ID, TLMessageActionChatDeleteUser.class);\n registerClass(TLMessageActionChatEditPhoto.CONSTRUCTOR_ID, TLMessageActionChatEditPhoto.class);\n registerClass(TLMessageActionChatEditTitle.CONSTRUCTOR_ID, TLMessageActionChatEditTitle.class);\n registerClass(TLMessageActionChatJoinedByLink.CONSTRUCTOR_ID, TLMessageActionChatJoinedByLink.class);\n registerClass(TLMessageActionChatMigrateTo.CONSTRUCTOR_ID, TLMessageActionChatMigrateTo.class);\n registerClass(TLMessageActionEmpty.CONSTRUCTOR_ID, TLMessageActionEmpty.class);\n registerClass(TLMessageActionGameScore.CONSTRUCTOR_ID, TLMessageActionGameScore.class);\n registerClass(TLMessageActionHistoryClear.CONSTRUCTOR_ID, TLMessageActionHistoryClear.class);\n registerClass(TLMessageActionPaymentSent.CONSTRUCTOR_ID, TLMessageActionPaymentSent.class);\n registerClass(TLMessageActionPaymentSentMe.CONSTRUCTOR_ID, TLMessageActionPaymentSentMe.class);\n registerClass(TLMessageActionPhoneCall.CONSTRUCTOR_ID, TLMessageActionPhoneCall.class);\n registerClass(TLMessageActionPinMessage.CONSTRUCTOR_ID, TLMessageActionPinMessage.class);\n registerClass(TLMessageEmpty.CONSTRUCTOR_ID, TLMessageEmpty.class);\n registerClass(TLMessageEntityBold.CONSTRUCTOR_ID, TLMessageEntityBold.class);\n registerClass(TLMessageEntityBotCommand.CONSTRUCTOR_ID, TLMessageEntityBotCommand.class);\n registerClass(TLMessageEntityCode.CONSTRUCTOR_ID, TLMessageEntityCode.class);\n registerClass(TLMessageEntityEmail.CONSTRUCTOR_ID, TLMessageEntityEmail.class);\n registerClass(TLMessageEntityHashtag.CONSTRUCTOR_ID, TLMessageEntityHashtag.class);\n registerClass(TLMessageEntityItalic.CONSTRUCTOR_ID, TLMessageEntityItalic.class);\n registerClass(TLMessageEntityMention.CONSTRUCTOR_ID, TLMessageEntityMention.class);\n registerClass(TLMessageEntityMentionName.CONSTRUCTOR_ID, TLMessageEntityMentionName.class);\n registerClass(TLMessageEntityPre.CONSTRUCTOR_ID, TLMessageEntityPre.class);\n registerClass(TLMessageEntityTextUrl.CONSTRUCTOR_ID, TLMessageEntityTextUrl.class);\n registerClass(TLMessageEntityUnknown.CONSTRUCTOR_ID, TLMessageEntityUnknown.class);\n registerClass(TLMessageEntityUrl.CONSTRUCTOR_ID, TLMessageEntityUrl.class);\n registerClass(TLMessageFwdHeader.CONSTRUCTOR_ID, TLMessageFwdHeader.class);\n registerClass(TLMessageMediaContact.CONSTRUCTOR_ID, TLMessageMediaContact.class);\n registerClass(TLMessageMediaDocument.CONSTRUCTOR_ID, TLMessageMediaDocument.class);\n registerClass(TLMessageMediaEmpty.CONSTRUCTOR_ID, TLMessageMediaEmpty.class);\n registerClass(TLMessageMediaGame.CONSTRUCTOR_ID, TLMessageMediaGame.class);\n registerClass(TLMessageMediaGeo.CONSTRUCTOR_ID, TLMessageMediaGeo.class);\n registerClass(TLMessageMediaInvoice.CONSTRUCTOR_ID, TLMessageMediaInvoice.class);\n registerClass(TLMessageMediaPhoto.CONSTRUCTOR_ID, TLMessageMediaPhoto.class);\n registerClass(TLMessageMediaUnsupported.CONSTRUCTOR_ID, TLMessageMediaUnsupported.class);\n registerClass(TLMessageMediaVenue.CONSTRUCTOR_ID, TLMessageMediaVenue.class);\n registerClass(TLMessageMediaWebPage.CONSTRUCTOR_ID, TLMessageMediaWebPage.class);\n registerClass(TLMessageRange.CONSTRUCTOR_ID, TLMessageRange.class);\n registerClass(TLMessageService.CONSTRUCTOR_ID, TLMessageService.class);\n registerClass(TLAffectedHistory.CONSTRUCTOR_ID, TLAffectedHistory.class);\n registerClass(TLAffectedMessages.CONSTRUCTOR_ID, TLAffectedMessages.class);\n registerClass(TLAllStickers.CONSTRUCTOR_ID, TLAllStickers.class);\n registerClass(TLAllStickersNotModified.CONSTRUCTOR_ID, TLAllStickersNotModified.class);\n registerClass(TLArchivedStickers.CONSTRUCTOR_ID, TLArchivedStickers.class);\n registerClass(TLBotCallbackAnswer.CONSTRUCTOR_ID, TLBotCallbackAnswer.class);\n registerClass(TLBotResults.CONSTRUCTOR_ID, TLBotResults.class);\n registerClass(TLChannelMessages.CONSTRUCTOR_ID, TLChannelMessages.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLChatFull.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLChatFull.class);\n registerClass(TLChats.CONSTRUCTOR_ID, TLChats.class);\n registerClass(TLChatsSlice.CONSTRUCTOR_ID, TLChatsSlice.class);\n registerClass(TLDhConfig.CONSTRUCTOR_ID, TLDhConfig.class);\n registerClass(TLDhConfigNotModified.CONSTRUCTOR_ID, TLDhConfigNotModified.class);\n registerClass(TLDialogs.CONSTRUCTOR_ID, TLDialogs.class);\n registerClass(TLDialogsSlice.CONSTRUCTOR_ID, TLDialogsSlice.class);\n registerClass(TLFeaturedStickers.CONSTRUCTOR_ID, TLFeaturedStickers.class);\n registerClass(TLFeaturedStickersNotModified.CONSTRUCTOR_ID, TLFeaturedStickersNotModified.class);\n registerClass(TLFoundGifs.CONSTRUCTOR_ID, TLFoundGifs.class);\n registerClass(TLHighScores.CONSTRUCTOR_ID, TLHighScores.class);\n registerClass(TLMessageEditData.CONSTRUCTOR_ID, TLMessageEditData.class);\n registerClass(TLMessages.CONSTRUCTOR_ID, TLMessages.class);\n registerClass(TLMessagesSlice.CONSTRUCTOR_ID, TLMessagesSlice.class);\n registerClass(TLPeerDialogs.CONSTRUCTOR_ID, TLPeerDialogs.class);\n registerClass(TLRecentStickers.CONSTRUCTOR_ID, TLRecentStickers.class);\n registerClass(TLRecentStickersNotModified.CONSTRUCTOR_ID, TLRecentStickersNotModified.class);\n registerClass(TLSavedGifs.CONSTRUCTOR_ID, TLSavedGifs.class);\n registerClass(TLSavedGifsNotModified.CONSTRUCTOR_ID, TLSavedGifsNotModified.class);\n registerClass(TLSentEncryptedFile.CONSTRUCTOR_ID, TLSentEncryptedFile.class);\n registerClass(TLSentEncryptedMessage.CONSTRUCTOR_ID, TLSentEncryptedMessage.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLStickerSet.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLStickerSet.class);\n registerClass(TLStickerSetInstallResultArchive.CONSTRUCTOR_ID, TLStickerSetInstallResultArchive.class);\n registerClass(TLStickerSetInstallResultSuccess.CONSTRUCTOR_ID, TLStickerSetInstallResultSuccess.class);\n registerClass(TLStickers.CONSTRUCTOR_ID, TLStickers.class);\n registerClass(TLStickersNotModified.CONSTRUCTOR_ID, TLStickersNotModified.class);\n registerClass(TLNearestDc.CONSTRUCTOR_ID, TLNearestDc.class);\n registerClass(TLNotifyAll.CONSTRUCTOR_ID, TLNotifyAll.class);\n registerClass(TLNotifyChats.CONSTRUCTOR_ID, TLNotifyChats.class);\n registerClass(TLNotifyPeer.CONSTRUCTOR_ID, TLNotifyPeer.class);\n registerClass(TLNotifyUsers.CONSTRUCTOR_ID, TLNotifyUsers.class);\n registerClass(TLPageBlockAnchor.CONSTRUCTOR_ID, TLPageBlockAnchor.class);\n registerClass(TLPageBlockAuthorDate.CONSTRUCTOR_ID, TLPageBlockAuthorDate.class);\n registerClass(TLPageBlockBlockquote.CONSTRUCTOR_ID, TLPageBlockBlockquote.class);\n registerClass(TLPageBlockChannel.CONSTRUCTOR_ID, TLPageBlockChannel.class);\n registerClass(TLPageBlockCollage.CONSTRUCTOR_ID, TLPageBlockCollage.class);\n registerClass(TLPageBlockCover.CONSTRUCTOR_ID, TLPageBlockCover.class);\n registerClass(TLPageBlockDivider.CONSTRUCTOR_ID, TLPageBlockDivider.class);\n registerClass(TLPageBlockEmbed.CONSTRUCTOR_ID, TLPageBlockEmbed.class);\n registerClass(TLPageBlockEmbedPost.CONSTRUCTOR_ID, TLPageBlockEmbedPost.class);\n registerClass(TLPageBlockFooter.CONSTRUCTOR_ID, TLPageBlockFooter.class);\n registerClass(TLPageBlockHeader.CONSTRUCTOR_ID, TLPageBlockHeader.class);\n registerClass(TLPageBlockList.CONSTRUCTOR_ID, TLPageBlockList.class);\n registerClass(TLPageBlockParagraph.CONSTRUCTOR_ID, TLPageBlockParagraph.class);\n registerClass(TLPageBlockPhoto.CONSTRUCTOR_ID, TLPageBlockPhoto.class);\n registerClass(TLPageBlockPreformatted.CONSTRUCTOR_ID, TLPageBlockPreformatted.class);\n registerClass(TLPageBlockPullquote.CONSTRUCTOR_ID, TLPageBlockPullquote.class);\n registerClass(TLPageBlockSlideshow.CONSTRUCTOR_ID, TLPageBlockSlideshow.class);\n registerClass(TLPageBlockSubheader.CONSTRUCTOR_ID, TLPageBlockSubheader.class);\n registerClass(TLPageBlockSubtitle.CONSTRUCTOR_ID, TLPageBlockSubtitle.class);\n registerClass(TLPageBlockTitle.CONSTRUCTOR_ID, TLPageBlockTitle.class);\n registerClass(TLPageBlockUnsupported.CONSTRUCTOR_ID, TLPageBlockUnsupported.class);\n registerClass(TLPageBlockVideo.CONSTRUCTOR_ID, TLPageBlockVideo.class);\n registerClass(TLPageFull.CONSTRUCTOR_ID, TLPageFull.class);\n registerClass(TLPagePart.CONSTRUCTOR_ID, TLPagePart.class);\n registerClass(TLPaymentCharge.CONSTRUCTOR_ID, TLPaymentCharge.class);\n registerClass(TLPaymentRequestedInfo.CONSTRUCTOR_ID, TLPaymentRequestedInfo.class);\n registerClass(TLPaymentSavedCredentialsCard.CONSTRUCTOR_ID, TLPaymentSavedCredentialsCard.class);\n registerClass(TLPaymentForm.CONSTRUCTOR_ID, TLPaymentForm.class);\n registerClass(TLPaymentReceipt.CONSTRUCTOR_ID, TLPaymentReceipt.class);\n registerClass(TLPaymentResult.CONSTRUCTOR_ID, TLPaymentResult.class);\n registerClass(TLPaymentVerficationNeeded.CONSTRUCTOR_ID, TLPaymentVerficationNeeded.class);\n registerClass(TLSavedInfo.CONSTRUCTOR_ID, TLSavedInfo.class);\n registerClass(TLValidatedRequestedInfo.CONSTRUCTOR_ID, TLValidatedRequestedInfo.class);\n registerClass(TLPeerChannel.CONSTRUCTOR_ID, TLPeerChannel.class);\n registerClass(TLPeerChat.CONSTRUCTOR_ID, TLPeerChat.class);\n registerClass(TLPeerNotifyEventsAll.CONSTRUCTOR_ID, TLPeerNotifyEventsAll.class);\n registerClass(TLPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLPeerNotifyEventsEmpty.class);\n registerClass(TLPeerNotifySettings.CONSTRUCTOR_ID, TLPeerNotifySettings.class);\n registerClass(TLPeerNotifySettingsEmpty.CONSTRUCTOR_ID, TLPeerNotifySettingsEmpty.class);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_104", "language": "Java", "task_type": "single_line", "source_file": "java/github/badoualy/kotlogram/tl/src/main/java/com/github/badoualy/telegram/tl/api/TLApiContext.java", "mask_start_position": 31868, "mask_end_position": 31931, "canonical_solution": "TLMessageMediaEmpty.CONSTRUCTOR_ID, TLMessageMediaEmpty.class);", "pre_mask_code": "package com.github.badoualy.telegram.tl.api;\n\nimport com.github.badoualy.telegram.tl.TLContext;\nimport com.github.badoualy.telegram.tl.api.account.TLAuthorizations;\nimport com.github.badoualy.telegram.tl.api.account.TLNoPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordInputSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPrivacyRules;\nimport com.github.badoualy.telegram.tl.api.account.TLTmpPassword;\nimport com.github.badoualy.telegram.tl.api.auth.TLCheckedPhone;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.auth.TLExportedAuthorization;\nimport com.github.badoualy.telegram.tl.api.auth.TLPasswordRecovery;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCode;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeApp;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.channels.TLChannelParticipants;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlocked;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlockedSlice;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContactsNotModified;\nimport com.github.badoualy.telegram.tl.api.contacts.TLFound;\nimport com.github.badoualy.telegram.tl.api.contacts.TLImportedContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLLink;\nimport com.github.badoualy.telegram.tl.api.contacts.TLResolvedPeer;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeers;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeersNotModified;\nimport com.github.badoualy.telegram.tl.api.help.TLAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLInviteText;\nimport com.github.badoualy.telegram.tl.api.help.TLNoAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLSupport;\nimport com.github.badoualy.telegram.tl.api.help.TLTermsOfService;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedHistory;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLArchivedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotCallbackAnswer;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotResults;\nimport com.github.badoualy.telegram.tl.api.messages.TLChannelMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLChats;\nimport com.github.badoualy.telegram.tl.api.messages.TLChatsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfig;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfigNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLFoundGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLHighScores;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessageEditData;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessagesSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLPeerDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifsNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedFile;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedMessage;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultArchive;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultSuccess;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentForm;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentReceipt;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentResult;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentVerficationNeeded;\nimport com.github.badoualy.telegram.tl.api.payments.TLSavedInfo;\nimport com.github.badoualy.telegram.tl.api.payments.TLValidatedRequestedInfo;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotos;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotosSlice;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileGif;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileJpeg;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMov;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp3;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp4;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePartial;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePdf;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePng;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileUnknown;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileWebp;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceSlice;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLState;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFileReuploadNeeded;\nimport com.github.badoualy.telegram.tl.api.upload.TLFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLFileCdnRedirect;\nimport com.github.badoualy.telegram.tl.api.upload.TLWebFile;\n\n/**\n * @author Yannick Badoual example@nnthink.com\n * @see http://example.com\n */\n@SuppressWarnings(\"unused\")\npublic class TLApiContext extends TLContext {\n\n private static TLApiContext instance;\n\n public TLApiContext() {\n super(543);\n }\n\n public static TLApiContext getInstance() {\n if (instance == null) {\n instance = new TLApiContext();\n }\n return instance;\n }\n\n @Override\n public void init() {\n registerClass(TLAuthorizations.CONSTRUCTOR_ID, TLAuthorizations.class);\n registerClass(TLNoPassword.CONSTRUCTOR_ID, TLNoPassword.class);\n registerClass(TLPassword.CONSTRUCTOR_ID, TLPassword.class);\n registerClass(TLPasswordInputSettings.CONSTRUCTOR_ID, TLPasswordInputSettings.class);\n registerClass(TLPasswordSettings.CONSTRUCTOR_ID, TLPasswordSettings.class);\n registerClass(TLPrivacyRules.CONSTRUCTOR_ID, TLPrivacyRules.class);\n registerClass(TLTmpPassword.CONSTRUCTOR_ID, TLTmpPassword.class);\n registerClass(TLAccountDaysTTL.CONSTRUCTOR_ID, TLAccountDaysTTL.class);\n registerClass(com.github.badoualy.telegram.tl.api.auth.TLAuthorization.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.auth.TLAuthorization.class);\n registerClass(TLCheckedPhone.CONSTRUCTOR_ID, TLCheckedPhone.class);\n registerClass(TLCodeTypeCall.CONSTRUCTOR_ID, TLCodeTypeCall.class);\n registerClass(TLCodeTypeFlashCall.CONSTRUCTOR_ID, TLCodeTypeFlashCall.class);\n registerClass(TLCodeTypeSms.CONSTRUCTOR_ID, TLCodeTypeSms.class);\n registerClass(TLExportedAuthorization.CONSTRUCTOR_ID, TLExportedAuthorization.class);\n registerClass(TLPasswordRecovery.CONSTRUCTOR_ID, TLPasswordRecovery.class);\n registerClass(TLSentCode.CONSTRUCTOR_ID, TLSentCode.class);\n registerClass(TLSentCodeTypeApp.CONSTRUCTOR_ID, TLSentCodeTypeApp.class);\n registerClass(TLSentCodeTypeCall.CONSTRUCTOR_ID, TLSentCodeTypeCall.class);\n registerClass(TLSentCodeTypeFlashCall.CONSTRUCTOR_ID, TLSentCodeTypeFlashCall.class);\n registerClass(TLSentCodeTypeSms.CONSTRUCTOR_ID, TLSentCodeTypeSms.class);\n registerClass(TLAuthorization.CONSTRUCTOR_ID, TLAuthorization.class);\n registerClass(TLBotCommand.CONSTRUCTOR_ID, TLBotCommand.class);\n registerClass(TLBotInfo.CONSTRUCTOR_ID, TLBotInfo.class);\n registerClass(TLBotInlineMediaResult.CONSTRUCTOR_ID, TLBotInlineMediaResult.class);\n registerClass(TLBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLBotInlineMessageMediaAuto.class);\n registerClass(TLBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLBotInlineMessageMediaContact.class);\n registerClass(TLBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLBotInlineMessageMediaGeo.class);\n registerClass(TLBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLBotInlineMessageMediaVenue.class);\n registerClass(TLBotInlineMessageText.CONSTRUCTOR_ID, TLBotInlineMessageText.class);\n registerClass(TLBotInlineResult.CONSTRUCTOR_ID, TLBotInlineResult.class);\n registerClass(TLCdnConfig.CONSTRUCTOR_ID, TLCdnConfig.class);\n registerClass(TLCdnPublicKey.CONSTRUCTOR_ID, TLCdnPublicKey.class);\n registerClass(TLChannel.CONSTRUCTOR_ID, TLChannel.class);\n registerClass(TLChannelForbidden.CONSTRUCTOR_ID, TLChannelForbidden.class);\n registerClass(TLChannelFull.CONSTRUCTOR_ID, TLChannelFull.class);\n registerClass(TLChannelMessagesFilter.CONSTRUCTOR_ID, TLChannelMessagesFilter.class);\n registerClass(TLChannelMessagesFilterEmpty.CONSTRUCTOR_ID, TLChannelMessagesFilterEmpty.class);\n registerClass(TLChannelParticipant.CONSTRUCTOR_ID, TLChannelParticipant.class);\n registerClass(TLChannelParticipantCreator.CONSTRUCTOR_ID, TLChannelParticipantCreator.class);\n registerClass(TLChannelParticipantEditor.CONSTRUCTOR_ID, TLChannelParticipantEditor.class);\n registerClass(TLChannelParticipantKicked.CONSTRUCTOR_ID, TLChannelParticipantKicked.class);\n registerClass(TLChannelParticipantModerator.CONSTRUCTOR_ID, TLChannelParticipantModerator.class);\n registerClass(TLChannelParticipantSelf.CONSTRUCTOR_ID, TLChannelParticipantSelf.class);\n registerClass(TLChannelParticipantsAdmins.CONSTRUCTOR_ID, TLChannelParticipantsAdmins.class);\n registerClass(TLChannelParticipantsBots.CONSTRUCTOR_ID, TLChannelParticipantsBots.class);\n registerClass(TLChannelParticipantsKicked.CONSTRUCTOR_ID, TLChannelParticipantsKicked.class);\n registerClass(TLChannelParticipantsRecent.CONSTRUCTOR_ID, TLChannelParticipantsRecent.class);\n registerClass(TLChannelRoleEditor.CONSTRUCTOR_ID, TLChannelRoleEditor.class);\n registerClass(TLChannelRoleEmpty.CONSTRUCTOR_ID, TLChannelRoleEmpty.class);\n registerClass(TLChannelRoleModerator.CONSTRUCTOR_ID, TLChannelRoleModerator.class);\n registerClass(com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.class);\n registerClass(TLChannelParticipants.CONSTRUCTOR_ID, TLChannelParticipants.class);\n registerClass(TLChat.CONSTRUCTOR_ID, TLChat.class);\n registerClass(TLChatEmpty.CONSTRUCTOR_ID, TLChatEmpty.class);\n registerClass(TLChatForbidden.CONSTRUCTOR_ID, TLChatForbidden.class);\n registerClass(TLChatFull.CONSTRUCTOR_ID, TLChatFull.class);\n registerClass(TLChatInvite.CONSTRUCTOR_ID, TLChatInvite.class);\n registerClass(TLChatInviteAlready.CONSTRUCTOR_ID, TLChatInviteAlready.class);\n registerClass(TLChatInviteEmpty.CONSTRUCTOR_ID, TLChatInviteEmpty.class);\n registerClass(TLChatInviteExported.CONSTRUCTOR_ID, TLChatInviteExported.class);\n registerClass(TLChatParticipant.CONSTRUCTOR_ID, TLChatParticipant.class);\n registerClass(TLChatParticipantAdmin.CONSTRUCTOR_ID, TLChatParticipantAdmin.class);\n registerClass(TLChatParticipantCreator.CONSTRUCTOR_ID, TLChatParticipantCreator.class);\n registerClass(TLChatParticipants.CONSTRUCTOR_ID, TLChatParticipants.class);\n registerClass(TLChatParticipantsForbidden.CONSTRUCTOR_ID, TLChatParticipantsForbidden.class);\n registerClass(TLChatPhoto.CONSTRUCTOR_ID, TLChatPhoto.class);\n registerClass(TLChatPhotoEmpty.CONSTRUCTOR_ID, TLChatPhotoEmpty.class);\n registerClass(TLConfig.CONSTRUCTOR_ID, TLConfig.class);\n registerClass(TLContact.CONSTRUCTOR_ID, TLContact.class);\n registerClass(TLContactBlocked.CONSTRUCTOR_ID, TLContactBlocked.class);\n registerClass(TLContactLinkContact.CONSTRUCTOR_ID, TLContactLinkContact.class);\n registerClass(TLContactLinkHasPhone.CONSTRUCTOR_ID, TLContactLinkHasPhone.class);\n registerClass(TLContactLinkNone.CONSTRUCTOR_ID, TLContactLinkNone.class);\n registerClass(TLContactLinkUnknown.CONSTRUCTOR_ID, TLContactLinkUnknown.class);\n registerClass(TLContactStatus.CONSTRUCTOR_ID, TLContactStatus.class);\n registerClass(TLBlocked.CONSTRUCTOR_ID, TLBlocked.class);\n registerClass(TLBlockedSlice.CONSTRUCTOR_ID, TLBlockedSlice.class);\n registerClass(TLContacts.CONSTRUCTOR_ID, TLContacts.class);\n registerClass(TLContactsNotModified.CONSTRUCTOR_ID, TLContactsNotModified.class);\n registerClass(TLFound.CONSTRUCTOR_ID, TLFound.class);\n registerClass(TLImportedContacts.CONSTRUCTOR_ID, TLImportedContacts.class);\n registerClass(TLLink.CONSTRUCTOR_ID, TLLink.class);\n registerClass(TLResolvedPeer.CONSTRUCTOR_ID, TLResolvedPeer.class);\n registerClass(TLTopPeers.CONSTRUCTOR_ID, TLTopPeers.class);\n registerClass(TLTopPeersNotModified.CONSTRUCTOR_ID, TLTopPeersNotModified.class);\n registerClass(TLDataJSON.CONSTRUCTOR_ID, TLDataJSON.class);\n registerClass(TLDcOption.CONSTRUCTOR_ID, TLDcOption.class);\n registerClass(TLDialog.CONSTRUCTOR_ID, TLDialog.class);\n registerClass(TLDisabledFeature.CONSTRUCTOR_ID, TLDisabledFeature.class);\n registerClass(TLDocument.CONSTRUCTOR_ID, TLDocument.class);\n registerClass(TLDocumentAttributeAnimated.CONSTRUCTOR_ID, TLDocumentAttributeAnimated.class);\n registerClass(TLDocumentAttributeAudio.CONSTRUCTOR_ID, TLDocumentAttributeAudio.class);\n registerClass(TLDocumentAttributeFilename.CONSTRUCTOR_ID, TLDocumentAttributeFilename.class);\n registerClass(TLDocumentAttributeHasStickers.CONSTRUCTOR_ID, TLDocumentAttributeHasStickers.class);\n registerClass(TLDocumentAttributeImageSize.CONSTRUCTOR_ID, TLDocumentAttributeImageSize.class);\n registerClass(TLDocumentAttributeSticker.CONSTRUCTOR_ID, TLDocumentAttributeSticker.class);\n registerClass(TLDocumentAttributeVideo.CONSTRUCTOR_ID, TLDocumentAttributeVideo.class);\n registerClass(TLDocumentEmpty.CONSTRUCTOR_ID, TLDocumentEmpty.class);\n registerClass(TLDraftMessage.CONSTRUCTOR_ID, TLDraftMessage.class);\n registerClass(TLDraftMessageEmpty.CONSTRUCTOR_ID, TLDraftMessageEmpty.class);\n registerClass(TLEncryptedChat.CONSTRUCTOR_ID, TLEncryptedChat.class);\n registerClass(TLEncryptedChatDiscarded.CONSTRUCTOR_ID, TLEncryptedChatDiscarded.class);\n registerClass(TLEncryptedChatEmpty.CONSTRUCTOR_ID, TLEncryptedChatEmpty.class);\n registerClass(TLEncryptedChatRequested.CONSTRUCTOR_ID, TLEncryptedChatRequested.class);\n registerClass(TLEncryptedChatWaiting.CONSTRUCTOR_ID, TLEncryptedChatWaiting.class);\n registerClass(TLEncryptedFile.CONSTRUCTOR_ID, TLEncryptedFile.class);\n registerClass(TLEncryptedFileEmpty.CONSTRUCTOR_ID, TLEncryptedFileEmpty.class);\n registerClass(TLEncryptedMessage.CONSTRUCTOR_ID, TLEncryptedMessage.class);\n registerClass(TLEncryptedMessageService.CONSTRUCTOR_ID, TLEncryptedMessageService.class);\n registerClass(TLExportedMessageLink.CONSTRUCTOR_ID, TLExportedMessageLink.class);\n registerClass(TLFileLocation.CONSTRUCTOR_ID, TLFileLocation.class);\n registerClass(TLFileLocationUnavailable.CONSTRUCTOR_ID, TLFileLocationUnavailable.class);\n registerClass(TLFoundGif.CONSTRUCTOR_ID, TLFoundGif.class);\n registerClass(TLFoundGifCached.CONSTRUCTOR_ID, TLFoundGifCached.class);\n registerClass(TLGame.CONSTRUCTOR_ID, TLGame.class);\n registerClass(TLGeoPoint.CONSTRUCTOR_ID, TLGeoPoint.class);\n registerClass(TLGeoPointEmpty.CONSTRUCTOR_ID, TLGeoPointEmpty.class);\n registerClass(TLAppUpdate.CONSTRUCTOR_ID, TLAppUpdate.class);\n registerClass(TLInviteText.CONSTRUCTOR_ID, TLInviteText.class);\n registerClass(TLNoAppUpdate.CONSTRUCTOR_ID, TLNoAppUpdate.class);\n registerClass(TLSupport.CONSTRUCTOR_ID, TLSupport.class);\n registerClass(TLTermsOfService.CONSTRUCTOR_ID, TLTermsOfService.class);\n registerClass(TLHighScore.CONSTRUCTOR_ID, TLHighScore.class);\n registerClass(TLImportedContact.CONSTRUCTOR_ID, TLImportedContact.class);\n registerClass(TLInlineBotSwitchPM.CONSTRUCTOR_ID, TLInlineBotSwitchPM.class);\n registerClass(TLInputAppEvent.CONSTRUCTOR_ID, TLInputAppEvent.class);\n registerClass(TLInputBotInlineMessageGame.CONSTRUCTOR_ID, TLInputBotInlineMessageGame.class);\n registerClass(TLInputBotInlineMessageID.CONSTRUCTOR_ID, TLInputBotInlineMessageID.class);\n registerClass(TLInputBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaAuto.class);\n registerClass(TLInputBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaContact.class);\n registerClass(TLInputBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaGeo.class);\n registerClass(TLInputBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaVenue.class);\n registerClass(TLInputBotInlineMessageText.CONSTRUCTOR_ID, TLInputBotInlineMessageText.class);\n registerClass(TLInputBotInlineResult.CONSTRUCTOR_ID, TLInputBotInlineResult.class);\n registerClass(TLInputBotInlineResultDocument.CONSTRUCTOR_ID, TLInputBotInlineResultDocument.class);\n registerClass(TLInputBotInlineResultGame.CONSTRUCTOR_ID, TLInputBotInlineResultGame.class);\n registerClass(TLInputBotInlineResultPhoto.CONSTRUCTOR_ID, TLInputBotInlineResultPhoto.class);\n registerClass(TLInputChannel.CONSTRUCTOR_ID, TLInputChannel.class);\n registerClass(TLInputChannelEmpty.CONSTRUCTOR_ID, TLInputChannelEmpty.class);\n registerClass(TLInputChatPhoto.CONSTRUCTOR_ID, TLInputChatPhoto.class);\n registerClass(TLInputChatPhotoEmpty.CONSTRUCTOR_ID, TLInputChatPhotoEmpty.class);\n registerClass(TLInputChatUploadedPhoto.CONSTRUCTOR_ID, TLInputChatUploadedPhoto.class);\n registerClass(TLInputDocument.CONSTRUCTOR_ID, TLInputDocument.class);\n registerClass(TLInputDocumentEmpty.CONSTRUCTOR_ID, TLInputDocumentEmpty.class);\n registerClass(TLInputDocumentFileLocation.CONSTRUCTOR_ID, TLInputDocumentFileLocation.class);\n registerClass(TLInputEncryptedChat.CONSTRUCTOR_ID, TLInputEncryptedChat.class);\n registerClass(TLInputEncryptedFile.CONSTRUCTOR_ID, TLInputEncryptedFile.class);\n registerClass(TLInputEncryptedFileBigUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileBigUploaded.class);\n registerClass(TLInputEncryptedFileEmpty.CONSTRUCTOR_ID, TLInputEncryptedFileEmpty.class);\n registerClass(TLInputEncryptedFileLocation.CONSTRUCTOR_ID, TLInputEncryptedFileLocation.class);\n registerClass(TLInputEncryptedFileUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileUploaded.class);\n registerClass(TLInputFile.CONSTRUCTOR_ID, TLInputFile.class);\n registerClass(TLInputFileBig.CONSTRUCTOR_ID, TLInputFileBig.class);\n registerClass(TLInputFileLocation.CONSTRUCTOR_ID, TLInputFileLocation.class);\n registerClass(TLInputGameID.CONSTRUCTOR_ID, TLInputGameID.class);\n registerClass(TLInputGameShortName.CONSTRUCTOR_ID, TLInputGameShortName.class);\n registerClass(TLInputGeoPoint.CONSTRUCTOR_ID, TLInputGeoPoint.class);\n registerClass(TLInputGeoPointEmpty.CONSTRUCTOR_ID, TLInputGeoPointEmpty.class);\n registerClass(TLInputMediaContact.CONSTRUCTOR_ID, TLInputMediaContact.class);\n registerClass(TLInputMediaDocument.CONSTRUCTOR_ID, TLInputMediaDocument.class);\n registerClass(TLInputMediaDocumentExternal.CONSTRUCTOR_ID, TLInputMediaDocumentExternal.class);\n registerClass(TLInputMediaEmpty.CONSTRUCTOR_ID, TLInputMediaEmpty.class);\n registerClass(TLInputMediaGame.CONSTRUCTOR_ID, TLInputMediaGame.class);\n registerClass(TLInputMediaGeoPoint.CONSTRUCTOR_ID, TLInputMediaGeoPoint.class);\n registerClass(TLInputMediaGifExternal.CONSTRUCTOR_ID, TLInputMediaGifExternal.class);\n registerClass(TLInputMediaInvoice.CONSTRUCTOR_ID, TLInputMediaInvoice.class);\n registerClass(TLInputMediaPhoto.CONSTRUCTOR_ID, TLInputMediaPhoto.class);\n registerClass(TLInputMediaPhotoExternal.CONSTRUCTOR_ID, TLInputMediaPhotoExternal.class);\n registerClass(TLInputMediaUploadedDocument.CONSTRUCTOR_ID, TLInputMediaUploadedDocument.class);\n registerClass(TLInputMediaUploadedPhoto.CONSTRUCTOR_ID, TLInputMediaUploadedPhoto.class);\n registerClass(TLInputMediaUploadedThumbDocument.CONSTRUCTOR_ID, TLInputMediaUploadedThumbDocument.class);\n registerClass(TLInputMediaVenue.CONSTRUCTOR_ID, TLInputMediaVenue.class);\n registerClass(TLInputMessageEntityMentionName.CONSTRUCTOR_ID, TLInputMessageEntityMentionName.class);\n registerClass(TLInputMessagesFilterChatPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterChatPhotos.class);\n registerClass(TLInputMessagesFilterDocument.CONSTRUCTOR_ID, TLInputMessagesFilterDocument.class);\n registerClass(TLInputMessagesFilterEmpty.CONSTRUCTOR_ID, TLInputMessagesFilterEmpty.class);\n registerClass(TLInputMessagesFilterGif.CONSTRUCTOR_ID, TLInputMessagesFilterGif.class);\n registerClass(TLInputMessagesFilterMusic.CONSTRUCTOR_ID, TLInputMessagesFilterMusic.class);\n registerClass(TLInputMessagesFilterPhoneCalls.CONSTRUCTOR_ID, TLInputMessagesFilterPhoneCalls.class);\n registerClass(TLInputMessagesFilterPhotoVideo.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideo.class);\n registerClass(TLInputMessagesFilterPhotoVideoDocuments.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideoDocuments.class);\n registerClass(TLInputMessagesFilterPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterPhotos.class);\n registerClass(TLInputMessagesFilterRoundVideo.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVideo.class);\n registerClass(TLInputMessagesFilterRoundVoice.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVoice.class);\n registerClass(TLInputMessagesFilterUrl.CONSTRUCTOR_ID, TLInputMessagesFilterUrl.class);\n registerClass(TLInputMessagesFilterVideo.CONSTRUCTOR_ID, TLInputMessagesFilterVideo.class);\n registerClass(TLInputMessagesFilterVoice.CONSTRUCTOR_ID, TLInputMessagesFilterVoice.class);\n registerClass(TLInputNotifyAll.CONSTRUCTOR_ID, TLInputNotifyAll.class);\n registerClass(TLInputNotifyChats.CONSTRUCTOR_ID, TLInputNotifyChats.class);\n registerClass(TLInputNotifyPeer.CONSTRUCTOR_ID, TLInputNotifyPeer.class);\n registerClass(TLInputNotifyUsers.CONSTRUCTOR_ID, TLInputNotifyUsers.class);\n registerClass(TLInputPaymentCredentials.CONSTRUCTOR_ID, TLInputPaymentCredentials.class);\n registerClass(TLInputPaymentCredentialsSaved.CONSTRUCTOR_ID, TLInputPaymentCredentialsSaved.class);\n registerClass(TLInputPeerChannel.CONSTRUCTOR_ID, TLInputPeerChannel.class);\n registerClass(TLInputPeerChat.CONSTRUCTOR_ID, TLInputPeerChat.class);\n registerClass(TLInputPeerEmpty.CONSTRUCTOR_ID, TLInputPeerEmpty.class);\n registerClass(TLInputPeerNotifyEventsAll.CONSTRUCTOR_ID, TLInputPeerNotifyEventsAll.class);\n registerClass(TLInputPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLInputPeerNotifyEventsEmpty.class);\n registerClass(TLInputPeerNotifySettings.CONSTRUCTOR_ID, TLInputPeerNotifySettings.class);\n registerClass(TLInputPeerSelf.CONSTRUCTOR_ID, TLInputPeerSelf.class);\n registerClass(TLInputPeerUser.CONSTRUCTOR_ID, TLInputPeerUser.class);\n registerClass(TLInputPhoneCall.CONSTRUCTOR_ID, TLInputPhoneCall.class);\n registerClass(TLInputPhoneContact.CONSTRUCTOR_ID, TLInputPhoneContact.class);\n registerClass(TLInputPhoto.CONSTRUCTOR_ID, TLInputPhoto.class);\n registerClass(TLInputPhotoEmpty.CONSTRUCTOR_ID, TLInputPhotoEmpty.class);\n registerClass(TLInputPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLInputPrivacyKeyChatInvite.class);\n registerClass(TLInputPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLInputPrivacyKeyPhoneCall.class);\n registerClass(TLInputPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLInputPrivacyKeyStatusTimestamp.class);\n registerClass(TLInputPrivacyValueAllowAll.CONSTRUCTOR_ID, TLInputPrivacyValueAllowAll.class);\n registerClass(TLInputPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueAllowContacts.class);\n registerClass(TLInputPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueAllowUsers.class);\n registerClass(TLInputPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowAll.class);\n registerClass(TLInputPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowContacts.class);\n registerClass(TLInputPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowUsers.class);\n registerClass(TLInputReportReasonOther.CONSTRUCTOR_ID, TLInputReportReasonOther.class);\n registerClass(TLInputReportReasonPornography.CONSTRUCTOR_ID, TLInputReportReasonPornography.class);\n registerClass(TLInputReportReasonSpam.CONSTRUCTOR_ID, TLInputReportReasonSpam.class);\n registerClass(TLInputReportReasonViolence.CONSTRUCTOR_ID, TLInputReportReasonViolence.class);\n registerClass(TLInputStickerSetEmpty.CONSTRUCTOR_ID, TLInputStickerSetEmpty.class);\n registerClass(TLInputStickerSetID.CONSTRUCTOR_ID, TLInputStickerSetID.class);\n registerClass(TLInputStickerSetShortName.CONSTRUCTOR_ID, TLInputStickerSetShortName.class);\n registerClass(TLInputStickeredMediaDocument.CONSTRUCTOR_ID, TLInputStickeredMediaDocument.class);\n registerClass(TLInputStickeredMediaPhoto.CONSTRUCTOR_ID, TLInputStickeredMediaPhoto.class);\n registerClass(TLInputUser.CONSTRUCTOR_ID, TLInputUser.class);\n registerClass(TLInputUserEmpty.CONSTRUCTOR_ID, TLInputUserEmpty.class);\n registerClass(TLInputUserSelf.CONSTRUCTOR_ID, TLInputUserSelf.class);\n registerClass(TLInputWebDocument.CONSTRUCTOR_ID, TLInputWebDocument.class);\n registerClass(TLInputWebFileLocation.CONSTRUCTOR_ID, TLInputWebFileLocation.class);\n registerClass(TLInvoice.CONSTRUCTOR_ID, TLInvoice.class);\n registerClass(TLKeyboardButton.CONSTRUCTOR_ID, TLKeyboardButton.class);\n registerClass(TLKeyboardButtonBuy.CONSTRUCTOR_ID, TLKeyboardButtonBuy.class);\n registerClass(TLKeyboardButtonCallback.CONSTRUCTOR_ID, TLKeyboardButtonCallback.class);\n registerClass(TLKeyboardButtonGame.CONSTRUCTOR_ID, TLKeyboardButtonGame.class);\n registerClass(TLKeyboardButtonRequestGeoLocation.CONSTRUCTOR_ID, TLKeyboardButtonRequestGeoLocation.class);\n registerClass(TLKeyboardButtonRequestPhone.CONSTRUCTOR_ID, TLKeyboardButtonRequestPhone.class);\n registerClass(TLKeyboardButtonRow.CONSTRUCTOR_ID, TLKeyboardButtonRow.class);\n registerClass(TLKeyboardButtonSwitchInline.CONSTRUCTOR_ID, TLKeyboardButtonSwitchInline.class);\n registerClass(TLKeyboardButtonUrl.CONSTRUCTOR_ID, TLKeyboardButtonUrl.class);\n registerClass(TLLabeledPrice.CONSTRUCTOR_ID, TLLabeledPrice.class);\n registerClass(TLMaskCoords.CONSTRUCTOR_ID, TLMaskCoords.class);\n registerClass(TLMessage.CONSTRUCTOR_ID, TLMessage.class);\n registerClass(TLMessageActionChannelCreate.CONSTRUCTOR_ID, TLMessageActionChannelCreate.class);\n registerClass(TLMessageActionChannelMigrateFrom.CONSTRUCTOR_ID, TLMessageActionChannelMigrateFrom.class);\n registerClass(TLMessageActionChatAddUser.CONSTRUCTOR_ID, TLMessageActionChatAddUser.class);\n registerClass(TLMessageActionChatCreate.CONSTRUCTOR_ID, TLMessageActionChatCreate.class);\n registerClass(TLMessageActionChatDeletePhoto.CONSTRUCTOR_ID, TLMessageActionChatDeletePhoto.class);\n registerClass(TLMessageActionChatDeleteUser.CONSTRUCTOR_ID, TLMessageActionChatDeleteUser.class);\n registerClass(TLMessageActionChatEditPhoto.CONSTRUCTOR_ID, TLMessageActionChatEditPhoto.class);\n registerClass(TLMessageActionChatEditTitle.CONSTRUCTOR_ID, TLMessageActionChatEditTitle.class);\n registerClass(TLMessageActionChatJoinedByLink.CONSTRUCTOR_ID, TLMessageActionChatJoinedByLink.class);\n registerClass(TLMessageActionChatMigrateTo.CONSTRUCTOR_ID, TLMessageActionChatMigrateTo.class);\n registerClass(TLMessageActionEmpty.CONSTRUCTOR_ID, TLMessageActionEmpty.class);\n registerClass(TLMessageActionGameScore.CONSTRUCTOR_ID, TLMessageActionGameScore.class);\n registerClass(TLMessageActionHistoryClear.CONSTRUCTOR_ID, TLMessageActionHistoryClear.class);\n registerClass(TLMessageActionPaymentSent.CONSTRUCTOR_ID, TLMessageActionPaymentSent.class);\n registerClass(TLMessageActionPaymentSentMe.CONSTRUCTOR_ID, TLMessageActionPaymentSentMe.class);\n registerClass(TLMessageActionPhoneCall.CONSTRUCTOR_ID, TLMessageActionPhoneCall.class);\n registerClass(TLMessageActionPinMessage.CONSTRUCTOR_ID, TLMessageActionPinMessage.class);\n registerClass(TLMessageEmpty.CONSTRUCTOR_ID, TLMessageEmpty.class);\n registerClass(TLMessageEntityBold.CONSTRUCTOR_ID, TLMessageEntityBold.class);\n registerClass(TLMessageEntityBotCommand.CONSTRUCTOR_ID, TLMessageEntityBotCommand.class);\n registerClass(TLMessageEntityCode.CONSTRUCTOR_ID, TLMessageEntityCode.class);\n registerClass(TLMessageEntityEmail.CONSTRUCTOR_ID, TLMessageEntityEmail.class);\n registerClass(TLMessageEntityHashtag.CONSTRUCTOR_ID, TLMessageEntityHashtag.class);\n registerClass(TLMessageEntityItalic.CONSTRUCTOR_ID, TLMessageEntityItalic.class);\n registerClass(TLMessageEntityMention.CONSTRUCTOR_ID, TLMessageEntityMention.class);\n registerClass(TLMessageEntityMentionName.CONSTRUCTOR_ID, TLMessageEntityMentionName.class);\n registerClass(TLMessageEntityPre.CONSTRUCTOR_ID, TLMessageEntityPre.class);\n registerClass(TLMessageEntityTextUrl.CONSTRUCTOR_ID, TLMessageEntityTextUrl.class);\n registerClass(TLMessageEntityUnknown.CONSTRUCTOR_ID, TLMessageEntityUnknown.class);\n registerClass(TLMessageEntityUrl.CONSTRUCTOR_ID, TLMessageEntityUrl.class);\n registerClass(TLMessageFwdHeader.CONSTRUCTOR_ID, TLMessageFwdHeader.class);\n registerClass(TLMessageMediaContact.CONSTRUCTOR_ID, TLMessageMediaContact.class);\n registerClass(TLMessageMediaDocument.CONSTRUCTOR_ID, TLMessageMediaDocument.class);\n registerClass(", "post_mask_code": "\n registerClass(TLMessageMediaGame.CONSTRUCTOR_ID, TLMessageMediaGame.class);\n registerClass(TLMessageMediaGeo.CONSTRUCTOR_ID, TLMessageMediaGeo.class);\n registerClass(TLMessageMediaInvoice.CONSTRUCTOR_ID, TLMessageMediaInvoice.class);\n registerClass(TLMessageMediaPhoto.CONSTRUCTOR_ID, TLMessageMediaPhoto.class);\n registerClass(TLMessageMediaUnsupported.CONSTRUCTOR_ID, TLMessageMediaUnsupported.class);\n registerClass(TLMessageMediaVenue.CONSTRUCTOR_ID, TLMessageMediaVenue.class);\n registerClass(TLMessageMediaWebPage.CONSTRUCTOR_ID, TLMessageMediaWebPage.class);\n registerClass(TLMessageRange.CONSTRUCTOR_ID, TLMessageRange.class);\n registerClass(TLMessageService.CONSTRUCTOR_ID, TLMessageService.class);\n registerClass(TLAffectedHistory.CONSTRUCTOR_ID, TLAffectedHistory.class);\n registerClass(TLAffectedMessages.CONSTRUCTOR_ID, TLAffectedMessages.class);\n registerClass(TLAllStickers.CONSTRUCTOR_ID, TLAllStickers.class);\n registerClass(TLAllStickersNotModified.CONSTRUCTOR_ID, TLAllStickersNotModified.class);\n registerClass(TLArchivedStickers.CONSTRUCTOR_ID, TLArchivedStickers.class);\n registerClass(TLBotCallbackAnswer.CONSTRUCTOR_ID, TLBotCallbackAnswer.class);\n registerClass(TLBotResults.CONSTRUCTOR_ID, TLBotResults.class);\n registerClass(TLChannelMessages.CONSTRUCTOR_ID, TLChannelMessages.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLChatFull.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLChatFull.class);\n registerClass(TLChats.CONSTRUCTOR_ID, TLChats.class);\n registerClass(TLChatsSlice.CONSTRUCTOR_ID, TLChatsSlice.class);\n registerClass(TLDhConfig.CONSTRUCTOR_ID, TLDhConfig.class);\n registerClass(TLDhConfigNotModified.CONSTRUCTOR_ID, TLDhConfigNotModified.class);\n registerClass(TLDialogs.CONSTRUCTOR_ID, TLDialogs.class);\n registerClass(TLDialogsSlice.CONSTRUCTOR_ID, TLDialogsSlice.class);\n registerClass(TLFeaturedStickers.CONSTRUCTOR_ID, TLFeaturedStickers.class);\n registerClass(TLFeaturedStickersNotModified.CONSTRUCTOR_ID, TLFeaturedStickersNotModified.class);\n registerClass(TLFoundGifs.CONSTRUCTOR_ID, TLFoundGifs.class);\n registerClass(TLHighScores.CONSTRUCTOR_ID, TLHighScores.class);\n registerClass(TLMessageEditData.CONSTRUCTOR_ID, TLMessageEditData.class);\n registerClass(TLMessages.CONSTRUCTOR_ID, TLMessages.class);\n registerClass(TLMessagesSlice.CONSTRUCTOR_ID, TLMessagesSlice.class);\n registerClass(TLPeerDialogs.CONSTRUCTOR_ID, TLPeerDialogs.class);\n registerClass(TLRecentStickers.CONSTRUCTOR_ID, TLRecentStickers.class);\n registerClass(TLRecentStickersNotModified.CONSTRUCTOR_ID, TLRecentStickersNotModified.class);\n registerClass(TLSavedGifs.CONSTRUCTOR_ID, TLSavedGifs.class);\n registerClass(TLSavedGifsNotModified.CONSTRUCTOR_ID, TLSavedGifsNotModified.class);\n registerClass(TLSentEncryptedFile.CONSTRUCTOR_ID, TLSentEncryptedFile.class);\n registerClass(TLSentEncryptedMessage.CONSTRUCTOR_ID, TLSentEncryptedMessage.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLStickerSet.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLStickerSet.class);\n registerClass(TLStickerSetInstallResultArchive.CONSTRUCTOR_ID, TLStickerSetInstallResultArchive.class);\n registerClass(TLStickerSetInstallResultSuccess.CONSTRUCTOR_ID, TLStickerSetInstallResultSuccess.class);\n registerClass(TLStickers.CONSTRUCTOR_ID, TLStickers.class);\n registerClass(TLStickersNotModified.CONSTRUCTOR_ID, TLStickersNotModified.class);\n registerClass(TLNearestDc.CONSTRUCTOR_ID, TLNearestDc.class);\n registerClass(TLNotifyAll.CONSTRUCTOR_ID, TLNotifyAll.class);\n registerClass(TLNotifyChats.CONSTRUCTOR_ID, TLNotifyChats.class);\n registerClass(TLNotifyPeer.CONSTRUCTOR_ID, TLNotifyPeer.class);\n registerClass(TLNotifyUsers.CONSTRUCTOR_ID, TLNotifyUsers.class);\n registerClass(TLPageBlockAnchor.CONSTRUCTOR_ID, TLPageBlockAnchor.class);\n registerClass(TLPageBlockAuthorDate.CONSTRUCTOR_ID, TLPageBlockAuthorDate.class);\n registerClass(TLPageBlockBlockquote.CONSTRUCTOR_ID, TLPageBlockBlockquote.class);\n registerClass(TLPageBlockChannel.CONSTRUCTOR_ID, TLPageBlockChannel.class);\n registerClass(TLPageBlockCollage.CONSTRUCTOR_ID, TLPageBlockCollage.class);\n registerClass(TLPageBlockCover.CONSTRUCTOR_ID, TLPageBlockCover.class);\n registerClass(TLPageBlockDivider.CONSTRUCTOR_ID, TLPageBlockDivider.class);\n registerClass(TLPageBlockEmbed.CONSTRUCTOR_ID, TLPageBlockEmbed.class);\n registerClass(TLPageBlockEmbedPost.CONSTRUCTOR_ID, TLPageBlockEmbedPost.class);\n registerClass(TLPageBlockFooter.CONSTRUCTOR_ID, TLPageBlockFooter.class);\n registerClass(TLPageBlockHeader.CONSTRUCTOR_ID, TLPageBlockHeader.class);\n registerClass(TLPageBlockList.CONSTRUCTOR_ID, TLPageBlockList.class);\n registerClass(TLPageBlockParagraph.CONSTRUCTOR_ID, TLPageBlockParagraph.class);\n registerClass(TLPageBlockPhoto.CONSTRUCTOR_ID, TLPageBlockPhoto.class);\n registerClass(TLPageBlockPreformatted.CONSTRUCTOR_ID, TLPageBlockPreformatted.class);\n registerClass(TLPageBlockPullquote.CONSTRUCTOR_ID, TLPageBlockPullquote.class);\n registerClass(TLPageBlockSlideshow.CONSTRUCTOR_ID, TLPageBlockSlideshow.class);\n registerClass(TLPageBlockSubheader.CONSTRUCTOR_ID, TLPageBlockSubheader.class);\n registerClass(TLPageBlockSubtitle.CONSTRUCTOR_ID, TLPageBlockSubtitle.class);\n registerClass(TLPageBlockTitle.CONSTRUCTOR_ID, TLPageBlockTitle.class);\n registerClass(TLPageBlockUnsupported.CONSTRUCTOR_ID, TLPageBlockUnsupported.class);\n registerClass(TLPageBlockVideo.CONSTRUCTOR_ID, TLPageBlockVideo.class);\n registerClass(TLPageFull.CONSTRUCTOR_ID, TLPageFull.class);\n registerClass(TLPagePart.CONSTRUCTOR_ID, TLPagePart.class);\n registerClass(TLPaymentCharge.CONSTRUCTOR_ID, TLPaymentCharge.class);\n registerClass(TLPaymentRequestedInfo.CONSTRUCTOR_ID, TLPaymentRequestedInfo.class);\n registerClass(TLPaymentSavedCredentialsCard.CONSTRUCTOR_ID, TLPaymentSavedCredentialsCard.class);\n registerClass(TLPaymentForm.CONSTRUCTOR_ID, TLPaymentForm.class);\n registerClass(TLPaymentReceipt.CONSTRUCTOR_ID, TLPaymentReceipt.class);\n registerClass(TLPaymentResult.CONSTRUCTOR_ID, TLPaymentResult.class);\n registerClass(TLPaymentVerficationNeeded.CONSTRUCTOR_ID, TLPaymentVerficationNeeded.class);\n registerClass(TLSavedInfo.CONSTRUCTOR_ID, TLSavedInfo.class);\n registerClass(TLValidatedRequestedInfo.CONSTRUCTOR_ID, TLValidatedRequestedInfo.class);\n registerClass(TLPeerChannel.CONSTRUCTOR_ID, TLPeerChannel.class);\n registerClass(TLPeerChat.CONSTRUCTOR_ID, TLPeerChat.class);\n registerClass(TLPeerNotifyEventsAll.CONSTRUCTOR_ID, TLPeerNotifyEventsAll.class);\n registerClass(TLPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLPeerNotifyEventsEmpty.class);\n registerClass(TLPeerNotifySettings.CONSTRUCTOR_ID, TLPeerNotifySettings.class);\n registerClass(TLPeerNotifySettingsEmpty.CONSTRUCTOR_ID, TLPeerNotifySettingsEmpty.class);\n registerClass(TLPeerSettings.CONSTRUCTOR_ID, TLPeerSettings.class);\n registerClass(TLPeerUser.CONSTRUCTOR_ID, TLPeerUser.class);\n registerClass(com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.class);\n registerClass(TLPhoneCall.CONSTRUCTOR_ID, TLPhoneCall.class);\n registerClass(TLPhoneCallAccepted.CONSTRUCTOR_ID, TLPhoneCallAccepted.class);\n registerClass(TLPhoneCallDiscardReasonBusy.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonBusy.class);\n registerClass(TLPhoneCallDiscardReasonDisconnect.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonDisconnect.class);\n registerClass(TLPhoneCallDiscardReasonHangup.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonHangup.class);\n registerClass(TLPhoneCallDiscardReasonMissed.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonMissed.class);\n registerClass(TLPhoneCallDiscarded.CONSTRUCTOR_ID, TLPhoneCallDiscarded.class);\n registerClass(TLPhoneCallEmpty.CONSTRUCTOR_ID, TLPhoneCallEmpty.class);\n registerClass(TLPhoneCallProtocol.CONSTRUCTOR_ID, TLPhoneCallProtocol.class);\n registerClass(TLPhoneCallRequested.CONSTRUCTOR_ID, TLPhoneCallRequested.class);\n registerClass(TLPhoneCallWaiting.CONSTRUCTOR_ID, TLPhoneCallWaiting.class);\n registerClass(TLPhoneConnection.CONSTRUCTOR_ID, TLPhoneConnection.class);\n registerClass(TLPhoto.CONSTRUCTOR_ID, TLPhoto.class);\n registerClass(TLPhotoCachedSize.CONSTRUCTOR_ID, TLPhotoCachedSize.class);\n registerClass(TLPhotoEmpty.CONSTRUCTOR_ID, TLPhotoEmpty.class);\n registerClass(TLPhotoSize.CONSTRUCTOR_ID, TLPhotoSize.class);\n registerClass(TLPhotoSizeEmpty.CONSTRUCTOR_ID, TLPhotoSizeEmpty.class);\n registerClass(com.github.badoualy.telegram.tl.api.photos.TLPhoto.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.photos.TLPhoto.class);\n registerClass(TLPhotos.CONSTRUCTOR_ID, TLPhotos.class);\n registerClass(TLPhotosSlice.CONSTRUCTOR_ID, TLPhotosSlice.class);\n registerClass(TLPostAddress.CONSTRUCTOR_ID, TLPostAddress.class);\n registerClass(TLPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLPrivacyKeyChatInvite.class);\n registerClass(TLPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLPrivacyKeyPhoneCall.class);\n registerClass(TLPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLPrivacyKeyStatusTimestamp.class);\n registerClass(TLPrivacyValueAllowAll.CONSTRUCTOR_ID, TLPrivacyValueAllowAll.class);\n registerClass(TLPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLPrivacyValueAllowContacts.class);\n registerClass(TLPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLPrivacyValueAllowUsers.class);\n registerClass(TLPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLPrivacyValueDisallowAll.class);\n registerClass(TLPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLPrivacyValueDisallowContacts.class);\n registerClass(TLPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLPrivacyValueDisallowUsers.class);\n registerClass(TLReceivedNotifyMessage.CONSTRUCTOR_ID, TLReceivedNotifyMessage.class);\n registerClass(TLReplyInlineMarkup.CONSTRUCTOR_ID, TLReplyInlineMarkup.class);\n registerClass(TLReplyKeyboardForceReply.CONSTRUCTOR_ID, TLReplyKeyboardForceReply.class);\n registerClass(TLReplyKeyboardHide.CONSTRUCTOR_ID, TLReplyKeyboardHide.class);\n registerClass(TLReplyKeyboardMarkup.CONSTRUCTOR_ID, TLReplyKeyboardMarkup.class);\n registerClass(TLSendMessageCancelAction.CONSTRUCTOR_ID, TLSendMessageCancelAction.class);\n registerClass(TLSendMessageChooseContactAction.CONSTRUCTOR_ID, TLSendMessageChooseContactAction.class);\n registerClass(TLSendMessageGamePlayAction.CONSTRUCTOR_ID, TLSendMessageGamePlayAction.class);\n registerClass(TLSendMessageGeoLocationAction.CONSTRUCTOR_ID, TLSendMessageGeoLocationAction.class);\n registerClass(TLSendMessageRecordAudioAction.CONSTRUCTOR_ID, TLSendMessageRecordAudioAction.class);\n registerClass(TLSendMessageRecordRoundAction.CONSTRUCTOR_ID, TLSendMessageRecordRoundAction.class);\n registerClass(TLSendMessageRecordVideoAction.CONSTRUCTOR_ID, TLSendMessageRecordVideoAction.class);\n registerClass(TLSendMessageTypingAction.CONSTRUCTOR_ID, TLSendMessageTypingAction.class);\n registerClass(TLSendMessageUploadAudioAction.CONSTRUCTOR_ID, TLSendMessageUploadAudioAction.class);\n registerClass(TLSendMessageUploadDocumentAction.CONSTRUCTOR_ID, TLSendMessageUploadDocumentAction.class);\n registerClass(TLSendMessageUploadPhotoAction.CONSTRUCTOR_ID, TLSendMessageUploadPhotoAction.class);\n registerClass(TLSendMessageUploadRoundAction.CONSTRUCTOR_ID, TLSendMessageUploadRoundAction.class);\n registerClass(TLSendMessageUploadVideoAction.CONSTRUCTOR_ID, TLSendMessageUploadVideoAction.class);\n registerClass(TLShippingOption.CONSTRUCTOR_ID, TLShippingOption.class);\n registerClass(TLStickerPack.CONSTRUCTOR_ID, TLStickerPack.class);\n registerClass(TLStickerSet.CONSTRUCTOR_ID, TLStickerSet.class);\n registerClass(TLStickerSetCovered.CONSTRUCTOR_ID, TLStickerSetCovered.class);\n registerClass(TLStickerSetMultiCovered.CONSTRUCTOR_ID, TLStickerSetMultiCovered.class);\n registerClass(TLFileGif.CONSTRUCTOR_ID, TLFileGif.class);\n registerClass(TLFileJpeg.CONSTRUCTOR_ID, TLFileJpeg.class);\n registerClass(TLFileMov.CONSTRUCTOR_ID, TLFileMov.class);\n registerClass(TLFileMp3.CONSTRUCTOR_ID, TLFileMp3.class);\n registerClass(TLFileMp4.CONSTRUCTOR_ID, TLFileMp4.class);\n registerClass(TLFilePartial.CONSTRUCTOR_ID, TLFilePartial.class);\n registerClass(TLFilePdf.CONSTRUCTOR_ID, TLFilePdf.class);\n registerClass(TLFilePng.CONSTRUCTOR_ID, TLFilePng.class);\n registerClass(TLFileUnknown.CONSTRUCTOR_ID, TLFileUnknown.class);\n registerClass(TLFileWebp.CONSTRUCTOR_ID, TLFileWebp.class);\n registerClass(TLTextBold.CONSTRUCTOR_ID, TLTextBold.class);\n registerClass(TLTextConcat.CONSTRUCTOR_ID, TLTextConcat.class);\n registerClass(TLTextEmail.CONSTRUCTOR_ID, TLTextEmail.class);\n registerClass(TLTextEmpty.CONSTRUCTOR_ID, TLTextEmpty.class);\n registerClass(TLTextFixed.CONSTRUCTOR_ID, TLTextFixed.class);\n registerClass(TLTextItalic.CONSTRUCTOR_ID, TLTextItalic.class);\n registerClass(TLTextPlain.CONSTRUCTOR_ID, TLTextPlain.class);\n registerClass(TLTextStrike.CONSTRUCTOR_ID, TLTextStrike.class);\n registerClass(TLTextUnderline.CONSTRUCTOR_ID, TLTextUnderline.class);\n registerClass(TLTextUrl.CONSTRUCTOR_ID, TLTextUrl.class);\n registerClass(TLTopPeer.CONSTRUCTOR_ID, TLTopPeer.class);\n registerClass(TLTopPeerCategoryBotsInline.CONSTRUCTOR_ID, TLTopPeerCategoryBotsInline.class);\n registerClass(TLTopPeerCategoryBotsPM.CONSTRUCTOR_ID, TLTopPeerCategoryBotsPM.class);\n registerClass(TLTopPeerCategoryChannels.CONSTRUCTOR_ID, TLTopPeerCategoryChannels.class);\n registerClass(TLTopPeerCategoryCorrespondents.CONSTRUCTOR_ID, TLTopPeerCategoryCorrespondents.class);\n registerClass(TLTopPeerCategoryGroups.CONSTRUCTOR_ID, TLTopPeerCategoryGroups.class);\n registerClass(TLTopPeerCategoryPeers.CONSTRUCTOR_ID, TLTopPeerCategoryPeers.class);\n registerClass(TLUpdateBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateBotCallbackQuery.class);\n registerClass(TLUpdateBotInlineQuery.CONSTRUCTOR_ID, TLUpdateBotInlineQuery.class);\n registerClass(TLUpdateBotInlineSend.CONSTRUCTOR_ID, TLUpdateBotInlineSend.class);\n registerClass(TLUpdateBotPrecheckoutQuery.CONSTRUCTOR_ID, TLUpdateBotPrecheckoutQuery.class);\n registerClass(TLUpdateBotShippingQuery.CONSTRUCTOR_ID, TLUpdateBotShippingQuery.class);\n registerClass(TLUpdateBotWebhookJSON.CONSTRUCTOR_ID, TLUpdateBotWebhookJSON.class);\n registerClass(TLUpdateBotWebhookJSONQuery.CONSTRUCTOR_ID, TLUpdateBotWebhookJSONQuery.class);\n registerClass(TLUpdateChannel.CONSTRUCTOR_ID, TLUpdateChannel.class);\n registerClass(TLUpdateChannelMessageViews.CONSTRUCTOR_ID, TLUpdateChannelMessageViews.class);\n registerClass(TLUpdateChannelPinnedMessage.CONSTRUCTOR_ID, TLUpdateChannelPinnedMessage.class);\n registerClass(TLUpdateChannelTooLong.CONSTRUCTOR_ID, TLUpdateChannelTooLong.class);\n registerClass(TLUpdateChannelWebPage.CONSTRUCTOR_ID, TLUpdateChannelWebPage.class);\n registerClass(TLUpdateChatAdmins.CONSTRUCTOR_ID, TLUpdateChatAdmins.class);\n registerClass(TLUpdateChatParticipantAdd.CONSTRUCTOR_ID, TLUpdateChatParticipantAdd.class);\n registerClass(TLUpdateChatParticipantAdmin.CONSTRUCTOR_ID, TLUpdateChatParticipantAdmin.class);\n registerClass(TLUpdateChatParticipantDelete.CONSTRUCTOR_ID, TLUpdateChatParticipantDelete.class);\n registerClass(TLUpdateChatParticipants.CONSTRUCTOR_ID, TLUpdateChatParticipants.class);\n registerClass(TLUpdateChatUserTyping.CONSTRUCTOR_ID, TLUpdateChatUserTyping.class);\n registerClass(TLUpdateConfig.CONSTRUCTOR_ID, TLUpdateConfig.class);\n registerClass(TLUpdateContactLink.CONSTRUCTOR_ID, TLUpdateContactLink.class);\n registerClass(TLUpdateContactRegistered.CONSTRUCTOR_ID, TLUpdateContactRegistered.class);\n registerClass(TLUpdateDcOptions.CONSTRUCTOR_ID, TLUpdateDcOptions.class);\n registerClass(TLUpdateDeleteChannelMessages.CONSTRUCTOR_ID, TLUpdateDeleteChannelMessages.class);\n registerClass(TLUpdateDeleteMessages.CONSTRUCTOR_ID, TLUpdateDeleteMessages.class);\n registerClass(TLUpdateDialogPinned.CONSTRUCTOR_ID, TLUpdateDialogPinned.class);\n registerClass(TLUpdateDraftMessage.CONSTRUCTOR_ID, TLUpdateDraftMessage.class);\n registerClass(TLUpdateEditChannelMessage.CONSTRUCTOR_ID, TLUpdateEditChannelMessage.class);\n registerClass(TLUpdateEditMessage.CONSTRUCTOR_ID, TLUpdateEditMessage.class);\n registerClass(TLUpdateEncryptedChatTyping.CONSTRUCTOR_ID, TLUpdateEncryptedChatTyping.class);\n registerClass(TLUpdateEncryptedMessagesRead.CONSTRUCTOR_ID, TLUpdateEncryptedMessagesRead.class);\n registerClass(TLUpdateEncryption.CONSTRUCTOR_ID, TLUpdateEncryption.class);\n registerClass(TLUpdateInlineBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateInlineBotCallbackQuery.class);\n registerClass(TLUpdateMessageID.CONSTRUCTOR_ID, TLUpdateMessageID.class);\n registerClass(TLUpdateNewChannelMessage.CONSTRUCTOR_ID, TLUpdateNewChannelMessage.class);\n registerClass(TLUpdateNewEncryptedMessage.CONSTRUCTOR_ID, TLUpdateNewEncryptedMessage.class);\n registerClass(TLUpdateNewMessage.CONSTRUCTOR_ID, TLUpdateNewMessage.class);\n registerClass(TLUpdateNewStickerSet.CONSTRUCTOR_ID, TLUpdateNewStickerSet.class);\n registerClass(TLUpdateNotifySettings.CONSTRUCTOR_ID, TLUpdateNotifySettings.class);\n registerClass(TLUpdatePhoneCall.CONSTRUCTOR_ID, TLUpdatePhoneCall.class);\n registerClass(TLUpdatePinnedDialogs.CONSTRUCTOR_ID, TLUpdatePinnedDialogs.class);\n registerClass(TLUpdatePrivacy.CONSTRUCTOR_ID, TLUpdatePrivacy.class);\n registerClass(TLUpdatePtsChanged.CONSTRUCTOR_ID, TLUpdatePtsChanged.class);\n registerClass(TLUpdateReadChannelInbox.CONSTRUCTOR_ID, TLUpdateReadChannelInbox.class);\n registerClass(TLUpdateReadChannelOutbox.CONSTRUCTOR_ID, TLUpdateReadChannelOutbox.class);\n registerClass(TLUpdateReadFeaturedStickers.CONSTRUCTOR_ID, TLUpdateReadFeaturedStickers.class);\n registerClass(TLUpdateReadHistoryInbox.CONSTRUCTOR_ID, TLUpdateReadHistoryInbox.class);\n registerClass(TLUpdateReadHistoryOutbox.CONSTRUCTOR_ID, TLUpdateReadHistoryOutbox.class);\n registerClass(TLUpdateReadMessagesContents.CONSTRUCTOR_ID, TLUpdateReadMessagesContents.class);\n registerClass(TLUpdateRecentStickers.CONSTRUCTOR_ID, TLUpdateRecentStickers.class);\n registerClass(TLUpdateSavedGifs.CONSTRUCTOR_ID, TLUpdateSavedGifs.class);\n registerClass(TLUpdateServiceNotification.CONSTRUCTOR_ID, TLUpdateServiceNotification.class);\n registerClass(TLUpdateShort.CONSTRUCTOR_ID, TLUpdateShort.class);\n registerClass(TLUpdateShortChatMessage.CONSTRUCTOR_ID, TLUpdateShortChatMessage.class);\n registerClass(TLUpdateShortMessage.CONSTRUCTOR_ID, TLUpdateShortMessage.class);\n registerClass(TLUpdateShortSentMessage.CONSTRUCTOR_ID, TLUpdateShortSentMessage.class);\n registerClass(TLUpdateStickerSets.CONSTRUCTOR_ID, TLUpdateStickerSets.class);\n registerClass(TLUpdateStickerSetsOrder.CONSTRUCTOR_ID, TLUpdateStickerSetsOrder.class);\n registerClass(TLUpdateUserBlocked.CONSTRUCTOR_ID, TLUpdateUserBlocked.class);\n registerClass(TLUpdateUserName.CONSTRUCTOR_ID, TLUpdateUserName.class);\n registerClass(TLUpdateUserPhone.CONSTRUCTOR_ID, TLUpdateUserPhone.class);\n registerClass(TLUpdateUserPhoto.CONSTRUCTOR_ID, TLUpdateUserPhoto.class);\n registerClass(TLUpdateUserStatus.CONSTRUCTOR_ID, TLUpdateUserStatus.class);\n registerClass(TLUpdateUserTyping.CONSTRUCTOR_ID, TLUpdateUserTyping.class);\n registerClass(TLUpdateWebPage.CONSTRUCTOR_ID, TLUpdateWebPage.class);\n registerClass(TLUpdates.CONSTRUCTOR_ID, TLUpdates.class);\n registerClass(TLChannelDifference.CONSTRUCTOR_ID, TLChannelDifference.class);\n registerClass(TLChannelDifferenceEmpty.CONSTRUCTOR_ID, TLChannelDifferenceEmpty.class);\n registerClass(TLChannelDifferenceTooLong.CONSTRUCTOR_ID, TLChannelDifferenceTooLong.class);\n registerClass(TLDifference.CONSTRUCTOR_ID, TLDifference.class);\n registerClass(TLDifferenceEmpty.CONSTRUCTOR_ID, TLDifferenceEmpty.class);\n registerClass(TLDifferenceSlice.CONSTRUCTOR_ID, TLDifferenceSlice.class);\n registerClass(TLDifferenceTooLong.CONSTRUCTOR_ID, TLDifferenceTooLong.class);\n registerClass(TLState.CONSTRUCTOR_ID, TLState.class);\n registerClass(TLUpdatesCombined.CONSTRUCTOR_ID, TLUpdatesCombined.class);\n registerClass(TLUpdatesTooLong.CONSTRUCTOR_ID, TLUpdatesTooLong.class);\n registerClass(TLCdnFile.CONSTRUCTOR_ID, TLCdnFile.class);\n registerClass(TLCdnFileReuploadNeeded.CONSTRUCTOR_ID, TLCdnFileReuploadNeeded.class);\n registerClass(TLFile.CONSTRUCTOR_ID, TLFile.class);\n registerClass(TLFileCdnRedirect.CONSTRUCTOR_ID, TLFileCdnRedirect.class);\n registerClass(TLWebFile.CONSTRUCTOR_ID, TLWebFile.class);\n registerClass(TLUser.CONSTRUCTOR_ID, TLUser.class);\n registerClass(TLUserEmpty.CONSTRUCTOR_ID, TLUserEmpty.class);\n registerClass(TLUserFull.CONSTRUCTOR_ID, TLUserFull.class);\n registerClass(TLUserProfilePhoto.CONSTRUCTOR_ID, TLUserProfilePhoto.class);\n registerClass(TLUserProfilePhotoEmpty.CONSTRUCTOR_ID, TLUserProfilePhotoEmpty.class);\n registerClass(TLUserStatusEmpty.CONSTRUCTOR_ID, TLUserStatusEmpty.class);\n registerClass(TLUserStatusLastMonth.CONSTRUCTOR_ID, TLUserStatusLastMonth.class);\n registerClass(TLUserStatusLastWeek.CONSTRUCTOR_ID, TLUserStatusLastWeek.class);\n registerClass(TLUserStatusOffline.CONSTRUCTOR_ID, TLUserStatusOffline.class);\n registerClass(TLUserStatusOnline.CONSTRUCTOR_ID, TLUserStatusOnline.class);\n registerClass(TLUserStatusRecently.CONSTRUCTOR_ID, TLUserStatusRecently.class);\n registerClass(TLWallPaper.CONSTRUCTOR_ID, TLWallPaper.class);\n registerClass(TLWallPaperSolid.CONSTRUCTOR_ID, TLWallPaperSolid.class);\n registerClass(TLWebDocument.CONSTRUCTOR_ID, TLWebDocument.class);\n registerClass(TLWebPage.CONSTRUCTOR_ID, TLWebPage.class);\n registerClass(TLWebPageEmpty.CONSTRUCTOR_ID, TLWebPageEmpty.class);\n registerClass(TLWebPageNotModified.CONSTRUCTOR_ID, TLWebPageNotModified.class);\n registerClass(TLWebPagePending.CONSTRUCTOR_ID, TLWebPagePending.class);\n }\n}\n"} {"task_id": "Java_105", "language": "Java", "task_type": "if_statement", "source_file": "java/github/badoualy/kotlogram/tl/src/main/java/com/github/badoualy/telegram/tl/api/TLApiContext.java", "mask_start_position": 7058, "mask_end_position": 7134, "canonical_solution": "if (instance == null) {\n instance = new TLApiContext();\n }", "pre_mask_code": "package com.github.badoualy.telegram.tl.api;\n\nimport com.github.badoualy.telegram.tl.TLContext;\nimport com.github.badoualy.telegram.tl.api.account.TLAuthorizations;\nimport com.github.badoualy.telegram.tl.api.account.TLNoPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordInputSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPrivacyRules;\nimport com.github.badoualy.telegram.tl.api.account.TLTmpPassword;\nimport com.github.badoualy.telegram.tl.api.auth.TLCheckedPhone;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.auth.TLExportedAuthorization;\nimport com.github.badoualy.telegram.tl.api.auth.TLPasswordRecovery;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCode;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeApp;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.channels.TLChannelParticipants;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlocked;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlockedSlice;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContactsNotModified;\nimport com.github.badoualy.telegram.tl.api.contacts.TLFound;\nimport com.github.badoualy.telegram.tl.api.contacts.TLImportedContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLLink;\nimport com.github.badoualy.telegram.tl.api.contacts.TLResolvedPeer;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeers;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeersNotModified;\nimport com.github.badoualy.telegram.tl.api.help.TLAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLInviteText;\nimport com.github.badoualy.telegram.tl.api.help.TLNoAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLSupport;\nimport com.github.badoualy.telegram.tl.api.help.TLTermsOfService;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedHistory;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLArchivedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotCallbackAnswer;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotResults;\nimport com.github.badoualy.telegram.tl.api.messages.TLChannelMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLChats;\nimport com.github.badoualy.telegram.tl.api.messages.TLChatsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfig;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfigNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLFoundGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLHighScores;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessageEditData;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessagesSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLPeerDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifsNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedFile;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedMessage;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultArchive;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultSuccess;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentForm;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentReceipt;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentResult;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentVerficationNeeded;\nimport com.github.badoualy.telegram.tl.api.payments.TLSavedInfo;\nimport com.github.badoualy.telegram.tl.api.payments.TLValidatedRequestedInfo;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotos;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotosSlice;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileGif;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileJpeg;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMov;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp3;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp4;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePartial;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePdf;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePng;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileUnknown;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileWebp;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceSlice;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLState;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFileReuploadNeeded;\nimport com.github.badoualy.telegram.tl.api.upload.TLFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLFileCdnRedirect;\nimport com.github.badoualy.telegram.tl.api.upload.TLWebFile;\n\n/**\n * @author Yannick Badoual example@nnthink.com\n * @see http://example.com\n */\n@SuppressWarnings(\"unused\")\npublic class TLApiContext extends TLContext {\n\n private static TLApiContext instance;\n\n public TLApiContext() {\n super(543);\n }\n\n public static TLApiContext getInstance() {\n ", "post_mask_code": "\n return instance;\n }\n\n @Override\n public void init() {\n registerClass(TLAuthorizations.CONSTRUCTOR_ID, TLAuthorizations.class);\n registerClass(TLNoPassword.CONSTRUCTOR_ID, TLNoPassword.class);\n registerClass(TLPassword.CONSTRUCTOR_ID, TLPassword.class);\n registerClass(TLPasswordInputSettings.CONSTRUCTOR_ID, TLPasswordInputSettings.class);\n registerClass(TLPasswordSettings.CONSTRUCTOR_ID, TLPasswordSettings.class);\n registerClass(TLPrivacyRules.CONSTRUCTOR_ID, TLPrivacyRules.class);\n registerClass(TLTmpPassword.CONSTRUCTOR_ID, TLTmpPassword.class);\n registerClass(TLAccountDaysTTL.CONSTRUCTOR_ID, TLAccountDaysTTL.class);\n registerClass(com.github.badoualy.telegram.tl.api.auth.TLAuthorization.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.auth.TLAuthorization.class);\n registerClass(TLCheckedPhone.CONSTRUCTOR_ID, TLCheckedPhone.class);\n registerClass(TLCodeTypeCall.CONSTRUCTOR_ID, TLCodeTypeCall.class);\n registerClass(TLCodeTypeFlashCall.CONSTRUCTOR_ID, TLCodeTypeFlashCall.class);\n registerClass(TLCodeTypeSms.CONSTRUCTOR_ID, TLCodeTypeSms.class);\n registerClass(TLExportedAuthorization.CONSTRUCTOR_ID, TLExportedAuthorization.class);\n registerClass(TLPasswordRecovery.CONSTRUCTOR_ID, TLPasswordRecovery.class);\n registerClass(TLSentCode.CONSTRUCTOR_ID, TLSentCode.class);\n registerClass(TLSentCodeTypeApp.CONSTRUCTOR_ID, TLSentCodeTypeApp.class);\n registerClass(TLSentCodeTypeCall.CONSTRUCTOR_ID, TLSentCodeTypeCall.class);\n registerClass(TLSentCodeTypeFlashCall.CONSTRUCTOR_ID, TLSentCodeTypeFlashCall.class);\n registerClass(TLSentCodeTypeSms.CONSTRUCTOR_ID, TLSentCodeTypeSms.class);\n registerClass(TLAuthorization.CONSTRUCTOR_ID, TLAuthorization.class);\n registerClass(TLBotCommand.CONSTRUCTOR_ID, TLBotCommand.class);\n registerClass(TLBotInfo.CONSTRUCTOR_ID, TLBotInfo.class);\n registerClass(TLBotInlineMediaResult.CONSTRUCTOR_ID, TLBotInlineMediaResult.class);\n registerClass(TLBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLBotInlineMessageMediaAuto.class);\n registerClass(TLBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLBotInlineMessageMediaContact.class);\n registerClass(TLBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLBotInlineMessageMediaGeo.class);\n registerClass(TLBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLBotInlineMessageMediaVenue.class);\n registerClass(TLBotInlineMessageText.CONSTRUCTOR_ID, TLBotInlineMessageText.class);\n registerClass(TLBotInlineResult.CONSTRUCTOR_ID, TLBotInlineResult.class);\n registerClass(TLCdnConfig.CONSTRUCTOR_ID, TLCdnConfig.class);\n registerClass(TLCdnPublicKey.CONSTRUCTOR_ID, TLCdnPublicKey.class);\n registerClass(TLChannel.CONSTRUCTOR_ID, TLChannel.class);\n registerClass(TLChannelForbidden.CONSTRUCTOR_ID, TLChannelForbidden.class);\n registerClass(TLChannelFull.CONSTRUCTOR_ID, TLChannelFull.class);\n registerClass(TLChannelMessagesFilter.CONSTRUCTOR_ID, TLChannelMessagesFilter.class);\n registerClass(TLChannelMessagesFilterEmpty.CONSTRUCTOR_ID, TLChannelMessagesFilterEmpty.class);\n registerClass(TLChannelParticipant.CONSTRUCTOR_ID, TLChannelParticipant.class);\n registerClass(TLChannelParticipantCreator.CONSTRUCTOR_ID, TLChannelParticipantCreator.class);\n registerClass(TLChannelParticipantEditor.CONSTRUCTOR_ID, TLChannelParticipantEditor.class);\n registerClass(TLChannelParticipantKicked.CONSTRUCTOR_ID, TLChannelParticipantKicked.class);\n registerClass(TLChannelParticipantModerator.CONSTRUCTOR_ID, TLChannelParticipantModerator.class);\n registerClass(TLChannelParticipantSelf.CONSTRUCTOR_ID, TLChannelParticipantSelf.class);\n registerClass(TLChannelParticipantsAdmins.CONSTRUCTOR_ID, TLChannelParticipantsAdmins.class);\n registerClass(TLChannelParticipantsBots.CONSTRUCTOR_ID, TLChannelParticipantsBots.class);\n registerClass(TLChannelParticipantsKicked.CONSTRUCTOR_ID, TLChannelParticipantsKicked.class);\n registerClass(TLChannelParticipantsRecent.CONSTRUCTOR_ID, TLChannelParticipantsRecent.class);\n registerClass(TLChannelRoleEditor.CONSTRUCTOR_ID, TLChannelRoleEditor.class);\n registerClass(TLChannelRoleEmpty.CONSTRUCTOR_ID, TLChannelRoleEmpty.class);\n registerClass(TLChannelRoleModerator.CONSTRUCTOR_ID, TLChannelRoleModerator.class);\n registerClass(com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.class);\n registerClass(TLChannelParticipants.CONSTRUCTOR_ID, TLChannelParticipants.class);\n registerClass(TLChat.CONSTRUCTOR_ID, TLChat.class);\n registerClass(TLChatEmpty.CONSTRUCTOR_ID, TLChatEmpty.class);\n registerClass(TLChatForbidden.CONSTRUCTOR_ID, TLChatForbidden.class);\n registerClass(TLChatFull.CONSTRUCTOR_ID, TLChatFull.class);\n registerClass(TLChatInvite.CONSTRUCTOR_ID, TLChatInvite.class);\n registerClass(TLChatInviteAlready.CONSTRUCTOR_ID, TLChatInviteAlready.class);\n registerClass(TLChatInviteEmpty.CONSTRUCTOR_ID, TLChatInviteEmpty.class);\n registerClass(TLChatInviteExported.CONSTRUCTOR_ID, TLChatInviteExported.class);\n registerClass(TLChatParticipant.CONSTRUCTOR_ID, TLChatParticipant.class);\n registerClass(TLChatParticipantAdmin.CONSTRUCTOR_ID, TLChatParticipantAdmin.class);\n registerClass(TLChatParticipantCreator.CONSTRUCTOR_ID, TLChatParticipantCreator.class);\n registerClass(TLChatParticipants.CONSTRUCTOR_ID, TLChatParticipants.class);\n registerClass(TLChatParticipantsForbidden.CONSTRUCTOR_ID, TLChatParticipantsForbidden.class);\n registerClass(TLChatPhoto.CONSTRUCTOR_ID, TLChatPhoto.class);\n registerClass(TLChatPhotoEmpty.CONSTRUCTOR_ID, TLChatPhotoEmpty.class);\n registerClass(TLConfig.CONSTRUCTOR_ID, TLConfig.class);\n registerClass(TLContact.CONSTRUCTOR_ID, TLContact.class);\n registerClass(TLContactBlocked.CONSTRUCTOR_ID, TLContactBlocked.class);\n registerClass(TLContactLinkContact.CONSTRUCTOR_ID, TLContactLinkContact.class);\n registerClass(TLContactLinkHasPhone.CONSTRUCTOR_ID, TLContactLinkHasPhone.class);\n registerClass(TLContactLinkNone.CONSTRUCTOR_ID, TLContactLinkNone.class);\n registerClass(TLContactLinkUnknown.CONSTRUCTOR_ID, TLContactLinkUnknown.class);\n registerClass(TLContactStatus.CONSTRUCTOR_ID, TLContactStatus.class);\n registerClass(TLBlocked.CONSTRUCTOR_ID, TLBlocked.class);\n registerClass(TLBlockedSlice.CONSTRUCTOR_ID, TLBlockedSlice.class);\n registerClass(TLContacts.CONSTRUCTOR_ID, TLContacts.class);\n registerClass(TLContactsNotModified.CONSTRUCTOR_ID, TLContactsNotModified.class);\n registerClass(TLFound.CONSTRUCTOR_ID, TLFound.class);\n registerClass(TLImportedContacts.CONSTRUCTOR_ID, TLImportedContacts.class);\n registerClass(TLLink.CONSTRUCTOR_ID, TLLink.class);\n registerClass(TLResolvedPeer.CONSTRUCTOR_ID, TLResolvedPeer.class);\n registerClass(TLTopPeers.CONSTRUCTOR_ID, TLTopPeers.class);\n registerClass(TLTopPeersNotModified.CONSTRUCTOR_ID, TLTopPeersNotModified.class);\n registerClass(TLDataJSON.CONSTRUCTOR_ID, TLDataJSON.class);\n registerClass(TLDcOption.CONSTRUCTOR_ID, TLDcOption.class);\n registerClass(TLDialog.CONSTRUCTOR_ID, TLDialog.class);\n registerClass(TLDisabledFeature.CONSTRUCTOR_ID, TLDisabledFeature.class);\n registerClass(TLDocument.CONSTRUCTOR_ID, TLDocument.class);\n registerClass(TLDocumentAttributeAnimated.CONSTRUCTOR_ID, TLDocumentAttributeAnimated.class);\n registerClass(TLDocumentAttributeAudio.CONSTRUCTOR_ID, TLDocumentAttributeAudio.class);\n registerClass(TLDocumentAttributeFilename.CONSTRUCTOR_ID, TLDocumentAttributeFilename.class);\n registerClass(TLDocumentAttributeHasStickers.CONSTRUCTOR_ID, TLDocumentAttributeHasStickers.class);\n registerClass(TLDocumentAttributeImageSize.CONSTRUCTOR_ID, TLDocumentAttributeImageSize.class);\n registerClass(TLDocumentAttributeSticker.CONSTRUCTOR_ID, TLDocumentAttributeSticker.class);\n registerClass(TLDocumentAttributeVideo.CONSTRUCTOR_ID, TLDocumentAttributeVideo.class);\n registerClass(TLDocumentEmpty.CONSTRUCTOR_ID, TLDocumentEmpty.class);\n registerClass(TLDraftMessage.CONSTRUCTOR_ID, TLDraftMessage.class);\n registerClass(TLDraftMessageEmpty.CONSTRUCTOR_ID, TLDraftMessageEmpty.class);\n registerClass(TLEncryptedChat.CONSTRUCTOR_ID, TLEncryptedChat.class);\n registerClass(TLEncryptedChatDiscarded.CONSTRUCTOR_ID, TLEncryptedChatDiscarded.class);\n registerClass(TLEncryptedChatEmpty.CONSTRUCTOR_ID, TLEncryptedChatEmpty.class);\n registerClass(TLEncryptedChatRequested.CONSTRUCTOR_ID, TLEncryptedChatRequested.class);\n registerClass(TLEncryptedChatWaiting.CONSTRUCTOR_ID, TLEncryptedChatWaiting.class);\n registerClass(TLEncryptedFile.CONSTRUCTOR_ID, TLEncryptedFile.class);\n registerClass(TLEncryptedFileEmpty.CONSTRUCTOR_ID, TLEncryptedFileEmpty.class);\n registerClass(TLEncryptedMessage.CONSTRUCTOR_ID, TLEncryptedMessage.class);\n registerClass(TLEncryptedMessageService.CONSTRUCTOR_ID, TLEncryptedMessageService.class);\n registerClass(TLExportedMessageLink.CONSTRUCTOR_ID, TLExportedMessageLink.class);\n registerClass(TLFileLocation.CONSTRUCTOR_ID, TLFileLocation.class);\n registerClass(TLFileLocationUnavailable.CONSTRUCTOR_ID, TLFileLocationUnavailable.class);\n registerClass(TLFoundGif.CONSTRUCTOR_ID, TLFoundGif.class);\n registerClass(TLFoundGifCached.CONSTRUCTOR_ID, TLFoundGifCached.class);\n registerClass(TLGame.CONSTRUCTOR_ID, TLGame.class);\n registerClass(TLGeoPoint.CONSTRUCTOR_ID, TLGeoPoint.class);\n registerClass(TLGeoPointEmpty.CONSTRUCTOR_ID, TLGeoPointEmpty.class);\n registerClass(TLAppUpdate.CONSTRUCTOR_ID, TLAppUpdate.class);\n registerClass(TLInviteText.CONSTRUCTOR_ID, TLInviteText.class);\n registerClass(TLNoAppUpdate.CONSTRUCTOR_ID, TLNoAppUpdate.class);\n registerClass(TLSupport.CONSTRUCTOR_ID, TLSupport.class);\n registerClass(TLTermsOfService.CONSTRUCTOR_ID, TLTermsOfService.class);\n registerClass(TLHighScore.CONSTRUCTOR_ID, TLHighScore.class);\n registerClass(TLImportedContact.CONSTRUCTOR_ID, TLImportedContact.class);\n registerClass(TLInlineBotSwitchPM.CONSTRUCTOR_ID, TLInlineBotSwitchPM.class);\n registerClass(TLInputAppEvent.CONSTRUCTOR_ID, TLInputAppEvent.class);\n registerClass(TLInputBotInlineMessageGame.CONSTRUCTOR_ID, TLInputBotInlineMessageGame.class);\n registerClass(TLInputBotInlineMessageID.CONSTRUCTOR_ID, TLInputBotInlineMessageID.class);\n registerClass(TLInputBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaAuto.class);\n registerClass(TLInputBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaContact.class);\n registerClass(TLInputBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaGeo.class);\n registerClass(TLInputBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaVenue.class);\n registerClass(TLInputBotInlineMessageText.CONSTRUCTOR_ID, TLInputBotInlineMessageText.class);\n registerClass(TLInputBotInlineResult.CONSTRUCTOR_ID, TLInputBotInlineResult.class);\n registerClass(TLInputBotInlineResultDocument.CONSTRUCTOR_ID, TLInputBotInlineResultDocument.class);\n registerClass(TLInputBotInlineResultGame.CONSTRUCTOR_ID, TLInputBotInlineResultGame.class);\n registerClass(TLInputBotInlineResultPhoto.CONSTRUCTOR_ID, TLInputBotInlineResultPhoto.class);\n registerClass(TLInputChannel.CONSTRUCTOR_ID, TLInputChannel.class);\n registerClass(TLInputChannelEmpty.CONSTRUCTOR_ID, TLInputChannelEmpty.class);\n registerClass(TLInputChatPhoto.CONSTRUCTOR_ID, TLInputChatPhoto.class);\n registerClass(TLInputChatPhotoEmpty.CONSTRUCTOR_ID, TLInputChatPhotoEmpty.class);\n registerClass(TLInputChatUploadedPhoto.CONSTRUCTOR_ID, TLInputChatUploadedPhoto.class);\n registerClass(TLInputDocument.CONSTRUCTOR_ID, TLInputDocument.class);\n registerClass(TLInputDocumentEmpty.CONSTRUCTOR_ID, TLInputDocumentEmpty.class);\n registerClass(TLInputDocumentFileLocation.CONSTRUCTOR_ID, TLInputDocumentFileLocation.class);\n registerClass(TLInputEncryptedChat.CONSTRUCTOR_ID, TLInputEncryptedChat.class);\n registerClass(TLInputEncryptedFile.CONSTRUCTOR_ID, TLInputEncryptedFile.class);\n registerClass(TLInputEncryptedFileBigUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileBigUploaded.class);\n registerClass(TLInputEncryptedFileEmpty.CONSTRUCTOR_ID, TLInputEncryptedFileEmpty.class);\n registerClass(TLInputEncryptedFileLocation.CONSTRUCTOR_ID, TLInputEncryptedFileLocation.class);\n registerClass(TLInputEncryptedFileUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileUploaded.class);\n registerClass(TLInputFile.CONSTRUCTOR_ID, TLInputFile.class);\n registerClass(TLInputFileBig.CONSTRUCTOR_ID, TLInputFileBig.class);\n registerClass(TLInputFileLocation.CONSTRUCTOR_ID, TLInputFileLocation.class);\n registerClass(TLInputGameID.CONSTRUCTOR_ID, TLInputGameID.class);\n registerClass(TLInputGameShortName.CONSTRUCTOR_ID, TLInputGameShortName.class);\n registerClass(TLInputGeoPoint.CONSTRUCTOR_ID, TLInputGeoPoint.class);\n registerClass(TLInputGeoPointEmpty.CONSTRUCTOR_ID, TLInputGeoPointEmpty.class);\n registerClass(TLInputMediaContact.CONSTRUCTOR_ID, TLInputMediaContact.class);\n registerClass(TLInputMediaDocument.CONSTRUCTOR_ID, TLInputMediaDocument.class);\n registerClass(TLInputMediaDocumentExternal.CONSTRUCTOR_ID, TLInputMediaDocumentExternal.class);\n registerClass(TLInputMediaEmpty.CONSTRUCTOR_ID, TLInputMediaEmpty.class);\n registerClass(TLInputMediaGame.CONSTRUCTOR_ID, TLInputMediaGame.class);\n registerClass(TLInputMediaGeoPoint.CONSTRUCTOR_ID, TLInputMediaGeoPoint.class);\n registerClass(TLInputMediaGifExternal.CONSTRUCTOR_ID, TLInputMediaGifExternal.class);\n registerClass(TLInputMediaInvoice.CONSTRUCTOR_ID, TLInputMediaInvoice.class);\n registerClass(TLInputMediaPhoto.CONSTRUCTOR_ID, TLInputMediaPhoto.class);\n registerClass(TLInputMediaPhotoExternal.CONSTRUCTOR_ID, TLInputMediaPhotoExternal.class);\n registerClass(TLInputMediaUploadedDocument.CONSTRUCTOR_ID, TLInputMediaUploadedDocument.class);\n registerClass(TLInputMediaUploadedPhoto.CONSTRUCTOR_ID, TLInputMediaUploadedPhoto.class);\n registerClass(TLInputMediaUploadedThumbDocument.CONSTRUCTOR_ID, TLInputMediaUploadedThumbDocument.class);\n registerClass(TLInputMediaVenue.CONSTRUCTOR_ID, TLInputMediaVenue.class);\n registerClass(TLInputMessageEntityMentionName.CONSTRUCTOR_ID, TLInputMessageEntityMentionName.class);\n registerClass(TLInputMessagesFilterChatPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterChatPhotos.class);\n registerClass(TLInputMessagesFilterDocument.CONSTRUCTOR_ID, TLInputMessagesFilterDocument.class);\n registerClass(TLInputMessagesFilterEmpty.CONSTRUCTOR_ID, TLInputMessagesFilterEmpty.class);\n registerClass(TLInputMessagesFilterGif.CONSTRUCTOR_ID, TLInputMessagesFilterGif.class);\n registerClass(TLInputMessagesFilterMusic.CONSTRUCTOR_ID, TLInputMessagesFilterMusic.class);\n registerClass(TLInputMessagesFilterPhoneCalls.CONSTRUCTOR_ID, TLInputMessagesFilterPhoneCalls.class);\n registerClass(TLInputMessagesFilterPhotoVideo.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideo.class);\n registerClass(TLInputMessagesFilterPhotoVideoDocuments.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideoDocuments.class);\n registerClass(TLInputMessagesFilterPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterPhotos.class);\n registerClass(TLInputMessagesFilterRoundVideo.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVideo.class);\n registerClass(TLInputMessagesFilterRoundVoice.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVoice.class);\n registerClass(TLInputMessagesFilterUrl.CONSTRUCTOR_ID, TLInputMessagesFilterUrl.class);\n registerClass(TLInputMessagesFilterVideo.CONSTRUCTOR_ID, TLInputMessagesFilterVideo.class);\n registerClass(TLInputMessagesFilterVoice.CONSTRUCTOR_ID, TLInputMessagesFilterVoice.class);\n registerClass(TLInputNotifyAll.CONSTRUCTOR_ID, TLInputNotifyAll.class);\n registerClass(TLInputNotifyChats.CONSTRUCTOR_ID, TLInputNotifyChats.class);\n registerClass(TLInputNotifyPeer.CONSTRUCTOR_ID, TLInputNotifyPeer.class);\n registerClass(TLInputNotifyUsers.CONSTRUCTOR_ID, TLInputNotifyUsers.class);\n registerClass(TLInputPaymentCredentials.CONSTRUCTOR_ID, TLInputPaymentCredentials.class);\n registerClass(TLInputPaymentCredentialsSaved.CONSTRUCTOR_ID, TLInputPaymentCredentialsSaved.class);\n registerClass(TLInputPeerChannel.CONSTRUCTOR_ID, TLInputPeerChannel.class);\n registerClass(TLInputPeerChat.CONSTRUCTOR_ID, TLInputPeerChat.class);\n registerClass(TLInputPeerEmpty.CONSTRUCTOR_ID, TLInputPeerEmpty.class);\n registerClass(TLInputPeerNotifyEventsAll.CONSTRUCTOR_ID, TLInputPeerNotifyEventsAll.class);\n registerClass(TLInputPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLInputPeerNotifyEventsEmpty.class);\n registerClass(TLInputPeerNotifySettings.CONSTRUCTOR_ID, TLInputPeerNotifySettings.class);\n registerClass(TLInputPeerSelf.CONSTRUCTOR_ID, TLInputPeerSelf.class);\n registerClass(TLInputPeerUser.CONSTRUCTOR_ID, TLInputPeerUser.class);\n registerClass(TLInputPhoneCall.CONSTRUCTOR_ID, TLInputPhoneCall.class);\n registerClass(TLInputPhoneContact.CONSTRUCTOR_ID, TLInputPhoneContact.class);\n registerClass(TLInputPhoto.CONSTRUCTOR_ID, TLInputPhoto.class);\n registerClass(TLInputPhotoEmpty.CONSTRUCTOR_ID, TLInputPhotoEmpty.class);\n registerClass(TLInputPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLInputPrivacyKeyChatInvite.class);\n registerClass(TLInputPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLInputPrivacyKeyPhoneCall.class);\n registerClass(TLInputPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLInputPrivacyKeyStatusTimestamp.class);\n registerClass(TLInputPrivacyValueAllowAll.CONSTRUCTOR_ID, TLInputPrivacyValueAllowAll.class);\n registerClass(TLInputPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueAllowContacts.class);\n registerClass(TLInputPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueAllowUsers.class);\n registerClass(TLInputPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowAll.class);\n registerClass(TLInputPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowContacts.class);\n registerClass(TLInputPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowUsers.class);\n registerClass(TLInputReportReasonOther.CONSTRUCTOR_ID, TLInputReportReasonOther.class);\n registerClass(TLInputReportReasonPornography.CONSTRUCTOR_ID, TLInputReportReasonPornography.class);\n registerClass(TLInputReportReasonSpam.CONSTRUCTOR_ID, TLInputReportReasonSpam.class);\n registerClass(TLInputReportReasonViolence.CONSTRUCTOR_ID, TLInputReportReasonViolence.class);\n registerClass(TLInputStickerSetEmpty.CONSTRUCTOR_ID, TLInputStickerSetEmpty.class);\n registerClass(TLInputStickerSetID.CONSTRUCTOR_ID, TLInputStickerSetID.class);\n registerClass(TLInputStickerSetShortName.CONSTRUCTOR_ID, TLInputStickerSetShortName.class);\n registerClass(TLInputStickeredMediaDocument.CONSTRUCTOR_ID, TLInputStickeredMediaDocument.class);\n registerClass(TLInputStickeredMediaPhoto.CONSTRUCTOR_ID, TLInputStickeredMediaPhoto.class);\n registerClass(TLInputUser.CONSTRUCTOR_ID, TLInputUser.class);\n registerClass(TLInputUserEmpty.CONSTRUCTOR_ID, TLInputUserEmpty.class);\n registerClass(TLInputUserSelf.CONSTRUCTOR_ID, TLInputUserSelf.class);\n registerClass(TLInputWebDocument.CONSTRUCTOR_ID, TLInputWebDocument.class);\n registerClass(TLInputWebFileLocation.CONSTRUCTOR_ID, TLInputWebFileLocation.class);\n registerClass(TLInvoice.CONSTRUCTOR_ID, TLInvoice.class);\n registerClass(TLKeyboardButton.CONSTRUCTOR_ID, TLKeyboardButton.class);\n registerClass(TLKeyboardButtonBuy.CONSTRUCTOR_ID, TLKeyboardButtonBuy.class);\n registerClass(TLKeyboardButtonCallback.CONSTRUCTOR_ID, TLKeyboardButtonCallback.class);\n registerClass(TLKeyboardButtonGame.CONSTRUCTOR_ID, TLKeyboardButtonGame.class);\n registerClass(TLKeyboardButtonRequestGeoLocation.CONSTRUCTOR_ID, TLKeyboardButtonRequestGeoLocation.class);\n registerClass(TLKeyboardButtonRequestPhone.CONSTRUCTOR_ID, TLKeyboardButtonRequestPhone.class);\n registerClass(TLKeyboardButtonRow.CONSTRUCTOR_ID, TLKeyboardButtonRow.class);\n registerClass(TLKeyboardButtonSwitchInline.CONSTRUCTOR_ID, TLKeyboardButtonSwitchInline.class);\n registerClass(TLKeyboardButtonUrl.CONSTRUCTOR_ID, TLKeyboardButtonUrl.class);\n registerClass(TLLabeledPrice.CONSTRUCTOR_ID, TLLabeledPrice.class);\n registerClass(TLMaskCoords.CONSTRUCTOR_ID, TLMaskCoords.class);\n registerClass(TLMessage.CONSTRUCTOR_ID, TLMessage.class);\n registerClass(TLMessageActionChannelCreate.CONSTRUCTOR_ID, TLMessageActionChannelCreate.class);\n registerClass(TLMessageActionChannelMigrateFrom.CONSTRUCTOR_ID, TLMessageActionChannelMigrateFrom.class);\n registerClass(TLMessageActionChatAddUser.CONSTRUCTOR_ID, TLMessageActionChatAddUser.class);\n registerClass(TLMessageActionChatCreate.CONSTRUCTOR_ID, TLMessageActionChatCreate.class);\n registerClass(TLMessageActionChatDeletePhoto.CONSTRUCTOR_ID, TLMessageActionChatDeletePhoto.class);\n registerClass(TLMessageActionChatDeleteUser.CONSTRUCTOR_ID, TLMessageActionChatDeleteUser.class);\n registerClass(TLMessageActionChatEditPhoto.CONSTRUCTOR_ID, TLMessageActionChatEditPhoto.class);\n registerClass(TLMessageActionChatEditTitle.CONSTRUCTOR_ID, TLMessageActionChatEditTitle.class);\n registerClass(TLMessageActionChatJoinedByLink.CONSTRUCTOR_ID, TLMessageActionChatJoinedByLink.class);\n registerClass(TLMessageActionChatMigrateTo.CONSTRUCTOR_ID, TLMessageActionChatMigrateTo.class);\n registerClass(TLMessageActionEmpty.CONSTRUCTOR_ID, TLMessageActionEmpty.class);\n registerClass(TLMessageActionGameScore.CONSTRUCTOR_ID, TLMessageActionGameScore.class);\n registerClass(TLMessageActionHistoryClear.CONSTRUCTOR_ID, TLMessageActionHistoryClear.class);\n registerClass(TLMessageActionPaymentSent.CONSTRUCTOR_ID, TLMessageActionPaymentSent.class);\n registerClass(TLMessageActionPaymentSentMe.CONSTRUCTOR_ID, TLMessageActionPaymentSentMe.class);\n registerClass(TLMessageActionPhoneCall.CONSTRUCTOR_ID, TLMessageActionPhoneCall.class);\n registerClass(TLMessageActionPinMessage.CONSTRUCTOR_ID, TLMessageActionPinMessage.class);\n registerClass(TLMessageEmpty.CONSTRUCTOR_ID, TLMessageEmpty.class);\n registerClass(TLMessageEntityBold.CONSTRUCTOR_ID, TLMessageEntityBold.class);\n registerClass(TLMessageEntityBotCommand.CONSTRUCTOR_ID, TLMessageEntityBotCommand.class);\n registerClass(TLMessageEntityCode.CONSTRUCTOR_ID, TLMessageEntityCode.class);\n registerClass(TLMessageEntityEmail.CONSTRUCTOR_ID, TLMessageEntityEmail.class);\n registerClass(TLMessageEntityHashtag.CONSTRUCTOR_ID, TLMessageEntityHashtag.class);\n registerClass(TLMessageEntityItalic.CONSTRUCTOR_ID, TLMessageEntityItalic.class);\n registerClass(TLMessageEntityMention.CONSTRUCTOR_ID, TLMessageEntityMention.class);\n registerClass(TLMessageEntityMentionName.CONSTRUCTOR_ID, TLMessageEntityMentionName.class);\n registerClass(TLMessageEntityPre.CONSTRUCTOR_ID, TLMessageEntityPre.class);\n registerClass(TLMessageEntityTextUrl.CONSTRUCTOR_ID, TLMessageEntityTextUrl.class);\n registerClass(TLMessageEntityUnknown.CONSTRUCTOR_ID, TLMessageEntityUnknown.class);\n registerClass(TLMessageEntityUrl.CONSTRUCTOR_ID, TLMessageEntityUrl.class);\n registerClass(TLMessageFwdHeader.CONSTRUCTOR_ID, TLMessageFwdHeader.class);\n registerClass(TLMessageMediaContact.CONSTRUCTOR_ID, TLMessageMediaContact.class);\n registerClass(TLMessageMediaDocument.CONSTRUCTOR_ID, TLMessageMediaDocument.class);\n registerClass(TLMessageMediaEmpty.CONSTRUCTOR_ID, TLMessageMediaEmpty.class);\n registerClass(TLMessageMediaGame.CONSTRUCTOR_ID, TLMessageMediaGame.class);\n registerClass(TLMessageMediaGeo.CONSTRUCTOR_ID, TLMessageMediaGeo.class);\n registerClass(TLMessageMediaInvoice.CONSTRUCTOR_ID, TLMessageMediaInvoice.class);\n registerClass(TLMessageMediaPhoto.CONSTRUCTOR_ID, TLMessageMediaPhoto.class);\n registerClass(TLMessageMediaUnsupported.CONSTRUCTOR_ID, TLMessageMediaUnsupported.class);\n registerClass(TLMessageMediaVenue.CONSTRUCTOR_ID, TLMessageMediaVenue.class);\n registerClass(TLMessageMediaWebPage.CONSTRUCTOR_ID, TLMessageMediaWebPage.class);\n registerClass(TLMessageRange.CONSTRUCTOR_ID, TLMessageRange.class);\n registerClass(TLMessageService.CONSTRUCTOR_ID, TLMessageService.class);\n registerClass(TLAffectedHistory.CONSTRUCTOR_ID, TLAffectedHistory.class);\n registerClass(TLAffectedMessages.CONSTRUCTOR_ID, TLAffectedMessages.class);\n registerClass(TLAllStickers.CONSTRUCTOR_ID, TLAllStickers.class);\n registerClass(TLAllStickersNotModified.CONSTRUCTOR_ID, TLAllStickersNotModified.class);\n registerClass(TLArchivedStickers.CONSTRUCTOR_ID, TLArchivedStickers.class);\n registerClass(TLBotCallbackAnswer.CONSTRUCTOR_ID, TLBotCallbackAnswer.class);\n registerClass(TLBotResults.CONSTRUCTOR_ID, TLBotResults.class);\n registerClass(TLChannelMessages.CONSTRUCTOR_ID, TLChannelMessages.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLChatFull.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLChatFull.class);\n registerClass(TLChats.CONSTRUCTOR_ID, TLChats.class);\n registerClass(TLChatsSlice.CONSTRUCTOR_ID, TLChatsSlice.class);\n registerClass(TLDhConfig.CONSTRUCTOR_ID, TLDhConfig.class);\n registerClass(TLDhConfigNotModified.CONSTRUCTOR_ID, TLDhConfigNotModified.class);\n registerClass(TLDialogs.CONSTRUCTOR_ID, TLDialogs.class);\n registerClass(TLDialogsSlice.CONSTRUCTOR_ID, TLDialogsSlice.class);\n registerClass(TLFeaturedStickers.CONSTRUCTOR_ID, TLFeaturedStickers.class);\n registerClass(TLFeaturedStickersNotModified.CONSTRUCTOR_ID, TLFeaturedStickersNotModified.class);\n registerClass(TLFoundGifs.CONSTRUCTOR_ID, TLFoundGifs.class);\n registerClass(TLHighScores.CONSTRUCTOR_ID, TLHighScores.class);\n registerClass(TLMessageEditData.CONSTRUCTOR_ID, TLMessageEditData.class);\n registerClass(TLMessages.CONSTRUCTOR_ID, TLMessages.class);\n registerClass(TLMessagesSlice.CONSTRUCTOR_ID, TLMessagesSlice.class);\n registerClass(TLPeerDialogs.CONSTRUCTOR_ID, TLPeerDialogs.class);\n registerClass(TLRecentStickers.CONSTRUCTOR_ID, TLRecentStickers.class);\n registerClass(TLRecentStickersNotModified.CONSTRUCTOR_ID, TLRecentStickersNotModified.class);\n registerClass(TLSavedGifs.CONSTRUCTOR_ID, TLSavedGifs.class);\n registerClass(TLSavedGifsNotModified.CONSTRUCTOR_ID, TLSavedGifsNotModified.class);\n registerClass(TLSentEncryptedFile.CONSTRUCTOR_ID, TLSentEncryptedFile.class);\n registerClass(TLSentEncryptedMessage.CONSTRUCTOR_ID, TLSentEncryptedMessage.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLStickerSet.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLStickerSet.class);\n registerClass(TLStickerSetInstallResultArchive.CONSTRUCTOR_ID, TLStickerSetInstallResultArchive.class);\n registerClass(TLStickerSetInstallResultSuccess.CONSTRUCTOR_ID, TLStickerSetInstallResultSuccess.class);\n registerClass(TLStickers.CONSTRUCTOR_ID, TLStickers.class);\n registerClass(TLStickersNotModified.CONSTRUCTOR_ID, TLStickersNotModified.class);\n registerClass(TLNearestDc.CONSTRUCTOR_ID, TLNearestDc.class);\n registerClass(TLNotifyAll.CONSTRUCTOR_ID, TLNotifyAll.class);\n registerClass(TLNotifyChats.CONSTRUCTOR_ID, TLNotifyChats.class);\n registerClass(TLNotifyPeer.CONSTRUCTOR_ID, TLNotifyPeer.class);\n registerClass(TLNotifyUsers.CONSTRUCTOR_ID, TLNotifyUsers.class);\n registerClass(TLPageBlockAnchor.CONSTRUCTOR_ID, TLPageBlockAnchor.class);\n registerClass(TLPageBlockAuthorDate.CONSTRUCTOR_ID, TLPageBlockAuthorDate.class);\n registerClass(TLPageBlockBlockquote.CONSTRUCTOR_ID, TLPageBlockBlockquote.class);\n registerClass(TLPageBlockChannel.CONSTRUCTOR_ID, TLPageBlockChannel.class);\n registerClass(TLPageBlockCollage.CONSTRUCTOR_ID, TLPageBlockCollage.class);\n registerClass(TLPageBlockCover.CONSTRUCTOR_ID, TLPageBlockCover.class);\n registerClass(TLPageBlockDivider.CONSTRUCTOR_ID, TLPageBlockDivider.class);\n registerClass(TLPageBlockEmbed.CONSTRUCTOR_ID, TLPageBlockEmbed.class);\n registerClass(TLPageBlockEmbedPost.CONSTRUCTOR_ID, TLPageBlockEmbedPost.class);\n registerClass(TLPageBlockFooter.CONSTRUCTOR_ID, TLPageBlockFooter.class);\n registerClass(TLPageBlockHeader.CONSTRUCTOR_ID, TLPageBlockHeader.class);\n registerClass(TLPageBlockList.CONSTRUCTOR_ID, TLPageBlockList.class);\n registerClass(TLPageBlockParagraph.CONSTRUCTOR_ID, TLPageBlockParagraph.class);\n registerClass(TLPageBlockPhoto.CONSTRUCTOR_ID, TLPageBlockPhoto.class);\n registerClass(TLPageBlockPreformatted.CONSTRUCTOR_ID, TLPageBlockPreformatted.class);\n registerClass(TLPageBlockPullquote.CONSTRUCTOR_ID, TLPageBlockPullquote.class);\n registerClass(TLPageBlockSlideshow.CONSTRUCTOR_ID, TLPageBlockSlideshow.class);\n registerClass(TLPageBlockSubheader.CONSTRUCTOR_ID, TLPageBlockSubheader.class);\n registerClass(TLPageBlockSubtitle.CONSTRUCTOR_ID, TLPageBlockSubtitle.class);\n registerClass(TLPageBlockTitle.CONSTRUCTOR_ID, TLPageBlockTitle.class);\n registerClass(TLPageBlockUnsupported.CONSTRUCTOR_ID, TLPageBlockUnsupported.class);\n registerClass(TLPageBlockVideo.CONSTRUCTOR_ID, TLPageBlockVideo.class);\n registerClass(TLPageFull.CONSTRUCTOR_ID, TLPageFull.class);\n registerClass(TLPagePart.CONSTRUCTOR_ID, TLPagePart.class);\n registerClass(TLPaymentCharge.CONSTRUCTOR_ID, TLPaymentCharge.class);\n registerClass(TLPaymentRequestedInfo.CONSTRUCTOR_ID, TLPaymentRequestedInfo.class);\n registerClass(TLPaymentSavedCredentialsCard.CONSTRUCTOR_ID, TLPaymentSavedCredentialsCard.class);\n registerClass(TLPaymentForm.CONSTRUCTOR_ID, TLPaymentForm.class);\n registerClass(TLPaymentReceipt.CONSTRUCTOR_ID, TLPaymentReceipt.class);\n registerClass(TLPaymentResult.CONSTRUCTOR_ID, TLPaymentResult.class);\n registerClass(TLPaymentVerficationNeeded.CONSTRUCTOR_ID, TLPaymentVerficationNeeded.class);\n registerClass(TLSavedInfo.CONSTRUCTOR_ID, TLSavedInfo.class);\n registerClass(TLValidatedRequestedInfo.CONSTRUCTOR_ID, TLValidatedRequestedInfo.class);\n registerClass(TLPeerChannel.CONSTRUCTOR_ID, TLPeerChannel.class);\n registerClass(TLPeerChat.CONSTRUCTOR_ID, TLPeerChat.class);\n registerClass(TLPeerNotifyEventsAll.CONSTRUCTOR_ID, TLPeerNotifyEventsAll.class);\n registerClass(TLPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLPeerNotifyEventsEmpty.class);\n registerClass(TLPeerNotifySettings.CONSTRUCTOR_ID, TLPeerNotifySettings.class);\n registerClass(TLPeerNotifySettingsEmpty.CONSTRUCTOR_ID, TLPeerNotifySettingsEmpty.class);\n registerClass(TLPeerSettings.CONSTRUCTOR_ID, TLPeerSettings.class);\n registerClass(TLPeerUser.CONSTRUCTOR_ID, TLPeerUser.class);\n registerClass(com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.class);\n registerClass(TLPhoneCall.CONSTRUCTOR_ID, TLPhoneCall.class);\n registerClass(TLPhoneCallAccepted.CONSTRUCTOR_ID, TLPhoneCallAccepted.class);\n registerClass(TLPhoneCallDiscardReasonBusy.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonBusy.class);\n registerClass(TLPhoneCallDiscardReasonDisconnect.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonDisconnect.class);\n registerClass(TLPhoneCallDiscardReasonHangup.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonHangup.class);\n registerClass(TLPhoneCallDiscardReasonMissed.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonMissed.class);\n registerClass(TLPhoneCallDiscarded.CONSTRUCTOR_ID, TLPhoneCallDiscarded.class);\n registerClass(TLPhoneCallEmpty.CONSTRUCTOR_ID, TLPhoneCallEmpty.class);\n registerClass(TLPhoneCallProtocol.CONSTRUCTOR_ID, TLPhoneCallProtocol.class);\n registerClass(TLPhoneCallRequested.CONSTRUCTOR_ID, TLPhoneCallRequested.class);\n registerClass(TLPhoneCallWaiting.CONSTRUCTOR_ID, TLPhoneCallWaiting.class);\n registerClass(TLPhoneConnection.CONSTRUCTOR_ID, TLPhoneConnection.class);\n registerClass(TLPhoto.CONSTRUCTOR_ID, TLPhoto.class);\n registerClass(TLPhotoCachedSize.CONSTRUCTOR_ID, TLPhotoCachedSize.class);\n registerClass(TLPhotoEmpty.CONSTRUCTOR_ID, TLPhotoEmpty.class);\n registerClass(TLPhotoSize.CONSTRUCTOR_ID, TLPhotoSize.class);\n registerClass(TLPhotoSizeEmpty.CONSTRUCTOR_ID, TLPhotoSizeEmpty.class);\n registerClass(com.github.badoualy.telegram.tl.api.photos.TLPhoto.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.photos.TLPhoto.class);\n registerClass(TLPhotos.CONSTRUCTOR_ID, TLPhotos.class);\n registerClass(TLPhotosSlice.CONSTRUCTOR_ID, TLPhotosSlice.class);\n registerClass(TLPostAddress.CONSTRUCTOR_ID, TLPostAddress.class);\n registerClass(TLPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLPrivacyKeyChatInvite.class);\n registerClass(TLPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLPrivacyKeyPhoneCall.class);\n registerClass(TLPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLPrivacyKeyStatusTimestamp.class);\n registerClass(TLPrivacyValueAllowAll.CONSTRUCTOR_ID, TLPrivacyValueAllowAll.class);\n registerClass(TLPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLPrivacyValueAllowContacts.class);\n registerClass(TLPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLPrivacyValueAllowUsers.class);\n registerClass(TLPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLPrivacyValueDisallowAll.class);\n registerClass(TLPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLPrivacyValueDisallowContacts.class);\n registerClass(TLPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLPrivacyValueDisallowUsers.class);\n registerClass(TLReceivedNotifyMessage.CONSTRUCTOR_ID, TLReceivedNotifyMessage.class);\n registerClass(TLReplyInlineMarkup.CONSTRUCTOR_ID, TLReplyInlineMarkup.class);\n registerClass(TLReplyKeyboardForceReply.CONSTRUCTOR_ID, TLReplyKeyboardForceReply.class);\n registerClass(TLReplyKeyboardHide.CONSTRUCTOR_ID, TLReplyKeyboardHide.class);\n registerClass(TLReplyKeyboardMarkup.CONSTRUCTOR_ID, TLReplyKeyboardMarkup.class);\n registerClass(TLSendMessageCancelAction.CONSTRUCTOR_ID, TLSendMessageCancelAction.class);\n registerClass(TLSendMessageChooseContactAction.CONSTRUCTOR_ID, TLSendMessageChooseContactAction.class);\n registerClass(TLSendMessageGamePlayAction.CONSTRUCTOR_ID, TLSendMessageGamePlayAction.class);\n registerClass(TLSendMessageGeoLocationAction.CONSTRUCTOR_ID, TLSendMessageGeoLocationAction.class);\n registerClass(TLSendMessageRecordAudioAction.CONSTRUCTOR_ID, TLSendMessageRecordAudioAction.class);\n registerClass(TLSendMessageRecordRoundAction.CONSTRUCTOR_ID, TLSendMessageRecordRoundAction.class);\n registerClass(TLSendMessageRecordVideoAction.CONSTRUCTOR_ID, TLSendMessageRecordVideoAction.class);\n registerClass(TLSendMessageTypingAction.CONSTRUCTOR_ID, TLSendMessageTypingAction.class);\n registerClass(TLSendMessageUploadAudioAction.CONSTRUCTOR_ID, TLSendMessageUploadAudioAction.class);\n registerClass(TLSendMessageUploadDocumentAction.CONSTRUCTOR_ID, TLSendMessageUploadDocumentAction.class);\n registerClass(TLSendMessageUploadPhotoAction.CONSTRUCTOR_ID, TLSendMessageUploadPhotoAction.class);\n registerClass(TLSendMessageUploadRoundAction.CONSTRUCTOR_ID, TLSendMessageUploadRoundAction.class);\n registerClass(TLSendMessageUploadVideoAction.CONSTRUCTOR_ID, TLSendMessageUploadVideoAction.class);\n registerClass(TLShippingOption.CONSTRUCTOR_ID, TLShippingOption.class);\n registerClass(TLStickerPack.CONSTRUCTOR_ID, TLStickerPack.class);\n registerClass(TLStickerSet.CONSTRUCTOR_ID, TLStickerSet.class);\n registerClass(TLStickerSetCovered.CONSTRUCTOR_ID, TLStickerSetCovered.class);\n registerClass(TLStickerSetMultiCovered.CONSTRUCTOR_ID, TLStickerSetMultiCovered.class);\n registerClass(TLFileGif.CONSTRUCTOR_ID, TLFileGif.class);\n registerClass(TLFileJpeg.CONSTRUCTOR_ID, TLFileJpeg.class);\n registerClass(TLFileMov.CONSTRUCTOR_ID, TLFileMov.class);\n registerClass(TLFileMp3.CONSTRUCTOR_ID, TLFileMp3.class);\n registerClass(TLFileMp4.CONSTRUCTOR_ID, TLFileMp4.class);\n registerClass(TLFilePartial.CONSTRUCTOR_ID, TLFilePartial.class);\n registerClass(TLFilePdf.CONSTRUCTOR_ID, TLFilePdf.class);\n registerClass(TLFilePng.CONSTRUCTOR_ID, TLFilePng.class);\n registerClass(TLFileUnknown.CONSTRUCTOR_ID, TLFileUnknown.class);\n registerClass(TLFileWebp.CONSTRUCTOR_ID, TLFileWebp.class);\n registerClass(TLTextBold.CONSTRUCTOR_ID, TLTextBold.class);\n registerClass(TLTextConcat.CONSTRUCTOR_ID, TLTextConcat.class);\n registerClass(TLTextEmail.CONSTRUCTOR_ID, TLTextEmail.class);\n registerClass(TLTextEmpty.CONSTRUCTOR_ID, TLTextEmpty.class);\n registerClass(TLTextFixed.CONSTRUCTOR_ID, TLTextFixed.class);\n registerClass(TLTextItalic.CONSTRUCTOR_ID, TLTextItalic.class);\n registerClass(TLTextPlain.CONSTRUCTOR_ID, TLTextPlain.class);\n registerClass(TLTextStrike.CONSTRUCTOR_ID, TLTextStrike.class);\n registerClass(TLTextUnderline.CONSTRUCTOR_ID, TLTextUnderline.class);\n registerClass(TLTextUrl.CONSTRUCTOR_ID, TLTextUrl.class);\n registerClass(TLTopPeer.CONSTRUCTOR_ID, TLTopPeer.class);\n registerClass(TLTopPeerCategoryBotsInline.CONSTRUCTOR_ID, TLTopPeerCategoryBotsInline.class);\n registerClass(TLTopPeerCategoryBotsPM.CONSTRUCTOR_ID, TLTopPeerCategoryBotsPM.class);\n registerClass(TLTopPeerCategoryChannels.CONSTRUCTOR_ID, TLTopPeerCategoryChannels.class);\n registerClass(TLTopPeerCategoryCorrespondents.CONSTRUCTOR_ID, TLTopPeerCategoryCorrespondents.class);\n registerClass(TLTopPeerCategoryGroups.CONSTRUCTOR_ID, TLTopPeerCategoryGroups.class);\n registerClass(TLTopPeerCategoryPeers.CONSTRUCTOR_ID, TLTopPeerCategoryPeers.class);\n registerClass(TLUpdateBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateBotCallbackQuery.class);\n registerClass(TLUpdateBotInlineQuery.CONSTRUCTOR_ID, TLUpdateBotInlineQuery.class);\n registerClass(TLUpdateBotInlineSend.CONSTRUCTOR_ID, TLUpdateBotInlineSend.class);\n registerClass(TLUpdateBotPrecheckoutQuery.CONSTRUCTOR_ID, TLUpdateBotPrecheckoutQuery.class);\n registerClass(TLUpdateBotShippingQuery.CONSTRUCTOR_ID, TLUpdateBotShippingQuery.class);\n registerClass(TLUpdateBotWebhookJSON.CONSTRUCTOR_ID, TLUpdateBotWebhookJSON.class);\n registerClass(TLUpdateBotWebhookJSONQuery.CONSTRUCTOR_ID, TLUpdateBotWebhookJSONQuery.class);\n registerClass(TLUpdateChannel.CONSTRUCTOR_ID, TLUpdateChannel.class);\n registerClass(TLUpdateChannelMessageViews.CONSTRUCTOR_ID, TLUpdateChannelMessageViews.class);\n registerClass(TLUpdateChannelPinnedMessage.CONSTRUCTOR_ID, TLUpdateChannelPinnedMessage.class);\n registerClass(TLUpdateChannelTooLong.CONSTRUCTOR_ID, TLUpdateChannelTooLong.class);\n registerClass(TLUpdateChannelWebPage.CONSTRUCTOR_ID, TLUpdateChannelWebPage.class);\n registerClass(TLUpdateChatAdmins.CONSTRUCTOR_ID, TLUpdateChatAdmins.class);\n registerClass(TLUpdateChatParticipantAdd.CONSTRUCTOR_ID, TLUpdateChatParticipantAdd.class);\n registerClass(TLUpdateChatParticipantAdmin.CONSTRUCTOR_ID, TLUpdateChatParticipantAdmin.class);\n registerClass(TLUpdateChatParticipantDelete.CONSTRUCTOR_ID, TLUpdateChatParticipantDelete.class);\n registerClass(TLUpdateChatParticipants.CONSTRUCTOR_ID, TLUpdateChatParticipants.class);\n registerClass(TLUpdateChatUserTyping.CONSTRUCTOR_ID, TLUpdateChatUserTyping.class);\n registerClass(TLUpdateConfig.CONSTRUCTOR_ID, TLUpdateConfig.class);\n registerClass(TLUpdateContactLink.CONSTRUCTOR_ID, TLUpdateContactLink.class);\n registerClass(TLUpdateContactRegistered.CONSTRUCTOR_ID, TLUpdateContactRegistered.class);\n registerClass(TLUpdateDcOptions.CONSTRUCTOR_ID, TLUpdateDcOptions.class);\n registerClass(TLUpdateDeleteChannelMessages.CONSTRUCTOR_ID, TLUpdateDeleteChannelMessages.class);\n registerClass(TLUpdateDeleteMessages.CONSTRUCTOR_ID, TLUpdateDeleteMessages.class);\n registerClass(TLUpdateDialogPinned.CONSTRUCTOR_ID, TLUpdateDialogPinned.class);\n registerClass(TLUpdateDraftMessage.CONSTRUCTOR_ID, TLUpdateDraftMessage.class);\n registerClass(TLUpdateEditChannelMessage.CONSTRUCTOR_ID, TLUpdateEditChannelMessage.class);\n registerClass(TLUpdateEditMessage.CONSTRUCTOR_ID, TLUpdateEditMessage.class);\n registerClass(TLUpdateEncryptedChatTyping.CONSTRUCTOR_ID, TLUpdateEncryptedChatTyping.class);\n registerClass(TLUpdateEncryptedMessagesRead.CONSTRUCTOR_ID, TLUpdateEncryptedMessagesRead.class);\n registerClass(TLUpdateEncryption.CONSTRUCTOR_ID, TLUpdateEncryption.class);\n registerClass(TLUpdateInlineBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateInlineBotCallbackQuery.class);\n registerClass(TLUpdateMessageID.CONSTRUCTOR_ID, TLUpdateMessageID.class);\n registerClass(TLUpdateNewChannelMessage.CONSTRUCTOR_ID, TLUpdateNewChannelMessage.class);\n registerClass(TLUpdateNewEncryptedMessage.CONSTRUCTOR_ID, TLUpdateNewEncryptedMessage.class);\n registerClass(TLUpdateNewMessage.CONSTRUCTOR_ID, TLUpdateNewMessage.class);\n registerClass(TLUpdateNewStickerSet.CONSTRUCTOR_ID, TLUpdateNewStickerSet.class);\n registerClass(TLUpdateNotifySettings.CONSTRUCTOR_ID, TLUpdateNotifySettings.class);\n registerClass(TLUpdatePhoneCall.CONSTRUCTOR_ID, TLUpdatePhoneCall.class);\n registerClass(TLUpdatePinnedDialogs.CONSTRUCTOR_ID, TLUpdatePinnedDialogs.class);\n registerClass(TLUpdatePrivacy.CONSTRUCTOR_ID, TLUpdatePrivacy.class);\n registerClass(TLUpdatePtsChanged.CONSTRUCTOR_ID, TLUpdatePtsChanged.class);\n registerClass(TLUpdateReadChannelInbox.CONSTRUCTOR_ID, TLUpdateReadChannelInbox.class);\n registerClass(TLUpdateReadChannelOutbox.CONSTRUCTOR_ID, TLUpdateReadChannelOutbox.class);\n registerClass(TLUpdateReadFeaturedStickers.CONSTRUCTOR_ID, TLUpdateReadFeaturedStickers.class);\n registerClass(TLUpdateReadHistoryInbox.CONSTRUCTOR_ID, TLUpdateReadHistoryInbox.class);\n registerClass(TLUpdateReadHistoryOutbox.CONSTRUCTOR_ID, TLUpdateReadHistoryOutbox.class);\n registerClass(TLUpdateReadMessagesContents.CONSTRUCTOR_ID, TLUpdateReadMessagesContents.class);\n registerClass(TLUpdateRecentStickers.CONSTRUCTOR_ID, TLUpdateRecentStickers.class);\n registerClass(TLUpdateSavedGifs.CONSTRUCTOR_ID, TLUpdateSavedGifs.class);\n registerClass(TLUpdateServiceNotification.CONSTRUCTOR_ID, TLUpdateServiceNotification.class);\n registerClass(TLUpdateShort.CONSTRUCTOR_ID, TLUpdateShort.class);\n registerClass(TLUpdateShortChatMessage.CONSTRUCTOR_ID, TLUpdateShortChatMessage.class);\n registerClass(TLUpdateShortMessage.CONSTRUCTOR_ID, TLUpdateShortMessage.class);\n registerClass(TLUpdateShortSentMessage.CONSTRUCTOR_ID, TLUpdateShortSentMessage.class);\n registerClass(TLUpdateStickerSets.CONSTRUCTOR_ID, TLUpdateStickerSets.class);\n registerClass(TLUpdateStickerSetsOrder.CONSTRUCTOR_ID, TLUpdateStickerSetsOrder.class);\n registerClass(TLUpdateUserBlocked.CONSTRUCTOR_ID, TLUpdateUserBlocked.class);\n registerClass(TLUpdateUserName.CONSTRUCTOR_ID, TLUpdateUserName.class);\n registerClass(TLUpdateUserPhone.CONSTRUCTOR_ID, TLUpdateUserPhone.class);\n registerClass(TLUpdateUserPhoto.CONSTRUCTOR_ID, TLUpdateUserPhoto.class);\n registerClass(TLUpdateUserStatus.CONSTRUCTOR_ID, TLUpdateUserStatus.class);\n registerClass(TLUpdateUserTyping.CONSTRUCTOR_ID, TLUpdateUserTyping.class);\n registerClass(TLUpdateWebPage.CONSTRUCTOR_ID, TLUpdateWebPage.class);\n registerClass(TLUpdates.CONSTRUCTOR_ID, TLUpdates.class);\n registerClass(TLChannelDifference.CONSTRUCTOR_ID, TLChannelDifference.class);\n registerClass(TLChannelDifferenceEmpty.CONSTRUCTOR_ID, TLChannelDifferenceEmpty.class);\n registerClass(TLChannelDifferenceTooLong.CONSTRUCTOR_ID, TLChannelDifferenceTooLong.class);\n registerClass(TLDifference.CONSTRUCTOR_ID, TLDifference.class);\n registerClass(TLDifferenceEmpty.CONSTRUCTOR_ID, TLDifferenceEmpty.class);\n registerClass(TLDifferenceSlice.CONSTRUCTOR_ID, TLDifferenceSlice.class);\n registerClass(TLDifferenceTooLong.CONSTRUCTOR_ID, TLDifferenceTooLong.class);\n registerClass(TLState.CONSTRUCTOR_ID, TLState.class);\n registerClass(TLUpdatesCombined.CONSTRUCTOR_ID, TLUpdatesCombined.class);\n registerClass(TLUpdatesTooLong.CONSTRUCTOR_ID, TLUpdatesTooLong.class);\n registerClass(TLCdnFile.CONSTRUCTOR_ID, TLCdnFile.class);\n registerClass(TLCdnFileReuploadNeeded.CONSTRUCTOR_ID, TLCdnFileReuploadNeeded.class);\n registerClass(TLFile.CONSTRUCTOR_ID, TLFile.class);\n registerClass(TLFileCdnRedirect.CONSTRUCTOR_ID, TLFileCdnRedirect.class);\n registerClass(TLWebFile.CONSTRUCTOR_ID, TLWebFile.class);\n registerClass(TLUser.CONSTRUCTOR_ID, TLUser.class);\n registerClass(TLUserEmpty.CONSTRUCTOR_ID, TLUserEmpty.class);\n registerClass(TLUserFull.CONSTRUCTOR_ID, TLUserFull.class);\n registerClass(TLUserProfilePhoto.CONSTRUCTOR_ID, TLUserProfilePhoto.class);\n registerClass(TLUserProfilePhotoEmpty.CONSTRUCTOR_ID, TLUserProfilePhotoEmpty.class);\n registerClass(TLUserStatusEmpty.CONSTRUCTOR_ID, TLUserStatusEmpty.class);\n registerClass(TLUserStatusLastMonth.CONSTRUCTOR_ID, TLUserStatusLastMonth.class);\n registerClass(TLUserStatusLastWeek.CONSTRUCTOR_ID, TLUserStatusLastWeek.class);\n registerClass(TLUserStatusOffline.CONSTRUCTOR_ID, TLUserStatusOffline.class);\n registerClass(TLUserStatusOnline.CONSTRUCTOR_ID, TLUserStatusOnline.class);\n registerClass(TLUserStatusRecently.CONSTRUCTOR_ID, TLUserStatusRecently.class);\n registerClass(TLWallPaper.CONSTRUCTOR_ID, TLWallPaper.class);\n registerClass(TLWallPaperSolid.CONSTRUCTOR_ID, TLWallPaperSolid.class);\n registerClass(TLWebDocument.CONSTRUCTOR_ID, TLWebDocument.class);\n registerClass(TLWebPage.CONSTRUCTOR_ID, TLWebPage.class);\n registerClass(TLWebPageEmpty.CONSTRUCTOR_ID, TLWebPageEmpty.class);\n registerClass(TLWebPageNotModified.CONSTRUCTOR_ID, TLWebPageNotModified.class);\n registerClass(TLWebPagePending.CONSTRUCTOR_ID, TLWebPagePending.class);\n }\n}\n"} {"task_id": "Java_106", "language": "Java", "task_type": "empty", "source_file": "java/github/badoualy/kotlogram/tl/src/main/java/com/github/badoualy/telegram/tl/api/TLApiContext.java", "mask_start_position": 19166, "mask_end_position": 19166, "canonical_solution": "", "pre_mask_code": "package com.github.badoualy.telegram.tl.api;\n\nimport com.github.badoualy.telegram.tl.TLContext;\nimport com.github.badoualy.telegram.tl.api.account.TLAuthorizations;\nimport com.github.badoualy.telegram.tl.api.account.TLNoPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPassword;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordInputSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPasswordSettings;\nimport com.github.badoualy.telegram.tl.api.account.TLPrivacyRules;\nimport com.github.badoualy.telegram.tl.api.account.TLTmpPassword;\nimport com.github.badoualy.telegram.tl.api.auth.TLCheckedPhone;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.auth.TLExportedAuthorization;\nimport com.github.badoualy.telegram.tl.api.auth.TLPasswordRecovery;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCode;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeApp;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeFlashCall;\nimport com.github.badoualy.telegram.tl.api.auth.TLSentCodeTypeSms;\nimport com.github.badoualy.telegram.tl.api.channels.TLChannelParticipants;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlocked;\nimport com.github.badoualy.telegram.tl.api.contacts.TLBlockedSlice;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLContactsNotModified;\nimport com.github.badoualy.telegram.tl.api.contacts.TLFound;\nimport com.github.badoualy.telegram.tl.api.contacts.TLImportedContacts;\nimport com.github.badoualy.telegram.tl.api.contacts.TLLink;\nimport com.github.badoualy.telegram.tl.api.contacts.TLResolvedPeer;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeers;\nimport com.github.badoualy.telegram.tl.api.contacts.TLTopPeersNotModified;\nimport com.github.badoualy.telegram.tl.api.help.TLAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLInviteText;\nimport com.github.badoualy.telegram.tl.api.help.TLNoAppUpdate;\nimport com.github.badoualy.telegram.tl.api.help.TLSupport;\nimport com.github.badoualy.telegram.tl.api.help.TLTermsOfService;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedHistory;\nimport com.github.badoualy.telegram.tl.api.messages.TLAffectedMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLAllStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLArchivedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotCallbackAnswer;\nimport com.github.badoualy.telegram.tl.api.messages.TLBotResults;\nimport com.github.badoualy.telegram.tl.api.messages.TLChannelMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLChats;\nimport com.github.badoualy.telegram.tl.api.messages.TLChatsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfig;\nimport com.github.badoualy.telegram.tl.api.messages.TLDhConfigNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLDialogsSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLFeaturedStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLFoundGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLHighScores;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessageEditData;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessages;\nimport com.github.badoualy.telegram.tl.api.messages.TLMessagesSlice;\nimport com.github.badoualy.telegram.tl.api.messages.TLPeerDialogs;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLRecentStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifs;\nimport com.github.badoualy.telegram.tl.api.messages.TLSavedGifsNotModified;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedFile;\nimport com.github.badoualy.telegram.tl.api.messages.TLSentEncryptedMessage;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultArchive;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickerSetInstallResultSuccess;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickers;\nimport com.github.badoualy.telegram.tl.api.messages.TLStickersNotModified;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentForm;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentReceipt;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentResult;\nimport com.github.badoualy.telegram.tl.api.payments.TLPaymentVerficationNeeded;\nimport com.github.badoualy.telegram.tl.api.payments.TLSavedInfo;\nimport com.github.badoualy.telegram.tl.api.payments.TLValidatedRequestedInfo;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotos;\nimport com.github.badoualy.telegram.tl.api.photos.TLPhotosSlice;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileGif;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileJpeg;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMov;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp3;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileMp4;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePartial;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePdf;\nimport com.github.badoualy.telegram.tl.api.storage.TLFilePng;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileUnknown;\nimport com.github.badoualy.telegram.tl.api.storage.TLFileWebp;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLChannelDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifference;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceEmpty;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceSlice;\nimport com.github.badoualy.telegram.tl.api.updates.TLDifferenceTooLong;\nimport com.github.badoualy.telegram.tl.api.updates.TLState;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLCdnFileReuploadNeeded;\nimport com.github.badoualy.telegram.tl.api.upload.TLFile;\nimport com.github.badoualy.telegram.tl.api.upload.TLFileCdnRedirect;\nimport com.github.badoualy.telegram.tl.api.upload.TLWebFile;\n\n/**\n * @author Yannick Badoual example@nnthink.com\n * @see http://example.com\n */\n@SuppressWarnings(\"unused\")\npublic class TLApiContext extends TLContext {\n\n private static TLApiContext instance;\n\n public TLApiContext() {\n super(543);\n }\n\n public static TLApiContext getInstance() {\n if (instance == null) {\n instance = new TLApiContext();\n }\n return instance;\n }\n\n @Override\n public void init() {\n registerClass(TLAuthorizations.CONSTRUCTOR_ID, TLAuthorizations.class);\n registerClass(TLNoPassword.CONSTRUCTOR_ID, TLNoPassword.class);\n registerClass(TLPassword.CONSTRUCTOR_ID, TLPassword.class);\n registerClass(TLPasswordInputSettings.CONSTRUCTOR_ID, TLPasswordInputSettings.class);\n registerClass(TLPasswordSettings.CONSTRUCTOR_ID, TLPasswordSettings.class);\n registerClass(TLPrivacyRules.CONSTRUCTOR_ID, TLPrivacyRules.class);\n registerClass(TLTmpPassword.CONSTRUCTOR_ID, TLTmpPassword.class);\n registerClass(TLAccountDaysTTL.CONSTRUCTOR_ID, TLAccountDaysTTL.class);\n registerClass(com.github.badoualy.telegram.tl.api.auth.TLAuthorization.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.auth.TLAuthorization.class);\n registerClass(TLCheckedPhone.CONSTRUCTOR_ID, TLCheckedPhone.class);\n registerClass(TLCodeTypeCall.CONSTRUCTOR_ID, TLCodeTypeCall.class);\n registerClass(TLCodeTypeFlashCall.CONSTRUCTOR_ID, TLCodeTypeFlashCall.class);\n registerClass(TLCodeTypeSms.CONSTRUCTOR_ID, TLCodeTypeSms.class);\n registerClass(TLExportedAuthorization.CONSTRUCTOR_ID, TLExportedAuthorization.class);\n registerClass(TLPasswordRecovery.CONSTRUCTOR_ID, TLPasswordRecovery.class);\n registerClass(TLSentCode.CONSTRUCTOR_ID, TLSentCode.class);\n registerClass(TLSentCodeTypeApp.CONSTRUCTOR_ID, TLSentCodeTypeApp.class);\n registerClass(TLSentCodeTypeCall.CONSTRUCTOR_ID, TLSentCodeTypeCall.class);\n registerClass(TLSentCodeTypeFlashCall.CONSTRUCTOR_ID, TLSentCodeTypeFlashCall.class);\n registerClass(TLSentCodeTypeSms.CONSTRUCTOR_ID, TLSentCodeTypeSms.class);\n registerClass(TLAuthorization.CONSTRUCTOR_ID, TLAuthorization.class);\n registerClass(TLBotCommand.CONSTRUCTOR_ID, TLBotCommand.class);\n registerClass(TLBotInfo.CONSTRUCTOR_ID, TLBotInfo.class);\n registerClass(TLBotInlineMediaResult.CONSTRUCTOR_ID, TLBotInlineMediaResult.class);\n registerClass(TLBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLBotInlineMessageMediaAuto.class);\n registerClass(TLBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLBotInlineMessageMediaContact.class);\n registerClass(TLBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLBotInlineMessageMediaGeo.class);\n registerClass(TLBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLBotInlineMessageMediaVenue.class);\n registerClass(TLBotInlineMessageText.CONSTRUCTOR_ID, TLBotInlineMessageText.class);\n registerClass(TLBotInlineResult.CONSTRUCTOR_ID, TLBotInlineResult.class);\n registerClass(TLCdnConfig.CONSTRUCTOR_ID, TLCdnConfig.class);\n registerClass(TLCdnPublicKey.CONSTRUCTOR_ID, TLCdnPublicKey.class);\n registerClass(TLChannel.CONSTRUCTOR_ID, TLChannel.class);\n registerClass(TLChannelForbidden.CONSTRUCTOR_ID, TLChannelForbidden.class);\n registerClass(TLChannelFull.CONSTRUCTOR_ID, TLChannelFull.class);\n registerClass(TLChannelMessagesFilter.CONSTRUCTOR_ID, TLChannelMessagesFilter.class);\n registerClass(TLChannelMessagesFilterEmpty.CONSTRUCTOR_ID, TLChannelMessagesFilterEmpty.class);\n registerClass(TLChannelParticipant.CONSTRUCTOR_ID, TLChannelParticipant.class);\n registerClass(TLChannelParticipantCreator.CONSTRUCTOR_ID, TLChannelParticipantCreator.class);\n registerClass(TLChannelParticipantEditor.CONSTRUCTOR_ID, TLChannelParticipantEditor.class);\n registerClass(TLChannelParticipantKicked.CONSTRUCTOR_ID, TLChannelParticipantKicked.class);\n registerClass(TLChannelParticipantModerator.CONSTRUCTOR_ID, TLChannelParticipantModerator.class);\n registerClass(TLChannelParticipantSelf.CONSTRUCTOR_ID, TLChannelParticipantSelf.class);\n registerClass(TLChannelParticipantsAdmins.CONSTRUCTOR_ID, TLChannelParticipantsAdmins.class);\n registerClass(TLChannelParticipantsBots.CONSTRUCTOR_ID, TLChannelParticipantsBots.class);\n registerClass(TLChannelParticipantsKicked.CONSTRUCTOR_ID, TLChannelParticipantsKicked.class);\n registerClass(TLChannelParticipantsRecent.CONSTRUCTOR_ID, TLChannelParticipantsRecent.class);\n registerClass(TLChannelRoleEditor.CONSTRUCTOR_ID, TLChannelRoleEditor.class);\n registerClass(TLChannelRoleEmpty.CONSTRUCTOR_ID, TLChannelRoleEmpty.class);\n registerClass(TLChannelRoleModerator.CONSTRUCTOR_ID, TLChannelRoleModerator.class);\n registerClass(com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.channels.TLChannelParticipant.class);\n registerClass(TLChannelParticipants.CONSTRUCTOR_ID, TLChannelParticipants.class);\n registerClass(TLChat.CONSTRUCTOR_ID, TLChat.class);\n registerClass(TLChatEmpty.CONSTRUCTOR_ID, TLChatEmpty.class);\n registerClass(TLChatForbidden.CONSTRUCTOR_ID, TLChatForbidden.class);\n registerClass(TLChatFull.CONSTRUCTOR_ID, TLChatFull.class);\n registerClass(TLChatInvite.CONSTRUCTOR_ID, TLChatInvite.class);\n registerClass(TLChatInviteAlready.CONSTRUCTOR_ID, TLChatInviteAlready.class);\n registerClass(TLChatInviteEmpty.CONSTRUCTOR_ID, TLChatInviteEmpty.class);\n registerClass(TLChatInviteExported.CONSTRUCTOR_ID, TLChatInviteExported.class);\n registerClass(TLChatParticipant.CONSTRUCTOR_ID, TLChatParticipant.class);\n registerClass(TLChatParticipantAdmin.CONSTRUCTOR_ID, TLChatParticipantAdmin.class);\n registerClass(TLChatParticipantCreator.CONSTRUCTOR_ID, TLChatParticipantCreator.class);\n registerClass(TLChatParticipants.CONSTRUCTOR_ID, TLChatParticipants.class);\n registerClass(TLChatParticipantsForbidden.CONSTRUCTOR_ID, TLChatParticipantsForbidden.class);\n registerClass(TLChatPhoto.CONSTRUCTOR_ID, TLChatPhoto.class);\n registerClass(TLChatPhotoEmpty.CONSTRUCTOR_ID, TLChatPhotoEmpty.class);\n registerClass(TLConfig.CONSTRUCTOR_ID, TLConfig.class);\n registerClass(TLContact.CONSTRUCTOR_ID, TLContact.class);\n registerClass(TLContactBlocked.CONSTRUCTOR_ID, TLContactBlocked.class);\n registerClass(TLContactLinkContact.CONSTRUCTOR_ID, TLContactLinkContact.class);\n registerClass(TLContactLinkHasPhone.CONSTRUCTOR_ID, TLContactLinkHasPhone.class);\n registerClass(TLContactLinkNone.CONSTRUCTOR_ID, TLContactLinkNone.class);\n registerClass(TLContactLinkUnknown.CONSTRUCTOR_ID, TLContactLinkUnknown.class);\n registerClass(TLContactStatus.CONSTRUCTOR_ID, TLContactStatus.class);\n registerClass(TLBlocked.CONSTRUCTOR_ID, TLBlocked.class);\n registerClass(TLBlockedSlice.CONSTRUCTOR_ID, TLBlockedSlice.class);\n registerClass(TLContacts.CONSTRUCTOR_ID, TLContacts.class);\n registerClass(TLContactsNotModified.CONSTRUCTOR_ID, TLContactsNotModified.class);\n registerClass(TLFound.CONSTRUCTOR_ID, TLFound.class);\n registerClass(TLImportedContacts.CONSTRUCTOR_ID, TLImportedContacts.class);\n registerClass(TLLink.CONSTRUCTOR_ID, TLLink.class);\n registerClass(TLResolvedPeer.CONSTRUCTOR_ID, TLResolvedPeer.class);\n registerClass(TLTopPeers.CONSTRUCTOR_ID, TLTopPeers.class);\n registerClass(TLTopPeersNotModified.CONSTRUCTOR_ID, TLTopPeersNotModified.class);\n registerClass(TLDataJSON.CONSTRUCTOR_ID, TLDataJSON.class);\n registerClass(TLDcOption.CONSTRUCTOR_ID, TLDcOption.class);\n registerClass(TLDialog.CONSTRUCTOR_ID, TLDialog.class);\n registerClass(TLDisabledFeature.CONSTRUCTOR_ID, TLDisabledFeature.class);\n registerClass(TLDocument.CONSTRUCTOR_ID, TLDocument.class);\n registerClass(TLDocumentAttributeAnimated.CONSTRUCTOR_ID, TLDocumentAttributeAnimated.class);\n registerClass(TLDocumentAttributeAudio.CONSTRUCTOR_ID, TLDocumentAttributeAudio.class);\n registerClass(TLDocumentAttributeFilename.CONSTRUCTOR_ID, TLDocumentAttributeFilename.class);\n registerClass(TLDocumentAttributeHasStickers.CONSTRUCTOR_ID, TLDocumentAttributeHasStickers.class);\n registerClass(TLDocumentAttributeImageSize.CONSTRUCTOR_ID, TLDocumentAttributeImageSize.class);\n registerClass(TLDocumentAttributeSticker.CONSTRUCTOR_ID, TLDocumentAttributeSticker.class);\n registerClass(TLDocumentAttributeVideo.CONSTRUCTOR_ID, TLDocumentAttributeVideo.class);\n registerClass(TLDocumentEmpty.CONSTRUCTOR_ID, TLDocumentEmpty.class);\n registerClass(TLDraftMessage.CONSTRUCTOR_ID, TLDraftMessage.class);\n registerClass(TLDraftMessageEmpty.CONSTRUCTOR_ID, TLDraftMessageEmpty.class);\n registerClass(TLEncryptedChat.CONSTRUCTOR_ID, TLEncryptedChat.class);\n registerClass(TLEncryptedChatDiscarded.CONSTRUCTOR_ID, TLEncryptedChatDiscarded.class);\n registerClass(TLEncryptedChatEmpty.CONSTRUCTOR_ID, TLEncryptedChatEmpty.class);\n registerClass(TLEncryptedChatRequested.CONSTRUCTOR_ID, TLEncryptedChatRequested.class);\n registerClass(TLEncryptedChatWaiting.CONSTRUCTOR_ID, TLEncryptedChatWaiting.class);\n registerClass(TLEncryptedFile.CONSTRUCTOR_ID, TLEncryptedFile.class);\n registerClass(TLEncryptedFileEmpty.CONSTRUCTOR_ID, TLEncryptedFileEmpty.class);\n registerClass(TLEncryptedMessage.CONSTRUCTOR_ID, TLEncryptedMessage.class);\n registerClass(TLEncryptedMessageService.CONSTRUCTOR_ID, TLEncryptedMessageService.class);\n registerClass(TLExportedMessageLink.CONSTRUCTOR_ID, TLExportedMessageLink.class);\n registerClass(TLFileLocation.CONSTRUCTOR_ID, TLFileLocation.class);\n registerClass(TLFileLocationUnavailable.CONSTRUCTOR_ID, TLFileLocationUnavailable.class);\n registerClass(TLFoundGif.CONSTRUCTOR_ID, TLFoundGif.class);\n registerClass(TLFoundGifCached.CONSTRUCTOR_ID, TLFoundGifCached.class);\n registerClass(TLGame.CONSTRUCTOR_ID, TLGame.class);\n registerClass(TLGeoPoint.CONSTRUCTOR_ID, TLGeoPoint.class);\n registerClass(TLGeoPointEmpty.CONSTRUCTOR_ID, TLGeoPointEmpty.class);\n registerClass(TLAppUpdate.CONSTRUCTOR_ID, TLAppUpdate.class);\n registerClass(TLInviteText.CONSTRUCTOR_ID, TLInviteText.class);\n registerClass(TLNoAppUpdate.CONSTRUCTOR_ID, TLNoAppUpdate.class);\n registerClass(TLSupport.CONSTRUCTOR_ID, TLSupport.class);\n registerClass(TLTermsOfService.CONSTRUCTOR_ID, TLTermsOfService.class);\n registerClass(TLHighScore.CONSTRUCTOR_ID, TLHighScore.class);\n registerClass(TLImportedContact.CONSTRUCTOR_ID, TLImportedContact.class);\n registerClass(TLInlineBotSwitchPM.CONSTRUCTOR_ID, TLInlineBotSwitchPM.class);\n registerClass(TLInputAppEvent.CONSTRUCTOR_ID, TLInputAppEvent.class);\n registerClass(TLInputBotInlineMessageGame.CONSTRUCTOR_ID, TLInputBotInlineMessageGame.class);\n registerClass(TLInputBotInlineMessageID.CONSTRUCTOR_ID, TLInputBotInlineMessageID.class);\n registerClass(TLInputBotInlineMessageMediaAuto.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaAuto.class);\n registerClass(TLInputBotInlineMessageMediaContact.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaContact.class);\n registerClass(TLInputBotInlineMessageMediaGeo.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaGeo.class);\n registerClass(TLInputBotInlineMessageMediaVenue.CONSTRUCTOR_ID, TLInputBotInlineMessageMediaVenue.class);\n registerClass(TLInputBotInlineMessageText.CONSTRUCTOR_ID, TLInputBotInlineMessageText.class);\n registerClass(TLInputBotInlineResult.CONSTRUCTOR_ID, TLInputBotInlineResult.class);\n registerClass(TLInputBotInlineResultDocument.CONSTRUCTOR_ID, TLInputBotInlineResultDocument.class);\n registerClass(TLInputBotInlineResultGame.CONSTRUCTOR_ID, TLInputBotInlineResultGame.class);\n registerClass(TLInputBotInlineResultPhoto.CONSTRUCTOR_ID, TLInputBotInlineResultPhoto.class);\n registerClass(TLInputChannel.CONSTRUCTOR_ID, TLInputChannel.class);\n registerClass(TLInputChannelEmpty.CONSTRUCTOR_ID, TLInputChann", "post_mask_code": "elEmpty.class);\n registerClass(TLInputChatPhoto.CONSTRUCTOR_ID, TLInputChatPhoto.class);\n registerClass(TLInputChatPhotoEmpty.CONSTRUCTOR_ID, TLInputChatPhotoEmpty.class);\n registerClass(TLInputChatUploadedPhoto.CONSTRUCTOR_ID, TLInputChatUploadedPhoto.class);\n registerClass(TLInputDocument.CONSTRUCTOR_ID, TLInputDocument.class);\n registerClass(TLInputDocumentEmpty.CONSTRUCTOR_ID, TLInputDocumentEmpty.class);\n registerClass(TLInputDocumentFileLocation.CONSTRUCTOR_ID, TLInputDocumentFileLocation.class);\n registerClass(TLInputEncryptedChat.CONSTRUCTOR_ID, TLInputEncryptedChat.class);\n registerClass(TLInputEncryptedFile.CONSTRUCTOR_ID, TLInputEncryptedFile.class);\n registerClass(TLInputEncryptedFileBigUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileBigUploaded.class);\n registerClass(TLInputEncryptedFileEmpty.CONSTRUCTOR_ID, TLInputEncryptedFileEmpty.class);\n registerClass(TLInputEncryptedFileLocation.CONSTRUCTOR_ID, TLInputEncryptedFileLocation.class);\n registerClass(TLInputEncryptedFileUploaded.CONSTRUCTOR_ID, TLInputEncryptedFileUploaded.class);\n registerClass(TLInputFile.CONSTRUCTOR_ID, TLInputFile.class);\n registerClass(TLInputFileBig.CONSTRUCTOR_ID, TLInputFileBig.class);\n registerClass(TLInputFileLocation.CONSTRUCTOR_ID, TLInputFileLocation.class);\n registerClass(TLInputGameID.CONSTRUCTOR_ID, TLInputGameID.class);\n registerClass(TLInputGameShortName.CONSTRUCTOR_ID, TLInputGameShortName.class);\n registerClass(TLInputGeoPoint.CONSTRUCTOR_ID, TLInputGeoPoint.class);\n registerClass(TLInputGeoPointEmpty.CONSTRUCTOR_ID, TLInputGeoPointEmpty.class);\n registerClass(TLInputMediaContact.CONSTRUCTOR_ID, TLInputMediaContact.class);\n registerClass(TLInputMediaDocument.CONSTRUCTOR_ID, TLInputMediaDocument.class);\n registerClass(TLInputMediaDocumentExternal.CONSTRUCTOR_ID, TLInputMediaDocumentExternal.class);\n registerClass(TLInputMediaEmpty.CONSTRUCTOR_ID, TLInputMediaEmpty.class);\n registerClass(TLInputMediaGame.CONSTRUCTOR_ID, TLInputMediaGame.class);\n registerClass(TLInputMediaGeoPoint.CONSTRUCTOR_ID, TLInputMediaGeoPoint.class);\n registerClass(TLInputMediaGifExternal.CONSTRUCTOR_ID, TLInputMediaGifExternal.class);\n registerClass(TLInputMediaInvoice.CONSTRUCTOR_ID, TLInputMediaInvoice.class);\n registerClass(TLInputMediaPhoto.CONSTRUCTOR_ID, TLInputMediaPhoto.class);\n registerClass(TLInputMediaPhotoExternal.CONSTRUCTOR_ID, TLInputMediaPhotoExternal.class);\n registerClass(TLInputMediaUploadedDocument.CONSTRUCTOR_ID, TLInputMediaUploadedDocument.class);\n registerClass(TLInputMediaUploadedPhoto.CONSTRUCTOR_ID, TLInputMediaUploadedPhoto.class);\n registerClass(TLInputMediaUploadedThumbDocument.CONSTRUCTOR_ID, TLInputMediaUploadedThumbDocument.class);\n registerClass(TLInputMediaVenue.CONSTRUCTOR_ID, TLInputMediaVenue.class);\n registerClass(TLInputMessageEntityMentionName.CONSTRUCTOR_ID, TLInputMessageEntityMentionName.class);\n registerClass(TLInputMessagesFilterChatPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterChatPhotos.class);\n registerClass(TLInputMessagesFilterDocument.CONSTRUCTOR_ID, TLInputMessagesFilterDocument.class);\n registerClass(TLInputMessagesFilterEmpty.CONSTRUCTOR_ID, TLInputMessagesFilterEmpty.class);\n registerClass(TLInputMessagesFilterGif.CONSTRUCTOR_ID, TLInputMessagesFilterGif.class);\n registerClass(TLInputMessagesFilterMusic.CONSTRUCTOR_ID, TLInputMessagesFilterMusic.class);\n registerClass(TLInputMessagesFilterPhoneCalls.CONSTRUCTOR_ID, TLInputMessagesFilterPhoneCalls.class);\n registerClass(TLInputMessagesFilterPhotoVideo.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideo.class);\n registerClass(TLInputMessagesFilterPhotoVideoDocuments.CONSTRUCTOR_ID, TLInputMessagesFilterPhotoVideoDocuments.class);\n registerClass(TLInputMessagesFilterPhotos.CONSTRUCTOR_ID, TLInputMessagesFilterPhotos.class);\n registerClass(TLInputMessagesFilterRoundVideo.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVideo.class);\n registerClass(TLInputMessagesFilterRoundVoice.CONSTRUCTOR_ID, TLInputMessagesFilterRoundVoice.class);\n registerClass(TLInputMessagesFilterUrl.CONSTRUCTOR_ID, TLInputMessagesFilterUrl.class);\n registerClass(TLInputMessagesFilterVideo.CONSTRUCTOR_ID, TLInputMessagesFilterVideo.class);\n registerClass(TLInputMessagesFilterVoice.CONSTRUCTOR_ID, TLInputMessagesFilterVoice.class);\n registerClass(TLInputNotifyAll.CONSTRUCTOR_ID, TLInputNotifyAll.class);\n registerClass(TLInputNotifyChats.CONSTRUCTOR_ID, TLInputNotifyChats.class);\n registerClass(TLInputNotifyPeer.CONSTRUCTOR_ID, TLInputNotifyPeer.class);\n registerClass(TLInputNotifyUsers.CONSTRUCTOR_ID, TLInputNotifyUsers.class);\n registerClass(TLInputPaymentCredentials.CONSTRUCTOR_ID, TLInputPaymentCredentials.class);\n registerClass(TLInputPaymentCredentialsSaved.CONSTRUCTOR_ID, TLInputPaymentCredentialsSaved.class);\n registerClass(TLInputPeerChannel.CONSTRUCTOR_ID, TLInputPeerChannel.class);\n registerClass(TLInputPeerChat.CONSTRUCTOR_ID, TLInputPeerChat.class);\n registerClass(TLInputPeerEmpty.CONSTRUCTOR_ID, TLInputPeerEmpty.class);\n registerClass(TLInputPeerNotifyEventsAll.CONSTRUCTOR_ID, TLInputPeerNotifyEventsAll.class);\n registerClass(TLInputPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLInputPeerNotifyEventsEmpty.class);\n registerClass(TLInputPeerNotifySettings.CONSTRUCTOR_ID, TLInputPeerNotifySettings.class);\n registerClass(TLInputPeerSelf.CONSTRUCTOR_ID, TLInputPeerSelf.class);\n registerClass(TLInputPeerUser.CONSTRUCTOR_ID, TLInputPeerUser.class);\n registerClass(TLInputPhoneCall.CONSTRUCTOR_ID, TLInputPhoneCall.class);\n registerClass(TLInputPhoneContact.CONSTRUCTOR_ID, TLInputPhoneContact.class);\n registerClass(TLInputPhoto.CONSTRUCTOR_ID, TLInputPhoto.class);\n registerClass(TLInputPhotoEmpty.CONSTRUCTOR_ID, TLInputPhotoEmpty.class);\n registerClass(TLInputPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLInputPrivacyKeyChatInvite.class);\n registerClass(TLInputPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLInputPrivacyKeyPhoneCall.class);\n registerClass(TLInputPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLInputPrivacyKeyStatusTimestamp.class);\n registerClass(TLInputPrivacyValueAllowAll.CONSTRUCTOR_ID, TLInputPrivacyValueAllowAll.class);\n registerClass(TLInputPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueAllowContacts.class);\n registerClass(TLInputPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueAllowUsers.class);\n registerClass(TLInputPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowAll.class);\n registerClass(TLInputPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowContacts.class);\n registerClass(TLInputPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLInputPrivacyValueDisallowUsers.class);\n registerClass(TLInputReportReasonOther.CONSTRUCTOR_ID, TLInputReportReasonOther.class);\n registerClass(TLInputReportReasonPornography.CONSTRUCTOR_ID, TLInputReportReasonPornography.class);\n registerClass(TLInputReportReasonSpam.CONSTRUCTOR_ID, TLInputReportReasonSpam.class);\n registerClass(TLInputReportReasonViolence.CONSTRUCTOR_ID, TLInputReportReasonViolence.class);\n registerClass(TLInputStickerSetEmpty.CONSTRUCTOR_ID, TLInputStickerSetEmpty.class);\n registerClass(TLInputStickerSetID.CONSTRUCTOR_ID, TLInputStickerSetID.class);\n registerClass(TLInputStickerSetShortName.CONSTRUCTOR_ID, TLInputStickerSetShortName.class);\n registerClass(TLInputStickeredMediaDocument.CONSTRUCTOR_ID, TLInputStickeredMediaDocument.class);\n registerClass(TLInputStickeredMediaPhoto.CONSTRUCTOR_ID, TLInputStickeredMediaPhoto.class);\n registerClass(TLInputUser.CONSTRUCTOR_ID, TLInputUser.class);\n registerClass(TLInputUserEmpty.CONSTRUCTOR_ID, TLInputUserEmpty.class);\n registerClass(TLInputUserSelf.CONSTRUCTOR_ID, TLInputUserSelf.class);\n registerClass(TLInputWebDocument.CONSTRUCTOR_ID, TLInputWebDocument.class);\n registerClass(TLInputWebFileLocation.CONSTRUCTOR_ID, TLInputWebFileLocation.class);\n registerClass(TLInvoice.CONSTRUCTOR_ID, TLInvoice.class);\n registerClass(TLKeyboardButton.CONSTRUCTOR_ID, TLKeyboardButton.class);\n registerClass(TLKeyboardButtonBuy.CONSTRUCTOR_ID, TLKeyboardButtonBuy.class);\n registerClass(TLKeyboardButtonCallback.CONSTRUCTOR_ID, TLKeyboardButtonCallback.class);\n registerClass(TLKeyboardButtonGame.CONSTRUCTOR_ID, TLKeyboardButtonGame.class);\n registerClass(TLKeyboardButtonRequestGeoLocation.CONSTRUCTOR_ID, TLKeyboardButtonRequestGeoLocation.class);\n registerClass(TLKeyboardButtonRequestPhone.CONSTRUCTOR_ID, TLKeyboardButtonRequestPhone.class);\n registerClass(TLKeyboardButtonRow.CONSTRUCTOR_ID, TLKeyboardButtonRow.class);\n registerClass(TLKeyboardButtonSwitchInline.CONSTRUCTOR_ID, TLKeyboardButtonSwitchInline.class);\n registerClass(TLKeyboardButtonUrl.CONSTRUCTOR_ID, TLKeyboardButtonUrl.class);\n registerClass(TLLabeledPrice.CONSTRUCTOR_ID, TLLabeledPrice.class);\n registerClass(TLMaskCoords.CONSTRUCTOR_ID, TLMaskCoords.class);\n registerClass(TLMessage.CONSTRUCTOR_ID, TLMessage.class);\n registerClass(TLMessageActionChannelCreate.CONSTRUCTOR_ID, TLMessageActionChannelCreate.class);\n registerClass(TLMessageActionChannelMigrateFrom.CONSTRUCTOR_ID, TLMessageActionChannelMigrateFrom.class);\n registerClass(TLMessageActionChatAddUser.CONSTRUCTOR_ID, TLMessageActionChatAddUser.class);\n registerClass(TLMessageActionChatCreate.CONSTRUCTOR_ID, TLMessageActionChatCreate.class);\n registerClass(TLMessageActionChatDeletePhoto.CONSTRUCTOR_ID, TLMessageActionChatDeletePhoto.class);\n registerClass(TLMessageActionChatDeleteUser.CONSTRUCTOR_ID, TLMessageActionChatDeleteUser.class);\n registerClass(TLMessageActionChatEditPhoto.CONSTRUCTOR_ID, TLMessageActionChatEditPhoto.class);\n registerClass(TLMessageActionChatEditTitle.CONSTRUCTOR_ID, TLMessageActionChatEditTitle.class);\n registerClass(TLMessageActionChatJoinedByLink.CONSTRUCTOR_ID, TLMessageActionChatJoinedByLink.class);\n registerClass(TLMessageActionChatMigrateTo.CONSTRUCTOR_ID, TLMessageActionChatMigrateTo.class);\n registerClass(TLMessageActionEmpty.CONSTRUCTOR_ID, TLMessageActionEmpty.class);\n registerClass(TLMessageActionGameScore.CONSTRUCTOR_ID, TLMessageActionGameScore.class);\n registerClass(TLMessageActionHistoryClear.CONSTRUCTOR_ID, TLMessageActionHistoryClear.class);\n registerClass(TLMessageActionPaymentSent.CONSTRUCTOR_ID, TLMessageActionPaymentSent.class);\n registerClass(TLMessageActionPaymentSentMe.CONSTRUCTOR_ID, TLMessageActionPaymentSentMe.class);\n registerClass(TLMessageActionPhoneCall.CONSTRUCTOR_ID, TLMessageActionPhoneCall.class);\n registerClass(TLMessageActionPinMessage.CONSTRUCTOR_ID, TLMessageActionPinMessage.class);\n registerClass(TLMessageEmpty.CONSTRUCTOR_ID, TLMessageEmpty.class);\n registerClass(TLMessageEntityBold.CONSTRUCTOR_ID, TLMessageEntityBold.class);\n registerClass(TLMessageEntityBotCommand.CONSTRUCTOR_ID, TLMessageEntityBotCommand.class);\n registerClass(TLMessageEntityCode.CONSTRUCTOR_ID, TLMessageEntityCode.class);\n registerClass(TLMessageEntityEmail.CONSTRUCTOR_ID, TLMessageEntityEmail.class);\n registerClass(TLMessageEntityHashtag.CONSTRUCTOR_ID, TLMessageEntityHashtag.class);\n registerClass(TLMessageEntityItalic.CONSTRUCTOR_ID, TLMessageEntityItalic.class);\n registerClass(TLMessageEntityMention.CONSTRUCTOR_ID, TLMessageEntityMention.class);\n registerClass(TLMessageEntityMentionName.CONSTRUCTOR_ID, TLMessageEntityMentionName.class);\n registerClass(TLMessageEntityPre.CONSTRUCTOR_ID, TLMessageEntityPre.class);\n registerClass(TLMessageEntityTextUrl.CONSTRUCTOR_ID, TLMessageEntityTextUrl.class);\n registerClass(TLMessageEntityUnknown.CONSTRUCTOR_ID, TLMessageEntityUnknown.class);\n registerClass(TLMessageEntityUrl.CONSTRUCTOR_ID, TLMessageEntityUrl.class);\n registerClass(TLMessageFwdHeader.CONSTRUCTOR_ID, TLMessageFwdHeader.class);\n registerClass(TLMessageMediaContact.CONSTRUCTOR_ID, TLMessageMediaContact.class);\n registerClass(TLMessageMediaDocument.CONSTRUCTOR_ID, TLMessageMediaDocument.class);\n registerClass(TLMessageMediaEmpty.CONSTRUCTOR_ID, TLMessageMediaEmpty.class);\n registerClass(TLMessageMediaGame.CONSTRUCTOR_ID, TLMessageMediaGame.class);\n registerClass(TLMessageMediaGeo.CONSTRUCTOR_ID, TLMessageMediaGeo.class);\n registerClass(TLMessageMediaInvoice.CONSTRUCTOR_ID, TLMessageMediaInvoice.class);\n registerClass(TLMessageMediaPhoto.CONSTRUCTOR_ID, TLMessageMediaPhoto.class);\n registerClass(TLMessageMediaUnsupported.CONSTRUCTOR_ID, TLMessageMediaUnsupported.class);\n registerClass(TLMessageMediaVenue.CONSTRUCTOR_ID, TLMessageMediaVenue.class);\n registerClass(TLMessageMediaWebPage.CONSTRUCTOR_ID, TLMessageMediaWebPage.class);\n registerClass(TLMessageRange.CONSTRUCTOR_ID, TLMessageRange.class);\n registerClass(TLMessageService.CONSTRUCTOR_ID, TLMessageService.class);\n registerClass(TLAffectedHistory.CONSTRUCTOR_ID, TLAffectedHistory.class);\n registerClass(TLAffectedMessages.CONSTRUCTOR_ID, TLAffectedMessages.class);\n registerClass(TLAllStickers.CONSTRUCTOR_ID, TLAllStickers.class);\n registerClass(TLAllStickersNotModified.CONSTRUCTOR_ID, TLAllStickersNotModified.class);\n registerClass(TLArchivedStickers.CONSTRUCTOR_ID, TLArchivedStickers.class);\n registerClass(TLBotCallbackAnswer.CONSTRUCTOR_ID, TLBotCallbackAnswer.class);\n registerClass(TLBotResults.CONSTRUCTOR_ID, TLBotResults.class);\n registerClass(TLChannelMessages.CONSTRUCTOR_ID, TLChannelMessages.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLChatFull.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLChatFull.class);\n registerClass(TLChats.CONSTRUCTOR_ID, TLChats.class);\n registerClass(TLChatsSlice.CONSTRUCTOR_ID, TLChatsSlice.class);\n registerClass(TLDhConfig.CONSTRUCTOR_ID, TLDhConfig.class);\n registerClass(TLDhConfigNotModified.CONSTRUCTOR_ID, TLDhConfigNotModified.class);\n registerClass(TLDialogs.CONSTRUCTOR_ID, TLDialogs.class);\n registerClass(TLDialogsSlice.CONSTRUCTOR_ID, TLDialogsSlice.class);\n registerClass(TLFeaturedStickers.CONSTRUCTOR_ID, TLFeaturedStickers.class);\n registerClass(TLFeaturedStickersNotModified.CONSTRUCTOR_ID, TLFeaturedStickersNotModified.class);\n registerClass(TLFoundGifs.CONSTRUCTOR_ID, TLFoundGifs.class);\n registerClass(TLHighScores.CONSTRUCTOR_ID, TLHighScores.class);\n registerClass(TLMessageEditData.CONSTRUCTOR_ID, TLMessageEditData.class);\n registerClass(TLMessages.CONSTRUCTOR_ID, TLMessages.class);\n registerClass(TLMessagesSlice.CONSTRUCTOR_ID, TLMessagesSlice.class);\n registerClass(TLPeerDialogs.CONSTRUCTOR_ID, TLPeerDialogs.class);\n registerClass(TLRecentStickers.CONSTRUCTOR_ID, TLRecentStickers.class);\n registerClass(TLRecentStickersNotModified.CONSTRUCTOR_ID, TLRecentStickersNotModified.class);\n registerClass(TLSavedGifs.CONSTRUCTOR_ID, TLSavedGifs.class);\n registerClass(TLSavedGifsNotModified.CONSTRUCTOR_ID, TLSavedGifsNotModified.class);\n registerClass(TLSentEncryptedFile.CONSTRUCTOR_ID, TLSentEncryptedFile.class);\n registerClass(TLSentEncryptedMessage.CONSTRUCTOR_ID, TLSentEncryptedMessage.class);\n registerClass(com.github.badoualy.telegram.tl.api.messages.TLStickerSet.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.messages.TLStickerSet.class);\n registerClass(TLStickerSetInstallResultArchive.CONSTRUCTOR_ID, TLStickerSetInstallResultArchive.class);\n registerClass(TLStickerSetInstallResultSuccess.CONSTRUCTOR_ID, TLStickerSetInstallResultSuccess.class);\n registerClass(TLStickers.CONSTRUCTOR_ID, TLStickers.class);\n registerClass(TLStickersNotModified.CONSTRUCTOR_ID, TLStickersNotModified.class);\n registerClass(TLNearestDc.CONSTRUCTOR_ID, TLNearestDc.class);\n registerClass(TLNotifyAll.CONSTRUCTOR_ID, TLNotifyAll.class);\n registerClass(TLNotifyChats.CONSTRUCTOR_ID, TLNotifyChats.class);\n registerClass(TLNotifyPeer.CONSTRUCTOR_ID, TLNotifyPeer.class);\n registerClass(TLNotifyUsers.CONSTRUCTOR_ID, TLNotifyUsers.class);\n registerClass(TLPageBlockAnchor.CONSTRUCTOR_ID, TLPageBlockAnchor.class);\n registerClass(TLPageBlockAuthorDate.CONSTRUCTOR_ID, TLPageBlockAuthorDate.class);\n registerClass(TLPageBlockBlockquote.CONSTRUCTOR_ID, TLPageBlockBlockquote.class);\n registerClass(TLPageBlockChannel.CONSTRUCTOR_ID, TLPageBlockChannel.class);\n registerClass(TLPageBlockCollage.CONSTRUCTOR_ID, TLPageBlockCollage.class);\n registerClass(TLPageBlockCover.CONSTRUCTOR_ID, TLPageBlockCover.class);\n registerClass(TLPageBlockDivider.CONSTRUCTOR_ID, TLPageBlockDivider.class);\n registerClass(TLPageBlockEmbed.CONSTRUCTOR_ID, TLPageBlockEmbed.class);\n registerClass(TLPageBlockEmbedPost.CONSTRUCTOR_ID, TLPageBlockEmbedPost.class);\n registerClass(TLPageBlockFooter.CONSTRUCTOR_ID, TLPageBlockFooter.class);\n registerClass(TLPageBlockHeader.CONSTRUCTOR_ID, TLPageBlockHeader.class);\n registerClass(TLPageBlockList.CONSTRUCTOR_ID, TLPageBlockList.class);\n registerClass(TLPageBlockParagraph.CONSTRUCTOR_ID, TLPageBlockParagraph.class);\n registerClass(TLPageBlockPhoto.CONSTRUCTOR_ID, TLPageBlockPhoto.class);\n registerClass(TLPageBlockPreformatted.CONSTRUCTOR_ID, TLPageBlockPreformatted.class);\n registerClass(TLPageBlockPullquote.CONSTRUCTOR_ID, TLPageBlockPullquote.class);\n registerClass(TLPageBlockSlideshow.CONSTRUCTOR_ID, TLPageBlockSlideshow.class);\n registerClass(TLPageBlockSubheader.CONSTRUCTOR_ID, TLPageBlockSubheader.class);\n registerClass(TLPageBlockSubtitle.CONSTRUCTOR_ID, TLPageBlockSubtitle.class);\n registerClass(TLPageBlockTitle.CONSTRUCTOR_ID, TLPageBlockTitle.class);\n registerClass(TLPageBlockUnsupported.CONSTRUCTOR_ID, TLPageBlockUnsupported.class);\n registerClass(TLPageBlockVideo.CONSTRUCTOR_ID, TLPageBlockVideo.class);\n registerClass(TLPageFull.CONSTRUCTOR_ID, TLPageFull.class);\n registerClass(TLPagePart.CONSTRUCTOR_ID, TLPagePart.class);\n registerClass(TLPaymentCharge.CONSTRUCTOR_ID, TLPaymentCharge.class);\n registerClass(TLPaymentRequestedInfo.CONSTRUCTOR_ID, TLPaymentRequestedInfo.class);\n registerClass(TLPaymentSavedCredentialsCard.CONSTRUCTOR_ID, TLPaymentSavedCredentialsCard.class);\n registerClass(TLPaymentForm.CONSTRUCTOR_ID, TLPaymentForm.class);\n registerClass(TLPaymentReceipt.CONSTRUCTOR_ID, TLPaymentReceipt.class);\n registerClass(TLPaymentResult.CONSTRUCTOR_ID, TLPaymentResult.class);\n registerClass(TLPaymentVerficationNeeded.CONSTRUCTOR_ID, TLPaymentVerficationNeeded.class);\n registerClass(TLSavedInfo.CONSTRUCTOR_ID, TLSavedInfo.class);\n registerClass(TLValidatedRequestedInfo.CONSTRUCTOR_ID, TLValidatedRequestedInfo.class);\n registerClass(TLPeerChannel.CONSTRUCTOR_ID, TLPeerChannel.class);\n registerClass(TLPeerChat.CONSTRUCTOR_ID, TLPeerChat.class);\n registerClass(TLPeerNotifyEventsAll.CONSTRUCTOR_ID, TLPeerNotifyEventsAll.class);\n registerClass(TLPeerNotifyEventsEmpty.CONSTRUCTOR_ID, TLPeerNotifyEventsEmpty.class);\n registerClass(TLPeerNotifySettings.CONSTRUCTOR_ID, TLPeerNotifySettings.class);\n registerClass(TLPeerNotifySettingsEmpty.CONSTRUCTOR_ID, TLPeerNotifySettingsEmpty.class);\n registerClass(TLPeerSettings.CONSTRUCTOR_ID, TLPeerSettings.class);\n registerClass(TLPeerUser.CONSTRUCTOR_ID, TLPeerUser.class);\n registerClass(com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.phone.TLPhoneCall.class);\n registerClass(TLPhoneCall.CONSTRUCTOR_ID, TLPhoneCall.class);\n registerClass(TLPhoneCallAccepted.CONSTRUCTOR_ID, TLPhoneCallAccepted.class);\n registerClass(TLPhoneCallDiscardReasonBusy.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonBusy.class);\n registerClass(TLPhoneCallDiscardReasonDisconnect.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonDisconnect.class);\n registerClass(TLPhoneCallDiscardReasonHangup.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonHangup.class);\n registerClass(TLPhoneCallDiscardReasonMissed.CONSTRUCTOR_ID, TLPhoneCallDiscardReasonMissed.class);\n registerClass(TLPhoneCallDiscarded.CONSTRUCTOR_ID, TLPhoneCallDiscarded.class);\n registerClass(TLPhoneCallEmpty.CONSTRUCTOR_ID, TLPhoneCallEmpty.class);\n registerClass(TLPhoneCallProtocol.CONSTRUCTOR_ID, TLPhoneCallProtocol.class);\n registerClass(TLPhoneCallRequested.CONSTRUCTOR_ID, TLPhoneCallRequested.class);\n registerClass(TLPhoneCallWaiting.CONSTRUCTOR_ID, TLPhoneCallWaiting.class);\n registerClass(TLPhoneConnection.CONSTRUCTOR_ID, TLPhoneConnection.class);\n registerClass(TLPhoto.CONSTRUCTOR_ID, TLPhoto.class);\n registerClass(TLPhotoCachedSize.CONSTRUCTOR_ID, TLPhotoCachedSize.class);\n registerClass(TLPhotoEmpty.CONSTRUCTOR_ID, TLPhotoEmpty.class);\n registerClass(TLPhotoSize.CONSTRUCTOR_ID, TLPhotoSize.class);\n registerClass(TLPhotoSizeEmpty.CONSTRUCTOR_ID, TLPhotoSizeEmpty.class);\n registerClass(com.github.badoualy.telegram.tl.api.photos.TLPhoto.CONSTRUCTOR_ID, com.github.badoualy.telegram.tl.api.photos.TLPhoto.class);\n registerClass(TLPhotos.CONSTRUCTOR_ID, TLPhotos.class);\n registerClass(TLPhotosSlice.CONSTRUCTOR_ID, TLPhotosSlice.class);\n registerClass(TLPostAddress.CONSTRUCTOR_ID, TLPostAddress.class);\n registerClass(TLPrivacyKeyChatInvite.CONSTRUCTOR_ID, TLPrivacyKeyChatInvite.class);\n registerClass(TLPrivacyKeyPhoneCall.CONSTRUCTOR_ID, TLPrivacyKeyPhoneCall.class);\n registerClass(TLPrivacyKeyStatusTimestamp.CONSTRUCTOR_ID, TLPrivacyKeyStatusTimestamp.class);\n registerClass(TLPrivacyValueAllowAll.CONSTRUCTOR_ID, TLPrivacyValueAllowAll.class);\n registerClass(TLPrivacyValueAllowContacts.CONSTRUCTOR_ID, TLPrivacyValueAllowContacts.class);\n registerClass(TLPrivacyValueAllowUsers.CONSTRUCTOR_ID, TLPrivacyValueAllowUsers.class);\n registerClass(TLPrivacyValueDisallowAll.CONSTRUCTOR_ID, TLPrivacyValueDisallowAll.class);\n registerClass(TLPrivacyValueDisallowContacts.CONSTRUCTOR_ID, TLPrivacyValueDisallowContacts.class);\n registerClass(TLPrivacyValueDisallowUsers.CONSTRUCTOR_ID, TLPrivacyValueDisallowUsers.class);\n registerClass(TLReceivedNotifyMessage.CONSTRUCTOR_ID, TLReceivedNotifyMessage.class);\n registerClass(TLReplyInlineMarkup.CONSTRUCTOR_ID, TLReplyInlineMarkup.class);\n registerClass(TLReplyKeyboardForceReply.CONSTRUCTOR_ID, TLReplyKeyboardForceReply.class);\n registerClass(TLReplyKeyboardHide.CONSTRUCTOR_ID, TLReplyKeyboardHide.class);\n registerClass(TLReplyKeyboardMarkup.CONSTRUCTOR_ID, TLReplyKeyboardMarkup.class);\n registerClass(TLSendMessageCancelAction.CONSTRUCTOR_ID, TLSendMessageCancelAction.class);\n registerClass(TLSendMessageChooseContactAction.CONSTRUCTOR_ID, TLSendMessageChooseContactAction.class);\n registerClass(TLSendMessageGamePlayAction.CONSTRUCTOR_ID, TLSendMessageGamePlayAction.class);\n registerClass(TLSendMessageGeoLocationAction.CONSTRUCTOR_ID, TLSendMessageGeoLocationAction.class);\n registerClass(TLSendMessageRecordAudioAction.CONSTRUCTOR_ID, TLSendMessageRecordAudioAction.class);\n registerClass(TLSendMessageRecordRoundAction.CONSTRUCTOR_ID, TLSendMessageRecordRoundAction.class);\n registerClass(TLSendMessageRecordVideoAction.CONSTRUCTOR_ID, TLSendMessageRecordVideoAction.class);\n registerClass(TLSendMessageTypingAction.CONSTRUCTOR_ID, TLSendMessageTypingAction.class);\n registerClass(TLSendMessageUploadAudioAction.CONSTRUCTOR_ID, TLSendMessageUploadAudioAction.class);\n registerClass(TLSendMessageUploadDocumentAction.CONSTRUCTOR_ID, TLSendMessageUploadDocumentAction.class);\n registerClass(TLSendMessageUploadPhotoAction.CONSTRUCTOR_ID, TLSendMessageUploadPhotoAction.class);\n registerClass(TLSendMessageUploadRoundAction.CONSTRUCTOR_ID, TLSendMessageUploadRoundAction.class);\n registerClass(TLSendMessageUploadVideoAction.CONSTRUCTOR_ID, TLSendMessageUploadVideoAction.class);\n registerClass(TLShippingOption.CONSTRUCTOR_ID, TLShippingOption.class);\n registerClass(TLStickerPack.CONSTRUCTOR_ID, TLStickerPack.class);\n registerClass(TLStickerSet.CONSTRUCTOR_ID, TLStickerSet.class);\n registerClass(TLStickerSetCovered.CONSTRUCTOR_ID, TLStickerSetCovered.class);\n registerClass(TLStickerSetMultiCovered.CONSTRUCTOR_ID, TLStickerSetMultiCovered.class);\n registerClass(TLFileGif.CONSTRUCTOR_ID, TLFileGif.class);\n registerClass(TLFileJpeg.CONSTRUCTOR_ID, TLFileJpeg.class);\n registerClass(TLFileMov.CONSTRUCTOR_ID, TLFileMov.class);\n registerClass(TLFileMp3.CONSTRUCTOR_ID, TLFileMp3.class);\n registerClass(TLFileMp4.CONSTRUCTOR_ID, TLFileMp4.class);\n registerClass(TLFilePartial.CONSTRUCTOR_ID, TLFilePartial.class);\n registerClass(TLFilePdf.CONSTRUCTOR_ID, TLFilePdf.class);\n registerClass(TLFilePng.CONSTRUCTOR_ID, TLFilePng.class);\n registerClass(TLFileUnknown.CONSTRUCTOR_ID, TLFileUnknown.class);\n registerClass(TLFileWebp.CONSTRUCTOR_ID, TLFileWebp.class);\n registerClass(TLTextBold.CONSTRUCTOR_ID, TLTextBold.class);\n registerClass(TLTextConcat.CONSTRUCTOR_ID, TLTextConcat.class);\n registerClass(TLTextEmail.CONSTRUCTOR_ID, TLTextEmail.class);\n registerClass(TLTextEmpty.CONSTRUCTOR_ID, TLTextEmpty.class);\n registerClass(TLTextFixed.CONSTRUCTOR_ID, TLTextFixed.class);\n registerClass(TLTextItalic.CONSTRUCTOR_ID, TLTextItalic.class);\n registerClass(TLTextPlain.CONSTRUCTOR_ID, TLTextPlain.class);\n registerClass(TLTextStrike.CONSTRUCTOR_ID, TLTextStrike.class);\n registerClass(TLTextUnderline.CONSTRUCTOR_ID, TLTextUnderline.class);\n registerClass(TLTextUrl.CONSTRUCTOR_ID, TLTextUrl.class);\n registerClass(TLTopPeer.CONSTRUCTOR_ID, TLTopPeer.class);\n registerClass(TLTopPeerCategoryBotsInline.CONSTRUCTOR_ID, TLTopPeerCategoryBotsInline.class);\n registerClass(TLTopPeerCategoryBotsPM.CONSTRUCTOR_ID, TLTopPeerCategoryBotsPM.class);\n registerClass(TLTopPeerCategoryChannels.CONSTRUCTOR_ID, TLTopPeerCategoryChannels.class);\n registerClass(TLTopPeerCategoryCorrespondents.CONSTRUCTOR_ID, TLTopPeerCategoryCorrespondents.class);\n registerClass(TLTopPeerCategoryGroups.CONSTRUCTOR_ID, TLTopPeerCategoryGroups.class);\n registerClass(TLTopPeerCategoryPeers.CONSTRUCTOR_ID, TLTopPeerCategoryPeers.class);\n registerClass(TLUpdateBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateBotCallbackQuery.class);\n registerClass(TLUpdateBotInlineQuery.CONSTRUCTOR_ID, TLUpdateBotInlineQuery.class);\n registerClass(TLUpdateBotInlineSend.CONSTRUCTOR_ID, TLUpdateBotInlineSend.class);\n registerClass(TLUpdateBotPrecheckoutQuery.CONSTRUCTOR_ID, TLUpdateBotPrecheckoutQuery.class);\n registerClass(TLUpdateBotShippingQuery.CONSTRUCTOR_ID, TLUpdateBotShippingQuery.class);\n registerClass(TLUpdateBotWebhookJSON.CONSTRUCTOR_ID, TLUpdateBotWebhookJSON.class);\n registerClass(TLUpdateBotWebhookJSONQuery.CONSTRUCTOR_ID, TLUpdateBotWebhookJSONQuery.class);\n registerClass(TLUpdateChannel.CONSTRUCTOR_ID, TLUpdateChannel.class);\n registerClass(TLUpdateChannelMessageViews.CONSTRUCTOR_ID, TLUpdateChannelMessageViews.class);\n registerClass(TLUpdateChannelPinnedMessage.CONSTRUCTOR_ID, TLUpdateChannelPinnedMessage.class);\n registerClass(TLUpdateChannelTooLong.CONSTRUCTOR_ID, TLUpdateChannelTooLong.class);\n registerClass(TLUpdateChannelWebPage.CONSTRUCTOR_ID, TLUpdateChannelWebPage.class);\n registerClass(TLUpdateChatAdmins.CONSTRUCTOR_ID, TLUpdateChatAdmins.class);\n registerClass(TLUpdateChatParticipantAdd.CONSTRUCTOR_ID, TLUpdateChatParticipantAdd.class);\n registerClass(TLUpdateChatParticipantAdmin.CONSTRUCTOR_ID, TLUpdateChatParticipantAdmin.class);\n registerClass(TLUpdateChatParticipantDelete.CONSTRUCTOR_ID, TLUpdateChatParticipantDelete.class);\n registerClass(TLUpdateChatParticipants.CONSTRUCTOR_ID, TLUpdateChatParticipants.class);\n registerClass(TLUpdateChatUserTyping.CONSTRUCTOR_ID, TLUpdateChatUserTyping.class);\n registerClass(TLUpdateConfig.CONSTRUCTOR_ID, TLUpdateConfig.class);\n registerClass(TLUpdateContactLink.CONSTRUCTOR_ID, TLUpdateContactLink.class);\n registerClass(TLUpdateContactRegistered.CONSTRUCTOR_ID, TLUpdateContactRegistered.class);\n registerClass(TLUpdateDcOptions.CONSTRUCTOR_ID, TLUpdateDcOptions.class);\n registerClass(TLUpdateDeleteChannelMessages.CONSTRUCTOR_ID, TLUpdateDeleteChannelMessages.class);\n registerClass(TLUpdateDeleteMessages.CONSTRUCTOR_ID, TLUpdateDeleteMessages.class);\n registerClass(TLUpdateDialogPinned.CONSTRUCTOR_ID, TLUpdateDialogPinned.class);\n registerClass(TLUpdateDraftMessage.CONSTRUCTOR_ID, TLUpdateDraftMessage.class);\n registerClass(TLUpdateEditChannelMessage.CONSTRUCTOR_ID, TLUpdateEditChannelMessage.class);\n registerClass(TLUpdateEditMessage.CONSTRUCTOR_ID, TLUpdateEditMessage.class);\n registerClass(TLUpdateEncryptedChatTyping.CONSTRUCTOR_ID, TLUpdateEncryptedChatTyping.class);\n registerClass(TLUpdateEncryptedMessagesRead.CONSTRUCTOR_ID, TLUpdateEncryptedMessagesRead.class);\n registerClass(TLUpdateEncryption.CONSTRUCTOR_ID, TLUpdateEncryption.class);\n registerClass(TLUpdateInlineBotCallbackQuery.CONSTRUCTOR_ID, TLUpdateInlineBotCallbackQuery.class);\n registerClass(TLUpdateMessageID.CONSTRUCTOR_ID, TLUpdateMessageID.class);\n registerClass(TLUpdateNewChannelMessage.CONSTRUCTOR_ID, TLUpdateNewChannelMessage.class);\n registerClass(TLUpdateNewEncryptedMessage.CONSTRUCTOR_ID, TLUpdateNewEncryptedMessage.class);\n registerClass(TLUpdateNewMessage.CONSTRUCTOR_ID, TLUpdateNewMessage.class);\n registerClass(TLUpdateNewStickerSet.CONSTRUCTOR_ID, TLUpdateNewStickerSet.class);\n registerClass(TLUpdateNotifySettings.CONSTRUCTOR_ID, TLUpdateNotifySettings.class);\n registerClass(TLUpdatePhoneCall.CONSTRUCTOR_ID, TLUpdatePhoneCall.class);\n registerClass(TLUpdatePinnedDialogs.CONSTRUCTOR_ID, TLUpdatePinnedDialogs.class);\n registerClass(TLUpdatePrivacy.CONSTRUCTOR_ID, TLUpdatePrivacy.class);\n registerClass(TLUpdatePtsChanged.CONSTRUCTOR_ID, TLUpdatePtsChanged.class);\n registerClass(TLUpdateReadChannelInbox.CONSTRUCTOR_ID, TLUpdateReadChannelInbox.class);\n registerClass(TLUpdateReadChannelOutbox.CONSTRUCTOR_ID, TLUpdateReadChannelOutbox.class);\n registerClass(TLUpdateReadFeaturedStickers.CONSTRUCTOR_ID, TLUpdateReadFeaturedStickers.class);\n registerClass(TLUpdateReadHistoryInbox.CONSTRUCTOR_ID, TLUpdateReadHistoryInbox.class);\n registerClass(TLUpdateReadHistoryOutbox.CONSTRUCTOR_ID, TLUpdateReadHistoryOutbox.class);\n registerClass(TLUpdateReadMessagesContents.CONSTRUCTOR_ID, TLUpdateReadMessagesContents.class);\n registerClass(TLUpdateRecentStickers.CONSTRUCTOR_ID, TLUpdateRecentStickers.class);\n registerClass(TLUpdateSavedGifs.CONSTRUCTOR_ID, TLUpdateSavedGifs.class);\n registerClass(TLUpdateServiceNotification.CONSTRUCTOR_ID, TLUpdateServiceNotification.class);\n registerClass(TLUpdateShort.CONSTRUCTOR_ID, TLUpdateShort.class);\n registerClass(TLUpdateShortChatMessage.CONSTRUCTOR_ID, TLUpdateShortChatMessage.class);\n registerClass(TLUpdateShortMessage.CONSTRUCTOR_ID, TLUpdateShortMessage.class);\n registerClass(TLUpdateShortSentMessage.CONSTRUCTOR_ID, TLUpdateShortSentMessage.class);\n registerClass(TLUpdateStickerSets.CONSTRUCTOR_ID, TLUpdateStickerSets.class);\n registerClass(TLUpdateStickerSetsOrder.CONSTRUCTOR_ID, TLUpdateStickerSetsOrder.class);\n registerClass(TLUpdateUserBlocked.CONSTRUCTOR_ID, TLUpdateUserBlocked.class);\n registerClass(TLUpdateUserName.CONSTRUCTOR_ID, TLUpdateUserName.class);\n registerClass(TLUpdateUserPhone.CONSTRUCTOR_ID, TLUpdateUserPhone.class);\n registerClass(TLUpdateUserPhoto.CONSTRUCTOR_ID, TLUpdateUserPhoto.class);\n registerClass(TLUpdateUserStatus.CONSTRUCTOR_ID, TLUpdateUserStatus.class);\n registerClass(TLUpdateUserTyping.CONSTRUCTOR_ID, TLUpdateUserTyping.class);\n registerClass(TLUpdateWebPage.CONSTRUCTOR_ID, TLUpdateWebPage.class);\n registerClass(TLUpdates.CONSTRUCTOR_ID, TLUpdates.class);\n registerClass(TLChannelDifference.CONSTRUCTOR_ID, TLChannelDifference.class);\n registerClass(TLChannelDifferenceEmpty.CONSTRUCTOR_ID, TLChannelDifferenceEmpty.class);\n registerClass(TLChannelDifferenceTooLong.CONSTRUCTOR_ID, TLChannelDifferenceTooLong.class);\n registerClass(TLDifference.CONSTRUCTOR_ID, TLDifference.class);\n registerClass(TLDifferenceEmpty.CONSTRUCTOR_ID, TLDifferenceEmpty.class);\n registerClass(TLDifferenceSlice.CONSTRUCTOR_ID, TLDifferenceSlice.class);\n registerClass(TLDifferenceTooLong.CONSTRUCTOR_ID, TLDifferenceTooLong.class);\n registerClass(TLState.CONSTRUCTOR_ID, TLState.class);\n registerClass(TLUpdatesCombined.CONSTRUCTOR_ID, TLUpdatesCombined.class);\n registerClass(TLUpdatesTooLong.CONSTRUCTOR_ID, TLUpdatesTooLong.class);\n registerClass(TLCdnFile.CONSTRUCTOR_ID, TLCdnFile.class);\n registerClass(TLCdnFileReuploadNeeded.CONSTRUCTOR_ID, TLCdnFileReuploadNeeded.class);\n registerClass(TLFile.CONSTRUCTOR_ID, TLFile.class);\n registerClass(TLFileCdnRedirect.CONSTRUCTOR_ID, TLFileCdnRedirect.class);\n registerClass(TLWebFile.CONSTRUCTOR_ID, TLWebFile.class);\n registerClass(TLUser.CONSTRUCTOR_ID, TLUser.class);\n registerClass(TLUserEmpty.CONSTRUCTOR_ID, TLUserEmpty.class);\n registerClass(TLUserFull.CONSTRUCTOR_ID, TLUserFull.class);\n registerClass(TLUserProfilePhoto.CONSTRUCTOR_ID, TLUserProfilePhoto.class);\n registerClass(TLUserProfilePhotoEmpty.CONSTRUCTOR_ID, TLUserProfilePhotoEmpty.class);\n registerClass(TLUserStatusEmpty.CONSTRUCTOR_ID, TLUserStatusEmpty.class);\n registerClass(TLUserStatusLastMonth.CONSTRUCTOR_ID, TLUserStatusLastMonth.class);\n registerClass(TLUserStatusLastWeek.CONSTRUCTOR_ID, TLUserStatusLastWeek.class);\n registerClass(TLUserStatusOffline.CONSTRUCTOR_ID, TLUserStatusOffline.class);\n registerClass(TLUserStatusOnline.CONSTRUCTOR_ID, TLUserStatusOnline.class);\n registerClass(TLUserStatusRecently.CONSTRUCTOR_ID, TLUserStatusRecently.class);\n registerClass(TLWallPaper.CONSTRUCTOR_ID, TLWallPaper.class);\n registerClass(TLWallPaperSolid.CONSTRUCTOR_ID, TLWallPaperSolid.class);\n registerClass(TLWebDocument.CONSTRUCTOR_ID, TLWebDocument.class);\n registerClass(TLWebPage.CONSTRUCTOR_ID, TLWebPage.class);\n registerClass(TLWebPageEmpty.CONSTRUCTOR_ID, TLWebPageEmpty.class);\n registerClass(TLWebPageNotModified.CONSTRUCTOR_ID, TLWebPageNotModified.class);\n registerClass(TLWebPagePending.CONSTRUCTOR_ID, TLWebPagePending.class);\n }\n}\n"} {"task_id": "Java_107", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ethereum/ethereumj/ethereumj-core/src/main/java/org/ethereum/util/ByteArrayMap.java", "mask_start_position": 2031, "mask_end_position": 2067, "canonical_solution": "@Override\n public int hashCode() ", "pre_mask_code": "/*\n * This file is part of the ethereumJ library.\n *\n */\npackage org.ethereum.util;\n\nimport org.ethereum.db.ByteArrayWrapper;\nimport java.util.*;\n\n/**\n * Created by Anton Nashatyrev on 06.10.2016.\n */\npublic class ByteArrayMap implements Map {\n\n private final Map delegate;\n\n public ByteArrayMap() {\n this(new HashMap());\n }\n\n public ByteArrayMap(Map delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean containsKey(Object key) {\n return delegate.containsKey(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public boolean containsValue(Object value) {\n return delegate.containsValue(value);\n }\n\n @Override\n public V get(Object key) {\n return delegate.get(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public V put(byte[] key, V value) {\n return delegate.put(new ByteArrayWrapper(key), value);\n }\n\n @Override\n public V remove(Object key) {\n return delegate.remove(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public void putAll(Map m) {\n for (Entry entry : m.entrySet()) {\n delegate.put(new ByteArrayWrapper(entry.getKey()), entry.getValue());\n }\n }\n\n @Override\n public void clear() {\n delegate.clear();\n }\n\n @Override\n public Set keySet() {\n return new ByteArraySet(new SetAdapter<>(delegate));\n }\n\n @Override\n public Collection values() {\n return delegate.values();\n }\n\n @Override\n public Set> entrySet() {\n return new MapEntrySet(delegate.entrySet());\n }\n\n @Override\n public boolean equals(Object o) {\n return delegate.equals(o);\n }\n\n ", "post_mask_code": "{\n return delegate.hashCode();\n }\n\n @Override\n public String toString() {\n return delegate.toString();\n }\n\n private class MapEntrySet implements Set> {\n\n private final Set> delegate;\n\n private MapEntrySet(Set> delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean contains(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public Iterator> iterator() {\n final Iterator> it = delegate.iterator();\n return new Iterator>() {\n\n @Override\n public boolean hasNext() {\n return it.hasNext();\n }\n\n @Override\n public Entry next() {\n Entry next = it.next();\n return new AbstractMap.SimpleImmutableEntry(next.getKey().getData(), next.getValue());\n }\n\n @Override\n public void remove() {\n it.remove();\n }\n };\n }\n\n @Override\n public Object[] toArray() {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public T[] toArray(T[] a) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean add(Entry vEntry) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean remove(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean containsAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean addAll(Collection> c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean retainAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean removeAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public void clear() {\n throw new RuntimeException(\"Not implemented\");\n }\n }\n}\n"} {"task_id": "Java_108", "language": "Java", "task_type": "method_body", "source_file": "java/github/ethereum/ethereumj/ethereumj-core/src/main/java/org/ethereum/util/ByteArrayMap.java", "mask_start_position": 4430, "mask_end_position": 4500, "canonical_solution": "{\n throw new RuntimeException(\"Not implemented\");\n }", "pre_mask_code": "/*\n * This file is part of the ethereumJ library.\n *\n */\npackage org.ethereum.util;\n\nimport org.ethereum.db.ByteArrayWrapper;\nimport java.util.*;\n\n/**\n * Created by Anton Nashatyrev on 06.10.2016.\n */\npublic class ByteArrayMap implements Map {\n\n private final Map delegate;\n\n public ByteArrayMap() {\n this(new HashMap());\n }\n\n public ByteArrayMap(Map delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean containsKey(Object key) {\n return delegate.containsKey(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public boolean containsValue(Object value) {\n return delegate.containsValue(value);\n }\n\n @Override\n public V get(Object key) {\n return delegate.get(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public V put(byte[] key, V value) {\n return delegate.put(new ByteArrayWrapper(key), value);\n }\n\n @Override\n public V remove(Object key) {\n return delegate.remove(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public void putAll(Map m) {\n for (Entry entry : m.entrySet()) {\n delegate.put(new ByteArrayWrapper(entry.getKey()), entry.getValue());\n }\n }\n\n @Override\n public void clear() {\n delegate.clear();\n }\n\n @Override\n public Set keySet() {\n return new ByteArraySet(new SetAdapter<>(delegate));\n }\n\n @Override\n public Collection values() {\n return delegate.values();\n }\n\n @Override\n public Set> entrySet() {\n return new MapEntrySet(delegate.entrySet());\n }\n\n @Override\n public boolean equals(Object o) {\n return delegate.equals(o);\n }\n\n @Override\n public int hashCode() {\n return delegate.hashCode();\n }\n\n @Override\n public String toString() {\n return delegate.toString();\n }\n\n private class MapEntrySet implements Set> {\n\n private final Set> delegate;\n\n private MapEntrySet(Set> delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean contains(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public Iterator> iterator() {\n final Iterator> it = delegate.iterator();\n return new Iterator>() {\n\n @Override\n public boolean hasNext() {\n return it.hasNext();\n }\n\n @Override\n public Entry next() {\n Entry next = it.next();\n return new AbstractMap.SimpleImmutableEntry(next.getKey().getData(), next.getValue());\n }\n\n @Override\n public void remove() {\n it.remove();\n }\n };\n }\n\n @Override\n public Object[] toArray() {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public T[] toArray(T[] a) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean add(Entry vEntry) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean remove(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean containsAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean addAll(Collection> c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean retainAll(Collection c) ", "post_mask_code": "\n\n @Override\n public boolean removeAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public void clear() {\n throw new RuntimeException(\"Not implemented\");\n }\n }\n}\n"} {"task_id": "Java_109", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/ethereum/ethereumj/ethereumj-core/src/main/java/org/ethereum/util/ByteArrayMap.java", "mask_start_position": 2860, "mask_end_position": 2941, "canonical_solution": "\n final Iterator> it = delegate.iterator();", "pre_mask_code": "/*\n * This file is part of the ethereumJ library.\n *\n */\npackage org.ethereum.util;\n\nimport org.ethereum.db.ByteArrayWrapper;\nimport java.util.*;\n\n/**\n * Created by Anton Nashatyrev on 06.10.2016.\n */\npublic class ByteArrayMap implements Map {\n\n private final Map delegate;\n\n public ByteArrayMap() {\n this(new HashMap());\n }\n\n public ByteArrayMap(Map delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean containsKey(Object key) {\n return delegate.containsKey(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public boolean containsValue(Object value) {\n return delegate.containsValue(value);\n }\n\n @Override\n public V get(Object key) {\n return delegate.get(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public V put(byte[] key, V value) {\n return delegate.put(new ByteArrayWrapper(key), value);\n }\n\n @Override\n public V remove(Object key) {\n return delegate.remove(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public void putAll(Map m) {\n for (Entry entry : m.entrySet()) {\n delegate.put(new ByteArrayWrapper(entry.getKey()), entry.getValue());\n }\n }\n\n @Override\n public void clear() {\n delegate.clear();\n }\n\n @Override\n public Set keySet() {\n return new ByteArraySet(new SetAdapter<>(delegate));\n }\n\n @Override\n public Collection values() {\n return delegate.values();\n }\n\n @Override\n public Set> entrySet() {\n return new MapEntrySet(delegate.entrySet());\n }\n\n @Override\n public boolean equals(Object o) {\n return delegate.equals(o);\n }\n\n @Override\n public int hashCode() {\n return delegate.hashCode();\n }\n\n @Override\n public String toString() {\n return delegate.toString();\n }\n\n private class MapEntrySet implements Set> {\n\n private final Set> delegate;\n\n private MapEntrySet(Set> delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean contains(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public Iterator> iterator() {", "post_mask_code": "\n return new Iterator>() {\n\n @Override\n public boolean hasNext() {\n return it.hasNext();\n }\n\n @Override\n public Entry next() {\n Entry next = it.next();\n return new AbstractMap.SimpleImmutableEntry(next.getKey().getData(), next.getValue());\n }\n\n @Override\n public void remove() {\n it.remove();\n }\n };\n }\n\n @Override\n public Object[] toArray() {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public T[] toArray(T[] a) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean add(Entry vEntry) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean remove(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean containsAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean addAll(Collection> c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean retainAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean removeAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public void clear() {\n throw new RuntimeException(\"Not implemented\");\n }\n }\n}\n"} {"task_id": "Java_110", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/ethereum/ethereumj/ethereumj-core/src/main/java/org/ethereum/util/ByteArrayMap.java", "mask_start_position": 2954, "mask_end_position": 3522, "canonical_solution": "return new Iterator>() {\n\n @Override\n public boolean hasNext() {\n return it.hasNext();\n }\n\n @Override\n public Entry next() {\n Entry next = it.next();\n return new AbstractMap.SimpleImmutableEntry(next.getKey().getData(), next.getValue());\n }\n\n @Override\n public void remove() {\n it.remove();\n }\n };", "pre_mask_code": "/*\n * This file is part of the ethereumJ library.\n *\n */\npackage org.ethereum.util;\n\nimport org.ethereum.db.ByteArrayWrapper;\nimport java.util.*;\n\n/**\n * Created by Anton Nashatyrev on 06.10.2016.\n */\npublic class ByteArrayMap implements Map {\n\n private final Map delegate;\n\n public ByteArrayMap() {\n this(new HashMap());\n }\n\n public ByteArrayMap(Map delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean containsKey(Object key) {\n return delegate.containsKey(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public boolean containsValue(Object value) {\n return delegate.containsValue(value);\n }\n\n @Override\n public V get(Object key) {\n return delegate.get(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public V put(byte[] key, V value) {\n return delegate.put(new ByteArrayWrapper(key), value);\n }\n\n @Override\n public V remove(Object key) {\n return delegate.remove(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public void putAll(Map m) {\n for (Entry entry : m.entrySet()) {\n delegate.put(new ByteArrayWrapper(entry.getKey()), entry.getValue());\n }\n }\n\n @Override\n public void clear() {\n delegate.clear();\n }\n\n @Override\n public Set keySet() {\n return new ByteArraySet(new SetAdapter<>(delegate));\n }\n\n @Override\n public Collection values() {\n return delegate.values();\n }\n\n @Override\n public Set> entrySet() {\n return new MapEntrySet(delegate.entrySet());\n }\n\n @Override\n public boolean equals(Object o) {\n return delegate.equals(o);\n }\n\n @Override\n public int hashCode() {\n return delegate.hashCode();\n }\n\n @Override\n public String toString() {\n return delegate.toString();\n }\n\n private class MapEntrySet implements Set> {\n\n private final Set> delegate;\n\n private MapEntrySet(Set> delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean contains(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public Iterator> iterator() {\n final Iterator> it = delegate.iterator();\n ", "post_mask_code": "\n }\n\n @Override\n public Object[] toArray() {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public T[] toArray(T[] a) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean add(Entry vEntry) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean remove(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean containsAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean addAll(Collection> c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean retainAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean removeAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public void clear() {\n throw new RuntimeException(\"Not implemented\");\n }\n }\n}\n"} {"task_id": "Java_111", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/ethereum/ethereumj/ethereumj-core/src/main/java/org/ethereum/util/ByteArrayMap.java", "mask_start_position": 3531, "mask_end_position": 3532, "canonical_solution": "}", "pre_mask_code": "/*\n * This file is part of the ethereumJ library.\n *\n */\npackage org.ethereum.util;\n\nimport org.ethereum.db.ByteArrayWrapper;\nimport java.util.*;\n\n/**\n * Created by Anton Nashatyrev on 06.10.2016.\n */\npublic class ByteArrayMap implements Map {\n\n private final Map delegate;\n\n public ByteArrayMap() {\n this(new HashMap());\n }\n\n public ByteArrayMap(Map delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean containsKey(Object key) {\n return delegate.containsKey(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public boolean containsValue(Object value) {\n return delegate.containsValue(value);\n }\n\n @Override\n public V get(Object key) {\n return delegate.get(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public V put(byte[] key, V value) {\n return delegate.put(new ByteArrayWrapper(key), value);\n }\n\n @Override\n public V remove(Object key) {\n return delegate.remove(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public void putAll(Map m) {\n for (Entry entry : m.entrySet()) {\n delegate.put(new ByteArrayWrapper(entry.getKey()), entry.getValue());\n }\n }\n\n @Override\n public void clear() {\n delegate.clear();\n }\n\n @Override\n public Set keySet() {\n return new ByteArraySet(new SetAdapter<>(delegate));\n }\n\n @Override\n public Collection values() {\n return delegate.values();\n }\n\n @Override\n public Set> entrySet() {\n return new MapEntrySet(delegate.entrySet());\n }\n\n @Override\n public boolean equals(Object o) {\n return delegate.equals(o);\n }\n\n @Override\n public int hashCode() {\n return delegate.hashCode();\n }\n\n @Override\n public String toString() {\n return delegate.toString();\n }\n\n private class MapEntrySet implements Set> {\n\n private final Set> delegate;\n\n private MapEntrySet(Set> delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean contains(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public Iterator> iterator() {\n final Iterator> it = delegate.iterator();\n return new Iterator>() {\n\n @Override\n public boolean hasNext() {\n return it.hasNext();\n }\n\n @Override\n public Entry next() {\n Entry next = it.next();\n return new AbstractMap.SimpleImmutableEntry(next.getKey().getData(), next.getValue());\n }\n\n @Override\n public void remove() {\n it.remove();\n }\n };\n ", "post_mask_code": "\n\n @Override\n public Object[] toArray() {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public T[] toArray(T[] a) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean add(Entry vEntry) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean remove(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean containsAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean addAll(Collection> c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean retainAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean removeAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public void clear() {\n throw new RuntimeException(\"Not implemented\");\n }\n }\n}\n"} {"task_id": "Java_112", "language": "Java", "task_type": "single_line", "source_file": "java/github/ethereum/ethereumj/ethereumj-core/src/main/java/org/ethereum/util/ByteArrayMap.java", "mask_start_position": 3089, "mask_end_position": 3106, "canonical_solution": "urn it.hasNext();", "pre_mask_code": "/*\n * This file is part of the ethereumJ library.\n *\n */\npackage org.ethereum.util;\n\nimport org.ethereum.db.ByteArrayWrapper;\nimport java.util.*;\n\n/**\n * Created by Anton Nashatyrev on 06.10.2016.\n */\npublic class ByteArrayMap implements Map {\n\n private final Map delegate;\n\n public ByteArrayMap() {\n this(new HashMap());\n }\n\n public ByteArrayMap(Map delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean containsKey(Object key) {\n return delegate.containsKey(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public boolean containsValue(Object value) {\n return delegate.containsValue(value);\n }\n\n @Override\n public V get(Object key) {\n return delegate.get(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public V put(byte[] key, V value) {\n return delegate.put(new ByteArrayWrapper(key), value);\n }\n\n @Override\n public V remove(Object key) {\n return delegate.remove(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public void putAll(Map m) {\n for (Entry entry : m.entrySet()) {\n delegate.put(new ByteArrayWrapper(entry.getKey()), entry.getValue());\n }\n }\n\n @Override\n public void clear() {\n delegate.clear();\n }\n\n @Override\n public Set keySet() {\n return new ByteArraySet(new SetAdapter<>(delegate));\n }\n\n @Override\n public Collection values() {\n return delegate.values();\n }\n\n @Override\n public Set> entrySet() {\n return new MapEntrySet(delegate.entrySet());\n }\n\n @Override\n public boolean equals(Object o) {\n return delegate.equals(o);\n }\n\n @Override\n public int hashCode() {\n return delegate.hashCode();\n }\n\n @Override\n public String toString() {\n return delegate.toString();\n }\n\n private class MapEntrySet implements Set> {\n\n private final Set> delegate;\n\n private MapEntrySet(Set> delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean contains(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public Iterator> iterator() {\n final Iterator> it = delegate.iterator();\n return new Iterator>() {\n\n @Override\n public boolean hasNext() {\n ret", "post_mask_code": "\n }\n\n @Override\n public Entry next() {\n Entry next = it.next();\n return new AbstractMap.SimpleImmutableEntry(next.getKey().getData(), next.getValue());\n }\n\n @Override\n public void remove() {\n it.remove();\n }\n };\n }\n\n @Override\n public Object[] toArray() {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public T[] toArray(T[] a) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean add(Entry vEntry) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean remove(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean containsAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean addAll(Collection> c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean retainAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean removeAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public void clear() {\n throw new RuntimeException(\"Not implemented\");\n }\n }\n}\n"} {"task_id": "Java_113", "language": "Java", "task_type": "empty", "source_file": "java/github/ethereum/ethereumj/ethereumj-core/src/main/java/org/ethereum/util/ByteArrayMap.java", "mask_start_position": 4491, "mask_end_position": 4491, "canonical_solution": "", "pre_mask_code": "/*\n * This file is part of the ethereumJ library.\n *\n */\npackage org.ethereum.util;\n\nimport org.ethereum.db.ByteArrayWrapper;\nimport java.util.*;\n\n/**\n * Created by Anton Nashatyrev on 06.10.2016.\n */\npublic class ByteArrayMap implements Map {\n\n private final Map delegate;\n\n public ByteArrayMap() {\n this(new HashMap());\n }\n\n public ByteArrayMap(Map delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean containsKey(Object key) {\n return delegate.containsKey(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public boolean containsValue(Object value) {\n return delegate.containsValue(value);\n }\n\n @Override\n public V get(Object key) {\n return delegate.get(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public V put(byte[] key, V value) {\n return delegate.put(new ByteArrayWrapper(key), value);\n }\n\n @Override\n public V remove(Object key) {\n return delegate.remove(new ByteArrayWrapper((byte[]) key));\n }\n\n @Override\n public void putAll(Map m) {\n for (Entry entry : m.entrySet()) {\n delegate.put(new ByteArrayWrapper(entry.getKey()), entry.getValue());\n }\n }\n\n @Override\n public void clear() {\n delegate.clear();\n }\n\n @Override\n public Set keySet() {\n return new ByteArraySet(new SetAdapter<>(delegate));\n }\n\n @Override\n public Collection values() {\n return delegate.values();\n }\n\n @Override\n public Set> entrySet() {\n return new MapEntrySet(delegate.entrySet());\n }\n\n @Override\n public boolean equals(Object o) {\n return delegate.equals(o);\n }\n\n @Override\n public int hashCode() {\n return delegate.hashCode();\n }\n\n @Override\n public String toString() {\n return delegate.toString();\n }\n\n private class MapEntrySet implements Set> {\n\n private final Set> delegate;\n\n private MapEntrySet(Set> delegate) {\n this.delegate = delegate;\n }\n\n @Override\n public int size() {\n return delegate.size();\n }\n\n @Override\n public boolean isEmpty() {\n return delegate.isEmpty();\n }\n\n @Override\n public boolean contains(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public Iterator> iterator() {\n final Iterator> it = delegate.iterator();\n return new Iterator>() {\n\n @Override\n public boolean hasNext() {\n return it.hasNext();\n }\n\n @Override\n public Entry next() {\n Entry next = it.next();\n return new AbstractMap.SimpleImmutableEntry(next.getKey().getData(), next.getValue());\n }\n\n @Override\n public void remove() {\n it.remove();\n }\n };\n }\n\n @Override\n public Object[] toArray() {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public T[] toArray(T[] a) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean add(Entry vEntry) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean remove(Object o) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean containsAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean addAll(Collection> c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public boolean retainAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n", "post_mask_code": " }\n\n @Override\n public boolean removeAll(Collection c) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public void clear() {\n throw new RuntimeException(\"Not implemented\");\n }\n }\n}\n"} {"task_id": "Java_114", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse-cdt/cdt/qt/org.eclipse.cdt.qt.core/src/org/eclipse/cdt/internal/qt/core/qmltypes/QMLSignalInfo.java", "mask_start_position": 2265, "mask_end_position": 2290, "canonical_solution": "public int getRevision() ", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * QNX Software Systems - Initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.cdt.internal.qt.core.qmltypes;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlObjectDefinition;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlObjectMember;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlPropertyBinding;\n\npublic class QMLSignalInfo {\n\n static final String IDENTIFIER = \"Signal\";\n\n static final String PROPERTY_NAME = \"name\";\n\n static final String PROPERTY_TYPE = \"type\";\n\n static final String PROPERTY_REVISION = \"revision\";\n\n private String name;\n\n private String type;\n\n private Integer revision;\n\n private List parameterList = new ArrayList<>();\n\n QMLSignalInfo(QMLModelBuilder builder, IQmlObjectDefinition obj) {\n if (builder.ensureIdentifier(obj.getIdentifier(), IDENTIFIER)) {\n for (IQmlObjectMember member : obj.getBody().getMembers()) {\n if (member instanceof IQmlPropertyBinding) {\n IQmlPropertyBinding prop = (IQmlPropertyBinding) member;\n switch(prop.getIdentifier().getName()) {\n case PROPERTY_NAME:\n this.name = builder.getStringBinding(prop);\n break;\n case PROPERTY_TYPE:\n this.type = builder.getStringBinding(prop);\n break;\n case PROPERTY_REVISION:\n this.revision = builder.getIntegerBinding(prop);\n break;\n default:\n }\n } else if (member instanceof IQmlObjectDefinition) {\n this.parameterList.add(new QMLParameterInfo(builder, (IQmlObjectDefinition) member));\n } else {\n builder.unexpectedNode(member);\n }\n }\n }\n }\n\n public String getName() {\n return name;\n }\n\n public String getType() {\n return type;\n }\n\n ", "post_mask_code": "{\n return revision;\n }\n}\n"} {"task_id": "Java_115", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse-cdt/cdt/qt/org.eclipse.cdt.qt.core/src/org/eclipse/cdt/internal/qt/core/qmltypes/QMLSignalInfo.java", "mask_start_position": 2173, "mask_end_position": 2201, "canonical_solution": "{\n return name;\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * QNX Software Systems - Initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.cdt.internal.qt.core.qmltypes;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlObjectDefinition;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlObjectMember;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlPropertyBinding;\n\npublic class QMLSignalInfo {\n\n static final String IDENTIFIER = \"Signal\";\n\n static final String PROPERTY_NAME = \"name\";\n\n static final String PROPERTY_TYPE = \"type\";\n\n static final String PROPERTY_REVISION = \"revision\";\n\n private String name;\n\n private String type;\n\n private Integer revision;\n\n private List parameterList = new ArrayList<>();\n\n QMLSignalInfo(QMLModelBuilder builder, IQmlObjectDefinition obj) {\n if (builder.ensureIdentifier(obj.getIdentifier(), IDENTIFIER)) {\n for (IQmlObjectMember member : obj.getBody().getMembers()) {\n if (member instanceof IQmlPropertyBinding) {\n IQmlPropertyBinding prop = (IQmlPropertyBinding) member;\n switch(prop.getIdentifier().getName()) {\n case PROPERTY_NAME:\n this.name = builder.getStringBinding(prop);\n break;\n case PROPERTY_TYPE:\n this.type = builder.getStringBinding(prop);\n break;\n case PROPERTY_REVISION:\n this.revision = builder.getIntegerBinding(prop);\n break;\n default:\n }\n } else if (member instanceof IQmlObjectDefinition) {\n this.parameterList.add(new QMLParameterInfo(builder, (IQmlObjectDefinition) member));\n } else {\n builder.unexpectedNode(member);\n }\n }\n }\n }\n\n public String getName() ", "post_mask_code": "\n\n public String getType() {\n return type;\n }\n\n public int getRevision() {\n return revision;\n }\n}\n"} {"task_id": "Java_116", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse-cdt/cdt/qt/org.eclipse.cdt.qt.core/src/org/eclipse/cdt/internal/qt/core/qmltypes/QMLSignalInfo.java", "mask_start_position": 2252, "mask_end_position": 2253, "canonical_solution": ";", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * QNX Software Systems - Initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.cdt.internal.qt.core.qmltypes;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlObjectDefinition;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlObjectMember;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlPropertyBinding;\n\npublic class QMLSignalInfo {\n\n static final String IDENTIFIER = \"Signal\";\n\n static final String PROPERTY_NAME = \"name\";\n\n static final String PROPERTY_TYPE = \"type\";\n\n static final String PROPERTY_REVISION = \"revision\";\n\n private String name;\n\n private String type;\n\n private Integer revision;\n\n private List parameterList = new ArrayList<>();\n\n QMLSignalInfo(QMLModelBuilder builder, IQmlObjectDefinition obj) {\n if (builder.ensureIdentifier(obj.getIdentifier(), IDENTIFIER)) {\n for (IQmlObjectMember member : obj.getBody().getMembers()) {\n if (member instanceof IQmlPropertyBinding) {\n IQmlPropertyBinding prop = (IQmlPropertyBinding) member;\n switch(prop.getIdentifier().getName()) {\n case PROPERTY_NAME:\n this.name = builder.getStringBinding(prop);\n break;\n case PROPERTY_TYPE:\n this.type = builder.getStringBinding(prop);\n break;\n case PROPERTY_REVISION:\n this.revision = builder.getIntegerBinding(prop);\n break;\n default:\n }\n } else if (member instanceof IQmlObjectDefinition) {\n this.parameterList.add(new QMLParameterInfo(builder, (IQmlObjectDefinition) member));\n } else {\n builder.unexpectedNode(member);\n }\n }\n }\n }\n\n public String getName() {\n return name;\n }\n\n public String getType() {\n return type", "post_mask_code": "\n }\n\n public int getRevision() {\n return revision;\n }\n}\n"} {"task_id": "Java_117", "language": "Java", "task_type": "if_statement", "source_file": "java/github/eclipse-cdt/cdt/qt/org.eclipse.cdt.qt.core/src/org/eclipse/cdt/internal/qt/core/qmltypes/QMLSignalInfo.java", "mask_start_position": 1867, "mask_end_position": 2113, "canonical_solution": "if (member instanceof IQmlObjectDefinition) {\n this.parameterList.add(new QMLParameterInfo(builder, (IQmlObjectDefinition) member));\n } else {\n builder.unexpectedNode(member);\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * QNX Software Systems - Initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.cdt.internal.qt.core.qmltypes;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlObjectDefinition;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlObjectMember;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlPropertyBinding;\n\npublic class QMLSignalInfo {\n\n static final String IDENTIFIER = \"Signal\";\n\n static final String PROPERTY_NAME = \"name\";\n\n static final String PROPERTY_TYPE = \"type\";\n\n static final String PROPERTY_REVISION = \"revision\";\n\n private String name;\n\n private String type;\n\n private Integer revision;\n\n private List parameterList = new ArrayList<>();\n\n QMLSignalInfo(QMLModelBuilder builder, IQmlObjectDefinition obj) {\n if (builder.ensureIdentifier(obj.getIdentifier(), IDENTIFIER)) {\n for (IQmlObjectMember member : obj.getBody().getMembers()) {\n if (member instanceof IQmlPropertyBinding) {\n IQmlPropertyBinding prop = (IQmlPropertyBinding) member;\n switch(prop.getIdentifier().getName()) {\n case PROPERTY_NAME:\n this.name = builder.getStringBinding(prop);\n break;\n case PROPERTY_TYPE:\n this.type = builder.getStringBinding(prop);\n break;\n case PROPERTY_REVISION:\n this.revision = builder.getIntegerBinding(prop);\n break;\n default:\n }\n } else ", "post_mask_code": "\n }\n }\n }\n\n public String getName() {\n return name;\n }\n\n public String getType() {\n return type;\n }\n\n public int getRevision() {\n return revision;\n }\n}\n"} {"task_id": "Java_118", "language": "Java", "task_type": "empty", "source_file": "java/github/eclipse-cdt/cdt/qt/org.eclipse.cdt.qt.core/src/org/eclipse/cdt/internal/qt/core/qmltypes/QMLSignalInfo.java", "mask_start_position": 1305, "mask_end_position": 1305, "canonical_solution": "", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * QNX Software Systems - Initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.cdt.internal.qt.core.qmltypes;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlObjectDefinition;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlObjectMember;\nimport org.eclipse.cdt.qt.core.qmljs.IQmlPropertyBinding;\n\npublic class QMLSignalInfo {\n\n static final String IDENTIFIER = \"Signal\";\n\n static final String PROPERTY_NAME = \"name\";\n\n static final String PROPERTY_TYPE = \"type\";\n\n static final String PROPERTY_REVISION = \"revision\";\n\n private String name;\n\n private String type;\n\n private Integer revision;\n\n private List parameterList = new ArrayList<>();\n\n QMLSignalInfo(QMLModelBuilder builder, IQmlObjectDefinition obj) {\n if (builder.ensureIdentifier(obj.getIdentifier(), IDENTIFIER)) {\n for (IQmlObjectMember member : obj.getBody().getMembers()) {\n if (member instanceof IQmlPropertyBinding) {\n IQmlPropertyBinding prop = (IQmlPropertyBinding) member;\n switch(prop.getIden", "post_mask_code": "tifier().getName()) {\n case PROPERTY_NAME:\n this.name = builder.getStringBinding(prop);\n break;\n case PROPERTY_TYPE:\n this.type = builder.getStringBinding(prop);\n break;\n case PROPERTY_REVISION:\n this.revision = builder.getIntegerBinding(prop);\n break;\n default:\n }\n } else if (member instanceof IQmlObjectDefinition) {\n this.parameterList.add(new QMLParameterInfo(builder, (IQmlObjectDefinition) member));\n } else {\n builder.unexpectedNode(member);\n }\n }\n }\n }\n\n public String getName() {\n return name;\n }\n\n public String getType() {\n return type;\n }\n\n public int getRevision() {\n return revision;\n }\n}\n"} {"task_id": "Java_119", "language": "Java", "task_type": "method_signature", "source_file": "java/github/stapler/stapler/jsp/src/main/java/org/kohsuke/stapler/jsp/JSPFacet.java", "mask_start_position": 2326, "mask_end_position": 2351, "canonical_solution": "public String toString() ", "pre_mask_code": "/*\n * All rights reserved.\n *\n */\npackage org.kohsuke.stapler.jsp;\n\nimport org.kohsuke.stapler.Facet;\nimport org.kohsuke.stapler.MetaClass;\nimport org.kohsuke.stapler.Dispatcher;\nimport org.kohsuke.stapler.RequestImpl;\nimport org.kohsuke.stapler.ResponseImpl;\nimport org.kohsuke.stapler.Stapler;\nimport org.kohsuke.MetaInfServices;\nimport org.kohsuke.stapler.lang.Klass;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletContext;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.io.IOException;\n\n/**\n * {@link Facet} that adds JSP file support.\n *\n * @author Kohsuke Kawaguchi\n */\n@MetaInfServices\npublic class JSPFacet extends Facet {\n\n public void buildViewDispatchers(MetaClass owner, List dispatchers) {\n dispatchers.add(new Dispatcher() {\n\n public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException {\n String next = req.tokens.peek();\n if (next == null)\n return false;\n // only match the end of the URL\n if (req.tokens.countRemainingTokens() > 1)\n return false;\n // and avoid serving both \"foo\" and \"foo/\" as relative URL semantics are drastically different\n if (req.getRequestURI().endsWith(\"/\"))\n return false;\n Stapler stapler = req.getStapler();\n if (!isBasename(next)) {\n // potentially an attempt to make a folder traversal\n return false;\n }\n // check static resources\n RequestDispatcher disp = createRequestDispatcher(req, node.getClass(), node, next);\n if (disp == null) {\n // check JSP views\n disp = createRequestDispatcher(req, node.getClass(), node, next + \".jsp\");\n if (disp == null)\n return false;\n }\n req.tokens.next();\n if (traceable())\n trace(req, rsp, \"Invoking \" + next + \".jsp\" + \" on \" + node + \" for \" + req.tokens);\n stapler.forward(disp, req, rsp);\n return true;\n }\n\n ", "post_mask_code": "{\n return \"TOKEN.jsp for url=/TOKEN/...\";\n }\n });\n }\n\n public RequestDispatcher createRequestDispatcher(RequestImpl request, Klass type, Object it, String viewName) throws IOException {\n ServletContext context = request.stapler.getServletContext();\n // JSP support is deprecated, and this doesn't work with non-Java objects\n for (Class c = type.toJavaClass(); c != Object.class; c = c.getSuperclass()) {\n String name = \"/WEB-INF/side-files/\" + c.getName().replace('.', '/').replace('$', '/') + '/' + viewName;\n if (context.getResource(name) != null) {\n // Tomcat returns a RequestDispatcher even if the JSP file doesn't exist.\n // so check if the resource exists first.\n RequestDispatcher disp = context.getRequestDispatcher(name);\n if (disp != null) {\n return new RequestDispatcherWrapper(disp, it);\n }\n }\n }\n return null;\n }\n\n public boolean handleIndexRequest(RequestImpl req, ResponseImpl rsp, Object node, MetaClass nodeMetaClass) throws IOException, ServletException {\n Stapler stapler = req.stapler;\n // TODO: find the list of welcome pages for this class by reading web.xml\n RequestDispatcher indexJsp = createRequestDispatcher(req, node.getClass(), node, \"index.jsp\");\n if (indexJsp != null) {\n if (LOGGER.isLoggable(Level.FINE))\n LOGGER.fine(\"Invoking index.jsp on \" + node);\n stapler.forward(indexJsp, req, rsp);\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_120", "language": "Java", "task_type": "method_body", "source_file": "java/github/stapler/stapler/jsp/src/main/java/org/kohsuke/stapler/jsp/JSPFacet.java", "mask_start_position": 3531, "mask_end_position": 4009, "canonical_solution": "{\n Stapler stapler = req.stapler;\n // TODO: find the list of welcome pages for this class by reading web.xml\n RequestDispatcher indexJsp = createRequestDispatcher(req, node.getClass(), node, \"index.jsp\");\n if (indexJsp != null) {\n if (LOGGER.isLoggable(Level.FINE))\n LOGGER.fine(\"Invoking index.jsp on \" + node);\n stapler.forward(indexJsp, req, rsp);\n return true;\n }\n return false;\n }", "pre_mask_code": "/*\n * All rights reserved.\n *\n */\npackage org.kohsuke.stapler.jsp;\n\nimport org.kohsuke.stapler.Facet;\nimport org.kohsuke.stapler.MetaClass;\nimport org.kohsuke.stapler.Dispatcher;\nimport org.kohsuke.stapler.RequestImpl;\nimport org.kohsuke.stapler.ResponseImpl;\nimport org.kohsuke.stapler.Stapler;\nimport org.kohsuke.MetaInfServices;\nimport org.kohsuke.stapler.lang.Klass;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletContext;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.io.IOException;\n\n/**\n * {@link Facet} that adds JSP file support.\n *\n * @author Kohsuke Kawaguchi\n */\n@MetaInfServices\npublic class JSPFacet extends Facet {\n\n public void buildViewDispatchers(MetaClass owner, List dispatchers) {\n dispatchers.add(new Dispatcher() {\n\n public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException {\n String next = req.tokens.peek();\n if (next == null)\n return false;\n // only match the end of the URL\n if (req.tokens.countRemainingTokens() > 1)\n return false;\n // and avoid serving both \"foo\" and \"foo/\" as relative URL semantics are drastically different\n if (req.getRequestURI().endsWith(\"/\"))\n return false;\n Stapler stapler = req.getStapler();\n if (!isBasename(next)) {\n // potentially an attempt to make a folder traversal\n return false;\n }\n // check static resources\n RequestDispatcher disp = createRequestDispatcher(req, node.getClass(), node, next);\n if (disp == null) {\n // check JSP views\n disp = createRequestDispatcher(req, node.getClass(), node, next + \".jsp\");\n if (disp == null)\n return false;\n }\n req.tokens.next();\n if (traceable())\n trace(req, rsp, \"Invoking \" + next + \".jsp\" + \" on \" + node + \" for \" + req.tokens);\n stapler.forward(disp, req, rsp);\n return true;\n }\n\n public String toString() {\n return \"TOKEN.jsp for url=/TOKEN/...\";\n }\n });\n }\n\n public RequestDispatcher createRequestDispatcher(RequestImpl request, Klass type, Object it, String viewName) throws IOException {\n ServletContext context = request.stapler.getServletContext();\n // JSP support is deprecated, and this doesn't work with non-Java objects\n for (Class c = type.toJavaClass(); c != Object.class; c = c.getSuperclass()) {\n String name = \"/WEB-INF/side-files/\" + c.getName().replace('.', '/').replace('$', '/') + '/' + viewName;\n if (context.getResource(name) != null) {\n // Tomcat returns a RequestDispatcher even if the JSP file doesn't exist.\n // so check if the resource exists first.\n RequestDispatcher disp = context.getRequestDispatcher(name);\n if (disp != null) {\n return new RequestDispatcherWrapper(disp, it);\n }\n }\n }\n return null;\n }\n\n public boolean handleIndexRequest(RequestImpl req, ResponseImpl rsp, Object node, MetaClass nodeMetaClass) throws IOException, ServletException ", "post_mask_code": "\n}\n"} {"task_id": "Java_121", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/stapler/stapler/jsp/src/main/java/org/kohsuke/stapler/jsp/JSPFacet.java", "mask_start_position": 3532, "mask_end_position": 3653, "canonical_solution": "\n Stapler stapler = req.stapler;\n // TODO: find the list of welcome pages for this class by reading web.xml", "pre_mask_code": "/*\n * All rights reserved.\n *\n */\npackage org.kohsuke.stapler.jsp;\n\nimport org.kohsuke.stapler.Facet;\nimport org.kohsuke.stapler.MetaClass;\nimport org.kohsuke.stapler.Dispatcher;\nimport org.kohsuke.stapler.RequestImpl;\nimport org.kohsuke.stapler.ResponseImpl;\nimport org.kohsuke.stapler.Stapler;\nimport org.kohsuke.MetaInfServices;\nimport org.kohsuke.stapler.lang.Klass;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletContext;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.io.IOException;\n\n/**\n * {@link Facet} that adds JSP file support.\n *\n * @author Kohsuke Kawaguchi\n */\n@MetaInfServices\npublic class JSPFacet extends Facet {\n\n public void buildViewDispatchers(MetaClass owner, List dispatchers) {\n dispatchers.add(new Dispatcher() {\n\n public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException {\n String next = req.tokens.peek();\n if (next == null)\n return false;\n // only match the end of the URL\n if (req.tokens.countRemainingTokens() > 1)\n return false;\n // and avoid serving both \"foo\" and \"foo/\" as relative URL semantics are drastically different\n if (req.getRequestURI().endsWith(\"/\"))\n return false;\n Stapler stapler = req.getStapler();\n if (!isBasename(next)) {\n // potentially an attempt to make a folder traversal\n return false;\n }\n // check static resources\n RequestDispatcher disp = createRequestDispatcher(req, node.getClass(), node, next);\n if (disp == null) {\n // check JSP views\n disp = createRequestDispatcher(req, node.getClass(), node, next + \".jsp\");\n if (disp == null)\n return false;\n }\n req.tokens.next();\n if (traceable())\n trace(req, rsp, \"Invoking \" + next + \".jsp\" + \" on \" + node + \" for \" + req.tokens);\n stapler.forward(disp, req, rsp);\n return true;\n }\n\n public String toString() {\n return \"TOKEN.jsp for url=/TOKEN/...\";\n }\n });\n }\n\n public RequestDispatcher createRequestDispatcher(RequestImpl request, Klass type, Object it, String viewName) throws IOException {\n ServletContext context = request.stapler.getServletContext();\n // JSP support is deprecated, and this doesn't work with non-Java objects\n for (Class c = type.toJavaClass(); c != Object.class; c = c.getSuperclass()) {\n String name = \"/WEB-INF/side-files/\" + c.getName().replace('.', '/').replace('$', '/') + '/' + viewName;\n if (context.getResource(name) != null) {\n // Tomcat returns a RequestDispatcher even if the JSP file doesn't exist.\n // so check if the resource exists first.\n RequestDispatcher disp = context.getRequestDispatcher(name);\n if (disp != null) {\n return new RequestDispatcherWrapper(disp, it);\n }\n }\n }\n return null;\n }\n\n public boolean handleIndexRequest(RequestImpl req, ResponseImpl rsp, Object node, MetaClass nodeMetaClass) throws IOException, ServletException {", "post_mask_code": "\n RequestDispatcher indexJsp = createRequestDispatcher(req, node.getClass(), node, \"index.jsp\");\n if (indexJsp != null) {\n if (LOGGER.isLoggable(Level.FINE))\n LOGGER.fine(\"Invoking index.jsp on \" + node);\n stapler.forward(indexJsp, req, rsp);\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_122", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/stapler/stapler/jsp/src/main/java/org/kohsuke/stapler/jsp/JSPFacet.java", "mask_start_position": 3662, "mask_end_position": 3981, "canonical_solution": "RequestDispatcher indexJsp = createRequestDispatcher(req, node.getClass(), node, \"index.jsp\");\n if (indexJsp != null) {\n if (LOGGER.isLoggable(Level.FINE))\n LOGGER.fine(\"Invoking index.jsp on \" + node);\n stapler.forward(indexJsp, req, rsp);\n return true;\n }", "pre_mask_code": "/*\n * All rights reserved.\n *\n */\npackage org.kohsuke.stapler.jsp;\n\nimport org.kohsuke.stapler.Facet;\nimport org.kohsuke.stapler.MetaClass;\nimport org.kohsuke.stapler.Dispatcher;\nimport org.kohsuke.stapler.RequestImpl;\nimport org.kohsuke.stapler.ResponseImpl;\nimport org.kohsuke.stapler.Stapler;\nimport org.kohsuke.MetaInfServices;\nimport org.kohsuke.stapler.lang.Klass;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletContext;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.io.IOException;\n\n/**\n * {@link Facet} that adds JSP file support.\n *\n * @author Kohsuke Kawaguchi\n */\n@MetaInfServices\npublic class JSPFacet extends Facet {\n\n public void buildViewDispatchers(MetaClass owner, List dispatchers) {\n dispatchers.add(new Dispatcher() {\n\n public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException {\n String next = req.tokens.peek();\n if (next == null)\n return false;\n // only match the end of the URL\n if (req.tokens.countRemainingTokens() > 1)\n return false;\n // and avoid serving both \"foo\" and \"foo/\" as relative URL semantics are drastically different\n if (req.getRequestURI().endsWith(\"/\"))\n return false;\n Stapler stapler = req.getStapler();\n if (!isBasename(next)) {\n // potentially an attempt to make a folder traversal\n return false;\n }\n // check static resources\n RequestDispatcher disp = createRequestDispatcher(req, node.getClass(), node, next);\n if (disp == null) {\n // check JSP views\n disp = createRequestDispatcher(req, node.getClass(), node, next + \".jsp\");\n if (disp == null)\n return false;\n }\n req.tokens.next();\n if (traceable())\n trace(req, rsp, \"Invoking \" + next + \".jsp\" + \" on \" + node + \" for \" + req.tokens);\n stapler.forward(disp, req, rsp);\n return true;\n }\n\n public String toString() {\n return \"TOKEN.jsp for url=/TOKEN/...\";\n }\n });\n }\n\n public RequestDispatcher createRequestDispatcher(RequestImpl request, Klass type, Object it, String viewName) throws IOException {\n ServletContext context = request.stapler.getServletContext();\n // JSP support is deprecated, and this doesn't work with non-Java objects\n for (Class c = type.toJavaClass(); c != Object.class; c = c.getSuperclass()) {\n String name = \"/WEB-INF/side-files/\" + c.getName().replace('.', '/').replace('$', '/') + '/' + viewName;\n if (context.getResource(name) != null) {\n // Tomcat returns a RequestDispatcher even if the JSP file doesn't exist.\n // so check if the resource exists first.\n RequestDispatcher disp = context.getRequestDispatcher(name);\n if (disp != null) {\n return new RequestDispatcherWrapper(disp, it);\n }\n }\n }\n return null;\n }\n\n public boolean handleIndexRequest(RequestImpl req, ResponseImpl rsp, Object node, MetaClass nodeMetaClass) throws IOException, ServletException {\n Stapler stapler = req.stapler;\n // TODO: find the list of welcome pages for this class by reading web.xml\n ", "post_mask_code": "\n return false;\n }\n}\n"} {"task_id": "Java_123", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/stapler/stapler/jsp/src/main/java/org/kohsuke/stapler/jsp/JSPFacet.java", "mask_start_position": 3990, "mask_end_position": 4009, "canonical_solution": "return false;\n }", "pre_mask_code": "/*\n * All rights reserved.\n *\n */\npackage org.kohsuke.stapler.jsp;\n\nimport org.kohsuke.stapler.Facet;\nimport org.kohsuke.stapler.MetaClass;\nimport org.kohsuke.stapler.Dispatcher;\nimport org.kohsuke.stapler.RequestImpl;\nimport org.kohsuke.stapler.ResponseImpl;\nimport org.kohsuke.stapler.Stapler;\nimport org.kohsuke.MetaInfServices;\nimport org.kohsuke.stapler.lang.Klass;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletContext;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.io.IOException;\n\n/**\n * {@link Facet} that adds JSP file support.\n *\n * @author Kohsuke Kawaguchi\n */\n@MetaInfServices\npublic class JSPFacet extends Facet {\n\n public void buildViewDispatchers(MetaClass owner, List dispatchers) {\n dispatchers.add(new Dispatcher() {\n\n public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException {\n String next = req.tokens.peek();\n if (next == null)\n return false;\n // only match the end of the URL\n if (req.tokens.countRemainingTokens() > 1)\n return false;\n // and avoid serving both \"foo\" and \"foo/\" as relative URL semantics are drastically different\n if (req.getRequestURI().endsWith(\"/\"))\n return false;\n Stapler stapler = req.getStapler();\n if (!isBasename(next)) {\n // potentially an attempt to make a folder traversal\n return false;\n }\n // check static resources\n RequestDispatcher disp = createRequestDispatcher(req, node.getClass(), node, next);\n if (disp == null) {\n // check JSP views\n disp = createRequestDispatcher(req, node.getClass(), node, next + \".jsp\");\n if (disp == null)\n return false;\n }\n req.tokens.next();\n if (traceable())\n trace(req, rsp, \"Invoking \" + next + \".jsp\" + \" on \" + node + \" for \" + req.tokens);\n stapler.forward(disp, req, rsp);\n return true;\n }\n\n public String toString() {\n return \"TOKEN.jsp for url=/TOKEN/...\";\n }\n });\n }\n\n public RequestDispatcher createRequestDispatcher(RequestImpl request, Klass type, Object it, String viewName) throws IOException {\n ServletContext context = request.stapler.getServletContext();\n // JSP support is deprecated, and this doesn't work with non-Java objects\n for (Class c = type.toJavaClass(); c != Object.class; c = c.getSuperclass()) {\n String name = \"/WEB-INF/side-files/\" + c.getName().replace('.', '/').replace('$', '/') + '/' + viewName;\n if (context.getResource(name) != null) {\n // Tomcat returns a RequestDispatcher even if the JSP file doesn't exist.\n // so check if the resource exists first.\n RequestDispatcher disp = context.getRequestDispatcher(name);\n if (disp != null) {\n return new RequestDispatcherWrapper(disp, it);\n }\n }\n }\n return null;\n }\n\n public boolean handleIndexRequest(RequestImpl req, ResponseImpl rsp, Object node, MetaClass nodeMetaClass) throws IOException, ServletException {\n Stapler stapler = req.stapler;\n // TODO: find the list of welcome pages for this class by reading web.xml\n RequestDispatcher indexJsp = createRequestDispatcher(req, node.getClass(), node, \"index.jsp\");\n if (indexJsp != null) {\n if (LOGGER.isLoggable(Level.FINE))\n LOGGER.fine(\"Invoking index.jsp on \" + node);\n stapler.forward(indexJsp, req, rsp);\n return true;\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_124", "language": "Java", "task_type": "single_line", "source_file": "java/github/stapler/stapler/jsp/src/main/java/org/kohsuke/stapler/jsp/JSPFacet.java", "mask_start_position": 2288, "mask_end_position": 2298, "canonical_solution": "turn true;", "pre_mask_code": "/*\n * All rights reserved.\n *\n */\npackage org.kohsuke.stapler.jsp;\n\nimport org.kohsuke.stapler.Facet;\nimport org.kohsuke.stapler.MetaClass;\nimport org.kohsuke.stapler.Dispatcher;\nimport org.kohsuke.stapler.RequestImpl;\nimport org.kohsuke.stapler.ResponseImpl;\nimport org.kohsuke.stapler.Stapler;\nimport org.kohsuke.MetaInfServices;\nimport org.kohsuke.stapler.lang.Klass;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletContext;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.io.IOException;\n\n/**\n * {@link Facet} that adds JSP file support.\n *\n * @author Kohsuke Kawaguchi\n */\n@MetaInfServices\npublic class JSPFacet extends Facet {\n\n public void buildViewDispatchers(MetaClass owner, List dispatchers) {\n dispatchers.add(new Dispatcher() {\n\n public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException {\n String next = req.tokens.peek();\n if (next == null)\n return false;\n // only match the end of the URL\n if (req.tokens.countRemainingTokens() > 1)\n return false;\n // and avoid serving both \"foo\" and \"foo/\" as relative URL semantics are drastically different\n if (req.getRequestURI().endsWith(\"/\"))\n return false;\n Stapler stapler = req.getStapler();\n if (!isBasename(next)) {\n // potentially an attempt to make a folder traversal\n return false;\n }\n // check static resources\n RequestDispatcher disp = createRequestDispatcher(req, node.getClass(), node, next);\n if (disp == null) {\n // check JSP views\n disp = createRequestDispatcher(req, node.getClass(), node, next + \".jsp\");\n if (disp == null)\n return false;\n }\n req.tokens.next();\n if (traceable())\n trace(req, rsp, \"Invoking \" + next + \".jsp\" + \" on \" + node + \" for \" + req.tokens);\n stapler.forward(disp, req, rsp);\n re", "post_mask_code": "\n }\n\n public String toString() {\n return \"TOKEN.jsp for url=/TOKEN/...\";\n }\n });\n }\n\n public RequestDispatcher createRequestDispatcher(RequestImpl request, Klass type, Object it, String viewName) throws IOException {\n ServletContext context = request.stapler.getServletContext();\n // JSP support is deprecated, and this doesn't work with non-Java objects\n for (Class c = type.toJavaClass(); c != Object.class; c = c.getSuperclass()) {\n String name = \"/WEB-INF/side-files/\" + c.getName().replace('.', '/').replace('$', '/') + '/' + viewName;\n if (context.getResource(name) != null) {\n // Tomcat returns a RequestDispatcher even if the JSP file doesn't exist.\n // so check if the resource exists first.\n RequestDispatcher disp = context.getRequestDispatcher(name);\n if (disp != null) {\n return new RequestDispatcherWrapper(disp, it);\n }\n }\n }\n return null;\n }\n\n public boolean handleIndexRequest(RequestImpl req, ResponseImpl rsp, Object node, MetaClass nodeMetaClass) throws IOException, ServletException {\n Stapler stapler = req.stapler;\n // TODO: find the list of welcome pages for this class by reading web.xml\n RequestDispatcher indexJsp = createRequestDispatcher(req, node.getClass(), node, \"index.jsp\");\n if (indexJsp != null) {\n if (LOGGER.isLoggable(Level.FINE))\n LOGGER.fine(\"Invoking index.jsp on \" + node);\n stapler.forward(indexJsp, req, rsp);\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_125", "language": "Java", "task_type": "if_statement", "source_file": "java/github/stapler/stapler/jsp/src/main/java/org/kohsuke/stapler/jsp/JSPFacet.java", "mask_start_position": 2099, "mask_end_position": 2220, "canonical_solution": "if (traceable())\n trace(req, rsp, \"Invoking \" + next + \".jsp\" + \" on \" + node + \" for \" + req.tokens);", "pre_mask_code": "/*\n * All rights reserved.\n *\n */\npackage org.kohsuke.stapler.jsp;\n\nimport org.kohsuke.stapler.Facet;\nimport org.kohsuke.stapler.MetaClass;\nimport org.kohsuke.stapler.Dispatcher;\nimport org.kohsuke.stapler.RequestImpl;\nimport org.kohsuke.stapler.ResponseImpl;\nimport org.kohsuke.stapler.Stapler;\nimport org.kohsuke.MetaInfServices;\nimport org.kohsuke.stapler.lang.Klass;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletContext;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.io.IOException;\n\n/**\n * {@link Facet} that adds JSP file support.\n *\n * @author Kohsuke Kawaguchi\n */\n@MetaInfServices\npublic class JSPFacet extends Facet {\n\n public void buildViewDispatchers(MetaClass owner, List dispatchers) {\n dispatchers.add(new Dispatcher() {\n\n public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException {\n String next = req.tokens.peek();\n if (next == null)\n return false;\n // only match the end of the URL\n if (req.tokens.countRemainingTokens() > 1)\n return false;\n // and avoid serving both \"foo\" and \"foo/\" as relative URL semantics are drastically different\n if (req.getRequestURI().endsWith(\"/\"))\n return false;\n Stapler stapler = req.getStapler();\n if (!isBasename(next)) {\n // potentially an attempt to make a folder traversal\n return false;\n }\n // check static resources\n RequestDispatcher disp = createRequestDispatcher(req, node.getClass(), node, next);\n if (disp == null) {\n // check JSP views\n disp = createRequestDispatcher(req, node.getClass(), node, next + \".jsp\");\n if (disp == null)\n return false;\n }\n req.tokens.next();\n ", "post_mask_code": "\n stapler.forward(disp, req, rsp);\n return true;\n }\n\n public String toString() {\n return \"TOKEN.jsp for url=/TOKEN/...\";\n }\n });\n }\n\n public RequestDispatcher createRequestDispatcher(RequestImpl request, Klass type, Object it, String viewName) throws IOException {\n ServletContext context = request.stapler.getServletContext();\n // JSP support is deprecated, and this doesn't work with non-Java objects\n for (Class c = type.toJavaClass(); c != Object.class; c = c.getSuperclass()) {\n String name = \"/WEB-INF/side-files/\" + c.getName().replace('.', '/').replace('$', '/') + '/' + viewName;\n if (context.getResource(name) != null) {\n // Tomcat returns a RequestDispatcher even if the JSP file doesn't exist.\n // so check if the resource exists first.\n RequestDispatcher disp = context.getRequestDispatcher(name);\n if (disp != null) {\n return new RequestDispatcherWrapper(disp, it);\n }\n }\n }\n return null;\n }\n\n public boolean handleIndexRequest(RequestImpl req, ResponseImpl rsp, Object node, MetaClass nodeMetaClass) throws IOException, ServletException {\n Stapler stapler = req.stapler;\n // TODO: find the list of welcome pages for this class by reading web.xml\n RequestDispatcher indexJsp = createRequestDispatcher(req, node.getClass(), node, \"index.jsp\");\n if (indexJsp != null) {\n if (LOGGER.isLoggable(Level.FINE))\n LOGGER.fine(\"Invoking index.jsp on \" + node);\n stapler.forward(indexJsp, req, rsp);\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_126", "language": "Java", "task_type": "empty", "source_file": "java/github/stapler/stapler/jsp/src/main/java/org/kohsuke/stapler/jsp/JSPFacet.java", "mask_start_position": 3945, "mask_end_position": 3945, "canonical_solution": "", "pre_mask_code": "/*\n * All rights reserved.\n *\n */\npackage org.kohsuke.stapler.jsp;\n\nimport org.kohsuke.stapler.Facet;\nimport org.kohsuke.stapler.MetaClass;\nimport org.kohsuke.stapler.Dispatcher;\nimport org.kohsuke.stapler.RequestImpl;\nimport org.kohsuke.stapler.ResponseImpl;\nimport org.kohsuke.stapler.Stapler;\nimport org.kohsuke.MetaInfServices;\nimport org.kohsuke.stapler.lang.Klass;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletContext;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.io.IOException;\n\n/**\n * {@link Facet} that adds JSP file support.\n *\n * @author Kohsuke Kawaguchi\n */\n@MetaInfServices\npublic class JSPFacet extends Facet {\n\n public void buildViewDispatchers(MetaClass owner, List dispatchers) {\n dispatchers.add(new Dispatcher() {\n\n public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException {\n String next = req.tokens.peek();\n if (next == null)\n return false;\n // only match the end of the URL\n if (req.tokens.countRemainingTokens() > 1)\n return false;\n // and avoid serving both \"foo\" and \"foo/\" as relative URL semantics are drastically different\n if (req.getRequestURI().endsWith(\"/\"))\n return false;\n Stapler stapler = req.getStapler();\n if (!isBasename(next)) {\n // potentially an attempt to make a folder traversal\n return false;\n }\n // check static resources\n RequestDispatcher disp = createRequestDispatcher(req, node.getClass(), node, next);\n if (disp == null) {\n // check JSP views\n disp = createRequestDispatcher(req, node.getClass(), node, next + \".jsp\");\n if (disp == null)\n return false;\n }\n req.tokens.next();\n if (traceable())\n trace(req, rsp, \"Invoking \" + next + \".jsp\" + \" on \" + node + \" for \" + req.tokens);\n stapler.forward(disp, req, rsp);\n return true;\n }\n\n public String toString() {\n return \"TOKEN.jsp for url=/TOKEN/...\";\n }\n });\n }\n\n public RequestDispatcher createRequestDispatcher(RequestImpl request, Klass type, Object it, String viewName) throws IOException {\n ServletContext context = request.stapler.getServletContext();\n // JSP support is deprecated, and this doesn't work with non-Java objects\n for (Class c = type.toJavaClass(); c != Object.class; c = c.getSuperclass()) {\n String name = \"/WEB-INF/side-files/\" + c.getName().replace('.', '/').replace('$', '/') + '/' + viewName;\n if (context.getResource(name) != null) {\n // Tomcat returns a RequestDispatcher even if the JSP file doesn't exist.\n // so check if the resource exists first.\n RequestDispatcher disp = context.getRequestDispatcher(name);\n if (disp != null) {\n return new RequestDispatcherWrapper(disp, it);\n }\n }\n }\n return null;\n }\n\n public boolean handleIndexRequest(RequestImpl req, ResponseImpl rsp, Object node, MetaClass nodeMetaClass) throws IOException, ServletException {\n Stapler stapler = req.stapler;\n // TODO: find the list of welcome pages for this class by reading web.xml\n RequestDispatcher indexJsp = createRequestDispatcher(req, node.getClass(), node, \"index.jsp\");\n if (indexJsp != null) {\n if (LOGGER.isLoggable(Level.FINE))\n LOGGER.fine(\"Invoking index.jsp on \" + node);\n stapler.forward(indexJsp, req, rsp)", "post_mask_code": ";\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_127", "language": "Java", "task_type": "method_signature", "source_file": "java/github/javaee/jstl-api/impl/src/main/java/org/apache/taglibs/standard/tag/rt/core/ForEachTag.java", "mask_start_position": 718, "mask_end_position": 769, "canonical_solution": "public void setEnd(int end) throws JspTagException ", "pre_mask_code": "package org.apache.taglibs.standard.tag.rt.core;\n\nimport java.util.ArrayList;\nimport javax.servlet.jsp.JspTagException;\nimport javax.servlet.jsp.jstl.core.LoopTag;\nimport javax.servlet.jsp.tagext.IterationTag;\nimport org.apache.taglibs.standard.tag.common.core.ForEachSupport;\n\n/**\n *

A handler for <forEach> that supports rtexprvalue-based\n * attributes.

\n *\n * @author Shawn Bayern\n */\npublic class ForEachTag extends ForEachSupport implements LoopTag, IterationTag {\n\n // Accessor methods\n // for tag attribute\n public void setBegin(int begin) throws JspTagException {\n this.beginSpecified = true;\n this.begin = begin;\n validateBegin();\n }\n\n // for tag attribute\n ", "post_mask_code": "{\n this.endSpecified = true;\n this.end = end;\n validateEnd();\n }\n\n // for tag attribute\n public void setStep(int step) throws JspTagException {\n this.stepSpecified = true;\n this.step = step;\n validateStep();\n }\n\n public void setItems(Object o) throws JspTagException {\n // for null items, simulate an empty list\n if (o == null)\n rawItems = new ArrayList();\n else\n rawItems = o;\n }\n}\n"} {"task_id": "Java_128", "language": "Java", "task_type": "method_body", "source_file": "java/github/javaee/jstl-api/impl/src/main/java/org/apache/taglibs/standard/tag/rt/core/ForEachTag.java", "mask_start_position": 591, "mask_end_position": 687, "canonical_solution": "{\n this.beginSpecified = true;\n this.begin = begin;\n validateBegin();\n }", "pre_mask_code": "package org.apache.taglibs.standard.tag.rt.core;\n\nimport java.util.ArrayList;\nimport javax.servlet.jsp.JspTagException;\nimport javax.servlet.jsp.jstl.core.LoopTag;\nimport javax.servlet.jsp.tagext.IterationTag;\nimport org.apache.taglibs.standard.tag.common.core.ForEachSupport;\n\n/**\n *

A handler for <forEach> that supports rtexprvalue-based\n * attributes.

\n *\n * @author Shawn Bayern\n */\npublic class ForEachTag extends ForEachSupport implements LoopTag, IterationTag {\n\n // Accessor methods\n // for tag attribute\n public void setBegin(int begin) throws JspTagException ", "post_mask_code": "\n\n // for tag attribute\n public void setEnd(int end) throws JspTagException {\n this.endSpecified = true;\n this.end = end;\n validateEnd();\n }\n\n // for tag attribute\n public void setStep(int step) throws JspTagException {\n this.stepSpecified = true;\n this.step = step;\n validateStep();\n }\n\n public void setItems(Object o) throws JspTagException {\n // for null items, simulate an empty list\n if (o == null)\n rawItems = new ArrayList();\n else\n rawItems = o;\n }\n}\n"} {"task_id": "Java_129", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/javaee/jstl-api/impl/src/main/java/org/apache/taglibs/standard/tag/rt/core/ForEachTag.java", "mask_start_position": 1094, "mask_end_position": 1144, "canonical_solution": "\n // for null items, simulate an empty list", "pre_mask_code": "package org.apache.taglibs.standard.tag.rt.core;\n\nimport java.util.ArrayList;\nimport javax.servlet.jsp.JspTagException;\nimport javax.servlet.jsp.jstl.core.LoopTag;\nimport javax.servlet.jsp.tagext.IterationTag;\nimport org.apache.taglibs.standard.tag.common.core.ForEachSupport;\n\n/**\n *

A handler for <forEach> that supports rtexprvalue-based\n * attributes.

\n *\n * @author Shawn Bayern\n */\npublic class ForEachTag extends ForEachSupport implements LoopTag, IterationTag {\n\n // Accessor methods\n // for tag attribute\n public void setBegin(int begin) throws JspTagException {\n this.beginSpecified = true;\n this.begin = begin;\n validateBegin();\n }\n\n // for tag attribute\n public void setEnd(int end) throws JspTagException {\n this.endSpecified = true;\n this.end = end;\n validateEnd();\n }\n\n // for tag attribute\n public void setStep(int step) throws JspTagException {\n this.stepSpecified = true;\n this.step = step;\n validateStep();\n }\n\n public void setItems(Object o) throws JspTagException {", "post_mask_code": "\n if (o == null)\n rawItems = new ArrayList();\n else\n rawItems = o;\n }\n}\n"} {"task_id": "Java_130", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/javaee/jstl-api/impl/src/main/java/org/apache/taglibs/standard/tag/rt/core/ForEachTag.java", "mask_start_position": 1153, "mask_end_position": 1246, "canonical_solution": "if (o == null)\n rawItems = new ArrayList();\n else\n rawItems = o;", "pre_mask_code": "package org.apache.taglibs.standard.tag.rt.core;\n\nimport java.util.ArrayList;\nimport javax.servlet.jsp.JspTagException;\nimport javax.servlet.jsp.jstl.core.LoopTag;\nimport javax.servlet.jsp.tagext.IterationTag;\nimport org.apache.taglibs.standard.tag.common.core.ForEachSupport;\n\n/**\n *

A handler for <forEach> that supports rtexprvalue-based\n * attributes.

\n *\n * @author Shawn Bayern\n */\npublic class ForEachTag extends ForEachSupport implements LoopTag, IterationTag {\n\n // Accessor methods\n // for tag attribute\n public void setBegin(int begin) throws JspTagException {\n this.beginSpecified = true;\n this.begin = begin;\n validateBegin();\n }\n\n // for tag attribute\n public void setEnd(int end) throws JspTagException {\n this.endSpecified = true;\n this.end = end;\n validateEnd();\n }\n\n // for tag attribute\n public void setStep(int step) throws JspTagException {\n this.stepSpecified = true;\n this.step = step;\n validateStep();\n }\n\n public void setItems(Object o) throws JspTagException {\n // for null items, simulate an empty list\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_131", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/javaee/jstl-api/impl/src/main/java/org/apache/taglibs/standard/tag/rt/core/ForEachTag.java", "mask_start_position": 1251, "mask_end_position": 1252, "canonical_solution": "}", "pre_mask_code": "package org.apache.taglibs.standard.tag.rt.core;\n\nimport java.util.ArrayList;\nimport javax.servlet.jsp.JspTagException;\nimport javax.servlet.jsp.jstl.core.LoopTag;\nimport javax.servlet.jsp.tagext.IterationTag;\nimport org.apache.taglibs.standard.tag.common.core.ForEachSupport;\n\n/**\n *

A handler for <forEach> that supports rtexprvalue-based\n * attributes.

\n *\n * @author Shawn Bayern\n */\npublic class ForEachTag extends ForEachSupport implements LoopTag, IterationTag {\n\n // Accessor methods\n // for tag attribute\n public void setBegin(int begin) throws JspTagException {\n this.beginSpecified = true;\n this.begin = begin;\n validateBegin();\n }\n\n // for tag attribute\n public void setEnd(int end) throws JspTagException {\n this.endSpecified = true;\n this.end = end;\n validateEnd();\n }\n\n // for tag attribute\n public void setStep(int step) throws JspTagException {\n this.stepSpecified = true;\n this.step = step;\n validateStep();\n }\n\n public void setItems(Object o) throws JspTagException {\n // for null items, simulate an empty list\n if (o == null)\n rawItems = new ArrayList();\n else\n rawItems = o;\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_132", "language": "Java", "task_type": "single_line", "source_file": "java/github/javaee/jstl-api/impl/src/main/java/org/apache/taglibs/standard/tag/rt/core/ForEachTag.java", "mask_start_position": 825, "mask_end_position": 828, "canonical_solution": "nd;", "pre_mask_code": "package org.apache.taglibs.standard.tag.rt.core;\n\nimport java.util.ArrayList;\nimport javax.servlet.jsp.JspTagException;\nimport javax.servlet.jsp.jstl.core.LoopTag;\nimport javax.servlet.jsp.tagext.IterationTag;\nimport org.apache.taglibs.standard.tag.common.core.ForEachSupport;\n\n/**\n *

A handler for <forEach> that supports rtexprvalue-based\n * attributes.

\n *\n * @author Shawn Bayern\n */\npublic class ForEachTag extends ForEachSupport implements LoopTag, IterationTag {\n\n // Accessor methods\n // for tag attribute\n public void setBegin(int begin) throws JspTagException {\n this.beginSpecified = true;\n this.begin = begin;\n validateBegin();\n }\n\n // for tag attribute\n public void setEnd(int end) throws JspTagException {\n this.endSpecified = true;\n this.end = e", "post_mask_code": "\n validateEnd();\n }\n\n // for tag attribute\n public void setStep(int step) throws JspTagException {\n this.stepSpecified = true;\n this.step = step;\n validateStep();\n }\n\n public void setItems(Object o) throws JspTagException {\n // for null items, simulate an empty list\n if (o == null)\n rawItems = new ArrayList();\n else\n rawItems = o;\n }\n}\n"} {"task_id": "Java_133", "language": "Java", "task_type": "if_statement", "source_file": "java/github/javaee/jstl-api/impl/src/main/java/org/apache/taglibs/standard/tag/rt/core/ForEachTag.java", "mask_start_position": 1153, "mask_end_position": 1246, "canonical_solution": "if (o == null)\n rawItems = new ArrayList();\n else\n rawItems = o;", "pre_mask_code": "package org.apache.taglibs.standard.tag.rt.core;\n\nimport java.util.ArrayList;\nimport javax.servlet.jsp.JspTagException;\nimport javax.servlet.jsp.jstl.core.LoopTag;\nimport javax.servlet.jsp.tagext.IterationTag;\nimport org.apache.taglibs.standard.tag.common.core.ForEachSupport;\n\n/**\n *

A handler for <forEach> that supports rtexprvalue-based\n * attributes.

\n *\n * @author Shawn Bayern\n */\npublic class ForEachTag extends ForEachSupport implements LoopTag, IterationTag {\n\n // Accessor methods\n // for tag attribute\n public void setBegin(int begin) throws JspTagException {\n this.beginSpecified = true;\n this.begin = begin;\n validateBegin();\n }\n\n // for tag attribute\n public void setEnd(int end) throws JspTagException {\n this.endSpecified = true;\n this.end = end;\n validateEnd();\n }\n\n // for tag attribute\n public void setStep(int step) throws JspTagException {\n this.stepSpecified = true;\n this.step = step;\n validateStep();\n }\n\n public void setItems(Object o) throws JspTagException {\n // for null items, simulate an empty list\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_134", "language": "Java", "task_type": "empty", "source_file": "java/github/javaee/jstl-api/impl/src/main/java/org/apache/taglibs/standard/tag/rt/core/ForEachTag.java", "mask_start_position": 1054, "mask_end_position": 1054, "canonical_solution": "", "pre_mask_code": "package org.apache.taglibs.standard.tag.rt.core;\n\nimport java.util.ArrayList;\nimport javax.servlet.jsp.JspTagException;\nimport javax.servlet.jsp.jstl.core.LoopTag;\nimport javax.servlet.jsp.tagext.IterationTag;\nimport org.apache.taglibs.standard.tag.common.core.ForEachSupport;\n\n/**\n *

A handler for <forEach> that supports rtexprvalue-based\n * attributes.

\n *\n * @author Shawn Bayern\n */\npublic class ForEachTag extends ForEachSupport implements LoopTag, IterationTag {\n\n // Accessor methods\n // for tag attribute\n public void setBegin(int begin) throws JspTagException {\n this.beginSpecified = true;\n this.begin = begin;\n validateBegin();\n }\n\n // for tag attribute\n public void setEnd(int end) throws JspTagException {\n this.endSpecified = true;\n this.end = end;\n validateEnd();\n }\n\n // for tag attribute\n public void setStep(int step) throws JspTagException {\n this.stepSpecified = true;\n this.step = step;\n validateStep();\n }\n\n public void set", "post_mask_code": "Items(Object o) throws JspTagException {\n // for null items, simulate an empty list\n if (o == null)\n rawItems = new ArrayList();\n else\n rawItems = o;\n }\n}\n"} {"task_id": "Java_135", "language": "Java", "task_type": "method_signature", "source_file": "java/github/VKCOM/vk-java-sdk/sdk/src/main/java/com/vk/api/sdk/objects/groups/CountersGroup.java", "mask_start_position": 3343, "mask_end_position": 3370, "canonical_solution": "public Integer getVideos() ", "pre_mask_code": "// Autogenerated from vk-api-schema. Please don't edit it manually.\npackage com.vk.api.sdk.objects.groups;\n\nimport com.google.gson.Gson;\nimport com.google.gson.annotations.SerializedName;\nimport com.vk.api.sdk.objects.Validable;\nimport java.util.Objects;\n\n/**\n * CountersGroup object\n */\npublic class CountersGroup implements Validable {\n\n /**\n * Addresses number\n */\n @SerializedName(\"addresses\")\n private Integer addresses;\n\n /**\n * Photo albums number\n */\n @SerializedName(\"albums\")\n private Integer albums;\n\n /**\n * Audios number\n */\n @SerializedName(\"audios\")\n private Integer audios;\n\n /**\n * Audio playlists number\n */\n @SerializedName(\"audio_playlists\")\n private Integer audioPlaylists;\n\n /**\n * Docs number\n */\n @SerializedName(\"docs\")\n private Integer docs;\n\n /**\n * Market items number\n */\n @SerializedName(\"market\")\n private Integer market;\n\n /**\n * Photos number\n */\n @SerializedName(\"photos\")\n private Integer photos;\n\n /**\n * Topics number\n */\n @SerializedName(\"topics\")\n private Integer topics;\n\n /**\n * Videos number\n */\n @SerializedName(\"videos\")\n private Integer videos;\n\n /**\n * Market services number\n */\n @SerializedName(\"market_services\")\n private Integer marketServices;\n\n /**\n * Podcasts number\n */\n @SerializedName(\"podcasts\")\n private Integer podcasts;\n\n /**\n * Articles number\n */\n @SerializedName(\"articles\")\n private Integer articles;\n\n /**\n * Narratives number\n */\n @SerializedName(\"narratives\")\n private Integer narratives;\n\n /**\n * Clips number\n */\n @SerializedName(\"clips\")\n private Integer clips;\n\n /**\n * Clips followers number\n */\n @SerializedName(\"clips_followers\")\n private Integer clipsFollowers;\n\n public Integer getAddresses() {\n return addresses;\n }\n\n public CountersGroup setAddresses(Integer addresses) {\n this.addresses = addresses;\n return this;\n }\n\n public Integer getAlbums() {\n return albums;\n }\n\n public CountersGroup setAlbums(Integer albums) {\n this.albums = albums;\n return this;\n }\n\n public Integer getAudios() {\n return audios;\n }\n\n public CountersGroup setAudios(Integer audios) {\n this.audios = audios;\n return this;\n }\n\n public Integer getAudioPlaylists() {\n return audioPlaylists;\n }\n\n public CountersGroup setAudioPlaylists(Integer audioPlaylists) {\n this.audioPlaylists = audioPlaylists;\n return this;\n }\n\n public Integer getDocs() {\n return docs;\n }\n\n public CountersGroup setDocs(Integer docs) {\n this.docs = docs;\n return this;\n }\n\n public Integer getMarket() {\n return market;\n }\n\n public CountersGroup setMarket(Integer market) {\n this.market = market;\n return this;\n }\n\n public Integer getPhotos() {\n return photos;\n }\n\n public CountersGroup setPhotos(Integer photos) {\n this.photos = photos;\n return this;\n }\n\n public Integer getTopics() {\n return topics;\n }\n\n public CountersGroup setTopics(Integer topics) {\n this.topics = topics;\n return this;\n }\n\n ", "post_mask_code": "{\n return videos;\n }\n\n public CountersGroup setVideos(Integer videos) {\n this.videos = videos;\n return this;\n }\n\n public Integer getMarketServices() {\n return marketServices;\n }\n\n public CountersGroup setMarketServices(Integer marketServices) {\n this.marketServices = marketServices;\n return this;\n }\n\n public Integer getPodcasts() {\n return podcasts;\n }\n\n public CountersGroup setPodcasts(Integer podcasts) {\n this.podcasts = podcasts;\n return this;\n }\n\n public Integer getArticles() {\n return articles;\n }\n\n public CountersGroup setArticles(Integer articles) {\n this.articles = articles;\n return this;\n }\n\n public Integer getNarratives() {\n return narratives;\n }\n\n public CountersGroup setNarratives(Integer narratives) {\n this.narratives = narratives;\n return this;\n }\n\n public Integer getClips() {\n return clips;\n }\n\n public CountersGroup setClips(Integer clips) {\n this.clips = clips;\n return this;\n }\n\n public Integer getClipsFollowers() {\n return clipsFollowers;\n }\n\n public CountersGroup setClipsFollowers(Integer clipsFollowers) {\n this.clipsFollowers = clipsFollowers;\n return this;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(addresses, albums, narratives, topics, clips, marketServices, videos, photos, market, podcasts, docs, audios, audioPlaylists, articles, clipsFollowers);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n CountersGroup countersGroup = (CountersGroup) o;\n return Objects.equals(addresses, countersGroup.addresses) && Objects.equals(albums, countersGroup.albums) && Objects.equals(narratives, countersGroup.narratives) && Objects.equals(topics, countersGroup.topics) && Objects.equals(clips, countersGroup.clips) && Objects.equals(audioPlaylists, countersGroup.audioPlaylists) && Objects.equals(videos, countersGroup.videos) && Objects.equals(marketServices, countersGroup.marketServices) && Objects.equals(photos, countersGroup.photos) && Objects.equals(market, countersGroup.market) && Objects.equals(podcasts, countersGroup.podcasts) && Objects.equals(docs, countersGroup.docs) && Objects.equals(audios, countersGroup.audios) && Objects.equals(clipsFollowers, countersGroup.clipsFollowers) && Objects.equals(articles, countersGroup.articles);\n }\n\n @Override\n public String toString() {\n final Gson gson = new Gson();\n return gson.toJson(this);\n }\n\n public String toPrettyString() {\n final StringBuilder sb = new StringBuilder(\"CountersGroup{\");\n sb.append(\"addresses=\").append(addresses);\n sb.append(\", albums=\").append(albums);\n sb.append(\", narratives=\").append(narratives);\n sb.append(\", topics=\").append(topics);\n sb.append(\", clips=\").append(clips);\n sb.append(\", audioPlaylists=\").append(audioPlaylists);\n sb.append(\", videos=\").append(videos);\n sb.append(\", marketServices=\").append(marketServices);\n sb.append(\", photos=\").append(photos);\n sb.append(\", market=\").append(market);\n sb.append(\", podcasts=\").append(podcasts);\n sb.append(\", docs=\").append(docs);\n sb.append(\", audios=\").append(audios);\n sb.append(\", clipsFollowers=\").append(clipsFollowers);\n sb.append(\", articles=\").append(articles);\n sb.append('}');\n return sb.toString();\n }\n}\n"} {"task_id": "Java_136", "language": "Java", "task_type": "method_body", "source_file": "java/github/VKCOM/vk-java-sdk/sdk/src/main/java/com/vk/api/sdk/objects/groups/CountersGroup.java", "mask_start_position": 4335, "mask_end_position": 4364, "canonical_solution": "{\n return clips;\n }", "pre_mask_code": "// Autogenerated from vk-api-schema. Please don't edit it manually.\npackage com.vk.api.sdk.objects.groups;\n\nimport com.google.gson.Gson;\nimport com.google.gson.annotations.SerializedName;\nimport com.vk.api.sdk.objects.Validable;\nimport java.util.Objects;\n\n/**\n * CountersGroup object\n */\npublic class CountersGroup implements Validable {\n\n /**\n * Addresses number\n */\n @SerializedName(\"addresses\")\n private Integer addresses;\n\n /**\n * Photo albums number\n */\n @SerializedName(\"albums\")\n private Integer albums;\n\n /**\n * Audios number\n */\n @SerializedName(\"audios\")\n private Integer audios;\n\n /**\n * Audio playlists number\n */\n @SerializedName(\"audio_playlists\")\n private Integer audioPlaylists;\n\n /**\n * Docs number\n */\n @SerializedName(\"docs\")\n private Integer docs;\n\n /**\n * Market items number\n */\n @SerializedName(\"market\")\n private Integer market;\n\n /**\n * Photos number\n */\n @SerializedName(\"photos\")\n private Integer photos;\n\n /**\n * Topics number\n */\n @SerializedName(\"topics\")\n private Integer topics;\n\n /**\n * Videos number\n */\n @SerializedName(\"videos\")\n private Integer videos;\n\n /**\n * Market services number\n */\n @SerializedName(\"market_services\")\n private Integer marketServices;\n\n /**\n * Podcasts number\n */\n @SerializedName(\"podcasts\")\n private Integer podcasts;\n\n /**\n * Articles number\n */\n @SerializedName(\"articles\")\n private Integer articles;\n\n /**\n * Narratives number\n */\n @SerializedName(\"narratives\")\n private Integer narratives;\n\n /**\n * Clips number\n */\n @SerializedName(\"clips\")\n private Integer clips;\n\n /**\n * Clips followers number\n */\n @SerializedName(\"clips_followers\")\n private Integer clipsFollowers;\n\n public Integer getAddresses() {\n return addresses;\n }\n\n public CountersGroup setAddresses(Integer addresses) {\n this.addresses = addresses;\n return this;\n }\n\n public Integer getAlbums() {\n return albums;\n }\n\n public CountersGroup setAlbums(Integer albums) {\n this.albums = albums;\n return this;\n }\n\n public Integer getAudios() {\n return audios;\n }\n\n public CountersGroup setAudios(Integer audios) {\n this.audios = audios;\n return this;\n }\n\n public Integer getAudioPlaylists() {\n return audioPlaylists;\n }\n\n public CountersGroup setAudioPlaylists(Integer audioPlaylists) {\n this.audioPlaylists = audioPlaylists;\n return this;\n }\n\n public Integer getDocs() {\n return docs;\n }\n\n public CountersGroup setDocs(Integer docs) {\n this.docs = docs;\n return this;\n }\n\n public Integer getMarket() {\n return market;\n }\n\n public CountersGroup setMarket(Integer market) {\n this.market = market;\n return this;\n }\n\n public Integer getPhotos() {\n return photos;\n }\n\n public CountersGroup setPhotos(Integer photos) {\n this.photos = photos;\n return this;\n }\n\n public Integer getTopics() {\n return topics;\n }\n\n public CountersGroup setTopics(Integer topics) {\n this.topics = topics;\n return this;\n }\n\n public Integer getVideos() {\n return videos;\n }\n\n public CountersGroup setVideos(Integer videos) {\n this.videos = videos;\n return this;\n }\n\n public Integer getMarketServices() {\n return marketServices;\n }\n\n public CountersGroup setMarketServices(Integer marketServices) {\n this.marketServices = marketServices;\n return this;\n }\n\n public Integer getPodcasts() {\n return podcasts;\n }\n\n public CountersGroup setPodcasts(Integer podcasts) {\n this.podcasts = podcasts;\n return this;\n }\n\n public Integer getArticles() {\n return articles;\n }\n\n public CountersGroup setArticles(Integer articles) {\n this.articles = articles;\n return this;\n }\n\n public Integer getNarratives() {\n return narratives;\n }\n\n public CountersGroup setNarratives(Integer narratives) {\n this.narratives = narratives;\n return this;\n }\n\n public Integer getClips() ", "post_mask_code": "\n\n public CountersGroup setClips(Integer clips) {\n this.clips = clips;\n return this;\n }\n\n public Integer getClipsFollowers() {\n return clipsFollowers;\n }\n\n public CountersGroup setClipsFollowers(Integer clipsFollowers) {\n this.clipsFollowers = clipsFollowers;\n return this;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(addresses, albums, narratives, topics, clips, marketServices, videos, photos, market, podcasts, docs, audios, audioPlaylists, articles, clipsFollowers);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n CountersGroup countersGroup = (CountersGroup) o;\n return Objects.equals(addresses, countersGroup.addresses) && Objects.equals(albums, countersGroup.albums) && Objects.equals(narratives, countersGroup.narratives) && Objects.equals(topics, countersGroup.topics) && Objects.equals(clips, countersGroup.clips) && Objects.equals(audioPlaylists, countersGroup.audioPlaylists) && Objects.equals(videos, countersGroup.videos) && Objects.equals(marketServices, countersGroup.marketServices) && Objects.equals(photos, countersGroup.photos) && Objects.equals(market, countersGroup.market) && Objects.equals(podcasts, countersGroup.podcasts) && Objects.equals(docs, countersGroup.docs) && Objects.equals(audios, countersGroup.audios) && Objects.equals(clipsFollowers, countersGroup.clipsFollowers) && Objects.equals(articles, countersGroup.articles);\n }\n\n @Override\n public String toString() {\n final Gson gson = new Gson();\n return gson.toJson(this);\n }\n\n public String toPrettyString() {\n final StringBuilder sb = new StringBuilder(\"CountersGroup{\");\n sb.append(\"addresses=\").append(addresses);\n sb.append(\", albums=\").append(albums);\n sb.append(\", narratives=\").append(narratives);\n sb.append(\", topics=\").append(topics);\n sb.append(\", clips=\").append(clips);\n sb.append(\", audioPlaylists=\").append(audioPlaylists);\n sb.append(\", videos=\").append(videos);\n sb.append(\", marketServices=\").append(marketServices);\n sb.append(\", photos=\").append(photos);\n sb.append(\", market=\").append(market);\n sb.append(\", podcasts=\").append(podcasts);\n sb.append(\", docs=\").append(docs);\n sb.append(\", audios=\").append(audios);\n sb.append(\", clipsFollowers=\").append(clipsFollowers);\n sb.append(\", articles=\").append(articles);\n sb.append('}');\n return sb.toString();\n }\n}\n"} {"task_id": "Java_137", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/VKCOM/vk-java-sdk/sdk/src/main/java/com/vk/api/sdk/objects/groups/CountersGroup.java", "mask_start_position": 4976, "mask_end_position": 5024, "canonical_solution": "\n if (this == o)\n return true;", "pre_mask_code": "// Autogenerated from vk-api-schema. Please don't edit it manually.\npackage com.vk.api.sdk.objects.groups;\n\nimport com.google.gson.Gson;\nimport com.google.gson.annotations.SerializedName;\nimport com.vk.api.sdk.objects.Validable;\nimport java.util.Objects;\n\n/**\n * CountersGroup object\n */\npublic class CountersGroup implements Validable {\n\n /**\n * Addresses number\n */\n @SerializedName(\"addresses\")\n private Integer addresses;\n\n /**\n * Photo albums number\n */\n @SerializedName(\"albums\")\n private Integer albums;\n\n /**\n * Audios number\n */\n @SerializedName(\"audios\")\n private Integer audios;\n\n /**\n * Audio playlists number\n */\n @SerializedName(\"audio_playlists\")\n private Integer audioPlaylists;\n\n /**\n * Docs number\n */\n @SerializedName(\"docs\")\n private Integer docs;\n\n /**\n * Market items number\n */\n @SerializedName(\"market\")\n private Integer market;\n\n /**\n * Photos number\n */\n @SerializedName(\"photos\")\n private Integer photos;\n\n /**\n * Topics number\n */\n @SerializedName(\"topics\")\n private Integer topics;\n\n /**\n * Videos number\n */\n @SerializedName(\"videos\")\n private Integer videos;\n\n /**\n * Market services number\n */\n @SerializedName(\"market_services\")\n private Integer marketServices;\n\n /**\n * Podcasts number\n */\n @SerializedName(\"podcasts\")\n private Integer podcasts;\n\n /**\n * Articles number\n */\n @SerializedName(\"articles\")\n private Integer articles;\n\n /**\n * Narratives number\n */\n @SerializedName(\"narratives\")\n private Integer narratives;\n\n /**\n * Clips number\n */\n @SerializedName(\"clips\")\n private Integer clips;\n\n /**\n * Clips followers number\n */\n @SerializedName(\"clips_followers\")\n private Integer clipsFollowers;\n\n public Integer getAddresses() {\n return addresses;\n }\n\n public CountersGroup setAddresses(Integer addresses) {\n this.addresses = addresses;\n return this;\n }\n\n public Integer getAlbums() {\n return albums;\n }\n\n public CountersGroup setAlbums(Integer albums) {\n this.albums = albums;\n return this;\n }\n\n public Integer getAudios() {\n return audios;\n }\n\n public CountersGroup setAudios(Integer audios) {\n this.audios = audios;\n return this;\n }\n\n public Integer getAudioPlaylists() {\n return audioPlaylists;\n }\n\n public CountersGroup setAudioPlaylists(Integer audioPlaylists) {\n this.audioPlaylists = audioPlaylists;\n return this;\n }\n\n public Integer getDocs() {\n return docs;\n }\n\n public CountersGroup setDocs(Integer docs) {\n this.docs = docs;\n return this;\n }\n\n public Integer getMarket() {\n return market;\n }\n\n public CountersGroup setMarket(Integer market) {\n this.market = market;\n return this;\n }\n\n public Integer getPhotos() {\n return photos;\n }\n\n public CountersGroup setPhotos(Integer photos) {\n this.photos = photos;\n return this;\n }\n\n public Integer getTopics() {\n return topics;\n }\n\n public CountersGroup setTopics(Integer topics) {\n this.topics = topics;\n return this;\n }\n\n public Integer getVideos() {\n return videos;\n }\n\n public CountersGroup setVideos(Integer videos) {\n this.videos = videos;\n return this;\n }\n\n public Integer getMarketServices() {\n return marketServices;\n }\n\n public CountersGroup setMarketServices(Integer marketServices) {\n this.marketServices = marketServices;\n return this;\n }\n\n public Integer getPodcasts() {\n return podcasts;\n }\n\n public CountersGroup setPodcasts(Integer podcasts) {\n this.podcasts = podcasts;\n return this;\n }\n\n public Integer getArticles() {\n return articles;\n }\n\n public CountersGroup setArticles(Integer articles) {\n this.articles = articles;\n return this;\n }\n\n public Integer getNarratives() {\n return narratives;\n }\n\n public CountersGroup setNarratives(Integer narratives) {\n this.narratives = narratives;\n return this;\n }\n\n public Integer getClips() {\n return clips;\n }\n\n public CountersGroup setClips(Integer clips) {\n this.clips = clips;\n return this;\n }\n\n public Integer getClipsFollowers() {\n return clipsFollowers;\n }\n\n public CountersGroup setClipsFollowers(Integer clipsFollowers) {\n this.clipsFollowers = clipsFollowers;\n return this;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(addresses, albums, narratives, topics, clips, marketServices, videos, photos, market, podcasts, docs, audios, audioPlaylists, articles, clipsFollowers);\n }\n\n @Override\n public boolean equals(Object o) {", "post_mask_code": "\n if (o == null || getClass() != o.getClass())\n return false;\n CountersGroup countersGroup = (CountersGroup) o;\n return Objects.equals(addresses, countersGroup.addresses) && Objects.equals(albums, countersGroup.albums) && Objects.equals(narratives, countersGroup.narratives) && Objects.equals(topics, countersGroup.topics) && Objects.equals(clips, countersGroup.clips) && Objects.equals(audioPlaylists, countersGroup.audioPlaylists) && Objects.equals(videos, countersGroup.videos) && Objects.equals(marketServices, countersGroup.marketServices) && Objects.equals(photos, countersGroup.photos) && Objects.equals(market, countersGroup.market) && Objects.equals(podcasts, countersGroup.podcasts) && Objects.equals(docs, countersGroup.docs) && Objects.equals(audios, countersGroup.audios) && Objects.equals(clipsFollowers, countersGroup.clipsFollowers) && Objects.equals(articles, countersGroup.articles);\n }\n\n @Override\n public String toString() {\n final Gson gson = new Gson();\n return gson.toJson(this);\n }\n\n public String toPrettyString() {\n final StringBuilder sb = new StringBuilder(\"CountersGroup{\");\n sb.append(\"addresses=\").append(addresses);\n sb.append(\", albums=\").append(albums);\n sb.append(\", narratives=\").append(narratives);\n sb.append(\", topics=\").append(topics);\n sb.append(\", clips=\").append(clips);\n sb.append(\", audioPlaylists=\").append(audioPlaylists);\n sb.append(\", videos=\").append(videos);\n sb.append(\", marketServices=\").append(marketServices);\n sb.append(\", photos=\").append(photos);\n sb.append(\", market=\").append(market);\n sb.append(\", podcasts=\").append(podcasts);\n sb.append(\", docs=\").append(docs);\n sb.append(\", audios=\").append(audios);\n sb.append(\", clipsFollowers=\").append(clipsFollowers);\n sb.append(\", articles=\").append(articles);\n sb.append('}');\n return sb.toString();\n }\n}\n"} {"task_id": "Java_138", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/VKCOM/vk-java-sdk/sdk/src/main/java/com/vk/api/sdk/objects/groups/CountersGroup.java", "mask_start_position": 5033, "mask_end_position": 5160, "canonical_solution": "if (o == null || getClass() != o.getClass())\n return false;\n CountersGroup countersGroup = (CountersGroup) o;", "pre_mask_code": "// Autogenerated from vk-api-schema. Please don't edit it manually.\npackage com.vk.api.sdk.objects.groups;\n\nimport com.google.gson.Gson;\nimport com.google.gson.annotations.SerializedName;\nimport com.vk.api.sdk.objects.Validable;\nimport java.util.Objects;\n\n/**\n * CountersGroup object\n */\npublic class CountersGroup implements Validable {\n\n /**\n * Addresses number\n */\n @SerializedName(\"addresses\")\n private Integer addresses;\n\n /**\n * Photo albums number\n */\n @SerializedName(\"albums\")\n private Integer albums;\n\n /**\n * Audios number\n */\n @SerializedName(\"audios\")\n private Integer audios;\n\n /**\n * Audio playlists number\n */\n @SerializedName(\"audio_playlists\")\n private Integer audioPlaylists;\n\n /**\n * Docs number\n */\n @SerializedName(\"docs\")\n private Integer docs;\n\n /**\n * Market items number\n */\n @SerializedName(\"market\")\n private Integer market;\n\n /**\n * Photos number\n */\n @SerializedName(\"photos\")\n private Integer photos;\n\n /**\n * Topics number\n */\n @SerializedName(\"topics\")\n private Integer topics;\n\n /**\n * Videos number\n */\n @SerializedName(\"videos\")\n private Integer videos;\n\n /**\n * Market services number\n */\n @SerializedName(\"market_services\")\n private Integer marketServices;\n\n /**\n * Podcasts number\n */\n @SerializedName(\"podcasts\")\n private Integer podcasts;\n\n /**\n * Articles number\n */\n @SerializedName(\"articles\")\n private Integer articles;\n\n /**\n * Narratives number\n */\n @SerializedName(\"narratives\")\n private Integer narratives;\n\n /**\n * Clips number\n */\n @SerializedName(\"clips\")\n private Integer clips;\n\n /**\n * Clips followers number\n */\n @SerializedName(\"clips_followers\")\n private Integer clipsFollowers;\n\n public Integer getAddresses() {\n return addresses;\n }\n\n public CountersGroup setAddresses(Integer addresses) {\n this.addresses = addresses;\n return this;\n }\n\n public Integer getAlbums() {\n return albums;\n }\n\n public CountersGroup setAlbums(Integer albums) {\n this.albums = albums;\n return this;\n }\n\n public Integer getAudios() {\n return audios;\n }\n\n public CountersGroup setAudios(Integer audios) {\n this.audios = audios;\n return this;\n }\n\n public Integer getAudioPlaylists() {\n return audioPlaylists;\n }\n\n public CountersGroup setAudioPlaylists(Integer audioPlaylists) {\n this.audioPlaylists = audioPlaylists;\n return this;\n }\n\n public Integer getDocs() {\n return docs;\n }\n\n public CountersGroup setDocs(Integer docs) {\n this.docs = docs;\n return this;\n }\n\n public Integer getMarket() {\n return market;\n }\n\n public CountersGroup setMarket(Integer market) {\n this.market = market;\n return this;\n }\n\n public Integer getPhotos() {\n return photos;\n }\n\n public CountersGroup setPhotos(Integer photos) {\n this.photos = photos;\n return this;\n }\n\n public Integer getTopics() {\n return topics;\n }\n\n public CountersGroup setTopics(Integer topics) {\n this.topics = topics;\n return this;\n }\n\n public Integer getVideos() {\n return videos;\n }\n\n public CountersGroup setVideos(Integer videos) {\n this.videos = videos;\n return this;\n }\n\n public Integer getMarketServices() {\n return marketServices;\n }\n\n public CountersGroup setMarketServices(Integer marketServices) {\n this.marketServices = marketServices;\n return this;\n }\n\n public Integer getPodcasts() {\n return podcasts;\n }\n\n public CountersGroup setPodcasts(Integer podcasts) {\n this.podcasts = podcasts;\n return this;\n }\n\n public Integer getArticles() {\n return articles;\n }\n\n public CountersGroup setArticles(Integer articles) {\n this.articles = articles;\n return this;\n }\n\n public Integer getNarratives() {\n return narratives;\n }\n\n public CountersGroup setNarratives(Integer narratives) {\n this.narratives = narratives;\n return this;\n }\n\n public Integer getClips() {\n return clips;\n }\n\n public CountersGroup setClips(Integer clips) {\n this.clips = clips;\n return this;\n }\n\n public Integer getClipsFollowers() {\n return clipsFollowers;\n }\n\n public CountersGroup setClipsFollowers(Integer clipsFollowers) {\n this.clipsFollowers = clipsFollowers;\n return this;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(addresses, albums, narratives, topics, clips, marketServices, videos, photos, market, podcasts, docs, audios, audioPlaylists, articles, clipsFollowers);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n ", "post_mask_code": "\n return Objects.equals(addresses, countersGroup.addresses) && Objects.equals(albums, countersGroup.albums) && Objects.equals(narratives, countersGroup.narratives) && Objects.equals(topics, countersGroup.topics) && Objects.equals(clips, countersGroup.clips) && Objects.equals(audioPlaylists, countersGroup.audioPlaylists) && Objects.equals(videos, countersGroup.videos) && Objects.equals(marketServices, countersGroup.marketServices) && Objects.equals(photos, countersGroup.photos) && Objects.equals(market, countersGroup.market) && Objects.equals(podcasts, countersGroup.podcasts) && Objects.equals(docs, countersGroup.docs) && Objects.equals(audios, countersGroup.audios) && Objects.equals(clipsFollowers, countersGroup.clipsFollowers) && Objects.equals(articles, countersGroup.articles);\n }\n\n @Override\n public String toString() {\n final Gson gson = new Gson();\n return gson.toJson(this);\n }\n\n public String toPrettyString() {\n final StringBuilder sb = new StringBuilder(\"CountersGroup{\");\n sb.append(\"addresses=\").append(addresses);\n sb.append(\", albums=\").append(albums);\n sb.append(\", narratives=\").append(narratives);\n sb.append(\", topics=\").append(topics);\n sb.append(\", clips=\").append(clips);\n sb.append(\", audioPlaylists=\").append(audioPlaylists);\n sb.append(\", videos=\").append(videos);\n sb.append(\", marketServices=\").append(marketServices);\n sb.append(\", photos=\").append(photos);\n sb.append(\", market=\").append(market);\n sb.append(\", podcasts=\").append(podcasts);\n sb.append(\", docs=\").append(docs);\n sb.append(\", audios=\").append(audios);\n sb.append(\", clipsFollowers=\").append(clipsFollowers);\n sb.append(\", articles=\").append(articles);\n sb.append('}');\n return sb.toString();\n }\n}\n"} {"task_id": "Java_139", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/VKCOM/vk-java-sdk/sdk/src/main/java/com/vk/api/sdk/objects/groups/CountersGroup.java", "mask_start_position": 5169, "mask_end_position": 5963, "canonical_solution": "return Objects.equals(addresses, countersGroup.addresses) && Objects.equals(albums, countersGroup.albums) && Objects.equals(narratives, countersGroup.narratives) && Objects.equals(topics, countersGroup.topics) && Objects.equals(clips, countersGroup.clips) && Objects.equals(audioPlaylists, countersGroup.audioPlaylists) && Objects.equals(videos, countersGroup.videos) && Objects.equals(marketServices, countersGroup.marketServices) && Objects.equals(photos, countersGroup.photos) && Objects.equals(market, countersGroup.market) && Objects.equals(podcasts, countersGroup.podcasts) && Objects.equals(docs, countersGroup.docs) && Objects.equals(audios, countersGroup.audios) && Objects.equals(clipsFollowers, countersGroup.clipsFollowers) && Objects.equals(articles, countersGroup.articles);\n }", "pre_mask_code": "// Autogenerated from vk-api-schema. Please don't edit it manually.\npackage com.vk.api.sdk.objects.groups;\n\nimport com.google.gson.Gson;\nimport com.google.gson.annotations.SerializedName;\nimport com.vk.api.sdk.objects.Validable;\nimport java.util.Objects;\n\n/**\n * CountersGroup object\n */\npublic class CountersGroup implements Validable {\n\n /**\n * Addresses number\n */\n @SerializedName(\"addresses\")\n private Integer addresses;\n\n /**\n * Photo albums number\n */\n @SerializedName(\"albums\")\n private Integer albums;\n\n /**\n * Audios number\n */\n @SerializedName(\"audios\")\n private Integer audios;\n\n /**\n * Audio playlists number\n */\n @SerializedName(\"audio_playlists\")\n private Integer audioPlaylists;\n\n /**\n * Docs number\n */\n @SerializedName(\"docs\")\n private Integer docs;\n\n /**\n * Market items number\n */\n @SerializedName(\"market\")\n private Integer market;\n\n /**\n * Photos number\n */\n @SerializedName(\"photos\")\n private Integer photos;\n\n /**\n * Topics number\n */\n @SerializedName(\"topics\")\n private Integer topics;\n\n /**\n * Videos number\n */\n @SerializedName(\"videos\")\n private Integer videos;\n\n /**\n * Market services number\n */\n @SerializedName(\"market_services\")\n private Integer marketServices;\n\n /**\n * Podcasts number\n */\n @SerializedName(\"podcasts\")\n private Integer podcasts;\n\n /**\n * Articles number\n */\n @SerializedName(\"articles\")\n private Integer articles;\n\n /**\n * Narratives number\n */\n @SerializedName(\"narratives\")\n private Integer narratives;\n\n /**\n * Clips number\n */\n @SerializedName(\"clips\")\n private Integer clips;\n\n /**\n * Clips followers number\n */\n @SerializedName(\"clips_followers\")\n private Integer clipsFollowers;\n\n public Integer getAddresses() {\n return addresses;\n }\n\n public CountersGroup setAddresses(Integer addresses) {\n this.addresses = addresses;\n return this;\n }\n\n public Integer getAlbums() {\n return albums;\n }\n\n public CountersGroup setAlbums(Integer albums) {\n this.albums = albums;\n return this;\n }\n\n public Integer getAudios() {\n return audios;\n }\n\n public CountersGroup setAudios(Integer audios) {\n this.audios = audios;\n return this;\n }\n\n public Integer getAudioPlaylists() {\n return audioPlaylists;\n }\n\n public CountersGroup setAudioPlaylists(Integer audioPlaylists) {\n this.audioPlaylists = audioPlaylists;\n return this;\n }\n\n public Integer getDocs() {\n return docs;\n }\n\n public CountersGroup setDocs(Integer docs) {\n this.docs = docs;\n return this;\n }\n\n public Integer getMarket() {\n return market;\n }\n\n public CountersGroup setMarket(Integer market) {\n this.market = market;\n return this;\n }\n\n public Integer getPhotos() {\n return photos;\n }\n\n public CountersGroup setPhotos(Integer photos) {\n this.photos = photos;\n return this;\n }\n\n public Integer getTopics() {\n return topics;\n }\n\n public CountersGroup setTopics(Integer topics) {\n this.topics = topics;\n return this;\n }\n\n public Integer getVideos() {\n return videos;\n }\n\n public CountersGroup setVideos(Integer videos) {\n this.videos = videos;\n return this;\n }\n\n public Integer getMarketServices() {\n return marketServices;\n }\n\n public CountersGroup setMarketServices(Integer marketServices) {\n this.marketServices = marketServices;\n return this;\n }\n\n public Integer getPodcasts() {\n return podcasts;\n }\n\n public CountersGroup setPodcasts(Integer podcasts) {\n this.podcasts = podcasts;\n return this;\n }\n\n public Integer getArticles() {\n return articles;\n }\n\n public CountersGroup setArticles(Integer articles) {\n this.articles = articles;\n return this;\n }\n\n public Integer getNarratives() {\n return narratives;\n }\n\n public CountersGroup setNarratives(Integer narratives) {\n this.narratives = narratives;\n return this;\n }\n\n public Integer getClips() {\n return clips;\n }\n\n public CountersGroup setClips(Integer clips) {\n this.clips = clips;\n return this;\n }\n\n public Integer getClipsFollowers() {\n return clipsFollowers;\n }\n\n public CountersGroup setClipsFollowers(Integer clipsFollowers) {\n this.clipsFollowers = clipsFollowers;\n return this;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(addresses, albums, narratives, topics, clips, marketServices, videos, photos, market, podcasts, docs, audios, audioPlaylists, articles, clipsFollowers);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n CountersGroup countersGroup = (CountersGroup) o;\n ", "post_mask_code": "\n\n @Override\n public String toString() {\n final Gson gson = new Gson();\n return gson.toJson(this);\n }\n\n public String toPrettyString() {\n final StringBuilder sb = new StringBuilder(\"CountersGroup{\");\n sb.append(\"addresses=\").append(addresses);\n sb.append(\", albums=\").append(albums);\n sb.append(\", narratives=\").append(narratives);\n sb.append(\", topics=\").append(topics);\n sb.append(\", clips=\").append(clips);\n sb.append(\", audioPlaylists=\").append(audioPlaylists);\n sb.append(\", videos=\").append(videos);\n sb.append(\", marketServices=\").append(marketServices);\n sb.append(\", photos=\").append(photos);\n sb.append(\", market=\").append(market);\n sb.append(\", podcasts=\").append(podcasts);\n sb.append(\", docs=\").append(docs);\n sb.append(\", audios=\").append(audios);\n sb.append(\", clipsFollowers=\").append(clipsFollowers);\n sb.append(\", articles=\").append(articles);\n sb.append('}');\n return sb.toString();\n }\n}\n"} {"task_id": "Java_140", "language": "Java", "task_type": "single_line", "source_file": "java/github/VKCOM/vk-java-sdk/sdk/src/main/java/com/vk/api/sdk/objects/groups/CountersGroup.java", "mask_start_position": 6654, "mask_end_position": 6660, "canonical_solution": "otos);", "pre_mask_code": "// Autogenerated from vk-api-schema. Please don't edit it manually.\npackage com.vk.api.sdk.objects.groups;\n\nimport com.google.gson.Gson;\nimport com.google.gson.annotations.SerializedName;\nimport com.vk.api.sdk.objects.Validable;\nimport java.util.Objects;\n\n/**\n * CountersGroup object\n */\npublic class CountersGroup implements Validable {\n\n /**\n * Addresses number\n */\n @SerializedName(\"addresses\")\n private Integer addresses;\n\n /**\n * Photo albums number\n */\n @SerializedName(\"albums\")\n private Integer albums;\n\n /**\n * Audios number\n */\n @SerializedName(\"audios\")\n private Integer audios;\n\n /**\n * Audio playlists number\n */\n @SerializedName(\"audio_playlists\")\n private Integer audioPlaylists;\n\n /**\n * Docs number\n */\n @SerializedName(\"docs\")\n private Integer docs;\n\n /**\n * Market items number\n */\n @SerializedName(\"market\")\n private Integer market;\n\n /**\n * Photos number\n */\n @SerializedName(\"photos\")\n private Integer photos;\n\n /**\n * Topics number\n */\n @SerializedName(\"topics\")\n private Integer topics;\n\n /**\n * Videos number\n */\n @SerializedName(\"videos\")\n private Integer videos;\n\n /**\n * Market services number\n */\n @SerializedName(\"market_services\")\n private Integer marketServices;\n\n /**\n * Podcasts number\n */\n @SerializedName(\"podcasts\")\n private Integer podcasts;\n\n /**\n * Articles number\n */\n @SerializedName(\"articles\")\n private Integer articles;\n\n /**\n * Narratives number\n */\n @SerializedName(\"narratives\")\n private Integer narratives;\n\n /**\n * Clips number\n */\n @SerializedName(\"clips\")\n private Integer clips;\n\n /**\n * Clips followers number\n */\n @SerializedName(\"clips_followers\")\n private Integer clipsFollowers;\n\n public Integer getAddresses() {\n return addresses;\n }\n\n public CountersGroup setAddresses(Integer addresses) {\n this.addresses = addresses;\n return this;\n }\n\n public Integer getAlbums() {\n return albums;\n }\n\n public CountersGroup setAlbums(Integer albums) {\n this.albums = albums;\n return this;\n }\n\n public Integer getAudios() {\n return audios;\n }\n\n public CountersGroup setAudios(Integer audios) {\n this.audios = audios;\n return this;\n }\n\n public Integer getAudioPlaylists() {\n return audioPlaylists;\n }\n\n public CountersGroup setAudioPlaylists(Integer audioPlaylists) {\n this.audioPlaylists = audioPlaylists;\n return this;\n }\n\n public Integer getDocs() {\n return docs;\n }\n\n public CountersGroup setDocs(Integer docs) {\n this.docs = docs;\n return this;\n }\n\n public Integer getMarket() {\n return market;\n }\n\n public CountersGroup setMarket(Integer market) {\n this.market = market;\n return this;\n }\n\n public Integer getPhotos() {\n return photos;\n }\n\n public CountersGroup setPhotos(Integer photos) {\n this.photos = photos;\n return this;\n }\n\n public Integer getTopics() {\n return topics;\n }\n\n public CountersGroup setTopics(Integer topics) {\n this.topics = topics;\n return this;\n }\n\n public Integer getVideos() {\n return videos;\n }\n\n public CountersGroup setVideos(Integer videos) {\n this.videos = videos;\n return this;\n }\n\n public Integer getMarketServices() {\n return marketServices;\n }\n\n public CountersGroup setMarketServices(Integer marketServices) {\n this.marketServices = marketServices;\n return this;\n }\n\n public Integer getPodcasts() {\n return podcasts;\n }\n\n public CountersGroup setPodcasts(Integer podcasts) {\n this.podcasts = podcasts;\n return this;\n }\n\n public Integer getArticles() {\n return articles;\n }\n\n public CountersGroup setArticles(Integer articles) {\n this.articles = articles;\n return this;\n }\n\n public Integer getNarratives() {\n return narratives;\n }\n\n public CountersGroup setNarratives(Integer narratives) {\n this.narratives = narratives;\n return this;\n }\n\n public Integer getClips() {\n return clips;\n }\n\n public CountersGroup setClips(Integer clips) {\n this.clips = clips;\n return this;\n }\n\n public Integer getClipsFollowers() {\n return clipsFollowers;\n }\n\n public CountersGroup setClipsFollowers(Integer clipsFollowers) {\n this.clipsFollowers = clipsFollowers;\n return this;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(addresses, albums, narratives, topics, clips, marketServices, videos, photos, market, podcasts, docs, audios, audioPlaylists, articles, clipsFollowers);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n CountersGroup countersGroup = (CountersGroup) o;\n return Objects.equals(addresses, countersGroup.addresses) && Objects.equals(albums, countersGroup.albums) && Objects.equals(narratives, countersGroup.narratives) && Objects.equals(topics, countersGroup.topics) && Objects.equals(clips, countersGroup.clips) && Objects.equals(audioPlaylists, countersGroup.audioPlaylists) && Objects.equals(videos, countersGroup.videos) && Objects.equals(marketServices, countersGroup.marketServices) && Objects.equals(photos, countersGroup.photos) && Objects.equals(market, countersGroup.market) && Objects.equals(podcasts, countersGroup.podcasts) && Objects.equals(docs, countersGroup.docs) && Objects.equals(audios, countersGroup.audios) && Objects.equals(clipsFollowers, countersGroup.clipsFollowers) && Objects.equals(articles, countersGroup.articles);\n }\n\n @Override\n public String toString() {\n final Gson gson = new Gson();\n return gson.toJson(this);\n }\n\n public String toPrettyString() {\n final StringBuilder sb = new StringBuilder(\"CountersGroup{\");\n sb.append(\"addresses=\").append(addresses);\n sb.append(\", albums=\").append(albums);\n sb.append(\", narratives=\").append(narratives);\n sb.append(\", topics=\").append(topics);\n sb.append(\", clips=\").append(clips);\n sb.append(\", audioPlaylists=\").append(audioPlaylists);\n sb.append(\", videos=\").append(videos);\n sb.append(\", marketServices=\").append(marketServices);\n sb.append(\", photos=\").append(ph", "post_mask_code": "\n sb.append(\", market=\").append(market);\n sb.append(\", podcasts=\").append(podcasts);\n sb.append(\", docs=\").append(docs);\n sb.append(\", audios=\").append(audios);\n sb.append(\", clipsFollowers=\").append(clipsFollowers);\n sb.append(\", articles=\").append(articles);\n sb.append('}');\n return sb.toString();\n }\n}\n"} {"task_id": "Java_141", "language": "Java", "task_type": "if_statement", "source_file": "java/github/VKCOM/vk-java-sdk/sdk/src/main/java/com/vk/api/sdk/objects/groups/CountersGroup.java", "mask_start_position": 5033, "mask_end_position": 5103, "canonical_solution": "if (o == null || getClass() != o.getClass())\n return false;", "pre_mask_code": "// Autogenerated from vk-api-schema. Please don't edit it manually.\npackage com.vk.api.sdk.objects.groups;\n\nimport com.google.gson.Gson;\nimport com.google.gson.annotations.SerializedName;\nimport com.vk.api.sdk.objects.Validable;\nimport java.util.Objects;\n\n/**\n * CountersGroup object\n */\npublic class CountersGroup implements Validable {\n\n /**\n * Addresses number\n */\n @SerializedName(\"addresses\")\n private Integer addresses;\n\n /**\n * Photo albums number\n */\n @SerializedName(\"albums\")\n private Integer albums;\n\n /**\n * Audios number\n */\n @SerializedName(\"audios\")\n private Integer audios;\n\n /**\n * Audio playlists number\n */\n @SerializedName(\"audio_playlists\")\n private Integer audioPlaylists;\n\n /**\n * Docs number\n */\n @SerializedName(\"docs\")\n private Integer docs;\n\n /**\n * Market items number\n */\n @SerializedName(\"market\")\n private Integer market;\n\n /**\n * Photos number\n */\n @SerializedName(\"photos\")\n private Integer photos;\n\n /**\n * Topics number\n */\n @SerializedName(\"topics\")\n private Integer topics;\n\n /**\n * Videos number\n */\n @SerializedName(\"videos\")\n private Integer videos;\n\n /**\n * Market services number\n */\n @SerializedName(\"market_services\")\n private Integer marketServices;\n\n /**\n * Podcasts number\n */\n @SerializedName(\"podcasts\")\n private Integer podcasts;\n\n /**\n * Articles number\n */\n @SerializedName(\"articles\")\n private Integer articles;\n\n /**\n * Narratives number\n */\n @SerializedName(\"narratives\")\n private Integer narratives;\n\n /**\n * Clips number\n */\n @SerializedName(\"clips\")\n private Integer clips;\n\n /**\n * Clips followers number\n */\n @SerializedName(\"clips_followers\")\n private Integer clipsFollowers;\n\n public Integer getAddresses() {\n return addresses;\n }\n\n public CountersGroup setAddresses(Integer addresses) {\n this.addresses = addresses;\n return this;\n }\n\n public Integer getAlbums() {\n return albums;\n }\n\n public CountersGroup setAlbums(Integer albums) {\n this.albums = albums;\n return this;\n }\n\n public Integer getAudios() {\n return audios;\n }\n\n public CountersGroup setAudios(Integer audios) {\n this.audios = audios;\n return this;\n }\n\n public Integer getAudioPlaylists() {\n return audioPlaylists;\n }\n\n public CountersGroup setAudioPlaylists(Integer audioPlaylists) {\n this.audioPlaylists = audioPlaylists;\n return this;\n }\n\n public Integer getDocs() {\n return docs;\n }\n\n public CountersGroup setDocs(Integer docs) {\n this.docs = docs;\n return this;\n }\n\n public Integer getMarket() {\n return market;\n }\n\n public CountersGroup setMarket(Integer market) {\n this.market = market;\n return this;\n }\n\n public Integer getPhotos() {\n return photos;\n }\n\n public CountersGroup setPhotos(Integer photos) {\n this.photos = photos;\n return this;\n }\n\n public Integer getTopics() {\n return topics;\n }\n\n public CountersGroup setTopics(Integer topics) {\n this.topics = topics;\n return this;\n }\n\n public Integer getVideos() {\n return videos;\n }\n\n public CountersGroup setVideos(Integer videos) {\n this.videos = videos;\n return this;\n }\n\n public Integer getMarketServices() {\n return marketServices;\n }\n\n public CountersGroup setMarketServices(Integer marketServices) {\n this.marketServices = marketServices;\n return this;\n }\n\n public Integer getPodcasts() {\n return podcasts;\n }\n\n public CountersGroup setPodcasts(Integer podcasts) {\n this.podcasts = podcasts;\n return this;\n }\n\n public Integer getArticles() {\n return articles;\n }\n\n public CountersGroup setArticles(Integer articles) {\n this.articles = articles;\n return this;\n }\n\n public Integer getNarratives() {\n return narratives;\n }\n\n public CountersGroup setNarratives(Integer narratives) {\n this.narratives = narratives;\n return this;\n }\n\n public Integer getClips() {\n return clips;\n }\n\n public CountersGroup setClips(Integer clips) {\n this.clips = clips;\n return this;\n }\n\n public Integer getClipsFollowers() {\n return clipsFollowers;\n }\n\n public CountersGroup setClipsFollowers(Integer clipsFollowers) {\n this.clipsFollowers = clipsFollowers;\n return this;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(addresses, albums, narratives, topics, clips, marketServices, videos, photos, market, podcasts, docs, audios, audioPlaylists, articles, clipsFollowers);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n ", "post_mask_code": "\n CountersGroup countersGroup = (CountersGroup) o;\n return Objects.equals(addresses, countersGroup.addresses) && Objects.equals(albums, countersGroup.albums) && Objects.equals(narratives, countersGroup.narratives) && Objects.equals(topics, countersGroup.topics) && Objects.equals(clips, countersGroup.clips) && Objects.equals(audioPlaylists, countersGroup.audioPlaylists) && Objects.equals(videos, countersGroup.videos) && Objects.equals(marketServices, countersGroup.marketServices) && Objects.equals(photos, countersGroup.photos) && Objects.equals(market, countersGroup.market) && Objects.equals(podcasts, countersGroup.podcasts) && Objects.equals(docs, countersGroup.docs) && Objects.equals(audios, countersGroup.audios) && Objects.equals(clipsFollowers, countersGroup.clipsFollowers) && Objects.equals(articles, countersGroup.articles);\n }\n\n @Override\n public String toString() {\n final Gson gson = new Gson();\n return gson.toJson(this);\n }\n\n public String toPrettyString() {\n final StringBuilder sb = new StringBuilder(\"CountersGroup{\");\n sb.append(\"addresses=\").append(addresses);\n sb.append(\", albums=\").append(albums);\n sb.append(\", narratives=\").append(narratives);\n sb.append(\", topics=\").append(topics);\n sb.append(\", clips=\").append(clips);\n sb.append(\", audioPlaylists=\").append(audioPlaylists);\n sb.append(\", videos=\").append(videos);\n sb.append(\", marketServices=\").append(marketServices);\n sb.append(\", photos=\").append(photos);\n sb.append(\", market=\").append(market);\n sb.append(\", podcasts=\").append(podcasts);\n sb.append(\", docs=\").append(docs);\n sb.append(\", audios=\").append(audios);\n sb.append(\", clipsFollowers=\").append(clipsFollowers);\n sb.append(\", articles=\").append(articles);\n sb.append('}');\n return sb.toString();\n }\n}\n"} {"task_id": "Java_142", "language": "Java", "task_type": "empty", "source_file": "java/github/VKCOM/vk-java-sdk/sdk/src/main/java/com/vk/api/sdk/objects/groups/CountersGroup.java", "mask_start_position": 5780, "mask_end_position": 5780, "canonical_solution": "", "pre_mask_code": "// Autogenerated from vk-api-schema. Please don't edit it manually.\npackage com.vk.api.sdk.objects.groups;\n\nimport com.google.gson.Gson;\nimport com.google.gson.annotations.SerializedName;\nimport com.vk.api.sdk.objects.Validable;\nimport java.util.Objects;\n\n/**\n * CountersGroup object\n */\npublic class CountersGroup implements Validable {\n\n /**\n * Addresses number\n */\n @SerializedName(\"addresses\")\n private Integer addresses;\n\n /**\n * Photo albums number\n */\n @SerializedName(\"albums\")\n private Integer albums;\n\n /**\n * Audios number\n */\n @SerializedName(\"audios\")\n private Integer audios;\n\n /**\n * Audio playlists number\n */\n @SerializedName(\"audio_playlists\")\n private Integer audioPlaylists;\n\n /**\n * Docs number\n */\n @SerializedName(\"docs\")\n private Integer docs;\n\n /**\n * Market items number\n */\n @SerializedName(\"market\")\n private Integer market;\n\n /**\n * Photos number\n */\n @SerializedName(\"photos\")\n private Integer photos;\n\n /**\n * Topics number\n */\n @SerializedName(\"topics\")\n private Integer topics;\n\n /**\n * Videos number\n */\n @SerializedName(\"videos\")\n private Integer videos;\n\n /**\n * Market services number\n */\n @SerializedName(\"market_services\")\n private Integer marketServices;\n\n /**\n * Podcasts number\n */\n @SerializedName(\"podcasts\")\n private Integer podcasts;\n\n /**\n * Articles number\n */\n @SerializedName(\"articles\")\n private Integer articles;\n\n /**\n * Narratives number\n */\n @SerializedName(\"narratives\")\n private Integer narratives;\n\n /**\n * Clips number\n */\n @SerializedName(\"clips\")\n private Integer clips;\n\n /**\n * Clips followers number\n */\n @SerializedName(\"clips_followers\")\n private Integer clipsFollowers;\n\n public Integer getAddresses() {\n return addresses;\n }\n\n public CountersGroup setAddresses(Integer addresses) {\n this.addresses = addresses;\n return this;\n }\n\n public Integer getAlbums() {\n return albums;\n }\n\n public CountersGroup setAlbums(Integer albums) {\n this.albums = albums;\n return this;\n }\n\n public Integer getAudios() {\n return audios;\n }\n\n public CountersGroup setAudios(Integer audios) {\n this.audios = audios;\n return this;\n }\n\n public Integer getAudioPlaylists() {\n return audioPlaylists;\n }\n\n public CountersGroup setAudioPlaylists(Integer audioPlaylists) {\n this.audioPlaylists = audioPlaylists;\n return this;\n }\n\n public Integer getDocs() {\n return docs;\n }\n\n public CountersGroup setDocs(Integer docs) {\n this.docs = docs;\n return this;\n }\n\n public Integer getMarket() {\n return market;\n }\n\n public CountersGroup setMarket(Integer market) {\n this.market = market;\n return this;\n }\n\n public Integer getPhotos() {\n return photos;\n }\n\n public CountersGroup setPhotos(Integer photos) {\n this.photos = photos;\n return this;\n }\n\n public Integer getTopics() {\n return topics;\n }\n\n public CountersGroup setTopics(Integer topics) {\n this.topics = topics;\n return this;\n }\n\n public Integer getVideos() {\n return videos;\n }\n\n public CountersGroup setVideos(Integer videos) {\n this.videos = videos;\n return this;\n }\n\n public Integer getMarketServices() {\n return marketServices;\n }\n\n public CountersGroup setMarketServices(Integer marketServices) {\n this.marketServices = marketServices;\n return this;\n }\n\n public Integer getPodcasts() {\n return podcasts;\n }\n\n public CountersGroup setPodcasts(Integer podcasts) {\n this.podcasts = podcasts;\n return this;\n }\n\n public Integer getArticles() {\n return articles;\n }\n\n public CountersGroup setArticles(Integer articles) {\n this.articles = articles;\n return this;\n }\n\n public Integer getNarratives() {\n return narratives;\n }\n\n public CountersGroup setNarratives(Integer narratives) {\n this.narratives = narratives;\n return this;\n }\n\n public Integer getClips() {\n return clips;\n }\n\n public CountersGroup setClips(Integer clips) {\n this.clips = clips;\n return this;\n }\n\n public Integer getClipsFollowers() {\n return clipsFollowers;\n }\n\n public CountersGroup setClipsFollowers(Integer clipsFollowers) {\n this.clipsFollowers = clipsFollowers;\n return this;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(addresses, albums, narratives, topics, clips, marketServices, videos, photos, market, podcasts, docs, audios, audioPlaylists, articles, clipsFollowers);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n CountersGroup countersGroup = (CountersGroup) o;\n return Objects.equals(addresses, countersGroup.addresses) && Objects.equals(albums, countersGroup.albums) && Objects.equals(narratives, countersGroup.narratives) && Objects.equals(topics, countersGroup.topics) && Objects.equals(clips, countersGroup.clips) && Objects.equals(audioPlaylists, countersGroup.audioPlaylists) && Objects.equals(videos, countersGroup.videos) && Objects.equals(marketServices, countersGroup.marketServices) && Objects.equals(photos, countersGroup.photos) && Objects.equals(market, countersGroup.market) && Objects.equals(podcasts, countersGroup.podcasts) && Objects.equals(docs, counter", "post_mask_code": "sGroup.docs) && Objects.equals(audios, countersGroup.audios) && Objects.equals(clipsFollowers, countersGroup.clipsFollowers) && Objects.equals(articles, countersGroup.articles);\n }\n\n @Override\n public String toString() {\n final Gson gson = new Gson();\n return gson.toJson(this);\n }\n\n public String toPrettyString() {\n final StringBuilder sb = new StringBuilder(\"CountersGroup{\");\n sb.append(\"addresses=\").append(addresses);\n sb.append(\", albums=\").append(albums);\n sb.append(\", narratives=\").append(narratives);\n sb.append(\", topics=\").append(topics);\n sb.append(\", clips=\").append(clips);\n sb.append(\", audioPlaylists=\").append(audioPlaylists);\n sb.append(\", videos=\").append(videos);\n sb.append(\", marketServices=\").append(marketServices);\n sb.append(\", photos=\").append(photos);\n sb.append(\", market=\").append(market);\n sb.append(\", podcasts=\").append(podcasts);\n sb.append(\", docs=\").append(docs);\n sb.append(\", audios=\").append(audios);\n sb.append(\", clipsFollowers=\").append(clipsFollowers);\n sb.append(\", articles=\").append(articles);\n sb.append('}');\n return sb.toString();\n }\n}\n"} {"task_id": "Java_143", "language": "Java", "task_type": "method_signature", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/slice/widget/SliceView.java", "mask_start_position": 9080, "mask_end_position": 9147, "canonical_solution": "@Override\n public boolean onInterceptTouchEvent(MotionEvent ev) ", "pre_mask_code": "package androidx.slice.widget;\n\nimport static android.app.slice.Slice.SUBTYPE_COLOR;\nimport static android.app.slice.SliceItem.FORMAT_INT;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.HapticFeedbackConstants;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport androidx.annotation.ColorInt;\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.RestrictTo;\nimport androidx.lifecycle.Observer;\nimport androidx.slice.Slice;\nimport androidx.slice.SliceItem;\nimport androidx.slice.SliceMetadata;\nimport androidx.slice.core.SliceActionImpl;\nimport androidx.slice.core.SliceHints;\nimport androidx.slice.core.SliceQuery;\nimport androidx.slice.view.R;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.List;\n\n/**\n * A view for displaying a {@link Slice} which is a piece of app content and actions. SliceView is\n * able to present slice content in a templated format outside of the associated app. The way this\n * content is displayed depends on the structure of the slice, the hints associated with the\n * content, and the mode that SliceView is configured for. The modes that SliceView supports are:\n *
    \n *
  • Shortcut: A shortcut is presented as an icon and a text label representing the main\n * content or action associated with the slice.
  • \n *
  • Small: The small format has a restricted height and can present a single\n * {@link SliceItem} or a limited collection of items.
  • \n *
  • Large: The large format displays multiple small templates in a list, if scrolling is\n * not enabled (see {@link #setScrollable(boolean)}) the view will show as many items as it can\n * comfortably fit.
  • \n *
\n *

\n * When constructing a slice, the contents of it can be annotated with hints, these provide the OS\n * with some information on how the content should be displayed. For example, text annotated with\n * {@link android.app.slice.Slice#HINT_TITLE} would be placed in the title position of a template.\n * A slice annotated with {@link android.app.slice.Slice#HINT_LIST} would present the child items\n * of that slice in a list.\n *

\n * Example usage:\n *\n *

\n * SliceView v = new SliceView(getContext());\n * v.setMode(desiredMode);\n * LiveData liveData = SliceLiveData.fromUri(sliceUri);\n * liveData.observe(lifecycleOwner, v);\n * 
\n * @see SliceLiveData\n */\npublic class SliceView extends ViewGroup implements Observer, View.OnClickListener {\n\n private static final String TAG = \"SliceView\";\n\n /**\n * Implement this interface to be notified of interactions with the slice displayed\n * in this view.\n * @see EventInfo\n */\n public interface OnSliceActionListener {\n\n /**\n * Called when an interaction has occurred with an element in this view.\n * @param info the type of event that occurred.\n * @param item the specific item within the {@link Slice} that was interacted with.\n */\n void onSliceAction(@NonNull EventInfo info, @NonNull SliceItem item);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n @IntDef({ MODE_SMALL, MODE_LARGE, MODE_SHORTCUT })\n @Retention(RetentionPolicy.SOURCE)\n public @interface SliceMode {\n }\n\n /**\n * Mode indicating this slice should be presented in small template format.\n */\n public static final int MODE_SMALL = 1;\n\n /**\n * Mode indicating this slice should be presented in large template format.\n */\n public static final int MODE_LARGE = 2;\n\n /**\n * Mode indicating this slice should be presented as an icon. A shortcut requires an intent,\n * icon, and label. This can be indicated by using {@link android.app.slice.Slice#HINT_TITLE}\n * on an action in a slice.\n */\n public static final int MODE_SHORTCUT = 3;\n\n private int mMode = MODE_LARGE;\n\n private Slice mCurrentSlice;\n\n private ListContent mListContent;\n\n private SliceChildView mCurrentView;\n\n private List mActions;\n\n private ActionRow mActionRow;\n\n private boolean mShowActions = false;\n\n private boolean mIsScrollable = true;\n\n private boolean mShowLastUpdated = true;\n\n private int mShortcutSize;\n\n private int mMinLargeHeight;\n\n private int mMaxLargeHeight;\n\n private int mActionRowHeight;\n\n private AttributeSet mAttrs;\n\n private int mDefStyleAttr;\n\n private int mDefStyleRes;\n\n private int mThemeTintColor = -1;\n\n private OnSliceActionListener mSliceObserver;\n\n private int mTouchSlopSquared;\n\n private View.OnLongClickListener mLongClickListener;\n\n private View.OnClickListener mOnClickListener;\n\n private int mDownX;\n\n private int mDownY;\n\n private boolean mPressing;\n\n private boolean mInLongpress;\n\n private Handler mHandler;\n\n int[] mClickInfo;\n\n public SliceView(Context context) {\n this(context, null);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, R.attr.sliceViewStyle);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, R.style.Widget_SliceView);\n }\n\n @RequiresApi(21)\n public SliceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n init(context, attrs, defStyleAttr, defStyleRes);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n mAttrs = attrs;\n mDefStyleAttr = defStyleAttr;\n mDefStyleRes = defStyleRes;\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliceView, defStyleAttr, defStyleRes);\n try {\n mThemeTintColor = a.getColor(R.styleable.SliceView_tintColor, -1);\n } finally {\n a.recycle();\n }\n mShortcutSize = getContext().getResources().getDimensionPixelSize(R.dimen.abc_slice_shortcut_size);\n mMinLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_large_height);\n mMaxLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_max_large_height);\n mActionRowHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_action_row_height);\n mCurrentView = new LargeTemplateView(getContext());\n mCurrentView.setMode(getMode());\n addView(mCurrentView, getChildLp(mCurrentView));\n // TODO: action row background should support light / dark / maybe presenter customization\n mActionRow = new ActionRow(getContext(), true);\n mActionRow.setBackground(new ColorDrawable(0xffeeeeee));\n addView(mActionRow, getChildLp(mActionRow));\n final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();\n mTouchSlopSquared = slop * slop;\n mHandler = new Handler();\n super.setOnClickListener(this);\n }\n\n /**\n * Indicates whether this view reacts to click events or not.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isSliceViewClickable() {\n return mOnClickListener != null || (mListContent != null && mListContent.getPrimaryAction() != null);\n }\n\n /**\n * Sets the event info for logging a click.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setClickInfo(int[] info) {\n mClickInfo = info;\n }\n\n @Override\n public void onClick(View v) {\n if (mListContent != null && mListContent.getPrimaryAction() != null) {\n try {\n SliceActionImpl sa = new SliceActionImpl(mListContent.getPrimaryAction());\n sa.getAction().send();\n if (mSliceObserver != null && mClickInfo != null && mClickInfo.length > 1) {\n EventInfo eventInfo = new EventInfo(getMode(), EventInfo.ACTION_TYPE_CONTENT, mClickInfo[0], mClickInfo[1]);\n mSliceObserver.onSliceAction(eventInfo, mListContent.getPrimaryAction());\n }\n } catch (PendingIntent.CanceledException e) {\n Log.e(TAG, \"PendingIntent for slice cannot be sent\", e);\n }\n } else if (mOnClickListener != null) {\n mOnClickListener.onClick(this);\n }\n }\n\n @Override\n public void setOnClickListener(View.OnClickListener listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public void setOnLongClickListener(View.OnLongClickListener listener) {\n super.setOnLongClickListener(listener);\n mLongClickListener = listener;\n }\n\n ", "post_mask_code": "{\n boolean ret = super.onInterceptTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n boolean ret = super.onTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n private boolean handleTouchForLongpress(MotionEvent ev) {\n int action = ev.getActionMasked();\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n mHandler.removeCallbacks(mLongpressCheck);\n mDownX = (int) ev.getRawX();\n mDownY = (int) ev.getRawY();\n mPressing = true;\n mInLongpress = false;\n mHandler.postDelayed(mLongpressCheck, ViewConfiguration.getLongPressTimeout());\n break;\n case MotionEvent.ACTION_MOVE:\n final int deltaX = (int) ev.getRawX() - mDownX;\n final int deltaY = (int) ev.getRawY() - mDownY;\n int distance = (deltaX * deltaX) + (deltaY * deltaY);\n if (distance > mTouchSlopSquared) {\n mPressing = false;\n mHandler.removeCallbacks(mLongpressCheck);\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n mPressing = false;\n mInLongpress = false;\n mHandler.removeCallbacks(mLongpressCheck);\n break;\n }\n return mInLongpress;\n }\n\n private int getHeightForMode() {\n int mode = getMode();\n if (mode == MODE_SHORTCUT) {\n return mListContent != null && mListContent.isValid() ? mShortcutSize : 0;\n }\n return mode == MODE_LARGE ? mCurrentView.getActualHeight() : mCurrentView.getSmallHeight();\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int width = MeasureSpec.getSize(widthMeasureSpec);\n int childWidth = MeasureSpec.getSize(widthMeasureSpec);\n if (MODE_SHORTCUT == mMode) {\n // TODO: consider scaling the shortcut to fit if too small\n childWidth = mShortcutSize;\n width = mShortcutSize + getPaddingLeft() + getPaddingRight();\n }\n final int actionHeight = mActionRow.getVisibility() != View.GONE ? mActionRowHeight : 0;\n final int sliceHeight = getHeightForMode();\n final int heightAvailable = MeasureSpec.getSize(heightMeasureSpec);\n final int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n // Remove the padding from our available height\n int height = heightAvailable - getPaddingTop() - getPaddingBottom();\n if (heightAvailable >= sliceHeight + actionHeight || heightMode == MeasureSpec.UNSPECIFIED) {\n // Available space is larger than the slice or we be what we want\n if (heightMode != MeasureSpec.EXACTLY) {\n if (!mIsScrollable) {\n height = Math.min(mMaxLargeHeight, sliceHeight);\n } else {\n // If we want to be bigger than max, then we can be a good scrollable at min\n // large height, if it's not larger lets just use its desired height\n height = sliceHeight > mMaxLargeHeight ? mMinLargeHeight : sliceHeight;\n }\n }\n } else {\n // Not enough space available for slice in current mode\n if (getMode() == MODE_LARGE && heightAvailable >= mMinLargeHeight + actionHeight) {\n // It's just a slice with scrolling content; cap it to height available.\n height = Math.min(mMinLargeHeight, heightAvailable);\n } else if (getMode() == MODE_SHORTCUT) {\n // TODO: consider scaling the shortcut to fit if too small\n height = mShortcutSize;\n }\n }\n int childHeight = height + getPaddingTop() + getPaddingBottom();\n int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);\n int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);\n measureChild(mCurrentView, childWidthMeasureSpec, childHeightMeasureSpec);\n int actionPaddedHeight = actionHeight + getPaddingTop() + getPaddingBottom();\n int actionHeightSpec = MeasureSpec.makeMeasureSpec(actionPaddedHeight, MeasureSpec.EXACTLY);\n measureChild(mActionRow, childWidthMeasureSpec, actionHeightSpec);\n // Total height should include action row and our padding\n height += actionHeight + getPaddingTop() + getPaddingBottom();\n setMeasuredDimension(width, height);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n View v = mCurrentView;\n final int left = getPaddingLeft();\n final int top = getPaddingTop();\n v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight());\n if (mActionRow.getVisibility() != View.GONE) {\n mActionRow.layout(left, top + v.getMeasuredHeight(), left + mActionRow.getMeasuredWidth(), top + v.getMeasuredHeight() + mActionRow.getMeasuredHeight());\n }\n }\n\n @Override\n public void onChanged(@Nullable Slice slice) {\n setSlice(slice);\n }\n\n /**\n * Populates this view to the provided {@link Slice}.\n *\n * This will not update automatically if the slice content changes, for live\n * content see {@link SliceLiveData}.\n */\n public void setSlice(@Nullable Slice slice) {\n if (slice != null) {\n if (mCurrentSlice == null || !mCurrentSlice.getUri().equals(slice.getUri())) {\n mCurrentView.resetView();\n }\n } else {\n // No slice, no actions\n mActions = null;\n }\n mActions = SliceMetadata.getSliceActions(slice);\n mCurrentSlice = slice;\n reinflate();\n }\n\n /**\n * @return the slice being used to populate this view.\n */\n @Nullable\n public Slice getSlice() {\n return mCurrentSlice;\n }\n\n /**\n * Returns the slice actions presented in this view.\n *

\n * Note that these may be different from {@link SliceMetadata#getSliceActions()} if the actions\n * set on the view have been adjusted using {@link #setSliceActions(List)}.\n */\n @Nullable\n public List getSliceActions() {\n return mActions;\n }\n\n /**\n * Sets the slice actions to display for the slice contained in this view. Normally SliceView\n * will automatically show actions, however, it is possible to reorder or omit actions on the\n * view using this method. This is generally discouraged.\n *

\n * It is required that the slice be set on this view before actions can be set, otherwise\n * this will throw {@link IllegalStateException}. If any of the actions supplied are not\n * available for the slice set on this view (i.e. the action is not returned by\n * {@link SliceMetadata#getSliceActions()} this will throw {@link IllegalArgumentException}.\n */\n public void setSliceActions(@Nullable List newActions) {\n // Check that these actions are part of available set\n if (mCurrentSlice == null) {\n throw new IllegalStateException(\"Trying to set actions on a view without a slice\");\n }\n List availableActions = SliceMetadata.getSliceActions(mCurrentSlice);\n if (availableActions != null && newActions != null) {\n for (int i = 0; i < newActions.size(); i++) {\n if (!availableActions.contains(newActions.get(i))) {\n throw new IllegalArgumentException(\"Trying to set an action that isn't available: \" + newActions.get(i));\n }\n }\n }\n mActions = newActions;\n updateActions();\n }\n\n /**\n * Set the mode this view should present in.\n */\n public void setMode(@SliceMode int mode) {\n setMode(mode, false);\n }\n\n /**\n * Set whether this view should allow scrollable content when presenting in {@link #MODE_LARGE}.\n */\n public void setScrollable(boolean isScrollable) {\n mIsScrollable = isScrollable;\n reinflate();\n }\n\n /**\n * Sets the listener to notify when an interaction events occur on the view.\n * @see EventInfo\n */\n public void setOnSliceActionListener(@Nullable OnSliceActionListener observer) {\n mSliceObserver = observer;\n mCurrentView.setSliceActionListener(mSliceObserver);\n }\n\n /**\n * @deprecated TO BE REMOVED; use {@link #setAccentColor(int)} instead.\n */\n @Deprecated\n public void setTint(int tintColor) {\n setAccentColor(tintColor);\n }\n\n /**\n * Contents of a slice such as icons, text, and controls (e.g. toggle) can be tinted. Normally\n * a color for tinting will be provided by the slice. Using this method will override\n * the slice-provided color information and instead tint elements with the color set here.\n *\n * @param accentColor the color to use for tinting contents of this view.\n */\n public void setAccentColor(@ColorInt int accentColor) {\n mThemeTintColor = accentColor;\n mCurrentView.setTint(accentColor);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setMode(@SliceMode int mode, boolean animate) {\n if (animate) {\n Log.e(TAG, \"Animation not supported yet\");\n }\n if (mMode == mode) {\n return;\n }\n mMode = mode;\n reinflate();\n }\n\n /**\n * @return the mode this view is presenting in.\n */\n @SliceMode\n public int getMode() {\n return mMode;\n }\n\n /**\n * @hide\n *\n * Whether this view should show a row of actions with it.\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setShowActionRow(boolean show) {\n mShowActions = show;\n updateActions();\n }\n\n /**\n * @return whether this view is showing a row of actions.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isShowingActionRow() {\n return mShowActions;\n }\n\n private void reinflate() {\n if (mCurrentSlice == null) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n mListContent = new ListContent(getContext(), mCurrentSlice, mAttrs, mDefStyleAttr, mDefStyleRes);\n if (!mListContent.isValid()) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n // TODO: Smarter mapping here from one state to the next.\n int mode = getMode();\n boolean isCurrentViewShortcut = mCurrentView instanceof ShortcutView;\n if (mode == MODE_SHORTCUT && !isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new ShortcutView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n } else if (mode != MODE_SHORTCUT && isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new LargeTemplateView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n }\n mCurrentView.setMode(mode);\n mCurrentView.setSliceActionListener(mSliceObserver);\n if (mCurrentView instanceof LargeTemplateView) {\n ((LargeTemplateView) mCurrentView).setScrollable(mIsScrollable);\n }\n mCurrentView.setStyle(mAttrs, mDefStyleAttr, mDefStyleRes);\n mCurrentView.setTint(getTintColor());\n // Check if the slice content is expired and show when it was last updated\n SliceMetadata sliceMetadata = SliceMetadata.from(getContext(), mCurrentSlice);\n long lastUpdated = sliceMetadata.getLastUpdatedTime();\n long expiry = sliceMetadata.getExpiry();\n long now = System.currentTimeMillis();\n mCurrentView.setLastUpdated(lastUpdated);\n boolean expired = expiry != 0 && expiry != SliceHints.INFINITY && now > expiry;\n mCurrentView.setShowLastUpdated(mShowLastUpdated && expired);\n // Set the slice\n mCurrentView.setSliceContent(mListContent);\n updateActions();\n }\n\n private void updateActions() {\n if (mActions == null || mActions.isEmpty()) {\n // No actions, hide the row, clear out the view\n mActionRow.setVisibility(View.GONE);\n mCurrentView.setSliceActions(null);\n return;\n }\n // TODO: take priority attached to actions into account\n if (mShowActions && mMode != MODE_SHORTCUT && mActions.size() >= 2) {\n // Show in action row if available\n mActionRow.setActions(mActions, getTintColor());\n mActionRow.setVisibility(View.VISIBLE);\n // Hide them on the template\n mCurrentView.setSliceActions(null);\n } else if (mActions.size() > 0) {\n // Otherwise set them on the template\n mCurrentView.setSliceActions(mActions);\n mActionRow.setVisibility(View.GONE);\n }\n }\n\n private int getTintColor() {\n if (mThemeTintColor != -1) {\n // Theme has specified a color, use that\n return mThemeTintColor;\n } else {\n final SliceItem colorItem = SliceQuery.findSubtype(mCurrentSlice, FORMAT_INT, SUBTYPE_COLOR);\n return colorItem != null ? colorItem.getInt() : SliceViewUtil.getColorAccent(getContext());\n }\n }\n\n private LayoutParams getChildLp(View child) {\n if (child instanceof ShortcutView) {\n return new LayoutParams(mShortcutSize, mShortcutSize);\n } else {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n }\n\n /**\n * @return String representation of the provided mode.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public static String modeToString(@SliceMode int mode) {\n switch(mode) {\n case MODE_SHORTCUT:\n return \"MODE SHORTCUT\";\n case MODE_SMALL:\n return \"MODE SMALL\";\n case MODE_LARGE:\n return \"MODE LARGE\";\n default:\n return \"unknown mode: \" + mode;\n }\n }\n\n Runnable mLongpressCheck = new Runnable() {\n\n @Override\n public void run() {\n if (mPressing && mLongClickListener != null) {\n mInLongpress = true;\n mLongClickListener.onLongClick(SliceView.this);\n performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);\n }\n }\n };\n}\n"} {"task_id": "Java_144", "language": "Java", "task_type": "method_body", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/slice/widget/SliceView.java", "mask_start_position": 17798, "mask_end_position": 17901, "canonical_solution": "{\n mSliceObserver = observer;\n mCurrentView.setSliceActionListener(mSliceObserver);\n }", "pre_mask_code": "package androidx.slice.widget;\n\nimport static android.app.slice.Slice.SUBTYPE_COLOR;\nimport static android.app.slice.SliceItem.FORMAT_INT;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.HapticFeedbackConstants;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport androidx.annotation.ColorInt;\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.RestrictTo;\nimport androidx.lifecycle.Observer;\nimport androidx.slice.Slice;\nimport androidx.slice.SliceItem;\nimport androidx.slice.SliceMetadata;\nimport androidx.slice.core.SliceActionImpl;\nimport androidx.slice.core.SliceHints;\nimport androidx.slice.core.SliceQuery;\nimport androidx.slice.view.R;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.List;\n\n/**\n * A view for displaying a {@link Slice} which is a piece of app content and actions. SliceView is\n * able to present slice content in a templated format outside of the associated app. The way this\n * content is displayed depends on the structure of the slice, the hints associated with the\n * content, and the mode that SliceView is configured for. The modes that SliceView supports are:\n *

    \n *
  • Shortcut: A shortcut is presented as an icon and a text label representing the main\n * content or action associated with the slice.
  • \n *
  • Small: The small format has a restricted height and can present a single\n * {@link SliceItem} or a limited collection of items.
  • \n *
  • Large: The large format displays multiple small templates in a list, if scrolling is\n * not enabled (see {@link #setScrollable(boolean)}) the view will show as many items as it can\n * comfortably fit.
  • \n *
\n *

\n * When constructing a slice, the contents of it can be annotated with hints, these provide the OS\n * with some information on how the content should be displayed. For example, text annotated with\n * {@link android.app.slice.Slice#HINT_TITLE} would be placed in the title position of a template.\n * A slice annotated with {@link android.app.slice.Slice#HINT_LIST} would present the child items\n * of that slice in a list.\n *

\n * Example usage:\n *\n *

\n * SliceView v = new SliceView(getContext());\n * v.setMode(desiredMode);\n * LiveData liveData = SliceLiveData.fromUri(sliceUri);\n * liveData.observe(lifecycleOwner, v);\n * 
\n * @see SliceLiveData\n */\npublic class SliceView extends ViewGroup implements Observer, View.OnClickListener {\n\n private static final String TAG = \"SliceView\";\n\n /**\n * Implement this interface to be notified of interactions with the slice displayed\n * in this view.\n * @see EventInfo\n */\n public interface OnSliceActionListener {\n\n /**\n * Called when an interaction has occurred with an element in this view.\n * @param info the type of event that occurred.\n * @param item the specific item within the {@link Slice} that was interacted with.\n */\n void onSliceAction(@NonNull EventInfo info, @NonNull SliceItem item);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n @IntDef({ MODE_SMALL, MODE_LARGE, MODE_SHORTCUT })\n @Retention(RetentionPolicy.SOURCE)\n public @interface SliceMode {\n }\n\n /**\n * Mode indicating this slice should be presented in small template format.\n */\n public static final int MODE_SMALL = 1;\n\n /**\n * Mode indicating this slice should be presented in large template format.\n */\n public static final int MODE_LARGE = 2;\n\n /**\n * Mode indicating this slice should be presented as an icon. A shortcut requires an intent,\n * icon, and label. This can be indicated by using {@link android.app.slice.Slice#HINT_TITLE}\n * on an action in a slice.\n */\n public static final int MODE_SHORTCUT = 3;\n\n private int mMode = MODE_LARGE;\n\n private Slice mCurrentSlice;\n\n private ListContent mListContent;\n\n private SliceChildView mCurrentView;\n\n private List mActions;\n\n private ActionRow mActionRow;\n\n private boolean mShowActions = false;\n\n private boolean mIsScrollable = true;\n\n private boolean mShowLastUpdated = true;\n\n private int mShortcutSize;\n\n private int mMinLargeHeight;\n\n private int mMaxLargeHeight;\n\n private int mActionRowHeight;\n\n private AttributeSet mAttrs;\n\n private int mDefStyleAttr;\n\n private int mDefStyleRes;\n\n private int mThemeTintColor = -1;\n\n private OnSliceActionListener mSliceObserver;\n\n private int mTouchSlopSquared;\n\n private View.OnLongClickListener mLongClickListener;\n\n private View.OnClickListener mOnClickListener;\n\n private int mDownX;\n\n private int mDownY;\n\n private boolean mPressing;\n\n private boolean mInLongpress;\n\n private Handler mHandler;\n\n int[] mClickInfo;\n\n public SliceView(Context context) {\n this(context, null);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, R.attr.sliceViewStyle);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, R.style.Widget_SliceView);\n }\n\n @RequiresApi(21)\n public SliceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n init(context, attrs, defStyleAttr, defStyleRes);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n mAttrs = attrs;\n mDefStyleAttr = defStyleAttr;\n mDefStyleRes = defStyleRes;\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliceView, defStyleAttr, defStyleRes);\n try {\n mThemeTintColor = a.getColor(R.styleable.SliceView_tintColor, -1);\n } finally {\n a.recycle();\n }\n mShortcutSize = getContext().getResources().getDimensionPixelSize(R.dimen.abc_slice_shortcut_size);\n mMinLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_large_height);\n mMaxLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_max_large_height);\n mActionRowHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_action_row_height);\n mCurrentView = new LargeTemplateView(getContext());\n mCurrentView.setMode(getMode());\n addView(mCurrentView, getChildLp(mCurrentView));\n // TODO: action row background should support light / dark / maybe presenter customization\n mActionRow = new ActionRow(getContext(), true);\n mActionRow.setBackground(new ColorDrawable(0xffeeeeee));\n addView(mActionRow, getChildLp(mActionRow));\n final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();\n mTouchSlopSquared = slop * slop;\n mHandler = new Handler();\n super.setOnClickListener(this);\n }\n\n /**\n * Indicates whether this view reacts to click events or not.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isSliceViewClickable() {\n return mOnClickListener != null || (mListContent != null && mListContent.getPrimaryAction() != null);\n }\n\n /**\n * Sets the event info for logging a click.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setClickInfo(int[] info) {\n mClickInfo = info;\n }\n\n @Override\n public void onClick(View v) {\n if (mListContent != null && mListContent.getPrimaryAction() != null) {\n try {\n SliceActionImpl sa = new SliceActionImpl(mListContent.getPrimaryAction());\n sa.getAction().send();\n if (mSliceObserver != null && mClickInfo != null && mClickInfo.length > 1) {\n EventInfo eventInfo = new EventInfo(getMode(), EventInfo.ACTION_TYPE_CONTENT, mClickInfo[0], mClickInfo[1]);\n mSliceObserver.onSliceAction(eventInfo, mListContent.getPrimaryAction());\n }\n } catch (PendingIntent.CanceledException e) {\n Log.e(TAG, \"PendingIntent for slice cannot be sent\", e);\n }\n } else if (mOnClickListener != null) {\n mOnClickListener.onClick(this);\n }\n }\n\n @Override\n public void setOnClickListener(View.OnClickListener listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public void setOnLongClickListener(View.OnLongClickListener listener) {\n super.setOnLongClickListener(listener);\n mLongClickListener = listener;\n }\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n boolean ret = super.onInterceptTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n boolean ret = super.onTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n private boolean handleTouchForLongpress(MotionEvent ev) {\n int action = ev.getActionMasked();\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n mHandler.removeCallbacks(mLongpressCheck);\n mDownX = (int) ev.getRawX();\n mDownY = (int) ev.getRawY();\n mPressing = true;\n mInLongpress = false;\n mHandler.postDelayed(mLongpressCheck, ViewConfiguration.getLongPressTimeout());\n break;\n case MotionEvent.ACTION_MOVE:\n final int deltaX = (int) ev.getRawX() - mDownX;\n final int deltaY = (int) ev.getRawY() - mDownY;\n int distance = (deltaX * deltaX) + (deltaY * deltaY);\n if (distance > mTouchSlopSquared) {\n mPressing = false;\n mHandler.removeCallbacks(mLongpressCheck);\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n mPressing = false;\n mInLongpress = false;\n mHandler.removeCallbacks(mLongpressCheck);\n break;\n }\n return mInLongpress;\n }\n\n private int getHeightForMode() {\n int mode = getMode();\n if (mode == MODE_SHORTCUT) {\n return mListContent != null && mListContent.isValid() ? mShortcutSize : 0;\n }\n return mode == MODE_LARGE ? mCurrentView.getActualHeight() : mCurrentView.getSmallHeight();\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int width = MeasureSpec.getSize(widthMeasureSpec);\n int childWidth = MeasureSpec.getSize(widthMeasureSpec);\n if (MODE_SHORTCUT == mMode) {\n // TODO: consider scaling the shortcut to fit if too small\n childWidth = mShortcutSize;\n width = mShortcutSize + getPaddingLeft() + getPaddingRight();\n }\n final int actionHeight = mActionRow.getVisibility() != View.GONE ? mActionRowHeight : 0;\n final int sliceHeight = getHeightForMode();\n final int heightAvailable = MeasureSpec.getSize(heightMeasureSpec);\n final int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n // Remove the padding from our available height\n int height = heightAvailable - getPaddingTop() - getPaddingBottom();\n if (heightAvailable >= sliceHeight + actionHeight || heightMode == MeasureSpec.UNSPECIFIED) {\n // Available space is larger than the slice or we be what we want\n if (heightMode != MeasureSpec.EXACTLY) {\n if (!mIsScrollable) {\n height = Math.min(mMaxLargeHeight, sliceHeight);\n } else {\n // If we want to be bigger than max, then we can be a good scrollable at min\n // large height, if it's not larger lets just use its desired height\n height = sliceHeight > mMaxLargeHeight ? mMinLargeHeight : sliceHeight;\n }\n }\n } else {\n // Not enough space available for slice in current mode\n if (getMode() == MODE_LARGE && heightAvailable >= mMinLargeHeight + actionHeight) {\n // It's just a slice with scrolling content; cap it to height available.\n height = Math.min(mMinLargeHeight, heightAvailable);\n } else if (getMode() == MODE_SHORTCUT) {\n // TODO: consider scaling the shortcut to fit if too small\n height = mShortcutSize;\n }\n }\n int childHeight = height + getPaddingTop() + getPaddingBottom();\n int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);\n int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);\n measureChild(mCurrentView, childWidthMeasureSpec, childHeightMeasureSpec);\n int actionPaddedHeight = actionHeight + getPaddingTop() + getPaddingBottom();\n int actionHeightSpec = MeasureSpec.makeMeasureSpec(actionPaddedHeight, MeasureSpec.EXACTLY);\n measureChild(mActionRow, childWidthMeasureSpec, actionHeightSpec);\n // Total height should include action row and our padding\n height += actionHeight + getPaddingTop() + getPaddingBottom();\n setMeasuredDimension(width, height);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n View v = mCurrentView;\n final int left = getPaddingLeft();\n final int top = getPaddingTop();\n v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight());\n if (mActionRow.getVisibility() != View.GONE) {\n mActionRow.layout(left, top + v.getMeasuredHeight(), left + mActionRow.getMeasuredWidth(), top + v.getMeasuredHeight() + mActionRow.getMeasuredHeight());\n }\n }\n\n @Override\n public void onChanged(@Nullable Slice slice) {\n setSlice(slice);\n }\n\n /**\n * Populates this view to the provided {@link Slice}.\n *\n * This will not update automatically if the slice content changes, for live\n * content see {@link SliceLiveData}.\n */\n public void setSlice(@Nullable Slice slice) {\n if (slice != null) {\n if (mCurrentSlice == null || !mCurrentSlice.getUri().equals(slice.getUri())) {\n mCurrentView.resetView();\n }\n } else {\n // No slice, no actions\n mActions = null;\n }\n mActions = SliceMetadata.getSliceActions(slice);\n mCurrentSlice = slice;\n reinflate();\n }\n\n /**\n * @return the slice being used to populate this view.\n */\n @Nullable\n public Slice getSlice() {\n return mCurrentSlice;\n }\n\n /**\n * Returns the slice actions presented in this view.\n *

\n * Note that these may be different from {@link SliceMetadata#getSliceActions()} if the actions\n * set on the view have been adjusted using {@link #setSliceActions(List)}.\n */\n @Nullable\n public List getSliceActions() {\n return mActions;\n }\n\n /**\n * Sets the slice actions to display for the slice contained in this view. Normally SliceView\n * will automatically show actions, however, it is possible to reorder or omit actions on the\n * view using this method. This is generally discouraged.\n *

\n * It is required that the slice be set on this view before actions can be set, otherwise\n * this will throw {@link IllegalStateException}. If any of the actions supplied are not\n * available for the slice set on this view (i.e. the action is not returned by\n * {@link SliceMetadata#getSliceActions()} this will throw {@link IllegalArgumentException}.\n */\n public void setSliceActions(@Nullable List newActions) {\n // Check that these actions are part of available set\n if (mCurrentSlice == null) {\n throw new IllegalStateException(\"Trying to set actions on a view without a slice\");\n }\n List availableActions = SliceMetadata.getSliceActions(mCurrentSlice);\n if (availableActions != null && newActions != null) {\n for (int i = 0; i < newActions.size(); i++) {\n if (!availableActions.contains(newActions.get(i))) {\n throw new IllegalArgumentException(\"Trying to set an action that isn't available: \" + newActions.get(i));\n }\n }\n }\n mActions = newActions;\n updateActions();\n }\n\n /**\n * Set the mode this view should present in.\n */\n public void setMode(@SliceMode int mode) {\n setMode(mode, false);\n }\n\n /**\n * Set whether this view should allow scrollable content when presenting in {@link #MODE_LARGE}.\n */\n public void setScrollable(boolean isScrollable) {\n mIsScrollable = isScrollable;\n reinflate();\n }\n\n /**\n * Sets the listener to notify when an interaction events occur on the view.\n * @see EventInfo\n */\n public void setOnSliceActionListener(@Nullable OnSliceActionListener observer) ", "post_mask_code": "\n\n /**\n * @deprecated TO BE REMOVED; use {@link #setAccentColor(int)} instead.\n */\n @Deprecated\n public void setTint(int tintColor) {\n setAccentColor(tintColor);\n }\n\n /**\n * Contents of a slice such as icons, text, and controls (e.g. toggle) can be tinted. Normally\n * a color for tinting will be provided by the slice. Using this method will override\n * the slice-provided color information and instead tint elements with the color set here.\n *\n * @param accentColor the color to use for tinting contents of this view.\n */\n public void setAccentColor(@ColorInt int accentColor) {\n mThemeTintColor = accentColor;\n mCurrentView.setTint(accentColor);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setMode(@SliceMode int mode, boolean animate) {\n if (animate) {\n Log.e(TAG, \"Animation not supported yet\");\n }\n if (mMode == mode) {\n return;\n }\n mMode = mode;\n reinflate();\n }\n\n /**\n * @return the mode this view is presenting in.\n */\n @SliceMode\n public int getMode() {\n return mMode;\n }\n\n /**\n * @hide\n *\n * Whether this view should show a row of actions with it.\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setShowActionRow(boolean show) {\n mShowActions = show;\n updateActions();\n }\n\n /**\n * @return whether this view is showing a row of actions.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isShowingActionRow() {\n return mShowActions;\n }\n\n private void reinflate() {\n if (mCurrentSlice == null) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n mListContent = new ListContent(getContext(), mCurrentSlice, mAttrs, mDefStyleAttr, mDefStyleRes);\n if (!mListContent.isValid()) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n // TODO: Smarter mapping here from one state to the next.\n int mode = getMode();\n boolean isCurrentViewShortcut = mCurrentView instanceof ShortcutView;\n if (mode == MODE_SHORTCUT && !isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new ShortcutView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n } else if (mode != MODE_SHORTCUT && isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new LargeTemplateView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n }\n mCurrentView.setMode(mode);\n mCurrentView.setSliceActionListener(mSliceObserver);\n if (mCurrentView instanceof LargeTemplateView) {\n ((LargeTemplateView) mCurrentView).setScrollable(mIsScrollable);\n }\n mCurrentView.setStyle(mAttrs, mDefStyleAttr, mDefStyleRes);\n mCurrentView.setTint(getTintColor());\n // Check if the slice content is expired and show when it was last updated\n SliceMetadata sliceMetadata = SliceMetadata.from(getContext(), mCurrentSlice);\n long lastUpdated = sliceMetadata.getLastUpdatedTime();\n long expiry = sliceMetadata.getExpiry();\n long now = System.currentTimeMillis();\n mCurrentView.setLastUpdated(lastUpdated);\n boolean expired = expiry != 0 && expiry != SliceHints.INFINITY && now > expiry;\n mCurrentView.setShowLastUpdated(mShowLastUpdated && expired);\n // Set the slice\n mCurrentView.setSliceContent(mListContent);\n updateActions();\n }\n\n private void updateActions() {\n if (mActions == null || mActions.isEmpty()) {\n // No actions, hide the row, clear out the view\n mActionRow.setVisibility(View.GONE);\n mCurrentView.setSliceActions(null);\n return;\n }\n // TODO: take priority attached to actions into account\n if (mShowActions && mMode != MODE_SHORTCUT && mActions.size() >= 2) {\n // Show in action row if available\n mActionRow.setActions(mActions, getTintColor());\n mActionRow.setVisibility(View.VISIBLE);\n // Hide them on the template\n mCurrentView.setSliceActions(null);\n } else if (mActions.size() > 0) {\n // Otherwise set them on the template\n mCurrentView.setSliceActions(mActions);\n mActionRow.setVisibility(View.GONE);\n }\n }\n\n private int getTintColor() {\n if (mThemeTintColor != -1) {\n // Theme has specified a color, use that\n return mThemeTintColor;\n } else {\n final SliceItem colorItem = SliceQuery.findSubtype(mCurrentSlice, FORMAT_INT, SUBTYPE_COLOR);\n return colorItem != null ? colorItem.getInt() : SliceViewUtil.getColorAccent(getContext());\n }\n }\n\n private LayoutParams getChildLp(View child) {\n if (child instanceof ShortcutView) {\n return new LayoutParams(mShortcutSize, mShortcutSize);\n } else {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n }\n\n /**\n * @return String representation of the provided mode.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public static String modeToString(@SliceMode int mode) {\n switch(mode) {\n case MODE_SHORTCUT:\n return \"MODE SHORTCUT\";\n case MODE_SMALL:\n return \"MODE SMALL\";\n case MODE_LARGE:\n return \"MODE LARGE\";\n default:\n return \"unknown mode: \" + mode;\n }\n }\n\n Runnable mLongpressCheck = new Runnable() {\n\n @Override\n public void run() {\n if (mPressing && mLongClickListener != null) {\n mInLongpress = true;\n mLongClickListener.onLongClick(SliceView.this);\n performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);\n }\n }\n };\n}\n"} {"task_id": "Java_145", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/slice/widget/SliceView.java", "mask_start_position": 23347, "mask_end_position": 23347, "canonical_solution": "", "pre_mask_code": "package androidx.slice.widget;\n\nimport static android.app.slice.Slice.SUBTYPE_COLOR;\nimport static android.app.slice.SliceItem.FORMAT_INT;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.HapticFeedbackConstants;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport androidx.annotation.ColorInt;\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.RestrictTo;\nimport androidx.lifecycle.Observer;\nimport androidx.slice.Slice;\nimport androidx.slice.SliceItem;\nimport androidx.slice.SliceMetadata;\nimport androidx.slice.core.SliceActionImpl;\nimport androidx.slice.core.SliceHints;\nimport androidx.slice.core.SliceQuery;\nimport androidx.slice.view.R;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.List;\n\n/**\n * A view for displaying a {@link Slice} which is a piece of app content and actions. SliceView is\n * able to present slice content in a templated format outside of the associated app. The way this\n * content is displayed depends on the structure of the slice, the hints associated with the\n * content, and the mode that SliceView is configured for. The modes that SliceView supports are:\n *

    \n *
  • Shortcut: A shortcut is presented as an icon and a text label representing the main\n * content or action associated with the slice.
  • \n *
  • Small: The small format has a restricted height and can present a single\n * {@link SliceItem} or a limited collection of items.
  • \n *
  • Large: The large format displays multiple small templates in a list, if scrolling is\n * not enabled (see {@link #setScrollable(boolean)}) the view will show as many items as it can\n * comfortably fit.
  • \n *
\n *

\n * When constructing a slice, the contents of it can be annotated with hints, these provide the OS\n * with some information on how the content should be displayed. For example, text annotated with\n * {@link android.app.slice.Slice#HINT_TITLE} would be placed in the title position of a template.\n * A slice annotated with {@link android.app.slice.Slice#HINT_LIST} would present the child items\n * of that slice in a list.\n *

\n * Example usage:\n *\n *

\n * SliceView v = new SliceView(getContext());\n * v.setMode(desiredMode);\n * LiveData liveData = SliceLiveData.fromUri(sliceUri);\n * liveData.observe(lifecycleOwner, v);\n * 
\n * @see SliceLiveData\n */\npublic class SliceView extends ViewGroup implements Observer, View.OnClickListener {\n\n private static final String TAG = \"SliceView\";\n\n /**\n * Implement this interface to be notified of interactions with the slice displayed\n * in this view.\n * @see EventInfo\n */\n public interface OnSliceActionListener {\n\n /**\n * Called when an interaction has occurred with an element in this view.\n * @param info the type of event that occurred.\n * @param item the specific item within the {@link Slice} that was interacted with.\n */\n void onSliceAction(@NonNull EventInfo info, @NonNull SliceItem item);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n @IntDef({ MODE_SMALL, MODE_LARGE, MODE_SHORTCUT })\n @Retention(RetentionPolicy.SOURCE)\n public @interface SliceMode {\n }\n\n /**\n * Mode indicating this slice should be presented in small template format.\n */\n public static final int MODE_SMALL = 1;\n\n /**\n * Mode indicating this slice should be presented in large template format.\n */\n public static final int MODE_LARGE = 2;\n\n /**\n * Mode indicating this slice should be presented as an icon. A shortcut requires an intent,\n * icon, and label. This can be indicated by using {@link android.app.slice.Slice#HINT_TITLE}\n * on an action in a slice.\n */\n public static final int MODE_SHORTCUT = 3;\n\n private int mMode = MODE_LARGE;\n\n private Slice mCurrentSlice;\n\n private ListContent mListContent;\n\n private SliceChildView mCurrentView;\n\n private List mActions;\n\n private ActionRow mActionRow;\n\n private boolean mShowActions = false;\n\n private boolean mIsScrollable = true;\n\n private boolean mShowLastUpdated = true;\n\n private int mShortcutSize;\n\n private int mMinLargeHeight;\n\n private int mMaxLargeHeight;\n\n private int mActionRowHeight;\n\n private AttributeSet mAttrs;\n\n private int mDefStyleAttr;\n\n private int mDefStyleRes;\n\n private int mThemeTintColor = -1;\n\n private OnSliceActionListener mSliceObserver;\n\n private int mTouchSlopSquared;\n\n private View.OnLongClickListener mLongClickListener;\n\n private View.OnClickListener mOnClickListener;\n\n private int mDownX;\n\n private int mDownY;\n\n private boolean mPressing;\n\n private boolean mInLongpress;\n\n private Handler mHandler;\n\n int[] mClickInfo;\n\n public SliceView(Context context) {\n this(context, null);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, R.attr.sliceViewStyle);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, R.style.Widget_SliceView);\n }\n\n @RequiresApi(21)\n public SliceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n init(context, attrs, defStyleAttr, defStyleRes);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n mAttrs = attrs;\n mDefStyleAttr = defStyleAttr;\n mDefStyleRes = defStyleRes;\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliceView, defStyleAttr, defStyleRes);\n try {\n mThemeTintColor = a.getColor(R.styleable.SliceView_tintColor, -1);\n } finally {\n a.recycle();\n }\n mShortcutSize = getContext().getResources().getDimensionPixelSize(R.dimen.abc_slice_shortcut_size);\n mMinLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_large_height);\n mMaxLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_max_large_height);\n mActionRowHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_action_row_height);\n mCurrentView = new LargeTemplateView(getContext());\n mCurrentView.setMode(getMode());\n addView(mCurrentView, getChildLp(mCurrentView));\n // TODO: action row background should support light / dark / maybe presenter customization\n mActionRow = new ActionRow(getContext(), true);\n mActionRow.setBackground(new ColorDrawable(0xffeeeeee));\n addView(mActionRow, getChildLp(mActionRow));\n final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();\n mTouchSlopSquared = slop * slop;\n mHandler = new Handler();\n super.setOnClickListener(this);\n }\n\n /**\n * Indicates whether this view reacts to click events or not.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isSliceViewClickable() {\n return mOnClickListener != null || (mListContent != null && mListContent.getPrimaryAction() != null);\n }\n\n /**\n * Sets the event info for logging a click.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setClickInfo(int[] info) {\n mClickInfo = info;\n }\n\n @Override\n public void onClick(View v) {\n if (mListContent != null && mListContent.getPrimaryAction() != null) {\n try {\n SliceActionImpl sa = new SliceActionImpl(mListContent.getPrimaryAction());\n sa.getAction().send();\n if (mSliceObserver != null && mClickInfo != null && mClickInfo.length > 1) {\n EventInfo eventInfo = new EventInfo(getMode(), EventInfo.ACTION_TYPE_CONTENT, mClickInfo[0], mClickInfo[1]);\n mSliceObserver.onSliceAction(eventInfo, mListContent.getPrimaryAction());\n }\n } catch (PendingIntent.CanceledException e) {\n Log.e(TAG, \"PendingIntent for slice cannot be sent\", e);\n }\n } else if (mOnClickListener != null) {\n mOnClickListener.onClick(this);\n }\n }\n\n @Override\n public void setOnClickListener(View.OnClickListener listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public void setOnLongClickListener(View.OnLongClickListener listener) {\n super.setOnLongClickListener(listener);\n mLongClickListener = listener;\n }\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n boolean ret = super.onInterceptTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n boolean ret = super.onTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n private boolean handleTouchForLongpress(MotionEvent ev) {\n int action = ev.getActionMasked();\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n mHandler.removeCallbacks(mLongpressCheck);\n mDownX = (int) ev.getRawX();\n mDownY = (int) ev.getRawY();\n mPressing = true;\n mInLongpress = false;\n mHandler.postDelayed(mLongpressCheck, ViewConfiguration.getLongPressTimeout());\n break;\n case MotionEvent.ACTION_MOVE:\n final int deltaX = (int) ev.getRawX() - mDownX;\n final int deltaY = (int) ev.getRawY() - mDownY;\n int distance = (deltaX * deltaX) + (deltaY * deltaY);\n if (distance > mTouchSlopSquared) {\n mPressing = false;\n mHandler.removeCallbacks(mLongpressCheck);\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n mPressing = false;\n mInLongpress = false;\n mHandler.removeCallbacks(mLongpressCheck);\n break;\n }\n return mInLongpress;\n }\n\n private int getHeightForMode() {\n int mode = getMode();\n if (mode == MODE_SHORTCUT) {\n return mListContent != null && mListContent.isValid() ? mShortcutSize : 0;\n }\n return mode == MODE_LARGE ? mCurrentView.getActualHeight() : mCurrentView.getSmallHeight();\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int width = MeasureSpec.getSize(widthMeasureSpec);\n int childWidth = MeasureSpec.getSize(widthMeasureSpec);\n if (MODE_SHORTCUT == mMode) {\n // TODO: consider scaling the shortcut to fit if too small\n childWidth = mShortcutSize;\n width = mShortcutSize + getPaddingLeft() + getPaddingRight();\n }\n final int actionHeight = mActionRow.getVisibility() != View.GONE ? mActionRowHeight : 0;\n final int sliceHeight = getHeightForMode();\n final int heightAvailable = MeasureSpec.getSize(heightMeasureSpec);\n final int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n // Remove the padding from our available height\n int height = heightAvailable - getPaddingTop() - getPaddingBottom();\n if (heightAvailable >= sliceHeight + actionHeight || heightMode == MeasureSpec.UNSPECIFIED) {\n // Available space is larger than the slice or we be what we want\n if (heightMode != MeasureSpec.EXACTLY) {\n if (!mIsScrollable) {\n height = Math.min(mMaxLargeHeight, sliceHeight);\n } else {\n // If we want to be bigger than max, then we can be a good scrollable at min\n // large height, if it's not larger lets just use its desired height\n height = sliceHeight > mMaxLargeHeight ? mMinLargeHeight : sliceHeight;\n }\n }\n } else {\n // Not enough space available for slice in current mode\n if (getMode() == MODE_LARGE && heightAvailable >= mMinLargeHeight + actionHeight) {\n // It's just a slice with scrolling content; cap it to height available.\n height = Math.min(mMinLargeHeight, heightAvailable);\n } else if (getMode() == MODE_SHORTCUT) {\n // TODO: consider scaling the shortcut to fit if too small\n height = mShortcutSize;\n }\n }\n int childHeight = height + getPaddingTop() + getPaddingBottom();\n int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);\n int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);\n measureChild(mCurrentView, childWidthMeasureSpec, childHeightMeasureSpec);\n int actionPaddedHeight = actionHeight + getPaddingTop() + getPaddingBottom();\n int actionHeightSpec = MeasureSpec.makeMeasureSpec(actionPaddedHeight, MeasureSpec.EXACTLY);\n measureChild(mActionRow, childWidthMeasureSpec, actionHeightSpec);\n // Total height should include action row and our padding\n height += actionHeight + getPaddingTop() + getPaddingBottom();\n setMeasuredDimension(width, height);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n View v = mCurrentView;\n final int left = getPaddingLeft();\n final int top = getPaddingTop();\n v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight());\n if (mActionRow.getVisibility() != View.GONE) {\n mActionRow.layout(left, top + v.getMeasuredHeight(), left + mActionRow.getMeasuredWidth(), top + v.getMeasuredHeight() + mActionRow.getMeasuredHeight());\n }\n }\n\n @Override\n public void onChanged(@Nullable Slice slice) {\n setSlice(slice);\n }\n\n /**\n * Populates this view to the provided {@link Slice}.\n *\n * This will not update automatically if the slice content changes, for live\n * content see {@link SliceLiveData}.\n */\n public void setSlice(@Nullable Slice slice) {\n if (slice != null) {\n if (mCurrentSlice == null || !mCurrentSlice.getUri().equals(slice.getUri())) {\n mCurrentView.resetView();\n }\n } else {\n // No slice, no actions\n mActions = null;\n }\n mActions = SliceMetadata.getSliceActions(slice);\n mCurrentSlice = slice;\n reinflate();\n }\n\n /**\n * @return the slice being used to populate this view.\n */\n @Nullable\n public Slice getSlice() {\n return mCurrentSlice;\n }\n\n /**\n * Returns the slice actions presented in this view.\n *

\n * Note that these may be different from {@link SliceMetadata#getSliceActions()} if the actions\n * set on the view have been adjusted using {@link #setSliceActions(List)}.\n */\n @Nullable\n public List getSliceActions() {\n return mActions;\n }\n\n /**\n * Sets the slice actions to display for the slice contained in this view. Normally SliceView\n * will automatically show actions, however, it is possible to reorder or omit actions on the\n * view using this method. This is generally discouraged.\n *

\n * It is required that the slice be set on this view before actions can be set, otherwise\n * this will throw {@link IllegalStateException}. If any of the actions supplied are not\n * available for the slice set on this view (i.e. the action is not returned by\n * {@link SliceMetadata#getSliceActions()} this will throw {@link IllegalArgumentException}.\n */\n public void setSliceActions(@Nullable List newActions) {\n // Check that these actions are part of available set\n if (mCurrentSlice == null) {\n throw new IllegalStateException(\"Trying to set actions on a view without a slice\");\n }\n List availableActions = SliceMetadata.getSliceActions(mCurrentSlice);\n if (availableActions != null && newActions != null) {\n for (int i = 0; i < newActions.size(); i++) {\n if (!availableActions.contains(newActions.get(i))) {\n throw new IllegalArgumentException(\"Trying to set an action that isn't available: \" + newActions.get(i));\n }\n }\n }\n mActions = newActions;\n updateActions();\n }\n\n /**\n * Set the mode this view should present in.\n */\n public void setMode(@SliceMode int mode) {\n setMode(mode, false);\n }\n\n /**\n * Set whether this view should allow scrollable content when presenting in {@link #MODE_LARGE}.\n */\n public void setScrollable(boolean isScrollable) {\n mIsScrollable = isScrollable;\n reinflate();\n }\n\n /**\n * Sets the listener to notify when an interaction events occur on the view.\n * @see EventInfo\n */\n public void setOnSliceActionListener(@Nullable OnSliceActionListener observer) {\n mSliceObserver = observer;\n mCurrentView.setSliceActionListener(mSliceObserver);\n }\n\n /**\n * @deprecated TO BE REMOVED; use {@link #setAccentColor(int)} instead.\n */\n @Deprecated\n public void setTint(int tintColor) {\n setAccentColor(tintColor);\n }\n\n /**\n * Contents of a slice such as icons, text, and controls (e.g. toggle) can be tinted. Normally\n * a color for tinting will be provided by the slice. Using this method will override\n * the slice-provided color information and instead tint elements with the color set here.\n *\n * @param accentColor the color to use for tinting contents of this view.\n */\n public void setAccentColor(@ColorInt int accentColor) {\n mThemeTintColor = accentColor;\n mCurrentView.setTint(accentColor);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setMode(@SliceMode int mode, boolean animate) {\n if (animate) {\n Log.e(TAG, \"Animation not supported yet\");\n }\n if (mMode == mode) {\n return;\n }\n mMode = mode;\n reinflate();\n }\n\n /**\n * @return the mode this view is presenting in.\n */\n @SliceMode\n public int getMode() {\n return mMode;\n }\n\n /**\n * @hide\n *\n * Whether this view should show a row of actions with it.\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setShowActionRow(boolean show) {\n mShowActions = show;\n updateActions();\n }\n\n /**\n * @return whether this view is showing a row of actions.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isShowingActionRow() {\n return mShowActions;\n }\n\n private void reinflate() {\n if (mCurrentSlice == null) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n mListContent = new ListContent(getContext(), mCurrentSlice, mAttrs, mDefStyleAttr, mDefStyleRes);\n if (!mListContent.isValid()) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n // TODO: Smarter mapping here from one state to the next.\n int mode = getMode();\n boolean isCurrentViewShortcut = mCurrentView instanceof ShortcutView;\n if (mode == MODE_SHORTCUT && !isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new ShortcutView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n } else if (mode != MODE_SHORTCUT && isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new LargeTemplateView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n }\n mCurrentView.setMode(mode);\n mCurrentView.setSliceActionListener(mSliceObserver);\n if (mCurrentView instanceof LargeTemplateView) {\n ((LargeTemplateView) mCurrentView).setScrollable(mIsScrollable);\n }\n mCurrentView.setStyle(mAttrs, mDefStyleAttr, mDefStyleRes);\n mCurrentView.setTint(getTintColor());\n // Check if the slice content is expired and show when it was last updated\n SliceMetadata sliceMetadata = SliceMetadata.from(getContext(), mCurrentSlice);\n long lastUpdated = sliceMetadata.getLastUpdatedTime();\n long expiry = sliceMetadata.getExpiry();\n long now = System.currentTimeMillis();\n mCurrentView.setLastUpdated(lastUpdated);\n boolean expired = expiry != 0 && expiry != SliceHints.INFINITY && now > expiry;\n mCurrentView.setShowLastUpdated(mShowLastUpdated && expired);\n // Set the slice\n mCurrentView.setSliceContent(mListContent);\n updateActions();\n }\n\n private void updateActions() {\n if (mActions == null || mActions.isEmpty()) {\n // No actions, hide the row, clear out the view\n mActionRow.setVisibility(View.GONE);\n mCurrentView.setSliceActions(null);\n return;\n }\n // TODO: take priority attached to actions into account\n if (mShowActions && mMode != MODE_SHORTCUT && mActions.size() >= 2) {\n // Show in action row if available\n mActionRow.setActions(mActions, getTintColor());\n mActionRow.setVisibility(View.VISIBLE);\n // Hide them on the template\n mCurrentView.setSliceActions(null);\n } else if (mActions.size() > 0) {\n // Otherwise set them on the template\n mCurrentView.setSliceActions(mActions);\n mActionRow.setVisibility(View.GONE);\n }\n }\n\n private int getTintColor() {\n if (mThemeTintColor != -1) {\n // Theme has specified a color, use that\n return mThemeTintColor;\n } else {\n final SliceItem colorItem = SliceQuery.findSubtype(mCurrentSlice, FORMAT_INT, SUBTYPE_COLOR);\n return colorItem != null ? colorItem.getInt() : SliceViewUtil.getColorAccent(getContext());\n }\n }\n\n private LayoutParams getChildLp(View child) {\n if (child instanceof ShortcutView) {\n return new LayoutParams(mShortcutSize, mShortcutSize);\n } else {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n }\n\n /**\n * @return String representation of the provided mode.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public static String modeToString(@SliceMode int mode) {", "post_mask_code": "\n switch(mode) {\n case MODE_SHORTCUT:\n return \"MODE SHORTCUT\";\n case MODE_SMALL:\n return \"MODE SMALL\";\n case MODE_LARGE:\n return \"MODE LARGE\";\n default:\n return \"unknown mode: \" + mode;\n }\n }\n\n Runnable mLongpressCheck = new Runnable() {\n\n @Override\n public void run() {\n if (mPressing && mLongClickListener != null) {\n mInLongpress = true;\n mLongClickListener.onLongClick(SliceView.this);\n performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);\n }\n }\n };\n}\n"} {"task_id": "Java_146", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/slice/widget/SliceView.java", "mask_start_position": 23356, "mask_end_position": 23653, "canonical_solution": "switch(mode) {\n case MODE_SHORTCUT:\n return \"MODE SHORTCUT\";\n case MODE_SMALL:\n return \"MODE SMALL\";\n case MODE_LARGE:\n return \"MODE LARGE\";\n default:\n return \"unknown mode: \" + mode;\n }", "pre_mask_code": "package androidx.slice.widget;\n\nimport static android.app.slice.Slice.SUBTYPE_COLOR;\nimport static android.app.slice.SliceItem.FORMAT_INT;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.HapticFeedbackConstants;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport androidx.annotation.ColorInt;\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.RestrictTo;\nimport androidx.lifecycle.Observer;\nimport androidx.slice.Slice;\nimport androidx.slice.SliceItem;\nimport androidx.slice.SliceMetadata;\nimport androidx.slice.core.SliceActionImpl;\nimport androidx.slice.core.SliceHints;\nimport androidx.slice.core.SliceQuery;\nimport androidx.slice.view.R;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.List;\n\n/**\n * A view for displaying a {@link Slice} which is a piece of app content and actions. SliceView is\n * able to present slice content in a templated format outside of the associated app. The way this\n * content is displayed depends on the structure of the slice, the hints associated with the\n * content, and the mode that SliceView is configured for. The modes that SliceView supports are:\n *

    \n *
  • Shortcut: A shortcut is presented as an icon and a text label representing the main\n * content or action associated with the slice.
  • \n *
  • Small: The small format has a restricted height and can present a single\n * {@link SliceItem} or a limited collection of items.
  • \n *
  • Large: The large format displays multiple small templates in a list, if scrolling is\n * not enabled (see {@link #setScrollable(boolean)}) the view will show as many items as it can\n * comfortably fit.
  • \n *
\n *

\n * When constructing a slice, the contents of it can be annotated with hints, these provide the OS\n * with some information on how the content should be displayed. For example, text annotated with\n * {@link android.app.slice.Slice#HINT_TITLE} would be placed in the title position of a template.\n * A slice annotated with {@link android.app.slice.Slice#HINT_LIST} would present the child items\n * of that slice in a list.\n *

\n * Example usage:\n *\n *

\n * SliceView v = new SliceView(getContext());\n * v.setMode(desiredMode);\n * LiveData liveData = SliceLiveData.fromUri(sliceUri);\n * liveData.observe(lifecycleOwner, v);\n * 
\n * @see SliceLiveData\n */\npublic class SliceView extends ViewGroup implements Observer, View.OnClickListener {\n\n private static final String TAG = \"SliceView\";\n\n /**\n * Implement this interface to be notified of interactions with the slice displayed\n * in this view.\n * @see EventInfo\n */\n public interface OnSliceActionListener {\n\n /**\n * Called when an interaction has occurred with an element in this view.\n * @param info the type of event that occurred.\n * @param item the specific item within the {@link Slice} that was interacted with.\n */\n void onSliceAction(@NonNull EventInfo info, @NonNull SliceItem item);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n @IntDef({ MODE_SMALL, MODE_LARGE, MODE_SHORTCUT })\n @Retention(RetentionPolicy.SOURCE)\n public @interface SliceMode {\n }\n\n /**\n * Mode indicating this slice should be presented in small template format.\n */\n public static final int MODE_SMALL = 1;\n\n /**\n * Mode indicating this slice should be presented in large template format.\n */\n public static final int MODE_LARGE = 2;\n\n /**\n * Mode indicating this slice should be presented as an icon. A shortcut requires an intent,\n * icon, and label. This can be indicated by using {@link android.app.slice.Slice#HINT_TITLE}\n * on an action in a slice.\n */\n public static final int MODE_SHORTCUT = 3;\n\n private int mMode = MODE_LARGE;\n\n private Slice mCurrentSlice;\n\n private ListContent mListContent;\n\n private SliceChildView mCurrentView;\n\n private List mActions;\n\n private ActionRow mActionRow;\n\n private boolean mShowActions = false;\n\n private boolean mIsScrollable = true;\n\n private boolean mShowLastUpdated = true;\n\n private int mShortcutSize;\n\n private int mMinLargeHeight;\n\n private int mMaxLargeHeight;\n\n private int mActionRowHeight;\n\n private AttributeSet mAttrs;\n\n private int mDefStyleAttr;\n\n private int mDefStyleRes;\n\n private int mThemeTintColor = -1;\n\n private OnSliceActionListener mSliceObserver;\n\n private int mTouchSlopSquared;\n\n private View.OnLongClickListener mLongClickListener;\n\n private View.OnClickListener mOnClickListener;\n\n private int mDownX;\n\n private int mDownY;\n\n private boolean mPressing;\n\n private boolean mInLongpress;\n\n private Handler mHandler;\n\n int[] mClickInfo;\n\n public SliceView(Context context) {\n this(context, null);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, R.attr.sliceViewStyle);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, R.style.Widget_SliceView);\n }\n\n @RequiresApi(21)\n public SliceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n init(context, attrs, defStyleAttr, defStyleRes);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n mAttrs = attrs;\n mDefStyleAttr = defStyleAttr;\n mDefStyleRes = defStyleRes;\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliceView, defStyleAttr, defStyleRes);\n try {\n mThemeTintColor = a.getColor(R.styleable.SliceView_tintColor, -1);\n } finally {\n a.recycle();\n }\n mShortcutSize = getContext().getResources().getDimensionPixelSize(R.dimen.abc_slice_shortcut_size);\n mMinLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_large_height);\n mMaxLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_max_large_height);\n mActionRowHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_action_row_height);\n mCurrentView = new LargeTemplateView(getContext());\n mCurrentView.setMode(getMode());\n addView(mCurrentView, getChildLp(mCurrentView));\n // TODO: action row background should support light / dark / maybe presenter customization\n mActionRow = new ActionRow(getContext(), true);\n mActionRow.setBackground(new ColorDrawable(0xffeeeeee));\n addView(mActionRow, getChildLp(mActionRow));\n final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();\n mTouchSlopSquared = slop * slop;\n mHandler = new Handler();\n super.setOnClickListener(this);\n }\n\n /**\n * Indicates whether this view reacts to click events or not.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isSliceViewClickable() {\n return mOnClickListener != null || (mListContent != null && mListContent.getPrimaryAction() != null);\n }\n\n /**\n * Sets the event info for logging a click.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setClickInfo(int[] info) {\n mClickInfo = info;\n }\n\n @Override\n public void onClick(View v) {\n if (mListContent != null && mListContent.getPrimaryAction() != null) {\n try {\n SliceActionImpl sa = new SliceActionImpl(mListContent.getPrimaryAction());\n sa.getAction().send();\n if (mSliceObserver != null && mClickInfo != null && mClickInfo.length > 1) {\n EventInfo eventInfo = new EventInfo(getMode(), EventInfo.ACTION_TYPE_CONTENT, mClickInfo[0], mClickInfo[1]);\n mSliceObserver.onSliceAction(eventInfo, mListContent.getPrimaryAction());\n }\n } catch (PendingIntent.CanceledException e) {\n Log.e(TAG, \"PendingIntent for slice cannot be sent\", e);\n }\n } else if (mOnClickListener != null) {\n mOnClickListener.onClick(this);\n }\n }\n\n @Override\n public void setOnClickListener(View.OnClickListener listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public void setOnLongClickListener(View.OnLongClickListener listener) {\n super.setOnLongClickListener(listener);\n mLongClickListener = listener;\n }\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n boolean ret = super.onInterceptTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n boolean ret = super.onTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n private boolean handleTouchForLongpress(MotionEvent ev) {\n int action = ev.getActionMasked();\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n mHandler.removeCallbacks(mLongpressCheck);\n mDownX = (int) ev.getRawX();\n mDownY = (int) ev.getRawY();\n mPressing = true;\n mInLongpress = false;\n mHandler.postDelayed(mLongpressCheck, ViewConfiguration.getLongPressTimeout());\n break;\n case MotionEvent.ACTION_MOVE:\n final int deltaX = (int) ev.getRawX() - mDownX;\n final int deltaY = (int) ev.getRawY() - mDownY;\n int distance = (deltaX * deltaX) + (deltaY * deltaY);\n if (distance > mTouchSlopSquared) {\n mPressing = false;\n mHandler.removeCallbacks(mLongpressCheck);\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n mPressing = false;\n mInLongpress = false;\n mHandler.removeCallbacks(mLongpressCheck);\n break;\n }\n return mInLongpress;\n }\n\n private int getHeightForMode() {\n int mode = getMode();\n if (mode == MODE_SHORTCUT) {\n return mListContent != null && mListContent.isValid() ? mShortcutSize : 0;\n }\n return mode == MODE_LARGE ? mCurrentView.getActualHeight() : mCurrentView.getSmallHeight();\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int width = MeasureSpec.getSize(widthMeasureSpec);\n int childWidth = MeasureSpec.getSize(widthMeasureSpec);\n if (MODE_SHORTCUT == mMode) {\n // TODO: consider scaling the shortcut to fit if too small\n childWidth = mShortcutSize;\n width = mShortcutSize + getPaddingLeft() + getPaddingRight();\n }\n final int actionHeight = mActionRow.getVisibility() != View.GONE ? mActionRowHeight : 0;\n final int sliceHeight = getHeightForMode();\n final int heightAvailable = MeasureSpec.getSize(heightMeasureSpec);\n final int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n // Remove the padding from our available height\n int height = heightAvailable - getPaddingTop() - getPaddingBottom();\n if (heightAvailable >= sliceHeight + actionHeight || heightMode == MeasureSpec.UNSPECIFIED) {\n // Available space is larger than the slice or we be what we want\n if (heightMode != MeasureSpec.EXACTLY) {\n if (!mIsScrollable) {\n height = Math.min(mMaxLargeHeight, sliceHeight);\n } else {\n // If we want to be bigger than max, then we can be a good scrollable at min\n // large height, if it's not larger lets just use its desired height\n height = sliceHeight > mMaxLargeHeight ? mMinLargeHeight : sliceHeight;\n }\n }\n } else {\n // Not enough space available for slice in current mode\n if (getMode() == MODE_LARGE && heightAvailable >= mMinLargeHeight + actionHeight) {\n // It's just a slice with scrolling content; cap it to height available.\n height = Math.min(mMinLargeHeight, heightAvailable);\n } else if (getMode() == MODE_SHORTCUT) {\n // TODO: consider scaling the shortcut to fit if too small\n height = mShortcutSize;\n }\n }\n int childHeight = height + getPaddingTop() + getPaddingBottom();\n int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);\n int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);\n measureChild(mCurrentView, childWidthMeasureSpec, childHeightMeasureSpec);\n int actionPaddedHeight = actionHeight + getPaddingTop() + getPaddingBottom();\n int actionHeightSpec = MeasureSpec.makeMeasureSpec(actionPaddedHeight, MeasureSpec.EXACTLY);\n measureChild(mActionRow, childWidthMeasureSpec, actionHeightSpec);\n // Total height should include action row and our padding\n height += actionHeight + getPaddingTop() + getPaddingBottom();\n setMeasuredDimension(width, height);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n View v = mCurrentView;\n final int left = getPaddingLeft();\n final int top = getPaddingTop();\n v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight());\n if (mActionRow.getVisibility() != View.GONE) {\n mActionRow.layout(left, top + v.getMeasuredHeight(), left + mActionRow.getMeasuredWidth(), top + v.getMeasuredHeight() + mActionRow.getMeasuredHeight());\n }\n }\n\n @Override\n public void onChanged(@Nullable Slice slice) {\n setSlice(slice);\n }\n\n /**\n * Populates this view to the provided {@link Slice}.\n *\n * This will not update automatically if the slice content changes, for live\n * content see {@link SliceLiveData}.\n */\n public void setSlice(@Nullable Slice slice) {\n if (slice != null) {\n if (mCurrentSlice == null || !mCurrentSlice.getUri().equals(slice.getUri())) {\n mCurrentView.resetView();\n }\n } else {\n // No slice, no actions\n mActions = null;\n }\n mActions = SliceMetadata.getSliceActions(slice);\n mCurrentSlice = slice;\n reinflate();\n }\n\n /**\n * @return the slice being used to populate this view.\n */\n @Nullable\n public Slice getSlice() {\n return mCurrentSlice;\n }\n\n /**\n * Returns the slice actions presented in this view.\n *

\n * Note that these may be different from {@link SliceMetadata#getSliceActions()} if the actions\n * set on the view have been adjusted using {@link #setSliceActions(List)}.\n */\n @Nullable\n public List getSliceActions() {\n return mActions;\n }\n\n /**\n * Sets the slice actions to display for the slice contained in this view. Normally SliceView\n * will automatically show actions, however, it is possible to reorder or omit actions on the\n * view using this method. This is generally discouraged.\n *

\n * It is required that the slice be set on this view before actions can be set, otherwise\n * this will throw {@link IllegalStateException}. If any of the actions supplied are not\n * available for the slice set on this view (i.e. the action is not returned by\n * {@link SliceMetadata#getSliceActions()} this will throw {@link IllegalArgumentException}.\n */\n public void setSliceActions(@Nullable List newActions) {\n // Check that these actions are part of available set\n if (mCurrentSlice == null) {\n throw new IllegalStateException(\"Trying to set actions on a view without a slice\");\n }\n List availableActions = SliceMetadata.getSliceActions(mCurrentSlice);\n if (availableActions != null && newActions != null) {\n for (int i = 0; i < newActions.size(); i++) {\n if (!availableActions.contains(newActions.get(i))) {\n throw new IllegalArgumentException(\"Trying to set an action that isn't available: \" + newActions.get(i));\n }\n }\n }\n mActions = newActions;\n updateActions();\n }\n\n /**\n * Set the mode this view should present in.\n */\n public void setMode(@SliceMode int mode) {\n setMode(mode, false);\n }\n\n /**\n * Set whether this view should allow scrollable content when presenting in {@link #MODE_LARGE}.\n */\n public void setScrollable(boolean isScrollable) {\n mIsScrollable = isScrollable;\n reinflate();\n }\n\n /**\n * Sets the listener to notify when an interaction events occur on the view.\n * @see EventInfo\n */\n public void setOnSliceActionListener(@Nullable OnSliceActionListener observer) {\n mSliceObserver = observer;\n mCurrentView.setSliceActionListener(mSliceObserver);\n }\n\n /**\n * @deprecated TO BE REMOVED; use {@link #setAccentColor(int)} instead.\n */\n @Deprecated\n public void setTint(int tintColor) {\n setAccentColor(tintColor);\n }\n\n /**\n * Contents of a slice such as icons, text, and controls (e.g. toggle) can be tinted. Normally\n * a color for tinting will be provided by the slice. Using this method will override\n * the slice-provided color information and instead tint elements with the color set here.\n *\n * @param accentColor the color to use for tinting contents of this view.\n */\n public void setAccentColor(@ColorInt int accentColor) {\n mThemeTintColor = accentColor;\n mCurrentView.setTint(accentColor);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setMode(@SliceMode int mode, boolean animate) {\n if (animate) {\n Log.e(TAG, \"Animation not supported yet\");\n }\n if (mMode == mode) {\n return;\n }\n mMode = mode;\n reinflate();\n }\n\n /**\n * @return the mode this view is presenting in.\n */\n @SliceMode\n public int getMode() {\n return mMode;\n }\n\n /**\n * @hide\n *\n * Whether this view should show a row of actions with it.\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setShowActionRow(boolean show) {\n mShowActions = show;\n updateActions();\n }\n\n /**\n * @return whether this view is showing a row of actions.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isShowingActionRow() {\n return mShowActions;\n }\n\n private void reinflate() {\n if (mCurrentSlice == null) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n mListContent = new ListContent(getContext(), mCurrentSlice, mAttrs, mDefStyleAttr, mDefStyleRes);\n if (!mListContent.isValid()) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n // TODO: Smarter mapping here from one state to the next.\n int mode = getMode();\n boolean isCurrentViewShortcut = mCurrentView instanceof ShortcutView;\n if (mode == MODE_SHORTCUT && !isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new ShortcutView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n } else if (mode != MODE_SHORTCUT && isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new LargeTemplateView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n }\n mCurrentView.setMode(mode);\n mCurrentView.setSliceActionListener(mSliceObserver);\n if (mCurrentView instanceof LargeTemplateView) {\n ((LargeTemplateView) mCurrentView).setScrollable(mIsScrollable);\n }\n mCurrentView.setStyle(mAttrs, mDefStyleAttr, mDefStyleRes);\n mCurrentView.setTint(getTintColor());\n // Check if the slice content is expired and show when it was last updated\n SliceMetadata sliceMetadata = SliceMetadata.from(getContext(), mCurrentSlice);\n long lastUpdated = sliceMetadata.getLastUpdatedTime();\n long expiry = sliceMetadata.getExpiry();\n long now = System.currentTimeMillis();\n mCurrentView.setLastUpdated(lastUpdated);\n boolean expired = expiry != 0 && expiry != SliceHints.INFINITY && now > expiry;\n mCurrentView.setShowLastUpdated(mShowLastUpdated && expired);\n // Set the slice\n mCurrentView.setSliceContent(mListContent);\n updateActions();\n }\n\n private void updateActions() {\n if (mActions == null || mActions.isEmpty()) {\n // No actions, hide the row, clear out the view\n mActionRow.setVisibility(View.GONE);\n mCurrentView.setSliceActions(null);\n return;\n }\n // TODO: take priority attached to actions into account\n if (mShowActions && mMode != MODE_SHORTCUT && mActions.size() >= 2) {\n // Show in action row if available\n mActionRow.setActions(mActions, getTintColor());\n mActionRow.setVisibility(View.VISIBLE);\n // Hide them on the template\n mCurrentView.setSliceActions(null);\n } else if (mActions.size() > 0) {\n // Otherwise set them on the template\n mCurrentView.setSliceActions(mActions);\n mActionRow.setVisibility(View.GONE);\n }\n }\n\n private int getTintColor() {\n if (mThemeTintColor != -1) {\n // Theme has specified a color, use that\n return mThemeTintColor;\n } else {\n final SliceItem colorItem = SliceQuery.findSubtype(mCurrentSlice, FORMAT_INT, SUBTYPE_COLOR);\n return colorItem != null ? colorItem.getInt() : SliceViewUtil.getColorAccent(getContext());\n }\n }\n\n private LayoutParams getChildLp(View child) {\n if (child instanceof ShortcutView) {\n return new LayoutParams(mShortcutSize, mShortcutSize);\n } else {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n }\n\n /**\n * @return String representation of the provided mode.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public static String modeToString(@SliceMode int mode) {\n ", "post_mask_code": "\n }\n\n Runnable mLongpressCheck = new Runnable() {\n\n @Override\n public void run() {\n if (mPressing && mLongClickListener != null) {\n mInLongpress = true;\n mLongClickListener.onLongClick(SliceView.this);\n performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);\n }\n }\n };\n}\n"} {"task_id": "Java_147", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/slice/widget/SliceView.java", "mask_start_position": 23658, "mask_end_position": 23659, "canonical_solution": "}", "pre_mask_code": "package androidx.slice.widget;\n\nimport static android.app.slice.Slice.SUBTYPE_COLOR;\nimport static android.app.slice.SliceItem.FORMAT_INT;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.HapticFeedbackConstants;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport androidx.annotation.ColorInt;\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.RestrictTo;\nimport androidx.lifecycle.Observer;\nimport androidx.slice.Slice;\nimport androidx.slice.SliceItem;\nimport androidx.slice.SliceMetadata;\nimport androidx.slice.core.SliceActionImpl;\nimport androidx.slice.core.SliceHints;\nimport androidx.slice.core.SliceQuery;\nimport androidx.slice.view.R;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.List;\n\n/**\n * A view for displaying a {@link Slice} which is a piece of app content and actions. SliceView is\n * able to present slice content in a templated format outside of the associated app. The way this\n * content is displayed depends on the structure of the slice, the hints associated with the\n * content, and the mode that SliceView is configured for. The modes that SliceView supports are:\n *

    \n *
  • Shortcut: A shortcut is presented as an icon and a text label representing the main\n * content or action associated with the slice.
  • \n *
  • Small: The small format has a restricted height and can present a single\n * {@link SliceItem} or a limited collection of items.
  • \n *
  • Large: The large format displays multiple small templates in a list, if scrolling is\n * not enabled (see {@link #setScrollable(boolean)}) the view will show as many items as it can\n * comfortably fit.
  • \n *
\n *

\n * When constructing a slice, the contents of it can be annotated with hints, these provide the OS\n * with some information on how the content should be displayed. For example, text annotated with\n * {@link android.app.slice.Slice#HINT_TITLE} would be placed in the title position of a template.\n * A slice annotated with {@link android.app.slice.Slice#HINT_LIST} would present the child items\n * of that slice in a list.\n *

\n * Example usage:\n *\n *

\n * SliceView v = new SliceView(getContext());\n * v.setMode(desiredMode);\n * LiveData liveData = SliceLiveData.fromUri(sliceUri);\n * liveData.observe(lifecycleOwner, v);\n * 
\n * @see SliceLiveData\n */\npublic class SliceView extends ViewGroup implements Observer, View.OnClickListener {\n\n private static final String TAG = \"SliceView\";\n\n /**\n * Implement this interface to be notified of interactions with the slice displayed\n * in this view.\n * @see EventInfo\n */\n public interface OnSliceActionListener {\n\n /**\n * Called when an interaction has occurred with an element in this view.\n * @param info the type of event that occurred.\n * @param item the specific item within the {@link Slice} that was interacted with.\n */\n void onSliceAction(@NonNull EventInfo info, @NonNull SliceItem item);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n @IntDef({ MODE_SMALL, MODE_LARGE, MODE_SHORTCUT })\n @Retention(RetentionPolicy.SOURCE)\n public @interface SliceMode {\n }\n\n /**\n * Mode indicating this slice should be presented in small template format.\n */\n public static final int MODE_SMALL = 1;\n\n /**\n * Mode indicating this slice should be presented in large template format.\n */\n public static final int MODE_LARGE = 2;\n\n /**\n * Mode indicating this slice should be presented as an icon. A shortcut requires an intent,\n * icon, and label. This can be indicated by using {@link android.app.slice.Slice#HINT_TITLE}\n * on an action in a slice.\n */\n public static final int MODE_SHORTCUT = 3;\n\n private int mMode = MODE_LARGE;\n\n private Slice mCurrentSlice;\n\n private ListContent mListContent;\n\n private SliceChildView mCurrentView;\n\n private List mActions;\n\n private ActionRow mActionRow;\n\n private boolean mShowActions = false;\n\n private boolean mIsScrollable = true;\n\n private boolean mShowLastUpdated = true;\n\n private int mShortcutSize;\n\n private int mMinLargeHeight;\n\n private int mMaxLargeHeight;\n\n private int mActionRowHeight;\n\n private AttributeSet mAttrs;\n\n private int mDefStyleAttr;\n\n private int mDefStyleRes;\n\n private int mThemeTintColor = -1;\n\n private OnSliceActionListener mSliceObserver;\n\n private int mTouchSlopSquared;\n\n private View.OnLongClickListener mLongClickListener;\n\n private View.OnClickListener mOnClickListener;\n\n private int mDownX;\n\n private int mDownY;\n\n private boolean mPressing;\n\n private boolean mInLongpress;\n\n private Handler mHandler;\n\n int[] mClickInfo;\n\n public SliceView(Context context) {\n this(context, null);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, R.attr.sliceViewStyle);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, R.style.Widget_SliceView);\n }\n\n @RequiresApi(21)\n public SliceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n init(context, attrs, defStyleAttr, defStyleRes);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n mAttrs = attrs;\n mDefStyleAttr = defStyleAttr;\n mDefStyleRes = defStyleRes;\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliceView, defStyleAttr, defStyleRes);\n try {\n mThemeTintColor = a.getColor(R.styleable.SliceView_tintColor, -1);\n } finally {\n a.recycle();\n }\n mShortcutSize = getContext().getResources().getDimensionPixelSize(R.dimen.abc_slice_shortcut_size);\n mMinLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_large_height);\n mMaxLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_max_large_height);\n mActionRowHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_action_row_height);\n mCurrentView = new LargeTemplateView(getContext());\n mCurrentView.setMode(getMode());\n addView(mCurrentView, getChildLp(mCurrentView));\n // TODO: action row background should support light / dark / maybe presenter customization\n mActionRow = new ActionRow(getContext(), true);\n mActionRow.setBackground(new ColorDrawable(0xffeeeeee));\n addView(mActionRow, getChildLp(mActionRow));\n final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();\n mTouchSlopSquared = slop * slop;\n mHandler = new Handler();\n super.setOnClickListener(this);\n }\n\n /**\n * Indicates whether this view reacts to click events or not.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isSliceViewClickable() {\n return mOnClickListener != null || (mListContent != null && mListContent.getPrimaryAction() != null);\n }\n\n /**\n * Sets the event info for logging a click.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setClickInfo(int[] info) {\n mClickInfo = info;\n }\n\n @Override\n public void onClick(View v) {\n if (mListContent != null && mListContent.getPrimaryAction() != null) {\n try {\n SliceActionImpl sa = new SliceActionImpl(mListContent.getPrimaryAction());\n sa.getAction().send();\n if (mSliceObserver != null && mClickInfo != null && mClickInfo.length > 1) {\n EventInfo eventInfo = new EventInfo(getMode(), EventInfo.ACTION_TYPE_CONTENT, mClickInfo[0], mClickInfo[1]);\n mSliceObserver.onSliceAction(eventInfo, mListContent.getPrimaryAction());\n }\n } catch (PendingIntent.CanceledException e) {\n Log.e(TAG, \"PendingIntent for slice cannot be sent\", e);\n }\n } else if (mOnClickListener != null) {\n mOnClickListener.onClick(this);\n }\n }\n\n @Override\n public void setOnClickListener(View.OnClickListener listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public void setOnLongClickListener(View.OnLongClickListener listener) {\n super.setOnLongClickListener(listener);\n mLongClickListener = listener;\n }\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n boolean ret = super.onInterceptTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n boolean ret = super.onTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n private boolean handleTouchForLongpress(MotionEvent ev) {\n int action = ev.getActionMasked();\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n mHandler.removeCallbacks(mLongpressCheck);\n mDownX = (int) ev.getRawX();\n mDownY = (int) ev.getRawY();\n mPressing = true;\n mInLongpress = false;\n mHandler.postDelayed(mLongpressCheck, ViewConfiguration.getLongPressTimeout());\n break;\n case MotionEvent.ACTION_MOVE:\n final int deltaX = (int) ev.getRawX() - mDownX;\n final int deltaY = (int) ev.getRawY() - mDownY;\n int distance = (deltaX * deltaX) + (deltaY * deltaY);\n if (distance > mTouchSlopSquared) {\n mPressing = false;\n mHandler.removeCallbacks(mLongpressCheck);\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n mPressing = false;\n mInLongpress = false;\n mHandler.removeCallbacks(mLongpressCheck);\n break;\n }\n return mInLongpress;\n }\n\n private int getHeightForMode() {\n int mode = getMode();\n if (mode == MODE_SHORTCUT) {\n return mListContent != null && mListContent.isValid() ? mShortcutSize : 0;\n }\n return mode == MODE_LARGE ? mCurrentView.getActualHeight() : mCurrentView.getSmallHeight();\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int width = MeasureSpec.getSize(widthMeasureSpec);\n int childWidth = MeasureSpec.getSize(widthMeasureSpec);\n if (MODE_SHORTCUT == mMode) {\n // TODO: consider scaling the shortcut to fit if too small\n childWidth = mShortcutSize;\n width = mShortcutSize + getPaddingLeft() + getPaddingRight();\n }\n final int actionHeight = mActionRow.getVisibility() != View.GONE ? mActionRowHeight : 0;\n final int sliceHeight = getHeightForMode();\n final int heightAvailable = MeasureSpec.getSize(heightMeasureSpec);\n final int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n // Remove the padding from our available height\n int height = heightAvailable - getPaddingTop() - getPaddingBottom();\n if (heightAvailable >= sliceHeight + actionHeight || heightMode == MeasureSpec.UNSPECIFIED) {\n // Available space is larger than the slice or we be what we want\n if (heightMode != MeasureSpec.EXACTLY) {\n if (!mIsScrollable) {\n height = Math.min(mMaxLargeHeight, sliceHeight);\n } else {\n // If we want to be bigger than max, then we can be a good scrollable at min\n // large height, if it's not larger lets just use its desired height\n height = sliceHeight > mMaxLargeHeight ? mMinLargeHeight : sliceHeight;\n }\n }\n } else {\n // Not enough space available for slice in current mode\n if (getMode() == MODE_LARGE && heightAvailable >= mMinLargeHeight + actionHeight) {\n // It's just a slice with scrolling content; cap it to height available.\n height = Math.min(mMinLargeHeight, heightAvailable);\n } else if (getMode() == MODE_SHORTCUT) {\n // TODO: consider scaling the shortcut to fit if too small\n height = mShortcutSize;\n }\n }\n int childHeight = height + getPaddingTop() + getPaddingBottom();\n int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);\n int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);\n measureChild(mCurrentView, childWidthMeasureSpec, childHeightMeasureSpec);\n int actionPaddedHeight = actionHeight + getPaddingTop() + getPaddingBottom();\n int actionHeightSpec = MeasureSpec.makeMeasureSpec(actionPaddedHeight, MeasureSpec.EXACTLY);\n measureChild(mActionRow, childWidthMeasureSpec, actionHeightSpec);\n // Total height should include action row and our padding\n height += actionHeight + getPaddingTop() + getPaddingBottom();\n setMeasuredDimension(width, height);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n View v = mCurrentView;\n final int left = getPaddingLeft();\n final int top = getPaddingTop();\n v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight());\n if (mActionRow.getVisibility() != View.GONE) {\n mActionRow.layout(left, top + v.getMeasuredHeight(), left + mActionRow.getMeasuredWidth(), top + v.getMeasuredHeight() + mActionRow.getMeasuredHeight());\n }\n }\n\n @Override\n public void onChanged(@Nullable Slice slice) {\n setSlice(slice);\n }\n\n /**\n * Populates this view to the provided {@link Slice}.\n *\n * This will not update automatically if the slice content changes, for live\n * content see {@link SliceLiveData}.\n */\n public void setSlice(@Nullable Slice slice) {\n if (slice != null) {\n if (mCurrentSlice == null || !mCurrentSlice.getUri().equals(slice.getUri())) {\n mCurrentView.resetView();\n }\n } else {\n // No slice, no actions\n mActions = null;\n }\n mActions = SliceMetadata.getSliceActions(slice);\n mCurrentSlice = slice;\n reinflate();\n }\n\n /**\n * @return the slice being used to populate this view.\n */\n @Nullable\n public Slice getSlice() {\n return mCurrentSlice;\n }\n\n /**\n * Returns the slice actions presented in this view.\n *

\n * Note that these may be different from {@link SliceMetadata#getSliceActions()} if the actions\n * set on the view have been adjusted using {@link #setSliceActions(List)}.\n */\n @Nullable\n public List getSliceActions() {\n return mActions;\n }\n\n /**\n * Sets the slice actions to display for the slice contained in this view. Normally SliceView\n * will automatically show actions, however, it is possible to reorder or omit actions on the\n * view using this method. This is generally discouraged.\n *

\n * It is required that the slice be set on this view before actions can be set, otherwise\n * this will throw {@link IllegalStateException}. If any of the actions supplied are not\n * available for the slice set on this view (i.e. the action is not returned by\n * {@link SliceMetadata#getSliceActions()} this will throw {@link IllegalArgumentException}.\n */\n public void setSliceActions(@Nullable List newActions) {\n // Check that these actions are part of available set\n if (mCurrentSlice == null) {\n throw new IllegalStateException(\"Trying to set actions on a view without a slice\");\n }\n List availableActions = SliceMetadata.getSliceActions(mCurrentSlice);\n if (availableActions != null && newActions != null) {\n for (int i = 0; i < newActions.size(); i++) {\n if (!availableActions.contains(newActions.get(i))) {\n throw new IllegalArgumentException(\"Trying to set an action that isn't available: \" + newActions.get(i));\n }\n }\n }\n mActions = newActions;\n updateActions();\n }\n\n /**\n * Set the mode this view should present in.\n */\n public void setMode(@SliceMode int mode) {\n setMode(mode, false);\n }\n\n /**\n * Set whether this view should allow scrollable content when presenting in {@link #MODE_LARGE}.\n */\n public void setScrollable(boolean isScrollable) {\n mIsScrollable = isScrollable;\n reinflate();\n }\n\n /**\n * Sets the listener to notify when an interaction events occur on the view.\n * @see EventInfo\n */\n public void setOnSliceActionListener(@Nullable OnSliceActionListener observer) {\n mSliceObserver = observer;\n mCurrentView.setSliceActionListener(mSliceObserver);\n }\n\n /**\n * @deprecated TO BE REMOVED; use {@link #setAccentColor(int)} instead.\n */\n @Deprecated\n public void setTint(int tintColor) {\n setAccentColor(tintColor);\n }\n\n /**\n * Contents of a slice such as icons, text, and controls (e.g. toggle) can be tinted. Normally\n * a color for tinting will be provided by the slice. Using this method will override\n * the slice-provided color information and instead tint elements with the color set here.\n *\n * @param accentColor the color to use for tinting contents of this view.\n */\n public void setAccentColor(@ColorInt int accentColor) {\n mThemeTintColor = accentColor;\n mCurrentView.setTint(accentColor);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setMode(@SliceMode int mode, boolean animate) {\n if (animate) {\n Log.e(TAG, \"Animation not supported yet\");\n }\n if (mMode == mode) {\n return;\n }\n mMode = mode;\n reinflate();\n }\n\n /**\n * @return the mode this view is presenting in.\n */\n @SliceMode\n public int getMode() {\n return mMode;\n }\n\n /**\n * @hide\n *\n * Whether this view should show a row of actions with it.\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setShowActionRow(boolean show) {\n mShowActions = show;\n updateActions();\n }\n\n /**\n * @return whether this view is showing a row of actions.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isShowingActionRow() {\n return mShowActions;\n }\n\n private void reinflate() {\n if (mCurrentSlice == null) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n mListContent = new ListContent(getContext(), mCurrentSlice, mAttrs, mDefStyleAttr, mDefStyleRes);\n if (!mListContent.isValid()) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n // TODO: Smarter mapping here from one state to the next.\n int mode = getMode();\n boolean isCurrentViewShortcut = mCurrentView instanceof ShortcutView;\n if (mode == MODE_SHORTCUT && !isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new ShortcutView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n } else if (mode != MODE_SHORTCUT && isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new LargeTemplateView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n }\n mCurrentView.setMode(mode);\n mCurrentView.setSliceActionListener(mSliceObserver);\n if (mCurrentView instanceof LargeTemplateView) {\n ((LargeTemplateView) mCurrentView).setScrollable(mIsScrollable);\n }\n mCurrentView.setStyle(mAttrs, mDefStyleAttr, mDefStyleRes);\n mCurrentView.setTint(getTintColor());\n // Check if the slice content is expired and show when it was last updated\n SliceMetadata sliceMetadata = SliceMetadata.from(getContext(), mCurrentSlice);\n long lastUpdated = sliceMetadata.getLastUpdatedTime();\n long expiry = sliceMetadata.getExpiry();\n long now = System.currentTimeMillis();\n mCurrentView.setLastUpdated(lastUpdated);\n boolean expired = expiry != 0 && expiry != SliceHints.INFINITY && now > expiry;\n mCurrentView.setShowLastUpdated(mShowLastUpdated && expired);\n // Set the slice\n mCurrentView.setSliceContent(mListContent);\n updateActions();\n }\n\n private void updateActions() {\n if (mActions == null || mActions.isEmpty()) {\n // No actions, hide the row, clear out the view\n mActionRow.setVisibility(View.GONE);\n mCurrentView.setSliceActions(null);\n return;\n }\n // TODO: take priority attached to actions into account\n if (mShowActions && mMode != MODE_SHORTCUT && mActions.size() >= 2) {\n // Show in action row if available\n mActionRow.setActions(mActions, getTintColor());\n mActionRow.setVisibility(View.VISIBLE);\n // Hide them on the template\n mCurrentView.setSliceActions(null);\n } else if (mActions.size() > 0) {\n // Otherwise set them on the template\n mCurrentView.setSliceActions(mActions);\n mActionRow.setVisibility(View.GONE);\n }\n }\n\n private int getTintColor() {\n if (mThemeTintColor != -1) {\n // Theme has specified a color, use that\n return mThemeTintColor;\n } else {\n final SliceItem colorItem = SliceQuery.findSubtype(mCurrentSlice, FORMAT_INT, SUBTYPE_COLOR);\n return colorItem != null ? colorItem.getInt() : SliceViewUtil.getColorAccent(getContext());\n }\n }\n\n private LayoutParams getChildLp(View child) {\n if (child instanceof ShortcutView) {\n return new LayoutParams(mShortcutSize, mShortcutSize);\n } else {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n }\n\n /**\n * @return String representation of the provided mode.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public static String modeToString(@SliceMode int mode) {\n switch(mode) {\n case MODE_SHORTCUT:\n return \"MODE SHORTCUT\";\n case MODE_SMALL:\n return \"MODE SMALL\";\n case MODE_LARGE:\n return \"MODE LARGE\";\n default:\n return \"unknown mode: \" + mode;\n }\n ", "post_mask_code": "\n\n Runnable mLongpressCheck = new Runnable() {\n\n @Override\n public void run() {\n if (mPressing && mLongClickListener != null) {\n mInLongpress = true;\n mLongClickListener.onLongClick(SliceView.this);\n performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);\n }\n }\n };\n}\n"} {"task_id": "Java_148", "language": "Java", "task_type": "single_line", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/slice/widget/SliceView.java", "mask_start_position": 6917, "mask_end_position": 6931, "canonical_solution": "CurrentView));", "pre_mask_code": "package androidx.slice.widget;\n\nimport static android.app.slice.Slice.SUBTYPE_COLOR;\nimport static android.app.slice.SliceItem.FORMAT_INT;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.HapticFeedbackConstants;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport androidx.annotation.ColorInt;\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.RestrictTo;\nimport androidx.lifecycle.Observer;\nimport androidx.slice.Slice;\nimport androidx.slice.SliceItem;\nimport androidx.slice.SliceMetadata;\nimport androidx.slice.core.SliceActionImpl;\nimport androidx.slice.core.SliceHints;\nimport androidx.slice.core.SliceQuery;\nimport androidx.slice.view.R;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.List;\n\n/**\n * A view for displaying a {@link Slice} which is a piece of app content and actions. SliceView is\n * able to present slice content in a templated format outside of the associated app. The way this\n * content is displayed depends on the structure of the slice, the hints associated with the\n * content, and the mode that SliceView is configured for. The modes that SliceView supports are:\n *

    \n *
  • Shortcut: A shortcut is presented as an icon and a text label representing the main\n * content or action associated with the slice.
  • \n *
  • Small: The small format has a restricted height and can present a single\n * {@link SliceItem} or a limited collection of items.
  • \n *
  • Large: The large format displays multiple small templates in a list, if scrolling is\n * not enabled (see {@link #setScrollable(boolean)}) the view will show as many items as it can\n * comfortably fit.
  • \n *
\n *

\n * When constructing a slice, the contents of it can be annotated with hints, these provide the OS\n * with some information on how the content should be displayed. For example, text annotated with\n * {@link android.app.slice.Slice#HINT_TITLE} would be placed in the title position of a template.\n * A slice annotated with {@link android.app.slice.Slice#HINT_LIST} would present the child items\n * of that slice in a list.\n *

\n * Example usage:\n *\n *

\n * SliceView v = new SliceView(getContext());\n * v.setMode(desiredMode);\n * LiveData liveData = SliceLiveData.fromUri(sliceUri);\n * liveData.observe(lifecycleOwner, v);\n * 
\n * @see SliceLiveData\n */\npublic class SliceView extends ViewGroup implements Observer, View.OnClickListener {\n\n private static final String TAG = \"SliceView\";\n\n /**\n * Implement this interface to be notified of interactions with the slice displayed\n * in this view.\n * @see EventInfo\n */\n public interface OnSliceActionListener {\n\n /**\n * Called when an interaction has occurred with an element in this view.\n * @param info the type of event that occurred.\n * @param item the specific item within the {@link Slice} that was interacted with.\n */\n void onSliceAction(@NonNull EventInfo info, @NonNull SliceItem item);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n @IntDef({ MODE_SMALL, MODE_LARGE, MODE_SHORTCUT })\n @Retention(RetentionPolicy.SOURCE)\n public @interface SliceMode {\n }\n\n /**\n * Mode indicating this slice should be presented in small template format.\n */\n public static final int MODE_SMALL = 1;\n\n /**\n * Mode indicating this slice should be presented in large template format.\n */\n public static final int MODE_LARGE = 2;\n\n /**\n * Mode indicating this slice should be presented as an icon. A shortcut requires an intent,\n * icon, and label. This can be indicated by using {@link android.app.slice.Slice#HINT_TITLE}\n * on an action in a slice.\n */\n public static final int MODE_SHORTCUT = 3;\n\n private int mMode = MODE_LARGE;\n\n private Slice mCurrentSlice;\n\n private ListContent mListContent;\n\n private SliceChildView mCurrentView;\n\n private List mActions;\n\n private ActionRow mActionRow;\n\n private boolean mShowActions = false;\n\n private boolean mIsScrollable = true;\n\n private boolean mShowLastUpdated = true;\n\n private int mShortcutSize;\n\n private int mMinLargeHeight;\n\n private int mMaxLargeHeight;\n\n private int mActionRowHeight;\n\n private AttributeSet mAttrs;\n\n private int mDefStyleAttr;\n\n private int mDefStyleRes;\n\n private int mThemeTintColor = -1;\n\n private OnSliceActionListener mSliceObserver;\n\n private int mTouchSlopSquared;\n\n private View.OnLongClickListener mLongClickListener;\n\n private View.OnClickListener mOnClickListener;\n\n private int mDownX;\n\n private int mDownY;\n\n private boolean mPressing;\n\n private boolean mInLongpress;\n\n private Handler mHandler;\n\n int[] mClickInfo;\n\n public SliceView(Context context) {\n this(context, null);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, R.attr.sliceViewStyle);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, R.style.Widget_SliceView);\n }\n\n @RequiresApi(21)\n public SliceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n init(context, attrs, defStyleAttr, defStyleRes);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n mAttrs = attrs;\n mDefStyleAttr = defStyleAttr;\n mDefStyleRes = defStyleRes;\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliceView, defStyleAttr, defStyleRes);\n try {\n mThemeTintColor = a.getColor(R.styleable.SliceView_tintColor, -1);\n } finally {\n a.recycle();\n }\n mShortcutSize = getContext().getResources().getDimensionPixelSize(R.dimen.abc_slice_shortcut_size);\n mMinLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_large_height);\n mMaxLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_max_large_height);\n mActionRowHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_action_row_height);\n mCurrentView = new LargeTemplateView(getContext());\n mCurrentView.setMode(getMode());\n addView(mCurrentView, getChildLp(m", "post_mask_code": "\n // TODO: action row background should support light / dark / maybe presenter customization\n mActionRow = new ActionRow(getContext(), true);\n mActionRow.setBackground(new ColorDrawable(0xffeeeeee));\n addView(mActionRow, getChildLp(mActionRow));\n final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();\n mTouchSlopSquared = slop * slop;\n mHandler = new Handler();\n super.setOnClickListener(this);\n }\n\n /**\n * Indicates whether this view reacts to click events or not.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isSliceViewClickable() {\n return mOnClickListener != null || (mListContent != null && mListContent.getPrimaryAction() != null);\n }\n\n /**\n * Sets the event info for logging a click.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setClickInfo(int[] info) {\n mClickInfo = info;\n }\n\n @Override\n public void onClick(View v) {\n if (mListContent != null && mListContent.getPrimaryAction() != null) {\n try {\n SliceActionImpl sa = new SliceActionImpl(mListContent.getPrimaryAction());\n sa.getAction().send();\n if (mSliceObserver != null && mClickInfo != null && mClickInfo.length > 1) {\n EventInfo eventInfo = new EventInfo(getMode(), EventInfo.ACTION_TYPE_CONTENT, mClickInfo[0], mClickInfo[1]);\n mSliceObserver.onSliceAction(eventInfo, mListContent.getPrimaryAction());\n }\n } catch (PendingIntent.CanceledException e) {\n Log.e(TAG, \"PendingIntent for slice cannot be sent\", e);\n }\n } else if (mOnClickListener != null) {\n mOnClickListener.onClick(this);\n }\n }\n\n @Override\n public void setOnClickListener(View.OnClickListener listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public void setOnLongClickListener(View.OnLongClickListener listener) {\n super.setOnLongClickListener(listener);\n mLongClickListener = listener;\n }\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n boolean ret = super.onInterceptTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n boolean ret = super.onTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n private boolean handleTouchForLongpress(MotionEvent ev) {\n int action = ev.getActionMasked();\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n mHandler.removeCallbacks(mLongpressCheck);\n mDownX = (int) ev.getRawX();\n mDownY = (int) ev.getRawY();\n mPressing = true;\n mInLongpress = false;\n mHandler.postDelayed(mLongpressCheck, ViewConfiguration.getLongPressTimeout());\n break;\n case MotionEvent.ACTION_MOVE:\n final int deltaX = (int) ev.getRawX() - mDownX;\n final int deltaY = (int) ev.getRawY() - mDownY;\n int distance = (deltaX * deltaX) + (deltaY * deltaY);\n if (distance > mTouchSlopSquared) {\n mPressing = false;\n mHandler.removeCallbacks(mLongpressCheck);\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n mPressing = false;\n mInLongpress = false;\n mHandler.removeCallbacks(mLongpressCheck);\n break;\n }\n return mInLongpress;\n }\n\n private int getHeightForMode() {\n int mode = getMode();\n if (mode == MODE_SHORTCUT) {\n return mListContent != null && mListContent.isValid() ? mShortcutSize : 0;\n }\n return mode == MODE_LARGE ? mCurrentView.getActualHeight() : mCurrentView.getSmallHeight();\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int width = MeasureSpec.getSize(widthMeasureSpec);\n int childWidth = MeasureSpec.getSize(widthMeasureSpec);\n if (MODE_SHORTCUT == mMode) {\n // TODO: consider scaling the shortcut to fit if too small\n childWidth = mShortcutSize;\n width = mShortcutSize + getPaddingLeft() + getPaddingRight();\n }\n final int actionHeight = mActionRow.getVisibility() != View.GONE ? mActionRowHeight : 0;\n final int sliceHeight = getHeightForMode();\n final int heightAvailable = MeasureSpec.getSize(heightMeasureSpec);\n final int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n // Remove the padding from our available height\n int height = heightAvailable - getPaddingTop() - getPaddingBottom();\n if (heightAvailable >= sliceHeight + actionHeight || heightMode == MeasureSpec.UNSPECIFIED) {\n // Available space is larger than the slice or we be what we want\n if (heightMode != MeasureSpec.EXACTLY) {\n if (!mIsScrollable) {\n height = Math.min(mMaxLargeHeight, sliceHeight);\n } else {\n // If we want to be bigger than max, then we can be a good scrollable at min\n // large height, if it's not larger lets just use its desired height\n height = sliceHeight > mMaxLargeHeight ? mMinLargeHeight : sliceHeight;\n }\n }\n } else {\n // Not enough space available for slice in current mode\n if (getMode() == MODE_LARGE && heightAvailable >= mMinLargeHeight + actionHeight) {\n // It's just a slice with scrolling content; cap it to height available.\n height = Math.min(mMinLargeHeight, heightAvailable);\n } else if (getMode() == MODE_SHORTCUT) {\n // TODO: consider scaling the shortcut to fit if too small\n height = mShortcutSize;\n }\n }\n int childHeight = height + getPaddingTop() + getPaddingBottom();\n int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);\n int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);\n measureChild(mCurrentView, childWidthMeasureSpec, childHeightMeasureSpec);\n int actionPaddedHeight = actionHeight + getPaddingTop() + getPaddingBottom();\n int actionHeightSpec = MeasureSpec.makeMeasureSpec(actionPaddedHeight, MeasureSpec.EXACTLY);\n measureChild(mActionRow, childWidthMeasureSpec, actionHeightSpec);\n // Total height should include action row and our padding\n height += actionHeight + getPaddingTop() + getPaddingBottom();\n setMeasuredDimension(width, height);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n View v = mCurrentView;\n final int left = getPaddingLeft();\n final int top = getPaddingTop();\n v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight());\n if (mActionRow.getVisibility() != View.GONE) {\n mActionRow.layout(left, top + v.getMeasuredHeight(), left + mActionRow.getMeasuredWidth(), top + v.getMeasuredHeight() + mActionRow.getMeasuredHeight());\n }\n }\n\n @Override\n public void onChanged(@Nullable Slice slice) {\n setSlice(slice);\n }\n\n /**\n * Populates this view to the provided {@link Slice}.\n *\n * This will not update automatically if the slice content changes, for live\n * content see {@link SliceLiveData}.\n */\n public void setSlice(@Nullable Slice slice) {\n if (slice != null) {\n if (mCurrentSlice == null || !mCurrentSlice.getUri().equals(slice.getUri())) {\n mCurrentView.resetView();\n }\n } else {\n // No slice, no actions\n mActions = null;\n }\n mActions = SliceMetadata.getSliceActions(slice);\n mCurrentSlice = slice;\n reinflate();\n }\n\n /**\n * @return the slice being used to populate this view.\n */\n @Nullable\n public Slice getSlice() {\n return mCurrentSlice;\n }\n\n /**\n * Returns the slice actions presented in this view.\n *

\n * Note that these may be different from {@link SliceMetadata#getSliceActions()} if the actions\n * set on the view have been adjusted using {@link #setSliceActions(List)}.\n */\n @Nullable\n public List getSliceActions() {\n return mActions;\n }\n\n /**\n * Sets the slice actions to display for the slice contained in this view. Normally SliceView\n * will automatically show actions, however, it is possible to reorder or omit actions on the\n * view using this method. This is generally discouraged.\n *

\n * It is required that the slice be set on this view before actions can be set, otherwise\n * this will throw {@link IllegalStateException}. If any of the actions supplied are not\n * available for the slice set on this view (i.e. the action is not returned by\n * {@link SliceMetadata#getSliceActions()} this will throw {@link IllegalArgumentException}.\n */\n public void setSliceActions(@Nullable List newActions) {\n // Check that these actions are part of available set\n if (mCurrentSlice == null) {\n throw new IllegalStateException(\"Trying to set actions on a view without a slice\");\n }\n List availableActions = SliceMetadata.getSliceActions(mCurrentSlice);\n if (availableActions != null && newActions != null) {\n for (int i = 0; i < newActions.size(); i++) {\n if (!availableActions.contains(newActions.get(i))) {\n throw new IllegalArgumentException(\"Trying to set an action that isn't available: \" + newActions.get(i));\n }\n }\n }\n mActions = newActions;\n updateActions();\n }\n\n /**\n * Set the mode this view should present in.\n */\n public void setMode(@SliceMode int mode) {\n setMode(mode, false);\n }\n\n /**\n * Set whether this view should allow scrollable content when presenting in {@link #MODE_LARGE}.\n */\n public void setScrollable(boolean isScrollable) {\n mIsScrollable = isScrollable;\n reinflate();\n }\n\n /**\n * Sets the listener to notify when an interaction events occur on the view.\n * @see EventInfo\n */\n public void setOnSliceActionListener(@Nullable OnSliceActionListener observer) {\n mSliceObserver = observer;\n mCurrentView.setSliceActionListener(mSliceObserver);\n }\n\n /**\n * @deprecated TO BE REMOVED; use {@link #setAccentColor(int)} instead.\n */\n @Deprecated\n public void setTint(int tintColor) {\n setAccentColor(tintColor);\n }\n\n /**\n * Contents of a slice such as icons, text, and controls (e.g. toggle) can be tinted. Normally\n * a color for tinting will be provided by the slice. Using this method will override\n * the slice-provided color information and instead tint elements with the color set here.\n *\n * @param accentColor the color to use for tinting contents of this view.\n */\n public void setAccentColor(@ColorInt int accentColor) {\n mThemeTintColor = accentColor;\n mCurrentView.setTint(accentColor);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setMode(@SliceMode int mode, boolean animate) {\n if (animate) {\n Log.e(TAG, \"Animation not supported yet\");\n }\n if (mMode == mode) {\n return;\n }\n mMode = mode;\n reinflate();\n }\n\n /**\n * @return the mode this view is presenting in.\n */\n @SliceMode\n public int getMode() {\n return mMode;\n }\n\n /**\n * @hide\n *\n * Whether this view should show a row of actions with it.\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setShowActionRow(boolean show) {\n mShowActions = show;\n updateActions();\n }\n\n /**\n * @return whether this view is showing a row of actions.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isShowingActionRow() {\n return mShowActions;\n }\n\n private void reinflate() {\n if (mCurrentSlice == null) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n mListContent = new ListContent(getContext(), mCurrentSlice, mAttrs, mDefStyleAttr, mDefStyleRes);\n if (!mListContent.isValid()) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n // TODO: Smarter mapping here from one state to the next.\n int mode = getMode();\n boolean isCurrentViewShortcut = mCurrentView instanceof ShortcutView;\n if (mode == MODE_SHORTCUT && !isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new ShortcutView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n } else if (mode != MODE_SHORTCUT && isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new LargeTemplateView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n }\n mCurrentView.setMode(mode);\n mCurrentView.setSliceActionListener(mSliceObserver);\n if (mCurrentView instanceof LargeTemplateView) {\n ((LargeTemplateView) mCurrentView).setScrollable(mIsScrollable);\n }\n mCurrentView.setStyle(mAttrs, mDefStyleAttr, mDefStyleRes);\n mCurrentView.setTint(getTintColor());\n // Check if the slice content is expired and show when it was last updated\n SliceMetadata sliceMetadata = SliceMetadata.from(getContext(), mCurrentSlice);\n long lastUpdated = sliceMetadata.getLastUpdatedTime();\n long expiry = sliceMetadata.getExpiry();\n long now = System.currentTimeMillis();\n mCurrentView.setLastUpdated(lastUpdated);\n boolean expired = expiry != 0 && expiry != SliceHints.INFINITY && now > expiry;\n mCurrentView.setShowLastUpdated(mShowLastUpdated && expired);\n // Set the slice\n mCurrentView.setSliceContent(mListContent);\n updateActions();\n }\n\n private void updateActions() {\n if (mActions == null || mActions.isEmpty()) {\n // No actions, hide the row, clear out the view\n mActionRow.setVisibility(View.GONE);\n mCurrentView.setSliceActions(null);\n return;\n }\n // TODO: take priority attached to actions into account\n if (mShowActions && mMode != MODE_SHORTCUT && mActions.size() >= 2) {\n // Show in action row if available\n mActionRow.setActions(mActions, getTintColor());\n mActionRow.setVisibility(View.VISIBLE);\n // Hide them on the template\n mCurrentView.setSliceActions(null);\n } else if (mActions.size() > 0) {\n // Otherwise set them on the template\n mCurrentView.setSliceActions(mActions);\n mActionRow.setVisibility(View.GONE);\n }\n }\n\n private int getTintColor() {\n if (mThemeTintColor != -1) {\n // Theme has specified a color, use that\n return mThemeTintColor;\n } else {\n final SliceItem colorItem = SliceQuery.findSubtype(mCurrentSlice, FORMAT_INT, SUBTYPE_COLOR);\n return colorItem != null ? colorItem.getInt() : SliceViewUtil.getColorAccent(getContext());\n }\n }\n\n private LayoutParams getChildLp(View child) {\n if (child instanceof ShortcutView) {\n return new LayoutParams(mShortcutSize, mShortcutSize);\n } else {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n }\n\n /**\n * @return String representation of the provided mode.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public static String modeToString(@SliceMode int mode) {\n switch(mode) {\n case MODE_SHORTCUT:\n return \"MODE SHORTCUT\";\n case MODE_SMALL:\n return \"MODE SMALL\";\n case MODE_LARGE:\n return \"MODE LARGE\";\n default:\n return \"unknown mode: \" + mode;\n }\n }\n\n Runnable mLongpressCheck = new Runnable() {\n\n @Override\n public void run() {\n if (mPressing && mLongClickListener != null) {\n mInLongpress = true;\n mLongClickListener.onLongClick(SliceView.this);\n performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);\n }\n }\n };\n}\n"} {"task_id": "Java_149", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/slice/widget/SliceView.java", "mask_start_position": 7509, "mask_end_position": 7706, "canonical_solution": "@RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isSliceViewClickable() {\n return mOnClickListener != null || (mListContent != null && mListContent.getPrimaryAction() != null);\n }", "pre_mask_code": "package androidx.slice.widget;\n\nimport static android.app.slice.Slice.SUBTYPE_COLOR;\nimport static android.app.slice.SliceItem.FORMAT_INT;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.HapticFeedbackConstants;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport androidx.annotation.ColorInt;\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.RestrictTo;\nimport androidx.lifecycle.Observer;\nimport androidx.slice.Slice;\nimport androidx.slice.SliceItem;\nimport androidx.slice.SliceMetadata;\nimport androidx.slice.core.SliceActionImpl;\nimport androidx.slice.core.SliceHints;\nimport androidx.slice.core.SliceQuery;\nimport androidx.slice.view.R;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.List;\n\n/**\n * A view for displaying a {@link Slice} which is a piece of app content and actions. SliceView is\n * able to present slice content in a templated format outside of the associated app. The way this\n * content is displayed depends on the structure of the slice, the hints associated with the\n * content, and the mode that SliceView is configured for. The modes that SliceView supports are:\n *

    \n *
  • Shortcut: A shortcut is presented as an icon and a text label representing the main\n * content or action associated with the slice.
  • \n *
  • Small: The small format has a restricted height and can present a single\n * {@link SliceItem} or a limited collection of items.
  • \n *
  • Large: The large format displays multiple small templates in a list, if scrolling is\n * not enabled (see {@link #setScrollable(boolean)}) the view will show as many items as it can\n * comfortably fit.
  • \n *
\n *

\n * When constructing a slice, the contents of it can be annotated with hints, these provide the OS\n * with some information on how the content should be displayed. For example, text annotated with\n * {@link android.app.slice.Slice#HINT_TITLE} would be placed in the title position of a template.\n * A slice annotated with {@link android.app.slice.Slice#HINT_LIST} would present the child items\n * of that slice in a list.\n *

\n * Example usage:\n *\n *

\n * SliceView v = new SliceView(getContext());\n * v.setMode(desiredMode);\n * LiveData liveData = SliceLiveData.fromUri(sliceUri);\n * liveData.observe(lifecycleOwner, v);\n * 
\n * @see SliceLiveData\n */\npublic class SliceView extends ViewGroup implements Observer, View.OnClickListener {\n\n private static final String TAG = \"SliceView\";\n\n /**\n * Implement this interface to be notified of interactions with the slice displayed\n * in this view.\n * @see EventInfo\n */\n public interface OnSliceActionListener {\n\n /**\n * Called when an interaction has occurred with an element in this view.\n * @param info the type of event that occurred.\n * @param item the specific item within the {@link Slice} that was interacted with.\n */\n void onSliceAction(@NonNull EventInfo info, @NonNull SliceItem item);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n @IntDef({ MODE_SMALL, MODE_LARGE, MODE_SHORTCUT })\n @Retention(RetentionPolicy.SOURCE)\n public @interface SliceMode {\n }\n\n /**\n * Mode indicating this slice should be presented in small template format.\n */\n public static final int MODE_SMALL = 1;\n\n /**\n * Mode indicating this slice should be presented in large template format.\n */\n public static final int MODE_LARGE = 2;\n\n /**\n * Mode indicating this slice should be presented as an icon. A shortcut requires an intent,\n * icon, and label. This can be indicated by using {@link android.app.slice.Slice#HINT_TITLE}\n * on an action in a slice.\n */\n public static final int MODE_SHORTCUT = 3;\n\n private int mMode = MODE_LARGE;\n\n private Slice mCurrentSlice;\n\n private ListContent mListContent;\n\n private SliceChildView mCurrentView;\n\n private List mActions;\n\n private ActionRow mActionRow;\n\n private boolean mShowActions = false;\n\n private boolean mIsScrollable = true;\n\n private boolean mShowLastUpdated = true;\n\n private int mShortcutSize;\n\n private int mMinLargeHeight;\n\n private int mMaxLargeHeight;\n\n private int mActionRowHeight;\n\n private AttributeSet mAttrs;\n\n private int mDefStyleAttr;\n\n private int mDefStyleRes;\n\n private int mThemeTintColor = -1;\n\n private OnSliceActionListener mSliceObserver;\n\n private int mTouchSlopSquared;\n\n private View.OnLongClickListener mLongClickListener;\n\n private View.OnClickListener mOnClickListener;\n\n private int mDownX;\n\n private int mDownY;\n\n private boolean mPressing;\n\n private boolean mInLongpress;\n\n private Handler mHandler;\n\n int[] mClickInfo;\n\n public SliceView(Context context) {\n this(context, null);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, R.attr.sliceViewStyle);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, R.style.Widget_SliceView);\n }\n\n @RequiresApi(21)\n public SliceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n init(context, attrs, defStyleAttr, defStyleRes);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n mAttrs = attrs;\n mDefStyleAttr = defStyleAttr;\n mDefStyleRes = defStyleRes;\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliceView, defStyleAttr, defStyleRes);\n try {\n mThemeTintColor = a.getColor(R.styleable.SliceView_tintColor, -1);\n } finally {\n a.recycle();\n }\n mShortcutSize = getContext().getResources().getDimensionPixelSize(R.dimen.abc_slice_shortcut_size);\n mMinLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_large_height);\n mMaxLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_max_large_height);\n mActionRowHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_action_row_height);\n mCurrentView = new LargeTemplateView(getContext());\n mCurrentView.setMode(getMode());\n addView(mCurrentView, getChildLp(mCurrentView));\n // TODO: action row background should support light / dark / maybe presenter customization\n mActionRow = new ActionRow(getContext(), true);\n mActionRow.setBackground(new ColorDrawable(0xffeeeeee));\n addView(mActionRow, getChildLp(mActionRow));\n final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();\n mTouchSlopSquared = slop * slop;\n mHandler = new Handler();\n super.setOnClickListener(this);\n }\n\n /**\n * Indicates whether this view reacts to click events or not.\n * @hide\n */\n ", "post_mask_code": "\n\n /**\n * Sets the event info for logging a click.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setClickInfo(int[] info) {\n mClickInfo = info;\n }\n\n @Override\n public void onClick(View v) {\n if (mListContent != null && mListContent.getPrimaryAction() != null) {\n try {\n SliceActionImpl sa = new SliceActionImpl(mListContent.getPrimaryAction());\n sa.getAction().send();\n if (mSliceObserver != null && mClickInfo != null && mClickInfo.length > 1) {\n EventInfo eventInfo = new EventInfo(getMode(), EventInfo.ACTION_TYPE_CONTENT, mClickInfo[0], mClickInfo[1]);\n mSliceObserver.onSliceAction(eventInfo, mListContent.getPrimaryAction());\n }\n } catch (PendingIntent.CanceledException e) {\n Log.e(TAG, \"PendingIntent for slice cannot be sent\", e);\n }\n } else if (mOnClickListener != null) {\n mOnClickListener.onClick(this);\n }\n }\n\n @Override\n public void setOnClickListener(View.OnClickListener listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public void setOnLongClickListener(View.OnLongClickListener listener) {\n super.setOnLongClickListener(listener);\n mLongClickListener = listener;\n }\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n boolean ret = super.onInterceptTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n boolean ret = super.onTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n private boolean handleTouchForLongpress(MotionEvent ev) {\n int action = ev.getActionMasked();\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n mHandler.removeCallbacks(mLongpressCheck);\n mDownX = (int) ev.getRawX();\n mDownY = (int) ev.getRawY();\n mPressing = true;\n mInLongpress = false;\n mHandler.postDelayed(mLongpressCheck, ViewConfiguration.getLongPressTimeout());\n break;\n case MotionEvent.ACTION_MOVE:\n final int deltaX = (int) ev.getRawX() - mDownX;\n final int deltaY = (int) ev.getRawY() - mDownY;\n int distance = (deltaX * deltaX) + (deltaY * deltaY);\n if (distance > mTouchSlopSquared) {\n mPressing = false;\n mHandler.removeCallbacks(mLongpressCheck);\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n mPressing = false;\n mInLongpress = false;\n mHandler.removeCallbacks(mLongpressCheck);\n break;\n }\n return mInLongpress;\n }\n\n private int getHeightForMode() {\n int mode = getMode();\n if (mode == MODE_SHORTCUT) {\n return mListContent != null && mListContent.isValid() ? mShortcutSize : 0;\n }\n return mode == MODE_LARGE ? mCurrentView.getActualHeight() : mCurrentView.getSmallHeight();\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int width = MeasureSpec.getSize(widthMeasureSpec);\n int childWidth = MeasureSpec.getSize(widthMeasureSpec);\n if (MODE_SHORTCUT == mMode) {\n // TODO: consider scaling the shortcut to fit if too small\n childWidth = mShortcutSize;\n width = mShortcutSize + getPaddingLeft() + getPaddingRight();\n }\n final int actionHeight = mActionRow.getVisibility() != View.GONE ? mActionRowHeight : 0;\n final int sliceHeight = getHeightForMode();\n final int heightAvailable = MeasureSpec.getSize(heightMeasureSpec);\n final int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n // Remove the padding from our available height\n int height = heightAvailable - getPaddingTop() - getPaddingBottom();\n if (heightAvailable >= sliceHeight + actionHeight || heightMode == MeasureSpec.UNSPECIFIED) {\n // Available space is larger than the slice or we be what we want\n if (heightMode != MeasureSpec.EXACTLY) {\n if (!mIsScrollable) {\n height = Math.min(mMaxLargeHeight, sliceHeight);\n } else {\n // If we want to be bigger than max, then we can be a good scrollable at min\n // large height, if it's not larger lets just use its desired height\n height = sliceHeight > mMaxLargeHeight ? mMinLargeHeight : sliceHeight;\n }\n }\n } else {\n // Not enough space available for slice in current mode\n if (getMode() == MODE_LARGE && heightAvailable >= mMinLargeHeight + actionHeight) {\n // It's just a slice with scrolling content; cap it to height available.\n height = Math.min(mMinLargeHeight, heightAvailable);\n } else if (getMode() == MODE_SHORTCUT) {\n // TODO: consider scaling the shortcut to fit if too small\n height = mShortcutSize;\n }\n }\n int childHeight = height + getPaddingTop() + getPaddingBottom();\n int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);\n int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);\n measureChild(mCurrentView, childWidthMeasureSpec, childHeightMeasureSpec);\n int actionPaddedHeight = actionHeight + getPaddingTop() + getPaddingBottom();\n int actionHeightSpec = MeasureSpec.makeMeasureSpec(actionPaddedHeight, MeasureSpec.EXACTLY);\n measureChild(mActionRow, childWidthMeasureSpec, actionHeightSpec);\n // Total height should include action row and our padding\n height += actionHeight + getPaddingTop() + getPaddingBottom();\n setMeasuredDimension(width, height);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n View v = mCurrentView;\n final int left = getPaddingLeft();\n final int top = getPaddingTop();\n v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight());\n if (mActionRow.getVisibility() != View.GONE) {\n mActionRow.layout(left, top + v.getMeasuredHeight(), left + mActionRow.getMeasuredWidth(), top + v.getMeasuredHeight() + mActionRow.getMeasuredHeight());\n }\n }\n\n @Override\n public void onChanged(@Nullable Slice slice) {\n setSlice(slice);\n }\n\n /**\n * Populates this view to the provided {@link Slice}.\n *\n * This will not update automatically if the slice content changes, for live\n * content see {@link SliceLiveData}.\n */\n public void setSlice(@Nullable Slice slice) {\n if (slice != null) {\n if (mCurrentSlice == null || !mCurrentSlice.getUri().equals(slice.getUri())) {\n mCurrentView.resetView();\n }\n } else {\n // No slice, no actions\n mActions = null;\n }\n mActions = SliceMetadata.getSliceActions(slice);\n mCurrentSlice = slice;\n reinflate();\n }\n\n /**\n * @return the slice being used to populate this view.\n */\n @Nullable\n public Slice getSlice() {\n return mCurrentSlice;\n }\n\n /**\n * Returns the slice actions presented in this view.\n *

\n * Note that these may be different from {@link SliceMetadata#getSliceActions()} if the actions\n * set on the view have been adjusted using {@link #setSliceActions(List)}.\n */\n @Nullable\n public List getSliceActions() {\n return mActions;\n }\n\n /**\n * Sets the slice actions to display for the slice contained in this view. Normally SliceView\n * will automatically show actions, however, it is possible to reorder or omit actions on the\n * view using this method. This is generally discouraged.\n *

\n * It is required that the slice be set on this view before actions can be set, otherwise\n * this will throw {@link IllegalStateException}. If any of the actions supplied are not\n * available for the slice set on this view (i.e. the action is not returned by\n * {@link SliceMetadata#getSliceActions()} this will throw {@link IllegalArgumentException}.\n */\n public void setSliceActions(@Nullable List newActions) {\n // Check that these actions are part of available set\n if (mCurrentSlice == null) {\n throw new IllegalStateException(\"Trying to set actions on a view without a slice\");\n }\n List availableActions = SliceMetadata.getSliceActions(mCurrentSlice);\n if (availableActions != null && newActions != null) {\n for (int i = 0; i < newActions.size(); i++) {\n if (!availableActions.contains(newActions.get(i))) {\n throw new IllegalArgumentException(\"Trying to set an action that isn't available: \" + newActions.get(i));\n }\n }\n }\n mActions = newActions;\n updateActions();\n }\n\n /**\n * Set the mode this view should present in.\n */\n public void setMode(@SliceMode int mode) {\n setMode(mode, false);\n }\n\n /**\n * Set whether this view should allow scrollable content when presenting in {@link #MODE_LARGE}.\n */\n public void setScrollable(boolean isScrollable) {\n mIsScrollable = isScrollable;\n reinflate();\n }\n\n /**\n * Sets the listener to notify when an interaction events occur on the view.\n * @see EventInfo\n */\n public void setOnSliceActionListener(@Nullable OnSliceActionListener observer) {\n mSliceObserver = observer;\n mCurrentView.setSliceActionListener(mSliceObserver);\n }\n\n /**\n * @deprecated TO BE REMOVED; use {@link #setAccentColor(int)} instead.\n */\n @Deprecated\n public void setTint(int tintColor) {\n setAccentColor(tintColor);\n }\n\n /**\n * Contents of a slice such as icons, text, and controls (e.g. toggle) can be tinted. Normally\n * a color for tinting will be provided by the slice. Using this method will override\n * the slice-provided color information and instead tint elements with the color set here.\n *\n * @param accentColor the color to use for tinting contents of this view.\n */\n public void setAccentColor(@ColorInt int accentColor) {\n mThemeTintColor = accentColor;\n mCurrentView.setTint(accentColor);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setMode(@SliceMode int mode, boolean animate) {\n if (animate) {\n Log.e(TAG, \"Animation not supported yet\");\n }\n if (mMode == mode) {\n return;\n }\n mMode = mode;\n reinflate();\n }\n\n /**\n * @return the mode this view is presenting in.\n */\n @SliceMode\n public int getMode() {\n return mMode;\n }\n\n /**\n * @hide\n *\n * Whether this view should show a row of actions with it.\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setShowActionRow(boolean show) {\n mShowActions = show;\n updateActions();\n }\n\n /**\n * @return whether this view is showing a row of actions.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isShowingActionRow() {\n return mShowActions;\n }\n\n private void reinflate() {\n if (mCurrentSlice == null) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n mListContent = new ListContent(getContext(), mCurrentSlice, mAttrs, mDefStyleAttr, mDefStyleRes);\n if (!mListContent.isValid()) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n // TODO: Smarter mapping here from one state to the next.\n int mode = getMode();\n boolean isCurrentViewShortcut = mCurrentView instanceof ShortcutView;\n if (mode == MODE_SHORTCUT && !isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new ShortcutView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n } else if (mode != MODE_SHORTCUT && isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new LargeTemplateView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n }\n mCurrentView.setMode(mode);\n mCurrentView.setSliceActionListener(mSliceObserver);\n if (mCurrentView instanceof LargeTemplateView) {\n ((LargeTemplateView) mCurrentView).setScrollable(mIsScrollable);\n }\n mCurrentView.setStyle(mAttrs, mDefStyleAttr, mDefStyleRes);\n mCurrentView.setTint(getTintColor());\n // Check if the slice content is expired and show when it was last updated\n SliceMetadata sliceMetadata = SliceMetadata.from(getContext(), mCurrentSlice);\n long lastUpdated = sliceMetadata.getLastUpdatedTime();\n long expiry = sliceMetadata.getExpiry();\n long now = System.currentTimeMillis();\n mCurrentView.setLastUpdated(lastUpdated);\n boolean expired = expiry != 0 && expiry != SliceHints.INFINITY && now > expiry;\n mCurrentView.setShowLastUpdated(mShowLastUpdated && expired);\n // Set the slice\n mCurrentView.setSliceContent(mListContent);\n updateActions();\n }\n\n private void updateActions() {\n if (mActions == null || mActions.isEmpty()) {\n // No actions, hide the row, clear out the view\n mActionRow.setVisibility(View.GONE);\n mCurrentView.setSliceActions(null);\n return;\n }\n // TODO: take priority attached to actions into account\n if (mShowActions && mMode != MODE_SHORTCUT && mActions.size() >= 2) {\n // Show in action row if available\n mActionRow.setActions(mActions, getTintColor());\n mActionRow.setVisibility(View.VISIBLE);\n // Hide them on the template\n mCurrentView.setSliceActions(null);\n } else if (mActions.size() > 0) {\n // Otherwise set them on the template\n mCurrentView.setSliceActions(mActions);\n mActionRow.setVisibility(View.GONE);\n }\n }\n\n private int getTintColor() {\n if (mThemeTintColor != -1) {\n // Theme has specified a color, use that\n return mThemeTintColor;\n } else {\n final SliceItem colorItem = SliceQuery.findSubtype(mCurrentSlice, FORMAT_INT, SUBTYPE_COLOR);\n return colorItem != null ? colorItem.getInt() : SliceViewUtil.getColorAccent(getContext());\n }\n }\n\n private LayoutParams getChildLp(View child) {\n if (child instanceof ShortcutView) {\n return new LayoutParams(mShortcutSize, mShortcutSize);\n } else {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n }\n\n /**\n * @return String representation of the provided mode.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public static String modeToString(@SliceMode int mode) {\n switch(mode) {\n case MODE_SHORTCUT:\n return \"MODE SHORTCUT\";\n case MODE_SMALL:\n return \"MODE SMALL\";\n case MODE_LARGE:\n return \"MODE LARGE\";\n default:\n return \"unknown mode: \" + mode;\n }\n }\n\n Runnable mLongpressCheck = new Runnable() {\n\n @Override\n public void run() {\n if (mPressing && mLongClickListener != null) {\n mInLongpress = true;\n mLongClickListener.onLongClick(SliceView.this);\n performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);\n }\n }\n };\n}\n"} {"task_id": "Java_150", "language": "Java", "task_type": "if_statement", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/slice/widget/SliceView.java", "mask_start_position": 18859, "mask_end_position": 18909, "canonical_solution": "if (mMode == mode) {\n return;\n }", "pre_mask_code": "package androidx.slice.widget;\n\nimport static android.app.slice.Slice.SUBTYPE_COLOR;\nimport static android.app.slice.SliceItem.FORMAT_INT;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.HapticFeedbackConstants;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport androidx.annotation.ColorInt;\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.RestrictTo;\nimport androidx.lifecycle.Observer;\nimport androidx.slice.Slice;\nimport androidx.slice.SliceItem;\nimport androidx.slice.SliceMetadata;\nimport androidx.slice.core.SliceActionImpl;\nimport androidx.slice.core.SliceHints;\nimport androidx.slice.core.SliceQuery;\nimport androidx.slice.view.R;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.List;\n\n/**\n * A view for displaying a {@link Slice} which is a piece of app content and actions. SliceView is\n * able to present slice content in a templated format outside of the associated app. The way this\n * content is displayed depends on the structure of the slice, the hints associated with the\n * content, and the mode that SliceView is configured for. The modes that SliceView supports are:\n *

    \n *
  • Shortcut: A shortcut is presented as an icon and a text label representing the main\n * content or action associated with the slice.
  • \n *
  • Small: The small format has a restricted height and can present a single\n * {@link SliceItem} or a limited collection of items.
  • \n *
  • Large: The large format displays multiple small templates in a list, if scrolling is\n * not enabled (see {@link #setScrollable(boolean)}) the view will show as many items as it can\n * comfortably fit.
  • \n *
\n *

\n * When constructing a slice, the contents of it can be annotated with hints, these provide the OS\n * with some information on how the content should be displayed. For example, text annotated with\n * {@link android.app.slice.Slice#HINT_TITLE} would be placed in the title position of a template.\n * A slice annotated with {@link android.app.slice.Slice#HINT_LIST} would present the child items\n * of that slice in a list.\n *

\n * Example usage:\n *\n *

\n * SliceView v = new SliceView(getContext());\n * v.setMode(desiredMode);\n * LiveData liveData = SliceLiveData.fromUri(sliceUri);\n * liveData.observe(lifecycleOwner, v);\n * 
\n * @see SliceLiveData\n */\npublic class SliceView extends ViewGroup implements Observer, View.OnClickListener {\n\n private static final String TAG = \"SliceView\";\n\n /**\n * Implement this interface to be notified of interactions with the slice displayed\n * in this view.\n * @see EventInfo\n */\n public interface OnSliceActionListener {\n\n /**\n * Called when an interaction has occurred with an element in this view.\n * @param info the type of event that occurred.\n * @param item the specific item within the {@link Slice} that was interacted with.\n */\n void onSliceAction(@NonNull EventInfo info, @NonNull SliceItem item);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n @IntDef({ MODE_SMALL, MODE_LARGE, MODE_SHORTCUT })\n @Retention(RetentionPolicy.SOURCE)\n public @interface SliceMode {\n }\n\n /**\n * Mode indicating this slice should be presented in small template format.\n */\n public static final int MODE_SMALL = 1;\n\n /**\n * Mode indicating this slice should be presented in large template format.\n */\n public static final int MODE_LARGE = 2;\n\n /**\n * Mode indicating this slice should be presented as an icon. A shortcut requires an intent,\n * icon, and label. This can be indicated by using {@link android.app.slice.Slice#HINT_TITLE}\n * on an action in a slice.\n */\n public static final int MODE_SHORTCUT = 3;\n\n private int mMode = MODE_LARGE;\n\n private Slice mCurrentSlice;\n\n private ListContent mListContent;\n\n private SliceChildView mCurrentView;\n\n private List mActions;\n\n private ActionRow mActionRow;\n\n private boolean mShowActions = false;\n\n private boolean mIsScrollable = true;\n\n private boolean mShowLastUpdated = true;\n\n private int mShortcutSize;\n\n private int mMinLargeHeight;\n\n private int mMaxLargeHeight;\n\n private int mActionRowHeight;\n\n private AttributeSet mAttrs;\n\n private int mDefStyleAttr;\n\n private int mDefStyleRes;\n\n private int mThemeTintColor = -1;\n\n private OnSliceActionListener mSliceObserver;\n\n private int mTouchSlopSquared;\n\n private View.OnLongClickListener mLongClickListener;\n\n private View.OnClickListener mOnClickListener;\n\n private int mDownX;\n\n private int mDownY;\n\n private boolean mPressing;\n\n private boolean mInLongpress;\n\n private Handler mHandler;\n\n int[] mClickInfo;\n\n public SliceView(Context context) {\n this(context, null);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, R.attr.sliceViewStyle);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, R.style.Widget_SliceView);\n }\n\n @RequiresApi(21)\n public SliceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n init(context, attrs, defStyleAttr, defStyleRes);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n mAttrs = attrs;\n mDefStyleAttr = defStyleAttr;\n mDefStyleRes = defStyleRes;\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliceView, defStyleAttr, defStyleRes);\n try {\n mThemeTintColor = a.getColor(R.styleable.SliceView_tintColor, -1);\n } finally {\n a.recycle();\n }\n mShortcutSize = getContext().getResources().getDimensionPixelSize(R.dimen.abc_slice_shortcut_size);\n mMinLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_large_height);\n mMaxLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_max_large_height);\n mActionRowHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_action_row_height);\n mCurrentView = new LargeTemplateView(getContext());\n mCurrentView.setMode(getMode());\n addView(mCurrentView, getChildLp(mCurrentView));\n // TODO: action row background should support light / dark / maybe presenter customization\n mActionRow = new ActionRow(getContext(), true);\n mActionRow.setBackground(new ColorDrawable(0xffeeeeee));\n addView(mActionRow, getChildLp(mActionRow));\n final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();\n mTouchSlopSquared = slop * slop;\n mHandler = new Handler();\n super.setOnClickListener(this);\n }\n\n /**\n * Indicates whether this view reacts to click events or not.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isSliceViewClickable() {\n return mOnClickListener != null || (mListContent != null && mListContent.getPrimaryAction() != null);\n }\n\n /**\n * Sets the event info for logging a click.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setClickInfo(int[] info) {\n mClickInfo = info;\n }\n\n @Override\n public void onClick(View v) {\n if (mListContent != null && mListContent.getPrimaryAction() != null) {\n try {\n SliceActionImpl sa = new SliceActionImpl(mListContent.getPrimaryAction());\n sa.getAction().send();\n if (mSliceObserver != null && mClickInfo != null && mClickInfo.length > 1) {\n EventInfo eventInfo = new EventInfo(getMode(), EventInfo.ACTION_TYPE_CONTENT, mClickInfo[0], mClickInfo[1]);\n mSliceObserver.onSliceAction(eventInfo, mListContent.getPrimaryAction());\n }\n } catch (PendingIntent.CanceledException e) {\n Log.e(TAG, \"PendingIntent for slice cannot be sent\", e);\n }\n } else if (mOnClickListener != null) {\n mOnClickListener.onClick(this);\n }\n }\n\n @Override\n public void setOnClickListener(View.OnClickListener listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public void setOnLongClickListener(View.OnLongClickListener listener) {\n super.setOnLongClickListener(listener);\n mLongClickListener = listener;\n }\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n boolean ret = super.onInterceptTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n boolean ret = super.onTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n private boolean handleTouchForLongpress(MotionEvent ev) {\n int action = ev.getActionMasked();\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n mHandler.removeCallbacks(mLongpressCheck);\n mDownX = (int) ev.getRawX();\n mDownY = (int) ev.getRawY();\n mPressing = true;\n mInLongpress = false;\n mHandler.postDelayed(mLongpressCheck, ViewConfiguration.getLongPressTimeout());\n break;\n case MotionEvent.ACTION_MOVE:\n final int deltaX = (int) ev.getRawX() - mDownX;\n final int deltaY = (int) ev.getRawY() - mDownY;\n int distance = (deltaX * deltaX) + (deltaY * deltaY);\n if (distance > mTouchSlopSquared) {\n mPressing = false;\n mHandler.removeCallbacks(mLongpressCheck);\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n mPressing = false;\n mInLongpress = false;\n mHandler.removeCallbacks(mLongpressCheck);\n break;\n }\n return mInLongpress;\n }\n\n private int getHeightForMode() {\n int mode = getMode();\n if (mode == MODE_SHORTCUT) {\n return mListContent != null && mListContent.isValid() ? mShortcutSize : 0;\n }\n return mode == MODE_LARGE ? mCurrentView.getActualHeight() : mCurrentView.getSmallHeight();\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int width = MeasureSpec.getSize(widthMeasureSpec);\n int childWidth = MeasureSpec.getSize(widthMeasureSpec);\n if (MODE_SHORTCUT == mMode) {\n // TODO: consider scaling the shortcut to fit if too small\n childWidth = mShortcutSize;\n width = mShortcutSize + getPaddingLeft() + getPaddingRight();\n }\n final int actionHeight = mActionRow.getVisibility() != View.GONE ? mActionRowHeight : 0;\n final int sliceHeight = getHeightForMode();\n final int heightAvailable = MeasureSpec.getSize(heightMeasureSpec);\n final int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n // Remove the padding from our available height\n int height = heightAvailable - getPaddingTop() - getPaddingBottom();\n if (heightAvailable >= sliceHeight + actionHeight || heightMode == MeasureSpec.UNSPECIFIED) {\n // Available space is larger than the slice or we be what we want\n if (heightMode != MeasureSpec.EXACTLY) {\n if (!mIsScrollable) {\n height = Math.min(mMaxLargeHeight, sliceHeight);\n } else {\n // If we want to be bigger than max, then we can be a good scrollable at min\n // large height, if it's not larger lets just use its desired height\n height = sliceHeight > mMaxLargeHeight ? mMinLargeHeight : sliceHeight;\n }\n }\n } else {\n // Not enough space available for slice in current mode\n if (getMode() == MODE_LARGE && heightAvailable >= mMinLargeHeight + actionHeight) {\n // It's just a slice with scrolling content; cap it to height available.\n height = Math.min(mMinLargeHeight, heightAvailable);\n } else if (getMode() == MODE_SHORTCUT) {\n // TODO: consider scaling the shortcut to fit if too small\n height = mShortcutSize;\n }\n }\n int childHeight = height + getPaddingTop() + getPaddingBottom();\n int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);\n int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);\n measureChild(mCurrentView, childWidthMeasureSpec, childHeightMeasureSpec);\n int actionPaddedHeight = actionHeight + getPaddingTop() + getPaddingBottom();\n int actionHeightSpec = MeasureSpec.makeMeasureSpec(actionPaddedHeight, MeasureSpec.EXACTLY);\n measureChild(mActionRow, childWidthMeasureSpec, actionHeightSpec);\n // Total height should include action row and our padding\n height += actionHeight + getPaddingTop() + getPaddingBottom();\n setMeasuredDimension(width, height);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n View v = mCurrentView;\n final int left = getPaddingLeft();\n final int top = getPaddingTop();\n v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight());\n if (mActionRow.getVisibility() != View.GONE) {\n mActionRow.layout(left, top + v.getMeasuredHeight(), left + mActionRow.getMeasuredWidth(), top + v.getMeasuredHeight() + mActionRow.getMeasuredHeight());\n }\n }\n\n @Override\n public void onChanged(@Nullable Slice slice) {\n setSlice(slice);\n }\n\n /**\n * Populates this view to the provided {@link Slice}.\n *\n * This will not update automatically if the slice content changes, for live\n * content see {@link SliceLiveData}.\n */\n public void setSlice(@Nullable Slice slice) {\n if (slice != null) {\n if (mCurrentSlice == null || !mCurrentSlice.getUri().equals(slice.getUri())) {\n mCurrentView.resetView();\n }\n } else {\n // No slice, no actions\n mActions = null;\n }\n mActions = SliceMetadata.getSliceActions(slice);\n mCurrentSlice = slice;\n reinflate();\n }\n\n /**\n * @return the slice being used to populate this view.\n */\n @Nullable\n public Slice getSlice() {\n return mCurrentSlice;\n }\n\n /**\n * Returns the slice actions presented in this view.\n *

\n * Note that these may be different from {@link SliceMetadata#getSliceActions()} if the actions\n * set on the view have been adjusted using {@link #setSliceActions(List)}.\n */\n @Nullable\n public List getSliceActions() {\n return mActions;\n }\n\n /**\n * Sets the slice actions to display for the slice contained in this view. Normally SliceView\n * will automatically show actions, however, it is possible to reorder or omit actions on the\n * view using this method. This is generally discouraged.\n *

\n * It is required that the slice be set on this view before actions can be set, otherwise\n * this will throw {@link IllegalStateException}. If any of the actions supplied are not\n * available for the slice set on this view (i.e. the action is not returned by\n * {@link SliceMetadata#getSliceActions()} this will throw {@link IllegalArgumentException}.\n */\n public void setSliceActions(@Nullable List newActions) {\n // Check that these actions are part of available set\n if (mCurrentSlice == null) {\n throw new IllegalStateException(\"Trying to set actions on a view without a slice\");\n }\n List availableActions = SliceMetadata.getSliceActions(mCurrentSlice);\n if (availableActions != null && newActions != null) {\n for (int i = 0; i < newActions.size(); i++) {\n if (!availableActions.contains(newActions.get(i))) {\n throw new IllegalArgumentException(\"Trying to set an action that isn't available: \" + newActions.get(i));\n }\n }\n }\n mActions = newActions;\n updateActions();\n }\n\n /**\n * Set the mode this view should present in.\n */\n public void setMode(@SliceMode int mode) {\n setMode(mode, false);\n }\n\n /**\n * Set whether this view should allow scrollable content when presenting in {@link #MODE_LARGE}.\n */\n public void setScrollable(boolean isScrollable) {\n mIsScrollable = isScrollable;\n reinflate();\n }\n\n /**\n * Sets the listener to notify when an interaction events occur on the view.\n * @see EventInfo\n */\n public void setOnSliceActionListener(@Nullable OnSliceActionListener observer) {\n mSliceObserver = observer;\n mCurrentView.setSliceActionListener(mSliceObserver);\n }\n\n /**\n * @deprecated TO BE REMOVED; use {@link #setAccentColor(int)} instead.\n */\n @Deprecated\n public void setTint(int tintColor) {\n setAccentColor(tintColor);\n }\n\n /**\n * Contents of a slice such as icons, text, and controls (e.g. toggle) can be tinted. Normally\n * a color for tinting will be provided by the slice. Using this method will override\n * the slice-provided color information and instead tint elements with the color set here.\n *\n * @param accentColor the color to use for tinting contents of this view.\n */\n public void setAccentColor(@ColorInt int accentColor) {\n mThemeTintColor = accentColor;\n mCurrentView.setTint(accentColor);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setMode(@SliceMode int mode, boolean animate) {\n if (animate) {\n Log.e(TAG, \"Animation not supported yet\");\n }\n ", "post_mask_code": "\n mMode = mode;\n reinflate();\n }\n\n /**\n * @return the mode this view is presenting in.\n */\n @SliceMode\n public int getMode() {\n return mMode;\n }\n\n /**\n * @hide\n *\n * Whether this view should show a row of actions with it.\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setShowActionRow(boolean show) {\n mShowActions = show;\n updateActions();\n }\n\n /**\n * @return whether this view is showing a row of actions.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isShowingActionRow() {\n return mShowActions;\n }\n\n private void reinflate() {\n if (mCurrentSlice == null) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n mListContent = new ListContent(getContext(), mCurrentSlice, mAttrs, mDefStyleAttr, mDefStyleRes);\n if (!mListContent.isValid()) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n // TODO: Smarter mapping here from one state to the next.\n int mode = getMode();\n boolean isCurrentViewShortcut = mCurrentView instanceof ShortcutView;\n if (mode == MODE_SHORTCUT && !isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new ShortcutView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n } else if (mode != MODE_SHORTCUT && isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new LargeTemplateView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n }\n mCurrentView.setMode(mode);\n mCurrentView.setSliceActionListener(mSliceObserver);\n if (mCurrentView instanceof LargeTemplateView) {\n ((LargeTemplateView) mCurrentView).setScrollable(mIsScrollable);\n }\n mCurrentView.setStyle(mAttrs, mDefStyleAttr, mDefStyleRes);\n mCurrentView.setTint(getTintColor());\n // Check if the slice content is expired and show when it was last updated\n SliceMetadata sliceMetadata = SliceMetadata.from(getContext(), mCurrentSlice);\n long lastUpdated = sliceMetadata.getLastUpdatedTime();\n long expiry = sliceMetadata.getExpiry();\n long now = System.currentTimeMillis();\n mCurrentView.setLastUpdated(lastUpdated);\n boolean expired = expiry != 0 && expiry != SliceHints.INFINITY && now > expiry;\n mCurrentView.setShowLastUpdated(mShowLastUpdated && expired);\n // Set the slice\n mCurrentView.setSliceContent(mListContent);\n updateActions();\n }\n\n private void updateActions() {\n if (mActions == null || mActions.isEmpty()) {\n // No actions, hide the row, clear out the view\n mActionRow.setVisibility(View.GONE);\n mCurrentView.setSliceActions(null);\n return;\n }\n // TODO: take priority attached to actions into account\n if (mShowActions && mMode != MODE_SHORTCUT && mActions.size() >= 2) {\n // Show in action row if available\n mActionRow.setActions(mActions, getTintColor());\n mActionRow.setVisibility(View.VISIBLE);\n // Hide them on the template\n mCurrentView.setSliceActions(null);\n } else if (mActions.size() > 0) {\n // Otherwise set them on the template\n mCurrentView.setSliceActions(mActions);\n mActionRow.setVisibility(View.GONE);\n }\n }\n\n private int getTintColor() {\n if (mThemeTintColor != -1) {\n // Theme has specified a color, use that\n return mThemeTintColor;\n } else {\n final SliceItem colorItem = SliceQuery.findSubtype(mCurrentSlice, FORMAT_INT, SUBTYPE_COLOR);\n return colorItem != null ? colorItem.getInt() : SliceViewUtil.getColorAccent(getContext());\n }\n }\n\n private LayoutParams getChildLp(View child) {\n if (child instanceof ShortcutView) {\n return new LayoutParams(mShortcutSize, mShortcutSize);\n } else {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n }\n\n /**\n * @return String representation of the provided mode.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public static String modeToString(@SliceMode int mode) {\n switch(mode) {\n case MODE_SHORTCUT:\n return \"MODE SHORTCUT\";\n case MODE_SMALL:\n return \"MODE SMALL\";\n case MODE_LARGE:\n return \"MODE LARGE\";\n default:\n return \"unknown mode: \" + mode;\n }\n }\n\n Runnable mLongpressCheck = new Runnable() {\n\n @Override\n public void run() {\n if (mPressing && mLongClickListener != null) {\n mInLongpress = true;\n mLongClickListener.onLongClick(SliceView.this);\n performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);\n }\n }\n };\n}\n"} {"task_id": "Java_151", "language": "Java", "task_type": "switch_case", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/slice/widget/SliceView.java", "mask_start_position": 23356, "mask_end_position": 23653, "canonical_solution": "switch(mode) {\n case MODE_SHORTCUT:\n return \"MODE SHORTCUT\";\n case MODE_SMALL:\n return \"MODE SMALL\";\n case MODE_LARGE:\n return \"MODE LARGE\";\n default:\n return \"unknown mode: \" + mode;\n }", "pre_mask_code": "package androidx.slice.widget;\n\nimport static android.app.slice.Slice.SUBTYPE_COLOR;\nimport static android.app.slice.SliceItem.FORMAT_INT;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.HapticFeedbackConstants;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport androidx.annotation.ColorInt;\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.RestrictTo;\nimport androidx.lifecycle.Observer;\nimport androidx.slice.Slice;\nimport androidx.slice.SliceItem;\nimport androidx.slice.SliceMetadata;\nimport androidx.slice.core.SliceActionImpl;\nimport androidx.slice.core.SliceHints;\nimport androidx.slice.core.SliceQuery;\nimport androidx.slice.view.R;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.List;\n\n/**\n * A view for displaying a {@link Slice} which is a piece of app content and actions. SliceView is\n * able to present slice content in a templated format outside of the associated app. The way this\n * content is displayed depends on the structure of the slice, the hints associated with the\n * content, and the mode that SliceView is configured for. The modes that SliceView supports are:\n *

    \n *
  • Shortcut: A shortcut is presented as an icon and a text label representing the main\n * content or action associated with the slice.
  • \n *
  • Small: The small format has a restricted height and can present a single\n * {@link SliceItem} or a limited collection of items.
  • \n *
  • Large: The large format displays multiple small templates in a list, if scrolling is\n * not enabled (see {@link #setScrollable(boolean)}) the view will show as many items as it can\n * comfortably fit.
  • \n *
\n *

\n * When constructing a slice, the contents of it can be annotated with hints, these provide the OS\n * with some information on how the content should be displayed. For example, text annotated with\n * {@link android.app.slice.Slice#HINT_TITLE} would be placed in the title position of a template.\n * A slice annotated with {@link android.app.slice.Slice#HINT_LIST} would present the child items\n * of that slice in a list.\n *

\n * Example usage:\n *\n *

\n * SliceView v = new SliceView(getContext());\n * v.setMode(desiredMode);\n * LiveData liveData = SliceLiveData.fromUri(sliceUri);\n * liveData.observe(lifecycleOwner, v);\n * 
\n * @see SliceLiveData\n */\npublic class SliceView extends ViewGroup implements Observer, View.OnClickListener {\n\n private static final String TAG = \"SliceView\";\n\n /**\n * Implement this interface to be notified of interactions with the slice displayed\n * in this view.\n * @see EventInfo\n */\n public interface OnSliceActionListener {\n\n /**\n * Called when an interaction has occurred with an element in this view.\n * @param info the type of event that occurred.\n * @param item the specific item within the {@link Slice} that was interacted with.\n */\n void onSliceAction(@NonNull EventInfo info, @NonNull SliceItem item);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n @IntDef({ MODE_SMALL, MODE_LARGE, MODE_SHORTCUT })\n @Retention(RetentionPolicy.SOURCE)\n public @interface SliceMode {\n }\n\n /**\n * Mode indicating this slice should be presented in small template format.\n */\n public static final int MODE_SMALL = 1;\n\n /**\n * Mode indicating this slice should be presented in large template format.\n */\n public static final int MODE_LARGE = 2;\n\n /**\n * Mode indicating this slice should be presented as an icon. A shortcut requires an intent,\n * icon, and label. This can be indicated by using {@link android.app.slice.Slice#HINT_TITLE}\n * on an action in a slice.\n */\n public static final int MODE_SHORTCUT = 3;\n\n private int mMode = MODE_LARGE;\n\n private Slice mCurrentSlice;\n\n private ListContent mListContent;\n\n private SliceChildView mCurrentView;\n\n private List mActions;\n\n private ActionRow mActionRow;\n\n private boolean mShowActions = false;\n\n private boolean mIsScrollable = true;\n\n private boolean mShowLastUpdated = true;\n\n private int mShortcutSize;\n\n private int mMinLargeHeight;\n\n private int mMaxLargeHeight;\n\n private int mActionRowHeight;\n\n private AttributeSet mAttrs;\n\n private int mDefStyleAttr;\n\n private int mDefStyleRes;\n\n private int mThemeTintColor = -1;\n\n private OnSliceActionListener mSliceObserver;\n\n private int mTouchSlopSquared;\n\n private View.OnLongClickListener mLongClickListener;\n\n private View.OnClickListener mOnClickListener;\n\n private int mDownX;\n\n private int mDownY;\n\n private boolean mPressing;\n\n private boolean mInLongpress;\n\n private Handler mHandler;\n\n int[] mClickInfo;\n\n public SliceView(Context context) {\n this(context, null);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, R.attr.sliceViewStyle);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, R.style.Widget_SliceView);\n }\n\n @RequiresApi(21)\n public SliceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n init(context, attrs, defStyleAttr, defStyleRes);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n mAttrs = attrs;\n mDefStyleAttr = defStyleAttr;\n mDefStyleRes = defStyleRes;\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliceView, defStyleAttr, defStyleRes);\n try {\n mThemeTintColor = a.getColor(R.styleable.SliceView_tintColor, -1);\n } finally {\n a.recycle();\n }\n mShortcutSize = getContext().getResources().getDimensionPixelSize(R.dimen.abc_slice_shortcut_size);\n mMinLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_large_height);\n mMaxLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_max_large_height);\n mActionRowHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_action_row_height);\n mCurrentView = new LargeTemplateView(getContext());\n mCurrentView.setMode(getMode());\n addView(mCurrentView, getChildLp(mCurrentView));\n // TODO: action row background should support light / dark / maybe presenter customization\n mActionRow = new ActionRow(getContext(), true);\n mActionRow.setBackground(new ColorDrawable(0xffeeeeee));\n addView(mActionRow, getChildLp(mActionRow));\n final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();\n mTouchSlopSquared = slop * slop;\n mHandler = new Handler();\n super.setOnClickListener(this);\n }\n\n /**\n * Indicates whether this view reacts to click events or not.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isSliceViewClickable() {\n return mOnClickListener != null || (mListContent != null && mListContent.getPrimaryAction() != null);\n }\n\n /**\n * Sets the event info for logging a click.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setClickInfo(int[] info) {\n mClickInfo = info;\n }\n\n @Override\n public void onClick(View v) {\n if (mListContent != null && mListContent.getPrimaryAction() != null) {\n try {\n SliceActionImpl sa = new SliceActionImpl(mListContent.getPrimaryAction());\n sa.getAction().send();\n if (mSliceObserver != null && mClickInfo != null && mClickInfo.length > 1) {\n EventInfo eventInfo = new EventInfo(getMode(), EventInfo.ACTION_TYPE_CONTENT, mClickInfo[0], mClickInfo[1]);\n mSliceObserver.onSliceAction(eventInfo, mListContent.getPrimaryAction());\n }\n } catch (PendingIntent.CanceledException e) {\n Log.e(TAG, \"PendingIntent for slice cannot be sent\", e);\n }\n } else if (mOnClickListener != null) {\n mOnClickListener.onClick(this);\n }\n }\n\n @Override\n public void setOnClickListener(View.OnClickListener listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public void setOnLongClickListener(View.OnLongClickListener listener) {\n super.setOnLongClickListener(listener);\n mLongClickListener = listener;\n }\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n boolean ret = super.onInterceptTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n boolean ret = super.onTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n private boolean handleTouchForLongpress(MotionEvent ev) {\n int action = ev.getActionMasked();\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n mHandler.removeCallbacks(mLongpressCheck);\n mDownX = (int) ev.getRawX();\n mDownY = (int) ev.getRawY();\n mPressing = true;\n mInLongpress = false;\n mHandler.postDelayed(mLongpressCheck, ViewConfiguration.getLongPressTimeout());\n break;\n case MotionEvent.ACTION_MOVE:\n final int deltaX = (int) ev.getRawX() - mDownX;\n final int deltaY = (int) ev.getRawY() - mDownY;\n int distance = (deltaX * deltaX) + (deltaY * deltaY);\n if (distance > mTouchSlopSquared) {\n mPressing = false;\n mHandler.removeCallbacks(mLongpressCheck);\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n mPressing = false;\n mInLongpress = false;\n mHandler.removeCallbacks(mLongpressCheck);\n break;\n }\n return mInLongpress;\n }\n\n private int getHeightForMode() {\n int mode = getMode();\n if (mode == MODE_SHORTCUT) {\n return mListContent != null && mListContent.isValid() ? mShortcutSize : 0;\n }\n return mode == MODE_LARGE ? mCurrentView.getActualHeight() : mCurrentView.getSmallHeight();\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int width = MeasureSpec.getSize(widthMeasureSpec);\n int childWidth = MeasureSpec.getSize(widthMeasureSpec);\n if (MODE_SHORTCUT == mMode) {\n // TODO: consider scaling the shortcut to fit if too small\n childWidth = mShortcutSize;\n width = mShortcutSize + getPaddingLeft() + getPaddingRight();\n }\n final int actionHeight = mActionRow.getVisibility() != View.GONE ? mActionRowHeight : 0;\n final int sliceHeight = getHeightForMode();\n final int heightAvailable = MeasureSpec.getSize(heightMeasureSpec);\n final int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n // Remove the padding from our available height\n int height = heightAvailable - getPaddingTop() - getPaddingBottom();\n if (heightAvailable >= sliceHeight + actionHeight || heightMode == MeasureSpec.UNSPECIFIED) {\n // Available space is larger than the slice or we be what we want\n if (heightMode != MeasureSpec.EXACTLY) {\n if (!mIsScrollable) {\n height = Math.min(mMaxLargeHeight, sliceHeight);\n } else {\n // If we want to be bigger than max, then we can be a good scrollable at min\n // large height, if it's not larger lets just use its desired height\n height = sliceHeight > mMaxLargeHeight ? mMinLargeHeight : sliceHeight;\n }\n }\n } else {\n // Not enough space available for slice in current mode\n if (getMode() == MODE_LARGE && heightAvailable >= mMinLargeHeight + actionHeight) {\n // It's just a slice with scrolling content; cap it to height available.\n height = Math.min(mMinLargeHeight, heightAvailable);\n } else if (getMode() == MODE_SHORTCUT) {\n // TODO: consider scaling the shortcut to fit if too small\n height = mShortcutSize;\n }\n }\n int childHeight = height + getPaddingTop() + getPaddingBottom();\n int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);\n int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);\n measureChild(mCurrentView, childWidthMeasureSpec, childHeightMeasureSpec);\n int actionPaddedHeight = actionHeight + getPaddingTop() + getPaddingBottom();\n int actionHeightSpec = MeasureSpec.makeMeasureSpec(actionPaddedHeight, MeasureSpec.EXACTLY);\n measureChild(mActionRow, childWidthMeasureSpec, actionHeightSpec);\n // Total height should include action row and our padding\n height += actionHeight + getPaddingTop() + getPaddingBottom();\n setMeasuredDimension(width, height);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n View v = mCurrentView;\n final int left = getPaddingLeft();\n final int top = getPaddingTop();\n v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight());\n if (mActionRow.getVisibility() != View.GONE) {\n mActionRow.layout(left, top + v.getMeasuredHeight(), left + mActionRow.getMeasuredWidth(), top + v.getMeasuredHeight() + mActionRow.getMeasuredHeight());\n }\n }\n\n @Override\n public void onChanged(@Nullable Slice slice) {\n setSlice(slice);\n }\n\n /**\n * Populates this view to the provided {@link Slice}.\n *\n * This will not update automatically if the slice content changes, for live\n * content see {@link SliceLiveData}.\n */\n public void setSlice(@Nullable Slice slice) {\n if (slice != null) {\n if (mCurrentSlice == null || !mCurrentSlice.getUri().equals(slice.getUri())) {\n mCurrentView.resetView();\n }\n } else {\n // No slice, no actions\n mActions = null;\n }\n mActions = SliceMetadata.getSliceActions(slice);\n mCurrentSlice = slice;\n reinflate();\n }\n\n /**\n * @return the slice being used to populate this view.\n */\n @Nullable\n public Slice getSlice() {\n return mCurrentSlice;\n }\n\n /**\n * Returns the slice actions presented in this view.\n *

\n * Note that these may be different from {@link SliceMetadata#getSliceActions()} if the actions\n * set on the view have been adjusted using {@link #setSliceActions(List)}.\n */\n @Nullable\n public List getSliceActions() {\n return mActions;\n }\n\n /**\n * Sets the slice actions to display for the slice contained in this view. Normally SliceView\n * will automatically show actions, however, it is possible to reorder or omit actions on the\n * view using this method. This is generally discouraged.\n *

\n * It is required that the slice be set on this view before actions can be set, otherwise\n * this will throw {@link IllegalStateException}. If any of the actions supplied are not\n * available for the slice set on this view (i.e. the action is not returned by\n * {@link SliceMetadata#getSliceActions()} this will throw {@link IllegalArgumentException}.\n */\n public void setSliceActions(@Nullable List newActions) {\n // Check that these actions are part of available set\n if (mCurrentSlice == null) {\n throw new IllegalStateException(\"Trying to set actions on a view without a slice\");\n }\n List availableActions = SliceMetadata.getSliceActions(mCurrentSlice);\n if (availableActions != null && newActions != null) {\n for (int i = 0; i < newActions.size(); i++) {\n if (!availableActions.contains(newActions.get(i))) {\n throw new IllegalArgumentException(\"Trying to set an action that isn't available: \" + newActions.get(i));\n }\n }\n }\n mActions = newActions;\n updateActions();\n }\n\n /**\n * Set the mode this view should present in.\n */\n public void setMode(@SliceMode int mode) {\n setMode(mode, false);\n }\n\n /**\n * Set whether this view should allow scrollable content when presenting in {@link #MODE_LARGE}.\n */\n public void setScrollable(boolean isScrollable) {\n mIsScrollable = isScrollable;\n reinflate();\n }\n\n /**\n * Sets the listener to notify when an interaction events occur on the view.\n * @see EventInfo\n */\n public void setOnSliceActionListener(@Nullable OnSliceActionListener observer) {\n mSliceObserver = observer;\n mCurrentView.setSliceActionListener(mSliceObserver);\n }\n\n /**\n * @deprecated TO BE REMOVED; use {@link #setAccentColor(int)} instead.\n */\n @Deprecated\n public void setTint(int tintColor) {\n setAccentColor(tintColor);\n }\n\n /**\n * Contents of a slice such as icons, text, and controls (e.g. toggle) can be tinted. Normally\n * a color for tinting will be provided by the slice. Using this method will override\n * the slice-provided color information and instead tint elements with the color set here.\n *\n * @param accentColor the color to use for tinting contents of this view.\n */\n public void setAccentColor(@ColorInt int accentColor) {\n mThemeTintColor = accentColor;\n mCurrentView.setTint(accentColor);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setMode(@SliceMode int mode, boolean animate) {\n if (animate) {\n Log.e(TAG, \"Animation not supported yet\");\n }\n if (mMode == mode) {\n return;\n }\n mMode = mode;\n reinflate();\n }\n\n /**\n * @return the mode this view is presenting in.\n */\n @SliceMode\n public int getMode() {\n return mMode;\n }\n\n /**\n * @hide\n *\n * Whether this view should show a row of actions with it.\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setShowActionRow(boolean show) {\n mShowActions = show;\n updateActions();\n }\n\n /**\n * @return whether this view is showing a row of actions.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isShowingActionRow() {\n return mShowActions;\n }\n\n private void reinflate() {\n if (mCurrentSlice == null) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n mListContent = new ListContent(getContext(), mCurrentSlice, mAttrs, mDefStyleAttr, mDefStyleRes);\n if (!mListContent.isValid()) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n // TODO: Smarter mapping here from one state to the next.\n int mode = getMode();\n boolean isCurrentViewShortcut = mCurrentView instanceof ShortcutView;\n if (mode == MODE_SHORTCUT && !isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new ShortcutView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n } else if (mode != MODE_SHORTCUT && isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new LargeTemplateView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n }\n mCurrentView.setMode(mode);\n mCurrentView.setSliceActionListener(mSliceObserver);\n if (mCurrentView instanceof LargeTemplateView) {\n ((LargeTemplateView) mCurrentView).setScrollable(mIsScrollable);\n }\n mCurrentView.setStyle(mAttrs, mDefStyleAttr, mDefStyleRes);\n mCurrentView.setTint(getTintColor());\n // Check if the slice content is expired and show when it was last updated\n SliceMetadata sliceMetadata = SliceMetadata.from(getContext(), mCurrentSlice);\n long lastUpdated = sliceMetadata.getLastUpdatedTime();\n long expiry = sliceMetadata.getExpiry();\n long now = System.currentTimeMillis();\n mCurrentView.setLastUpdated(lastUpdated);\n boolean expired = expiry != 0 && expiry != SliceHints.INFINITY && now > expiry;\n mCurrentView.setShowLastUpdated(mShowLastUpdated && expired);\n // Set the slice\n mCurrentView.setSliceContent(mListContent);\n updateActions();\n }\n\n private void updateActions() {\n if (mActions == null || mActions.isEmpty()) {\n // No actions, hide the row, clear out the view\n mActionRow.setVisibility(View.GONE);\n mCurrentView.setSliceActions(null);\n return;\n }\n // TODO: take priority attached to actions into account\n if (mShowActions && mMode != MODE_SHORTCUT && mActions.size() >= 2) {\n // Show in action row if available\n mActionRow.setActions(mActions, getTintColor());\n mActionRow.setVisibility(View.VISIBLE);\n // Hide them on the template\n mCurrentView.setSliceActions(null);\n } else if (mActions.size() > 0) {\n // Otherwise set them on the template\n mCurrentView.setSliceActions(mActions);\n mActionRow.setVisibility(View.GONE);\n }\n }\n\n private int getTintColor() {\n if (mThemeTintColor != -1) {\n // Theme has specified a color, use that\n return mThemeTintColor;\n } else {\n final SliceItem colorItem = SliceQuery.findSubtype(mCurrentSlice, FORMAT_INT, SUBTYPE_COLOR);\n return colorItem != null ? colorItem.getInt() : SliceViewUtil.getColorAccent(getContext());\n }\n }\n\n private LayoutParams getChildLp(View child) {\n if (child instanceof ShortcutView) {\n return new LayoutParams(mShortcutSize, mShortcutSize);\n } else {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n }\n\n /**\n * @return String representation of the provided mode.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public static String modeToString(@SliceMode int mode) {\n ", "post_mask_code": "\n }\n\n Runnable mLongpressCheck = new Runnable() {\n\n @Override\n public void run() {\n if (mPressing && mLongClickListener != null) {\n mInLongpress = true;\n mLongClickListener.onLongClick(SliceView.this);\n performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);\n }\n }\n };\n}\n"} {"task_id": "Java_152", "language": "Java", "task_type": "for_statement", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/slice/widget/SliceView.java", "mask_start_position": 16864, "mask_end_position": 17136, "canonical_solution": "for (int i = 0; i < newActions.size(); i++) {\n if (!availableActions.contains(newActions.get(i))) {\n throw new IllegalArgumentException(\"Trying to set an action that isn't available: \" + newActions.get(i));\n }\n }", "pre_mask_code": "package androidx.slice.widget;\n\nimport static android.app.slice.Slice.SUBTYPE_COLOR;\nimport static android.app.slice.SliceItem.FORMAT_INT;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.HapticFeedbackConstants;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport androidx.annotation.ColorInt;\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.RestrictTo;\nimport androidx.lifecycle.Observer;\nimport androidx.slice.Slice;\nimport androidx.slice.SliceItem;\nimport androidx.slice.SliceMetadata;\nimport androidx.slice.core.SliceActionImpl;\nimport androidx.slice.core.SliceHints;\nimport androidx.slice.core.SliceQuery;\nimport androidx.slice.view.R;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.List;\n\n/**\n * A view for displaying a {@link Slice} which is a piece of app content and actions. SliceView is\n * able to present slice content in a templated format outside of the associated app. The way this\n * content is displayed depends on the structure of the slice, the hints associated with the\n * content, and the mode that SliceView is configured for. The modes that SliceView supports are:\n *

    \n *
  • Shortcut: A shortcut is presented as an icon and a text label representing the main\n * content or action associated with the slice.
  • \n *
  • Small: The small format has a restricted height and can present a single\n * {@link SliceItem} or a limited collection of items.
  • \n *
  • Large: The large format displays multiple small templates in a list, if scrolling is\n * not enabled (see {@link #setScrollable(boolean)}) the view will show as many items as it can\n * comfortably fit.
  • \n *
\n *

\n * When constructing a slice, the contents of it can be annotated with hints, these provide the OS\n * with some information on how the content should be displayed. For example, text annotated with\n * {@link android.app.slice.Slice#HINT_TITLE} would be placed in the title position of a template.\n * A slice annotated with {@link android.app.slice.Slice#HINT_LIST} would present the child items\n * of that slice in a list.\n *

\n * Example usage:\n *\n *

\n * SliceView v = new SliceView(getContext());\n * v.setMode(desiredMode);\n * LiveData liveData = SliceLiveData.fromUri(sliceUri);\n * liveData.observe(lifecycleOwner, v);\n * 
\n * @see SliceLiveData\n */\npublic class SliceView extends ViewGroup implements Observer, View.OnClickListener {\n\n private static final String TAG = \"SliceView\";\n\n /**\n * Implement this interface to be notified of interactions with the slice displayed\n * in this view.\n * @see EventInfo\n */\n public interface OnSliceActionListener {\n\n /**\n * Called when an interaction has occurred with an element in this view.\n * @param info the type of event that occurred.\n * @param item the specific item within the {@link Slice} that was interacted with.\n */\n void onSliceAction(@NonNull EventInfo info, @NonNull SliceItem item);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n @IntDef({ MODE_SMALL, MODE_LARGE, MODE_SHORTCUT })\n @Retention(RetentionPolicy.SOURCE)\n public @interface SliceMode {\n }\n\n /**\n * Mode indicating this slice should be presented in small template format.\n */\n public static final int MODE_SMALL = 1;\n\n /**\n * Mode indicating this slice should be presented in large template format.\n */\n public static final int MODE_LARGE = 2;\n\n /**\n * Mode indicating this slice should be presented as an icon. A shortcut requires an intent,\n * icon, and label. This can be indicated by using {@link android.app.slice.Slice#HINT_TITLE}\n * on an action in a slice.\n */\n public static final int MODE_SHORTCUT = 3;\n\n private int mMode = MODE_LARGE;\n\n private Slice mCurrentSlice;\n\n private ListContent mListContent;\n\n private SliceChildView mCurrentView;\n\n private List mActions;\n\n private ActionRow mActionRow;\n\n private boolean mShowActions = false;\n\n private boolean mIsScrollable = true;\n\n private boolean mShowLastUpdated = true;\n\n private int mShortcutSize;\n\n private int mMinLargeHeight;\n\n private int mMaxLargeHeight;\n\n private int mActionRowHeight;\n\n private AttributeSet mAttrs;\n\n private int mDefStyleAttr;\n\n private int mDefStyleRes;\n\n private int mThemeTintColor = -1;\n\n private OnSliceActionListener mSliceObserver;\n\n private int mTouchSlopSquared;\n\n private View.OnLongClickListener mLongClickListener;\n\n private View.OnClickListener mOnClickListener;\n\n private int mDownX;\n\n private int mDownY;\n\n private boolean mPressing;\n\n private boolean mInLongpress;\n\n private Handler mHandler;\n\n int[] mClickInfo;\n\n public SliceView(Context context) {\n this(context, null);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, R.attr.sliceViewStyle);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, R.style.Widget_SliceView);\n }\n\n @RequiresApi(21)\n public SliceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n init(context, attrs, defStyleAttr, defStyleRes);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n mAttrs = attrs;\n mDefStyleAttr = defStyleAttr;\n mDefStyleRes = defStyleRes;\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliceView, defStyleAttr, defStyleRes);\n try {\n mThemeTintColor = a.getColor(R.styleable.SliceView_tintColor, -1);\n } finally {\n a.recycle();\n }\n mShortcutSize = getContext().getResources().getDimensionPixelSize(R.dimen.abc_slice_shortcut_size);\n mMinLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_large_height);\n mMaxLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_max_large_height);\n mActionRowHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_action_row_height);\n mCurrentView = new LargeTemplateView(getContext());\n mCurrentView.setMode(getMode());\n addView(mCurrentView, getChildLp(mCurrentView));\n // TODO: action row background should support light / dark / maybe presenter customization\n mActionRow = new ActionRow(getContext(), true);\n mActionRow.setBackground(new ColorDrawable(0xffeeeeee));\n addView(mActionRow, getChildLp(mActionRow));\n final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();\n mTouchSlopSquared = slop * slop;\n mHandler = new Handler();\n super.setOnClickListener(this);\n }\n\n /**\n * Indicates whether this view reacts to click events or not.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isSliceViewClickable() {\n return mOnClickListener != null || (mListContent != null && mListContent.getPrimaryAction() != null);\n }\n\n /**\n * Sets the event info for logging a click.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setClickInfo(int[] info) {\n mClickInfo = info;\n }\n\n @Override\n public void onClick(View v) {\n if (mListContent != null && mListContent.getPrimaryAction() != null) {\n try {\n SliceActionImpl sa = new SliceActionImpl(mListContent.getPrimaryAction());\n sa.getAction().send();\n if (mSliceObserver != null && mClickInfo != null && mClickInfo.length > 1) {\n EventInfo eventInfo = new EventInfo(getMode(), EventInfo.ACTION_TYPE_CONTENT, mClickInfo[0], mClickInfo[1]);\n mSliceObserver.onSliceAction(eventInfo, mListContent.getPrimaryAction());\n }\n } catch (PendingIntent.CanceledException e) {\n Log.e(TAG, \"PendingIntent for slice cannot be sent\", e);\n }\n } else if (mOnClickListener != null) {\n mOnClickListener.onClick(this);\n }\n }\n\n @Override\n public void setOnClickListener(View.OnClickListener listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public void setOnLongClickListener(View.OnLongClickListener listener) {\n super.setOnLongClickListener(listener);\n mLongClickListener = listener;\n }\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n boolean ret = super.onInterceptTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n boolean ret = super.onTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n private boolean handleTouchForLongpress(MotionEvent ev) {\n int action = ev.getActionMasked();\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n mHandler.removeCallbacks(mLongpressCheck);\n mDownX = (int) ev.getRawX();\n mDownY = (int) ev.getRawY();\n mPressing = true;\n mInLongpress = false;\n mHandler.postDelayed(mLongpressCheck, ViewConfiguration.getLongPressTimeout());\n break;\n case MotionEvent.ACTION_MOVE:\n final int deltaX = (int) ev.getRawX() - mDownX;\n final int deltaY = (int) ev.getRawY() - mDownY;\n int distance = (deltaX * deltaX) + (deltaY * deltaY);\n if (distance > mTouchSlopSquared) {\n mPressing = false;\n mHandler.removeCallbacks(mLongpressCheck);\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n mPressing = false;\n mInLongpress = false;\n mHandler.removeCallbacks(mLongpressCheck);\n break;\n }\n return mInLongpress;\n }\n\n private int getHeightForMode() {\n int mode = getMode();\n if (mode == MODE_SHORTCUT) {\n return mListContent != null && mListContent.isValid() ? mShortcutSize : 0;\n }\n return mode == MODE_LARGE ? mCurrentView.getActualHeight() : mCurrentView.getSmallHeight();\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int width = MeasureSpec.getSize(widthMeasureSpec);\n int childWidth = MeasureSpec.getSize(widthMeasureSpec);\n if (MODE_SHORTCUT == mMode) {\n // TODO: consider scaling the shortcut to fit if too small\n childWidth = mShortcutSize;\n width = mShortcutSize + getPaddingLeft() + getPaddingRight();\n }\n final int actionHeight = mActionRow.getVisibility() != View.GONE ? mActionRowHeight : 0;\n final int sliceHeight = getHeightForMode();\n final int heightAvailable = MeasureSpec.getSize(heightMeasureSpec);\n final int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n // Remove the padding from our available height\n int height = heightAvailable - getPaddingTop() - getPaddingBottom();\n if (heightAvailable >= sliceHeight + actionHeight || heightMode == MeasureSpec.UNSPECIFIED) {\n // Available space is larger than the slice or we be what we want\n if (heightMode != MeasureSpec.EXACTLY) {\n if (!mIsScrollable) {\n height = Math.min(mMaxLargeHeight, sliceHeight);\n } else {\n // If we want to be bigger than max, then we can be a good scrollable at min\n // large height, if it's not larger lets just use its desired height\n height = sliceHeight > mMaxLargeHeight ? mMinLargeHeight : sliceHeight;\n }\n }\n } else {\n // Not enough space available for slice in current mode\n if (getMode() == MODE_LARGE && heightAvailable >= mMinLargeHeight + actionHeight) {\n // It's just a slice with scrolling content; cap it to height available.\n height = Math.min(mMinLargeHeight, heightAvailable);\n } else if (getMode() == MODE_SHORTCUT) {\n // TODO: consider scaling the shortcut to fit if too small\n height = mShortcutSize;\n }\n }\n int childHeight = height + getPaddingTop() + getPaddingBottom();\n int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);\n int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);\n measureChild(mCurrentView, childWidthMeasureSpec, childHeightMeasureSpec);\n int actionPaddedHeight = actionHeight + getPaddingTop() + getPaddingBottom();\n int actionHeightSpec = MeasureSpec.makeMeasureSpec(actionPaddedHeight, MeasureSpec.EXACTLY);\n measureChild(mActionRow, childWidthMeasureSpec, actionHeightSpec);\n // Total height should include action row and our padding\n height += actionHeight + getPaddingTop() + getPaddingBottom();\n setMeasuredDimension(width, height);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n View v = mCurrentView;\n final int left = getPaddingLeft();\n final int top = getPaddingTop();\n v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight());\n if (mActionRow.getVisibility() != View.GONE) {\n mActionRow.layout(left, top + v.getMeasuredHeight(), left + mActionRow.getMeasuredWidth(), top + v.getMeasuredHeight() + mActionRow.getMeasuredHeight());\n }\n }\n\n @Override\n public void onChanged(@Nullable Slice slice) {\n setSlice(slice);\n }\n\n /**\n * Populates this view to the provided {@link Slice}.\n *\n * This will not update automatically if the slice content changes, for live\n * content see {@link SliceLiveData}.\n */\n public void setSlice(@Nullable Slice slice) {\n if (slice != null) {\n if (mCurrentSlice == null || !mCurrentSlice.getUri().equals(slice.getUri())) {\n mCurrentView.resetView();\n }\n } else {\n // No slice, no actions\n mActions = null;\n }\n mActions = SliceMetadata.getSliceActions(slice);\n mCurrentSlice = slice;\n reinflate();\n }\n\n /**\n * @return the slice being used to populate this view.\n */\n @Nullable\n public Slice getSlice() {\n return mCurrentSlice;\n }\n\n /**\n * Returns the slice actions presented in this view.\n *

\n * Note that these may be different from {@link SliceMetadata#getSliceActions()} if the actions\n * set on the view have been adjusted using {@link #setSliceActions(List)}.\n */\n @Nullable\n public List getSliceActions() {\n return mActions;\n }\n\n /**\n * Sets the slice actions to display for the slice contained in this view. Normally SliceView\n * will automatically show actions, however, it is possible to reorder or omit actions on the\n * view using this method. This is generally discouraged.\n *

\n * It is required that the slice be set on this view before actions can be set, otherwise\n * this will throw {@link IllegalStateException}. If any of the actions supplied are not\n * available for the slice set on this view (i.e. the action is not returned by\n * {@link SliceMetadata#getSliceActions()} this will throw {@link IllegalArgumentException}.\n */\n public void setSliceActions(@Nullable List newActions) {\n // Check that these actions are part of available set\n if (mCurrentSlice == null) {\n throw new IllegalStateException(\"Trying to set actions on a view without a slice\");\n }\n List availableActions = SliceMetadata.getSliceActions(mCurrentSlice);\n if (availableActions != null && newActions != null) {\n ", "post_mask_code": "\n }\n mActions = newActions;\n updateActions();\n }\n\n /**\n * Set the mode this view should present in.\n */\n public void setMode(@SliceMode int mode) {\n setMode(mode, false);\n }\n\n /**\n * Set whether this view should allow scrollable content when presenting in {@link #MODE_LARGE}.\n */\n public void setScrollable(boolean isScrollable) {\n mIsScrollable = isScrollable;\n reinflate();\n }\n\n /**\n * Sets the listener to notify when an interaction events occur on the view.\n * @see EventInfo\n */\n public void setOnSliceActionListener(@Nullable OnSliceActionListener observer) {\n mSliceObserver = observer;\n mCurrentView.setSliceActionListener(mSliceObserver);\n }\n\n /**\n * @deprecated TO BE REMOVED; use {@link #setAccentColor(int)} instead.\n */\n @Deprecated\n public void setTint(int tintColor) {\n setAccentColor(tintColor);\n }\n\n /**\n * Contents of a slice such as icons, text, and controls (e.g. toggle) can be tinted. Normally\n * a color for tinting will be provided by the slice. Using this method will override\n * the slice-provided color information and instead tint elements with the color set here.\n *\n * @param accentColor the color to use for tinting contents of this view.\n */\n public void setAccentColor(@ColorInt int accentColor) {\n mThemeTintColor = accentColor;\n mCurrentView.setTint(accentColor);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setMode(@SliceMode int mode, boolean animate) {\n if (animate) {\n Log.e(TAG, \"Animation not supported yet\");\n }\n if (mMode == mode) {\n return;\n }\n mMode = mode;\n reinflate();\n }\n\n /**\n * @return the mode this view is presenting in.\n */\n @SliceMode\n public int getMode() {\n return mMode;\n }\n\n /**\n * @hide\n *\n * Whether this view should show a row of actions with it.\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setShowActionRow(boolean show) {\n mShowActions = show;\n updateActions();\n }\n\n /**\n * @return whether this view is showing a row of actions.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isShowingActionRow() {\n return mShowActions;\n }\n\n private void reinflate() {\n if (mCurrentSlice == null) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n mListContent = new ListContent(getContext(), mCurrentSlice, mAttrs, mDefStyleAttr, mDefStyleRes);\n if (!mListContent.isValid()) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n // TODO: Smarter mapping here from one state to the next.\n int mode = getMode();\n boolean isCurrentViewShortcut = mCurrentView instanceof ShortcutView;\n if (mode == MODE_SHORTCUT && !isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new ShortcutView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n } else if (mode != MODE_SHORTCUT && isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new LargeTemplateView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n }\n mCurrentView.setMode(mode);\n mCurrentView.setSliceActionListener(mSliceObserver);\n if (mCurrentView instanceof LargeTemplateView) {\n ((LargeTemplateView) mCurrentView).setScrollable(mIsScrollable);\n }\n mCurrentView.setStyle(mAttrs, mDefStyleAttr, mDefStyleRes);\n mCurrentView.setTint(getTintColor());\n // Check if the slice content is expired and show when it was last updated\n SliceMetadata sliceMetadata = SliceMetadata.from(getContext(), mCurrentSlice);\n long lastUpdated = sliceMetadata.getLastUpdatedTime();\n long expiry = sliceMetadata.getExpiry();\n long now = System.currentTimeMillis();\n mCurrentView.setLastUpdated(lastUpdated);\n boolean expired = expiry != 0 && expiry != SliceHints.INFINITY && now > expiry;\n mCurrentView.setShowLastUpdated(mShowLastUpdated && expired);\n // Set the slice\n mCurrentView.setSliceContent(mListContent);\n updateActions();\n }\n\n private void updateActions() {\n if (mActions == null || mActions.isEmpty()) {\n // No actions, hide the row, clear out the view\n mActionRow.setVisibility(View.GONE);\n mCurrentView.setSliceActions(null);\n return;\n }\n // TODO: take priority attached to actions into account\n if (mShowActions && mMode != MODE_SHORTCUT && mActions.size() >= 2) {\n // Show in action row if available\n mActionRow.setActions(mActions, getTintColor());\n mActionRow.setVisibility(View.VISIBLE);\n // Hide them on the template\n mCurrentView.setSliceActions(null);\n } else if (mActions.size() > 0) {\n // Otherwise set them on the template\n mCurrentView.setSliceActions(mActions);\n mActionRow.setVisibility(View.GONE);\n }\n }\n\n private int getTintColor() {\n if (mThemeTintColor != -1) {\n // Theme has specified a color, use that\n return mThemeTintColor;\n } else {\n final SliceItem colorItem = SliceQuery.findSubtype(mCurrentSlice, FORMAT_INT, SUBTYPE_COLOR);\n return colorItem != null ? colorItem.getInt() : SliceViewUtil.getColorAccent(getContext());\n }\n }\n\n private LayoutParams getChildLp(View child) {\n if (child instanceof ShortcutView) {\n return new LayoutParams(mShortcutSize, mShortcutSize);\n } else {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n }\n\n /**\n * @return String representation of the provided mode.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public static String modeToString(@SliceMode int mode) {\n switch(mode) {\n case MODE_SHORTCUT:\n return \"MODE SHORTCUT\";\n case MODE_SMALL:\n return \"MODE SMALL\";\n case MODE_LARGE:\n return \"MODE LARGE\";\n default:\n return \"unknown mode: \" + mode;\n }\n }\n\n Runnable mLongpressCheck = new Runnable() {\n\n @Override\n public void run() {\n if (mPressing && mLongClickListener != null) {\n mInLongpress = true;\n mLongClickListener.onLongClick(SliceView.this);\n performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);\n }\n }\n };\n}\n"} {"task_id": "Java_153", "language": "Java", "task_type": "try_statement", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/slice/widget/SliceView.java", "mask_start_position": 6228, "mask_end_position": 6367, "canonical_solution": "try {\n mThemeTintColor = a.getColor(R.styleable.SliceView_tintColor, -1);\n } finally {\n a.recycle();\n }", "pre_mask_code": "package androidx.slice.widget;\n\nimport static android.app.slice.Slice.SUBTYPE_COLOR;\nimport static android.app.slice.SliceItem.FORMAT_INT;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.HapticFeedbackConstants;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport androidx.annotation.ColorInt;\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.RestrictTo;\nimport androidx.lifecycle.Observer;\nimport androidx.slice.Slice;\nimport androidx.slice.SliceItem;\nimport androidx.slice.SliceMetadata;\nimport androidx.slice.core.SliceActionImpl;\nimport androidx.slice.core.SliceHints;\nimport androidx.slice.core.SliceQuery;\nimport androidx.slice.view.R;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.List;\n\n/**\n * A view for displaying a {@link Slice} which is a piece of app content and actions. SliceView is\n * able to present slice content in a templated format outside of the associated app. The way this\n * content is displayed depends on the structure of the slice, the hints associated with the\n * content, and the mode that SliceView is configured for. The modes that SliceView supports are:\n *

    \n *
  • Shortcut: A shortcut is presented as an icon and a text label representing the main\n * content or action associated with the slice.
  • \n *
  • Small: The small format has a restricted height and can present a single\n * {@link SliceItem} or a limited collection of items.
  • \n *
  • Large: The large format displays multiple small templates in a list, if scrolling is\n * not enabled (see {@link #setScrollable(boolean)}) the view will show as many items as it can\n * comfortably fit.
  • \n *
\n *

\n * When constructing a slice, the contents of it can be annotated with hints, these provide the OS\n * with some information on how the content should be displayed. For example, text annotated with\n * {@link android.app.slice.Slice#HINT_TITLE} would be placed in the title position of a template.\n * A slice annotated with {@link android.app.slice.Slice#HINT_LIST} would present the child items\n * of that slice in a list.\n *

\n * Example usage:\n *\n *

\n * SliceView v = new SliceView(getContext());\n * v.setMode(desiredMode);\n * LiveData liveData = SliceLiveData.fromUri(sliceUri);\n * liveData.observe(lifecycleOwner, v);\n * 
\n * @see SliceLiveData\n */\npublic class SliceView extends ViewGroup implements Observer, View.OnClickListener {\n\n private static final String TAG = \"SliceView\";\n\n /**\n * Implement this interface to be notified of interactions with the slice displayed\n * in this view.\n * @see EventInfo\n */\n public interface OnSliceActionListener {\n\n /**\n * Called when an interaction has occurred with an element in this view.\n * @param info the type of event that occurred.\n * @param item the specific item within the {@link Slice} that was interacted with.\n */\n void onSliceAction(@NonNull EventInfo info, @NonNull SliceItem item);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n @IntDef({ MODE_SMALL, MODE_LARGE, MODE_SHORTCUT })\n @Retention(RetentionPolicy.SOURCE)\n public @interface SliceMode {\n }\n\n /**\n * Mode indicating this slice should be presented in small template format.\n */\n public static final int MODE_SMALL = 1;\n\n /**\n * Mode indicating this slice should be presented in large template format.\n */\n public static final int MODE_LARGE = 2;\n\n /**\n * Mode indicating this slice should be presented as an icon. A shortcut requires an intent,\n * icon, and label. This can be indicated by using {@link android.app.slice.Slice#HINT_TITLE}\n * on an action in a slice.\n */\n public static final int MODE_SHORTCUT = 3;\n\n private int mMode = MODE_LARGE;\n\n private Slice mCurrentSlice;\n\n private ListContent mListContent;\n\n private SliceChildView mCurrentView;\n\n private List mActions;\n\n private ActionRow mActionRow;\n\n private boolean mShowActions = false;\n\n private boolean mIsScrollable = true;\n\n private boolean mShowLastUpdated = true;\n\n private int mShortcutSize;\n\n private int mMinLargeHeight;\n\n private int mMaxLargeHeight;\n\n private int mActionRowHeight;\n\n private AttributeSet mAttrs;\n\n private int mDefStyleAttr;\n\n private int mDefStyleRes;\n\n private int mThemeTintColor = -1;\n\n private OnSliceActionListener mSliceObserver;\n\n private int mTouchSlopSquared;\n\n private View.OnLongClickListener mLongClickListener;\n\n private View.OnClickListener mOnClickListener;\n\n private int mDownX;\n\n private int mDownY;\n\n private boolean mPressing;\n\n private boolean mInLongpress;\n\n private Handler mHandler;\n\n int[] mClickInfo;\n\n public SliceView(Context context) {\n this(context, null);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, R.attr.sliceViewStyle);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, R.style.Widget_SliceView);\n }\n\n @RequiresApi(21)\n public SliceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n init(context, attrs, defStyleAttr, defStyleRes);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n mAttrs = attrs;\n mDefStyleAttr = defStyleAttr;\n mDefStyleRes = defStyleRes;\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliceView, defStyleAttr, defStyleRes);\n ", "post_mask_code": "\n mShortcutSize = getContext().getResources().getDimensionPixelSize(R.dimen.abc_slice_shortcut_size);\n mMinLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_large_height);\n mMaxLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_max_large_height);\n mActionRowHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_action_row_height);\n mCurrentView = new LargeTemplateView(getContext());\n mCurrentView.setMode(getMode());\n addView(mCurrentView, getChildLp(mCurrentView));\n // TODO: action row background should support light / dark / maybe presenter customization\n mActionRow = new ActionRow(getContext(), true);\n mActionRow.setBackground(new ColorDrawable(0xffeeeeee));\n addView(mActionRow, getChildLp(mActionRow));\n final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();\n mTouchSlopSquared = slop * slop;\n mHandler = new Handler();\n super.setOnClickListener(this);\n }\n\n /**\n * Indicates whether this view reacts to click events or not.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isSliceViewClickable() {\n return mOnClickListener != null || (mListContent != null && mListContent.getPrimaryAction() != null);\n }\n\n /**\n * Sets the event info for logging a click.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setClickInfo(int[] info) {\n mClickInfo = info;\n }\n\n @Override\n public void onClick(View v) {\n if (mListContent != null && mListContent.getPrimaryAction() != null) {\n try {\n SliceActionImpl sa = new SliceActionImpl(mListContent.getPrimaryAction());\n sa.getAction().send();\n if (mSliceObserver != null && mClickInfo != null && mClickInfo.length > 1) {\n EventInfo eventInfo = new EventInfo(getMode(), EventInfo.ACTION_TYPE_CONTENT, mClickInfo[0], mClickInfo[1]);\n mSliceObserver.onSliceAction(eventInfo, mListContent.getPrimaryAction());\n }\n } catch (PendingIntent.CanceledException e) {\n Log.e(TAG, \"PendingIntent for slice cannot be sent\", e);\n }\n } else if (mOnClickListener != null) {\n mOnClickListener.onClick(this);\n }\n }\n\n @Override\n public void setOnClickListener(View.OnClickListener listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public void setOnLongClickListener(View.OnLongClickListener listener) {\n super.setOnLongClickListener(listener);\n mLongClickListener = listener;\n }\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n boolean ret = super.onInterceptTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n boolean ret = super.onTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n private boolean handleTouchForLongpress(MotionEvent ev) {\n int action = ev.getActionMasked();\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n mHandler.removeCallbacks(mLongpressCheck);\n mDownX = (int) ev.getRawX();\n mDownY = (int) ev.getRawY();\n mPressing = true;\n mInLongpress = false;\n mHandler.postDelayed(mLongpressCheck, ViewConfiguration.getLongPressTimeout());\n break;\n case MotionEvent.ACTION_MOVE:\n final int deltaX = (int) ev.getRawX() - mDownX;\n final int deltaY = (int) ev.getRawY() - mDownY;\n int distance = (deltaX * deltaX) + (deltaY * deltaY);\n if (distance > mTouchSlopSquared) {\n mPressing = false;\n mHandler.removeCallbacks(mLongpressCheck);\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n mPressing = false;\n mInLongpress = false;\n mHandler.removeCallbacks(mLongpressCheck);\n break;\n }\n return mInLongpress;\n }\n\n private int getHeightForMode() {\n int mode = getMode();\n if (mode == MODE_SHORTCUT) {\n return mListContent != null && mListContent.isValid() ? mShortcutSize : 0;\n }\n return mode == MODE_LARGE ? mCurrentView.getActualHeight() : mCurrentView.getSmallHeight();\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int width = MeasureSpec.getSize(widthMeasureSpec);\n int childWidth = MeasureSpec.getSize(widthMeasureSpec);\n if (MODE_SHORTCUT == mMode) {\n // TODO: consider scaling the shortcut to fit if too small\n childWidth = mShortcutSize;\n width = mShortcutSize + getPaddingLeft() + getPaddingRight();\n }\n final int actionHeight = mActionRow.getVisibility() != View.GONE ? mActionRowHeight : 0;\n final int sliceHeight = getHeightForMode();\n final int heightAvailable = MeasureSpec.getSize(heightMeasureSpec);\n final int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n // Remove the padding from our available height\n int height = heightAvailable - getPaddingTop() - getPaddingBottom();\n if (heightAvailable >= sliceHeight + actionHeight || heightMode == MeasureSpec.UNSPECIFIED) {\n // Available space is larger than the slice or we be what we want\n if (heightMode != MeasureSpec.EXACTLY) {\n if (!mIsScrollable) {\n height = Math.min(mMaxLargeHeight, sliceHeight);\n } else {\n // If we want to be bigger than max, then we can be a good scrollable at min\n // large height, if it's not larger lets just use its desired height\n height = sliceHeight > mMaxLargeHeight ? mMinLargeHeight : sliceHeight;\n }\n }\n } else {\n // Not enough space available for slice in current mode\n if (getMode() == MODE_LARGE && heightAvailable >= mMinLargeHeight + actionHeight) {\n // It's just a slice with scrolling content; cap it to height available.\n height = Math.min(mMinLargeHeight, heightAvailable);\n } else if (getMode() == MODE_SHORTCUT) {\n // TODO: consider scaling the shortcut to fit if too small\n height = mShortcutSize;\n }\n }\n int childHeight = height + getPaddingTop() + getPaddingBottom();\n int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);\n int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);\n measureChild(mCurrentView, childWidthMeasureSpec, childHeightMeasureSpec);\n int actionPaddedHeight = actionHeight + getPaddingTop() + getPaddingBottom();\n int actionHeightSpec = MeasureSpec.makeMeasureSpec(actionPaddedHeight, MeasureSpec.EXACTLY);\n measureChild(mActionRow, childWidthMeasureSpec, actionHeightSpec);\n // Total height should include action row and our padding\n height += actionHeight + getPaddingTop() + getPaddingBottom();\n setMeasuredDimension(width, height);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n View v = mCurrentView;\n final int left = getPaddingLeft();\n final int top = getPaddingTop();\n v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight());\n if (mActionRow.getVisibility() != View.GONE) {\n mActionRow.layout(left, top + v.getMeasuredHeight(), left + mActionRow.getMeasuredWidth(), top + v.getMeasuredHeight() + mActionRow.getMeasuredHeight());\n }\n }\n\n @Override\n public void onChanged(@Nullable Slice slice) {\n setSlice(slice);\n }\n\n /**\n * Populates this view to the provided {@link Slice}.\n *\n * This will not update automatically if the slice content changes, for live\n * content see {@link SliceLiveData}.\n */\n public void setSlice(@Nullable Slice slice) {\n if (slice != null) {\n if (mCurrentSlice == null || !mCurrentSlice.getUri().equals(slice.getUri())) {\n mCurrentView.resetView();\n }\n } else {\n // No slice, no actions\n mActions = null;\n }\n mActions = SliceMetadata.getSliceActions(slice);\n mCurrentSlice = slice;\n reinflate();\n }\n\n /**\n * @return the slice being used to populate this view.\n */\n @Nullable\n public Slice getSlice() {\n return mCurrentSlice;\n }\n\n /**\n * Returns the slice actions presented in this view.\n *

\n * Note that these may be different from {@link SliceMetadata#getSliceActions()} if the actions\n * set on the view have been adjusted using {@link #setSliceActions(List)}.\n */\n @Nullable\n public List getSliceActions() {\n return mActions;\n }\n\n /**\n * Sets the slice actions to display for the slice contained in this view. Normally SliceView\n * will automatically show actions, however, it is possible to reorder or omit actions on the\n * view using this method. This is generally discouraged.\n *

\n * It is required that the slice be set on this view before actions can be set, otherwise\n * this will throw {@link IllegalStateException}. If any of the actions supplied are not\n * available for the slice set on this view (i.e. the action is not returned by\n * {@link SliceMetadata#getSliceActions()} this will throw {@link IllegalArgumentException}.\n */\n public void setSliceActions(@Nullable List newActions) {\n // Check that these actions are part of available set\n if (mCurrentSlice == null) {\n throw new IllegalStateException(\"Trying to set actions on a view without a slice\");\n }\n List availableActions = SliceMetadata.getSliceActions(mCurrentSlice);\n if (availableActions != null && newActions != null) {\n for (int i = 0; i < newActions.size(); i++) {\n if (!availableActions.contains(newActions.get(i))) {\n throw new IllegalArgumentException(\"Trying to set an action that isn't available: \" + newActions.get(i));\n }\n }\n }\n mActions = newActions;\n updateActions();\n }\n\n /**\n * Set the mode this view should present in.\n */\n public void setMode(@SliceMode int mode) {\n setMode(mode, false);\n }\n\n /**\n * Set whether this view should allow scrollable content when presenting in {@link #MODE_LARGE}.\n */\n public void setScrollable(boolean isScrollable) {\n mIsScrollable = isScrollable;\n reinflate();\n }\n\n /**\n * Sets the listener to notify when an interaction events occur on the view.\n * @see EventInfo\n */\n public void setOnSliceActionListener(@Nullable OnSliceActionListener observer) {\n mSliceObserver = observer;\n mCurrentView.setSliceActionListener(mSliceObserver);\n }\n\n /**\n * @deprecated TO BE REMOVED; use {@link #setAccentColor(int)} instead.\n */\n @Deprecated\n public void setTint(int tintColor) {\n setAccentColor(tintColor);\n }\n\n /**\n * Contents of a slice such as icons, text, and controls (e.g. toggle) can be tinted. Normally\n * a color for tinting will be provided by the slice. Using this method will override\n * the slice-provided color information and instead tint elements with the color set here.\n *\n * @param accentColor the color to use for tinting contents of this view.\n */\n public void setAccentColor(@ColorInt int accentColor) {\n mThemeTintColor = accentColor;\n mCurrentView.setTint(accentColor);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setMode(@SliceMode int mode, boolean animate) {\n if (animate) {\n Log.e(TAG, \"Animation not supported yet\");\n }\n if (mMode == mode) {\n return;\n }\n mMode = mode;\n reinflate();\n }\n\n /**\n * @return the mode this view is presenting in.\n */\n @SliceMode\n public int getMode() {\n return mMode;\n }\n\n /**\n * @hide\n *\n * Whether this view should show a row of actions with it.\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setShowActionRow(boolean show) {\n mShowActions = show;\n updateActions();\n }\n\n /**\n * @return whether this view is showing a row of actions.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isShowingActionRow() {\n return mShowActions;\n }\n\n private void reinflate() {\n if (mCurrentSlice == null) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n mListContent = new ListContent(getContext(), mCurrentSlice, mAttrs, mDefStyleAttr, mDefStyleRes);\n if (!mListContent.isValid()) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n // TODO: Smarter mapping here from one state to the next.\n int mode = getMode();\n boolean isCurrentViewShortcut = mCurrentView instanceof ShortcutView;\n if (mode == MODE_SHORTCUT && !isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new ShortcutView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n } else if (mode != MODE_SHORTCUT && isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new LargeTemplateView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n }\n mCurrentView.setMode(mode);\n mCurrentView.setSliceActionListener(mSliceObserver);\n if (mCurrentView instanceof LargeTemplateView) {\n ((LargeTemplateView) mCurrentView).setScrollable(mIsScrollable);\n }\n mCurrentView.setStyle(mAttrs, mDefStyleAttr, mDefStyleRes);\n mCurrentView.setTint(getTintColor());\n // Check if the slice content is expired and show when it was last updated\n SliceMetadata sliceMetadata = SliceMetadata.from(getContext(), mCurrentSlice);\n long lastUpdated = sliceMetadata.getLastUpdatedTime();\n long expiry = sliceMetadata.getExpiry();\n long now = System.currentTimeMillis();\n mCurrentView.setLastUpdated(lastUpdated);\n boolean expired = expiry != 0 && expiry != SliceHints.INFINITY && now > expiry;\n mCurrentView.setShowLastUpdated(mShowLastUpdated && expired);\n // Set the slice\n mCurrentView.setSliceContent(mListContent);\n updateActions();\n }\n\n private void updateActions() {\n if (mActions == null || mActions.isEmpty()) {\n // No actions, hide the row, clear out the view\n mActionRow.setVisibility(View.GONE);\n mCurrentView.setSliceActions(null);\n return;\n }\n // TODO: take priority attached to actions into account\n if (mShowActions && mMode != MODE_SHORTCUT && mActions.size() >= 2) {\n // Show in action row if available\n mActionRow.setActions(mActions, getTintColor());\n mActionRow.setVisibility(View.VISIBLE);\n // Hide them on the template\n mCurrentView.setSliceActions(null);\n } else if (mActions.size() > 0) {\n // Otherwise set them on the template\n mCurrentView.setSliceActions(mActions);\n mActionRow.setVisibility(View.GONE);\n }\n }\n\n private int getTintColor() {\n if (mThemeTintColor != -1) {\n // Theme has specified a color, use that\n return mThemeTintColor;\n } else {\n final SliceItem colorItem = SliceQuery.findSubtype(mCurrentSlice, FORMAT_INT, SUBTYPE_COLOR);\n return colorItem != null ? colorItem.getInt() : SliceViewUtil.getColorAccent(getContext());\n }\n }\n\n private LayoutParams getChildLp(View child) {\n if (child instanceof ShortcutView) {\n return new LayoutParams(mShortcutSize, mShortcutSize);\n } else {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n }\n\n /**\n * @return String representation of the provided mode.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public static String modeToString(@SliceMode int mode) {\n switch(mode) {\n case MODE_SHORTCUT:\n return \"MODE SHORTCUT\";\n case MODE_SMALL:\n return \"MODE SMALL\";\n case MODE_LARGE:\n return \"MODE LARGE\";\n default:\n return \"unknown mode: \" + mode;\n }\n }\n\n Runnable mLongpressCheck = new Runnable() {\n\n @Override\n public void run() {\n if (mPressing && mLongClickListener != null) {\n mInLongpress = true;\n mLongClickListener.onLongClick(SliceView.this);\n performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);\n }\n }\n };\n}\n"} {"task_id": "Java_154", "language": "Java", "task_type": "empty", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/slice/widget/SliceView.java", "mask_start_position": 20825, "mask_end_position": 20825, "canonical_solution": "", "pre_mask_code": "package androidx.slice.widget;\n\nimport static android.app.slice.Slice.SUBTYPE_COLOR;\nimport static android.app.slice.SliceItem.FORMAT_INT;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.drawable.ColorDrawable;\nimport android.os.Handler;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.HapticFeedbackConstants;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport androidx.annotation.ColorInt;\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.RestrictTo;\nimport androidx.lifecycle.Observer;\nimport androidx.slice.Slice;\nimport androidx.slice.SliceItem;\nimport androidx.slice.SliceMetadata;\nimport androidx.slice.core.SliceActionImpl;\nimport androidx.slice.core.SliceHints;\nimport androidx.slice.core.SliceQuery;\nimport androidx.slice.view.R;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.List;\n\n/**\n * A view for displaying a {@link Slice} which is a piece of app content and actions. SliceView is\n * able to present slice content in a templated format outside of the associated app. The way this\n * content is displayed depends on the structure of the slice, the hints associated with the\n * content, and the mode that SliceView is configured for. The modes that SliceView supports are:\n *

    \n *
  • Shortcut: A shortcut is presented as an icon and a text label representing the main\n * content or action associated with the slice.
  • \n *
  • Small: The small format has a restricted height and can present a single\n * {@link SliceItem} or a limited collection of items.
  • \n *
  • Large: The large format displays multiple small templates in a list, if scrolling is\n * not enabled (see {@link #setScrollable(boolean)}) the view will show as many items as it can\n * comfortably fit.
  • \n *
\n *

\n * When constructing a slice, the contents of it can be annotated with hints, these provide the OS\n * with some information on how the content should be displayed. For example, text annotated with\n * {@link android.app.slice.Slice#HINT_TITLE} would be placed in the title position of a template.\n * A slice annotated with {@link android.app.slice.Slice#HINT_LIST} would present the child items\n * of that slice in a list.\n *

\n * Example usage:\n *\n *

\n * SliceView v = new SliceView(getContext());\n * v.setMode(desiredMode);\n * LiveData liveData = SliceLiveData.fromUri(sliceUri);\n * liveData.observe(lifecycleOwner, v);\n * 
\n * @see SliceLiveData\n */\npublic class SliceView extends ViewGroup implements Observer, View.OnClickListener {\n\n private static final String TAG = \"SliceView\";\n\n /**\n * Implement this interface to be notified of interactions with the slice displayed\n * in this view.\n * @see EventInfo\n */\n public interface OnSliceActionListener {\n\n /**\n * Called when an interaction has occurred with an element in this view.\n * @param info the type of event that occurred.\n * @param item the specific item within the {@link Slice} that was interacted with.\n */\n void onSliceAction(@NonNull EventInfo info, @NonNull SliceItem item);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n @IntDef({ MODE_SMALL, MODE_LARGE, MODE_SHORTCUT })\n @Retention(RetentionPolicy.SOURCE)\n public @interface SliceMode {\n }\n\n /**\n * Mode indicating this slice should be presented in small template format.\n */\n public static final int MODE_SMALL = 1;\n\n /**\n * Mode indicating this slice should be presented in large template format.\n */\n public static final int MODE_LARGE = 2;\n\n /**\n * Mode indicating this slice should be presented as an icon. A shortcut requires an intent,\n * icon, and label. This can be indicated by using {@link android.app.slice.Slice#HINT_TITLE}\n * on an action in a slice.\n */\n public static final int MODE_SHORTCUT = 3;\n\n private int mMode = MODE_LARGE;\n\n private Slice mCurrentSlice;\n\n private ListContent mListContent;\n\n private SliceChildView mCurrentView;\n\n private List mActions;\n\n private ActionRow mActionRow;\n\n private boolean mShowActions = false;\n\n private boolean mIsScrollable = true;\n\n private boolean mShowLastUpdated = true;\n\n private int mShortcutSize;\n\n private int mMinLargeHeight;\n\n private int mMaxLargeHeight;\n\n private int mActionRowHeight;\n\n private AttributeSet mAttrs;\n\n private int mDefStyleAttr;\n\n private int mDefStyleRes;\n\n private int mThemeTintColor = -1;\n\n private OnSliceActionListener mSliceObserver;\n\n private int mTouchSlopSquared;\n\n private View.OnLongClickListener mLongClickListener;\n\n private View.OnClickListener mOnClickListener;\n\n private int mDownX;\n\n private int mDownY;\n\n private boolean mPressing;\n\n private boolean mInLongpress;\n\n private Handler mHandler;\n\n int[] mClickInfo;\n\n public SliceView(Context context) {\n this(context, null);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, R.attr.sliceViewStyle);\n }\n\n public SliceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, R.style.Widget_SliceView);\n }\n\n @RequiresApi(21)\n public SliceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n init(context, attrs, defStyleAttr, defStyleRes);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n mAttrs = attrs;\n mDefStyleAttr = defStyleAttr;\n mDefStyleRes = defStyleRes;\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliceView, defStyleAttr, defStyleRes);\n try {\n mThemeTintColor = a.getColor(R.styleable.SliceView_tintColor, -1);\n } finally {\n a.recycle();\n }\n mShortcutSize = getContext().getResources().getDimensionPixelSize(R.dimen.abc_slice_shortcut_size);\n mMinLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_large_height);\n mMaxLargeHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_max_large_height);\n mActionRowHeight = getResources().getDimensionPixelSize(R.dimen.abc_slice_action_row_height);\n mCurrentView = new LargeTemplateView(getContext());\n mCurrentView.setMode(getMode());\n addView(mCurrentView, getChildLp(mCurrentView));\n // TODO: action row background should support light / dark / maybe presenter customization\n mActionRow = new ActionRow(getContext(), true);\n mActionRow.setBackground(new ColorDrawable(0xffeeeeee));\n addView(mActionRow, getChildLp(mActionRow));\n final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();\n mTouchSlopSquared = slop * slop;\n mHandler = new Handler();\n super.setOnClickListener(this);\n }\n\n /**\n * Indicates whether this view reacts to click events or not.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isSliceViewClickable() {\n return mOnClickListener != null || (mListContent != null && mListContent.getPrimaryAction() != null);\n }\n\n /**\n * Sets the event info for logging a click.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setClickInfo(int[] info) {\n mClickInfo = info;\n }\n\n @Override\n public void onClick(View v) {\n if (mListContent != null && mListContent.getPrimaryAction() != null) {\n try {\n SliceActionImpl sa = new SliceActionImpl(mListContent.getPrimaryAction());\n sa.getAction().send();\n if (mSliceObserver != null && mClickInfo != null && mClickInfo.length > 1) {\n EventInfo eventInfo = new EventInfo(getMode(), EventInfo.ACTION_TYPE_CONTENT, mClickInfo[0], mClickInfo[1]);\n mSliceObserver.onSliceAction(eventInfo, mListContent.getPrimaryAction());\n }\n } catch (PendingIntent.CanceledException e) {\n Log.e(TAG, \"PendingIntent for slice cannot be sent\", e);\n }\n } else if (mOnClickListener != null) {\n mOnClickListener.onClick(this);\n }\n }\n\n @Override\n public void setOnClickListener(View.OnClickListener listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public void setOnLongClickListener(View.OnLongClickListener listener) {\n super.setOnLongClickListener(listener);\n mLongClickListener = listener;\n }\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n boolean ret = super.onInterceptTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n boolean ret = super.onTouchEvent(ev);\n if (mLongClickListener != null) {\n return handleTouchForLongpress(ev);\n }\n return ret;\n }\n\n private boolean handleTouchForLongpress(MotionEvent ev) {\n int action = ev.getActionMasked();\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n mHandler.removeCallbacks(mLongpressCheck);\n mDownX = (int) ev.getRawX();\n mDownY = (int) ev.getRawY();\n mPressing = true;\n mInLongpress = false;\n mHandler.postDelayed(mLongpressCheck, ViewConfiguration.getLongPressTimeout());\n break;\n case MotionEvent.ACTION_MOVE:\n final int deltaX = (int) ev.getRawX() - mDownX;\n final int deltaY = (int) ev.getRawY() - mDownY;\n int distance = (deltaX * deltaX) + (deltaY * deltaY);\n if (distance > mTouchSlopSquared) {\n mPressing = false;\n mHandler.removeCallbacks(mLongpressCheck);\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n mPressing = false;\n mInLongpress = false;\n mHandler.removeCallbacks(mLongpressCheck);\n break;\n }\n return mInLongpress;\n }\n\n private int getHeightForMode() {\n int mode = getMode();\n if (mode == MODE_SHORTCUT) {\n return mListContent != null && mListContent.isValid() ? mShortcutSize : 0;\n }\n return mode == MODE_LARGE ? mCurrentView.getActualHeight() : mCurrentView.getSmallHeight();\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int width = MeasureSpec.getSize(widthMeasureSpec);\n int childWidth = MeasureSpec.getSize(widthMeasureSpec);\n if (MODE_SHORTCUT == mMode) {\n // TODO: consider scaling the shortcut to fit if too small\n childWidth = mShortcutSize;\n width = mShortcutSize + getPaddingLeft() + getPaddingRight();\n }\n final int actionHeight = mActionRow.getVisibility() != View.GONE ? mActionRowHeight : 0;\n final int sliceHeight = getHeightForMode();\n final int heightAvailable = MeasureSpec.getSize(heightMeasureSpec);\n final int heightMode = MeasureSpec.getMode(heightMeasureSpec);\n // Remove the padding from our available height\n int height = heightAvailable - getPaddingTop() - getPaddingBottom();\n if (heightAvailable >= sliceHeight + actionHeight || heightMode == MeasureSpec.UNSPECIFIED) {\n // Available space is larger than the slice or we be what we want\n if (heightMode != MeasureSpec.EXACTLY) {\n if (!mIsScrollable) {\n height = Math.min(mMaxLargeHeight, sliceHeight);\n } else {\n // If we want to be bigger than max, then we can be a good scrollable at min\n // large height, if it's not larger lets just use its desired height\n height = sliceHeight > mMaxLargeHeight ? mMinLargeHeight : sliceHeight;\n }\n }\n } else {\n // Not enough space available for slice in current mode\n if (getMode() == MODE_LARGE && heightAvailable >= mMinLargeHeight + actionHeight) {\n // It's just a slice with scrolling content; cap it to height available.\n height = Math.min(mMinLargeHeight, heightAvailable);\n } else if (getMode() == MODE_SHORTCUT) {\n // TODO: consider scaling the shortcut to fit if too small\n height = mShortcutSize;\n }\n }\n int childHeight = height + getPaddingTop() + getPaddingBottom();\n int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);\n int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);\n measureChild(mCurrentView, childWidthMeasureSpec, childHeightMeasureSpec);\n int actionPaddedHeight = actionHeight + getPaddingTop() + getPaddingBottom();\n int actionHeightSpec = MeasureSpec.makeMeasureSpec(actionPaddedHeight, MeasureSpec.EXACTLY);\n measureChild(mActionRow, childWidthMeasureSpec, actionHeightSpec);\n // Total height should include action row and our padding\n height += actionHeight + getPaddingTop() + getPaddingBottom();\n setMeasuredDimension(width, height);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n View v = mCurrentView;\n final int left = getPaddingLeft();\n final int top = getPaddingTop();\n v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight());\n if (mActionRow.getVisibility() != View.GONE) {\n mActionRow.layout(left, top + v.getMeasuredHeight(), left + mActionRow.getMeasuredWidth(), top + v.getMeasuredHeight() + mActionRow.getMeasuredHeight());\n }\n }\n\n @Override\n public void onChanged(@Nullable Slice slice) {\n setSlice(slice);\n }\n\n /**\n * Populates this view to the provided {@link Slice}.\n *\n * This will not update automatically if the slice content changes, for live\n * content see {@link SliceLiveData}.\n */\n public void setSlice(@Nullable Slice slice) {\n if (slice != null) {\n if (mCurrentSlice == null || !mCurrentSlice.getUri().equals(slice.getUri())) {\n mCurrentView.resetView();\n }\n } else {\n // No slice, no actions\n mActions = null;\n }\n mActions = SliceMetadata.getSliceActions(slice);\n mCurrentSlice = slice;\n reinflate();\n }\n\n /**\n * @return the slice being used to populate this view.\n */\n @Nullable\n public Slice getSlice() {\n return mCurrentSlice;\n }\n\n /**\n * Returns the slice actions presented in this view.\n *

\n * Note that these may be different from {@link SliceMetadata#getSliceActions()} if the actions\n * set on the view have been adjusted using {@link #setSliceActions(List)}.\n */\n @Nullable\n public List getSliceActions() {\n return mActions;\n }\n\n /**\n * Sets the slice actions to display for the slice contained in this view. Normally SliceView\n * will automatically show actions, however, it is possible to reorder or omit actions on the\n * view using this method. This is generally discouraged.\n *

\n * It is required that the slice be set on this view before actions can be set, otherwise\n * this will throw {@link IllegalStateException}. If any of the actions supplied are not\n * available for the slice set on this view (i.e. the action is not returned by\n * {@link SliceMetadata#getSliceActions()} this will throw {@link IllegalArgumentException}.\n */\n public void setSliceActions(@Nullable List newActions) {\n // Check that these actions are part of available set\n if (mCurrentSlice == null) {\n throw new IllegalStateException(\"Trying to set actions on a view without a slice\");\n }\n List availableActions = SliceMetadata.getSliceActions(mCurrentSlice);\n if (availableActions != null && newActions != null) {\n for (int i = 0; i < newActions.size(); i++) {\n if (!availableActions.contains(newActions.get(i))) {\n throw new IllegalArgumentException(\"Trying to set an action that isn't available: \" + newActions.get(i));\n }\n }\n }\n mActions = newActions;\n updateActions();\n }\n\n /**\n * Set the mode this view should present in.\n */\n public void setMode(@SliceMode int mode) {\n setMode(mode, false);\n }\n\n /**\n * Set whether this view should allow scrollable content when presenting in {@link #MODE_LARGE}.\n */\n public void setScrollable(boolean isScrollable) {\n mIsScrollable = isScrollable;\n reinflate();\n }\n\n /**\n * Sets the listener to notify when an interaction events occur on the view.\n * @see EventInfo\n */\n public void setOnSliceActionListener(@Nullable OnSliceActionListener observer) {\n mSliceObserver = observer;\n mCurrentView.setSliceActionListener(mSliceObserver);\n }\n\n /**\n * @deprecated TO BE REMOVED; use {@link #setAccentColor(int)} instead.\n */\n @Deprecated\n public void setTint(int tintColor) {\n setAccentColor(tintColor);\n }\n\n /**\n * Contents of a slice such as icons, text, and controls (e.g. toggle) can be tinted. Normally\n * a color for tinting will be provided by the slice. Using this method will override\n * the slice-provided color information and instead tint elements with the color set here.\n *\n * @param accentColor the color to use for tinting contents of this view.\n */\n public void setAccentColor(@ColorInt int accentColor) {\n mThemeTintColor = accentColor;\n mCurrentView.setTint(accentColor);\n }\n\n /**\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setMode(@SliceMode int mode, boolean animate) {\n if (animate) {\n Log.e(TAG, \"Animation not supported yet\");\n }\n if (mMode == mode) {\n return;\n }\n mMode = mode;\n reinflate();\n }\n\n /**\n * @return the mode this view is presenting in.\n */\n @SliceMode\n public int getMode() {\n return mMode;\n }\n\n /**\n * @hide\n *\n * Whether this view should show a row of actions with it.\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public void setShowActionRow(boolean show) {\n mShowActions = show;\n updateActions();\n }\n\n /**\n * @return whether this view is showing a row of actions.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public boolean isShowingActionRow() {\n return mShowActions;\n }\n\n private void reinflate() {\n if (mCurrentSlice == null) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n mListContent = new ListContent(getContext(), mCurrentSlice, mAttrs, mDefStyleAttr, mDefStyleRes);\n if (!mListContent.isValid()) {\n mCurrentView.resetView();\n updateActions();\n return;\n }\n // TODO: Smarter mapping here from one state to the next.\n int mode = getMode();\n boolean isCurrentViewShortcut = mCurrentView instanceof ShortcutView;\n if (mode == MODE_SHORTCUT && !isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new ShortcutView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n } else if (mode != MODE_SHORTCUT && isCurrentViewShortcut) {\n removeAllViews();\n mCurrentView = new LargeTemplateView(getContext());\n addView(mCurrentView, getChildLp(mCurrentView));\n }\n mCurrentView.setMode(mode);\n mCurrentView.setSliceActionListener(mSliceObserver);\n if (mCurrentView instanceof LargeTemplateView) {\n ((LargeTemplateView) mCurrentView).setScrollable(mIsScrollable);\n ", "post_mask_code": " }\n mCurrentView.setStyle(mAttrs, mDefStyleAttr, mDefStyleRes);\n mCurrentView.setTint(getTintColor());\n // Check if the slice content is expired and show when it was last updated\n SliceMetadata sliceMetadata = SliceMetadata.from(getContext(), mCurrentSlice);\n long lastUpdated = sliceMetadata.getLastUpdatedTime();\n long expiry = sliceMetadata.getExpiry();\n long now = System.currentTimeMillis();\n mCurrentView.setLastUpdated(lastUpdated);\n boolean expired = expiry != 0 && expiry != SliceHints.INFINITY && now > expiry;\n mCurrentView.setShowLastUpdated(mShowLastUpdated && expired);\n // Set the slice\n mCurrentView.setSliceContent(mListContent);\n updateActions();\n }\n\n private void updateActions() {\n if (mActions == null || mActions.isEmpty()) {\n // No actions, hide the row, clear out the view\n mActionRow.setVisibility(View.GONE);\n mCurrentView.setSliceActions(null);\n return;\n }\n // TODO: take priority attached to actions into account\n if (mShowActions && mMode != MODE_SHORTCUT && mActions.size() >= 2) {\n // Show in action row if available\n mActionRow.setActions(mActions, getTintColor());\n mActionRow.setVisibility(View.VISIBLE);\n // Hide them on the template\n mCurrentView.setSliceActions(null);\n } else if (mActions.size() > 0) {\n // Otherwise set them on the template\n mCurrentView.setSliceActions(mActions);\n mActionRow.setVisibility(View.GONE);\n }\n }\n\n private int getTintColor() {\n if (mThemeTintColor != -1) {\n // Theme has specified a color, use that\n return mThemeTintColor;\n } else {\n final SliceItem colorItem = SliceQuery.findSubtype(mCurrentSlice, FORMAT_INT, SUBTYPE_COLOR);\n return colorItem != null ? colorItem.getInt() : SliceViewUtil.getColorAccent(getContext());\n }\n }\n\n private LayoutParams getChildLp(View child) {\n if (child instanceof ShortcutView) {\n return new LayoutParams(mShortcutSize, mShortcutSize);\n } else {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n }\n\n /**\n * @return String representation of the provided mode.\n * @hide\n */\n @RestrictTo(RestrictTo.Scope.LIBRARY)\n public static String modeToString(@SliceMode int mode) {\n switch(mode) {\n case MODE_SHORTCUT:\n return \"MODE SHORTCUT\";\n case MODE_SMALL:\n return \"MODE SMALL\";\n case MODE_LARGE:\n return \"MODE LARGE\";\n default:\n return \"unknown mode: \" + mode;\n }\n }\n\n Runnable mLongpressCheck = new Runnable() {\n\n @Override\n public void run() {\n if (mPressing && mLongClickListener != null) {\n mInLongpress = true;\n mLongClickListener.onLongClick(SliceView.this);\n performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);\n }\n }\n };\n}\n"} {"task_id": "Java_155", "language": "Java", "task_type": "method_signature", "source_file": "java/github/spring-projects/spring-framework/spring-core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java", "mask_start_position": 7612, "mask_end_position": 7692, "canonical_solution": "@Override\n public ListenableFuture submitListenable(Callable task) ", "pre_mask_code": "package org.springframework.core.task;\n\nimport java.io.Serializable;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.FutureTask;\nimport java.util.concurrent.ThreadFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ConcurrencyThrottleSupport;\nimport org.springframework.util.CustomizableThreadCreator;\nimport org.springframework.util.concurrent.ListenableFuture;\nimport org.springframework.util.concurrent.ListenableFutureTask;\n\n/**\n * {@link TaskExecutor} implementation that fires up a new Thread for each task,\n * executing it asynchronously.\n *\n *

Supports limiting concurrent threads through the \"concurrencyLimit\"\n * bean property. By default, the number of concurrent threads is unlimited.\n *\n *

NOTE: This implementation does not reuse threads! Consider a\n * thread-pooling TaskExecutor implementation instead, in particular for\n * executing a large number of short-lived tasks.\n *\n * @author Juergen Hoeller\n * @since 2.0\n * @see #setConcurrencyLimit\n * @see SyncTaskExecutor\n * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor\n */\n@SuppressWarnings(\"serial\")\npublic class SimpleAsyncTaskExecutor extends CustomizableThreadCreator implements AsyncListenableTaskExecutor, Serializable {\n\n /**\n * Permit any number of concurrent invocations: that is, don't throttle concurrency.\n * @see ConcurrencyThrottleSupport#UNBOUNDED_CONCURRENCY\n */\n public static final int UNBOUNDED_CONCURRENCY = ConcurrencyThrottleSupport.UNBOUNDED_CONCURRENCY;\n\n /**\n * Switch concurrency 'off': that is, don't allow any concurrent invocations.\n * @see ConcurrencyThrottleSupport#NO_CONCURRENCY\n */\n public static final int NO_CONCURRENCY = ConcurrencyThrottleSupport.NO_CONCURRENCY;\n\n /**\n * Internal concurrency throttle used by this executor.\n */\n private final ConcurrencyThrottleAdapter concurrencyThrottle = new ConcurrencyThrottleAdapter();\n\n @Nullable\n private ThreadFactory threadFactory;\n\n @Nullable\n private TaskDecorator taskDecorator;\n\n /**\n * Create a new SimpleAsyncTaskExecutor with default thread name prefix.\n */\n public SimpleAsyncTaskExecutor() {\n super();\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given thread name prefix.\n * @param threadNamePrefix the prefix to use for the names of newly created threads\n */\n public SimpleAsyncTaskExecutor(String threadNamePrefix) {\n super(threadNamePrefix);\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given external thread factory.\n * @param threadFactory the factory to use for creating new Threads\n */\n public SimpleAsyncTaskExecutor(ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Specify an external factory to use for creating new Threads,\n * instead of relying on the local properties of this executor.\n *

You may specify an inner ThreadFactory bean or also a ThreadFactory reference\n * obtained from JNDI (on a Jakarta EE server) or some other lookup mechanism.\n * @see #setThreadNamePrefix\n * @see #setThreadPriority\n */\n public void setThreadFactory(@Nullable ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Return the external factory to use for creating new Threads, if any.\n */\n @Nullable\n public final ThreadFactory getThreadFactory() {\n return this.threadFactory;\n }\n\n /**\n * Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}\n * about to be executed.\n *

Note that such a decorator is not necessarily being applied to the\n * user-supplied {@code Runnable}/{@code Callable} but rather to the actual\n * execution callback (which may be a wrapper around the user-supplied task).\n *

The primary use case is to set some execution context around the task's\n * invocation, or to provide some monitoring/statistics for task execution.\n *

NOTE: Exception handling in {@code TaskDecorator} implementations\n * is limited to plain {@code Runnable} execution via {@code execute} calls.\n * In case of {@code #submit} calls, the exposed {@code Runnable} will be a\n * {@code FutureTask} which does not propagate any exceptions; you might\n * have to cast it and call {@code Future#get} to evaluate exceptions.\n * @since 4.3\n */\n public final void setTaskDecorator(TaskDecorator taskDecorator) {\n this.taskDecorator = taskDecorator;\n }\n\n /**\n * Set the maximum number of parallel accesses allowed.\n * -1 indicates no concurrency limit at all.\n *

In principle, this limit can be changed at runtime,\n * although it is generally designed as a config time setting.\n * NOTE: Do not switch between -1 and any concrete limit at runtime,\n * as this will lead to inconsistent concurrency counts: A limit\n * of -1 effectively turns off concurrency counting completely.\n * @see #UNBOUNDED_CONCURRENCY\n */\n public void setConcurrencyLimit(int concurrencyLimit) {\n this.concurrencyThrottle.setConcurrencyLimit(concurrencyLimit);\n }\n\n /**\n * Return the maximum number of parallel accesses allowed.\n */\n public final int getConcurrencyLimit() {\n return this.concurrencyThrottle.getConcurrencyLimit();\n }\n\n /**\n * Return whether this throttle is currently active.\n * @return {@code true} if the concurrency limit for this instance is active\n * @see #getConcurrencyLimit()\n * @see #setConcurrencyLimit\n */\n public final boolean isThrottleActive() {\n return this.concurrencyThrottle.isThrottleActive();\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task) {\n execute(task, TIMEOUT_INDEFINITE);\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n *

Executes urgent tasks (with 'immediate' timeout) directly,\n * bypassing the concurrency throttle (if active). All other\n * tasks are subject to throttling.\n * @see #TIMEOUT_IMMEDIATE\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task, long startTimeout) {\n Assert.notNull(task, \"Runnable must not be null\");\n Runnable taskToUse = (this.taskDecorator != null ? this.taskDecorator.decorate(task) : task);\n if (isThrottleActive() && startTimeout > TIMEOUT_IMMEDIATE) {\n this.concurrencyThrottle.beforeAccess();\n doExecute(new ConcurrencyThrottlingRunnable(taskToUse));\n } else {\n doExecute(taskToUse);\n }\n }\n\n @Override\n public Future submit(Runnable task) {\n FutureTask future = new FutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public Future submit(Callable task) {\n FutureTask future = new FutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Runnable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n ", "post_mask_code": "{\n ListenableFutureTask future = new ListenableFutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n /**\n * Template method for the actual execution of a task.\n *

The default implementation creates a new Thread and starts it.\n * @param task the Runnable to execute\n * @see #setThreadFactory\n * @see #createThread\n * @see java.lang.Thread#start()\n */\n protected void doExecute(Runnable task) {\n Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));\n thread.start();\n }\n\n /**\n * Subclass of the general ConcurrencyThrottleSupport class,\n * making {@code beforeAccess()} and {@code afterAccess()}\n * visible to the surrounding class.\n */\n private static class ConcurrencyThrottleAdapter extends ConcurrencyThrottleSupport {\n\n @Override\n protected void beforeAccess() {\n super.beforeAccess();\n }\n\n @Override\n protected void afterAccess() {\n super.afterAccess();\n }\n }\n\n /**\n * This Runnable calls {@code afterAccess()} after the\n * target Runnable has finished its execution.\n */\n private class ConcurrencyThrottlingRunnable implements Runnable {\n\n private final Runnable target;\n\n public ConcurrencyThrottlingRunnable(Runnable target) {\n this.target = target;\n }\n\n @Override\n public void run() {\n try {\n this.target.run();\n } finally {\n concurrencyThrottle.afterAccess();\n }\n }\n }\n}\n"} {"task_id": "Java_156", "language": "Java", "task_type": "method_body", "source_file": "java/github/spring-projects/spring-framework/spring-core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java", "mask_start_position": 8648, "mask_end_position": 8693, "canonical_solution": "{\n super.beforeAccess();\n }", "pre_mask_code": "package org.springframework.core.task;\n\nimport java.io.Serializable;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.FutureTask;\nimport java.util.concurrent.ThreadFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ConcurrencyThrottleSupport;\nimport org.springframework.util.CustomizableThreadCreator;\nimport org.springframework.util.concurrent.ListenableFuture;\nimport org.springframework.util.concurrent.ListenableFutureTask;\n\n/**\n * {@link TaskExecutor} implementation that fires up a new Thread for each task,\n * executing it asynchronously.\n *\n *

Supports limiting concurrent threads through the \"concurrencyLimit\"\n * bean property. By default, the number of concurrent threads is unlimited.\n *\n *

NOTE: This implementation does not reuse threads! Consider a\n * thread-pooling TaskExecutor implementation instead, in particular for\n * executing a large number of short-lived tasks.\n *\n * @author Juergen Hoeller\n * @since 2.0\n * @see #setConcurrencyLimit\n * @see SyncTaskExecutor\n * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor\n */\n@SuppressWarnings(\"serial\")\npublic class SimpleAsyncTaskExecutor extends CustomizableThreadCreator implements AsyncListenableTaskExecutor, Serializable {\n\n /**\n * Permit any number of concurrent invocations: that is, don't throttle concurrency.\n * @see ConcurrencyThrottleSupport#UNBOUNDED_CONCURRENCY\n */\n public static final int UNBOUNDED_CONCURRENCY = ConcurrencyThrottleSupport.UNBOUNDED_CONCURRENCY;\n\n /**\n * Switch concurrency 'off': that is, don't allow any concurrent invocations.\n * @see ConcurrencyThrottleSupport#NO_CONCURRENCY\n */\n public static final int NO_CONCURRENCY = ConcurrencyThrottleSupport.NO_CONCURRENCY;\n\n /**\n * Internal concurrency throttle used by this executor.\n */\n private final ConcurrencyThrottleAdapter concurrencyThrottle = new ConcurrencyThrottleAdapter();\n\n @Nullable\n private ThreadFactory threadFactory;\n\n @Nullable\n private TaskDecorator taskDecorator;\n\n /**\n * Create a new SimpleAsyncTaskExecutor with default thread name prefix.\n */\n public SimpleAsyncTaskExecutor() {\n super();\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given thread name prefix.\n * @param threadNamePrefix the prefix to use for the names of newly created threads\n */\n public SimpleAsyncTaskExecutor(String threadNamePrefix) {\n super(threadNamePrefix);\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given external thread factory.\n * @param threadFactory the factory to use for creating new Threads\n */\n public SimpleAsyncTaskExecutor(ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Specify an external factory to use for creating new Threads,\n * instead of relying on the local properties of this executor.\n *

You may specify an inner ThreadFactory bean or also a ThreadFactory reference\n * obtained from JNDI (on a Jakarta EE server) or some other lookup mechanism.\n * @see #setThreadNamePrefix\n * @see #setThreadPriority\n */\n public void setThreadFactory(@Nullable ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Return the external factory to use for creating new Threads, if any.\n */\n @Nullable\n public final ThreadFactory getThreadFactory() {\n return this.threadFactory;\n }\n\n /**\n * Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}\n * about to be executed.\n *

Note that such a decorator is not necessarily being applied to the\n * user-supplied {@code Runnable}/{@code Callable} but rather to the actual\n * execution callback (which may be a wrapper around the user-supplied task).\n *

The primary use case is to set some execution context around the task's\n * invocation, or to provide some monitoring/statistics for task execution.\n *

NOTE: Exception handling in {@code TaskDecorator} implementations\n * is limited to plain {@code Runnable} execution via {@code execute} calls.\n * In case of {@code #submit} calls, the exposed {@code Runnable} will be a\n * {@code FutureTask} which does not propagate any exceptions; you might\n * have to cast it and call {@code Future#get} to evaluate exceptions.\n * @since 4.3\n */\n public final void setTaskDecorator(TaskDecorator taskDecorator) {\n this.taskDecorator = taskDecorator;\n }\n\n /**\n * Set the maximum number of parallel accesses allowed.\n * -1 indicates no concurrency limit at all.\n *

In principle, this limit can be changed at runtime,\n * although it is generally designed as a config time setting.\n * NOTE: Do not switch between -1 and any concrete limit at runtime,\n * as this will lead to inconsistent concurrency counts: A limit\n * of -1 effectively turns off concurrency counting completely.\n * @see #UNBOUNDED_CONCURRENCY\n */\n public void setConcurrencyLimit(int concurrencyLimit) {\n this.concurrencyThrottle.setConcurrencyLimit(concurrencyLimit);\n }\n\n /**\n * Return the maximum number of parallel accesses allowed.\n */\n public final int getConcurrencyLimit() {\n return this.concurrencyThrottle.getConcurrencyLimit();\n }\n\n /**\n * Return whether this throttle is currently active.\n * @return {@code true} if the concurrency limit for this instance is active\n * @see #getConcurrencyLimit()\n * @see #setConcurrencyLimit\n */\n public final boolean isThrottleActive() {\n return this.concurrencyThrottle.isThrottleActive();\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task) {\n execute(task, TIMEOUT_INDEFINITE);\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n *

Executes urgent tasks (with 'immediate' timeout) directly,\n * bypassing the concurrency throttle (if active). All other\n * tasks are subject to throttling.\n * @see #TIMEOUT_IMMEDIATE\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task, long startTimeout) {\n Assert.notNull(task, \"Runnable must not be null\");\n Runnable taskToUse = (this.taskDecorator != null ? this.taskDecorator.decorate(task) : task);\n if (isThrottleActive() && startTimeout > TIMEOUT_IMMEDIATE) {\n this.concurrencyThrottle.beforeAccess();\n doExecute(new ConcurrencyThrottlingRunnable(taskToUse));\n } else {\n doExecute(taskToUse);\n }\n }\n\n @Override\n public Future submit(Runnable task) {\n FutureTask future = new FutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public Future submit(Callable task) {\n FutureTask future = new FutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Runnable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Callable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n /**\n * Template method for the actual execution of a task.\n *

The default implementation creates a new Thread and starts it.\n * @param task the Runnable to execute\n * @see #setThreadFactory\n * @see #createThread\n * @see java.lang.Thread#start()\n */\n protected void doExecute(Runnable task) {\n Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));\n thread.start();\n }\n\n /**\n * Subclass of the general ConcurrencyThrottleSupport class,\n * making {@code beforeAccess()} and {@code afterAccess()}\n * visible to the surrounding class.\n */\n private static class ConcurrencyThrottleAdapter extends ConcurrencyThrottleSupport {\n\n @Override\n protected void beforeAccess() ", "post_mask_code": "\n\n @Override\n protected void afterAccess() {\n super.afterAccess();\n }\n }\n\n /**\n * This Runnable calls {@code afterAccess()} after the\n * target Runnable has finished its execution.\n */\n private class ConcurrencyThrottlingRunnable implements Runnable {\n\n private final Runnable target;\n\n public ConcurrencyThrottlingRunnable(Runnable target) {\n this.target = target;\n }\n\n @Override\n public void run() {\n try {\n this.target.run();\n } finally {\n concurrencyThrottle.afterAccess();\n }\n }\n }\n}\n"} {"task_id": "Java_157", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/spring-projects/spring-framework/spring-core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java", "mask_start_position": 9193, "mask_end_position": 9193, "canonical_solution": "", "pre_mask_code": "package org.springframework.core.task;\n\nimport java.io.Serializable;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.FutureTask;\nimport java.util.concurrent.ThreadFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ConcurrencyThrottleSupport;\nimport org.springframework.util.CustomizableThreadCreator;\nimport org.springframework.util.concurrent.ListenableFuture;\nimport org.springframework.util.concurrent.ListenableFutureTask;\n\n/**\n * {@link TaskExecutor} implementation that fires up a new Thread for each task,\n * executing it asynchronously.\n *\n *

Supports limiting concurrent threads through the \"concurrencyLimit\"\n * bean property. By default, the number of concurrent threads is unlimited.\n *\n *

NOTE: This implementation does not reuse threads! Consider a\n * thread-pooling TaskExecutor implementation instead, in particular for\n * executing a large number of short-lived tasks.\n *\n * @author Juergen Hoeller\n * @since 2.0\n * @see #setConcurrencyLimit\n * @see SyncTaskExecutor\n * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor\n */\n@SuppressWarnings(\"serial\")\npublic class SimpleAsyncTaskExecutor extends CustomizableThreadCreator implements AsyncListenableTaskExecutor, Serializable {\n\n /**\n * Permit any number of concurrent invocations: that is, don't throttle concurrency.\n * @see ConcurrencyThrottleSupport#UNBOUNDED_CONCURRENCY\n */\n public static final int UNBOUNDED_CONCURRENCY = ConcurrencyThrottleSupport.UNBOUNDED_CONCURRENCY;\n\n /**\n * Switch concurrency 'off': that is, don't allow any concurrent invocations.\n * @see ConcurrencyThrottleSupport#NO_CONCURRENCY\n */\n public static final int NO_CONCURRENCY = ConcurrencyThrottleSupport.NO_CONCURRENCY;\n\n /**\n * Internal concurrency throttle used by this executor.\n */\n private final ConcurrencyThrottleAdapter concurrencyThrottle = new ConcurrencyThrottleAdapter();\n\n @Nullable\n private ThreadFactory threadFactory;\n\n @Nullable\n private TaskDecorator taskDecorator;\n\n /**\n * Create a new SimpleAsyncTaskExecutor with default thread name prefix.\n */\n public SimpleAsyncTaskExecutor() {\n super();\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given thread name prefix.\n * @param threadNamePrefix the prefix to use for the names of newly created threads\n */\n public SimpleAsyncTaskExecutor(String threadNamePrefix) {\n super(threadNamePrefix);\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given external thread factory.\n * @param threadFactory the factory to use for creating new Threads\n */\n public SimpleAsyncTaskExecutor(ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Specify an external factory to use for creating new Threads,\n * instead of relying on the local properties of this executor.\n *

You may specify an inner ThreadFactory bean or also a ThreadFactory reference\n * obtained from JNDI (on a Jakarta EE server) or some other lookup mechanism.\n * @see #setThreadNamePrefix\n * @see #setThreadPriority\n */\n public void setThreadFactory(@Nullable ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Return the external factory to use for creating new Threads, if any.\n */\n @Nullable\n public final ThreadFactory getThreadFactory() {\n return this.threadFactory;\n }\n\n /**\n * Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}\n * about to be executed.\n *

Note that such a decorator is not necessarily being applied to the\n * user-supplied {@code Runnable}/{@code Callable} but rather to the actual\n * execution callback (which may be a wrapper around the user-supplied task).\n *

The primary use case is to set some execution context around the task's\n * invocation, or to provide some monitoring/statistics for task execution.\n *

NOTE: Exception handling in {@code TaskDecorator} implementations\n * is limited to plain {@code Runnable} execution via {@code execute} calls.\n * In case of {@code #submit} calls, the exposed {@code Runnable} will be a\n * {@code FutureTask} which does not propagate any exceptions; you might\n * have to cast it and call {@code Future#get} to evaluate exceptions.\n * @since 4.3\n */\n public final void setTaskDecorator(TaskDecorator taskDecorator) {\n this.taskDecorator = taskDecorator;\n }\n\n /**\n * Set the maximum number of parallel accesses allowed.\n * -1 indicates no concurrency limit at all.\n *

In principle, this limit can be changed at runtime,\n * although it is generally designed as a config time setting.\n * NOTE: Do not switch between -1 and any concrete limit at runtime,\n * as this will lead to inconsistent concurrency counts: A limit\n * of -1 effectively turns off concurrency counting completely.\n * @see #UNBOUNDED_CONCURRENCY\n */\n public void setConcurrencyLimit(int concurrencyLimit) {\n this.concurrencyThrottle.setConcurrencyLimit(concurrencyLimit);\n }\n\n /**\n * Return the maximum number of parallel accesses allowed.\n */\n public final int getConcurrencyLimit() {\n return this.concurrencyThrottle.getConcurrencyLimit();\n }\n\n /**\n * Return whether this throttle is currently active.\n * @return {@code true} if the concurrency limit for this instance is active\n * @see #getConcurrencyLimit()\n * @see #setConcurrencyLimit\n */\n public final boolean isThrottleActive() {\n return this.concurrencyThrottle.isThrottleActive();\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task) {\n execute(task, TIMEOUT_INDEFINITE);\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n *

Executes urgent tasks (with 'immediate' timeout) directly,\n * bypassing the concurrency throttle (if active). All other\n * tasks are subject to throttling.\n * @see #TIMEOUT_IMMEDIATE\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task, long startTimeout) {\n Assert.notNull(task, \"Runnable must not be null\");\n Runnable taskToUse = (this.taskDecorator != null ? this.taskDecorator.decorate(task) : task);\n if (isThrottleActive() && startTimeout > TIMEOUT_IMMEDIATE) {\n this.concurrencyThrottle.beforeAccess();\n doExecute(new ConcurrencyThrottlingRunnable(taskToUse));\n } else {\n doExecute(taskToUse);\n }\n }\n\n @Override\n public Future submit(Runnable task) {\n FutureTask future = new FutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public Future submit(Callable task) {\n FutureTask future = new FutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Runnable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Callable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n /**\n * Template method for the actual execution of a task.\n *

The default implementation creates a new Thread and starts it.\n * @param task the Runnable to execute\n * @see #setThreadFactory\n * @see #createThread\n * @see java.lang.Thread#start()\n */\n protected void doExecute(Runnable task) {\n Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));\n thread.start();\n }\n\n /**\n * Subclass of the general ConcurrencyThrottleSupport class,\n * making {@code beforeAccess()} and {@code afterAccess()}\n * visible to the surrounding class.\n */\n private static class ConcurrencyThrottleAdapter extends ConcurrencyThrottleSupport {\n\n @Override\n protected void beforeAccess() {\n super.beforeAccess();\n }\n\n @Override\n protected void afterAccess() {\n super.afterAccess();\n }\n }\n\n /**\n * This Runnable calls {@code afterAccess()} after the\n * target Runnable has finished its execution.\n */\n private class ConcurrencyThrottlingRunnable implements Runnable {\n\n private final Runnable target;\n\n public ConcurrencyThrottlingRunnable(Runnable target) {\n this.target = target;\n }\n\n @Override\n public void run() {", "post_mask_code": "\n try {\n this.target.run();\n } finally {\n concurrencyThrottle.afterAccess();\n }\n }\n }\n}\n"} {"task_id": "Java_158", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/spring-projects/spring-framework/spring-core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java", "mask_start_position": 9206, "mask_end_position": 9335, "canonical_solution": "try {\n this.target.run();\n } finally {\n concurrencyThrottle.afterAccess();\n }", "pre_mask_code": "package org.springframework.core.task;\n\nimport java.io.Serializable;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.FutureTask;\nimport java.util.concurrent.ThreadFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ConcurrencyThrottleSupport;\nimport org.springframework.util.CustomizableThreadCreator;\nimport org.springframework.util.concurrent.ListenableFuture;\nimport org.springframework.util.concurrent.ListenableFutureTask;\n\n/**\n * {@link TaskExecutor} implementation that fires up a new Thread for each task,\n * executing it asynchronously.\n *\n *

Supports limiting concurrent threads through the \"concurrencyLimit\"\n * bean property. By default, the number of concurrent threads is unlimited.\n *\n *

NOTE: This implementation does not reuse threads! Consider a\n * thread-pooling TaskExecutor implementation instead, in particular for\n * executing a large number of short-lived tasks.\n *\n * @author Juergen Hoeller\n * @since 2.0\n * @see #setConcurrencyLimit\n * @see SyncTaskExecutor\n * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor\n */\n@SuppressWarnings(\"serial\")\npublic class SimpleAsyncTaskExecutor extends CustomizableThreadCreator implements AsyncListenableTaskExecutor, Serializable {\n\n /**\n * Permit any number of concurrent invocations: that is, don't throttle concurrency.\n * @see ConcurrencyThrottleSupport#UNBOUNDED_CONCURRENCY\n */\n public static final int UNBOUNDED_CONCURRENCY = ConcurrencyThrottleSupport.UNBOUNDED_CONCURRENCY;\n\n /**\n * Switch concurrency 'off': that is, don't allow any concurrent invocations.\n * @see ConcurrencyThrottleSupport#NO_CONCURRENCY\n */\n public static final int NO_CONCURRENCY = ConcurrencyThrottleSupport.NO_CONCURRENCY;\n\n /**\n * Internal concurrency throttle used by this executor.\n */\n private final ConcurrencyThrottleAdapter concurrencyThrottle = new ConcurrencyThrottleAdapter();\n\n @Nullable\n private ThreadFactory threadFactory;\n\n @Nullable\n private TaskDecorator taskDecorator;\n\n /**\n * Create a new SimpleAsyncTaskExecutor with default thread name prefix.\n */\n public SimpleAsyncTaskExecutor() {\n super();\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given thread name prefix.\n * @param threadNamePrefix the prefix to use for the names of newly created threads\n */\n public SimpleAsyncTaskExecutor(String threadNamePrefix) {\n super(threadNamePrefix);\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given external thread factory.\n * @param threadFactory the factory to use for creating new Threads\n */\n public SimpleAsyncTaskExecutor(ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Specify an external factory to use for creating new Threads,\n * instead of relying on the local properties of this executor.\n *

You may specify an inner ThreadFactory bean or also a ThreadFactory reference\n * obtained from JNDI (on a Jakarta EE server) or some other lookup mechanism.\n * @see #setThreadNamePrefix\n * @see #setThreadPriority\n */\n public void setThreadFactory(@Nullable ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Return the external factory to use for creating new Threads, if any.\n */\n @Nullable\n public final ThreadFactory getThreadFactory() {\n return this.threadFactory;\n }\n\n /**\n * Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}\n * about to be executed.\n *

Note that such a decorator is not necessarily being applied to the\n * user-supplied {@code Runnable}/{@code Callable} but rather to the actual\n * execution callback (which may be a wrapper around the user-supplied task).\n *

The primary use case is to set some execution context around the task's\n * invocation, or to provide some monitoring/statistics for task execution.\n *

NOTE: Exception handling in {@code TaskDecorator} implementations\n * is limited to plain {@code Runnable} execution via {@code execute} calls.\n * In case of {@code #submit} calls, the exposed {@code Runnable} will be a\n * {@code FutureTask} which does not propagate any exceptions; you might\n * have to cast it and call {@code Future#get} to evaluate exceptions.\n * @since 4.3\n */\n public final void setTaskDecorator(TaskDecorator taskDecorator) {\n this.taskDecorator = taskDecorator;\n }\n\n /**\n * Set the maximum number of parallel accesses allowed.\n * -1 indicates no concurrency limit at all.\n *

In principle, this limit can be changed at runtime,\n * although it is generally designed as a config time setting.\n * NOTE: Do not switch between -1 and any concrete limit at runtime,\n * as this will lead to inconsistent concurrency counts: A limit\n * of -1 effectively turns off concurrency counting completely.\n * @see #UNBOUNDED_CONCURRENCY\n */\n public void setConcurrencyLimit(int concurrencyLimit) {\n this.concurrencyThrottle.setConcurrencyLimit(concurrencyLimit);\n }\n\n /**\n * Return the maximum number of parallel accesses allowed.\n */\n public final int getConcurrencyLimit() {\n return this.concurrencyThrottle.getConcurrencyLimit();\n }\n\n /**\n * Return whether this throttle is currently active.\n * @return {@code true} if the concurrency limit for this instance is active\n * @see #getConcurrencyLimit()\n * @see #setConcurrencyLimit\n */\n public final boolean isThrottleActive() {\n return this.concurrencyThrottle.isThrottleActive();\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task) {\n execute(task, TIMEOUT_INDEFINITE);\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n *

Executes urgent tasks (with 'immediate' timeout) directly,\n * bypassing the concurrency throttle (if active). All other\n * tasks are subject to throttling.\n * @see #TIMEOUT_IMMEDIATE\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task, long startTimeout) {\n Assert.notNull(task, \"Runnable must not be null\");\n Runnable taskToUse = (this.taskDecorator != null ? this.taskDecorator.decorate(task) : task);\n if (isThrottleActive() && startTimeout > TIMEOUT_IMMEDIATE) {\n this.concurrencyThrottle.beforeAccess();\n doExecute(new ConcurrencyThrottlingRunnable(taskToUse));\n } else {\n doExecute(taskToUse);\n }\n }\n\n @Override\n public Future submit(Runnable task) {\n FutureTask future = new FutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public Future submit(Callable task) {\n FutureTask future = new FutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Runnable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Callable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n /**\n * Template method for the actual execution of a task.\n *

The default implementation creates a new Thread and starts it.\n * @param task the Runnable to execute\n * @see #setThreadFactory\n * @see #createThread\n * @see java.lang.Thread#start()\n */\n protected void doExecute(Runnable task) {\n Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));\n thread.start();\n }\n\n /**\n * Subclass of the general ConcurrencyThrottleSupport class,\n * making {@code beforeAccess()} and {@code afterAccess()}\n * visible to the surrounding class.\n */\n private static class ConcurrencyThrottleAdapter extends ConcurrencyThrottleSupport {\n\n @Override\n protected void beforeAccess() {\n super.beforeAccess();\n }\n\n @Override\n protected void afterAccess() {\n super.afterAccess();\n }\n }\n\n /**\n * This Runnable calls {@code afterAccess()} after the\n * target Runnable has finished its execution.\n */\n private class ConcurrencyThrottlingRunnable implements Runnable {\n\n private final Runnable target;\n\n public ConcurrencyThrottlingRunnable(Runnable target) {\n this.target = target;\n }\n\n @Override\n public void run() {\n ", "post_mask_code": "\n }\n }\n}\n"} {"task_id": "Java_159", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/spring-projects/spring-framework/spring-core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java", "mask_start_position": 9344, "mask_end_position": 9345, "canonical_solution": "}", "pre_mask_code": "package org.springframework.core.task;\n\nimport java.io.Serializable;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.FutureTask;\nimport java.util.concurrent.ThreadFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ConcurrencyThrottleSupport;\nimport org.springframework.util.CustomizableThreadCreator;\nimport org.springframework.util.concurrent.ListenableFuture;\nimport org.springframework.util.concurrent.ListenableFutureTask;\n\n/**\n * {@link TaskExecutor} implementation that fires up a new Thread for each task,\n * executing it asynchronously.\n *\n *

Supports limiting concurrent threads through the \"concurrencyLimit\"\n * bean property. By default, the number of concurrent threads is unlimited.\n *\n *

NOTE: This implementation does not reuse threads! Consider a\n * thread-pooling TaskExecutor implementation instead, in particular for\n * executing a large number of short-lived tasks.\n *\n * @author Juergen Hoeller\n * @since 2.0\n * @see #setConcurrencyLimit\n * @see SyncTaskExecutor\n * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor\n */\n@SuppressWarnings(\"serial\")\npublic class SimpleAsyncTaskExecutor extends CustomizableThreadCreator implements AsyncListenableTaskExecutor, Serializable {\n\n /**\n * Permit any number of concurrent invocations: that is, don't throttle concurrency.\n * @see ConcurrencyThrottleSupport#UNBOUNDED_CONCURRENCY\n */\n public static final int UNBOUNDED_CONCURRENCY = ConcurrencyThrottleSupport.UNBOUNDED_CONCURRENCY;\n\n /**\n * Switch concurrency 'off': that is, don't allow any concurrent invocations.\n * @see ConcurrencyThrottleSupport#NO_CONCURRENCY\n */\n public static final int NO_CONCURRENCY = ConcurrencyThrottleSupport.NO_CONCURRENCY;\n\n /**\n * Internal concurrency throttle used by this executor.\n */\n private final ConcurrencyThrottleAdapter concurrencyThrottle = new ConcurrencyThrottleAdapter();\n\n @Nullable\n private ThreadFactory threadFactory;\n\n @Nullable\n private TaskDecorator taskDecorator;\n\n /**\n * Create a new SimpleAsyncTaskExecutor with default thread name prefix.\n */\n public SimpleAsyncTaskExecutor() {\n super();\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given thread name prefix.\n * @param threadNamePrefix the prefix to use for the names of newly created threads\n */\n public SimpleAsyncTaskExecutor(String threadNamePrefix) {\n super(threadNamePrefix);\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given external thread factory.\n * @param threadFactory the factory to use for creating new Threads\n */\n public SimpleAsyncTaskExecutor(ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Specify an external factory to use for creating new Threads,\n * instead of relying on the local properties of this executor.\n *

You may specify an inner ThreadFactory bean or also a ThreadFactory reference\n * obtained from JNDI (on a Jakarta EE server) or some other lookup mechanism.\n * @see #setThreadNamePrefix\n * @see #setThreadPriority\n */\n public void setThreadFactory(@Nullable ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Return the external factory to use for creating new Threads, if any.\n */\n @Nullable\n public final ThreadFactory getThreadFactory() {\n return this.threadFactory;\n }\n\n /**\n * Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}\n * about to be executed.\n *

Note that such a decorator is not necessarily being applied to the\n * user-supplied {@code Runnable}/{@code Callable} but rather to the actual\n * execution callback (which may be a wrapper around the user-supplied task).\n *

The primary use case is to set some execution context around the task's\n * invocation, or to provide some monitoring/statistics for task execution.\n *

NOTE: Exception handling in {@code TaskDecorator} implementations\n * is limited to plain {@code Runnable} execution via {@code execute} calls.\n * In case of {@code #submit} calls, the exposed {@code Runnable} will be a\n * {@code FutureTask} which does not propagate any exceptions; you might\n * have to cast it and call {@code Future#get} to evaluate exceptions.\n * @since 4.3\n */\n public final void setTaskDecorator(TaskDecorator taskDecorator) {\n this.taskDecorator = taskDecorator;\n }\n\n /**\n * Set the maximum number of parallel accesses allowed.\n * -1 indicates no concurrency limit at all.\n *

In principle, this limit can be changed at runtime,\n * although it is generally designed as a config time setting.\n * NOTE: Do not switch between -1 and any concrete limit at runtime,\n * as this will lead to inconsistent concurrency counts: A limit\n * of -1 effectively turns off concurrency counting completely.\n * @see #UNBOUNDED_CONCURRENCY\n */\n public void setConcurrencyLimit(int concurrencyLimit) {\n this.concurrencyThrottle.setConcurrencyLimit(concurrencyLimit);\n }\n\n /**\n * Return the maximum number of parallel accesses allowed.\n */\n public final int getConcurrencyLimit() {\n return this.concurrencyThrottle.getConcurrencyLimit();\n }\n\n /**\n * Return whether this throttle is currently active.\n * @return {@code true} if the concurrency limit for this instance is active\n * @see #getConcurrencyLimit()\n * @see #setConcurrencyLimit\n */\n public final boolean isThrottleActive() {\n return this.concurrencyThrottle.isThrottleActive();\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task) {\n execute(task, TIMEOUT_INDEFINITE);\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n *

Executes urgent tasks (with 'immediate' timeout) directly,\n * bypassing the concurrency throttle (if active). All other\n * tasks are subject to throttling.\n * @see #TIMEOUT_IMMEDIATE\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task, long startTimeout) {\n Assert.notNull(task, \"Runnable must not be null\");\n Runnable taskToUse = (this.taskDecorator != null ? this.taskDecorator.decorate(task) : task);\n if (isThrottleActive() && startTimeout > TIMEOUT_IMMEDIATE) {\n this.concurrencyThrottle.beforeAccess();\n doExecute(new ConcurrencyThrottlingRunnable(taskToUse));\n } else {\n doExecute(taskToUse);\n }\n }\n\n @Override\n public Future submit(Runnable task) {\n FutureTask future = new FutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public Future submit(Callable task) {\n FutureTask future = new FutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Runnable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Callable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n /**\n * Template method for the actual execution of a task.\n *

The default implementation creates a new Thread and starts it.\n * @param task the Runnable to execute\n * @see #setThreadFactory\n * @see #createThread\n * @see java.lang.Thread#start()\n */\n protected void doExecute(Runnable task) {\n Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));\n thread.start();\n }\n\n /**\n * Subclass of the general ConcurrencyThrottleSupport class,\n * making {@code beforeAccess()} and {@code afterAccess()}\n * visible to the surrounding class.\n */\n private static class ConcurrencyThrottleAdapter extends ConcurrencyThrottleSupport {\n\n @Override\n protected void beforeAccess() {\n super.beforeAccess();\n }\n\n @Override\n protected void afterAccess() {\n super.afterAccess();\n }\n }\n\n /**\n * This Runnable calls {@code afterAccess()} after the\n * target Runnable has finished its execution.\n */\n private class ConcurrencyThrottlingRunnable implements Runnable {\n\n private final Runnable target;\n\n public ConcurrencyThrottlingRunnable(Runnable target) {\n this.target = target;\n }\n\n @Override\n public void run() {\n try {\n this.target.run();\n } finally {\n concurrencyThrottle.afterAccess();\n }\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_160", "language": "Java", "task_type": "single_line", "source_file": "java/github/spring-projects/spring-framework/spring-core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java", "mask_start_position": 5265, "mask_end_position": 5292, "canonical_solution": "ncyLimit(concurrencyLimit);", "pre_mask_code": "package org.springframework.core.task;\n\nimport java.io.Serializable;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.FutureTask;\nimport java.util.concurrent.ThreadFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ConcurrencyThrottleSupport;\nimport org.springframework.util.CustomizableThreadCreator;\nimport org.springframework.util.concurrent.ListenableFuture;\nimport org.springframework.util.concurrent.ListenableFutureTask;\n\n/**\n * {@link TaskExecutor} implementation that fires up a new Thread for each task,\n * executing it asynchronously.\n *\n *

Supports limiting concurrent threads through the \"concurrencyLimit\"\n * bean property. By default, the number of concurrent threads is unlimited.\n *\n *

NOTE: This implementation does not reuse threads! Consider a\n * thread-pooling TaskExecutor implementation instead, in particular for\n * executing a large number of short-lived tasks.\n *\n * @author Juergen Hoeller\n * @since 2.0\n * @see #setConcurrencyLimit\n * @see SyncTaskExecutor\n * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor\n */\n@SuppressWarnings(\"serial\")\npublic class SimpleAsyncTaskExecutor extends CustomizableThreadCreator implements AsyncListenableTaskExecutor, Serializable {\n\n /**\n * Permit any number of concurrent invocations: that is, don't throttle concurrency.\n * @see ConcurrencyThrottleSupport#UNBOUNDED_CONCURRENCY\n */\n public static final int UNBOUNDED_CONCURRENCY = ConcurrencyThrottleSupport.UNBOUNDED_CONCURRENCY;\n\n /**\n * Switch concurrency 'off': that is, don't allow any concurrent invocations.\n * @see ConcurrencyThrottleSupport#NO_CONCURRENCY\n */\n public static final int NO_CONCURRENCY = ConcurrencyThrottleSupport.NO_CONCURRENCY;\n\n /**\n * Internal concurrency throttle used by this executor.\n */\n private final ConcurrencyThrottleAdapter concurrencyThrottle = new ConcurrencyThrottleAdapter();\n\n @Nullable\n private ThreadFactory threadFactory;\n\n @Nullable\n private TaskDecorator taskDecorator;\n\n /**\n * Create a new SimpleAsyncTaskExecutor with default thread name prefix.\n */\n public SimpleAsyncTaskExecutor() {\n super();\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given thread name prefix.\n * @param threadNamePrefix the prefix to use for the names of newly created threads\n */\n public SimpleAsyncTaskExecutor(String threadNamePrefix) {\n super(threadNamePrefix);\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given external thread factory.\n * @param threadFactory the factory to use for creating new Threads\n */\n public SimpleAsyncTaskExecutor(ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Specify an external factory to use for creating new Threads,\n * instead of relying on the local properties of this executor.\n *

You may specify an inner ThreadFactory bean or also a ThreadFactory reference\n * obtained from JNDI (on a Jakarta EE server) or some other lookup mechanism.\n * @see #setThreadNamePrefix\n * @see #setThreadPriority\n */\n public void setThreadFactory(@Nullable ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Return the external factory to use for creating new Threads, if any.\n */\n @Nullable\n public final ThreadFactory getThreadFactory() {\n return this.threadFactory;\n }\n\n /**\n * Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}\n * about to be executed.\n *

Note that such a decorator is not necessarily being applied to the\n * user-supplied {@code Runnable}/{@code Callable} but rather to the actual\n * execution callback (which may be a wrapper around the user-supplied task).\n *

The primary use case is to set some execution context around the task's\n * invocation, or to provide some monitoring/statistics for task execution.\n *

NOTE: Exception handling in {@code TaskDecorator} implementations\n * is limited to plain {@code Runnable} execution via {@code execute} calls.\n * In case of {@code #submit} calls, the exposed {@code Runnable} will be a\n * {@code FutureTask} which does not propagate any exceptions; you might\n * have to cast it and call {@code Future#get} to evaluate exceptions.\n * @since 4.3\n */\n public final void setTaskDecorator(TaskDecorator taskDecorator) {\n this.taskDecorator = taskDecorator;\n }\n\n /**\n * Set the maximum number of parallel accesses allowed.\n * -1 indicates no concurrency limit at all.\n *

In principle, this limit can be changed at runtime,\n * although it is generally designed as a config time setting.\n * NOTE: Do not switch between -1 and any concrete limit at runtime,\n * as this will lead to inconsistent concurrency counts: A limit\n * of -1 effectively turns off concurrency counting completely.\n * @see #UNBOUNDED_CONCURRENCY\n */\n public void setConcurrencyLimit(int concurrencyLimit) {\n this.concurrencyThrottle.setConcurre", "post_mask_code": "\n }\n\n /**\n * Return the maximum number of parallel accesses allowed.\n */\n public final int getConcurrencyLimit() {\n return this.concurrencyThrottle.getConcurrencyLimit();\n }\n\n /**\n * Return whether this throttle is currently active.\n * @return {@code true} if the concurrency limit for this instance is active\n * @see #getConcurrencyLimit()\n * @see #setConcurrencyLimit\n */\n public final boolean isThrottleActive() {\n return this.concurrencyThrottle.isThrottleActive();\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task) {\n execute(task, TIMEOUT_INDEFINITE);\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n *

Executes urgent tasks (with 'immediate' timeout) directly,\n * bypassing the concurrency throttle (if active). All other\n * tasks are subject to throttling.\n * @see #TIMEOUT_IMMEDIATE\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task, long startTimeout) {\n Assert.notNull(task, \"Runnable must not be null\");\n Runnable taskToUse = (this.taskDecorator != null ? this.taskDecorator.decorate(task) : task);\n if (isThrottleActive() && startTimeout > TIMEOUT_IMMEDIATE) {\n this.concurrencyThrottle.beforeAccess();\n doExecute(new ConcurrencyThrottlingRunnable(taskToUse));\n } else {\n doExecute(taskToUse);\n }\n }\n\n @Override\n public Future submit(Runnable task) {\n FutureTask future = new FutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public Future submit(Callable task) {\n FutureTask future = new FutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Runnable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Callable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n /**\n * Template method for the actual execution of a task.\n *

The default implementation creates a new Thread and starts it.\n * @param task the Runnable to execute\n * @see #setThreadFactory\n * @see #createThread\n * @see java.lang.Thread#start()\n */\n protected void doExecute(Runnable task) {\n Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));\n thread.start();\n }\n\n /**\n * Subclass of the general ConcurrencyThrottleSupport class,\n * making {@code beforeAccess()} and {@code afterAccess()}\n * visible to the surrounding class.\n */\n private static class ConcurrencyThrottleAdapter extends ConcurrencyThrottleSupport {\n\n @Override\n protected void beforeAccess() {\n super.beforeAccess();\n }\n\n @Override\n protected void afterAccess() {\n super.afterAccess();\n }\n }\n\n /**\n * This Runnable calls {@code afterAccess()} after the\n * target Runnable has finished its execution.\n */\n private class ConcurrencyThrottlingRunnable implements Runnable {\n\n private final Runnable target;\n\n public ConcurrencyThrottlingRunnable(Runnable target) {\n this.target = target;\n }\n\n @Override\n public void run() {\n try {\n this.target.run();\n } finally {\n concurrencyThrottle.afterAccess();\n }\n }\n }\n}\n"} {"task_id": "Java_161", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/spring-projects/spring-framework/spring-core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java", "mask_start_position": 6002, "mask_end_position": 6101, "canonical_solution": "@Override\n public void execute(Runnable task) {\n execute(task, TIMEOUT_INDEFINITE);\n }", "pre_mask_code": "package org.springframework.core.task;\n\nimport java.io.Serializable;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.FutureTask;\nimport java.util.concurrent.ThreadFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ConcurrencyThrottleSupport;\nimport org.springframework.util.CustomizableThreadCreator;\nimport org.springframework.util.concurrent.ListenableFuture;\nimport org.springframework.util.concurrent.ListenableFutureTask;\n\n/**\n * {@link TaskExecutor} implementation that fires up a new Thread for each task,\n * executing it asynchronously.\n *\n *

Supports limiting concurrent threads through the \"concurrencyLimit\"\n * bean property. By default, the number of concurrent threads is unlimited.\n *\n *

NOTE: This implementation does not reuse threads! Consider a\n * thread-pooling TaskExecutor implementation instead, in particular for\n * executing a large number of short-lived tasks.\n *\n * @author Juergen Hoeller\n * @since 2.0\n * @see #setConcurrencyLimit\n * @see SyncTaskExecutor\n * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor\n */\n@SuppressWarnings(\"serial\")\npublic class SimpleAsyncTaskExecutor extends CustomizableThreadCreator implements AsyncListenableTaskExecutor, Serializable {\n\n /**\n * Permit any number of concurrent invocations: that is, don't throttle concurrency.\n * @see ConcurrencyThrottleSupport#UNBOUNDED_CONCURRENCY\n */\n public static final int UNBOUNDED_CONCURRENCY = ConcurrencyThrottleSupport.UNBOUNDED_CONCURRENCY;\n\n /**\n * Switch concurrency 'off': that is, don't allow any concurrent invocations.\n * @see ConcurrencyThrottleSupport#NO_CONCURRENCY\n */\n public static final int NO_CONCURRENCY = ConcurrencyThrottleSupport.NO_CONCURRENCY;\n\n /**\n * Internal concurrency throttle used by this executor.\n */\n private final ConcurrencyThrottleAdapter concurrencyThrottle = new ConcurrencyThrottleAdapter();\n\n @Nullable\n private ThreadFactory threadFactory;\n\n @Nullable\n private TaskDecorator taskDecorator;\n\n /**\n * Create a new SimpleAsyncTaskExecutor with default thread name prefix.\n */\n public SimpleAsyncTaskExecutor() {\n super();\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given thread name prefix.\n * @param threadNamePrefix the prefix to use for the names of newly created threads\n */\n public SimpleAsyncTaskExecutor(String threadNamePrefix) {\n super(threadNamePrefix);\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given external thread factory.\n * @param threadFactory the factory to use for creating new Threads\n */\n public SimpleAsyncTaskExecutor(ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Specify an external factory to use for creating new Threads,\n * instead of relying on the local properties of this executor.\n *

You may specify an inner ThreadFactory bean or also a ThreadFactory reference\n * obtained from JNDI (on a Jakarta EE server) or some other lookup mechanism.\n * @see #setThreadNamePrefix\n * @see #setThreadPriority\n */\n public void setThreadFactory(@Nullable ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Return the external factory to use for creating new Threads, if any.\n */\n @Nullable\n public final ThreadFactory getThreadFactory() {\n return this.threadFactory;\n }\n\n /**\n * Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}\n * about to be executed.\n *

Note that such a decorator is not necessarily being applied to the\n * user-supplied {@code Runnable}/{@code Callable} but rather to the actual\n * execution callback (which may be a wrapper around the user-supplied task).\n *

The primary use case is to set some execution context around the task's\n * invocation, or to provide some monitoring/statistics for task execution.\n *

NOTE: Exception handling in {@code TaskDecorator} implementations\n * is limited to plain {@code Runnable} execution via {@code execute} calls.\n * In case of {@code #submit} calls, the exposed {@code Runnable} will be a\n * {@code FutureTask} which does not propagate any exceptions; you might\n * have to cast it and call {@code Future#get} to evaluate exceptions.\n * @since 4.3\n */\n public final void setTaskDecorator(TaskDecorator taskDecorator) {\n this.taskDecorator = taskDecorator;\n }\n\n /**\n * Set the maximum number of parallel accesses allowed.\n * -1 indicates no concurrency limit at all.\n *

In principle, this limit can be changed at runtime,\n * although it is generally designed as a config time setting.\n * NOTE: Do not switch between -1 and any concrete limit at runtime,\n * as this will lead to inconsistent concurrency counts: A limit\n * of -1 effectively turns off concurrency counting completely.\n * @see #UNBOUNDED_CONCURRENCY\n */\n public void setConcurrencyLimit(int concurrencyLimit) {\n this.concurrencyThrottle.setConcurrencyLimit(concurrencyLimit);\n }\n\n /**\n * Return the maximum number of parallel accesses allowed.\n */\n public final int getConcurrencyLimit() {\n return this.concurrencyThrottle.getConcurrencyLimit();\n }\n\n /**\n * Return whether this throttle is currently active.\n * @return {@code true} if the concurrency limit for this instance is active\n * @see #getConcurrencyLimit()\n * @see #setConcurrencyLimit\n */\n public final boolean isThrottleActive() {\n return this.concurrencyThrottle.isThrottleActive();\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n * @see #doExecute(Runnable)\n */\n ", "post_mask_code": "\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n *

Executes urgent tasks (with 'immediate' timeout) directly,\n * bypassing the concurrency throttle (if active). All other\n * tasks are subject to throttling.\n * @see #TIMEOUT_IMMEDIATE\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task, long startTimeout) {\n Assert.notNull(task, \"Runnable must not be null\");\n Runnable taskToUse = (this.taskDecorator != null ? this.taskDecorator.decorate(task) : task);\n if (isThrottleActive() && startTimeout > TIMEOUT_IMMEDIATE) {\n this.concurrencyThrottle.beforeAccess();\n doExecute(new ConcurrencyThrottlingRunnable(taskToUse));\n } else {\n doExecute(taskToUse);\n }\n }\n\n @Override\n public Future submit(Runnable task) {\n FutureTask future = new FutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public Future submit(Callable task) {\n FutureTask future = new FutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Runnable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Callable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n /**\n * Template method for the actual execution of a task.\n *

The default implementation creates a new Thread and starts it.\n * @param task the Runnable to execute\n * @see #setThreadFactory\n * @see #createThread\n * @see java.lang.Thread#start()\n */\n protected void doExecute(Runnable task) {\n Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));\n thread.start();\n }\n\n /**\n * Subclass of the general ConcurrencyThrottleSupport class,\n * making {@code beforeAccess()} and {@code afterAccess()}\n * visible to the surrounding class.\n */\n private static class ConcurrencyThrottleAdapter extends ConcurrencyThrottleSupport {\n\n @Override\n protected void beforeAccess() {\n super.beforeAccess();\n }\n\n @Override\n protected void afterAccess() {\n super.afterAccess();\n }\n }\n\n /**\n * This Runnable calls {@code afterAccess()} after the\n * target Runnable has finished its execution.\n */\n private class ConcurrencyThrottlingRunnable implements Runnable {\n\n private final Runnable target;\n\n public ConcurrencyThrottlingRunnable(Runnable target) {\n this.target = target;\n }\n\n @Override\n public void run() {\n try {\n this.target.run();\n } finally {\n concurrencyThrottle.afterAccess();\n }\n }\n }\n}\n"} {"task_id": "Java_162", "language": "Java", "task_type": "if_statement", "source_file": "java/github/spring-projects/spring-framework/spring-core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java", "mask_start_position": 6720, "mask_end_position": 6964, "canonical_solution": "if (isThrottleActive() && startTimeout > TIMEOUT_IMMEDIATE) {\n this.concurrencyThrottle.beforeAccess();\n doExecute(new ConcurrencyThrottlingRunnable(taskToUse));\n } else {\n doExecute(taskToUse);\n }", "pre_mask_code": "package org.springframework.core.task;\n\nimport java.io.Serializable;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.FutureTask;\nimport java.util.concurrent.ThreadFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ConcurrencyThrottleSupport;\nimport org.springframework.util.CustomizableThreadCreator;\nimport org.springframework.util.concurrent.ListenableFuture;\nimport org.springframework.util.concurrent.ListenableFutureTask;\n\n/**\n * {@link TaskExecutor} implementation that fires up a new Thread for each task,\n * executing it asynchronously.\n *\n *

Supports limiting concurrent threads through the \"concurrencyLimit\"\n * bean property. By default, the number of concurrent threads is unlimited.\n *\n *

NOTE: This implementation does not reuse threads! Consider a\n * thread-pooling TaskExecutor implementation instead, in particular for\n * executing a large number of short-lived tasks.\n *\n * @author Juergen Hoeller\n * @since 2.0\n * @see #setConcurrencyLimit\n * @see SyncTaskExecutor\n * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor\n */\n@SuppressWarnings(\"serial\")\npublic class SimpleAsyncTaskExecutor extends CustomizableThreadCreator implements AsyncListenableTaskExecutor, Serializable {\n\n /**\n * Permit any number of concurrent invocations: that is, don't throttle concurrency.\n * @see ConcurrencyThrottleSupport#UNBOUNDED_CONCURRENCY\n */\n public static final int UNBOUNDED_CONCURRENCY = ConcurrencyThrottleSupport.UNBOUNDED_CONCURRENCY;\n\n /**\n * Switch concurrency 'off': that is, don't allow any concurrent invocations.\n * @see ConcurrencyThrottleSupport#NO_CONCURRENCY\n */\n public static final int NO_CONCURRENCY = ConcurrencyThrottleSupport.NO_CONCURRENCY;\n\n /**\n * Internal concurrency throttle used by this executor.\n */\n private final ConcurrencyThrottleAdapter concurrencyThrottle = new ConcurrencyThrottleAdapter();\n\n @Nullable\n private ThreadFactory threadFactory;\n\n @Nullable\n private TaskDecorator taskDecorator;\n\n /**\n * Create a new SimpleAsyncTaskExecutor with default thread name prefix.\n */\n public SimpleAsyncTaskExecutor() {\n super();\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given thread name prefix.\n * @param threadNamePrefix the prefix to use for the names of newly created threads\n */\n public SimpleAsyncTaskExecutor(String threadNamePrefix) {\n super(threadNamePrefix);\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given external thread factory.\n * @param threadFactory the factory to use for creating new Threads\n */\n public SimpleAsyncTaskExecutor(ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Specify an external factory to use for creating new Threads,\n * instead of relying on the local properties of this executor.\n *

You may specify an inner ThreadFactory bean or also a ThreadFactory reference\n * obtained from JNDI (on a Jakarta EE server) or some other lookup mechanism.\n * @see #setThreadNamePrefix\n * @see #setThreadPriority\n */\n public void setThreadFactory(@Nullable ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Return the external factory to use for creating new Threads, if any.\n */\n @Nullable\n public final ThreadFactory getThreadFactory() {\n return this.threadFactory;\n }\n\n /**\n * Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}\n * about to be executed.\n *

Note that such a decorator is not necessarily being applied to the\n * user-supplied {@code Runnable}/{@code Callable} but rather to the actual\n * execution callback (which may be a wrapper around the user-supplied task).\n *

The primary use case is to set some execution context around the task's\n * invocation, or to provide some monitoring/statistics for task execution.\n *

NOTE: Exception handling in {@code TaskDecorator} implementations\n * is limited to plain {@code Runnable} execution via {@code execute} calls.\n * In case of {@code #submit} calls, the exposed {@code Runnable} will be a\n * {@code FutureTask} which does not propagate any exceptions; you might\n * have to cast it and call {@code Future#get} to evaluate exceptions.\n * @since 4.3\n */\n public final void setTaskDecorator(TaskDecorator taskDecorator) {\n this.taskDecorator = taskDecorator;\n }\n\n /**\n * Set the maximum number of parallel accesses allowed.\n * -1 indicates no concurrency limit at all.\n *

In principle, this limit can be changed at runtime,\n * although it is generally designed as a config time setting.\n * NOTE: Do not switch between -1 and any concrete limit at runtime,\n * as this will lead to inconsistent concurrency counts: A limit\n * of -1 effectively turns off concurrency counting completely.\n * @see #UNBOUNDED_CONCURRENCY\n */\n public void setConcurrencyLimit(int concurrencyLimit) {\n this.concurrencyThrottle.setConcurrencyLimit(concurrencyLimit);\n }\n\n /**\n * Return the maximum number of parallel accesses allowed.\n */\n public final int getConcurrencyLimit() {\n return this.concurrencyThrottle.getConcurrencyLimit();\n }\n\n /**\n * Return whether this throttle is currently active.\n * @return {@code true} if the concurrency limit for this instance is active\n * @see #getConcurrencyLimit()\n * @see #setConcurrencyLimit\n */\n public final boolean isThrottleActive() {\n return this.concurrencyThrottle.isThrottleActive();\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task) {\n execute(task, TIMEOUT_INDEFINITE);\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n *

Executes urgent tasks (with 'immediate' timeout) directly,\n * bypassing the concurrency throttle (if active). All other\n * tasks are subject to throttling.\n * @see #TIMEOUT_IMMEDIATE\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task, long startTimeout) {\n Assert.notNull(task, \"Runnable must not be null\");\n Runnable taskToUse = (this.taskDecorator != null ? this.taskDecorator.decorate(task) : task);\n ", "post_mask_code": "\n }\n\n @Override\n public Future submit(Runnable task) {\n FutureTask future = new FutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public Future submit(Callable task) {\n FutureTask future = new FutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Runnable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Callable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n /**\n * Template method for the actual execution of a task.\n *

The default implementation creates a new Thread and starts it.\n * @param task the Runnable to execute\n * @see #setThreadFactory\n * @see #createThread\n * @see java.lang.Thread#start()\n */\n protected void doExecute(Runnable task) {\n Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));\n thread.start();\n }\n\n /**\n * Subclass of the general ConcurrencyThrottleSupport class,\n * making {@code beforeAccess()} and {@code afterAccess()}\n * visible to the surrounding class.\n */\n private static class ConcurrencyThrottleAdapter extends ConcurrencyThrottleSupport {\n\n @Override\n protected void beforeAccess() {\n super.beforeAccess();\n }\n\n @Override\n protected void afterAccess() {\n super.afterAccess();\n }\n }\n\n /**\n * This Runnable calls {@code afterAccess()} after the\n * target Runnable has finished its execution.\n */\n private class ConcurrencyThrottlingRunnable implements Runnable {\n\n private final Runnable target;\n\n public ConcurrencyThrottlingRunnable(Runnable target) {\n this.target = target;\n }\n\n @Override\n public void run() {\n try {\n this.target.run();\n } finally {\n concurrencyThrottle.afterAccess();\n }\n }\n }\n}\n"} {"task_id": "Java_163", "language": "Java", "task_type": "try_statement", "source_file": "java/github/spring-projects/spring-framework/spring-core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java", "mask_start_position": 9206, "mask_end_position": 9335, "canonical_solution": "try {\n this.target.run();\n } finally {\n concurrencyThrottle.afterAccess();\n }", "pre_mask_code": "package org.springframework.core.task;\n\nimport java.io.Serializable;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.FutureTask;\nimport java.util.concurrent.ThreadFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ConcurrencyThrottleSupport;\nimport org.springframework.util.CustomizableThreadCreator;\nimport org.springframework.util.concurrent.ListenableFuture;\nimport org.springframework.util.concurrent.ListenableFutureTask;\n\n/**\n * {@link TaskExecutor} implementation that fires up a new Thread for each task,\n * executing it asynchronously.\n *\n *

Supports limiting concurrent threads through the \"concurrencyLimit\"\n * bean property. By default, the number of concurrent threads is unlimited.\n *\n *

NOTE: This implementation does not reuse threads! Consider a\n * thread-pooling TaskExecutor implementation instead, in particular for\n * executing a large number of short-lived tasks.\n *\n * @author Juergen Hoeller\n * @since 2.0\n * @see #setConcurrencyLimit\n * @see SyncTaskExecutor\n * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor\n */\n@SuppressWarnings(\"serial\")\npublic class SimpleAsyncTaskExecutor extends CustomizableThreadCreator implements AsyncListenableTaskExecutor, Serializable {\n\n /**\n * Permit any number of concurrent invocations: that is, don't throttle concurrency.\n * @see ConcurrencyThrottleSupport#UNBOUNDED_CONCURRENCY\n */\n public static final int UNBOUNDED_CONCURRENCY = ConcurrencyThrottleSupport.UNBOUNDED_CONCURRENCY;\n\n /**\n * Switch concurrency 'off': that is, don't allow any concurrent invocations.\n * @see ConcurrencyThrottleSupport#NO_CONCURRENCY\n */\n public static final int NO_CONCURRENCY = ConcurrencyThrottleSupport.NO_CONCURRENCY;\n\n /**\n * Internal concurrency throttle used by this executor.\n */\n private final ConcurrencyThrottleAdapter concurrencyThrottle = new ConcurrencyThrottleAdapter();\n\n @Nullable\n private ThreadFactory threadFactory;\n\n @Nullable\n private TaskDecorator taskDecorator;\n\n /**\n * Create a new SimpleAsyncTaskExecutor with default thread name prefix.\n */\n public SimpleAsyncTaskExecutor() {\n super();\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given thread name prefix.\n * @param threadNamePrefix the prefix to use for the names of newly created threads\n */\n public SimpleAsyncTaskExecutor(String threadNamePrefix) {\n super(threadNamePrefix);\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given external thread factory.\n * @param threadFactory the factory to use for creating new Threads\n */\n public SimpleAsyncTaskExecutor(ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Specify an external factory to use for creating new Threads,\n * instead of relying on the local properties of this executor.\n *

You may specify an inner ThreadFactory bean or also a ThreadFactory reference\n * obtained from JNDI (on a Jakarta EE server) or some other lookup mechanism.\n * @see #setThreadNamePrefix\n * @see #setThreadPriority\n */\n public void setThreadFactory(@Nullable ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Return the external factory to use for creating new Threads, if any.\n */\n @Nullable\n public final ThreadFactory getThreadFactory() {\n return this.threadFactory;\n }\n\n /**\n * Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}\n * about to be executed.\n *

Note that such a decorator is not necessarily being applied to the\n * user-supplied {@code Runnable}/{@code Callable} but rather to the actual\n * execution callback (which may be a wrapper around the user-supplied task).\n *

The primary use case is to set some execution context around the task's\n * invocation, or to provide some monitoring/statistics for task execution.\n *

NOTE: Exception handling in {@code TaskDecorator} implementations\n * is limited to plain {@code Runnable} execution via {@code execute} calls.\n * In case of {@code #submit} calls, the exposed {@code Runnable} will be a\n * {@code FutureTask} which does not propagate any exceptions; you might\n * have to cast it and call {@code Future#get} to evaluate exceptions.\n * @since 4.3\n */\n public final void setTaskDecorator(TaskDecorator taskDecorator) {\n this.taskDecorator = taskDecorator;\n }\n\n /**\n * Set the maximum number of parallel accesses allowed.\n * -1 indicates no concurrency limit at all.\n *

In principle, this limit can be changed at runtime,\n * although it is generally designed as a config time setting.\n * NOTE: Do not switch between -1 and any concrete limit at runtime,\n * as this will lead to inconsistent concurrency counts: A limit\n * of -1 effectively turns off concurrency counting completely.\n * @see #UNBOUNDED_CONCURRENCY\n */\n public void setConcurrencyLimit(int concurrencyLimit) {\n this.concurrencyThrottle.setConcurrencyLimit(concurrencyLimit);\n }\n\n /**\n * Return the maximum number of parallel accesses allowed.\n */\n public final int getConcurrencyLimit() {\n return this.concurrencyThrottle.getConcurrencyLimit();\n }\n\n /**\n * Return whether this throttle is currently active.\n * @return {@code true} if the concurrency limit for this instance is active\n * @see #getConcurrencyLimit()\n * @see #setConcurrencyLimit\n */\n public final boolean isThrottleActive() {\n return this.concurrencyThrottle.isThrottleActive();\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task) {\n execute(task, TIMEOUT_INDEFINITE);\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n *

Executes urgent tasks (with 'immediate' timeout) directly,\n * bypassing the concurrency throttle (if active). All other\n * tasks are subject to throttling.\n * @see #TIMEOUT_IMMEDIATE\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task, long startTimeout) {\n Assert.notNull(task, \"Runnable must not be null\");\n Runnable taskToUse = (this.taskDecorator != null ? this.taskDecorator.decorate(task) : task);\n if (isThrottleActive() && startTimeout > TIMEOUT_IMMEDIATE) {\n this.concurrencyThrottle.beforeAccess();\n doExecute(new ConcurrencyThrottlingRunnable(taskToUse));\n } else {\n doExecute(taskToUse);\n }\n }\n\n @Override\n public Future submit(Runnable task) {\n FutureTask future = new FutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public Future submit(Callable task) {\n FutureTask future = new FutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Runnable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Callable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n /**\n * Template method for the actual execution of a task.\n *

The default implementation creates a new Thread and starts it.\n * @param task the Runnable to execute\n * @see #setThreadFactory\n * @see #createThread\n * @see java.lang.Thread#start()\n */\n protected void doExecute(Runnable task) {\n Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));\n thread.start();\n }\n\n /**\n * Subclass of the general ConcurrencyThrottleSupport class,\n * making {@code beforeAccess()} and {@code afterAccess()}\n * visible to the surrounding class.\n */\n private static class ConcurrencyThrottleAdapter extends ConcurrencyThrottleSupport {\n\n @Override\n protected void beforeAccess() {\n super.beforeAccess();\n }\n\n @Override\n protected void afterAccess() {\n super.afterAccess();\n }\n }\n\n /**\n * This Runnable calls {@code afterAccess()} after the\n * target Runnable has finished its execution.\n */\n private class ConcurrencyThrottlingRunnable implements Runnable {\n\n private final Runnable target;\n\n public ConcurrencyThrottlingRunnable(Runnable target) {\n this.target = target;\n }\n\n @Override\n public void run() {\n ", "post_mask_code": "\n }\n }\n}\n"} {"task_id": "Java_164", "language": "Java", "task_type": "empty", "source_file": "java/github/spring-projects/spring-framework/spring-core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java", "mask_start_position": 4216, "mask_end_position": 4216, "canonical_solution": "", "pre_mask_code": "package org.springframework.core.task;\n\nimport java.io.Serializable;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.FutureTask;\nimport java.util.concurrent.ThreadFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ConcurrencyThrottleSupport;\nimport org.springframework.util.CustomizableThreadCreator;\nimport org.springframework.util.concurrent.ListenableFuture;\nimport org.springframework.util.concurrent.ListenableFutureTask;\n\n/**\n * {@link TaskExecutor} implementation that fires up a new Thread for each task,\n * executing it asynchronously.\n *\n *

Supports limiting concurrent threads through the \"concurrencyLimit\"\n * bean property. By default, the number of concurrent threads is unlimited.\n *\n *

NOTE: This implementation does not reuse threads! Consider a\n * thread-pooling TaskExecutor implementation instead, in particular for\n * executing a large number of short-lived tasks.\n *\n * @author Juergen Hoeller\n * @since 2.0\n * @see #setConcurrencyLimit\n * @see SyncTaskExecutor\n * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor\n */\n@SuppressWarnings(\"serial\")\npublic class SimpleAsyncTaskExecutor extends CustomizableThreadCreator implements AsyncListenableTaskExecutor, Serializable {\n\n /**\n * Permit any number of concurrent invocations: that is, don't throttle concurrency.\n * @see ConcurrencyThrottleSupport#UNBOUNDED_CONCURRENCY\n */\n public static final int UNBOUNDED_CONCURRENCY = ConcurrencyThrottleSupport.UNBOUNDED_CONCURRENCY;\n\n /**\n * Switch concurrency 'off': that is, don't allow any concurrent invocations.\n * @see ConcurrencyThrottleSupport#NO_CONCURRENCY\n */\n public static final int NO_CONCURRENCY = ConcurrencyThrottleSupport.NO_CONCURRENCY;\n\n /**\n * Internal concurrency throttle used by this executor.\n */\n private final ConcurrencyThrottleAdapter concurrencyThrottle = new ConcurrencyThrottleAdapter();\n\n @Nullable\n private ThreadFactory threadFactory;\n\n @Nullable\n private TaskDecorator taskDecorator;\n\n /**\n * Create a new SimpleAsyncTaskExecutor with default thread name prefix.\n */\n public SimpleAsyncTaskExecutor() {\n super();\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given thread name prefix.\n * @param threadNamePrefix the prefix to use for the names of newly created threads\n */\n public SimpleAsyncTaskExecutor(String threadNamePrefix) {\n super(threadNamePrefix);\n }\n\n /**\n * Create a new SimpleAsyncTaskExecutor with the given external thread factory.\n * @param threadFactory the factory to use for creating new Threads\n */\n public SimpleAsyncTaskExecutor(ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Specify an external factory to use for creating new Threads,\n * instead of relying on the local properties of this executor.\n *

You may specify an inner ThreadFactory bean or also a ThreadFactory reference\n * obtained from JNDI (on a Jakarta EE server) or some other lookup mechanism.\n * @see #setThreadNamePrefix\n * @see #setThreadPriority\n */\n public void setThreadFactory(@Nullable ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n /**\n * Return the external factory to use for creating new Threads, if any.\n */\n @Nullable\n public final ThreadFactory getThreadFactory() {\n return this.threadFactory;\n }\n\n /**\n * Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}\n * about to be executed.\n *

Note that such a decorator is not necessarily being applied to the\n * user-supplied {@code Runnable}/{@code Callable} but rather to the actual\n * execution callback (which may be a wrapper around the user-supplied task).\n *

The primary use case is to set some execution context around the task's\n * invocation, or to provide some monitoring/statistics for task execution.\n *

NOTE: Exception handling in {@code TaskDecorator} implementations\n * is limi", "post_mask_code": "ted to plain {@code Runnable} execution via {@code execute} calls.\n * In case of {@code #submit} calls, the exposed {@code Runnable} will be a\n * {@code FutureTask} which does not propagate any exceptions; you might\n * have to cast it and call {@code Future#get} to evaluate exceptions.\n * @since 4.3\n */\n public final void setTaskDecorator(TaskDecorator taskDecorator) {\n this.taskDecorator = taskDecorator;\n }\n\n /**\n * Set the maximum number of parallel accesses allowed.\n * -1 indicates no concurrency limit at all.\n *

In principle, this limit can be changed at runtime,\n * although it is generally designed as a config time setting.\n * NOTE: Do not switch between -1 and any concrete limit at runtime,\n * as this will lead to inconsistent concurrency counts: A limit\n * of -1 effectively turns off concurrency counting completely.\n * @see #UNBOUNDED_CONCURRENCY\n */\n public void setConcurrencyLimit(int concurrencyLimit) {\n this.concurrencyThrottle.setConcurrencyLimit(concurrencyLimit);\n }\n\n /**\n * Return the maximum number of parallel accesses allowed.\n */\n public final int getConcurrencyLimit() {\n return this.concurrencyThrottle.getConcurrencyLimit();\n }\n\n /**\n * Return whether this throttle is currently active.\n * @return {@code true} if the concurrency limit for this instance is active\n * @see #getConcurrencyLimit()\n * @see #setConcurrencyLimit\n */\n public final boolean isThrottleActive() {\n return this.concurrencyThrottle.isThrottleActive();\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task) {\n execute(task, TIMEOUT_INDEFINITE);\n }\n\n /**\n * Executes the given task, within a concurrency throttle\n * if configured (through the superclass's settings).\n *

Executes urgent tasks (with 'immediate' timeout) directly,\n * bypassing the concurrency throttle (if active). All other\n * tasks are subject to throttling.\n * @see #TIMEOUT_IMMEDIATE\n * @see #doExecute(Runnable)\n */\n @Override\n public void execute(Runnable task, long startTimeout) {\n Assert.notNull(task, \"Runnable must not be null\");\n Runnable taskToUse = (this.taskDecorator != null ? this.taskDecorator.decorate(task) : task);\n if (isThrottleActive() && startTimeout > TIMEOUT_IMMEDIATE) {\n this.concurrencyThrottle.beforeAccess();\n doExecute(new ConcurrencyThrottlingRunnable(taskToUse));\n } else {\n doExecute(taskToUse);\n }\n }\n\n @Override\n public Future submit(Runnable task) {\n FutureTask future = new FutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public Future submit(Callable task) {\n FutureTask future = new FutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Runnable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task, null);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n @Override\n public ListenableFuture submitListenable(Callable task) {\n ListenableFutureTask future = new ListenableFutureTask<>(task);\n execute(future, TIMEOUT_INDEFINITE);\n return future;\n }\n\n /**\n * Template method for the actual execution of a task.\n *

The default implementation creates a new Thread and starts it.\n * @param task the Runnable to execute\n * @see #setThreadFactory\n * @see #createThread\n * @see java.lang.Thread#start()\n */\n protected void doExecute(Runnable task) {\n Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));\n thread.start();\n }\n\n /**\n * Subclass of the general ConcurrencyThrottleSupport class,\n * making {@code beforeAccess()} and {@code afterAccess()}\n * visible to the surrounding class.\n */\n private static class ConcurrencyThrottleAdapter extends ConcurrencyThrottleSupport {\n\n @Override\n protected void beforeAccess() {\n super.beforeAccess();\n }\n\n @Override\n protected void afterAccess() {\n super.afterAccess();\n }\n }\n\n /**\n * This Runnable calls {@code afterAccess()} after the\n * target Runnable has finished its execution.\n */\n private class ConcurrencyThrottlingRunnable implements Runnable {\n\n private final Runnable target;\n\n public ConcurrencyThrottlingRunnable(Runnable target) {\n this.target = target;\n }\n\n @Override\n public void run() {\n try {\n this.target.run();\n } finally {\n concurrencyThrottle.afterAccess();\n }\n }\n }\n}\n"} {"task_id": "Java_165", "language": "Java", "task_type": "method_signature", "source_file": "java/github/wmr513/messaging/01_12_Message_Filtering_Code/src/main/java/oreilly/video/messaging/JMSSender.java", "mask_start_position": 262, "mask_end_position": 318, "canonical_solution": "public static void main(String[] args) throws Exception ", "pre_mask_code": "package oreilly.video.messaging;\n\nimport javax.jms.Connection;\nimport javax.jms.MessageProducer;\nimport javax.jms.Queue;\nimport javax.jms.Session;\nimport javax.jms.TextMessage;\nimport org.apache.activemq.ActiveMQConnectionFactory;\n\npublic class JMSSender {\n\n ", "post_mask_code": "{\n Connection connection = new ActiveMQConnectionFactory(\"tcp://localhost:61616\").createConnection();\n connection.start();\n Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n Queue queue = session.createQueue(\"EM_TRADE_FILTER.Q\");\n MessageProducer sender = session.createProducer(queue);\n TextMessage msg = session.createTextMessage(\"BUY AAPL 1000 SHARES\");\n msg.setStringProperty(\"State\", \"open\");\n sender.send(msg);\n System.out.println(\"Message Sent\");\n connection.close();\n }\n}\n"} {"task_id": "Java_166", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/wmr513/messaging/01_12_Message_Filtering_Code/src/main/java/oreilly/video/messaging/JMSSender.java", "mask_start_position": 319, "mask_end_position": 539, "canonical_solution": "\n Connection connection = new ActiveMQConnectionFactory(\"tcp://localhost:61616\").createConnection();\n connection.start();\n Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);", "pre_mask_code": "package oreilly.video.messaging;\n\nimport javax.jms.Connection;\nimport javax.jms.MessageProducer;\nimport javax.jms.Queue;\nimport javax.jms.Session;\nimport javax.jms.TextMessage;\nimport org.apache.activemq.ActiveMQConnectionFactory;\n\npublic class JMSSender {\n\n public static void main(String[] args) throws Exception {", "post_mask_code": "\n Queue queue = session.createQueue(\"EM_TRADE_FILTER.Q\");\n MessageProducer sender = session.createProducer(queue);\n TextMessage msg = session.createTextMessage(\"BUY AAPL 1000 SHARES\");\n msg.setStringProperty(\"State\", \"open\");\n sender.send(msg);\n System.out.println(\"Message Sent\");\n connection.close();\n }\n}\n"} {"task_id": "Java_167", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/wmr513/messaging/01_12_Message_Filtering_Code/src/main/java/oreilly/video/messaging/JMSSender.java", "mask_start_position": 548, "mask_end_position": 792, "canonical_solution": "Queue queue = session.createQueue(\"EM_TRADE_FILTER.Q\");\n MessageProducer sender = session.createProducer(queue);\n TextMessage msg = session.createTextMessage(\"BUY AAPL 1000 SHARES\");\n msg.setStringProperty(\"State\", \"open\");", "pre_mask_code": "package oreilly.video.messaging;\n\nimport javax.jms.Connection;\nimport javax.jms.MessageProducer;\nimport javax.jms.Queue;\nimport javax.jms.Session;\nimport javax.jms.TextMessage;\nimport org.apache.activemq.ActiveMQConnectionFactory;\n\npublic class JMSSender {\n\n public static void main(String[] args) throws Exception {\n Connection connection = new ActiveMQConnectionFactory(\"tcp://localhost:61616\").createConnection();\n connection.start();\n Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n ", "post_mask_code": "\n sender.send(msg);\n System.out.println(\"Message Sent\");\n connection.close();\n }\n}\n"} {"task_id": "Java_168", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/wmr513/messaging/01_12_Message_Filtering_Code/src/main/java/oreilly/video/messaging/JMSSender.java", "mask_start_position": 801, "mask_end_position": 896, "canonical_solution": "sender.send(msg);\n System.out.println(\"Message Sent\");\n connection.close();\n }", "pre_mask_code": "package oreilly.video.messaging;\n\nimport javax.jms.Connection;\nimport javax.jms.MessageProducer;\nimport javax.jms.Queue;\nimport javax.jms.Session;\nimport javax.jms.TextMessage;\nimport org.apache.activemq.ActiveMQConnectionFactory;\n\npublic class JMSSender {\n\n public static void main(String[] args) throws Exception {\n Connection connection = new ActiveMQConnectionFactory(\"tcp://localhost:61616\").createConnection();\n connection.start();\n Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n Queue queue = session.createQueue(\"EM_TRADE_FILTER.Q\");\n MessageProducer sender = session.createProducer(queue);\n TextMessage msg = session.createTextMessage(\"BUY AAPL 1000 SHARES\");\n msg.setStringProperty(\"State\", \"open\");\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_169", "language": "Java", "task_type": "single_line", "source_file": "java/github/wmr513/messaging/01_12_Message_Filtering_Code/src/main/java/oreilly/video/messaging/JMSSender.java", "mask_start_position": 558, "mask_end_position": 603, "canonical_solution": "e = session.createQueue(\"EM_TRADE_FILTER.Q\");", "pre_mask_code": "package oreilly.video.messaging;\n\nimport javax.jms.Connection;\nimport javax.jms.MessageProducer;\nimport javax.jms.Queue;\nimport javax.jms.Session;\nimport javax.jms.TextMessage;\nimport org.apache.activemq.ActiveMQConnectionFactory;\n\npublic class JMSSender {\n\n public static void main(String[] args) throws Exception {\n Connection connection = new ActiveMQConnectionFactory(\"tcp://localhost:61616\").createConnection();\n connection.start();\n Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n Queue queu", "post_mask_code": "\n MessageProducer sender = session.createProducer(queue);\n TextMessage msg = session.createTextMessage(\"BUY AAPL 1000 SHARES\");\n msg.setStringProperty(\"State\", \"open\");\n sender.send(msg);\n System.out.println(\"Message Sent\");\n connection.close();\n }\n}\n"} {"task_id": "Java_170", "language": "Java", "task_type": "empty", "source_file": "java/github/wmr513/messaging/01_12_Message_Filtering_Code/src/main/java/oreilly/video/messaging/JMSSender.java", "mask_start_position": 685, "mask_end_position": 685, "canonical_solution": "", "pre_mask_code": "package oreilly.video.messaging;\n\nimport javax.jms.Connection;\nimport javax.jms.MessageProducer;\nimport javax.jms.Queue;\nimport javax.jms.Session;\nimport javax.jms.TextMessage;\nimport org.apache.activemq.ActiveMQConnectionFactory;\n\npublic class JMSSender {\n\n public static void main(String[] args) throws Exception {\n Connection connection = new ActiveMQConnectionFactory(\"tcp://localhost:61616\").createConnection();\n connection.start();\n Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n Queue queue = session.createQueue(\"EM_TRADE_FILTER.Q\");\n MessageProducer sender = session.createProducer(queue);\n TextMessa", "post_mask_code": "ge msg = session.createTextMessage(\"BUY AAPL 1000 SHARES\");\n msg.setStringProperty(\"State\", \"open\");\n sender.send(msg);\n System.out.println(\"Message Sent\");\n connection.close();\n }\n}\n"} {"task_id": "Java_171", "language": "Java", "task_type": "method_signature", "source_file": "java/github/doyensec/burpdeveltraining/Bradamsa/com/doyensec/RadamsaPayloadGenerator.java", "mask_start_position": 1119, "mask_end_position": 1166, "canonical_solution": "@Override\n public boolean hasMorePayloads() ", "pre_mask_code": "/*\n * Bradamsa - Burp Intruder payloads generator (simplified code - does not work!) \n *\n */\npackage com.doyensec;\n\nimport burp.BurpExtender;\nimport burp.IBurpExtenderCallbacks;\nimport burp.IIntruderAttack;\nimport burp.IIntruderPayloadGenerator;\nimport burp.IIntruderPayloadGeneratorFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport javax.swing.JOptionPane;\nimport org.apache.commons.io.FileUtils;\n\npublic class RadamsaPayloadGenerator implements IIntruderPayloadGenerator, IIntruderPayloadGeneratorFactory {\n\n private final IBurpExtenderCallbacks callbacks;\n\n private boolean firstInvoke;\n\n private ArrayList samples;\n\n private Iterator samplesIte;\n\n private BradamsaPanel panel;\n\n public RadamsaPayloadGenerator(BurpExtender burpExt) {\n callbacks = burpExt.getCallbacks();\n panel = (BradamsaPanel) burpExt.getTab().getUiComponent();\n firstInvoke = true;\n samples = new ArrayList<>();\n samplesIte = samples.iterator();\n }\n\n ", "post_mask_code": "{\n if (firstInvoke) {\n return true;\n }\n return samplesIte.hasNext();\n }\n\n @Override\n public byte[] getNextPayload(byte[] basePayload) {\n byte[] result = null;\n if (basePayload == null) {\n // Display warning. Battering ram attack type was selected\n JOptionPane.showMessageDialog(null, \"Bradamsa can only be used in a sniper attack\", \"Abort\", JOptionPane.ERROR_MESSAGE);\n firstInvoke = false;\n }\n try {\n if (firstInvoke) {\n // Generate samples from Burp's payload\n String cmdLine = panel.getRadamsaCmdLine();\n if (!cmdLine.isEmpty()) {\n if (panel.getCount() > 9999) {\n JOptionPane.showMessageDialog(null, \"As you've selected an high count number,\" + \" generating all Radamsa samples may take some time.
Your intruder \" + \"attack will start once all samples are successfully generated.\", \"Radamsa Samples Generation\", JOptionPane.INFORMATION_MESSAGE);\n }\n BurpUtils.executeAndPipe(cmdLine, basePayload, callbacks, true);\n // If enabled, mark all files for deletion before JVM shutdown\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.deleteOnExit();\n }\n }\n } else {\n // Display warning. Invalid user input\n JOptionPane.showMessageDialog(null, \"Invalid command line arguments\", \"Check the 'Bradamsa' tab...\", JOptionPane.WARNING_MESSAGE);\n }\n // create samples index\n samples.addAll(Arrays.asList(panel.getOutputDir().listFiles()));\n samplesIte = samples.iterator();\n // prevent further initialization\n firstInvoke = false;\n }\n if (samplesIte.hasNext()) {\n File currentSample = samplesIte.next();\n result = FileUtils.readFileToByteArray(currentSample);\n // If enabled, remove the sample as it has been already used\n if (panel.deleteFiles()) {\n currentSample.delete();\n }\n }\n } catch (IOException | InterruptedException ex) {\n new PrintWriter(callbacks.getStdout()).println(\"[!] Bradamsa Exception: RadamsaPayloadGenerator.getNextPayload()\");\n }\n return result;\n }\n\n @Override\n public void reset() {\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n }\n\n @Override\n public String getGeneratorName() {\n return \"Bradamsa\";\n }\n\n @Override\n public IIntruderPayloadGenerator createNewInstance(IIntruderAttack iia) {\n // Delete previous samples, if applicable\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.delete();\n }\n }\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n return this;\n }\n}\n"} {"task_id": "Java_172", "language": "Java", "task_type": "method_body", "source_file": "java/github/doyensec/burpdeveltraining/Bradamsa/com/doyensec/RadamsaPayloadGenerator.java", "mask_start_position": 3947, "mask_end_position": 3981, "canonical_solution": "{\n return \"Bradamsa\";\n }", "pre_mask_code": "/*\n * Bradamsa - Burp Intruder payloads generator (simplified code - does not work!) \n *\n */\npackage com.doyensec;\n\nimport burp.BurpExtender;\nimport burp.IBurpExtenderCallbacks;\nimport burp.IIntruderAttack;\nimport burp.IIntruderPayloadGenerator;\nimport burp.IIntruderPayloadGeneratorFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport javax.swing.JOptionPane;\nimport org.apache.commons.io.FileUtils;\n\npublic class RadamsaPayloadGenerator implements IIntruderPayloadGenerator, IIntruderPayloadGeneratorFactory {\n\n private final IBurpExtenderCallbacks callbacks;\n\n private boolean firstInvoke;\n\n private ArrayList samples;\n\n private Iterator samplesIte;\n\n private BradamsaPanel panel;\n\n public RadamsaPayloadGenerator(BurpExtender burpExt) {\n callbacks = burpExt.getCallbacks();\n panel = (BradamsaPanel) burpExt.getTab().getUiComponent();\n firstInvoke = true;\n samples = new ArrayList<>();\n samplesIte = samples.iterator();\n }\n\n @Override\n public boolean hasMorePayloads() {\n if (firstInvoke) {\n return true;\n }\n return samplesIte.hasNext();\n }\n\n @Override\n public byte[] getNextPayload(byte[] basePayload) {\n byte[] result = null;\n if (basePayload == null) {\n // Display warning. Battering ram attack type was selected\n JOptionPane.showMessageDialog(null, \"Bradamsa can only be used in a sniper attack\", \"Abort\", JOptionPane.ERROR_MESSAGE);\n firstInvoke = false;\n }\n try {\n if (firstInvoke) {\n // Generate samples from Burp's payload\n String cmdLine = panel.getRadamsaCmdLine();\n if (!cmdLine.isEmpty()) {\n if (panel.getCount() > 9999) {\n JOptionPane.showMessageDialog(null, \"As you've selected an high count number,\" + \" generating all Radamsa samples may take some time.
Your intruder \" + \"attack will start once all samples are successfully generated.\", \"Radamsa Samples Generation\", JOptionPane.INFORMATION_MESSAGE);\n }\n BurpUtils.executeAndPipe(cmdLine, basePayload, callbacks, true);\n // If enabled, mark all files for deletion before JVM shutdown\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.deleteOnExit();\n }\n }\n } else {\n // Display warning. Invalid user input\n JOptionPane.showMessageDialog(null, \"Invalid command line arguments\", \"Check the 'Bradamsa' tab...\", JOptionPane.WARNING_MESSAGE);\n }\n // create samples index\n samples.addAll(Arrays.asList(panel.getOutputDir().listFiles()));\n samplesIte = samples.iterator();\n // prevent further initialization\n firstInvoke = false;\n }\n if (samplesIte.hasNext()) {\n File currentSample = samplesIte.next();\n result = FileUtils.readFileToByteArray(currentSample);\n // If enabled, remove the sample as it has been already used\n if (panel.deleteFiles()) {\n currentSample.delete();\n }\n }\n } catch (IOException | InterruptedException ex) {\n new PrintWriter(callbacks.getStdout()).println(\"[!] Bradamsa Exception: RadamsaPayloadGenerator.getNextPayload()\");\n }\n return result;\n }\n\n @Override\n public void reset() {\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n }\n\n @Override\n public String getGeneratorName() ", "post_mask_code": "\n\n @Override\n public IIntruderPayloadGenerator createNewInstance(IIntruderAttack iia) {\n // Delete previous samples, if applicable\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.delete();\n }\n }\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n return this;\n }\n}\n"} {"task_id": "Java_173", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/doyensec/burpdeveltraining/Bradamsa/com/doyensec/RadamsaPayloadGenerator.java", "mask_start_position": 1342, "mask_end_position": 1372, "canonical_solution": "\n byte[] result = null;", "pre_mask_code": "/*\n * Bradamsa - Burp Intruder payloads generator (simplified code - does not work!) \n *\n */\npackage com.doyensec;\n\nimport burp.BurpExtender;\nimport burp.IBurpExtenderCallbacks;\nimport burp.IIntruderAttack;\nimport burp.IIntruderPayloadGenerator;\nimport burp.IIntruderPayloadGeneratorFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport javax.swing.JOptionPane;\nimport org.apache.commons.io.FileUtils;\n\npublic class RadamsaPayloadGenerator implements IIntruderPayloadGenerator, IIntruderPayloadGeneratorFactory {\n\n private final IBurpExtenderCallbacks callbacks;\n\n private boolean firstInvoke;\n\n private ArrayList samples;\n\n private Iterator samplesIte;\n\n private BradamsaPanel panel;\n\n public RadamsaPayloadGenerator(BurpExtender burpExt) {\n callbacks = burpExt.getCallbacks();\n panel = (BradamsaPanel) burpExt.getTab().getUiComponent();\n firstInvoke = true;\n samples = new ArrayList<>();\n samplesIte = samples.iterator();\n }\n\n @Override\n public boolean hasMorePayloads() {\n if (firstInvoke) {\n return true;\n }\n return samplesIte.hasNext();\n }\n\n @Override\n public byte[] getNextPayload(byte[] basePayload) {", "post_mask_code": "\n if (basePayload == null) {\n // Display warning. Battering ram attack type was selected\n JOptionPane.showMessageDialog(null, \"Bradamsa can only be used in a sniper attack\", \"Abort\", JOptionPane.ERROR_MESSAGE);\n firstInvoke = false;\n }\n try {\n if (firstInvoke) {\n // Generate samples from Burp's payload\n String cmdLine = panel.getRadamsaCmdLine();\n if (!cmdLine.isEmpty()) {\n if (panel.getCount() > 9999) {\n JOptionPane.showMessageDialog(null, \"As you've selected an high count number,\" + \" generating all Radamsa samples may take some time.
Your intruder \" + \"attack will start once all samples are successfully generated.\", \"Radamsa Samples Generation\", JOptionPane.INFORMATION_MESSAGE);\n }\n BurpUtils.executeAndPipe(cmdLine, basePayload, callbacks, true);\n // If enabled, mark all files for deletion before JVM shutdown\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.deleteOnExit();\n }\n }\n } else {\n // Display warning. Invalid user input\n JOptionPane.showMessageDialog(null, \"Invalid command line arguments\", \"Check the 'Bradamsa' tab...\", JOptionPane.WARNING_MESSAGE);\n }\n // create samples index\n samples.addAll(Arrays.asList(panel.getOutputDir().listFiles()));\n samplesIte = samples.iterator();\n // prevent further initialization\n firstInvoke = false;\n }\n if (samplesIte.hasNext()) {\n File currentSample = samplesIte.next();\n result = FileUtils.readFileToByteArray(currentSample);\n // If enabled, remove the sample as it has been already used\n if (panel.deleteFiles()) {\n currentSample.delete();\n }\n }\n } catch (IOException | InterruptedException ex) {\n new PrintWriter(callbacks.getStdout()).println(\"[!] Bradamsa Exception: RadamsaPayloadGenerator.getNextPayload()\");\n }\n return result;\n }\n\n @Override\n public void reset() {\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n }\n\n @Override\n public String getGeneratorName() {\n return \"Bradamsa\";\n }\n\n @Override\n public IIntruderPayloadGenerator createNewInstance(IIntruderAttack iia) {\n // Delete previous samples, if applicable\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.delete();\n }\n }\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n return this;\n }\n}\n"} {"task_id": "Java_174", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/doyensec/burpdeveltraining/Bradamsa/com/doyensec/RadamsaPayloadGenerator.java", "mask_start_position": 1381, "mask_end_position": 3724, "canonical_solution": "if (basePayload == null) {\n // Display warning. Battering ram attack type was selected\n JOptionPane.showMessageDialog(null, \"Bradamsa can only be used in a sniper attack\", \"Abort\", JOptionPane.ERROR_MESSAGE);\n firstInvoke = false;\n }\n try {\n if (firstInvoke) {\n // Generate samples from Burp's payload\n String cmdLine = panel.getRadamsaCmdLine();\n if (!cmdLine.isEmpty()) {\n if (panel.getCount() > 9999) {\n JOptionPane.showMessageDialog(null, \"As you've selected an high count number,\" + \" generating all Radamsa samples may take some time.
Your intruder \" + \"attack will start once all samples are successfully generated.\", \"Radamsa Samples Generation\", JOptionPane.INFORMATION_MESSAGE);\n }\n BurpUtils.executeAndPipe(cmdLine, basePayload, callbacks, true);\n // If enabled, mark all files for deletion before JVM shutdown\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.deleteOnExit();\n }\n }\n } else {\n // Display warning. Invalid user input\n JOptionPane.showMessageDialog(null, \"Invalid command line arguments\", \"Check the 'Bradamsa' tab...\", JOptionPane.WARNING_MESSAGE);\n }\n // create samples index\n samples.addAll(Arrays.asList(panel.getOutputDir().listFiles()));\n samplesIte = samples.iterator();\n // prevent further initialization\n firstInvoke = false;\n }\n if (samplesIte.hasNext()) {\n File currentSample = samplesIte.next();\n result = FileUtils.readFileToByteArray(currentSample);\n // If enabled, remove the sample as it has been already used\n if (panel.deleteFiles()) {\n currentSample.delete();\n }\n }\n } catch (IOException | InterruptedException ex) {\n new PrintWriter(callbacks.getStdout()).println(\"[!] Bradamsa Exception: RadamsaPayloadGenerator.getNextPayload()\");\n }", "pre_mask_code": "/*\n * Bradamsa - Burp Intruder payloads generator (simplified code - does not work!) \n *\n */\npackage com.doyensec;\n\nimport burp.BurpExtender;\nimport burp.IBurpExtenderCallbacks;\nimport burp.IIntruderAttack;\nimport burp.IIntruderPayloadGenerator;\nimport burp.IIntruderPayloadGeneratorFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport javax.swing.JOptionPane;\nimport org.apache.commons.io.FileUtils;\n\npublic class RadamsaPayloadGenerator implements IIntruderPayloadGenerator, IIntruderPayloadGeneratorFactory {\n\n private final IBurpExtenderCallbacks callbacks;\n\n private boolean firstInvoke;\n\n private ArrayList samples;\n\n private Iterator samplesIte;\n\n private BradamsaPanel panel;\n\n public RadamsaPayloadGenerator(BurpExtender burpExt) {\n callbacks = burpExt.getCallbacks();\n panel = (BradamsaPanel) burpExt.getTab().getUiComponent();\n firstInvoke = true;\n samples = new ArrayList<>();\n samplesIte = samples.iterator();\n }\n\n @Override\n public boolean hasMorePayloads() {\n if (firstInvoke) {\n return true;\n }\n return samplesIte.hasNext();\n }\n\n @Override\n public byte[] getNextPayload(byte[] basePayload) {\n byte[] result = null;\n ", "post_mask_code": "\n return result;\n }\n\n @Override\n public void reset() {\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n }\n\n @Override\n public String getGeneratorName() {\n return \"Bradamsa\";\n }\n\n @Override\n public IIntruderPayloadGenerator createNewInstance(IIntruderAttack iia) {\n // Delete previous samples, if applicable\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.delete();\n }\n }\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n return this;\n }\n}\n"} {"task_id": "Java_175", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/doyensec/burpdeveltraining/Bradamsa/com/doyensec/RadamsaPayloadGenerator.java", "mask_start_position": 3733, "mask_end_position": 3753, "canonical_solution": "return result;\n }", "pre_mask_code": "/*\n * Bradamsa - Burp Intruder payloads generator (simplified code - does not work!) \n *\n */\npackage com.doyensec;\n\nimport burp.BurpExtender;\nimport burp.IBurpExtenderCallbacks;\nimport burp.IIntruderAttack;\nimport burp.IIntruderPayloadGenerator;\nimport burp.IIntruderPayloadGeneratorFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport javax.swing.JOptionPane;\nimport org.apache.commons.io.FileUtils;\n\npublic class RadamsaPayloadGenerator implements IIntruderPayloadGenerator, IIntruderPayloadGeneratorFactory {\n\n private final IBurpExtenderCallbacks callbacks;\n\n private boolean firstInvoke;\n\n private ArrayList samples;\n\n private Iterator samplesIte;\n\n private BradamsaPanel panel;\n\n public RadamsaPayloadGenerator(BurpExtender burpExt) {\n callbacks = burpExt.getCallbacks();\n panel = (BradamsaPanel) burpExt.getTab().getUiComponent();\n firstInvoke = true;\n samples = new ArrayList<>();\n samplesIte = samples.iterator();\n }\n\n @Override\n public boolean hasMorePayloads() {\n if (firstInvoke) {\n return true;\n }\n return samplesIte.hasNext();\n }\n\n @Override\n public byte[] getNextPayload(byte[] basePayload) {\n byte[] result = null;\n if (basePayload == null) {\n // Display warning. Battering ram attack type was selected\n JOptionPane.showMessageDialog(null, \"Bradamsa can only be used in a sniper attack\", \"Abort\", JOptionPane.ERROR_MESSAGE);\n firstInvoke = false;\n }\n try {\n if (firstInvoke) {\n // Generate samples from Burp's payload\n String cmdLine = panel.getRadamsaCmdLine();\n if (!cmdLine.isEmpty()) {\n if (panel.getCount() > 9999) {\n JOptionPane.showMessageDialog(null, \"As you've selected an high count number,\" + \" generating all Radamsa samples may take some time.
Your intruder \" + \"attack will start once all samples are successfully generated.\", \"Radamsa Samples Generation\", JOptionPane.INFORMATION_MESSAGE);\n }\n BurpUtils.executeAndPipe(cmdLine, basePayload, callbacks, true);\n // If enabled, mark all files for deletion before JVM shutdown\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.deleteOnExit();\n }\n }\n } else {\n // Display warning. Invalid user input\n JOptionPane.showMessageDialog(null, \"Invalid command line arguments\", \"Check the 'Bradamsa' tab...\", JOptionPane.WARNING_MESSAGE);\n }\n // create samples index\n samples.addAll(Arrays.asList(panel.getOutputDir().listFiles()));\n samplesIte = samples.iterator();\n // prevent further initialization\n firstInvoke = false;\n }\n if (samplesIte.hasNext()) {\n File currentSample = samplesIte.next();\n result = FileUtils.readFileToByteArray(currentSample);\n // If enabled, remove the sample as it has been already used\n if (panel.deleteFiles()) {\n currentSample.delete();\n }\n }\n } catch (IOException | InterruptedException ex) {\n new PrintWriter(callbacks.getStdout()).println(\"[!] Bradamsa Exception: RadamsaPayloadGenerator.getNextPayload()\");\n }\n ", "post_mask_code": "\n\n @Override\n public void reset() {\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n }\n\n @Override\n public String getGeneratorName() {\n return \"Bradamsa\";\n }\n\n @Override\n public IIntruderPayloadGenerator createNewInstance(IIntruderAttack iia) {\n // Delete previous samples, if applicable\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.delete();\n }\n }\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n return this;\n }\n}\n"} {"task_id": "Java_176", "language": "Java", "task_type": "single_line", "source_file": "java/github/doyensec/burpdeveltraining/Bradamsa/com/doyensec/RadamsaPayloadGenerator.java", "mask_start_position": 3878, "mask_end_position": 3888, "canonical_solution": "ke = true;", "pre_mask_code": "/*\n * Bradamsa - Burp Intruder payloads generator (simplified code - does not work!) \n *\n */\npackage com.doyensec;\n\nimport burp.BurpExtender;\nimport burp.IBurpExtenderCallbacks;\nimport burp.IIntruderAttack;\nimport burp.IIntruderPayloadGenerator;\nimport burp.IIntruderPayloadGeneratorFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport javax.swing.JOptionPane;\nimport org.apache.commons.io.FileUtils;\n\npublic class RadamsaPayloadGenerator implements IIntruderPayloadGenerator, IIntruderPayloadGeneratorFactory {\n\n private final IBurpExtenderCallbacks callbacks;\n\n private boolean firstInvoke;\n\n private ArrayList samples;\n\n private Iterator samplesIte;\n\n private BradamsaPanel panel;\n\n public RadamsaPayloadGenerator(BurpExtender burpExt) {\n callbacks = burpExt.getCallbacks();\n panel = (BradamsaPanel) burpExt.getTab().getUiComponent();\n firstInvoke = true;\n samples = new ArrayList<>();\n samplesIte = samples.iterator();\n }\n\n @Override\n public boolean hasMorePayloads() {\n if (firstInvoke) {\n return true;\n }\n return samplesIte.hasNext();\n }\n\n @Override\n public byte[] getNextPayload(byte[] basePayload) {\n byte[] result = null;\n if (basePayload == null) {\n // Display warning. Battering ram attack type was selected\n JOptionPane.showMessageDialog(null, \"Bradamsa can only be used in a sniper attack\", \"Abort\", JOptionPane.ERROR_MESSAGE);\n firstInvoke = false;\n }\n try {\n if (firstInvoke) {\n // Generate samples from Burp's payload\n String cmdLine = panel.getRadamsaCmdLine();\n if (!cmdLine.isEmpty()) {\n if (panel.getCount() > 9999) {\n JOptionPane.showMessageDialog(null, \"As you've selected an high count number,\" + \" generating all Radamsa samples may take some time.
Your intruder \" + \"attack will start once all samples are successfully generated.\", \"Radamsa Samples Generation\", JOptionPane.INFORMATION_MESSAGE);\n }\n BurpUtils.executeAndPipe(cmdLine, basePayload, callbacks, true);\n // If enabled, mark all files for deletion before JVM shutdown\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.deleteOnExit();\n }\n }\n } else {\n // Display warning. Invalid user input\n JOptionPane.showMessageDialog(null, \"Invalid command line arguments\", \"Check the 'Bradamsa' tab...\", JOptionPane.WARNING_MESSAGE);\n }\n // create samples index\n samples.addAll(Arrays.asList(panel.getOutputDir().listFiles()));\n samplesIte = samples.iterator();\n // prevent further initialization\n firstInvoke = false;\n }\n if (samplesIte.hasNext()) {\n File currentSample = samplesIte.next();\n result = FileUtils.readFileToByteArray(currentSample);\n // If enabled, remove the sample as it has been already used\n if (panel.deleteFiles()) {\n currentSample.delete();\n }\n }\n } catch (IOException | InterruptedException ex) {\n new PrintWriter(callbacks.getStdout()).println(\"[!] Bradamsa Exception: RadamsaPayloadGenerator.getNextPayload()\");\n }\n return result;\n }\n\n @Override\n public void reset() {\n samples.clear();\n samplesIte = samples.iterator();\n firstInvo", "post_mask_code": "\n }\n\n @Override\n public String getGeneratorName() {\n return \"Bradamsa\";\n }\n\n @Override\n public IIntruderPayloadGenerator createNewInstance(IIntruderAttack iia) {\n // Delete previous samples, if applicable\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.delete();\n }\n }\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n return this;\n }\n}\n"} {"task_id": "Java_177", "language": "Java", "task_type": "if_statement", "source_file": "java/github/doyensec/burpdeveltraining/Bradamsa/com/doyensec/RadamsaPayloadGenerator.java", "mask_start_position": 4133, "mask_end_position": 4279, "canonical_solution": "if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.delete();\n }\n }", "pre_mask_code": "/*\n * Bradamsa - Burp Intruder payloads generator (simplified code - does not work!) \n *\n */\npackage com.doyensec;\n\nimport burp.BurpExtender;\nimport burp.IBurpExtenderCallbacks;\nimport burp.IIntruderAttack;\nimport burp.IIntruderPayloadGenerator;\nimport burp.IIntruderPayloadGeneratorFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport javax.swing.JOptionPane;\nimport org.apache.commons.io.FileUtils;\n\npublic class RadamsaPayloadGenerator implements IIntruderPayloadGenerator, IIntruderPayloadGeneratorFactory {\n\n private final IBurpExtenderCallbacks callbacks;\n\n private boolean firstInvoke;\n\n private ArrayList samples;\n\n private Iterator samplesIte;\n\n private BradamsaPanel panel;\n\n public RadamsaPayloadGenerator(BurpExtender burpExt) {\n callbacks = burpExt.getCallbacks();\n panel = (BradamsaPanel) burpExt.getTab().getUiComponent();\n firstInvoke = true;\n samples = new ArrayList<>();\n samplesIte = samples.iterator();\n }\n\n @Override\n public boolean hasMorePayloads() {\n if (firstInvoke) {\n return true;\n }\n return samplesIte.hasNext();\n }\n\n @Override\n public byte[] getNextPayload(byte[] basePayload) {\n byte[] result = null;\n if (basePayload == null) {\n // Display warning. Battering ram attack type was selected\n JOptionPane.showMessageDialog(null, \"Bradamsa can only be used in a sniper attack\", \"Abort\", JOptionPane.ERROR_MESSAGE);\n firstInvoke = false;\n }\n try {\n if (firstInvoke) {\n // Generate samples from Burp's payload\n String cmdLine = panel.getRadamsaCmdLine();\n if (!cmdLine.isEmpty()) {\n if (panel.getCount() > 9999) {\n JOptionPane.showMessageDialog(null, \"As you've selected an high count number,\" + \" generating all Radamsa samples may take some time.
Your intruder \" + \"attack will start once all samples are successfully generated.\", \"Radamsa Samples Generation\", JOptionPane.INFORMATION_MESSAGE);\n }\n BurpUtils.executeAndPipe(cmdLine, basePayload, callbacks, true);\n // If enabled, mark all files for deletion before JVM shutdown\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.deleteOnExit();\n }\n }\n } else {\n // Display warning. Invalid user input\n JOptionPane.showMessageDialog(null, \"Invalid command line arguments\", \"Check the 'Bradamsa' tab...\", JOptionPane.WARNING_MESSAGE);\n }\n // create samples index\n samples.addAll(Arrays.asList(panel.getOutputDir().listFiles()));\n samplesIte = samples.iterator();\n // prevent further initialization\n firstInvoke = false;\n }\n if (samplesIte.hasNext()) {\n File currentSample = samplesIte.next();\n result = FileUtils.readFileToByteArray(currentSample);\n // If enabled, remove the sample as it has been already used\n if (panel.deleteFiles()) {\n currentSample.delete();\n }\n }\n } catch (IOException | InterruptedException ex) {\n new PrintWriter(callbacks.getStdout()).println(\"[!] Bradamsa Exception: RadamsaPayloadGenerator.getNextPayload()\");\n }\n return result;\n }\n\n @Override\n public void reset() {\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n }\n\n @Override\n public String getGeneratorName() {\n return \"Bradamsa\";\n }\n\n @Override\n public IIntruderPayloadGenerator createNewInstance(IIntruderAttack iia) {\n // Delete previous samples, if applicable\n ", "post_mask_code": "\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n return this;\n }\n}\n"} {"task_id": "Java_178", "language": "Java", "task_type": "empty", "source_file": "java/github/doyensec/burpdeveltraining/Bradamsa/com/doyensec/RadamsaPayloadGenerator.java", "mask_start_position": 2743, "mask_end_position": 2743, "canonical_solution": "", "pre_mask_code": "/*\n * Bradamsa - Burp Intruder payloads generator (simplified code - does not work!) \n *\n */\npackage com.doyensec;\n\nimport burp.BurpExtender;\nimport burp.IBurpExtenderCallbacks;\nimport burp.IIntruderAttack;\nimport burp.IIntruderPayloadGenerator;\nimport burp.IIntruderPayloadGeneratorFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport javax.swing.JOptionPane;\nimport org.apache.commons.io.FileUtils;\n\npublic class RadamsaPayloadGenerator implements IIntruderPayloadGenerator, IIntruderPayloadGeneratorFactory {\n\n private final IBurpExtenderCallbacks callbacks;\n\n private boolean firstInvoke;\n\n private ArrayList samples;\n\n private Iterator samplesIte;\n\n private BradamsaPanel panel;\n\n public RadamsaPayloadGenerator(BurpExtender burpExt) {\n callbacks = burpExt.getCallbacks();\n panel = (BradamsaPanel) burpExt.getTab().getUiComponent();\n firstInvoke = true;\n samples = new ArrayList<>();\n samplesIte = samples.iterator();\n }\n\n @Override\n public boolean hasMorePayloads() {\n if (firstInvoke) {\n return true;\n }\n return samplesIte.hasNext();\n }\n\n @Override\n public byte[] getNextPayload(byte[] basePayload) {\n byte[] result = null;\n if (basePayload == null) {\n // Display warning. Battering ram attack type was selected\n JOptionPane.showMessageDialog(null, \"Bradamsa can only be used in a sniper attack\", \"Abort\", JOptionPane.ERROR_MESSAGE);\n firstInvoke = false;\n }\n try {\n if (firstInvoke) {\n // Generate samples from Burp's payload\n String cmdLine = panel.getRadamsaCmdLine();\n if (!cmdLine.isEmpty()) {\n if (panel.getCount() > 9999) {\n JOptionPane.showMessageDialog(null, \"As you've selected an high count number,\" + \" generating all Radamsa samples may take some time.
Your intruder \" + \"attack will start once all samples are successfully generated.\", \"Radamsa Samples Generation\", JOptionPane.INFORMATION_MESSAGE);\n }\n BurpUtils.executeAndPipe(cmdLine, basePayload, callbacks, true);\n // If enabled, mark all files for deletion before JVM shutdown\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.deleteOnExit();\n }\n }\n } else {\n // Display warning. Invalid user input\n ", "post_mask_code": " JOptionPane.showMessageDialog(null, \"Invalid command line arguments\", \"Check the 'Bradamsa' tab...\", JOptionPane.WARNING_MESSAGE);\n }\n // create samples index\n samples.addAll(Arrays.asList(panel.getOutputDir().listFiles()));\n samplesIte = samples.iterator();\n // prevent further initialization\n firstInvoke = false;\n }\n if (samplesIte.hasNext()) {\n File currentSample = samplesIte.next();\n result = FileUtils.readFileToByteArray(currentSample);\n // If enabled, remove the sample as it has been already used\n if (panel.deleteFiles()) {\n currentSample.delete();\n }\n }\n } catch (IOException | InterruptedException ex) {\n new PrintWriter(callbacks.getStdout()).println(\"[!] Bradamsa Exception: RadamsaPayloadGenerator.getNextPayload()\");\n }\n return result;\n }\n\n @Override\n public void reset() {\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n }\n\n @Override\n public String getGeneratorName() {\n return \"Bradamsa\";\n }\n\n @Override\n public IIntruderPayloadGenerator createNewInstance(IIntruderAttack iia) {\n // Delete previous samples, if applicable\n if (panel.deleteFiles()) {\n for (File file : panel.getOutputDir().listFiles()) {\n file.delete();\n }\n }\n samples.clear();\n samplesIte = samples.iterator();\n firstInvoke = true;\n return this;\n }\n}\n"} {"task_id": "Java_179", "language": "Java", "task_type": "method_signature", "source_file": "java/github/dstmath/OppoFramework/A5_8_1_0/src/main/java/com/color/actionbar/app/ColorActionBarUtil.java", "mask_start_position": 4674, "mask_end_position": 4723, "canonical_solution": "public static int getHomeId(ActionBar actionBar) ", "pre_mask_code": "package com.color.actionbar.app;\n\nimport android.animation.Animator;\nimport android.animation.Animator.AnimatorListener;\nimport android.app.ActionBar;\nimport android.app.Activity;\nimport android.content.res.ColorStateList;\nimport android.graphics.drawable.Drawable;\nimport android.view.View;\nimport android.widget.AdapterView.OnItemClickListener;\nimport com.android.internal.R;\nimport com.color.animation.ColorAnimatorWrapper;\nimport com.color.widget.ColorActionModeCallback;\nimport com.color.widget.ColorBottomMenuCallback;\nimport com.color.widget.ColorPagerCallback;\nimport com.color.widget.ColorSpinnerCallback;\nimport com.color.widget.ColorSpinnerCallback.DropdownDismissCallback;\nimport java.util.List;\n\npublic class ColorActionBarUtil {\n\n private static final boolean DBG = false;\n\n private static final String TAG = \"ColorActionBarUtil\";\n\n static final String THEME_CUSTOM_ACTIONBAR = \"oppo:Theme.OPPO.CustomActionBar\";\n\n public interface ScrollTabCallback extends ColorPagerCallback {\n\n void updateTabScrollPosition(int i, float f, int i2);\n\n void updateTabScrollState(int i);\n }\n\n public interface ActionBarCallback extends ScrollTabCallback, ColorBottomMenuCallback, ColorSpinnerCallback {\n\n void addAfterAnimator(Animator animator);\n\n void addAfterAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addAfterAnimatorWrappers(List list);\n\n void addAfterAnimators(List list);\n\n void addBeforeAnimator(Animator animator);\n\n void addBeforeAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addBeforeAnimatorWrappers(List list);\n\n void addBeforeAnimators(List list);\n\n void addHideListener(AnimatorListener animatorListener);\n\n void addSearchViewHideListener(AnimatorListener animatorListener);\n\n void addSearchViewShowListener(AnimatorListener animatorListener);\n\n void addSearchViewWithAnimator(Animator animator);\n\n void addShowListener(AnimatorListener animatorListener);\n\n void addWithAnimator(Animator animator);\n\n void addWithAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addWithAnimatorWrappers(List list);\n\n void addWithAnimators(List list);\n\n void cancelShowHide();\n\n int getContentId();\n\n int getHomeId();\n\n boolean hasEmbeddedTabs();\n\n void setActionBarSubTitle(int i);\n\n void setActionBarSubTitle(CharSequence charSequence);\n\n void setActionMenuTextColor(ColorStateList colorStateList);\n\n void setActionModeAnim(boolean z);\n\n void setActionModeCallback(ColorActionModeCallback colorActionModeCallback);\n\n void setBackTitle(int i);\n\n void setBackTitle(CharSequence charSequence);\n\n void setBackTitleTextColor(ColorStateList colorStateList);\n\n void setColorBottomWindowContentOverlay(Drawable drawable);\n\n void setColorWindowContentOverlay(Drawable drawable);\n\n void setEmbeddedTabs(boolean z);\n\n void setHintText(int i);\n\n void setHintText(CharSequence charSequence);\n\n void setIgnoreColorBottomWindowContentOverlay(boolean z);\n\n void setIgnoreColorWindowContentOverlay(boolean z);\n\n void setMainActionBar(boolean z);\n\n void setSearchBarMode(boolean z);\n\n void setSplitActionBarBg(Drawable drawable);\n\n void setSplitActionBarOverlay(boolean z);\n\n void setSplitActionBarTextColor(ColorStateList colorStateList);\n\n void setSplitHideWithActionBar(boolean z);\n\n void setStatusBarActionBarBg(Drawable drawable);\n\n void setSubtitleTextColor(int i);\n\n void setTitleTextColor(int i);\n }\n\n public interface DelegateCallback {\n\n boolean hasWindowFeature(int i);\n\n void superSetContentView(int i);\n\n void superSetContentView(View view);\n\n boolean supportRequestWindowFeature(int i);\n }\n\n public interface ActivityCallback extends DelegateCallback {\n\n void setSupportProgress(int i);\n\n void setSupportProgressBarIndeterminate(boolean z);\n\n void setSupportProgressBarIndeterminateVisibility(boolean z);\n\n void setSupportProgressBarVisibility(boolean z);\n\n void setSupportSecondaryProgress(int i);\n }\n\n public interface DialogCallback extends DelegateCallback {\n }\n\n public static int getContentId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getContentId();\n }\n return 16908290;\n }\n\n ", "post_mask_code": "{\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getHomeId();\n }\n return R.id.home;\n }\n\n public static int getBottomMenuViewId() {\n return 201458882;\n }\n\n public static void updateTabScrollPosition(ActionBar actionBar, int position, float positionOffset, int positionOffsetPixels) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollPosition(position, positionOffset, positionOffsetPixels);\n }\n }\n\n public static void updateTabScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollState(state);\n }\n }\n\n public static void updateMenuScrollPosition(ActionBar actionBar, int index, float offset) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollPosition(index, offset);\n }\n }\n\n public static void updateMenuScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).updateMenuScrollState(state);\n }\n }\n\n public static void updateMenuScrollData(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollData();\n }\n }\n\n public static void setMenuUpdateMode(ActionBar actionBar, int mode) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).setMenuUpdateMode(mode);\n }\n }\n\n public static void lockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).lockMenuUpdate();\n }\n }\n\n public static void unlockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).unlockMenuUpdate();\n }\n }\n\n public static void setDropdownDismissCallback(ActionBar actionBar, DropdownDismissCallback callback) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownDismissCallback(callback);\n }\n }\n\n public static void setDropdownItemClickListener(ActionBar actionBar, OnItemClickListener listener) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownItemClickListener(listener);\n }\n }\n\n public static void setDropdownUpdateAfterAnim(ActionBar actionBar, boolean update) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownUpdateAfterAnim(update);\n }\n }\n\n public static void setHasEmbeddedTabs(ActionBar actionBar, boolean hasEmbeddedTabs) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setEmbeddedTabs(hasEmbeddedTabs);\n }\n }\n\n public static void setSplitActionBarOverlay(ActionBar actionBar, boolean overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarOverlay(overlay);\n }\n }\n\n public static void setSplitHideWithActionBar(ActionBar actionBar, boolean hideWith) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitHideWithActionBar(hideWith);\n }\n }\n\n public static boolean hasEmbeddedTabs(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).hasEmbeddedTabs();\n }\n return false;\n }\n\n public static void setColorWindowContentOverlay(ActionBar actionBar, Drawable overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorWindowContentOverlay(overlay);\n }\n }\n\n public static void setColorBottomWindowContentOverlay(ActionBar actionBar, Drawable bottomOverlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorBottomWindowContentOverlay(bottomOverlay);\n }\n }\n\n public static void setIgnoreColorWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setIgnoreColorBottomWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorBottomWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setStatusBarActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setStatusBarActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarTextColor(textColor);\n }\n }\n\n public static void setBackTitleTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitleTextColor(textColor);\n }\n }\n\n public static void setTitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setTitleTextColor(textColor);\n }\n }\n\n public static void setSubtitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSubtitleTextColor(textColor);\n }\n }\n\n public static void setActionMenuTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionMenuTextColor(textColor);\n }\n }\n\n public static boolean requestWindowFeature(Activity activity, int featureId) {\n if (activity instanceof ActivityCallback) {\n return ((ActivityCallback) activity).supportRequestWindowFeature(featureId);\n }\n return activity.requestWindowFeature(featureId);\n }\n\n public static void setProgressBarVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarVisibility(visible);\n } else {\n activity.setProgressBarVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminateVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminateVisibility(visible);\n } else {\n activity.setProgressBarIndeterminateVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminate(Activity activity, boolean indeterminate) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminate(indeterminate);\n } else {\n activity.setProgressBarIndeterminate(indeterminate);\n }\n }\n\n public static void setProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgress(progress);\n } else {\n activity.setProgress(progress);\n }\n }\n\n public static void setSecondaryProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportSecondaryProgress(progress);\n } else {\n activity.setSecondaryProgress(progress);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, CharSequence title) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(title);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(resId);\n }\n }\n\n public static void setHintText(ActionBar actionBar, CharSequence hintText) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(hintText);\n }\n }\n\n public static void setHintText(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(resId);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, CharSequence subtitle) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(subtitle);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(resId);\n }\n }\n\n public static void setMainActionBar(ActionBar actionBar, boolean isMain) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setMainActionBar(isMain);\n }\n }\n}\n"} {"task_id": "Java_180", "language": "Java", "task_type": "method_body", "source_file": "java/github/dstmath/OppoFramework/A5_8_1_0/src/main/java/com/color/actionbar/app/ColorActionBarUtil.java", "mask_start_position": 6498, "mask_end_position": 6643, "canonical_solution": "{\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).lockMenuUpdate();\n }\n }", "pre_mask_code": "package com.color.actionbar.app;\n\nimport android.animation.Animator;\nimport android.animation.Animator.AnimatorListener;\nimport android.app.ActionBar;\nimport android.app.Activity;\nimport android.content.res.ColorStateList;\nimport android.graphics.drawable.Drawable;\nimport android.view.View;\nimport android.widget.AdapterView.OnItemClickListener;\nimport com.android.internal.R;\nimport com.color.animation.ColorAnimatorWrapper;\nimport com.color.widget.ColorActionModeCallback;\nimport com.color.widget.ColorBottomMenuCallback;\nimport com.color.widget.ColorPagerCallback;\nimport com.color.widget.ColorSpinnerCallback;\nimport com.color.widget.ColorSpinnerCallback.DropdownDismissCallback;\nimport java.util.List;\n\npublic class ColorActionBarUtil {\n\n private static final boolean DBG = false;\n\n private static final String TAG = \"ColorActionBarUtil\";\n\n static final String THEME_CUSTOM_ACTIONBAR = \"oppo:Theme.OPPO.CustomActionBar\";\n\n public interface ScrollTabCallback extends ColorPagerCallback {\n\n void updateTabScrollPosition(int i, float f, int i2);\n\n void updateTabScrollState(int i);\n }\n\n public interface ActionBarCallback extends ScrollTabCallback, ColorBottomMenuCallback, ColorSpinnerCallback {\n\n void addAfterAnimator(Animator animator);\n\n void addAfterAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addAfterAnimatorWrappers(List list);\n\n void addAfterAnimators(List list);\n\n void addBeforeAnimator(Animator animator);\n\n void addBeforeAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addBeforeAnimatorWrappers(List list);\n\n void addBeforeAnimators(List list);\n\n void addHideListener(AnimatorListener animatorListener);\n\n void addSearchViewHideListener(AnimatorListener animatorListener);\n\n void addSearchViewShowListener(AnimatorListener animatorListener);\n\n void addSearchViewWithAnimator(Animator animator);\n\n void addShowListener(AnimatorListener animatorListener);\n\n void addWithAnimator(Animator animator);\n\n void addWithAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addWithAnimatorWrappers(List list);\n\n void addWithAnimators(List list);\n\n void cancelShowHide();\n\n int getContentId();\n\n int getHomeId();\n\n boolean hasEmbeddedTabs();\n\n void setActionBarSubTitle(int i);\n\n void setActionBarSubTitle(CharSequence charSequence);\n\n void setActionMenuTextColor(ColorStateList colorStateList);\n\n void setActionModeAnim(boolean z);\n\n void setActionModeCallback(ColorActionModeCallback colorActionModeCallback);\n\n void setBackTitle(int i);\n\n void setBackTitle(CharSequence charSequence);\n\n void setBackTitleTextColor(ColorStateList colorStateList);\n\n void setColorBottomWindowContentOverlay(Drawable drawable);\n\n void setColorWindowContentOverlay(Drawable drawable);\n\n void setEmbeddedTabs(boolean z);\n\n void setHintText(int i);\n\n void setHintText(CharSequence charSequence);\n\n void setIgnoreColorBottomWindowContentOverlay(boolean z);\n\n void setIgnoreColorWindowContentOverlay(boolean z);\n\n void setMainActionBar(boolean z);\n\n void setSearchBarMode(boolean z);\n\n void setSplitActionBarBg(Drawable drawable);\n\n void setSplitActionBarOverlay(boolean z);\n\n void setSplitActionBarTextColor(ColorStateList colorStateList);\n\n void setSplitHideWithActionBar(boolean z);\n\n void setStatusBarActionBarBg(Drawable drawable);\n\n void setSubtitleTextColor(int i);\n\n void setTitleTextColor(int i);\n }\n\n public interface DelegateCallback {\n\n boolean hasWindowFeature(int i);\n\n void superSetContentView(int i);\n\n void superSetContentView(View view);\n\n boolean supportRequestWindowFeature(int i);\n }\n\n public interface ActivityCallback extends DelegateCallback {\n\n void setSupportProgress(int i);\n\n void setSupportProgressBarIndeterminate(boolean z);\n\n void setSupportProgressBarIndeterminateVisibility(boolean z);\n\n void setSupportProgressBarVisibility(boolean z);\n\n void setSupportSecondaryProgress(int i);\n }\n\n public interface DialogCallback extends DelegateCallback {\n }\n\n public static int getContentId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getContentId();\n }\n return 16908290;\n }\n\n public static int getHomeId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getHomeId();\n }\n return R.id.home;\n }\n\n public static int getBottomMenuViewId() {\n return 201458882;\n }\n\n public static void updateTabScrollPosition(ActionBar actionBar, int position, float positionOffset, int positionOffsetPixels) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollPosition(position, positionOffset, positionOffsetPixels);\n }\n }\n\n public static void updateTabScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollState(state);\n }\n }\n\n public static void updateMenuScrollPosition(ActionBar actionBar, int index, float offset) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollPosition(index, offset);\n }\n }\n\n public static void updateMenuScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).updateMenuScrollState(state);\n }\n }\n\n public static void updateMenuScrollData(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollData();\n }\n }\n\n public static void setMenuUpdateMode(ActionBar actionBar, int mode) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).setMenuUpdateMode(mode);\n }\n }\n\n public static void lockMenuUpdate(ActionBar actionBar) ", "post_mask_code": "\n\n public static void unlockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).unlockMenuUpdate();\n }\n }\n\n public static void setDropdownDismissCallback(ActionBar actionBar, DropdownDismissCallback callback) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownDismissCallback(callback);\n }\n }\n\n public static void setDropdownItemClickListener(ActionBar actionBar, OnItemClickListener listener) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownItemClickListener(listener);\n }\n }\n\n public static void setDropdownUpdateAfterAnim(ActionBar actionBar, boolean update) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownUpdateAfterAnim(update);\n }\n }\n\n public static void setHasEmbeddedTabs(ActionBar actionBar, boolean hasEmbeddedTabs) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setEmbeddedTabs(hasEmbeddedTabs);\n }\n }\n\n public static void setSplitActionBarOverlay(ActionBar actionBar, boolean overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarOverlay(overlay);\n }\n }\n\n public static void setSplitHideWithActionBar(ActionBar actionBar, boolean hideWith) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitHideWithActionBar(hideWith);\n }\n }\n\n public static boolean hasEmbeddedTabs(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).hasEmbeddedTabs();\n }\n return false;\n }\n\n public static void setColorWindowContentOverlay(ActionBar actionBar, Drawable overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorWindowContentOverlay(overlay);\n }\n }\n\n public static void setColorBottomWindowContentOverlay(ActionBar actionBar, Drawable bottomOverlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorBottomWindowContentOverlay(bottomOverlay);\n }\n }\n\n public static void setIgnoreColorWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setIgnoreColorBottomWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorBottomWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setStatusBarActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setStatusBarActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarTextColor(textColor);\n }\n }\n\n public static void setBackTitleTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitleTextColor(textColor);\n }\n }\n\n public static void setTitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setTitleTextColor(textColor);\n }\n }\n\n public static void setSubtitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSubtitleTextColor(textColor);\n }\n }\n\n public static void setActionMenuTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionMenuTextColor(textColor);\n }\n }\n\n public static boolean requestWindowFeature(Activity activity, int featureId) {\n if (activity instanceof ActivityCallback) {\n return ((ActivityCallback) activity).supportRequestWindowFeature(featureId);\n }\n return activity.requestWindowFeature(featureId);\n }\n\n public static void setProgressBarVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarVisibility(visible);\n } else {\n activity.setProgressBarVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminateVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminateVisibility(visible);\n } else {\n activity.setProgressBarIndeterminateVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminate(Activity activity, boolean indeterminate) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminate(indeterminate);\n } else {\n activity.setProgressBarIndeterminate(indeterminate);\n }\n }\n\n public static void setProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgress(progress);\n } else {\n activity.setProgress(progress);\n }\n }\n\n public static void setSecondaryProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportSecondaryProgress(progress);\n } else {\n activity.setSecondaryProgress(progress);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, CharSequence title) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(title);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(resId);\n }\n }\n\n public static void setHintText(ActionBar actionBar, CharSequence hintText) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(hintText);\n }\n }\n\n public static void setHintText(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(resId);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, CharSequence subtitle) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(subtitle);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(resId);\n }\n }\n\n public static void setMainActionBar(ActionBar actionBar, boolean isMain) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setMainActionBar(isMain);\n }\n }\n}\n"} {"task_id": "Java_181", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/dstmath/OppoFramework/A5_8_1_0/src/main/java/com/color/actionbar/app/ColorActionBarUtil.java", "mask_start_position": 11979, "mask_end_position": 11979, "canonical_solution": "", "pre_mask_code": "package com.color.actionbar.app;\n\nimport android.animation.Animator;\nimport android.animation.Animator.AnimatorListener;\nimport android.app.ActionBar;\nimport android.app.Activity;\nimport android.content.res.ColorStateList;\nimport android.graphics.drawable.Drawable;\nimport android.view.View;\nimport android.widget.AdapterView.OnItemClickListener;\nimport com.android.internal.R;\nimport com.color.animation.ColorAnimatorWrapper;\nimport com.color.widget.ColorActionModeCallback;\nimport com.color.widget.ColorBottomMenuCallback;\nimport com.color.widget.ColorPagerCallback;\nimport com.color.widget.ColorSpinnerCallback;\nimport com.color.widget.ColorSpinnerCallback.DropdownDismissCallback;\nimport java.util.List;\n\npublic class ColorActionBarUtil {\n\n private static final boolean DBG = false;\n\n private static final String TAG = \"ColorActionBarUtil\";\n\n static final String THEME_CUSTOM_ACTIONBAR = \"oppo:Theme.OPPO.CustomActionBar\";\n\n public interface ScrollTabCallback extends ColorPagerCallback {\n\n void updateTabScrollPosition(int i, float f, int i2);\n\n void updateTabScrollState(int i);\n }\n\n public interface ActionBarCallback extends ScrollTabCallback, ColorBottomMenuCallback, ColorSpinnerCallback {\n\n void addAfterAnimator(Animator animator);\n\n void addAfterAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addAfterAnimatorWrappers(List list);\n\n void addAfterAnimators(List list);\n\n void addBeforeAnimator(Animator animator);\n\n void addBeforeAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addBeforeAnimatorWrappers(List list);\n\n void addBeforeAnimators(List list);\n\n void addHideListener(AnimatorListener animatorListener);\n\n void addSearchViewHideListener(AnimatorListener animatorListener);\n\n void addSearchViewShowListener(AnimatorListener animatorListener);\n\n void addSearchViewWithAnimator(Animator animator);\n\n void addShowListener(AnimatorListener animatorListener);\n\n void addWithAnimator(Animator animator);\n\n void addWithAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addWithAnimatorWrappers(List list);\n\n void addWithAnimators(List list);\n\n void cancelShowHide();\n\n int getContentId();\n\n int getHomeId();\n\n boolean hasEmbeddedTabs();\n\n void setActionBarSubTitle(int i);\n\n void setActionBarSubTitle(CharSequence charSequence);\n\n void setActionMenuTextColor(ColorStateList colorStateList);\n\n void setActionModeAnim(boolean z);\n\n void setActionModeCallback(ColorActionModeCallback colorActionModeCallback);\n\n void setBackTitle(int i);\n\n void setBackTitle(CharSequence charSequence);\n\n void setBackTitleTextColor(ColorStateList colorStateList);\n\n void setColorBottomWindowContentOverlay(Drawable drawable);\n\n void setColorWindowContentOverlay(Drawable drawable);\n\n void setEmbeddedTabs(boolean z);\n\n void setHintText(int i);\n\n void setHintText(CharSequence charSequence);\n\n void setIgnoreColorBottomWindowContentOverlay(boolean z);\n\n void setIgnoreColorWindowContentOverlay(boolean z);\n\n void setMainActionBar(boolean z);\n\n void setSearchBarMode(boolean z);\n\n void setSplitActionBarBg(Drawable drawable);\n\n void setSplitActionBarOverlay(boolean z);\n\n void setSplitActionBarTextColor(ColorStateList colorStateList);\n\n void setSplitHideWithActionBar(boolean z);\n\n void setStatusBarActionBarBg(Drawable drawable);\n\n void setSubtitleTextColor(int i);\n\n void setTitleTextColor(int i);\n }\n\n public interface DelegateCallback {\n\n boolean hasWindowFeature(int i);\n\n void superSetContentView(int i);\n\n void superSetContentView(View view);\n\n boolean supportRequestWindowFeature(int i);\n }\n\n public interface ActivityCallback extends DelegateCallback {\n\n void setSupportProgress(int i);\n\n void setSupportProgressBarIndeterminate(boolean z);\n\n void setSupportProgressBarIndeterminateVisibility(boolean z);\n\n void setSupportProgressBarVisibility(boolean z);\n\n void setSupportSecondaryProgress(int i);\n }\n\n public interface DialogCallback extends DelegateCallback {\n }\n\n public static int getContentId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getContentId();\n }\n return 16908290;\n }\n\n public static int getHomeId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getHomeId();\n }\n return R.id.home;\n }\n\n public static int getBottomMenuViewId() {\n return 201458882;\n }\n\n public static void updateTabScrollPosition(ActionBar actionBar, int position, float positionOffset, int positionOffsetPixels) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollPosition(position, positionOffset, positionOffsetPixels);\n }\n }\n\n public static void updateTabScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollState(state);\n }\n }\n\n public static void updateMenuScrollPosition(ActionBar actionBar, int index, float offset) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollPosition(index, offset);\n }\n }\n\n public static void updateMenuScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).updateMenuScrollState(state);\n }\n }\n\n public static void updateMenuScrollData(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollData();\n }\n }\n\n public static void setMenuUpdateMode(ActionBar actionBar, int mode) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).setMenuUpdateMode(mode);\n }\n }\n\n public static void lockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).lockMenuUpdate();\n }\n }\n\n public static void unlockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).unlockMenuUpdate();\n }\n }\n\n public static void setDropdownDismissCallback(ActionBar actionBar, DropdownDismissCallback callback) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownDismissCallback(callback);\n }\n }\n\n public static void setDropdownItemClickListener(ActionBar actionBar, OnItemClickListener listener) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownItemClickListener(listener);\n }\n }\n\n public static void setDropdownUpdateAfterAnim(ActionBar actionBar, boolean update) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownUpdateAfterAnim(update);\n }\n }\n\n public static void setHasEmbeddedTabs(ActionBar actionBar, boolean hasEmbeddedTabs) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setEmbeddedTabs(hasEmbeddedTabs);\n }\n }\n\n public static void setSplitActionBarOverlay(ActionBar actionBar, boolean overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarOverlay(overlay);\n }\n }\n\n public static void setSplitHideWithActionBar(ActionBar actionBar, boolean hideWith) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitHideWithActionBar(hideWith);\n }\n }\n\n public static boolean hasEmbeddedTabs(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).hasEmbeddedTabs();\n }\n return false;\n }\n\n public static void setColorWindowContentOverlay(ActionBar actionBar, Drawable overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorWindowContentOverlay(overlay);\n }\n }\n\n public static void setColorBottomWindowContentOverlay(ActionBar actionBar, Drawable bottomOverlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorBottomWindowContentOverlay(bottomOverlay);\n }\n }\n\n public static void setIgnoreColorWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setIgnoreColorBottomWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorBottomWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setStatusBarActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setStatusBarActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarTextColor(textColor);\n }\n }\n\n public static void setBackTitleTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitleTextColor(textColor);\n }\n }\n\n public static void setTitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setTitleTextColor(textColor);\n }\n }\n\n public static void setSubtitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSubtitleTextColor(textColor);\n }\n }\n\n public static void setActionMenuTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionMenuTextColor(textColor);\n }\n }\n\n public static boolean requestWindowFeature(Activity activity, int featureId) {\n if (activity instanceof ActivityCallback) {\n return ((ActivityCallback) activity).supportRequestWindowFeature(featureId);\n }\n return activity.requestWindowFeature(featureId);\n }\n\n public static void setProgressBarVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarVisibility(visible);\n } else {\n activity.setProgressBarVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminateVisibility(Activity activity, boolean visible) {", "post_mask_code": "\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminateVisibility(visible);\n } else {\n activity.setProgressBarIndeterminateVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminate(Activity activity, boolean indeterminate) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminate(indeterminate);\n } else {\n activity.setProgressBarIndeterminate(indeterminate);\n }\n }\n\n public static void setProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgress(progress);\n } else {\n activity.setProgress(progress);\n }\n }\n\n public static void setSecondaryProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportSecondaryProgress(progress);\n } else {\n activity.setSecondaryProgress(progress);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, CharSequence title) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(title);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(resId);\n }\n }\n\n public static void setHintText(ActionBar actionBar, CharSequence hintText) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(hintText);\n }\n }\n\n public static void setHintText(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(resId);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, CharSequence subtitle) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(subtitle);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(resId);\n }\n }\n\n public static void setMainActionBar(ActionBar actionBar, boolean isMain) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setMainActionBar(isMain);\n }\n }\n}\n"} {"task_id": "Java_182", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/dstmath/OppoFramework/A5_8_1_0/src/main/java/com/color/actionbar/app/ColorActionBarUtil.java", "mask_start_position": 11988, "mask_end_position": 12224, "canonical_solution": "if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminateVisibility(visible);\n } else {\n activity.setProgressBarIndeterminateVisibility(visible);\n }", "pre_mask_code": "package com.color.actionbar.app;\n\nimport android.animation.Animator;\nimport android.animation.Animator.AnimatorListener;\nimport android.app.ActionBar;\nimport android.app.Activity;\nimport android.content.res.ColorStateList;\nimport android.graphics.drawable.Drawable;\nimport android.view.View;\nimport android.widget.AdapterView.OnItemClickListener;\nimport com.android.internal.R;\nimport com.color.animation.ColorAnimatorWrapper;\nimport com.color.widget.ColorActionModeCallback;\nimport com.color.widget.ColorBottomMenuCallback;\nimport com.color.widget.ColorPagerCallback;\nimport com.color.widget.ColorSpinnerCallback;\nimport com.color.widget.ColorSpinnerCallback.DropdownDismissCallback;\nimport java.util.List;\n\npublic class ColorActionBarUtil {\n\n private static final boolean DBG = false;\n\n private static final String TAG = \"ColorActionBarUtil\";\n\n static final String THEME_CUSTOM_ACTIONBAR = \"oppo:Theme.OPPO.CustomActionBar\";\n\n public interface ScrollTabCallback extends ColorPagerCallback {\n\n void updateTabScrollPosition(int i, float f, int i2);\n\n void updateTabScrollState(int i);\n }\n\n public interface ActionBarCallback extends ScrollTabCallback, ColorBottomMenuCallback, ColorSpinnerCallback {\n\n void addAfterAnimator(Animator animator);\n\n void addAfterAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addAfterAnimatorWrappers(List list);\n\n void addAfterAnimators(List list);\n\n void addBeforeAnimator(Animator animator);\n\n void addBeforeAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addBeforeAnimatorWrappers(List list);\n\n void addBeforeAnimators(List list);\n\n void addHideListener(AnimatorListener animatorListener);\n\n void addSearchViewHideListener(AnimatorListener animatorListener);\n\n void addSearchViewShowListener(AnimatorListener animatorListener);\n\n void addSearchViewWithAnimator(Animator animator);\n\n void addShowListener(AnimatorListener animatorListener);\n\n void addWithAnimator(Animator animator);\n\n void addWithAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addWithAnimatorWrappers(List list);\n\n void addWithAnimators(List list);\n\n void cancelShowHide();\n\n int getContentId();\n\n int getHomeId();\n\n boolean hasEmbeddedTabs();\n\n void setActionBarSubTitle(int i);\n\n void setActionBarSubTitle(CharSequence charSequence);\n\n void setActionMenuTextColor(ColorStateList colorStateList);\n\n void setActionModeAnim(boolean z);\n\n void setActionModeCallback(ColorActionModeCallback colorActionModeCallback);\n\n void setBackTitle(int i);\n\n void setBackTitle(CharSequence charSequence);\n\n void setBackTitleTextColor(ColorStateList colorStateList);\n\n void setColorBottomWindowContentOverlay(Drawable drawable);\n\n void setColorWindowContentOverlay(Drawable drawable);\n\n void setEmbeddedTabs(boolean z);\n\n void setHintText(int i);\n\n void setHintText(CharSequence charSequence);\n\n void setIgnoreColorBottomWindowContentOverlay(boolean z);\n\n void setIgnoreColorWindowContentOverlay(boolean z);\n\n void setMainActionBar(boolean z);\n\n void setSearchBarMode(boolean z);\n\n void setSplitActionBarBg(Drawable drawable);\n\n void setSplitActionBarOverlay(boolean z);\n\n void setSplitActionBarTextColor(ColorStateList colorStateList);\n\n void setSplitHideWithActionBar(boolean z);\n\n void setStatusBarActionBarBg(Drawable drawable);\n\n void setSubtitleTextColor(int i);\n\n void setTitleTextColor(int i);\n }\n\n public interface DelegateCallback {\n\n boolean hasWindowFeature(int i);\n\n void superSetContentView(int i);\n\n void superSetContentView(View view);\n\n boolean supportRequestWindowFeature(int i);\n }\n\n public interface ActivityCallback extends DelegateCallback {\n\n void setSupportProgress(int i);\n\n void setSupportProgressBarIndeterminate(boolean z);\n\n void setSupportProgressBarIndeterminateVisibility(boolean z);\n\n void setSupportProgressBarVisibility(boolean z);\n\n void setSupportSecondaryProgress(int i);\n }\n\n public interface DialogCallback extends DelegateCallback {\n }\n\n public static int getContentId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getContentId();\n }\n return 16908290;\n }\n\n public static int getHomeId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getHomeId();\n }\n return R.id.home;\n }\n\n public static int getBottomMenuViewId() {\n return 201458882;\n }\n\n public static void updateTabScrollPosition(ActionBar actionBar, int position, float positionOffset, int positionOffsetPixels) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollPosition(position, positionOffset, positionOffsetPixels);\n }\n }\n\n public static void updateTabScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollState(state);\n }\n }\n\n public static void updateMenuScrollPosition(ActionBar actionBar, int index, float offset) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollPosition(index, offset);\n }\n }\n\n public static void updateMenuScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).updateMenuScrollState(state);\n }\n }\n\n public static void updateMenuScrollData(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollData();\n }\n }\n\n public static void setMenuUpdateMode(ActionBar actionBar, int mode) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).setMenuUpdateMode(mode);\n }\n }\n\n public static void lockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).lockMenuUpdate();\n }\n }\n\n public static void unlockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).unlockMenuUpdate();\n }\n }\n\n public static void setDropdownDismissCallback(ActionBar actionBar, DropdownDismissCallback callback) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownDismissCallback(callback);\n }\n }\n\n public static void setDropdownItemClickListener(ActionBar actionBar, OnItemClickListener listener) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownItemClickListener(listener);\n }\n }\n\n public static void setDropdownUpdateAfterAnim(ActionBar actionBar, boolean update) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownUpdateAfterAnim(update);\n }\n }\n\n public static void setHasEmbeddedTabs(ActionBar actionBar, boolean hasEmbeddedTabs) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setEmbeddedTabs(hasEmbeddedTabs);\n }\n }\n\n public static void setSplitActionBarOverlay(ActionBar actionBar, boolean overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarOverlay(overlay);\n }\n }\n\n public static void setSplitHideWithActionBar(ActionBar actionBar, boolean hideWith) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitHideWithActionBar(hideWith);\n }\n }\n\n public static boolean hasEmbeddedTabs(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).hasEmbeddedTabs();\n }\n return false;\n }\n\n public static void setColorWindowContentOverlay(ActionBar actionBar, Drawable overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorWindowContentOverlay(overlay);\n }\n }\n\n public static void setColorBottomWindowContentOverlay(ActionBar actionBar, Drawable bottomOverlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorBottomWindowContentOverlay(bottomOverlay);\n }\n }\n\n public static void setIgnoreColorWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setIgnoreColorBottomWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorBottomWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setStatusBarActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setStatusBarActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarTextColor(textColor);\n }\n }\n\n public static void setBackTitleTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitleTextColor(textColor);\n }\n }\n\n public static void setTitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setTitleTextColor(textColor);\n }\n }\n\n public static void setSubtitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSubtitleTextColor(textColor);\n }\n }\n\n public static void setActionMenuTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionMenuTextColor(textColor);\n }\n }\n\n public static boolean requestWindowFeature(Activity activity, int featureId) {\n if (activity instanceof ActivityCallback) {\n return ((ActivityCallback) activity).supportRequestWindowFeature(featureId);\n }\n return activity.requestWindowFeature(featureId);\n }\n\n public static void setProgressBarVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarVisibility(visible);\n } else {\n activity.setProgressBarVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminateVisibility(Activity activity, boolean visible) {\n ", "post_mask_code": "\n }\n\n public static void setProgressBarIndeterminate(Activity activity, boolean indeterminate) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminate(indeterminate);\n } else {\n activity.setProgressBarIndeterminate(indeterminate);\n }\n }\n\n public static void setProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgress(progress);\n } else {\n activity.setProgress(progress);\n }\n }\n\n public static void setSecondaryProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportSecondaryProgress(progress);\n } else {\n activity.setSecondaryProgress(progress);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, CharSequence title) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(title);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(resId);\n }\n }\n\n public static void setHintText(ActionBar actionBar, CharSequence hintText) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(hintText);\n }\n }\n\n public static void setHintText(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(resId);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, CharSequence subtitle) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(subtitle);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(resId);\n }\n }\n\n public static void setMainActionBar(ActionBar actionBar, boolean isMain) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setMainActionBar(isMain);\n }\n }\n}\n"} {"task_id": "Java_183", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/dstmath/OppoFramework/A5_8_1_0/src/main/java/com/color/actionbar/app/ColorActionBarUtil.java", "mask_start_position": 12229, "mask_end_position": 12230, "canonical_solution": "}", "pre_mask_code": "package com.color.actionbar.app;\n\nimport android.animation.Animator;\nimport android.animation.Animator.AnimatorListener;\nimport android.app.ActionBar;\nimport android.app.Activity;\nimport android.content.res.ColorStateList;\nimport android.graphics.drawable.Drawable;\nimport android.view.View;\nimport android.widget.AdapterView.OnItemClickListener;\nimport com.android.internal.R;\nimport com.color.animation.ColorAnimatorWrapper;\nimport com.color.widget.ColorActionModeCallback;\nimport com.color.widget.ColorBottomMenuCallback;\nimport com.color.widget.ColorPagerCallback;\nimport com.color.widget.ColorSpinnerCallback;\nimport com.color.widget.ColorSpinnerCallback.DropdownDismissCallback;\nimport java.util.List;\n\npublic class ColorActionBarUtil {\n\n private static final boolean DBG = false;\n\n private static final String TAG = \"ColorActionBarUtil\";\n\n static final String THEME_CUSTOM_ACTIONBAR = \"oppo:Theme.OPPO.CustomActionBar\";\n\n public interface ScrollTabCallback extends ColorPagerCallback {\n\n void updateTabScrollPosition(int i, float f, int i2);\n\n void updateTabScrollState(int i);\n }\n\n public interface ActionBarCallback extends ScrollTabCallback, ColorBottomMenuCallback, ColorSpinnerCallback {\n\n void addAfterAnimator(Animator animator);\n\n void addAfterAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addAfterAnimatorWrappers(List list);\n\n void addAfterAnimators(List list);\n\n void addBeforeAnimator(Animator animator);\n\n void addBeforeAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addBeforeAnimatorWrappers(List list);\n\n void addBeforeAnimators(List list);\n\n void addHideListener(AnimatorListener animatorListener);\n\n void addSearchViewHideListener(AnimatorListener animatorListener);\n\n void addSearchViewShowListener(AnimatorListener animatorListener);\n\n void addSearchViewWithAnimator(Animator animator);\n\n void addShowListener(AnimatorListener animatorListener);\n\n void addWithAnimator(Animator animator);\n\n void addWithAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addWithAnimatorWrappers(List list);\n\n void addWithAnimators(List list);\n\n void cancelShowHide();\n\n int getContentId();\n\n int getHomeId();\n\n boolean hasEmbeddedTabs();\n\n void setActionBarSubTitle(int i);\n\n void setActionBarSubTitle(CharSequence charSequence);\n\n void setActionMenuTextColor(ColorStateList colorStateList);\n\n void setActionModeAnim(boolean z);\n\n void setActionModeCallback(ColorActionModeCallback colorActionModeCallback);\n\n void setBackTitle(int i);\n\n void setBackTitle(CharSequence charSequence);\n\n void setBackTitleTextColor(ColorStateList colorStateList);\n\n void setColorBottomWindowContentOverlay(Drawable drawable);\n\n void setColorWindowContentOverlay(Drawable drawable);\n\n void setEmbeddedTabs(boolean z);\n\n void setHintText(int i);\n\n void setHintText(CharSequence charSequence);\n\n void setIgnoreColorBottomWindowContentOverlay(boolean z);\n\n void setIgnoreColorWindowContentOverlay(boolean z);\n\n void setMainActionBar(boolean z);\n\n void setSearchBarMode(boolean z);\n\n void setSplitActionBarBg(Drawable drawable);\n\n void setSplitActionBarOverlay(boolean z);\n\n void setSplitActionBarTextColor(ColorStateList colorStateList);\n\n void setSplitHideWithActionBar(boolean z);\n\n void setStatusBarActionBarBg(Drawable drawable);\n\n void setSubtitleTextColor(int i);\n\n void setTitleTextColor(int i);\n }\n\n public interface DelegateCallback {\n\n boolean hasWindowFeature(int i);\n\n void superSetContentView(int i);\n\n void superSetContentView(View view);\n\n boolean supportRequestWindowFeature(int i);\n }\n\n public interface ActivityCallback extends DelegateCallback {\n\n void setSupportProgress(int i);\n\n void setSupportProgressBarIndeterminate(boolean z);\n\n void setSupportProgressBarIndeterminateVisibility(boolean z);\n\n void setSupportProgressBarVisibility(boolean z);\n\n void setSupportSecondaryProgress(int i);\n }\n\n public interface DialogCallback extends DelegateCallback {\n }\n\n public static int getContentId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getContentId();\n }\n return 16908290;\n }\n\n public static int getHomeId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getHomeId();\n }\n return R.id.home;\n }\n\n public static int getBottomMenuViewId() {\n return 201458882;\n }\n\n public static void updateTabScrollPosition(ActionBar actionBar, int position, float positionOffset, int positionOffsetPixels) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollPosition(position, positionOffset, positionOffsetPixels);\n }\n }\n\n public static void updateTabScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollState(state);\n }\n }\n\n public static void updateMenuScrollPosition(ActionBar actionBar, int index, float offset) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollPosition(index, offset);\n }\n }\n\n public static void updateMenuScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).updateMenuScrollState(state);\n }\n }\n\n public static void updateMenuScrollData(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollData();\n }\n }\n\n public static void setMenuUpdateMode(ActionBar actionBar, int mode) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).setMenuUpdateMode(mode);\n }\n }\n\n public static void lockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).lockMenuUpdate();\n }\n }\n\n public static void unlockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).unlockMenuUpdate();\n }\n }\n\n public static void setDropdownDismissCallback(ActionBar actionBar, DropdownDismissCallback callback) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownDismissCallback(callback);\n }\n }\n\n public static void setDropdownItemClickListener(ActionBar actionBar, OnItemClickListener listener) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownItemClickListener(listener);\n }\n }\n\n public static void setDropdownUpdateAfterAnim(ActionBar actionBar, boolean update) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownUpdateAfterAnim(update);\n }\n }\n\n public static void setHasEmbeddedTabs(ActionBar actionBar, boolean hasEmbeddedTabs) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setEmbeddedTabs(hasEmbeddedTabs);\n }\n }\n\n public static void setSplitActionBarOverlay(ActionBar actionBar, boolean overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarOverlay(overlay);\n }\n }\n\n public static void setSplitHideWithActionBar(ActionBar actionBar, boolean hideWith) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitHideWithActionBar(hideWith);\n }\n }\n\n public static boolean hasEmbeddedTabs(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).hasEmbeddedTabs();\n }\n return false;\n }\n\n public static void setColorWindowContentOverlay(ActionBar actionBar, Drawable overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorWindowContentOverlay(overlay);\n }\n }\n\n public static void setColorBottomWindowContentOverlay(ActionBar actionBar, Drawable bottomOverlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorBottomWindowContentOverlay(bottomOverlay);\n }\n }\n\n public static void setIgnoreColorWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setIgnoreColorBottomWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorBottomWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setStatusBarActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setStatusBarActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarTextColor(textColor);\n }\n }\n\n public static void setBackTitleTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitleTextColor(textColor);\n }\n }\n\n public static void setTitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setTitleTextColor(textColor);\n }\n }\n\n public static void setSubtitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSubtitleTextColor(textColor);\n }\n }\n\n public static void setActionMenuTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionMenuTextColor(textColor);\n }\n }\n\n public static boolean requestWindowFeature(Activity activity, int featureId) {\n if (activity instanceof ActivityCallback) {\n return ((ActivityCallback) activity).supportRequestWindowFeature(featureId);\n }\n return activity.requestWindowFeature(featureId);\n }\n\n public static void setProgressBarVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarVisibility(visible);\n } else {\n activity.setProgressBarVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminateVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminateVisibility(visible);\n } else {\n activity.setProgressBarIndeterminateVisibility(visible);\n }\n ", "post_mask_code": "\n\n public static void setProgressBarIndeterminate(Activity activity, boolean indeterminate) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminate(indeterminate);\n } else {\n activity.setProgressBarIndeterminate(indeterminate);\n }\n }\n\n public static void setProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgress(progress);\n } else {\n activity.setProgress(progress);\n }\n }\n\n public static void setSecondaryProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportSecondaryProgress(progress);\n } else {\n activity.setSecondaryProgress(progress);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, CharSequence title) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(title);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(resId);\n }\n }\n\n public static void setHintText(ActionBar actionBar, CharSequence hintText) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(hintText);\n }\n }\n\n public static void setHintText(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(resId);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, CharSequence subtitle) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(subtitle);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(resId);\n }\n }\n\n public static void setMainActionBar(ActionBar actionBar, boolean isMain) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setMainActionBar(isMain);\n }\n }\n}\n"} {"task_id": "Java_184", "language": "Java", "task_type": "single_line", "source_file": "java/github/dstmath/OppoFramework/A5_8_1_0/src/main/java/com/color/actionbar/app/ColorActionBarUtil.java", "mask_start_position": 8559, "mask_end_position": 8572, "canonical_solution": "return false;", "pre_mask_code": "package com.color.actionbar.app;\n\nimport android.animation.Animator;\nimport android.animation.Animator.AnimatorListener;\nimport android.app.ActionBar;\nimport android.app.Activity;\nimport android.content.res.ColorStateList;\nimport android.graphics.drawable.Drawable;\nimport android.view.View;\nimport android.widget.AdapterView.OnItemClickListener;\nimport com.android.internal.R;\nimport com.color.animation.ColorAnimatorWrapper;\nimport com.color.widget.ColorActionModeCallback;\nimport com.color.widget.ColorBottomMenuCallback;\nimport com.color.widget.ColorPagerCallback;\nimport com.color.widget.ColorSpinnerCallback;\nimport com.color.widget.ColorSpinnerCallback.DropdownDismissCallback;\nimport java.util.List;\n\npublic class ColorActionBarUtil {\n\n private static final boolean DBG = false;\n\n private static final String TAG = \"ColorActionBarUtil\";\n\n static final String THEME_CUSTOM_ACTIONBAR = \"oppo:Theme.OPPO.CustomActionBar\";\n\n public interface ScrollTabCallback extends ColorPagerCallback {\n\n void updateTabScrollPosition(int i, float f, int i2);\n\n void updateTabScrollState(int i);\n }\n\n public interface ActionBarCallback extends ScrollTabCallback, ColorBottomMenuCallback, ColorSpinnerCallback {\n\n void addAfterAnimator(Animator animator);\n\n void addAfterAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addAfterAnimatorWrappers(List list);\n\n void addAfterAnimators(List list);\n\n void addBeforeAnimator(Animator animator);\n\n void addBeforeAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addBeforeAnimatorWrappers(List list);\n\n void addBeforeAnimators(List list);\n\n void addHideListener(AnimatorListener animatorListener);\n\n void addSearchViewHideListener(AnimatorListener animatorListener);\n\n void addSearchViewShowListener(AnimatorListener animatorListener);\n\n void addSearchViewWithAnimator(Animator animator);\n\n void addShowListener(AnimatorListener animatorListener);\n\n void addWithAnimator(Animator animator);\n\n void addWithAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addWithAnimatorWrappers(List list);\n\n void addWithAnimators(List list);\n\n void cancelShowHide();\n\n int getContentId();\n\n int getHomeId();\n\n boolean hasEmbeddedTabs();\n\n void setActionBarSubTitle(int i);\n\n void setActionBarSubTitle(CharSequence charSequence);\n\n void setActionMenuTextColor(ColorStateList colorStateList);\n\n void setActionModeAnim(boolean z);\n\n void setActionModeCallback(ColorActionModeCallback colorActionModeCallback);\n\n void setBackTitle(int i);\n\n void setBackTitle(CharSequence charSequence);\n\n void setBackTitleTextColor(ColorStateList colorStateList);\n\n void setColorBottomWindowContentOverlay(Drawable drawable);\n\n void setColorWindowContentOverlay(Drawable drawable);\n\n void setEmbeddedTabs(boolean z);\n\n void setHintText(int i);\n\n void setHintText(CharSequence charSequence);\n\n void setIgnoreColorBottomWindowContentOverlay(boolean z);\n\n void setIgnoreColorWindowContentOverlay(boolean z);\n\n void setMainActionBar(boolean z);\n\n void setSearchBarMode(boolean z);\n\n void setSplitActionBarBg(Drawable drawable);\n\n void setSplitActionBarOverlay(boolean z);\n\n void setSplitActionBarTextColor(ColorStateList colorStateList);\n\n void setSplitHideWithActionBar(boolean z);\n\n void setStatusBarActionBarBg(Drawable drawable);\n\n void setSubtitleTextColor(int i);\n\n void setTitleTextColor(int i);\n }\n\n public interface DelegateCallback {\n\n boolean hasWindowFeature(int i);\n\n void superSetContentView(int i);\n\n void superSetContentView(View view);\n\n boolean supportRequestWindowFeature(int i);\n }\n\n public interface ActivityCallback extends DelegateCallback {\n\n void setSupportProgress(int i);\n\n void setSupportProgressBarIndeterminate(boolean z);\n\n void setSupportProgressBarIndeterminateVisibility(boolean z);\n\n void setSupportProgressBarVisibility(boolean z);\n\n void setSupportSecondaryProgress(int i);\n }\n\n public interface DialogCallback extends DelegateCallback {\n }\n\n public static int getContentId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getContentId();\n }\n return 16908290;\n }\n\n public static int getHomeId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getHomeId();\n }\n return R.id.home;\n }\n\n public static int getBottomMenuViewId() {\n return 201458882;\n }\n\n public static void updateTabScrollPosition(ActionBar actionBar, int position, float positionOffset, int positionOffsetPixels) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollPosition(position, positionOffset, positionOffsetPixels);\n }\n }\n\n public static void updateTabScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollState(state);\n }\n }\n\n public static void updateMenuScrollPosition(ActionBar actionBar, int index, float offset) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollPosition(index, offset);\n }\n }\n\n public static void updateMenuScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).updateMenuScrollState(state);\n }\n }\n\n public static void updateMenuScrollData(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollData();\n }\n }\n\n public static void setMenuUpdateMode(ActionBar actionBar, int mode) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).setMenuUpdateMode(mode);\n }\n }\n\n public static void lockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).lockMenuUpdate();\n }\n }\n\n public static void unlockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).unlockMenuUpdate();\n }\n }\n\n public static void setDropdownDismissCallback(ActionBar actionBar, DropdownDismissCallback callback) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownDismissCallback(callback);\n }\n }\n\n public static void setDropdownItemClickListener(ActionBar actionBar, OnItemClickListener listener) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownItemClickListener(listener);\n }\n }\n\n public static void setDropdownUpdateAfterAnim(ActionBar actionBar, boolean update) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownUpdateAfterAnim(update);\n }\n }\n\n public static void setHasEmbeddedTabs(ActionBar actionBar, boolean hasEmbeddedTabs) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setEmbeddedTabs(hasEmbeddedTabs);\n }\n }\n\n public static void setSplitActionBarOverlay(ActionBar actionBar, boolean overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarOverlay(overlay);\n }\n }\n\n public static void setSplitHideWithActionBar(ActionBar actionBar, boolean hideWith) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitHideWithActionBar(hideWith);\n }\n }\n\n public static boolean hasEmbeddedTabs(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).hasEmbeddedTabs();\n }\n ", "post_mask_code": "\n }\n\n public static void setColorWindowContentOverlay(ActionBar actionBar, Drawable overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorWindowContentOverlay(overlay);\n }\n }\n\n public static void setColorBottomWindowContentOverlay(ActionBar actionBar, Drawable bottomOverlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorBottomWindowContentOverlay(bottomOverlay);\n }\n }\n\n public static void setIgnoreColorWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setIgnoreColorBottomWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorBottomWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setStatusBarActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setStatusBarActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarTextColor(textColor);\n }\n }\n\n public static void setBackTitleTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitleTextColor(textColor);\n }\n }\n\n public static void setTitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setTitleTextColor(textColor);\n }\n }\n\n public static void setSubtitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSubtitleTextColor(textColor);\n }\n }\n\n public static void setActionMenuTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionMenuTextColor(textColor);\n }\n }\n\n public static boolean requestWindowFeature(Activity activity, int featureId) {\n if (activity instanceof ActivityCallback) {\n return ((ActivityCallback) activity).supportRequestWindowFeature(featureId);\n }\n return activity.requestWindowFeature(featureId);\n }\n\n public static void setProgressBarVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarVisibility(visible);\n } else {\n activity.setProgressBarVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminateVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminateVisibility(visible);\n } else {\n activity.setProgressBarIndeterminateVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminate(Activity activity, boolean indeterminate) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminate(indeterminate);\n } else {\n activity.setProgressBarIndeterminate(indeterminate);\n }\n }\n\n public static void setProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgress(progress);\n } else {\n activity.setProgress(progress);\n }\n }\n\n public static void setSecondaryProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportSecondaryProgress(progress);\n } else {\n activity.setSecondaryProgress(progress);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, CharSequence title) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(title);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(resId);\n }\n }\n\n public static void setHintText(ActionBar actionBar, CharSequence hintText) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(hintText);\n }\n }\n\n public static void setHintText(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(resId);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, CharSequence subtitle) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(subtitle);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(resId);\n }\n }\n\n public static void setMainActionBar(ActionBar actionBar, boolean isMain) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setMainActionBar(isMain);\n }\n }\n}\n"} {"task_id": "Java_185", "language": "Java", "task_type": "if_statement", "source_file": "java/github/dstmath/OppoFramework/A5_8_1_0/src/main/java/com/color/actionbar/app/ColorActionBarUtil.java", "mask_start_position": 6070, "mask_end_position": 6205, "canonical_solution": "if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollData();\n }", "pre_mask_code": "package com.color.actionbar.app;\n\nimport android.animation.Animator;\nimport android.animation.Animator.AnimatorListener;\nimport android.app.ActionBar;\nimport android.app.Activity;\nimport android.content.res.ColorStateList;\nimport android.graphics.drawable.Drawable;\nimport android.view.View;\nimport android.widget.AdapterView.OnItemClickListener;\nimport com.android.internal.R;\nimport com.color.animation.ColorAnimatorWrapper;\nimport com.color.widget.ColorActionModeCallback;\nimport com.color.widget.ColorBottomMenuCallback;\nimport com.color.widget.ColorPagerCallback;\nimport com.color.widget.ColorSpinnerCallback;\nimport com.color.widget.ColorSpinnerCallback.DropdownDismissCallback;\nimport java.util.List;\n\npublic class ColorActionBarUtil {\n\n private static final boolean DBG = false;\n\n private static final String TAG = \"ColorActionBarUtil\";\n\n static final String THEME_CUSTOM_ACTIONBAR = \"oppo:Theme.OPPO.CustomActionBar\";\n\n public interface ScrollTabCallback extends ColorPagerCallback {\n\n void updateTabScrollPosition(int i, float f, int i2);\n\n void updateTabScrollState(int i);\n }\n\n public interface ActionBarCallback extends ScrollTabCallback, ColorBottomMenuCallback, ColorSpinnerCallback {\n\n void addAfterAnimator(Animator animator);\n\n void addAfterAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addAfterAnimatorWrappers(List list);\n\n void addAfterAnimators(List list);\n\n void addBeforeAnimator(Animator animator);\n\n void addBeforeAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addBeforeAnimatorWrappers(List list);\n\n void addBeforeAnimators(List list);\n\n void addHideListener(AnimatorListener animatorListener);\n\n void addSearchViewHideListener(AnimatorListener animatorListener);\n\n void addSearchViewShowListener(AnimatorListener animatorListener);\n\n void addSearchViewWithAnimator(Animator animator);\n\n void addShowListener(AnimatorListener animatorListener);\n\n void addWithAnimator(Animator animator);\n\n void addWithAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addWithAnimatorWrappers(List list);\n\n void addWithAnimators(List list);\n\n void cancelShowHide();\n\n int getContentId();\n\n int getHomeId();\n\n boolean hasEmbeddedTabs();\n\n void setActionBarSubTitle(int i);\n\n void setActionBarSubTitle(CharSequence charSequence);\n\n void setActionMenuTextColor(ColorStateList colorStateList);\n\n void setActionModeAnim(boolean z);\n\n void setActionModeCallback(ColorActionModeCallback colorActionModeCallback);\n\n void setBackTitle(int i);\n\n void setBackTitle(CharSequence charSequence);\n\n void setBackTitleTextColor(ColorStateList colorStateList);\n\n void setColorBottomWindowContentOverlay(Drawable drawable);\n\n void setColorWindowContentOverlay(Drawable drawable);\n\n void setEmbeddedTabs(boolean z);\n\n void setHintText(int i);\n\n void setHintText(CharSequence charSequence);\n\n void setIgnoreColorBottomWindowContentOverlay(boolean z);\n\n void setIgnoreColorWindowContentOverlay(boolean z);\n\n void setMainActionBar(boolean z);\n\n void setSearchBarMode(boolean z);\n\n void setSplitActionBarBg(Drawable drawable);\n\n void setSplitActionBarOverlay(boolean z);\n\n void setSplitActionBarTextColor(ColorStateList colorStateList);\n\n void setSplitHideWithActionBar(boolean z);\n\n void setStatusBarActionBarBg(Drawable drawable);\n\n void setSubtitleTextColor(int i);\n\n void setTitleTextColor(int i);\n }\n\n public interface DelegateCallback {\n\n boolean hasWindowFeature(int i);\n\n void superSetContentView(int i);\n\n void superSetContentView(View view);\n\n boolean supportRequestWindowFeature(int i);\n }\n\n public interface ActivityCallback extends DelegateCallback {\n\n void setSupportProgress(int i);\n\n void setSupportProgressBarIndeterminate(boolean z);\n\n void setSupportProgressBarIndeterminateVisibility(boolean z);\n\n void setSupportProgressBarVisibility(boolean z);\n\n void setSupportSecondaryProgress(int i);\n }\n\n public interface DialogCallback extends DelegateCallback {\n }\n\n public static int getContentId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getContentId();\n }\n return 16908290;\n }\n\n public static int getHomeId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getHomeId();\n }\n return R.id.home;\n }\n\n public static int getBottomMenuViewId() {\n return 201458882;\n }\n\n public static void updateTabScrollPosition(ActionBar actionBar, int position, float positionOffset, int positionOffsetPixels) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollPosition(position, positionOffset, positionOffsetPixels);\n }\n }\n\n public static void updateTabScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollState(state);\n }\n }\n\n public static void updateMenuScrollPosition(ActionBar actionBar, int index, float offset) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollPosition(index, offset);\n }\n }\n\n public static void updateMenuScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).updateMenuScrollState(state);\n }\n }\n\n public static void updateMenuScrollData(ActionBar actionBar) {\n ", "post_mask_code": "\n }\n\n public static void setMenuUpdateMode(ActionBar actionBar, int mode) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).setMenuUpdateMode(mode);\n }\n }\n\n public static void lockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).lockMenuUpdate();\n }\n }\n\n public static void unlockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).unlockMenuUpdate();\n }\n }\n\n public static void setDropdownDismissCallback(ActionBar actionBar, DropdownDismissCallback callback) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownDismissCallback(callback);\n }\n }\n\n public static void setDropdownItemClickListener(ActionBar actionBar, OnItemClickListener listener) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownItemClickListener(listener);\n }\n }\n\n public static void setDropdownUpdateAfterAnim(ActionBar actionBar, boolean update) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownUpdateAfterAnim(update);\n }\n }\n\n public static void setHasEmbeddedTabs(ActionBar actionBar, boolean hasEmbeddedTabs) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setEmbeddedTabs(hasEmbeddedTabs);\n }\n }\n\n public static void setSplitActionBarOverlay(ActionBar actionBar, boolean overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarOverlay(overlay);\n }\n }\n\n public static void setSplitHideWithActionBar(ActionBar actionBar, boolean hideWith) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitHideWithActionBar(hideWith);\n }\n }\n\n public static boolean hasEmbeddedTabs(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).hasEmbeddedTabs();\n }\n return false;\n }\n\n public static void setColorWindowContentOverlay(ActionBar actionBar, Drawable overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorWindowContentOverlay(overlay);\n }\n }\n\n public static void setColorBottomWindowContentOverlay(ActionBar actionBar, Drawable bottomOverlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorBottomWindowContentOverlay(bottomOverlay);\n }\n }\n\n public static void setIgnoreColorWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setIgnoreColorBottomWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorBottomWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setStatusBarActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setStatusBarActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarTextColor(textColor);\n }\n }\n\n public static void setBackTitleTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitleTextColor(textColor);\n }\n }\n\n public static void setTitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setTitleTextColor(textColor);\n }\n }\n\n public static void setSubtitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSubtitleTextColor(textColor);\n }\n }\n\n public static void setActionMenuTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionMenuTextColor(textColor);\n }\n }\n\n public static boolean requestWindowFeature(Activity activity, int featureId) {\n if (activity instanceof ActivityCallback) {\n return ((ActivityCallback) activity).supportRequestWindowFeature(featureId);\n }\n return activity.requestWindowFeature(featureId);\n }\n\n public static void setProgressBarVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarVisibility(visible);\n } else {\n activity.setProgressBarVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminateVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminateVisibility(visible);\n } else {\n activity.setProgressBarIndeterminateVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminate(Activity activity, boolean indeterminate) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminate(indeterminate);\n } else {\n activity.setProgressBarIndeterminate(indeterminate);\n }\n }\n\n public static void setProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgress(progress);\n } else {\n activity.setProgress(progress);\n }\n }\n\n public static void setSecondaryProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportSecondaryProgress(progress);\n } else {\n activity.setSecondaryProgress(progress);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, CharSequence title) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(title);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(resId);\n }\n }\n\n public static void setHintText(ActionBar actionBar, CharSequence hintText) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(hintText);\n }\n }\n\n public static void setHintText(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(resId);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, CharSequence subtitle) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(subtitle);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(resId);\n }\n }\n\n public static void setMainActionBar(ActionBar actionBar, boolean isMain) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setMainActionBar(isMain);\n }\n }\n}\n"} {"task_id": "Java_186", "language": "Java", "task_type": "empty", "source_file": "java/github/dstmath/OppoFramework/A5_8_1_0/src/main/java/com/color/actionbar/app/ColorActionBarUtil.java", "mask_start_position": 14654, "mask_end_position": 14654, "canonical_solution": "", "pre_mask_code": "package com.color.actionbar.app;\n\nimport android.animation.Animator;\nimport android.animation.Animator.AnimatorListener;\nimport android.app.ActionBar;\nimport android.app.Activity;\nimport android.content.res.ColorStateList;\nimport android.graphics.drawable.Drawable;\nimport android.view.View;\nimport android.widget.AdapterView.OnItemClickListener;\nimport com.android.internal.R;\nimport com.color.animation.ColorAnimatorWrapper;\nimport com.color.widget.ColorActionModeCallback;\nimport com.color.widget.ColorBottomMenuCallback;\nimport com.color.widget.ColorPagerCallback;\nimport com.color.widget.ColorSpinnerCallback;\nimport com.color.widget.ColorSpinnerCallback.DropdownDismissCallback;\nimport java.util.List;\n\npublic class ColorActionBarUtil {\n\n private static final boolean DBG = false;\n\n private static final String TAG = \"ColorActionBarUtil\";\n\n static final String THEME_CUSTOM_ACTIONBAR = \"oppo:Theme.OPPO.CustomActionBar\";\n\n public interface ScrollTabCallback extends ColorPagerCallback {\n\n void updateTabScrollPosition(int i, float f, int i2);\n\n void updateTabScrollState(int i);\n }\n\n public interface ActionBarCallback extends ScrollTabCallback, ColorBottomMenuCallback, ColorSpinnerCallback {\n\n void addAfterAnimator(Animator animator);\n\n void addAfterAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addAfterAnimatorWrappers(List list);\n\n void addAfterAnimators(List list);\n\n void addBeforeAnimator(Animator animator);\n\n void addBeforeAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addBeforeAnimatorWrappers(List list);\n\n void addBeforeAnimators(List list);\n\n void addHideListener(AnimatorListener animatorListener);\n\n void addSearchViewHideListener(AnimatorListener animatorListener);\n\n void addSearchViewShowListener(AnimatorListener animatorListener);\n\n void addSearchViewWithAnimator(Animator animator);\n\n void addShowListener(AnimatorListener animatorListener);\n\n void addWithAnimator(Animator animator);\n\n void addWithAnimatorWrapper(ColorAnimatorWrapper colorAnimatorWrapper);\n\n void addWithAnimatorWrappers(List list);\n\n void addWithAnimators(List list);\n\n void cancelShowHide();\n\n int getContentId();\n\n int getHomeId();\n\n boolean hasEmbeddedTabs();\n\n void setActionBarSubTitle(int i);\n\n void setActionBarSubTitle(CharSequence charSequence);\n\n void setActionMenuTextColor(ColorStateList colorStateList);\n\n void setActionModeAnim(boolean z);\n\n void setActionModeCallback(ColorActionModeCallback colorActionModeCallback);\n\n void setBackTitle(int i);\n\n void setBackTitle(CharSequence charSequence);\n\n void setBackTitleTextColor(ColorStateList colorStateList);\n\n void setColorBottomWindowContentOverlay(Drawable drawable);\n\n void setColorWindowContentOverlay(Drawable drawable);\n\n void setEmbeddedTabs(boolean z);\n\n void setHintText(int i);\n\n void setHintText(CharSequence charSequence);\n\n void setIgnoreColorBottomWindowContentOverlay(boolean z);\n\n void setIgnoreColorWindowContentOverlay(boolean z);\n\n void setMainActionBar(boolean z);\n\n void setSearchBarMode(boolean z);\n\n void setSplitActionBarBg(Drawable drawable);\n\n void setSplitActionBarOverlay(boolean z);\n\n void setSplitActionBarTextColor(ColorStateList colorStateList);\n\n void setSplitHideWithActionBar(boolean z);\n\n void setStatusBarActionBarBg(Drawable drawable);\n\n void setSubtitleTextColor(int i);\n\n void setTitleTextColor(int i);\n }\n\n public interface DelegateCallback {\n\n boolean hasWindowFeature(int i);\n\n void superSetContentView(int i);\n\n void superSetContentView(View view);\n\n boolean supportRequestWindowFeature(int i);\n }\n\n public interface ActivityCallback extends DelegateCallback {\n\n void setSupportProgress(int i);\n\n void setSupportProgressBarIndeterminate(boolean z);\n\n void setSupportProgressBarIndeterminateVisibility(boolean z);\n\n void setSupportProgressBarVisibility(boolean z);\n\n void setSupportSecondaryProgress(int i);\n }\n\n public interface DialogCallback extends DelegateCallback {\n }\n\n public static int getContentId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getContentId();\n }\n return 16908290;\n }\n\n public static int getHomeId(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).getHomeId();\n }\n return R.id.home;\n }\n\n public static int getBottomMenuViewId() {\n return 201458882;\n }\n\n public static void updateTabScrollPosition(ActionBar actionBar, int position, float positionOffset, int positionOffsetPixels) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollPosition(position, positionOffset, positionOffsetPixels);\n }\n }\n\n public static void updateTabScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ScrollTabCallback) {\n ((ScrollTabCallback) actionBar).updateTabScrollState(state);\n }\n }\n\n public static void updateMenuScrollPosition(ActionBar actionBar, int index, float offset) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollPosition(index, offset);\n }\n }\n\n public static void updateMenuScrollState(ActionBar actionBar, int state) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).updateMenuScrollState(state);\n }\n }\n\n public static void updateMenuScrollData(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).updateMenuScrollData();\n }\n }\n\n public static void setMenuUpdateMode(ActionBar actionBar, int mode) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).setMenuUpdateMode(mode);\n }\n }\n\n public static void lockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).lockMenuUpdate();\n }\n }\n\n public static void unlockMenuUpdate(ActionBar actionBar) {\n if (actionBar instanceof ColorBottomMenuCallback) {\n ((ColorBottomMenuCallback) actionBar).unlockMenuUpdate();\n }\n }\n\n public static void setDropdownDismissCallback(ActionBar actionBar, DropdownDismissCallback callback) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownDismissCallback(callback);\n }\n }\n\n public static void setDropdownItemClickListener(ActionBar actionBar, OnItemClickListener listener) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownItemClickListener(listener);\n }\n }\n\n public static void setDropdownUpdateAfterAnim(ActionBar actionBar, boolean update) {\n if (actionBar instanceof ColorSpinnerCallback) {\n ((ColorSpinnerCallback) actionBar).setDropdownUpdateAfterAnim(update);\n }\n }\n\n public static void setHasEmbeddedTabs(ActionBar actionBar, boolean hasEmbeddedTabs) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setEmbeddedTabs(hasEmbeddedTabs);\n }\n }\n\n public static void setSplitActionBarOverlay(ActionBar actionBar, boolean overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarOverlay(overlay);\n }\n }\n\n public static void setSplitHideWithActionBar(ActionBar actionBar, boolean hideWith) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitHideWithActionBar(hideWith);\n }\n }\n\n public static boolean hasEmbeddedTabs(ActionBar actionBar) {\n if (actionBar instanceof ActionBarCallback) {\n return ((ActionBarCallback) actionBar).hasEmbeddedTabs();\n }\n return false;\n }\n\n public static void setColorWindowContentOverlay(ActionBar actionBar, Drawable overlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorWindowContentOverlay(overlay);\n }\n }\n\n public static void setColorBottomWindowContentOverlay(ActionBar actionBar, Drawable bottomOverlay) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setColorBottomWindowContentOverlay(bottomOverlay);\n }\n }\n\n public static void setIgnoreColorWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setIgnoreColorBottomWindowContentOverlay(ActionBar actionBar, boolean isIgnore) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setIgnoreColorBottomWindowContentOverlay(isIgnore);\n }\n }\n\n public static void setStatusBarActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setStatusBarActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarBg(ActionBar actionBar, Drawable bg) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarBg(bg);\n }\n }\n\n public static void setSplitActionBarTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSplitActionBarTextColor(textColor);\n }\n }\n\n public static void setBackTitleTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitleTextColor(textColor);\n }\n }\n\n public static void setTitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setTitleTextColor(textColor);\n }\n }\n\n public static void setSubtitleTextColor(ActionBar actionBar, int textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setSubtitleTextColor(textColor);\n }\n }\n\n public static void setActionMenuTextColor(ActionBar actionBar, ColorStateList textColor) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionMenuTextColor(textColor);\n }\n }\n\n public static boolean requestWindowFeature(Activity activity, int featureId) {\n if (activity instanceof ActivityCallback) {\n return ((ActivityCallback) activity).supportRequestWindowFeature(featureId);\n }\n return activity.requestWindowFeature(featureId);\n }\n\n public static void setProgressBarVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarVisibility(visible);\n } else {\n activity.setProgressBarVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminateVisibility(Activity activity, boolean visible) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminateVisibility(visible);\n } else {\n activity.setProgressBarIndeterminateVisibility(visible);\n }\n }\n\n public static void setProgressBarIndeterminate(Activity activity, boolean indeterminate) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgressBarIndeterminate(indeterminate);\n } else {\n activity.setProgressBarIndeterminate(indeterminate);\n }\n }\n\n public static void setProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportProgress(progress);\n } else {\n activity.setProgress(progress);\n }\n }\n\n public static void setSecondaryProgress(Activity activity, int progress) {\n if (activity instanceof ActivityCallback) {\n ((ActivityCallback) activity).setSupportSecondaryProgress(progress);\n } else {\n activity.setSecondaryProgress(progress);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, CharSequence title) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(title);\n }\n }\n\n public static void setBackTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setBackTitle(resId);\n }\n }\n\n public static void setHintText(ActionBar actionBar, CharSequence hintText) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(hintText);\n }\n }\n\n public static void setHintText(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setHintText(resId);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, CharSequence subtitle) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(subtitle);\n }\n }\n\n public static void setActionBarSubTitle(ActionBar actionBar, int resId) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setActionBarSubTitle(resId);\n }\n }\n\n public static void setMainActionBar(ActionBar actionBar, boolean isMain) {\n if (actionBar instanceof ActionBarCallback) {\n ((ActionBarCallback) actionBar).setMainActionBar(isMain);\n ", "post_mask_code": " }\n }\n}\n"} {"task_id": "Java_187", "language": "Java", "task_type": "method_signature", "source_file": "java/github/componavt/wikokit/common_wiki_jdbc/src/wikokit/base/wikt/sql/quote/TQuotAuthor.java", "mask_start_position": 8318, "mask_end_position": 8397, "canonical_solution": "public static TQuotAuthor get(Connect connect, String _name, String _wikilink) ", "pre_mask_code": "/* TQuotAuthor.java - author of quotation,\n * SQL operations with the table 'quot_author' in Wiktionary parsed database.\n *\n */\npackage wikokit.base.wikt.sql.quote;\n\nimport wikokit.base.wikipedia.sql.Connect;\nimport java.sql.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport wikokit.base.wikipedia.language.Encodings;\nimport wikokit.base.wikipedia.sql.PageTableBase;\n\n/**\n * Author of quotation and\n * operations with the table 'quot_author' in MySQL Wiktionary parsed database.\n *\n * Remark: quot_author table has UNIQUE compound KEY (name, wikilink),\n * and wikilink field could be NULL.\n */\npublic class TQuotAuthor {\n\n /**\n * Inique identifier of the author.\n */\n private int id;\n\n /**\n * Author's name of the quote.\n */\n private String name;\n\n /**\n * A wikilink to author's name in Wikipedia (format: [[w:name|]]),\n * it could not be NULL, though it can be empty (\"\").\n */\n private String wikilink;\n\n private final static TQuotAuthor[] NULL_TQUOTAUTHOR_ARRAY = new TQuotAuthor[0];\n\n public TQuotAuthor(int _id, String _name, String _wikilink) {\n id = _id;\n name = _name;\n wikilink = _wikilink;\n }\n\n public TQuotAuthor(int _id, String _name) {\n id = _id;\n name = _name;\n wikilink = \"\";\n }\n\n /**\n * Gets unique ID from database\n */\n public int getID() {\n return id;\n }\n\n /**\n * Gets author's name from database.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets wikilink to Wikipedia (format: [[w:name|]]) for the author.\n */\n public String getWikilink() {\n return wikilink;\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * _wikilink can be empty or NULL\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertName(Connect connect, String _name) {\n return insertNameWikilink(connect, _name, \"\");\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n * INSERT INTO quot_author (name,wikilink) VALUES (\"Isaac Asimov\", \"Isaac Asimov\");\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertNameWikilink(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor.insertNameAndWikilink()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"INSERT INTO quot_author (name,wikilink) VALUES (\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\", \\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\")\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.executeUpdate(str_sql.toString());\n s = connect.conn.createStatement();\n ResultSet rs = s.executeQuery(\"SELECT LAST_INSERT_ID() as id\");\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.insertName):: _name='\" + _name + \"'; _wikilink='\" + _wikilink + \"'; sql='\" + str_sql.toString() + \"' error=\" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's first record from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" LIMIT 1;\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor getFirst(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n result = new TQuotAuthor(_id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's array of records from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\";\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor[] get(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\";\");\n List list_authors = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n while (rs.next()) {\n if (null == list_authors)\n list_authors = new ArrayList();\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n list_authors.add(new TQuotAuthor(_id, _name, _wikilink));\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n if (null == list_authors)\n return NULL_TQUOTAUTHOR_ARRAY;\n return (TQuotAuthor[]) list_authors.toArray(NULL_TQUOTAUTHOR_ARRAY);\n }\n\n /**\n * Get's first suitable row from the table 'quot_author' by the author's name and wikilink.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" AND wikilink=\"\" LIMIT 1;\n *\n * @param _name author's name\n * @param _wikilink author's name, it could be NULL or empty (\"\")\n *\n * @return NULL if data is absent\n */\n ", "post_mask_code": "{\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"SELECT id FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" AND wikilink=\\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Gets ID of a record or inserts record (if it is absent)\n * into the table 'quot_author'.\n *\n * @param _author author's name\n * @param _author_wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n */\n public static TQuotAuthor getOrInsert(Connect connect, String _author, String _author_wikilink) {\n if (null == _author || 0 == _author.length())\n return null;\n TQuotAuthor a = TQuotAuthor.getFirst(connect, _author);\n if (null == a)\n a = TQuotAuthor.insertNameWikilink(connect, _author, _author_wikilink);\n return a;\n }\n\n /**\n * Selects row from the table 'quot_author' by ID.

\n *\n * SELECT name,wikilink FROM quot_author WHERE id=1\n *\n * @return null if data is absent\n */\n public static TQuotAuthor getByID(Connect connect, int id) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"SELECT name,wikilink FROM quot_author WHERE id=\");\n str_sql.append(id);\n TQuotAuthor quot_author = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n byte[] bb = rs.getBytes(\"name\");\n String _name = null == bb ? null : Encodings.bytesToUTF8(bb);\n bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? null : Encodings.bytesToUTF8(bb);\n quot_author = new TQuotAuthor(id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.getByID()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return quot_author;\n }\n\n /**\n * Deletes row from the table 'quot_author' by a value of ID.

\n * DELETE FROM quot_author WHERE id=4;\n */\n public void delete(Connect connect) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"DELETE FROM quot_author WHERE id=\");\n str_sql.append(id);\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.execute(str_sql.toString());\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.delete()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n }\n}\n"} {"task_id": "Java_188", "language": "Java", "task_type": "method_body", "source_file": "java/github/componavt/wikokit/common_wiki_jdbc/src/wikokit/base/wikt/sql/quote/TQuotAuthor.java", "mask_start_position": 10214, "mask_end_position": 10489, "canonical_solution": "{\n if (null == _author || 0 == _author.length())\n return null;\n TQuotAuthor a = TQuotAuthor.getFirst(connect, _author);\n if (null == a)\n a = TQuotAuthor.insertNameWikilink(connect, _author, _author_wikilink);\n return a;\n }", "pre_mask_code": "/* TQuotAuthor.java - author of quotation,\n * SQL operations with the table 'quot_author' in Wiktionary parsed database.\n *\n */\npackage wikokit.base.wikt.sql.quote;\n\nimport wikokit.base.wikipedia.sql.Connect;\nimport java.sql.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport wikokit.base.wikipedia.language.Encodings;\nimport wikokit.base.wikipedia.sql.PageTableBase;\n\n/**\n * Author of quotation and\n * operations with the table 'quot_author' in MySQL Wiktionary parsed database.\n *\n * Remark: quot_author table has UNIQUE compound KEY (name, wikilink),\n * and wikilink field could be NULL.\n */\npublic class TQuotAuthor {\n\n /**\n * Inique identifier of the author.\n */\n private int id;\n\n /**\n * Author's name of the quote.\n */\n private String name;\n\n /**\n * A wikilink to author's name in Wikipedia (format: [[w:name|]]),\n * it could not be NULL, though it can be empty (\"\").\n */\n private String wikilink;\n\n private final static TQuotAuthor[] NULL_TQUOTAUTHOR_ARRAY = new TQuotAuthor[0];\n\n public TQuotAuthor(int _id, String _name, String _wikilink) {\n id = _id;\n name = _name;\n wikilink = _wikilink;\n }\n\n public TQuotAuthor(int _id, String _name) {\n id = _id;\n name = _name;\n wikilink = \"\";\n }\n\n /**\n * Gets unique ID from database\n */\n public int getID() {\n return id;\n }\n\n /**\n * Gets author's name from database.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets wikilink to Wikipedia (format: [[w:name|]]) for the author.\n */\n public String getWikilink() {\n return wikilink;\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * _wikilink can be empty or NULL\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertName(Connect connect, String _name) {\n return insertNameWikilink(connect, _name, \"\");\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n * INSERT INTO quot_author (name,wikilink) VALUES (\"Isaac Asimov\", \"Isaac Asimov\");\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertNameWikilink(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor.insertNameAndWikilink()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"INSERT INTO quot_author (name,wikilink) VALUES (\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\", \\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\")\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.executeUpdate(str_sql.toString());\n s = connect.conn.createStatement();\n ResultSet rs = s.executeQuery(\"SELECT LAST_INSERT_ID() as id\");\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.insertName):: _name='\" + _name + \"'; _wikilink='\" + _wikilink + \"'; sql='\" + str_sql.toString() + \"' error=\" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's first record from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" LIMIT 1;\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor getFirst(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n result = new TQuotAuthor(_id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's array of records from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\";\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor[] get(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\";\");\n List list_authors = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n while (rs.next()) {\n if (null == list_authors)\n list_authors = new ArrayList();\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n list_authors.add(new TQuotAuthor(_id, _name, _wikilink));\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n if (null == list_authors)\n return NULL_TQUOTAUTHOR_ARRAY;\n return (TQuotAuthor[]) list_authors.toArray(NULL_TQUOTAUTHOR_ARRAY);\n }\n\n /**\n * Get's first suitable row from the table 'quot_author' by the author's name and wikilink.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" AND wikilink=\"\" LIMIT 1;\n *\n * @param _name author's name\n * @param _wikilink author's name, it could be NULL or empty (\"\")\n *\n * @return NULL if data is absent\n */\n public static TQuotAuthor get(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"SELECT id FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" AND wikilink=\\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Gets ID of a record or inserts record (if it is absent)\n * into the table 'quot_author'.\n *\n * @param _author author's name\n * @param _author_wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n */\n public static TQuotAuthor getOrInsert(Connect connect, String _author, String _author_wikilink) ", "post_mask_code": "\n\n /**\n * Selects row from the table 'quot_author' by ID.

\n *\n * SELECT name,wikilink FROM quot_author WHERE id=1\n *\n * @return null if data is absent\n */\n public static TQuotAuthor getByID(Connect connect, int id) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"SELECT name,wikilink FROM quot_author WHERE id=\");\n str_sql.append(id);\n TQuotAuthor quot_author = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n byte[] bb = rs.getBytes(\"name\");\n String _name = null == bb ? null : Encodings.bytesToUTF8(bb);\n bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? null : Encodings.bytesToUTF8(bb);\n quot_author = new TQuotAuthor(id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.getByID()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return quot_author;\n }\n\n /**\n * Deletes row from the table 'quot_author' by a value of ID.

\n * DELETE FROM quot_author WHERE id=4;\n */\n public void delete(Connect connect) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"DELETE FROM quot_author WHERE id=\");\n str_sql.append(id);\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.execute(str_sql.toString());\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.delete()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n }\n}\n"} {"task_id": "Java_189", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/componavt/wikokit/common_wiki_jdbc/src/wikokit/base/wikt/sql/quote/TQuotAuthor.java", "mask_start_position": 12065, "mask_end_position": 12118, "canonical_solution": "\n StringBuilder str_sql = new StringBuilder();", "pre_mask_code": "/* TQuotAuthor.java - author of quotation,\n * SQL operations with the table 'quot_author' in Wiktionary parsed database.\n *\n */\npackage wikokit.base.wikt.sql.quote;\n\nimport wikokit.base.wikipedia.sql.Connect;\nimport java.sql.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport wikokit.base.wikipedia.language.Encodings;\nimport wikokit.base.wikipedia.sql.PageTableBase;\n\n/**\n * Author of quotation and\n * operations with the table 'quot_author' in MySQL Wiktionary parsed database.\n *\n * Remark: quot_author table has UNIQUE compound KEY (name, wikilink),\n * and wikilink field could be NULL.\n */\npublic class TQuotAuthor {\n\n /**\n * Inique identifier of the author.\n */\n private int id;\n\n /**\n * Author's name of the quote.\n */\n private String name;\n\n /**\n * A wikilink to author's name in Wikipedia (format: [[w:name|]]),\n * it could not be NULL, though it can be empty (\"\").\n */\n private String wikilink;\n\n private final static TQuotAuthor[] NULL_TQUOTAUTHOR_ARRAY = new TQuotAuthor[0];\n\n public TQuotAuthor(int _id, String _name, String _wikilink) {\n id = _id;\n name = _name;\n wikilink = _wikilink;\n }\n\n public TQuotAuthor(int _id, String _name) {\n id = _id;\n name = _name;\n wikilink = \"\";\n }\n\n /**\n * Gets unique ID from database\n */\n public int getID() {\n return id;\n }\n\n /**\n * Gets author's name from database.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets wikilink to Wikipedia (format: [[w:name|]]) for the author.\n */\n public String getWikilink() {\n return wikilink;\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * _wikilink can be empty or NULL\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertName(Connect connect, String _name) {\n return insertNameWikilink(connect, _name, \"\");\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n * INSERT INTO quot_author (name,wikilink) VALUES (\"Isaac Asimov\", \"Isaac Asimov\");\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertNameWikilink(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor.insertNameAndWikilink()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"INSERT INTO quot_author (name,wikilink) VALUES (\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\", \\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\")\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.executeUpdate(str_sql.toString());\n s = connect.conn.createStatement();\n ResultSet rs = s.executeQuery(\"SELECT LAST_INSERT_ID() as id\");\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.insertName):: _name='\" + _name + \"'; _wikilink='\" + _wikilink + \"'; sql='\" + str_sql.toString() + \"' error=\" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's first record from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" LIMIT 1;\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor getFirst(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n result = new TQuotAuthor(_id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's array of records from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\";\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor[] get(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\";\");\n List list_authors = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n while (rs.next()) {\n if (null == list_authors)\n list_authors = new ArrayList();\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n list_authors.add(new TQuotAuthor(_id, _name, _wikilink));\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n if (null == list_authors)\n return NULL_TQUOTAUTHOR_ARRAY;\n return (TQuotAuthor[]) list_authors.toArray(NULL_TQUOTAUTHOR_ARRAY);\n }\n\n /**\n * Get's first suitable row from the table 'quot_author' by the author's name and wikilink.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" AND wikilink=\"\" LIMIT 1;\n *\n * @param _name author's name\n * @param _wikilink author's name, it could be NULL or empty (\"\")\n *\n * @return NULL if data is absent\n */\n public static TQuotAuthor get(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"SELECT id FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" AND wikilink=\\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Gets ID of a record or inserts record (if it is absent)\n * into the table 'quot_author'.\n *\n * @param _author author's name\n * @param _author_wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n */\n public static TQuotAuthor getOrInsert(Connect connect, String _author, String _author_wikilink) {\n if (null == _author || 0 == _author.length())\n return null;\n TQuotAuthor a = TQuotAuthor.getFirst(connect, _author);\n if (null == a)\n a = TQuotAuthor.insertNameWikilink(connect, _author, _author_wikilink);\n return a;\n }\n\n /**\n * Selects row from the table 'quot_author' by ID.

\n *\n * SELECT name,wikilink FROM quot_author WHERE id=1\n *\n * @return null if data is absent\n */\n public static TQuotAuthor getByID(Connect connect, int id) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"SELECT name,wikilink FROM quot_author WHERE id=\");\n str_sql.append(id);\n TQuotAuthor quot_author = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n byte[] bb = rs.getBytes(\"name\");\n String _name = null == bb ? null : Encodings.bytesToUTF8(bb);\n bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? null : Encodings.bytesToUTF8(bb);\n quot_author = new TQuotAuthor(id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.getByID()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return quot_author;\n }\n\n /**\n * Deletes row from the table 'quot_author' by a value of ID.

\n * DELETE FROM quot_author WHERE id=4;\n */\n public void delete(Connect connect) {", "post_mask_code": "\n str_sql.append(\"DELETE FROM quot_author WHERE id=\");\n str_sql.append(id);\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.execute(str_sql.toString());\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.delete()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n }\n}\n"} {"task_id": "Java_190", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/componavt/wikokit/common_wiki_jdbc/src/wikokit/base/wikt/sql/quote/TQuotAuthor.java", "mask_start_position": 12127, "mask_end_position": 12207, "canonical_solution": "str_sql.append(\"DELETE FROM quot_author WHERE id=\");\n str_sql.append(id);", "pre_mask_code": "/* TQuotAuthor.java - author of quotation,\n * SQL operations with the table 'quot_author' in Wiktionary parsed database.\n *\n */\npackage wikokit.base.wikt.sql.quote;\n\nimport wikokit.base.wikipedia.sql.Connect;\nimport java.sql.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport wikokit.base.wikipedia.language.Encodings;\nimport wikokit.base.wikipedia.sql.PageTableBase;\n\n/**\n * Author of quotation and\n * operations with the table 'quot_author' in MySQL Wiktionary parsed database.\n *\n * Remark: quot_author table has UNIQUE compound KEY (name, wikilink),\n * and wikilink field could be NULL.\n */\npublic class TQuotAuthor {\n\n /**\n * Inique identifier of the author.\n */\n private int id;\n\n /**\n * Author's name of the quote.\n */\n private String name;\n\n /**\n * A wikilink to author's name in Wikipedia (format: [[w:name|]]),\n * it could not be NULL, though it can be empty (\"\").\n */\n private String wikilink;\n\n private final static TQuotAuthor[] NULL_TQUOTAUTHOR_ARRAY = new TQuotAuthor[0];\n\n public TQuotAuthor(int _id, String _name, String _wikilink) {\n id = _id;\n name = _name;\n wikilink = _wikilink;\n }\n\n public TQuotAuthor(int _id, String _name) {\n id = _id;\n name = _name;\n wikilink = \"\";\n }\n\n /**\n * Gets unique ID from database\n */\n public int getID() {\n return id;\n }\n\n /**\n * Gets author's name from database.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets wikilink to Wikipedia (format: [[w:name|]]) for the author.\n */\n public String getWikilink() {\n return wikilink;\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * _wikilink can be empty or NULL\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertName(Connect connect, String _name) {\n return insertNameWikilink(connect, _name, \"\");\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n * INSERT INTO quot_author (name,wikilink) VALUES (\"Isaac Asimov\", \"Isaac Asimov\");\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertNameWikilink(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor.insertNameAndWikilink()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"INSERT INTO quot_author (name,wikilink) VALUES (\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\", \\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\")\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.executeUpdate(str_sql.toString());\n s = connect.conn.createStatement();\n ResultSet rs = s.executeQuery(\"SELECT LAST_INSERT_ID() as id\");\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.insertName):: _name='\" + _name + \"'; _wikilink='\" + _wikilink + \"'; sql='\" + str_sql.toString() + \"' error=\" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's first record from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" LIMIT 1;\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor getFirst(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n result = new TQuotAuthor(_id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's array of records from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\";\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor[] get(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\";\");\n List list_authors = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n while (rs.next()) {\n if (null == list_authors)\n list_authors = new ArrayList();\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n list_authors.add(new TQuotAuthor(_id, _name, _wikilink));\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n if (null == list_authors)\n return NULL_TQUOTAUTHOR_ARRAY;\n return (TQuotAuthor[]) list_authors.toArray(NULL_TQUOTAUTHOR_ARRAY);\n }\n\n /**\n * Get's first suitable row from the table 'quot_author' by the author's name and wikilink.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" AND wikilink=\"\" LIMIT 1;\n *\n * @param _name author's name\n * @param _wikilink author's name, it could be NULL or empty (\"\")\n *\n * @return NULL if data is absent\n */\n public static TQuotAuthor get(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"SELECT id FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" AND wikilink=\\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Gets ID of a record or inserts record (if it is absent)\n * into the table 'quot_author'.\n *\n * @param _author author's name\n * @param _author_wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n */\n public static TQuotAuthor getOrInsert(Connect connect, String _author, String _author_wikilink) {\n if (null == _author || 0 == _author.length())\n return null;\n TQuotAuthor a = TQuotAuthor.getFirst(connect, _author);\n if (null == a)\n a = TQuotAuthor.insertNameWikilink(connect, _author, _author_wikilink);\n return a;\n }\n\n /**\n * Selects row from the table 'quot_author' by ID.

\n *\n * SELECT name,wikilink FROM quot_author WHERE id=1\n *\n * @return null if data is absent\n */\n public static TQuotAuthor getByID(Connect connect, int id) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"SELECT name,wikilink FROM quot_author WHERE id=\");\n str_sql.append(id);\n TQuotAuthor quot_author = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n byte[] bb = rs.getBytes(\"name\");\n String _name = null == bb ? null : Encodings.bytesToUTF8(bb);\n bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? null : Encodings.bytesToUTF8(bb);\n quot_author = new TQuotAuthor(id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.getByID()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return quot_author;\n }\n\n /**\n * Deletes row from the table 'quot_author' by a value of ID.

\n * DELETE FROM quot_author WHERE id=4;\n */\n public void delete(Connect connect) {\n StringBuilder str_sql = new StringBuilder();\n ", "post_mask_code": "\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.execute(str_sql.toString());\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.delete()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n }\n}\n"} {"task_id": "Java_191", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/componavt/wikokit/common_wiki_jdbc/src/wikokit/base/wikt/sql/quote/TQuotAuthor.java", "mask_start_position": 12216, "mask_end_position": 12586, "canonical_solution": "try {\n Statement s = connect.conn.createStatement();\n try {\n s.execute(str_sql.toString());\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.delete()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n }", "pre_mask_code": "/* TQuotAuthor.java - author of quotation,\n * SQL operations with the table 'quot_author' in Wiktionary parsed database.\n *\n */\npackage wikokit.base.wikt.sql.quote;\n\nimport wikokit.base.wikipedia.sql.Connect;\nimport java.sql.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport wikokit.base.wikipedia.language.Encodings;\nimport wikokit.base.wikipedia.sql.PageTableBase;\n\n/**\n * Author of quotation and\n * operations with the table 'quot_author' in MySQL Wiktionary parsed database.\n *\n * Remark: quot_author table has UNIQUE compound KEY (name, wikilink),\n * and wikilink field could be NULL.\n */\npublic class TQuotAuthor {\n\n /**\n * Inique identifier of the author.\n */\n private int id;\n\n /**\n * Author's name of the quote.\n */\n private String name;\n\n /**\n * A wikilink to author's name in Wikipedia (format: [[w:name|]]),\n * it could not be NULL, though it can be empty (\"\").\n */\n private String wikilink;\n\n private final static TQuotAuthor[] NULL_TQUOTAUTHOR_ARRAY = new TQuotAuthor[0];\n\n public TQuotAuthor(int _id, String _name, String _wikilink) {\n id = _id;\n name = _name;\n wikilink = _wikilink;\n }\n\n public TQuotAuthor(int _id, String _name) {\n id = _id;\n name = _name;\n wikilink = \"\";\n }\n\n /**\n * Gets unique ID from database\n */\n public int getID() {\n return id;\n }\n\n /**\n * Gets author's name from database.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets wikilink to Wikipedia (format: [[w:name|]]) for the author.\n */\n public String getWikilink() {\n return wikilink;\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * _wikilink can be empty or NULL\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertName(Connect connect, String _name) {\n return insertNameWikilink(connect, _name, \"\");\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n * INSERT INTO quot_author (name,wikilink) VALUES (\"Isaac Asimov\", \"Isaac Asimov\");\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertNameWikilink(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor.insertNameAndWikilink()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"INSERT INTO quot_author (name,wikilink) VALUES (\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\", \\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\")\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.executeUpdate(str_sql.toString());\n s = connect.conn.createStatement();\n ResultSet rs = s.executeQuery(\"SELECT LAST_INSERT_ID() as id\");\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.insertName):: _name='\" + _name + \"'; _wikilink='\" + _wikilink + \"'; sql='\" + str_sql.toString() + \"' error=\" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's first record from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" LIMIT 1;\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor getFirst(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n result = new TQuotAuthor(_id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's array of records from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\";\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor[] get(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\";\");\n List list_authors = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n while (rs.next()) {\n if (null == list_authors)\n list_authors = new ArrayList();\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n list_authors.add(new TQuotAuthor(_id, _name, _wikilink));\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n if (null == list_authors)\n return NULL_TQUOTAUTHOR_ARRAY;\n return (TQuotAuthor[]) list_authors.toArray(NULL_TQUOTAUTHOR_ARRAY);\n }\n\n /**\n * Get's first suitable row from the table 'quot_author' by the author's name and wikilink.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" AND wikilink=\"\" LIMIT 1;\n *\n * @param _name author's name\n * @param _wikilink author's name, it could be NULL or empty (\"\")\n *\n * @return NULL if data is absent\n */\n public static TQuotAuthor get(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"SELECT id FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" AND wikilink=\\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Gets ID of a record or inserts record (if it is absent)\n * into the table 'quot_author'.\n *\n * @param _author author's name\n * @param _author_wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n */\n public static TQuotAuthor getOrInsert(Connect connect, String _author, String _author_wikilink) {\n if (null == _author || 0 == _author.length())\n return null;\n TQuotAuthor a = TQuotAuthor.getFirst(connect, _author);\n if (null == a)\n a = TQuotAuthor.insertNameWikilink(connect, _author, _author_wikilink);\n return a;\n }\n\n /**\n * Selects row from the table 'quot_author' by ID.

\n *\n * SELECT name,wikilink FROM quot_author WHERE id=1\n *\n * @return null if data is absent\n */\n public static TQuotAuthor getByID(Connect connect, int id) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"SELECT name,wikilink FROM quot_author WHERE id=\");\n str_sql.append(id);\n TQuotAuthor quot_author = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n byte[] bb = rs.getBytes(\"name\");\n String _name = null == bb ? null : Encodings.bytesToUTF8(bb);\n bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? null : Encodings.bytesToUTF8(bb);\n quot_author = new TQuotAuthor(id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.getByID()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return quot_author;\n }\n\n /**\n * Deletes row from the table 'quot_author' by a value of ID.

\n * DELETE FROM quot_author WHERE id=4;\n */\n public void delete(Connect connect) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"DELETE FROM quot_author WHERE id=\");\n str_sql.append(id);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_192", "language": "Java", "task_type": "single_line", "source_file": "java/github/componavt/wikokit/common_wiki_jdbc/src/wikokit/base/wikt/sql/quote/TQuotAuthor.java", "mask_start_position": 4801, "mask_end_position": 4840, "canonical_solution": "gBuilder str_sql = new StringBuilder();", "pre_mask_code": "/* TQuotAuthor.java - author of quotation,\n * SQL operations with the table 'quot_author' in Wiktionary parsed database.\n *\n */\npackage wikokit.base.wikt.sql.quote;\n\nimport wikokit.base.wikipedia.sql.Connect;\nimport java.sql.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport wikokit.base.wikipedia.language.Encodings;\nimport wikokit.base.wikipedia.sql.PageTableBase;\n\n/**\n * Author of quotation and\n * operations with the table 'quot_author' in MySQL Wiktionary parsed database.\n *\n * Remark: quot_author table has UNIQUE compound KEY (name, wikilink),\n * and wikilink field could be NULL.\n */\npublic class TQuotAuthor {\n\n /**\n * Inique identifier of the author.\n */\n private int id;\n\n /**\n * Author's name of the quote.\n */\n private String name;\n\n /**\n * A wikilink to author's name in Wikipedia (format: [[w:name|]]),\n * it could not be NULL, though it can be empty (\"\").\n */\n private String wikilink;\n\n private final static TQuotAuthor[] NULL_TQUOTAUTHOR_ARRAY = new TQuotAuthor[0];\n\n public TQuotAuthor(int _id, String _name, String _wikilink) {\n id = _id;\n name = _name;\n wikilink = _wikilink;\n }\n\n public TQuotAuthor(int _id, String _name) {\n id = _id;\n name = _name;\n wikilink = \"\";\n }\n\n /**\n * Gets unique ID from database\n */\n public int getID() {\n return id;\n }\n\n /**\n * Gets author's name from database.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets wikilink to Wikipedia (format: [[w:name|]]) for the author.\n */\n public String getWikilink() {\n return wikilink;\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * _wikilink can be empty or NULL\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertName(Connect connect, String _name) {\n return insertNameWikilink(connect, _name, \"\");\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n * INSERT INTO quot_author (name,wikilink) VALUES (\"Isaac Asimov\", \"Isaac Asimov\");\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertNameWikilink(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor.insertNameAndWikilink()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"INSERT INTO quot_author (name,wikilink) VALUES (\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\", \\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\")\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.executeUpdate(str_sql.toString());\n s = connect.conn.createStatement();\n ResultSet rs = s.executeQuery(\"SELECT LAST_INSERT_ID() as id\");\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.insertName):: _name='\" + _name + \"'; _wikilink='\" + _wikilink + \"'; sql='\" + str_sql.toString() + \"' error=\" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's first record from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" LIMIT 1;\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor getFirst(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n Strin", "post_mask_code": "\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n result = new TQuotAuthor(_id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's array of records from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\";\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor[] get(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\";\");\n List list_authors = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n while (rs.next()) {\n if (null == list_authors)\n list_authors = new ArrayList();\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n list_authors.add(new TQuotAuthor(_id, _name, _wikilink));\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n if (null == list_authors)\n return NULL_TQUOTAUTHOR_ARRAY;\n return (TQuotAuthor[]) list_authors.toArray(NULL_TQUOTAUTHOR_ARRAY);\n }\n\n /**\n * Get's first suitable row from the table 'quot_author' by the author's name and wikilink.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" AND wikilink=\"\" LIMIT 1;\n *\n * @param _name author's name\n * @param _wikilink author's name, it could be NULL or empty (\"\")\n *\n * @return NULL if data is absent\n */\n public static TQuotAuthor get(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"SELECT id FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" AND wikilink=\\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Gets ID of a record or inserts record (if it is absent)\n * into the table 'quot_author'.\n *\n * @param _author author's name\n * @param _author_wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n */\n public static TQuotAuthor getOrInsert(Connect connect, String _author, String _author_wikilink) {\n if (null == _author || 0 == _author.length())\n return null;\n TQuotAuthor a = TQuotAuthor.getFirst(connect, _author);\n if (null == a)\n a = TQuotAuthor.insertNameWikilink(connect, _author, _author_wikilink);\n return a;\n }\n\n /**\n * Selects row from the table 'quot_author' by ID.

\n *\n * SELECT name,wikilink FROM quot_author WHERE id=1\n *\n * @return null if data is absent\n */\n public static TQuotAuthor getByID(Connect connect, int id) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"SELECT name,wikilink FROM quot_author WHERE id=\");\n str_sql.append(id);\n TQuotAuthor quot_author = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n byte[] bb = rs.getBytes(\"name\");\n String _name = null == bb ? null : Encodings.bytesToUTF8(bb);\n bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? null : Encodings.bytesToUTF8(bb);\n quot_author = new TQuotAuthor(id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.getByID()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return quot_author;\n }\n\n /**\n * Deletes row from the table 'quot_author' by a value of ID.

\n * DELETE FROM quot_author WHERE id=4;\n */\n public void delete(Connect connect) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"DELETE FROM quot_author WHERE id=\");\n str_sql.append(id);\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.execute(str_sql.toString());\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.delete()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n }\n}\n"} {"task_id": "Java_193", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/componavt/wikokit/common_wiki_jdbc/src/wikokit/base/wikt/sql/quote/TQuotAuthor.java", "mask_start_position": 1472, "mask_end_position": 1524, "canonical_solution": "public String getName() {\n return name;\n }", "pre_mask_code": "/* TQuotAuthor.java - author of quotation,\n * SQL operations with the table 'quot_author' in Wiktionary parsed database.\n *\n */\npackage wikokit.base.wikt.sql.quote;\n\nimport wikokit.base.wikipedia.sql.Connect;\nimport java.sql.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport wikokit.base.wikipedia.language.Encodings;\nimport wikokit.base.wikipedia.sql.PageTableBase;\n\n/**\n * Author of quotation and\n * operations with the table 'quot_author' in MySQL Wiktionary parsed database.\n *\n * Remark: quot_author table has UNIQUE compound KEY (name, wikilink),\n * and wikilink field could be NULL.\n */\npublic class TQuotAuthor {\n\n /**\n * Inique identifier of the author.\n */\n private int id;\n\n /**\n * Author's name of the quote.\n */\n private String name;\n\n /**\n * A wikilink to author's name in Wikipedia (format: [[w:name|]]),\n * it could not be NULL, though it can be empty (\"\").\n */\n private String wikilink;\n\n private final static TQuotAuthor[] NULL_TQUOTAUTHOR_ARRAY = new TQuotAuthor[0];\n\n public TQuotAuthor(int _id, String _name, String _wikilink) {\n id = _id;\n name = _name;\n wikilink = _wikilink;\n }\n\n public TQuotAuthor(int _id, String _name) {\n id = _id;\n name = _name;\n wikilink = \"\";\n }\n\n /**\n * Gets unique ID from database\n */\n public int getID() {\n return id;\n }\n\n /**\n * Gets author's name from database.\n */\n ", "post_mask_code": "\n\n /**\n * Gets wikilink to Wikipedia (format: [[w:name|]]) for the author.\n */\n public String getWikilink() {\n return wikilink;\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * _wikilink can be empty or NULL\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertName(Connect connect, String _name) {\n return insertNameWikilink(connect, _name, \"\");\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n * INSERT INTO quot_author (name,wikilink) VALUES (\"Isaac Asimov\", \"Isaac Asimov\");\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertNameWikilink(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor.insertNameAndWikilink()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"INSERT INTO quot_author (name,wikilink) VALUES (\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\", \\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\")\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.executeUpdate(str_sql.toString());\n s = connect.conn.createStatement();\n ResultSet rs = s.executeQuery(\"SELECT LAST_INSERT_ID() as id\");\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.insertName):: _name='\" + _name + \"'; _wikilink='\" + _wikilink + \"'; sql='\" + str_sql.toString() + \"' error=\" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's first record from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" LIMIT 1;\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor getFirst(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n result = new TQuotAuthor(_id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's array of records from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\";\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor[] get(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\";\");\n List list_authors = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n while (rs.next()) {\n if (null == list_authors)\n list_authors = new ArrayList();\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n list_authors.add(new TQuotAuthor(_id, _name, _wikilink));\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n if (null == list_authors)\n return NULL_TQUOTAUTHOR_ARRAY;\n return (TQuotAuthor[]) list_authors.toArray(NULL_TQUOTAUTHOR_ARRAY);\n }\n\n /**\n * Get's first suitable row from the table 'quot_author' by the author's name and wikilink.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" AND wikilink=\"\" LIMIT 1;\n *\n * @param _name author's name\n * @param _wikilink author's name, it could be NULL or empty (\"\")\n *\n * @return NULL if data is absent\n */\n public static TQuotAuthor get(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"SELECT id FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" AND wikilink=\\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Gets ID of a record or inserts record (if it is absent)\n * into the table 'quot_author'.\n *\n * @param _author author's name\n * @param _author_wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n */\n public static TQuotAuthor getOrInsert(Connect connect, String _author, String _author_wikilink) {\n if (null == _author || 0 == _author.length())\n return null;\n TQuotAuthor a = TQuotAuthor.getFirst(connect, _author);\n if (null == a)\n a = TQuotAuthor.insertNameWikilink(connect, _author, _author_wikilink);\n return a;\n }\n\n /**\n * Selects row from the table 'quot_author' by ID.

\n *\n * SELECT name,wikilink FROM quot_author WHERE id=1\n *\n * @return null if data is absent\n */\n public static TQuotAuthor getByID(Connect connect, int id) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"SELECT name,wikilink FROM quot_author WHERE id=\");\n str_sql.append(id);\n TQuotAuthor quot_author = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n byte[] bb = rs.getBytes(\"name\");\n String _name = null == bb ? null : Encodings.bytesToUTF8(bb);\n bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? null : Encodings.bytesToUTF8(bb);\n quot_author = new TQuotAuthor(id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.getByID()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return quot_author;\n }\n\n /**\n * Deletes row from the table 'quot_author' by a value of ID.

\n * DELETE FROM quot_author WHERE id=4;\n */\n public void delete(Connect connect) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"DELETE FROM quot_author WHERE id=\");\n str_sql.append(id);\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.execute(str_sql.toString());\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.delete()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n }\n}\n"} {"task_id": "Java_194", "language": "Java", "task_type": "if_statement", "source_file": "java/github/componavt/wikokit/common_wiki_jdbc/src/wikokit/base/wikt/sql/quote/TQuotAuthor.java", "mask_start_position": 10367, "mask_end_position": 10465, "canonical_solution": "if (null == a)\n a = TQuotAuthor.insertNameWikilink(connect, _author, _author_wikilink);", "pre_mask_code": "/* TQuotAuthor.java - author of quotation,\n * SQL operations with the table 'quot_author' in Wiktionary parsed database.\n *\n */\npackage wikokit.base.wikt.sql.quote;\n\nimport wikokit.base.wikipedia.sql.Connect;\nimport java.sql.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport wikokit.base.wikipedia.language.Encodings;\nimport wikokit.base.wikipedia.sql.PageTableBase;\n\n/**\n * Author of quotation and\n * operations with the table 'quot_author' in MySQL Wiktionary parsed database.\n *\n * Remark: quot_author table has UNIQUE compound KEY (name, wikilink),\n * and wikilink field could be NULL.\n */\npublic class TQuotAuthor {\n\n /**\n * Inique identifier of the author.\n */\n private int id;\n\n /**\n * Author's name of the quote.\n */\n private String name;\n\n /**\n * A wikilink to author's name in Wikipedia (format: [[w:name|]]),\n * it could not be NULL, though it can be empty (\"\").\n */\n private String wikilink;\n\n private final static TQuotAuthor[] NULL_TQUOTAUTHOR_ARRAY = new TQuotAuthor[0];\n\n public TQuotAuthor(int _id, String _name, String _wikilink) {\n id = _id;\n name = _name;\n wikilink = _wikilink;\n }\n\n public TQuotAuthor(int _id, String _name) {\n id = _id;\n name = _name;\n wikilink = \"\";\n }\n\n /**\n * Gets unique ID from database\n */\n public int getID() {\n return id;\n }\n\n /**\n * Gets author's name from database.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets wikilink to Wikipedia (format: [[w:name|]]) for the author.\n */\n public String getWikilink() {\n return wikilink;\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * _wikilink can be empty or NULL\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertName(Connect connect, String _name) {\n return insertNameWikilink(connect, _name, \"\");\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n * INSERT INTO quot_author (name,wikilink) VALUES (\"Isaac Asimov\", \"Isaac Asimov\");\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertNameWikilink(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor.insertNameAndWikilink()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"INSERT INTO quot_author (name,wikilink) VALUES (\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\", \\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\")\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.executeUpdate(str_sql.toString());\n s = connect.conn.createStatement();\n ResultSet rs = s.executeQuery(\"SELECT LAST_INSERT_ID() as id\");\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.insertName):: _name='\" + _name + \"'; _wikilink='\" + _wikilink + \"'; sql='\" + str_sql.toString() + \"' error=\" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's first record from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" LIMIT 1;\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor getFirst(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n result = new TQuotAuthor(_id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's array of records from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\";\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor[] get(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\";\");\n List list_authors = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n while (rs.next()) {\n if (null == list_authors)\n list_authors = new ArrayList();\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n list_authors.add(new TQuotAuthor(_id, _name, _wikilink));\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n if (null == list_authors)\n return NULL_TQUOTAUTHOR_ARRAY;\n return (TQuotAuthor[]) list_authors.toArray(NULL_TQUOTAUTHOR_ARRAY);\n }\n\n /**\n * Get's first suitable row from the table 'quot_author' by the author's name and wikilink.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" AND wikilink=\"\" LIMIT 1;\n *\n * @param _name author's name\n * @param _wikilink author's name, it could be NULL or empty (\"\")\n *\n * @return NULL if data is absent\n */\n public static TQuotAuthor get(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"SELECT id FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" AND wikilink=\\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Gets ID of a record or inserts record (if it is absent)\n * into the table 'quot_author'.\n *\n * @param _author author's name\n * @param _author_wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n */\n public static TQuotAuthor getOrInsert(Connect connect, String _author, String _author_wikilink) {\n if (null == _author || 0 == _author.length())\n return null;\n TQuotAuthor a = TQuotAuthor.getFirst(connect, _author);\n ", "post_mask_code": "\n return a;\n }\n\n /**\n * Selects row from the table 'quot_author' by ID.

\n *\n * SELECT name,wikilink FROM quot_author WHERE id=1\n *\n * @return null if data is absent\n */\n public static TQuotAuthor getByID(Connect connect, int id) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"SELECT name,wikilink FROM quot_author WHERE id=\");\n str_sql.append(id);\n TQuotAuthor quot_author = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n byte[] bb = rs.getBytes(\"name\");\n String _name = null == bb ? null : Encodings.bytesToUTF8(bb);\n bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? null : Encodings.bytesToUTF8(bb);\n quot_author = new TQuotAuthor(id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.getByID()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return quot_author;\n }\n\n /**\n * Deletes row from the table 'quot_author' by a value of ID.

\n * DELETE FROM quot_author WHERE id=4;\n */\n public void delete(Connect connect) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"DELETE FROM quot_author WHERE id=\");\n str_sql.append(id);\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.execute(str_sql.toString());\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.delete()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n }\n}\n"} {"task_id": "Java_195", "language": "Java", "task_type": "while_statement", "source_file": "java/github/componavt/wikokit/common_wiki_jdbc/src/wikokit/base/wikt/sql/quote/TQuotAuthor.java", "mask_start_position": 7030, "mask_end_position": 7476, "canonical_solution": "while (rs.next()) {\n if (null == list_authors)\n list_authors = new ArrayList();\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n list_authors.add(new TQuotAuthor(_id, _name, _wikilink));\n }", "pre_mask_code": "/* TQuotAuthor.java - author of quotation,\n * SQL operations with the table 'quot_author' in Wiktionary parsed database.\n *\n */\npackage wikokit.base.wikt.sql.quote;\n\nimport wikokit.base.wikipedia.sql.Connect;\nimport java.sql.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport wikokit.base.wikipedia.language.Encodings;\nimport wikokit.base.wikipedia.sql.PageTableBase;\n\n/**\n * Author of quotation and\n * operations with the table 'quot_author' in MySQL Wiktionary parsed database.\n *\n * Remark: quot_author table has UNIQUE compound KEY (name, wikilink),\n * and wikilink field could be NULL.\n */\npublic class TQuotAuthor {\n\n /**\n * Inique identifier of the author.\n */\n private int id;\n\n /**\n * Author's name of the quote.\n */\n private String name;\n\n /**\n * A wikilink to author's name in Wikipedia (format: [[w:name|]]),\n * it could not be NULL, though it can be empty (\"\").\n */\n private String wikilink;\n\n private final static TQuotAuthor[] NULL_TQUOTAUTHOR_ARRAY = new TQuotAuthor[0];\n\n public TQuotAuthor(int _id, String _name, String _wikilink) {\n id = _id;\n name = _name;\n wikilink = _wikilink;\n }\n\n public TQuotAuthor(int _id, String _name) {\n id = _id;\n name = _name;\n wikilink = \"\";\n }\n\n /**\n * Gets unique ID from database\n */\n public int getID() {\n return id;\n }\n\n /**\n * Gets author's name from database.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets wikilink to Wikipedia (format: [[w:name|]]) for the author.\n */\n public String getWikilink() {\n return wikilink;\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * _wikilink can be empty or NULL\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertName(Connect connect, String _name) {\n return insertNameWikilink(connect, _name, \"\");\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n * INSERT INTO quot_author (name,wikilink) VALUES (\"Isaac Asimov\", \"Isaac Asimov\");\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertNameWikilink(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor.insertNameAndWikilink()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"INSERT INTO quot_author (name,wikilink) VALUES (\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\", \\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\")\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.executeUpdate(str_sql.toString());\n s = connect.conn.createStatement();\n ResultSet rs = s.executeQuery(\"SELECT LAST_INSERT_ID() as id\");\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.insertName):: _name='\" + _name + \"'; _wikilink='\" + _wikilink + \"'; sql='\" + str_sql.toString() + \"' error=\" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's first record from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" LIMIT 1;\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor getFirst(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n result = new TQuotAuthor(_id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's array of records from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\";\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor[] get(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\";\");\n List list_authors = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n ", "post_mask_code": "\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n if (null == list_authors)\n return NULL_TQUOTAUTHOR_ARRAY;\n return (TQuotAuthor[]) list_authors.toArray(NULL_TQUOTAUTHOR_ARRAY);\n }\n\n /**\n * Get's first suitable row from the table 'quot_author' by the author's name and wikilink.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" AND wikilink=\"\" LIMIT 1;\n *\n * @param _name author's name\n * @param _wikilink author's name, it could be NULL or empty (\"\")\n *\n * @return NULL if data is absent\n */\n public static TQuotAuthor get(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"SELECT id FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" AND wikilink=\\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Gets ID of a record or inserts record (if it is absent)\n * into the table 'quot_author'.\n *\n * @param _author author's name\n * @param _author_wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n */\n public static TQuotAuthor getOrInsert(Connect connect, String _author, String _author_wikilink) {\n if (null == _author || 0 == _author.length())\n return null;\n TQuotAuthor a = TQuotAuthor.getFirst(connect, _author);\n if (null == a)\n a = TQuotAuthor.insertNameWikilink(connect, _author, _author_wikilink);\n return a;\n }\n\n /**\n * Selects row from the table 'quot_author' by ID.

\n *\n * SELECT name,wikilink FROM quot_author WHERE id=1\n *\n * @return null if data is absent\n */\n public static TQuotAuthor getByID(Connect connect, int id) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"SELECT name,wikilink FROM quot_author WHERE id=\");\n str_sql.append(id);\n TQuotAuthor quot_author = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n byte[] bb = rs.getBytes(\"name\");\n String _name = null == bb ? null : Encodings.bytesToUTF8(bb);\n bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? null : Encodings.bytesToUTF8(bb);\n quot_author = new TQuotAuthor(id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.getByID()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return quot_author;\n }\n\n /**\n * Deletes row from the table 'quot_author' by a value of ID.

\n * DELETE FROM quot_author WHERE id=4;\n */\n public void delete(Connect connect) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"DELETE FROM quot_author WHERE id=\");\n str_sql.append(id);\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.execute(str_sql.toString());\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.delete()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n }\n}\n"} {"task_id": "Java_196", "language": "Java", "task_type": "try_statement", "source_file": "java/github/componavt/wikokit/common_wiki_jdbc/src/wikokit/base/wikt/sql/quote/TQuotAuthor.java", "mask_start_position": 3530, "mask_end_position": 4005, "canonical_solution": "try {\n s.executeUpdate(str_sql.toString());\n s = connect.conn.createStatement();\n ResultSet rs = s.executeQuery(\"SELECT LAST_INSERT_ID() as id\");\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }", "pre_mask_code": "/* TQuotAuthor.java - author of quotation,\n * SQL operations with the table 'quot_author' in Wiktionary parsed database.\n *\n */\npackage wikokit.base.wikt.sql.quote;\n\nimport wikokit.base.wikipedia.sql.Connect;\nimport java.sql.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport wikokit.base.wikipedia.language.Encodings;\nimport wikokit.base.wikipedia.sql.PageTableBase;\n\n/**\n * Author of quotation and\n * operations with the table 'quot_author' in MySQL Wiktionary parsed database.\n *\n * Remark: quot_author table has UNIQUE compound KEY (name, wikilink),\n * and wikilink field could be NULL.\n */\npublic class TQuotAuthor {\n\n /**\n * Inique identifier of the author.\n */\n private int id;\n\n /**\n * Author's name of the quote.\n */\n private String name;\n\n /**\n * A wikilink to author's name in Wikipedia (format: [[w:name|]]),\n * it could not be NULL, though it can be empty (\"\").\n */\n private String wikilink;\n\n private final static TQuotAuthor[] NULL_TQUOTAUTHOR_ARRAY = new TQuotAuthor[0];\n\n public TQuotAuthor(int _id, String _name, String _wikilink) {\n id = _id;\n name = _name;\n wikilink = _wikilink;\n }\n\n public TQuotAuthor(int _id, String _name) {\n id = _id;\n name = _name;\n wikilink = \"\";\n }\n\n /**\n * Gets unique ID from database\n */\n public int getID() {\n return id;\n }\n\n /**\n * Gets author's name from database.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets wikilink to Wikipedia (format: [[w:name|]]) for the author.\n */\n public String getWikilink() {\n return wikilink;\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * _wikilink can be empty or NULL\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertName(Connect connect, String _name) {\n return insertNameWikilink(connect, _name, \"\");\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n * INSERT INTO quot_author (name,wikilink) VALUES (\"Isaac Asimov\", \"Isaac Asimov\");\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertNameWikilink(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor.insertNameAndWikilink()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"INSERT INTO quot_author (name,wikilink) VALUES (\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\", \\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\")\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n ", "post_mask_code": "\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.insertName):: _name='\" + _name + \"'; _wikilink='\" + _wikilink + \"'; sql='\" + str_sql.toString() + \"' error=\" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's first record from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" LIMIT 1;\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor getFirst(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n result = new TQuotAuthor(_id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's array of records from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\";\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor[] get(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\";\");\n List list_authors = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n while (rs.next()) {\n if (null == list_authors)\n list_authors = new ArrayList();\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n list_authors.add(new TQuotAuthor(_id, _name, _wikilink));\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n if (null == list_authors)\n return NULL_TQUOTAUTHOR_ARRAY;\n return (TQuotAuthor[]) list_authors.toArray(NULL_TQUOTAUTHOR_ARRAY);\n }\n\n /**\n * Get's first suitable row from the table 'quot_author' by the author's name and wikilink.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" AND wikilink=\"\" LIMIT 1;\n *\n * @param _name author's name\n * @param _wikilink author's name, it could be NULL or empty (\"\")\n *\n * @return NULL if data is absent\n */\n public static TQuotAuthor get(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"SELECT id FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" AND wikilink=\\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Gets ID of a record or inserts record (if it is absent)\n * into the table 'quot_author'.\n *\n * @param _author author's name\n * @param _author_wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n */\n public static TQuotAuthor getOrInsert(Connect connect, String _author, String _author_wikilink) {\n if (null == _author || 0 == _author.length())\n return null;\n TQuotAuthor a = TQuotAuthor.getFirst(connect, _author);\n if (null == a)\n a = TQuotAuthor.insertNameWikilink(connect, _author, _author_wikilink);\n return a;\n }\n\n /**\n * Selects row from the table 'quot_author' by ID.

\n *\n * SELECT name,wikilink FROM quot_author WHERE id=1\n *\n * @return null if data is absent\n */\n public static TQuotAuthor getByID(Connect connect, int id) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"SELECT name,wikilink FROM quot_author WHERE id=\");\n str_sql.append(id);\n TQuotAuthor quot_author = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n byte[] bb = rs.getBytes(\"name\");\n String _name = null == bb ? null : Encodings.bytesToUTF8(bb);\n bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? null : Encodings.bytesToUTF8(bb);\n quot_author = new TQuotAuthor(id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.getByID()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return quot_author;\n }\n\n /**\n * Deletes row from the table 'quot_author' by a value of ID.

\n * DELETE FROM quot_author WHERE id=4;\n */\n public void delete(Connect connect) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"DELETE FROM quot_author WHERE id=\");\n str_sql.append(id);\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.execute(str_sql.toString());\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.delete()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n }\n}\n"} {"task_id": "Java_197", "language": "Java", "task_type": "empty", "source_file": "java/github/componavt/wikokit/common_wiki_jdbc/src/wikokit/base/wikt/sql/quote/TQuotAuthor.java", "mask_start_position": 11960, "mask_end_position": 11960, "canonical_solution": "", "pre_mask_code": "/* TQuotAuthor.java - author of quotation,\n * SQL operations with the table 'quot_author' in Wiktionary parsed database.\n *\n */\npackage wikokit.base.wikt.sql.quote;\n\nimport wikokit.base.wikipedia.sql.Connect;\nimport java.sql.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport wikokit.base.wikipedia.language.Encodings;\nimport wikokit.base.wikipedia.sql.PageTableBase;\n\n/**\n * Author of quotation and\n * operations with the table 'quot_author' in MySQL Wiktionary parsed database.\n *\n * Remark: quot_author table has UNIQUE compound KEY (name, wikilink),\n * and wikilink field could be NULL.\n */\npublic class TQuotAuthor {\n\n /**\n * Inique identifier of the author.\n */\n private int id;\n\n /**\n * Author's name of the quote.\n */\n private String name;\n\n /**\n * A wikilink to author's name in Wikipedia (format: [[w:name|]]),\n * it could not be NULL, though it can be empty (\"\").\n */\n private String wikilink;\n\n private final static TQuotAuthor[] NULL_TQUOTAUTHOR_ARRAY = new TQuotAuthor[0];\n\n public TQuotAuthor(int _id, String _name, String _wikilink) {\n id = _id;\n name = _name;\n wikilink = _wikilink;\n }\n\n public TQuotAuthor(int _id, String _name) {\n id = _id;\n name = _name;\n wikilink = \"\";\n }\n\n /**\n * Gets unique ID from database\n */\n public int getID() {\n return id;\n }\n\n /**\n * Gets author's name from database.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets wikilink to Wikipedia (format: [[w:name|]]) for the author.\n */\n public String getWikilink() {\n return wikilink;\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * _wikilink can be empty or NULL\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertName(Connect connect, String _name) {\n return insertNameWikilink(connect, _name, \"\");\n }\n\n /**\n * Inserts record into the table 'quot_author'.

\n * INSERT INTO quot_author (name,wikilink) VALUES (\"Isaac Asimov\", \"Isaac Asimov\");\n *\n * @param _name author's name, it is not empty or NULL\n * @param _wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n * @return inserted record, or null if insertion failed\n */\n public static TQuotAuthor insertNameWikilink(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor.insertNameAndWikilink()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"INSERT INTO quot_author (name,wikilink) VALUES (\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\", \\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\")\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.executeUpdate(str_sql.toString());\n s = connect.conn.createStatement();\n ResultSet rs = s.executeQuery(\"SELECT LAST_INSERT_ID() as id\");\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.insertName):: _name='\" + _name + \"'; _wikilink='\" + _wikilink + \"'; sql='\" + str_sql.toString() + \"' error=\" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's first record from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" LIMIT 1;\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor getFirst(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n result = new TQuotAuthor(_id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Get's array of records from the table 'quot_author' by the author's name.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\";\n *\n * @param _name author's name\n * @return NULL if data is absent\n */\n public static TQuotAuthor[] get(Connect connect, String _name) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor[] TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n str_sql.append(\"SELECT id,wikilink FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\";\");\n List list_authors = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n while (rs.next()) {\n if (null == list_authors)\n list_authors = new ArrayList();\n int _id = rs.getInt(\"id\");\n byte[] bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? \"\" : Encodings.bytesToUTF8(bb);\n list_authors.add(new TQuotAuthor(_id, _name, _wikilink));\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n if (null == list_authors)\n return NULL_TQUOTAUTHOR_ARRAY;\n return (TQuotAuthor[]) list_authors.toArray(NULL_TQUOTAUTHOR_ARRAY);\n }\n\n /**\n * Get's first suitable row from the table 'quot_author' by the author's name and wikilink.

.\n * SELECT id,wikilink FROM quot_author WHERE name=\"Azimov\" AND wikilink=\"\" LIMIT 1;\n *\n * @param _name author's name\n * @param _wikilink author's name, it could be NULL or empty (\"\")\n *\n * @return NULL if data is absent\n */\n public static TQuotAuthor get(Connect connect, String _name, String _wikilink) {\n if (null == _name || 0 == _name.length()) {\n System.out.println(\"Error (TQuotAuthor TQuotAuthor.get()):: null argument: author's name.\");\n return null;\n }\n if (null == _wikilink)\n _wikilink = \"\";\n StringBuilder str_sql = new StringBuilder();\n String safe_name = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _name);\n String safe_wikilink = PageTableBase.convertToSafeStringEncodeToDBWunderscore(connect, _wikilink);\n str_sql.append(\"SELECT id FROM quot_author WHERE name=\\\"\");\n str_sql.append(safe_name);\n str_sql.append(\"\\\" AND wikilink=\\\"\");\n str_sql.append(safe_wikilink);\n str_sql.append(\"\\\" LIMIT 1\");\n TQuotAuthor result = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next())\n result = new TQuotAuthor(rs.getInt(\"id\"), _name, _wikilink);\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.get()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return result;\n }\n\n /**\n * Gets ID of a record or inserts record (if it is absent)\n * into the table 'quot_author'.\n *\n * @param _author author's name\n * @param _author_wikilink link to author's name in Wikipedia (format: [[w:name|]]),\n * it could be empty (\"\")\n */\n public static TQuotAuthor getOrInsert(Connect connect, String _author, String _author_wikilink) {\n if (null == _author || 0 == _author.length())\n return null;\n TQuotAuthor a = TQuotAuthor.getFirst(connect, _author);\n if (null == a)\n a = TQuotAuthor.insertNameWikilink(connect, _author, _author_wikilink);\n return a;\n }\n\n /**\n * Selects row from the table 'quot_author' by ID.

\n *\n * SELECT name,wikilink FROM quot_author WHERE id=1\n *\n * @return null if data is absent\n */\n public static TQuotAuthor getByID(Connect connect, int id) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"SELECT name,wikilink FROM quot_author WHERE id=\");\n str_sql.append(id);\n TQuotAuthor quot_author = null;\n try {\n Statement s = connect.conn.createStatement();\n try {\n ResultSet rs = s.executeQuery(str_sql.toString());\n try {\n if (rs.next()) {\n byte[] bb = rs.getBytes(\"name\");\n String _name = null == bb ? null : Encodings.bytesToUTF8(bb);\n bb = rs.getBytes(\"wikilink\");\n String _wikilink = null == bb ? null : Encodings.bytesToUTF8(bb);\n quot_author = new TQuotAuthor(id, _name, _wikilink);\n }\n } finally {\n rs.close();\n }\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.getByID()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n return quot_author;\n }\n\n /**\n * Deletes row from the table 'quot_author' by a value of", "post_mask_code": " ID.

\n * DELETE FROM quot_author WHERE id=4;\n */\n public void delete(Connect connect) {\n StringBuilder str_sql = new StringBuilder();\n str_sql.append(\"DELETE FROM quot_author WHERE id=\");\n str_sql.append(id);\n try {\n Statement s = connect.conn.createStatement();\n try {\n s.execute(str_sql.toString());\n } finally {\n s.close();\n }\n } catch (SQLException ex) {\n System.out.println(\"SQLException (TQuotAuthor.delete()):: sql='\" + str_sql.toString() + \"' \" + ex.getMessage());\n }\n }\n}\n"} {"task_id": "Java_198", "language": "Java", "task_type": "method_signature", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/deviceinfo/storage/StorageEntry.java", "mask_start_position": 6196, "mask_end_position": 6223, "canonical_solution": "public boolean isMounted() ", "pre_mask_code": "package com.android.settings.deviceinfo.storage;\n\nimport android.annotation.NonNull;\nimport android.content.Context;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.storage.DiskInfo;\nimport android.os.storage.StorageManager;\nimport android.os.storage.VolumeInfo;\nimport android.os.storage.VolumeRecord;\nimport android.text.TextUtils;\nimport com.android.settings.R;\nimport java.io.File;\n\n/**\n * This object contains a {@link VolumeInfo} for a mountable storage or a {@link DiskInfo} for an\n * unsupported disk which is not able to be mounted automatically.\n */\npublic class StorageEntry implements Comparable, Parcelable {\n\n private final VolumeInfo mVolumeInfo;\n\n private final DiskInfo mUnsupportedDiskInfo;\n\n private final VolumeRecord mMissingVolumeRecord;\n\n private final String mVolumeInfoDescription;\n\n public StorageEntry(@NonNull Context context, @NonNull VolumeInfo volumeInfo) {\n mVolumeInfo = volumeInfo;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = null;\n if (isDefaultInternalStorage()) {\n mVolumeInfoDescription = context.getResources().getString(R.string.storage_default_internal_storage);\n } else {\n mVolumeInfoDescription = context.getSystemService(StorageManager.class).getBestVolumeDescription(mVolumeInfo);\n }\n }\n\n public StorageEntry(@NonNull DiskInfo diskInfo) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = diskInfo;\n mMissingVolumeRecord = null;\n mVolumeInfoDescription = null;\n }\n\n public StorageEntry(@NonNull VolumeRecord volumeRecord) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = volumeRecord;\n mVolumeInfoDescription = null;\n }\n\n private StorageEntry(Parcel in) {\n mVolumeInfo = in.readParcelable(VolumeInfo.class.getClassLoader());\n mUnsupportedDiskInfo = in.readParcelable(DiskInfo.class.getClassLoader());\n mMissingVolumeRecord = in.readParcelable(VolumeRecord.class.getClassLoader());\n mVolumeInfoDescription = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeParcelable(mVolumeInfo, 0);\n out.writeParcelable(mUnsupportedDiskInfo, 0);\n out.writeParcelable(mMissingVolumeRecord, 0);\n out.writeString(mVolumeInfoDescription);\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n\n public StorageEntry createFromParcel(Parcel in) {\n return new StorageEntry(in);\n }\n\n public StorageEntry[] newArray(int size) {\n return new StorageEntry[size];\n }\n };\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof StorageEntry)) {\n return false;\n }\n final StorageEntry StorageEntry = (StorageEntry) o;\n if (isVolumeInfo()) {\n return mVolumeInfo.equals(StorageEntry.mVolumeInfo);\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.equals(StorageEntry.mUnsupportedDiskInfo);\n }\n return mMissingVolumeRecord.equals(StorageEntry.mMissingVolumeRecord);\n }\n\n @Override\n public int hashCode() {\n if (isVolumeInfo()) {\n return mVolumeInfo.hashCode();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.hashCode();\n }\n return mMissingVolumeRecord.hashCode();\n }\n\n @Override\n public String toString() {\n if (isVolumeInfo()) {\n return mVolumeInfo.toString();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.toString();\n }\n return mMissingVolumeRecord.toString();\n }\n\n @Override\n public int compareTo(StorageEntry other) {\n if (isDefaultInternalStorage() && !other.isDefaultInternalStorage()) {\n return -1;\n }\n if (!isDefaultInternalStorage() && other.isDefaultInternalStorage()) {\n return 1;\n }\n if (isVolumeInfo() && !other.isVolumeInfo()) {\n return -1;\n }\n if (!isVolumeInfo() && other.isVolumeInfo()) {\n return 1;\n }\n if (isPrivate() && !other.isPrivate()) {\n return -1;\n }\n if (!isPrivate() && other.isPrivate()) {\n return 1;\n }\n if (isMounted() && !other.isMounted()) {\n return -1;\n }\n if (!isMounted() && other.isMounted()) {\n return 1;\n }\n if (!isVolumeRecordMissed() && other.isVolumeRecordMissed()) {\n return -1;\n }\n if (isVolumeRecordMissed() && !other.isVolumeRecordMissed()) {\n return 1;\n }\n if (getDescription() == null) {\n return 1;\n }\n if (other.getDescription() == null) {\n return -1;\n }\n return getDescription().compareTo(other.getDescription());\n }\n\n public static StorageEntry getDefaultInternalStorageEntry(Context context) {\n return new StorageEntry(context, context.getSystemService(StorageManager.class).findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL));\n }\n\n /**\n * If it's a VolumeInfo.\n */\n public boolean isVolumeInfo() {\n return mVolumeInfo != null;\n }\n\n /**\n * If it's an unsupported DiskInfo.\n */\n public boolean isDiskInfoUnsupported() {\n return mUnsupportedDiskInfo != null;\n }\n\n /**\n * If it's a missing VolumeRecord.\n */\n public boolean isVolumeRecordMissed() {\n return mMissingVolumeRecord != null;\n }\n\n /**\n * If it's a default internal storage.\n */\n public boolean isDefaultInternalStorage() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE && TextUtils.equals(mVolumeInfo.getId(), VolumeInfo.ID_PRIVATE_INTERNAL);\n }\n return false;\n }\n\n /**\n * If it's a mounted storage.\n */\n ", "post_mask_code": "{\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED || mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED_READ_ONLY);\n }\n\n /**\n * If it's an unmounted storage.\n */\n public boolean isUnmounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTED);\n }\n\n /**\n * If it's an unmountable storage.\n */\n public boolean isUnmountable() {\n return mVolumeInfo == null ? false : mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTABLE;\n }\n\n /**\n * If it's a private storage.\n */\n public boolean isPrivate() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE;\n }\n\n /**\n * If it's a public storage.\n */\n public boolean isPublic() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PUBLIC;\n }\n\n /**\n * Returns description.\n */\n public String getDescription() {\n if (isVolumeInfo()) {\n return mVolumeInfoDescription;\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getDescription();\n }\n return mMissingVolumeRecord.getNickname();\n }\n\n /**\n * Returns ID.\n */\n public String getId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns disk ID.\n */\n public String getDiskId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getDiskId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return null;\n }\n\n /**\n * Returns fsUuid.\n */\n public String getFsUuid() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getFsUuid();\n }\n if (isDiskInfoUnsupported()) {\n return null;\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns root file if it's a VolumeInfo.\n */\n public File getPath() {\n return mVolumeInfo == null ? null : mVolumeInfo.getPath();\n }\n\n /**\n * Returns VolumeInfo of the StorageEntry.\n */\n public VolumeInfo getVolumeInfo() {\n return mVolumeInfo;\n }\n}\n"} {"task_id": "Java_199", "language": "Java", "task_type": "method_body", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/deviceinfo/storage/StorageEntry.java", "mask_start_position": 3429, "mask_end_position": 3668, "canonical_solution": "{\n if (isVolumeInfo()) {\n return mVolumeInfo.hashCode();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.hashCode();\n }\n return mMissingVolumeRecord.hashCode();\n }", "pre_mask_code": "package com.android.settings.deviceinfo.storage;\n\nimport android.annotation.NonNull;\nimport android.content.Context;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.storage.DiskInfo;\nimport android.os.storage.StorageManager;\nimport android.os.storage.VolumeInfo;\nimport android.os.storage.VolumeRecord;\nimport android.text.TextUtils;\nimport com.android.settings.R;\nimport java.io.File;\n\n/**\n * This object contains a {@link VolumeInfo} for a mountable storage or a {@link DiskInfo} for an\n * unsupported disk which is not able to be mounted automatically.\n */\npublic class StorageEntry implements Comparable, Parcelable {\n\n private final VolumeInfo mVolumeInfo;\n\n private final DiskInfo mUnsupportedDiskInfo;\n\n private final VolumeRecord mMissingVolumeRecord;\n\n private final String mVolumeInfoDescription;\n\n public StorageEntry(@NonNull Context context, @NonNull VolumeInfo volumeInfo) {\n mVolumeInfo = volumeInfo;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = null;\n if (isDefaultInternalStorage()) {\n mVolumeInfoDescription = context.getResources().getString(R.string.storage_default_internal_storage);\n } else {\n mVolumeInfoDescription = context.getSystemService(StorageManager.class).getBestVolumeDescription(mVolumeInfo);\n }\n }\n\n public StorageEntry(@NonNull DiskInfo diskInfo) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = diskInfo;\n mMissingVolumeRecord = null;\n mVolumeInfoDescription = null;\n }\n\n public StorageEntry(@NonNull VolumeRecord volumeRecord) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = volumeRecord;\n mVolumeInfoDescription = null;\n }\n\n private StorageEntry(Parcel in) {\n mVolumeInfo = in.readParcelable(VolumeInfo.class.getClassLoader());\n mUnsupportedDiskInfo = in.readParcelable(DiskInfo.class.getClassLoader());\n mMissingVolumeRecord = in.readParcelable(VolumeRecord.class.getClassLoader());\n mVolumeInfoDescription = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeParcelable(mVolumeInfo, 0);\n out.writeParcelable(mUnsupportedDiskInfo, 0);\n out.writeParcelable(mMissingVolumeRecord, 0);\n out.writeString(mVolumeInfoDescription);\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n\n public StorageEntry createFromParcel(Parcel in) {\n return new StorageEntry(in);\n }\n\n public StorageEntry[] newArray(int size) {\n return new StorageEntry[size];\n }\n };\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof StorageEntry)) {\n return false;\n }\n final StorageEntry StorageEntry = (StorageEntry) o;\n if (isVolumeInfo()) {\n return mVolumeInfo.equals(StorageEntry.mVolumeInfo);\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.equals(StorageEntry.mUnsupportedDiskInfo);\n }\n return mMissingVolumeRecord.equals(StorageEntry.mMissingVolumeRecord);\n }\n\n @Override\n public int hashCode() ", "post_mask_code": "\n\n @Override\n public String toString() {\n if (isVolumeInfo()) {\n return mVolumeInfo.toString();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.toString();\n }\n return mMissingVolumeRecord.toString();\n }\n\n @Override\n public int compareTo(StorageEntry other) {\n if (isDefaultInternalStorage() && !other.isDefaultInternalStorage()) {\n return -1;\n }\n if (!isDefaultInternalStorage() && other.isDefaultInternalStorage()) {\n return 1;\n }\n if (isVolumeInfo() && !other.isVolumeInfo()) {\n return -1;\n }\n if (!isVolumeInfo() && other.isVolumeInfo()) {\n return 1;\n }\n if (isPrivate() && !other.isPrivate()) {\n return -1;\n }\n if (!isPrivate() && other.isPrivate()) {\n return 1;\n }\n if (isMounted() && !other.isMounted()) {\n return -1;\n }\n if (!isMounted() && other.isMounted()) {\n return 1;\n }\n if (!isVolumeRecordMissed() && other.isVolumeRecordMissed()) {\n return -1;\n }\n if (isVolumeRecordMissed() && !other.isVolumeRecordMissed()) {\n return 1;\n }\n if (getDescription() == null) {\n return 1;\n }\n if (other.getDescription() == null) {\n return -1;\n }\n return getDescription().compareTo(other.getDescription());\n }\n\n public static StorageEntry getDefaultInternalStorageEntry(Context context) {\n return new StorageEntry(context, context.getSystemService(StorageManager.class).findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL));\n }\n\n /**\n * If it's a VolumeInfo.\n */\n public boolean isVolumeInfo() {\n return mVolumeInfo != null;\n }\n\n /**\n * If it's an unsupported DiskInfo.\n */\n public boolean isDiskInfoUnsupported() {\n return mUnsupportedDiskInfo != null;\n }\n\n /**\n * If it's a missing VolumeRecord.\n */\n public boolean isVolumeRecordMissed() {\n return mMissingVolumeRecord != null;\n }\n\n /**\n * If it's a default internal storage.\n */\n public boolean isDefaultInternalStorage() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE && TextUtils.equals(mVolumeInfo.getId(), VolumeInfo.ID_PRIVATE_INTERNAL);\n }\n return false;\n }\n\n /**\n * If it's a mounted storage.\n */\n public boolean isMounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED || mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED_READ_ONLY);\n }\n\n /**\n * If it's an unmounted storage.\n */\n public boolean isUnmounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTED);\n }\n\n /**\n * If it's an unmountable storage.\n */\n public boolean isUnmountable() {\n return mVolumeInfo == null ? false : mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTABLE;\n }\n\n /**\n * If it's a private storage.\n */\n public boolean isPrivate() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE;\n }\n\n /**\n * If it's a public storage.\n */\n public boolean isPublic() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PUBLIC;\n }\n\n /**\n * Returns description.\n */\n public String getDescription() {\n if (isVolumeInfo()) {\n return mVolumeInfoDescription;\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getDescription();\n }\n return mMissingVolumeRecord.getNickname();\n }\n\n /**\n * Returns ID.\n */\n public String getId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns disk ID.\n */\n public String getDiskId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getDiskId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return null;\n }\n\n /**\n * Returns fsUuid.\n */\n public String getFsUuid() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getFsUuid();\n }\n if (isDiskInfoUnsupported()) {\n return null;\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns root file if it's a VolumeInfo.\n */\n public File getPath() {\n return mVolumeInfo == null ? null : mVolumeInfo.getPath();\n }\n\n /**\n * Returns VolumeInfo of the StorageEntry.\n */\n public VolumeInfo getVolumeInfo() {\n return mVolumeInfo;\n }\n}\n"} {"task_id": "Java_200", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/deviceinfo/storage/StorageEntry.java", "mask_start_position": 7238, "mask_end_position": 7321, "canonical_solution": "\n if (isVolumeInfo()) {\n return mVolumeInfoDescription;\n }", "pre_mask_code": "package com.android.settings.deviceinfo.storage;\n\nimport android.annotation.NonNull;\nimport android.content.Context;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.storage.DiskInfo;\nimport android.os.storage.StorageManager;\nimport android.os.storage.VolumeInfo;\nimport android.os.storage.VolumeRecord;\nimport android.text.TextUtils;\nimport com.android.settings.R;\nimport java.io.File;\n\n/**\n * This object contains a {@link VolumeInfo} for a mountable storage or a {@link DiskInfo} for an\n * unsupported disk which is not able to be mounted automatically.\n */\npublic class StorageEntry implements Comparable, Parcelable {\n\n private final VolumeInfo mVolumeInfo;\n\n private final DiskInfo mUnsupportedDiskInfo;\n\n private final VolumeRecord mMissingVolumeRecord;\n\n private final String mVolumeInfoDescription;\n\n public StorageEntry(@NonNull Context context, @NonNull VolumeInfo volumeInfo) {\n mVolumeInfo = volumeInfo;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = null;\n if (isDefaultInternalStorage()) {\n mVolumeInfoDescription = context.getResources().getString(R.string.storage_default_internal_storage);\n } else {\n mVolumeInfoDescription = context.getSystemService(StorageManager.class).getBestVolumeDescription(mVolumeInfo);\n }\n }\n\n public StorageEntry(@NonNull DiskInfo diskInfo) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = diskInfo;\n mMissingVolumeRecord = null;\n mVolumeInfoDescription = null;\n }\n\n public StorageEntry(@NonNull VolumeRecord volumeRecord) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = volumeRecord;\n mVolumeInfoDescription = null;\n }\n\n private StorageEntry(Parcel in) {\n mVolumeInfo = in.readParcelable(VolumeInfo.class.getClassLoader());\n mUnsupportedDiskInfo = in.readParcelable(DiskInfo.class.getClassLoader());\n mMissingVolumeRecord = in.readParcelable(VolumeRecord.class.getClassLoader());\n mVolumeInfoDescription = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeParcelable(mVolumeInfo, 0);\n out.writeParcelable(mUnsupportedDiskInfo, 0);\n out.writeParcelable(mMissingVolumeRecord, 0);\n out.writeString(mVolumeInfoDescription);\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n\n public StorageEntry createFromParcel(Parcel in) {\n return new StorageEntry(in);\n }\n\n public StorageEntry[] newArray(int size) {\n return new StorageEntry[size];\n }\n };\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof StorageEntry)) {\n return false;\n }\n final StorageEntry StorageEntry = (StorageEntry) o;\n if (isVolumeInfo()) {\n return mVolumeInfo.equals(StorageEntry.mVolumeInfo);\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.equals(StorageEntry.mUnsupportedDiskInfo);\n }\n return mMissingVolumeRecord.equals(StorageEntry.mMissingVolumeRecord);\n }\n\n @Override\n public int hashCode() {\n if (isVolumeInfo()) {\n return mVolumeInfo.hashCode();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.hashCode();\n }\n return mMissingVolumeRecord.hashCode();\n }\n\n @Override\n public String toString() {\n if (isVolumeInfo()) {\n return mVolumeInfo.toString();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.toString();\n }\n return mMissingVolumeRecord.toString();\n }\n\n @Override\n public int compareTo(StorageEntry other) {\n if (isDefaultInternalStorage() && !other.isDefaultInternalStorage()) {\n return -1;\n }\n if (!isDefaultInternalStorage() && other.isDefaultInternalStorage()) {\n return 1;\n }\n if (isVolumeInfo() && !other.isVolumeInfo()) {\n return -1;\n }\n if (!isVolumeInfo() && other.isVolumeInfo()) {\n return 1;\n }\n if (isPrivate() && !other.isPrivate()) {\n return -1;\n }\n if (!isPrivate() && other.isPrivate()) {\n return 1;\n }\n if (isMounted() && !other.isMounted()) {\n return -1;\n }\n if (!isMounted() && other.isMounted()) {\n return 1;\n }\n if (!isVolumeRecordMissed() && other.isVolumeRecordMissed()) {\n return -1;\n }\n if (isVolumeRecordMissed() && !other.isVolumeRecordMissed()) {\n return 1;\n }\n if (getDescription() == null) {\n return 1;\n }\n if (other.getDescription() == null) {\n return -1;\n }\n return getDescription().compareTo(other.getDescription());\n }\n\n public static StorageEntry getDefaultInternalStorageEntry(Context context) {\n return new StorageEntry(context, context.getSystemService(StorageManager.class).findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL));\n }\n\n /**\n * If it's a VolumeInfo.\n */\n public boolean isVolumeInfo() {\n return mVolumeInfo != null;\n }\n\n /**\n * If it's an unsupported DiskInfo.\n */\n public boolean isDiskInfoUnsupported() {\n return mUnsupportedDiskInfo != null;\n }\n\n /**\n * If it's a missing VolumeRecord.\n */\n public boolean isVolumeRecordMissed() {\n return mMissingVolumeRecord != null;\n }\n\n /**\n * If it's a default internal storage.\n */\n public boolean isDefaultInternalStorage() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE && TextUtils.equals(mVolumeInfo.getId(), VolumeInfo.ID_PRIVATE_INTERNAL);\n }\n return false;\n }\n\n /**\n * If it's a mounted storage.\n */\n public boolean isMounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED || mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED_READ_ONLY);\n }\n\n /**\n * If it's an unmounted storage.\n */\n public boolean isUnmounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTED);\n }\n\n /**\n * If it's an unmountable storage.\n */\n public boolean isUnmountable() {\n return mVolumeInfo == null ? false : mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTABLE;\n }\n\n /**\n * If it's a private storage.\n */\n public boolean isPrivate() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE;\n }\n\n /**\n * If it's a public storage.\n */\n public boolean isPublic() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PUBLIC;\n }\n\n /**\n * Returns description.\n */\n public String getDescription() {", "post_mask_code": "\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getDescription();\n }\n return mMissingVolumeRecord.getNickname();\n }\n\n /**\n * Returns ID.\n */\n public String getId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns disk ID.\n */\n public String getDiskId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getDiskId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return null;\n }\n\n /**\n * Returns fsUuid.\n */\n public String getFsUuid() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getFsUuid();\n }\n if (isDiskInfoUnsupported()) {\n return null;\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns root file if it's a VolumeInfo.\n */\n public File getPath() {\n return mVolumeInfo == null ? null : mVolumeInfo.getPath();\n }\n\n /**\n * Returns VolumeInfo of the StorageEntry.\n */\n public VolumeInfo getVolumeInfo() {\n return mVolumeInfo;\n }\n}\n"} {"task_id": "Java_201", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/deviceinfo/storage/StorageEntry.java", "mask_start_position": 7330, "mask_end_position": 7428, "canonical_solution": "if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getDescription();\n }", "pre_mask_code": "package com.android.settings.deviceinfo.storage;\n\nimport android.annotation.NonNull;\nimport android.content.Context;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.storage.DiskInfo;\nimport android.os.storage.StorageManager;\nimport android.os.storage.VolumeInfo;\nimport android.os.storage.VolumeRecord;\nimport android.text.TextUtils;\nimport com.android.settings.R;\nimport java.io.File;\n\n/**\n * This object contains a {@link VolumeInfo} for a mountable storage or a {@link DiskInfo} for an\n * unsupported disk which is not able to be mounted automatically.\n */\npublic class StorageEntry implements Comparable, Parcelable {\n\n private final VolumeInfo mVolumeInfo;\n\n private final DiskInfo mUnsupportedDiskInfo;\n\n private final VolumeRecord mMissingVolumeRecord;\n\n private final String mVolumeInfoDescription;\n\n public StorageEntry(@NonNull Context context, @NonNull VolumeInfo volumeInfo) {\n mVolumeInfo = volumeInfo;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = null;\n if (isDefaultInternalStorage()) {\n mVolumeInfoDescription = context.getResources().getString(R.string.storage_default_internal_storage);\n } else {\n mVolumeInfoDescription = context.getSystemService(StorageManager.class).getBestVolumeDescription(mVolumeInfo);\n }\n }\n\n public StorageEntry(@NonNull DiskInfo diskInfo) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = diskInfo;\n mMissingVolumeRecord = null;\n mVolumeInfoDescription = null;\n }\n\n public StorageEntry(@NonNull VolumeRecord volumeRecord) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = volumeRecord;\n mVolumeInfoDescription = null;\n }\n\n private StorageEntry(Parcel in) {\n mVolumeInfo = in.readParcelable(VolumeInfo.class.getClassLoader());\n mUnsupportedDiskInfo = in.readParcelable(DiskInfo.class.getClassLoader());\n mMissingVolumeRecord = in.readParcelable(VolumeRecord.class.getClassLoader());\n mVolumeInfoDescription = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeParcelable(mVolumeInfo, 0);\n out.writeParcelable(mUnsupportedDiskInfo, 0);\n out.writeParcelable(mMissingVolumeRecord, 0);\n out.writeString(mVolumeInfoDescription);\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n\n public StorageEntry createFromParcel(Parcel in) {\n return new StorageEntry(in);\n }\n\n public StorageEntry[] newArray(int size) {\n return new StorageEntry[size];\n }\n };\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof StorageEntry)) {\n return false;\n }\n final StorageEntry StorageEntry = (StorageEntry) o;\n if (isVolumeInfo()) {\n return mVolumeInfo.equals(StorageEntry.mVolumeInfo);\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.equals(StorageEntry.mUnsupportedDiskInfo);\n }\n return mMissingVolumeRecord.equals(StorageEntry.mMissingVolumeRecord);\n }\n\n @Override\n public int hashCode() {\n if (isVolumeInfo()) {\n return mVolumeInfo.hashCode();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.hashCode();\n }\n return mMissingVolumeRecord.hashCode();\n }\n\n @Override\n public String toString() {\n if (isVolumeInfo()) {\n return mVolumeInfo.toString();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.toString();\n }\n return mMissingVolumeRecord.toString();\n }\n\n @Override\n public int compareTo(StorageEntry other) {\n if (isDefaultInternalStorage() && !other.isDefaultInternalStorage()) {\n return -1;\n }\n if (!isDefaultInternalStorage() && other.isDefaultInternalStorage()) {\n return 1;\n }\n if (isVolumeInfo() && !other.isVolumeInfo()) {\n return -1;\n }\n if (!isVolumeInfo() && other.isVolumeInfo()) {\n return 1;\n }\n if (isPrivate() && !other.isPrivate()) {\n return -1;\n }\n if (!isPrivate() && other.isPrivate()) {\n return 1;\n }\n if (isMounted() && !other.isMounted()) {\n return -1;\n }\n if (!isMounted() && other.isMounted()) {\n return 1;\n }\n if (!isVolumeRecordMissed() && other.isVolumeRecordMissed()) {\n return -1;\n }\n if (isVolumeRecordMissed() && !other.isVolumeRecordMissed()) {\n return 1;\n }\n if (getDescription() == null) {\n return 1;\n }\n if (other.getDescription() == null) {\n return -1;\n }\n return getDescription().compareTo(other.getDescription());\n }\n\n public static StorageEntry getDefaultInternalStorageEntry(Context context) {\n return new StorageEntry(context, context.getSystemService(StorageManager.class).findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL));\n }\n\n /**\n * If it's a VolumeInfo.\n */\n public boolean isVolumeInfo() {\n return mVolumeInfo != null;\n }\n\n /**\n * If it's an unsupported DiskInfo.\n */\n public boolean isDiskInfoUnsupported() {\n return mUnsupportedDiskInfo != null;\n }\n\n /**\n * If it's a missing VolumeRecord.\n */\n public boolean isVolumeRecordMissed() {\n return mMissingVolumeRecord != null;\n }\n\n /**\n * If it's a default internal storage.\n */\n public boolean isDefaultInternalStorage() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE && TextUtils.equals(mVolumeInfo.getId(), VolumeInfo.ID_PRIVATE_INTERNAL);\n }\n return false;\n }\n\n /**\n * If it's a mounted storage.\n */\n public boolean isMounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED || mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED_READ_ONLY);\n }\n\n /**\n * If it's an unmounted storage.\n */\n public boolean isUnmounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTED);\n }\n\n /**\n * If it's an unmountable storage.\n */\n public boolean isUnmountable() {\n return mVolumeInfo == null ? false : mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTABLE;\n }\n\n /**\n * If it's a private storage.\n */\n public boolean isPrivate() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE;\n }\n\n /**\n * If it's a public storage.\n */\n public boolean isPublic() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PUBLIC;\n }\n\n /**\n * Returns description.\n */\n public String getDescription() {\n if (isVolumeInfo()) {\n return mVolumeInfoDescription;\n }\n ", "post_mask_code": "\n return mMissingVolumeRecord.getNickname();\n }\n\n /**\n * Returns ID.\n */\n public String getId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns disk ID.\n */\n public String getDiskId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getDiskId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return null;\n }\n\n /**\n * Returns fsUuid.\n */\n public String getFsUuid() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getFsUuid();\n }\n if (isDiskInfoUnsupported()) {\n return null;\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns root file if it's a VolumeInfo.\n */\n public File getPath() {\n return mVolumeInfo == null ? null : mVolumeInfo.getPath();\n }\n\n /**\n * Returns VolumeInfo of the StorageEntry.\n */\n public VolumeInfo getVolumeInfo() {\n return mVolumeInfo;\n }\n}\n"} {"task_id": "Java_202", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/deviceinfo/storage/StorageEntry.java", "mask_start_position": 7437, "mask_end_position": 7485, "canonical_solution": "return mMissingVolumeRecord.getNickname();\n }", "pre_mask_code": "package com.android.settings.deviceinfo.storage;\n\nimport android.annotation.NonNull;\nimport android.content.Context;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.storage.DiskInfo;\nimport android.os.storage.StorageManager;\nimport android.os.storage.VolumeInfo;\nimport android.os.storage.VolumeRecord;\nimport android.text.TextUtils;\nimport com.android.settings.R;\nimport java.io.File;\n\n/**\n * This object contains a {@link VolumeInfo} for a mountable storage or a {@link DiskInfo} for an\n * unsupported disk which is not able to be mounted automatically.\n */\npublic class StorageEntry implements Comparable, Parcelable {\n\n private final VolumeInfo mVolumeInfo;\n\n private final DiskInfo mUnsupportedDiskInfo;\n\n private final VolumeRecord mMissingVolumeRecord;\n\n private final String mVolumeInfoDescription;\n\n public StorageEntry(@NonNull Context context, @NonNull VolumeInfo volumeInfo) {\n mVolumeInfo = volumeInfo;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = null;\n if (isDefaultInternalStorage()) {\n mVolumeInfoDescription = context.getResources().getString(R.string.storage_default_internal_storage);\n } else {\n mVolumeInfoDescription = context.getSystemService(StorageManager.class).getBestVolumeDescription(mVolumeInfo);\n }\n }\n\n public StorageEntry(@NonNull DiskInfo diskInfo) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = diskInfo;\n mMissingVolumeRecord = null;\n mVolumeInfoDescription = null;\n }\n\n public StorageEntry(@NonNull VolumeRecord volumeRecord) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = volumeRecord;\n mVolumeInfoDescription = null;\n }\n\n private StorageEntry(Parcel in) {\n mVolumeInfo = in.readParcelable(VolumeInfo.class.getClassLoader());\n mUnsupportedDiskInfo = in.readParcelable(DiskInfo.class.getClassLoader());\n mMissingVolumeRecord = in.readParcelable(VolumeRecord.class.getClassLoader());\n mVolumeInfoDescription = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeParcelable(mVolumeInfo, 0);\n out.writeParcelable(mUnsupportedDiskInfo, 0);\n out.writeParcelable(mMissingVolumeRecord, 0);\n out.writeString(mVolumeInfoDescription);\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n\n public StorageEntry createFromParcel(Parcel in) {\n return new StorageEntry(in);\n }\n\n public StorageEntry[] newArray(int size) {\n return new StorageEntry[size];\n }\n };\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof StorageEntry)) {\n return false;\n }\n final StorageEntry StorageEntry = (StorageEntry) o;\n if (isVolumeInfo()) {\n return mVolumeInfo.equals(StorageEntry.mVolumeInfo);\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.equals(StorageEntry.mUnsupportedDiskInfo);\n }\n return mMissingVolumeRecord.equals(StorageEntry.mMissingVolumeRecord);\n }\n\n @Override\n public int hashCode() {\n if (isVolumeInfo()) {\n return mVolumeInfo.hashCode();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.hashCode();\n }\n return mMissingVolumeRecord.hashCode();\n }\n\n @Override\n public String toString() {\n if (isVolumeInfo()) {\n return mVolumeInfo.toString();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.toString();\n }\n return mMissingVolumeRecord.toString();\n }\n\n @Override\n public int compareTo(StorageEntry other) {\n if (isDefaultInternalStorage() && !other.isDefaultInternalStorage()) {\n return -1;\n }\n if (!isDefaultInternalStorage() && other.isDefaultInternalStorage()) {\n return 1;\n }\n if (isVolumeInfo() && !other.isVolumeInfo()) {\n return -1;\n }\n if (!isVolumeInfo() && other.isVolumeInfo()) {\n return 1;\n }\n if (isPrivate() && !other.isPrivate()) {\n return -1;\n }\n if (!isPrivate() && other.isPrivate()) {\n return 1;\n }\n if (isMounted() && !other.isMounted()) {\n return -1;\n }\n if (!isMounted() && other.isMounted()) {\n return 1;\n }\n if (!isVolumeRecordMissed() && other.isVolumeRecordMissed()) {\n return -1;\n }\n if (isVolumeRecordMissed() && !other.isVolumeRecordMissed()) {\n return 1;\n }\n if (getDescription() == null) {\n return 1;\n }\n if (other.getDescription() == null) {\n return -1;\n }\n return getDescription().compareTo(other.getDescription());\n }\n\n public static StorageEntry getDefaultInternalStorageEntry(Context context) {\n return new StorageEntry(context, context.getSystemService(StorageManager.class).findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL));\n }\n\n /**\n * If it's a VolumeInfo.\n */\n public boolean isVolumeInfo() {\n return mVolumeInfo != null;\n }\n\n /**\n * If it's an unsupported DiskInfo.\n */\n public boolean isDiskInfoUnsupported() {\n return mUnsupportedDiskInfo != null;\n }\n\n /**\n * If it's a missing VolumeRecord.\n */\n public boolean isVolumeRecordMissed() {\n return mMissingVolumeRecord != null;\n }\n\n /**\n * If it's a default internal storage.\n */\n public boolean isDefaultInternalStorage() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE && TextUtils.equals(mVolumeInfo.getId(), VolumeInfo.ID_PRIVATE_INTERNAL);\n }\n return false;\n }\n\n /**\n * If it's a mounted storage.\n */\n public boolean isMounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED || mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED_READ_ONLY);\n }\n\n /**\n * If it's an unmounted storage.\n */\n public boolean isUnmounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTED);\n }\n\n /**\n * If it's an unmountable storage.\n */\n public boolean isUnmountable() {\n return mVolumeInfo == null ? false : mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTABLE;\n }\n\n /**\n * If it's a private storage.\n */\n public boolean isPrivate() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE;\n }\n\n /**\n * If it's a public storage.\n */\n public boolean isPublic() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PUBLIC;\n }\n\n /**\n * Returns description.\n */\n public String getDescription() {\n if (isVolumeInfo()) {\n return mVolumeInfoDescription;\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getDescription();\n }\n ", "post_mask_code": "\n\n /**\n * Returns ID.\n */\n public String getId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns disk ID.\n */\n public String getDiskId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getDiskId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return null;\n }\n\n /**\n * Returns fsUuid.\n */\n public String getFsUuid() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getFsUuid();\n }\n if (isDiskInfoUnsupported()) {\n return null;\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns root file if it's a VolumeInfo.\n */\n public File getPath() {\n return mVolumeInfo == null ? null : mVolumeInfo.getPath();\n }\n\n /**\n * Returns VolumeInfo of the StorageEntry.\n */\n public VolumeInfo getVolumeInfo() {\n return mVolumeInfo;\n }\n}\n"} {"task_id": "Java_203", "language": "Java", "task_type": "single_line", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/deviceinfo/storage/StorageEntry.java", "mask_start_position": 8056, "mask_end_position": 8058, "canonical_solution": "l;", "pre_mask_code": "package com.android.settings.deviceinfo.storage;\n\nimport android.annotation.NonNull;\nimport android.content.Context;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.storage.DiskInfo;\nimport android.os.storage.StorageManager;\nimport android.os.storage.VolumeInfo;\nimport android.os.storage.VolumeRecord;\nimport android.text.TextUtils;\nimport com.android.settings.R;\nimport java.io.File;\n\n/**\n * This object contains a {@link VolumeInfo} for a mountable storage or a {@link DiskInfo} for an\n * unsupported disk which is not able to be mounted automatically.\n */\npublic class StorageEntry implements Comparable, Parcelable {\n\n private final VolumeInfo mVolumeInfo;\n\n private final DiskInfo mUnsupportedDiskInfo;\n\n private final VolumeRecord mMissingVolumeRecord;\n\n private final String mVolumeInfoDescription;\n\n public StorageEntry(@NonNull Context context, @NonNull VolumeInfo volumeInfo) {\n mVolumeInfo = volumeInfo;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = null;\n if (isDefaultInternalStorage()) {\n mVolumeInfoDescription = context.getResources().getString(R.string.storage_default_internal_storage);\n } else {\n mVolumeInfoDescription = context.getSystemService(StorageManager.class).getBestVolumeDescription(mVolumeInfo);\n }\n }\n\n public StorageEntry(@NonNull DiskInfo diskInfo) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = diskInfo;\n mMissingVolumeRecord = null;\n mVolumeInfoDescription = null;\n }\n\n public StorageEntry(@NonNull VolumeRecord volumeRecord) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = volumeRecord;\n mVolumeInfoDescription = null;\n }\n\n private StorageEntry(Parcel in) {\n mVolumeInfo = in.readParcelable(VolumeInfo.class.getClassLoader());\n mUnsupportedDiskInfo = in.readParcelable(DiskInfo.class.getClassLoader());\n mMissingVolumeRecord = in.readParcelable(VolumeRecord.class.getClassLoader());\n mVolumeInfoDescription = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeParcelable(mVolumeInfo, 0);\n out.writeParcelable(mUnsupportedDiskInfo, 0);\n out.writeParcelable(mMissingVolumeRecord, 0);\n out.writeString(mVolumeInfoDescription);\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n\n public StorageEntry createFromParcel(Parcel in) {\n return new StorageEntry(in);\n }\n\n public StorageEntry[] newArray(int size) {\n return new StorageEntry[size];\n }\n };\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof StorageEntry)) {\n return false;\n }\n final StorageEntry StorageEntry = (StorageEntry) o;\n if (isVolumeInfo()) {\n return mVolumeInfo.equals(StorageEntry.mVolumeInfo);\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.equals(StorageEntry.mUnsupportedDiskInfo);\n }\n return mMissingVolumeRecord.equals(StorageEntry.mMissingVolumeRecord);\n }\n\n @Override\n public int hashCode() {\n if (isVolumeInfo()) {\n return mVolumeInfo.hashCode();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.hashCode();\n }\n return mMissingVolumeRecord.hashCode();\n }\n\n @Override\n public String toString() {\n if (isVolumeInfo()) {\n return mVolumeInfo.toString();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.toString();\n }\n return mMissingVolumeRecord.toString();\n }\n\n @Override\n public int compareTo(StorageEntry other) {\n if (isDefaultInternalStorage() && !other.isDefaultInternalStorage()) {\n return -1;\n }\n if (!isDefaultInternalStorage() && other.isDefaultInternalStorage()) {\n return 1;\n }\n if (isVolumeInfo() && !other.isVolumeInfo()) {\n return -1;\n }\n if (!isVolumeInfo() && other.isVolumeInfo()) {\n return 1;\n }\n if (isPrivate() && !other.isPrivate()) {\n return -1;\n }\n if (!isPrivate() && other.isPrivate()) {\n return 1;\n }\n if (isMounted() && !other.isMounted()) {\n return -1;\n }\n if (!isMounted() && other.isMounted()) {\n return 1;\n }\n if (!isVolumeRecordMissed() && other.isVolumeRecordMissed()) {\n return -1;\n }\n if (isVolumeRecordMissed() && !other.isVolumeRecordMissed()) {\n return 1;\n }\n if (getDescription() == null) {\n return 1;\n }\n if (other.getDescription() == null) {\n return -1;\n }\n return getDescription().compareTo(other.getDescription());\n }\n\n public static StorageEntry getDefaultInternalStorageEntry(Context context) {\n return new StorageEntry(context, context.getSystemService(StorageManager.class).findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL));\n }\n\n /**\n * If it's a VolumeInfo.\n */\n public boolean isVolumeInfo() {\n return mVolumeInfo != null;\n }\n\n /**\n * If it's an unsupported DiskInfo.\n */\n public boolean isDiskInfoUnsupported() {\n return mUnsupportedDiskInfo != null;\n }\n\n /**\n * If it's a missing VolumeRecord.\n */\n public boolean isVolumeRecordMissed() {\n return mMissingVolumeRecord != null;\n }\n\n /**\n * If it's a default internal storage.\n */\n public boolean isDefaultInternalStorage() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE && TextUtils.equals(mVolumeInfo.getId(), VolumeInfo.ID_PRIVATE_INTERNAL);\n }\n return false;\n }\n\n /**\n * If it's a mounted storage.\n */\n public boolean isMounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED || mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED_READ_ONLY);\n }\n\n /**\n * If it's an unmounted storage.\n */\n public boolean isUnmounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTED);\n }\n\n /**\n * If it's an unmountable storage.\n */\n public boolean isUnmountable() {\n return mVolumeInfo == null ? false : mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTABLE;\n }\n\n /**\n * If it's a private storage.\n */\n public boolean isPrivate() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE;\n }\n\n /**\n * If it's a public storage.\n */\n public boolean isPublic() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PUBLIC;\n }\n\n /**\n * Returns description.\n */\n public String getDescription() {\n if (isVolumeInfo()) {\n return mVolumeInfoDescription;\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getDescription();\n }\n return mMissingVolumeRecord.getNickname();\n }\n\n /**\n * Returns ID.\n */\n public String getId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns disk ID.\n */\n public String getDiskId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getDiskId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return nul", "post_mask_code": "\n }\n\n /**\n * Returns fsUuid.\n */\n public String getFsUuid() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getFsUuid();\n }\n if (isDiskInfoUnsupported()) {\n return null;\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns root file if it's a VolumeInfo.\n */\n public File getPath() {\n return mVolumeInfo == null ? null : mVolumeInfo.getPath();\n }\n\n /**\n * Returns VolumeInfo of the StorageEntry.\n */\n public VolumeInfo getVolumeInfo() {\n return mVolumeInfo;\n }\n}\n"} {"task_id": "Java_204", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/deviceinfo/storage/StorageEntry.java", "mask_start_position": 8109, "mask_end_position": 8349, "canonical_solution": "public String getFsUuid() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getFsUuid();\n }\n if (isDiskInfoUnsupported()) {\n return null;\n }\n return mMissingVolumeRecord.getFsUuid();\n }", "pre_mask_code": "package com.android.settings.deviceinfo.storage;\n\nimport android.annotation.NonNull;\nimport android.content.Context;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.storage.DiskInfo;\nimport android.os.storage.StorageManager;\nimport android.os.storage.VolumeInfo;\nimport android.os.storage.VolumeRecord;\nimport android.text.TextUtils;\nimport com.android.settings.R;\nimport java.io.File;\n\n/**\n * This object contains a {@link VolumeInfo} for a mountable storage or a {@link DiskInfo} for an\n * unsupported disk which is not able to be mounted automatically.\n */\npublic class StorageEntry implements Comparable, Parcelable {\n\n private final VolumeInfo mVolumeInfo;\n\n private final DiskInfo mUnsupportedDiskInfo;\n\n private final VolumeRecord mMissingVolumeRecord;\n\n private final String mVolumeInfoDescription;\n\n public StorageEntry(@NonNull Context context, @NonNull VolumeInfo volumeInfo) {\n mVolumeInfo = volumeInfo;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = null;\n if (isDefaultInternalStorage()) {\n mVolumeInfoDescription = context.getResources().getString(R.string.storage_default_internal_storage);\n } else {\n mVolumeInfoDescription = context.getSystemService(StorageManager.class).getBestVolumeDescription(mVolumeInfo);\n }\n }\n\n public StorageEntry(@NonNull DiskInfo diskInfo) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = diskInfo;\n mMissingVolumeRecord = null;\n mVolumeInfoDescription = null;\n }\n\n public StorageEntry(@NonNull VolumeRecord volumeRecord) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = volumeRecord;\n mVolumeInfoDescription = null;\n }\n\n private StorageEntry(Parcel in) {\n mVolumeInfo = in.readParcelable(VolumeInfo.class.getClassLoader());\n mUnsupportedDiskInfo = in.readParcelable(DiskInfo.class.getClassLoader());\n mMissingVolumeRecord = in.readParcelable(VolumeRecord.class.getClassLoader());\n mVolumeInfoDescription = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeParcelable(mVolumeInfo, 0);\n out.writeParcelable(mUnsupportedDiskInfo, 0);\n out.writeParcelable(mMissingVolumeRecord, 0);\n out.writeString(mVolumeInfoDescription);\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n\n public StorageEntry createFromParcel(Parcel in) {\n return new StorageEntry(in);\n }\n\n public StorageEntry[] newArray(int size) {\n return new StorageEntry[size];\n }\n };\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof StorageEntry)) {\n return false;\n }\n final StorageEntry StorageEntry = (StorageEntry) o;\n if (isVolumeInfo()) {\n return mVolumeInfo.equals(StorageEntry.mVolumeInfo);\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.equals(StorageEntry.mUnsupportedDiskInfo);\n }\n return mMissingVolumeRecord.equals(StorageEntry.mMissingVolumeRecord);\n }\n\n @Override\n public int hashCode() {\n if (isVolumeInfo()) {\n return mVolumeInfo.hashCode();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.hashCode();\n }\n return mMissingVolumeRecord.hashCode();\n }\n\n @Override\n public String toString() {\n if (isVolumeInfo()) {\n return mVolumeInfo.toString();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.toString();\n }\n return mMissingVolumeRecord.toString();\n }\n\n @Override\n public int compareTo(StorageEntry other) {\n if (isDefaultInternalStorage() && !other.isDefaultInternalStorage()) {\n return -1;\n }\n if (!isDefaultInternalStorage() && other.isDefaultInternalStorage()) {\n return 1;\n }\n if (isVolumeInfo() && !other.isVolumeInfo()) {\n return -1;\n }\n if (!isVolumeInfo() && other.isVolumeInfo()) {\n return 1;\n }\n if (isPrivate() && !other.isPrivate()) {\n return -1;\n }\n if (!isPrivate() && other.isPrivate()) {\n return 1;\n }\n if (isMounted() && !other.isMounted()) {\n return -1;\n }\n if (!isMounted() && other.isMounted()) {\n return 1;\n }\n if (!isVolumeRecordMissed() && other.isVolumeRecordMissed()) {\n return -1;\n }\n if (isVolumeRecordMissed() && !other.isVolumeRecordMissed()) {\n return 1;\n }\n if (getDescription() == null) {\n return 1;\n }\n if (other.getDescription() == null) {\n return -1;\n }\n return getDescription().compareTo(other.getDescription());\n }\n\n public static StorageEntry getDefaultInternalStorageEntry(Context context) {\n return new StorageEntry(context, context.getSystemService(StorageManager.class).findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL));\n }\n\n /**\n * If it's a VolumeInfo.\n */\n public boolean isVolumeInfo() {\n return mVolumeInfo != null;\n }\n\n /**\n * If it's an unsupported DiskInfo.\n */\n public boolean isDiskInfoUnsupported() {\n return mUnsupportedDiskInfo != null;\n }\n\n /**\n * If it's a missing VolumeRecord.\n */\n public boolean isVolumeRecordMissed() {\n return mMissingVolumeRecord != null;\n }\n\n /**\n * If it's a default internal storage.\n */\n public boolean isDefaultInternalStorage() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE && TextUtils.equals(mVolumeInfo.getId(), VolumeInfo.ID_PRIVATE_INTERNAL);\n }\n return false;\n }\n\n /**\n * If it's a mounted storage.\n */\n public boolean isMounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED || mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED_READ_ONLY);\n }\n\n /**\n * If it's an unmounted storage.\n */\n public boolean isUnmounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTED);\n }\n\n /**\n * If it's an unmountable storage.\n */\n public boolean isUnmountable() {\n return mVolumeInfo == null ? false : mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTABLE;\n }\n\n /**\n * If it's a private storage.\n */\n public boolean isPrivate() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE;\n }\n\n /**\n * If it's a public storage.\n */\n public boolean isPublic() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PUBLIC;\n }\n\n /**\n * Returns description.\n */\n public String getDescription() {\n if (isVolumeInfo()) {\n return mVolumeInfoDescription;\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getDescription();\n }\n return mMissingVolumeRecord.getNickname();\n }\n\n /**\n * Returns ID.\n */\n public String getId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns disk ID.\n */\n public String getDiskId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getDiskId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return null;\n }\n\n /**\n * Returns fsUuid.\n */\n ", "post_mask_code": "\n\n /**\n * Returns root file if it's a VolumeInfo.\n */\n public File getPath() {\n return mVolumeInfo == null ? null : mVolumeInfo.getPath();\n }\n\n /**\n * Returns VolumeInfo of the StorageEntry.\n */\n public VolumeInfo getVolumeInfo() {\n return mVolumeInfo;\n }\n}\n"} {"task_id": "Java_205", "language": "Java", "task_type": "if_statement", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/deviceinfo/storage/StorageEntry.java", "mask_start_position": 3439, "mask_end_position": 3513, "canonical_solution": "if (isVolumeInfo()) {\n return mVolumeInfo.hashCode();\n }", "pre_mask_code": "package com.android.settings.deviceinfo.storage;\n\nimport android.annotation.NonNull;\nimport android.content.Context;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.storage.DiskInfo;\nimport android.os.storage.StorageManager;\nimport android.os.storage.VolumeInfo;\nimport android.os.storage.VolumeRecord;\nimport android.text.TextUtils;\nimport com.android.settings.R;\nimport java.io.File;\n\n/**\n * This object contains a {@link VolumeInfo} for a mountable storage or a {@link DiskInfo} for an\n * unsupported disk which is not able to be mounted automatically.\n */\npublic class StorageEntry implements Comparable, Parcelable {\n\n private final VolumeInfo mVolumeInfo;\n\n private final DiskInfo mUnsupportedDiskInfo;\n\n private final VolumeRecord mMissingVolumeRecord;\n\n private final String mVolumeInfoDescription;\n\n public StorageEntry(@NonNull Context context, @NonNull VolumeInfo volumeInfo) {\n mVolumeInfo = volumeInfo;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = null;\n if (isDefaultInternalStorage()) {\n mVolumeInfoDescription = context.getResources().getString(R.string.storage_default_internal_storage);\n } else {\n mVolumeInfoDescription = context.getSystemService(StorageManager.class).getBestVolumeDescription(mVolumeInfo);\n }\n }\n\n public StorageEntry(@NonNull DiskInfo diskInfo) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = diskInfo;\n mMissingVolumeRecord = null;\n mVolumeInfoDescription = null;\n }\n\n public StorageEntry(@NonNull VolumeRecord volumeRecord) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = volumeRecord;\n mVolumeInfoDescription = null;\n }\n\n private StorageEntry(Parcel in) {\n mVolumeInfo = in.readParcelable(VolumeInfo.class.getClassLoader());\n mUnsupportedDiskInfo = in.readParcelable(DiskInfo.class.getClassLoader());\n mMissingVolumeRecord = in.readParcelable(VolumeRecord.class.getClassLoader());\n mVolumeInfoDescription = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeParcelable(mVolumeInfo, 0);\n out.writeParcelable(mUnsupportedDiskInfo, 0);\n out.writeParcelable(mMissingVolumeRecord, 0);\n out.writeString(mVolumeInfoDescription);\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n\n public StorageEntry createFromParcel(Parcel in) {\n return new StorageEntry(in);\n }\n\n public StorageEntry[] newArray(int size) {\n return new StorageEntry[size];\n }\n };\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof StorageEntry)) {\n return false;\n }\n final StorageEntry StorageEntry = (StorageEntry) o;\n if (isVolumeInfo()) {\n return mVolumeInfo.equals(StorageEntry.mVolumeInfo);\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.equals(StorageEntry.mUnsupportedDiskInfo);\n }\n return mMissingVolumeRecord.equals(StorageEntry.mMissingVolumeRecord);\n }\n\n @Override\n public int hashCode() {\n ", "post_mask_code": "\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.hashCode();\n }\n return mMissingVolumeRecord.hashCode();\n }\n\n @Override\n public String toString() {\n if (isVolumeInfo()) {\n return mVolumeInfo.toString();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.toString();\n }\n return mMissingVolumeRecord.toString();\n }\n\n @Override\n public int compareTo(StorageEntry other) {\n if (isDefaultInternalStorage() && !other.isDefaultInternalStorage()) {\n return -1;\n }\n if (!isDefaultInternalStorage() && other.isDefaultInternalStorage()) {\n return 1;\n }\n if (isVolumeInfo() && !other.isVolumeInfo()) {\n return -1;\n }\n if (!isVolumeInfo() && other.isVolumeInfo()) {\n return 1;\n }\n if (isPrivate() && !other.isPrivate()) {\n return -1;\n }\n if (!isPrivate() && other.isPrivate()) {\n return 1;\n }\n if (isMounted() && !other.isMounted()) {\n return -1;\n }\n if (!isMounted() && other.isMounted()) {\n return 1;\n }\n if (!isVolumeRecordMissed() && other.isVolumeRecordMissed()) {\n return -1;\n }\n if (isVolumeRecordMissed() && !other.isVolumeRecordMissed()) {\n return 1;\n }\n if (getDescription() == null) {\n return 1;\n }\n if (other.getDescription() == null) {\n return -1;\n }\n return getDescription().compareTo(other.getDescription());\n }\n\n public static StorageEntry getDefaultInternalStorageEntry(Context context) {\n return new StorageEntry(context, context.getSystemService(StorageManager.class).findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL));\n }\n\n /**\n * If it's a VolumeInfo.\n */\n public boolean isVolumeInfo() {\n return mVolumeInfo != null;\n }\n\n /**\n * If it's an unsupported DiskInfo.\n */\n public boolean isDiskInfoUnsupported() {\n return mUnsupportedDiskInfo != null;\n }\n\n /**\n * If it's a missing VolumeRecord.\n */\n public boolean isVolumeRecordMissed() {\n return mMissingVolumeRecord != null;\n }\n\n /**\n * If it's a default internal storage.\n */\n public boolean isDefaultInternalStorage() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE && TextUtils.equals(mVolumeInfo.getId(), VolumeInfo.ID_PRIVATE_INTERNAL);\n }\n return false;\n }\n\n /**\n * If it's a mounted storage.\n */\n public boolean isMounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED || mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED_READ_ONLY);\n }\n\n /**\n * If it's an unmounted storage.\n */\n public boolean isUnmounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTED);\n }\n\n /**\n * If it's an unmountable storage.\n */\n public boolean isUnmountable() {\n return mVolumeInfo == null ? false : mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTABLE;\n }\n\n /**\n * If it's a private storage.\n */\n public boolean isPrivate() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE;\n }\n\n /**\n * If it's a public storage.\n */\n public boolean isPublic() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PUBLIC;\n }\n\n /**\n * Returns description.\n */\n public String getDescription() {\n if (isVolumeInfo()) {\n return mVolumeInfoDescription;\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getDescription();\n }\n return mMissingVolumeRecord.getNickname();\n }\n\n /**\n * Returns ID.\n */\n public String getId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns disk ID.\n */\n public String getDiskId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getDiskId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return null;\n }\n\n /**\n * Returns fsUuid.\n */\n public String getFsUuid() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getFsUuid();\n }\n if (isDiskInfoUnsupported()) {\n return null;\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns root file if it's a VolumeInfo.\n */\n public File getPath() {\n return mVolumeInfo == null ? null : mVolumeInfo.getPath();\n }\n\n /**\n * Returns VolumeInfo of the StorageEntry.\n */\n public VolumeInfo getVolumeInfo() {\n return mVolumeInfo;\n }\n}\n"} {"task_id": "Java_206", "language": "Java", "task_type": "empty", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/deviceinfo/storage/StorageEntry.java", "mask_start_position": 4571, "mask_end_position": 4571, "canonical_solution": "", "pre_mask_code": "package com.android.settings.deviceinfo.storage;\n\nimport android.annotation.NonNull;\nimport android.content.Context;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.storage.DiskInfo;\nimport android.os.storage.StorageManager;\nimport android.os.storage.VolumeInfo;\nimport android.os.storage.VolumeRecord;\nimport android.text.TextUtils;\nimport com.android.settings.R;\nimport java.io.File;\n\n/**\n * This object contains a {@link VolumeInfo} for a mountable storage or a {@link DiskInfo} for an\n * unsupported disk which is not able to be mounted automatically.\n */\npublic class StorageEntry implements Comparable, Parcelable {\n\n private final VolumeInfo mVolumeInfo;\n\n private final DiskInfo mUnsupportedDiskInfo;\n\n private final VolumeRecord mMissingVolumeRecord;\n\n private final String mVolumeInfoDescription;\n\n public StorageEntry(@NonNull Context context, @NonNull VolumeInfo volumeInfo) {\n mVolumeInfo = volumeInfo;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = null;\n if (isDefaultInternalStorage()) {\n mVolumeInfoDescription = context.getResources().getString(R.string.storage_default_internal_storage);\n } else {\n mVolumeInfoDescription = context.getSystemService(StorageManager.class).getBestVolumeDescription(mVolumeInfo);\n }\n }\n\n public StorageEntry(@NonNull DiskInfo diskInfo) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = diskInfo;\n mMissingVolumeRecord = null;\n mVolumeInfoDescription = null;\n }\n\n public StorageEntry(@NonNull VolumeRecord volumeRecord) {\n mVolumeInfo = null;\n mUnsupportedDiskInfo = null;\n mMissingVolumeRecord = volumeRecord;\n mVolumeInfoDescription = null;\n }\n\n private StorageEntry(Parcel in) {\n mVolumeInfo = in.readParcelable(VolumeInfo.class.getClassLoader());\n mUnsupportedDiskInfo = in.readParcelable(DiskInfo.class.getClassLoader());\n mMissingVolumeRecord = in.readParcelable(VolumeRecord.class.getClassLoader());\n mVolumeInfoDescription = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeParcelable(mVolumeInfo, 0);\n out.writeParcelable(mUnsupportedDiskInfo, 0);\n out.writeParcelable(mMissingVolumeRecord, 0);\n out.writeString(mVolumeInfoDescription);\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n\n public StorageEntry createFromParcel(Parcel in) {\n return new StorageEntry(in);\n }\n\n public StorageEntry[] newArray(int size) {\n return new StorageEntry[size];\n }\n };\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof StorageEntry)) {\n return false;\n }\n final StorageEntry StorageEntry = (StorageEntry) o;\n if (isVolumeInfo()) {\n return mVolumeInfo.equals(StorageEntry.mVolumeInfo);\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.equals(StorageEntry.mUnsupportedDiskInfo);\n }\n return mMissingVolumeRecord.equals(StorageEntry.mMissingVolumeRecord);\n }\n\n @Override\n public int hashCode() {\n if (isVolumeInfo()) {\n return mVolumeInfo.hashCode();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.hashCode();\n }\n return mMissingVolumeRecord.hashCode();\n }\n\n @Override\n public String toString() {\n if (isVolumeInfo()) {\n return mVolumeInfo.toString();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.toString();\n }\n return mMissingVolumeRecord.toString();\n }\n\n @Override\n public int compareTo(StorageEntry other) {\n if (isDefaultInternalStorage() && !other.isDefaultInternalStorage()) {\n return -1;\n }\n if (!isDefaultInternalStorage() && other.isDefaultInternalStorage()) {\n return 1;\n }\n if (isVolumeInfo() && !other.isVolumeInfo()) {\n return -1;\n }\n if (!isVolumeInfo() && other.isVolumeInfo()) {\n return 1;\n }\n if (isPrivate() && !other.isPrivate()) {\n return -1;\n }\n if (!isPrivate() && other.isPrivate()) {\n return 1;\n ", "post_mask_code": " }\n if (isMounted() && !other.isMounted()) {\n return -1;\n }\n if (!isMounted() && other.isMounted()) {\n return 1;\n }\n if (!isVolumeRecordMissed() && other.isVolumeRecordMissed()) {\n return -1;\n }\n if (isVolumeRecordMissed() && !other.isVolumeRecordMissed()) {\n return 1;\n }\n if (getDescription() == null) {\n return 1;\n }\n if (other.getDescription() == null) {\n return -1;\n }\n return getDescription().compareTo(other.getDescription());\n }\n\n public static StorageEntry getDefaultInternalStorageEntry(Context context) {\n return new StorageEntry(context, context.getSystemService(StorageManager.class).findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL));\n }\n\n /**\n * If it's a VolumeInfo.\n */\n public boolean isVolumeInfo() {\n return mVolumeInfo != null;\n }\n\n /**\n * If it's an unsupported DiskInfo.\n */\n public boolean isDiskInfoUnsupported() {\n return mUnsupportedDiskInfo != null;\n }\n\n /**\n * If it's a missing VolumeRecord.\n */\n public boolean isVolumeRecordMissed() {\n return mMissingVolumeRecord != null;\n }\n\n /**\n * If it's a default internal storage.\n */\n public boolean isDefaultInternalStorage() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE && TextUtils.equals(mVolumeInfo.getId(), VolumeInfo.ID_PRIVATE_INTERNAL);\n }\n return false;\n }\n\n /**\n * If it's a mounted storage.\n */\n public boolean isMounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED || mVolumeInfo.getState() == VolumeInfo.STATE_MOUNTED_READ_ONLY);\n }\n\n /**\n * If it's an unmounted storage.\n */\n public boolean isUnmounted() {\n return mVolumeInfo == null ? false : (mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTED);\n }\n\n /**\n * If it's an unmountable storage.\n */\n public boolean isUnmountable() {\n return mVolumeInfo == null ? false : mVolumeInfo.getState() == VolumeInfo.STATE_UNMOUNTABLE;\n }\n\n /**\n * If it's a private storage.\n */\n public boolean isPrivate() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PRIVATE;\n }\n\n /**\n * If it's a public storage.\n */\n public boolean isPublic() {\n return mVolumeInfo == null ? false : mVolumeInfo.getType() == VolumeInfo.TYPE_PUBLIC;\n }\n\n /**\n * Returns description.\n */\n public String getDescription() {\n if (isVolumeInfo()) {\n return mVolumeInfoDescription;\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getDescription();\n }\n return mMissingVolumeRecord.getNickname();\n }\n\n /**\n * Returns ID.\n */\n public String getId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns disk ID.\n */\n public String getDiskId() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getDiskId();\n }\n if (isDiskInfoUnsupported()) {\n return mUnsupportedDiskInfo.getId();\n }\n return null;\n }\n\n /**\n * Returns fsUuid.\n */\n public String getFsUuid() {\n if (isVolumeInfo()) {\n return mVolumeInfo.getFsUuid();\n }\n if (isDiskInfoUnsupported()) {\n return null;\n }\n return mMissingVolumeRecord.getFsUuid();\n }\n\n /**\n * Returns root file if it's a VolumeInfo.\n */\n public File getPath() {\n return mVolumeInfo == null ? null : mVolumeInfo.getPath();\n }\n\n /**\n * Returns VolumeInfo of the StorageEntry.\n */\n public VolumeInfo getVolumeInfo() {\n return mVolumeInfo;\n }\n}\n"} {"task_id": "Java_207", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/module/system/page/SessioncleaningPage.java", "mask_start_position": 1125, "mask_end_position": 1172, "canonical_solution": "@Override\n protected SPageNode getContent() ", "pre_mask_code": "package org.openlowcode.module.system.page;\n\nimport org.openlowcode.module.system.action.SessioncleaningAction;\nimport org.openlowcode.module.system.action.generated.AtgLaunchsearchusersessionAction;\nimport org.openlowcode.module.system.page.generated.AbsSessioncleaningPage;\nimport org.openlowcode.server.graphic.SPageNode;\nimport org.openlowcode.server.graphic.widget.SActionButton;\nimport org.openlowcode.server.graphic.widget.SComponentBand;\nimport org.openlowcode.server.graphic.widget.SIntegerField;\nimport org.openlowcode.server.graphic.widget.SPageText;\n\n/**\n * Page to perform session cleaning\n *\n * @author Open Lowcode\n * SAS\n */\npublic class SessioncleaningPage extends AbsSessioncleaningPage {\n\n /**\n * create the page\n *\n * @param numberofitems\n * @param oldestlog\n */\n public SessioncleaningPage(Integer numberofitems, Integer oldestlog) {\n super(numberofitems, oldestlog);\n }\n\n @Override\n public String generateTitle(Integer numberofitems, Integer oldestlog) {\n return \"Clean Sessions\";\n }\n\n ", "post_mask_code": "{\n SComponentBand mainband = new SComponentBand(SComponentBand.DIRECTION_DOWN, this);\n mainband.addElement(new SPageText(\"Session Log cleaning\", SPageText.TYPE_TITLE, this));\n SIntegerField numberofrecords = new SIntegerField(\"Number of records\", \"RECORDS\", \"\", this.getNumberofitems(), false, this, true, false, false, null);\n mainband.addElement(numberofrecords);\n SIntegerField oldestlog = new SIntegerField(\"Oldest log (days)\", \"OLDESTLOGS\", \"\", this.getOldestlog(), false, this, true, false, false, null);\n mainband.addElement(oldestlog);\n SessioncleaningAction.ActionRef sessioncleaningaction = SessioncleaningAction.get().getActionRef();\n SIntegerField keepdays = new SIntegerField(\"Keep days of history\", \"KEEPDAYS\", \"\", new Integer(31), false, this, false, false, false, sessioncleaningaction);\n mainband.addElement(keepdays);\n sessioncleaningaction.setCleansessionsolderthandays(keepdays.getIntegerInput());\n SActionButton clean = new SActionButton(\"Clean older logs\", sessioncleaningaction, this);\n SComponentBand buttonband = new SComponentBand(SComponentBand.DIRECTION_RIGHT, this);\n buttonband.addElement(clean);\n AtgLaunchsearchusersessionAction.ActionRef searchsessionlogs = AtgLaunchsearchusersessionAction.get().getActionRef();\n buttonband.addElement(new SActionButton(\"Search Session Logs\", searchsessionlogs, this));\n mainband.addElement(buttonband);\n return mainband;\n }\n}\n"} {"task_id": "Java_208", "language": "Java", "task_type": "method_body", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/module/system/page/SessioncleaningPage.java", "mask_start_position": 1079, "mask_end_position": 1119, "canonical_solution": "{\n return \"Clean Sessions\";\n }", "pre_mask_code": "package org.openlowcode.module.system.page;\n\nimport org.openlowcode.module.system.action.SessioncleaningAction;\nimport org.openlowcode.module.system.action.generated.AtgLaunchsearchusersessionAction;\nimport org.openlowcode.module.system.page.generated.AbsSessioncleaningPage;\nimport org.openlowcode.server.graphic.SPageNode;\nimport org.openlowcode.server.graphic.widget.SActionButton;\nimport org.openlowcode.server.graphic.widget.SComponentBand;\nimport org.openlowcode.server.graphic.widget.SIntegerField;\nimport org.openlowcode.server.graphic.widget.SPageText;\n\n/**\n * Page to perform session cleaning\n *\n * @author Open Lowcode\n * SAS\n */\npublic class SessioncleaningPage extends AbsSessioncleaningPage {\n\n /**\n * create the page\n *\n * @param numberofitems\n * @param oldestlog\n */\n public SessioncleaningPage(Integer numberofitems, Integer oldestlog) {\n super(numberofitems, oldestlog);\n }\n\n @Override\n public String generateTitle(Integer numberofitems, Integer oldestlog) ", "post_mask_code": "\n\n @Override\n protected SPageNode getContent() {\n SComponentBand mainband = new SComponentBand(SComponentBand.DIRECTION_DOWN, this);\n mainband.addElement(new SPageText(\"Session Log cleaning\", SPageText.TYPE_TITLE, this));\n SIntegerField numberofrecords = new SIntegerField(\"Number of records\", \"RECORDS\", \"\", this.getNumberofitems(), false, this, true, false, false, null);\n mainband.addElement(numberofrecords);\n SIntegerField oldestlog = new SIntegerField(\"Oldest log (days)\", \"OLDESTLOGS\", \"\", this.getOldestlog(), false, this, true, false, false, null);\n mainband.addElement(oldestlog);\n SessioncleaningAction.ActionRef sessioncleaningaction = SessioncleaningAction.get().getActionRef();\n SIntegerField keepdays = new SIntegerField(\"Keep days of history\", \"KEEPDAYS\", \"\", new Integer(31), false, this, false, false, false, sessioncleaningaction);\n mainband.addElement(keepdays);\n sessioncleaningaction.setCleansessionsolderthandays(keepdays.getIntegerInput());\n SActionButton clean = new SActionButton(\"Clean older logs\", sessioncleaningaction, this);\n SComponentBand buttonband = new SComponentBand(SComponentBand.DIRECTION_RIGHT, this);\n buttonband.addElement(clean);\n AtgLaunchsearchusersessionAction.ActionRef searchsessionlogs = AtgLaunchsearchusersessionAction.get().getActionRef();\n buttonband.addElement(new SActionButton(\"Search Session Logs\", searchsessionlogs, this));\n mainband.addElement(buttonband);\n return mainband;\n }\n}\n"} {"task_id": "Java_209", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/module/system/page/SessioncleaningPage.java", "mask_start_position": 1173, "mask_end_position": 1757, "canonical_solution": "\n SComponentBand mainband = new SComponentBand(SComponentBand.DIRECTION_DOWN, this);\n mainband.addElement(new SPageText(\"Session Log cleaning\", SPageText.TYPE_TITLE, this));\n SIntegerField numberofrecords = new SIntegerField(\"Number of records\", \"RECORDS\", \"\", this.getNumberofitems(), false, this, true, false, false, null);\n mainband.addElement(numberofrecords);\n SIntegerField oldestlog = new SIntegerField(\"Oldest log (days)\", \"OLDESTLOGS\", \"\", this.getOldestlog(), false, this, true, false, false, null);\n mainband.addElement(oldestlog);", "pre_mask_code": "package org.openlowcode.module.system.page;\n\nimport org.openlowcode.module.system.action.SessioncleaningAction;\nimport org.openlowcode.module.system.action.generated.AtgLaunchsearchusersessionAction;\nimport org.openlowcode.module.system.page.generated.AbsSessioncleaningPage;\nimport org.openlowcode.server.graphic.SPageNode;\nimport org.openlowcode.server.graphic.widget.SActionButton;\nimport org.openlowcode.server.graphic.widget.SComponentBand;\nimport org.openlowcode.server.graphic.widget.SIntegerField;\nimport org.openlowcode.server.graphic.widget.SPageText;\n\n/**\n * Page to perform session cleaning\n *\n * @author Open Lowcode\n * SAS\n */\npublic class SessioncleaningPage extends AbsSessioncleaningPage {\n\n /**\n * create the page\n *\n * @param numberofitems\n * @param oldestlog\n */\n public SessioncleaningPage(Integer numberofitems, Integer oldestlog) {\n super(numberofitems, oldestlog);\n }\n\n @Override\n public String generateTitle(Integer numberofitems, Integer oldestlog) {\n return \"Clean Sessions\";\n }\n\n @Override\n protected SPageNode getContent() {", "post_mask_code": "\n SessioncleaningAction.ActionRef sessioncleaningaction = SessioncleaningAction.get().getActionRef();\n SIntegerField keepdays = new SIntegerField(\"Keep days of history\", \"KEEPDAYS\", \"\", new Integer(31), false, this, false, false, false, sessioncleaningaction);\n mainband.addElement(keepdays);\n sessioncleaningaction.setCleansessionsolderthandays(keepdays.getIntegerInput());\n SActionButton clean = new SActionButton(\"Clean older logs\", sessioncleaningaction, this);\n SComponentBand buttonband = new SComponentBand(SComponentBand.DIRECTION_RIGHT, this);\n buttonband.addElement(clean);\n AtgLaunchsearchusersessionAction.ActionRef searchsessionlogs = AtgLaunchsearchusersessionAction.get().getActionRef();\n buttonband.addElement(new SActionButton(\"Search Session Logs\", searchsessionlogs, this));\n mainband.addElement(buttonband);\n return mainband;\n }\n}\n"} {"task_id": "Java_210", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/module/system/page/SessioncleaningPage.java", "mask_start_position": 1766, "mask_end_position": 2351, "canonical_solution": "SessioncleaningAction.ActionRef sessioncleaningaction = SessioncleaningAction.get().getActionRef();\n SIntegerField keepdays = new SIntegerField(\"Keep days of history\", \"KEEPDAYS\", \"\", new Integer(31), false, this, false, false, false, sessioncleaningaction);\n mainband.addElement(keepdays);\n sessioncleaningaction.setCleansessionsolderthandays(keepdays.getIntegerInput());\n SActionButton clean = new SActionButton(\"Clean older logs\", sessioncleaningaction, this);\n SComponentBand buttonband = new SComponentBand(SComponentBand.DIRECTION_RIGHT, this);", "pre_mask_code": "package org.openlowcode.module.system.page;\n\nimport org.openlowcode.module.system.action.SessioncleaningAction;\nimport org.openlowcode.module.system.action.generated.AtgLaunchsearchusersessionAction;\nimport org.openlowcode.module.system.page.generated.AbsSessioncleaningPage;\nimport org.openlowcode.server.graphic.SPageNode;\nimport org.openlowcode.server.graphic.widget.SActionButton;\nimport org.openlowcode.server.graphic.widget.SComponentBand;\nimport org.openlowcode.server.graphic.widget.SIntegerField;\nimport org.openlowcode.server.graphic.widget.SPageText;\n\n/**\n * Page to perform session cleaning\n *\n * @author Open Lowcode\n * SAS\n */\npublic class SessioncleaningPage extends AbsSessioncleaningPage {\n\n /**\n * create the page\n *\n * @param numberofitems\n * @param oldestlog\n */\n public SessioncleaningPage(Integer numberofitems, Integer oldestlog) {\n super(numberofitems, oldestlog);\n }\n\n @Override\n public String generateTitle(Integer numberofitems, Integer oldestlog) {\n return \"Clean Sessions\";\n }\n\n @Override\n protected SPageNode getContent() {\n SComponentBand mainband = new SComponentBand(SComponentBand.DIRECTION_DOWN, this);\n mainband.addElement(new SPageText(\"Session Log cleaning\", SPageText.TYPE_TITLE, this));\n SIntegerField numberofrecords = new SIntegerField(\"Number of records\", \"RECORDS\", \"\", this.getNumberofitems(), false, this, true, false, false, null);\n mainband.addElement(numberofrecords);\n SIntegerField oldestlog = new SIntegerField(\"Oldest log (days)\", \"OLDESTLOGS\", \"\", this.getOldestlog(), false, this, true, false, false, null);\n mainband.addElement(oldestlog);\n ", "post_mask_code": "\n buttonband.addElement(clean);\n AtgLaunchsearchusersessionAction.ActionRef searchsessionlogs = AtgLaunchsearchusersessionAction.get().getActionRef();\n buttonband.addElement(new SActionButton(\"Search Session Logs\", searchsessionlogs, this));\n mainband.addElement(buttonband);\n return mainband;\n }\n}\n"} {"task_id": "Java_211", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/module/system/page/SessioncleaningPage.java", "mask_start_position": 2360, "mask_end_position": 2685, "canonical_solution": "buttonband.addElement(clean);\n AtgLaunchsearchusersessionAction.ActionRef searchsessionlogs = AtgLaunchsearchusersessionAction.get().getActionRef();\n buttonband.addElement(new SActionButton(\"Search Session Logs\", searchsessionlogs, this));\n mainband.addElement(buttonband);\n return mainband;\n }", "pre_mask_code": "package org.openlowcode.module.system.page;\n\nimport org.openlowcode.module.system.action.SessioncleaningAction;\nimport org.openlowcode.module.system.action.generated.AtgLaunchsearchusersessionAction;\nimport org.openlowcode.module.system.page.generated.AbsSessioncleaningPage;\nimport org.openlowcode.server.graphic.SPageNode;\nimport org.openlowcode.server.graphic.widget.SActionButton;\nimport org.openlowcode.server.graphic.widget.SComponentBand;\nimport org.openlowcode.server.graphic.widget.SIntegerField;\nimport org.openlowcode.server.graphic.widget.SPageText;\n\n/**\n * Page to perform session cleaning\n *\n * @author Open Lowcode\n * SAS\n */\npublic class SessioncleaningPage extends AbsSessioncleaningPage {\n\n /**\n * create the page\n *\n * @param numberofitems\n * @param oldestlog\n */\n public SessioncleaningPage(Integer numberofitems, Integer oldestlog) {\n super(numberofitems, oldestlog);\n }\n\n @Override\n public String generateTitle(Integer numberofitems, Integer oldestlog) {\n return \"Clean Sessions\";\n }\n\n @Override\n protected SPageNode getContent() {\n SComponentBand mainband = new SComponentBand(SComponentBand.DIRECTION_DOWN, this);\n mainband.addElement(new SPageText(\"Session Log cleaning\", SPageText.TYPE_TITLE, this));\n SIntegerField numberofrecords = new SIntegerField(\"Number of records\", \"RECORDS\", \"\", this.getNumberofitems(), false, this, true, false, false, null);\n mainband.addElement(numberofrecords);\n SIntegerField oldestlog = new SIntegerField(\"Oldest log (days)\", \"OLDESTLOGS\", \"\", this.getOldestlog(), false, this, true, false, false, null);\n mainband.addElement(oldestlog);\n SessioncleaningAction.ActionRef sessioncleaningaction = SessioncleaningAction.get().getActionRef();\n SIntegerField keepdays = new SIntegerField(\"Keep days of history\", \"KEEPDAYS\", \"\", new Integer(31), false, this, false, false, false, sessioncleaningaction);\n mainband.addElement(keepdays);\n sessioncleaningaction.setCleansessionsolderthandays(keepdays.getIntegerInput());\n SActionButton clean = new SActionButton(\"Clean older logs\", sessioncleaningaction, this);\n SComponentBand buttonband = new SComponentBand(SComponentBand.DIRECTION_RIGHT, this);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_212", "language": "Java", "task_type": "single_line", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/module/system/page/SessioncleaningPage.java", "mask_start_position": 1093, "mask_end_position": 1113, "canonical_solution": "rn \"Clean Sessions\";", "pre_mask_code": "package org.openlowcode.module.system.page;\n\nimport org.openlowcode.module.system.action.SessioncleaningAction;\nimport org.openlowcode.module.system.action.generated.AtgLaunchsearchusersessionAction;\nimport org.openlowcode.module.system.page.generated.AbsSessioncleaningPage;\nimport org.openlowcode.server.graphic.SPageNode;\nimport org.openlowcode.server.graphic.widget.SActionButton;\nimport org.openlowcode.server.graphic.widget.SComponentBand;\nimport org.openlowcode.server.graphic.widget.SIntegerField;\nimport org.openlowcode.server.graphic.widget.SPageText;\n\n/**\n * Page to perform session cleaning\n *\n * @author Open Lowcode\n * SAS\n */\npublic class SessioncleaningPage extends AbsSessioncleaningPage {\n\n /**\n * create the page\n *\n * @param numberofitems\n * @param oldestlog\n */\n public SessioncleaningPage(Integer numberofitems, Integer oldestlog) {\n super(numberofitems, oldestlog);\n }\n\n @Override\n public String generateTitle(Integer numberofitems, Integer oldestlog) {\n retu", "post_mask_code": "\n }\n\n @Override\n protected SPageNode getContent() {\n SComponentBand mainband = new SComponentBand(SComponentBand.DIRECTION_DOWN, this);\n mainband.addElement(new SPageText(\"Session Log cleaning\", SPageText.TYPE_TITLE, this));\n SIntegerField numberofrecords = new SIntegerField(\"Number of records\", \"RECORDS\", \"\", this.getNumberofitems(), false, this, true, false, false, null);\n mainband.addElement(numberofrecords);\n SIntegerField oldestlog = new SIntegerField(\"Oldest log (days)\", \"OLDESTLOGS\", \"\", this.getOldestlog(), false, this, true, false, false, null);\n mainband.addElement(oldestlog);\n SessioncleaningAction.ActionRef sessioncleaningaction = SessioncleaningAction.get().getActionRef();\n SIntegerField keepdays = new SIntegerField(\"Keep days of history\", \"KEEPDAYS\", \"\", new Integer(31), false, this, false, false, false, sessioncleaningaction);\n mainband.addElement(keepdays);\n sessioncleaningaction.setCleansessionsolderthandays(keepdays.getIntegerInput());\n SActionButton clean = new SActionButton(\"Clean older logs\", sessioncleaningaction, this);\n SComponentBand buttonband = new SComponentBand(SComponentBand.DIRECTION_RIGHT, this);\n buttonband.addElement(clean);\n AtgLaunchsearchusersessionAction.ActionRef searchsessionlogs = AtgLaunchsearchusersessionAction.get().getActionRef();\n buttonband.addElement(new SActionButton(\"Search Session Logs\", searchsessionlogs, this));\n mainband.addElement(buttonband);\n return mainband;\n }\n}\n"} {"task_id": "Java_213", "language": "Java", "task_type": "empty", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/module/system/page/SessioncleaningPage.java", "mask_start_position": 1803, "mask_end_position": 1803, "canonical_solution": "", "pre_mask_code": "package org.openlowcode.module.system.page;\n\nimport org.openlowcode.module.system.action.SessioncleaningAction;\nimport org.openlowcode.module.system.action.generated.AtgLaunchsearchusersessionAction;\nimport org.openlowcode.module.system.page.generated.AbsSessioncleaningPage;\nimport org.openlowcode.server.graphic.SPageNode;\nimport org.openlowcode.server.graphic.widget.SActionButton;\nimport org.openlowcode.server.graphic.widget.SComponentBand;\nimport org.openlowcode.server.graphic.widget.SIntegerField;\nimport org.openlowcode.server.graphic.widget.SPageText;\n\n/**\n * Page to perform session cleaning\n *\n * @author Open Lowcode\n * SAS\n */\npublic class SessioncleaningPage extends AbsSessioncleaningPage {\n\n /**\n * create the page\n *\n * @param numberofitems\n * @param oldestlog\n */\n public SessioncleaningPage(Integer numberofitems, Integer oldestlog) {\n super(numberofitems, oldestlog);\n }\n\n @Override\n public String generateTitle(Integer numberofitems, Integer oldestlog) {\n return \"Clean Sessions\";\n }\n\n @Override\n protected SPageNode getContent() {\n SComponentBand mainband = new SComponentBand(SComponentBand.DIRECTION_DOWN, this);\n mainband.addElement(new SPageText(\"Session Log cleaning\", SPageText.TYPE_TITLE, this));\n SIntegerField numberofrecords = new SIntegerField(\"Number of records\", \"RECORDS\", \"\", this.getNumberofitems(), false, this, true, false, false, null);\n mainband.addElement(numberofrecords);\n SIntegerField oldestlog = new SIntegerField(\"Oldest log (days)\", \"OLDESTLOGS\", \"\", this.getOldestlog(), false, this, true, false, false, null);\n mainband.addElement(oldestlog);\n SessioncleaningAction.ActionRef sessi", "post_mask_code": "oncleaningaction = SessioncleaningAction.get().getActionRef();\n SIntegerField keepdays = new SIntegerField(\"Keep days of history\", \"KEEPDAYS\", \"\", new Integer(31), false, this, false, false, false, sessioncleaningaction);\n mainband.addElement(keepdays);\n sessioncleaningaction.setCleansessionsolderthandays(keepdays.getIntegerInput());\n SActionButton clean = new SActionButton(\"Clean older logs\", sessioncleaningaction, this);\n SComponentBand buttonband = new SComponentBand(SComponentBand.DIRECTION_RIGHT, this);\n buttonband.addElement(clean);\n AtgLaunchsearchusersessionAction.ActionRef searchsessionlogs = AtgLaunchsearchusersessionAction.get().getActionRef();\n buttonband.addElement(new SActionButton(\"Search Session Logs\", searchsessionlogs, this));\n mainband.addElement(buttonband);\n return mainband;\n }\n}\n"} {"task_id": "Java_214", "language": "Java", "task_type": "empty", "source_file": "java/github/jboss-switchyard/core/validate/src/main/java/org/switchyard/validate/internal/DuplicateValidatorException.java", "mask_start_position": 881, "mask_end_position": 881, "canonical_solution": "", "pre_mask_code": "package org.switchyard.validate.internal;\n\nimport org.switchyard.SwitchYardException;\n\n/**\n * A DuplicateValidatorException is thrown by SwitchYard when a duplicate validator\n * is trying to be registered for a 'name' type for which there already exists\n * a validator in the validator registry.\n *\n * @author Tomohisa Igarashi\n */\npublic class DuplicateValidatorException extends SwitchYardException {\n\n /**\n * Serial version unique id.\n */\n private static final long serialVersionUID = -8937972965502786027L;\n\n /**\n * Public constructor.\n * @param message Exception message.\n */\n public DuplicateValidatorException(final String message) {\n super(message);\n }\n\n /**\n * Public constructor.\n * @param message Exception message.\n * @param cause Throwable cause.\n */\n public Dupl", "post_mask_code": "icateValidatorException(final String message, final Throwable cause) {\n super(message, cause);\n }\n}\n"} {"task_id": "Java_215", "language": "Java", "task_type": "method_signature", "source_file": "java/github/wangpeiyuan/DanmuDemo/app/src/main/java/com/wpy/danmudemo/utils/DpOrSp2PxUtil.java", "mask_start_position": 182, "mask_end_position": 248, "canonical_solution": "public static int dp2pxConvertInt(Context context, float dpValue) ", "pre_mask_code": "package com.wpy.danmudemo.utils;\n\nimport android.content.Context;\nimport android.util.TypedValue;\n\n/**\n * 像素转换\n * Created by feiyang on 16/3/2.\n */\npublic class DpOrSp2PxUtil {\n\n ", "post_mask_code": "{\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());\n }\n\n public static int sp2pxConvertInt(Context context, float spValue) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics());\n }\n\n public static float dp2px(Context context, float dpValue) {\n return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());\n }\n\n public static float sp2px(Context context, float spValue) {\n return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics());\n }\n}\n"} {"task_id": "Java_216", "language": "Java", "task_type": "method_body", "source_file": "java/github/wangpeiyuan/DanmuDemo/app/src/main/java/com/wpy/danmudemo/utils/DpOrSp2PxUtil.java", "mask_start_position": 248, "mask_end_position": 385, "canonical_solution": "{\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());\n }", "pre_mask_code": "package com.wpy.danmudemo.utils;\n\nimport android.content.Context;\nimport android.util.TypedValue;\n\n/**\n * 像素转换\n * Created by feiyang on 16/3/2.\n */\npublic class DpOrSp2PxUtil {\n\n public static int dp2pxConvertInt(Context context, float dpValue) ", "post_mask_code": "\n\n public static int sp2pxConvertInt(Context context, float spValue) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics());\n }\n\n public static float dp2px(Context context, float dpValue) {\n return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());\n }\n\n public static float sp2px(Context context, float spValue) {\n return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics());\n }\n}\n"} {"task_id": "Java_217", "language": "Java", "task_type": "single_line", "source_file": "java/github/wangpeiyuan/DanmuDemo/app/src/main/java/com/wpy/danmudemo/utils/DpOrSp2PxUtil.java", "mask_start_position": 367, "mask_end_position": 379, "canonical_solution": "yMetrics());", "pre_mask_code": "package com.wpy.danmudemo.utils;\n\nimport android.content.Context;\nimport android.util.TypedValue;\n\n/**\n * 像素转换\n * Created by feiyang on 16/3/2.\n */\npublic class DpOrSp2PxUtil {\n\n public static int dp2pxConvertInt(Context context, float dpValue) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDispla", "post_mask_code": "\n }\n\n public static int sp2pxConvertInt(Context context, float spValue) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics());\n }\n\n public static float dp2px(Context context, float dpValue) {\n return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());\n }\n\n public static float sp2px(Context context, float spValue) {\n return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics());\n }\n}\n"} {"task_id": "Java_218", "language": "Java", "task_type": "empty", "source_file": "java/github/wangpeiyuan/DanmuDemo/app/src/main/java/com/wpy/danmudemo/utils/DpOrSp2PxUtil.java", "mask_start_position": 804, "mask_end_position": 804, "canonical_solution": "", "pre_mask_code": "package com.wpy.danmudemo.utils;\n\nimport android.content.Context;\nimport android.util.TypedValue;\n\n/**\n * 像素转换\n * Created by feiyang on 16/3/2.\n */\npublic class DpOrSp2PxUtil {\n\n public static int dp2pxConvertInt(Context context, float dpValue) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());\n }\n\n public static int sp2pxConvertInt(Context context, float spValue) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics());\n }\n\n public static float dp2px(Context context, float dpValue) {\n return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());\n }\n\n public sta", "post_mask_code": "tic float sp2px(Context context, float spValue) {\n return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics());\n }\n}\n"} {"task_id": "Java_219", "language": "Java", "task_type": "empty", "source_file": "java/github/FlowCI/flow-core-x/core/src/main/java/com/flowci/core/secret/domain/KubeConfigSecret.java", "mask_start_position": 108, "mask_end_position": 108, "canonical_solution": "", "pre_mask_code": "package com.flowci.core.secret.domain;\n\nimport com.flowci.domain.SecretField;\nimport lombok.Getter;\nimport l", "post_mask_code": "ombok.Setter;\nimport org.springframework.data.mongodb.core.mapping.Document;\n\n@Getter\n@Setter\n@Document(collection = \"secret\")\npublic class KubeConfigSecret extends Secret {\n\n private SecretField content;\n\n public KubeConfigSecret() {\n setCategory(Category.KUBE_CONFIG);\n }\n}\n"} {"task_id": "Java_220", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SonarSonic/DrawingBotV3/src/main/java/drawingbot/image/PixelDataLuminance.java", "mask_start_position": 552, "mask_end_position": 599, "canonical_solution": "@Override\n public int getARGB(int x, int y) ", "pre_mask_code": "package drawingbot.image;\n\n/**\n * an implementation of {@link drawingbot.api.IPixelData} optimised for quick access to perceived luminance values and the cached average\n */\n// TODO ISSUE WITH LUMINANCE VALUES?\npublic class PixelDataLuminance extends PixelDataAbstract {\n\n public RawData luminance;\n\n private final float[] hsbCache = new float[3];\n\n private final int[] argbCache = new int[4];\n\n public PixelDataLuminance(int width, int height) {\n super(width, height);\n this.luminance = new RawData(width, height);\n }\n\n ", "post_mask_code": "{\n int g = luminance.getData(x, y);\n return ImageTools.getARGB(255, g, g, g);\n }\n\n @Override\n public void setARGB(int x, int y, int argb) {\n ImageTools.getColourIntsFromARGB(argb, argbCache);\n luminance.setData(x, y, ImageTools.getPerceivedLuminanceFromRGB(argbCache[1], argbCache[2], argbCache[3]));\n }\n\n @Override\n public void setARGB(int x, int y, int a, int r, int g, int b) {\n luminance.setData(x, y, ImageTools.getPerceivedLuminanceFromRGB(r, g, b));\n }\n\n @Override\n public int getChannel(int channel, int x, int y) {\n return luminance.getData(x, y);\n }\n\n @Override\n public void setChannel(int channel, int x, int y, int value) {\n luminance.setData(x, y, value);\n }\n\n @Override\n public void adjustChannel(int channel, int x, int y, int value) {\n luminance.adjustData(x, y, value);\n }\n\n @Override\n public double getAverageChannel(int channel) {\n return luminance.getAverage();\n }\n\n @Override\n public int getHSB(int type, int x, int y) {\n return 0;\n }\n\n @Override\n public void setHSB(int type, int x, int y, int value) {\n }\n\n @Override\n public void adjustHSB(int type, int x, int y, int value) {\n }\n\n @Override\n public double getAverageHSB(int type) {\n return 0;\n }\n\n @Override\n public int getLuminance(int x, int y) {\n return luminance.getData(x, y);\n }\n\n @Override\n public void setLuminance(int x, int y, int lum) {\n luminance.setData(x, y, lum);\n }\n\n @Override\n public void adjustLuminance(int x, int y, int lum) {\n luminance.adjustData(x, y, lum);\n }\n\n @Override\n public double getAverageLuminance() {\n return luminance.getAverage();\n }\n}\n"} {"task_id": "Java_221", "language": "Java", "task_type": "method_body", "source_file": "java/github/SonarSonic/DrawingBotV3/src/main/java/drawingbot/image/PixelDataLuminance.java", "mask_start_position": 599, "mask_end_position": 696, "canonical_solution": "{\n int g = luminance.getData(x, y);\n return ImageTools.getARGB(255, g, g, g);\n }", "pre_mask_code": "package drawingbot.image;\n\n/**\n * an implementation of {@link drawingbot.api.IPixelData} optimised for quick access to perceived luminance values and the cached average\n */\n// TODO ISSUE WITH LUMINANCE VALUES?\npublic class PixelDataLuminance extends PixelDataAbstract {\n\n public RawData luminance;\n\n private final float[] hsbCache = new float[3];\n\n private final int[] argbCache = new int[4];\n\n public PixelDataLuminance(int width, int height) {\n super(width, height);\n this.luminance = new RawData(width, height);\n }\n\n @Override\n public int getARGB(int x, int y) ", "post_mask_code": "\n\n @Override\n public void setARGB(int x, int y, int argb) {\n ImageTools.getColourIntsFromARGB(argb, argbCache);\n luminance.setData(x, y, ImageTools.getPerceivedLuminanceFromRGB(argbCache[1], argbCache[2], argbCache[3]));\n }\n\n @Override\n public void setARGB(int x, int y, int a, int r, int g, int b) {\n luminance.setData(x, y, ImageTools.getPerceivedLuminanceFromRGB(r, g, b));\n }\n\n @Override\n public int getChannel(int channel, int x, int y) {\n return luminance.getData(x, y);\n }\n\n @Override\n public void setChannel(int channel, int x, int y, int value) {\n luminance.setData(x, y, value);\n }\n\n @Override\n public void adjustChannel(int channel, int x, int y, int value) {\n luminance.adjustData(x, y, value);\n }\n\n @Override\n public double getAverageChannel(int channel) {\n return luminance.getAverage();\n }\n\n @Override\n public int getHSB(int type, int x, int y) {\n return 0;\n }\n\n @Override\n public void setHSB(int type, int x, int y, int value) {\n }\n\n @Override\n public void adjustHSB(int type, int x, int y, int value) {\n }\n\n @Override\n public double getAverageHSB(int type) {\n return 0;\n }\n\n @Override\n public int getLuminance(int x, int y) {\n return luminance.getData(x, y);\n }\n\n @Override\n public void setLuminance(int x, int y, int lum) {\n luminance.setData(x, y, lum);\n }\n\n @Override\n public void adjustLuminance(int x, int y, int lum) {\n luminance.adjustData(x, y, lum);\n }\n\n @Override\n public double getAverageLuminance() {\n return luminance.getAverage();\n }\n}\n"} {"task_id": "Java_222", "language": "Java", "task_type": "single_line", "source_file": "java/github/SonarSonic/DrawingBotV3/src/main/java/drawingbot/image/PixelDataLuminance.java", "mask_start_position": 1676, "mask_end_position": 1684, "canonical_solution": "eturn 0;", "pre_mask_code": "package drawingbot.image;\n\n/**\n * an implementation of {@link drawingbot.api.IPixelData} optimised for quick access to perceived luminance values and the cached average\n */\n// TODO ISSUE WITH LUMINANCE VALUES?\npublic class PixelDataLuminance extends PixelDataAbstract {\n\n public RawData luminance;\n\n private final float[] hsbCache = new float[3];\n\n private final int[] argbCache = new int[4];\n\n public PixelDataLuminance(int width, int height) {\n super(width, height);\n this.luminance = new RawData(width, height);\n }\n\n @Override\n public int getARGB(int x, int y) {\n int g = luminance.getData(x, y);\n return ImageTools.getARGB(255, g, g, g);\n }\n\n @Override\n public void setARGB(int x, int y, int argb) {\n ImageTools.getColourIntsFromARGB(argb, argbCache);\n luminance.setData(x, y, ImageTools.getPerceivedLuminanceFromRGB(argbCache[1], argbCache[2], argbCache[3]));\n }\n\n @Override\n public void setARGB(int x, int y, int a, int r, int g, int b) {\n luminance.setData(x, y, ImageTools.getPerceivedLuminanceFromRGB(r, g, b));\n }\n\n @Override\n public int getChannel(int channel, int x, int y) {\n return luminance.getData(x, y);\n }\n\n @Override\n public void setChannel(int channel, int x, int y, int value) {\n luminance.setData(x, y, value);\n }\n\n @Override\n public void adjustChannel(int channel, int x, int y, int value) {\n luminance.adjustData(x, y, value);\n }\n\n @Override\n public double getAverageChannel(int channel) {\n return luminance.getAverage();\n }\n\n @Override\n public int getHSB(int type, int x, int y) {\n r", "post_mask_code": "\n }\n\n @Override\n public void setHSB(int type, int x, int y, int value) {\n }\n\n @Override\n public void adjustHSB(int type, int x, int y, int value) {\n }\n\n @Override\n public double getAverageHSB(int type) {\n return 0;\n }\n\n @Override\n public int getLuminance(int x, int y) {\n return luminance.getData(x, y);\n }\n\n @Override\n public void setLuminance(int x, int y, int lum) {\n luminance.setData(x, y, lum);\n }\n\n @Override\n public void adjustLuminance(int x, int y, int lum) {\n luminance.adjustData(x, y, lum);\n }\n\n @Override\n public double getAverageLuminance() {\n return luminance.getAverage();\n }\n}\n"} {"task_id": "Java_223", "language": "Java", "task_type": "empty", "source_file": "java/github/SonarSonic/DrawingBotV3/src/main/java/drawingbot/image/PixelDataLuminance.java", "mask_start_position": 324, "mask_end_position": 324, "canonical_solution": "", "pre_mask_code": "package drawingbot.image;\n\n/**\n * an implementation of {@link drawingbot.api.IPixelData} optimised for quick access to perceived luminance values and the cached average\n */\n// TODO ISSUE WITH LUMINANCE VALUES?\npublic class PixelDataLuminance extends PixelDataAbstract {\n\n public RawData luminance;\n\n private final floa", "post_mask_code": "t[] hsbCache = new float[3];\n\n private final int[] argbCache = new int[4];\n\n public PixelDataLuminance(int width, int height) {\n super(width, height);\n this.luminance = new RawData(width, height);\n }\n\n @Override\n public int getARGB(int x, int y) {\n int g = luminance.getData(x, y);\n return ImageTools.getARGB(255, g, g, g);\n }\n\n @Override\n public void setARGB(int x, int y, int argb) {\n ImageTools.getColourIntsFromARGB(argb, argbCache);\n luminance.setData(x, y, ImageTools.getPerceivedLuminanceFromRGB(argbCache[1], argbCache[2], argbCache[3]));\n }\n\n @Override\n public void setARGB(int x, int y, int a, int r, int g, int b) {\n luminance.setData(x, y, ImageTools.getPerceivedLuminanceFromRGB(r, g, b));\n }\n\n @Override\n public int getChannel(int channel, int x, int y) {\n return luminance.getData(x, y);\n }\n\n @Override\n public void setChannel(int channel, int x, int y, int value) {\n luminance.setData(x, y, value);\n }\n\n @Override\n public void adjustChannel(int channel, int x, int y, int value) {\n luminance.adjustData(x, y, value);\n }\n\n @Override\n public double getAverageChannel(int channel) {\n return luminance.getAverage();\n }\n\n @Override\n public int getHSB(int type, int x, int y) {\n return 0;\n }\n\n @Override\n public void setHSB(int type, int x, int y, int value) {\n }\n\n @Override\n public void adjustHSB(int type, int x, int y, int value) {\n }\n\n @Override\n public double getAverageHSB(int type) {\n return 0;\n }\n\n @Override\n public int getLuminance(int x, int y) {\n return luminance.getData(x, y);\n }\n\n @Override\n public void setLuminance(int x, int y, int lum) {\n luminance.setData(x, y, lum);\n }\n\n @Override\n public void adjustLuminance(int x, int y, int lum) {\n luminance.adjustData(x, y, lum);\n }\n\n @Override\n public double getAverageLuminance() {\n return luminance.getAverage();\n }\n}\n"} {"task_id": "Java_224", "language": "Java", "task_type": "method_signature", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/as/src/main/java/com/huaweicloud/sdk/as/v1/model/ShowApiVersionResponse.java", "mask_start_position": 1451, "mask_end_position": 1487, "canonical_solution": "@Override\n public int hashCode() ", "pre_mask_code": "package com.huaweicloud.sdk.as.v1.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.huaweicloud.sdk.core.SdkResponse;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * Response Object\n */\npublic class ShowApiVersionResponse extends SdkResponse {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"version\")\n private VersionInfo version;\n\n public ShowApiVersionResponse withVersion(VersionInfo version) {\n this.version = version;\n return this;\n }\n\n public ShowApiVersionResponse withVersion(Consumer versionSetter) {\n if (this.version == null) {\n this.version = new VersionInfo();\n versionSetter.accept(this.version);\n }\n return this;\n }\n\n /**\n * Get version\n *\n * @return version\n */\n public VersionInfo getVersion() {\n return version;\n }\n\n public void setVersion(VersionInfo version) {\n this.version = version;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ShowApiVersionResponse showApiVersionResponse = (ShowApiVersionResponse) o;\n return Objects.equals(this.version, showApiVersionResponse.version);\n }\n\n ", "post_mask_code": "{\n return Objects.hash(version);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ShowApiVersionResponse {\\n\");\n sb.append(\" version: \").append(toIndentedString(version)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_225", "language": "Java", "task_type": "method_body", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/as/src/main/java/com/huaweicloud/sdk/as/v1/model/ShowApiVersionResponse.java", "mask_start_position": 1487, "mask_end_position": 1532, "canonical_solution": "{\n return Objects.hash(version);\n }", "pre_mask_code": "package com.huaweicloud.sdk.as.v1.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.huaweicloud.sdk.core.SdkResponse;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * Response Object\n */\npublic class ShowApiVersionResponse extends SdkResponse {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"version\")\n private VersionInfo version;\n\n public ShowApiVersionResponse withVersion(VersionInfo version) {\n this.version = version;\n return this;\n }\n\n public ShowApiVersionResponse withVersion(Consumer versionSetter) {\n if (this.version == null) {\n this.version = new VersionInfo();\n versionSetter.accept(this.version);\n }\n return this;\n }\n\n /**\n * Get version\n *\n * @return version\n */\n public VersionInfo getVersion() {\n return version;\n }\n\n public void setVersion(VersionInfo version) {\n this.version = version;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ShowApiVersionResponse showApiVersionResponse = (ShowApiVersionResponse) o;\n return Objects.equals(this.version, showApiVersionResponse.version);\n }\n\n @Override\n public int hashCode() ", "post_mask_code": "\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ShowApiVersionResponse {\\n\");\n sb.append(\" version: \").append(toIndentedString(version)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_226", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/as/src/main/java/com/huaweicloud/sdk/as/v1/model/ShowApiVersionResponse.java", "mask_start_position": 1578, "mask_end_position": 1681, "canonical_solution": "\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ShowApiVersionResponse {\\n\");", "pre_mask_code": "package com.huaweicloud.sdk.as.v1.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.huaweicloud.sdk.core.SdkResponse;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * Response Object\n */\npublic class ShowApiVersionResponse extends SdkResponse {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"version\")\n private VersionInfo version;\n\n public ShowApiVersionResponse withVersion(VersionInfo version) {\n this.version = version;\n return this;\n }\n\n public ShowApiVersionResponse withVersion(Consumer versionSetter) {\n if (this.version == null) {\n this.version = new VersionInfo();\n versionSetter.accept(this.version);\n }\n return this;\n }\n\n /**\n * Get version\n *\n * @return version\n */\n public VersionInfo getVersion() {\n return version;\n }\n\n public void setVersion(VersionInfo version) {\n this.version = version;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ShowApiVersionResponse showApiVersionResponse = (ShowApiVersionResponse) o;\n return Objects.equals(this.version, showApiVersionResponse.version);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(version);\n }\n\n @Override\n public String toString() {", "post_mask_code": "\n sb.append(\" version: \").append(toIndentedString(version)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_227", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/as/src/main/java/com/huaweicloud/sdk/as/v1/model/ShowApiVersionResponse.java", "mask_start_position": 1690, "mask_end_position": 1788, "canonical_solution": "sb.append(\" version: \").append(toIndentedString(version)).append(\"\\n\");\n sb.append(\"}\");", "pre_mask_code": "package com.huaweicloud.sdk.as.v1.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.huaweicloud.sdk.core.SdkResponse;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * Response Object\n */\npublic class ShowApiVersionResponse extends SdkResponse {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"version\")\n private VersionInfo version;\n\n public ShowApiVersionResponse withVersion(VersionInfo version) {\n this.version = version;\n return this;\n }\n\n public ShowApiVersionResponse withVersion(Consumer versionSetter) {\n if (this.version == null) {\n this.version = new VersionInfo();\n versionSetter.accept(this.version);\n }\n return this;\n }\n\n /**\n * Get version\n *\n * @return version\n */\n public VersionInfo getVersion() {\n return version;\n }\n\n public void setVersion(VersionInfo version) {\n this.version = version;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ShowApiVersionResponse showApiVersionResponse = (ShowApiVersionResponse) o;\n return Objects.equals(this.version, showApiVersionResponse.version);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(version);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ShowApiVersionResponse {\\n\");\n ", "post_mask_code": "\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_228", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/as/src/main/java/com/huaweicloud/sdk/as/v1/model/ShowApiVersionResponse.java", "mask_start_position": 1797, "mask_end_position": 1824, "canonical_solution": "return sb.toString();\n }", "pre_mask_code": "package com.huaweicloud.sdk.as.v1.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.huaweicloud.sdk.core.SdkResponse;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * Response Object\n */\npublic class ShowApiVersionResponse extends SdkResponse {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"version\")\n private VersionInfo version;\n\n public ShowApiVersionResponse withVersion(VersionInfo version) {\n this.version = version;\n return this;\n }\n\n public ShowApiVersionResponse withVersion(Consumer versionSetter) {\n if (this.version == null) {\n this.version = new VersionInfo();\n versionSetter.accept(this.version);\n }\n return this;\n }\n\n /**\n * Get version\n *\n * @return version\n */\n public VersionInfo getVersion() {\n return version;\n }\n\n public void setVersion(VersionInfo version) {\n this.version = version;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ShowApiVersionResponse showApiVersionResponse = (ShowApiVersionResponse) o;\n return Objects.equals(this.version, showApiVersionResponse.version);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(version);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ShowApiVersionResponse {\\n\");\n sb.append(\" version: \").append(toIndentedString(version)).append(\"\\n\");\n sb.append(\"}\");\n ", "post_mask_code": "\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_229", "language": "Java", "task_type": "single_line", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/as/src/main/java/com/huaweicloud/sdk/as/v1/model/ShowApiVersionResponse.java", "mask_start_position": 1320, "mask_end_position": 1362, "canonical_solution": "sionResponse = (ShowApiVersionResponse) o;", "pre_mask_code": "package com.huaweicloud.sdk.as.v1.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.huaweicloud.sdk.core.SdkResponse;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * Response Object\n */\npublic class ShowApiVersionResponse extends SdkResponse {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"version\")\n private VersionInfo version;\n\n public ShowApiVersionResponse withVersion(VersionInfo version) {\n this.version = version;\n return this;\n }\n\n public ShowApiVersionResponse withVersion(Consumer versionSetter) {\n if (this.version == null) {\n this.version = new VersionInfo();\n versionSetter.accept(this.version);\n }\n return this;\n }\n\n /**\n * Get version\n *\n * @return version\n */\n public VersionInfo getVersion() {\n return version;\n }\n\n public void setVersion(VersionInfo version) {\n this.version = version;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ShowApiVersionResponse showApiVer", "post_mask_code": "\n return Objects.equals(this.version, showApiVersionResponse.version);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(version);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ShowApiVersionResponse {\\n\");\n sb.append(\" version: \").append(toIndentedString(version)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_230", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/as/src/main/java/com/huaweicloud/sdk/as/v1/model/ShowApiVersionResponse.java", "mask_start_position": 912, "mask_end_position": 975, "canonical_solution": "public VersionInfo getVersion() {\n return version;\n }", "pre_mask_code": "package com.huaweicloud.sdk.as.v1.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.huaweicloud.sdk.core.SdkResponse;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * Response Object\n */\npublic class ShowApiVersionResponse extends SdkResponse {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"version\")\n private VersionInfo version;\n\n public ShowApiVersionResponse withVersion(VersionInfo version) {\n this.version = version;\n return this;\n }\n\n public ShowApiVersionResponse withVersion(Consumer versionSetter) {\n if (this.version == null) {\n this.version = new VersionInfo();\n versionSetter.accept(this.version);\n }\n return this;\n }\n\n /**\n * Get version\n *\n * @return version\n */\n ", "post_mask_code": "\n\n public void setVersion(VersionInfo version) {\n this.version = version;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ShowApiVersionResponse showApiVersionResponse = (ShowApiVersionResponse) o;\n return Objects.equals(this.version, showApiVersionResponse.version);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(version);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ShowApiVersionResponse {\\n\");\n sb.append(\" version: \").append(toIndentedString(version)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_231", "language": "Java", "task_type": "if_statement", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/as/src/main/java/com/huaweicloud/sdk/as/v1/model/ShowApiVersionResponse.java", "mask_start_position": 1136, "mask_end_position": 1187, "canonical_solution": "if (this == o) {\n return true;\n }", "pre_mask_code": "package com.huaweicloud.sdk.as.v1.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.huaweicloud.sdk.core.SdkResponse;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * Response Object\n */\npublic class ShowApiVersionResponse extends SdkResponse {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"version\")\n private VersionInfo version;\n\n public ShowApiVersionResponse withVersion(VersionInfo version) {\n this.version = version;\n return this;\n }\n\n public ShowApiVersionResponse withVersion(Consumer versionSetter) {\n if (this.version == null) {\n this.version = new VersionInfo();\n versionSetter.accept(this.version);\n }\n return this;\n }\n\n /**\n * Get version\n *\n * @return version\n */\n public VersionInfo getVersion() {\n return version;\n }\n\n public void setVersion(VersionInfo version) {\n this.version = version;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n ", "post_mask_code": "\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ShowApiVersionResponse showApiVersionResponse = (ShowApiVersionResponse) o;\n return Objects.equals(this.version, showApiVersionResponse.version);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(version);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ShowApiVersionResponse {\\n\");\n sb.append(\" version: \").append(toIndentedString(version)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_232", "language": "Java", "task_type": "empty", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/as/src/main/java/com/huaweicloud/sdk/as/v1/model/ShowApiVersionResponse.java", "mask_start_position": 289, "mask_end_position": 289, "canonical_solution": "", "pre_mask_code": "package com.huaweicloud.sdk.as.v1.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.huaweicloud.sdk.core.SdkResponse;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * Response Object\n */\npubli", "post_mask_code": "c class ShowApiVersionResponse extends SdkResponse {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"version\")\n private VersionInfo version;\n\n public ShowApiVersionResponse withVersion(VersionInfo version) {\n this.version = version;\n return this;\n }\n\n public ShowApiVersionResponse withVersion(Consumer versionSetter) {\n if (this.version == null) {\n this.version = new VersionInfo();\n versionSetter.accept(this.version);\n }\n return this;\n }\n\n /**\n * Get version\n *\n * @return version\n */\n public VersionInfo getVersion() {\n return version;\n }\n\n public void setVersion(VersionInfo version) {\n this.version = version;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ShowApiVersionResponse showApiVersionResponse = (ShowApiVersionResponse) o;\n return Objects.equals(this.version, showApiVersionResponse.version);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(version);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ShowApiVersionResponse {\\n\");\n sb.append(\" version: \").append(toIndentedString(version)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_233", "language": "Java", "task_type": "method_signature", "source_file": "java/github/oracle/oci-java-sdk/bmc-dns/src/main/java/com/oracle/bmc/dns/requests/CreateTsigKeyRequest.java", "mask_start_position": 4087, "mask_end_position": 4196, "canonical_solution": "@com.oracle.bmc.InternalSdk\n public Builder body$(com.oracle.bmc.dns.model.CreateTsigKeyDetails body) ", "pre_mask_code": "package com.oracle.bmc.dns.requests;\n\nimport com.oracle.bmc.dns.model.*;\n\n/**\n * Example: Click here to see how to use CreateTsigKeyRequest.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20180115\")\n@lombok.Builder(builderClassName = \"Builder\", buildMethodName = \"buildWithoutInvocationCallback\", toBuilder = true)\n@lombok.ToString(callSuper = true)\n@lombok.EqualsAndHashCode(callSuper = true)\n@lombok.Getter\npublic class CreateTsigKeyRequest extends com.oracle.bmc.requests.BmcRequest {\n\n /**\n * Details for creating a new TSIG key.\n */\n private com.oracle.bmc.dns.model.CreateTsigKeyDetails createTsigKeyDetails;\n\n /**\n * Unique Oracle-assigned identifier for the request. If you need\n * to contact Oracle about a particular request, please provide\n * the request ID.\n */\n private String opcRequestId;\n\n /**\n * Specifies to operate only on resources that have a matching DNS scope.\n */\n private com.oracle.bmc.dns.model.Scope scope;\n\n /**\n * Alternative accessor for the body parameter.\n * @return body parameter\n */\n @Override\n @com.oracle.bmc.InternalSdk\n public com.oracle.bmc.dns.model.CreateTsigKeyDetails getBody$() {\n return createTsigKeyDetails;\n }\n\n public static class Builder implements com.oracle.bmc.requests.BmcRequest.Builder {\n\n private com.oracle.bmc.util.internal.Consumer invocationCallback = null;\n\n private com.oracle.bmc.retrier.RetryConfiguration retryConfiguration = null;\n\n /**\n * Set the invocation callback for the request to be built.\n * @param invocationCallback the invocation callback to be set for the request\n * @return this builder instance\n */\n public Builder invocationCallback(com.oracle.bmc.util.internal.Consumer invocationCallback) {\n this.invocationCallback = invocationCallback;\n return this;\n }\n\n /**\n * Set the retry configuration for the request to be built.\n * @param retryConfiguration the retry configuration to be used for the request\n * @return this builder instance\n */\n public Builder retryConfiguration(com.oracle.bmc.retrier.RetryConfiguration retryConfiguration) {\n this.retryConfiguration = retryConfiguration;\n return this;\n }\n\n /**\n * Copy method to populate the builder with values from the given instance.\n * @return this builder instance\n */\n public Builder copy(CreateTsigKeyRequest o) {\n createTsigKeyDetails(o.getCreateTsigKeyDetails());\n opcRequestId(o.getOpcRequestId());\n scope(o.getScope());\n invocationCallback(o.getInvocationCallback());\n retryConfiguration(o.getRetryConfiguration());\n return this;\n }\n\n /**\n * Build the instance of CreateTsigKeyRequest as configured by this builder\n *\n * Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,\n * while the method {@link Builder#buildWithoutInvocationCallback} does not.\n *\n * This is the preferred method to build an instance.\n *\n * @return instance of CreateTsigKeyRequest\n */\n public CreateTsigKeyRequest build() {\n CreateTsigKeyRequest request = buildWithoutInvocationCallback();\n request.setInvocationCallback(invocationCallback);\n request.setRetryConfiguration(retryConfiguration);\n return request;\n }\n\n /**\n * Alternative setter for the body parameter.\n * @param body the body parameter\n * @return this builder instance\n */\n ", "post_mask_code": "{\n createTsigKeyDetails(body);\n return this;\n }\n }\n}\n"} {"task_id": "Java_234", "language": "Java", "task_type": "method_body", "source_file": "java/github/oracle/oci-java-sdk/bmc-dns/src/main/java/com/oracle/bmc/dns/requests/CreateTsigKeyRequest.java", "mask_start_position": 3674, "mask_end_position": 3916, "canonical_solution": "{\n CreateTsigKeyRequest request = buildWithoutInvocationCallback();\n request.setInvocationCallback(invocationCallback);\n request.setRetryConfiguration(retryConfiguration);\n return request;\n }", "pre_mask_code": "package com.oracle.bmc.dns.requests;\n\nimport com.oracle.bmc.dns.model.*;\n\n/**\n * Example: Click here to see how to use CreateTsigKeyRequest.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20180115\")\n@lombok.Builder(builderClassName = \"Builder\", buildMethodName = \"buildWithoutInvocationCallback\", toBuilder = true)\n@lombok.ToString(callSuper = true)\n@lombok.EqualsAndHashCode(callSuper = true)\n@lombok.Getter\npublic class CreateTsigKeyRequest extends com.oracle.bmc.requests.BmcRequest {\n\n /**\n * Details for creating a new TSIG key.\n */\n private com.oracle.bmc.dns.model.CreateTsigKeyDetails createTsigKeyDetails;\n\n /**\n * Unique Oracle-assigned identifier for the request. If you need\n * to contact Oracle about a particular request, please provide\n * the request ID.\n */\n private String opcRequestId;\n\n /**\n * Specifies to operate only on resources that have a matching DNS scope.\n */\n private com.oracle.bmc.dns.model.Scope scope;\n\n /**\n * Alternative accessor for the body parameter.\n * @return body parameter\n */\n @Override\n @com.oracle.bmc.InternalSdk\n public com.oracle.bmc.dns.model.CreateTsigKeyDetails getBody$() {\n return createTsigKeyDetails;\n }\n\n public static class Builder implements com.oracle.bmc.requests.BmcRequest.Builder {\n\n private com.oracle.bmc.util.internal.Consumer invocationCallback = null;\n\n private com.oracle.bmc.retrier.RetryConfiguration retryConfiguration = null;\n\n /**\n * Set the invocation callback for the request to be built.\n * @param invocationCallback the invocation callback to be set for the request\n * @return this builder instance\n */\n public Builder invocationCallback(com.oracle.bmc.util.internal.Consumer invocationCallback) {\n this.invocationCallback = invocationCallback;\n return this;\n }\n\n /**\n * Set the retry configuration for the request to be built.\n * @param retryConfiguration the retry configuration to be used for the request\n * @return this builder instance\n */\n public Builder retryConfiguration(com.oracle.bmc.retrier.RetryConfiguration retryConfiguration) {\n this.retryConfiguration = retryConfiguration;\n return this;\n }\n\n /**\n * Copy method to populate the builder with values from the given instance.\n * @return this builder instance\n */\n public Builder copy(CreateTsigKeyRequest o) {\n createTsigKeyDetails(o.getCreateTsigKeyDetails());\n opcRequestId(o.getOpcRequestId());\n scope(o.getScope());\n invocationCallback(o.getInvocationCallback());\n retryConfiguration(o.getRetryConfiguration());\n return this;\n }\n\n /**\n * Build the instance of CreateTsigKeyRequest as configured by this builder\n *\n * Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,\n * while the method {@link Builder#buildWithoutInvocationCallback} does not.\n *\n * This is the preferred method to build an instance.\n *\n * @return instance of CreateTsigKeyRequest\n */\n public CreateTsigKeyRequest build() ", "post_mask_code": "\n\n /**\n * Alternative setter for the body parameter.\n * @param body the body parameter\n * @return this builder instance\n */\n @com.oracle.bmc.InternalSdk\n public Builder body$(com.oracle.bmc.dns.model.CreateTsigKeyDetails body) {\n createTsigKeyDetails(body);\n return this;\n }\n }\n}\n"} {"task_id": "Java_235", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/oracle/oci-java-sdk/bmc-dns/src/main/java/com/oracle/bmc/dns/requests/CreateTsigKeyRequest.java", "mask_start_position": 2856, "mask_end_position": 2966, "canonical_solution": "\n createTsigKeyDetails(o.getCreateTsigKeyDetails());\n opcRequestId(o.getOpcRequestId());", "pre_mask_code": "package com.oracle.bmc.dns.requests;\n\nimport com.oracle.bmc.dns.model.*;\n\n/**\n * Example: Click here to see how to use CreateTsigKeyRequest.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20180115\")\n@lombok.Builder(builderClassName = \"Builder\", buildMethodName = \"buildWithoutInvocationCallback\", toBuilder = true)\n@lombok.ToString(callSuper = true)\n@lombok.EqualsAndHashCode(callSuper = true)\n@lombok.Getter\npublic class CreateTsigKeyRequest extends com.oracle.bmc.requests.BmcRequest {\n\n /**\n * Details for creating a new TSIG key.\n */\n private com.oracle.bmc.dns.model.CreateTsigKeyDetails createTsigKeyDetails;\n\n /**\n * Unique Oracle-assigned identifier for the request. If you need\n * to contact Oracle about a particular request, please provide\n * the request ID.\n */\n private String opcRequestId;\n\n /**\n * Specifies to operate only on resources that have a matching DNS scope.\n */\n private com.oracle.bmc.dns.model.Scope scope;\n\n /**\n * Alternative accessor for the body parameter.\n * @return body parameter\n */\n @Override\n @com.oracle.bmc.InternalSdk\n public com.oracle.bmc.dns.model.CreateTsigKeyDetails getBody$() {\n return createTsigKeyDetails;\n }\n\n public static class Builder implements com.oracle.bmc.requests.BmcRequest.Builder {\n\n private com.oracle.bmc.util.internal.Consumer invocationCallback = null;\n\n private com.oracle.bmc.retrier.RetryConfiguration retryConfiguration = null;\n\n /**\n * Set the invocation callback for the request to be built.\n * @param invocationCallback the invocation callback to be set for the request\n * @return this builder instance\n */\n public Builder invocationCallback(com.oracle.bmc.util.internal.Consumer invocationCallback) {\n this.invocationCallback = invocationCallback;\n return this;\n }\n\n /**\n * Set the retry configuration for the request to be built.\n * @param retryConfiguration the retry configuration to be used for the request\n * @return this builder instance\n */\n public Builder retryConfiguration(com.oracle.bmc.retrier.RetryConfiguration retryConfiguration) {\n this.retryConfiguration = retryConfiguration;\n return this;\n }\n\n /**\n * Copy method to populate the builder with values from the given instance.\n * @return this builder instance\n */\n public Builder copy(CreateTsigKeyRequest o) {", "post_mask_code": "\n scope(o.getScope());\n invocationCallback(o.getInvocationCallback());\n retryConfiguration(o.getRetryConfiguration());\n return this;\n }\n\n /**\n * Build the instance of CreateTsigKeyRequest as configured by this builder\n *\n * Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,\n * while the method {@link Builder#buildWithoutInvocationCallback} does not.\n *\n * This is the preferred method to build an instance.\n *\n * @return instance of CreateTsigKeyRequest\n */\n public CreateTsigKeyRequest build() {\n CreateTsigKeyRequest request = buildWithoutInvocationCallback();\n request.setInvocationCallback(invocationCallback);\n request.setRetryConfiguration(retryConfiguration);\n return request;\n }\n\n /**\n * Alternative setter for the body parameter.\n * @param body the body parameter\n * @return this builder instance\n */\n @com.oracle.bmc.InternalSdk\n public Builder body$(com.oracle.bmc.dns.model.CreateTsigKeyDetails body) {\n createTsigKeyDetails(body);\n return this;\n }\n }\n}\n"} {"task_id": "Java_236", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/oracle/oci-java-sdk/bmc-dns/src/main/java/com/oracle/bmc/dns/requests/CreateTsigKeyRequest.java", "mask_start_position": 2979, "mask_end_position": 3058, "canonical_solution": "scope(o.getScope());\n invocationCallback(o.getInvocationCallback());", "pre_mask_code": "package com.oracle.bmc.dns.requests;\n\nimport com.oracle.bmc.dns.model.*;\n\n/**\n * Example: Click here to see how to use CreateTsigKeyRequest.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20180115\")\n@lombok.Builder(builderClassName = \"Builder\", buildMethodName = \"buildWithoutInvocationCallback\", toBuilder = true)\n@lombok.ToString(callSuper = true)\n@lombok.EqualsAndHashCode(callSuper = true)\n@lombok.Getter\npublic class CreateTsigKeyRequest extends com.oracle.bmc.requests.BmcRequest {\n\n /**\n * Details for creating a new TSIG key.\n */\n private com.oracle.bmc.dns.model.CreateTsigKeyDetails createTsigKeyDetails;\n\n /**\n * Unique Oracle-assigned identifier for the request. If you need\n * to contact Oracle about a particular request, please provide\n * the request ID.\n */\n private String opcRequestId;\n\n /**\n * Specifies to operate only on resources that have a matching DNS scope.\n */\n private com.oracle.bmc.dns.model.Scope scope;\n\n /**\n * Alternative accessor for the body parameter.\n * @return body parameter\n */\n @Override\n @com.oracle.bmc.InternalSdk\n public com.oracle.bmc.dns.model.CreateTsigKeyDetails getBody$() {\n return createTsigKeyDetails;\n }\n\n public static class Builder implements com.oracle.bmc.requests.BmcRequest.Builder {\n\n private com.oracle.bmc.util.internal.Consumer invocationCallback = null;\n\n private com.oracle.bmc.retrier.RetryConfiguration retryConfiguration = null;\n\n /**\n * Set the invocation callback for the request to be built.\n * @param invocationCallback the invocation callback to be set for the request\n * @return this builder instance\n */\n public Builder invocationCallback(com.oracle.bmc.util.internal.Consumer invocationCallback) {\n this.invocationCallback = invocationCallback;\n return this;\n }\n\n /**\n * Set the retry configuration for the request to be built.\n * @param retryConfiguration the retry configuration to be used for the request\n * @return this builder instance\n */\n public Builder retryConfiguration(com.oracle.bmc.retrier.RetryConfiguration retryConfiguration) {\n this.retryConfiguration = retryConfiguration;\n return this;\n }\n\n /**\n * Copy method to populate the builder with values from the given instance.\n * @return this builder instance\n */\n public Builder copy(CreateTsigKeyRequest o) {\n createTsigKeyDetails(o.getCreateTsigKeyDetails());\n opcRequestId(o.getOpcRequestId());\n ", "post_mask_code": "\n retryConfiguration(o.getRetryConfiguration());\n return this;\n }\n\n /**\n * Build the instance of CreateTsigKeyRequest as configured by this builder\n *\n * Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,\n * while the method {@link Builder#buildWithoutInvocationCallback} does not.\n *\n * This is the preferred method to build an instance.\n *\n * @return instance of CreateTsigKeyRequest\n */\n public CreateTsigKeyRequest build() {\n CreateTsigKeyRequest request = buildWithoutInvocationCallback();\n request.setInvocationCallback(invocationCallback);\n request.setRetryConfiguration(retryConfiguration);\n return request;\n }\n\n /**\n * Alternative setter for the body parameter.\n * @param body the body parameter\n * @return this builder instance\n */\n @com.oracle.bmc.InternalSdk\n public Builder body$(com.oracle.bmc.dns.model.CreateTsigKeyDetails body) {\n createTsigKeyDetails(body);\n return this;\n }\n }\n}\n"} {"task_id": "Java_237", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/oracle/oci-java-sdk/bmc-dns/src/main/java/com/oracle/bmc/dns/requests/CreateTsigKeyRequest.java", "mask_start_position": 3071, "mask_end_position": 3152, "canonical_solution": "retryConfiguration(o.getRetryConfiguration());\n return this;\n }", "pre_mask_code": "package com.oracle.bmc.dns.requests;\n\nimport com.oracle.bmc.dns.model.*;\n\n/**\n * Example: Click here to see how to use CreateTsigKeyRequest.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20180115\")\n@lombok.Builder(builderClassName = \"Builder\", buildMethodName = \"buildWithoutInvocationCallback\", toBuilder = true)\n@lombok.ToString(callSuper = true)\n@lombok.EqualsAndHashCode(callSuper = true)\n@lombok.Getter\npublic class CreateTsigKeyRequest extends com.oracle.bmc.requests.BmcRequest {\n\n /**\n * Details for creating a new TSIG key.\n */\n private com.oracle.bmc.dns.model.CreateTsigKeyDetails createTsigKeyDetails;\n\n /**\n * Unique Oracle-assigned identifier for the request. If you need\n * to contact Oracle about a particular request, please provide\n * the request ID.\n */\n private String opcRequestId;\n\n /**\n * Specifies to operate only on resources that have a matching DNS scope.\n */\n private com.oracle.bmc.dns.model.Scope scope;\n\n /**\n * Alternative accessor for the body parameter.\n * @return body parameter\n */\n @Override\n @com.oracle.bmc.InternalSdk\n public com.oracle.bmc.dns.model.CreateTsigKeyDetails getBody$() {\n return createTsigKeyDetails;\n }\n\n public static class Builder implements com.oracle.bmc.requests.BmcRequest.Builder {\n\n private com.oracle.bmc.util.internal.Consumer invocationCallback = null;\n\n private com.oracle.bmc.retrier.RetryConfiguration retryConfiguration = null;\n\n /**\n * Set the invocation callback for the request to be built.\n * @param invocationCallback the invocation callback to be set for the request\n * @return this builder instance\n */\n public Builder invocationCallback(com.oracle.bmc.util.internal.Consumer invocationCallback) {\n this.invocationCallback = invocationCallback;\n return this;\n }\n\n /**\n * Set the retry configuration for the request to be built.\n * @param retryConfiguration the retry configuration to be used for the request\n * @return this builder instance\n */\n public Builder retryConfiguration(com.oracle.bmc.retrier.RetryConfiguration retryConfiguration) {\n this.retryConfiguration = retryConfiguration;\n return this;\n }\n\n /**\n * Copy method to populate the builder with values from the given instance.\n * @return this builder instance\n */\n public Builder copy(CreateTsigKeyRequest o) {\n createTsigKeyDetails(o.getCreateTsigKeyDetails());\n opcRequestId(o.getOpcRequestId());\n scope(o.getScope());\n invocationCallback(o.getInvocationCallback());\n ", "post_mask_code": "\n\n /**\n * Build the instance of CreateTsigKeyRequest as configured by this builder\n *\n * Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,\n * while the method {@link Builder#buildWithoutInvocationCallback} does not.\n *\n * This is the preferred method to build an instance.\n *\n * @return instance of CreateTsigKeyRequest\n */\n public CreateTsigKeyRequest build() {\n CreateTsigKeyRequest request = buildWithoutInvocationCallback();\n request.setInvocationCallback(invocationCallback);\n request.setRetryConfiguration(retryConfiguration);\n return request;\n }\n\n /**\n * Alternative setter for the body parameter.\n * @param body the body parameter\n * @return this builder instance\n */\n @com.oracle.bmc.InternalSdk\n public Builder body$(com.oracle.bmc.dns.model.CreateTsigKeyDetails body) {\n createTsigKeyDetails(body);\n return this;\n }\n }\n}\n"} {"task_id": "Java_238", "language": "Java", "task_type": "single_line", "source_file": "java/github/oracle/oci-java-sdk/bmc-dns/src/main/java/com/oracle/bmc/dns/requests/CreateTsigKeyRequest.java", "mask_start_position": 3901, "mask_end_position": 3906, "canonical_solution": "uest;", "pre_mask_code": "package com.oracle.bmc.dns.requests;\n\nimport com.oracle.bmc.dns.model.*;\n\n/**\n * Example: Click here to see how to use CreateTsigKeyRequest.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20180115\")\n@lombok.Builder(builderClassName = \"Builder\", buildMethodName = \"buildWithoutInvocationCallback\", toBuilder = true)\n@lombok.ToString(callSuper = true)\n@lombok.EqualsAndHashCode(callSuper = true)\n@lombok.Getter\npublic class CreateTsigKeyRequest extends com.oracle.bmc.requests.BmcRequest {\n\n /**\n * Details for creating a new TSIG key.\n */\n private com.oracle.bmc.dns.model.CreateTsigKeyDetails createTsigKeyDetails;\n\n /**\n * Unique Oracle-assigned identifier for the request. If you need\n * to contact Oracle about a particular request, please provide\n * the request ID.\n */\n private String opcRequestId;\n\n /**\n * Specifies to operate only on resources that have a matching DNS scope.\n */\n private com.oracle.bmc.dns.model.Scope scope;\n\n /**\n * Alternative accessor for the body parameter.\n * @return body parameter\n */\n @Override\n @com.oracle.bmc.InternalSdk\n public com.oracle.bmc.dns.model.CreateTsigKeyDetails getBody$() {\n return createTsigKeyDetails;\n }\n\n public static class Builder implements com.oracle.bmc.requests.BmcRequest.Builder {\n\n private com.oracle.bmc.util.internal.Consumer invocationCallback = null;\n\n private com.oracle.bmc.retrier.RetryConfiguration retryConfiguration = null;\n\n /**\n * Set the invocation callback for the request to be built.\n * @param invocationCallback the invocation callback to be set for the request\n * @return this builder instance\n */\n public Builder invocationCallback(com.oracle.bmc.util.internal.Consumer invocationCallback) {\n this.invocationCallback = invocationCallback;\n return this;\n }\n\n /**\n * Set the retry configuration for the request to be built.\n * @param retryConfiguration the retry configuration to be used for the request\n * @return this builder instance\n */\n public Builder retryConfiguration(com.oracle.bmc.retrier.RetryConfiguration retryConfiguration) {\n this.retryConfiguration = retryConfiguration;\n return this;\n }\n\n /**\n * Copy method to populate the builder with values from the given instance.\n * @return this builder instance\n */\n public Builder copy(CreateTsigKeyRequest o) {\n createTsigKeyDetails(o.getCreateTsigKeyDetails());\n opcRequestId(o.getOpcRequestId());\n scope(o.getScope());\n invocationCallback(o.getInvocationCallback());\n retryConfiguration(o.getRetryConfiguration());\n return this;\n }\n\n /**\n * Build the instance of CreateTsigKeyRequest as configured by this builder\n *\n * Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,\n * while the method {@link Builder#buildWithoutInvocationCallback} does not.\n *\n * This is the preferred method to build an instance.\n *\n * @return instance of CreateTsigKeyRequest\n */\n public CreateTsigKeyRequest build() {\n CreateTsigKeyRequest request = buildWithoutInvocationCallback();\n request.setInvocationCallback(invocationCallback);\n request.setRetryConfiguration(retryConfiguration);\n return req", "post_mask_code": "\n }\n\n /**\n * Alternative setter for the body parameter.\n * @param body the body parameter\n * @return this builder instance\n */\n @com.oracle.bmc.InternalSdk\n public Builder body$(com.oracle.bmc.dns.model.CreateTsigKeyDetails body) {\n createTsigKeyDetails(body);\n return this;\n }\n }\n}\n"} {"task_id": "Java_239", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/oracle/oci-java-sdk/bmc-dns/src/main/java/com/oracle/bmc/dns/requests/CreateTsigKeyRequest.java", "mask_start_position": 1257, "mask_end_position": 1411, "canonical_solution": "@Override\n @com.oracle.bmc.InternalSdk\n public com.oracle.bmc.dns.model.CreateTsigKeyDetails getBody$() {\n return createTsigKeyDetails;\n }", "pre_mask_code": "package com.oracle.bmc.dns.requests;\n\nimport com.oracle.bmc.dns.model.*;\n\n/**\n * Example: Click here to see how to use CreateTsigKeyRequest.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20180115\")\n@lombok.Builder(builderClassName = \"Builder\", buildMethodName = \"buildWithoutInvocationCallback\", toBuilder = true)\n@lombok.ToString(callSuper = true)\n@lombok.EqualsAndHashCode(callSuper = true)\n@lombok.Getter\npublic class CreateTsigKeyRequest extends com.oracle.bmc.requests.BmcRequest {\n\n /**\n * Details for creating a new TSIG key.\n */\n private com.oracle.bmc.dns.model.CreateTsigKeyDetails createTsigKeyDetails;\n\n /**\n * Unique Oracle-assigned identifier for the request. If you need\n * to contact Oracle about a particular request, please provide\n * the request ID.\n */\n private String opcRequestId;\n\n /**\n * Specifies to operate only on resources that have a matching DNS scope.\n */\n private com.oracle.bmc.dns.model.Scope scope;\n\n /**\n * Alternative accessor for the body parameter.\n * @return body parameter\n */\n ", "post_mask_code": "\n\n public static class Builder implements com.oracle.bmc.requests.BmcRequest.Builder {\n\n private com.oracle.bmc.util.internal.Consumer invocationCallback = null;\n\n private com.oracle.bmc.retrier.RetryConfiguration retryConfiguration = null;\n\n /**\n * Set the invocation callback for the request to be built.\n * @param invocationCallback the invocation callback to be set for the request\n * @return this builder instance\n */\n public Builder invocationCallback(com.oracle.bmc.util.internal.Consumer invocationCallback) {\n this.invocationCallback = invocationCallback;\n return this;\n }\n\n /**\n * Set the retry configuration for the request to be built.\n * @param retryConfiguration the retry configuration to be used for the request\n * @return this builder instance\n */\n public Builder retryConfiguration(com.oracle.bmc.retrier.RetryConfiguration retryConfiguration) {\n this.retryConfiguration = retryConfiguration;\n return this;\n }\n\n /**\n * Copy method to populate the builder with values from the given instance.\n * @return this builder instance\n */\n public Builder copy(CreateTsigKeyRequest o) {\n createTsigKeyDetails(o.getCreateTsigKeyDetails());\n opcRequestId(o.getOpcRequestId());\n scope(o.getScope());\n invocationCallback(o.getInvocationCallback());\n retryConfiguration(o.getRetryConfiguration());\n return this;\n }\n\n /**\n * Build the instance of CreateTsigKeyRequest as configured by this builder\n *\n * Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,\n * while the method {@link Builder#buildWithoutInvocationCallback} does not.\n *\n * This is the preferred method to build an instance.\n *\n * @return instance of CreateTsigKeyRequest\n */\n public CreateTsigKeyRequest build() {\n CreateTsigKeyRequest request = buildWithoutInvocationCallback();\n request.setInvocationCallback(invocationCallback);\n request.setRetryConfiguration(retryConfiguration);\n return request;\n }\n\n /**\n * Alternative setter for the body parameter.\n * @param body the body parameter\n * @return this builder instance\n */\n @com.oracle.bmc.InternalSdk\n public Builder body$(com.oracle.bmc.dns.model.CreateTsigKeyDetails body) {\n createTsigKeyDetails(body);\n return this;\n }\n }\n}\n"} {"task_id": "Java_240", "language": "Java", "task_type": "empty", "source_file": "java/github/oracle/oci-java-sdk/bmc-dns/src/main/java/com/oracle/bmc/dns/requests/CreateTsigKeyRequest.java", "mask_start_position": 545, "mask_end_position": 545, "canonical_solution": "", "pre_mask_code": "package com.oracle.bmc.dns.requests;\n\nimport com.oracle.bmc.dns.model.*;\n\n/**\n * Example: Click here to see how to use CreateTsigKeyRequest.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20180115\")\n@lombok.Builder(builderClassName = \"Builder\", buildMethodName = \"buildWithoutInvocationCallback\", toBuilder = true)\n@lombok.ToString(callSuper = true)\n@lombok.EqualsAndHashCode(callSuper = true)\n@lombok.Getter\npublic class C", "post_mask_code": "reateTsigKeyRequest extends com.oracle.bmc.requests.BmcRequest {\n\n /**\n * Details for creating a new TSIG key.\n */\n private com.oracle.bmc.dns.model.CreateTsigKeyDetails createTsigKeyDetails;\n\n /**\n * Unique Oracle-assigned identifier for the request. If you need\n * to contact Oracle about a particular request, please provide\n * the request ID.\n */\n private String opcRequestId;\n\n /**\n * Specifies to operate only on resources that have a matching DNS scope.\n */\n private com.oracle.bmc.dns.model.Scope scope;\n\n /**\n * Alternative accessor for the body parameter.\n * @return body parameter\n */\n @Override\n @com.oracle.bmc.InternalSdk\n public com.oracle.bmc.dns.model.CreateTsigKeyDetails getBody$() {\n return createTsigKeyDetails;\n }\n\n public static class Builder implements com.oracle.bmc.requests.BmcRequest.Builder {\n\n private com.oracle.bmc.util.internal.Consumer invocationCallback = null;\n\n private com.oracle.bmc.retrier.RetryConfiguration retryConfiguration = null;\n\n /**\n * Set the invocation callback for the request to be built.\n * @param invocationCallback the invocation callback to be set for the request\n * @return this builder instance\n */\n public Builder invocationCallback(com.oracle.bmc.util.internal.Consumer invocationCallback) {\n this.invocationCallback = invocationCallback;\n return this;\n }\n\n /**\n * Set the retry configuration for the request to be built.\n * @param retryConfiguration the retry configuration to be used for the request\n * @return this builder instance\n */\n public Builder retryConfiguration(com.oracle.bmc.retrier.RetryConfiguration retryConfiguration) {\n this.retryConfiguration = retryConfiguration;\n return this;\n }\n\n /**\n * Copy method to populate the builder with values from the given instance.\n * @return this builder instance\n */\n public Builder copy(CreateTsigKeyRequest o) {\n createTsigKeyDetails(o.getCreateTsigKeyDetails());\n opcRequestId(o.getOpcRequestId());\n scope(o.getScope());\n invocationCallback(o.getInvocationCallback());\n retryConfiguration(o.getRetryConfiguration());\n return this;\n }\n\n /**\n * Build the instance of CreateTsigKeyRequest as configured by this builder\n *\n * Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,\n * while the method {@link Builder#buildWithoutInvocationCallback} does not.\n *\n * This is the preferred method to build an instance.\n *\n * @return instance of CreateTsigKeyRequest\n */\n public CreateTsigKeyRequest build() {\n CreateTsigKeyRequest request = buildWithoutInvocationCallback();\n request.setInvocationCallback(invocationCallback);\n request.setRetryConfiguration(retryConfiguration);\n return request;\n }\n\n /**\n * Alternative setter for the body parameter.\n * @param body the body parameter\n * @return this builder instance\n */\n @com.oracle.bmc.InternalSdk\n public Builder body$(com.oracle.bmc.dns.model.CreateTsigKeyDetails body) {\n createTsigKeyDetails(body);\n return this;\n }\n }\n}\n"} {"task_id": "Java_241", "language": "Java", "task_type": "method_signature", "source_file": "java/github/LineageOS/android_frameworks_base/core/java/android/app/PictureInPictureParams.java", "mask_start_position": 5399, "mask_end_position": 5442, "canonical_solution": "@TestApi\n public float getAspectRatio() ", "pre_mask_code": "package android.app;\n\nimport android.annotation.Nullable;\nimport android.annotation.TestApi;\nimport android.graphics.Rect;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.util.Rational;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Represents a set of parameters used to initialize and update an Activity in picture-in-picture\n * mode.\n */\npublic final class PictureInPictureParams implements Parcelable {\n\n /**\n * Builder class for {@link PictureInPictureParams} objects.\n */\n public static class Builder {\n\n @Nullable\n private Rational mAspectRatio;\n\n @Nullable\n private List mUserActions;\n\n @Nullable\n private Rect mSourceRectHint;\n\n /**\n * Sets the aspect ratio. This aspect ratio is defined as the desired width / height, and\n * does not change upon device rotation.\n *\n * @param aspectRatio the new aspect ratio for the activity in picture-in-picture, must be\n * between 2.39:1 and 1:2.39 (inclusive).\n *\n * @return this builder instance.\n */\n public Builder setAspectRatio(Rational aspectRatio) {\n mAspectRatio = aspectRatio;\n return this;\n }\n\n /**\n * Sets the user actions. If there are more than\n * {@link Activity#getMaxNumPictureInPictureActions()} actions, then the input list\n * will be truncated to that number.\n *\n * @param actions the new actions to show in the picture-in-picture menu.\n *\n * @return this builder instance.\n *\n * @see RemoteAction\n */\n public Builder setActions(List actions) {\n if (mUserActions != null) {\n mUserActions = null;\n }\n if (actions != null) {\n mUserActions = new ArrayList<>(actions);\n }\n return this;\n }\n\n /**\n * Sets the source bounds hint. These bounds are only used when an activity first enters\n * picture-in-picture, and describe the bounds in window coordinates of activity entering\n * picture-in-picture that will be visible following the transition. For the best effect,\n * these bounds should also match the aspect ratio in the arguments.\n *\n * @param launchBounds window-coordinate bounds indicating the area of the activity that\n * will still be visible following the transition into picture-in-picture (eg. the video\n * view bounds in a video player)\n *\n * @return this builder instance.\n */\n public Builder setSourceRectHint(Rect launchBounds) {\n if (launchBounds == null) {\n mSourceRectHint = null;\n } else {\n mSourceRectHint = new Rect(launchBounds);\n }\n return this;\n }\n\n /**\n * @return an immutable {@link PictureInPictureParams} to be used when entering or updating\n * the activity in picture-in-picture.\n *\n * @see Activity#enterPictureInPictureMode(PictureInPictureParams)\n * @see Activity#setPictureInPictureParams(PictureInPictureParams)\n */\n public PictureInPictureParams build() {\n PictureInPictureParams params = new PictureInPictureParams(mAspectRatio, mUserActions, mSourceRectHint);\n return params;\n }\n }\n\n /**\n * The expected aspect ratio of the picture-in-picture.\n */\n @Nullable\n private Rational mAspectRatio;\n\n /**\n * The set of actions that are associated with this activity when in picture-in-picture.\n */\n @Nullable\n private List mUserActions;\n\n /**\n * The source bounds hint used when entering picture-in-picture, relative to the window bounds.\n * We can use this internally for the transition into picture-in-picture to ensure that a\n * particular source rect is visible throughout the whole transition.\n */\n @Nullable\n private Rect mSourceRectHint;\n\n PictureInPictureParams() {\n }\n\n PictureInPictureParams(Parcel in) {\n if (in.readInt() != 0) {\n mAspectRatio = new Rational(in.readInt(), in.readInt());\n }\n if (in.readInt() != 0) {\n mUserActions = new ArrayList<>();\n in.readParcelableList(mUserActions, RemoteAction.class.getClassLoader());\n }\n if (in.readInt() != 0) {\n mSourceRectHint = Rect.CREATOR.createFromParcel(in);\n }\n }\n\n PictureInPictureParams(Rational aspectRatio, List actions, Rect sourceRectHint) {\n mAspectRatio = aspectRatio;\n mUserActions = actions;\n mSourceRectHint = sourceRectHint;\n }\n\n /**\n * Copies the set parameters from the other picture-in-picture args.\n * @hide\n */\n public void copyOnlySet(PictureInPictureParams otherArgs) {\n if (otherArgs.hasSetAspectRatio()) {\n mAspectRatio = otherArgs.mAspectRatio;\n }\n if (otherArgs.hasSetActions()) {\n mUserActions = otherArgs.mUserActions;\n }\n if (otherArgs.hasSourceBoundsHint()) {\n mSourceRectHint = new Rect(otherArgs.getSourceRectHint());\n }\n }\n\n /**\n * @return the aspect ratio. If none is set, return 0.\n * @hide\n */\n ", "post_mask_code": "{\n if (mAspectRatio != null) {\n return mAspectRatio.floatValue();\n }\n return 0f;\n }\n\n /**\n * @hide\n */\n public Rational getAspectRatioRational() {\n return mAspectRatio;\n }\n\n /**\n * @return whether the aspect ratio is set.\n * @hide\n */\n public boolean hasSetAspectRatio() {\n return mAspectRatio != null;\n }\n\n /**\n * @return the set of user actions.\n * @hide\n */\n @TestApi\n public List getActions() {\n return mUserActions;\n }\n\n /**\n * @return whether the user actions are set.\n * @hide\n */\n public boolean hasSetActions() {\n return mUserActions != null;\n }\n\n /**\n * Truncates the set of actions to the given {@param size}.\n * @hide\n */\n public void truncateActions(int size) {\n if (hasSetActions()) {\n mUserActions = mUserActions.subList(0, Math.min(mUserActions.size(), size));\n }\n }\n\n /**\n * @return the source rect hint\n * @hide\n */\n @TestApi\n public Rect getSourceRectHint() {\n return mSourceRectHint;\n }\n\n /**\n * @return whether there are launch bounds set\n * @hide\n */\n public boolean hasSourceBoundsHint() {\n return mSourceRectHint != null && !mSourceRectHint.isEmpty();\n }\n\n /**\n * @return True if no parameters are set\n * @hide\n */\n public boolean empty() {\n return !hasSourceBoundsHint() && !hasSetActions() && !hasSetAspectRatio();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n if (mAspectRatio != null) {\n out.writeInt(1);\n out.writeInt(mAspectRatio.getNumerator());\n out.writeInt(mAspectRatio.getDenominator());\n } else {\n out.writeInt(0);\n }\n if (mUserActions != null) {\n out.writeInt(1);\n out.writeParcelableList(mUserActions, 0);\n } else {\n out.writeInt(0);\n }\n if (mSourceRectHint != null) {\n out.writeInt(1);\n mSourceRectHint.writeToParcel(out, 0);\n } else {\n out.writeInt(0);\n }\n }\n\n @android.annotation.NonNull\n public static final Creator CREATOR = new Creator() {\n\n public PictureInPictureParams createFromParcel(Parcel in) {\n return new PictureInPictureParams(in);\n }\n\n public PictureInPictureParams[] newArray(int size) {\n return new PictureInPictureParams[size];\n }\n };\n}\n"} {"task_id": "Java_242", "language": "Java", "task_type": "method_body", "source_file": "java/github/LineageOS/android_frameworks_base/core/java/android/app/PictureInPictureParams.java", "mask_start_position": 4962, "mask_end_position": 5305, "canonical_solution": "{\n if (otherArgs.hasSetAspectRatio()) {\n mAspectRatio = otherArgs.mAspectRatio;\n }\n if (otherArgs.hasSetActions()) {\n mUserActions = otherArgs.mUserActions;\n }\n if (otherArgs.hasSourceBoundsHint()) {\n mSourceRectHint = new Rect(otherArgs.getSourceRectHint());\n }\n }", "pre_mask_code": "package android.app;\n\nimport android.annotation.Nullable;\nimport android.annotation.TestApi;\nimport android.graphics.Rect;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.util.Rational;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Represents a set of parameters used to initialize and update an Activity in picture-in-picture\n * mode.\n */\npublic final class PictureInPictureParams implements Parcelable {\n\n /**\n * Builder class for {@link PictureInPictureParams} objects.\n */\n public static class Builder {\n\n @Nullable\n private Rational mAspectRatio;\n\n @Nullable\n private List mUserActions;\n\n @Nullable\n private Rect mSourceRectHint;\n\n /**\n * Sets the aspect ratio. This aspect ratio is defined as the desired width / height, and\n * does not change upon device rotation.\n *\n * @param aspectRatio the new aspect ratio for the activity in picture-in-picture, must be\n * between 2.39:1 and 1:2.39 (inclusive).\n *\n * @return this builder instance.\n */\n public Builder setAspectRatio(Rational aspectRatio) {\n mAspectRatio = aspectRatio;\n return this;\n }\n\n /**\n * Sets the user actions. If there are more than\n * {@link Activity#getMaxNumPictureInPictureActions()} actions, then the input list\n * will be truncated to that number.\n *\n * @param actions the new actions to show in the picture-in-picture menu.\n *\n * @return this builder instance.\n *\n * @see RemoteAction\n */\n public Builder setActions(List actions) {\n if (mUserActions != null) {\n mUserActions = null;\n }\n if (actions != null) {\n mUserActions = new ArrayList<>(actions);\n }\n return this;\n }\n\n /**\n * Sets the source bounds hint. These bounds are only used when an activity first enters\n * picture-in-picture, and describe the bounds in window coordinates of activity entering\n * picture-in-picture that will be visible following the transition. For the best effect,\n * these bounds should also match the aspect ratio in the arguments.\n *\n * @param launchBounds window-coordinate bounds indicating the area of the activity that\n * will still be visible following the transition into picture-in-picture (eg. the video\n * view bounds in a video player)\n *\n * @return this builder instance.\n */\n public Builder setSourceRectHint(Rect launchBounds) {\n if (launchBounds == null) {\n mSourceRectHint = null;\n } else {\n mSourceRectHint = new Rect(launchBounds);\n }\n return this;\n }\n\n /**\n * @return an immutable {@link PictureInPictureParams} to be used when entering or updating\n * the activity in picture-in-picture.\n *\n * @see Activity#enterPictureInPictureMode(PictureInPictureParams)\n * @see Activity#setPictureInPictureParams(PictureInPictureParams)\n */\n public PictureInPictureParams build() {\n PictureInPictureParams params = new PictureInPictureParams(mAspectRatio, mUserActions, mSourceRectHint);\n return params;\n }\n }\n\n /**\n * The expected aspect ratio of the picture-in-picture.\n */\n @Nullable\n private Rational mAspectRatio;\n\n /**\n * The set of actions that are associated with this activity when in picture-in-picture.\n */\n @Nullable\n private List mUserActions;\n\n /**\n * The source bounds hint used when entering picture-in-picture, relative to the window bounds.\n * We can use this internally for the transition into picture-in-picture to ensure that a\n * particular source rect is visible throughout the whole transition.\n */\n @Nullable\n private Rect mSourceRectHint;\n\n PictureInPictureParams() {\n }\n\n PictureInPictureParams(Parcel in) {\n if (in.readInt() != 0) {\n mAspectRatio = new Rational(in.readInt(), in.readInt());\n }\n if (in.readInt() != 0) {\n mUserActions = new ArrayList<>();\n in.readParcelableList(mUserActions, RemoteAction.class.getClassLoader());\n }\n if (in.readInt() != 0) {\n mSourceRectHint = Rect.CREATOR.createFromParcel(in);\n }\n }\n\n PictureInPictureParams(Rational aspectRatio, List actions, Rect sourceRectHint) {\n mAspectRatio = aspectRatio;\n mUserActions = actions;\n mSourceRectHint = sourceRectHint;\n }\n\n /**\n * Copies the set parameters from the other picture-in-picture args.\n * @hide\n */\n public void copyOnlySet(PictureInPictureParams otherArgs) ", "post_mask_code": "\n\n /**\n * @return the aspect ratio. If none is set, return 0.\n * @hide\n */\n @TestApi\n public float getAspectRatio() {\n if (mAspectRatio != null) {\n return mAspectRatio.floatValue();\n }\n return 0f;\n }\n\n /**\n * @hide\n */\n public Rational getAspectRatioRational() {\n return mAspectRatio;\n }\n\n /**\n * @return whether the aspect ratio is set.\n * @hide\n */\n public boolean hasSetAspectRatio() {\n return mAspectRatio != null;\n }\n\n /**\n * @return the set of user actions.\n * @hide\n */\n @TestApi\n public List getActions() {\n return mUserActions;\n }\n\n /**\n * @return whether the user actions are set.\n * @hide\n */\n public boolean hasSetActions() {\n return mUserActions != null;\n }\n\n /**\n * Truncates the set of actions to the given {@param size}.\n * @hide\n */\n public void truncateActions(int size) {\n if (hasSetActions()) {\n mUserActions = mUserActions.subList(0, Math.min(mUserActions.size(), size));\n }\n }\n\n /**\n * @return the source rect hint\n * @hide\n */\n @TestApi\n public Rect getSourceRectHint() {\n return mSourceRectHint;\n }\n\n /**\n * @return whether there are launch bounds set\n * @hide\n */\n public boolean hasSourceBoundsHint() {\n return mSourceRectHint != null && !mSourceRectHint.isEmpty();\n }\n\n /**\n * @return True if no parameters are set\n * @hide\n */\n public boolean empty() {\n return !hasSourceBoundsHint() && !hasSetActions() && !hasSetAspectRatio();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n if (mAspectRatio != null) {\n out.writeInt(1);\n out.writeInt(mAspectRatio.getNumerator());\n out.writeInt(mAspectRatio.getDenominator());\n } else {\n out.writeInt(0);\n }\n if (mUserActions != null) {\n out.writeInt(1);\n out.writeParcelableList(mUserActions, 0);\n } else {\n out.writeInt(0);\n }\n if (mSourceRectHint != null) {\n out.writeInt(1);\n mSourceRectHint.writeToParcel(out, 0);\n } else {\n out.writeInt(0);\n }\n }\n\n @android.annotation.NonNull\n public static final Creator CREATOR = new Creator() {\n\n public PictureInPictureParams createFromParcel(Parcel in) {\n return new PictureInPictureParams(in);\n }\n\n public PictureInPictureParams[] newArray(int size) {\n return new PictureInPictureParams[size];\n }\n };\n}\n"} {"task_id": "Java_243", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/LineageOS/android_frameworks_base/core/java/android/app/PictureInPictureParams.java", "mask_start_position": 4963, "mask_end_position": 5069, "canonical_solution": "\n if (otherArgs.hasSetAspectRatio()) {\n mAspectRatio = otherArgs.mAspectRatio;\n }", "pre_mask_code": "package android.app;\n\nimport android.annotation.Nullable;\nimport android.annotation.TestApi;\nimport android.graphics.Rect;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.util.Rational;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Represents a set of parameters used to initialize and update an Activity in picture-in-picture\n * mode.\n */\npublic final class PictureInPictureParams implements Parcelable {\n\n /**\n * Builder class for {@link PictureInPictureParams} objects.\n */\n public static class Builder {\n\n @Nullable\n private Rational mAspectRatio;\n\n @Nullable\n private List mUserActions;\n\n @Nullable\n private Rect mSourceRectHint;\n\n /**\n * Sets the aspect ratio. This aspect ratio is defined as the desired width / height, and\n * does not change upon device rotation.\n *\n * @param aspectRatio the new aspect ratio for the activity in picture-in-picture, must be\n * between 2.39:1 and 1:2.39 (inclusive).\n *\n * @return this builder instance.\n */\n public Builder setAspectRatio(Rational aspectRatio) {\n mAspectRatio = aspectRatio;\n return this;\n }\n\n /**\n * Sets the user actions. If there are more than\n * {@link Activity#getMaxNumPictureInPictureActions()} actions, then the input list\n * will be truncated to that number.\n *\n * @param actions the new actions to show in the picture-in-picture menu.\n *\n * @return this builder instance.\n *\n * @see RemoteAction\n */\n public Builder setActions(List actions) {\n if (mUserActions != null) {\n mUserActions = null;\n }\n if (actions != null) {\n mUserActions = new ArrayList<>(actions);\n }\n return this;\n }\n\n /**\n * Sets the source bounds hint. These bounds are only used when an activity first enters\n * picture-in-picture, and describe the bounds in window coordinates of activity entering\n * picture-in-picture that will be visible following the transition. For the best effect,\n * these bounds should also match the aspect ratio in the arguments.\n *\n * @param launchBounds window-coordinate bounds indicating the area of the activity that\n * will still be visible following the transition into picture-in-picture (eg. the video\n * view bounds in a video player)\n *\n * @return this builder instance.\n */\n public Builder setSourceRectHint(Rect launchBounds) {\n if (launchBounds == null) {\n mSourceRectHint = null;\n } else {\n mSourceRectHint = new Rect(launchBounds);\n }\n return this;\n }\n\n /**\n * @return an immutable {@link PictureInPictureParams} to be used when entering or updating\n * the activity in picture-in-picture.\n *\n * @see Activity#enterPictureInPictureMode(PictureInPictureParams)\n * @see Activity#setPictureInPictureParams(PictureInPictureParams)\n */\n public PictureInPictureParams build() {\n PictureInPictureParams params = new PictureInPictureParams(mAspectRatio, mUserActions, mSourceRectHint);\n return params;\n }\n }\n\n /**\n * The expected aspect ratio of the picture-in-picture.\n */\n @Nullable\n private Rational mAspectRatio;\n\n /**\n * The set of actions that are associated with this activity when in picture-in-picture.\n */\n @Nullable\n private List mUserActions;\n\n /**\n * The source bounds hint used when entering picture-in-picture, relative to the window bounds.\n * We can use this internally for the transition into picture-in-picture to ensure that a\n * particular source rect is visible throughout the whole transition.\n */\n @Nullable\n private Rect mSourceRectHint;\n\n PictureInPictureParams() {\n }\n\n PictureInPictureParams(Parcel in) {\n if (in.readInt() != 0) {\n mAspectRatio = new Rational(in.readInt(), in.readInt());\n }\n if (in.readInt() != 0) {\n mUserActions = new ArrayList<>();\n in.readParcelableList(mUserActions, RemoteAction.class.getClassLoader());\n }\n if (in.readInt() != 0) {\n mSourceRectHint = Rect.CREATOR.createFromParcel(in);\n }\n }\n\n PictureInPictureParams(Rational aspectRatio, List actions, Rect sourceRectHint) {\n mAspectRatio = aspectRatio;\n mUserActions = actions;\n mSourceRectHint = sourceRectHint;\n }\n\n /**\n * Copies the set parameters from the other picture-in-picture args.\n * @hide\n */\n public void copyOnlySet(PictureInPictureParams otherArgs) {", "post_mask_code": "\n if (otherArgs.hasSetActions()) {\n mUserActions = otherArgs.mUserActions;\n }\n if (otherArgs.hasSourceBoundsHint()) {\n mSourceRectHint = new Rect(otherArgs.getSourceRectHint());\n }\n }\n\n /**\n * @return the aspect ratio. If none is set, return 0.\n * @hide\n */\n @TestApi\n public float getAspectRatio() {\n if (mAspectRatio != null) {\n return mAspectRatio.floatValue();\n }\n return 0f;\n }\n\n /**\n * @hide\n */\n public Rational getAspectRatioRational() {\n return mAspectRatio;\n }\n\n /**\n * @return whether the aspect ratio is set.\n * @hide\n */\n public boolean hasSetAspectRatio() {\n return mAspectRatio != null;\n }\n\n /**\n * @return the set of user actions.\n * @hide\n */\n @TestApi\n public List getActions() {\n return mUserActions;\n }\n\n /**\n * @return whether the user actions are set.\n * @hide\n */\n public boolean hasSetActions() {\n return mUserActions != null;\n }\n\n /**\n * Truncates the set of actions to the given {@param size}.\n * @hide\n */\n public void truncateActions(int size) {\n if (hasSetActions()) {\n mUserActions = mUserActions.subList(0, Math.min(mUserActions.size(), size));\n }\n }\n\n /**\n * @return the source rect hint\n * @hide\n */\n @TestApi\n public Rect getSourceRectHint() {\n return mSourceRectHint;\n }\n\n /**\n * @return whether there are launch bounds set\n * @hide\n */\n public boolean hasSourceBoundsHint() {\n return mSourceRectHint != null && !mSourceRectHint.isEmpty();\n }\n\n /**\n * @return True if no parameters are set\n * @hide\n */\n public boolean empty() {\n return !hasSourceBoundsHint() && !hasSetActions() && !hasSetAspectRatio();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n if (mAspectRatio != null) {\n out.writeInt(1);\n out.writeInt(mAspectRatio.getNumerator());\n out.writeInt(mAspectRatio.getDenominator());\n } else {\n out.writeInt(0);\n }\n if (mUserActions != null) {\n out.writeInt(1);\n out.writeParcelableList(mUserActions, 0);\n } else {\n out.writeInt(0);\n }\n if (mSourceRectHint != null) {\n out.writeInt(1);\n mSourceRectHint.writeToParcel(out, 0);\n } else {\n out.writeInt(0);\n }\n }\n\n @android.annotation.NonNull\n public static final Creator CREATOR = new Creator() {\n\n public PictureInPictureParams createFromParcel(Parcel in) {\n return new PictureInPictureParams(in);\n }\n\n public PictureInPictureParams[] newArray(int size) {\n return new PictureInPictureParams[size];\n }\n };\n}\n"} {"task_id": "Java_244", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/LineageOS/android_frameworks_base/core/java/android/app/PictureInPictureParams.java", "mask_start_position": 5078, "mask_end_position": 5171, "canonical_solution": "if (otherArgs.hasSetActions()) {\n mUserActions = otherArgs.mUserActions;\n }", "pre_mask_code": "package android.app;\n\nimport android.annotation.Nullable;\nimport android.annotation.TestApi;\nimport android.graphics.Rect;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.util.Rational;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Represents a set of parameters used to initialize and update an Activity in picture-in-picture\n * mode.\n */\npublic final class PictureInPictureParams implements Parcelable {\n\n /**\n * Builder class for {@link PictureInPictureParams} objects.\n */\n public static class Builder {\n\n @Nullable\n private Rational mAspectRatio;\n\n @Nullable\n private List mUserActions;\n\n @Nullable\n private Rect mSourceRectHint;\n\n /**\n * Sets the aspect ratio. This aspect ratio is defined as the desired width / height, and\n * does not change upon device rotation.\n *\n * @param aspectRatio the new aspect ratio for the activity in picture-in-picture, must be\n * between 2.39:1 and 1:2.39 (inclusive).\n *\n * @return this builder instance.\n */\n public Builder setAspectRatio(Rational aspectRatio) {\n mAspectRatio = aspectRatio;\n return this;\n }\n\n /**\n * Sets the user actions. If there are more than\n * {@link Activity#getMaxNumPictureInPictureActions()} actions, then the input list\n * will be truncated to that number.\n *\n * @param actions the new actions to show in the picture-in-picture menu.\n *\n * @return this builder instance.\n *\n * @see RemoteAction\n */\n public Builder setActions(List actions) {\n if (mUserActions != null) {\n mUserActions = null;\n }\n if (actions != null) {\n mUserActions = new ArrayList<>(actions);\n }\n return this;\n }\n\n /**\n * Sets the source bounds hint. These bounds are only used when an activity first enters\n * picture-in-picture, and describe the bounds in window coordinates of activity entering\n * picture-in-picture that will be visible following the transition. For the best effect,\n * these bounds should also match the aspect ratio in the arguments.\n *\n * @param launchBounds window-coordinate bounds indicating the area of the activity that\n * will still be visible following the transition into picture-in-picture (eg. the video\n * view bounds in a video player)\n *\n * @return this builder instance.\n */\n public Builder setSourceRectHint(Rect launchBounds) {\n if (launchBounds == null) {\n mSourceRectHint = null;\n } else {\n mSourceRectHint = new Rect(launchBounds);\n }\n return this;\n }\n\n /**\n * @return an immutable {@link PictureInPictureParams} to be used when entering or updating\n * the activity in picture-in-picture.\n *\n * @see Activity#enterPictureInPictureMode(PictureInPictureParams)\n * @see Activity#setPictureInPictureParams(PictureInPictureParams)\n */\n public PictureInPictureParams build() {\n PictureInPictureParams params = new PictureInPictureParams(mAspectRatio, mUserActions, mSourceRectHint);\n return params;\n }\n }\n\n /**\n * The expected aspect ratio of the picture-in-picture.\n */\n @Nullable\n private Rational mAspectRatio;\n\n /**\n * The set of actions that are associated with this activity when in picture-in-picture.\n */\n @Nullable\n private List mUserActions;\n\n /**\n * The source bounds hint used when entering picture-in-picture, relative to the window bounds.\n * We can use this internally for the transition into picture-in-picture to ensure that a\n * particular source rect is visible throughout the whole transition.\n */\n @Nullable\n private Rect mSourceRectHint;\n\n PictureInPictureParams() {\n }\n\n PictureInPictureParams(Parcel in) {\n if (in.readInt() != 0) {\n mAspectRatio = new Rational(in.readInt(), in.readInt());\n }\n if (in.readInt() != 0) {\n mUserActions = new ArrayList<>();\n in.readParcelableList(mUserActions, RemoteAction.class.getClassLoader());\n }\n if (in.readInt() != 0) {\n mSourceRectHint = Rect.CREATOR.createFromParcel(in);\n }\n }\n\n PictureInPictureParams(Rational aspectRatio, List actions, Rect sourceRectHint) {\n mAspectRatio = aspectRatio;\n mUserActions = actions;\n mSourceRectHint = sourceRectHint;\n }\n\n /**\n * Copies the set parameters from the other picture-in-picture args.\n * @hide\n */\n public void copyOnlySet(PictureInPictureParams otherArgs) {\n if (otherArgs.hasSetAspectRatio()) {\n mAspectRatio = otherArgs.mAspectRatio;\n }\n ", "post_mask_code": "\n if (otherArgs.hasSourceBoundsHint()) {\n mSourceRectHint = new Rect(otherArgs.getSourceRectHint());\n }\n }\n\n /**\n * @return the aspect ratio. If none is set, return 0.\n * @hide\n */\n @TestApi\n public float getAspectRatio() {\n if (mAspectRatio != null) {\n return mAspectRatio.floatValue();\n }\n return 0f;\n }\n\n /**\n * @hide\n */\n public Rational getAspectRatioRational() {\n return mAspectRatio;\n }\n\n /**\n * @return whether the aspect ratio is set.\n * @hide\n */\n public boolean hasSetAspectRatio() {\n return mAspectRatio != null;\n }\n\n /**\n * @return the set of user actions.\n * @hide\n */\n @TestApi\n public List getActions() {\n return mUserActions;\n }\n\n /**\n * @return whether the user actions are set.\n * @hide\n */\n public boolean hasSetActions() {\n return mUserActions != null;\n }\n\n /**\n * Truncates the set of actions to the given {@param size}.\n * @hide\n */\n public void truncateActions(int size) {\n if (hasSetActions()) {\n mUserActions = mUserActions.subList(0, Math.min(mUserActions.size(), size));\n }\n }\n\n /**\n * @return the source rect hint\n * @hide\n */\n @TestApi\n public Rect getSourceRectHint() {\n return mSourceRectHint;\n }\n\n /**\n * @return whether there are launch bounds set\n * @hide\n */\n public boolean hasSourceBoundsHint() {\n return mSourceRectHint != null && !mSourceRectHint.isEmpty();\n }\n\n /**\n * @return True if no parameters are set\n * @hide\n */\n public boolean empty() {\n return !hasSourceBoundsHint() && !hasSetActions() && !hasSetAspectRatio();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n if (mAspectRatio != null) {\n out.writeInt(1);\n out.writeInt(mAspectRatio.getNumerator());\n out.writeInt(mAspectRatio.getDenominator());\n } else {\n out.writeInt(0);\n }\n if (mUserActions != null) {\n out.writeInt(1);\n out.writeParcelableList(mUserActions, 0);\n } else {\n out.writeInt(0);\n }\n if (mSourceRectHint != null) {\n out.writeInt(1);\n mSourceRectHint.writeToParcel(out, 0);\n } else {\n out.writeInt(0);\n }\n }\n\n @android.annotation.NonNull\n public static final Creator CREATOR = new Creator() {\n\n public PictureInPictureParams createFromParcel(Parcel in) {\n return new PictureInPictureParams(in);\n }\n\n public PictureInPictureParams[] newArray(int size) {\n return new PictureInPictureParams[size];\n }\n };\n}\n"} {"task_id": "Java_245", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/LineageOS/android_frameworks_base/core/java/android/app/PictureInPictureParams.java", "mask_start_position": 5180, "mask_end_position": 5305, "canonical_solution": "if (otherArgs.hasSourceBoundsHint()) {\n mSourceRectHint = new Rect(otherArgs.getSourceRectHint());\n }\n }", "pre_mask_code": "package android.app;\n\nimport android.annotation.Nullable;\nimport android.annotation.TestApi;\nimport android.graphics.Rect;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.util.Rational;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Represents a set of parameters used to initialize and update an Activity in picture-in-picture\n * mode.\n */\npublic final class PictureInPictureParams implements Parcelable {\n\n /**\n * Builder class for {@link PictureInPictureParams} objects.\n */\n public static class Builder {\n\n @Nullable\n private Rational mAspectRatio;\n\n @Nullable\n private List mUserActions;\n\n @Nullable\n private Rect mSourceRectHint;\n\n /**\n * Sets the aspect ratio. This aspect ratio is defined as the desired width / height, and\n * does not change upon device rotation.\n *\n * @param aspectRatio the new aspect ratio for the activity in picture-in-picture, must be\n * between 2.39:1 and 1:2.39 (inclusive).\n *\n * @return this builder instance.\n */\n public Builder setAspectRatio(Rational aspectRatio) {\n mAspectRatio = aspectRatio;\n return this;\n }\n\n /**\n * Sets the user actions. If there are more than\n * {@link Activity#getMaxNumPictureInPictureActions()} actions, then the input list\n * will be truncated to that number.\n *\n * @param actions the new actions to show in the picture-in-picture menu.\n *\n * @return this builder instance.\n *\n * @see RemoteAction\n */\n public Builder setActions(List actions) {\n if (mUserActions != null) {\n mUserActions = null;\n }\n if (actions != null) {\n mUserActions = new ArrayList<>(actions);\n }\n return this;\n }\n\n /**\n * Sets the source bounds hint. These bounds are only used when an activity first enters\n * picture-in-picture, and describe the bounds in window coordinates of activity entering\n * picture-in-picture that will be visible following the transition. For the best effect,\n * these bounds should also match the aspect ratio in the arguments.\n *\n * @param launchBounds window-coordinate bounds indicating the area of the activity that\n * will still be visible following the transition into picture-in-picture (eg. the video\n * view bounds in a video player)\n *\n * @return this builder instance.\n */\n public Builder setSourceRectHint(Rect launchBounds) {\n if (launchBounds == null) {\n mSourceRectHint = null;\n } else {\n mSourceRectHint = new Rect(launchBounds);\n }\n return this;\n }\n\n /**\n * @return an immutable {@link PictureInPictureParams} to be used when entering or updating\n * the activity in picture-in-picture.\n *\n * @see Activity#enterPictureInPictureMode(PictureInPictureParams)\n * @see Activity#setPictureInPictureParams(PictureInPictureParams)\n */\n public PictureInPictureParams build() {\n PictureInPictureParams params = new PictureInPictureParams(mAspectRatio, mUserActions, mSourceRectHint);\n return params;\n }\n }\n\n /**\n * The expected aspect ratio of the picture-in-picture.\n */\n @Nullable\n private Rational mAspectRatio;\n\n /**\n * The set of actions that are associated with this activity when in picture-in-picture.\n */\n @Nullable\n private List mUserActions;\n\n /**\n * The source bounds hint used when entering picture-in-picture, relative to the window bounds.\n * We can use this internally for the transition into picture-in-picture to ensure that a\n * particular source rect is visible throughout the whole transition.\n */\n @Nullable\n private Rect mSourceRectHint;\n\n PictureInPictureParams() {\n }\n\n PictureInPictureParams(Parcel in) {\n if (in.readInt() != 0) {\n mAspectRatio = new Rational(in.readInt(), in.readInt());\n }\n if (in.readInt() != 0) {\n mUserActions = new ArrayList<>();\n in.readParcelableList(mUserActions, RemoteAction.class.getClassLoader());\n }\n if (in.readInt() != 0) {\n mSourceRectHint = Rect.CREATOR.createFromParcel(in);\n }\n }\n\n PictureInPictureParams(Rational aspectRatio, List actions, Rect sourceRectHint) {\n mAspectRatio = aspectRatio;\n mUserActions = actions;\n mSourceRectHint = sourceRectHint;\n }\n\n /**\n * Copies the set parameters from the other picture-in-picture args.\n * @hide\n */\n public void copyOnlySet(PictureInPictureParams otherArgs) {\n if (otherArgs.hasSetAspectRatio()) {\n mAspectRatio = otherArgs.mAspectRatio;\n }\n if (otherArgs.hasSetActions()) {\n mUserActions = otherArgs.mUserActions;\n }\n ", "post_mask_code": "\n\n /**\n * @return the aspect ratio. If none is set, return 0.\n * @hide\n */\n @TestApi\n public float getAspectRatio() {\n if (mAspectRatio != null) {\n return mAspectRatio.floatValue();\n }\n return 0f;\n }\n\n /**\n * @hide\n */\n public Rational getAspectRatioRational() {\n return mAspectRatio;\n }\n\n /**\n * @return whether the aspect ratio is set.\n * @hide\n */\n public boolean hasSetAspectRatio() {\n return mAspectRatio != null;\n }\n\n /**\n * @return the set of user actions.\n * @hide\n */\n @TestApi\n public List getActions() {\n return mUserActions;\n }\n\n /**\n * @return whether the user actions are set.\n * @hide\n */\n public boolean hasSetActions() {\n return mUserActions != null;\n }\n\n /**\n * Truncates the set of actions to the given {@param size}.\n * @hide\n */\n public void truncateActions(int size) {\n if (hasSetActions()) {\n mUserActions = mUserActions.subList(0, Math.min(mUserActions.size(), size));\n }\n }\n\n /**\n * @return the source rect hint\n * @hide\n */\n @TestApi\n public Rect getSourceRectHint() {\n return mSourceRectHint;\n }\n\n /**\n * @return whether there are launch bounds set\n * @hide\n */\n public boolean hasSourceBoundsHint() {\n return mSourceRectHint != null && !mSourceRectHint.isEmpty();\n }\n\n /**\n * @return True if no parameters are set\n * @hide\n */\n public boolean empty() {\n return !hasSourceBoundsHint() && !hasSetActions() && !hasSetAspectRatio();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n if (mAspectRatio != null) {\n out.writeInt(1);\n out.writeInt(mAspectRatio.getNumerator());\n out.writeInt(mAspectRatio.getDenominator());\n } else {\n out.writeInt(0);\n }\n if (mUserActions != null) {\n out.writeInt(1);\n out.writeParcelableList(mUserActions, 0);\n } else {\n out.writeInt(0);\n }\n if (mSourceRectHint != null) {\n out.writeInt(1);\n mSourceRectHint.writeToParcel(out, 0);\n } else {\n out.writeInt(0);\n }\n }\n\n @android.annotation.NonNull\n public static final Creator CREATOR = new Creator() {\n\n public PictureInPictureParams createFromParcel(Parcel in) {\n return new PictureInPictureParams(in);\n }\n\n public PictureInPictureParams[] newArray(int size) {\n return new PictureInPictureParams[size];\n }\n };\n}\n"} {"task_id": "Java_246", "language": "Java", "task_type": "single_line", "source_file": "java/github/LineageOS/android_frameworks_base/core/java/android/app/PictureInPictureParams.java", "mask_start_position": 5807, "mask_end_position": 5828, "canonical_solution": "mAspectRatio != null;", "pre_mask_code": "package android.app;\n\nimport android.annotation.Nullable;\nimport android.annotation.TestApi;\nimport android.graphics.Rect;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.util.Rational;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Represents a set of parameters used to initialize and update an Activity in picture-in-picture\n * mode.\n */\npublic final class PictureInPictureParams implements Parcelable {\n\n /**\n * Builder class for {@link PictureInPictureParams} objects.\n */\n public static class Builder {\n\n @Nullable\n private Rational mAspectRatio;\n\n @Nullable\n private List mUserActions;\n\n @Nullable\n private Rect mSourceRectHint;\n\n /**\n * Sets the aspect ratio. This aspect ratio is defined as the desired width / height, and\n * does not change upon device rotation.\n *\n * @param aspectRatio the new aspect ratio for the activity in picture-in-picture, must be\n * between 2.39:1 and 1:2.39 (inclusive).\n *\n * @return this builder instance.\n */\n public Builder setAspectRatio(Rational aspectRatio) {\n mAspectRatio = aspectRatio;\n return this;\n }\n\n /**\n * Sets the user actions. If there are more than\n * {@link Activity#getMaxNumPictureInPictureActions()} actions, then the input list\n * will be truncated to that number.\n *\n * @param actions the new actions to show in the picture-in-picture menu.\n *\n * @return this builder instance.\n *\n * @see RemoteAction\n */\n public Builder setActions(List actions) {\n if (mUserActions != null) {\n mUserActions = null;\n }\n if (actions != null) {\n mUserActions = new ArrayList<>(actions);\n }\n return this;\n }\n\n /**\n * Sets the source bounds hint. These bounds are only used when an activity first enters\n * picture-in-picture, and describe the bounds in window coordinates of activity entering\n * picture-in-picture that will be visible following the transition. For the best effect,\n * these bounds should also match the aspect ratio in the arguments.\n *\n * @param launchBounds window-coordinate bounds indicating the area of the activity that\n * will still be visible following the transition into picture-in-picture (eg. the video\n * view bounds in a video player)\n *\n * @return this builder instance.\n */\n public Builder setSourceRectHint(Rect launchBounds) {\n if (launchBounds == null) {\n mSourceRectHint = null;\n } else {\n mSourceRectHint = new Rect(launchBounds);\n }\n return this;\n }\n\n /**\n * @return an immutable {@link PictureInPictureParams} to be used when entering or updating\n * the activity in picture-in-picture.\n *\n * @see Activity#enterPictureInPictureMode(PictureInPictureParams)\n * @see Activity#setPictureInPictureParams(PictureInPictureParams)\n */\n public PictureInPictureParams build() {\n PictureInPictureParams params = new PictureInPictureParams(mAspectRatio, mUserActions, mSourceRectHint);\n return params;\n }\n }\n\n /**\n * The expected aspect ratio of the picture-in-picture.\n */\n @Nullable\n private Rational mAspectRatio;\n\n /**\n * The set of actions that are associated with this activity when in picture-in-picture.\n */\n @Nullable\n private List mUserActions;\n\n /**\n * The source bounds hint used when entering picture-in-picture, relative to the window bounds.\n * We can use this internally for the transition into picture-in-picture to ensure that a\n * particular source rect is visible throughout the whole transition.\n */\n @Nullable\n private Rect mSourceRectHint;\n\n PictureInPictureParams() {\n }\n\n PictureInPictureParams(Parcel in) {\n if (in.readInt() != 0) {\n mAspectRatio = new Rational(in.readInt(), in.readInt());\n }\n if (in.readInt() != 0) {\n mUserActions = new ArrayList<>();\n in.readParcelableList(mUserActions, RemoteAction.class.getClassLoader());\n }\n if (in.readInt() != 0) {\n mSourceRectHint = Rect.CREATOR.createFromParcel(in);\n }\n }\n\n PictureInPictureParams(Rational aspectRatio, List actions, Rect sourceRectHint) {\n mAspectRatio = aspectRatio;\n mUserActions = actions;\n mSourceRectHint = sourceRectHint;\n }\n\n /**\n * Copies the set parameters from the other picture-in-picture args.\n * @hide\n */\n public void copyOnlySet(PictureInPictureParams otherArgs) {\n if (otherArgs.hasSetAspectRatio()) {\n mAspectRatio = otherArgs.mAspectRatio;\n }\n if (otherArgs.hasSetActions()) {\n mUserActions = otherArgs.mUserActions;\n }\n if (otherArgs.hasSourceBoundsHint()) {\n mSourceRectHint = new Rect(otherArgs.getSourceRectHint());\n }\n }\n\n /**\n * @return the aspect ratio. If none is set, return 0.\n * @hide\n */\n @TestApi\n public float getAspectRatio() {\n if (mAspectRatio != null) {\n return mAspectRatio.floatValue();\n }\n return 0f;\n }\n\n /**\n * @hide\n */\n public Rational getAspectRatioRational() {\n return mAspectRatio;\n }\n\n /**\n * @return whether the aspect ratio is set.\n * @hide\n */\n public boolean hasSetAspectRatio() {\n return ", "post_mask_code": "\n }\n\n /**\n * @return the set of user actions.\n * @hide\n */\n @TestApi\n public List getActions() {\n return mUserActions;\n }\n\n /**\n * @return whether the user actions are set.\n * @hide\n */\n public boolean hasSetActions() {\n return mUserActions != null;\n }\n\n /**\n * Truncates the set of actions to the given {@param size}.\n * @hide\n */\n public void truncateActions(int size) {\n if (hasSetActions()) {\n mUserActions = mUserActions.subList(0, Math.min(mUserActions.size(), size));\n }\n }\n\n /**\n * @return the source rect hint\n * @hide\n */\n @TestApi\n public Rect getSourceRectHint() {\n return mSourceRectHint;\n }\n\n /**\n * @return whether there are launch bounds set\n * @hide\n */\n public boolean hasSourceBoundsHint() {\n return mSourceRectHint != null && !mSourceRectHint.isEmpty();\n }\n\n /**\n * @return True if no parameters are set\n * @hide\n */\n public boolean empty() {\n return !hasSourceBoundsHint() && !hasSetActions() && !hasSetAspectRatio();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n if (mAspectRatio != null) {\n out.writeInt(1);\n out.writeInt(mAspectRatio.getNumerator());\n out.writeInt(mAspectRatio.getDenominator());\n } else {\n out.writeInt(0);\n }\n if (mUserActions != null) {\n out.writeInt(1);\n out.writeParcelableList(mUserActions, 0);\n } else {\n out.writeInt(0);\n }\n if (mSourceRectHint != null) {\n out.writeInt(1);\n mSourceRectHint.writeToParcel(out, 0);\n } else {\n out.writeInt(0);\n }\n }\n\n @android.annotation.NonNull\n public static final Creator CREATOR = new Creator() {\n\n public PictureInPictureParams createFromParcel(Parcel in) {\n return new PictureInPictureParams(in);\n }\n\n public PictureInPictureParams[] newArray(int size) {\n return new PictureInPictureParams[size];\n }\n };\n}\n"} {"task_id": "Java_247", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/LineageOS/android_frameworks_base/core/java/android/app/PictureInPictureParams.java", "mask_start_position": 6081, "mask_end_position": 6156, "canonical_solution": "public boolean hasSetActions() {\n return mUserActions != null;\n }", "pre_mask_code": "package android.app;\n\nimport android.annotation.Nullable;\nimport android.annotation.TestApi;\nimport android.graphics.Rect;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.util.Rational;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Represents a set of parameters used to initialize and update an Activity in picture-in-picture\n * mode.\n */\npublic final class PictureInPictureParams implements Parcelable {\n\n /**\n * Builder class for {@link PictureInPictureParams} objects.\n */\n public static class Builder {\n\n @Nullable\n private Rational mAspectRatio;\n\n @Nullable\n private List mUserActions;\n\n @Nullable\n private Rect mSourceRectHint;\n\n /**\n * Sets the aspect ratio. This aspect ratio is defined as the desired width / height, and\n * does not change upon device rotation.\n *\n * @param aspectRatio the new aspect ratio for the activity in picture-in-picture, must be\n * between 2.39:1 and 1:2.39 (inclusive).\n *\n * @return this builder instance.\n */\n public Builder setAspectRatio(Rational aspectRatio) {\n mAspectRatio = aspectRatio;\n return this;\n }\n\n /**\n * Sets the user actions. If there are more than\n * {@link Activity#getMaxNumPictureInPictureActions()} actions, then the input list\n * will be truncated to that number.\n *\n * @param actions the new actions to show in the picture-in-picture menu.\n *\n * @return this builder instance.\n *\n * @see RemoteAction\n */\n public Builder setActions(List actions) {\n if (mUserActions != null) {\n mUserActions = null;\n }\n if (actions != null) {\n mUserActions = new ArrayList<>(actions);\n }\n return this;\n }\n\n /**\n * Sets the source bounds hint. These bounds are only used when an activity first enters\n * picture-in-picture, and describe the bounds in window coordinates of activity entering\n * picture-in-picture that will be visible following the transition. For the best effect,\n * these bounds should also match the aspect ratio in the arguments.\n *\n * @param launchBounds window-coordinate bounds indicating the area of the activity that\n * will still be visible following the transition into picture-in-picture (eg. the video\n * view bounds in a video player)\n *\n * @return this builder instance.\n */\n public Builder setSourceRectHint(Rect launchBounds) {\n if (launchBounds == null) {\n mSourceRectHint = null;\n } else {\n mSourceRectHint = new Rect(launchBounds);\n }\n return this;\n }\n\n /**\n * @return an immutable {@link PictureInPictureParams} to be used when entering or updating\n * the activity in picture-in-picture.\n *\n * @see Activity#enterPictureInPictureMode(PictureInPictureParams)\n * @see Activity#setPictureInPictureParams(PictureInPictureParams)\n */\n public PictureInPictureParams build() {\n PictureInPictureParams params = new PictureInPictureParams(mAspectRatio, mUserActions, mSourceRectHint);\n return params;\n }\n }\n\n /**\n * The expected aspect ratio of the picture-in-picture.\n */\n @Nullable\n private Rational mAspectRatio;\n\n /**\n * The set of actions that are associated with this activity when in picture-in-picture.\n */\n @Nullable\n private List mUserActions;\n\n /**\n * The source bounds hint used when entering picture-in-picture, relative to the window bounds.\n * We can use this internally for the transition into picture-in-picture to ensure that a\n * particular source rect is visible throughout the whole transition.\n */\n @Nullable\n private Rect mSourceRectHint;\n\n PictureInPictureParams() {\n }\n\n PictureInPictureParams(Parcel in) {\n if (in.readInt() != 0) {\n mAspectRatio = new Rational(in.readInt(), in.readInt());\n }\n if (in.readInt() != 0) {\n mUserActions = new ArrayList<>();\n in.readParcelableList(mUserActions, RemoteAction.class.getClassLoader());\n }\n if (in.readInt() != 0) {\n mSourceRectHint = Rect.CREATOR.createFromParcel(in);\n }\n }\n\n PictureInPictureParams(Rational aspectRatio, List actions, Rect sourceRectHint) {\n mAspectRatio = aspectRatio;\n mUserActions = actions;\n mSourceRectHint = sourceRectHint;\n }\n\n /**\n * Copies the set parameters from the other picture-in-picture args.\n * @hide\n */\n public void copyOnlySet(PictureInPictureParams otherArgs) {\n if (otherArgs.hasSetAspectRatio()) {\n mAspectRatio = otherArgs.mAspectRatio;\n }\n if (otherArgs.hasSetActions()) {\n mUserActions = otherArgs.mUserActions;\n }\n if (otherArgs.hasSourceBoundsHint()) {\n mSourceRectHint = new Rect(otherArgs.getSourceRectHint());\n }\n }\n\n /**\n * @return the aspect ratio. If none is set, return 0.\n * @hide\n */\n @TestApi\n public float getAspectRatio() {\n if (mAspectRatio != null) {\n return mAspectRatio.floatValue();\n }\n return 0f;\n }\n\n /**\n * @hide\n */\n public Rational getAspectRatioRational() {\n return mAspectRatio;\n }\n\n /**\n * @return whether the aspect ratio is set.\n * @hide\n */\n public boolean hasSetAspectRatio() {\n return mAspectRatio != null;\n }\n\n /**\n * @return the set of user actions.\n * @hide\n */\n @TestApi\n public List getActions() {\n return mUserActions;\n }\n\n /**\n * @return whether the user actions are set.\n * @hide\n */\n ", "post_mask_code": "\n\n /**\n * Truncates the set of actions to the given {@param size}.\n * @hide\n */\n public void truncateActions(int size) {\n if (hasSetActions()) {\n mUserActions = mUserActions.subList(0, Math.min(mUserActions.size(), size));\n }\n }\n\n /**\n * @return the source rect hint\n * @hide\n */\n @TestApi\n public Rect getSourceRectHint() {\n return mSourceRectHint;\n }\n\n /**\n * @return whether there are launch bounds set\n * @hide\n */\n public boolean hasSourceBoundsHint() {\n return mSourceRectHint != null && !mSourceRectHint.isEmpty();\n }\n\n /**\n * @return True if no parameters are set\n * @hide\n */\n public boolean empty() {\n return !hasSourceBoundsHint() && !hasSetActions() && !hasSetAspectRatio();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n if (mAspectRatio != null) {\n out.writeInt(1);\n out.writeInt(mAspectRatio.getNumerator());\n out.writeInt(mAspectRatio.getDenominator());\n } else {\n out.writeInt(0);\n }\n if (mUserActions != null) {\n out.writeInt(1);\n out.writeParcelableList(mUserActions, 0);\n } else {\n out.writeInt(0);\n }\n if (mSourceRectHint != null) {\n out.writeInt(1);\n mSourceRectHint.writeToParcel(out, 0);\n } else {\n out.writeInt(0);\n }\n }\n\n @android.annotation.NonNull\n public static final Creator CREATOR = new Creator() {\n\n public PictureInPictureParams createFromParcel(Parcel in) {\n return new PictureInPictureParams(in);\n }\n\n public PictureInPictureParams[] newArray(int size) {\n return new PictureInPictureParams[size];\n }\n };\n}\n"} {"task_id": "Java_248", "language": "Java", "task_type": "if_statement", "source_file": "java/github/LineageOS/android_frameworks_base/core/java/android/app/PictureInPictureParams.java", "mask_start_position": 2735, "mask_end_position": 2895, "canonical_solution": "if (launchBounds == null) {\n mSourceRectHint = null;\n } else {\n mSourceRectHint = new Rect(launchBounds);\n }", "pre_mask_code": "package android.app;\n\nimport android.annotation.Nullable;\nimport android.annotation.TestApi;\nimport android.graphics.Rect;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.util.Rational;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Represents a set of parameters used to initialize and update an Activity in picture-in-picture\n * mode.\n */\npublic final class PictureInPictureParams implements Parcelable {\n\n /**\n * Builder class for {@link PictureInPictureParams} objects.\n */\n public static class Builder {\n\n @Nullable\n private Rational mAspectRatio;\n\n @Nullable\n private List mUserActions;\n\n @Nullable\n private Rect mSourceRectHint;\n\n /**\n * Sets the aspect ratio. This aspect ratio is defined as the desired width / height, and\n * does not change upon device rotation.\n *\n * @param aspectRatio the new aspect ratio for the activity in picture-in-picture, must be\n * between 2.39:1 and 1:2.39 (inclusive).\n *\n * @return this builder instance.\n */\n public Builder setAspectRatio(Rational aspectRatio) {\n mAspectRatio = aspectRatio;\n return this;\n }\n\n /**\n * Sets the user actions. If there are more than\n * {@link Activity#getMaxNumPictureInPictureActions()} actions, then the input list\n * will be truncated to that number.\n *\n * @param actions the new actions to show in the picture-in-picture menu.\n *\n * @return this builder instance.\n *\n * @see RemoteAction\n */\n public Builder setActions(List actions) {\n if (mUserActions != null) {\n mUserActions = null;\n }\n if (actions != null) {\n mUserActions = new ArrayList<>(actions);\n }\n return this;\n }\n\n /**\n * Sets the source bounds hint. These bounds are only used when an activity first enters\n * picture-in-picture, and describe the bounds in window coordinates of activity entering\n * picture-in-picture that will be visible following the transition. For the best effect,\n * these bounds should also match the aspect ratio in the arguments.\n *\n * @param launchBounds window-coordinate bounds indicating the area of the activity that\n * will still be visible following the transition into picture-in-picture (eg. the video\n * view bounds in a video player)\n *\n * @return this builder instance.\n */\n public Builder setSourceRectHint(Rect launchBounds) {\n ", "post_mask_code": "\n return this;\n }\n\n /**\n * @return an immutable {@link PictureInPictureParams} to be used when entering or updating\n * the activity in picture-in-picture.\n *\n * @see Activity#enterPictureInPictureMode(PictureInPictureParams)\n * @see Activity#setPictureInPictureParams(PictureInPictureParams)\n */\n public PictureInPictureParams build() {\n PictureInPictureParams params = new PictureInPictureParams(mAspectRatio, mUserActions, mSourceRectHint);\n return params;\n }\n }\n\n /**\n * The expected aspect ratio of the picture-in-picture.\n */\n @Nullable\n private Rational mAspectRatio;\n\n /**\n * The set of actions that are associated with this activity when in picture-in-picture.\n */\n @Nullable\n private List mUserActions;\n\n /**\n * The source bounds hint used when entering picture-in-picture, relative to the window bounds.\n * We can use this internally for the transition into picture-in-picture to ensure that a\n * particular source rect is visible throughout the whole transition.\n */\n @Nullable\n private Rect mSourceRectHint;\n\n PictureInPictureParams() {\n }\n\n PictureInPictureParams(Parcel in) {\n if (in.readInt() != 0) {\n mAspectRatio = new Rational(in.readInt(), in.readInt());\n }\n if (in.readInt() != 0) {\n mUserActions = new ArrayList<>();\n in.readParcelableList(mUserActions, RemoteAction.class.getClassLoader());\n }\n if (in.readInt() != 0) {\n mSourceRectHint = Rect.CREATOR.createFromParcel(in);\n }\n }\n\n PictureInPictureParams(Rational aspectRatio, List actions, Rect sourceRectHint) {\n mAspectRatio = aspectRatio;\n mUserActions = actions;\n mSourceRectHint = sourceRectHint;\n }\n\n /**\n * Copies the set parameters from the other picture-in-picture args.\n * @hide\n */\n public void copyOnlySet(PictureInPictureParams otherArgs) {\n if (otherArgs.hasSetAspectRatio()) {\n mAspectRatio = otherArgs.mAspectRatio;\n }\n if (otherArgs.hasSetActions()) {\n mUserActions = otherArgs.mUserActions;\n }\n if (otherArgs.hasSourceBoundsHint()) {\n mSourceRectHint = new Rect(otherArgs.getSourceRectHint());\n }\n }\n\n /**\n * @return the aspect ratio. If none is set, return 0.\n * @hide\n */\n @TestApi\n public float getAspectRatio() {\n if (mAspectRatio != null) {\n return mAspectRatio.floatValue();\n }\n return 0f;\n }\n\n /**\n * @hide\n */\n public Rational getAspectRatioRational() {\n return mAspectRatio;\n }\n\n /**\n * @return whether the aspect ratio is set.\n * @hide\n */\n public boolean hasSetAspectRatio() {\n return mAspectRatio != null;\n }\n\n /**\n * @return the set of user actions.\n * @hide\n */\n @TestApi\n public List getActions() {\n return mUserActions;\n }\n\n /**\n * @return whether the user actions are set.\n * @hide\n */\n public boolean hasSetActions() {\n return mUserActions != null;\n }\n\n /**\n * Truncates the set of actions to the given {@param size}.\n * @hide\n */\n public void truncateActions(int size) {\n if (hasSetActions()) {\n mUserActions = mUserActions.subList(0, Math.min(mUserActions.size(), size));\n }\n }\n\n /**\n * @return the source rect hint\n * @hide\n */\n @TestApi\n public Rect getSourceRectHint() {\n return mSourceRectHint;\n }\n\n /**\n * @return whether there are launch bounds set\n * @hide\n */\n public boolean hasSourceBoundsHint() {\n return mSourceRectHint != null && !mSourceRectHint.isEmpty();\n }\n\n /**\n * @return True if no parameters are set\n * @hide\n */\n public boolean empty() {\n return !hasSourceBoundsHint() && !hasSetActions() && !hasSetAspectRatio();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n if (mAspectRatio != null) {\n out.writeInt(1);\n out.writeInt(mAspectRatio.getNumerator());\n out.writeInt(mAspectRatio.getDenominator());\n } else {\n out.writeInt(0);\n }\n if (mUserActions != null) {\n out.writeInt(1);\n out.writeParcelableList(mUserActions, 0);\n } else {\n out.writeInt(0);\n }\n if (mSourceRectHint != null) {\n out.writeInt(1);\n mSourceRectHint.writeToParcel(out, 0);\n } else {\n out.writeInt(0);\n }\n }\n\n @android.annotation.NonNull\n public static final Creator CREATOR = new Creator() {\n\n public PictureInPictureParams createFromParcel(Parcel in) {\n return new PictureInPictureParams(in);\n }\n\n public PictureInPictureParams[] newArray(int size) {\n return new PictureInPictureParams[size];\n }\n };\n}\n"} {"task_id": "Java_249", "language": "Java", "task_type": "empty", "source_file": "java/github/LineageOS/android_frameworks_base/core/java/android/app/PictureInPictureParams.java", "mask_start_position": 5671, "mask_end_position": 5671, "canonical_solution": "", "pre_mask_code": "package android.app;\n\nimport android.annotation.Nullable;\nimport android.annotation.TestApi;\nimport android.graphics.Rect;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.util.Rational;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Represents a set of parameters used to initialize and update an Activity in picture-in-picture\n * mode.\n */\npublic final class PictureInPictureParams implements Parcelable {\n\n /**\n * Builder class for {@link PictureInPictureParams} objects.\n */\n public static class Builder {\n\n @Nullable\n private Rational mAspectRatio;\n\n @Nullable\n private List mUserActions;\n\n @Nullable\n private Rect mSourceRectHint;\n\n /**\n * Sets the aspect ratio. This aspect ratio is defined as the desired width / height, and\n * does not change upon device rotation.\n *\n * @param aspectRatio the new aspect ratio for the activity in picture-in-picture, must be\n * between 2.39:1 and 1:2.39 (inclusive).\n *\n * @return this builder instance.\n */\n public Builder setAspectRatio(Rational aspectRatio) {\n mAspectRatio = aspectRatio;\n return this;\n }\n\n /**\n * Sets the user actions. If there are more than\n * {@link Activity#getMaxNumPictureInPictureActions()} actions, then the input list\n * will be truncated to that number.\n *\n * @param actions the new actions to show in the picture-in-picture menu.\n *\n * @return this builder instance.\n *\n * @see RemoteAction\n */\n public Builder setActions(List actions) {\n if (mUserActions != null) {\n mUserActions = null;\n }\n if (actions != null) {\n mUserActions = new ArrayList<>(actions);\n }\n return this;\n }\n\n /**\n * Sets the source bounds hint. These bounds are only used when an activity first enters\n * picture-in-picture, and describe the bounds in window coordinates of activity entering\n * picture-in-picture that will be visible following the transition. For the best effect,\n * these bounds should also match the aspect ratio in the arguments.\n *\n * @param launchBounds window-coordinate bounds indicating the area of the activity that\n * will still be visible following the transition into picture-in-picture (eg. the video\n * view bounds in a video player)\n *\n * @return this builder instance.\n */\n public Builder setSourceRectHint(Rect launchBounds) {\n if (launchBounds == null) {\n mSourceRectHint = null;\n } else {\n mSourceRectHint = new Rect(launchBounds);\n }\n return this;\n }\n\n /**\n * @return an immutable {@link PictureInPictureParams} to be used when entering or updating\n * the activity in picture-in-picture.\n *\n * @see Activity#enterPictureInPictureMode(PictureInPictureParams)\n * @see Activity#setPictureInPictureParams(PictureInPictureParams)\n */\n public PictureInPictureParams build() {\n PictureInPictureParams params = new PictureInPictureParams(mAspectRatio, mUserActions, mSourceRectHint);\n return params;\n }\n }\n\n /**\n * The expected aspect ratio of the picture-in-picture.\n */\n @Nullable\n private Rational mAspectRatio;\n\n /**\n * The set of actions that are associated with this activity when in picture-in-picture.\n */\n @Nullable\n private List mUserActions;\n\n /**\n * The source bounds hint used when entering picture-in-picture, relative to the window bounds.\n * We can use this internally for the transition into picture-in-picture to ensure that a\n * particular source rect is visible throughout the whole transition.\n */\n @Nullable\n private Rect mSourceRectHint;\n\n PictureInPictureParams() {\n }\n\n PictureInPictureParams(Parcel in) {\n if (in.readInt() != 0) {\n mAspectRatio = new Rational(in.readInt(), in.readInt());\n }\n if (in.readInt() != 0) {\n mUserActions = new ArrayList<>();\n in.readParcelableList(mUserActions, RemoteAction.class.getClassLoader());\n }\n if (in.readInt() != 0) {\n mSourceRectHint = Rect.CREATOR.createFromParcel(in);\n }\n }\n\n PictureInPictureParams(Rational aspectRatio, List actions, Rect sourceRectHint) {\n mAspectRatio = aspectRatio;\n mUserActions = actions;\n mSourceRectHint = sourceRectHint;\n }\n\n /**\n * Copies the set parameters from the other picture-in-picture args.\n * @hide\n */\n public void copyOnlySet(PictureInPictureParams otherArgs) {\n if (otherArgs.hasSetAspectRatio()) {\n mAspectRatio = otherArgs.mAspectRatio;\n }\n if (otherArgs.hasSetActions()) {\n mUserActions = otherArgs.mUserActions;\n }\n if (otherArgs.hasSourceBoundsHint()) {\n mSourceRectHint = new Rect(otherArgs.getSourceRectHint());\n }\n }\n\n /**\n * @return the aspect ratio. If none is set, return 0.\n * @hide\n */\n @TestApi\n public float getAspectRatio() {\n if (mAspectRatio != null) {\n return mAspectRatio.floatValue();\n }\n return 0f;\n }\n\n /**\n * @hide\n */\n public Rational getAspectRatioRational() {\n return mAspectRatio;\n ", "post_mask_code": "}\n\n /**\n * @return whether the aspect ratio is set.\n * @hide\n */\n public boolean hasSetAspectRatio() {\n return mAspectRatio != null;\n }\n\n /**\n * @return the set of user actions.\n * @hide\n */\n @TestApi\n public List getActions() {\n return mUserActions;\n }\n\n /**\n * @return whether the user actions are set.\n * @hide\n */\n public boolean hasSetActions() {\n return mUserActions != null;\n }\n\n /**\n * Truncates the set of actions to the given {@param size}.\n * @hide\n */\n public void truncateActions(int size) {\n if (hasSetActions()) {\n mUserActions = mUserActions.subList(0, Math.min(mUserActions.size(), size));\n }\n }\n\n /**\n * @return the source rect hint\n * @hide\n */\n @TestApi\n public Rect getSourceRectHint() {\n return mSourceRectHint;\n }\n\n /**\n * @return whether there are launch bounds set\n * @hide\n */\n public boolean hasSourceBoundsHint() {\n return mSourceRectHint != null && !mSourceRectHint.isEmpty();\n }\n\n /**\n * @return True if no parameters are set\n * @hide\n */\n public boolean empty() {\n return !hasSourceBoundsHint() && !hasSetActions() && !hasSetAspectRatio();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n if (mAspectRatio != null) {\n out.writeInt(1);\n out.writeInt(mAspectRatio.getNumerator());\n out.writeInt(mAspectRatio.getDenominator());\n } else {\n out.writeInt(0);\n }\n if (mUserActions != null) {\n out.writeInt(1);\n out.writeParcelableList(mUserActions, 0);\n } else {\n out.writeInt(0);\n }\n if (mSourceRectHint != null) {\n out.writeInt(1);\n mSourceRectHint.writeToParcel(out, 0);\n } else {\n out.writeInt(0);\n }\n }\n\n @android.annotation.NonNull\n public static final Creator CREATOR = new Creator() {\n\n public PictureInPictureParams createFromParcel(Parcel in) {\n return new PictureInPictureParams(in);\n }\n\n public PictureInPictureParams[] newArray(int size) {\n return new PictureInPictureParams[size];\n }\n };\n}\n"} {"task_id": "Java_250", "language": "Java", "task_type": "method_signature", "source_file": "java/github/drinkjava2/frog/history/003a_legs/src/main/java/com/github/drinkjava2/frog/brain/organ/RFootDrop.java", "mask_start_position": 314, "mask_end_position": 355, "canonical_solution": "@Override\n public void active(Frog f) ", "pre_mask_code": "package com.github.drinkjava2.frog.brain.organ;\n\nimport com.github.drinkjava2.frog.Frog;\nimport com.github.drinkjava2.frog.brain.Organ;\n\n/**\n * Move down frog 1 unit if outputs of nerve cells active in this zone\n */\npublic class RFootDrop extends Organ {\n\n private static final long serialVersionUID = 1L;\n\n ", "post_mask_code": "{\n if (f.rFootStatus == \"DOWN\")\n return;\n if (activedByCells(f)) {\n actived = true;\n f.rFootStatus = \"DOWN\";\n } else\n actived = false;\n }\n}\n"} {"task_id": "Java_251", "language": "Java", "task_type": "method_body", "source_file": "java/github/drinkjava2/frog/history/003a_legs/src/main/java/com/github/drinkjava2/frog/brain/organ/RFootDrop.java", "mask_start_position": 355, "mask_end_position": 560, "canonical_solution": "{\n if (f.rFootStatus == \"DOWN\")\n return;\n if (activedByCells(f)) {\n actived = true;\n f.rFootStatus = \"DOWN\";\n } else\n actived = false;\n }", "pre_mask_code": "package com.github.drinkjava2.frog.brain.organ;\n\nimport com.github.drinkjava2.frog.Frog;\nimport com.github.drinkjava2.frog.brain.Organ;\n\n/**\n * Move down frog 1 unit if outputs of nerve cells active in this zone\n */\npublic class RFootDrop extends Organ {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public void active(Frog f) ", "post_mask_code": "\n}\n"} {"task_id": "Java_252", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/drinkjava2/frog/history/003a_legs/src/main/java/com/github/drinkjava2/frog/brain/organ/RFootDrop.java", "mask_start_position": 356, "mask_end_position": 413, "canonical_solution": "\n if (f.rFootStatus == \"DOWN\")\n return;", "pre_mask_code": "package com.github.drinkjava2.frog.brain.organ;\n\nimport com.github.drinkjava2.frog.Frog;\nimport com.github.drinkjava2.frog.brain.Organ;\n\n/**\n * Move down frog 1 unit if outputs of nerve cells active in this zone\n */\npublic class RFootDrop extends Organ {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public void active(Frog f) {", "post_mask_code": "\n if (activedByCells(f)) {\n actived = true;\n f.rFootStatus = \"DOWN\";\n } else\n actived = false;\n }\n}\n"} {"task_id": "Java_253", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/drinkjava2/frog/history/003a_legs/src/main/java/com/github/drinkjava2/frog/brain/organ/RFootDrop.java", "mask_start_position": 422, "mask_end_position": 554, "canonical_solution": "if (activedByCells(f)) {\n actived = true;\n f.rFootStatus = \"DOWN\";\n } else\n actived = false;", "pre_mask_code": "package com.github.drinkjava2.frog.brain.organ;\n\nimport com.github.drinkjava2.frog.Frog;\nimport com.github.drinkjava2.frog.brain.Organ;\n\n/**\n * Move down frog 1 unit if outputs of nerve cells active in this zone\n */\npublic class RFootDrop extends Organ {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public void active(Frog f) {\n if (f.rFootStatus == \"DOWN\")\n return;\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_254", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/drinkjava2/frog/history/003a_legs/src/main/java/com/github/drinkjava2/frog/brain/organ/RFootDrop.java", "mask_start_position": 559, "mask_end_position": 560, "canonical_solution": "}", "pre_mask_code": "package com.github.drinkjava2.frog.brain.organ;\n\nimport com.github.drinkjava2.frog.Frog;\nimport com.github.drinkjava2.frog.brain.Organ;\n\n/**\n * Move down frog 1 unit if outputs of nerve cells active in this zone\n */\npublic class RFootDrop extends Organ {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public void active(Frog f) {\n if (f.rFootStatus == \"DOWN\")\n return;\n if (activedByCells(f)) {\n actived = true;\n f.rFootStatus = \"DOWN\";\n } else\n actived = false;\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_255", "language": "Java", "task_type": "if_statement", "source_file": "java/github/drinkjava2/frog/history/003a_legs/src/main/java/com/github/drinkjava2/frog/brain/organ/RFootDrop.java", "mask_start_position": 422, "mask_end_position": 554, "canonical_solution": "if (activedByCells(f)) {\n actived = true;\n f.rFootStatus = \"DOWN\";\n } else\n actived = false;", "pre_mask_code": "package com.github.drinkjava2.frog.brain.organ;\n\nimport com.github.drinkjava2.frog.Frog;\nimport com.github.drinkjava2.frog.brain.Organ;\n\n/**\n * Move down frog 1 unit if outputs of nerve cells active in this zone\n */\npublic class RFootDrop extends Organ {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public void active(Frog f) {\n if (f.rFootStatus == \"DOWN\")\n return;\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_256", "language": "Java", "task_type": "empty", "source_file": "java/github/drinkjava2/frog/history/003a_legs/src/main/java/com/github/drinkjava2/frog/brain/organ/RFootDrop.java", "mask_start_position": 210, "mask_end_position": 210, "canonical_solution": "", "pre_mask_code": "package com.github.drinkjava2.frog.brain.organ;\n\nimport com.github.drinkjava2.frog.Frog;\nimport com.github.drinkjava2.frog.brain.Organ;\n\n/**\n * Move down frog 1 unit if outputs of nerve cells active in this zon", "post_mask_code": "e\n */\npublic class RFootDrop extends Organ {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public void active(Frog f) {\n if (f.rFootStatus == \"DOWN\")\n return;\n if (activedByCells(f)) {\n actived = true;\n f.rFootStatus = \"DOWN\";\n } else\n actived = false;\n }\n}\n"} {"task_id": "Java_257", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/manifoldcf/framework/pull-agent/src/main/java/org/apache/manifoldcf/crawler/system/JobResetThread.java", "mask_start_position": 9347, "mask_end_position": 9544, "canonical_solution": "protected static void doEndNotifications(IJobDescription jobDescription, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException ", "pre_mask_code": "package org.apache.manifoldcf.crawler.system;\n\nimport org.apache.manifoldcf.core.interfaces.*;\nimport org.apache.manifoldcf.agents.interfaces.*;\nimport org.apache.manifoldcf.crawler.interfaces.*;\nimport org.apache.manifoldcf.crawler.system.Logging;\nimport java.util.*;\nimport java.lang.reflect.*;\n\n/**\n * This class represents the thread that notices jobs that have completed their shutdown phase, and puts them in the\n * \"notify connector\" state.\n */\npublic class JobResetThread extends Thread {\n\n public static final String _rcsid = \"@(#)$Id: JobResetThread.java 991295 2010-08-31 19:12:14Z kwright $\";\n\n // Local data\n /**\n * Process ID\n */\n protected final String processID;\n\n public JobResetThread(String processID) throws ManifoldCFException {\n super();\n setName(\"Job reset thread\");\n setDaemon(true);\n this.processID = processID;\n }\n\n public void run() {\n try {\n // Create a thread context object.\n IThreadContext threadContext = ThreadContextFactory.make();\n IJobManager jobManager = JobManagerFactory.make(threadContext);\n IRepositoryConnectionManager connectionManager = RepositoryConnectionManagerFactory.make(threadContext);\n INotificationConnectionManager notificationManager = NotificationConnectionManagerFactory.make(threadContext);\n INotificationConnectorPool notificationPool = NotificationConnectorPoolFactory.make(threadContext);\n // Loop\n while (true) {\n // Do another try/catch around everything in the loop\n try {\n // See if there are any completed jobs\n long currentTime = System.currentTimeMillis();\n List jobStops = new ArrayList();\n List jobStopNotifications = new ArrayList();\n jobManager.finishJobStops(currentTime, jobStops, jobStopNotifications);\n List jobResumes = new ArrayList();\n jobManager.finishJobResumes(currentTime, jobResumes);\n List jobCompletions = new ArrayList();\n jobManager.resetJobs(currentTime, jobCompletions);\n // If there were any job aborts, we must reprioritize all active documents, since we've done something\n // not predicted by the algorithm that assigned those priorities. This is, of course, quite expensive,\n // but it cannot be helped (at least, I cannot find a way to avoid it).\n if (jobStops.size() > 0) {\n Logging.threads.debug(\"Job reset thread reprioritizing documents...\");\n ManifoldCF.resetAllDocumentPriorities(threadContext, processID);\n Logging.threads.debug(\"Job reset thread done reprioritizing documents.\");\n }\n int k = 0;\n while (k < jobStops.size()) {\n IJobDescription desc = jobStops.get(k);\n Integer notificationType = jobStopNotifications.get(k);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBSTOP, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doStopNotifications(desc, notificationType, notificationManager, notificationPool);\n k++;\n }\n k = 0;\n while (k < jobResumes.size()) {\n IJobDescription desc = jobResumes.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBCONTINUE, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n }\n k = 0;\n while (k < jobCompletions.size()) {\n IJobDescription desc = jobCompletions.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBEND, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doEndNotifications(desc, notificationManager, notificationPool);\n }\n ManifoldCF.sleep(10000L);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n break;\n if (e.getErrorCode() == ManifoldCFException.DATABASE_CONNECTION_ERROR) {\n Logging.threads.error(\"Job reset thread aborting and restarting due to database connection reset: \" + e.getMessage(), e);\n try {\n // Give the database a chance to catch up/wake up\n ManifoldCF.sleep(10000L);\n } catch (InterruptedException se) {\n break;\n }\n continue;\n }\n // Log it, but keep the thread alive\n Logging.threads.error(\"Exception tossed: \" + e.getMessage(), e);\n if (e.getErrorCode() == ManifoldCFException.SETUP_ERROR) {\n // Shut the whole system down!\n ManifoldCF.systemExit(1);\n }\n } catch (InterruptedException e) {\n // We're supposed to quit\n break;\n } catch (OutOfMemoryError e) {\n System.err.println(\"agents process ran out of memory - shutting down\");\n e.printStackTrace(System.err);\n ManifoldCF.systemExit(-200);\n } catch (Throwable e) {\n // A more severe error - but stay alive\n Logging.threads.fatal(\"Error tossed: \" + e.getMessage(), e);\n }\n }\n } catch (Throwable e) {\n // Severe error on initialization\n System.err.println(\"agents process could not start - shutting down\");\n Logging.threads.fatal(\"JobResetThread initialization error tossed: \" + e.getMessage(), e);\n ManifoldCF.systemExit(-300);\n }\n }\n\n protected static void doStopNotifications(IJobDescription jobDescription, int notificationType, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n switch(notificationType) {\n case IJobManager.STOP_ERRORABORT:\n connector.notifyOfJobStopErrorAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALABORT:\n connector.notifyOfJobStopManualAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALPAUSE:\n connector.notifyOfJobStopManualPause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_SCHEDULEPAUSE:\n connector.notifyOfJobStopSchedulePause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_RESTART:\n connector.notifyOfJobStopRestart(jobDescription.getNotificationSpecification(j));\n break;\n default:\n throw new RuntimeException(\"Unhandled notification type: \" + notificationType);\n }\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n\n ", "post_mask_code": "{\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n connector.notifyOfJobEnd(jobDescription.getNotificationSpecification(j));\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n}\n"} {"task_id": "Java_258", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/manifoldcf/framework/pull-agent/src/main/java/org/apache/manifoldcf/crawler/system/JobResetThread.java", "mask_start_position": 918, "mask_end_position": 918, "canonical_solution": "", "pre_mask_code": "package org.apache.manifoldcf.crawler.system;\n\nimport org.apache.manifoldcf.core.interfaces.*;\nimport org.apache.manifoldcf.agents.interfaces.*;\nimport org.apache.manifoldcf.crawler.interfaces.*;\nimport org.apache.manifoldcf.crawler.system.Logging;\nimport java.util.*;\nimport java.lang.reflect.*;\n\n/**\n * This class represents the thread that notices jobs that have completed their shutdown phase, and puts them in the\n * \"notify connector\" state.\n */\npublic class JobResetThread extends Thread {\n\n public static final String _rcsid = \"@(#)$Id: JobResetThread.java 991295 2010-08-31 19:12:14Z kwright $\";\n\n // Local data\n /**\n * Process ID\n */\n protected final String processID;\n\n public JobResetThread(String processID) throws ManifoldCFException {\n super();\n setName(\"Job reset thread\");\n setDaemon(true);\n this.processID = processID;\n }\n\n public void run() {", "post_mask_code": "\n try {\n // Create a thread context object.\n IThreadContext threadContext = ThreadContextFactory.make();\n IJobManager jobManager = JobManagerFactory.make(threadContext);\n IRepositoryConnectionManager connectionManager = RepositoryConnectionManagerFactory.make(threadContext);\n INotificationConnectionManager notificationManager = NotificationConnectionManagerFactory.make(threadContext);\n INotificationConnectorPool notificationPool = NotificationConnectorPoolFactory.make(threadContext);\n // Loop\n while (true) {\n // Do another try/catch around everything in the loop\n try {\n // See if there are any completed jobs\n long currentTime = System.currentTimeMillis();\n List jobStops = new ArrayList();\n List jobStopNotifications = new ArrayList();\n jobManager.finishJobStops(currentTime, jobStops, jobStopNotifications);\n List jobResumes = new ArrayList();\n jobManager.finishJobResumes(currentTime, jobResumes);\n List jobCompletions = new ArrayList();\n jobManager.resetJobs(currentTime, jobCompletions);\n // If there were any job aborts, we must reprioritize all active documents, since we've done something\n // not predicted by the algorithm that assigned those priorities. This is, of course, quite expensive,\n // but it cannot be helped (at least, I cannot find a way to avoid it).\n if (jobStops.size() > 0) {\n Logging.threads.debug(\"Job reset thread reprioritizing documents...\");\n ManifoldCF.resetAllDocumentPriorities(threadContext, processID);\n Logging.threads.debug(\"Job reset thread done reprioritizing documents.\");\n }\n int k = 0;\n while (k < jobStops.size()) {\n IJobDescription desc = jobStops.get(k);\n Integer notificationType = jobStopNotifications.get(k);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBSTOP, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doStopNotifications(desc, notificationType, notificationManager, notificationPool);\n k++;\n }\n k = 0;\n while (k < jobResumes.size()) {\n IJobDescription desc = jobResumes.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBCONTINUE, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n }\n k = 0;\n while (k < jobCompletions.size()) {\n IJobDescription desc = jobCompletions.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBEND, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doEndNotifications(desc, notificationManager, notificationPool);\n }\n ManifoldCF.sleep(10000L);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n break;\n if (e.getErrorCode() == ManifoldCFException.DATABASE_CONNECTION_ERROR) {\n Logging.threads.error(\"Job reset thread aborting and restarting due to database connection reset: \" + e.getMessage(), e);\n try {\n // Give the database a chance to catch up/wake up\n ManifoldCF.sleep(10000L);\n } catch (InterruptedException se) {\n break;\n }\n continue;\n }\n // Log it, but keep the thread alive\n Logging.threads.error(\"Exception tossed: \" + e.getMessage(), e);\n if (e.getErrorCode() == ManifoldCFException.SETUP_ERROR) {\n // Shut the whole system down!\n ManifoldCF.systemExit(1);\n }\n } catch (InterruptedException e) {\n // We're supposed to quit\n break;\n } catch (OutOfMemoryError e) {\n System.err.println(\"agents process ran out of memory - shutting down\");\n e.printStackTrace(System.err);\n ManifoldCF.systemExit(-200);\n } catch (Throwable e) {\n // A more severe error - but stay alive\n Logging.threads.fatal(\"Error tossed: \" + e.getMessage(), e);\n }\n }\n } catch (Throwable e) {\n // Severe error on initialization\n System.err.println(\"agents process could not start - shutting down\");\n Logging.threads.fatal(\"JobResetThread initialization error tossed: \" + e.getMessage(), e);\n ManifoldCF.systemExit(-300);\n }\n }\n\n protected static void doStopNotifications(IJobDescription jobDescription, int notificationType, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n switch(notificationType) {\n case IJobManager.STOP_ERRORABORT:\n connector.notifyOfJobStopErrorAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALABORT:\n connector.notifyOfJobStopManualAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALPAUSE:\n connector.notifyOfJobStopManualPause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_SCHEDULEPAUSE:\n connector.notifyOfJobStopSchedulePause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_RESTART:\n connector.notifyOfJobStopRestart(jobDescription.getNotificationSpecification(j));\n break;\n default:\n throw new RuntimeException(\"Unhandled notification type: \" + notificationType);\n }\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n\n protected static void doEndNotifications(IJobDescription jobDescription, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n connector.notifyOfJobEnd(jobDescription.getNotificationSpecification(j));\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n}\n"} {"task_id": "Java_259", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/manifoldcf/framework/pull-agent/src/main/java/org/apache/manifoldcf/crawler/system/JobResetThread.java", "mask_start_position": 927, "mask_end_position": 6673, "canonical_solution": "try {\n // Create a thread context object.\n IThreadContext threadContext = ThreadContextFactory.make();\n IJobManager jobManager = JobManagerFactory.make(threadContext);\n IRepositoryConnectionManager connectionManager = RepositoryConnectionManagerFactory.make(threadContext);\n INotificationConnectionManager notificationManager = NotificationConnectionManagerFactory.make(threadContext);\n INotificationConnectorPool notificationPool = NotificationConnectorPoolFactory.make(threadContext);\n // Loop\n while (true) {\n // Do another try/catch around everything in the loop\n try {\n // See if there are any completed jobs\n long currentTime = System.currentTimeMillis();\n List jobStops = new ArrayList();\n List jobStopNotifications = new ArrayList();\n jobManager.finishJobStops(currentTime, jobStops, jobStopNotifications);\n List jobResumes = new ArrayList();\n jobManager.finishJobResumes(currentTime, jobResumes);\n List jobCompletions = new ArrayList();\n jobManager.resetJobs(currentTime, jobCompletions);\n // If there were any job aborts, we must reprioritize all active documents, since we've done something\n // not predicted by the algorithm that assigned those priorities. This is, of course, quite expensive,\n // but it cannot be helped (at least, I cannot find a way to avoid it).\n if (jobStops.size() > 0) {\n Logging.threads.debug(\"Job reset thread reprioritizing documents...\");\n ManifoldCF.resetAllDocumentPriorities(threadContext, processID);\n Logging.threads.debug(\"Job reset thread done reprioritizing documents.\");\n }\n int k = 0;\n while (k < jobStops.size()) {\n IJobDescription desc = jobStops.get(k);\n Integer notificationType = jobStopNotifications.get(k);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBSTOP, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doStopNotifications(desc, notificationType, notificationManager, notificationPool);\n k++;\n }\n k = 0;\n while (k < jobResumes.size()) {\n IJobDescription desc = jobResumes.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBCONTINUE, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n }\n k = 0;\n while (k < jobCompletions.size()) {\n IJobDescription desc = jobCompletions.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBEND, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doEndNotifications(desc, notificationManager, notificationPool);\n }\n ManifoldCF.sleep(10000L);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n break;\n if (e.getErrorCode() == ManifoldCFException.DATABASE_CONNECTION_ERROR) {\n Logging.threads.error(\"Job reset thread aborting and restarting due to database connection reset: \" + e.getMessage(), e);\n try {\n // Give the database a chance to catch up/wake up\n ManifoldCF.sleep(10000L);\n } catch (InterruptedException se) {\n break;\n }\n continue;\n }\n // Log it, but keep the thread alive\n Logging.threads.error(\"Exception tossed: \" + e.getMessage(), e);\n if (e.getErrorCode() == ManifoldCFException.SETUP_ERROR) {\n // Shut the whole system down!\n ManifoldCF.systemExit(1);\n }\n } catch (InterruptedException e) {\n // We're supposed to quit\n break;\n } catch (OutOfMemoryError e) {\n System.err.println(\"agents process ran out of memory - shutting down\");\n e.printStackTrace(System.err);\n ManifoldCF.systemExit(-200);\n } catch (Throwable e) {\n // A more severe error - but stay alive\n Logging.threads.fatal(\"Error tossed: \" + e.getMessage(), e);\n }\n }\n } catch (Throwable e) {\n // Severe error on initialization\n System.err.println(\"agents process could not start - shutting down\");\n Logging.threads.fatal(\"JobResetThread initialization error tossed: \" + e.getMessage(), e);\n ManifoldCF.systemExit(-300);\n }", "pre_mask_code": "package org.apache.manifoldcf.crawler.system;\n\nimport org.apache.manifoldcf.core.interfaces.*;\nimport org.apache.manifoldcf.agents.interfaces.*;\nimport org.apache.manifoldcf.crawler.interfaces.*;\nimport org.apache.manifoldcf.crawler.system.Logging;\nimport java.util.*;\nimport java.lang.reflect.*;\n\n/**\n * This class represents the thread that notices jobs that have completed their shutdown phase, and puts them in the\n * \"notify connector\" state.\n */\npublic class JobResetThread extends Thread {\n\n public static final String _rcsid = \"@(#)$Id: JobResetThread.java 991295 2010-08-31 19:12:14Z kwright $\";\n\n // Local data\n /**\n * Process ID\n */\n protected final String processID;\n\n public JobResetThread(String processID) throws ManifoldCFException {\n super();\n setName(\"Job reset thread\");\n setDaemon(true);\n this.processID = processID;\n }\n\n public void run() {\n ", "post_mask_code": "\n }\n\n protected static void doStopNotifications(IJobDescription jobDescription, int notificationType, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n switch(notificationType) {\n case IJobManager.STOP_ERRORABORT:\n connector.notifyOfJobStopErrorAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALABORT:\n connector.notifyOfJobStopManualAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALPAUSE:\n connector.notifyOfJobStopManualPause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_SCHEDULEPAUSE:\n connector.notifyOfJobStopSchedulePause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_RESTART:\n connector.notifyOfJobStopRestart(jobDescription.getNotificationSpecification(j));\n break;\n default:\n throw new RuntimeException(\"Unhandled notification type: \" + notificationType);\n }\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n\n protected static void doEndNotifications(IJobDescription jobDescription, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n connector.notifyOfJobEnd(jobDescription.getNotificationSpecification(j));\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n}\n"} {"task_id": "Java_260", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/manifoldcf/framework/pull-agent/src/main/java/org/apache/manifoldcf/crawler/system/JobResetThread.java", "mask_start_position": 6678, "mask_end_position": 6679, "canonical_solution": "}", "pre_mask_code": "package org.apache.manifoldcf.crawler.system;\n\nimport org.apache.manifoldcf.core.interfaces.*;\nimport org.apache.manifoldcf.agents.interfaces.*;\nimport org.apache.manifoldcf.crawler.interfaces.*;\nimport org.apache.manifoldcf.crawler.system.Logging;\nimport java.util.*;\nimport java.lang.reflect.*;\n\n/**\n * This class represents the thread that notices jobs that have completed their shutdown phase, and puts them in the\n * \"notify connector\" state.\n */\npublic class JobResetThread extends Thread {\n\n public static final String _rcsid = \"@(#)$Id: JobResetThread.java 991295 2010-08-31 19:12:14Z kwright $\";\n\n // Local data\n /**\n * Process ID\n */\n protected final String processID;\n\n public JobResetThread(String processID) throws ManifoldCFException {\n super();\n setName(\"Job reset thread\");\n setDaemon(true);\n this.processID = processID;\n }\n\n public void run() {\n try {\n // Create a thread context object.\n IThreadContext threadContext = ThreadContextFactory.make();\n IJobManager jobManager = JobManagerFactory.make(threadContext);\n IRepositoryConnectionManager connectionManager = RepositoryConnectionManagerFactory.make(threadContext);\n INotificationConnectionManager notificationManager = NotificationConnectionManagerFactory.make(threadContext);\n INotificationConnectorPool notificationPool = NotificationConnectorPoolFactory.make(threadContext);\n // Loop\n while (true) {\n // Do another try/catch around everything in the loop\n try {\n // See if there are any completed jobs\n long currentTime = System.currentTimeMillis();\n List jobStops = new ArrayList();\n List jobStopNotifications = new ArrayList();\n jobManager.finishJobStops(currentTime, jobStops, jobStopNotifications);\n List jobResumes = new ArrayList();\n jobManager.finishJobResumes(currentTime, jobResumes);\n List jobCompletions = new ArrayList();\n jobManager.resetJobs(currentTime, jobCompletions);\n // If there were any job aborts, we must reprioritize all active documents, since we've done something\n // not predicted by the algorithm that assigned those priorities. This is, of course, quite expensive,\n // but it cannot be helped (at least, I cannot find a way to avoid it).\n if (jobStops.size() > 0) {\n Logging.threads.debug(\"Job reset thread reprioritizing documents...\");\n ManifoldCF.resetAllDocumentPriorities(threadContext, processID);\n Logging.threads.debug(\"Job reset thread done reprioritizing documents.\");\n }\n int k = 0;\n while (k < jobStops.size()) {\n IJobDescription desc = jobStops.get(k);\n Integer notificationType = jobStopNotifications.get(k);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBSTOP, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doStopNotifications(desc, notificationType, notificationManager, notificationPool);\n k++;\n }\n k = 0;\n while (k < jobResumes.size()) {\n IJobDescription desc = jobResumes.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBCONTINUE, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n }\n k = 0;\n while (k < jobCompletions.size()) {\n IJobDescription desc = jobCompletions.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBEND, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doEndNotifications(desc, notificationManager, notificationPool);\n }\n ManifoldCF.sleep(10000L);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n break;\n if (e.getErrorCode() == ManifoldCFException.DATABASE_CONNECTION_ERROR) {\n Logging.threads.error(\"Job reset thread aborting and restarting due to database connection reset: \" + e.getMessage(), e);\n try {\n // Give the database a chance to catch up/wake up\n ManifoldCF.sleep(10000L);\n } catch (InterruptedException se) {\n break;\n }\n continue;\n }\n // Log it, but keep the thread alive\n Logging.threads.error(\"Exception tossed: \" + e.getMessage(), e);\n if (e.getErrorCode() == ManifoldCFException.SETUP_ERROR) {\n // Shut the whole system down!\n ManifoldCF.systemExit(1);\n }\n } catch (InterruptedException e) {\n // We're supposed to quit\n break;\n } catch (OutOfMemoryError e) {\n System.err.println(\"agents process ran out of memory - shutting down\");\n e.printStackTrace(System.err);\n ManifoldCF.systemExit(-200);\n } catch (Throwable e) {\n // A more severe error - but stay alive\n Logging.threads.fatal(\"Error tossed: \" + e.getMessage(), e);\n }\n }\n } catch (Throwable e) {\n // Severe error on initialization\n System.err.println(\"agents process could not start - shutting down\");\n Logging.threads.fatal(\"JobResetThread initialization error tossed: \" + e.getMessage(), e);\n ManifoldCF.systemExit(-300);\n }\n ", "post_mask_code": "\n\n protected static void doStopNotifications(IJobDescription jobDescription, int notificationType, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n switch(notificationType) {\n case IJobManager.STOP_ERRORABORT:\n connector.notifyOfJobStopErrorAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALABORT:\n connector.notifyOfJobStopManualAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALPAUSE:\n connector.notifyOfJobStopManualPause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_SCHEDULEPAUSE:\n connector.notifyOfJobStopSchedulePause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_RESTART:\n connector.notifyOfJobStopRestart(jobDescription.getNotificationSpecification(j));\n break;\n default:\n throw new RuntimeException(\"Unhandled notification type: \" + notificationType);\n }\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n\n protected static void doEndNotifications(IJobDescription jobDescription, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n connector.notifyOfJobEnd(jobDescription.getNotificationSpecification(j));\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n}\n"} {"task_id": "Java_261", "language": "Java", "task_type": "if_statement", "source_file": "java/github/apache/manifoldcf/framework/pull-agent/src/main/java/org/apache/manifoldcf/crawler/system/JobResetThread.java", "mask_start_position": 9144, "mask_end_position": 9229, "canonical_solution": "if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;", "pre_mask_code": "package org.apache.manifoldcf.crawler.system;\n\nimport org.apache.manifoldcf.core.interfaces.*;\nimport org.apache.manifoldcf.agents.interfaces.*;\nimport org.apache.manifoldcf.crawler.interfaces.*;\nimport org.apache.manifoldcf.crawler.system.Logging;\nimport java.util.*;\nimport java.lang.reflect.*;\n\n/**\n * This class represents the thread that notices jobs that have completed their shutdown phase, and puts them in the\n * \"notify connector\" state.\n */\npublic class JobResetThread extends Thread {\n\n public static final String _rcsid = \"@(#)$Id: JobResetThread.java 991295 2010-08-31 19:12:14Z kwright $\";\n\n // Local data\n /**\n * Process ID\n */\n protected final String processID;\n\n public JobResetThread(String processID) throws ManifoldCFException {\n super();\n setName(\"Job reset thread\");\n setDaemon(true);\n this.processID = processID;\n }\n\n public void run() {\n try {\n // Create a thread context object.\n IThreadContext threadContext = ThreadContextFactory.make();\n IJobManager jobManager = JobManagerFactory.make(threadContext);\n IRepositoryConnectionManager connectionManager = RepositoryConnectionManagerFactory.make(threadContext);\n INotificationConnectionManager notificationManager = NotificationConnectionManagerFactory.make(threadContext);\n INotificationConnectorPool notificationPool = NotificationConnectorPoolFactory.make(threadContext);\n // Loop\n while (true) {\n // Do another try/catch around everything in the loop\n try {\n // See if there are any completed jobs\n long currentTime = System.currentTimeMillis();\n List jobStops = new ArrayList();\n List jobStopNotifications = new ArrayList();\n jobManager.finishJobStops(currentTime, jobStops, jobStopNotifications);\n List jobResumes = new ArrayList();\n jobManager.finishJobResumes(currentTime, jobResumes);\n List jobCompletions = new ArrayList();\n jobManager.resetJobs(currentTime, jobCompletions);\n // If there were any job aborts, we must reprioritize all active documents, since we've done something\n // not predicted by the algorithm that assigned those priorities. This is, of course, quite expensive,\n // but it cannot be helped (at least, I cannot find a way to avoid it).\n if (jobStops.size() > 0) {\n Logging.threads.debug(\"Job reset thread reprioritizing documents...\");\n ManifoldCF.resetAllDocumentPriorities(threadContext, processID);\n Logging.threads.debug(\"Job reset thread done reprioritizing documents.\");\n }\n int k = 0;\n while (k < jobStops.size()) {\n IJobDescription desc = jobStops.get(k);\n Integer notificationType = jobStopNotifications.get(k);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBSTOP, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doStopNotifications(desc, notificationType, notificationManager, notificationPool);\n k++;\n }\n k = 0;\n while (k < jobResumes.size()) {\n IJobDescription desc = jobResumes.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBCONTINUE, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n }\n k = 0;\n while (k < jobCompletions.size()) {\n IJobDescription desc = jobCompletions.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBEND, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doEndNotifications(desc, notificationManager, notificationPool);\n }\n ManifoldCF.sleep(10000L);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n break;\n if (e.getErrorCode() == ManifoldCFException.DATABASE_CONNECTION_ERROR) {\n Logging.threads.error(\"Job reset thread aborting and restarting due to database connection reset: \" + e.getMessage(), e);\n try {\n // Give the database a chance to catch up/wake up\n ManifoldCF.sleep(10000L);\n } catch (InterruptedException se) {\n break;\n }\n continue;\n }\n // Log it, but keep the thread alive\n Logging.threads.error(\"Exception tossed: \" + e.getMessage(), e);\n if (e.getErrorCode() == ManifoldCFException.SETUP_ERROR) {\n // Shut the whole system down!\n ManifoldCF.systemExit(1);\n }\n } catch (InterruptedException e) {\n // We're supposed to quit\n break;\n } catch (OutOfMemoryError e) {\n System.err.println(\"agents process ran out of memory - shutting down\");\n e.printStackTrace(System.err);\n ManifoldCF.systemExit(-200);\n } catch (Throwable e) {\n // A more severe error - but stay alive\n Logging.threads.fatal(\"Error tossed: \" + e.getMessage(), e);\n }\n }\n } catch (Throwable e) {\n // Severe error on initialization\n System.err.println(\"agents process could not start - shutting down\");\n Logging.threads.fatal(\"JobResetThread initialization error tossed: \" + e.getMessage(), e);\n ManifoldCF.systemExit(-300);\n }\n }\n\n protected static void doStopNotifications(IJobDescription jobDescription, int notificationType, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n switch(notificationType) {\n case IJobManager.STOP_ERRORABORT:\n connector.notifyOfJobStopErrorAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALABORT:\n connector.notifyOfJobStopManualAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALPAUSE:\n connector.notifyOfJobStopManualPause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_SCHEDULEPAUSE:\n connector.notifyOfJobStopSchedulePause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_RESTART:\n connector.notifyOfJobStopRestart(jobDescription.getNotificationSpecification(j));\n break;\n default:\n throw new RuntimeException(\"Unhandled notification type: \" + notificationType);\n }\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n ", "post_mask_code": "\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n\n protected static void doEndNotifications(IJobDescription jobDescription, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n connector.notifyOfJobEnd(jobDescription.getNotificationSpecification(j));\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n}\n"} {"task_id": "Java_262", "language": "Java", "task_type": "while_statement", "source_file": "java/github/apache/manifoldcf/framework/pull-agent/src/main/java/org/apache/manifoldcf/crawler/system/JobResetThread.java", "mask_start_position": 3754, "mask_end_position": 4089, "canonical_solution": "while (k < jobResumes.size()) {\n IJobDescription desc = jobResumes.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBCONTINUE, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n }", "pre_mask_code": "package org.apache.manifoldcf.crawler.system;\n\nimport org.apache.manifoldcf.core.interfaces.*;\nimport org.apache.manifoldcf.agents.interfaces.*;\nimport org.apache.manifoldcf.crawler.interfaces.*;\nimport org.apache.manifoldcf.crawler.system.Logging;\nimport java.util.*;\nimport java.lang.reflect.*;\n\n/**\n * This class represents the thread that notices jobs that have completed their shutdown phase, and puts them in the\n * \"notify connector\" state.\n */\npublic class JobResetThread extends Thread {\n\n public static final String _rcsid = \"@(#)$Id: JobResetThread.java 991295 2010-08-31 19:12:14Z kwright $\";\n\n // Local data\n /**\n * Process ID\n */\n protected final String processID;\n\n public JobResetThread(String processID) throws ManifoldCFException {\n super();\n setName(\"Job reset thread\");\n setDaemon(true);\n this.processID = processID;\n }\n\n public void run() {\n try {\n // Create a thread context object.\n IThreadContext threadContext = ThreadContextFactory.make();\n IJobManager jobManager = JobManagerFactory.make(threadContext);\n IRepositoryConnectionManager connectionManager = RepositoryConnectionManagerFactory.make(threadContext);\n INotificationConnectionManager notificationManager = NotificationConnectionManagerFactory.make(threadContext);\n INotificationConnectorPool notificationPool = NotificationConnectorPoolFactory.make(threadContext);\n // Loop\n while (true) {\n // Do another try/catch around everything in the loop\n try {\n // See if there are any completed jobs\n long currentTime = System.currentTimeMillis();\n List jobStops = new ArrayList();\n List jobStopNotifications = new ArrayList();\n jobManager.finishJobStops(currentTime, jobStops, jobStopNotifications);\n List jobResumes = new ArrayList();\n jobManager.finishJobResumes(currentTime, jobResumes);\n List jobCompletions = new ArrayList();\n jobManager.resetJobs(currentTime, jobCompletions);\n // If there were any job aborts, we must reprioritize all active documents, since we've done something\n // not predicted by the algorithm that assigned those priorities. This is, of course, quite expensive,\n // but it cannot be helped (at least, I cannot find a way to avoid it).\n if (jobStops.size() > 0) {\n Logging.threads.debug(\"Job reset thread reprioritizing documents...\");\n ManifoldCF.resetAllDocumentPriorities(threadContext, processID);\n Logging.threads.debug(\"Job reset thread done reprioritizing documents.\");\n }\n int k = 0;\n while (k < jobStops.size()) {\n IJobDescription desc = jobStops.get(k);\n Integer notificationType = jobStopNotifications.get(k);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBSTOP, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doStopNotifications(desc, notificationType, notificationManager, notificationPool);\n k++;\n }\n k = 0;\n ", "post_mask_code": "\n k = 0;\n while (k < jobCompletions.size()) {\n IJobDescription desc = jobCompletions.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBEND, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doEndNotifications(desc, notificationManager, notificationPool);\n }\n ManifoldCF.sleep(10000L);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n break;\n if (e.getErrorCode() == ManifoldCFException.DATABASE_CONNECTION_ERROR) {\n Logging.threads.error(\"Job reset thread aborting and restarting due to database connection reset: \" + e.getMessage(), e);\n try {\n // Give the database a chance to catch up/wake up\n ManifoldCF.sleep(10000L);\n } catch (InterruptedException se) {\n break;\n }\n continue;\n }\n // Log it, but keep the thread alive\n Logging.threads.error(\"Exception tossed: \" + e.getMessage(), e);\n if (e.getErrorCode() == ManifoldCFException.SETUP_ERROR) {\n // Shut the whole system down!\n ManifoldCF.systemExit(1);\n }\n } catch (InterruptedException e) {\n // We're supposed to quit\n break;\n } catch (OutOfMemoryError e) {\n System.err.println(\"agents process ran out of memory - shutting down\");\n e.printStackTrace(System.err);\n ManifoldCF.systemExit(-200);\n } catch (Throwable e) {\n // A more severe error - but stay alive\n Logging.threads.fatal(\"Error tossed: \" + e.getMessage(), e);\n }\n }\n } catch (Throwable e) {\n // Severe error on initialization\n System.err.println(\"agents process could not start - shutting down\");\n Logging.threads.fatal(\"JobResetThread initialization error tossed: \" + e.getMessage(), e);\n ManifoldCF.systemExit(-300);\n }\n }\n\n protected static void doStopNotifications(IJobDescription jobDescription, int notificationType, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n switch(notificationType) {\n case IJobManager.STOP_ERRORABORT:\n connector.notifyOfJobStopErrorAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALABORT:\n connector.notifyOfJobStopManualAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALPAUSE:\n connector.notifyOfJobStopManualPause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_SCHEDULEPAUSE:\n connector.notifyOfJobStopSchedulePause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_RESTART:\n connector.notifyOfJobStopRestart(jobDescription.getNotificationSpecification(j));\n break;\n default:\n throw new RuntimeException(\"Unhandled notification type: \" + notificationType);\n }\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n\n protected static void doEndNotifications(IJobDescription jobDescription, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n connector.notifyOfJobEnd(jobDescription.getNotificationSpecification(j));\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n}\n"} {"task_id": "Java_263", "language": "Java", "task_type": "try_statement", "source_file": "java/github/apache/manifoldcf/framework/pull-agent/src/main/java/org/apache/manifoldcf/crawler/system/JobResetThread.java", "mask_start_position": 5121, "mask_end_position": 5379, "canonical_solution": "try {\n // Give the database a chance to catch up/wake up\n ManifoldCF.sleep(10000L);\n } catch (InterruptedException se) {\n break;\n }", "pre_mask_code": "package org.apache.manifoldcf.crawler.system;\n\nimport org.apache.manifoldcf.core.interfaces.*;\nimport org.apache.manifoldcf.agents.interfaces.*;\nimport org.apache.manifoldcf.crawler.interfaces.*;\nimport org.apache.manifoldcf.crawler.system.Logging;\nimport java.util.*;\nimport java.lang.reflect.*;\n\n/**\n * This class represents the thread that notices jobs that have completed their shutdown phase, and puts them in the\n * \"notify connector\" state.\n */\npublic class JobResetThread extends Thread {\n\n public static final String _rcsid = \"@(#)$Id: JobResetThread.java 991295 2010-08-31 19:12:14Z kwright $\";\n\n // Local data\n /**\n * Process ID\n */\n protected final String processID;\n\n public JobResetThread(String processID) throws ManifoldCFException {\n super();\n setName(\"Job reset thread\");\n setDaemon(true);\n this.processID = processID;\n }\n\n public void run() {\n try {\n // Create a thread context object.\n IThreadContext threadContext = ThreadContextFactory.make();\n IJobManager jobManager = JobManagerFactory.make(threadContext);\n IRepositoryConnectionManager connectionManager = RepositoryConnectionManagerFactory.make(threadContext);\n INotificationConnectionManager notificationManager = NotificationConnectionManagerFactory.make(threadContext);\n INotificationConnectorPool notificationPool = NotificationConnectorPoolFactory.make(threadContext);\n // Loop\n while (true) {\n // Do another try/catch around everything in the loop\n try {\n // See if there are any completed jobs\n long currentTime = System.currentTimeMillis();\n List jobStops = new ArrayList();\n List jobStopNotifications = new ArrayList();\n jobManager.finishJobStops(currentTime, jobStops, jobStopNotifications);\n List jobResumes = new ArrayList();\n jobManager.finishJobResumes(currentTime, jobResumes);\n List jobCompletions = new ArrayList();\n jobManager.resetJobs(currentTime, jobCompletions);\n // If there were any job aborts, we must reprioritize all active documents, since we've done something\n // not predicted by the algorithm that assigned those priorities. This is, of course, quite expensive,\n // but it cannot be helped (at least, I cannot find a way to avoid it).\n if (jobStops.size() > 0) {\n Logging.threads.debug(\"Job reset thread reprioritizing documents...\");\n ManifoldCF.resetAllDocumentPriorities(threadContext, processID);\n Logging.threads.debug(\"Job reset thread done reprioritizing documents.\");\n }\n int k = 0;\n while (k < jobStops.size()) {\n IJobDescription desc = jobStops.get(k);\n Integer notificationType = jobStopNotifications.get(k);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBSTOP, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doStopNotifications(desc, notificationType, notificationManager, notificationPool);\n k++;\n }\n k = 0;\n while (k < jobResumes.size()) {\n IJobDescription desc = jobResumes.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBCONTINUE, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n }\n k = 0;\n while (k < jobCompletions.size()) {\n IJobDescription desc = jobCompletions.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBEND, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doEndNotifications(desc, notificationManager, notificationPool);\n }\n ManifoldCF.sleep(10000L);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n break;\n if (e.getErrorCode() == ManifoldCFException.DATABASE_CONNECTION_ERROR) {\n Logging.threads.error(\"Job reset thread aborting and restarting due to database connection reset: \" + e.getMessage(), e);\n ", "post_mask_code": "\n continue;\n }\n // Log it, but keep the thread alive\n Logging.threads.error(\"Exception tossed: \" + e.getMessage(), e);\n if (e.getErrorCode() == ManifoldCFException.SETUP_ERROR) {\n // Shut the whole system down!\n ManifoldCF.systemExit(1);\n }\n } catch (InterruptedException e) {\n // We're supposed to quit\n break;\n } catch (OutOfMemoryError e) {\n System.err.println(\"agents process ran out of memory - shutting down\");\n e.printStackTrace(System.err);\n ManifoldCF.systemExit(-200);\n } catch (Throwable e) {\n // A more severe error - but stay alive\n Logging.threads.fatal(\"Error tossed: \" + e.getMessage(), e);\n }\n }\n } catch (Throwable e) {\n // Severe error on initialization\n System.err.println(\"agents process could not start - shutting down\");\n Logging.threads.fatal(\"JobResetThread initialization error tossed: \" + e.getMessage(), e);\n ManifoldCF.systemExit(-300);\n }\n }\n\n protected static void doStopNotifications(IJobDescription jobDescription, int notificationType, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n switch(notificationType) {\n case IJobManager.STOP_ERRORABORT:\n connector.notifyOfJobStopErrorAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALABORT:\n connector.notifyOfJobStopManualAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALPAUSE:\n connector.notifyOfJobStopManualPause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_SCHEDULEPAUSE:\n connector.notifyOfJobStopSchedulePause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_RESTART:\n connector.notifyOfJobStopRestart(jobDescription.getNotificationSpecification(j));\n break;\n default:\n throw new RuntimeException(\"Unhandled notification type: \" + notificationType);\n }\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n\n protected static void doEndNotifications(IJobDescription jobDescription, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n connector.notifyOfJobEnd(jobDescription.getNotificationSpecification(j));\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n}\n"} {"task_id": "Java_264", "language": "Java", "task_type": "empty", "source_file": "java/github/apache/manifoldcf/framework/pull-agent/src/main/java/org/apache/manifoldcf/crawler/system/JobResetThread.java", "mask_start_position": 7413, "mask_end_position": 7413, "canonical_solution": "", "pre_mask_code": "package org.apache.manifoldcf.crawler.system;\n\nimport org.apache.manifoldcf.core.interfaces.*;\nimport org.apache.manifoldcf.agents.interfaces.*;\nimport org.apache.manifoldcf.crawler.interfaces.*;\nimport org.apache.manifoldcf.crawler.system.Logging;\nimport java.util.*;\nimport java.lang.reflect.*;\n\n/**\n * This class represents the thread that notices jobs that have completed their shutdown phase, and puts them in the\n * \"notify connector\" state.\n */\npublic class JobResetThread extends Thread {\n\n public static final String _rcsid = \"@(#)$Id: JobResetThread.java 991295 2010-08-31 19:12:14Z kwright $\";\n\n // Local data\n /**\n * Process ID\n */\n protected final String processID;\n\n public JobResetThread(String processID) throws ManifoldCFException {\n super();\n setName(\"Job reset thread\");\n setDaemon(true);\n this.processID = processID;\n }\n\n public void run() {\n try {\n // Create a thread context object.\n IThreadContext threadContext = ThreadContextFactory.make();\n IJobManager jobManager = JobManagerFactory.make(threadContext);\n IRepositoryConnectionManager connectionManager = RepositoryConnectionManagerFactory.make(threadContext);\n INotificationConnectionManager notificationManager = NotificationConnectionManagerFactory.make(threadContext);\n INotificationConnectorPool notificationPool = NotificationConnectorPoolFactory.make(threadContext);\n // Loop\n while (true) {\n // Do another try/catch around everything in the loop\n try {\n // See if there are any completed jobs\n long currentTime = System.currentTimeMillis();\n List jobStops = new ArrayList();\n List jobStopNotifications = new ArrayList();\n jobManager.finishJobStops(currentTime, jobStops, jobStopNotifications);\n List jobResumes = new ArrayList();\n jobManager.finishJobResumes(currentTime, jobResumes);\n List jobCompletions = new ArrayList();\n jobManager.resetJobs(currentTime, jobCompletions);\n // If there were any job aborts, we must reprioritize all active documents, since we've done something\n // not predicted by the algorithm that assigned those priorities. This is, of course, quite expensive,\n // but it cannot be helped (at least, I cannot find a way to avoid it).\n if (jobStops.size() > 0) {\n Logging.threads.debug(\"Job reset thread reprioritizing documents...\");\n ManifoldCF.resetAllDocumentPriorities(threadContext, processID);\n Logging.threads.debug(\"Job reset thread done reprioritizing documents.\");\n }\n int k = 0;\n while (k < jobStops.size()) {\n IJobDescription desc = jobStops.get(k);\n Integer notificationType = jobStopNotifications.get(k);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBSTOP, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doStopNotifications(desc, notificationType, notificationManager, notificationPool);\n k++;\n }\n k = 0;\n while (k < jobResumes.size()) {\n IJobDescription desc = jobResumes.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBCONTINUE, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n }\n k = 0;\n while (k < jobCompletions.size()) {\n IJobDescription desc = jobCompletions.get(k++);\n connectionManager.recordHistory(desc.getConnectionName(), null, connectionManager.ACTIVITY_JOBEND, null, desc.getID().toString() + \"(\" + desc.getDescription() + \")\", null, null, null);\n // As a courtesy, call all the notification connections (if any)\n doEndNotifications(desc, notificationManager, notificationPool);\n }\n ManifoldCF.sleep(10000L);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n break;\n if (e.getErrorCode() == ManifoldCFException.DATABASE_CONNECTION_ERROR) {\n Logging.threads.error(\"Job reset thread aborting and restarting due to database connection reset: \" + e.getMessage(), e);\n try {\n // Give the database a chance to catch up/wake up\n ManifoldCF.sleep(10000L);\n } catch (InterruptedException se) {\n break;\n }\n continue;\n }\n // Log it, but keep the thread alive\n Logging.threads.error(\"Exception tossed: \" + e.getMessage(), e);\n if (e.getErrorCode() == ManifoldCFException.SETUP_ERROR) {\n // Shut the whole system down!\n ManifoldCF.systemExit(1);\n }\n } catch (InterruptedException e) {\n // We're supposed to quit\n break;\n } catch (OutOfMemoryError e) {\n System.err.println(\"agents process ran out of memory - shutting down\");\n e.printStackTrace(System.err);\n ManifoldCF.systemExit(-200);\n } catch (Throwable e) {\n // A more severe error - but stay alive\n Logging.threads.fatal(\"Error tossed: \" + e.getMessage(), e);\n }\n }\n } catch (Throwable e) {\n // Severe error on initialization\n System.err.println(\"agents process could not start - shutting down\");\n Logging.threads.fatal(\"JobResetThread initialization error tossed: \" + e.getMessage(), e);\n ManifoldCF.systemExit(-300);\n }\n }\n\n protected static void doStopNotifications(IJobDescription jobDescription, int notificationType, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n swit", "post_mask_code": "ch(notificationType) {\n case IJobManager.STOP_ERRORABORT:\n connector.notifyOfJobStopErrorAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALABORT:\n connector.notifyOfJobStopManualAbort(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_MANUALPAUSE:\n connector.notifyOfJobStopManualPause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_SCHEDULEPAUSE:\n connector.notifyOfJobStopSchedulePause(jobDescription.getNotificationSpecification(j));\n break;\n case IJobManager.STOP_RESTART:\n connector.notifyOfJobStopRestart(jobDescription.getNotificationSpecification(j));\n break;\n default:\n throw new RuntimeException(\"Unhandled notification type: \" + notificationType);\n }\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n\n protected static void doEndNotifications(IJobDescription jobDescription, INotificationConnectionManager notificationManager, INotificationConnectorPool notificationPool) throws ManifoldCFException {\n for (int j = 0; j < jobDescription.countNotifications(); j++) {\n String notificationConnectionName = jobDescription.getNotificationConnectionName(j);\n try {\n INotificationConnection c = notificationManager.load(notificationConnectionName);\n if (c != null) {\n INotificationConnector connector = notificationPool.grab(c);\n if (connector != null) {\n try {\n connector.notifyOfJobEnd(jobDescription.getNotificationSpecification(j));\n } finally {\n notificationPool.release(c, connector);\n }\n }\n }\n } catch (ServiceInterruption e) {\n Logging.connectors.warn(\"Can't notify right now: \" + e.getMessage(), e);\n } catch (ManifoldCFException e) {\n if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)\n throw e;\n Logging.connectors.warn(\"Error notifying: \" + e.getMessage(), e);\n }\n }\n }\n}\n"} {"task_id": "Java_265", "language": "Java", "task_type": "method_signature", "source_file": "java/github/open-telemetry/opentelemetry-java-instrumentation/instrumentation/jsf/jsf-myfaces-1.2/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/myfaces/MyFacesInstrumentationModule.java", "mask_start_position": 591, "mask_end_position": 661, "canonical_solution": "@Override\n public List typeInstrumentations() ", "pre_mask_code": "/*\n * Copyright The OpenTelemetry Authors\n */\npackage io.opentelemetry.javaagent.instrumentation.myfaces;\n\nimport static java.util.Arrays.asList;\nimport com.google.auto.service.AutoService;\nimport io.opentelemetry.javaagent.extension.instrumentation.InstrumentationModule;\nimport io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;\nimport java.util.List;\n\n@AutoService(InstrumentationModule.class)\npublic class MyFacesInstrumentationModule extends InstrumentationModule {\n\n public MyFacesInstrumentationModule() {\n super(\"myfaces\", \"myfaces-1.2\");\n }\n\n ", "post_mask_code": "{\n return asList(new ActionListenerImplInstrumentation(), new RestoreViewExecutorInstrumentation());\n }\n}\n"} {"task_id": "Java_266", "language": "Java", "task_type": "method_body", "source_file": "java/github/open-telemetry/opentelemetry-java-instrumentation/instrumentation/jsf/jsf-myfaces-1.2/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/myfaces/MyFacesInstrumentationModule.java", "mask_start_position": 661, "mask_end_position": 774, "canonical_solution": "{\n return asList(new ActionListenerImplInstrumentation(), new RestoreViewExecutorInstrumentation());\n }", "pre_mask_code": "/*\n * Copyright The OpenTelemetry Authors\n */\npackage io.opentelemetry.javaagent.instrumentation.myfaces;\n\nimport static java.util.Arrays.asList;\nimport com.google.auto.service.AutoService;\nimport io.opentelemetry.javaagent.extension.instrumentation.InstrumentationModule;\nimport io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;\nimport java.util.List;\n\n@AutoService(InstrumentationModule.class)\npublic class MyFacesInstrumentationModule extends InstrumentationModule {\n\n public MyFacesInstrumentationModule() {\n super(\"myfaces\", \"myfaces-1.2\");\n }\n\n @Override\n public List typeInstrumentations() ", "post_mask_code": "\n}\n"} {"task_id": "Java_267", "language": "Java", "task_type": "single_line", "source_file": "java/github/open-telemetry/opentelemetry-java-instrumentation/instrumentation/jsf/jsf-myfaces-1.2/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/myfaces/MyFacesInstrumentationModule.java", "mask_start_position": 673, "mask_end_position": 768, "canonical_solution": "turn asList(new ActionListenerImplInstrumentation(), new RestoreViewExecutorInstrumentation());", "pre_mask_code": "/*\n * Copyright The OpenTelemetry Authors\n */\npackage io.opentelemetry.javaagent.instrumentation.myfaces;\n\nimport static java.util.Arrays.asList;\nimport com.google.auto.service.AutoService;\nimport io.opentelemetry.javaagent.extension.instrumentation.InstrumentationModule;\nimport io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;\nimport java.util.List;\n\n@AutoService(InstrumentationModule.class)\npublic class MyFacesInstrumentationModule extends InstrumentationModule {\n\n public MyFacesInstrumentationModule() {\n super(\"myfaces\", \"myfaces-1.2\");\n }\n\n @Override\n public List typeInstrumentations() {\n re", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_268", "language": "Java", "task_type": "empty", "source_file": "java/github/open-telemetry/opentelemetry-java-instrumentation/instrumentation/jsf/jsf-myfaces-1.2/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/myfaces/MyFacesInstrumentationModule.java", "mask_start_position": 165, "mask_end_position": 165, "canonical_solution": "", "pre_mask_code": "/*\n * Copyright The OpenTelemetry Authors\n */\npackage io.opentelemetry.javaagent.instrumentation.myfaces;\n\nimport static java.util.Arrays.asList;\nimport com.google.a", "post_mask_code": "uto.service.AutoService;\nimport io.opentelemetry.javaagent.extension.instrumentation.InstrumentationModule;\nimport io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;\nimport java.util.List;\n\n@AutoService(InstrumentationModule.class)\npublic class MyFacesInstrumentationModule extends InstrumentationModule {\n\n public MyFacesInstrumentationModule() {\n super(\"myfaces\", \"myfaces-1.2\");\n }\n\n @Override\n public List typeInstrumentations() {\n return asList(new ActionListenerImplInstrumentation(), new RestoreViewExecutorInstrumentation());\n }\n}\n"} {"task_id": "Java_269", "language": "Java", "task_type": "method_signature", "source_file": "java/github/indigo-iam/iam/iam-login-service/src/main/java/it/infn/mw/iam/audit/IamAuthenticationSuccessAuditListener.java", "mask_start_position": 839, "mask_end_position": 919, "canonical_solution": "@Override\n public void onApplicationEvent(AbstractAuthenticationEvent event) ", "pre_mask_code": "package it.infn.mw.iam.audit;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.security.authentication.event.AbstractAuthenticationEvent;\nimport org.springframework.security.authentication.event.AuthenticationSuccessEvent;\nimport org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;\nimport org.springframework.stereotype.Component;\nimport it.infn.mw.iam.audit.events.auth.IamAuthenticationSuccessEvent;\n\n@Component\npublic class IamAuthenticationSuccessAuditListener implements ApplicationListener {\n\n private final AuditEventLogger logger;\n\n @Autowired\n public IamAuthenticationSuccessAuditListener(AuditEventLogger logger) {\n this.logger = logger;\n }\n\n ", "post_mask_code": "{\n if ((event instanceof AuthenticationSuccessEvent) || (event instanceof InteractiveAuthenticationSuccessEvent)) {\n IamAuthenticationSuccessEvent ev = new IamAuthenticationSuccessEvent(event);\n logger.logAuditEvent(ev);\n }\n }\n}\n"} {"task_id": "Java_270", "language": "Java", "task_type": "method_body", "source_file": "java/github/indigo-iam/iam/iam-login-service/src/main/java/it/infn/mw/iam/audit/IamAuthenticationSuccessAuditListener.java", "mask_start_position": 919, "mask_end_position": 1184, "canonical_solution": "{\n if ((event instanceof AuthenticationSuccessEvent) || (event instanceof InteractiveAuthenticationSuccessEvent)) {\n IamAuthenticationSuccessEvent ev = new IamAuthenticationSuccessEvent(event);\n logger.logAuditEvent(ev);\n }\n }", "pre_mask_code": "package it.infn.mw.iam.audit;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.security.authentication.event.AbstractAuthenticationEvent;\nimport org.springframework.security.authentication.event.AuthenticationSuccessEvent;\nimport org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;\nimport org.springframework.stereotype.Component;\nimport it.infn.mw.iam.audit.events.auth.IamAuthenticationSuccessEvent;\n\n@Component\npublic class IamAuthenticationSuccessAuditListener implements ApplicationListener {\n\n private final AuditEventLogger logger;\n\n @Autowired\n public IamAuthenticationSuccessAuditListener(AuditEventLogger logger) {\n this.logger = logger;\n }\n\n @Override\n public void onApplicationEvent(AbstractAuthenticationEvent event) ", "post_mask_code": "\n}\n"} {"task_id": "Java_271", "language": "Java", "task_type": "if_statement", "source_file": "java/github/indigo-iam/iam/iam-login-service/src/main/java/it/infn/mw/iam/audit/IamAuthenticationSuccessAuditListener.java", "mask_start_position": 929, "mask_end_position": 1178, "canonical_solution": "if ((event instanceof AuthenticationSuccessEvent) || (event instanceof InteractiveAuthenticationSuccessEvent)) {\n IamAuthenticationSuccessEvent ev = new IamAuthenticationSuccessEvent(event);\n logger.logAuditEvent(ev);\n }", "pre_mask_code": "package it.infn.mw.iam.audit;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.security.authentication.event.AbstractAuthenticationEvent;\nimport org.springframework.security.authentication.event.AuthenticationSuccessEvent;\nimport org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;\nimport org.springframework.stereotype.Component;\nimport it.infn.mw.iam.audit.events.auth.IamAuthenticationSuccessEvent;\n\n@Component\npublic class IamAuthenticationSuccessAuditListener implements ApplicationListener {\n\n private final AuditEventLogger logger;\n\n @Autowired\n public IamAuthenticationSuccessAuditListener(AuditEventLogger logger) {\n this.logger = logger;\n }\n\n @Override\n public void onApplicationEvent(AbstractAuthenticationEvent event) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_272", "language": "Java", "task_type": "empty", "source_file": "java/github/indigo-iam/iam/iam-login-service/src/main/java/it/infn/mw/iam/audit/IamAuthenticationSuccessAuditListener.java", "mask_start_position": 489, "mask_end_position": 489, "canonical_solution": "", "pre_mask_code": "package it.infn.mw.iam.audit;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.security.authentication.event.AbstractAuthenticationEvent;\nimport org.springframework.security.authentication.event.AuthenticationSuccessEvent;\nimport org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;\nimport org.springframework.stereotype.Component;\nimport it.infn.mw.iam.a", "post_mask_code": "udit.events.auth.IamAuthenticationSuccessEvent;\n\n@Component\npublic class IamAuthenticationSuccessAuditListener implements ApplicationListener {\n\n private final AuditEventLogger logger;\n\n @Autowired\n public IamAuthenticationSuccessAuditListener(AuditEventLogger logger) {\n this.logger = logger;\n }\n\n @Override\n public void onApplicationEvent(AbstractAuthenticationEvent event) {\n if ((event instanceof AuthenticationSuccessEvent) || (event instanceof InteractiveAuthenticationSuccessEvent)) {\n IamAuthenticationSuccessEvent ev = new IamAuthenticationSuccessEvent(event);\n logger.logAuditEvent(ev);\n }\n }\n}\n"} {"task_id": "Java_273", "language": "Java", "task_type": "empty", "source_file": "java/github/kangta123/hawk/container-service/domain/src/main/java/com/oc/hawk/container/domain/model/runtime/build/ProjectBuildPost.java", "mask_start_position": 124, "mask_end_position": 124, "canonical_solution": "", "pre_mask_code": "package com.oc.hawk.container.domain.model.runtime.build;\n\nimport com.oc.hawk.container.domain.model.runtime.config.Instance", "post_mask_code": "Id;\nimport lombok.Getter;\n\n@Getter\npublic class ProjectBuildPost {\n\n private InstanceId instanceId;\n\n private String instanceName;\n\n public ProjectBuildPost(InstanceId instanceId, String instanceName) {\n this.instanceId = instanceId;\n this.instanceName = instanceName;\n }\n}\n"} {"task_id": "Java_274", "language": "Java", "task_type": "method_signature", "source_file": "java/github/quoll/mulgara/src/jar/server-rmi/java/org/mulgara/server/rmi/BlankNodeWrapperAnswer.java", "mask_start_position": 4358, "mask_end_position": 4407, "canonical_solution": "public long getRowCount() throws TuplesException ", "pre_mask_code": "/*\n *\n *\n * Contributor(s): N/A.\n *\n * [NOTE: The text of this Exhibit A may differ slightly from the text\n * of the notices in the Source Code files of the Original Code. You\n * should use the text of this Exhibit A rather than the text found in the\n * Original Code Source Code for Your Modifications.]\n *\n */\npackage org.mulgara.server.rmi;\n\n// Java 2 standard packages\nimport java.rmi.*;\nimport java.util.*;\n// Log4j\nimport org.apache.log4j.*;\n// JRDF\nimport org.jrdf.graph.*;\n// Third party packages\nimport org.mulgara.query.AbstractAnswer;\nimport org.mulgara.query.Answer;\nimport org.mulgara.query.TuplesException;\nimport org.mulgara.query.Variable;\n\n/**\n * Takes a regular answer and uses a map to convert blank nodes from server side\n * blank nodes to JRDF in memory blank nodes.\n *\n * @author Andrew Newman\n *\n * @created 2005-01-28\n *\n * @version $Revision: 1.2 $\n *\n * @modified $Date: 2005/02/02 21:15:04 $\n *\n * @maintenanceAuthor $Author: newmana $\n */\npublic class BlankNodeWrapperAnswer extends AbstractAnswer implements Answer {\n\n /**\n * Logger\n */\n @SuppressWarnings(\"unused\")\n private static final Logger logger = Logger.getLogger(BlankNodeWrapperAnswer.class.getName());\n\n /**\n * The wrapped instance.\n */\n protected Answer answer;\n\n /**\n * The blank node map.\n */\n protected Map blankNodeMap = null;\n\n /**\n * Creates a new wrapper for converting answers with blank nodes.\n *\n * @param answer the instance to wrap.\n * @param newBlankNodeMap a map which converts server side blank nodes to\n * in memory blank nodes.\n * @throws IllegalArgumentException if answer is null\n */\n public BlankNodeWrapperAnswer(Answer answer, Map newBlankNodeMap) throws RemoteException {\n this.answer = answer;\n blankNodeMap = newBlankNodeMap;\n }\n\n public Object clone() {\n BlankNodeWrapperAnswer cloned = (BlankNodeWrapperAnswer) super.clone();\n cloned.answer = (Answer) this.answer.clone();\n return cloned;\n }\n\n public Object getObject(int column) throws TuplesException {\n Object obj = answer.getObject(column);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n public Object getObject(String columnName) throws TuplesException {\n Object obj = answer.getObject(columnName);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n /**\n * Returns the local value, the key of the hashmap, based on the given value\n * or null if not found. Does so by getting the entry set of the map and\n * testing each for the value - very inefficient.\n *\n * @param serverBlankNode the server side blank node to convert to an in\n * memory blank node.\n * @return the JRDF memory blank node or null if not found.\n */\n private BlankNode getKey(Object serverBlankNode) {\n Set> entrySet = blankNodeMap.entrySet();\n Iterator> iter = entrySet.iterator();\n while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n if (entry.getValue().equals(serverBlankNode)) {\n return entry.getKey();\n }\n }\n return null;\n }\n\n public void beforeFirst() throws TuplesException {\n answer.beforeFirst();\n }\n\n public void close() throws TuplesException {\n answer.close();\n }\n\n public int getColumnIndex(Variable column) throws TuplesException {\n return answer.getColumnIndex(column);\n }\n\n public int getNumberOfVariables() {\n return answer.getNumberOfVariables();\n }\n\n public Variable[] getVariables() {\n return answer.getVariables();\n }\n\n public boolean isUnconstrained() throws TuplesException {\n return answer.isUnconstrained();\n }\n\n ", "post_mask_code": "{\n return answer.getRowCount();\n }\n\n public long getRowUpperBound() throws TuplesException {\n return answer.getRowUpperBound();\n }\n\n public long getRowExpectedCount() throws TuplesException {\n return answer.getRowExpectedCount();\n }\n\n public int getRowCardinality() throws TuplesException {\n return answer.getRowCardinality();\n }\n\n public boolean isEmpty() throws TuplesException {\n return answer.isEmpty();\n }\n\n public boolean next() throws TuplesException {\n return answer.next();\n }\n}\n"} {"task_id": "Java_275", "language": "Java", "task_type": "method_body", "source_file": "java/github/quoll/mulgara/src/jar/server-rmi/java/org/mulgara/server/rmi/BlankNodeWrapperAnswer.java", "mask_start_position": 4623, "mask_end_position": 4675, "canonical_solution": "{\n return answer.getRowExpectedCount();\n }", "pre_mask_code": "/*\n *\n *\n * Contributor(s): N/A.\n *\n * [NOTE: The text of this Exhibit A may differ slightly from the text\n * of the notices in the Source Code files of the Original Code. You\n * should use the text of this Exhibit A rather than the text found in the\n * Original Code Source Code for Your Modifications.]\n *\n */\npackage org.mulgara.server.rmi;\n\n// Java 2 standard packages\nimport java.rmi.*;\nimport java.util.*;\n// Log4j\nimport org.apache.log4j.*;\n// JRDF\nimport org.jrdf.graph.*;\n// Third party packages\nimport org.mulgara.query.AbstractAnswer;\nimport org.mulgara.query.Answer;\nimport org.mulgara.query.TuplesException;\nimport org.mulgara.query.Variable;\n\n/**\n * Takes a regular answer and uses a map to convert blank nodes from server side\n * blank nodes to JRDF in memory blank nodes.\n *\n * @author Andrew Newman\n *\n * @created 2005-01-28\n *\n * @version $Revision: 1.2 $\n *\n * @modified $Date: 2005/02/02 21:15:04 $\n *\n * @maintenanceAuthor $Author: newmana $\n */\npublic class BlankNodeWrapperAnswer extends AbstractAnswer implements Answer {\n\n /**\n * Logger\n */\n @SuppressWarnings(\"unused\")\n private static final Logger logger = Logger.getLogger(BlankNodeWrapperAnswer.class.getName());\n\n /**\n * The wrapped instance.\n */\n protected Answer answer;\n\n /**\n * The blank node map.\n */\n protected Map blankNodeMap = null;\n\n /**\n * Creates a new wrapper for converting answers with blank nodes.\n *\n * @param answer the instance to wrap.\n * @param newBlankNodeMap a map which converts server side blank nodes to\n * in memory blank nodes.\n * @throws IllegalArgumentException if answer is null\n */\n public BlankNodeWrapperAnswer(Answer answer, Map newBlankNodeMap) throws RemoteException {\n this.answer = answer;\n blankNodeMap = newBlankNodeMap;\n }\n\n public Object clone() {\n BlankNodeWrapperAnswer cloned = (BlankNodeWrapperAnswer) super.clone();\n cloned.answer = (Answer) this.answer.clone();\n return cloned;\n }\n\n public Object getObject(int column) throws TuplesException {\n Object obj = answer.getObject(column);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n public Object getObject(String columnName) throws TuplesException {\n Object obj = answer.getObject(columnName);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n /**\n * Returns the local value, the key of the hashmap, based on the given value\n * or null if not found. Does so by getting the entry set of the map and\n * testing each for the value - very inefficient.\n *\n * @param serverBlankNode the server side blank node to convert to an in\n * memory blank node.\n * @return the JRDF memory blank node or null if not found.\n */\n private BlankNode getKey(Object serverBlankNode) {\n Set> entrySet = blankNodeMap.entrySet();\n Iterator> iter = entrySet.iterator();\n while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n if (entry.getValue().equals(serverBlankNode)) {\n return entry.getKey();\n }\n }\n return null;\n }\n\n public void beforeFirst() throws TuplesException {\n answer.beforeFirst();\n }\n\n public void close() throws TuplesException {\n answer.close();\n }\n\n public int getColumnIndex(Variable column) throws TuplesException {\n return answer.getColumnIndex(column);\n }\n\n public int getNumberOfVariables() {\n return answer.getNumberOfVariables();\n }\n\n public Variable[] getVariables() {\n return answer.getVariables();\n }\n\n public boolean isUnconstrained() throws TuplesException {\n return answer.isUnconstrained();\n }\n\n public long getRowCount() throws TuplesException {\n return answer.getRowCount();\n }\n\n public long getRowUpperBound() throws TuplesException {\n return answer.getRowUpperBound();\n }\n\n public long getRowExpectedCount() throws TuplesException ", "post_mask_code": "\n\n public int getRowCardinality() throws TuplesException {\n return answer.getRowCardinality();\n }\n\n public boolean isEmpty() throws TuplesException {\n return answer.isEmpty();\n }\n\n public boolean next() throws TuplesException {\n return answer.next();\n }\n}\n"} {"task_id": "Java_276", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/quoll/mulgara/src/jar/server-rmi/java/org/mulgara/server/rmi/BlankNodeWrapperAnswer.java", "mask_start_position": 2167, "mask_end_position": 2214, "canonical_solution": "\n Object obj = answer.getObject(column);", "pre_mask_code": "/*\n *\n *\n * Contributor(s): N/A.\n *\n * [NOTE: The text of this Exhibit A may differ slightly from the text\n * of the notices in the Source Code files of the Original Code. You\n * should use the text of this Exhibit A rather than the text found in the\n * Original Code Source Code for Your Modifications.]\n *\n */\npackage org.mulgara.server.rmi;\n\n// Java 2 standard packages\nimport java.rmi.*;\nimport java.util.*;\n// Log4j\nimport org.apache.log4j.*;\n// JRDF\nimport org.jrdf.graph.*;\n// Third party packages\nimport org.mulgara.query.AbstractAnswer;\nimport org.mulgara.query.Answer;\nimport org.mulgara.query.TuplesException;\nimport org.mulgara.query.Variable;\n\n/**\n * Takes a regular answer and uses a map to convert blank nodes from server side\n * blank nodes to JRDF in memory blank nodes.\n *\n * @author Andrew Newman\n *\n * @created 2005-01-28\n *\n * @version $Revision: 1.2 $\n *\n * @modified $Date: 2005/02/02 21:15:04 $\n *\n * @maintenanceAuthor $Author: newmana $\n */\npublic class BlankNodeWrapperAnswer extends AbstractAnswer implements Answer {\n\n /**\n * Logger\n */\n @SuppressWarnings(\"unused\")\n private static final Logger logger = Logger.getLogger(BlankNodeWrapperAnswer.class.getName());\n\n /**\n * The wrapped instance.\n */\n protected Answer answer;\n\n /**\n * The blank node map.\n */\n protected Map blankNodeMap = null;\n\n /**\n * Creates a new wrapper for converting answers with blank nodes.\n *\n * @param answer the instance to wrap.\n * @param newBlankNodeMap a map which converts server side blank nodes to\n * in memory blank nodes.\n * @throws IllegalArgumentException if answer is null\n */\n public BlankNodeWrapperAnswer(Answer answer, Map newBlankNodeMap) throws RemoteException {\n this.answer = answer;\n blankNodeMap = newBlankNodeMap;\n }\n\n public Object clone() {\n BlankNodeWrapperAnswer cloned = (BlankNodeWrapperAnswer) super.clone();\n cloned.answer = (Answer) this.answer.clone();\n return cloned;\n }\n\n public Object getObject(int column) throws TuplesException {", "post_mask_code": "\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n public Object getObject(String columnName) throws TuplesException {\n Object obj = answer.getObject(columnName);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n /**\n * Returns the local value, the key of the hashmap, based on the given value\n * or null if not found. Does so by getting the entry set of the map and\n * testing each for the value - very inefficient.\n *\n * @param serverBlankNode the server side blank node to convert to an in\n * memory blank node.\n * @return the JRDF memory blank node or null if not found.\n */\n private BlankNode getKey(Object serverBlankNode) {\n Set> entrySet = blankNodeMap.entrySet();\n Iterator> iter = entrySet.iterator();\n while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n if (entry.getValue().equals(serverBlankNode)) {\n return entry.getKey();\n }\n }\n return null;\n }\n\n public void beforeFirst() throws TuplesException {\n answer.beforeFirst();\n }\n\n public void close() throws TuplesException {\n answer.close();\n }\n\n public int getColumnIndex(Variable column) throws TuplesException {\n return answer.getColumnIndex(column);\n }\n\n public int getNumberOfVariables() {\n return answer.getNumberOfVariables();\n }\n\n public Variable[] getVariables() {\n return answer.getVariables();\n }\n\n public boolean isUnconstrained() throws TuplesException {\n return answer.isUnconstrained();\n }\n\n public long getRowCount() throws TuplesException {\n return answer.getRowCount();\n }\n\n public long getRowUpperBound() throws TuplesException {\n return answer.getRowUpperBound();\n }\n\n public long getRowExpectedCount() throws TuplesException {\n return answer.getRowExpectedCount();\n }\n\n public int getRowCardinality() throws TuplesException {\n return answer.getRowCardinality();\n }\n\n public boolean isEmpty() throws TuplesException {\n return answer.isEmpty();\n }\n\n public boolean next() throws TuplesException {\n return answer.next();\n }\n}\n"} {"task_id": "Java_277", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/quoll/mulgara/src/jar/server-rmi/java/org/mulgara/server/rmi/BlankNodeWrapperAnswer.java", "mask_start_position": 2223, "mask_end_position": 2452, "canonical_solution": "// Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }", "pre_mask_code": "/*\n *\n *\n * Contributor(s): N/A.\n *\n * [NOTE: The text of this Exhibit A may differ slightly from the text\n * of the notices in the Source Code files of the Original Code. You\n * should use the text of this Exhibit A rather than the text found in the\n * Original Code Source Code for Your Modifications.]\n *\n */\npackage org.mulgara.server.rmi;\n\n// Java 2 standard packages\nimport java.rmi.*;\nimport java.util.*;\n// Log4j\nimport org.apache.log4j.*;\n// JRDF\nimport org.jrdf.graph.*;\n// Third party packages\nimport org.mulgara.query.AbstractAnswer;\nimport org.mulgara.query.Answer;\nimport org.mulgara.query.TuplesException;\nimport org.mulgara.query.Variable;\n\n/**\n * Takes a regular answer and uses a map to convert blank nodes from server side\n * blank nodes to JRDF in memory blank nodes.\n *\n * @author Andrew Newman\n *\n * @created 2005-01-28\n *\n * @version $Revision: 1.2 $\n *\n * @modified $Date: 2005/02/02 21:15:04 $\n *\n * @maintenanceAuthor $Author: newmana $\n */\npublic class BlankNodeWrapperAnswer extends AbstractAnswer implements Answer {\n\n /**\n * Logger\n */\n @SuppressWarnings(\"unused\")\n private static final Logger logger = Logger.getLogger(BlankNodeWrapperAnswer.class.getName());\n\n /**\n * The wrapped instance.\n */\n protected Answer answer;\n\n /**\n * The blank node map.\n */\n protected Map blankNodeMap = null;\n\n /**\n * Creates a new wrapper for converting answers with blank nodes.\n *\n * @param answer the instance to wrap.\n * @param newBlankNodeMap a map which converts server side blank nodes to\n * in memory blank nodes.\n * @throws IllegalArgumentException if answer is null\n */\n public BlankNodeWrapperAnswer(Answer answer, Map newBlankNodeMap) throws RemoteException {\n this.answer = answer;\n blankNodeMap = newBlankNodeMap;\n }\n\n public Object clone() {\n BlankNodeWrapperAnswer cloned = (BlankNodeWrapperAnswer) super.clone();\n cloned.answer = (Answer) this.answer.clone();\n return cloned;\n }\n\n public Object getObject(int column) throws TuplesException {\n Object obj = answer.getObject(column);\n ", "post_mask_code": "\n return obj;\n }\n\n public Object getObject(String columnName) throws TuplesException {\n Object obj = answer.getObject(columnName);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n /**\n * Returns the local value, the key of the hashmap, based on the given value\n * or null if not found. Does so by getting the entry set of the map and\n * testing each for the value - very inefficient.\n *\n * @param serverBlankNode the server side blank node to convert to an in\n * memory blank node.\n * @return the JRDF memory blank node or null if not found.\n */\n private BlankNode getKey(Object serverBlankNode) {\n Set> entrySet = blankNodeMap.entrySet();\n Iterator> iter = entrySet.iterator();\n while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n if (entry.getValue().equals(serverBlankNode)) {\n return entry.getKey();\n }\n }\n return null;\n }\n\n public void beforeFirst() throws TuplesException {\n answer.beforeFirst();\n }\n\n public void close() throws TuplesException {\n answer.close();\n }\n\n public int getColumnIndex(Variable column) throws TuplesException {\n return answer.getColumnIndex(column);\n }\n\n public int getNumberOfVariables() {\n return answer.getNumberOfVariables();\n }\n\n public Variable[] getVariables() {\n return answer.getVariables();\n }\n\n public boolean isUnconstrained() throws TuplesException {\n return answer.isUnconstrained();\n }\n\n public long getRowCount() throws TuplesException {\n return answer.getRowCount();\n }\n\n public long getRowUpperBound() throws TuplesException {\n return answer.getRowUpperBound();\n }\n\n public long getRowExpectedCount() throws TuplesException {\n return answer.getRowExpectedCount();\n }\n\n public int getRowCardinality() throws TuplesException {\n return answer.getRowCardinality();\n }\n\n public boolean isEmpty() throws TuplesException {\n return answer.isEmpty();\n }\n\n public boolean next() throws TuplesException {\n return answer.next();\n }\n}\n"} {"task_id": "Java_278", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/quoll/mulgara/src/jar/server-rmi/java/org/mulgara/server/rmi/BlankNodeWrapperAnswer.java", "mask_start_position": 2461, "mask_end_position": 2478, "canonical_solution": "return obj;\n }", "pre_mask_code": "/*\n *\n *\n * Contributor(s): N/A.\n *\n * [NOTE: The text of this Exhibit A may differ slightly from the text\n * of the notices in the Source Code files of the Original Code. You\n * should use the text of this Exhibit A rather than the text found in the\n * Original Code Source Code for Your Modifications.]\n *\n */\npackage org.mulgara.server.rmi;\n\n// Java 2 standard packages\nimport java.rmi.*;\nimport java.util.*;\n// Log4j\nimport org.apache.log4j.*;\n// JRDF\nimport org.jrdf.graph.*;\n// Third party packages\nimport org.mulgara.query.AbstractAnswer;\nimport org.mulgara.query.Answer;\nimport org.mulgara.query.TuplesException;\nimport org.mulgara.query.Variable;\n\n/**\n * Takes a regular answer and uses a map to convert blank nodes from server side\n * blank nodes to JRDF in memory blank nodes.\n *\n * @author Andrew Newman\n *\n * @created 2005-01-28\n *\n * @version $Revision: 1.2 $\n *\n * @modified $Date: 2005/02/02 21:15:04 $\n *\n * @maintenanceAuthor $Author: newmana $\n */\npublic class BlankNodeWrapperAnswer extends AbstractAnswer implements Answer {\n\n /**\n * Logger\n */\n @SuppressWarnings(\"unused\")\n private static final Logger logger = Logger.getLogger(BlankNodeWrapperAnswer.class.getName());\n\n /**\n * The wrapped instance.\n */\n protected Answer answer;\n\n /**\n * The blank node map.\n */\n protected Map blankNodeMap = null;\n\n /**\n * Creates a new wrapper for converting answers with blank nodes.\n *\n * @param answer the instance to wrap.\n * @param newBlankNodeMap a map which converts server side blank nodes to\n * in memory blank nodes.\n * @throws IllegalArgumentException if answer is null\n */\n public BlankNodeWrapperAnswer(Answer answer, Map newBlankNodeMap) throws RemoteException {\n this.answer = answer;\n blankNodeMap = newBlankNodeMap;\n }\n\n public Object clone() {\n BlankNodeWrapperAnswer cloned = (BlankNodeWrapperAnswer) super.clone();\n cloned.answer = (Answer) this.answer.clone();\n return cloned;\n }\n\n public Object getObject(int column) throws TuplesException {\n Object obj = answer.getObject(column);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n ", "post_mask_code": "\n\n public Object getObject(String columnName) throws TuplesException {\n Object obj = answer.getObject(columnName);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n /**\n * Returns the local value, the key of the hashmap, based on the given value\n * or null if not found. Does so by getting the entry set of the map and\n * testing each for the value - very inefficient.\n *\n * @param serverBlankNode the server side blank node to convert to an in\n * memory blank node.\n * @return the JRDF memory blank node or null if not found.\n */\n private BlankNode getKey(Object serverBlankNode) {\n Set> entrySet = blankNodeMap.entrySet();\n Iterator> iter = entrySet.iterator();\n while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n if (entry.getValue().equals(serverBlankNode)) {\n return entry.getKey();\n }\n }\n return null;\n }\n\n public void beforeFirst() throws TuplesException {\n answer.beforeFirst();\n }\n\n public void close() throws TuplesException {\n answer.close();\n }\n\n public int getColumnIndex(Variable column) throws TuplesException {\n return answer.getColumnIndex(column);\n }\n\n public int getNumberOfVariables() {\n return answer.getNumberOfVariables();\n }\n\n public Variable[] getVariables() {\n return answer.getVariables();\n }\n\n public boolean isUnconstrained() throws TuplesException {\n return answer.isUnconstrained();\n }\n\n public long getRowCount() throws TuplesException {\n return answer.getRowCount();\n }\n\n public long getRowUpperBound() throws TuplesException {\n return answer.getRowUpperBound();\n }\n\n public long getRowExpectedCount() throws TuplesException {\n return answer.getRowExpectedCount();\n }\n\n public int getRowCardinality() throws TuplesException {\n return answer.getRowCardinality();\n }\n\n public boolean isEmpty() throws TuplesException {\n return answer.isEmpty();\n }\n\n public boolean next() throws TuplesException {\n return answer.next();\n }\n}\n"} {"task_id": "Java_279", "language": "Java", "task_type": "single_line", "source_file": "java/github/quoll/mulgara/src/jar/server-rmi/java/org/mulgara/server/rmi/BlankNodeWrapperAnswer.java", "mask_start_position": 4854, "mask_end_position": 4873, "canonical_solution": "n answer.isEmpty();", "pre_mask_code": "/*\n *\n *\n * Contributor(s): N/A.\n *\n * [NOTE: The text of this Exhibit A may differ slightly from the text\n * of the notices in the Source Code files of the Original Code. You\n * should use the text of this Exhibit A rather than the text found in the\n * Original Code Source Code for Your Modifications.]\n *\n */\npackage org.mulgara.server.rmi;\n\n// Java 2 standard packages\nimport java.rmi.*;\nimport java.util.*;\n// Log4j\nimport org.apache.log4j.*;\n// JRDF\nimport org.jrdf.graph.*;\n// Third party packages\nimport org.mulgara.query.AbstractAnswer;\nimport org.mulgara.query.Answer;\nimport org.mulgara.query.TuplesException;\nimport org.mulgara.query.Variable;\n\n/**\n * Takes a regular answer and uses a map to convert blank nodes from server side\n * blank nodes to JRDF in memory blank nodes.\n *\n * @author Andrew Newman\n *\n * @created 2005-01-28\n *\n * @version $Revision: 1.2 $\n *\n * @modified $Date: 2005/02/02 21:15:04 $\n *\n * @maintenanceAuthor $Author: newmana $\n */\npublic class BlankNodeWrapperAnswer extends AbstractAnswer implements Answer {\n\n /**\n * Logger\n */\n @SuppressWarnings(\"unused\")\n private static final Logger logger = Logger.getLogger(BlankNodeWrapperAnswer.class.getName());\n\n /**\n * The wrapped instance.\n */\n protected Answer answer;\n\n /**\n * The blank node map.\n */\n protected Map blankNodeMap = null;\n\n /**\n * Creates a new wrapper for converting answers with blank nodes.\n *\n * @param answer the instance to wrap.\n * @param newBlankNodeMap a map which converts server side blank nodes to\n * in memory blank nodes.\n * @throws IllegalArgumentException if answer is null\n */\n public BlankNodeWrapperAnswer(Answer answer, Map newBlankNodeMap) throws RemoteException {\n this.answer = answer;\n blankNodeMap = newBlankNodeMap;\n }\n\n public Object clone() {\n BlankNodeWrapperAnswer cloned = (BlankNodeWrapperAnswer) super.clone();\n cloned.answer = (Answer) this.answer.clone();\n return cloned;\n }\n\n public Object getObject(int column) throws TuplesException {\n Object obj = answer.getObject(column);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n public Object getObject(String columnName) throws TuplesException {\n Object obj = answer.getObject(columnName);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n /**\n * Returns the local value, the key of the hashmap, based on the given value\n * or null if not found. Does so by getting the entry set of the map and\n * testing each for the value - very inefficient.\n *\n * @param serverBlankNode the server side blank node to convert to an in\n * memory blank node.\n * @return the JRDF memory blank node or null if not found.\n */\n private BlankNode getKey(Object serverBlankNode) {\n Set> entrySet = blankNodeMap.entrySet();\n Iterator> iter = entrySet.iterator();\n while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n if (entry.getValue().equals(serverBlankNode)) {\n return entry.getKey();\n }\n }\n return null;\n }\n\n public void beforeFirst() throws TuplesException {\n answer.beforeFirst();\n }\n\n public void close() throws TuplesException {\n answer.close();\n }\n\n public int getColumnIndex(Variable column) throws TuplesException {\n return answer.getColumnIndex(column);\n }\n\n public int getNumberOfVariables() {\n return answer.getNumberOfVariables();\n }\n\n public Variable[] getVariables() {\n return answer.getVariables();\n }\n\n public boolean isUnconstrained() throws TuplesException {\n return answer.isUnconstrained();\n }\n\n public long getRowCount() throws TuplesException {\n return answer.getRowCount();\n }\n\n public long getRowUpperBound() throws TuplesException {\n return answer.getRowUpperBound();\n }\n\n public long getRowExpectedCount() throws TuplesException {\n return answer.getRowExpectedCount();\n }\n\n public int getRowCardinality() throws TuplesException {\n return answer.getRowCardinality();\n }\n\n public boolean isEmpty() throws TuplesException {\n retur", "post_mask_code": "\n }\n\n public boolean next() throws TuplesException {\n return answer.next();\n }\n}\n"} {"task_id": "Java_280", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/quoll/mulgara/src/jar/server-rmi/java/org/mulgara/server/rmi/BlankNodeWrapperAnswer.java", "mask_start_position": 3277, "mask_end_position": 3768, "canonical_solution": "private BlankNode getKey(Object serverBlankNode) {\n Set> entrySet = blankNodeMap.entrySet();\n Iterator> iter = entrySet.iterator();\n while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n if (entry.getValue().equals(serverBlankNode)) {\n return entry.getKey();\n }\n }\n return null;\n }", "pre_mask_code": "/*\n *\n *\n * Contributor(s): N/A.\n *\n * [NOTE: The text of this Exhibit A may differ slightly from the text\n * of the notices in the Source Code files of the Original Code. You\n * should use the text of this Exhibit A rather than the text found in the\n * Original Code Source Code for Your Modifications.]\n *\n */\npackage org.mulgara.server.rmi;\n\n// Java 2 standard packages\nimport java.rmi.*;\nimport java.util.*;\n// Log4j\nimport org.apache.log4j.*;\n// JRDF\nimport org.jrdf.graph.*;\n// Third party packages\nimport org.mulgara.query.AbstractAnswer;\nimport org.mulgara.query.Answer;\nimport org.mulgara.query.TuplesException;\nimport org.mulgara.query.Variable;\n\n/**\n * Takes a regular answer and uses a map to convert blank nodes from server side\n * blank nodes to JRDF in memory blank nodes.\n *\n * @author Andrew Newman\n *\n * @created 2005-01-28\n *\n * @version $Revision: 1.2 $\n *\n * @modified $Date: 2005/02/02 21:15:04 $\n *\n * @maintenanceAuthor $Author: newmana $\n */\npublic class BlankNodeWrapperAnswer extends AbstractAnswer implements Answer {\n\n /**\n * Logger\n */\n @SuppressWarnings(\"unused\")\n private static final Logger logger = Logger.getLogger(BlankNodeWrapperAnswer.class.getName());\n\n /**\n * The wrapped instance.\n */\n protected Answer answer;\n\n /**\n * The blank node map.\n */\n protected Map blankNodeMap = null;\n\n /**\n * Creates a new wrapper for converting answers with blank nodes.\n *\n * @param answer the instance to wrap.\n * @param newBlankNodeMap a map which converts server side blank nodes to\n * in memory blank nodes.\n * @throws IllegalArgumentException if answer is null\n */\n public BlankNodeWrapperAnswer(Answer answer, Map newBlankNodeMap) throws RemoteException {\n this.answer = answer;\n blankNodeMap = newBlankNodeMap;\n }\n\n public Object clone() {\n BlankNodeWrapperAnswer cloned = (BlankNodeWrapperAnswer) super.clone();\n cloned.answer = (Answer) this.answer.clone();\n return cloned;\n }\n\n public Object getObject(int column) throws TuplesException {\n Object obj = answer.getObject(column);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n public Object getObject(String columnName) throws TuplesException {\n Object obj = answer.getObject(columnName);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n /**\n * Returns the local value, the key of the hashmap, based on the given value\n * or null if not found. Does so by getting the entry set of the map and\n * testing each for the value - very inefficient.\n *\n * @param serverBlankNode the server side blank node to convert to an in\n * memory blank node.\n * @return the JRDF memory blank node or null if not found.\n */\n ", "post_mask_code": "\n\n public void beforeFirst() throws TuplesException {\n answer.beforeFirst();\n }\n\n public void close() throws TuplesException {\n answer.close();\n }\n\n public int getColumnIndex(Variable column) throws TuplesException {\n return answer.getColumnIndex(column);\n }\n\n public int getNumberOfVariables() {\n return answer.getNumberOfVariables();\n }\n\n public Variable[] getVariables() {\n return answer.getVariables();\n }\n\n public boolean isUnconstrained() throws TuplesException {\n return answer.isUnconstrained();\n }\n\n public long getRowCount() throws TuplesException {\n return answer.getRowCount();\n }\n\n public long getRowUpperBound() throws TuplesException {\n return answer.getRowUpperBound();\n }\n\n public long getRowExpectedCount() throws TuplesException {\n return answer.getRowExpectedCount();\n }\n\n public int getRowCardinality() throws TuplesException {\n return answer.getRowCardinality();\n }\n\n public boolean isEmpty() throws TuplesException {\n return answer.isEmpty();\n }\n\n public boolean next() throws TuplesException {\n return answer.next();\n }\n}\n"} {"task_id": "Java_281", "language": "Java", "task_type": "if_statement", "source_file": "java/github/quoll/mulgara/src/jar/server-rmi/java/org/mulgara/server/rmi/BlankNodeWrapperAnswer.java", "mask_start_position": 2377, "mask_end_position": 2442, "canonical_solution": "if (newObj != null) {\n obj = newObj;\n }", "pre_mask_code": "/*\n *\n *\n * Contributor(s): N/A.\n *\n * [NOTE: The text of this Exhibit A may differ slightly from the text\n * of the notices in the Source Code files of the Original Code. You\n * should use the text of this Exhibit A rather than the text found in the\n * Original Code Source Code for Your Modifications.]\n *\n */\npackage org.mulgara.server.rmi;\n\n// Java 2 standard packages\nimport java.rmi.*;\nimport java.util.*;\n// Log4j\nimport org.apache.log4j.*;\n// JRDF\nimport org.jrdf.graph.*;\n// Third party packages\nimport org.mulgara.query.AbstractAnswer;\nimport org.mulgara.query.Answer;\nimport org.mulgara.query.TuplesException;\nimport org.mulgara.query.Variable;\n\n/**\n * Takes a regular answer and uses a map to convert blank nodes from server side\n * blank nodes to JRDF in memory blank nodes.\n *\n * @author Andrew Newman\n *\n * @created 2005-01-28\n *\n * @version $Revision: 1.2 $\n *\n * @modified $Date: 2005/02/02 21:15:04 $\n *\n * @maintenanceAuthor $Author: newmana $\n */\npublic class BlankNodeWrapperAnswer extends AbstractAnswer implements Answer {\n\n /**\n * Logger\n */\n @SuppressWarnings(\"unused\")\n private static final Logger logger = Logger.getLogger(BlankNodeWrapperAnswer.class.getName());\n\n /**\n * The wrapped instance.\n */\n protected Answer answer;\n\n /**\n * The blank node map.\n */\n protected Map blankNodeMap = null;\n\n /**\n * Creates a new wrapper for converting answers with blank nodes.\n *\n * @param answer the instance to wrap.\n * @param newBlankNodeMap a map which converts server side blank nodes to\n * in memory blank nodes.\n * @throws IllegalArgumentException if answer is null\n */\n public BlankNodeWrapperAnswer(Answer answer, Map newBlankNodeMap) throws RemoteException {\n this.answer = answer;\n blankNodeMap = newBlankNodeMap;\n }\n\n public Object clone() {\n BlankNodeWrapperAnswer cloned = (BlankNodeWrapperAnswer) super.clone();\n cloned.answer = (Answer) this.answer.clone();\n return cloned;\n }\n\n public Object getObject(int column) throws TuplesException {\n Object obj = answer.getObject(column);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n ", "post_mask_code": "\n }\n return obj;\n }\n\n public Object getObject(String columnName) throws TuplesException {\n Object obj = answer.getObject(columnName);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n /**\n * Returns the local value, the key of the hashmap, based on the given value\n * or null if not found. Does so by getting the entry set of the map and\n * testing each for the value - very inefficient.\n *\n * @param serverBlankNode the server side blank node to convert to an in\n * memory blank node.\n * @return the JRDF memory blank node or null if not found.\n */\n private BlankNode getKey(Object serverBlankNode) {\n Set> entrySet = blankNodeMap.entrySet();\n Iterator> iter = entrySet.iterator();\n while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n if (entry.getValue().equals(serverBlankNode)) {\n return entry.getKey();\n }\n }\n return null;\n }\n\n public void beforeFirst() throws TuplesException {\n answer.beforeFirst();\n }\n\n public void close() throws TuplesException {\n answer.close();\n }\n\n public int getColumnIndex(Variable column) throws TuplesException {\n return answer.getColumnIndex(column);\n }\n\n public int getNumberOfVariables() {\n return answer.getNumberOfVariables();\n }\n\n public Variable[] getVariables() {\n return answer.getVariables();\n }\n\n public boolean isUnconstrained() throws TuplesException {\n return answer.isUnconstrained();\n }\n\n public long getRowCount() throws TuplesException {\n return answer.getRowCount();\n }\n\n public long getRowUpperBound() throws TuplesException {\n return answer.getRowUpperBound();\n }\n\n public long getRowExpectedCount() throws TuplesException {\n return answer.getRowExpectedCount();\n }\n\n public int getRowCardinality() throws TuplesException {\n return answer.getRowCardinality();\n }\n\n public boolean isEmpty() throws TuplesException {\n return answer.isEmpty();\n }\n\n public boolean next() throws TuplesException {\n return answer.next();\n }\n}\n"} {"task_id": "Java_282", "language": "Java", "task_type": "while_statement", "source_file": "java/github/quoll/mulgara/src/jar/server-rmi/java/org/mulgara/server/rmi/BlankNodeWrapperAnswer.java", "mask_start_position": 3495, "mask_end_position": 3741, "canonical_solution": "while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n if (entry.getValue().equals(serverBlankNode)) {\n return entry.getKey();\n }\n }", "pre_mask_code": "/*\n *\n *\n * Contributor(s): N/A.\n *\n * [NOTE: The text of this Exhibit A may differ slightly from the text\n * of the notices in the Source Code files of the Original Code. You\n * should use the text of this Exhibit A rather than the text found in the\n * Original Code Source Code for Your Modifications.]\n *\n */\npackage org.mulgara.server.rmi;\n\n// Java 2 standard packages\nimport java.rmi.*;\nimport java.util.*;\n// Log4j\nimport org.apache.log4j.*;\n// JRDF\nimport org.jrdf.graph.*;\n// Third party packages\nimport org.mulgara.query.AbstractAnswer;\nimport org.mulgara.query.Answer;\nimport org.mulgara.query.TuplesException;\nimport org.mulgara.query.Variable;\n\n/**\n * Takes a regular answer and uses a map to convert blank nodes from server side\n * blank nodes to JRDF in memory blank nodes.\n *\n * @author Andrew Newman\n *\n * @created 2005-01-28\n *\n * @version $Revision: 1.2 $\n *\n * @modified $Date: 2005/02/02 21:15:04 $\n *\n * @maintenanceAuthor $Author: newmana $\n */\npublic class BlankNodeWrapperAnswer extends AbstractAnswer implements Answer {\n\n /**\n * Logger\n */\n @SuppressWarnings(\"unused\")\n private static final Logger logger = Logger.getLogger(BlankNodeWrapperAnswer.class.getName());\n\n /**\n * The wrapped instance.\n */\n protected Answer answer;\n\n /**\n * The blank node map.\n */\n protected Map blankNodeMap = null;\n\n /**\n * Creates a new wrapper for converting answers with blank nodes.\n *\n * @param answer the instance to wrap.\n * @param newBlankNodeMap a map which converts server side blank nodes to\n * in memory blank nodes.\n * @throws IllegalArgumentException if answer is null\n */\n public BlankNodeWrapperAnswer(Answer answer, Map newBlankNodeMap) throws RemoteException {\n this.answer = answer;\n blankNodeMap = newBlankNodeMap;\n }\n\n public Object clone() {\n BlankNodeWrapperAnswer cloned = (BlankNodeWrapperAnswer) super.clone();\n cloned.answer = (Answer) this.answer.clone();\n return cloned;\n }\n\n public Object getObject(int column) throws TuplesException {\n Object obj = answer.getObject(column);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n public Object getObject(String columnName) throws TuplesException {\n Object obj = answer.getObject(columnName);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n /**\n * Returns the local value, the key of the hashmap, based on the given value\n * or null if not found. Does so by getting the entry set of the map and\n * testing each for the value - very inefficient.\n *\n * @param serverBlankNode the server side blank node to convert to an in\n * memory blank node.\n * @return the JRDF memory blank node or null if not found.\n */\n private BlankNode getKey(Object serverBlankNode) {\n Set> entrySet = blankNodeMap.entrySet();\n Iterator> iter = entrySet.iterator();\n ", "post_mask_code": "\n return null;\n }\n\n public void beforeFirst() throws TuplesException {\n answer.beforeFirst();\n }\n\n public void close() throws TuplesException {\n answer.close();\n }\n\n public int getColumnIndex(Variable column) throws TuplesException {\n return answer.getColumnIndex(column);\n }\n\n public int getNumberOfVariables() {\n return answer.getNumberOfVariables();\n }\n\n public Variable[] getVariables() {\n return answer.getVariables();\n }\n\n public boolean isUnconstrained() throws TuplesException {\n return answer.isUnconstrained();\n }\n\n public long getRowCount() throws TuplesException {\n return answer.getRowCount();\n }\n\n public long getRowUpperBound() throws TuplesException {\n return answer.getRowUpperBound();\n }\n\n public long getRowExpectedCount() throws TuplesException {\n return answer.getRowExpectedCount();\n }\n\n public int getRowCardinality() throws TuplesException {\n return answer.getRowCardinality();\n }\n\n public boolean isEmpty() throws TuplesException {\n return answer.isEmpty();\n }\n\n public boolean next() throws TuplesException {\n return answer.next();\n }\n}\n"} {"task_id": "Java_283", "language": "Java", "task_type": "empty", "source_file": "java/github/quoll/mulgara/src/jar/server-rmi/java/org/mulgara/server/rmi/BlankNodeWrapperAnswer.java", "mask_start_position": 87, "mask_end_position": 87, "canonical_solution": "", "pre_mask_code": "/*\n *\n *\n * Contributor(s): N/A.\n *\n * [NOTE: The text of this Exhibit A may differ sli", "post_mask_code": "ghtly from the text\n * of the notices in the Source Code files of the Original Code. You\n * should use the text of this Exhibit A rather than the text found in the\n * Original Code Source Code for Your Modifications.]\n *\n */\npackage org.mulgara.server.rmi;\n\n// Java 2 standard packages\nimport java.rmi.*;\nimport java.util.*;\n// Log4j\nimport org.apache.log4j.*;\n// JRDF\nimport org.jrdf.graph.*;\n// Third party packages\nimport org.mulgara.query.AbstractAnswer;\nimport org.mulgara.query.Answer;\nimport org.mulgara.query.TuplesException;\nimport org.mulgara.query.Variable;\n\n/**\n * Takes a regular answer and uses a map to convert blank nodes from server side\n * blank nodes to JRDF in memory blank nodes.\n *\n * @author Andrew Newman\n *\n * @created 2005-01-28\n *\n * @version $Revision: 1.2 $\n *\n * @modified $Date: 2005/02/02 21:15:04 $\n *\n * @maintenanceAuthor $Author: newmana $\n */\npublic class BlankNodeWrapperAnswer extends AbstractAnswer implements Answer {\n\n /**\n * Logger\n */\n @SuppressWarnings(\"unused\")\n private static final Logger logger = Logger.getLogger(BlankNodeWrapperAnswer.class.getName());\n\n /**\n * The wrapped instance.\n */\n protected Answer answer;\n\n /**\n * The blank node map.\n */\n protected Map blankNodeMap = null;\n\n /**\n * Creates a new wrapper for converting answers with blank nodes.\n *\n * @param answer the instance to wrap.\n * @param newBlankNodeMap a map which converts server side blank nodes to\n * in memory blank nodes.\n * @throws IllegalArgumentException if answer is null\n */\n public BlankNodeWrapperAnswer(Answer answer, Map newBlankNodeMap) throws RemoteException {\n this.answer = answer;\n blankNodeMap = newBlankNodeMap;\n }\n\n public Object clone() {\n BlankNodeWrapperAnswer cloned = (BlankNodeWrapperAnswer) super.clone();\n cloned.answer = (Answer) this.answer.clone();\n return cloned;\n }\n\n public Object getObject(int column) throws TuplesException {\n Object obj = answer.getObject(column);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n public Object getObject(String columnName) throws TuplesException {\n Object obj = answer.getObject(columnName);\n // Convert server side blank nodes to in memory blank nodes.\n if (obj instanceof BlankNode) {\n Object newObj = getKey(obj);\n if (newObj != null) {\n obj = newObj;\n }\n }\n return obj;\n }\n\n /**\n * Returns the local value, the key of the hashmap, based on the given value\n * or null if not found. Does so by getting the entry set of the map and\n * testing each for the value - very inefficient.\n *\n * @param serverBlankNode the server side blank node to convert to an in\n * memory blank node.\n * @return the JRDF memory blank node or null if not found.\n */\n private BlankNode getKey(Object serverBlankNode) {\n Set> entrySet = blankNodeMap.entrySet();\n Iterator> iter = entrySet.iterator();\n while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n if (entry.getValue().equals(serverBlankNode)) {\n return entry.getKey();\n }\n }\n return null;\n }\n\n public void beforeFirst() throws TuplesException {\n answer.beforeFirst();\n }\n\n public void close() throws TuplesException {\n answer.close();\n }\n\n public int getColumnIndex(Variable column) throws TuplesException {\n return answer.getColumnIndex(column);\n }\n\n public int getNumberOfVariables() {\n return answer.getNumberOfVariables();\n }\n\n public Variable[] getVariables() {\n return answer.getVariables();\n }\n\n public boolean isUnconstrained() throws TuplesException {\n return answer.isUnconstrained();\n }\n\n public long getRowCount() throws TuplesException {\n return answer.getRowCount();\n }\n\n public long getRowUpperBound() throws TuplesException {\n return answer.getRowUpperBound();\n }\n\n public long getRowExpectedCount() throws TuplesException {\n return answer.getRowExpectedCount();\n }\n\n public int getRowCardinality() throws TuplesException {\n return answer.getRowCardinality();\n }\n\n public boolean isEmpty() throws TuplesException {\n return answer.isEmpty();\n }\n\n public boolean next() throws TuplesException {\n return answer.next();\n }\n}\n"} {"task_id": "Java_284", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/openengsb/openengsb/api/core/src/main/java/org/openengsb/core/api/ConnectorProvider.java", "mask_start_position": 1119, "mask_end_position": 1153, "canonical_solution": "ServiceDescriptor getDescriptor();", "pre_mask_code": "package org.openengsb.core.api;\n\nimport org.openengsb.core.api.descriptor.ServiceDescriptor;\nimport org.openengsb.core.api.l10n.LocalizableString;\n\n/**\n * Provides metadata describing a connector implementation.\n *\n * Each connector-implementation needs to export a service of this type, so it can be found by management services and\n * interface.\n */\npublic interface ConnectorProvider {\n\n /**\n * unique short human readable id to identify the connector-type (e.g. \"git\")\n */\n String getId();\n\n /**\n * The full name of the connector. This String is localized. It is recommended to use\n * {@link org.openengsb.core.api.l10n.BundleStrings} and bundle-properties to achieve this.\n */\n LocalizableString getName();\n\n /**\n * A description of the connector implementation. This String is localized. It is recommended to use\n * {@link org.openengsb.core.api.l10n.BundleStrings} and bundle-properties to achieve this.\n */\n LocalizableString getDescription();\n\n /**\n * A service-descriptor for determining what attributes this connector-implementation uses.\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_285", "language": "Java", "task_type": "empty", "source_file": "java/github/openengsb/openengsb/api/core/src/main/java/org/openengsb/core/api/ConnectorProvider.java", "mask_start_position": 1071, "mask_end_position": 1071, "canonical_solution": "", "pre_mask_code": "package org.openengsb.core.api;\n\nimport org.openengsb.core.api.descriptor.ServiceDescriptor;\nimport org.openengsb.core.api.l10n.LocalizableString;\n\n/**\n * Provides metadata describing a connector implementation.\n *\n * Each connector-implementation needs to export a service of this type, so it can be found by management services and\n * interface.\n */\npublic interface ConnectorProvider {\n\n /**\n * unique short human readable id to identify the connector-type (e.g. \"git\")\n */\n String getId();\n\n /**\n * The full name of the connector. This String is localized. It is recommended to use\n * {@link org.openengsb.core.api.l10n.BundleStrings} and bundle-properties to achieve this.\n */\n LocalizableString getName();\n\n /**\n * A description of the connector implementation. This String is localized. It is recommended to use\n * {@link org.openengsb.core.api.l10n.BundleStrings} and bundle-properties to achieve this.\n */\n LocalizableString getDescription();\n\n /**\n * A service-descriptor for determining what attributes ", "post_mask_code": "this connector-implementation uses.\n */\n ServiceDescriptor getDescriptor();\n}\n"} {"task_id": "Java_286", "language": "Java", "task_type": "method_signature", "source_file": "java/github/my2iu/Jinq/api/src/org/jinq/tuples/Tuple5.java", "mask_start_position": 633, "mask_end_position": 672, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "package org.jinq.tuples;\n\npublic class Tuple5 extends Tuple {\n\n final A one;\n\n final B two;\n\n final C three;\n\n final D four;\n\n final E five;\n\n public A getOne() {\n return one;\n }\n\n public B getTwo() {\n return two;\n }\n\n public C getThree() {\n return three;\n }\n\n public D getFour() {\n return four;\n }\n\n public E getFive() {\n return five;\n }\n\n public Tuple5(A one, B two, C three, D four, E five) {\n this.one = one;\n this.two = two;\n this.three = three;\n this.four = four;\n this.five = five;\n }\n\n ", "post_mask_code": "{\n return \"Tuple5(\" + getOne() + \",\" + getTwo() + \",\" + getThree() + \",\" + getFour() + \",\" + getFive() + \")\";\n }\n\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (!(obj instanceof Tuple5))\n return false;\n Tuple5 tuple = (Tuple5) obj;\n return (this.one == null ? tuple.one == null : this.one.equals(tuple.one)) && (this.two == null ? tuple.two == null : this.two.equals(tuple.two)) && (this.three == null ? tuple.three == null : this.three.equals(tuple.three)) && (this.four == null ? tuple.four == null : this.four.equals(tuple.four)) && (this.five == null ? tuple.five == null : this.five.equals(tuple.five));\n }\n\n public int hashCode() {\n return one.hashCode() + two.hashCode() + three.hashCode() + four.hashCode() + five.hashCode();\n }\n}\n"} {"task_id": "Java_287", "language": "Java", "task_type": "method_body", "source_file": "java/github/my2iu/Jinq/api/src/org/jinq/tuples/Tuple5.java", "mask_start_position": 298, "mask_end_position": 327, "canonical_solution": "{\n return three;\n }", "pre_mask_code": "package org.jinq.tuples;\n\npublic class Tuple5 extends Tuple {\n\n final A one;\n\n final B two;\n\n final C three;\n\n final D four;\n\n final E five;\n\n public A getOne() {\n return one;\n }\n\n public B getTwo() {\n return two;\n }\n\n public C getThree() ", "post_mask_code": "\n\n public D getFour() {\n return four;\n }\n\n public E getFive() {\n return five;\n }\n\n public Tuple5(A one, B two, C three, D four, E five) {\n this.one = one;\n this.two = two;\n this.three = three;\n this.four = four;\n this.five = five;\n }\n\n @Override\n public String toString() {\n return \"Tuple5(\" + getOne() + \",\" + getTwo() + \",\" + getThree() + \",\" + getFour() + \",\" + getFive() + \")\";\n }\n\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (!(obj instanceof Tuple5))\n return false;\n Tuple5 tuple = (Tuple5) obj;\n return (this.one == null ? tuple.one == null : this.one.equals(tuple.one)) && (this.two == null ? tuple.two == null : this.two.equals(tuple.two)) && (this.three == null ? tuple.three == null : this.three.equals(tuple.three)) && (this.four == null ? tuple.four == null : this.four.equals(tuple.four)) && (this.five == null ? tuple.five == null : this.five.equals(tuple.five));\n }\n\n public int hashCode() {\n return one.hashCode() + two.hashCode() + three.hashCode() + four.hashCode() + five.hashCode();\n }\n}\n"} {"task_id": "Java_288", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/my2iu/Jinq/api/src/org/jinq/tuples/Tuple5.java", "mask_start_position": 835, "mask_end_position": 885, "canonical_solution": "\n if (this == obj)\n return true;", "pre_mask_code": "package org.jinq.tuples;\n\npublic class Tuple5 extends Tuple {\n\n final A one;\n\n final B two;\n\n final C three;\n\n final D four;\n\n final E five;\n\n public A getOne() {\n return one;\n }\n\n public B getTwo() {\n return two;\n }\n\n public C getThree() {\n return three;\n }\n\n public D getFour() {\n return four;\n }\n\n public E getFive() {\n return five;\n }\n\n public Tuple5(A one, B two, C three, D four, E five) {\n this.one = one;\n this.two = two;\n this.three = three;\n this.four = four;\n this.five = five;\n }\n\n @Override\n public String toString() {\n return \"Tuple5(\" + getOne() + \",\" + getTwo() + \",\" + getThree() + \",\" + getFour() + \",\" + getFive() + \")\";\n }\n\n public boolean equals(Object obj) {", "post_mask_code": "\n if (!(obj instanceof Tuple5))\n return false;\n Tuple5 tuple = (Tuple5) obj;\n return (this.one == null ? tuple.one == null : this.one.equals(tuple.one)) && (this.two == null ? tuple.two == null : this.two.equals(tuple.two)) && (this.three == null ? tuple.three == null : this.three.equals(tuple.three)) && (this.four == null ? tuple.four == null : this.four.equals(tuple.four)) && (this.five == null ? tuple.five == null : this.five.equals(tuple.five));\n }\n\n public int hashCode() {\n return one.hashCode() + two.hashCode() + three.hashCode() + four.hashCode() + five.hashCode();\n }\n}\n"} {"task_id": "Java_289", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/my2iu/Jinq/api/src/org/jinq/tuples/Tuple5.java", "mask_start_position": 894, "mask_end_position": 1016, "canonical_solution": "if (!(obj instanceof Tuple5))\n return false;\n Tuple5 tuple = (Tuple5) obj;", "pre_mask_code": "package org.jinq.tuples;\n\npublic class Tuple5 extends Tuple {\n\n final A one;\n\n final B two;\n\n final C three;\n\n final D four;\n\n final E five;\n\n public A getOne() {\n return one;\n }\n\n public B getTwo() {\n return two;\n }\n\n public C getThree() {\n return three;\n }\n\n public D getFour() {\n return four;\n }\n\n public E getFive() {\n return five;\n }\n\n public Tuple5(A one, B two, C three, D four, E five) {\n this.one = one;\n this.two = two;\n this.three = three;\n this.four = four;\n this.five = five;\n }\n\n @Override\n public String toString() {\n return \"Tuple5(\" + getOne() + \",\" + getTwo() + \",\" + getThree() + \",\" + getFour() + \",\" + getFive() + \")\";\n }\n\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n ", "post_mask_code": "\n return (this.one == null ? tuple.one == null : this.one.equals(tuple.one)) && (this.two == null ? tuple.two == null : this.two.equals(tuple.two)) && (this.three == null ? tuple.three == null : this.three.equals(tuple.three)) && (this.four == null ? tuple.four == null : this.four.equals(tuple.four)) && (this.five == null ? tuple.five == null : this.five.equals(tuple.five));\n }\n\n public int hashCode() {\n return one.hashCode() + two.hashCode() + three.hashCode() + four.hashCode() + five.hashCode();\n }\n}\n"} {"task_id": "Java_290", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/my2iu/Jinq/api/src/org/jinq/tuples/Tuple5.java", "mask_start_position": 1025, "mask_end_position": 1406, "canonical_solution": "return (this.one == null ? tuple.one == null : this.one.equals(tuple.one)) && (this.two == null ? tuple.two == null : this.two.equals(tuple.two)) && (this.three == null ? tuple.three == null : this.three.equals(tuple.three)) && (this.four == null ? tuple.four == null : this.four.equals(tuple.four)) && (this.five == null ? tuple.five == null : this.five.equals(tuple.five));\n }", "pre_mask_code": "package org.jinq.tuples;\n\npublic class Tuple5 extends Tuple {\n\n final A one;\n\n final B two;\n\n final C three;\n\n final D four;\n\n final E five;\n\n public A getOne() {\n return one;\n }\n\n public B getTwo() {\n return two;\n }\n\n public C getThree() {\n return three;\n }\n\n public D getFour() {\n return four;\n }\n\n public E getFive() {\n return five;\n }\n\n public Tuple5(A one, B two, C three, D four, E five) {\n this.one = one;\n this.two = two;\n this.three = three;\n this.four = four;\n this.five = five;\n }\n\n @Override\n public String toString() {\n return \"Tuple5(\" + getOne() + \",\" + getTwo() + \",\" + getThree() + \",\" + getFour() + \",\" + getFive() + \")\";\n }\n\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (!(obj instanceof Tuple5))\n return false;\n Tuple5 tuple = (Tuple5) obj;\n ", "post_mask_code": "\n\n public int hashCode() {\n return one.hashCode() + two.hashCode() + three.hashCode() + four.hashCode() + five.hashCode();\n }\n}\n"} {"task_id": "Java_291", "language": "Java", "task_type": "single_line", "source_file": "java/github/my2iu/Jinq/api/src/org/jinq/tuples/Tuple5.java", "mask_start_position": 731, "mask_end_position": 788, "canonical_solution": "\" + getThree() + \",\" + getFour() + \",\" + getFive() + \")\";", "pre_mask_code": "package org.jinq.tuples;\n\npublic class Tuple5 extends Tuple {\n\n final A one;\n\n final B two;\n\n final C three;\n\n final D four;\n\n final E five;\n\n public A getOne() {\n return one;\n }\n\n public B getTwo() {\n return two;\n }\n\n public C getThree() {\n return three;\n }\n\n public D getFour() {\n return four;\n }\n\n public E getFive() {\n return five;\n }\n\n public Tuple5(A one, B two, C three, D four, E five) {\n this.one = one;\n this.two = two;\n this.three = three;\n this.four = four;\n this.five = five;\n }\n\n @Override\n public String toString() {\n return \"Tuple5(\" + getOne() + \",\" + getTwo() + \",", "post_mask_code": "\n }\n\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (!(obj instanceof Tuple5))\n return false;\n Tuple5 tuple = (Tuple5) obj;\n return (this.one == null ? tuple.one == null : this.one.equals(tuple.one)) && (this.two == null ? tuple.two == null : this.two.equals(tuple.two)) && (this.three == null ? tuple.three == null : this.three.equals(tuple.three)) && (this.four == null ? tuple.four == null : this.four.equals(tuple.four)) && (this.five == null ? tuple.five == null : this.five.equals(tuple.five));\n }\n\n public int hashCode() {\n return one.hashCode() + two.hashCode() + three.hashCode() + four.hashCode() + five.hashCode();\n }\n}\n"} {"task_id": "Java_292", "language": "Java", "task_type": "if_statement", "source_file": "java/github/my2iu/Jinq/api/src/org/jinq/tuples/Tuple5.java", "mask_start_position": 894, "mask_end_position": 949, "canonical_solution": "if (!(obj instanceof Tuple5))\n return false;", "pre_mask_code": "package org.jinq.tuples;\n\npublic class Tuple5 extends Tuple {\n\n final A one;\n\n final B two;\n\n final C three;\n\n final D four;\n\n final E five;\n\n public A getOne() {\n return one;\n }\n\n public B getTwo() {\n return two;\n }\n\n public C getThree() {\n return three;\n }\n\n public D getFour() {\n return four;\n }\n\n public E getFive() {\n return five;\n }\n\n public Tuple5(A one, B two, C three, D four, E five) {\n this.one = one;\n this.two = two;\n this.three = three;\n this.four = four;\n this.five = five;\n }\n\n @Override\n public String toString() {\n return \"Tuple5(\" + getOne() + \",\" + getTwo() + \",\" + getThree() + \",\" + getFour() + \",\" + getFive() + \")\";\n }\n\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n ", "post_mask_code": "\n Tuple5 tuple = (Tuple5) obj;\n return (this.one == null ? tuple.one == null : this.one.equals(tuple.one)) && (this.two == null ? tuple.two == null : this.two.equals(tuple.two)) && (this.three == null ? tuple.three == null : this.three.equals(tuple.three)) && (this.four == null ? tuple.four == null : this.four.equals(tuple.four)) && (this.five == null ? tuple.five == null : this.five.equals(tuple.five));\n }\n\n public int hashCode() {\n return one.hashCode() + two.hashCode() + three.hashCode() + four.hashCode() + five.hashCode();\n }\n}\n"} {"task_id": "Java_293", "language": "Java", "task_type": "empty", "source_file": "java/github/my2iu/Jinq/api/src/org/jinq/tuples/Tuple5.java", "mask_start_position": 1255, "mask_end_position": 1255, "canonical_solution": "", "pre_mask_code": "package org.jinq.tuples;\n\npublic class Tuple5 extends Tuple {\n\n final A one;\n\n final B two;\n\n final C three;\n\n final D four;\n\n final E five;\n\n public A getOne() {\n return one;\n }\n\n public B getTwo() {\n return two;\n }\n\n public C getThree() {\n return three;\n }\n\n public D getFour() {\n return four;\n }\n\n public E getFive() {\n return five;\n }\n\n public Tuple5(A one, B two, C three, D four, E five) {\n this.one = one;\n this.two = two;\n this.three = three;\n this.four = four;\n this.five = five;\n }\n\n @Override\n public String toString() {\n return \"Tuple5(\" + getOne() + \",\" + getTwo() + \",\" + getThree() + \",\" + getFour() + \",\" + getFive() + \")\";\n }\n\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (!(obj instanceof Tuple5))\n return false;\n Tuple5 tuple = (Tuple5) obj;\n return (this.one == null ? tuple.one == null : this.one.equals(tuple.one)) && (this.two == null ? tuple.two == null : this.two.equals(tuple.two)) && (this.three == null ? tuple.three == null : this.three.equals(tuple.three)) && (t", "post_mask_code": "his.four == null ? tuple.four == null : this.four.equals(tuple.four)) && (this.five == null ? tuple.five == null : this.five.equals(tuple.five));\n }\n\n public int hashCode() {\n return one.hashCode() + two.hashCode() + three.hashCode() + four.hashCode() + five.hashCode();\n }\n}\n"} {"task_id": "Java_294", "language": "Java", "task_type": "method_signature", "source_file": "java/github/hortonworks/cloudbreak/freeipa-api/src/main/java/com/sequenceiq/freeipa/api/v1/dns/model/AddDnsZoneForSubnetIdsRequest.java", "mask_start_position": 1331, "mask_end_position": 1370, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "package com.sequenceiq.freeipa.api.v1.dns.model;\n\nimport javax.validation.constraints.NotNull;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.sequenceiq.cloudbreak.auth.crn.CrnResourceDescriptor;\nimport com.sequenceiq.cloudbreak.validation.ValidCrn;\nimport com.sequenceiq.service.api.doc.ModelDescriptions;\nimport io.swagger.annotations.ApiModel;\nimport io.swagger.annotations.ApiModelProperty;\n\n@ApiModel(\"AddDnsZoneForSubnetIdsV1Request\")\n@JsonIgnoreProperties(ignoreUnknown = true)\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class AddDnsZoneForSubnetIdsRequest {\n\n @ValidCrn(resource = CrnResourceDescriptor.ENVIRONMENT)\n @NotNull\n @ApiModelProperty(value = ModelDescriptions.ENVIRONMENT_CRN, required = true)\n private String environmentCrn;\n\n @NotNull\n private AddDnsZoneNetwork addDnsZoneNetwork;\n\n public String getEnvironmentCrn() {\n return environmentCrn;\n }\n\n public void setEnvironmentCrn(String environmentCrn) {\n this.environmentCrn = environmentCrn;\n }\n\n public AddDnsZoneNetwork getAddDnsZoneNetwork() {\n return addDnsZoneNetwork;\n }\n\n public void setAddDnsZoneNetwork(AddDnsZoneNetwork addDnsZoneNetwork) {\n this.addDnsZoneNetwork = addDnsZoneNetwork;\n }\n\n ", "post_mask_code": "{\n return \"AddDnsZoneForSubnetIdsRequest{\" + \"environmentCrn='\" + environmentCrn + '\\'' + \", addDnsZoneNetwork=\" + addDnsZoneNetwork + '}';\n }\n}\n"} {"task_id": "Java_295", "language": "Java", "task_type": "method_body", "source_file": "java/github/hortonworks/cloudbreak/freeipa-api/src/main/java/com/sequenceiq/freeipa/api/v1/dns/model/AddDnsZoneForSubnetIdsRequest.java", "mask_start_position": 1266, "mask_end_position": 1325, "canonical_solution": "{\n this.addDnsZoneNetwork = addDnsZoneNetwork;\n }", "pre_mask_code": "package com.sequenceiq.freeipa.api.v1.dns.model;\n\nimport javax.validation.constraints.NotNull;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.sequenceiq.cloudbreak.auth.crn.CrnResourceDescriptor;\nimport com.sequenceiq.cloudbreak.validation.ValidCrn;\nimport com.sequenceiq.service.api.doc.ModelDescriptions;\nimport io.swagger.annotations.ApiModel;\nimport io.swagger.annotations.ApiModelProperty;\n\n@ApiModel(\"AddDnsZoneForSubnetIdsV1Request\")\n@JsonIgnoreProperties(ignoreUnknown = true)\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class AddDnsZoneForSubnetIdsRequest {\n\n @ValidCrn(resource = CrnResourceDescriptor.ENVIRONMENT)\n @NotNull\n @ApiModelProperty(value = ModelDescriptions.ENVIRONMENT_CRN, required = true)\n private String environmentCrn;\n\n @NotNull\n private AddDnsZoneNetwork addDnsZoneNetwork;\n\n public String getEnvironmentCrn() {\n return environmentCrn;\n }\n\n public void setEnvironmentCrn(String environmentCrn) {\n this.environmentCrn = environmentCrn;\n }\n\n public AddDnsZoneNetwork getAddDnsZoneNetwork() {\n return addDnsZoneNetwork;\n }\n\n public void setAddDnsZoneNetwork(AddDnsZoneNetwork addDnsZoneNetwork) ", "post_mask_code": "\n\n @Override\n public String toString() {\n return \"AddDnsZoneForSubnetIdsRequest{\" + \"environmentCrn='\" + environmentCrn + '\\'' + \", addDnsZoneNetwork=\" + addDnsZoneNetwork + '}';\n }\n}\n"} {"task_id": "Java_296", "language": "Java", "task_type": "single_line", "source_file": "java/github/hortonworks/cloudbreak/freeipa-api/src/main/java/com/sequenceiq/freeipa/api/v1/dns/model/AddDnsZoneForSubnetIdsRequest.java", "mask_start_position": 1177, "mask_end_position": 1184, "canonical_solution": "etwork;", "pre_mask_code": "package com.sequenceiq.freeipa.api.v1.dns.model;\n\nimport javax.validation.constraints.NotNull;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.sequenceiq.cloudbreak.auth.crn.CrnResourceDescriptor;\nimport com.sequenceiq.cloudbreak.validation.ValidCrn;\nimport com.sequenceiq.service.api.doc.ModelDescriptions;\nimport io.swagger.annotations.ApiModel;\nimport io.swagger.annotations.ApiModelProperty;\n\n@ApiModel(\"AddDnsZoneForSubnetIdsV1Request\")\n@JsonIgnoreProperties(ignoreUnknown = true)\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class AddDnsZoneForSubnetIdsRequest {\n\n @ValidCrn(resource = CrnResourceDescriptor.ENVIRONMENT)\n @NotNull\n @ApiModelProperty(value = ModelDescriptions.ENVIRONMENT_CRN, required = true)\n private String environmentCrn;\n\n @NotNull\n private AddDnsZoneNetwork addDnsZoneNetwork;\n\n public String getEnvironmentCrn() {\n return environmentCrn;\n }\n\n public void setEnvironmentCrn(String environmentCrn) {\n this.environmentCrn = environmentCrn;\n }\n\n public AddDnsZoneNetwork getAddDnsZoneNetwork() {\n return addDnsZoneN", "post_mask_code": "\n }\n\n public void setAddDnsZoneNetwork(AddDnsZoneNetwork addDnsZoneNetwork) {\n this.addDnsZoneNetwork = addDnsZoneNetwork;\n }\n\n @Override\n public String toString() {\n return \"AddDnsZoneForSubnetIdsRequest{\" + \"environmentCrn='\" + environmentCrn + '\\'' + \", addDnsZoneNetwork=\" + addDnsZoneNetwork + '}';\n }\n}\n"} {"task_id": "Java_297", "language": "Java", "task_type": "empty", "source_file": "java/github/hortonworks/cloudbreak/freeipa-api/src/main/java/com/sequenceiq/freeipa/api/v1/dns/model/AddDnsZoneForSubnetIdsRequest.java", "mask_start_position": 230, "mask_end_position": 230, "canonical_solution": "", "pre_mask_code": "package com.sequenceiq.freeipa.api.v1.dns.model;\n\nimport javax.validation.constraints.NotNull;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.sequencei", "post_mask_code": "q.cloudbreak.auth.crn.CrnResourceDescriptor;\nimport com.sequenceiq.cloudbreak.validation.ValidCrn;\nimport com.sequenceiq.service.api.doc.ModelDescriptions;\nimport io.swagger.annotations.ApiModel;\nimport io.swagger.annotations.ApiModelProperty;\n\n@ApiModel(\"AddDnsZoneForSubnetIdsV1Request\")\n@JsonIgnoreProperties(ignoreUnknown = true)\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class AddDnsZoneForSubnetIdsRequest {\n\n @ValidCrn(resource = CrnResourceDescriptor.ENVIRONMENT)\n @NotNull\n @ApiModelProperty(value = ModelDescriptions.ENVIRONMENT_CRN, required = true)\n private String environmentCrn;\n\n @NotNull\n private AddDnsZoneNetwork addDnsZoneNetwork;\n\n public String getEnvironmentCrn() {\n return environmentCrn;\n }\n\n public void setEnvironmentCrn(String environmentCrn) {\n this.environmentCrn = environmentCrn;\n }\n\n public AddDnsZoneNetwork getAddDnsZoneNetwork() {\n return addDnsZoneNetwork;\n }\n\n public void setAddDnsZoneNetwork(AddDnsZoneNetwork addDnsZoneNetwork) {\n this.addDnsZoneNetwork = addDnsZoneNetwork;\n }\n\n @Override\n public String toString() {\n return \"AddDnsZoneForSubnetIdsRequest{\" + \"environmentCrn='\" + environmentCrn + '\\'' + \", addDnsZoneNetwork=\" + addDnsZoneNetwork + '}';\n }\n}\n"} {"task_id": "Java_298", "language": "Java", "task_type": "method_signature", "source_file": "java/github/limpoxe/Android-Plugin-Framework/Samples/PluginTest/src/main/java/com/example/plugintest/manymethods/i/a/A4.java", "mask_start_position": 72, "mask_end_position": 106, "canonical_solution": "public static void a0(String msg) ", "pre_mask_code": "package com.example.plugintest.manymethods.i.a;\n\npublic class A4 {\n\n ", "post_mask_code": "{\n System.out.println(\"msg=\" + msg + 0);\n }\n\n public static void a1(String msg) {\n System.out.println(\"msg=\" + msg + 1);\n }\n\n public static void a2(String msg) {\n System.out.println(\"msg=\" + msg + 2);\n }\n\n public static void a3(String msg) {\n System.out.println(\"msg=\" + msg + 3);\n }\n\n public static void a4(String msg) {\n System.out.println(\"msg=\" + msg + 4);\n }\n\n public static void a5(String msg) {\n System.out.println(\"msg=\" + msg + 5);\n }\n\n public static void a6(String msg) {\n System.out.println(\"msg=\" + msg + 6);\n }\n\n public static void a7(String msg) {\n System.out.println(\"msg=\" + msg + 7);\n }\n\n public static void a8(String msg) {\n System.out.println(\"msg=\" + msg + 8);\n }\n\n public static void a9(String msg) {\n System.out.println(\"msg=\" + msg + 9);\n }\n\n public static void a10(String msg) {\n System.out.println(\"msg=\" + msg + 10);\n }\n\n public static void a11(String msg) {\n System.out.println(\"msg=\" + msg + 11);\n }\n\n public static void a12(String msg) {\n System.out.println(\"msg=\" + msg + 12);\n }\n\n public static void a13(String msg) {\n System.out.println(\"msg=\" + msg + 13);\n }\n\n public static void a14(String msg) {\n System.out.println(\"msg=\" + msg + 14);\n }\n\n public static void a15(String msg) {\n System.out.println(\"msg=\" + msg + 15);\n }\n\n public static void a16(String msg) {\n System.out.println(\"msg=\" + msg + 16);\n }\n\n public static void a17(String msg) {\n System.out.println(\"msg=\" + msg + 17);\n }\n\n public static void a18(String msg) {\n System.out.println(\"msg=\" + msg + 18);\n }\n\n public static void a19(String msg) {\n System.out.println(\"msg=\" + msg + 19);\n }\n\n public static void a20(String msg) {\n System.out.println(\"msg=\" + msg + 20);\n }\n\n public static void a21(String msg) {\n System.out.println(\"msg=\" + msg + 21);\n }\n\n public static void a22(String msg) {\n System.out.println(\"msg=\" + msg + 22);\n }\n\n public static void a23(String msg) {\n System.out.println(\"msg=\" + msg + 23);\n }\n\n public static void a24(String msg) {\n System.out.println(\"msg=\" + msg + 24);\n }\n\n public static void a25(String msg) {\n System.out.println(\"msg=\" + msg + 25);\n }\n\n public static void a26(String msg) {\n System.out.println(\"msg=\" + msg + 26);\n }\n\n public static void a27(String msg) {\n System.out.println(\"msg=\" + msg + 27);\n }\n\n public static void a28(String msg) {\n System.out.println(\"msg=\" + msg + 28);\n }\n\n public static void a29(String msg) {\n System.out.println(\"msg=\" + msg + 29);\n }\n\n public static void a30(String msg) {\n System.out.println(\"msg=\" + msg + 30);\n }\n\n public static void a31(String msg) {\n System.out.println(\"msg=\" + msg + 31);\n }\n\n public static void a32(String msg) {\n System.out.println(\"msg=\" + msg + 32);\n }\n\n public static void a33(String msg) {\n System.out.println(\"msg=\" + msg + 33);\n }\n\n public static void a34(String msg) {\n System.out.println(\"msg=\" + msg + 34);\n }\n\n public static void a35(String msg) {\n System.out.println(\"msg=\" + msg + 35);\n }\n\n public static void a36(String msg) {\n System.out.println(\"msg=\" + msg + 36);\n }\n\n public static void a37(String msg) {\n System.out.println(\"msg=\" + msg + 37);\n }\n\n public static void a38(String msg) {\n System.out.println(\"msg=\" + msg + 38);\n }\n\n public static void a39(String msg) {\n System.out.println(\"msg=\" + msg + 39);\n }\n\n public static void a40(String msg) {\n System.out.println(\"msg=\" + msg + 40);\n }\n\n public static void a41(String msg) {\n System.out.println(\"msg=\" + msg + 41);\n }\n\n public static void a42(String msg) {\n System.out.println(\"msg=\" + msg + 42);\n }\n\n public static void a43(String msg) {\n System.out.println(\"msg=\" + msg + 43);\n }\n\n public static void a44(String msg) {\n System.out.println(\"msg=\" + msg + 44);\n }\n\n public static void a45(String msg) {\n System.out.println(\"msg=\" + msg + 45);\n }\n\n public static void a46(String msg) {\n System.out.println(\"msg=\" + msg + 46);\n }\n\n public static void a47(String msg) {\n System.out.println(\"msg=\" + msg + 47);\n }\n\n public static void a48(String msg) {\n System.out.println(\"msg=\" + msg + 48);\n }\n\n public static void a49(String msg) {\n System.out.println(\"msg=\" + msg + 49);\n }\n\n public static void a50(String msg) {\n System.out.println(\"msg=\" + msg + 50);\n }\n\n public static void a51(String msg) {\n System.out.println(\"msg=\" + msg + 51);\n }\n\n public static void a52(String msg) {\n System.out.println(\"msg=\" + msg + 52);\n }\n\n public static void a53(String msg) {\n System.out.println(\"msg=\" + msg + 53);\n }\n\n public static void a54(String msg) {\n System.out.println(\"msg=\" + msg + 54);\n }\n\n public static void a55(String msg) {\n System.out.println(\"msg=\" + msg + 55);\n }\n\n public static void a56(String msg) {\n System.out.println(\"msg=\" + msg + 56);\n }\n\n public static void a57(String msg) {\n System.out.println(\"msg=\" + msg + 57);\n }\n\n public static void a58(String msg) {\n System.out.println(\"msg=\" + msg + 58);\n }\n\n public static void a59(String msg) {\n System.out.println(\"msg=\" + msg + 59);\n }\n\n public static void a60(String msg) {\n System.out.println(\"msg=\" + msg + 60);\n }\n\n public static void a61(String msg) {\n System.out.println(\"msg=\" + msg + 61);\n }\n\n public static void a62(String msg) {\n System.out.println(\"msg=\" + msg + 62);\n }\n\n public static void a63(String msg) {\n System.out.println(\"msg=\" + msg + 63);\n }\n\n public static void a64(String msg) {\n System.out.println(\"msg=\" + msg + 64);\n }\n\n public static void a65(String msg) {\n System.out.println(\"msg=\" + msg + 65);\n }\n\n public static void a66(String msg) {\n System.out.println(\"msg=\" + msg + 66);\n }\n\n public static void a67(String msg) {\n System.out.println(\"msg=\" + msg + 67);\n }\n\n public static void a68(String msg) {\n System.out.println(\"msg=\" + msg + 68);\n }\n\n public static void a69(String msg) {\n System.out.println(\"msg=\" + msg + 69);\n }\n\n public static void a70(String msg) {\n System.out.println(\"msg=\" + msg + 70);\n }\n\n public static void a71(String msg) {\n System.out.println(\"msg=\" + msg + 71);\n }\n\n public static void a72(String msg) {\n System.out.println(\"msg=\" + msg + 72);\n }\n\n public static void a73(String msg) {\n System.out.println(\"msg=\" + msg + 73);\n }\n\n public static void a74(String msg) {\n System.out.println(\"msg=\" + msg + 74);\n }\n\n public static void a75(String msg) {\n System.out.println(\"msg=\" + msg + 75);\n }\n\n public static void a76(String msg) {\n System.out.println(\"msg=\" + msg + 76);\n }\n\n public static void a77(String msg) {\n System.out.println(\"msg=\" + msg + 77);\n }\n\n public static void a78(String msg) {\n System.out.println(\"msg=\" + msg + 78);\n }\n\n public static void a79(String msg) {\n System.out.println(\"msg=\" + msg + 79);\n }\n\n public static void a80(String msg) {\n System.out.println(\"msg=\" + msg + 80);\n }\n\n public static void a81(String msg) {\n System.out.println(\"msg=\" + msg + 81);\n }\n\n public static void a82(String msg) {\n System.out.println(\"msg=\" + msg + 82);\n }\n\n public static void a83(String msg) {\n System.out.println(\"msg=\" + msg + 83);\n }\n\n public static void a84(String msg) {\n System.out.println(\"msg=\" + msg + 84);\n }\n\n public static void a85(String msg) {\n System.out.println(\"msg=\" + msg + 85);\n }\n\n public static void a86(String msg) {\n System.out.println(\"msg=\" + msg + 86);\n }\n\n public static void a87(String msg) {\n System.out.println(\"msg=\" + msg + 87);\n }\n\n public static void a88(String msg) {\n System.out.println(\"msg=\" + msg + 88);\n }\n\n public static void a89(String msg) {\n System.out.println(\"msg=\" + msg + 89);\n }\n\n public static void a90(String msg) {\n System.out.println(\"msg=\" + msg + 90);\n }\n\n public static void a91(String msg) {\n System.out.println(\"msg=\" + msg + 91);\n }\n\n public static void a92(String msg) {\n System.out.println(\"msg=\" + msg + 92);\n }\n\n public static void a93(String msg) {\n System.out.println(\"msg=\" + msg + 93);\n }\n\n public static void a94(String msg) {\n System.out.println(\"msg=\" + msg + 94);\n }\n\n public static void a95(String msg) {\n System.out.println(\"msg=\" + msg + 95);\n }\n\n public static void a96(String msg) {\n System.out.println(\"msg=\" + msg + 96);\n }\n\n public static void a97(String msg) {\n System.out.println(\"msg=\" + msg + 97);\n }\n\n public static void a98(String msg) {\n System.out.println(\"msg=\" + msg + 98);\n }\n\n public static void a99(String msg) {\n System.out.println(\"msg=\" + msg + 99);\n }\n}\n"} {"task_id": "Java_299", "language": "Java", "task_type": "method_body", "source_file": "java/github/limpoxe/Android-Plugin-Framework/Samples/PluginTest/src/main/java/com/example/plugintest/manymethods/i/a/A4.java", "mask_start_position": 8827, "mask_end_position": 8881, "canonical_solution": "{\n System.out.println(\"msg=\" + msg + 92);\n }", "pre_mask_code": "package com.example.plugintest.manymethods.i.a;\n\npublic class A4 {\n\n public static void a0(String msg) {\n System.out.println(\"msg=\" + msg + 0);\n }\n\n public static void a1(String msg) {\n System.out.println(\"msg=\" + msg + 1);\n }\n\n public static void a2(String msg) {\n System.out.println(\"msg=\" + msg + 2);\n }\n\n public static void a3(String msg) {\n System.out.println(\"msg=\" + msg + 3);\n }\n\n public static void a4(String msg) {\n System.out.println(\"msg=\" + msg + 4);\n }\n\n public static void a5(String msg) {\n System.out.println(\"msg=\" + msg + 5);\n }\n\n public static void a6(String msg) {\n System.out.println(\"msg=\" + msg + 6);\n }\n\n public static void a7(String msg) {\n System.out.println(\"msg=\" + msg + 7);\n }\n\n public static void a8(String msg) {\n System.out.println(\"msg=\" + msg + 8);\n }\n\n public static void a9(String msg) {\n System.out.println(\"msg=\" + msg + 9);\n }\n\n public static void a10(String msg) {\n System.out.println(\"msg=\" + msg + 10);\n }\n\n public static void a11(String msg) {\n System.out.println(\"msg=\" + msg + 11);\n }\n\n public static void a12(String msg) {\n System.out.println(\"msg=\" + msg + 12);\n }\n\n public static void a13(String msg) {\n System.out.println(\"msg=\" + msg + 13);\n }\n\n public static void a14(String msg) {\n System.out.println(\"msg=\" + msg + 14);\n }\n\n public static void a15(String msg) {\n System.out.println(\"msg=\" + msg + 15);\n }\n\n public static void a16(String msg) {\n System.out.println(\"msg=\" + msg + 16);\n }\n\n public static void a17(String msg) {\n System.out.println(\"msg=\" + msg + 17);\n }\n\n public static void a18(String msg) {\n System.out.println(\"msg=\" + msg + 18);\n }\n\n public static void a19(String msg) {\n System.out.println(\"msg=\" + msg + 19);\n }\n\n public static void a20(String msg) {\n System.out.println(\"msg=\" + msg + 20);\n }\n\n public static void a21(String msg) {\n System.out.println(\"msg=\" + msg + 21);\n }\n\n public static void a22(String msg) {\n System.out.println(\"msg=\" + msg + 22);\n }\n\n public static void a23(String msg) {\n System.out.println(\"msg=\" + msg + 23);\n }\n\n public static void a24(String msg) {\n System.out.println(\"msg=\" + msg + 24);\n }\n\n public static void a25(String msg) {\n System.out.println(\"msg=\" + msg + 25);\n }\n\n public static void a26(String msg) {\n System.out.println(\"msg=\" + msg + 26);\n }\n\n public static void a27(String msg) {\n System.out.println(\"msg=\" + msg + 27);\n }\n\n public static void a28(String msg) {\n System.out.println(\"msg=\" + msg + 28);\n }\n\n public static void a29(String msg) {\n System.out.println(\"msg=\" + msg + 29);\n }\n\n public static void a30(String msg) {\n System.out.println(\"msg=\" + msg + 30);\n }\n\n public static void a31(String msg) {\n System.out.println(\"msg=\" + msg + 31);\n }\n\n public static void a32(String msg) {\n System.out.println(\"msg=\" + msg + 32);\n }\n\n public static void a33(String msg) {\n System.out.println(\"msg=\" + msg + 33);\n }\n\n public static void a34(String msg) {\n System.out.println(\"msg=\" + msg + 34);\n }\n\n public static void a35(String msg) {\n System.out.println(\"msg=\" + msg + 35);\n }\n\n public static void a36(String msg) {\n System.out.println(\"msg=\" + msg + 36);\n }\n\n public static void a37(String msg) {\n System.out.println(\"msg=\" + msg + 37);\n }\n\n public static void a38(String msg) {\n System.out.println(\"msg=\" + msg + 38);\n }\n\n public static void a39(String msg) {\n System.out.println(\"msg=\" + msg + 39);\n }\n\n public static void a40(String msg) {\n System.out.println(\"msg=\" + msg + 40);\n }\n\n public static void a41(String msg) {\n System.out.println(\"msg=\" + msg + 41);\n }\n\n public static void a42(String msg) {\n System.out.println(\"msg=\" + msg + 42);\n }\n\n public static void a43(String msg) {\n System.out.println(\"msg=\" + msg + 43);\n }\n\n public static void a44(String msg) {\n System.out.println(\"msg=\" + msg + 44);\n }\n\n public static void a45(String msg) {\n System.out.println(\"msg=\" + msg + 45);\n }\n\n public static void a46(String msg) {\n System.out.println(\"msg=\" + msg + 46);\n }\n\n public static void a47(String msg) {\n System.out.println(\"msg=\" + msg + 47);\n }\n\n public static void a48(String msg) {\n System.out.println(\"msg=\" + msg + 48);\n }\n\n public static void a49(String msg) {\n System.out.println(\"msg=\" + msg + 49);\n }\n\n public static void a50(String msg) {\n System.out.println(\"msg=\" + msg + 50);\n }\n\n public static void a51(String msg) {\n System.out.println(\"msg=\" + msg + 51);\n }\n\n public static void a52(String msg) {\n System.out.println(\"msg=\" + msg + 52);\n }\n\n public static void a53(String msg) {\n System.out.println(\"msg=\" + msg + 53);\n }\n\n public static void a54(String msg) {\n System.out.println(\"msg=\" + msg + 54);\n }\n\n public static void a55(String msg) {\n System.out.println(\"msg=\" + msg + 55);\n }\n\n public static void a56(String msg) {\n System.out.println(\"msg=\" + msg + 56);\n }\n\n public static void a57(String msg) {\n System.out.println(\"msg=\" + msg + 57);\n }\n\n public static void a58(String msg) {\n System.out.println(\"msg=\" + msg + 58);\n }\n\n public static void a59(String msg) {\n System.out.println(\"msg=\" + msg + 59);\n }\n\n public static void a60(String msg) {\n System.out.println(\"msg=\" + msg + 60);\n }\n\n public static void a61(String msg) {\n System.out.println(\"msg=\" + msg + 61);\n }\n\n public static void a62(String msg) {\n System.out.println(\"msg=\" + msg + 62);\n }\n\n public static void a63(String msg) {\n System.out.println(\"msg=\" + msg + 63);\n }\n\n public static void a64(String msg) {\n System.out.println(\"msg=\" + msg + 64);\n }\n\n public static void a65(String msg) {\n System.out.println(\"msg=\" + msg + 65);\n }\n\n public static void a66(String msg) {\n System.out.println(\"msg=\" + msg + 66);\n }\n\n public static void a67(String msg) {\n System.out.println(\"msg=\" + msg + 67);\n }\n\n public static void a68(String msg) {\n System.out.println(\"msg=\" + msg + 68);\n }\n\n public static void a69(String msg) {\n System.out.println(\"msg=\" + msg + 69);\n }\n\n public static void a70(String msg) {\n System.out.println(\"msg=\" + msg + 70);\n }\n\n public static void a71(String msg) {\n System.out.println(\"msg=\" + msg + 71);\n }\n\n public static void a72(String msg) {\n System.out.println(\"msg=\" + msg + 72);\n }\n\n public static void a73(String msg) {\n System.out.println(\"msg=\" + msg + 73);\n }\n\n public static void a74(String msg) {\n System.out.println(\"msg=\" + msg + 74);\n }\n\n public static void a75(String msg) {\n System.out.println(\"msg=\" + msg + 75);\n }\n\n public static void a76(String msg) {\n System.out.println(\"msg=\" + msg + 76);\n }\n\n public static void a77(String msg) {\n System.out.println(\"msg=\" + msg + 77);\n }\n\n public static void a78(String msg) {\n System.out.println(\"msg=\" + msg + 78);\n }\n\n public static void a79(String msg) {\n System.out.println(\"msg=\" + msg + 79);\n }\n\n public static void a80(String msg) {\n System.out.println(\"msg=\" + msg + 80);\n }\n\n public static void a81(String msg) {\n System.out.println(\"msg=\" + msg + 81);\n }\n\n public static void a82(String msg) {\n System.out.println(\"msg=\" + msg + 82);\n }\n\n public static void a83(String msg) {\n System.out.println(\"msg=\" + msg + 83);\n }\n\n public static void a84(String msg) {\n System.out.println(\"msg=\" + msg + 84);\n }\n\n public static void a85(String msg) {\n System.out.println(\"msg=\" + msg + 85);\n }\n\n public static void a86(String msg) {\n System.out.println(\"msg=\" + msg + 86);\n }\n\n public static void a87(String msg) {\n System.out.println(\"msg=\" + msg + 87);\n }\n\n public static void a88(String msg) {\n System.out.println(\"msg=\" + msg + 88);\n }\n\n public static void a89(String msg) {\n System.out.println(\"msg=\" + msg + 89);\n }\n\n public static void a90(String msg) {\n System.out.println(\"msg=\" + msg + 90);\n }\n\n public static void a91(String msg) {\n System.out.println(\"msg=\" + msg + 91);\n }\n\n public static void a92(String msg) ", "post_mask_code": "\n\n public static void a93(String msg) {\n System.out.println(\"msg=\" + msg + 93);\n }\n\n public static void a94(String msg) {\n System.out.println(\"msg=\" + msg + 94);\n }\n\n public static void a95(String msg) {\n System.out.println(\"msg=\" + msg + 95);\n }\n\n public static void a96(String msg) {\n System.out.println(\"msg=\" + msg + 96);\n }\n\n public static void a97(String msg) {\n System.out.println(\"msg=\" + msg + 97);\n }\n\n public static void a98(String msg) {\n System.out.println(\"msg=\" + msg + 98);\n }\n\n public static void a99(String msg) {\n System.out.println(\"msg=\" + msg + 99);\n }\n}\n"} {"task_id": "Java_300", "language": "Java", "task_type": "single_line", "source_file": "java/github/limpoxe/Android-Plugin-Framework/Samples/PluginTest/src/main/java/com/example/plugintest/manymethods/i/a/A4.java", "mask_start_position": 4482, "mask_end_position": 4505, "canonical_solution": "tln(\"msg=\" + msg + 46);", "pre_mask_code": "package com.example.plugintest.manymethods.i.a;\n\npublic class A4 {\n\n public static void a0(String msg) {\n System.out.println(\"msg=\" + msg + 0);\n }\n\n public static void a1(String msg) {\n System.out.println(\"msg=\" + msg + 1);\n }\n\n public static void a2(String msg) {\n System.out.println(\"msg=\" + msg + 2);\n }\n\n public static void a3(String msg) {\n System.out.println(\"msg=\" + msg + 3);\n }\n\n public static void a4(String msg) {\n System.out.println(\"msg=\" + msg + 4);\n }\n\n public static void a5(String msg) {\n System.out.println(\"msg=\" + msg + 5);\n }\n\n public static void a6(String msg) {\n System.out.println(\"msg=\" + msg + 6);\n }\n\n public static void a7(String msg) {\n System.out.println(\"msg=\" + msg + 7);\n }\n\n public static void a8(String msg) {\n System.out.println(\"msg=\" + msg + 8);\n }\n\n public static void a9(String msg) {\n System.out.println(\"msg=\" + msg + 9);\n }\n\n public static void a10(String msg) {\n System.out.println(\"msg=\" + msg + 10);\n }\n\n public static void a11(String msg) {\n System.out.println(\"msg=\" + msg + 11);\n }\n\n public static void a12(String msg) {\n System.out.println(\"msg=\" + msg + 12);\n }\n\n public static void a13(String msg) {\n System.out.println(\"msg=\" + msg + 13);\n }\n\n public static void a14(String msg) {\n System.out.println(\"msg=\" + msg + 14);\n }\n\n public static void a15(String msg) {\n System.out.println(\"msg=\" + msg + 15);\n }\n\n public static void a16(String msg) {\n System.out.println(\"msg=\" + msg + 16);\n }\n\n public static void a17(String msg) {\n System.out.println(\"msg=\" + msg + 17);\n }\n\n public static void a18(String msg) {\n System.out.println(\"msg=\" + msg + 18);\n }\n\n public static void a19(String msg) {\n System.out.println(\"msg=\" + msg + 19);\n }\n\n public static void a20(String msg) {\n System.out.println(\"msg=\" + msg + 20);\n }\n\n public static void a21(String msg) {\n System.out.println(\"msg=\" + msg + 21);\n }\n\n public static void a22(String msg) {\n System.out.println(\"msg=\" + msg + 22);\n }\n\n public static void a23(String msg) {\n System.out.println(\"msg=\" + msg + 23);\n }\n\n public static void a24(String msg) {\n System.out.println(\"msg=\" + msg + 24);\n }\n\n public static void a25(String msg) {\n System.out.println(\"msg=\" + msg + 25);\n }\n\n public static void a26(String msg) {\n System.out.println(\"msg=\" + msg + 26);\n }\n\n public static void a27(String msg) {\n System.out.println(\"msg=\" + msg + 27);\n }\n\n public static void a28(String msg) {\n System.out.println(\"msg=\" + msg + 28);\n }\n\n public static void a29(String msg) {\n System.out.println(\"msg=\" + msg + 29);\n }\n\n public static void a30(String msg) {\n System.out.println(\"msg=\" + msg + 30);\n }\n\n public static void a31(String msg) {\n System.out.println(\"msg=\" + msg + 31);\n }\n\n public static void a32(String msg) {\n System.out.println(\"msg=\" + msg + 32);\n }\n\n public static void a33(String msg) {\n System.out.println(\"msg=\" + msg + 33);\n }\n\n public static void a34(String msg) {\n System.out.println(\"msg=\" + msg + 34);\n }\n\n public static void a35(String msg) {\n System.out.println(\"msg=\" + msg + 35);\n }\n\n public static void a36(String msg) {\n System.out.println(\"msg=\" + msg + 36);\n }\n\n public static void a37(String msg) {\n System.out.println(\"msg=\" + msg + 37);\n }\n\n public static void a38(String msg) {\n System.out.println(\"msg=\" + msg + 38);\n }\n\n public static void a39(String msg) {\n System.out.println(\"msg=\" + msg + 39);\n }\n\n public static void a40(String msg) {\n System.out.println(\"msg=\" + msg + 40);\n }\n\n public static void a41(String msg) {\n System.out.println(\"msg=\" + msg + 41);\n }\n\n public static void a42(String msg) {\n System.out.println(\"msg=\" + msg + 42);\n }\n\n public static void a43(String msg) {\n System.out.println(\"msg=\" + msg + 43);\n }\n\n public static void a44(String msg) {\n System.out.println(\"msg=\" + msg + 44);\n }\n\n public static void a45(String msg) {\n System.out.println(\"msg=\" + msg + 45);\n }\n\n public static void a46(String msg) {\n System.out.prin", "post_mask_code": "\n }\n\n public static void a47(String msg) {\n System.out.println(\"msg=\" + msg + 47);\n }\n\n public static void a48(String msg) {\n System.out.println(\"msg=\" + msg + 48);\n }\n\n public static void a49(String msg) {\n System.out.println(\"msg=\" + msg + 49);\n }\n\n public static void a50(String msg) {\n System.out.println(\"msg=\" + msg + 50);\n }\n\n public static void a51(String msg) {\n System.out.println(\"msg=\" + msg + 51);\n }\n\n public static void a52(String msg) {\n System.out.println(\"msg=\" + msg + 52);\n }\n\n public static void a53(String msg) {\n System.out.println(\"msg=\" + msg + 53);\n }\n\n public static void a54(String msg) {\n System.out.println(\"msg=\" + msg + 54);\n }\n\n public static void a55(String msg) {\n System.out.println(\"msg=\" + msg + 55);\n }\n\n public static void a56(String msg) {\n System.out.println(\"msg=\" + msg + 56);\n }\n\n public static void a57(String msg) {\n System.out.println(\"msg=\" + msg + 57);\n }\n\n public static void a58(String msg) {\n System.out.println(\"msg=\" + msg + 58);\n }\n\n public static void a59(String msg) {\n System.out.println(\"msg=\" + msg + 59);\n }\n\n public static void a60(String msg) {\n System.out.println(\"msg=\" + msg + 60);\n }\n\n public static void a61(String msg) {\n System.out.println(\"msg=\" + msg + 61);\n }\n\n public static void a62(String msg) {\n System.out.println(\"msg=\" + msg + 62);\n }\n\n public static void a63(String msg) {\n System.out.println(\"msg=\" + msg + 63);\n }\n\n public static void a64(String msg) {\n System.out.println(\"msg=\" + msg + 64);\n }\n\n public static void a65(String msg) {\n System.out.println(\"msg=\" + msg + 65);\n }\n\n public static void a66(String msg) {\n System.out.println(\"msg=\" + msg + 66);\n }\n\n public static void a67(String msg) {\n System.out.println(\"msg=\" + msg + 67);\n }\n\n public static void a68(String msg) {\n System.out.println(\"msg=\" + msg + 68);\n }\n\n public static void a69(String msg) {\n System.out.println(\"msg=\" + msg + 69);\n }\n\n public static void a70(String msg) {\n System.out.println(\"msg=\" + msg + 70);\n }\n\n public static void a71(String msg) {\n System.out.println(\"msg=\" + msg + 71);\n }\n\n public static void a72(String msg) {\n System.out.println(\"msg=\" + msg + 72);\n }\n\n public static void a73(String msg) {\n System.out.println(\"msg=\" + msg + 73);\n }\n\n public static void a74(String msg) {\n System.out.println(\"msg=\" + msg + 74);\n }\n\n public static void a75(String msg) {\n System.out.println(\"msg=\" + msg + 75);\n }\n\n public static void a76(String msg) {\n System.out.println(\"msg=\" + msg + 76);\n }\n\n public static void a77(String msg) {\n System.out.println(\"msg=\" + msg + 77);\n }\n\n public static void a78(String msg) {\n System.out.println(\"msg=\" + msg + 78);\n }\n\n public static void a79(String msg) {\n System.out.println(\"msg=\" + msg + 79);\n }\n\n public static void a80(String msg) {\n System.out.println(\"msg=\" + msg + 80);\n }\n\n public static void a81(String msg) {\n System.out.println(\"msg=\" + msg + 81);\n }\n\n public static void a82(String msg) {\n System.out.println(\"msg=\" + msg + 82);\n }\n\n public static void a83(String msg) {\n System.out.println(\"msg=\" + msg + 83);\n }\n\n public static void a84(String msg) {\n System.out.println(\"msg=\" + msg + 84);\n }\n\n public static void a85(String msg) {\n System.out.println(\"msg=\" + msg + 85);\n }\n\n public static void a86(String msg) {\n System.out.println(\"msg=\" + msg + 86);\n }\n\n public static void a87(String msg) {\n System.out.println(\"msg=\" + msg + 87);\n }\n\n public static void a88(String msg) {\n System.out.println(\"msg=\" + msg + 88);\n }\n\n public static void a89(String msg) {\n System.out.println(\"msg=\" + msg + 89);\n }\n\n public static void a90(String msg) {\n System.out.println(\"msg=\" + msg + 90);\n }\n\n public static void a91(String msg) {\n System.out.println(\"msg=\" + msg + 91);\n }\n\n public static void a92(String msg) {\n System.out.println(\"msg=\" + msg + 92);\n }\n\n public static void a93(String msg) {\n System.out.println(\"msg=\" + msg + 93);\n }\n\n public static void a94(String msg) {\n System.out.println(\"msg=\" + msg + 94);\n }\n\n public static void a95(String msg) {\n System.out.println(\"msg=\" + msg + 95);\n }\n\n public static void a96(String msg) {\n System.out.println(\"msg=\" + msg + 96);\n }\n\n public static void a97(String msg) {\n System.out.println(\"msg=\" + msg + 97);\n }\n\n public static void a98(String msg) {\n System.out.println(\"msg=\" + msg + 98);\n }\n\n public static void a99(String msg) {\n System.out.println(\"msg=\" + msg + 99);\n }\n}\n"} {"task_id": "Java_301", "language": "Java", "task_type": "empty", "source_file": "java/github/limpoxe/Android-Plugin-Framework/Samples/PluginTest/src/main/java/com/example/plugintest/manymethods/i/a/A4.java", "mask_start_position": 3095, "mask_end_position": 3095, "canonical_solution": "", "pre_mask_code": "package com.example.plugintest.manymethods.i.a;\n\npublic class A4 {\n\n public static void a0(String msg) {\n System.out.println(\"msg=\" + msg + 0);\n }\n\n public static void a1(String msg) {\n System.out.println(\"msg=\" + msg + 1);\n }\n\n public static void a2(String msg) {\n System.out.println(\"msg=\" + msg + 2);\n }\n\n public static void a3(String msg) {\n System.out.println(\"msg=\" + msg + 3);\n }\n\n public static void a4(String msg) {\n System.out.println(\"msg=\" + msg + 4);\n }\n\n public static void a5(String msg) {\n System.out.println(\"msg=\" + msg + 5);\n }\n\n public static void a6(String msg) {\n System.out.println(\"msg=\" + msg + 6);\n }\n\n public static void a7(String msg) {\n System.out.println(\"msg=\" + msg + 7);\n }\n\n public static void a8(String msg) {\n System.out.println(\"msg=\" + msg + 8);\n }\n\n public static void a9(String msg) {\n System.out.println(\"msg=\" + msg + 9);\n }\n\n public static void a10(String msg) {\n System.out.println(\"msg=\" + msg + 10);\n }\n\n public static void a11(String msg) {\n System.out.println(\"msg=\" + msg + 11);\n }\n\n public static void a12(String msg) {\n System.out.println(\"msg=\" + msg + 12);\n }\n\n public static void a13(String msg) {\n System.out.println(\"msg=\" + msg + 13);\n }\n\n public static void a14(String msg) {\n System.out.println(\"msg=\" + msg + 14);\n }\n\n public static void a15(String msg) {\n System.out.println(\"msg=\" + msg + 15);\n }\n\n public static void a16(String msg) {\n System.out.println(\"msg=\" + msg + 16);\n }\n\n public static void a17(String msg) {\n System.out.println(\"msg=\" + msg + 17);\n }\n\n public static void a18(String msg) {\n System.out.println(\"msg=\" + msg + 18);\n }\n\n public static void a19(String msg) {\n System.out.println(\"msg=\" + msg + 19);\n }\n\n public static void a20(String msg) {\n System.out.println(\"msg=\" + msg + 20);\n }\n\n public static void a21(String msg) {\n System.out.println(\"msg=\" + msg + 21);\n }\n\n public static void a22(String msg) {\n System.out.println(\"msg=\" + msg + 22);\n }\n\n public static void a23(String msg) {\n System.out.println(\"msg=\" + msg + 23);\n }\n\n public static void a24(String msg) {\n System.out.println(\"msg=\" + msg + 24);\n }\n\n public static void a25(String msg) {\n System.out.println(\"msg=\" + msg + 25);\n }\n\n public static void a26(String msg) {\n System.out.println(\"msg=\" + msg + 26);\n }\n\n public static void a27(String msg) {\n System.out.println(\"msg=\" + msg + 27);\n }\n\n public static void a28(String msg) {\n System.out.println(\"msg=\" + msg + 28);\n }\n\n public static void a29(String msg) {\n System.out.println(\"msg=\" + msg + 29);\n }\n\n public static void a30(String msg) {\n System.out.println(\"msg=\" + msg + 30);\n }\n\n public static void a31(String msg) {\n System.out.println(\"msg=\" + msg + 31);\n }\n\n pub", "post_mask_code": "lic static void a32(String msg) {\n System.out.println(\"msg=\" + msg + 32);\n }\n\n public static void a33(String msg) {\n System.out.println(\"msg=\" + msg + 33);\n }\n\n public static void a34(String msg) {\n System.out.println(\"msg=\" + msg + 34);\n }\n\n public static void a35(String msg) {\n System.out.println(\"msg=\" + msg + 35);\n }\n\n public static void a36(String msg) {\n System.out.println(\"msg=\" + msg + 36);\n }\n\n public static void a37(String msg) {\n System.out.println(\"msg=\" + msg + 37);\n }\n\n public static void a38(String msg) {\n System.out.println(\"msg=\" + msg + 38);\n }\n\n public static void a39(String msg) {\n System.out.println(\"msg=\" + msg + 39);\n }\n\n public static void a40(String msg) {\n System.out.println(\"msg=\" + msg + 40);\n }\n\n public static void a41(String msg) {\n System.out.println(\"msg=\" + msg + 41);\n }\n\n public static void a42(String msg) {\n System.out.println(\"msg=\" + msg + 42);\n }\n\n public static void a43(String msg) {\n System.out.println(\"msg=\" + msg + 43);\n }\n\n public static void a44(String msg) {\n System.out.println(\"msg=\" + msg + 44);\n }\n\n public static void a45(String msg) {\n System.out.println(\"msg=\" + msg + 45);\n }\n\n public static void a46(String msg) {\n System.out.println(\"msg=\" + msg + 46);\n }\n\n public static void a47(String msg) {\n System.out.println(\"msg=\" + msg + 47);\n }\n\n public static void a48(String msg) {\n System.out.println(\"msg=\" + msg + 48);\n }\n\n public static void a49(String msg) {\n System.out.println(\"msg=\" + msg + 49);\n }\n\n public static void a50(String msg) {\n System.out.println(\"msg=\" + msg + 50);\n }\n\n public static void a51(String msg) {\n System.out.println(\"msg=\" + msg + 51);\n }\n\n public static void a52(String msg) {\n System.out.println(\"msg=\" + msg + 52);\n }\n\n public static void a53(String msg) {\n System.out.println(\"msg=\" + msg + 53);\n }\n\n public static void a54(String msg) {\n System.out.println(\"msg=\" + msg + 54);\n }\n\n public static void a55(String msg) {\n System.out.println(\"msg=\" + msg + 55);\n }\n\n public static void a56(String msg) {\n System.out.println(\"msg=\" + msg + 56);\n }\n\n public static void a57(String msg) {\n System.out.println(\"msg=\" + msg + 57);\n }\n\n public static void a58(String msg) {\n System.out.println(\"msg=\" + msg + 58);\n }\n\n public static void a59(String msg) {\n System.out.println(\"msg=\" + msg + 59);\n }\n\n public static void a60(String msg) {\n System.out.println(\"msg=\" + msg + 60);\n }\n\n public static void a61(String msg) {\n System.out.println(\"msg=\" + msg + 61);\n }\n\n public static void a62(String msg) {\n System.out.println(\"msg=\" + msg + 62);\n }\n\n public static void a63(String msg) {\n System.out.println(\"msg=\" + msg + 63);\n }\n\n public static void a64(String msg) {\n System.out.println(\"msg=\" + msg + 64);\n }\n\n public static void a65(String msg) {\n System.out.println(\"msg=\" + msg + 65);\n }\n\n public static void a66(String msg) {\n System.out.println(\"msg=\" + msg + 66);\n }\n\n public static void a67(String msg) {\n System.out.println(\"msg=\" + msg + 67);\n }\n\n public static void a68(String msg) {\n System.out.println(\"msg=\" + msg + 68);\n }\n\n public static void a69(String msg) {\n System.out.println(\"msg=\" + msg + 69);\n }\n\n public static void a70(String msg) {\n System.out.println(\"msg=\" + msg + 70);\n }\n\n public static void a71(String msg) {\n System.out.println(\"msg=\" + msg + 71);\n }\n\n public static void a72(String msg) {\n System.out.println(\"msg=\" + msg + 72);\n }\n\n public static void a73(String msg) {\n System.out.println(\"msg=\" + msg + 73);\n }\n\n public static void a74(String msg) {\n System.out.println(\"msg=\" + msg + 74);\n }\n\n public static void a75(String msg) {\n System.out.println(\"msg=\" + msg + 75);\n }\n\n public static void a76(String msg) {\n System.out.println(\"msg=\" + msg + 76);\n }\n\n public static void a77(String msg) {\n System.out.println(\"msg=\" + msg + 77);\n }\n\n public static void a78(String msg) {\n System.out.println(\"msg=\" + msg + 78);\n }\n\n public static void a79(String msg) {\n System.out.println(\"msg=\" + msg + 79);\n }\n\n public static void a80(String msg) {\n System.out.println(\"msg=\" + msg + 80);\n }\n\n public static void a81(String msg) {\n System.out.println(\"msg=\" + msg + 81);\n }\n\n public static void a82(String msg) {\n System.out.println(\"msg=\" + msg + 82);\n }\n\n public static void a83(String msg) {\n System.out.println(\"msg=\" + msg + 83);\n }\n\n public static void a84(String msg) {\n System.out.println(\"msg=\" + msg + 84);\n }\n\n public static void a85(String msg) {\n System.out.println(\"msg=\" + msg + 85);\n }\n\n public static void a86(String msg) {\n System.out.println(\"msg=\" + msg + 86);\n }\n\n public static void a87(String msg) {\n System.out.println(\"msg=\" + msg + 87);\n }\n\n public static void a88(String msg) {\n System.out.println(\"msg=\" + msg + 88);\n }\n\n public static void a89(String msg) {\n System.out.println(\"msg=\" + msg + 89);\n }\n\n public static void a90(String msg) {\n System.out.println(\"msg=\" + msg + 90);\n }\n\n public static void a91(String msg) {\n System.out.println(\"msg=\" + msg + 91);\n }\n\n public static void a92(String msg) {\n System.out.println(\"msg=\" + msg + 92);\n }\n\n public static void a93(String msg) {\n System.out.println(\"msg=\" + msg + 93);\n }\n\n public static void a94(String msg) {\n System.out.println(\"msg=\" + msg + 94);\n }\n\n public static void a95(String msg) {\n System.out.println(\"msg=\" + msg + 95);\n }\n\n public static void a96(String msg) {\n System.out.println(\"msg=\" + msg + 96);\n }\n\n public static void a97(String msg) {\n System.out.println(\"msg=\" + msg + 97);\n }\n\n public static void a98(String msg) {\n System.out.println(\"msg=\" + msg + 98);\n }\n\n public static void a99(String msg) {\n System.out.println(\"msg=\" + msg + 99);\n }\n}\n"} {"task_id": "Java_302", "language": "Java", "task_type": "method_signature", "source_file": "java/github/MangoAutomation/ma-core-public/Core/src/com/serotonin/json/util/ParsePositionTracker.java", "mask_start_position": 775, "mask_end_position": 802, "canonical_solution": "public void update(char c) ", "pre_mask_code": "/*\n \t@author Matthew Lohbihler\n */\npackage com.serotonin.json.util;\n\n/**\n * @author Matthew Lohbihler\n */\npublic class ParsePositionTracker {\n\n private int line = 1;\n\n private int column = 1;\n\n private int elementLine;\n\n private int elementColumn;\n\n private int characterCount;\n\n private int markedLine;\n\n private int markedColumn;\n\n private int markedCharacterCount;\n\n public void mark() {\n markedLine = line;\n markedColumn = column;\n markedCharacterCount = characterCount;\n }\n\n public void reset() {\n line = markedLine;\n column = markedColumn;\n characterCount = markedCharacterCount;\n }\n\n public void setElementStart() {\n elementLine = line;\n elementColumn = column;\n }\n\n ", "post_mask_code": "{\n if (c == 0xA) {\n // Line feed\n line++;\n column = 1;\n } else\n column++;\n characterCount++;\n }\n\n public int getLine() {\n return line;\n }\n\n public int getColumn() {\n return column;\n }\n\n public int getElementLine() {\n return elementLine;\n }\n\n public int getElementColumn() {\n return elementColumn;\n }\n\n public int getCharacterCount() {\n return characterCount;\n }\n}\n"} {"task_id": "Java_303", "language": "Java", "task_type": "method_body", "source_file": "java/github/MangoAutomation/ma-core-public/Core/src/com/serotonin/json/util/ParsePositionTracker.java", "mask_start_position": 1113, "mask_end_position": 1148, "canonical_solution": "{\n return elementLine;\n }", "pre_mask_code": "/*\n \t@author Matthew Lohbihler\n */\npackage com.serotonin.json.util;\n\n/**\n * @author Matthew Lohbihler\n */\npublic class ParsePositionTracker {\n\n private int line = 1;\n\n private int column = 1;\n\n private int elementLine;\n\n private int elementColumn;\n\n private int characterCount;\n\n private int markedLine;\n\n private int markedColumn;\n\n private int markedCharacterCount;\n\n public void mark() {\n markedLine = line;\n markedColumn = column;\n markedCharacterCount = characterCount;\n }\n\n public void reset() {\n line = markedLine;\n column = markedColumn;\n characterCount = markedCharacterCount;\n }\n\n public void setElementStart() {\n elementLine = line;\n elementColumn = column;\n }\n\n public void update(char c) {\n if (c == 0xA) {\n // Line feed\n line++;\n column = 1;\n } else\n column++;\n characterCount++;\n }\n\n public int getLine() {\n return line;\n }\n\n public int getColumn() {\n return column;\n }\n\n public int getElementLine() ", "post_mask_code": "\n\n public int getElementColumn() {\n return elementColumn;\n }\n\n public int getCharacterCount() {\n return characterCount;\n }\n}\n"} {"task_id": "Java_304", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/MangoAutomation/ma-core-public/Core/src/com/serotonin/json/util/ParsePositionTracker.java", "mask_start_position": 803, "mask_end_position": 933, "canonical_solution": "\n if (c == 0xA) {\n // Line feed\n line++;\n column = 1;\n } else\n column++;", "pre_mask_code": "/*\n \t@author Matthew Lohbihler\n */\npackage com.serotonin.json.util;\n\n/**\n * @author Matthew Lohbihler\n */\npublic class ParsePositionTracker {\n\n private int line = 1;\n\n private int column = 1;\n\n private int elementLine;\n\n private int elementColumn;\n\n private int characterCount;\n\n private int markedLine;\n\n private int markedColumn;\n\n private int markedCharacterCount;\n\n public void mark() {\n markedLine = line;\n markedColumn = column;\n markedCharacterCount = characterCount;\n }\n\n public void reset() {\n line = markedLine;\n column = markedColumn;\n characterCount = markedCharacterCount;\n }\n\n public void setElementStart() {\n elementLine = line;\n elementColumn = column;\n }\n\n public void update(char c) {", "post_mask_code": "\n characterCount++;\n }\n\n public int getLine() {\n return line;\n }\n\n public int getColumn() {\n return column;\n }\n\n public int getElementLine() {\n return elementLine;\n }\n\n public int getElementColumn() {\n return elementColumn;\n }\n\n public int getCharacterCount() {\n return characterCount;\n }\n}\n"} {"task_id": "Java_305", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/MangoAutomation/ma-core-public/Core/src/com/serotonin/json/util/ParsePositionTracker.java", "mask_start_position": 942, "mask_end_position": 959, "canonical_solution": "characterCount++;", "pre_mask_code": "/*\n \t@author Matthew Lohbihler\n */\npackage com.serotonin.json.util;\n\n/**\n * @author Matthew Lohbihler\n */\npublic class ParsePositionTracker {\n\n private int line = 1;\n\n private int column = 1;\n\n private int elementLine;\n\n private int elementColumn;\n\n private int characterCount;\n\n private int markedLine;\n\n private int markedColumn;\n\n private int markedCharacterCount;\n\n public void mark() {\n markedLine = line;\n markedColumn = column;\n markedCharacterCount = characterCount;\n }\n\n public void reset() {\n line = markedLine;\n column = markedColumn;\n characterCount = markedCharacterCount;\n }\n\n public void setElementStart() {\n elementLine = line;\n elementColumn = column;\n }\n\n public void update(char c) {\n if (c == 0xA) {\n // Line feed\n line++;\n column = 1;\n } else\n column++;\n ", "post_mask_code": "\n }\n\n public int getLine() {\n return line;\n }\n\n public int getColumn() {\n return column;\n }\n\n public int getElementLine() {\n return elementLine;\n }\n\n public int getElementColumn() {\n return elementColumn;\n }\n\n public int getCharacterCount() {\n return characterCount;\n }\n}\n"} {"task_id": "Java_306", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/MangoAutomation/ma-core-public/Core/src/com/serotonin/json/util/ParsePositionTracker.java", "mask_start_position": 964, "mask_end_position": 965, "canonical_solution": "}", "pre_mask_code": "/*\n \t@author Matthew Lohbihler\n */\npackage com.serotonin.json.util;\n\n/**\n * @author Matthew Lohbihler\n */\npublic class ParsePositionTracker {\n\n private int line = 1;\n\n private int column = 1;\n\n private int elementLine;\n\n private int elementColumn;\n\n private int characterCount;\n\n private int markedLine;\n\n private int markedColumn;\n\n private int markedCharacterCount;\n\n public void mark() {\n markedLine = line;\n markedColumn = column;\n markedCharacterCount = characterCount;\n }\n\n public void reset() {\n line = markedLine;\n column = markedColumn;\n characterCount = markedCharacterCount;\n }\n\n public void setElementStart() {\n elementLine = line;\n elementColumn = column;\n }\n\n public void update(char c) {\n if (c == 0xA) {\n // Line feed\n line++;\n column = 1;\n } else\n column++;\n characterCount++;\n ", "post_mask_code": "\n\n public int getLine() {\n return line;\n }\n\n public int getColumn() {\n return column;\n }\n\n public int getElementLine() {\n return elementLine;\n }\n\n public int getElementColumn() {\n return elementColumn;\n }\n\n public int getCharacterCount() {\n return characterCount;\n }\n}\n"} {"task_id": "Java_307", "language": "Java", "task_type": "single_line", "source_file": "java/github/MangoAutomation/ma-core-public/Core/src/com/serotonin/json/util/ParsePositionTracker.java", "mask_start_position": 456, "mask_end_position": 475, "canonical_solution": "kedColumn = column;", "pre_mask_code": "/*\n \t@author Matthew Lohbihler\n */\npackage com.serotonin.json.util;\n\n/**\n * @author Matthew Lohbihler\n */\npublic class ParsePositionTracker {\n\n private int line = 1;\n\n private int column = 1;\n\n private int elementLine;\n\n private int elementColumn;\n\n private int characterCount;\n\n private int markedLine;\n\n private int markedColumn;\n\n private int markedCharacterCount;\n\n public void mark() {\n markedLine = line;\n mar", "post_mask_code": "\n markedCharacterCount = characterCount;\n }\n\n public void reset() {\n line = markedLine;\n column = markedColumn;\n characterCount = markedCharacterCount;\n }\n\n public void setElementStart() {\n elementLine = line;\n elementColumn = column;\n }\n\n public void update(char c) {\n if (c == 0xA) {\n // Line feed\n line++;\n column = 1;\n } else\n column++;\n characterCount++;\n }\n\n public int getLine() {\n return line;\n }\n\n public int getColumn() {\n return column;\n }\n\n public int getElementLine() {\n return elementLine;\n }\n\n public int getElementColumn() {\n return elementColumn;\n }\n\n public int getCharacterCount() {\n return characterCount;\n }\n}\n"} {"task_id": "Java_308", "language": "Java", "task_type": "if_statement", "source_file": "java/github/MangoAutomation/ma-core-public/Core/src/com/serotonin/json/util/ParsePositionTracker.java", "mask_start_position": 812, "mask_end_position": 933, "canonical_solution": "if (c == 0xA) {\n // Line feed\n line++;\n column = 1;\n } else\n column++;", "pre_mask_code": "/*\n \t@author Matthew Lohbihler\n */\npackage com.serotonin.json.util;\n\n/**\n * @author Matthew Lohbihler\n */\npublic class ParsePositionTracker {\n\n private int line = 1;\n\n private int column = 1;\n\n private int elementLine;\n\n private int elementColumn;\n\n private int characterCount;\n\n private int markedLine;\n\n private int markedColumn;\n\n private int markedCharacterCount;\n\n public void mark() {\n markedLine = line;\n markedColumn = column;\n markedCharacterCount = characterCount;\n }\n\n public void reset() {\n line = markedLine;\n column = markedColumn;\n characterCount = markedCharacterCount;\n }\n\n public void setElementStart() {\n elementLine = line;\n elementColumn = column;\n }\n\n public void update(char c) {\n ", "post_mask_code": "\n characterCount++;\n }\n\n public int getLine() {\n return line;\n }\n\n public int getColumn() {\n return column;\n }\n\n public int getElementLine() {\n return elementLine;\n }\n\n public int getElementColumn() {\n return elementColumn;\n }\n\n public int getCharacterCount() {\n return characterCount;\n }\n}\n"} {"task_id": "Java_309", "language": "Java", "task_type": "empty", "source_file": "java/github/MangoAutomation/ma-core-public/Core/src/com/serotonin/json/util/ParsePositionTracker.java", "mask_start_position": 827, "mask_end_position": 827, "canonical_solution": "", "pre_mask_code": "/*\n \t@author Matthew Lohbihler\n */\npackage com.serotonin.json.util;\n\n/**\n * @author Matthew Lohbihler\n */\npublic class ParsePositionTracker {\n\n private int line = 1;\n\n private int column = 1;\n\n private int elementLine;\n\n private int elementColumn;\n\n private int characterCount;\n\n private int markedLine;\n\n private int markedColumn;\n\n private int markedCharacterCount;\n\n public void mark() {\n markedLine = line;\n markedColumn = column;\n markedCharacterCount = characterCount;\n }\n\n public void reset() {\n line = markedLine;\n column = markedColumn;\n characterCount = markedCharacterCount;\n }\n\n public void setElementStart() {\n elementLine = line;\n elementColumn = column;\n }\n\n public void update(char c) {\n if (c == 0xA) {", "post_mask_code": "\n // Line feed\n line++;\n column = 1;\n } else\n column++;\n characterCount++;\n }\n\n public int getLine() {\n return line;\n }\n\n public int getColumn() {\n return column;\n }\n\n public int getElementLine() {\n return elementLine;\n }\n\n public int getElementColumn() {\n return elementColumn;\n }\n\n public int getCharacterCount() {\n return characterCount;\n }\n}\n"} {"task_id": "Java_310", "language": "Java", "task_type": "method_signature", "source_file": "java/github/sonatype/nexus-public/components/nexus-common/src/main/java/org/sonatype/nexus/common/property/SystemPropertiesHelper.java", "mask_start_position": 2188, "mask_end_position": 2264, "canonical_solution": "public static String getString(final String key, final String defaultValue) ", "pre_mask_code": "/*\n * Sonatype Nexus (TM) Open Source Version\n * All rights reserved. Includes the third-party code listed at http://example.com.\n *\n *\n * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. \"Sonatype\" and \"Sonatype Nexus\" are trademarks\n * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the\n * Eclipse Foundation. All other trademarks are the property of their respective owners.\n */\npackage org.sonatype.nexus.common.property;\n\nimport org.sonatype.goodies.common.Time;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Helper to retrieve a system property typed value.\n */\npublic class SystemPropertiesHelper {\n\n private static final Logger log = LoggerFactory.getLogger(SystemPropertiesHelper.class);\n\n private SystemPropertiesHelper() {\n // empty\n }\n\n public static int getInteger(final String key, final int defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Integer.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid integer '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static long getLong(final String key, final long defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Long.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid long '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static boolean getBoolean(final String key, final boolean defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n return Boolean.valueOf(value);\n }\n\n ", "post_mask_code": "{\n return System.getProperty(key, defaultValue);\n }\n\n public static Time getTime(final String key, final Time defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Time.parse(value);\n } catch (RuntimeException e) {\n // NOSONAR\n log.warn(\"Invalid time '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n}\n"} {"task_id": "Java_311", "language": "Java", "task_type": "method_body", "source_file": "java/github/sonatype/nexus-public/components/nexus-common/src/main/java/org/sonatype/nexus/common/property/SystemPropertiesHelper.java", "mask_start_position": 2264, "mask_end_position": 2325, "canonical_solution": "{\n return System.getProperty(key, defaultValue);\n }", "pre_mask_code": "/*\n * Sonatype Nexus (TM) Open Source Version\n * All rights reserved. Includes the third-party code listed at http://example.com.\n *\n *\n * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. \"Sonatype\" and \"Sonatype Nexus\" are trademarks\n * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the\n * Eclipse Foundation. All other trademarks are the property of their respective owners.\n */\npackage org.sonatype.nexus.common.property;\n\nimport org.sonatype.goodies.common.Time;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Helper to retrieve a system property typed value.\n */\npublic class SystemPropertiesHelper {\n\n private static final Logger log = LoggerFactory.getLogger(SystemPropertiesHelper.class);\n\n private SystemPropertiesHelper() {\n // empty\n }\n\n public static int getInteger(final String key, final int defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Integer.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid integer '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static long getLong(final String key, final long defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Long.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid long '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static boolean getBoolean(final String key, final boolean defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n return Boolean.valueOf(value);\n }\n\n public static String getString(final String key, final String defaultValue) ", "post_mask_code": "\n\n public static Time getTime(final String key, final Time defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Time.parse(value);\n } catch (RuntimeException e) {\n // NOSONAR\n log.warn(\"Invalid time '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n}\n"} {"task_id": "Java_312", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/sonatype/nexus-public/components/nexus-common/src/main/java/org/sonatype/nexus/common/property/SystemPropertiesHelper.java", "mask_start_position": 2402, "mask_end_position": 2456, "canonical_solution": "\n final String value = System.getProperty(key);", "pre_mask_code": "/*\n * Sonatype Nexus (TM) Open Source Version\n * All rights reserved. Includes the third-party code listed at http://example.com.\n *\n *\n * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. \"Sonatype\" and \"Sonatype Nexus\" are trademarks\n * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the\n * Eclipse Foundation. All other trademarks are the property of their respective owners.\n */\npackage org.sonatype.nexus.common.property;\n\nimport org.sonatype.goodies.common.Time;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Helper to retrieve a system property typed value.\n */\npublic class SystemPropertiesHelper {\n\n private static final Logger log = LoggerFactory.getLogger(SystemPropertiesHelper.class);\n\n private SystemPropertiesHelper() {\n // empty\n }\n\n public static int getInteger(final String key, final int defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Integer.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid integer '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static long getLong(final String key, final long defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Long.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid long '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static boolean getBoolean(final String key, final boolean defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n return Boolean.valueOf(value);\n }\n\n public static String getString(final String key, final String defaultValue) {\n return System.getProperty(key, defaultValue);\n }\n\n public static Time getTime(final String key, final Time defaultValue) {", "post_mask_code": "\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Time.parse(value);\n } catch (RuntimeException e) {\n // NOSONAR\n log.warn(\"Invalid time '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n}\n"} {"task_id": "Java_313", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/sonatype/nexus-public/components/nexus-common/src/main/java/org/sonatype/nexus/common/property/SystemPropertiesHelper.java", "mask_start_position": 2465, "mask_end_position": 2558, "canonical_solution": "if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }", "pre_mask_code": "/*\n * Sonatype Nexus (TM) Open Source Version\n * All rights reserved. Includes the third-party code listed at http://example.com.\n *\n *\n * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. \"Sonatype\" and \"Sonatype Nexus\" are trademarks\n * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the\n * Eclipse Foundation. All other trademarks are the property of their respective owners.\n */\npackage org.sonatype.nexus.common.property;\n\nimport org.sonatype.goodies.common.Time;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Helper to retrieve a system property typed value.\n */\npublic class SystemPropertiesHelper {\n\n private static final Logger log = LoggerFactory.getLogger(SystemPropertiesHelper.class);\n\n private SystemPropertiesHelper() {\n // empty\n }\n\n public static int getInteger(final String key, final int defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Integer.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid integer '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static long getLong(final String key, final long defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Long.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid long '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static boolean getBoolean(final String key, final boolean defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n return Boolean.valueOf(value);\n }\n\n public static String getString(final String key, final String defaultValue) {\n return System.getProperty(key, defaultValue);\n }\n\n public static Time getTime(final String key, final Time defaultValue) {\n final String value = System.getProperty(key);\n ", "post_mask_code": "\n try {\n return Time.parse(value);\n } catch (RuntimeException e) {\n // NOSONAR\n log.warn(\"Invalid time '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n}\n"} {"task_id": "Java_314", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/sonatype/nexus-public/components/nexus-common/src/main/java/org/sonatype/nexus/common/property/SystemPropertiesHelper.java", "mask_start_position": 2567, "mask_end_position": 2828, "canonical_solution": "try {\n return Time.parse(value);\n } catch (RuntimeException e) {\n // NOSONAR\n log.warn(\"Invalid time '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }", "pre_mask_code": "/*\n * Sonatype Nexus (TM) Open Source Version\n * All rights reserved. Includes the third-party code listed at http://example.com.\n *\n *\n * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. \"Sonatype\" and \"Sonatype Nexus\" are trademarks\n * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the\n * Eclipse Foundation. All other trademarks are the property of their respective owners.\n */\npackage org.sonatype.nexus.common.property;\n\nimport org.sonatype.goodies.common.Time;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Helper to retrieve a system property typed value.\n */\npublic class SystemPropertiesHelper {\n\n private static final Logger log = LoggerFactory.getLogger(SystemPropertiesHelper.class);\n\n private SystemPropertiesHelper() {\n // empty\n }\n\n public static int getInteger(final String key, final int defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Integer.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid integer '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static long getLong(final String key, final long defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Long.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid long '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static boolean getBoolean(final String key, final boolean defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n return Boolean.valueOf(value);\n }\n\n public static String getString(final String key, final String defaultValue) {\n return System.getProperty(key, defaultValue);\n }\n\n public static Time getTime(final String key, final Time defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_315", "language": "Java", "task_type": "single_line", "source_file": "java/github/sonatype/nexus-public/components/nexus-common/src/main/java/org/sonatype/nexus/common/property/SystemPropertiesHelper.java", "mask_start_position": 1991, "mask_end_position": 2035, "canonical_solution": "inal String value = System.getProperty(key);", "pre_mask_code": "/*\n * Sonatype Nexus (TM) Open Source Version\n * All rights reserved. Includes the third-party code listed at http://example.com.\n *\n *\n * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. \"Sonatype\" and \"Sonatype Nexus\" are trademarks\n * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the\n * Eclipse Foundation. All other trademarks are the property of their respective owners.\n */\npackage org.sonatype.nexus.common.property;\n\nimport org.sonatype.goodies.common.Time;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Helper to retrieve a system property typed value.\n */\npublic class SystemPropertiesHelper {\n\n private static final Logger log = LoggerFactory.getLogger(SystemPropertiesHelper.class);\n\n private SystemPropertiesHelper() {\n // empty\n }\n\n public static int getInteger(final String key, final int defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Integer.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid integer '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static long getLong(final String key, final long defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Long.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid long '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static boolean getBoolean(final String key, final boolean defaultValue) {\n f", "post_mask_code": "\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n return Boolean.valueOf(value);\n }\n\n public static String getString(final String key, final String defaultValue) {\n return System.getProperty(key, defaultValue);\n }\n\n public static Time getTime(final String key, final Time defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Time.parse(value);\n } catch (RuntimeException e) {\n // NOSONAR\n log.warn(\"Invalid time '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n}\n"} {"task_id": "Java_316", "language": "Java", "task_type": "if_statement", "source_file": "java/github/sonatype/nexus-public/components/nexus-common/src/main/java/org/sonatype/nexus/common/property/SystemPropertiesHelper.java", "mask_start_position": 1009, "mask_end_position": 1102, "canonical_solution": "if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }", "pre_mask_code": "/*\n * Sonatype Nexus (TM) Open Source Version\n * All rights reserved. Includes the third-party code listed at http://example.com.\n *\n *\n * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. \"Sonatype\" and \"Sonatype Nexus\" are trademarks\n * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the\n * Eclipse Foundation. All other trademarks are the property of their respective owners.\n */\npackage org.sonatype.nexus.common.property;\n\nimport org.sonatype.goodies.common.Time;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Helper to retrieve a system property typed value.\n */\npublic class SystemPropertiesHelper {\n\n private static final Logger log = LoggerFactory.getLogger(SystemPropertiesHelper.class);\n\n private SystemPropertiesHelper() {\n // empty\n }\n\n public static int getInteger(final String key, final int defaultValue) {\n final String value = System.getProperty(key);\n ", "post_mask_code": "\n try {\n return Integer.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid integer '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static long getLong(final String key, final long defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Long.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid long '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static boolean getBoolean(final String key, final boolean defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n return Boolean.valueOf(value);\n }\n\n public static String getString(final String key, final String defaultValue) {\n return System.getProperty(key, defaultValue);\n }\n\n public static Time getTime(final String key, final Time defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Time.parse(value);\n } catch (RuntimeException e) {\n // NOSONAR\n log.warn(\"Invalid time '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n}\n"} {"task_id": "Java_317", "language": "Java", "task_type": "try_statement", "source_file": "java/github/sonatype/nexus-public/components/nexus-common/src/main/java/org/sonatype/nexus/common/property/SystemPropertiesHelper.java", "mask_start_position": 2567, "mask_end_position": 2822, "canonical_solution": "try {\n return Time.parse(value);\n } catch (RuntimeException e) {\n // NOSONAR\n log.warn(\"Invalid time '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }", "pre_mask_code": "/*\n * Sonatype Nexus (TM) Open Source Version\n * All rights reserved. Includes the third-party code listed at http://example.com.\n *\n *\n * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. \"Sonatype\" and \"Sonatype Nexus\" are trademarks\n * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the\n * Eclipse Foundation. All other trademarks are the property of their respective owners.\n */\npackage org.sonatype.nexus.common.property;\n\nimport org.sonatype.goodies.common.Time;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Helper to retrieve a system property typed value.\n */\npublic class SystemPropertiesHelper {\n\n private static final Logger log = LoggerFactory.getLogger(SystemPropertiesHelper.class);\n\n private SystemPropertiesHelper() {\n // empty\n }\n\n public static int getInteger(final String key, final int defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Integer.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid integer '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static long getLong(final String key, final long defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Long.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid long '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static boolean getBoolean(final String key, final boolean defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n return Boolean.valueOf(value);\n }\n\n public static String getString(final String key, final String defaultValue) {\n return System.getProperty(key, defaultValue);\n }\n\n public static Time getTime(final String key, final Time defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_318", "language": "Java", "task_type": "empty", "source_file": "java/github/sonatype/nexus-public/components/nexus-common/src/main/java/org/sonatype/nexus/common/property/SystemPropertiesHelper.java", "mask_start_position": 2812, "mask_end_position": 2812, "canonical_solution": "", "pre_mask_code": "/*\n * Sonatype Nexus (TM) Open Source Version\n * All rights reserved. Includes the third-party code listed at http://example.com.\n *\n *\n * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. \"Sonatype\" and \"Sonatype Nexus\" are trademarks\n * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the\n * Eclipse Foundation. All other trademarks are the property of their respective owners.\n */\npackage org.sonatype.nexus.common.property;\n\nimport org.sonatype.goodies.common.Time;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Helper to retrieve a system property typed value.\n */\npublic class SystemPropertiesHelper {\n\n private static final Logger log = LoggerFactory.getLogger(SystemPropertiesHelper.class);\n\n private SystemPropertiesHelper() {\n // empty\n }\n\n public static int getInteger(final String key, final int defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Integer.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid integer '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static long getLong(final String key, final long defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Long.valueOf(value);\n } catch (NumberFormatException e) {\n // NOSONAR\n log.warn(\"Invalid long '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;\n }\n }\n\n public static boolean getBoolean(final String key, final boolean defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n return Boolean.valueOf(value);\n }\n\n public static String getString(final String key, final String defaultValue) {\n return System.getProperty(key, defaultValue);\n }\n\n public static Time getTime(final String key, final Time defaultValue) {\n final String value = System.getProperty(key);\n if (value == null || value.trim().length() == 0) {\n return defaultValue;\n }\n try {\n return Time.parse(value);\n } catch (RuntimeException e) {\n // NOSONAR\n log.warn(\"Invalid time '{}' for property '{}'. Defaulting to '{}'\", value, key, defaultValue);\n return defaultValue;", "post_mask_code": "\n }\n }\n}\n"} {"task_id": "Java_319", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Unidata/awips2/cave/com.raytheon.uf.viz.npp.nucaps/src/com/raytheon/uf/viz/npp/nucaps/xml/NucapsConfig.java", "mask_start_position": 1021, "mask_end_position": 1056, "canonical_solution": "public String getPassedColorName() ", "pre_mask_code": "package com.raytheon.uf.viz.npp.nucaps.xml;\n\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * NUCAPS Configuration: QC color model: 0: pass, 1,17: partially passed, 9,25:\n * totally failed, others.\n *\n *

\n *\n * SOFTWARE HISTORY\n *\n * Date         Ticket#    Engineer    Description\n * ------------ ---------- ----------- --------------------------\n * Jul 25, 2017 19924       wkwock     Initial creation\n *\n * 
\n *\n * @author wkwock\n */\n@XmlRootElement(name = \"nucapsConfig\")\n@XmlAccessorType(XmlAccessType.NONE)\npublic class NucapsConfig {\n\n @XmlElement(name = \"passed\")\n private String passedColorName;\n\n @XmlElement(name = \"partiallyPassed\")\n private String partiallyPassedColorName;\n\n @XmlElement(name = \"totallyFailed\")\n private String totallyFailedColorName;\n\n @XmlElement(name = \"default\")\n private String defaultColorName;\n\n ", "post_mask_code": "{\n return passedColorName;\n }\n\n public void setPassedColorName(String passedColorName) {\n this.passedColorName = passedColorName;\n }\n\n public String getPartiallyPassedColorName() {\n return partiallyPassedColorName;\n }\n\n public void setPartiallyPassedColorName(String partiallyPassedColorName) {\n this.partiallyPassedColorName = partiallyPassedColorName;\n }\n\n public String getTotallyFailedColorName() {\n return totallyFailedColorName;\n }\n\n public void setTotallyFailedColorName(String totallyFailedColorName) {\n this.totallyFailedColorName = totallyFailedColorName;\n }\n\n public String getDefaultColorName() {\n return defaultColorName;\n }\n\n public void setDefaultColorName(String defaultColorName) {\n this.defaultColorName = defaultColorName;\n }\n}\n"} {"task_id": "Java_320", "language": "Java", "task_type": "method_body", "source_file": "java/github/Unidata/awips2/cave/com.raytheon.uf.viz.npp.nucaps/src/com/raytheon/uf/viz/npp/nucaps/xml/NucapsConfig.java", "mask_start_position": 1844, "mask_end_position": 1901, "canonical_solution": "{\n this.defaultColorName = defaultColorName;\n }", "pre_mask_code": "package com.raytheon.uf.viz.npp.nucaps.xml;\n\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * NUCAPS Configuration: QC color model: 0: pass, 1,17: partially passed, 9,25:\n * totally failed, others.\n *\n *
\n *\n * SOFTWARE HISTORY\n *\n * Date         Ticket#    Engineer    Description\n * ------------ ---------- ----------- --------------------------\n * Jul 25, 2017 19924       wkwock     Initial creation\n *\n * 
\n *\n * @author wkwock\n */\n@XmlRootElement(name = \"nucapsConfig\")\n@XmlAccessorType(XmlAccessType.NONE)\npublic class NucapsConfig {\n\n @XmlElement(name = \"passed\")\n private String passedColorName;\n\n @XmlElement(name = \"partiallyPassed\")\n private String partiallyPassedColorName;\n\n @XmlElement(name = \"totallyFailed\")\n private String totallyFailedColorName;\n\n @XmlElement(name = \"default\")\n private String defaultColorName;\n\n public String getPassedColorName() {\n return passedColorName;\n }\n\n public void setPassedColorName(String passedColorName) {\n this.passedColorName = passedColorName;\n }\n\n public String getPartiallyPassedColorName() {\n return partiallyPassedColorName;\n }\n\n public void setPartiallyPassedColorName(String partiallyPassedColorName) {\n this.partiallyPassedColorName = partiallyPassedColorName;\n }\n\n public String getTotallyFailedColorName() {\n return totallyFailedColorName;\n }\n\n public void setTotallyFailedColorName(String totallyFailedColorName) {\n this.totallyFailedColorName = totallyFailedColorName;\n }\n\n public String getDefaultColorName() {\n return defaultColorName;\n }\n\n public void setDefaultColorName(String defaultColorName) ", "post_mask_code": "\n}\n"} {"task_id": "Java_321", "language": "Java", "task_type": "single_line", "source_file": "java/github/Unidata/awips2/cave/com.raytheon.uf.viz.npp.nucaps/src/com/raytheon/uf/viz/npp/nucaps/xml/NucapsConfig.java", "mask_start_position": 1526, "mask_end_position": 1549, "canonical_solution": "totallyFailedColorName;", "pre_mask_code": "package com.raytheon.uf.viz.npp.nucaps.xml;\n\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * NUCAPS Configuration: QC color model: 0: pass, 1,17: partially passed, 9,25:\n * totally failed, others.\n *\n *
\n *\n * SOFTWARE HISTORY\n *\n * Date         Ticket#    Engineer    Description\n * ------------ ---------- ----------- --------------------------\n * Jul 25, 2017 19924       wkwock     Initial creation\n *\n * 
\n *\n * @author wkwock\n */\n@XmlRootElement(name = \"nucapsConfig\")\n@XmlAccessorType(XmlAccessType.NONE)\npublic class NucapsConfig {\n\n @XmlElement(name = \"passed\")\n private String passedColorName;\n\n @XmlElement(name = \"partiallyPassed\")\n private String partiallyPassedColorName;\n\n @XmlElement(name = \"totallyFailed\")\n private String totallyFailedColorName;\n\n @XmlElement(name = \"default\")\n private String defaultColorName;\n\n public String getPassedColorName() {\n return passedColorName;\n }\n\n public void setPassedColorName(String passedColorName) {\n this.passedColorName = passedColorName;\n }\n\n public String getPartiallyPassedColorName() {\n return partiallyPassedColorName;\n }\n\n public void setPartiallyPassedColorName(String partiallyPassedColorName) {\n this.partiallyPassedColorName = partiallyPassedColorName;\n }\n\n public String getTotallyFailedColorName() {\n return ", "post_mask_code": "\n }\n\n public void setTotallyFailedColorName(String totallyFailedColorName) {\n this.totallyFailedColorName = totallyFailedColorName;\n }\n\n public String getDefaultColorName() {\n return defaultColorName;\n }\n\n public void setDefaultColorName(String defaultColorName) {\n this.defaultColorName = defaultColorName;\n }\n}\n"} {"task_id": "Java_322", "language": "Java", "task_type": "empty", "source_file": "java/github/Unidata/awips2/cave/com.raytheon.uf.viz.npp.nucaps/src/com/raytheon/uf/viz/npp/nucaps/xml/NucapsConfig.java", "mask_start_position": 1627, "mask_end_position": 1627, "canonical_solution": "", "pre_mask_code": "package com.raytheon.uf.viz.npp.nucaps.xml;\n\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * NUCAPS Configuration: QC color model: 0: pass, 1,17: partially passed, 9,25:\n * totally failed, others.\n *\n *
\n *\n * SOFTWARE HISTORY\n *\n * Date         Ticket#    Engineer    Description\n * ------------ ---------- ----------- --------------------------\n * Jul 25, 2017 19924       wkwock     Initial creation\n *\n * 
\n *\n * @author wkwock\n */\n@XmlRootElement(name = \"nucapsConfig\")\n@XmlAccessorType(XmlAccessType.NONE)\npublic class NucapsConfig {\n\n @XmlElement(name = \"passed\")\n private String passedColorName;\n\n @XmlElement(name = \"partiallyPassed\")\n private String partiallyPassedColorName;\n\n @XmlElement(name = \"totallyFailed\")\n private String totallyFailedColorName;\n\n @XmlElement(name = \"default\")\n private String defaultColorName;\n\n public String getPassedColorName() {\n return passedColorName;\n }\n\n public void setPassedColorName(String passedColorName) {\n this.passedColorName = passedColorName;\n }\n\n public String getPartiallyPassedColorName() {\n return partiallyPassedColorName;\n }\n\n public void setPartiallyPassedColorName(String partiallyPassedColorName) {\n this.partiallyPassedColorName = partiallyPassedColorName;\n }\n\n public String getTotallyFailedColorName() {\n return totallyFailedColorName;\n }\n\n public void setTotallyFailedColorName(String totallyFailedColorNam", "post_mask_code": "e) {\n this.totallyFailedColorName = totallyFailedColorName;\n }\n\n public String getDefaultColorName() {\n return defaultColorName;\n }\n\n public void setDefaultColorName(String defaultColorName) {\n this.defaultColorName = defaultColorName;\n }\n}\n"} {"task_id": "Java_323", "language": "Java", "task_type": "empty", "source_file": "java/github/stephenh/tessell/user/src/main/java/org/tessell/gwt/user/client/ui/IsPopupPanel.java", "mask_start_position": 639, "mask_end_position": 639, "canonical_solution": "", "pre_mask_code": "package org.tessell.gwt.user.client.ui;\n\nimport org.tessell.gwt.dom.client.IsElement;\nimport com.google.gwt.event.logical.shared.HasCloseHandlers;\nimport com.google.gwt.user.client.ui.HasAnimation;\nimport com.google.gwt.user.client.ui.PopupPanel;\nimport com.google.gwt.user.client.ui.PopupPanel.PositionCallback;\n\npublic interface IsPopupPanel extends IsSimplePanel, HasAnimation, HasCloseHandlers {\n\n void setPopupPosition(int left, int top);\n\n void setPopupPositionAndShow(PositionCallback callback);\n\n void center();\n\n void show();\n\n void hide();\n\n void setGlassEnabled(boolean enabled);\n\n void setGlass", "post_mask_code": "StyleName(String styleName);\n\n boolean isShowing();\n\n void addAutoHidePartner(IsElement element);\n\n boolean isAutoHideEnabled();\n\n void setAutoHideEnabled(boolean autoHide);\n\n boolean isAutoHideOnHistoryEventsEnabled();\n\n void setAutoHideOnHistoryEventsEnabled(boolean enabled);\n\n boolean isModal();\n\n void setModal(boolean modal);\n}\n"} {"task_id": "Java_324", "language": "Java", "task_type": "method_signature", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/AbstractJPAProviderIntegration.java", "mask_start_position": 4886, "mask_end_position": 5045, "canonical_solution": "@FFDCIgnore(PrivilegedActionException.class)\n private static Class loadClass(final ClassLoader cl, final String className) throws ClassNotFoundException ", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.jpa;\n\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_RESOURCE_BUNDLE_NAME;\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_TRACE_GROUP;\nimport java.lang.reflect.Proxy;\nimport java.security.AccessController;\nimport java.security.PrivilegedActionException;\nimport java.security.PrivilegedExceptionAction;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentSkipListSet;\nimport javax.persistence.spi.PersistenceUnitInfo;\nimport com.ibm.websphere.ras.Tr;\nimport com.ibm.websphere.ras.TraceComponent;\nimport com.ibm.ws.container.service.app.deploy.ModuleInfo;\nimport com.ibm.ws.ffdc.annotation.FFDCIgnore;\nimport com.ibm.ws.jpa.hibernate.LibertyJtaPlatform;\n\n/**\n * Common JPAProviderIntegration implementation that provides general integration required for known\n * JPA providers.\n */\npublic abstract class AbstractJPAProviderIntegration implements JPAProviderIntegration {\n\n private static final TraceComponent tc = Tr.register(AbstractJPAProviderIntegration.class, JPA_TRACE_GROUP, JPA_RESOURCE_BUNDLE_NAME);\n\n // Known JPA provider implementation classes\n protected static final String PROVIDER_ECLIPSELINK = \"org.eclipse.persistence.jpa.PersistenceProvider\";\n\n protected static final String PROVIDER_HIBERNATE = \"org.hibernate.jpa.HibernatePersistenceProvider\";\n\n protected static final String PROVIDER_OPENJPA = \"org.apache.openjpa.persistence.PersistenceProviderImpl\";\n\n /**\n * As persistence providers are first used, they are added to this list so that version information is only logged once for them.\n */\n protected final ConcurrentSkipListSet providersUsed = new ConcurrentSkipListSet();\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#disablePersistenceUnitLogging(java.util.Map)\n */\n @Override\n public void disablePersistenceUnitLogging(Map integrationProperties) {\n integrationProperties.put(\"eclipselink.logging.level\", \"OFF\");\n // Since we're disabling logging, we don't want this to conflict with other normally configured PUs. Give it a random\n // session-name such that when/if another EMF is created for this PU the EclipseLink JPAInitializer cache\n // value of PersistenceUnitProperties.SESSION_NAME\n integrationProperties.// value of PersistenceUnitProperties.SESSION_NAME\n put(// value of PersistenceUnitProperties.SESSION_NAME\n \"eclipselink.session-name\", \"disabled-logging-pu\" + UUID.randomUUID().toString());\n }\n\n /**\n * Log version information about the specified persistence provider, if it can be determined.\n *\n * @param providerName fully qualified class name of JPA persistence provider\n * @param loader class loader with access to the JPA provider classes\n */\n @FFDCIgnore(Exception.class)\n private void logProviderInfo(String providerName, ClassLoader loader) {\n try {\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n Class Version = loadClass(loader, \"org.eclipse.persistence.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(Version.newInstance());\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"EclipseLink\", version);\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n Class Version = loadClass(loader, \"org.hibernate.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(null);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"Hibernate\", version);\n } else if (PROVIDER_OPENJPA.equals(providerName)) {\n // OpenJPAVersion.appendOpenJPABanner(sb): OpenJPA #.#.#\\n version id: openjpa-#.#.#-r# \\n Apache svn revision: #\n StringBuilder version = new StringBuilder();\n Class OpenJPAVersion = loadClass(loader, \"org.apache.openjpa.conf.OpenJPAVersion\");\n OpenJPAVersion.getMethod(\"appendOpenJPABanner\", StringBuilder.class).invoke(OpenJPAVersion.newInstance(), version);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"OpenJPA\", version);\n } else {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n }\n } catch (Exception x) {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"unable to determine provider info\", x);\n }\n }\n\n ", "post_mask_code": "{\n if (System.getSecurityManager() == null)\n return cl.loadClass(className);\n else\n try {\n return AccessController.doPrivileged(new PrivilegedExceptionAction>() {\n\n @Override\n public Class run() throws ClassNotFoundException {\n return cl.loadClass(className);\n }\n });\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof ClassNotFoundException)\n throw (ClassNotFoundException) e.getCause();\n else\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void moduleStarting(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStarted(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopping(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopped(ModuleInfo moduleInfo) {\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#supportsEntityManagerPooling()\n */\n @Override\n public boolean supportsEntityManagerPooling() {\n return false;\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#addIntegrationProperties(java.util.Properties)\n */\n @FFDCIgnore(ClassNotFoundException.class)\n @Override\n public void updatePersistenceProviderIntegrationProperties(PersistenceUnitInfo puInfo, java.util.Map props) {\n String providerName = puInfo.getPersistenceProviderClassName();\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n props.put(\"eclipselink.target-server\", \"WebSphere_Liberty\");\n if (puInfo instanceof com.ibm.ws.jpa.management.JPAPUnitInfo) {\n props.put(\"eclipselink.application-id\", ((com.ibm.ws.jpa.management.JPAPUnitInfo) puInfo).getApplName());\n }\n Properties properties = puInfo.getProperties();\n /*\n * Section 4.8.5 of the JPA Specification:\n * If SUM, AVG, MAX, or MIN is used, and there are no values\n * to which the aggregate function can be applied, the result of\n * the aggregate function is NULL.\n *\n * Set this property to so that EclipseLink does not return null by default\n *\n * JPA 3.0: Do not force this override with JPA 3.0 and later.\n */\n if (!properties.containsKey(\"eclipselink.allow-null-max-min\") && JPAAccessor.getJPAComponent().getJPAVersion().lesserThan(JPAVersion.JPA30)) {\n props.put(\"eclipselink.allow-null-max-min\", \"false\");\n }\n /*\n * EclipseLink Bug 567891: Case expressions that should return boolean instead\n * return integer values. The JPA spec is too vague to change this, so we set this\n * property to be safe for customers.\n *\n * Set this property to `false` so that EclipseLink will return the same integer\n * value it has always returned for CASE expressions and not change behavior\n *\n * NOTE: This property is applicable for JPA 21 & JPA 22. JPAVersion > JPA22 has changed\n * behavior by default\n */\n if (!properties.containsKey(\"eclipselink.sql.allow-convert-result-to-boolean\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA22)) {\n props.put(\"eclipselink.sql.allow-convert-result-to-boolean\", \"false\");\n }\n // The property is named differently for EclipseLink 2.6\n if (!properties.containsKey(\"eclipselink.allow-result-type-conversion\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA21)) {\n props.put(\"eclipselink.allow-result-type-conversion\", \"false\");\n }\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n // Hibernate had vastly outdated built-in knowledge of WebSphere API, until version 5.2.13+ and 5.3+.\n // If the version of Hibernate has the Liberty JtaPlatform, use it\n // otherwise, tell Hibernate to use a proxy implementation of JtaPlatform that we will provide based on the WAS transaction manager\n ClassLoader loader = puInfo.getClassLoader();\n if (isWebSphereLibertyJtaPlatformAvailable(loader)) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Detected WebSphereLibertyJtaPlatform, not applying dynamic proxy JtaPlatform.\");\n } else {\n try {\n Class JtaPlatform = loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform\");\n Object libertyJtaPlatform = Proxy.newProxyInstance(loader, new Class[] { JtaPlatform }, new LibertyJtaPlatform());\n props.put(\"hibernate.transaction.jta.platform\", libertyJtaPlatform);\n } catch (ClassNotFoundException x) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Unable to provide JtaPlatform for Liberty TransactionManager to Hibernate\", x);\n }\n }\n }\n // Log third party provider name and version info once per provider\n if (providersUsed.add(providerName))\n logProviderInfo(providerName, puInfo.getClassLoader());\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#modifyPersistenceUnitProperties(java.lang.String, java.util.Properties)\n */\n @Override\n public void updatePersistenceUnitProperties(String providerClassName, Properties props) {\n }\n\n /**\n * As of Hibernate 5.2.13+ and 5.3+ built-in knowledge of Liberty's transaction integration was delivered as:\n * org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\n * If this class is available, we do not need to set our dynamic proxy instance.\n */\n @FFDCIgnore(ClassNotFoundException.class)\n private boolean isWebSphereLibertyJtaPlatformAvailable(ClassLoader loader) {\n try {\n loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\");\n return true;\n } catch (ClassNotFoundException notFound) {\n return false;\n }\n }\n}\n"} {"task_id": "Java_325", "language": "Java", "task_type": "method_body", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/AbstractJPAProviderIntegration.java", "mask_start_position": 10788, "mask_end_position": 10795, "canonical_solution": "{\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.jpa;\n\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_RESOURCE_BUNDLE_NAME;\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_TRACE_GROUP;\nimport java.lang.reflect.Proxy;\nimport java.security.AccessController;\nimport java.security.PrivilegedActionException;\nimport java.security.PrivilegedExceptionAction;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentSkipListSet;\nimport javax.persistence.spi.PersistenceUnitInfo;\nimport com.ibm.websphere.ras.Tr;\nimport com.ibm.websphere.ras.TraceComponent;\nimport com.ibm.ws.container.service.app.deploy.ModuleInfo;\nimport com.ibm.ws.ffdc.annotation.FFDCIgnore;\nimport com.ibm.ws.jpa.hibernate.LibertyJtaPlatform;\n\n/**\n * Common JPAProviderIntegration implementation that provides general integration required for known\n * JPA providers.\n */\npublic abstract class AbstractJPAProviderIntegration implements JPAProviderIntegration {\n\n private static final TraceComponent tc = Tr.register(AbstractJPAProviderIntegration.class, JPA_TRACE_GROUP, JPA_RESOURCE_BUNDLE_NAME);\n\n // Known JPA provider implementation classes\n protected static final String PROVIDER_ECLIPSELINK = \"org.eclipse.persistence.jpa.PersistenceProvider\";\n\n protected static final String PROVIDER_HIBERNATE = \"org.hibernate.jpa.HibernatePersistenceProvider\";\n\n protected static final String PROVIDER_OPENJPA = \"org.apache.openjpa.persistence.PersistenceProviderImpl\";\n\n /**\n * As persistence providers are first used, they are added to this list so that version information is only logged once for them.\n */\n protected final ConcurrentSkipListSet providersUsed = new ConcurrentSkipListSet();\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#disablePersistenceUnitLogging(java.util.Map)\n */\n @Override\n public void disablePersistenceUnitLogging(Map integrationProperties) {\n integrationProperties.put(\"eclipselink.logging.level\", \"OFF\");\n // Since we're disabling logging, we don't want this to conflict with other normally configured PUs. Give it a random\n // session-name such that when/if another EMF is created for this PU the EclipseLink JPAInitializer cache\n // value of PersistenceUnitProperties.SESSION_NAME\n integrationProperties.// value of PersistenceUnitProperties.SESSION_NAME\n put(// value of PersistenceUnitProperties.SESSION_NAME\n \"eclipselink.session-name\", \"disabled-logging-pu\" + UUID.randomUUID().toString());\n }\n\n /**\n * Log version information about the specified persistence provider, if it can be determined.\n *\n * @param providerName fully qualified class name of JPA persistence provider\n * @param loader class loader with access to the JPA provider classes\n */\n @FFDCIgnore(Exception.class)\n private void logProviderInfo(String providerName, ClassLoader loader) {\n try {\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n Class Version = loadClass(loader, \"org.eclipse.persistence.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(Version.newInstance());\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"EclipseLink\", version);\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n Class Version = loadClass(loader, \"org.hibernate.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(null);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"Hibernate\", version);\n } else if (PROVIDER_OPENJPA.equals(providerName)) {\n // OpenJPAVersion.appendOpenJPABanner(sb): OpenJPA #.#.#\\n version id: openjpa-#.#.#-r# \\n Apache svn revision: #\n StringBuilder version = new StringBuilder();\n Class OpenJPAVersion = loadClass(loader, \"org.apache.openjpa.conf.OpenJPAVersion\");\n OpenJPAVersion.getMethod(\"appendOpenJPABanner\", StringBuilder.class).invoke(OpenJPAVersion.newInstance(), version);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"OpenJPA\", version);\n } else {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n }\n } catch (Exception x) {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"unable to determine provider info\", x);\n }\n }\n\n @FFDCIgnore(PrivilegedActionException.class)\n private static Class loadClass(final ClassLoader cl, final String className) throws ClassNotFoundException {\n if (System.getSecurityManager() == null)\n return cl.loadClass(className);\n else\n try {\n return AccessController.doPrivileged(new PrivilegedExceptionAction>() {\n\n @Override\n public Class run() throws ClassNotFoundException {\n return cl.loadClass(className);\n }\n });\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof ClassNotFoundException)\n throw (ClassNotFoundException) e.getCause();\n else\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void moduleStarting(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStarted(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopping(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopped(ModuleInfo moduleInfo) {\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#supportsEntityManagerPooling()\n */\n @Override\n public boolean supportsEntityManagerPooling() {\n return false;\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#addIntegrationProperties(java.util.Properties)\n */\n @FFDCIgnore(ClassNotFoundException.class)\n @Override\n public void updatePersistenceProviderIntegrationProperties(PersistenceUnitInfo puInfo, java.util.Map props) {\n String providerName = puInfo.getPersistenceProviderClassName();\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n props.put(\"eclipselink.target-server\", \"WebSphere_Liberty\");\n if (puInfo instanceof com.ibm.ws.jpa.management.JPAPUnitInfo) {\n props.put(\"eclipselink.application-id\", ((com.ibm.ws.jpa.management.JPAPUnitInfo) puInfo).getApplName());\n }\n Properties properties = puInfo.getProperties();\n /*\n * Section 4.8.5 of the JPA Specification:\n * If SUM, AVG, MAX, or MIN is used, and there are no values\n * to which the aggregate function can be applied, the result of\n * the aggregate function is NULL.\n *\n * Set this property to so that EclipseLink does not return null by default\n *\n * JPA 3.0: Do not force this override with JPA 3.0 and later.\n */\n if (!properties.containsKey(\"eclipselink.allow-null-max-min\") && JPAAccessor.getJPAComponent().getJPAVersion().lesserThan(JPAVersion.JPA30)) {\n props.put(\"eclipselink.allow-null-max-min\", \"false\");\n }\n /*\n * EclipseLink Bug 567891: Case expressions that should return boolean instead\n * return integer values. The JPA spec is too vague to change this, so we set this\n * property to be safe for customers.\n *\n * Set this property to `false` so that EclipseLink will return the same integer\n * value it has always returned for CASE expressions and not change behavior\n *\n * NOTE: This property is applicable for JPA 21 & JPA 22. JPAVersion > JPA22 has changed\n * behavior by default\n */\n if (!properties.containsKey(\"eclipselink.sql.allow-convert-result-to-boolean\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA22)) {\n props.put(\"eclipselink.sql.allow-convert-result-to-boolean\", \"false\");\n }\n // The property is named differently for EclipseLink 2.6\n if (!properties.containsKey(\"eclipselink.allow-result-type-conversion\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA21)) {\n props.put(\"eclipselink.allow-result-type-conversion\", \"false\");\n }\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n // Hibernate had vastly outdated built-in knowledge of WebSphere API, until version 5.2.13+ and 5.3+.\n // If the version of Hibernate has the Liberty JtaPlatform, use it\n // otherwise, tell Hibernate to use a proxy implementation of JtaPlatform that we will provide based on the WAS transaction manager\n ClassLoader loader = puInfo.getClassLoader();\n if (isWebSphereLibertyJtaPlatformAvailable(loader)) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Detected WebSphereLibertyJtaPlatform, not applying dynamic proxy JtaPlatform.\");\n } else {\n try {\n Class JtaPlatform = loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform\");\n Object libertyJtaPlatform = Proxy.newProxyInstance(loader, new Class[] { JtaPlatform }, new LibertyJtaPlatform());\n props.put(\"hibernate.transaction.jta.platform\", libertyJtaPlatform);\n } catch (ClassNotFoundException x) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Unable to provide JtaPlatform for Liberty TransactionManager to Hibernate\", x);\n }\n }\n }\n // Log third party provider name and version info once per provider\n if (providersUsed.add(providerName))\n logProviderInfo(providerName, puInfo.getClassLoader());\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#modifyPersistenceUnitProperties(java.lang.String, java.util.Properties)\n */\n @Override\n public void updatePersistenceUnitProperties(String providerClassName, Properties props) ", "post_mask_code": "\n\n /**\n * As of Hibernate 5.2.13+ and 5.3+ built-in knowledge of Liberty's transaction integration was delivered as:\n * org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\n * If this class is available, we do not need to set our dynamic proxy instance.\n */\n @FFDCIgnore(ClassNotFoundException.class)\n private boolean isWebSphereLibertyJtaPlatformAvailable(ClassLoader loader) {\n try {\n loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\");\n return true;\n } catch (ClassNotFoundException notFound) {\n return false;\n }\n }\n}\n"} {"task_id": "Java_326", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/AbstractJPAProviderIntegration.java", "mask_start_position": 3205, "mask_end_position": 3205, "canonical_solution": "", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.jpa;\n\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_RESOURCE_BUNDLE_NAME;\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_TRACE_GROUP;\nimport java.lang.reflect.Proxy;\nimport java.security.AccessController;\nimport java.security.PrivilegedActionException;\nimport java.security.PrivilegedExceptionAction;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentSkipListSet;\nimport javax.persistence.spi.PersistenceUnitInfo;\nimport com.ibm.websphere.ras.Tr;\nimport com.ibm.websphere.ras.TraceComponent;\nimport com.ibm.ws.container.service.app.deploy.ModuleInfo;\nimport com.ibm.ws.ffdc.annotation.FFDCIgnore;\nimport com.ibm.ws.jpa.hibernate.LibertyJtaPlatform;\n\n/**\n * Common JPAProviderIntegration implementation that provides general integration required for known\n * JPA providers.\n */\npublic abstract class AbstractJPAProviderIntegration implements JPAProviderIntegration {\n\n private static final TraceComponent tc = Tr.register(AbstractJPAProviderIntegration.class, JPA_TRACE_GROUP, JPA_RESOURCE_BUNDLE_NAME);\n\n // Known JPA provider implementation classes\n protected static final String PROVIDER_ECLIPSELINK = \"org.eclipse.persistence.jpa.PersistenceProvider\";\n\n protected static final String PROVIDER_HIBERNATE = \"org.hibernate.jpa.HibernatePersistenceProvider\";\n\n protected static final String PROVIDER_OPENJPA = \"org.apache.openjpa.persistence.PersistenceProviderImpl\";\n\n /**\n * As persistence providers are first used, they are added to this list so that version information is only logged once for them.\n */\n protected final ConcurrentSkipListSet providersUsed = new ConcurrentSkipListSet();\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#disablePersistenceUnitLogging(java.util.Map)\n */\n @Override\n public void disablePersistenceUnitLogging(Map integrationProperties) {\n integrationProperties.put(\"eclipselink.logging.level\", \"OFF\");\n // Since we're disabling logging, we don't want this to conflict with other normally configured PUs. Give it a random\n // session-name such that when/if another EMF is created for this PU the EclipseLink JPAInitializer cache\n // value of PersistenceUnitProperties.SESSION_NAME\n integrationProperties.// value of PersistenceUnitProperties.SESSION_NAME\n put(// value of PersistenceUnitProperties.SESSION_NAME\n \"eclipselink.session-name\", \"disabled-logging-pu\" + UUID.randomUUID().toString());\n }\n\n /**\n * Log version information about the specified persistence provider, if it can be determined.\n *\n * @param providerName fully qualified class name of JPA persistence provider\n * @param loader class loader with access to the JPA provider classes\n */\n @FFDCIgnore(Exception.class)\n private void logProviderInfo(String providerName, ClassLoader loader) {", "post_mask_code": "\n try {\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n Class Version = loadClass(loader, \"org.eclipse.persistence.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(Version.newInstance());\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"EclipseLink\", version);\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n Class Version = loadClass(loader, \"org.hibernate.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(null);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"Hibernate\", version);\n } else if (PROVIDER_OPENJPA.equals(providerName)) {\n // OpenJPAVersion.appendOpenJPABanner(sb): OpenJPA #.#.#\\n version id: openjpa-#.#.#-r# \\n Apache svn revision: #\n StringBuilder version = new StringBuilder();\n Class OpenJPAVersion = loadClass(loader, \"org.apache.openjpa.conf.OpenJPAVersion\");\n OpenJPAVersion.getMethod(\"appendOpenJPABanner\", StringBuilder.class).invoke(OpenJPAVersion.newInstance(), version);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"OpenJPA\", version);\n } else {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n }\n } catch (Exception x) {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"unable to determine provider info\", x);\n }\n }\n\n @FFDCIgnore(PrivilegedActionException.class)\n private static Class loadClass(final ClassLoader cl, final String className) throws ClassNotFoundException {\n if (System.getSecurityManager() == null)\n return cl.loadClass(className);\n else\n try {\n return AccessController.doPrivileged(new PrivilegedExceptionAction>() {\n\n @Override\n public Class run() throws ClassNotFoundException {\n return cl.loadClass(className);\n }\n });\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof ClassNotFoundException)\n throw (ClassNotFoundException) e.getCause();\n else\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void moduleStarting(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStarted(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopping(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopped(ModuleInfo moduleInfo) {\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#supportsEntityManagerPooling()\n */\n @Override\n public boolean supportsEntityManagerPooling() {\n return false;\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#addIntegrationProperties(java.util.Properties)\n */\n @FFDCIgnore(ClassNotFoundException.class)\n @Override\n public void updatePersistenceProviderIntegrationProperties(PersistenceUnitInfo puInfo, java.util.Map props) {\n String providerName = puInfo.getPersistenceProviderClassName();\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n props.put(\"eclipselink.target-server\", \"WebSphere_Liberty\");\n if (puInfo instanceof com.ibm.ws.jpa.management.JPAPUnitInfo) {\n props.put(\"eclipselink.application-id\", ((com.ibm.ws.jpa.management.JPAPUnitInfo) puInfo).getApplName());\n }\n Properties properties = puInfo.getProperties();\n /*\n * Section 4.8.5 of the JPA Specification:\n * If SUM, AVG, MAX, or MIN is used, and there are no values\n * to which the aggregate function can be applied, the result of\n * the aggregate function is NULL.\n *\n * Set this property to so that EclipseLink does not return null by default\n *\n * JPA 3.0: Do not force this override with JPA 3.0 and later.\n */\n if (!properties.containsKey(\"eclipselink.allow-null-max-min\") && JPAAccessor.getJPAComponent().getJPAVersion().lesserThan(JPAVersion.JPA30)) {\n props.put(\"eclipselink.allow-null-max-min\", \"false\");\n }\n /*\n * EclipseLink Bug 567891: Case expressions that should return boolean instead\n * return integer values. The JPA spec is too vague to change this, so we set this\n * property to be safe for customers.\n *\n * Set this property to `false` so that EclipseLink will return the same integer\n * value it has always returned for CASE expressions and not change behavior\n *\n * NOTE: This property is applicable for JPA 21 & JPA 22. JPAVersion > JPA22 has changed\n * behavior by default\n */\n if (!properties.containsKey(\"eclipselink.sql.allow-convert-result-to-boolean\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA22)) {\n props.put(\"eclipselink.sql.allow-convert-result-to-boolean\", \"false\");\n }\n // The property is named differently for EclipseLink 2.6\n if (!properties.containsKey(\"eclipselink.allow-result-type-conversion\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA21)) {\n props.put(\"eclipselink.allow-result-type-conversion\", \"false\");\n }\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n // Hibernate had vastly outdated built-in knowledge of WebSphere API, until version 5.2.13+ and 5.3+.\n // If the version of Hibernate has the Liberty JtaPlatform, use it\n // otherwise, tell Hibernate to use a proxy implementation of JtaPlatform that we will provide based on the WAS transaction manager\n ClassLoader loader = puInfo.getClassLoader();\n if (isWebSphereLibertyJtaPlatformAvailable(loader)) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Detected WebSphereLibertyJtaPlatform, not applying dynamic proxy JtaPlatform.\");\n } else {\n try {\n Class JtaPlatform = loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform\");\n Object libertyJtaPlatform = Proxy.newProxyInstance(loader, new Class[] { JtaPlatform }, new LibertyJtaPlatform());\n props.put(\"hibernate.transaction.jta.platform\", libertyJtaPlatform);\n } catch (ClassNotFoundException x) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Unable to provide JtaPlatform for Liberty TransactionManager to Hibernate\", x);\n }\n }\n }\n // Log third party provider name and version info once per provider\n if (providersUsed.add(providerName))\n logProviderInfo(providerName, puInfo.getClassLoader());\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#modifyPersistenceUnitProperties(java.lang.String, java.util.Properties)\n */\n @Override\n public void updatePersistenceUnitProperties(String providerClassName, Properties props) {\n }\n\n /**\n * As of Hibernate 5.2.13+ and 5.3+ built-in knowledge of Liberty's transaction integration was delivered as:\n * org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\n * If this class is available, we do not need to set our dynamic proxy instance.\n */\n @FFDCIgnore(ClassNotFoundException.class)\n private boolean isWebSphereLibertyJtaPlatformAvailable(ClassLoader loader) {\n try {\n loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\");\n return true;\n } catch (ClassNotFoundException notFound) {\n return false;\n }\n }\n}\n"} {"task_id": "Java_327", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/AbstractJPAProviderIntegration.java", "mask_start_position": 3214, "mask_end_position": 4874, "canonical_solution": "try {\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n Class Version = loadClass(loader, \"org.eclipse.persistence.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(Version.newInstance());\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"EclipseLink\", version);\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n Class Version = loadClass(loader, \"org.hibernate.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(null);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"Hibernate\", version);\n } else if (PROVIDER_OPENJPA.equals(providerName)) {\n // OpenJPAVersion.appendOpenJPABanner(sb): OpenJPA #.#.#\\n version id: openjpa-#.#.#-r# \\n Apache svn revision: #\n StringBuilder version = new StringBuilder();\n Class OpenJPAVersion = loadClass(loader, \"org.apache.openjpa.conf.OpenJPAVersion\");\n OpenJPAVersion.getMethod(\"appendOpenJPABanner\", StringBuilder.class).invoke(OpenJPAVersion.newInstance(), version);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"OpenJPA\", version);\n } else {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n }\n } catch (Exception x) {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"unable to determine provider info\", x);\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.jpa;\n\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_RESOURCE_BUNDLE_NAME;\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_TRACE_GROUP;\nimport java.lang.reflect.Proxy;\nimport java.security.AccessController;\nimport java.security.PrivilegedActionException;\nimport java.security.PrivilegedExceptionAction;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentSkipListSet;\nimport javax.persistence.spi.PersistenceUnitInfo;\nimport com.ibm.websphere.ras.Tr;\nimport com.ibm.websphere.ras.TraceComponent;\nimport com.ibm.ws.container.service.app.deploy.ModuleInfo;\nimport com.ibm.ws.ffdc.annotation.FFDCIgnore;\nimport com.ibm.ws.jpa.hibernate.LibertyJtaPlatform;\n\n/**\n * Common JPAProviderIntegration implementation that provides general integration required for known\n * JPA providers.\n */\npublic abstract class AbstractJPAProviderIntegration implements JPAProviderIntegration {\n\n private static final TraceComponent tc = Tr.register(AbstractJPAProviderIntegration.class, JPA_TRACE_GROUP, JPA_RESOURCE_BUNDLE_NAME);\n\n // Known JPA provider implementation classes\n protected static final String PROVIDER_ECLIPSELINK = \"org.eclipse.persistence.jpa.PersistenceProvider\";\n\n protected static final String PROVIDER_HIBERNATE = \"org.hibernate.jpa.HibernatePersistenceProvider\";\n\n protected static final String PROVIDER_OPENJPA = \"org.apache.openjpa.persistence.PersistenceProviderImpl\";\n\n /**\n * As persistence providers are first used, they are added to this list so that version information is only logged once for them.\n */\n protected final ConcurrentSkipListSet providersUsed = new ConcurrentSkipListSet();\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#disablePersistenceUnitLogging(java.util.Map)\n */\n @Override\n public void disablePersistenceUnitLogging(Map integrationProperties) {\n integrationProperties.put(\"eclipselink.logging.level\", \"OFF\");\n // Since we're disabling logging, we don't want this to conflict with other normally configured PUs. Give it a random\n // session-name such that when/if another EMF is created for this PU the EclipseLink JPAInitializer cache\n // value of PersistenceUnitProperties.SESSION_NAME\n integrationProperties.// value of PersistenceUnitProperties.SESSION_NAME\n put(// value of PersistenceUnitProperties.SESSION_NAME\n \"eclipselink.session-name\", \"disabled-logging-pu\" + UUID.randomUUID().toString());\n }\n\n /**\n * Log version information about the specified persistence provider, if it can be determined.\n *\n * @param providerName fully qualified class name of JPA persistence provider\n * @param loader class loader with access to the JPA provider classes\n */\n @FFDCIgnore(Exception.class)\n private void logProviderInfo(String providerName, ClassLoader loader) {\n ", "post_mask_code": "\n }\n\n @FFDCIgnore(PrivilegedActionException.class)\n private static Class loadClass(final ClassLoader cl, final String className) throws ClassNotFoundException {\n if (System.getSecurityManager() == null)\n return cl.loadClass(className);\n else\n try {\n return AccessController.doPrivileged(new PrivilegedExceptionAction>() {\n\n @Override\n public Class run() throws ClassNotFoundException {\n return cl.loadClass(className);\n }\n });\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof ClassNotFoundException)\n throw (ClassNotFoundException) e.getCause();\n else\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void moduleStarting(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStarted(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopping(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopped(ModuleInfo moduleInfo) {\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#supportsEntityManagerPooling()\n */\n @Override\n public boolean supportsEntityManagerPooling() {\n return false;\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#addIntegrationProperties(java.util.Properties)\n */\n @FFDCIgnore(ClassNotFoundException.class)\n @Override\n public void updatePersistenceProviderIntegrationProperties(PersistenceUnitInfo puInfo, java.util.Map props) {\n String providerName = puInfo.getPersistenceProviderClassName();\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n props.put(\"eclipselink.target-server\", \"WebSphere_Liberty\");\n if (puInfo instanceof com.ibm.ws.jpa.management.JPAPUnitInfo) {\n props.put(\"eclipselink.application-id\", ((com.ibm.ws.jpa.management.JPAPUnitInfo) puInfo).getApplName());\n }\n Properties properties = puInfo.getProperties();\n /*\n * Section 4.8.5 of the JPA Specification:\n * If SUM, AVG, MAX, or MIN is used, and there are no values\n * to which the aggregate function can be applied, the result of\n * the aggregate function is NULL.\n *\n * Set this property to so that EclipseLink does not return null by default\n *\n * JPA 3.0: Do not force this override with JPA 3.0 and later.\n */\n if (!properties.containsKey(\"eclipselink.allow-null-max-min\") && JPAAccessor.getJPAComponent().getJPAVersion().lesserThan(JPAVersion.JPA30)) {\n props.put(\"eclipselink.allow-null-max-min\", \"false\");\n }\n /*\n * EclipseLink Bug 567891: Case expressions that should return boolean instead\n * return integer values. The JPA spec is too vague to change this, so we set this\n * property to be safe for customers.\n *\n * Set this property to `false` so that EclipseLink will return the same integer\n * value it has always returned for CASE expressions and not change behavior\n *\n * NOTE: This property is applicable for JPA 21 & JPA 22. JPAVersion > JPA22 has changed\n * behavior by default\n */\n if (!properties.containsKey(\"eclipselink.sql.allow-convert-result-to-boolean\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA22)) {\n props.put(\"eclipselink.sql.allow-convert-result-to-boolean\", \"false\");\n }\n // The property is named differently for EclipseLink 2.6\n if (!properties.containsKey(\"eclipselink.allow-result-type-conversion\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA21)) {\n props.put(\"eclipselink.allow-result-type-conversion\", \"false\");\n }\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n // Hibernate had vastly outdated built-in knowledge of WebSphere API, until version 5.2.13+ and 5.3+.\n // If the version of Hibernate has the Liberty JtaPlatform, use it\n // otherwise, tell Hibernate to use a proxy implementation of JtaPlatform that we will provide based on the WAS transaction manager\n ClassLoader loader = puInfo.getClassLoader();\n if (isWebSphereLibertyJtaPlatformAvailable(loader)) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Detected WebSphereLibertyJtaPlatform, not applying dynamic proxy JtaPlatform.\");\n } else {\n try {\n Class JtaPlatform = loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform\");\n Object libertyJtaPlatform = Proxy.newProxyInstance(loader, new Class[] { JtaPlatform }, new LibertyJtaPlatform());\n props.put(\"hibernate.transaction.jta.platform\", libertyJtaPlatform);\n } catch (ClassNotFoundException x) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Unable to provide JtaPlatform for Liberty TransactionManager to Hibernate\", x);\n }\n }\n }\n // Log third party provider name and version info once per provider\n if (providersUsed.add(providerName))\n logProviderInfo(providerName, puInfo.getClassLoader());\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#modifyPersistenceUnitProperties(java.lang.String, java.util.Properties)\n */\n @Override\n public void updatePersistenceUnitProperties(String providerClassName, Properties props) {\n }\n\n /**\n * As of Hibernate 5.2.13+ and 5.3+ built-in knowledge of Liberty's transaction integration was delivered as:\n * org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\n * If this class is available, we do not need to set our dynamic proxy instance.\n */\n @FFDCIgnore(ClassNotFoundException.class)\n private boolean isWebSphereLibertyJtaPlatformAvailable(ClassLoader loader) {\n try {\n loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\");\n return true;\n } catch (ClassNotFoundException notFound) {\n return false;\n }\n }\n}\n"} {"task_id": "Java_328", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/AbstractJPAProviderIntegration.java", "mask_start_position": 4879, "mask_end_position": 4880, "canonical_solution": "}", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.jpa;\n\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_RESOURCE_BUNDLE_NAME;\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_TRACE_GROUP;\nimport java.lang.reflect.Proxy;\nimport java.security.AccessController;\nimport java.security.PrivilegedActionException;\nimport java.security.PrivilegedExceptionAction;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentSkipListSet;\nimport javax.persistence.spi.PersistenceUnitInfo;\nimport com.ibm.websphere.ras.Tr;\nimport com.ibm.websphere.ras.TraceComponent;\nimport com.ibm.ws.container.service.app.deploy.ModuleInfo;\nimport com.ibm.ws.ffdc.annotation.FFDCIgnore;\nimport com.ibm.ws.jpa.hibernate.LibertyJtaPlatform;\n\n/**\n * Common JPAProviderIntegration implementation that provides general integration required for known\n * JPA providers.\n */\npublic abstract class AbstractJPAProviderIntegration implements JPAProviderIntegration {\n\n private static final TraceComponent tc = Tr.register(AbstractJPAProviderIntegration.class, JPA_TRACE_GROUP, JPA_RESOURCE_BUNDLE_NAME);\n\n // Known JPA provider implementation classes\n protected static final String PROVIDER_ECLIPSELINK = \"org.eclipse.persistence.jpa.PersistenceProvider\";\n\n protected static final String PROVIDER_HIBERNATE = \"org.hibernate.jpa.HibernatePersistenceProvider\";\n\n protected static final String PROVIDER_OPENJPA = \"org.apache.openjpa.persistence.PersistenceProviderImpl\";\n\n /**\n * As persistence providers are first used, they are added to this list so that version information is only logged once for them.\n */\n protected final ConcurrentSkipListSet providersUsed = new ConcurrentSkipListSet();\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#disablePersistenceUnitLogging(java.util.Map)\n */\n @Override\n public void disablePersistenceUnitLogging(Map integrationProperties) {\n integrationProperties.put(\"eclipselink.logging.level\", \"OFF\");\n // Since we're disabling logging, we don't want this to conflict with other normally configured PUs. Give it a random\n // session-name such that when/if another EMF is created for this PU the EclipseLink JPAInitializer cache\n // value of PersistenceUnitProperties.SESSION_NAME\n integrationProperties.// value of PersistenceUnitProperties.SESSION_NAME\n put(// value of PersistenceUnitProperties.SESSION_NAME\n \"eclipselink.session-name\", \"disabled-logging-pu\" + UUID.randomUUID().toString());\n }\n\n /**\n * Log version information about the specified persistence provider, if it can be determined.\n *\n * @param providerName fully qualified class name of JPA persistence provider\n * @param loader class loader with access to the JPA provider classes\n */\n @FFDCIgnore(Exception.class)\n private void logProviderInfo(String providerName, ClassLoader loader) {\n try {\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n Class Version = loadClass(loader, \"org.eclipse.persistence.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(Version.newInstance());\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"EclipseLink\", version);\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n Class Version = loadClass(loader, \"org.hibernate.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(null);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"Hibernate\", version);\n } else if (PROVIDER_OPENJPA.equals(providerName)) {\n // OpenJPAVersion.appendOpenJPABanner(sb): OpenJPA #.#.#\\n version id: openjpa-#.#.#-r# \\n Apache svn revision: #\n StringBuilder version = new StringBuilder();\n Class OpenJPAVersion = loadClass(loader, \"org.apache.openjpa.conf.OpenJPAVersion\");\n OpenJPAVersion.getMethod(\"appendOpenJPABanner\", StringBuilder.class).invoke(OpenJPAVersion.newInstance(), version);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"OpenJPA\", version);\n } else {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n }\n } catch (Exception x) {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"unable to determine provider info\", x);\n }\n ", "post_mask_code": "\n\n @FFDCIgnore(PrivilegedActionException.class)\n private static Class loadClass(final ClassLoader cl, final String className) throws ClassNotFoundException {\n if (System.getSecurityManager() == null)\n return cl.loadClass(className);\n else\n try {\n return AccessController.doPrivileged(new PrivilegedExceptionAction>() {\n\n @Override\n public Class run() throws ClassNotFoundException {\n return cl.loadClass(className);\n }\n });\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof ClassNotFoundException)\n throw (ClassNotFoundException) e.getCause();\n else\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void moduleStarting(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStarted(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopping(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopped(ModuleInfo moduleInfo) {\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#supportsEntityManagerPooling()\n */\n @Override\n public boolean supportsEntityManagerPooling() {\n return false;\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#addIntegrationProperties(java.util.Properties)\n */\n @FFDCIgnore(ClassNotFoundException.class)\n @Override\n public void updatePersistenceProviderIntegrationProperties(PersistenceUnitInfo puInfo, java.util.Map props) {\n String providerName = puInfo.getPersistenceProviderClassName();\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n props.put(\"eclipselink.target-server\", \"WebSphere_Liberty\");\n if (puInfo instanceof com.ibm.ws.jpa.management.JPAPUnitInfo) {\n props.put(\"eclipselink.application-id\", ((com.ibm.ws.jpa.management.JPAPUnitInfo) puInfo).getApplName());\n }\n Properties properties = puInfo.getProperties();\n /*\n * Section 4.8.5 of the JPA Specification:\n * If SUM, AVG, MAX, or MIN is used, and there are no values\n * to which the aggregate function can be applied, the result of\n * the aggregate function is NULL.\n *\n * Set this property to so that EclipseLink does not return null by default\n *\n * JPA 3.0: Do not force this override with JPA 3.0 and later.\n */\n if (!properties.containsKey(\"eclipselink.allow-null-max-min\") && JPAAccessor.getJPAComponent().getJPAVersion().lesserThan(JPAVersion.JPA30)) {\n props.put(\"eclipselink.allow-null-max-min\", \"false\");\n }\n /*\n * EclipseLink Bug 567891: Case expressions that should return boolean instead\n * return integer values. The JPA spec is too vague to change this, so we set this\n * property to be safe for customers.\n *\n * Set this property to `false` so that EclipseLink will return the same integer\n * value it has always returned for CASE expressions and not change behavior\n *\n * NOTE: This property is applicable for JPA 21 & JPA 22. JPAVersion > JPA22 has changed\n * behavior by default\n */\n if (!properties.containsKey(\"eclipselink.sql.allow-convert-result-to-boolean\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA22)) {\n props.put(\"eclipselink.sql.allow-convert-result-to-boolean\", \"false\");\n }\n // The property is named differently for EclipseLink 2.6\n if (!properties.containsKey(\"eclipselink.allow-result-type-conversion\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA21)) {\n props.put(\"eclipselink.allow-result-type-conversion\", \"false\");\n }\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n // Hibernate had vastly outdated built-in knowledge of WebSphere API, until version 5.2.13+ and 5.3+.\n // If the version of Hibernate has the Liberty JtaPlatform, use it\n // otherwise, tell Hibernate to use a proxy implementation of JtaPlatform that we will provide based on the WAS transaction manager\n ClassLoader loader = puInfo.getClassLoader();\n if (isWebSphereLibertyJtaPlatformAvailable(loader)) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Detected WebSphereLibertyJtaPlatform, not applying dynamic proxy JtaPlatform.\");\n } else {\n try {\n Class JtaPlatform = loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform\");\n Object libertyJtaPlatform = Proxy.newProxyInstance(loader, new Class[] { JtaPlatform }, new LibertyJtaPlatform());\n props.put(\"hibernate.transaction.jta.platform\", libertyJtaPlatform);\n } catch (ClassNotFoundException x) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Unable to provide JtaPlatform for Liberty TransactionManager to Hibernate\", x);\n }\n }\n }\n // Log third party provider name and version info once per provider\n if (providersUsed.add(providerName))\n logProviderInfo(providerName, puInfo.getClassLoader());\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#modifyPersistenceUnitProperties(java.lang.String, java.util.Properties)\n */\n @Override\n public void updatePersistenceUnitProperties(String providerClassName, Properties props) {\n }\n\n /**\n * As of Hibernate 5.2.13+ and 5.3+ built-in knowledge of Liberty's transaction integration was delivered as:\n * org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\n * If this class is available, we do not need to set our dynamic proxy instance.\n */\n @FFDCIgnore(ClassNotFoundException.class)\n private boolean isWebSphereLibertyJtaPlatformAvailable(ClassLoader loader) {\n try {\n loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\");\n return true;\n } catch (ClassNotFoundException notFound) {\n return false;\n }\n }\n}\n"} {"task_id": "Java_329", "language": "Java", "task_type": "single_line", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/AbstractJPAProviderIntegration.java", "mask_start_position": 2253, "mask_end_position": 2272, "canonical_solution": "ing.level\", \"OFF\");", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.jpa;\n\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_RESOURCE_BUNDLE_NAME;\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_TRACE_GROUP;\nimport java.lang.reflect.Proxy;\nimport java.security.AccessController;\nimport java.security.PrivilegedActionException;\nimport java.security.PrivilegedExceptionAction;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentSkipListSet;\nimport javax.persistence.spi.PersistenceUnitInfo;\nimport com.ibm.websphere.ras.Tr;\nimport com.ibm.websphere.ras.TraceComponent;\nimport com.ibm.ws.container.service.app.deploy.ModuleInfo;\nimport com.ibm.ws.ffdc.annotation.FFDCIgnore;\nimport com.ibm.ws.jpa.hibernate.LibertyJtaPlatform;\n\n/**\n * Common JPAProviderIntegration implementation that provides general integration required for known\n * JPA providers.\n */\npublic abstract class AbstractJPAProviderIntegration implements JPAProviderIntegration {\n\n private static final TraceComponent tc = Tr.register(AbstractJPAProviderIntegration.class, JPA_TRACE_GROUP, JPA_RESOURCE_BUNDLE_NAME);\n\n // Known JPA provider implementation classes\n protected static final String PROVIDER_ECLIPSELINK = \"org.eclipse.persistence.jpa.PersistenceProvider\";\n\n protected static final String PROVIDER_HIBERNATE = \"org.hibernate.jpa.HibernatePersistenceProvider\";\n\n protected static final String PROVIDER_OPENJPA = \"org.apache.openjpa.persistence.PersistenceProviderImpl\";\n\n /**\n * As persistence providers are first used, they are added to this list so that version information is only logged once for them.\n */\n protected final ConcurrentSkipListSet providersUsed = new ConcurrentSkipListSet();\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#disablePersistenceUnitLogging(java.util.Map)\n */\n @Override\n public void disablePersistenceUnitLogging(Map integrationProperties) {\n integrationProperties.put(\"eclipselink.logg", "post_mask_code": "\n // Since we're disabling logging, we don't want this to conflict with other normally configured PUs. Give it a random\n // session-name such that when/if another EMF is created for this PU the EclipseLink JPAInitializer cache\n // value of PersistenceUnitProperties.SESSION_NAME\n integrationProperties.// value of PersistenceUnitProperties.SESSION_NAME\n put(// value of PersistenceUnitProperties.SESSION_NAME\n \"eclipselink.session-name\", \"disabled-logging-pu\" + UUID.randomUUID().toString());\n }\n\n /**\n * Log version information about the specified persistence provider, if it can be determined.\n *\n * @param providerName fully qualified class name of JPA persistence provider\n * @param loader class loader with access to the JPA provider classes\n */\n @FFDCIgnore(Exception.class)\n private void logProviderInfo(String providerName, ClassLoader loader) {\n try {\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n Class Version = loadClass(loader, \"org.eclipse.persistence.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(Version.newInstance());\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"EclipseLink\", version);\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n Class Version = loadClass(loader, \"org.hibernate.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(null);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"Hibernate\", version);\n } else if (PROVIDER_OPENJPA.equals(providerName)) {\n // OpenJPAVersion.appendOpenJPABanner(sb): OpenJPA #.#.#\\n version id: openjpa-#.#.#-r# \\n Apache svn revision: #\n StringBuilder version = new StringBuilder();\n Class OpenJPAVersion = loadClass(loader, \"org.apache.openjpa.conf.OpenJPAVersion\");\n OpenJPAVersion.getMethod(\"appendOpenJPABanner\", StringBuilder.class).invoke(OpenJPAVersion.newInstance(), version);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"OpenJPA\", version);\n } else {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n }\n } catch (Exception x) {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"unable to determine provider info\", x);\n }\n }\n\n @FFDCIgnore(PrivilegedActionException.class)\n private static Class loadClass(final ClassLoader cl, final String className) throws ClassNotFoundException {\n if (System.getSecurityManager() == null)\n return cl.loadClass(className);\n else\n try {\n return AccessController.doPrivileged(new PrivilegedExceptionAction>() {\n\n @Override\n public Class run() throws ClassNotFoundException {\n return cl.loadClass(className);\n }\n });\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof ClassNotFoundException)\n throw (ClassNotFoundException) e.getCause();\n else\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void moduleStarting(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStarted(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopping(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopped(ModuleInfo moduleInfo) {\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#supportsEntityManagerPooling()\n */\n @Override\n public boolean supportsEntityManagerPooling() {\n return false;\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#addIntegrationProperties(java.util.Properties)\n */\n @FFDCIgnore(ClassNotFoundException.class)\n @Override\n public void updatePersistenceProviderIntegrationProperties(PersistenceUnitInfo puInfo, java.util.Map props) {\n String providerName = puInfo.getPersistenceProviderClassName();\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n props.put(\"eclipselink.target-server\", \"WebSphere_Liberty\");\n if (puInfo instanceof com.ibm.ws.jpa.management.JPAPUnitInfo) {\n props.put(\"eclipselink.application-id\", ((com.ibm.ws.jpa.management.JPAPUnitInfo) puInfo).getApplName());\n }\n Properties properties = puInfo.getProperties();\n /*\n * Section 4.8.5 of the JPA Specification:\n * If SUM, AVG, MAX, or MIN is used, and there are no values\n * to which the aggregate function can be applied, the result of\n * the aggregate function is NULL.\n *\n * Set this property to so that EclipseLink does not return null by default\n *\n * JPA 3.0: Do not force this override with JPA 3.0 and later.\n */\n if (!properties.containsKey(\"eclipselink.allow-null-max-min\") && JPAAccessor.getJPAComponent().getJPAVersion().lesserThan(JPAVersion.JPA30)) {\n props.put(\"eclipselink.allow-null-max-min\", \"false\");\n }\n /*\n * EclipseLink Bug 567891: Case expressions that should return boolean instead\n * return integer values. The JPA spec is too vague to change this, so we set this\n * property to be safe for customers.\n *\n * Set this property to `false` so that EclipseLink will return the same integer\n * value it has always returned for CASE expressions and not change behavior\n *\n * NOTE: This property is applicable for JPA 21 & JPA 22. JPAVersion > JPA22 has changed\n * behavior by default\n */\n if (!properties.containsKey(\"eclipselink.sql.allow-convert-result-to-boolean\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA22)) {\n props.put(\"eclipselink.sql.allow-convert-result-to-boolean\", \"false\");\n }\n // The property is named differently for EclipseLink 2.6\n if (!properties.containsKey(\"eclipselink.allow-result-type-conversion\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA21)) {\n props.put(\"eclipselink.allow-result-type-conversion\", \"false\");\n }\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n // Hibernate had vastly outdated built-in knowledge of WebSphere API, until version 5.2.13+ and 5.3+.\n // If the version of Hibernate has the Liberty JtaPlatform, use it\n // otherwise, tell Hibernate to use a proxy implementation of JtaPlatform that we will provide based on the WAS transaction manager\n ClassLoader loader = puInfo.getClassLoader();\n if (isWebSphereLibertyJtaPlatformAvailable(loader)) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Detected WebSphereLibertyJtaPlatform, not applying dynamic proxy JtaPlatform.\");\n } else {\n try {\n Class JtaPlatform = loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform\");\n Object libertyJtaPlatform = Proxy.newProxyInstance(loader, new Class[] { JtaPlatform }, new LibertyJtaPlatform());\n props.put(\"hibernate.transaction.jta.platform\", libertyJtaPlatform);\n } catch (ClassNotFoundException x) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Unable to provide JtaPlatform for Liberty TransactionManager to Hibernate\", x);\n }\n }\n }\n // Log third party provider name and version info once per provider\n if (providersUsed.add(providerName))\n logProviderInfo(providerName, puInfo.getClassLoader());\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#modifyPersistenceUnitProperties(java.lang.String, java.util.Properties)\n */\n @Override\n public void updatePersistenceUnitProperties(String providerClassName, Properties props) {\n }\n\n /**\n * As of Hibernate 5.2.13+ and 5.3+ built-in knowledge of Liberty's transaction integration was delivered as:\n * org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\n * If this class is available, we do not need to set our dynamic proxy instance.\n */\n @FFDCIgnore(ClassNotFoundException.class)\n private boolean isWebSphereLibertyJtaPlatformAvailable(ClassLoader loader) {\n try {\n loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\");\n return true;\n } catch (ClassNotFoundException notFound) {\n return false;\n }\n }\n}\n"} {"task_id": "Java_330", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/AbstractJPAProviderIntegration.java", "mask_start_position": 11106, "mask_end_position": 11478, "canonical_solution": "@FFDCIgnore(ClassNotFoundException.class)\n private boolean isWebSphereLibertyJtaPlatformAvailable(ClassLoader loader) {\n try {\n loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\");\n return true;\n } catch (ClassNotFoundException notFound) {\n return false;\n }\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.jpa;\n\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_RESOURCE_BUNDLE_NAME;\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_TRACE_GROUP;\nimport java.lang.reflect.Proxy;\nimport java.security.AccessController;\nimport java.security.PrivilegedActionException;\nimport java.security.PrivilegedExceptionAction;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentSkipListSet;\nimport javax.persistence.spi.PersistenceUnitInfo;\nimport com.ibm.websphere.ras.Tr;\nimport com.ibm.websphere.ras.TraceComponent;\nimport com.ibm.ws.container.service.app.deploy.ModuleInfo;\nimport com.ibm.ws.ffdc.annotation.FFDCIgnore;\nimport com.ibm.ws.jpa.hibernate.LibertyJtaPlatform;\n\n/**\n * Common JPAProviderIntegration implementation that provides general integration required for known\n * JPA providers.\n */\npublic abstract class AbstractJPAProviderIntegration implements JPAProviderIntegration {\n\n private static final TraceComponent tc = Tr.register(AbstractJPAProviderIntegration.class, JPA_TRACE_GROUP, JPA_RESOURCE_BUNDLE_NAME);\n\n // Known JPA provider implementation classes\n protected static final String PROVIDER_ECLIPSELINK = \"org.eclipse.persistence.jpa.PersistenceProvider\";\n\n protected static final String PROVIDER_HIBERNATE = \"org.hibernate.jpa.HibernatePersistenceProvider\";\n\n protected static final String PROVIDER_OPENJPA = \"org.apache.openjpa.persistence.PersistenceProviderImpl\";\n\n /**\n * As persistence providers are first used, they are added to this list so that version information is only logged once for them.\n */\n protected final ConcurrentSkipListSet providersUsed = new ConcurrentSkipListSet();\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#disablePersistenceUnitLogging(java.util.Map)\n */\n @Override\n public void disablePersistenceUnitLogging(Map integrationProperties) {\n integrationProperties.put(\"eclipselink.logging.level\", \"OFF\");\n // Since we're disabling logging, we don't want this to conflict with other normally configured PUs. Give it a random\n // session-name such that when/if another EMF is created for this PU the EclipseLink JPAInitializer cache\n // value of PersistenceUnitProperties.SESSION_NAME\n integrationProperties.// value of PersistenceUnitProperties.SESSION_NAME\n put(// value of PersistenceUnitProperties.SESSION_NAME\n \"eclipselink.session-name\", \"disabled-logging-pu\" + UUID.randomUUID().toString());\n }\n\n /**\n * Log version information about the specified persistence provider, if it can be determined.\n *\n * @param providerName fully qualified class name of JPA persistence provider\n * @param loader class loader with access to the JPA provider classes\n */\n @FFDCIgnore(Exception.class)\n private void logProviderInfo(String providerName, ClassLoader loader) {\n try {\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n Class Version = loadClass(loader, \"org.eclipse.persistence.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(Version.newInstance());\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"EclipseLink\", version);\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n Class Version = loadClass(loader, \"org.hibernate.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(null);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"Hibernate\", version);\n } else if (PROVIDER_OPENJPA.equals(providerName)) {\n // OpenJPAVersion.appendOpenJPABanner(sb): OpenJPA #.#.#\\n version id: openjpa-#.#.#-r# \\n Apache svn revision: #\n StringBuilder version = new StringBuilder();\n Class OpenJPAVersion = loadClass(loader, \"org.apache.openjpa.conf.OpenJPAVersion\");\n OpenJPAVersion.getMethod(\"appendOpenJPABanner\", StringBuilder.class).invoke(OpenJPAVersion.newInstance(), version);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"OpenJPA\", version);\n } else {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n }\n } catch (Exception x) {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"unable to determine provider info\", x);\n }\n }\n\n @FFDCIgnore(PrivilegedActionException.class)\n private static Class loadClass(final ClassLoader cl, final String className) throws ClassNotFoundException {\n if (System.getSecurityManager() == null)\n return cl.loadClass(className);\n else\n try {\n return AccessController.doPrivileged(new PrivilegedExceptionAction>() {\n\n @Override\n public Class run() throws ClassNotFoundException {\n return cl.loadClass(className);\n }\n });\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof ClassNotFoundException)\n throw (ClassNotFoundException) e.getCause();\n else\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void moduleStarting(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStarted(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopping(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopped(ModuleInfo moduleInfo) {\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#supportsEntityManagerPooling()\n */\n @Override\n public boolean supportsEntityManagerPooling() {\n return false;\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#addIntegrationProperties(java.util.Properties)\n */\n @FFDCIgnore(ClassNotFoundException.class)\n @Override\n public void updatePersistenceProviderIntegrationProperties(PersistenceUnitInfo puInfo, java.util.Map props) {\n String providerName = puInfo.getPersistenceProviderClassName();\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n props.put(\"eclipselink.target-server\", \"WebSphere_Liberty\");\n if (puInfo instanceof com.ibm.ws.jpa.management.JPAPUnitInfo) {\n props.put(\"eclipselink.application-id\", ((com.ibm.ws.jpa.management.JPAPUnitInfo) puInfo).getApplName());\n }\n Properties properties = puInfo.getProperties();\n /*\n * Section 4.8.5 of the JPA Specification:\n * If SUM, AVG, MAX, or MIN is used, and there are no values\n * to which the aggregate function can be applied, the result of\n * the aggregate function is NULL.\n *\n * Set this property to so that EclipseLink does not return null by default\n *\n * JPA 3.0: Do not force this override with JPA 3.0 and later.\n */\n if (!properties.containsKey(\"eclipselink.allow-null-max-min\") && JPAAccessor.getJPAComponent().getJPAVersion().lesserThan(JPAVersion.JPA30)) {\n props.put(\"eclipselink.allow-null-max-min\", \"false\");\n }\n /*\n * EclipseLink Bug 567891: Case expressions that should return boolean instead\n * return integer values. The JPA spec is too vague to change this, so we set this\n * property to be safe for customers.\n *\n * Set this property to `false` so that EclipseLink will return the same integer\n * value it has always returned for CASE expressions and not change behavior\n *\n * NOTE: This property is applicable for JPA 21 & JPA 22. JPAVersion > JPA22 has changed\n * behavior by default\n */\n if (!properties.containsKey(\"eclipselink.sql.allow-convert-result-to-boolean\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA22)) {\n props.put(\"eclipselink.sql.allow-convert-result-to-boolean\", \"false\");\n }\n // The property is named differently for EclipseLink 2.6\n if (!properties.containsKey(\"eclipselink.allow-result-type-conversion\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA21)) {\n props.put(\"eclipselink.allow-result-type-conversion\", \"false\");\n }\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n // Hibernate had vastly outdated built-in knowledge of WebSphere API, until version 5.2.13+ and 5.3+.\n // If the version of Hibernate has the Liberty JtaPlatform, use it\n // otherwise, tell Hibernate to use a proxy implementation of JtaPlatform that we will provide based on the WAS transaction manager\n ClassLoader loader = puInfo.getClassLoader();\n if (isWebSphereLibertyJtaPlatformAvailable(loader)) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Detected WebSphereLibertyJtaPlatform, not applying dynamic proxy JtaPlatform.\");\n } else {\n try {\n Class JtaPlatform = loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform\");\n Object libertyJtaPlatform = Proxy.newProxyInstance(loader, new Class[] { JtaPlatform }, new LibertyJtaPlatform());\n props.put(\"hibernate.transaction.jta.platform\", libertyJtaPlatform);\n } catch (ClassNotFoundException x) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Unable to provide JtaPlatform for Liberty TransactionManager to Hibernate\", x);\n }\n }\n }\n // Log third party provider name and version info once per provider\n if (providersUsed.add(providerName))\n logProviderInfo(providerName, puInfo.getClassLoader());\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#modifyPersistenceUnitProperties(java.lang.String, java.util.Properties)\n */\n @Override\n public void updatePersistenceUnitProperties(String providerClassName, Properties props) {\n }\n\n /**\n * As of Hibernate 5.2.13+ and 5.3+ built-in knowledge of Liberty's transaction integration was delivered as:\n * org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\n * If this class is available, we do not need to set our dynamic proxy instance.\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_331", "language": "Java", "task_type": "if_statement", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/AbstractJPAProviderIntegration.java", "mask_start_position": 10443, "mask_end_position": 10547, "canonical_solution": "if (providersUsed.add(providerName))\n logProviderInfo(providerName, puInfo.getClassLoader());", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.jpa;\n\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_RESOURCE_BUNDLE_NAME;\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_TRACE_GROUP;\nimport java.lang.reflect.Proxy;\nimport java.security.AccessController;\nimport java.security.PrivilegedActionException;\nimport java.security.PrivilegedExceptionAction;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentSkipListSet;\nimport javax.persistence.spi.PersistenceUnitInfo;\nimport com.ibm.websphere.ras.Tr;\nimport com.ibm.websphere.ras.TraceComponent;\nimport com.ibm.ws.container.service.app.deploy.ModuleInfo;\nimport com.ibm.ws.ffdc.annotation.FFDCIgnore;\nimport com.ibm.ws.jpa.hibernate.LibertyJtaPlatform;\n\n/**\n * Common JPAProviderIntegration implementation that provides general integration required for known\n * JPA providers.\n */\npublic abstract class AbstractJPAProviderIntegration implements JPAProviderIntegration {\n\n private static final TraceComponent tc = Tr.register(AbstractJPAProviderIntegration.class, JPA_TRACE_GROUP, JPA_RESOURCE_BUNDLE_NAME);\n\n // Known JPA provider implementation classes\n protected static final String PROVIDER_ECLIPSELINK = \"org.eclipse.persistence.jpa.PersistenceProvider\";\n\n protected static final String PROVIDER_HIBERNATE = \"org.hibernate.jpa.HibernatePersistenceProvider\";\n\n protected static final String PROVIDER_OPENJPA = \"org.apache.openjpa.persistence.PersistenceProviderImpl\";\n\n /**\n * As persistence providers are first used, they are added to this list so that version information is only logged once for them.\n */\n protected final ConcurrentSkipListSet providersUsed = new ConcurrentSkipListSet();\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#disablePersistenceUnitLogging(java.util.Map)\n */\n @Override\n public void disablePersistenceUnitLogging(Map integrationProperties) {\n integrationProperties.put(\"eclipselink.logging.level\", \"OFF\");\n // Since we're disabling logging, we don't want this to conflict with other normally configured PUs. Give it a random\n // session-name such that when/if another EMF is created for this PU the EclipseLink JPAInitializer cache\n // value of PersistenceUnitProperties.SESSION_NAME\n integrationProperties.// value of PersistenceUnitProperties.SESSION_NAME\n put(// value of PersistenceUnitProperties.SESSION_NAME\n \"eclipselink.session-name\", \"disabled-logging-pu\" + UUID.randomUUID().toString());\n }\n\n /**\n * Log version information about the specified persistence provider, if it can be determined.\n *\n * @param providerName fully qualified class name of JPA persistence provider\n * @param loader class loader with access to the JPA provider classes\n */\n @FFDCIgnore(Exception.class)\n private void logProviderInfo(String providerName, ClassLoader loader) {\n try {\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n Class Version = loadClass(loader, \"org.eclipse.persistence.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(Version.newInstance());\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"EclipseLink\", version);\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n Class Version = loadClass(loader, \"org.hibernate.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(null);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"Hibernate\", version);\n } else if (PROVIDER_OPENJPA.equals(providerName)) {\n // OpenJPAVersion.appendOpenJPABanner(sb): OpenJPA #.#.#\\n version id: openjpa-#.#.#-r# \\n Apache svn revision: #\n StringBuilder version = new StringBuilder();\n Class OpenJPAVersion = loadClass(loader, \"org.apache.openjpa.conf.OpenJPAVersion\");\n OpenJPAVersion.getMethod(\"appendOpenJPABanner\", StringBuilder.class).invoke(OpenJPAVersion.newInstance(), version);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"OpenJPA\", version);\n } else {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n }\n } catch (Exception x) {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"unable to determine provider info\", x);\n }\n }\n\n @FFDCIgnore(PrivilegedActionException.class)\n private static Class loadClass(final ClassLoader cl, final String className) throws ClassNotFoundException {\n if (System.getSecurityManager() == null)\n return cl.loadClass(className);\n else\n try {\n return AccessController.doPrivileged(new PrivilegedExceptionAction>() {\n\n @Override\n public Class run() throws ClassNotFoundException {\n return cl.loadClass(className);\n }\n });\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof ClassNotFoundException)\n throw (ClassNotFoundException) e.getCause();\n else\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void moduleStarting(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStarted(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopping(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopped(ModuleInfo moduleInfo) {\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#supportsEntityManagerPooling()\n */\n @Override\n public boolean supportsEntityManagerPooling() {\n return false;\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#addIntegrationProperties(java.util.Properties)\n */\n @FFDCIgnore(ClassNotFoundException.class)\n @Override\n public void updatePersistenceProviderIntegrationProperties(PersistenceUnitInfo puInfo, java.util.Map props) {\n String providerName = puInfo.getPersistenceProviderClassName();\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n props.put(\"eclipselink.target-server\", \"WebSphere_Liberty\");\n if (puInfo instanceof com.ibm.ws.jpa.management.JPAPUnitInfo) {\n props.put(\"eclipselink.application-id\", ((com.ibm.ws.jpa.management.JPAPUnitInfo) puInfo).getApplName());\n }\n Properties properties = puInfo.getProperties();\n /*\n * Section 4.8.5 of the JPA Specification:\n * If SUM, AVG, MAX, or MIN is used, and there are no values\n * to which the aggregate function can be applied, the result of\n * the aggregate function is NULL.\n *\n * Set this property to so that EclipseLink does not return null by default\n *\n * JPA 3.0: Do not force this override with JPA 3.0 and later.\n */\n if (!properties.containsKey(\"eclipselink.allow-null-max-min\") && JPAAccessor.getJPAComponent().getJPAVersion().lesserThan(JPAVersion.JPA30)) {\n props.put(\"eclipselink.allow-null-max-min\", \"false\");\n }\n /*\n * EclipseLink Bug 567891: Case expressions that should return boolean instead\n * return integer values. The JPA spec is too vague to change this, so we set this\n * property to be safe for customers.\n *\n * Set this property to `false` so that EclipseLink will return the same integer\n * value it has always returned for CASE expressions and not change behavior\n *\n * NOTE: This property is applicable for JPA 21 & JPA 22. JPAVersion > JPA22 has changed\n * behavior by default\n */\n if (!properties.containsKey(\"eclipselink.sql.allow-convert-result-to-boolean\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA22)) {\n props.put(\"eclipselink.sql.allow-convert-result-to-boolean\", \"false\");\n }\n // The property is named differently for EclipseLink 2.6\n if (!properties.containsKey(\"eclipselink.allow-result-type-conversion\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA21)) {\n props.put(\"eclipselink.allow-result-type-conversion\", \"false\");\n }\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n // Hibernate had vastly outdated built-in knowledge of WebSphere API, until version 5.2.13+ and 5.3+.\n // If the version of Hibernate has the Liberty JtaPlatform, use it\n // otherwise, tell Hibernate to use a proxy implementation of JtaPlatform that we will provide based on the WAS transaction manager\n ClassLoader loader = puInfo.getClassLoader();\n if (isWebSphereLibertyJtaPlatformAvailable(loader)) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Detected WebSphereLibertyJtaPlatform, not applying dynamic proxy JtaPlatform.\");\n } else {\n try {\n Class JtaPlatform = loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform\");\n Object libertyJtaPlatform = Proxy.newProxyInstance(loader, new Class[] { JtaPlatform }, new LibertyJtaPlatform());\n props.put(\"hibernate.transaction.jta.platform\", libertyJtaPlatform);\n } catch (ClassNotFoundException x) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Unable to provide JtaPlatform for Liberty TransactionManager to Hibernate\", x);\n }\n }\n }\n // Log third party provider name and version info once per provider\n ", "post_mask_code": "\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#modifyPersistenceUnitProperties(java.lang.String, java.util.Properties)\n */\n @Override\n public void updatePersistenceUnitProperties(String providerClassName, Properties props) {\n }\n\n /**\n * As of Hibernate 5.2.13+ and 5.3+ built-in knowledge of Liberty's transaction integration was delivered as:\n * org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\n * If this class is available, we do not need to set our dynamic proxy instance.\n */\n @FFDCIgnore(ClassNotFoundException.class)\n private boolean isWebSphereLibertyJtaPlatformAvailable(ClassLoader loader) {\n try {\n loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\");\n return true;\n } catch (ClassNotFoundException notFound) {\n return false;\n }\n }\n}\n"} {"task_id": "Java_332", "language": "Java", "task_type": "try_statement", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/AbstractJPAProviderIntegration.java", "mask_start_position": 11237, "mask_end_position": 11472, "canonical_solution": "try {\n loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\");\n return true;\n } catch (ClassNotFoundException notFound) {\n return false;\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.jpa;\n\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_RESOURCE_BUNDLE_NAME;\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_TRACE_GROUP;\nimport java.lang.reflect.Proxy;\nimport java.security.AccessController;\nimport java.security.PrivilegedActionException;\nimport java.security.PrivilegedExceptionAction;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentSkipListSet;\nimport javax.persistence.spi.PersistenceUnitInfo;\nimport com.ibm.websphere.ras.Tr;\nimport com.ibm.websphere.ras.TraceComponent;\nimport com.ibm.ws.container.service.app.deploy.ModuleInfo;\nimport com.ibm.ws.ffdc.annotation.FFDCIgnore;\nimport com.ibm.ws.jpa.hibernate.LibertyJtaPlatform;\n\n/**\n * Common JPAProviderIntegration implementation that provides general integration required for known\n * JPA providers.\n */\npublic abstract class AbstractJPAProviderIntegration implements JPAProviderIntegration {\n\n private static final TraceComponent tc = Tr.register(AbstractJPAProviderIntegration.class, JPA_TRACE_GROUP, JPA_RESOURCE_BUNDLE_NAME);\n\n // Known JPA provider implementation classes\n protected static final String PROVIDER_ECLIPSELINK = \"org.eclipse.persistence.jpa.PersistenceProvider\";\n\n protected static final String PROVIDER_HIBERNATE = \"org.hibernate.jpa.HibernatePersistenceProvider\";\n\n protected static final String PROVIDER_OPENJPA = \"org.apache.openjpa.persistence.PersistenceProviderImpl\";\n\n /**\n * As persistence providers are first used, they are added to this list so that version information is only logged once for them.\n */\n protected final ConcurrentSkipListSet providersUsed = new ConcurrentSkipListSet();\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#disablePersistenceUnitLogging(java.util.Map)\n */\n @Override\n public void disablePersistenceUnitLogging(Map integrationProperties) {\n integrationProperties.put(\"eclipselink.logging.level\", \"OFF\");\n // Since we're disabling logging, we don't want this to conflict with other normally configured PUs. Give it a random\n // session-name such that when/if another EMF is created for this PU the EclipseLink JPAInitializer cache\n // value of PersistenceUnitProperties.SESSION_NAME\n integrationProperties.// value of PersistenceUnitProperties.SESSION_NAME\n put(// value of PersistenceUnitProperties.SESSION_NAME\n \"eclipselink.session-name\", \"disabled-logging-pu\" + UUID.randomUUID().toString());\n }\n\n /**\n * Log version information about the specified persistence provider, if it can be determined.\n *\n * @param providerName fully qualified class name of JPA persistence provider\n * @param loader class loader with access to the JPA provider classes\n */\n @FFDCIgnore(Exception.class)\n private void logProviderInfo(String providerName, ClassLoader loader) {\n try {\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n Class Version = loadClass(loader, \"org.eclipse.persistence.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(Version.newInstance());\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"EclipseLink\", version);\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n Class Version = loadClass(loader, \"org.hibernate.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(null);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"Hibernate\", version);\n } else if (PROVIDER_OPENJPA.equals(providerName)) {\n // OpenJPAVersion.appendOpenJPABanner(sb): OpenJPA #.#.#\\n version id: openjpa-#.#.#-r# \\n Apache svn revision: #\n StringBuilder version = new StringBuilder();\n Class OpenJPAVersion = loadClass(loader, \"org.apache.openjpa.conf.OpenJPAVersion\");\n OpenJPAVersion.getMethod(\"appendOpenJPABanner\", StringBuilder.class).invoke(OpenJPAVersion.newInstance(), version);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"OpenJPA\", version);\n } else {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n }\n } catch (Exception x) {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"unable to determine provider info\", x);\n }\n }\n\n @FFDCIgnore(PrivilegedActionException.class)\n private static Class loadClass(final ClassLoader cl, final String className) throws ClassNotFoundException {\n if (System.getSecurityManager() == null)\n return cl.loadClass(className);\n else\n try {\n return AccessController.doPrivileged(new PrivilegedExceptionAction>() {\n\n @Override\n public Class run() throws ClassNotFoundException {\n return cl.loadClass(className);\n }\n });\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof ClassNotFoundException)\n throw (ClassNotFoundException) e.getCause();\n else\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void moduleStarting(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStarted(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopping(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopped(ModuleInfo moduleInfo) {\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#supportsEntityManagerPooling()\n */\n @Override\n public boolean supportsEntityManagerPooling() {\n return false;\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#addIntegrationProperties(java.util.Properties)\n */\n @FFDCIgnore(ClassNotFoundException.class)\n @Override\n public void updatePersistenceProviderIntegrationProperties(PersistenceUnitInfo puInfo, java.util.Map props) {\n String providerName = puInfo.getPersistenceProviderClassName();\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n props.put(\"eclipselink.target-server\", \"WebSphere_Liberty\");\n if (puInfo instanceof com.ibm.ws.jpa.management.JPAPUnitInfo) {\n props.put(\"eclipselink.application-id\", ((com.ibm.ws.jpa.management.JPAPUnitInfo) puInfo).getApplName());\n }\n Properties properties = puInfo.getProperties();\n /*\n * Section 4.8.5 of the JPA Specification:\n * If SUM, AVG, MAX, or MIN is used, and there are no values\n * to which the aggregate function can be applied, the result of\n * the aggregate function is NULL.\n *\n * Set this property to so that EclipseLink does not return null by default\n *\n * JPA 3.0: Do not force this override with JPA 3.0 and later.\n */\n if (!properties.containsKey(\"eclipselink.allow-null-max-min\") && JPAAccessor.getJPAComponent().getJPAVersion().lesserThan(JPAVersion.JPA30)) {\n props.put(\"eclipselink.allow-null-max-min\", \"false\");\n }\n /*\n * EclipseLink Bug 567891: Case expressions that should return boolean instead\n * return integer values. The JPA spec is too vague to change this, so we set this\n * property to be safe for customers.\n *\n * Set this property to `false` so that EclipseLink will return the same integer\n * value it has always returned for CASE expressions and not change behavior\n *\n * NOTE: This property is applicable for JPA 21 & JPA 22. JPAVersion > JPA22 has changed\n * behavior by default\n */\n if (!properties.containsKey(\"eclipselink.sql.allow-convert-result-to-boolean\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA22)) {\n props.put(\"eclipselink.sql.allow-convert-result-to-boolean\", \"false\");\n }\n // The property is named differently for EclipseLink 2.6\n if (!properties.containsKey(\"eclipselink.allow-result-type-conversion\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA21)) {\n props.put(\"eclipselink.allow-result-type-conversion\", \"false\");\n }\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n // Hibernate had vastly outdated built-in knowledge of WebSphere API, until version 5.2.13+ and 5.3+.\n // If the version of Hibernate has the Liberty JtaPlatform, use it\n // otherwise, tell Hibernate to use a proxy implementation of JtaPlatform that we will provide based on the WAS transaction manager\n ClassLoader loader = puInfo.getClassLoader();\n if (isWebSphereLibertyJtaPlatformAvailable(loader)) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Detected WebSphereLibertyJtaPlatform, not applying dynamic proxy JtaPlatform.\");\n } else {\n try {\n Class JtaPlatform = loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform\");\n Object libertyJtaPlatform = Proxy.newProxyInstance(loader, new Class[] { JtaPlatform }, new LibertyJtaPlatform());\n props.put(\"hibernate.transaction.jta.platform\", libertyJtaPlatform);\n } catch (ClassNotFoundException x) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Unable to provide JtaPlatform for Liberty TransactionManager to Hibernate\", x);\n }\n }\n }\n // Log third party provider name and version info once per provider\n if (providersUsed.add(providerName))\n logProviderInfo(providerName, puInfo.getClassLoader());\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#modifyPersistenceUnitProperties(java.lang.String, java.util.Properties)\n */\n @Override\n public void updatePersistenceUnitProperties(String providerClassName, Properties props) {\n }\n\n /**\n * As of Hibernate 5.2.13+ and 5.3+ built-in knowledge of Liberty's transaction integration was delivered as:\n * org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\n * If this class is available, we do not need to set our dynamic proxy instance.\n */\n @FFDCIgnore(ClassNotFoundException.class)\n private boolean isWebSphereLibertyJtaPlatformAvailable(ClassLoader loader) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_333", "language": "Java", "task_type": "empty", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/AbstractJPAProviderIntegration.java", "mask_start_position": 244, "mask_end_position": 244, "canonical_solution": "", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n ", "post_mask_code": "*/\npackage com.ibm.ws.jpa;\n\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_RESOURCE_BUNDLE_NAME;\nimport static com.ibm.ws.jpa.management.JPAConstants.JPA_TRACE_GROUP;\nimport java.lang.reflect.Proxy;\nimport java.security.AccessController;\nimport java.security.PrivilegedActionException;\nimport java.security.PrivilegedExceptionAction;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentSkipListSet;\nimport javax.persistence.spi.PersistenceUnitInfo;\nimport com.ibm.websphere.ras.Tr;\nimport com.ibm.websphere.ras.TraceComponent;\nimport com.ibm.ws.container.service.app.deploy.ModuleInfo;\nimport com.ibm.ws.ffdc.annotation.FFDCIgnore;\nimport com.ibm.ws.jpa.hibernate.LibertyJtaPlatform;\n\n/**\n * Common JPAProviderIntegration implementation that provides general integration required for known\n * JPA providers.\n */\npublic abstract class AbstractJPAProviderIntegration implements JPAProviderIntegration {\n\n private static final TraceComponent tc = Tr.register(AbstractJPAProviderIntegration.class, JPA_TRACE_GROUP, JPA_RESOURCE_BUNDLE_NAME);\n\n // Known JPA provider implementation classes\n protected static final String PROVIDER_ECLIPSELINK = \"org.eclipse.persistence.jpa.PersistenceProvider\";\n\n protected static final String PROVIDER_HIBERNATE = \"org.hibernate.jpa.HibernatePersistenceProvider\";\n\n protected static final String PROVIDER_OPENJPA = \"org.apache.openjpa.persistence.PersistenceProviderImpl\";\n\n /**\n * As persistence providers are first used, they are added to this list so that version information is only logged once for them.\n */\n protected final ConcurrentSkipListSet providersUsed = new ConcurrentSkipListSet();\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#disablePersistenceUnitLogging(java.util.Map)\n */\n @Override\n public void disablePersistenceUnitLogging(Map integrationProperties) {\n integrationProperties.put(\"eclipselink.logging.level\", \"OFF\");\n // Since we're disabling logging, we don't want this to conflict with other normally configured PUs. Give it a random\n // session-name such that when/if another EMF is created for this PU the EclipseLink JPAInitializer cache\n // value of PersistenceUnitProperties.SESSION_NAME\n integrationProperties.// value of PersistenceUnitProperties.SESSION_NAME\n put(// value of PersistenceUnitProperties.SESSION_NAME\n \"eclipselink.session-name\", \"disabled-logging-pu\" + UUID.randomUUID().toString());\n }\n\n /**\n * Log version information about the specified persistence provider, if it can be determined.\n *\n * @param providerName fully qualified class name of JPA persistence provider\n * @param loader class loader with access to the JPA provider classes\n */\n @FFDCIgnore(Exception.class)\n private void logProviderInfo(String providerName, ClassLoader loader) {\n try {\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n Class Version = loadClass(loader, \"org.eclipse.persistence.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(Version.newInstance());\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"EclipseLink\", version);\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n Class Version = loadClass(loader, \"org.hibernate.Version\");\n String version = (String) Version.getMethod(\"getVersionString\").invoke(null);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"Hibernate\", version);\n } else if (PROVIDER_OPENJPA.equals(providerName)) {\n // OpenJPAVersion.appendOpenJPABanner(sb): OpenJPA #.#.#\\n version id: openjpa-#.#.#-r# \\n Apache svn revision: #\n StringBuilder version = new StringBuilder();\n Class OpenJPAVersion = loadClass(loader, \"org.apache.openjpa.conf.OpenJPAVersion\");\n OpenJPAVersion.getMethod(\"appendOpenJPABanner\", StringBuilder.class).invoke(OpenJPAVersion.newInstance(), version);\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_INFO_CWWJP0053I\", \"OpenJPA\", version);\n } else {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n }\n } catch (Exception x) {\n Tr.info(tc, \"JPA_THIRD_PARTY_PROV_NAME_CWWJP0052I\", providerName);\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"unable to determine provider info\", x);\n }\n }\n\n @FFDCIgnore(PrivilegedActionException.class)\n private static Class loadClass(final ClassLoader cl, final String className) throws ClassNotFoundException {\n if (System.getSecurityManager() == null)\n return cl.loadClass(className);\n else\n try {\n return AccessController.doPrivileged(new PrivilegedExceptionAction>() {\n\n @Override\n public Class run() throws ClassNotFoundException {\n return cl.loadClass(className);\n }\n });\n } catch (PrivilegedActionException e) {\n if (e.getCause() instanceof ClassNotFoundException)\n throw (ClassNotFoundException) e.getCause();\n else\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void moduleStarting(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStarted(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopping(ModuleInfo moduleInfo) {\n }\n\n @Override\n public void moduleStopped(ModuleInfo moduleInfo) {\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProviderIntegration#supportsEntityManagerPooling()\n */\n @Override\n public boolean supportsEntityManagerPooling() {\n return false;\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#addIntegrationProperties(java.util.Properties)\n */\n @FFDCIgnore(ClassNotFoundException.class)\n @Override\n public void updatePersistenceProviderIntegrationProperties(PersistenceUnitInfo puInfo, java.util.Map props) {\n String providerName = puInfo.getPersistenceProviderClassName();\n if (PROVIDER_ECLIPSELINK.equals(providerName)) {\n props.put(\"eclipselink.target-server\", \"WebSphere_Liberty\");\n if (puInfo instanceof com.ibm.ws.jpa.management.JPAPUnitInfo) {\n props.put(\"eclipselink.application-id\", ((com.ibm.ws.jpa.management.JPAPUnitInfo) puInfo).getApplName());\n }\n Properties properties = puInfo.getProperties();\n /*\n * Section 4.8.5 of the JPA Specification:\n * If SUM, AVG, MAX, or MIN is used, and there are no values\n * to which the aggregate function can be applied, the result of\n * the aggregate function is NULL.\n *\n * Set this property to so that EclipseLink does not return null by default\n *\n * JPA 3.0: Do not force this override with JPA 3.0 and later.\n */\n if (!properties.containsKey(\"eclipselink.allow-null-max-min\") && JPAAccessor.getJPAComponent().getJPAVersion().lesserThan(JPAVersion.JPA30)) {\n props.put(\"eclipselink.allow-null-max-min\", \"false\");\n }\n /*\n * EclipseLink Bug 567891: Case expressions that should return boolean instead\n * return integer values. The JPA spec is too vague to change this, so we set this\n * property to be safe for customers.\n *\n * Set this property to `false` so that EclipseLink will return the same integer\n * value it has always returned for CASE expressions and not change behavior\n *\n * NOTE: This property is applicable for JPA 21 & JPA 22. JPAVersion > JPA22 has changed\n * behavior by default\n */\n if (!properties.containsKey(\"eclipselink.sql.allow-convert-result-to-boolean\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA22)) {\n props.put(\"eclipselink.sql.allow-convert-result-to-boolean\", \"false\");\n }\n // The property is named differently for EclipseLink 2.6\n if (!properties.containsKey(\"eclipselink.allow-result-type-conversion\") && JPAAccessor.getJPAComponent().getJPAVersion().equals(JPAVersion.JPA21)) {\n props.put(\"eclipselink.allow-result-type-conversion\", \"false\");\n }\n } else if (PROVIDER_HIBERNATE.equals(providerName)) {\n // Hibernate had vastly outdated built-in knowledge of WebSphere API, until version 5.2.13+ and 5.3+.\n // If the version of Hibernate has the Liberty JtaPlatform, use it\n // otherwise, tell Hibernate to use a proxy implementation of JtaPlatform that we will provide based on the WAS transaction manager\n ClassLoader loader = puInfo.getClassLoader();\n if (isWebSphereLibertyJtaPlatformAvailable(loader)) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Detected WebSphereLibertyJtaPlatform, not applying dynamic proxy JtaPlatform.\");\n } else {\n try {\n Class JtaPlatform = loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform\");\n Object libertyJtaPlatform = Proxy.newProxyInstance(loader, new Class[] { JtaPlatform }, new LibertyJtaPlatform());\n props.put(\"hibernate.transaction.jta.platform\", libertyJtaPlatform);\n } catch (ClassNotFoundException x) {\n if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())\n Tr.debug(this, tc, \"Unable to provide JtaPlatform for Liberty TransactionManager to Hibernate\", x);\n }\n }\n }\n // Log third party provider name and version info once per provider\n if (providersUsed.add(providerName))\n logProviderInfo(providerName, puInfo.getClassLoader());\n }\n\n /**\n * @see com.ibm.ws.jpa.JPAProvider#modifyPersistenceUnitProperties(java.lang.String, java.util.Properties)\n */\n @Override\n public void updatePersistenceUnitProperties(String providerClassName, Properties props) {\n }\n\n /**\n * As of Hibernate 5.2.13+ and 5.3+ built-in knowledge of Liberty's transaction integration was delivered as:\n * org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\n * If this class is available, we do not need to set our dynamic proxy instance.\n */\n @FFDCIgnore(ClassNotFoundException.class)\n private boolean isWebSphereLibertyJtaPlatformAvailable(ClassLoader loader) {\n try {\n loadClass(loader, \"org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform\");\n return true;\n } catch (ClassNotFoundException notFound) {\n return false;\n }\n }\n}\n"} {"task_id": "Java_334", "language": "Java", "task_type": "empty", "source_file": "java/github/liveontologies/elk-reasoner/elk-proofs/src/main/java/org/semanticweb/elk/matching/conclusions/ConclusionMatchHierarchy.java", "mask_start_position": 1325, "mask_end_position": 1325, "canonical_solution": "", "pre_mask_code": "package org.semanticweb.elk.matching.conclusions;\n\n/*\n * #%L\n * ELK Proofs Package\n * $Id:$\n * $HeadURL:$\n * %%\n * %%\n * #L%\n */\npublic interface ConclusionMatchHierarchy {\n\n Iterable getChildren(BackwardLinkMatch1 parent);\n\n Iterable getChildren(BackwardLinkMatch2 parent);\n\n Iterable getChildren(BackwardLinkMatch3 parent);\n\n Iterable getChildren(ClassInconsistencyMatch1 parent);\n\n Iterable getChildren(DisjointSubsumerMatch1 parent);\n\n Iterable getChildren(ForwardLinkMatch1 parent);\n\n Iterable getChildren(ForwardLinkMatch2 parent);\n\n Iterable getChildren(ForwardLinkMatch3 parent);\n\n Iterable getChildren(IndexedDisjointClassesAxiomMatch1 parent);\n\n Iterable getChildren(IndexedEquivalentClassesAxiomMatch1 parent);\n\n Iterable getChildren(IndexedObjectPropertyRangeAxiomMatch1 parent);\n\n Iterable getChildren(IndexedSubClassOfAxiomMatch1 parent);\n\n Ite", "post_mask_code": "rable getChildren(IndexedSubObjectPropertyOfAxiomMatch1 parent);\n\n Iterable getChildren(PropagationMatch1 parent);\n\n Iterable getChildren(PropertyRangeMatch1 parent);\n\n Iterable getChildren(SubClassInclusionComposedMatch1 parent);\n\n Iterable getChildren(SubClassInclusionDecomposedMatch1 parent);\n\n Iterable getChildren(SubPropertyChainMatch1 parent);\n}\n"} {"task_id": "Java_335", "language": "Java", "task_type": "method_signature", "source_file": "java/github/archimatetool/archi/com.archimatetool.editor/src/com/archimatetool/editor/diagram/figures/elements/PathFigure.java", "mask_start_position": 974, "mask_end_position": 1031, "canonical_solution": "@Override\n protected void drawIcon(Graphics graphics) ", "pre_mask_code": "package com.archimatetool.editor.diagram.figures.elements;\n\nimport org.eclipse.draw2d.ColorConstants;\nimport org.eclipse.draw2d.Graphics;\nimport org.eclipse.draw2d.geometry.Dimension;\nimport org.eclipse.draw2d.geometry.Point;\nimport org.eclipse.draw2d.geometry.Rectangle;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.graphics.Path;\n\n/**\n * Path Figure\n *\n * @author Phillip Beauvoir\n */\npublic class PathFigure extends CommunicationNetworkFigure {\n\n public PathFigure() {\n }\n\n @Override\n protected void drawHorizontalLine(Graphics graphics, Rectangle rect, Dimension arrow) {\n // Line dashes\n graphics.setLineStyle(SWT.LINE_CUSTOM);\n graphics.setLineDash(new float[] { graphics.getLineWidthFloat() * 2, graphics.getLineWidthFloat() });\n graphics.setLineCap(SWT.CAP_FLAT);\n graphics.drawLine(rect.x, rect.y + rect.height / 2, rect.x + rect.width, rect.y + rect.height / 2);\n }\n\n /**\n * Draw the icon\n */\n ", "post_mask_code": "{\n if (!isIconVisible()) {\n return;\n }\n graphics.pushState();\n graphics.setLineWidthFloat(1.5f);\n graphics.setForegroundColor(isEnabled() ? ColorConstants.black : ColorConstants.gray);\n Point pt = getIconOrigin();\n Path path = new Path(null);\n path.moveTo(pt.x + 2.5f, pt.y);\n path.lineTo(pt.x + 4.5f, pt.y);\n path.moveTo(pt.x + 6.5f, pt.y);\n path.lineTo(pt.x + 8.5f, pt.y);\n path.moveTo(pt.x + 10.5f, pt.y);\n path.lineTo(pt.x + 12.5f, pt.y);\n graphics.drawPath(path);\n path.dispose();\n path = new Path(null);\n path.moveTo(pt.x + 4, pt.y - 5);\n path.lineTo(pt.x - 1, pt.y);\n path.lineTo(pt.x + 4, pt.y + 5);\n path.moveTo(pt.x + 11, pt.y - 5);\n path.lineTo(pt.x + 16, pt.y);\n path.lineTo(pt.x + 11, pt.y + 5);\n graphics.drawPath(path);\n path.dispose();\n graphics.popState();\n }\n\n /**\n * @return The icon start position\n */\n @Override\n protected Point getIconOrigin() {\n Rectangle bounds = getBounds();\n return new Point(bounds.x + bounds.width - 20, bounds.y + 12);\n }\n}\n"} {"task_id": "Java_336", "language": "Java", "task_type": "method_body", "source_file": "java/github/archimatetool/archi/com.archimatetool.editor/src/com/archimatetool/editor/diagram/figures/elements/PathFigure.java", "mask_start_position": 2103, "mask_end_position": 2221, "canonical_solution": "{\n Rectangle bounds = getBounds();\n return new Point(bounds.x + bounds.width - 20, bounds.y + 12);\n }", "pre_mask_code": "package com.archimatetool.editor.diagram.figures.elements;\n\nimport org.eclipse.draw2d.ColorConstants;\nimport org.eclipse.draw2d.Graphics;\nimport org.eclipse.draw2d.geometry.Dimension;\nimport org.eclipse.draw2d.geometry.Point;\nimport org.eclipse.draw2d.geometry.Rectangle;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.graphics.Path;\n\n/**\n * Path Figure\n *\n * @author Phillip Beauvoir\n */\npublic class PathFigure extends CommunicationNetworkFigure {\n\n public PathFigure() {\n }\n\n @Override\n protected void drawHorizontalLine(Graphics graphics, Rectangle rect, Dimension arrow) {\n // Line dashes\n graphics.setLineStyle(SWT.LINE_CUSTOM);\n graphics.setLineDash(new float[] { graphics.getLineWidthFloat() * 2, graphics.getLineWidthFloat() });\n graphics.setLineCap(SWT.CAP_FLAT);\n graphics.drawLine(rect.x, rect.y + rect.height / 2, rect.x + rect.width, rect.y + rect.height / 2);\n }\n\n /**\n * Draw the icon\n */\n @Override\n protected void drawIcon(Graphics graphics) {\n if (!isIconVisible()) {\n return;\n }\n graphics.pushState();\n graphics.setLineWidthFloat(1.5f);\n graphics.setForegroundColor(isEnabled() ? ColorConstants.black : ColorConstants.gray);\n Point pt = getIconOrigin();\n Path path = new Path(null);\n path.moveTo(pt.x + 2.5f, pt.y);\n path.lineTo(pt.x + 4.5f, pt.y);\n path.moveTo(pt.x + 6.5f, pt.y);\n path.lineTo(pt.x + 8.5f, pt.y);\n path.moveTo(pt.x + 10.5f, pt.y);\n path.lineTo(pt.x + 12.5f, pt.y);\n graphics.drawPath(path);\n path.dispose();\n path = new Path(null);\n path.moveTo(pt.x + 4, pt.y - 5);\n path.lineTo(pt.x - 1, pt.y);\n path.lineTo(pt.x + 4, pt.y + 5);\n path.moveTo(pt.x + 11, pt.y - 5);\n path.lineTo(pt.x + 16, pt.y);\n path.lineTo(pt.x + 11, pt.y + 5);\n graphics.drawPath(path);\n path.dispose();\n graphics.popState();\n }\n\n /**\n * @return The icon start position\n */\n @Override\n protected Point getIconOrigin() ", "post_mask_code": "\n}\n"} {"task_id": "Java_337", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/archimatetool/archi/com.archimatetool.editor/src/com/archimatetool/editor/diagram/figures/elements/PathFigure.java", "mask_start_position": 593, "mask_end_position": 664, "canonical_solution": "\n // Line dashes\n graphics.setLineStyle(SWT.LINE_CUSTOM);", "pre_mask_code": "package com.archimatetool.editor.diagram.figures.elements;\n\nimport org.eclipse.draw2d.ColorConstants;\nimport org.eclipse.draw2d.Graphics;\nimport org.eclipse.draw2d.geometry.Dimension;\nimport org.eclipse.draw2d.geometry.Point;\nimport org.eclipse.draw2d.geometry.Rectangle;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.graphics.Path;\n\n/**\n * Path Figure\n *\n * @author Phillip Beauvoir\n */\npublic class PathFigure extends CommunicationNetworkFigure {\n\n public PathFigure() {\n }\n\n @Override\n protected void drawHorizontalLine(Graphics graphics, Rectangle rect, Dimension arrow) {", "post_mask_code": "\n graphics.setLineDash(new float[] { graphics.getLineWidthFloat() * 2, graphics.getLineWidthFloat() });\n graphics.setLineCap(SWT.CAP_FLAT);\n graphics.drawLine(rect.x, rect.y + rect.height / 2, rect.x + rect.width, rect.y + rect.height / 2);\n }\n\n /**\n * Draw the icon\n */\n @Override\n protected void drawIcon(Graphics graphics) {\n if (!isIconVisible()) {\n return;\n }\n graphics.pushState();\n graphics.setLineWidthFloat(1.5f);\n graphics.setForegroundColor(isEnabled() ? ColorConstants.black : ColorConstants.gray);\n Point pt = getIconOrigin();\n Path path = new Path(null);\n path.moveTo(pt.x + 2.5f, pt.y);\n path.lineTo(pt.x + 4.5f, pt.y);\n path.moveTo(pt.x + 6.5f, pt.y);\n path.lineTo(pt.x + 8.5f, pt.y);\n path.moveTo(pt.x + 10.5f, pt.y);\n path.lineTo(pt.x + 12.5f, pt.y);\n graphics.drawPath(path);\n path.dispose();\n path = new Path(null);\n path.moveTo(pt.x + 4, pt.y - 5);\n path.lineTo(pt.x - 1, pt.y);\n path.lineTo(pt.x + 4, pt.y + 5);\n path.moveTo(pt.x + 11, pt.y - 5);\n path.lineTo(pt.x + 16, pt.y);\n path.lineTo(pt.x + 11, pt.y + 5);\n graphics.drawPath(path);\n path.dispose();\n graphics.popState();\n }\n\n /**\n * @return The icon start position\n */\n @Override\n protected Point getIconOrigin() {\n Rectangle bounds = getBounds();\n return new Point(bounds.x + bounds.width - 20, bounds.y + 12);\n }\n}\n"} {"task_id": "Java_338", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/archimatetool/archi/com.archimatetool.editor/src/com/archimatetool/editor/diagram/figures/elements/PathFigure.java", "mask_start_position": 673, "mask_end_position": 817, "canonical_solution": "graphics.setLineDash(new float[] { graphics.getLineWidthFloat() * 2, graphics.getLineWidthFloat() });\n graphics.setLineCap(SWT.CAP_FLAT);", "pre_mask_code": "package com.archimatetool.editor.diagram.figures.elements;\n\nimport org.eclipse.draw2d.ColorConstants;\nimport org.eclipse.draw2d.Graphics;\nimport org.eclipse.draw2d.geometry.Dimension;\nimport org.eclipse.draw2d.geometry.Point;\nimport org.eclipse.draw2d.geometry.Rectangle;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.graphics.Path;\n\n/**\n * Path Figure\n *\n * @author Phillip Beauvoir\n */\npublic class PathFigure extends CommunicationNetworkFigure {\n\n public PathFigure() {\n }\n\n @Override\n protected void drawHorizontalLine(Graphics graphics, Rectangle rect, Dimension arrow) {\n // Line dashes\n graphics.setLineStyle(SWT.LINE_CUSTOM);\n ", "post_mask_code": "\n graphics.drawLine(rect.x, rect.y + rect.height / 2, rect.x + rect.width, rect.y + rect.height / 2);\n }\n\n /**\n * Draw the icon\n */\n @Override\n protected void drawIcon(Graphics graphics) {\n if (!isIconVisible()) {\n return;\n }\n graphics.pushState();\n graphics.setLineWidthFloat(1.5f);\n graphics.setForegroundColor(isEnabled() ? ColorConstants.black : ColorConstants.gray);\n Point pt = getIconOrigin();\n Path path = new Path(null);\n path.moveTo(pt.x + 2.5f, pt.y);\n path.lineTo(pt.x + 4.5f, pt.y);\n path.moveTo(pt.x + 6.5f, pt.y);\n path.lineTo(pt.x + 8.5f, pt.y);\n path.moveTo(pt.x + 10.5f, pt.y);\n path.lineTo(pt.x + 12.5f, pt.y);\n graphics.drawPath(path);\n path.dispose();\n path = new Path(null);\n path.moveTo(pt.x + 4, pt.y - 5);\n path.lineTo(pt.x - 1, pt.y);\n path.lineTo(pt.x + 4, pt.y + 5);\n path.moveTo(pt.x + 11, pt.y - 5);\n path.lineTo(pt.x + 16, pt.y);\n path.lineTo(pt.x + 11, pt.y + 5);\n graphics.drawPath(path);\n path.dispose();\n graphics.popState();\n }\n\n /**\n * @return The icon start position\n */\n @Override\n protected Point getIconOrigin() {\n Rectangle bounds = getBounds();\n return new Point(bounds.x + bounds.width - 20, bounds.y + 12);\n }\n}\n"} {"task_id": "Java_339", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/archimatetool/archi/com.archimatetool.editor/src/com/archimatetool/editor/diagram/figures/elements/PathFigure.java", "mask_start_position": 826, "mask_end_position": 931, "canonical_solution": "graphics.drawLine(rect.x, rect.y + rect.height / 2, rect.x + rect.width, rect.y + rect.height / 2);\n }", "pre_mask_code": "package com.archimatetool.editor.diagram.figures.elements;\n\nimport org.eclipse.draw2d.ColorConstants;\nimport org.eclipse.draw2d.Graphics;\nimport org.eclipse.draw2d.geometry.Dimension;\nimport org.eclipse.draw2d.geometry.Point;\nimport org.eclipse.draw2d.geometry.Rectangle;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.graphics.Path;\n\n/**\n * Path Figure\n *\n * @author Phillip Beauvoir\n */\npublic class PathFigure extends CommunicationNetworkFigure {\n\n public PathFigure() {\n }\n\n @Override\n protected void drawHorizontalLine(Graphics graphics, Rectangle rect, Dimension arrow) {\n // Line dashes\n graphics.setLineStyle(SWT.LINE_CUSTOM);\n graphics.setLineDash(new float[] { graphics.getLineWidthFloat() * 2, graphics.getLineWidthFloat() });\n graphics.setLineCap(SWT.CAP_FLAT);\n ", "post_mask_code": "\n\n /**\n * Draw the icon\n */\n @Override\n protected void drawIcon(Graphics graphics) {\n if (!isIconVisible()) {\n return;\n }\n graphics.pushState();\n graphics.setLineWidthFloat(1.5f);\n graphics.setForegroundColor(isEnabled() ? ColorConstants.black : ColorConstants.gray);\n Point pt = getIconOrigin();\n Path path = new Path(null);\n path.moveTo(pt.x + 2.5f, pt.y);\n path.lineTo(pt.x + 4.5f, pt.y);\n path.moveTo(pt.x + 6.5f, pt.y);\n path.lineTo(pt.x + 8.5f, pt.y);\n path.moveTo(pt.x + 10.5f, pt.y);\n path.lineTo(pt.x + 12.5f, pt.y);\n graphics.drawPath(path);\n path.dispose();\n path = new Path(null);\n path.moveTo(pt.x + 4, pt.y - 5);\n path.lineTo(pt.x - 1, pt.y);\n path.lineTo(pt.x + 4, pt.y + 5);\n path.moveTo(pt.x + 11, pt.y - 5);\n path.lineTo(pt.x + 16, pt.y);\n path.lineTo(pt.x + 11, pt.y + 5);\n graphics.drawPath(path);\n path.dispose();\n graphics.popState();\n }\n\n /**\n * @return The icon start position\n */\n @Override\n protected Point getIconOrigin() {\n Rectangle bounds = getBounds();\n return new Point(bounds.x + bounds.width - 20, bounds.y + 12);\n }\n}\n"} {"task_id": "Java_340", "language": "Java", "task_type": "single_line", "source_file": "java/github/archimatetool/archi/com.archimatetool.editor/src/com/archimatetool/editor/diagram/figures/elements/PathFigure.java", "mask_start_position": 1629, "mask_end_position": 1632, "canonical_solution": "();", "pre_mask_code": "package com.archimatetool.editor.diagram.figures.elements;\n\nimport org.eclipse.draw2d.ColorConstants;\nimport org.eclipse.draw2d.Graphics;\nimport org.eclipse.draw2d.geometry.Dimension;\nimport org.eclipse.draw2d.geometry.Point;\nimport org.eclipse.draw2d.geometry.Rectangle;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.graphics.Path;\n\n/**\n * Path Figure\n *\n * @author Phillip Beauvoir\n */\npublic class PathFigure extends CommunicationNetworkFigure {\n\n public PathFigure() {\n }\n\n @Override\n protected void drawHorizontalLine(Graphics graphics, Rectangle rect, Dimension arrow) {\n // Line dashes\n graphics.setLineStyle(SWT.LINE_CUSTOM);\n graphics.setLineDash(new float[] { graphics.getLineWidthFloat() * 2, graphics.getLineWidthFloat() });\n graphics.setLineCap(SWT.CAP_FLAT);\n graphics.drawLine(rect.x, rect.y + rect.height / 2, rect.x + rect.width, rect.y + rect.height / 2);\n }\n\n /**\n * Draw the icon\n */\n @Override\n protected void drawIcon(Graphics graphics) {\n if (!isIconVisible()) {\n return;\n }\n graphics.pushState();\n graphics.setLineWidthFloat(1.5f);\n graphics.setForegroundColor(isEnabled() ? ColorConstants.black : ColorConstants.gray);\n Point pt = getIconOrigin();\n Path path = new Path(null);\n path.moveTo(pt.x + 2.5f, pt.y);\n path.lineTo(pt.x + 4.5f, pt.y);\n path.moveTo(pt.x + 6.5f, pt.y);\n path.lineTo(pt.x + 8.5f, pt.y);\n path.moveTo(pt.x + 10.5f, pt.y);\n path.lineTo(pt.x + 12.5f, pt.y);\n graphics.drawPath(path);\n path.dispose", "post_mask_code": "\n path = new Path(null);\n path.moveTo(pt.x + 4, pt.y - 5);\n path.lineTo(pt.x - 1, pt.y);\n path.lineTo(pt.x + 4, pt.y + 5);\n path.moveTo(pt.x + 11, pt.y - 5);\n path.lineTo(pt.x + 16, pt.y);\n path.lineTo(pt.x + 11, pt.y + 5);\n graphics.drawPath(path);\n path.dispose();\n graphics.popState();\n }\n\n /**\n * @return The icon start position\n */\n @Override\n protected Point getIconOrigin() {\n Rectangle bounds = getBounds();\n return new Point(bounds.x + bounds.width - 20, bounds.y + 12);\n }\n}\n"} {"task_id": "Java_341", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/archimatetool/archi/com.archimatetool.editor/src/com/archimatetool/editor/diagram/figures/elements/PathFigure.java", "mask_start_position": 2057, "mask_end_position": 2221, "canonical_solution": "@Override\n protected Point getIconOrigin() {\n Rectangle bounds = getBounds();\n return new Point(bounds.x + bounds.width - 20, bounds.y + 12);\n }", "pre_mask_code": "package com.archimatetool.editor.diagram.figures.elements;\n\nimport org.eclipse.draw2d.ColorConstants;\nimport org.eclipse.draw2d.Graphics;\nimport org.eclipse.draw2d.geometry.Dimension;\nimport org.eclipse.draw2d.geometry.Point;\nimport org.eclipse.draw2d.geometry.Rectangle;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.graphics.Path;\n\n/**\n * Path Figure\n *\n * @author Phillip Beauvoir\n */\npublic class PathFigure extends CommunicationNetworkFigure {\n\n public PathFigure() {\n }\n\n @Override\n protected void drawHorizontalLine(Graphics graphics, Rectangle rect, Dimension arrow) {\n // Line dashes\n graphics.setLineStyle(SWT.LINE_CUSTOM);\n graphics.setLineDash(new float[] { graphics.getLineWidthFloat() * 2, graphics.getLineWidthFloat() });\n graphics.setLineCap(SWT.CAP_FLAT);\n graphics.drawLine(rect.x, rect.y + rect.height / 2, rect.x + rect.width, rect.y + rect.height / 2);\n }\n\n /**\n * Draw the icon\n */\n @Override\n protected void drawIcon(Graphics graphics) {\n if (!isIconVisible()) {\n return;\n }\n graphics.pushState();\n graphics.setLineWidthFloat(1.5f);\n graphics.setForegroundColor(isEnabled() ? ColorConstants.black : ColorConstants.gray);\n Point pt = getIconOrigin();\n Path path = new Path(null);\n path.moveTo(pt.x + 2.5f, pt.y);\n path.lineTo(pt.x + 4.5f, pt.y);\n path.moveTo(pt.x + 6.5f, pt.y);\n path.lineTo(pt.x + 8.5f, pt.y);\n path.moveTo(pt.x + 10.5f, pt.y);\n path.lineTo(pt.x + 12.5f, pt.y);\n graphics.drawPath(path);\n path.dispose();\n path = new Path(null);\n path.moveTo(pt.x + 4, pt.y - 5);\n path.lineTo(pt.x - 1, pt.y);\n path.lineTo(pt.x + 4, pt.y + 5);\n path.moveTo(pt.x + 11, pt.y - 5);\n path.lineTo(pt.x + 16, pt.y);\n path.lineTo(pt.x + 11, pt.y + 5);\n graphics.drawPath(path);\n path.dispose();\n graphics.popState();\n }\n\n /**\n * @return The icon start position\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_342", "language": "Java", "task_type": "if_statement", "source_file": "java/github/archimatetool/archi/com.archimatetool.editor/src/com/archimatetool/editor/diagram/figures/elements/PathFigure.java", "mask_start_position": 1041, "mask_end_position": 1094, "canonical_solution": "if (!isIconVisible()) {\n return;\n }", "pre_mask_code": "package com.archimatetool.editor.diagram.figures.elements;\n\nimport org.eclipse.draw2d.ColorConstants;\nimport org.eclipse.draw2d.Graphics;\nimport org.eclipse.draw2d.geometry.Dimension;\nimport org.eclipse.draw2d.geometry.Point;\nimport org.eclipse.draw2d.geometry.Rectangle;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.graphics.Path;\n\n/**\n * Path Figure\n *\n * @author Phillip Beauvoir\n */\npublic class PathFigure extends CommunicationNetworkFigure {\n\n public PathFigure() {\n }\n\n @Override\n protected void drawHorizontalLine(Graphics graphics, Rectangle rect, Dimension arrow) {\n // Line dashes\n graphics.setLineStyle(SWT.LINE_CUSTOM);\n graphics.setLineDash(new float[] { graphics.getLineWidthFloat() * 2, graphics.getLineWidthFloat() });\n graphics.setLineCap(SWT.CAP_FLAT);\n graphics.drawLine(rect.x, rect.y + rect.height / 2, rect.x + rect.width, rect.y + rect.height / 2);\n }\n\n /**\n * Draw the icon\n */\n @Override\n protected void drawIcon(Graphics graphics) {\n ", "post_mask_code": "\n graphics.pushState();\n graphics.setLineWidthFloat(1.5f);\n graphics.setForegroundColor(isEnabled() ? ColorConstants.black : ColorConstants.gray);\n Point pt = getIconOrigin();\n Path path = new Path(null);\n path.moveTo(pt.x + 2.5f, pt.y);\n path.lineTo(pt.x + 4.5f, pt.y);\n path.moveTo(pt.x + 6.5f, pt.y);\n path.lineTo(pt.x + 8.5f, pt.y);\n path.moveTo(pt.x + 10.5f, pt.y);\n path.lineTo(pt.x + 12.5f, pt.y);\n graphics.drawPath(path);\n path.dispose();\n path = new Path(null);\n path.moveTo(pt.x + 4, pt.y - 5);\n path.lineTo(pt.x - 1, pt.y);\n path.lineTo(pt.x + 4, pt.y + 5);\n path.moveTo(pt.x + 11, pt.y - 5);\n path.lineTo(pt.x + 16, pt.y);\n path.lineTo(pt.x + 11, pt.y + 5);\n graphics.drawPath(path);\n path.dispose();\n graphics.popState();\n }\n\n /**\n * @return The icon start position\n */\n @Override\n protected Point getIconOrigin() {\n Rectangle bounds = getBounds();\n return new Point(bounds.x + bounds.width - 20, bounds.y + 12);\n }\n}\n"} {"task_id": "Java_343", "language": "Java", "task_type": "empty", "source_file": "java/github/archimatetool/archi/com.archimatetool.editor/src/com/archimatetool/editor/diagram/figures/elements/PathFigure.java", "mask_start_position": 446, "mask_end_position": 446, "canonical_solution": "", "pre_mask_code": "package com.archimatetool.editor.diagram.figures.elements;\n\nimport org.eclipse.draw2d.ColorConstants;\nimport org.eclipse.draw2d.Graphics;\nimport org.eclipse.draw2d.geometry.Dimension;\nimport org.eclipse.draw2d.geometry.Point;\nimport org.eclipse.draw2d.geometry.Rectangle;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.graphics.Path;\n\n/**\n * Path Figure\n *\n * @author Phillip Beauvoir\n */\npublic class PathFigure extends CommunicationNetworkF", "post_mask_code": "igure {\n\n public PathFigure() {\n }\n\n @Override\n protected void drawHorizontalLine(Graphics graphics, Rectangle rect, Dimension arrow) {\n // Line dashes\n graphics.setLineStyle(SWT.LINE_CUSTOM);\n graphics.setLineDash(new float[] { graphics.getLineWidthFloat() * 2, graphics.getLineWidthFloat() });\n graphics.setLineCap(SWT.CAP_FLAT);\n graphics.drawLine(rect.x, rect.y + rect.height / 2, rect.x + rect.width, rect.y + rect.height / 2);\n }\n\n /**\n * Draw the icon\n */\n @Override\n protected void drawIcon(Graphics graphics) {\n if (!isIconVisible()) {\n return;\n }\n graphics.pushState();\n graphics.setLineWidthFloat(1.5f);\n graphics.setForegroundColor(isEnabled() ? ColorConstants.black : ColorConstants.gray);\n Point pt = getIconOrigin();\n Path path = new Path(null);\n path.moveTo(pt.x + 2.5f, pt.y);\n path.lineTo(pt.x + 4.5f, pt.y);\n path.moveTo(pt.x + 6.5f, pt.y);\n path.lineTo(pt.x + 8.5f, pt.y);\n path.moveTo(pt.x + 10.5f, pt.y);\n path.lineTo(pt.x + 12.5f, pt.y);\n graphics.drawPath(path);\n path.dispose();\n path = new Path(null);\n path.moveTo(pt.x + 4, pt.y - 5);\n path.lineTo(pt.x - 1, pt.y);\n path.lineTo(pt.x + 4, pt.y + 5);\n path.moveTo(pt.x + 11, pt.y - 5);\n path.lineTo(pt.x + 16, pt.y);\n path.lineTo(pt.x + 11, pt.y + 5);\n graphics.drawPath(path);\n path.dispose();\n graphics.popState();\n }\n\n /**\n * @return The icon start position\n */\n @Override\n protected Point getIconOrigin() {\n Rectangle bounds = getBounds();\n return new Point(bounds.x + bounds.width - 20, bounds.y + 12);\n }\n}\n"} {"task_id": "Java_344", "language": "Java", "task_type": "method_signature", "source_file": "java/github/android-rcs/rcsjta/tests/cts/provider/src/androidTest/java/android/tests/provider/Utils.java", "mask_start_position": 342, "mask_end_position": 415, "canonical_solution": "public static void checkProjection(String[] expected, String[] obtained) ", "pre_mask_code": "/**\n * ****************************************************************************\n * Software Name : RCS IMS Stack\n *\n * ****************************************************************************\n */\npackage android.tests.provider;\n\nimport android.test.InstrumentationTestCase;\n\npublic class Utils extends InstrumentationTestCase {\n\n ", "post_mask_code": "{\n if (expected != null) {\n if (obtained == null) {\n fail(\"projection is null\");\n }\n assertEquals(expected.length, obtained.length);\n for (String field1 : expected) {\n boolean found = false;\n for (String field2 : obtained) {\n if (field1.equals(field2)) {\n found = true;\n break;\n }\n }\n if (!found) {\n fail(\"field is not present: \".concat(field1));\n }\n }\n } else {\n if (obtained != null) {\n fail(\"invalid Projection\");\n }\n }\n }\n}\n"} {"task_id": "Java_345", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/android-rcs/rcsjta/tests/cts/provider/src/androidTest/java/android/tests/provider/Utils.java", "mask_start_position": 416, "mask_end_position": 416, "canonical_solution": "", "pre_mask_code": "/**\n * ****************************************************************************\n * Software Name : RCS IMS Stack\n *\n * ****************************************************************************\n */\npackage android.tests.provider;\n\nimport android.test.InstrumentationTestCase;\n\npublic class Utils extends InstrumentationTestCase {\n\n public static void checkProjection(String[] expected, String[] obtained) {", "post_mask_code": "\n if (expected != null) {\n if (obtained == null) {\n fail(\"projection is null\");\n }\n assertEquals(expected.length, obtained.length);\n for (String field1 : expected) {\n boolean found = false;\n for (String field2 : obtained) {\n if (field1.equals(field2)) {\n found = true;\n break;\n }\n }\n if (!found) {\n fail(\"field is not present: \".concat(field1));\n }\n }\n } else {\n if (obtained != null) {\n fail(\"invalid Projection\");\n }\n }\n }\n}\n"} {"task_id": "Java_346", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/android-rcs/rcsjta/tests/cts/provider/src/androidTest/java/android/tests/provider/Utils.java", "mask_start_position": 425, "mask_end_position": 1143, "canonical_solution": "if (expected != null) {\n if (obtained == null) {\n fail(\"projection is null\");\n }\n assertEquals(expected.length, obtained.length);\n for (String field1 : expected) {\n boolean found = false;\n for (String field2 : obtained) {\n if (field1.equals(field2)) {\n found = true;\n break;\n }\n }\n if (!found) {\n fail(\"field is not present: \".concat(field1));\n }\n }\n } else {\n if (obtained != null) {\n fail(\"invalid Projection\");\n }\n }", "pre_mask_code": "/**\n * ****************************************************************************\n * Software Name : RCS IMS Stack\n *\n * ****************************************************************************\n */\npackage android.tests.provider;\n\nimport android.test.InstrumentationTestCase;\n\npublic class Utils extends InstrumentationTestCase {\n\n public static void checkProjection(String[] expected, String[] obtained) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_347", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/android-rcs/rcsjta/tests/cts/provider/src/androidTest/java/android/tests/provider/Utils.java", "mask_start_position": 1148, "mask_end_position": 1149, "canonical_solution": "}", "pre_mask_code": "/**\n * ****************************************************************************\n * Software Name : RCS IMS Stack\n *\n * ****************************************************************************\n */\npackage android.tests.provider;\n\nimport android.test.InstrumentationTestCase;\n\npublic class Utils extends InstrumentationTestCase {\n\n public static void checkProjection(String[] expected, String[] obtained) {\n if (expected != null) {\n if (obtained == null) {\n fail(\"projection is null\");\n }\n assertEquals(expected.length, obtained.length);\n for (String field1 : expected) {\n boolean found = false;\n for (String field2 : obtained) {\n if (field1.equals(field2)) {\n found = true;\n break;\n }\n }\n if (!found) {\n fail(\"field is not present: \".concat(field1));\n }\n }\n } else {\n if (obtained != null) {\n fail(\"invalid Projection\");\n }\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_348", "language": "Java", "task_type": "if_statement", "source_file": "java/github/android-rcs/rcsjta/tests/cts/provider/src/androidTest/java/android/tests/provider/Utils.java", "mask_start_position": 1052, "mask_end_position": 1133, "canonical_solution": "if (obtained != null) {\n fail(\"invalid Projection\");\n }", "pre_mask_code": "/**\n * ****************************************************************************\n * Software Name : RCS IMS Stack\n *\n * ****************************************************************************\n */\npackage android.tests.provider;\n\nimport android.test.InstrumentationTestCase;\n\npublic class Utils extends InstrumentationTestCase {\n\n public static void checkProjection(String[] expected, String[] obtained) {\n if (expected != null) {\n if (obtained == null) {\n fail(\"projection is null\");\n }\n assertEquals(expected.length, obtained.length);\n for (String field1 : expected) {\n boolean found = false;\n for (String field2 : obtained) {\n if (field1.equals(field2)) {\n found = true;\n break;\n }\n }\n if (!found) {\n fail(\"field is not present: \".concat(field1));\n }\n }\n } else {\n ", "post_mask_code": "\n }\n }\n}\n"} {"task_id": "Java_349", "language": "Java", "task_type": "empty", "source_file": "java/github/android-rcs/rcsjta/tests/cts/provider/src/androidTest/java/android/tests/provider/Utils.java", "mask_start_position": 80, "mask_end_position": 80, "canonical_solution": "", "pre_mask_code": "/**\n * *************************************************************************", "post_mask_code": "***\n * Software Name : RCS IMS Stack\n *\n * ****************************************************************************\n */\npackage android.tests.provider;\n\nimport android.test.InstrumentationTestCase;\n\npublic class Utils extends InstrumentationTestCase {\n\n public static void checkProjection(String[] expected, String[] obtained) {\n if (expected != null) {\n if (obtained == null) {\n fail(\"projection is null\");\n }\n assertEquals(expected.length, obtained.length);\n for (String field1 : expected) {\n boolean found = false;\n for (String field2 : obtained) {\n if (field1.equals(field2)) {\n found = true;\n break;\n }\n }\n if (!found) {\n fail(\"field is not present: \".concat(field1));\n }\n }\n } else {\n if (obtained != null) {\n fail(\"invalid Projection\");\n }\n }\n }\n}\n"} {"task_id": "Java_350", "language": "Java", "task_type": "method_signature", "source_file": "java/github/usb4java/usb4java-javax-examples/src/main/java/org/usb4java/javax/examples/adb/MessageHeader.java", "mask_start_position": 3562, "mask_end_position": 3583, "canonical_solution": "public int getArg1() ", "pre_mask_code": "package org.usb4java.javax.examples.adb;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n/**\n * The header of an ADB message.\n *\n * @author Klaus Reimer (k@ailis.de)\n */\npublic class MessageHeader {\n\n /**\n * Command for SYNC message.\n */\n public static final int CMD_SYNC = 0x434e5953;\n\n /**\n * Command for CONNECT message.\n */\n public static final int CMD_CNXN = 0x4e584e43;\n\n /**\n * Command for AUTH message.\n */\n public static final int CMD_AUTH = 0x48545541;\n\n /**\n * Command for OPEN message.\n */\n public static final int CMD_OPEN = 0x4e45504f;\n\n /**\n * Command for OKAY message.\n */\n public static final int CMD_OKAY = 0x59414b4f;\n\n /**\n * Command for CLOSE message.\n */\n public static final int CMD_CLSE = 0x45534c43;\n\n /**\n * Command for WRITE message.\n */\n public static final int CMD_WRTE = 0x45545257;\n\n /**\n * The ADB message header size in bytes.\n */\n public static final int SIZE = 24;\n\n /**\n * The ADB message command.\n */\n private final int command;\n\n /**\n * First argument.\n */\n private final int arg0;\n\n /**\n * Second argument.\n */\n private final int arg1;\n\n /**\n * Length of payload (0 is allowed).\n */\n private final int dataLength;\n\n /**\n * Checksum of data payload (Sum of all bytes).\n */\n private final int dataChecksum;\n\n /**\n * Inverted command.\n */\n private final int magic;\n\n /**\n * Constructs a new ADB message.\n *\n * @param command\n * The command.\n * @param arg0\n * The first argument.\n * @param arg1\n * The second argument.\n * @param dataLength\n * The data length in bytes.\n * @param dataChecksum\n * The data checksum. According to the documentation this is a\n * CRC32 checksum but in reality it is just the sum of all data\n * bytes.\n * @param magic\n * The inverted command. Can be used for validating the message\n * header.\n */\n public MessageHeader(int command, int arg0, int arg1, int dataLength, int dataChecksum, int magic) {\n this.command = command;\n this.arg0 = arg0;\n this.arg1 = arg1;\n this.dataLength = dataLength;\n this.dataChecksum = dataChecksum;\n this.magic = command ^ 0xffffffff;\n }\n\n /**\n * Constructs a new ADB message header from the specified byte array.\n *\n * @param bytes\n * The ADB message header as bytes.\n */\n public MessageHeader(byte[] bytes) {\n if (bytes.length != SIZE)\n throw new IllegalArgumentException(\"ADB message header must be \" + SIZE + \" bytes large, not \" + bytes.length + \" bytes\");\n ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);\n this.command = buffer.getInt();\n this.arg0 = buffer.getInt();\n this.arg1 = buffer.getInt();\n this.dataLength = buffer.getInt();\n this.dataChecksum = buffer.getInt();\n this.magic = buffer.getInt();\n }\n\n /**\n * Returns the command.\n *\n * @return The command.\n */\n public int getCommand() {\n return this.command;\n }\n\n /**\n * Returns the first argument.\n *\n * @return The first argument.\n */\n public int getArg0() {\n return this.arg0;\n }\n\n /**\n * Returns the second argument.\n *\n * @return The second argument.\n */\n ", "post_mask_code": "{\n return this.arg1;\n }\n\n /**\n * Returns the data checksum.\n *\n * @return The data checksum.\n */\n public int getDataChecksum() {\n return this.dataChecksum;\n }\n\n /**\n * Returns the data length.\n *\n * @return The data length.\n */\n public int getDataLength() {\n return this.dataLength;\n }\n\n /**\n * Returns the inverted command.\n *\n * @return The inverted command.\n */\n public int getMagic() {\n return this.magic;\n }\n\n /**\n * Check if this message header is valid. This simply checks if the header\n * magic value is the inverted value of the command value.\n *\n * @return True if message header is valid, false if not.\n */\n public boolean isValid() {\n return this.magic == (this.command ^ 0xffffffff);\n }\n\n /**\n * Returns the message header as a byte array.\n *\n * @return The message header as a byte array.\n */\n public byte[] getBytes() {\n ByteBuffer buffer = ByteBuffer.allocate(SIZE);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(this.command);\n buffer.putInt(this.arg0);\n buffer.putInt(this.arg1);\n buffer.putInt(this.dataLength);\n buffer.putInt(this.dataChecksum);\n buffer.putInt(this.magic);\n return buffer.array();\n }\n}\n"} {"task_id": "Java_351", "language": "Java", "task_type": "method_body", "source_file": "java/github/usb4java/usb4java-javax-examples/src/main/java/org/usb4java/javax/examples/adb/MessageHeader.java", "mask_start_position": 3903, "mask_end_position": 3942, "canonical_solution": "{\n return this.dataLength;\n }", "pre_mask_code": "package org.usb4java.javax.examples.adb;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n/**\n * The header of an ADB message.\n *\n * @author Klaus Reimer (k@ailis.de)\n */\npublic class MessageHeader {\n\n /**\n * Command for SYNC message.\n */\n public static final int CMD_SYNC = 0x434e5953;\n\n /**\n * Command for CONNECT message.\n */\n public static final int CMD_CNXN = 0x4e584e43;\n\n /**\n * Command for AUTH message.\n */\n public static final int CMD_AUTH = 0x48545541;\n\n /**\n * Command for OPEN message.\n */\n public static final int CMD_OPEN = 0x4e45504f;\n\n /**\n * Command for OKAY message.\n */\n public static final int CMD_OKAY = 0x59414b4f;\n\n /**\n * Command for CLOSE message.\n */\n public static final int CMD_CLSE = 0x45534c43;\n\n /**\n * Command for WRITE message.\n */\n public static final int CMD_WRTE = 0x45545257;\n\n /**\n * The ADB message header size in bytes.\n */\n public static final int SIZE = 24;\n\n /**\n * The ADB message command.\n */\n private final int command;\n\n /**\n * First argument.\n */\n private final int arg0;\n\n /**\n * Second argument.\n */\n private final int arg1;\n\n /**\n * Length of payload (0 is allowed).\n */\n private final int dataLength;\n\n /**\n * Checksum of data payload (Sum of all bytes).\n */\n private final int dataChecksum;\n\n /**\n * Inverted command.\n */\n private final int magic;\n\n /**\n * Constructs a new ADB message.\n *\n * @param command\n * The command.\n * @param arg0\n * The first argument.\n * @param arg1\n * The second argument.\n * @param dataLength\n * The data length in bytes.\n * @param dataChecksum\n * The data checksum. According to the documentation this is a\n * CRC32 checksum but in reality it is just the sum of all data\n * bytes.\n * @param magic\n * The inverted command. Can be used for validating the message\n * header.\n */\n public MessageHeader(int command, int arg0, int arg1, int dataLength, int dataChecksum, int magic) {\n this.command = command;\n this.arg0 = arg0;\n this.arg1 = arg1;\n this.dataLength = dataLength;\n this.dataChecksum = dataChecksum;\n this.magic = command ^ 0xffffffff;\n }\n\n /**\n * Constructs a new ADB message header from the specified byte array.\n *\n * @param bytes\n * The ADB message header as bytes.\n */\n public MessageHeader(byte[] bytes) {\n if (bytes.length != SIZE)\n throw new IllegalArgumentException(\"ADB message header must be \" + SIZE + \" bytes large, not \" + bytes.length + \" bytes\");\n ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);\n this.command = buffer.getInt();\n this.arg0 = buffer.getInt();\n this.arg1 = buffer.getInt();\n this.dataLength = buffer.getInt();\n this.dataChecksum = buffer.getInt();\n this.magic = buffer.getInt();\n }\n\n /**\n * Returns the command.\n *\n * @return The command.\n */\n public int getCommand() {\n return this.command;\n }\n\n /**\n * Returns the first argument.\n *\n * @return The first argument.\n */\n public int getArg0() {\n return this.arg0;\n }\n\n /**\n * Returns the second argument.\n *\n * @return The second argument.\n */\n public int getArg1() {\n return this.arg1;\n }\n\n /**\n * Returns the data checksum.\n *\n * @return The data checksum.\n */\n public int getDataChecksum() {\n return this.dataChecksum;\n }\n\n /**\n * Returns the data length.\n *\n * @return The data length.\n */\n public int getDataLength() ", "post_mask_code": "\n\n /**\n * Returns the inverted command.\n *\n * @return The inverted command.\n */\n public int getMagic() {\n return this.magic;\n }\n\n /**\n * Check if this message header is valid. This simply checks if the header\n * magic value is the inverted value of the command value.\n *\n * @return True if message header is valid, false if not.\n */\n public boolean isValid() {\n return this.magic == (this.command ^ 0xffffffff);\n }\n\n /**\n * Returns the message header as a byte array.\n *\n * @return The message header as a byte array.\n */\n public byte[] getBytes() {\n ByteBuffer buffer = ByteBuffer.allocate(SIZE);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(this.command);\n buffer.putInt(this.arg0);\n buffer.putInt(this.arg1);\n buffer.putInt(this.dataLength);\n buffer.putInt(this.dataChecksum);\n buffer.putInt(this.magic);\n return buffer.array();\n }\n}\n"} {"task_id": "Java_352", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/usb4java/usb4java-javax-examples/src/main/java/org/usb4java/javax/examples/adb/MessageHeader.java", "mask_start_position": 4581, "mask_end_position": 4720, "canonical_solution": "\n ByteBuffer buffer = ByteBuffer.allocate(SIZE);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(this.command);", "pre_mask_code": "package org.usb4java.javax.examples.adb;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n/**\n * The header of an ADB message.\n *\n * @author Klaus Reimer (k@ailis.de)\n */\npublic class MessageHeader {\n\n /**\n * Command for SYNC message.\n */\n public static final int CMD_SYNC = 0x434e5953;\n\n /**\n * Command for CONNECT message.\n */\n public static final int CMD_CNXN = 0x4e584e43;\n\n /**\n * Command for AUTH message.\n */\n public static final int CMD_AUTH = 0x48545541;\n\n /**\n * Command for OPEN message.\n */\n public static final int CMD_OPEN = 0x4e45504f;\n\n /**\n * Command for OKAY message.\n */\n public static final int CMD_OKAY = 0x59414b4f;\n\n /**\n * Command for CLOSE message.\n */\n public static final int CMD_CLSE = 0x45534c43;\n\n /**\n * Command for WRITE message.\n */\n public static final int CMD_WRTE = 0x45545257;\n\n /**\n * The ADB message header size in bytes.\n */\n public static final int SIZE = 24;\n\n /**\n * The ADB message command.\n */\n private final int command;\n\n /**\n * First argument.\n */\n private final int arg0;\n\n /**\n * Second argument.\n */\n private final int arg1;\n\n /**\n * Length of payload (0 is allowed).\n */\n private final int dataLength;\n\n /**\n * Checksum of data payload (Sum of all bytes).\n */\n private final int dataChecksum;\n\n /**\n * Inverted command.\n */\n private final int magic;\n\n /**\n * Constructs a new ADB message.\n *\n * @param command\n * The command.\n * @param arg0\n * The first argument.\n * @param arg1\n * The second argument.\n * @param dataLength\n * The data length in bytes.\n * @param dataChecksum\n * The data checksum. According to the documentation this is a\n * CRC32 checksum but in reality it is just the sum of all data\n * bytes.\n * @param magic\n * The inverted command. Can be used for validating the message\n * header.\n */\n public MessageHeader(int command, int arg0, int arg1, int dataLength, int dataChecksum, int magic) {\n this.command = command;\n this.arg0 = arg0;\n this.arg1 = arg1;\n this.dataLength = dataLength;\n this.dataChecksum = dataChecksum;\n this.magic = command ^ 0xffffffff;\n }\n\n /**\n * Constructs a new ADB message header from the specified byte array.\n *\n * @param bytes\n * The ADB message header as bytes.\n */\n public MessageHeader(byte[] bytes) {\n if (bytes.length != SIZE)\n throw new IllegalArgumentException(\"ADB message header must be \" + SIZE + \" bytes large, not \" + bytes.length + \" bytes\");\n ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);\n this.command = buffer.getInt();\n this.arg0 = buffer.getInt();\n this.arg1 = buffer.getInt();\n this.dataLength = buffer.getInt();\n this.dataChecksum = buffer.getInt();\n this.magic = buffer.getInt();\n }\n\n /**\n * Returns the command.\n *\n * @return The command.\n */\n public int getCommand() {\n return this.command;\n }\n\n /**\n * Returns the first argument.\n *\n * @return The first argument.\n */\n public int getArg0() {\n return this.arg0;\n }\n\n /**\n * Returns the second argument.\n *\n * @return The second argument.\n */\n public int getArg1() {\n return this.arg1;\n }\n\n /**\n * Returns the data checksum.\n *\n * @return The data checksum.\n */\n public int getDataChecksum() {\n return this.dataChecksum;\n }\n\n /**\n * Returns the data length.\n *\n * @return The data length.\n */\n public int getDataLength() {\n return this.dataLength;\n }\n\n /**\n * Returns the inverted command.\n *\n * @return The inverted command.\n */\n public int getMagic() {\n return this.magic;\n }\n\n /**\n * Check if this message header is valid. This simply checks if the header\n * magic value is the inverted value of the command value.\n *\n * @return True if message header is valid, false if not.\n */\n public boolean isValid() {\n return this.magic == (this.command ^ 0xffffffff);\n }\n\n /**\n * Returns the message header as a byte array.\n *\n * @return The message header as a byte array.\n */\n public byte[] getBytes() {", "post_mask_code": "\n buffer.putInt(this.arg0);\n buffer.putInt(this.arg1);\n buffer.putInt(this.dataLength);\n buffer.putInt(this.dataChecksum);\n buffer.putInt(this.magic);\n return buffer.array();\n }\n}\n"} {"task_id": "Java_353", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/usb4java/usb4java-javax-examples/src/main/java/org/usb4java/javax/examples/adb/MessageHeader.java", "mask_start_position": 4729, "mask_end_position": 4828, "canonical_solution": "buffer.putInt(this.arg0);\n buffer.putInt(this.arg1);\n buffer.putInt(this.dataLength);", "pre_mask_code": "package org.usb4java.javax.examples.adb;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n/**\n * The header of an ADB message.\n *\n * @author Klaus Reimer (k@ailis.de)\n */\npublic class MessageHeader {\n\n /**\n * Command for SYNC message.\n */\n public static final int CMD_SYNC = 0x434e5953;\n\n /**\n * Command for CONNECT message.\n */\n public static final int CMD_CNXN = 0x4e584e43;\n\n /**\n * Command for AUTH message.\n */\n public static final int CMD_AUTH = 0x48545541;\n\n /**\n * Command for OPEN message.\n */\n public static final int CMD_OPEN = 0x4e45504f;\n\n /**\n * Command for OKAY message.\n */\n public static final int CMD_OKAY = 0x59414b4f;\n\n /**\n * Command for CLOSE message.\n */\n public static final int CMD_CLSE = 0x45534c43;\n\n /**\n * Command for WRITE message.\n */\n public static final int CMD_WRTE = 0x45545257;\n\n /**\n * The ADB message header size in bytes.\n */\n public static final int SIZE = 24;\n\n /**\n * The ADB message command.\n */\n private final int command;\n\n /**\n * First argument.\n */\n private final int arg0;\n\n /**\n * Second argument.\n */\n private final int arg1;\n\n /**\n * Length of payload (0 is allowed).\n */\n private final int dataLength;\n\n /**\n * Checksum of data payload (Sum of all bytes).\n */\n private final int dataChecksum;\n\n /**\n * Inverted command.\n */\n private final int magic;\n\n /**\n * Constructs a new ADB message.\n *\n * @param command\n * The command.\n * @param arg0\n * The first argument.\n * @param arg1\n * The second argument.\n * @param dataLength\n * The data length in bytes.\n * @param dataChecksum\n * The data checksum. According to the documentation this is a\n * CRC32 checksum but in reality it is just the sum of all data\n * bytes.\n * @param magic\n * The inverted command. Can be used for validating the message\n * header.\n */\n public MessageHeader(int command, int arg0, int arg1, int dataLength, int dataChecksum, int magic) {\n this.command = command;\n this.arg0 = arg0;\n this.arg1 = arg1;\n this.dataLength = dataLength;\n this.dataChecksum = dataChecksum;\n this.magic = command ^ 0xffffffff;\n }\n\n /**\n * Constructs a new ADB message header from the specified byte array.\n *\n * @param bytes\n * The ADB message header as bytes.\n */\n public MessageHeader(byte[] bytes) {\n if (bytes.length != SIZE)\n throw new IllegalArgumentException(\"ADB message header must be \" + SIZE + \" bytes large, not \" + bytes.length + \" bytes\");\n ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);\n this.command = buffer.getInt();\n this.arg0 = buffer.getInt();\n this.arg1 = buffer.getInt();\n this.dataLength = buffer.getInt();\n this.dataChecksum = buffer.getInt();\n this.magic = buffer.getInt();\n }\n\n /**\n * Returns the command.\n *\n * @return The command.\n */\n public int getCommand() {\n return this.command;\n }\n\n /**\n * Returns the first argument.\n *\n * @return The first argument.\n */\n public int getArg0() {\n return this.arg0;\n }\n\n /**\n * Returns the second argument.\n *\n * @return The second argument.\n */\n public int getArg1() {\n return this.arg1;\n }\n\n /**\n * Returns the data checksum.\n *\n * @return The data checksum.\n */\n public int getDataChecksum() {\n return this.dataChecksum;\n }\n\n /**\n * Returns the data length.\n *\n * @return The data length.\n */\n public int getDataLength() {\n return this.dataLength;\n }\n\n /**\n * Returns the inverted command.\n *\n * @return The inverted command.\n */\n public int getMagic() {\n return this.magic;\n }\n\n /**\n * Check if this message header is valid. This simply checks if the header\n * magic value is the inverted value of the command value.\n *\n * @return True if message header is valid, false if not.\n */\n public boolean isValid() {\n return this.magic == (this.command ^ 0xffffffff);\n }\n\n /**\n * Returns the message header as a byte array.\n *\n * @return The message header as a byte array.\n */\n public byte[] getBytes() {\n ByteBuffer buffer = ByteBuffer.allocate(SIZE);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(this.command);\n ", "post_mask_code": "\n buffer.putInt(this.dataChecksum);\n buffer.putInt(this.magic);\n return buffer.array();\n }\n}\n"} {"task_id": "Java_354", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/usb4java/usb4java-javax-examples/src/main/java/org/usb4java/javax/examples/adb/MessageHeader.java", "mask_start_position": 4837, "mask_end_position": 4942, "canonical_solution": "buffer.putInt(this.dataChecksum);\n buffer.putInt(this.magic);\n return buffer.array();\n }", "pre_mask_code": "package org.usb4java.javax.examples.adb;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n/**\n * The header of an ADB message.\n *\n * @author Klaus Reimer (k@ailis.de)\n */\npublic class MessageHeader {\n\n /**\n * Command for SYNC message.\n */\n public static final int CMD_SYNC = 0x434e5953;\n\n /**\n * Command for CONNECT message.\n */\n public static final int CMD_CNXN = 0x4e584e43;\n\n /**\n * Command for AUTH message.\n */\n public static final int CMD_AUTH = 0x48545541;\n\n /**\n * Command for OPEN message.\n */\n public static final int CMD_OPEN = 0x4e45504f;\n\n /**\n * Command for OKAY message.\n */\n public static final int CMD_OKAY = 0x59414b4f;\n\n /**\n * Command for CLOSE message.\n */\n public static final int CMD_CLSE = 0x45534c43;\n\n /**\n * Command for WRITE message.\n */\n public static final int CMD_WRTE = 0x45545257;\n\n /**\n * The ADB message header size in bytes.\n */\n public static final int SIZE = 24;\n\n /**\n * The ADB message command.\n */\n private final int command;\n\n /**\n * First argument.\n */\n private final int arg0;\n\n /**\n * Second argument.\n */\n private final int arg1;\n\n /**\n * Length of payload (0 is allowed).\n */\n private final int dataLength;\n\n /**\n * Checksum of data payload (Sum of all bytes).\n */\n private final int dataChecksum;\n\n /**\n * Inverted command.\n */\n private final int magic;\n\n /**\n * Constructs a new ADB message.\n *\n * @param command\n * The command.\n * @param arg0\n * The first argument.\n * @param arg1\n * The second argument.\n * @param dataLength\n * The data length in bytes.\n * @param dataChecksum\n * The data checksum. According to the documentation this is a\n * CRC32 checksum but in reality it is just the sum of all data\n * bytes.\n * @param magic\n * The inverted command. Can be used for validating the message\n * header.\n */\n public MessageHeader(int command, int arg0, int arg1, int dataLength, int dataChecksum, int magic) {\n this.command = command;\n this.arg0 = arg0;\n this.arg1 = arg1;\n this.dataLength = dataLength;\n this.dataChecksum = dataChecksum;\n this.magic = command ^ 0xffffffff;\n }\n\n /**\n * Constructs a new ADB message header from the specified byte array.\n *\n * @param bytes\n * The ADB message header as bytes.\n */\n public MessageHeader(byte[] bytes) {\n if (bytes.length != SIZE)\n throw new IllegalArgumentException(\"ADB message header must be \" + SIZE + \" bytes large, not \" + bytes.length + \" bytes\");\n ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);\n this.command = buffer.getInt();\n this.arg0 = buffer.getInt();\n this.arg1 = buffer.getInt();\n this.dataLength = buffer.getInt();\n this.dataChecksum = buffer.getInt();\n this.magic = buffer.getInt();\n }\n\n /**\n * Returns the command.\n *\n * @return The command.\n */\n public int getCommand() {\n return this.command;\n }\n\n /**\n * Returns the first argument.\n *\n * @return The first argument.\n */\n public int getArg0() {\n return this.arg0;\n }\n\n /**\n * Returns the second argument.\n *\n * @return The second argument.\n */\n public int getArg1() {\n return this.arg1;\n }\n\n /**\n * Returns the data checksum.\n *\n * @return The data checksum.\n */\n public int getDataChecksum() {\n return this.dataChecksum;\n }\n\n /**\n * Returns the data length.\n *\n * @return The data length.\n */\n public int getDataLength() {\n return this.dataLength;\n }\n\n /**\n * Returns the inverted command.\n *\n * @return The inverted command.\n */\n public int getMagic() {\n return this.magic;\n }\n\n /**\n * Check if this message header is valid. This simply checks if the header\n * magic value is the inverted value of the command value.\n *\n * @return True if message header is valid, false if not.\n */\n public boolean isValid() {\n return this.magic == (this.command ^ 0xffffffff);\n }\n\n /**\n * Returns the message header as a byte array.\n *\n * @return The message header as a byte array.\n */\n public byte[] getBytes() {\n ByteBuffer buffer = ByteBuffer.allocate(SIZE);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(this.command);\n buffer.putInt(this.arg0);\n buffer.putInt(this.arg1);\n buffer.putInt(this.dataLength);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_355", "language": "Java", "task_type": "single_line", "source_file": "java/github/usb4java/usb4java-javax-examples/src/main/java/org/usb4java/javax/examples/adb/MessageHeader.java", "mask_start_position": 4718, "mask_end_position": 4720, "canonical_solution": ");", "pre_mask_code": "package org.usb4java.javax.examples.adb;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n/**\n * The header of an ADB message.\n *\n * @author Klaus Reimer (k@ailis.de)\n */\npublic class MessageHeader {\n\n /**\n * Command for SYNC message.\n */\n public static final int CMD_SYNC = 0x434e5953;\n\n /**\n * Command for CONNECT message.\n */\n public static final int CMD_CNXN = 0x4e584e43;\n\n /**\n * Command for AUTH message.\n */\n public static final int CMD_AUTH = 0x48545541;\n\n /**\n * Command for OPEN message.\n */\n public static final int CMD_OPEN = 0x4e45504f;\n\n /**\n * Command for OKAY message.\n */\n public static final int CMD_OKAY = 0x59414b4f;\n\n /**\n * Command for CLOSE message.\n */\n public static final int CMD_CLSE = 0x45534c43;\n\n /**\n * Command for WRITE message.\n */\n public static final int CMD_WRTE = 0x45545257;\n\n /**\n * The ADB message header size in bytes.\n */\n public static final int SIZE = 24;\n\n /**\n * The ADB message command.\n */\n private final int command;\n\n /**\n * First argument.\n */\n private final int arg0;\n\n /**\n * Second argument.\n */\n private final int arg1;\n\n /**\n * Length of payload (0 is allowed).\n */\n private final int dataLength;\n\n /**\n * Checksum of data payload (Sum of all bytes).\n */\n private final int dataChecksum;\n\n /**\n * Inverted command.\n */\n private final int magic;\n\n /**\n * Constructs a new ADB message.\n *\n * @param command\n * The command.\n * @param arg0\n * The first argument.\n * @param arg1\n * The second argument.\n * @param dataLength\n * The data length in bytes.\n * @param dataChecksum\n * The data checksum. According to the documentation this is a\n * CRC32 checksum but in reality it is just the sum of all data\n * bytes.\n * @param magic\n * The inverted command. Can be used for validating the message\n * header.\n */\n public MessageHeader(int command, int arg0, int arg1, int dataLength, int dataChecksum, int magic) {\n this.command = command;\n this.arg0 = arg0;\n this.arg1 = arg1;\n this.dataLength = dataLength;\n this.dataChecksum = dataChecksum;\n this.magic = command ^ 0xffffffff;\n }\n\n /**\n * Constructs a new ADB message header from the specified byte array.\n *\n * @param bytes\n * The ADB message header as bytes.\n */\n public MessageHeader(byte[] bytes) {\n if (bytes.length != SIZE)\n throw new IllegalArgumentException(\"ADB message header must be \" + SIZE + \" bytes large, not \" + bytes.length + \" bytes\");\n ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);\n this.command = buffer.getInt();\n this.arg0 = buffer.getInt();\n this.arg1 = buffer.getInt();\n this.dataLength = buffer.getInt();\n this.dataChecksum = buffer.getInt();\n this.magic = buffer.getInt();\n }\n\n /**\n * Returns the command.\n *\n * @return The command.\n */\n public int getCommand() {\n return this.command;\n }\n\n /**\n * Returns the first argument.\n *\n * @return The first argument.\n */\n public int getArg0() {\n return this.arg0;\n }\n\n /**\n * Returns the second argument.\n *\n * @return The second argument.\n */\n public int getArg1() {\n return this.arg1;\n }\n\n /**\n * Returns the data checksum.\n *\n * @return The data checksum.\n */\n public int getDataChecksum() {\n return this.dataChecksum;\n }\n\n /**\n * Returns the data length.\n *\n * @return The data length.\n */\n public int getDataLength() {\n return this.dataLength;\n }\n\n /**\n * Returns the inverted command.\n *\n * @return The inverted command.\n */\n public int getMagic() {\n return this.magic;\n }\n\n /**\n * Check if this message header is valid. This simply checks if the header\n * magic value is the inverted value of the command value.\n *\n * @return True if message header is valid, false if not.\n */\n public boolean isValid() {\n return this.magic == (this.command ^ 0xffffffff);\n }\n\n /**\n * Returns the message header as a byte array.\n *\n * @return The message header as a byte array.\n */\n public byte[] getBytes() {\n ByteBuffer buffer = ByteBuffer.allocate(SIZE);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(this.command", "post_mask_code": "\n buffer.putInt(this.arg0);\n buffer.putInt(this.arg1);\n buffer.putInt(this.dataLength);\n buffer.putInt(this.dataChecksum);\n buffer.putInt(this.magic);\n return buffer.array();\n }\n}\n"} {"task_id": "Java_356", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/usb4java/usb4java-javax-examples/src/main/java/org/usb4java/javax/examples/adb/MessageHeader.java", "mask_start_position": 3562, "mask_end_position": 3616, "canonical_solution": "public int getArg1() {\n return this.arg1;\n }", "pre_mask_code": "package org.usb4java.javax.examples.adb;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n/**\n * The header of an ADB message.\n *\n * @author Klaus Reimer (k@ailis.de)\n */\npublic class MessageHeader {\n\n /**\n * Command for SYNC message.\n */\n public static final int CMD_SYNC = 0x434e5953;\n\n /**\n * Command for CONNECT message.\n */\n public static final int CMD_CNXN = 0x4e584e43;\n\n /**\n * Command for AUTH message.\n */\n public static final int CMD_AUTH = 0x48545541;\n\n /**\n * Command for OPEN message.\n */\n public static final int CMD_OPEN = 0x4e45504f;\n\n /**\n * Command for OKAY message.\n */\n public static final int CMD_OKAY = 0x59414b4f;\n\n /**\n * Command for CLOSE message.\n */\n public static final int CMD_CLSE = 0x45534c43;\n\n /**\n * Command for WRITE message.\n */\n public static final int CMD_WRTE = 0x45545257;\n\n /**\n * The ADB message header size in bytes.\n */\n public static final int SIZE = 24;\n\n /**\n * The ADB message command.\n */\n private final int command;\n\n /**\n * First argument.\n */\n private final int arg0;\n\n /**\n * Second argument.\n */\n private final int arg1;\n\n /**\n * Length of payload (0 is allowed).\n */\n private final int dataLength;\n\n /**\n * Checksum of data payload (Sum of all bytes).\n */\n private final int dataChecksum;\n\n /**\n * Inverted command.\n */\n private final int magic;\n\n /**\n * Constructs a new ADB message.\n *\n * @param command\n * The command.\n * @param arg0\n * The first argument.\n * @param arg1\n * The second argument.\n * @param dataLength\n * The data length in bytes.\n * @param dataChecksum\n * The data checksum. According to the documentation this is a\n * CRC32 checksum but in reality it is just the sum of all data\n * bytes.\n * @param magic\n * The inverted command. Can be used for validating the message\n * header.\n */\n public MessageHeader(int command, int arg0, int arg1, int dataLength, int dataChecksum, int magic) {\n this.command = command;\n this.arg0 = arg0;\n this.arg1 = arg1;\n this.dataLength = dataLength;\n this.dataChecksum = dataChecksum;\n this.magic = command ^ 0xffffffff;\n }\n\n /**\n * Constructs a new ADB message header from the specified byte array.\n *\n * @param bytes\n * The ADB message header as bytes.\n */\n public MessageHeader(byte[] bytes) {\n if (bytes.length != SIZE)\n throw new IllegalArgumentException(\"ADB message header must be \" + SIZE + \" bytes large, not \" + bytes.length + \" bytes\");\n ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);\n this.command = buffer.getInt();\n this.arg0 = buffer.getInt();\n this.arg1 = buffer.getInt();\n this.dataLength = buffer.getInt();\n this.dataChecksum = buffer.getInt();\n this.magic = buffer.getInt();\n }\n\n /**\n * Returns the command.\n *\n * @return The command.\n */\n public int getCommand() {\n return this.command;\n }\n\n /**\n * Returns the first argument.\n *\n * @return The first argument.\n */\n public int getArg0() {\n return this.arg0;\n }\n\n /**\n * Returns the second argument.\n *\n * @return The second argument.\n */\n ", "post_mask_code": "\n\n /**\n * Returns the data checksum.\n *\n * @return The data checksum.\n */\n public int getDataChecksum() {\n return this.dataChecksum;\n }\n\n /**\n * Returns the data length.\n *\n * @return The data length.\n */\n public int getDataLength() {\n return this.dataLength;\n }\n\n /**\n * Returns the inverted command.\n *\n * @return The inverted command.\n */\n public int getMagic() {\n return this.magic;\n }\n\n /**\n * Check if this message header is valid. This simply checks if the header\n * magic value is the inverted value of the command value.\n *\n * @return True if message header is valid, false if not.\n */\n public boolean isValid() {\n return this.magic == (this.command ^ 0xffffffff);\n }\n\n /**\n * Returns the message header as a byte array.\n *\n * @return The message header as a byte array.\n */\n public byte[] getBytes() {\n ByteBuffer buffer = ByteBuffer.allocate(SIZE);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(this.command);\n buffer.putInt(this.arg0);\n buffer.putInt(this.arg1);\n buffer.putInt(this.dataLength);\n buffer.putInt(this.dataChecksum);\n buffer.putInt(this.magic);\n return buffer.array();\n }\n}\n"} {"task_id": "Java_357", "language": "Java", "task_type": "if_statement", "source_file": "java/github/usb4java/usb4java-javax-examples/src/main/java/org/usb4java/javax/examples/adb/MessageHeader.java", "mask_start_position": 2674, "mask_end_position": 2834, "canonical_solution": "if (bytes.length != SIZE)\n throw new IllegalArgumentException(\"ADB message header must be \" + SIZE + \" bytes large, not \" + bytes.length + \" bytes\");", "pre_mask_code": "package org.usb4java.javax.examples.adb;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n/**\n * The header of an ADB message.\n *\n * @author Klaus Reimer (k@ailis.de)\n */\npublic class MessageHeader {\n\n /**\n * Command for SYNC message.\n */\n public static final int CMD_SYNC = 0x434e5953;\n\n /**\n * Command for CONNECT message.\n */\n public static final int CMD_CNXN = 0x4e584e43;\n\n /**\n * Command for AUTH message.\n */\n public static final int CMD_AUTH = 0x48545541;\n\n /**\n * Command for OPEN message.\n */\n public static final int CMD_OPEN = 0x4e45504f;\n\n /**\n * Command for OKAY message.\n */\n public static final int CMD_OKAY = 0x59414b4f;\n\n /**\n * Command for CLOSE message.\n */\n public static final int CMD_CLSE = 0x45534c43;\n\n /**\n * Command for WRITE message.\n */\n public static final int CMD_WRTE = 0x45545257;\n\n /**\n * The ADB message header size in bytes.\n */\n public static final int SIZE = 24;\n\n /**\n * The ADB message command.\n */\n private final int command;\n\n /**\n * First argument.\n */\n private final int arg0;\n\n /**\n * Second argument.\n */\n private final int arg1;\n\n /**\n * Length of payload (0 is allowed).\n */\n private final int dataLength;\n\n /**\n * Checksum of data payload (Sum of all bytes).\n */\n private final int dataChecksum;\n\n /**\n * Inverted command.\n */\n private final int magic;\n\n /**\n * Constructs a new ADB message.\n *\n * @param command\n * The command.\n * @param arg0\n * The first argument.\n * @param arg1\n * The second argument.\n * @param dataLength\n * The data length in bytes.\n * @param dataChecksum\n * The data checksum. According to the documentation this is a\n * CRC32 checksum but in reality it is just the sum of all data\n * bytes.\n * @param magic\n * The inverted command. Can be used for validating the message\n * header.\n */\n public MessageHeader(int command, int arg0, int arg1, int dataLength, int dataChecksum, int magic) {\n this.command = command;\n this.arg0 = arg0;\n this.arg1 = arg1;\n this.dataLength = dataLength;\n this.dataChecksum = dataChecksum;\n this.magic = command ^ 0xffffffff;\n }\n\n /**\n * Constructs a new ADB message header from the specified byte array.\n *\n * @param bytes\n * The ADB message header as bytes.\n */\n public MessageHeader(byte[] bytes) {\n ", "post_mask_code": "\n ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);\n this.command = buffer.getInt();\n this.arg0 = buffer.getInt();\n this.arg1 = buffer.getInt();\n this.dataLength = buffer.getInt();\n this.dataChecksum = buffer.getInt();\n this.magic = buffer.getInt();\n }\n\n /**\n * Returns the command.\n *\n * @return The command.\n */\n public int getCommand() {\n return this.command;\n }\n\n /**\n * Returns the first argument.\n *\n * @return The first argument.\n */\n public int getArg0() {\n return this.arg0;\n }\n\n /**\n * Returns the second argument.\n *\n * @return The second argument.\n */\n public int getArg1() {\n return this.arg1;\n }\n\n /**\n * Returns the data checksum.\n *\n * @return The data checksum.\n */\n public int getDataChecksum() {\n return this.dataChecksum;\n }\n\n /**\n * Returns the data length.\n *\n * @return The data length.\n */\n public int getDataLength() {\n return this.dataLength;\n }\n\n /**\n * Returns the inverted command.\n *\n * @return The inverted command.\n */\n public int getMagic() {\n return this.magic;\n }\n\n /**\n * Check if this message header is valid. This simply checks if the header\n * magic value is the inverted value of the command value.\n *\n * @return True if message header is valid, false if not.\n */\n public boolean isValid() {\n return this.magic == (this.command ^ 0xffffffff);\n }\n\n /**\n * Returns the message header as a byte array.\n *\n * @return The message header as a byte array.\n */\n public byte[] getBytes() {\n ByteBuffer buffer = ByteBuffer.allocate(SIZE);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(this.command);\n buffer.putInt(this.arg0);\n buffer.putInt(this.arg1);\n buffer.putInt(this.dataLength);\n buffer.putInt(this.dataChecksum);\n buffer.putInt(this.magic);\n return buffer.array();\n }\n}\n"} {"task_id": "Java_358", "language": "Java", "task_type": "empty", "source_file": "java/github/usb4java/usb4java-javax-examples/src/main/java/org/usb4java/javax/examples/adb/MessageHeader.java", "mask_start_position": 345, "mask_end_position": 345, "canonical_solution": "", "pre_mask_code": "package org.usb4java.javax.examples.adb;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n/**\n * The header of an ADB message.\n *\n * @author Klaus Reimer (k@ailis.de)\n */\npublic class MessageHeader {\n\n /**\n * Command for SYNC message.\n */\n public static final int CMD_SYNC = 0x434e5953;\n\n /**\n * Command for CONNECT ", "post_mask_code": "message.\n */\n public static final int CMD_CNXN = 0x4e584e43;\n\n /**\n * Command for AUTH message.\n */\n public static final int CMD_AUTH = 0x48545541;\n\n /**\n * Command for OPEN message.\n */\n public static final int CMD_OPEN = 0x4e45504f;\n\n /**\n * Command for OKAY message.\n */\n public static final int CMD_OKAY = 0x59414b4f;\n\n /**\n * Command for CLOSE message.\n */\n public static final int CMD_CLSE = 0x45534c43;\n\n /**\n * Command for WRITE message.\n */\n public static final int CMD_WRTE = 0x45545257;\n\n /**\n * The ADB message header size in bytes.\n */\n public static final int SIZE = 24;\n\n /**\n * The ADB message command.\n */\n private final int command;\n\n /**\n * First argument.\n */\n private final int arg0;\n\n /**\n * Second argument.\n */\n private final int arg1;\n\n /**\n * Length of payload (0 is allowed).\n */\n private final int dataLength;\n\n /**\n * Checksum of data payload (Sum of all bytes).\n */\n private final int dataChecksum;\n\n /**\n * Inverted command.\n */\n private final int magic;\n\n /**\n * Constructs a new ADB message.\n *\n * @param command\n * The command.\n * @param arg0\n * The first argument.\n * @param arg1\n * The second argument.\n * @param dataLength\n * The data length in bytes.\n * @param dataChecksum\n * The data checksum. According to the documentation this is a\n * CRC32 checksum but in reality it is just the sum of all data\n * bytes.\n * @param magic\n * The inverted command. Can be used for validating the message\n * header.\n */\n public MessageHeader(int command, int arg0, int arg1, int dataLength, int dataChecksum, int magic) {\n this.command = command;\n this.arg0 = arg0;\n this.arg1 = arg1;\n this.dataLength = dataLength;\n this.dataChecksum = dataChecksum;\n this.magic = command ^ 0xffffffff;\n }\n\n /**\n * Constructs a new ADB message header from the specified byte array.\n *\n * @param bytes\n * The ADB message header as bytes.\n */\n public MessageHeader(byte[] bytes) {\n if (bytes.length != SIZE)\n throw new IllegalArgumentException(\"ADB message header must be \" + SIZE + \" bytes large, not \" + bytes.length + \" bytes\");\n ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);\n this.command = buffer.getInt();\n this.arg0 = buffer.getInt();\n this.arg1 = buffer.getInt();\n this.dataLength = buffer.getInt();\n this.dataChecksum = buffer.getInt();\n this.magic = buffer.getInt();\n }\n\n /**\n * Returns the command.\n *\n * @return The command.\n */\n public int getCommand() {\n return this.command;\n }\n\n /**\n * Returns the first argument.\n *\n * @return The first argument.\n */\n public int getArg0() {\n return this.arg0;\n }\n\n /**\n * Returns the second argument.\n *\n * @return The second argument.\n */\n public int getArg1() {\n return this.arg1;\n }\n\n /**\n * Returns the data checksum.\n *\n * @return The data checksum.\n */\n public int getDataChecksum() {\n return this.dataChecksum;\n }\n\n /**\n * Returns the data length.\n *\n * @return The data length.\n */\n public int getDataLength() {\n return this.dataLength;\n }\n\n /**\n * Returns the inverted command.\n *\n * @return The inverted command.\n */\n public int getMagic() {\n return this.magic;\n }\n\n /**\n * Check if this message header is valid. This simply checks if the header\n * magic value is the inverted value of the command value.\n *\n * @return True if message header is valid, false if not.\n */\n public boolean isValid() {\n return this.magic == (this.command ^ 0xffffffff);\n }\n\n /**\n * Returns the message header as a byte array.\n *\n * @return The message header as a byte array.\n */\n public byte[] getBytes() {\n ByteBuffer buffer = ByteBuffer.allocate(SIZE);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(this.command);\n buffer.putInt(this.arg0);\n buffer.putInt(this.arg1);\n buffer.putInt(this.dataLength);\n buffer.putInt(this.dataChecksum);\n buffer.putInt(this.magic);\n return buffer.array();\n }\n}\n"} {"task_id": "Java_359", "language": "Java", "task_type": "method_signature", "source_file": "java/github/bcgit/bc-java/prov/src/main/java/org/bouncycastle/jce/spec/GOST3410PublicKeySpec.java", "mask_start_position": 1096, "mask_end_position": 1121, "canonical_solution": "public BigInteger getQ() ", "pre_mask_code": "package org.bouncycastle.jce.spec;\n\nimport java.math.BigInteger;\nimport java.security.spec.KeySpec;\n\n/**\n * This class specifies a GOST3410-94 public key with its associated parameters.\n */\npublic class GOST3410PublicKeySpec implements KeySpec {\n\n private BigInteger y;\n\n private BigInteger p;\n\n private BigInteger q;\n\n private BigInteger a;\n\n /**\n * Creates a new GOST3410PublicKeySpec with the specified parameter values.\n *\n * @param y the public key.\n * @param p the prime.\n * @param q the sub-prime.\n * @param a the base.\n */\n public GOST3410PublicKeySpec(BigInteger y, BigInteger p, BigInteger q, BigInteger a) {\n this.y = y;\n this.p = p;\n this.q = q;\n this.a = a;\n }\n\n public BigInteger getY() {\n return this.y;\n }\n\n /**\n * Returns the prime p.\n *\n * @return the prime p.\n */\n public BigInteger getP() {\n return this.p;\n }\n\n /**\n * Returns the sub-prime q.\n *\n * @return the sub-prime q.\n */\n ", "post_mask_code": "{\n return this.q;\n }\n\n /**\n * Returns the base g.\n *\n * @return the base g.\n */\n public BigInteger getA() {\n return this.a;\n }\n}\n"} {"task_id": "Java_360", "language": "Java", "task_type": "method_body", "source_file": "java/github/bcgit/bc-java/prov/src/main/java/org/bouncycastle/jce/spec/GOST3410PublicKeySpec.java", "mask_start_position": 947, "mask_end_position": 977, "canonical_solution": "{\n return this.p;\n }", "pre_mask_code": "package org.bouncycastle.jce.spec;\n\nimport java.math.BigInteger;\nimport java.security.spec.KeySpec;\n\n/**\n * This class specifies a GOST3410-94 public key with its associated parameters.\n */\npublic class GOST3410PublicKeySpec implements KeySpec {\n\n private BigInteger y;\n\n private BigInteger p;\n\n private BigInteger q;\n\n private BigInteger a;\n\n /**\n * Creates a new GOST3410PublicKeySpec with the specified parameter values.\n *\n * @param y the public key.\n * @param p the prime.\n * @param q the sub-prime.\n * @param a the base.\n */\n public GOST3410PublicKeySpec(BigInteger y, BigInteger p, BigInteger q, BigInteger a) {\n this.y = y;\n this.p = p;\n this.q = q;\n this.a = a;\n }\n\n public BigInteger getY() {\n return this.y;\n }\n\n /**\n * Returns the prime p.\n *\n * @return the prime p.\n */\n public BigInteger getP() ", "post_mask_code": "\n\n /**\n * Returns the sub-prime q.\n *\n * @return the sub-prime q.\n */\n public BigInteger getQ() {\n return this.q;\n }\n\n /**\n * Returns the base g.\n *\n * @return the base g.\n */\n public BigInteger getA() {\n return this.a;\n }\n}\n"} {"task_id": "Java_361", "language": "Java", "task_type": "single_line", "source_file": "java/github/bcgit/bc-java/prov/src/main/java/org/bouncycastle/jce/spec/GOST3410PublicKeySpec.java", "mask_start_position": 792, "mask_end_position": 805, "canonical_solution": "eturn this.y;", "pre_mask_code": "package org.bouncycastle.jce.spec;\n\nimport java.math.BigInteger;\nimport java.security.spec.KeySpec;\n\n/**\n * This class specifies a GOST3410-94 public key with its associated parameters.\n */\npublic class GOST3410PublicKeySpec implements KeySpec {\n\n private BigInteger y;\n\n private BigInteger p;\n\n private BigInteger q;\n\n private BigInteger a;\n\n /**\n * Creates a new GOST3410PublicKeySpec with the specified parameter values.\n *\n * @param y the public key.\n * @param p the prime.\n * @param q the sub-prime.\n * @param a the base.\n */\n public GOST3410PublicKeySpec(BigInteger y, BigInteger p, BigInteger q, BigInteger a) {\n this.y = y;\n this.p = p;\n this.q = q;\n this.a = a;\n }\n\n public BigInteger getY() {\n r", "post_mask_code": "\n }\n\n /**\n * Returns the prime p.\n *\n * @return the prime p.\n */\n public BigInteger getP() {\n return this.p;\n }\n\n /**\n * Returns the sub-prime q.\n *\n * @return the sub-prime q.\n */\n public BigInteger getQ() {\n return this.q;\n }\n\n /**\n * Returns the base g.\n *\n * @return the base g.\n */\n public BigInteger getA() {\n return this.a;\n }\n}\n"} {"task_id": "Java_362", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/bcgit/bc-java/prov/src/main/java/org/bouncycastle/jce/spec/GOST3410PublicKeySpec.java", "mask_start_position": 1096, "mask_end_position": 1151, "canonical_solution": "public BigInteger getQ() {\n return this.q;\n }", "pre_mask_code": "package org.bouncycastle.jce.spec;\n\nimport java.math.BigInteger;\nimport java.security.spec.KeySpec;\n\n/**\n * This class specifies a GOST3410-94 public key with its associated parameters.\n */\npublic class GOST3410PublicKeySpec implements KeySpec {\n\n private BigInteger y;\n\n private BigInteger p;\n\n private BigInteger q;\n\n private BigInteger a;\n\n /**\n * Creates a new GOST3410PublicKeySpec with the specified parameter values.\n *\n * @param y the public key.\n * @param p the prime.\n * @param q the sub-prime.\n * @param a the base.\n */\n public GOST3410PublicKeySpec(BigInteger y, BigInteger p, BigInteger q, BigInteger a) {\n this.y = y;\n this.p = p;\n this.q = q;\n this.a = a;\n }\n\n public BigInteger getY() {\n return this.y;\n }\n\n /**\n * Returns the prime p.\n *\n * @return the prime p.\n */\n public BigInteger getP() {\n return this.p;\n }\n\n /**\n * Returns the sub-prime q.\n *\n * @return the sub-prime q.\n */\n ", "post_mask_code": "\n\n /**\n * Returns the base g.\n *\n * @return the base g.\n */\n public BigInteger getA() {\n return this.a;\n }\n}\n"} {"task_id": "Java_363", "language": "Java", "task_type": "empty", "source_file": "java/github/bcgit/bc-java/prov/src/main/java/org/bouncycastle/jce/spec/GOST3410PublicKeySpec.java", "mask_start_position": 1237, "mask_end_position": 1237, "canonical_solution": "", "pre_mask_code": "package org.bouncycastle.jce.spec;\n\nimport java.math.BigInteger;\nimport java.security.spec.KeySpec;\n\n/**\n * This class specifies a GOST3410-94 public key with its associated parameters.\n */\npublic class GOST3410PublicKeySpec implements KeySpec {\n\n private BigInteger y;\n\n private BigInteger p;\n\n private BigInteger q;\n\n private BigInteger a;\n\n /**\n * Creates a new GOST3410PublicKeySpec with the specified parameter values.\n *\n * @param y the public key.\n * @param p the prime.\n * @param q the sub-prime.\n * @param a the base.\n */\n public GOST3410PublicKeySpec(BigInteger y, BigInteger p, BigInteger q, BigInteger a) {\n this.y = y;\n this.p = p;\n this.q = q;\n this.a = a;\n }\n\n public BigInteger getY() {\n return this.y;\n }\n\n /**\n * Returns the prime p.\n *\n * @return the prime p.\n */\n public BigInteger getP() {\n return this.p;\n }\n\n /**\n * Returns the sub-prime q.\n *\n * @return the sub-prime q.\n */\n public BigInteger getQ() {\n return this.q;\n }\n\n /**\n * Returns the base g.\n *\n * @return the base g.\n */\n public BigInteger getA() {\n return this.a;\n }\n}\n"} {"task_id": "Java_364", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openforis/collect/collect-core/unused/ApplicationContextAwareImpl.java", "mask_start_position": 383, "mask_end_position": 492, "canonical_solution": "@Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException ", "pre_mask_code": "package org.openforis.collect.context;\n\nimport org.springframework.beans.BeansException;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\n\n/**\n * @author M. Togna\n */\npublic class ApplicationContextAwareImpl implements ApplicationContextAware {\n\n public ApplicationContextAwareImpl() {\n super();\n }\n\n ", "post_mask_code": "{\n CollectContext.setApplicationContext(applicationContext);\n }\n}\n"} {"task_id": "Java_365", "language": "Java", "task_type": "method_body", "source_file": "java/github/openforis/collect/collect-core/unused/ApplicationContextAwareImpl.java", "mask_start_position": 492, "mask_end_position": 565, "canonical_solution": "{\n CollectContext.setApplicationContext(applicationContext);\n }", "pre_mask_code": "package org.openforis.collect.context;\n\nimport org.springframework.beans.BeansException;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\n\n/**\n * @author M. Togna\n */\npublic class ApplicationContextAwareImpl implements ApplicationContextAware {\n\n public ApplicationContextAwareImpl() {\n super();\n }\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException ", "post_mask_code": "\n}\n"} {"task_id": "Java_366", "language": "Java", "task_type": "single_line", "source_file": "java/github/openforis/collect/collect-core/unused/ApplicationContextAwareImpl.java", "mask_start_position": 528, "mask_end_position": 559, "canonical_solution": "ionContext(applicationContext);", "pre_mask_code": "package org.openforis.collect.context;\n\nimport org.springframework.beans.BeansException;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\n\n/**\n * @author M. Togna\n */\npublic class ApplicationContextAwareImpl implements ApplicationContextAware {\n\n public ApplicationContextAwareImpl() {\n super();\n }\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n CollectContext.setApplicat", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_367", "language": "Java", "task_type": "empty", "source_file": "java/github/openforis/collect/collect-core/unused/ApplicationContextAwareImpl.java", "mask_start_position": 107, "mask_end_position": 107, "canonical_solution": "", "pre_mask_code": "package org.openforis.collect.context;\n\nimport org.springframework.beans.BeansException;\nimport org.springf", "post_mask_code": "ramework.context.ApplicationContext;\nimport org.springframework.context.ApplicationContextAware;\n\n/**\n * @author M. Togna\n */\npublic class ApplicationContextAwareImpl implements ApplicationContextAware {\n\n public ApplicationContextAwareImpl() {\n super();\n }\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n CollectContext.setApplicationContext(applicationContext);\n }\n}\n"} {"task_id": "Java_368", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/umple/umple/Umplificator/UmplifiedProjects/weka-umplified-0/src/main/java/weka/classifiers/functions/neural/NeuralMethod.java", "mask_start_position": 501, "mask_end_position": 537, "canonical_solution": "double outputValue(NeuralNode node);", "pre_mask_code": "package weka.classifiers.functions.neural;\n\nimport java.io.Serializable;\n\n/**\n * This is an interface used to create classes that can be used by the\n * neuralnode to perform all it's computations.\n *\n * @author Malcolm Ware (example@nnthink.com)\n * @version $Revision: 8034 $\n */\npublic interface NeuralMethod extends Serializable {\n\n /**\n * This function calculates what the output value should be.\n * @param node The node to calculate the value for.\n * @return The value.\n */\n ", "post_mask_code": "\n\n /**\n * This function calculates what the error value should be.\n * @param node The node to calculate the error for.\n * @return The error.\n */\n double errorValue(NeuralNode node);\n\n /**\n * This function will calculate what the change in weights should be\n * and also update them.\n * @param node The node to update the weights for.\n * @param learn The learning rate to use.\n * @param momentum The momentum to use.\n */\n void updateWeights(NeuralNode node, double learn, double momentum);\n}\n"} {"task_id": "Java_369", "language": "Java", "task_type": "empty", "source_file": "java/github/umple/umple/Umplificator/UmplifiedProjects/weka-umplified-0/src/main/java/weka/classifiers/functions/neural/NeuralMethod.java", "mask_start_position": 878, "mask_end_position": 878, "canonical_solution": "", "pre_mask_code": "package weka.classifiers.functions.neural;\n\nimport java.io.Serializable;\n\n/**\n * This is an interface used to create classes that can be used by the\n * neuralnode to perform all it's computations.\n *\n * @author Malcolm Ware (example@nnthink.com)\n * @version $Revision: 8034 $\n */\npublic interface NeuralMethod extends Serializable {\n\n /**\n * This function calculates what the output value should be.\n * @param node The node to calculate the value for.\n * @return The value.\n */\n double outputValue(NeuralNode node);\n\n /**\n * This function calculates what the error value should be.\n * @param node The node to calculate the error for.\n * @return The error.\n */\n double errorValue(NeuralNode node);\n\n /**\n * This function will calculate what the change in weights should be\n * and also update them.\n * @param node The nod", "post_mask_code": "e to update the weights for.\n * @param learn The learning rate to use.\n * @param momentum The momentum to use.\n */\n void updateWeights(NeuralNode node, double learn, double momentum);\n}\n"} {"task_id": "Java_370", "language": "Java", "task_type": "method_signature", "source_file": "java/github/MovingBlocks/Terasology/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfig.java", "mask_start_position": 2141, "mask_end_position": 2166, "canonical_solution": "void setId(SimpleUri id) ", "pre_mask_code": "package org.terasology.engine.config.flexible;\n\nimport com.google.common.collect.ImmutableList;\nimport org.reflections.ReflectionUtils;\nimport org.terasology.engine.config.flexible.internal.SettingBuilder;\nimport org.terasology.engine.config.flexible.internal.SettingImplBuilder;\nimport org.terasology.engine.core.SimpleUri;\nimport org.terasology.reflection.TypeInfo;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n/**\n * Represents a config class that will be automatically initialized and rendered by the engine.\n * All settings must be contained in {@code public static} fields of type {@link Setting}.\n */\npublic abstract class AutoConfig {\n\n private SimpleUri id;\n\n static Set getSettingFieldsIn(Class configType) {\n return ReflectionUtils.getFields(configType, ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withModifier(Modifier.FINAL), ReflectionUtils.withType(Setting.class));\n }\n\n public Set> getSettings() {\n return getSettingFieldsIn(getClass()).stream().map(field -> {\n try {\n return (Setting) field.get(this);\n } catch (IllegalAccessException e) {\n // Setting field will always be accessible, exception should never be thrown\n throw new RuntimeException(e);\n }\n }).collect(Collectors.toSet());\n }\n\n private static Setting setting(Iterable> arguments) {\n SettingBuilder builder = new SettingImplBuilder<>();\n for (SettingArgument argument : arguments) {\n argument.setInBuilder(builder);\n }\n return builder.build();\n }\n\n @SafeVarargs\n protected static Setting setting(SettingArgument, T> valueType, SettingArgument defaultValue, SettingArgument... arguments) {\n return setting(ImmutableList.>builder().add(valueType).add(defaultValue).add(arguments).build());\n }\n\n public SimpleUri getId() {\n return id;\n }\n\n ", "post_mask_code": "{\n this.id = id;\n }\n\n public abstract String getName();\n}\n"} {"task_id": "Java_371", "language": "Java", "task_type": "method_body", "source_file": "java/github/MovingBlocks/Terasology/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfig.java", "mask_start_position": 1549, "mask_end_position": 1765, "canonical_solution": "{\n SettingBuilder builder = new SettingImplBuilder<>();\n for (SettingArgument argument : arguments) {\n argument.setInBuilder(builder);\n }\n return builder.build();\n }", "pre_mask_code": "package org.terasology.engine.config.flexible;\n\nimport com.google.common.collect.ImmutableList;\nimport org.reflections.ReflectionUtils;\nimport org.terasology.engine.config.flexible.internal.SettingBuilder;\nimport org.terasology.engine.config.flexible.internal.SettingImplBuilder;\nimport org.terasology.engine.core.SimpleUri;\nimport org.terasology.reflection.TypeInfo;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n/**\n * Represents a config class that will be automatically initialized and rendered by the engine.\n * All settings must be contained in {@code public static} fields of type {@link Setting}.\n */\npublic abstract class AutoConfig {\n\n private SimpleUri id;\n\n static Set getSettingFieldsIn(Class configType) {\n return ReflectionUtils.getFields(configType, ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withModifier(Modifier.FINAL), ReflectionUtils.withType(Setting.class));\n }\n\n public Set> getSettings() {\n return getSettingFieldsIn(getClass()).stream().map(field -> {\n try {\n return (Setting) field.get(this);\n } catch (IllegalAccessException e) {\n // Setting field will always be accessible, exception should never be thrown\n throw new RuntimeException(e);\n }\n }).collect(Collectors.toSet());\n }\n\n private static Setting setting(Iterable> arguments) ", "post_mask_code": "\n\n @SafeVarargs\n protected static Setting setting(SettingArgument, T> valueType, SettingArgument defaultValue, SettingArgument... arguments) {\n return setting(ImmutableList.>builder().add(valueType).add(defaultValue).add(arguments).build());\n }\n\n public SimpleUri getId() {\n return id;\n }\n\n void setId(SimpleUri id) {\n this.id = id;\n }\n\n public abstract String getName();\n}\n"} {"task_id": "Java_372", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/MovingBlocks/Terasology/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfig.java", "mask_start_position": 1550, "mask_end_position": 1614, "canonical_solution": "\n SettingBuilder builder = new SettingImplBuilder<>();", "pre_mask_code": "package org.terasology.engine.config.flexible;\n\nimport com.google.common.collect.ImmutableList;\nimport org.reflections.ReflectionUtils;\nimport org.terasology.engine.config.flexible.internal.SettingBuilder;\nimport org.terasology.engine.config.flexible.internal.SettingImplBuilder;\nimport org.terasology.engine.core.SimpleUri;\nimport org.terasology.reflection.TypeInfo;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n/**\n * Represents a config class that will be automatically initialized and rendered by the engine.\n * All settings must be contained in {@code public static} fields of type {@link Setting}.\n */\npublic abstract class AutoConfig {\n\n private SimpleUri id;\n\n static Set getSettingFieldsIn(Class configType) {\n return ReflectionUtils.getFields(configType, ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withModifier(Modifier.FINAL), ReflectionUtils.withType(Setting.class));\n }\n\n public Set> getSettings() {\n return getSettingFieldsIn(getClass()).stream().map(field -> {\n try {\n return (Setting) field.get(this);\n } catch (IllegalAccessException e) {\n // Setting field will always be accessible, exception should never be thrown\n throw new RuntimeException(e);\n }\n }).collect(Collectors.toSet());\n }\n\n private static Setting setting(Iterable> arguments) {", "post_mask_code": "\n for (SettingArgument argument : arguments) {\n argument.setInBuilder(builder);\n }\n return builder.build();\n }\n\n @SafeVarargs\n protected static Setting setting(SettingArgument, T> valueType, SettingArgument defaultValue, SettingArgument... arguments) {\n return setting(ImmutableList.>builder().add(valueType).add(defaultValue).add(arguments).build());\n }\n\n public SimpleUri getId() {\n return id;\n }\n\n void setId(SimpleUri id) {\n this.id = id;\n }\n\n public abstract String getName();\n}\n"} {"task_id": "Java_373", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/MovingBlocks/Terasology/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfig.java", "mask_start_position": 1623, "mask_end_position": 1727, "canonical_solution": "for (SettingArgument argument : arguments) {\n argument.setInBuilder(builder);\n }", "pre_mask_code": "package org.terasology.engine.config.flexible;\n\nimport com.google.common.collect.ImmutableList;\nimport org.reflections.ReflectionUtils;\nimport org.terasology.engine.config.flexible.internal.SettingBuilder;\nimport org.terasology.engine.config.flexible.internal.SettingImplBuilder;\nimport org.terasology.engine.core.SimpleUri;\nimport org.terasology.reflection.TypeInfo;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n/**\n * Represents a config class that will be automatically initialized and rendered by the engine.\n * All settings must be contained in {@code public static} fields of type {@link Setting}.\n */\npublic abstract class AutoConfig {\n\n private SimpleUri id;\n\n static Set getSettingFieldsIn(Class configType) {\n return ReflectionUtils.getFields(configType, ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withModifier(Modifier.FINAL), ReflectionUtils.withType(Setting.class));\n }\n\n public Set> getSettings() {\n return getSettingFieldsIn(getClass()).stream().map(field -> {\n try {\n return (Setting) field.get(this);\n } catch (IllegalAccessException e) {\n // Setting field will always be accessible, exception should never be thrown\n throw new RuntimeException(e);\n }\n }).collect(Collectors.toSet());\n }\n\n private static Setting setting(Iterable> arguments) {\n SettingBuilder builder = new SettingImplBuilder<>();\n ", "post_mask_code": "\n return builder.build();\n }\n\n @SafeVarargs\n protected static Setting setting(SettingArgument, T> valueType, SettingArgument defaultValue, SettingArgument... arguments) {\n return setting(ImmutableList.>builder().add(valueType).add(defaultValue).add(arguments).build());\n }\n\n public SimpleUri getId() {\n return id;\n }\n\n void setId(SimpleUri id) {\n this.id = id;\n }\n\n public abstract String getName();\n}\n"} {"task_id": "Java_374", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/MovingBlocks/Terasology/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfig.java", "mask_start_position": 1736, "mask_end_position": 1765, "canonical_solution": "return builder.build();\n }", "pre_mask_code": "package org.terasology.engine.config.flexible;\n\nimport com.google.common.collect.ImmutableList;\nimport org.reflections.ReflectionUtils;\nimport org.terasology.engine.config.flexible.internal.SettingBuilder;\nimport org.terasology.engine.config.flexible.internal.SettingImplBuilder;\nimport org.terasology.engine.core.SimpleUri;\nimport org.terasology.reflection.TypeInfo;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n/**\n * Represents a config class that will be automatically initialized and rendered by the engine.\n * All settings must be contained in {@code public static} fields of type {@link Setting}.\n */\npublic abstract class AutoConfig {\n\n private SimpleUri id;\n\n static Set getSettingFieldsIn(Class configType) {\n return ReflectionUtils.getFields(configType, ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withModifier(Modifier.FINAL), ReflectionUtils.withType(Setting.class));\n }\n\n public Set> getSettings() {\n return getSettingFieldsIn(getClass()).stream().map(field -> {\n try {\n return (Setting) field.get(this);\n } catch (IllegalAccessException e) {\n // Setting field will always be accessible, exception should never be thrown\n throw new RuntimeException(e);\n }\n }).collect(Collectors.toSet());\n }\n\n private static Setting setting(Iterable> arguments) {\n SettingBuilder builder = new SettingImplBuilder<>();\n for (SettingArgument argument : arguments) {\n argument.setInBuilder(builder);\n }\n ", "post_mask_code": "\n\n @SafeVarargs\n protected static Setting setting(SettingArgument, T> valueType, SettingArgument defaultValue, SettingArgument... arguments) {\n return setting(ImmutableList.>builder().add(valueType).add(defaultValue).add(arguments).build());\n }\n\n public SimpleUri getId() {\n return id;\n }\n\n void setId(SimpleUri id) {\n this.id = id;\n }\n\n public abstract String getName();\n}\n"} {"task_id": "Java_375", "language": "Java", "task_type": "single_line", "source_file": "java/github/MovingBlocks/Terasology/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfig.java", "mask_start_position": 984, "mask_end_position": 1022, "canonical_solution": "lectionUtils.withType(Setting.class));", "pre_mask_code": "package org.terasology.engine.config.flexible;\n\nimport com.google.common.collect.ImmutableList;\nimport org.reflections.ReflectionUtils;\nimport org.terasology.engine.config.flexible.internal.SettingBuilder;\nimport org.terasology.engine.config.flexible.internal.SettingImplBuilder;\nimport org.terasology.engine.core.SimpleUri;\nimport org.terasology.reflection.TypeInfo;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n/**\n * Represents a config class that will be automatically initialized and rendered by the engine.\n * All settings must be contained in {@code public static} fields of type {@link Setting}.\n */\npublic abstract class AutoConfig {\n\n private SimpleUri id;\n\n static Set getSettingFieldsIn(Class configType) {\n return ReflectionUtils.getFields(configType, ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withModifier(Modifier.FINAL), Ref", "post_mask_code": "\n }\n\n public Set> getSettings() {\n return getSettingFieldsIn(getClass()).stream().map(field -> {\n try {\n return (Setting) field.get(this);\n } catch (IllegalAccessException e) {\n // Setting field will always be accessible, exception should never be thrown\n throw new RuntimeException(e);\n }\n }).collect(Collectors.toSet());\n }\n\n private static Setting setting(Iterable> arguments) {\n SettingBuilder builder = new SettingImplBuilder<>();\n for (SettingArgument argument : arguments) {\n argument.setInBuilder(builder);\n }\n return builder.build();\n }\n\n @SafeVarargs\n protected static Setting setting(SettingArgument, T> valueType, SettingArgument defaultValue, SettingArgument... arguments) {\n return setting(ImmutableList.>builder().add(valueType).add(defaultValue).add(arguments).build());\n }\n\n public SimpleUri getId() {\n return id;\n }\n\n void setId(SimpleUri id) {\n this.id = id;\n }\n\n public abstract String getName();\n}\n"} {"task_id": "Java_376", "language": "Java", "task_type": "try_statement", "source_file": "java/github/MovingBlocks/Terasology/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfig.java", "mask_start_position": 1155, "mask_end_position": 1416, "canonical_solution": "try {\n return (Setting) field.get(this);\n } catch (IllegalAccessException e) {\n // Setting field will always be accessible, exception should never be thrown\n throw new RuntimeException(e);\n }", "pre_mask_code": "package org.terasology.engine.config.flexible;\n\nimport com.google.common.collect.ImmutableList;\nimport org.reflections.ReflectionUtils;\nimport org.terasology.engine.config.flexible.internal.SettingBuilder;\nimport org.terasology.engine.config.flexible.internal.SettingImplBuilder;\nimport org.terasology.engine.core.SimpleUri;\nimport org.terasology.reflection.TypeInfo;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n/**\n * Represents a config class that will be automatically initialized and rendered by the engine.\n * All settings must be contained in {@code public static} fields of type {@link Setting}.\n */\npublic abstract class AutoConfig {\n\n private SimpleUri id;\n\n static Set getSettingFieldsIn(Class configType) {\n return ReflectionUtils.getFields(configType, ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withModifier(Modifier.FINAL), ReflectionUtils.withType(Setting.class));\n }\n\n public Set> getSettings() {\n return getSettingFieldsIn(getClass()).stream().map(field -> {\n ", "post_mask_code": "\n }).collect(Collectors.toSet());\n }\n\n private static Setting setting(Iterable> arguments) {\n SettingBuilder builder = new SettingImplBuilder<>();\n for (SettingArgument argument : arguments) {\n argument.setInBuilder(builder);\n }\n return builder.build();\n }\n\n @SafeVarargs\n protected static Setting setting(SettingArgument, T> valueType, SettingArgument defaultValue, SettingArgument... arguments) {\n return setting(ImmutableList.>builder().add(valueType).add(defaultValue).add(arguments).build());\n }\n\n public SimpleUri getId() {\n return id;\n }\n\n void setId(SimpleUri id) {\n this.id = id;\n }\n\n public abstract String getName();\n}\n"} {"task_id": "Java_377", "language": "Java", "task_type": "empty", "source_file": "java/github/MovingBlocks/Terasology/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfig.java", "mask_start_position": 761, "mask_end_position": 761, "canonical_solution": "", "pre_mask_code": "package org.terasology.engine.config.flexible;\n\nimport com.google.common.collect.ImmutableList;\nimport org.reflections.ReflectionUtils;\nimport org.terasology.engine.config.flexible.internal.SettingBuilder;\nimport org.terasology.engine.config.flexible.internal.SettingImplBuilder;\nimport org.terasology.engine.core.SimpleUri;\nimport org.terasology.reflection.TypeInfo;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n/**\n * Represents a config class that will be automatically initialized and rendered by the engine.\n * All settings must be contained in {@code public static} fields of type {@link Setting}.\n */\npublic abstract class AutoConfig {\n\n private SimpleUri id;\n\n stati", "post_mask_code": "c Set getSettingFieldsIn(Class configType) {\n return ReflectionUtils.getFields(configType, ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withModifier(Modifier.FINAL), ReflectionUtils.withType(Setting.class));\n }\n\n public Set> getSettings() {\n return getSettingFieldsIn(getClass()).stream().map(field -> {\n try {\n return (Setting) field.get(this);\n } catch (IllegalAccessException e) {\n // Setting field will always be accessible, exception should never be thrown\n throw new RuntimeException(e);\n }\n }).collect(Collectors.toSet());\n }\n\n private static Setting setting(Iterable> arguments) {\n SettingBuilder builder = new SettingImplBuilder<>();\n for (SettingArgument argument : arguments) {\n argument.setInBuilder(builder);\n }\n return builder.build();\n }\n\n @SafeVarargs\n protected static Setting setting(SettingArgument, T> valueType, SettingArgument defaultValue, SettingArgument... arguments) {\n return setting(ImmutableList.>builder().add(valueType).add(defaultValue).add(arguments).build());\n }\n\n public SimpleUri getId() {\n return id;\n }\n\n void setId(SimpleUri id) {\n this.id = id;\n }\n\n public abstract String getName();\n}\n"} {"task_id": "Java_378", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/jfree/orson-charts/src/main/java/org/jfree/chart3d/label/CategoryLabelGenerator.java", "mask_start_position": 2377, "mask_end_position": 2453, "canonical_solution": "String generateColumnLabel(CategoryDataset3D dataset, C columnKey);", "pre_mask_code": "/* ===========================================================\n * Orson Charts : a 3D chart library for the Java(tm) platform\n * ===========================================================\n * \n * \n * http://example.com\n * \n * \n * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. \n * Other names may be trademarks of their respective owners.]\n * \n * commercial license can be purchased. For details, please see visit the\n * Orson Charts home page:\n * \n * http://example.com\n * \n */\npackage org.jfree.chart3d.label;\n\nimport org.jfree.chart3d.data.category.CategoryDataset3D;\nimport org.jfree.chart3d.plot.CategoryPlot3D;\n\n/**\n * A label generator for category charts, used to create labels for the axes\n * and for the chart legend. The ({@link StandardCategoryLabelGenerator}) class\n * provides the default implementation.\n *

\n * Note that a different generator is used for item labels in\n * a {@link CategoryPlot3D} - see the {@link CategoryItemLabelGenerator}\n * interface.\n *\n * @param The series key type (must implement Comparable).\n * @param The row key type (must implement Comparable).\n * @param The column key type (must implement Comparable).\n *\n * @since 1.2\n */\npublic interface CategoryLabelGenerator, R extends Comparable, C extends Comparable> {\n\n /**\n * Generates a label for one series in a {@link CategoryDataset3D}.\n *\n * @param dataset the dataset ({@code null} not permitted).\n * @param seriesKey the series key ({@code null} not permitted).\n *\n * @return The series label (possibly {@code null}).\n */\n String generateSeriesLabel(CategoryDataset3D dataset, S seriesKey);\n\n /**\n * Generates a label for one row in a {@link CategoryDataset3D}.\n *\n * @param dataset the dataset ({@code null} not permitted).\n * @param rowKey the key ({@code null} not permitted).\n *\n * @return The row label (possibly {@code null}).\n */\n String generateRowLabel(CategoryDataset3D dataset, R rowKey);\n\n /**\n * Generates a label for one column in a {@link CategoryDataset3D}.\n *\n * @param dataset the dataset ({@code null} not permitted).\n * @param columnKey the key ({@code null} not permitted).\n *\n * @return The column label (possibly {@code null}).\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_379", "language": "Java", "task_type": "empty", "source_file": "java/github/jfree/orson-charts/src/main/java/org/jfree/chart3d/label/CategoryLabelGenerator.java", "mask_start_position": 1084, "mask_end_position": 1084, "canonical_solution": "", "pre_mask_code": "/* ===========================================================\n * Orson Charts : a 3D chart library for the Java(tm) platform\n * ===========================================================\n * \n * \n * http://example.com\n * \n * \n * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. \n * Other names may be trademarks of their respective owners.]\n * \n * commercial license can be purchased. For details, please see visit the\n * Orson Charts home page:\n * \n * http://example.com\n * \n */\npackage org.jfree.chart3d.label;\n\nimport org.jfree.chart3d.data.category.CategoryDataset3D;\nimport org.jfree.chart3d.plot.CategoryPlot3D;\n\n/**\n * A label generator for category charts, used to create labels for the axes\n * and for the chart legend. The ({@link StandardCategoryLabelGenerator}) class\n * provides the default implementation.\n *

\n * Note that a different generator is used for item labels in\n * a {@link CategoryPlot3D} - see the {@link CategoryItemLabelGenerator}\n * interface.\n *\n * @param The series key type (must implement Com", "post_mask_code": "parable).\n * @param The row key type (must implement Comparable).\n * @param The column key type (must implement Comparable).\n *\n * @since 1.2\n */\npublic interface CategoryLabelGenerator, R extends Comparable, C extends Comparable> {\n\n /**\n * Generates a label for one series in a {@link CategoryDataset3D}.\n *\n * @param dataset the dataset ({@code null} not permitted).\n * @param seriesKey the series key ({@code null} not permitted).\n *\n * @return The series label (possibly {@code null}).\n */\n String generateSeriesLabel(CategoryDataset3D dataset, S seriesKey);\n\n /**\n * Generates a label for one row in a {@link CategoryDataset3D}.\n *\n * @param dataset the dataset ({@code null} not permitted).\n * @param rowKey the key ({@code null} not permitted).\n *\n * @return The row label (possibly {@code null}).\n */\n String generateRowLabel(CategoryDataset3D dataset, R rowKey);\n\n /**\n * Generates a label for one column in a {@link CategoryDataset3D}.\n *\n * @param dataset the dataset ({@code null} not permitted).\n * @param columnKey the key ({@code null} not permitted).\n *\n * @return The column label (possibly {@code null}).\n */\n String generateColumnLabel(CategoryDataset3D dataset, C columnKey);\n}\n"} {"task_id": "Java_380", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/umple/umple/Umplificator/UmplifiedProjects/weka-umplified-0/src/main/java/weka/core/CommandlineRunnable.java", "mask_start_position": 469, "mask_end_position": 542, "canonical_solution": "void run(Object toRun, String[] options) throws IllegalArgumentException;", "pre_mask_code": "package weka.core;\n\n/**\n * Interface to something that can be run from the command line.\n *\n * @author Mark Hall (mhall{[at]}pentaho{[dot]}com)\n * @version $Revision: 8034 $\n */\npublic interface CommandlineRunnable {\n\n /**\n * Execute the supplied object.\n *\n * @param toRun the object to execute\n * @param options any options to pass to the object\n * @throws IllegalArgumentException if the object is not of the expected\n * type.\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_381", "language": "Java", "task_type": "empty", "source_file": "java/github/umple/umple/Umplificator/UmplifiedProjects/weka-umplified-0/src/main/java/weka/core/CommandlineRunnable.java", "mask_start_position": 340, "mask_end_position": 340, "canonical_solution": "", "pre_mask_code": "package weka.core;\n\n/**\n * Interface to something that can be run from the command line.\n *\n * @author Mark Hall (mhall{[at]}pentaho{[dot]}com)\n * @version $Revision: 8034 $\n */\npublic interface CommandlineRunnable {\n\n /**\n * Execute the supplied object.\n *\n * @param toRun the object to execute\n * @param options any opt", "post_mask_code": "ions to pass to the object\n * @throws IllegalArgumentException if the object is not of the expected\n * type.\n */\n void run(Object toRun, String[] options) throws IllegalArgumentException;\n}\n"} {"task_id": "Java_382", "language": "Java", "task_type": "method_signature", "source_file": "java/github/stratosphere/stratosphere/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dataproperties/InterestingProperties.java", "mask_start_position": 2463, "mask_end_position": 2547, "canonical_solution": "public InterestingProperties filterByCodeAnnotations(OptimizerNode node, int input) ", "pre_mask_code": "package eu.stratosphere.compiler.dataproperties;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\nimport eu.stratosphere.compiler.dag.OptimizerNode;\n\n/**\n * The interesting properties that a node in the optimizer plan hands to its predecessors. It has the\n * purpose to tell the preceding nodes, which data properties might have the advantage, because they would\n * let the node fulfill its pact cheaper. More on optimization with interesting properties can be found\n * in the works on the volcano- and cascades optimizer framework.\n */\npublic class InterestingProperties implements Cloneable {\n\n // the global properties, i.e. properties across partitions\n private Set globalProps;\n\n // the local properties, i.e. properties within partitions\n private Set localProps;\n\n public InterestingProperties() {\n this.globalProps = new HashSet();\n this.localProps = new HashSet();\n }\n\n /**\n * Private constructor for cloning purposes.\n *\n * @param maxCostsGlobal The maximal costs for the global properties.\n * @param maxCostsLocal The maximal costs for the local properties.\n * @param globalProps The global properties for this new object.\n * @param localProps The local properties for this new object.\n */\n private InterestingProperties(Set globalProps, Set localProps) {\n this.globalProps = globalProps;\n this.localProps = localProps;\n }\n\n public void addGlobalProperties(RequestedGlobalProperties props) {\n this.globalProps.add(props);\n }\n\n public void addLocalProperties(RequestedLocalProperties props) {\n this.localProps.add(props);\n }\n\n public void addInterestingProperties(InterestingProperties other) {\n this.globalProps.addAll(other.globalProps);\n this.localProps.addAll(other.localProps);\n }\n\n /**\n * Gets the interesting local properties.\n *\n * @return The interesting local properties.\n */\n public Set getLocalProperties() {\n return this.localProps;\n }\n\n /**\n * Gets the interesting global properties.\n *\n * @return The interesting global properties.\n */\n public Set getGlobalProperties() {\n return this.globalProps;\n }\n\n ", "post_mask_code": "{\n InterestingProperties iProps = new InterestingProperties();\n for (RequestedGlobalProperties rgp : this.globalProps) {\n RequestedGlobalProperties filtered = rgp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addGlobalProperties(filtered);\n }\n }\n for (RequestedLocalProperties rlp : this.localProps) {\n RequestedLocalProperties filtered = rlp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addLocalProperties(filtered);\n }\n }\n return iProps;\n }\n\n public void dropTrivials() {\n for (Iterator iter = this.globalProps.iterator(); iter.hasNext(); ) {\n RequestedGlobalProperties gp = iter.next();\n if (gp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n for (Iterator iter = this.localProps.iterator(); iter.hasNext(); ) {\n RequestedLocalProperties lp = iter.next();\n if (lp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((globalProps == null) ? 0 : globalProps.hashCode());\n result = prime * result + ((localProps == null) ? 0 : localProps.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj != null && obj instanceof InterestingProperties) {\n InterestingProperties other = (InterestingProperties) obj;\n return this.globalProps.equals(other.globalProps) && this.localProps.equals(other.localProps);\n } else {\n return false;\n }\n }\n\n @Override\n public String toString() {\n return \"InterestingProperties [globalProps=\" + this.globalProps + \", localProps=\" + this.localProps + \" ]\";\n }\n\n @Override\n public InterestingProperties clone() {\n HashSet globalProps = new HashSet();\n for (RequestedGlobalProperties p : this.globalProps) {\n globalProps.add(p.clone());\n }\n HashSet localProps = new HashSet();\n for (RequestedLocalProperties p : this.localProps) {\n localProps.add(p.clone());\n }\n return new InterestingProperties(globalProps, localProps);\n }\n}\n"} {"task_id": "Java_383", "language": "Java", "task_type": "method_body", "source_file": "java/github/stratosphere/stratosphere/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dataproperties/InterestingProperties.java", "mask_start_position": 3858, "mask_end_position": 4116, "canonical_solution": "{\n final int prime = 31;\n int result = 1;\n result = prime * result + ((globalProps == null) ? 0 : globalProps.hashCode());\n result = prime * result + ((localProps == null) ? 0 : localProps.hashCode());\n return result;\n }", "pre_mask_code": "package eu.stratosphere.compiler.dataproperties;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\nimport eu.stratosphere.compiler.dag.OptimizerNode;\n\n/**\n * The interesting properties that a node in the optimizer plan hands to its predecessors. It has the\n * purpose to tell the preceding nodes, which data properties might have the advantage, because they would\n * let the node fulfill its pact cheaper. More on optimization with interesting properties can be found\n * in the works on the volcano- and cascades optimizer framework.\n */\npublic class InterestingProperties implements Cloneable {\n\n // the global properties, i.e. properties across partitions\n private Set globalProps;\n\n // the local properties, i.e. properties within partitions\n private Set localProps;\n\n public InterestingProperties() {\n this.globalProps = new HashSet();\n this.localProps = new HashSet();\n }\n\n /**\n * Private constructor for cloning purposes.\n *\n * @param maxCostsGlobal The maximal costs for the global properties.\n * @param maxCostsLocal The maximal costs for the local properties.\n * @param globalProps The global properties for this new object.\n * @param localProps The local properties for this new object.\n */\n private InterestingProperties(Set globalProps, Set localProps) {\n this.globalProps = globalProps;\n this.localProps = localProps;\n }\n\n public void addGlobalProperties(RequestedGlobalProperties props) {\n this.globalProps.add(props);\n }\n\n public void addLocalProperties(RequestedLocalProperties props) {\n this.localProps.add(props);\n }\n\n public void addInterestingProperties(InterestingProperties other) {\n this.globalProps.addAll(other.globalProps);\n this.localProps.addAll(other.localProps);\n }\n\n /**\n * Gets the interesting local properties.\n *\n * @return The interesting local properties.\n */\n public Set getLocalProperties() {\n return this.localProps;\n }\n\n /**\n * Gets the interesting global properties.\n *\n * @return The interesting global properties.\n */\n public Set getGlobalProperties() {\n return this.globalProps;\n }\n\n public InterestingProperties filterByCodeAnnotations(OptimizerNode node, int input) {\n InterestingProperties iProps = new InterestingProperties();\n for (RequestedGlobalProperties rgp : this.globalProps) {\n RequestedGlobalProperties filtered = rgp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addGlobalProperties(filtered);\n }\n }\n for (RequestedLocalProperties rlp : this.localProps) {\n RequestedLocalProperties filtered = rlp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addLocalProperties(filtered);\n }\n }\n return iProps;\n }\n\n public void dropTrivials() {\n for (Iterator iter = this.globalProps.iterator(); iter.hasNext(); ) {\n RequestedGlobalProperties gp = iter.next();\n if (gp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n for (Iterator iter = this.localProps.iterator(); iter.hasNext(); ) {\n RequestedLocalProperties lp = iter.next();\n if (lp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n }\n\n @Override\n public int hashCode() ", "post_mask_code": "\n\n @Override\n public boolean equals(Object obj) {\n if (obj != null && obj instanceof InterestingProperties) {\n InterestingProperties other = (InterestingProperties) obj;\n return this.globalProps.equals(other.globalProps) && this.localProps.equals(other.localProps);\n } else {\n return false;\n }\n }\n\n @Override\n public String toString() {\n return \"InterestingProperties [globalProps=\" + this.globalProps + \", localProps=\" + this.localProps + \" ]\";\n }\n\n @Override\n public InterestingProperties clone() {\n HashSet globalProps = new HashSet();\n for (RequestedGlobalProperties p : this.globalProps) {\n globalProps.add(p.clone());\n }\n HashSet localProps = new HashSet();\n for (RequestedLocalProperties p : this.localProps) {\n localProps.add(p.clone());\n }\n return new InterestingProperties(globalProps, localProps);\n }\n}\n"} {"task_id": "Java_384", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/stratosphere/stratosphere/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dataproperties/InterestingProperties.java", "mask_start_position": 4701, "mask_end_position": 4913, "canonical_solution": "\n HashSet globalProps = new HashSet();\n for (RequestedGlobalProperties p : this.globalProps) {\n globalProps.add(p.clone());\n }", "pre_mask_code": "package eu.stratosphere.compiler.dataproperties;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\nimport eu.stratosphere.compiler.dag.OptimizerNode;\n\n/**\n * The interesting properties that a node in the optimizer plan hands to its predecessors. It has the\n * purpose to tell the preceding nodes, which data properties might have the advantage, because they would\n * let the node fulfill its pact cheaper. More on optimization with interesting properties can be found\n * in the works on the volcano- and cascades optimizer framework.\n */\npublic class InterestingProperties implements Cloneable {\n\n // the global properties, i.e. properties across partitions\n private Set globalProps;\n\n // the local properties, i.e. properties within partitions\n private Set localProps;\n\n public InterestingProperties() {\n this.globalProps = new HashSet();\n this.localProps = new HashSet();\n }\n\n /**\n * Private constructor for cloning purposes.\n *\n * @param maxCostsGlobal The maximal costs for the global properties.\n * @param maxCostsLocal The maximal costs for the local properties.\n * @param globalProps The global properties for this new object.\n * @param localProps The local properties for this new object.\n */\n private InterestingProperties(Set globalProps, Set localProps) {\n this.globalProps = globalProps;\n this.localProps = localProps;\n }\n\n public void addGlobalProperties(RequestedGlobalProperties props) {\n this.globalProps.add(props);\n }\n\n public void addLocalProperties(RequestedLocalProperties props) {\n this.localProps.add(props);\n }\n\n public void addInterestingProperties(InterestingProperties other) {\n this.globalProps.addAll(other.globalProps);\n this.localProps.addAll(other.localProps);\n }\n\n /**\n * Gets the interesting local properties.\n *\n * @return The interesting local properties.\n */\n public Set getLocalProperties() {\n return this.localProps;\n }\n\n /**\n * Gets the interesting global properties.\n *\n * @return The interesting global properties.\n */\n public Set getGlobalProperties() {\n return this.globalProps;\n }\n\n public InterestingProperties filterByCodeAnnotations(OptimizerNode node, int input) {\n InterestingProperties iProps = new InterestingProperties();\n for (RequestedGlobalProperties rgp : this.globalProps) {\n RequestedGlobalProperties filtered = rgp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addGlobalProperties(filtered);\n }\n }\n for (RequestedLocalProperties rlp : this.localProps) {\n RequestedLocalProperties filtered = rlp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addLocalProperties(filtered);\n }\n }\n return iProps;\n }\n\n public void dropTrivials() {\n for (Iterator iter = this.globalProps.iterator(); iter.hasNext(); ) {\n RequestedGlobalProperties gp = iter.next();\n if (gp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n for (Iterator iter = this.localProps.iterator(); iter.hasNext(); ) {\n RequestedLocalProperties lp = iter.next();\n if (lp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((globalProps == null) ? 0 : globalProps.hashCode());\n result = prime * result + ((localProps == null) ? 0 : localProps.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj != null && obj instanceof InterestingProperties) {\n InterestingProperties other = (InterestingProperties) obj;\n return this.globalProps.equals(other.globalProps) && this.localProps.equals(other.localProps);\n } else {\n return false;\n }\n }\n\n @Override\n public String toString() {\n return \"InterestingProperties [globalProps=\" + this.globalProps + \", localProps=\" + this.localProps + \" ]\";\n }\n\n @Override\n public InterestingProperties clone() {", "post_mask_code": "\n HashSet localProps = new HashSet();\n for (RequestedLocalProperties p : this.localProps) {\n localProps.add(p.clone());\n }\n return new InterestingProperties(globalProps, localProps);\n }\n}\n"} {"task_id": "Java_385", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/stratosphere/stratosphere/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dataproperties/InterestingProperties.java", "mask_start_position": 4922, "mask_end_position": 5119, "canonical_solution": "HashSet localProps = new HashSet();\n for (RequestedLocalProperties p : this.localProps) {\n localProps.add(p.clone());\n }", "pre_mask_code": "package eu.stratosphere.compiler.dataproperties;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\nimport eu.stratosphere.compiler.dag.OptimizerNode;\n\n/**\n * The interesting properties that a node in the optimizer plan hands to its predecessors. It has the\n * purpose to tell the preceding nodes, which data properties might have the advantage, because they would\n * let the node fulfill its pact cheaper. More on optimization with interesting properties can be found\n * in the works on the volcano- and cascades optimizer framework.\n */\npublic class InterestingProperties implements Cloneable {\n\n // the global properties, i.e. properties across partitions\n private Set globalProps;\n\n // the local properties, i.e. properties within partitions\n private Set localProps;\n\n public InterestingProperties() {\n this.globalProps = new HashSet();\n this.localProps = new HashSet();\n }\n\n /**\n * Private constructor for cloning purposes.\n *\n * @param maxCostsGlobal The maximal costs for the global properties.\n * @param maxCostsLocal The maximal costs for the local properties.\n * @param globalProps The global properties for this new object.\n * @param localProps The local properties for this new object.\n */\n private InterestingProperties(Set globalProps, Set localProps) {\n this.globalProps = globalProps;\n this.localProps = localProps;\n }\n\n public void addGlobalProperties(RequestedGlobalProperties props) {\n this.globalProps.add(props);\n }\n\n public void addLocalProperties(RequestedLocalProperties props) {\n this.localProps.add(props);\n }\n\n public void addInterestingProperties(InterestingProperties other) {\n this.globalProps.addAll(other.globalProps);\n this.localProps.addAll(other.localProps);\n }\n\n /**\n * Gets the interesting local properties.\n *\n * @return The interesting local properties.\n */\n public Set getLocalProperties() {\n return this.localProps;\n }\n\n /**\n * Gets the interesting global properties.\n *\n * @return The interesting global properties.\n */\n public Set getGlobalProperties() {\n return this.globalProps;\n }\n\n public InterestingProperties filterByCodeAnnotations(OptimizerNode node, int input) {\n InterestingProperties iProps = new InterestingProperties();\n for (RequestedGlobalProperties rgp : this.globalProps) {\n RequestedGlobalProperties filtered = rgp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addGlobalProperties(filtered);\n }\n }\n for (RequestedLocalProperties rlp : this.localProps) {\n RequestedLocalProperties filtered = rlp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addLocalProperties(filtered);\n }\n }\n return iProps;\n }\n\n public void dropTrivials() {\n for (Iterator iter = this.globalProps.iterator(); iter.hasNext(); ) {\n RequestedGlobalProperties gp = iter.next();\n if (gp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n for (Iterator iter = this.localProps.iterator(); iter.hasNext(); ) {\n RequestedLocalProperties lp = iter.next();\n if (lp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((globalProps == null) ? 0 : globalProps.hashCode());\n result = prime * result + ((localProps == null) ? 0 : localProps.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj != null && obj instanceof InterestingProperties) {\n InterestingProperties other = (InterestingProperties) obj;\n return this.globalProps.equals(other.globalProps) && this.localProps.equals(other.localProps);\n } else {\n return false;\n }\n }\n\n @Override\n public String toString() {\n return \"InterestingProperties [globalProps=\" + this.globalProps + \", localProps=\" + this.localProps + \" ]\";\n }\n\n @Override\n public InterestingProperties clone() {\n HashSet globalProps = new HashSet();\n for (RequestedGlobalProperties p : this.globalProps) {\n globalProps.add(p.clone());\n }\n ", "post_mask_code": "\n return new InterestingProperties(globalProps, localProps);\n }\n}\n"} {"task_id": "Java_386", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/stratosphere/stratosphere/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dataproperties/InterestingProperties.java", "mask_start_position": 5128, "mask_end_position": 5192, "canonical_solution": "return new InterestingProperties(globalProps, localProps);\n }", "pre_mask_code": "package eu.stratosphere.compiler.dataproperties;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\nimport eu.stratosphere.compiler.dag.OptimizerNode;\n\n/**\n * The interesting properties that a node in the optimizer plan hands to its predecessors. It has the\n * purpose to tell the preceding nodes, which data properties might have the advantage, because they would\n * let the node fulfill its pact cheaper. More on optimization with interesting properties can be found\n * in the works on the volcano- and cascades optimizer framework.\n */\npublic class InterestingProperties implements Cloneable {\n\n // the global properties, i.e. properties across partitions\n private Set globalProps;\n\n // the local properties, i.e. properties within partitions\n private Set localProps;\n\n public InterestingProperties() {\n this.globalProps = new HashSet();\n this.localProps = new HashSet();\n }\n\n /**\n * Private constructor for cloning purposes.\n *\n * @param maxCostsGlobal The maximal costs for the global properties.\n * @param maxCostsLocal The maximal costs for the local properties.\n * @param globalProps The global properties for this new object.\n * @param localProps The local properties for this new object.\n */\n private InterestingProperties(Set globalProps, Set localProps) {\n this.globalProps = globalProps;\n this.localProps = localProps;\n }\n\n public void addGlobalProperties(RequestedGlobalProperties props) {\n this.globalProps.add(props);\n }\n\n public void addLocalProperties(RequestedLocalProperties props) {\n this.localProps.add(props);\n }\n\n public void addInterestingProperties(InterestingProperties other) {\n this.globalProps.addAll(other.globalProps);\n this.localProps.addAll(other.localProps);\n }\n\n /**\n * Gets the interesting local properties.\n *\n * @return The interesting local properties.\n */\n public Set getLocalProperties() {\n return this.localProps;\n }\n\n /**\n * Gets the interesting global properties.\n *\n * @return The interesting global properties.\n */\n public Set getGlobalProperties() {\n return this.globalProps;\n }\n\n public InterestingProperties filterByCodeAnnotations(OptimizerNode node, int input) {\n InterestingProperties iProps = new InterestingProperties();\n for (RequestedGlobalProperties rgp : this.globalProps) {\n RequestedGlobalProperties filtered = rgp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addGlobalProperties(filtered);\n }\n }\n for (RequestedLocalProperties rlp : this.localProps) {\n RequestedLocalProperties filtered = rlp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addLocalProperties(filtered);\n }\n }\n return iProps;\n }\n\n public void dropTrivials() {\n for (Iterator iter = this.globalProps.iterator(); iter.hasNext(); ) {\n RequestedGlobalProperties gp = iter.next();\n if (gp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n for (Iterator iter = this.localProps.iterator(); iter.hasNext(); ) {\n RequestedLocalProperties lp = iter.next();\n if (lp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((globalProps == null) ? 0 : globalProps.hashCode());\n result = prime * result + ((localProps == null) ? 0 : localProps.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj != null && obj instanceof InterestingProperties) {\n InterestingProperties other = (InterestingProperties) obj;\n return this.globalProps.equals(other.globalProps) && this.localProps.equals(other.localProps);\n } else {\n return false;\n }\n }\n\n @Override\n public String toString() {\n return \"InterestingProperties [globalProps=\" + this.globalProps + \", localProps=\" + this.localProps + \" ]\";\n }\n\n @Override\n public InterestingProperties clone() {\n HashSet globalProps = new HashSet();\n for (RequestedGlobalProperties p : this.globalProps) {\n globalProps.add(p.clone());\n }\n HashSet localProps = new HashSet();\n for (RequestedLocalProperties p : this.localProps) {\n localProps.add(p.clone());\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_387", "language": "Java", "task_type": "single_line", "source_file": "java/github/stratosphere/stratosphere/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dataproperties/InterestingProperties.java", "mask_start_position": 2219, "mask_end_position": 2225, "canonical_solution": "Props;", "pre_mask_code": "package eu.stratosphere.compiler.dataproperties;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\nimport eu.stratosphere.compiler.dag.OptimizerNode;\n\n/**\n * The interesting properties that a node in the optimizer plan hands to its predecessors. It has the\n * purpose to tell the preceding nodes, which data properties might have the advantage, because they would\n * let the node fulfill its pact cheaper. More on optimization with interesting properties can be found\n * in the works on the volcano- and cascades optimizer framework.\n */\npublic class InterestingProperties implements Cloneable {\n\n // the global properties, i.e. properties across partitions\n private Set globalProps;\n\n // the local properties, i.e. properties within partitions\n private Set localProps;\n\n public InterestingProperties() {\n this.globalProps = new HashSet();\n this.localProps = new HashSet();\n }\n\n /**\n * Private constructor for cloning purposes.\n *\n * @param maxCostsGlobal The maximal costs for the global properties.\n * @param maxCostsLocal The maximal costs for the local properties.\n * @param globalProps The global properties for this new object.\n * @param localProps The local properties for this new object.\n */\n private InterestingProperties(Set globalProps, Set localProps) {\n this.globalProps = globalProps;\n this.localProps = localProps;\n }\n\n public void addGlobalProperties(RequestedGlobalProperties props) {\n this.globalProps.add(props);\n }\n\n public void addLocalProperties(RequestedLocalProperties props) {\n this.localProps.add(props);\n }\n\n public void addInterestingProperties(InterestingProperties other) {\n this.globalProps.addAll(other.globalProps);\n this.localProps.addAll(other.localProps);\n }\n\n /**\n * Gets the interesting local properties.\n *\n * @return The interesting local properties.\n */\n public Set getLocalProperties() {\n return this.local", "post_mask_code": "\n }\n\n /**\n * Gets the interesting global properties.\n *\n * @return The interesting global properties.\n */\n public Set getGlobalProperties() {\n return this.globalProps;\n }\n\n public InterestingProperties filterByCodeAnnotations(OptimizerNode node, int input) {\n InterestingProperties iProps = new InterestingProperties();\n for (RequestedGlobalProperties rgp : this.globalProps) {\n RequestedGlobalProperties filtered = rgp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addGlobalProperties(filtered);\n }\n }\n for (RequestedLocalProperties rlp : this.localProps) {\n RequestedLocalProperties filtered = rlp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addLocalProperties(filtered);\n }\n }\n return iProps;\n }\n\n public void dropTrivials() {\n for (Iterator iter = this.globalProps.iterator(); iter.hasNext(); ) {\n RequestedGlobalProperties gp = iter.next();\n if (gp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n for (Iterator iter = this.localProps.iterator(); iter.hasNext(); ) {\n RequestedLocalProperties lp = iter.next();\n if (lp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((globalProps == null) ? 0 : globalProps.hashCode());\n result = prime * result + ((localProps == null) ? 0 : localProps.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj != null && obj instanceof InterestingProperties) {\n InterestingProperties other = (InterestingProperties) obj;\n return this.globalProps.equals(other.globalProps) && this.localProps.equals(other.localProps);\n } else {\n return false;\n }\n }\n\n @Override\n public String toString() {\n return \"InterestingProperties [globalProps=\" + this.globalProps + \", localProps=\" + this.localProps + \" ]\";\n }\n\n @Override\n public InterestingProperties clone() {\n HashSet globalProps = new HashSet();\n for (RequestedGlobalProperties p : this.globalProps) {\n globalProps.add(p.clone());\n }\n HashSet localProps = new HashSet();\n for (RequestedLocalProperties p : this.localProps) {\n localProps.add(p.clone());\n }\n return new InterestingProperties(globalProps, localProps);\n }\n}\n"} {"task_id": "Java_388", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/stratosphere/stratosphere/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dataproperties/InterestingProperties.java", "mask_start_position": 2357, "mask_end_position": 2457, "canonical_solution": "public Set getGlobalProperties() {\n return this.globalProps;\n }", "pre_mask_code": "package eu.stratosphere.compiler.dataproperties;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\nimport eu.stratosphere.compiler.dag.OptimizerNode;\n\n/**\n * The interesting properties that a node in the optimizer plan hands to its predecessors. It has the\n * purpose to tell the preceding nodes, which data properties might have the advantage, because they would\n * let the node fulfill its pact cheaper. More on optimization with interesting properties can be found\n * in the works on the volcano- and cascades optimizer framework.\n */\npublic class InterestingProperties implements Cloneable {\n\n // the global properties, i.e. properties across partitions\n private Set globalProps;\n\n // the local properties, i.e. properties within partitions\n private Set localProps;\n\n public InterestingProperties() {\n this.globalProps = new HashSet();\n this.localProps = new HashSet();\n }\n\n /**\n * Private constructor for cloning purposes.\n *\n * @param maxCostsGlobal The maximal costs for the global properties.\n * @param maxCostsLocal The maximal costs for the local properties.\n * @param globalProps The global properties for this new object.\n * @param localProps The local properties for this new object.\n */\n private InterestingProperties(Set globalProps, Set localProps) {\n this.globalProps = globalProps;\n this.localProps = localProps;\n }\n\n public void addGlobalProperties(RequestedGlobalProperties props) {\n this.globalProps.add(props);\n }\n\n public void addLocalProperties(RequestedLocalProperties props) {\n this.localProps.add(props);\n }\n\n public void addInterestingProperties(InterestingProperties other) {\n this.globalProps.addAll(other.globalProps);\n this.localProps.addAll(other.localProps);\n }\n\n /**\n * Gets the interesting local properties.\n *\n * @return The interesting local properties.\n */\n public Set getLocalProperties() {\n return this.localProps;\n }\n\n /**\n * Gets the interesting global properties.\n *\n * @return The interesting global properties.\n */\n ", "post_mask_code": "\n\n public InterestingProperties filterByCodeAnnotations(OptimizerNode node, int input) {\n InterestingProperties iProps = new InterestingProperties();\n for (RequestedGlobalProperties rgp : this.globalProps) {\n RequestedGlobalProperties filtered = rgp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addGlobalProperties(filtered);\n }\n }\n for (RequestedLocalProperties rlp : this.localProps) {\n RequestedLocalProperties filtered = rlp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addLocalProperties(filtered);\n }\n }\n return iProps;\n }\n\n public void dropTrivials() {\n for (Iterator iter = this.globalProps.iterator(); iter.hasNext(); ) {\n RequestedGlobalProperties gp = iter.next();\n if (gp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n for (Iterator iter = this.localProps.iterator(); iter.hasNext(); ) {\n RequestedLocalProperties lp = iter.next();\n if (lp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((globalProps == null) ? 0 : globalProps.hashCode());\n result = prime * result + ((localProps == null) ? 0 : localProps.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj != null && obj instanceof InterestingProperties) {\n InterestingProperties other = (InterestingProperties) obj;\n return this.globalProps.equals(other.globalProps) && this.localProps.equals(other.localProps);\n } else {\n return false;\n }\n }\n\n @Override\n public String toString() {\n return \"InterestingProperties [globalProps=\" + this.globalProps + \", localProps=\" + this.localProps + \" ]\";\n }\n\n @Override\n public InterestingProperties clone() {\n HashSet globalProps = new HashSet();\n for (RequestedGlobalProperties p : this.globalProps) {\n globalProps.add(p.clone());\n }\n HashSet localProps = new HashSet();\n for (RequestedLocalProperties p : this.localProps) {\n localProps.add(p.clone());\n }\n return new InterestingProperties(globalProps, localProps);\n }\n}\n"} {"task_id": "Java_389", "language": "Java", "task_type": "if_statement", "source_file": "java/github/stratosphere/stratosphere/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dataproperties/InterestingProperties.java", "mask_start_position": 4180, "mask_end_position": 4469, "canonical_solution": "if (obj != null && obj instanceof InterestingProperties) {\n InterestingProperties other = (InterestingProperties) obj;\n return this.globalProps.equals(other.globalProps) && this.localProps.equals(other.localProps);\n } else {\n return false;\n }", "pre_mask_code": "package eu.stratosphere.compiler.dataproperties;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\nimport eu.stratosphere.compiler.dag.OptimizerNode;\n\n/**\n * The interesting properties that a node in the optimizer plan hands to its predecessors. It has the\n * purpose to tell the preceding nodes, which data properties might have the advantage, because they would\n * let the node fulfill its pact cheaper. More on optimization with interesting properties can be found\n * in the works on the volcano- and cascades optimizer framework.\n */\npublic class InterestingProperties implements Cloneable {\n\n // the global properties, i.e. properties across partitions\n private Set globalProps;\n\n // the local properties, i.e. properties within partitions\n private Set localProps;\n\n public InterestingProperties() {\n this.globalProps = new HashSet();\n this.localProps = new HashSet();\n }\n\n /**\n * Private constructor for cloning purposes.\n *\n * @param maxCostsGlobal The maximal costs for the global properties.\n * @param maxCostsLocal The maximal costs for the local properties.\n * @param globalProps The global properties for this new object.\n * @param localProps The local properties for this new object.\n */\n private InterestingProperties(Set globalProps, Set localProps) {\n this.globalProps = globalProps;\n this.localProps = localProps;\n }\n\n public void addGlobalProperties(RequestedGlobalProperties props) {\n this.globalProps.add(props);\n }\n\n public void addLocalProperties(RequestedLocalProperties props) {\n this.localProps.add(props);\n }\n\n public void addInterestingProperties(InterestingProperties other) {\n this.globalProps.addAll(other.globalProps);\n this.localProps.addAll(other.localProps);\n }\n\n /**\n * Gets the interesting local properties.\n *\n * @return The interesting local properties.\n */\n public Set getLocalProperties() {\n return this.localProps;\n }\n\n /**\n * Gets the interesting global properties.\n *\n * @return The interesting global properties.\n */\n public Set getGlobalProperties() {\n return this.globalProps;\n }\n\n public InterestingProperties filterByCodeAnnotations(OptimizerNode node, int input) {\n InterestingProperties iProps = new InterestingProperties();\n for (RequestedGlobalProperties rgp : this.globalProps) {\n RequestedGlobalProperties filtered = rgp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addGlobalProperties(filtered);\n }\n }\n for (RequestedLocalProperties rlp : this.localProps) {\n RequestedLocalProperties filtered = rlp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addLocalProperties(filtered);\n }\n }\n return iProps;\n }\n\n public void dropTrivials() {\n for (Iterator iter = this.globalProps.iterator(); iter.hasNext(); ) {\n RequestedGlobalProperties gp = iter.next();\n if (gp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n for (Iterator iter = this.localProps.iterator(); iter.hasNext(); ) {\n RequestedLocalProperties lp = iter.next();\n if (lp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((globalProps == null) ? 0 : globalProps.hashCode());\n result = prime * result + ((localProps == null) ? 0 : localProps.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n ", "post_mask_code": "\n }\n\n @Override\n public String toString() {\n return \"InterestingProperties [globalProps=\" + this.globalProps + \", localProps=\" + this.localProps + \" ]\";\n }\n\n @Override\n public InterestingProperties clone() {\n HashSet globalProps = new HashSet();\n for (RequestedGlobalProperties p : this.globalProps) {\n globalProps.add(p.clone());\n }\n HashSet localProps = new HashSet();\n for (RequestedLocalProperties p : this.localProps) {\n localProps.add(p.clone());\n }\n return new InterestingProperties(globalProps, localProps);\n }\n}\n"} {"task_id": "Java_390", "language": "Java", "task_type": "for_statement", "source_file": "java/github/stratosphere/stratosphere/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dataproperties/InterestingProperties.java", "mask_start_position": 3549, "mask_end_position": 3810, "canonical_solution": "for (Iterator iter = this.localProps.iterator(); iter.hasNext(); ) {\n RequestedLocalProperties lp = iter.next();\n if (lp.isTrivial()) {\n iter.remove();\n break;\n }\n }", "pre_mask_code": "package eu.stratosphere.compiler.dataproperties;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\nimport eu.stratosphere.compiler.dag.OptimizerNode;\n\n/**\n * The interesting properties that a node in the optimizer plan hands to its predecessors. It has the\n * purpose to tell the preceding nodes, which data properties might have the advantage, because they would\n * let the node fulfill its pact cheaper. More on optimization with interesting properties can be found\n * in the works on the volcano- and cascades optimizer framework.\n */\npublic class InterestingProperties implements Cloneable {\n\n // the global properties, i.e. properties across partitions\n private Set globalProps;\n\n // the local properties, i.e. properties within partitions\n private Set localProps;\n\n public InterestingProperties() {\n this.globalProps = new HashSet();\n this.localProps = new HashSet();\n }\n\n /**\n * Private constructor for cloning purposes.\n *\n * @param maxCostsGlobal The maximal costs for the global properties.\n * @param maxCostsLocal The maximal costs for the local properties.\n * @param globalProps The global properties for this new object.\n * @param localProps The local properties for this new object.\n */\n private InterestingProperties(Set globalProps, Set localProps) {\n this.globalProps = globalProps;\n this.localProps = localProps;\n }\n\n public void addGlobalProperties(RequestedGlobalProperties props) {\n this.globalProps.add(props);\n }\n\n public void addLocalProperties(RequestedLocalProperties props) {\n this.localProps.add(props);\n }\n\n public void addInterestingProperties(InterestingProperties other) {\n this.globalProps.addAll(other.globalProps);\n this.localProps.addAll(other.localProps);\n }\n\n /**\n * Gets the interesting local properties.\n *\n * @return The interesting local properties.\n */\n public Set getLocalProperties() {\n return this.localProps;\n }\n\n /**\n * Gets the interesting global properties.\n *\n * @return The interesting global properties.\n */\n public Set getGlobalProperties() {\n return this.globalProps;\n }\n\n public InterestingProperties filterByCodeAnnotations(OptimizerNode node, int input) {\n InterestingProperties iProps = new InterestingProperties();\n for (RequestedGlobalProperties rgp : this.globalProps) {\n RequestedGlobalProperties filtered = rgp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addGlobalProperties(filtered);\n }\n }\n for (RequestedLocalProperties rlp : this.localProps) {\n RequestedLocalProperties filtered = rlp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addLocalProperties(filtered);\n }\n }\n return iProps;\n }\n\n public void dropTrivials() {\n for (Iterator iter = this.globalProps.iterator(); iter.hasNext(); ) {\n RequestedGlobalProperties gp = iter.next();\n if (gp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n ", "post_mask_code": "\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((globalProps == null) ? 0 : globalProps.hashCode());\n result = prime * result + ((localProps == null) ? 0 : localProps.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj != null && obj instanceof InterestingProperties) {\n InterestingProperties other = (InterestingProperties) obj;\n return this.globalProps.equals(other.globalProps) && this.localProps.equals(other.localProps);\n } else {\n return false;\n }\n }\n\n @Override\n public String toString() {\n return \"InterestingProperties [globalProps=\" + this.globalProps + \", localProps=\" + this.localProps + \" ]\";\n }\n\n @Override\n public InterestingProperties clone() {\n HashSet globalProps = new HashSet();\n for (RequestedGlobalProperties p : this.globalProps) {\n globalProps.add(p.clone());\n }\n HashSet localProps = new HashSet();\n for (RequestedLocalProperties p : this.localProps) {\n localProps.add(p.clone());\n }\n return new InterestingProperties(globalProps, localProps);\n }\n}\n"} {"task_id": "Java_391", "language": "Java", "task_type": "empty", "source_file": "java/github/stratosphere/stratosphere/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dataproperties/InterestingProperties.java", "mask_start_position": 4167, "mask_end_position": 4167, "canonical_solution": "", "pre_mask_code": "package eu.stratosphere.compiler.dataproperties;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\nimport eu.stratosphere.compiler.dag.OptimizerNode;\n\n/**\n * The interesting properties that a node in the optimizer plan hands to its predecessors. It has the\n * purpose to tell the preceding nodes, which data properties might have the advantage, because they would\n * let the node fulfill its pact cheaper. More on optimization with interesting properties can be found\n * in the works on the volcano- and cascades optimizer framework.\n */\npublic class InterestingProperties implements Cloneable {\n\n // the global properties, i.e. properties across partitions\n private Set globalProps;\n\n // the local properties, i.e. properties within partitions\n private Set localProps;\n\n public InterestingProperties() {\n this.globalProps = new HashSet();\n this.localProps = new HashSet();\n }\n\n /**\n * Private constructor for cloning purposes.\n *\n * @param maxCostsGlobal The maximal costs for the global properties.\n * @param maxCostsLocal The maximal costs for the local properties.\n * @param globalProps The global properties for this new object.\n * @param localProps The local properties for this new object.\n */\n private InterestingProperties(Set globalProps, Set localProps) {\n this.globalProps = globalProps;\n this.localProps = localProps;\n }\n\n public void addGlobalProperties(RequestedGlobalProperties props) {\n this.globalProps.add(props);\n }\n\n public void addLocalProperties(RequestedLocalProperties props) {\n this.localProps.add(props);\n }\n\n public void addInterestingProperties(InterestingProperties other) {\n this.globalProps.addAll(other.globalProps);\n this.localProps.addAll(other.localProps);\n }\n\n /**\n * Gets the interesting local properties.\n *\n * @return The interesting local properties.\n */\n public Set getLocalProperties() {\n return this.localProps;\n }\n\n /**\n * Gets the interesting global properties.\n *\n * @return The interesting global properties.\n */\n public Set getGlobalProperties() {\n return this.globalProps;\n }\n\n public InterestingProperties filterByCodeAnnotations(OptimizerNode node, int input) {\n InterestingProperties iProps = new InterestingProperties();\n for (RequestedGlobalProperties rgp : this.globalProps) {\n RequestedGlobalProperties filtered = rgp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addGlobalProperties(filtered);\n }\n }\n for (RequestedLocalProperties rlp : this.localProps) {\n RequestedLocalProperties filtered = rlp.filterByNodesConstantSet(node, input);\n if (filtered != null && !filtered.isTrivial()) {\n iProps.addLocalProperties(filtered);\n }\n }\n return iProps;\n }\n\n public void dropTrivials() {\n for (Iterator iter = this.globalProps.iterator(); iter.hasNext(); ) {\n RequestedGlobalProperties gp = iter.next();\n if (gp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n for (Iterator iter = this.localProps.iterator(); iter.hasNext(); ) {\n RequestedLocalProperties lp = iter.next();\n if (lp.isTrivial()) {\n iter.remove();\n break;\n }\n }\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((globalProps == null) ? 0 : globalProps.hashCode());\n result = prime * result + ((localProps == null) ? 0 : localProps.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object ob", "post_mask_code": "j) {\n if (obj != null && obj instanceof InterestingProperties) {\n InterestingProperties other = (InterestingProperties) obj;\n return this.globalProps.equals(other.globalProps) && this.localProps.equals(other.localProps);\n } else {\n return false;\n }\n }\n\n @Override\n public String toString() {\n return \"InterestingProperties [globalProps=\" + this.globalProps + \", localProps=\" + this.localProps + \" ]\";\n }\n\n @Override\n public InterestingProperties clone() {\n HashSet globalProps = new HashSet();\n for (RequestedGlobalProperties p : this.globalProps) {\n globalProps.add(p.clone());\n }\n HashSet localProps = new HashSet();\n for (RequestedLocalProperties p : this.localProps) {\n localProps.add(p.clone());\n }\n return new InterestingProperties(globalProps, localProps);\n }\n}\n"} {"task_id": "Java_392", "language": "Java", "task_type": "method_signature", "source_file": "java/github/oracle/oci-java-sdk/bmc-networkloadbalancer/src/main/java/com/oracle/bmc/networkloadbalancer/NetworkLoadBalancerPaginators.java", "mask_start_position": 42154, "mask_end_position": 42257, "canonical_solution": "@Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) ", "pre_mask_code": "package com.oracle.bmc.networkloadbalancer;\n\nimport com.oracle.bmc.networkloadbalancer.requests.*;\nimport com.oracle.bmc.networkloadbalancer.responses.*;\n\n/**\n * Collection of helper methods that can be used to provide an {@link java.lang.Iterable} interface\n * to any list operations of NetworkLoadBalancer where multiple pages of data may be fetched.\n * Two styles of iteration are supported:\n *\n *
    \n *
  • Iterating over the Response objects returned by the list operation. These are referred to as ResponseIterators, and the methods are suffixed with ResponseIterator. For example: listUsersResponseIterator
  • \n *
  • Iterating over the resources/records being listed. These are referred to as RecordIterators, and the methods are suffixed with RecordIterator. For example: listUsersRecordIterator
  • \n *
\n *\n * These iterables abstract away the need to write code to manually handle pagination via looping and using the page tokens.\n * They will automatically fetch more data from the service when required.\n *\n * As an example, if we were using the ListUsers operation in IdentityService, then the {@link java.lang.Iterable} returned by calling a\n * ResponseIterator method would iterate over the ListUsersResponse objects returned by each ListUsers call, whereas the {@link java.lang.Iterable}\n * returned by calling a RecordIterator method would iterate over the User records and we don't have to deal with ListUsersResponse objects at all.\n * In either case, pagination will be automatically handled so we can iterate until there are no more responses or no more resources/records available.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20200501\")\n@lombok.RequiredArgsConstructor\npublic class NetworkLoadBalancerPaginators {\n\n private final NetworkLoadBalancer client;\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackendSets operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendSetsResponseIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses from the listBackendSets operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendSetsRecordIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendSetsResponse response) {\n return response.getBackendSetCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackends operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendsResponseIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses from the listBackends operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendsRecordIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendsResponse response) {\n return response.getBackendCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listListeners operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listListenersResponseIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses from the listListeners operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listListenersRecordIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListListenersResponse response) {\n return response.getListenerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancerHealths operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsResponseIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses from the listNetworkLoadBalancerHealths operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsRecordIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getNetworkLoadBalancerHealthCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancers operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersResponseIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses from the listNetworkLoadBalancers operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersRecordIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersResponse response) {\n return response.getNetworkLoadBalancerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersPolicies operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesResponseIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses from the listNetworkLoadBalancersPolicies operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesRecordIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getNetworkLoadBalancersPolicyCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersProtocols operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsResponseIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses from the listNetworkLoadBalancersProtocols operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsRecordIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getNetworkLoadBalancersProtocolCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestErrors operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestErrorsResponseIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses from the listWorkRequestErrors operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestErrorsRecordIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n ", "post_mask_code": "{\n return client.listWorkRequestErrors(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestErrorsResponse response) {\n return response.getWorkRequestErrorCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestLogs operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestLogsResponseIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses from the listWorkRequestLogs operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestLogsRecordIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestLogsResponse response) {\n return response.getWorkRequestLogEntryCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequests operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestsResponseIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses from the listWorkRequests operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestsRecordIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestsResponse response) {\n return response.getWorkRequestCollection().getItems();\n }\n });\n }\n}\n"} {"task_id": "Java_393", "language": "Java", "task_type": "method_body", "source_file": "java/github/oracle/oci-java-sdk/bmc-networkloadbalancer/src/main/java/com/oracle/bmc/networkloadbalancer/NetworkLoadBalancerPaginators.java", "mask_start_position": 31532, "mask_end_position": 31620, "canonical_solution": "{\n return client.listNetworkLoadBalancersPolicies(request);\n }", "pre_mask_code": "package com.oracle.bmc.networkloadbalancer;\n\nimport com.oracle.bmc.networkloadbalancer.requests.*;\nimport com.oracle.bmc.networkloadbalancer.responses.*;\n\n/**\n * Collection of helper methods that can be used to provide an {@link java.lang.Iterable} interface\n * to any list operations of NetworkLoadBalancer where multiple pages of data may be fetched.\n * Two styles of iteration are supported:\n *\n *
    \n *
  • Iterating over the Response objects returned by the list operation. These are referred to as ResponseIterators, and the methods are suffixed with ResponseIterator. For example: listUsersResponseIterator
  • \n *
  • Iterating over the resources/records being listed. These are referred to as RecordIterators, and the methods are suffixed with RecordIterator. For example: listUsersRecordIterator
  • \n *
\n *\n * These iterables abstract away the need to write code to manually handle pagination via looping and using the page tokens.\n * They will automatically fetch more data from the service when required.\n *\n * As an example, if we were using the ListUsers operation in IdentityService, then the {@link java.lang.Iterable} returned by calling a\n * ResponseIterator method would iterate over the ListUsersResponse objects returned by each ListUsers call, whereas the {@link java.lang.Iterable}\n * returned by calling a RecordIterator method would iterate over the User records and we don't have to deal with ListUsersResponse objects at all.\n * In either case, pagination will be automatically handled so we can iterate until there are no more responses or no more resources/records available.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20200501\")\n@lombok.RequiredArgsConstructor\npublic class NetworkLoadBalancerPaginators {\n\n private final NetworkLoadBalancer client;\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackendSets operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendSetsResponseIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses from the listBackendSets operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendSetsRecordIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendSetsResponse response) {\n return response.getBackendSetCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackends operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendsResponseIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses from the listBackends operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendsRecordIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendsResponse response) {\n return response.getBackendCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listListeners operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listListenersResponseIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses from the listListeners operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listListenersRecordIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListListenersResponse response) {\n return response.getListenerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancerHealths operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsResponseIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses from the listNetworkLoadBalancerHealths operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsRecordIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getNetworkLoadBalancerHealthCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancers operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersResponseIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses from the listNetworkLoadBalancers operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersRecordIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersResponse response) {\n return response.getNetworkLoadBalancerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersPolicies operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesResponseIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses from the listNetworkLoadBalancersPolicies operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesRecordIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) ", "post_mask_code": "\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getNetworkLoadBalancersPolicyCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersProtocols operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsResponseIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses from the listNetworkLoadBalancersProtocols operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsRecordIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getNetworkLoadBalancersProtocolCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestErrors operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestErrorsResponseIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses from the listWorkRequestErrors operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestErrorsRecordIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestErrorsResponse response) {\n return response.getWorkRequestErrorCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestLogs operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestLogsResponseIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses from the listWorkRequestLogs operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestLogsRecordIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestLogsResponse response) {\n return response.getWorkRequestLogEntryCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequests operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestsResponseIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses from the listWorkRequests operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestsRecordIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestsResponse response) {\n return response.getWorkRequestCollection().getItems();\n }\n });\n }\n}\n"} {"task_id": "Java_394", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/oracle/oci-java-sdk/bmc-networkloadbalancer/src/main/java/com/oracle/bmc/networkloadbalancer/NetworkLoadBalancerPaginators.java", "mask_start_position": 14907, "mask_end_position": 14907, "canonical_solution": "", "pre_mask_code": "package com.oracle.bmc.networkloadbalancer;\n\nimport com.oracle.bmc.networkloadbalancer.requests.*;\nimport com.oracle.bmc.networkloadbalancer.responses.*;\n\n/**\n * Collection of helper methods that can be used to provide an {@link java.lang.Iterable} interface\n * to any list operations of NetworkLoadBalancer where multiple pages of data may be fetched.\n * Two styles of iteration are supported:\n *\n *
    \n *
  • Iterating over the Response objects returned by the list operation. These are referred to as ResponseIterators, and the methods are suffixed with ResponseIterator. For example: listUsersResponseIterator
  • \n *
  • Iterating over the resources/records being listed. These are referred to as RecordIterators, and the methods are suffixed with RecordIterator. For example: listUsersRecordIterator
  • \n *
\n *\n * These iterables abstract away the need to write code to manually handle pagination via looping and using the page tokens.\n * They will automatically fetch more data from the service when required.\n *\n * As an example, if we were using the ListUsers operation in IdentityService, then the {@link java.lang.Iterable} returned by calling a\n * ResponseIterator method would iterate over the ListUsersResponse objects returned by each ListUsers call, whereas the {@link java.lang.Iterable}\n * returned by calling a RecordIterator method would iterate over the User records and we don't have to deal with ListUsersResponse objects at all.\n * In either case, pagination will be automatically handled so we can iterate until there are no more responses or no more resources/records available.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20200501\")\n@lombok.RequiredArgsConstructor\npublic class NetworkLoadBalancerPaginators {\n\n private final NetworkLoadBalancer client;\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackendSets operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendSetsResponseIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses from the listBackendSets operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendSetsRecordIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendSetsResponse response) {\n return response.getBackendSetCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackends operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendsResponseIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses from the listBackends operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendsRecordIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendsResponse response) {\n return response.getBackendCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listListeners operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listListenersResponseIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses from the listListeners operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listListenersRecordIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {", "post_mask_code": "\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListListenersResponse response) {\n return response.getListenerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancerHealths operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsResponseIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses from the listNetworkLoadBalancerHealths operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsRecordIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getNetworkLoadBalancerHealthCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancers operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersResponseIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses from the listNetworkLoadBalancers operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersRecordIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersResponse response) {\n return response.getNetworkLoadBalancerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersPolicies operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesResponseIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses from the listNetworkLoadBalancersPolicies operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesRecordIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getNetworkLoadBalancersPolicyCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersProtocols operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsResponseIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses from the listNetworkLoadBalancersProtocols operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsRecordIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getNetworkLoadBalancersProtocolCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestErrors operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestErrorsResponseIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses from the listWorkRequestErrors operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestErrorsRecordIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestErrorsResponse response) {\n return response.getWorkRequestErrorCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestLogs operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestLogsResponseIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses from the listWorkRequestLogs operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestLogsRecordIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestLogsResponse response) {\n return response.getWorkRequestLogEntryCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequests operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestsResponseIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses from the listWorkRequests operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestsRecordIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestsResponse response) {\n return response.getWorkRequestCollection().getItems();\n }\n });\n }\n}\n"} {"task_id": "Java_395", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/oracle/oci-java-sdk/bmc-networkloadbalancer/src/main/java/com/oracle/bmc/networkloadbalancer/NetworkLoadBalancerPaginators.java", "mask_start_position": 14924, "mask_end_position": 15154, "canonical_solution": "if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }", "pre_mask_code": "package com.oracle.bmc.networkloadbalancer;\n\nimport com.oracle.bmc.networkloadbalancer.requests.*;\nimport com.oracle.bmc.networkloadbalancer.responses.*;\n\n/**\n * Collection of helper methods that can be used to provide an {@link java.lang.Iterable} interface\n * to any list operations of NetworkLoadBalancer where multiple pages of data may be fetched.\n * Two styles of iteration are supported:\n *\n *
    \n *
  • Iterating over the Response objects returned by the list operation. These are referred to as ResponseIterators, and the methods are suffixed with ResponseIterator. For example: listUsersResponseIterator
  • \n *
  • Iterating over the resources/records being listed. These are referred to as RecordIterators, and the methods are suffixed with RecordIterator. For example: listUsersRecordIterator
  • \n *
\n *\n * These iterables abstract away the need to write code to manually handle pagination via looping and using the page tokens.\n * They will automatically fetch more data from the service when required.\n *\n * As an example, if we were using the ListUsers operation in IdentityService, then the {@link java.lang.Iterable} returned by calling a\n * ResponseIterator method would iterate over the ListUsersResponse objects returned by each ListUsers call, whereas the {@link java.lang.Iterable}\n * returned by calling a RecordIterator method would iterate over the User records and we don't have to deal with ListUsersResponse objects at all.\n * In either case, pagination will be automatically handled so we can iterate until there are no more responses or no more resources/records available.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20200501\")\n@lombok.RequiredArgsConstructor\npublic class NetworkLoadBalancerPaginators {\n\n private final NetworkLoadBalancer client;\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackendSets operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendSetsResponseIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses from the listBackendSets operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendSetsRecordIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendSetsResponse response) {\n return response.getBackendSetCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackends operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendsResponseIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses from the listBackends operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendsRecordIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendsResponse response) {\n return response.getBackendCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listListeners operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listListenersResponseIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses from the listListeners operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listListenersRecordIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n ", "post_mask_code": "\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListListenersResponse response) {\n return response.getListenerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancerHealths operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsResponseIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses from the listNetworkLoadBalancerHealths operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsRecordIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getNetworkLoadBalancerHealthCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancers operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersResponseIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses from the listNetworkLoadBalancers operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersRecordIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersResponse response) {\n return response.getNetworkLoadBalancerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersPolicies operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesResponseIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses from the listNetworkLoadBalancersPolicies operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesRecordIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getNetworkLoadBalancersPolicyCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersProtocols operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsResponseIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses from the listNetworkLoadBalancersProtocols operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsRecordIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getNetworkLoadBalancersProtocolCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestErrors operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestErrorsResponseIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses from the listWorkRequestErrors operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestErrorsRecordIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestErrorsResponse response) {\n return response.getWorkRequestErrorCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestLogs operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestLogsResponseIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses from the listWorkRequestLogs operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestLogsRecordIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestLogsResponse response) {\n return response.getWorkRequestLogEntryCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequests operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestsResponseIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses from the listWorkRequests operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestsRecordIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestsResponse response) {\n return response.getWorkRequestCollection().getItems();\n }\n });\n }\n}\n"} {"task_id": "Java_396", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/oracle/oci-java-sdk/bmc-networkloadbalancer/src/main/java/com/oracle/bmc/networkloadbalancer/NetworkLoadBalancerPaginators.java", "mask_start_position": 15167, "mask_end_position": 15168, "canonical_solution": "}", "pre_mask_code": "package com.oracle.bmc.networkloadbalancer;\n\nimport com.oracle.bmc.networkloadbalancer.requests.*;\nimport com.oracle.bmc.networkloadbalancer.responses.*;\n\n/**\n * Collection of helper methods that can be used to provide an {@link java.lang.Iterable} interface\n * to any list operations of NetworkLoadBalancer where multiple pages of data may be fetched.\n * Two styles of iteration are supported:\n *\n *
    \n *
  • Iterating over the Response objects returned by the list operation. These are referred to as ResponseIterators, and the methods are suffixed with ResponseIterator. For example: listUsersResponseIterator
  • \n *
  • Iterating over the resources/records being listed. These are referred to as RecordIterators, and the methods are suffixed with RecordIterator. For example: listUsersRecordIterator
  • \n *
\n *\n * These iterables abstract away the need to write code to manually handle pagination via looping and using the page tokens.\n * They will automatically fetch more data from the service when required.\n *\n * As an example, if we were using the ListUsers operation in IdentityService, then the {@link java.lang.Iterable} returned by calling a\n * ResponseIterator method would iterate over the ListUsersResponse objects returned by each ListUsers call, whereas the {@link java.lang.Iterable}\n * returned by calling a RecordIterator method would iterate over the User records and we don't have to deal with ListUsersResponse objects at all.\n * In either case, pagination will be automatically handled so we can iterate until there are no more responses or no more resources/records available.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20200501\")\n@lombok.RequiredArgsConstructor\npublic class NetworkLoadBalancerPaginators {\n\n private final NetworkLoadBalancer client;\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackendSets operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendSetsResponseIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses from the listBackendSets operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendSetsRecordIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendSetsResponse response) {\n return response.getBackendSetCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackends operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendsResponseIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses from the listBackends operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendsRecordIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendsResponse response) {\n return response.getBackendCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listListeners operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listListenersResponseIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses from the listListeners operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listListenersRecordIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n ", "post_mask_code": "\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListListenersResponse response) {\n return response.getListenerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancerHealths operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsResponseIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses from the listNetworkLoadBalancerHealths operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsRecordIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getNetworkLoadBalancerHealthCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancers operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersResponseIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses from the listNetworkLoadBalancers operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersRecordIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersResponse response) {\n return response.getNetworkLoadBalancerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersPolicies operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesResponseIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses from the listNetworkLoadBalancersPolicies operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesRecordIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getNetworkLoadBalancersPolicyCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersProtocols operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsResponseIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses from the listNetworkLoadBalancersProtocols operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsRecordIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getNetworkLoadBalancersProtocolCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestErrors operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestErrorsResponseIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses from the listWorkRequestErrors operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestErrorsRecordIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestErrorsResponse response) {\n return response.getWorkRequestErrorCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestLogs operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestLogsResponseIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses from the listWorkRequestLogs operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestLogsRecordIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestLogsResponse response) {\n return response.getWorkRequestLogEntryCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequests operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestsResponseIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses from the listWorkRequests operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestsRecordIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestsResponse response) {\n return response.getWorkRequestCollection().getItems();\n }\n });\n }\n}\n"} {"task_id": "Java_397", "language": "Java", "task_type": "single_line", "source_file": "java/github/oracle/oci-java-sdk/bmc-networkloadbalancer/src/main/java/com/oracle/bmc/networkloadbalancer/NetworkLoadBalancerPaginators.java", "mask_start_position": 2955, "mask_end_position": 2984, "canonical_solution": "rn response.getOpcNextPage();", "pre_mask_code": "package com.oracle.bmc.networkloadbalancer;\n\nimport com.oracle.bmc.networkloadbalancer.requests.*;\nimport com.oracle.bmc.networkloadbalancer.responses.*;\n\n/**\n * Collection of helper methods that can be used to provide an {@link java.lang.Iterable} interface\n * to any list operations of NetworkLoadBalancer where multiple pages of data may be fetched.\n * Two styles of iteration are supported:\n *\n *
    \n *
  • Iterating over the Response objects returned by the list operation. These are referred to as ResponseIterators, and the methods are suffixed with ResponseIterator. For example: listUsersResponseIterator
  • \n *
  • Iterating over the resources/records being listed. These are referred to as RecordIterators, and the methods are suffixed with RecordIterator. For example: listUsersRecordIterator
  • \n *
\n *\n * These iterables abstract away the need to write code to manually handle pagination via looping and using the page tokens.\n * They will automatically fetch more data from the service when required.\n *\n * As an example, if we were using the ListUsers operation in IdentityService, then the {@link java.lang.Iterable} returned by calling a\n * ResponseIterator method would iterate over the ListUsersResponse objects returned by each ListUsers call, whereas the {@link java.lang.Iterable}\n * returned by calling a RecordIterator method would iterate over the User records and we don't have to deal with ListUsersResponse objects at all.\n * In either case, pagination will be automatically handled so we can iterate until there are no more responses or no more resources/records available.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20200501\")\n@lombok.RequiredArgsConstructor\npublic class NetworkLoadBalancerPaginators {\n\n private final NetworkLoadBalancer client;\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackendSets operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendSetsResponseIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n retu", "post_mask_code": "\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses from the listBackendSets operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendSetsRecordIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendSetsResponse response) {\n return response.getBackendSetCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackends operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendsResponseIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses from the listBackends operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendsRecordIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendsResponse response) {\n return response.getBackendCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listListeners operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listListenersResponseIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses from the listListeners operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listListenersRecordIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListListenersResponse response) {\n return response.getListenerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancerHealths operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsResponseIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses from the listNetworkLoadBalancerHealths operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsRecordIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getNetworkLoadBalancerHealthCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancers operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersResponseIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses from the listNetworkLoadBalancers operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersRecordIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersResponse response) {\n return response.getNetworkLoadBalancerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersPolicies operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesResponseIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses from the listNetworkLoadBalancersPolicies operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesRecordIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getNetworkLoadBalancersPolicyCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersProtocols operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsResponseIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses from the listNetworkLoadBalancersProtocols operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsRecordIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getNetworkLoadBalancersProtocolCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestErrors operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestErrorsResponseIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses from the listWorkRequestErrors operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestErrorsRecordIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestErrorsResponse response) {\n return response.getWorkRequestErrorCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestLogs operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestLogsResponseIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses from the listWorkRequestLogs operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestLogsRecordIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestLogsResponse response) {\n return response.getWorkRequestLogEntryCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequests operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestsResponseIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses from the listWorkRequests operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestsRecordIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestsResponse response) {\n return response.getWorkRequestCollection().getItems();\n }\n });\n }\n}\n"} {"task_id": "Java_398", "language": "Java", "task_type": "if_statement", "source_file": "java/github/oracle/oci-java-sdk/bmc-networkloadbalancer/src/main/java/com/oracle/bmc/networkloadbalancer/NetworkLoadBalancerPaginators.java", "mask_start_position": 41784, "mask_end_position": 42014, "canonical_solution": "if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }", "pre_mask_code": "package com.oracle.bmc.networkloadbalancer;\n\nimport com.oracle.bmc.networkloadbalancer.requests.*;\nimport com.oracle.bmc.networkloadbalancer.responses.*;\n\n/**\n * Collection of helper methods that can be used to provide an {@link java.lang.Iterable} interface\n * to any list operations of NetworkLoadBalancer where multiple pages of data may be fetched.\n * Two styles of iteration are supported:\n *\n *
    \n *
  • Iterating over the Response objects returned by the list operation. These are referred to as ResponseIterators, and the methods are suffixed with ResponseIterator. For example: listUsersResponseIterator
  • \n *
  • Iterating over the resources/records being listed. These are referred to as RecordIterators, and the methods are suffixed with RecordIterator. For example: listUsersRecordIterator
  • \n *
\n *\n * These iterables abstract away the need to write code to manually handle pagination via looping and using the page tokens.\n * They will automatically fetch more data from the service when required.\n *\n * As an example, if we were using the ListUsers operation in IdentityService, then the {@link java.lang.Iterable} returned by calling a\n * ResponseIterator method would iterate over the ListUsersResponse objects returned by each ListUsers call, whereas the {@link java.lang.Iterable}\n * returned by calling a RecordIterator method would iterate over the User records and we don't have to deal with ListUsersResponse objects at all.\n * In either case, pagination will be automatically handled so we can iterate until there are no more responses or no more resources/records available.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20200501\")\n@lombok.RequiredArgsConstructor\npublic class NetworkLoadBalancerPaginators {\n\n private final NetworkLoadBalancer client;\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackendSets operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendSetsResponseIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses from the listBackendSets operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendSetsRecordIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendSetsResponse response) {\n return response.getBackendSetCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackends operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendsResponseIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses from the listBackends operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendsRecordIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendsResponse response) {\n return response.getBackendCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listListeners operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listListenersResponseIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses from the listListeners operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listListenersRecordIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListListenersResponse response) {\n return response.getListenerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancerHealths operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsResponseIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses from the listNetworkLoadBalancerHealths operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsRecordIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getNetworkLoadBalancerHealthCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancers operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersResponseIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses from the listNetworkLoadBalancers operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersRecordIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersResponse response) {\n return response.getNetworkLoadBalancerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersPolicies operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesResponseIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses from the listNetworkLoadBalancersPolicies operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesRecordIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getNetworkLoadBalancersPolicyCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersProtocols operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsResponseIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses from the listNetworkLoadBalancersProtocols operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsRecordIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getNetworkLoadBalancersProtocolCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestErrors operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestErrorsResponseIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses from the listWorkRequestErrors operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestErrorsRecordIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n ", "post_mask_code": "\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestErrorsResponse response) {\n return response.getWorkRequestErrorCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestLogs operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestLogsResponseIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses from the listWorkRequestLogs operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestLogsRecordIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestLogsResponse response) {\n return response.getWorkRequestLogEntryCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequests operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestsResponseIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses from the listWorkRequests operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestsRecordIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestsResponse response) {\n return response.getWorkRequestCollection().getItems();\n }\n });\n }\n}\n"} {"task_id": "Java_399", "language": "Java", "task_type": "empty", "source_file": "java/github/oracle/oci-java-sdk/bmc-networkloadbalancer/src/main/java/com/oracle/bmc/networkloadbalancer/NetworkLoadBalancerPaginators.java", "mask_start_position": 27680, "mask_end_position": 27680, "canonical_solution": "", "pre_mask_code": "package com.oracle.bmc.networkloadbalancer;\n\nimport com.oracle.bmc.networkloadbalancer.requests.*;\nimport com.oracle.bmc.networkloadbalancer.responses.*;\n\n/**\n * Collection of helper methods that can be used to provide an {@link java.lang.Iterable} interface\n * to any list operations of NetworkLoadBalancer where multiple pages of data may be fetched.\n * Two styles of iteration are supported:\n *\n *
    \n *
  • Iterating over the Response objects returned by the list operation. These are referred to as ResponseIterators, and the methods are suffixed with ResponseIterator. For example: listUsersResponseIterator
  • \n *
  • Iterating over the resources/records being listed. These are referred to as RecordIterators, and the methods are suffixed with RecordIterator. For example: listUsersRecordIterator
  • \n *
\n *\n * These iterables abstract away the need to write code to manually handle pagination via looping and using the page tokens.\n * They will automatically fetch more data from the service when required.\n *\n * As an example, if we were using the ListUsers operation in IdentityService, then the {@link java.lang.Iterable} returned by calling a\n * ResponseIterator method would iterate over the ListUsersResponse objects returned by each ListUsers call, whereas the {@link java.lang.Iterable}\n * returned by calling a RecordIterator method would iterate over the User records and we don't have to deal with ListUsersResponse objects at all.\n * In either case, pagination will be automatically handled so we can iterate until there are no more responses or no more resources/records available.\n */\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20200501\")\n@lombok.RequiredArgsConstructor\npublic class NetworkLoadBalancerPaginators {\n\n private final NetworkLoadBalancer client;\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackendSets operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendSetsResponseIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses from the listBackendSets operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSetSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendSetsRecordIterator(final ListBackendSetsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendSetsRequest.Builder get() {\n return ListBackendSetsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendSetsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendSetsRequest>() {\n\n @Override\n public ListBackendSetsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendSetsResponse apply(ListBackendSetsRequest request) {\n return client.listBackendSets(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendSetsResponse response) {\n return response.getBackendSetCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listBackends operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listBackendsResponseIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses from the listBackends operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.BackendSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listBackendsRecordIterator(final ListBackendsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListBackendsRequest.Builder get() {\n return ListBackendsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListBackendsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListBackendsRequest>() {\n\n @Override\n public ListBackendsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListBackendsResponse apply(ListBackendsRequest request) {\n return client.listBackends(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListBackendsResponse response) {\n return response.getBackendCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listListeners operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listListenersResponseIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses from the listListeners operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.ListenerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listListenersRecordIterator(final ListListenersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListListenersRequest.Builder get() {\n return ListListenersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListListenersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListListenersRequest>() {\n\n @Override\n public ListListenersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListListenersResponse apply(ListListenersRequest request) {\n return client.listListeners(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListListenersResponse response) {\n return response.getListenerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancerHealths operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsResponseIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses from the listNetworkLoadBalancerHealths operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerHealthSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancerHealthsRecordIterator(final ListNetworkLoadBalancerHealthsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest.Builder get() {\n return ListNetworkLoadBalancerHealthsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancerHealthsRequest>() {\n\n @Override\n public ListNetworkLoadBalancerHealthsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancerHealthsResponse apply(ListNetworkLoadBalancerHealthsRequest request) {\n return client.listNetworkLoadBalancerHealths(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancerHealthsResponse response) {\n return response.getNetworkLoadBalancerHealthCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancers operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersResponseIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses from the listNetworkLoadBalancers operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancerSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersRecordIterator(final ListNetworkLoadBalancersRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersRequest.Builder get() {\n return ListNetworkLoadBalancersRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersRequest>() {\n\n @Override\n public ListNetworkLoadBalancersRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersResponse apply(ListNetworkLoadBalancersRequest request) {\n return client.listNetworkLoadBalancers(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersResponse response) {\n return response.getNetworkLoadBalancerCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersPolicies operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesResponseIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses from the listNetworkLoadBalancersPolicies operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersPolicySummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersPoliciesRecordIterator(final ListNetworkLoadBalancersPoliciesRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest.Builder get() {\n return ListNetworkLoadBalancersPoliciesRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersPoliciesRequest>() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersPoliciesResponse apply(ListNetworkLoadBalancersPoliciesRequest request) {\n return client.listNetworkLoadBalancersPolicies(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersPoliciesResponse response) {\n return response.getNetworkLoadBalancersPolicyCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listNetworkLoadBalancersProtocols operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsResponseIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses from the listNetworkLoadBalancersProtocols operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.NetworkLoadBalancersProtocolSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listNetworkLoadBalancersProtocolsRecordIterator(final ListNetworkLoadBalancersProtocolsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest.Builder get() {\n return ListNetworkLoadBalancersProtocolsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListNetworkLoadBalancersProtocolsRequest>() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListNetworkLoadBalancersProtocolsResponse apply(ListNetworkLoadBalancersProtocolsRequest request) {\n return client.listNetworkLoadBalancersProtocols(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListNetworkLoadBalancersProtocolsResponse response) {\n return response.getNetworkLoadBalancersProtocolCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestErrors operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestErrorsResponseIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses from the listWorkRequestErrors operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestError} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestErrorsRecordIterator(final ListWorkRequestErrorsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestErrorsRequest.Builder get() {\n return ListWorkRequestErrorsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestErrorsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestErrorsRequest>() {\n\n @Override\n public ListWorkRequestErrorsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestErrorsResponse apply(ListWorkRequestErrorsRequest request) {\n return client.listWorkRequestErrors(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestErrorsResponse response) {\n return response.getWorkRequestErrorCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequestLogs operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestLogsResponseIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses from the listWorkRequestLogs operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestLogEntry} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestLogsRecordIterator(final ListWorkRequestLogsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestLogsRequest.Builder get() {\n return ListWorkRequestLogsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestLogsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestLogsRequest>() {\n\n @Override\n public ListWorkRequestLogsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestLogsResponse apply(ListWorkRequestLogsRequest request) {\n return client.listWorkRequestLogs(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestLogsResponse response) {\n return response.getWorkRequestLogEntryCollection().getItems();\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the responses received from the listWorkRequests operation. This iterable\n * will fetch more data from the server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the responses received from the service.\n */\n public Iterable listWorkRequestsResponseIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n });\n }\n\n /**\n * Creates a new iterable which will iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses from the listWorkRequests operation. This iterable will fetch more data from the\n * server as needed.\n *\n * @param request a request which can be sent to the service operation\n * @return an {@link java.lang.Iterable} which can be used to iterate over the {@link com.oracle.bmc.networkloadbalancer.model.WorkRequestSummary} objects\n * contained in responses received from the service.\n */\n public Iterable listWorkRequestsRecordIterator(final ListWorkRequestsRequest request) {\n return new com.oracle.bmc.paginator.internal.ResponseRecordIterable(new com.google.common.base.Supplier() {\n\n @Override\n public ListWorkRequestsRequest.Builder get() {\n return ListWorkRequestsRequest.builder().copy(request);\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public String apply(ListWorkRequestsResponse response) {\n return response.getOpcNextPage();\n }\n }, new com.google.common.base.Function, ListWorkRequestsRequest>() {\n\n @Override\n public ListWorkRequestsRequest apply(com.oracle.bmc.paginator.internal.RequestBuilderAndToken input) {\n if (input.getToken() == null) {\n return input.getRequestBuilder().build();\n } else {\n return input.getRequestBuilder().page(input.getToken().orNull()).build();\n }\n }\n }, new com.google.common.base.Function() {\n\n @Override\n public ListWorkRequestsResponse apply(ListWorkRequestsRequest request) {\n return client.listWorkRequests(request);\n }\n }, new com.google.common.base.Function>() {\n\n @Override\n public java.util.List apply(ListWorkRequestsResponse response) {\n return response.getWorkRequestCollection().getItems();\n }\n });\n }\n}\n"} {"task_id": "Java_400", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Protocoder/Protocoder/protocoder_apprunner/src/main/java/org/protocoderrunner/apprunner/api/widgets/PImageView.java", "mask_start_position": 1296, "mask_end_position": 1329, "canonical_solution": "public void setImage(Bitmap bmp) ", "pre_mask_code": "/*\n* Part of Protocoder http://www.protocoder.org\n* A prototyping platform for Android devices \n*\n* \n*/\npackage org.protocoderrunner.apprunner.api.widgets;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.Shader;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.widget.ImageView;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethod;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethodParam;\nimport org.protocoderrunner.apprunner.AppRunnerSettings;\nimport java.io.File;\n\npublic class PImageView extends ImageView implements PViewInterface {\n\n private Context mContext;\n\n public PImageView(Context context) {\n super(context);\n this.mContext = context;\n }\n\n @ProtoMethod(description = \"Sets an image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, false).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, false).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n }\n\n ", "post_mask_code": "{\n this.setImageBitmap(bmp);\n }\n\n @ProtoMethod(description = \"Sets a tiled image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setTiledImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, true).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, true).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n }\n\n public PImageView setRepeat() {\n BitmapDrawable bitmapDrawable = ((BitmapDrawable) this.getDrawable());\n Shader.TileMode mode = Shader.TileMode.REPEAT;\n bitmapDrawable.setTileModeXY(mode, mode);\n setBackground(bitmapDrawable);\n setImageBitmap(null);\n return this;\n }\n}\n"} {"task_id": "Java_401", "language": "Java", "task_type": "method_body", "source_file": "java/github/Protocoder/Protocoder/protocoder_apprunner/src/main/java/org/protocoderrunner/apprunner/api/widgets/PImageView.java", "mask_start_position": 1541, "mask_end_position": 1926, "canonical_solution": "{\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, true).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, true).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n }", "pre_mask_code": "/*\n* Part of Protocoder http://www.protocoder.org\n* A prototyping platform for Android devices \n*\n* \n*/\npackage org.protocoderrunner.apprunner.api.widgets;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.Shader;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.widget.ImageView;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethod;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethodParam;\nimport org.protocoderrunner.apprunner.AppRunnerSettings;\nimport java.io.File;\n\npublic class PImageView extends ImageView implements PViewInterface {\n\n private Context mContext;\n\n public PImageView(Context context) {\n super(context);\n this.mContext = context;\n }\n\n @ProtoMethod(description = \"Sets an image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, false).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, false).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n }\n\n public void setImage(Bitmap bmp) {\n this.setImageBitmap(bmp);\n }\n\n @ProtoMethod(description = \"Sets a tiled image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setTiledImage(String imagePath) ", "post_mask_code": "\n\n public PImageView setRepeat() {\n BitmapDrawable bitmapDrawable = ((BitmapDrawable) this.getDrawable());\n Shader.TileMode mode = Shader.TileMode.REPEAT;\n bitmapDrawable.setTileModeXY(mode, mode);\n setBackground(bitmapDrawable);\n setImageBitmap(null);\n return this;\n }\n}\n"} {"task_id": "Java_402", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Protocoder/Protocoder/protocoder_apprunner/src/main/java/org/protocoderrunner/apprunner/api/widgets/PImageView.java", "mask_start_position": 1542, "mask_end_position": 1899, "canonical_solution": "\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, true).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, true).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }", "pre_mask_code": "/*\n* Part of Protocoder http://www.protocoder.org\n* A prototyping platform for Android devices \n*\n* \n*/\npackage org.protocoderrunner.apprunner.api.widgets;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.Shader;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.widget.ImageView;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethod;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethodParam;\nimport org.protocoderrunner.apprunner.AppRunnerSettings;\nimport java.io.File;\n\npublic class PImageView extends ImageView implements PViewInterface {\n\n private Context mContext;\n\n public PImageView(Context context) {\n super(context);\n this.mContext = context;\n }\n\n @ProtoMethod(description = \"Sets an image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, false).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, false).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n }\n\n public void setImage(Bitmap bmp) {\n this.setImageBitmap(bmp);\n }\n\n @ProtoMethod(description = \"Sets a tiled image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setTiledImage(String imagePath) {", "post_mask_code": "\n return this;\n }\n\n public PImageView setRepeat() {\n BitmapDrawable bitmapDrawable = ((BitmapDrawable) this.getDrawable());\n Shader.TileMode mode = Shader.TileMode.REPEAT;\n bitmapDrawable.setTileModeXY(mode, mode);\n setBackground(bitmapDrawable);\n setImageBitmap(null);\n return this;\n }\n}\n"} {"task_id": "Java_403", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Protocoder/Protocoder/protocoder_apprunner/src/main/java/org/protocoderrunner/apprunner/api/widgets/PImageView.java", "mask_start_position": 1908, "mask_end_position": 1920, "canonical_solution": "return this;", "pre_mask_code": "/*\n* Part of Protocoder http://www.protocoder.org\n* A prototyping platform for Android devices \n*\n* \n*/\npackage org.protocoderrunner.apprunner.api.widgets;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.Shader;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.widget.ImageView;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethod;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethodParam;\nimport org.protocoderrunner.apprunner.AppRunnerSettings;\nimport java.io.File;\n\npublic class PImageView extends ImageView implements PViewInterface {\n\n private Context mContext;\n\n public PImageView(Context context) {\n super(context);\n this.mContext = context;\n }\n\n @ProtoMethod(description = \"Sets an image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, false).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, false).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n }\n\n public void setImage(Bitmap bmp) {\n this.setImageBitmap(bmp);\n }\n\n @ProtoMethod(description = \"Sets a tiled image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setTiledImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, true).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, true).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n ", "post_mask_code": "\n }\n\n public PImageView setRepeat() {\n BitmapDrawable bitmapDrawable = ((BitmapDrawable) this.getDrawable());\n Shader.TileMode mode = Shader.TileMode.REPEAT;\n bitmapDrawable.setTileModeXY(mode, mode);\n setBackground(bitmapDrawable);\n setImageBitmap(null);\n return this;\n }\n}\n"} {"task_id": "Java_404", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Protocoder/Protocoder/protocoder_apprunner/src/main/java/org/protocoderrunner/apprunner/api/widgets/PImageView.java", "mask_start_position": 1925, "mask_end_position": 1926, "canonical_solution": "}", "pre_mask_code": "/*\n* Part of Protocoder http://www.protocoder.org\n* A prototyping platform for Android devices \n*\n* \n*/\npackage org.protocoderrunner.apprunner.api.widgets;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.Shader;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.widget.ImageView;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethod;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethodParam;\nimport org.protocoderrunner.apprunner.AppRunnerSettings;\nimport java.io.File;\n\npublic class PImageView extends ImageView implements PViewInterface {\n\n private Context mContext;\n\n public PImageView(Context context) {\n super(context);\n this.mContext = context;\n }\n\n @ProtoMethod(description = \"Sets an image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, false).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, false).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n }\n\n public void setImage(Bitmap bmp) {\n this.setImageBitmap(bmp);\n }\n\n @ProtoMethod(description = \"Sets a tiled image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setTiledImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, true).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, true).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n ", "post_mask_code": "\n\n public PImageView setRepeat() {\n BitmapDrawable bitmapDrawable = ((BitmapDrawable) this.getDrawable());\n Shader.TileMode mode = Shader.TileMode.REPEAT;\n bitmapDrawable.setTileModeXY(mode, mode);\n setBackground(bitmapDrawable);\n setImageBitmap(null);\n return this;\n }\n}\n"} {"task_id": "Java_405", "language": "Java", "task_type": "single_line", "source_file": "java/github/Protocoder/Protocoder/protocoder_apprunner/src/main/java/org/protocoderrunner/apprunner/api/widgets/PImageView.java", "mask_start_position": 2014, "mask_end_position": 2042, "canonical_solution": "awable) this.getDrawable());", "pre_mask_code": "/*\n* Part of Protocoder http://www.protocoder.org\n* A prototyping platform for Android devices \n*\n* \n*/\npackage org.protocoderrunner.apprunner.api.widgets;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.Shader;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.widget.ImageView;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethod;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethodParam;\nimport org.protocoderrunner.apprunner.AppRunnerSettings;\nimport java.io.File;\n\npublic class PImageView extends ImageView implements PViewInterface {\n\n private Context mContext;\n\n public PImageView(Context context) {\n super(context);\n this.mContext = context;\n }\n\n @ProtoMethod(description = \"Sets an image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, false).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, false).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n }\n\n public void setImage(Bitmap bmp) {\n this.setImageBitmap(bmp);\n }\n\n @ProtoMethod(description = \"Sets a tiled image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setTiledImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, true).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, true).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n }\n\n public PImageView setRepeat() {\n BitmapDrawable bitmapDrawable = ((BitmapDr", "post_mask_code": "\n Shader.TileMode mode = Shader.TileMode.REPEAT;\n bitmapDrawable.setTileModeXY(mode, mode);\n setBackground(bitmapDrawable);\n setImageBitmap(null);\n return this;\n }\n}\n"} {"task_id": "Java_406", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Protocoder/Protocoder/protocoder_apprunner/src/main/java/org/protocoderrunner/apprunner/api/widgets/PImageView.java", "mask_start_position": 1551, "mask_end_position": 1899, "canonical_solution": "if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, true).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, true).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }", "pre_mask_code": "/*\n* Part of Protocoder http://www.protocoder.org\n* A prototyping platform for Android devices \n*\n* \n*/\npackage org.protocoderrunner.apprunner.api.widgets;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.Shader;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.widget.ImageView;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethod;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethodParam;\nimport org.protocoderrunner.apprunner.AppRunnerSettings;\nimport java.io.File;\n\npublic class PImageView extends ImageView implements PViewInterface {\n\n private Context mContext;\n\n public PImageView(Context context) {\n super(context);\n this.mContext = context;\n }\n\n @ProtoMethod(description = \"Sets an image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, false).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, false).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n }\n\n public void setImage(Bitmap bmp) {\n this.setImageBitmap(bmp);\n }\n\n @ProtoMethod(description = \"Sets a tiled image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setTiledImage(String imagePath) {\n ", "post_mask_code": "\n return this;\n }\n\n public PImageView setRepeat() {\n BitmapDrawable bitmapDrawable = ((BitmapDrawable) this.getDrawable());\n Shader.TileMode mode = Shader.TileMode.REPEAT;\n bitmapDrawable.setTileModeXY(mode, mode);\n setBackground(bitmapDrawable);\n setImageBitmap(null);\n return this;\n }\n}\n"} {"task_id": "Java_407", "language": "Java", "task_type": "empty", "source_file": "java/github/Protocoder/Protocoder/protocoder_apprunner/src/main/java/org/protocoderrunner/apprunner/api/widgets/PImageView.java", "mask_start_position": 461, "mask_end_position": 461, "canonical_solution": "", "pre_mask_code": "/*\n* Part of Protocoder http://www.protocoder.org\n* A prototyping platform for Android devices \n*\n* \n*/\npackage org.protocoderrunner.apprunner.api.widgets;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.Shader;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.widget.ImageView;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethod;\nimport org.protocoderrunner.apidoc.annotation.ProtoMethodParam;\nimp", "post_mask_code": "ort org.protocoderrunner.apprunner.AppRunnerSettings;\nimport java.io.File;\n\npublic class PImageView extends ImageView implements PViewInterface {\n\n private Context mContext;\n\n public PImageView(Context context) {\n super(context);\n this.mContext = context;\n }\n\n @ProtoMethod(description = \"Sets an image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, false).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, false).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n }\n\n public void setImage(Bitmap bmp) {\n this.setImageBitmap(bmp);\n }\n\n @ProtoMethod(description = \"Sets a tiled image\", example = \"\")\n @ProtoMethodParam(params = { \"imageName\" })\n public PImageView setTiledImage(String imagePath) {\n if (imagePath.startsWith(\"http\")) {\n // Add image asynchronously\n new PUIGeneric.DownloadImageTask(this, true).execute(imagePath);\n } else {\n // Add the image\n new PUIGeneric.SetImageTask(this, true).execute(AppRunnerSettings.get().project.getStoragePath() + File.separator + imagePath);\n }\n return this;\n }\n\n public PImageView setRepeat() {\n BitmapDrawable bitmapDrawable = ((BitmapDrawable) this.getDrawable());\n Shader.TileMode mode = Shader.TileMode.REPEAT;\n bitmapDrawable.setTileModeXY(mode, mode);\n setBackground(bitmapDrawable);\n setImageBitmap(null);\n return this;\n }\n}\n"} {"task_id": "Java_408", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/org.eclipse.persistence.core/src/main/java/org/eclipse/persistence/internal/codegen/AttributeDefinition.java", "mask_start_position": 1580, "mask_end_position": 1649, "canonical_solution": "protected void adjustTypeNames(Map> typeNameMap) ", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.internal.codegen;\n\nimport java.util.*;\n\n/**\n * INTERNAL:\n *

Purpose: Model an attribute for code generation purposes.\n *\n * @since TopLink 3.0\n * @author James Sutherland\n */\npublic abstract class AttributeDefinition extends CodeDefinition {\n\n protected String initialValue;\n\n protected AttributeDefinition() {\n }\n\n /**\n * Parses the initial value, removing the package name for each type\n * (and adding the appropriate import) if the type is\n * unambiguous.\n */\n private void adjustInitialValue(Map> typeNameMap) {\n if (getInitialValue() == null) {\n return;\n }\n StringBuilder initialValue = new StringBuilder(getInitialValue());\n Set typeNames = parseForTypeNames(initialValue.toString());\n for (Iterator i = typeNames.iterator(); i.hasNext(); ) {\n String typeName = i.next();\n String adjustedTypeName = adjustTypeName(typeName, typeNameMap);\n if (!typeName.equals(adjustedTypeName)) {\n int typeNameStartIndex = initialValue.toString().indexOf(typeName);\n while (typeNameStartIndex != -1) {\n initialValue.replace(typeNameStartIndex, typeNameStartIndex + typeName.length(), adjustedTypeName);\n typeNameStartIndex = initialValue.toString().indexOf(typeName);\n }\n }\n }\n setInitialValue(initialValue.toString());\n }\n\n ", "post_mask_code": "{\n adjustInitialValue(typeNameMap);\n }\n\n public String getInitialValue() {\n return initialValue;\n }\n\n protected abstract String getTypeName();\n\n /**\n * Used for calculating imports. @see org.eclipse.persistence.internal.codegen.ClassDefinition#calculateImports()\n */\n protected void putTypeNamesInMap(Map> typeNameMap) {\n putTypeNameInMap(getTypeName(), typeNameMap);\n for (Iterator i = parseForTypeNames(getInitialValue()).iterator(); i.hasNext(); ) {\n putTypeNameInMap(i.next(), typeNameMap);\n }\n }\n\n public void setInitialValue(String initialValue) {\n this.initialValue = initialValue;\n }\n\n @Override\n public void writeBody(CodeGenerator generator) {\n generator.writeType(getTypeName());\n generator.writeType(\" \");\n generator.write(getName());\n if (getInitialValue() != null) {\n generator.write(\" = \");\n generator.write(getInitialValue());\n }\n generator.write(\";\");\n }\n}\n"} {"task_id": "Java_409", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/org.eclipse.persistence.core/src/main/java/org/eclipse/persistence/internal/codegen/AttributeDefinition.java", "mask_start_position": 2308, "mask_end_position": 2357, "canonical_solution": "{\n this.initialValue = initialValue;\n }", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.internal.codegen;\n\nimport java.util.*;\n\n/**\n * INTERNAL:\n *

Purpose: Model an attribute for code generation purposes.\n *\n * @since TopLink 3.0\n * @author James Sutherland\n */\npublic abstract class AttributeDefinition extends CodeDefinition {\n\n protected String initialValue;\n\n protected AttributeDefinition() {\n }\n\n /**\n * Parses the initial value, removing the package name for each type\n * (and adding the appropriate import) if the type is\n * unambiguous.\n */\n private void adjustInitialValue(Map> typeNameMap) {\n if (getInitialValue() == null) {\n return;\n }\n StringBuilder initialValue = new StringBuilder(getInitialValue());\n Set typeNames = parseForTypeNames(initialValue.toString());\n for (Iterator i = typeNames.iterator(); i.hasNext(); ) {\n String typeName = i.next();\n String adjustedTypeName = adjustTypeName(typeName, typeNameMap);\n if (!typeName.equals(adjustedTypeName)) {\n int typeNameStartIndex = initialValue.toString().indexOf(typeName);\n while (typeNameStartIndex != -1) {\n initialValue.replace(typeNameStartIndex, typeNameStartIndex + typeName.length(), adjustedTypeName);\n typeNameStartIndex = initialValue.toString().indexOf(typeName);\n }\n }\n }\n setInitialValue(initialValue.toString());\n }\n\n protected void adjustTypeNames(Map> typeNameMap) {\n adjustInitialValue(typeNameMap);\n }\n\n public String getInitialValue() {\n return initialValue;\n }\n\n protected abstract String getTypeName();\n\n /**\n * Used for calculating imports. @see org.eclipse.persistence.internal.codegen.ClassDefinition#calculateImports()\n */\n protected void putTypeNamesInMap(Map> typeNameMap) {\n putTypeNameInMap(getTypeName(), typeNameMap);\n for (Iterator i = parseForTypeNames(getInitialValue()).iterator(); i.hasNext(); ) {\n putTypeNameInMap(i.next(), typeNameMap);\n }\n }\n\n public void setInitialValue(String initialValue) ", "post_mask_code": "\n\n @Override\n public void writeBody(CodeGenerator generator) {\n generator.writeType(getTypeName());\n generator.writeType(\" \");\n generator.write(getName());\n if (getInitialValue() != null) {\n generator.write(\" = \");\n generator.write(getInitialValue());\n }\n generator.write(\";\");\n }\n}\n"} {"task_id": "Java_410", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/org.eclipse.persistence.core/src/main/java/org/eclipse/persistence/internal/codegen/AttributeDefinition.java", "mask_start_position": 671, "mask_end_position": 817, "canonical_solution": "\n if (getInitialValue() == null) {\n return;\n }\n StringBuilder initialValue = new StringBuilder(getInitialValue());", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.internal.codegen;\n\nimport java.util.*;\n\n/**\n * INTERNAL:\n *

Purpose: Model an attribute for code generation purposes.\n *\n * @since TopLink 3.0\n * @author James Sutherland\n */\npublic abstract class AttributeDefinition extends CodeDefinition {\n\n protected String initialValue;\n\n protected AttributeDefinition() {\n }\n\n /**\n * Parses the initial value, removing the package name for each type\n * (and adding the appropriate import) if the type is\n * unambiguous.\n */\n private void adjustInitialValue(Map> typeNameMap) {", "post_mask_code": "\n Set typeNames = parseForTypeNames(initialValue.toString());\n for (Iterator i = typeNames.iterator(); i.hasNext(); ) {\n String typeName = i.next();\n String adjustedTypeName = adjustTypeName(typeName, typeNameMap);\n if (!typeName.equals(adjustedTypeName)) {\n int typeNameStartIndex = initialValue.toString().indexOf(typeName);\n while (typeNameStartIndex != -1) {\n initialValue.replace(typeNameStartIndex, typeNameStartIndex + typeName.length(), adjustedTypeName);\n typeNameStartIndex = initialValue.toString().indexOf(typeName);\n }\n }\n }\n setInitialValue(initialValue.toString());\n }\n\n protected void adjustTypeNames(Map> typeNameMap) {\n adjustInitialValue(typeNameMap);\n }\n\n public String getInitialValue() {\n return initialValue;\n }\n\n protected abstract String getTypeName();\n\n /**\n * Used for calculating imports. @see org.eclipse.persistence.internal.codegen.ClassDefinition#calculateImports()\n */\n protected void putTypeNamesInMap(Map> typeNameMap) {\n putTypeNameInMap(getTypeName(), typeNameMap);\n for (Iterator i = parseForTypeNames(getInitialValue()).iterator(); i.hasNext(); ) {\n putTypeNameInMap(i.next(), typeNameMap);\n }\n }\n\n public void setInitialValue(String initialValue) {\n this.initialValue = initialValue;\n }\n\n @Override\n public void writeBody(CodeGenerator generator) {\n generator.writeType(getTypeName());\n generator.writeType(\" \");\n generator.write(getName());\n if (getInitialValue() != null) {\n generator.write(\" = \");\n generator.write(getInitialValue());\n }\n generator.write(\";\");\n }\n}\n"} {"task_id": "Java_411", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/org.eclipse.persistence.core/src/main/java/org/eclipse/persistence/internal/codegen/AttributeDefinition.java", "mask_start_position": 826, "mask_end_position": 1518, "canonical_solution": "Set typeNames = parseForTypeNames(initialValue.toString());\n for (Iterator i = typeNames.iterator(); i.hasNext(); ) {\n String typeName = i.next();\n String adjustedTypeName = adjustTypeName(typeName, typeNameMap);\n if (!typeName.equals(adjustedTypeName)) {\n int typeNameStartIndex = initialValue.toString().indexOf(typeName);\n while (typeNameStartIndex != -1) {\n initialValue.replace(typeNameStartIndex, typeNameStartIndex + typeName.length(), adjustedTypeName);\n typeNameStartIndex = initialValue.toString().indexOf(typeName);\n }\n }\n }", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.internal.codegen;\n\nimport java.util.*;\n\n/**\n * INTERNAL:\n *

Purpose: Model an attribute for code generation purposes.\n *\n * @since TopLink 3.0\n * @author James Sutherland\n */\npublic abstract class AttributeDefinition extends CodeDefinition {\n\n protected String initialValue;\n\n protected AttributeDefinition() {\n }\n\n /**\n * Parses the initial value, removing the package name for each type\n * (and adding the appropriate import) if the type is\n * unambiguous.\n */\n private void adjustInitialValue(Map> typeNameMap) {\n if (getInitialValue() == null) {\n return;\n }\n StringBuilder initialValue = new StringBuilder(getInitialValue());\n ", "post_mask_code": "\n setInitialValue(initialValue.toString());\n }\n\n protected void adjustTypeNames(Map> typeNameMap) {\n adjustInitialValue(typeNameMap);\n }\n\n public String getInitialValue() {\n return initialValue;\n }\n\n protected abstract String getTypeName();\n\n /**\n * Used for calculating imports. @see org.eclipse.persistence.internal.codegen.ClassDefinition#calculateImports()\n */\n protected void putTypeNamesInMap(Map> typeNameMap) {\n putTypeNameInMap(getTypeName(), typeNameMap);\n for (Iterator i = parseForTypeNames(getInitialValue()).iterator(); i.hasNext(); ) {\n putTypeNameInMap(i.next(), typeNameMap);\n }\n }\n\n public void setInitialValue(String initialValue) {\n this.initialValue = initialValue;\n }\n\n @Override\n public void writeBody(CodeGenerator generator) {\n generator.writeType(getTypeName());\n generator.writeType(\" \");\n generator.write(getName());\n if (getInitialValue() != null) {\n generator.write(\" = \");\n generator.write(getInitialValue());\n }\n generator.write(\";\");\n }\n}\n"} {"task_id": "Java_412", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/org.eclipse.persistence.core/src/main/java/org/eclipse/persistence/internal/codegen/AttributeDefinition.java", "mask_start_position": 1527, "mask_end_position": 1574, "canonical_solution": "setInitialValue(initialValue.toString());\n }", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.internal.codegen;\n\nimport java.util.*;\n\n/**\n * INTERNAL:\n *

Purpose: Model an attribute for code generation purposes.\n *\n * @since TopLink 3.0\n * @author James Sutherland\n */\npublic abstract class AttributeDefinition extends CodeDefinition {\n\n protected String initialValue;\n\n protected AttributeDefinition() {\n }\n\n /**\n * Parses the initial value, removing the package name for each type\n * (and adding the appropriate import) if the type is\n * unambiguous.\n */\n private void adjustInitialValue(Map> typeNameMap) {\n if (getInitialValue() == null) {\n return;\n }\n StringBuilder initialValue = new StringBuilder(getInitialValue());\n Set typeNames = parseForTypeNames(initialValue.toString());\n for (Iterator i = typeNames.iterator(); i.hasNext(); ) {\n String typeName = i.next();\n String adjustedTypeName = adjustTypeName(typeName, typeNameMap);\n if (!typeName.equals(adjustedTypeName)) {\n int typeNameStartIndex = initialValue.toString().indexOf(typeName);\n while (typeNameStartIndex != -1) {\n initialValue.replace(typeNameStartIndex, typeNameStartIndex + typeName.length(), adjustedTypeName);\n typeNameStartIndex = initialValue.toString().indexOf(typeName);\n }\n }\n }\n ", "post_mask_code": "\n\n protected void adjustTypeNames(Map> typeNameMap) {\n adjustInitialValue(typeNameMap);\n }\n\n public String getInitialValue() {\n return initialValue;\n }\n\n protected abstract String getTypeName();\n\n /**\n * Used for calculating imports. @see org.eclipse.persistence.internal.codegen.ClassDefinition#calculateImports()\n */\n protected void putTypeNamesInMap(Map> typeNameMap) {\n putTypeNameInMap(getTypeName(), typeNameMap);\n for (Iterator i = parseForTypeNames(getInitialValue()).iterator(); i.hasNext(); ) {\n putTypeNameInMap(i.next(), typeNameMap);\n }\n }\n\n public void setInitialValue(String initialValue) {\n this.initialValue = initialValue;\n }\n\n @Override\n public void writeBody(CodeGenerator generator) {\n generator.writeType(getTypeName());\n generator.writeType(\" \");\n generator.write(getName());\n if (getInitialValue() != null) {\n generator.write(\" = \");\n generator.write(getInitialValue());\n }\n generator.write(\";\");\n }\n}\n"} {"task_id": "Java_413", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/org.eclipse.persistence.core/src/main/java/org/eclipse/persistence/internal/codegen/AttributeDefinition.java", "mask_start_position": 1756, "mask_end_position": 1765, "canonical_solution": "ialValue;", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.internal.codegen;\n\nimport java.util.*;\n\n/**\n * INTERNAL:\n *

Purpose: Model an attribute for code generation purposes.\n *\n * @since TopLink 3.0\n * @author James Sutherland\n */\npublic abstract class AttributeDefinition extends CodeDefinition {\n\n protected String initialValue;\n\n protected AttributeDefinition() {\n }\n\n /**\n * Parses the initial value, removing the package name for each type\n * (and adding the appropriate import) if the type is\n * unambiguous.\n */\n private void adjustInitialValue(Map> typeNameMap) {\n if (getInitialValue() == null) {\n return;\n }\n StringBuilder initialValue = new StringBuilder(getInitialValue());\n Set typeNames = parseForTypeNames(initialValue.toString());\n for (Iterator i = typeNames.iterator(); i.hasNext(); ) {\n String typeName = i.next();\n String adjustedTypeName = adjustTypeName(typeName, typeNameMap);\n if (!typeName.equals(adjustedTypeName)) {\n int typeNameStartIndex = initialValue.toString().indexOf(typeName);\n while (typeNameStartIndex != -1) {\n initialValue.replace(typeNameStartIndex, typeNameStartIndex + typeName.length(), adjustedTypeName);\n typeNameStartIndex = initialValue.toString().indexOf(typeName);\n }\n }\n }\n setInitialValue(initialValue.toString());\n }\n\n protected void adjustTypeNames(Map> typeNameMap) {\n adjustInitialValue(typeNameMap);\n }\n\n public String getInitialValue() {\n return init", "post_mask_code": "\n }\n\n protected abstract String getTypeName();\n\n /**\n * Used for calculating imports. @see org.eclipse.persistence.internal.codegen.ClassDefinition#calculateImports()\n */\n protected void putTypeNamesInMap(Map> typeNameMap) {\n putTypeNameInMap(getTypeName(), typeNameMap);\n for (Iterator i = parseForTypeNames(getInitialValue()).iterator(); i.hasNext(); ) {\n putTypeNameInMap(i.next(), typeNameMap);\n }\n }\n\n public void setInitialValue(String initialValue) {\n this.initialValue = initialValue;\n }\n\n @Override\n public void writeBody(CodeGenerator generator) {\n generator.writeType(getTypeName());\n generator.writeType(\" \");\n generator.write(getName());\n if (getInitialValue() != null) {\n generator.write(\" = \");\n generator.write(getInitialValue());\n }\n generator.write(\";\");\n }\n}\n"} {"task_id": "Java_414", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/org.eclipse.persistence.core/src/main/java/org/eclipse/persistence/internal/codegen/AttributeDefinition.java", "mask_start_position": 1958, "mask_end_position": 2253, "canonical_solution": "protected void putTypeNamesInMap(Map> typeNameMap) {\n putTypeNameInMap(getTypeName(), typeNameMap);\n for (Iterator i = parseForTypeNames(getInitialValue()).iterator(); i.hasNext(); ) {\n putTypeNameInMap(i.next(), typeNameMap);\n }\n }", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.internal.codegen;\n\nimport java.util.*;\n\n/**\n * INTERNAL:\n *

Purpose: Model an attribute for code generation purposes.\n *\n * @since TopLink 3.0\n * @author James Sutherland\n */\npublic abstract class AttributeDefinition extends CodeDefinition {\n\n protected String initialValue;\n\n protected AttributeDefinition() {\n }\n\n /**\n * Parses the initial value, removing the package name for each type\n * (and adding the appropriate import) if the type is\n * unambiguous.\n */\n private void adjustInitialValue(Map> typeNameMap) {\n if (getInitialValue() == null) {\n return;\n }\n StringBuilder initialValue = new StringBuilder(getInitialValue());\n Set typeNames = parseForTypeNames(initialValue.toString());\n for (Iterator i = typeNames.iterator(); i.hasNext(); ) {\n String typeName = i.next();\n String adjustedTypeName = adjustTypeName(typeName, typeNameMap);\n if (!typeName.equals(adjustedTypeName)) {\n int typeNameStartIndex = initialValue.toString().indexOf(typeName);\n while (typeNameStartIndex != -1) {\n initialValue.replace(typeNameStartIndex, typeNameStartIndex + typeName.length(), adjustedTypeName);\n typeNameStartIndex = initialValue.toString().indexOf(typeName);\n }\n }\n }\n setInitialValue(initialValue.toString());\n }\n\n protected void adjustTypeNames(Map> typeNameMap) {\n adjustInitialValue(typeNameMap);\n }\n\n public String getInitialValue() {\n return initialValue;\n }\n\n protected abstract String getTypeName();\n\n /**\n * Used for calculating imports. @see org.eclipse.persistence.internal.codegen.ClassDefinition#calculateImports()\n */\n ", "post_mask_code": "\n\n public void setInitialValue(String initialValue) {\n this.initialValue = initialValue;\n }\n\n @Override\n public void writeBody(CodeGenerator generator) {\n generator.writeType(getTypeName());\n generator.writeType(\" \");\n generator.write(getName());\n if (getInitialValue() != null) {\n generator.write(\" = \");\n generator.write(getInitialValue());\n }\n generator.write(\";\");\n }\n}\n"} {"task_id": "Java_415", "language": "Java", "task_type": "if_statement", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/org.eclipse.persistence.core/src/main/java/org/eclipse/persistence/internal/codegen/AttributeDefinition.java", "mask_start_position": 2548, "mask_end_position": 2674, "canonical_solution": "if (getInitialValue() != null) {\n generator.write(\" = \");\n generator.write(getInitialValue());\n }", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.internal.codegen;\n\nimport java.util.*;\n\n/**\n * INTERNAL:\n *

Purpose: Model an attribute for code generation purposes.\n *\n * @since TopLink 3.0\n * @author James Sutherland\n */\npublic abstract class AttributeDefinition extends CodeDefinition {\n\n protected String initialValue;\n\n protected AttributeDefinition() {\n }\n\n /**\n * Parses the initial value, removing the package name for each type\n * (and adding the appropriate import) if the type is\n * unambiguous.\n */\n private void adjustInitialValue(Map> typeNameMap) {\n if (getInitialValue() == null) {\n return;\n }\n StringBuilder initialValue = new StringBuilder(getInitialValue());\n Set typeNames = parseForTypeNames(initialValue.toString());\n for (Iterator i = typeNames.iterator(); i.hasNext(); ) {\n String typeName = i.next();\n String adjustedTypeName = adjustTypeName(typeName, typeNameMap);\n if (!typeName.equals(adjustedTypeName)) {\n int typeNameStartIndex = initialValue.toString().indexOf(typeName);\n while (typeNameStartIndex != -1) {\n initialValue.replace(typeNameStartIndex, typeNameStartIndex + typeName.length(), adjustedTypeName);\n typeNameStartIndex = initialValue.toString().indexOf(typeName);\n }\n }\n }\n setInitialValue(initialValue.toString());\n }\n\n protected void adjustTypeNames(Map> typeNameMap) {\n adjustInitialValue(typeNameMap);\n }\n\n public String getInitialValue() {\n return initialValue;\n }\n\n protected abstract String getTypeName();\n\n /**\n * Used for calculating imports. @see org.eclipse.persistence.internal.codegen.ClassDefinition#calculateImports()\n */\n protected void putTypeNamesInMap(Map> typeNameMap) {\n putTypeNameInMap(getTypeName(), typeNameMap);\n for (Iterator i = parseForTypeNames(getInitialValue()).iterator(); i.hasNext(); ) {\n putTypeNameInMap(i.next(), typeNameMap);\n }\n }\n\n public void setInitialValue(String initialValue) {\n this.initialValue = initialValue;\n }\n\n @Override\n public void writeBody(CodeGenerator generator) {\n generator.writeType(getTypeName());\n generator.writeType(\" \");\n generator.write(getName());\n ", "post_mask_code": "\n generator.write(\";\");\n }\n}\n"} {"task_id": "Java_416", "language": "Java", "task_type": "for_statement", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/org.eclipse.persistence.core/src/main/java/org/eclipse/persistence/internal/codegen/AttributeDefinition.java", "mask_start_position": 2093, "mask_end_position": 2247, "canonical_solution": "for (Iterator i = parseForTypeNames(getInitialValue()).iterator(); i.hasNext(); ) {\n putTypeNameInMap(i.next(), typeNameMap);\n }", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.internal.codegen;\n\nimport java.util.*;\n\n/**\n * INTERNAL:\n *

Purpose: Model an attribute for code generation purposes.\n *\n * @since TopLink 3.0\n * @author James Sutherland\n */\npublic abstract class AttributeDefinition extends CodeDefinition {\n\n protected String initialValue;\n\n protected AttributeDefinition() {\n }\n\n /**\n * Parses the initial value, removing the package name for each type\n * (and adding the appropriate import) if the type is\n * unambiguous.\n */\n private void adjustInitialValue(Map> typeNameMap) {\n if (getInitialValue() == null) {\n return;\n }\n StringBuilder initialValue = new StringBuilder(getInitialValue());\n Set typeNames = parseForTypeNames(initialValue.toString());\n for (Iterator i = typeNames.iterator(); i.hasNext(); ) {\n String typeName = i.next();\n String adjustedTypeName = adjustTypeName(typeName, typeNameMap);\n if (!typeName.equals(adjustedTypeName)) {\n int typeNameStartIndex = initialValue.toString().indexOf(typeName);\n while (typeNameStartIndex != -1) {\n initialValue.replace(typeNameStartIndex, typeNameStartIndex + typeName.length(), adjustedTypeName);\n typeNameStartIndex = initialValue.toString().indexOf(typeName);\n }\n }\n }\n setInitialValue(initialValue.toString());\n }\n\n protected void adjustTypeNames(Map> typeNameMap) {\n adjustInitialValue(typeNameMap);\n }\n\n public String getInitialValue() {\n return initialValue;\n }\n\n protected abstract String getTypeName();\n\n /**\n * Used for calculating imports. @see org.eclipse.persistence.internal.codegen.ClassDefinition#calculateImports()\n */\n protected void putTypeNamesInMap(Map> typeNameMap) {\n putTypeNameInMap(getTypeName(), typeNameMap);\n ", "post_mask_code": "\n }\n\n public void setInitialValue(String initialValue) {\n this.initialValue = initialValue;\n }\n\n @Override\n public void writeBody(CodeGenerator generator) {\n generator.writeType(getTypeName());\n generator.writeType(\" \");\n generator.write(getName());\n if (getInitialValue() != null) {\n generator.write(\" = \");\n generator.write(getInitialValue());\n }\n generator.write(\";\");\n }\n}\n"} {"task_id": "Java_417", "language": "Java", "task_type": "while_statement", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/org.eclipse.persistence.core/src/main/java/org/eclipse/persistence/internal/codegen/AttributeDefinition.java", "mask_start_position": 1238, "mask_end_position": 1494, "canonical_solution": "while (typeNameStartIndex != -1) {\n initialValue.replace(typeNameStartIndex, typeNameStartIndex + typeName.length(), adjustedTypeName);\n typeNameStartIndex = initialValue.toString().indexOf(typeName);\n }", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.internal.codegen;\n\nimport java.util.*;\n\n/**\n * INTERNAL:\n *

Purpose: Model an attribute for code generation purposes.\n *\n * @since TopLink 3.0\n * @author James Sutherland\n */\npublic abstract class AttributeDefinition extends CodeDefinition {\n\n protected String initialValue;\n\n protected AttributeDefinition() {\n }\n\n /**\n * Parses the initial value, removing the package name for each type\n * (and adding the appropriate import) if the type is\n * unambiguous.\n */\n private void adjustInitialValue(Map> typeNameMap) {\n if (getInitialValue() == null) {\n return;\n }\n StringBuilder initialValue = new StringBuilder(getInitialValue());\n Set typeNames = parseForTypeNames(initialValue.toString());\n for (Iterator i = typeNames.iterator(); i.hasNext(); ) {\n String typeName = i.next();\n String adjustedTypeName = adjustTypeName(typeName, typeNameMap);\n if (!typeName.equals(adjustedTypeName)) {\n int typeNameStartIndex = initialValue.toString().indexOf(typeName);\n ", "post_mask_code": "\n }\n }\n setInitialValue(initialValue.toString());\n }\n\n protected void adjustTypeNames(Map> typeNameMap) {\n adjustInitialValue(typeNameMap);\n }\n\n public String getInitialValue() {\n return initialValue;\n }\n\n protected abstract String getTypeName();\n\n /**\n * Used for calculating imports. @see org.eclipse.persistence.internal.codegen.ClassDefinition#calculateImports()\n */\n protected void putTypeNamesInMap(Map> typeNameMap) {\n putTypeNameInMap(getTypeName(), typeNameMap);\n for (Iterator i = parseForTypeNames(getInitialValue()).iterator(); i.hasNext(); ) {\n putTypeNameInMap(i.next(), typeNameMap);\n }\n }\n\n public void setInitialValue(String initialValue) {\n this.initialValue = initialValue;\n }\n\n @Override\n public void writeBody(CodeGenerator generator) {\n generator.writeType(getTypeName());\n generator.writeType(\" \");\n generator.write(getName());\n if (getInitialValue() != null) {\n generator.write(\" = \");\n generator.write(getInitialValue());\n }\n generator.write(\";\");\n }\n}\n"} {"task_id": "Java_418", "language": "Java", "task_type": "empty", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/org.eclipse.persistence.core/src/main/java/org/eclipse/persistence/internal/codegen/AttributeDefinition.java", "mask_start_position": 5, "mask_end_position": 5, "canonical_solution": "", "pre_mask_code": "// Or", "post_mask_code": "acle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.internal.codegen;\n\nimport java.util.*;\n\n/**\n * INTERNAL:\n *

Purpose: Model an attribute for code generation purposes.\n *\n * @since TopLink 3.0\n * @author James Sutherland\n */\npublic abstract class AttributeDefinition extends CodeDefinition {\n\n protected String initialValue;\n\n protected AttributeDefinition() {\n }\n\n /**\n * Parses the initial value, removing the package name for each type\n * (and adding the appropriate import) if the type is\n * unambiguous.\n */\n private void adjustInitialValue(Map> typeNameMap) {\n if (getInitialValue() == null) {\n return;\n }\n StringBuilder initialValue = new StringBuilder(getInitialValue());\n Set typeNames = parseForTypeNames(initialValue.toString());\n for (Iterator i = typeNames.iterator(); i.hasNext(); ) {\n String typeName = i.next();\n String adjustedTypeName = adjustTypeName(typeName, typeNameMap);\n if (!typeName.equals(adjustedTypeName)) {\n int typeNameStartIndex = initialValue.toString().indexOf(typeName);\n while (typeNameStartIndex != -1) {\n initialValue.replace(typeNameStartIndex, typeNameStartIndex + typeName.length(), adjustedTypeName);\n typeNameStartIndex = initialValue.toString().indexOf(typeName);\n }\n }\n }\n setInitialValue(initialValue.toString());\n }\n\n protected void adjustTypeNames(Map> typeNameMap) {\n adjustInitialValue(typeNameMap);\n }\n\n public String getInitialValue() {\n return initialValue;\n }\n\n protected abstract String getTypeName();\n\n /**\n * Used for calculating imports. @see org.eclipse.persistence.internal.codegen.ClassDefinition#calculateImports()\n */\n protected void putTypeNamesInMap(Map> typeNameMap) {\n putTypeNameInMap(getTypeName(), typeNameMap);\n for (Iterator i = parseForTypeNames(getInitialValue()).iterator(); i.hasNext(); ) {\n putTypeNameInMap(i.next(), typeNameMap);\n }\n }\n\n public void setInitialValue(String initialValue) {\n this.initialValue = initialValue;\n }\n\n @Override\n public void writeBody(CodeGenerator generator) {\n generator.writeType(getTypeName());\n generator.writeType(\" \");\n generator.write(getName());\n if (getInitialValue() != null) {\n generator.write(\" = \");\n generator.write(getInitialValue());\n }\n generator.write(\";\");\n }\n}\n"} {"task_id": "Java_419", "language": "Java", "task_type": "method_signature", "source_file": "java/github/klask-io/klask-io/src/main/java/io/klask/web/rest/dto/FileDetailDTO.java", "mask_start_position": 2479, "mask_end_position": 2510, "canonical_solution": "public void setSize(Long size) ", "pre_mask_code": "package io.klask.web.rest.dto;\n\nimport io.klask.domain.File;\nimport io.klask.web.rest.mapper.FileMapper;\nimport javax.validation.constraints.NotNull;\nimport javax.validation.constraints.Size;\nimport java.io.Serializable;\n\n/**\n * A DTO representing a full content file with contentType for syntax highlight\n */\npublic class FileDetailDTO implements Serializable {\n\n @NotNull\n @Size(max = 255)\n private String id;\n\n @NotNull\n @Size(max = 255)\n private String name;\n\n @Size(max = 255)\n private String extension;\n\n @Size(max = 255)\n private String contentType;\n\n private String content;\n\n @NotNull\n @Size(max = 255)\n private String path;\n\n private String project;\n\n private String version;\n\n private Long size;\n\n public FileDetailDTO(File f) {\n this(f.getId(), f.getName(), f.getExtension(), f.getContent(), f.getPath(), f.getProject(), f.getVersion(), f.getSize());\n }\n\n public FileDetailDTO(String id, String name, String extension, String content, String path, String project, String version, Long size) {\n this.id = id;\n this.name = name;\n this.extension = extension;\n this.content = content;\n this.contentType = FileMapper.getMappingContentType(extension);\n this.path = path;\n this.project = project;\n this.version = version;\n this.size = size;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getExtension() {\n return extension;\n }\n\n public void setExtension(String extension) {\n this.extension = extension;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public String getContentType() {\n return contentType;\n }\n\n public void setContentType(String contentType) {\n this.contentType = contentType;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public String getProject() {\n return project;\n }\n\n public void setProject(String project) {\n this.project = project;\n }\n\n public String getVersion() {\n return version;\n }\n\n public void setVersion(String version) {\n this.version = version;\n }\n\n public Long getSize() {\n return size;\n }\n\n ", "post_mask_code": "{\n this.size = size;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n @Override\n public String toString() {\n return \"FileDTO{\" + \"id='\" + id + '\\'' + \"name='\" + name + '\\'' + \", extension='\" + extension + '\\'' + \", project='\" + project + '\\'' + \", version='\" + version + '\\'' + \", size=\" + size + '}';\n }\n}\n"} {"task_id": "Java_420", "language": "Java", "task_type": "method_body", "source_file": "java/github/klask-io/klask-io/src/main/java/io/klask/web/rest/dto/FileDetailDTO.java", "mask_start_position": 2302, "mask_end_position": 2333, "canonical_solution": "{\n return version;\n }", "pre_mask_code": "package io.klask.web.rest.dto;\n\nimport io.klask.domain.File;\nimport io.klask.web.rest.mapper.FileMapper;\nimport javax.validation.constraints.NotNull;\nimport javax.validation.constraints.Size;\nimport java.io.Serializable;\n\n/**\n * A DTO representing a full content file with contentType for syntax highlight\n */\npublic class FileDetailDTO implements Serializable {\n\n @NotNull\n @Size(max = 255)\n private String id;\n\n @NotNull\n @Size(max = 255)\n private String name;\n\n @Size(max = 255)\n private String extension;\n\n @Size(max = 255)\n private String contentType;\n\n private String content;\n\n @NotNull\n @Size(max = 255)\n private String path;\n\n private String project;\n\n private String version;\n\n private Long size;\n\n public FileDetailDTO(File f) {\n this(f.getId(), f.getName(), f.getExtension(), f.getContent(), f.getPath(), f.getProject(), f.getVersion(), f.getSize());\n }\n\n public FileDetailDTO(String id, String name, String extension, String content, String path, String project, String version, Long size) {\n this.id = id;\n this.name = name;\n this.extension = extension;\n this.content = content;\n this.contentType = FileMapper.getMappingContentType(extension);\n this.path = path;\n this.project = project;\n this.version = version;\n this.size = size;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getExtension() {\n return extension;\n }\n\n public void setExtension(String extension) {\n this.extension = extension;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public String getContentType() {\n return contentType;\n }\n\n public void setContentType(String contentType) {\n this.contentType = contentType;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public String getProject() {\n return project;\n }\n\n public void setProject(String project) {\n this.project = project;\n }\n\n public String getVersion() ", "post_mask_code": "\n\n public void setVersion(String version) {\n this.version = version;\n }\n\n public Long getSize() {\n return size;\n }\n\n public void setSize(Long size) {\n this.size = size;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n @Override\n public String toString() {\n return \"FileDTO{\" + \"id='\" + id + '\\'' + \"name='\" + name + '\\'' + \", extension='\" + extension + '\\'' + \", project='\" + project + '\\'' + \", version='\" + version + '\\'' + \", size=\" + size + '}';\n }\n}\n"} {"task_id": "Java_421", "language": "Java", "task_type": "single_line", "source_file": "java/github/klask-io/klask-io/src/main/java/io/klask/web/rest/dto/FileDetailDTO.java", "mask_start_position": 2723, "mask_end_position": 2908, "canonical_solution": "\"FileDTO{\" + \"id='\" + id + '\\'' + \"name='\" + name + '\\'' + \", extension='\" + extension + '\\'' + \", project='\" + project + '\\'' + \", version='\" + version + '\\'' + \", size=\" + size + '}';", "pre_mask_code": "package io.klask.web.rest.dto;\n\nimport io.klask.domain.File;\nimport io.klask.web.rest.mapper.FileMapper;\nimport javax.validation.constraints.NotNull;\nimport javax.validation.constraints.Size;\nimport java.io.Serializable;\n\n/**\n * A DTO representing a full content file with contentType for syntax highlight\n */\npublic class FileDetailDTO implements Serializable {\n\n @NotNull\n @Size(max = 255)\n private String id;\n\n @NotNull\n @Size(max = 255)\n private String name;\n\n @Size(max = 255)\n private String extension;\n\n @Size(max = 255)\n private String contentType;\n\n private String content;\n\n @NotNull\n @Size(max = 255)\n private String path;\n\n private String project;\n\n private String version;\n\n private Long size;\n\n public FileDetailDTO(File f) {\n this(f.getId(), f.getName(), f.getExtension(), f.getContent(), f.getPath(), f.getProject(), f.getVersion(), f.getSize());\n }\n\n public FileDetailDTO(String id, String name, String extension, String content, String path, String project, String version, Long size) {\n this.id = id;\n this.name = name;\n this.extension = extension;\n this.content = content;\n this.contentType = FileMapper.getMappingContentType(extension);\n this.path = path;\n this.project = project;\n this.version = version;\n this.size = size;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getExtension() {\n return extension;\n }\n\n public void setExtension(String extension) {\n this.extension = extension;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public String getContentType() {\n return contentType;\n }\n\n public void setContentType(String contentType) {\n this.contentType = contentType;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public String getProject() {\n return project;\n }\n\n public void setProject(String project) {\n this.project = project;\n }\n\n public String getVersion() {\n return version;\n }\n\n public void setVersion(String version) {\n this.version = version;\n }\n\n public Long getSize() {\n return size;\n }\n\n public void setSize(Long size) {\n this.size = size;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n @Override\n public String toString() {\n return ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_422", "language": "Java", "task_type": "empty", "source_file": "java/github/klask-io/klask-io/src/main/java/io/klask/web/rest/dto/FileDetailDTO.java", "mask_start_position": 618, "mask_end_position": 618, "canonical_solution": "", "pre_mask_code": "package io.klask.web.rest.dto;\n\nimport io.klask.domain.File;\nimport io.klask.web.rest.mapper.FileMapper;\nimport javax.validation.constraints.NotNull;\nimport javax.validation.constraints.Size;\nimport java.io.Serializable;\n\n/**\n * A DTO representing a full content file with contentType for syntax highlight\n */\npublic class FileDetailDTO implements Serializable {\n\n @NotNull\n @Size(max = 255)\n private String id;\n\n @NotNull\n @Size(max = 255)\n private String name;\n\n @Size(max = 255)\n private String extension;\n\n @Size(max = 255)\n private String contentType;\n\n private String content;\n\n ", "post_mask_code": " @NotNull\n @Size(max = 255)\n private String path;\n\n private String project;\n\n private String version;\n\n private Long size;\n\n public FileDetailDTO(File f) {\n this(f.getId(), f.getName(), f.getExtension(), f.getContent(), f.getPath(), f.getProject(), f.getVersion(), f.getSize());\n }\n\n public FileDetailDTO(String id, String name, String extension, String content, String path, String project, String version, Long size) {\n this.id = id;\n this.name = name;\n this.extension = extension;\n this.content = content;\n this.contentType = FileMapper.getMappingContentType(extension);\n this.path = path;\n this.project = project;\n this.version = version;\n this.size = size;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getExtension() {\n return extension;\n }\n\n public void setExtension(String extension) {\n this.extension = extension;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public String getContentType() {\n return contentType;\n }\n\n public void setContentType(String contentType) {\n this.contentType = contentType;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public String getProject() {\n return project;\n }\n\n public void setProject(String project) {\n this.project = project;\n }\n\n public String getVersion() {\n return version;\n }\n\n public void setVersion(String version) {\n this.version = version;\n }\n\n public Long getSize() {\n return size;\n }\n\n public void setSize(Long size) {\n this.size = size;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n @Override\n public String toString() {\n return \"FileDTO{\" + \"id='\" + id + '\\'' + \"name='\" + name + '\\'' + \", extension='\" + extension + '\\'' + \", project='\" + project + '\\'' + \", version='\" + version + '\\'' + \", size=\" + size + '}';\n }\n}\n"} {"task_id": "Java_423", "language": "Java", "task_type": "method_signature", "source_file": "java/github/igniterealtime/Spark/core/src/main/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java", "mask_start_position": 5303, "mask_end_position": 5393, "canonical_solution": "@Override\n public void authenticated(XMPPConnection xmppConnection, boolean b) ", "pre_mask_code": "package org.jivesoftware.sparkimpl.plugin.transcripts;\n\nimport java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.MouseEvent;\nimport java.io.File;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport javax.swing.AbstractAction;\nimport javax.swing.Action;\nimport javax.swing.JButton;\nimport javax.swing.JDialog;\nimport javax.swing.JPanel;\nimport javax.swing.JPopupMenu;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\nimport org.jivesoftware.MainWindowListener;\nimport org.jivesoftware.resource.Default;\nimport org.jivesoftware.resource.Res;\nimport org.jivesoftware.resource.SparkRes;\nimport org.jivesoftware.smack.ConnectionListener;\nimport org.jivesoftware.smack.XMPPConnection;\nimport org.jivesoftware.smack.packet.Message;\nimport org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension;\nimport org.jivesoftware.spark.SparkManager;\nimport org.jivesoftware.spark.plugin.ContextMenuListener;\nimport org.jivesoftware.spark.ui.ChatRoom;\nimport org.jivesoftware.spark.ui.ChatRoomButton;\nimport org.jivesoftware.spark.ui.ChatRoomClosingListener;\nimport org.jivesoftware.spark.ui.ChatRoomListener;\nimport org.jivesoftware.spark.ui.ContactItem;\nimport org.jivesoftware.spark.ui.ContactList;\nimport org.jivesoftware.spark.ui.rooms.ChatRoomImpl;\nimport org.jivesoftware.spark.util.UIComponentRegistry;\nimport org.jivesoftware.sparkimpl.plugin.manager.Enterprise;\nimport org.jivesoftware.sparkimpl.settings.local.LocalPreferences;\nimport org.jivesoftware.sparkimpl.settings.local.SettingsManager;\nimport org.jxmpp.jid.BareJid;\nimport org.jxmpp.jid.EntityBareJid;\n\n/**\n * The ChatTranscriptPlugin is responsible for transcript handling within Spark.\n *\n * @author Derek DeMoro\n */\npublic class ChatTranscriptPlugin implements ChatRoomListener {\n\n private final SimpleDateFormat notificationDateFormatter;\n\n private final SimpleDateFormat messageDateFormatter;\n\n private final HashMap lastMessage = new HashMap<>();\n\n private JDialog Frame;\n\n private HistoryTranscript transcript = null;\n\n /**\n * Register the listeners for transcript persistence.\n */\n public ChatTranscriptPlugin() {\n SparkManager.getChatManager().addChatRoomListener(this);\n String dateFormat = ((SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL)).toPattern();\n notificationDateFormatter = new SimpleDateFormat(dateFormat);\n String timeFormat = \"HH:mm:ss\";\n messageDateFormatter = new SimpleDateFormat(timeFormat);\n final ContactList contactList = SparkManager.getWorkspace().getContactList();\n final Action viewHistoryAction = new AbstractAction() {\n\n private static final long serialVersionUID = -6498776252446416099L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n final BareJid jid = item.getJid();\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(jid);\n }\n };\n viewHistoryAction.putValue(Action.NAME, Res.getString(\"menuitem.view.contact.history\"));\n viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.HISTORY_16x16));\n final Action showStatusMessageAction = new AbstractAction() {\n\n private static final long serialVersionUID = -5000370836304286019L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n showStatusMessage(item);\n }\n };\n showStatusMessageAction.putValue(Action.NAME, Res.getString(\"menuitem.show.contact.statusmessage\"));\n contactList.addContextMenuListener(new ContextMenuListener() {\n\n @Override\n public void poppingUp(Object object, JPopupMenu popup) {\n if (object instanceof ContactItem) {\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n popup.add(viewHistoryAction);\n popup.add(showStatusMessageAction);\n }\n }\n\n @Override\n public void poppingDown(JPopupMenu popup) {\n }\n\n @Override\n public boolean handleDefaultAction(MouseEvent e) {\n return false;\n }\n });\n SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() {\n\n @Override\n public void shutdown() {\n persistConversations();\n }\n\n @Override\n public void mainWindowActivated() {\n }\n\n @Override\n public void mainWindowDeactivated() {\n }\n });\n SparkManager.getConnection().addConnectionListener(new ConnectionListener() {\n\n @Override\n public void connected(XMPPConnection xmppConnection) {\n }\n\n ", "post_mask_code": "{\n }\n\n @Override\n public void connectionClosed() {\n }\n\n @Override\n public void connectionClosedOnError(Exception e) {\n persistConversations();\n }\n });\n }\n\n public void persistConversations() {\n for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) {\n if (room instanceof ChatRoomImpl) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) room;\n if (roomImpl.isActive()) {\n persistChatRoom(roomImpl);\n }\n }\n }\n }\n\n public boolean canShutDown() {\n return true;\n }\n\n @Override\n public void chatRoomOpened(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n File transcriptFile = ChatTranscripts.getTranscriptFile(jid);\n if (!transcriptFile.exists()) {\n return;\n }\n if (room instanceof ChatRoomImpl) {\n new ChatRoomDecorator(room);\n }\n }\n\n @Override\n public void chatRoomLeft(ChatRoom room) {\n }\n\n @Override\n public void chatRoomClosed(final ChatRoom room) {\n // Persist only agent to agent chat rooms.\n if (room.getChatType() == Message.Type.chat) {\n persistChatRoom(room);\n }\n }\n\n public void persistChatRoom(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n final List transcripts = room.getTranscripts();\n ChatTranscript transcript = new ChatTranscript();\n int count = 0;\n int i = 0;\n if (lastMessage.get(jid) != null) {\n count = transcripts.indexOf(lastMessage.get(jid)) + 1;\n }\n for (Message message : transcripts) {\n if (i < count) {\n i++;\n continue;\n }\n lastMessage.put(jid, message);\n HistoryMessage history = new HistoryMessage();\n history.setTo(message.getTo());\n history.setFrom(message.getFrom());\n history.setBody(message.getBody());\n final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension(JivePropertiesExtension.NAMESPACE));\n Date date = null;\n if (extension != null) {\n date = (Date) extension.getProperty(\"date\");\n }\n history.setDate(date == null ? new Date() : date);\n transcript.addHistoryMessage(history);\n }\n ChatTranscripts.appendToTranscript(jid, transcript);\n }\n\n @Override\n public void chatRoomActivated(ChatRoom room) {\n }\n\n @Override\n public void userHasJoined(ChatRoom room, String userid) {\n }\n\n @Override\n public void userHasLeft(ChatRoom room, String userid) {\n }\n\n private void showStatusMessage(ContactItem item) {\n Frame = new JDialog();\n Frame.setTitle(item.getDisplayName() + \" - Status\");\n JPanel pane = new JPanel();\n JTextArea textArea = new JTextArea(5, 30);\n JButton btn_close = new JButton(Res.getString(\"button.close\"));\n btn_close.addActionListener(e -> Frame.setVisible(false));\n textArea.setLineWrap(true);\n textArea.setWrapStyleWord(true);\n pane.add(new JScrollPane(textArea));\n Frame.setLayout(new BorderLayout());\n Frame.add(pane, BorderLayout.CENTER);\n Frame.add(btn_close, BorderLayout.SOUTH);\n textArea.setEditable(false);\n textArea.setText(item.getStatus());\n Frame.setLocationRelativeTo(SparkManager.getMainWindow());\n Frame.setBounds(Frame.getX() - 175, Frame.getY() - 75, 350, 150);\n Frame.setSize(350, 150);\n Frame.setResizable(false);\n Frame.setVisible(true);\n }\n\n private class ChatRoomDecorator implements ActionListener, ChatRoomClosingListener {\n\n private ChatRoom chatRoom;\n\n private ChatRoomButton chatHistoryButton;\n\n private final LocalPreferences localPreferences;\n\n public ChatRoomDecorator(ChatRoom chatRoom) {\n this.chatRoom = chatRoom;\n chatRoom.addClosingListener(this);\n // Add History Button\n localPreferences = SettingsManager.getLocalPreferences();\n if (!localPreferences.isChatHistoryEnabled()) {\n return;\n }\n chatHistoryButton = UIComponentRegistry.getButtonFactory().createChatTranscriptButton();\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n chatRoom.addChatRoomButton(chatHistoryButton);\n chatHistoryButton.setToolTipText(Res.getString(\"tooltip.view.history\"));\n chatHistoryButton.addActionListener(this);\n }\n\n @Override\n public void closing() {\n if (localPreferences.isChatHistoryEnabled()) {\n chatHistoryButton.removeActionListener(this);\n }\n chatRoom.removeClosingListener(this);\n chatRoom = null;\n chatHistoryButton = null;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) chatRoom;\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(roomImpl.getParticipantJID());\n }\n }\n}\n"} {"task_id": "Java_424", "language": "Java", "task_type": "method_body", "source_file": "java/github/igniterealtime/Spark/core/src/main/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java", "mask_start_position": 5475, "mask_end_position": 5490, "canonical_solution": "{\n }", "pre_mask_code": "package org.jivesoftware.sparkimpl.plugin.transcripts;\n\nimport java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.MouseEvent;\nimport java.io.File;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport javax.swing.AbstractAction;\nimport javax.swing.Action;\nimport javax.swing.JButton;\nimport javax.swing.JDialog;\nimport javax.swing.JPanel;\nimport javax.swing.JPopupMenu;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\nimport org.jivesoftware.MainWindowListener;\nimport org.jivesoftware.resource.Default;\nimport org.jivesoftware.resource.Res;\nimport org.jivesoftware.resource.SparkRes;\nimport org.jivesoftware.smack.ConnectionListener;\nimport org.jivesoftware.smack.XMPPConnection;\nimport org.jivesoftware.smack.packet.Message;\nimport org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension;\nimport org.jivesoftware.spark.SparkManager;\nimport org.jivesoftware.spark.plugin.ContextMenuListener;\nimport org.jivesoftware.spark.ui.ChatRoom;\nimport org.jivesoftware.spark.ui.ChatRoomButton;\nimport org.jivesoftware.spark.ui.ChatRoomClosingListener;\nimport org.jivesoftware.spark.ui.ChatRoomListener;\nimport org.jivesoftware.spark.ui.ContactItem;\nimport org.jivesoftware.spark.ui.ContactList;\nimport org.jivesoftware.spark.ui.rooms.ChatRoomImpl;\nimport org.jivesoftware.spark.util.UIComponentRegistry;\nimport org.jivesoftware.sparkimpl.plugin.manager.Enterprise;\nimport org.jivesoftware.sparkimpl.settings.local.LocalPreferences;\nimport org.jivesoftware.sparkimpl.settings.local.SettingsManager;\nimport org.jxmpp.jid.BareJid;\nimport org.jxmpp.jid.EntityBareJid;\n\n/**\n * The ChatTranscriptPlugin is responsible for transcript handling within Spark.\n *\n * @author Derek DeMoro\n */\npublic class ChatTranscriptPlugin implements ChatRoomListener {\n\n private final SimpleDateFormat notificationDateFormatter;\n\n private final SimpleDateFormat messageDateFormatter;\n\n private final HashMap lastMessage = new HashMap<>();\n\n private JDialog Frame;\n\n private HistoryTranscript transcript = null;\n\n /**\n * Register the listeners for transcript persistence.\n */\n public ChatTranscriptPlugin() {\n SparkManager.getChatManager().addChatRoomListener(this);\n String dateFormat = ((SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL)).toPattern();\n notificationDateFormatter = new SimpleDateFormat(dateFormat);\n String timeFormat = \"HH:mm:ss\";\n messageDateFormatter = new SimpleDateFormat(timeFormat);\n final ContactList contactList = SparkManager.getWorkspace().getContactList();\n final Action viewHistoryAction = new AbstractAction() {\n\n private static final long serialVersionUID = -6498776252446416099L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n final BareJid jid = item.getJid();\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(jid);\n }\n };\n viewHistoryAction.putValue(Action.NAME, Res.getString(\"menuitem.view.contact.history\"));\n viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.HISTORY_16x16));\n final Action showStatusMessageAction = new AbstractAction() {\n\n private static final long serialVersionUID = -5000370836304286019L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n showStatusMessage(item);\n }\n };\n showStatusMessageAction.putValue(Action.NAME, Res.getString(\"menuitem.show.contact.statusmessage\"));\n contactList.addContextMenuListener(new ContextMenuListener() {\n\n @Override\n public void poppingUp(Object object, JPopupMenu popup) {\n if (object instanceof ContactItem) {\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n popup.add(viewHistoryAction);\n popup.add(showStatusMessageAction);\n }\n }\n\n @Override\n public void poppingDown(JPopupMenu popup) {\n }\n\n @Override\n public boolean handleDefaultAction(MouseEvent e) {\n return false;\n }\n });\n SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() {\n\n @Override\n public void shutdown() {\n persistConversations();\n }\n\n @Override\n public void mainWindowActivated() {\n }\n\n @Override\n public void mainWindowDeactivated() {\n }\n });\n SparkManager.getConnection().addConnectionListener(new ConnectionListener() {\n\n @Override\n public void connected(XMPPConnection xmppConnection) {\n }\n\n @Override\n public void authenticated(XMPPConnection xmppConnection, boolean b) {\n }\n\n @Override\n public void connectionClosed() ", "post_mask_code": "\n\n @Override\n public void connectionClosedOnError(Exception e) {\n persistConversations();\n }\n });\n }\n\n public void persistConversations() {\n for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) {\n if (room instanceof ChatRoomImpl) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) room;\n if (roomImpl.isActive()) {\n persistChatRoom(roomImpl);\n }\n }\n }\n }\n\n public boolean canShutDown() {\n return true;\n }\n\n @Override\n public void chatRoomOpened(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n File transcriptFile = ChatTranscripts.getTranscriptFile(jid);\n if (!transcriptFile.exists()) {\n return;\n }\n if (room instanceof ChatRoomImpl) {\n new ChatRoomDecorator(room);\n }\n }\n\n @Override\n public void chatRoomLeft(ChatRoom room) {\n }\n\n @Override\n public void chatRoomClosed(final ChatRoom room) {\n // Persist only agent to agent chat rooms.\n if (room.getChatType() == Message.Type.chat) {\n persistChatRoom(room);\n }\n }\n\n public void persistChatRoom(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n final List transcripts = room.getTranscripts();\n ChatTranscript transcript = new ChatTranscript();\n int count = 0;\n int i = 0;\n if (lastMessage.get(jid) != null) {\n count = transcripts.indexOf(lastMessage.get(jid)) + 1;\n }\n for (Message message : transcripts) {\n if (i < count) {\n i++;\n continue;\n }\n lastMessage.put(jid, message);\n HistoryMessage history = new HistoryMessage();\n history.setTo(message.getTo());\n history.setFrom(message.getFrom());\n history.setBody(message.getBody());\n final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension(JivePropertiesExtension.NAMESPACE));\n Date date = null;\n if (extension != null) {\n date = (Date) extension.getProperty(\"date\");\n }\n history.setDate(date == null ? new Date() : date);\n transcript.addHistoryMessage(history);\n }\n ChatTranscripts.appendToTranscript(jid, transcript);\n }\n\n @Override\n public void chatRoomActivated(ChatRoom room) {\n }\n\n @Override\n public void userHasJoined(ChatRoom room, String userid) {\n }\n\n @Override\n public void userHasLeft(ChatRoom room, String userid) {\n }\n\n private void showStatusMessage(ContactItem item) {\n Frame = new JDialog();\n Frame.setTitle(item.getDisplayName() + \" - Status\");\n JPanel pane = new JPanel();\n JTextArea textArea = new JTextArea(5, 30);\n JButton btn_close = new JButton(Res.getString(\"button.close\"));\n btn_close.addActionListener(e -> Frame.setVisible(false));\n textArea.setLineWrap(true);\n textArea.setWrapStyleWord(true);\n pane.add(new JScrollPane(textArea));\n Frame.setLayout(new BorderLayout());\n Frame.add(pane, BorderLayout.CENTER);\n Frame.add(btn_close, BorderLayout.SOUTH);\n textArea.setEditable(false);\n textArea.setText(item.getStatus());\n Frame.setLocationRelativeTo(SparkManager.getMainWindow());\n Frame.setBounds(Frame.getX() - 175, Frame.getY() - 75, 350, 150);\n Frame.setSize(350, 150);\n Frame.setResizable(false);\n Frame.setVisible(true);\n }\n\n private class ChatRoomDecorator implements ActionListener, ChatRoomClosingListener {\n\n private ChatRoom chatRoom;\n\n private ChatRoomButton chatHistoryButton;\n\n private final LocalPreferences localPreferences;\n\n public ChatRoomDecorator(ChatRoom chatRoom) {\n this.chatRoom = chatRoom;\n chatRoom.addClosingListener(this);\n // Add History Button\n localPreferences = SettingsManager.getLocalPreferences();\n if (!localPreferences.isChatHistoryEnabled()) {\n return;\n }\n chatHistoryButton = UIComponentRegistry.getButtonFactory().createChatTranscriptButton();\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n chatRoom.addChatRoomButton(chatHistoryButton);\n chatHistoryButton.setToolTipText(Res.getString(\"tooltip.view.history\"));\n chatHistoryButton.addActionListener(this);\n }\n\n @Override\n public void closing() {\n if (localPreferences.isChatHistoryEnabled()) {\n chatHistoryButton.removeActionListener(this);\n }\n chatRoom.removeClosingListener(this);\n chatRoom = null;\n chatHistoryButton = null;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) chatRoom;\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(roomImpl.getParticipantJID());\n }\n }\n}\n"} {"task_id": "Java_425", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/igniterealtime/Spark/core/src/main/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java", "mask_start_position": 8579, "mask_end_position": 8897, "canonical_solution": "\n Frame = new JDialog();\n Frame.setTitle(item.getDisplayName() + \" - Status\");\n JPanel pane = new JPanel();\n JTextArea textArea = new JTextArea(5, 30);\n JButton btn_close = new JButton(Res.getString(\"button.close\"));\n btn_close.addActionListener(e -> Frame.setVisible(false));", "pre_mask_code": "package org.jivesoftware.sparkimpl.plugin.transcripts;\n\nimport java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.MouseEvent;\nimport java.io.File;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport javax.swing.AbstractAction;\nimport javax.swing.Action;\nimport javax.swing.JButton;\nimport javax.swing.JDialog;\nimport javax.swing.JPanel;\nimport javax.swing.JPopupMenu;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\nimport org.jivesoftware.MainWindowListener;\nimport org.jivesoftware.resource.Default;\nimport org.jivesoftware.resource.Res;\nimport org.jivesoftware.resource.SparkRes;\nimport org.jivesoftware.smack.ConnectionListener;\nimport org.jivesoftware.smack.XMPPConnection;\nimport org.jivesoftware.smack.packet.Message;\nimport org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension;\nimport org.jivesoftware.spark.SparkManager;\nimport org.jivesoftware.spark.plugin.ContextMenuListener;\nimport org.jivesoftware.spark.ui.ChatRoom;\nimport org.jivesoftware.spark.ui.ChatRoomButton;\nimport org.jivesoftware.spark.ui.ChatRoomClosingListener;\nimport org.jivesoftware.spark.ui.ChatRoomListener;\nimport org.jivesoftware.spark.ui.ContactItem;\nimport org.jivesoftware.spark.ui.ContactList;\nimport org.jivesoftware.spark.ui.rooms.ChatRoomImpl;\nimport org.jivesoftware.spark.util.UIComponentRegistry;\nimport org.jivesoftware.sparkimpl.plugin.manager.Enterprise;\nimport org.jivesoftware.sparkimpl.settings.local.LocalPreferences;\nimport org.jivesoftware.sparkimpl.settings.local.SettingsManager;\nimport org.jxmpp.jid.BareJid;\nimport org.jxmpp.jid.EntityBareJid;\n\n/**\n * The ChatTranscriptPlugin is responsible for transcript handling within Spark.\n *\n * @author Derek DeMoro\n */\npublic class ChatTranscriptPlugin implements ChatRoomListener {\n\n private final SimpleDateFormat notificationDateFormatter;\n\n private final SimpleDateFormat messageDateFormatter;\n\n private final HashMap lastMessage = new HashMap<>();\n\n private JDialog Frame;\n\n private HistoryTranscript transcript = null;\n\n /**\n * Register the listeners for transcript persistence.\n */\n public ChatTranscriptPlugin() {\n SparkManager.getChatManager().addChatRoomListener(this);\n String dateFormat = ((SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL)).toPattern();\n notificationDateFormatter = new SimpleDateFormat(dateFormat);\n String timeFormat = \"HH:mm:ss\";\n messageDateFormatter = new SimpleDateFormat(timeFormat);\n final ContactList contactList = SparkManager.getWorkspace().getContactList();\n final Action viewHistoryAction = new AbstractAction() {\n\n private static final long serialVersionUID = -6498776252446416099L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n final BareJid jid = item.getJid();\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(jid);\n }\n };\n viewHistoryAction.putValue(Action.NAME, Res.getString(\"menuitem.view.contact.history\"));\n viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.HISTORY_16x16));\n final Action showStatusMessageAction = new AbstractAction() {\n\n private static final long serialVersionUID = -5000370836304286019L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n showStatusMessage(item);\n }\n };\n showStatusMessageAction.putValue(Action.NAME, Res.getString(\"menuitem.show.contact.statusmessage\"));\n contactList.addContextMenuListener(new ContextMenuListener() {\n\n @Override\n public void poppingUp(Object object, JPopupMenu popup) {\n if (object instanceof ContactItem) {\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n popup.add(viewHistoryAction);\n popup.add(showStatusMessageAction);\n }\n }\n\n @Override\n public void poppingDown(JPopupMenu popup) {\n }\n\n @Override\n public boolean handleDefaultAction(MouseEvent e) {\n return false;\n }\n });\n SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() {\n\n @Override\n public void shutdown() {\n persistConversations();\n }\n\n @Override\n public void mainWindowActivated() {\n }\n\n @Override\n public void mainWindowDeactivated() {\n }\n });\n SparkManager.getConnection().addConnectionListener(new ConnectionListener() {\n\n @Override\n public void connected(XMPPConnection xmppConnection) {\n }\n\n @Override\n public void authenticated(XMPPConnection xmppConnection, boolean b) {\n }\n\n @Override\n public void connectionClosed() {\n }\n\n @Override\n public void connectionClosedOnError(Exception e) {\n persistConversations();\n }\n });\n }\n\n public void persistConversations() {\n for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) {\n if (room instanceof ChatRoomImpl) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) room;\n if (roomImpl.isActive()) {\n persistChatRoom(roomImpl);\n }\n }\n }\n }\n\n public boolean canShutDown() {\n return true;\n }\n\n @Override\n public void chatRoomOpened(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n File transcriptFile = ChatTranscripts.getTranscriptFile(jid);\n if (!transcriptFile.exists()) {\n return;\n }\n if (room instanceof ChatRoomImpl) {\n new ChatRoomDecorator(room);\n }\n }\n\n @Override\n public void chatRoomLeft(ChatRoom room) {\n }\n\n @Override\n public void chatRoomClosed(final ChatRoom room) {\n // Persist only agent to agent chat rooms.\n if (room.getChatType() == Message.Type.chat) {\n persistChatRoom(room);\n }\n }\n\n public void persistChatRoom(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n final List transcripts = room.getTranscripts();\n ChatTranscript transcript = new ChatTranscript();\n int count = 0;\n int i = 0;\n if (lastMessage.get(jid) != null) {\n count = transcripts.indexOf(lastMessage.get(jid)) + 1;\n }\n for (Message message : transcripts) {\n if (i < count) {\n i++;\n continue;\n }\n lastMessage.put(jid, message);\n HistoryMessage history = new HistoryMessage();\n history.setTo(message.getTo());\n history.setFrom(message.getFrom());\n history.setBody(message.getBody());\n final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension(JivePropertiesExtension.NAMESPACE));\n Date date = null;\n if (extension != null) {\n date = (Date) extension.getProperty(\"date\");\n }\n history.setDate(date == null ? new Date() : date);\n transcript.addHistoryMessage(history);\n }\n ChatTranscripts.appendToTranscript(jid, transcript);\n }\n\n @Override\n public void chatRoomActivated(ChatRoom room) {\n }\n\n @Override\n public void userHasJoined(ChatRoom room, String userid) {\n }\n\n @Override\n public void userHasLeft(ChatRoom room, String userid) {\n }\n\n private void showStatusMessage(ContactItem item) {", "post_mask_code": "\n textArea.setLineWrap(true);\n textArea.setWrapStyleWord(true);\n pane.add(new JScrollPane(textArea));\n Frame.setLayout(new BorderLayout());\n Frame.add(pane, BorderLayout.CENTER);\n Frame.add(btn_close, BorderLayout.SOUTH);\n textArea.setEditable(false);\n textArea.setText(item.getStatus());\n Frame.setLocationRelativeTo(SparkManager.getMainWindow());\n Frame.setBounds(Frame.getX() - 175, Frame.getY() - 75, 350, 150);\n Frame.setSize(350, 150);\n Frame.setResizable(false);\n Frame.setVisible(true);\n }\n\n private class ChatRoomDecorator implements ActionListener, ChatRoomClosingListener {\n\n private ChatRoom chatRoom;\n\n private ChatRoomButton chatHistoryButton;\n\n private final LocalPreferences localPreferences;\n\n public ChatRoomDecorator(ChatRoom chatRoom) {\n this.chatRoom = chatRoom;\n chatRoom.addClosingListener(this);\n // Add History Button\n localPreferences = SettingsManager.getLocalPreferences();\n if (!localPreferences.isChatHistoryEnabled()) {\n return;\n }\n chatHistoryButton = UIComponentRegistry.getButtonFactory().createChatTranscriptButton();\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n chatRoom.addChatRoomButton(chatHistoryButton);\n chatHistoryButton.setToolTipText(Res.getString(\"tooltip.view.history\"));\n chatHistoryButton.addActionListener(this);\n }\n\n @Override\n public void closing() {\n if (localPreferences.isChatHistoryEnabled()) {\n chatHistoryButton.removeActionListener(this);\n }\n chatRoom.removeClosingListener(this);\n chatRoom = null;\n chatHistoryButton = null;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) chatRoom;\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(roomImpl.getParticipantJID());\n }\n }\n}\n"} {"task_id": "Java_426", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/igniterealtime/Spark/core/src/main/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java", "mask_start_position": 8906, "mask_end_position": 9197, "canonical_solution": "textArea.setLineWrap(true);\n textArea.setWrapStyleWord(true);\n pane.add(new JScrollPane(textArea));\n Frame.setLayout(new BorderLayout());\n Frame.add(pane, BorderLayout.CENTER);\n Frame.add(btn_close, BorderLayout.SOUTH);\n textArea.setEditable(false);", "pre_mask_code": "package org.jivesoftware.sparkimpl.plugin.transcripts;\n\nimport java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.MouseEvent;\nimport java.io.File;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport javax.swing.AbstractAction;\nimport javax.swing.Action;\nimport javax.swing.JButton;\nimport javax.swing.JDialog;\nimport javax.swing.JPanel;\nimport javax.swing.JPopupMenu;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\nimport org.jivesoftware.MainWindowListener;\nimport org.jivesoftware.resource.Default;\nimport org.jivesoftware.resource.Res;\nimport org.jivesoftware.resource.SparkRes;\nimport org.jivesoftware.smack.ConnectionListener;\nimport org.jivesoftware.smack.XMPPConnection;\nimport org.jivesoftware.smack.packet.Message;\nimport org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension;\nimport org.jivesoftware.spark.SparkManager;\nimport org.jivesoftware.spark.plugin.ContextMenuListener;\nimport org.jivesoftware.spark.ui.ChatRoom;\nimport org.jivesoftware.spark.ui.ChatRoomButton;\nimport org.jivesoftware.spark.ui.ChatRoomClosingListener;\nimport org.jivesoftware.spark.ui.ChatRoomListener;\nimport org.jivesoftware.spark.ui.ContactItem;\nimport org.jivesoftware.spark.ui.ContactList;\nimport org.jivesoftware.spark.ui.rooms.ChatRoomImpl;\nimport org.jivesoftware.spark.util.UIComponentRegistry;\nimport org.jivesoftware.sparkimpl.plugin.manager.Enterprise;\nimport org.jivesoftware.sparkimpl.settings.local.LocalPreferences;\nimport org.jivesoftware.sparkimpl.settings.local.SettingsManager;\nimport org.jxmpp.jid.BareJid;\nimport org.jxmpp.jid.EntityBareJid;\n\n/**\n * The ChatTranscriptPlugin is responsible for transcript handling within Spark.\n *\n * @author Derek DeMoro\n */\npublic class ChatTranscriptPlugin implements ChatRoomListener {\n\n private final SimpleDateFormat notificationDateFormatter;\n\n private final SimpleDateFormat messageDateFormatter;\n\n private final HashMap lastMessage = new HashMap<>();\n\n private JDialog Frame;\n\n private HistoryTranscript transcript = null;\n\n /**\n * Register the listeners for transcript persistence.\n */\n public ChatTranscriptPlugin() {\n SparkManager.getChatManager().addChatRoomListener(this);\n String dateFormat = ((SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL)).toPattern();\n notificationDateFormatter = new SimpleDateFormat(dateFormat);\n String timeFormat = \"HH:mm:ss\";\n messageDateFormatter = new SimpleDateFormat(timeFormat);\n final ContactList contactList = SparkManager.getWorkspace().getContactList();\n final Action viewHistoryAction = new AbstractAction() {\n\n private static final long serialVersionUID = -6498776252446416099L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n final BareJid jid = item.getJid();\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(jid);\n }\n };\n viewHistoryAction.putValue(Action.NAME, Res.getString(\"menuitem.view.contact.history\"));\n viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.HISTORY_16x16));\n final Action showStatusMessageAction = new AbstractAction() {\n\n private static final long serialVersionUID = -5000370836304286019L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n showStatusMessage(item);\n }\n };\n showStatusMessageAction.putValue(Action.NAME, Res.getString(\"menuitem.show.contact.statusmessage\"));\n contactList.addContextMenuListener(new ContextMenuListener() {\n\n @Override\n public void poppingUp(Object object, JPopupMenu popup) {\n if (object instanceof ContactItem) {\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n popup.add(viewHistoryAction);\n popup.add(showStatusMessageAction);\n }\n }\n\n @Override\n public void poppingDown(JPopupMenu popup) {\n }\n\n @Override\n public boolean handleDefaultAction(MouseEvent e) {\n return false;\n }\n });\n SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() {\n\n @Override\n public void shutdown() {\n persistConversations();\n }\n\n @Override\n public void mainWindowActivated() {\n }\n\n @Override\n public void mainWindowDeactivated() {\n }\n });\n SparkManager.getConnection().addConnectionListener(new ConnectionListener() {\n\n @Override\n public void connected(XMPPConnection xmppConnection) {\n }\n\n @Override\n public void authenticated(XMPPConnection xmppConnection, boolean b) {\n }\n\n @Override\n public void connectionClosed() {\n }\n\n @Override\n public void connectionClosedOnError(Exception e) {\n persistConversations();\n }\n });\n }\n\n public void persistConversations() {\n for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) {\n if (room instanceof ChatRoomImpl) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) room;\n if (roomImpl.isActive()) {\n persistChatRoom(roomImpl);\n }\n }\n }\n }\n\n public boolean canShutDown() {\n return true;\n }\n\n @Override\n public void chatRoomOpened(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n File transcriptFile = ChatTranscripts.getTranscriptFile(jid);\n if (!transcriptFile.exists()) {\n return;\n }\n if (room instanceof ChatRoomImpl) {\n new ChatRoomDecorator(room);\n }\n }\n\n @Override\n public void chatRoomLeft(ChatRoom room) {\n }\n\n @Override\n public void chatRoomClosed(final ChatRoom room) {\n // Persist only agent to agent chat rooms.\n if (room.getChatType() == Message.Type.chat) {\n persistChatRoom(room);\n }\n }\n\n public void persistChatRoom(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n final List transcripts = room.getTranscripts();\n ChatTranscript transcript = new ChatTranscript();\n int count = 0;\n int i = 0;\n if (lastMessage.get(jid) != null) {\n count = transcripts.indexOf(lastMessage.get(jid)) + 1;\n }\n for (Message message : transcripts) {\n if (i < count) {\n i++;\n continue;\n }\n lastMessage.put(jid, message);\n HistoryMessage history = new HistoryMessage();\n history.setTo(message.getTo());\n history.setFrom(message.getFrom());\n history.setBody(message.getBody());\n final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension(JivePropertiesExtension.NAMESPACE));\n Date date = null;\n if (extension != null) {\n date = (Date) extension.getProperty(\"date\");\n }\n history.setDate(date == null ? new Date() : date);\n transcript.addHistoryMessage(history);\n }\n ChatTranscripts.appendToTranscript(jid, transcript);\n }\n\n @Override\n public void chatRoomActivated(ChatRoom room) {\n }\n\n @Override\n public void userHasJoined(ChatRoom room, String userid) {\n }\n\n @Override\n public void userHasLeft(ChatRoom room, String userid) {\n }\n\n private void showStatusMessage(ContactItem item) {\n Frame = new JDialog();\n Frame.setTitle(item.getDisplayName() + \" - Status\");\n JPanel pane = new JPanel();\n JTextArea textArea = new JTextArea(5, 30);\n JButton btn_close = new JButton(Res.getString(\"button.close\"));\n btn_close.addActionListener(e -> Frame.setVisible(false));\n ", "post_mask_code": "\n textArea.setText(item.getStatus());\n Frame.setLocationRelativeTo(SparkManager.getMainWindow());\n Frame.setBounds(Frame.getX() - 175, Frame.getY() - 75, 350, 150);\n Frame.setSize(350, 150);\n Frame.setResizable(false);\n Frame.setVisible(true);\n }\n\n private class ChatRoomDecorator implements ActionListener, ChatRoomClosingListener {\n\n private ChatRoom chatRoom;\n\n private ChatRoomButton chatHistoryButton;\n\n private final LocalPreferences localPreferences;\n\n public ChatRoomDecorator(ChatRoom chatRoom) {\n this.chatRoom = chatRoom;\n chatRoom.addClosingListener(this);\n // Add History Button\n localPreferences = SettingsManager.getLocalPreferences();\n if (!localPreferences.isChatHistoryEnabled()) {\n return;\n }\n chatHistoryButton = UIComponentRegistry.getButtonFactory().createChatTranscriptButton();\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n chatRoom.addChatRoomButton(chatHistoryButton);\n chatHistoryButton.setToolTipText(Res.getString(\"tooltip.view.history\"));\n chatHistoryButton.addActionListener(this);\n }\n\n @Override\n public void closing() {\n if (localPreferences.isChatHistoryEnabled()) {\n chatHistoryButton.removeActionListener(this);\n }\n chatRoom.removeClosingListener(this);\n chatRoom = null;\n chatHistoryButton = null;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) chatRoom;\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(roomImpl.getParticipantJID());\n }\n }\n}\n"} {"task_id": "Java_427", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/igniterealtime/Spark/core/src/main/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java", "mask_start_position": 9206, "mask_end_position": 9488, "canonical_solution": "textArea.setText(item.getStatus());\n Frame.setLocationRelativeTo(SparkManager.getMainWindow());\n Frame.setBounds(Frame.getX() - 175, Frame.getY() - 75, 350, 150);\n Frame.setSize(350, 150);\n Frame.setResizable(false);\n Frame.setVisible(true);\n }", "pre_mask_code": "package org.jivesoftware.sparkimpl.plugin.transcripts;\n\nimport java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.MouseEvent;\nimport java.io.File;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport javax.swing.AbstractAction;\nimport javax.swing.Action;\nimport javax.swing.JButton;\nimport javax.swing.JDialog;\nimport javax.swing.JPanel;\nimport javax.swing.JPopupMenu;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\nimport org.jivesoftware.MainWindowListener;\nimport org.jivesoftware.resource.Default;\nimport org.jivesoftware.resource.Res;\nimport org.jivesoftware.resource.SparkRes;\nimport org.jivesoftware.smack.ConnectionListener;\nimport org.jivesoftware.smack.XMPPConnection;\nimport org.jivesoftware.smack.packet.Message;\nimport org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension;\nimport org.jivesoftware.spark.SparkManager;\nimport org.jivesoftware.spark.plugin.ContextMenuListener;\nimport org.jivesoftware.spark.ui.ChatRoom;\nimport org.jivesoftware.spark.ui.ChatRoomButton;\nimport org.jivesoftware.spark.ui.ChatRoomClosingListener;\nimport org.jivesoftware.spark.ui.ChatRoomListener;\nimport org.jivesoftware.spark.ui.ContactItem;\nimport org.jivesoftware.spark.ui.ContactList;\nimport org.jivesoftware.spark.ui.rooms.ChatRoomImpl;\nimport org.jivesoftware.spark.util.UIComponentRegistry;\nimport org.jivesoftware.sparkimpl.plugin.manager.Enterprise;\nimport org.jivesoftware.sparkimpl.settings.local.LocalPreferences;\nimport org.jivesoftware.sparkimpl.settings.local.SettingsManager;\nimport org.jxmpp.jid.BareJid;\nimport org.jxmpp.jid.EntityBareJid;\n\n/**\n * The ChatTranscriptPlugin is responsible for transcript handling within Spark.\n *\n * @author Derek DeMoro\n */\npublic class ChatTranscriptPlugin implements ChatRoomListener {\n\n private final SimpleDateFormat notificationDateFormatter;\n\n private final SimpleDateFormat messageDateFormatter;\n\n private final HashMap lastMessage = new HashMap<>();\n\n private JDialog Frame;\n\n private HistoryTranscript transcript = null;\n\n /**\n * Register the listeners for transcript persistence.\n */\n public ChatTranscriptPlugin() {\n SparkManager.getChatManager().addChatRoomListener(this);\n String dateFormat = ((SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL)).toPattern();\n notificationDateFormatter = new SimpleDateFormat(dateFormat);\n String timeFormat = \"HH:mm:ss\";\n messageDateFormatter = new SimpleDateFormat(timeFormat);\n final ContactList contactList = SparkManager.getWorkspace().getContactList();\n final Action viewHistoryAction = new AbstractAction() {\n\n private static final long serialVersionUID = -6498776252446416099L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n final BareJid jid = item.getJid();\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(jid);\n }\n };\n viewHistoryAction.putValue(Action.NAME, Res.getString(\"menuitem.view.contact.history\"));\n viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.HISTORY_16x16));\n final Action showStatusMessageAction = new AbstractAction() {\n\n private static final long serialVersionUID = -5000370836304286019L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n showStatusMessage(item);\n }\n };\n showStatusMessageAction.putValue(Action.NAME, Res.getString(\"menuitem.show.contact.statusmessage\"));\n contactList.addContextMenuListener(new ContextMenuListener() {\n\n @Override\n public void poppingUp(Object object, JPopupMenu popup) {\n if (object instanceof ContactItem) {\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n popup.add(viewHistoryAction);\n popup.add(showStatusMessageAction);\n }\n }\n\n @Override\n public void poppingDown(JPopupMenu popup) {\n }\n\n @Override\n public boolean handleDefaultAction(MouseEvent e) {\n return false;\n }\n });\n SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() {\n\n @Override\n public void shutdown() {\n persistConversations();\n }\n\n @Override\n public void mainWindowActivated() {\n }\n\n @Override\n public void mainWindowDeactivated() {\n }\n });\n SparkManager.getConnection().addConnectionListener(new ConnectionListener() {\n\n @Override\n public void connected(XMPPConnection xmppConnection) {\n }\n\n @Override\n public void authenticated(XMPPConnection xmppConnection, boolean b) {\n }\n\n @Override\n public void connectionClosed() {\n }\n\n @Override\n public void connectionClosedOnError(Exception e) {\n persistConversations();\n }\n });\n }\n\n public void persistConversations() {\n for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) {\n if (room instanceof ChatRoomImpl) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) room;\n if (roomImpl.isActive()) {\n persistChatRoom(roomImpl);\n }\n }\n }\n }\n\n public boolean canShutDown() {\n return true;\n }\n\n @Override\n public void chatRoomOpened(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n File transcriptFile = ChatTranscripts.getTranscriptFile(jid);\n if (!transcriptFile.exists()) {\n return;\n }\n if (room instanceof ChatRoomImpl) {\n new ChatRoomDecorator(room);\n }\n }\n\n @Override\n public void chatRoomLeft(ChatRoom room) {\n }\n\n @Override\n public void chatRoomClosed(final ChatRoom room) {\n // Persist only agent to agent chat rooms.\n if (room.getChatType() == Message.Type.chat) {\n persistChatRoom(room);\n }\n }\n\n public void persistChatRoom(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n final List transcripts = room.getTranscripts();\n ChatTranscript transcript = new ChatTranscript();\n int count = 0;\n int i = 0;\n if (lastMessage.get(jid) != null) {\n count = transcripts.indexOf(lastMessage.get(jid)) + 1;\n }\n for (Message message : transcripts) {\n if (i < count) {\n i++;\n continue;\n }\n lastMessage.put(jid, message);\n HistoryMessage history = new HistoryMessage();\n history.setTo(message.getTo());\n history.setFrom(message.getFrom());\n history.setBody(message.getBody());\n final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension(JivePropertiesExtension.NAMESPACE));\n Date date = null;\n if (extension != null) {\n date = (Date) extension.getProperty(\"date\");\n }\n history.setDate(date == null ? new Date() : date);\n transcript.addHistoryMessage(history);\n }\n ChatTranscripts.appendToTranscript(jid, transcript);\n }\n\n @Override\n public void chatRoomActivated(ChatRoom room) {\n }\n\n @Override\n public void userHasJoined(ChatRoom room, String userid) {\n }\n\n @Override\n public void userHasLeft(ChatRoom room, String userid) {\n }\n\n private void showStatusMessage(ContactItem item) {\n Frame = new JDialog();\n Frame.setTitle(item.getDisplayName() + \" - Status\");\n JPanel pane = new JPanel();\n JTextArea textArea = new JTextArea(5, 30);\n JButton btn_close = new JButton(Res.getString(\"button.close\"));\n btn_close.addActionListener(e -> Frame.setVisible(false));\n textArea.setLineWrap(true);\n textArea.setWrapStyleWord(true);\n pane.add(new JScrollPane(textArea));\n Frame.setLayout(new BorderLayout());\n Frame.add(pane, BorderLayout.CENTER);\n Frame.add(btn_close, BorderLayout.SOUTH);\n textArea.setEditable(false);\n ", "post_mask_code": "\n\n private class ChatRoomDecorator implements ActionListener, ChatRoomClosingListener {\n\n private ChatRoom chatRoom;\n\n private ChatRoomButton chatHistoryButton;\n\n private final LocalPreferences localPreferences;\n\n public ChatRoomDecorator(ChatRoom chatRoom) {\n this.chatRoom = chatRoom;\n chatRoom.addClosingListener(this);\n // Add History Button\n localPreferences = SettingsManager.getLocalPreferences();\n if (!localPreferences.isChatHistoryEnabled()) {\n return;\n }\n chatHistoryButton = UIComponentRegistry.getButtonFactory().createChatTranscriptButton();\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n chatRoom.addChatRoomButton(chatHistoryButton);\n chatHistoryButton.setToolTipText(Res.getString(\"tooltip.view.history\"));\n chatHistoryButton.addActionListener(this);\n }\n\n @Override\n public void closing() {\n if (localPreferences.isChatHistoryEnabled()) {\n chatHistoryButton.removeActionListener(this);\n }\n chatRoom.removeClosingListener(this);\n chatRoom = null;\n chatHistoryButton = null;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) chatRoom;\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(roomImpl.getParticipantJID());\n }\n }\n}\n"} {"task_id": "Java_428", "language": "Java", "task_type": "single_line", "source_file": "java/github/igniterealtime/Spark/core/src/main/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java", "mask_start_position": 8983, "mask_end_position": 9019, "canonical_solution": "pane.add(new JScrollPane(textArea));", "pre_mask_code": "package org.jivesoftware.sparkimpl.plugin.transcripts;\n\nimport java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.MouseEvent;\nimport java.io.File;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport javax.swing.AbstractAction;\nimport javax.swing.Action;\nimport javax.swing.JButton;\nimport javax.swing.JDialog;\nimport javax.swing.JPanel;\nimport javax.swing.JPopupMenu;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\nimport org.jivesoftware.MainWindowListener;\nimport org.jivesoftware.resource.Default;\nimport org.jivesoftware.resource.Res;\nimport org.jivesoftware.resource.SparkRes;\nimport org.jivesoftware.smack.ConnectionListener;\nimport org.jivesoftware.smack.XMPPConnection;\nimport org.jivesoftware.smack.packet.Message;\nimport org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension;\nimport org.jivesoftware.spark.SparkManager;\nimport org.jivesoftware.spark.plugin.ContextMenuListener;\nimport org.jivesoftware.spark.ui.ChatRoom;\nimport org.jivesoftware.spark.ui.ChatRoomButton;\nimport org.jivesoftware.spark.ui.ChatRoomClosingListener;\nimport org.jivesoftware.spark.ui.ChatRoomListener;\nimport org.jivesoftware.spark.ui.ContactItem;\nimport org.jivesoftware.spark.ui.ContactList;\nimport org.jivesoftware.spark.ui.rooms.ChatRoomImpl;\nimport org.jivesoftware.spark.util.UIComponentRegistry;\nimport org.jivesoftware.sparkimpl.plugin.manager.Enterprise;\nimport org.jivesoftware.sparkimpl.settings.local.LocalPreferences;\nimport org.jivesoftware.sparkimpl.settings.local.SettingsManager;\nimport org.jxmpp.jid.BareJid;\nimport org.jxmpp.jid.EntityBareJid;\n\n/**\n * The ChatTranscriptPlugin is responsible for transcript handling within Spark.\n *\n * @author Derek DeMoro\n */\npublic class ChatTranscriptPlugin implements ChatRoomListener {\n\n private final SimpleDateFormat notificationDateFormatter;\n\n private final SimpleDateFormat messageDateFormatter;\n\n private final HashMap lastMessage = new HashMap<>();\n\n private JDialog Frame;\n\n private HistoryTranscript transcript = null;\n\n /**\n * Register the listeners for transcript persistence.\n */\n public ChatTranscriptPlugin() {\n SparkManager.getChatManager().addChatRoomListener(this);\n String dateFormat = ((SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL)).toPattern();\n notificationDateFormatter = new SimpleDateFormat(dateFormat);\n String timeFormat = \"HH:mm:ss\";\n messageDateFormatter = new SimpleDateFormat(timeFormat);\n final ContactList contactList = SparkManager.getWorkspace().getContactList();\n final Action viewHistoryAction = new AbstractAction() {\n\n private static final long serialVersionUID = -6498776252446416099L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n final BareJid jid = item.getJid();\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(jid);\n }\n };\n viewHistoryAction.putValue(Action.NAME, Res.getString(\"menuitem.view.contact.history\"));\n viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.HISTORY_16x16));\n final Action showStatusMessageAction = new AbstractAction() {\n\n private static final long serialVersionUID = -5000370836304286019L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n showStatusMessage(item);\n }\n };\n showStatusMessageAction.putValue(Action.NAME, Res.getString(\"menuitem.show.contact.statusmessage\"));\n contactList.addContextMenuListener(new ContextMenuListener() {\n\n @Override\n public void poppingUp(Object object, JPopupMenu popup) {\n if (object instanceof ContactItem) {\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n popup.add(viewHistoryAction);\n popup.add(showStatusMessageAction);\n }\n }\n\n @Override\n public void poppingDown(JPopupMenu popup) {\n }\n\n @Override\n public boolean handleDefaultAction(MouseEvent e) {\n return false;\n }\n });\n SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() {\n\n @Override\n public void shutdown() {\n persistConversations();\n }\n\n @Override\n public void mainWindowActivated() {\n }\n\n @Override\n public void mainWindowDeactivated() {\n }\n });\n SparkManager.getConnection().addConnectionListener(new ConnectionListener() {\n\n @Override\n public void connected(XMPPConnection xmppConnection) {\n }\n\n @Override\n public void authenticated(XMPPConnection xmppConnection, boolean b) {\n }\n\n @Override\n public void connectionClosed() {\n }\n\n @Override\n public void connectionClosedOnError(Exception e) {\n persistConversations();\n }\n });\n }\n\n public void persistConversations() {\n for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) {\n if (room instanceof ChatRoomImpl) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) room;\n if (roomImpl.isActive()) {\n persistChatRoom(roomImpl);\n }\n }\n }\n }\n\n public boolean canShutDown() {\n return true;\n }\n\n @Override\n public void chatRoomOpened(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n File transcriptFile = ChatTranscripts.getTranscriptFile(jid);\n if (!transcriptFile.exists()) {\n return;\n }\n if (room instanceof ChatRoomImpl) {\n new ChatRoomDecorator(room);\n }\n }\n\n @Override\n public void chatRoomLeft(ChatRoom room) {\n }\n\n @Override\n public void chatRoomClosed(final ChatRoom room) {\n // Persist only agent to agent chat rooms.\n if (room.getChatType() == Message.Type.chat) {\n persistChatRoom(room);\n }\n }\n\n public void persistChatRoom(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n final List transcripts = room.getTranscripts();\n ChatTranscript transcript = new ChatTranscript();\n int count = 0;\n int i = 0;\n if (lastMessage.get(jid) != null) {\n count = transcripts.indexOf(lastMessage.get(jid)) + 1;\n }\n for (Message message : transcripts) {\n if (i < count) {\n i++;\n continue;\n }\n lastMessage.put(jid, message);\n HistoryMessage history = new HistoryMessage();\n history.setTo(message.getTo());\n history.setFrom(message.getFrom());\n history.setBody(message.getBody());\n final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension(JivePropertiesExtension.NAMESPACE));\n Date date = null;\n if (extension != null) {\n date = (Date) extension.getProperty(\"date\");\n }\n history.setDate(date == null ? new Date() : date);\n transcript.addHistoryMessage(history);\n }\n ChatTranscripts.appendToTranscript(jid, transcript);\n }\n\n @Override\n public void chatRoomActivated(ChatRoom room) {\n }\n\n @Override\n public void userHasJoined(ChatRoom room, String userid) {\n }\n\n @Override\n public void userHasLeft(ChatRoom room, String userid) {\n }\n\n private void showStatusMessage(ContactItem item) {\n Frame = new JDialog();\n Frame.setTitle(item.getDisplayName() + \" - Status\");\n JPanel pane = new JPanel();\n JTextArea textArea = new JTextArea(5, 30);\n JButton btn_close = new JButton(Res.getString(\"button.close\"));\n btn_close.addActionListener(e -> Frame.setVisible(false));\n textArea.setLineWrap(true);\n textArea.setWrapStyleWord(true);\n ", "post_mask_code": "\n Frame.setLayout(new BorderLayout());\n Frame.add(pane, BorderLayout.CENTER);\n Frame.add(btn_close, BorderLayout.SOUTH);\n textArea.setEditable(false);\n textArea.setText(item.getStatus());\n Frame.setLocationRelativeTo(SparkManager.getMainWindow());\n Frame.setBounds(Frame.getX() - 175, Frame.getY() - 75, 350, 150);\n Frame.setSize(350, 150);\n Frame.setResizable(false);\n Frame.setVisible(true);\n }\n\n private class ChatRoomDecorator implements ActionListener, ChatRoomClosingListener {\n\n private ChatRoom chatRoom;\n\n private ChatRoomButton chatHistoryButton;\n\n private final LocalPreferences localPreferences;\n\n public ChatRoomDecorator(ChatRoom chatRoom) {\n this.chatRoom = chatRoom;\n chatRoom.addClosingListener(this);\n // Add History Button\n localPreferences = SettingsManager.getLocalPreferences();\n if (!localPreferences.isChatHistoryEnabled()) {\n return;\n }\n chatHistoryButton = UIComponentRegistry.getButtonFactory().createChatTranscriptButton();\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n chatRoom.addChatRoomButton(chatHistoryButton);\n chatHistoryButton.setToolTipText(Res.getString(\"tooltip.view.history\"));\n chatHistoryButton.addActionListener(this);\n }\n\n @Override\n public void closing() {\n if (localPreferences.isChatHistoryEnabled()) {\n chatHistoryButton.removeActionListener(this);\n }\n chatRoom.removeClosingListener(this);\n chatRoom = null;\n chatHistoryButton = null;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) chatRoom;\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(roomImpl.getParticipantJID());\n }\n }\n}\n"} {"task_id": "Java_429", "language": "Java", "task_type": "if_statement", "source_file": "java/github/igniterealtime/Spark/core/src/main/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java", "mask_start_position": 7033, "mask_end_position": 7098, "canonical_solution": "if (!pref.isChatHistoryEnabled()) {\n return;\n }", "pre_mask_code": "package org.jivesoftware.sparkimpl.plugin.transcripts;\n\nimport java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.MouseEvent;\nimport java.io.File;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport javax.swing.AbstractAction;\nimport javax.swing.Action;\nimport javax.swing.JButton;\nimport javax.swing.JDialog;\nimport javax.swing.JPanel;\nimport javax.swing.JPopupMenu;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\nimport org.jivesoftware.MainWindowListener;\nimport org.jivesoftware.resource.Default;\nimport org.jivesoftware.resource.Res;\nimport org.jivesoftware.resource.SparkRes;\nimport org.jivesoftware.smack.ConnectionListener;\nimport org.jivesoftware.smack.XMPPConnection;\nimport org.jivesoftware.smack.packet.Message;\nimport org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension;\nimport org.jivesoftware.spark.SparkManager;\nimport org.jivesoftware.spark.plugin.ContextMenuListener;\nimport org.jivesoftware.spark.ui.ChatRoom;\nimport org.jivesoftware.spark.ui.ChatRoomButton;\nimport org.jivesoftware.spark.ui.ChatRoomClosingListener;\nimport org.jivesoftware.spark.ui.ChatRoomListener;\nimport org.jivesoftware.spark.ui.ContactItem;\nimport org.jivesoftware.spark.ui.ContactList;\nimport org.jivesoftware.spark.ui.rooms.ChatRoomImpl;\nimport org.jivesoftware.spark.util.UIComponentRegistry;\nimport org.jivesoftware.sparkimpl.plugin.manager.Enterprise;\nimport org.jivesoftware.sparkimpl.settings.local.LocalPreferences;\nimport org.jivesoftware.sparkimpl.settings.local.SettingsManager;\nimport org.jxmpp.jid.BareJid;\nimport org.jxmpp.jid.EntityBareJid;\n\n/**\n * The ChatTranscriptPlugin is responsible for transcript handling within Spark.\n *\n * @author Derek DeMoro\n */\npublic class ChatTranscriptPlugin implements ChatRoomListener {\n\n private final SimpleDateFormat notificationDateFormatter;\n\n private final SimpleDateFormat messageDateFormatter;\n\n private final HashMap lastMessage = new HashMap<>();\n\n private JDialog Frame;\n\n private HistoryTranscript transcript = null;\n\n /**\n * Register the listeners for transcript persistence.\n */\n public ChatTranscriptPlugin() {\n SparkManager.getChatManager().addChatRoomListener(this);\n String dateFormat = ((SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL)).toPattern();\n notificationDateFormatter = new SimpleDateFormat(dateFormat);\n String timeFormat = \"HH:mm:ss\";\n messageDateFormatter = new SimpleDateFormat(timeFormat);\n final ContactList contactList = SparkManager.getWorkspace().getContactList();\n final Action viewHistoryAction = new AbstractAction() {\n\n private static final long serialVersionUID = -6498776252446416099L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n final BareJid jid = item.getJid();\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(jid);\n }\n };\n viewHistoryAction.putValue(Action.NAME, Res.getString(\"menuitem.view.contact.history\"));\n viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.HISTORY_16x16));\n final Action showStatusMessageAction = new AbstractAction() {\n\n private static final long serialVersionUID = -5000370836304286019L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n showStatusMessage(item);\n }\n };\n showStatusMessageAction.putValue(Action.NAME, Res.getString(\"menuitem.show.contact.statusmessage\"));\n contactList.addContextMenuListener(new ContextMenuListener() {\n\n @Override\n public void poppingUp(Object object, JPopupMenu popup) {\n if (object instanceof ContactItem) {\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n popup.add(viewHistoryAction);\n popup.add(showStatusMessageAction);\n }\n }\n\n @Override\n public void poppingDown(JPopupMenu popup) {\n }\n\n @Override\n public boolean handleDefaultAction(MouseEvent e) {\n return false;\n }\n });\n SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() {\n\n @Override\n public void shutdown() {\n persistConversations();\n }\n\n @Override\n public void mainWindowActivated() {\n }\n\n @Override\n public void mainWindowDeactivated() {\n }\n });\n SparkManager.getConnection().addConnectionListener(new ConnectionListener() {\n\n @Override\n public void connected(XMPPConnection xmppConnection) {\n }\n\n @Override\n public void authenticated(XMPPConnection xmppConnection, boolean b) {\n }\n\n @Override\n public void connectionClosed() {\n }\n\n @Override\n public void connectionClosedOnError(Exception e) {\n persistConversations();\n }\n });\n }\n\n public void persistConversations() {\n for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) {\n if (room instanceof ChatRoomImpl) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) room;\n if (roomImpl.isActive()) {\n persistChatRoom(roomImpl);\n }\n }\n }\n }\n\n public boolean canShutDown() {\n return true;\n }\n\n @Override\n public void chatRoomOpened(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n File transcriptFile = ChatTranscripts.getTranscriptFile(jid);\n if (!transcriptFile.exists()) {\n return;\n }\n if (room instanceof ChatRoomImpl) {\n new ChatRoomDecorator(room);\n }\n }\n\n @Override\n public void chatRoomLeft(ChatRoom room) {\n }\n\n @Override\n public void chatRoomClosed(final ChatRoom room) {\n // Persist only agent to agent chat rooms.\n if (room.getChatType() == Message.Type.chat) {\n persistChatRoom(room);\n }\n }\n\n public void persistChatRoom(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n ", "post_mask_code": "\n final EntityBareJid jid = room.getBareJid();\n final List transcripts = room.getTranscripts();\n ChatTranscript transcript = new ChatTranscript();\n int count = 0;\n int i = 0;\n if (lastMessage.get(jid) != null) {\n count = transcripts.indexOf(lastMessage.get(jid)) + 1;\n }\n for (Message message : transcripts) {\n if (i < count) {\n i++;\n continue;\n }\n lastMessage.put(jid, message);\n HistoryMessage history = new HistoryMessage();\n history.setTo(message.getTo());\n history.setFrom(message.getFrom());\n history.setBody(message.getBody());\n final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension(JivePropertiesExtension.NAMESPACE));\n Date date = null;\n if (extension != null) {\n date = (Date) extension.getProperty(\"date\");\n }\n history.setDate(date == null ? new Date() : date);\n transcript.addHistoryMessage(history);\n }\n ChatTranscripts.appendToTranscript(jid, transcript);\n }\n\n @Override\n public void chatRoomActivated(ChatRoom room) {\n }\n\n @Override\n public void userHasJoined(ChatRoom room, String userid) {\n }\n\n @Override\n public void userHasLeft(ChatRoom room, String userid) {\n }\n\n private void showStatusMessage(ContactItem item) {\n Frame = new JDialog();\n Frame.setTitle(item.getDisplayName() + \" - Status\");\n JPanel pane = new JPanel();\n JTextArea textArea = new JTextArea(5, 30);\n JButton btn_close = new JButton(Res.getString(\"button.close\"));\n btn_close.addActionListener(e -> Frame.setVisible(false));\n textArea.setLineWrap(true);\n textArea.setWrapStyleWord(true);\n pane.add(new JScrollPane(textArea));\n Frame.setLayout(new BorderLayout());\n Frame.add(pane, BorderLayout.CENTER);\n Frame.add(btn_close, BorderLayout.SOUTH);\n textArea.setEditable(false);\n textArea.setText(item.getStatus());\n Frame.setLocationRelativeTo(SparkManager.getMainWindow());\n Frame.setBounds(Frame.getX() - 175, Frame.getY() - 75, 350, 150);\n Frame.setSize(350, 150);\n Frame.setResizable(false);\n Frame.setVisible(true);\n }\n\n private class ChatRoomDecorator implements ActionListener, ChatRoomClosingListener {\n\n private ChatRoom chatRoom;\n\n private ChatRoomButton chatHistoryButton;\n\n private final LocalPreferences localPreferences;\n\n public ChatRoomDecorator(ChatRoom chatRoom) {\n this.chatRoom = chatRoom;\n chatRoom.addClosingListener(this);\n // Add History Button\n localPreferences = SettingsManager.getLocalPreferences();\n if (!localPreferences.isChatHistoryEnabled()) {\n return;\n }\n chatHistoryButton = UIComponentRegistry.getButtonFactory().createChatTranscriptButton();\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n chatRoom.addChatRoomButton(chatHistoryButton);\n chatHistoryButton.setToolTipText(Res.getString(\"tooltip.view.history\"));\n chatHistoryButton.addActionListener(this);\n }\n\n @Override\n public void closing() {\n if (localPreferences.isChatHistoryEnabled()) {\n chatHistoryButton.removeActionListener(this);\n }\n chatRoom.removeClosingListener(this);\n chatRoom = null;\n chatHistoryButton = null;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) chatRoom;\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(roomImpl.getParticipantJID());\n }\n }\n}\n"} {"task_id": "Java_430", "language": "Java", "task_type": "empty", "source_file": "java/github/igniterealtime/Spark/core/src/main/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java", "mask_start_position": 2357, "mask_end_position": 2357, "canonical_solution": "", "pre_mask_code": "package org.jivesoftware.sparkimpl.plugin.transcripts;\n\nimport java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.MouseEvent;\nimport java.io.File;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport javax.swing.AbstractAction;\nimport javax.swing.Action;\nimport javax.swing.JButton;\nimport javax.swing.JDialog;\nimport javax.swing.JPanel;\nimport javax.swing.JPopupMenu;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\nimport org.jivesoftware.MainWindowListener;\nimport org.jivesoftware.resource.Default;\nimport org.jivesoftware.resource.Res;\nimport org.jivesoftware.resource.SparkRes;\nimport org.jivesoftware.smack.ConnectionListener;\nimport org.jivesoftware.smack.XMPPConnection;\nimport org.jivesoftware.smack.packet.Message;\nimport org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension;\nimport org.jivesoftware.spark.SparkManager;\nimport org.jivesoftware.spark.plugin.ContextMenuListener;\nimport org.jivesoftware.spark.ui.ChatRoom;\nimport org.jivesoftware.spark.ui.ChatRoomButton;\nimport org.jivesoftware.spark.ui.ChatRoomClosingListener;\nimport org.jivesoftware.spark.ui.ChatRoomListener;\nimport org.jivesoftware.spark.ui.ContactItem;\nimport org.jivesoftware.spark.ui.ContactList;\nimport org.jivesoftware.spark.ui.rooms.ChatRoomImpl;\nimport org.jivesoftware.spark.util.UIComponentRegistry;\nimport org.jivesoftware.sparkimpl.plugin.manager.Enterprise;\nimport org.jivesoftware.sparkimpl.settings.local.LocalPreferences;\nimport org.jivesoftware.sparkimpl.settings.local.SettingsManager;\nimport org.jxmpp.jid.BareJid;\nimport org.jxmpp.jid.EntityBareJid;\n\n/**\n * The ChatTranscriptPlugin is responsible for transcript handling within Spark.\n *\n * @author Derek DeMoro\n */\npublic class ChatTranscriptPlugin implements ChatRoomListener {\n\n private final SimpleDateFormat notificationDateFormatter;\n\n private final SimpleDateFormat messageDateFormatter;\n\n private final HashMap lastMessage = new HashMap<>();\n\n private JDialog Frame;\n\n private HistoryTranscript transcript = null;\n\n /**\n * Register the listeners for transcript persistence.\n */\n public ChatTranscriptPlugin() {\n SparkManager.getChatManager().addChatRoomListener(thi", "post_mask_code": "s);\n String dateFormat = ((SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL)).toPattern();\n notificationDateFormatter = new SimpleDateFormat(dateFormat);\n String timeFormat = \"HH:mm:ss\";\n messageDateFormatter = new SimpleDateFormat(timeFormat);\n final ContactList contactList = SparkManager.getWorkspace().getContactList();\n final Action viewHistoryAction = new AbstractAction() {\n\n private static final long serialVersionUID = -6498776252446416099L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n final BareJid jid = item.getJid();\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(jid);\n }\n };\n viewHistoryAction.putValue(Action.NAME, Res.getString(\"menuitem.view.contact.history\"));\n viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.HISTORY_16x16));\n final Action showStatusMessageAction = new AbstractAction() {\n\n private static final long serialVersionUID = -5000370836304286019L;\n\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n ContactItem item = contactList.getSelectedUsers().iterator().next();\n showStatusMessage(item);\n }\n };\n showStatusMessageAction.putValue(Action.NAME, Res.getString(\"menuitem.show.contact.statusmessage\"));\n contactList.addContextMenuListener(new ContextMenuListener() {\n\n @Override\n public void poppingUp(Object object, JPopupMenu popup) {\n if (object instanceof ContactItem) {\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n popup.add(viewHistoryAction);\n popup.add(showStatusMessageAction);\n }\n }\n\n @Override\n public void poppingDown(JPopupMenu popup) {\n }\n\n @Override\n public boolean handleDefaultAction(MouseEvent e) {\n return false;\n }\n });\n SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() {\n\n @Override\n public void shutdown() {\n persistConversations();\n }\n\n @Override\n public void mainWindowActivated() {\n }\n\n @Override\n public void mainWindowDeactivated() {\n }\n });\n SparkManager.getConnection().addConnectionListener(new ConnectionListener() {\n\n @Override\n public void connected(XMPPConnection xmppConnection) {\n }\n\n @Override\n public void authenticated(XMPPConnection xmppConnection, boolean b) {\n }\n\n @Override\n public void connectionClosed() {\n }\n\n @Override\n public void connectionClosedOnError(Exception e) {\n persistConversations();\n }\n });\n }\n\n public void persistConversations() {\n for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) {\n if (room instanceof ChatRoomImpl) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) room;\n if (roomImpl.isActive()) {\n persistChatRoom(roomImpl);\n }\n }\n }\n }\n\n public boolean canShutDown() {\n return true;\n }\n\n @Override\n public void chatRoomOpened(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n File transcriptFile = ChatTranscripts.getTranscriptFile(jid);\n if (!transcriptFile.exists()) {\n return;\n }\n if (room instanceof ChatRoomImpl) {\n new ChatRoomDecorator(room);\n }\n }\n\n @Override\n public void chatRoomLeft(ChatRoom room) {\n }\n\n @Override\n public void chatRoomClosed(final ChatRoom room) {\n // Persist only agent to agent chat rooms.\n if (room.getChatType() == Message.Type.chat) {\n persistChatRoom(room);\n }\n }\n\n public void persistChatRoom(final ChatRoom room) {\n LocalPreferences pref = SettingsManager.getLocalPreferences();\n if (!pref.isChatHistoryEnabled()) {\n return;\n }\n final EntityBareJid jid = room.getBareJid();\n final List transcripts = room.getTranscripts();\n ChatTranscript transcript = new ChatTranscript();\n int count = 0;\n int i = 0;\n if (lastMessage.get(jid) != null) {\n count = transcripts.indexOf(lastMessage.get(jid)) + 1;\n }\n for (Message message : transcripts) {\n if (i < count) {\n i++;\n continue;\n }\n lastMessage.put(jid, message);\n HistoryMessage history = new HistoryMessage();\n history.setTo(message.getTo());\n history.setFrom(message.getFrom());\n history.setBody(message.getBody());\n final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension(JivePropertiesExtension.NAMESPACE));\n Date date = null;\n if (extension != null) {\n date = (Date) extension.getProperty(\"date\");\n }\n history.setDate(date == null ? new Date() : date);\n transcript.addHistoryMessage(history);\n }\n ChatTranscripts.appendToTranscript(jid, transcript);\n }\n\n @Override\n public void chatRoomActivated(ChatRoom room) {\n }\n\n @Override\n public void userHasJoined(ChatRoom room, String userid) {\n }\n\n @Override\n public void userHasLeft(ChatRoom room, String userid) {\n }\n\n private void showStatusMessage(ContactItem item) {\n Frame = new JDialog();\n Frame.setTitle(item.getDisplayName() + \" - Status\");\n JPanel pane = new JPanel();\n JTextArea textArea = new JTextArea(5, 30);\n JButton btn_close = new JButton(Res.getString(\"button.close\"));\n btn_close.addActionListener(e -> Frame.setVisible(false));\n textArea.setLineWrap(true);\n textArea.setWrapStyleWord(true);\n pane.add(new JScrollPane(textArea));\n Frame.setLayout(new BorderLayout());\n Frame.add(pane, BorderLayout.CENTER);\n Frame.add(btn_close, BorderLayout.SOUTH);\n textArea.setEditable(false);\n textArea.setText(item.getStatus());\n Frame.setLocationRelativeTo(SparkManager.getMainWindow());\n Frame.setBounds(Frame.getX() - 175, Frame.getY() - 75, 350, 150);\n Frame.setSize(350, 150);\n Frame.setResizable(false);\n Frame.setVisible(true);\n }\n\n private class ChatRoomDecorator implements ActionListener, ChatRoomClosingListener {\n\n private ChatRoom chatRoom;\n\n private ChatRoomButton chatHistoryButton;\n\n private final LocalPreferences localPreferences;\n\n public ChatRoomDecorator(ChatRoom chatRoom) {\n this.chatRoom = chatRoom;\n chatRoom.addClosingListener(this);\n // Add History Button\n localPreferences = SettingsManager.getLocalPreferences();\n if (!localPreferences.isChatHistoryEnabled()) {\n return;\n }\n chatHistoryButton = UIComponentRegistry.getButtonFactory().createChatTranscriptButton();\n if (!Default.getBoolean(Default.HISTORY_DISABLED) && Enterprise.containsFeature(Enterprise.HISTORY_TRANSCRIPTS_FEATURE))\n chatRoom.addChatRoomButton(chatHistoryButton);\n chatHistoryButton.setToolTipText(Res.getString(\"tooltip.view.history\"));\n chatHistoryButton.addActionListener(this);\n }\n\n @Override\n public void closing() {\n if (localPreferences.isChatHistoryEnabled()) {\n chatHistoryButton.removeActionListener(this);\n }\n chatRoom.removeClosingListener(this);\n chatRoom = null;\n chatHistoryButton = null;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n ChatRoomImpl roomImpl = (ChatRoomImpl) chatRoom;\n transcript = new HistoryTranscript(notificationDateFormatter, messageDateFormatter);\n transcript.showHistory(roomImpl.getParticipantJID());\n }\n }\n}\n"} {"task_id": "Java_431", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ZainZhao/HIS/his-cloud/his-cloud-service-bms/src/main/java/com/neu/his/cloud/service/bms/model/SmsWorkloadRecord.java", "mask_start_position": 3890, "mask_end_position": 3924, "canonical_solution": "public void setType(Integer type) ", "pre_mask_code": "package com.neu.his.cloud.service.bms.model;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport java.io.Serializable;\nimport java.math.BigDecimal;\nimport java.util.Date;\n\npublic class SmsWorkloadRecord implements Serializable {\n\n private Long id;\n\n private Date createTime;\n\n private Long staffId;\n\n private BigDecimal medicineAmount;\n\n private BigDecimal herbalAmount;\n\n private BigDecimal checkAmount;\n\n private BigDecimal dispositionAmount;\n\n private BigDecimal registrationAmount;\n\n private BigDecimal testAmount;\n\n private BigDecimal amount;\n\n private Date date;\n\n private Integer status;\n\n private Long registrationNum;\n\n private BigDecimal excuteCheckAmount;\n\n private BigDecimal excuteTestAmount;\n\n private BigDecimal excuteDispositionAmount;\n\n private Integer type;\n\n private Long deptId;\n\n private Long excuteNum;\n\n private static final long serialVersionUID = 1L;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Long getStaffId() {\n return staffId;\n }\n\n public void setStaffId(Long staffId) {\n this.staffId = staffId;\n }\n\n public BigDecimal getMedicineAmount() {\n return medicineAmount;\n }\n\n public void setMedicineAmount(BigDecimal medicineAmount) {\n this.medicineAmount = medicineAmount;\n }\n\n public BigDecimal getHerbalAmount() {\n return herbalAmount;\n }\n\n public void setHerbalAmount(BigDecimal herbalAmount) {\n this.herbalAmount = herbalAmount;\n }\n\n public BigDecimal getCheckAmount() {\n return checkAmount;\n }\n\n public void setCheckAmount(BigDecimal checkAmount) {\n this.checkAmount = checkAmount;\n }\n\n public BigDecimal getDispositionAmount() {\n return dispositionAmount;\n }\n\n public void setDispositionAmount(BigDecimal dispositionAmount) {\n this.dispositionAmount = dispositionAmount;\n }\n\n public BigDecimal getRegistrationAmount() {\n return registrationAmount;\n }\n\n public void setRegistrationAmount(BigDecimal registrationAmount) {\n this.registrationAmount = registrationAmount;\n }\n\n public BigDecimal getTestAmount() {\n return testAmount;\n }\n\n public void setTestAmount(BigDecimal testAmount) {\n this.testAmount = testAmount;\n }\n\n public BigDecimal getAmount() {\n return amount;\n }\n\n public void setAmount(BigDecimal amount) {\n this.amount = amount;\n }\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public Integer getStatus() {\n return status;\n }\n\n public void setStatus(Integer status) {\n this.status = status;\n }\n\n public Long getRegistrationNum() {\n return registrationNum;\n }\n\n public void setRegistrationNum(Long registrationNum) {\n this.registrationNum = registrationNum;\n }\n\n public BigDecimal getExcuteCheckAmount() {\n return excuteCheckAmount;\n }\n\n public void setExcuteCheckAmount(BigDecimal excuteCheckAmount) {\n this.excuteCheckAmount = excuteCheckAmount;\n }\n\n public BigDecimal getExcuteTestAmount() {\n return excuteTestAmount;\n }\n\n public void setExcuteTestAmount(BigDecimal excuteTestAmount) {\n this.excuteTestAmount = excuteTestAmount;\n }\n\n public BigDecimal getExcuteDispositionAmount() {\n return excuteDispositionAmount;\n }\n\n public void setExcuteDispositionAmount(BigDecimal excuteDispositionAmount) {\n this.excuteDispositionAmount = excuteDispositionAmount;\n }\n\n public Integer getType() {\n return type;\n }\n\n ", "post_mask_code": "{\n this.type = type;\n }\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n public Long getExcuteNum() {\n return excuteNum;\n }\n\n public void setExcuteNum(Long excuteNum) {\n this.excuteNum = excuteNum;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", createTime=\").append(createTime);\n sb.append(\", staffId=\").append(staffId);\n sb.append(\", medicineAmount=\").append(medicineAmount);\n sb.append(\", herbalAmount=\").append(herbalAmount);\n sb.append(\", checkAmount=\").append(checkAmount);\n sb.append(\", dispositionAmount=\").append(dispositionAmount);\n sb.append(\", registrationAmount=\").append(registrationAmount);\n sb.append(\", testAmount=\").append(testAmount);\n sb.append(\", amount=\").append(amount);\n sb.append(\", date=\").append(date);\n sb.append(\", status=\").append(status);\n sb.append(\", registrationNum=\").append(registrationNum);\n sb.append(\", excuteCheckAmount=\").append(excuteCheckAmount);\n sb.append(\", excuteTestAmount=\").append(excuteTestAmount);\n sb.append(\", excuteDispositionAmount=\").append(excuteDispositionAmount);\n sb.append(\", type=\").append(type);\n sb.append(\", deptId=\").append(deptId);\n sb.append(\", excuteNum=\").append(excuteNum);\n sb.append(\", serialVersionUID=\").append(serialVersionUID);\n sb.append(\"]\");\n return sb.toString();\n }\n}\n"} {"task_id": "Java_432", "language": "Java", "task_type": "method_body", "source_file": "java/github/ZainZhao/HIS/his-cloud/his-cloud-service-bms/src/main/java/com/neu/his/cloud/service/bms/model/SmsWorkloadRecord.java", "mask_start_position": 2187, "mask_end_position": 2229, "canonical_solution": "{\n return registrationAmount;\n }", "pre_mask_code": "package com.neu.his.cloud.service.bms.model;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport java.io.Serializable;\nimport java.math.BigDecimal;\nimport java.util.Date;\n\npublic class SmsWorkloadRecord implements Serializable {\n\n private Long id;\n\n private Date createTime;\n\n private Long staffId;\n\n private BigDecimal medicineAmount;\n\n private BigDecimal herbalAmount;\n\n private BigDecimal checkAmount;\n\n private BigDecimal dispositionAmount;\n\n private BigDecimal registrationAmount;\n\n private BigDecimal testAmount;\n\n private BigDecimal amount;\n\n private Date date;\n\n private Integer status;\n\n private Long registrationNum;\n\n private BigDecimal excuteCheckAmount;\n\n private BigDecimal excuteTestAmount;\n\n private BigDecimal excuteDispositionAmount;\n\n private Integer type;\n\n private Long deptId;\n\n private Long excuteNum;\n\n private static final long serialVersionUID = 1L;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Long getStaffId() {\n return staffId;\n }\n\n public void setStaffId(Long staffId) {\n this.staffId = staffId;\n }\n\n public BigDecimal getMedicineAmount() {\n return medicineAmount;\n }\n\n public void setMedicineAmount(BigDecimal medicineAmount) {\n this.medicineAmount = medicineAmount;\n }\n\n public BigDecimal getHerbalAmount() {\n return herbalAmount;\n }\n\n public void setHerbalAmount(BigDecimal herbalAmount) {\n this.herbalAmount = herbalAmount;\n }\n\n public BigDecimal getCheckAmount() {\n return checkAmount;\n }\n\n public void setCheckAmount(BigDecimal checkAmount) {\n this.checkAmount = checkAmount;\n }\n\n public BigDecimal getDispositionAmount() {\n return dispositionAmount;\n }\n\n public void setDispositionAmount(BigDecimal dispositionAmount) {\n this.dispositionAmount = dispositionAmount;\n }\n\n public BigDecimal getRegistrationAmount() ", "post_mask_code": "\n\n public void setRegistrationAmount(BigDecimal registrationAmount) {\n this.registrationAmount = registrationAmount;\n }\n\n public BigDecimal getTestAmount() {\n return testAmount;\n }\n\n public void setTestAmount(BigDecimal testAmount) {\n this.testAmount = testAmount;\n }\n\n public BigDecimal getAmount() {\n return amount;\n }\n\n public void setAmount(BigDecimal amount) {\n this.amount = amount;\n }\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public Integer getStatus() {\n return status;\n }\n\n public void setStatus(Integer status) {\n this.status = status;\n }\n\n public Long getRegistrationNum() {\n return registrationNum;\n }\n\n public void setRegistrationNum(Long registrationNum) {\n this.registrationNum = registrationNum;\n }\n\n public BigDecimal getExcuteCheckAmount() {\n return excuteCheckAmount;\n }\n\n public void setExcuteCheckAmount(BigDecimal excuteCheckAmount) {\n this.excuteCheckAmount = excuteCheckAmount;\n }\n\n public BigDecimal getExcuteTestAmount() {\n return excuteTestAmount;\n }\n\n public void setExcuteTestAmount(BigDecimal excuteTestAmount) {\n this.excuteTestAmount = excuteTestAmount;\n }\n\n public BigDecimal getExcuteDispositionAmount() {\n return excuteDispositionAmount;\n }\n\n public void setExcuteDispositionAmount(BigDecimal excuteDispositionAmount) {\n this.excuteDispositionAmount = excuteDispositionAmount;\n }\n\n public Integer getType() {\n return type;\n }\n\n public void setType(Integer type) {\n this.type = type;\n }\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n public Long getExcuteNum() {\n return excuteNum;\n }\n\n public void setExcuteNum(Long excuteNum) {\n this.excuteNum = excuteNum;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", createTime=\").append(createTime);\n sb.append(\", staffId=\").append(staffId);\n sb.append(\", medicineAmount=\").append(medicineAmount);\n sb.append(\", herbalAmount=\").append(herbalAmount);\n sb.append(\", checkAmount=\").append(checkAmount);\n sb.append(\", dispositionAmount=\").append(dispositionAmount);\n sb.append(\", registrationAmount=\").append(registrationAmount);\n sb.append(\", testAmount=\").append(testAmount);\n sb.append(\", amount=\").append(amount);\n sb.append(\", date=\").append(date);\n sb.append(\", status=\").append(status);\n sb.append(\", registrationNum=\").append(registrationNum);\n sb.append(\", excuteCheckAmount=\").append(excuteCheckAmount);\n sb.append(\", excuteTestAmount=\").append(excuteTestAmount);\n sb.append(\", excuteDispositionAmount=\").append(excuteDispositionAmount);\n sb.append(\", type=\").append(type);\n sb.append(\", deptId=\").append(deptId);\n sb.append(\", excuteNum=\").append(excuteNum);\n sb.append(\", serialVersionUID=\").append(serialVersionUID);\n sb.append(\"]\");\n return sb.toString();\n }\n}\n"} {"task_id": "Java_433", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/ZainZhao/HIS/his-cloud/his-cloud-service-bms/src/main/java/com/neu/his/cloud/service/bms/model/SmsWorkloadRecord.java", "mask_start_position": 4297, "mask_end_position": 4731, "canonical_solution": "\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", createTime=\").append(createTime);\n sb.append(\", staffId=\").append(staffId);\n sb.append(\", medicineAmount=\").append(medicineAmount);\n sb.append(\", herbalAmount=\").append(herbalAmount);", "pre_mask_code": "package com.neu.his.cloud.service.bms.model;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport java.io.Serializable;\nimport java.math.BigDecimal;\nimport java.util.Date;\n\npublic class SmsWorkloadRecord implements Serializable {\n\n private Long id;\n\n private Date createTime;\n\n private Long staffId;\n\n private BigDecimal medicineAmount;\n\n private BigDecimal herbalAmount;\n\n private BigDecimal checkAmount;\n\n private BigDecimal dispositionAmount;\n\n private BigDecimal registrationAmount;\n\n private BigDecimal testAmount;\n\n private BigDecimal amount;\n\n private Date date;\n\n private Integer status;\n\n private Long registrationNum;\n\n private BigDecimal excuteCheckAmount;\n\n private BigDecimal excuteTestAmount;\n\n private BigDecimal excuteDispositionAmount;\n\n private Integer type;\n\n private Long deptId;\n\n private Long excuteNum;\n\n private static final long serialVersionUID = 1L;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Long getStaffId() {\n return staffId;\n }\n\n public void setStaffId(Long staffId) {\n this.staffId = staffId;\n }\n\n public BigDecimal getMedicineAmount() {\n return medicineAmount;\n }\n\n public void setMedicineAmount(BigDecimal medicineAmount) {\n this.medicineAmount = medicineAmount;\n }\n\n public BigDecimal getHerbalAmount() {\n return herbalAmount;\n }\n\n public void setHerbalAmount(BigDecimal herbalAmount) {\n this.herbalAmount = herbalAmount;\n }\n\n public BigDecimal getCheckAmount() {\n return checkAmount;\n }\n\n public void setCheckAmount(BigDecimal checkAmount) {\n this.checkAmount = checkAmount;\n }\n\n public BigDecimal getDispositionAmount() {\n return dispositionAmount;\n }\n\n public void setDispositionAmount(BigDecimal dispositionAmount) {\n this.dispositionAmount = dispositionAmount;\n }\n\n public BigDecimal getRegistrationAmount() {\n return registrationAmount;\n }\n\n public void setRegistrationAmount(BigDecimal registrationAmount) {\n this.registrationAmount = registrationAmount;\n }\n\n public BigDecimal getTestAmount() {\n return testAmount;\n }\n\n public void setTestAmount(BigDecimal testAmount) {\n this.testAmount = testAmount;\n }\n\n public BigDecimal getAmount() {\n return amount;\n }\n\n public void setAmount(BigDecimal amount) {\n this.amount = amount;\n }\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public Integer getStatus() {\n return status;\n }\n\n public void setStatus(Integer status) {\n this.status = status;\n }\n\n public Long getRegistrationNum() {\n return registrationNum;\n }\n\n public void setRegistrationNum(Long registrationNum) {\n this.registrationNum = registrationNum;\n }\n\n public BigDecimal getExcuteCheckAmount() {\n return excuteCheckAmount;\n }\n\n public void setExcuteCheckAmount(BigDecimal excuteCheckAmount) {\n this.excuteCheckAmount = excuteCheckAmount;\n }\n\n public BigDecimal getExcuteTestAmount() {\n return excuteTestAmount;\n }\n\n public void setExcuteTestAmount(BigDecimal excuteTestAmount) {\n this.excuteTestAmount = excuteTestAmount;\n }\n\n public BigDecimal getExcuteDispositionAmount() {\n return excuteDispositionAmount;\n }\n\n public void setExcuteDispositionAmount(BigDecimal excuteDispositionAmount) {\n this.excuteDispositionAmount = excuteDispositionAmount;\n }\n\n public Integer getType() {\n return type;\n }\n\n public void setType(Integer type) {\n this.type = type;\n }\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n public Long getExcuteNum() {\n return excuteNum;\n }\n\n public void setExcuteNum(Long excuteNum) {\n this.excuteNum = excuteNum;\n }\n\n @Override\n public String toString() {", "post_mask_code": "\n sb.append(\", checkAmount=\").append(checkAmount);\n sb.append(\", dispositionAmount=\").append(dispositionAmount);\n sb.append(\", registrationAmount=\").append(registrationAmount);\n sb.append(\", testAmount=\").append(testAmount);\n sb.append(\", amount=\").append(amount);\n sb.append(\", date=\").append(date);\n sb.append(\", status=\").append(status);\n sb.append(\", registrationNum=\").append(registrationNum);\n sb.append(\", excuteCheckAmount=\").append(excuteCheckAmount);\n sb.append(\", excuteTestAmount=\").append(excuteTestAmount);\n sb.append(\", excuteDispositionAmount=\").append(excuteDispositionAmount);\n sb.append(\", type=\").append(type);\n sb.append(\", deptId=\").append(deptId);\n sb.append(\", excuteNum=\").append(excuteNum);\n sb.append(\", serialVersionUID=\").append(serialVersionUID);\n sb.append(\"]\");\n return sb.toString();\n }\n}\n"} {"task_id": "Java_434", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/ZainZhao/HIS/his-cloud/his-cloud-service-bms/src/main/java/com/neu/his/cloud/service/bms/model/SmsWorkloadRecord.java", "mask_start_position": 4740, "mask_end_position": 5254, "canonical_solution": "sb.append(\", checkAmount=\").append(checkAmount);\n sb.append(\", dispositionAmount=\").append(dispositionAmount);\n sb.append(\", registrationAmount=\").append(registrationAmount);\n sb.append(\", testAmount=\").append(testAmount);\n sb.append(\", amount=\").append(amount);\n sb.append(\", date=\").append(date);\n sb.append(\", status=\").append(status);\n sb.append(\", registrationNum=\").append(registrationNum);\n sb.append(\", excuteCheckAmount=\").append(excuteCheckAmount);", "pre_mask_code": "package com.neu.his.cloud.service.bms.model;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport java.io.Serializable;\nimport java.math.BigDecimal;\nimport java.util.Date;\n\npublic class SmsWorkloadRecord implements Serializable {\n\n private Long id;\n\n private Date createTime;\n\n private Long staffId;\n\n private BigDecimal medicineAmount;\n\n private BigDecimal herbalAmount;\n\n private BigDecimal checkAmount;\n\n private BigDecimal dispositionAmount;\n\n private BigDecimal registrationAmount;\n\n private BigDecimal testAmount;\n\n private BigDecimal amount;\n\n private Date date;\n\n private Integer status;\n\n private Long registrationNum;\n\n private BigDecimal excuteCheckAmount;\n\n private BigDecimal excuteTestAmount;\n\n private BigDecimal excuteDispositionAmount;\n\n private Integer type;\n\n private Long deptId;\n\n private Long excuteNum;\n\n private static final long serialVersionUID = 1L;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Long getStaffId() {\n return staffId;\n }\n\n public void setStaffId(Long staffId) {\n this.staffId = staffId;\n }\n\n public BigDecimal getMedicineAmount() {\n return medicineAmount;\n }\n\n public void setMedicineAmount(BigDecimal medicineAmount) {\n this.medicineAmount = medicineAmount;\n }\n\n public BigDecimal getHerbalAmount() {\n return herbalAmount;\n }\n\n public void setHerbalAmount(BigDecimal herbalAmount) {\n this.herbalAmount = herbalAmount;\n }\n\n public BigDecimal getCheckAmount() {\n return checkAmount;\n }\n\n public void setCheckAmount(BigDecimal checkAmount) {\n this.checkAmount = checkAmount;\n }\n\n public BigDecimal getDispositionAmount() {\n return dispositionAmount;\n }\n\n public void setDispositionAmount(BigDecimal dispositionAmount) {\n this.dispositionAmount = dispositionAmount;\n }\n\n public BigDecimal getRegistrationAmount() {\n return registrationAmount;\n }\n\n public void setRegistrationAmount(BigDecimal registrationAmount) {\n this.registrationAmount = registrationAmount;\n }\n\n public BigDecimal getTestAmount() {\n return testAmount;\n }\n\n public void setTestAmount(BigDecimal testAmount) {\n this.testAmount = testAmount;\n }\n\n public BigDecimal getAmount() {\n return amount;\n }\n\n public void setAmount(BigDecimal amount) {\n this.amount = amount;\n }\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public Integer getStatus() {\n return status;\n }\n\n public void setStatus(Integer status) {\n this.status = status;\n }\n\n public Long getRegistrationNum() {\n return registrationNum;\n }\n\n public void setRegistrationNum(Long registrationNum) {\n this.registrationNum = registrationNum;\n }\n\n public BigDecimal getExcuteCheckAmount() {\n return excuteCheckAmount;\n }\n\n public void setExcuteCheckAmount(BigDecimal excuteCheckAmount) {\n this.excuteCheckAmount = excuteCheckAmount;\n }\n\n public BigDecimal getExcuteTestAmount() {\n return excuteTestAmount;\n }\n\n public void setExcuteTestAmount(BigDecimal excuteTestAmount) {\n this.excuteTestAmount = excuteTestAmount;\n }\n\n public BigDecimal getExcuteDispositionAmount() {\n return excuteDispositionAmount;\n }\n\n public void setExcuteDispositionAmount(BigDecimal excuteDispositionAmount) {\n this.excuteDispositionAmount = excuteDispositionAmount;\n }\n\n public Integer getType() {\n return type;\n }\n\n public void setType(Integer type) {\n this.type = type;\n }\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n public Long getExcuteNum() {\n return excuteNum;\n }\n\n public void setExcuteNum(Long excuteNum) {\n this.excuteNum = excuteNum;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", createTime=\").append(createTime);\n sb.append(\", staffId=\").append(staffId);\n sb.append(\", medicineAmount=\").append(medicineAmount);\n sb.append(\", herbalAmount=\").append(herbalAmount);\n ", "post_mask_code": "\n sb.append(\", excuteTestAmount=\").append(excuteTestAmount);\n sb.append(\", excuteDispositionAmount=\").append(excuteDispositionAmount);\n sb.append(\", type=\").append(type);\n sb.append(\", deptId=\").append(deptId);\n sb.append(\", excuteNum=\").append(excuteNum);\n sb.append(\", serialVersionUID=\").append(serialVersionUID);\n sb.append(\"]\");\n return sb.toString();\n }\n}\n"} {"task_id": "Java_435", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/ZainZhao/HIS/his-cloud/his-cloud-service-bms/src/main/java/com/neu/his/cloud/service/bms/model/SmsWorkloadRecord.java", "mask_start_position": 5263, "mask_end_position": 5672, "canonical_solution": "sb.append(\", excuteTestAmount=\").append(excuteTestAmount);\n sb.append(\", excuteDispositionAmount=\").append(excuteDispositionAmount);\n sb.append(\", type=\").append(type);\n sb.append(\", deptId=\").append(deptId);\n sb.append(\", excuteNum=\").append(excuteNum);\n sb.append(\", serialVersionUID=\").append(serialVersionUID);\n sb.append(\"]\");\n return sb.toString();\n }", "pre_mask_code": "package com.neu.his.cloud.service.bms.model;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport java.io.Serializable;\nimport java.math.BigDecimal;\nimport java.util.Date;\n\npublic class SmsWorkloadRecord implements Serializable {\n\n private Long id;\n\n private Date createTime;\n\n private Long staffId;\n\n private BigDecimal medicineAmount;\n\n private BigDecimal herbalAmount;\n\n private BigDecimal checkAmount;\n\n private BigDecimal dispositionAmount;\n\n private BigDecimal registrationAmount;\n\n private BigDecimal testAmount;\n\n private BigDecimal amount;\n\n private Date date;\n\n private Integer status;\n\n private Long registrationNum;\n\n private BigDecimal excuteCheckAmount;\n\n private BigDecimal excuteTestAmount;\n\n private BigDecimal excuteDispositionAmount;\n\n private Integer type;\n\n private Long deptId;\n\n private Long excuteNum;\n\n private static final long serialVersionUID = 1L;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Long getStaffId() {\n return staffId;\n }\n\n public void setStaffId(Long staffId) {\n this.staffId = staffId;\n }\n\n public BigDecimal getMedicineAmount() {\n return medicineAmount;\n }\n\n public void setMedicineAmount(BigDecimal medicineAmount) {\n this.medicineAmount = medicineAmount;\n }\n\n public BigDecimal getHerbalAmount() {\n return herbalAmount;\n }\n\n public void setHerbalAmount(BigDecimal herbalAmount) {\n this.herbalAmount = herbalAmount;\n }\n\n public BigDecimal getCheckAmount() {\n return checkAmount;\n }\n\n public void setCheckAmount(BigDecimal checkAmount) {\n this.checkAmount = checkAmount;\n }\n\n public BigDecimal getDispositionAmount() {\n return dispositionAmount;\n }\n\n public void setDispositionAmount(BigDecimal dispositionAmount) {\n this.dispositionAmount = dispositionAmount;\n }\n\n public BigDecimal getRegistrationAmount() {\n return registrationAmount;\n }\n\n public void setRegistrationAmount(BigDecimal registrationAmount) {\n this.registrationAmount = registrationAmount;\n }\n\n public BigDecimal getTestAmount() {\n return testAmount;\n }\n\n public void setTestAmount(BigDecimal testAmount) {\n this.testAmount = testAmount;\n }\n\n public BigDecimal getAmount() {\n return amount;\n }\n\n public void setAmount(BigDecimal amount) {\n this.amount = amount;\n }\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public Integer getStatus() {\n return status;\n }\n\n public void setStatus(Integer status) {\n this.status = status;\n }\n\n public Long getRegistrationNum() {\n return registrationNum;\n }\n\n public void setRegistrationNum(Long registrationNum) {\n this.registrationNum = registrationNum;\n }\n\n public BigDecimal getExcuteCheckAmount() {\n return excuteCheckAmount;\n }\n\n public void setExcuteCheckAmount(BigDecimal excuteCheckAmount) {\n this.excuteCheckAmount = excuteCheckAmount;\n }\n\n public BigDecimal getExcuteTestAmount() {\n return excuteTestAmount;\n }\n\n public void setExcuteTestAmount(BigDecimal excuteTestAmount) {\n this.excuteTestAmount = excuteTestAmount;\n }\n\n public BigDecimal getExcuteDispositionAmount() {\n return excuteDispositionAmount;\n }\n\n public void setExcuteDispositionAmount(BigDecimal excuteDispositionAmount) {\n this.excuteDispositionAmount = excuteDispositionAmount;\n }\n\n public Integer getType() {\n return type;\n }\n\n public void setType(Integer type) {\n this.type = type;\n }\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n public Long getExcuteNum() {\n return excuteNum;\n }\n\n public void setExcuteNum(Long excuteNum) {\n this.excuteNum = excuteNum;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", createTime=\").append(createTime);\n sb.append(\", staffId=\").append(staffId);\n sb.append(\", medicineAmount=\").append(medicineAmount);\n sb.append(\", herbalAmount=\").append(herbalAmount);\n sb.append(\", checkAmount=\").append(checkAmount);\n sb.append(\", dispositionAmount=\").append(dispositionAmount);\n sb.append(\", registrationAmount=\").append(registrationAmount);\n sb.append(\", testAmount=\").append(testAmount);\n sb.append(\", amount=\").append(amount);\n sb.append(\", date=\").append(date);\n sb.append(\", status=\").append(status);\n sb.append(\", registrationNum=\").append(registrationNum);\n sb.append(\", excuteCheckAmount=\").append(excuteCheckAmount);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_436", "language": "Java", "task_type": "single_line", "source_file": "java/github/ZainZhao/HIS/his-cloud/his-cloud-service-bms/src/main/java/com/neu/his/cloud/service/bms/model/SmsWorkloadRecord.java", "mask_start_position": 4437, "mask_end_position": 4466, "canonical_solution": "Hash = \").append(hashCode());", "pre_mask_code": "package com.neu.his.cloud.service.bms.model;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport java.io.Serializable;\nimport java.math.BigDecimal;\nimport java.util.Date;\n\npublic class SmsWorkloadRecord implements Serializable {\n\n private Long id;\n\n private Date createTime;\n\n private Long staffId;\n\n private BigDecimal medicineAmount;\n\n private BigDecimal herbalAmount;\n\n private BigDecimal checkAmount;\n\n private BigDecimal dispositionAmount;\n\n private BigDecimal registrationAmount;\n\n private BigDecimal testAmount;\n\n private BigDecimal amount;\n\n private Date date;\n\n private Integer status;\n\n private Long registrationNum;\n\n private BigDecimal excuteCheckAmount;\n\n private BigDecimal excuteTestAmount;\n\n private BigDecimal excuteDispositionAmount;\n\n private Integer type;\n\n private Long deptId;\n\n private Long excuteNum;\n\n private static final long serialVersionUID = 1L;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Long getStaffId() {\n return staffId;\n }\n\n public void setStaffId(Long staffId) {\n this.staffId = staffId;\n }\n\n public BigDecimal getMedicineAmount() {\n return medicineAmount;\n }\n\n public void setMedicineAmount(BigDecimal medicineAmount) {\n this.medicineAmount = medicineAmount;\n }\n\n public BigDecimal getHerbalAmount() {\n return herbalAmount;\n }\n\n public void setHerbalAmount(BigDecimal herbalAmount) {\n this.herbalAmount = herbalAmount;\n }\n\n public BigDecimal getCheckAmount() {\n return checkAmount;\n }\n\n public void setCheckAmount(BigDecimal checkAmount) {\n this.checkAmount = checkAmount;\n }\n\n public BigDecimal getDispositionAmount() {\n return dispositionAmount;\n }\n\n public void setDispositionAmount(BigDecimal dispositionAmount) {\n this.dispositionAmount = dispositionAmount;\n }\n\n public BigDecimal getRegistrationAmount() {\n return registrationAmount;\n }\n\n public void setRegistrationAmount(BigDecimal registrationAmount) {\n this.registrationAmount = registrationAmount;\n }\n\n public BigDecimal getTestAmount() {\n return testAmount;\n }\n\n public void setTestAmount(BigDecimal testAmount) {\n this.testAmount = testAmount;\n }\n\n public BigDecimal getAmount() {\n return amount;\n }\n\n public void setAmount(BigDecimal amount) {\n this.amount = amount;\n }\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public Integer getStatus() {\n return status;\n }\n\n public void setStatus(Integer status) {\n this.status = status;\n }\n\n public Long getRegistrationNum() {\n return registrationNum;\n }\n\n public void setRegistrationNum(Long registrationNum) {\n this.registrationNum = registrationNum;\n }\n\n public BigDecimal getExcuteCheckAmount() {\n return excuteCheckAmount;\n }\n\n public void setExcuteCheckAmount(BigDecimal excuteCheckAmount) {\n this.excuteCheckAmount = excuteCheckAmount;\n }\n\n public BigDecimal getExcuteTestAmount() {\n return excuteTestAmount;\n }\n\n public void setExcuteTestAmount(BigDecimal excuteTestAmount) {\n this.excuteTestAmount = excuteTestAmount;\n }\n\n public BigDecimal getExcuteDispositionAmount() {\n return excuteDispositionAmount;\n }\n\n public void setExcuteDispositionAmount(BigDecimal excuteDispositionAmount) {\n this.excuteDispositionAmount = excuteDispositionAmount;\n }\n\n public Integer getType() {\n return type;\n }\n\n public void setType(Integer type) {\n this.type = type;\n }\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n public Long getExcuteNum() {\n return excuteNum;\n }\n\n public void setExcuteNum(Long excuteNum) {\n this.excuteNum = excuteNum;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"", "post_mask_code": "\n sb.append(\", id=\").append(id);\n sb.append(\", createTime=\").append(createTime);\n sb.append(\", staffId=\").append(staffId);\n sb.append(\", medicineAmount=\").append(medicineAmount);\n sb.append(\", herbalAmount=\").append(herbalAmount);\n sb.append(\", checkAmount=\").append(checkAmount);\n sb.append(\", dispositionAmount=\").append(dispositionAmount);\n sb.append(\", registrationAmount=\").append(registrationAmount);\n sb.append(\", testAmount=\").append(testAmount);\n sb.append(\", amount=\").append(amount);\n sb.append(\", date=\").append(date);\n sb.append(\", status=\").append(status);\n sb.append(\", registrationNum=\").append(registrationNum);\n sb.append(\", excuteCheckAmount=\").append(excuteCheckAmount);\n sb.append(\", excuteTestAmount=\").append(excuteTestAmount);\n sb.append(\", excuteDispositionAmount=\").append(excuteDispositionAmount);\n sb.append(\", type=\").append(type);\n sb.append(\", deptId=\").append(deptId);\n sb.append(\", excuteNum=\").append(excuteNum);\n sb.append(\", serialVersionUID=\").append(serialVersionUID);\n sb.append(\"]\");\n return sb.toString();\n }\n}\n"} {"task_id": "Java_437", "language": "Java", "task_type": "empty", "source_file": "java/github/ZainZhao/HIS/his-cloud/his-cloud-service-bms/src/main/java/com/neu/his/cloud/service/bms/model/SmsWorkloadRecord.java", "mask_start_position": 5287, "mask_end_position": 5287, "canonical_solution": "", "pre_mask_code": "package com.neu.his.cloud.service.bms.model;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport java.io.Serializable;\nimport java.math.BigDecimal;\nimport java.util.Date;\n\npublic class SmsWorkloadRecord implements Serializable {\n\n private Long id;\n\n private Date createTime;\n\n private Long staffId;\n\n private BigDecimal medicineAmount;\n\n private BigDecimal herbalAmount;\n\n private BigDecimal checkAmount;\n\n private BigDecimal dispositionAmount;\n\n private BigDecimal registrationAmount;\n\n private BigDecimal testAmount;\n\n private BigDecimal amount;\n\n private Date date;\n\n private Integer status;\n\n private Long registrationNum;\n\n private BigDecimal excuteCheckAmount;\n\n private BigDecimal excuteTestAmount;\n\n private BigDecimal excuteDispositionAmount;\n\n private Integer type;\n\n private Long deptId;\n\n private Long excuteNum;\n\n private static final long serialVersionUID = 1L;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Long getStaffId() {\n return staffId;\n }\n\n public void setStaffId(Long staffId) {\n this.staffId = staffId;\n }\n\n public BigDecimal getMedicineAmount() {\n return medicineAmount;\n }\n\n public void setMedicineAmount(BigDecimal medicineAmount) {\n this.medicineAmount = medicineAmount;\n }\n\n public BigDecimal getHerbalAmount() {\n return herbalAmount;\n }\n\n public void setHerbalAmount(BigDecimal herbalAmount) {\n this.herbalAmount = herbalAmount;\n }\n\n public BigDecimal getCheckAmount() {\n return checkAmount;\n }\n\n public void setCheckAmount(BigDecimal checkAmount) {\n this.checkAmount = checkAmount;\n }\n\n public BigDecimal getDispositionAmount() {\n return dispositionAmount;\n }\n\n public void setDispositionAmount(BigDecimal dispositionAmount) {\n this.dispositionAmount = dispositionAmount;\n }\n\n public BigDecimal getRegistrationAmount() {\n return registrationAmount;\n }\n\n public void setRegistrationAmount(BigDecimal registrationAmount) {\n this.registrationAmount = registrationAmount;\n }\n\n public BigDecimal getTestAmount() {\n return testAmount;\n }\n\n public void setTestAmount(BigDecimal testAmount) {\n this.testAmount = testAmount;\n }\n\n public BigDecimal getAmount() {\n return amount;\n }\n\n public void setAmount(BigDecimal amount) {\n this.amount = amount;\n }\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public Integer getStatus() {\n return status;\n }\n\n public void setStatus(Integer status) {\n this.status = status;\n }\n\n public Long getRegistrationNum() {\n return registrationNum;\n }\n\n public void setRegistrationNum(Long registrationNum) {\n this.registrationNum = registrationNum;\n }\n\n public BigDecimal getExcuteCheckAmount() {\n return excuteCheckAmount;\n }\n\n public void setExcuteCheckAmount(BigDecimal excuteCheckAmount) {\n this.excuteCheckAmount = excuteCheckAmount;\n }\n\n public BigDecimal getExcuteTestAmount() {\n return excuteTestAmount;\n }\n\n public void setExcuteTestAmount(BigDecimal excuteTestAmount) {\n this.excuteTestAmount = excuteTestAmount;\n }\n\n public BigDecimal getExcuteDispositionAmount() {\n return excuteDispositionAmount;\n }\n\n public void setExcuteDispositionAmount(BigDecimal excuteDispositionAmount) {\n this.excuteDispositionAmount = excuteDispositionAmount;\n }\n\n public Integer getType() {\n return type;\n }\n\n public void setType(Integer type) {\n this.type = type;\n }\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n public Long getExcuteNum() {\n return excuteNum;\n }\n\n public void setExcuteNum(Long excuteNum) {\n this.excuteNum = excuteNum;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", createTime=\").append(createTime);\n sb.append(\", staffId=\").append(staffId);\n sb.append(\", medicineAmount=\").append(medicineAmount);\n sb.append(\", herbalAmount=\").append(herbalAmount);\n sb.append(\", checkAmount=\").append(checkAmount);\n sb.append(\", dispositionAmount=\").append(dispositionAmount);\n sb.append(\", registrationAmount=\").append(registrationAmount);\n sb.append(\", testAmount=\").append(testAmount);\n sb.append(\", amount=\").append(amount);\n sb.append(\", date=\").append(date);\n sb.append(\", status=\").append(status);\n sb.append(\", registrationNum=\").append(registrationNum);\n sb.append(\", excuteCheckAmount=\").append(excuteCheckAmount);\n sb.append(\", excuteTestA", "post_mask_code": "mount=\").append(excuteTestAmount);\n sb.append(\", excuteDispositionAmount=\").append(excuteDispositionAmount);\n sb.append(\", type=\").append(type);\n sb.append(\", deptId=\").append(deptId);\n sb.append(\", excuteNum=\").append(excuteNum);\n sb.append(\", serialVersionUID=\").append(serialVersionUID);\n sb.append(\"]\");\n return sb.toString();\n }\n}\n"} {"task_id": "Java_438", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/netbeans/ide/spi.debugger.ui/src/org/netbeans/spi/debugger/ui/ViewLifecycle.java", "mask_start_position": 840, "mask_end_position": 879, "canonical_solution": "public Models.CompoundModel getModel() ", "pre_mask_code": "package org.netbeans.spi.debugger.ui;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport org.netbeans.api.debugger.DebuggerEngine;\nimport org.netbeans.modules.debugger.ui.views.ViewModelListener;\nimport org.netbeans.spi.viewmodel.Models;\nimport org.netbeans.spi.viewmodel.Models.CompoundModel;\n\n/**\n * Support class for a custom view based on registered view models.\n *\n * @author Martin Entlicher\n * @since 2.34\n */\npublic final class ViewLifecycle {\n\n private ViewModelListener vml;\n\n private final CompoundModelUpdateListener cmul;\n\n ViewLifecycle(ViewModelListener vml, CompoundModelUpdateListener cmul) {\n this.vml = vml;\n this.cmul = cmul;\n }\n\n /**\n * Get the current compound model, that can be used to construct the custom\n * view.\n * @return The current compound model\n */\n ", "post_mask_code": "{\n return cmul.getCurrentModel();\n }\n\n /**\n * Add a listener, which is called with the updated compound model.\n * @param mul The model update listener\n */\n public void addModelUpdateListener(ModelUpdateListener mul) {\n cmul.addModelUpdateListener(mul);\n }\n\n /**\n * Remove a model update listener\n * @param mul The model update listener\n */\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n cmul.removeModelUpdateListener(mul);\n }\n\n /**\n * Destroy the underlying data, call this method when the view is closed.\n * Model updates will no longer be received after this method is called.\n */\n public void destroy() {\n vml.destroy();\n }\n\n /**\n * Model update listener, notified with updated compound model.\n */\n public static interface ModelUpdateListener {\n\n /**\n * Called when compound model is updated.\n *\n * @param compoundModel The new compound model\n * @param de The associated debugger engine, whose models were used to create the\n * compound model. Can be null, when no active debugger engine\n * was found.\n */\n public void modelUpdated(Models.CompoundModel compoundModel, DebuggerEngine de);\n }\n\n static class CompoundModelUpdateListener implements ModelUpdateListener {\n\n private final List muls = new LinkedList();\n\n private CompoundModel currentCompoundModel;\n\n public void addModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.add(mul);\n }\n }\n\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.remove(mul);\n }\n }\n\n public CompoundModel getCurrentModel() {\n return currentCompoundModel;\n }\n\n @Override\n public void modelUpdated(CompoundModel compoundModel, DebuggerEngine de) {\n List muls2;\n synchronized (muls) {\n currentCompoundModel = compoundModel;\n muls2 = new LinkedList(muls);\n }\n for (ModelUpdateListener mul : muls2) {\n mul.modelUpdated(compoundModel, de);\n }\n }\n }\n}\n"} {"task_id": "Java_439", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/netbeans/ide/spi.debugger.ui/src/org/netbeans/spi/debugger/ui/ViewLifecycle.java", "mask_start_position": 2647, "mask_end_position": 2740, "canonical_solution": "{\n synchronized (muls) {\n muls.remove(mul);\n }\n }", "pre_mask_code": "package org.netbeans.spi.debugger.ui;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport org.netbeans.api.debugger.DebuggerEngine;\nimport org.netbeans.modules.debugger.ui.views.ViewModelListener;\nimport org.netbeans.spi.viewmodel.Models;\nimport org.netbeans.spi.viewmodel.Models.CompoundModel;\n\n/**\n * Support class for a custom view based on registered view models.\n *\n * @author Martin Entlicher\n * @since 2.34\n */\npublic final class ViewLifecycle {\n\n private ViewModelListener vml;\n\n private final CompoundModelUpdateListener cmul;\n\n ViewLifecycle(ViewModelListener vml, CompoundModelUpdateListener cmul) {\n this.vml = vml;\n this.cmul = cmul;\n }\n\n /**\n * Get the current compound model, that can be used to construct the custom\n * view.\n * @return The current compound model\n */\n public Models.CompoundModel getModel() {\n return cmul.getCurrentModel();\n }\n\n /**\n * Add a listener, which is called with the updated compound model.\n * @param mul The model update listener\n */\n public void addModelUpdateListener(ModelUpdateListener mul) {\n cmul.addModelUpdateListener(mul);\n }\n\n /**\n * Remove a model update listener\n * @param mul The model update listener\n */\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n cmul.removeModelUpdateListener(mul);\n }\n\n /**\n * Destroy the underlying data, call this method when the view is closed.\n * Model updates will no longer be received after this method is called.\n */\n public void destroy() {\n vml.destroy();\n }\n\n /**\n * Model update listener, notified with updated compound model.\n */\n public static interface ModelUpdateListener {\n\n /**\n * Called when compound model is updated.\n *\n * @param compoundModel The new compound model\n * @param de The associated debugger engine, whose models were used to create the\n * compound model. Can be null, when no active debugger engine\n * was found.\n */\n public void modelUpdated(Models.CompoundModel compoundModel, DebuggerEngine de);\n }\n\n static class CompoundModelUpdateListener implements ModelUpdateListener {\n\n private final List muls = new LinkedList();\n\n private CompoundModel currentCompoundModel;\n\n public void addModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.add(mul);\n }\n }\n\n public void removeModelUpdateListener(ModelUpdateListener mul) ", "post_mask_code": "\n\n public CompoundModel getCurrentModel() {\n return currentCompoundModel;\n }\n\n @Override\n public void modelUpdated(CompoundModel compoundModel, DebuggerEngine de) {\n List muls2;\n synchronized (muls) {\n currentCompoundModel = compoundModel;\n muls2 = new LinkedList(muls);\n }\n for (ModelUpdateListener mul : muls2) {\n mul.modelUpdated(compoundModel, de);\n }\n }\n }\n}\n"} {"task_id": "Java_440", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/netbeans/ide/spi.debugger.ui/src/org/netbeans/spi/debugger/ui/ViewLifecycle.java", "mask_start_position": 2943, "mask_end_position": 2988, "canonical_solution": "\n List muls2;", "pre_mask_code": "package org.netbeans.spi.debugger.ui;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport org.netbeans.api.debugger.DebuggerEngine;\nimport org.netbeans.modules.debugger.ui.views.ViewModelListener;\nimport org.netbeans.spi.viewmodel.Models;\nimport org.netbeans.spi.viewmodel.Models.CompoundModel;\n\n/**\n * Support class for a custom view based on registered view models.\n *\n * @author Martin Entlicher\n * @since 2.34\n */\npublic final class ViewLifecycle {\n\n private ViewModelListener vml;\n\n private final CompoundModelUpdateListener cmul;\n\n ViewLifecycle(ViewModelListener vml, CompoundModelUpdateListener cmul) {\n this.vml = vml;\n this.cmul = cmul;\n }\n\n /**\n * Get the current compound model, that can be used to construct the custom\n * view.\n * @return The current compound model\n */\n public Models.CompoundModel getModel() {\n return cmul.getCurrentModel();\n }\n\n /**\n * Add a listener, which is called with the updated compound model.\n * @param mul The model update listener\n */\n public void addModelUpdateListener(ModelUpdateListener mul) {\n cmul.addModelUpdateListener(mul);\n }\n\n /**\n * Remove a model update listener\n * @param mul The model update listener\n */\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n cmul.removeModelUpdateListener(mul);\n }\n\n /**\n * Destroy the underlying data, call this method when the view is closed.\n * Model updates will no longer be received after this method is called.\n */\n public void destroy() {\n vml.destroy();\n }\n\n /**\n * Model update listener, notified with updated compound model.\n */\n public static interface ModelUpdateListener {\n\n /**\n * Called when compound model is updated.\n *\n * @param compoundModel The new compound model\n * @param de The associated debugger engine, whose models were used to create the\n * compound model. Can be null, when no active debugger engine\n * was found.\n */\n public void modelUpdated(Models.CompoundModel compoundModel, DebuggerEngine de);\n }\n\n static class CompoundModelUpdateListener implements ModelUpdateListener {\n\n private final List muls = new LinkedList();\n\n private CompoundModel currentCompoundModel;\n\n public void addModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.add(mul);\n }\n }\n\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.remove(mul);\n }\n }\n\n public CompoundModel getCurrentModel() {\n return currentCompoundModel;\n }\n\n @Override\n public void modelUpdated(CompoundModel compoundModel, DebuggerEngine de) {", "post_mask_code": "\n synchronized (muls) {\n currentCompoundModel = compoundModel;\n muls2 = new LinkedList(muls);\n }\n for (ModelUpdateListener mul : muls2) {\n mul.modelUpdated(compoundModel, de);\n }\n }\n }\n}\n"} {"task_id": "Java_441", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/netbeans/ide/spi.debugger.ui/src/org/netbeans/spi/debugger/ui/ViewLifecycle.java", "mask_start_position": 3001, "mask_end_position": 3157, "canonical_solution": "synchronized (muls) {\n currentCompoundModel = compoundModel;\n muls2 = new LinkedList(muls);\n }", "pre_mask_code": "package org.netbeans.spi.debugger.ui;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport org.netbeans.api.debugger.DebuggerEngine;\nimport org.netbeans.modules.debugger.ui.views.ViewModelListener;\nimport org.netbeans.spi.viewmodel.Models;\nimport org.netbeans.spi.viewmodel.Models.CompoundModel;\n\n/**\n * Support class for a custom view based on registered view models.\n *\n * @author Martin Entlicher\n * @since 2.34\n */\npublic final class ViewLifecycle {\n\n private ViewModelListener vml;\n\n private final CompoundModelUpdateListener cmul;\n\n ViewLifecycle(ViewModelListener vml, CompoundModelUpdateListener cmul) {\n this.vml = vml;\n this.cmul = cmul;\n }\n\n /**\n * Get the current compound model, that can be used to construct the custom\n * view.\n * @return The current compound model\n */\n public Models.CompoundModel getModel() {\n return cmul.getCurrentModel();\n }\n\n /**\n * Add a listener, which is called with the updated compound model.\n * @param mul The model update listener\n */\n public void addModelUpdateListener(ModelUpdateListener mul) {\n cmul.addModelUpdateListener(mul);\n }\n\n /**\n * Remove a model update listener\n * @param mul The model update listener\n */\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n cmul.removeModelUpdateListener(mul);\n }\n\n /**\n * Destroy the underlying data, call this method when the view is closed.\n * Model updates will no longer be received after this method is called.\n */\n public void destroy() {\n vml.destroy();\n }\n\n /**\n * Model update listener, notified with updated compound model.\n */\n public static interface ModelUpdateListener {\n\n /**\n * Called when compound model is updated.\n *\n * @param compoundModel The new compound model\n * @param de The associated debugger engine, whose models were used to create the\n * compound model. Can be null, when no active debugger engine\n * was found.\n */\n public void modelUpdated(Models.CompoundModel compoundModel, DebuggerEngine de);\n }\n\n static class CompoundModelUpdateListener implements ModelUpdateListener {\n\n private final List muls = new LinkedList();\n\n private CompoundModel currentCompoundModel;\n\n public void addModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.add(mul);\n }\n }\n\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.remove(mul);\n }\n }\n\n public CompoundModel getCurrentModel() {\n return currentCompoundModel;\n }\n\n @Override\n public void modelUpdated(CompoundModel compoundModel, DebuggerEngine de) {\n List muls2;\n ", "post_mask_code": "\n for (ModelUpdateListener mul : muls2) {\n mul.modelUpdated(compoundModel, de);\n }\n }\n }\n}\n"} {"task_id": "Java_442", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/netbeans/ide/spi.debugger.ui/src/org/netbeans/spi/debugger/ui/ViewLifecycle.java", "mask_start_position": 3170, "mask_end_position": 3286, "canonical_solution": "for (ModelUpdateListener mul : muls2) {\n mul.modelUpdated(compoundModel, de);\n }\n }", "pre_mask_code": "package org.netbeans.spi.debugger.ui;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport org.netbeans.api.debugger.DebuggerEngine;\nimport org.netbeans.modules.debugger.ui.views.ViewModelListener;\nimport org.netbeans.spi.viewmodel.Models;\nimport org.netbeans.spi.viewmodel.Models.CompoundModel;\n\n/**\n * Support class for a custom view based on registered view models.\n *\n * @author Martin Entlicher\n * @since 2.34\n */\npublic final class ViewLifecycle {\n\n private ViewModelListener vml;\n\n private final CompoundModelUpdateListener cmul;\n\n ViewLifecycle(ViewModelListener vml, CompoundModelUpdateListener cmul) {\n this.vml = vml;\n this.cmul = cmul;\n }\n\n /**\n * Get the current compound model, that can be used to construct the custom\n * view.\n * @return The current compound model\n */\n public Models.CompoundModel getModel() {\n return cmul.getCurrentModel();\n }\n\n /**\n * Add a listener, which is called with the updated compound model.\n * @param mul The model update listener\n */\n public void addModelUpdateListener(ModelUpdateListener mul) {\n cmul.addModelUpdateListener(mul);\n }\n\n /**\n * Remove a model update listener\n * @param mul The model update listener\n */\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n cmul.removeModelUpdateListener(mul);\n }\n\n /**\n * Destroy the underlying data, call this method when the view is closed.\n * Model updates will no longer be received after this method is called.\n */\n public void destroy() {\n vml.destroy();\n }\n\n /**\n * Model update listener, notified with updated compound model.\n */\n public static interface ModelUpdateListener {\n\n /**\n * Called when compound model is updated.\n *\n * @param compoundModel The new compound model\n * @param de The associated debugger engine, whose models were used to create the\n * compound model. Can be null, when no active debugger engine\n * was found.\n */\n public void modelUpdated(Models.CompoundModel compoundModel, DebuggerEngine de);\n }\n\n static class CompoundModelUpdateListener implements ModelUpdateListener {\n\n private final List muls = new LinkedList();\n\n private CompoundModel currentCompoundModel;\n\n public void addModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.add(mul);\n }\n }\n\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.remove(mul);\n }\n }\n\n public CompoundModel getCurrentModel() {\n return currentCompoundModel;\n }\n\n @Override\n public void modelUpdated(CompoundModel compoundModel, DebuggerEngine de) {\n List muls2;\n synchronized (muls) {\n currentCompoundModel = compoundModel;\n muls2 = new LinkedList(muls);\n }\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_443", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/netbeans/ide/spi.debugger.ui/src/org/netbeans/spi/debugger/ui/ViewLifecycle.java", "mask_start_position": 895, "mask_end_position": 919, "canonical_solution": " cmul.getCurrentModel();", "pre_mask_code": "package org.netbeans.spi.debugger.ui;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport org.netbeans.api.debugger.DebuggerEngine;\nimport org.netbeans.modules.debugger.ui.views.ViewModelListener;\nimport org.netbeans.spi.viewmodel.Models;\nimport org.netbeans.spi.viewmodel.Models.CompoundModel;\n\n/**\n * Support class for a custom view based on registered view models.\n *\n * @author Martin Entlicher\n * @since 2.34\n */\npublic final class ViewLifecycle {\n\n private ViewModelListener vml;\n\n private final CompoundModelUpdateListener cmul;\n\n ViewLifecycle(ViewModelListener vml, CompoundModelUpdateListener cmul) {\n this.vml = vml;\n this.cmul = cmul;\n }\n\n /**\n * Get the current compound model, that can be used to construct the custom\n * view.\n * @return The current compound model\n */\n public Models.CompoundModel getModel() {\n return", "post_mask_code": "\n }\n\n /**\n * Add a listener, which is called with the updated compound model.\n * @param mul The model update listener\n */\n public void addModelUpdateListener(ModelUpdateListener mul) {\n cmul.addModelUpdateListener(mul);\n }\n\n /**\n * Remove a model update listener\n * @param mul The model update listener\n */\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n cmul.removeModelUpdateListener(mul);\n }\n\n /**\n * Destroy the underlying data, call this method when the view is closed.\n * Model updates will no longer be received after this method is called.\n */\n public void destroy() {\n vml.destroy();\n }\n\n /**\n * Model update listener, notified with updated compound model.\n */\n public static interface ModelUpdateListener {\n\n /**\n * Called when compound model is updated.\n *\n * @param compoundModel The new compound model\n * @param de The associated debugger engine, whose models were used to create the\n * compound model. Can be null, when no active debugger engine\n * was found.\n */\n public void modelUpdated(Models.CompoundModel compoundModel, DebuggerEngine de);\n }\n\n static class CompoundModelUpdateListener implements ModelUpdateListener {\n\n private final List muls = new LinkedList();\n\n private CompoundModel currentCompoundModel;\n\n public void addModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.add(mul);\n }\n }\n\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.remove(mul);\n }\n }\n\n public CompoundModel getCurrentModel() {\n return currentCompoundModel;\n }\n\n @Override\n public void modelUpdated(CompoundModel compoundModel, DebuggerEngine de) {\n List muls2;\n synchronized (muls) {\n currentCompoundModel = compoundModel;\n muls2 = new LinkedList(muls);\n }\n for (ModelUpdateListener mul : muls2) {\n mul.modelUpdated(compoundModel, de);\n }\n }\n }\n}\n"} {"task_id": "Java_444", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/apache/netbeans/ide/spi.debugger.ui/src/org/netbeans/spi/debugger/ui/ViewLifecycle.java", "mask_start_position": 840, "mask_end_position": 925, "canonical_solution": "public Models.CompoundModel getModel() {\n return cmul.getCurrentModel();\n }", "pre_mask_code": "package org.netbeans.spi.debugger.ui;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport org.netbeans.api.debugger.DebuggerEngine;\nimport org.netbeans.modules.debugger.ui.views.ViewModelListener;\nimport org.netbeans.spi.viewmodel.Models;\nimport org.netbeans.spi.viewmodel.Models.CompoundModel;\n\n/**\n * Support class for a custom view based on registered view models.\n *\n * @author Martin Entlicher\n * @since 2.34\n */\npublic final class ViewLifecycle {\n\n private ViewModelListener vml;\n\n private final CompoundModelUpdateListener cmul;\n\n ViewLifecycle(ViewModelListener vml, CompoundModelUpdateListener cmul) {\n this.vml = vml;\n this.cmul = cmul;\n }\n\n /**\n * Get the current compound model, that can be used to construct the custom\n * view.\n * @return The current compound model\n */\n ", "post_mask_code": "\n\n /**\n * Add a listener, which is called with the updated compound model.\n * @param mul The model update listener\n */\n public void addModelUpdateListener(ModelUpdateListener mul) {\n cmul.addModelUpdateListener(mul);\n }\n\n /**\n * Remove a model update listener\n * @param mul The model update listener\n */\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n cmul.removeModelUpdateListener(mul);\n }\n\n /**\n * Destroy the underlying data, call this method when the view is closed.\n * Model updates will no longer be received after this method is called.\n */\n public void destroy() {\n vml.destroy();\n }\n\n /**\n * Model update listener, notified with updated compound model.\n */\n public static interface ModelUpdateListener {\n\n /**\n * Called when compound model is updated.\n *\n * @param compoundModel The new compound model\n * @param de The associated debugger engine, whose models were used to create the\n * compound model. Can be null, when no active debugger engine\n * was found.\n */\n public void modelUpdated(Models.CompoundModel compoundModel, DebuggerEngine de);\n }\n\n static class CompoundModelUpdateListener implements ModelUpdateListener {\n\n private final List muls = new LinkedList();\n\n private CompoundModel currentCompoundModel;\n\n public void addModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.add(mul);\n }\n }\n\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.remove(mul);\n }\n }\n\n public CompoundModel getCurrentModel() {\n return currentCompoundModel;\n }\n\n @Override\n public void modelUpdated(CompoundModel compoundModel, DebuggerEngine de) {\n List muls2;\n synchronized (muls) {\n currentCompoundModel = compoundModel;\n muls2 = new LinkedList(muls);\n }\n for (ModelUpdateListener mul : muls2) {\n mul.modelUpdated(compoundModel, de);\n }\n }\n }\n}\n"} {"task_id": "Java_445", "language": "Java", "task_type": "empty", "source_file": "java/github/apache/netbeans/ide/spi.debugger.ui/src/org/netbeans/spi/debugger/ui/ViewLifecycle.java", "mask_start_position": 2912, "mask_end_position": 2912, "canonical_solution": "", "pre_mask_code": "package org.netbeans.spi.debugger.ui;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport org.netbeans.api.debugger.DebuggerEngine;\nimport org.netbeans.modules.debugger.ui.views.ViewModelListener;\nimport org.netbeans.spi.viewmodel.Models;\nimport org.netbeans.spi.viewmodel.Models.CompoundModel;\n\n/**\n * Support class for a custom view based on registered view models.\n *\n * @author Martin Entlicher\n * @since 2.34\n */\npublic final class ViewLifecycle {\n\n private ViewModelListener vml;\n\n private final CompoundModelUpdateListener cmul;\n\n ViewLifecycle(ViewModelListener vml, CompoundModelUpdateListener cmul) {\n this.vml = vml;\n this.cmul = cmul;\n }\n\n /**\n * Get the current compound model, that can be used to construct the custom\n * view.\n * @return The current compound model\n */\n public Models.CompoundModel getModel() {\n return cmul.getCurrentModel();\n }\n\n /**\n * Add a listener, which is called with the updated compound model.\n * @param mul The model update listener\n */\n public void addModelUpdateListener(ModelUpdateListener mul) {\n cmul.addModelUpdateListener(mul);\n }\n\n /**\n * Remove a model update listener\n * @param mul The model update listener\n */\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n cmul.removeModelUpdateListener(mul);\n }\n\n /**\n * Destroy the underlying data, call this method when the view is closed.\n * Model updates will no longer be received after this method is called.\n */\n public void destroy() {\n vml.destroy();\n }\n\n /**\n * Model update listener, notified with updated compound model.\n */\n public static interface ModelUpdateListener {\n\n /**\n * Called when compound model is updated.\n *\n * @param compoundModel The new compound model\n * @param de The associated debugger engine, whose models were used to create the\n * compound model. Can be null, when no active debugger engine\n * was found.\n */\n public void modelUpdated(Models.CompoundModel compoundModel, DebuggerEngine de);\n }\n\n static class CompoundModelUpdateListener implements ModelUpdateListener {\n\n private final List muls = new LinkedList();\n\n private CompoundModel currentCompoundModel;\n\n public void addModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.add(mul);\n }\n }\n\n public void removeModelUpdateListener(ModelUpdateListener mul) {\n synchronized (muls) {\n muls.remove(mul);\n }\n }\n\n public CompoundModel getCurrentModel() {\n return currentCompoundModel;\n }\n\n @Override\n public void modelUpdated(CompoundModel comp", "post_mask_code": "oundModel, DebuggerEngine de) {\n List muls2;\n synchronized (muls) {\n currentCompoundModel = compoundModel;\n muls2 = new LinkedList(muls);\n }\n for (ModelUpdateListener mul : muls2) {\n mul.modelUpdated(compoundModel, de);\n }\n }\n }\n}\n"} {"task_id": "Java_446", "language": "Java", "task_type": "method_signature", "source_file": "java/github/OpenRock/OpenAM/openam-core/src/main/java/com/sun/identity/config/wizard/Step6.java", "mask_start_position": 696, "mask_end_position": 717, "canonical_solution": "public void onInit() ", "pre_mask_code": "/**\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * $Id: Step6.java,v 1.13 2009/01/05 23:17:10 veiming Exp $\n */\npackage com.sun.identity.config.wizard;\n\nimport com.sun.identity.config.SessionAttributeNames;\nimport com.sun.identity.config.util.ProtectedPage;\nimport org.apache.click.control.ActionLink;\n\n/**\n * This is the first step in the advanced configuration flow.\n * The user will be required to add the default admin password and\n * the agent passwords.\n */\npublic class Step6 extends ProtectedPage {\n\n // this links required for client side validation calls\n public ActionLink validateAgent = new ActionLink(\"checkAgentPassword\", this, \"checkAgentPassword\");\n\n ", "post_mask_code": "{\n String agentPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD);\n if (agentPwd != null) {\n addModel(\"agentPassword\", agentPwd);\n }\n String confirmPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD_CONFIRM);\n if (confirmPwd != null) {\n addModel(\"agentConfirm\", confirmPwd);\n }\n super.onInit();\n }\n\n public boolean checkAgentPassword() {\n String agentPassword = toString(\"agent\");\n String agentConfirm = toString(\"agentConfirm\");\n String tmpadmin = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_ADMIN_PWD);\n if (agentPassword == null || agentConfirm == null) {\n writeInvalid(getLocalizedString(\"missing.required.field\"));\n } else if (agentPassword.equals(tmpadmin)) {\n writeInvalid(getLocalizedString(\"agent.admin.passwords.match\"));\n } else if (agentPassword.length() < 8) {\n writeInvalid(getLocalizedString(\"invalid.password.length\"));\n } else if (!agentPassword.equals(agentConfirm)) {\n writeInvalid(getLocalizedString(\"passwords.do.not.match\"));\n } else {\n writeValid(\"OK\");\n getContext().setSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD, agentPassword);\n }\n setPath(null);\n return false;\n }\n}\n"} {"task_id": "Java_447", "language": "Java", "task_type": "method_body", "source_file": "java/github/OpenRock/OpenAM/openam-core/src/main/java/com/sun/identity/config/wizard/Step6.java", "mask_start_position": 717, "mask_end_position": 1183, "canonical_solution": "{\n String agentPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD);\n if (agentPwd != null) {\n addModel(\"agentPassword\", agentPwd);\n }\n String confirmPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD_CONFIRM);\n if (confirmPwd != null) {\n addModel(\"agentConfirm\", confirmPwd);\n }\n super.onInit();\n }", "pre_mask_code": "/**\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * $Id: Step6.java,v 1.13 2009/01/05 23:17:10 veiming Exp $\n */\npackage com.sun.identity.config.wizard;\n\nimport com.sun.identity.config.SessionAttributeNames;\nimport com.sun.identity.config.util.ProtectedPage;\nimport org.apache.click.control.ActionLink;\n\n/**\n * This is the first step in the advanced configuration flow.\n * The user will be required to add the default admin password and\n * the agent passwords.\n */\npublic class Step6 extends ProtectedPage {\n\n // this links required for client side validation calls\n public ActionLink validateAgent = new ActionLink(\"checkAgentPassword\", this, \"checkAgentPassword\");\n\n public void onInit() ", "post_mask_code": "\n\n public boolean checkAgentPassword() {\n String agentPassword = toString(\"agent\");\n String agentConfirm = toString(\"agentConfirm\");\n String tmpadmin = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_ADMIN_PWD);\n if (agentPassword == null || agentConfirm == null) {\n writeInvalid(getLocalizedString(\"missing.required.field\"));\n } else if (agentPassword.equals(tmpadmin)) {\n writeInvalid(getLocalizedString(\"agent.admin.passwords.match\"));\n } else if (agentPassword.length() < 8) {\n writeInvalid(getLocalizedString(\"invalid.password.length\"));\n } else if (!agentPassword.equals(agentConfirm)) {\n writeInvalid(getLocalizedString(\"passwords.do.not.match\"));\n } else {\n writeValid(\"OK\");\n getContext().setSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD, agentPassword);\n }\n setPath(null);\n return false;\n }\n}\n"} {"task_id": "Java_448", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/OpenRock/OpenAM/openam-core/src/main/java/com/sun/identity/config/wizard/Step6.java", "mask_start_position": 718, "mask_end_position": 929, "canonical_solution": "\n String agentPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD);\n if (agentPwd != null) {\n addModel(\"agentPassword\", agentPwd);\n }", "pre_mask_code": "/**\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * $Id: Step6.java,v 1.13 2009/01/05 23:17:10 veiming Exp $\n */\npackage com.sun.identity.config.wizard;\n\nimport com.sun.identity.config.SessionAttributeNames;\nimport com.sun.identity.config.util.ProtectedPage;\nimport org.apache.click.control.ActionLink;\n\n/**\n * This is the first step in the advanced configuration flow.\n * The user will be required to add the default admin password and\n * the agent passwords.\n */\npublic class Step6 extends ProtectedPage {\n\n // this links required for client side validation calls\n public ActionLink validateAgent = new ActionLink(\"checkAgentPassword\", this, \"checkAgentPassword\");\n\n public void onInit() {", "post_mask_code": "\n String confirmPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD_CONFIRM);\n if (confirmPwd != null) {\n addModel(\"agentConfirm\", confirmPwd);\n }\n super.onInit();\n }\n\n public boolean checkAgentPassword() {\n String agentPassword = toString(\"agent\");\n String agentConfirm = toString(\"agentConfirm\");\n String tmpadmin = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_ADMIN_PWD);\n if (agentPassword == null || agentConfirm == null) {\n writeInvalid(getLocalizedString(\"missing.required.field\"));\n } else if (agentPassword.equals(tmpadmin)) {\n writeInvalid(getLocalizedString(\"agent.admin.passwords.match\"));\n } else if (agentPassword.length() < 8) {\n writeInvalid(getLocalizedString(\"invalid.password.length\"));\n } else if (!agentPassword.equals(agentConfirm)) {\n writeInvalid(getLocalizedString(\"passwords.do.not.match\"));\n } else {\n writeValid(\"OK\");\n getContext().setSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD, agentPassword);\n }\n setPath(null);\n return false;\n }\n}\n"} {"task_id": "Java_449", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/OpenRock/OpenAM/openam-core/src/main/java/com/sun/identity/config/wizard/Step6.java", "mask_start_position": 938, "mask_end_position": 1153, "canonical_solution": "String confirmPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD_CONFIRM);\n if (confirmPwd != null) {\n addModel(\"agentConfirm\", confirmPwd);\n }", "pre_mask_code": "/**\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * $Id: Step6.java,v 1.13 2009/01/05 23:17:10 veiming Exp $\n */\npackage com.sun.identity.config.wizard;\n\nimport com.sun.identity.config.SessionAttributeNames;\nimport com.sun.identity.config.util.ProtectedPage;\nimport org.apache.click.control.ActionLink;\n\n/**\n * This is the first step in the advanced configuration flow.\n * The user will be required to add the default admin password and\n * the agent passwords.\n */\npublic class Step6 extends ProtectedPage {\n\n // this links required for client side validation calls\n public ActionLink validateAgent = new ActionLink(\"checkAgentPassword\", this, \"checkAgentPassword\");\n\n public void onInit() {\n String agentPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD);\n if (agentPwd != null) {\n addModel(\"agentPassword\", agentPwd);\n }\n ", "post_mask_code": "\n super.onInit();\n }\n\n public boolean checkAgentPassword() {\n String agentPassword = toString(\"agent\");\n String agentConfirm = toString(\"agentConfirm\");\n String tmpadmin = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_ADMIN_PWD);\n if (agentPassword == null || agentConfirm == null) {\n writeInvalid(getLocalizedString(\"missing.required.field\"));\n } else if (agentPassword.equals(tmpadmin)) {\n writeInvalid(getLocalizedString(\"agent.admin.passwords.match\"));\n } else if (agentPassword.length() < 8) {\n writeInvalid(getLocalizedString(\"invalid.password.length\"));\n } else if (!agentPassword.equals(agentConfirm)) {\n writeInvalid(getLocalizedString(\"passwords.do.not.match\"));\n } else {\n writeValid(\"OK\");\n getContext().setSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD, agentPassword);\n }\n setPath(null);\n return false;\n }\n}\n"} {"task_id": "Java_450", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/OpenRock/OpenAM/openam-core/src/main/java/com/sun/identity/config/wizard/Step6.java", "mask_start_position": 1162, "mask_end_position": 1183, "canonical_solution": "super.onInit();\n }", "pre_mask_code": "/**\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * $Id: Step6.java,v 1.13 2009/01/05 23:17:10 veiming Exp $\n */\npackage com.sun.identity.config.wizard;\n\nimport com.sun.identity.config.SessionAttributeNames;\nimport com.sun.identity.config.util.ProtectedPage;\nimport org.apache.click.control.ActionLink;\n\n/**\n * This is the first step in the advanced configuration flow.\n * The user will be required to add the default admin password and\n * the agent passwords.\n */\npublic class Step6 extends ProtectedPage {\n\n // this links required for client side validation calls\n public ActionLink validateAgent = new ActionLink(\"checkAgentPassword\", this, \"checkAgentPassword\");\n\n public void onInit() {\n String agentPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD);\n if (agentPwd != null) {\n addModel(\"agentPassword\", agentPwd);\n }\n String confirmPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD_CONFIRM);\n if (confirmPwd != null) {\n addModel(\"agentConfirm\", confirmPwd);\n }\n ", "post_mask_code": "\n\n public boolean checkAgentPassword() {\n String agentPassword = toString(\"agent\");\n String agentConfirm = toString(\"agentConfirm\");\n String tmpadmin = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_ADMIN_PWD);\n if (agentPassword == null || agentConfirm == null) {\n writeInvalid(getLocalizedString(\"missing.required.field\"));\n } else if (agentPassword.equals(tmpadmin)) {\n writeInvalid(getLocalizedString(\"agent.admin.passwords.match\"));\n } else if (agentPassword.length() < 8) {\n writeInvalid(getLocalizedString(\"invalid.password.length\"));\n } else if (!agentPassword.equals(agentConfirm)) {\n writeInvalid(getLocalizedString(\"passwords.do.not.match\"));\n } else {\n writeValid(\"OK\");\n getContext().setSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD, agentPassword);\n }\n setPath(null);\n return false;\n }\n}\n"} {"task_id": "Java_451", "language": "Java", "task_type": "single_line", "source_file": "java/github/OpenRock/OpenAM/openam-core/src/main/java/com/sun/identity/config/wizard/Step6.java", "mask_start_position": 1028, "mask_end_position": 1059, "canonical_solution": "_VAR_AMLDAPUSERPASSWD_CONFIRM);", "pre_mask_code": "/**\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * $Id: Step6.java,v 1.13 2009/01/05 23:17:10 veiming Exp $\n */\npackage com.sun.identity.config.wizard;\n\nimport com.sun.identity.config.SessionAttributeNames;\nimport com.sun.identity.config.util.ProtectedPage;\nimport org.apache.click.control.ActionLink;\n\n/**\n * This is the first step in the advanced configuration flow.\n * The user will be required to add the default admin password and\n * the agent passwords.\n */\npublic class Step6 extends ProtectedPage {\n\n // this links required for client side validation calls\n public ActionLink validateAgent = new ActionLink(\"checkAgentPassword\", this, \"checkAgentPassword\");\n\n public void onInit() {\n String agentPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD);\n if (agentPwd != null) {\n addModel(\"agentPassword\", agentPwd);\n }\n String confirmPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG", "post_mask_code": "\n if (confirmPwd != null) {\n addModel(\"agentConfirm\", confirmPwd);\n }\n super.onInit();\n }\n\n public boolean checkAgentPassword() {\n String agentPassword = toString(\"agent\");\n String agentConfirm = toString(\"agentConfirm\");\n String tmpadmin = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_ADMIN_PWD);\n if (agentPassword == null || agentConfirm == null) {\n writeInvalid(getLocalizedString(\"missing.required.field\"));\n } else if (agentPassword.equals(tmpadmin)) {\n writeInvalid(getLocalizedString(\"agent.admin.passwords.match\"));\n } else if (agentPassword.length() < 8) {\n writeInvalid(getLocalizedString(\"invalid.password.length\"));\n } else if (!agentPassword.equals(agentConfirm)) {\n writeInvalid(getLocalizedString(\"passwords.do.not.match\"));\n } else {\n writeValid(\"OK\");\n getContext().setSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD, agentPassword);\n }\n setPath(null);\n return false;\n }\n}\n"} {"task_id": "Java_452", "language": "Java", "task_type": "if_statement", "source_file": "java/github/OpenRock/OpenAM/openam-core/src/main/java/com/sun/identity/config/wizard/Step6.java", "mask_start_position": 847, "mask_end_position": 929, "canonical_solution": "if (agentPwd != null) {\n addModel(\"agentPassword\", agentPwd);\n }", "pre_mask_code": "/**\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * $Id: Step6.java,v 1.13 2009/01/05 23:17:10 veiming Exp $\n */\npackage com.sun.identity.config.wizard;\n\nimport com.sun.identity.config.SessionAttributeNames;\nimport com.sun.identity.config.util.ProtectedPage;\nimport org.apache.click.control.ActionLink;\n\n/**\n * This is the first step in the advanced configuration flow.\n * The user will be required to add the default admin password and\n * the agent passwords.\n */\npublic class Step6 extends ProtectedPage {\n\n // this links required for client side validation calls\n public ActionLink validateAgent = new ActionLink(\"checkAgentPassword\", this, \"checkAgentPassword\");\n\n public void onInit() {\n String agentPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD);\n ", "post_mask_code": "\n String confirmPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD_CONFIRM);\n if (confirmPwd != null) {\n addModel(\"agentConfirm\", confirmPwd);\n }\n super.onInit();\n }\n\n public boolean checkAgentPassword() {\n String agentPassword = toString(\"agent\");\n String agentConfirm = toString(\"agentConfirm\");\n String tmpadmin = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_ADMIN_PWD);\n if (agentPassword == null || agentConfirm == null) {\n writeInvalid(getLocalizedString(\"missing.required.field\"));\n } else if (agentPassword.equals(tmpadmin)) {\n writeInvalid(getLocalizedString(\"agent.admin.passwords.match\"));\n } else if (agentPassword.length() < 8) {\n writeInvalid(getLocalizedString(\"invalid.password.length\"));\n } else if (!agentPassword.equals(agentConfirm)) {\n writeInvalid(getLocalizedString(\"passwords.do.not.match\"));\n } else {\n writeValid(\"OK\");\n getContext().setSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD, agentPassword);\n }\n setPath(null);\n return false;\n }\n}\n"} {"task_id": "Java_453", "language": "Java", "task_type": "empty", "source_file": "java/github/OpenRock/OpenAM/openam-core/src/main/java/com/sun/identity/config/wizard/Step6.java", "mask_start_position": 1530, "mask_end_position": 1530, "canonical_solution": "", "pre_mask_code": "/**\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * $Id: Step6.java,v 1.13 2009/01/05 23:17:10 veiming Exp $\n */\npackage com.sun.identity.config.wizard;\n\nimport com.sun.identity.config.SessionAttributeNames;\nimport com.sun.identity.config.util.ProtectedPage;\nimport org.apache.click.control.ActionLink;\n\n/**\n * This is the first step in the advanced configuration flow.\n * The user will be required to add the default admin password and\n * the agent passwords.\n */\npublic class Step6 extends ProtectedPage {\n\n // this links required for client side validation calls\n public ActionLink validateAgent = new ActionLink(\"checkAgentPassword\", this, \"checkAgentPassword\");\n\n public void onInit() {\n String agentPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD);\n if (agentPwd != null) {\n addModel(\"agentPassword\", agentPwd);\n }\n String confirmPwd = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD_CONFIRM);\n if (confirmPwd != null) {\n addModel(\"agentConfirm\", confirmPwd);\n }\n super.onInit();\n }\n\n public boolean checkAgentPassword() {\n String agentPassword = toString(\"agent\");\n String agentConfirm = toString(\"agentConfirm\");\n String tmpadmin = (String) getContext().getSessionAttribute(SessionAttributeNames.CONFIG_VAR_ADMIN_PWD);\n if (agentPassword == null || agentConfirm == null) {\n writeInvali", "post_mask_code": "d(getLocalizedString(\"missing.required.field\"));\n } else if (agentPassword.equals(tmpadmin)) {\n writeInvalid(getLocalizedString(\"agent.admin.passwords.match\"));\n } else if (agentPassword.length() < 8) {\n writeInvalid(getLocalizedString(\"invalid.password.length\"));\n } else if (!agentPassword.equals(agentConfirm)) {\n writeInvalid(getLocalizedString(\"passwords.do.not.match\"));\n } else {\n writeValid(\"OK\");\n getContext().setSessionAttribute(SessionAttributeNames.CONFIG_VAR_AMLDAPUSERPASSWD, agentPassword);\n }\n setPath(null);\n return false;\n }\n}\n"} {"task_id": "Java_454", "language": "Java", "task_type": "method_signature", "source_file": "java/github/liusCoding/springcloud-2020/cloud-stream-rabbitmq-provider-8801/src/main/java/com/liuscoding/springcloud/service/impl/MessageProviderImpl.java", "mask_start_position": 604, "mask_end_position": 639, "canonical_solution": "@Override\n public String send() ", "pre_mask_code": "package com.liuscoding.springcloud.service.impl;\n\nimport com.liuscoding.springcloud.service.IMessageProvider;\nimport org.springframework.cloud.stream.annotation.EnableBinding;\nimport org.springframework.cloud.stream.messaging.Source;\nimport org.springframework.messaging.MessageChannel;\nimport org.springframework.messaging.support.MessageBuilder;\nimport java.util.UUID;\n\n@EnableBinding(Source.class)\npublic class MessageProviderImpl implements IMessageProvider {\n\n private final MessageChannel output;\n\n public MessageProviderImpl(MessageChannel output) {\n this.output = output;\n }\n\n ", "post_mask_code": "{\n String serial = UUID.randomUUID().toString();\n output.send(MessageBuilder.withPayload(serial).build());\n System.out.println(\"****************serial:\" + serial);\n return serial;\n }\n}\n"} {"task_id": "Java_455", "language": "Java", "task_type": "method_body", "source_file": "java/github/liusCoding/springcloud-2020/cloud-stream-rabbitmq-provider-8801/src/main/java/com/liuscoding/springcloud/service/impl/MessageProviderImpl.java", "mask_start_position": 639, "mask_end_position": 852, "canonical_solution": "{\n String serial = UUID.randomUUID().toString();\n output.send(MessageBuilder.withPayload(serial).build());\n System.out.println(\"****************serial:\" + serial);\n return serial;\n }", "pre_mask_code": "package com.liuscoding.springcloud.service.impl;\n\nimport com.liuscoding.springcloud.service.IMessageProvider;\nimport org.springframework.cloud.stream.annotation.EnableBinding;\nimport org.springframework.cloud.stream.messaging.Source;\nimport org.springframework.messaging.MessageChannel;\nimport org.springframework.messaging.support.MessageBuilder;\nimport java.util.UUID;\n\n@EnableBinding(Source.class)\npublic class MessageProviderImpl implements IMessageProvider {\n\n private final MessageChannel output;\n\n public MessageProviderImpl(MessageChannel output) {\n this.output = output;\n }\n\n @Override\n public String send() ", "post_mask_code": "\n}\n"} {"task_id": "Java_456", "language": "Java", "task_type": "single_line", "source_file": "java/github/liusCoding/springcloud-2020/cloud-stream-rabbitmq-provider-8801/src/main/java/com/liuscoding/springcloud/service/impl/MessageProviderImpl.java", "mask_start_position": 685, "mask_end_position": 694, "canonical_solution": "String();", "pre_mask_code": "package com.liuscoding.springcloud.service.impl;\n\nimport com.liuscoding.springcloud.service.IMessageProvider;\nimport org.springframework.cloud.stream.annotation.EnableBinding;\nimport org.springframework.cloud.stream.messaging.Source;\nimport org.springframework.messaging.MessageChannel;\nimport org.springframework.messaging.support.MessageBuilder;\nimport java.util.UUID;\n\n@EnableBinding(Source.class)\npublic class MessageProviderImpl implements IMessageProvider {\n\n private final MessageChannel output;\n\n public MessageProviderImpl(MessageChannel output) {\n this.output = output;\n }\n\n @Override\n public String send() {\n String serial = UUID.randomUUID().to", "post_mask_code": "\n output.send(MessageBuilder.withPayload(serial).build());\n System.out.println(\"****************serial:\" + serial);\n return serial;\n }\n}\n"} {"task_id": "Java_457", "language": "Java", "task_type": "empty", "source_file": "java/github/liusCoding/springcloud-2020/cloud-stream-rabbitmq-provider-8801/src/main/java/com/liuscoding/springcloud/service/impl/MessageProviderImpl.java", "mask_start_position": 736, "mask_end_position": 736, "canonical_solution": "", "pre_mask_code": "package com.liuscoding.springcloud.service.impl;\n\nimport com.liuscoding.springcloud.service.IMessageProvider;\nimport org.springframework.cloud.stream.annotation.EnableBinding;\nimport org.springframework.cloud.stream.messaging.Source;\nimport org.springframework.messaging.MessageChannel;\nimport org.springframework.messaging.support.MessageBuilder;\nimport java.util.UUID;\n\n@EnableBinding(Source.class)\npublic class MessageProviderImpl implements IMessageProvider {\n\n private final MessageChannel output;\n\n public MessageProviderImpl(MessageChannel output) {\n this.output = output;\n }\n\n @Override\n public String send() {\n String serial = UUID.randomUUID().toString();\n output.send(MessageBuilder.withPa", "post_mask_code": "yload(serial).build());\n System.out.println(\"****************serial:\" + serial);\n return serial;\n }\n}\n"} {"task_id": "Java_458", "language": "Java", "task_type": "empty", "source_file": "java/github/projectdanube/xdi2/core/src/main/java/xdi2/core/security/digest/validate/SHADigestValidator.java", "mask_start_position": 38, "mask_end_position": 38, "canonical_solution": "", "pre_mask_code": "package xdi2.core.security.digest.vali", "post_mask_code": "date;\n\nimport xdi2.core.features.digests.SHADigest;\n\n/**\n * This is a DigestValidator that can validate an XDI SHADigest.\n */\npublic interface SHADigestValidator extends DigestValidator {\n}\n"} {"task_id": "Java_459", "language": "Java", "task_type": "method_signature", "source_file": "java/github/seven332/EhViewer/app/src/main/java/com/hippo/drawable/DrawableWrapper.java", "mask_start_position": 2322, "mask_end_position": 2354, "canonical_solution": "public int getIntrinsicHeight() ", "pre_mask_code": "package com.hippo.drawable;\n\nimport android.content.res.ColorStateList;\nimport android.graphics.Canvas;\nimport android.graphics.ColorFilter;\nimport android.graphics.PorterDuff;\nimport android.graphics.Rect;\nimport android.graphics.Region;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.core.graphics.drawable.DrawableCompat;\n\npublic class DrawableWrapper extends Drawable implements Drawable.Callback {\n\n private Drawable mDrawable;\n\n public DrawableWrapper(Drawable drawable) {\n this.setWrappedDrawable(drawable);\n }\n\n public void draw(@NonNull Canvas canvas) {\n this.mDrawable.draw(canvas);\n }\n\n protected void onBoundsChange(Rect bounds) {\n this.mDrawable.setBounds(bounds);\n }\n\n public void setChangingConfigurations(int configs) {\n this.mDrawable.setChangingConfigurations(configs);\n }\n\n public int getChangingConfigurations() {\n return this.mDrawable.getChangingConfigurations();\n }\n\n public void setDither(boolean dither) {\n this.mDrawable.setDither(dither);\n }\n\n public void setFilterBitmap(boolean filter) {\n this.mDrawable.setFilterBitmap(filter);\n }\n\n public void setAlpha(int alpha) {\n this.mDrawable.setAlpha(alpha);\n }\n\n public void setColorFilter(ColorFilter cf) {\n this.mDrawable.setColorFilter(cf);\n }\n\n public boolean isStateful() {\n return this.mDrawable.isStateful();\n }\n\n public boolean setState(@NonNull int[] stateSet) {\n return this.mDrawable.setState(stateSet);\n }\n\n @NonNull\n public int[] getState() {\n return this.mDrawable.getState();\n }\n\n public void jumpToCurrentState() {\n this.mDrawable.jumpToCurrentState();\n }\n\n @NonNull\n public Drawable getCurrent() {\n return this.mDrawable.getCurrent();\n }\n\n public boolean setVisible(boolean visible, boolean restart) {\n return super.setVisible(visible, restart) || this.mDrawable.setVisible(visible, restart);\n }\n\n public int getOpacity() {\n return this.mDrawable.getOpacity();\n }\n\n public Region getTransparentRegion() {\n return this.mDrawable.getTransparentRegion();\n }\n\n public int getIntrinsicWidth() {\n return this.mDrawable.getIntrinsicWidth();\n }\n\n ", "post_mask_code": "{\n return this.mDrawable.getIntrinsicHeight();\n }\n\n public int getMinimumWidth() {\n return this.mDrawable.getMinimumWidth();\n }\n\n public int getMinimumHeight() {\n return this.mDrawable.getMinimumHeight();\n }\n\n public boolean getPadding(@NonNull Rect padding) {\n return this.mDrawable.getPadding(padding);\n }\n\n public void invalidateDrawable(@NonNull Drawable who) {\n this.invalidateSelf();\n }\n\n public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {\n this.scheduleSelf(what, when);\n }\n\n public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {\n this.unscheduleSelf(what);\n }\n\n protected boolean onLevelChange(int level) {\n return this.mDrawable.setLevel(level);\n }\n\n public void setAutoMirrored(boolean mirrored) {\n DrawableCompat.setAutoMirrored(this.mDrawable, mirrored);\n }\n\n public boolean isAutoMirrored() {\n return DrawableCompat.isAutoMirrored(this.mDrawable);\n }\n\n public void setTint(int tint) {\n DrawableCompat.setTint(this.mDrawable, tint);\n }\n\n public void setTintList(ColorStateList tint) {\n DrawableCompat.setTintList(this.mDrawable, tint);\n }\n\n public void setTintMode(@NonNull PorterDuff.Mode tintMode) {\n DrawableCompat.setTintMode(this.mDrawable, tintMode);\n }\n\n public void setHotspot(float x, float y) {\n DrawableCompat.setHotspot(this.mDrawable, x, y);\n }\n\n public void setHotspotBounds(int left, int top, int right, int bottom) {\n DrawableCompat.setHotspotBounds(this.mDrawable, left, top, right, bottom);\n }\n\n public Drawable getWrappedDrawable() {\n return this.mDrawable;\n }\n\n public void setWrappedDrawable(Drawable drawable) {\n if (this.mDrawable != null) {\n this.mDrawable.setCallback(null);\n }\n this.mDrawable = drawable;\n if (drawable != null) {\n drawable.setCallback(this);\n }\n }\n}\n"} {"task_id": "Java_460", "language": "Java", "task_type": "method_body", "source_file": "java/github/seven332/EhViewer/app/src/main/java/com/hippo/drawable/DrawableWrapper.java", "mask_start_position": 3943, "mask_end_position": 4033, "canonical_solution": "{\n DrawableCompat.setHotspotBounds(this.mDrawable, left, top, right, bottom);\n }", "pre_mask_code": "package com.hippo.drawable;\n\nimport android.content.res.ColorStateList;\nimport android.graphics.Canvas;\nimport android.graphics.ColorFilter;\nimport android.graphics.PorterDuff;\nimport android.graphics.Rect;\nimport android.graphics.Region;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.core.graphics.drawable.DrawableCompat;\n\npublic class DrawableWrapper extends Drawable implements Drawable.Callback {\n\n private Drawable mDrawable;\n\n public DrawableWrapper(Drawable drawable) {\n this.setWrappedDrawable(drawable);\n }\n\n public void draw(@NonNull Canvas canvas) {\n this.mDrawable.draw(canvas);\n }\n\n protected void onBoundsChange(Rect bounds) {\n this.mDrawable.setBounds(bounds);\n }\n\n public void setChangingConfigurations(int configs) {\n this.mDrawable.setChangingConfigurations(configs);\n }\n\n public int getChangingConfigurations() {\n return this.mDrawable.getChangingConfigurations();\n }\n\n public void setDither(boolean dither) {\n this.mDrawable.setDither(dither);\n }\n\n public void setFilterBitmap(boolean filter) {\n this.mDrawable.setFilterBitmap(filter);\n }\n\n public void setAlpha(int alpha) {\n this.mDrawable.setAlpha(alpha);\n }\n\n public void setColorFilter(ColorFilter cf) {\n this.mDrawable.setColorFilter(cf);\n }\n\n public boolean isStateful() {\n return this.mDrawable.isStateful();\n }\n\n public boolean setState(@NonNull int[] stateSet) {\n return this.mDrawable.setState(stateSet);\n }\n\n @NonNull\n public int[] getState() {\n return this.mDrawable.getState();\n }\n\n public void jumpToCurrentState() {\n this.mDrawable.jumpToCurrentState();\n }\n\n @NonNull\n public Drawable getCurrent() {\n return this.mDrawable.getCurrent();\n }\n\n public boolean setVisible(boolean visible, boolean restart) {\n return super.setVisible(visible, restart) || this.mDrawable.setVisible(visible, restart);\n }\n\n public int getOpacity() {\n return this.mDrawable.getOpacity();\n }\n\n public Region getTransparentRegion() {\n return this.mDrawable.getTransparentRegion();\n }\n\n public int getIntrinsicWidth() {\n return this.mDrawable.getIntrinsicWidth();\n }\n\n public int getIntrinsicHeight() {\n return this.mDrawable.getIntrinsicHeight();\n }\n\n public int getMinimumWidth() {\n return this.mDrawable.getMinimumWidth();\n }\n\n public int getMinimumHeight() {\n return this.mDrawable.getMinimumHeight();\n }\n\n public boolean getPadding(@NonNull Rect padding) {\n return this.mDrawable.getPadding(padding);\n }\n\n public void invalidateDrawable(@NonNull Drawable who) {\n this.invalidateSelf();\n }\n\n public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {\n this.scheduleSelf(what, when);\n }\n\n public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {\n this.unscheduleSelf(what);\n }\n\n protected boolean onLevelChange(int level) {\n return this.mDrawable.setLevel(level);\n }\n\n public void setAutoMirrored(boolean mirrored) {\n DrawableCompat.setAutoMirrored(this.mDrawable, mirrored);\n }\n\n public boolean isAutoMirrored() {\n return DrawableCompat.isAutoMirrored(this.mDrawable);\n }\n\n public void setTint(int tint) {\n DrawableCompat.setTint(this.mDrawable, tint);\n }\n\n public void setTintList(ColorStateList tint) {\n DrawableCompat.setTintList(this.mDrawable, tint);\n }\n\n public void setTintMode(@NonNull PorterDuff.Mode tintMode) {\n DrawableCompat.setTintMode(this.mDrawable, tintMode);\n }\n\n public void setHotspot(float x, float y) {\n DrawableCompat.setHotspot(this.mDrawable, x, y);\n }\n\n public void setHotspotBounds(int left, int top, int right, int bottom) ", "post_mask_code": "\n\n public Drawable getWrappedDrawable() {\n return this.mDrawable;\n }\n\n public void setWrappedDrawable(Drawable drawable) {\n if (this.mDrawable != null) {\n this.mDrawable.setCallback(null);\n }\n this.mDrawable = drawable;\n if (drawable != null) {\n drawable.setCallback(this);\n }\n }\n}\n"} {"task_id": "Java_461", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/seven332/EhViewer/app/src/main/java/com/hippo/drawable/DrawableWrapper.java", "mask_start_position": 4171, "mask_end_position": 4265, "canonical_solution": "\n if (this.mDrawable != null) {\n this.mDrawable.setCallback(null);\n }", "pre_mask_code": "package com.hippo.drawable;\n\nimport android.content.res.ColorStateList;\nimport android.graphics.Canvas;\nimport android.graphics.ColorFilter;\nimport android.graphics.PorterDuff;\nimport android.graphics.Rect;\nimport android.graphics.Region;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.core.graphics.drawable.DrawableCompat;\n\npublic class DrawableWrapper extends Drawable implements Drawable.Callback {\n\n private Drawable mDrawable;\n\n public DrawableWrapper(Drawable drawable) {\n this.setWrappedDrawable(drawable);\n }\n\n public void draw(@NonNull Canvas canvas) {\n this.mDrawable.draw(canvas);\n }\n\n protected void onBoundsChange(Rect bounds) {\n this.mDrawable.setBounds(bounds);\n }\n\n public void setChangingConfigurations(int configs) {\n this.mDrawable.setChangingConfigurations(configs);\n }\n\n public int getChangingConfigurations() {\n return this.mDrawable.getChangingConfigurations();\n }\n\n public void setDither(boolean dither) {\n this.mDrawable.setDither(dither);\n }\n\n public void setFilterBitmap(boolean filter) {\n this.mDrawable.setFilterBitmap(filter);\n }\n\n public void setAlpha(int alpha) {\n this.mDrawable.setAlpha(alpha);\n }\n\n public void setColorFilter(ColorFilter cf) {\n this.mDrawable.setColorFilter(cf);\n }\n\n public boolean isStateful() {\n return this.mDrawable.isStateful();\n }\n\n public boolean setState(@NonNull int[] stateSet) {\n return this.mDrawable.setState(stateSet);\n }\n\n @NonNull\n public int[] getState() {\n return this.mDrawable.getState();\n }\n\n public void jumpToCurrentState() {\n this.mDrawable.jumpToCurrentState();\n }\n\n @NonNull\n public Drawable getCurrent() {\n return this.mDrawable.getCurrent();\n }\n\n public boolean setVisible(boolean visible, boolean restart) {\n return super.setVisible(visible, restart) || this.mDrawable.setVisible(visible, restart);\n }\n\n public int getOpacity() {\n return this.mDrawable.getOpacity();\n }\n\n public Region getTransparentRegion() {\n return this.mDrawable.getTransparentRegion();\n }\n\n public int getIntrinsicWidth() {\n return this.mDrawable.getIntrinsicWidth();\n }\n\n public int getIntrinsicHeight() {\n return this.mDrawable.getIntrinsicHeight();\n }\n\n public int getMinimumWidth() {\n return this.mDrawable.getMinimumWidth();\n }\n\n public int getMinimumHeight() {\n return this.mDrawable.getMinimumHeight();\n }\n\n public boolean getPadding(@NonNull Rect padding) {\n return this.mDrawable.getPadding(padding);\n }\n\n public void invalidateDrawable(@NonNull Drawable who) {\n this.invalidateSelf();\n }\n\n public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {\n this.scheduleSelf(what, when);\n }\n\n public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {\n this.unscheduleSelf(what);\n }\n\n protected boolean onLevelChange(int level) {\n return this.mDrawable.setLevel(level);\n }\n\n public void setAutoMirrored(boolean mirrored) {\n DrawableCompat.setAutoMirrored(this.mDrawable, mirrored);\n }\n\n public boolean isAutoMirrored() {\n return DrawableCompat.isAutoMirrored(this.mDrawable);\n }\n\n public void setTint(int tint) {\n DrawableCompat.setTint(this.mDrawable, tint);\n }\n\n public void setTintList(ColorStateList tint) {\n DrawableCompat.setTintList(this.mDrawable, tint);\n }\n\n public void setTintMode(@NonNull PorterDuff.Mode tintMode) {\n DrawableCompat.setTintMode(this.mDrawable, tintMode);\n }\n\n public void setHotspot(float x, float y) {\n DrawableCompat.setHotspot(this.mDrawable, x, y);\n }\n\n public void setHotspotBounds(int left, int top, int right, int bottom) {\n DrawableCompat.setHotspotBounds(this.mDrawable, left, top, right, bottom);\n }\n\n public Drawable getWrappedDrawable() {\n return this.mDrawable;\n }\n\n public void setWrappedDrawable(Drawable drawable) {", "post_mask_code": "\n this.mDrawable = drawable;\n if (drawable != null) {\n drawable.setCallback(this);\n }\n }\n}\n"} {"task_id": "Java_462", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/seven332/EhViewer/app/src/main/java/com/hippo/drawable/DrawableWrapper.java", "mask_start_position": 4274, "mask_end_position": 4300, "canonical_solution": "this.mDrawable = drawable;", "pre_mask_code": "package com.hippo.drawable;\n\nimport android.content.res.ColorStateList;\nimport android.graphics.Canvas;\nimport android.graphics.ColorFilter;\nimport android.graphics.PorterDuff;\nimport android.graphics.Rect;\nimport android.graphics.Region;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.core.graphics.drawable.DrawableCompat;\n\npublic class DrawableWrapper extends Drawable implements Drawable.Callback {\n\n private Drawable mDrawable;\n\n public DrawableWrapper(Drawable drawable) {\n this.setWrappedDrawable(drawable);\n }\n\n public void draw(@NonNull Canvas canvas) {\n this.mDrawable.draw(canvas);\n }\n\n protected void onBoundsChange(Rect bounds) {\n this.mDrawable.setBounds(bounds);\n }\n\n public void setChangingConfigurations(int configs) {\n this.mDrawable.setChangingConfigurations(configs);\n }\n\n public int getChangingConfigurations() {\n return this.mDrawable.getChangingConfigurations();\n }\n\n public void setDither(boolean dither) {\n this.mDrawable.setDither(dither);\n }\n\n public void setFilterBitmap(boolean filter) {\n this.mDrawable.setFilterBitmap(filter);\n }\n\n public void setAlpha(int alpha) {\n this.mDrawable.setAlpha(alpha);\n }\n\n public void setColorFilter(ColorFilter cf) {\n this.mDrawable.setColorFilter(cf);\n }\n\n public boolean isStateful() {\n return this.mDrawable.isStateful();\n }\n\n public boolean setState(@NonNull int[] stateSet) {\n return this.mDrawable.setState(stateSet);\n }\n\n @NonNull\n public int[] getState() {\n return this.mDrawable.getState();\n }\n\n public void jumpToCurrentState() {\n this.mDrawable.jumpToCurrentState();\n }\n\n @NonNull\n public Drawable getCurrent() {\n return this.mDrawable.getCurrent();\n }\n\n public boolean setVisible(boolean visible, boolean restart) {\n return super.setVisible(visible, restart) || this.mDrawable.setVisible(visible, restart);\n }\n\n public int getOpacity() {\n return this.mDrawable.getOpacity();\n }\n\n public Region getTransparentRegion() {\n return this.mDrawable.getTransparentRegion();\n }\n\n public int getIntrinsicWidth() {\n return this.mDrawable.getIntrinsicWidth();\n }\n\n public int getIntrinsicHeight() {\n return this.mDrawable.getIntrinsicHeight();\n }\n\n public int getMinimumWidth() {\n return this.mDrawable.getMinimumWidth();\n }\n\n public int getMinimumHeight() {\n return this.mDrawable.getMinimumHeight();\n }\n\n public boolean getPadding(@NonNull Rect padding) {\n return this.mDrawable.getPadding(padding);\n }\n\n public void invalidateDrawable(@NonNull Drawable who) {\n this.invalidateSelf();\n }\n\n public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {\n this.scheduleSelf(what, when);\n }\n\n public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {\n this.unscheduleSelf(what);\n }\n\n protected boolean onLevelChange(int level) {\n return this.mDrawable.setLevel(level);\n }\n\n public void setAutoMirrored(boolean mirrored) {\n DrawableCompat.setAutoMirrored(this.mDrawable, mirrored);\n }\n\n public boolean isAutoMirrored() {\n return DrawableCompat.isAutoMirrored(this.mDrawable);\n }\n\n public void setTint(int tint) {\n DrawableCompat.setTint(this.mDrawable, tint);\n }\n\n public void setTintList(ColorStateList tint) {\n DrawableCompat.setTintList(this.mDrawable, tint);\n }\n\n public void setTintMode(@NonNull PorterDuff.Mode tintMode) {\n DrawableCompat.setTintMode(this.mDrawable, tintMode);\n }\n\n public void setHotspot(float x, float y) {\n DrawableCompat.setHotspot(this.mDrawable, x, y);\n }\n\n public void setHotspotBounds(int left, int top, int right, int bottom) {\n DrawableCompat.setHotspotBounds(this.mDrawable, left, top, right, bottom);\n }\n\n public Drawable getWrappedDrawable() {\n return this.mDrawable;\n }\n\n public void setWrappedDrawable(Drawable drawable) {\n if (this.mDrawable != null) {\n this.mDrawable.setCallback(null);\n }\n ", "post_mask_code": "\n if (drawable != null) {\n drawable.setCallback(this);\n }\n }\n}\n"} {"task_id": "Java_463", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/seven332/EhViewer/app/src/main/java/com/hippo/drawable/DrawableWrapper.java", "mask_start_position": 4309, "mask_end_position": 4388, "canonical_solution": "if (drawable != null) {\n drawable.setCallback(this);\n }\n }", "pre_mask_code": "package com.hippo.drawable;\n\nimport android.content.res.ColorStateList;\nimport android.graphics.Canvas;\nimport android.graphics.ColorFilter;\nimport android.graphics.PorterDuff;\nimport android.graphics.Rect;\nimport android.graphics.Region;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.core.graphics.drawable.DrawableCompat;\n\npublic class DrawableWrapper extends Drawable implements Drawable.Callback {\n\n private Drawable mDrawable;\n\n public DrawableWrapper(Drawable drawable) {\n this.setWrappedDrawable(drawable);\n }\n\n public void draw(@NonNull Canvas canvas) {\n this.mDrawable.draw(canvas);\n }\n\n protected void onBoundsChange(Rect bounds) {\n this.mDrawable.setBounds(bounds);\n }\n\n public void setChangingConfigurations(int configs) {\n this.mDrawable.setChangingConfigurations(configs);\n }\n\n public int getChangingConfigurations() {\n return this.mDrawable.getChangingConfigurations();\n }\n\n public void setDither(boolean dither) {\n this.mDrawable.setDither(dither);\n }\n\n public void setFilterBitmap(boolean filter) {\n this.mDrawable.setFilterBitmap(filter);\n }\n\n public void setAlpha(int alpha) {\n this.mDrawable.setAlpha(alpha);\n }\n\n public void setColorFilter(ColorFilter cf) {\n this.mDrawable.setColorFilter(cf);\n }\n\n public boolean isStateful() {\n return this.mDrawable.isStateful();\n }\n\n public boolean setState(@NonNull int[] stateSet) {\n return this.mDrawable.setState(stateSet);\n }\n\n @NonNull\n public int[] getState() {\n return this.mDrawable.getState();\n }\n\n public void jumpToCurrentState() {\n this.mDrawable.jumpToCurrentState();\n }\n\n @NonNull\n public Drawable getCurrent() {\n return this.mDrawable.getCurrent();\n }\n\n public boolean setVisible(boolean visible, boolean restart) {\n return super.setVisible(visible, restart) || this.mDrawable.setVisible(visible, restart);\n }\n\n public int getOpacity() {\n return this.mDrawable.getOpacity();\n }\n\n public Region getTransparentRegion() {\n return this.mDrawable.getTransparentRegion();\n }\n\n public int getIntrinsicWidth() {\n return this.mDrawable.getIntrinsicWidth();\n }\n\n public int getIntrinsicHeight() {\n return this.mDrawable.getIntrinsicHeight();\n }\n\n public int getMinimumWidth() {\n return this.mDrawable.getMinimumWidth();\n }\n\n public int getMinimumHeight() {\n return this.mDrawable.getMinimumHeight();\n }\n\n public boolean getPadding(@NonNull Rect padding) {\n return this.mDrawable.getPadding(padding);\n }\n\n public void invalidateDrawable(@NonNull Drawable who) {\n this.invalidateSelf();\n }\n\n public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {\n this.scheduleSelf(what, when);\n }\n\n public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {\n this.unscheduleSelf(what);\n }\n\n protected boolean onLevelChange(int level) {\n return this.mDrawable.setLevel(level);\n }\n\n public void setAutoMirrored(boolean mirrored) {\n DrawableCompat.setAutoMirrored(this.mDrawable, mirrored);\n }\n\n public boolean isAutoMirrored() {\n return DrawableCompat.isAutoMirrored(this.mDrawable);\n }\n\n public void setTint(int tint) {\n DrawableCompat.setTint(this.mDrawable, tint);\n }\n\n public void setTintList(ColorStateList tint) {\n DrawableCompat.setTintList(this.mDrawable, tint);\n }\n\n public void setTintMode(@NonNull PorterDuff.Mode tintMode) {\n DrawableCompat.setTintMode(this.mDrawable, tintMode);\n }\n\n public void setHotspot(float x, float y) {\n DrawableCompat.setHotspot(this.mDrawable, x, y);\n }\n\n public void setHotspotBounds(int left, int top, int right, int bottom) {\n DrawableCompat.setHotspotBounds(this.mDrawable, left, top, right, bottom);\n }\n\n public Drawable getWrappedDrawable() {\n return this.mDrawable;\n }\n\n public void setWrappedDrawable(Drawable drawable) {\n if (this.mDrawable != null) {\n this.mDrawable.setCallback(null);\n }\n this.mDrawable = drawable;\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_464", "language": "Java", "task_type": "single_line", "source_file": "java/github/seven332/EhViewer/app/src/main/java/com/hippo/drawable/DrawableWrapper.java", "mask_start_position": 1157, "mask_end_position": 1196, "canonical_solution": "this.mDrawable.setFilterBitmap(filter);", "pre_mask_code": "package com.hippo.drawable;\n\nimport android.content.res.ColorStateList;\nimport android.graphics.Canvas;\nimport android.graphics.ColorFilter;\nimport android.graphics.PorterDuff;\nimport android.graphics.Rect;\nimport android.graphics.Region;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.core.graphics.drawable.DrawableCompat;\n\npublic class DrawableWrapper extends Drawable implements Drawable.Callback {\n\n private Drawable mDrawable;\n\n public DrawableWrapper(Drawable drawable) {\n this.setWrappedDrawable(drawable);\n }\n\n public void draw(@NonNull Canvas canvas) {\n this.mDrawable.draw(canvas);\n }\n\n protected void onBoundsChange(Rect bounds) {\n this.mDrawable.setBounds(bounds);\n }\n\n public void setChangingConfigurations(int configs) {\n this.mDrawable.setChangingConfigurations(configs);\n }\n\n public int getChangingConfigurations() {\n return this.mDrawable.getChangingConfigurations();\n }\n\n public void setDither(boolean dither) {\n this.mDrawable.setDither(dither);\n }\n\n public void setFilterBitmap(boolean filter) {\n ", "post_mask_code": "\n }\n\n public void setAlpha(int alpha) {\n this.mDrawable.setAlpha(alpha);\n }\n\n public void setColorFilter(ColorFilter cf) {\n this.mDrawable.setColorFilter(cf);\n }\n\n public boolean isStateful() {\n return this.mDrawable.isStateful();\n }\n\n public boolean setState(@NonNull int[] stateSet) {\n return this.mDrawable.setState(stateSet);\n }\n\n @NonNull\n public int[] getState() {\n return this.mDrawable.getState();\n }\n\n public void jumpToCurrentState() {\n this.mDrawable.jumpToCurrentState();\n }\n\n @NonNull\n public Drawable getCurrent() {\n return this.mDrawable.getCurrent();\n }\n\n public boolean setVisible(boolean visible, boolean restart) {\n return super.setVisible(visible, restart) || this.mDrawable.setVisible(visible, restart);\n }\n\n public int getOpacity() {\n return this.mDrawable.getOpacity();\n }\n\n public Region getTransparentRegion() {\n return this.mDrawable.getTransparentRegion();\n }\n\n public int getIntrinsicWidth() {\n return this.mDrawable.getIntrinsicWidth();\n }\n\n public int getIntrinsicHeight() {\n return this.mDrawable.getIntrinsicHeight();\n }\n\n public int getMinimumWidth() {\n return this.mDrawable.getMinimumWidth();\n }\n\n public int getMinimumHeight() {\n return this.mDrawable.getMinimumHeight();\n }\n\n public boolean getPadding(@NonNull Rect padding) {\n return this.mDrawable.getPadding(padding);\n }\n\n public void invalidateDrawable(@NonNull Drawable who) {\n this.invalidateSelf();\n }\n\n public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {\n this.scheduleSelf(what, when);\n }\n\n public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {\n this.unscheduleSelf(what);\n }\n\n protected boolean onLevelChange(int level) {\n return this.mDrawable.setLevel(level);\n }\n\n public void setAutoMirrored(boolean mirrored) {\n DrawableCompat.setAutoMirrored(this.mDrawable, mirrored);\n }\n\n public boolean isAutoMirrored() {\n return DrawableCompat.isAutoMirrored(this.mDrawable);\n }\n\n public void setTint(int tint) {\n DrawableCompat.setTint(this.mDrawable, tint);\n }\n\n public void setTintList(ColorStateList tint) {\n DrawableCompat.setTintList(this.mDrawable, tint);\n }\n\n public void setTintMode(@NonNull PorterDuff.Mode tintMode) {\n DrawableCompat.setTintMode(this.mDrawable, tintMode);\n }\n\n public void setHotspot(float x, float y) {\n DrawableCompat.setHotspot(this.mDrawable, x, y);\n }\n\n public void setHotspotBounds(int left, int top, int right, int bottom) {\n DrawableCompat.setHotspotBounds(this.mDrawable, left, top, right, bottom);\n }\n\n public Drawable getWrappedDrawable() {\n return this.mDrawable;\n }\n\n public void setWrappedDrawable(Drawable drawable) {\n if (this.mDrawable != null) {\n this.mDrawable.setCallback(null);\n }\n this.mDrawable = drawable;\n if (drawable != null) {\n drawable.setCallback(this);\n }\n }\n}\n"} {"task_id": "Java_465", "language": "Java", "task_type": "if_statement", "source_file": "java/github/seven332/EhViewer/app/src/main/java/com/hippo/drawable/DrawableWrapper.java", "mask_start_position": 4180, "mask_end_position": 4265, "canonical_solution": "if (this.mDrawable != null) {\n this.mDrawable.setCallback(null);\n }", "pre_mask_code": "package com.hippo.drawable;\n\nimport android.content.res.ColorStateList;\nimport android.graphics.Canvas;\nimport android.graphics.ColorFilter;\nimport android.graphics.PorterDuff;\nimport android.graphics.Rect;\nimport android.graphics.Region;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.core.graphics.drawable.DrawableCompat;\n\npublic class DrawableWrapper extends Drawable implements Drawable.Callback {\n\n private Drawable mDrawable;\n\n public DrawableWrapper(Drawable drawable) {\n this.setWrappedDrawable(drawable);\n }\n\n public void draw(@NonNull Canvas canvas) {\n this.mDrawable.draw(canvas);\n }\n\n protected void onBoundsChange(Rect bounds) {\n this.mDrawable.setBounds(bounds);\n }\n\n public void setChangingConfigurations(int configs) {\n this.mDrawable.setChangingConfigurations(configs);\n }\n\n public int getChangingConfigurations() {\n return this.mDrawable.getChangingConfigurations();\n }\n\n public void setDither(boolean dither) {\n this.mDrawable.setDither(dither);\n }\n\n public void setFilterBitmap(boolean filter) {\n this.mDrawable.setFilterBitmap(filter);\n }\n\n public void setAlpha(int alpha) {\n this.mDrawable.setAlpha(alpha);\n }\n\n public void setColorFilter(ColorFilter cf) {\n this.mDrawable.setColorFilter(cf);\n }\n\n public boolean isStateful() {\n return this.mDrawable.isStateful();\n }\n\n public boolean setState(@NonNull int[] stateSet) {\n return this.mDrawable.setState(stateSet);\n }\n\n @NonNull\n public int[] getState() {\n return this.mDrawable.getState();\n }\n\n public void jumpToCurrentState() {\n this.mDrawable.jumpToCurrentState();\n }\n\n @NonNull\n public Drawable getCurrent() {\n return this.mDrawable.getCurrent();\n }\n\n public boolean setVisible(boolean visible, boolean restart) {\n return super.setVisible(visible, restart) || this.mDrawable.setVisible(visible, restart);\n }\n\n public int getOpacity() {\n return this.mDrawable.getOpacity();\n }\n\n public Region getTransparentRegion() {\n return this.mDrawable.getTransparentRegion();\n }\n\n public int getIntrinsicWidth() {\n return this.mDrawable.getIntrinsicWidth();\n }\n\n public int getIntrinsicHeight() {\n return this.mDrawable.getIntrinsicHeight();\n }\n\n public int getMinimumWidth() {\n return this.mDrawable.getMinimumWidth();\n }\n\n public int getMinimumHeight() {\n return this.mDrawable.getMinimumHeight();\n }\n\n public boolean getPadding(@NonNull Rect padding) {\n return this.mDrawable.getPadding(padding);\n }\n\n public void invalidateDrawable(@NonNull Drawable who) {\n this.invalidateSelf();\n }\n\n public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {\n this.scheduleSelf(what, when);\n }\n\n public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {\n this.unscheduleSelf(what);\n }\n\n protected boolean onLevelChange(int level) {\n return this.mDrawable.setLevel(level);\n }\n\n public void setAutoMirrored(boolean mirrored) {\n DrawableCompat.setAutoMirrored(this.mDrawable, mirrored);\n }\n\n public boolean isAutoMirrored() {\n return DrawableCompat.isAutoMirrored(this.mDrawable);\n }\n\n public void setTint(int tint) {\n DrawableCompat.setTint(this.mDrawable, tint);\n }\n\n public void setTintList(ColorStateList tint) {\n DrawableCompat.setTintList(this.mDrawable, tint);\n }\n\n public void setTintMode(@NonNull PorterDuff.Mode tintMode) {\n DrawableCompat.setTintMode(this.mDrawable, tintMode);\n }\n\n public void setHotspot(float x, float y) {\n DrawableCompat.setHotspot(this.mDrawable, x, y);\n }\n\n public void setHotspotBounds(int left, int top, int right, int bottom) {\n DrawableCompat.setHotspotBounds(this.mDrawable, left, top, right, bottom);\n }\n\n public Drawable getWrappedDrawable() {\n return this.mDrawable;\n }\n\n public void setWrappedDrawable(Drawable drawable) {\n ", "post_mask_code": "\n this.mDrawable = drawable;\n if (drawable != null) {\n drawable.setCallback(this);\n }\n }\n}\n"} {"task_id": "Java_466", "language": "Java", "task_type": "empty", "source_file": "java/github/seven332/EhViewer/app/src/main/java/com/hippo/drawable/DrawableWrapper.java", "mask_start_position": 2268, "mask_end_position": 2268, "canonical_solution": "", "pre_mask_code": "package com.hippo.drawable;\n\nimport android.content.res.ColorStateList;\nimport android.graphics.Canvas;\nimport android.graphics.ColorFilter;\nimport android.graphics.PorterDuff;\nimport android.graphics.Rect;\nimport android.graphics.Region;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.core.graphics.drawable.DrawableCompat;\n\npublic class DrawableWrapper extends Drawable implements Drawable.Callback {\n\n private Drawable mDrawable;\n\n public DrawableWrapper(Drawable drawable) {\n this.setWrappedDrawable(drawable);\n }\n\n public void draw(@NonNull Canvas canvas) {\n this.mDrawable.draw(canvas);\n }\n\n protected void onBoundsChange(Rect bounds) {\n this.mDrawable.setBounds(bounds);\n }\n\n public void setChangingConfigurations(int configs) {\n this.mDrawable.setChangingConfigurations(configs);\n }\n\n public int getChangingConfigurations() {\n return this.mDrawable.getChangingConfigurations();\n }\n\n public void setDither(boolean dither) {\n this.mDrawable.setDither(dither);\n }\n\n public void setFilterBitmap(boolean filter) {\n this.mDrawable.setFilterBitmap(filter);\n }\n\n public void setAlpha(int alpha) {\n this.mDrawable.setAlpha(alpha);\n }\n\n public void setColorFilter(ColorFilter cf) {\n this.mDrawable.setColorFilter(cf);\n }\n\n public boolean isStateful() {\n return this.mDrawable.isStateful();\n }\n\n public boolean setState(@NonNull int[] stateSet) {\n return this.mDrawable.setState(stateSet);\n }\n\n @NonNull\n public int[] getState() {\n return this.mDrawable.getState();\n }\n\n public void jumpToCurrentState() {\n this.mDrawable.jumpToCurrentState();\n }\n\n @NonNull\n public Drawable getCurrent() {\n return this.mDrawable.getCurrent();\n }\n\n public boolean setVisible(boolean visible, boolean restart) {\n return super.setVisible(visible, restart) || this.mDrawable.setVisible(visible, restart);\n }\n\n public int getOpacity() {\n return this.mDrawable.getOpacity();\n }\n\n public Region getTransparentRegion() {\n return this.mDrawable.getTransparentRegion();\n }\n\n public int getIntrinsicWidth() {\n ", "post_mask_code": "return this.mDrawable.getIntrinsicWidth();\n }\n\n public int getIntrinsicHeight() {\n return this.mDrawable.getIntrinsicHeight();\n }\n\n public int getMinimumWidth() {\n return this.mDrawable.getMinimumWidth();\n }\n\n public int getMinimumHeight() {\n return this.mDrawable.getMinimumHeight();\n }\n\n public boolean getPadding(@NonNull Rect padding) {\n return this.mDrawable.getPadding(padding);\n }\n\n public void invalidateDrawable(@NonNull Drawable who) {\n this.invalidateSelf();\n }\n\n public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {\n this.scheduleSelf(what, when);\n }\n\n public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {\n this.unscheduleSelf(what);\n }\n\n protected boolean onLevelChange(int level) {\n return this.mDrawable.setLevel(level);\n }\n\n public void setAutoMirrored(boolean mirrored) {\n DrawableCompat.setAutoMirrored(this.mDrawable, mirrored);\n }\n\n public boolean isAutoMirrored() {\n return DrawableCompat.isAutoMirrored(this.mDrawable);\n }\n\n public void setTint(int tint) {\n DrawableCompat.setTint(this.mDrawable, tint);\n }\n\n public void setTintList(ColorStateList tint) {\n DrawableCompat.setTintList(this.mDrawable, tint);\n }\n\n public void setTintMode(@NonNull PorterDuff.Mode tintMode) {\n DrawableCompat.setTintMode(this.mDrawable, tintMode);\n }\n\n public void setHotspot(float x, float y) {\n DrawableCompat.setHotspot(this.mDrawable, x, y);\n }\n\n public void setHotspotBounds(int left, int top, int right, int bottom) {\n DrawableCompat.setHotspotBounds(this.mDrawable, left, top, right, bottom);\n }\n\n public Drawable getWrappedDrawable() {\n return this.mDrawable;\n }\n\n public void setWrappedDrawable(Drawable drawable) {\n if (this.mDrawable != null) {\n this.mDrawable.setCallback(null);\n }\n this.mDrawable = drawable;\n if (drawable != null) {\n drawable.setCallback(this);\n }\n }\n}\n"} {"task_id": "Java_467", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cwarden/kettle/src-ui/org/pentaho/di/ui/repository/repositoryexplorer/model/UITransformation.java", "mask_start_position": 555, "mask_end_position": 619, "canonical_solution": "@Override\n public void setName(String name) throws Exception ", "pre_mask_code": "package org.pentaho.di.ui.repository.repositoryexplorer.model;\n\nimport org.pentaho.di.core.exception.KettleException;\nimport org.pentaho.di.repository.Repository;\nimport org.pentaho.di.repository.RepositoryElementMetaInterface;\n\npublic class UITransformation extends UIRepositoryContent {\n\n private static final long serialVersionUID = 3826725834758429573L;\n\n public UITransformation() {\n }\n\n public UITransformation(RepositoryElementMetaInterface rc, UIRepositoryDirectory parent, Repository rep) {\n super(rc, parent, rep);\n }\n\n ", "post_mask_code": "{\n super.setName(name);\n rep.renameTransformation(this.getObjectId(), getRepositoryDirectory(), name);\n uiParent.fireCollectionChanged();\n }\n\n public void delete() throws Exception {\n rep.deleteTransformation(this.getObjectId());\n if (uiParent.getRepositoryObjects().contains(this))\n uiParent.getRepositoryObjects().remove(this);\n }\n\n public void move(UIRepositoryDirectory newParentDir) throws KettleException {\n if (newParentDir != null) {\n rep.renameTransformation(obj.getObjectId(), newParentDir.getDirectory(), null);\n newParentDir.refresh();\n }\n }\n}\n"} {"task_id": "Java_468", "language": "Java", "task_type": "method_body", "source_file": "java/github/cwarden/kettle/src-ui/org/pentaho/di/ui/repository/repositoryexplorer/model/UITransformation.java", "mask_start_position": 619, "mask_end_position": 783, "canonical_solution": "{\n super.setName(name);\n rep.renameTransformation(this.getObjectId(), getRepositoryDirectory(), name);\n uiParent.fireCollectionChanged();\n }", "pre_mask_code": "package org.pentaho.di.ui.repository.repositoryexplorer.model;\n\nimport org.pentaho.di.core.exception.KettleException;\nimport org.pentaho.di.repository.Repository;\nimport org.pentaho.di.repository.RepositoryElementMetaInterface;\n\npublic class UITransformation extends UIRepositoryContent {\n\n private static final long serialVersionUID = 3826725834758429573L;\n\n public UITransformation() {\n }\n\n public UITransformation(RepositoryElementMetaInterface rc, UIRepositoryDirectory parent, Repository rep) {\n super(rc, parent, rep);\n }\n\n @Override\n public void setName(String name) throws Exception ", "post_mask_code": "\n\n public void delete() throws Exception {\n rep.deleteTransformation(this.getObjectId());\n if (uiParent.getRepositoryObjects().contains(this))\n uiParent.getRepositoryObjects().remove(this);\n }\n\n public void move(UIRepositoryDirectory newParentDir) throws KettleException {\n if (newParentDir != null) {\n rep.renameTransformation(obj.getObjectId(), newParentDir.getDirectory(), null);\n newParentDir.refresh();\n }\n }\n}\n"} {"task_id": "Java_469", "language": "Java", "task_type": "single_line", "source_file": "java/github/cwarden/kettle/src-ui/org/pentaho/di/ui/repository/repositoryexplorer/model/UITransformation.java", "mask_start_position": 772, "mask_end_position": 777, "canonical_solution": "ed();", "pre_mask_code": "package org.pentaho.di.ui.repository.repositoryexplorer.model;\n\nimport org.pentaho.di.core.exception.KettleException;\nimport org.pentaho.di.repository.Repository;\nimport org.pentaho.di.repository.RepositoryElementMetaInterface;\n\npublic class UITransformation extends UIRepositoryContent {\n\n private static final long serialVersionUID = 3826725834758429573L;\n\n public UITransformation() {\n }\n\n public UITransformation(RepositoryElementMetaInterface rc, UIRepositoryDirectory parent, Repository rep) {\n super(rc, parent, rep);\n }\n\n @Override\n public void setName(String name) throws Exception {\n super.setName(name);\n rep.renameTransformation(this.getObjectId(), getRepositoryDirectory(), name);\n uiParent.fireCollectionChang", "post_mask_code": "\n }\n\n public void delete() throws Exception {\n rep.deleteTransformation(this.getObjectId());\n if (uiParent.getRepositoryObjects().contains(this))\n uiParent.getRepositoryObjects().remove(this);\n }\n\n public void move(UIRepositoryDirectory newParentDir) throws KettleException {\n if (newParentDir != null) {\n rep.renameTransformation(obj.getObjectId(), newParentDir.getDirectory(), null);\n newParentDir.refresh();\n }\n }\n}\n"} {"task_id": "Java_470", "language": "Java", "task_type": "if_statement", "source_file": "java/github/cwarden/kettle/src-ui/org/pentaho/di/ui/repository/repositoryexplorer/model/UITransformation.java", "mask_start_position": 891, "mask_end_position": 1000, "canonical_solution": "if (uiParent.getRepositoryObjects().contains(this))\n uiParent.getRepositoryObjects().remove(this);", "pre_mask_code": "package org.pentaho.di.ui.repository.repositoryexplorer.model;\n\nimport org.pentaho.di.core.exception.KettleException;\nimport org.pentaho.di.repository.Repository;\nimport org.pentaho.di.repository.RepositoryElementMetaInterface;\n\npublic class UITransformation extends UIRepositoryContent {\n\n private static final long serialVersionUID = 3826725834758429573L;\n\n public UITransformation() {\n }\n\n public UITransformation(RepositoryElementMetaInterface rc, UIRepositoryDirectory parent, Repository rep) {\n super(rc, parent, rep);\n }\n\n @Override\n public void setName(String name) throws Exception {\n super.setName(name);\n rep.renameTransformation(this.getObjectId(), getRepositoryDirectory(), name);\n uiParent.fireCollectionChanged();\n }\n\n public void delete() throws Exception {\n rep.deleteTransformation(this.getObjectId());\n ", "post_mask_code": "\n }\n\n public void move(UIRepositoryDirectory newParentDir) throws KettleException {\n if (newParentDir != null) {\n rep.renameTransformation(obj.getObjectId(), newParentDir.getDirectory(), null);\n newParentDir.refresh();\n }\n }\n}\n"} {"task_id": "Java_471", "language": "Java", "task_type": "empty", "source_file": "java/github/cwarden/kettle/src-ui/org/pentaho/di/ui/repository/repositoryexplorer/model/UITransformation.java", "mask_start_position": 788, "mask_end_position": 788, "canonical_solution": "", "pre_mask_code": "package org.pentaho.di.ui.repository.repositoryexplorer.model;\n\nimport org.pentaho.di.core.exception.KettleException;\nimport org.pentaho.di.repository.Repository;\nimport org.pentaho.di.repository.RepositoryElementMetaInterface;\n\npublic class UITransformation extends UIRepositoryContent {\n\n private static final long serialVersionUID = 3826725834758429573L;\n\n public UITransformation() {\n }\n\n public UITransformation(RepositoryElementMetaInterface rc, UIRepositoryDirectory parent, Repository rep) {\n super(rc, parent, rep);\n }\n\n @Override\n public void setName(String name) throws Exception {\n super.setName(name);\n rep.renameTransformation(this.getObjectId(), getRepositoryDirectory(), name);\n uiParent.fireCollectionChanged();\n }\n\n ", "post_mask_code": " public void delete() throws Exception {\n rep.deleteTransformation(this.getObjectId());\n if (uiParent.getRepositoryObjects().contains(this))\n uiParent.getRepositoryObjects().remove(this);\n }\n\n public void move(UIRepositoryDirectory newParentDir) throws KettleException {\n if (newParentDir != null) {\n rep.renameTransformation(obj.getObjectId(), newParentDir.getDirectory(), null);\n newParentDir.refresh();\n }\n }\n}\n"} {"task_id": "Java_472", "language": "Java", "task_type": "method_signature", "source_file": "java/github/edx/edx-app-android/OpenEdXMobile/src/main/java/org/edx/mobile/whatsnew/WhatsNewModel.java", "mask_start_position": 725, "mask_end_position": 789, "canonical_solution": "@Override\n public void writeToParcel(Parcel dest, int flags) ", "pre_mask_code": "package org.edx.mobile.whatsnew;\n\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport androidx.annotation.NonNull;\nimport java.util.List;\n\npublic class WhatsNewModel implements Parcelable {\n\n @NonNull\n private String version;\n\n @NonNull\n private List messages;\n\n protected WhatsNewModel(Parcel in) {\n this.version = in.readString();\n this.messages = in.createTypedArrayList(WhatsNewItemModel.CREATOR);\n }\n\n @NonNull\n public String getVersion() {\n return version;\n }\n\n @NonNull\n public List getWhatsNewItems() {\n return messages;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n ", "post_mask_code": "{\n dest.writeString(this.version);\n dest.writeTypedList(this.messages);\n }\n\n public static final Creator CREATOR = new Creator() {\n\n @Override\n public WhatsNewModel createFromParcel(Parcel source) {\n return new WhatsNewModel(source);\n }\n\n @Override\n public WhatsNewModel[] newArray(int size) {\n return new WhatsNewModel[size];\n }\n };\n}\n"} {"task_id": "Java_473", "language": "Java", "task_type": "method_body", "source_file": "java/github/edx/edx-app-android/OpenEdXMobile/src/main/java/org/edx/mobile/whatsnew/WhatsNewModel.java", "mask_start_position": 1177, "mask_end_position": 1232, "canonical_solution": "{\n return new WhatsNewModel[size];\n }", "pre_mask_code": "package org.edx.mobile.whatsnew;\n\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport androidx.annotation.NonNull;\nimport java.util.List;\n\npublic class WhatsNewModel implements Parcelable {\n\n @NonNull\n private String version;\n\n @NonNull\n private List messages;\n\n protected WhatsNewModel(Parcel in) {\n this.version = in.readString();\n this.messages = in.createTypedArrayList(WhatsNewItemModel.CREATOR);\n }\n\n @NonNull\n public String getVersion() {\n return version;\n }\n\n @NonNull\n public List getWhatsNewItems() {\n return messages;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(this.version);\n dest.writeTypedList(this.messages);\n }\n\n public static final Creator CREATOR = new Creator() {\n\n @Override\n public WhatsNewModel createFromParcel(Parcel source) {\n return new WhatsNewModel(source);\n }\n\n @Override\n public WhatsNewModel[] newArray(int size) ", "post_mask_code": "\n };\n}\n"} {"task_id": "Java_474", "language": "Java", "task_type": "single_line", "source_file": "java/github/edx/edx-app-android/OpenEdXMobile/src/main/java/org/edx/mobile/whatsnew/WhatsNewModel.java", "mask_start_position": 1069, "mask_end_position": 1097, "canonical_solution": "n new WhatsNewModel(source);", "pre_mask_code": "package org.edx.mobile.whatsnew;\n\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport androidx.annotation.NonNull;\nimport java.util.List;\n\npublic class WhatsNewModel implements Parcelable {\n\n @NonNull\n private String version;\n\n @NonNull\n private List messages;\n\n protected WhatsNewModel(Parcel in) {\n this.version = in.readString();\n this.messages = in.createTypedArrayList(WhatsNewItemModel.CREATOR);\n }\n\n @NonNull\n public String getVersion() {\n return version;\n }\n\n @NonNull\n public List getWhatsNewItems() {\n return messages;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(this.version);\n dest.writeTypedList(this.messages);\n }\n\n public static final Creator CREATOR = new Creator() {\n\n @Override\n public WhatsNewModel createFromParcel(Parcel source) {\n retur", "post_mask_code": "\n }\n\n @Override\n public WhatsNewModel[] newArray(int size) {\n return new WhatsNewModel[size];\n }\n };\n}\n"} {"task_id": "Java_475", "language": "Java", "task_type": "empty", "source_file": "java/github/edx/edx-app-android/OpenEdXMobile/src/main/java/org/edx/mobile/whatsnew/WhatsNewModel.java", "mask_start_position": 511, "mask_end_position": 511, "canonical_solution": "", "pre_mask_code": "package org.edx.mobile.whatsnew;\n\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport androidx.annotation.NonNull;\nimport java.util.List;\n\npublic class WhatsNewModel implements Parcelable {\n\n @NonNull\n private String version;\n\n @NonNull\n private List messages;\n\n protected WhatsNewModel(Parcel in) {\n this.version = in.readString();\n this.messages = in.createTypedArrayList(WhatsNewItemModel.CREATOR);\n }\n\n @NonNull\n public String getVersion()", "post_mask_code": " {\n return version;\n }\n\n @NonNull\n public List getWhatsNewItems() {\n return messages;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(this.version);\n dest.writeTypedList(this.messages);\n }\n\n public static final Creator CREATOR = new Creator() {\n\n @Override\n public WhatsNewModel createFromParcel(Parcel source) {\n return new WhatsNewModel(source);\n }\n\n @Override\n public WhatsNewModel[] newArray(int size) {\n return new WhatsNewModel[size];\n }\n };\n}\n"} {"task_id": "Java_476", "language": "Java", "task_type": "empty", "source_file": "java/github/hinemos/hinemos/HinemosManager/src_infra/com/clustercontrol/infra/util/InfraConstants.java", "mask_start_position": 130, "mask_end_position": 130, "canonical_solution": "", "pre_mask_code": "package com.clustercontrol.infra.util;\n\npublic class InfraConstants {\n\n public static final String notifyGroupIdPrefix = \"INFRA", "post_mask_code": "_\";\n\n private InfraConstants() {\n }\n}\n"} {"task_id": "Java_477", "language": "Java", "task_type": "method_signature", "source_file": "java/github/easemob/kefu-android-demo/app/src/main/java/com/easemob/helpdeskdemo/ui/VideoCallActivity.java", "mask_start_position": 13779, "mask_end_position": 13844, "canonical_solution": "@Override\n public void onWindowFocusChanged(boolean hasFocus) ", "pre_mask_code": "package com.easemob.helpdeskdemo.ui;\n\nimport android.app.Activity;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.media.AudioManager;\nimport android.media.Ringtone;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.WindowManager;\nimport android.widget.ImageButton;\nimport android.widget.Toast;\nimport com.easemob.helpdeskdemo.Preferences;\nimport com.easemob.helpdeskdemo.R;\nimport com.easemob.helpdeskdemo.widget.BottomRelativeLayout;\nimport com.easemob.helpdeskdemo.widget.CustomVideoContainer;\nimport com.easemob.helpdeskdemo.widget.CustomVideoView;\nimport com.hyphenate.chat.CallManager;\nimport com.hyphenate.chat.ChatClient;\nimport com.hyphenate.chat.MediaStream;\nimport com.hyphenate.helpdesk.easeui.widget.ToastHelper;\nimport com.hyphenate.helpdesk.util.Log;\nimport com.hyphenate.util.EMLog;\nimport com.superrtc.mediamanager.EMediaDefines;\nimport com.superrtc.mediamanager.EMediaEntities;\nimport com.superrtc.mediamanager.ScreenCaptureManager;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n// this class is not used?\npublic class VideoCallActivity extends DemoBaseActivity implements CallManager.CallManagerDelegate {\n\n private static final String TAG = \"call\";\n\n protected final int MSG_CALL_ANSWER = 2;\n\n protected final int MSG_CALL_END = 3;\n\n protected final int MSG_CALL_RELEASE_HANDLER = 4;\n\n protected final int MSG_CALL_SWITCH_CAMERA = 5;\n\n private View rootLayout;\n\n private CustomVideoContainer multiVideoView;\n\n private CustomVideoView localSurfaceView;\n\n private ImageButton ibMinimize;\n\n private Map> streamItemMaps = new HashMap<>();\n\n private BottomRelativeLayout bottomRelativeLayout;\n\n protected AudioManager audioManager;\n\n protected Ringtone ringtone;\n\n private HeadsetReceiver headsetReceiver = new HeadsetReceiver();\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n finish();\n return;\n }\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);\n setContentView(R.layout.activity_call);\n String fromUsername = getIntent().getStringExtra(\"username\");\n audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);\n initViews();\n info(\"conference demo\");\n initListeners();\n ChatClient.getInstance().callManager().addDelegate(this);\n Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);\n audioManager.setMode(AudioManager.MODE_RINGTONE);\n audioManager.setSpeakerphoneOn(true);\n ringtone = RingtoneManager.getRingtone(this, ringUri);\n if (ringtone != null) {\n ringtone.play();\n }\n final int MAKE_CALL_TIMEOUT = 60 * 1000;\n handler.removeCallbacks(timeoutHangup);\n handler.postDelayed(timeoutHangup, MAKE_CALL_TIMEOUT);\n registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));\n }\n\n private String getSelfNick() {\n String nickName = Preferences.getInstance().getNickName();\n if (TextUtils.isEmpty(nickName)) {\n nickName = ChatClient.getInstance().currentUserName();\n }\n return nickName;\n }\n\n class HeadsetReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n switch(action) {\n // 插入和拔出耳机会触发广播\n case Intent.ACTION_HEADSET_PLUG:\n int state = intent.getIntExtra(\"state\", 0);\n if (state == 1) {\n // 耳机已插入\n closeSpeakerOn();\n } else if (state == 0) {\n // 耳机已拔出\n openSpeakerOn();\n }\n break;\n }\n }\n }\n\n HandlerThread callHandlerThread = new HandlerThread(\"callHandlerThread\");\n\n {\n callHandlerThread.start();\n }\n\n protected Handler handler = new Handler(callHandlerThread.getLooper()) {\n\n @Override\n public void handleMessage(android.os.Message msg) {\n EMLog.d(TAG, \"handleMessage -- enter block -- msg.what: \" + msg.what);\n switch(msg.what) {\n case MSG_CALL_ANSWER:\n EMLog.d(TAG, \"MSG_CALL_ANSWER\");\n handler.removeCallbacks(timeoutHangup);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n openSpeakerOn();\n bottomRelativeLayout.startChronometer();\n bottomRelativeLayout.setCallStateText(getString(R.string.tip_multi_video_calling));\n ChatClient.getInstance().callManager().acceptCall(getSelfNick(), new com.hyphenate.helpdesk.callback.Callback() {\n\n @Override\n public void onSuccess() {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n bottomRelativeLayout.setControllerButtonsVisibile(true);\n localSurfaceView = addViewToMultiLayout(null);\n localSurfaceView.setLabel(getSelfNick());\n ChatClient.getInstance().callManager().setLocalView(localSurfaceView.getSurfaceView());\n }\n });\n }\n\n @Override\n public void onError(int code, final String error) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ToastHelper.show(getBaseContext(), \"Publish Failed:\" + error);\n }\n });\n }\n\n @Override\n public void onProgress(int progress, String status) {\n }\n });\n }\n });\n break;\n case MSG_CALL_END:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n break;\n case MSG_CALL_RELEASE_HANDLER:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n info(\"click hangup\");\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n handler.removeCallbacks(timeoutHangup);\n handler.removeMessages(MSG_CALL_ANSWER);\n handler.removeMessages(MSG_CALL_END);\n callHandlerThread.quit();\n }\n });\n break;\n case MSG_CALL_SWITCH_CAMERA:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ChatClient.getInstance().callManager().switchCamera();\n }\n });\n break;\n default:\n break;\n }\n }\n };\n\n void releaseHandler() {\n handler.sendEmptyMessage(MSG_CALL_RELEASE_HANDLER);\n }\n\n Runnable timeoutHangup = new Runnable() {\n\n @Override\n public void run() {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n };\n\n @Override\n public void onBackPressed() {\n handler.sendEmptyMessage(MSG_CALL_END);\n finish();\n super.onBackPressed();\n }\n\n private CustomVideoView addViewToMultiLayout(String streamId) {\n final CustomVideoView item = new CustomVideoView(this);\n item.setTag(streamId);\n multiVideoView.addView(item);\n return item;\n }\n\n private void initListeners() {\n bottomRelativeLayout.setAnswerOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_ANSWER);\n }\n });\n bottomRelativeLayout.setHangUpOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n });\n bottomRelativeLayout.setLocalVideoOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().pauseVideo();\n localSurfaceView.setSurfaceViewVisible(false);\n } else {\n ChatClient.getInstance().callManager().resumeVideo();\n localSurfaceView.setSurfaceViewVisible(true);\n }\n }\n });\n bottomRelativeLayout.setMuteOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().resumeVoice();\n } else {\n ChatClient.getInstance().callManager().pauseVoice();\n }\n }\n });\n bottomRelativeLayout.setSwitchCameraOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_SWITCH_CAMERA);\n }\n });\n bottomRelativeLayout.setSpeakerOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n closeSpeakerOn();\n } else {\n openSpeakerOn();\n }\n }\n });\n bottomRelativeLayout.setSharedWindowOnClickListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().publishWindow(VideoCallActivity.this, null);\n } else {\n ChatClient.getInstance().callManager().unPublishWindow(null);\n stopForegroundService();\n }\n }\n });\n multiVideoView.setOnMaxVideoChangeListener(new CustomVideoContainer.OnMaxVideoChangeListener() {\n\n @Override\n public void onChanged(boolean isMax) {\n bottomRelativeLayout.setMaxScreenState(isMax);\n ibMinimize.setVisibility(isMax ? View.VISIBLE : View.GONE);\n }\n });\n ibMinimize.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n ibMinimize.setVisibility(View.GONE);\n multiVideoView.minimizeChildView();\n bottomRelativeLayout.setMaxScreenState(false);\n }\n });\n }\n\n private void initViews() {\n ibMinimize = (ImageButton) findViewById(R.id.ib_minimize);\n ibMinimize.setVisibility(View.GONE);\n multiVideoView = (CustomVideoContainer) findViewById(R.id.multi_view_container);\n bottomRelativeLayout = (BottomRelativeLayout) findViewById(R.id.bottom_relative);\n rootLayout = findViewById(R.id.root_layout);\n bottomRelativeLayout.setAgentNick(ChatClient.getInstance().callManager().getCallNickName());\n }\n\n private boolean firstChanged = true;\n\n ", "post_mask_code": "{\n super.onWindowFocusChanged(hasFocus);\n if (firstChanged) {\n firstChanged = false;\n ViewGroup.LayoutParams layoutParams = bottomRelativeLayout.getLayoutParams();\n layoutParams.height = rootLayout.getHeight() - multiVideoView.getHeight();\n bottomRelativeLayout.setLayoutParams(layoutParams);\n }\n }\n\n private void info(String msg) {\n Log.d(TAG, \"\" + msg);\n }\n\n @Override\n public void onAddStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n List streamItemList;\n if (!streamItemMaps.containsKey(stream.memberName)) {\n streamItemList = new ArrayList<>();\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n streamItemMaps.put(stream.memberName, streamItemList);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n } else {\n streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n } else if (streamItemList.size() == 1) {\n if (stream.streamType == EMediaDefines.EMediaStreamType.EMSTREAM_TYPE_DESKTOP) {\n StreamItem item0 = streamItemList.get(0);\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = item0.videoView;\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n }\n }\n });\n }\n\n @Override\n public void onRemoveStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (!streamItemMaps.containsKey(stream.memberName)) {\n return;\n }\n List streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n streamItemMaps.remove(stream.memberName);\n } else if (streamItemList.size() == 1) {\n CustomVideoView videoView = streamItemList.get(0).videoView;\n if (videoView != null) {\n multiVideoView.removeVideoView(videoView);\n }\n streamItemMaps.remove(stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(stream.streamId, null);\n } else if (streamItemList.size() == 2) {\n StreamItem item0 = streamItemList.get(0);\n StreamItem item1 = streamItemList.get(1);\n if (item0.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item1.videoView = item0.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n streamItemList.remove(item0);\n item1.videoView.setLabel(item1.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, item1.videoView.getSurfaceView());\n } else if (item1.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item0.videoView = item1.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, null);\n streamItemList.remove(item1);\n item0.videoView.setLabel(item0.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, item0.videoView.getSurfaceView());\n }\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n });\n }\n\n @Override\n public void onUpdateStream(MediaStream stream) {\n }\n\n @Override\n public void onCallEnd(int reason, String desc) {\n EMLog.d(TAG, \"onCallEnd-reason:\" + reason + \",desc:\" + desc);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n }\n\n @Override\n public void onNotice(CallManager.HMediaNoticeCode code, String arg1, String arg2, Object arg3) {\n switch(code) {\n case HMediaNoticeOpenCameraFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n case HMediaNoticeOpenMicFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n }\n }\n\n public static class StreamItem {\n\n CustomVideoView videoView;\n\n MediaStream stream;\n }\n\n private void stopForegroundService() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n stopService(service);\n }\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n ChatClient.getInstance().callManager().removeDelegate(this);\n if (ringtone != null && ringtone.isPlaying()) {\n ringtone.stop();\n }\n unregisterReceiver(headsetReceiver);\n audioManager.setMode(AudioManager.MODE_NORMAL);\n audioManager.setMicrophoneMute(false);\n releaseHandler();\n }\n\n public String getNickName(String memberName) {\n EMediaEntities.EMediaMember mediaMember = ChatClient.getInstance().callManager().getEMediaMember(memberName);\n if (mediaMember != null && !TextUtils.isEmpty(mediaMember.extension)) {\n try {\n JSONObject jsonObject = new JSONObject(mediaMember.extension);\n return jsonObject.getString(\"nickname\");\n } catch (Exception ignored) {\n }\n }\n return memberName;\n }\n\n protected void openSpeakerOn() {\n try {\n if (!audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(true);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n protected void closeSpeakerOn() {\n try {\n if (audioManager != null) {\n if (audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(false);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == ScreenCaptureManager.RECORD_REQUEST_CODE) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n service.putExtra(\"code\", resultCode);\n service.putExtra(\"data\", data);\n startForegroundService(service);\n } else {\n ChatClient.getInstance().callManager().onActivityResult(requestCode, resultCode, data);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_478", "language": "Java", "task_type": "method_body", "source_file": "java/github/easemob/kefu-android-demo/app/src/main/java/com/easemob/helpdeskdemo/ui/VideoCallActivity.java", "mask_start_position": 11536, "mask_end_position": 11617, "canonical_solution": "{\n handler.sendEmptyMessage(MSG_CALL_SWITCH_CAMERA);\n }", "pre_mask_code": "package com.easemob.helpdeskdemo.ui;\n\nimport android.app.Activity;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.media.AudioManager;\nimport android.media.Ringtone;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.WindowManager;\nimport android.widget.ImageButton;\nimport android.widget.Toast;\nimport com.easemob.helpdeskdemo.Preferences;\nimport com.easemob.helpdeskdemo.R;\nimport com.easemob.helpdeskdemo.widget.BottomRelativeLayout;\nimport com.easemob.helpdeskdemo.widget.CustomVideoContainer;\nimport com.easemob.helpdeskdemo.widget.CustomVideoView;\nimport com.hyphenate.chat.CallManager;\nimport com.hyphenate.chat.ChatClient;\nimport com.hyphenate.chat.MediaStream;\nimport com.hyphenate.helpdesk.easeui.widget.ToastHelper;\nimport com.hyphenate.helpdesk.util.Log;\nimport com.hyphenate.util.EMLog;\nimport com.superrtc.mediamanager.EMediaDefines;\nimport com.superrtc.mediamanager.EMediaEntities;\nimport com.superrtc.mediamanager.ScreenCaptureManager;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n// this class is not used?\npublic class VideoCallActivity extends DemoBaseActivity implements CallManager.CallManagerDelegate {\n\n private static final String TAG = \"call\";\n\n protected final int MSG_CALL_ANSWER = 2;\n\n protected final int MSG_CALL_END = 3;\n\n protected final int MSG_CALL_RELEASE_HANDLER = 4;\n\n protected final int MSG_CALL_SWITCH_CAMERA = 5;\n\n private View rootLayout;\n\n private CustomVideoContainer multiVideoView;\n\n private CustomVideoView localSurfaceView;\n\n private ImageButton ibMinimize;\n\n private Map> streamItemMaps = new HashMap<>();\n\n private BottomRelativeLayout bottomRelativeLayout;\n\n protected AudioManager audioManager;\n\n protected Ringtone ringtone;\n\n private HeadsetReceiver headsetReceiver = new HeadsetReceiver();\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n finish();\n return;\n }\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);\n setContentView(R.layout.activity_call);\n String fromUsername = getIntent().getStringExtra(\"username\");\n audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);\n initViews();\n info(\"conference demo\");\n initListeners();\n ChatClient.getInstance().callManager().addDelegate(this);\n Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);\n audioManager.setMode(AudioManager.MODE_RINGTONE);\n audioManager.setSpeakerphoneOn(true);\n ringtone = RingtoneManager.getRingtone(this, ringUri);\n if (ringtone != null) {\n ringtone.play();\n }\n final int MAKE_CALL_TIMEOUT = 60 * 1000;\n handler.removeCallbacks(timeoutHangup);\n handler.postDelayed(timeoutHangup, MAKE_CALL_TIMEOUT);\n registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));\n }\n\n private String getSelfNick() {\n String nickName = Preferences.getInstance().getNickName();\n if (TextUtils.isEmpty(nickName)) {\n nickName = ChatClient.getInstance().currentUserName();\n }\n return nickName;\n }\n\n class HeadsetReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n switch(action) {\n // 插入和拔出耳机会触发广播\n case Intent.ACTION_HEADSET_PLUG:\n int state = intent.getIntExtra(\"state\", 0);\n if (state == 1) {\n // 耳机已插入\n closeSpeakerOn();\n } else if (state == 0) {\n // 耳机已拔出\n openSpeakerOn();\n }\n break;\n }\n }\n }\n\n HandlerThread callHandlerThread = new HandlerThread(\"callHandlerThread\");\n\n {\n callHandlerThread.start();\n }\n\n protected Handler handler = new Handler(callHandlerThread.getLooper()) {\n\n @Override\n public void handleMessage(android.os.Message msg) {\n EMLog.d(TAG, \"handleMessage -- enter block -- msg.what: \" + msg.what);\n switch(msg.what) {\n case MSG_CALL_ANSWER:\n EMLog.d(TAG, \"MSG_CALL_ANSWER\");\n handler.removeCallbacks(timeoutHangup);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n openSpeakerOn();\n bottomRelativeLayout.startChronometer();\n bottomRelativeLayout.setCallStateText(getString(R.string.tip_multi_video_calling));\n ChatClient.getInstance().callManager().acceptCall(getSelfNick(), new com.hyphenate.helpdesk.callback.Callback() {\n\n @Override\n public void onSuccess() {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n bottomRelativeLayout.setControllerButtonsVisibile(true);\n localSurfaceView = addViewToMultiLayout(null);\n localSurfaceView.setLabel(getSelfNick());\n ChatClient.getInstance().callManager().setLocalView(localSurfaceView.getSurfaceView());\n }\n });\n }\n\n @Override\n public void onError(int code, final String error) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ToastHelper.show(getBaseContext(), \"Publish Failed:\" + error);\n }\n });\n }\n\n @Override\n public void onProgress(int progress, String status) {\n }\n });\n }\n });\n break;\n case MSG_CALL_END:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n break;\n case MSG_CALL_RELEASE_HANDLER:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n info(\"click hangup\");\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n handler.removeCallbacks(timeoutHangup);\n handler.removeMessages(MSG_CALL_ANSWER);\n handler.removeMessages(MSG_CALL_END);\n callHandlerThread.quit();\n }\n });\n break;\n case MSG_CALL_SWITCH_CAMERA:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ChatClient.getInstance().callManager().switchCamera();\n }\n });\n break;\n default:\n break;\n }\n }\n };\n\n void releaseHandler() {\n handler.sendEmptyMessage(MSG_CALL_RELEASE_HANDLER);\n }\n\n Runnable timeoutHangup = new Runnable() {\n\n @Override\n public void run() {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n };\n\n @Override\n public void onBackPressed() {\n handler.sendEmptyMessage(MSG_CALL_END);\n finish();\n super.onBackPressed();\n }\n\n private CustomVideoView addViewToMultiLayout(String streamId) {\n final CustomVideoView item = new CustomVideoView(this);\n item.setTag(streamId);\n multiVideoView.addView(item);\n return item;\n }\n\n private void initListeners() {\n bottomRelativeLayout.setAnswerOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_ANSWER);\n }\n });\n bottomRelativeLayout.setHangUpOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n });\n bottomRelativeLayout.setLocalVideoOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().pauseVideo();\n localSurfaceView.setSurfaceViewVisible(false);\n } else {\n ChatClient.getInstance().callManager().resumeVideo();\n localSurfaceView.setSurfaceViewVisible(true);\n }\n }\n });\n bottomRelativeLayout.setMuteOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().resumeVoice();\n } else {\n ChatClient.getInstance().callManager().pauseVoice();\n }\n }\n });\n bottomRelativeLayout.setSwitchCameraOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) ", "post_mask_code": "\n });\n bottomRelativeLayout.setSpeakerOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n closeSpeakerOn();\n } else {\n openSpeakerOn();\n }\n }\n });\n bottomRelativeLayout.setSharedWindowOnClickListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().publishWindow(VideoCallActivity.this, null);\n } else {\n ChatClient.getInstance().callManager().unPublishWindow(null);\n stopForegroundService();\n }\n }\n });\n multiVideoView.setOnMaxVideoChangeListener(new CustomVideoContainer.OnMaxVideoChangeListener() {\n\n @Override\n public void onChanged(boolean isMax) {\n bottomRelativeLayout.setMaxScreenState(isMax);\n ibMinimize.setVisibility(isMax ? View.VISIBLE : View.GONE);\n }\n });\n ibMinimize.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n ibMinimize.setVisibility(View.GONE);\n multiVideoView.minimizeChildView();\n bottomRelativeLayout.setMaxScreenState(false);\n }\n });\n }\n\n private void initViews() {\n ibMinimize = (ImageButton) findViewById(R.id.ib_minimize);\n ibMinimize.setVisibility(View.GONE);\n multiVideoView = (CustomVideoContainer) findViewById(R.id.multi_view_container);\n bottomRelativeLayout = (BottomRelativeLayout) findViewById(R.id.bottom_relative);\n rootLayout = findViewById(R.id.root_layout);\n bottomRelativeLayout.setAgentNick(ChatClient.getInstance().callManager().getCallNickName());\n }\n\n private boolean firstChanged = true;\n\n @Override\n public void onWindowFocusChanged(boolean hasFocus) {\n super.onWindowFocusChanged(hasFocus);\n if (firstChanged) {\n firstChanged = false;\n ViewGroup.LayoutParams layoutParams = bottomRelativeLayout.getLayoutParams();\n layoutParams.height = rootLayout.getHeight() - multiVideoView.getHeight();\n bottomRelativeLayout.setLayoutParams(layoutParams);\n }\n }\n\n private void info(String msg) {\n Log.d(TAG, \"\" + msg);\n }\n\n @Override\n public void onAddStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n List streamItemList;\n if (!streamItemMaps.containsKey(stream.memberName)) {\n streamItemList = new ArrayList<>();\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n streamItemMaps.put(stream.memberName, streamItemList);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n } else {\n streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n } else if (streamItemList.size() == 1) {\n if (stream.streamType == EMediaDefines.EMediaStreamType.EMSTREAM_TYPE_DESKTOP) {\n StreamItem item0 = streamItemList.get(0);\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = item0.videoView;\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n }\n }\n });\n }\n\n @Override\n public void onRemoveStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (!streamItemMaps.containsKey(stream.memberName)) {\n return;\n }\n List streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n streamItemMaps.remove(stream.memberName);\n } else if (streamItemList.size() == 1) {\n CustomVideoView videoView = streamItemList.get(0).videoView;\n if (videoView != null) {\n multiVideoView.removeVideoView(videoView);\n }\n streamItemMaps.remove(stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(stream.streamId, null);\n } else if (streamItemList.size() == 2) {\n StreamItem item0 = streamItemList.get(0);\n StreamItem item1 = streamItemList.get(1);\n if (item0.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item1.videoView = item0.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n streamItemList.remove(item0);\n item1.videoView.setLabel(item1.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, item1.videoView.getSurfaceView());\n } else if (item1.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item0.videoView = item1.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, null);\n streamItemList.remove(item1);\n item0.videoView.setLabel(item0.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, item0.videoView.getSurfaceView());\n }\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n });\n }\n\n @Override\n public void onUpdateStream(MediaStream stream) {\n }\n\n @Override\n public void onCallEnd(int reason, String desc) {\n EMLog.d(TAG, \"onCallEnd-reason:\" + reason + \",desc:\" + desc);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n }\n\n @Override\n public void onNotice(CallManager.HMediaNoticeCode code, String arg1, String arg2, Object arg3) {\n switch(code) {\n case HMediaNoticeOpenCameraFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n case HMediaNoticeOpenMicFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n }\n }\n\n public static class StreamItem {\n\n CustomVideoView videoView;\n\n MediaStream stream;\n }\n\n private void stopForegroundService() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n stopService(service);\n }\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n ChatClient.getInstance().callManager().removeDelegate(this);\n if (ringtone != null && ringtone.isPlaying()) {\n ringtone.stop();\n }\n unregisterReceiver(headsetReceiver);\n audioManager.setMode(AudioManager.MODE_NORMAL);\n audioManager.setMicrophoneMute(false);\n releaseHandler();\n }\n\n public String getNickName(String memberName) {\n EMediaEntities.EMediaMember mediaMember = ChatClient.getInstance().callManager().getEMediaMember(memberName);\n if (mediaMember != null && !TextUtils.isEmpty(mediaMember.extension)) {\n try {\n JSONObject jsonObject = new JSONObject(mediaMember.extension);\n return jsonObject.getString(\"nickname\");\n } catch (Exception ignored) {\n }\n }\n return memberName;\n }\n\n protected void openSpeakerOn() {\n try {\n if (!audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(true);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n protected void closeSpeakerOn() {\n try {\n if (audioManager != null) {\n if (audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(false);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == ScreenCaptureManager.RECORD_REQUEST_CODE) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n service.putExtra(\"code\", resultCode);\n service.putExtra(\"data\", data);\n startForegroundService(service);\n } else {\n ChatClient.getInstance().callManager().onActivityResult(requestCode, resultCode, data);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_479", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/easemob/kefu-android-demo/app/src/main/java/com/easemob/helpdeskdemo/ui/VideoCallActivity.java", "mask_start_position": 21136, "mask_end_position": 21254, "canonical_solution": "\n EMediaEntities.EMediaMember mediaMember = ChatClient.getInstance().callManager().getEMediaMember(memberName);", "pre_mask_code": "package com.easemob.helpdeskdemo.ui;\n\nimport android.app.Activity;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.media.AudioManager;\nimport android.media.Ringtone;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.WindowManager;\nimport android.widget.ImageButton;\nimport android.widget.Toast;\nimport com.easemob.helpdeskdemo.Preferences;\nimport com.easemob.helpdeskdemo.R;\nimport com.easemob.helpdeskdemo.widget.BottomRelativeLayout;\nimport com.easemob.helpdeskdemo.widget.CustomVideoContainer;\nimport com.easemob.helpdeskdemo.widget.CustomVideoView;\nimport com.hyphenate.chat.CallManager;\nimport com.hyphenate.chat.ChatClient;\nimport com.hyphenate.chat.MediaStream;\nimport com.hyphenate.helpdesk.easeui.widget.ToastHelper;\nimport com.hyphenate.helpdesk.util.Log;\nimport com.hyphenate.util.EMLog;\nimport com.superrtc.mediamanager.EMediaDefines;\nimport com.superrtc.mediamanager.EMediaEntities;\nimport com.superrtc.mediamanager.ScreenCaptureManager;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n// this class is not used?\npublic class VideoCallActivity extends DemoBaseActivity implements CallManager.CallManagerDelegate {\n\n private static final String TAG = \"call\";\n\n protected final int MSG_CALL_ANSWER = 2;\n\n protected final int MSG_CALL_END = 3;\n\n protected final int MSG_CALL_RELEASE_HANDLER = 4;\n\n protected final int MSG_CALL_SWITCH_CAMERA = 5;\n\n private View rootLayout;\n\n private CustomVideoContainer multiVideoView;\n\n private CustomVideoView localSurfaceView;\n\n private ImageButton ibMinimize;\n\n private Map> streamItemMaps = new HashMap<>();\n\n private BottomRelativeLayout bottomRelativeLayout;\n\n protected AudioManager audioManager;\n\n protected Ringtone ringtone;\n\n private HeadsetReceiver headsetReceiver = new HeadsetReceiver();\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n finish();\n return;\n }\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);\n setContentView(R.layout.activity_call);\n String fromUsername = getIntent().getStringExtra(\"username\");\n audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);\n initViews();\n info(\"conference demo\");\n initListeners();\n ChatClient.getInstance().callManager().addDelegate(this);\n Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);\n audioManager.setMode(AudioManager.MODE_RINGTONE);\n audioManager.setSpeakerphoneOn(true);\n ringtone = RingtoneManager.getRingtone(this, ringUri);\n if (ringtone != null) {\n ringtone.play();\n }\n final int MAKE_CALL_TIMEOUT = 60 * 1000;\n handler.removeCallbacks(timeoutHangup);\n handler.postDelayed(timeoutHangup, MAKE_CALL_TIMEOUT);\n registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));\n }\n\n private String getSelfNick() {\n String nickName = Preferences.getInstance().getNickName();\n if (TextUtils.isEmpty(nickName)) {\n nickName = ChatClient.getInstance().currentUserName();\n }\n return nickName;\n }\n\n class HeadsetReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n switch(action) {\n // 插入和拔出耳机会触发广播\n case Intent.ACTION_HEADSET_PLUG:\n int state = intent.getIntExtra(\"state\", 0);\n if (state == 1) {\n // 耳机已插入\n closeSpeakerOn();\n } else if (state == 0) {\n // 耳机已拔出\n openSpeakerOn();\n }\n break;\n }\n }\n }\n\n HandlerThread callHandlerThread = new HandlerThread(\"callHandlerThread\");\n\n {\n callHandlerThread.start();\n }\n\n protected Handler handler = new Handler(callHandlerThread.getLooper()) {\n\n @Override\n public void handleMessage(android.os.Message msg) {\n EMLog.d(TAG, \"handleMessage -- enter block -- msg.what: \" + msg.what);\n switch(msg.what) {\n case MSG_CALL_ANSWER:\n EMLog.d(TAG, \"MSG_CALL_ANSWER\");\n handler.removeCallbacks(timeoutHangup);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n openSpeakerOn();\n bottomRelativeLayout.startChronometer();\n bottomRelativeLayout.setCallStateText(getString(R.string.tip_multi_video_calling));\n ChatClient.getInstance().callManager().acceptCall(getSelfNick(), new com.hyphenate.helpdesk.callback.Callback() {\n\n @Override\n public void onSuccess() {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n bottomRelativeLayout.setControllerButtonsVisibile(true);\n localSurfaceView = addViewToMultiLayout(null);\n localSurfaceView.setLabel(getSelfNick());\n ChatClient.getInstance().callManager().setLocalView(localSurfaceView.getSurfaceView());\n }\n });\n }\n\n @Override\n public void onError(int code, final String error) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ToastHelper.show(getBaseContext(), \"Publish Failed:\" + error);\n }\n });\n }\n\n @Override\n public void onProgress(int progress, String status) {\n }\n });\n }\n });\n break;\n case MSG_CALL_END:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n break;\n case MSG_CALL_RELEASE_HANDLER:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n info(\"click hangup\");\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n handler.removeCallbacks(timeoutHangup);\n handler.removeMessages(MSG_CALL_ANSWER);\n handler.removeMessages(MSG_CALL_END);\n callHandlerThread.quit();\n }\n });\n break;\n case MSG_CALL_SWITCH_CAMERA:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ChatClient.getInstance().callManager().switchCamera();\n }\n });\n break;\n default:\n break;\n }\n }\n };\n\n void releaseHandler() {\n handler.sendEmptyMessage(MSG_CALL_RELEASE_HANDLER);\n }\n\n Runnable timeoutHangup = new Runnable() {\n\n @Override\n public void run() {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n };\n\n @Override\n public void onBackPressed() {\n handler.sendEmptyMessage(MSG_CALL_END);\n finish();\n super.onBackPressed();\n }\n\n private CustomVideoView addViewToMultiLayout(String streamId) {\n final CustomVideoView item = new CustomVideoView(this);\n item.setTag(streamId);\n multiVideoView.addView(item);\n return item;\n }\n\n private void initListeners() {\n bottomRelativeLayout.setAnswerOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_ANSWER);\n }\n });\n bottomRelativeLayout.setHangUpOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n });\n bottomRelativeLayout.setLocalVideoOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().pauseVideo();\n localSurfaceView.setSurfaceViewVisible(false);\n } else {\n ChatClient.getInstance().callManager().resumeVideo();\n localSurfaceView.setSurfaceViewVisible(true);\n }\n }\n });\n bottomRelativeLayout.setMuteOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().resumeVoice();\n } else {\n ChatClient.getInstance().callManager().pauseVoice();\n }\n }\n });\n bottomRelativeLayout.setSwitchCameraOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_SWITCH_CAMERA);\n }\n });\n bottomRelativeLayout.setSpeakerOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n closeSpeakerOn();\n } else {\n openSpeakerOn();\n }\n }\n });\n bottomRelativeLayout.setSharedWindowOnClickListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().publishWindow(VideoCallActivity.this, null);\n } else {\n ChatClient.getInstance().callManager().unPublishWindow(null);\n stopForegroundService();\n }\n }\n });\n multiVideoView.setOnMaxVideoChangeListener(new CustomVideoContainer.OnMaxVideoChangeListener() {\n\n @Override\n public void onChanged(boolean isMax) {\n bottomRelativeLayout.setMaxScreenState(isMax);\n ibMinimize.setVisibility(isMax ? View.VISIBLE : View.GONE);\n }\n });\n ibMinimize.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n ibMinimize.setVisibility(View.GONE);\n multiVideoView.minimizeChildView();\n bottomRelativeLayout.setMaxScreenState(false);\n }\n });\n }\n\n private void initViews() {\n ibMinimize = (ImageButton) findViewById(R.id.ib_minimize);\n ibMinimize.setVisibility(View.GONE);\n multiVideoView = (CustomVideoContainer) findViewById(R.id.multi_view_container);\n bottomRelativeLayout = (BottomRelativeLayout) findViewById(R.id.bottom_relative);\n rootLayout = findViewById(R.id.root_layout);\n bottomRelativeLayout.setAgentNick(ChatClient.getInstance().callManager().getCallNickName());\n }\n\n private boolean firstChanged = true;\n\n @Override\n public void onWindowFocusChanged(boolean hasFocus) {\n super.onWindowFocusChanged(hasFocus);\n if (firstChanged) {\n firstChanged = false;\n ViewGroup.LayoutParams layoutParams = bottomRelativeLayout.getLayoutParams();\n layoutParams.height = rootLayout.getHeight() - multiVideoView.getHeight();\n bottomRelativeLayout.setLayoutParams(layoutParams);\n }\n }\n\n private void info(String msg) {\n Log.d(TAG, \"\" + msg);\n }\n\n @Override\n public void onAddStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n List streamItemList;\n if (!streamItemMaps.containsKey(stream.memberName)) {\n streamItemList = new ArrayList<>();\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n streamItemMaps.put(stream.memberName, streamItemList);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n } else {\n streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n } else if (streamItemList.size() == 1) {\n if (stream.streamType == EMediaDefines.EMediaStreamType.EMSTREAM_TYPE_DESKTOP) {\n StreamItem item0 = streamItemList.get(0);\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = item0.videoView;\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n }\n }\n });\n }\n\n @Override\n public void onRemoveStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (!streamItemMaps.containsKey(stream.memberName)) {\n return;\n }\n List streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n streamItemMaps.remove(stream.memberName);\n } else if (streamItemList.size() == 1) {\n CustomVideoView videoView = streamItemList.get(0).videoView;\n if (videoView != null) {\n multiVideoView.removeVideoView(videoView);\n }\n streamItemMaps.remove(stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(stream.streamId, null);\n } else if (streamItemList.size() == 2) {\n StreamItem item0 = streamItemList.get(0);\n StreamItem item1 = streamItemList.get(1);\n if (item0.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item1.videoView = item0.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n streamItemList.remove(item0);\n item1.videoView.setLabel(item1.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, item1.videoView.getSurfaceView());\n } else if (item1.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item0.videoView = item1.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, null);\n streamItemList.remove(item1);\n item0.videoView.setLabel(item0.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, item0.videoView.getSurfaceView());\n }\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n });\n }\n\n @Override\n public void onUpdateStream(MediaStream stream) {\n }\n\n @Override\n public void onCallEnd(int reason, String desc) {\n EMLog.d(TAG, \"onCallEnd-reason:\" + reason + \",desc:\" + desc);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n }\n\n @Override\n public void onNotice(CallManager.HMediaNoticeCode code, String arg1, String arg2, Object arg3) {\n switch(code) {\n case HMediaNoticeOpenCameraFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n case HMediaNoticeOpenMicFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n }\n }\n\n public static class StreamItem {\n\n CustomVideoView videoView;\n\n MediaStream stream;\n }\n\n private void stopForegroundService() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n stopService(service);\n }\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n ChatClient.getInstance().callManager().removeDelegate(this);\n if (ringtone != null && ringtone.isPlaying()) {\n ringtone.stop();\n }\n unregisterReceiver(headsetReceiver);\n audioManager.setMode(AudioManager.MODE_NORMAL);\n audioManager.setMicrophoneMute(false);\n releaseHandler();\n }\n\n public String getNickName(String memberName) {", "post_mask_code": "\n if (mediaMember != null && !TextUtils.isEmpty(mediaMember.extension)) {\n try {\n JSONObject jsonObject = new JSONObject(mediaMember.extension);\n return jsonObject.getString(\"nickname\");\n } catch (Exception ignored) {\n }\n }\n return memberName;\n }\n\n protected void openSpeakerOn() {\n try {\n if (!audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(true);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n protected void closeSpeakerOn() {\n try {\n if (audioManager != null) {\n if (audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(false);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == ScreenCaptureManager.RECORD_REQUEST_CODE) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n service.putExtra(\"code\", resultCode);\n service.putExtra(\"data\", data);\n startForegroundService(service);\n } else {\n ChatClient.getInstance().callManager().onActivityResult(requestCode, resultCode, data);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_480", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/easemob/kefu-android-demo/app/src/main/java/com/easemob/helpdeskdemo/ui/VideoCallActivity.java", "mask_start_position": 21263, "mask_end_position": 21554, "canonical_solution": "if (mediaMember != null && !TextUtils.isEmpty(mediaMember.extension)) {\n try {\n JSONObject jsonObject = new JSONObject(mediaMember.extension);\n return jsonObject.getString(\"nickname\");\n } catch (Exception ignored) {\n }\n }", "pre_mask_code": "package com.easemob.helpdeskdemo.ui;\n\nimport android.app.Activity;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.media.AudioManager;\nimport android.media.Ringtone;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.WindowManager;\nimport android.widget.ImageButton;\nimport android.widget.Toast;\nimport com.easemob.helpdeskdemo.Preferences;\nimport com.easemob.helpdeskdemo.R;\nimport com.easemob.helpdeskdemo.widget.BottomRelativeLayout;\nimport com.easemob.helpdeskdemo.widget.CustomVideoContainer;\nimport com.easemob.helpdeskdemo.widget.CustomVideoView;\nimport com.hyphenate.chat.CallManager;\nimport com.hyphenate.chat.ChatClient;\nimport com.hyphenate.chat.MediaStream;\nimport com.hyphenate.helpdesk.easeui.widget.ToastHelper;\nimport com.hyphenate.helpdesk.util.Log;\nimport com.hyphenate.util.EMLog;\nimport com.superrtc.mediamanager.EMediaDefines;\nimport com.superrtc.mediamanager.EMediaEntities;\nimport com.superrtc.mediamanager.ScreenCaptureManager;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n// this class is not used?\npublic class VideoCallActivity extends DemoBaseActivity implements CallManager.CallManagerDelegate {\n\n private static final String TAG = \"call\";\n\n protected final int MSG_CALL_ANSWER = 2;\n\n protected final int MSG_CALL_END = 3;\n\n protected final int MSG_CALL_RELEASE_HANDLER = 4;\n\n protected final int MSG_CALL_SWITCH_CAMERA = 5;\n\n private View rootLayout;\n\n private CustomVideoContainer multiVideoView;\n\n private CustomVideoView localSurfaceView;\n\n private ImageButton ibMinimize;\n\n private Map> streamItemMaps = new HashMap<>();\n\n private BottomRelativeLayout bottomRelativeLayout;\n\n protected AudioManager audioManager;\n\n protected Ringtone ringtone;\n\n private HeadsetReceiver headsetReceiver = new HeadsetReceiver();\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n finish();\n return;\n }\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);\n setContentView(R.layout.activity_call);\n String fromUsername = getIntent().getStringExtra(\"username\");\n audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);\n initViews();\n info(\"conference demo\");\n initListeners();\n ChatClient.getInstance().callManager().addDelegate(this);\n Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);\n audioManager.setMode(AudioManager.MODE_RINGTONE);\n audioManager.setSpeakerphoneOn(true);\n ringtone = RingtoneManager.getRingtone(this, ringUri);\n if (ringtone != null) {\n ringtone.play();\n }\n final int MAKE_CALL_TIMEOUT = 60 * 1000;\n handler.removeCallbacks(timeoutHangup);\n handler.postDelayed(timeoutHangup, MAKE_CALL_TIMEOUT);\n registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));\n }\n\n private String getSelfNick() {\n String nickName = Preferences.getInstance().getNickName();\n if (TextUtils.isEmpty(nickName)) {\n nickName = ChatClient.getInstance().currentUserName();\n }\n return nickName;\n }\n\n class HeadsetReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n switch(action) {\n // 插入和拔出耳机会触发广播\n case Intent.ACTION_HEADSET_PLUG:\n int state = intent.getIntExtra(\"state\", 0);\n if (state == 1) {\n // 耳机已插入\n closeSpeakerOn();\n } else if (state == 0) {\n // 耳机已拔出\n openSpeakerOn();\n }\n break;\n }\n }\n }\n\n HandlerThread callHandlerThread = new HandlerThread(\"callHandlerThread\");\n\n {\n callHandlerThread.start();\n }\n\n protected Handler handler = new Handler(callHandlerThread.getLooper()) {\n\n @Override\n public void handleMessage(android.os.Message msg) {\n EMLog.d(TAG, \"handleMessage -- enter block -- msg.what: \" + msg.what);\n switch(msg.what) {\n case MSG_CALL_ANSWER:\n EMLog.d(TAG, \"MSG_CALL_ANSWER\");\n handler.removeCallbacks(timeoutHangup);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n openSpeakerOn();\n bottomRelativeLayout.startChronometer();\n bottomRelativeLayout.setCallStateText(getString(R.string.tip_multi_video_calling));\n ChatClient.getInstance().callManager().acceptCall(getSelfNick(), new com.hyphenate.helpdesk.callback.Callback() {\n\n @Override\n public void onSuccess() {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n bottomRelativeLayout.setControllerButtonsVisibile(true);\n localSurfaceView = addViewToMultiLayout(null);\n localSurfaceView.setLabel(getSelfNick());\n ChatClient.getInstance().callManager().setLocalView(localSurfaceView.getSurfaceView());\n }\n });\n }\n\n @Override\n public void onError(int code, final String error) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ToastHelper.show(getBaseContext(), \"Publish Failed:\" + error);\n }\n });\n }\n\n @Override\n public void onProgress(int progress, String status) {\n }\n });\n }\n });\n break;\n case MSG_CALL_END:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n break;\n case MSG_CALL_RELEASE_HANDLER:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n info(\"click hangup\");\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n handler.removeCallbacks(timeoutHangup);\n handler.removeMessages(MSG_CALL_ANSWER);\n handler.removeMessages(MSG_CALL_END);\n callHandlerThread.quit();\n }\n });\n break;\n case MSG_CALL_SWITCH_CAMERA:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ChatClient.getInstance().callManager().switchCamera();\n }\n });\n break;\n default:\n break;\n }\n }\n };\n\n void releaseHandler() {\n handler.sendEmptyMessage(MSG_CALL_RELEASE_HANDLER);\n }\n\n Runnable timeoutHangup = new Runnable() {\n\n @Override\n public void run() {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n };\n\n @Override\n public void onBackPressed() {\n handler.sendEmptyMessage(MSG_CALL_END);\n finish();\n super.onBackPressed();\n }\n\n private CustomVideoView addViewToMultiLayout(String streamId) {\n final CustomVideoView item = new CustomVideoView(this);\n item.setTag(streamId);\n multiVideoView.addView(item);\n return item;\n }\n\n private void initListeners() {\n bottomRelativeLayout.setAnswerOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_ANSWER);\n }\n });\n bottomRelativeLayout.setHangUpOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n });\n bottomRelativeLayout.setLocalVideoOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().pauseVideo();\n localSurfaceView.setSurfaceViewVisible(false);\n } else {\n ChatClient.getInstance().callManager().resumeVideo();\n localSurfaceView.setSurfaceViewVisible(true);\n }\n }\n });\n bottomRelativeLayout.setMuteOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().resumeVoice();\n } else {\n ChatClient.getInstance().callManager().pauseVoice();\n }\n }\n });\n bottomRelativeLayout.setSwitchCameraOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_SWITCH_CAMERA);\n }\n });\n bottomRelativeLayout.setSpeakerOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n closeSpeakerOn();\n } else {\n openSpeakerOn();\n }\n }\n });\n bottomRelativeLayout.setSharedWindowOnClickListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().publishWindow(VideoCallActivity.this, null);\n } else {\n ChatClient.getInstance().callManager().unPublishWindow(null);\n stopForegroundService();\n }\n }\n });\n multiVideoView.setOnMaxVideoChangeListener(new CustomVideoContainer.OnMaxVideoChangeListener() {\n\n @Override\n public void onChanged(boolean isMax) {\n bottomRelativeLayout.setMaxScreenState(isMax);\n ibMinimize.setVisibility(isMax ? View.VISIBLE : View.GONE);\n }\n });\n ibMinimize.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n ibMinimize.setVisibility(View.GONE);\n multiVideoView.minimizeChildView();\n bottomRelativeLayout.setMaxScreenState(false);\n }\n });\n }\n\n private void initViews() {\n ibMinimize = (ImageButton) findViewById(R.id.ib_minimize);\n ibMinimize.setVisibility(View.GONE);\n multiVideoView = (CustomVideoContainer) findViewById(R.id.multi_view_container);\n bottomRelativeLayout = (BottomRelativeLayout) findViewById(R.id.bottom_relative);\n rootLayout = findViewById(R.id.root_layout);\n bottomRelativeLayout.setAgentNick(ChatClient.getInstance().callManager().getCallNickName());\n }\n\n private boolean firstChanged = true;\n\n @Override\n public void onWindowFocusChanged(boolean hasFocus) {\n super.onWindowFocusChanged(hasFocus);\n if (firstChanged) {\n firstChanged = false;\n ViewGroup.LayoutParams layoutParams = bottomRelativeLayout.getLayoutParams();\n layoutParams.height = rootLayout.getHeight() - multiVideoView.getHeight();\n bottomRelativeLayout.setLayoutParams(layoutParams);\n }\n }\n\n private void info(String msg) {\n Log.d(TAG, \"\" + msg);\n }\n\n @Override\n public void onAddStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n List streamItemList;\n if (!streamItemMaps.containsKey(stream.memberName)) {\n streamItemList = new ArrayList<>();\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n streamItemMaps.put(stream.memberName, streamItemList);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n } else {\n streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n } else if (streamItemList.size() == 1) {\n if (stream.streamType == EMediaDefines.EMediaStreamType.EMSTREAM_TYPE_DESKTOP) {\n StreamItem item0 = streamItemList.get(0);\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = item0.videoView;\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n }\n }\n });\n }\n\n @Override\n public void onRemoveStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (!streamItemMaps.containsKey(stream.memberName)) {\n return;\n }\n List streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n streamItemMaps.remove(stream.memberName);\n } else if (streamItemList.size() == 1) {\n CustomVideoView videoView = streamItemList.get(0).videoView;\n if (videoView != null) {\n multiVideoView.removeVideoView(videoView);\n }\n streamItemMaps.remove(stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(stream.streamId, null);\n } else if (streamItemList.size() == 2) {\n StreamItem item0 = streamItemList.get(0);\n StreamItem item1 = streamItemList.get(1);\n if (item0.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item1.videoView = item0.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n streamItemList.remove(item0);\n item1.videoView.setLabel(item1.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, item1.videoView.getSurfaceView());\n } else if (item1.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item0.videoView = item1.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, null);\n streamItemList.remove(item1);\n item0.videoView.setLabel(item0.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, item0.videoView.getSurfaceView());\n }\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n });\n }\n\n @Override\n public void onUpdateStream(MediaStream stream) {\n }\n\n @Override\n public void onCallEnd(int reason, String desc) {\n EMLog.d(TAG, \"onCallEnd-reason:\" + reason + \",desc:\" + desc);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n }\n\n @Override\n public void onNotice(CallManager.HMediaNoticeCode code, String arg1, String arg2, Object arg3) {\n switch(code) {\n case HMediaNoticeOpenCameraFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n case HMediaNoticeOpenMicFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n }\n }\n\n public static class StreamItem {\n\n CustomVideoView videoView;\n\n MediaStream stream;\n }\n\n private void stopForegroundService() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n stopService(service);\n }\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n ChatClient.getInstance().callManager().removeDelegate(this);\n if (ringtone != null && ringtone.isPlaying()) {\n ringtone.stop();\n }\n unregisterReceiver(headsetReceiver);\n audioManager.setMode(AudioManager.MODE_NORMAL);\n audioManager.setMicrophoneMute(false);\n releaseHandler();\n }\n\n public String getNickName(String memberName) {\n EMediaEntities.EMediaMember mediaMember = ChatClient.getInstance().callManager().getEMediaMember(memberName);\n ", "post_mask_code": "\n return memberName;\n }\n\n protected void openSpeakerOn() {\n try {\n if (!audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(true);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n protected void closeSpeakerOn() {\n try {\n if (audioManager != null) {\n if (audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(false);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == ScreenCaptureManager.RECORD_REQUEST_CODE) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n service.putExtra(\"code\", resultCode);\n service.putExtra(\"data\", data);\n startForegroundService(service);\n } else {\n ChatClient.getInstance().callManager().onActivityResult(requestCode, resultCode, data);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_481", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/easemob/kefu-android-demo/app/src/main/java/com/easemob/helpdeskdemo/ui/VideoCallActivity.java", "mask_start_position": 21563, "mask_end_position": 21587, "canonical_solution": "return memberName;\n }", "pre_mask_code": "package com.easemob.helpdeskdemo.ui;\n\nimport android.app.Activity;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.media.AudioManager;\nimport android.media.Ringtone;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.WindowManager;\nimport android.widget.ImageButton;\nimport android.widget.Toast;\nimport com.easemob.helpdeskdemo.Preferences;\nimport com.easemob.helpdeskdemo.R;\nimport com.easemob.helpdeskdemo.widget.BottomRelativeLayout;\nimport com.easemob.helpdeskdemo.widget.CustomVideoContainer;\nimport com.easemob.helpdeskdemo.widget.CustomVideoView;\nimport com.hyphenate.chat.CallManager;\nimport com.hyphenate.chat.ChatClient;\nimport com.hyphenate.chat.MediaStream;\nimport com.hyphenate.helpdesk.easeui.widget.ToastHelper;\nimport com.hyphenate.helpdesk.util.Log;\nimport com.hyphenate.util.EMLog;\nimport com.superrtc.mediamanager.EMediaDefines;\nimport com.superrtc.mediamanager.EMediaEntities;\nimport com.superrtc.mediamanager.ScreenCaptureManager;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n// this class is not used?\npublic class VideoCallActivity extends DemoBaseActivity implements CallManager.CallManagerDelegate {\n\n private static final String TAG = \"call\";\n\n protected final int MSG_CALL_ANSWER = 2;\n\n protected final int MSG_CALL_END = 3;\n\n protected final int MSG_CALL_RELEASE_HANDLER = 4;\n\n protected final int MSG_CALL_SWITCH_CAMERA = 5;\n\n private View rootLayout;\n\n private CustomVideoContainer multiVideoView;\n\n private CustomVideoView localSurfaceView;\n\n private ImageButton ibMinimize;\n\n private Map> streamItemMaps = new HashMap<>();\n\n private BottomRelativeLayout bottomRelativeLayout;\n\n protected AudioManager audioManager;\n\n protected Ringtone ringtone;\n\n private HeadsetReceiver headsetReceiver = new HeadsetReceiver();\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n finish();\n return;\n }\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);\n setContentView(R.layout.activity_call);\n String fromUsername = getIntent().getStringExtra(\"username\");\n audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);\n initViews();\n info(\"conference demo\");\n initListeners();\n ChatClient.getInstance().callManager().addDelegate(this);\n Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);\n audioManager.setMode(AudioManager.MODE_RINGTONE);\n audioManager.setSpeakerphoneOn(true);\n ringtone = RingtoneManager.getRingtone(this, ringUri);\n if (ringtone != null) {\n ringtone.play();\n }\n final int MAKE_CALL_TIMEOUT = 60 * 1000;\n handler.removeCallbacks(timeoutHangup);\n handler.postDelayed(timeoutHangup, MAKE_CALL_TIMEOUT);\n registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));\n }\n\n private String getSelfNick() {\n String nickName = Preferences.getInstance().getNickName();\n if (TextUtils.isEmpty(nickName)) {\n nickName = ChatClient.getInstance().currentUserName();\n }\n return nickName;\n }\n\n class HeadsetReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n switch(action) {\n // 插入和拔出耳机会触发广播\n case Intent.ACTION_HEADSET_PLUG:\n int state = intent.getIntExtra(\"state\", 0);\n if (state == 1) {\n // 耳机已插入\n closeSpeakerOn();\n } else if (state == 0) {\n // 耳机已拔出\n openSpeakerOn();\n }\n break;\n }\n }\n }\n\n HandlerThread callHandlerThread = new HandlerThread(\"callHandlerThread\");\n\n {\n callHandlerThread.start();\n }\n\n protected Handler handler = new Handler(callHandlerThread.getLooper()) {\n\n @Override\n public void handleMessage(android.os.Message msg) {\n EMLog.d(TAG, \"handleMessage -- enter block -- msg.what: \" + msg.what);\n switch(msg.what) {\n case MSG_CALL_ANSWER:\n EMLog.d(TAG, \"MSG_CALL_ANSWER\");\n handler.removeCallbacks(timeoutHangup);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n openSpeakerOn();\n bottomRelativeLayout.startChronometer();\n bottomRelativeLayout.setCallStateText(getString(R.string.tip_multi_video_calling));\n ChatClient.getInstance().callManager().acceptCall(getSelfNick(), new com.hyphenate.helpdesk.callback.Callback() {\n\n @Override\n public void onSuccess() {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n bottomRelativeLayout.setControllerButtonsVisibile(true);\n localSurfaceView = addViewToMultiLayout(null);\n localSurfaceView.setLabel(getSelfNick());\n ChatClient.getInstance().callManager().setLocalView(localSurfaceView.getSurfaceView());\n }\n });\n }\n\n @Override\n public void onError(int code, final String error) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ToastHelper.show(getBaseContext(), \"Publish Failed:\" + error);\n }\n });\n }\n\n @Override\n public void onProgress(int progress, String status) {\n }\n });\n }\n });\n break;\n case MSG_CALL_END:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n break;\n case MSG_CALL_RELEASE_HANDLER:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n info(\"click hangup\");\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n handler.removeCallbacks(timeoutHangup);\n handler.removeMessages(MSG_CALL_ANSWER);\n handler.removeMessages(MSG_CALL_END);\n callHandlerThread.quit();\n }\n });\n break;\n case MSG_CALL_SWITCH_CAMERA:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ChatClient.getInstance().callManager().switchCamera();\n }\n });\n break;\n default:\n break;\n }\n }\n };\n\n void releaseHandler() {\n handler.sendEmptyMessage(MSG_CALL_RELEASE_HANDLER);\n }\n\n Runnable timeoutHangup = new Runnable() {\n\n @Override\n public void run() {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n };\n\n @Override\n public void onBackPressed() {\n handler.sendEmptyMessage(MSG_CALL_END);\n finish();\n super.onBackPressed();\n }\n\n private CustomVideoView addViewToMultiLayout(String streamId) {\n final CustomVideoView item = new CustomVideoView(this);\n item.setTag(streamId);\n multiVideoView.addView(item);\n return item;\n }\n\n private void initListeners() {\n bottomRelativeLayout.setAnswerOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_ANSWER);\n }\n });\n bottomRelativeLayout.setHangUpOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n });\n bottomRelativeLayout.setLocalVideoOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().pauseVideo();\n localSurfaceView.setSurfaceViewVisible(false);\n } else {\n ChatClient.getInstance().callManager().resumeVideo();\n localSurfaceView.setSurfaceViewVisible(true);\n }\n }\n });\n bottomRelativeLayout.setMuteOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().resumeVoice();\n } else {\n ChatClient.getInstance().callManager().pauseVoice();\n }\n }\n });\n bottomRelativeLayout.setSwitchCameraOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_SWITCH_CAMERA);\n }\n });\n bottomRelativeLayout.setSpeakerOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n closeSpeakerOn();\n } else {\n openSpeakerOn();\n }\n }\n });\n bottomRelativeLayout.setSharedWindowOnClickListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().publishWindow(VideoCallActivity.this, null);\n } else {\n ChatClient.getInstance().callManager().unPublishWindow(null);\n stopForegroundService();\n }\n }\n });\n multiVideoView.setOnMaxVideoChangeListener(new CustomVideoContainer.OnMaxVideoChangeListener() {\n\n @Override\n public void onChanged(boolean isMax) {\n bottomRelativeLayout.setMaxScreenState(isMax);\n ibMinimize.setVisibility(isMax ? View.VISIBLE : View.GONE);\n }\n });\n ibMinimize.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n ibMinimize.setVisibility(View.GONE);\n multiVideoView.minimizeChildView();\n bottomRelativeLayout.setMaxScreenState(false);\n }\n });\n }\n\n private void initViews() {\n ibMinimize = (ImageButton) findViewById(R.id.ib_minimize);\n ibMinimize.setVisibility(View.GONE);\n multiVideoView = (CustomVideoContainer) findViewById(R.id.multi_view_container);\n bottomRelativeLayout = (BottomRelativeLayout) findViewById(R.id.bottom_relative);\n rootLayout = findViewById(R.id.root_layout);\n bottomRelativeLayout.setAgentNick(ChatClient.getInstance().callManager().getCallNickName());\n }\n\n private boolean firstChanged = true;\n\n @Override\n public void onWindowFocusChanged(boolean hasFocus) {\n super.onWindowFocusChanged(hasFocus);\n if (firstChanged) {\n firstChanged = false;\n ViewGroup.LayoutParams layoutParams = bottomRelativeLayout.getLayoutParams();\n layoutParams.height = rootLayout.getHeight() - multiVideoView.getHeight();\n bottomRelativeLayout.setLayoutParams(layoutParams);\n }\n }\n\n private void info(String msg) {\n Log.d(TAG, \"\" + msg);\n }\n\n @Override\n public void onAddStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n List streamItemList;\n if (!streamItemMaps.containsKey(stream.memberName)) {\n streamItemList = new ArrayList<>();\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n streamItemMaps.put(stream.memberName, streamItemList);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n } else {\n streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n } else if (streamItemList.size() == 1) {\n if (stream.streamType == EMediaDefines.EMediaStreamType.EMSTREAM_TYPE_DESKTOP) {\n StreamItem item0 = streamItemList.get(0);\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = item0.videoView;\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n }\n }\n });\n }\n\n @Override\n public void onRemoveStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (!streamItemMaps.containsKey(stream.memberName)) {\n return;\n }\n List streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n streamItemMaps.remove(stream.memberName);\n } else if (streamItemList.size() == 1) {\n CustomVideoView videoView = streamItemList.get(0).videoView;\n if (videoView != null) {\n multiVideoView.removeVideoView(videoView);\n }\n streamItemMaps.remove(stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(stream.streamId, null);\n } else if (streamItemList.size() == 2) {\n StreamItem item0 = streamItemList.get(0);\n StreamItem item1 = streamItemList.get(1);\n if (item0.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item1.videoView = item0.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n streamItemList.remove(item0);\n item1.videoView.setLabel(item1.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, item1.videoView.getSurfaceView());\n } else if (item1.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item0.videoView = item1.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, null);\n streamItemList.remove(item1);\n item0.videoView.setLabel(item0.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, item0.videoView.getSurfaceView());\n }\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n });\n }\n\n @Override\n public void onUpdateStream(MediaStream stream) {\n }\n\n @Override\n public void onCallEnd(int reason, String desc) {\n EMLog.d(TAG, \"onCallEnd-reason:\" + reason + \",desc:\" + desc);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n }\n\n @Override\n public void onNotice(CallManager.HMediaNoticeCode code, String arg1, String arg2, Object arg3) {\n switch(code) {\n case HMediaNoticeOpenCameraFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n case HMediaNoticeOpenMicFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n }\n }\n\n public static class StreamItem {\n\n CustomVideoView videoView;\n\n MediaStream stream;\n }\n\n private void stopForegroundService() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n stopService(service);\n }\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n ChatClient.getInstance().callManager().removeDelegate(this);\n if (ringtone != null && ringtone.isPlaying()) {\n ringtone.stop();\n }\n unregisterReceiver(headsetReceiver);\n audioManager.setMode(AudioManager.MODE_NORMAL);\n audioManager.setMicrophoneMute(false);\n releaseHandler();\n }\n\n public String getNickName(String memberName) {\n EMediaEntities.EMediaMember mediaMember = ChatClient.getInstance().callManager().getEMediaMember(memberName);\n if (mediaMember != null && !TextUtils.isEmpty(mediaMember.extension)) {\n try {\n JSONObject jsonObject = new JSONObject(mediaMember.extension);\n return jsonObject.getString(\"nickname\");\n } catch (Exception ignored) {\n }\n }\n ", "post_mask_code": "\n\n protected void openSpeakerOn() {\n try {\n if (!audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(true);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n protected void closeSpeakerOn() {\n try {\n if (audioManager != null) {\n if (audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(false);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == ScreenCaptureManager.RECORD_REQUEST_CODE) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n service.putExtra(\"code\", resultCode);\n service.putExtra(\"data\", data);\n startForegroundService(service);\n } else {\n ChatClient.getInstance().callManager().onActivityResult(requestCode, resultCode, data);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_482", "language": "Java", "task_type": "single_line", "source_file": "java/github/easemob/kefu-android-demo/app/src/main/java/com/easemob/helpdeskdemo/ui/VideoCallActivity.java", "mask_start_position": 5405, "mask_end_position": 5412, "canonical_solution": "erOn();", "pre_mask_code": "package com.easemob.helpdeskdemo.ui;\n\nimport android.app.Activity;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.media.AudioManager;\nimport android.media.Ringtone;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.WindowManager;\nimport android.widget.ImageButton;\nimport android.widget.Toast;\nimport com.easemob.helpdeskdemo.Preferences;\nimport com.easemob.helpdeskdemo.R;\nimport com.easemob.helpdeskdemo.widget.BottomRelativeLayout;\nimport com.easemob.helpdeskdemo.widget.CustomVideoContainer;\nimport com.easemob.helpdeskdemo.widget.CustomVideoView;\nimport com.hyphenate.chat.CallManager;\nimport com.hyphenate.chat.ChatClient;\nimport com.hyphenate.chat.MediaStream;\nimport com.hyphenate.helpdesk.easeui.widget.ToastHelper;\nimport com.hyphenate.helpdesk.util.Log;\nimport com.hyphenate.util.EMLog;\nimport com.superrtc.mediamanager.EMediaDefines;\nimport com.superrtc.mediamanager.EMediaEntities;\nimport com.superrtc.mediamanager.ScreenCaptureManager;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n// this class is not used?\npublic class VideoCallActivity extends DemoBaseActivity implements CallManager.CallManagerDelegate {\n\n private static final String TAG = \"call\";\n\n protected final int MSG_CALL_ANSWER = 2;\n\n protected final int MSG_CALL_END = 3;\n\n protected final int MSG_CALL_RELEASE_HANDLER = 4;\n\n protected final int MSG_CALL_SWITCH_CAMERA = 5;\n\n private View rootLayout;\n\n private CustomVideoContainer multiVideoView;\n\n private CustomVideoView localSurfaceView;\n\n private ImageButton ibMinimize;\n\n private Map> streamItemMaps = new HashMap<>();\n\n private BottomRelativeLayout bottomRelativeLayout;\n\n protected AudioManager audioManager;\n\n protected Ringtone ringtone;\n\n private HeadsetReceiver headsetReceiver = new HeadsetReceiver();\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n finish();\n return;\n }\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);\n setContentView(R.layout.activity_call);\n String fromUsername = getIntent().getStringExtra(\"username\");\n audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);\n initViews();\n info(\"conference demo\");\n initListeners();\n ChatClient.getInstance().callManager().addDelegate(this);\n Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);\n audioManager.setMode(AudioManager.MODE_RINGTONE);\n audioManager.setSpeakerphoneOn(true);\n ringtone = RingtoneManager.getRingtone(this, ringUri);\n if (ringtone != null) {\n ringtone.play();\n }\n final int MAKE_CALL_TIMEOUT = 60 * 1000;\n handler.removeCallbacks(timeoutHangup);\n handler.postDelayed(timeoutHangup, MAKE_CALL_TIMEOUT);\n registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));\n }\n\n private String getSelfNick() {\n String nickName = Preferences.getInstance().getNickName();\n if (TextUtils.isEmpty(nickName)) {\n nickName = ChatClient.getInstance().currentUserName();\n }\n return nickName;\n }\n\n class HeadsetReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n switch(action) {\n // 插入和拔出耳机会触发广播\n case Intent.ACTION_HEADSET_PLUG:\n int state = intent.getIntExtra(\"state\", 0);\n if (state == 1) {\n // 耳机已插入\n closeSpeakerOn();\n } else if (state == 0) {\n // 耳机已拔出\n openSpeakerOn();\n }\n break;\n }\n }\n }\n\n HandlerThread callHandlerThread = new HandlerThread(\"callHandlerThread\");\n\n {\n callHandlerThread.start();\n }\n\n protected Handler handler = new Handler(callHandlerThread.getLooper()) {\n\n @Override\n public void handleMessage(android.os.Message msg) {\n EMLog.d(TAG, \"handleMessage -- enter block -- msg.what: \" + msg.what);\n switch(msg.what) {\n case MSG_CALL_ANSWER:\n EMLog.d(TAG, \"MSG_CALL_ANSWER\");\n handler.removeCallbacks(timeoutHangup);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n openSpeak", "post_mask_code": "\n bottomRelativeLayout.startChronometer();\n bottomRelativeLayout.setCallStateText(getString(R.string.tip_multi_video_calling));\n ChatClient.getInstance().callManager().acceptCall(getSelfNick(), new com.hyphenate.helpdesk.callback.Callback() {\n\n @Override\n public void onSuccess() {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n bottomRelativeLayout.setControllerButtonsVisibile(true);\n localSurfaceView = addViewToMultiLayout(null);\n localSurfaceView.setLabel(getSelfNick());\n ChatClient.getInstance().callManager().setLocalView(localSurfaceView.getSurfaceView());\n }\n });\n }\n\n @Override\n public void onError(int code, final String error) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ToastHelper.show(getBaseContext(), \"Publish Failed:\" + error);\n }\n });\n }\n\n @Override\n public void onProgress(int progress, String status) {\n }\n });\n }\n });\n break;\n case MSG_CALL_END:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n break;\n case MSG_CALL_RELEASE_HANDLER:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n info(\"click hangup\");\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n handler.removeCallbacks(timeoutHangup);\n handler.removeMessages(MSG_CALL_ANSWER);\n handler.removeMessages(MSG_CALL_END);\n callHandlerThread.quit();\n }\n });\n break;\n case MSG_CALL_SWITCH_CAMERA:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ChatClient.getInstance().callManager().switchCamera();\n }\n });\n break;\n default:\n break;\n }\n }\n };\n\n void releaseHandler() {\n handler.sendEmptyMessage(MSG_CALL_RELEASE_HANDLER);\n }\n\n Runnable timeoutHangup = new Runnable() {\n\n @Override\n public void run() {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n };\n\n @Override\n public void onBackPressed() {\n handler.sendEmptyMessage(MSG_CALL_END);\n finish();\n super.onBackPressed();\n }\n\n private CustomVideoView addViewToMultiLayout(String streamId) {\n final CustomVideoView item = new CustomVideoView(this);\n item.setTag(streamId);\n multiVideoView.addView(item);\n return item;\n }\n\n private void initListeners() {\n bottomRelativeLayout.setAnswerOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_ANSWER);\n }\n });\n bottomRelativeLayout.setHangUpOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n });\n bottomRelativeLayout.setLocalVideoOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().pauseVideo();\n localSurfaceView.setSurfaceViewVisible(false);\n } else {\n ChatClient.getInstance().callManager().resumeVideo();\n localSurfaceView.setSurfaceViewVisible(true);\n }\n }\n });\n bottomRelativeLayout.setMuteOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().resumeVoice();\n } else {\n ChatClient.getInstance().callManager().pauseVoice();\n }\n }\n });\n bottomRelativeLayout.setSwitchCameraOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_SWITCH_CAMERA);\n }\n });\n bottomRelativeLayout.setSpeakerOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n closeSpeakerOn();\n } else {\n openSpeakerOn();\n }\n }\n });\n bottomRelativeLayout.setSharedWindowOnClickListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().publishWindow(VideoCallActivity.this, null);\n } else {\n ChatClient.getInstance().callManager().unPublishWindow(null);\n stopForegroundService();\n }\n }\n });\n multiVideoView.setOnMaxVideoChangeListener(new CustomVideoContainer.OnMaxVideoChangeListener() {\n\n @Override\n public void onChanged(boolean isMax) {\n bottomRelativeLayout.setMaxScreenState(isMax);\n ibMinimize.setVisibility(isMax ? View.VISIBLE : View.GONE);\n }\n });\n ibMinimize.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n ibMinimize.setVisibility(View.GONE);\n multiVideoView.minimizeChildView();\n bottomRelativeLayout.setMaxScreenState(false);\n }\n });\n }\n\n private void initViews() {\n ibMinimize = (ImageButton) findViewById(R.id.ib_minimize);\n ibMinimize.setVisibility(View.GONE);\n multiVideoView = (CustomVideoContainer) findViewById(R.id.multi_view_container);\n bottomRelativeLayout = (BottomRelativeLayout) findViewById(R.id.bottom_relative);\n rootLayout = findViewById(R.id.root_layout);\n bottomRelativeLayout.setAgentNick(ChatClient.getInstance().callManager().getCallNickName());\n }\n\n private boolean firstChanged = true;\n\n @Override\n public void onWindowFocusChanged(boolean hasFocus) {\n super.onWindowFocusChanged(hasFocus);\n if (firstChanged) {\n firstChanged = false;\n ViewGroup.LayoutParams layoutParams = bottomRelativeLayout.getLayoutParams();\n layoutParams.height = rootLayout.getHeight() - multiVideoView.getHeight();\n bottomRelativeLayout.setLayoutParams(layoutParams);\n }\n }\n\n private void info(String msg) {\n Log.d(TAG, \"\" + msg);\n }\n\n @Override\n public void onAddStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n List streamItemList;\n if (!streamItemMaps.containsKey(stream.memberName)) {\n streamItemList = new ArrayList<>();\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n streamItemMaps.put(stream.memberName, streamItemList);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n } else {\n streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n } else if (streamItemList.size() == 1) {\n if (stream.streamType == EMediaDefines.EMediaStreamType.EMSTREAM_TYPE_DESKTOP) {\n StreamItem item0 = streamItemList.get(0);\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = item0.videoView;\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n }\n }\n });\n }\n\n @Override\n public void onRemoveStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (!streamItemMaps.containsKey(stream.memberName)) {\n return;\n }\n List streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n streamItemMaps.remove(stream.memberName);\n } else if (streamItemList.size() == 1) {\n CustomVideoView videoView = streamItemList.get(0).videoView;\n if (videoView != null) {\n multiVideoView.removeVideoView(videoView);\n }\n streamItemMaps.remove(stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(stream.streamId, null);\n } else if (streamItemList.size() == 2) {\n StreamItem item0 = streamItemList.get(0);\n StreamItem item1 = streamItemList.get(1);\n if (item0.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item1.videoView = item0.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n streamItemList.remove(item0);\n item1.videoView.setLabel(item1.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, item1.videoView.getSurfaceView());\n } else if (item1.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item0.videoView = item1.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, null);\n streamItemList.remove(item1);\n item0.videoView.setLabel(item0.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, item0.videoView.getSurfaceView());\n }\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n });\n }\n\n @Override\n public void onUpdateStream(MediaStream stream) {\n }\n\n @Override\n public void onCallEnd(int reason, String desc) {\n EMLog.d(TAG, \"onCallEnd-reason:\" + reason + \",desc:\" + desc);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n }\n\n @Override\n public void onNotice(CallManager.HMediaNoticeCode code, String arg1, String arg2, Object arg3) {\n switch(code) {\n case HMediaNoticeOpenCameraFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n case HMediaNoticeOpenMicFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n }\n }\n\n public static class StreamItem {\n\n CustomVideoView videoView;\n\n MediaStream stream;\n }\n\n private void stopForegroundService() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n stopService(service);\n }\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n ChatClient.getInstance().callManager().removeDelegate(this);\n if (ringtone != null && ringtone.isPlaying()) {\n ringtone.stop();\n }\n unregisterReceiver(headsetReceiver);\n audioManager.setMode(AudioManager.MODE_NORMAL);\n audioManager.setMicrophoneMute(false);\n releaseHandler();\n }\n\n public String getNickName(String memberName) {\n EMediaEntities.EMediaMember mediaMember = ChatClient.getInstance().callManager().getEMediaMember(memberName);\n if (mediaMember != null && !TextUtils.isEmpty(mediaMember.extension)) {\n try {\n JSONObject jsonObject = new JSONObject(mediaMember.extension);\n return jsonObject.getString(\"nickname\");\n } catch (Exception ignored) {\n }\n }\n return memberName;\n }\n\n protected void openSpeakerOn() {\n try {\n if (!audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(true);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n protected void closeSpeakerOn() {\n try {\n if (audioManager != null) {\n if (audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(false);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == ScreenCaptureManager.RECORD_REQUEST_CODE) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n service.putExtra(\"code\", resultCode);\n service.putExtra(\"data\", data);\n startForegroundService(service);\n } else {\n ChatClient.getInstance().callManager().onActivityResult(requestCode, resultCode, data);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_483", "language": "Java", "task_type": "if_statement", "source_file": "java/github/easemob/kefu-android-demo/app/src/main/java/com/easemob/helpdeskdemo/ui/VideoCallActivity.java", "mask_start_position": 17551, "mask_end_position": 17664, "canonical_solution": "if (videoView != null) {\n multiVideoView.removeVideoView(videoView);\n }", "pre_mask_code": "package com.easemob.helpdeskdemo.ui;\n\nimport android.app.Activity;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.media.AudioManager;\nimport android.media.Ringtone;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.WindowManager;\nimport android.widget.ImageButton;\nimport android.widget.Toast;\nimport com.easemob.helpdeskdemo.Preferences;\nimport com.easemob.helpdeskdemo.R;\nimport com.easemob.helpdeskdemo.widget.BottomRelativeLayout;\nimport com.easemob.helpdeskdemo.widget.CustomVideoContainer;\nimport com.easemob.helpdeskdemo.widget.CustomVideoView;\nimport com.hyphenate.chat.CallManager;\nimport com.hyphenate.chat.ChatClient;\nimport com.hyphenate.chat.MediaStream;\nimport com.hyphenate.helpdesk.easeui.widget.ToastHelper;\nimport com.hyphenate.helpdesk.util.Log;\nimport com.hyphenate.util.EMLog;\nimport com.superrtc.mediamanager.EMediaDefines;\nimport com.superrtc.mediamanager.EMediaEntities;\nimport com.superrtc.mediamanager.ScreenCaptureManager;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n// this class is not used?\npublic class VideoCallActivity extends DemoBaseActivity implements CallManager.CallManagerDelegate {\n\n private static final String TAG = \"call\";\n\n protected final int MSG_CALL_ANSWER = 2;\n\n protected final int MSG_CALL_END = 3;\n\n protected final int MSG_CALL_RELEASE_HANDLER = 4;\n\n protected final int MSG_CALL_SWITCH_CAMERA = 5;\n\n private View rootLayout;\n\n private CustomVideoContainer multiVideoView;\n\n private CustomVideoView localSurfaceView;\n\n private ImageButton ibMinimize;\n\n private Map> streamItemMaps = new HashMap<>();\n\n private BottomRelativeLayout bottomRelativeLayout;\n\n protected AudioManager audioManager;\n\n protected Ringtone ringtone;\n\n private HeadsetReceiver headsetReceiver = new HeadsetReceiver();\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n finish();\n return;\n }\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);\n setContentView(R.layout.activity_call);\n String fromUsername = getIntent().getStringExtra(\"username\");\n audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);\n initViews();\n info(\"conference demo\");\n initListeners();\n ChatClient.getInstance().callManager().addDelegate(this);\n Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);\n audioManager.setMode(AudioManager.MODE_RINGTONE);\n audioManager.setSpeakerphoneOn(true);\n ringtone = RingtoneManager.getRingtone(this, ringUri);\n if (ringtone != null) {\n ringtone.play();\n }\n final int MAKE_CALL_TIMEOUT = 60 * 1000;\n handler.removeCallbacks(timeoutHangup);\n handler.postDelayed(timeoutHangup, MAKE_CALL_TIMEOUT);\n registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));\n }\n\n private String getSelfNick() {\n String nickName = Preferences.getInstance().getNickName();\n if (TextUtils.isEmpty(nickName)) {\n nickName = ChatClient.getInstance().currentUserName();\n }\n return nickName;\n }\n\n class HeadsetReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n switch(action) {\n // 插入和拔出耳机会触发广播\n case Intent.ACTION_HEADSET_PLUG:\n int state = intent.getIntExtra(\"state\", 0);\n if (state == 1) {\n // 耳机已插入\n closeSpeakerOn();\n } else if (state == 0) {\n // 耳机已拔出\n openSpeakerOn();\n }\n break;\n }\n }\n }\n\n HandlerThread callHandlerThread = new HandlerThread(\"callHandlerThread\");\n\n {\n callHandlerThread.start();\n }\n\n protected Handler handler = new Handler(callHandlerThread.getLooper()) {\n\n @Override\n public void handleMessage(android.os.Message msg) {\n EMLog.d(TAG, \"handleMessage -- enter block -- msg.what: \" + msg.what);\n switch(msg.what) {\n case MSG_CALL_ANSWER:\n EMLog.d(TAG, \"MSG_CALL_ANSWER\");\n handler.removeCallbacks(timeoutHangup);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n openSpeakerOn();\n bottomRelativeLayout.startChronometer();\n bottomRelativeLayout.setCallStateText(getString(R.string.tip_multi_video_calling));\n ChatClient.getInstance().callManager().acceptCall(getSelfNick(), new com.hyphenate.helpdesk.callback.Callback() {\n\n @Override\n public void onSuccess() {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n bottomRelativeLayout.setControllerButtonsVisibile(true);\n localSurfaceView = addViewToMultiLayout(null);\n localSurfaceView.setLabel(getSelfNick());\n ChatClient.getInstance().callManager().setLocalView(localSurfaceView.getSurfaceView());\n }\n });\n }\n\n @Override\n public void onError(int code, final String error) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ToastHelper.show(getBaseContext(), \"Publish Failed:\" + error);\n }\n });\n }\n\n @Override\n public void onProgress(int progress, String status) {\n }\n });\n }\n });\n break;\n case MSG_CALL_END:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n break;\n case MSG_CALL_RELEASE_HANDLER:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n info(\"click hangup\");\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n handler.removeCallbacks(timeoutHangup);\n handler.removeMessages(MSG_CALL_ANSWER);\n handler.removeMessages(MSG_CALL_END);\n callHandlerThread.quit();\n }\n });\n break;\n case MSG_CALL_SWITCH_CAMERA:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ChatClient.getInstance().callManager().switchCamera();\n }\n });\n break;\n default:\n break;\n }\n }\n };\n\n void releaseHandler() {\n handler.sendEmptyMessage(MSG_CALL_RELEASE_HANDLER);\n }\n\n Runnable timeoutHangup = new Runnable() {\n\n @Override\n public void run() {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n };\n\n @Override\n public void onBackPressed() {\n handler.sendEmptyMessage(MSG_CALL_END);\n finish();\n super.onBackPressed();\n }\n\n private CustomVideoView addViewToMultiLayout(String streamId) {\n final CustomVideoView item = new CustomVideoView(this);\n item.setTag(streamId);\n multiVideoView.addView(item);\n return item;\n }\n\n private void initListeners() {\n bottomRelativeLayout.setAnswerOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_ANSWER);\n }\n });\n bottomRelativeLayout.setHangUpOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n });\n bottomRelativeLayout.setLocalVideoOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().pauseVideo();\n localSurfaceView.setSurfaceViewVisible(false);\n } else {\n ChatClient.getInstance().callManager().resumeVideo();\n localSurfaceView.setSurfaceViewVisible(true);\n }\n }\n });\n bottomRelativeLayout.setMuteOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().resumeVoice();\n } else {\n ChatClient.getInstance().callManager().pauseVoice();\n }\n }\n });\n bottomRelativeLayout.setSwitchCameraOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_SWITCH_CAMERA);\n }\n });\n bottomRelativeLayout.setSpeakerOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n closeSpeakerOn();\n } else {\n openSpeakerOn();\n }\n }\n });\n bottomRelativeLayout.setSharedWindowOnClickListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().publishWindow(VideoCallActivity.this, null);\n } else {\n ChatClient.getInstance().callManager().unPublishWindow(null);\n stopForegroundService();\n }\n }\n });\n multiVideoView.setOnMaxVideoChangeListener(new CustomVideoContainer.OnMaxVideoChangeListener() {\n\n @Override\n public void onChanged(boolean isMax) {\n bottomRelativeLayout.setMaxScreenState(isMax);\n ibMinimize.setVisibility(isMax ? View.VISIBLE : View.GONE);\n }\n });\n ibMinimize.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n ibMinimize.setVisibility(View.GONE);\n multiVideoView.minimizeChildView();\n bottomRelativeLayout.setMaxScreenState(false);\n }\n });\n }\n\n private void initViews() {\n ibMinimize = (ImageButton) findViewById(R.id.ib_minimize);\n ibMinimize.setVisibility(View.GONE);\n multiVideoView = (CustomVideoContainer) findViewById(R.id.multi_view_container);\n bottomRelativeLayout = (BottomRelativeLayout) findViewById(R.id.bottom_relative);\n rootLayout = findViewById(R.id.root_layout);\n bottomRelativeLayout.setAgentNick(ChatClient.getInstance().callManager().getCallNickName());\n }\n\n private boolean firstChanged = true;\n\n @Override\n public void onWindowFocusChanged(boolean hasFocus) {\n super.onWindowFocusChanged(hasFocus);\n if (firstChanged) {\n firstChanged = false;\n ViewGroup.LayoutParams layoutParams = bottomRelativeLayout.getLayoutParams();\n layoutParams.height = rootLayout.getHeight() - multiVideoView.getHeight();\n bottomRelativeLayout.setLayoutParams(layoutParams);\n }\n }\n\n private void info(String msg) {\n Log.d(TAG, \"\" + msg);\n }\n\n @Override\n public void onAddStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n List streamItemList;\n if (!streamItemMaps.containsKey(stream.memberName)) {\n streamItemList = new ArrayList<>();\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n streamItemMaps.put(stream.memberName, streamItemList);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n } else {\n streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n } else if (streamItemList.size() == 1) {\n if (stream.streamType == EMediaDefines.EMediaStreamType.EMSTREAM_TYPE_DESKTOP) {\n StreamItem item0 = streamItemList.get(0);\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = item0.videoView;\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n }\n }\n });\n }\n\n @Override\n public void onRemoveStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (!streamItemMaps.containsKey(stream.memberName)) {\n return;\n }\n List streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n streamItemMaps.remove(stream.memberName);\n } else if (streamItemList.size() == 1) {\n CustomVideoView videoView = streamItemList.get(0).videoView;\n ", "post_mask_code": "\n streamItemMaps.remove(stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(stream.streamId, null);\n } else if (streamItemList.size() == 2) {\n StreamItem item0 = streamItemList.get(0);\n StreamItem item1 = streamItemList.get(1);\n if (item0.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item1.videoView = item0.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n streamItemList.remove(item0);\n item1.videoView.setLabel(item1.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, item1.videoView.getSurfaceView());\n } else if (item1.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item0.videoView = item1.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, null);\n streamItemList.remove(item1);\n item0.videoView.setLabel(item0.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, item0.videoView.getSurfaceView());\n }\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n });\n }\n\n @Override\n public void onUpdateStream(MediaStream stream) {\n }\n\n @Override\n public void onCallEnd(int reason, String desc) {\n EMLog.d(TAG, \"onCallEnd-reason:\" + reason + \",desc:\" + desc);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n }\n\n @Override\n public void onNotice(CallManager.HMediaNoticeCode code, String arg1, String arg2, Object arg3) {\n switch(code) {\n case HMediaNoticeOpenCameraFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n case HMediaNoticeOpenMicFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n }\n }\n\n public static class StreamItem {\n\n CustomVideoView videoView;\n\n MediaStream stream;\n }\n\n private void stopForegroundService() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n stopService(service);\n }\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n ChatClient.getInstance().callManager().removeDelegate(this);\n if (ringtone != null && ringtone.isPlaying()) {\n ringtone.stop();\n }\n unregisterReceiver(headsetReceiver);\n audioManager.setMode(AudioManager.MODE_NORMAL);\n audioManager.setMicrophoneMute(false);\n releaseHandler();\n }\n\n public String getNickName(String memberName) {\n EMediaEntities.EMediaMember mediaMember = ChatClient.getInstance().callManager().getEMediaMember(memberName);\n if (mediaMember != null && !TextUtils.isEmpty(mediaMember.extension)) {\n try {\n JSONObject jsonObject = new JSONObject(mediaMember.extension);\n return jsonObject.getString(\"nickname\");\n } catch (Exception ignored) {\n }\n }\n return memberName;\n }\n\n protected void openSpeakerOn() {\n try {\n if (!audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(true);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n protected void closeSpeakerOn() {\n try {\n if (audioManager != null) {\n if (audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(false);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == ScreenCaptureManager.RECORD_REQUEST_CODE) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n service.putExtra(\"code\", resultCode);\n service.putExtra(\"data\", data);\n startForegroundService(service);\n } else {\n ChatClient.getInstance().callManager().onActivityResult(requestCode, resultCode, data);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_484", "language": "Java", "task_type": "switch_case", "source_file": "java/github/easemob/kefu-android-demo/app/src/main/java/com/easemob/helpdeskdemo/ui/VideoCallActivity.java", "mask_start_position": 4085, "mask_end_position": 4541, "canonical_solution": "switch(action) {\n // 插入和拔出耳机会触发广播\n case Intent.ACTION_HEADSET_PLUG:\n int state = intent.getIntExtra(\"state\", 0);\n if (state == 1) {\n // 耳机已插入\n closeSpeakerOn();\n } else if (state == 0) {\n // 耳机已拔出\n openSpeakerOn();\n }\n break;\n }", "pre_mask_code": "package com.easemob.helpdeskdemo.ui;\n\nimport android.app.Activity;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.media.AudioManager;\nimport android.media.Ringtone;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.WindowManager;\nimport android.widget.ImageButton;\nimport android.widget.Toast;\nimport com.easemob.helpdeskdemo.Preferences;\nimport com.easemob.helpdeskdemo.R;\nimport com.easemob.helpdeskdemo.widget.BottomRelativeLayout;\nimport com.easemob.helpdeskdemo.widget.CustomVideoContainer;\nimport com.easemob.helpdeskdemo.widget.CustomVideoView;\nimport com.hyphenate.chat.CallManager;\nimport com.hyphenate.chat.ChatClient;\nimport com.hyphenate.chat.MediaStream;\nimport com.hyphenate.helpdesk.easeui.widget.ToastHelper;\nimport com.hyphenate.helpdesk.util.Log;\nimport com.hyphenate.util.EMLog;\nimport com.superrtc.mediamanager.EMediaDefines;\nimport com.superrtc.mediamanager.EMediaEntities;\nimport com.superrtc.mediamanager.ScreenCaptureManager;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n// this class is not used?\npublic class VideoCallActivity extends DemoBaseActivity implements CallManager.CallManagerDelegate {\n\n private static final String TAG = \"call\";\n\n protected final int MSG_CALL_ANSWER = 2;\n\n protected final int MSG_CALL_END = 3;\n\n protected final int MSG_CALL_RELEASE_HANDLER = 4;\n\n protected final int MSG_CALL_SWITCH_CAMERA = 5;\n\n private View rootLayout;\n\n private CustomVideoContainer multiVideoView;\n\n private CustomVideoView localSurfaceView;\n\n private ImageButton ibMinimize;\n\n private Map> streamItemMaps = new HashMap<>();\n\n private BottomRelativeLayout bottomRelativeLayout;\n\n protected AudioManager audioManager;\n\n protected Ringtone ringtone;\n\n private HeadsetReceiver headsetReceiver = new HeadsetReceiver();\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n finish();\n return;\n }\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);\n setContentView(R.layout.activity_call);\n String fromUsername = getIntent().getStringExtra(\"username\");\n audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);\n initViews();\n info(\"conference demo\");\n initListeners();\n ChatClient.getInstance().callManager().addDelegate(this);\n Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);\n audioManager.setMode(AudioManager.MODE_RINGTONE);\n audioManager.setSpeakerphoneOn(true);\n ringtone = RingtoneManager.getRingtone(this, ringUri);\n if (ringtone != null) {\n ringtone.play();\n }\n final int MAKE_CALL_TIMEOUT = 60 * 1000;\n handler.removeCallbacks(timeoutHangup);\n handler.postDelayed(timeoutHangup, MAKE_CALL_TIMEOUT);\n registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));\n }\n\n private String getSelfNick() {\n String nickName = Preferences.getInstance().getNickName();\n if (TextUtils.isEmpty(nickName)) {\n nickName = ChatClient.getInstance().currentUserName();\n }\n return nickName;\n }\n\n class HeadsetReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n ", "post_mask_code": "\n }\n }\n\n HandlerThread callHandlerThread = new HandlerThread(\"callHandlerThread\");\n\n {\n callHandlerThread.start();\n }\n\n protected Handler handler = new Handler(callHandlerThread.getLooper()) {\n\n @Override\n public void handleMessage(android.os.Message msg) {\n EMLog.d(TAG, \"handleMessage -- enter block -- msg.what: \" + msg.what);\n switch(msg.what) {\n case MSG_CALL_ANSWER:\n EMLog.d(TAG, \"MSG_CALL_ANSWER\");\n handler.removeCallbacks(timeoutHangup);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n openSpeakerOn();\n bottomRelativeLayout.startChronometer();\n bottomRelativeLayout.setCallStateText(getString(R.string.tip_multi_video_calling));\n ChatClient.getInstance().callManager().acceptCall(getSelfNick(), new com.hyphenate.helpdesk.callback.Callback() {\n\n @Override\n public void onSuccess() {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n bottomRelativeLayout.setControllerButtonsVisibile(true);\n localSurfaceView = addViewToMultiLayout(null);\n localSurfaceView.setLabel(getSelfNick());\n ChatClient.getInstance().callManager().setLocalView(localSurfaceView.getSurfaceView());\n }\n });\n }\n\n @Override\n public void onError(int code, final String error) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ToastHelper.show(getBaseContext(), \"Publish Failed:\" + error);\n }\n });\n }\n\n @Override\n public void onProgress(int progress, String status) {\n }\n });\n }\n });\n break;\n case MSG_CALL_END:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n break;\n case MSG_CALL_RELEASE_HANDLER:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n info(\"click hangup\");\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n handler.removeCallbacks(timeoutHangup);\n handler.removeMessages(MSG_CALL_ANSWER);\n handler.removeMessages(MSG_CALL_END);\n callHandlerThread.quit();\n }\n });\n break;\n case MSG_CALL_SWITCH_CAMERA:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ChatClient.getInstance().callManager().switchCamera();\n }\n });\n break;\n default:\n break;\n }\n }\n };\n\n void releaseHandler() {\n handler.sendEmptyMessage(MSG_CALL_RELEASE_HANDLER);\n }\n\n Runnable timeoutHangup = new Runnable() {\n\n @Override\n public void run() {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n };\n\n @Override\n public void onBackPressed() {\n handler.sendEmptyMessage(MSG_CALL_END);\n finish();\n super.onBackPressed();\n }\n\n private CustomVideoView addViewToMultiLayout(String streamId) {\n final CustomVideoView item = new CustomVideoView(this);\n item.setTag(streamId);\n multiVideoView.addView(item);\n return item;\n }\n\n private void initListeners() {\n bottomRelativeLayout.setAnswerOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_ANSWER);\n }\n });\n bottomRelativeLayout.setHangUpOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n });\n bottomRelativeLayout.setLocalVideoOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().pauseVideo();\n localSurfaceView.setSurfaceViewVisible(false);\n } else {\n ChatClient.getInstance().callManager().resumeVideo();\n localSurfaceView.setSurfaceViewVisible(true);\n }\n }\n });\n bottomRelativeLayout.setMuteOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().resumeVoice();\n } else {\n ChatClient.getInstance().callManager().pauseVoice();\n }\n }\n });\n bottomRelativeLayout.setSwitchCameraOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_SWITCH_CAMERA);\n }\n });\n bottomRelativeLayout.setSpeakerOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n closeSpeakerOn();\n } else {\n openSpeakerOn();\n }\n }\n });\n bottomRelativeLayout.setSharedWindowOnClickListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().publishWindow(VideoCallActivity.this, null);\n } else {\n ChatClient.getInstance().callManager().unPublishWindow(null);\n stopForegroundService();\n }\n }\n });\n multiVideoView.setOnMaxVideoChangeListener(new CustomVideoContainer.OnMaxVideoChangeListener() {\n\n @Override\n public void onChanged(boolean isMax) {\n bottomRelativeLayout.setMaxScreenState(isMax);\n ibMinimize.setVisibility(isMax ? View.VISIBLE : View.GONE);\n }\n });\n ibMinimize.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n ibMinimize.setVisibility(View.GONE);\n multiVideoView.minimizeChildView();\n bottomRelativeLayout.setMaxScreenState(false);\n }\n });\n }\n\n private void initViews() {\n ibMinimize = (ImageButton) findViewById(R.id.ib_minimize);\n ibMinimize.setVisibility(View.GONE);\n multiVideoView = (CustomVideoContainer) findViewById(R.id.multi_view_container);\n bottomRelativeLayout = (BottomRelativeLayout) findViewById(R.id.bottom_relative);\n rootLayout = findViewById(R.id.root_layout);\n bottomRelativeLayout.setAgentNick(ChatClient.getInstance().callManager().getCallNickName());\n }\n\n private boolean firstChanged = true;\n\n @Override\n public void onWindowFocusChanged(boolean hasFocus) {\n super.onWindowFocusChanged(hasFocus);\n if (firstChanged) {\n firstChanged = false;\n ViewGroup.LayoutParams layoutParams = bottomRelativeLayout.getLayoutParams();\n layoutParams.height = rootLayout.getHeight() - multiVideoView.getHeight();\n bottomRelativeLayout.setLayoutParams(layoutParams);\n }\n }\n\n private void info(String msg) {\n Log.d(TAG, \"\" + msg);\n }\n\n @Override\n public void onAddStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n List streamItemList;\n if (!streamItemMaps.containsKey(stream.memberName)) {\n streamItemList = new ArrayList<>();\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n streamItemMaps.put(stream.memberName, streamItemList);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n } else {\n streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n } else if (streamItemList.size() == 1) {\n if (stream.streamType == EMediaDefines.EMediaStreamType.EMSTREAM_TYPE_DESKTOP) {\n StreamItem item0 = streamItemList.get(0);\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = item0.videoView;\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n }\n }\n });\n }\n\n @Override\n public void onRemoveStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (!streamItemMaps.containsKey(stream.memberName)) {\n return;\n }\n List streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n streamItemMaps.remove(stream.memberName);\n } else if (streamItemList.size() == 1) {\n CustomVideoView videoView = streamItemList.get(0).videoView;\n if (videoView != null) {\n multiVideoView.removeVideoView(videoView);\n }\n streamItemMaps.remove(stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(stream.streamId, null);\n } else if (streamItemList.size() == 2) {\n StreamItem item0 = streamItemList.get(0);\n StreamItem item1 = streamItemList.get(1);\n if (item0.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item1.videoView = item0.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n streamItemList.remove(item0);\n item1.videoView.setLabel(item1.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, item1.videoView.getSurfaceView());\n } else if (item1.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item0.videoView = item1.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, null);\n streamItemList.remove(item1);\n item0.videoView.setLabel(item0.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, item0.videoView.getSurfaceView());\n }\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n });\n }\n\n @Override\n public void onUpdateStream(MediaStream stream) {\n }\n\n @Override\n public void onCallEnd(int reason, String desc) {\n EMLog.d(TAG, \"onCallEnd-reason:\" + reason + \",desc:\" + desc);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n }\n\n @Override\n public void onNotice(CallManager.HMediaNoticeCode code, String arg1, String arg2, Object arg3) {\n switch(code) {\n case HMediaNoticeOpenCameraFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n case HMediaNoticeOpenMicFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n }\n }\n\n public static class StreamItem {\n\n CustomVideoView videoView;\n\n MediaStream stream;\n }\n\n private void stopForegroundService() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n stopService(service);\n }\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n ChatClient.getInstance().callManager().removeDelegate(this);\n if (ringtone != null && ringtone.isPlaying()) {\n ringtone.stop();\n }\n unregisterReceiver(headsetReceiver);\n audioManager.setMode(AudioManager.MODE_NORMAL);\n audioManager.setMicrophoneMute(false);\n releaseHandler();\n }\n\n public String getNickName(String memberName) {\n EMediaEntities.EMediaMember mediaMember = ChatClient.getInstance().callManager().getEMediaMember(memberName);\n if (mediaMember != null && !TextUtils.isEmpty(mediaMember.extension)) {\n try {\n JSONObject jsonObject = new JSONObject(mediaMember.extension);\n return jsonObject.getString(\"nickname\");\n } catch (Exception ignored) {\n }\n }\n return memberName;\n }\n\n protected void openSpeakerOn() {\n try {\n if (!audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(true);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n protected void closeSpeakerOn() {\n try {\n if (audioManager != null) {\n if (audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(false);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == ScreenCaptureManager.RECORD_REQUEST_CODE) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n service.putExtra(\"code\", resultCode);\n service.putExtra(\"data\", data);\n startForegroundService(service);\n } else {\n ChatClient.getInstance().callManager().onActivityResult(requestCode, resultCode, data);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_485", "language": "Java", "task_type": "try_statement", "source_file": "java/github/easemob/kefu-android-demo/app/src/main/java/com/easemob/helpdeskdemo/ui/VideoCallActivity.java", "mask_start_position": 21634, "mask_end_position": 21904, "canonical_solution": "try {\n if (!audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(true);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n } catch (Exception e) {\n e.printStackTrace();\n }", "pre_mask_code": "package com.easemob.helpdeskdemo.ui;\n\nimport android.app.Activity;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.media.AudioManager;\nimport android.media.Ringtone;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.WindowManager;\nimport android.widget.ImageButton;\nimport android.widget.Toast;\nimport com.easemob.helpdeskdemo.Preferences;\nimport com.easemob.helpdeskdemo.R;\nimport com.easemob.helpdeskdemo.widget.BottomRelativeLayout;\nimport com.easemob.helpdeskdemo.widget.CustomVideoContainer;\nimport com.easemob.helpdeskdemo.widget.CustomVideoView;\nimport com.hyphenate.chat.CallManager;\nimport com.hyphenate.chat.ChatClient;\nimport com.hyphenate.chat.MediaStream;\nimport com.hyphenate.helpdesk.easeui.widget.ToastHelper;\nimport com.hyphenate.helpdesk.util.Log;\nimport com.hyphenate.util.EMLog;\nimport com.superrtc.mediamanager.EMediaDefines;\nimport com.superrtc.mediamanager.EMediaEntities;\nimport com.superrtc.mediamanager.ScreenCaptureManager;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n// this class is not used?\npublic class VideoCallActivity extends DemoBaseActivity implements CallManager.CallManagerDelegate {\n\n private static final String TAG = \"call\";\n\n protected final int MSG_CALL_ANSWER = 2;\n\n protected final int MSG_CALL_END = 3;\n\n protected final int MSG_CALL_RELEASE_HANDLER = 4;\n\n protected final int MSG_CALL_SWITCH_CAMERA = 5;\n\n private View rootLayout;\n\n private CustomVideoContainer multiVideoView;\n\n private CustomVideoView localSurfaceView;\n\n private ImageButton ibMinimize;\n\n private Map> streamItemMaps = new HashMap<>();\n\n private BottomRelativeLayout bottomRelativeLayout;\n\n protected AudioManager audioManager;\n\n protected Ringtone ringtone;\n\n private HeadsetReceiver headsetReceiver = new HeadsetReceiver();\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n finish();\n return;\n }\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);\n setContentView(R.layout.activity_call);\n String fromUsername = getIntent().getStringExtra(\"username\");\n audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);\n initViews();\n info(\"conference demo\");\n initListeners();\n ChatClient.getInstance().callManager().addDelegate(this);\n Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);\n audioManager.setMode(AudioManager.MODE_RINGTONE);\n audioManager.setSpeakerphoneOn(true);\n ringtone = RingtoneManager.getRingtone(this, ringUri);\n if (ringtone != null) {\n ringtone.play();\n }\n final int MAKE_CALL_TIMEOUT = 60 * 1000;\n handler.removeCallbacks(timeoutHangup);\n handler.postDelayed(timeoutHangup, MAKE_CALL_TIMEOUT);\n registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));\n }\n\n private String getSelfNick() {\n String nickName = Preferences.getInstance().getNickName();\n if (TextUtils.isEmpty(nickName)) {\n nickName = ChatClient.getInstance().currentUserName();\n }\n return nickName;\n }\n\n class HeadsetReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n switch(action) {\n // 插入和拔出耳机会触发广播\n case Intent.ACTION_HEADSET_PLUG:\n int state = intent.getIntExtra(\"state\", 0);\n if (state == 1) {\n // 耳机已插入\n closeSpeakerOn();\n } else if (state == 0) {\n // 耳机已拔出\n openSpeakerOn();\n }\n break;\n }\n }\n }\n\n HandlerThread callHandlerThread = new HandlerThread(\"callHandlerThread\");\n\n {\n callHandlerThread.start();\n }\n\n protected Handler handler = new Handler(callHandlerThread.getLooper()) {\n\n @Override\n public void handleMessage(android.os.Message msg) {\n EMLog.d(TAG, \"handleMessage -- enter block -- msg.what: \" + msg.what);\n switch(msg.what) {\n case MSG_CALL_ANSWER:\n EMLog.d(TAG, \"MSG_CALL_ANSWER\");\n handler.removeCallbacks(timeoutHangup);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n openSpeakerOn();\n bottomRelativeLayout.startChronometer();\n bottomRelativeLayout.setCallStateText(getString(R.string.tip_multi_video_calling));\n ChatClient.getInstance().callManager().acceptCall(getSelfNick(), new com.hyphenate.helpdesk.callback.Callback() {\n\n @Override\n public void onSuccess() {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n bottomRelativeLayout.setControllerButtonsVisibile(true);\n localSurfaceView = addViewToMultiLayout(null);\n localSurfaceView.setLabel(getSelfNick());\n ChatClient.getInstance().callManager().setLocalView(localSurfaceView.getSurfaceView());\n }\n });\n }\n\n @Override\n public void onError(int code, final String error) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ToastHelper.show(getBaseContext(), \"Publish Failed:\" + error);\n }\n });\n }\n\n @Override\n public void onProgress(int progress, String status) {\n }\n });\n }\n });\n break;\n case MSG_CALL_END:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n break;\n case MSG_CALL_RELEASE_HANDLER:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n info(\"click hangup\");\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n handler.removeCallbacks(timeoutHangup);\n handler.removeMessages(MSG_CALL_ANSWER);\n handler.removeMessages(MSG_CALL_END);\n callHandlerThread.quit();\n }\n });\n break;\n case MSG_CALL_SWITCH_CAMERA:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ChatClient.getInstance().callManager().switchCamera();\n }\n });\n break;\n default:\n break;\n }\n }\n };\n\n void releaseHandler() {\n handler.sendEmptyMessage(MSG_CALL_RELEASE_HANDLER);\n }\n\n Runnable timeoutHangup = new Runnable() {\n\n @Override\n public void run() {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n };\n\n @Override\n public void onBackPressed() {\n handler.sendEmptyMessage(MSG_CALL_END);\n finish();\n super.onBackPressed();\n }\n\n private CustomVideoView addViewToMultiLayout(String streamId) {\n final CustomVideoView item = new CustomVideoView(this);\n item.setTag(streamId);\n multiVideoView.addView(item);\n return item;\n }\n\n private void initListeners() {\n bottomRelativeLayout.setAnswerOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_ANSWER);\n }\n });\n bottomRelativeLayout.setHangUpOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n });\n bottomRelativeLayout.setLocalVideoOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().pauseVideo();\n localSurfaceView.setSurfaceViewVisible(false);\n } else {\n ChatClient.getInstance().callManager().resumeVideo();\n localSurfaceView.setSurfaceViewVisible(true);\n }\n }\n });\n bottomRelativeLayout.setMuteOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().resumeVoice();\n } else {\n ChatClient.getInstance().callManager().pauseVoice();\n }\n }\n });\n bottomRelativeLayout.setSwitchCameraOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_SWITCH_CAMERA);\n }\n });\n bottomRelativeLayout.setSpeakerOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n closeSpeakerOn();\n } else {\n openSpeakerOn();\n }\n }\n });\n bottomRelativeLayout.setSharedWindowOnClickListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().publishWindow(VideoCallActivity.this, null);\n } else {\n ChatClient.getInstance().callManager().unPublishWindow(null);\n stopForegroundService();\n }\n }\n });\n multiVideoView.setOnMaxVideoChangeListener(new CustomVideoContainer.OnMaxVideoChangeListener() {\n\n @Override\n public void onChanged(boolean isMax) {\n bottomRelativeLayout.setMaxScreenState(isMax);\n ibMinimize.setVisibility(isMax ? View.VISIBLE : View.GONE);\n }\n });\n ibMinimize.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n ibMinimize.setVisibility(View.GONE);\n multiVideoView.minimizeChildView();\n bottomRelativeLayout.setMaxScreenState(false);\n }\n });\n }\n\n private void initViews() {\n ibMinimize = (ImageButton) findViewById(R.id.ib_minimize);\n ibMinimize.setVisibility(View.GONE);\n multiVideoView = (CustomVideoContainer) findViewById(R.id.multi_view_container);\n bottomRelativeLayout = (BottomRelativeLayout) findViewById(R.id.bottom_relative);\n rootLayout = findViewById(R.id.root_layout);\n bottomRelativeLayout.setAgentNick(ChatClient.getInstance().callManager().getCallNickName());\n }\n\n private boolean firstChanged = true;\n\n @Override\n public void onWindowFocusChanged(boolean hasFocus) {\n super.onWindowFocusChanged(hasFocus);\n if (firstChanged) {\n firstChanged = false;\n ViewGroup.LayoutParams layoutParams = bottomRelativeLayout.getLayoutParams();\n layoutParams.height = rootLayout.getHeight() - multiVideoView.getHeight();\n bottomRelativeLayout.setLayoutParams(layoutParams);\n }\n }\n\n private void info(String msg) {\n Log.d(TAG, \"\" + msg);\n }\n\n @Override\n public void onAddStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n List streamItemList;\n if (!streamItemMaps.containsKey(stream.memberName)) {\n streamItemList = new ArrayList<>();\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n streamItemMaps.put(stream.memberName, streamItemList);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n } else {\n streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n } else if (streamItemList.size() == 1) {\n if (stream.streamType == EMediaDefines.EMediaStreamType.EMSTREAM_TYPE_DESKTOP) {\n StreamItem item0 = streamItemList.get(0);\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = item0.videoView;\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n }\n }\n });\n }\n\n @Override\n public void onRemoveStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (!streamItemMaps.containsKey(stream.memberName)) {\n return;\n }\n List streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n streamItemMaps.remove(stream.memberName);\n } else if (streamItemList.size() == 1) {\n CustomVideoView videoView = streamItemList.get(0).videoView;\n if (videoView != null) {\n multiVideoView.removeVideoView(videoView);\n }\n streamItemMaps.remove(stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(stream.streamId, null);\n } else if (streamItemList.size() == 2) {\n StreamItem item0 = streamItemList.get(0);\n StreamItem item1 = streamItemList.get(1);\n if (item0.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item1.videoView = item0.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n streamItemList.remove(item0);\n item1.videoView.setLabel(item1.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, item1.videoView.getSurfaceView());\n } else if (item1.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item0.videoView = item1.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, null);\n streamItemList.remove(item1);\n item0.videoView.setLabel(item0.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, item0.videoView.getSurfaceView());\n }\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n });\n }\n\n @Override\n public void onUpdateStream(MediaStream stream) {\n }\n\n @Override\n public void onCallEnd(int reason, String desc) {\n EMLog.d(TAG, \"onCallEnd-reason:\" + reason + \",desc:\" + desc);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n }\n\n @Override\n public void onNotice(CallManager.HMediaNoticeCode code, String arg1, String arg2, Object arg3) {\n switch(code) {\n case HMediaNoticeOpenCameraFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n case HMediaNoticeOpenMicFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n }\n }\n\n public static class StreamItem {\n\n CustomVideoView videoView;\n\n MediaStream stream;\n }\n\n private void stopForegroundService() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n stopService(service);\n }\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n ChatClient.getInstance().callManager().removeDelegate(this);\n if (ringtone != null && ringtone.isPlaying()) {\n ringtone.stop();\n }\n unregisterReceiver(headsetReceiver);\n audioManager.setMode(AudioManager.MODE_NORMAL);\n audioManager.setMicrophoneMute(false);\n releaseHandler();\n }\n\n public String getNickName(String memberName) {\n EMediaEntities.EMediaMember mediaMember = ChatClient.getInstance().callManager().getEMediaMember(memberName);\n if (mediaMember != null && !TextUtils.isEmpty(mediaMember.extension)) {\n try {\n JSONObject jsonObject = new JSONObject(mediaMember.extension);\n return jsonObject.getString(\"nickname\");\n } catch (Exception ignored) {\n }\n }\n return memberName;\n }\n\n protected void openSpeakerOn() {\n ", "post_mask_code": "\n }\n\n protected void closeSpeakerOn() {\n try {\n if (audioManager != null) {\n if (audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(false);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == ScreenCaptureManager.RECORD_REQUEST_CODE) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n service.putExtra(\"code\", resultCode);\n service.putExtra(\"data\", data);\n startForegroundService(service);\n } else {\n ChatClient.getInstance().callManager().onActivityResult(requestCode, resultCode, data);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_486", "language": "Java", "task_type": "empty", "source_file": "java/github/easemob/kefu-android-demo/app/src/main/java/com/easemob/helpdeskdemo/ui/VideoCallActivity.java", "mask_start_position": 7860, "mask_end_position": 7860, "canonical_solution": "", "pre_mask_code": "package com.easemob.helpdeskdemo.ui;\n\nimport android.app.Activity;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.media.AudioManager;\nimport android.media.Ringtone;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.WindowManager;\nimport android.widget.ImageButton;\nimport android.widget.Toast;\nimport com.easemob.helpdeskdemo.Preferences;\nimport com.easemob.helpdeskdemo.R;\nimport com.easemob.helpdeskdemo.widget.BottomRelativeLayout;\nimport com.easemob.helpdeskdemo.widget.CustomVideoContainer;\nimport com.easemob.helpdeskdemo.widget.CustomVideoView;\nimport com.hyphenate.chat.CallManager;\nimport com.hyphenate.chat.ChatClient;\nimport com.hyphenate.chat.MediaStream;\nimport com.hyphenate.helpdesk.easeui.widget.ToastHelper;\nimport com.hyphenate.helpdesk.util.Log;\nimport com.hyphenate.util.EMLog;\nimport com.superrtc.mediamanager.EMediaDefines;\nimport com.superrtc.mediamanager.EMediaEntities;\nimport com.superrtc.mediamanager.ScreenCaptureManager;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n// this class is not used?\npublic class VideoCallActivity extends DemoBaseActivity implements CallManager.CallManagerDelegate {\n\n private static final String TAG = \"call\";\n\n protected final int MSG_CALL_ANSWER = 2;\n\n protected final int MSG_CALL_END = 3;\n\n protected final int MSG_CALL_RELEASE_HANDLER = 4;\n\n protected final int MSG_CALL_SWITCH_CAMERA = 5;\n\n private View rootLayout;\n\n private CustomVideoContainer multiVideoView;\n\n private CustomVideoView localSurfaceView;\n\n private ImageButton ibMinimize;\n\n private Map> streamItemMaps = new HashMap<>();\n\n private BottomRelativeLayout bottomRelativeLayout;\n\n protected AudioManager audioManager;\n\n protected Ringtone ringtone;\n\n private HeadsetReceiver headsetReceiver = new HeadsetReceiver();\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n finish();\n return;\n }\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);\n setContentView(R.layout.activity_call);\n String fromUsername = getIntent().getStringExtra(\"username\");\n audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);\n initViews();\n info(\"conference demo\");\n initListeners();\n ChatClient.getInstance().callManager().addDelegate(this);\n Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);\n audioManager.setMode(AudioManager.MODE_RINGTONE);\n audioManager.setSpeakerphoneOn(true);\n ringtone = RingtoneManager.getRingtone(this, ringUri);\n if (ringtone != null) {\n ringtone.play();\n }\n final int MAKE_CALL_TIMEOUT = 60 * 1000;\n handler.removeCallbacks(timeoutHangup);\n handler.postDelayed(timeoutHangup, MAKE_CALL_TIMEOUT);\n registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));\n }\n\n private String getSelfNick() {\n String nickName = Preferences.getInstance().getNickName();\n if (TextUtils.isEmpty(nickName)) {\n nickName = ChatClient.getInstance().currentUserName();\n }\n return nickName;\n }\n\n class HeadsetReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n switch(action) {\n // 插入和拔出耳机会触发广播\n case Intent.ACTION_HEADSET_PLUG:\n int state = intent.getIntExtra(\"state\", 0);\n if (state == 1) {\n // 耳机已插入\n closeSpeakerOn();\n } else if (state == 0) {\n // 耳机已拔出\n openSpeakerOn();\n }\n break;\n }\n }\n }\n\n HandlerThread callHandlerThread = new HandlerThread(\"callHandlerThread\");\n\n {\n callHandlerThread.start();\n }\n\n protected Handler handler = new Handler(callHandlerThread.getLooper()) {\n\n @Override\n public void handleMessage(android.os.Message msg) {\n EMLog.d(TAG, \"handleMessage -- enter block -- msg.what: \" + msg.what);\n switch(msg.what) {\n case MSG_CALL_ANSWER:\n EMLog.d(TAG, \"MSG_CALL_ANSWER\");\n handler.removeCallbacks(timeoutHangup);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n openSpeakerOn();\n bottomRelativeLayout.startChronometer();\n bottomRelativeLayout.setCallStateText(getString(R.string.tip_multi_video_calling));\n ChatClient.getInstance().callManager().acceptCall(getSelfNick(), new com.hyphenate.helpdesk.callback.Callback() {\n\n @Override\n public void onSuccess() {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n bottomRelativeLayout.setControllerButtonsVisibile(true);\n localSurfaceView = addViewToMultiLayout(null);\n localSurfaceView.setLabel(getSelfNick());\n ChatClient.getInstance().callManager().setLocalView(localSurfaceView.getSurfaceView());\n }\n });\n }\n\n @Override\n public void onError(int code, final String error) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ToastHelper.show(getBaseContext(), \"Publish Failed:\" + error);\n }\n });\n }\n\n @Override\n public void onProgress(int progress, String status) {\n }\n });\n }\n });\n break;\n case MSG_CALL_END:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClien", "post_mask_code": "t.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n break;\n case MSG_CALL_RELEASE_HANDLER:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n info(\"click hangup\");\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n handler.removeCallbacks(timeoutHangup);\n handler.removeMessages(MSG_CALL_ANSWER);\n handler.removeMessages(MSG_CALL_END);\n callHandlerThread.quit();\n }\n });\n break;\n case MSG_CALL_SWITCH_CAMERA:\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ChatClient.getInstance().callManager().switchCamera();\n }\n });\n break;\n default:\n break;\n }\n }\n };\n\n void releaseHandler() {\n handler.sendEmptyMessage(MSG_CALL_RELEASE_HANDLER);\n }\n\n Runnable timeoutHangup = new Runnable() {\n\n @Override\n public void run() {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n };\n\n @Override\n public void onBackPressed() {\n handler.sendEmptyMessage(MSG_CALL_END);\n finish();\n super.onBackPressed();\n }\n\n private CustomVideoView addViewToMultiLayout(String streamId) {\n final CustomVideoView item = new CustomVideoView(this);\n item.setTag(streamId);\n multiVideoView.addView(item);\n return item;\n }\n\n private void initListeners() {\n bottomRelativeLayout.setAnswerOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_ANSWER);\n }\n });\n bottomRelativeLayout.setHangUpOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_END);\n }\n });\n bottomRelativeLayout.setLocalVideoOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().pauseVideo();\n localSurfaceView.setSurfaceViewVisible(false);\n } else {\n ChatClient.getInstance().callManager().resumeVideo();\n localSurfaceView.setSurfaceViewVisible(true);\n }\n }\n });\n bottomRelativeLayout.setMuteOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().resumeVoice();\n } else {\n ChatClient.getInstance().callManager().pauseVoice();\n }\n }\n });\n bottomRelativeLayout.setSwitchCameraOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n handler.sendEmptyMessage(MSG_CALL_SWITCH_CAMERA);\n }\n });\n bottomRelativeLayout.setSpeakerOnCheckedChangeListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n closeSpeakerOn();\n } else {\n openSpeakerOn();\n }\n }\n });\n bottomRelativeLayout.setSharedWindowOnClickListener(new BottomRelativeLayout.OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(View buttonView, boolean isChecked) {\n if (isChecked) {\n ChatClient.getInstance().callManager().publishWindow(VideoCallActivity.this, null);\n } else {\n ChatClient.getInstance().callManager().unPublishWindow(null);\n stopForegroundService();\n }\n }\n });\n multiVideoView.setOnMaxVideoChangeListener(new CustomVideoContainer.OnMaxVideoChangeListener() {\n\n @Override\n public void onChanged(boolean isMax) {\n bottomRelativeLayout.setMaxScreenState(isMax);\n ibMinimize.setVisibility(isMax ? View.VISIBLE : View.GONE);\n }\n });\n ibMinimize.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n ibMinimize.setVisibility(View.GONE);\n multiVideoView.minimizeChildView();\n bottomRelativeLayout.setMaxScreenState(false);\n }\n });\n }\n\n private void initViews() {\n ibMinimize = (ImageButton) findViewById(R.id.ib_minimize);\n ibMinimize.setVisibility(View.GONE);\n multiVideoView = (CustomVideoContainer) findViewById(R.id.multi_view_container);\n bottomRelativeLayout = (BottomRelativeLayout) findViewById(R.id.bottom_relative);\n rootLayout = findViewById(R.id.root_layout);\n bottomRelativeLayout.setAgentNick(ChatClient.getInstance().callManager().getCallNickName());\n }\n\n private boolean firstChanged = true;\n\n @Override\n public void onWindowFocusChanged(boolean hasFocus) {\n super.onWindowFocusChanged(hasFocus);\n if (firstChanged) {\n firstChanged = false;\n ViewGroup.LayoutParams layoutParams = bottomRelativeLayout.getLayoutParams();\n layoutParams.height = rootLayout.getHeight() - multiVideoView.getHeight();\n bottomRelativeLayout.setLayoutParams(layoutParams);\n }\n }\n\n private void info(String msg) {\n Log.d(TAG, \"\" + msg);\n }\n\n @Override\n public void onAddStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n List streamItemList;\n if (!streamItemMaps.containsKey(stream.memberName)) {\n streamItemList = new ArrayList<>();\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n streamItemMaps.put(stream.memberName, streamItemList);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n } else {\n streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = addViewToMultiLayout(stream.streamId);\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n } else if (streamItemList.size() == 1) {\n if (stream.streamType == EMediaDefines.EMediaStreamType.EMSTREAM_TYPE_DESKTOP) {\n StreamItem item0 = streamItemList.get(0);\n final StreamItem streamItem = new StreamItem();\n streamItem.stream = stream;\n streamItem.videoView = item0.videoView;\n streamItem.videoView.setLabel(getNickName(stream.memberName));\n streamItemList.add(streamItem);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n ChatClient.getInstance().callManager().subscribe(streamItem.stream, streamItem.videoView.getSurfaceView(), null);\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n }\n }\n });\n }\n\n @Override\n public void onRemoveStream(final MediaStream stream) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (!streamItemMaps.containsKey(stream.memberName)) {\n return;\n }\n List streamItemList = streamItemMaps.get(stream.memberName);\n if (streamItemList.isEmpty()) {\n streamItemMaps.remove(stream.memberName);\n } else if (streamItemList.size() == 1) {\n CustomVideoView videoView = streamItemList.get(0).videoView;\n if (videoView != null) {\n multiVideoView.removeVideoView(videoView);\n }\n streamItemMaps.remove(stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(stream.streamId, null);\n } else if (streamItemList.size() == 2) {\n StreamItem item0 = streamItemList.get(0);\n StreamItem item1 = streamItemList.get(1);\n if (item0.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item1.videoView = item0.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, null);\n streamItemList.remove(item0);\n item1.videoView.setLabel(item1.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, item1.videoView.getSurfaceView());\n } else if (item1.stream.streamId.equalsIgnoreCase(stream.streamId)) {\n item0.videoView = item1.videoView;\n ChatClient.getInstance().callManager().setRemoteView(item1.stream.streamId, null);\n streamItemList.remove(item1);\n item0.videoView.setLabel(item0.stream.memberName);\n ChatClient.getInstance().callManager().setRemoteView(item0.stream.streamId, item0.videoView.getSurfaceView());\n }\n streamItemMaps.put(stream.memberName, streamItemList);\n }\n }\n });\n }\n\n @Override\n public void onUpdateStream(MediaStream stream) {\n }\n\n @Override\n public void onCallEnd(int reason, String desc) {\n EMLog.d(TAG, \"onCallEnd-reason:\" + reason + \",desc:\" + desc);\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if (ringtone != null) {\n ringtone.stop();\n }\n bottomRelativeLayout.stopChronometer();\n streamItemMaps.clear();\n multiVideoView.removeAllVideoViews();\n ChatClient.getInstance().callManager().endCall();\n stopForegroundService();\n finish();\n }\n });\n }\n\n @Override\n public void onNotice(CallManager.HMediaNoticeCode code, String arg1, String arg2, Object arg3) {\n switch(code) {\n case HMediaNoticeOpenCameraFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n case HMediaNoticeOpenMicFail:\n EMLog.d(TAG, \"onNotice:HMediaNoticeOpenCameraFail\");\n break;\n }\n }\n\n public static class StreamItem {\n\n CustomVideoView videoView;\n\n MediaStream stream;\n }\n\n private void stopForegroundService() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n stopService(service);\n }\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n ChatClient.getInstance().callManager().removeDelegate(this);\n if (ringtone != null && ringtone.isPlaying()) {\n ringtone.stop();\n }\n unregisterReceiver(headsetReceiver);\n audioManager.setMode(AudioManager.MODE_NORMAL);\n audioManager.setMicrophoneMute(false);\n releaseHandler();\n }\n\n public String getNickName(String memberName) {\n EMediaEntities.EMediaMember mediaMember = ChatClient.getInstance().callManager().getEMediaMember(memberName);\n if (mediaMember != null && !TextUtils.isEmpty(mediaMember.extension)) {\n try {\n JSONObject jsonObject = new JSONObject(mediaMember.extension);\n return jsonObject.getString(\"nickname\");\n } catch (Exception ignored) {\n }\n }\n return memberName;\n }\n\n protected void openSpeakerOn() {\n try {\n if (!audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(true);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n protected void closeSpeakerOn() {\n try {\n if (audioManager != null) {\n if (audioManager.isSpeakerphoneOn()) {\n audioManager.setSpeakerphoneOn(false);\n }\n audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == ScreenCaptureManager.RECORD_REQUEST_CODE) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n Intent service = new Intent(this, SRForegroundService.class);\n service.putExtra(\"code\", resultCode);\n service.putExtra(\"data\", data);\n startForegroundService(service);\n } else {\n ChatClient.getInstance().callManager().onActivityResult(requestCode, resultCode, data);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_487", "language": "Java", "task_type": "method_signature", "source_file": "java/github/hazelcast/hazelcast/hazelcast/src/main/java/com/hazelcast/map/impl/MapMergeRunnable.java", "mask_start_position": 1363, "mask_end_position": 1483, "canonical_solution": "@Override\n protected void mergeStore(RecordStore store, BiConsumer> consumer) ", "pre_mask_code": "package com.hazelcast.map.impl;\n\nimport com.hazelcast.config.InMemoryFormat;\nimport com.hazelcast.config.MapConfig;\nimport com.hazelcast.config.MergePolicyConfig;\nimport com.hazelcast.internal.serialization.Data;\nimport com.hazelcast.map.impl.operation.MapOperationProvider;\nimport com.hazelcast.map.impl.record.Record;\nimport com.hazelcast.map.impl.recordstore.RecordStore;\nimport com.hazelcast.map.impl.recordstore.expiry.ExpiryMetadata;\nimport com.hazelcast.spi.impl.merge.AbstractMergeRunnable;\nimport com.hazelcast.spi.impl.operationservice.OperationFactory;\nimport com.hazelcast.spi.merge.SplitBrainMergePolicy;\nimport com.hazelcast.spi.merge.SplitBrainMergeTypes.MapMergeTypes;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.function.BiConsumer;\nimport static com.hazelcast.spi.impl.merge.MergingValueFactory.createMergingEntry;\n\nclass MapMergeRunnable extends AbstractMergeRunnable> {\n\n private final MapServiceContext mapServiceContext;\n\n MapMergeRunnable(Collection mergingStores, MapSplitBrainHandlerService splitBrainHandlerService, MapServiceContext mapServiceContext) {\n super(MapService.SERVICE_NAME, mergingStores, splitBrainHandlerService, mapServiceContext.getNodeEngine());\n this.mapServiceContext = mapServiceContext;\n }\n\n ", "post_mask_code": "{\n int partitionId = store.getPartitionId();\n store.forEach((BiConsumer) (key, record) -> {\n Data dataKey = toHeapData(key);\n Data dataValue = toHeapData(record.getValue());\n ExpiryMetadata expiryMetadata = store.getExpirySystem().getExpiryMetadata(dataKey);\n consumer.accept(partitionId, createMergingEntry(getSerializationService(), dataKey, dataValue, record, expiryMetadata));\n }, false);\n }\n\n @Override\n protected int getBatchSize(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyConfig.getBatchSize();\n }\n\n @Override\n protected InMemoryFormat getInMemoryFormat(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n return mapConfig.getInMemoryFormat();\n }\n\n @Override\n protected SplitBrainMergePolicy getMergePolicy(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyProvider.getMergePolicy(mergePolicyConfig.getPolicy());\n }\n\n @Override\n protected String getDataStructureName(RecordStore recordStore) {\n return recordStore.getName();\n }\n\n @Override\n protected int getPartitionId(RecordStore store) {\n return store.getPartitionId();\n }\n\n @Override\n protected OperationFactory createMergeOperationFactory(String dataStructureName, SplitBrainMergePolicy, Object> mergePolicy, int[] partitions, List>[] entries) {\n MapOperationProvider operationProvider = mapServiceContext.getMapOperationProvider(dataStructureName);\n return operationProvider.createMergeOperationFactory(dataStructureName, partitions, entries, mergePolicy);\n }\n\n private MapConfig getMapConfig(String dataStructureName) {\n MapContainer mapContainer = mapServiceContext.getMapContainer(dataStructureName);\n return mapContainer.getMapConfig();\n }\n}\n"} {"task_id": "Java_488", "language": "Java", "task_type": "method_body", "source_file": "java/github/hazelcast/hazelcast/hazelcast/src/main/java/com/hazelcast/map/impl/MapMergeRunnable.java", "mask_start_position": 3252, "mask_end_position": 3485, "canonical_solution": "{\n MapOperationProvider operationProvider = mapServiceContext.getMapOperationProvider(dataStructureName);\n return operationProvider.createMergeOperationFactory(dataStructureName, partitions, entries, mergePolicy);\n }", "pre_mask_code": "package com.hazelcast.map.impl;\n\nimport com.hazelcast.config.InMemoryFormat;\nimport com.hazelcast.config.MapConfig;\nimport com.hazelcast.config.MergePolicyConfig;\nimport com.hazelcast.internal.serialization.Data;\nimport com.hazelcast.map.impl.operation.MapOperationProvider;\nimport com.hazelcast.map.impl.record.Record;\nimport com.hazelcast.map.impl.recordstore.RecordStore;\nimport com.hazelcast.map.impl.recordstore.expiry.ExpiryMetadata;\nimport com.hazelcast.spi.impl.merge.AbstractMergeRunnable;\nimport com.hazelcast.spi.impl.operationservice.OperationFactory;\nimport com.hazelcast.spi.merge.SplitBrainMergePolicy;\nimport com.hazelcast.spi.merge.SplitBrainMergeTypes.MapMergeTypes;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.function.BiConsumer;\nimport static com.hazelcast.spi.impl.merge.MergingValueFactory.createMergingEntry;\n\nclass MapMergeRunnable extends AbstractMergeRunnable> {\n\n private final MapServiceContext mapServiceContext;\n\n MapMergeRunnable(Collection mergingStores, MapSplitBrainHandlerService splitBrainHandlerService, MapServiceContext mapServiceContext) {\n super(MapService.SERVICE_NAME, mergingStores, splitBrainHandlerService, mapServiceContext.getNodeEngine());\n this.mapServiceContext = mapServiceContext;\n }\n\n @Override\n protected void mergeStore(RecordStore store, BiConsumer> consumer) {\n int partitionId = store.getPartitionId();\n store.forEach((BiConsumer) (key, record) -> {\n Data dataKey = toHeapData(key);\n Data dataValue = toHeapData(record.getValue());\n ExpiryMetadata expiryMetadata = store.getExpirySystem().getExpiryMetadata(dataKey);\n consumer.accept(partitionId, createMergingEntry(getSerializationService(), dataKey, dataValue, record, expiryMetadata));\n }, false);\n }\n\n @Override\n protected int getBatchSize(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyConfig.getBatchSize();\n }\n\n @Override\n protected InMemoryFormat getInMemoryFormat(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n return mapConfig.getInMemoryFormat();\n }\n\n @Override\n protected SplitBrainMergePolicy getMergePolicy(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyProvider.getMergePolicy(mergePolicyConfig.getPolicy());\n }\n\n @Override\n protected String getDataStructureName(RecordStore recordStore) {\n return recordStore.getName();\n }\n\n @Override\n protected int getPartitionId(RecordStore store) {\n return store.getPartitionId();\n }\n\n @Override\n protected OperationFactory createMergeOperationFactory(String dataStructureName, SplitBrainMergePolicy, Object> mergePolicy, int[] partitions, List>[] entries) ", "post_mask_code": "\n\n private MapConfig getMapConfig(String dataStructureName) {\n MapContainer mapContainer = mapServiceContext.getMapContainer(dataStructureName);\n return mapContainer.getMapConfig();\n }\n}\n"} {"task_id": "Java_489", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/hazelcast/hazelcast/hazelcast/src/main/java/com/hazelcast/map/impl/MapMergeRunnable.java", "mask_start_position": 1484, "mask_end_position": 1534, "canonical_solution": "\n int partitionId = store.getPartitionId();", "pre_mask_code": "package com.hazelcast.map.impl;\n\nimport com.hazelcast.config.InMemoryFormat;\nimport com.hazelcast.config.MapConfig;\nimport com.hazelcast.config.MergePolicyConfig;\nimport com.hazelcast.internal.serialization.Data;\nimport com.hazelcast.map.impl.operation.MapOperationProvider;\nimport com.hazelcast.map.impl.record.Record;\nimport com.hazelcast.map.impl.recordstore.RecordStore;\nimport com.hazelcast.map.impl.recordstore.expiry.ExpiryMetadata;\nimport com.hazelcast.spi.impl.merge.AbstractMergeRunnable;\nimport com.hazelcast.spi.impl.operationservice.OperationFactory;\nimport com.hazelcast.spi.merge.SplitBrainMergePolicy;\nimport com.hazelcast.spi.merge.SplitBrainMergeTypes.MapMergeTypes;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.function.BiConsumer;\nimport static com.hazelcast.spi.impl.merge.MergingValueFactory.createMergingEntry;\n\nclass MapMergeRunnable extends AbstractMergeRunnable> {\n\n private final MapServiceContext mapServiceContext;\n\n MapMergeRunnable(Collection mergingStores, MapSplitBrainHandlerService splitBrainHandlerService, MapServiceContext mapServiceContext) {\n super(MapService.SERVICE_NAME, mergingStores, splitBrainHandlerService, mapServiceContext.getNodeEngine());\n this.mapServiceContext = mapServiceContext;\n }\n\n @Override\n protected void mergeStore(RecordStore store, BiConsumer> consumer) {", "post_mask_code": "\n store.forEach((BiConsumer) (key, record) -> {\n Data dataKey = toHeapData(key);\n Data dataValue = toHeapData(record.getValue());\n ExpiryMetadata expiryMetadata = store.getExpirySystem().getExpiryMetadata(dataKey);\n consumer.accept(partitionId, createMergingEntry(getSerializationService(), dataKey, dataValue, record, expiryMetadata));\n }, false);\n }\n\n @Override\n protected int getBatchSize(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyConfig.getBatchSize();\n }\n\n @Override\n protected InMemoryFormat getInMemoryFormat(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n return mapConfig.getInMemoryFormat();\n }\n\n @Override\n protected SplitBrainMergePolicy getMergePolicy(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyProvider.getMergePolicy(mergePolicyConfig.getPolicy());\n }\n\n @Override\n protected String getDataStructureName(RecordStore recordStore) {\n return recordStore.getName();\n }\n\n @Override\n protected int getPartitionId(RecordStore store) {\n return store.getPartitionId();\n }\n\n @Override\n protected OperationFactory createMergeOperationFactory(String dataStructureName, SplitBrainMergePolicy, Object> mergePolicy, int[] partitions, List>[] entries) {\n MapOperationProvider operationProvider = mapServiceContext.getMapOperationProvider(dataStructureName);\n return operationProvider.createMergeOperationFactory(dataStructureName, partitions, entries, mergePolicy);\n }\n\n private MapConfig getMapConfig(String dataStructureName) {\n MapContainer mapContainer = mapServiceContext.getMapContainer(dataStructureName);\n return mapContainer.getMapConfig();\n }\n}\n"} {"task_id": "Java_490", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/hazelcast/hazelcast/hazelcast/src/main/java/com/hazelcast/map/impl/MapMergeRunnable.java", "mask_start_position": 1543, "mask_end_position": 1954, "canonical_solution": "store.forEach((BiConsumer) (key, record) -> {\n Data dataKey = toHeapData(key);\n Data dataValue = toHeapData(record.getValue());\n ExpiryMetadata expiryMetadata = store.getExpirySystem().getExpiryMetadata(dataKey);\n consumer.accept(partitionId, createMergingEntry(getSerializationService(), dataKey, dataValue, record, expiryMetadata));\n }, false);", "pre_mask_code": "package com.hazelcast.map.impl;\n\nimport com.hazelcast.config.InMemoryFormat;\nimport com.hazelcast.config.MapConfig;\nimport com.hazelcast.config.MergePolicyConfig;\nimport com.hazelcast.internal.serialization.Data;\nimport com.hazelcast.map.impl.operation.MapOperationProvider;\nimport com.hazelcast.map.impl.record.Record;\nimport com.hazelcast.map.impl.recordstore.RecordStore;\nimport com.hazelcast.map.impl.recordstore.expiry.ExpiryMetadata;\nimport com.hazelcast.spi.impl.merge.AbstractMergeRunnable;\nimport com.hazelcast.spi.impl.operationservice.OperationFactory;\nimport com.hazelcast.spi.merge.SplitBrainMergePolicy;\nimport com.hazelcast.spi.merge.SplitBrainMergeTypes.MapMergeTypes;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.function.BiConsumer;\nimport static com.hazelcast.spi.impl.merge.MergingValueFactory.createMergingEntry;\n\nclass MapMergeRunnable extends AbstractMergeRunnable> {\n\n private final MapServiceContext mapServiceContext;\n\n MapMergeRunnable(Collection mergingStores, MapSplitBrainHandlerService splitBrainHandlerService, MapServiceContext mapServiceContext) {\n super(MapService.SERVICE_NAME, mergingStores, splitBrainHandlerService, mapServiceContext.getNodeEngine());\n this.mapServiceContext = mapServiceContext;\n }\n\n @Override\n protected void mergeStore(RecordStore store, BiConsumer> consumer) {\n int partitionId = store.getPartitionId();\n ", "post_mask_code": "\n }\n\n @Override\n protected int getBatchSize(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyConfig.getBatchSize();\n }\n\n @Override\n protected InMemoryFormat getInMemoryFormat(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n return mapConfig.getInMemoryFormat();\n }\n\n @Override\n protected SplitBrainMergePolicy getMergePolicy(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyProvider.getMergePolicy(mergePolicyConfig.getPolicy());\n }\n\n @Override\n protected String getDataStructureName(RecordStore recordStore) {\n return recordStore.getName();\n }\n\n @Override\n protected int getPartitionId(RecordStore store) {\n return store.getPartitionId();\n }\n\n @Override\n protected OperationFactory createMergeOperationFactory(String dataStructureName, SplitBrainMergePolicy, Object> mergePolicy, int[] partitions, List>[] entries) {\n MapOperationProvider operationProvider = mapServiceContext.getMapOperationProvider(dataStructureName);\n return operationProvider.createMergeOperationFactory(dataStructureName, partitions, entries, mergePolicy);\n }\n\n private MapConfig getMapConfig(String dataStructureName) {\n MapContainer mapContainer = mapServiceContext.getMapContainer(dataStructureName);\n return mapContainer.getMapConfig();\n }\n}\n"} {"task_id": "Java_491", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/hazelcast/hazelcast/hazelcast/src/main/java/com/hazelcast/map/impl/MapMergeRunnable.java", "mask_start_position": 1959, "mask_end_position": 1960, "canonical_solution": "}", "pre_mask_code": "package com.hazelcast.map.impl;\n\nimport com.hazelcast.config.InMemoryFormat;\nimport com.hazelcast.config.MapConfig;\nimport com.hazelcast.config.MergePolicyConfig;\nimport com.hazelcast.internal.serialization.Data;\nimport com.hazelcast.map.impl.operation.MapOperationProvider;\nimport com.hazelcast.map.impl.record.Record;\nimport com.hazelcast.map.impl.recordstore.RecordStore;\nimport com.hazelcast.map.impl.recordstore.expiry.ExpiryMetadata;\nimport com.hazelcast.spi.impl.merge.AbstractMergeRunnable;\nimport com.hazelcast.spi.impl.operationservice.OperationFactory;\nimport com.hazelcast.spi.merge.SplitBrainMergePolicy;\nimport com.hazelcast.spi.merge.SplitBrainMergeTypes.MapMergeTypes;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.function.BiConsumer;\nimport static com.hazelcast.spi.impl.merge.MergingValueFactory.createMergingEntry;\n\nclass MapMergeRunnable extends AbstractMergeRunnable> {\n\n private final MapServiceContext mapServiceContext;\n\n MapMergeRunnable(Collection mergingStores, MapSplitBrainHandlerService splitBrainHandlerService, MapServiceContext mapServiceContext) {\n super(MapService.SERVICE_NAME, mergingStores, splitBrainHandlerService, mapServiceContext.getNodeEngine());\n this.mapServiceContext = mapServiceContext;\n }\n\n @Override\n protected void mergeStore(RecordStore store, BiConsumer> consumer) {\n int partitionId = store.getPartitionId();\n store.forEach((BiConsumer) (key, record) -> {\n Data dataKey = toHeapData(key);\n Data dataValue = toHeapData(record.getValue());\n ExpiryMetadata expiryMetadata = store.getExpirySystem().getExpiryMetadata(dataKey);\n consumer.accept(partitionId, createMergingEntry(getSerializationService(), dataKey, dataValue, record, expiryMetadata));\n }, false);\n ", "post_mask_code": "\n\n @Override\n protected int getBatchSize(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyConfig.getBatchSize();\n }\n\n @Override\n protected InMemoryFormat getInMemoryFormat(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n return mapConfig.getInMemoryFormat();\n }\n\n @Override\n protected SplitBrainMergePolicy getMergePolicy(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyProvider.getMergePolicy(mergePolicyConfig.getPolicy());\n }\n\n @Override\n protected String getDataStructureName(RecordStore recordStore) {\n return recordStore.getName();\n }\n\n @Override\n protected int getPartitionId(RecordStore store) {\n return store.getPartitionId();\n }\n\n @Override\n protected OperationFactory createMergeOperationFactory(String dataStructureName, SplitBrainMergePolicy, Object> mergePolicy, int[] partitions, List>[] entries) {\n MapOperationProvider operationProvider = mapServiceContext.getMapOperationProvider(dataStructureName);\n return operationProvider.createMergeOperationFactory(dataStructureName, partitions, entries, mergePolicy);\n }\n\n private MapConfig getMapConfig(String dataStructureName) {\n MapContainer mapContainer = mapServiceContext.getMapContainer(dataStructureName);\n return mapContainer.getMapConfig();\n }\n}\n"} {"task_id": "Java_492", "language": "Java", "task_type": "single_line", "source_file": "java/github/hazelcast/hazelcast/hazelcast/src/main/java/com/hazelcast/map/impl/MapMergeRunnable.java", "mask_start_position": 3621, "mask_end_position": 3639, "canonical_solution": "ataStructureName);", "pre_mask_code": "package com.hazelcast.map.impl;\n\nimport com.hazelcast.config.InMemoryFormat;\nimport com.hazelcast.config.MapConfig;\nimport com.hazelcast.config.MergePolicyConfig;\nimport com.hazelcast.internal.serialization.Data;\nimport com.hazelcast.map.impl.operation.MapOperationProvider;\nimport com.hazelcast.map.impl.record.Record;\nimport com.hazelcast.map.impl.recordstore.RecordStore;\nimport com.hazelcast.map.impl.recordstore.expiry.ExpiryMetadata;\nimport com.hazelcast.spi.impl.merge.AbstractMergeRunnable;\nimport com.hazelcast.spi.impl.operationservice.OperationFactory;\nimport com.hazelcast.spi.merge.SplitBrainMergePolicy;\nimport com.hazelcast.spi.merge.SplitBrainMergeTypes.MapMergeTypes;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.function.BiConsumer;\nimport static com.hazelcast.spi.impl.merge.MergingValueFactory.createMergingEntry;\n\nclass MapMergeRunnable extends AbstractMergeRunnable> {\n\n private final MapServiceContext mapServiceContext;\n\n MapMergeRunnable(Collection mergingStores, MapSplitBrainHandlerService splitBrainHandlerService, MapServiceContext mapServiceContext) {\n super(MapService.SERVICE_NAME, mergingStores, splitBrainHandlerService, mapServiceContext.getNodeEngine());\n this.mapServiceContext = mapServiceContext;\n }\n\n @Override\n protected void mergeStore(RecordStore store, BiConsumer> consumer) {\n int partitionId = store.getPartitionId();\n store.forEach((BiConsumer) (key, record) -> {\n Data dataKey = toHeapData(key);\n Data dataValue = toHeapData(record.getValue());\n ExpiryMetadata expiryMetadata = store.getExpirySystem().getExpiryMetadata(dataKey);\n consumer.accept(partitionId, createMergingEntry(getSerializationService(), dataKey, dataValue, record, expiryMetadata));\n }, false);\n }\n\n @Override\n protected int getBatchSize(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyConfig.getBatchSize();\n }\n\n @Override\n protected InMemoryFormat getInMemoryFormat(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n return mapConfig.getInMemoryFormat();\n }\n\n @Override\n protected SplitBrainMergePolicy getMergePolicy(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyProvider.getMergePolicy(mergePolicyConfig.getPolicy());\n }\n\n @Override\n protected String getDataStructureName(RecordStore recordStore) {\n return recordStore.getName();\n }\n\n @Override\n protected int getPartitionId(RecordStore store) {\n return store.getPartitionId();\n }\n\n @Override\n protected OperationFactory createMergeOperationFactory(String dataStructureName, SplitBrainMergePolicy, Object> mergePolicy, int[] partitions, List>[] entries) {\n MapOperationProvider operationProvider = mapServiceContext.getMapOperationProvider(dataStructureName);\n return operationProvider.createMergeOperationFactory(dataStructureName, partitions, entries, mergePolicy);\n }\n\n private MapConfig getMapConfig(String dataStructureName) {\n MapContainer mapContainer = mapServiceContext.getMapContainer(d", "post_mask_code": "\n return mapContainer.getMapConfig();\n }\n}\n"} {"task_id": "Java_493", "language": "Java", "task_type": "empty", "source_file": "java/github/hazelcast/hazelcast/hazelcast/src/main/java/com/hazelcast/map/impl/MapMergeRunnable.java", "mask_start_position": 284, "mask_end_position": 284, "canonical_solution": "", "pre_mask_code": "package com.hazelcast.map.impl;\n\nimport com.hazelcast.config.InMemoryFormat;\nimport com.hazelcast.config.MapConfig;\nimport com.hazelcast.config.MergePolicyConfig;\nimport com.hazelcast.internal.serialization.Data;\nimport com.hazelcast.map.impl.operation.MapOperationProvider;\nimport co", "post_mask_code": "m.hazelcast.map.impl.record.Record;\nimport com.hazelcast.map.impl.recordstore.RecordStore;\nimport com.hazelcast.map.impl.recordstore.expiry.ExpiryMetadata;\nimport com.hazelcast.spi.impl.merge.AbstractMergeRunnable;\nimport com.hazelcast.spi.impl.operationservice.OperationFactory;\nimport com.hazelcast.spi.merge.SplitBrainMergePolicy;\nimport com.hazelcast.spi.merge.SplitBrainMergeTypes.MapMergeTypes;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.function.BiConsumer;\nimport static com.hazelcast.spi.impl.merge.MergingValueFactory.createMergingEntry;\n\nclass MapMergeRunnable extends AbstractMergeRunnable> {\n\n private final MapServiceContext mapServiceContext;\n\n MapMergeRunnable(Collection mergingStores, MapSplitBrainHandlerService splitBrainHandlerService, MapServiceContext mapServiceContext) {\n super(MapService.SERVICE_NAME, mergingStores, splitBrainHandlerService, mapServiceContext.getNodeEngine());\n this.mapServiceContext = mapServiceContext;\n }\n\n @Override\n protected void mergeStore(RecordStore store, BiConsumer> consumer) {\n int partitionId = store.getPartitionId();\n store.forEach((BiConsumer) (key, record) -> {\n Data dataKey = toHeapData(key);\n Data dataValue = toHeapData(record.getValue());\n ExpiryMetadata expiryMetadata = store.getExpirySystem().getExpiryMetadata(dataKey);\n consumer.accept(partitionId, createMergingEntry(getSerializationService(), dataKey, dataValue, record, expiryMetadata));\n }, false);\n }\n\n @Override\n protected int getBatchSize(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyConfig.getBatchSize();\n }\n\n @Override\n protected InMemoryFormat getInMemoryFormat(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n return mapConfig.getInMemoryFormat();\n }\n\n @Override\n protected SplitBrainMergePolicy getMergePolicy(String dataStructureName) {\n MapConfig mapConfig = getMapConfig(dataStructureName);\n MergePolicyConfig mergePolicyConfig = mapConfig.getMergePolicyConfig();\n return mergePolicyProvider.getMergePolicy(mergePolicyConfig.getPolicy());\n }\n\n @Override\n protected String getDataStructureName(RecordStore recordStore) {\n return recordStore.getName();\n }\n\n @Override\n protected int getPartitionId(RecordStore store) {\n return store.getPartitionId();\n }\n\n @Override\n protected OperationFactory createMergeOperationFactory(String dataStructureName, SplitBrainMergePolicy, Object> mergePolicy, int[] partitions, List>[] entries) {\n MapOperationProvider operationProvider = mapServiceContext.getMapOperationProvider(dataStructureName);\n return operationProvider.createMergeOperationFactory(dataStructureName, partitions, entries, mergePolicy);\n }\n\n private MapConfig getMapConfig(String dataStructureName) {\n MapContainer mapContainer = mapServiceContext.getMapContainer(dataStructureName);\n return mapContainer.getMapConfig();\n }\n}\n"} {"task_id": "Java_494", "language": "Java", "task_type": "method_signature", "source_file": "java/github/CONNECT-Solution/CONNECT/Product/Production/Services/DocumentSubmissionCore/src/main/java/gov/hhs/fha/nhinc/docsubmission/adapter/component/proxy/AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.java", "mask_start_position": 1774, "mask_end_position": 1918, "canonical_solution": "@Override\n public RegistryResponseType provideAndRegisterDocumentSetB(ProvideAndRegisterDocumentSetRequestType msg, AssertionType assertion) ", "pre_mask_code": "/*\n * All rights reserved.\n * \n*/\npackage gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy;\n\nimport gov.hhs.fha.nhinc.adaptercomponentxdr.AdapterComponentXDRPortType;\nimport gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;\nimport gov.hhs.fha.nhinc.common.nhinccommonadapter.AdapterProvideAndRegisterDocumentSetRequestType;\nimport gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy.service.AdapterComponentDocSubmissionServicePortDescriptor;\nimport gov.hhs.fha.nhinc.event.error.ErrorEventException;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTCXFClientFactory;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTClient;\nimport gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;\nimport gov.hhs.fha.nhinc.nhinclib.NhincConstants;\nimport gov.hhs.fha.nhinc.nhinclib.NullChecker;\nimport gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;\nimport ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;\nimport javax.xml.ws.WebServiceException;\nimport oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * @author jhoppesc\n */\npublic class AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl implements AdapterComponentDocSubmissionProxy {\n\n private static final Logger LOG = LoggerFactory.getLogger(AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.class);\n\n private WebServiceProxyHelper oProxyHelper = new WebServiceProxyHelper();\n\n protected CONNECTClient getCONNECTClientUnsecured(ServicePortDescriptor portDescriptor, String url, AssertionType assertion) {\n return CONNECTCXFClientFactory.getInstance().getCONNECTClientUnsecured(portDescriptor, url, assertion);\n }\n\n ", "post_mask_code": "{\n LOG.debug(\"Begin provideAndRegisterDocumentSetB\");\n RegistryResponseType response = null;\n try {\n String url = oProxyHelper.getAdapterEndPointFromConnectionManager(NhincConstants.ADAPTER_COMPONENT_XDR_SERVICE_NAME);\n if (NullChecker.isNotNullish(url)) {\n if (msg == null) {\n throw new IllegalArgumentException(\"Request Message must be provided\");\n } else if (assertion == null) {\n throw new IllegalArgumentException(\"Assertion must be provided\");\n } else {\n AdapterProvideAndRegisterDocumentSetRequestType request = new AdapterProvideAndRegisterDocumentSetRequestType();\n request.setProvideAndRegisterDocumentSetRequest(msg);\n request.setAssertion(assertion);\n ServicePortDescriptor portDescriptor = new AdapterComponentDocSubmissionServicePortDescriptor();\n CONNECTClient client = getCONNECTClientUnsecured(portDescriptor, url, assertion);\n client.enableMtom();\n response = (RegistryResponseType) client.invokePort(AdapterComponentXDRPortType.class, \"provideAndRegisterDocumentSetb\", request);\n }\n } else {\n throw new WebServiceException(\"Could not determine URL for Doc Submission Adapter Component endpoint\");\n }\n } catch (Exception ex) {\n response = new RegistryResponseType();\n response.setStatus(\"urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Failure\");\n throw new ErrorEventException(ex, response, \"Unable to call Doc Submission Adapter Component\");\n }\n LOG.debug(\"End provideAndRegisterDocumentSetB\");\n return response;\n }\n}\n"} {"task_id": "Java_495", "language": "Java", "task_type": "method_body", "source_file": "java/github/CONNECT-Solution/CONNECT/Product/Production/Services/DocumentSubmissionCore/src/main/java/gov/hhs/fha/nhinc/docsubmission/adapter/component/proxy/AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.java", "mask_start_position": 1649, "mask_end_position": 1768, "canonical_solution": "{\n return CONNECTCXFClientFactory.getInstance().getCONNECTClientUnsecured(portDescriptor, url, assertion);\n }", "pre_mask_code": "/*\n * All rights reserved.\n * \n*/\npackage gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy;\n\nimport gov.hhs.fha.nhinc.adaptercomponentxdr.AdapterComponentXDRPortType;\nimport gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;\nimport gov.hhs.fha.nhinc.common.nhinccommonadapter.AdapterProvideAndRegisterDocumentSetRequestType;\nimport gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy.service.AdapterComponentDocSubmissionServicePortDescriptor;\nimport gov.hhs.fha.nhinc.event.error.ErrorEventException;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTCXFClientFactory;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTClient;\nimport gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;\nimport gov.hhs.fha.nhinc.nhinclib.NhincConstants;\nimport gov.hhs.fha.nhinc.nhinclib.NullChecker;\nimport gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;\nimport ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;\nimport javax.xml.ws.WebServiceException;\nimport oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * @author jhoppesc\n */\npublic class AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl implements AdapterComponentDocSubmissionProxy {\n\n private static final Logger LOG = LoggerFactory.getLogger(AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.class);\n\n private WebServiceProxyHelper oProxyHelper = new WebServiceProxyHelper();\n\n protected CONNECTClient getCONNECTClientUnsecured(ServicePortDescriptor portDescriptor, String url, AssertionType assertion) ", "post_mask_code": "\n\n @Override\n public RegistryResponseType provideAndRegisterDocumentSetB(ProvideAndRegisterDocumentSetRequestType msg, AssertionType assertion) {\n LOG.debug(\"Begin provideAndRegisterDocumentSetB\");\n RegistryResponseType response = null;\n try {\n String url = oProxyHelper.getAdapterEndPointFromConnectionManager(NhincConstants.ADAPTER_COMPONENT_XDR_SERVICE_NAME);\n if (NullChecker.isNotNullish(url)) {\n if (msg == null) {\n throw new IllegalArgumentException(\"Request Message must be provided\");\n } else if (assertion == null) {\n throw new IllegalArgumentException(\"Assertion must be provided\");\n } else {\n AdapterProvideAndRegisterDocumentSetRequestType request = new AdapterProvideAndRegisterDocumentSetRequestType();\n request.setProvideAndRegisterDocumentSetRequest(msg);\n request.setAssertion(assertion);\n ServicePortDescriptor portDescriptor = new AdapterComponentDocSubmissionServicePortDescriptor();\n CONNECTClient client = getCONNECTClientUnsecured(portDescriptor, url, assertion);\n client.enableMtom();\n response = (RegistryResponseType) client.invokePort(AdapterComponentXDRPortType.class, \"provideAndRegisterDocumentSetb\", request);\n }\n } else {\n throw new WebServiceException(\"Could not determine URL for Doc Submission Adapter Component endpoint\");\n }\n } catch (Exception ex) {\n response = new RegistryResponseType();\n response.setStatus(\"urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Failure\");\n throw new ErrorEventException(ex, response, \"Unable to call Doc Submission Adapter Component\");\n }\n LOG.debug(\"End provideAndRegisterDocumentSetB\");\n return response;\n }\n}\n"} {"task_id": "Java_496", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/CONNECT-Solution/CONNECT/Product/Production/Services/DocumentSubmissionCore/src/main/java/gov/hhs/fha/nhinc/docsubmission/adapter/component/proxy/AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.java", "mask_start_position": 1919, "mask_end_position": 2024, "canonical_solution": "\n LOG.debug(\"Begin provideAndRegisterDocumentSetB\");\n RegistryResponseType response = null;", "pre_mask_code": "/*\n * All rights reserved.\n * \n*/\npackage gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy;\n\nimport gov.hhs.fha.nhinc.adaptercomponentxdr.AdapterComponentXDRPortType;\nimport gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;\nimport gov.hhs.fha.nhinc.common.nhinccommonadapter.AdapterProvideAndRegisterDocumentSetRequestType;\nimport gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy.service.AdapterComponentDocSubmissionServicePortDescriptor;\nimport gov.hhs.fha.nhinc.event.error.ErrorEventException;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTCXFClientFactory;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTClient;\nimport gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;\nimport gov.hhs.fha.nhinc.nhinclib.NhincConstants;\nimport gov.hhs.fha.nhinc.nhinclib.NullChecker;\nimport gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;\nimport ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;\nimport javax.xml.ws.WebServiceException;\nimport oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * @author jhoppesc\n */\npublic class AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl implements AdapterComponentDocSubmissionProxy {\n\n private static final Logger LOG = LoggerFactory.getLogger(AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.class);\n\n private WebServiceProxyHelper oProxyHelper = new WebServiceProxyHelper();\n\n protected CONNECTClient getCONNECTClientUnsecured(ServicePortDescriptor portDescriptor, String url, AssertionType assertion) {\n return CONNECTCXFClientFactory.getInstance().getCONNECTClientUnsecured(portDescriptor, url, assertion);\n }\n\n @Override\n public RegistryResponseType provideAndRegisterDocumentSetB(ProvideAndRegisterDocumentSetRequestType msg, AssertionType assertion) {", "post_mask_code": "\n try {\n String url = oProxyHelper.getAdapterEndPointFromConnectionManager(NhincConstants.ADAPTER_COMPONENT_XDR_SERVICE_NAME);\n if (NullChecker.isNotNullish(url)) {\n if (msg == null) {\n throw new IllegalArgumentException(\"Request Message must be provided\");\n } else if (assertion == null) {\n throw new IllegalArgumentException(\"Assertion must be provided\");\n } else {\n AdapterProvideAndRegisterDocumentSetRequestType request = new AdapterProvideAndRegisterDocumentSetRequestType();\n request.setProvideAndRegisterDocumentSetRequest(msg);\n request.setAssertion(assertion);\n ServicePortDescriptor portDescriptor = new AdapterComponentDocSubmissionServicePortDescriptor();\n CONNECTClient client = getCONNECTClientUnsecured(portDescriptor, url, assertion);\n client.enableMtom();\n response = (RegistryResponseType) client.invokePort(AdapterComponentXDRPortType.class, \"provideAndRegisterDocumentSetb\", request);\n }\n } else {\n throw new WebServiceException(\"Could not determine URL for Doc Submission Adapter Component endpoint\");\n }\n } catch (Exception ex) {\n response = new RegistryResponseType();\n response.setStatus(\"urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Failure\");\n throw new ErrorEventException(ex, response, \"Unable to call Doc Submission Adapter Component\");\n }\n LOG.debug(\"End provideAndRegisterDocumentSetB\");\n return response;\n }\n}\n"} {"task_id": "Java_497", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/CONNECT-Solution/CONNECT/Product/Production/Services/DocumentSubmissionCore/src/main/java/gov/hhs/fha/nhinc/docsubmission/adapter/component/proxy/AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.java", "mask_start_position": 2033, "mask_end_position": 3758, "canonical_solution": "try {\n String url = oProxyHelper.getAdapterEndPointFromConnectionManager(NhincConstants.ADAPTER_COMPONENT_XDR_SERVICE_NAME);\n if (NullChecker.isNotNullish(url)) {\n if (msg == null) {\n throw new IllegalArgumentException(\"Request Message must be provided\");\n } else if (assertion == null) {\n throw new IllegalArgumentException(\"Assertion must be provided\");\n } else {\n AdapterProvideAndRegisterDocumentSetRequestType request = new AdapterProvideAndRegisterDocumentSetRequestType();\n request.setProvideAndRegisterDocumentSetRequest(msg);\n request.setAssertion(assertion);\n ServicePortDescriptor portDescriptor = new AdapterComponentDocSubmissionServicePortDescriptor();\n CONNECTClient client = getCONNECTClientUnsecured(portDescriptor, url, assertion);\n client.enableMtom();\n response = (RegistryResponseType) client.invokePort(AdapterComponentXDRPortType.class, \"provideAndRegisterDocumentSetb\", request);\n }\n } else {\n throw new WebServiceException(\"Could not determine URL for Doc Submission Adapter Component endpoint\");\n }\n } catch (Exception ex) {\n response = new RegistryResponseType();\n response.setStatus(\"urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Failure\");\n throw new ErrorEventException(ex, response, \"Unable to call Doc Submission Adapter Component\");\n }\n LOG.debug(\"End provideAndRegisterDocumentSetB\");", "pre_mask_code": "/*\n * All rights reserved.\n * \n*/\npackage gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy;\n\nimport gov.hhs.fha.nhinc.adaptercomponentxdr.AdapterComponentXDRPortType;\nimport gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;\nimport gov.hhs.fha.nhinc.common.nhinccommonadapter.AdapterProvideAndRegisterDocumentSetRequestType;\nimport gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy.service.AdapterComponentDocSubmissionServicePortDescriptor;\nimport gov.hhs.fha.nhinc.event.error.ErrorEventException;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTCXFClientFactory;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTClient;\nimport gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;\nimport gov.hhs.fha.nhinc.nhinclib.NhincConstants;\nimport gov.hhs.fha.nhinc.nhinclib.NullChecker;\nimport gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;\nimport ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;\nimport javax.xml.ws.WebServiceException;\nimport oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * @author jhoppesc\n */\npublic class AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl implements AdapterComponentDocSubmissionProxy {\n\n private static final Logger LOG = LoggerFactory.getLogger(AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.class);\n\n private WebServiceProxyHelper oProxyHelper = new WebServiceProxyHelper();\n\n protected CONNECTClient getCONNECTClientUnsecured(ServicePortDescriptor portDescriptor, String url, AssertionType assertion) {\n return CONNECTCXFClientFactory.getInstance().getCONNECTClientUnsecured(portDescriptor, url, assertion);\n }\n\n @Override\n public RegistryResponseType provideAndRegisterDocumentSetB(ProvideAndRegisterDocumentSetRequestType msg, AssertionType assertion) {\n LOG.debug(\"Begin provideAndRegisterDocumentSetB\");\n RegistryResponseType response = null;\n ", "post_mask_code": "\n return response;\n }\n}\n"} {"task_id": "Java_498", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/CONNECT-Solution/CONNECT/Product/Production/Services/DocumentSubmissionCore/src/main/java/gov/hhs/fha/nhinc/docsubmission/adapter/component/proxy/AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.java", "mask_start_position": 3767, "mask_end_position": 3789, "canonical_solution": "return response;\n }", "pre_mask_code": "/*\n * All rights reserved.\n * \n*/\npackage gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy;\n\nimport gov.hhs.fha.nhinc.adaptercomponentxdr.AdapterComponentXDRPortType;\nimport gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;\nimport gov.hhs.fha.nhinc.common.nhinccommonadapter.AdapterProvideAndRegisterDocumentSetRequestType;\nimport gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy.service.AdapterComponentDocSubmissionServicePortDescriptor;\nimport gov.hhs.fha.nhinc.event.error.ErrorEventException;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTCXFClientFactory;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTClient;\nimport gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;\nimport gov.hhs.fha.nhinc.nhinclib.NhincConstants;\nimport gov.hhs.fha.nhinc.nhinclib.NullChecker;\nimport gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;\nimport ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;\nimport javax.xml.ws.WebServiceException;\nimport oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * @author jhoppesc\n */\npublic class AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl implements AdapterComponentDocSubmissionProxy {\n\n private static final Logger LOG = LoggerFactory.getLogger(AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.class);\n\n private WebServiceProxyHelper oProxyHelper = new WebServiceProxyHelper();\n\n protected CONNECTClient getCONNECTClientUnsecured(ServicePortDescriptor portDescriptor, String url, AssertionType assertion) {\n return CONNECTCXFClientFactory.getInstance().getCONNECTClientUnsecured(portDescriptor, url, assertion);\n }\n\n @Override\n public RegistryResponseType provideAndRegisterDocumentSetB(ProvideAndRegisterDocumentSetRequestType msg, AssertionType assertion) {\n LOG.debug(\"Begin provideAndRegisterDocumentSetB\");\n RegistryResponseType response = null;\n try {\n String url = oProxyHelper.getAdapterEndPointFromConnectionManager(NhincConstants.ADAPTER_COMPONENT_XDR_SERVICE_NAME);\n if (NullChecker.isNotNullish(url)) {\n if (msg == null) {\n throw new IllegalArgumentException(\"Request Message must be provided\");\n } else if (assertion == null) {\n throw new IllegalArgumentException(\"Assertion must be provided\");\n } else {\n AdapterProvideAndRegisterDocumentSetRequestType request = new AdapterProvideAndRegisterDocumentSetRequestType();\n request.setProvideAndRegisterDocumentSetRequest(msg);\n request.setAssertion(assertion);\n ServicePortDescriptor portDescriptor = new AdapterComponentDocSubmissionServicePortDescriptor();\n CONNECTClient client = getCONNECTClientUnsecured(portDescriptor, url, assertion);\n client.enableMtom();\n response = (RegistryResponseType) client.invokePort(AdapterComponentXDRPortType.class, \"provideAndRegisterDocumentSetb\", request);\n }\n } else {\n throw new WebServiceException(\"Could not determine URL for Doc Submission Adapter Component endpoint\");\n }\n } catch (Exception ex) {\n response = new RegistryResponseType();\n response.setStatus(\"urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Failure\");\n throw new ErrorEventException(ex, response, \"Unable to call Doc Submission Adapter Component\");\n }\n LOG.debug(\"End provideAndRegisterDocumentSetB\");\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_499", "language": "Java", "task_type": "single_line", "source_file": "java/github/CONNECT-Solution/CONNECT/Product/Production/Services/DocumentSubmissionCore/src/main/java/gov/hhs/fha/nhinc/docsubmission/adapter/component/proxy/AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.java", "mask_start_position": 3753, "mask_end_position": 3758, "canonical_solution": "tB\");", "pre_mask_code": "/*\n * All rights reserved.\n * \n*/\npackage gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy;\n\nimport gov.hhs.fha.nhinc.adaptercomponentxdr.AdapterComponentXDRPortType;\nimport gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;\nimport gov.hhs.fha.nhinc.common.nhinccommonadapter.AdapterProvideAndRegisterDocumentSetRequestType;\nimport gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy.service.AdapterComponentDocSubmissionServicePortDescriptor;\nimport gov.hhs.fha.nhinc.event.error.ErrorEventException;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTCXFClientFactory;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTClient;\nimport gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;\nimport gov.hhs.fha.nhinc.nhinclib.NhincConstants;\nimport gov.hhs.fha.nhinc.nhinclib.NullChecker;\nimport gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;\nimport ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;\nimport javax.xml.ws.WebServiceException;\nimport oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * @author jhoppesc\n */\npublic class AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl implements AdapterComponentDocSubmissionProxy {\n\n private static final Logger LOG = LoggerFactory.getLogger(AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.class);\n\n private WebServiceProxyHelper oProxyHelper = new WebServiceProxyHelper();\n\n protected CONNECTClient getCONNECTClientUnsecured(ServicePortDescriptor portDescriptor, String url, AssertionType assertion) {\n return CONNECTCXFClientFactory.getInstance().getCONNECTClientUnsecured(portDescriptor, url, assertion);\n }\n\n @Override\n public RegistryResponseType provideAndRegisterDocumentSetB(ProvideAndRegisterDocumentSetRequestType msg, AssertionType assertion) {\n LOG.debug(\"Begin provideAndRegisterDocumentSetB\");\n RegistryResponseType response = null;\n try {\n String url = oProxyHelper.getAdapterEndPointFromConnectionManager(NhincConstants.ADAPTER_COMPONENT_XDR_SERVICE_NAME);\n if (NullChecker.isNotNullish(url)) {\n if (msg == null) {\n throw new IllegalArgumentException(\"Request Message must be provided\");\n } else if (assertion == null) {\n throw new IllegalArgumentException(\"Assertion must be provided\");\n } else {\n AdapterProvideAndRegisterDocumentSetRequestType request = new AdapterProvideAndRegisterDocumentSetRequestType();\n request.setProvideAndRegisterDocumentSetRequest(msg);\n request.setAssertion(assertion);\n ServicePortDescriptor portDescriptor = new AdapterComponentDocSubmissionServicePortDescriptor();\n CONNECTClient client = getCONNECTClientUnsecured(portDescriptor, url, assertion);\n client.enableMtom();\n response = (RegistryResponseType) client.invokePort(AdapterComponentXDRPortType.class, \"provideAndRegisterDocumentSetb\", request);\n }\n } else {\n throw new WebServiceException(\"Could not determine URL for Doc Submission Adapter Component endpoint\");\n }\n } catch (Exception ex) {\n response = new RegistryResponseType();\n response.setStatus(\"urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Failure\");\n throw new ErrorEventException(ex, response, \"Unable to call Doc Submission Adapter Component\");\n }\n LOG.debug(\"End provideAndRegisterDocumentSe", "post_mask_code": "\n return response;\n }\n}\n"} {"task_id": "Java_500", "language": "Java", "task_type": "empty", "source_file": "java/github/CONNECT-Solution/CONNECT/Product/Production/Services/DocumentSubmissionCore/src/main/java/gov/hhs/fha/nhinc/docsubmission/adapter/component/proxy/AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.java", "mask_start_position": 555, "mask_end_position": 555, "canonical_solution": "", "pre_mask_code": "/*\n * All rights reserved.\n * \n*/\npackage gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy;\n\nimport gov.hhs.fha.nhinc.adaptercomponentxdr.AdapterComponentXDRPortType;\nimport gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;\nimport gov.hhs.fha.nhinc.common.nhinccommonadapter.AdapterProvideAndRegisterDocumentSetRequestType;\nimport gov.hhs.fha.nhinc.docsubmission.adapter.component.proxy.service.AdapterComponentDocSubmissionServicePortDescriptor;\nimport gov.hhs.fha.nhinc.event.error.ErrorEventException;\nimport gov.hhs.fha.nhinc.messaging.clien", "post_mask_code": "t.CONNECTCXFClientFactory;\nimport gov.hhs.fha.nhinc.messaging.client.CONNECTClient;\nimport gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;\nimport gov.hhs.fha.nhinc.nhinclib.NhincConstants;\nimport gov.hhs.fha.nhinc.nhinclib.NullChecker;\nimport gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;\nimport ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;\nimport javax.xml.ws.WebServiceException;\nimport oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * @author jhoppesc\n */\npublic class AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl implements AdapterComponentDocSubmissionProxy {\n\n private static final Logger LOG = LoggerFactory.getLogger(AdapterComponentDocSubmissionProxyWebServiceUnsecuredImpl.class);\n\n private WebServiceProxyHelper oProxyHelper = new WebServiceProxyHelper();\n\n protected CONNECTClient getCONNECTClientUnsecured(ServicePortDescriptor portDescriptor, String url, AssertionType assertion) {\n return CONNECTCXFClientFactory.getInstance().getCONNECTClientUnsecured(portDescriptor, url, assertion);\n }\n\n @Override\n public RegistryResponseType provideAndRegisterDocumentSetB(ProvideAndRegisterDocumentSetRequestType msg, AssertionType assertion) {\n LOG.debug(\"Begin provideAndRegisterDocumentSetB\");\n RegistryResponseType response = null;\n try {\n String url = oProxyHelper.getAdapterEndPointFromConnectionManager(NhincConstants.ADAPTER_COMPONENT_XDR_SERVICE_NAME);\n if (NullChecker.isNotNullish(url)) {\n if (msg == null) {\n throw new IllegalArgumentException(\"Request Message must be provided\");\n } else if (assertion == null) {\n throw new IllegalArgumentException(\"Assertion must be provided\");\n } else {\n AdapterProvideAndRegisterDocumentSetRequestType request = new AdapterProvideAndRegisterDocumentSetRequestType();\n request.setProvideAndRegisterDocumentSetRequest(msg);\n request.setAssertion(assertion);\n ServicePortDescriptor portDescriptor = new AdapterComponentDocSubmissionServicePortDescriptor();\n CONNECTClient client = getCONNECTClientUnsecured(portDescriptor, url, assertion);\n client.enableMtom();\n response = (RegistryResponseType) client.invokePort(AdapterComponentXDRPortType.class, \"provideAndRegisterDocumentSetb\", request);\n }\n } else {\n throw new WebServiceException(\"Could not determine URL for Doc Submission Adapter Component endpoint\");\n }\n } catch (Exception ex) {\n response = new RegistryResponseType();\n response.setStatus(\"urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Failure\");\n throw new ErrorEventException(ex, response, \"Unable to call Doc Submission Adapter Component\");\n }\n LOG.debug(\"End provideAndRegisterDocumentSetB\");\n return response;\n }\n}\n"} {"task_id": "Java_501", "language": "Java", "task_type": "method_signature", "source_file": "java/github/wxiaoqi/Spring-Cloud-Platform/ace-modules/ace-generator/src/main/java/com/github/wxiaoqi/security/generator/config/DataSourceConfigurer.java", "mask_start_position": 725, "mask_end_position": 847, "canonical_solution": "@Bean(\"Admin数据库\")\n @ConfigurationProperties(prefix = \"spring.datasource\")\n public DruidDataSource adminDatasource() ", "pre_mask_code": "package com.github.wxiaoqi.security.generator.config;\n\nimport com.alibaba.druid.pool.DruidDataSource;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.boot.jdbc.DataSourceBuilder;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n/**\n * 数据源配置类,在tomcat启动时触发,在该类中生成多个数据源实例并将其注入到 ApplicationContext 中\n * @author lxf 2018-09-27\n */\n@Configuration\npublic class DataSourceConfigurer {\n\n @Bean(\"Sample数据库\")\n @ConfigurationProperties(prefix = \"spring.sample-datasource\")\n public DruidDataSource sampleDatasource() {\n return DataSourceBuilder.create().type(DruidDataSource.class).build();\n }\n\n ", "post_mask_code": "{\n return DataSourceBuilder.create().type(DruidDataSource.class).build();\n }\n}\n"} {"task_id": "Java_502", "language": "Java", "task_type": "method_body", "source_file": "java/github/wxiaoqi/Spring-Cloud-Platform/ace-modules/ace-generator/src/main/java/com/github/wxiaoqi/security/generator/config/DataSourceConfigurer.java", "mask_start_position": 633, "mask_end_position": 719, "canonical_solution": "{\n return DataSourceBuilder.create().type(DruidDataSource.class).build();\n }", "pre_mask_code": "package com.github.wxiaoqi.security.generator.config;\n\nimport com.alibaba.druid.pool.DruidDataSource;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.boot.jdbc.DataSourceBuilder;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n/**\n * 数据源配置类,在tomcat启动时触发,在该类中生成多个数据源实例并将其注入到 ApplicationContext 中\n * @author lxf 2018-09-27\n */\n@Configuration\npublic class DataSourceConfigurer {\n\n @Bean(\"Sample数据库\")\n @ConfigurationProperties(prefix = \"spring.sample-datasource\")\n public DruidDataSource sampleDatasource() ", "post_mask_code": "\n\n @Bean(\"Admin数据库\")\n @ConfigurationProperties(prefix = \"spring.datasource\")\n public DruidDataSource adminDatasource() {\n return DataSourceBuilder.create().type(DruidDataSource.class).build();\n }\n}\n"} {"task_id": "Java_503", "language": "Java", "task_type": "single_line", "source_file": "java/github/wxiaoqi/Spring-Cloud-Platform/ace-modules/ace-generator/src/main/java/com/github/wxiaoqi/security/generator/config/DataSourceConfigurer.java", "mask_start_position": 881, "mask_end_position": 927, "canonical_solution": ".create().type(DruidDataSource.class).build();", "pre_mask_code": "package com.github.wxiaoqi.security.generator.config;\n\nimport com.alibaba.druid.pool.DruidDataSource;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.boot.jdbc.DataSourceBuilder;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n/**\n * 数据源配置类,在tomcat启动时触发,在该类中生成多个数据源实例并将其注入到 ApplicationContext 中\n * @author lxf 2018-09-27\n */\n@Configuration\npublic class DataSourceConfigurer {\n\n @Bean(\"Sample数据库\")\n @ConfigurationProperties(prefix = \"spring.sample-datasource\")\n public DruidDataSource sampleDatasource() {\n return DataSourceBuilder.create().type(DruidDataSource.class).build();\n }\n\n @Bean(\"Admin数据库\")\n @ConfigurationProperties(prefix = \"spring.datasource\")\n public DruidDataSource adminDatasource() {\n return DataSourceBuilder", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_504", "language": "Java", "task_type": "empty", "source_file": "java/github/wxiaoqi/Spring-Cloud-Platform/ace-modules/ace-generator/src/main/java/com/github/wxiaoqi/security/generator/config/DataSourceConfigurer.java", "mask_start_position": 916, "mask_end_position": 916, "canonical_solution": "", "pre_mask_code": "package com.github.wxiaoqi.security.generator.config;\n\nimport com.alibaba.druid.pool.DruidDataSource;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.boot.jdbc.DataSourceBuilder;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n/**\n * 数据源配置类,在tomcat启动时触发,在该类中生成多个数据源实例并将其注入到 ApplicationContext 中\n * @author lxf 2018-09-27\n */\n@Configuration\npublic class DataSourceConfigurer {\n\n @Bean(\"Sample数据库\")\n @ConfigurationProperties(prefix = \"spring.sample-datasource\")\n public DruidDataSource sampleDatasource() {\n return DataSourceBuilder.create().type(DruidDataSource.class).build();\n }\n\n @Bean(\"Admin数据库\")\n @ConfigurationProperties(prefix = \"spring.datasource\")\n public DruidDataSource adminDatasource() {\n return DataSourceBuilder.create().type(DruidDataSource.clas", "post_mask_code": "s).build();\n }\n}\n"} {"task_id": "Java_505", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jwhitbeck/dendrite/dendrite/java-src/dendrite/java/FileReader.java", "mask_start_position": 11214, "mask_end_position": 11316, "canonical_solution": "private static MetadataReadResult readMetadata(File file, FileChannel fileChannel) throws IOException ", "pre_mask_code": "package dendrite.java;\n\nimport clojure.lang.Agent;\nimport clojure.lang.IFn;\nimport clojure.lang.IPersistentMap;\nimport clojure.lang.IPersistentVector;\nimport clojure.lang.Keyword;\nimport clojure.lang.PersistentArrayMap;\nimport clojure.lang.Symbol;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\n\npublic final class FileReader implements Closeable, IReader {\n\n public static final Keyword RECORD_GROUPS = Keyword.intern(\"record-groups\"), COLUMNS = Keyword.intern(\"columns\"), GLOBAL = Keyword.intern(\"global\"), DATA_HEADER_LENGTH = Keyword.intern(\"data-header-length\"), REPETITION_LEVELS_LENGTH = Keyword.intern(\"repetition-levels-length\"), DEFINITION_LEVELS_LENGTH = Keyword.intern(\"definition-levels-length\"), METADATA_LENGTH = Keyword.intern(\"metadata-length\"), DATA_LENGTH = Keyword.intern(\"data-length\"), DICTIONARY_HEADER_LENGTH = Keyword.intern(\"dictionary-header-length\"), DICTIONARY_LENGTH = Keyword.intern(\"dictionary-length\"), NUM_VALUES = Keyword.intern(\"num-values\"), NUM_NON_NIL_VALUES = Keyword.intern(\"num-non-nil-values\"), LENGTH = Keyword.intern(\"length\"), NUM_PAGES = Keyword.intern(\"num-pages\"), NUM_DICTIONARY_VALUES = Keyword.intern(\"num-dictionary-values\"), TYPE = Keyword.intern(\"type\"), ENCODING = Keyword.intern(\"encoding\"), COMPRESSION = Keyword.intern(\"compression\"), MAX_REPETITION_LEVEL = Keyword.intern(\"max-repetition-level\"), MAX_DEFINITION_LEVEL = Keyword.intern(\"max-definition-level\"), PATH = Keyword.intern(\"path\"), NUM_RECORDS = Keyword.intern(\"num-records\"), NUM_RECORD_GROUPS = Keyword.intern(\"num-record-groups\"), NUM_COLUMN_CHUNKS = Keyword.intern(\"num-column-chunks\"), NUM_COLUMNS = Keyword.intern(\"num-columns\");\n\n final Types types;\n\n final File file;\n\n final FileChannel fileChannel;\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n private FileReader(Types types, File file, FileChannel fileChannel, Metadata.File fileMetadata, long metadataLength) {\n this.types = types;\n this.file = file;\n this.fileChannel = fileChannel;\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n\n public static FileReader create(Options.ReaderOptions options, File file) throws IOException {\n FileChannel fileChannel = Utils.getReadingFileChannel(file);\n MetadataReadResult res = readMetadata(file, fileChannel);\n Types types = Types.create(options.customTypeDefinitions, res.fileMetadata.customTypes);\n return new FileReader(types, file, fileChannel, res.fileMetadata, res.metadataLength);\n }\n\n public ByteBuffer getMetadata() {\n return fileMetadata.metadata;\n }\n\n public long getNumRecords() {\n return fileMetadata.getNumRecords();\n }\n\n public Map getCustomTypeMappings() {\n Map customTypeMappings = new HashMap();\n for (CustomType ct : fileMetadata.customTypes) {\n customTypeMappings.put(ct.sym, types.getTypeSymbol(ct.baseType));\n }\n return customTypeMappings;\n }\n\n Schema.QueryResult getQueryResult(Options.ReadOptions options) {\n return Schema.applyQuery(types, options.isMissingFieldsAsNil, options.readers, Schema.getSubSchema(options.subSchemaPath, fileMetadata.schema), options.query);\n }\n\n @Override\n public View read(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n private Iterator getRecordGroupReaders(Schema.Column[] columns, int bundleSize) {\n return getRecordGroupReaders(types, fileChannel, Constants.magicBytes.length, fileMetadata.recordGroups, columns, bundleSize);\n }\n\n private static Iterator getRecordGroupReaders(final Types types, final FileChannel fileChannel, final long offset, final Metadata.RecordGroup[] recordGroupsMetadata, final Schema.Column[] queriedColumns, final int bundleSize) {\n final int numRecordGroups = recordGroupsMetadata.length;\n if (numRecordGroups == 0) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n int i = 0;\n\n long nextOffset = offset;\n\n @Override\n public boolean hasNext() {\n return i < numRecordGroups;\n }\n\n @Override\n public RecordGroup.Reader next() {\n Metadata.RecordGroup recordGroupMetadata = recordGroupsMetadata[i];\n long length = recordGroupMetadata.length;\n ByteBuffer bb;\n try {\n bb = Utils.mapFileChannel(fileChannel, nextOffset, length);\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n RecordGroup.Reader recordGroupReader = new RecordGroup.Reader(types, bb, recordGroupMetadata, queriedColumns, bundleSize);\n nextOffset += length;\n i += 1;\n return recordGroupReader;\n }\n };\n }\n\n private IPersistentMap asPersistentMap(Stats.Global globalStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_COLUMNS, globalStats.numColumns).assoc(NUM_RECORD_GROUPS, globalStats.numRecordGroups).assoc(NUM_RECORDS, globalStats.numRecords).assoc(LENGTH, globalStats.length).assoc(DATA_HEADER_LENGTH, globalStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, globalStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, globalStats.definitionLevelsLength).assoc(DATA_LENGTH, globalStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, globalStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, globalStats.dictionaryLength).assoc(METADATA_LENGTH, globalStats.metadataLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.Column columnStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(TYPE, columnStats.type).assoc(ENCODING, columnStats.encoding).assoc(COMPRESSION, columnStats.compression).assoc(PATH, columnStats.path).assoc(MAX_REPETITION_LEVEL, columnStats.maxRepetitionLevel).assoc(MAX_DEFINITION_LEVEL, columnStats.maxDefinitionLevel).assoc(NUM_COLUMN_CHUNKS, columnStats.numColumnChunks).assoc(NUM_PAGES, columnStats.numPages).assoc(NUM_VALUES, columnStats.numValues).assoc(NUM_NON_NIL_VALUES, columnStats.numNonNilValues).assoc(LENGTH, columnStats.length).assoc(DATA_HEADER_LENGTH, columnStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, columnStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, columnStats.definitionLevelsLength).assoc(DATA_LENGTH, columnStats.dataLength).assoc(NUM_DICTIONARY_VALUES, columnStats.numDictionaryValues).assoc(DICTIONARY_HEADER_LENGTH, columnStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, columnStats.dictionaryLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.RecordGroup recordGroupStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_RECORDS, recordGroupStats.numRecords).assoc(NUM_COLUMN_CHUNKS, recordGroupStats.numColumnChunks).assoc(LENGTH, recordGroupStats.length).assoc(DATA_HEADER_LENGTH, recordGroupStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, recordGroupStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, recordGroupStats.definitionLevelsLength).assoc(DATA_LENGTH, recordGroupStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, recordGroupStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, recordGroupStats.dictionaryLength).persistent();\n }\n\n public IPersistentMap getStats() throws IOException {\n IPersistentVector[] paths = Schema.getPaths(fileMetadata.schema);\n Schema.Column[] columns = Schema.getColumns(fileMetadata.schema);\n List recordGroupsStats = new ArrayList();\n List> columnChunkStatsByColumn = new ArrayList>(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n columnChunkStatsByColumn.add(new ArrayList());\n }\n Iterator recordGroupReaders = getRecordGroupReaders(columns, 100);\n while (recordGroupReaders.hasNext()) {\n RecordGroup.Reader recordGroupReader = recordGroupReaders.next();\n List columnChunksStats = recordGroupReader.getColumnChunkStats();\n recordGroupsStats.add(Stats.createRecordGroupStats(recordGroupReader.getNumRecords(), columnChunksStats));\n int i = 0;\n for (Stats.ColumnChunk columnChunkStats : columnChunksStats) {\n columnChunkStatsByColumn.get(i).add(columnChunkStats);\n i += 1;\n }\n }\n List columnsStats = new ArrayList(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n Schema.Column col = columns[i];\n columnsStats.add(Stats.createColumnStats(types.getTypeSymbol(col.type), types.getEncodingSymbol(col.encoding), types.getCompressionSymbol(col.compression), col.repetitionLevel, col.definitionLevel, paths[i], columnChunkStatsByColumn.get(i)));\n }\n List recordGroupStatsMaps = new ArrayList();\n for (Stats.RecordGroup recordGroupStats : recordGroupsStats) {\n recordGroupStatsMaps.add(asPersistentMap(recordGroupStats));\n }\n List columnStatsMaps = new ArrayList();\n for (Stats.Column columnStats : columnsStats) {\n columnStatsMaps.add(asPersistentMap(columnStats));\n }\n IPersistentMap globalStatsMap = asPersistentMap(Stats.createGlobalStats(fileChannel.size(), metadataLength, columns.length, recordGroupsStats));\n return new PersistentArrayMap(new Object[] { RECORD_GROUPS, recordGroupStatsMaps, COLUMNS, columnStatsMaps, GLOBAL, globalStatsMap });\n }\n\n public Object getSchema() {\n return Schema.unparse(types, fileMetadata.schema);\n }\n\n public Object getPlainSchema() {\n return Schema.unparsePlain(types, fileMetadata.schema);\n }\n\n @Override\n public void close() throws IOException {\n fileChannel.close();\n }\n\n private static boolean isValidMagicBytes(ByteBuffer bb) {\n return Arrays.equals(Constants.magicBytes, Types.toByteArray(bb));\n }\n\n private static final int fixedIntLength = 4;\n\n private static final class MetadataReadResult {\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n MetadataReadResult(Metadata.File fileMetadata, long metadataLength) {\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n }\n\n ", "post_mask_code": "{\n long length = fileChannel.size();\n long lastMagicBytesPosition = length - Constants.magicBytes.length;\n ByteBuffer lastMagicBytesBuffer = Utils.mapFileChannel(fileChannel, lastMagicBytesPosition, Constants.magicBytes.length);\n if (!isValidMagicBytes(lastMagicBytesBuffer)) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n long metadataLengthPosition = lastMagicBytesPosition - fixedIntLength;\n if (metadataLengthPosition < Constants.magicBytes.length) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataLengthBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition, fixedIntLength);\n metadataLengthBuffer.order(ByteOrder.LITTLE_ENDIAN);\n long metadataLength = metadataLengthBuffer.getInt();\n if (metadataLength <= 0) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition - metadataLength, metadataLength);\n return new MetadataReadResult(Metadata.File.read(metadataBuffer), metadataLength);\n }\n\n private static Iterator getBundlesIterator(final File file, final Iterator recordGroupReaders) {\n if (!recordGroupReaders.hasNext()) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n private Iterator bundleIterator = recordGroupReaders.next().iterator();\n\n private void step() {\n if (recordGroupReaders.hasNext()) {\n bundleIterator = recordGroupReaders.next().iterator();\n } else {\n bundleIterator = null;\n }\n }\n\n @Override\n public boolean hasNext() {\n if (bundleIterator == null) {\n return false;\n }\n try {\n if (bundleIterator.hasNext()) {\n return true;\n } else {\n step();\n return bundleIterator != null && bundleIterator.hasNext();\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Error while reading from \" + file, e);\n }\n }\n\n @Override\n public Bundle next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return bundleIterator.next();\n }\n };\n }\n\n private interface IReduceFutureFactory {\n\n Future get(Bundle bundle);\n }\n\n private static final class ReduceFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n ReduceFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduce(reduceFn, completeFn, initFn, assembleFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n ReduceSampledFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampled(reduceFn, completeFn, initFn, assembleFn, sampleFn);\n }\n });\n }\n }\n\n private static final class ReduceIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn indexedByFn;\n\n ReduceIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceIndexed(reduceFn, completeFn, initFn, assembleFn, indexedByFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledAndIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n private final IFn indexedByFn;\n\n ReduceSampledAndIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampledAndIndexed(reduceFn, completeFn, initFn, assembleFn, sampleFn, indexedByFn);\n }\n });\n }\n }\n\n private IReduceFutureFactory getReduceFutureFactory(IFn reduceFn, IFn completeFn, IFn initFn, Assemble.Fn assembleFn, IFn sampleFn, IFn indexedByFn) {\n if (sampleFn == null) {\n if (indexedByFn == null) {\n return new ReduceFutureFactory(assembleFn, reduceFn, completeFn, initFn);\n } else {\n return new ReduceIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, indexedByFn);\n }\n } else {\n if (indexedByFn == null) {\n return new ReduceSampledFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn);\n } else {\n return new ReduceSampledAndIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn, indexedByFn);\n }\n }\n }\n\n private static Iterator getReducedChunksIterator(final Iterator bundlesIterator, final IReduceFutureFactory reduceFutureFactory) {\n int n = 2 + Runtime.getRuntime().availableProcessors();\n final LinkedList> futures = new LinkedList>();\n int k = 0;\n while (bundlesIterator.hasNext() && k < n) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n k += 1;\n }\n return new AReadOnlyIterator() {\n\n @Override\n public boolean hasNext() {\n return !futures.isEmpty();\n }\n\n @Override\n public Object next() {\n Future fut = futures.pollFirst();\n Object obj = Utils.tryGetFuture(fut);\n if (bundlesIterator.hasNext()) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n }\n return obj;\n }\n };\n }\n\n public final class LazyView extends View {\n\n private Options.ReadOptions options;\n\n private Schema.QueryResult queryResult;\n\n private Assemble.Fn assembleFn;\n\n LazyView(Options.ReadOptions options) {\n super(options.bundleSize);\n this.options = options;\n }\n\n private synchronized Schema.QueryResult getQueryResult() {\n if (queryResult == null) {\n queryResult = FileReader.this.getQueryResult(options);\n }\n return queryResult;\n }\n\n private synchronized Schema.Column[] getQueriedColumns() {\n return getQueryResult().columns;\n }\n\n private synchronized Assemble.Fn getAssembleFn() {\n if (assembleFn == null) {\n assembleFn = Assemble.getFn(FileReader.this.types, getQueryResult().schema);\n }\n return assembleFn;\n }\n\n @Override\n protected View withOptions(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n @Override\n protected Options.ReadOptions getReadOptions() {\n return options;\n }\n\n @Override\n protected Iterable getReducedChunks(final IFn reduceFn, final IFn completeFn, final IFn initFn, final int bundleSize) {\n return new Iterable() {\n\n @Override\n public Iterator iterator() {\n return FileReader.getReducedChunksIterator(getBundlesIterator(bundleSize), getReduceFutureFactory(reduceFn, completeFn, initFn, getAssembleFn(), options.sampleFn, options.indexedByFn));\n }\n };\n }\n\n private Iterator getBundlesIterator(int bundleSize) {\n return FileReader.getBundlesIterator(FileReader.this.file, getRecordGroupReaders(getQueriedColumns(), bundleSize));\n }\n }\n}\n"} {"task_id": "Java_506", "language": "Java", "task_type": "method_body", "source_file": "java/github/jwhitbeck/dendrite/dendrite/java-src/dendrite/java/FileReader.java", "mask_start_position": 3227, "mask_end_position": 3494, "canonical_solution": "{\n Map customTypeMappings = new HashMap();\n for (CustomType ct : fileMetadata.customTypes) {\n customTypeMappings.put(ct.sym, types.getTypeSymbol(ct.baseType));\n }\n return customTypeMappings;\n }", "pre_mask_code": "package dendrite.java;\n\nimport clojure.lang.Agent;\nimport clojure.lang.IFn;\nimport clojure.lang.IPersistentMap;\nimport clojure.lang.IPersistentVector;\nimport clojure.lang.Keyword;\nimport clojure.lang.PersistentArrayMap;\nimport clojure.lang.Symbol;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\n\npublic final class FileReader implements Closeable, IReader {\n\n public static final Keyword RECORD_GROUPS = Keyword.intern(\"record-groups\"), COLUMNS = Keyword.intern(\"columns\"), GLOBAL = Keyword.intern(\"global\"), DATA_HEADER_LENGTH = Keyword.intern(\"data-header-length\"), REPETITION_LEVELS_LENGTH = Keyword.intern(\"repetition-levels-length\"), DEFINITION_LEVELS_LENGTH = Keyword.intern(\"definition-levels-length\"), METADATA_LENGTH = Keyword.intern(\"metadata-length\"), DATA_LENGTH = Keyword.intern(\"data-length\"), DICTIONARY_HEADER_LENGTH = Keyword.intern(\"dictionary-header-length\"), DICTIONARY_LENGTH = Keyword.intern(\"dictionary-length\"), NUM_VALUES = Keyword.intern(\"num-values\"), NUM_NON_NIL_VALUES = Keyword.intern(\"num-non-nil-values\"), LENGTH = Keyword.intern(\"length\"), NUM_PAGES = Keyword.intern(\"num-pages\"), NUM_DICTIONARY_VALUES = Keyword.intern(\"num-dictionary-values\"), TYPE = Keyword.intern(\"type\"), ENCODING = Keyword.intern(\"encoding\"), COMPRESSION = Keyword.intern(\"compression\"), MAX_REPETITION_LEVEL = Keyword.intern(\"max-repetition-level\"), MAX_DEFINITION_LEVEL = Keyword.intern(\"max-definition-level\"), PATH = Keyword.intern(\"path\"), NUM_RECORDS = Keyword.intern(\"num-records\"), NUM_RECORD_GROUPS = Keyword.intern(\"num-record-groups\"), NUM_COLUMN_CHUNKS = Keyword.intern(\"num-column-chunks\"), NUM_COLUMNS = Keyword.intern(\"num-columns\");\n\n final Types types;\n\n final File file;\n\n final FileChannel fileChannel;\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n private FileReader(Types types, File file, FileChannel fileChannel, Metadata.File fileMetadata, long metadataLength) {\n this.types = types;\n this.file = file;\n this.fileChannel = fileChannel;\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n\n public static FileReader create(Options.ReaderOptions options, File file) throws IOException {\n FileChannel fileChannel = Utils.getReadingFileChannel(file);\n MetadataReadResult res = readMetadata(file, fileChannel);\n Types types = Types.create(options.customTypeDefinitions, res.fileMetadata.customTypes);\n return new FileReader(types, file, fileChannel, res.fileMetadata, res.metadataLength);\n }\n\n public ByteBuffer getMetadata() {\n return fileMetadata.metadata;\n }\n\n public long getNumRecords() {\n return fileMetadata.getNumRecords();\n }\n\n public Map getCustomTypeMappings() ", "post_mask_code": "\n\n Schema.QueryResult getQueryResult(Options.ReadOptions options) {\n return Schema.applyQuery(types, options.isMissingFieldsAsNil, options.readers, Schema.getSubSchema(options.subSchemaPath, fileMetadata.schema), options.query);\n }\n\n @Override\n public View read(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n private Iterator getRecordGroupReaders(Schema.Column[] columns, int bundleSize) {\n return getRecordGroupReaders(types, fileChannel, Constants.magicBytes.length, fileMetadata.recordGroups, columns, bundleSize);\n }\n\n private static Iterator getRecordGroupReaders(final Types types, final FileChannel fileChannel, final long offset, final Metadata.RecordGroup[] recordGroupsMetadata, final Schema.Column[] queriedColumns, final int bundleSize) {\n final int numRecordGroups = recordGroupsMetadata.length;\n if (numRecordGroups == 0) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n int i = 0;\n\n long nextOffset = offset;\n\n @Override\n public boolean hasNext() {\n return i < numRecordGroups;\n }\n\n @Override\n public RecordGroup.Reader next() {\n Metadata.RecordGroup recordGroupMetadata = recordGroupsMetadata[i];\n long length = recordGroupMetadata.length;\n ByteBuffer bb;\n try {\n bb = Utils.mapFileChannel(fileChannel, nextOffset, length);\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n RecordGroup.Reader recordGroupReader = new RecordGroup.Reader(types, bb, recordGroupMetadata, queriedColumns, bundleSize);\n nextOffset += length;\n i += 1;\n return recordGroupReader;\n }\n };\n }\n\n private IPersistentMap asPersistentMap(Stats.Global globalStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_COLUMNS, globalStats.numColumns).assoc(NUM_RECORD_GROUPS, globalStats.numRecordGroups).assoc(NUM_RECORDS, globalStats.numRecords).assoc(LENGTH, globalStats.length).assoc(DATA_HEADER_LENGTH, globalStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, globalStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, globalStats.definitionLevelsLength).assoc(DATA_LENGTH, globalStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, globalStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, globalStats.dictionaryLength).assoc(METADATA_LENGTH, globalStats.metadataLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.Column columnStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(TYPE, columnStats.type).assoc(ENCODING, columnStats.encoding).assoc(COMPRESSION, columnStats.compression).assoc(PATH, columnStats.path).assoc(MAX_REPETITION_LEVEL, columnStats.maxRepetitionLevel).assoc(MAX_DEFINITION_LEVEL, columnStats.maxDefinitionLevel).assoc(NUM_COLUMN_CHUNKS, columnStats.numColumnChunks).assoc(NUM_PAGES, columnStats.numPages).assoc(NUM_VALUES, columnStats.numValues).assoc(NUM_NON_NIL_VALUES, columnStats.numNonNilValues).assoc(LENGTH, columnStats.length).assoc(DATA_HEADER_LENGTH, columnStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, columnStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, columnStats.definitionLevelsLength).assoc(DATA_LENGTH, columnStats.dataLength).assoc(NUM_DICTIONARY_VALUES, columnStats.numDictionaryValues).assoc(DICTIONARY_HEADER_LENGTH, columnStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, columnStats.dictionaryLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.RecordGroup recordGroupStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_RECORDS, recordGroupStats.numRecords).assoc(NUM_COLUMN_CHUNKS, recordGroupStats.numColumnChunks).assoc(LENGTH, recordGroupStats.length).assoc(DATA_HEADER_LENGTH, recordGroupStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, recordGroupStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, recordGroupStats.definitionLevelsLength).assoc(DATA_LENGTH, recordGroupStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, recordGroupStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, recordGroupStats.dictionaryLength).persistent();\n }\n\n public IPersistentMap getStats() throws IOException {\n IPersistentVector[] paths = Schema.getPaths(fileMetadata.schema);\n Schema.Column[] columns = Schema.getColumns(fileMetadata.schema);\n List recordGroupsStats = new ArrayList();\n List> columnChunkStatsByColumn = new ArrayList>(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n columnChunkStatsByColumn.add(new ArrayList());\n }\n Iterator recordGroupReaders = getRecordGroupReaders(columns, 100);\n while (recordGroupReaders.hasNext()) {\n RecordGroup.Reader recordGroupReader = recordGroupReaders.next();\n List columnChunksStats = recordGroupReader.getColumnChunkStats();\n recordGroupsStats.add(Stats.createRecordGroupStats(recordGroupReader.getNumRecords(), columnChunksStats));\n int i = 0;\n for (Stats.ColumnChunk columnChunkStats : columnChunksStats) {\n columnChunkStatsByColumn.get(i).add(columnChunkStats);\n i += 1;\n }\n }\n List columnsStats = new ArrayList(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n Schema.Column col = columns[i];\n columnsStats.add(Stats.createColumnStats(types.getTypeSymbol(col.type), types.getEncodingSymbol(col.encoding), types.getCompressionSymbol(col.compression), col.repetitionLevel, col.definitionLevel, paths[i], columnChunkStatsByColumn.get(i)));\n }\n List recordGroupStatsMaps = new ArrayList();\n for (Stats.RecordGroup recordGroupStats : recordGroupsStats) {\n recordGroupStatsMaps.add(asPersistentMap(recordGroupStats));\n }\n List columnStatsMaps = new ArrayList();\n for (Stats.Column columnStats : columnsStats) {\n columnStatsMaps.add(asPersistentMap(columnStats));\n }\n IPersistentMap globalStatsMap = asPersistentMap(Stats.createGlobalStats(fileChannel.size(), metadataLength, columns.length, recordGroupsStats));\n return new PersistentArrayMap(new Object[] { RECORD_GROUPS, recordGroupStatsMaps, COLUMNS, columnStatsMaps, GLOBAL, globalStatsMap });\n }\n\n public Object getSchema() {\n return Schema.unparse(types, fileMetadata.schema);\n }\n\n public Object getPlainSchema() {\n return Schema.unparsePlain(types, fileMetadata.schema);\n }\n\n @Override\n public void close() throws IOException {\n fileChannel.close();\n }\n\n private static boolean isValidMagicBytes(ByteBuffer bb) {\n return Arrays.equals(Constants.magicBytes, Types.toByteArray(bb));\n }\n\n private static final int fixedIntLength = 4;\n\n private static final class MetadataReadResult {\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n MetadataReadResult(Metadata.File fileMetadata, long metadataLength) {\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n }\n\n private static MetadataReadResult readMetadata(File file, FileChannel fileChannel) throws IOException {\n long length = fileChannel.size();\n long lastMagicBytesPosition = length - Constants.magicBytes.length;\n ByteBuffer lastMagicBytesBuffer = Utils.mapFileChannel(fileChannel, lastMagicBytesPosition, Constants.magicBytes.length);\n if (!isValidMagicBytes(lastMagicBytesBuffer)) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n long metadataLengthPosition = lastMagicBytesPosition - fixedIntLength;\n if (metadataLengthPosition < Constants.magicBytes.length) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataLengthBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition, fixedIntLength);\n metadataLengthBuffer.order(ByteOrder.LITTLE_ENDIAN);\n long metadataLength = metadataLengthBuffer.getInt();\n if (metadataLength <= 0) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition - metadataLength, metadataLength);\n return new MetadataReadResult(Metadata.File.read(metadataBuffer), metadataLength);\n }\n\n private static Iterator getBundlesIterator(final File file, final Iterator recordGroupReaders) {\n if (!recordGroupReaders.hasNext()) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n private Iterator bundleIterator = recordGroupReaders.next().iterator();\n\n private void step() {\n if (recordGroupReaders.hasNext()) {\n bundleIterator = recordGroupReaders.next().iterator();\n } else {\n bundleIterator = null;\n }\n }\n\n @Override\n public boolean hasNext() {\n if (bundleIterator == null) {\n return false;\n }\n try {\n if (bundleIterator.hasNext()) {\n return true;\n } else {\n step();\n return bundleIterator != null && bundleIterator.hasNext();\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Error while reading from \" + file, e);\n }\n }\n\n @Override\n public Bundle next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return bundleIterator.next();\n }\n };\n }\n\n private interface IReduceFutureFactory {\n\n Future get(Bundle bundle);\n }\n\n private static final class ReduceFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n ReduceFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduce(reduceFn, completeFn, initFn, assembleFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n ReduceSampledFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampled(reduceFn, completeFn, initFn, assembleFn, sampleFn);\n }\n });\n }\n }\n\n private static final class ReduceIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn indexedByFn;\n\n ReduceIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceIndexed(reduceFn, completeFn, initFn, assembleFn, indexedByFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledAndIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n private final IFn indexedByFn;\n\n ReduceSampledAndIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampledAndIndexed(reduceFn, completeFn, initFn, assembleFn, sampleFn, indexedByFn);\n }\n });\n }\n }\n\n private IReduceFutureFactory getReduceFutureFactory(IFn reduceFn, IFn completeFn, IFn initFn, Assemble.Fn assembleFn, IFn sampleFn, IFn indexedByFn) {\n if (sampleFn == null) {\n if (indexedByFn == null) {\n return new ReduceFutureFactory(assembleFn, reduceFn, completeFn, initFn);\n } else {\n return new ReduceIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, indexedByFn);\n }\n } else {\n if (indexedByFn == null) {\n return new ReduceSampledFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn);\n } else {\n return new ReduceSampledAndIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn, indexedByFn);\n }\n }\n }\n\n private static Iterator getReducedChunksIterator(final Iterator bundlesIterator, final IReduceFutureFactory reduceFutureFactory) {\n int n = 2 + Runtime.getRuntime().availableProcessors();\n final LinkedList> futures = new LinkedList>();\n int k = 0;\n while (bundlesIterator.hasNext() && k < n) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n k += 1;\n }\n return new AReadOnlyIterator() {\n\n @Override\n public boolean hasNext() {\n return !futures.isEmpty();\n }\n\n @Override\n public Object next() {\n Future fut = futures.pollFirst();\n Object obj = Utils.tryGetFuture(fut);\n if (bundlesIterator.hasNext()) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n }\n return obj;\n }\n };\n }\n\n public final class LazyView extends View {\n\n private Options.ReadOptions options;\n\n private Schema.QueryResult queryResult;\n\n private Assemble.Fn assembleFn;\n\n LazyView(Options.ReadOptions options) {\n super(options.bundleSize);\n this.options = options;\n }\n\n private synchronized Schema.QueryResult getQueryResult() {\n if (queryResult == null) {\n queryResult = FileReader.this.getQueryResult(options);\n }\n return queryResult;\n }\n\n private synchronized Schema.Column[] getQueriedColumns() {\n return getQueryResult().columns;\n }\n\n private synchronized Assemble.Fn getAssembleFn() {\n if (assembleFn == null) {\n assembleFn = Assemble.getFn(FileReader.this.types, getQueryResult().schema);\n }\n return assembleFn;\n }\n\n @Override\n protected View withOptions(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n @Override\n protected Options.ReadOptions getReadOptions() {\n return options;\n }\n\n @Override\n protected Iterable getReducedChunks(final IFn reduceFn, final IFn completeFn, final IFn initFn, final int bundleSize) {\n return new Iterable() {\n\n @Override\n public Iterator iterator() {\n return FileReader.getReducedChunksIterator(getBundlesIterator(bundleSize), getReduceFutureFactory(reduceFn, completeFn, initFn, getAssembleFn(), options.sampleFn, options.indexedByFn));\n }\n };\n }\n\n private Iterator getBundlesIterator(int bundleSize) {\n return FileReader.getBundlesIterator(FileReader.this.file, getRecordGroupReaders(getQueriedColumns(), bundleSize));\n }\n }\n}\n"} {"task_id": "Java_507", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/jwhitbeck/dendrite/dendrite/java-src/dendrite/java/FileReader.java", "mask_start_position": 18208, "mask_end_position": 18208, "canonical_solution": "", "pre_mask_code": "package dendrite.java;\n\nimport clojure.lang.Agent;\nimport clojure.lang.IFn;\nimport clojure.lang.IPersistentMap;\nimport clojure.lang.IPersistentVector;\nimport clojure.lang.Keyword;\nimport clojure.lang.PersistentArrayMap;\nimport clojure.lang.Symbol;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\n\npublic final class FileReader implements Closeable, IReader {\n\n public static final Keyword RECORD_GROUPS = Keyword.intern(\"record-groups\"), COLUMNS = Keyword.intern(\"columns\"), GLOBAL = Keyword.intern(\"global\"), DATA_HEADER_LENGTH = Keyword.intern(\"data-header-length\"), REPETITION_LEVELS_LENGTH = Keyword.intern(\"repetition-levels-length\"), DEFINITION_LEVELS_LENGTH = Keyword.intern(\"definition-levels-length\"), METADATA_LENGTH = Keyword.intern(\"metadata-length\"), DATA_LENGTH = Keyword.intern(\"data-length\"), DICTIONARY_HEADER_LENGTH = Keyword.intern(\"dictionary-header-length\"), DICTIONARY_LENGTH = Keyword.intern(\"dictionary-length\"), NUM_VALUES = Keyword.intern(\"num-values\"), NUM_NON_NIL_VALUES = Keyword.intern(\"num-non-nil-values\"), LENGTH = Keyword.intern(\"length\"), NUM_PAGES = Keyword.intern(\"num-pages\"), NUM_DICTIONARY_VALUES = Keyword.intern(\"num-dictionary-values\"), TYPE = Keyword.intern(\"type\"), ENCODING = Keyword.intern(\"encoding\"), COMPRESSION = Keyword.intern(\"compression\"), MAX_REPETITION_LEVEL = Keyword.intern(\"max-repetition-level\"), MAX_DEFINITION_LEVEL = Keyword.intern(\"max-definition-level\"), PATH = Keyword.intern(\"path\"), NUM_RECORDS = Keyword.intern(\"num-records\"), NUM_RECORD_GROUPS = Keyword.intern(\"num-record-groups\"), NUM_COLUMN_CHUNKS = Keyword.intern(\"num-column-chunks\"), NUM_COLUMNS = Keyword.intern(\"num-columns\");\n\n final Types types;\n\n final File file;\n\n final FileChannel fileChannel;\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n private FileReader(Types types, File file, FileChannel fileChannel, Metadata.File fileMetadata, long metadataLength) {\n this.types = types;\n this.file = file;\n this.fileChannel = fileChannel;\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n\n public static FileReader create(Options.ReaderOptions options, File file) throws IOException {\n FileChannel fileChannel = Utils.getReadingFileChannel(file);\n MetadataReadResult res = readMetadata(file, fileChannel);\n Types types = Types.create(options.customTypeDefinitions, res.fileMetadata.customTypes);\n return new FileReader(types, file, fileChannel, res.fileMetadata, res.metadataLength);\n }\n\n public ByteBuffer getMetadata() {\n return fileMetadata.metadata;\n }\n\n public long getNumRecords() {\n return fileMetadata.getNumRecords();\n }\n\n public Map getCustomTypeMappings() {\n Map customTypeMappings = new HashMap();\n for (CustomType ct : fileMetadata.customTypes) {\n customTypeMappings.put(ct.sym, types.getTypeSymbol(ct.baseType));\n }\n return customTypeMappings;\n }\n\n Schema.QueryResult getQueryResult(Options.ReadOptions options) {\n return Schema.applyQuery(types, options.isMissingFieldsAsNil, options.readers, Schema.getSubSchema(options.subSchemaPath, fileMetadata.schema), options.query);\n }\n\n @Override\n public View read(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n private Iterator getRecordGroupReaders(Schema.Column[] columns, int bundleSize) {\n return getRecordGroupReaders(types, fileChannel, Constants.magicBytes.length, fileMetadata.recordGroups, columns, bundleSize);\n }\n\n private static Iterator getRecordGroupReaders(final Types types, final FileChannel fileChannel, final long offset, final Metadata.RecordGroup[] recordGroupsMetadata, final Schema.Column[] queriedColumns, final int bundleSize) {\n final int numRecordGroups = recordGroupsMetadata.length;\n if (numRecordGroups == 0) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n int i = 0;\n\n long nextOffset = offset;\n\n @Override\n public boolean hasNext() {\n return i < numRecordGroups;\n }\n\n @Override\n public RecordGroup.Reader next() {\n Metadata.RecordGroup recordGroupMetadata = recordGroupsMetadata[i];\n long length = recordGroupMetadata.length;\n ByteBuffer bb;\n try {\n bb = Utils.mapFileChannel(fileChannel, nextOffset, length);\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n RecordGroup.Reader recordGroupReader = new RecordGroup.Reader(types, bb, recordGroupMetadata, queriedColumns, bundleSize);\n nextOffset += length;\n i += 1;\n return recordGroupReader;\n }\n };\n }\n\n private IPersistentMap asPersistentMap(Stats.Global globalStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_COLUMNS, globalStats.numColumns).assoc(NUM_RECORD_GROUPS, globalStats.numRecordGroups).assoc(NUM_RECORDS, globalStats.numRecords).assoc(LENGTH, globalStats.length).assoc(DATA_HEADER_LENGTH, globalStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, globalStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, globalStats.definitionLevelsLength).assoc(DATA_LENGTH, globalStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, globalStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, globalStats.dictionaryLength).assoc(METADATA_LENGTH, globalStats.metadataLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.Column columnStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(TYPE, columnStats.type).assoc(ENCODING, columnStats.encoding).assoc(COMPRESSION, columnStats.compression).assoc(PATH, columnStats.path).assoc(MAX_REPETITION_LEVEL, columnStats.maxRepetitionLevel).assoc(MAX_DEFINITION_LEVEL, columnStats.maxDefinitionLevel).assoc(NUM_COLUMN_CHUNKS, columnStats.numColumnChunks).assoc(NUM_PAGES, columnStats.numPages).assoc(NUM_VALUES, columnStats.numValues).assoc(NUM_NON_NIL_VALUES, columnStats.numNonNilValues).assoc(LENGTH, columnStats.length).assoc(DATA_HEADER_LENGTH, columnStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, columnStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, columnStats.definitionLevelsLength).assoc(DATA_LENGTH, columnStats.dataLength).assoc(NUM_DICTIONARY_VALUES, columnStats.numDictionaryValues).assoc(DICTIONARY_HEADER_LENGTH, columnStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, columnStats.dictionaryLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.RecordGroup recordGroupStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_RECORDS, recordGroupStats.numRecords).assoc(NUM_COLUMN_CHUNKS, recordGroupStats.numColumnChunks).assoc(LENGTH, recordGroupStats.length).assoc(DATA_HEADER_LENGTH, recordGroupStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, recordGroupStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, recordGroupStats.definitionLevelsLength).assoc(DATA_LENGTH, recordGroupStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, recordGroupStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, recordGroupStats.dictionaryLength).persistent();\n }\n\n public IPersistentMap getStats() throws IOException {\n IPersistentVector[] paths = Schema.getPaths(fileMetadata.schema);\n Schema.Column[] columns = Schema.getColumns(fileMetadata.schema);\n List recordGroupsStats = new ArrayList();\n List> columnChunkStatsByColumn = new ArrayList>(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n columnChunkStatsByColumn.add(new ArrayList());\n }\n Iterator recordGroupReaders = getRecordGroupReaders(columns, 100);\n while (recordGroupReaders.hasNext()) {\n RecordGroup.Reader recordGroupReader = recordGroupReaders.next();\n List columnChunksStats = recordGroupReader.getColumnChunkStats();\n recordGroupsStats.add(Stats.createRecordGroupStats(recordGroupReader.getNumRecords(), columnChunksStats));\n int i = 0;\n for (Stats.ColumnChunk columnChunkStats : columnChunksStats) {\n columnChunkStatsByColumn.get(i).add(columnChunkStats);\n i += 1;\n }\n }\n List columnsStats = new ArrayList(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n Schema.Column col = columns[i];\n columnsStats.add(Stats.createColumnStats(types.getTypeSymbol(col.type), types.getEncodingSymbol(col.encoding), types.getCompressionSymbol(col.compression), col.repetitionLevel, col.definitionLevel, paths[i], columnChunkStatsByColumn.get(i)));\n }\n List recordGroupStatsMaps = new ArrayList();\n for (Stats.RecordGroup recordGroupStats : recordGroupsStats) {\n recordGroupStatsMaps.add(asPersistentMap(recordGroupStats));\n }\n List columnStatsMaps = new ArrayList();\n for (Stats.Column columnStats : columnsStats) {\n columnStatsMaps.add(asPersistentMap(columnStats));\n }\n IPersistentMap globalStatsMap = asPersistentMap(Stats.createGlobalStats(fileChannel.size(), metadataLength, columns.length, recordGroupsStats));\n return new PersistentArrayMap(new Object[] { RECORD_GROUPS, recordGroupStatsMaps, COLUMNS, columnStatsMaps, GLOBAL, globalStatsMap });\n }\n\n public Object getSchema() {\n return Schema.unparse(types, fileMetadata.schema);\n }\n\n public Object getPlainSchema() {\n return Schema.unparsePlain(types, fileMetadata.schema);\n }\n\n @Override\n public void close() throws IOException {\n fileChannel.close();\n }\n\n private static boolean isValidMagicBytes(ByteBuffer bb) {\n return Arrays.equals(Constants.magicBytes, Types.toByteArray(bb));\n }\n\n private static final int fixedIntLength = 4;\n\n private static final class MetadataReadResult {\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n MetadataReadResult(Metadata.File fileMetadata, long metadataLength) {\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n }\n\n private static MetadataReadResult readMetadata(File file, FileChannel fileChannel) throws IOException {\n long length = fileChannel.size();\n long lastMagicBytesPosition = length - Constants.magicBytes.length;\n ByteBuffer lastMagicBytesBuffer = Utils.mapFileChannel(fileChannel, lastMagicBytesPosition, Constants.magicBytes.length);\n if (!isValidMagicBytes(lastMagicBytesBuffer)) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n long metadataLengthPosition = lastMagicBytesPosition - fixedIntLength;\n if (metadataLengthPosition < Constants.magicBytes.length) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataLengthBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition, fixedIntLength);\n metadataLengthBuffer.order(ByteOrder.LITTLE_ENDIAN);\n long metadataLength = metadataLengthBuffer.getInt();\n if (metadataLength <= 0) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition - metadataLength, metadataLength);\n return new MetadataReadResult(Metadata.File.read(metadataBuffer), metadataLength);\n }\n\n private static Iterator getBundlesIterator(final File file, final Iterator recordGroupReaders) {\n if (!recordGroupReaders.hasNext()) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n private Iterator bundleIterator = recordGroupReaders.next().iterator();\n\n private void step() {\n if (recordGroupReaders.hasNext()) {\n bundleIterator = recordGroupReaders.next().iterator();\n } else {\n bundleIterator = null;\n }\n }\n\n @Override\n public boolean hasNext() {\n if (bundleIterator == null) {\n return false;\n }\n try {\n if (bundleIterator.hasNext()) {\n return true;\n } else {\n step();\n return bundleIterator != null && bundleIterator.hasNext();\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Error while reading from \" + file, e);\n }\n }\n\n @Override\n public Bundle next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return bundleIterator.next();\n }\n };\n }\n\n private interface IReduceFutureFactory {\n\n Future get(Bundle bundle);\n }\n\n private static final class ReduceFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n ReduceFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduce(reduceFn, completeFn, initFn, assembleFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n ReduceSampledFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampled(reduceFn, completeFn, initFn, assembleFn, sampleFn);\n }\n });\n }\n }\n\n private static final class ReduceIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn indexedByFn;\n\n ReduceIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceIndexed(reduceFn, completeFn, initFn, assembleFn, indexedByFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledAndIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n private final IFn indexedByFn;\n\n ReduceSampledAndIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampledAndIndexed(reduceFn, completeFn, initFn, assembleFn, sampleFn, indexedByFn);\n }\n });\n }\n }\n\n private IReduceFutureFactory getReduceFutureFactory(IFn reduceFn, IFn completeFn, IFn initFn, Assemble.Fn assembleFn, IFn sampleFn, IFn indexedByFn) {", "post_mask_code": "\n if (sampleFn == null) {\n if (indexedByFn == null) {\n return new ReduceFutureFactory(assembleFn, reduceFn, completeFn, initFn);\n } else {\n return new ReduceIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, indexedByFn);\n }\n } else {\n if (indexedByFn == null) {\n return new ReduceSampledFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn);\n } else {\n return new ReduceSampledAndIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn, indexedByFn);\n }\n }\n }\n\n private static Iterator getReducedChunksIterator(final Iterator bundlesIterator, final IReduceFutureFactory reduceFutureFactory) {\n int n = 2 + Runtime.getRuntime().availableProcessors();\n final LinkedList> futures = new LinkedList>();\n int k = 0;\n while (bundlesIterator.hasNext() && k < n) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n k += 1;\n }\n return new AReadOnlyIterator() {\n\n @Override\n public boolean hasNext() {\n return !futures.isEmpty();\n }\n\n @Override\n public Object next() {\n Future fut = futures.pollFirst();\n Object obj = Utils.tryGetFuture(fut);\n if (bundlesIterator.hasNext()) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n }\n return obj;\n }\n };\n }\n\n public final class LazyView extends View {\n\n private Options.ReadOptions options;\n\n private Schema.QueryResult queryResult;\n\n private Assemble.Fn assembleFn;\n\n LazyView(Options.ReadOptions options) {\n super(options.bundleSize);\n this.options = options;\n }\n\n private synchronized Schema.QueryResult getQueryResult() {\n if (queryResult == null) {\n queryResult = FileReader.this.getQueryResult(options);\n }\n return queryResult;\n }\n\n private synchronized Schema.Column[] getQueriedColumns() {\n return getQueryResult().columns;\n }\n\n private synchronized Assemble.Fn getAssembleFn() {\n if (assembleFn == null) {\n assembleFn = Assemble.getFn(FileReader.this.types, getQueryResult().schema);\n }\n return assembleFn;\n }\n\n @Override\n protected View withOptions(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n @Override\n protected Options.ReadOptions getReadOptions() {\n return options;\n }\n\n @Override\n protected Iterable getReducedChunks(final IFn reduceFn, final IFn completeFn, final IFn initFn, final int bundleSize) {\n return new Iterable() {\n\n @Override\n public Iterator iterator() {\n return FileReader.getReducedChunksIterator(getBundlesIterator(bundleSize), getReduceFutureFactory(reduceFn, completeFn, initFn, getAssembleFn(), options.sampleFn, options.indexedByFn));\n }\n };\n }\n\n private Iterator getBundlesIterator(int bundleSize) {\n return FileReader.getBundlesIterator(FileReader.this.file, getRecordGroupReaders(getQueriedColumns(), bundleSize));\n }\n }\n}\n"} {"task_id": "Java_508", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/jwhitbeck/dendrite/dendrite/java-src/dendrite/java/FileReader.java", "mask_start_position": 18217, "mask_end_position": 18852, "canonical_solution": "if (sampleFn == null) {\n if (indexedByFn == null) {\n return new ReduceFutureFactory(assembleFn, reduceFn, completeFn, initFn);\n } else {\n return new ReduceIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, indexedByFn);\n }\n } else {\n if (indexedByFn == null) {\n return new ReduceSampledFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn);\n } else {\n return new ReduceSampledAndIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn, indexedByFn);\n }\n }", "pre_mask_code": "package dendrite.java;\n\nimport clojure.lang.Agent;\nimport clojure.lang.IFn;\nimport clojure.lang.IPersistentMap;\nimport clojure.lang.IPersistentVector;\nimport clojure.lang.Keyword;\nimport clojure.lang.PersistentArrayMap;\nimport clojure.lang.Symbol;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\n\npublic final class FileReader implements Closeable, IReader {\n\n public static final Keyword RECORD_GROUPS = Keyword.intern(\"record-groups\"), COLUMNS = Keyword.intern(\"columns\"), GLOBAL = Keyword.intern(\"global\"), DATA_HEADER_LENGTH = Keyword.intern(\"data-header-length\"), REPETITION_LEVELS_LENGTH = Keyword.intern(\"repetition-levels-length\"), DEFINITION_LEVELS_LENGTH = Keyword.intern(\"definition-levels-length\"), METADATA_LENGTH = Keyword.intern(\"metadata-length\"), DATA_LENGTH = Keyword.intern(\"data-length\"), DICTIONARY_HEADER_LENGTH = Keyword.intern(\"dictionary-header-length\"), DICTIONARY_LENGTH = Keyword.intern(\"dictionary-length\"), NUM_VALUES = Keyword.intern(\"num-values\"), NUM_NON_NIL_VALUES = Keyword.intern(\"num-non-nil-values\"), LENGTH = Keyword.intern(\"length\"), NUM_PAGES = Keyword.intern(\"num-pages\"), NUM_DICTIONARY_VALUES = Keyword.intern(\"num-dictionary-values\"), TYPE = Keyword.intern(\"type\"), ENCODING = Keyword.intern(\"encoding\"), COMPRESSION = Keyword.intern(\"compression\"), MAX_REPETITION_LEVEL = Keyword.intern(\"max-repetition-level\"), MAX_DEFINITION_LEVEL = Keyword.intern(\"max-definition-level\"), PATH = Keyword.intern(\"path\"), NUM_RECORDS = Keyword.intern(\"num-records\"), NUM_RECORD_GROUPS = Keyword.intern(\"num-record-groups\"), NUM_COLUMN_CHUNKS = Keyword.intern(\"num-column-chunks\"), NUM_COLUMNS = Keyword.intern(\"num-columns\");\n\n final Types types;\n\n final File file;\n\n final FileChannel fileChannel;\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n private FileReader(Types types, File file, FileChannel fileChannel, Metadata.File fileMetadata, long metadataLength) {\n this.types = types;\n this.file = file;\n this.fileChannel = fileChannel;\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n\n public static FileReader create(Options.ReaderOptions options, File file) throws IOException {\n FileChannel fileChannel = Utils.getReadingFileChannel(file);\n MetadataReadResult res = readMetadata(file, fileChannel);\n Types types = Types.create(options.customTypeDefinitions, res.fileMetadata.customTypes);\n return new FileReader(types, file, fileChannel, res.fileMetadata, res.metadataLength);\n }\n\n public ByteBuffer getMetadata() {\n return fileMetadata.metadata;\n }\n\n public long getNumRecords() {\n return fileMetadata.getNumRecords();\n }\n\n public Map getCustomTypeMappings() {\n Map customTypeMappings = new HashMap();\n for (CustomType ct : fileMetadata.customTypes) {\n customTypeMappings.put(ct.sym, types.getTypeSymbol(ct.baseType));\n }\n return customTypeMappings;\n }\n\n Schema.QueryResult getQueryResult(Options.ReadOptions options) {\n return Schema.applyQuery(types, options.isMissingFieldsAsNil, options.readers, Schema.getSubSchema(options.subSchemaPath, fileMetadata.schema), options.query);\n }\n\n @Override\n public View read(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n private Iterator getRecordGroupReaders(Schema.Column[] columns, int bundleSize) {\n return getRecordGroupReaders(types, fileChannel, Constants.magicBytes.length, fileMetadata.recordGroups, columns, bundleSize);\n }\n\n private static Iterator getRecordGroupReaders(final Types types, final FileChannel fileChannel, final long offset, final Metadata.RecordGroup[] recordGroupsMetadata, final Schema.Column[] queriedColumns, final int bundleSize) {\n final int numRecordGroups = recordGroupsMetadata.length;\n if (numRecordGroups == 0) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n int i = 0;\n\n long nextOffset = offset;\n\n @Override\n public boolean hasNext() {\n return i < numRecordGroups;\n }\n\n @Override\n public RecordGroup.Reader next() {\n Metadata.RecordGroup recordGroupMetadata = recordGroupsMetadata[i];\n long length = recordGroupMetadata.length;\n ByteBuffer bb;\n try {\n bb = Utils.mapFileChannel(fileChannel, nextOffset, length);\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n RecordGroup.Reader recordGroupReader = new RecordGroup.Reader(types, bb, recordGroupMetadata, queriedColumns, bundleSize);\n nextOffset += length;\n i += 1;\n return recordGroupReader;\n }\n };\n }\n\n private IPersistentMap asPersistentMap(Stats.Global globalStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_COLUMNS, globalStats.numColumns).assoc(NUM_RECORD_GROUPS, globalStats.numRecordGroups).assoc(NUM_RECORDS, globalStats.numRecords).assoc(LENGTH, globalStats.length).assoc(DATA_HEADER_LENGTH, globalStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, globalStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, globalStats.definitionLevelsLength).assoc(DATA_LENGTH, globalStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, globalStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, globalStats.dictionaryLength).assoc(METADATA_LENGTH, globalStats.metadataLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.Column columnStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(TYPE, columnStats.type).assoc(ENCODING, columnStats.encoding).assoc(COMPRESSION, columnStats.compression).assoc(PATH, columnStats.path).assoc(MAX_REPETITION_LEVEL, columnStats.maxRepetitionLevel).assoc(MAX_DEFINITION_LEVEL, columnStats.maxDefinitionLevel).assoc(NUM_COLUMN_CHUNKS, columnStats.numColumnChunks).assoc(NUM_PAGES, columnStats.numPages).assoc(NUM_VALUES, columnStats.numValues).assoc(NUM_NON_NIL_VALUES, columnStats.numNonNilValues).assoc(LENGTH, columnStats.length).assoc(DATA_HEADER_LENGTH, columnStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, columnStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, columnStats.definitionLevelsLength).assoc(DATA_LENGTH, columnStats.dataLength).assoc(NUM_DICTIONARY_VALUES, columnStats.numDictionaryValues).assoc(DICTIONARY_HEADER_LENGTH, columnStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, columnStats.dictionaryLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.RecordGroup recordGroupStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_RECORDS, recordGroupStats.numRecords).assoc(NUM_COLUMN_CHUNKS, recordGroupStats.numColumnChunks).assoc(LENGTH, recordGroupStats.length).assoc(DATA_HEADER_LENGTH, recordGroupStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, recordGroupStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, recordGroupStats.definitionLevelsLength).assoc(DATA_LENGTH, recordGroupStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, recordGroupStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, recordGroupStats.dictionaryLength).persistent();\n }\n\n public IPersistentMap getStats() throws IOException {\n IPersistentVector[] paths = Schema.getPaths(fileMetadata.schema);\n Schema.Column[] columns = Schema.getColumns(fileMetadata.schema);\n List recordGroupsStats = new ArrayList();\n List> columnChunkStatsByColumn = new ArrayList>(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n columnChunkStatsByColumn.add(new ArrayList());\n }\n Iterator recordGroupReaders = getRecordGroupReaders(columns, 100);\n while (recordGroupReaders.hasNext()) {\n RecordGroup.Reader recordGroupReader = recordGroupReaders.next();\n List columnChunksStats = recordGroupReader.getColumnChunkStats();\n recordGroupsStats.add(Stats.createRecordGroupStats(recordGroupReader.getNumRecords(), columnChunksStats));\n int i = 0;\n for (Stats.ColumnChunk columnChunkStats : columnChunksStats) {\n columnChunkStatsByColumn.get(i).add(columnChunkStats);\n i += 1;\n }\n }\n List columnsStats = new ArrayList(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n Schema.Column col = columns[i];\n columnsStats.add(Stats.createColumnStats(types.getTypeSymbol(col.type), types.getEncodingSymbol(col.encoding), types.getCompressionSymbol(col.compression), col.repetitionLevel, col.definitionLevel, paths[i], columnChunkStatsByColumn.get(i)));\n }\n List recordGroupStatsMaps = new ArrayList();\n for (Stats.RecordGroup recordGroupStats : recordGroupsStats) {\n recordGroupStatsMaps.add(asPersistentMap(recordGroupStats));\n }\n List columnStatsMaps = new ArrayList();\n for (Stats.Column columnStats : columnsStats) {\n columnStatsMaps.add(asPersistentMap(columnStats));\n }\n IPersistentMap globalStatsMap = asPersistentMap(Stats.createGlobalStats(fileChannel.size(), metadataLength, columns.length, recordGroupsStats));\n return new PersistentArrayMap(new Object[] { RECORD_GROUPS, recordGroupStatsMaps, COLUMNS, columnStatsMaps, GLOBAL, globalStatsMap });\n }\n\n public Object getSchema() {\n return Schema.unparse(types, fileMetadata.schema);\n }\n\n public Object getPlainSchema() {\n return Schema.unparsePlain(types, fileMetadata.schema);\n }\n\n @Override\n public void close() throws IOException {\n fileChannel.close();\n }\n\n private static boolean isValidMagicBytes(ByteBuffer bb) {\n return Arrays.equals(Constants.magicBytes, Types.toByteArray(bb));\n }\n\n private static final int fixedIntLength = 4;\n\n private static final class MetadataReadResult {\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n MetadataReadResult(Metadata.File fileMetadata, long metadataLength) {\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n }\n\n private static MetadataReadResult readMetadata(File file, FileChannel fileChannel) throws IOException {\n long length = fileChannel.size();\n long lastMagicBytesPosition = length - Constants.magicBytes.length;\n ByteBuffer lastMagicBytesBuffer = Utils.mapFileChannel(fileChannel, lastMagicBytesPosition, Constants.magicBytes.length);\n if (!isValidMagicBytes(lastMagicBytesBuffer)) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n long metadataLengthPosition = lastMagicBytesPosition - fixedIntLength;\n if (metadataLengthPosition < Constants.magicBytes.length) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataLengthBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition, fixedIntLength);\n metadataLengthBuffer.order(ByteOrder.LITTLE_ENDIAN);\n long metadataLength = metadataLengthBuffer.getInt();\n if (metadataLength <= 0) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition - metadataLength, metadataLength);\n return new MetadataReadResult(Metadata.File.read(metadataBuffer), metadataLength);\n }\n\n private static Iterator getBundlesIterator(final File file, final Iterator recordGroupReaders) {\n if (!recordGroupReaders.hasNext()) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n private Iterator bundleIterator = recordGroupReaders.next().iterator();\n\n private void step() {\n if (recordGroupReaders.hasNext()) {\n bundleIterator = recordGroupReaders.next().iterator();\n } else {\n bundleIterator = null;\n }\n }\n\n @Override\n public boolean hasNext() {\n if (bundleIterator == null) {\n return false;\n }\n try {\n if (bundleIterator.hasNext()) {\n return true;\n } else {\n step();\n return bundleIterator != null && bundleIterator.hasNext();\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Error while reading from \" + file, e);\n }\n }\n\n @Override\n public Bundle next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return bundleIterator.next();\n }\n };\n }\n\n private interface IReduceFutureFactory {\n\n Future get(Bundle bundle);\n }\n\n private static final class ReduceFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n ReduceFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduce(reduceFn, completeFn, initFn, assembleFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n ReduceSampledFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampled(reduceFn, completeFn, initFn, assembleFn, sampleFn);\n }\n });\n }\n }\n\n private static final class ReduceIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn indexedByFn;\n\n ReduceIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceIndexed(reduceFn, completeFn, initFn, assembleFn, indexedByFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledAndIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n private final IFn indexedByFn;\n\n ReduceSampledAndIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampledAndIndexed(reduceFn, completeFn, initFn, assembleFn, sampleFn, indexedByFn);\n }\n });\n }\n }\n\n private IReduceFutureFactory getReduceFutureFactory(IFn reduceFn, IFn completeFn, IFn initFn, Assemble.Fn assembleFn, IFn sampleFn, IFn indexedByFn) {\n ", "post_mask_code": "\n }\n\n private static Iterator getReducedChunksIterator(final Iterator bundlesIterator, final IReduceFutureFactory reduceFutureFactory) {\n int n = 2 + Runtime.getRuntime().availableProcessors();\n final LinkedList> futures = new LinkedList>();\n int k = 0;\n while (bundlesIterator.hasNext() && k < n) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n k += 1;\n }\n return new AReadOnlyIterator() {\n\n @Override\n public boolean hasNext() {\n return !futures.isEmpty();\n }\n\n @Override\n public Object next() {\n Future fut = futures.pollFirst();\n Object obj = Utils.tryGetFuture(fut);\n if (bundlesIterator.hasNext()) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n }\n return obj;\n }\n };\n }\n\n public final class LazyView extends View {\n\n private Options.ReadOptions options;\n\n private Schema.QueryResult queryResult;\n\n private Assemble.Fn assembleFn;\n\n LazyView(Options.ReadOptions options) {\n super(options.bundleSize);\n this.options = options;\n }\n\n private synchronized Schema.QueryResult getQueryResult() {\n if (queryResult == null) {\n queryResult = FileReader.this.getQueryResult(options);\n }\n return queryResult;\n }\n\n private synchronized Schema.Column[] getQueriedColumns() {\n return getQueryResult().columns;\n }\n\n private synchronized Assemble.Fn getAssembleFn() {\n if (assembleFn == null) {\n assembleFn = Assemble.getFn(FileReader.this.types, getQueryResult().schema);\n }\n return assembleFn;\n }\n\n @Override\n protected View withOptions(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n @Override\n protected Options.ReadOptions getReadOptions() {\n return options;\n }\n\n @Override\n protected Iterable getReducedChunks(final IFn reduceFn, final IFn completeFn, final IFn initFn, final int bundleSize) {\n return new Iterable() {\n\n @Override\n public Iterator iterator() {\n return FileReader.getReducedChunksIterator(getBundlesIterator(bundleSize), getReduceFutureFactory(reduceFn, completeFn, initFn, getAssembleFn(), options.sampleFn, options.indexedByFn));\n }\n };\n }\n\n private Iterator getBundlesIterator(int bundleSize) {\n return FileReader.getBundlesIterator(FileReader.this.file, getRecordGroupReaders(getQueriedColumns(), bundleSize));\n }\n }\n}\n"} {"task_id": "Java_509", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/jwhitbeck/dendrite/dendrite/java-src/dendrite/java/FileReader.java", "mask_start_position": 18857, "mask_end_position": 18858, "canonical_solution": "}", "pre_mask_code": "package dendrite.java;\n\nimport clojure.lang.Agent;\nimport clojure.lang.IFn;\nimport clojure.lang.IPersistentMap;\nimport clojure.lang.IPersistentVector;\nimport clojure.lang.Keyword;\nimport clojure.lang.PersistentArrayMap;\nimport clojure.lang.Symbol;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\n\npublic final class FileReader implements Closeable, IReader {\n\n public static final Keyword RECORD_GROUPS = Keyword.intern(\"record-groups\"), COLUMNS = Keyword.intern(\"columns\"), GLOBAL = Keyword.intern(\"global\"), DATA_HEADER_LENGTH = Keyword.intern(\"data-header-length\"), REPETITION_LEVELS_LENGTH = Keyword.intern(\"repetition-levels-length\"), DEFINITION_LEVELS_LENGTH = Keyword.intern(\"definition-levels-length\"), METADATA_LENGTH = Keyword.intern(\"metadata-length\"), DATA_LENGTH = Keyword.intern(\"data-length\"), DICTIONARY_HEADER_LENGTH = Keyword.intern(\"dictionary-header-length\"), DICTIONARY_LENGTH = Keyword.intern(\"dictionary-length\"), NUM_VALUES = Keyword.intern(\"num-values\"), NUM_NON_NIL_VALUES = Keyword.intern(\"num-non-nil-values\"), LENGTH = Keyword.intern(\"length\"), NUM_PAGES = Keyword.intern(\"num-pages\"), NUM_DICTIONARY_VALUES = Keyword.intern(\"num-dictionary-values\"), TYPE = Keyword.intern(\"type\"), ENCODING = Keyword.intern(\"encoding\"), COMPRESSION = Keyword.intern(\"compression\"), MAX_REPETITION_LEVEL = Keyword.intern(\"max-repetition-level\"), MAX_DEFINITION_LEVEL = Keyword.intern(\"max-definition-level\"), PATH = Keyword.intern(\"path\"), NUM_RECORDS = Keyword.intern(\"num-records\"), NUM_RECORD_GROUPS = Keyword.intern(\"num-record-groups\"), NUM_COLUMN_CHUNKS = Keyword.intern(\"num-column-chunks\"), NUM_COLUMNS = Keyword.intern(\"num-columns\");\n\n final Types types;\n\n final File file;\n\n final FileChannel fileChannel;\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n private FileReader(Types types, File file, FileChannel fileChannel, Metadata.File fileMetadata, long metadataLength) {\n this.types = types;\n this.file = file;\n this.fileChannel = fileChannel;\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n\n public static FileReader create(Options.ReaderOptions options, File file) throws IOException {\n FileChannel fileChannel = Utils.getReadingFileChannel(file);\n MetadataReadResult res = readMetadata(file, fileChannel);\n Types types = Types.create(options.customTypeDefinitions, res.fileMetadata.customTypes);\n return new FileReader(types, file, fileChannel, res.fileMetadata, res.metadataLength);\n }\n\n public ByteBuffer getMetadata() {\n return fileMetadata.metadata;\n }\n\n public long getNumRecords() {\n return fileMetadata.getNumRecords();\n }\n\n public Map getCustomTypeMappings() {\n Map customTypeMappings = new HashMap();\n for (CustomType ct : fileMetadata.customTypes) {\n customTypeMappings.put(ct.sym, types.getTypeSymbol(ct.baseType));\n }\n return customTypeMappings;\n }\n\n Schema.QueryResult getQueryResult(Options.ReadOptions options) {\n return Schema.applyQuery(types, options.isMissingFieldsAsNil, options.readers, Schema.getSubSchema(options.subSchemaPath, fileMetadata.schema), options.query);\n }\n\n @Override\n public View read(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n private Iterator getRecordGroupReaders(Schema.Column[] columns, int bundleSize) {\n return getRecordGroupReaders(types, fileChannel, Constants.magicBytes.length, fileMetadata.recordGroups, columns, bundleSize);\n }\n\n private static Iterator getRecordGroupReaders(final Types types, final FileChannel fileChannel, final long offset, final Metadata.RecordGroup[] recordGroupsMetadata, final Schema.Column[] queriedColumns, final int bundleSize) {\n final int numRecordGroups = recordGroupsMetadata.length;\n if (numRecordGroups == 0) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n int i = 0;\n\n long nextOffset = offset;\n\n @Override\n public boolean hasNext() {\n return i < numRecordGroups;\n }\n\n @Override\n public RecordGroup.Reader next() {\n Metadata.RecordGroup recordGroupMetadata = recordGroupsMetadata[i];\n long length = recordGroupMetadata.length;\n ByteBuffer bb;\n try {\n bb = Utils.mapFileChannel(fileChannel, nextOffset, length);\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n RecordGroup.Reader recordGroupReader = new RecordGroup.Reader(types, bb, recordGroupMetadata, queriedColumns, bundleSize);\n nextOffset += length;\n i += 1;\n return recordGroupReader;\n }\n };\n }\n\n private IPersistentMap asPersistentMap(Stats.Global globalStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_COLUMNS, globalStats.numColumns).assoc(NUM_RECORD_GROUPS, globalStats.numRecordGroups).assoc(NUM_RECORDS, globalStats.numRecords).assoc(LENGTH, globalStats.length).assoc(DATA_HEADER_LENGTH, globalStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, globalStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, globalStats.definitionLevelsLength).assoc(DATA_LENGTH, globalStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, globalStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, globalStats.dictionaryLength).assoc(METADATA_LENGTH, globalStats.metadataLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.Column columnStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(TYPE, columnStats.type).assoc(ENCODING, columnStats.encoding).assoc(COMPRESSION, columnStats.compression).assoc(PATH, columnStats.path).assoc(MAX_REPETITION_LEVEL, columnStats.maxRepetitionLevel).assoc(MAX_DEFINITION_LEVEL, columnStats.maxDefinitionLevel).assoc(NUM_COLUMN_CHUNKS, columnStats.numColumnChunks).assoc(NUM_PAGES, columnStats.numPages).assoc(NUM_VALUES, columnStats.numValues).assoc(NUM_NON_NIL_VALUES, columnStats.numNonNilValues).assoc(LENGTH, columnStats.length).assoc(DATA_HEADER_LENGTH, columnStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, columnStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, columnStats.definitionLevelsLength).assoc(DATA_LENGTH, columnStats.dataLength).assoc(NUM_DICTIONARY_VALUES, columnStats.numDictionaryValues).assoc(DICTIONARY_HEADER_LENGTH, columnStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, columnStats.dictionaryLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.RecordGroup recordGroupStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_RECORDS, recordGroupStats.numRecords).assoc(NUM_COLUMN_CHUNKS, recordGroupStats.numColumnChunks).assoc(LENGTH, recordGroupStats.length).assoc(DATA_HEADER_LENGTH, recordGroupStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, recordGroupStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, recordGroupStats.definitionLevelsLength).assoc(DATA_LENGTH, recordGroupStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, recordGroupStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, recordGroupStats.dictionaryLength).persistent();\n }\n\n public IPersistentMap getStats() throws IOException {\n IPersistentVector[] paths = Schema.getPaths(fileMetadata.schema);\n Schema.Column[] columns = Schema.getColumns(fileMetadata.schema);\n List recordGroupsStats = new ArrayList();\n List> columnChunkStatsByColumn = new ArrayList>(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n columnChunkStatsByColumn.add(new ArrayList());\n }\n Iterator recordGroupReaders = getRecordGroupReaders(columns, 100);\n while (recordGroupReaders.hasNext()) {\n RecordGroup.Reader recordGroupReader = recordGroupReaders.next();\n List columnChunksStats = recordGroupReader.getColumnChunkStats();\n recordGroupsStats.add(Stats.createRecordGroupStats(recordGroupReader.getNumRecords(), columnChunksStats));\n int i = 0;\n for (Stats.ColumnChunk columnChunkStats : columnChunksStats) {\n columnChunkStatsByColumn.get(i).add(columnChunkStats);\n i += 1;\n }\n }\n List columnsStats = new ArrayList(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n Schema.Column col = columns[i];\n columnsStats.add(Stats.createColumnStats(types.getTypeSymbol(col.type), types.getEncodingSymbol(col.encoding), types.getCompressionSymbol(col.compression), col.repetitionLevel, col.definitionLevel, paths[i], columnChunkStatsByColumn.get(i)));\n }\n List recordGroupStatsMaps = new ArrayList();\n for (Stats.RecordGroup recordGroupStats : recordGroupsStats) {\n recordGroupStatsMaps.add(asPersistentMap(recordGroupStats));\n }\n List columnStatsMaps = new ArrayList();\n for (Stats.Column columnStats : columnsStats) {\n columnStatsMaps.add(asPersistentMap(columnStats));\n }\n IPersistentMap globalStatsMap = asPersistentMap(Stats.createGlobalStats(fileChannel.size(), metadataLength, columns.length, recordGroupsStats));\n return new PersistentArrayMap(new Object[] { RECORD_GROUPS, recordGroupStatsMaps, COLUMNS, columnStatsMaps, GLOBAL, globalStatsMap });\n }\n\n public Object getSchema() {\n return Schema.unparse(types, fileMetadata.schema);\n }\n\n public Object getPlainSchema() {\n return Schema.unparsePlain(types, fileMetadata.schema);\n }\n\n @Override\n public void close() throws IOException {\n fileChannel.close();\n }\n\n private static boolean isValidMagicBytes(ByteBuffer bb) {\n return Arrays.equals(Constants.magicBytes, Types.toByteArray(bb));\n }\n\n private static final int fixedIntLength = 4;\n\n private static final class MetadataReadResult {\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n MetadataReadResult(Metadata.File fileMetadata, long metadataLength) {\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n }\n\n private static MetadataReadResult readMetadata(File file, FileChannel fileChannel) throws IOException {\n long length = fileChannel.size();\n long lastMagicBytesPosition = length - Constants.magicBytes.length;\n ByteBuffer lastMagicBytesBuffer = Utils.mapFileChannel(fileChannel, lastMagicBytesPosition, Constants.magicBytes.length);\n if (!isValidMagicBytes(lastMagicBytesBuffer)) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n long metadataLengthPosition = lastMagicBytesPosition - fixedIntLength;\n if (metadataLengthPosition < Constants.magicBytes.length) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataLengthBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition, fixedIntLength);\n metadataLengthBuffer.order(ByteOrder.LITTLE_ENDIAN);\n long metadataLength = metadataLengthBuffer.getInt();\n if (metadataLength <= 0) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition - metadataLength, metadataLength);\n return new MetadataReadResult(Metadata.File.read(metadataBuffer), metadataLength);\n }\n\n private static Iterator getBundlesIterator(final File file, final Iterator recordGroupReaders) {\n if (!recordGroupReaders.hasNext()) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n private Iterator bundleIterator = recordGroupReaders.next().iterator();\n\n private void step() {\n if (recordGroupReaders.hasNext()) {\n bundleIterator = recordGroupReaders.next().iterator();\n } else {\n bundleIterator = null;\n }\n }\n\n @Override\n public boolean hasNext() {\n if (bundleIterator == null) {\n return false;\n }\n try {\n if (bundleIterator.hasNext()) {\n return true;\n } else {\n step();\n return bundleIterator != null && bundleIterator.hasNext();\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Error while reading from \" + file, e);\n }\n }\n\n @Override\n public Bundle next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return bundleIterator.next();\n }\n };\n }\n\n private interface IReduceFutureFactory {\n\n Future get(Bundle bundle);\n }\n\n private static final class ReduceFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n ReduceFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduce(reduceFn, completeFn, initFn, assembleFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n ReduceSampledFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampled(reduceFn, completeFn, initFn, assembleFn, sampleFn);\n }\n });\n }\n }\n\n private static final class ReduceIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn indexedByFn;\n\n ReduceIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceIndexed(reduceFn, completeFn, initFn, assembleFn, indexedByFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledAndIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n private final IFn indexedByFn;\n\n ReduceSampledAndIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampledAndIndexed(reduceFn, completeFn, initFn, assembleFn, sampleFn, indexedByFn);\n }\n });\n }\n }\n\n private IReduceFutureFactory getReduceFutureFactory(IFn reduceFn, IFn completeFn, IFn initFn, Assemble.Fn assembleFn, IFn sampleFn, IFn indexedByFn) {\n if (sampleFn == null) {\n if (indexedByFn == null) {\n return new ReduceFutureFactory(assembleFn, reduceFn, completeFn, initFn);\n } else {\n return new ReduceIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, indexedByFn);\n }\n } else {\n if (indexedByFn == null) {\n return new ReduceSampledFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn);\n } else {\n return new ReduceSampledAndIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn, indexedByFn);\n }\n }\n ", "post_mask_code": "\n\n private static Iterator getReducedChunksIterator(final Iterator bundlesIterator, final IReduceFutureFactory reduceFutureFactory) {\n int n = 2 + Runtime.getRuntime().availableProcessors();\n final LinkedList> futures = new LinkedList>();\n int k = 0;\n while (bundlesIterator.hasNext() && k < n) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n k += 1;\n }\n return new AReadOnlyIterator() {\n\n @Override\n public boolean hasNext() {\n return !futures.isEmpty();\n }\n\n @Override\n public Object next() {\n Future fut = futures.pollFirst();\n Object obj = Utils.tryGetFuture(fut);\n if (bundlesIterator.hasNext()) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n }\n return obj;\n }\n };\n }\n\n public final class LazyView extends View {\n\n private Options.ReadOptions options;\n\n private Schema.QueryResult queryResult;\n\n private Assemble.Fn assembleFn;\n\n LazyView(Options.ReadOptions options) {\n super(options.bundleSize);\n this.options = options;\n }\n\n private synchronized Schema.QueryResult getQueryResult() {\n if (queryResult == null) {\n queryResult = FileReader.this.getQueryResult(options);\n }\n return queryResult;\n }\n\n private synchronized Schema.Column[] getQueriedColumns() {\n return getQueryResult().columns;\n }\n\n private synchronized Assemble.Fn getAssembleFn() {\n if (assembleFn == null) {\n assembleFn = Assemble.getFn(FileReader.this.types, getQueryResult().schema);\n }\n return assembleFn;\n }\n\n @Override\n protected View withOptions(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n @Override\n protected Options.ReadOptions getReadOptions() {\n return options;\n }\n\n @Override\n protected Iterable getReducedChunks(final IFn reduceFn, final IFn completeFn, final IFn initFn, final int bundleSize) {\n return new Iterable() {\n\n @Override\n public Iterator iterator() {\n return FileReader.getReducedChunksIterator(getBundlesIterator(bundleSize), getReduceFutureFactory(reduceFn, completeFn, initFn, getAssembleFn(), options.sampleFn, options.indexedByFn));\n }\n };\n }\n\n private Iterator getBundlesIterator(int bundleSize) {\n return FileReader.getBundlesIterator(FileReader.this.file, getRecordGroupReaders(getQueriedColumns(), bundleSize));\n }\n }\n}\n"} {"task_id": "Java_510", "language": "Java", "task_type": "single_line", "source_file": "java/github/jwhitbeck/dendrite/dendrite/java-src/dendrite/java/FileReader.java", "mask_start_position": 4399, "mask_end_position": 4415, "canonical_solution": "Metadata.length;", "pre_mask_code": "package dendrite.java;\n\nimport clojure.lang.Agent;\nimport clojure.lang.IFn;\nimport clojure.lang.IPersistentMap;\nimport clojure.lang.IPersistentVector;\nimport clojure.lang.Keyword;\nimport clojure.lang.PersistentArrayMap;\nimport clojure.lang.Symbol;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\n\npublic final class FileReader implements Closeable, IReader {\n\n public static final Keyword RECORD_GROUPS = Keyword.intern(\"record-groups\"), COLUMNS = Keyword.intern(\"columns\"), GLOBAL = Keyword.intern(\"global\"), DATA_HEADER_LENGTH = Keyword.intern(\"data-header-length\"), REPETITION_LEVELS_LENGTH = Keyword.intern(\"repetition-levels-length\"), DEFINITION_LEVELS_LENGTH = Keyword.intern(\"definition-levels-length\"), METADATA_LENGTH = Keyword.intern(\"metadata-length\"), DATA_LENGTH = Keyword.intern(\"data-length\"), DICTIONARY_HEADER_LENGTH = Keyword.intern(\"dictionary-header-length\"), DICTIONARY_LENGTH = Keyword.intern(\"dictionary-length\"), NUM_VALUES = Keyword.intern(\"num-values\"), NUM_NON_NIL_VALUES = Keyword.intern(\"num-non-nil-values\"), LENGTH = Keyword.intern(\"length\"), NUM_PAGES = Keyword.intern(\"num-pages\"), NUM_DICTIONARY_VALUES = Keyword.intern(\"num-dictionary-values\"), TYPE = Keyword.intern(\"type\"), ENCODING = Keyword.intern(\"encoding\"), COMPRESSION = Keyword.intern(\"compression\"), MAX_REPETITION_LEVEL = Keyword.intern(\"max-repetition-level\"), MAX_DEFINITION_LEVEL = Keyword.intern(\"max-definition-level\"), PATH = Keyword.intern(\"path\"), NUM_RECORDS = Keyword.intern(\"num-records\"), NUM_RECORD_GROUPS = Keyword.intern(\"num-record-groups\"), NUM_COLUMN_CHUNKS = Keyword.intern(\"num-column-chunks\"), NUM_COLUMNS = Keyword.intern(\"num-columns\");\n\n final Types types;\n\n final File file;\n\n final FileChannel fileChannel;\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n private FileReader(Types types, File file, FileChannel fileChannel, Metadata.File fileMetadata, long metadataLength) {\n this.types = types;\n this.file = file;\n this.fileChannel = fileChannel;\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n\n public static FileReader create(Options.ReaderOptions options, File file) throws IOException {\n FileChannel fileChannel = Utils.getReadingFileChannel(file);\n MetadataReadResult res = readMetadata(file, fileChannel);\n Types types = Types.create(options.customTypeDefinitions, res.fileMetadata.customTypes);\n return new FileReader(types, file, fileChannel, res.fileMetadata, res.metadataLength);\n }\n\n public ByteBuffer getMetadata() {\n return fileMetadata.metadata;\n }\n\n public long getNumRecords() {\n return fileMetadata.getNumRecords();\n }\n\n public Map getCustomTypeMappings() {\n Map customTypeMappings = new HashMap();\n for (CustomType ct : fileMetadata.customTypes) {\n customTypeMappings.put(ct.sym, types.getTypeSymbol(ct.baseType));\n }\n return customTypeMappings;\n }\n\n Schema.QueryResult getQueryResult(Options.ReadOptions options) {\n return Schema.applyQuery(types, options.isMissingFieldsAsNil, options.readers, Schema.getSubSchema(options.subSchemaPath, fileMetadata.schema), options.query);\n }\n\n @Override\n public View read(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n private Iterator getRecordGroupReaders(Schema.Column[] columns, int bundleSize) {\n return getRecordGroupReaders(types, fileChannel, Constants.magicBytes.length, fileMetadata.recordGroups, columns, bundleSize);\n }\n\n private static Iterator getRecordGroupReaders(final Types types, final FileChannel fileChannel, final long offset, final Metadata.RecordGroup[] recordGroupsMetadata, final Schema.Column[] queriedColumns, final int bundleSize) {\n final int numRecordGroups = recordGroups", "post_mask_code": "\n if (numRecordGroups == 0) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n int i = 0;\n\n long nextOffset = offset;\n\n @Override\n public boolean hasNext() {\n return i < numRecordGroups;\n }\n\n @Override\n public RecordGroup.Reader next() {\n Metadata.RecordGroup recordGroupMetadata = recordGroupsMetadata[i];\n long length = recordGroupMetadata.length;\n ByteBuffer bb;\n try {\n bb = Utils.mapFileChannel(fileChannel, nextOffset, length);\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n RecordGroup.Reader recordGroupReader = new RecordGroup.Reader(types, bb, recordGroupMetadata, queriedColumns, bundleSize);\n nextOffset += length;\n i += 1;\n return recordGroupReader;\n }\n };\n }\n\n private IPersistentMap asPersistentMap(Stats.Global globalStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_COLUMNS, globalStats.numColumns).assoc(NUM_RECORD_GROUPS, globalStats.numRecordGroups).assoc(NUM_RECORDS, globalStats.numRecords).assoc(LENGTH, globalStats.length).assoc(DATA_HEADER_LENGTH, globalStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, globalStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, globalStats.definitionLevelsLength).assoc(DATA_LENGTH, globalStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, globalStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, globalStats.dictionaryLength).assoc(METADATA_LENGTH, globalStats.metadataLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.Column columnStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(TYPE, columnStats.type).assoc(ENCODING, columnStats.encoding).assoc(COMPRESSION, columnStats.compression).assoc(PATH, columnStats.path).assoc(MAX_REPETITION_LEVEL, columnStats.maxRepetitionLevel).assoc(MAX_DEFINITION_LEVEL, columnStats.maxDefinitionLevel).assoc(NUM_COLUMN_CHUNKS, columnStats.numColumnChunks).assoc(NUM_PAGES, columnStats.numPages).assoc(NUM_VALUES, columnStats.numValues).assoc(NUM_NON_NIL_VALUES, columnStats.numNonNilValues).assoc(LENGTH, columnStats.length).assoc(DATA_HEADER_LENGTH, columnStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, columnStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, columnStats.definitionLevelsLength).assoc(DATA_LENGTH, columnStats.dataLength).assoc(NUM_DICTIONARY_VALUES, columnStats.numDictionaryValues).assoc(DICTIONARY_HEADER_LENGTH, columnStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, columnStats.dictionaryLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.RecordGroup recordGroupStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_RECORDS, recordGroupStats.numRecords).assoc(NUM_COLUMN_CHUNKS, recordGroupStats.numColumnChunks).assoc(LENGTH, recordGroupStats.length).assoc(DATA_HEADER_LENGTH, recordGroupStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, recordGroupStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, recordGroupStats.definitionLevelsLength).assoc(DATA_LENGTH, recordGroupStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, recordGroupStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, recordGroupStats.dictionaryLength).persistent();\n }\n\n public IPersistentMap getStats() throws IOException {\n IPersistentVector[] paths = Schema.getPaths(fileMetadata.schema);\n Schema.Column[] columns = Schema.getColumns(fileMetadata.schema);\n List recordGroupsStats = new ArrayList();\n List> columnChunkStatsByColumn = new ArrayList>(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n columnChunkStatsByColumn.add(new ArrayList());\n }\n Iterator recordGroupReaders = getRecordGroupReaders(columns, 100);\n while (recordGroupReaders.hasNext()) {\n RecordGroup.Reader recordGroupReader = recordGroupReaders.next();\n List columnChunksStats = recordGroupReader.getColumnChunkStats();\n recordGroupsStats.add(Stats.createRecordGroupStats(recordGroupReader.getNumRecords(), columnChunksStats));\n int i = 0;\n for (Stats.ColumnChunk columnChunkStats : columnChunksStats) {\n columnChunkStatsByColumn.get(i).add(columnChunkStats);\n i += 1;\n }\n }\n List columnsStats = new ArrayList(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n Schema.Column col = columns[i];\n columnsStats.add(Stats.createColumnStats(types.getTypeSymbol(col.type), types.getEncodingSymbol(col.encoding), types.getCompressionSymbol(col.compression), col.repetitionLevel, col.definitionLevel, paths[i], columnChunkStatsByColumn.get(i)));\n }\n List recordGroupStatsMaps = new ArrayList();\n for (Stats.RecordGroup recordGroupStats : recordGroupsStats) {\n recordGroupStatsMaps.add(asPersistentMap(recordGroupStats));\n }\n List columnStatsMaps = new ArrayList();\n for (Stats.Column columnStats : columnsStats) {\n columnStatsMaps.add(asPersistentMap(columnStats));\n }\n IPersistentMap globalStatsMap = asPersistentMap(Stats.createGlobalStats(fileChannel.size(), metadataLength, columns.length, recordGroupsStats));\n return new PersistentArrayMap(new Object[] { RECORD_GROUPS, recordGroupStatsMaps, COLUMNS, columnStatsMaps, GLOBAL, globalStatsMap });\n }\n\n public Object getSchema() {\n return Schema.unparse(types, fileMetadata.schema);\n }\n\n public Object getPlainSchema() {\n return Schema.unparsePlain(types, fileMetadata.schema);\n }\n\n @Override\n public void close() throws IOException {\n fileChannel.close();\n }\n\n private static boolean isValidMagicBytes(ByteBuffer bb) {\n return Arrays.equals(Constants.magicBytes, Types.toByteArray(bb));\n }\n\n private static final int fixedIntLength = 4;\n\n private static final class MetadataReadResult {\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n MetadataReadResult(Metadata.File fileMetadata, long metadataLength) {\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n }\n\n private static MetadataReadResult readMetadata(File file, FileChannel fileChannel) throws IOException {\n long length = fileChannel.size();\n long lastMagicBytesPosition = length - Constants.magicBytes.length;\n ByteBuffer lastMagicBytesBuffer = Utils.mapFileChannel(fileChannel, lastMagicBytesPosition, Constants.magicBytes.length);\n if (!isValidMagicBytes(lastMagicBytesBuffer)) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n long metadataLengthPosition = lastMagicBytesPosition - fixedIntLength;\n if (metadataLengthPosition < Constants.magicBytes.length) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataLengthBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition, fixedIntLength);\n metadataLengthBuffer.order(ByteOrder.LITTLE_ENDIAN);\n long metadataLength = metadataLengthBuffer.getInt();\n if (metadataLength <= 0) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition - metadataLength, metadataLength);\n return new MetadataReadResult(Metadata.File.read(metadataBuffer), metadataLength);\n }\n\n private static Iterator getBundlesIterator(final File file, final Iterator recordGroupReaders) {\n if (!recordGroupReaders.hasNext()) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n private Iterator bundleIterator = recordGroupReaders.next().iterator();\n\n private void step() {\n if (recordGroupReaders.hasNext()) {\n bundleIterator = recordGroupReaders.next().iterator();\n } else {\n bundleIterator = null;\n }\n }\n\n @Override\n public boolean hasNext() {\n if (bundleIterator == null) {\n return false;\n }\n try {\n if (bundleIterator.hasNext()) {\n return true;\n } else {\n step();\n return bundleIterator != null && bundleIterator.hasNext();\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Error while reading from \" + file, e);\n }\n }\n\n @Override\n public Bundle next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return bundleIterator.next();\n }\n };\n }\n\n private interface IReduceFutureFactory {\n\n Future get(Bundle bundle);\n }\n\n private static final class ReduceFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n ReduceFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduce(reduceFn, completeFn, initFn, assembleFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n ReduceSampledFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampled(reduceFn, completeFn, initFn, assembleFn, sampleFn);\n }\n });\n }\n }\n\n private static final class ReduceIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn indexedByFn;\n\n ReduceIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceIndexed(reduceFn, completeFn, initFn, assembleFn, indexedByFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledAndIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n private final IFn indexedByFn;\n\n ReduceSampledAndIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampledAndIndexed(reduceFn, completeFn, initFn, assembleFn, sampleFn, indexedByFn);\n }\n });\n }\n }\n\n private IReduceFutureFactory getReduceFutureFactory(IFn reduceFn, IFn completeFn, IFn initFn, Assemble.Fn assembleFn, IFn sampleFn, IFn indexedByFn) {\n if (sampleFn == null) {\n if (indexedByFn == null) {\n return new ReduceFutureFactory(assembleFn, reduceFn, completeFn, initFn);\n } else {\n return new ReduceIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, indexedByFn);\n }\n } else {\n if (indexedByFn == null) {\n return new ReduceSampledFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn);\n } else {\n return new ReduceSampledAndIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn, indexedByFn);\n }\n }\n }\n\n private static Iterator getReducedChunksIterator(final Iterator bundlesIterator, final IReduceFutureFactory reduceFutureFactory) {\n int n = 2 + Runtime.getRuntime().availableProcessors();\n final LinkedList> futures = new LinkedList>();\n int k = 0;\n while (bundlesIterator.hasNext() && k < n) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n k += 1;\n }\n return new AReadOnlyIterator() {\n\n @Override\n public boolean hasNext() {\n return !futures.isEmpty();\n }\n\n @Override\n public Object next() {\n Future fut = futures.pollFirst();\n Object obj = Utils.tryGetFuture(fut);\n if (bundlesIterator.hasNext()) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n }\n return obj;\n }\n };\n }\n\n public final class LazyView extends View {\n\n private Options.ReadOptions options;\n\n private Schema.QueryResult queryResult;\n\n private Assemble.Fn assembleFn;\n\n LazyView(Options.ReadOptions options) {\n super(options.bundleSize);\n this.options = options;\n }\n\n private synchronized Schema.QueryResult getQueryResult() {\n if (queryResult == null) {\n queryResult = FileReader.this.getQueryResult(options);\n }\n return queryResult;\n }\n\n private synchronized Schema.Column[] getQueriedColumns() {\n return getQueryResult().columns;\n }\n\n private synchronized Assemble.Fn getAssembleFn() {\n if (assembleFn == null) {\n assembleFn = Assemble.getFn(FileReader.this.types, getQueryResult().schema);\n }\n return assembleFn;\n }\n\n @Override\n protected View withOptions(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n @Override\n protected Options.ReadOptions getReadOptions() {\n return options;\n }\n\n @Override\n protected Iterable getReducedChunks(final IFn reduceFn, final IFn completeFn, final IFn initFn, final int bundleSize) {\n return new Iterable() {\n\n @Override\n public Iterator iterator() {\n return FileReader.getReducedChunksIterator(getBundlesIterator(bundleSize), getReduceFutureFactory(reduceFn, completeFn, initFn, getAssembleFn(), options.sampleFn, options.indexedByFn));\n }\n };\n }\n\n private Iterator getBundlesIterator(int bundleSize) {\n return FileReader.getBundlesIterator(FileReader.this.file, getRecordGroupReaders(getQueriedColumns(), bundleSize));\n }\n }\n}\n"} {"task_id": "Java_511", "language": "Java", "task_type": "if_statement", "source_file": "java/github/jwhitbeck/dendrite/dendrite/java-src/dendrite/java/FileReader.java", "mask_start_position": 20288, "mask_end_position": 20399, "canonical_solution": "if (queryResult == null) {\n queryResult = FileReader.this.getQueryResult(options);\n }", "pre_mask_code": "package dendrite.java;\n\nimport clojure.lang.Agent;\nimport clojure.lang.IFn;\nimport clojure.lang.IPersistentMap;\nimport clojure.lang.IPersistentVector;\nimport clojure.lang.Keyword;\nimport clojure.lang.PersistentArrayMap;\nimport clojure.lang.Symbol;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\n\npublic final class FileReader implements Closeable, IReader {\n\n public static final Keyword RECORD_GROUPS = Keyword.intern(\"record-groups\"), COLUMNS = Keyword.intern(\"columns\"), GLOBAL = Keyword.intern(\"global\"), DATA_HEADER_LENGTH = Keyword.intern(\"data-header-length\"), REPETITION_LEVELS_LENGTH = Keyword.intern(\"repetition-levels-length\"), DEFINITION_LEVELS_LENGTH = Keyword.intern(\"definition-levels-length\"), METADATA_LENGTH = Keyword.intern(\"metadata-length\"), DATA_LENGTH = Keyword.intern(\"data-length\"), DICTIONARY_HEADER_LENGTH = Keyword.intern(\"dictionary-header-length\"), DICTIONARY_LENGTH = Keyword.intern(\"dictionary-length\"), NUM_VALUES = Keyword.intern(\"num-values\"), NUM_NON_NIL_VALUES = Keyword.intern(\"num-non-nil-values\"), LENGTH = Keyword.intern(\"length\"), NUM_PAGES = Keyword.intern(\"num-pages\"), NUM_DICTIONARY_VALUES = Keyword.intern(\"num-dictionary-values\"), TYPE = Keyword.intern(\"type\"), ENCODING = Keyword.intern(\"encoding\"), COMPRESSION = Keyword.intern(\"compression\"), MAX_REPETITION_LEVEL = Keyword.intern(\"max-repetition-level\"), MAX_DEFINITION_LEVEL = Keyword.intern(\"max-definition-level\"), PATH = Keyword.intern(\"path\"), NUM_RECORDS = Keyword.intern(\"num-records\"), NUM_RECORD_GROUPS = Keyword.intern(\"num-record-groups\"), NUM_COLUMN_CHUNKS = Keyword.intern(\"num-column-chunks\"), NUM_COLUMNS = Keyword.intern(\"num-columns\");\n\n final Types types;\n\n final File file;\n\n final FileChannel fileChannel;\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n private FileReader(Types types, File file, FileChannel fileChannel, Metadata.File fileMetadata, long metadataLength) {\n this.types = types;\n this.file = file;\n this.fileChannel = fileChannel;\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n\n public static FileReader create(Options.ReaderOptions options, File file) throws IOException {\n FileChannel fileChannel = Utils.getReadingFileChannel(file);\n MetadataReadResult res = readMetadata(file, fileChannel);\n Types types = Types.create(options.customTypeDefinitions, res.fileMetadata.customTypes);\n return new FileReader(types, file, fileChannel, res.fileMetadata, res.metadataLength);\n }\n\n public ByteBuffer getMetadata() {\n return fileMetadata.metadata;\n }\n\n public long getNumRecords() {\n return fileMetadata.getNumRecords();\n }\n\n public Map getCustomTypeMappings() {\n Map customTypeMappings = new HashMap();\n for (CustomType ct : fileMetadata.customTypes) {\n customTypeMappings.put(ct.sym, types.getTypeSymbol(ct.baseType));\n }\n return customTypeMappings;\n }\n\n Schema.QueryResult getQueryResult(Options.ReadOptions options) {\n return Schema.applyQuery(types, options.isMissingFieldsAsNil, options.readers, Schema.getSubSchema(options.subSchemaPath, fileMetadata.schema), options.query);\n }\n\n @Override\n public View read(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n private Iterator getRecordGroupReaders(Schema.Column[] columns, int bundleSize) {\n return getRecordGroupReaders(types, fileChannel, Constants.magicBytes.length, fileMetadata.recordGroups, columns, bundleSize);\n }\n\n private static Iterator getRecordGroupReaders(final Types types, final FileChannel fileChannel, final long offset, final Metadata.RecordGroup[] recordGroupsMetadata, final Schema.Column[] queriedColumns, final int bundleSize) {\n final int numRecordGroups = recordGroupsMetadata.length;\n if (numRecordGroups == 0) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n int i = 0;\n\n long nextOffset = offset;\n\n @Override\n public boolean hasNext() {\n return i < numRecordGroups;\n }\n\n @Override\n public RecordGroup.Reader next() {\n Metadata.RecordGroup recordGroupMetadata = recordGroupsMetadata[i];\n long length = recordGroupMetadata.length;\n ByteBuffer bb;\n try {\n bb = Utils.mapFileChannel(fileChannel, nextOffset, length);\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n RecordGroup.Reader recordGroupReader = new RecordGroup.Reader(types, bb, recordGroupMetadata, queriedColumns, bundleSize);\n nextOffset += length;\n i += 1;\n return recordGroupReader;\n }\n };\n }\n\n private IPersistentMap asPersistentMap(Stats.Global globalStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_COLUMNS, globalStats.numColumns).assoc(NUM_RECORD_GROUPS, globalStats.numRecordGroups).assoc(NUM_RECORDS, globalStats.numRecords).assoc(LENGTH, globalStats.length).assoc(DATA_HEADER_LENGTH, globalStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, globalStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, globalStats.definitionLevelsLength).assoc(DATA_LENGTH, globalStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, globalStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, globalStats.dictionaryLength).assoc(METADATA_LENGTH, globalStats.metadataLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.Column columnStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(TYPE, columnStats.type).assoc(ENCODING, columnStats.encoding).assoc(COMPRESSION, columnStats.compression).assoc(PATH, columnStats.path).assoc(MAX_REPETITION_LEVEL, columnStats.maxRepetitionLevel).assoc(MAX_DEFINITION_LEVEL, columnStats.maxDefinitionLevel).assoc(NUM_COLUMN_CHUNKS, columnStats.numColumnChunks).assoc(NUM_PAGES, columnStats.numPages).assoc(NUM_VALUES, columnStats.numValues).assoc(NUM_NON_NIL_VALUES, columnStats.numNonNilValues).assoc(LENGTH, columnStats.length).assoc(DATA_HEADER_LENGTH, columnStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, columnStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, columnStats.definitionLevelsLength).assoc(DATA_LENGTH, columnStats.dataLength).assoc(NUM_DICTIONARY_VALUES, columnStats.numDictionaryValues).assoc(DICTIONARY_HEADER_LENGTH, columnStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, columnStats.dictionaryLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.RecordGroup recordGroupStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_RECORDS, recordGroupStats.numRecords).assoc(NUM_COLUMN_CHUNKS, recordGroupStats.numColumnChunks).assoc(LENGTH, recordGroupStats.length).assoc(DATA_HEADER_LENGTH, recordGroupStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, recordGroupStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, recordGroupStats.definitionLevelsLength).assoc(DATA_LENGTH, recordGroupStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, recordGroupStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, recordGroupStats.dictionaryLength).persistent();\n }\n\n public IPersistentMap getStats() throws IOException {\n IPersistentVector[] paths = Schema.getPaths(fileMetadata.schema);\n Schema.Column[] columns = Schema.getColumns(fileMetadata.schema);\n List recordGroupsStats = new ArrayList();\n List> columnChunkStatsByColumn = new ArrayList>(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n columnChunkStatsByColumn.add(new ArrayList());\n }\n Iterator recordGroupReaders = getRecordGroupReaders(columns, 100);\n while (recordGroupReaders.hasNext()) {\n RecordGroup.Reader recordGroupReader = recordGroupReaders.next();\n List columnChunksStats = recordGroupReader.getColumnChunkStats();\n recordGroupsStats.add(Stats.createRecordGroupStats(recordGroupReader.getNumRecords(), columnChunksStats));\n int i = 0;\n for (Stats.ColumnChunk columnChunkStats : columnChunksStats) {\n columnChunkStatsByColumn.get(i).add(columnChunkStats);\n i += 1;\n }\n }\n List columnsStats = new ArrayList(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n Schema.Column col = columns[i];\n columnsStats.add(Stats.createColumnStats(types.getTypeSymbol(col.type), types.getEncodingSymbol(col.encoding), types.getCompressionSymbol(col.compression), col.repetitionLevel, col.definitionLevel, paths[i], columnChunkStatsByColumn.get(i)));\n }\n List recordGroupStatsMaps = new ArrayList();\n for (Stats.RecordGroup recordGroupStats : recordGroupsStats) {\n recordGroupStatsMaps.add(asPersistentMap(recordGroupStats));\n }\n List columnStatsMaps = new ArrayList();\n for (Stats.Column columnStats : columnsStats) {\n columnStatsMaps.add(asPersistentMap(columnStats));\n }\n IPersistentMap globalStatsMap = asPersistentMap(Stats.createGlobalStats(fileChannel.size(), metadataLength, columns.length, recordGroupsStats));\n return new PersistentArrayMap(new Object[] { RECORD_GROUPS, recordGroupStatsMaps, COLUMNS, columnStatsMaps, GLOBAL, globalStatsMap });\n }\n\n public Object getSchema() {\n return Schema.unparse(types, fileMetadata.schema);\n }\n\n public Object getPlainSchema() {\n return Schema.unparsePlain(types, fileMetadata.schema);\n }\n\n @Override\n public void close() throws IOException {\n fileChannel.close();\n }\n\n private static boolean isValidMagicBytes(ByteBuffer bb) {\n return Arrays.equals(Constants.magicBytes, Types.toByteArray(bb));\n }\n\n private static final int fixedIntLength = 4;\n\n private static final class MetadataReadResult {\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n MetadataReadResult(Metadata.File fileMetadata, long metadataLength) {\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n }\n\n private static MetadataReadResult readMetadata(File file, FileChannel fileChannel) throws IOException {\n long length = fileChannel.size();\n long lastMagicBytesPosition = length - Constants.magicBytes.length;\n ByteBuffer lastMagicBytesBuffer = Utils.mapFileChannel(fileChannel, lastMagicBytesPosition, Constants.magicBytes.length);\n if (!isValidMagicBytes(lastMagicBytesBuffer)) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n long metadataLengthPosition = lastMagicBytesPosition - fixedIntLength;\n if (metadataLengthPosition < Constants.magicBytes.length) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataLengthBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition, fixedIntLength);\n metadataLengthBuffer.order(ByteOrder.LITTLE_ENDIAN);\n long metadataLength = metadataLengthBuffer.getInt();\n if (metadataLength <= 0) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition - metadataLength, metadataLength);\n return new MetadataReadResult(Metadata.File.read(metadataBuffer), metadataLength);\n }\n\n private static Iterator getBundlesIterator(final File file, final Iterator recordGroupReaders) {\n if (!recordGroupReaders.hasNext()) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n private Iterator bundleIterator = recordGroupReaders.next().iterator();\n\n private void step() {\n if (recordGroupReaders.hasNext()) {\n bundleIterator = recordGroupReaders.next().iterator();\n } else {\n bundleIterator = null;\n }\n }\n\n @Override\n public boolean hasNext() {\n if (bundleIterator == null) {\n return false;\n }\n try {\n if (bundleIterator.hasNext()) {\n return true;\n } else {\n step();\n return bundleIterator != null && bundleIterator.hasNext();\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Error while reading from \" + file, e);\n }\n }\n\n @Override\n public Bundle next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return bundleIterator.next();\n }\n };\n }\n\n private interface IReduceFutureFactory {\n\n Future get(Bundle bundle);\n }\n\n private static final class ReduceFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n ReduceFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduce(reduceFn, completeFn, initFn, assembleFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n ReduceSampledFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampled(reduceFn, completeFn, initFn, assembleFn, sampleFn);\n }\n });\n }\n }\n\n private static final class ReduceIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn indexedByFn;\n\n ReduceIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceIndexed(reduceFn, completeFn, initFn, assembleFn, indexedByFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledAndIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n private final IFn indexedByFn;\n\n ReduceSampledAndIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampledAndIndexed(reduceFn, completeFn, initFn, assembleFn, sampleFn, indexedByFn);\n }\n });\n }\n }\n\n private IReduceFutureFactory getReduceFutureFactory(IFn reduceFn, IFn completeFn, IFn initFn, Assemble.Fn assembleFn, IFn sampleFn, IFn indexedByFn) {\n if (sampleFn == null) {\n if (indexedByFn == null) {\n return new ReduceFutureFactory(assembleFn, reduceFn, completeFn, initFn);\n } else {\n return new ReduceIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, indexedByFn);\n }\n } else {\n if (indexedByFn == null) {\n return new ReduceSampledFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn);\n } else {\n return new ReduceSampledAndIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn, indexedByFn);\n }\n }\n }\n\n private static Iterator getReducedChunksIterator(final Iterator bundlesIterator, final IReduceFutureFactory reduceFutureFactory) {\n int n = 2 + Runtime.getRuntime().availableProcessors();\n final LinkedList> futures = new LinkedList>();\n int k = 0;\n while (bundlesIterator.hasNext() && k < n) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n k += 1;\n }\n return new AReadOnlyIterator() {\n\n @Override\n public boolean hasNext() {\n return !futures.isEmpty();\n }\n\n @Override\n public Object next() {\n Future fut = futures.pollFirst();\n Object obj = Utils.tryGetFuture(fut);\n if (bundlesIterator.hasNext()) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n }\n return obj;\n }\n };\n }\n\n public final class LazyView extends View {\n\n private Options.ReadOptions options;\n\n private Schema.QueryResult queryResult;\n\n private Assemble.Fn assembleFn;\n\n LazyView(Options.ReadOptions options) {\n super(options.bundleSize);\n this.options = options;\n }\n\n private synchronized Schema.QueryResult getQueryResult() {\n ", "post_mask_code": "\n return queryResult;\n }\n\n private synchronized Schema.Column[] getQueriedColumns() {\n return getQueryResult().columns;\n }\n\n private synchronized Assemble.Fn getAssembleFn() {\n if (assembleFn == null) {\n assembleFn = Assemble.getFn(FileReader.this.types, getQueryResult().schema);\n }\n return assembleFn;\n }\n\n @Override\n protected View withOptions(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n @Override\n protected Options.ReadOptions getReadOptions() {\n return options;\n }\n\n @Override\n protected Iterable getReducedChunks(final IFn reduceFn, final IFn completeFn, final IFn initFn, final int bundleSize) {\n return new Iterable() {\n\n @Override\n public Iterator iterator() {\n return FileReader.getReducedChunksIterator(getBundlesIterator(bundleSize), getReduceFutureFactory(reduceFn, completeFn, initFn, getAssembleFn(), options.sampleFn, options.indexedByFn));\n }\n };\n }\n\n private Iterator getBundlesIterator(int bundleSize) {\n return FileReader.getBundlesIterator(FileReader.this.file, getRecordGroupReaders(getQueriedColumns(), bundleSize));\n }\n }\n}\n"} {"task_id": "Java_512", "language": "Java", "task_type": "for_statement", "source_file": "java/github/jwhitbeck/dendrite/dendrite/java-src/dendrite/java/FileReader.java", "mask_start_position": 8410, "mask_end_position": 8540, "canonical_solution": "for (int i = 0; i < columns.length; ++i) {\n columnChunkStatsByColumn.add(new ArrayList());\n }", "pre_mask_code": "package dendrite.java;\n\nimport clojure.lang.Agent;\nimport clojure.lang.IFn;\nimport clojure.lang.IPersistentMap;\nimport clojure.lang.IPersistentVector;\nimport clojure.lang.Keyword;\nimport clojure.lang.PersistentArrayMap;\nimport clojure.lang.Symbol;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\n\npublic final class FileReader implements Closeable, IReader {\n\n public static final Keyword RECORD_GROUPS = Keyword.intern(\"record-groups\"), COLUMNS = Keyword.intern(\"columns\"), GLOBAL = Keyword.intern(\"global\"), DATA_HEADER_LENGTH = Keyword.intern(\"data-header-length\"), REPETITION_LEVELS_LENGTH = Keyword.intern(\"repetition-levels-length\"), DEFINITION_LEVELS_LENGTH = Keyword.intern(\"definition-levels-length\"), METADATA_LENGTH = Keyword.intern(\"metadata-length\"), DATA_LENGTH = Keyword.intern(\"data-length\"), DICTIONARY_HEADER_LENGTH = Keyword.intern(\"dictionary-header-length\"), DICTIONARY_LENGTH = Keyword.intern(\"dictionary-length\"), NUM_VALUES = Keyword.intern(\"num-values\"), NUM_NON_NIL_VALUES = Keyword.intern(\"num-non-nil-values\"), LENGTH = Keyword.intern(\"length\"), NUM_PAGES = Keyword.intern(\"num-pages\"), NUM_DICTIONARY_VALUES = Keyword.intern(\"num-dictionary-values\"), TYPE = Keyword.intern(\"type\"), ENCODING = Keyword.intern(\"encoding\"), COMPRESSION = Keyword.intern(\"compression\"), MAX_REPETITION_LEVEL = Keyword.intern(\"max-repetition-level\"), MAX_DEFINITION_LEVEL = Keyword.intern(\"max-definition-level\"), PATH = Keyword.intern(\"path\"), NUM_RECORDS = Keyword.intern(\"num-records\"), NUM_RECORD_GROUPS = Keyword.intern(\"num-record-groups\"), NUM_COLUMN_CHUNKS = Keyword.intern(\"num-column-chunks\"), NUM_COLUMNS = Keyword.intern(\"num-columns\");\n\n final Types types;\n\n final File file;\n\n final FileChannel fileChannel;\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n private FileReader(Types types, File file, FileChannel fileChannel, Metadata.File fileMetadata, long metadataLength) {\n this.types = types;\n this.file = file;\n this.fileChannel = fileChannel;\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n\n public static FileReader create(Options.ReaderOptions options, File file) throws IOException {\n FileChannel fileChannel = Utils.getReadingFileChannel(file);\n MetadataReadResult res = readMetadata(file, fileChannel);\n Types types = Types.create(options.customTypeDefinitions, res.fileMetadata.customTypes);\n return new FileReader(types, file, fileChannel, res.fileMetadata, res.metadataLength);\n }\n\n public ByteBuffer getMetadata() {\n return fileMetadata.metadata;\n }\n\n public long getNumRecords() {\n return fileMetadata.getNumRecords();\n }\n\n public Map getCustomTypeMappings() {\n Map customTypeMappings = new HashMap();\n for (CustomType ct : fileMetadata.customTypes) {\n customTypeMappings.put(ct.sym, types.getTypeSymbol(ct.baseType));\n }\n return customTypeMappings;\n }\n\n Schema.QueryResult getQueryResult(Options.ReadOptions options) {\n return Schema.applyQuery(types, options.isMissingFieldsAsNil, options.readers, Schema.getSubSchema(options.subSchemaPath, fileMetadata.schema), options.query);\n }\n\n @Override\n public View read(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n private Iterator getRecordGroupReaders(Schema.Column[] columns, int bundleSize) {\n return getRecordGroupReaders(types, fileChannel, Constants.magicBytes.length, fileMetadata.recordGroups, columns, bundleSize);\n }\n\n private static Iterator getRecordGroupReaders(final Types types, final FileChannel fileChannel, final long offset, final Metadata.RecordGroup[] recordGroupsMetadata, final Schema.Column[] queriedColumns, final int bundleSize) {\n final int numRecordGroups = recordGroupsMetadata.length;\n if (numRecordGroups == 0) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n int i = 0;\n\n long nextOffset = offset;\n\n @Override\n public boolean hasNext() {\n return i < numRecordGroups;\n }\n\n @Override\n public RecordGroup.Reader next() {\n Metadata.RecordGroup recordGroupMetadata = recordGroupsMetadata[i];\n long length = recordGroupMetadata.length;\n ByteBuffer bb;\n try {\n bb = Utils.mapFileChannel(fileChannel, nextOffset, length);\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n RecordGroup.Reader recordGroupReader = new RecordGroup.Reader(types, bb, recordGroupMetadata, queriedColumns, bundleSize);\n nextOffset += length;\n i += 1;\n return recordGroupReader;\n }\n };\n }\n\n private IPersistentMap asPersistentMap(Stats.Global globalStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_COLUMNS, globalStats.numColumns).assoc(NUM_RECORD_GROUPS, globalStats.numRecordGroups).assoc(NUM_RECORDS, globalStats.numRecords).assoc(LENGTH, globalStats.length).assoc(DATA_HEADER_LENGTH, globalStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, globalStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, globalStats.definitionLevelsLength).assoc(DATA_LENGTH, globalStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, globalStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, globalStats.dictionaryLength).assoc(METADATA_LENGTH, globalStats.metadataLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.Column columnStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(TYPE, columnStats.type).assoc(ENCODING, columnStats.encoding).assoc(COMPRESSION, columnStats.compression).assoc(PATH, columnStats.path).assoc(MAX_REPETITION_LEVEL, columnStats.maxRepetitionLevel).assoc(MAX_DEFINITION_LEVEL, columnStats.maxDefinitionLevel).assoc(NUM_COLUMN_CHUNKS, columnStats.numColumnChunks).assoc(NUM_PAGES, columnStats.numPages).assoc(NUM_VALUES, columnStats.numValues).assoc(NUM_NON_NIL_VALUES, columnStats.numNonNilValues).assoc(LENGTH, columnStats.length).assoc(DATA_HEADER_LENGTH, columnStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, columnStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, columnStats.definitionLevelsLength).assoc(DATA_LENGTH, columnStats.dataLength).assoc(NUM_DICTIONARY_VALUES, columnStats.numDictionaryValues).assoc(DICTIONARY_HEADER_LENGTH, columnStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, columnStats.dictionaryLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.RecordGroup recordGroupStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_RECORDS, recordGroupStats.numRecords).assoc(NUM_COLUMN_CHUNKS, recordGroupStats.numColumnChunks).assoc(LENGTH, recordGroupStats.length).assoc(DATA_HEADER_LENGTH, recordGroupStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, recordGroupStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, recordGroupStats.definitionLevelsLength).assoc(DATA_LENGTH, recordGroupStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, recordGroupStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, recordGroupStats.dictionaryLength).persistent();\n }\n\n public IPersistentMap getStats() throws IOException {\n IPersistentVector[] paths = Schema.getPaths(fileMetadata.schema);\n Schema.Column[] columns = Schema.getColumns(fileMetadata.schema);\n List recordGroupsStats = new ArrayList();\n List> columnChunkStatsByColumn = new ArrayList>(columns.length);\n ", "post_mask_code": "\n Iterator recordGroupReaders = getRecordGroupReaders(columns, 100);\n while (recordGroupReaders.hasNext()) {\n RecordGroup.Reader recordGroupReader = recordGroupReaders.next();\n List columnChunksStats = recordGroupReader.getColumnChunkStats();\n recordGroupsStats.add(Stats.createRecordGroupStats(recordGroupReader.getNumRecords(), columnChunksStats));\n int i = 0;\n for (Stats.ColumnChunk columnChunkStats : columnChunksStats) {\n columnChunkStatsByColumn.get(i).add(columnChunkStats);\n i += 1;\n }\n }\n List columnsStats = new ArrayList(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n Schema.Column col = columns[i];\n columnsStats.add(Stats.createColumnStats(types.getTypeSymbol(col.type), types.getEncodingSymbol(col.encoding), types.getCompressionSymbol(col.compression), col.repetitionLevel, col.definitionLevel, paths[i], columnChunkStatsByColumn.get(i)));\n }\n List recordGroupStatsMaps = new ArrayList();\n for (Stats.RecordGroup recordGroupStats : recordGroupsStats) {\n recordGroupStatsMaps.add(asPersistentMap(recordGroupStats));\n }\n List columnStatsMaps = new ArrayList();\n for (Stats.Column columnStats : columnsStats) {\n columnStatsMaps.add(asPersistentMap(columnStats));\n }\n IPersistentMap globalStatsMap = asPersistentMap(Stats.createGlobalStats(fileChannel.size(), metadataLength, columns.length, recordGroupsStats));\n return new PersistentArrayMap(new Object[] { RECORD_GROUPS, recordGroupStatsMaps, COLUMNS, columnStatsMaps, GLOBAL, globalStatsMap });\n }\n\n public Object getSchema() {\n return Schema.unparse(types, fileMetadata.schema);\n }\n\n public Object getPlainSchema() {\n return Schema.unparsePlain(types, fileMetadata.schema);\n }\n\n @Override\n public void close() throws IOException {\n fileChannel.close();\n }\n\n private static boolean isValidMagicBytes(ByteBuffer bb) {\n return Arrays.equals(Constants.magicBytes, Types.toByteArray(bb));\n }\n\n private static final int fixedIntLength = 4;\n\n private static final class MetadataReadResult {\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n MetadataReadResult(Metadata.File fileMetadata, long metadataLength) {\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n }\n\n private static MetadataReadResult readMetadata(File file, FileChannel fileChannel) throws IOException {\n long length = fileChannel.size();\n long lastMagicBytesPosition = length - Constants.magicBytes.length;\n ByteBuffer lastMagicBytesBuffer = Utils.mapFileChannel(fileChannel, lastMagicBytesPosition, Constants.magicBytes.length);\n if (!isValidMagicBytes(lastMagicBytesBuffer)) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n long metadataLengthPosition = lastMagicBytesPosition - fixedIntLength;\n if (metadataLengthPosition < Constants.magicBytes.length) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataLengthBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition, fixedIntLength);\n metadataLengthBuffer.order(ByteOrder.LITTLE_ENDIAN);\n long metadataLength = metadataLengthBuffer.getInt();\n if (metadataLength <= 0) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition - metadataLength, metadataLength);\n return new MetadataReadResult(Metadata.File.read(metadataBuffer), metadataLength);\n }\n\n private static Iterator getBundlesIterator(final File file, final Iterator recordGroupReaders) {\n if (!recordGroupReaders.hasNext()) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n private Iterator bundleIterator = recordGroupReaders.next().iterator();\n\n private void step() {\n if (recordGroupReaders.hasNext()) {\n bundleIterator = recordGroupReaders.next().iterator();\n } else {\n bundleIterator = null;\n }\n }\n\n @Override\n public boolean hasNext() {\n if (bundleIterator == null) {\n return false;\n }\n try {\n if (bundleIterator.hasNext()) {\n return true;\n } else {\n step();\n return bundleIterator != null && bundleIterator.hasNext();\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Error while reading from \" + file, e);\n }\n }\n\n @Override\n public Bundle next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return bundleIterator.next();\n }\n };\n }\n\n private interface IReduceFutureFactory {\n\n Future get(Bundle bundle);\n }\n\n private static final class ReduceFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n ReduceFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduce(reduceFn, completeFn, initFn, assembleFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n ReduceSampledFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampled(reduceFn, completeFn, initFn, assembleFn, sampleFn);\n }\n });\n }\n }\n\n private static final class ReduceIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn indexedByFn;\n\n ReduceIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceIndexed(reduceFn, completeFn, initFn, assembleFn, indexedByFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledAndIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n private final IFn indexedByFn;\n\n ReduceSampledAndIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampledAndIndexed(reduceFn, completeFn, initFn, assembleFn, sampleFn, indexedByFn);\n }\n });\n }\n }\n\n private IReduceFutureFactory getReduceFutureFactory(IFn reduceFn, IFn completeFn, IFn initFn, Assemble.Fn assembleFn, IFn sampleFn, IFn indexedByFn) {\n if (sampleFn == null) {\n if (indexedByFn == null) {\n return new ReduceFutureFactory(assembleFn, reduceFn, completeFn, initFn);\n } else {\n return new ReduceIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, indexedByFn);\n }\n } else {\n if (indexedByFn == null) {\n return new ReduceSampledFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn);\n } else {\n return new ReduceSampledAndIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn, indexedByFn);\n }\n }\n }\n\n private static Iterator getReducedChunksIterator(final Iterator bundlesIterator, final IReduceFutureFactory reduceFutureFactory) {\n int n = 2 + Runtime.getRuntime().availableProcessors();\n final LinkedList> futures = new LinkedList>();\n int k = 0;\n while (bundlesIterator.hasNext() && k < n) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n k += 1;\n }\n return new AReadOnlyIterator() {\n\n @Override\n public boolean hasNext() {\n return !futures.isEmpty();\n }\n\n @Override\n public Object next() {\n Future fut = futures.pollFirst();\n Object obj = Utils.tryGetFuture(fut);\n if (bundlesIterator.hasNext()) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n }\n return obj;\n }\n };\n }\n\n public final class LazyView extends View {\n\n private Options.ReadOptions options;\n\n private Schema.QueryResult queryResult;\n\n private Assemble.Fn assembleFn;\n\n LazyView(Options.ReadOptions options) {\n super(options.bundleSize);\n this.options = options;\n }\n\n private synchronized Schema.QueryResult getQueryResult() {\n if (queryResult == null) {\n queryResult = FileReader.this.getQueryResult(options);\n }\n return queryResult;\n }\n\n private synchronized Schema.Column[] getQueriedColumns() {\n return getQueryResult().columns;\n }\n\n private synchronized Assemble.Fn getAssembleFn() {\n if (assembleFn == null) {\n assembleFn = Assemble.getFn(FileReader.this.types, getQueryResult().schema);\n }\n return assembleFn;\n }\n\n @Override\n protected View withOptions(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n @Override\n protected Options.ReadOptions getReadOptions() {\n return options;\n }\n\n @Override\n protected Iterable getReducedChunks(final IFn reduceFn, final IFn completeFn, final IFn initFn, final int bundleSize) {\n return new Iterable() {\n\n @Override\n public Iterator iterator() {\n return FileReader.getReducedChunksIterator(getBundlesIterator(bundleSize), getReduceFutureFactory(reduceFn, completeFn, initFn, getAssembleFn(), options.sampleFn, options.indexedByFn));\n }\n };\n }\n\n private Iterator getBundlesIterator(int bundleSize) {\n return FileReader.getBundlesIterator(FileReader.this.file, getRecordGroupReaders(getQueriedColumns(), bundleSize));\n }\n }\n}\n"} {"task_id": "Java_513", "language": "Java", "task_type": "while_statement", "source_file": "java/github/jwhitbeck/dendrite/dendrite/java-src/dendrite/java/FileReader.java", "mask_start_position": 19187, "mask_end_position": 19339, "canonical_solution": "while (bundlesIterator.hasNext() && k < n) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n k += 1;\n }", "pre_mask_code": "package dendrite.java;\n\nimport clojure.lang.Agent;\nimport clojure.lang.IFn;\nimport clojure.lang.IPersistentMap;\nimport clojure.lang.IPersistentVector;\nimport clojure.lang.Keyword;\nimport clojure.lang.PersistentArrayMap;\nimport clojure.lang.Symbol;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\n\npublic final class FileReader implements Closeable, IReader {\n\n public static final Keyword RECORD_GROUPS = Keyword.intern(\"record-groups\"), COLUMNS = Keyword.intern(\"columns\"), GLOBAL = Keyword.intern(\"global\"), DATA_HEADER_LENGTH = Keyword.intern(\"data-header-length\"), REPETITION_LEVELS_LENGTH = Keyword.intern(\"repetition-levels-length\"), DEFINITION_LEVELS_LENGTH = Keyword.intern(\"definition-levels-length\"), METADATA_LENGTH = Keyword.intern(\"metadata-length\"), DATA_LENGTH = Keyword.intern(\"data-length\"), DICTIONARY_HEADER_LENGTH = Keyword.intern(\"dictionary-header-length\"), DICTIONARY_LENGTH = Keyword.intern(\"dictionary-length\"), NUM_VALUES = Keyword.intern(\"num-values\"), NUM_NON_NIL_VALUES = Keyword.intern(\"num-non-nil-values\"), LENGTH = Keyword.intern(\"length\"), NUM_PAGES = Keyword.intern(\"num-pages\"), NUM_DICTIONARY_VALUES = Keyword.intern(\"num-dictionary-values\"), TYPE = Keyword.intern(\"type\"), ENCODING = Keyword.intern(\"encoding\"), COMPRESSION = Keyword.intern(\"compression\"), MAX_REPETITION_LEVEL = Keyword.intern(\"max-repetition-level\"), MAX_DEFINITION_LEVEL = Keyword.intern(\"max-definition-level\"), PATH = Keyword.intern(\"path\"), NUM_RECORDS = Keyword.intern(\"num-records\"), NUM_RECORD_GROUPS = Keyword.intern(\"num-record-groups\"), NUM_COLUMN_CHUNKS = Keyword.intern(\"num-column-chunks\"), NUM_COLUMNS = Keyword.intern(\"num-columns\");\n\n final Types types;\n\n final File file;\n\n final FileChannel fileChannel;\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n private FileReader(Types types, File file, FileChannel fileChannel, Metadata.File fileMetadata, long metadataLength) {\n this.types = types;\n this.file = file;\n this.fileChannel = fileChannel;\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n\n public static FileReader create(Options.ReaderOptions options, File file) throws IOException {\n FileChannel fileChannel = Utils.getReadingFileChannel(file);\n MetadataReadResult res = readMetadata(file, fileChannel);\n Types types = Types.create(options.customTypeDefinitions, res.fileMetadata.customTypes);\n return new FileReader(types, file, fileChannel, res.fileMetadata, res.metadataLength);\n }\n\n public ByteBuffer getMetadata() {\n return fileMetadata.metadata;\n }\n\n public long getNumRecords() {\n return fileMetadata.getNumRecords();\n }\n\n public Map getCustomTypeMappings() {\n Map customTypeMappings = new HashMap();\n for (CustomType ct : fileMetadata.customTypes) {\n customTypeMappings.put(ct.sym, types.getTypeSymbol(ct.baseType));\n }\n return customTypeMappings;\n }\n\n Schema.QueryResult getQueryResult(Options.ReadOptions options) {\n return Schema.applyQuery(types, options.isMissingFieldsAsNil, options.readers, Schema.getSubSchema(options.subSchemaPath, fileMetadata.schema), options.query);\n }\n\n @Override\n public View read(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n private Iterator getRecordGroupReaders(Schema.Column[] columns, int bundleSize) {\n return getRecordGroupReaders(types, fileChannel, Constants.magicBytes.length, fileMetadata.recordGroups, columns, bundleSize);\n }\n\n private static Iterator getRecordGroupReaders(final Types types, final FileChannel fileChannel, final long offset, final Metadata.RecordGroup[] recordGroupsMetadata, final Schema.Column[] queriedColumns, final int bundleSize) {\n final int numRecordGroups = recordGroupsMetadata.length;\n if (numRecordGroups == 0) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n int i = 0;\n\n long nextOffset = offset;\n\n @Override\n public boolean hasNext() {\n return i < numRecordGroups;\n }\n\n @Override\n public RecordGroup.Reader next() {\n Metadata.RecordGroup recordGroupMetadata = recordGroupsMetadata[i];\n long length = recordGroupMetadata.length;\n ByteBuffer bb;\n try {\n bb = Utils.mapFileChannel(fileChannel, nextOffset, length);\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n RecordGroup.Reader recordGroupReader = new RecordGroup.Reader(types, bb, recordGroupMetadata, queriedColumns, bundleSize);\n nextOffset += length;\n i += 1;\n return recordGroupReader;\n }\n };\n }\n\n private IPersistentMap asPersistentMap(Stats.Global globalStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_COLUMNS, globalStats.numColumns).assoc(NUM_RECORD_GROUPS, globalStats.numRecordGroups).assoc(NUM_RECORDS, globalStats.numRecords).assoc(LENGTH, globalStats.length).assoc(DATA_HEADER_LENGTH, globalStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, globalStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, globalStats.definitionLevelsLength).assoc(DATA_LENGTH, globalStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, globalStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, globalStats.dictionaryLength).assoc(METADATA_LENGTH, globalStats.metadataLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.Column columnStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(TYPE, columnStats.type).assoc(ENCODING, columnStats.encoding).assoc(COMPRESSION, columnStats.compression).assoc(PATH, columnStats.path).assoc(MAX_REPETITION_LEVEL, columnStats.maxRepetitionLevel).assoc(MAX_DEFINITION_LEVEL, columnStats.maxDefinitionLevel).assoc(NUM_COLUMN_CHUNKS, columnStats.numColumnChunks).assoc(NUM_PAGES, columnStats.numPages).assoc(NUM_VALUES, columnStats.numValues).assoc(NUM_NON_NIL_VALUES, columnStats.numNonNilValues).assoc(LENGTH, columnStats.length).assoc(DATA_HEADER_LENGTH, columnStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, columnStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, columnStats.definitionLevelsLength).assoc(DATA_LENGTH, columnStats.dataLength).assoc(NUM_DICTIONARY_VALUES, columnStats.numDictionaryValues).assoc(DICTIONARY_HEADER_LENGTH, columnStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, columnStats.dictionaryLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.RecordGroup recordGroupStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_RECORDS, recordGroupStats.numRecords).assoc(NUM_COLUMN_CHUNKS, recordGroupStats.numColumnChunks).assoc(LENGTH, recordGroupStats.length).assoc(DATA_HEADER_LENGTH, recordGroupStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, recordGroupStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, recordGroupStats.definitionLevelsLength).assoc(DATA_LENGTH, recordGroupStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, recordGroupStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, recordGroupStats.dictionaryLength).persistent();\n }\n\n public IPersistentMap getStats() throws IOException {\n IPersistentVector[] paths = Schema.getPaths(fileMetadata.schema);\n Schema.Column[] columns = Schema.getColumns(fileMetadata.schema);\n List recordGroupsStats = new ArrayList();\n List> columnChunkStatsByColumn = new ArrayList>(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n columnChunkStatsByColumn.add(new ArrayList());\n }\n Iterator recordGroupReaders = getRecordGroupReaders(columns, 100);\n while (recordGroupReaders.hasNext()) {\n RecordGroup.Reader recordGroupReader = recordGroupReaders.next();\n List columnChunksStats = recordGroupReader.getColumnChunkStats();\n recordGroupsStats.add(Stats.createRecordGroupStats(recordGroupReader.getNumRecords(), columnChunksStats));\n int i = 0;\n for (Stats.ColumnChunk columnChunkStats : columnChunksStats) {\n columnChunkStatsByColumn.get(i).add(columnChunkStats);\n i += 1;\n }\n }\n List columnsStats = new ArrayList(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n Schema.Column col = columns[i];\n columnsStats.add(Stats.createColumnStats(types.getTypeSymbol(col.type), types.getEncodingSymbol(col.encoding), types.getCompressionSymbol(col.compression), col.repetitionLevel, col.definitionLevel, paths[i], columnChunkStatsByColumn.get(i)));\n }\n List recordGroupStatsMaps = new ArrayList();\n for (Stats.RecordGroup recordGroupStats : recordGroupsStats) {\n recordGroupStatsMaps.add(asPersistentMap(recordGroupStats));\n }\n List columnStatsMaps = new ArrayList();\n for (Stats.Column columnStats : columnsStats) {\n columnStatsMaps.add(asPersistentMap(columnStats));\n }\n IPersistentMap globalStatsMap = asPersistentMap(Stats.createGlobalStats(fileChannel.size(), metadataLength, columns.length, recordGroupsStats));\n return new PersistentArrayMap(new Object[] { RECORD_GROUPS, recordGroupStatsMaps, COLUMNS, columnStatsMaps, GLOBAL, globalStatsMap });\n }\n\n public Object getSchema() {\n return Schema.unparse(types, fileMetadata.schema);\n }\n\n public Object getPlainSchema() {\n return Schema.unparsePlain(types, fileMetadata.schema);\n }\n\n @Override\n public void close() throws IOException {\n fileChannel.close();\n }\n\n private static boolean isValidMagicBytes(ByteBuffer bb) {\n return Arrays.equals(Constants.magicBytes, Types.toByteArray(bb));\n }\n\n private static final int fixedIntLength = 4;\n\n private static final class MetadataReadResult {\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n MetadataReadResult(Metadata.File fileMetadata, long metadataLength) {\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n }\n\n private static MetadataReadResult readMetadata(File file, FileChannel fileChannel) throws IOException {\n long length = fileChannel.size();\n long lastMagicBytesPosition = length - Constants.magicBytes.length;\n ByteBuffer lastMagicBytesBuffer = Utils.mapFileChannel(fileChannel, lastMagicBytesPosition, Constants.magicBytes.length);\n if (!isValidMagicBytes(lastMagicBytesBuffer)) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n long metadataLengthPosition = lastMagicBytesPosition - fixedIntLength;\n if (metadataLengthPosition < Constants.magicBytes.length) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataLengthBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition, fixedIntLength);\n metadataLengthBuffer.order(ByteOrder.LITTLE_ENDIAN);\n long metadataLength = metadataLengthBuffer.getInt();\n if (metadataLength <= 0) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition - metadataLength, metadataLength);\n return new MetadataReadResult(Metadata.File.read(metadataBuffer), metadataLength);\n }\n\n private static Iterator getBundlesIterator(final File file, final Iterator recordGroupReaders) {\n if (!recordGroupReaders.hasNext()) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n private Iterator bundleIterator = recordGroupReaders.next().iterator();\n\n private void step() {\n if (recordGroupReaders.hasNext()) {\n bundleIterator = recordGroupReaders.next().iterator();\n } else {\n bundleIterator = null;\n }\n }\n\n @Override\n public boolean hasNext() {\n if (bundleIterator == null) {\n return false;\n }\n try {\n if (bundleIterator.hasNext()) {\n return true;\n } else {\n step();\n return bundleIterator != null && bundleIterator.hasNext();\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Error while reading from \" + file, e);\n }\n }\n\n @Override\n public Bundle next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return bundleIterator.next();\n }\n };\n }\n\n private interface IReduceFutureFactory {\n\n Future get(Bundle bundle);\n }\n\n private static final class ReduceFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n ReduceFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduce(reduceFn, completeFn, initFn, assembleFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n ReduceSampledFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampled(reduceFn, completeFn, initFn, assembleFn, sampleFn);\n }\n });\n }\n }\n\n private static final class ReduceIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn indexedByFn;\n\n ReduceIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceIndexed(reduceFn, completeFn, initFn, assembleFn, indexedByFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledAndIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n private final IFn indexedByFn;\n\n ReduceSampledAndIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampledAndIndexed(reduceFn, completeFn, initFn, assembleFn, sampleFn, indexedByFn);\n }\n });\n }\n }\n\n private IReduceFutureFactory getReduceFutureFactory(IFn reduceFn, IFn completeFn, IFn initFn, Assemble.Fn assembleFn, IFn sampleFn, IFn indexedByFn) {\n if (sampleFn == null) {\n if (indexedByFn == null) {\n return new ReduceFutureFactory(assembleFn, reduceFn, completeFn, initFn);\n } else {\n return new ReduceIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, indexedByFn);\n }\n } else {\n if (indexedByFn == null) {\n return new ReduceSampledFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn);\n } else {\n return new ReduceSampledAndIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn, indexedByFn);\n }\n }\n }\n\n private static Iterator getReducedChunksIterator(final Iterator bundlesIterator, final IReduceFutureFactory reduceFutureFactory) {\n int n = 2 + Runtime.getRuntime().availableProcessors();\n final LinkedList> futures = new LinkedList>();\n int k = 0;\n ", "post_mask_code": "\n return new AReadOnlyIterator() {\n\n @Override\n public boolean hasNext() {\n return !futures.isEmpty();\n }\n\n @Override\n public Object next() {\n Future fut = futures.pollFirst();\n Object obj = Utils.tryGetFuture(fut);\n if (bundlesIterator.hasNext()) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n }\n return obj;\n }\n };\n }\n\n public final class LazyView extends View {\n\n private Options.ReadOptions options;\n\n private Schema.QueryResult queryResult;\n\n private Assemble.Fn assembleFn;\n\n LazyView(Options.ReadOptions options) {\n super(options.bundleSize);\n this.options = options;\n }\n\n private synchronized Schema.QueryResult getQueryResult() {\n if (queryResult == null) {\n queryResult = FileReader.this.getQueryResult(options);\n }\n return queryResult;\n }\n\n private synchronized Schema.Column[] getQueriedColumns() {\n return getQueryResult().columns;\n }\n\n private synchronized Assemble.Fn getAssembleFn() {\n if (assembleFn == null) {\n assembleFn = Assemble.getFn(FileReader.this.types, getQueryResult().schema);\n }\n return assembleFn;\n }\n\n @Override\n protected View withOptions(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n @Override\n protected Options.ReadOptions getReadOptions() {\n return options;\n }\n\n @Override\n protected Iterable getReducedChunks(final IFn reduceFn, final IFn completeFn, final IFn initFn, final int bundleSize) {\n return new Iterable() {\n\n @Override\n public Iterator iterator() {\n return FileReader.getReducedChunksIterator(getBundlesIterator(bundleSize), getReduceFutureFactory(reduceFn, completeFn, initFn, getAssembleFn(), options.sampleFn, options.indexedByFn));\n }\n };\n }\n\n private Iterator getBundlesIterator(int bundleSize) {\n return FileReader.getBundlesIterator(FileReader.this.file, getRecordGroupReaders(getQueriedColumns(), bundleSize));\n }\n }\n}\n"} {"task_id": "Java_514", "language": "Java", "task_type": "try_statement", "source_file": "java/github/jwhitbeck/dendrite/dendrite/java-src/dendrite/java/FileReader.java", "mask_start_position": 13462, "mask_end_position": 13872, "canonical_solution": "try {\n if (bundleIterator.hasNext()) {\n return true;\n } else {\n step();\n return bundleIterator != null && bundleIterator.hasNext();\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Error while reading from \" + file, e);\n }", "pre_mask_code": "package dendrite.java;\n\nimport clojure.lang.Agent;\nimport clojure.lang.IFn;\nimport clojure.lang.IPersistentMap;\nimport clojure.lang.IPersistentVector;\nimport clojure.lang.Keyword;\nimport clojure.lang.PersistentArrayMap;\nimport clojure.lang.Symbol;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\n\npublic final class FileReader implements Closeable, IReader {\n\n public static final Keyword RECORD_GROUPS = Keyword.intern(\"record-groups\"), COLUMNS = Keyword.intern(\"columns\"), GLOBAL = Keyword.intern(\"global\"), DATA_HEADER_LENGTH = Keyword.intern(\"data-header-length\"), REPETITION_LEVELS_LENGTH = Keyword.intern(\"repetition-levels-length\"), DEFINITION_LEVELS_LENGTH = Keyword.intern(\"definition-levels-length\"), METADATA_LENGTH = Keyword.intern(\"metadata-length\"), DATA_LENGTH = Keyword.intern(\"data-length\"), DICTIONARY_HEADER_LENGTH = Keyword.intern(\"dictionary-header-length\"), DICTIONARY_LENGTH = Keyword.intern(\"dictionary-length\"), NUM_VALUES = Keyword.intern(\"num-values\"), NUM_NON_NIL_VALUES = Keyword.intern(\"num-non-nil-values\"), LENGTH = Keyword.intern(\"length\"), NUM_PAGES = Keyword.intern(\"num-pages\"), NUM_DICTIONARY_VALUES = Keyword.intern(\"num-dictionary-values\"), TYPE = Keyword.intern(\"type\"), ENCODING = Keyword.intern(\"encoding\"), COMPRESSION = Keyword.intern(\"compression\"), MAX_REPETITION_LEVEL = Keyword.intern(\"max-repetition-level\"), MAX_DEFINITION_LEVEL = Keyword.intern(\"max-definition-level\"), PATH = Keyword.intern(\"path\"), NUM_RECORDS = Keyword.intern(\"num-records\"), NUM_RECORD_GROUPS = Keyword.intern(\"num-record-groups\"), NUM_COLUMN_CHUNKS = Keyword.intern(\"num-column-chunks\"), NUM_COLUMNS = Keyword.intern(\"num-columns\");\n\n final Types types;\n\n final File file;\n\n final FileChannel fileChannel;\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n private FileReader(Types types, File file, FileChannel fileChannel, Metadata.File fileMetadata, long metadataLength) {\n this.types = types;\n this.file = file;\n this.fileChannel = fileChannel;\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n\n public static FileReader create(Options.ReaderOptions options, File file) throws IOException {\n FileChannel fileChannel = Utils.getReadingFileChannel(file);\n MetadataReadResult res = readMetadata(file, fileChannel);\n Types types = Types.create(options.customTypeDefinitions, res.fileMetadata.customTypes);\n return new FileReader(types, file, fileChannel, res.fileMetadata, res.metadataLength);\n }\n\n public ByteBuffer getMetadata() {\n return fileMetadata.metadata;\n }\n\n public long getNumRecords() {\n return fileMetadata.getNumRecords();\n }\n\n public Map getCustomTypeMappings() {\n Map customTypeMappings = new HashMap();\n for (CustomType ct : fileMetadata.customTypes) {\n customTypeMappings.put(ct.sym, types.getTypeSymbol(ct.baseType));\n }\n return customTypeMappings;\n }\n\n Schema.QueryResult getQueryResult(Options.ReadOptions options) {\n return Schema.applyQuery(types, options.isMissingFieldsAsNil, options.readers, Schema.getSubSchema(options.subSchemaPath, fileMetadata.schema), options.query);\n }\n\n @Override\n public View read(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n private Iterator getRecordGroupReaders(Schema.Column[] columns, int bundleSize) {\n return getRecordGroupReaders(types, fileChannel, Constants.magicBytes.length, fileMetadata.recordGroups, columns, bundleSize);\n }\n\n private static Iterator getRecordGroupReaders(final Types types, final FileChannel fileChannel, final long offset, final Metadata.RecordGroup[] recordGroupsMetadata, final Schema.Column[] queriedColumns, final int bundleSize) {\n final int numRecordGroups = recordGroupsMetadata.length;\n if (numRecordGroups == 0) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n int i = 0;\n\n long nextOffset = offset;\n\n @Override\n public boolean hasNext() {\n return i < numRecordGroups;\n }\n\n @Override\n public RecordGroup.Reader next() {\n Metadata.RecordGroup recordGroupMetadata = recordGroupsMetadata[i];\n long length = recordGroupMetadata.length;\n ByteBuffer bb;\n try {\n bb = Utils.mapFileChannel(fileChannel, nextOffset, length);\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n RecordGroup.Reader recordGroupReader = new RecordGroup.Reader(types, bb, recordGroupMetadata, queriedColumns, bundleSize);\n nextOffset += length;\n i += 1;\n return recordGroupReader;\n }\n };\n }\n\n private IPersistentMap asPersistentMap(Stats.Global globalStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_COLUMNS, globalStats.numColumns).assoc(NUM_RECORD_GROUPS, globalStats.numRecordGroups).assoc(NUM_RECORDS, globalStats.numRecords).assoc(LENGTH, globalStats.length).assoc(DATA_HEADER_LENGTH, globalStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, globalStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, globalStats.definitionLevelsLength).assoc(DATA_LENGTH, globalStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, globalStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, globalStats.dictionaryLength).assoc(METADATA_LENGTH, globalStats.metadataLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.Column columnStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(TYPE, columnStats.type).assoc(ENCODING, columnStats.encoding).assoc(COMPRESSION, columnStats.compression).assoc(PATH, columnStats.path).assoc(MAX_REPETITION_LEVEL, columnStats.maxRepetitionLevel).assoc(MAX_DEFINITION_LEVEL, columnStats.maxDefinitionLevel).assoc(NUM_COLUMN_CHUNKS, columnStats.numColumnChunks).assoc(NUM_PAGES, columnStats.numPages).assoc(NUM_VALUES, columnStats.numValues).assoc(NUM_NON_NIL_VALUES, columnStats.numNonNilValues).assoc(LENGTH, columnStats.length).assoc(DATA_HEADER_LENGTH, columnStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, columnStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, columnStats.definitionLevelsLength).assoc(DATA_LENGTH, columnStats.dataLength).assoc(NUM_DICTIONARY_VALUES, columnStats.numDictionaryValues).assoc(DICTIONARY_HEADER_LENGTH, columnStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, columnStats.dictionaryLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.RecordGroup recordGroupStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_RECORDS, recordGroupStats.numRecords).assoc(NUM_COLUMN_CHUNKS, recordGroupStats.numColumnChunks).assoc(LENGTH, recordGroupStats.length).assoc(DATA_HEADER_LENGTH, recordGroupStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, recordGroupStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, recordGroupStats.definitionLevelsLength).assoc(DATA_LENGTH, recordGroupStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, recordGroupStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, recordGroupStats.dictionaryLength).persistent();\n }\n\n public IPersistentMap getStats() throws IOException {\n IPersistentVector[] paths = Schema.getPaths(fileMetadata.schema);\n Schema.Column[] columns = Schema.getColumns(fileMetadata.schema);\n List recordGroupsStats = new ArrayList();\n List> columnChunkStatsByColumn = new ArrayList>(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n columnChunkStatsByColumn.add(new ArrayList());\n }\n Iterator recordGroupReaders = getRecordGroupReaders(columns, 100);\n while (recordGroupReaders.hasNext()) {\n RecordGroup.Reader recordGroupReader = recordGroupReaders.next();\n List columnChunksStats = recordGroupReader.getColumnChunkStats();\n recordGroupsStats.add(Stats.createRecordGroupStats(recordGroupReader.getNumRecords(), columnChunksStats));\n int i = 0;\n for (Stats.ColumnChunk columnChunkStats : columnChunksStats) {\n columnChunkStatsByColumn.get(i).add(columnChunkStats);\n i += 1;\n }\n }\n List columnsStats = new ArrayList(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n Schema.Column col = columns[i];\n columnsStats.add(Stats.createColumnStats(types.getTypeSymbol(col.type), types.getEncodingSymbol(col.encoding), types.getCompressionSymbol(col.compression), col.repetitionLevel, col.definitionLevel, paths[i], columnChunkStatsByColumn.get(i)));\n }\n List recordGroupStatsMaps = new ArrayList();\n for (Stats.RecordGroup recordGroupStats : recordGroupsStats) {\n recordGroupStatsMaps.add(asPersistentMap(recordGroupStats));\n }\n List columnStatsMaps = new ArrayList();\n for (Stats.Column columnStats : columnsStats) {\n columnStatsMaps.add(asPersistentMap(columnStats));\n }\n IPersistentMap globalStatsMap = asPersistentMap(Stats.createGlobalStats(fileChannel.size(), metadataLength, columns.length, recordGroupsStats));\n return new PersistentArrayMap(new Object[] { RECORD_GROUPS, recordGroupStatsMaps, COLUMNS, columnStatsMaps, GLOBAL, globalStatsMap });\n }\n\n public Object getSchema() {\n return Schema.unparse(types, fileMetadata.schema);\n }\n\n public Object getPlainSchema() {\n return Schema.unparsePlain(types, fileMetadata.schema);\n }\n\n @Override\n public void close() throws IOException {\n fileChannel.close();\n }\n\n private static boolean isValidMagicBytes(ByteBuffer bb) {\n return Arrays.equals(Constants.magicBytes, Types.toByteArray(bb));\n }\n\n private static final int fixedIntLength = 4;\n\n private static final class MetadataReadResult {\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n MetadataReadResult(Metadata.File fileMetadata, long metadataLength) {\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n }\n\n private static MetadataReadResult readMetadata(File file, FileChannel fileChannel) throws IOException {\n long length = fileChannel.size();\n long lastMagicBytesPosition = length - Constants.magicBytes.length;\n ByteBuffer lastMagicBytesBuffer = Utils.mapFileChannel(fileChannel, lastMagicBytesPosition, Constants.magicBytes.length);\n if (!isValidMagicBytes(lastMagicBytesBuffer)) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n long metadataLengthPosition = lastMagicBytesPosition - fixedIntLength;\n if (metadataLengthPosition < Constants.magicBytes.length) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataLengthBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition, fixedIntLength);\n metadataLengthBuffer.order(ByteOrder.LITTLE_ENDIAN);\n long metadataLength = metadataLengthBuffer.getInt();\n if (metadataLength <= 0) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition - metadataLength, metadataLength);\n return new MetadataReadResult(Metadata.File.read(metadataBuffer), metadataLength);\n }\n\n private static Iterator getBundlesIterator(final File file, final Iterator recordGroupReaders) {\n if (!recordGroupReaders.hasNext()) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n private Iterator bundleIterator = recordGroupReaders.next().iterator();\n\n private void step() {\n if (recordGroupReaders.hasNext()) {\n bundleIterator = recordGroupReaders.next().iterator();\n } else {\n bundleIterator = null;\n }\n }\n\n @Override\n public boolean hasNext() {\n if (bundleIterator == null) {\n return false;\n }\n ", "post_mask_code": "\n }\n\n @Override\n public Bundle next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return bundleIterator.next();\n }\n };\n }\n\n private interface IReduceFutureFactory {\n\n Future get(Bundle bundle);\n }\n\n private static final class ReduceFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n ReduceFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduce(reduceFn, completeFn, initFn, assembleFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n ReduceSampledFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampled(reduceFn, completeFn, initFn, assembleFn, sampleFn);\n }\n });\n }\n }\n\n private static final class ReduceIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn indexedByFn;\n\n ReduceIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceIndexed(reduceFn, completeFn, initFn, assembleFn, indexedByFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledAndIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n private final IFn indexedByFn;\n\n ReduceSampledAndIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampledAndIndexed(reduceFn, completeFn, initFn, assembleFn, sampleFn, indexedByFn);\n }\n });\n }\n }\n\n private IReduceFutureFactory getReduceFutureFactory(IFn reduceFn, IFn completeFn, IFn initFn, Assemble.Fn assembleFn, IFn sampleFn, IFn indexedByFn) {\n if (sampleFn == null) {\n if (indexedByFn == null) {\n return new ReduceFutureFactory(assembleFn, reduceFn, completeFn, initFn);\n } else {\n return new ReduceIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, indexedByFn);\n }\n } else {\n if (indexedByFn == null) {\n return new ReduceSampledFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn);\n } else {\n return new ReduceSampledAndIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn, indexedByFn);\n }\n }\n }\n\n private static Iterator getReducedChunksIterator(final Iterator bundlesIterator, final IReduceFutureFactory reduceFutureFactory) {\n int n = 2 + Runtime.getRuntime().availableProcessors();\n final LinkedList> futures = new LinkedList>();\n int k = 0;\n while (bundlesIterator.hasNext() && k < n) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n k += 1;\n }\n return new AReadOnlyIterator() {\n\n @Override\n public boolean hasNext() {\n return !futures.isEmpty();\n }\n\n @Override\n public Object next() {\n Future fut = futures.pollFirst();\n Object obj = Utils.tryGetFuture(fut);\n if (bundlesIterator.hasNext()) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n }\n return obj;\n }\n };\n }\n\n public final class LazyView extends View {\n\n private Options.ReadOptions options;\n\n private Schema.QueryResult queryResult;\n\n private Assemble.Fn assembleFn;\n\n LazyView(Options.ReadOptions options) {\n super(options.bundleSize);\n this.options = options;\n }\n\n private synchronized Schema.QueryResult getQueryResult() {\n if (queryResult == null) {\n queryResult = FileReader.this.getQueryResult(options);\n }\n return queryResult;\n }\n\n private synchronized Schema.Column[] getQueriedColumns() {\n return getQueryResult().columns;\n }\n\n private synchronized Assemble.Fn getAssembleFn() {\n if (assembleFn == null) {\n assembleFn = Assemble.getFn(FileReader.this.types, getQueryResult().schema);\n }\n return assembleFn;\n }\n\n @Override\n protected View withOptions(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n @Override\n protected Options.ReadOptions getReadOptions() {\n return options;\n }\n\n @Override\n protected Iterable getReducedChunks(final IFn reduceFn, final IFn completeFn, final IFn initFn, final int bundleSize) {\n return new Iterable() {\n\n @Override\n public Iterator iterator() {\n return FileReader.getReducedChunksIterator(getBundlesIterator(bundleSize), getReduceFutureFactory(reduceFn, completeFn, initFn, getAssembleFn(), options.sampleFn, options.indexedByFn));\n }\n };\n }\n\n private Iterator getBundlesIterator(int bundleSize) {\n return FileReader.getBundlesIterator(FileReader.this.file, getRecordGroupReaders(getQueriedColumns(), bundleSize));\n }\n }\n}\n"} {"task_id": "Java_515", "language": "Java", "task_type": "empty", "source_file": "java/github/jwhitbeck/dendrite/dendrite/java-src/dendrite/java/FileReader.java", "mask_start_position": 5156, "mask_end_position": 5156, "canonical_solution": "", "pre_mask_code": "package dendrite.java;\n\nimport clojure.lang.Agent;\nimport clojure.lang.IFn;\nimport clojure.lang.IPersistentMap;\nimport clojure.lang.IPersistentVector;\nimport clojure.lang.Keyword;\nimport clojure.lang.PersistentArrayMap;\nimport clojure.lang.Symbol;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\n\npublic final class FileReader implements Closeable, IReader {\n\n public static final Keyword RECORD_GROUPS = Keyword.intern(\"record-groups\"), COLUMNS = Keyword.intern(\"columns\"), GLOBAL = Keyword.intern(\"global\"), DATA_HEADER_LENGTH = Keyword.intern(\"data-header-length\"), REPETITION_LEVELS_LENGTH = Keyword.intern(\"repetition-levels-length\"), DEFINITION_LEVELS_LENGTH = Keyword.intern(\"definition-levels-length\"), METADATA_LENGTH = Keyword.intern(\"metadata-length\"), DATA_LENGTH = Keyword.intern(\"data-length\"), DICTIONARY_HEADER_LENGTH = Keyword.intern(\"dictionary-header-length\"), DICTIONARY_LENGTH = Keyword.intern(\"dictionary-length\"), NUM_VALUES = Keyword.intern(\"num-values\"), NUM_NON_NIL_VALUES = Keyword.intern(\"num-non-nil-values\"), LENGTH = Keyword.intern(\"length\"), NUM_PAGES = Keyword.intern(\"num-pages\"), NUM_DICTIONARY_VALUES = Keyword.intern(\"num-dictionary-values\"), TYPE = Keyword.intern(\"type\"), ENCODING = Keyword.intern(\"encoding\"), COMPRESSION = Keyword.intern(\"compression\"), MAX_REPETITION_LEVEL = Keyword.intern(\"max-repetition-level\"), MAX_DEFINITION_LEVEL = Keyword.intern(\"max-definition-level\"), PATH = Keyword.intern(\"path\"), NUM_RECORDS = Keyword.intern(\"num-records\"), NUM_RECORD_GROUPS = Keyword.intern(\"num-record-groups\"), NUM_COLUMN_CHUNKS = Keyword.intern(\"num-column-chunks\"), NUM_COLUMNS = Keyword.intern(\"num-columns\");\n\n final Types types;\n\n final File file;\n\n final FileChannel fileChannel;\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n private FileReader(Types types, File file, FileChannel fileChannel, Metadata.File fileMetadata, long metadataLength) {\n this.types = types;\n this.file = file;\n this.fileChannel = fileChannel;\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n\n public static FileReader create(Options.ReaderOptions options, File file) throws IOException {\n FileChannel fileChannel = Utils.getReadingFileChannel(file);\n MetadataReadResult res = readMetadata(file, fileChannel);\n Types types = Types.create(options.customTypeDefinitions, res.fileMetadata.customTypes);\n return new FileReader(types, file, fileChannel, res.fileMetadata, res.metadataLength);\n }\n\n public ByteBuffer getMetadata() {\n return fileMetadata.metadata;\n }\n\n public long getNumRecords() {\n return fileMetadata.getNumRecords();\n }\n\n public Map getCustomTypeMappings() {\n Map customTypeMappings = new HashMap();\n for (CustomType ct : fileMetadata.customTypes) {\n customTypeMappings.put(ct.sym, types.getTypeSymbol(ct.baseType));\n }\n return customTypeMappings;\n }\n\n Schema.QueryResult getQueryResult(Options.ReadOptions options) {\n return Schema.applyQuery(types, options.isMissingFieldsAsNil, options.readers, Schema.getSubSchema(options.subSchemaPath, fileMetadata.schema), options.query);\n }\n\n @Override\n public View read(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n private Iterator getRecordGroupReaders(Schema.Column[] columns, int bundleSize) {\n return getRecordGroupReaders(types, fileChannel, Constants.magicBytes.length, fileMetadata.recordGroups, columns, bundleSize);\n }\n\n private static Iterator getRecordGroupReaders(final Types types, final FileChannel fileChannel, final long offset, final Metadata.RecordGroup[] recordGroupsMetadata, final Schema.Column[] queriedColumns, final int bundleSize) {\n final int numRecordGroups = recordGroupsMetadata.length;\n if (numRecordGroups == 0) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n int i = 0;\n\n long nextOffset = offset;\n\n @Override\n public boolean hasNext() {\n return i < numRecordGroups;\n }\n\n @Override\n public RecordGroup.Reader next() {\n Metadata.RecordGroup recordGroupMetadata = recordGroupsMetadata[i];\n long length = recordGroupMetadata.length;\n ByteBuffer bb;\n try {\n bb = Utils.mapFileChannel(fileChannel, nextOffset, length);\n } catch (IOExc", "post_mask_code": "eption e) {\n throw new IllegalStateException(e);\n }\n RecordGroup.Reader recordGroupReader = new RecordGroup.Reader(types, bb, recordGroupMetadata, queriedColumns, bundleSize);\n nextOffset += length;\n i += 1;\n return recordGroupReader;\n }\n };\n }\n\n private IPersistentMap asPersistentMap(Stats.Global globalStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_COLUMNS, globalStats.numColumns).assoc(NUM_RECORD_GROUPS, globalStats.numRecordGroups).assoc(NUM_RECORDS, globalStats.numRecords).assoc(LENGTH, globalStats.length).assoc(DATA_HEADER_LENGTH, globalStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, globalStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, globalStats.definitionLevelsLength).assoc(DATA_LENGTH, globalStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, globalStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, globalStats.dictionaryLength).assoc(METADATA_LENGTH, globalStats.metadataLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.Column columnStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(TYPE, columnStats.type).assoc(ENCODING, columnStats.encoding).assoc(COMPRESSION, columnStats.compression).assoc(PATH, columnStats.path).assoc(MAX_REPETITION_LEVEL, columnStats.maxRepetitionLevel).assoc(MAX_DEFINITION_LEVEL, columnStats.maxDefinitionLevel).assoc(NUM_COLUMN_CHUNKS, columnStats.numColumnChunks).assoc(NUM_PAGES, columnStats.numPages).assoc(NUM_VALUES, columnStats.numValues).assoc(NUM_NON_NIL_VALUES, columnStats.numNonNilValues).assoc(LENGTH, columnStats.length).assoc(DATA_HEADER_LENGTH, columnStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, columnStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, columnStats.definitionLevelsLength).assoc(DATA_LENGTH, columnStats.dataLength).assoc(NUM_DICTIONARY_VALUES, columnStats.numDictionaryValues).assoc(DICTIONARY_HEADER_LENGTH, columnStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, columnStats.dictionaryLength).persistent();\n }\n\n private IPersistentMap asPersistentMap(Stats.RecordGroup recordGroupStats) {\n return PersistentArrayMap.EMPTY.asTransient().assoc(NUM_RECORDS, recordGroupStats.numRecords).assoc(NUM_COLUMN_CHUNKS, recordGroupStats.numColumnChunks).assoc(LENGTH, recordGroupStats.length).assoc(DATA_HEADER_LENGTH, recordGroupStats.dataHeaderLength).assoc(REPETITION_LEVELS_LENGTH, recordGroupStats.repetitionLevelsLength).assoc(DEFINITION_LEVELS_LENGTH, recordGroupStats.definitionLevelsLength).assoc(DATA_LENGTH, recordGroupStats.dataLength).assoc(DICTIONARY_HEADER_LENGTH, recordGroupStats.dictionaryHeaderLength).assoc(DICTIONARY_LENGTH, recordGroupStats.dictionaryLength).persistent();\n }\n\n public IPersistentMap getStats() throws IOException {\n IPersistentVector[] paths = Schema.getPaths(fileMetadata.schema);\n Schema.Column[] columns = Schema.getColumns(fileMetadata.schema);\n List recordGroupsStats = new ArrayList();\n List> columnChunkStatsByColumn = new ArrayList>(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n columnChunkStatsByColumn.add(new ArrayList());\n }\n Iterator recordGroupReaders = getRecordGroupReaders(columns, 100);\n while (recordGroupReaders.hasNext()) {\n RecordGroup.Reader recordGroupReader = recordGroupReaders.next();\n List columnChunksStats = recordGroupReader.getColumnChunkStats();\n recordGroupsStats.add(Stats.createRecordGroupStats(recordGroupReader.getNumRecords(), columnChunksStats));\n int i = 0;\n for (Stats.ColumnChunk columnChunkStats : columnChunksStats) {\n columnChunkStatsByColumn.get(i).add(columnChunkStats);\n i += 1;\n }\n }\n List columnsStats = new ArrayList(columns.length);\n for (int i = 0; i < columns.length; ++i) {\n Schema.Column col = columns[i];\n columnsStats.add(Stats.createColumnStats(types.getTypeSymbol(col.type), types.getEncodingSymbol(col.encoding), types.getCompressionSymbol(col.compression), col.repetitionLevel, col.definitionLevel, paths[i], columnChunkStatsByColumn.get(i)));\n }\n List recordGroupStatsMaps = new ArrayList();\n for (Stats.RecordGroup recordGroupStats : recordGroupsStats) {\n recordGroupStatsMaps.add(asPersistentMap(recordGroupStats));\n }\n List columnStatsMaps = new ArrayList();\n for (Stats.Column columnStats : columnsStats) {\n columnStatsMaps.add(asPersistentMap(columnStats));\n }\n IPersistentMap globalStatsMap = asPersistentMap(Stats.createGlobalStats(fileChannel.size(), metadataLength, columns.length, recordGroupsStats));\n return new PersistentArrayMap(new Object[] { RECORD_GROUPS, recordGroupStatsMaps, COLUMNS, columnStatsMaps, GLOBAL, globalStatsMap });\n }\n\n public Object getSchema() {\n return Schema.unparse(types, fileMetadata.schema);\n }\n\n public Object getPlainSchema() {\n return Schema.unparsePlain(types, fileMetadata.schema);\n }\n\n @Override\n public void close() throws IOException {\n fileChannel.close();\n }\n\n private static boolean isValidMagicBytes(ByteBuffer bb) {\n return Arrays.equals(Constants.magicBytes, Types.toByteArray(bb));\n }\n\n private static final int fixedIntLength = 4;\n\n private static final class MetadataReadResult {\n\n final Metadata.File fileMetadata;\n\n final long metadataLength;\n\n MetadataReadResult(Metadata.File fileMetadata, long metadataLength) {\n this.fileMetadata = fileMetadata;\n this.metadataLength = metadataLength;\n }\n }\n\n private static MetadataReadResult readMetadata(File file, FileChannel fileChannel) throws IOException {\n long length = fileChannel.size();\n long lastMagicBytesPosition = length - Constants.magicBytes.length;\n ByteBuffer lastMagicBytesBuffer = Utils.mapFileChannel(fileChannel, lastMagicBytesPosition, Constants.magicBytes.length);\n if (!isValidMagicBytes(lastMagicBytesBuffer)) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n long metadataLengthPosition = lastMagicBytesPosition - fixedIntLength;\n if (metadataLengthPosition < Constants.magicBytes.length) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataLengthBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition, fixedIntLength);\n metadataLengthBuffer.order(ByteOrder.LITTLE_ENDIAN);\n long metadataLength = metadataLengthBuffer.getInt();\n if (metadataLength <= 0) {\n throw new IllegalStateException(String.format(\"%s is not a valid dendrite file.\", file.getPath()));\n }\n ByteBuffer metadataBuffer = Utils.mapFileChannel(fileChannel, metadataLengthPosition - metadataLength, metadataLength);\n return new MetadataReadResult(Metadata.File.read(metadataBuffer), metadataLength);\n }\n\n private static Iterator getBundlesIterator(final File file, final Iterator recordGroupReaders) {\n if (!recordGroupReaders.hasNext()) {\n return Collections.emptyList().iterator();\n }\n return new AReadOnlyIterator() {\n\n private Iterator bundleIterator = recordGroupReaders.next().iterator();\n\n private void step() {\n if (recordGroupReaders.hasNext()) {\n bundleIterator = recordGroupReaders.next().iterator();\n } else {\n bundleIterator = null;\n }\n }\n\n @Override\n public boolean hasNext() {\n if (bundleIterator == null) {\n return false;\n }\n try {\n if (bundleIterator.hasNext()) {\n return true;\n } else {\n step();\n return bundleIterator != null && bundleIterator.hasNext();\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Error while reading from \" + file, e);\n }\n }\n\n @Override\n public Bundle next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return bundleIterator.next();\n }\n };\n }\n\n private interface IReduceFutureFactory {\n\n Future get(Bundle bundle);\n }\n\n private static final class ReduceFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n ReduceFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduce(reduceFn, completeFn, initFn, assembleFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n ReduceSampledFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampled(reduceFn, completeFn, initFn, assembleFn, sampleFn);\n }\n });\n }\n }\n\n private static final class ReduceIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn indexedByFn;\n\n ReduceIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceIndexed(reduceFn, completeFn, initFn, assembleFn, indexedByFn);\n }\n });\n }\n }\n\n private static final class ReduceSampledAndIndexedFutureFactory implements IReduceFutureFactory {\n\n private final Assemble.Fn assembleFn;\n\n private final IFn reduceFn;\n\n private final IFn completeFn;\n\n private final IFn initFn;\n\n private final IFn sampleFn;\n\n private final IFn indexedByFn;\n\n ReduceSampledAndIndexedFutureFactory(Assemble.Fn assembleFn, IFn reduceFn, IFn completeFn, IFn initFn, IFn sampleFn, IFn indexedByFn) {\n this.assembleFn = assembleFn;\n this.reduceFn = reduceFn;\n this.completeFn = completeFn;\n this.initFn = initFn;\n this.sampleFn = sampleFn;\n this.indexedByFn = indexedByFn;\n }\n\n @Override\n public Future get(final Bundle bundle) {\n return Agent.soloExecutor.submit(new Callable() {\n\n public Object call() {\n return bundle.reduceSampledAndIndexed(reduceFn, completeFn, initFn, assembleFn, sampleFn, indexedByFn);\n }\n });\n }\n }\n\n private IReduceFutureFactory getReduceFutureFactory(IFn reduceFn, IFn completeFn, IFn initFn, Assemble.Fn assembleFn, IFn sampleFn, IFn indexedByFn) {\n if (sampleFn == null) {\n if (indexedByFn == null) {\n return new ReduceFutureFactory(assembleFn, reduceFn, completeFn, initFn);\n } else {\n return new ReduceIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, indexedByFn);\n }\n } else {\n if (indexedByFn == null) {\n return new ReduceSampledFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn);\n } else {\n return new ReduceSampledAndIndexedFutureFactory(assembleFn, reduceFn, completeFn, initFn, sampleFn, indexedByFn);\n }\n }\n }\n\n private static Iterator getReducedChunksIterator(final Iterator bundlesIterator, final IReduceFutureFactory reduceFutureFactory) {\n int n = 2 + Runtime.getRuntime().availableProcessors();\n final LinkedList> futures = new LinkedList>();\n int k = 0;\n while (bundlesIterator.hasNext() && k < n) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n k += 1;\n }\n return new AReadOnlyIterator() {\n\n @Override\n public boolean hasNext() {\n return !futures.isEmpty();\n }\n\n @Override\n public Object next() {\n Future fut = futures.pollFirst();\n Object obj = Utils.tryGetFuture(fut);\n if (bundlesIterator.hasNext()) {\n futures.addLast(reduceFutureFactory.get(bundlesIterator.next()));\n }\n return obj;\n }\n };\n }\n\n public final class LazyView extends View {\n\n private Options.ReadOptions options;\n\n private Schema.QueryResult queryResult;\n\n private Assemble.Fn assembleFn;\n\n LazyView(Options.ReadOptions options) {\n super(options.bundleSize);\n this.options = options;\n }\n\n private synchronized Schema.QueryResult getQueryResult() {\n if (queryResult == null) {\n queryResult = FileReader.this.getQueryResult(options);\n }\n return queryResult;\n }\n\n private synchronized Schema.Column[] getQueriedColumns() {\n return getQueryResult().columns;\n }\n\n private synchronized Assemble.Fn getAssembleFn() {\n if (assembleFn == null) {\n assembleFn = Assemble.getFn(FileReader.this.types, getQueryResult().schema);\n }\n return assembleFn;\n }\n\n @Override\n protected View withOptions(Options.ReadOptions options) {\n return new LazyView(options);\n }\n\n @Override\n protected Options.ReadOptions getReadOptions() {\n return options;\n }\n\n @Override\n protected Iterable getReducedChunks(final IFn reduceFn, final IFn completeFn, final IFn initFn, final int bundleSize) {\n return new Iterable() {\n\n @Override\n public Iterator iterator() {\n return FileReader.getReducedChunksIterator(getBundlesIterator(bundleSize), getReduceFutureFactory(reduceFn, completeFn, initFn, getAssembleFn(), options.sampleFn, options.indexedByFn));\n }\n };\n }\n\n private Iterator getBundlesIterator(int bundleSize) {\n return FileReader.getBundlesIterator(FileReader.this.file, getRecordGroupReaders(getQueriedColumns(), bundleSize));\n }\n }\n}\n"} {"task_id": "Java_516", "language": "Java", "task_type": "method_signature", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/awt/image/InputStreamImageSource.java", "mask_start_position": 6482, "mask_end_position": 6504, "canonical_solution": "public void doFetch() ", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.awt.image;\n\nimport java.awt.image.*;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.BufferedInputStream;\nimport java.util.Hashtable;\n\npublic abstract class InputStreamImageSource implements ImageProducer, ImageFetchable {\n\n ImageConsumerQueue consumers;\n\n ImageDecoder decoder;\n\n ImageDecoder decoders;\n\n boolean awaitingFetch = false;\n\n abstract boolean checkSecurity(Object context, boolean quiet);\n\n int countConsumers(ImageConsumerQueue cq) {\n int i = 0;\n while (cq != null) {\n i++;\n cq = cq.next;\n }\n return i;\n }\n\n synchronized int countConsumers() {\n ImageDecoder id = decoders;\n int i = countConsumers(consumers);\n while (id != null) {\n i += countConsumers(id.queue);\n id = id.next;\n }\n return i;\n }\n\n public void addConsumer(ImageConsumer ic) {\n addConsumer(ic, false);\n }\n\n synchronized void printQueue(ImageConsumerQueue cq, String prefix) {\n while (cq != null) {\n System.out.println(prefix + cq);\n cq = cq.next;\n }\n }\n\n synchronized void printQueues(String title) {\n System.out.println(title + \"[ -----------\");\n printQueue(consumers, \" \");\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n System.out.println(\" \" + id);\n printQueue(id.queue, \" \");\n }\n System.out.println(\"----------- ]\" + title);\n }\n\n synchronized void addConsumer(ImageConsumer ic, boolean produce) {\n checkSecurity(null, false);\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n // This consumer is already being fed.\n return;\n }\n }\n ImageConsumerQueue cq = consumers;\n while (cq != null && cq.consumer != ic) {\n cq = cq.next;\n }\n if (cq == null) {\n cq = new ImageConsumerQueue(this, ic);\n cq.next = consumers;\n consumers = cq;\n } else {\n if (!cq.secure) {\n Object context = null;\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n context = security.getSecurityContext();\n }\n if (cq.securityContext == null) {\n cq.securityContext = context;\n } else if (!cq.securityContext.equals(context)) {\n // If there are two different security contexts that both\n // have a handle on the same ImageConsumer, then there has\n // been a security breach and whether or not they trade\n // image data is small fish compared to what they could be\n // trading. Throw a Security exception anyway...\n errorConsumer(cq, false);\n throw new SecurityException(\"Applets are trading image data!\");\n }\n }\n cq.interested = true;\n }\n if (produce && decoder == null) {\n startProduction();\n }\n }\n\n public synchronized boolean isConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n return true;\n }\n }\n return ImageConsumerQueue.isConsumer(consumers, ic);\n }\n\n private void errorAllConsumers(ImageConsumerQueue cq, boolean needReload) {\n while (cq != null) {\n if (cq.interested) {\n errorConsumer(cq, needReload);\n }\n cq = cq.next;\n }\n }\n\n private void errorConsumer(ImageConsumerQueue cq, boolean needReload) {\n cq.consumer.imageComplete(ImageConsumer.IMAGEERROR);\n if (needReload && cq.consumer instanceof ImageRepresentation) {\n ((ImageRepresentation) cq.consumer).image.flush();\n }\n removeConsumer(cq.consumer);\n }\n\n public synchronized void removeConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n id.removeConsumer(ic);\n }\n consumers = ImageConsumerQueue.removeConsumer(consumers, ic, false);\n }\n\n public void startProduction(ImageConsumer ic) {\n addConsumer(ic, true);\n }\n\n private synchronized void startProduction() {\n if (!awaitingFetch) {\n ImageFetcher.add(this);\n awaitingFetch = true;\n }\n }\n\n private synchronized void stopProduction() {\n if (awaitingFetch) {\n ImageFetcher.remove(this);\n awaitingFetch = false;\n }\n }\n\n public void requestTopDownLeftRightResend(ImageConsumer ic) {\n }\n\n protected abstract ImageDecoder getDecoder();\n\n protected ImageDecoder decoderForType(InputStream is, String content_type) {\n // Don't believe the content type - file extensions can\n return null;\n }\n\n protected ImageDecoder getDecoder(InputStream is) {\n if (!is.markSupported())\n is = new BufferedInputStream(is);\n try {\n /* changed to support png\n is.mark(6);\n */\n is.mark(8);\n int c1 = is.read();\n int c2 = is.read();\n int c3 = is.read();\n int c4 = is.read();\n int c5 = is.read();\n int c6 = is.read();\n // added to support png\n int c7 = is.read();\n int c8 = is.read();\n // end of adding\n is.reset();\n is.mark(-1);\n if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8') {\n return new GifImageDecoder(this, is);\n } else if (c1 == '\\377' && c2 == '\\330' && c3 == '\\377') {\n return new JPEGImageDecoder(this, is);\n } else if (c1 == '#' && c2 == 'd' && c3 == 'e' && c4 == 'f') {\n return new XbmImageDecoder(this, is);\n // added to support png\n } else if (c1 == 137 && c2 == 80 && c3 == 78 && c4 == 71 && c5 == 13 && c6 == 10 && c7 == 26 && c8 == 10) {\n return new PNGImageDecoder(this, is);\n }\n // end of adding\n } catch (IOException e) {\n }\n return null;\n }\n\n ", "post_mask_code": "{\n synchronized (this) {\n if (consumers == null) {\n awaitingFetch = false;\n return;\n }\n }\n ImageDecoder imgd = getDecoder();\n if (imgd == null) {\n badDecoder();\n } else {\n setDecoder(imgd);\n try {\n imgd.produceImage();\n } catch (IOException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } catch (ImageFormatException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } finally {\n removeDecoder(imgd);\n if (Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) {\n errorAllConsumers(imgd.queue, true);\n } else {\n errorAllConsumers(imgd.queue, false);\n }\n }\n }\n }\n\n private void badDecoder() {\n ImageConsumerQueue cq;\n synchronized (this) {\n cq = consumers;\n consumers = null;\n awaitingFetch = false;\n }\n errorAllConsumers(cq, false);\n }\n\n private void setDecoder(ImageDecoder mydecoder) {\n ImageConsumerQueue cq;\n synchronized (this) {\n mydecoder.next = decoders;\n decoders = mydecoder;\n decoder = mydecoder;\n cq = consumers;\n mydecoder.queue = cq;\n consumers = null;\n awaitingFetch = false;\n }\n while (cq != null) {\n if (cq.interested) {\n // Now that there is a decoder, security may have changed\n // so reverify it here, just in case.\n if (!checkSecurity(cq.securityContext, true)) {\n errorConsumer(cq, false);\n }\n }\n cq = cq.next;\n }\n }\n\n private synchronized void removeDecoder(ImageDecoder mydecoder) {\n doneDecoding(mydecoder);\n ImageDecoder idprev = null;\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id == mydecoder) {\n if (idprev == null) {\n decoders = id.next;\n } else {\n idprev.next = id.next;\n }\n break;\n }\n idprev = id;\n }\n }\n\n synchronized void doneDecoding(ImageDecoder mydecoder) {\n if (decoder == mydecoder) {\n decoder = null;\n if (consumers != null) {\n startProduction();\n }\n }\n }\n\n void latchConsumers(ImageDecoder id) {\n doneDecoding(id);\n }\n\n synchronized void flush() {\n decoder = null;\n }\n}\n"} {"task_id": "Java_517", "language": "Java", "task_type": "method_body", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/awt/image/InputStreamImageSource.java", "mask_start_position": 9211, "mask_end_position": 9244, "canonical_solution": "{\n doneDecoding(id);\n }", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.awt.image;\n\nimport java.awt.image.*;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.BufferedInputStream;\nimport java.util.Hashtable;\n\npublic abstract class InputStreamImageSource implements ImageProducer, ImageFetchable {\n\n ImageConsumerQueue consumers;\n\n ImageDecoder decoder;\n\n ImageDecoder decoders;\n\n boolean awaitingFetch = false;\n\n abstract boolean checkSecurity(Object context, boolean quiet);\n\n int countConsumers(ImageConsumerQueue cq) {\n int i = 0;\n while (cq != null) {\n i++;\n cq = cq.next;\n }\n return i;\n }\n\n synchronized int countConsumers() {\n ImageDecoder id = decoders;\n int i = countConsumers(consumers);\n while (id != null) {\n i += countConsumers(id.queue);\n id = id.next;\n }\n return i;\n }\n\n public void addConsumer(ImageConsumer ic) {\n addConsumer(ic, false);\n }\n\n synchronized void printQueue(ImageConsumerQueue cq, String prefix) {\n while (cq != null) {\n System.out.println(prefix + cq);\n cq = cq.next;\n }\n }\n\n synchronized void printQueues(String title) {\n System.out.println(title + \"[ -----------\");\n printQueue(consumers, \" \");\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n System.out.println(\" \" + id);\n printQueue(id.queue, \" \");\n }\n System.out.println(\"----------- ]\" + title);\n }\n\n synchronized void addConsumer(ImageConsumer ic, boolean produce) {\n checkSecurity(null, false);\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n // This consumer is already being fed.\n return;\n }\n }\n ImageConsumerQueue cq = consumers;\n while (cq != null && cq.consumer != ic) {\n cq = cq.next;\n }\n if (cq == null) {\n cq = new ImageConsumerQueue(this, ic);\n cq.next = consumers;\n consumers = cq;\n } else {\n if (!cq.secure) {\n Object context = null;\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n context = security.getSecurityContext();\n }\n if (cq.securityContext == null) {\n cq.securityContext = context;\n } else if (!cq.securityContext.equals(context)) {\n // If there are two different security contexts that both\n // have a handle on the same ImageConsumer, then there has\n // been a security breach and whether or not they trade\n // image data is small fish compared to what they could be\n // trading. Throw a Security exception anyway...\n errorConsumer(cq, false);\n throw new SecurityException(\"Applets are trading image data!\");\n }\n }\n cq.interested = true;\n }\n if (produce && decoder == null) {\n startProduction();\n }\n }\n\n public synchronized boolean isConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n return true;\n }\n }\n return ImageConsumerQueue.isConsumer(consumers, ic);\n }\n\n private void errorAllConsumers(ImageConsumerQueue cq, boolean needReload) {\n while (cq != null) {\n if (cq.interested) {\n errorConsumer(cq, needReload);\n }\n cq = cq.next;\n }\n }\n\n private void errorConsumer(ImageConsumerQueue cq, boolean needReload) {\n cq.consumer.imageComplete(ImageConsumer.IMAGEERROR);\n if (needReload && cq.consumer instanceof ImageRepresentation) {\n ((ImageRepresentation) cq.consumer).image.flush();\n }\n removeConsumer(cq.consumer);\n }\n\n public synchronized void removeConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n id.removeConsumer(ic);\n }\n consumers = ImageConsumerQueue.removeConsumer(consumers, ic, false);\n }\n\n public void startProduction(ImageConsumer ic) {\n addConsumer(ic, true);\n }\n\n private synchronized void startProduction() {\n if (!awaitingFetch) {\n ImageFetcher.add(this);\n awaitingFetch = true;\n }\n }\n\n private synchronized void stopProduction() {\n if (awaitingFetch) {\n ImageFetcher.remove(this);\n awaitingFetch = false;\n }\n }\n\n public void requestTopDownLeftRightResend(ImageConsumer ic) {\n }\n\n protected abstract ImageDecoder getDecoder();\n\n protected ImageDecoder decoderForType(InputStream is, String content_type) {\n // Don't believe the content type - file extensions can\n return null;\n }\n\n protected ImageDecoder getDecoder(InputStream is) {\n if (!is.markSupported())\n is = new BufferedInputStream(is);\n try {\n /* changed to support png\n is.mark(6);\n */\n is.mark(8);\n int c1 = is.read();\n int c2 = is.read();\n int c3 = is.read();\n int c4 = is.read();\n int c5 = is.read();\n int c6 = is.read();\n // added to support png\n int c7 = is.read();\n int c8 = is.read();\n // end of adding\n is.reset();\n is.mark(-1);\n if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8') {\n return new GifImageDecoder(this, is);\n } else if (c1 == '\\377' && c2 == '\\330' && c3 == '\\377') {\n return new JPEGImageDecoder(this, is);\n } else if (c1 == '#' && c2 == 'd' && c3 == 'e' && c4 == 'f') {\n return new XbmImageDecoder(this, is);\n // added to support png\n } else if (c1 == 137 && c2 == 80 && c3 == 78 && c4 == 71 && c5 == 13 && c6 == 10 && c7 == 26 && c8 == 10) {\n return new PNGImageDecoder(this, is);\n }\n // end of adding\n } catch (IOException e) {\n }\n return null;\n }\n\n public void doFetch() {\n synchronized (this) {\n if (consumers == null) {\n awaitingFetch = false;\n return;\n }\n }\n ImageDecoder imgd = getDecoder();\n if (imgd == null) {\n badDecoder();\n } else {\n setDecoder(imgd);\n try {\n imgd.produceImage();\n } catch (IOException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } catch (ImageFormatException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } finally {\n removeDecoder(imgd);\n if (Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) {\n errorAllConsumers(imgd.queue, true);\n } else {\n errorAllConsumers(imgd.queue, false);\n }\n }\n }\n }\n\n private void badDecoder() {\n ImageConsumerQueue cq;\n synchronized (this) {\n cq = consumers;\n consumers = null;\n awaitingFetch = false;\n }\n errorAllConsumers(cq, false);\n }\n\n private void setDecoder(ImageDecoder mydecoder) {\n ImageConsumerQueue cq;\n synchronized (this) {\n mydecoder.next = decoders;\n decoders = mydecoder;\n decoder = mydecoder;\n cq = consumers;\n mydecoder.queue = cq;\n consumers = null;\n awaitingFetch = false;\n }\n while (cq != null) {\n if (cq.interested) {\n // Now that there is a decoder, security may have changed\n // so reverify it here, just in case.\n if (!checkSecurity(cq.securityContext, true)) {\n errorConsumer(cq, false);\n }\n }\n cq = cq.next;\n }\n }\n\n private synchronized void removeDecoder(ImageDecoder mydecoder) {\n doneDecoding(mydecoder);\n ImageDecoder idprev = null;\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id == mydecoder) {\n if (idprev == null) {\n decoders = id.next;\n } else {\n idprev.next = id.next;\n }\n break;\n }\n idprev = id;\n }\n }\n\n synchronized void doneDecoding(ImageDecoder mydecoder) {\n if (decoder == mydecoder) {\n decoder = null;\n if (consumers != null) {\n startProduction();\n }\n }\n }\n\n void latchConsumers(ImageDecoder id) ", "post_mask_code": "\n\n synchronized void flush() {\n decoder = null;\n }\n}\n"} {"task_id": "Java_518", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/awt/image/InputStreamImageSource.java", "mask_start_position": 7513, "mask_end_position": 7544, "canonical_solution": "\n ImageConsumerQueue cq;", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.awt.image;\n\nimport java.awt.image.*;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.BufferedInputStream;\nimport java.util.Hashtable;\n\npublic abstract class InputStreamImageSource implements ImageProducer, ImageFetchable {\n\n ImageConsumerQueue consumers;\n\n ImageDecoder decoder;\n\n ImageDecoder decoders;\n\n boolean awaitingFetch = false;\n\n abstract boolean checkSecurity(Object context, boolean quiet);\n\n int countConsumers(ImageConsumerQueue cq) {\n int i = 0;\n while (cq != null) {\n i++;\n cq = cq.next;\n }\n return i;\n }\n\n synchronized int countConsumers() {\n ImageDecoder id = decoders;\n int i = countConsumers(consumers);\n while (id != null) {\n i += countConsumers(id.queue);\n id = id.next;\n }\n return i;\n }\n\n public void addConsumer(ImageConsumer ic) {\n addConsumer(ic, false);\n }\n\n synchronized void printQueue(ImageConsumerQueue cq, String prefix) {\n while (cq != null) {\n System.out.println(prefix + cq);\n cq = cq.next;\n }\n }\n\n synchronized void printQueues(String title) {\n System.out.println(title + \"[ -----------\");\n printQueue(consumers, \" \");\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n System.out.println(\" \" + id);\n printQueue(id.queue, \" \");\n }\n System.out.println(\"----------- ]\" + title);\n }\n\n synchronized void addConsumer(ImageConsumer ic, boolean produce) {\n checkSecurity(null, false);\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n // This consumer is already being fed.\n return;\n }\n }\n ImageConsumerQueue cq = consumers;\n while (cq != null && cq.consumer != ic) {\n cq = cq.next;\n }\n if (cq == null) {\n cq = new ImageConsumerQueue(this, ic);\n cq.next = consumers;\n consumers = cq;\n } else {\n if (!cq.secure) {\n Object context = null;\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n context = security.getSecurityContext();\n }\n if (cq.securityContext == null) {\n cq.securityContext = context;\n } else if (!cq.securityContext.equals(context)) {\n // If there are two different security contexts that both\n // have a handle on the same ImageConsumer, then there has\n // been a security breach and whether or not they trade\n // image data is small fish compared to what they could be\n // trading. Throw a Security exception anyway...\n errorConsumer(cq, false);\n throw new SecurityException(\"Applets are trading image data!\");\n }\n }\n cq.interested = true;\n }\n if (produce && decoder == null) {\n startProduction();\n }\n }\n\n public synchronized boolean isConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n return true;\n }\n }\n return ImageConsumerQueue.isConsumer(consumers, ic);\n }\n\n private void errorAllConsumers(ImageConsumerQueue cq, boolean needReload) {\n while (cq != null) {\n if (cq.interested) {\n errorConsumer(cq, needReload);\n }\n cq = cq.next;\n }\n }\n\n private void errorConsumer(ImageConsumerQueue cq, boolean needReload) {\n cq.consumer.imageComplete(ImageConsumer.IMAGEERROR);\n if (needReload && cq.consumer instanceof ImageRepresentation) {\n ((ImageRepresentation) cq.consumer).image.flush();\n }\n removeConsumer(cq.consumer);\n }\n\n public synchronized void removeConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n id.removeConsumer(ic);\n }\n consumers = ImageConsumerQueue.removeConsumer(consumers, ic, false);\n }\n\n public void startProduction(ImageConsumer ic) {\n addConsumer(ic, true);\n }\n\n private synchronized void startProduction() {\n if (!awaitingFetch) {\n ImageFetcher.add(this);\n awaitingFetch = true;\n }\n }\n\n private synchronized void stopProduction() {\n if (awaitingFetch) {\n ImageFetcher.remove(this);\n awaitingFetch = false;\n }\n }\n\n public void requestTopDownLeftRightResend(ImageConsumer ic) {\n }\n\n protected abstract ImageDecoder getDecoder();\n\n protected ImageDecoder decoderForType(InputStream is, String content_type) {\n // Don't believe the content type - file extensions can\n return null;\n }\n\n protected ImageDecoder getDecoder(InputStream is) {\n if (!is.markSupported())\n is = new BufferedInputStream(is);\n try {\n /* changed to support png\n is.mark(6);\n */\n is.mark(8);\n int c1 = is.read();\n int c2 = is.read();\n int c3 = is.read();\n int c4 = is.read();\n int c5 = is.read();\n int c6 = is.read();\n // added to support png\n int c7 = is.read();\n int c8 = is.read();\n // end of adding\n is.reset();\n is.mark(-1);\n if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8') {\n return new GifImageDecoder(this, is);\n } else if (c1 == '\\377' && c2 == '\\330' && c3 == '\\377') {\n return new JPEGImageDecoder(this, is);\n } else if (c1 == '#' && c2 == 'd' && c3 == 'e' && c4 == 'f') {\n return new XbmImageDecoder(this, is);\n // added to support png\n } else if (c1 == 137 && c2 == 80 && c3 == 78 && c4 == 71 && c5 == 13 && c6 == 10 && c7 == 26 && c8 == 10) {\n return new PNGImageDecoder(this, is);\n }\n // end of adding\n } catch (IOException e) {\n }\n return null;\n }\n\n public void doFetch() {\n synchronized (this) {\n if (consumers == null) {\n awaitingFetch = false;\n return;\n }\n }\n ImageDecoder imgd = getDecoder();\n if (imgd == null) {\n badDecoder();\n } else {\n setDecoder(imgd);\n try {\n imgd.produceImage();\n } catch (IOException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } catch (ImageFormatException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } finally {\n removeDecoder(imgd);\n if (Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) {\n errorAllConsumers(imgd.queue, true);\n } else {\n errorAllConsumers(imgd.queue, false);\n }\n }\n }\n }\n\n private void badDecoder() {", "post_mask_code": "\n synchronized (this) {\n cq = consumers;\n consumers = null;\n awaitingFetch = false;\n }\n errorAllConsumers(cq, false);\n }\n\n private void setDecoder(ImageDecoder mydecoder) {\n ImageConsumerQueue cq;\n synchronized (this) {\n mydecoder.next = decoders;\n decoders = mydecoder;\n decoder = mydecoder;\n cq = consumers;\n mydecoder.queue = cq;\n consumers = null;\n awaitingFetch = false;\n }\n while (cq != null) {\n if (cq.interested) {\n // Now that there is a decoder, security may have changed\n // so reverify it here, just in case.\n if (!checkSecurity(cq.securityContext, true)) {\n errorConsumer(cq, false);\n }\n }\n cq = cq.next;\n }\n }\n\n private synchronized void removeDecoder(ImageDecoder mydecoder) {\n doneDecoding(mydecoder);\n ImageDecoder idprev = null;\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id == mydecoder) {\n if (idprev == null) {\n decoders = id.next;\n } else {\n idprev.next = id.next;\n }\n break;\n }\n idprev = id;\n }\n }\n\n synchronized void doneDecoding(ImageDecoder mydecoder) {\n if (decoder == mydecoder) {\n decoder = null;\n if (consumers != null) {\n startProduction();\n }\n }\n }\n\n void latchConsumers(ImageDecoder id) {\n doneDecoding(id);\n }\n\n synchronized void flush() {\n decoder = null;\n }\n}\n"} {"task_id": "Java_519", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/awt/image/InputStreamImageSource.java", "mask_start_position": 7553, "mask_end_position": 7677, "canonical_solution": "synchronized (this) {\n cq = consumers;\n consumers = null;\n awaitingFetch = false;\n }", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.awt.image;\n\nimport java.awt.image.*;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.BufferedInputStream;\nimport java.util.Hashtable;\n\npublic abstract class InputStreamImageSource implements ImageProducer, ImageFetchable {\n\n ImageConsumerQueue consumers;\n\n ImageDecoder decoder;\n\n ImageDecoder decoders;\n\n boolean awaitingFetch = false;\n\n abstract boolean checkSecurity(Object context, boolean quiet);\n\n int countConsumers(ImageConsumerQueue cq) {\n int i = 0;\n while (cq != null) {\n i++;\n cq = cq.next;\n }\n return i;\n }\n\n synchronized int countConsumers() {\n ImageDecoder id = decoders;\n int i = countConsumers(consumers);\n while (id != null) {\n i += countConsumers(id.queue);\n id = id.next;\n }\n return i;\n }\n\n public void addConsumer(ImageConsumer ic) {\n addConsumer(ic, false);\n }\n\n synchronized void printQueue(ImageConsumerQueue cq, String prefix) {\n while (cq != null) {\n System.out.println(prefix + cq);\n cq = cq.next;\n }\n }\n\n synchronized void printQueues(String title) {\n System.out.println(title + \"[ -----------\");\n printQueue(consumers, \" \");\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n System.out.println(\" \" + id);\n printQueue(id.queue, \" \");\n }\n System.out.println(\"----------- ]\" + title);\n }\n\n synchronized void addConsumer(ImageConsumer ic, boolean produce) {\n checkSecurity(null, false);\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n // This consumer is already being fed.\n return;\n }\n }\n ImageConsumerQueue cq = consumers;\n while (cq != null && cq.consumer != ic) {\n cq = cq.next;\n }\n if (cq == null) {\n cq = new ImageConsumerQueue(this, ic);\n cq.next = consumers;\n consumers = cq;\n } else {\n if (!cq.secure) {\n Object context = null;\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n context = security.getSecurityContext();\n }\n if (cq.securityContext == null) {\n cq.securityContext = context;\n } else if (!cq.securityContext.equals(context)) {\n // If there are two different security contexts that both\n // have a handle on the same ImageConsumer, then there has\n // been a security breach and whether or not they trade\n // image data is small fish compared to what they could be\n // trading. Throw a Security exception anyway...\n errorConsumer(cq, false);\n throw new SecurityException(\"Applets are trading image data!\");\n }\n }\n cq.interested = true;\n }\n if (produce && decoder == null) {\n startProduction();\n }\n }\n\n public synchronized boolean isConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n return true;\n }\n }\n return ImageConsumerQueue.isConsumer(consumers, ic);\n }\n\n private void errorAllConsumers(ImageConsumerQueue cq, boolean needReload) {\n while (cq != null) {\n if (cq.interested) {\n errorConsumer(cq, needReload);\n }\n cq = cq.next;\n }\n }\n\n private void errorConsumer(ImageConsumerQueue cq, boolean needReload) {\n cq.consumer.imageComplete(ImageConsumer.IMAGEERROR);\n if (needReload && cq.consumer instanceof ImageRepresentation) {\n ((ImageRepresentation) cq.consumer).image.flush();\n }\n removeConsumer(cq.consumer);\n }\n\n public synchronized void removeConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n id.removeConsumer(ic);\n }\n consumers = ImageConsumerQueue.removeConsumer(consumers, ic, false);\n }\n\n public void startProduction(ImageConsumer ic) {\n addConsumer(ic, true);\n }\n\n private synchronized void startProduction() {\n if (!awaitingFetch) {\n ImageFetcher.add(this);\n awaitingFetch = true;\n }\n }\n\n private synchronized void stopProduction() {\n if (awaitingFetch) {\n ImageFetcher.remove(this);\n awaitingFetch = false;\n }\n }\n\n public void requestTopDownLeftRightResend(ImageConsumer ic) {\n }\n\n protected abstract ImageDecoder getDecoder();\n\n protected ImageDecoder decoderForType(InputStream is, String content_type) {\n // Don't believe the content type - file extensions can\n return null;\n }\n\n protected ImageDecoder getDecoder(InputStream is) {\n if (!is.markSupported())\n is = new BufferedInputStream(is);\n try {\n /* changed to support png\n is.mark(6);\n */\n is.mark(8);\n int c1 = is.read();\n int c2 = is.read();\n int c3 = is.read();\n int c4 = is.read();\n int c5 = is.read();\n int c6 = is.read();\n // added to support png\n int c7 = is.read();\n int c8 = is.read();\n // end of adding\n is.reset();\n is.mark(-1);\n if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8') {\n return new GifImageDecoder(this, is);\n } else if (c1 == '\\377' && c2 == '\\330' && c3 == '\\377') {\n return new JPEGImageDecoder(this, is);\n } else if (c1 == '#' && c2 == 'd' && c3 == 'e' && c4 == 'f') {\n return new XbmImageDecoder(this, is);\n // added to support png\n } else if (c1 == 137 && c2 == 80 && c3 == 78 && c4 == 71 && c5 == 13 && c6 == 10 && c7 == 26 && c8 == 10) {\n return new PNGImageDecoder(this, is);\n }\n // end of adding\n } catch (IOException e) {\n }\n return null;\n }\n\n public void doFetch() {\n synchronized (this) {\n if (consumers == null) {\n awaitingFetch = false;\n return;\n }\n }\n ImageDecoder imgd = getDecoder();\n if (imgd == null) {\n badDecoder();\n } else {\n setDecoder(imgd);\n try {\n imgd.produceImage();\n } catch (IOException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } catch (ImageFormatException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } finally {\n removeDecoder(imgd);\n if (Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) {\n errorAllConsumers(imgd.queue, true);\n } else {\n errorAllConsumers(imgd.queue, false);\n }\n }\n }\n }\n\n private void badDecoder() {\n ImageConsumerQueue cq;\n ", "post_mask_code": "\n errorAllConsumers(cq, false);\n }\n\n private void setDecoder(ImageDecoder mydecoder) {\n ImageConsumerQueue cq;\n synchronized (this) {\n mydecoder.next = decoders;\n decoders = mydecoder;\n decoder = mydecoder;\n cq = consumers;\n mydecoder.queue = cq;\n consumers = null;\n awaitingFetch = false;\n }\n while (cq != null) {\n if (cq.interested) {\n // Now that there is a decoder, security may have changed\n // so reverify it here, just in case.\n if (!checkSecurity(cq.securityContext, true)) {\n errorConsumer(cq, false);\n }\n }\n cq = cq.next;\n }\n }\n\n private synchronized void removeDecoder(ImageDecoder mydecoder) {\n doneDecoding(mydecoder);\n ImageDecoder idprev = null;\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id == mydecoder) {\n if (idprev == null) {\n decoders = id.next;\n } else {\n idprev.next = id.next;\n }\n break;\n }\n idprev = id;\n }\n }\n\n synchronized void doneDecoding(ImageDecoder mydecoder) {\n if (decoder == mydecoder) {\n decoder = null;\n if (consumers != null) {\n startProduction();\n }\n }\n }\n\n void latchConsumers(ImageDecoder id) {\n doneDecoding(id);\n }\n\n synchronized void flush() {\n decoder = null;\n }\n}\n"} {"task_id": "Java_520", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/awt/image/InputStreamImageSource.java", "mask_start_position": 7686, "mask_end_position": 7721, "canonical_solution": "errorAllConsumers(cq, false);\n }", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.awt.image;\n\nimport java.awt.image.*;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.BufferedInputStream;\nimport java.util.Hashtable;\n\npublic abstract class InputStreamImageSource implements ImageProducer, ImageFetchable {\n\n ImageConsumerQueue consumers;\n\n ImageDecoder decoder;\n\n ImageDecoder decoders;\n\n boolean awaitingFetch = false;\n\n abstract boolean checkSecurity(Object context, boolean quiet);\n\n int countConsumers(ImageConsumerQueue cq) {\n int i = 0;\n while (cq != null) {\n i++;\n cq = cq.next;\n }\n return i;\n }\n\n synchronized int countConsumers() {\n ImageDecoder id = decoders;\n int i = countConsumers(consumers);\n while (id != null) {\n i += countConsumers(id.queue);\n id = id.next;\n }\n return i;\n }\n\n public void addConsumer(ImageConsumer ic) {\n addConsumer(ic, false);\n }\n\n synchronized void printQueue(ImageConsumerQueue cq, String prefix) {\n while (cq != null) {\n System.out.println(prefix + cq);\n cq = cq.next;\n }\n }\n\n synchronized void printQueues(String title) {\n System.out.println(title + \"[ -----------\");\n printQueue(consumers, \" \");\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n System.out.println(\" \" + id);\n printQueue(id.queue, \" \");\n }\n System.out.println(\"----------- ]\" + title);\n }\n\n synchronized void addConsumer(ImageConsumer ic, boolean produce) {\n checkSecurity(null, false);\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n // This consumer is already being fed.\n return;\n }\n }\n ImageConsumerQueue cq = consumers;\n while (cq != null && cq.consumer != ic) {\n cq = cq.next;\n }\n if (cq == null) {\n cq = new ImageConsumerQueue(this, ic);\n cq.next = consumers;\n consumers = cq;\n } else {\n if (!cq.secure) {\n Object context = null;\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n context = security.getSecurityContext();\n }\n if (cq.securityContext == null) {\n cq.securityContext = context;\n } else if (!cq.securityContext.equals(context)) {\n // If there are two different security contexts that both\n // have a handle on the same ImageConsumer, then there has\n // been a security breach and whether or not they trade\n // image data is small fish compared to what they could be\n // trading. Throw a Security exception anyway...\n errorConsumer(cq, false);\n throw new SecurityException(\"Applets are trading image data!\");\n }\n }\n cq.interested = true;\n }\n if (produce && decoder == null) {\n startProduction();\n }\n }\n\n public synchronized boolean isConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n return true;\n }\n }\n return ImageConsumerQueue.isConsumer(consumers, ic);\n }\n\n private void errorAllConsumers(ImageConsumerQueue cq, boolean needReload) {\n while (cq != null) {\n if (cq.interested) {\n errorConsumer(cq, needReload);\n }\n cq = cq.next;\n }\n }\n\n private void errorConsumer(ImageConsumerQueue cq, boolean needReload) {\n cq.consumer.imageComplete(ImageConsumer.IMAGEERROR);\n if (needReload && cq.consumer instanceof ImageRepresentation) {\n ((ImageRepresentation) cq.consumer).image.flush();\n }\n removeConsumer(cq.consumer);\n }\n\n public synchronized void removeConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n id.removeConsumer(ic);\n }\n consumers = ImageConsumerQueue.removeConsumer(consumers, ic, false);\n }\n\n public void startProduction(ImageConsumer ic) {\n addConsumer(ic, true);\n }\n\n private synchronized void startProduction() {\n if (!awaitingFetch) {\n ImageFetcher.add(this);\n awaitingFetch = true;\n }\n }\n\n private synchronized void stopProduction() {\n if (awaitingFetch) {\n ImageFetcher.remove(this);\n awaitingFetch = false;\n }\n }\n\n public void requestTopDownLeftRightResend(ImageConsumer ic) {\n }\n\n protected abstract ImageDecoder getDecoder();\n\n protected ImageDecoder decoderForType(InputStream is, String content_type) {\n // Don't believe the content type - file extensions can\n return null;\n }\n\n protected ImageDecoder getDecoder(InputStream is) {\n if (!is.markSupported())\n is = new BufferedInputStream(is);\n try {\n /* changed to support png\n is.mark(6);\n */\n is.mark(8);\n int c1 = is.read();\n int c2 = is.read();\n int c3 = is.read();\n int c4 = is.read();\n int c5 = is.read();\n int c6 = is.read();\n // added to support png\n int c7 = is.read();\n int c8 = is.read();\n // end of adding\n is.reset();\n is.mark(-1);\n if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8') {\n return new GifImageDecoder(this, is);\n } else if (c1 == '\\377' && c2 == '\\330' && c3 == '\\377') {\n return new JPEGImageDecoder(this, is);\n } else if (c1 == '#' && c2 == 'd' && c3 == 'e' && c4 == 'f') {\n return new XbmImageDecoder(this, is);\n // added to support png\n } else if (c1 == 137 && c2 == 80 && c3 == 78 && c4 == 71 && c5 == 13 && c6 == 10 && c7 == 26 && c8 == 10) {\n return new PNGImageDecoder(this, is);\n }\n // end of adding\n } catch (IOException e) {\n }\n return null;\n }\n\n public void doFetch() {\n synchronized (this) {\n if (consumers == null) {\n awaitingFetch = false;\n return;\n }\n }\n ImageDecoder imgd = getDecoder();\n if (imgd == null) {\n badDecoder();\n } else {\n setDecoder(imgd);\n try {\n imgd.produceImage();\n } catch (IOException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } catch (ImageFormatException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } finally {\n removeDecoder(imgd);\n if (Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) {\n errorAllConsumers(imgd.queue, true);\n } else {\n errorAllConsumers(imgd.queue, false);\n }\n }\n }\n }\n\n private void badDecoder() {\n ImageConsumerQueue cq;\n synchronized (this) {\n cq = consumers;\n consumers = null;\n awaitingFetch = false;\n }\n ", "post_mask_code": "\n\n private void setDecoder(ImageDecoder mydecoder) {\n ImageConsumerQueue cq;\n synchronized (this) {\n mydecoder.next = decoders;\n decoders = mydecoder;\n decoder = mydecoder;\n cq = consumers;\n mydecoder.queue = cq;\n consumers = null;\n awaitingFetch = false;\n }\n while (cq != null) {\n if (cq.interested) {\n // Now that there is a decoder, security may have changed\n // so reverify it here, just in case.\n if (!checkSecurity(cq.securityContext, true)) {\n errorConsumer(cq, false);\n }\n }\n cq = cq.next;\n }\n }\n\n private synchronized void removeDecoder(ImageDecoder mydecoder) {\n doneDecoding(mydecoder);\n ImageDecoder idprev = null;\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id == mydecoder) {\n if (idprev == null) {\n decoders = id.next;\n } else {\n idprev.next = id.next;\n }\n break;\n }\n idprev = id;\n }\n }\n\n synchronized void doneDecoding(ImageDecoder mydecoder) {\n if (decoder == mydecoder) {\n decoder = null;\n if (consumers != null) {\n startProduction();\n }\n }\n }\n\n void latchConsumers(ImageDecoder id) {\n doneDecoding(id);\n }\n\n synchronized void flush() {\n decoder = null;\n }\n}\n"} {"task_id": "Java_521", "language": "Java", "task_type": "single_line", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/awt/image/InputStreamImageSource.java", "mask_start_position": 6693, "mask_end_position": 6701, "canonical_solution": "coder();", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.awt.image;\n\nimport java.awt.image.*;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.BufferedInputStream;\nimport java.util.Hashtable;\n\npublic abstract class InputStreamImageSource implements ImageProducer, ImageFetchable {\n\n ImageConsumerQueue consumers;\n\n ImageDecoder decoder;\n\n ImageDecoder decoders;\n\n boolean awaitingFetch = false;\n\n abstract boolean checkSecurity(Object context, boolean quiet);\n\n int countConsumers(ImageConsumerQueue cq) {\n int i = 0;\n while (cq != null) {\n i++;\n cq = cq.next;\n }\n return i;\n }\n\n synchronized int countConsumers() {\n ImageDecoder id = decoders;\n int i = countConsumers(consumers);\n while (id != null) {\n i += countConsumers(id.queue);\n id = id.next;\n }\n return i;\n }\n\n public void addConsumer(ImageConsumer ic) {\n addConsumer(ic, false);\n }\n\n synchronized void printQueue(ImageConsumerQueue cq, String prefix) {\n while (cq != null) {\n System.out.println(prefix + cq);\n cq = cq.next;\n }\n }\n\n synchronized void printQueues(String title) {\n System.out.println(title + \"[ -----------\");\n printQueue(consumers, \" \");\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n System.out.println(\" \" + id);\n printQueue(id.queue, \" \");\n }\n System.out.println(\"----------- ]\" + title);\n }\n\n synchronized void addConsumer(ImageConsumer ic, boolean produce) {\n checkSecurity(null, false);\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n // This consumer is already being fed.\n return;\n }\n }\n ImageConsumerQueue cq = consumers;\n while (cq != null && cq.consumer != ic) {\n cq = cq.next;\n }\n if (cq == null) {\n cq = new ImageConsumerQueue(this, ic);\n cq.next = consumers;\n consumers = cq;\n } else {\n if (!cq.secure) {\n Object context = null;\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n context = security.getSecurityContext();\n }\n if (cq.securityContext == null) {\n cq.securityContext = context;\n } else if (!cq.securityContext.equals(context)) {\n // If there are two different security contexts that both\n // have a handle on the same ImageConsumer, then there has\n // been a security breach and whether or not they trade\n // image data is small fish compared to what they could be\n // trading. Throw a Security exception anyway...\n errorConsumer(cq, false);\n throw new SecurityException(\"Applets are trading image data!\");\n }\n }\n cq.interested = true;\n }\n if (produce && decoder == null) {\n startProduction();\n }\n }\n\n public synchronized boolean isConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n return true;\n }\n }\n return ImageConsumerQueue.isConsumer(consumers, ic);\n }\n\n private void errorAllConsumers(ImageConsumerQueue cq, boolean needReload) {\n while (cq != null) {\n if (cq.interested) {\n errorConsumer(cq, needReload);\n }\n cq = cq.next;\n }\n }\n\n private void errorConsumer(ImageConsumerQueue cq, boolean needReload) {\n cq.consumer.imageComplete(ImageConsumer.IMAGEERROR);\n if (needReload && cq.consumer instanceof ImageRepresentation) {\n ((ImageRepresentation) cq.consumer).image.flush();\n }\n removeConsumer(cq.consumer);\n }\n\n public synchronized void removeConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n id.removeConsumer(ic);\n }\n consumers = ImageConsumerQueue.removeConsumer(consumers, ic, false);\n }\n\n public void startProduction(ImageConsumer ic) {\n addConsumer(ic, true);\n }\n\n private synchronized void startProduction() {\n if (!awaitingFetch) {\n ImageFetcher.add(this);\n awaitingFetch = true;\n }\n }\n\n private synchronized void stopProduction() {\n if (awaitingFetch) {\n ImageFetcher.remove(this);\n awaitingFetch = false;\n }\n }\n\n public void requestTopDownLeftRightResend(ImageConsumer ic) {\n }\n\n protected abstract ImageDecoder getDecoder();\n\n protected ImageDecoder decoderForType(InputStream is, String content_type) {\n // Don't believe the content type - file extensions can\n return null;\n }\n\n protected ImageDecoder getDecoder(InputStream is) {\n if (!is.markSupported())\n is = new BufferedInputStream(is);\n try {\n /* changed to support png\n is.mark(6);\n */\n is.mark(8);\n int c1 = is.read();\n int c2 = is.read();\n int c3 = is.read();\n int c4 = is.read();\n int c5 = is.read();\n int c6 = is.read();\n // added to support png\n int c7 = is.read();\n int c8 = is.read();\n // end of adding\n is.reset();\n is.mark(-1);\n if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8') {\n return new GifImageDecoder(this, is);\n } else if (c1 == '\\377' && c2 == '\\330' && c3 == '\\377') {\n return new JPEGImageDecoder(this, is);\n } else if (c1 == '#' && c2 == 'd' && c3 == 'e' && c4 == 'f') {\n return new XbmImageDecoder(this, is);\n // added to support png\n } else if (c1 == 137 && c2 == 80 && c3 == 78 && c4 == 71 && c5 == 13 && c6 == 10 && c7 == 26 && c8 == 10) {\n return new PNGImageDecoder(this, is);\n }\n // end of adding\n } catch (IOException e) {\n }\n return null;\n }\n\n public void doFetch() {\n synchronized (this) {\n if (consumers == null) {\n awaitingFetch = false;\n return;\n }\n }\n ImageDecoder imgd = getDe", "post_mask_code": "\n if (imgd == null) {\n badDecoder();\n } else {\n setDecoder(imgd);\n try {\n imgd.produceImage();\n } catch (IOException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } catch (ImageFormatException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } finally {\n removeDecoder(imgd);\n if (Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) {\n errorAllConsumers(imgd.queue, true);\n } else {\n errorAllConsumers(imgd.queue, false);\n }\n }\n }\n }\n\n private void badDecoder() {\n ImageConsumerQueue cq;\n synchronized (this) {\n cq = consumers;\n consumers = null;\n awaitingFetch = false;\n }\n errorAllConsumers(cq, false);\n }\n\n private void setDecoder(ImageDecoder mydecoder) {\n ImageConsumerQueue cq;\n synchronized (this) {\n mydecoder.next = decoders;\n decoders = mydecoder;\n decoder = mydecoder;\n cq = consumers;\n mydecoder.queue = cq;\n consumers = null;\n awaitingFetch = false;\n }\n while (cq != null) {\n if (cq.interested) {\n // Now that there is a decoder, security may have changed\n // so reverify it here, just in case.\n if (!checkSecurity(cq.securityContext, true)) {\n errorConsumer(cq, false);\n }\n }\n cq = cq.next;\n }\n }\n\n private synchronized void removeDecoder(ImageDecoder mydecoder) {\n doneDecoding(mydecoder);\n ImageDecoder idprev = null;\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id == mydecoder) {\n if (idprev == null) {\n decoders = id.next;\n } else {\n idprev.next = id.next;\n }\n break;\n }\n idprev = id;\n }\n }\n\n synchronized void doneDecoding(ImageDecoder mydecoder) {\n if (decoder == mydecoder) {\n decoder = null;\n if (consumers != null) {\n startProduction();\n }\n }\n }\n\n void latchConsumers(ImageDecoder id) {\n doneDecoding(id);\n }\n\n synchronized void flush() {\n decoder = null;\n }\n}\n"} {"task_id": "Java_522", "language": "Java", "task_type": "if_statement", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/awt/image/InputStreamImageSource.java", "mask_start_position": 6208, "mask_end_position": 6376, "canonical_solution": "if (c1 == 137 && c2 == 80 && c3 == 78 && c4 == 71 && c5 == 13 && c6 == 10 && c7 == 26 && c8 == 10) {\n return new PNGImageDecoder(this, is);\n }", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.awt.image;\n\nimport java.awt.image.*;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.BufferedInputStream;\nimport java.util.Hashtable;\n\npublic abstract class InputStreamImageSource implements ImageProducer, ImageFetchable {\n\n ImageConsumerQueue consumers;\n\n ImageDecoder decoder;\n\n ImageDecoder decoders;\n\n boolean awaitingFetch = false;\n\n abstract boolean checkSecurity(Object context, boolean quiet);\n\n int countConsumers(ImageConsumerQueue cq) {\n int i = 0;\n while (cq != null) {\n i++;\n cq = cq.next;\n }\n return i;\n }\n\n synchronized int countConsumers() {\n ImageDecoder id = decoders;\n int i = countConsumers(consumers);\n while (id != null) {\n i += countConsumers(id.queue);\n id = id.next;\n }\n return i;\n }\n\n public void addConsumer(ImageConsumer ic) {\n addConsumer(ic, false);\n }\n\n synchronized void printQueue(ImageConsumerQueue cq, String prefix) {\n while (cq != null) {\n System.out.println(prefix + cq);\n cq = cq.next;\n }\n }\n\n synchronized void printQueues(String title) {\n System.out.println(title + \"[ -----------\");\n printQueue(consumers, \" \");\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n System.out.println(\" \" + id);\n printQueue(id.queue, \" \");\n }\n System.out.println(\"----------- ]\" + title);\n }\n\n synchronized void addConsumer(ImageConsumer ic, boolean produce) {\n checkSecurity(null, false);\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n // This consumer is already being fed.\n return;\n }\n }\n ImageConsumerQueue cq = consumers;\n while (cq != null && cq.consumer != ic) {\n cq = cq.next;\n }\n if (cq == null) {\n cq = new ImageConsumerQueue(this, ic);\n cq.next = consumers;\n consumers = cq;\n } else {\n if (!cq.secure) {\n Object context = null;\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n context = security.getSecurityContext();\n }\n if (cq.securityContext == null) {\n cq.securityContext = context;\n } else if (!cq.securityContext.equals(context)) {\n // If there are two different security contexts that both\n // have a handle on the same ImageConsumer, then there has\n // been a security breach and whether or not they trade\n // image data is small fish compared to what they could be\n // trading. Throw a Security exception anyway...\n errorConsumer(cq, false);\n throw new SecurityException(\"Applets are trading image data!\");\n }\n }\n cq.interested = true;\n }\n if (produce && decoder == null) {\n startProduction();\n }\n }\n\n public synchronized boolean isConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n return true;\n }\n }\n return ImageConsumerQueue.isConsumer(consumers, ic);\n }\n\n private void errorAllConsumers(ImageConsumerQueue cq, boolean needReload) {\n while (cq != null) {\n if (cq.interested) {\n errorConsumer(cq, needReload);\n }\n cq = cq.next;\n }\n }\n\n private void errorConsumer(ImageConsumerQueue cq, boolean needReload) {\n cq.consumer.imageComplete(ImageConsumer.IMAGEERROR);\n if (needReload && cq.consumer instanceof ImageRepresentation) {\n ((ImageRepresentation) cq.consumer).image.flush();\n }\n removeConsumer(cq.consumer);\n }\n\n public synchronized void removeConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n id.removeConsumer(ic);\n }\n consumers = ImageConsumerQueue.removeConsumer(consumers, ic, false);\n }\n\n public void startProduction(ImageConsumer ic) {\n addConsumer(ic, true);\n }\n\n private synchronized void startProduction() {\n if (!awaitingFetch) {\n ImageFetcher.add(this);\n awaitingFetch = true;\n }\n }\n\n private synchronized void stopProduction() {\n if (awaitingFetch) {\n ImageFetcher.remove(this);\n awaitingFetch = false;\n }\n }\n\n public void requestTopDownLeftRightResend(ImageConsumer ic) {\n }\n\n protected abstract ImageDecoder getDecoder();\n\n protected ImageDecoder decoderForType(InputStream is, String content_type) {\n // Don't believe the content type - file extensions can\n return null;\n }\n\n protected ImageDecoder getDecoder(InputStream is) {\n if (!is.markSupported())\n is = new BufferedInputStream(is);\n try {\n /* changed to support png\n is.mark(6);\n */\n is.mark(8);\n int c1 = is.read();\n int c2 = is.read();\n int c3 = is.read();\n int c4 = is.read();\n int c5 = is.read();\n int c6 = is.read();\n // added to support png\n int c7 = is.read();\n int c8 = is.read();\n // end of adding\n is.reset();\n is.mark(-1);\n if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8') {\n return new GifImageDecoder(this, is);\n } else if (c1 == '\\377' && c2 == '\\330' && c3 == '\\377') {\n return new JPEGImageDecoder(this, is);\n } else if (c1 == '#' && c2 == 'd' && c3 == 'e' && c4 == 'f') {\n return new XbmImageDecoder(this, is);\n // added to support png\n } else ", "post_mask_code": "\n // end of adding\n } catch (IOException e) {\n }\n return null;\n }\n\n public void doFetch() {\n synchronized (this) {\n if (consumers == null) {\n awaitingFetch = false;\n return;\n }\n }\n ImageDecoder imgd = getDecoder();\n if (imgd == null) {\n badDecoder();\n } else {\n setDecoder(imgd);\n try {\n imgd.produceImage();\n } catch (IOException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } catch (ImageFormatException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } finally {\n removeDecoder(imgd);\n if (Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) {\n errorAllConsumers(imgd.queue, true);\n } else {\n errorAllConsumers(imgd.queue, false);\n }\n }\n }\n }\n\n private void badDecoder() {\n ImageConsumerQueue cq;\n synchronized (this) {\n cq = consumers;\n consumers = null;\n awaitingFetch = false;\n }\n errorAllConsumers(cq, false);\n }\n\n private void setDecoder(ImageDecoder mydecoder) {\n ImageConsumerQueue cq;\n synchronized (this) {\n mydecoder.next = decoders;\n decoders = mydecoder;\n decoder = mydecoder;\n cq = consumers;\n mydecoder.queue = cq;\n consumers = null;\n awaitingFetch = false;\n }\n while (cq != null) {\n if (cq.interested) {\n // Now that there is a decoder, security may have changed\n // so reverify it here, just in case.\n if (!checkSecurity(cq.securityContext, true)) {\n errorConsumer(cq, false);\n }\n }\n cq = cq.next;\n }\n }\n\n private synchronized void removeDecoder(ImageDecoder mydecoder) {\n doneDecoding(mydecoder);\n ImageDecoder idprev = null;\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id == mydecoder) {\n if (idprev == null) {\n decoders = id.next;\n } else {\n idprev.next = id.next;\n }\n break;\n }\n idprev = id;\n }\n }\n\n synchronized void doneDecoding(ImageDecoder mydecoder) {\n if (decoder == mydecoder) {\n decoder = null;\n if (consumers != null) {\n startProduction();\n }\n }\n }\n\n void latchConsumers(ImageDecoder id) {\n doneDecoding(id);\n }\n\n synchronized void flush() {\n decoder = null;\n }\n}\n"} {"task_id": "Java_523", "language": "Java", "task_type": "for_statement", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/awt/image/InputStreamImageSource.java", "mask_start_position": 3374, "mask_end_position": 3524, "canonical_solution": "for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n return true;\n }\n }", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.awt.image;\n\nimport java.awt.image.*;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.BufferedInputStream;\nimport java.util.Hashtable;\n\npublic abstract class InputStreamImageSource implements ImageProducer, ImageFetchable {\n\n ImageConsumerQueue consumers;\n\n ImageDecoder decoder;\n\n ImageDecoder decoders;\n\n boolean awaitingFetch = false;\n\n abstract boolean checkSecurity(Object context, boolean quiet);\n\n int countConsumers(ImageConsumerQueue cq) {\n int i = 0;\n while (cq != null) {\n i++;\n cq = cq.next;\n }\n return i;\n }\n\n synchronized int countConsumers() {\n ImageDecoder id = decoders;\n int i = countConsumers(consumers);\n while (id != null) {\n i += countConsumers(id.queue);\n id = id.next;\n }\n return i;\n }\n\n public void addConsumer(ImageConsumer ic) {\n addConsumer(ic, false);\n }\n\n synchronized void printQueue(ImageConsumerQueue cq, String prefix) {\n while (cq != null) {\n System.out.println(prefix + cq);\n cq = cq.next;\n }\n }\n\n synchronized void printQueues(String title) {\n System.out.println(title + \"[ -----------\");\n printQueue(consumers, \" \");\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n System.out.println(\" \" + id);\n printQueue(id.queue, \" \");\n }\n System.out.println(\"----------- ]\" + title);\n }\n\n synchronized void addConsumer(ImageConsumer ic, boolean produce) {\n checkSecurity(null, false);\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n // This consumer is already being fed.\n return;\n }\n }\n ImageConsumerQueue cq = consumers;\n while (cq != null && cq.consumer != ic) {\n cq = cq.next;\n }\n if (cq == null) {\n cq = new ImageConsumerQueue(this, ic);\n cq.next = consumers;\n consumers = cq;\n } else {\n if (!cq.secure) {\n Object context = null;\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n context = security.getSecurityContext();\n }\n if (cq.securityContext == null) {\n cq.securityContext = context;\n } else if (!cq.securityContext.equals(context)) {\n // If there are two different security contexts that both\n // have a handle on the same ImageConsumer, then there has\n // been a security breach and whether or not they trade\n // image data is small fish compared to what they could be\n // trading. Throw a Security exception anyway...\n errorConsumer(cq, false);\n throw new SecurityException(\"Applets are trading image data!\");\n }\n }\n cq.interested = true;\n }\n if (produce && decoder == null) {\n startProduction();\n }\n }\n\n public synchronized boolean isConsumer(ImageConsumer ic) {\n ", "post_mask_code": "\n return ImageConsumerQueue.isConsumer(consumers, ic);\n }\n\n private void errorAllConsumers(ImageConsumerQueue cq, boolean needReload) {\n while (cq != null) {\n if (cq.interested) {\n errorConsumer(cq, needReload);\n }\n cq = cq.next;\n }\n }\n\n private void errorConsumer(ImageConsumerQueue cq, boolean needReload) {\n cq.consumer.imageComplete(ImageConsumer.IMAGEERROR);\n if (needReload && cq.consumer instanceof ImageRepresentation) {\n ((ImageRepresentation) cq.consumer).image.flush();\n }\n removeConsumer(cq.consumer);\n }\n\n public synchronized void removeConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n id.removeConsumer(ic);\n }\n consumers = ImageConsumerQueue.removeConsumer(consumers, ic, false);\n }\n\n public void startProduction(ImageConsumer ic) {\n addConsumer(ic, true);\n }\n\n private synchronized void startProduction() {\n if (!awaitingFetch) {\n ImageFetcher.add(this);\n awaitingFetch = true;\n }\n }\n\n private synchronized void stopProduction() {\n if (awaitingFetch) {\n ImageFetcher.remove(this);\n awaitingFetch = false;\n }\n }\n\n public void requestTopDownLeftRightResend(ImageConsumer ic) {\n }\n\n protected abstract ImageDecoder getDecoder();\n\n protected ImageDecoder decoderForType(InputStream is, String content_type) {\n // Don't believe the content type - file extensions can\n return null;\n }\n\n protected ImageDecoder getDecoder(InputStream is) {\n if (!is.markSupported())\n is = new BufferedInputStream(is);\n try {\n /* changed to support png\n is.mark(6);\n */\n is.mark(8);\n int c1 = is.read();\n int c2 = is.read();\n int c3 = is.read();\n int c4 = is.read();\n int c5 = is.read();\n int c6 = is.read();\n // added to support png\n int c7 = is.read();\n int c8 = is.read();\n // end of adding\n is.reset();\n is.mark(-1);\n if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8') {\n return new GifImageDecoder(this, is);\n } else if (c1 == '\\377' && c2 == '\\330' && c3 == '\\377') {\n return new JPEGImageDecoder(this, is);\n } else if (c1 == '#' && c2 == 'd' && c3 == 'e' && c4 == 'f') {\n return new XbmImageDecoder(this, is);\n // added to support png\n } else if (c1 == 137 && c2 == 80 && c3 == 78 && c4 == 71 && c5 == 13 && c6 == 10 && c7 == 26 && c8 == 10) {\n return new PNGImageDecoder(this, is);\n }\n // end of adding\n } catch (IOException e) {\n }\n return null;\n }\n\n public void doFetch() {\n synchronized (this) {\n if (consumers == null) {\n awaitingFetch = false;\n return;\n }\n }\n ImageDecoder imgd = getDecoder();\n if (imgd == null) {\n badDecoder();\n } else {\n setDecoder(imgd);\n try {\n imgd.produceImage();\n } catch (IOException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } catch (ImageFormatException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } finally {\n removeDecoder(imgd);\n if (Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) {\n errorAllConsumers(imgd.queue, true);\n } else {\n errorAllConsumers(imgd.queue, false);\n }\n }\n }\n }\n\n private void badDecoder() {\n ImageConsumerQueue cq;\n synchronized (this) {\n cq = consumers;\n consumers = null;\n awaitingFetch = false;\n }\n errorAllConsumers(cq, false);\n }\n\n private void setDecoder(ImageDecoder mydecoder) {\n ImageConsumerQueue cq;\n synchronized (this) {\n mydecoder.next = decoders;\n decoders = mydecoder;\n decoder = mydecoder;\n cq = consumers;\n mydecoder.queue = cq;\n consumers = null;\n awaitingFetch = false;\n }\n while (cq != null) {\n if (cq.interested) {\n // Now that there is a decoder, security may have changed\n // so reverify it here, just in case.\n if (!checkSecurity(cq.securityContext, true)) {\n errorConsumer(cq, false);\n }\n }\n cq = cq.next;\n }\n }\n\n private synchronized void removeDecoder(ImageDecoder mydecoder) {\n doneDecoding(mydecoder);\n ImageDecoder idprev = null;\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id == mydecoder) {\n if (idprev == null) {\n decoders = id.next;\n } else {\n idprev.next = id.next;\n }\n break;\n }\n idprev = id;\n }\n }\n\n synchronized void doneDecoding(ImageDecoder mydecoder) {\n if (decoder == mydecoder) {\n decoder = null;\n if (consumers != null) {\n startProduction();\n }\n }\n }\n\n void latchConsumers(ImageDecoder id) {\n doneDecoding(id);\n }\n\n synchronized void flush() {\n decoder = null;\n }\n}\n"} {"task_id": "Java_524", "language": "Java", "task_type": "while_statement", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/awt/image/InputStreamImageSource.java", "mask_start_position": 1966, "mask_end_position": 2043, "canonical_solution": "while (cq != null && cq.consumer != ic) {\n cq = cq.next;\n }", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.awt.image;\n\nimport java.awt.image.*;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.BufferedInputStream;\nimport java.util.Hashtable;\n\npublic abstract class InputStreamImageSource implements ImageProducer, ImageFetchable {\n\n ImageConsumerQueue consumers;\n\n ImageDecoder decoder;\n\n ImageDecoder decoders;\n\n boolean awaitingFetch = false;\n\n abstract boolean checkSecurity(Object context, boolean quiet);\n\n int countConsumers(ImageConsumerQueue cq) {\n int i = 0;\n while (cq != null) {\n i++;\n cq = cq.next;\n }\n return i;\n }\n\n synchronized int countConsumers() {\n ImageDecoder id = decoders;\n int i = countConsumers(consumers);\n while (id != null) {\n i += countConsumers(id.queue);\n id = id.next;\n }\n return i;\n }\n\n public void addConsumer(ImageConsumer ic) {\n addConsumer(ic, false);\n }\n\n synchronized void printQueue(ImageConsumerQueue cq, String prefix) {\n while (cq != null) {\n System.out.println(prefix + cq);\n cq = cq.next;\n }\n }\n\n synchronized void printQueues(String title) {\n System.out.println(title + \"[ -----------\");\n printQueue(consumers, \" \");\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n System.out.println(\" \" + id);\n printQueue(id.queue, \" \");\n }\n System.out.println(\"----------- ]\" + title);\n }\n\n synchronized void addConsumer(ImageConsumer ic, boolean produce) {\n checkSecurity(null, false);\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n // This consumer is already being fed.\n return;\n }\n }\n ImageConsumerQueue cq = consumers;\n ", "post_mask_code": "\n if (cq == null) {\n cq = new ImageConsumerQueue(this, ic);\n cq.next = consumers;\n consumers = cq;\n } else {\n if (!cq.secure) {\n Object context = null;\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n context = security.getSecurityContext();\n }\n if (cq.securityContext == null) {\n cq.securityContext = context;\n } else if (!cq.securityContext.equals(context)) {\n // If there are two different security contexts that both\n // have a handle on the same ImageConsumer, then there has\n // been a security breach and whether or not they trade\n // image data is small fish compared to what they could be\n // trading. Throw a Security exception anyway...\n errorConsumer(cq, false);\n throw new SecurityException(\"Applets are trading image data!\");\n }\n }\n cq.interested = true;\n }\n if (produce && decoder == null) {\n startProduction();\n }\n }\n\n public synchronized boolean isConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n return true;\n }\n }\n return ImageConsumerQueue.isConsumer(consumers, ic);\n }\n\n private void errorAllConsumers(ImageConsumerQueue cq, boolean needReload) {\n while (cq != null) {\n if (cq.interested) {\n errorConsumer(cq, needReload);\n }\n cq = cq.next;\n }\n }\n\n private void errorConsumer(ImageConsumerQueue cq, boolean needReload) {\n cq.consumer.imageComplete(ImageConsumer.IMAGEERROR);\n if (needReload && cq.consumer instanceof ImageRepresentation) {\n ((ImageRepresentation) cq.consumer).image.flush();\n }\n removeConsumer(cq.consumer);\n }\n\n public synchronized void removeConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n id.removeConsumer(ic);\n }\n consumers = ImageConsumerQueue.removeConsumer(consumers, ic, false);\n }\n\n public void startProduction(ImageConsumer ic) {\n addConsumer(ic, true);\n }\n\n private synchronized void startProduction() {\n if (!awaitingFetch) {\n ImageFetcher.add(this);\n awaitingFetch = true;\n }\n }\n\n private synchronized void stopProduction() {\n if (awaitingFetch) {\n ImageFetcher.remove(this);\n awaitingFetch = false;\n }\n }\n\n public void requestTopDownLeftRightResend(ImageConsumer ic) {\n }\n\n protected abstract ImageDecoder getDecoder();\n\n protected ImageDecoder decoderForType(InputStream is, String content_type) {\n // Don't believe the content type - file extensions can\n return null;\n }\n\n protected ImageDecoder getDecoder(InputStream is) {\n if (!is.markSupported())\n is = new BufferedInputStream(is);\n try {\n /* changed to support png\n is.mark(6);\n */\n is.mark(8);\n int c1 = is.read();\n int c2 = is.read();\n int c3 = is.read();\n int c4 = is.read();\n int c5 = is.read();\n int c6 = is.read();\n // added to support png\n int c7 = is.read();\n int c8 = is.read();\n // end of adding\n is.reset();\n is.mark(-1);\n if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8') {\n return new GifImageDecoder(this, is);\n } else if (c1 == '\\377' && c2 == '\\330' && c3 == '\\377') {\n return new JPEGImageDecoder(this, is);\n } else if (c1 == '#' && c2 == 'd' && c3 == 'e' && c4 == 'f') {\n return new XbmImageDecoder(this, is);\n // added to support png\n } else if (c1 == 137 && c2 == 80 && c3 == 78 && c4 == 71 && c5 == 13 && c6 == 10 && c7 == 26 && c8 == 10) {\n return new PNGImageDecoder(this, is);\n }\n // end of adding\n } catch (IOException e) {\n }\n return null;\n }\n\n public void doFetch() {\n synchronized (this) {\n if (consumers == null) {\n awaitingFetch = false;\n return;\n }\n }\n ImageDecoder imgd = getDecoder();\n if (imgd == null) {\n badDecoder();\n } else {\n setDecoder(imgd);\n try {\n imgd.produceImage();\n } catch (IOException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } catch (ImageFormatException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } finally {\n removeDecoder(imgd);\n if (Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) {\n errorAllConsumers(imgd.queue, true);\n } else {\n errorAllConsumers(imgd.queue, false);\n }\n }\n }\n }\n\n private void badDecoder() {\n ImageConsumerQueue cq;\n synchronized (this) {\n cq = consumers;\n consumers = null;\n awaitingFetch = false;\n }\n errorAllConsumers(cq, false);\n }\n\n private void setDecoder(ImageDecoder mydecoder) {\n ImageConsumerQueue cq;\n synchronized (this) {\n mydecoder.next = decoders;\n decoders = mydecoder;\n decoder = mydecoder;\n cq = consumers;\n mydecoder.queue = cq;\n consumers = null;\n awaitingFetch = false;\n }\n while (cq != null) {\n if (cq.interested) {\n // Now that there is a decoder, security may have changed\n // so reverify it here, just in case.\n if (!checkSecurity(cq.securityContext, true)) {\n errorConsumer(cq, false);\n }\n }\n cq = cq.next;\n }\n }\n\n private synchronized void removeDecoder(ImageDecoder mydecoder) {\n doneDecoding(mydecoder);\n ImageDecoder idprev = null;\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id == mydecoder) {\n if (idprev == null) {\n decoders = id.next;\n } else {\n idprev.next = id.next;\n }\n break;\n }\n idprev = id;\n }\n }\n\n synchronized void doneDecoding(ImageDecoder mydecoder) {\n if (decoder == mydecoder) {\n decoder = null;\n if (consumers != null) {\n startProduction();\n }\n }\n }\n\n void latchConsumers(ImageDecoder id) {\n doneDecoding(id);\n }\n\n synchronized void flush() {\n decoder = null;\n }\n}\n"} {"task_id": "Java_525", "language": "Java", "task_type": "empty", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/awt/image/InputStreamImageSource.java", "mask_start_position": 1562, "mask_end_position": 1562, "canonical_solution": "", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.awt.image;\n\nimport java.awt.image.*;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.BufferedInputStream;\nimport java.util.Hashtable;\n\npublic abstract class InputStreamImageSource implements ImageProducer, ImageFetchable {\n\n ImageConsumerQueue consumers;\n\n ImageDecoder decoder;\n\n ImageDecoder decoders;\n\n boolean awaitingFetch = false;\n\n abstract boolean checkSecurity(Object context, boolean quiet);\n\n int countConsumers(ImageConsumerQueue cq) {\n int i = 0;\n while (cq != null) {\n i++;\n cq = cq.next;\n }\n return i;\n }\n\n synchronized int countConsumers() {\n ImageDecoder id = decoders;\n int i = countConsumers(consumers);\n while (id != null) {\n i += countConsumers(id.queue);\n id = id.next;\n }\n return i;\n }\n\n public void addConsumer(ImageConsumer ic) {\n addConsumer(ic, false);\n }\n\n synchronized void printQueue(ImageConsumerQueue cq, String prefix) {\n while (cq != null) {\n System.out.println(prefix + cq);\n cq = cq.next;\n }\n }\n\n synchronized void printQueues(String title) {\n System.out.println(title + \"[ -----------\");\n printQueue(consumers, \" \");\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n System.out.println(\" \" + id);\n printQueue(id.queue, \" \");\n }\n System.out.prin", "post_mask_code": "tln(\"----------- ]\" + title);\n }\n\n synchronized void addConsumer(ImageConsumer ic, boolean produce) {\n checkSecurity(null, false);\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n // This consumer is already being fed.\n return;\n }\n }\n ImageConsumerQueue cq = consumers;\n while (cq != null && cq.consumer != ic) {\n cq = cq.next;\n }\n if (cq == null) {\n cq = new ImageConsumerQueue(this, ic);\n cq.next = consumers;\n consumers = cq;\n } else {\n if (!cq.secure) {\n Object context = null;\n SecurityManager security = System.getSecurityManager();\n if (security != null) {\n context = security.getSecurityContext();\n }\n if (cq.securityContext == null) {\n cq.securityContext = context;\n } else if (!cq.securityContext.equals(context)) {\n // If there are two different security contexts that both\n // have a handle on the same ImageConsumer, then there has\n // been a security breach and whether or not they trade\n // image data is small fish compared to what they could be\n // trading. Throw a Security exception anyway...\n errorConsumer(cq, false);\n throw new SecurityException(\"Applets are trading image data!\");\n }\n }\n cq.interested = true;\n }\n if (produce && decoder == null) {\n startProduction();\n }\n }\n\n public synchronized boolean isConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id.isConsumer(ic)) {\n return true;\n }\n }\n return ImageConsumerQueue.isConsumer(consumers, ic);\n }\n\n private void errorAllConsumers(ImageConsumerQueue cq, boolean needReload) {\n while (cq != null) {\n if (cq.interested) {\n errorConsumer(cq, needReload);\n }\n cq = cq.next;\n }\n }\n\n private void errorConsumer(ImageConsumerQueue cq, boolean needReload) {\n cq.consumer.imageComplete(ImageConsumer.IMAGEERROR);\n if (needReload && cq.consumer instanceof ImageRepresentation) {\n ((ImageRepresentation) cq.consumer).image.flush();\n }\n removeConsumer(cq.consumer);\n }\n\n public synchronized void removeConsumer(ImageConsumer ic) {\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n id.removeConsumer(ic);\n }\n consumers = ImageConsumerQueue.removeConsumer(consumers, ic, false);\n }\n\n public void startProduction(ImageConsumer ic) {\n addConsumer(ic, true);\n }\n\n private synchronized void startProduction() {\n if (!awaitingFetch) {\n ImageFetcher.add(this);\n awaitingFetch = true;\n }\n }\n\n private synchronized void stopProduction() {\n if (awaitingFetch) {\n ImageFetcher.remove(this);\n awaitingFetch = false;\n }\n }\n\n public void requestTopDownLeftRightResend(ImageConsumer ic) {\n }\n\n protected abstract ImageDecoder getDecoder();\n\n protected ImageDecoder decoderForType(InputStream is, String content_type) {\n // Don't believe the content type - file extensions can\n return null;\n }\n\n protected ImageDecoder getDecoder(InputStream is) {\n if (!is.markSupported())\n is = new BufferedInputStream(is);\n try {\n /* changed to support png\n is.mark(6);\n */\n is.mark(8);\n int c1 = is.read();\n int c2 = is.read();\n int c3 = is.read();\n int c4 = is.read();\n int c5 = is.read();\n int c6 = is.read();\n // added to support png\n int c7 = is.read();\n int c8 = is.read();\n // end of adding\n is.reset();\n is.mark(-1);\n if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8') {\n return new GifImageDecoder(this, is);\n } else if (c1 == '\\377' && c2 == '\\330' && c3 == '\\377') {\n return new JPEGImageDecoder(this, is);\n } else if (c1 == '#' && c2 == 'd' && c3 == 'e' && c4 == 'f') {\n return new XbmImageDecoder(this, is);\n // added to support png\n } else if (c1 == 137 && c2 == 80 && c3 == 78 && c4 == 71 && c5 == 13 && c6 == 10 && c7 == 26 && c8 == 10) {\n return new PNGImageDecoder(this, is);\n }\n // end of adding\n } catch (IOException e) {\n }\n return null;\n }\n\n public void doFetch() {\n synchronized (this) {\n if (consumers == null) {\n awaitingFetch = false;\n return;\n }\n }\n ImageDecoder imgd = getDecoder();\n if (imgd == null) {\n badDecoder();\n } else {\n setDecoder(imgd);\n try {\n imgd.produceImage();\n } catch (IOException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } catch (ImageFormatException e) {\n e.printStackTrace();\n // the finally clause will send an error.\n } finally {\n removeDecoder(imgd);\n if (Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) {\n errorAllConsumers(imgd.queue, true);\n } else {\n errorAllConsumers(imgd.queue, false);\n }\n }\n }\n }\n\n private void badDecoder() {\n ImageConsumerQueue cq;\n synchronized (this) {\n cq = consumers;\n consumers = null;\n awaitingFetch = false;\n }\n errorAllConsumers(cq, false);\n }\n\n private void setDecoder(ImageDecoder mydecoder) {\n ImageConsumerQueue cq;\n synchronized (this) {\n mydecoder.next = decoders;\n decoders = mydecoder;\n decoder = mydecoder;\n cq = consumers;\n mydecoder.queue = cq;\n consumers = null;\n awaitingFetch = false;\n }\n while (cq != null) {\n if (cq.interested) {\n // Now that there is a decoder, security may have changed\n // so reverify it here, just in case.\n if (!checkSecurity(cq.securityContext, true)) {\n errorConsumer(cq, false);\n }\n }\n cq = cq.next;\n }\n }\n\n private synchronized void removeDecoder(ImageDecoder mydecoder) {\n doneDecoding(mydecoder);\n ImageDecoder idprev = null;\n for (ImageDecoder id = decoders; id != null; id = id.next) {\n if (id == mydecoder) {\n if (idprev == null) {\n decoders = id.next;\n } else {\n idprev.next = id.next;\n }\n break;\n }\n idprev = id;\n }\n }\n\n synchronized void doneDecoding(ImageDecoder mydecoder) {\n if (decoder == mydecoder) {\n decoder = null;\n if (consumers != null) {\n startProduction();\n }\n }\n }\n\n void latchConsumers(ImageDecoder id) {\n doneDecoding(id);\n }\n\n synchronized void flush() {\n decoder = null;\n }\n}\n"} {"task_id": "Java_526", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SpoonLabs/astor/examples/math_57/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java", "mask_start_position": 2039, "mask_end_position": 2099, "canonical_solution": "public double chiSquare(double[] expected, long[] observed) ", "pre_mask_code": "package org.apache.commons.math.stat.inference;\n\nimport org.apache.commons.math.MathException;\nimport org.apache.commons.math.exception.NotPositiveException;\nimport org.apache.commons.math.exception.NotStrictlyPositiveException;\nimport org.apache.commons.math.exception.NumberIsTooSmallException;\nimport org.apache.commons.math.exception.OutOfRangeException;\nimport org.apache.commons.math.exception.DimensionMismatchException;\nimport org.apache.commons.math.exception.MathIllegalArgumentException;\nimport org.apache.commons.math.distribution.ChiSquaredDistribution;\nimport org.apache.commons.math.distribution.ChiSquaredDistributionImpl;\nimport org.apache.commons.math.exception.util.LocalizedFormats;\nimport org.apache.commons.math.util.FastMath;\n\n/**\n * Implements Chi-Square test statistics defined in the\n * {@link UnknownDistributionChiSquareTest} interface.\n *\n * @version $Revision$ $Date$\n */\npublic class ChiSquareTestImpl implements UnknownDistributionChiSquareTest {\n\n /**\n * Distribution used to compute inference statistics.\n */\n private ChiSquaredDistribution distribution;\n\n /**\n * Construct a ChiSquareTestImpl\n */\n public ChiSquareTestImpl() {\n this(new ChiSquaredDistributionImpl(1.0));\n }\n\n /**\n * Create a test instance using the given distribution for computing\n * inference statistics.\n * @param x distribution used to compute inference statistics.\n * @since 1.2\n */\n public ChiSquareTestImpl(ChiSquaredDistribution x) {\n super();\n setDistribution(x);\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return chi-square test statistic\n * @throws DimensionMismatchException if the arrays length is less than 2.\n */\n ", "post_mask_code": "{\n if (expected.length < 2) {\n throw new DimensionMismatchException(expected.length, 2);\n }\n if (expected.length != observed.length) {\n throw new DimensionMismatchException(expected.length, observed.length);\n }\n checkPositive(expected);\n checkNonNegative(observed);\n double sumExpected = 0d;\n double sumObserved = 0d;\n for (int i = 0; i < observed.length; i++) {\n sumExpected += expected[i];\n sumObserved += observed[i];\n }\n double ratio = 1.0d;\n boolean rescale = false;\n if (FastMath.abs(sumExpected - sumObserved) > 10E-6) {\n ratio = sumObserved / sumExpected;\n rescale = true;\n }\n double sumSq = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n if (rescale) {\n final double dev = observed[i] - ratio * expected[i];\n sumSq += dev * dev / (ratio * expected[i]);\n } else {\n final double dev = observed[i] - expected[i];\n sumSq += dev * dev / expected[i];\n }\n }\n return sumSq;\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(double[] expected, long[] observed) throws MathException {\n distribution = new ChiSquaredDistributionImpl(expected.length - 1.0);\n return 1.0 - distribution.cumulativeProbability(chiSquare(expected, observed));\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(double[] expected, long[] observed, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(expected, observed) < alpha;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met.\n */\n public double chiSquare(long[][] counts) {\n checkArray(counts);\n int nRows = counts.length;\n int nCols = counts[0].length;\n // compute row, column and total sums\n double[] rowSum = new double[nRows];\n double[] colSum = new double[nCols];\n double total = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n rowSum[row] += counts[row][col];\n colSum[col] += counts[row][col];\n total += counts[row][col];\n }\n }\n // compute expected counts and chi-square\n double sumSq = 0.0d;\n double expected = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n expected = (rowSum[row] * colSum[col]) / total;\n sumSq += ((counts[row][col] - expected) * (counts[row][col] - expected)) / expected;\n }\n }\n return sumSq;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(long[][] counts) throws MathException {\n checkArray(counts);\n double df = ((double) counts.length - 1) * ((double) counts[0].length - 1);\n distribution = new ChiSquaredDistributionImpl(df);\n return 1 - distribution.cumulativeProbability(chiSquare(counts));\n }\n\n /**\n * @param counts array representation of 2-way table\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(long[][] counts, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(counts) < alpha;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met\n * @since 1.2\n */\n public double chiSquareDataSetsComparison(long[] observed1, long[] observed2) {\n // Make sure lengths are same\n if (observed1.length < 2) {\n throw new DimensionMismatchException(observed1.length, 2);\n }\n if (observed1.length != observed2.length) {\n throw new DimensionMismatchException(observed1.length, observed2.length);\n }\n // Ensure non-negative counts\n checkNonNegative(observed1);\n checkNonNegative(observed2);\n // Compute and compare count sums\n long countSum1 = 0;\n long countSum2 = 0;\n boolean unequalCounts = false;\n double weight = 0.0;\n for (int i = 0; i < observed1.length; i++) {\n countSum1 += observed1[i];\n countSum2 += observed2[i];\n }\n // Ensure neither sample is uniformly 0\n if (countSum1 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 1);\n }\n if (countSum2 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 2);\n }\n // Compare and compute weight only if different\n unequalCounts = countSum1 != countSum2;\n if (unequalCounts) {\n weight = FastMath.sqrt((double) countSum1 / (double) countSum2);\n }\n // Compute ChiSquare statistic\n double sumSq = 0.0d;\n double dev = 0.0d;\n double obs1 = 0.0d;\n double obs2 = 0.0d;\n for (int i = 0; i < observed1.length; i++) {\n if (observed1[i] == 0 && observed2[i] == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY, i);\n } else {\n obs1 = observed1[i];\n obs2 = observed2[i];\n if (unequalCounts) {\n // apply weights\n dev = obs1 / weight - obs2 * weight;\n } else {\n dev = obs1 - obs2;\n }\n sumSq += (dev * dev) / (obs1 + obs2);\n }\n }\n return sumSq;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n * @since 1.2\n */\n public double chiSquareTestDataSetsComparison(long[] observed1, long[] observed2) throws MathException {\n distribution = new ChiSquaredDistributionImpl((double) observed1.length - 1);\n return 1 - distribution.cumulativeProbability(chiSquareDataSetsComparison(observed1, observed2));\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n * @since 1.2\n */\n public boolean chiSquareTestDataSetsComparison(long[] observed1, long[] observed2, double alpha) throws MathException {\n if (alpha <= 0 || alpha > 0.5) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTestDataSetsComparison(observed1, observed2) < alpha;\n }\n\n /**\n * Checks to make sure that the input long[][] array is rectangular,\n * has at least 2 rows and 2 columns, and has all non-negative entries,\n * throwing MathIllegalArgumentException if any of these checks fail.\n *\n * @param in input 2-way table to check\n * @throws MathIllegalArgumentException if the array is not valid\n */\n private void checkArray(long[][] in) {\n if (in.length < 2) {\n throw new NumberIsTooSmallException(in.length, 2, true);\n }\n if (in[0].length < 2) {\n throw new NumberIsTooSmallException(in[0].length, 2, true);\n }\n checkRectangular(in);\n checkNonNegative(in);\n }\n\n // --------------------- Private array methods -- should find a utility home for these\n /**\n * Throws MathIllegalArgumentException if the input array is not rectangular.\n *\n * @param in array to be tested\n * @throws NullPointerException if input array is null\n * @throws MathIllegalArgumentException if input array is not rectangular\n */\n private void checkRectangular(long[][] in) {\n for (int i = 1; i < in.length; i++) {\n if (in[i].length != in[0].length) {\n throw new DimensionMismatchException(LocalizedFormats.DIFFERENT_ROWS_LENGTHS, in[i].length, in[0].length);\n }\n }\n }\n\n /**\n * Check all entries of the input array are strictly postive.\n *\n * @param in Array to be tested.\n * @exception NotStrictlyPositiveException if one entry is not positive.\n */\n private void checkPositive(double[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] <= 0) {\n throw new NotStrictlyPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] < 0) {\n throw new NotPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[][] in) {\n for (int i = 0; i < in.length; i++) {\n for (int j = 0; j < in[i].length; j++) {\n if (in[i][j] < 0) {\n throw new NotPositiveException(in[i][j]);\n }\n }\n }\n }\n\n /**\n * Modify the distribution used to compute inference statistics.\n *\n * @param value\n * the new distribution\n * @since 1.2\n */\n public void setDistribution(ChiSquaredDistribution value) {\n distribution = value;\n }\n}\n"} {"task_id": "Java_527", "language": "Java", "task_type": "method_body", "source_file": "java/github/SpoonLabs/astor/examples/math_57/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java", "mask_start_position": 10363, "mask_end_position": 10562, "canonical_solution": "{\n distribution = new ChiSquaredDistributionImpl((double) observed1.length - 1);\n return 1 - distribution.cumulativeProbability(chiSquareDataSetsComparison(observed1, observed2));\n }", "pre_mask_code": "package org.apache.commons.math.stat.inference;\n\nimport org.apache.commons.math.MathException;\nimport org.apache.commons.math.exception.NotPositiveException;\nimport org.apache.commons.math.exception.NotStrictlyPositiveException;\nimport org.apache.commons.math.exception.NumberIsTooSmallException;\nimport org.apache.commons.math.exception.OutOfRangeException;\nimport org.apache.commons.math.exception.DimensionMismatchException;\nimport org.apache.commons.math.exception.MathIllegalArgumentException;\nimport org.apache.commons.math.distribution.ChiSquaredDistribution;\nimport org.apache.commons.math.distribution.ChiSquaredDistributionImpl;\nimport org.apache.commons.math.exception.util.LocalizedFormats;\nimport org.apache.commons.math.util.FastMath;\n\n/**\n * Implements Chi-Square test statistics defined in the\n * {@link UnknownDistributionChiSquareTest} interface.\n *\n * @version $Revision$ $Date$\n */\npublic class ChiSquareTestImpl implements UnknownDistributionChiSquareTest {\n\n /**\n * Distribution used to compute inference statistics.\n */\n private ChiSquaredDistribution distribution;\n\n /**\n * Construct a ChiSquareTestImpl\n */\n public ChiSquareTestImpl() {\n this(new ChiSquaredDistributionImpl(1.0));\n }\n\n /**\n * Create a test instance using the given distribution for computing\n * inference statistics.\n * @param x distribution used to compute inference statistics.\n * @since 1.2\n */\n public ChiSquareTestImpl(ChiSquaredDistribution x) {\n super();\n setDistribution(x);\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return chi-square test statistic\n * @throws DimensionMismatchException if the arrays length is less than 2.\n */\n public double chiSquare(double[] expected, long[] observed) {\n if (expected.length < 2) {\n throw new DimensionMismatchException(expected.length, 2);\n }\n if (expected.length != observed.length) {\n throw new DimensionMismatchException(expected.length, observed.length);\n }\n checkPositive(expected);\n checkNonNegative(observed);\n double sumExpected = 0d;\n double sumObserved = 0d;\n for (int i = 0; i < observed.length; i++) {\n sumExpected += expected[i];\n sumObserved += observed[i];\n }\n double ratio = 1.0d;\n boolean rescale = false;\n if (FastMath.abs(sumExpected - sumObserved) > 10E-6) {\n ratio = sumObserved / sumExpected;\n rescale = true;\n }\n double sumSq = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n if (rescale) {\n final double dev = observed[i] - ratio * expected[i];\n sumSq += dev * dev / (ratio * expected[i]);\n } else {\n final double dev = observed[i] - expected[i];\n sumSq += dev * dev / expected[i];\n }\n }\n return sumSq;\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(double[] expected, long[] observed) throws MathException {\n distribution = new ChiSquaredDistributionImpl(expected.length - 1.0);\n return 1.0 - distribution.cumulativeProbability(chiSquare(expected, observed));\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(double[] expected, long[] observed, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(expected, observed) < alpha;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met.\n */\n public double chiSquare(long[][] counts) {\n checkArray(counts);\n int nRows = counts.length;\n int nCols = counts[0].length;\n // compute row, column and total sums\n double[] rowSum = new double[nRows];\n double[] colSum = new double[nCols];\n double total = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n rowSum[row] += counts[row][col];\n colSum[col] += counts[row][col];\n total += counts[row][col];\n }\n }\n // compute expected counts and chi-square\n double sumSq = 0.0d;\n double expected = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n expected = (rowSum[row] * colSum[col]) / total;\n sumSq += ((counts[row][col] - expected) * (counts[row][col] - expected)) / expected;\n }\n }\n return sumSq;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(long[][] counts) throws MathException {\n checkArray(counts);\n double df = ((double) counts.length - 1) * ((double) counts[0].length - 1);\n distribution = new ChiSquaredDistributionImpl(df);\n return 1 - distribution.cumulativeProbability(chiSquare(counts));\n }\n\n /**\n * @param counts array representation of 2-way table\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(long[][] counts, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(counts) < alpha;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met\n * @since 1.2\n */\n public double chiSquareDataSetsComparison(long[] observed1, long[] observed2) {\n // Make sure lengths are same\n if (observed1.length < 2) {\n throw new DimensionMismatchException(observed1.length, 2);\n }\n if (observed1.length != observed2.length) {\n throw new DimensionMismatchException(observed1.length, observed2.length);\n }\n // Ensure non-negative counts\n checkNonNegative(observed1);\n checkNonNegative(observed2);\n // Compute and compare count sums\n long countSum1 = 0;\n long countSum2 = 0;\n boolean unequalCounts = false;\n double weight = 0.0;\n for (int i = 0; i < observed1.length; i++) {\n countSum1 += observed1[i];\n countSum2 += observed2[i];\n }\n // Ensure neither sample is uniformly 0\n if (countSum1 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 1);\n }\n if (countSum2 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 2);\n }\n // Compare and compute weight only if different\n unequalCounts = countSum1 != countSum2;\n if (unequalCounts) {\n weight = FastMath.sqrt((double) countSum1 / (double) countSum2);\n }\n // Compute ChiSquare statistic\n double sumSq = 0.0d;\n double dev = 0.0d;\n double obs1 = 0.0d;\n double obs2 = 0.0d;\n for (int i = 0; i < observed1.length; i++) {\n if (observed1[i] == 0 && observed2[i] == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY, i);\n } else {\n obs1 = observed1[i];\n obs2 = observed2[i];\n if (unequalCounts) {\n // apply weights\n dev = obs1 / weight - obs2 * weight;\n } else {\n dev = obs1 - obs2;\n }\n sumSq += (dev * dev) / (obs1 + obs2);\n }\n }\n return sumSq;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n * @since 1.2\n */\n public double chiSquareTestDataSetsComparison(long[] observed1, long[] observed2) throws MathException ", "post_mask_code": "\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n * @since 1.2\n */\n public boolean chiSquareTestDataSetsComparison(long[] observed1, long[] observed2, double alpha) throws MathException {\n if (alpha <= 0 || alpha > 0.5) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTestDataSetsComparison(observed1, observed2) < alpha;\n }\n\n /**\n * Checks to make sure that the input long[][] array is rectangular,\n * has at least 2 rows and 2 columns, and has all non-negative entries,\n * throwing MathIllegalArgumentException if any of these checks fail.\n *\n * @param in input 2-way table to check\n * @throws MathIllegalArgumentException if the array is not valid\n */\n private void checkArray(long[][] in) {\n if (in.length < 2) {\n throw new NumberIsTooSmallException(in.length, 2, true);\n }\n if (in[0].length < 2) {\n throw new NumberIsTooSmallException(in[0].length, 2, true);\n }\n checkRectangular(in);\n checkNonNegative(in);\n }\n\n // --------------------- Private array methods -- should find a utility home for these\n /**\n * Throws MathIllegalArgumentException if the input array is not rectangular.\n *\n * @param in array to be tested\n * @throws NullPointerException if input array is null\n * @throws MathIllegalArgumentException if input array is not rectangular\n */\n private void checkRectangular(long[][] in) {\n for (int i = 1; i < in.length; i++) {\n if (in[i].length != in[0].length) {\n throw new DimensionMismatchException(LocalizedFormats.DIFFERENT_ROWS_LENGTHS, in[i].length, in[0].length);\n }\n }\n }\n\n /**\n * Check all entries of the input array are strictly postive.\n *\n * @param in Array to be tested.\n * @exception NotStrictlyPositiveException if one entry is not positive.\n */\n private void checkPositive(double[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] <= 0) {\n throw new NotStrictlyPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] < 0) {\n throw new NotPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[][] in) {\n for (int i = 0; i < in.length; i++) {\n for (int j = 0; j < in[i].length; j++) {\n if (in[i][j] < 0) {\n throw new NotPositiveException(in[i][j]);\n }\n }\n }\n }\n\n /**\n * Modify the distribution used to compute inference statistics.\n *\n * @param value\n * the new distribution\n * @since 1.2\n */\n public void setDistribution(ChiSquaredDistribution value) {\n distribution = value;\n }\n}\n"} {"task_id": "Java_528", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/SpoonLabs/astor/examples/math_57/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java", "mask_start_position": 13413, "mask_end_position": 13413, "canonical_solution": "", "pre_mask_code": "package org.apache.commons.math.stat.inference;\n\nimport org.apache.commons.math.MathException;\nimport org.apache.commons.math.exception.NotPositiveException;\nimport org.apache.commons.math.exception.NotStrictlyPositiveException;\nimport org.apache.commons.math.exception.NumberIsTooSmallException;\nimport org.apache.commons.math.exception.OutOfRangeException;\nimport org.apache.commons.math.exception.DimensionMismatchException;\nimport org.apache.commons.math.exception.MathIllegalArgumentException;\nimport org.apache.commons.math.distribution.ChiSquaredDistribution;\nimport org.apache.commons.math.distribution.ChiSquaredDistributionImpl;\nimport org.apache.commons.math.exception.util.LocalizedFormats;\nimport org.apache.commons.math.util.FastMath;\n\n/**\n * Implements Chi-Square test statistics defined in the\n * {@link UnknownDistributionChiSquareTest} interface.\n *\n * @version $Revision$ $Date$\n */\npublic class ChiSquareTestImpl implements UnknownDistributionChiSquareTest {\n\n /**\n * Distribution used to compute inference statistics.\n */\n private ChiSquaredDistribution distribution;\n\n /**\n * Construct a ChiSquareTestImpl\n */\n public ChiSquareTestImpl() {\n this(new ChiSquaredDistributionImpl(1.0));\n }\n\n /**\n * Create a test instance using the given distribution for computing\n * inference statistics.\n * @param x distribution used to compute inference statistics.\n * @since 1.2\n */\n public ChiSquareTestImpl(ChiSquaredDistribution x) {\n super();\n setDistribution(x);\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return chi-square test statistic\n * @throws DimensionMismatchException if the arrays length is less than 2.\n */\n public double chiSquare(double[] expected, long[] observed) {\n if (expected.length < 2) {\n throw new DimensionMismatchException(expected.length, 2);\n }\n if (expected.length != observed.length) {\n throw new DimensionMismatchException(expected.length, observed.length);\n }\n checkPositive(expected);\n checkNonNegative(observed);\n double sumExpected = 0d;\n double sumObserved = 0d;\n for (int i = 0; i < observed.length; i++) {\n sumExpected += expected[i];\n sumObserved += observed[i];\n }\n double ratio = 1.0d;\n boolean rescale = false;\n if (FastMath.abs(sumExpected - sumObserved) > 10E-6) {\n ratio = sumObserved / sumExpected;\n rescale = true;\n }\n double sumSq = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n if (rescale) {\n final double dev = observed[i] - ratio * expected[i];\n sumSq += dev * dev / (ratio * expected[i]);\n } else {\n final double dev = observed[i] - expected[i];\n sumSq += dev * dev / expected[i];\n }\n }\n return sumSq;\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(double[] expected, long[] observed) throws MathException {\n distribution = new ChiSquaredDistributionImpl(expected.length - 1.0);\n return 1.0 - distribution.cumulativeProbability(chiSquare(expected, observed));\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(double[] expected, long[] observed, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(expected, observed) < alpha;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met.\n */\n public double chiSquare(long[][] counts) {\n checkArray(counts);\n int nRows = counts.length;\n int nCols = counts[0].length;\n // compute row, column and total sums\n double[] rowSum = new double[nRows];\n double[] colSum = new double[nCols];\n double total = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n rowSum[row] += counts[row][col];\n colSum[col] += counts[row][col];\n total += counts[row][col];\n }\n }\n // compute expected counts and chi-square\n double sumSq = 0.0d;\n double expected = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n expected = (rowSum[row] * colSum[col]) / total;\n sumSq += ((counts[row][col] - expected) * (counts[row][col] - expected)) / expected;\n }\n }\n return sumSq;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(long[][] counts) throws MathException {\n checkArray(counts);\n double df = ((double) counts.length - 1) * ((double) counts[0].length - 1);\n distribution = new ChiSquaredDistributionImpl(df);\n return 1 - distribution.cumulativeProbability(chiSquare(counts));\n }\n\n /**\n * @param counts array representation of 2-way table\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(long[][] counts, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(counts) < alpha;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met\n * @since 1.2\n */\n public double chiSquareDataSetsComparison(long[] observed1, long[] observed2) {\n // Make sure lengths are same\n if (observed1.length < 2) {\n throw new DimensionMismatchException(observed1.length, 2);\n }\n if (observed1.length != observed2.length) {\n throw new DimensionMismatchException(observed1.length, observed2.length);\n }\n // Ensure non-negative counts\n checkNonNegative(observed1);\n checkNonNegative(observed2);\n // Compute and compare count sums\n long countSum1 = 0;\n long countSum2 = 0;\n boolean unequalCounts = false;\n double weight = 0.0;\n for (int i = 0; i < observed1.length; i++) {\n countSum1 += observed1[i];\n countSum2 += observed2[i];\n }\n // Ensure neither sample is uniformly 0\n if (countSum1 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 1);\n }\n if (countSum2 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 2);\n }\n // Compare and compute weight only if different\n unequalCounts = countSum1 != countSum2;\n if (unequalCounts) {\n weight = FastMath.sqrt((double) countSum1 / (double) countSum2);\n }\n // Compute ChiSquare statistic\n double sumSq = 0.0d;\n double dev = 0.0d;\n double obs1 = 0.0d;\n double obs2 = 0.0d;\n for (int i = 0; i < observed1.length; i++) {\n if (observed1[i] == 0 && observed2[i] == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY, i);\n } else {\n obs1 = observed1[i];\n obs2 = observed2[i];\n if (unequalCounts) {\n // apply weights\n dev = obs1 / weight - obs2 * weight;\n } else {\n dev = obs1 - obs2;\n }\n sumSq += (dev * dev) / (obs1 + obs2);\n }\n }\n return sumSq;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n * @since 1.2\n */\n public double chiSquareTestDataSetsComparison(long[] observed1, long[] observed2) throws MathException {\n distribution = new ChiSquaredDistributionImpl((double) observed1.length - 1);\n return 1 - distribution.cumulativeProbability(chiSquareDataSetsComparison(observed1, observed2));\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n * @since 1.2\n */\n public boolean chiSquareTestDataSetsComparison(long[] observed1, long[] observed2, double alpha) throws MathException {\n if (alpha <= 0 || alpha > 0.5) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTestDataSetsComparison(observed1, observed2) < alpha;\n }\n\n /**\n * Checks to make sure that the input long[][] array is rectangular,\n * has at least 2 rows and 2 columns, and has all non-negative entries,\n * throwing MathIllegalArgumentException if any of these checks fail.\n *\n * @param in input 2-way table to check\n * @throws MathIllegalArgumentException if the array is not valid\n */\n private void checkArray(long[][] in) {\n if (in.length < 2) {\n throw new NumberIsTooSmallException(in.length, 2, true);\n }\n if (in[0].length < 2) {\n throw new NumberIsTooSmallException(in[0].length, 2, true);\n }\n checkRectangular(in);\n checkNonNegative(in);\n }\n\n // --------------------- Private array methods -- should find a utility home for these\n /**\n * Throws MathIllegalArgumentException if the input array is not rectangular.\n *\n * @param in array to be tested\n * @throws NullPointerException if input array is null\n * @throws MathIllegalArgumentException if input array is not rectangular\n */\n private void checkRectangular(long[][] in) {\n for (int i = 1; i < in.length; i++) {\n if (in[i].length != in[0].length) {\n throw new DimensionMismatchException(LocalizedFormats.DIFFERENT_ROWS_LENGTHS, in[i].length, in[0].length);\n }\n }\n }\n\n /**\n * Check all entries of the input array are strictly postive.\n *\n * @param in Array to be tested.\n * @exception NotStrictlyPositiveException if one entry is not positive.\n */\n private void checkPositive(double[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] <= 0) {\n throw new NotStrictlyPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[] in) {", "post_mask_code": "\n for (int i = 0; i < in.length; i++) {\n if (in[i] < 0) {\n throw new NotPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[][] in) {\n for (int i = 0; i < in.length; i++) {\n for (int j = 0; j < in[i].length; j++) {\n if (in[i][j] < 0) {\n throw new NotPositiveException(in[i][j]);\n }\n }\n }\n }\n\n /**\n * Modify the distribution used to compute inference statistics.\n *\n * @param value\n * the new distribution\n * @since 1.2\n */\n public void setDistribution(ChiSquaredDistribution value) {\n distribution = value;\n }\n}\n"} {"task_id": "Java_529", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/SpoonLabs/astor/examples/math_57/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java", "mask_start_position": 13422, "mask_end_position": 13567, "canonical_solution": "for (int i = 0; i < in.length; i++) {\n if (in[i] < 0) {\n throw new NotPositiveException(in[i]);\n }\n }", "pre_mask_code": "package org.apache.commons.math.stat.inference;\n\nimport org.apache.commons.math.MathException;\nimport org.apache.commons.math.exception.NotPositiveException;\nimport org.apache.commons.math.exception.NotStrictlyPositiveException;\nimport org.apache.commons.math.exception.NumberIsTooSmallException;\nimport org.apache.commons.math.exception.OutOfRangeException;\nimport org.apache.commons.math.exception.DimensionMismatchException;\nimport org.apache.commons.math.exception.MathIllegalArgumentException;\nimport org.apache.commons.math.distribution.ChiSquaredDistribution;\nimport org.apache.commons.math.distribution.ChiSquaredDistributionImpl;\nimport org.apache.commons.math.exception.util.LocalizedFormats;\nimport org.apache.commons.math.util.FastMath;\n\n/**\n * Implements Chi-Square test statistics defined in the\n * {@link UnknownDistributionChiSquareTest} interface.\n *\n * @version $Revision$ $Date$\n */\npublic class ChiSquareTestImpl implements UnknownDistributionChiSquareTest {\n\n /**\n * Distribution used to compute inference statistics.\n */\n private ChiSquaredDistribution distribution;\n\n /**\n * Construct a ChiSquareTestImpl\n */\n public ChiSquareTestImpl() {\n this(new ChiSquaredDistributionImpl(1.0));\n }\n\n /**\n * Create a test instance using the given distribution for computing\n * inference statistics.\n * @param x distribution used to compute inference statistics.\n * @since 1.2\n */\n public ChiSquareTestImpl(ChiSquaredDistribution x) {\n super();\n setDistribution(x);\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return chi-square test statistic\n * @throws DimensionMismatchException if the arrays length is less than 2.\n */\n public double chiSquare(double[] expected, long[] observed) {\n if (expected.length < 2) {\n throw new DimensionMismatchException(expected.length, 2);\n }\n if (expected.length != observed.length) {\n throw new DimensionMismatchException(expected.length, observed.length);\n }\n checkPositive(expected);\n checkNonNegative(observed);\n double sumExpected = 0d;\n double sumObserved = 0d;\n for (int i = 0; i < observed.length; i++) {\n sumExpected += expected[i];\n sumObserved += observed[i];\n }\n double ratio = 1.0d;\n boolean rescale = false;\n if (FastMath.abs(sumExpected - sumObserved) > 10E-6) {\n ratio = sumObserved / sumExpected;\n rescale = true;\n }\n double sumSq = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n if (rescale) {\n final double dev = observed[i] - ratio * expected[i];\n sumSq += dev * dev / (ratio * expected[i]);\n } else {\n final double dev = observed[i] - expected[i];\n sumSq += dev * dev / expected[i];\n }\n }\n return sumSq;\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(double[] expected, long[] observed) throws MathException {\n distribution = new ChiSquaredDistributionImpl(expected.length - 1.0);\n return 1.0 - distribution.cumulativeProbability(chiSquare(expected, observed));\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(double[] expected, long[] observed, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(expected, observed) < alpha;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met.\n */\n public double chiSquare(long[][] counts) {\n checkArray(counts);\n int nRows = counts.length;\n int nCols = counts[0].length;\n // compute row, column and total sums\n double[] rowSum = new double[nRows];\n double[] colSum = new double[nCols];\n double total = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n rowSum[row] += counts[row][col];\n colSum[col] += counts[row][col];\n total += counts[row][col];\n }\n }\n // compute expected counts and chi-square\n double sumSq = 0.0d;\n double expected = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n expected = (rowSum[row] * colSum[col]) / total;\n sumSq += ((counts[row][col] - expected) * (counts[row][col] - expected)) / expected;\n }\n }\n return sumSq;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(long[][] counts) throws MathException {\n checkArray(counts);\n double df = ((double) counts.length - 1) * ((double) counts[0].length - 1);\n distribution = new ChiSquaredDistributionImpl(df);\n return 1 - distribution.cumulativeProbability(chiSquare(counts));\n }\n\n /**\n * @param counts array representation of 2-way table\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(long[][] counts, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(counts) < alpha;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met\n * @since 1.2\n */\n public double chiSquareDataSetsComparison(long[] observed1, long[] observed2) {\n // Make sure lengths are same\n if (observed1.length < 2) {\n throw new DimensionMismatchException(observed1.length, 2);\n }\n if (observed1.length != observed2.length) {\n throw new DimensionMismatchException(observed1.length, observed2.length);\n }\n // Ensure non-negative counts\n checkNonNegative(observed1);\n checkNonNegative(observed2);\n // Compute and compare count sums\n long countSum1 = 0;\n long countSum2 = 0;\n boolean unequalCounts = false;\n double weight = 0.0;\n for (int i = 0; i < observed1.length; i++) {\n countSum1 += observed1[i];\n countSum2 += observed2[i];\n }\n // Ensure neither sample is uniformly 0\n if (countSum1 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 1);\n }\n if (countSum2 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 2);\n }\n // Compare and compute weight only if different\n unequalCounts = countSum1 != countSum2;\n if (unequalCounts) {\n weight = FastMath.sqrt((double) countSum1 / (double) countSum2);\n }\n // Compute ChiSquare statistic\n double sumSq = 0.0d;\n double dev = 0.0d;\n double obs1 = 0.0d;\n double obs2 = 0.0d;\n for (int i = 0; i < observed1.length; i++) {\n if (observed1[i] == 0 && observed2[i] == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY, i);\n } else {\n obs1 = observed1[i];\n obs2 = observed2[i];\n if (unequalCounts) {\n // apply weights\n dev = obs1 / weight - obs2 * weight;\n } else {\n dev = obs1 - obs2;\n }\n sumSq += (dev * dev) / (obs1 + obs2);\n }\n }\n return sumSq;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n * @since 1.2\n */\n public double chiSquareTestDataSetsComparison(long[] observed1, long[] observed2) throws MathException {\n distribution = new ChiSquaredDistributionImpl((double) observed1.length - 1);\n return 1 - distribution.cumulativeProbability(chiSquareDataSetsComparison(observed1, observed2));\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n * @since 1.2\n */\n public boolean chiSquareTestDataSetsComparison(long[] observed1, long[] observed2, double alpha) throws MathException {\n if (alpha <= 0 || alpha > 0.5) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTestDataSetsComparison(observed1, observed2) < alpha;\n }\n\n /**\n * Checks to make sure that the input long[][] array is rectangular,\n * has at least 2 rows and 2 columns, and has all non-negative entries,\n * throwing MathIllegalArgumentException if any of these checks fail.\n *\n * @param in input 2-way table to check\n * @throws MathIllegalArgumentException if the array is not valid\n */\n private void checkArray(long[][] in) {\n if (in.length < 2) {\n throw new NumberIsTooSmallException(in.length, 2, true);\n }\n if (in[0].length < 2) {\n throw new NumberIsTooSmallException(in[0].length, 2, true);\n }\n checkRectangular(in);\n checkNonNegative(in);\n }\n\n // --------------------- Private array methods -- should find a utility home for these\n /**\n * Throws MathIllegalArgumentException if the input array is not rectangular.\n *\n * @param in array to be tested\n * @throws NullPointerException if input array is null\n * @throws MathIllegalArgumentException if input array is not rectangular\n */\n private void checkRectangular(long[][] in) {\n for (int i = 1; i < in.length; i++) {\n if (in[i].length != in[0].length) {\n throw new DimensionMismatchException(LocalizedFormats.DIFFERENT_ROWS_LENGTHS, in[i].length, in[0].length);\n }\n }\n }\n\n /**\n * Check all entries of the input array are strictly postive.\n *\n * @param in Array to be tested.\n * @exception NotStrictlyPositiveException if one entry is not positive.\n */\n private void checkPositive(double[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] <= 0) {\n throw new NotStrictlyPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[] in) {\n ", "post_mask_code": "\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[][] in) {\n for (int i = 0; i < in.length; i++) {\n for (int j = 0; j < in[i].length; j++) {\n if (in[i][j] < 0) {\n throw new NotPositiveException(in[i][j]);\n }\n }\n }\n }\n\n /**\n * Modify the distribution used to compute inference statistics.\n *\n * @param value\n * the new distribution\n * @since 1.2\n */\n public void setDistribution(ChiSquaredDistribution value) {\n distribution = value;\n }\n}\n"} {"task_id": "Java_530", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/SpoonLabs/astor/examples/math_57/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java", "mask_start_position": 13572, "mask_end_position": 13573, "canonical_solution": "}", "pre_mask_code": "package org.apache.commons.math.stat.inference;\n\nimport org.apache.commons.math.MathException;\nimport org.apache.commons.math.exception.NotPositiveException;\nimport org.apache.commons.math.exception.NotStrictlyPositiveException;\nimport org.apache.commons.math.exception.NumberIsTooSmallException;\nimport org.apache.commons.math.exception.OutOfRangeException;\nimport org.apache.commons.math.exception.DimensionMismatchException;\nimport org.apache.commons.math.exception.MathIllegalArgumentException;\nimport org.apache.commons.math.distribution.ChiSquaredDistribution;\nimport org.apache.commons.math.distribution.ChiSquaredDistributionImpl;\nimport org.apache.commons.math.exception.util.LocalizedFormats;\nimport org.apache.commons.math.util.FastMath;\n\n/**\n * Implements Chi-Square test statistics defined in the\n * {@link UnknownDistributionChiSquareTest} interface.\n *\n * @version $Revision$ $Date$\n */\npublic class ChiSquareTestImpl implements UnknownDistributionChiSquareTest {\n\n /**\n * Distribution used to compute inference statistics.\n */\n private ChiSquaredDistribution distribution;\n\n /**\n * Construct a ChiSquareTestImpl\n */\n public ChiSquareTestImpl() {\n this(new ChiSquaredDistributionImpl(1.0));\n }\n\n /**\n * Create a test instance using the given distribution for computing\n * inference statistics.\n * @param x distribution used to compute inference statistics.\n * @since 1.2\n */\n public ChiSquareTestImpl(ChiSquaredDistribution x) {\n super();\n setDistribution(x);\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return chi-square test statistic\n * @throws DimensionMismatchException if the arrays length is less than 2.\n */\n public double chiSquare(double[] expected, long[] observed) {\n if (expected.length < 2) {\n throw new DimensionMismatchException(expected.length, 2);\n }\n if (expected.length != observed.length) {\n throw new DimensionMismatchException(expected.length, observed.length);\n }\n checkPositive(expected);\n checkNonNegative(observed);\n double sumExpected = 0d;\n double sumObserved = 0d;\n for (int i = 0; i < observed.length; i++) {\n sumExpected += expected[i];\n sumObserved += observed[i];\n }\n double ratio = 1.0d;\n boolean rescale = false;\n if (FastMath.abs(sumExpected - sumObserved) > 10E-6) {\n ratio = sumObserved / sumExpected;\n rescale = true;\n }\n double sumSq = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n if (rescale) {\n final double dev = observed[i] - ratio * expected[i];\n sumSq += dev * dev / (ratio * expected[i]);\n } else {\n final double dev = observed[i] - expected[i];\n sumSq += dev * dev / expected[i];\n }\n }\n return sumSq;\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(double[] expected, long[] observed) throws MathException {\n distribution = new ChiSquaredDistributionImpl(expected.length - 1.0);\n return 1.0 - distribution.cumulativeProbability(chiSquare(expected, observed));\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(double[] expected, long[] observed, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(expected, observed) < alpha;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met.\n */\n public double chiSquare(long[][] counts) {\n checkArray(counts);\n int nRows = counts.length;\n int nCols = counts[0].length;\n // compute row, column and total sums\n double[] rowSum = new double[nRows];\n double[] colSum = new double[nCols];\n double total = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n rowSum[row] += counts[row][col];\n colSum[col] += counts[row][col];\n total += counts[row][col];\n }\n }\n // compute expected counts and chi-square\n double sumSq = 0.0d;\n double expected = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n expected = (rowSum[row] * colSum[col]) / total;\n sumSq += ((counts[row][col] - expected) * (counts[row][col] - expected)) / expected;\n }\n }\n return sumSq;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(long[][] counts) throws MathException {\n checkArray(counts);\n double df = ((double) counts.length - 1) * ((double) counts[0].length - 1);\n distribution = new ChiSquaredDistributionImpl(df);\n return 1 - distribution.cumulativeProbability(chiSquare(counts));\n }\n\n /**\n * @param counts array representation of 2-way table\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(long[][] counts, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(counts) < alpha;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met\n * @since 1.2\n */\n public double chiSquareDataSetsComparison(long[] observed1, long[] observed2) {\n // Make sure lengths are same\n if (observed1.length < 2) {\n throw new DimensionMismatchException(observed1.length, 2);\n }\n if (observed1.length != observed2.length) {\n throw new DimensionMismatchException(observed1.length, observed2.length);\n }\n // Ensure non-negative counts\n checkNonNegative(observed1);\n checkNonNegative(observed2);\n // Compute and compare count sums\n long countSum1 = 0;\n long countSum2 = 0;\n boolean unequalCounts = false;\n double weight = 0.0;\n for (int i = 0; i < observed1.length; i++) {\n countSum1 += observed1[i];\n countSum2 += observed2[i];\n }\n // Ensure neither sample is uniformly 0\n if (countSum1 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 1);\n }\n if (countSum2 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 2);\n }\n // Compare and compute weight only if different\n unequalCounts = countSum1 != countSum2;\n if (unequalCounts) {\n weight = FastMath.sqrt((double) countSum1 / (double) countSum2);\n }\n // Compute ChiSquare statistic\n double sumSq = 0.0d;\n double dev = 0.0d;\n double obs1 = 0.0d;\n double obs2 = 0.0d;\n for (int i = 0; i < observed1.length; i++) {\n if (observed1[i] == 0 && observed2[i] == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY, i);\n } else {\n obs1 = observed1[i];\n obs2 = observed2[i];\n if (unequalCounts) {\n // apply weights\n dev = obs1 / weight - obs2 * weight;\n } else {\n dev = obs1 - obs2;\n }\n sumSq += (dev * dev) / (obs1 + obs2);\n }\n }\n return sumSq;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n * @since 1.2\n */\n public double chiSquareTestDataSetsComparison(long[] observed1, long[] observed2) throws MathException {\n distribution = new ChiSquaredDistributionImpl((double) observed1.length - 1);\n return 1 - distribution.cumulativeProbability(chiSquareDataSetsComparison(observed1, observed2));\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n * @since 1.2\n */\n public boolean chiSquareTestDataSetsComparison(long[] observed1, long[] observed2, double alpha) throws MathException {\n if (alpha <= 0 || alpha > 0.5) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTestDataSetsComparison(observed1, observed2) < alpha;\n }\n\n /**\n * Checks to make sure that the input long[][] array is rectangular,\n * has at least 2 rows and 2 columns, and has all non-negative entries,\n * throwing MathIllegalArgumentException if any of these checks fail.\n *\n * @param in input 2-way table to check\n * @throws MathIllegalArgumentException if the array is not valid\n */\n private void checkArray(long[][] in) {\n if (in.length < 2) {\n throw new NumberIsTooSmallException(in.length, 2, true);\n }\n if (in[0].length < 2) {\n throw new NumberIsTooSmallException(in[0].length, 2, true);\n }\n checkRectangular(in);\n checkNonNegative(in);\n }\n\n // --------------------- Private array methods -- should find a utility home for these\n /**\n * Throws MathIllegalArgumentException if the input array is not rectangular.\n *\n * @param in array to be tested\n * @throws NullPointerException if input array is null\n * @throws MathIllegalArgumentException if input array is not rectangular\n */\n private void checkRectangular(long[][] in) {\n for (int i = 1; i < in.length; i++) {\n if (in[i].length != in[0].length) {\n throw new DimensionMismatchException(LocalizedFormats.DIFFERENT_ROWS_LENGTHS, in[i].length, in[0].length);\n }\n }\n }\n\n /**\n * Check all entries of the input array are strictly postive.\n *\n * @param in Array to be tested.\n * @exception NotStrictlyPositiveException if one entry is not positive.\n */\n private void checkPositive(double[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] <= 0) {\n throw new NotStrictlyPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] < 0) {\n throw new NotPositiveException(in[i]);\n }\n }\n ", "post_mask_code": "\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[][] in) {\n for (int i = 0; i < in.length; i++) {\n for (int j = 0; j < in[i].length; j++) {\n if (in[i][j] < 0) {\n throw new NotPositiveException(in[i][j]);\n }\n }\n }\n }\n\n /**\n * Modify the distribution used to compute inference statistics.\n *\n * @param value\n * the new distribution\n * @since 1.2\n */\n public void setDistribution(ChiSquaredDistribution value) {\n distribution = value;\n }\n}\n"} {"task_id": "Java_531", "language": "Java", "task_type": "single_line", "source_file": "java/github/SpoonLabs/astor/examples/math_57/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java", "mask_start_position": 8401, "mask_end_position": 8416, "canonical_solution": "e weight = 0.0;", "pre_mask_code": "package org.apache.commons.math.stat.inference;\n\nimport org.apache.commons.math.MathException;\nimport org.apache.commons.math.exception.NotPositiveException;\nimport org.apache.commons.math.exception.NotStrictlyPositiveException;\nimport org.apache.commons.math.exception.NumberIsTooSmallException;\nimport org.apache.commons.math.exception.OutOfRangeException;\nimport org.apache.commons.math.exception.DimensionMismatchException;\nimport org.apache.commons.math.exception.MathIllegalArgumentException;\nimport org.apache.commons.math.distribution.ChiSquaredDistribution;\nimport org.apache.commons.math.distribution.ChiSquaredDistributionImpl;\nimport org.apache.commons.math.exception.util.LocalizedFormats;\nimport org.apache.commons.math.util.FastMath;\n\n/**\n * Implements Chi-Square test statistics defined in the\n * {@link UnknownDistributionChiSquareTest} interface.\n *\n * @version $Revision$ $Date$\n */\npublic class ChiSquareTestImpl implements UnknownDistributionChiSquareTest {\n\n /**\n * Distribution used to compute inference statistics.\n */\n private ChiSquaredDistribution distribution;\n\n /**\n * Construct a ChiSquareTestImpl\n */\n public ChiSquareTestImpl() {\n this(new ChiSquaredDistributionImpl(1.0));\n }\n\n /**\n * Create a test instance using the given distribution for computing\n * inference statistics.\n * @param x distribution used to compute inference statistics.\n * @since 1.2\n */\n public ChiSquareTestImpl(ChiSquaredDistribution x) {\n super();\n setDistribution(x);\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return chi-square test statistic\n * @throws DimensionMismatchException if the arrays length is less than 2.\n */\n public double chiSquare(double[] expected, long[] observed) {\n if (expected.length < 2) {\n throw new DimensionMismatchException(expected.length, 2);\n }\n if (expected.length != observed.length) {\n throw new DimensionMismatchException(expected.length, observed.length);\n }\n checkPositive(expected);\n checkNonNegative(observed);\n double sumExpected = 0d;\n double sumObserved = 0d;\n for (int i = 0; i < observed.length; i++) {\n sumExpected += expected[i];\n sumObserved += observed[i];\n }\n double ratio = 1.0d;\n boolean rescale = false;\n if (FastMath.abs(sumExpected - sumObserved) > 10E-6) {\n ratio = sumObserved / sumExpected;\n rescale = true;\n }\n double sumSq = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n if (rescale) {\n final double dev = observed[i] - ratio * expected[i];\n sumSq += dev * dev / (ratio * expected[i]);\n } else {\n final double dev = observed[i] - expected[i];\n sumSq += dev * dev / expected[i];\n }\n }\n return sumSq;\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(double[] expected, long[] observed) throws MathException {\n distribution = new ChiSquaredDistributionImpl(expected.length - 1.0);\n return 1.0 - distribution.cumulativeProbability(chiSquare(expected, observed));\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(double[] expected, long[] observed, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(expected, observed) < alpha;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met.\n */\n public double chiSquare(long[][] counts) {\n checkArray(counts);\n int nRows = counts.length;\n int nCols = counts[0].length;\n // compute row, column and total sums\n double[] rowSum = new double[nRows];\n double[] colSum = new double[nCols];\n double total = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n rowSum[row] += counts[row][col];\n colSum[col] += counts[row][col];\n total += counts[row][col];\n }\n }\n // compute expected counts and chi-square\n double sumSq = 0.0d;\n double expected = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n expected = (rowSum[row] * colSum[col]) / total;\n sumSq += ((counts[row][col] - expected) * (counts[row][col] - expected)) / expected;\n }\n }\n return sumSq;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(long[][] counts) throws MathException {\n checkArray(counts);\n double df = ((double) counts.length - 1) * ((double) counts[0].length - 1);\n distribution = new ChiSquaredDistributionImpl(df);\n return 1 - distribution.cumulativeProbability(chiSquare(counts));\n }\n\n /**\n * @param counts array representation of 2-way table\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(long[][] counts, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(counts) < alpha;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met\n * @since 1.2\n */\n public double chiSquareDataSetsComparison(long[] observed1, long[] observed2) {\n // Make sure lengths are same\n if (observed1.length < 2) {\n throw new DimensionMismatchException(observed1.length, 2);\n }\n if (observed1.length != observed2.length) {\n throw new DimensionMismatchException(observed1.length, observed2.length);\n }\n // Ensure non-negative counts\n checkNonNegative(observed1);\n checkNonNegative(observed2);\n // Compute and compare count sums\n long countSum1 = 0;\n long countSum2 = 0;\n boolean unequalCounts = false;\n doubl", "post_mask_code": "\n for (int i = 0; i < observed1.length; i++) {\n countSum1 += observed1[i];\n countSum2 += observed2[i];\n }\n // Ensure neither sample is uniformly 0\n if (countSum1 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 1);\n }\n if (countSum2 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 2);\n }\n // Compare and compute weight only if different\n unequalCounts = countSum1 != countSum2;\n if (unequalCounts) {\n weight = FastMath.sqrt((double) countSum1 / (double) countSum2);\n }\n // Compute ChiSquare statistic\n double sumSq = 0.0d;\n double dev = 0.0d;\n double obs1 = 0.0d;\n double obs2 = 0.0d;\n for (int i = 0; i < observed1.length; i++) {\n if (observed1[i] == 0 && observed2[i] == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY, i);\n } else {\n obs1 = observed1[i];\n obs2 = observed2[i];\n if (unequalCounts) {\n // apply weights\n dev = obs1 / weight - obs2 * weight;\n } else {\n dev = obs1 - obs2;\n }\n sumSq += (dev * dev) / (obs1 + obs2);\n }\n }\n return sumSq;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n * @since 1.2\n */\n public double chiSquareTestDataSetsComparison(long[] observed1, long[] observed2) throws MathException {\n distribution = new ChiSquaredDistributionImpl((double) observed1.length - 1);\n return 1 - distribution.cumulativeProbability(chiSquareDataSetsComparison(observed1, observed2));\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n * @since 1.2\n */\n public boolean chiSquareTestDataSetsComparison(long[] observed1, long[] observed2, double alpha) throws MathException {\n if (alpha <= 0 || alpha > 0.5) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTestDataSetsComparison(observed1, observed2) < alpha;\n }\n\n /**\n * Checks to make sure that the input long[][] array is rectangular,\n * has at least 2 rows and 2 columns, and has all non-negative entries,\n * throwing MathIllegalArgumentException if any of these checks fail.\n *\n * @param in input 2-way table to check\n * @throws MathIllegalArgumentException if the array is not valid\n */\n private void checkArray(long[][] in) {\n if (in.length < 2) {\n throw new NumberIsTooSmallException(in.length, 2, true);\n }\n if (in[0].length < 2) {\n throw new NumberIsTooSmallException(in[0].length, 2, true);\n }\n checkRectangular(in);\n checkNonNegative(in);\n }\n\n // --------------------- Private array methods -- should find a utility home for these\n /**\n * Throws MathIllegalArgumentException if the input array is not rectangular.\n *\n * @param in array to be tested\n * @throws NullPointerException if input array is null\n * @throws MathIllegalArgumentException if input array is not rectangular\n */\n private void checkRectangular(long[][] in) {\n for (int i = 1; i < in.length; i++) {\n if (in[i].length != in[0].length) {\n throw new DimensionMismatchException(LocalizedFormats.DIFFERENT_ROWS_LENGTHS, in[i].length, in[0].length);\n }\n }\n }\n\n /**\n * Check all entries of the input array are strictly postive.\n *\n * @param in Array to be tested.\n * @exception NotStrictlyPositiveException if one entry is not positive.\n */\n private void checkPositive(double[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] <= 0) {\n throw new NotStrictlyPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] < 0) {\n throw new NotPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[][] in) {\n for (int i = 0; i < in.length; i++) {\n for (int j = 0; j < in[i].length; j++) {\n if (in[i][j] < 0) {\n throw new NotPositiveException(in[i][j]);\n }\n }\n }\n }\n\n /**\n * Modify the distribution used to compute inference statistics.\n *\n * @param value\n * the new distribution\n * @since 1.2\n */\n public void setDistribution(ChiSquaredDistribution value) {\n distribution = value;\n }\n}\n"} {"task_id": "Java_532", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/SpoonLabs/astor/examples/math_57/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java", "mask_start_position": 12476, "mask_end_position": 12767, "canonical_solution": "private void checkRectangular(long[][] in) {\n for (int i = 1; i < in.length; i++) {\n if (in[i].length != in[0].length) {\n throw new DimensionMismatchException(LocalizedFormats.DIFFERENT_ROWS_LENGTHS, in[i].length, in[0].length);\n }\n }\n }", "pre_mask_code": "package org.apache.commons.math.stat.inference;\n\nimport org.apache.commons.math.MathException;\nimport org.apache.commons.math.exception.NotPositiveException;\nimport org.apache.commons.math.exception.NotStrictlyPositiveException;\nimport org.apache.commons.math.exception.NumberIsTooSmallException;\nimport org.apache.commons.math.exception.OutOfRangeException;\nimport org.apache.commons.math.exception.DimensionMismatchException;\nimport org.apache.commons.math.exception.MathIllegalArgumentException;\nimport org.apache.commons.math.distribution.ChiSquaredDistribution;\nimport org.apache.commons.math.distribution.ChiSquaredDistributionImpl;\nimport org.apache.commons.math.exception.util.LocalizedFormats;\nimport org.apache.commons.math.util.FastMath;\n\n/**\n * Implements Chi-Square test statistics defined in the\n * {@link UnknownDistributionChiSquareTest} interface.\n *\n * @version $Revision$ $Date$\n */\npublic class ChiSquareTestImpl implements UnknownDistributionChiSquareTest {\n\n /**\n * Distribution used to compute inference statistics.\n */\n private ChiSquaredDistribution distribution;\n\n /**\n * Construct a ChiSquareTestImpl\n */\n public ChiSquareTestImpl() {\n this(new ChiSquaredDistributionImpl(1.0));\n }\n\n /**\n * Create a test instance using the given distribution for computing\n * inference statistics.\n * @param x distribution used to compute inference statistics.\n * @since 1.2\n */\n public ChiSquareTestImpl(ChiSquaredDistribution x) {\n super();\n setDistribution(x);\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return chi-square test statistic\n * @throws DimensionMismatchException if the arrays length is less than 2.\n */\n public double chiSquare(double[] expected, long[] observed) {\n if (expected.length < 2) {\n throw new DimensionMismatchException(expected.length, 2);\n }\n if (expected.length != observed.length) {\n throw new DimensionMismatchException(expected.length, observed.length);\n }\n checkPositive(expected);\n checkNonNegative(observed);\n double sumExpected = 0d;\n double sumObserved = 0d;\n for (int i = 0; i < observed.length; i++) {\n sumExpected += expected[i];\n sumObserved += observed[i];\n }\n double ratio = 1.0d;\n boolean rescale = false;\n if (FastMath.abs(sumExpected - sumObserved) > 10E-6) {\n ratio = sumObserved / sumExpected;\n rescale = true;\n }\n double sumSq = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n if (rescale) {\n final double dev = observed[i] - ratio * expected[i];\n sumSq += dev * dev / (ratio * expected[i]);\n } else {\n final double dev = observed[i] - expected[i];\n sumSq += dev * dev / expected[i];\n }\n }\n return sumSq;\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(double[] expected, long[] observed) throws MathException {\n distribution = new ChiSquaredDistributionImpl(expected.length - 1.0);\n return 1.0 - distribution.cumulativeProbability(chiSquare(expected, observed));\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(double[] expected, long[] observed, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(expected, observed) < alpha;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met.\n */\n public double chiSquare(long[][] counts) {\n checkArray(counts);\n int nRows = counts.length;\n int nCols = counts[0].length;\n // compute row, column and total sums\n double[] rowSum = new double[nRows];\n double[] colSum = new double[nCols];\n double total = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n rowSum[row] += counts[row][col];\n colSum[col] += counts[row][col];\n total += counts[row][col];\n }\n }\n // compute expected counts and chi-square\n double sumSq = 0.0d;\n double expected = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n expected = (rowSum[row] * colSum[col]) / total;\n sumSq += ((counts[row][col] - expected) * (counts[row][col] - expected)) / expected;\n }\n }\n return sumSq;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(long[][] counts) throws MathException {\n checkArray(counts);\n double df = ((double) counts.length - 1) * ((double) counts[0].length - 1);\n distribution = new ChiSquaredDistributionImpl(df);\n return 1 - distribution.cumulativeProbability(chiSquare(counts));\n }\n\n /**\n * @param counts array representation of 2-way table\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(long[][] counts, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(counts) < alpha;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met\n * @since 1.2\n */\n public double chiSquareDataSetsComparison(long[] observed1, long[] observed2) {\n // Make sure lengths are same\n if (observed1.length < 2) {\n throw new DimensionMismatchException(observed1.length, 2);\n }\n if (observed1.length != observed2.length) {\n throw new DimensionMismatchException(observed1.length, observed2.length);\n }\n // Ensure non-negative counts\n checkNonNegative(observed1);\n checkNonNegative(observed2);\n // Compute and compare count sums\n long countSum1 = 0;\n long countSum2 = 0;\n boolean unequalCounts = false;\n double weight = 0.0;\n for (int i = 0; i < observed1.length; i++) {\n countSum1 += observed1[i];\n countSum2 += observed2[i];\n }\n // Ensure neither sample is uniformly 0\n if (countSum1 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 1);\n }\n if (countSum2 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 2);\n }\n // Compare and compute weight only if different\n unequalCounts = countSum1 != countSum2;\n if (unequalCounts) {\n weight = FastMath.sqrt((double) countSum1 / (double) countSum2);\n }\n // Compute ChiSquare statistic\n double sumSq = 0.0d;\n double dev = 0.0d;\n double obs1 = 0.0d;\n double obs2 = 0.0d;\n for (int i = 0; i < observed1.length; i++) {\n if (observed1[i] == 0 && observed2[i] == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY, i);\n } else {\n obs1 = observed1[i];\n obs2 = observed2[i];\n if (unequalCounts) {\n // apply weights\n dev = obs1 / weight - obs2 * weight;\n } else {\n dev = obs1 - obs2;\n }\n sumSq += (dev * dev) / (obs1 + obs2);\n }\n }\n return sumSq;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n * @since 1.2\n */\n public double chiSquareTestDataSetsComparison(long[] observed1, long[] observed2) throws MathException {\n distribution = new ChiSquaredDistributionImpl((double) observed1.length - 1);\n return 1 - distribution.cumulativeProbability(chiSquareDataSetsComparison(observed1, observed2));\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n * @since 1.2\n */\n public boolean chiSquareTestDataSetsComparison(long[] observed1, long[] observed2, double alpha) throws MathException {\n if (alpha <= 0 || alpha > 0.5) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTestDataSetsComparison(observed1, observed2) < alpha;\n }\n\n /**\n * Checks to make sure that the input long[][] array is rectangular,\n * has at least 2 rows and 2 columns, and has all non-negative entries,\n * throwing MathIllegalArgumentException if any of these checks fail.\n *\n * @param in input 2-way table to check\n * @throws MathIllegalArgumentException if the array is not valid\n */\n private void checkArray(long[][] in) {\n if (in.length < 2) {\n throw new NumberIsTooSmallException(in.length, 2, true);\n }\n if (in[0].length < 2) {\n throw new NumberIsTooSmallException(in[0].length, 2, true);\n }\n checkRectangular(in);\n checkNonNegative(in);\n }\n\n // --------------------- Private array methods -- should find a utility home for these\n /**\n * Throws MathIllegalArgumentException if the input array is not rectangular.\n *\n * @param in array to be tested\n * @throws NullPointerException if input array is null\n * @throws MathIllegalArgumentException if input array is not rectangular\n */\n ", "post_mask_code": "\n\n /**\n * Check all entries of the input array are strictly postive.\n *\n * @param in Array to be tested.\n * @exception NotStrictlyPositiveException if one entry is not positive.\n */\n private void checkPositive(double[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] <= 0) {\n throw new NotStrictlyPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] < 0) {\n throw new NotPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[][] in) {\n for (int i = 0; i < in.length; i++) {\n for (int j = 0; j < in[i].length; j++) {\n if (in[i][j] < 0) {\n throw new NotPositiveException(in[i][j]);\n }\n }\n }\n }\n\n /**\n * Modify the distribution used to compute inference statistics.\n *\n * @param value\n * the new distribution\n * @since 1.2\n */\n public void setDistribution(ChiSquaredDistribution value) {\n distribution = value;\n }\n}\n"} {"task_id": "Java_533", "language": "Java", "task_type": "if_statement", "source_file": "java/github/SpoonLabs/astor/examples/math_57/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java", "mask_start_position": 8752, "mask_end_position": 8881, "canonical_solution": "if (countSum2 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 2);\n }", "pre_mask_code": "package org.apache.commons.math.stat.inference;\n\nimport org.apache.commons.math.MathException;\nimport org.apache.commons.math.exception.NotPositiveException;\nimport org.apache.commons.math.exception.NotStrictlyPositiveException;\nimport org.apache.commons.math.exception.NumberIsTooSmallException;\nimport org.apache.commons.math.exception.OutOfRangeException;\nimport org.apache.commons.math.exception.DimensionMismatchException;\nimport org.apache.commons.math.exception.MathIllegalArgumentException;\nimport org.apache.commons.math.distribution.ChiSquaredDistribution;\nimport org.apache.commons.math.distribution.ChiSquaredDistributionImpl;\nimport org.apache.commons.math.exception.util.LocalizedFormats;\nimport org.apache.commons.math.util.FastMath;\n\n/**\n * Implements Chi-Square test statistics defined in the\n * {@link UnknownDistributionChiSquareTest} interface.\n *\n * @version $Revision$ $Date$\n */\npublic class ChiSquareTestImpl implements UnknownDistributionChiSquareTest {\n\n /**\n * Distribution used to compute inference statistics.\n */\n private ChiSquaredDistribution distribution;\n\n /**\n * Construct a ChiSquareTestImpl\n */\n public ChiSquareTestImpl() {\n this(new ChiSquaredDistributionImpl(1.0));\n }\n\n /**\n * Create a test instance using the given distribution for computing\n * inference statistics.\n * @param x distribution used to compute inference statistics.\n * @since 1.2\n */\n public ChiSquareTestImpl(ChiSquaredDistribution x) {\n super();\n setDistribution(x);\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return chi-square test statistic\n * @throws DimensionMismatchException if the arrays length is less than 2.\n */\n public double chiSquare(double[] expected, long[] observed) {\n if (expected.length < 2) {\n throw new DimensionMismatchException(expected.length, 2);\n }\n if (expected.length != observed.length) {\n throw new DimensionMismatchException(expected.length, observed.length);\n }\n checkPositive(expected);\n checkNonNegative(observed);\n double sumExpected = 0d;\n double sumObserved = 0d;\n for (int i = 0; i < observed.length; i++) {\n sumExpected += expected[i];\n sumObserved += observed[i];\n }\n double ratio = 1.0d;\n boolean rescale = false;\n if (FastMath.abs(sumExpected - sumObserved) > 10E-6) {\n ratio = sumObserved / sumExpected;\n rescale = true;\n }\n double sumSq = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n if (rescale) {\n final double dev = observed[i] - ratio * expected[i];\n sumSq += dev * dev / (ratio * expected[i]);\n } else {\n final double dev = observed[i] - expected[i];\n sumSq += dev * dev / expected[i];\n }\n }\n return sumSq;\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(double[] expected, long[] observed) throws MathException {\n distribution = new ChiSquaredDistributionImpl(expected.length - 1.0);\n return 1.0 - distribution.cumulativeProbability(chiSquare(expected, observed));\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(double[] expected, long[] observed, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(expected, observed) < alpha;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met.\n */\n public double chiSquare(long[][] counts) {\n checkArray(counts);\n int nRows = counts.length;\n int nCols = counts[0].length;\n // compute row, column and total sums\n double[] rowSum = new double[nRows];\n double[] colSum = new double[nCols];\n double total = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n rowSum[row] += counts[row][col];\n colSum[col] += counts[row][col];\n total += counts[row][col];\n }\n }\n // compute expected counts and chi-square\n double sumSq = 0.0d;\n double expected = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n expected = (rowSum[row] * colSum[col]) / total;\n sumSq += ((counts[row][col] - expected) * (counts[row][col] - expected)) / expected;\n }\n }\n return sumSq;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(long[][] counts) throws MathException {\n checkArray(counts);\n double df = ((double) counts.length - 1) * ((double) counts[0].length - 1);\n distribution = new ChiSquaredDistributionImpl(df);\n return 1 - distribution.cumulativeProbability(chiSquare(counts));\n }\n\n /**\n * @param counts array representation of 2-way table\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(long[][] counts, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(counts) < alpha;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met\n * @since 1.2\n */\n public double chiSquareDataSetsComparison(long[] observed1, long[] observed2) {\n // Make sure lengths are same\n if (observed1.length < 2) {\n throw new DimensionMismatchException(observed1.length, 2);\n }\n if (observed1.length != observed2.length) {\n throw new DimensionMismatchException(observed1.length, observed2.length);\n }\n // Ensure non-negative counts\n checkNonNegative(observed1);\n checkNonNegative(observed2);\n // Compute and compare count sums\n long countSum1 = 0;\n long countSum2 = 0;\n boolean unequalCounts = false;\n double weight = 0.0;\n for (int i = 0; i < observed1.length; i++) {\n countSum1 += observed1[i];\n countSum2 += observed2[i];\n }\n // Ensure neither sample is uniformly 0\n if (countSum1 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 1);\n }\n ", "post_mask_code": "\n // Compare and compute weight only if different\n unequalCounts = countSum1 != countSum2;\n if (unequalCounts) {\n weight = FastMath.sqrt((double) countSum1 / (double) countSum2);\n }\n // Compute ChiSquare statistic\n double sumSq = 0.0d;\n double dev = 0.0d;\n double obs1 = 0.0d;\n double obs2 = 0.0d;\n for (int i = 0; i < observed1.length; i++) {\n if (observed1[i] == 0 && observed2[i] == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY, i);\n } else {\n obs1 = observed1[i];\n obs2 = observed2[i];\n if (unequalCounts) {\n // apply weights\n dev = obs1 / weight - obs2 * weight;\n } else {\n dev = obs1 - obs2;\n }\n sumSq += (dev * dev) / (obs1 + obs2);\n }\n }\n return sumSq;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n * @since 1.2\n */\n public double chiSquareTestDataSetsComparison(long[] observed1, long[] observed2) throws MathException {\n distribution = new ChiSquaredDistributionImpl((double) observed1.length - 1);\n return 1 - distribution.cumulativeProbability(chiSquareDataSetsComparison(observed1, observed2));\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n * @since 1.2\n */\n public boolean chiSquareTestDataSetsComparison(long[] observed1, long[] observed2, double alpha) throws MathException {\n if (alpha <= 0 || alpha > 0.5) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTestDataSetsComparison(observed1, observed2) < alpha;\n }\n\n /**\n * Checks to make sure that the input long[][] array is rectangular,\n * has at least 2 rows and 2 columns, and has all non-negative entries,\n * throwing MathIllegalArgumentException if any of these checks fail.\n *\n * @param in input 2-way table to check\n * @throws MathIllegalArgumentException if the array is not valid\n */\n private void checkArray(long[][] in) {\n if (in.length < 2) {\n throw new NumberIsTooSmallException(in.length, 2, true);\n }\n if (in[0].length < 2) {\n throw new NumberIsTooSmallException(in[0].length, 2, true);\n }\n checkRectangular(in);\n checkNonNegative(in);\n }\n\n // --------------------- Private array methods -- should find a utility home for these\n /**\n * Throws MathIllegalArgumentException if the input array is not rectangular.\n *\n * @param in array to be tested\n * @throws NullPointerException if input array is null\n * @throws MathIllegalArgumentException if input array is not rectangular\n */\n private void checkRectangular(long[][] in) {\n for (int i = 1; i < in.length; i++) {\n if (in[i].length != in[0].length) {\n throw new DimensionMismatchException(LocalizedFormats.DIFFERENT_ROWS_LENGTHS, in[i].length, in[0].length);\n }\n }\n }\n\n /**\n * Check all entries of the input array are strictly postive.\n *\n * @param in Array to be tested.\n * @exception NotStrictlyPositiveException if one entry is not positive.\n */\n private void checkPositive(double[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] <= 0) {\n throw new NotStrictlyPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] < 0) {\n throw new NotPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[][] in) {\n for (int i = 0; i < in.length; i++) {\n for (int j = 0; j < in[i].length; j++) {\n if (in[i][j] < 0) {\n throw new NotPositiveException(in[i][j]);\n }\n }\n }\n }\n\n /**\n * Modify the distribution used to compute inference statistics.\n *\n * @param value\n * the new distribution\n * @since 1.2\n */\n public void setDistribution(ChiSquaredDistribution value) {\n distribution = value;\n }\n}\n"} {"task_id": "Java_534", "language": "Java", "task_type": "for_statement", "source_file": "java/github/SpoonLabs/astor/examples/math_57/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java", "mask_start_position": 2503, "mask_end_position": 2636, "canonical_solution": "for (int i = 0; i < observed.length; i++) {\n sumExpected += expected[i];\n sumObserved += observed[i];\n }", "pre_mask_code": "package org.apache.commons.math.stat.inference;\n\nimport org.apache.commons.math.MathException;\nimport org.apache.commons.math.exception.NotPositiveException;\nimport org.apache.commons.math.exception.NotStrictlyPositiveException;\nimport org.apache.commons.math.exception.NumberIsTooSmallException;\nimport org.apache.commons.math.exception.OutOfRangeException;\nimport org.apache.commons.math.exception.DimensionMismatchException;\nimport org.apache.commons.math.exception.MathIllegalArgumentException;\nimport org.apache.commons.math.distribution.ChiSquaredDistribution;\nimport org.apache.commons.math.distribution.ChiSquaredDistributionImpl;\nimport org.apache.commons.math.exception.util.LocalizedFormats;\nimport org.apache.commons.math.util.FastMath;\n\n/**\n * Implements Chi-Square test statistics defined in the\n * {@link UnknownDistributionChiSquareTest} interface.\n *\n * @version $Revision$ $Date$\n */\npublic class ChiSquareTestImpl implements UnknownDistributionChiSquareTest {\n\n /**\n * Distribution used to compute inference statistics.\n */\n private ChiSquaredDistribution distribution;\n\n /**\n * Construct a ChiSquareTestImpl\n */\n public ChiSquareTestImpl() {\n this(new ChiSquaredDistributionImpl(1.0));\n }\n\n /**\n * Create a test instance using the given distribution for computing\n * inference statistics.\n * @param x distribution used to compute inference statistics.\n * @since 1.2\n */\n public ChiSquareTestImpl(ChiSquaredDistribution x) {\n super();\n setDistribution(x);\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return chi-square test statistic\n * @throws DimensionMismatchException if the arrays length is less than 2.\n */\n public double chiSquare(double[] expected, long[] observed) {\n if (expected.length < 2) {\n throw new DimensionMismatchException(expected.length, 2);\n }\n if (expected.length != observed.length) {\n throw new DimensionMismatchException(expected.length, observed.length);\n }\n checkPositive(expected);\n checkNonNegative(observed);\n double sumExpected = 0d;\n double sumObserved = 0d;\n ", "post_mask_code": "\n double ratio = 1.0d;\n boolean rescale = false;\n if (FastMath.abs(sumExpected - sumObserved) > 10E-6) {\n ratio = sumObserved / sumExpected;\n rescale = true;\n }\n double sumSq = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n if (rescale) {\n final double dev = observed[i] - ratio * expected[i];\n sumSq += dev * dev / (ratio * expected[i]);\n } else {\n final double dev = observed[i] - expected[i];\n sumSq += dev * dev / expected[i];\n }\n }\n return sumSq;\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(double[] expected, long[] observed) throws MathException {\n distribution = new ChiSquaredDistributionImpl(expected.length - 1.0);\n return 1.0 - distribution.cumulativeProbability(chiSquare(expected, observed));\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(double[] expected, long[] observed, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(expected, observed) < alpha;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met.\n */\n public double chiSquare(long[][] counts) {\n checkArray(counts);\n int nRows = counts.length;\n int nCols = counts[0].length;\n // compute row, column and total sums\n double[] rowSum = new double[nRows];\n double[] colSum = new double[nCols];\n double total = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n rowSum[row] += counts[row][col];\n colSum[col] += counts[row][col];\n total += counts[row][col];\n }\n }\n // compute expected counts and chi-square\n double sumSq = 0.0d;\n double expected = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n expected = (rowSum[row] * colSum[col]) / total;\n sumSq += ((counts[row][col] - expected) * (counts[row][col] - expected)) / expected;\n }\n }\n return sumSq;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(long[][] counts) throws MathException {\n checkArray(counts);\n double df = ((double) counts.length - 1) * ((double) counts[0].length - 1);\n distribution = new ChiSquaredDistributionImpl(df);\n return 1 - distribution.cumulativeProbability(chiSquare(counts));\n }\n\n /**\n * @param counts array representation of 2-way table\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(long[][] counts, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(counts) < alpha;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met\n * @since 1.2\n */\n public double chiSquareDataSetsComparison(long[] observed1, long[] observed2) {\n // Make sure lengths are same\n if (observed1.length < 2) {\n throw new DimensionMismatchException(observed1.length, 2);\n }\n if (observed1.length != observed2.length) {\n throw new DimensionMismatchException(observed1.length, observed2.length);\n }\n // Ensure non-negative counts\n checkNonNegative(observed1);\n checkNonNegative(observed2);\n // Compute and compare count sums\n long countSum1 = 0;\n long countSum2 = 0;\n boolean unequalCounts = false;\n double weight = 0.0;\n for (int i = 0; i < observed1.length; i++) {\n countSum1 += observed1[i];\n countSum2 += observed2[i];\n }\n // Ensure neither sample is uniformly 0\n if (countSum1 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 1);\n }\n if (countSum2 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 2);\n }\n // Compare and compute weight only if different\n unequalCounts = countSum1 != countSum2;\n if (unequalCounts) {\n weight = FastMath.sqrt((double) countSum1 / (double) countSum2);\n }\n // Compute ChiSquare statistic\n double sumSq = 0.0d;\n double dev = 0.0d;\n double obs1 = 0.0d;\n double obs2 = 0.0d;\n for (int i = 0; i < observed1.length; i++) {\n if (observed1[i] == 0 && observed2[i] == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY, i);\n } else {\n obs1 = observed1[i];\n obs2 = observed2[i];\n if (unequalCounts) {\n // apply weights\n dev = obs1 / weight - obs2 * weight;\n } else {\n dev = obs1 - obs2;\n }\n sumSq += (dev * dev) / (obs1 + obs2);\n }\n }\n return sumSq;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n * @since 1.2\n */\n public double chiSquareTestDataSetsComparison(long[] observed1, long[] observed2) throws MathException {\n distribution = new ChiSquaredDistributionImpl((double) observed1.length - 1);\n return 1 - distribution.cumulativeProbability(chiSquareDataSetsComparison(observed1, observed2));\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n * @since 1.2\n */\n public boolean chiSquareTestDataSetsComparison(long[] observed1, long[] observed2, double alpha) throws MathException {\n if (alpha <= 0 || alpha > 0.5) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTestDataSetsComparison(observed1, observed2) < alpha;\n }\n\n /**\n * Checks to make sure that the input long[][] array is rectangular,\n * has at least 2 rows and 2 columns, and has all non-negative entries,\n * throwing MathIllegalArgumentException if any of these checks fail.\n *\n * @param in input 2-way table to check\n * @throws MathIllegalArgumentException if the array is not valid\n */\n private void checkArray(long[][] in) {\n if (in.length < 2) {\n throw new NumberIsTooSmallException(in.length, 2, true);\n }\n if (in[0].length < 2) {\n throw new NumberIsTooSmallException(in[0].length, 2, true);\n }\n checkRectangular(in);\n checkNonNegative(in);\n }\n\n // --------------------- Private array methods -- should find a utility home for these\n /**\n * Throws MathIllegalArgumentException if the input array is not rectangular.\n *\n * @param in array to be tested\n * @throws NullPointerException if input array is null\n * @throws MathIllegalArgumentException if input array is not rectangular\n */\n private void checkRectangular(long[][] in) {\n for (int i = 1; i < in.length; i++) {\n if (in[i].length != in[0].length) {\n throw new DimensionMismatchException(LocalizedFormats.DIFFERENT_ROWS_LENGTHS, in[i].length, in[0].length);\n }\n }\n }\n\n /**\n * Check all entries of the input array are strictly postive.\n *\n * @param in Array to be tested.\n * @exception NotStrictlyPositiveException if one entry is not positive.\n */\n private void checkPositive(double[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] <= 0) {\n throw new NotStrictlyPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] < 0) {\n throw new NotPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[][] in) {\n for (int i = 0; i < in.length; i++) {\n for (int j = 0; j < in[i].length; j++) {\n if (in[i][j] < 0) {\n throw new NotPositiveException(in[i][j]);\n }\n }\n }\n }\n\n /**\n * Modify the distribution used to compute inference statistics.\n *\n * @param value\n * the new distribution\n * @since 1.2\n */\n public void setDistribution(ChiSquaredDistribution value) {\n distribution = value;\n }\n}\n"} {"task_id": "Java_535", "language": "Java", "task_type": "empty", "source_file": "java/github/SpoonLabs/astor/examples/math_57/src/main/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java", "mask_start_position": 9450, "mask_end_position": 9450, "canonical_solution": "", "pre_mask_code": "package org.apache.commons.math.stat.inference;\n\nimport org.apache.commons.math.MathException;\nimport org.apache.commons.math.exception.NotPositiveException;\nimport org.apache.commons.math.exception.NotStrictlyPositiveException;\nimport org.apache.commons.math.exception.NumberIsTooSmallException;\nimport org.apache.commons.math.exception.OutOfRangeException;\nimport org.apache.commons.math.exception.DimensionMismatchException;\nimport org.apache.commons.math.exception.MathIllegalArgumentException;\nimport org.apache.commons.math.distribution.ChiSquaredDistribution;\nimport org.apache.commons.math.distribution.ChiSquaredDistributionImpl;\nimport org.apache.commons.math.exception.util.LocalizedFormats;\nimport org.apache.commons.math.util.FastMath;\n\n/**\n * Implements Chi-Square test statistics defined in the\n * {@link UnknownDistributionChiSquareTest} interface.\n *\n * @version $Revision$ $Date$\n */\npublic class ChiSquareTestImpl implements UnknownDistributionChiSquareTest {\n\n /**\n * Distribution used to compute inference statistics.\n */\n private ChiSquaredDistribution distribution;\n\n /**\n * Construct a ChiSquareTestImpl\n */\n public ChiSquareTestImpl() {\n this(new ChiSquaredDistributionImpl(1.0));\n }\n\n /**\n * Create a test instance using the given distribution for computing\n * inference statistics.\n * @param x distribution used to compute inference statistics.\n * @since 1.2\n */\n public ChiSquareTestImpl(ChiSquaredDistribution x) {\n super();\n setDistribution(x);\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return chi-square test statistic\n * @throws DimensionMismatchException if the arrays length is less than 2.\n */\n public double chiSquare(double[] expected, long[] observed) {\n if (expected.length < 2) {\n throw new DimensionMismatchException(expected.length, 2);\n }\n if (expected.length != observed.length) {\n throw new DimensionMismatchException(expected.length, observed.length);\n }\n checkPositive(expected);\n checkNonNegative(observed);\n double sumExpected = 0d;\n double sumObserved = 0d;\n for (int i = 0; i < observed.length; i++) {\n sumExpected += expected[i];\n sumObserved += observed[i];\n }\n double ratio = 1.0d;\n boolean rescale = false;\n if (FastMath.abs(sumExpected - sumObserved) > 10E-6) {\n ratio = sumObserved / sumExpected;\n rescale = true;\n }\n double sumSq = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n if (rescale) {\n final double dev = observed[i] - ratio * expected[i];\n sumSq += dev * dev / (ratio * expected[i]);\n } else {\n final double dev = observed[i] - expected[i];\n sumSq += dev * dev / expected[i];\n }\n }\n return sumSq;\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(double[] expected, long[] observed) throws MathException {\n distribution = new ChiSquaredDistributionImpl(expected.length - 1.0);\n return 1.0 - distribution.cumulativeProbability(chiSquare(expected, observed));\n }\n\n /**\n * {@inheritDoc}\n *

Note: This implementation rescales the\n * expected array if necessary to ensure that the sum of the\n * expected and observed counts are equal.

\n *\n * @param observed array of observed frequency counts\n * @param expected array of expected frequency counts\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(double[] expected, long[] observed, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(expected, observed) < alpha;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met.\n */\n public double chiSquare(long[][] counts) {\n checkArray(counts);\n int nRows = counts.length;\n int nCols = counts[0].length;\n // compute row, column and total sums\n double[] rowSum = new double[nRows];\n double[] colSum = new double[nCols];\n double total = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n rowSum[row] += counts[row][col];\n colSum[col] += counts[row][col];\n total += counts[row][col];\n }\n }\n // compute expected counts and chi-square\n double sumSq = 0.0d;\n double expected = 0.0d;\n for (int row = 0; row < nRows; row++) {\n for (int col = 0; col < nCols; col++) {\n expected = (rowSum[row] * colSum[col]) / total;\n sumSq += ((counts[row][col] - expected) * (counts[row][col] - expected)) / expected;\n }\n }\n return sumSq;\n }\n\n /**\n * @param counts array representation of 2-way table\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n */\n public double chiSquareTest(long[][] counts) throws MathException {\n checkArray(counts);\n double df = ((double) counts.length - 1) * ((double) counts[0].length - 1);\n distribution = new ChiSquaredDistributionImpl(df);\n return 1 - distribution.cumulativeProbability(chiSquare(counts));\n }\n\n /**\n * @param counts array representation of 2-way table\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n */\n public boolean chiSquareTest(long[][] counts, double alpha) throws MathException {\n if ((alpha <= 0) || (alpha > 0.5)) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTest(counts) < alpha;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return chi-square test statistic\n * @throws MathIllegalArgumentException if preconditions are not met\n * @since 1.2\n */\n public double chiSquareDataSetsComparison(long[] observed1, long[] observed2) {\n // Make sure lengths are same\n if (observed1.length < 2) {\n throw new DimensionMismatchException(observed1.length, 2);\n }\n if (observed1.length != observed2.length) {\n throw new DimensionMismatchException(observed1.length, observed2.length);\n }\n // Ensure non-negative counts\n checkNonNegative(observed1);\n checkNonNegative(observed2);\n // Compute and compare count sums\n long countSum1 = 0;\n long countSum2 = 0;\n boolean unequalCounts = false;\n double weight = 0.0;\n for (int i = 0; i < observed1.length; i++) {\n countSum1 += observed1[i];\n countSum2 += observed2[i];\n }\n // Ensure neither sample is uniformly 0\n if (countSum1 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 1);\n }\n if (countSum2 == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO, 2);\n }\n // Compare and compute weight only if different\n unequalCounts = countSum1 != countSum2;\n if (unequalCounts) {\n weight = FastMath.sqrt((double) countSum1 / (double) countSum2);\n }\n // Compute ChiSquare statistic\n double sumSq = 0.0d;\n double dev = 0.0d;\n double obs1 = 0.0d;\n double obs2 = 0.0d;\n for (int i = 0; i < observed1.length; i++) {\n if (observed1[i] == 0 && observed2[i] == 0) {\n throw new MathIllegalArgumentException(LocalizedFormats.OBSERVED_COUNT", "post_mask_code": "S_BOTTH_ZERO_FOR_ENTRY, i);\n } else {\n obs1 = observed1[i];\n obs2 = observed2[i];\n if (unequalCounts) {\n // apply weights\n dev = obs1 / weight - obs2 * weight;\n } else {\n dev = obs1 - obs2;\n }\n sumSq += (dev * dev) / (obs1 + obs2);\n }\n }\n return sumSq;\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @return p-value\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs computing the p-value\n * @since 1.2\n */\n public double chiSquareTestDataSetsComparison(long[] observed1, long[] observed2) throws MathException {\n distribution = new ChiSquaredDistributionImpl((double) observed1.length - 1);\n return 1 - distribution.cumulativeProbability(chiSquareDataSetsComparison(observed1, observed2));\n }\n\n /**\n * @param observed1 array of observed frequency counts of the first data set\n * @param observed2 array of observed frequency counts of the second data set\n * @param alpha significance level of the test\n * @return true iff null hypothesis can be rejected with confidence\n * 1 - alpha\n * @throws MathIllegalArgumentException if preconditions are not met\n * @throws MathException if an error occurs performing the test\n * @since 1.2\n */\n public boolean chiSquareTestDataSetsComparison(long[] observed1, long[] observed2, double alpha) throws MathException {\n if (alpha <= 0 || alpha > 0.5) {\n throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL, alpha, 0, 0.5);\n }\n return chiSquareTestDataSetsComparison(observed1, observed2) < alpha;\n }\n\n /**\n * Checks to make sure that the input long[][] array is rectangular,\n * has at least 2 rows and 2 columns, and has all non-negative entries,\n * throwing MathIllegalArgumentException if any of these checks fail.\n *\n * @param in input 2-way table to check\n * @throws MathIllegalArgumentException if the array is not valid\n */\n private void checkArray(long[][] in) {\n if (in.length < 2) {\n throw new NumberIsTooSmallException(in.length, 2, true);\n }\n if (in[0].length < 2) {\n throw new NumberIsTooSmallException(in[0].length, 2, true);\n }\n checkRectangular(in);\n checkNonNegative(in);\n }\n\n // --------------------- Private array methods -- should find a utility home for these\n /**\n * Throws MathIllegalArgumentException if the input array is not rectangular.\n *\n * @param in array to be tested\n * @throws NullPointerException if input array is null\n * @throws MathIllegalArgumentException if input array is not rectangular\n */\n private void checkRectangular(long[][] in) {\n for (int i = 1; i < in.length; i++) {\n if (in[i].length != in[0].length) {\n throw new DimensionMismatchException(LocalizedFormats.DIFFERENT_ROWS_LENGTHS, in[i].length, in[0].length);\n }\n }\n }\n\n /**\n * Check all entries of the input array are strictly postive.\n *\n * @param in Array to be tested.\n * @exception NotStrictlyPositiveException if one entry is not positive.\n */\n private void checkPositive(double[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] <= 0) {\n throw new NotStrictlyPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[] in) {\n for (int i = 0; i < in.length; i++) {\n if (in[i] < 0) {\n throw new NotPositiveException(in[i]);\n }\n }\n }\n\n /**\n * Check all entries of the input array are >= 0.\n *\n * @param in Array to be tested.\n * @exception NotPositiveException if one entry is negative.\n */\n private void checkNonNegative(long[][] in) {\n for (int i = 0; i < in.length; i++) {\n for (int j = 0; j < in[i].length; j++) {\n if (in[i][j] < 0) {\n throw new NotPositiveException(in[i][j]);\n }\n }\n }\n }\n\n /**\n * Modify the distribution used to compute inference statistics.\n *\n * @param value\n * the new distribution\n * @since 1.2\n */\n public void setDistribution(ChiSquaredDistribution value) {\n distribution = value;\n }\n}\n"} {"task_id": "Java_536", "language": "Java", "task_type": "method_signature", "source_file": "java/github/YANG-DB/yang-db/fuse-model/src/main/java/com/yangdb/fuse/model/resourceInfo/ResourceInfoBase.java", "mask_start_position": 400, "mask_end_position": 431, "canonical_solution": "public String getResourceUrl() ", "pre_mask_code": "package com.yangdb.fuse.model.resourceInfo;\n\n/**\n * Created by lior.perry on 09/03/2017.\n */\npublic abstract class ResourceInfoBase {\n\n // region Constructor\n public ResourceInfoBase() {\n }\n\n public ResourceInfoBase(String resourceUrl, String resourceId) {\n this.resourceUrl = resourceUrl;\n this.resourceId = resourceId;\n }\n\n // endregion\n // region properties\n ", "post_mask_code": "{\n return this.resourceUrl;\n }\n\n public String getResourceId() {\n return resourceId;\n }\n\n public void setResourceUrl(String resourceUrl) {\n this.resourceUrl = resourceUrl;\n }\n\n public void setResourceId(String resourceId) {\n this.resourceId = resourceId;\n }\n\n // endregion\n // region Fields\n private String resourceUrl;\n\n private String resourceId;\n // endregion\n}\n"} {"task_id": "Java_537", "language": "Java", "task_type": "method_body", "source_file": "java/github/YANG-DB/yang-db/fuse-model/src/main/java/com/yangdb/fuse/model/resourceInfo/ResourceInfoBase.java", "mask_start_position": 594, "mask_end_position": 641, "canonical_solution": "{\n this.resourceUrl = resourceUrl;\n }", "pre_mask_code": "package com.yangdb.fuse.model.resourceInfo;\n\n/**\n * Created by lior.perry on 09/03/2017.\n */\npublic abstract class ResourceInfoBase {\n\n // region Constructor\n public ResourceInfoBase() {\n }\n\n public ResourceInfoBase(String resourceUrl, String resourceId) {\n this.resourceUrl = resourceUrl;\n this.resourceId = resourceId;\n }\n\n // endregion\n // region properties\n public String getResourceUrl() {\n return this.resourceUrl;\n }\n\n public String getResourceId() {\n return resourceId;\n }\n\n public void setResourceUrl(String resourceUrl) ", "post_mask_code": "\n\n public void setResourceId(String resourceId) {\n this.resourceId = resourceId;\n }\n\n // endregion\n // region Fields\n private String resourceUrl;\n\n private String resourceId;\n // endregion\n}\n"} {"task_id": "Java_538", "language": "Java", "task_type": "single_line", "source_file": "java/github/YANG-DB/yang-db/fuse-model/src/main/java/com/yangdb/fuse/model/resourceInfo/ResourceInfoBase.java", "mask_start_position": 634, "mask_end_position": 635, "canonical_solution": ";", "pre_mask_code": "package com.yangdb.fuse.model.resourceInfo;\n\n/**\n * Created by lior.perry on 09/03/2017.\n */\npublic abstract class ResourceInfoBase {\n\n // region Constructor\n public ResourceInfoBase() {\n }\n\n public ResourceInfoBase(String resourceUrl, String resourceId) {\n this.resourceUrl = resourceUrl;\n this.resourceId = resourceId;\n }\n\n // endregion\n // region properties\n public String getResourceUrl() {\n return this.resourceUrl;\n }\n\n public String getResourceId() {\n return resourceId;\n }\n\n public void setResourceUrl(String resourceUrl) {\n this.resourceUrl = resourceUrl", "post_mask_code": "\n }\n\n public void setResourceId(String resourceId) {\n this.resourceId = resourceId;\n }\n\n // endregion\n // region Fields\n private String resourceUrl;\n\n private String resourceId;\n // endregion\n}\n"} {"task_id": "Java_539", "language": "Java", "task_type": "empty", "source_file": "java/github/YANG-DB/yang-db/fuse-model/src/main/java/com/yangdb/fuse/model/resourceInfo/ResourceInfoBase.java", "mask_start_position": 543, "mask_end_position": 543, "canonical_solution": "", "pre_mask_code": "package com.yangdb.fuse.model.resourceInfo;\n\n/**\n * Created by lior.perry on 09/03/2017.\n */\npublic abstract class ResourceInfoBase {\n\n // region Constructor\n public ResourceInfoBase() {\n }\n\n public ResourceInfoBase(String resourceUrl, String resourceId) {\n this.resourceUrl = resourceUrl;\n this.resourceId = resourceId;\n }\n\n // endregion\n // region properties\n public String getResourceUrl() {\n return this.resourceUrl;\n }\n\n public String getResourceId() {\n return resourceId;\n }\n\n", "post_mask_code": " public void setResourceUrl(String resourceUrl) {\n this.resourceUrl = resourceUrl;\n }\n\n public void setResourceId(String resourceId) {\n this.resourceId = resourceId;\n }\n\n // endregion\n // region Fields\n private String resourceUrl;\n\n private String resourceId;\n // endregion\n}\n"} {"task_id": "Java_540", "language": "Java", "task_type": "method_signature", "source_file": "java/github/CyanogenMod/android_packages_apps_Gallery2/src/com/android/gallery3d/filtershow/imageshow/ImageCrop.java", "mask_start_position": 8276, "mask_end_position": 8324, "canonical_solution": "@Override\n public void onDraw(Canvas canvas) ", "pre_mask_code": "package com.android.gallery3d.filtershow.imageshow;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.RectF;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport com.android.gallery3d.R;\nimport com.android.gallery3d.filtershow.crop.CropDrawingUtils;\nimport com.android.gallery3d.filtershow.crop.CropMath;\nimport com.android.gallery3d.filtershow.crop.CropObject;\nimport com.android.gallery3d.filtershow.editors.EditorCrop;\nimport com.android.gallery3d.filtershow.filters.FilterCropRepresentation;\nimport com.android.gallery3d.filtershow.imageshow.GeometryMathUtils.GeometryHolder;\n\npublic class ImageCrop extends ImageShow {\n\n private static final String TAG = ImageCrop.class.getSimpleName();\n\n private RectF mImageBounds = new RectF();\n\n private RectF mScreenCropBounds = new RectF();\n\n private Paint mPaint = new Paint();\n\n private CropObject mCropObj = null;\n\n private GeometryHolder mGeometry = new GeometryHolder();\n\n private GeometryHolder mUpdateHolder = new GeometryHolder();\n\n private Drawable mCropIndicator;\n\n private int mIndicatorSize;\n\n private boolean mMovingBlock = false;\n\n private Matrix mDisplayMatrix = null;\n\n private Matrix mDisplayCropMatrix = null;\n\n private Matrix mDisplayMatrixInverse = null;\n\n private float mPrevX = 0;\n\n private float mPrevY = 0;\n\n private int mMinSideSize = 90;\n\n private int mTouchTolerance = 40;\n\n private enum Mode {\n\n NONE, MOVE\n }\n\n private Mode mState = Mode.NONE;\n\n private boolean mValidDraw = false;\n\n FilterCropRepresentation mLocalRep = new FilterCropRepresentation();\n\n EditorCrop mEditorCrop;\n\n public ImageCrop(Context context) {\n super(context);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs) {\n super(context, attrs);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setup(context);\n }\n\n private void setup(Context context) {\n Resources rsc = context.getResources();\n mCropIndicator = rsc.getDrawable(R.drawable.camera_crop);\n mIndicatorSize = (int) rsc.getDimension(R.dimen.crop_indicator_size);\n mMinSideSize = (int) rsc.getDimension(R.dimen.crop_min_side);\n mTouchTolerance = (int) rsc.getDimension(R.dimen.crop_touch_tolerance);\n }\n\n public void setFilterCropRepresentation(FilterCropRepresentation crop) {\n mLocalRep = (crop == null) ? new FilterCropRepresentation() : crop;\n GeometryMathUtils.initializeHolder(mUpdateHolder, mLocalRep);\n mValidDraw = true;\n }\n\n public FilterCropRepresentation getFinalRepresentation() {\n return mLocalRep;\n }\n\n private void internallyUpdateLocalRep(RectF crop, RectF image) {\n FilterCropRepresentation.findNormalizedCrop(crop, (int) image.width(), (int) image.height());\n mGeometry.crop.set(crop);\n mUpdateHolder.set(mGeometry);\n mLocalRep.setCrop(crop);\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n float x = event.getX();\n float y = event.getY();\n if (mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n return true;\n }\n float[] touchPoint = { x, y };\n mDisplayMatrixInverse.mapPoints(touchPoint);\n x = touchPoint[0];\n y = touchPoint[1];\n switch(event.getActionMasked()) {\n case (MotionEvent.ACTION_DOWN):\n if (mState == Mode.NONE) {\n if (!mCropObj.selectEdge(x, y)) {\n mMovingBlock = mCropObj.selectEdge(CropObject.MOVE_BLOCK);\n }\n mPrevX = x;\n mPrevY = y;\n mState = Mode.MOVE;\n }\n break;\n case (MotionEvent.ACTION_UP):\n if (mState == Mode.MOVE) {\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n mMovingBlock = false;\n mPrevX = x;\n mPrevY = y;\n mState = Mode.NONE;\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n }\n break;\n case (MotionEvent.ACTION_MOVE):\n if (mState == Mode.MOVE) {\n float dx = x - mPrevX;\n float dy = y - mPrevY;\n mCropObj.moveCurrentSelection(dx, dy);\n mPrevX = x;\n mPrevY = y;\n }\n break;\n default:\n break;\n }\n invalidate();\n return true;\n }\n\n private void clearDisplay() {\n mDisplayMatrix = null;\n mDisplayMatrixInverse = null;\n invalidate();\n }\n\n public void applyFreeAspect() {\n mCropObj.unsetAspectRatio();\n invalidate();\n }\n\n public void applyOriginalAspect() {\n RectF outer = mCropObj.getOuterBounds();\n float w = outer.width();\n float h = outer.height();\n if (w > 0 && h > 0) {\n applyAspect(w, h);\n mCropObj.resetBoundsTo(outer, outer);\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n } else {\n Log.w(TAG, \"failed to set aspect ratio original\");\n }\n invalidate();\n }\n\n public void applyAspect(float x, float y) {\n if (x <= 0 || y <= 0) {\n throw new IllegalArgumentException(\"Bad arguments to applyAspect\");\n }\n // If we are rotated by 90 degrees from horizontal, swap x and y\n if (GeometryMathUtils.needsDimensionSwap(mGeometry.rotation)) {\n float tmp = x;\n x = y;\n y = tmp;\n }\n if (!mCropObj.setInnerAspectRatio(x, y)) {\n Log.w(TAG, \"failed to set aspect ratio\");\n }\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n invalidate();\n }\n\n /**\n * Rotates first d bits in integer x to the left some number of times.\n */\n private int bitCycleLeft(int x, int times, int d) {\n int mask = (1 << d) - 1;\n int mout = x & mask;\n times %= d;\n int hi = mout >> (d - times);\n int low = (mout << times) & mask;\n int ret = x & ~mask;\n ret |= low;\n ret |= hi;\n return ret;\n }\n\n /**\n * Find the selected edge or corner in screen coordinates.\n */\n private int decode(int movingEdges, float rotation) {\n int rot = CropMath.constrainedRotation(rotation);\n switch(rot) {\n case 90:\n return bitCycleLeft(movingEdges, 1, 4);\n case 180:\n return bitCycleLeft(movingEdges, 2, 4);\n case 270:\n return bitCycleLeft(movingEdges, 3, 4);\n default:\n return movingEdges;\n }\n }\n\n private void forceStateConsistency() {\n MasterImage master = MasterImage.getImage();\n Bitmap image = master.getFiltersOnlyImage();\n int width = image.getWidth();\n int height = image.getHeight();\n if (mCropObj == null || !mUpdateHolder.equals(mGeometry) || mImageBounds.width() != width || mImageBounds.height() != height || !mLocalRep.getCrop().equals(mUpdateHolder.crop)) {\n mImageBounds.set(0, 0, width, height);\n mGeometry.set(mUpdateHolder);\n mLocalRep.setCrop(mUpdateHolder.crop);\n RectF scaledCrop = new RectF(mUpdateHolder.crop);\n FilterCropRepresentation.findScaledCrop(scaledCrop, width, height);\n mCropObj = new CropObject(mImageBounds, scaledCrop, (int) mUpdateHolder.straighten);\n mState = Mode.NONE;\n clearDisplay();\n }\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n clearDisplay();\n }\n\n ", "post_mask_code": "{\n Bitmap bitmap = MasterImage.getImage().getFiltersOnlyImage();\n if (bitmap == null) {\n MasterImage.getImage().invalidateFiltersOnly();\n }\n if (!mValidDraw || bitmap == null) {\n return;\n }\n forceStateConsistency();\n mImageBounds.set(0, 0, bitmap.getWidth(), bitmap.getHeight());\n // If display matrix doesn't exist, create it and its dependencies\n if (mDisplayCropMatrix == null || mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n mCropObj.unsetAspectRatio();\n mDisplayMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n float straighten = mGeometry.straighten;\n mGeometry.straighten = 0;\n mDisplayCropMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n mGeometry.straighten = straighten;\n mDisplayMatrixInverse = new Matrix();\n mDisplayMatrixInverse.reset();\n if (!mDisplayCropMatrix.invert(mDisplayMatrixInverse)) {\n Log.w(TAG, \"could not invert display matrix\");\n mDisplayMatrixInverse = null;\n return;\n }\n // Scale min side and tolerance by display matrix scale factor\n mCropObj.setMinInnerSideSize(mDisplayMatrixInverse.mapRadius(mMinSideSize));\n mCropObj.setTouchTolerance(mDisplayMatrixInverse.mapRadius(mTouchTolerance));\n // drive Crop engine to clamp to crop bounds\n int[] sides = { CropObject.MOVE_TOP, CropObject.MOVE_BOTTOM, CropObject.MOVE_LEFT, CropObject.MOVE_RIGHT };\n int delta = Math.min(canvas.getWidth(), canvas.getHeight()) / 4;\n int[] dx = { delta, -delta, 0, 0 };\n int[] dy = { 0, 0, delta, -delta };\n for (int i = 0; i < sides.length; i++) {\n mCropObj.selectEdge(sides[i]);\n mCropObj.moveCurrentSelection(dx[i], dy[i]);\n mCropObj.moveCurrentSelection(-dx[i], -dy[i]);\n }\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n }\n // Draw actual bitmap\n mPaint.reset();\n mPaint.setAntiAlias(true);\n mPaint.setFilterBitmap(true);\n canvas.drawBitmap(bitmap, mDisplayMatrix, mPaint);\n mCropObj.getInnerBounds(mScreenCropBounds);\n RectF outer = mCropObj.getOuterBounds();\n FilterCropRepresentation.findNormalizedCrop(mScreenCropBounds, (int) outer.width(), (int) outer.height());\n FilterCropRepresentation.findScaledCrop(mScreenCropBounds, bitmap.getWidth(), bitmap.getHeight());\n if (mDisplayCropMatrix.mapRect(mScreenCropBounds)) {\n // Draw crop rect and markers\n CropDrawingUtils.drawCropRect(canvas, mScreenCropBounds);\n CropDrawingUtils.drawShade(canvas, mScreenCropBounds);\n CropDrawingUtils.drawRuleOfThird(canvas, mScreenCropBounds);\n CropDrawingUtils.drawIndicators(canvas, mCropIndicator, mIndicatorSize, mScreenCropBounds, mCropObj.isFixedAspect(), decode(mCropObj.getSelectState(), mGeometry.rotation.value()));\n }\n }\n\n public void setEditor(EditorCrop editorCrop) {\n mEditorCrop = editorCrop;\n }\n}\n"} {"task_id": "Java_541", "language": "Java", "task_type": "method_body", "source_file": "java/github/CyanogenMod/android_packages_apps_Gallery2/src/com/android/gallery3d/filtershow/imageshow/ImageCrop.java", "mask_start_position": 2294, "mask_end_position": 2643, "canonical_solution": "{\n Resources rsc = context.getResources();\n mCropIndicator = rsc.getDrawable(R.drawable.camera_crop);\n mIndicatorSize = (int) rsc.getDimension(R.dimen.crop_indicator_size);\n mMinSideSize = (int) rsc.getDimension(R.dimen.crop_min_side);\n mTouchTolerance = (int) rsc.getDimension(R.dimen.crop_touch_tolerance);\n }", "pre_mask_code": "package com.android.gallery3d.filtershow.imageshow;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.RectF;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport com.android.gallery3d.R;\nimport com.android.gallery3d.filtershow.crop.CropDrawingUtils;\nimport com.android.gallery3d.filtershow.crop.CropMath;\nimport com.android.gallery3d.filtershow.crop.CropObject;\nimport com.android.gallery3d.filtershow.editors.EditorCrop;\nimport com.android.gallery3d.filtershow.filters.FilterCropRepresentation;\nimport com.android.gallery3d.filtershow.imageshow.GeometryMathUtils.GeometryHolder;\n\npublic class ImageCrop extends ImageShow {\n\n private static final String TAG = ImageCrop.class.getSimpleName();\n\n private RectF mImageBounds = new RectF();\n\n private RectF mScreenCropBounds = new RectF();\n\n private Paint mPaint = new Paint();\n\n private CropObject mCropObj = null;\n\n private GeometryHolder mGeometry = new GeometryHolder();\n\n private GeometryHolder mUpdateHolder = new GeometryHolder();\n\n private Drawable mCropIndicator;\n\n private int mIndicatorSize;\n\n private boolean mMovingBlock = false;\n\n private Matrix mDisplayMatrix = null;\n\n private Matrix mDisplayCropMatrix = null;\n\n private Matrix mDisplayMatrixInverse = null;\n\n private float mPrevX = 0;\n\n private float mPrevY = 0;\n\n private int mMinSideSize = 90;\n\n private int mTouchTolerance = 40;\n\n private enum Mode {\n\n NONE, MOVE\n }\n\n private Mode mState = Mode.NONE;\n\n private boolean mValidDraw = false;\n\n FilterCropRepresentation mLocalRep = new FilterCropRepresentation();\n\n EditorCrop mEditorCrop;\n\n public ImageCrop(Context context) {\n super(context);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs) {\n super(context, attrs);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setup(context);\n }\n\n private void setup(Context context) ", "post_mask_code": "\n\n public void setFilterCropRepresentation(FilterCropRepresentation crop) {\n mLocalRep = (crop == null) ? new FilterCropRepresentation() : crop;\n GeometryMathUtils.initializeHolder(mUpdateHolder, mLocalRep);\n mValidDraw = true;\n }\n\n public FilterCropRepresentation getFinalRepresentation() {\n return mLocalRep;\n }\n\n private void internallyUpdateLocalRep(RectF crop, RectF image) {\n FilterCropRepresentation.findNormalizedCrop(crop, (int) image.width(), (int) image.height());\n mGeometry.crop.set(crop);\n mUpdateHolder.set(mGeometry);\n mLocalRep.setCrop(crop);\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n float x = event.getX();\n float y = event.getY();\n if (mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n return true;\n }\n float[] touchPoint = { x, y };\n mDisplayMatrixInverse.mapPoints(touchPoint);\n x = touchPoint[0];\n y = touchPoint[1];\n switch(event.getActionMasked()) {\n case (MotionEvent.ACTION_DOWN):\n if (mState == Mode.NONE) {\n if (!mCropObj.selectEdge(x, y)) {\n mMovingBlock = mCropObj.selectEdge(CropObject.MOVE_BLOCK);\n }\n mPrevX = x;\n mPrevY = y;\n mState = Mode.MOVE;\n }\n break;\n case (MotionEvent.ACTION_UP):\n if (mState == Mode.MOVE) {\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n mMovingBlock = false;\n mPrevX = x;\n mPrevY = y;\n mState = Mode.NONE;\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n }\n break;\n case (MotionEvent.ACTION_MOVE):\n if (mState == Mode.MOVE) {\n float dx = x - mPrevX;\n float dy = y - mPrevY;\n mCropObj.moveCurrentSelection(dx, dy);\n mPrevX = x;\n mPrevY = y;\n }\n break;\n default:\n break;\n }\n invalidate();\n return true;\n }\n\n private void clearDisplay() {\n mDisplayMatrix = null;\n mDisplayMatrixInverse = null;\n invalidate();\n }\n\n public void applyFreeAspect() {\n mCropObj.unsetAspectRatio();\n invalidate();\n }\n\n public void applyOriginalAspect() {\n RectF outer = mCropObj.getOuterBounds();\n float w = outer.width();\n float h = outer.height();\n if (w > 0 && h > 0) {\n applyAspect(w, h);\n mCropObj.resetBoundsTo(outer, outer);\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n } else {\n Log.w(TAG, \"failed to set aspect ratio original\");\n }\n invalidate();\n }\n\n public void applyAspect(float x, float y) {\n if (x <= 0 || y <= 0) {\n throw new IllegalArgumentException(\"Bad arguments to applyAspect\");\n }\n // If we are rotated by 90 degrees from horizontal, swap x and y\n if (GeometryMathUtils.needsDimensionSwap(mGeometry.rotation)) {\n float tmp = x;\n x = y;\n y = tmp;\n }\n if (!mCropObj.setInnerAspectRatio(x, y)) {\n Log.w(TAG, \"failed to set aspect ratio\");\n }\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n invalidate();\n }\n\n /**\n * Rotates first d bits in integer x to the left some number of times.\n */\n private int bitCycleLeft(int x, int times, int d) {\n int mask = (1 << d) - 1;\n int mout = x & mask;\n times %= d;\n int hi = mout >> (d - times);\n int low = (mout << times) & mask;\n int ret = x & ~mask;\n ret |= low;\n ret |= hi;\n return ret;\n }\n\n /**\n * Find the selected edge or corner in screen coordinates.\n */\n private int decode(int movingEdges, float rotation) {\n int rot = CropMath.constrainedRotation(rotation);\n switch(rot) {\n case 90:\n return bitCycleLeft(movingEdges, 1, 4);\n case 180:\n return bitCycleLeft(movingEdges, 2, 4);\n case 270:\n return bitCycleLeft(movingEdges, 3, 4);\n default:\n return movingEdges;\n }\n }\n\n private void forceStateConsistency() {\n MasterImage master = MasterImage.getImage();\n Bitmap image = master.getFiltersOnlyImage();\n int width = image.getWidth();\n int height = image.getHeight();\n if (mCropObj == null || !mUpdateHolder.equals(mGeometry) || mImageBounds.width() != width || mImageBounds.height() != height || !mLocalRep.getCrop().equals(mUpdateHolder.crop)) {\n mImageBounds.set(0, 0, width, height);\n mGeometry.set(mUpdateHolder);\n mLocalRep.setCrop(mUpdateHolder.crop);\n RectF scaledCrop = new RectF(mUpdateHolder.crop);\n FilterCropRepresentation.findScaledCrop(scaledCrop, width, height);\n mCropObj = new CropObject(mImageBounds, scaledCrop, (int) mUpdateHolder.straighten);\n mState = Mode.NONE;\n clearDisplay();\n }\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n clearDisplay();\n }\n\n @Override\n public void onDraw(Canvas canvas) {\n Bitmap bitmap = MasterImage.getImage().getFiltersOnlyImage();\n if (bitmap == null) {\n MasterImage.getImage().invalidateFiltersOnly();\n }\n if (!mValidDraw || bitmap == null) {\n return;\n }\n forceStateConsistency();\n mImageBounds.set(0, 0, bitmap.getWidth(), bitmap.getHeight());\n // If display matrix doesn't exist, create it and its dependencies\n if (mDisplayCropMatrix == null || mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n mCropObj.unsetAspectRatio();\n mDisplayMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n float straighten = mGeometry.straighten;\n mGeometry.straighten = 0;\n mDisplayCropMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n mGeometry.straighten = straighten;\n mDisplayMatrixInverse = new Matrix();\n mDisplayMatrixInverse.reset();\n if (!mDisplayCropMatrix.invert(mDisplayMatrixInverse)) {\n Log.w(TAG, \"could not invert display matrix\");\n mDisplayMatrixInverse = null;\n return;\n }\n // Scale min side and tolerance by display matrix scale factor\n mCropObj.setMinInnerSideSize(mDisplayMatrixInverse.mapRadius(mMinSideSize));\n mCropObj.setTouchTolerance(mDisplayMatrixInverse.mapRadius(mTouchTolerance));\n // drive Crop engine to clamp to crop bounds\n int[] sides = { CropObject.MOVE_TOP, CropObject.MOVE_BOTTOM, CropObject.MOVE_LEFT, CropObject.MOVE_RIGHT };\n int delta = Math.min(canvas.getWidth(), canvas.getHeight()) / 4;\n int[] dx = { delta, -delta, 0, 0 };\n int[] dy = { 0, 0, delta, -delta };\n for (int i = 0; i < sides.length; i++) {\n mCropObj.selectEdge(sides[i]);\n mCropObj.moveCurrentSelection(dx[i], dy[i]);\n mCropObj.moveCurrentSelection(-dx[i], -dy[i]);\n }\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n }\n // Draw actual bitmap\n mPaint.reset();\n mPaint.setAntiAlias(true);\n mPaint.setFilterBitmap(true);\n canvas.drawBitmap(bitmap, mDisplayMatrix, mPaint);\n mCropObj.getInnerBounds(mScreenCropBounds);\n RectF outer = mCropObj.getOuterBounds();\n FilterCropRepresentation.findNormalizedCrop(mScreenCropBounds, (int) outer.width(), (int) outer.height());\n FilterCropRepresentation.findScaledCrop(mScreenCropBounds, bitmap.getWidth(), bitmap.getHeight());\n if (mDisplayCropMatrix.mapRect(mScreenCropBounds)) {\n // Draw crop rect and markers\n CropDrawingUtils.drawCropRect(canvas, mScreenCropBounds);\n CropDrawingUtils.drawShade(canvas, mScreenCropBounds);\n CropDrawingUtils.drawRuleOfThird(canvas, mScreenCropBounds);\n CropDrawingUtils.drawIndicators(canvas, mCropIndicator, mIndicatorSize, mScreenCropBounds, mCropObj.isFixedAspect(), decode(mCropObj.getSelectState(), mGeometry.rotation.value()));\n }\n }\n\n public void setEditor(EditorCrop editorCrop) {\n mEditorCrop = editorCrop;\n }\n}\n"} {"task_id": "Java_542", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/CyanogenMod/android_packages_apps_Gallery2/src/com/android/gallery3d/filtershow/imageshow/ImageCrop.java", "mask_start_position": 5246, "mask_end_position": 5328, "canonical_solution": "\n RectF outer = mCropObj.getOuterBounds();\n float w = outer.width();", "pre_mask_code": "package com.android.gallery3d.filtershow.imageshow;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.RectF;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport com.android.gallery3d.R;\nimport com.android.gallery3d.filtershow.crop.CropDrawingUtils;\nimport com.android.gallery3d.filtershow.crop.CropMath;\nimport com.android.gallery3d.filtershow.crop.CropObject;\nimport com.android.gallery3d.filtershow.editors.EditorCrop;\nimport com.android.gallery3d.filtershow.filters.FilterCropRepresentation;\nimport com.android.gallery3d.filtershow.imageshow.GeometryMathUtils.GeometryHolder;\n\npublic class ImageCrop extends ImageShow {\n\n private static final String TAG = ImageCrop.class.getSimpleName();\n\n private RectF mImageBounds = new RectF();\n\n private RectF mScreenCropBounds = new RectF();\n\n private Paint mPaint = new Paint();\n\n private CropObject mCropObj = null;\n\n private GeometryHolder mGeometry = new GeometryHolder();\n\n private GeometryHolder mUpdateHolder = new GeometryHolder();\n\n private Drawable mCropIndicator;\n\n private int mIndicatorSize;\n\n private boolean mMovingBlock = false;\n\n private Matrix mDisplayMatrix = null;\n\n private Matrix mDisplayCropMatrix = null;\n\n private Matrix mDisplayMatrixInverse = null;\n\n private float mPrevX = 0;\n\n private float mPrevY = 0;\n\n private int mMinSideSize = 90;\n\n private int mTouchTolerance = 40;\n\n private enum Mode {\n\n NONE, MOVE\n }\n\n private Mode mState = Mode.NONE;\n\n private boolean mValidDraw = false;\n\n FilterCropRepresentation mLocalRep = new FilterCropRepresentation();\n\n EditorCrop mEditorCrop;\n\n public ImageCrop(Context context) {\n super(context);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs) {\n super(context, attrs);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setup(context);\n }\n\n private void setup(Context context) {\n Resources rsc = context.getResources();\n mCropIndicator = rsc.getDrawable(R.drawable.camera_crop);\n mIndicatorSize = (int) rsc.getDimension(R.dimen.crop_indicator_size);\n mMinSideSize = (int) rsc.getDimension(R.dimen.crop_min_side);\n mTouchTolerance = (int) rsc.getDimension(R.dimen.crop_touch_tolerance);\n }\n\n public void setFilterCropRepresentation(FilterCropRepresentation crop) {\n mLocalRep = (crop == null) ? new FilterCropRepresentation() : crop;\n GeometryMathUtils.initializeHolder(mUpdateHolder, mLocalRep);\n mValidDraw = true;\n }\n\n public FilterCropRepresentation getFinalRepresentation() {\n return mLocalRep;\n }\n\n private void internallyUpdateLocalRep(RectF crop, RectF image) {\n FilterCropRepresentation.findNormalizedCrop(crop, (int) image.width(), (int) image.height());\n mGeometry.crop.set(crop);\n mUpdateHolder.set(mGeometry);\n mLocalRep.setCrop(crop);\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n float x = event.getX();\n float y = event.getY();\n if (mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n return true;\n }\n float[] touchPoint = { x, y };\n mDisplayMatrixInverse.mapPoints(touchPoint);\n x = touchPoint[0];\n y = touchPoint[1];\n switch(event.getActionMasked()) {\n case (MotionEvent.ACTION_DOWN):\n if (mState == Mode.NONE) {\n if (!mCropObj.selectEdge(x, y)) {\n mMovingBlock = mCropObj.selectEdge(CropObject.MOVE_BLOCK);\n }\n mPrevX = x;\n mPrevY = y;\n mState = Mode.MOVE;\n }\n break;\n case (MotionEvent.ACTION_UP):\n if (mState == Mode.MOVE) {\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n mMovingBlock = false;\n mPrevX = x;\n mPrevY = y;\n mState = Mode.NONE;\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n }\n break;\n case (MotionEvent.ACTION_MOVE):\n if (mState == Mode.MOVE) {\n float dx = x - mPrevX;\n float dy = y - mPrevY;\n mCropObj.moveCurrentSelection(dx, dy);\n mPrevX = x;\n mPrevY = y;\n }\n break;\n default:\n break;\n }\n invalidate();\n return true;\n }\n\n private void clearDisplay() {\n mDisplayMatrix = null;\n mDisplayMatrixInverse = null;\n invalidate();\n }\n\n public void applyFreeAspect() {\n mCropObj.unsetAspectRatio();\n invalidate();\n }\n\n public void applyOriginalAspect() {", "post_mask_code": "\n float h = outer.height();\n if (w > 0 && h > 0) {\n applyAspect(w, h);\n mCropObj.resetBoundsTo(outer, outer);\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n } else {\n Log.w(TAG, \"failed to set aspect ratio original\");\n }\n invalidate();\n }\n\n public void applyAspect(float x, float y) {\n if (x <= 0 || y <= 0) {\n throw new IllegalArgumentException(\"Bad arguments to applyAspect\");\n }\n // If we are rotated by 90 degrees from horizontal, swap x and y\n if (GeometryMathUtils.needsDimensionSwap(mGeometry.rotation)) {\n float tmp = x;\n x = y;\n y = tmp;\n }\n if (!mCropObj.setInnerAspectRatio(x, y)) {\n Log.w(TAG, \"failed to set aspect ratio\");\n }\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n invalidate();\n }\n\n /**\n * Rotates first d bits in integer x to the left some number of times.\n */\n private int bitCycleLeft(int x, int times, int d) {\n int mask = (1 << d) - 1;\n int mout = x & mask;\n times %= d;\n int hi = mout >> (d - times);\n int low = (mout << times) & mask;\n int ret = x & ~mask;\n ret |= low;\n ret |= hi;\n return ret;\n }\n\n /**\n * Find the selected edge or corner in screen coordinates.\n */\n private int decode(int movingEdges, float rotation) {\n int rot = CropMath.constrainedRotation(rotation);\n switch(rot) {\n case 90:\n return bitCycleLeft(movingEdges, 1, 4);\n case 180:\n return bitCycleLeft(movingEdges, 2, 4);\n case 270:\n return bitCycleLeft(movingEdges, 3, 4);\n default:\n return movingEdges;\n }\n }\n\n private void forceStateConsistency() {\n MasterImage master = MasterImage.getImage();\n Bitmap image = master.getFiltersOnlyImage();\n int width = image.getWidth();\n int height = image.getHeight();\n if (mCropObj == null || !mUpdateHolder.equals(mGeometry) || mImageBounds.width() != width || mImageBounds.height() != height || !mLocalRep.getCrop().equals(mUpdateHolder.crop)) {\n mImageBounds.set(0, 0, width, height);\n mGeometry.set(mUpdateHolder);\n mLocalRep.setCrop(mUpdateHolder.crop);\n RectF scaledCrop = new RectF(mUpdateHolder.crop);\n FilterCropRepresentation.findScaledCrop(scaledCrop, width, height);\n mCropObj = new CropObject(mImageBounds, scaledCrop, (int) mUpdateHolder.straighten);\n mState = Mode.NONE;\n clearDisplay();\n }\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n clearDisplay();\n }\n\n @Override\n public void onDraw(Canvas canvas) {\n Bitmap bitmap = MasterImage.getImage().getFiltersOnlyImage();\n if (bitmap == null) {\n MasterImage.getImage().invalidateFiltersOnly();\n }\n if (!mValidDraw || bitmap == null) {\n return;\n }\n forceStateConsistency();\n mImageBounds.set(0, 0, bitmap.getWidth(), bitmap.getHeight());\n // If display matrix doesn't exist, create it and its dependencies\n if (mDisplayCropMatrix == null || mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n mCropObj.unsetAspectRatio();\n mDisplayMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n float straighten = mGeometry.straighten;\n mGeometry.straighten = 0;\n mDisplayCropMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n mGeometry.straighten = straighten;\n mDisplayMatrixInverse = new Matrix();\n mDisplayMatrixInverse.reset();\n if (!mDisplayCropMatrix.invert(mDisplayMatrixInverse)) {\n Log.w(TAG, \"could not invert display matrix\");\n mDisplayMatrixInverse = null;\n return;\n }\n // Scale min side and tolerance by display matrix scale factor\n mCropObj.setMinInnerSideSize(mDisplayMatrixInverse.mapRadius(mMinSideSize));\n mCropObj.setTouchTolerance(mDisplayMatrixInverse.mapRadius(mTouchTolerance));\n // drive Crop engine to clamp to crop bounds\n int[] sides = { CropObject.MOVE_TOP, CropObject.MOVE_BOTTOM, CropObject.MOVE_LEFT, CropObject.MOVE_RIGHT };\n int delta = Math.min(canvas.getWidth(), canvas.getHeight()) / 4;\n int[] dx = { delta, -delta, 0, 0 };\n int[] dy = { 0, 0, delta, -delta };\n for (int i = 0; i < sides.length; i++) {\n mCropObj.selectEdge(sides[i]);\n mCropObj.moveCurrentSelection(dx[i], dy[i]);\n mCropObj.moveCurrentSelection(-dx[i], -dy[i]);\n }\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n }\n // Draw actual bitmap\n mPaint.reset();\n mPaint.setAntiAlias(true);\n mPaint.setFilterBitmap(true);\n canvas.drawBitmap(bitmap, mDisplayMatrix, mPaint);\n mCropObj.getInnerBounds(mScreenCropBounds);\n RectF outer = mCropObj.getOuterBounds();\n FilterCropRepresentation.findNormalizedCrop(mScreenCropBounds, (int) outer.width(), (int) outer.height());\n FilterCropRepresentation.findScaledCrop(mScreenCropBounds, bitmap.getWidth(), bitmap.getHeight());\n if (mDisplayCropMatrix.mapRect(mScreenCropBounds)) {\n // Draw crop rect and markers\n CropDrawingUtils.drawCropRect(canvas, mScreenCropBounds);\n CropDrawingUtils.drawShade(canvas, mScreenCropBounds);\n CropDrawingUtils.drawRuleOfThird(canvas, mScreenCropBounds);\n CropDrawingUtils.drawIndicators(canvas, mCropIndicator, mIndicatorSize, mScreenCropBounds, mCropObj.isFixedAspect(), decode(mCropObj.getSelectState(), mGeometry.rotation.value()));\n }\n }\n\n public void setEditor(EditorCrop editorCrop) {\n mEditorCrop = editorCrop;\n }\n}\n"} {"task_id": "Java_543", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/CyanogenMod/android_packages_apps_Gallery2/src/com/android/gallery3d/filtershow/imageshow/ImageCrop.java", "mask_start_position": 5337, "mask_end_position": 5655, "canonical_solution": "float h = outer.height();\n if (w > 0 && h > 0) {\n applyAspect(w, h);\n mCropObj.resetBoundsTo(outer, outer);\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n } else {\n Log.w(TAG, \"failed to set aspect ratio original\");\n }", "pre_mask_code": "package com.android.gallery3d.filtershow.imageshow;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.RectF;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport com.android.gallery3d.R;\nimport com.android.gallery3d.filtershow.crop.CropDrawingUtils;\nimport com.android.gallery3d.filtershow.crop.CropMath;\nimport com.android.gallery3d.filtershow.crop.CropObject;\nimport com.android.gallery3d.filtershow.editors.EditorCrop;\nimport com.android.gallery3d.filtershow.filters.FilterCropRepresentation;\nimport com.android.gallery3d.filtershow.imageshow.GeometryMathUtils.GeometryHolder;\n\npublic class ImageCrop extends ImageShow {\n\n private static final String TAG = ImageCrop.class.getSimpleName();\n\n private RectF mImageBounds = new RectF();\n\n private RectF mScreenCropBounds = new RectF();\n\n private Paint mPaint = new Paint();\n\n private CropObject mCropObj = null;\n\n private GeometryHolder mGeometry = new GeometryHolder();\n\n private GeometryHolder mUpdateHolder = new GeometryHolder();\n\n private Drawable mCropIndicator;\n\n private int mIndicatorSize;\n\n private boolean mMovingBlock = false;\n\n private Matrix mDisplayMatrix = null;\n\n private Matrix mDisplayCropMatrix = null;\n\n private Matrix mDisplayMatrixInverse = null;\n\n private float mPrevX = 0;\n\n private float mPrevY = 0;\n\n private int mMinSideSize = 90;\n\n private int mTouchTolerance = 40;\n\n private enum Mode {\n\n NONE, MOVE\n }\n\n private Mode mState = Mode.NONE;\n\n private boolean mValidDraw = false;\n\n FilterCropRepresentation mLocalRep = new FilterCropRepresentation();\n\n EditorCrop mEditorCrop;\n\n public ImageCrop(Context context) {\n super(context);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs) {\n super(context, attrs);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setup(context);\n }\n\n private void setup(Context context) {\n Resources rsc = context.getResources();\n mCropIndicator = rsc.getDrawable(R.drawable.camera_crop);\n mIndicatorSize = (int) rsc.getDimension(R.dimen.crop_indicator_size);\n mMinSideSize = (int) rsc.getDimension(R.dimen.crop_min_side);\n mTouchTolerance = (int) rsc.getDimension(R.dimen.crop_touch_tolerance);\n }\n\n public void setFilterCropRepresentation(FilterCropRepresentation crop) {\n mLocalRep = (crop == null) ? new FilterCropRepresentation() : crop;\n GeometryMathUtils.initializeHolder(mUpdateHolder, mLocalRep);\n mValidDraw = true;\n }\n\n public FilterCropRepresentation getFinalRepresentation() {\n return mLocalRep;\n }\n\n private void internallyUpdateLocalRep(RectF crop, RectF image) {\n FilterCropRepresentation.findNormalizedCrop(crop, (int) image.width(), (int) image.height());\n mGeometry.crop.set(crop);\n mUpdateHolder.set(mGeometry);\n mLocalRep.setCrop(crop);\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n float x = event.getX();\n float y = event.getY();\n if (mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n return true;\n }\n float[] touchPoint = { x, y };\n mDisplayMatrixInverse.mapPoints(touchPoint);\n x = touchPoint[0];\n y = touchPoint[1];\n switch(event.getActionMasked()) {\n case (MotionEvent.ACTION_DOWN):\n if (mState == Mode.NONE) {\n if (!mCropObj.selectEdge(x, y)) {\n mMovingBlock = mCropObj.selectEdge(CropObject.MOVE_BLOCK);\n }\n mPrevX = x;\n mPrevY = y;\n mState = Mode.MOVE;\n }\n break;\n case (MotionEvent.ACTION_UP):\n if (mState == Mode.MOVE) {\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n mMovingBlock = false;\n mPrevX = x;\n mPrevY = y;\n mState = Mode.NONE;\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n }\n break;\n case (MotionEvent.ACTION_MOVE):\n if (mState == Mode.MOVE) {\n float dx = x - mPrevX;\n float dy = y - mPrevY;\n mCropObj.moveCurrentSelection(dx, dy);\n mPrevX = x;\n mPrevY = y;\n }\n break;\n default:\n break;\n }\n invalidate();\n return true;\n }\n\n private void clearDisplay() {\n mDisplayMatrix = null;\n mDisplayMatrixInverse = null;\n invalidate();\n }\n\n public void applyFreeAspect() {\n mCropObj.unsetAspectRatio();\n invalidate();\n }\n\n public void applyOriginalAspect() {\n RectF outer = mCropObj.getOuterBounds();\n float w = outer.width();\n ", "post_mask_code": "\n invalidate();\n }\n\n public void applyAspect(float x, float y) {\n if (x <= 0 || y <= 0) {\n throw new IllegalArgumentException(\"Bad arguments to applyAspect\");\n }\n // If we are rotated by 90 degrees from horizontal, swap x and y\n if (GeometryMathUtils.needsDimensionSwap(mGeometry.rotation)) {\n float tmp = x;\n x = y;\n y = tmp;\n }\n if (!mCropObj.setInnerAspectRatio(x, y)) {\n Log.w(TAG, \"failed to set aspect ratio\");\n }\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n invalidate();\n }\n\n /**\n * Rotates first d bits in integer x to the left some number of times.\n */\n private int bitCycleLeft(int x, int times, int d) {\n int mask = (1 << d) - 1;\n int mout = x & mask;\n times %= d;\n int hi = mout >> (d - times);\n int low = (mout << times) & mask;\n int ret = x & ~mask;\n ret |= low;\n ret |= hi;\n return ret;\n }\n\n /**\n * Find the selected edge or corner in screen coordinates.\n */\n private int decode(int movingEdges, float rotation) {\n int rot = CropMath.constrainedRotation(rotation);\n switch(rot) {\n case 90:\n return bitCycleLeft(movingEdges, 1, 4);\n case 180:\n return bitCycleLeft(movingEdges, 2, 4);\n case 270:\n return bitCycleLeft(movingEdges, 3, 4);\n default:\n return movingEdges;\n }\n }\n\n private void forceStateConsistency() {\n MasterImage master = MasterImage.getImage();\n Bitmap image = master.getFiltersOnlyImage();\n int width = image.getWidth();\n int height = image.getHeight();\n if (mCropObj == null || !mUpdateHolder.equals(mGeometry) || mImageBounds.width() != width || mImageBounds.height() != height || !mLocalRep.getCrop().equals(mUpdateHolder.crop)) {\n mImageBounds.set(0, 0, width, height);\n mGeometry.set(mUpdateHolder);\n mLocalRep.setCrop(mUpdateHolder.crop);\n RectF scaledCrop = new RectF(mUpdateHolder.crop);\n FilterCropRepresentation.findScaledCrop(scaledCrop, width, height);\n mCropObj = new CropObject(mImageBounds, scaledCrop, (int) mUpdateHolder.straighten);\n mState = Mode.NONE;\n clearDisplay();\n }\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n clearDisplay();\n }\n\n @Override\n public void onDraw(Canvas canvas) {\n Bitmap bitmap = MasterImage.getImage().getFiltersOnlyImage();\n if (bitmap == null) {\n MasterImage.getImage().invalidateFiltersOnly();\n }\n if (!mValidDraw || bitmap == null) {\n return;\n }\n forceStateConsistency();\n mImageBounds.set(0, 0, bitmap.getWidth(), bitmap.getHeight());\n // If display matrix doesn't exist, create it and its dependencies\n if (mDisplayCropMatrix == null || mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n mCropObj.unsetAspectRatio();\n mDisplayMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n float straighten = mGeometry.straighten;\n mGeometry.straighten = 0;\n mDisplayCropMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n mGeometry.straighten = straighten;\n mDisplayMatrixInverse = new Matrix();\n mDisplayMatrixInverse.reset();\n if (!mDisplayCropMatrix.invert(mDisplayMatrixInverse)) {\n Log.w(TAG, \"could not invert display matrix\");\n mDisplayMatrixInverse = null;\n return;\n }\n // Scale min side and tolerance by display matrix scale factor\n mCropObj.setMinInnerSideSize(mDisplayMatrixInverse.mapRadius(mMinSideSize));\n mCropObj.setTouchTolerance(mDisplayMatrixInverse.mapRadius(mTouchTolerance));\n // drive Crop engine to clamp to crop bounds\n int[] sides = { CropObject.MOVE_TOP, CropObject.MOVE_BOTTOM, CropObject.MOVE_LEFT, CropObject.MOVE_RIGHT };\n int delta = Math.min(canvas.getWidth(), canvas.getHeight()) / 4;\n int[] dx = { delta, -delta, 0, 0 };\n int[] dy = { 0, 0, delta, -delta };\n for (int i = 0; i < sides.length; i++) {\n mCropObj.selectEdge(sides[i]);\n mCropObj.moveCurrentSelection(dx[i], dy[i]);\n mCropObj.moveCurrentSelection(-dx[i], -dy[i]);\n }\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n }\n // Draw actual bitmap\n mPaint.reset();\n mPaint.setAntiAlias(true);\n mPaint.setFilterBitmap(true);\n canvas.drawBitmap(bitmap, mDisplayMatrix, mPaint);\n mCropObj.getInnerBounds(mScreenCropBounds);\n RectF outer = mCropObj.getOuterBounds();\n FilterCropRepresentation.findNormalizedCrop(mScreenCropBounds, (int) outer.width(), (int) outer.height());\n FilterCropRepresentation.findScaledCrop(mScreenCropBounds, bitmap.getWidth(), bitmap.getHeight());\n if (mDisplayCropMatrix.mapRect(mScreenCropBounds)) {\n // Draw crop rect and markers\n CropDrawingUtils.drawCropRect(canvas, mScreenCropBounds);\n CropDrawingUtils.drawShade(canvas, mScreenCropBounds);\n CropDrawingUtils.drawRuleOfThird(canvas, mScreenCropBounds);\n CropDrawingUtils.drawIndicators(canvas, mCropIndicator, mIndicatorSize, mScreenCropBounds, mCropObj.isFixedAspect(), decode(mCropObj.getSelectState(), mGeometry.rotation.value()));\n }\n }\n\n public void setEditor(EditorCrop editorCrop) {\n mEditorCrop = editorCrop;\n }\n}\n"} {"task_id": "Java_544", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/CyanogenMod/android_packages_apps_Gallery2/src/com/android/gallery3d/filtershow/imageshow/ImageCrop.java", "mask_start_position": 5664, "mask_end_position": 5683, "canonical_solution": "invalidate();\n }", "pre_mask_code": "package com.android.gallery3d.filtershow.imageshow;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.RectF;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport com.android.gallery3d.R;\nimport com.android.gallery3d.filtershow.crop.CropDrawingUtils;\nimport com.android.gallery3d.filtershow.crop.CropMath;\nimport com.android.gallery3d.filtershow.crop.CropObject;\nimport com.android.gallery3d.filtershow.editors.EditorCrop;\nimport com.android.gallery3d.filtershow.filters.FilterCropRepresentation;\nimport com.android.gallery3d.filtershow.imageshow.GeometryMathUtils.GeometryHolder;\n\npublic class ImageCrop extends ImageShow {\n\n private static final String TAG = ImageCrop.class.getSimpleName();\n\n private RectF mImageBounds = new RectF();\n\n private RectF mScreenCropBounds = new RectF();\n\n private Paint mPaint = new Paint();\n\n private CropObject mCropObj = null;\n\n private GeometryHolder mGeometry = new GeometryHolder();\n\n private GeometryHolder mUpdateHolder = new GeometryHolder();\n\n private Drawable mCropIndicator;\n\n private int mIndicatorSize;\n\n private boolean mMovingBlock = false;\n\n private Matrix mDisplayMatrix = null;\n\n private Matrix mDisplayCropMatrix = null;\n\n private Matrix mDisplayMatrixInverse = null;\n\n private float mPrevX = 0;\n\n private float mPrevY = 0;\n\n private int mMinSideSize = 90;\n\n private int mTouchTolerance = 40;\n\n private enum Mode {\n\n NONE, MOVE\n }\n\n private Mode mState = Mode.NONE;\n\n private boolean mValidDraw = false;\n\n FilterCropRepresentation mLocalRep = new FilterCropRepresentation();\n\n EditorCrop mEditorCrop;\n\n public ImageCrop(Context context) {\n super(context);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs) {\n super(context, attrs);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setup(context);\n }\n\n private void setup(Context context) {\n Resources rsc = context.getResources();\n mCropIndicator = rsc.getDrawable(R.drawable.camera_crop);\n mIndicatorSize = (int) rsc.getDimension(R.dimen.crop_indicator_size);\n mMinSideSize = (int) rsc.getDimension(R.dimen.crop_min_side);\n mTouchTolerance = (int) rsc.getDimension(R.dimen.crop_touch_tolerance);\n }\n\n public void setFilterCropRepresentation(FilterCropRepresentation crop) {\n mLocalRep = (crop == null) ? new FilterCropRepresentation() : crop;\n GeometryMathUtils.initializeHolder(mUpdateHolder, mLocalRep);\n mValidDraw = true;\n }\n\n public FilterCropRepresentation getFinalRepresentation() {\n return mLocalRep;\n }\n\n private void internallyUpdateLocalRep(RectF crop, RectF image) {\n FilterCropRepresentation.findNormalizedCrop(crop, (int) image.width(), (int) image.height());\n mGeometry.crop.set(crop);\n mUpdateHolder.set(mGeometry);\n mLocalRep.setCrop(crop);\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n float x = event.getX();\n float y = event.getY();\n if (mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n return true;\n }\n float[] touchPoint = { x, y };\n mDisplayMatrixInverse.mapPoints(touchPoint);\n x = touchPoint[0];\n y = touchPoint[1];\n switch(event.getActionMasked()) {\n case (MotionEvent.ACTION_DOWN):\n if (mState == Mode.NONE) {\n if (!mCropObj.selectEdge(x, y)) {\n mMovingBlock = mCropObj.selectEdge(CropObject.MOVE_BLOCK);\n }\n mPrevX = x;\n mPrevY = y;\n mState = Mode.MOVE;\n }\n break;\n case (MotionEvent.ACTION_UP):\n if (mState == Mode.MOVE) {\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n mMovingBlock = false;\n mPrevX = x;\n mPrevY = y;\n mState = Mode.NONE;\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n }\n break;\n case (MotionEvent.ACTION_MOVE):\n if (mState == Mode.MOVE) {\n float dx = x - mPrevX;\n float dy = y - mPrevY;\n mCropObj.moveCurrentSelection(dx, dy);\n mPrevX = x;\n mPrevY = y;\n }\n break;\n default:\n break;\n }\n invalidate();\n return true;\n }\n\n private void clearDisplay() {\n mDisplayMatrix = null;\n mDisplayMatrixInverse = null;\n invalidate();\n }\n\n public void applyFreeAspect() {\n mCropObj.unsetAspectRatio();\n invalidate();\n }\n\n public void applyOriginalAspect() {\n RectF outer = mCropObj.getOuterBounds();\n float w = outer.width();\n float h = outer.height();\n if (w > 0 && h > 0) {\n applyAspect(w, h);\n mCropObj.resetBoundsTo(outer, outer);\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n } else {\n Log.w(TAG, \"failed to set aspect ratio original\");\n }\n ", "post_mask_code": "\n\n public void applyAspect(float x, float y) {\n if (x <= 0 || y <= 0) {\n throw new IllegalArgumentException(\"Bad arguments to applyAspect\");\n }\n // If we are rotated by 90 degrees from horizontal, swap x and y\n if (GeometryMathUtils.needsDimensionSwap(mGeometry.rotation)) {\n float tmp = x;\n x = y;\n y = tmp;\n }\n if (!mCropObj.setInnerAspectRatio(x, y)) {\n Log.w(TAG, \"failed to set aspect ratio\");\n }\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n invalidate();\n }\n\n /**\n * Rotates first d bits in integer x to the left some number of times.\n */\n private int bitCycleLeft(int x, int times, int d) {\n int mask = (1 << d) - 1;\n int mout = x & mask;\n times %= d;\n int hi = mout >> (d - times);\n int low = (mout << times) & mask;\n int ret = x & ~mask;\n ret |= low;\n ret |= hi;\n return ret;\n }\n\n /**\n * Find the selected edge or corner in screen coordinates.\n */\n private int decode(int movingEdges, float rotation) {\n int rot = CropMath.constrainedRotation(rotation);\n switch(rot) {\n case 90:\n return bitCycleLeft(movingEdges, 1, 4);\n case 180:\n return bitCycleLeft(movingEdges, 2, 4);\n case 270:\n return bitCycleLeft(movingEdges, 3, 4);\n default:\n return movingEdges;\n }\n }\n\n private void forceStateConsistency() {\n MasterImage master = MasterImage.getImage();\n Bitmap image = master.getFiltersOnlyImage();\n int width = image.getWidth();\n int height = image.getHeight();\n if (mCropObj == null || !mUpdateHolder.equals(mGeometry) || mImageBounds.width() != width || mImageBounds.height() != height || !mLocalRep.getCrop().equals(mUpdateHolder.crop)) {\n mImageBounds.set(0, 0, width, height);\n mGeometry.set(mUpdateHolder);\n mLocalRep.setCrop(mUpdateHolder.crop);\n RectF scaledCrop = new RectF(mUpdateHolder.crop);\n FilterCropRepresentation.findScaledCrop(scaledCrop, width, height);\n mCropObj = new CropObject(mImageBounds, scaledCrop, (int) mUpdateHolder.straighten);\n mState = Mode.NONE;\n clearDisplay();\n }\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n clearDisplay();\n }\n\n @Override\n public void onDraw(Canvas canvas) {\n Bitmap bitmap = MasterImage.getImage().getFiltersOnlyImage();\n if (bitmap == null) {\n MasterImage.getImage().invalidateFiltersOnly();\n }\n if (!mValidDraw || bitmap == null) {\n return;\n }\n forceStateConsistency();\n mImageBounds.set(0, 0, bitmap.getWidth(), bitmap.getHeight());\n // If display matrix doesn't exist, create it and its dependencies\n if (mDisplayCropMatrix == null || mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n mCropObj.unsetAspectRatio();\n mDisplayMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n float straighten = mGeometry.straighten;\n mGeometry.straighten = 0;\n mDisplayCropMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n mGeometry.straighten = straighten;\n mDisplayMatrixInverse = new Matrix();\n mDisplayMatrixInverse.reset();\n if (!mDisplayCropMatrix.invert(mDisplayMatrixInverse)) {\n Log.w(TAG, \"could not invert display matrix\");\n mDisplayMatrixInverse = null;\n return;\n }\n // Scale min side and tolerance by display matrix scale factor\n mCropObj.setMinInnerSideSize(mDisplayMatrixInverse.mapRadius(mMinSideSize));\n mCropObj.setTouchTolerance(mDisplayMatrixInverse.mapRadius(mTouchTolerance));\n // drive Crop engine to clamp to crop bounds\n int[] sides = { CropObject.MOVE_TOP, CropObject.MOVE_BOTTOM, CropObject.MOVE_LEFT, CropObject.MOVE_RIGHT };\n int delta = Math.min(canvas.getWidth(), canvas.getHeight()) / 4;\n int[] dx = { delta, -delta, 0, 0 };\n int[] dy = { 0, 0, delta, -delta };\n for (int i = 0; i < sides.length; i++) {\n mCropObj.selectEdge(sides[i]);\n mCropObj.moveCurrentSelection(dx[i], dy[i]);\n mCropObj.moveCurrentSelection(-dx[i], -dy[i]);\n }\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n }\n // Draw actual bitmap\n mPaint.reset();\n mPaint.setAntiAlias(true);\n mPaint.setFilterBitmap(true);\n canvas.drawBitmap(bitmap, mDisplayMatrix, mPaint);\n mCropObj.getInnerBounds(mScreenCropBounds);\n RectF outer = mCropObj.getOuterBounds();\n FilterCropRepresentation.findNormalizedCrop(mScreenCropBounds, (int) outer.width(), (int) outer.height());\n FilterCropRepresentation.findScaledCrop(mScreenCropBounds, bitmap.getWidth(), bitmap.getHeight());\n if (mDisplayCropMatrix.mapRect(mScreenCropBounds)) {\n // Draw crop rect and markers\n CropDrawingUtils.drawCropRect(canvas, mScreenCropBounds);\n CropDrawingUtils.drawShade(canvas, mScreenCropBounds);\n CropDrawingUtils.drawRuleOfThird(canvas, mScreenCropBounds);\n CropDrawingUtils.drawIndicators(canvas, mCropIndicator, mIndicatorSize, mScreenCropBounds, mCropObj.isFixedAspect(), decode(mCropObj.getSelectState(), mGeometry.rotation.value()));\n }\n }\n\n public void setEditor(EditorCrop editorCrop) {\n mEditorCrop = editorCrop;\n }\n}\n"} {"task_id": "Java_545", "language": "Java", "task_type": "single_line", "source_file": "java/github/CyanogenMod/android_packages_apps_Gallery2/src/com/android/gallery3d/filtershow/imageshow/ImageCrop.java", "mask_start_position": 2745, "mask_end_position": 2797, "canonical_solution": "op == null) ? new FilterCropRepresentation() : crop;", "pre_mask_code": "package com.android.gallery3d.filtershow.imageshow;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.RectF;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport com.android.gallery3d.R;\nimport com.android.gallery3d.filtershow.crop.CropDrawingUtils;\nimport com.android.gallery3d.filtershow.crop.CropMath;\nimport com.android.gallery3d.filtershow.crop.CropObject;\nimport com.android.gallery3d.filtershow.editors.EditorCrop;\nimport com.android.gallery3d.filtershow.filters.FilterCropRepresentation;\nimport com.android.gallery3d.filtershow.imageshow.GeometryMathUtils.GeometryHolder;\n\npublic class ImageCrop extends ImageShow {\n\n private static final String TAG = ImageCrop.class.getSimpleName();\n\n private RectF mImageBounds = new RectF();\n\n private RectF mScreenCropBounds = new RectF();\n\n private Paint mPaint = new Paint();\n\n private CropObject mCropObj = null;\n\n private GeometryHolder mGeometry = new GeometryHolder();\n\n private GeometryHolder mUpdateHolder = new GeometryHolder();\n\n private Drawable mCropIndicator;\n\n private int mIndicatorSize;\n\n private boolean mMovingBlock = false;\n\n private Matrix mDisplayMatrix = null;\n\n private Matrix mDisplayCropMatrix = null;\n\n private Matrix mDisplayMatrixInverse = null;\n\n private float mPrevX = 0;\n\n private float mPrevY = 0;\n\n private int mMinSideSize = 90;\n\n private int mTouchTolerance = 40;\n\n private enum Mode {\n\n NONE, MOVE\n }\n\n private Mode mState = Mode.NONE;\n\n private boolean mValidDraw = false;\n\n FilterCropRepresentation mLocalRep = new FilterCropRepresentation();\n\n EditorCrop mEditorCrop;\n\n public ImageCrop(Context context) {\n super(context);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs) {\n super(context, attrs);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setup(context);\n }\n\n private void setup(Context context) {\n Resources rsc = context.getResources();\n mCropIndicator = rsc.getDrawable(R.drawable.camera_crop);\n mIndicatorSize = (int) rsc.getDimension(R.dimen.crop_indicator_size);\n mMinSideSize = (int) rsc.getDimension(R.dimen.crop_min_side);\n mTouchTolerance = (int) rsc.getDimension(R.dimen.crop_touch_tolerance);\n }\n\n public void setFilterCropRepresentation(FilterCropRepresentation crop) {\n mLocalRep = (cr", "post_mask_code": "\n GeometryMathUtils.initializeHolder(mUpdateHolder, mLocalRep);\n mValidDraw = true;\n }\n\n public FilterCropRepresentation getFinalRepresentation() {\n return mLocalRep;\n }\n\n private void internallyUpdateLocalRep(RectF crop, RectF image) {\n FilterCropRepresentation.findNormalizedCrop(crop, (int) image.width(), (int) image.height());\n mGeometry.crop.set(crop);\n mUpdateHolder.set(mGeometry);\n mLocalRep.setCrop(crop);\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n float x = event.getX();\n float y = event.getY();\n if (mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n return true;\n }\n float[] touchPoint = { x, y };\n mDisplayMatrixInverse.mapPoints(touchPoint);\n x = touchPoint[0];\n y = touchPoint[1];\n switch(event.getActionMasked()) {\n case (MotionEvent.ACTION_DOWN):\n if (mState == Mode.NONE) {\n if (!mCropObj.selectEdge(x, y)) {\n mMovingBlock = mCropObj.selectEdge(CropObject.MOVE_BLOCK);\n }\n mPrevX = x;\n mPrevY = y;\n mState = Mode.MOVE;\n }\n break;\n case (MotionEvent.ACTION_UP):\n if (mState == Mode.MOVE) {\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n mMovingBlock = false;\n mPrevX = x;\n mPrevY = y;\n mState = Mode.NONE;\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n }\n break;\n case (MotionEvent.ACTION_MOVE):\n if (mState == Mode.MOVE) {\n float dx = x - mPrevX;\n float dy = y - mPrevY;\n mCropObj.moveCurrentSelection(dx, dy);\n mPrevX = x;\n mPrevY = y;\n }\n break;\n default:\n break;\n }\n invalidate();\n return true;\n }\n\n private void clearDisplay() {\n mDisplayMatrix = null;\n mDisplayMatrixInverse = null;\n invalidate();\n }\n\n public void applyFreeAspect() {\n mCropObj.unsetAspectRatio();\n invalidate();\n }\n\n public void applyOriginalAspect() {\n RectF outer = mCropObj.getOuterBounds();\n float w = outer.width();\n float h = outer.height();\n if (w > 0 && h > 0) {\n applyAspect(w, h);\n mCropObj.resetBoundsTo(outer, outer);\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n } else {\n Log.w(TAG, \"failed to set aspect ratio original\");\n }\n invalidate();\n }\n\n public void applyAspect(float x, float y) {\n if (x <= 0 || y <= 0) {\n throw new IllegalArgumentException(\"Bad arguments to applyAspect\");\n }\n // If we are rotated by 90 degrees from horizontal, swap x and y\n if (GeometryMathUtils.needsDimensionSwap(mGeometry.rotation)) {\n float tmp = x;\n x = y;\n y = tmp;\n }\n if (!mCropObj.setInnerAspectRatio(x, y)) {\n Log.w(TAG, \"failed to set aspect ratio\");\n }\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n invalidate();\n }\n\n /**\n * Rotates first d bits in integer x to the left some number of times.\n */\n private int bitCycleLeft(int x, int times, int d) {\n int mask = (1 << d) - 1;\n int mout = x & mask;\n times %= d;\n int hi = mout >> (d - times);\n int low = (mout << times) & mask;\n int ret = x & ~mask;\n ret |= low;\n ret |= hi;\n return ret;\n }\n\n /**\n * Find the selected edge or corner in screen coordinates.\n */\n private int decode(int movingEdges, float rotation) {\n int rot = CropMath.constrainedRotation(rotation);\n switch(rot) {\n case 90:\n return bitCycleLeft(movingEdges, 1, 4);\n case 180:\n return bitCycleLeft(movingEdges, 2, 4);\n case 270:\n return bitCycleLeft(movingEdges, 3, 4);\n default:\n return movingEdges;\n }\n }\n\n private void forceStateConsistency() {\n MasterImage master = MasterImage.getImage();\n Bitmap image = master.getFiltersOnlyImage();\n int width = image.getWidth();\n int height = image.getHeight();\n if (mCropObj == null || !mUpdateHolder.equals(mGeometry) || mImageBounds.width() != width || mImageBounds.height() != height || !mLocalRep.getCrop().equals(mUpdateHolder.crop)) {\n mImageBounds.set(0, 0, width, height);\n mGeometry.set(mUpdateHolder);\n mLocalRep.setCrop(mUpdateHolder.crop);\n RectF scaledCrop = new RectF(mUpdateHolder.crop);\n FilterCropRepresentation.findScaledCrop(scaledCrop, width, height);\n mCropObj = new CropObject(mImageBounds, scaledCrop, (int) mUpdateHolder.straighten);\n mState = Mode.NONE;\n clearDisplay();\n }\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n clearDisplay();\n }\n\n @Override\n public void onDraw(Canvas canvas) {\n Bitmap bitmap = MasterImage.getImage().getFiltersOnlyImage();\n if (bitmap == null) {\n MasterImage.getImage().invalidateFiltersOnly();\n }\n if (!mValidDraw || bitmap == null) {\n return;\n }\n forceStateConsistency();\n mImageBounds.set(0, 0, bitmap.getWidth(), bitmap.getHeight());\n // If display matrix doesn't exist, create it and its dependencies\n if (mDisplayCropMatrix == null || mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n mCropObj.unsetAspectRatio();\n mDisplayMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n float straighten = mGeometry.straighten;\n mGeometry.straighten = 0;\n mDisplayCropMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n mGeometry.straighten = straighten;\n mDisplayMatrixInverse = new Matrix();\n mDisplayMatrixInverse.reset();\n if (!mDisplayCropMatrix.invert(mDisplayMatrixInverse)) {\n Log.w(TAG, \"could not invert display matrix\");\n mDisplayMatrixInverse = null;\n return;\n }\n // Scale min side and tolerance by display matrix scale factor\n mCropObj.setMinInnerSideSize(mDisplayMatrixInverse.mapRadius(mMinSideSize));\n mCropObj.setTouchTolerance(mDisplayMatrixInverse.mapRadius(mTouchTolerance));\n // drive Crop engine to clamp to crop bounds\n int[] sides = { CropObject.MOVE_TOP, CropObject.MOVE_BOTTOM, CropObject.MOVE_LEFT, CropObject.MOVE_RIGHT };\n int delta = Math.min(canvas.getWidth(), canvas.getHeight()) / 4;\n int[] dx = { delta, -delta, 0, 0 };\n int[] dy = { 0, 0, delta, -delta };\n for (int i = 0; i < sides.length; i++) {\n mCropObj.selectEdge(sides[i]);\n mCropObj.moveCurrentSelection(dx[i], dy[i]);\n mCropObj.moveCurrentSelection(-dx[i], -dy[i]);\n }\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n }\n // Draw actual bitmap\n mPaint.reset();\n mPaint.setAntiAlias(true);\n mPaint.setFilterBitmap(true);\n canvas.drawBitmap(bitmap, mDisplayMatrix, mPaint);\n mCropObj.getInnerBounds(mScreenCropBounds);\n RectF outer = mCropObj.getOuterBounds();\n FilterCropRepresentation.findNormalizedCrop(mScreenCropBounds, (int) outer.width(), (int) outer.height());\n FilterCropRepresentation.findScaledCrop(mScreenCropBounds, bitmap.getWidth(), bitmap.getHeight());\n if (mDisplayCropMatrix.mapRect(mScreenCropBounds)) {\n // Draw crop rect and markers\n CropDrawingUtils.drawCropRect(canvas, mScreenCropBounds);\n CropDrawingUtils.drawShade(canvas, mScreenCropBounds);\n CropDrawingUtils.drawRuleOfThird(canvas, mScreenCropBounds);\n CropDrawingUtils.drawIndicators(canvas, mCropIndicator, mIndicatorSize, mScreenCropBounds, mCropObj.isFixedAspect(), decode(mCropObj.getSelectState(), mGeometry.rotation.value()));\n }\n }\n\n public void setEditor(EditorCrop editorCrop) {\n mEditorCrop = editorCrop;\n }\n}\n"} {"task_id": "Java_546", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/CyanogenMod/android_packages_apps_Gallery2/src/com/android/gallery3d/filtershow/imageshow/ImageCrop.java", "mask_start_position": 6796, "mask_end_position": 7235, "canonical_solution": "private int decode(int movingEdges, float rotation) {\n int rot = CropMath.constrainedRotation(rotation);\n switch(rot) {\n case 90:\n return bitCycleLeft(movingEdges, 1, 4);\n case 180:\n return bitCycleLeft(movingEdges, 2, 4);\n case 270:\n return bitCycleLeft(movingEdges, 3, 4);\n default:\n return movingEdges;\n }\n }", "pre_mask_code": "package com.android.gallery3d.filtershow.imageshow;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.RectF;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport com.android.gallery3d.R;\nimport com.android.gallery3d.filtershow.crop.CropDrawingUtils;\nimport com.android.gallery3d.filtershow.crop.CropMath;\nimport com.android.gallery3d.filtershow.crop.CropObject;\nimport com.android.gallery3d.filtershow.editors.EditorCrop;\nimport com.android.gallery3d.filtershow.filters.FilterCropRepresentation;\nimport com.android.gallery3d.filtershow.imageshow.GeometryMathUtils.GeometryHolder;\n\npublic class ImageCrop extends ImageShow {\n\n private static final String TAG = ImageCrop.class.getSimpleName();\n\n private RectF mImageBounds = new RectF();\n\n private RectF mScreenCropBounds = new RectF();\n\n private Paint mPaint = new Paint();\n\n private CropObject mCropObj = null;\n\n private GeometryHolder mGeometry = new GeometryHolder();\n\n private GeometryHolder mUpdateHolder = new GeometryHolder();\n\n private Drawable mCropIndicator;\n\n private int mIndicatorSize;\n\n private boolean mMovingBlock = false;\n\n private Matrix mDisplayMatrix = null;\n\n private Matrix mDisplayCropMatrix = null;\n\n private Matrix mDisplayMatrixInverse = null;\n\n private float mPrevX = 0;\n\n private float mPrevY = 0;\n\n private int mMinSideSize = 90;\n\n private int mTouchTolerance = 40;\n\n private enum Mode {\n\n NONE, MOVE\n }\n\n private Mode mState = Mode.NONE;\n\n private boolean mValidDraw = false;\n\n FilterCropRepresentation mLocalRep = new FilterCropRepresentation();\n\n EditorCrop mEditorCrop;\n\n public ImageCrop(Context context) {\n super(context);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs) {\n super(context, attrs);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setup(context);\n }\n\n private void setup(Context context) {\n Resources rsc = context.getResources();\n mCropIndicator = rsc.getDrawable(R.drawable.camera_crop);\n mIndicatorSize = (int) rsc.getDimension(R.dimen.crop_indicator_size);\n mMinSideSize = (int) rsc.getDimension(R.dimen.crop_min_side);\n mTouchTolerance = (int) rsc.getDimension(R.dimen.crop_touch_tolerance);\n }\n\n public void setFilterCropRepresentation(FilterCropRepresentation crop) {\n mLocalRep = (crop == null) ? new FilterCropRepresentation() : crop;\n GeometryMathUtils.initializeHolder(mUpdateHolder, mLocalRep);\n mValidDraw = true;\n }\n\n public FilterCropRepresentation getFinalRepresentation() {\n return mLocalRep;\n }\n\n private void internallyUpdateLocalRep(RectF crop, RectF image) {\n FilterCropRepresentation.findNormalizedCrop(crop, (int) image.width(), (int) image.height());\n mGeometry.crop.set(crop);\n mUpdateHolder.set(mGeometry);\n mLocalRep.setCrop(crop);\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n float x = event.getX();\n float y = event.getY();\n if (mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n return true;\n }\n float[] touchPoint = { x, y };\n mDisplayMatrixInverse.mapPoints(touchPoint);\n x = touchPoint[0];\n y = touchPoint[1];\n switch(event.getActionMasked()) {\n case (MotionEvent.ACTION_DOWN):\n if (mState == Mode.NONE) {\n if (!mCropObj.selectEdge(x, y)) {\n mMovingBlock = mCropObj.selectEdge(CropObject.MOVE_BLOCK);\n }\n mPrevX = x;\n mPrevY = y;\n mState = Mode.MOVE;\n }\n break;\n case (MotionEvent.ACTION_UP):\n if (mState == Mode.MOVE) {\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n mMovingBlock = false;\n mPrevX = x;\n mPrevY = y;\n mState = Mode.NONE;\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n }\n break;\n case (MotionEvent.ACTION_MOVE):\n if (mState == Mode.MOVE) {\n float dx = x - mPrevX;\n float dy = y - mPrevY;\n mCropObj.moveCurrentSelection(dx, dy);\n mPrevX = x;\n mPrevY = y;\n }\n break;\n default:\n break;\n }\n invalidate();\n return true;\n }\n\n private void clearDisplay() {\n mDisplayMatrix = null;\n mDisplayMatrixInverse = null;\n invalidate();\n }\n\n public void applyFreeAspect() {\n mCropObj.unsetAspectRatio();\n invalidate();\n }\n\n public void applyOriginalAspect() {\n RectF outer = mCropObj.getOuterBounds();\n float w = outer.width();\n float h = outer.height();\n if (w > 0 && h > 0) {\n applyAspect(w, h);\n mCropObj.resetBoundsTo(outer, outer);\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n } else {\n Log.w(TAG, \"failed to set aspect ratio original\");\n }\n invalidate();\n }\n\n public void applyAspect(float x, float y) {\n if (x <= 0 || y <= 0) {\n throw new IllegalArgumentException(\"Bad arguments to applyAspect\");\n }\n // If we are rotated by 90 degrees from horizontal, swap x and y\n if (GeometryMathUtils.needsDimensionSwap(mGeometry.rotation)) {\n float tmp = x;\n x = y;\n y = tmp;\n }\n if (!mCropObj.setInnerAspectRatio(x, y)) {\n Log.w(TAG, \"failed to set aspect ratio\");\n }\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n invalidate();\n }\n\n /**\n * Rotates first d bits in integer x to the left some number of times.\n */\n private int bitCycleLeft(int x, int times, int d) {\n int mask = (1 << d) - 1;\n int mout = x & mask;\n times %= d;\n int hi = mout >> (d - times);\n int low = (mout << times) & mask;\n int ret = x & ~mask;\n ret |= low;\n ret |= hi;\n return ret;\n }\n\n /**\n * Find the selected edge or corner in screen coordinates.\n */\n ", "post_mask_code": "\n\n private void forceStateConsistency() {\n MasterImage master = MasterImage.getImage();\n Bitmap image = master.getFiltersOnlyImage();\n int width = image.getWidth();\n int height = image.getHeight();\n if (mCropObj == null || !mUpdateHolder.equals(mGeometry) || mImageBounds.width() != width || mImageBounds.height() != height || !mLocalRep.getCrop().equals(mUpdateHolder.crop)) {\n mImageBounds.set(0, 0, width, height);\n mGeometry.set(mUpdateHolder);\n mLocalRep.setCrop(mUpdateHolder.crop);\n RectF scaledCrop = new RectF(mUpdateHolder.crop);\n FilterCropRepresentation.findScaledCrop(scaledCrop, width, height);\n mCropObj = new CropObject(mImageBounds, scaledCrop, (int) mUpdateHolder.straighten);\n mState = Mode.NONE;\n clearDisplay();\n }\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n clearDisplay();\n }\n\n @Override\n public void onDraw(Canvas canvas) {\n Bitmap bitmap = MasterImage.getImage().getFiltersOnlyImage();\n if (bitmap == null) {\n MasterImage.getImage().invalidateFiltersOnly();\n }\n if (!mValidDraw || bitmap == null) {\n return;\n }\n forceStateConsistency();\n mImageBounds.set(0, 0, bitmap.getWidth(), bitmap.getHeight());\n // If display matrix doesn't exist, create it and its dependencies\n if (mDisplayCropMatrix == null || mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n mCropObj.unsetAspectRatio();\n mDisplayMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n float straighten = mGeometry.straighten;\n mGeometry.straighten = 0;\n mDisplayCropMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n mGeometry.straighten = straighten;\n mDisplayMatrixInverse = new Matrix();\n mDisplayMatrixInverse.reset();\n if (!mDisplayCropMatrix.invert(mDisplayMatrixInverse)) {\n Log.w(TAG, \"could not invert display matrix\");\n mDisplayMatrixInverse = null;\n return;\n }\n // Scale min side and tolerance by display matrix scale factor\n mCropObj.setMinInnerSideSize(mDisplayMatrixInverse.mapRadius(mMinSideSize));\n mCropObj.setTouchTolerance(mDisplayMatrixInverse.mapRadius(mTouchTolerance));\n // drive Crop engine to clamp to crop bounds\n int[] sides = { CropObject.MOVE_TOP, CropObject.MOVE_BOTTOM, CropObject.MOVE_LEFT, CropObject.MOVE_RIGHT };\n int delta = Math.min(canvas.getWidth(), canvas.getHeight()) / 4;\n int[] dx = { delta, -delta, 0, 0 };\n int[] dy = { 0, 0, delta, -delta };\n for (int i = 0; i < sides.length; i++) {\n mCropObj.selectEdge(sides[i]);\n mCropObj.moveCurrentSelection(dx[i], dy[i]);\n mCropObj.moveCurrentSelection(-dx[i], -dy[i]);\n }\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n }\n // Draw actual bitmap\n mPaint.reset();\n mPaint.setAntiAlias(true);\n mPaint.setFilterBitmap(true);\n canvas.drawBitmap(bitmap, mDisplayMatrix, mPaint);\n mCropObj.getInnerBounds(mScreenCropBounds);\n RectF outer = mCropObj.getOuterBounds();\n FilterCropRepresentation.findNormalizedCrop(mScreenCropBounds, (int) outer.width(), (int) outer.height());\n FilterCropRepresentation.findScaledCrop(mScreenCropBounds, bitmap.getWidth(), bitmap.getHeight());\n if (mDisplayCropMatrix.mapRect(mScreenCropBounds)) {\n // Draw crop rect and markers\n CropDrawingUtils.drawCropRect(canvas, mScreenCropBounds);\n CropDrawingUtils.drawShade(canvas, mScreenCropBounds);\n CropDrawingUtils.drawRuleOfThird(canvas, mScreenCropBounds);\n CropDrawingUtils.drawIndicators(canvas, mCropIndicator, mIndicatorSize, mScreenCropBounds, mCropObj.isFixedAspect(), decode(mCropObj.getSelectState(), mGeometry.rotation.value()));\n }\n }\n\n public void setEditor(EditorCrop editorCrop) {\n mEditorCrop = editorCrop;\n }\n}\n"} {"task_id": "Java_547", "language": "Java", "task_type": "if_statement", "source_file": "java/github/CyanogenMod/android_packages_apps_Gallery2/src/com/android/gallery3d/filtershow/imageshow/ImageCrop.java", "mask_start_position": 5741, "mask_end_position": 5854, "canonical_solution": "if (x <= 0 || y <= 0) {\n throw new IllegalArgumentException(\"Bad arguments to applyAspect\");\n }", "pre_mask_code": "package com.android.gallery3d.filtershow.imageshow;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.RectF;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport com.android.gallery3d.R;\nimport com.android.gallery3d.filtershow.crop.CropDrawingUtils;\nimport com.android.gallery3d.filtershow.crop.CropMath;\nimport com.android.gallery3d.filtershow.crop.CropObject;\nimport com.android.gallery3d.filtershow.editors.EditorCrop;\nimport com.android.gallery3d.filtershow.filters.FilterCropRepresentation;\nimport com.android.gallery3d.filtershow.imageshow.GeometryMathUtils.GeometryHolder;\n\npublic class ImageCrop extends ImageShow {\n\n private static final String TAG = ImageCrop.class.getSimpleName();\n\n private RectF mImageBounds = new RectF();\n\n private RectF mScreenCropBounds = new RectF();\n\n private Paint mPaint = new Paint();\n\n private CropObject mCropObj = null;\n\n private GeometryHolder mGeometry = new GeometryHolder();\n\n private GeometryHolder mUpdateHolder = new GeometryHolder();\n\n private Drawable mCropIndicator;\n\n private int mIndicatorSize;\n\n private boolean mMovingBlock = false;\n\n private Matrix mDisplayMatrix = null;\n\n private Matrix mDisplayCropMatrix = null;\n\n private Matrix mDisplayMatrixInverse = null;\n\n private float mPrevX = 0;\n\n private float mPrevY = 0;\n\n private int mMinSideSize = 90;\n\n private int mTouchTolerance = 40;\n\n private enum Mode {\n\n NONE, MOVE\n }\n\n private Mode mState = Mode.NONE;\n\n private boolean mValidDraw = false;\n\n FilterCropRepresentation mLocalRep = new FilterCropRepresentation();\n\n EditorCrop mEditorCrop;\n\n public ImageCrop(Context context) {\n super(context);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs) {\n super(context, attrs);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setup(context);\n }\n\n private void setup(Context context) {\n Resources rsc = context.getResources();\n mCropIndicator = rsc.getDrawable(R.drawable.camera_crop);\n mIndicatorSize = (int) rsc.getDimension(R.dimen.crop_indicator_size);\n mMinSideSize = (int) rsc.getDimension(R.dimen.crop_min_side);\n mTouchTolerance = (int) rsc.getDimension(R.dimen.crop_touch_tolerance);\n }\n\n public void setFilterCropRepresentation(FilterCropRepresentation crop) {\n mLocalRep = (crop == null) ? new FilterCropRepresentation() : crop;\n GeometryMathUtils.initializeHolder(mUpdateHolder, mLocalRep);\n mValidDraw = true;\n }\n\n public FilterCropRepresentation getFinalRepresentation() {\n return mLocalRep;\n }\n\n private void internallyUpdateLocalRep(RectF crop, RectF image) {\n FilterCropRepresentation.findNormalizedCrop(crop, (int) image.width(), (int) image.height());\n mGeometry.crop.set(crop);\n mUpdateHolder.set(mGeometry);\n mLocalRep.setCrop(crop);\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n float x = event.getX();\n float y = event.getY();\n if (mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n return true;\n }\n float[] touchPoint = { x, y };\n mDisplayMatrixInverse.mapPoints(touchPoint);\n x = touchPoint[0];\n y = touchPoint[1];\n switch(event.getActionMasked()) {\n case (MotionEvent.ACTION_DOWN):\n if (mState == Mode.NONE) {\n if (!mCropObj.selectEdge(x, y)) {\n mMovingBlock = mCropObj.selectEdge(CropObject.MOVE_BLOCK);\n }\n mPrevX = x;\n mPrevY = y;\n mState = Mode.MOVE;\n }\n break;\n case (MotionEvent.ACTION_UP):\n if (mState == Mode.MOVE) {\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n mMovingBlock = false;\n mPrevX = x;\n mPrevY = y;\n mState = Mode.NONE;\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n }\n break;\n case (MotionEvent.ACTION_MOVE):\n if (mState == Mode.MOVE) {\n float dx = x - mPrevX;\n float dy = y - mPrevY;\n mCropObj.moveCurrentSelection(dx, dy);\n mPrevX = x;\n mPrevY = y;\n }\n break;\n default:\n break;\n }\n invalidate();\n return true;\n }\n\n private void clearDisplay() {\n mDisplayMatrix = null;\n mDisplayMatrixInverse = null;\n invalidate();\n }\n\n public void applyFreeAspect() {\n mCropObj.unsetAspectRatio();\n invalidate();\n }\n\n public void applyOriginalAspect() {\n RectF outer = mCropObj.getOuterBounds();\n float w = outer.width();\n float h = outer.height();\n if (w > 0 && h > 0) {\n applyAspect(w, h);\n mCropObj.resetBoundsTo(outer, outer);\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n } else {\n Log.w(TAG, \"failed to set aspect ratio original\");\n }\n invalidate();\n }\n\n public void applyAspect(float x, float y) {\n ", "post_mask_code": "\n // If we are rotated by 90 degrees from horizontal, swap x and y\n if (GeometryMathUtils.needsDimensionSwap(mGeometry.rotation)) {\n float tmp = x;\n x = y;\n y = tmp;\n }\n if (!mCropObj.setInnerAspectRatio(x, y)) {\n Log.w(TAG, \"failed to set aspect ratio\");\n }\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n invalidate();\n }\n\n /**\n * Rotates first d bits in integer x to the left some number of times.\n */\n private int bitCycleLeft(int x, int times, int d) {\n int mask = (1 << d) - 1;\n int mout = x & mask;\n times %= d;\n int hi = mout >> (d - times);\n int low = (mout << times) & mask;\n int ret = x & ~mask;\n ret |= low;\n ret |= hi;\n return ret;\n }\n\n /**\n * Find the selected edge or corner in screen coordinates.\n */\n private int decode(int movingEdges, float rotation) {\n int rot = CropMath.constrainedRotation(rotation);\n switch(rot) {\n case 90:\n return bitCycleLeft(movingEdges, 1, 4);\n case 180:\n return bitCycleLeft(movingEdges, 2, 4);\n case 270:\n return bitCycleLeft(movingEdges, 3, 4);\n default:\n return movingEdges;\n }\n }\n\n private void forceStateConsistency() {\n MasterImage master = MasterImage.getImage();\n Bitmap image = master.getFiltersOnlyImage();\n int width = image.getWidth();\n int height = image.getHeight();\n if (mCropObj == null || !mUpdateHolder.equals(mGeometry) || mImageBounds.width() != width || mImageBounds.height() != height || !mLocalRep.getCrop().equals(mUpdateHolder.crop)) {\n mImageBounds.set(0, 0, width, height);\n mGeometry.set(mUpdateHolder);\n mLocalRep.setCrop(mUpdateHolder.crop);\n RectF scaledCrop = new RectF(mUpdateHolder.crop);\n FilterCropRepresentation.findScaledCrop(scaledCrop, width, height);\n mCropObj = new CropObject(mImageBounds, scaledCrop, (int) mUpdateHolder.straighten);\n mState = Mode.NONE;\n clearDisplay();\n }\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n clearDisplay();\n }\n\n @Override\n public void onDraw(Canvas canvas) {\n Bitmap bitmap = MasterImage.getImage().getFiltersOnlyImage();\n if (bitmap == null) {\n MasterImage.getImage().invalidateFiltersOnly();\n }\n if (!mValidDraw || bitmap == null) {\n return;\n }\n forceStateConsistency();\n mImageBounds.set(0, 0, bitmap.getWidth(), bitmap.getHeight());\n // If display matrix doesn't exist, create it and its dependencies\n if (mDisplayCropMatrix == null || mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n mCropObj.unsetAspectRatio();\n mDisplayMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n float straighten = mGeometry.straighten;\n mGeometry.straighten = 0;\n mDisplayCropMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n mGeometry.straighten = straighten;\n mDisplayMatrixInverse = new Matrix();\n mDisplayMatrixInverse.reset();\n if (!mDisplayCropMatrix.invert(mDisplayMatrixInverse)) {\n Log.w(TAG, \"could not invert display matrix\");\n mDisplayMatrixInverse = null;\n return;\n }\n // Scale min side and tolerance by display matrix scale factor\n mCropObj.setMinInnerSideSize(mDisplayMatrixInverse.mapRadius(mMinSideSize));\n mCropObj.setTouchTolerance(mDisplayMatrixInverse.mapRadius(mTouchTolerance));\n // drive Crop engine to clamp to crop bounds\n int[] sides = { CropObject.MOVE_TOP, CropObject.MOVE_BOTTOM, CropObject.MOVE_LEFT, CropObject.MOVE_RIGHT };\n int delta = Math.min(canvas.getWidth(), canvas.getHeight()) / 4;\n int[] dx = { delta, -delta, 0, 0 };\n int[] dy = { 0, 0, delta, -delta };\n for (int i = 0; i < sides.length; i++) {\n mCropObj.selectEdge(sides[i]);\n mCropObj.moveCurrentSelection(dx[i], dy[i]);\n mCropObj.moveCurrentSelection(-dx[i], -dy[i]);\n }\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n }\n // Draw actual bitmap\n mPaint.reset();\n mPaint.setAntiAlias(true);\n mPaint.setFilterBitmap(true);\n canvas.drawBitmap(bitmap, mDisplayMatrix, mPaint);\n mCropObj.getInnerBounds(mScreenCropBounds);\n RectF outer = mCropObj.getOuterBounds();\n FilterCropRepresentation.findNormalizedCrop(mScreenCropBounds, (int) outer.width(), (int) outer.height());\n FilterCropRepresentation.findScaledCrop(mScreenCropBounds, bitmap.getWidth(), bitmap.getHeight());\n if (mDisplayCropMatrix.mapRect(mScreenCropBounds)) {\n // Draw crop rect and markers\n CropDrawingUtils.drawCropRect(canvas, mScreenCropBounds);\n CropDrawingUtils.drawShade(canvas, mScreenCropBounds);\n CropDrawingUtils.drawRuleOfThird(canvas, mScreenCropBounds);\n CropDrawingUtils.drawIndicators(canvas, mCropIndicator, mIndicatorSize, mScreenCropBounds, mCropObj.isFixedAspect(), decode(mCropObj.getSelectState(), mGeometry.rotation.value()));\n }\n }\n\n public void setEditor(EditorCrop editorCrop) {\n mEditorCrop = editorCrop;\n }\n}\n"} {"task_id": "Java_548", "language": "Java", "task_type": "switch_case", "source_file": "java/github/CyanogenMod/android_packages_apps_Gallery2/src/com/android/gallery3d/filtershow/imageshow/ImageCrop.java", "mask_start_position": 6916, "mask_end_position": 7229, "canonical_solution": "switch(rot) {\n case 90:\n return bitCycleLeft(movingEdges, 1, 4);\n case 180:\n return bitCycleLeft(movingEdges, 2, 4);\n case 270:\n return bitCycleLeft(movingEdges, 3, 4);\n default:\n return movingEdges;\n }", "pre_mask_code": "package com.android.gallery3d.filtershow.imageshow;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.RectF;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport com.android.gallery3d.R;\nimport com.android.gallery3d.filtershow.crop.CropDrawingUtils;\nimport com.android.gallery3d.filtershow.crop.CropMath;\nimport com.android.gallery3d.filtershow.crop.CropObject;\nimport com.android.gallery3d.filtershow.editors.EditorCrop;\nimport com.android.gallery3d.filtershow.filters.FilterCropRepresentation;\nimport com.android.gallery3d.filtershow.imageshow.GeometryMathUtils.GeometryHolder;\n\npublic class ImageCrop extends ImageShow {\n\n private static final String TAG = ImageCrop.class.getSimpleName();\n\n private RectF mImageBounds = new RectF();\n\n private RectF mScreenCropBounds = new RectF();\n\n private Paint mPaint = new Paint();\n\n private CropObject mCropObj = null;\n\n private GeometryHolder mGeometry = new GeometryHolder();\n\n private GeometryHolder mUpdateHolder = new GeometryHolder();\n\n private Drawable mCropIndicator;\n\n private int mIndicatorSize;\n\n private boolean mMovingBlock = false;\n\n private Matrix mDisplayMatrix = null;\n\n private Matrix mDisplayCropMatrix = null;\n\n private Matrix mDisplayMatrixInverse = null;\n\n private float mPrevX = 0;\n\n private float mPrevY = 0;\n\n private int mMinSideSize = 90;\n\n private int mTouchTolerance = 40;\n\n private enum Mode {\n\n NONE, MOVE\n }\n\n private Mode mState = Mode.NONE;\n\n private boolean mValidDraw = false;\n\n FilterCropRepresentation mLocalRep = new FilterCropRepresentation();\n\n EditorCrop mEditorCrop;\n\n public ImageCrop(Context context) {\n super(context);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs) {\n super(context, attrs);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setup(context);\n }\n\n private void setup(Context context) {\n Resources rsc = context.getResources();\n mCropIndicator = rsc.getDrawable(R.drawable.camera_crop);\n mIndicatorSize = (int) rsc.getDimension(R.dimen.crop_indicator_size);\n mMinSideSize = (int) rsc.getDimension(R.dimen.crop_min_side);\n mTouchTolerance = (int) rsc.getDimension(R.dimen.crop_touch_tolerance);\n }\n\n public void setFilterCropRepresentation(FilterCropRepresentation crop) {\n mLocalRep = (crop == null) ? new FilterCropRepresentation() : crop;\n GeometryMathUtils.initializeHolder(mUpdateHolder, mLocalRep);\n mValidDraw = true;\n }\n\n public FilterCropRepresentation getFinalRepresentation() {\n return mLocalRep;\n }\n\n private void internallyUpdateLocalRep(RectF crop, RectF image) {\n FilterCropRepresentation.findNormalizedCrop(crop, (int) image.width(), (int) image.height());\n mGeometry.crop.set(crop);\n mUpdateHolder.set(mGeometry);\n mLocalRep.setCrop(crop);\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n float x = event.getX();\n float y = event.getY();\n if (mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n return true;\n }\n float[] touchPoint = { x, y };\n mDisplayMatrixInverse.mapPoints(touchPoint);\n x = touchPoint[0];\n y = touchPoint[1];\n switch(event.getActionMasked()) {\n case (MotionEvent.ACTION_DOWN):\n if (mState == Mode.NONE) {\n if (!mCropObj.selectEdge(x, y)) {\n mMovingBlock = mCropObj.selectEdge(CropObject.MOVE_BLOCK);\n }\n mPrevX = x;\n mPrevY = y;\n mState = Mode.MOVE;\n }\n break;\n case (MotionEvent.ACTION_UP):\n if (mState == Mode.MOVE) {\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n mMovingBlock = false;\n mPrevX = x;\n mPrevY = y;\n mState = Mode.NONE;\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n }\n break;\n case (MotionEvent.ACTION_MOVE):\n if (mState == Mode.MOVE) {\n float dx = x - mPrevX;\n float dy = y - mPrevY;\n mCropObj.moveCurrentSelection(dx, dy);\n mPrevX = x;\n mPrevY = y;\n }\n break;\n default:\n break;\n }\n invalidate();\n return true;\n }\n\n private void clearDisplay() {\n mDisplayMatrix = null;\n mDisplayMatrixInverse = null;\n invalidate();\n }\n\n public void applyFreeAspect() {\n mCropObj.unsetAspectRatio();\n invalidate();\n }\n\n public void applyOriginalAspect() {\n RectF outer = mCropObj.getOuterBounds();\n float w = outer.width();\n float h = outer.height();\n if (w > 0 && h > 0) {\n applyAspect(w, h);\n mCropObj.resetBoundsTo(outer, outer);\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n } else {\n Log.w(TAG, \"failed to set aspect ratio original\");\n }\n invalidate();\n }\n\n public void applyAspect(float x, float y) {\n if (x <= 0 || y <= 0) {\n throw new IllegalArgumentException(\"Bad arguments to applyAspect\");\n }\n // If we are rotated by 90 degrees from horizontal, swap x and y\n if (GeometryMathUtils.needsDimensionSwap(mGeometry.rotation)) {\n float tmp = x;\n x = y;\n y = tmp;\n }\n if (!mCropObj.setInnerAspectRatio(x, y)) {\n Log.w(TAG, \"failed to set aspect ratio\");\n }\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n invalidate();\n }\n\n /**\n * Rotates first d bits in integer x to the left some number of times.\n */\n private int bitCycleLeft(int x, int times, int d) {\n int mask = (1 << d) - 1;\n int mout = x & mask;\n times %= d;\n int hi = mout >> (d - times);\n int low = (mout << times) & mask;\n int ret = x & ~mask;\n ret |= low;\n ret |= hi;\n return ret;\n }\n\n /**\n * Find the selected edge or corner in screen coordinates.\n */\n private int decode(int movingEdges, float rotation) {\n int rot = CropMath.constrainedRotation(rotation);\n ", "post_mask_code": "\n }\n\n private void forceStateConsistency() {\n MasterImage master = MasterImage.getImage();\n Bitmap image = master.getFiltersOnlyImage();\n int width = image.getWidth();\n int height = image.getHeight();\n if (mCropObj == null || !mUpdateHolder.equals(mGeometry) || mImageBounds.width() != width || mImageBounds.height() != height || !mLocalRep.getCrop().equals(mUpdateHolder.crop)) {\n mImageBounds.set(0, 0, width, height);\n mGeometry.set(mUpdateHolder);\n mLocalRep.setCrop(mUpdateHolder.crop);\n RectF scaledCrop = new RectF(mUpdateHolder.crop);\n FilterCropRepresentation.findScaledCrop(scaledCrop, width, height);\n mCropObj = new CropObject(mImageBounds, scaledCrop, (int) mUpdateHolder.straighten);\n mState = Mode.NONE;\n clearDisplay();\n }\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n clearDisplay();\n }\n\n @Override\n public void onDraw(Canvas canvas) {\n Bitmap bitmap = MasterImage.getImage().getFiltersOnlyImage();\n if (bitmap == null) {\n MasterImage.getImage().invalidateFiltersOnly();\n }\n if (!mValidDraw || bitmap == null) {\n return;\n }\n forceStateConsistency();\n mImageBounds.set(0, 0, bitmap.getWidth(), bitmap.getHeight());\n // If display matrix doesn't exist, create it and its dependencies\n if (mDisplayCropMatrix == null || mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n mCropObj.unsetAspectRatio();\n mDisplayMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n float straighten = mGeometry.straighten;\n mGeometry.straighten = 0;\n mDisplayCropMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n mGeometry.straighten = straighten;\n mDisplayMatrixInverse = new Matrix();\n mDisplayMatrixInverse.reset();\n if (!mDisplayCropMatrix.invert(mDisplayMatrixInverse)) {\n Log.w(TAG, \"could not invert display matrix\");\n mDisplayMatrixInverse = null;\n return;\n }\n // Scale min side and tolerance by display matrix scale factor\n mCropObj.setMinInnerSideSize(mDisplayMatrixInverse.mapRadius(mMinSideSize));\n mCropObj.setTouchTolerance(mDisplayMatrixInverse.mapRadius(mTouchTolerance));\n // drive Crop engine to clamp to crop bounds\n int[] sides = { CropObject.MOVE_TOP, CropObject.MOVE_BOTTOM, CropObject.MOVE_LEFT, CropObject.MOVE_RIGHT };\n int delta = Math.min(canvas.getWidth(), canvas.getHeight()) / 4;\n int[] dx = { delta, -delta, 0, 0 };\n int[] dy = { 0, 0, delta, -delta };\n for (int i = 0; i < sides.length; i++) {\n mCropObj.selectEdge(sides[i]);\n mCropObj.moveCurrentSelection(dx[i], dy[i]);\n mCropObj.moveCurrentSelection(-dx[i], -dy[i]);\n }\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n }\n // Draw actual bitmap\n mPaint.reset();\n mPaint.setAntiAlias(true);\n mPaint.setFilterBitmap(true);\n canvas.drawBitmap(bitmap, mDisplayMatrix, mPaint);\n mCropObj.getInnerBounds(mScreenCropBounds);\n RectF outer = mCropObj.getOuterBounds();\n FilterCropRepresentation.findNormalizedCrop(mScreenCropBounds, (int) outer.width(), (int) outer.height());\n FilterCropRepresentation.findScaledCrop(mScreenCropBounds, bitmap.getWidth(), bitmap.getHeight());\n if (mDisplayCropMatrix.mapRect(mScreenCropBounds)) {\n // Draw crop rect and markers\n CropDrawingUtils.drawCropRect(canvas, mScreenCropBounds);\n CropDrawingUtils.drawShade(canvas, mScreenCropBounds);\n CropDrawingUtils.drawRuleOfThird(canvas, mScreenCropBounds);\n CropDrawingUtils.drawIndicators(canvas, mCropIndicator, mIndicatorSize, mScreenCropBounds, mCropObj.isFixedAspect(), decode(mCropObj.getSelectState(), mGeometry.rotation.value()));\n }\n }\n\n public void setEditor(EditorCrop editorCrop) {\n mEditorCrop = editorCrop;\n }\n}\n"} {"task_id": "Java_549", "language": "Java", "task_type": "for_statement", "source_file": "java/github/CyanogenMod/android_packages_apps_Gallery2/src/com/android/gallery3d/filtershow/imageshow/ImageCrop.java", "mask_start_position": 10293, "mask_end_position": 10518, "canonical_solution": "for (int i = 0; i < sides.length; i++) {\n mCropObj.selectEdge(sides[i]);\n mCropObj.moveCurrentSelection(dx[i], dy[i]);\n mCropObj.moveCurrentSelection(-dx[i], -dy[i]);\n }", "pre_mask_code": "package com.android.gallery3d.filtershow.imageshow;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.RectF;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport com.android.gallery3d.R;\nimport com.android.gallery3d.filtershow.crop.CropDrawingUtils;\nimport com.android.gallery3d.filtershow.crop.CropMath;\nimport com.android.gallery3d.filtershow.crop.CropObject;\nimport com.android.gallery3d.filtershow.editors.EditorCrop;\nimport com.android.gallery3d.filtershow.filters.FilterCropRepresentation;\nimport com.android.gallery3d.filtershow.imageshow.GeometryMathUtils.GeometryHolder;\n\npublic class ImageCrop extends ImageShow {\n\n private static final String TAG = ImageCrop.class.getSimpleName();\n\n private RectF mImageBounds = new RectF();\n\n private RectF mScreenCropBounds = new RectF();\n\n private Paint mPaint = new Paint();\n\n private CropObject mCropObj = null;\n\n private GeometryHolder mGeometry = new GeometryHolder();\n\n private GeometryHolder mUpdateHolder = new GeometryHolder();\n\n private Drawable mCropIndicator;\n\n private int mIndicatorSize;\n\n private boolean mMovingBlock = false;\n\n private Matrix mDisplayMatrix = null;\n\n private Matrix mDisplayCropMatrix = null;\n\n private Matrix mDisplayMatrixInverse = null;\n\n private float mPrevX = 0;\n\n private float mPrevY = 0;\n\n private int mMinSideSize = 90;\n\n private int mTouchTolerance = 40;\n\n private enum Mode {\n\n NONE, MOVE\n }\n\n private Mode mState = Mode.NONE;\n\n private boolean mValidDraw = false;\n\n FilterCropRepresentation mLocalRep = new FilterCropRepresentation();\n\n EditorCrop mEditorCrop;\n\n public ImageCrop(Context context) {\n super(context);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs) {\n super(context, attrs);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setup(context);\n }\n\n private void setup(Context context) {\n Resources rsc = context.getResources();\n mCropIndicator = rsc.getDrawable(R.drawable.camera_crop);\n mIndicatorSize = (int) rsc.getDimension(R.dimen.crop_indicator_size);\n mMinSideSize = (int) rsc.getDimension(R.dimen.crop_min_side);\n mTouchTolerance = (int) rsc.getDimension(R.dimen.crop_touch_tolerance);\n }\n\n public void setFilterCropRepresentation(FilterCropRepresentation crop) {\n mLocalRep = (crop == null) ? new FilterCropRepresentation() : crop;\n GeometryMathUtils.initializeHolder(mUpdateHolder, mLocalRep);\n mValidDraw = true;\n }\n\n public FilterCropRepresentation getFinalRepresentation() {\n return mLocalRep;\n }\n\n private void internallyUpdateLocalRep(RectF crop, RectF image) {\n FilterCropRepresentation.findNormalizedCrop(crop, (int) image.width(), (int) image.height());\n mGeometry.crop.set(crop);\n mUpdateHolder.set(mGeometry);\n mLocalRep.setCrop(crop);\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n float x = event.getX();\n float y = event.getY();\n if (mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n return true;\n }\n float[] touchPoint = { x, y };\n mDisplayMatrixInverse.mapPoints(touchPoint);\n x = touchPoint[0];\n y = touchPoint[1];\n switch(event.getActionMasked()) {\n case (MotionEvent.ACTION_DOWN):\n if (mState == Mode.NONE) {\n if (!mCropObj.selectEdge(x, y)) {\n mMovingBlock = mCropObj.selectEdge(CropObject.MOVE_BLOCK);\n }\n mPrevX = x;\n mPrevY = y;\n mState = Mode.MOVE;\n }\n break;\n case (MotionEvent.ACTION_UP):\n if (mState == Mode.MOVE) {\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n mMovingBlock = false;\n mPrevX = x;\n mPrevY = y;\n mState = Mode.NONE;\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n }\n break;\n case (MotionEvent.ACTION_MOVE):\n if (mState == Mode.MOVE) {\n float dx = x - mPrevX;\n float dy = y - mPrevY;\n mCropObj.moveCurrentSelection(dx, dy);\n mPrevX = x;\n mPrevY = y;\n }\n break;\n default:\n break;\n }\n invalidate();\n return true;\n }\n\n private void clearDisplay() {\n mDisplayMatrix = null;\n mDisplayMatrixInverse = null;\n invalidate();\n }\n\n public void applyFreeAspect() {\n mCropObj.unsetAspectRatio();\n invalidate();\n }\n\n public void applyOriginalAspect() {\n RectF outer = mCropObj.getOuterBounds();\n float w = outer.width();\n float h = outer.height();\n if (w > 0 && h > 0) {\n applyAspect(w, h);\n mCropObj.resetBoundsTo(outer, outer);\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n } else {\n Log.w(TAG, \"failed to set aspect ratio original\");\n }\n invalidate();\n }\n\n public void applyAspect(float x, float y) {\n if (x <= 0 || y <= 0) {\n throw new IllegalArgumentException(\"Bad arguments to applyAspect\");\n }\n // If we are rotated by 90 degrees from horizontal, swap x and y\n if (GeometryMathUtils.needsDimensionSwap(mGeometry.rotation)) {\n float tmp = x;\n x = y;\n y = tmp;\n }\n if (!mCropObj.setInnerAspectRatio(x, y)) {\n Log.w(TAG, \"failed to set aspect ratio\");\n }\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n invalidate();\n }\n\n /**\n * Rotates first d bits in integer x to the left some number of times.\n */\n private int bitCycleLeft(int x, int times, int d) {\n int mask = (1 << d) - 1;\n int mout = x & mask;\n times %= d;\n int hi = mout >> (d - times);\n int low = (mout << times) & mask;\n int ret = x & ~mask;\n ret |= low;\n ret |= hi;\n return ret;\n }\n\n /**\n * Find the selected edge or corner in screen coordinates.\n */\n private int decode(int movingEdges, float rotation) {\n int rot = CropMath.constrainedRotation(rotation);\n switch(rot) {\n case 90:\n return bitCycleLeft(movingEdges, 1, 4);\n case 180:\n return bitCycleLeft(movingEdges, 2, 4);\n case 270:\n return bitCycleLeft(movingEdges, 3, 4);\n default:\n return movingEdges;\n }\n }\n\n private void forceStateConsistency() {\n MasterImage master = MasterImage.getImage();\n Bitmap image = master.getFiltersOnlyImage();\n int width = image.getWidth();\n int height = image.getHeight();\n if (mCropObj == null || !mUpdateHolder.equals(mGeometry) || mImageBounds.width() != width || mImageBounds.height() != height || !mLocalRep.getCrop().equals(mUpdateHolder.crop)) {\n mImageBounds.set(0, 0, width, height);\n mGeometry.set(mUpdateHolder);\n mLocalRep.setCrop(mUpdateHolder.crop);\n RectF scaledCrop = new RectF(mUpdateHolder.crop);\n FilterCropRepresentation.findScaledCrop(scaledCrop, width, height);\n mCropObj = new CropObject(mImageBounds, scaledCrop, (int) mUpdateHolder.straighten);\n mState = Mode.NONE;\n clearDisplay();\n }\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n clearDisplay();\n }\n\n @Override\n public void onDraw(Canvas canvas) {\n Bitmap bitmap = MasterImage.getImage().getFiltersOnlyImage();\n if (bitmap == null) {\n MasterImage.getImage().invalidateFiltersOnly();\n }\n if (!mValidDraw || bitmap == null) {\n return;\n }\n forceStateConsistency();\n mImageBounds.set(0, 0, bitmap.getWidth(), bitmap.getHeight());\n // If display matrix doesn't exist, create it and its dependencies\n if (mDisplayCropMatrix == null || mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n mCropObj.unsetAspectRatio();\n mDisplayMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n float straighten = mGeometry.straighten;\n mGeometry.straighten = 0;\n mDisplayCropMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n mGeometry.straighten = straighten;\n mDisplayMatrixInverse = new Matrix();\n mDisplayMatrixInverse.reset();\n if (!mDisplayCropMatrix.invert(mDisplayMatrixInverse)) {\n Log.w(TAG, \"could not invert display matrix\");\n mDisplayMatrixInverse = null;\n return;\n }\n // Scale min side and tolerance by display matrix scale factor\n mCropObj.setMinInnerSideSize(mDisplayMatrixInverse.mapRadius(mMinSideSize));\n mCropObj.setTouchTolerance(mDisplayMatrixInverse.mapRadius(mTouchTolerance));\n // drive Crop engine to clamp to crop bounds\n int[] sides = { CropObject.MOVE_TOP, CropObject.MOVE_BOTTOM, CropObject.MOVE_LEFT, CropObject.MOVE_RIGHT };\n int delta = Math.min(canvas.getWidth(), canvas.getHeight()) / 4;\n int[] dx = { delta, -delta, 0, 0 };\n int[] dy = { 0, 0, delta, -delta };\n ", "post_mask_code": "\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n }\n // Draw actual bitmap\n mPaint.reset();\n mPaint.setAntiAlias(true);\n mPaint.setFilterBitmap(true);\n canvas.drawBitmap(bitmap, mDisplayMatrix, mPaint);\n mCropObj.getInnerBounds(mScreenCropBounds);\n RectF outer = mCropObj.getOuterBounds();\n FilterCropRepresentation.findNormalizedCrop(mScreenCropBounds, (int) outer.width(), (int) outer.height());\n FilterCropRepresentation.findScaledCrop(mScreenCropBounds, bitmap.getWidth(), bitmap.getHeight());\n if (mDisplayCropMatrix.mapRect(mScreenCropBounds)) {\n // Draw crop rect and markers\n CropDrawingUtils.drawCropRect(canvas, mScreenCropBounds);\n CropDrawingUtils.drawShade(canvas, mScreenCropBounds);\n CropDrawingUtils.drawRuleOfThird(canvas, mScreenCropBounds);\n CropDrawingUtils.drawIndicators(canvas, mCropIndicator, mIndicatorSize, mScreenCropBounds, mCropObj.isFixedAspect(), decode(mCropObj.getSelectState(), mGeometry.rotation.value()));\n }\n }\n\n public void setEditor(EditorCrop editorCrop) {\n mEditorCrop = editorCrop;\n }\n}\n"} {"task_id": "Java_550", "language": "Java", "task_type": "empty", "source_file": "java/github/CyanogenMod/android_packages_apps_Gallery2/src/com/android/gallery3d/filtershow/imageshow/ImageCrop.java", "mask_start_position": 3811, "mask_end_position": 3811, "canonical_solution": "", "pre_mask_code": "package com.android.gallery3d.filtershow.imageshow;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Matrix;\nimport android.graphics.Paint;\nimport android.graphics.RectF;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport com.android.gallery3d.R;\nimport com.android.gallery3d.filtershow.crop.CropDrawingUtils;\nimport com.android.gallery3d.filtershow.crop.CropMath;\nimport com.android.gallery3d.filtershow.crop.CropObject;\nimport com.android.gallery3d.filtershow.editors.EditorCrop;\nimport com.android.gallery3d.filtershow.filters.FilterCropRepresentation;\nimport com.android.gallery3d.filtershow.imageshow.GeometryMathUtils.GeometryHolder;\n\npublic class ImageCrop extends ImageShow {\n\n private static final String TAG = ImageCrop.class.getSimpleName();\n\n private RectF mImageBounds = new RectF();\n\n private RectF mScreenCropBounds = new RectF();\n\n private Paint mPaint = new Paint();\n\n private CropObject mCropObj = null;\n\n private GeometryHolder mGeometry = new GeometryHolder();\n\n private GeometryHolder mUpdateHolder = new GeometryHolder();\n\n private Drawable mCropIndicator;\n\n private int mIndicatorSize;\n\n private boolean mMovingBlock = false;\n\n private Matrix mDisplayMatrix = null;\n\n private Matrix mDisplayCropMatrix = null;\n\n private Matrix mDisplayMatrixInverse = null;\n\n private float mPrevX = 0;\n\n private float mPrevY = 0;\n\n private int mMinSideSize = 90;\n\n private int mTouchTolerance = 40;\n\n private enum Mode {\n\n NONE, MOVE\n }\n\n private Mode mState = Mode.NONE;\n\n private boolean mValidDraw = false;\n\n FilterCropRepresentation mLocalRep = new FilterCropRepresentation();\n\n EditorCrop mEditorCrop;\n\n public ImageCrop(Context context) {\n super(context);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs) {\n super(context, attrs);\n setup(context);\n }\n\n public ImageCrop(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n setup(context);\n }\n\n private void setup(Context context) {\n Resources rsc = context.getResources();\n mCropIndicator = rsc.getDrawable(R.drawable.camera_crop);\n mIndicatorSize = (int) rsc.getDimension(R.dimen.crop_indicator_size);\n mMinSideSize = (int) rsc.getDimension(R.dimen.crop_min_side);\n mTouchTolerance = (int) rsc.getDimension(R.dimen.crop_touch_tolerance);\n }\n\n public void setFilterCropRepresentation(FilterCropRepresentation crop) {\n mLocalRep = (crop == null) ? new FilterCropRepresentation() : crop;\n GeometryMathUtils.initializeHolder(mUpdateHolder, mLocalRep);\n mValidDraw = true;\n }\n\n public FilterCropRepresentation getFinalRepresentation() {\n return mLocalRep;\n }\n\n private void internallyUpdateLocalRep(RectF crop, RectF image) {\n FilterCropRepresentation.findNormalizedCrop(crop, (int) image.width(), (int) image.height());\n mGeometry.crop.set(crop);\n mUpdateHolder.set(mGeometry);\n mLocalRep.setCrop(crop);\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n float x = event.getX();\n float y = event.getY();\n if (mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n return true;\n }\n float[] touchPoint = { x, y };\n mDisplayMatrixInverse.mapPoints(touchPoint);\n x = touchPoint[0];\n y = touchPoint[1];\n switch(event.getActionMasked()) {\n case (MotionEvent.ACTION_DOWN):\n if (mState == Mode.NONE) {\n ", "post_mask_code": " if (!mCropObj.selectEdge(x, y)) {\n mMovingBlock = mCropObj.selectEdge(CropObject.MOVE_BLOCK);\n }\n mPrevX = x;\n mPrevY = y;\n mState = Mode.MOVE;\n }\n break;\n case (MotionEvent.ACTION_UP):\n if (mState == Mode.MOVE) {\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n mMovingBlock = false;\n mPrevX = x;\n mPrevY = y;\n mState = Mode.NONE;\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n }\n break;\n case (MotionEvent.ACTION_MOVE):\n if (mState == Mode.MOVE) {\n float dx = x - mPrevX;\n float dy = y - mPrevY;\n mCropObj.moveCurrentSelection(dx, dy);\n mPrevX = x;\n mPrevY = y;\n }\n break;\n default:\n break;\n }\n invalidate();\n return true;\n }\n\n private void clearDisplay() {\n mDisplayMatrix = null;\n mDisplayMatrixInverse = null;\n invalidate();\n }\n\n public void applyFreeAspect() {\n mCropObj.unsetAspectRatio();\n invalidate();\n }\n\n public void applyOriginalAspect() {\n RectF outer = mCropObj.getOuterBounds();\n float w = outer.width();\n float h = outer.height();\n if (w > 0 && h > 0) {\n applyAspect(w, h);\n mCropObj.resetBoundsTo(outer, outer);\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n } else {\n Log.w(TAG, \"failed to set aspect ratio original\");\n }\n invalidate();\n }\n\n public void applyAspect(float x, float y) {\n if (x <= 0 || y <= 0) {\n throw new IllegalArgumentException(\"Bad arguments to applyAspect\");\n }\n // If we are rotated by 90 degrees from horizontal, swap x and y\n if (GeometryMathUtils.needsDimensionSwap(mGeometry.rotation)) {\n float tmp = x;\n x = y;\n y = tmp;\n }\n if (!mCropObj.setInnerAspectRatio(x, y)) {\n Log.w(TAG, \"failed to set aspect ratio\");\n }\n internallyUpdateLocalRep(mCropObj.getInnerBounds(), mCropObj.getOuterBounds());\n invalidate();\n }\n\n /**\n * Rotates first d bits in integer x to the left some number of times.\n */\n private int bitCycleLeft(int x, int times, int d) {\n int mask = (1 << d) - 1;\n int mout = x & mask;\n times %= d;\n int hi = mout >> (d - times);\n int low = (mout << times) & mask;\n int ret = x & ~mask;\n ret |= low;\n ret |= hi;\n return ret;\n }\n\n /**\n * Find the selected edge or corner in screen coordinates.\n */\n private int decode(int movingEdges, float rotation) {\n int rot = CropMath.constrainedRotation(rotation);\n switch(rot) {\n case 90:\n return bitCycleLeft(movingEdges, 1, 4);\n case 180:\n return bitCycleLeft(movingEdges, 2, 4);\n case 270:\n return bitCycleLeft(movingEdges, 3, 4);\n default:\n return movingEdges;\n }\n }\n\n private void forceStateConsistency() {\n MasterImage master = MasterImage.getImage();\n Bitmap image = master.getFiltersOnlyImage();\n int width = image.getWidth();\n int height = image.getHeight();\n if (mCropObj == null || !mUpdateHolder.equals(mGeometry) || mImageBounds.width() != width || mImageBounds.height() != height || !mLocalRep.getCrop().equals(mUpdateHolder.crop)) {\n mImageBounds.set(0, 0, width, height);\n mGeometry.set(mUpdateHolder);\n mLocalRep.setCrop(mUpdateHolder.crop);\n RectF scaledCrop = new RectF(mUpdateHolder.crop);\n FilterCropRepresentation.findScaledCrop(scaledCrop, width, height);\n mCropObj = new CropObject(mImageBounds, scaledCrop, (int) mUpdateHolder.straighten);\n mState = Mode.NONE;\n clearDisplay();\n }\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n clearDisplay();\n }\n\n @Override\n public void onDraw(Canvas canvas) {\n Bitmap bitmap = MasterImage.getImage().getFiltersOnlyImage();\n if (bitmap == null) {\n MasterImage.getImage().invalidateFiltersOnly();\n }\n if (!mValidDraw || bitmap == null) {\n return;\n }\n forceStateConsistency();\n mImageBounds.set(0, 0, bitmap.getWidth(), bitmap.getHeight());\n // If display matrix doesn't exist, create it and its dependencies\n if (mDisplayCropMatrix == null || mDisplayMatrix == null || mDisplayMatrixInverse == null) {\n mCropObj.unsetAspectRatio();\n mDisplayMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n float straighten = mGeometry.straighten;\n mGeometry.straighten = 0;\n mDisplayCropMatrix = GeometryMathUtils.getFullGeometryToScreenMatrix(mGeometry, bitmap.getWidth(), bitmap.getHeight(), canvas.getWidth(), canvas.getHeight());\n mGeometry.straighten = straighten;\n mDisplayMatrixInverse = new Matrix();\n mDisplayMatrixInverse.reset();\n if (!mDisplayCropMatrix.invert(mDisplayMatrixInverse)) {\n Log.w(TAG, \"could not invert display matrix\");\n mDisplayMatrixInverse = null;\n return;\n }\n // Scale min side and tolerance by display matrix scale factor\n mCropObj.setMinInnerSideSize(mDisplayMatrixInverse.mapRadius(mMinSideSize));\n mCropObj.setTouchTolerance(mDisplayMatrixInverse.mapRadius(mTouchTolerance));\n // drive Crop engine to clamp to crop bounds\n int[] sides = { CropObject.MOVE_TOP, CropObject.MOVE_BOTTOM, CropObject.MOVE_LEFT, CropObject.MOVE_RIGHT };\n int delta = Math.min(canvas.getWidth(), canvas.getHeight()) / 4;\n int[] dx = { delta, -delta, 0, 0 };\n int[] dy = { 0, 0, delta, -delta };\n for (int i = 0; i < sides.length; i++) {\n mCropObj.selectEdge(sides[i]);\n mCropObj.moveCurrentSelection(dx[i], dy[i]);\n mCropObj.moveCurrentSelection(-dx[i], -dy[i]);\n }\n mCropObj.selectEdge(CropObject.MOVE_NONE);\n }\n // Draw actual bitmap\n mPaint.reset();\n mPaint.setAntiAlias(true);\n mPaint.setFilterBitmap(true);\n canvas.drawBitmap(bitmap, mDisplayMatrix, mPaint);\n mCropObj.getInnerBounds(mScreenCropBounds);\n RectF outer = mCropObj.getOuterBounds();\n FilterCropRepresentation.findNormalizedCrop(mScreenCropBounds, (int) outer.width(), (int) outer.height());\n FilterCropRepresentation.findScaledCrop(mScreenCropBounds, bitmap.getWidth(), bitmap.getHeight());\n if (mDisplayCropMatrix.mapRect(mScreenCropBounds)) {\n // Draw crop rect and markers\n CropDrawingUtils.drawCropRect(canvas, mScreenCropBounds);\n CropDrawingUtils.drawShade(canvas, mScreenCropBounds);\n CropDrawingUtils.drawRuleOfThird(canvas, mScreenCropBounds);\n CropDrawingUtils.drawIndicators(canvas, mCropIndicator, mIndicatorSize, mScreenCropBounds, mCropObj.isFixedAspect(), decode(mCropObj.getSelectState(), mGeometry.rotation.value()));\n }\n }\n\n public void setEditor(EditorCrop editorCrop) {\n mEditorCrop = editorCrop;\n }\n}\n"} {"task_id": "Java_551", "language": "Java", "task_type": "method_signature", "source_file": "java/github/NarimanN2/ParsiAnalyzer/src/main/java/org/elasticsearch/analyzer/tokenfilters/PersianStemFilter.java", "mask_start_position": 870, "mask_end_position": 935, "canonical_solution": "@Override\n public boolean incrementToken() throws IOException ", "pre_mask_code": "package org.elasticsearch.analyzer.tokenfilters;\n\nimport org.apache.lucene.analysis.TokenFilter;\nimport org.apache.lucene.analysis.TokenStream;\nimport org.apache.lucene.analysis.tokenattributes.CharTermAttribute;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by Nariman on 10/28/2017.\n */\npublic final class PersianStemFilter extends TokenFilter {\n\n private List suffixes;\n\n private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);\n\n public PersianStemFilter(TokenStream in) {\n super(in);\n suffixes = new ArrayList<>();\n suffixes.add(\"یی\");\n suffixes.add(\"ی\");\n suffixes.add(\"ها\");\n suffixes.add(\"تر\");\n suffixes.add(\"ترین\");\n suffixes.add(\"ان\");\n suffixes.add(\"ات\");\n suffixes.add(\"\\u200c\");\n }\n\n ", "post_mask_code": "{\n if (input.incrementToken()) {\n String token = new String(termAttribute.buffer(), 0, termAttribute.length()).trim();\n if (token.length() > 0) {\n for (String suffix : suffixes) {\n if (token.endsWith(suffix))\n token = token.substring(0, token.length() - suffix.length());\n }\n termAttribute.setEmpty();\n termAttribute.append(token);\n }\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_552", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/NarimanN2/ParsiAnalyzer/src/main/java/org/elasticsearch/analyzer/tokenfilters/PersianStemFilter.java", "mask_start_position": 936, "mask_end_position": 1446, "canonical_solution": "\n if (input.incrementToken()) {\n String token = new String(termAttribute.buffer(), 0, termAttribute.length()).trim();\n if (token.length() > 0) {\n for (String suffix : suffixes) {\n if (token.endsWith(suffix))\n token = token.substring(0, token.length() - suffix.length());\n }\n termAttribute.setEmpty();\n termAttribute.append(token);\n }\n return true;\n }", "pre_mask_code": "package org.elasticsearch.analyzer.tokenfilters;\n\nimport org.apache.lucene.analysis.TokenFilter;\nimport org.apache.lucene.analysis.TokenStream;\nimport org.apache.lucene.analysis.tokenattributes.CharTermAttribute;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by Nariman on 10/28/2017.\n */\npublic final class PersianStemFilter extends TokenFilter {\n\n private List suffixes;\n\n private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);\n\n public PersianStemFilter(TokenStream in) {\n super(in);\n suffixes = new ArrayList<>();\n suffixes.add(\"یی\");\n suffixes.add(\"ی\");\n suffixes.add(\"ها\");\n suffixes.add(\"تر\");\n suffixes.add(\"ترین\");\n suffixes.add(\"ان\");\n suffixes.add(\"ات\");\n suffixes.add(\"\\u200c\");\n }\n\n @Override\n public boolean incrementToken() throws IOException {", "post_mask_code": "\n return false;\n }\n}\n"} {"task_id": "Java_553", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/NarimanN2/ParsiAnalyzer/src/main/java/org/elasticsearch/analyzer/tokenfilters/PersianStemFilter.java", "mask_start_position": 1455, "mask_end_position": 1468, "canonical_solution": "return false;", "pre_mask_code": "package org.elasticsearch.analyzer.tokenfilters;\n\nimport org.apache.lucene.analysis.TokenFilter;\nimport org.apache.lucene.analysis.TokenStream;\nimport org.apache.lucene.analysis.tokenattributes.CharTermAttribute;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by Nariman on 10/28/2017.\n */\npublic final class PersianStemFilter extends TokenFilter {\n\n private List suffixes;\n\n private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);\n\n public PersianStemFilter(TokenStream in) {\n super(in);\n suffixes = new ArrayList<>();\n suffixes.add(\"یی\");\n suffixes.add(\"ی\");\n suffixes.add(\"ها\");\n suffixes.add(\"تر\");\n suffixes.add(\"ترین\");\n suffixes.add(\"ان\");\n suffixes.add(\"ات\");\n suffixes.add(\"\\u200c\");\n }\n\n @Override\n public boolean incrementToken() throws IOException {\n if (input.incrementToken()) {\n String token = new String(termAttribute.buffer(), 0, termAttribute.length()).trim();\n if (token.length() > 0) {\n for (String suffix : suffixes) {\n if (token.endsWith(suffix))\n token = token.substring(0, token.length() - suffix.length());\n }\n termAttribute.setEmpty();\n termAttribute.append(token);\n }\n return true;\n }\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_554", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/NarimanN2/ParsiAnalyzer/src/main/java/org/elasticsearch/analyzer/tokenfilters/PersianStemFilter.java", "mask_start_position": 1473, "mask_end_position": 1474, "canonical_solution": "}", "pre_mask_code": "package org.elasticsearch.analyzer.tokenfilters;\n\nimport org.apache.lucene.analysis.TokenFilter;\nimport org.apache.lucene.analysis.TokenStream;\nimport org.apache.lucene.analysis.tokenattributes.CharTermAttribute;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by Nariman on 10/28/2017.\n */\npublic final class PersianStemFilter extends TokenFilter {\n\n private List suffixes;\n\n private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);\n\n public PersianStemFilter(TokenStream in) {\n super(in);\n suffixes = new ArrayList<>();\n suffixes.add(\"یی\");\n suffixes.add(\"ی\");\n suffixes.add(\"ها\");\n suffixes.add(\"تر\");\n suffixes.add(\"ترین\");\n suffixes.add(\"ان\");\n suffixes.add(\"ات\");\n suffixes.add(\"\\u200c\");\n }\n\n @Override\n public boolean incrementToken() throws IOException {\n if (input.incrementToken()) {\n String token = new String(termAttribute.buffer(), 0, termAttribute.length()).trim();\n if (token.length() > 0) {\n for (String suffix : suffixes) {\n if (token.endsWith(suffix))\n token = token.substring(0, token.length() - suffix.length());\n }\n termAttribute.setEmpty();\n termAttribute.append(token);\n }\n return true;\n }\n return false;\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_555", "language": "Java", "task_type": "single_line", "source_file": "java/github/NarimanN2/ParsiAnalyzer/src/main/java/org/elasticsearch/analyzer/tokenfilters/PersianStemFilter.java", "mask_start_position": 1455, "mask_end_position": 1468, "canonical_solution": "return false;", "pre_mask_code": "package org.elasticsearch.analyzer.tokenfilters;\n\nimport org.apache.lucene.analysis.TokenFilter;\nimport org.apache.lucene.analysis.TokenStream;\nimport org.apache.lucene.analysis.tokenattributes.CharTermAttribute;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by Nariman on 10/28/2017.\n */\npublic final class PersianStemFilter extends TokenFilter {\n\n private List suffixes;\n\n private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);\n\n public PersianStemFilter(TokenStream in) {\n super(in);\n suffixes = new ArrayList<>();\n suffixes.add(\"یی\");\n suffixes.add(\"ی\");\n suffixes.add(\"ها\");\n suffixes.add(\"تر\");\n suffixes.add(\"ترین\");\n suffixes.add(\"ان\");\n suffixes.add(\"ات\");\n suffixes.add(\"\\u200c\");\n }\n\n @Override\n public boolean incrementToken() throws IOException {\n if (input.incrementToken()) {\n String token = new String(termAttribute.buffer(), 0, termAttribute.length()).trim();\n if (token.length() > 0) {\n for (String suffix : suffixes) {\n if (token.endsWith(suffix))\n token = token.substring(0, token.length() - suffix.length());\n }\n termAttribute.setEmpty();\n termAttribute.append(token);\n }\n return true;\n }\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_556", "language": "Java", "task_type": "if_statement", "source_file": "java/github/NarimanN2/ParsiAnalyzer/src/main/java/org/elasticsearch/analyzer/tokenfilters/PersianStemFilter.java", "mask_start_position": 1084, "mask_end_position": 1411, "canonical_solution": "if (token.length() > 0) {\n for (String suffix : suffixes) {\n if (token.endsWith(suffix))\n token = token.substring(0, token.length() - suffix.length());\n }\n termAttribute.setEmpty();\n termAttribute.append(token);\n }", "pre_mask_code": "package org.elasticsearch.analyzer.tokenfilters;\n\nimport org.apache.lucene.analysis.TokenFilter;\nimport org.apache.lucene.analysis.TokenStream;\nimport org.apache.lucene.analysis.tokenattributes.CharTermAttribute;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by Nariman on 10/28/2017.\n */\npublic final class PersianStemFilter extends TokenFilter {\n\n private List suffixes;\n\n private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);\n\n public PersianStemFilter(TokenStream in) {\n super(in);\n suffixes = new ArrayList<>();\n suffixes.add(\"یی\");\n suffixes.add(\"ی\");\n suffixes.add(\"ها\");\n suffixes.add(\"تر\");\n suffixes.add(\"ترین\");\n suffixes.add(\"ان\");\n suffixes.add(\"ات\");\n suffixes.add(\"\\u200c\");\n }\n\n @Override\n public boolean incrementToken() throws IOException {\n if (input.incrementToken()) {\n String token = new String(termAttribute.buffer(), 0, termAttribute.length()).trim();\n ", "post_mask_code": "\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_557", "language": "Java", "task_type": "empty", "source_file": "java/github/NarimanN2/ParsiAnalyzer/src/main/java/org/elasticsearch/analyzer/tokenfilters/PersianStemFilter.java", "mask_start_position": 1443, "mask_end_position": 1443, "canonical_solution": "", "pre_mask_code": "package org.elasticsearch.analyzer.tokenfilters;\n\nimport org.apache.lucene.analysis.TokenFilter;\nimport org.apache.lucene.analysis.TokenStream;\nimport org.apache.lucene.analysis.tokenattributes.CharTermAttribute;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by Nariman on 10/28/2017.\n */\npublic final class PersianStemFilter extends TokenFilter {\n\n private List suffixes;\n\n private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);\n\n public PersianStemFilter(TokenStream in) {\n super(in);\n suffixes = new ArrayList<>();\n suffixes.add(\"یی\");\n suffixes.add(\"ی\");\n suffixes.add(\"ها\");\n suffixes.add(\"تر\");\n suffixes.add(\"ترین\");\n suffixes.add(\"ان\");\n suffixes.add(\"ات\");\n suffixes.add(\"\\u200c\");\n }\n\n @Override\n public boolean incrementToken() throws IOException {\n if (input.incrementToken()) {\n String token = new String(termAttribute.buffer(), 0, termAttribute.length()).trim();\n if (token.length() > 0) {\n for (String suffix : suffixes) {\n if (token.endsWith(suffix))\n token = token.substring(0, token.length() - suffix.length());\n }\n termAttribute.setEmpty();\n termAttribute.append(token);\n }\n return true;\n ", "post_mask_code": " }\n return false;\n }\n}\n"} {"task_id": "Java_558", "language": "Java", "task_type": "method_signature", "source_file": "java/github/anotheria/moskito/moskito-webui/src/main/java/net/anotheria/moskito/webui/threshold/action/CreateThresholdAction.java", "mask_start_position": 525, "mask_end_position": 701, "canonical_solution": "@Override\n public ActionCommand execute(ActionMapping mapping, @Form(ThresholdPO.class) FormBean formBean, HttpServletRequest req, HttpServletResponse res) throws Exception ", "pre_mask_code": "package net.anotheria.moskito.webui.threshold.action;\n\nimport net.anotheria.maf.action.ActionCommand;\nimport net.anotheria.maf.action.ActionMapping;\nimport net.anotheria.maf.bean.FormBean;\nimport net.anotheria.maf.bean.annotations.Form;\nimport net.anotheria.moskito.webui.threshold.api.ThresholdPO;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/**\n * Creates a new threshold.\n *\n * @author lrosenberg\n */\npublic class CreateThresholdAction extends BaseThresholdsAction {\n\n ", "post_mask_code": "{\n ThresholdPO po = (ThresholdPO) formBean;\n getThresholdAPI().createThreshold(po);\n return mapping.redirect().addParameter(\"newThreshold\", ((ThresholdPO) formBean).getName()).addParameter(\"pProducerId\", po.getProducerId());\n }\n}\n"} {"task_id": "Java_559", "language": "Java", "task_type": "method_body", "source_file": "java/github/anotheria/moskito/moskito-webui/src/main/java/net/anotheria/moskito/webui/threshold/action/CreateThresholdAction.java", "mask_start_position": 701, "mask_end_position": 952, "canonical_solution": "{\n ThresholdPO po = (ThresholdPO) formBean;\n getThresholdAPI().createThreshold(po);\n return mapping.redirect().addParameter(\"newThreshold\", ((ThresholdPO) formBean).getName()).addParameter(\"pProducerId\", po.getProducerId());\n }", "pre_mask_code": "package net.anotheria.moskito.webui.threshold.action;\n\nimport net.anotheria.maf.action.ActionCommand;\nimport net.anotheria.maf.action.ActionMapping;\nimport net.anotheria.maf.bean.FormBean;\nimport net.anotheria.maf.bean.annotations.Form;\nimport net.anotheria.moskito.webui.threshold.api.ThresholdPO;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/**\n * Creates a new threshold.\n *\n * @author lrosenberg\n */\npublic class CreateThresholdAction extends BaseThresholdsAction {\n\n @Override\n public ActionCommand execute(ActionMapping mapping, @Form(ThresholdPO.class) FormBean formBean, HttpServletRequest req, HttpServletResponse res) throws Exception ", "post_mask_code": "\n}\n"} {"task_id": "Java_560", "language": "Java", "task_type": "single_line", "source_file": "java/github/anotheria/moskito/moskito-webui/src/main/java/net/anotheria/moskito/webui/threshold/action/CreateThresholdAction.java", "mask_start_position": 783, "mask_end_position": 798, "canonical_solution": "eThreshold(po);", "pre_mask_code": "package net.anotheria.moskito.webui.threshold.action;\n\nimport net.anotheria.maf.action.ActionCommand;\nimport net.anotheria.maf.action.ActionMapping;\nimport net.anotheria.maf.bean.FormBean;\nimport net.anotheria.maf.bean.annotations.Form;\nimport net.anotheria.moskito.webui.threshold.api.ThresholdPO;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/**\n * Creates a new threshold.\n *\n * @author lrosenberg\n */\npublic class CreateThresholdAction extends BaseThresholdsAction {\n\n @Override\n public ActionCommand execute(ActionMapping mapping, @Form(ThresholdPO.class) FormBean formBean, HttpServletRequest req, HttpServletResponse res) throws Exception {\n ThresholdPO po = (ThresholdPO) formBean;\n getThresholdAPI().creat", "post_mask_code": "\n return mapping.redirect().addParameter(\"newThreshold\", ((ThresholdPO) formBean).getName()).addParameter(\"pProducerId\", po.getProducerId());\n }\n}\n"} {"task_id": "Java_561", "language": "Java", "task_type": "empty", "source_file": "java/github/anotheria/moskito/moskito-webui/src/main/java/net/anotheria/moskito/webui/threshold/action/CreateThresholdAction.java", "mask_start_position": 661, "mask_end_position": 661, "canonical_solution": "", "pre_mask_code": "package net.anotheria.moskito.webui.threshold.action;\n\nimport net.anotheria.maf.action.ActionCommand;\nimport net.anotheria.maf.action.ActionMapping;\nimport net.anotheria.maf.bean.FormBean;\nimport net.anotheria.maf.bean.annotations.Form;\nimport net.anotheria.moskito.webui.threshold.api.ThresholdPO;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/**\n * Creates a new threshold.\n *\n * @author lrosenberg\n */\npublic class CreateThresholdAction extends BaseThresholdsAction {\n\n @Override\n public ActionCommand execute(ActionMapping mapping, @Form(ThresholdPO.class) FormBean formBean, HttpServletRequest req, Ht", "post_mask_code": "tpServletResponse res) throws Exception {\n ThresholdPO po = (ThresholdPO) formBean;\n getThresholdAPI().createThreshold(po);\n return mapping.redirect().addParameter(\"newThreshold\", ((ThresholdPO) formBean).getName()).addParameter(\"pProducerId\", po.getProducerId());\n }\n}\n"} {"task_id": "Java_562", "language": "Java", "task_type": "method_signature", "source_file": "java/github/DimpleFeng/online_exam_system/src/main/java/com/dimple/controller/TeacherReviewController.java", "mask_start_position": 1409, "mask_end_position": 1489, "canonical_solution": "@GetMapping(\"/list\")\n @ResponseBody\n public TableDataInfo list(Exam exam) ", "pre_mask_code": "package com.dimple.controller;\n\nimport com.dimple.annotation.Log;\nimport com.dimple.entity.Exam;\nimport com.dimple.entity.ExamRecord;\nimport com.dimple.entity.SysUser;\nimport com.dimple.service.ExamRecordService;\nimport com.dimple.service.ExamService;\nimport com.dimple.service.ExamStudentService;\nimport com.dimple.service.SysUserService;\nimport com.dimple.utils.web.AjaxResult;\nimport com.dimple.utils.web.BaseController;\nimport com.dimple.utils.web.TableDataInfo;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.ResponseBody;\nimport java.util.List;\n\n@Controller\n// 地址栏中的url前缀\n@RequestMapping(\"/onlineExam/review\")\npublic class TeacherReviewController extends BaseController {\n\n // 注入对象\n @Autowired\n ExamService examService;\n\n @Autowired\n ExamRecordService examRecordService;\n\n @Autowired\n ExamStudentService examStudentService;\n\n @Autowired\n SysUserService sysUserService;\n\n // 当url\n @GetMapping()\n public String review() {\n return \"onlineExam/review/review\";\n }\n\n ", "post_mask_code": "{\n startPage();\n List exams = examService.findExamListToReview(exam);\n return getDataTable(exams);\n }\n\n @GetMapping(\"/{examId}/{studentId}\")\n public String reviewStuExam(@PathVariable Integer examId, @PathVariable Integer studentId, Model model) {\n model.addAttribute(\"exam\", examService.findExamDetailToReview(examId, studentId));\n model.addAttribute(\"stuId\", studentId);\n return \"onlineExam/review/reviewExam\";\n }\n\n // 异步提交并更新单个试题的得分\n @PostMapping(\"/reviewExam\")\n @ResponseBody\n public AjaxResult reviewExam(ExamRecord examRecord) {\n return toAjax(examRecordService.teacherReviewRecord(examRecord));\n }\n\n // 完成阅卷,提交阅卷的结果,返回index界面,并更新e—s中,total-Score的值\n @PostMapping(\"/finisReview\")\n @Log(\"完成阅卷\")\n public String finishReview(Integer examId, Integer stuId) {\n examRecordService.finishReview(examId, stuId);\n return \"/index\";\n }\n\n // 展示试卷的详情,阅卷完成详情\n @GetMapping(\"/detail/{examId}/{stuId}\")\n public String examDetail(@PathVariable Integer examId, @PathVariable Integer stuId, Model model) {\n model.addAttribute(\"exam\", examService.findExamDetailToReview(examId, stuId));\n model.addAttribute(\"student\", sysUserService.selectSysyUserById(stuId));\n model.addAttribute(\"examStudent\", examStudentService.queryByExamIdAndStuId(examId, stuId));\n return \"onlineExam/review/detail\";\n }\n}\n"} {"task_id": "Java_563", "language": "Java", "task_type": "method_body", "source_file": "java/github/DimpleFeng/online_exam_system/src/main/java/com/dimple/controller/TeacherReviewController.java", "mask_start_position": 2094, "mask_end_position": 2175, "canonical_solution": "{\n return toAjax(examRecordService.teacherReviewRecord(examRecord));\n }", "pre_mask_code": "package com.dimple.controller;\n\nimport com.dimple.annotation.Log;\nimport com.dimple.entity.Exam;\nimport com.dimple.entity.ExamRecord;\nimport com.dimple.entity.SysUser;\nimport com.dimple.service.ExamRecordService;\nimport com.dimple.service.ExamService;\nimport com.dimple.service.ExamStudentService;\nimport com.dimple.service.SysUserService;\nimport com.dimple.utils.web.AjaxResult;\nimport com.dimple.utils.web.BaseController;\nimport com.dimple.utils.web.TableDataInfo;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.ResponseBody;\nimport java.util.List;\n\n@Controller\n// 地址栏中的url前缀\n@RequestMapping(\"/onlineExam/review\")\npublic class TeacherReviewController extends BaseController {\n\n // 注入对象\n @Autowired\n ExamService examService;\n\n @Autowired\n ExamRecordService examRecordService;\n\n @Autowired\n ExamStudentService examStudentService;\n\n @Autowired\n SysUserService sysUserService;\n\n // 当url\n @GetMapping()\n public String review() {\n return \"onlineExam/review/review\";\n }\n\n @GetMapping(\"/list\")\n @ResponseBody\n public TableDataInfo list(Exam exam) {\n startPage();\n List exams = examService.findExamListToReview(exam);\n return getDataTable(exams);\n }\n\n @GetMapping(\"/{examId}/{studentId}\")\n public String reviewStuExam(@PathVariable Integer examId, @PathVariable Integer studentId, Model model) {\n model.addAttribute(\"exam\", examService.findExamDetailToReview(examId, studentId));\n model.addAttribute(\"stuId\", studentId);\n return \"onlineExam/review/reviewExam\";\n }\n\n // 异步提交并更新单个试题的得分\n @PostMapping(\"/reviewExam\")\n @ResponseBody\n public AjaxResult reviewExam(ExamRecord examRecord) ", "post_mask_code": "\n\n // 完成阅卷,提交阅卷的结果,返回index界面,并更新e—s中,total-Score的值\n @PostMapping(\"/finisReview\")\n @Log(\"完成阅卷\")\n public String finishReview(Integer examId, Integer stuId) {\n examRecordService.finishReview(examId, stuId);\n return \"/index\";\n }\n\n // 展示试卷的详情,阅卷完成详情\n @GetMapping(\"/detail/{examId}/{stuId}\")\n public String examDetail(@PathVariable Integer examId, @PathVariable Integer stuId, Model model) {\n model.addAttribute(\"exam\", examService.findExamDetailToReview(examId, stuId));\n model.addAttribute(\"student\", sysUserService.selectSysyUserById(stuId));\n model.addAttribute(\"examStudent\", examStudentService.queryByExamIdAndStuId(examId, stuId));\n return \"onlineExam/review/detail\";\n }\n}\n"} {"task_id": "Java_564", "language": "Java", "task_type": "single_line", "source_file": "java/github/DimpleFeng/online_exam_system/src/main/java/com/dimple/controller/TeacherReviewController.java", "mask_start_position": 2712, "mask_end_position": 2766, "canonical_solution": "(\"student\", sysUserService.selectSysyUserById(stuId));", "pre_mask_code": "package com.dimple.controller;\n\nimport com.dimple.annotation.Log;\nimport com.dimple.entity.Exam;\nimport com.dimple.entity.ExamRecord;\nimport com.dimple.entity.SysUser;\nimport com.dimple.service.ExamRecordService;\nimport com.dimple.service.ExamService;\nimport com.dimple.service.ExamStudentService;\nimport com.dimple.service.SysUserService;\nimport com.dimple.utils.web.AjaxResult;\nimport com.dimple.utils.web.BaseController;\nimport com.dimple.utils.web.TableDataInfo;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.ResponseBody;\nimport java.util.List;\n\n@Controller\n// 地址栏中的url前缀\n@RequestMapping(\"/onlineExam/review\")\npublic class TeacherReviewController extends BaseController {\n\n // 注入对象\n @Autowired\n ExamService examService;\n\n @Autowired\n ExamRecordService examRecordService;\n\n @Autowired\n ExamStudentService examStudentService;\n\n @Autowired\n SysUserService sysUserService;\n\n // 当url\n @GetMapping()\n public String review() {\n return \"onlineExam/review/review\";\n }\n\n @GetMapping(\"/list\")\n @ResponseBody\n public TableDataInfo list(Exam exam) {\n startPage();\n List exams = examService.findExamListToReview(exam);\n return getDataTable(exams);\n }\n\n @GetMapping(\"/{examId}/{studentId}\")\n public String reviewStuExam(@PathVariable Integer examId, @PathVariable Integer studentId, Model model) {\n model.addAttribute(\"exam\", examService.findExamDetailToReview(examId, studentId));\n model.addAttribute(\"stuId\", studentId);\n return \"onlineExam/review/reviewExam\";\n }\n\n // 异步提交并更新单个试题的得分\n @PostMapping(\"/reviewExam\")\n @ResponseBody\n public AjaxResult reviewExam(ExamRecord examRecord) {\n return toAjax(examRecordService.teacherReviewRecord(examRecord));\n }\n\n // 完成阅卷,提交阅卷的结果,返回index界面,并更新e—s中,total-Score的值\n @PostMapping(\"/finisReview\")\n @Log(\"完成阅卷\")\n public String finishReview(Integer examId, Integer stuId) {\n examRecordService.finishReview(examId, stuId);\n return \"/index\";\n }\n\n // 展示试卷的详情,阅卷完成详情\n @GetMapping(\"/detail/{examId}/{stuId}\")\n public String examDetail(@PathVariable Integer examId, @PathVariable Integer stuId, Model model) {\n model.addAttribute(\"exam\", examService.findExamDetailToReview(examId, stuId));\n model.addAttribute", "post_mask_code": "\n model.addAttribute(\"examStudent\", examStudentService.queryByExamIdAndStuId(examId, stuId));\n return \"onlineExam/review/detail\";\n }\n}\n"} {"task_id": "Java_565", "language": "Java", "task_type": "empty", "source_file": "java/github/DimpleFeng/online_exam_system/src/main/java/com/dimple/controller/TeacherReviewController.java", "mask_start_position": 2894, "mask_end_position": 2894, "canonical_solution": "", "pre_mask_code": "package com.dimple.controller;\n\nimport com.dimple.annotation.Log;\nimport com.dimple.entity.Exam;\nimport com.dimple.entity.ExamRecord;\nimport com.dimple.entity.SysUser;\nimport com.dimple.service.ExamRecordService;\nimport com.dimple.service.ExamService;\nimport com.dimple.service.ExamStudentService;\nimport com.dimple.service.SysUserService;\nimport com.dimple.utils.web.AjaxResult;\nimport com.dimple.utils.web.BaseController;\nimport com.dimple.utils.web.TableDataInfo;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.ResponseBody;\nimport java.util.List;\n\n@Controller\n// 地址栏中的url前缀\n@RequestMapping(\"/onlineExam/review\")\npublic class TeacherReviewController extends BaseController {\n\n // 注入对象\n @Autowired\n ExamService examService;\n\n @Autowired\n ExamRecordService examRecordService;\n\n @Autowired\n ExamStudentService examStudentService;\n\n @Autowired\n SysUserService sysUserService;\n\n // 当url\n @GetMapping()\n public String review() {\n return \"onlineExam/review/review\";\n }\n\n @GetMapping(\"/list\")\n @ResponseBody\n public TableDataInfo list(Exam exam) {\n startPage();\n List exams = examService.findExamListToReview(exam);\n return getDataTable(exams);\n }\n\n @GetMapping(\"/{examId}/{studentId}\")\n public String reviewStuExam(@PathVariable Integer examId, @PathVariable Integer studentId, Model model) {\n model.addAttribute(\"exam\", examService.findExamDetailToReview(examId, studentId));\n model.addAttribute(\"stuId\", studentId);\n return \"onlineExam/review/reviewExam\";\n }\n\n // 异步提交并更新单个试题的得分\n @PostMapping(\"/reviewExam\")\n @ResponseBody\n public AjaxResult reviewExam(ExamRecord examRecord) {\n return toAjax(examRecordService.teacherReviewRecord(examRecord));\n }\n\n // 完成阅卷,提交阅卷的结果,返回index界面,并更新e—s中,total-Score的值\n @PostMapping(\"/finisReview\")\n @Log(\"完成阅卷\")\n public String finishReview(Integer examId, Integer stuId) {\n examRecordService.finishReview(examId, stuId);\n return \"/index\";\n }\n\n // 展示试卷的详情,阅卷完成详情\n @GetMapping(\"/detail/{examId}/{stuId}\")\n public String examDetail(@PathVariable Integer examId, @PathVariable Integer stuId, Model model) {\n model.addAttribute(\"exam\", examService.findExamDetailToReview(examId, stuId));\n model.addAttribute(\"student\", sysUserService.selectSysyUserById(stuId));\n model.addAttribute(\"examStudent\", examStudentService.queryByExamIdAndStuId(examId, stuId));\n return \"onlineExam/", "post_mask_code": "review/detail\";\n }\n}\n"} {"task_id": "Java_566", "language": "Java", "task_type": "method_signature", "source_file": "java/github/pgptool/pgptool/pgptool-gui/src/main/java/org/pgptool/gui/ui/tools/geometrymemory/WindowGeometryPersisterImpl.java", "mask_start_position": 3345, "mask_end_position": 3380, "canonical_solution": "@Override\n public void detach() ", "pre_mask_code": "/**\n * ****************************************************************************\n * PGPTool is a desktop application for pgp encryption/decryption\n *\n * ****************************************************************************\n */\npackage org.pgptool.gui.ui.tools.geometrymemory;\n\nimport java.awt.Dimension;\nimport java.awt.Window;\nimport java.awt.event.ComponentAdapter;\nimport java.awt.event.ComponentEvent;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\nimport org.pgptool.gui.configpairs.api.ConfigPairs;\nimport org.springframework.util.StringUtils;\nimport com.google.common.base.Preconditions;\n\npublic class WindowGeometryPersisterImpl extends ComponentAdapter implements WindowGeometryPersister {\n\n static final int MINIMUM_SANE_SIZE_VALUE = 10;\n\n private static final long DELAY = 500;\n\n private static final TimeUnit DELAY_TIME_UNIT = TimeUnit.MILLISECONDS;\n\n private ConfigPairs configPairs;\n\n private ScheduledExecutorService scheduledExecutorService;\n\n private Window window;\n\n private String keyId;\n\n private ScheduledFuture sizeSetter;\n\n /**\n * @param scheduledExecutorService it's used to dealy interraction with\n * configPairs to avoid spamming it with values\n * while user still dragging element\n */\n public WindowGeometryPersisterImpl(Window window, String windowId, ConfigPairs configPairs, ScheduledExecutorService scheduledExecutorService) {\n Preconditions.checkArgument(scheduledExecutorService != null);\n Preconditions.checkArgument(window != null);\n Preconditions.checkArgument(StringUtils.hasText(windowId));\n Preconditions.checkArgument(configPairs != null);\n this.window = window;\n // version to version application windows sizes might change\n this.keyId = windowId + \"_\" + window.getMinimumSize();\n this.configPairs = configPairs;\n this.scheduledExecutorService = scheduledExecutorService;\n window.addComponentListener(this);\n }\n\n @Override\n public boolean restoreSize() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n Dimension size = configPairs.find(keySize(), null);\n if (size == null) {\n return false;\n }\n window.setSize(size);\n return true;\n }\n\n // @Override\n // Preconditions.checkState(window != null, \"instance was detached, can't do\n // much after that\");\n @Override\n public void componentResized(ComponentEvent e) {\n if (window == null) {\n return;\n }\n Dimension size = window.getSize();\n if (size.getWidth() < MINIMUM_SANE_SIZE_VALUE || size.getHeight() < MINIMUM_SANE_SIZE_VALUE) {\n return;\n }\n if (sizeSetter != null) {\n sizeSetter.cancel(true);\n }\n sizeSetter = scheduledExecutorService.schedule(() -> configPairs.put(keySize(), window.getSize()), DELAY, DELAY_TIME_UNIT);\n }\n\n private String keySize() {\n return keyId + \"_size\";\n }\n\n // @Override\n // locationSetter = scheduledExecutorService\n @Override\n public boolean isAttached() {\n return window != null;\n }\n\n ", "post_mask_code": "{\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n window.removeComponentListener(this);\n window = null;\n }\n}\n"} {"task_id": "Java_567", "language": "Java", "task_type": "method_body", "source_file": "java/github/pgptool/pgptool/pgptool-gui/src/main/java/org/pgptool/gui/ui/tools/geometrymemory/WindowGeometryPersisterImpl.java", "mask_start_position": 2187, "mask_end_position": 2470, "canonical_solution": "{\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n Dimension size = configPairs.find(keySize(), null);\n if (size == null) {\n return false;\n }\n window.setSize(size);\n return true;\n }", "pre_mask_code": "/**\n * ****************************************************************************\n * PGPTool is a desktop application for pgp encryption/decryption\n *\n * ****************************************************************************\n */\npackage org.pgptool.gui.ui.tools.geometrymemory;\n\nimport java.awt.Dimension;\nimport java.awt.Window;\nimport java.awt.event.ComponentAdapter;\nimport java.awt.event.ComponentEvent;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\nimport org.pgptool.gui.configpairs.api.ConfigPairs;\nimport org.springframework.util.StringUtils;\nimport com.google.common.base.Preconditions;\n\npublic class WindowGeometryPersisterImpl extends ComponentAdapter implements WindowGeometryPersister {\n\n static final int MINIMUM_SANE_SIZE_VALUE = 10;\n\n private static final long DELAY = 500;\n\n private static final TimeUnit DELAY_TIME_UNIT = TimeUnit.MILLISECONDS;\n\n private ConfigPairs configPairs;\n\n private ScheduledExecutorService scheduledExecutorService;\n\n private Window window;\n\n private String keyId;\n\n private ScheduledFuture sizeSetter;\n\n /**\n * @param scheduledExecutorService it's used to dealy interraction with\n * configPairs to avoid spamming it with values\n * while user still dragging element\n */\n public WindowGeometryPersisterImpl(Window window, String windowId, ConfigPairs configPairs, ScheduledExecutorService scheduledExecutorService) {\n Preconditions.checkArgument(scheduledExecutorService != null);\n Preconditions.checkArgument(window != null);\n Preconditions.checkArgument(StringUtils.hasText(windowId));\n Preconditions.checkArgument(configPairs != null);\n this.window = window;\n // version to version application windows sizes might change\n this.keyId = windowId + \"_\" + window.getMinimumSize();\n this.configPairs = configPairs;\n this.scheduledExecutorService = scheduledExecutorService;\n window.addComponentListener(this);\n }\n\n @Override\n public boolean restoreSize() ", "post_mask_code": "\n\n // @Override\n // Preconditions.checkState(window != null, \"instance was detached, can't do\n // much after that\");\n @Override\n public void componentResized(ComponentEvent e) {\n if (window == null) {\n return;\n }\n Dimension size = window.getSize();\n if (size.getWidth() < MINIMUM_SANE_SIZE_VALUE || size.getHeight() < MINIMUM_SANE_SIZE_VALUE) {\n return;\n }\n if (sizeSetter != null) {\n sizeSetter.cancel(true);\n }\n sizeSetter = scheduledExecutorService.schedule(() -> configPairs.put(keySize(), window.getSize()), DELAY, DELAY_TIME_UNIT);\n }\n\n private String keySize() {\n return keyId + \"_size\";\n }\n\n // @Override\n // locationSetter = scheduledExecutorService\n @Override\n public boolean isAttached() {\n return window != null;\n }\n\n @Override\n public void detach() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n window.removeComponentListener(this);\n window = null;\n }\n}\n"} {"task_id": "Java_568", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/pgptool/pgptool/pgptool-gui/src/main/java/org/pgptool/gui/ui/tools/geometrymemory/WindowGeometryPersisterImpl.java", "mask_start_position": 2188, "mask_end_position": 2349, "canonical_solution": "\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n Dimension size = configPairs.find(keySize(), null);", "pre_mask_code": "/**\n * ****************************************************************************\n * PGPTool is a desktop application for pgp encryption/decryption\n *\n * ****************************************************************************\n */\npackage org.pgptool.gui.ui.tools.geometrymemory;\n\nimport java.awt.Dimension;\nimport java.awt.Window;\nimport java.awt.event.ComponentAdapter;\nimport java.awt.event.ComponentEvent;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\nimport org.pgptool.gui.configpairs.api.ConfigPairs;\nimport org.springframework.util.StringUtils;\nimport com.google.common.base.Preconditions;\n\npublic class WindowGeometryPersisterImpl extends ComponentAdapter implements WindowGeometryPersister {\n\n static final int MINIMUM_SANE_SIZE_VALUE = 10;\n\n private static final long DELAY = 500;\n\n private static final TimeUnit DELAY_TIME_UNIT = TimeUnit.MILLISECONDS;\n\n private ConfigPairs configPairs;\n\n private ScheduledExecutorService scheduledExecutorService;\n\n private Window window;\n\n private String keyId;\n\n private ScheduledFuture sizeSetter;\n\n /**\n * @param scheduledExecutorService it's used to dealy interraction with\n * configPairs to avoid spamming it with values\n * while user still dragging element\n */\n public WindowGeometryPersisterImpl(Window window, String windowId, ConfigPairs configPairs, ScheduledExecutorService scheduledExecutorService) {\n Preconditions.checkArgument(scheduledExecutorService != null);\n Preconditions.checkArgument(window != null);\n Preconditions.checkArgument(StringUtils.hasText(windowId));\n Preconditions.checkArgument(configPairs != null);\n this.window = window;\n // version to version application windows sizes might change\n this.keyId = windowId + \"_\" + window.getMinimumSize();\n this.configPairs = configPairs;\n this.scheduledExecutorService = scheduledExecutorService;\n window.addComponentListener(this);\n }\n\n @Override\n public boolean restoreSize() {", "post_mask_code": "\n if (size == null) {\n return false;\n }\n window.setSize(size);\n return true;\n }\n\n // @Override\n // Preconditions.checkState(window != null, \"instance was detached, can't do\n // much after that\");\n @Override\n public void componentResized(ComponentEvent e) {\n if (window == null) {\n return;\n }\n Dimension size = window.getSize();\n if (size.getWidth() < MINIMUM_SANE_SIZE_VALUE || size.getHeight() < MINIMUM_SANE_SIZE_VALUE) {\n return;\n }\n if (sizeSetter != null) {\n sizeSetter.cancel(true);\n }\n sizeSetter = scheduledExecutorService.schedule(() -> configPairs.put(keySize(), window.getSize()), DELAY, DELAY_TIME_UNIT);\n }\n\n private String keySize() {\n return keyId + \"_size\";\n }\n\n // @Override\n // locationSetter = scheduledExecutorService\n @Override\n public boolean isAttached() {\n return window != null;\n }\n\n @Override\n public void detach() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n window.removeComponentListener(this);\n window = null;\n }\n}\n"} {"task_id": "Java_569", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/pgptool/pgptool/pgptool-gui/src/main/java/org/pgptool/gui/ui/tools/geometrymemory/WindowGeometryPersisterImpl.java", "mask_start_position": 2358, "mask_end_position": 2443, "canonical_solution": "if (size == null) {\n return false;\n }\n window.setSize(size);", "pre_mask_code": "/**\n * ****************************************************************************\n * PGPTool is a desktop application for pgp encryption/decryption\n *\n * ****************************************************************************\n */\npackage org.pgptool.gui.ui.tools.geometrymemory;\n\nimport java.awt.Dimension;\nimport java.awt.Window;\nimport java.awt.event.ComponentAdapter;\nimport java.awt.event.ComponentEvent;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\nimport org.pgptool.gui.configpairs.api.ConfigPairs;\nimport org.springframework.util.StringUtils;\nimport com.google.common.base.Preconditions;\n\npublic class WindowGeometryPersisterImpl extends ComponentAdapter implements WindowGeometryPersister {\n\n static final int MINIMUM_SANE_SIZE_VALUE = 10;\n\n private static final long DELAY = 500;\n\n private static final TimeUnit DELAY_TIME_UNIT = TimeUnit.MILLISECONDS;\n\n private ConfigPairs configPairs;\n\n private ScheduledExecutorService scheduledExecutorService;\n\n private Window window;\n\n private String keyId;\n\n private ScheduledFuture sizeSetter;\n\n /**\n * @param scheduledExecutorService it's used to dealy interraction with\n * configPairs to avoid spamming it with values\n * while user still dragging element\n */\n public WindowGeometryPersisterImpl(Window window, String windowId, ConfigPairs configPairs, ScheduledExecutorService scheduledExecutorService) {\n Preconditions.checkArgument(scheduledExecutorService != null);\n Preconditions.checkArgument(window != null);\n Preconditions.checkArgument(StringUtils.hasText(windowId));\n Preconditions.checkArgument(configPairs != null);\n this.window = window;\n // version to version application windows sizes might change\n this.keyId = windowId + \"_\" + window.getMinimumSize();\n this.configPairs = configPairs;\n this.scheduledExecutorService = scheduledExecutorService;\n window.addComponentListener(this);\n }\n\n @Override\n public boolean restoreSize() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n Dimension size = configPairs.find(keySize(), null);\n ", "post_mask_code": "\n return true;\n }\n\n // @Override\n // Preconditions.checkState(window != null, \"instance was detached, can't do\n // much after that\");\n @Override\n public void componentResized(ComponentEvent e) {\n if (window == null) {\n return;\n }\n Dimension size = window.getSize();\n if (size.getWidth() < MINIMUM_SANE_SIZE_VALUE || size.getHeight() < MINIMUM_SANE_SIZE_VALUE) {\n return;\n }\n if (sizeSetter != null) {\n sizeSetter.cancel(true);\n }\n sizeSetter = scheduledExecutorService.schedule(() -> configPairs.put(keySize(), window.getSize()), DELAY, DELAY_TIME_UNIT);\n }\n\n private String keySize() {\n return keyId + \"_size\";\n }\n\n // @Override\n // locationSetter = scheduledExecutorService\n @Override\n public boolean isAttached() {\n return window != null;\n }\n\n @Override\n public void detach() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n window.removeComponentListener(this);\n window = null;\n }\n}\n"} {"task_id": "Java_570", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/pgptool/pgptool/pgptool-gui/src/main/java/org/pgptool/gui/ui/tools/geometrymemory/WindowGeometryPersisterImpl.java", "mask_start_position": 2452, "mask_end_position": 2470, "canonical_solution": "return true;\n }", "pre_mask_code": "/**\n * ****************************************************************************\n * PGPTool is a desktop application for pgp encryption/decryption\n *\n * ****************************************************************************\n */\npackage org.pgptool.gui.ui.tools.geometrymemory;\n\nimport java.awt.Dimension;\nimport java.awt.Window;\nimport java.awt.event.ComponentAdapter;\nimport java.awt.event.ComponentEvent;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\nimport org.pgptool.gui.configpairs.api.ConfigPairs;\nimport org.springframework.util.StringUtils;\nimport com.google.common.base.Preconditions;\n\npublic class WindowGeometryPersisterImpl extends ComponentAdapter implements WindowGeometryPersister {\n\n static final int MINIMUM_SANE_SIZE_VALUE = 10;\n\n private static final long DELAY = 500;\n\n private static final TimeUnit DELAY_TIME_UNIT = TimeUnit.MILLISECONDS;\n\n private ConfigPairs configPairs;\n\n private ScheduledExecutorService scheduledExecutorService;\n\n private Window window;\n\n private String keyId;\n\n private ScheduledFuture sizeSetter;\n\n /**\n * @param scheduledExecutorService it's used to dealy interraction with\n * configPairs to avoid spamming it with values\n * while user still dragging element\n */\n public WindowGeometryPersisterImpl(Window window, String windowId, ConfigPairs configPairs, ScheduledExecutorService scheduledExecutorService) {\n Preconditions.checkArgument(scheduledExecutorService != null);\n Preconditions.checkArgument(window != null);\n Preconditions.checkArgument(StringUtils.hasText(windowId));\n Preconditions.checkArgument(configPairs != null);\n this.window = window;\n // version to version application windows sizes might change\n this.keyId = windowId + \"_\" + window.getMinimumSize();\n this.configPairs = configPairs;\n this.scheduledExecutorService = scheduledExecutorService;\n window.addComponentListener(this);\n }\n\n @Override\n public boolean restoreSize() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n Dimension size = configPairs.find(keySize(), null);\n if (size == null) {\n return false;\n }\n window.setSize(size);\n ", "post_mask_code": "\n\n // @Override\n // Preconditions.checkState(window != null, \"instance was detached, can't do\n // much after that\");\n @Override\n public void componentResized(ComponentEvent e) {\n if (window == null) {\n return;\n }\n Dimension size = window.getSize();\n if (size.getWidth() < MINIMUM_SANE_SIZE_VALUE || size.getHeight() < MINIMUM_SANE_SIZE_VALUE) {\n return;\n }\n if (sizeSetter != null) {\n sizeSetter.cancel(true);\n }\n sizeSetter = scheduledExecutorService.schedule(() -> configPairs.put(keySize(), window.getSize()), DELAY, DELAY_TIME_UNIT);\n }\n\n private String keySize() {\n return keyId + \"_size\";\n }\n\n // @Override\n // locationSetter = scheduledExecutorService\n @Override\n public boolean isAttached() {\n return window != null;\n }\n\n @Override\n public void detach() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n window.removeComponentListener(this);\n window = null;\n }\n}\n"} {"task_id": "Java_571", "language": "Java", "task_type": "single_line", "source_file": "java/github/pgptool/pgptool/pgptool-gui/src/main/java/org/pgptool/gui/ui/tools/geometrymemory/WindowGeometryPersisterImpl.java", "mask_start_position": 3325, "mask_end_position": 3333, "canonical_solution": "!= null;", "pre_mask_code": "/**\n * ****************************************************************************\n * PGPTool is a desktop application for pgp encryption/decryption\n *\n * ****************************************************************************\n */\npackage org.pgptool.gui.ui.tools.geometrymemory;\n\nimport java.awt.Dimension;\nimport java.awt.Window;\nimport java.awt.event.ComponentAdapter;\nimport java.awt.event.ComponentEvent;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\nimport org.pgptool.gui.configpairs.api.ConfigPairs;\nimport org.springframework.util.StringUtils;\nimport com.google.common.base.Preconditions;\n\npublic class WindowGeometryPersisterImpl extends ComponentAdapter implements WindowGeometryPersister {\n\n static final int MINIMUM_SANE_SIZE_VALUE = 10;\n\n private static final long DELAY = 500;\n\n private static final TimeUnit DELAY_TIME_UNIT = TimeUnit.MILLISECONDS;\n\n private ConfigPairs configPairs;\n\n private ScheduledExecutorService scheduledExecutorService;\n\n private Window window;\n\n private String keyId;\n\n private ScheduledFuture sizeSetter;\n\n /**\n * @param scheduledExecutorService it's used to dealy interraction with\n * configPairs to avoid spamming it with values\n * while user still dragging element\n */\n public WindowGeometryPersisterImpl(Window window, String windowId, ConfigPairs configPairs, ScheduledExecutorService scheduledExecutorService) {\n Preconditions.checkArgument(scheduledExecutorService != null);\n Preconditions.checkArgument(window != null);\n Preconditions.checkArgument(StringUtils.hasText(windowId));\n Preconditions.checkArgument(configPairs != null);\n this.window = window;\n // version to version application windows sizes might change\n this.keyId = windowId + \"_\" + window.getMinimumSize();\n this.configPairs = configPairs;\n this.scheduledExecutorService = scheduledExecutorService;\n window.addComponentListener(this);\n }\n\n @Override\n public boolean restoreSize() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n Dimension size = configPairs.find(keySize(), null);\n if (size == null) {\n return false;\n }\n window.setSize(size);\n return true;\n }\n\n // @Override\n // Preconditions.checkState(window != null, \"instance was detached, can't do\n // much after that\");\n @Override\n public void componentResized(ComponentEvent e) {\n if (window == null) {\n return;\n }\n Dimension size = window.getSize();\n if (size.getWidth() < MINIMUM_SANE_SIZE_VALUE || size.getHeight() < MINIMUM_SANE_SIZE_VALUE) {\n return;\n }\n if (sizeSetter != null) {\n sizeSetter.cancel(true);\n }\n sizeSetter = scheduledExecutorService.schedule(() -> configPairs.put(keySize(), window.getSize()), DELAY, DELAY_TIME_UNIT);\n }\n\n private String keySize() {\n return keyId + \"_size\";\n }\n\n // @Override\n // locationSetter = scheduledExecutorService\n @Override\n public boolean isAttached() {\n return window ", "post_mask_code": "\n }\n\n @Override\n public void detach() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n window.removeComponentListener(this);\n window = null;\n }\n}\n"} {"task_id": "Java_572", "language": "Java", "task_type": "if_statement", "source_file": "java/github/pgptool/pgptool/pgptool-gui/src/main/java/org/pgptool/gui/ui/tools/geometrymemory/WindowGeometryPersisterImpl.java", "mask_start_position": 2671, "mask_end_position": 2722, "canonical_solution": "if (window == null) {\n return;\n }", "pre_mask_code": "/**\n * ****************************************************************************\n * PGPTool is a desktop application for pgp encryption/decryption\n *\n * ****************************************************************************\n */\npackage org.pgptool.gui.ui.tools.geometrymemory;\n\nimport java.awt.Dimension;\nimport java.awt.Window;\nimport java.awt.event.ComponentAdapter;\nimport java.awt.event.ComponentEvent;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\nimport org.pgptool.gui.configpairs.api.ConfigPairs;\nimport org.springframework.util.StringUtils;\nimport com.google.common.base.Preconditions;\n\npublic class WindowGeometryPersisterImpl extends ComponentAdapter implements WindowGeometryPersister {\n\n static final int MINIMUM_SANE_SIZE_VALUE = 10;\n\n private static final long DELAY = 500;\n\n private static final TimeUnit DELAY_TIME_UNIT = TimeUnit.MILLISECONDS;\n\n private ConfigPairs configPairs;\n\n private ScheduledExecutorService scheduledExecutorService;\n\n private Window window;\n\n private String keyId;\n\n private ScheduledFuture sizeSetter;\n\n /**\n * @param scheduledExecutorService it's used to dealy interraction with\n * configPairs to avoid spamming it with values\n * while user still dragging element\n */\n public WindowGeometryPersisterImpl(Window window, String windowId, ConfigPairs configPairs, ScheduledExecutorService scheduledExecutorService) {\n Preconditions.checkArgument(scheduledExecutorService != null);\n Preconditions.checkArgument(window != null);\n Preconditions.checkArgument(StringUtils.hasText(windowId));\n Preconditions.checkArgument(configPairs != null);\n this.window = window;\n // version to version application windows sizes might change\n this.keyId = windowId + \"_\" + window.getMinimumSize();\n this.configPairs = configPairs;\n this.scheduledExecutorService = scheduledExecutorService;\n window.addComponentListener(this);\n }\n\n @Override\n public boolean restoreSize() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n Dimension size = configPairs.find(keySize(), null);\n if (size == null) {\n return false;\n }\n window.setSize(size);\n return true;\n }\n\n // @Override\n // Preconditions.checkState(window != null, \"instance was detached, can't do\n // much after that\");\n @Override\n public void componentResized(ComponentEvent e) {\n ", "post_mask_code": "\n Dimension size = window.getSize();\n if (size.getWidth() < MINIMUM_SANE_SIZE_VALUE || size.getHeight() < MINIMUM_SANE_SIZE_VALUE) {\n return;\n }\n if (sizeSetter != null) {\n sizeSetter.cancel(true);\n }\n sizeSetter = scheduledExecutorService.schedule(() -> configPairs.put(keySize(), window.getSize()), DELAY, DELAY_TIME_UNIT);\n }\n\n private String keySize() {\n return keyId + \"_size\";\n }\n\n // @Override\n // locationSetter = scheduledExecutorService\n @Override\n public boolean isAttached() {\n return window != null;\n }\n\n @Override\n public void detach() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n window.removeComponentListener(this);\n window = null;\n }\n}\n"} {"task_id": "Java_573", "language": "Java", "task_type": "empty", "source_file": "java/github/pgptool/pgptool/pgptool-gui/src/main/java/org/pgptool/gui/ui/tools/geometrymemory/WindowGeometryPersisterImpl.java", "mask_start_position": 1236, "mask_end_position": 1236, "canonical_solution": "", "pre_mask_code": "/**\n * ****************************************************************************\n * PGPTool is a desktop application for pgp encryption/decryption\n *\n * ****************************************************************************\n */\npackage org.pgptool.gui.ui.tools.geometrymemory;\n\nimport java.awt.Dimension;\nimport java.awt.Window;\nimport java.awt.event.ComponentAdapter;\nimport java.awt.event.ComponentEvent;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\nimport org.pgptool.gui.configpairs.api.ConfigPairs;\nimport org.springframework.util.StringUtils;\nimport com.google.common.base.Preconditions;\n\npublic class WindowGeometryPersisterImpl extends ComponentAdapter implements WindowGeometryPersister {\n\n static final int MINIMUM_SANE_SIZE_VALUE = 10;\n\n private static final long DELAY = 500;\n\n private static final TimeUnit DELAY_TIME_UNIT = TimeUnit.MILLISECONDS;\n\n private ConfigPairs configPairs;\n\n private ScheduledExecutorService scheduledExecutorService;\n\n private Window window;\n\n private String keyId;\n\n private ScheduledFuture sizeSetter;\n\n /**\n * @param scheduledExecutorService it's used to de", "post_mask_code": "aly interraction with\n * configPairs to avoid spamming it with values\n * while user still dragging element\n */\n public WindowGeometryPersisterImpl(Window window, String windowId, ConfigPairs configPairs, ScheduledExecutorService scheduledExecutorService) {\n Preconditions.checkArgument(scheduledExecutorService != null);\n Preconditions.checkArgument(window != null);\n Preconditions.checkArgument(StringUtils.hasText(windowId));\n Preconditions.checkArgument(configPairs != null);\n this.window = window;\n // version to version application windows sizes might change\n this.keyId = windowId + \"_\" + window.getMinimumSize();\n this.configPairs = configPairs;\n this.scheduledExecutorService = scheduledExecutorService;\n window.addComponentListener(this);\n }\n\n @Override\n public boolean restoreSize() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n Dimension size = configPairs.find(keySize(), null);\n if (size == null) {\n return false;\n }\n window.setSize(size);\n return true;\n }\n\n // @Override\n // Preconditions.checkState(window != null, \"instance was detached, can't do\n // much after that\");\n @Override\n public void componentResized(ComponentEvent e) {\n if (window == null) {\n return;\n }\n Dimension size = window.getSize();\n if (size.getWidth() < MINIMUM_SANE_SIZE_VALUE || size.getHeight() < MINIMUM_SANE_SIZE_VALUE) {\n return;\n }\n if (sizeSetter != null) {\n sizeSetter.cancel(true);\n }\n sizeSetter = scheduledExecutorService.schedule(() -> configPairs.put(keySize(), window.getSize()), DELAY, DELAY_TIME_UNIT);\n }\n\n private String keySize() {\n return keyId + \"_size\";\n }\n\n // @Override\n // locationSetter = scheduledExecutorService\n @Override\n public boolean isAttached() {\n return window != null;\n }\n\n @Override\n public void detach() {\n Preconditions.checkState(window != null, \"instance was detached, can't do much after that\");\n window.removeComponentListener(this);\n window = null;\n }\n}\n"} {"task_id": "Java_574", "language": "Java", "task_type": "method_signature", "source_file": "java/github/komoot/photon/src/main/java/de/komoot/photon/elasticsearch/IndexSettings.java", "mask_start_position": 1776, "mask_end_position": 1833, "canonical_solution": "public void updateIndex(Client client, String indexName) ", "pre_mask_code": "package de.komoot.photon.elasticsearch;\n\nimport org.elasticsearch.client.Client;\nimport org.elasticsearch.common.xcontent.XContentType;\nimport org.json.JSONObject;\nimport org.json.JSONTokener;\nimport java.io.InputStream;\n\n/**\n * Encapsulates the ES index settings for the photon index. Adds functions to\n * manipulate and apply the settings.\n */\npublic class IndexSettings {\n\n private final JSONObject settings;\n\n /**\n * Create a new settings object and initialize it with the index settings\n * from the resources.\n */\n public IndexSettings() {\n final InputStream indexSettings = Thread.currentThread().getContextClassLoader().getResourceAsStream(\"index_settings.json\");\n settings = new JSONObject(new JSONTokener(indexSettings));\n }\n\n /**\n * Set the number of shards to use for the index.\n *\n * @param numShards Number of shards to use.\n *\n * @return Return this object for chaining.\n */\n public IndexSettings setShards(Integer numShards) {\n if (numShards != null) {\n settings.put(\"index\", new JSONObject().put(\"number_of_shards\", numShards));\n }\n return this;\n }\n\n /**\n * Create a new index using the current index settings.\n *\n * @param client Client connection to use for creating the index.\n * @param indexName Name of the new index\n */\n public void createIndex(Client client, String indexName) {\n client.admin().indices().prepareCreate(indexName).setSettings(settings.toString(), XContentType.JSON).execute().actionGet();\n }\n\n /**\n * Update the index settings for an existing index.\n *\n * @param client Client connection to use for creating the index.\n * @param indexName Name of the index to update\n */\n ", "post_mask_code": "{\n client.admin().indices().prepareClose(PhotonIndex.NAME).execute().actionGet();\n client.admin().indices().prepareUpdateSettings(PhotonIndex.NAME).setSettings(settings.toString(), XContentType.JSON).execute().actionGet();\n client.admin().indices().prepareOpen(PhotonIndex.NAME).execute().actionGet();\n }\n}\n"} {"task_id": "Java_575", "language": "Java", "task_type": "method_body", "source_file": "java/github/komoot/photon/src/main/java/de/komoot/photon/elasticsearch/IndexSettings.java", "mask_start_position": 1833, "mask_end_position": 2161, "canonical_solution": "{\n client.admin().indices().prepareClose(PhotonIndex.NAME).execute().actionGet();\n client.admin().indices().prepareUpdateSettings(PhotonIndex.NAME).setSettings(settings.toString(), XContentType.JSON).execute().actionGet();\n client.admin().indices().prepareOpen(PhotonIndex.NAME).execute().actionGet();\n }", "pre_mask_code": "package de.komoot.photon.elasticsearch;\n\nimport org.elasticsearch.client.Client;\nimport org.elasticsearch.common.xcontent.XContentType;\nimport org.json.JSONObject;\nimport org.json.JSONTokener;\nimport java.io.InputStream;\n\n/**\n * Encapsulates the ES index settings for the photon index. Adds functions to\n * manipulate and apply the settings.\n */\npublic class IndexSettings {\n\n private final JSONObject settings;\n\n /**\n * Create a new settings object and initialize it with the index settings\n * from the resources.\n */\n public IndexSettings() {\n final InputStream indexSettings = Thread.currentThread().getContextClassLoader().getResourceAsStream(\"index_settings.json\");\n settings = new JSONObject(new JSONTokener(indexSettings));\n }\n\n /**\n * Set the number of shards to use for the index.\n *\n * @param numShards Number of shards to use.\n *\n * @return Return this object for chaining.\n */\n public IndexSettings setShards(Integer numShards) {\n if (numShards != null) {\n settings.put(\"index\", new JSONObject().put(\"number_of_shards\", numShards));\n }\n return this;\n }\n\n /**\n * Create a new index using the current index settings.\n *\n * @param client Client connection to use for creating the index.\n * @param indexName Name of the new index\n */\n public void createIndex(Client client, String indexName) {\n client.admin().indices().prepareCreate(indexName).setSettings(settings.toString(), XContentType.JSON).execute().actionGet();\n }\n\n /**\n * Update the index settings for an existing index.\n *\n * @param client Client connection to use for creating the index.\n * @param indexName Name of the index to update\n */\n public void updateIndex(Client client, String indexName) ", "post_mask_code": "\n}\n"} {"task_id": "Java_576", "language": "Java", "task_type": "single_line", "source_file": "java/github/komoot/photon/src/main/java/de/komoot/photon/elasticsearch/IndexSettings.java", "mask_start_position": 1156, "mask_end_position": 1161, "canonical_solution": "this;", "pre_mask_code": "package de.komoot.photon.elasticsearch;\n\nimport org.elasticsearch.client.Client;\nimport org.elasticsearch.common.xcontent.XContentType;\nimport org.json.JSONObject;\nimport org.json.JSONTokener;\nimport java.io.InputStream;\n\n/**\n * Encapsulates the ES index settings for the photon index. Adds functions to\n * manipulate and apply the settings.\n */\npublic class IndexSettings {\n\n private final JSONObject settings;\n\n /**\n * Create a new settings object and initialize it with the index settings\n * from the resources.\n */\n public IndexSettings() {\n final InputStream indexSettings = Thread.currentThread().getContextClassLoader().getResourceAsStream(\"index_settings.json\");\n settings = new JSONObject(new JSONTokener(indexSettings));\n }\n\n /**\n * Set the number of shards to use for the index.\n *\n * @param numShards Number of shards to use.\n *\n * @return Return this object for chaining.\n */\n public IndexSettings setShards(Integer numShards) {\n if (numShards != null) {\n settings.put(\"index\", new JSONObject().put(\"number_of_shards\", numShards));\n }\n return ", "post_mask_code": "\n }\n\n /**\n * Create a new index using the current index settings.\n *\n * @param client Client connection to use for creating the index.\n * @param indexName Name of the new index\n */\n public void createIndex(Client client, String indexName) {\n client.admin().indices().prepareCreate(indexName).setSettings(settings.toString(), XContentType.JSON).execute().actionGet();\n }\n\n /**\n * Update the index settings for an existing index.\n *\n * @param client Client connection to use for creating the index.\n * @param indexName Name of the index to update\n */\n public void updateIndex(Client client, String indexName) {\n client.admin().indices().prepareClose(PhotonIndex.NAME).execute().actionGet();\n client.admin().indices().prepareUpdateSettings(PhotonIndex.NAME).setSettings(settings.toString(), XContentType.JSON).execute().actionGet();\n client.admin().indices().prepareOpen(PhotonIndex.NAME).execute().actionGet();\n }\n}\n"} {"task_id": "Java_577", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/komoot/photon/src/main/java/de/komoot/photon/elasticsearch/IndexSettings.java", "mask_start_position": 1372, "mask_end_position": 1569, "canonical_solution": "public void createIndex(Client client, String indexName) {\n client.admin().indices().prepareCreate(indexName).setSettings(settings.toString(), XContentType.JSON).execute().actionGet();\n }", "pre_mask_code": "package de.komoot.photon.elasticsearch;\n\nimport org.elasticsearch.client.Client;\nimport org.elasticsearch.common.xcontent.XContentType;\nimport org.json.JSONObject;\nimport org.json.JSONTokener;\nimport java.io.InputStream;\n\n/**\n * Encapsulates the ES index settings for the photon index. Adds functions to\n * manipulate and apply the settings.\n */\npublic class IndexSettings {\n\n private final JSONObject settings;\n\n /**\n * Create a new settings object and initialize it with the index settings\n * from the resources.\n */\n public IndexSettings() {\n final InputStream indexSettings = Thread.currentThread().getContextClassLoader().getResourceAsStream(\"index_settings.json\");\n settings = new JSONObject(new JSONTokener(indexSettings));\n }\n\n /**\n * Set the number of shards to use for the index.\n *\n * @param numShards Number of shards to use.\n *\n * @return Return this object for chaining.\n */\n public IndexSettings setShards(Integer numShards) {\n if (numShards != null) {\n settings.put(\"index\", new JSONObject().put(\"number_of_shards\", numShards));\n }\n return this;\n }\n\n /**\n * Create a new index using the current index settings.\n *\n * @param client Client connection to use for creating the index.\n * @param indexName Name of the new index\n */\n ", "post_mask_code": "\n\n /**\n * Update the index settings for an existing index.\n *\n * @param client Client connection to use for creating the index.\n * @param indexName Name of the index to update\n */\n public void updateIndex(Client client, String indexName) {\n client.admin().indices().prepareClose(PhotonIndex.NAME).execute().actionGet();\n client.admin().indices().prepareUpdateSettings(PhotonIndex.NAME).setSettings(settings.toString(), XContentType.JSON).execute().actionGet();\n client.admin().indices().prepareOpen(PhotonIndex.NAME).execute().actionGet();\n }\n}\n"} {"task_id": "Java_578", "language": "Java", "task_type": "if_statement", "source_file": "java/github/komoot/photon/src/main/java/de/komoot/photon/elasticsearch/IndexSettings.java", "mask_start_position": 1018, "mask_end_position": 1140, "canonical_solution": "if (numShards != null) {\n settings.put(\"index\", new JSONObject().put(\"number_of_shards\", numShards));\n }", "pre_mask_code": "package de.komoot.photon.elasticsearch;\n\nimport org.elasticsearch.client.Client;\nimport org.elasticsearch.common.xcontent.XContentType;\nimport org.json.JSONObject;\nimport org.json.JSONTokener;\nimport java.io.InputStream;\n\n/**\n * Encapsulates the ES index settings for the photon index. Adds functions to\n * manipulate and apply the settings.\n */\npublic class IndexSettings {\n\n private final JSONObject settings;\n\n /**\n * Create a new settings object and initialize it with the index settings\n * from the resources.\n */\n public IndexSettings() {\n final InputStream indexSettings = Thread.currentThread().getContextClassLoader().getResourceAsStream(\"index_settings.json\");\n settings = new JSONObject(new JSONTokener(indexSettings));\n }\n\n /**\n * Set the number of shards to use for the index.\n *\n * @param numShards Number of shards to use.\n *\n * @return Return this object for chaining.\n */\n public IndexSettings setShards(Integer numShards) {\n ", "post_mask_code": "\n return this;\n }\n\n /**\n * Create a new index using the current index settings.\n *\n * @param client Client connection to use for creating the index.\n * @param indexName Name of the new index\n */\n public void createIndex(Client client, String indexName) {\n client.admin().indices().prepareCreate(indexName).setSettings(settings.toString(), XContentType.JSON).execute().actionGet();\n }\n\n /**\n * Update the index settings for an existing index.\n *\n * @param client Client connection to use for creating the index.\n * @param indexName Name of the index to update\n */\n public void updateIndex(Client client, String indexName) {\n client.admin().indices().prepareClose(PhotonIndex.NAME).execute().actionGet();\n client.admin().indices().prepareUpdateSettings(PhotonIndex.NAME).setSettings(settings.toString(), XContentType.JSON).execute().actionGet();\n client.admin().indices().prepareOpen(PhotonIndex.NAME).execute().actionGet();\n }\n}\n"} {"task_id": "Java_579", "language": "Java", "task_type": "empty", "source_file": "java/github/komoot/photon/src/main/java/de/komoot/photon/elasticsearch/IndexSettings.java", "mask_start_position": 1299, "mask_end_position": 1299, "canonical_solution": "", "pre_mask_code": "package de.komoot.photon.elasticsearch;\n\nimport org.elasticsearch.client.Client;\nimport org.elasticsearch.common.xcontent.XContentType;\nimport org.json.JSONObject;\nimport org.json.JSONTokener;\nimport java.io.InputStream;\n\n/**\n * Encapsulates the ES index settings for the photon index. Adds functions to\n * manipulate and apply the settings.\n */\npublic class IndexSettings {\n\n private final JSONObject settings;\n\n /**\n * Create a new settings object and initialize it with the index settings\n * from the resources.\n */\n public IndexSettings() {\n final InputStream indexSettings = Thread.currentThread().getContextClassLoader().getResourceAsStream(\"index_settings.json\");\n settings = new JSONObject(new JSONTokener(indexSettings));\n }\n\n /**\n * Set the number of shards to use for the index.\n *\n * @param numShards Number of shards to use.\n *\n * @return Return this object for chaining.\n */\n public IndexSettings setShards(Integer numShards) {\n if (numShards != null) {\n settings.put(\"index\", new JSONObject().put(\"number_of_shards\", numShards));\n }\n return this;\n }\n\n /**\n * Create a new index using the current index settings.\n *\n * @param client Client connection to use for creat", "post_mask_code": "ing the index.\n * @param indexName Name of the new index\n */\n public void createIndex(Client client, String indexName) {\n client.admin().indices().prepareCreate(indexName).setSettings(settings.toString(), XContentType.JSON).execute().actionGet();\n }\n\n /**\n * Update the index settings for an existing index.\n *\n * @param client Client connection to use for creating the index.\n * @param indexName Name of the index to update\n */\n public void updateIndex(Client client, String indexName) {\n client.admin().indices().prepareClose(PhotonIndex.NAME).execute().actionGet();\n client.admin().indices().prepareUpdateSettings(PhotonIndex.NAME).setSettings(settings.toString(), XContentType.JSON).execute().actionGet();\n client.admin().indices().prepareOpen(PhotonIndex.NAME).execute().actionGet();\n }\n}\n"} {"task_id": "Java_580", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Mrfzh/FReader/app/src/main/java/com/feng/freader/presenter/PressPresenter.java", "mask_start_position": 742, "mask_end_position": 808, "canonical_solution": "@Override\n public void getCategoryNovelsError(String errorMsg) ", "pre_mask_code": "package com.feng.freader.presenter;\n\nimport com.feng.freader.base.BasePresenter;\nimport com.feng.freader.constract.IPressContract;\nimport com.feng.freader.entity.data.DiscoveryNovelData;\nimport com.feng.freader.model.PressModel;\nimport java.util.List;\n\n/**\n * @author Feng Zhaohao\n * Created on 2019/12/22\n */\npublic class PressPresenter extends BasePresenter implements IPressContract.Presenter {\n\n private IPressContract.Model mModel;\n\n public PressPresenter() {\n mModel = new PressModel(this);\n }\n\n @Override\n public void getCategoryNovelsSuccess(List dataList) {\n if (isAttachView()) {\n getMvpView().getCategoryNovelsSuccess(dataList);\n }\n }\n\n ", "post_mask_code": "{\n if (isAttachView()) {\n getMvpView().getCategoryNovelsError(errorMsg);\n }\n }\n\n @Override\n public void getCategoryNovels() {\n mModel.getCategoryNovels();\n }\n}\n"} {"task_id": "Java_581", "language": "Java", "task_type": "method_body", "source_file": "java/github/Mrfzh/FReader/app/src/main/java/com/feng/freader/presenter/PressPresenter.java", "mask_start_position": 808, "mask_end_position": 914, "canonical_solution": "{\n if (isAttachView()) {\n getMvpView().getCategoryNovelsError(errorMsg);\n }\n }", "pre_mask_code": "package com.feng.freader.presenter;\n\nimport com.feng.freader.base.BasePresenter;\nimport com.feng.freader.constract.IPressContract;\nimport com.feng.freader.entity.data.DiscoveryNovelData;\nimport com.feng.freader.model.PressModel;\nimport java.util.List;\n\n/**\n * @author Feng Zhaohao\n * Created on 2019/12/22\n */\npublic class PressPresenter extends BasePresenter implements IPressContract.Presenter {\n\n private IPressContract.Model mModel;\n\n public PressPresenter() {\n mModel = new PressModel(this);\n }\n\n @Override\n public void getCategoryNovelsSuccess(List dataList) {\n if (isAttachView()) {\n getMvpView().getCategoryNovelsSuccess(dataList);\n }\n }\n\n @Override\n public void getCategoryNovelsError(String errorMsg) ", "post_mask_code": "\n\n @Override\n public void getCategoryNovels() {\n mModel.getCategoryNovels();\n }\n}\n"} {"task_id": "Java_582", "language": "Java", "task_type": "single_line", "source_file": "java/github/Mrfzh/FReader/app/src/main/java/com/feng/freader/presenter/PressPresenter.java", "mask_start_position": 982, "mask_end_position": 1003, "canonical_solution": ".getCategoryNovels();", "pre_mask_code": "package com.feng.freader.presenter;\n\nimport com.feng.freader.base.BasePresenter;\nimport com.feng.freader.constract.IPressContract;\nimport com.feng.freader.entity.data.DiscoveryNovelData;\nimport com.feng.freader.model.PressModel;\nimport java.util.List;\n\n/**\n * @author Feng Zhaohao\n * Created on 2019/12/22\n */\npublic class PressPresenter extends BasePresenter implements IPressContract.Presenter {\n\n private IPressContract.Model mModel;\n\n public PressPresenter() {\n mModel = new PressModel(this);\n }\n\n @Override\n public void getCategoryNovelsSuccess(List dataList) {\n if (isAttachView()) {\n getMvpView().getCategoryNovelsSuccess(dataList);\n }\n }\n\n @Override\n public void getCategoryNovelsError(String errorMsg) {\n if (isAttachView()) {\n getMvpView().getCategoryNovelsError(errorMsg);\n }\n }\n\n @Override\n public void getCategoryNovels() {\n mModel", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_583", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Mrfzh/FReader/app/src/main/java/com/feng/freader/presenter/PressPresenter.java", "mask_start_position": 818, "mask_end_position": 908, "canonical_solution": "if (isAttachView()) {\n getMvpView().getCategoryNovelsError(errorMsg);\n }", "pre_mask_code": "package com.feng.freader.presenter;\n\nimport com.feng.freader.base.BasePresenter;\nimport com.feng.freader.constract.IPressContract;\nimport com.feng.freader.entity.data.DiscoveryNovelData;\nimport com.feng.freader.model.PressModel;\nimport java.util.List;\n\n/**\n * @author Feng Zhaohao\n * Created on 2019/12/22\n */\npublic class PressPresenter extends BasePresenter implements IPressContract.Presenter {\n\n private IPressContract.Model mModel;\n\n public PressPresenter() {\n mModel = new PressModel(this);\n }\n\n @Override\n public void getCategoryNovelsSuccess(List dataList) {\n if (isAttachView()) {\n getMvpView().getCategoryNovelsSuccess(dataList);\n }\n }\n\n @Override\n public void getCategoryNovelsError(String errorMsg) {\n ", "post_mask_code": "\n }\n\n @Override\n public void getCategoryNovels() {\n mModel.getCategoryNovels();\n }\n}\n"} {"task_id": "Java_584", "language": "Java", "task_type": "empty", "source_file": "java/github/Mrfzh/FReader/app/src/main/java/com/feng/freader/presenter/PressPresenter.java", "mask_start_position": 650, "mask_end_position": 650, "canonical_solution": "", "pre_mask_code": "package com.feng.freader.presenter;\n\nimport com.feng.freader.base.BasePresenter;\nimport com.feng.freader.constract.IPressContract;\nimport com.feng.freader.entity.data.DiscoveryNovelData;\nimport com.feng.freader.model.PressModel;\nimport java.util.List;\n\n/**\n * @author Feng Zhaohao\n * Created on 2019/12/22\n */\npublic class PressPresenter extends BasePresenter implements IPressContract.Presenter {\n\n private IPressContract.Model mModel;\n\n public PressPresenter() {\n mModel = new PressModel(this);\n }\n\n @Override\n public void getCategoryNovelsSuccess(List dataList) {\n if (isAttach", "post_mask_code": "View()) {\n getMvpView().getCategoryNovelsSuccess(dataList);\n }\n }\n\n @Override\n public void getCategoryNovelsError(String errorMsg) {\n if (isAttachView()) {\n getMvpView().getCategoryNovelsError(errorMsg);\n }\n }\n\n @Override\n public void getCategoryNovels() {\n mModel.getCategoryNovels();\n }\n}\n"} {"task_id": "Java_585", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/cmu-phil/tetrad/tetrad-lib/src/main/java/edu/cmu/tetrad/bayes/DiscreteProbs.java", "mask_start_position": 593, "mask_end_position": 624, "canonical_solution": "double getCellProb(int[] cell);", "pre_mask_code": "// For information as to what this class does, see the Javadoc, below. //\npackage edu.cmu.tetrad.bayes;\n\nimport edu.cmu.tetrad.graph.Node;\nimport java.util.List;\n\n/**\n * Interface containing methods to calculate probabilities for systems of\n * discrete variables. See instantiations for more details.\n *\n * @author Joseph Ramsey\n */\ninterface DiscreteProbs {\n\n /**\n * @return the variables over which probabilities and conditional\n * probabilities will be calculated.\n */\n List getVariables();\n\n /**\n * @return the probability in a given cell.\n */\n ", "post_mask_code": "\n\n /**\n * Calculates the probability P(a), where a is a two dimensional boolean\n * array, with a[i] representing particular combinations of values for\n * bayesIm.getNode(i) as boolean arrays of length bayesim.getNumSplits(i),\n * with a[i][j] = true iff the condition includes the j'th value of\n * bayesIm.getNode(i).\n */\n double getProb(Proposition assertion);\n\n /**\n *

Calculates the conditional probability P(a|b), where a and b are two\n * dimensional boolean arrays, with a[i] and b[i] representing particular\n * combinations of values for bayesIm.getNode(i) as boolean arrays of length\n * bayesim.getNumSplits(i), with a[i][j] = true iff the condition\n * includes the j'th value of bayesIm.getNode(i), and similarly for\n * b[i][j].

This does not allow all possible conditional\n * probabilities to be calculated, since for instance the condition X1 = 1\n * or X2 = 2 cannot be represented this way directly, but it does capture\n * all conditions for which this type of method would generally be of\n * interest.

\n */\n double getConditionalProb(Proposition assertion, Proposition condition);\n\n /**\n * @return true if a missing values case was encountered during the last\n * method call.\n */\n boolean isMissingValueCaseFound();\n}\n"} {"task_id": "Java_586", "language": "Java", "task_type": "empty", "source_file": "java/github/cmu-phil/tetrad/tetrad-lib/src/main/java/edu/cmu/tetrad/bayes/DiscreteProbs.java", "mask_start_position": 787, "mask_end_position": 787, "canonical_solution": "", "pre_mask_code": "// For information as to what this class does, see the Javadoc, below. //\npackage edu.cmu.tetrad.bayes;\n\nimport edu.cmu.tetrad.graph.Node;\nimport java.util.List;\n\n/**\n * Interface containing methods to calculate probabilities for systems of\n * discrete variables. See instantiations for more details.\n *\n * @author Joseph Ramsey\n */\ninterface DiscreteProbs {\n\n /**\n * @return the variables over which probabilities and conditional\n * probabilities will be calculated.\n */\n List getVariables();\n\n /**\n * @return the probability in a given cell.\n */\n double getCellProb(int[] cell);\n\n /**\n * Calculates the probability P(a), where a is a two dimensional boolean\n * array, with a[i] representing particular combinations of values for\n ", "post_mask_code": " * bayesIm.getNode(i) as boolean arrays of length bayesim.getNumSplits(i),\n * with a[i][j] = true iff the condition includes the j'th value of\n * bayesIm.getNode(i).\n */\n double getProb(Proposition assertion);\n\n /**\n *

Calculates the conditional probability P(a|b), where a and b are two\n * dimensional boolean arrays, with a[i] and b[i] representing particular\n * combinations of values for bayesIm.getNode(i) as boolean arrays of length\n * bayesim.getNumSplits(i), with a[i][j] = true iff the condition\n * includes the j'th value of bayesIm.getNode(i), and similarly for\n * b[i][j].

This does not allow all possible conditional\n * probabilities to be calculated, since for instance the condition X1 = 1\n * or X2 = 2 cannot be represented this way directly, but it does capture\n * all conditions for which this type of method would generally be of\n * interest.

\n */\n double getConditionalProb(Proposition assertion, Proposition condition);\n\n /**\n * @return true if a missing values case was encountered during the last\n * method call.\n */\n boolean isMissingValueCaseFound();\n}\n"} {"task_id": "Java_587", "language": "Java", "task_type": "method_signature", "source_file": "java/github/nayuki/Nayuki-web-published-code/go-train-acceleration-analyzed-by-video/PreprocessFrames.java", "mask_start_position": 16866, "mask_end_position": 16921, "canonical_solution": "private static double windowedSinc(double x, double y) ", "pre_mask_code": "/* \n * Preprocess frames\n * \n * All rights reserved. Contact Nayuki for licensing.\n * http://example.com\n */\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport javax.imageio.ImageIO;\n\npublic final class PreprocessFrames {\n\n // Configuration\n private static final int INPUT_FRAME_START = 990;\n\n private static final int INPUT_FRAME_END = 3900;\n\n private static final int INPUT_FRAME_DECIMATE = 3;\n\n private static final int IMAGE_WIDTH = 1280;\n\n private static final int IMAGE_HEIGHT = 192;\n\n private static final int IMAGE_UPSCALE = 4;\n\n public static void main(String[] args) throws IOException {\n // Get and check arguments\n if (args.length != 2) {\n System.err.println(\"Usage: java PreprocessFrames InDir OutDir\");\n System.exit(1);\n return;\n }\n File inDir = new File(args[0]);\n File outDir = new File(args[1]);\n if (!inDir.isDirectory())\n throw new RuntimeException(\"Invalid input directory\");\n if (!outDir.isDirectory())\n throw new RuntimeException(\"Invalid output directory\");\n // Process image frames\n for (int inFrame = INPUT_FRAME_START, outFrame = 0; inFrame < INPUT_FRAME_END; inFrame += INPUT_FRAME_DECIMATE, outFrame++) {\n File inFile = new File(inDir, String.format(\"%04d.bmp\", inFrame));\n File outFile = new File(outDir, String.format(\"%04d.bmp\", outFrame));\n FastSincImageResampler.resampleFile(inFile, IMAGE_WIDTH * IMAGE_UPSCALE, IMAGE_HEIGHT * IMAGE_UPSCALE, outFile);\n System.out.printf(\"%s --> %s%n\", inFile.getName(), outFile.getName());\n }\n }\n\n // Based on http://example.com\n private static final class FastSincImageResampler {\n\n /* Convenience methods */\n /**\n * Resamples the specified image file to the specified output dimensions, writing to the specified output file.\n * @param inFile the input image file (must be in BMP or PNG format)\n * @param outWidth the output image width (must be positive)\n * @param outHeight the output image height (must be positive)\n * @param outFile the output image file\n * @throws IOException if an I/O exception occurred in reading the input image file or writing the output image file\n */\n public static void resampleFile(File inFile, int outWidth, int outHeight, File outFile) throws IOException {\n FastSincImageResampler rs = new FastSincImageResampler();\n rs.inputFile = inFile;\n rs.outputWidth = outWidth;\n rs.outputHeight = outHeight;\n rs.outputFile = outFile;\n rs.run();\n }\n\n /* Full functionality */\n public File inputFile = null;\n\n public BufferedImage inputImage = null;\n\n // run() does not read this, but will overwrite this field\n public int inputWidth = -1;\n\n // run() does not read this, but will overwrite this field\n public int inputHeight = -1;\n\n // Must set to a positive number\n public int outputWidth = -1;\n\n // Must set to a positive number\n public int outputHeight = -1;\n\n // Horizontal filter length (set a positive value, otherwise an automatic default value will be computed)\n public double horizontalFilterLength = -1;\n\n // Vertical filter length (set a positive value, otherwise an automatic default value will be computed)\n public double verticalFilterLength = -1;\n\n // Number of threads to use (set a positive value, otherwise an automatic default value will be computed)\n public int threads = -1;\n\n // run() does not read this, but will overwrite this field\n public BufferedImage outputImage = null;\n\n public File outputFile = null;\n\n // Must be \"png\", \"bmp\", or null (auto-detection based on outputFile's extension)\n public String outputFileType = null;\n\n /**\n * Constructs a blank resampler object - certain fields must be set before calling {@code run()}.\n */\n public FastSincImageResampler() {\n }\n\n /**\n * Runs the resampler. The data flow operates on a \"waterfall\" model, reading and writing the fields from top to bottom:\n *
    \n *
  1. If {@code inputFile} is non-{@code null}, then it is read into {@code inputImage}.
  2. \n *
  3. {@code inputImage} needs to be non-{@code null} now (set explicitly or read from {@code inputFile}).
  4. \n *
  5. {@code inputImage} is read into {@code inputWidth} and {@code inputHeight}.
  6. \n *
  7. {@code outputWidth} and {@code outputHeight} must be positive (set explicitly).
  8. \n *
  9. If a filter length is zero or negative, then a default filter length is computed and set for that axis.
  10. \n *
  11. If {@code threads} is zero or negative, then a default number of threads is computed and set.
  12. \n *
  13. {@code outputImage} is computed by resampling {@code inputImage}. (This is the main purpose of the class.)
  14. \n *
  15. If {@code outputFile} is non-{@code null} and {@code outputFileType} is {@code null}: The type is set to {@code \"png\"} or {@code \"bmp\"}\n * if the output file has that extension (case-insensitive), otherwise it is set to {@code \"png\"} by default.
  16. \n *
  17. If {@code outputFile} is non-{@code null}, then {@code outputImage} is written to the file.
  18. \n *
\n *

After calling {@code run()}, it is recommend that this object should not be reused for another resampling operation.\n * This is because various fields probably need to be cleared, such as the filter length and output file type.

\n * @throws IOException if an I/O exception occurred\n * @throws IllegalStateException if there is no input image or the output dimensions are not set to positive values\n */\n public void run() throws IOException {\n // Read input file (optional)\n if (inputFile != null) {\n try {\n inputImage = ImageIO.read(inputFile);\n } catch (IOException e) {\n throw new IOException(\"Error reading input file (\" + inputFile + \"): \" + e.getMessage(), e);\n }\n }\n // Get input image dimensions\n if (inputImage == null)\n throw new IllegalStateException(\"No input image\");\n inputWidth = inputImage.getWidth();\n inputHeight = inputImage.getHeight();\n // Calculate filter lengths (optional)\n if (outputWidth <= 0 || outputHeight <= 0)\n throw new IllegalStateException(\"Output dimensions not set\");\n if (horizontalFilterLength <= 0)\n horizontalFilterLength = Math.max((double) inputWidth / outputWidth, 1) * 4.0;\n if (verticalFilterLength <= 0)\n verticalFilterLength = Math.max((double) inputHeight / outputHeight, 1) * 4.0;\n // Resample the image\n if (threads <= 0)\n threads = Runtime.getRuntime().availableProcessors();\n resampleImage();\n // Write output file (optional)\n if (outputFile != null) {\n if (outputFileType == null) {\n // Auto-detection by file extension\n String lowername = outputFile.getName().toLowerCase();\n if (lowername.endsWith(\".bmp\"))\n outputFileType = \"bmp\";\n else\n // Default\n outputFileType = \"png\";\n }\n try {\n ImageIO.write(outputImage, outputFileType, outputFile);\n } catch (IOException e) {\n throw new IOException(\"Error writing output file (\" + outputFile + \"): \" + e.getMessage(), e);\n }\n }\n }\n\n private void resampleImage() {\n final int inWidth = inputWidth;\n final int inHeight = inputHeight;\n final int outWidth = outputWidth;\n final int outHeight = outputHeight;\n // Get packed int pixels\n int[] inPixels = new int[inWidth * inHeight];\n inputImage.getRGB(0, 0, inWidth, inHeight, inPixels, 0, inWidth);\n // Convert to float\n final float[] inVert = new float[inWidth * inHeight * 3];\n for (int i = 0, j = 0; i < inPixels.length; i++, j += 3) {\n int rgb = inPixels[i];\n inVert[j + 0] = (float) Math.pow(((rgb >>> 16) & 0xFF) / 255.0, 2.2);\n inVert[j + 1] = (float) Math.pow(((rgb >>> 8) & 0xFF) / 255.0, 2.2);\n inVert[j + 2] = (float) Math.pow(((rgb >>> 0) & 0xFF) / 255.0, 2.2);\n }\n inPixels = null;\n Thread[] thr = new Thread[threads];\n final AtomicInteger sharedY = new AtomicInteger(0);\n final float[] inHorz = new float[inWidth * outHeight * 3];\n final CyclicBarrier barrier = new CyclicBarrier(threads);\n final AtomicInteger sharedX = new AtomicInteger(0);\n final int[] outPixels = new int[outWidth * outHeight];\n for (int i = 0; i < thr.length; i++) {\n thr[i] = new Thread() {\n\n public void run() {\n // Resample vertically and transpose\n {\n double sincScale = Math.min((double) outHeight / inHeight, 1);\n double[] weights = new double[(int) verticalFilterLength + 1];\n float[] outVertRow = new float[inWidth * 3];\n while (true) {\n // For each output row\n int y = sharedY.getAndIncrement();\n if (y >= outHeight)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerY = (y + 0.5) / outHeight * inHeight;\n double filterStartY = centerY - verticalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartY - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputY = startIndex + i;\n double weight = windowedSinc((inputY + 0.5 - centerY) * sincScale, (inputY + 0.5 - filterStartY) / verticalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outVertRow, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputY = Math.min(Math.max(startIndex + i, 0), inHeight - 1);\n for (int x = 0; x < inWidth; x++) {\n // For each pixel in the row\n int j = (clippedInputY * inWidth + x) * 3;\n outVertRow[x * 3 + 0] += inVert[j + 0] * weight;\n outVertRow[x * 3 + 1] += inVert[j + 1] * weight;\n outVertRow[x * 3 + 2] += inVert[j + 2] * weight;\n }\n }\n for (int x = 0; x < inWidth; x++) {\n int j = (x * outHeight + y) * 3;\n inHorz[j + 0] = outVertRow[x * 3 + 0];\n inHorz[j + 1] = outVertRow[x * 3 + 1];\n inHorz[j + 2] = outVertRow[x * 3 + 2];\n }\n }\n }\n // Wait for all threads to finish the phase\n try {\n barrier.await();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n } catch (BrokenBarrierException e) {\n throw new RuntimeException(e);\n }\n // Resample horizontally and transpose\n {\n double sincScale = Math.min((double) outWidth / inWidth, 1);\n double[] weights = new double[(int) horizontalFilterLength + 1];\n double[] outHorzCol = new double[outHeight * 3];\n while (true) {\n // For each output column\n int x = sharedX.getAndIncrement();\n if (x >= outWidth)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerX = (x + 0.5) / outWidth * inWidth;\n double filterStartX = centerX - horizontalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartX - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputX = startIndex + i;\n double weight = windowedSinc((inputX + 0.5 - centerX) * sincScale, (inputX + 0.5 - filterStartX) / horizontalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outHorzCol, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputX = Math.min(Math.max(startIndex + i, 0), inWidth - 1);\n for (int y = 0; y < outHeight; y++) {\n // For each pixel in the column\n int j = (clippedInputX * outHeight + y) * 3;\n outHorzCol[y * 3 + 0] += inHorz[j + 0] * weight;\n outHorzCol[y * 3 + 1] += inHorz[j + 1] * weight;\n outHorzCol[y * 3 + 2] += inHorz[j + 2] * weight;\n }\n }\n for (int y = 0; y < outHeight; y++) {\n // Convert to 8 bits per channel and pack integers\n double r = outHorzCol[y * 3 + 0] * 255;\n if (r < 0)\n r = 0;\n if (r > 255)\n r = 255;\n double g = outHorzCol[y * 3 + 1] * 255;\n if (g < 0)\n g = 0;\n if (g > 255)\n g = 255;\n double b = outHorzCol[y * 3 + 2] * 255;\n if (b < 0)\n b = 0;\n if (b > 255)\n b = 255;\n outPixels[y * outWidth + x] = (int) (r + 0.5) << 16 | (int) (g + 0.5) << 8 | (int) (b + 0.5);\n }\n }\n }\n }\n };\n thr[i].start();\n }\n try {\n for (Thread th : thr) th.join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n outputImage = new BufferedImage(outWidth, outHeight, BufferedImage.TYPE_INT_RGB);\n outputImage.setRGB(0, 0, outWidth, outHeight, outPixels, 0, outWidth);\n }\n\n // x is measured in half-cycles; y is for the window which has the domain [0, 1]\n ", "post_mask_code": "{\n x *= Math.PI;\n double sinc = x != 0 ? Math.sin(x) / x : 1;\n // Triangle window\n double window = 0 <= y && y <= 1 ? 1 - Math.abs(y - 0.5) * 2 : 0;\n return sinc * window;\n }\n }\n}\n"} {"task_id": "Java_588", "language": "Java", "task_type": "method_body", "source_file": "java/github/nayuki/Nayuki-web-published-code/go-train-acceleration-analyzed-by-video/PreprocessFrames.java", "mask_start_position": 2648, "mask_end_position": 2903, "canonical_solution": "{\n FastSincImageResampler rs = new FastSincImageResampler();\n rs.inputFile = inFile;\n rs.outputWidth = outWidth;\n rs.outputHeight = outHeight;\n rs.outputFile = outFile;\n rs.run();\n }", "pre_mask_code": "/* \n * Preprocess frames\n * \n * All rights reserved. Contact Nayuki for licensing.\n * http://example.com\n */\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport javax.imageio.ImageIO;\n\npublic final class PreprocessFrames {\n\n // Configuration\n private static final int INPUT_FRAME_START = 990;\n\n private static final int INPUT_FRAME_END = 3900;\n\n private static final int INPUT_FRAME_DECIMATE = 3;\n\n private static final int IMAGE_WIDTH = 1280;\n\n private static final int IMAGE_HEIGHT = 192;\n\n private static final int IMAGE_UPSCALE = 4;\n\n public static void main(String[] args) throws IOException {\n // Get and check arguments\n if (args.length != 2) {\n System.err.println(\"Usage: java PreprocessFrames InDir OutDir\");\n System.exit(1);\n return;\n }\n File inDir = new File(args[0]);\n File outDir = new File(args[1]);\n if (!inDir.isDirectory())\n throw new RuntimeException(\"Invalid input directory\");\n if (!outDir.isDirectory())\n throw new RuntimeException(\"Invalid output directory\");\n // Process image frames\n for (int inFrame = INPUT_FRAME_START, outFrame = 0; inFrame < INPUT_FRAME_END; inFrame += INPUT_FRAME_DECIMATE, outFrame++) {\n File inFile = new File(inDir, String.format(\"%04d.bmp\", inFrame));\n File outFile = new File(outDir, String.format(\"%04d.bmp\", outFrame));\n FastSincImageResampler.resampleFile(inFile, IMAGE_WIDTH * IMAGE_UPSCALE, IMAGE_HEIGHT * IMAGE_UPSCALE, outFile);\n System.out.printf(\"%s --> %s%n\", inFile.getName(), outFile.getName());\n }\n }\n\n // Based on http://example.com\n private static final class FastSincImageResampler {\n\n /* Convenience methods */\n /**\n * Resamples the specified image file to the specified output dimensions, writing to the specified output file.\n * @param inFile the input image file (must be in BMP or PNG format)\n * @param outWidth the output image width (must be positive)\n * @param outHeight the output image height (must be positive)\n * @param outFile the output image file\n * @throws IOException if an I/O exception occurred in reading the input image file or writing the output image file\n */\n public static void resampleFile(File inFile, int outWidth, int outHeight, File outFile) throws IOException ", "post_mask_code": "\n\n /* Full functionality */\n public File inputFile = null;\n\n public BufferedImage inputImage = null;\n\n // run() does not read this, but will overwrite this field\n public int inputWidth = -1;\n\n // run() does not read this, but will overwrite this field\n public int inputHeight = -1;\n\n // Must set to a positive number\n public int outputWidth = -1;\n\n // Must set to a positive number\n public int outputHeight = -1;\n\n // Horizontal filter length (set a positive value, otherwise an automatic default value will be computed)\n public double horizontalFilterLength = -1;\n\n // Vertical filter length (set a positive value, otherwise an automatic default value will be computed)\n public double verticalFilterLength = -1;\n\n // Number of threads to use (set a positive value, otherwise an automatic default value will be computed)\n public int threads = -1;\n\n // run() does not read this, but will overwrite this field\n public BufferedImage outputImage = null;\n\n public File outputFile = null;\n\n // Must be \"png\", \"bmp\", or null (auto-detection based on outputFile's extension)\n public String outputFileType = null;\n\n /**\n * Constructs a blank resampler object - certain fields must be set before calling {@code run()}.\n */\n public FastSincImageResampler() {\n }\n\n /**\n * Runs the resampler. The data flow operates on a \"waterfall\" model, reading and writing the fields from top to bottom:\n *
    \n *
  1. If {@code inputFile} is non-{@code null}, then it is read into {@code inputImage}.
  2. \n *
  3. {@code inputImage} needs to be non-{@code null} now (set explicitly or read from {@code inputFile}).
  4. \n *
  5. {@code inputImage} is read into {@code inputWidth} and {@code inputHeight}.
  6. \n *
  7. {@code outputWidth} and {@code outputHeight} must be positive (set explicitly).
  8. \n *
  9. If a filter length is zero or negative, then a default filter length is computed and set for that axis.
  10. \n *
  11. If {@code threads} is zero or negative, then a default number of threads is computed and set.
  12. \n *
  13. {@code outputImage} is computed by resampling {@code inputImage}. (This is the main purpose of the class.)
  14. \n *
  15. If {@code outputFile} is non-{@code null} and {@code outputFileType} is {@code null}: The type is set to {@code \"png\"} or {@code \"bmp\"}\n * if the output file has that extension (case-insensitive), otherwise it is set to {@code \"png\"} by default.
  16. \n *
  17. If {@code outputFile} is non-{@code null}, then {@code outputImage} is written to the file.
  18. \n *
\n *

After calling {@code run()}, it is recommend that this object should not be reused for another resampling operation.\n * This is because various fields probably need to be cleared, such as the filter length and output file type.

\n * @throws IOException if an I/O exception occurred\n * @throws IllegalStateException if there is no input image or the output dimensions are not set to positive values\n */\n public void run() throws IOException {\n // Read input file (optional)\n if (inputFile != null) {\n try {\n inputImage = ImageIO.read(inputFile);\n } catch (IOException e) {\n throw new IOException(\"Error reading input file (\" + inputFile + \"): \" + e.getMessage(), e);\n }\n }\n // Get input image dimensions\n if (inputImage == null)\n throw new IllegalStateException(\"No input image\");\n inputWidth = inputImage.getWidth();\n inputHeight = inputImage.getHeight();\n // Calculate filter lengths (optional)\n if (outputWidth <= 0 || outputHeight <= 0)\n throw new IllegalStateException(\"Output dimensions not set\");\n if (horizontalFilterLength <= 0)\n horizontalFilterLength = Math.max((double) inputWidth / outputWidth, 1) * 4.0;\n if (verticalFilterLength <= 0)\n verticalFilterLength = Math.max((double) inputHeight / outputHeight, 1) * 4.0;\n // Resample the image\n if (threads <= 0)\n threads = Runtime.getRuntime().availableProcessors();\n resampleImage();\n // Write output file (optional)\n if (outputFile != null) {\n if (outputFileType == null) {\n // Auto-detection by file extension\n String lowername = outputFile.getName().toLowerCase();\n if (lowername.endsWith(\".bmp\"))\n outputFileType = \"bmp\";\n else\n // Default\n outputFileType = \"png\";\n }\n try {\n ImageIO.write(outputImage, outputFileType, outputFile);\n } catch (IOException e) {\n throw new IOException(\"Error writing output file (\" + outputFile + \"): \" + e.getMessage(), e);\n }\n }\n }\n\n private void resampleImage() {\n final int inWidth = inputWidth;\n final int inHeight = inputHeight;\n final int outWidth = outputWidth;\n final int outHeight = outputHeight;\n // Get packed int pixels\n int[] inPixels = new int[inWidth * inHeight];\n inputImage.getRGB(0, 0, inWidth, inHeight, inPixels, 0, inWidth);\n // Convert to float\n final float[] inVert = new float[inWidth * inHeight * 3];\n for (int i = 0, j = 0; i < inPixels.length; i++, j += 3) {\n int rgb = inPixels[i];\n inVert[j + 0] = (float) Math.pow(((rgb >>> 16) & 0xFF) / 255.0, 2.2);\n inVert[j + 1] = (float) Math.pow(((rgb >>> 8) & 0xFF) / 255.0, 2.2);\n inVert[j + 2] = (float) Math.pow(((rgb >>> 0) & 0xFF) / 255.0, 2.2);\n }\n inPixels = null;\n Thread[] thr = new Thread[threads];\n final AtomicInteger sharedY = new AtomicInteger(0);\n final float[] inHorz = new float[inWidth * outHeight * 3];\n final CyclicBarrier barrier = new CyclicBarrier(threads);\n final AtomicInteger sharedX = new AtomicInteger(0);\n final int[] outPixels = new int[outWidth * outHeight];\n for (int i = 0; i < thr.length; i++) {\n thr[i] = new Thread() {\n\n public void run() {\n // Resample vertically and transpose\n {\n double sincScale = Math.min((double) outHeight / inHeight, 1);\n double[] weights = new double[(int) verticalFilterLength + 1];\n float[] outVertRow = new float[inWidth * 3];\n while (true) {\n // For each output row\n int y = sharedY.getAndIncrement();\n if (y >= outHeight)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerY = (y + 0.5) / outHeight * inHeight;\n double filterStartY = centerY - verticalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartY - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputY = startIndex + i;\n double weight = windowedSinc((inputY + 0.5 - centerY) * sincScale, (inputY + 0.5 - filterStartY) / verticalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outVertRow, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputY = Math.min(Math.max(startIndex + i, 0), inHeight - 1);\n for (int x = 0; x < inWidth; x++) {\n // For each pixel in the row\n int j = (clippedInputY * inWidth + x) * 3;\n outVertRow[x * 3 + 0] += inVert[j + 0] * weight;\n outVertRow[x * 3 + 1] += inVert[j + 1] * weight;\n outVertRow[x * 3 + 2] += inVert[j + 2] * weight;\n }\n }\n for (int x = 0; x < inWidth; x++) {\n int j = (x * outHeight + y) * 3;\n inHorz[j + 0] = outVertRow[x * 3 + 0];\n inHorz[j + 1] = outVertRow[x * 3 + 1];\n inHorz[j + 2] = outVertRow[x * 3 + 2];\n }\n }\n }\n // Wait for all threads to finish the phase\n try {\n barrier.await();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n } catch (BrokenBarrierException e) {\n throw new RuntimeException(e);\n }\n // Resample horizontally and transpose\n {\n double sincScale = Math.min((double) outWidth / inWidth, 1);\n double[] weights = new double[(int) horizontalFilterLength + 1];\n double[] outHorzCol = new double[outHeight * 3];\n while (true) {\n // For each output column\n int x = sharedX.getAndIncrement();\n if (x >= outWidth)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerX = (x + 0.5) / outWidth * inWidth;\n double filterStartX = centerX - horizontalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartX - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputX = startIndex + i;\n double weight = windowedSinc((inputX + 0.5 - centerX) * sincScale, (inputX + 0.5 - filterStartX) / horizontalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outHorzCol, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputX = Math.min(Math.max(startIndex + i, 0), inWidth - 1);\n for (int y = 0; y < outHeight; y++) {\n // For each pixel in the column\n int j = (clippedInputX * outHeight + y) * 3;\n outHorzCol[y * 3 + 0] += inHorz[j + 0] * weight;\n outHorzCol[y * 3 + 1] += inHorz[j + 1] * weight;\n outHorzCol[y * 3 + 2] += inHorz[j + 2] * weight;\n }\n }\n for (int y = 0; y < outHeight; y++) {\n // Convert to 8 bits per channel and pack integers\n double r = outHorzCol[y * 3 + 0] * 255;\n if (r < 0)\n r = 0;\n if (r > 255)\n r = 255;\n double g = outHorzCol[y * 3 + 1] * 255;\n if (g < 0)\n g = 0;\n if (g > 255)\n g = 255;\n double b = outHorzCol[y * 3 + 2] * 255;\n if (b < 0)\n b = 0;\n if (b > 255)\n b = 255;\n outPixels[y * outWidth + x] = (int) (r + 0.5) << 16 | (int) (g + 0.5) << 8 | (int) (b + 0.5);\n }\n }\n }\n }\n };\n thr[i].start();\n }\n try {\n for (Thread th : thr) th.join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n outputImage = new BufferedImage(outWidth, outHeight, BufferedImage.TYPE_INT_RGB);\n outputImage.setRGB(0, 0, outWidth, outHeight, outPixels, 0, outWidth);\n }\n\n // x is measured in half-cycles; y is for the window which has the domain [0, 1]\n private static double windowedSinc(double x, double y) {\n x *= Math.PI;\n double sinc = x != 0 ? Math.sin(x) / x : 1;\n // Triangle window\n double window = 0 <= y && y <= 1 ? 1 - Math.abs(y - 0.5) * 2 : 0;\n return sinc * window;\n }\n }\n}\n"} {"task_id": "Java_589", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/nayuki/Nayuki-web-published-code/go-train-acceleration-analyzed-by-video/PreprocessFrames.java", "mask_start_position": 833, "mask_end_position": 1075, "canonical_solution": "\n // Get and check arguments\n if (args.length != 2) {\n System.err.println(\"Usage: java PreprocessFrames InDir OutDir\");\n System.exit(1);\n return;\n }\n File inDir = new File(args[0]);", "pre_mask_code": "/* \n * Preprocess frames\n * \n * All rights reserved. Contact Nayuki for licensing.\n * http://example.com\n */\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport javax.imageio.ImageIO;\n\npublic final class PreprocessFrames {\n\n // Configuration\n private static final int INPUT_FRAME_START = 990;\n\n private static final int INPUT_FRAME_END = 3900;\n\n private static final int INPUT_FRAME_DECIMATE = 3;\n\n private static final int IMAGE_WIDTH = 1280;\n\n private static final int IMAGE_HEIGHT = 192;\n\n private static final int IMAGE_UPSCALE = 4;\n\n public static void main(String[] args) throws IOException {", "post_mask_code": "\n File outDir = new File(args[1]);\n if (!inDir.isDirectory())\n throw new RuntimeException(\"Invalid input directory\");\n if (!outDir.isDirectory())\n throw new RuntimeException(\"Invalid output directory\");\n // Process image frames\n for (int inFrame = INPUT_FRAME_START, outFrame = 0; inFrame < INPUT_FRAME_END; inFrame += INPUT_FRAME_DECIMATE, outFrame++) {\n File inFile = new File(inDir, String.format(\"%04d.bmp\", inFrame));\n File outFile = new File(outDir, String.format(\"%04d.bmp\", outFrame));\n FastSincImageResampler.resampleFile(inFile, IMAGE_WIDTH * IMAGE_UPSCALE, IMAGE_HEIGHT * IMAGE_UPSCALE, outFile);\n System.out.printf(\"%s --> %s%n\", inFile.getName(), outFile.getName());\n }\n }\n\n // Based on http://example.com\n private static final class FastSincImageResampler {\n\n /* Convenience methods */\n /**\n * Resamples the specified image file to the specified output dimensions, writing to the specified output file.\n * @param inFile the input image file (must be in BMP or PNG format)\n * @param outWidth the output image width (must be positive)\n * @param outHeight the output image height (must be positive)\n * @param outFile the output image file\n * @throws IOException if an I/O exception occurred in reading the input image file or writing the output image file\n */\n public static void resampleFile(File inFile, int outWidth, int outHeight, File outFile) throws IOException {\n FastSincImageResampler rs = new FastSincImageResampler();\n rs.inputFile = inFile;\n rs.outputWidth = outWidth;\n rs.outputHeight = outHeight;\n rs.outputFile = outFile;\n rs.run();\n }\n\n /* Full functionality */\n public File inputFile = null;\n\n public BufferedImage inputImage = null;\n\n // run() does not read this, but will overwrite this field\n public int inputWidth = -1;\n\n // run() does not read this, but will overwrite this field\n public int inputHeight = -1;\n\n // Must set to a positive number\n public int outputWidth = -1;\n\n // Must set to a positive number\n public int outputHeight = -1;\n\n // Horizontal filter length (set a positive value, otherwise an automatic default value will be computed)\n public double horizontalFilterLength = -1;\n\n // Vertical filter length (set a positive value, otherwise an automatic default value will be computed)\n public double verticalFilterLength = -1;\n\n // Number of threads to use (set a positive value, otherwise an automatic default value will be computed)\n public int threads = -1;\n\n // run() does not read this, but will overwrite this field\n public BufferedImage outputImage = null;\n\n public File outputFile = null;\n\n // Must be \"png\", \"bmp\", or null (auto-detection based on outputFile's extension)\n public String outputFileType = null;\n\n /**\n * Constructs a blank resampler object - certain fields must be set before calling {@code run()}.\n */\n public FastSincImageResampler() {\n }\n\n /**\n * Runs the resampler. The data flow operates on a \"waterfall\" model, reading and writing the fields from top to bottom:\n *
    \n *
  1. If {@code inputFile} is non-{@code null}, then it is read into {@code inputImage}.
  2. \n *
  3. {@code inputImage} needs to be non-{@code null} now (set explicitly or read from {@code inputFile}).
  4. \n *
  5. {@code inputImage} is read into {@code inputWidth} and {@code inputHeight}.
  6. \n *
  7. {@code outputWidth} and {@code outputHeight} must be positive (set explicitly).
  8. \n *
  9. If a filter length is zero or negative, then a default filter length is computed and set for that axis.
  10. \n *
  11. If {@code threads} is zero or negative, then a default number of threads is computed and set.
  12. \n *
  13. {@code outputImage} is computed by resampling {@code inputImage}. (This is the main purpose of the class.)
  14. \n *
  15. If {@code outputFile} is non-{@code null} and {@code outputFileType} is {@code null}: The type is set to {@code \"png\"} or {@code \"bmp\"}\n * if the output file has that extension (case-insensitive), otherwise it is set to {@code \"png\"} by default.
  16. \n *
  17. If {@code outputFile} is non-{@code null}, then {@code outputImage} is written to the file.
  18. \n *
\n *

After calling {@code run()}, it is recommend that this object should not be reused for another resampling operation.\n * This is because various fields probably need to be cleared, such as the filter length and output file type.

\n * @throws IOException if an I/O exception occurred\n * @throws IllegalStateException if there is no input image or the output dimensions are not set to positive values\n */\n public void run() throws IOException {\n // Read input file (optional)\n if (inputFile != null) {\n try {\n inputImage = ImageIO.read(inputFile);\n } catch (IOException e) {\n throw new IOException(\"Error reading input file (\" + inputFile + \"): \" + e.getMessage(), e);\n }\n }\n // Get input image dimensions\n if (inputImage == null)\n throw new IllegalStateException(\"No input image\");\n inputWidth = inputImage.getWidth();\n inputHeight = inputImage.getHeight();\n // Calculate filter lengths (optional)\n if (outputWidth <= 0 || outputHeight <= 0)\n throw new IllegalStateException(\"Output dimensions not set\");\n if (horizontalFilterLength <= 0)\n horizontalFilterLength = Math.max((double) inputWidth / outputWidth, 1) * 4.0;\n if (verticalFilterLength <= 0)\n verticalFilterLength = Math.max((double) inputHeight / outputHeight, 1) * 4.0;\n // Resample the image\n if (threads <= 0)\n threads = Runtime.getRuntime().availableProcessors();\n resampleImage();\n // Write output file (optional)\n if (outputFile != null) {\n if (outputFileType == null) {\n // Auto-detection by file extension\n String lowername = outputFile.getName().toLowerCase();\n if (lowername.endsWith(\".bmp\"))\n outputFileType = \"bmp\";\n else\n // Default\n outputFileType = \"png\";\n }\n try {\n ImageIO.write(outputImage, outputFileType, outputFile);\n } catch (IOException e) {\n throw new IOException(\"Error writing output file (\" + outputFile + \"): \" + e.getMessage(), e);\n }\n }\n }\n\n private void resampleImage() {\n final int inWidth = inputWidth;\n final int inHeight = inputHeight;\n final int outWidth = outputWidth;\n final int outHeight = outputHeight;\n // Get packed int pixels\n int[] inPixels = new int[inWidth * inHeight];\n inputImage.getRGB(0, 0, inWidth, inHeight, inPixels, 0, inWidth);\n // Convert to float\n final float[] inVert = new float[inWidth * inHeight * 3];\n for (int i = 0, j = 0; i < inPixels.length; i++, j += 3) {\n int rgb = inPixels[i];\n inVert[j + 0] = (float) Math.pow(((rgb >>> 16) & 0xFF) / 255.0, 2.2);\n inVert[j + 1] = (float) Math.pow(((rgb >>> 8) & 0xFF) / 255.0, 2.2);\n inVert[j + 2] = (float) Math.pow(((rgb >>> 0) & 0xFF) / 255.0, 2.2);\n }\n inPixels = null;\n Thread[] thr = new Thread[threads];\n final AtomicInteger sharedY = new AtomicInteger(0);\n final float[] inHorz = new float[inWidth * outHeight * 3];\n final CyclicBarrier barrier = new CyclicBarrier(threads);\n final AtomicInteger sharedX = new AtomicInteger(0);\n final int[] outPixels = new int[outWidth * outHeight];\n for (int i = 0; i < thr.length; i++) {\n thr[i] = new Thread() {\n\n public void run() {\n // Resample vertically and transpose\n {\n double sincScale = Math.min((double) outHeight / inHeight, 1);\n double[] weights = new double[(int) verticalFilterLength + 1];\n float[] outVertRow = new float[inWidth * 3];\n while (true) {\n // For each output row\n int y = sharedY.getAndIncrement();\n if (y >= outHeight)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerY = (y + 0.5) / outHeight * inHeight;\n double filterStartY = centerY - verticalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartY - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputY = startIndex + i;\n double weight = windowedSinc((inputY + 0.5 - centerY) * sincScale, (inputY + 0.5 - filterStartY) / verticalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outVertRow, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputY = Math.min(Math.max(startIndex + i, 0), inHeight - 1);\n for (int x = 0; x < inWidth; x++) {\n // For each pixel in the row\n int j = (clippedInputY * inWidth + x) * 3;\n outVertRow[x * 3 + 0] += inVert[j + 0] * weight;\n outVertRow[x * 3 + 1] += inVert[j + 1] * weight;\n outVertRow[x * 3 + 2] += inVert[j + 2] * weight;\n }\n }\n for (int x = 0; x < inWidth; x++) {\n int j = (x * outHeight + y) * 3;\n inHorz[j + 0] = outVertRow[x * 3 + 0];\n inHorz[j + 1] = outVertRow[x * 3 + 1];\n inHorz[j + 2] = outVertRow[x * 3 + 2];\n }\n }\n }\n // Wait for all threads to finish the phase\n try {\n barrier.await();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n } catch (BrokenBarrierException e) {\n throw new RuntimeException(e);\n }\n // Resample horizontally and transpose\n {\n double sincScale = Math.min((double) outWidth / inWidth, 1);\n double[] weights = new double[(int) horizontalFilterLength + 1];\n double[] outHorzCol = new double[outHeight * 3];\n while (true) {\n // For each output column\n int x = sharedX.getAndIncrement();\n if (x >= outWidth)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerX = (x + 0.5) / outWidth * inWidth;\n double filterStartX = centerX - horizontalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartX - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputX = startIndex + i;\n double weight = windowedSinc((inputX + 0.5 - centerX) * sincScale, (inputX + 0.5 - filterStartX) / horizontalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outHorzCol, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputX = Math.min(Math.max(startIndex + i, 0), inWidth - 1);\n for (int y = 0; y < outHeight; y++) {\n // For each pixel in the column\n int j = (clippedInputX * outHeight + y) * 3;\n outHorzCol[y * 3 + 0] += inHorz[j + 0] * weight;\n outHorzCol[y * 3 + 1] += inHorz[j + 1] * weight;\n outHorzCol[y * 3 + 2] += inHorz[j + 2] * weight;\n }\n }\n for (int y = 0; y < outHeight; y++) {\n // Convert to 8 bits per channel and pack integers\n double r = outHorzCol[y * 3 + 0] * 255;\n if (r < 0)\n r = 0;\n if (r > 255)\n r = 255;\n double g = outHorzCol[y * 3 + 1] * 255;\n if (g < 0)\n g = 0;\n if (g > 255)\n g = 255;\n double b = outHorzCol[y * 3 + 2] * 255;\n if (b < 0)\n b = 0;\n if (b > 255)\n b = 255;\n outPixels[y * outWidth + x] = (int) (r + 0.5) << 16 | (int) (g + 0.5) << 8 | (int) (b + 0.5);\n }\n }\n }\n }\n };\n thr[i].start();\n }\n try {\n for (Thread th : thr) th.join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n outputImage = new BufferedImage(outWidth, outHeight, BufferedImage.TYPE_INT_RGB);\n outputImage.setRGB(0, 0, outWidth, outHeight, outPixels, 0, outWidth);\n }\n\n // x is measured in half-cycles; y is for the window which has the domain [0, 1]\n private static double windowedSinc(double x, double y) {\n x *= Math.PI;\n double sinc = x != 0 ? Math.sin(x) / x : 1;\n // Triangle window\n double window = 0 <= y && y <= 1 ? 1 - Math.abs(y - 0.5) * 2 : 0;\n return sinc * window;\n }\n }\n}\n"} {"task_id": "Java_590", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/nayuki/Nayuki-web-published-code/go-train-acceleration-analyzed-by-video/PreprocessFrames.java", "mask_start_position": 1084, "mask_end_position": 1320, "canonical_solution": "File outDir = new File(args[1]);\n if (!inDir.isDirectory())\n throw new RuntimeException(\"Invalid input directory\");\n if (!outDir.isDirectory())\n throw new RuntimeException(\"Invalid output directory\");", "pre_mask_code": "/* \n * Preprocess frames\n * \n * All rights reserved. Contact Nayuki for licensing.\n * http://example.com\n */\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport javax.imageio.ImageIO;\n\npublic final class PreprocessFrames {\n\n // Configuration\n private static final int INPUT_FRAME_START = 990;\n\n private static final int INPUT_FRAME_END = 3900;\n\n private static final int INPUT_FRAME_DECIMATE = 3;\n\n private static final int IMAGE_WIDTH = 1280;\n\n private static final int IMAGE_HEIGHT = 192;\n\n private static final int IMAGE_UPSCALE = 4;\n\n public static void main(String[] args) throws IOException {\n // Get and check arguments\n if (args.length != 2) {\n System.err.println(\"Usage: java PreprocessFrames InDir OutDir\");\n System.exit(1);\n return;\n }\n File inDir = new File(args[0]);\n ", "post_mask_code": "\n // Process image frames\n for (int inFrame = INPUT_FRAME_START, outFrame = 0; inFrame < INPUT_FRAME_END; inFrame += INPUT_FRAME_DECIMATE, outFrame++) {\n File inFile = new File(inDir, String.format(\"%04d.bmp\", inFrame));\n File outFile = new File(outDir, String.format(\"%04d.bmp\", outFrame));\n FastSincImageResampler.resampleFile(inFile, IMAGE_WIDTH * IMAGE_UPSCALE, IMAGE_HEIGHT * IMAGE_UPSCALE, outFile);\n System.out.printf(\"%s --> %s%n\", inFile.getName(), outFile.getName());\n }\n }\n\n // Based on http://example.com\n private static final class FastSincImageResampler {\n\n /* Convenience methods */\n /**\n * Resamples the specified image file to the specified output dimensions, writing to the specified output file.\n * @param inFile the input image file (must be in BMP or PNG format)\n * @param outWidth the output image width (must be positive)\n * @param outHeight the output image height (must be positive)\n * @param outFile the output image file\n * @throws IOException if an I/O exception occurred in reading the input image file or writing the output image file\n */\n public static void resampleFile(File inFile, int outWidth, int outHeight, File outFile) throws IOException {\n FastSincImageResampler rs = new FastSincImageResampler();\n rs.inputFile = inFile;\n rs.outputWidth = outWidth;\n rs.outputHeight = outHeight;\n rs.outputFile = outFile;\n rs.run();\n }\n\n /* Full functionality */\n public File inputFile = null;\n\n public BufferedImage inputImage = null;\n\n // run() does not read this, but will overwrite this field\n public int inputWidth = -1;\n\n // run() does not read this, but will overwrite this field\n public int inputHeight = -1;\n\n // Must set to a positive number\n public int outputWidth = -1;\n\n // Must set to a positive number\n public int outputHeight = -1;\n\n // Horizontal filter length (set a positive value, otherwise an automatic default value will be computed)\n public double horizontalFilterLength = -1;\n\n // Vertical filter length (set a positive value, otherwise an automatic default value will be computed)\n public double verticalFilterLength = -1;\n\n // Number of threads to use (set a positive value, otherwise an automatic default value will be computed)\n public int threads = -1;\n\n // run() does not read this, but will overwrite this field\n public BufferedImage outputImage = null;\n\n public File outputFile = null;\n\n // Must be \"png\", \"bmp\", or null (auto-detection based on outputFile's extension)\n public String outputFileType = null;\n\n /**\n * Constructs a blank resampler object - certain fields must be set before calling {@code run()}.\n */\n public FastSincImageResampler() {\n }\n\n /**\n * Runs the resampler. The data flow operates on a \"waterfall\" model, reading and writing the fields from top to bottom:\n *
    \n *
  1. If {@code inputFile} is non-{@code null}, then it is read into {@code inputImage}.
  2. \n *
  3. {@code inputImage} needs to be non-{@code null} now (set explicitly or read from {@code inputFile}).
  4. \n *
  5. {@code inputImage} is read into {@code inputWidth} and {@code inputHeight}.
  6. \n *
  7. {@code outputWidth} and {@code outputHeight} must be positive (set explicitly).
  8. \n *
  9. If a filter length is zero or negative, then a default filter length is computed and set for that axis.
  10. \n *
  11. If {@code threads} is zero or negative, then a default number of threads is computed and set.
  12. \n *
  13. {@code outputImage} is computed by resampling {@code inputImage}. (This is the main purpose of the class.)
  14. \n *
  15. If {@code outputFile} is non-{@code null} and {@code outputFileType} is {@code null}: The type is set to {@code \"png\"} or {@code \"bmp\"}\n * if the output file has that extension (case-insensitive), otherwise it is set to {@code \"png\"} by default.
  16. \n *
  17. If {@code outputFile} is non-{@code null}, then {@code outputImage} is written to the file.
  18. \n *
\n *

After calling {@code run()}, it is recommend that this object should not be reused for another resampling operation.\n * This is because various fields probably need to be cleared, such as the filter length and output file type.

\n * @throws IOException if an I/O exception occurred\n * @throws IllegalStateException if there is no input image or the output dimensions are not set to positive values\n */\n public void run() throws IOException {\n // Read input file (optional)\n if (inputFile != null) {\n try {\n inputImage = ImageIO.read(inputFile);\n } catch (IOException e) {\n throw new IOException(\"Error reading input file (\" + inputFile + \"): \" + e.getMessage(), e);\n }\n }\n // Get input image dimensions\n if (inputImage == null)\n throw new IllegalStateException(\"No input image\");\n inputWidth = inputImage.getWidth();\n inputHeight = inputImage.getHeight();\n // Calculate filter lengths (optional)\n if (outputWidth <= 0 || outputHeight <= 0)\n throw new IllegalStateException(\"Output dimensions not set\");\n if (horizontalFilterLength <= 0)\n horizontalFilterLength = Math.max((double) inputWidth / outputWidth, 1) * 4.0;\n if (verticalFilterLength <= 0)\n verticalFilterLength = Math.max((double) inputHeight / outputHeight, 1) * 4.0;\n // Resample the image\n if (threads <= 0)\n threads = Runtime.getRuntime().availableProcessors();\n resampleImage();\n // Write output file (optional)\n if (outputFile != null) {\n if (outputFileType == null) {\n // Auto-detection by file extension\n String lowername = outputFile.getName().toLowerCase();\n if (lowername.endsWith(\".bmp\"))\n outputFileType = \"bmp\";\n else\n // Default\n outputFileType = \"png\";\n }\n try {\n ImageIO.write(outputImage, outputFileType, outputFile);\n } catch (IOException e) {\n throw new IOException(\"Error writing output file (\" + outputFile + \"): \" + e.getMessage(), e);\n }\n }\n }\n\n private void resampleImage() {\n final int inWidth = inputWidth;\n final int inHeight = inputHeight;\n final int outWidth = outputWidth;\n final int outHeight = outputHeight;\n // Get packed int pixels\n int[] inPixels = new int[inWidth * inHeight];\n inputImage.getRGB(0, 0, inWidth, inHeight, inPixels, 0, inWidth);\n // Convert to float\n final float[] inVert = new float[inWidth * inHeight * 3];\n for (int i = 0, j = 0; i < inPixels.length; i++, j += 3) {\n int rgb = inPixels[i];\n inVert[j + 0] = (float) Math.pow(((rgb >>> 16) & 0xFF) / 255.0, 2.2);\n inVert[j + 1] = (float) Math.pow(((rgb >>> 8) & 0xFF) / 255.0, 2.2);\n inVert[j + 2] = (float) Math.pow(((rgb >>> 0) & 0xFF) / 255.0, 2.2);\n }\n inPixels = null;\n Thread[] thr = new Thread[threads];\n final AtomicInteger sharedY = new AtomicInteger(0);\n final float[] inHorz = new float[inWidth * outHeight * 3];\n final CyclicBarrier barrier = new CyclicBarrier(threads);\n final AtomicInteger sharedX = new AtomicInteger(0);\n final int[] outPixels = new int[outWidth * outHeight];\n for (int i = 0; i < thr.length; i++) {\n thr[i] = new Thread() {\n\n public void run() {\n // Resample vertically and transpose\n {\n double sincScale = Math.min((double) outHeight / inHeight, 1);\n double[] weights = new double[(int) verticalFilterLength + 1];\n float[] outVertRow = new float[inWidth * 3];\n while (true) {\n // For each output row\n int y = sharedY.getAndIncrement();\n if (y >= outHeight)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerY = (y + 0.5) / outHeight * inHeight;\n double filterStartY = centerY - verticalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartY - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputY = startIndex + i;\n double weight = windowedSinc((inputY + 0.5 - centerY) * sincScale, (inputY + 0.5 - filterStartY) / verticalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outVertRow, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputY = Math.min(Math.max(startIndex + i, 0), inHeight - 1);\n for (int x = 0; x < inWidth; x++) {\n // For each pixel in the row\n int j = (clippedInputY * inWidth + x) * 3;\n outVertRow[x * 3 + 0] += inVert[j + 0] * weight;\n outVertRow[x * 3 + 1] += inVert[j + 1] * weight;\n outVertRow[x * 3 + 2] += inVert[j + 2] * weight;\n }\n }\n for (int x = 0; x < inWidth; x++) {\n int j = (x * outHeight + y) * 3;\n inHorz[j + 0] = outVertRow[x * 3 + 0];\n inHorz[j + 1] = outVertRow[x * 3 + 1];\n inHorz[j + 2] = outVertRow[x * 3 + 2];\n }\n }\n }\n // Wait for all threads to finish the phase\n try {\n barrier.await();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n } catch (BrokenBarrierException e) {\n throw new RuntimeException(e);\n }\n // Resample horizontally and transpose\n {\n double sincScale = Math.min((double) outWidth / inWidth, 1);\n double[] weights = new double[(int) horizontalFilterLength + 1];\n double[] outHorzCol = new double[outHeight * 3];\n while (true) {\n // For each output column\n int x = sharedX.getAndIncrement();\n if (x >= outWidth)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerX = (x + 0.5) / outWidth * inWidth;\n double filterStartX = centerX - horizontalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartX - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputX = startIndex + i;\n double weight = windowedSinc((inputX + 0.5 - centerX) * sincScale, (inputX + 0.5 - filterStartX) / horizontalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outHorzCol, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputX = Math.min(Math.max(startIndex + i, 0), inWidth - 1);\n for (int y = 0; y < outHeight; y++) {\n // For each pixel in the column\n int j = (clippedInputX * outHeight + y) * 3;\n outHorzCol[y * 3 + 0] += inHorz[j + 0] * weight;\n outHorzCol[y * 3 + 1] += inHorz[j + 1] * weight;\n outHorzCol[y * 3 + 2] += inHorz[j + 2] * weight;\n }\n }\n for (int y = 0; y < outHeight; y++) {\n // Convert to 8 bits per channel and pack integers\n double r = outHorzCol[y * 3 + 0] * 255;\n if (r < 0)\n r = 0;\n if (r > 255)\n r = 255;\n double g = outHorzCol[y * 3 + 1] * 255;\n if (g < 0)\n g = 0;\n if (g > 255)\n g = 255;\n double b = outHorzCol[y * 3 + 2] * 255;\n if (b < 0)\n b = 0;\n if (b > 255)\n b = 255;\n outPixels[y * outWidth + x] = (int) (r + 0.5) << 16 | (int) (g + 0.5) << 8 | (int) (b + 0.5);\n }\n }\n }\n }\n };\n thr[i].start();\n }\n try {\n for (Thread th : thr) th.join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n outputImage = new BufferedImage(outWidth, outHeight, BufferedImage.TYPE_INT_RGB);\n outputImage.setRGB(0, 0, outWidth, outHeight, outPixels, 0, outWidth);\n }\n\n // x is measured in half-cycles; y is for the window which has the domain [0, 1]\n private static double windowedSinc(double x, double y) {\n x *= Math.PI;\n double sinc = x != 0 ? Math.sin(x) / x : 1;\n // Triangle window\n double window = 0 <= y && y <= 1 ? 1 - Math.abs(y - 0.5) * 2 : 0;\n return sinc * window;\n }\n }\n}\n"} {"task_id": "Java_591", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/nayuki/Nayuki-web-published-code/go-train-acceleration-analyzed-by-video/PreprocessFrames.java", "mask_start_position": 1329, "mask_end_position": 1871, "canonical_solution": "// Process image frames\n for (int inFrame = INPUT_FRAME_START, outFrame = 0; inFrame < INPUT_FRAME_END; inFrame += INPUT_FRAME_DECIMATE, outFrame++) {\n File inFile = new File(inDir, String.format(\"%04d.bmp\", inFrame));\n File outFile = new File(outDir, String.format(\"%04d.bmp\", outFrame));\n FastSincImageResampler.resampleFile(inFile, IMAGE_WIDTH * IMAGE_UPSCALE, IMAGE_HEIGHT * IMAGE_UPSCALE, outFile);\n System.out.printf(\"%s --> %s%n\", inFile.getName(), outFile.getName());\n }\n }", "pre_mask_code": "/* \n * Preprocess frames\n * \n * All rights reserved. Contact Nayuki for licensing.\n * http://example.com\n */\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport javax.imageio.ImageIO;\n\npublic final class PreprocessFrames {\n\n // Configuration\n private static final int INPUT_FRAME_START = 990;\n\n private static final int INPUT_FRAME_END = 3900;\n\n private static final int INPUT_FRAME_DECIMATE = 3;\n\n private static final int IMAGE_WIDTH = 1280;\n\n private static final int IMAGE_HEIGHT = 192;\n\n private static final int IMAGE_UPSCALE = 4;\n\n public static void main(String[] args) throws IOException {\n // Get and check arguments\n if (args.length != 2) {\n System.err.println(\"Usage: java PreprocessFrames InDir OutDir\");\n System.exit(1);\n return;\n }\n File inDir = new File(args[0]);\n File outDir = new File(args[1]);\n if (!inDir.isDirectory())\n throw new RuntimeException(\"Invalid input directory\");\n if (!outDir.isDirectory())\n throw new RuntimeException(\"Invalid output directory\");\n ", "post_mask_code": "\n\n // Based on http://example.com\n private static final class FastSincImageResampler {\n\n /* Convenience methods */\n /**\n * Resamples the specified image file to the specified output dimensions, writing to the specified output file.\n * @param inFile the input image file (must be in BMP or PNG format)\n * @param outWidth the output image width (must be positive)\n * @param outHeight the output image height (must be positive)\n * @param outFile the output image file\n * @throws IOException if an I/O exception occurred in reading the input image file or writing the output image file\n */\n public static void resampleFile(File inFile, int outWidth, int outHeight, File outFile) throws IOException {\n FastSincImageResampler rs = new FastSincImageResampler();\n rs.inputFile = inFile;\n rs.outputWidth = outWidth;\n rs.outputHeight = outHeight;\n rs.outputFile = outFile;\n rs.run();\n }\n\n /* Full functionality */\n public File inputFile = null;\n\n public BufferedImage inputImage = null;\n\n // run() does not read this, but will overwrite this field\n public int inputWidth = -1;\n\n // run() does not read this, but will overwrite this field\n public int inputHeight = -1;\n\n // Must set to a positive number\n public int outputWidth = -1;\n\n // Must set to a positive number\n public int outputHeight = -1;\n\n // Horizontal filter length (set a positive value, otherwise an automatic default value will be computed)\n public double horizontalFilterLength = -1;\n\n // Vertical filter length (set a positive value, otherwise an automatic default value will be computed)\n public double verticalFilterLength = -1;\n\n // Number of threads to use (set a positive value, otherwise an automatic default value will be computed)\n public int threads = -1;\n\n // run() does not read this, but will overwrite this field\n public BufferedImage outputImage = null;\n\n public File outputFile = null;\n\n // Must be \"png\", \"bmp\", or null (auto-detection based on outputFile's extension)\n public String outputFileType = null;\n\n /**\n * Constructs a blank resampler object - certain fields must be set before calling {@code run()}.\n */\n public FastSincImageResampler() {\n }\n\n /**\n * Runs the resampler. The data flow operates on a \"waterfall\" model, reading and writing the fields from top to bottom:\n *
    \n *
  1. If {@code inputFile} is non-{@code null}, then it is read into {@code inputImage}.
  2. \n *
  3. {@code inputImage} needs to be non-{@code null} now (set explicitly or read from {@code inputFile}).
  4. \n *
  5. {@code inputImage} is read into {@code inputWidth} and {@code inputHeight}.
  6. \n *
  7. {@code outputWidth} and {@code outputHeight} must be positive (set explicitly).
  8. \n *
  9. If a filter length is zero or negative, then a default filter length is computed and set for that axis.
  10. \n *
  11. If {@code threads} is zero or negative, then a default number of threads is computed and set.
  12. \n *
  13. {@code outputImage} is computed by resampling {@code inputImage}. (This is the main purpose of the class.)
  14. \n *
  15. If {@code outputFile} is non-{@code null} and {@code outputFileType} is {@code null}: The type is set to {@code \"png\"} or {@code \"bmp\"}\n * if the output file has that extension (case-insensitive), otherwise it is set to {@code \"png\"} by default.
  16. \n *
  17. If {@code outputFile} is non-{@code null}, then {@code outputImage} is written to the file.
  18. \n *
\n *

After calling {@code run()}, it is recommend that this object should not be reused for another resampling operation.\n * This is because various fields probably need to be cleared, such as the filter length and output file type.

\n * @throws IOException if an I/O exception occurred\n * @throws IllegalStateException if there is no input image or the output dimensions are not set to positive values\n */\n public void run() throws IOException {\n // Read input file (optional)\n if (inputFile != null) {\n try {\n inputImage = ImageIO.read(inputFile);\n } catch (IOException e) {\n throw new IOException(\"Error reading input file (\" + inputFile + \"): \" + e.getMessage(), e);\n }\n }\n // Get input image dimensions\n if (inputImage == null)\n throw new IllegalStateException(\"No input image\");\n inputWidth = inputImage.getWidth();\n inputHeight = inputImage.getHeight();\n // Calculate filter lengths (optional)\n if (outputWidth <= 0 || outputHeight <= 0)\n throw new IllegalStateException(\"Output dimensions not set\");\n if (horizontalFilterLength <= 0)\n horizontalFilterLength = Math.max((double) inputWidth / outputWidth, 1) * 4.0;\n if (verticalFilterLength <= 0)\n verticalFilterLength = Math.max((double) inputHeight / outputHeight, 1) * 4.0;\n // Resample the image\n if (threads <= 0)\n threads = Runtime.getRuntime().availableProcessors();\n resampleImage();\n // Write output file (optional)\n if (outputFile != null) {\n if (outputFileType == null) {\n // Auto-detection by file extension\n String lowername = outputFile.getName().toLowerCase();\n if (lowername.endsWith(\".bmp\"))\n outputFileType = \"bmp\";\n else\n // Default\n outputFileType = \"png\";\n }\n try {\n ImageIO.write(outputImage, outputFileType, outputFile);\n } catch (IOException e) {\n throw new IOException(\"Error writing output file (\" + outputFile + \"): \" + e.getMessage(), e);\n }\n }\n }\n\n private void resampleImage() {\n final int inWidth = inputWidth;\n final int inHeight = inputHeight;\n final int outWidth = outputWidth;\n final int outHeight = outputHeight;\n // Get packed int pixels\n int[] inPixels = new int[inWidth * inHeight];\n inputImage.getRGB(0, 0, inWidth, inHeight, inPixels, 0, inWidth);\n // Convert to float\n final float[] inVert = new float[inWidth * inHeight * 3];\n for (int i = 0, j = 0; i < inPixels.length; i++, j += 3) {\n int rgb = inPixels[i];\n inVert[j + 0] = (float) Math.pow(((rgb >>> 16) & 0xFF) / 255.0, 2.2);\n inVert[j + 1] = (float) Math.pow(((rgb >>> 8) & 0xFF) / 255.0, 2.2);\n inVert[j + 2] = (float) Math.pow(((rgb >>> 0) & 0xFF) / 255.0, 2.2);\n }\n inPixels = null;\n Thread[] thr = new Thread[threads];\n final AtomicInteger sharedY = new AtomicInteger(0);\n final float[] inHorz = new float[inWidth * outHeight * 3];\n final CyclicBarrier barrier = new CyclicBarrier(threads);\n final AtomicInteger sharedX = new AtomicInteger(0);\n final int[] outPixels = new int[outWidth * outHeight];\n for (int i = 0; i < thr.length; i++) {\n thr[i] = new Thread() {\n\n public void run() {\n // Resample vertically and transpose\n {\n double sincScale = Math.min((double) outHeight / inHeight, 1);\n double[] weights = new double[(int) verticalFilterLength + 1];\n float[] outVertRow = new float[inWidth * 3];\n while (true) {\n // For each output row\n int y = sharedY.getAndIncrement();\n if (y >= outHeight)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerY = (y + 0.5) / outHeight * inHeight;\n double filterStartY = centerY - verticalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartY - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputY = startIndex + i;\n double weight = windowedSinc((inputY + 0.5 - centerY) * sincScale, (inputY + 0.5 - filterStartY) / verticalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outVertRow, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputY = Math.min(Math.max(startIndex + i, 0), inHeight - 1);\n for (int x = 0; x < inWidth; x++) {\n // For each pixel in the row\n int j = (clippedInputY * inWidth + x) * 3;\n outVertRow[x * 3 + 0] += inVert[j + 0] * weight;\n outVertRow[x * 3 + 1] += inVert[j + 1] * weight;\n outVertRow[x * 3 + 2] += inVert[j + 2] * weight;\n }\n }\n for (int x = 0; x < inWidth; x++) {\n int j = (x * outHeight + y) * 3;\n inHorz[j + 0] = outVertRow[x * 3 + 0];\n inHorz[j + 1] = outVertRow[x * 3 + 1];\n inHorz[j + 2] = outVertRow[x * 3 + 2];\n }\n }\n }\n // Wait for all threads to finish the phase\n try {\n barrier.await();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n } catch (BrokenBarrierException e) {\n throw new RuntimeException(e);\n }\n // Resample horizontally and transpose\n {\n double sincScale = Math.min((double) outWidth / inWidth, 1);\n double[] weights = new double[(int) horizontalFilterLength + 1];\n double[] outHorzCol = new double[outHeight * 3];\n while (true) {\n // For each output column\n int x = sharedX.getAndIncrement();\n if (x >= outWidth)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerX = (x + 0.5) / outWidth * inWidth;\n double filterStartX = centerX - horizontalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartX - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputX = startIndex + i;\n double weight = windowedSinc((inputX + 0.5 - centerX) * sincScale, (inputX + 0.5 - filterStartX) / horizontalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outHorzCol, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputX = Math.min(Math.max(startIndex + i, 0), inWidth - 1);\n for (int y = 0; y < outHeight; y++) {\n // For each pixel in the column\n int j = (clippedInputX * outHeight + y) * 3;\n outHorzCol[y * 3 + 0] += inHorz[j + 0] * weight;\n outHorzCol[y * 3 + 1] += inHorz[j + 1] * weight;\n outHorzCol[y * 3 + 2] += inHorz[j + 2] * weight;\n }\n }\n for (int y = 0; y < outHeight; y++) {\n // Convert to 8 bits per channel and pack integers\n double r = outHorzCol[y * 3 + 0] * 255;\n if (r < 0)\n r = 0;\n if (r > 255)\n r = 255;\n double g = outHorzCol[y * 3 + 1] * 255;\n if (g < 0)\n g = 0;\n if (g > 255)\n g = 255;\n double b = outHorzCol[y * 3 + 2] * 255;\n if (b < 0)\n b = 0;\n if (b > 255)\n b = 255;\n outPixels[y * outWidth + x] = (int) (r + 0.5) << 16 | (int) (g + 0.5) << 8 | (int) (b + 0.5);\n }\n }\n }\n }\n };\n thr[i].start();\n }\n try {\n for (Thread th : thr) th.join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n outputImage = new BufferedImage(outWidth, outHeight, BufferedImage.TYPE_INT_RGB);\n outputImage.setRGB(0, 0, outWidth, outHeight, outPixels, 0, outWidth);\n }\n\n // x is measured in half-cycles; y is for the window which has the domain [0, 1]\n private static double windowedSinc(double x, double y) {\n x *= Math.PI;\n double sinc = x != 0 ? Math.sin(x) / x : 1;\n // Triangle window\n double window = 0 <= y && y <= 1 ? 1 - Math.abs(y - 0.5) * 2 : 0;\n return sinc * window;\n }\n }\n}\n"} {"task_id": "Java_592", "language": "Java", "task_type": "single_line", "source_file": "java/github/nayuki/Nayuki-web-published-code/go-train-acceleration-analyzed-by-video/PreprocessFrames.java", "mask_start_position": 16982, "mask_end_position": 17004, "canonical_solution": "? Math.sin(x) / x : 1;", "pre_mask_code": "/* \n * Preprocess frames\n * \n * All rights reserved. Contact Nayuki for licensing.\n * http://example.com\n */\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport javax.imageio.ImageIO;\n\npublic final class PreprocessFrames {\n\n // Configuration\n private static final int INPUT_FRAME_START = 990;\n\n private static final int INPUT_FRAME_END = 3900;\n\n private static final int INPUT_FRAME_DECIMATE = 3;\n\n private static final int IMAGE_WIDTH = 1280;\n\n private static final int IMAGE_HEIGHT = 192;\n\n private static final int IMAGE_UPSCALE = 4;\n\n public static void main(String[] args) throws IOException {\n // Get and check arguments\n if (args.length != 2) {\n System.err.println(\"Usage: java PreprocessFrames InDir OutDir\");\n System.exit(1);\n return;\n }\n File inDir = new File(args[0]);\n File outDir = new File(args[1]);\n if (!inDir.isDirectory())\n throw new RuntimeException(\"Invalid input directory\");\n if (!outDir.isDirectory())\n throw new RuntimeException(\"Invalid output directory\");\n // Process image frames\n for (int inFrame = INPUT_FRAME_START, outFrame = 0; inFrame < INPUT_FRAME_END; inFrame += INPUT_FRAME_DECIMATE, outFrame++) {\n File inFile = new File(inDir, String.format(\"%04d.bmp\", inFrame));\n File outFile = new File(outDir, String.format(\"%04d.bmp\", outFrame));\n FastSincImageResampler.resampleFile(inFile, IMAGE_WIDTH * IMAGE_UPSCALE, IMAGE_HEIGHT * IMAGE_UPSCALE, outFile);\n System.out.printf(\"%s --> %s%n\", inFile.getName(), outFile.getName());\n }\n }\n\n // Based on http://example.com\n private static final class FastSincImageResampler {\n\n /* Convenience methods */\n /**\n * Resamples the specified image file to the specified output dimensions, writing to the specified output file.\n * @param inFile the input image file (must be in BMP or PNG format)\n * @param outWidth the output image width (must be positive)\n * @param outHeight the output image height (must be positive)\n * @param outFile the output image file\n * @throws IOException if an I/O exception occurred in reading the input image file or writing the output image file\n */\n public static void resampleFile(File inFile, int outWidth, int outHeight, File outFile) throws IOException {\n FastSincImageResampler rs = new FastSincImageResampler();\n rs.inputFile = inFile;\n rs.outputWidth = outWidth;\n rs.outputHeight = outHeight;\n rs.outputFile = outFile;\n rs.run();\n }\n\n /* Full functionality */\n public File inputFile = null;\n\n public BufferedImage inputImage = null;\n\n // run() does not read this, but will overwrite this field\n public int inputWidth = -1;\n\n // run() does not read this, but will overwrite this field\n public int inputHeight = -1;\n\n // Must set to a positive number\n public int outputWidth = -1;\n\n // Must set to a positive number\n public int outputHeight = -1;\n\n // Horizontal filter length (set a positive value, otherwise an automatic default value will be computed)\n public double horizontalFilterLength = -1;\n\n // Vertical filter length (set a positive value, otherwise an automatic default value will be computed)\n public double verticalFilterLength = -1;\n\n // Number of threads to use (set a positive value, otherwise an automatic default value will be computed)\n public int threads = -1;\n\n // run() does not read this, but will overwrite this field\n public BufferedImage outputImage = null;\n\n public File outputFile = null;\n\n // Must be \"png\", \"bmp\", or null (auto-detection based on outputFile's extension)\n public String outputFileType = null;\n\n /**\n * Constructs a blank resampler object - certain fields must be set before calling {@code run()}.\n */\n public FastSincImageResampler() {\n }\n\n /**\n * Runs the resampler. The data flow operates on a \"waterfall\" model, reading and writing the fields from top to bottom:\n *
    \n *
  1. If {@code inputFile} is non-{@code null}, then it is read into {@code inputImage}.
  2. \n *
  3. {@code inputImage} needs to be non-{@code null} now (set explicitly or read from {@code inputFile}).
  4. \n *
  5. {@code inputImage} is read into {@code inputWidth} and {@code inputHeight}.
  6. \n *
  7. {@code outputWidth} and {@code outputHeight} must be positive (set explicitly).
  8. \n *
  9. If a filter length is zero or negative, then a default filter length is computed and set for that axis.
  10. \n *
  11. If {@code threads} is zero or negative, then a default number of threads is computed and set.
  12. \n *
  13. {@code outputImage} is computed by resampling {@code inputImage}. (This is the main purpose of the class.)
  14. \n *
  15. If {@code outputFile} is non-{@code null} and {@code outputFileType} is {@code null}: The type is set to {@code \"png\"} or {@code \"bmp\"}\n * if the output file has that extension (case-insensitive), otherwise it is set to {@code \"png\"} by default.
  16. \n *
  17. If {@code outputFile} is non-{@code null}, then {@code outputImage} is written to the file.
  18. \n *
\n *

After calling {@code run()}, it is recommend that this object should not be reused for another resampling operation.\n * This is because various fields probably need to be cleared, such as the filter length and output file type.

\n * @throws IOException if an I/O exception occurred\n * @throws IllegalStateException if there is no input image or the output dimensions are not set to positive values\n */\n public void run() throws IOException {\n // Read input file (optional)\n if (inputFile != null) {\n try {\n inputImage = ImageIO.read(inputFile);\n } catch (IOException e) {\n throw new IOException(\"Error reading input file (\" + inputFile + \"): \" + e.getMessage(), e);\n }\n }\n // Get input image dimensions\n if (inputImage == null)\n throw new IllegalStateException(\"No input image\");\n inputWidth = inputImage.getWidth();\n inputHeight = inputImage.getHeight();\n // Calculate filter lengths (optional)\n if (outputWidth <= 0 || outputHeight <= 0)\n throw new IllegalStateException(\"Output dimensions not set\");\n if (horizontalFilterLength <= 0)\n horizontalFilterLength = Math.max((double) inputWidth / outputWidth, 1) * 4.0;\n if (verticalFilterLength <= 0)\n verticalFilterLength = Math.max((double) inputHeight / outputHeight, 1) * 4.0;\n // Resample the image\n if (threads <= 0)\n threads = Runtime.getRuntime().availableProcessors();\n resampleImage();\n // Write output file (optional)\n if (outputFile != null) {\n if (outputFileType == null) {\n // Auto-detection by file extension\n String lowername = outputFile.getName().toLowerCase();\n if (lowername.endsWith(\".bmp\"))\n outputFileType = \"bmp\";\n else\n // Default\n outputFileType = \"png\";\n }\n try {\n ImageIO.write(outputImage, outputFileType, outputFile);\n } catch (IOException e) {\n throw new IOException(\"Error writing output file (\" + outputFile + \"): \" + e.getMessage(), e);\n }\n }\n }\n\n private void resampleImage() {\n final int inWidth = inputWidth;\n final int inHeight = inputHeight;\n final int outWidth = outputWidth;\n final int outHeight = outputHeight;\n // Get packed int pixels\n int[] inPixels = new int[inWidth * inHeight];\n inputImage.getRGB(0, 0, inWidth, inHeight, inPixels, 0, inWidth);\n // Convert to float\n final float[] inVert = new float[inWidth * inHeight * 3];\n for (int i = 0, j = 0; i < inPixels.length; i++, j += 3) {\n int rgb = inPixels[i];\n inVert[j + 0] = (float) Math.pow(((rgb >>> 16) & 0xFF) / 255.0, 2.2);\n inVert[j + 1] = (float) Math.pow(((rgb >>> 8) & 0xFF) / 255.0, 2.2);\n inVert[j + 2] = (float) Math.pow(((rgb >>> 0) & 0xFF) / 255.0, 2.2);\n }\n inPixels = null;\n Thread[] thr = new Thread[threads];\n final AtomicInteger sharedY = new AtomicInteger(0);\n final float[] inHorz = new float[inWidth * outHeight * 3];\n final CyclicBarrier barrier = new CyclicBarrier(threads);\n final AtomicInteger sharedX = new AtomicInteger(0);\n final int[] outPixels = new int[outWidth * outHeight];\n for (int i = 0; i < thr.length; i++) {\n thr[i] = new Thread() {\n\n public void run() {\n // Resample vertically and transpose\n {\n double sincScale = Math.min((double) outHeight / inHeight, 1);\n double[] weights = new double[(int) verticalFilterLength + 1];\n float[] outVertRow = new float[inWidth * 3];\n while (true) {\n // For each output row\n int y = sharedY.getAndIncrement();\n if (y >= outHeight)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerY = (y + 0.5) / outHeight * inHeight;\n double filterStartY = centerY - verticalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartY - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputY = startIndex + i;\n double weight = windowedSinc((inputY + 0.5 - centerY) * sincScale, (inputY + 0.5 - filterStartY) / verticalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outVertRow, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputY = Math.min(Math.max(startIndex + i, 0), inHeight - 1);\n for (int x = 0; x < inWidth; x++) {\n // For each pixel in the row\n int j = (clippedInputY * inWidth + x) * 3;\n outVertRow[x * 3 + 0] += inVert[j + 0] * weight;\n outVertRow[x * 3 + 1] += inVert[j + 1] * weight;\n outVertRow[x * 3 + 2] += inVert[j + 2] * weight;\n }\n }\n for (int x = 0; x < inWidth; x++) {\n int j = (x * outHeight + y) * 3;\n inHorz[j + 0] = outVertRow[x * 3 + 0];\n inHorz[j + 1] = outVertRow[x * 3 + 1];\n inHorz[j + 2] = outVertRow[x * 3 + 2];\n }\n }\n }\n // Wait for all threads to finish the phase\n try {\n barrier.await();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n } catch (BrokenBarrierException e) {\n throw new RuntimeException(e);\n }\n // Resample horizontally and transpose\n {\n double sincScale = Math.min((double) outWidth / inWidth, 1);\n double[] weights = new double[(int) horizontalFilterLength + 1];\n double[] outHorzCol = new double[outHeight * 3];\n while (true) {\n // For each output column\n int x = sharedX.getAndIncrement();\n if (x >= outWidth)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerX = (x + 0.5) / outWidth * inWidth;\n double filterStartX = centerX - horizontalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartX - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputX = startIndex + i;\n double weight = windowedSinc((inputX + 0.5 - centerX) * sincScale, (inputX + 0.5 - filterStartX) / horizontalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outHorzCol, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputX = Math.min(Math.max(startIndex + i, 0), inWidth - 1);\n for (int y = 0; y < outHeight; y++) {\n // For each pixel in the column\n int j = (clippedInputX * outHeight + y) * 3;\n outHorzCol[y * 3 + 0] += inHorz[j + 0] * weight;\n outHorzCol[y * 3 + 1] += inHorz[j + 1] * weight;\n outHorzCol[y * 3 + 2] += inHorz[j + 2] * weight;\n }\n }\n for (int y = 0; y < outHeight; y++) {\n // Convert to 8 bits per channel and pack integers\n double r = outHorzCol[y * 3 + 0] * 255;\n if (r < 0)\n r = 0;\n if (r > 255)\n r = 255;\n double g = outHorzCol[y * 3 + 1] * 255;\n if (g < 0)\n g = 0;\n if (g > 255)\n g = 255;\n double b = outHorzCol[y * 3 + 2] * 255;\n if (b < 0)\n b = 0;\n if (b > 255)\n b = 255;\n outPixels[y * outWidth + x] = (int) (r + 0.5) << 16 | (int) (g + 0.5) << 8 | (int) (b + 0.5);\n }\n }\n }\n }\n };\n thr[i].start();\n }\n try {\n for (Thread th : thr) th.join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n outputImage = new BufferedImage(outWidth, outHeight, BufferedImage.TYPE_INT_RGB);\n outputImage.setRGB(0, 0, outWidth, outHeight, outPixels, 0, outWidth);\n }\n\n // x is measured in half-cycles; y is for the window which has the domain [0, 1]\n private static double windowedSinc(double x, double y) {\n x *= Math.PI;\n double sinc = x != 0 ", "post_mask_code": "\n // Triangle window\n double window = 0 <= y && y <= 1 ? 1 - Math.abs(y - 0.5) * 2 : 0;\n return sinc * window;\n }\n }\n}\n"} {"task_id": "Java_593", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/nayuki/Nayuki-web-published-code/go-train-acceleration-analyzed-by-video/PreprocessFrames.java", "mask_start_position": 2541, "mask_end_position": 2903, "canonical_solution": "public static void resampleFile(File inFile, int outWidth, int outHeight, File outFile) throws IOException {\n FastSincImageResampler rs = new FastSincImageResampler();\n rs.inputFile = inFile;\n rs.outputWidth = outWidth;\n rs.outputHeight = outHeight;\n rs.outputFile = outFile;\n rs.run();\n }", "pre_mask_code": "/* \n * Preprocess frames\n * \n * All rights reserved. Contact Nayuki for licensing.\n * http://example.com\n */\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport javax.imageio.ImageIO;\n\npublic final class PreprocessFrames {\n\n // Configuration\n private static final int INPUT_FRAME_START = 990;\n\n private static final int INPUT_FRAME_END = 3900;\n\n private static final int INPUT_FRAME_DECIMATE = 3;\n\n private static final int IMAGE_WIDTH = 1280;\n\n private static final int IMAGE_HEIGHT = 192;\n\n private static final int IMAGE_UPSCALE = 4;\n\n public static void main(String[] args) throws IOException {\n // Get and check arguments\n if (args.length != 2) {\n System.err.println(\"Usage: java PreprocessFrames InDir OutDir\");\n System.exit(1);\n return;\n }\n File inDir = new File(args[0]);\n File outDir = new File(args[1]);\n if (!inDir.isDirectory())\n throw new RuntimeException(\"Invalid input directory\");\n if (!outDir.isDirectory())\n throw new RuntimeException(\"Invalid output directory\");\n // Process image frames\n for (int inFrame = INPUT_FRAME_START, outFrame = 0; inFrame < INPUT_FRAME_END; inFrame += INPUT_FRAME_DECIMATE, outFrame++) {\n File inFile = new File(inDir, String.format(\"%04d.bmp\", inFrame));\n File outFile = new File(outDir, String.format(\"%04d.bmp\", outFrame));\n FastSincImageResampler.resampleFile(inFile, IMAGE_WIDTH * IMAGE_UPSCALE, IMAGE_HEIGHT * IMAGE_UPSCALE, outFile);\n System.out.printf(\"%s --> %s%n\", inFile.getName(), outFile.getName());\n }\n }\n\n // Based on http://example.com\n private static final class FastSincImageResampler {\n\n /* Convenience methods */\n /**\n * Resamples the specified image file to the specified output dimensions, writing to the specified output file.\n * @param inFile the input image file (must be in BMP or PNG format)\n * @param outWidth the output image width (must be positive)\n * @param outHeight the output image height (must be positive)\n * @param outFile the output image file\n * @throws IOException if an I/O exception occurred in reading the input image file or writing the output image file\n */\n ", "post_mask_code": "\n\n /* Full functionality */\n public File inputFile = null;\n\n public BufferedImage inputImage = null;\n\n // run() does not read this, but will overwrite this field\n public int inputWidth = -1;\n\n // run() does not read this, but will overwrite this field\n public int inputHeight = -1;\n\n // Must set to a positive number\n public int outputWidth = -1;\n\n // Must set to a positive number\n public int outputHeight = -1;\n\n // Horizontal filter length (set a positive value, otherwise an automatic default value will be computed)\n public double horizontalFilterLength = -1;\n\n // Vertical filter length (set a positive value, otherwise an automatic default value will be computed)\n public double verticalFilterLength = -1;\n\n // Number of threads to use (set a positive value, otherwise an automatic default value will be computed)\n public int threads = -1;\n\n // run() does not read this, but will overwrite this field\n public BufferedImage outputImage = null;\n\n public File outputFile = null;\n\n // Must be \"png\", \"bmp\", or null (auto-detection based on outputFile's extension)\n public String outputFileType = null;\n\n /**\n * Constructs a blank resampler object - certain fields must be set before calling {@code run()}.\n */\n public FastSincImageResampler() {\n }\n\n /**\n * Runs the resampler. The data flow operates on a \"waterfall\" model, reading and writing the fields from top to bottom:\n *
    \n *
  1. If {@code inputFile} is non-{@code null}, then it is read into {@code inputImage}.
  2. \n *
  3. {@code inputImage} needs to be non-{@code null} now (set explicitly or read from {@code inputFile}).
  4. \n *
  5. {@code inputImage} is read into {@code inputWidth} and {@code inputHeight}.
  6. \n *
  7. {@code outputWidth} and {@code outputHeight} must be positive (set explicitly).
  8. \n *
  9. If a filter length is zero or negative, then a default filter length is computed and set for that axis.
  10. \n *
  11. If {@code threads} is zero or negative, then a default number of threads is computed and set.
  12. \n *
  13. {@code outputImage} is computed by resampling {@code inputImage}. (This is the main purpose of the class.)
  14. \n *
  15. If {@code outputFile} is non-{@code null} and {@code outputFileType} is {@code null}: The type is set to {@code \"png\"} or {@code \"bmp\"}\n * if the output file has that extension (case-insensitive), otherwise it is set to {@code \"png\"} by default.
  16. \n *
  17. If {@code outputFile} is non-{@code null}, then {@code outputImage} is written to the file.
  18. \n *
\n *

After calling {@code run()}, it is recommend that this object should not be reused for another resampling operation.\n * This is because various fields probably need to be cleared, such as the filter length and output file type.

\n * @throws IOException if an I/O exception occurred\n * @throws IllegalStateException if there is no input image or the output dimensions are not set to positive values\n */\n public void run() throws IOException {\n // Read input file (optional)\n if (inputFile != null) {\n try {\n inputImage = ImageIO.read(inputFile);\n } catch (IOException e) {\n throw new IOException(\"Error reading input file (\" + inputFile + \"): \" + e.getMessage(), e);\n }\n }\n // Get input image dimensions\n if (inputImage == null)\n throw new IllegalStateException(\"No input image\");\n inputWidth = inputImage.getWidth();\n inputHeight = inputImage.getHeight();\n // Calculate filter lengths (optional)\n if (outputWidth <= 0 || outputHeight <= 0)\n throw new IllegalStateException(\"Output dimensions not set\");\n if (horizontalFilterLength <= 0)\n horizontalFilterLength = Math.max((double) inputWidth / outputWidth, 1) * 4.0;\n if (verticalFilterLength <= 0)\n verticalFilterLength = Math.max((double) inputHeight / outputHeight, 1) * 4.0;\n // Resample the image\n if (threads <= 0)\n threads = Runtime.getRuntime().availableProcessors();\n resampleImage();\n // Write output file (optional)\n if (outputFile != null) {\n if (outputFileType == null) {\n // Auto-detection by file extension\n String lowername = outputFile.getName().toLowerCase();\n if (lowername.endsWith(\".bmp\"))\n outputFileType = \"bmp\";\n else\n // Default\n outputFileType = \"png\";\n }\n try {\n ImageIO.write(outputImage, outputFileType, outputFile);\n } catch (IOException e) {\n throw new IOException(\"Error writing output file (\" + outputFile + \"): \" + e.getMessage(), e);\n }\n }\n }\n\n private void resampleImage() {\n final int inWidth = inputWidth;\n final int inHeight = inputHeight;\n final int outWidth = outputWidth;\n final int outHeight = outputHeight;\n // Get packed int pixels\n int[] inPixels = new int[inWidth * inHeight];\n inputImage.getRGB(0, 0, inWidth, inHeight, inPixels, 0, inWidth);\n // Convert to float\n final float[] inVert = new float[inWidth * inHeight * 3];\n for (int i = 0, j = 0; i < inPixels.length; i++, j += 3) {\n int rgb = inPixels[i];\n inVert[j + 0] = (float) Math.pow(((rgb >>> 16) & 0xFF) / 255.0, 2.2);\n inVert[j + 1] = (float) Math.pow(((rgb >>> 8) & 0xFF) / 255.0, 2.2);\n inVert[j + 2] = (float) Math.pow(((rgb >>> 0) & 0xFF) / 255.0, 2.2);\n }\n inPixels = null;\n Thread[] thr = new Thread[threads];\n final AtomicInteger sharedY = new AtomicInteger(0);\n final float[] inHorz = new float[inWidth * outHeight * 3];\n final CyclicBarrier barrier = new CyclicBarrier(threads);\n final AtomicInteger sharedX = new AtomicInteger(0);\n final int[] outPixels = new int[outWidth * outHeight];\n for (int i = 0; i < thr.length; i++) {\n thr[i] = new Thread() {\n\n public void run() {\n // Resample vertically and transpose\n {\n double sincScale = Math.min((double) outHeight / inHeight, 1);\n double[] weights = new double[(int) verticalFilterLength + 1];\n float[] outVertRow = new float[inWidth * 3];\n while (true) {\n // For each output row\n int y = sharedY.getAndIncrement();\n if (y >= outHeight)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerY = (y + 0.5) / outHeight * inHeight;\n double filterStartY = centerY - verticalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartY - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputY = startIndex + i;\n double weight = windowedSinc((inputY + 0.5 - centerY) * sincScale, (inputY + 0.5 - filterStartY) / verticalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outVertRow, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputY = Math.min(Math.max(startIndex + i, 0), inHeight - 1);\n for (int x = 0; x < inWidth; x++) {\n // For each pixel in the row\n int j = (clippedInputY * inWidth + x) * 3;\n outVertRow[x * 3 + 0] += inVert[j + 0] * weight;\n outVertRow[x * 3 + 1] += inVert[j + 1] * weight;\n outVertRow[x * 3 + 2] += inVert[j + 2] * weight;\n }\n }\n for (int x = 0; x < inWidth; x++) {\n int j = (x * outHeight + y) * 3;\n inHorz[j + 0] = outVertRow[x * 3 + 0];\n inHorz[j + 1] = outVertRow[x * 3 + 1];\n inHorz[j + 2] = outVertRow[x * 3 + 2];\n }\n }\n }\n // Wait for all threads to finish the phase\n try {\n barrier.await();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n } catch (BrokenBarrierException e) {\n throw new RuntimeException(e);\n }\n // Resample horizontally and transpose\n {\n double sincScale = Math.min((double) outWidth / inWidth, 1);\n double[] weights = new double[(int) horizontalFilterLength + 1];\n double[] outHorzCol = new double[outHeight * 3];\n while (true) {\n // For each output column\n int x = sharedX.getAndIncrement();\n if (x >= outWidth)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerX = (x + 0.5) / outWidth * inWidth;\n double filterStartX = centerX - horizontalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartX - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputX = startIndex + i;\n double weight = windowedSinc((inputX + 0.5 - centerX) * sincScale, (inputX + 0.5 - filterStartX) / horizontalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outHorzCol, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputX = Math.min(Math.max(startIndex + i, 0), inWidth - 1);\n for (int y = 0; y < outHeight; y++) {\n // For each pixel in the column\n int j = (clippedInputX * outHeight + y) * 3;\n outHorzCol[y * 3 + 0] += inHorz[j + 0] * weight;\n outHorzCol[y * 3 + 1] += inHorz[j + 1] * weight;\n outHorzCol[y * 3 + 2] += inHorz[j + 2] * weight;\n }\n }\n for (int y = 0; y < outHeight; y++) {\n // Convert to 8 bits per channel and pack integers\n double r = outHorzCol[y * 3 + 0] * 255;\n if (r < 0)\n r = 0;\n if (r > 255)\n r = 255;\n double g = outHorzCol[y * 3 + 1] * 255;\n if (g < 0)\n g = 0;\n if (g > 255)\n g = 255;\n double b = outHorzCol[y * 3 + 2] * 255;\n if (b < 0)\n b = 0;\n if (b > 255)\n b = 255;\n outPixels[y * outWidth + x] = (int) (r + 0.5) << 16 | (int) (g + 0.5) << 8 | (int) (b + 0.5);\n }\n }\n }\n }\n };\n thr[i].start();\n }\n try {\n for (Thread th : thr) th.join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n outputImage = new BufferedImage(outWidth, outHeight, BufferedImage.TYPE_INT_RGB);\n outputImage.setRGB(0, 0, outWidth, outHeight, outPixels, 0, outWidth);\n }\n\n // x is measured in half-cycles; y is for the window which has the domain [0, 1]\n private static double windowedSinc(double x, double y) {\n x *= Math.PI;\n double sinc = x != 0 ? Math.sin(x) / x : 1;\n // Triangle window\n double window = 0 <= y && y <= 1 ? 1 - Math.abs(y - 0.5) * 2 : 0;\n return sinc * window;\n }\n }\n}\n"} {"task_id": "Java_594", "language": "Java", "task_type": "if_statement", "source_file": "java/github/nayuki/Nayuki-web-published-code/go-train-acceleration-analyzed-by-video/PreprocessFrames.java", "mask_start_position": 15675, "mask_end_position": 15732, "canonical_solution": "if (g < 0)\n g = 0;", "pre_mask_code": "/* \n * Preprocess frames\n * \n * All rights reserved. Contact Nayuki for licensing.\n * http://example.com\n */\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport javax.imageio.ImageIO;\n\npublic final class PreprocessFrames {\n\n // Configuration\n private static final int INPUT_FRAME_START = 990;\n\n private static final int INPUT_FRAME_END = 3900;\n\n private static final int INPUT_FRAME_DECIMATE = 3;\n\n private static final int IMAGE_WIDTH = 1280;\n\n private static final int IMAGE_HEIGHT = 192;\n\n private static final int IMAGE_UPSCALE = 4;\n\n public static void main(String[] args) throws IOException {\n // Get and check arguments\n if (args.length != 2) {\n System.err.println(\"Usage: java PreprocessFrames InDir OutDir\");\n System.exit(1);\n return;\n }\n File inDir = new File(args[0]);\n File outDir = new File(args[1]);\n if (!inDir.isDirectory())\n throw new RuntimeException(\"Invalid input directory\");\n if (!outDir.isDirectory())\n throw new RuntimeException(\"Invalid output directory\");\n // Process image frames\n for (int inFrame = INPUT_FRAME_START, outFrame = 0; inFrame < INPUT_FRAME_END; inFrame += INPUT_FRAME_DECIMATE, outFrame++) {\n File inFile = new File(inDir, String.format(\"%04d.bmp\", inFrame));\n File outFile = new File(outDir, String.format(\"%04d.bmp\", outFrame));\n FastSincImageResampler.resampleFile(inFile, IMAGE_WIDTH * IMAGE_UPSCALE, IMAGE_HEIGHT * IMAGE_UPSCALE, outFile);\n System.out.printf(\"%s --> %s%n\", inFile.getName(), outFile.getName());\n }\n }\n\n // Based on http://example.com\n private static final class FastSincImageResampler {\n\n /* Convenience methods */\n /**\n * Resamples the specified image file to the specified output dimensions, writing to the specified output file.\n * @param inFile the input image file (must be in BMP or PNG format)\n * @param outWidth the output image width (must be positive)\n * @param outHeight the output image height (must be positive)\n * @param outFile the output image file\n * @throws IOException if an I/O exception occurred in reading the input image file or writing the output image file\n */\n public static void resampleFile(File inFile, int outWidth, int outHeight, File outFile) throws IOException {\n FastSincImageResampler rs = new FastSincImageResampler();\n rs.inputFile = inFile;\n rs.outputWidth = outWidth;\n rs.outputHeight = outHeight;\n rs.outputFile = outFile;\n rs.run();\n }\n\n /* Full functionality */\n public File inputFile = null;\n\n public BufferedImage inputImage = null;\n\n // run() does not read this, but will overwrite this field\n public int inputWidth = -1;\n\n // run() does not read this, but will overwrite this field\n public int inputHeight = -1;\n\n // Must set to a positive number\n public int outputWidth = -1;\n\n // Must set to a positive number\n public int outputHeight = -1;\n\n // Horizontal filter length (set a positive value, otherwise an automatic default value will be computed)\n public double horizontalFilterLength = -1;\n\n // Vertical filter length (set a positive value, otherwise an automatic default value will be computed)\n public double verticalFilterLength = -1;\n\n // Number of threads to use (set a positive value, otherwise an automatic default value will be computed)\n public int threads = -1;\n\n // run() does not read this, but will overwrite this field\n public BufferedImage outputImage = null;\n\n public File outputFile = null;\n\n // Must be \"png\", \"bmp\", or null (auto-detection based on outputFile's extension)\n public String outputFileType = null;\n\n /**\n * Constructs a blank resampler object - certain fields must be set before calling {@code run()}.\n */\n public FastSincImageResampler() {\n }\n\n /**\n * Runs the resampler. The data flow operates on a \"waterfall\" model, reading and writing the fields from top to bottom:\n *
    \n *
  1. If {@code inputFile} is non-{@code null}, then it is read into {@code inputImage}.
  2. \n *
  3. {@code inputImage} needs to be non-{@code null} now (set explicitly or read from {@code inputFile}).
  4. \n *
  5. {@code inputImage} is read into {@code inputWidth} and {@code inputHeight}.
  6. \n *
  7. {@code outputWidth} and {@code outputHeight} must be positive (set explicitly).
  8. \n *
  9. If a filter length is zero or negative, then a default filter length is computed and set for that axis.
  10. \n *
  11. If {@code threads} is zero or negative, then a default number of threads is computed and set.
  12. \n *
  13. {@code outputImage} is computed by resampling {@code inputImage}. (This is the main purpose of the class.)
  14. \n *
  15. If {@code outputFile} is non-{@code null} and {@code outputFileType} is {@code null}: The type is set to {@code \"png\"} or {@code \"bmp\"}\n * if the output file has that extension (case-insensitive), otherwise it is set to {@code \"png\"} by default.
  16. \n *
  17. If {@code outputFile} is non-{@code null}, then {@code outputImage} is written to the file.
  18. \n *
\n *

After calling {@code run()}, it is recommend that this object should not be reused for another resampling operation.\n * This is because various fields probably need to be cleared, such as the filter length and output file type.

\n * @throws IOException if an I/O exception occurred\n * @throws IllegalStateException if there is no input image or the output dimensions are not set to positive values\n */\n public void run() throws IOException {\n // Read input file (optional)\n if (inputFile != null) {\n try {\n inputImage = ImageIO.read(inputFile);\n } catch (IOException e) {\n throw new IOException(\"Error reading input file (\" + inputFile + \"): \" + e.getMessage(), e);\n }\n }\n // Get input image dimensions\n if (inputImage == null)\n throw new IllegalStateException(\"No input image\");\n inputWidth = inputImage.getWidth();\n inputHeight = inputImage.getHeight();\n // Calculate filter lengths (optional)\n if (outputWidth <= 0 || outputHeight <= 0)\n throw new IllegalStateException(\"Output dimensions not set\");\n if (horizontalFilterLength <= 0)\n horizontalFilterLength = Math.max((double) inputWidth / outputWidth, 1) * 4.0;\n if (verticalFilterLength <= 0)\n verticalFilterLength = Math.max((double) inputHeight / outputHeight, 1) * 4.0;\n // Resample the image\n if (threads <= 0)\n threads = Runtime.getRuntime().availableProcessors();\n resampleImage();\n // Write output file (optional)\n if (outputFile != null) {\n if (outputFileType == null) {\n // Auto-detection by file extension\n String lowername = outputFile.getName().toLowerCase();\n if (lowername.endsWith(\".bmp\"))\n outputFileType = \"bmp\";\n else\n // Default\n outputFileType = \"png\";\n }\n try {\n ImageIO.write(outputImage, outputFileType, outputFile);\n } catch (IOException e) {\n throw new IOException(\"Error writing output file (\" + outputFile + \"): \" + e.getMessage(), e);\n }\n }\n }\n\n private void resampleImage() {\n final int inWidth = inputWidth;\n final int inHeight = inputHeight;\n final int outWidth = outputWidth;\n final int outHeight = outputHeight;\n // Get packed int pixels\n int[] inPixels = new int[inWidth * inHeight];\n inputImage.getRGB(0, 0, inWidth, inHeight, inPixels, 0, inWidth);\n // Convert to float\n final float[] inVert = new float[inWidth * inHeight * 3];\n for (int i = 0, j = 0; i < inPixels.length; i++, j += 3) {\n int rgb = inPixels[i];\n inVert[j + 0] = (float) Math.pow(((rgb >>> 16) & 0xFF) / 255.0, 2.2);\n inVert[j + 1] = (float) Math.pow(((rgb >>> 8) & 0xFF) / 255.0, 2.2);\n inVert[j + 2] = (float) Math.pow(((rgb >>> 0) & 0xFF) / 255.0, 2.2);\n }\n inPixels = null;\n Thread[] thr = new Thread[threads];\n final AtomicInteger sharedY = new AtomicInteger(0);\n final float[] inHorz = new float[inWidth * outHeight * 3];\n final CyclicBarrier barrier = new CyclicBarrier(threads);\n final AtomicInteger sharedX = new AtomicInteger(0);\n final int[] outPixels = new int[outWidth * outHeight];\n for (int i = 0; i < thr.length; i++) {\n thr[i] = new Thread() {\n\n public void run() {\n // Resample vertically and transpose\n {\n double sincScale = Math.min((double) outHeight / inHeight, 1);\n double[] weights = new double[(int) verticalFilterLength + 1];\n float[] outVertRow = new float[inWidth * 3];\n while (true) {\n // For each output row\n int y = sharedY.getAndIncrement();\n if (y >= outHeight)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerY = (y + 0.5) / outHeight * inHeight;\n double filterStartY = centerY - verticalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartY - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputY = startIndex + i;\n double weight = windowedSinc((inputY + 0.5 - centerY) * sincScale, (inputY + 0.5 - filterStartY) / verticalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outVertRow, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputY = Math.min(Math.max(startIndex + i, 0), inHeight - 1);\n for (int x = 0; x < inWidth; x++) {\n // For each pixel in the row\n int j = (clippedInputY * inWidth + x) * 3;\n outVertRow[x * 3 + 0] += inVert[j + 0] * weight;\n outVertRow[x * 3 + 1] += inVert[j + 1] * weight;\n outVertRow[x * 3 + 2] += inVert[j + 2] * weight;\n }\n }\n for (int x = 0; x < inWidth; x++) {\n int j = (x * outHeight + y) * 3;\n inHorz[j + 0] = outVertRow[x * 3 + 0];\n inHorz[j + 1] = outVertRow[x * 3 + 1];\n inHorz[j + 2] = outVertRow[x * 3 + 2];\n }\n }\n }\n // Wait for all threads to finish the phase\n try {\n barrier.await();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n } catch (BrokenBarrierException e) {\n throw new RuntimeException(e);\n }\n // Resample horizontally and transpose\n {\n double sincScale = Math.min((double) outWidth / inWidth, 1);\n double[] weights = new double[(int) horizontalFilterLength + 1];\n double[] outHorzCol = new double[outHeight * 3];\n while (true) {\n // For each output column\n int x = sharedX.getAndIncrement();\n if (x >= outWidth)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerX = (x + 0.5) / outWidth * inWidth;\n double filterStartX = centerX - horizontalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartX - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputX = startIndex + i;\n double weight = windowedSinc((inputX + 0.5 - centerX) * sincScale, (inputX + 0.5 - filterStartX) / horizontalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outHorzCol, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputX = Math.min(Math.max(startIndex + i, 0), inWidth - 1);\n for (int y = 0; y < outHeight; y++) {\n // For each pixel in the column\n int j = (clippedInputX * outHeight + y) * 3;\n outHorzCol[y * 3 + 0] += inHorz[j + 0] * weight;\n outHorzCol[y * 3 + 1] += inHorz[j + 1] * weight;\n outHorzCol[y * 3 + 2] += inHorz[j + 2] * weight;\n }\n }\n for (int y = 0; y < outHeight; y++) {\n // Convert to 8 bits per channel and pack integers\n double r = outHorzCol[y * 3 + 0] * 255;\n if (r < 0)\n r = 0;\n if (r > 255)\n r = 255;\n double g = outHorzCol[y * 3 + 1] * 255;\n ", "post_mask_code": "\n if (g > 255)\n g = 255;\n double b = outHorzCol[y * 3 + 2] * 255;\n if (b < 0)\n b = 0;\n if (b > 255)\n b = 255;\n outPixels[y * outWidth + x] = (int) (r + 0.5) << 16 | (int) (g + 0.5) << 8 | (int) (b + 0.5);\n }\n }\n }\n }\n };\n thr[i].start();\n }\n try {\n for (Thread th : thr) th.join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n outputImage = new BufferedImage(outWidth, outHeight, BufferedImage.TYPE_INT_RGB);\n outputImage.setRGB(0, 0, outWidth, outHeight, outPixels, 0, outWidth);\n }\n\n // x is measured in half-cycles; y is for the window which has the domain [0, 1]\n private static double windowedSinc(double x, double y) {\n x *= Math.PI;\n double sinc = x != 0 ? Math.sin(x) / x : 1;\n // Triangle window\n double window = 0 <= y && y <= 1 ? 1 - Math.abs(y - 0.5) * 2 : 0;\n return sinc * window;\n }\n }\n}\n"} {"task_id": "Java_595", "language": "Java", "task_type": "for_statement", "source_file": "java/github/nayuki/Nayuki-web-published-code/go-train-acceleration-analyzed-by-video/PreprocessFrames.java", "mask_start_position": 11430, "mask_end_position": 11922, "canonical_solution": "for (int x = 0; x < inWidth; x++) {\n // For each pixel in the row\n int j = (clippedInputY * inWidth + x) * 3;\n outVertRow[x * 3 + 0] += inVert[j + 0] * weight;\n outVertRow[x * 3 + 1] += inVert[j + 1] * weight;\n outVertRow[x * 3 + 2] += inVert[j + 2] * weight;\n }", "pre_mask_code": "/* \n * Preprocess frames\n * \n * All rights reserved. Contact Nayuki for licensing.\n * http://example.com\n */\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport javax.imageio.ImageIO;\n\npublic final class PreprocessFrames {\n\n // Configuration\n private static final int INPUT_FRAME_START = 990;\n\n private static final int INPUT_FRAME_END = 3900;\n\n private static final int INPUT_FRAME_DECIMATE = 3;\n\n private static final int IMAGE_WIDTH = 1280;\n\n private static final int IMAGE_HEIGHT = 192;\n\n private static final int IMAGE_UPSCALE = 4;\n\n public static void main(String[] args) throws IOException {\n // Get and check arguments\n if (args.length != 2) {\n System.err.println(\"Usage: java PreprocessFrames InDir OutDir\");\n System.exit(1);\n return;\n }\n File inDir = new File(args[0]);\n File outDir = new File(args[1]);\n if (!inDir.isDirectory())\n throw new RuntimeException(\"Invalid input directory\");\n if (!outDir.isDirectory())\n throw new RuntimeException(\"Invalid output directory\");\n // Process image frames\n for (int inFrame = INPUT_FRAME_START, outFrame = 0; inFrame < INPUT_FRAME_END; inFrame += INPUT_FRAME_DECIMATE, outFrame++) {\n File inFile = new File(inDir, String.format(\"%04d.bmp\", inFrame));\n File outFile = new File(outDir, String.format(\"%04d.bmp\", outFrame));\n FastSincImageResampler.resampleFile(inFile, IMAGE_WIDTH * IMAGE_UPSCALE, IMAGE_HEIGHT * IMAGE_UPSCALE, outFile);\n System.out.printf(\"%s --> %s%n\", inFile.getName(), outFile.getName());\n }\n }\n\n // Based on http://example.com\n private static final class FastSincImageResampler {\n\n /* Convenience methods */\n /**\n * Resamples the specified image file to the specified output dimensions, writing to the specified output file.\n * @param inFile the input image file (must be in BMP or PNG format)\n * @param outWidth the output image width (must be positive)\n * @param outHeight the output image height (must be positive)\n * @param outFile the output image file\n * @throws IOException if an I/O exception occurred in reading the input image file or writing the output image file\n */\n public static void resampleFile(File inFile, int outWidth, int outHeight, File outFile) throws IOException {\n FastSincImageResampler rs = new FastSincImageResampler();\n rs.inputFile = inFile;\n rs.outputWidth = outWidth;\n rs.outputHeight = outHeight;\n rs.outputFile = outFile;\n rs.run();\n }\n\n /* Full functionality */\n public File inputFile = null;\n\n public BufferedImage inputImage = null;\n\n // run() does not read this, but will overwrite this field\n public int inputWidth = -1;\n\n // run() does not read this, but will overwrite this field\n public int inputHeight = -1;\n\n // Must set to a positive number\n public int outputWidth = -1;\n\n // Must set to a positive number\n public int outputHeight = -1;\n\n // Horizontal filter length (set a positive value, otherwise an automatic default value will be computed)\n public double horizontalFilterLength = -1;\n\n // Vertical filter length (set a positive value, otherwise an automatic default value will be computed)\n public double verticalFilterLength = -1;\n\n // Number of threads to use (set a positive value, otherwise an automatic default value will be computed)\n public int threads = -1;\n\n // run() does not read this, but will overwrite this field\n public BufferedImage outputImage = null;\n\n public File outputFile = null;\n\n // Must be \"png\", \"bmp\", or null (auto-detection based on outputFile's extension)\n public String outputFileType = null;\n\n /**\n * Constructs a blank resampler object - certain fields must be set before calling {@code run()}.\n */\n public FastSincImageResampler() {\n }\n\n /**\n * Runs the resampler. The data flow operates on a \"waterfall\" model, reading and writing the fields from top to bottom:\n *
    \n *
  1. If {@code inputFile} is non-{@code null}, then it is read into {@code inputImage}.
  2. \n *
  3. {@code inputImage} needs to be non-{@code null} now (set explicitly or read from {@code inputFile}).
  4. \n *
  5. {@code inputImage} is read into {@code inputWidth} and {@code inputHeight}.
  6. \n *
  7. {@code outputWidth} and {@code outputHeight} must be positive (set explicitly).
  8. \n *
  9. If a filter length is zero or negative, then a default filter length is computed and set for that axis.
  10. \n *
  11. If {@code threads} is zero or negative, then a default number of threads is computed and set.
  12. \n *
  13. {@code outputImage} is computed by resampling {@code inputImage}. (This is the main purpose of the class.)
  14. \n *
  15. If {@code outputFile} is non-{@code null} and {@code outputFileType} is {@code null}: The type is set to {@code \"png\"} or {@code \"bmp\"}\n * if the output file has that extension (case-insensitive), otherwise it is set to {@code \"png\"} by default.
  16. \n *
  17. If {@code outputFile} is non-{@code null}, then {@code outputImage} is written to the file.
  18. \n *
\n *

After calling {@code run()}, it is recommend that this object should not be reused for another resampling operation.\n * This is because various fields probably need to be cleared, such as the filter length and output file type.

\n * @throws IOException if an I/O exception occurred\n * @throws IllegalStateException if there is no input image or the output dimensions are not set to positive values\n */\n public void run() throws IOException {\n // Read input file (optional)\n if (inputFile != null) {\n try {\n inputImage = ImageIO.read(inputFile);\n } catch (IOException e) {\n throw new IOException(\"Error reading input file (\" + inputFile + \"): \" + e.getMessage(), e);\n }\n }\n // Get input image dimensions\n if (inputImage == null)\n throw new IllegalStateException(\"No input image\");\n inputWidth = inputImage.getWidth();\n inputHeight = inputImage.getHeight();\n // Calculate filter lengths (optional)\n if (outputWidth <= 0 || outputHeight <= 0)\n throw new IllegalStateException(\"Output dimensions not set\");\n if (horizontalFilterLength <= 0)\n horizontalFilterLength = Math.max((double) inputWidth / outputWidth, 1) * 4.0;\n if (verticalFilterLength <= 0)\n verticalFilterLength = Math.max((double) inputHeight / outputHeight, 1) * 4.0;\n // Resample the image\n if (threads <= 0)\n threads = Runtime.getRuntime().availableProcessors();\n resampleImage();\n // Write output file (optional)\n if (outputFile != null) {\n if (outputFileType == null) {\n // Auto-detection by file extension\n String lowername = outputFile.getName().toLowerCase();\n if (lowername.endsWith(\".bmp\"))\n outputFileType = \"bmp\";\n else\n // Default\n outputFileType = \"png\";\n }\n try {\n ImageIO.write(outputImage, outputFileType, outputFile);\n } catch (IOException e) {\n throw new IOException(\"Error writing output file (\" + outputFile + \"): \" + e.getMessage(), e);\n }\n }\n }\n\n private void resampleImage() {\n final int inWidth = inputWidth;\n final int inHeight = inputHeight;\n final int outWidth = outputWidth;\n final int outHeight = outputHeight;\n // Get packed int pixels\n int[] inPixels = new int[inWidth * inHeight];\n inputImage.getRGB(0, 0, inWidth, inHeight, inPixels, 0, inWidth);\n // Convert to float\n final float[] inVert = new float[inWidth * inHeight * 3];\n for (int i = 0, j = 0; i < inPixels.length; i++, j += 3) {\n int rgb = inPixels[i];\n inVert[j + 0] = (float) Math.pow(((rgb >>> 16) & 0xFF) / 255.0, 2.2);\n inVert[j + 1] = (float) Math.pow(((rgb >>> 8) & 0xFF) / 255.0, 2.2);\n inVert[j + 2] = (float) Math.pow(((rgb >>> 0) & 0xFF) / 255.0, 2.2);\n }\n inPixels = null;\n Thread[] thr = new Thread[threads];\n final AtomicInteger sharedY = new AtomicInteger(0);\n final float[] inHorz = new float[inWidth * outHeight * 3];\n final CyclicBarrier barrier = new CyclicBarrier(threads);\n final AtomicInteger sharedX = new AtomicInteger(0);\n final int[] outPixels = new int[outWidth * outHeight];\n for (int i = 0; i < thr.length; i++) {\n thr[i] = new Thread() {\n\n public void run() {\n // Resample vertically and transpose\n {\n double sincScale = Math.min((double) outHeight / inHeight, 1);\n double[] weights = new double[(int) verticalFilterLength + 1];\n float[] outVertRow = new float[inWidth * 3];\n while (true) {\n // For each output row\n int y = sharedY.getAndIncrement();\n if (y >= outHeight)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerY = (y + 0.5) / outHeight * inHeight;\n double filterStartY = centerY - verticalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartY - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputY = startIndex + i;\n double weight = windowedSinc((inputY + 0.5 - centerY) * sincScale, (inputY + 0.5 - filterStartY) / verticalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outVertRow, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputY = Math.min(Math.max(startIndex + i, 0), inHeight - 1);\n ", "post_mask_code": "\n }\n for (int x = 0; x < inWidth; x++) {\n int j = (x * outHeight + y) * 3;\n inHorz[j + 0] = outVertRow[x * 3 + 0];\n inHorz[j + 1] = outVertRow[x * 3 + 1];\n inHorz[j + 2] = outVertRow[x * 3 + 2];\n }\n }\n }\n // Wait for all threads to finish the phase\n try {\n barrier.await();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n } catch (BrokenBarrierException e) {\n throw new RuntimeException(e);\n }\n // Resample horizontally and transpose\n {\n double sincScale = Math.min((double) outWidth / inWidth, 1);\n double[] weights = new double[(int) horizontalFilterLength + 1];\n double[] outHorzCol = new double[outHeight * 3];\n while (true) {\n // For each output column\n int x = sharedX.getAndIncrement();\n if (x >= outWidth)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerX = (x + 0.5) / outWidth * inWidth;\n double filterStartX = centerX - horizontalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartX - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputX = startIndex + i;\n double weight = windowedSinc((inputX + 0.5 - centerX) * sincScale, (inputX + 0.5 - filterStartX) / horizontalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outHorzCol, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputX = Math.min(Math.max(startIndex + i, 0), inWidth - 1);\n for (int y = 0; y < outHeight; y++) {\n // For each pixel in the column\n int j = (clippedInputX * outHeight + y) * 3;\n outHorzCol[y * 3 + 0] += inHorz[j + 0] * weight;\n outHorzCol[y * 3 + 1] += inHorz[j + 1] * weight;\n outHorzCol[y * 3 + 2] += inHorz[j + 2] * weight;\n }\n }\n for (int y = 0; y < outHeight; y++) {\n // Convert to 8 bits per channel and pack integers\n double r = outHorzCol[y * 3 + 0] * 255;\n if (r < 0)\n r = 0;\n if (r > 255)\n r = 255;\n double g = outHorzCol[y * 3 + 1] * 255;\n if (g < 0)\n g = 0;\n if (g > 255)\n g = 255;\n double b = outHorzCol[y * 3 + 2] * 255;\n if (b < 0)\n b = 0;\n if (b > 255)\n b = 255;\n outPixels[y * outWidth + x] = (int) (r + 0.5) << 16 | (int) (g + 0.5) << 8 | (int) (b + 0.5);\n }\n }\n }\n }\n };\n thr[i].start();\n }\n try {\n for (Thread th : thr) th.join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n outputImage = new BufferedImage(outWidth, outHeight, BufferedImage.TYPE_INT_RGB);\n outputImage.setRGB(0, 0, outWidth, outHeight, outPixels, 0, outWidth);\n }\n\n // x is measured in half-cycles; y is for the window which has the domain [0, 1]\n private static double windowedSinc(double x, double y) {\n x *= Math.PI;\n double sinc = x != 0 ? Math.sin(x) / x : 1;\n // Triangle window\n double window = 0 <= y && y <= 1 ? 1 - Math.abs(y - 0.5) * 2 : 0;\n return sinc * window;\n }\n }\n}\n"} {"task_id": "Java_596", "language": "Java", "task_type": "try_statement", "source_file": "java/github/nayuki/Nayuki-web-published-code/go-train-acceleration-analyzed-by-video/PreprocessFrames.java", "mask_start_position": 16418, "mask_end_position": 16580, "canonical_solution": "try {\n for (Thread th : thr) th.join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }", "pre_mask_code": "/* \n * Preprocess frames\n * \n * All rights reserved. Contact Nayuki for licensing.\n * http://example.com\n */\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport javax.imageio.ImageIO;\n\npublic final class PreprocessFrames {\n\n // Configuration\n private static final int INPUT_FRAME_START = 990;\n\n private static final int INPUT_FRAME_END = 3900;\n\n private static final int INPUT_FRAME_DECIMATE = 3;\n\n private static final int IMAGE_WIDTH = 1280;\n\n private static final int IMAGE_HEIGHT = 192;\n\n private static final int IMAGE_UPSCALE = 4;\n\n public static void main(String[] args) throws IOException {\n // Get and check arguments\n if (args.length != 2) {\n System.err.println(\"Usage: java PreprocessFrames InDir OutDir\");\n System.exit(1);\n return;\n }\n File inDir = new File(args[0]);\n File outDir = new File(args[1]);\n if (!inDir.isDirectory())\n throw new RuntimeException(\"Invalid input directory\");\n if (!outDir.isDirectory())\n throw new RuntimeException(\"Invalid output directory\");\n // Process image frames\n for (int inFrame = INPUT_FRAME_START, outFrame = 0; inFrame < INPUT_FRAME_END; inFrame += INPUT_FRAME_DECIMATE, outFrame++) {\n File inFile = new File(inDir, String.format(\"%04d.bmp\", inFrame));\n File outFile = new File(outDir, String.format(\"%04d.bmp\", outFrame));\n FastSincImageResampler.resampleFile(inFile, IMAGE_WIDTH * IMAGE_UPSCALE, IMAGE_HEIGHT * IMAGE_UPSCALE, outFile);\n System.out.printf(\"%s --> %s%n\", inFile.getName(), outFile.getName());\n }\n }\n\n // Based on http://example.com\n private static final class FastSincImageResampler {\n\n /* Convenience methods */\n /**\n * Resamples the specified image file to the specified output dimensions, writing to the specified output file.\n * @param inFile the input image file (must be in BMP or PNG format)\n * @param outWidth the output image width (must be positive)\n * @param outHeight the output image height (must be positive)\n * @param outFile the output image file\n * @throws IOException if an I/O exception occurred in reading the input image file or writing the output image file\n */\n public static void resampleFile(File inFile, int outWidth, int outHeight, File outFile) throws IOException {\n FastSincImageResampler rs = new FastSincImageResampler();\n rs.inputFile = inFile;\n rs.outputWidth = outWidth;\n rs.outputHeight = outHeight;\n rs.outputFile = outFile;\n rs.run();\n }\n\n /* Full functionality */\n public File inputFile = null;\n\n public BufferedImage inputImage = null;\n\n // run() does not read this, but will overwrite this field\n public int inputWidth = -1;\n\n // run() does not read this, but will overwrite this field\n public int inputHeight = -1;\n\n // Must set to a positive number\n public int outputWidth = -1;\n\n // Must set to a positive number\n public int outputHeight = -1;\n\n // Horizontal filter length (set a positive value, otherwise an automatic default value will be computed)\n public double horizontalFilterLength = -1;\n\n // Vertical filter length (set a positive value, otherwise an automatic default value will be computed)\n public double verticalFilterLength = -1;\n\n // Number of threads to use (set a positive value, otherwise an automatic default value will be computed)\n public int threads = -1;\n\n // run() does not read this, but will overwrite this field\n public BufferedImage outputImage = null;\n\n public File outputFile = null;\n\n // Must be \"png\", \"bmp\", or null (auto-detection based on outputFile's extension)\n public String outputFileType = null;\n\n /**\n * Constructs a blank resampler object - certain fields must be set before calling {@code run()}.\n */\n public FastSincImageResampler() {\n }\n\n /**\n * Runs the resampler. The data flow operates on a \"waterfall\" model, reading and writing the fields from top to bottom:\n *
    \n *
  1. If {@code inputFile} is non-{@code null}, then it is read into {@code inputImage}.
  2. \n *
  3. {@code inputImage} needs to be non-{@code null} now (set explicitly or read from {@code inputFile}).
  4. \n *
  5. {@code inputImage} is read into {@code inputWidth} and {@code inputHeight}.
  6. \n *
  7. {@code outputWidth} and {@code outputHeight} must be positive (set explicitly).
  8. \n *
  9. If a filter length is zero or negative, then a default filter length is computed and set for that axis.
  10. \n *
  11. If {@code threads} is zero or negative, then a default number of threads is computed and set.
  12. \n *
  13. {@code outputImage} is computed by resampling {@code inputImage}. (This is the main purpose of the class.)
  14. \n *
  15. If {@code outputFile} is non-{@code null} and {@code outputFileType} is {@code null}: The type is set to {@code \"png\"} or {@code \"bmp\"}\n * if the output file has that extension (case-insensitive), otherwise it is set to {@code \"png\"} by default.
  16. \n *
  17. If {@code outputFile} is non-{@code null}, then {@code outputImage} is written to the file.
  18. \n *
\n *

After calling {@code run()}, it is recommend that this object should not be reused for another resampling operation.\n * This is because various fields probably need to be cleared, such as the filter length and output file type.

\n * @throws IOException if an I/O exception occurred\n * @throws IllegalStateException if there is no input image or the output dimensions are not set to positive values\n */\n public void run() throws IOException {\n // Read input file (optional)\n if (inputFile != null) {\n try {\n inputImage = ImageIO.read(inputFile);\n } catch (IOException e) {\n throw new IOException(\"Error reading input file (\" + inputFile + \"): \" + e.getMessage(), e);\n }\n }\n // Get input image dimensions\n if (inputImage == null)\n throw new IllegalStateException(\"No input image\");\n inputWidth = inputImage.getWidth();\n inputHeight = inputImage.getHeight();\n // Calculate filter lengths (optional)\n if (outputWidth <= 0 || outputHeight <= 0)\n throw new IllegalStateException(\"Output dimensions not set\");\n if (horizontalFilterLength <= 0)\n horizontalFilterLength = Math.max((double) inputWidth / outputWidth, 1) * 4.0;\n if (verticalFilterLength <= 0)\n verticalFilterLength = Math.max((double) inputHeight / outputHeight, 1) * 4.0;\n // Resample the image\n if (threads <= 0)\n threads = Runtime.getRuntime().availableProcessors();\n resampleImage();\n // Write output file (optional)\n if (outputFile != null) {\n if (outputFileType == null) {\n // Auto-detection by file extension\n String lowername = outputFile.getName().toLowerCase();\n if (lowername.endsWith(\".bmp\"))\n outputFileType = \"bmp\";\n else\n // Default\n outputFileType = \"png\";\n }\n try {\n ImageIO.write(outputImage, outputFileType, outputFile);\n } catch (IOException e) {\n throw new IOException(\"Error writing output file (\" + outputFile + \"): \" + e.getMessage(), e);\n }\n }\n }\n\n private void resampleImage() {\n final int inWidth = inputWidth;\n final int inHeight = inputHeight;\n final int outWidth = outputWidth;\n final int outHeight = outputHeight;\n // Get packed int pixels\n int[] inPixels = new int[inWidth * inHeight];\n inputImage.getRGB(0, 0, inWidth, inHeight, inPixels, 0, inWidth);\n // Convert to float\n final float[] inVert = new float[inWidth * inHeight * 3];\n for (int i = 0, j = 0; i < inPixels.length; i++, j += 3) {\n int rgb = inPixels[i];\n inVert[j + 0] = (float) Math.pow(((rgb >>> 16) & 0xFF) / 255.0, 2.2);\n inVert[j + 1] = (float) Math.pow(((rgb >>> 8) & 0xFF) / 255.0, 2.2);\n inVert[j + 2] = (float) Math.pow(((rgb >>> 0) & 0xFF) / 255.0, 2.2);\n }\n inPixels = null;\n Thread[] thr = new Thread[threads];\n final AtomicInteger sharedY = new AtomicInteger(0);\n final float[] inHorz = new float[inWidth * outHeight * 3];\n final CyclicBarrier barrier = new CyclicBarrier(threads);\n final AtomicInteger sharedX = new AtomicInteger(0);\n final int[] outPixels = new int[outWidth * outHeight];\n for (int i = 0; i < thr.length; i++) {\n thr[i] = new Thread() {\n\n public void run() {\n // Resample vertically and transpose\n {\n double sincScale = Math.min((double) outHeight / inHeight, 1);\n double[] weights = new double[(int) verticalFilterLength + 1];\n float[] outVertRow = new float[inWidth * 3];\n while (true) {\n // For each output row\n int y = sharedY.getAndIncrement();\n if (y >= outHeight)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerY = (y + 0.5) / outHeight * inHeight;\n double filterStartY = centerY - verticalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartY - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputY = startIndex + i;\n double weight = windowedSinc((inputY + 0.5 - centerY) * sincScale, (inputY + 0.5 - filterStartY) / verticalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outVertRow, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputY = Math.min(Math.max(startIndex + i, 0), inHeight - 1);\n for (int x = 0; x < inWidth; x++) {\n // For each pixel in the row\n int j = (clippedInputY * inWidth + x) * 3;\n outVertRow[x * 3 + 0] += inVert[j + 0] * weight;\n outVertRow[x * 3 + 1] += inVert[j + 1] * weight;\n outVertRow[x * 3 + 2] += inVert[j + 2] * weight;\n }\n }\n for (int x = 0; x < inWidth; x++) {\n int j = (x * outHeight + y) * 3;\n inHorz[j + 0] = outVertRow[x * 3 + 0];\n inHorz[j + 1] = outVertRow[x * 3 + 1];\n inHorz[j + 2] = outVertRow[x * 3 + 2];\n }\n }\n }\n // Wait for all threads to finish the phase\n try {\n barrier.await();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n } catch (BrokenBarrierException e) {\n throw new RuntimeException(e);\n }\n // Resample horizontally and transpose\n {\n double sincScale = Math.min((double) outWidth / inWidth, 1);\n double[] weights = new double[(int) horizontalFilterLength + 1];\n double[] outHorzCol = new double[outHeight * 3];\n while (true) {\n // For each output column\n int x = sharedX.getAndIncrement();\n if (x >= outWidth)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerX = (x + 0.5) / outWidth * inWidth;\n double filterStartX = centerX - horizontalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartX - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputX = startIndex + i;\n double weight = windowedSinc((inputX + 0.5 - centerX) * sincScale, (inputX + 0.5 - filterStartX) / horizontalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outHorzCol, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputX = Math.min(Math.max(startIndex + i, 0), inWidth - 1);\n for (int y = 0; y < outHeight; y++) {\n // For each pixel in the column\n int j = (clippedInputX * outHeight + y) * 3;\n outHorzCol[y * 3 + 0] += inHorz[j + 0] * weight;\n outHorzCol[y * 3 + 1] += inHorz[j + 1] * weight;\n outHorzCol[y * 3 + 2] += inHorz[j + 2] * weight;\n }\n }\n for (int y = 0; y < outHeight; y++) {\n // Convert to 8 bits per channel and pack integers\n double r = outHorzCol[y * 3 + 0] * 255;\n if (r < 0)\n r = 0;\n if (r > 255)\n r = 255;\n double g = outHorzCol[y * 3 + 1] * 255;\n if (g < 0)\n g = 0;\n if (g > 255)\n g = 255;\n double b = outHorzCol[y * 3 + 2] * 255;\n if (b < 0)\n b = 0;\n if (b > 255)\n b = 255;\n outPixels[y * outWidth + x] = (int) (r + 0.5) << 16 | (int) (g + 0.5) << 8 | (int) (b + 0.5);\n }\n }\n }\n }\n };\n thr[i].start();\n }\n ", "post_mask_code": "\n outputImage = new BufferedImage(outWidth, outHeight, BufferedImage.TYPE_INT_RGB);\n outputImage.setRGB(0, 0, outWidth, outHeight, outPixels, 0, outWidth);\n }\n\n // x is measured in half-cycles; y is for the window which has the domain [0, 1]\n private static double windowedSinc(double x, double y) {\n x *= Math.PI;\n double sinc = x != 0 ? Math.sin(x) / x : 1;\n // Triangle window\n double window = 0 <= y && y <= 1 ? 1 - Math.abs(y - 0.5) * 2 : 0;\n return sinc * window;\n }\n }\n}\n"} {"task_id": "Java_597", "language": "Java", "task_type": "empty", "source_file": "java/github/nayuki/Nayuki-web-published-code/go-train-acceleration-analyzed-by-video/PreprocessFrames.java", "mask_start_position": 8461, "mask_end_position": 8461, "canonical_solution": "", "pre_mask_code": "/* \n * Preprocess frames\n * \n * All rights reserved. Contact Nayuki for licensing.\n * http://example.com\n */\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport javax.imageio.ImageIO;\n\npublic final class PreprocessFrames {\n\n // Configuration\n private static final int INPUT_FRAME_START = 990;\n\n private static final int INPUT_FRAME_END = 3900;\n\n private static final int INPUT_FRAME_DECIMATE = 3;\n\n private static final int IMAGE_WIDTH = 1280;\n\n private static final int IMAGE_HEIGHT = 192;\n\n private static final int IMAGE_UPSCALE = 4;\n\n public static void main(String[] args) throws IOException {\n // Get and check arguments\n if (args.length != 2) {\n System.err.println(\"Usage: java PreprocessFrames InDir OutDir\");\n System.exit(1);\n return;\n }\n File inDir = new File(args[0]);\n File outDir = new File(args[1]);\n if (!inDir.isDirectory())\n throw new RuntimeException(\"Invalid input directory\");\n if (!outDir.isDirectory())\n throw new RuntimeException(\"Invalid output directory\");\n // Process image frames\n for (int inFrame = INPUT_FRAME_START, outFrame = 0; inFrame < INPUT_FRAME_END; inFrame += INPUT_FRAME_DECIMATE, outFrame++) {\n File inFile = new File(inDir, String.format(\"%04d.bmp\", inFrame));\n File outFile = new File(outDir, String.format(\"%04d.bmp\", outFrame));\n FastSincImageResampler.resampleFile(inFile, IMAGE_WIDTH * IMAGE_UPSCALE, IMAGE_HEIGHT * IMAGE_UPSCALE, outFile);\n System.out.printf(\"%s --> %s%n\", inFile.getName(), outFile.getName());\n }\n }\n\n // Based on http://example.com\n private static final class FastSincImageResampler {\n\n /* Convenience methods */\n /**\n * Resamples the specified image file to the specified output dimensions, writing to the specified output file.\n * @param inFile the input image file (must be in BMP or PNG format)\n * @param outWidth the output image width (must be positive)\n * @param outHeight the output image height (must be positive)\n * @param outFile the output image file\n * @throws IOException if an I/O exception occurred in reading the input image file or writing the output image file\n */\n public static void resampleFile(File inFile, int outWidth, int outHeight, File outFile) throws IOException {\n FastSincImageResampler rs = new FastSincImageResampler();\n rs.inputFile = inFile;\n rs.outputWidth = outWidth;\n rs.outputHeight = outHeight;\n rs.outputFile = outFile;\n rs.run();\n }\n\n /* Full functionality */\n public File inputFile = null;\n\n public BufferedImage inputImage = null;\n\n // run() does not read this, but will overwrite this field\n public int inputWidth = -1;\n\n // run() does not read this, but will overwrite this field\n public int inputHeight = -1;\n\n // Must set to a positive number\n public int outputWidth = -1;\n\n // Must set to a positive number\n public int outputHeight = -1;\n\n // Horizontal filter length (set a positive value, otherwise an automatic default value will be computed)\n public double horizontalFilterLength = -1;\n\n // Vertical filter length (set a positive value, otherwise an automatic default value will be computed)\n public double verticalFilterLength = -1;\n\n // Number of threads to use (set a positive value, otherwise an automatic default value will be computed)\n public int threads = -1;\n\n // run() does not read this, but will overwrite this field\n public BufferedImage outputImage = null;\n\n public File outputFile = null;\n\n // Must be \"png\", \"bmp\", or null (auto-detection based on outputFile's extension)\n public String outputFileType = null;\n\n /**\n * Constructs a blank resampler object - certain fields must be set before calling {@code run()}.\n */\n public FastSincImageResampler() {\n }\n\n /**\n * Runs the resampler. The data flow operates on a \"waterfall\" model, reading and writing the fields from top to bottom:\n *
    \n *
  1. If {@code inputFile} is non-{@code null}, then it is read into {@code inputImage}.
  2. \n *
  3. {@code inputImage} needs to be non-{@code null} now (set explicitly or read from {@code inputFile}).
  4. \n *
  5. {@code inputImage} is read into {@code inputWidth} and {@code inputHeight}.
  6. \n *
  7. {@code outputWidth} and {@code outputHeight} must be positive (set explicitly).
  8. \n *
  9. If a filter length is zero or negative, then a default filter length is computed and set for that axis.
  10. \n *
  11. If {@code threads} is zero or negative, then a default number of threads is computed and set.
  12. \n *
  13. {@code outputImage} is computed by resampling {@code inputImage}. (This is the main purpose of the class.)
  14. \n *
  15. If {@code outputFile} is non-{@code null} and {@code outputFileType} is {@code null}: The type is set to {@code \"png\"} or {@code \"bmp\"}\n * if the output file has that extension (case-insensitive), otherwise it is set to {@code \"png\"} by default.
  16. \n *
  17. If {@code outputFile} is non-{@code null}, then {@code outputImage} is written to the file.
  18. \n *
\n *

After calling {@code run()}, it is recommend that this object should not be reused for another resampling operation.\n * This is because various fields probably need to be cleared, such as the filter length and output file type.

\n * @throws IOException if an I/O exception occurred\n * @throws IllegalStateException if there is no input image or the output dimensions are not set to positive values\n */\n public void run() throws IOException {\n // Read input file (optional)\n if (inputFile != null) {\n try {\n inputImage = ImageIO.read(inputFile);\n } catch (IOException e) {\n throw new IOException(\"Error reading input file (\" + inputFile + \"): \" + e.getMessage(), e);\n }\n }\n // Get input image dimensions\n if (inputImage == null)\n throw new IllegalStateException(\"No input image\");\n inputWidth = inputImage.getWidth();\n inputHeight = inputImage.getHeight();\n // Calculate filter lengths (optional)\n if (outputWidth <= 0 || outputHeight <= 0)\n throw new IllegalStateException(\"Output dimensions not set\");\n if (horizontalFilterLength <= 0)\n horizontalFilterLength = Math.max((double) inputWidth / outputWidth, 1) * 4.0;\n if (verticalFilterLength <= 0)\n verticalFilterLength = Math.max((double) inputHeight / outputHeight, 1) * 4.0;\n // Resample the image\n if (threads <= 0)\n threads = Runtime.getRuntime().availableProcessors();\n resampleImage();\n // Write output file (optional)\n if (outputFile != null) {\n if (outputFileType == null) {\n // Auto-detection by file extension\n String lowername = outputFile.getName().toLowerCase();\n if (lowername.endsWith(\".bmp\"))\n outputFileType = \"bmp\";\n else\n // Default\n outputFileType = \"png\";\n }\n try {\n ImageIO.write(outputImage, outputFileType, outputFile);\n } catch (IOException e) {\n throw new IOException(\"Error writing output file (\" + outputFile + \"): \" + e.getMessage(), e);\n }\n }\n }\n\n private void resampleImage() {\n final int inWidth = inputWidth;\n final int inHeight = inputHeight;\n final int outWidth = outputWidth;\n final int outHeight = outputHeight;\n ", "post_mask_code": " // Get packed int pixels\n int[] inPixels = new int[inWidth * inHeight];\n inputImage.getRGB(0, 0, inWidth, inHeight, inPixels, 0, inWidth);\n // Convert to float\n final float[] inVert = new float[inWidth * inHeight * 3];\n for (int i = 0, j = 0; i < inPixels.length; i++, j += 3) {\n int rgb = inPixels[i];\n inVert[j + 0] = (float) Math.pow(((rgb >>> 16) & 0xFF) / 255.0, 2.2);\n inVert[j + 1] = (float) Math.pow(((rgb >>> 8) & 0xFF) / 255.0, 2.2);\n inVert[j + 2] = (float) Math.pow(((rgb >>> 0) & 0xFF) / 255.0, 2.2);\n }\n inPixels = null;\n Thread[] thr = new Thread[threads];\n final AtomicInteger sharedY = new AtomicInteger(0);\n final float[] inHorz = new float[inWidth * outHeight * 3];\n final CyclicBarrier barrier = new CyclicBarrier(threads);\n final AtomicInteger sharedX = new AtomicInteger(0);\n final int[] outPixels = new int[outWidth * outHeight];\n for (int i = 0; i < thr.length; i++) {\n thr[i] = new Thread() {\n\n public void run() {\n // Resample vertically and transpose\n {\n double sincScale = Math.min((double) outHeight / inHeight, 1);\n double[] weights = new double[(int) verticalFilterLength + 1];\n float[] outVertRow = new float[inWidth * 3];\n while (true) {\n // For each output row\n int y = sharedY.getAndIncrement();\n if (y >= outHeight)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerY = (y + 0.5) / outHeight * inHeight;\n double filterStartY = centerY - verticalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartY - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputY = startIndex + i;\n double weight = windowedSinc((inputY + 0.5 - centerY) * sincScale, (inputY + 0.5 - filterStartY) / verticalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outVertRow, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputY = Math.min(Math.max(startIndex + i, 0), inHeight - 1);\n for (int x = 0; x < inWidth; x++) {\n // For each pixel in the row\n int j = (clippedInputY * inWidth + x) * 3;\n outVertRow[x * 3 + 0] += inVert[j + 0] * weight;\n outVertRow[x * 3 + 1] += inVert[j + 1] * weight;\n outVertRow[x * 3 + 2] += inVert[j + 2] * weight;\n }\n }\n for (int x = 0; x < inWidth; x++) {\n int j = (x * outHeight + y) * 3;\n inHorz[j + 0] = outVertRow[x * 3 + 0];\n inHorz[j + 1] = outVertRow[x * 3 + 1];\n inHorz[j + 2] = outVertRow[x * 3 + 2];\n }\n }\n }\n // Wait for all threads to finish the phase\n try {\n barrier.await();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n } catch (BrokenBarrierException e) {\n throw new RuntimeException(e);\n }\n // Resample horizontally and transpose\n {\n double sincScale = Math.min((double) outWidth / inWidth, 1);\n double[] weights = new double[(int) horizontalFilterLength + 1];\n double[] outHorzCol = new double[outHeight * 3];\n while (true) {\n // For each output column\n int x = sharedX.getAndIncrement();\n if (x >= outWidth)\n break;\n double weightSum = 0;\n // In input image coordinates\n double centerX = (x + 0.5) / outWidth * inWidth;\n double filterStartX = centerX - horizontalFilterLength / 2;\n int startIndex = (int) Math.ceil(filterStartX - 0.5);\n for (int i = 0; i < weights.length; i++) {\n int inputX = startIndex + i;\n double weight = windowedSinc((inputX + 0.5 - centerX) * sincScale, (inputX + 0.5 - filterStartX) / horizontalFilterLength);\n weights[i] = weight;\n weightSum += weight;\n }\n Arrays.fill(outHorzCol, 0);\n for (int i = 0; i < weights.length; i++) {\n double weight = weights[i] / weightSum;\n int clippedInputX = Math.min(Math.max(startIndex + i, 0), inWidth - 1);\n for (int y = 0; y < outHeight; y++) {\n // For each pixel in the column\n int j = (clippedInputX * outHeight + y) * 3;\n outHorzCol[y * 3 + 0] += inHorz[j + 0] * weight;\n outHorzCol[y * 3 + 1] += inHorz[j + 1] * weight;\n outHorzCol[y * 3 + 2] += inHorz[j + 2] * weight;\n }\n }\n for (int y = 0; y < outHeight; y++) {\n // Convert to 8 bits per channel and pack integers\n double r = outHorzCol[y * 3 + 0] * 255;\n if (r < 0)\n r = 0;\n if (r > 255)\n r = 255;\n double g = outHorzCol[y * 3 + 1] * 255;\n if (g < 0)\n g = 0;\n if (g > 255)\n g = 255;\n double b = outHorzCol[y * 3 + 2] * 255;\n if (b < 0)\n b = 0;\n if (b > 255)\n b = 255;\n outPixels[y * outWidth + x] = (int) (r + 0.5) << 16 | (int) (g + 0.5) << 8 | (int) (b + 0.5);\n }\n }\n }\n }\n };\n thr[i].start();\n }\n try {\n for (Thread th : thr) th.join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n outputImage = new BufferedImage(outWidth, outHeight, BufferedImage.TYPE_INT_RGB);\n outputImage.setRGB(0, 0, outWidth, outHeight, outPixels, 0, outWidth);\n }\n\n // x is measured in half-cycles; y is for the window which has the domain [0, 1]\n private static double windowedSinc(double x, double y) {\n x *= Math.PI;\n double sinc = x != 0 ? Math.sin(x) / x : 1;\n // Triangle window\n double window = 0 <= y && y <= 1 ? 1 - Math.abs(y - 0.5) * 2 : 0;\n return sinc * window;\n }\n }\n}\n"} {"task_id": "Java_598", "language": "Java", "task_type": "method_signature", "source_file": "java/github/mc1arke/sonarqube-community-branch-plugin/src/main/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/github/GithubPullRequestDecorator.java", "mask_start_position": 1369, "mask_end_position": 1406, "canonical_solution": "@Override\n public List alm() ", "pre_mask_code": "package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.github;\n\nimport com.github.mc1arke.sonarqube.plugin.almclient.github.GithubClientFactory;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.AnalysisDetails;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.DecorationResult;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.PullRequestBuildStatusDecorator;\nimport org.sonar.db.alm.setting.ALM;\nimport org.sonar.db.alm.setting.AlmSettingDto;\nimport org.sonar.db.alm.setting.ProjectAlmSettingDto;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class GithubPullRequestDecorator implements PullRequestBuildStatusDecorator {\n\n private final GithubClientFactory githubClientFactory;\n\n public GithubPullRequestDecorator(GithubClientFactory githubClientFactory) {\n this.githubClientFactory = githubClientFactory;\n }\n\n @Override\n public DecorationResult decorateQualityGateStatus(AnalysisDetails analysisDetails, AlmSettingDto almSettingDto, ProjectAlmSettingDto projectAlmSettingDto) {\n try {\n return githubClientFactory.createClient(projectAlmSettingDto, almSettingDto).createCheckRun(analysisDetails, almSettingDto, projectAlmSettingDto);\n } catch (Exception ex) {\n throw new IllegalStateException(\"Could not decorate Pull Request on Github\", ex);\n }\n }\n\n ", "post_mask_code": "{\n return Collections.singletonList(ALM.GITHUB);\n }\n}\n"} {"task_id": "Java_599", "language": "Java", "task_type": "method_body", "source_file": "java/github/mc1arke/sonarqube-community-branch-plugin/src/main/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/github/GithubPullRequestDecorator.java", "mask_start_position": 1406, "mask_end_position": 1467, "canonical_solution": "{\n return Collections.singletonList(ALM.GITHUB);\n }", "pre_mask_code": "package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.github;\n\nimport com.github.mc1arke.sonarqube.plugin.almclient.github.GithubClientFactory;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.AnalysisDetails;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.DecorationResult;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.PullRequestBuildStatusDecorator;\nimport org.sonar.db.alm.setting.ALM;\nimport org.sonar.db.alm.setting.AlmSettingDto;\nimport org.sonar.db.alm.setting.ProjectAlmSettingDto;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class GithubPullRequestDecorator implements PullRequestBuildStatusDecorator {\n\n private final GithubClientFactory githubClientFactory;\n\n public GithubPullRequestDecorator(GithubClientFactory githubClientFactory) {\n this.githubClientFactory = githubClientFactory;\n }\n\n @Override\n public DecorationResult decorateQualityGateStatus(AnalysisDetails analysisDetails, AlmSettingDto almSettingDto, ProjectAlmSettingDto projectAlmSettingDto) {\n try {\n return githubClientFactory.createClient(projectAlmSettingDto, almSettingDto).createCheckRun(analysisDetails, almSettingDto, projectAlmSettingDto);\n } catch (Exception ex) {\n throw new IllegalStateException(\"Could not decorate Pull Request on Github\", ex);\n }\n }\n\n @Override\n public List alm() ", "post_mask_code": "\n}\n"} {"task_id": "Java_600", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/mc1arke/sonarqube-community-branch-plugin/src/main/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/github/GithubPullRequestDecorator.java", "mask_start_position": 1047, "mask_end_position": 1047, "canonical_solution": "", "pre_mask_code": "package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.github;\n\nimport com.github.mc1arke.sonarqube.plugin.almclient.github.GithubClientFactory;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.AnalysisDetails;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.DecorationResult;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.PullRequestBuildStatusDecorator;\nimport org.sonar.db.alm.setting.ALM;\nimport org.sonar.db.alm.setting.AlmSettingDto;\nimport org.sonar.db.alm.setting.ProjectAlmSettingDto;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class GithubPullRequestDecorator implements PullRequestBuildStatusDecorator {\n\n private final GithubClientFactory githubClientFactory;\n\n public GithubPullRequestDecorator(GithubClientFactory githubClientFactory) {\n this.githubClientFactory = githubClientFactory;\n }\n\n @Override\n public DecorationResult decorateQualityGateStatus(AnalysisDetails analysisDetails, AlmSettingDto almSettingDto, ProjectAlmSettingDto projectAlmSettingDto) {", "post_mask_code": "\n try {\n return githubClientFactory.createClient(projectAlmSettingDto, almSettingDto).createCheckRun(analysisDetails, almSettingDto, projectAlmSettingDto);\n } catch (Exception ex) {\n throw new IllegalStateException(\"Could not decorate Pull Request on Github\", ex);\n }\n }\n\n @Override\n public List alm() {\n return Collections.singletonList(ALM.GITHUB);\n }\n}\n"} {"task_id": "Java_601", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/mc1arke/sonarqube-community-branch-plugin/src/main/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/github/GithubPullRequestDecorator.java", "mask_start_position": 1056, "mask_end_position": 1357, "canonical_solution": "try {\n return githubClientFactory.createClient(projectAlmSettingDto, almSettingDto).createCheckRun(analysisDetails, almSettingDto, projectAlmSettingDto);\n } catch (Exception ex) {\n throw new IllegalStateException(\"Could not decorate Pull Request on Github\", ex);\n }", "pre_mask_code": "package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.github;\n\nimport com.github.mc1arke.sonarqube.plugin.almclient.github.GithubClientFactory;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.AnalysisDetails;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.DecorationResult;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.PullRequestBuildStatusDecorator;\nimport org.sonar.db.alm.setting.ALM;\nimport org.sonar.db.alm.setting.AlmSettingDto;\nimport org.sonar.db.alm.setting.ProjectAlmSettingDto;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class GithubPullRequestDecorator implements PullRequestBuildStatusDecorator {\n\n private final GithubClientFactory githubClientFactory;\n\n public GithubPullRequestDecorator(GithubClientFactory githubClientFactory) {\n this.githubClientFactory = githubClientFactory;\n }\n\n @Override\n public DecorationResult decorateQualityGateStatus(AnalysisDetails analysisDetails, AlmSettingDto almSettingDto, ProjectAlmSettingDto projectAlmSettingDto) {\n ", "post_mask_code": "\n }\n\n @Override\n public List alm() {\n return Collections.singletonList(ALM.GITHUB);\n }\n}\n"} {"task_id": "Java_602", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/mc1arke/sonarqube-community-branch-plugin/src/main/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/github/GithubPullRequestDecorator.java", "mask_start_position": 1362, "mask_end_position": 1363, "canonical_solution": "}", "pre_mask_code": "package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.github;\n\nimport com.github.mc1arke.sonarqube.plugin.almclient.github.GithubClientFactory;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.AnalysisDetails;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.DecorationResult;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.PullRequestBuildStatusDecorator;\nimport org.sonar.db.alm.setting.ALM;\nimport org.sonar.db.alm.setting.AlmSettingDto;\nimport org.sonar.db.alm.setting.ProjectAlmSettingDto;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class GithubPullRequestDecorator implements PullRequestBuildStatusDecorator {\n\n private final GithubClientFactory githubClientFactory;\n\n public GithubPullRequestDecorator(GithubClientFactory githubClientFactory) {\n this.githubClientFactory = githubClientFactory;\n }\n\n @Override\n public DecorationResult decorateQualityGateStatus(AnalysisDetails analysisDetails, AlmSettingDto almSettingDto, ProjectAlmSettingDto projectAlmSettingDto) {\n try {\n return githubClientFactory.createClient(projectAlmSettingDto, almSettingDto).createCheckRun(analysisDetails, almSettingDto, projectAlmSettingDto);\n } catch (Exception ex) {\n throw new IllegalStateException(\"Could not decorate Pull Request on Github\", ex);\n }\n ", "post_mask_code": "\n\n @Override\n public List alm() {\n return Collections.singletonList(ALM.GITHUB);\n }\n}\n"} {"task_id": "Java_603", "language": "Java", "task_type": "single_line", "source_file": "java/github/mc1arke/sonarqube-community-branch-plugin/src/main/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/github/GithubPullRequestDecorator.java", "mask_start_position": 1416, "mask_end_position": 1461, "canonical_solution": "return Collections.singletonList(ALM.GITHUB);", "pre_mask_code": "package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.github;\n\nimport com.github.mc1arke.sonarqube.plugin.almclient.github.GithubClientFactory;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.AnalysisDetails;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.DecorationResult;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.PullRequestBuildStatusDecorator;\nimport org.sonar.db.alm.setting.ALM;\nimport org.sonar.db.alm.setting.AlmSettingDto;\nimport org.sonar.db.alm.setting.ProjectAlmSettingDto;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class GithubPullRequestDecorator implements PullRequestBuildStatusDecorator {\n\n private final GithubClientFactory githubClientFactory;\n\n public GithubPullRequestDecorator(GithubClientFactory githubClientFactory) {\n this.githubClientFactory = githubClientFactory;\n }\n\n @Override\n public DecorationResult decorateQualityGateStatus(AnalysisDetails analysisDetails, AlmSettingDto almSettingDto, ProjectAlmSettingDto projectAlmSettingDto) {\n try {\n return githubClientFactory.createClient(projectAlmSettingDto, almSettingDto).createCheckRun(analysisDetails, almSettingDto, projectAlmSettingDto);\n } catch (Exception ex) {\n throw new IllegalStateException(\"Could not decorate Pull Request on Github\", ex);\n }\n }\n\n @Override\n public List alm() {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_604", "language": "Java", "task_type": "try_statement", "source_file": "java/github/mc1arke/sonarqube-community-branch-plugin/src/main/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/github/GithubPullRequestDecorator.java", "mask_start_position": 1056, "mask_end_position": 1357, "canonical_solution": "try {\n return githubClientFactory.createClient(projectAlmSettingDto, almSettingDto).createCheckRun(analysisDetails, almSettingDto, projectAlmSettingDto);\n } catch (Exception ex) {\n throw new IllegalStateException(\"Could not decorate Pull Request on Github\", ex);\n }", "pre_mask_code": "package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.github;\n\nimport com.github.mc1arke.sonarqube.plugin.almclient.github.GithubClientFactory;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.AnalysisDetails;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.DecorationResult;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.PullRequestBuildStatusDecorator;\nimport org.sonar.db.alm.setting.ALM;\nimport org.sonar.db.alm.setting.AlmSettingDto;\nimport org.sonar.db.alm.setting.ProjectAlmSettingDto;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class GithubPullRequestDecorator implements PullRequestBuildStatusDecorator {\n\n private final GithubClientFactory githubClientFactory;\n\n public GithubPullRequestDecorator(GithubClientFactory githubClientFactory) {\n this.githubClientFactory = githubClientFactory;\n }\n\n @Override\n public DecorationResult decorateQualityGateStatus(AnalysisDetails analysisDetails, AlmSettingDto almSettingDto, ProjectAlmSettingDto projectAlmSettingDto) {\n ", "post_mask_code": "\n }\n\n @Override\n public List alm() {\n return Collections.singletonList(ALM.GITHUB);\n }\n}\n"} {"task_id": "Java_605", "language": "Java", "task_type": "empty", "source_file": "java/github/mc1arke/sonarqube-community-branch-plugin/src/main/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/github/GithubPullRequestDecorator.java", "mask_start_position": 740, "mask_end_position": 740, "canonical_solution": "", "pre_mask_code": "package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.github;\n\nimport com.github.mc1arke.sonarqube.plugin.almclient.github.GithubClientFactory;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.AnalysisDetails;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.DecorationResult;\nimport com.github.mc1arke.sonarqube.plugin.ce.pullrequest.PullRequestBuildStatusDecorator;\nimport org.sonar.db.alm.setting.ALM;\nimport org.sonar.db.alm.setting.AlmSettingDto;\nimport org.sonar.db.alm.setting.ProjectAlmSettingDto;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class GithubPullRequestDecorator implements PullRequestBuildStatusDecorator {\n\n private final GithubClientFactory githubClientFactory;\n\n public ", "post_mask_code": "GithubPullRequestDecorator(GithubClientFactory githubClientFactory) {\n this.githubClientFactory = githubClientFactory;\n }\n\n @Override\n public DecorationResult decorateQualityGateStatus(AnalysisDetails analysisDetails, AlmSettingDto almSettingDto, ProjectAlmSettingDto projectAlmSettingDto) {\n try {\n return githubClientFactory.createClient(projectAlmSettingDto, almSettingDto).createCheckRun(analysisDetails, almSettingDto, projectAlmSettingDto);\n } catch (Exception ex) {\n throw new IllegalStateException(\"Could not decorate Pull Request on Github\", ex);\n }\n }\n\n @Override\n public List alm() {\n return Collections.singletonList(ALM.GITHUB);\n }\n}\n"} {"task_id": "Java_606", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cBioPortal/cbioportal/web/src/main/java/org/cbioportal/web/parameter/ClinicalDataMultiStudyFilter.java", "mask_start_position": 543, "mask_end_position": 596, "canonical_solution": "public List getIdentifiers() ", "pre_mask_code": "package org.cbioportal.web.parameter;\n\nimport org.cbioportal.web.ClinicalDataController;\nimport javax.validation.constraints.Size;\nimport java.util.List;\nimport java.io.Serializable;\nimport static org.cbioportal.web.parameter.PagingConstants.MAX_PAGE_SIZE;\n\npublic class ClinicalDataMultiStudyFilter implements Serializable {\n\n @Size(min = 1, max = ClinicalDataController.CLINICAL_DATA_MAX_PAGE_SIZE)\n private List identifiers;\n\n @Size(min = 1, max = MAX_PAGE_SIZE)\n private List attributeIds;\n\n ", "post_mask_code": "{\n return identifiers;\n }\n\n public void setIdentifiers(List identifiers) {\n this.identifiers = identifiers;\n }\n\n public List getAttributeIds() {\n return attributeIds;\n }\n\n public void setAttributeIds(List attributeIds) {\n this.attributeIds = attributeIds;\n }\n}\n"} {"task_id": "Java_607", "language": "Java", "task_type": "method_body", "source_file": "java/github/cBioPortal/cbioportal/web/src/main/java/org/cbioportal/web/parameter/ClinicalDataMultiStudyFilter.java", "mask_start_position": 797, "mask_end_position": 833, "canonical_solution": "{\n return attributeIds;\n }", "pre_mask_code": "package org.cbioportal.web.parameter;\n\nimport org.cbioportal.web.ClinicalDataController;\nimport javax.validation.constraints.Size;\nimport java.util.List;\nimport java.io.Serializable;\nimport static org.cbioportal.web.parameter.PagingConstants.MAX_PAGE_SIZE;\n\npublic class ClinicalDataMultiStudyFilter implements Serializable {\n\n @Size(min = 1, max = ClinicalDataController.CLINICAL_DATA_MAX_PAGE_SIZE)\n private List identifiers;\n\n @Size(min = 1, max = MAX_PAGE_SIZE)\n private List attributeIds;\n\n public List getIdentifiers() {\n return identifiers;\n }\n\n public void setIdentifiers(List identifiers) {\n this.identifiers = identifiers;\n }\n\n public List getAttributeIds() ", "post_mask_code": "\n\n public void setAttributeIds(List attributeIds) {\n this.attributeIds = attributeIds;\n }\n}\n"} {"task_id": "Java_608", "language": "Java", "task_type": "single_line", "source_file": "java/github/cBioPortal/cbioportal/web/src/main/java/org/cbioportal/web/parameter/ClinicalDataMultiStudyFilter.java", "mask_start_position": 619, "mask_end_position": 625, "canonical_solution": "fiers;", "pre_mask_code": "package org.cbioportal.web.parameter;\n\nimport org.cbioportal.web.ClinicalDataController;\nimport javax.validation.constraints.Size;\nimport java.util.List;\nimport java.io.Serializable;\nimport static org.cbioportal.web.parameter.PagingConstants.MAX_PAGE_SIZE;\n\npublic class ClinicalDataMultiStudyFilter implements Serializable {\n\n @Size(min = 1, max = ClinicalDataController.CLINICAL_DATA_MAX_PAGE_SIZE)\n private List identifiers;\n\n @Size(min = 1, max = MAX_PAGE_SIZE)\n private List attributeIds;\n\n public List getIdentifiers() {\n return identi", "post_mask_code": "\n }\n\n public void setIdentifiers(List identifiers) {\n this.identifiers = identifiers;\n }\n\n public List getAttributeIds() {\n return attributeIds;\n }\n\n public void setAttributeIds(List attributeIds) {\n this.attributeIds = attributeIds;\n }\n}\n"} {"task_id": "Java_609", "language": "Java", "task_type": "empty", "source_file": "java/github/cBioPortal/cbioportal/web/src/main/java/org/cbioportal/web/parameter/ClinicalDataMultiStudyFilter.java", "mask_start_position": 14, "mask_end_position": 14, "canonical_solution": "", "pre_mask_code": "package org.cb", "post_mask_code": "ioportal.web.parameter;\n\nimport org.cbioportal.web.ClinicalDataController;\nimport javax.validation.constraints.Size;\nimport java.util.List;\nimport java.io.Serializable;\nimport static org.cbioportal.web.parameter.PagingConstants.MAX_PAGE_SIZE;\n\npublic class ClinicalDataMultiStudyFilter implements Serializable {\n\n @Size(min = 1, max = ClinicalDataController.CLINICAL_DATA_MAX_PAGE_SIZE)\n private List identifiers;\n\n @Size(min = 1, max = MAX_PAGE_SIZE)\n private List attributeIds;\n\n public List getIdentifiers() {\n return identifiers;\n }\n\n public void setIdentifiers(List identifiers) {\n this.identifiers = identifiers;\n }\n\n public List getAttributeIds() {\n return attributeIds;\n }\n\n public void setAttributeIds(List attributeIds) {\n this.attributeIds = attributeIds;\n }\n}\n"} {"task_id": "Java_610", "language": "Java", "task_type": "method_signature", "source_file": "java/github/peholmst/DDDExample/shared-kernel/src/main/java/net/pkhapps/ddd/shared/domain/geo/PostalCode.java", "mask_start_position": 872, "mask_end_position": 908, "canonical_solution": "@Override\n public int hashCode() ", "pre_mask_code": "package net.pkhapps.ddd.shared.domain.geo;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonValue;\nimport net.pkhapps.ddd.shared.domain.base.ValueObject;\nimport org.springframework.lang.NonNull;\nimport java.util.Objects;\n\n/**\n * Value object representing a postal code.\n */\npublic class PostalCode implements ValueObject {\n\n private final String postalCode;\n\n @JsonCreator\n public PostalCode(@NonNull String postalCode) {\n this.postalCode = Objects.requireNonNull(postalCode, \"postalCode must not be null\");\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n PostalCode that = (PostalCode) o;\n return Objects.equals(postalCode, that.postalCode);\n }\n\n ", "post_mask_code": "{\n return Objects.hash(postalCode);\n }\n\n @Override\n @JsonValue\n public String toString() {\n return postalCode;\n }\n}\n"} {"task_id": "Java_611", "language": "Java", "task_type": "method_body", "source_file": "java/github/peholmst/DDDExample/shared-kernel/src/main/java/net/pkhapps/ddd/shared/domain/geo/PostalCode.java", "mask_start_position": 630, "mask_end_position": 866, "canonical_solution": "{\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n PostalCode that = (PostalCode) o;\n return Objects.equals(postalCode, that.postalCode);\n }", "pre_mask_code": "package net.pkhapps.ddd.shared.domain.geo;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonValue;\nimport net.pkhapps.ddd.shared.domain.base.ValueObject;\nimport org.springframework.lang.NonNull;\nimport java.util.Objects;\n\n/**\n * Value object representing a postal code.\n */\npublic class PostalCode implements ValueObject {\n\n private final String postalCode;\n\n @JsonCreator\n public PostalCode(@NonNull String postalCode) {\n this.postalCode = Objects.requireNonNull(postalCode, \"postalCode must not be null\");\n }\n\n @Override\n public boolean equals(Object o) ", "post_mask_code": "\n\n @Override\n public int hashCode() {\n return Objects.hash(postalCode);\n }\n\n @Override\n @JsonValue\n public String toString() {\n return postalCode;\n }\n}\n"} {"task_id": "Java_612", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/peholmst/DDDExample/shared-kernel/src/main/java/net/pkhapps/ddd/shared/domain/geo/PostalCode.java", "mask_start_position": 631, "mask_end_position": 679, "canonical_solution": "\n if (this == o)\n return true;", "pre_mask_code": "package net.pkhapps.ddd.shared.domain.geo;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonValue;\nimport net.pkhapps.ddd.shared.domain.base.ValueObject;\nimport org.springframework.lang.NonNull;\nimport java.util.Objects;\n\n/**\n * Value object representing a postal code.\n */\npublic class PostalCode implements ValueObject {\n\n private final String postalCode;\n\n @JsonCreator\n public PostalCode(@NonNull String postalCode) {\n this.postalCode = Objects.requireNonNull(postalCode, \"postalCode must not be null\");\n }\n\n @Override\n public boolean equals(Object o) {", "post_mask_code": "\n if (o == null || getClass() != o.getClass())\n return false;\n PostalCode that = (PostalCode) o;\n return Objects.equals(postalCode, that.postalCode);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(postalCode);\n }\n\n @Override\n @JsonValue\n public String toString() {\n return postalCode;\n }\n}\n"} {"task_id": "Java_613", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/peholmst/DDDExample/shared-kernel/src/main/java/net/pkhapps/ddd/shared/domain/geo/PostalCode.java", "mask_start_position": 688, "mask_end_position": 800, "canonical_solution": "if (o == null || getClass() != o.getClass())\n return false;\n PostalCode that = (PostalCode) o;", "pre_mask_code": "package net.pkhapps.ddd.shared.domain.geo;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonValue;\nimport net.pkhapps.ddd.shared.domain.base.ValueObject;\nimport org.springframework.lang.NonNull;\nimport java.util.Objects;\n\n/**\n * Value object representing a postal code.\n */\npublic class PostalCode implements ValueObject {\n\n private final String postalCode;\n\n @JsonCreator\n public PostalCode(@NonNull String postalCode) {\n this.postalCode = Objects.requireNonNull(postalCode, \"postalCode must not be null\");\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n ", "post_mask_code": "\n return Objects.equals(postalCode, that.postalCode);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(postalCode);\n }\n\n @Override\n @JsonValue\n public String toString() {\n return postalCode;\n }\n}\n"} {"task_id": "Java_614", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/peholmst/DDDExample/shared-kernel/src/main/java/net/pkhapps/ddd/shared/domain/geo/PostalCode.java", "mask_start_position": 809, "mask_end_position": 866, "canonical_solution": "return Objects.equals(postalCode, that.postalCode);\n }", "pre_mask_code": "package net.pkhapps.ddd.shared.domain.geo;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonValue;\nimport net.pkhapps.ddd.shared.domain.base.ValueObject;\nimport org.springframework.lang.NonNull;\nimport java.util.Objects;\n\n/**\n * Value object representing a postal code.\n */\npublic class PostalCode implements ValueObject {\n\n private final String postalCode;\n\n @JsonCreator\n public PostalCode(@NonNull String postalCode) {\n this.postalCode = Objects.requireNonNull(postalCode, \"postalCode must not be null\");\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n PostalCode that = (PostalCode) o;\n ", "post_mask_code": "\n\n @Override\n public int hashCode() {\n return Objects.hash(postalCode);\n }\n\n @Override\n @JsonValue\n public String toString() {\n return postalCode;\n }\n}\n"} {"task_id": "Java_615", "language": "Java", "task_type": "single_line", "source_file": "java/github/peholmst/DDDExample/shared-kernel/src/main/java/net/pkhapps/ddd/shared/domain/geo/PostalCode.java", "mask_start_position": 931, "mask_end_position": 950, "canonical_solution": "s.hash(postalCode);", "pre_mask_code": "package net.pkhapps.ddd.shared.domain.geo;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonValue;\nimport net.pkhapps.ddd.shared.domain.base.ValueObject;\nimport org.springframework.lang.NonNull;\nimport java.util.Objects;\n\n/**\n * Value object representing a postal code.\n */\npublic class PostalCode implements ValueObject {\n\n private final String postalCode;\n\n @JsonCreator\n public PostalCode(@NonNull String postalCode) {\n this.postalCode = Objects.requireNonNull(postalCode, \"postalCode must not be null\");\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n PostalCode that = (PostalCode) o;\n return Objects.equals(postalCode, that.postalCode);\n }\n\n @Override\n public int hashCode() {\n return Object", "post_mask_code": "\n }\n\n @Override\n @JsonValue\n public String toString() {\n return postalCode;\n }\n}\n"} {"task_id": "Java_616", "language": "Java", "task_type": "if_statement", "source_file": "java/github/peholmst/DDDExample/shared-kernel/src/main/java/net/pkhapps/ddd/shared/domain/geo/PostalCode.java", "mask_start_position": 640, "mask_end_position": 679, "canonical_solution": "if (this == o)\n return true;", "pre_mask_code": "package net.pkhapps.ddd.shared.domain.geo;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonValue;\nimport net.pkhapps.ddd.shared.domain.base.ValueObject;\nimport org.springframework.lang.NonNull;\nimport java.util.Objects;\n\n/**\n * Value object representing a postal code.\n */\npublic class PostalCode implements ValueObject {\n\n private final String postalCode;\n\n @JsonCreator\n public PostalCode(@NonNull String postalCode) {\n this.postalCode = Objects.requireNonNull(postalCode, \"postalCode must not be null\");\n }\n\n @Override\n public boolean equals(Object o) {\n ", "post_mask_code": "\n if (o == null || getClass() != o.getClass())\n return false;\n PostalCode that = (PostalCode) o;\n return Objects.equals(postalCode, that.postalCode);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(postalCode);\n }\n\n @Override\n @JsonValue\n public String toString() {\n return postalCode;\n }\n}\n"} {"task_id": "Java_617", "language": "Java", "task_type": "empty", "source_file": "java/github/peholmst/DDDExample/shared-kernel/src/main/java/net/pkhapps/ddd/shared/domain/geo/PostalCode.java", "mask_start_position": 392, "mask_end_position": 392, "canonical_solution": "", "pre_mask_code": "package net.pkhapps.ddd.shared.domain.geo;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonValue;\nimport net.pkhapps.ddd.shared.domain.base.ValueObject;\nimport org.springframework.lang.NonNull;\nimport java.util.Objects;\n\n/**\n * Value object representing a postal code.\n */\npublic class PostalCode implements ValueObject {\n\n private final S", "post_mask_code": "tring postalCode;\n\n @JsonCreator\n public PostalCode(@NonNull String postalCode) {\n this.postalCode = Objects.requireNonNull(postalCode, \"postalCode must not be null\");\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n PostalCode that = (PostalCode) o;\n return Objects.equals(postalCode, that.postalCode);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(postalCode);\n }\n\n @Override\n @JsonValue\n public String toString() {\n return postalCode;\n }\n}\n"} {"task_id": "Java_618", "language": "Java", "task_type": "method_signature", "source_file": "java/github/CameloeAnthony/Ant/ThirdPart/VideoListPlayer/src/main/java/com/anthony/videolistplayer/media/InfoHudViewHolder.java", "mask_start_position": 1634, "mask_end_position": 1693, "canonical_solution": "private static String formatedDurationMilli(long duration) ", "pre_mask_code": "package com.anthony.videolistplayer.media;\n\nimport android.content.Context;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.widget.TableLayout;\nimport com.anthony.videolistplayer.R;\nimport java.util.Locale;\nimport tv.danmaku.ijk.media.player.IMediaPlayer;\nimport tv.danmaku.ijk.media.player.IjkMediaPlayer;\nimport tv.danmaku.ijk.media.player.MediaPlayerProxy;\n\npublic class InfoHudViewHolder {\n\n private TableLayoutBinder mTableLayoutBinder;\n\n private SparseArray mRowMap = new SparseArray();\n\n private IMediaPlayer mMediaPlayer;\n\n public InfoHudViewHolder(Context context, TableLayout tableLayout) {\n mTableLayoutBinder = new TableLayoutBinder(context, tableLayout);\n }\n\n private void appendSection(int nameId) {\n mTableLayoutBinder.appendSection(nameId);\n }\n\n private void appendRow(int nameId) {\n View rowView = mTableLayoutBinder.appendRow2(nameId, null);\n mRowMap.put(nameId, rowView);\n }\n\n private void setRowValue(int id, String value) {\n View rowView = mRowMap.get(id);\n if (rowView == null) {\n rowView = mTableLayoutBinder.appendRow2(id, value);\n mRowMap.put(id, rowView);\n } else {\n mTableLayoutBinder.setValueText(rowView, value);\n }\n }\n\n public void setMediaPlayer(IMediaPlayer mp) {\n mMediaPlayer = mp;\n if (mMediaPlayer != null) {\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n } else {\n mHandler.removeMessages(MSG_UPDATE_HUD);\n }\n }\n\n ", "post_mask_code": "{\n if (duration >= 1000) {\n return String.format(Locale.US, \"%.2f sec\", ((float) duration) / 1000);\n } else {\n return String.format(Locale.US, \"%d msec\", duration);\n }\n }\n\n private static String formatedSize(long bytes) {\n if (bytes >= 100 * 1000) {\n return String.format(Locale.US, \"%.2f MB\", ((float) bytes) / 1000 / 1000);\n } else if (bytes >= 100) {\n return String.format(Locale.US, \"%.1f KB\", ((float) bytes) / 1000);\n } else {\n return String.format(Locale.US, \"%d B\", bytes);\n }\n }\n\n private static final int MSG_UPDATE_HUD = 1;\n\n private Handler mHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n switch(msg.what) {\n case MSG_UPDATE_HUD:\n {\n InfoHudViewHolder holder = InfoHudViewHolder.this;\n IjkMediaPlayer mp = null;\n if (mMediaPlayer == null)\n break;\n if (mMediaPlayer instanceof IjkMediaPlayer) {\n mp = (IjkMediaPlayer) mMediaPlayer;\n } else if (mMediaPlayer instanceof MediaPlayerProxy) {\n MediaPlayerProxy proxy = (MediaPlayerProxy) mMediaPlayer;\n IMediaPlayer internal = proxy.getInternalMediaPlayer();\n if (internal != null && internal instanceof IjkMediaPlayer)\n mp = (IjkMediaPlayer) internal;\n }\n if (mp == null)\n break;\n int vdec = mp.getVideoDecoder();\n switch(vdec) {\n case IjkMediaPlayer.FFP_PROPV_DECODER_AVCODEC:\n setRowValue(R.string.vdec, \"avcodec\");\n break;\n case IjkMediaPlayer.FFP_PROPV_DECODER_MEDIACODEC:\n setRowValue(R.string.vdec, \"MediaCodec\");\n break;\n default:\n setRowValue(R.string.vdec, \"\");\n break;\n }\n float fpsOutput = mp.getVideoOutputFramesPerSecond();\n float fpsDecode = mp.getVideoDecodeFramesPerSecond();\n setRowValue(R.string.fps, String.format(Locale.US, \"%.2f / %.2f\", fpsDecode, fpsOutput));\n long videoCachedDuration = mp.getVideoCachedDuration();\n long audioCachedDuration = mp.getAudioCachedDuration();\n long videoCachedBytes = mp.getVideoCachedBytes();\n long audioCachedBytes = mp.getAudioCachedBytes();\n setRowValue(R.string.v_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(videoCachedDuration), formatedSize(videoCachedBytes)));\n setRowValue(R.string.a_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(audioCachedDuration), formatedSize(audioCachedBytes)));\n mHandler.removeMessages(MSG_UPDATE_HUD);\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n }\n }\n }\n };\n}\n"} {"task_id": "Java_619", "language": "Java", "task_type": "method_body", "source_file": "java/github/CameloeAnthony/Ant/ThirdPart/VideoListPlayer/src/main/java/com/anthony/videolistplayer/media/InfoHudViewHolder.java", "mask_start_position": 1411, "mask_end_position": 1628, "canonical_solution": "{\n mMediaPlayer = mp;\n if (mMediaPlayer != null) {\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n } else {\n mHandler.removeMessages(MSG_UPDATE_HUD);\n }\n }", "pre_mask_code": "package com.anthony.videolistplayer.media;\n\nimport android.content.Context;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.widget.TableLayout;\nimport com.anthony.videolistplayer.R;\nimport java.util.Locale;\nimport tv.danmaku.ijk.media.player.IMediaPlayer;\nimport tv.danmaku.ijk.media.player.IjkMediaPlayer;\nimport tv.danmaku.ijk.media.player.MediaPlayerProxy;\n\npublic class InfoHudViewHolder {\n\n private TableLayoutBinder mTableLayoutBinder;\n\n private SparseArray mRowMap = new SparseArray();\n\n private IMediaPlayer mMediaPlayer;\n\n public InfoHudViewHolder(Context context, TableLayout tableLayout) {\n mTableLayoutBinder = new TableLayoutBinder(context, tableLayout);\n }\n\n private void appendSection(int nameId) {\n mTableLayoutBinder.appendSection(nameId);\n }\n\n private void appendRow(int nameId) {\n View rowView = mTableLayoutBinder.appendRow2(nameId, null);\n mRowMap.put(nameId, rowView);\n }\n\n private void setRowValue(int id, String value) {\n View rowView = mRowMap.get(id);\n if (rowView == null) {\n rowView = mTableLayoutBinder.appendRow2(id, value);\n mRowMap.put(id, rowView);\n } else {\n mTableLayoutBinder.setValueText(rowView, value);\n }\n }\n\n public void setMediaPlayer(IMediaPlayer mp) ", "post_mask_code": "\n\n private static String formatedDurationMilli(long duration) {\n if (duration >= 1000) {\n return String.format(Locale.US, \"%.2f sec\", ((float) duration) / 1000);\n } else {\n return String.format(Locale.US, \"%d msec\", duration);\n }\n }\n\n private static String formatedSize(long bytes) {\n if (bytes >= 100 * 1000) {\n return String.format(Locale.US, \"%.2f MB\", ((float) bytes) / 1000 / 1000);\n } else if (bytes >= 100) {\n return String.format(Locale.US, \"%.1f KB\", ((float) bytes) / 1000);\n } else {\n return String.format(Locale.US, \"%d B\", bytes);\n }\n }\n\n private static final int MSG_UPDATE_HUD = 1;\n\n private Handler mHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n switch(msg.what) {\n case MSG_UPDATE_HUD:\n {\n InfoHudViewHolder holder = InfoHudViewHolder.this;\n IjkMediaPlayer mp = null;\n if (mMediaPlayer == null)\n break;\n if (mMediaPlayer instanceof IjkMediaPlayer) {\n mp = (IjkMediaPlayer) mMediaPlayer;\n } else if (mMediaPlayer instanceof MediaPlayerProxy) {\n MediaPlayerProxy proxy = (MediaPlayerProxy) mMediaPlayer;\n IMediaPlayer internal = proxy.getInternalMediaPlayer();\n if (internal != null && internal instanceof IjkMediaPlayer)\n mp = (IjkMediaPlayer) internal;\n }\n if (mp == null)\n break;\n int vdec = mp.getVideoDecoder();\n switch(vdec) {\n case IjkMediaPlayer.FFP_PROPV_DECODER_AVCODEC:\n setRowValue(R.string.vdec, \"avcodec\");\n break;\n case IjkMediaPlayer.FFP_PROPV_DECODER_MEDIACODEC:\n setRowValue(R.string.vdec, \"MediaCodec\");\n break;\n default:\n setRowValue(R.string.vdec, \"\");\n break;\n }\n float fpsOutput = mp.getVideoOutputFramesPerSecond();\n float fpsDecode = mp.getVideoDecodeFramesPerSecond();\n setRowValue(R.string.fps, String.format(Locale.US, \"%.2f / %.2f\", fpsDecode, fpsOutput));\n long videoCachedDuration = mp.getVideoCachedDuration();\n long audioCachedDuration = mp.getAudioCachedDuration();\n long videoCachedBytes = mp.getVideoCachedBytes();\n long audioCachedBytes = mp.getAudioCachedBytes();\n setRowValue(R.string.v_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(videoCachedDuration), formatedSize(videoCachedBytes)));\n setRowValue(R.string.a_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(audioCachedDuration), formatedSize(audioCachedBytes)));\n mHandler.removeMessages(MSG_UPDATE_HUD);\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n }\n }\n }\n };\n}\n"} {"task_id": "Java_620", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/CameloeAnthony/Ant/ThirdPart/VideoListPlayer/src/main/java/com/anthony/videolistplayer/media/InfoHudViewHolder.java", "mask_start_position": 1694, "mask_end_position": 1694, "canonical_solution": "", "pre_mask_code": "package com.anthony.videolistplayer.media;\n\nimport android.content.Context;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.widget.TableLayout;\nimport com.anthony.videolistplayer.R;\nimport java.util.Locale;\nimport tv.danmaku.ijk.media.player.IMediaPlayer;\nimport tv.danmaku.ijk.media.player.IjkMediaPlayer;\nimport tv.danmaku.ijk.media.player.MediaPlayerProxy;\n\npublic class InfoHudViewHolder {\n\n private TableLayoutBinder mTableLayoutBinder;\n\n private SparseArray mRowMap = new SparseArray();\n\n private IMediaPlayer mMediaPlayer;\n\n public InfoHudViewHolder(Context context, TableLayout tableLayout) {\n mTableLayoutBinder = new TableLayoutBinder(context, tableLayout);\n }\n\n private void appendSection(int nameId) {\n mTableLayoutBinder.appendSection(nameId);\n }\n\n private void appendRow(int nameId) {\n View rowView = mTableLayoutBinder.appendRow2(nameId, null);\n mRowMap.put(nameId, rowView);\n }\n\n private void setRowValue(int id, String value) {\n View rowView = mRowMap.get(id);\n if (rowView == null) {\n rowView = mTableLayoutBinder.appendRow2(id, value);\n mRowMap.put(id, rowView);\n } else {\n mTableLayoutBinder.setValueText(rowView, value);\n }\n }\n\n public void setMediaPlayer(IMediaPlayer mp) {\n mMediaPlayer = mp;\n if (mMediaPlayer != null) {\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n } else {\n mHandler.removeMessages(MSG_UPDATE_HUD);\n }\n }\n\n private static String formatedDurationMilli(long duration) {", "post_mask_code": "\n if (duration >= 1000) {\n return String.format(Locale.US, \"%.2f sec\", ((float) duration) / 1000);\n } else {\n return String.format(Locale.US, \"%d msec\", duration);\n }\n }\n\n private static String formatedSize(long bytes) {\n if (bytes >= 100 * 1000) {\n return String.format(Locale.US, \"%.2f MB\", ((float) bytes) / 1000 / 1000);\n } else if (bytes >= 100) {\n return String.format(Locale.US, \"%.1f KB\", ((float) bytes) / 1000);\n } else {\n return String.format(Locale.US, \"%d B\", bytes);\n }\n }\n\n private static final int MSG_UPDATE_HUD = 1;\n\n private Handler mHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n switch(msg.what) {\n case MSG_UPDATE_HUD:\n {\n InfoHudViewHolder holder = InfoHudViewHolder.this;\n IjkMediaPlayer mp = null;\n if (mMediaPlayer == null)\n break;\n if (mMediaPlayer instanceof IjkMediaPlayer) {\n mp = (IjkMediaPlayer) mMediaPlayer;\n } else if (mMediaPlayer instanceof MediaPlayerProxy) {\n MediaPlayerProxy proxy = (MediaPlayerProxy) mMediaPlayer;\n IMediaPlayer internal = proxy.getInternalMediaPlayer();\n if (internal != null && internal instanceof IjkMediaPlayer)\n mp = (IjkMediaPlayer) internal;\n }\n if (mp == null)\n break;\n int vdec = mp.getVideoDecoder();\n switch(vdec) {\n case IjkMediaPlayer.FFP_PROPV_DECODER_AVCODEC:\n setRowValue(R.string.vdec, \"avcodec\");\n break;\n case IjkMediaPlayer.FFP_PROPV_DECODER_MEDIACODEC:\n setRowValue(R.string.vdec, \"MediaCodec\");\n break;\n default:\n setRowValue(R.string.vdec, \"\");\n break;\n }\n float fpsOutput = mp.getVideoOutputFramesPerSecond();\n float fpsDecode = mp.getVideoDecodeFramesPerSecond();\n setRowValue(R.string.fps, String.format(Locale.US, \"%.2f / %.2f\", fpsDecode, fpsOutput));\n long videoCachedDuration = mp.getVideoCachedDuration();\n long audioCachedDuration = mp.getAudioCachedDuration();\n long videoCachedBytes = mp.getVideoCachedBytes();\n long audioCachedBytes = mp.getAudioCachedBytes();\n setRowValue(R.string.v_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(videoCachedDuration), formatedSize(videoCachedBytes)));\n setRowValue(R.string.a_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(audioCachedDuration), formatedSize(audioCachedBytes)));\n mHandler.removeMessages(MSG_UPDATE_HUD);\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n }\n }\n }\n };\n}\n"} {"task_id": "Java_621", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/CameloeAnthony/Ant/ThirdPart/VideoListPlayer/src/main/java/com/anthony/videolistplayer/media/InfoHudViewHolder.java", "mask_start_position": 1703, "mask_end_position": 1903, "canonical_solution": "if (duration >= 1000) {\n return String.format(Locale.US, \"%.2f sec\", ((float) duration) / 1000);\n } else {\n return String.format(Locale.US, \"%d msec\", duration);\n }", "pre_mask_code": "package com.anthony.videolistplayer.media;\n\nimport android.content.Context;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.widget.TableLayout;\nimport com.anthony.videolistplayer.R;\nimport java.util.Locale;\nimport tv.danmaku.ijk.media.player.IMediaPlayer;\nimport tv.danmaku.ijk.media.player.IjkMediaPlayer;\nimport tv.danmaku.ijk.media.player.MediaPlayerProxy;\n\npublic class InfoHudViewHolder {\n\n private TableLayoutBinder mTableLayoutBinder;\n\n private SparseArray mRowMap = new SparseArray();\n\n private IMediaPlayer mMediaPlayer;\n\n public InfoHudViewHolder(Context context, TableLayout tableLayout) {\n mTableLayoutBinder = new TableLayoutBinder(context, tableLayout);\n }\n\n private void appendSection(int nameId) {\n mTableLayoutBinder.appendSection(nameId);\n }\n\n private void appendRow(int nameId) {\n View rowView = mTableLayoutBinder.appendRow2(nameId, null);\n mRowMap.put(nameId, rowView);\n }\n\n private void setRowValue(int id, String value) {\n View rowView = mRowMap.get(id);\n if (rowView == null) {\n rowView = mTableLayoutBinder.appendRow2(id, value);\n mRowMap.put(id, rowView);\n } else {\n mTableLayoutBinder.setValueText(rowView, value);\n }\n }\n\n public void setMediaPlayer(IMediaPlayer mp) {\n mMediaPlayer = mp;\n if (mMediaPlayer != null) {\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n } else {\n mHandler.removeMessages(MSG_UPDATE_HUD);\n }\n }\n\n private static String formatedDurationMilli(long duration) {\n ", "post_mask_code": "\n }\n\n private static String formatedSize(long bytes) {\n if (bytes >= 100 * 1000) {\n return String.format(Locale.US, \"%.2f MB\", ((float) bytes) / 1000 / 1000);\n } else if (bytes >= 100) {\n return String.format(Locale.US, \"%.1f KB\", ((float) bytes) / 1000);\n } else {\n return String.format(Locale.US, \"%d B\", bytes);\n }\n }\n\n private static final int MSG_UPDATE_HUD = 1;\n\n private Handler mHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n switch(msg.what) {\n case MSG_UPDATE_HUD:\n {\n InfoHudViewHolder holder = InfoHudViewHolder.this;\n IjkMediaPlayer mp = null;\n if (mMediaPlayer == null)\n break;\n if (mMediaPlayer instanceof IjkMediaPlayer) {\n mp = (IjkMediaPlayer) mMediaPlayer;\n } else if (mMediaPlayer instanceof MediaPlayerProxy) {\n MediaPlayerProxy proxy = (MediaPlayerProxy) mMediaPlayer;\n IMediaPlayer internal = proxy.getInternalMediaPlayer();\n if (internal != null && internal instanceof IjkMediaPlayer)\n mp = (IjkMediaPlayer) internal;\n }\n if (mp == null)\n break;\n int vdec = mp.getVideoDecoder();\n switch(vdec) {\n case IjkMediaPlayer.FFP_PROPV_DECODER_AVCODEC:\n setRowValue(R.string.vdec, \"avcodec\");\n break;\n case IjkMediaPlayer.FFP_PROPV_DECODER_MEDIACODEC:\n setRowValue(R.string.vdec, \"MediaCodec\");\n break;\n default:\n setRowValue(R.string.vdec, \"\");\n break;\n }\n float fpsOutput = mp.getVideoOutputFramesPerSecond();\n float fpsDecode = mp.getVideoDecodeFramesPerSecond();\n setRowValue(R.string.fps, String.format(Locale.US, \"%.2f / %.2f\", fpsDecode, fpsOutput));\n long videoCachedDuration = mp.getVideoCachedDuration();\n long audioCachedDuration = mp.getAudioCachedDuration();\n long videoCachedBytes = mp.getVideoCachedBytes();\n long audioCachedBytes = mp.getAudioCachedBytes();\n setRowValue(R.string.v_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(videoCachedDuration), formatedSize(videoCachedBytes)));\n setRowValue(R.string.a_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(audioCachedDuration), formatedSize(audioCachedBytes)));\n mHandler.removeMessages(MSG_UPDATE_HUD);\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n }\n }\n }\n };\n}\n"} {"task_id": "Java_622", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/CameloeAnthony/Ant/ThirdPart/VideoListPlayer/src/main/java/com/anthony/videolistplayer/media/InfoHudViewHolder.java", "mask_start_position": 1908, "mask_end_position": 1909, "canonical_solution": "}", "pre_mask_code": "package com.anthony.videolistplayer.media;\n\nimport android.content.Context;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.widget.TableLayout;\nimport com.anthony.videolistplayer.R;\nimport java.util.Locale;\nimport tv.danmaku.ijk.media.player.IMediaPlayer;\nimport tv.danmaku.ijk.media.player.IjkMediaPlayer;\nimport tv.danmaku.ijk.media.player.MediaPlayerProxy;\n\npublic class InfoHudViewHolder {\n\n private TableLayoutBinder mTableLayoutBinder;\n\n private SparseArray mRowMap = new SparseArray();\n\n private IMediaPlayer mMediaPlayer;\n\n public InfoHudViewHolder(Context context, TableLayout tableLayout) {\n mTableLayoutBinder = new TableLayoutBinder(context, tableLayout);\n }\n\n private void appendSection(int nameId) {\n mTableLayoutBinder.appendSection(nameId);\n }\n\n private void appendRow(int nameId) {\n View rowView = mTableLayoutBinder.appendRow2(nameId, null);\n mRowMap.put(nameId, rowView);\n }\n\n private void setRowValue(int id, String value) {\n View rowView = mRowMap.get(id);\n if (rowView == null) {\n rowView = mTableLayoutBinder.appendRow2(id, value);\n mRowMap.put(id, rowView);\n } else {\n mTableLayoutBinder.setValueText(rowView, value);\n }\n }\n\n public void setMediaPlayer(IMediaPlayer mp) {\n mMediaPlayer = mp;\n if (mMediaPlayer != null) {\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n } else {\n mHandler.removeMessages(MSG_UPDATE_HUD);\n }\n }\n\n private static String formatedDurationMilli(long duration) {\n if (duration >= 1000) {\n return String.format(Locale.US, \"%.2f sec\", ((float) duration) / 1000);\n } else {\n return String.format(Locale.US, \"%d msec\", duration);\n }\n ", "post_mask_code": "\n\n private static String formatedSize(long bytes) {\n if (bytes >= 100 * 1000) {\n return String.format(Locale.US, \"%.2f MB\", ((float) bytes) / 1000 / 1000);\n } else if (bytes >= 100) {\n return String.format(Locale.US, \"%.1f KB\", ((float) bytes) / 1000);\n } else {\n return String.format(Locale.US, \"%d B\", bytes);\n }\n }\n\n private static final int MSG_UPDATE_HUD = 1;\n\n private Handler mHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n switch(msg.what) {\n case MSG_UPDATE_HUD:\n {\n InfoHudViewHolder holder = InfoHudViewHolder.this;\n IjkMediaPlayer mp = null;\n if (mMediaPlayer == null)\n break;\n if (mMediaPlayer instanceof IjkMediaPlayer) {\n mp = (IjkMediaPlayer) mMediaPlayer;\n } else if (mMediaPlayer instanceof MediaPlayerProxy) {\n MediaPlayerProxy proxy = (MediaPlayerProxy) mMediaPlayer;\n IMediaPlayer internal = proxy.getInternalMediaPlayer();\n if (internal != null && internal instanceof IjkMediaPlayer)\n mp = (IjkMediaPlayer) internal;\n }\n if (mp == null)\n break;\n int vdec = mp.getVideoDecoder();\n switch(vdec) {\n case IjkMediaPlayer.FFP_PROPV_DECODER_AVCODEC:\n setRowValue(R.string.vdec, \"avcodec\");\n break;\n case IjkMediaPlayer.FFP_PROPV_DECODER_MEDIACODEC:\n setRowValue(R.string.vdec, \"MediaCodec\");\n break;\n default:\n setRowValue(R.string.vdec, \"\");\n break;\n }\n float fpsOutput = mp.getVideoOutputFramesPerSecond();\n float fpsDecode = mp.getVideoDecodeFramesPerSecond();\n setRowValue(R.string.fps, String.format(Locale.US, \"%.2f / %.2f\", fpsDecode, fpsOutput));\n long videoCachedDuration = mp.getVideoCachedDuration();\n long audioCachedDuration = mp.getAudioCachedDuration();\n long videoCachedBytes = mp.getVideoCachedBytes();\n long audioCachedBytes = mp.getAudioCachedBytes();\n setRowValue(R.string.v_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(videoCachedDuration), formatedSize(videoCachedBytes)));\n setRowValue(R.string.a_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(audioCachedDuration), formatedSize(audioCachedBytes)));\n mHandler.removeMessages(MSG_UPDATE_HUD);\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n }\n }\n }\n };\n}\n"} {"task_id": "Java_623", "language": "Java", "task_type": "single_line", "source_file": "java/github/CameloeAnthony/Ant/ThirdPart/VideoListPlayer/src/main/java/com/anthony/videolistplayer/media/InfoHudViewHolder.java", "mask_start_position": 952, "mask_end_position": 996, "canonical_solution": "mTableLayoutBinder.appendRow2(nameId, null);", "pre_mask_code": "package com.anthony.videolistplayer.media;\n\nimport android.content.Context;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.widget.TableLayout;\nimport com.anthony.videolistplayer.R;\nimport java.util.Locale;\nimport tv.danmaku.ijk.media.player.IMediaPlayer;\nimport tv.danmaku.ijk.media.player.IjkMediaPlayer;\nimport tv.danmaku.ijk.media.player.MediaPlayerProxy;\n\npublic class InfoHudViewHolder {\n\n private TableLayoutBinder mTableLayoutBinder;\n\n private SparseArray mRowMap = new SparseArray();\n\n private IMediaPlayer mMediaPlayer;\n\n public InfoHudViewHolder(Context context, TableLayout tableLayout) {\n mTableLayoutBinder = new TableLayoutBinder(context, tableLayout);\n }\n\n private void appendSection(int nameId) {\n mTableLayoutBinder.appendSection(nameId);\n }\n\n private void appendRow(int nameId) {\n View rowView = ", "post_mask_code": "\n mRowMap.put(nameId, rowView);\n }\n\n private void setRowValue(int id, String value) {\n View rowView = mRowMap.get(id);\n if (rowView == null) {\n rowView = mTableLayoutBinder.appendRow2(id, value);\n mRowMap.put(id, rowView);\n } else {\n mTableLayoutBinder.setValueText(rowView, value);\n }\n }\n\n public void setMediaPlayer(IMediaPlayer mp) {\n mMediaPlayer = mp;\n if (mMediaPlayer != null) {\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n } else {\n mHandler.removeMessages(MSG_UPDATE_HUD);\n }\n }\n\n private static String formatedDurationMilli(long duration) {\n if (duration >= 1000) {\n return String.format(Locale.US, \"%.2f sec\", ((float) duration) / 1000);\n } else {\n return String.format(Locale.US, \"%d msec\", duration);\n }\n }\n\n private static String formatedSize(long bytes) {\n if (bytes >= 100 * 1000) {\n return String.format(Locale.US, \"%.2f MB\", ((float) bytes) / 1000 / 1000);\n } else if (bytes >= 100) {\n return String.format(Locale.US, \"%.1f KB\", ((float) bytes) / 1000);\n } else {\n return String.format(Locale.US, \"%d B\", bytes);\n }\n }\n\n private static final int MSG_UPDATE_HUD = 1;\n\n private Handler mHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n switch(msg.what) {\n case MSG_UPDATE_HUD:\n {\n InfoHudViewHolder holder = InfoHudViewHolder.this;\n IjkMediaPlayer mp = null;\n if (mMediaPlayer == null)\n break;\n if (mMediaPlayer instanceof IjkMediaPlayer) {\n mp = (IjkMediaPlayer) mMediaPlayer;\n } else if (mMediaPlayer instanceof MediaPlayerProxy) {\n MediaPlayerProxy proxy = (MediaPlayerProxy) mMediaPlayer;\n IMediaPlayer internal = proxy.getInternalMediaPlayer();\n if (internal != null && internal instanceof IjkMediaPlayer)\n mp = (IjkMediaPlayer) internal;\n }\n if (mp == null)\n break;\n int vdec = mp.getVideoDecoder();\n switch(vdec) {\n case IjkMediaPlayer.FFP_PROPV_DECODER_AVCODEC:\n setRowValue(R.string.vdec, \"avcodec\");\n break;\n case IjkMediaPlayer.FFP_PROPV_DECODER_MEDIACODEC:\n setRowValue(R.string.vdec, \"MediaCodec\");\n break;\n default:\n setRowValue(R.string.vdec, \"\");\n break;\n }\n float fpsOutput = mp.getVideoOutputFramesPerSecond();\n float fpsDecode = mp.getVideoDecodeFramesPerSecond();\n setRowValue(R.string.fps, String.format(Locale.US, \"%.2f / %.2f\", fpsDecode, fpsOutput));\n long videoCachedDuration = mp.getVideoCachedDuration();\n long audioCachedDuration = mp.getAudioCachedDuration();\n long videoCachedBytes = mp.getVideoCachedBytes();\n long audioCachedBytes = mp.getAudioCachedBytes();\n setRowValue(R.string.v_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(videoCachedDuration), formatedSize(videoCachedBytes)));\n setRowValue(R.string.a_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(audioCachedDuration), formatedSize(audioCachedBytes)));\n mHandler.removeMessages(MSG_UPDATE_HUD);\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n }\n }\n }\n };\n}\n"} {"task_id": "Java_624", "language": "Java", "task_type": "if_statement", "source_file": "java/github/CameloeAnthony/Ant/ThirdPart/VideoListPlayer/src/main/java/com/anthony/videolistplayer/media/InfoHudViewHolder.java", "mask_start_position": 2101, "mask_end_position": 2287, "canonical_solution": "if (bytes >= 100) {\n return String.format(Locale.US, \"%.1f KB\", ((float) bytes) / 1000);\n } else {\n return String.format(Locale.US, \"%d B\", bytes);\n }", "pre_mask_code": "package com.anthony.videolistplayer.media;\n\nimport android.content.Context;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.widget.TableLayout;\nimport com.anthony.videolistplayer.R;\nimport java.util.Locale;\nimport tv.danmaku.ijk.media.player.IMediaPlayer;\nimport tv.danmaku.ijk.media.player.IjkMediaPlayer;\nimport tv.danmaku.ijk.media.player.MediaPlayerProxy;\n\npublic class InfoHudViewHolder {\n\n private TableLayoutBinder mTableLayoutBinder;\n\n private SparseArray mRowMap = new SparseArray();\n\n private IMediaPlayer mMediaPlayer;\n\n public InfoHudViewHolder(Context context, TableLayout tableLayout) {\n mTableLayoutBinder = new TableLayoutBinder(context, tableLayout);\n }\n\n private void appendSection(int nameId) {\n mTableLayoutBinder.appendSection(nameId);\n }\n\n private void appendRow(int nameId) {\n View rowView = mTableLayoutBinder.appendRow2(nameId, null);\n mRowMap.put(nameId, rowView);\n }\n\n private void setRowValue(int id, String value) {\n View rowView = mRowMap.get(id);\n if (rowView == null) {\n rowView = mTableLayoutBinder.appendRow2(id, value);\n mRowMap.put(id, rowView);\n } else {\n mTableLayoutBinder.setValueText(rowView, value);\n }\n }\n\n public void setMediaPlayer(IMediaPlayer mp) {\n mMediaPlayer = mp;\n if (mMediaPlayer != null) {\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n } else {\n mHandler.removeMessages(MSG_UPDATE_HUD);\n }\n }\n\n private static String formatedDurationMilli(long duration) {\n if (duration >= 1000) {\n return String.format(Locale.US, \"%.2f sec\", ((float) duration) / 1000);\n } else {\n return String.format(Locale.US, \"%d msec\", duration);\n }\n }\n\n private static String formatedSize(long bytes) {\n if (bytes >= 100 * 1000) {\n return String.format(Locale.US, \"%.2f MB\", ((float) bytes) / 1000 / 1000);\n } else ", "post_mask_code": "\n }\n\n private static final int MSG_UPDATE_HUD = 1;\n\n private Handler mHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n switch(msg.what) {\n case MSG_UPDATE_HUD:\n {\n InfoHudViewHolder holder = InfoHudViewHolder.this;\n IjkMediaPlayer mp = null;\n if (mMediaPlayer == null)\n break;\n if (mMediaPlayer instanceof IjkMediaPlayer) {\n mp = (IjkMediaPlayer) mMediaPlayer;\n } else if (mMediaPlayer instanceof MediaPlayerProxy) {\n MediaPlayerProxy proxy = (MediaPlayerProxy) mMediaPlayer;\n IMediaPlayer internal = proxy.getInternalMediaPlayer();\n if (internal != null && internal instanceof IjkMediaPlayer)\n mp = (IjkMediaPlayer) internal;\n }\n if (mp == null)\n break;\n int vdec = mp.getVideoDecoder();\n switch(vdec) {\n case IjkMediaPlayer.FFP_PROPV_DECODER_AVCODEC:\n setRowValue(R.string.vdec, \"avcodec\");\n break;\n case IjkMediaPlayer.FFP_PROPV_DECODER_MEDIACODEC:\n setRowValue(R.string.vdec, \"MediaCodec\");\n break;\n default:\n setRowValue(R.string.vdec, \"\");\n break;\n }\n float fpsOutput = mp.getVideoOutputFramesPerSecond();\n float fpsDecode = mp.getVideoDecodeFramesPerSecond();\n setRowValue(R.string.fps, String.format(Locale.US, \"%.2f / %.2f\", fpsDecode, fpsOutput));\n long videoCachedDuration = mp.getVideoCachedDuration();\n long audioCachedDuration = mp.getAudioCachedDuration();\n long videoCachedBytes = mp.getVideoCachedBytes();\n long audioCachedBytes = mp.getAudioCachedBytes();\n setRowValue(R.string.v_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(videoCachedDuration), formatedSize(videoCachedBytes)));\n setRowValue(R.string.a_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(audioCachedDuration), formatedSize(audioCachedBytes)));\n mHandler.removeMessages(MSG_UPDATE_HUD);\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n }\n }\n }\n };\n}\n"} {"task_id": "Java_625", "language": "Java", "task_type": "empty", "source_file": "java/github/CameloeAnthony/Ant/ThirdPart/VideoListPlayer/src/main/java/com/anthony/videolistplayer/media/InfoHudViewHolder.java", "mask_start_position": 4548, "mask_end_position": 4548, "canonical_solution": "", "pre_mask_code": "package com.anthony.videolistplayer.media;\n\nimport android.content.Context;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.widget.TableLayout;\nimport com.anthony.videolistplayer.R;\nimport java.util.Locale;\nimport tv.danmaku.ijk.media.player.IMediaPlayer;\nimport tv.danmaku.ijk.media.player.IjkMediaPlayer;\nimport tv.danmaku.ijk.media.player.MediaPlayerProxy;\n\npublic class InfoHudViewHolder {\n\n private TableLayoutBinder mTableLayoutBinder;\n\n private SparseArray mRowMap = new SparseArray();\n\n private IMediaPlayer mMediaPlayer;\n\n public InfoHudViewHolder(Context context, TableLayout tableLayout) {\n mTableLayoutBinder = new TableLayoutBinder(context, tableLayout);\n }\n\n private void appendSection(int nameId) {\n mTableLayoutBinder.appendSection(nameId);\n }\n\n private void appendRow(int nameId) {\n View rowView = mTableLayoutBinder.appendRow2(nameId, null);\n mRowMap.put(nameId, rowView);\n }\n\n private void setRowValue(int id, String value) {\n View rowView = mRowMap.get(id);\n if (rowView == null) {\n rowView = mTableLayoutBinder.appendRow2(id, value);\n mRowMap.put(id, rowView);\n } else {\n mTableLayoutBinder.setValueText(rowView, value);\n }\n }\n\n public void setMediaPlayer(IMediaPlayer mp) {\n mMediaPlayer = mp;\n if (mMediaPlayer != null) {\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n } else {\n mHandler.removeMessages(MSG_UPDATE_HUD);\n }\n }\n\n private static String formatedDurationMilli(long duration) {\n if (duration >= 1000) {\n return String.format(Locale.US, \"%.2f sec\", ((float) duration) / 1000);\n } else {\n return String.format(Locale.US, \"%d msec\", duration);\n }\n }\n\n private static String formatedSize(long bytes) {\n if (bytes >= 100 * 1000) {\n return String.format(Locale.US, \"%.2f MB\", ((float) bytes) / 1000 / 1000);\n } else if (bytes >= 100) {\n return String.format(Locale.US, \"%.1f KB\", ((float) bytes) / 1000);\n } else {\n return String.format(Locale.US, \"%d B\", bytes);\n }\n }\n\n private static final int MSG_UPDATE_HUD = 1;\n\n private Handler mHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n switch(msg.what) {\n case MSG_UPDATE_HUD:\n {\n InfoHudViewHolder holder = InfoHudViewHolder.this;\n IjkMediaPlayer mp = null;\n if (mMediaPlayer == null)\n break;\n if (mMediaPlayer instanceof IjkMediaPlayer) {\n mp = (IjkMediaPlayer) mMediaPlayer;\n } else if (mMediaPlayer instanceof MediaPlayerProxy) {\n MediaPlayerProxy proxy = (MediaPlayerProxy) mMediaPlayer;\n IMediaPlayer internal = proxy.getInternalMediaPlayer();\n if (internal != null && internal instanceof IjkMediaPlayer)\n mp = (IjkMediaPlayer) internal;\n }\n if (mp == null)\n break;\n int vdec = mp.getVideoDecoder();\n switch(vdec) {\n case IjkMediaPlayer.FFP_PROPV_DECODER_AVCODEC:\n setRowValue(R.string.vdec, \"avcodec\");\n break;\n case IjkMediaPlayer.FFP_PROPV_DECODER_MEDIACODEC:\n setRowValue(R.string.vdec, \"MediaCodec\");\n break;\n default:\n setRowValue(R.string.vdec, \"\");\n break;\n }\n float fpsOutput = mp.getVideoOutputFramesPerSecond();\n float fpsDecode = mp.getVideoDecodeFramesPerSecond();\n setRowValue(R.string.fps, String.format(Locale.US, \"%.2f / %.2f\", fpsDecode, fpsOutput));\n long videoCachedDuration = mp.getVideoCachedDuration();\n long audioCachedDuration = mp.getAudioCachedDuration();\n long videoCachedBytes = mp.getVideoCachedBytes();\n ", "post_mask_code": " long audioCachedBytes = mp.getAudioCachedBytes();\n setRowValue(R.string.v_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(videoCachedDuration), formatedSize(videoCachedBytes)));\n setRowValue(R.string.a_cache, String.format(Locale.US, \"%s, %s\", formatedDurationMilli(audioCachedDuration), formatedSize(audioCachedBytes)));\n mHandler.removeMessages(MSG_UPDATE_HUD);\n mHandler.sendEmptyMessageDelayed(MSG_UPDATE_HUD, 500);\n }\n }\n }\n };\n}\n"} {"task_id": "Java_626", "language": "Java", "task_type": "method_signature", "source_file": "java/github/noties/Storm/performance_test/src/main/java/ru/noties/performance_test/sprkls/SprinklesTest.java", "mask_start_position": 1584, "mask_end_position": 1624, "canonical_solution": "@Override\n protected void queryAll() ", "pre_mask_code": "package ru.noties.performance_test.sprkls;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport java.util.List;\nimport ru.noties.storm.InstanceCreator;\nimport ru.noties.performance_test.AbsTest;\nimport ru.noties.performance_test.BuildConfig;\nimport ru.noties.performance_test.OpType;\nimport ru.noties.performance_test.Time;\nimport se.emilsjolander.sprinkles.Migration;\nimport se.emilsjolander.sprinkles.Query;\nimport se.emilsjolander.sprinkles.Sprinkles;\nimport se.emilsjolander.sprinkles.Transaction;\nimport se.emilsjolander.sprinkles.typeserializers.SqlType;\nimport se.emilsjolander.sprinkles.typeserializers.TypeSerializer;\n\n/**\n * Created by Dimitry Ivanov (example@nnthink.com) on 12.02.2015.\n */\npublic class SprinklesTest extends AbsTest {\n\n public SprinklesTest(Context context, OpType[] opTypes, int rounds, Time time, boolean isLast) {\n super(context, opTypes, rounds, time, isLast);\n }\n\n @Override\n protected void setUp() {\n open();\n }\n\n @Override\n protected void tearDown() {\n }\n\n @Override\n protected void insert(List list) {\n final Transaction transaction = new Transaction();\n for (SprinklesObject object : list) {\n object.save(transaction);\n }\n transaction.setSuccessful(true);\n transaction.finish();\n }\n\n @Override\n protected void queryOne(long id) {\n Query.one(SprinklesObject.class, \"where id = ?\", id).get();\n }\n\n ", "post_mask_code": "{\n Query.all(SprinklesObject.class).get().asList();\n }\n\n @Override\n protected void deleteAll() {\n // no exceptions are thrown, catch it yourself\n // throws IndexOutOfBoundsException if passed db version is not starts with 0\n // java.lang.IllegalStateException: Couldn't read row 5470, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.\n final Transaction dt = new Transaction();\n for (SprinklesObject sprinklesObject : Query.all(SprinklesObject.class).get()) {\n sprinklesObject.delete(dt);\n }\n dt.setSuccessful(true);\n dt.finish();\n }\n\n Sprinkles open() {\n final BuildConfig.ORM orm = getORM();\n final Sprinkles sprinkles = Sprinkles.init(getContext(), orm.getDbName(), orm.getDbVersion());\n sprinkles.addMigration(new Migration() {\n\n @Override\n protected void doMigration(SQLiteDatabase sqLiteDatabase) {\n final String sql = \"CREATE TABLE IF NOT EXISTS `sprinkles_object` (\" + \"`someString` TEXT, \" + \"`someBool` INTEGER, \" + \"`id`INTEGER PRIMARY KEY AUTOINCREMENT, \" + \"`someDouble` REAL, \" + \"`someLong` INTEGER, \" + \"`someFloat` REAL, \" + \"`someInt` INTEGER, \" + \"`someShort` INTEGER\" + \");\";\n sqLiteDatabase.execSQL(sql);\n }\n });\n // no short type\n sprinkles.registerType(Short.TYPE, new TypeSerializer() {\n\n @Override\n public Short unpack(Cursor c, String name) {\n return c.getShort(c.getColumnIndex(name));\n }\n\n @Override\n public void pack(Short object, ContentValues cv, String name) {\n cv.put(name, object);\n }\n\n @Override\n public String toSql(Short object) {\n return String.valueOf(object);\n }\n\n @Override\n public SqlType getSqlType() {\n return SqlType.INTEGER;\n }\n });\n return sprinkles;\n }\n\n @Override\n protected InstanceCreator getInstanceCreator() {\n return new InstanceCreator() {\n\n @Override\n public SprinklesObject create(Class clazz) {\n return new SprinklesObject();\n }\n };\n }\n\n @Override\n protected BuildConfig.ORM getORM() {\n return BuildConfig.ORM.SPRINKLES;\n }\n}\n"} {"task_id": "Java_627", "language": "Java", "task_type": "method_body", "source_file": "java/github/noties/Storm/performance_test/src/main/java/ru/noties/performance_test/sprkls/SprinklesTest.java", "mask_start_position": 3771, "mask_end_position": 4002, "canonical_solution": "{\n return new InstanceCreator() {\n\n @Override\n public SprinklesObject create(Class clazz) {\n return new SprinklesObject();\n }\n };\n }", "pre_mask_code": "package ru.noties.performance_test.sprkls;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport java.util.List;\nimport ru.noties.storm.InstanceCreator;\nimport ru.noties.performance_test.AbsTest;\nimport ru.noties.performance_test.BuildConfig;\nimport ru.noties.performance_test.OpType;\nimport ru.noties.performance_test.Time;\nimport se.emilsjolander.sprinkles.Migration;\nimport se.emilsjolander.sprinkles.Query;\nimport se.emilsjolander.sprinkles.Sprinkles;\nimport se.emilsjolander.sprinkles.Transaction;\nimport se.emilsjolander.sprinkles.typeserializers.SqlType;\nimport se.emilsjolander.sprinkles.typeserializers.TypeSerializer;\n\n/**\n * Created by Dimitry Ivanov (example@nnthink.com) on 12.02.2015.\n */\npublic class SprinklesTest extends AbsTest {\n\n public SprinklesTest(Context context, OpType[] opTypes, int rounds, Time time, boolean isLast) {\n super(context, opTypes, rounds, time, isLast);\n }\n\n @Override\n protected void setUp() {\n open();\n }\n\n @Override\n protected void tearDown() {\n }\n\n @Override\n protected void insert(List list) {\n final Transaction transaction = new Transaction();\n for (SprinklesObject object : list) {\n object.save(transaction);\n }\n transaction.setSuccessful(true);\n transaction.finish();\n }\n\n @Override\n protected void queryOne(long id) {\n Query.one(SprinklesObject.class, \"where id = ?\", id).get();\n }\n\n @Override\n protected void queryAll() {\n Query.all(SprinklesObject.class).get().asList();\n }\n\n @Override\n protected void deleteAll() {\n // no exceptions are thrown, catch it yourself\n // throws IndexOutOfBoundsException if passed db version is not starts with 0\n // java.lang.IllegalStateException: Couldn't read row 5470, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.\n final Transaction dt = new Transaction();\n for (SprinklesObject sprinklesObject : Query.all(SprinklesObject.class).get()) {\n sprinklesObject.delete(dt);\n }\n dt.setSuccessful(true);\n dt.finish();\n }\n\n Sprinkles open() {\n final BuildConfig.ORM orm = getORM();\n final Sprinkles sprinkles = Sprinkles.init(getContext(), orm.getDbName(), orm.getDbVersion());\n sprinkles.addMigration(new Migration() {\n\n @Override\n protected void doMigration(SQLiteDatabase sqLiteDatabase) {\n final String sql = \"CREATE TABLE IF NOT EXISTS `sprinkles_object` (\" + \"`someString` TEXT, \" + \"`someBool` INTEGER, \" + \"`id`INTEGER PRIMARY KEY AUTOINCREMENT, \" + \"`someDouble` REAL, \" + \"`someLong` INTEGER, \" + \"`someFloat` REAL, \" + \"`someInt` INTEGER, \" + \"`someShort` INTEGER\" + \");\";\n sqLiteDatabase.execSQL(sql);\n }\n });\n // no short type\n sprinkles.registerType(Short.TYPE, new TypeSerializer() {\n\n @Override\n public Short unpack(Cursor c, String name) {\n return c.getShort(c.getColumnIndex(name));\n }\n\n @Override\n public void pack(Short object, ContentValues cv, String name) {\n cv.put(name, object);\n }\n\n @Override\n public String toSql(Short object) {\n return String.valueOf(object);\n }\n\n @Override\n public SqlType getSqlType() {\n return SqlType.INTEGER;\n }\n });\n return sprinkles;\n }\n\n @Override\n protected InstanceCreator getInstanceCreator() ", "post_mask_code": "\n\n @Override\n protected BuildConfig.ORM getORM() {\n return BuildConfig.ORM.SPRINKLES;\n }\n}\n"} {"task_id": "Java_628", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/noties/Storm/performance_test/src/main/java/ru/noties/performance_test/sprkls/SprinklesTest.java", "mask_start_position": 1220, "mask_end_position": 1279, "canonical_solution": "\n final Transaction transaction = new Transaction();", "pre_mask_code": "package ru.noties.performance_test.sprkls;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport java.util.List;\nimport ru.noties.storm.InstanceCreator;\nimport ru.noties.performance_test.AbsTest;\nimport ru.noties.performance_test.BuildConfig;\nimport ru.noties.performance_test.OpType;\nimport ru.noties.performance_test.Time;\nimport se.emilsjolander.sprinkles.Migration;\nimport se.emilsjolander.sprinkles.Query;\nimport se.emilsjolander.sprinkles.Sprinkles;\nimport se.emilsjolander.sprinkles.Transaction;\nimport se.emilsjolander.sprinkles.typeserializers.SqlType;\nimport se.emilsjolander.sprinkles.typeserializers.TypeSerializer;\n\n/**\n * Created by Dimitry Ivanov (example@nnthink.com) on 12.02.2015.\n */\npublic class SprinklesTest extends AbsTest {\n\n public SprinklesTest(Context context, OpType[] opTypes, int rounds, Time time, boolean isLast) {\n super(context, opTypes, rounds, time, isLast);\n }\n\n @Override\n protected void setUp() {\n open();\n }\n\n @Override\n protected void tearDown() {\n }\n\n @Override\n protected void insert(List list) {", "post_mask_code": "\n for (SprinklesObject object : list) {\n object.save(transaction);\n }\n transaction.setSuccessful(true);\n transaction.finish();\n }\n\n @Override\n protected void queryOne(long id) {\n Query.one(SprinklesObject.class, \"where id = ?\", id).get();\n }\n\n @Override\n protected void queryAll() {\n Query.all(SprinklesObject.class).get().asList();\n }\n\n @Override\n protected void deleteAll() {\n // no exceptions are thrown, catch it yourself\n // throws IndexOutOfBoundsException if passed db version is not starts with 0\n // java.lang.IllegalStateException: Couldn't read row 5470, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.\n final Transaction dt = new Transaction();\n for (SprinklesObject sprinklesObject : Query.all(SprinklesObject.class).get()) {\n sprinklesObject.delete(dt);\n }\n dt.setSuccessful(true);\n dt.finish();\n }\n\n Sprinkles open() {\n final BuildConfig.ORM orm = getORM();\n final Sprinkles sprinkles = Sprinkles.init(getContext(), orm.getDbName(), orm.getDbVersion());\n sprinkles.addMigration(new Migration() {\n\n @Override\n protected void doMigration(SQLiteDatabase sqLiteDatabase) {\n final String sql = \"CREATE TABLE IF NOT EXISTS `sprinkles_object` (\" + \"`someString` TEXT, \" + \"`someBool` INTEGER, \" + \"`id`INTEGER PRIMARY KEY AUTOINCREMENT, \" + \"`someDouble` REAL, \" + \"`someLong` INTEGER, \" + \"`someFloat` REAL, \" + \"`someInt` INTEGER, \" + \"`someShort` INTEGER\" + \");\";\n sqLiteDatabase.execSQL(sql);\n }\n });\n // no short type\n sprinkles.registerType(Short.TYPE, new TypeSerializer() {\n\n @Override\n public Short unpack(Cursor c, String name) {\n return c.getShort(c.getColumnIndex(name));\n }\n\n @Override\n public void pack(Short object, ContentValues cv, String name) {\n cv.put(name, object);\n }\n\n @Override\n public String toSql(Short object) {\n return String.valueOf(object);\n }\n\n @Override\n public SqlType getSqlType() {\n return SqlType.INTEGER;\n }\n });\n return sprinkles;\n }\n\n @Override\n protected InstanceCreator getInstanceCreator() {\n return new InstanceCreator() {\n\n @Override\n public SprinklesObject create(Class clazz) {\n return new SprinklesObject();\n }\n };\n }\n\n @Override\n protected BuildConfig.ORM getORM() {\n return BuildConfig.ORM.SPRINKLES;\n }\n}\n"} {"task_id": "Java_629", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/noties/Storm/performance_test/src/main/java/ru/noties/performance_test/sprkls/SprinklesTest.java", "mask_start_position": 1288, "mask_end_position": 1414, "canonical_solution": "for (SprinklesObject object : list) {\n object.save(transaction);\n }\n transaction.setSuccessful(true);", "pre_mask_code": "package ru.noties.performance_test.sprkls;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport java.util.List;\nimport ru.noties.storm.InstanceCreator;\nimport ru.noties.performance_test.AbsTest;\nimport ru.noties.performance_test.BuildConfig;\nimport ru.noties.performance_test.OpType;\nimport ru.noties.performance_test.Time;\nimport se.emilsjolander.sprinkles.Migration;\nimport se.emilsjolander.sprinkles.Query;\nimport se.emilsjolander.sprinkles.Sprinkles;\nimport se.emilsjolander.sprinkles.Transaction;\nimport se.emilsjolander.sprinkles.typeserializers.SqlType;\nimport se.emilsjolander.sprinkles.typeserializers.TypeSerializer;\n\n/**\n * Created by Dimitry Ivanov (example@nnthink.com) on 12.02.2015.\n */\npublic class SprinklesTest extends AbsTest {\n\n public SprinklesTest(Context context, OpType[] opTypes, int rounds, Time time, boolean isLast) {\n super(context, opTypes, rounds, time, isLast);\n }\n\n @Override\n protected void setUp() {\n open();\n }\n\n @Override\n protected void tearDown() {\n }\n\n @Override\n protected void insert(List list) {\n final Transaction transaction = new Transaction();\n ", "post_mask_code": "\n transaction.finish();\n }\n\n @Override\n protected void queryOne(long id) {\n Query.one(SprinklesObject.class, \"where id = ?\", id).get();\n }\n\n @Override\n protected void queryAll() {\n Query.all(SprinklesObject.class).get().asList();\n }\n\n @Override\n protected void deleteAll() {\n // no exceptions are thrown, catch it yourself\n // throws IndexOutOfBoundsException if passed db version is not starts with 0\n // java.lang.IllegalStateException: Couldn't read row 5470, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.\n final Transaction dt = new Transaction();\n for (SprinklesObject sprinklesObject : Query.all(SprinklesObject.class).get()) {\n sprinklesObject.delete(dt);\n }\n dt.setSuccessful(true);\n dt.finish();\n }\n\n Sprinkles open() {\n final BuildConfig.ORM orm = getORM();\n final Sprinkles sprinkles = Sprinkles.init(getContext(), orm.getDbName(), orm.getDbVersion());\n sprinkles.addMigration(new Migration() {\n\n @Override\n protected void doMigration(SQLiteDatabase sqLiteDatabase) {\n final String sql = \"CREATE TABLE IF NOT EXISTS `sprinkles_object` (\" + \"`someString` TEXT, \" + \"`someBool` INTEGER, \" + \"`id`INTEGER PRIMARY KEY AUTOINCREMENT, \" + \"`someDouble` REAL, \" + \"`someLong` INTEGER, \" + \"`someFloat` REAL, \" + \"`someInt` INTEGER, \" + \"`someShort` INTEGER\" + \");\";\n sqLiteDatabase.execSQL(sql);\n }\n });\n // no short type\n sprinkles.registerType(Short.TYPE, new TypeSerializer() {\n\n @Override\n public Short unpack(Cursor c, String name) {\n return c.getShort(c.getColumnIndex(name));\n }\n\n @Override\n public void pack(Short object, ContentValues cv, String name) {\n cv.put(name, object);\n }\n\n @Override\n public String toSql(Short object) {\n return String.valueOf(object);\n }\n\n @Override\n public SqlType getSqlType() {\n return SqlType.INTEGER;\n }\n });\n return sprinkles;\n }\n\n @Override\n protected InstanceCreator getInstanceCreator() {\n return new InstanceCreator() {\n\n @Override\n public SprinklesObject create(Class clazz) {\n return new SprinklesObject();\n }\n };\n }\n\n @Override\n protected BuildConfig.ORM getORM() {\n return BuildConfig.ORM.SPRINKLES;\n }\n}\n"} {"task_id": "Java_630", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/noties/Storm/performance_test/src/main/java/ru/noties/performance_test/sprkls/SprinklesTest.java", "mask_start_position": 1423, "mask_end_position": 1450, "canonical_solution": "transaction.finish();\n }", "pre_mask_code": "package ru.noties.performance_test.sprkls;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport java.util.List;\nimport ru.noties.storm.InstanceCreator;\nimport ru.noties.performance_test.AbsTest;\nimport ru.noties.performance_test.BuildConfig;\nimport ru.noties.performance_test.OpType;\nimport ru.noties.performance_test.Time;\nimport se.emilsjolander.sprinkles.Migration;\nimport se.emilsjolander.sprinkles.Query;\nimport se.emilsjolander.sprinkles.Sprinkles;\nimport se.emilsjolander.sprinkles.Transaction;\nimport se.emilsjolander.sprinkles.typeserializers.SqlType;\nimport se.emilsjolander.sprinkles.typeserializers.TypeSerializer;\n\n/**\n * Created by Dimitry Ivanov (example@nnthink.com) on 12.02.2015.\n */\npublic class SprinklesTest extends AbsTest {\n\n public SprinklesTest(Context context, OpType[] opTypes, int rounds, Time time, boolean isLast) {\n super(context, opTypes, rounds, time, isLast);\n }\n\n @Override\n protected void setUp() {\n open();\n }\n\n @Override\n protected void tearDown() {\n }\n\n @Override\n protected void insert(List list) {\n final Transaction transaction = new Transaction();\n for (SprinklesObject object : list) {\n object.save(transaction);\n }\n transaction.setSuccessful(true);\n ", "post_mask_code": "\n\n @Override\n protected void queryOne(long id) {\n Query.one(SprinklesObject.class, \"where id = ?\", id).get();\n }\n\n @Override\n protected void queryAll() {\n Query.all(SprinklesObject.class).get().asList();\n }\n\n @Override\n protected void deleteAll() {\n // no exceptions are thrown, catch it yourself\n // throws IndexOutOfBoundsException if passed db version is not starts with 0\n // java.lang.IllegalStateException: Couldn't read row 5470, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.\n final Transaction dt = new Transaction();\n for (SprinklesObject sprinklesObject : Query.all(SprinklesObject.class).get()) {\n sprinklesObject.delete(dt);\n }\n dt.setSuccessful(true);\n dt.finish();\n }\n\n Sprinkles open() {\n final BuildConfig.ORM orm = getORM();\n final Sprinkles sprinkles = Sprinkles.init(getContext(), orm.getDbName(), orm.getDbVersion());\n sprinkles.addMigration(new Migration() {\n\n @Override\n protected void doMigration(SQLiteDatabase sqLiteDatabase) {\n final String sql = \"CREATE TABLE IF NOT EXISTS `sprinkles_object` (\" + \"`someString` TEXT, \" + \"`someBool` INTEGER, \" + \"`id`INTEGER PRIMARY KEY AUTOINCREMENT, \" + \"`someDouble` REAL, \" + \"`someLong` INTEGER, \" + \"`someFloat` REAL, \" + \"`someInt` INTEGER, \" + \"`someShort` INTEGER\" + \");\";\n sqLiteDatabase.execSQL(sql);\n }\n });\n // no short type\n sprinkles.registerType(Short.TYPE, new TypeSerializer() {\n\n @Override\n public Short unpack(Cursor c, String name) {\n return c.getShort(c.getColumnIndex(name));\n }\n\n @Override\n public void pack(Short object, ContentValues cv, String name) {\n cv.put(name, object);\n }\n\n @Override\n public String toSql(Short object) {\n return String.valueOf(object);\n }\n\n @Override\n public SqlType getSqlType() {\n return SqlType.INTEGER;\n }\n });\n return sprinkles;\n }\n\n @Override\n protected InstanceCreator getInstanceCreator() {\n return new InstanceCreator() {\n\n @Override\n public SprinklesObject create(Class clazz) {\n return new SprinklesObject();\n }\n };\n }\n\n @Override\n protected BuildConfig.ORM getORM() {\n return BuildConfig.ORM.SPRINKLES;\n }\n}\n"} {"task_id": "Java_631", "language": "Java", "task_type": "single_line", "source_file": "java/github/noties/Storm/performance_test/src/main/java/ru/noties/performance_test/sprkls/SprinklesTest.java", "mask_start_position": 3489, "mask_end_position": 3510, "canonical_solution": "ring.valueOf(object);", "pre_mask_code": "package ru.noties.performance_test.sprkls;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport java.util.List;\nimport ru.noties.storm.InstanceCreator;\nimport ru.noties.performance_test.AbsTest;\nimport ru.noties.performance_test.BuildConfig;\nimport ru.noties.performance_test.OpType;\nimport ru.noties.performance_test.Time;\nimport se.emilsjolander.sprinkles.Migration;\nimport se.emilsjolander.sprinkles.Query;\nimport se.emilsjolander.sprinkles.Sprinkles;\nimport se.emilsjolander.sprinkles.Transaction;\nimport se.emilsjolander.sprinkles.typeserializers.SqlType;\nimport se.emilsjolander.sprinkles.typeserializers.TypeSerializer;\n\n/**\n * Created by Dimitry Ivanov (example@nnthink.com) on 12.02.2015.\n */\npublic class SprinklesTest extends AbsTest {\n\n public SprinklesTest(Context context, OpType[] opTypes, int rounds, Time time, boolean isLast) {\n super(context, opTypes, rounds, time, isLast);\n }\n\n @Override\n protected void setUp() {\n open();\n }\n\n @Override\n protected void tearDown() {\n }\n\n @Override\n protected void insert(List list) {\n final Transaction transaction = new Transaction();\n for (SprinklesObject object : list) {\n object.save(transaction);\n }\n transaction.setSuccessful(true);\n transaction.finish();\n }\n\n @Override\n protected void queryOne(long id) {\n Query.one(SprinklesObject.class, \"where id = ?\", id).get();\n }\n\n @Override\n protected void queryAll() {\n Query.all(SprinklesObject.class).get().asList();\n }\n\n @Override\n protected void deleteAll() {\n // no exceptions are thrown, catch it yourself\n // throws IndexOutOfBoundsException if passed db version is not starts with 0\n // java.lang.IllegalStateException: Couldn't read row 5470, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.\n final Transaction dt = new Transaction();\n for (SprinklesObject sprinklesObject : Query.all(SprinklesObject.class).get()) {\n sprinklesObject.delete(dt);\n }\n dt.setSuccessful(true);\n dt.finish();\n }\n\n Sprinkles open() {\n final BuildConfig.ORM orm = getORM();\n final Sprinkles sprinkles = Sprinkles.init(getContext(), orm.getDbName(), orm.getDbVersion());\n sprinkles.addMigration(new Migration() {\n\n @Override\n protected void doMigration(SQLiteDatabase sqLiteDatabase) {\n final String sql = \"CREATE TABLE IF NOT EXISTS `sprinkles_object` (\" + \"`someString` TEXT, \" + \"`someBool` INTEGER, \" + \"`id`INTEGER PRIMARY KEY AUTOINCREMENT, \" + \"`someDouble` REAL, \" + \"`someLong` INTEGER, \" + \"`someFloat` REAL, \" + \"`someInt` INTEGER, \" + \"`someShort` INTEGER\" + \");\";\n sqLiteDatabase.execSQL(sql);\n }\n });\n // no short type\n sprinkles.registerType(Short.TYPE, new TypeSerializer() {\n\n @Override\n public Short unpack(Cursor c, String name) {\n return c.getShort(c.getColumnIndex(name));\n }\n\n @Override\n public void pack(Short object, ContentValues cv, String name) {\n cv.put(name, object);\n }\n\n @Override\n public String toSql(Short object) {\n return St", "post_mask_code": "\n }\n\n @Override\n public SqlType getSqlType() {\n return SqlType.INTEGER;\n }\n });\n return sprinkles;\n }\n\n @Override\n protected InstanceCreator getInstanceCreator() {\n return new InstanceCreator() {\n\n @Override\n public SprinklesObject create(Class clazz) {\n return new SprinklesObject();\n }\n };\n }\n\n @Override\n protected BuildConfig.ORM getORM() {\n return BuildConfig.ORM.SPRINKLES;\n }\n}\n"} {"task_id": "Java_632", "language": "Java", "task_type": "empty", "source_file": "java/github/noties/Storm/performance_test/src/main/java/ru/noties/performance_test/sprkls/SprinklesTest.java", "mask_start_position": 729, "mask_end_position": 729, "canonical_solution": "", "pre_mask_code": "package ru.noties.performance_test.sprkls;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport java.util.List;\nimport ru.noties.storm.InstanceCreator;\nimport ru.noties.performance_test.AbsTest;\nimport ru.noties.performance_test.BuildConfig;\nimport ru.noties.performance_test.OpType;\nimport ru.noties.performance_test.Time;\nimport se.emilsjolander.sprinkles.Migration;\nimport se.emilsjolander.sprinkles.Query;\nimport se.emilsjolander.sprinkles.Sprinkles;\nimport se.emilsjolander.sprinkles.Transaction;\nimport se.emilsjolander.sprinkles.typeserializers.SqlType;\nimport se.emilsjolander.sprinkles.typeserializers.TypeSerializer", "post_mask_code": ";\n\n/**\n * Created by Dimitry Ivanov (example@nnthink.com) on 12.02.2015.\n */\npublic class SprinklesTest extends AbsTest {\n\n public SprinklesTest(Context context, OpType[] opTypes, int rounds, Time time, boolean isLast) {\n super(context, opTypes, rounds, time, isLast);\n }\n\n @Override\n protected void setUp() {\n open();\n }\n\n @Override\n protected void tearDown() {\n }\n\n @Override\n protected void insert(List list) {\n final Transaction transaction = new Transaction();\n for (SprinklesObject object : list) {\n object.save(transaction);\n }\n transaction.setSuccessful(true);\n transaction.finish();\n }\n\n @Override\n protected void queryOne(long id) {\n Query.one(SprinklesObject.class, \"where id = ?\", id).get();\n }\n\n @Override\n protected void queryAll() {\n Query.all(SprinklesObject.class).get().asList();\n }\n\n @Override\n protected void deleteAll() {\n // no exceptions are thrown, catch it yourself\n // throws IndexOutOfBoundsException if passed db version is not starts with 0\n // java.lang.IllegalStateException: Couldn't read row 5470, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.\n final Transaction dt = new Transaction();\n for (SprinklesObject sprinklesObject : Query.all(SprinklesObject.class).get()) {\n sprinklesObject.delete(dt);\n }\n dt.setSuccessful(true);\n dt.finish();\n }\n\n Sprinkles open() {\n final BuildConfig.ORM orm = getORM();\n final Sprinkles sprinkles = Sprinkles.init(getContext(), orm.getDbName(), orm.getDbVersion());\n sprinkles.addMigration(new Migration() {\n\n @Override\n protected void doMigration(SQLiteDatabase sqLiteDatabase) {\n final String sql = \"CREATE TABLE IF NOT EXISTS `sprinkles_object` (\" + \"`someString` TEXT, \" + \"`someBool` INTEGER, \" + \"`id`INTEGER PRIMARY KEY AUTOINCREMENT, \" + \"`someDouble` REAL, \" + \"`someLong` INTEGER, \" + \"`someFloat` REAL, \" + \"`someInt` INTEGER, \" + \"`someShort` INTEGER\" + \");\";\n sqLiteDatabase.execSQL(sql);\n }\n });\n // no short type\n sprinkles.registerType(Short.TYPE, new TypeSerializer() {\n\n @Override\n public Short unpack(Cursor c, String name) {\n return c.getShort(c.getColumnIndex(name));\n }\n\n @Override\n public void pack(Short object, ContentValues cv, String name) {\n cv.put(name, object);\n }\n\n @Override\n public String toSql(Short object) {\n return String.valueOf(object);\n }\n\n @Override\n public SqlType getSqlType() {\n return SqlType.INTEGER;\n }\n });\n return sprinkles;\n }\n\n @Override\n protected InstanceCreator getInstanceCreator() {\n return new InstanceCreator() {\n\n @Override\n public SprinklesObject create(Class clazz) {\n return new SprinklesObject();\n }\n };\n }\n\n @Override\n protected BuildConfig.ORM getORM() {\n return BuildConfig.ORM.SPRINKLES;\n }\n}\n"} {"task_id": "Java_633", "language": "Java", "task_type": "method_signature", "source_file": "java/github/WeTheInternet/xapi/common/src/api/java/xapi/util/X_Template.java", "mask_start_position": 225, "mask_end_position": 409, "canonical_solution": "@MagicMethod(generator = @Reference(typeName = \"xapi.javac.dev.template.TemplateInjector\"))\n @SuppressWarnings(\"unchecked\")\n public static T processTemplate(String template) ", "pre_mask_code": "package xapi.util;\n\nimport xapi.annotation.compile.Reference;\nimport xapi.annotation.compile.MagicMethod;\n\n/**\n * @author James X. Nelson (example@nnthink.com)\n * Created on 4/2/16.\n */\npublic class X_Template {\n\n ", "post_mask_code": "{\n // replaced with generated code\n return (T) template;\n }\n\n private X_Template() {\n }\n}\n"} {"task_id": "Java_634", "language": "Java", "task_type": "method_body", "source_file": "java/github/WeTheInternet/xapi/common/src/api/java/xapi/util/X_Template.java", "mask_start_position": 409, "mask_end_position": 485, "canonical_solution": "{\n // replaced with generated code\n return (T) template;\n }", "pre_mask_code": "package xapi.util;\n\nimport xapi.annotation.compile.Reference;\nimport xapi.annotation.compile.MagicMethod;\n\n/**\n * @author James X. Nelson (example@nnthink.com)\n * Created on 4/2/16.\n */\npublic class X_Template {\n\n @MagicMethod(generator = @Reference(typeName = \"xapi.javac.dev.template.TemplateInjector\"))\n @SuppressWarnings(\"unchecked\")\n public static T processTemplate(String template) ", "post_mask_code": "\n\n private X_Template() {\n }\n}\n"} {"task_id": "Java_635", "language": "Java", "task_type": "single_line", "source_file": "java/github/WeTheInternet/xapi/common/src/api/java/xapi/util/X_Template.java", "mask_start_position": 463, "mask_end_position": 479, "canonical_solution": "rn (T) template;", "pre_mask_code": "package xapi.util;\n\nimport xapi.annotation.compile.Reference;\nimport xapi.annotation.compile.MagicMethod;\n\n/**\n * @author James X. Nelson (example@nnthink.com)\n * Created on 4/2/16.\n */\npublic class X_Template {\n\n @MagicMethod(generator = @Reference(typeName = \"xapi.javac.dev.template.TemplateInjector\"))\n @SuppressWarnings(\"unchecked\")\n public static T processTemplate(String template) {\n // replaced with generated code\n retu", "post_mask_code": "\n }\n\n private X_Template() {\n }\n}\n"} {"task_id": "Java_636", "language": "Java", "task_type": "empty", "source_file": "java/github/WeTheInternet/xapi/common/src/api/java/xapi/util/X_Template.java", "mask_start_position": 259, "mask_end_position": 259, "canonical_solution": "", "pre_mask_code": "package xapi.util;\n\nimport xapi.annotation.compile.Reference;\nimport xapi.annotation.compile.MagicMethod;\n\n/**\n * @author James X. Nelson (example@nnthink.com)\n * Created on 4/2/16.\n */\npublic class X_Template {\n\n @MagicMethod(generator = @Referenc", "post_mask_code": "e(typeName = \"xapi.javac.dev.template.TemplateInjector\"))\n @SuppressWarnings(\"unchecked\")\n public static T processTemplate(String template) {\n // replaced with generated code\n return (T) template;\n }\n\n private X_Template() {\n }\n}\n"} {"task_id": "Java_637", "language": "Java", "task_type": "method_signature", "source_file": "java/github/codedrinker/letscode/src/main/java/ValidParentheses/AzusaMutan/zhanweta/ValidParentheses.java", "mask_start_position": 136, "mask_end_position": 175, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "package ValidParentheses.AzusaMutan.zhanweta;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ValidParentheses {\n\n ", "post_mask_code": "{\n String s = \"{[]}\";\n System.out.println(isValid(s));\n }\n\n public static boolean isValid(String s) {\n // 栈\n List chars = new ArrayList();\n // s长度\n int len = s.length();\n // 将s的前半部分去重部分放入一个栈中\n for (int i = 0; i < len; i++) {\n // chars长度为0,则直接添加\n if (chars.size() == 0)\n chars.add(s.charAt(i));\n else // chars长度不为0且与栈顶数据不等,入栈\n {\n switch(s.charAt(i)) {\n case ')':\n {\n if (chars.get(chars.size() - 1) == '(')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case '}':\n {\n if (chars.get(chars.size() - 1) == '{')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case ']':\n {\n if (chars.get(chars.size() - 1) == '[')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n default:\n chars.add(s.charAt(i));\n break;\n }\n }\n }\n return chars.size() == 0;\n }\n}\n"} {"task_id": "Java_638", "language": "Java", "task_type": "method_body", "source_file": "java/github/codedrinker/letscode/src/main/java/ValidParentheses/AzusaMutan/zhanweta/ValidParentheses.java", "mask_start_position": 175, "mask_end_position": 249, "canonical_solution": "{\n String s = \"{[]}\";\n System.out.println(isValid(s));\n }", "pre_mask_code": "package ValidParentheses.AzusaMutan.zhanweta;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ValidParentheses {\n\n public static void main(String[] args) ", "post_mask_code": "\n\n public static boolean isValid(String s) {\n // 栈\n List chars = new ArrayList();\n // s长度\n int len = s.length();\n // 将s的前半部分去重部分放入一个栈中\n for (int i = 0; i < len; i++) {\n // chars长度为0,则直接添加\n if (chars.size() == 0)\n chars.add(s.charAt(i));\n else // chars长度不为0且与栈顶数据不等,入栈\n {\n switch(s.charAt(i)) {\n case ')':\n {\n if (chars.get(chars.size() - 1) == '(')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case '}':\n {\n if (chars.get(chars.size() - 1) == '{')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case ']':\n {\n if (chars.get(chars.size() - 1) == '[')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n default:\n chars.add(s.charAt(i));\n break;\n }\n }\n }\n return chars.size() == 0;\n }\n}\n"} {"task_id": "Java_639", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/codedrinker/letscode/src/main/java/ValidParentheses/AzusaMutan/zhanweta/ValidParentheses.java", "mask_start_position": 296, "mask_end_position": 369, "canonical_solution": "\n // 栈\n List chars = new ArrayList();", "pre_mask_code": "package ValidParentheses.AzusaMutan.zhanweta;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ValidParentheses {\n\n public static void main(String[] args) {\n String s = \"{[]}\";\n System.out.println(isValid(s));\n }\n\n public static boolean isValid(String s) {", "post_mask_code": "\n // s长度\n int len = s.length();\n // 将s的前半部分去重部分放入一个栈中\n for (int i = 0; i < len; i++) {\n // chars长度为0,则直接添加\n if (chars.size() == 0)\n chars.add(s.charAt(i));\n else // chars长度不为0且与栈顶数据不等,入栈\n {\n switch(s.charAt(i)) {\n case ')':\n {\n if (chars.get(chars.size() - 1) == '(')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case '}':\n {\n if (chars.get(chars.size() - 1) == '{')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case ']':\n {\n if (chars.get(chars.size() - 1) == '[')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n default:\n chars.add(s.charAt(i));\n break;\n }\n }\n }\n return chars.size() == 0;\n }\n}\n"} {"task_id": "Java_640", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/codedrinker/letscode/src/main/java/ValidParentheses/AzusaMutan/zhanweta/ValidParentheses.java", "mask_start_position": 378, "mask_end_position": 443, "canonical_solution": "// s长度\n int len = s.length();\n // 将s的前半部分去重部分放入一个栈中", "pre_mask_code": "package ValidParentheses.AzusaMutan.zhanweta;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ValidParentheses {\n\n public static void main(String[] args) {\n String s = \"{[]}\";\n System.out.println(isValid(s));\n }\n\n public static boolean isValid(String s) {\n // 栈\n List chars = new ArrayList();\n ", "post_mask_code": "\n for (int i = 0; i < len; i++) {\n // chars长度为0,则直接添加\n if (chars.size() == 0)\n chars.add(s.charAt(i));\n else // chars长度不为0且与栈顶数据不等,入栈\n {\n switch(s.charAt(i)) {\n case ')':\n {\n if (chars.get(chars.size() - 1) == '(')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case '}':\n {\n if (chars.get(chars.size() - 1) == '{')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case ']':\n {\n if (chars.get(chars.size() - 1) == '[')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n default:\n chars.add(s.charAt(i));\n break;\n }\n }\n }\n return chars.size() == 0;\n }\n}\n"} {"task_id": "Java_641", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/codedrinker/letscode/src/main/java/ValidParentheses/AzusaMutan/zhanweta/ValidParentheses.java", "mask_start_position": 452, "mask_end_position": 1887, "canonical_solution": "for (int i = 0; i < len; i++) {\n // chars长度为0,则直接添加\n if (chars.size() == 0)\n chars.add(s.charAt(i));\n else // chars长度不为0且与栈顶数据不等,入栈\n {\n switch(s.charAt(i)) {\n case ')':\n {\n if (chars.get(chars.size() - 1) == '(')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case '}':\n {\n if (chars.get(chars.size() - 1) == '{')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case ']':\n {\n if (chars.get(chars.size() - 1) == '[')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n default:\n chars.add(s.charAt(i));\n break;\n }\n }\n }\n return chars.size() == 0;\n }", "pre_mask_code": "package ValidParentheses.AzusaMutan.zhanweta;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ValidParentheses {\n\n public static void main(String[] args) {\n String s = \"{[]}\";\n System.out.println(isValid(s));\n }\n\n public static boolean isValid(String s) {\n // 栈\n List chars = new ArrayList();\n // s长度\n int len = s.length();\n // 将s的前半部分去重部分放入一个栈中\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_642", "language": "Java", "task_type": "single_line", "source_file": "java/github/codedrinker/letscode/src/main/java/ValidParentheses/AzusaMutan/zhanweta/ValidParentheses.java", "mask_start_position": 1872, "mask_end_position": 1881, "canonical_solution": "e() == 0;", "pre_mask_code": "package ValidParentheses.AzusaMutan.zhanweta;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ValidParentheses {\n\n public static void main(String[] args) {\n String s = \"{[]}\";\n System.out.println(isValid(s));\n }\n\n public static boolean isValid(String s) {\n // 栈\n List chars = new ArrayList();\n // s长度\n int len = s.length();\n // 将s的前半部分去重部分放入一个栈中\n for (int i = 0; i < len; i++) {\n // chars长度为0,则直接添加\n if (chars.size() == 0)\n chars.add(s.charAt(i));\n else // chars长度不为0且与栈顶数据不等,入栈\n {\n switch(s.charAt(i)) {\n case ')':\n {\n if (chars.get(chars.size() - 1) == '(')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case '}':\n {\n if (chars.get(chars.size() - 1) == '{')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case ']':\n {\n if (chars.get(chars.size() - 1) == '[')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n default:\n chars.add(s.charAt(i));\n break;\n }\n }\n }\n return chars.siz", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_643", "language": "Java", "task_type": "if_statement", "source_file": "java/github/codedrinker/letscode/src/main/java/ValidParentheses/AzusaMutan/zhanweta/ValidParentheses.java", "mask_start_position": 768, "mask_end_position": 960, "canonical_solution": "if (chars.get(chars.size() - 1) == '(')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));", "pre_mask_code": "package ValidParentheses.AzusaMutan.zhanweta;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ValidParentheses {\n\n public static void main(String[] args) {\n String s = \"{[]}\";\n System.out.println(isValid(s));\n }\n\n public static boolean isValid(String s) {\n // 栈\n List chars = new ArrayList();\n // s长度\n int len = s.length();\n // 将s的前半部分去重部分放入一个栈中\n for (int i = 0; i < len; i++) {\n // chars长度为0,则直接添加\n if (chars.size() == 0)\n chars.add(s.charAt(i));\n else // chars长度不为0且与栈顶数据不等,入栈\n {\n switch(s.charAt(i)) {\n case ')':\n {\n ", "post_mask_code": "\n break;\n }\n case '}':\n {\n if (chars.get(chars.size() - 1) == '{')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case ']':\n {\n if (chars.get(chars.size() - 1) == '[')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n default:\n chars.add(s.charAt(i));\n break;\n }\n }\n }\n return chars.size() == 0;\n }\n}\n"} {"task_id": "Java_644", "language": "Java", "task_type": "empty", "source_file": "java/github/codedrinker/letscode/src/main/java/ValidParentheses/AzusaMutan/zhanweta/ValidParentheses.java", "mask_start_position": 1106, "mask_end_position": 1106, "canonical_solution": "", "pre_mask_code": "package ValidParentheses.AzusaMutan.zhanweta;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ValidParentheses {\n\n public static void main(String[] args) {\n String s = \"{[]}\";\n System.out.println(isValid(s));\n }\n\n public static boolean isValid(String s) {\n // 栈\n List chars = new ArrayList();\n // s长度\n int len = s.length();\n // 将s的前半部分去重部分放入一个栈中\n for (int i = 0; i < len; i++) {\n // chars长度为0,则直接添加\n if (chars.size() == 0)\n chars.add(s.charAt(i));\n else // chars长度不为0且与栈顶数据不等,入栈\n {\n switch(s.charAt(i)) {\n case ')':\n {\n if (chars.get(chars.size() - 1) == '(')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case '}':\n {\n ", "post_mask_code": "if (chars.get(chars.size() - 1) == '{')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n case ']':\n {\n if (chars.get(chars.size() - 1) == '[')\n chars.remove(chars.size() - 1);\n else\n chars.add(s.charAt(i));\n break;\n }\n default:\n chars.add(s.charAt(i));\n break;\n }\n }\n }\n return chars.size() == 0;\n }\n}\n"} {"task_id": "Java_645", "language": "Java", "task_type": "method_signature", "source_file": "java/github/gama-platform/gama/irit.gaml.extensions.database/src/irit/gaml/extensions/database/skills/MDXSkill.java", "mask_start_position": 1683, "mask_end_position": 1785, "canonical_solution": "@action(name = \"timeStamp\")\n public Long timeStamp(final IScope scope) throws GamaRuntimeException ", "pre_mask_code": "/**\n * ******************************************************************************************\n *\n * 'MDXSkill.java', in plugin 'irit.gaml.extensions.database', is part of the source code of the GAMA modeling and\n * simulation platform. (v. 1.8.1)\n *\n * Visit http://example.com for license information and developers contact.\n *\n * ********************************************************************************************\n */\npackage irit.gaml.extensions.database.skills;\n\nimport org.olap4j.OlapConnection;\nimport msi.gama.database.mdx.MdxConnection;\nimport msi.gama.database.mdx.MdxUtils;\nimport msi.gama.precompiler.GamlAnnotations.action;\nimport msi.gama.precompiler.GamlAnnotations.arg;\nimport msi.gama.precompiler.GamlAnnotations.doc;\nimport msi.gama.precompiler.GamlAnnotations.skill;\nimport msi.gama.precompiler.IConcept;\nimport msi.gama.runtime.IScope;\nimport msi.gama.runtime.exceptions.GamaRuntimeException;\nimport msi.gama.util.IList;\nimport msi.gaml.skills.Skill;\nimport msi.gaml.types.IType;\n\n/*\n * @Author TRUONG Minh Thai\n *\n * @Supervisors: Christophe Sibertin-BLANC Fredric AMBLARD Benoit GAUDOU\n *\n * Description: Define MultiDimensional eXpressions features\n *\n * created date: 04-Jul-2013 Modified: 08-Jul-2013: - correct error on testConnection method - add question mark and\n * values to select method\n *\n * Last Modified: 08-Jul-2013\n */\n@skill(name = \"MDXSKILL\", concept = { IConcept.DATABASE, IConcept.SKILL })\n@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n@doc(\"This skill allows agents to be provided with actions and attributes in order to connect to MDX databases\")\npublic class MDXSkill extends Skill {\n\n // Get current time of system\n ", "post_mask_code": "{\n final Long timeStamp = System.currentTimeMillis();\n return timeStamp;\n }\n\n /*\n\t * Make a connection to BDMS\n\t *\n\t * @syntax: do action: connectDB { arg params value:[ \"olaptype\":\"SSAS/XMLA\" //\"MONDRIAN\"/\"MONDRIAN/XMLA\"\n\t * \"dbtype\":\"SQLSERVER\", //MySQL/postgres/sqlite \"url\":\"host address\", \"port\":\"port number\", \"database\":\n\t * \"database name\", \"user\": \"user name\", \"passwd\": \"password\" ]; }\n\t */\n @action(name = \"testConnection\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")) })\n public boolean testConnection(final IScope scope) {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n try (final OlapConnection oConn = MdxUtils.createConnectionObject(scope, params).connectMDB(scope)) {\n oConn.getCatalog();\n } catch (final Exception e) {\n return false;\n }\n return true;\n }\n\n @action(name = \"select\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")), @arg(name = \"onColumns\", type = IType.STRING, optional = false, doc = @doc(\"select string with question marks\")), @arg(name = \"onRows\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"from\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"where\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"values\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")) })\n public IList select_QM(final IScope scope) throws GamaRuntimeException {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n final String onRowStr = (String) scope.getArg(\"onRows\", IType.STRING);\n final String onColumnStr = (String) scope.getArg(\"onColumns\", IType.STRING);\n final String fromStr = (String) scope.getArg(\"from\", IType.STRING);\n final String whereStr = scope.hasArg(\"where\") ? (String) scope.getArg(\"where\", IType.STRING) : null;\n final IList values = scope.hasArg(\"values\") ? (IList) scope.getArg(\"values\", IType.LIST) : null;\n String selectStr = \"SELECT \" + onColumnStr + \" ON COLUMNS , \" + onRowStr + \" ON ROWS FROM \" + fromStr;\n MdxConnection mdxConn;\n IList repRequest;\n try {\n if (whereStr != null) {\n selectStr = selectStr + \" WHERE \" + whereStr;\n }\n mdxConn = MdxUtils.createConnectionObject(scope, params);\n if (values != null) {\n repRequest = mdxConn.selectMDB(scope, selectStr, values);\n } else {\n repRequest = mdxConn.selectMDB(scope, selectStr);\n }\n } catch (final Exception e) {\n e.printStackTrace();\n throw GamaRuntimeException.error(\"MDXSkill.select_QM: \" + e.toString(), scope);\n }\n return repRequest;\n }\n}\n"} {"task_id": "Java_646", "language": "Java", "task_type": "method_body", "source_file": "java/github/gama-platform/gama/irit.gaml.extensions.database/src/irit/gaml/extensions/database/skills/MDXSkill.java", "mask_start_position": 2404, "mask_end_position": 2736, "canonical_solution": "{\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n try (final OlapConnection oConn = MdxUtils.createConnectionObject(scope, params).connectMDB(scope)) {\n oConn.getCatalog();\n } catch (final Exception e) {\n return false;\n }\n return true;\n }", "pre_mask_code": "/**\n * ******************************************************************************************\n *\n * 'MDXSkill.java', in plugin 'irit.gaml.extensions.database', is part of the source code of the GAMA modeling and\n * simulation platform. (v. 1.8.1)\n *\n * Visit http://example.com for license information and developers contact.\n *\n * ********************************************************************************************\n */\npackage irit.gaml.extensions.database.skills;\n\nimport org.olap4j.OlapConnection;\nimport msi.gama.database.mdx.MdxConnection;\nimport msi.gama.database.mdx.MdxUtils;\nimport msi.gama.precompiler.GamlAnnotations.action;\nimport msi.gama.precompiler.GamlAnnotations.arg;\nimport msi.gama.precompiler.GamlAnnotations.doc;\nimport msi.gama.precompiler.GamlAnnotations.skill;\nimport msi.gama.precompiler.IConcept;\nimport msi.gama.runtime.IScope;\nimport msi.gama.runtime.exceptions.GamaRuntimeException;\nimport msi.gama.util.IList;\nimport msi.gaml.skills.Skill;\nimport msi.gaml.types.IType;\n\n/*\n * @Author TRUONG Minh Thai\n *\n * @Supervisors: Christophe Sibertin-BLANC Fredric AMBLARD Benoit GAUDOU\n *\n * Description: Define MultiDimensional eXpressions features\n *\n * created date: 04-Jul-2013 Modified: 08-Jul-2013: - correct error on testConnection method - add question mark and\n * values to select method\n *\n * Last Modified: 08-Jul-2013\n */\n@skill(name = \"MDXSKILL\", concept = { IConcept.DATABASE, IConcept.SKILL })\n@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n@doc(\"This skill allows agents to be provided with actions and attributes in order to connect to MDX databases\")\npublic class MDXSkill extends Skill {\n\n // Get current time of system\n @action(name = \"timeStamp\")\n public Long timeStamp(final IScope scope) throws GamaRuntimeException {\n final Long timeStamp = System.currentTimeMillis();\n return timeStamp;\n }\n\n /*\n\t * Make a connection to BDMS\n\t *\n\t * @syntax: do action: connectDB { arg params value:[ \"olaptype\":\"SSAS/XMLA\" //\"MONDRIAN\"/\"MONDRIAN/XMLA\"\n\t * \"dbtype\":\"SQLSERVER\", //MySQL/postgres/sqlite \"url\":\"host address\", \"port\":\"port number\", \"database\":\n\t * \"database name\", \"user\": \"user name\", \"passwd\": \"password\" ]; }\n\t */\n @action(name = \"testConnection\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")) })\n public boolean testConnection(final IScope scope) ", "post_mask_code": "\n\n @action(name = \"select\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")), @arg(name = \"onColumns\", type = IType.STRING, optional = false, doc = @doc(\"select string with question marks\")), @arg(name = \"onRows\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"from\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"where\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"values\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")) })\n public IList select_QM(final IScope scope) throws GamaRuntimeException {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n final String onRowStr = (String) scope.getArg(\"onRows\", IType.STRING);\n final String onColumnStr = (String) scope.getArg(\"onColumns\", IType.STRING);\n final String fromStr = (String) scope.getArg(\"from\", IType.STRING);\n final String whereStr = scope.hasArg(\"where\") ? (String) scope.getArg(\"where\", IType.STRING) : null;\n final IList values = scope.hasArg(\"values\") ? (IList) scope.getArg(\"values\", IType.LIST) : null;\n String selectStr = \"SELECT \" + onColumnStr + \" ON COLUMNS , \" + onRowStr + \" ON ROWS FROM \" + fromStr;\n MdxConnection mdxConn;\n IList repRequest;\n try {\n if (whereStr != null) {\n selectStr = selectStr + \" WHERE \" + whereStr;\n }\n mdxConn = MdxUtils.createConnectionObject(scope, params);\n if (values != null) {\n repRequest = mdxConn.selectMDB(scope, selectStr, values);\n } else {\n repRequest = mdxConn.selectMDB(scope, selectStr);\n }\n } catch (final Exception e) {\n e.printStackTrace();\n throw GamaRuntimeException.error(\"MDXSkill.select_QM: \" + e.toString(), scope);\n }\n return repRequest;\n }\n}\n"} {"task_id": "Java_647", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/gama-platform/gama/irit.gaml.extensions.database/src/irit/gaml/extensions/database/skills/MDXSkill.java", "mask_start_position": 3587, "mask_end_position": 3915, "canonical_solution": "\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n final String onRowStr = (String) scope.getArg(\"onRows\", IType.STRING);\n final String onColumnStr = (String) scope.getArg(\"onColumns\", IType.STRING);\n final String fromStr = (String) scope.getArg(\"from\", IType.STRING);", "pre_mask_code": "/**\n * ******************************************************************************************\n *\n * 'MDXSkill.java', in plugin 'irit.gaml.extensions.database', is part of the source code of the GAMA modeling and\n * simulation platform. (v. 1.8.1)\n *\n * Visit http://example.com for license information and developers contact.\n *\n * ********************************************************************************************\n */\npackage irit.gaml.extensions.database.skills;\n\nimport org.olap4j.OlapConnection;\nimport msi.gama.database.mdx.MdxConnection;\nimport msi.gama.database.mdx.MdxUtils;\nimport msi.gama.precompiler.GamlAnnotations.action;\nimport msi.gama.precompiler.GamlAnnotations.arg;\nimport msi.gama.precompiler.GamlAnnotations.doc;\nimport msi.gama.precompiler.GamlAnnotations.skill;\nimport msi.gama.precompiler.IConcept;\nimport msi.gama.runtime.IScope;\nimport msi.gama.runtime.exceptions.GamaRuntimeException;\nimport msi.gama.util.IList;\nimport msi.gaml.skills.Skill;\nimport msi.gaml.types.IType;\n\n/*\n * @Author TRUONG Minh Thai\n *\n * @Supervisors: Christophe Sibertin-BLANC Fredric AMBLARD Benoit GAUDOU\n *\n * Description: Define MultiDimensional eXpressions features\n *\n * created date: 04-Jul-2013 Modified: 08-Jul-2013: - correct error on testConnection method - add question mark and\n * values to select method\n *\n * Last Modified: 08-Jul-2013\n */\n@skill(name = \"MDXSKILL\", concept = { IConcept.DATABASE, IConcept.SKILL })\n@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n@doc(\"This skill allows agents to be provided with actions and attributes in order to connect to MDX databases\")\npublic class MDXSkill extends Skill {\n\n // Get current time of system\n @action(name = \"timeStamp\")\n public Long timeStamp(final IScope scope) throws GamaRuntimeException {\n final Long timeStamp = System.currentTimeMillis();\n return timeStamp;\n }\n\n /*\n\t * Make a connection to BDMS\n\t *\n\t * @syntax: do action: connectDB { arg params value:[ \"olaptype\":\"SSAS/XMLA\" //\"MONDRIAN\"/\"MONDRIAN/XMLA\"\n\t * \"dbtype\":\"SQLSERVER\", //MySQL/postgres/sqlite \"url\":\"host address\", \"port\":\"port number\", \"database\":\n\t * \"database name\", \"user\": \"user name\", \"passwd\": \"password\" ]; }\n\t */\n @action(name = \"testConnection\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")) })\n public boolean testConnection(final IScope scope) {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n try (final OlapConnection oConn = MdxUtils.createConnectionObject(scope, params).connectMDB(scope)) {\n oConn.getCatalog();\n } catch (final Exception e) {\n return false;\n }\n return true;\n }\n\n @action(name = \"select\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")), @arg(name = \"onColumns\", type = IType.STRING, optional = false, doc = @doc(\"select string with question marks\")), @arg(name = \"onRows\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"from\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"where\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"values\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")) })\n public IList select_QM(final IScope scope) throws GamaRuntimeException {", "post_mask_code": "\n final String whereStr = scope.hasArg(\"where\") ? (String) scope.getArg(\"where\", IType.STRING) : null;\n final IList values = scope.hasArg(\"values\") ? (IList) scope.getArg(\"values\", IType.LIST) : null;\n String selectStr = \"SELECT \" + onColumnStr + \" ON COLUMNS , \" + onRowStr + \" ON ROWS FROM \" + fromStr;\n MdxConnection mdxConn;\n IList repRequest;\n try {\n if (whereStr != null) {\n selectStr = selectStr + \" WHERE \" + whereStr;\n }\n mdxConn = MdxUtils.createConnectionObject(scope, params);\n if (values != null) {\n repRequest = mdxConn.selectMDB(scope, selectStr, values);\n } else {\n repRequest = mdxConn.selectMDB(scope, selectStr);\n }\n } catch (final Exception e) {\n e.printStackTrace();\n throw GamaRuntimeException.error(\"MDXSkill.select_QM: \" + e.toString(), scope);\n }\n return repRequest;\n }\n}\n"} {"task_id": "Java_648", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/gama-platform/gama/irit.gaml.extensions.database/src/irit/gaml/extensions/database/skills/MDXSkill.java", "mask_start_position": 3924, "mask_end_position": 4287, "canonical_solution": "final String whereStr = scope.hasArg(\"where\") ? (String) scope.getArg(\"where\", IType.STRING) : null;\n final IList values = scope.hasArg(\"values\") ? (IList) scope.getArg(\"values\", IType.LIST) : null;\n String selectStr = \"SELECT \" + onColumnStr + \" ON COLUMNS , \" + onRowStr + \" ON ROWS FROM \" + fromStr;\n MdxConnection mdxConn;", "pre_mask_code": "/**\n * ******************************************************************************************\n *\n * 'MDXSkill.java', in plugin 'irit.gaml.extensions.database', is part of the source code of the GAMA modeling and\n * simulation platform. (v. 1.8.1)\n *\n * Visit http://example.com for license information and developers contact.\n *\n * ********************************************************************************************\n */\npackage irit.gaml.extensions.database.skills;\n\nimport org.olap4j.OlapConnection;\nimport msi.gama.database.mdx.MdxConnection;\nimport msi.gama.database.mdx.MdxUtils;\nimport msi.gama.precompiler.GamlAnnotations.action;\nimport msi.gama.precompiler.GamlAnnotations.arg;\nimport msi.gama.precompiler.GamlAnnotations.doc;\nimport msi.gama.precompiler.GamlAnnotations.skill;\nimport msi.gama.precompiler.IConcept;\nimport msi.gama.runtime.IScope;\nimport msi.gama.runtime.exceptions.GamaRuntimeException;\nimport msi.gama.util.IList;\nimport msi.gaml.skills.Skill;\nimport msi.gaml.types.IType;\n\n/*\n * @Author TRUONG Minh Thai\n *\n * @Supervisors: Christophe Sibertin-BLANC Fredric AMBLARD Benoit GAUDOU\n *\n * Description: Define MultiDimensional eXpressions features\n *\n * created date: 04-Jul-2013 Modified: 08-Jul-2013: - correct error on testConnection method - add question mark and\n * values to select method\n *\n * Last Modified: 08-Jul-2013\n */\n@skill(name = \"MDXSKILL\", concept = { IConcept.DATABASE, IConcept.SKILL })\n@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n@doc(\"This skill allows agents to be provided with actions and attributes in order to connect to MDX databases\")\npublic class MDXSkill extends Skill {\n\n // Get current time of system\n @action(name = \"timeStamp\")\n public Long timeStamp(final IScope scope) throws GamaRuntimeException {\n final Long timeStamp = System.currentTimeMillis();\n return timeStamp;\n }\n\n /*\n\t * Make a connection to BDMS\n\t *\n\t * @syntax: do action: connectDB { arg params value:[ \"olaptype\":\"SSAS/XMLA\" //\"MONDRIAN\"/\"MONDRIAN/XMLA\"\n\t * \"dbtype\":\"SQLSERVER\", //MySQL/postgres/sqlite \"url\":\"host address\", \"port\":\"port number\", \"database\":\n\t * \"database name\", \"user\": \"user name\", \"passwd\": \"password\" ]; }\n\t */\n @action(name = \"testConnection\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")) })\n public boolean testConnection(final IScope scope) {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n try (final OlapConnection oConn = MdxUtils.createConnectionObject(scope, params).connectMDB(scope)) {\n oConn.getCatalog();\n } catch (final Exception e) {\n return false;\n }\n return true;\n }\n\n @action(name = \"select\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")), @arg(name = \"onColumns\", type = IType.STRING, optional = false, doc = @doc(\"select string with question marks\")), @arg(name = \"onRows\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"from\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"where\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"values\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")) })\n public IList select_QM(final IScope scope) throws GamaRuntimeException {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n final String onRowStr = (String) scope.getArg(\"onRows\", IType.STRING);\n final String onColumnStr = (String) scope.getArg(\"onColumns\", IType.STRING);\n final String fromStr = (String) scope.getArg(\"from\", IType.STRING);\n ", "post_mask_code": "\n IList repRequest;\n try {\n if (whereStr != null) {\n selectStr = selectStr + \" WHERE \" + whereStr;\n }\n mdxConn = MdxUtils.createConnectionObject(scope, params);\n if (values != null) {\n repRequest = mdxConn.selectMDB(scope, selectStr, values);\n } else {\n repRequest = mdxConn.selectMDB(scope, selectStr);\n }\n } catch (final Exception e) {\n e.printStackTrace();\n throw GamaRuntimeException.error(\"MDXSkill.select_QM: \" + e.toString(), scope);\n }\n return repRequest;\n }\n}\n"} {"task_id": "Java_649", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/gama-platform/gama/irit.gaml.extensions.database/src/irit/gaml/extensions/database/skills/MDXSkill.java", "mask_start_position": 4296, "mask_end_position": 4932, "canonical_solution": "IList repRequest;\n try {\n if (whereStr != null) {\n selectStr = selectStr + \" WHERE \" + whereStr;\n }\n mdxConn = MdxUtils.createConnectionObject(scope, params);\n if (values != null) {\n repRequest = mdxConn.selectMDB(scope, selectStr, values);\n } else {\n repRequest = mdxConn.selectMDB(scope, selectStr);\n }\n } catch (final Exception e) {\n e.printStackTrace();\n throw GamaRuntimeException.error(\"MDXSkill.select_QM: \" + e.toString(), scope);\n }\n return repRequest;\n }", "pre_mask_code": "/**\n * ******************************************************************************************\n *\n * 'MDXSkill.java', in plugin 'irit.gaml.extensions.database', is part of the source code of the GAMA modeling and\n * simulation platform. (v. 1.8.1)\n *\n * Visit http://example.com for license information and developers contact.\n *\n * ********************************************************************************************\n */\npackage irit.gaml.extensions.database.skills;\n\nimport org.olap4j.OlapConnection;\nimport msi.gama.database.mdx.MdxConnection;\nimport msi.gama.database.mdx.MdxUtils;\nimport msi.gama.precompiler.GamlAnnotations.action;\nimport msi.gama.precompiler.GamlAnnotations.arg;\nimport msi.gama.precompiler.GamlAnnotations.doc;\nimport msi.gama.precompiler.GamlAnnotations.skill;\nimport msi.gama.precompiler.IConcept;\nimport msi.gama.runtime.IScope;\nimport msi.gama.runtime.exceptions.GamaRuntimeException;\nimport msi.gama.util.IList;\nimport msi.gaml.skills.Skill;\nimport msi.gaml.types.IType;\n\n/*\n * @Author TRUONG Minh Thai\n *\n * @Supervisors: Christophe Sibertin-BLANC Fredric AMBLARD Benoit GAUDOU\n *\n * Description: Define MultiDimensional eXpressions features\n *\n * created date: 04-Jul-2013 Modified: 08-Jul-2013: - correct error on testConnection method - add question mark and\n * values to select method\n *\n * Last Modified: 08-Jul-2013\n */\n@skill(name = \"MDXSKILL\", concept = { IConcept.DATABASE, IConcept.SKILL })\n@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n@doc(\"This skill allows agents to be provided with actions and attributes in order to connect to MDX databases\")\npublic class MDXSkill extends Skill {\n\n // Get current time of system\n @action(name = \"timeStamp\")\n public Long timeStamp(final IScope scope) throws GamaRuntimeException {\n final Long timeStamp = System.currentTimeMillis();\n return timeStamp;\n }\n\n /*\n\t * Make a connection to BDMS\n\t *\n\t * @syntax: do action: connectDB { arg params value:[ \"olaptype\":\"SSAS/XMLA\" //\"MONDRIAN\"/\"MONDRIAN/XMLA\"\n\t * \"dbtype\":\"SQLSERVER\", //MySQL/postgres/sqlite \"url\":\"host address\", \"port\":\"port number\", \"database\":\n\t * \"database name\", \"user\": \"user name\", \"passwd\": \"password\" ]; }\n\t */\n @action(name = \"testConnection\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")) })\n public boolean testConnection(final IScope scope) {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n try (final OlapConnection oConn = MdxUtils.createConnectionObject(scope, params).connectMDB(scope)) {\n oConn.getCatalog();\n } catch (final Exception e) {\n return false;\n }\n return true;\n }\n\n @action(name = \"select\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")), @arg(name = \"onColumns\", type = IType.STRING, optional = false, doc = @doc(\"select string with question marks\")), @arg(name = \"onRows\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"from\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"where\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"values\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")) })\n public IList select_QM(final IScope scope) throws GamaRuntimeException {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n final String onRowStr = (String) scope.getArg(\"onRows\", IType.STRING);\n final String onColumnStr = (String) scope.getArg(\"onColumns\", IType.STRING);\n final String fromStr = (String) scope.getArg(\"from\", IType.STRING);\n final String whereStr = scope.hasArg(\"where\") ? (String) scope.getArg(\"where\", IType.STRING) : null;\n final IList values = scope.hasArg(\"values\") ? (IList) scope.getArg(\"values\", IType.LIST) : null;\n String selectStr = \"SELECT \" + onColumnStr + \" ON COLUMNS , \" + onRowStr + \" ON ROWS FROM \" + fromStr;\n MdxConnection mdxConn;\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_650", "language": "Java", "task_type": "single_line", "source_file": "java/github/gama-platform/gama/irit.gaml.extensions.database/src/irit/gaml/extensions/database/skills/MDXSkill.java", "mask_start_position": 2467, "mask_end_position": 2493, "canonical_solution": "tArg(\"params\", IType.MAP);", "pre_mask_code": "/**\n * ******************************************************************************************\n *\n * 'MDXSkill.java', in plugin 'irit.gaml.extensions.database', is part of the source code of the GAMA modeling and\n * simulation platform. (v. 1.8.1)\n *\n * Visit http://example.com for license information and developers contact.\n *\n * ********************************************************************************************\n */\npackage irit.gaml.extensions.database.skills;\n\nimport org.olap4j.OlapConnection;\nimport msi.gama.database.mdx.MdxConnection;\nimport msi.gama.database.mdx.MdxUtils;\nimport msi.gama.precompiler.GamlAnnotations.action;\nimport msi.gama.precompiler.GamlAnnotations.arg;\nimport msi.gama.precompiler.GamlAnnotations.doc;\nimport msi.gama.precompiler.GamlAnnotations.skill;\nimport msi.gama.precompiler.IConcept;\nimport msi.gama.runtime.IScope;\nimport msi.gama.runtime.exceptions.GamaRuntimeException;\nimport msi.gama.util.IList;\nimport msi.gaml.skills.Skill;\nimport msi.gaml.types.IType;\n\n/*\n * @Author TRUONG Minh Thai\n *\n * @Supervisors: Christophe Sibertin-BLANC Fredric AMBLARD Benoit GAUDOU\n *\n * Description: Define MultiDimensional eXpressions features\n *\n * created date: 04-Jul-2013 Modified: 08-Jul-2013: - correct error on testConnection method - add question mark and\n * values to select method\n *\n * Last Modified: 08-Jul-2013\n */\n@skill(name = \"MDXSKILL\", concept = { IConcept.DATABASE, IConcept.SKILL })\n@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n@doc(\"This skill allows agents to be provided with actions and attributes in order to connect to MDX databases\")\npublic class MDXSkill extends Skill {\n\n // Get current time of system\n @action(name = \"timeStamp\")\n public Long timeStamp(final IScope scope) throws GamaRuntimeException {\n final Long timeStamp = System.currentTimeMillis();\n return timeStamp;\n }\n\n /*\n\t * Make a connection to BDMS\n\t *\n\t * @syntax: do action: connectDB { arg params value:[ \"olaptype\":\"SSAS/XMLA\" //\"MONDRIAN\"/\"MONDRIAN/XMLA\"\n\t * \"dbtype\":\"SQLSERVER\", //MySQL/postgres/sqlite \"url\":\"host address\", \"port\":\"port number\", \"database\":\n\t * \"database name\", \"user\": \"user name\", \"passwd\": \"password\" ]; }\n\t */\n @action(name = \"testConnection\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")) })\n public boolean testConnection(final IScope scope) {\n final java.util.Map params = (java.util.Map) scope.ge", "post_mask_code": "\n try (final OlapConnection oConn = MdxUtils.createConnectionObject(scope, params).connectMDB(scope)) {\n oConn.getCatalog();\n } catch (final Exception e) {\n return false;\n }\n return true;\n }\n\n @action(name = \"select\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")), @arg(name = \"onColumns\", type = IType.STRING, optional = false, doc = @doc(\"select string with question marks\")), @arg(name = \"onRows\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"from\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"where\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"values\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")) })\n public IList select_QM(final IScope scope) throws GamaRuntimeException {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n final String onRowStr = (String) scope.getArg(\"onRows\", IType.STRING);\n final String onColumnStr = (String) scope.getArg(\"onColumns\", IType.STRING);\n final String fromStr = (String) scope.getArg(\"from\", IType.STRING);\n final String whereStr = scope.hasArg(\"where\") ? (String) scope.getArg(\"where\", IType.STRING) : null;\n final IList values = scope.hasArg(\"values\") ? (IList) scope.getArg(\"values\", IType.LIST) : null;\n String selectStr = \"SELECT \" + onColumnStr + \" ON COLUMNS , \" + onRowStr + \" ON ROWS FROM \" + fromStr;\n MdxConnection mdxConn;\n IList repRequest;\n try {\n if (whereStr != null) {\n selectStr = selectStr + \" WHERE \" + whereStr;\n }\n mdxConn = MdxUtils.createConnectionObject(scope, params);\n if (values != null) {\n repRequest = mdxConn.selectMDB(scope, selectStr, values);\n } else {\n repRequest = mdxConn.selectMDB(scope, selectStr);\n }\n } catch (final Exception e) {\n e.printStackTrace();\n throw GamaRuntimeException.error(\"MDXSkill.select_QM: \" + e.toString(), scope);\n }\n return repRequest;\n }\n}\n"} {"task_id": "Java_651", "language": "Java", "task_type": "if_statement", "source_file": "java/github/gama-platform/gama/irit.gaml.extensions.database/src/irit/gaml/extensions/database/skills/MDXSkill.java", "mask_start_position": 4530, "mask_end_position": 4726, "canonical_solution": "if (values != null) {\n repRequest = mdxConn.selectMDB(scope, selectStr, values);\n } else {\n repRequest = mdxConn.selectMDB(scope, selectStr);\n }", "pre_mask_code": "/**\n * ******************************************************************************************\n *\n * 'MDXSkill.java', in plugin 'irit.gaml.extensions.database', is part of the source code of the GAMA modeling and\n * simulation platform. (v. 1.8.1)\n *\n * Visit http://example.com for license information and developers contact.\n *\n * ********************************************************************************************\n */\npackage irit.gaml.extensions.database.skills;\n\nimport org.olap4j.OlapConnection;\nimport msi.gama.database.mdx.MdxConnection;\nimport msi.gama.database.mdx.MdxUtils;\nimport msi.gama.precompiler.GamlAnnotations.action;\nimport msi.gama.precompiler.GamlAnnotations.arg;\nimport msi.gama.precompiler.GamlAnnotations.doc;\nimport msi.gama.precompiler.GamlAnnotations.skill;\nimport msi.gama.precompiler.IConcept;\nimport msi.gama.runtime.IScope;\nimport msi.gama.runtime.exceptions.GamaRuntimeException;\nimport msi.gama.util.IList;\nimport msi.gaml.skills.Skill;\nimport msi.gaml.types.IType;\n\n/*\n * @Author TRUONG Minh Thai\n *\n * @Supervisors: Christophe Sibertin-BLANC Fredric AMBLARD Benoit GAUDOU\n *\n * Description: Define MultiDimensional eXpressions features\n *\n * created date: 04-Jul-2013 Modified: 08-Jul-2013: - correct error on testConnection method - add question mark and\n * values to select method\n *\n * Last Modified: 08-Jul-2013\n */\n@skill(name = \"MDXSKILL\", concept = { IConcept.DATABASE, IConcept.SKILL })\n@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n@doc(\"This skill allows agents to be provided with actions and attributes in order to connect to MDX databases\")\npublic class MDXSkill extends Skill {\n\n // Get current time of system\n @action(name = \"timeStamp\")\n public Long timeStamp(final IScope scope) throws GamaRuntimeException {\n final Long timeStamp = System.currentTimeMillis();\n return timeStamp;\n }\n\n /*\n\t * Make a connection to BDMS\n\t *\n\t * @syntax: do action: connectDB { arg params value:[ \"olaptype\":\"SSAS/XMLA\" //\"MONDRIAN\"/\"MONDRIAN/XMLA\"\n\t * \"dbtype\":\"SQLSERVER\", //MySQL/postgres/sqlite \"url\":\"host address\", \"port\":\"port number\", \"database\":\n\t * \"database name\", \"user\": \"user name\", \"passwd\": \"password\" ]; }\n\t */\n @action(name = \"testConnection\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")) })\n public boolean testConnection(final IScope scope) {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n try (final OlapConnection oConn = MdxUtils.createConnectionObject(scope, params).connectMDB(scope)) {\n oConn.getCatalog();\n } catch (final Exception e) {\n return false;\n }\n return true;\n }\n\n @action(name = \"select\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")), @arg(name = \"onColumns\", type = IType.STRING, optional = false, doc = @doc(\"select string with question marks\")), @arg(name = \"onRows\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"from\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"where\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"values\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")) })\n public IList select_QM(final IScope scope) throws GamaRuntimeException {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n final String onRowStr = (String) scope.getArg(\"onRows\", IType.STRING);\n final String onColumnStr = (String) scope.getArg(\"onColumns\", IType.STRING);\n final String fromStr = (String) scope.getArg(\"from\", IType.STRING);\n final String whereStr = scope.hasArg(\"where\") ? (String) scope.getArg(\"where\", IType.STRING) : null;\n final IList values = scope.hasArg(\"values\") ? (IList) scope.getArg(\"values\", IType.LIST) : null;\n String selectStr = \"SELECT \" + onColumnStr + \" ON COLUMNS , \" + onRowStr + \" ON ROWS FROM \" + fromStr;\n MdxConnection mdxConn;\n IList repRequest;\n try {\n if (whereStr != null) {\n selectStr = selectStr + \" WHERE \" + whereStr;\n }\n mdxConn = MdxUtils.createConnectionObject(scope, params);\n ", "post_mask_code": "\n } catch (final Exception e) {\n e.printStackTrace();\n throw GamaRuntimeException.error(\"MDXSkill.select_QM: \" + e.toString(), scope);\n }\n return repRequest;\n }\n}\n"} {"task_id": "Java_652", "language": "Java", "task_type": "empty", "source_file": "java/github/gama-platform/gama/irit.gaml.extensions.database/src/irit/gaml/extensions/database/skills/MDXSkill.java", "mask_start_position": 1864, "mask_end_position": 1864, "canonical_solution": "", "pre_mask_code": "/**\n * ******************************************************************************************\n *\n * 'MDXSkill.java', in plugin 'irit.gaml.extensions.database', is part of the source code of the GAMA modeling and\n * simulation platform. (v. 1.8.1)\n *\n * Visit http://example.com for license information and developers contact.\n *\n * ********************************************************************************************\n */\npackage irit.gaml.extensions.database.skills;\n\nimport org.olap4j.OlapConnection;\nimport msi.gama.database.mdx.MdxConnection;\nimport msi.gama.database.mdx.MdxUtils;\nimport msi.gama.precompiler.GamlAnnotations.action;\nimport msi.gama.precompiler.GamlAnnotations.arg;\nimport msi.gama.precompiler.GamlAnnotations.doc;\nimport msi.gama.precompiler.GamlAnnotations.skill;\nimport msi.gama.precompiler.IConcept;\nimport msi.gama.runtime.IScope;\nimport msi.gama.runtime.exceptions.GamaRuntimeException;\nimport msi.gama.util.IList;\nimport msi.gaml.skills.Skill;\nimport msi.gaml.types.IType;\n\n/*\n * @Author TRUONG Minh Thai\n *\n * @Supervisors: Christophe Sibertin-BLANC Fredric AMBLARD Benoit GAUDOU\n *\n * Description: Define MultiDimensional eXpressions features\n *\n * created date: 04-Jul-2013 Modified: 08-Jul-2013: - correct error on testConnection method - add question mark and\n * values to select method\n *\n * Last Modified: 08-Jul-2013\n */\n@skill(name = \"MDXSKILL\", concept = { IConcept.DATABASE, IConcept.SKILL })\n@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n@doc(\"This skill allows agents to be provided with actions and attributes in order to connect to MDX databases\")\npublic class MDXSkill extends Skill {\n\n // Get current time of system\n @action(name = \"timeStamp\")\n public Long timeStamp(final IScope scope) throws GamaRuntimeException {\n final Long timeStamp = System.currentTimeMillis();\n return tim", "post_mask_code": "eStamp;\n }\n\n /*\n\t * Make a connection to BDMS\n\t *\n\t * @syntax: do action: connectDB { arg params value:[ \"olaptype\":\"SSAS/XMLA\" //\"MONDRIAN\"/\"MONDRIAN/XMLA\"\n\t * \"dbtype\":\"SQLSERVER\", //MySQL/postgres/sqlite \"url\":\"host address\", \"port\":\"port number\", \"database\":\n\t * \"database name\", \"user\": \"user name\", \"passwd\": \"password\" ]; }\n\t */\n @action(name = \"testConnection\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")) })\n public boolean testConnection(final IScope scope) {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n try (final OlapConnection oConn = MdxUtils.createConnectionObject(scope, params).connectMDB(scope)) {\n oConn.getCatalog();\n } catch (final Exception e) {\n return false;\n }\n return true;\n }\n\n @action(name = \"select\", args = { @arg(name = \"params\", type = IType.MAP, optional = false, doc = @doc(\"Connection parameters\")), @arg(name = \"onColumns\", type = IType.STRING, optional = false, doc = @doc(\"select string with question marks\")), @arg(name = \"onRows\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"from\", type = IType.LIST, optional = false, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"where\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")), @arg(name = \"values\", type = IType.LIST, optional = true, doc = @doc(\"List of values that are used to replace question marks\")) })\n public IList select_QM(final IScope scope) throws GamaRuntimeException {\n final java.util.Map params = (java.util.Map) scope.getArg(\"params\", IType.MAP);\n final String onRowStr = (String) scope.getArg(\"onRows\", IType.STRING);\n final String onColumnStr = (String) scope.getArg(\"onColumns\", IType.STRING);\n final String fromStr = (String) scope.getArg(\"from\", IType.STRING);\n final String whereStr = scope.hasArg(\"where\") ? (String) scope.getArg(\"where\", IType.STRING) : null;\n final IList values = scope.hasArg(\"values\") ? (IList) scope.getArg(\"values\", IType.LIST) : null;\n String selectStr = \"SELECT \" + onColumnStr + \" ON COLUMNS , \" + onRowStr + \" ON ROWS FROM \" + fromStr;\n MdxConnection mdxConn;\n IList repRequest;\n try {\n if (whereStr != null) {\n selectStr = selectStr + \" WHERE \" + whereStr;\n }\n mdxConn = MdxUtils.createConnectionObject(scope, params);\n if (values != null) {\n repRequest = mdxConn.selectMDB(scope, selectStr, values);\n } else {\n repRequest = mdxConn.selectMDB(scope, selectStr);\n }\n } catch (final Exception e) {\n e.printStackTrace();\n throw GamaRuntimeException.error(\"MDXSkill.select_QM: \" + e.toString(), scope);\n }\n return repRequest;\n }\n}\n"} {"task_id": "Java_653", "language": "Java", "task_type": "empty", "source_file": "java/github/beanit/asn1bean/projects/asn1bean-compiler/src/main/java/com/beanit/asn1bean/compiler/model/AsnDefinedValue.java", "mask_start_position": 2, "mask_end_position": 2, "canonical_solution": "", "pre_mask_code": "pa", "post_mask_code": "ckage com.beanit.asn1bean.compiler.model;\n\npublic class AsnDefinedValue {\n\n public boolean isDotPresent;\n\n public String moduleIdentifier;\n\n public String name;\n}\n"} {"task_id": "Java_654", "language": "Java", "task_type": "method_signature", "source_file": "java/github/batfish/batfish/projects/batfish/src/main/java/org/batfish/grammar/f5_bigip_imish/parsing/F5BigipImishBaseParser.java", "mask_start_position": 1228, "mask_end_position": 1271, "canonical_solution": "protected static boolean isUint32(Token t) ", "pre_mask_code": "package org.batfish.grammar.f5_bigip_imish.parsing;\n\nimport com.google.common.primitives.Ints;\nimport com.google.common.primitives.Longs;\nimport javax.annotation.ParametersAreNonnullByDefault;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.batfish.grammar.BatfishParser;\n\n/**\n * F5 BIG-IP imish parser base class providing validation functionality on top of {@link\n * BatfishParser}.\n */\n@ParametersAreNonnullByDefault\npublic abstract class F5BigipImishBaseParser extends BatfishParser {\n\n /**\n * Return {@code true} iff {@code t}'s text represents a valid IPv4 prefix-length in base 10.\n */\n protected static boolean isIpPrefixLength(Token t) {\n Integer val = Ints.tryParse(t.getText());\n return val != null && 0 <= val && val <= 32;\n }\n\n /**\n * Returns {@code true} iff {@code t}'s text represents a valid unsigned 16-bit integer in base\n * 10.\n */\n protected static boolean isUint16(Token t) {\n Integer val = Ints.tryParse(t.getText());\n return val != null && val == (val & 0xFFFFL);\n }\n\n /**\n * Returns {@code true} iff {@code t}'s text represents a valid unsigned 32-bit integer in base\n * 10.\n */\n ", "post_mask_code": "{\n Long val = Longs.tryParse(t.getText());\n return val != null && val == (val & 0xFFFFFFFFL);\n }\n\n public F5BigipImishBaseParser(TokenStream input) {\n super(input);\n }\n}\n"} {"task_id": "Java_655", "language": "Java", "task_type": "method_body", "source_file": "java/github/batfish/batfish/projects/batfish/src/main/java/org/batfish/grammar/f5_bigip_imish/parsing/F5BigipImishBaseParser.java", "mask_start_position": 1271, "mask_end_position": 1384, "canonical_solution": "{\n Long val = Longs.tryParse(t.getText());\n return val != null && val == (val & 0xFFFFFFFFL);\n }", "pre_mask_code": "package org.batfish.grammar.f5_bigip_imish.parsing;\n\nimport com.google.common.primitives.Ints;\nimport com.google.common.primitives.Longs;\nimport javax.annotation.ParametersAreNonnullByDefault;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.batfish.grammar.BatfishParser;\n\n/**\n * F5 BIG-IP imish parser base class providing validation functionality on top of {@link\n * BatfishParser}.\n */\n@ParametersAreNonnullByDefault\npublic abstract class F5BigipImishBaseParser extends BatfishParser {\n\n /**\n * Return {@code true} iff {@code t}'s text represents a valid IPv4 prefix-length in base 10.\n */\n protected static boolean isIpPrefixLength(Token t) {\n Integer val = Ints.tryParse(t.getText());\n return val != null && 0 <= val && val <= 32;\n }\n\n /**\n * Returns {@code true} iff {@code t}'s text represents a valid unsigned 16-bit integer in base\n * 10.\n */\n protected static boolean isUint16(Token t) {\n Integer val = Ints.tryParse(t.getText());\n return val != null && val == (val & 0xFFFFL);\n }\n\n /**\n * Returns {@code true} iff {@code t}'s text represents a valid unsigned 32-bit integer in base\n * 10.\n */\n protected static boolean isUint32(Token t) ", "post_mask_code": "\n\n public F5BigipImishBaseParser(TokenStream input) {\n super(input);\n }\n}\n"} {"task_id": "Java_656", "language": "Java", "task_type": "single_line", "source_file": "java/github/batfish/batfish/projects/batfish/src/main/java/org/batfish/grammar/f5_bigip_imish/parsing/F5BigipImishBaseParser.java", "mask_start_position": 1283, "mask_end_position": 1320, "canonical_solution": "ng val = Longs.tryParse(t.getText());", "pre_mask_code": "package org.batfish.grammar.f5_bigip_imish.parsing;\n\nimport com.google.common.primitives.Ints;\nimport com.google.common.primitives.Longs;\nimport javax.annotation.ParametersAreNonnullByDefault;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.batfish.grammar.BatfishParser;\n\n/**\n * F5 BIG-IP imish parser base class providing validation functionality on top of {@link\n * BatfishParser}.\n */\n@ParametersAreNonnullByDefault\npublic abstract class F5BigipImishBaseParser extends BatfishParser {\n\n /**\n * Return {@code true} iff {@code t}'s text represents a valid IPv4 prefix-length in base 10.\n */\n protected static boolean isIpPrefixLength(Token t) {\n Integer val = Ints.tryParse(t.getText());\n return val != null && 0 <= val && val <= 32;\n }\n\n /**\n * Returns {@code true} iff {@code t}'s text represents a valid unsigned 16-bit integer in base\n * 10.\n */\n protected static boolean isUint16(Token t) {\n Integer val = Ints.tryParse(t.getText());\n return val != null && val == (val & 0xFFFFL);\n }\n\n /**\n * Returns {@code true} iff {@code t}'s text represents a valid unsigned 32-bit integer in base\n * 10.\n */\n protected static boolean isUint32(Token t) {\n Lo", "post_mask_code": "\n return val != null && val == (val & 0xFFFFFFFFL);\n }\n\n public F5BigipImishBaseParser(TokenStream input) {\n super(input);\n }\n}\n"} {"task_id": "Java_657", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/batfish/batfish/projects/batfish/src/main/java/org/batfish/grammar/f5_bigip_imish/parsing/F5BigipImishBaseParser.java", "mask_start_position": 647, "mask_end_position": 808, "canonical_solution": "protected static boolean isIpPrefixLength(Token t) {\n Integer val = Ints.tryParse(t.getText());\n return val != null && 0 <= val && val <= 32;\n }", "pre_mask_code": "package org.batfish.grammar.f5_bigip_imish.parsing;\n\nimport com.google.common.primitives.Ints;\nimport com.google.common.primitives.Longs;\nimport javax.annotation.ParametersAreNonnullByDefault;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.batfish.grammar.BatfishParser;\n\n/**\n * F5 BIG-IP imish parser base class providing validation functionality on top of {@link\n * BatfishParser}.\n */\n@ParametersAreNonnullByDefault\npublic abstract class F5BigipImishBaseParser extends BatfishParser {\n\n /**\n * Return {@code true} iff {@code t}'s text represents a valid IPv4 prefix-length in base 10.\n */\n ", "post_mask_code": "\n\n /**\n * Returns {@code true} iff {@code t}'s text represents a valid unsigned 16-bit integer in base\n * 10.\n */\n protected static boolean isUint16(Token t) {\n Integer val = Ints.tryParse(t.getText());\n return val != null && val == (val & 0xFFFFL);\n }\n\n /**\n * Returns {@code true} iff {@code t}'s text represents a valid unsigned 32-bit integer in base\n * 10.\n */\n protected static boolean isUint32(Token t) {\n Long val = Longs.tryParse(t.getText());\n return val != null && val == (val & 0xFFFFFFFFL);\n }\n\n public F5BigipImishBaseParser(TokenStream input) {\n super(input);\n }\n}\n"} {"task_id": "Java_658", "language": "Java", "task_type": "empty", "source_file": "java/github/batfish/batfish/projects/batfish/src/main/java/org/batfish/grammar/f5_bigip_imish/parsing/F5BigipImishBaseParser.java", "mask_start_position": 586, "mask_end_position": 586, "canonical_solution": "", "pre_mask_code": "package org.batfish.grammar.f5_bigip_imish.parsing;\n\nimport com.google.common.primitives.Ints;\nimport com.google.common.primitives.Longs;\nimport javax.annotation.ParametersAreNonnullByDefault;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.batfish.grammar.BatfishParser;\n\n/**\n * F5 BIG-IP imish parser base class providing validation functionality on top of {@link\n * BatfishParser}.\n */\n@ParametersAreNonnullByDefault\npublic abstract class F5BigipImishBaseParser extends BatfishParser {\n\n /**\n * Return {@code true} iff {@code t}'s text r", "post_mask_code": "epresents a valid IPv4 prefix-length in base 10.\n */\n protected static boolean isIpPrefixLength(Token t) {\n Integer val = Ints.tryParse(t.getText());\n return val != null && 0 <= val && val <= 32;\n }\n\n /**\n * Returns {@code true} iff {@code t}'s text represents a valid unsigned 16-bit integer in base\n * 10.\n */\n protected static boolean isUint16(Token t) {\n Integer val = Ints.tryParse(t.getText());\n return val != null && val == (val & 0xFFFFL);\n }\n\n /**\n * Returns {@code true} iff {@code t}'s text represents a valid unsigned 32-bit integer in base\n * 10.\n */\n protected static boolean isUint32(Token t) {\n Long val = Longs.tryParse(t.getText());\n return val != null && val == (val & 0xFFFFFFFFL);\n }\n\n public F5BigipImishBaseParser(TokenStream input) {\n super(input);\n }\n}\n"} {"task_id": "Java_659", "language": "Java", "task_type": "method_signature", "source_file": "java/github/FeatureIDE/FeatureIDE/plugins/de.ovgu.featureide.examples/featureide_examples/BerkeleyDB-FH-Java/features/base/com/sleepycat/bind/tuple/CharacterBinding.java", "mask_start_position": 1355, "mask_end_position": 1407, "canonical_solution": "public static char entryToChar(DatabaseEntry entry) ", "pre_mask_code": "package com.sleepycat.bind.tuple;\n\nimport com.sleepycat.je.DatabaseEntry;\nimport de.ovgu.cide.jakutil.*;\n\n/**\n * A concrete TupleBinding for a Character\n * primitive wrapper or a char primitive.\n *

\n * There are two ways to use this class:\n *

\n *
    \n *
  1. When using the {@link com.sleepycat.je} package directly, the static\n * methods in this class can be used to convert between primitive values and{@link DatabaseEntry} objects.
  2. \n *
  3. When using the {@link com.sleepycat.collections} package, an instance of\n * this class can be used with any stored collection. The easiest way to obtain\n * a binding instance is with the {@link TupleBinding#getPrimitiveBinding}method.
  4. \n *
\n */\npublic class CharacterBinding extends TupleBinding {\n\n private static final int CHAR_SIZE = 2;\n\n public Object entryToObject(TupleInput input) {\n return new Character(input.readChar());\n }\n\n public void objectToEntry(Object object, TupleOutput output) {\n output.writeChar(((Character) object).charValue());\n }\n\n protected TupleOutput getTupleOutput(Object object) {\n return sizedOutput();\n }\n\n /**\n * Converts an entry buffer into a simple char value.\n * @param entryis the source entry buffer.\n * @return the resulting value.\n */\n ", "post_mask_code": "{\n return entryToInput(entry).readChar();\n }\n\n /**\n * Converts a simple char value into an entry buffer.\n * @param valis the source value.\n * @param entryis the destination entry buffer.\n */\n public static void charToEntry(char val, DatabaseEntry entry) {\n outputToEntry(sizedOutput().writeChar(val), entry);\n }\n\n /**\n * Returns a tuple output object of the exact size needed, to avoid wasting\n * space when a single primitive is output.\n */\n private static TupleOutput sizedOutput() {\n return new TupleOutput(new byte[CHAR_SIZE]);\n }\n}\n"} {"task_id": "Java_660", "language": "Java", "task_type": "method_body", "source_file": "java/github/FeatureIDE/FeatureIDE/plugins/de.ovgu.featureide.examples/featureide_examples/BerkeleyDB-FH-Java/features/base/com/sleepycat/bind/tuple/CharacterBinding.java", "mask_start_position": 1017, "mask_end_position": 1084, "canonical_solution": "{\n output.writeChar(((Character) object).charValue());\n }", "pre_mask_code": "package com.sleepycat.bind.tuple;\n\nimport com.sleepycat.je.DatabaseEntry;\nimport de.ovgu.cide.jakutil.*;\n\n/**\n * A concrete TupleBinding for a Character\n * primitive wrapper or a char primitive.\n *

\n * There are two ways to use this class:\n *

\n *
    \n *
  1. When using the {@link com.sleepycat.je} package directly, the static\n * methods in this class can be used to convert between primitive values and{@link DatabaseEntry} objects.
  2. \n *
  3. When using the {@link com.sleepycat.collections} package, an instance of\n * this class can be used with any stored collection. The easiest way to obtain\n * a binding instance is with the {@link TupleBinding#getPrimitiveBinding}method.
  4. \n *
\n */\npublic class CharacterBinding extends TupleBinding {\n\n private static final int CHAR_SIZE = 2;\n\n public Object entryToObject(TupleInput input) {\n return new Character(input.readChar());\n }\n\n public void objectToEntry(Object object, TupleOutput output) ", "post_mask_code": "\n\n protected TupleOutput getTupleOutput(Object object) {\n return sizedOutput();\n }\n\n /**\n * Converts an entry buffer into a simple char value.\n * @param entryis the source entry buffer.\n * @return the resulting value.\n */\n public static char entryToChar(DatabaseEntry entry) {\n return entryToInput(entry).readChar();\n }\n\n /**\n * Converts a simple char value into an entry buffer.\n * @param valis the source value.\n * @param entryis the destination entry buffer.\n */\n public static void charToEntry(char val, DatabaseEntry entry) {\n outputToEntry(sizedOutput().writeChar(val), entry);\n }\n\n /**\n * Returns a tuple output object of the exact size needed, to avoid wasting\n * space when a single primitive is output.\n */\n private static TupleOutput sizedOutput() {\n return new TupleOutput(new byte[CHAR_SIZE]);\n }\n}\n"} {"task_id": "Java_661", "language": "Java", "task_type": "single_line", "source_file": "java/github/FeatureIDE/FeatureIDE/plugins/de.ovgu.featureide.examples/featureide_examples/BerkeleyDB-FH-Java/features/base/com/sleepycat/bind/tuple/CharacterBinding.java", "mask_start_position": 1064, "mask_end_position": 1078, "canonical_solution": ".charValue());", "pre_mask_code": "package com.sleepycat.bind.tuple;\n\nimport com.sleepycat.je.DatabaseEntry;\nimport de.ovgu.cide.jakutil.*;\n\n/**\n * A concrete TupleBinding for a Character\n * primitive wrapper or a char primitive.\n *

\n * There are two ways to use this class:\n *

\n *
    \n *
  1. When using the {@link com.sleepycat.je} package directly, the static\n * methods in this class can be used to convert between primitive values and{@link DatabaseEntry} objects.
  2. \n *
  3. When using the {@link com.sleepycat.collections} package, an instance of\n * this class can be used with any stored collection. The easiest way to obtain\n * a binding instance is with the {@link TupleBinding#getPrimitiveBinding}method.
  4. \n *
\n */\npublic class CharacterBinding extends TupleBinding {\n\n private static final int CHAR_SIZE = 2;\n\n public Object entryToObject(TupleInput input) {\n return new Character(input.readChar());\n }\n\n public void objectToEntry(Object object, TupleOutput output) {\n output.writeChar(((Character) object)", "post_mask_code": "\n }\n\n protected TupleOutput getTupleOutput(Object object) {\n return sizedOutput();\n }\n\n /**\n * Converts an entry buffer into a simple char value.\n * @param entryis the source entry buffer.\n * @return the resulting value.\n */\n public static char entryToChar(DatabaseEntry entry) {\n return entryToInput(entry).readChar();\n }\n\n /**\n * Converts a simple char value into an entry buffer.\n * @param valis the source value.\n * @param entryis the destination entry buffer.\n */\n public static void charToEntry(char val, DatabaseEntry entry) {\n outputToEntry(sizedOutput().writeChar(val), entry);\n }\n\n /**\n * Returns a tuple output object of the exact size needed, to avoid wasting\n * space when a single primitive is output.\n */\n private static TupleOutput sizedOutput() {\n return new TupleOutput(new byte[CHAR_SIZE]);\n }\n}\n"} {"task_id": "Java_662", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/FeatureIDE/FeatureIDE/plugins/de.ovgu.featureide.examples/featureide_examples/BerkeleyDB-FH-Java/features/base/com/sleepycat/bind/tuple/CharacterBinding.java", "mask_start_position": 1644, "mask_end_position": 1773, "canonical_solution": "public static void charToEntry(char val, DatabaseEntry entry) {\n outputToEntry(sizedOutput().writeChar(val), entry);\n }", "pre_mask_code": "package com.sleepycat.bind.tuple;\n\nimport com.sleepycat.je.DatabaseEntry;\nimport de.ovgu.cide.jakutil.*;\n\n/**\n * A concrete TupleBinding for a Character\n * primitive wrapper or a char primitive.\n *

\n * There are two ways to use this class:\n *

\n *
    \n *
  1. When using the {@link com.sleepycat.je} package directly, the static\n * methods in this class can be used to convert between primitive values and{@link DatabaseEntry} objects.
  2. \n *
  3. When using the {@link com.sleepycat.collections} package, an instance of\n * this class can be used with any stored collection. The easiest way to obtain\n * a binding instance is with the {@link TupleBinding#getPrimitiveBinding}method.
  4. \n *
\n */\npublic class CharacterBinding extends TupleBinding {\n\n private static final int CHAR_SIZE = 2;\n\n public Object entryToObject(TupleInput input) {\n return new Character(input.readChar());\n }\n\n public void objectToEntry(Object object, TupleOutput output) {\n output.writeChar(((Character) object).charValue());\n }\n\n protected TupleOutput getTupleOutput(Object object) {\n return sizedOutput();\n }\n\n /**\n * Converts an entry buffer into a simple char value.\n * @param entryis the source entry buffer.\n * @return the resulting value.\n */\n public static char entryToChar(DatabaseEntry entry) {\n return entryToInput(entry).readChar();\n }\n\n /**\n * Converts a simple char value into an entry buffer.\n * @param valis the source value.\n * @param entryis the destination entry buffer.\n */\n ", "post_mask_code": "\n\n /**\n * Returns a tuple output object of the exact size needed, to avoid wasting\n * space when a single primitive is output.\n */\n private static TupleOutput sizedOutput() {\n return new TupleOutput(new byte[CHAR_SIZE]);\n }\n}\n"} {"task_id": "Java_663", "language": "Java", "task_type": "empty", "source_file": "java/github/FeatureIDE/FeatureIDE/plugins/de.ovgu.featureide.examples/featureide_examples/BerkeleyDB-FH-Java/features/base/com/sleepycat/bind/tuple/CharacterBinding.java", "mask_start_position": 1970, "mask_end_position": 1970, "canonical_solution": "", "pre_mask_code": "package com.sleepycat.bind.tuple;\n\nimport com.sleepycat.je.DatabaseEntry;\nimport de.ovgu.cide.jakutil.*;\n\n/**\n * A concrete TupleBinding for a Character\n * primitive wrapper or a char primitive.\n *

\n * There are two ways to use this class:\n *

\n *
    \n *
  1. When using the {@link com.sleepycat.je} package directly, the static\n * methods in this class can be used to convert between primitive values and{@link DatabaseEntry} objects.
  2. \n *
  3. When using the {@link com.sleepycat.collections} package, an instance of\n * this class can be used with any stored collection. The easiest way to obtain\n * a binding instance is with the {@link TupleBinding#getPrimitiveBinding}method.
  4. \n *
\n */\npublic class CharacterBinding extends TupleBinding {\n\n private static final int CHAR_SIZE = 2;\n\n public Object entryToObject(TupleInput input) {\n return new Character(input.readChar());\n }\n\n public void objectToEntry(Object object, TupleOutput output) {\n output.writeChar(((Character) object).charValue());\n }\n\n protected TupleOutput getTupleOutput(Object object) {\n return sizedOutput();\n }\n\n /**\n * Converts an entry buffer into a simple char value.\n * @param entryis the source entry buffer.\n * @return the resulting value.\n */\n public static char entryToChar(DatabaseEntry entry) {\n return entryToInput(entry).readChar();\n }\n\n /**\n * Converts a simple char value into an entry buffer.\n * @param valis the source value.\n * @param entryis the destination entry buffer.\n */\n public static void charToEntry(char val, DatabaseEntry entry) {\n outputToEntry(sizedOutput().writeChar(val), entry);\n }\n\n /**\n * Returns a tuple output object of the exact size needed, to avoid wasting\n * space when a single primitive is output.\n */\n private static TupleOutput sizedOutput() {\n ", "post_mask_code": " return new TupleOutput(new byte[CHAR_SIZE]);\n }\n}\n"} {"task_id": "Java_664", "language": "Java", "task_type": "method_signature", "source_file": "java/github/vespa-engine/vespa/vespajlib/src/main/java/com/yahoo/text/ForwardWriter.java", "mask_start_position": 1210, "mask_end_position": 1261, "canonical_solution": "@Override\n public GenericWriter write(double d) ", "pre_mask_code": "package com.yahoo.text;\n\nimport java.io.IOException;\n\n/**\n * Wraps another writer and also converting IOException to Exceptions.\n *\n * @author baldersheim\n * @since 5.2\n */\npublic class ForwardWriter extends GenericWriter {\n\n private final GenericWriter out;\n\n public ForwardWriter(GenericWriter writer) {\n super();\n this.out = writer;\n }\n\n @Override\n public void write(char[] c, int offset, int bytes) {\n try {\n out.write(c, offset, bytes);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(AbstractUtf8Array v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(String v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(CharSequence c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n ", "post_mask_code": "{\n try {\n out.write(d);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(float f) {\n try {\n out.write(f);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(long v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(int v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(short v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(char c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(byte b) {\n try {\n out.write(b);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(boolean v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void flush() {\n try {\n out.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void close() {\n try {\n out.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Gives access to the wrapped writer.\n * @return wrapped writer.\n */\n public GenericWriter getWriter() {\n return out;\n }\n}\n"} {"task_id": "Java_665", "language": "Java", "task_type": "method_body", "source_file": "java/github/vespa-engine/vespa/vespajlib/src/main/java/com/yahoo/text/ForwardWriter.java", "mask_start_position": 2492, "mask_end_position": 2647, "canonical_solution": "{\n try {\n out.write(b);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }", "pre_mask_code": "package com.yahoo.text;\n\nimport java.io.IOException;\n\n/**\n * Wraps another writer and also converting IOException to Exceptions.\n *\n * @author baldersheim\n * @since 5.2\n */\npublic class ForwardWriter extends GenericWriter {\n\n private final GenericWriter out;\n\n public ForwardWriter(GenericWriter writer) {\n super();\n this.out = writer;\n }\n\n @Override\n public void write(char[] c, int offset, int bytes) {\n try {\n out.write(c, offset, bytes);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(AbstractUtf8Array v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(String v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(CharSequence c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(double d) {\n try {\n out.write(d);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(float f) {\n try {\n out.write(f);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(long v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(int v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(short v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(char c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(byte b) ", "post_mask_code": "\n\n @Override\n public GenericWriter write(boolean v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void flush() {\n try {\n out.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void close() {\n try {\n out.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Gives access to the wrapped writer.\n * @return wrapped writer.\n */\n public GenericWriter getWriter() {\n return out;\n }\n}\n"} {"task_id": "Java_666", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/vespa-engine/vespa/vespajlib/src/main/java/com/yahoo/text/ForwardWriter.java", "mask_start_position": 433, "mask_end_position": 433, "canonical_solution": "", "pre_mask_code": "package com.yahoo.text;\n\nimport java.io.IOException;\n\n/**\n * Wraps another writer and also converting IOException to Exceptions.\n *\n * @author baldersheim\n * @since 5.2\n */\npublic class ForwardWriter extends GenericWriter {\n\n private final GenericWriter out;\n\n public ForwardWriter(GenericWriter writer) {\n super();\n this.out = writer;\n }\n\n @Override\n public void write(char[] c, int offset, int bytes) {", "post_mask_code": "\n try {\n out.write(c, offset, bytes);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(AbstractUtf8Array v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(String v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(CharSequence c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(double d) {\n try {\n out.write(d);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(float f) {\n try {\n out.write(f);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(long v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(int v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(short v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(char c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(byte b) {\n try {\n out.write(b);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(boolean v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void flush() {\n try {\n out.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void close() {\n try {\n out.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Gives access to the wrapped writer.\n * @return wrapped writer.\n */\n public GenericWriter getWriter() {\n return out;\n }\n}\n"} {"task_id": "Java_667", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/vespa-engine/vespa/vespajlib/src/main/java/com/yahoo/text/ForwardWriter.java", "mask_start_position": 442, "mask_end_position": 575, "canonical_solution": "try {\n out.write(c, offset, bytes);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }", "pre_mask_code": "package com.yahoo.text;\n\nimport java.io.IOException;\n\n/**\n * Wraps another writer and also converting IOException to Exceptions.\n *\n * @author baldersheim\n * @since 5.2\n */\npublic class ForwardWriter extends GenericWriter {\n\n private final GenericWriter out;\n\n public ForwardWriter(GenericWriter writer) {\n super();\n this.out = writer;\n }\n\n @Override\n public void write(char[] c, int offset, int bytes) {\n ", "post_mask_code": "\n }\n\n @Override\n public GenericWriter write(AbstractUtf8Array v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(String v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(CharSequence c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(double d) {\n try {\n out.write(d);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(float f) {\n try {\n out.write(f);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(long v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(int v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(short v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(char c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(byte b) {\n try {\n out.write(b);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(boolean v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void flush() {\n try {\n out.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void close() {\n try {\n out.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Gives access to the wrapped writer.\n * @return wrapped writer.\n */\n public GenericWriter getWriter() {\n return out;\n }\n}\n"} {"task_id": "Java_668", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/vespa-engine/vespa/vespajlib/src/main/java/com/yahoo/text/ForwardWriter.java", "mask_start_position": 580, "mask_end_position": 581, "canonical_solution": "}", "pre_mask_code": "package com.yahoo.text;\n\nimport java.io.IOException;\n\n/**\n * Wraps another writer and also converting IOException to Exceptions.\n *\n * @author baldersheim\n * @since 5.2\n */\npublic class ForwardWriter extends GenericWriter {\n\n private final GenericWriter out;\n\n public ForwardWriter(GenericWriter writer) {\n super();\n this.out = writer;\n }\n\n @Override\n public void write(char[] c, int offset, int bytes) {\n try {\n out.write(c, offset, bytes);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n ", "post_mask_code": "\n\n @Override\n public GenericWriter write(AbstractUtf8Array v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(String v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(CharSequence c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(double d) {\n try {\n out.write(d);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(float f) {\n try {\n out.write(f);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(long v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(int v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(short v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(char c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(byte b) {\n try {\n out.write(b);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(boolean v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void flush() {\n try {\n out.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void close() {\n try {\n out.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Gives access to the wrapped writer.\n * @return wrapped writer.\n */\n public GenericWriter getWriter() {\n return out;\n }\n}\n"} {"task_id": "Java_669", "language": "Java", "task_type": "single_line", "source_file": "java/github/vespa-engine/vespa/vespajlib/src/main/java/com/yahoo/text/ForwardWriter.java", "mask_start_position": 1611, "mask_end_position": 1621, "canonical_solution": "turn this;", "pre_mask_code": "package com.yahoo.text;\n\nimport java.io.IOException;\n\n/**\n * Wraps another writer and also converting IOException to Exceptions.\n *\n * @author baldersheim\n * @since 5.2\n */\npublic class ForwardWriter extends GenericWriter {\n\n private final GenericWriter out;\n\n public ForwardWriter(GenericWriter writer) {\n super();\n this.out = writer;\n }\n\n @Override\n public void write(char[] c, int offset, int bytes) {\n try {\n out.write(c, offset, bytes);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(AbstractUtf8Array v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(String v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(CharSequence c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(double d) {\n try {\n out.write(d);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(float f) {\n try {\n out.write(f);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n re", "post_mask_code": "\n }\n\n @Override\n public GenericWriter write(long v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(int v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(short v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(char c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(byte b) {\n try {\n out.write(b);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(boolean v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void flush() {\n try {\n out.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void close() {\n try {\n out.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Gives access to the wrapped writer.\n * @return wrapped writer.\n */\n public GenericWriter getWriter() {\n return out;\n }\n}\n"} {"task_id": "Java_670", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/vespa-engine/vespa/vespajlib/src/main/java/com/yahoo/text/ForwardWriter.java", "mask_start_position": 3302, "mask_end_position": 3362, "canonical_solution": "public GenericWriter getWriter() {\n return out;\n }", "pre_mask_code": "package com.yahoo.text;\n\nimport java.io.IOException;\n\n/**\n * Wraps another writer and also converting IOException to Exceptions.\n *\n * @author baldersheim\n * @since 5.2\n */\npublic class ForwardWriter extends GenericWriter {\n\n private final GenericWriter out;\n\n public ForwardWriter(GenericWriter writer) {\n super();\n this.out = writer;\n }\n\n @Override\n public void write(char[] c, int offset, int bytes) {\n try {\n out.write(c, offset, bytes);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(AbstractUtf8Array v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(String v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(CharSequence c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(double d) {\n try {\n out.write(d);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(float f) {\n try {\n out.write(f);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(long v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(int v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(short v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(char c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(byte b) {\n try {\n out.write(b);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(boolean v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void flush() {\n try {\n out.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void close() {\n try {\n out.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Gives access to the wrapped writer.\n * @return wrapped writer.\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_671", "language": "Java", "task_type": "try_statement", "source_file": "java/github/vespa-engine/vespa/vespajlib/src/main/java/com/yahoo/text/ForwardWriter.java", "mask_start_position": 2715, "mask_end_position": 2833, "canonical_solution": "try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }", "pre_mask_code": "package com.yahoo.text;\n\nimport java.io.IOException;\n\n/**\n * Wraps another writer and also converting IOException to Exceptions.\n *\n * @author baldersheim\n * @since 5.2\n */\npublic class ForwardWriter extends GenericWriter {\n\n private final GenericWriter out;\n\n public ForwardWriter(GenericWriter writer) {\n super();\n this.out = writer;\n }\n\n @Override\n public void write(char[] c, int offset, int bytes) {\n try {\n out.write(c, offset, bytes);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(AbstractUtf8Array v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(String v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(CharSequence c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(double d) {\n try {\n out.write(d);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(float f) {\n try {\n out.write(f);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(long v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(int v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(short v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(char c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(byte b) {\n try {\n out.write(b);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(boolean v) {\n ", "post_mask_code": "\n return this;\n }\n\n @Override\n public void flush() {\n try {\n out.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void close() {\n try {\n out.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Gives access to the wrapped writer.\n * @return wrapped writer.\n */\n public GenericWriter getWriter() {\n return out;\n }\n}\n"} {"task_id": "Java_672", "language": "Java", "task_type": "empty", "source_file": "java/github/vespa-engine/vespa/vespajlib/src/main/java/com/yahoo/text/ForwardWriter.java", "mask_start_position": 3044, "mask_end_position": 3044, "canonical_solution": "", "pre_mask_code": "package com.yahoo.text;\n\nimport java.io.IOException;\n\n/**\n * Wraps another writer and also converting IOException to Exceptions.\n *\n * @author baldersheim\n * @since 5.2\n */\npublic class ForwardWriter extends GenericWriter {\n\n private final GenericWriter out;\n\n public ForwardWriter(GenericWriter writer) {\n super();\n this.out = writer;\n }\n\n @Override\n public void write(char[] c, int offset, int bytes) {\n try {\n out.write(c, offset, bytes);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(AbstractUtf8Array v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(String v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(CharSequence c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(double d) {\n try {\n out.write(d);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(float f) {\n try {\n out.write(f);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(long v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void write(int v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public GenericWriter write(short v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(char c) {\n try {\n out.write(c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(byte b) {\n try {\n out.write(b);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public GenericWriter write(boolean v) {\n try {\n out.write(v);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n @Override\n public void flush() {\n try {\n out.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Over", "post_mask_code": "ride\n public void close() {\n try {\n out.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Gives access to the wrapped writer.\n * @return wrapped writer.\n */\n public GenericWriter getWriter() {\n return out;\n }\n}\n"} {"task_id": "Java_673", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jenkinsci/embeddable-build-status-plugin/src/main/java/org/jenkinsci/plugins/badge/extensions/SpecialValueParameterResolverExtension.java", "mask_start_position": 587, "mask_end_position": 650, "canonical_solution": "public String resolve(Actionable actionable, String parameter) ", "pre_mask_code": "/**\n * @author Thomas Doering (thomas-dee)\n */\npackage org.jenkinsci.plugins.badge.extensions;\n\nimport hudson.Extension;\nimport hudson.model.Actionable;\nimport hudson.model.Run;\nimport hudson.model.Job;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.jenkinsci.plugins.badge.extensionpoints.ParameterResolverExtensionPoint;\n\n@Extension\npublic class SpecialValueParameterResolverExtension implements ParameterResolverExtensionPoint {\n\n private static Pattern custom = Pattern.compile(\"(buildId|buildNumber|duration|description|displayName|startTime)\");\n\n ", "post_mask_code": "{\n if (parameter != null) {\n if (actionable instanceof Run) {\n Run run = (Run) actionable;\n /* try to match any custom value:\n ${buildId}\n ${buildNumber}\n ${duration}\n ${description}\n ${displayName}\n ${startTime}\n */\n Matcher matcher = custom.matcher(parameter);\n while (matcher.find()) {\n String customKey = matcher.group(1);\n if (customKey.equals(\"buildId\")) {\n parameter = matcher.replaceFirst(run.getId());\n } else if (customKey.equals(\"buildNumber\")) {\n parameter = matcher.replaceFirst(Integer.toString(run.getNumber()));\n } else if (customKey.equals(\"duration\")) {\n parameter = matcher.replaceFirst(run.getDurationString());\n } else if (customKey.equals(\"description\")) {\n parameter = matcher.replaceFirst(run.getDescription());\n } else if (customKey.equals(\"displayName\")) {\n parameter = matcher.replaceFirst(run.getDisplayName());\n } else if (customKey.equals(\"startTime\")) {\n parameter = matcher.replaceFirst(run.getTimestampString());\n } else {\n // this actually should NOT happen\n parameter = matcher.replaceFirst(customKey);\n }\n matcher = custom.matcher(parameter);\n }\n } else if (actionable instanceof Job) {\n parameter = resolve(((Job) actionable).getLastBuild(), parameter);\n }\n }\n return parameter;\n }\n}\n"} {"task_id": "Java_674", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/jenkinsci/embeddable-build-status-plugin/src/main/java/org/jenkinsci/plugins/badge/extensions/SpecialValueParameterResolverExtension.java", "mask_start_position": 651, "mask_end_position": 2516, "canonical_solution": "\n if (parameter != null) {\n if (actionable instanceof Run) {\n Run run = (Run) actionable;\n /* try to match any custom value:\n ${buildId}\n ${buildNumber}\n ${duration}\n ${description}\n ${displayName}\n ${startTime}\n */\n Matcher matcher = custom.matcher(parameter);\n while (matcher.find()) {\n String customKey = matcher.group(1);\n if (customKey.equals(\"buildId\")) {\n parameter = matcher.replaceFirst(run.getId());\n } else if (customKey.equals(\"buildNumber\")) {\n parameter = matcher.replaceFirst(Integer.toString(run.getNumber()));\n } else if (customKey.equals(\"duration\")) {\n parameter = matcher.replaceFirst(run.getDurationString());\n } else if (customKey.equals(\"description\")) {\n parameter = matcher.replaceFirst(run.getDescription());\n } else if (customKey.equals(\"displayName\")) {\n parameter = matcher.replaceFirst(run.getDisplayName());\n } else if (customKey.equals(\"startTime\")) {\n parameter = matcher.replaceFirst(run.getTimestampString());\n } else {\n // this actually should NOT happen\n parameter = matcher.replaceFirst(customKey);\n }\n matcher = custom.matcher(parameter);\n }\n } else if (actionable instanceof Job) {\n parameter = resolve(((Job) actionable).getLastBuild(), parameter);\n }\n }", "pre_mask_code": "/**\n * @author Thomas Doering (thomas-dee)\n */\npackage org.jenkinsci.plugins.badge.extensions;\n\nimport hudson.Extension;\nimport hudson.model.Actionable;\nimport hudson.model.Run;\nimport hudson.model.Job;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.jenkinsci.plugins.badge.extensionpoints.ParameterResolverExtensionPoint;\n\n@Extension\npublic class SpecialValueParameterResolverExtension implements ParameterResolverExtensionPoint {\n\n private static Pattern custom = Pattern.compile(\"(buildId|buildNumber|duration|description|displayName|startTime)\");\n\n public String resolve(Actionable actionable, String parameter) {", "post_mask_code": "\n return parameter;\n }\n}\n"} {"task_id": "Java_675", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/jenkinsci/embeddable-build-status-plugin/src/main/java/org/jenkinsci/plugins/badge/extensions/SpecialValueParameterResolverExtension.java", "mask_start_position": 2525, "mask_end_position": 2542, "canonical_solution": "return parameter;", "pre_mask_code": "/**\n * @author Thomas Doering (thomas-dee)\n */\npackage org.jenkinsci.plugins.badge.extensions;\n\nimport hudson.Extension;\nimport hudson.model.Actionable;\nimport hudson.model.Run;\nimport hudson.model.Job;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.jenkinsci.plugins.badge.extensionpoints.ParameterResolverExtensionPoint;\n\n@Extension\npublic class SpecialValueParameterResolverExtension implements ParameterResolverExtensionPoint {\n\n private static Pattern custom = Pattern.compile(\"(buildId|buildNumber|duration|description|displayName|startTime)\");\n\n public String resolve(Actionable actionable, String parameter) {\n if (parameter != null) {\n if (actionable instanceof Run) {\n Run run = (Run) actionable;\n /* try to match any custom value:\n ${buildId}\n ${buildNumber}\n ${duration}\n ${description}\n ${displayName}\n ${startTime}\n */\n Matcher matcher = custom.matcher(parameter);\n while (matcher.find()) {\n String customKey = matcher.group(1);\n if (customKey.equals(\"buildId\")) {\n parameter = matcher.replaceFirst(run.getId());\n } else if (customKey.equals(\"buildNumber\")) {\n parameter = matcher.replaceFirst(Integer.toString(run.getNumber()));\n } else if (customKey.equals(\"duration\")) {\n parameter = matcher.replaceFirst(run.getDurationString());\n } else if (customKey.equals(\"description\")) {\n parameter = matcher.replaceFirst(run.getDescription());\n } else if (customKey.equals(\"displayName\")) {\n parameter = matcher.replaceFirst(run.getDisplayName());\n } else if (customKey.equals(\"startTime\")) {\n parameter = matcher.replaceFirst(run.getTimestampString());\n } else {\n // this actually should NOT happen\n parameter = matcher.replaceFirst(customKey);\n }\n matcher = custom.matcher(parameter);\n }\n } else if (actionable instanceof Job) {\n parameter = resolve(((Job) actionable).getLastBuild(), parameter);\n }\n }\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_676", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/jenkinsci/embeddable-build-status-plugin/src/main/java/org/jenkinsci/plugins/badge/extensions/SpecialValueParameterResolverExtension.java", "mask_start_position": 2547, "mask_end_position": 2548, "canonical_solution": "}", "pre_mask_code": "/**\n * @author Thomas Doering (thomas-dee)\n */\npackage org.jenkinsci.plugins.badge.extensions;\n\nimport hudson.Extension;\nimport hudson.model.Actionable;\nimport hudson.model.Run;\nimport hudson.model.Job;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.jenkinsci.plugins.badge.extensionpoints.ParameterResolverExtensionPoint;\n\n@Extension\npublic class SpecialValueParameterResolverExtension implements ParameterResolverExtensionPoint {\n\n private static Pattern custom = Pattern.compile(\"(buildId|buildNumber|duration|description|displayName|startTime)\");\n\n public String resolve(Actionable actionable, String parameter) {\n if (parameter != null) {\n if (actionable instanceof Run) {\n Run run = (Run) actionable;\n /* try to match any custom value:\n ${buildId}\n ${buildNumber}\n ${duration}\n ${description}\n ${displayName}\n ${startTime}\n */\n Matcher matcher = custom.matcher(parameter);\n while (matcher.find()) {\n String customKey = matcher.group(1);\n if (customKey.equals(\"buildId\")) {\n parameter = matcher.replaceFirst(run.getId());\n } else if (customKey.equals(\"buildNumber\")) {\n parameter = matcher.replaceFirst(Integer.toString(run.getNumber()));\n } else if (customKey.equals(\"duration\")) {\n parameter = matcher.replaceFirst(run.getDurationString());\n } else if (customKey.equals(\"description\")) {\n parameter = matcher.replaceFirst(run.getDescription());\n } else if (customKey.equals(\"displayName\")) {\n parameter = matcher.replaceFirst(run.getDisplayName());\n } else if (customKey.equals(\"startTime\")) {\n parameter = matcher.replaceFirst(run.getTimestampString());\n } else {\n // this actually should NOT happen\n parameter = matcher.replaceFirst(customKey);\n }\n matcher = custom.matcher(parameter);\n }\n } else if (actionable instanceof Job) {\n parameter = resolve(((Job) actionable).getLastBuild(), parameter);\n }\n }\n return parameter;\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_677", "language": "Java", "task_type": "single_line", "source_file": "java/github/jenkinsci/embeddable-build-status-plugin/src/main/java/org/jenkinsci/plugins/badge/extensions/SpecialValueParameterResolverExtension.java", "mask_start_position": 2527, "mask_end_position": 2542, "canonical_solution": "turn parameter;", "pre_mask_code": "/**\n * @author Thomas Doering (thomas-dee)\n */\npackage org.jenkinsci.plugins.badge.extensions;\n\nimport hudson.Extension;\nimport hudson.model.Actionable;\nimport hudson.model.Run;\nimport hudson.model.Job;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.jenkinsci.plugins.badge.extensionpoints.ParameterResolverExtensionPoint;\n\n@Extension\npublic class SpecialValueParameterResolverExtension implements ParameterResolverExtensionPoint {\n\n private static Pattern custom = Pattern.compile(\"(buildId|buildNumber|duration|description|displayName|startTime)\");\n\n public String resolve(Actionable actionable, String parameter) {\n if (parameter != null) {\n if (actionable instanceof Run) {\n Run run = (Run) actionable;\n /* try to match any custom value:\n ${buildId}\n ${buildNumber}\n ${duration}\n ${description}\n ${displayName}\n ${startTime}\n */\n Matcher matcher = custom.matcher(parameter);\n while (matcher.find()) {\n String customKey = matcher.group(1);\n if (customKey.equals(\"buildId\")) {\n parameter = matcher.replaceFirst(run.getId());\n } else if (customKey.equals(\"buildNumber\")) {\n parameter = matcher.replaceFirst(Integer.toString(run.getNumber()));\n } else if (customKey.equals(\"duration\")) {\n parameter = matcher.replaceFirst(run.getDurationString());\n } else if (customKey.equals(\"description\")) {\n parameter = matcher.replaceFirst(run.getDescription());\n } else if (customKey.equals(\"displayName\")) {\n parameter = matcher.replaceFirst(run.getDisplayName());\n } else if (customKey.equals(\"startTime\")) {\n parameter = matcher.replaceFirst(run.getTimestampString());\n } else {\n // this actually should NOT happen\n parameter = matcher.replaceFirst(customKey);\n }\n matcher = custom.matcher(parameter);\n }\n } else if (actionable instanceof Job) {\n parameter = resolve(((Job) actionable).getLastBuild(), parameter);\n }\n }\n re", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_678", "language": "Java", "task_type": "if_statement", "source_file": "java/github/jenkinsci/embeddable-build-status-plugin/src/main/java/org/jenkinsci/plugins/badge/extensions/SpecialValueParameterResolverExtension.java", "mask_start_position": 2365, "mask_end_position": 2506, "canonical_solution": "if (actionable instanceof Job) {\n parameter = resolve(((Job) actionable).getLastBuild(), parameter);\n }", "pre_mask_code": "/**\n * @author Thomas Doering (thomas-dee)\n */\npackage org.jenkinsci.plugins.badge.extensions;\n\nimport hudson.Extension;\nimport hudson.model.Actionable;\nimport hudson.model.Run;\nimport hudson.model.Job;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.jenkinsci.plugins.badge.extensionpoints.ParameterResolverExtensionPoint;\n\n@Extension\npublic class SpecialValueParameterResolverExtension implements ParameterResolverExtensionPoint {\n\n private static Pattern custom = Pattern.compile(\"(buildId|buildNumber|duration|description|displayName|startTime)\");\n\n public String resolve(Actionable actionable, String parameter) {\n if (parameter != null) {\n if (actionable instanceof Run) {\n Run run = (Run) actionable;\n /* try to match any custom value:\n ${buildId}\n ${buildNumber}\n ${duration}\n ${description}\n ${displayName}\n ${startTime}\n */\n Matcher matcher = custom.matcher(parameter);\n while (matcher.find()) {\n String customKey = matcher.group(1);\n if (customKey.equals(\"buildId\")) {\n parameter = matcher.replaceFirst(run.getId());\n } else if (customKey.equals(\"buildNumber\")) {\n parameter = matcher.replaceFirst(Integer.toString(run.getNumber()));\n } else if (customKey.equals(\"duration\")) {\n parameter = matcher.replaceFirst(run.getDurationString());\n } else if (customKey.equals(\"description\")) {\n parameter = matcher.replaceFirst(run.getDescription());\n } else if (customKey.equals(\"displayName\")) {\n parameter = matcher.replaceFirst(run.getDisplayName());\n } else if (customKey.equals(\"startTime\")) {\n parameter = matcher.replaceFirst(run.getTimestampString());\n } else {\n // this actually should NOT happen\n parameter = matcher.replaceFirst(customKey);\n }\n matcher = custom.matcher(parameter);\n }\n } else ", "post_mask_code": "\n }\n return parameter;\n }\n}\n"} {"task_id": "Java_679", "language": "Java", "task_type": "empty", "source_file": "java/github/jenkinsci/embeddable-build-status-plugin/src/main/java/org/jenkinsci/plugins/badge/extensions/SpecialValueParameterResolverExtension.java", "mask_start_position": 747, "mask_end_position": 747, "canonical_solution": "", "pre_mask_code": "/**\n * @author Thomas Doering (thomas-dee)\n */\npackage org.jenkinsci.plugins.badge.extensions;\n\nimport hudson.Extension;\nimport hudson.model.Actionable;\nimport hudson.model.Run;\nimport hudson.model.Job;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.jenkinsci.plugins.badge.extensionpoints.ParameterResolverExtensionPoint;\n\n@Extension\npublic class SpecialValueParameterResolverExtension implements ParameterResolverExtensionPoint {\n\n private static Pattern custom = Pattern.compile(\"(buildId|buildNumber|duration|description|displayName|startTime)\");\n\n public String resolve(Actionable actionable, String parameter) {\n if (parameter != null) {\n if (actionable instanceof Run) {\n ", "post_mask_code": " Run run = (Run) actionable;\n /* try to match any custom value:\n ${buildId}\n ${buildNumber}\n ${duration}\n ${description}\n ${displayName}\n ${startTime}\n */\n Matcher matcher = custom.matcher(parameter);\n while (matcher.find()) {\n String customKey = matcher.group(1);\n if (customKey.equals(\"buildId\")) {\n parameter = matcher.replaceFirst(run.getId());\n } else if (customKey.equals(\"buildNumber\")) {\n parameter = matcher.replaceFirst(Integer.toString(run.getNumber()));\n } else if (customKey.equals(\"duration\")) {\n parameter = matcher.replaceFirst(run.getDurationString());\n } else if (customKey.equals(\"description\")) {\n parameter = matcher.replaceFirst(run.getDescription());\n } else if (customKey.equals(\"displayName\")) {\n parameter = matcher.replaceFirst(run.getDisplayName());\n } else if (customKey.equals(\"startTime\")) {\n parameter = matcher.replaceFirst(run.getTimestampString());\n } else {\n // this actually should NOT happen\n parameter = matcher.replaceFirst(customKey);\n }\n matcher = custom.matcher(parameter);\n }\n } else if (actionable instanceof Job) {\n parameter = resolve(((Job) actionable).getLastBuild(), parameter);\n }\n }\n return parameter;\n }\n}\n"} {"task_id": "Java_680", "language": "Java", "task_type": "method_signature", "source_file": "java/github/DivineRPG/DivineRPG/src/main/java/divinerpg/items/vanilla/ItemSlowingSword.java", "mask_start_position": 763, "mask_end_position": 844, "canonical_solution": "@Override\n protected void addAdditionalInformation(List list) ", "pre_mask_code": "package divinerpg.items.vanilla;\n\nimport divinerpg.*;\nimport divinerpg.items.base.*;\nimport divinerpg.util.*;\nimport net.minecraft.entity.*;\nimport net.minecraft.entity.player.*;\nimport net.minecraft.item.*;\nimport net.minecraft.potion.*;\nimport net.minecraft.util.text.*;\nimport java.util.*;\n\npublic class ItemSlowingSword extends ItemModSword {\n\n public ItemSlowingSword(IItemTier toolMaterial, String name) {\n super(name, toolMaterial, DivineRPG.tabs.melee);\n }\n\n @Override\n public boolean onLeftClickEntity(ItemStack stack, PlayerEntity player, Entity entity) {\n if (entity instanceof LivingEntity)\n ((LivingEntity) entity).addEffect(new EffectInstance(Effects.MOVEMENT_SLOWDOWN, 50, 1));\n return false;\n }\n\n ", "post_mask_code": "{\n list.add(LocalizeUtils.slow(2.5));\n }\n}\n"} {"task_id": "Java_681", "language": "Java", "task_type": "method_body", "source_file": "java/github/DivineRPG/DivineRPG/src/main/java/divinerpg/items/vanilla/ItemSlowingSword.java", "mask_start_position": 844, "mask_end_position": 894, "canonical_solution": "{\n list.add(LocalizeUtils.slow(2.5));\n }", "pre_mask_code": "package divinerpg.items.vanilla;\n\nimport divinerpg.*;\nimport divinerpg.items.base.*;\nimport divinerpg.util.*;\nimport net.minecraft.entity.*;\nimport net.minecraft.entity.player.*;\nimport net.minecraft.item.*;\nimport net.minecraft.potion.*;\nimport net.minecraft.util.text.*;\nimport java.util.*;\n\npublic class ItemSlowingSword extends ItemModSword {\n\n public ItemSlowingSword(IItemTier toolMaterial, String name) {\n super(name, toolMaterial, DivineRPG.tabs.melee);\n }\n\n @Override\n public boolean onLeftClickEntity(ItemStack stack, PlayerEntity player, Entity entity) {\n if (entity instanceof LivingEntity)\n ((LivingEntity) entity).addEffect(new EffectInstance(Effects.MOVEMENT_SLOWDOWN, 50, 1));\n return false;\n }\n\n @Override\n protected void addAdditionalInformation(List list) ", "post_mask_code": "\n}\n"} {"task_id": "Java_682", "language": "Java", "task_type": "single_line", "source_file": "java/github/DivineRPG/DivineRPG/src/main/java/divinerpg/items/vanilla/ItemSlowingSword.java", "mask_start_position": 740, "mask_end_position": 751, "canonical_solution": "turn false;", "pre_mask_code": "package divinerpg.items.vanilla;\n\nimport divinerpg.*;\nimport divinerpg.items.base.*;\nimport divinerpg.util.*;\nimport net.minecraft.entity.*;\nimport net.minecraft.entity.player.*;\nimport net.minecraft.item.*;\nimport net.minecraft.potion.*;\nimport net.minecraft.util.text.*;\nimport java.util.*;\n\npublic class ItemSlowingSword extends ItemModSword {\n\n public ItemSlowingSword(IItemTier toolMaterial, String name) {\n super(name, toolMaterial, DivineRPG.tabs.melee);\n }\n\n @Override\n public boolean onLeftClickEntity(ItemStack stack, PlayerEntity player, Entity entity) {\n if (entity instanceof LivingEntity)\n ((LivingEntity) entity).addEffect(new EffectInstance(Effects.MOVEMENT_SLOWDOWN, 50, 1));\n re", "post_mask_code": "\n }\n\n @Override\n protected void addAdditionalInformation(List list) {\n list.add(LocalizeUtils.slow(2.5));\n }\n}\n"} {"task_id": "Java_683", "language": "Java", "task_type": "if_statement", "source_file": "java/github/DivineRPG/DivineRPG/src/main/java/divinerpg/items/vanilla/ItemSlowingSword.java", "mask_start_position": 593, "mask_end_position": 729, "canonical_solution": "if (entity instanceof LivingEntity)\n ((LivingEntity) entity).addEffect(new EffectInstance(Effects.MOVEMENT_SLOWDOWN, 50, 1));", "pre_mask_code": "package divinerpg.items.vanilla;\n\nimport divinerpg.*;\nimport divinerpg.items.base.*;\nimport divinerpg.util.*;\nimport net.minecraft.entity.*;\nimport net.minecraft.entity.player.*;\nimport net.minecraft.item.*;\nimport net.minecraft.potion.*;\nimport net.minecraft.util.text.*;\nimport java.util.*;\n\npublic class ItemSlowingSword extends ItemModSword {\n\n public ItemSlowingSword(IItemTier toolMaterial, String name) {\n super(name, toolMaterial, DivineRPG.tabs.melee);\n }\n\n @Override\n public boolean onLeftClickEntity(ItemStack stack, PlayerEntity player, Entity entity) {\n ", "post_mask_code": "\n return false;\n }\n\n @Override\n protected void addAdditionalInformation(List list) {\n list.add(LocalizeUtils.slow(2.5));\n }\n}\n"} {"task_id": "Java_684", "language": "Java", "task_type": "empty", "source_file": "java/github/DivineRPG/DivineRPG/src/main/java/divinerpg/items/vanilla/ItemSlowingSword.java", "mask_start_position": 415, "mask_end_position": 415, "canonical_solution": "", "pre_mask_code": "package divinerpg.items.vanilla;\n\nimport divinerpg.*;\nimport divinerpg.items.base.*;\nimport divinerpg.util.*;\nimport net.minecraft.entity.*;\nimport net.minecraft.entity.player.*;\nimport net.minecraft.item.*;\nimport net.minecraft.potion.*;\nimport net.minecraft.util.text.*;\nimport java.util.*;\n\npublic class ItemSlowingSword extends ItemModSword {\n\n public ItemSlowingSword(IItemTier toolMaterial, String name) {\n", "post_mask_code": " super(name, toolMaterial, DivineRPG.tabs.melee);\n }\n\n @Override\n public boolean onLeftClickEntity(ItemStack stack, PlayerEntity player, Entity entity) {\n if (entity instanceof LivingEntity)\n ((LivingEntity) entity).addEffect(new EffectInstance(Effects.MOVEMENT_SLOWDOWN, 50, 1));\n return false;\n }\n\n @Override\n protected void addAdditionalInformation(List list) {\n list.add(LocalizeUtils.slow(2.5));\n }\n}\n"} {"task_id": "Java_685", "language": "Java", "task_type": "empty", "source_file": "java/github/citygml4j/citygml4j/src/main/java/org/citygml4j/builder/cityjson/json/io/writer/CityJSONWriteException.java", "mask_start_position": 284, "mask_end_position": 284, "canonical_solution": "", "pre_mask_code": "/*\n * citygml4j - The Open Source Java API for CityGML\n * http://example.com\n *\n *\n */\npackage org.citygml4j.builder.cityjson.json.io.writer;\n\npublic class CityJSONWriteException extends Exception {\n\n private static final long serialVersionUID = -3716015045363231263L;\n\n public ", "post_mask_code": "CityJSONWriteException() {\n super();\n }\n\n public CityJSONWriteException(String message) {\n super(message);\n }\n\n public CityJSONWriteException(Throwable cause) {\n super(cause);\n }\n\n public CityJSONWriteException(String message, Throwable cause) {\n super(message, cause);\n }\n}\n"} {"task_id": "Java_686", "language": "Java", "task_type": "empty", "source_file": "java/github/sika-code/sika-code/sika-code-core/common/src/main/java/com/sika/code/retryer/constant/WaitStrategyEnum.java", "mask_start_position": 231, "mask_end_position": 231, "canonical_solution": "", "pre_mask_code": "package com.sika.code.retryer.constant;\n\nimport com.sika.code.basic.constant.TypeEnumInf;\nimport lombok.AllArgsConstructor;\nimport lombok.Getter;\n\n/**\n * 等待时长策略(控制时间间隔) --- 发生异常后等待多久进行重试\n *\n * @author daiqi\n * @create 2019-12-05 22", "post_mask_code": ":38\n */\n@AllArgsConstructor\n@Getter\npublic enum WaitStrategyEnum implements TypeEnumInf {\n\n FIXED(1, \"固定等待时长策略\"),\n /**\n * 随机等待时长策略(可以提供一个最小和最大时长,等待时长为其区间随机值)\n */\n RANDOM(2, \"随机等待时长策略\"),\n /**\n * 递增等待时长策略(提供一个初始值和步长,等待时间随重试次数增加而增加)\n */\n INCREMENTING(3, \"递增等待时长策略\"),\n /**\n * 1、这中策略等待时间呈指数形式增长,指数形式增长,\n * 2、如果指定最大等待时间,则增长到最大等待时间就不再增长;\n * 3、如果没有指定最大等待时间,则最大等待时间为Long.MAX_VALUE\n */\n EXPONENTIAL(4, \":指数等待时长策略\"),\n /**\n * 等待时间以斐波拉契数列形式增长\n * 1、无参:等待时间从 1 增长到 Long.MAX_VALUE\n * 2、两个参数:等待时间从 1 增长到 maximumTimeUnit.toMillis(maximumTime),到最大值以后等待时间恒定不变\n * 3、三个参数:等待时间从 multiplier 增长到 maximumTimeUnit.toMillis(maximumTime)\n */\n FIBONACCI(5, \":FIBONACCI 等待时长策略;\");\n\n private Integer type;\n\n private String desc;\n}\n"} {"task_id": "Java_687", "language": "Java", "task_type": "method_signature", "source_file": "java/github/dstmath/OppoFramework/A1_7_1_1/src/main/java/com/android/server/wifi/WifiMetrics.java", "mask_start_position": 24794, "mask_end_position": 24848, "canonical_solution": "public void incrementNumConnectivityWatchdogPnoGood() ", "pre_mask_code": "package com.android.server.wifi;\n\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiConfiguration;\nimport android.util.Base64;\nimport android.util.SparseIntArray;\nimport com.android.server.wifi.WifiMetricsProto.AlertReasonCount;\nimport com.android.server.wifi.WifiMetricsProto.RssiPollCount;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.ScanReturnEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.WifiSystemStateEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiScoreCount;\nimport com.android.server.wifi.hotspot2.NetworkDetail;\nimport com.android.server.wifi.hotspot2.NetworkDetail.HSRelease;\nimport com.google.protobuf.nano.MessageNano;\nimport java.io.FileDescriptor;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.List;\n\npublic class WifiMetrics {\n\n public static final String CLEAN_DUMP_ARG = \"clean\";\n\n private static final boolean DBG = false;\n\n private static final int MAX_CONNECTION_EVENTS = 256;\n\n private static final int MAX_RSSI_POLL = 0;\n\n private static final int MAX_WIFI_SCORE = 5;\n\n private static final int MIN_RSSI_POLL = -127;\n\n private static final int MIN_WIFI_SCORE = 0;\n\n public static final String PROTO_DUMP_ARG = \"wifiMetricsProto\";\n\n private static final int SCREEN_OFF = 0;\n\n private static final int SCREEN_ON = 1;\n\n private static final String TAG = \"WifiMetrics\";\n\n private Clock mClock;\n\n private final List mConnectionEventList = new ArrayList();\n\n private ConnectionEvent mCurrentConnectionEvent;\n\n private final Object mLock = new Object();\n\n private long mRecordStartTimeSec;\n\n private final SparseIntArray mRssiPollCounts = new SparseIntArray();\n\n private final SparseIntArray mScanReturnEntries = new SparseIntArray();\n\n private boolean mScreenOn;\n\n private final SparseIntArray mWifiAlertReasonCounts = new SparseIntArray();\n\n private final WifiLog mWifiLogProto = new WifiLog();\n\n private final SparseIntArray mWifiScoreCounts = new SparseIntArray();\n\n private int mWifiState;\n\n private final SparseIntArray mWifiSystemStateEntries = new SparseIntArray();\n\n class ConnectionEvent {\n\n public static final int FAILURE_ASSOCIATION_REJECTION = 2;\n\n public static final int FAILURE_AUTHENTICATION_FAILURE = 3;\n\n public static final int FAILURE_CONNECT_NETWORK_FAILED = 5;\n\n public static final int FAILURE_DHCP = 10;\n\n public static final int FAILURE_NETWORK_DISCONNECTION = 6;\n\n public static final int FAILURE_NEW_CONNECTION_ATTEMPT = 7;\n\n public static final int FAILURE_NONE = 1;\n\n public static final int FAILURE_REDUNDANT_CONNECTION_ATTEMPT = 8;\n\n public static final int FAILURE_ROAM_TIMEOUT = 9;\n\n public static final int FAILURE_SSID_TEMP_DISABLED = 4;\n\n public static final int FAILURE_UNKNOWN = 0;\n\n private String mConfigBssid;\n\n private String mConfigSsid;\n\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent mConnectionEvent;\n\n private long mRealEndTime;\n\n private long mRealStartTime;\n\n RouterFingerPrint mRouterFingerPrint;\n\n private boolean mScreenOn;\n\n private int mWifiState;\n\n /* synthetic */\n ConnectionEvent(WifiMetrics this$0, ConnectionEvent connectionEvent) {\n this();\n }\n\n private ConnectionEvent() {\n this.mConnectionEvent = new com.android.server.wifi.WifiMetricsProto.ConnectionEvent();\n this.mRealEndTime = 0;\n this.mRealStartTime = 0;\n this.mRouterFingerPrint = new RouterFingerPrint();\n this.mConnectionEvent.routerFingerprint = this.mRouterFingerPrint.mRouterFingerPrintProto;\n this.mConfigSsid = \"\";\n this.mConfigBssid = \"\";\n this.mWifiState = 0;\n this.mScreenOn = false;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"startTime=\");\n Calendar c = Calendar.getInstance();\n synchronized (WifiMetrics.this.mLock) {\n String str;\n c.setTimeInMillis(this.mConnectionEvent.startTimeMillis);\n if (this.mConnectionEvent.startTimeMillis == 0) {\n str = \" \";\n } else {\n str = String.format(\"%tm-%td %tH:%tM:%tS.%tL\", new Object[] { c, c, c, c, c, c });\n }\n sb.append(str);\n sb.append(\", SSID=\");\n sb.append(this.mConfigSsid);\n sb.append(\", BSSID=\");\n sb.append(this.mConfigBssid);\n sb.append(\", durationMillis=\");\n sb.append(this.mConnectionEvent.durationTakenToConnectMillis);\n sb.append(\", roamType=\");\n switch(this.mConnectionEvent.roamType) {\n case 1:\n sb.append(\"ROAM_NONE\");\n break;\n case 2:\n sb.append(\"ROAM_DBDC\");\n break;\n case 3:\n sb.append(\"ROAM_ENTERPRISE\");\n break;\n case 4:\n sb.append(\"ROAM_USER_SELECTED\");\n break;\n case 5:\n sb.append(\"ROAM_UNRELATED\");\n break;\n default:\n sb.append(\"ROAM_UNKNOWN\");\n break;\n }\n sb.append(\", connectionResult=\");\n sb.append(this.mConnectionEvent.connectionResult);\n sb.append(\", level2FailureCode=\");\n switch(this.mConnectionEvent.level2FailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"ASSOCIATION_REJECTION\");\n break;\n case 3:\n sb.append(\"AUTHENTICATION_FAILURE\");\n break;\n case 4:\n sb.append(\"SSID_TEMP_DISABLED\");\n break;\n case 5:\n sb.append(\"CONNECT_NETWORK_FAILED\");\n break;\n case 6:\n sb.append(\"NETWORK_DISCONNECTION\");\n break;\n case 7:\n sb.append(\"NEW_CONNECTION_ATTEMPT\");\n break;\n case 8:\n sb.append(\"REDUNDANT_CONNECTION_ATTEMPT\");\n break;\n case 9:\n sb.append(\"ROAM_TIMEOUT\");\n break;\n case 10:\n sb.append(\"DHCP\");\n break;\n }\n sb.append(\"UNKNOWN\");\n sb.append(\", connectivityLevelFailureCode=\");\n switch(this.mConnectionEvent.connectivityLevelFailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"DHCP\");\n break;\n case 3:\n sb.append(\"NO_INTERNET\");\n break;\n case 4:\n sb.append(\"UNWANTED\");\n break;\n default:\n sb.append(\"UNKNOWN\");\n break;\n }\n sb.append(\", signalStrength=\");\n sb.append(this.mConnectionEvent.signalStrength);\n sb.append(\", wifiState=\");\n switch(this.mWifiState) {\n case 1:\n sb.append(\"WIFI_DISABLED\");\n break;\n case 2:\n sb.append(\"WIFI_DISCONNECTED\");\n break;\n case 3:\n sb.append(\"WIFI_ASSOCIATED\");\n break;\n default:\n sb.append(\"WIFI_UNKNOWN\");\n break;\n }\n sb.append(\", screenOn=\");\n sb.append(this.mScreenOn);\n sb.append(\". mRouterFingerprint: \");\n sb.append(this.mRouterFingerPrint.toString());\n }\n return sb.toString();\n }\n }\n\n class RouterFingerPrint {\n\n private com.android.server.wifi.WifiMetricsProto.RouterFingerPrint mRouterFingerPrintProto = new com.android.server.wifi.WifiMetricsProto.RouterFingerPrint();\n\n RouterFingerPrint() {\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n synchronized (WifiMetrics.this.mLock) {\n sb.append(\"mConnectionEvent.roamType=\").append(this.mRouterFingerPrintProto.roamType);\n sb.append(\", mChannelInfo=\").append(this.mRouterFingerPrintProto.channelInfo);\n sb.append(\", mDtim=\").append(this.mRouterFingerPrintProto.dtim);\n sb.append(\", mAuthentication=\").append(this.mRouterFingerPrintProto.authentication);\n sb.append(\", mHidden=\").append(this.mRouterFingerPrintProto.hidden);\n sb.append(\", mRouterTechnology=\").append(this.mRouterFingerPrintProto.routerTechnology);\n sb.append(\", mSupportsIpv6=\").append(this.mRouterFingerPrintProto.supportsIpv6);\n }\n return sb.toString();\n }\n\n public void updateFromWifiConfiguration(WifiConfiguration config) {\n synchronized (WifiMetrics.this.mLock) {\n if (config != null) {\n this.mRouterFingerPrintProto.hidden = config.hiddenSSID;\n if (config.dtimInterval > 0) {\n this.mRouterFingerPrintProto.dtim = config.dtimInterval;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mConfigSsid = config.SSID;\n if (config.allowedKeyManagement != null && config.allowedKeyManagement.get(0)) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n } else if (config.isEnterprise()) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n } else {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.passpoint = config.isPasspoint();\n ScanResult candidate = config.getNetworkSelectionStatus().getCandidate();\n if (candidate != null) {\n WifiMetrics.this.updateMetricsFromScanResult(candidate);\n }\n }\n }\n }\n }\n\n public WifiMetrics(Clock clock) {\n this.mClock = clock;\n this.mCurrentConnectionEvent = null;\n this.mScreenOn = true;\n this.mWifiState = 1;\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n }\n\n public void startConnectionEvent(WifiConfiguration config, String targetBSSID, int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n if (this.mCurrentConnectionEvent.mConfigSsid == null || this.mCurrentConnectionEvent.mConfigBssid == null || config == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(config.SSID) || !(this.mCurrentConnectionEvent.mConfigBssid.equals(WifiLastResortWatchdog.BSSID_ANY) || this.mCurrentConnectionEvent.mConfigBssid.equals(targetBSSID))) {\n endConnectionEvent(7, 1);\n } else {\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n endConnectionEvent(8, 1);\n }\n }\n while (this.mConnectionEventList.size() >= 256) {\n this.mConnectionEventList.remove(0);\n }\n this.mCurrentConnectionEvent = new ConnectionEvent(this, null);\n this.mCurrentConnectionEvent.mConnectionEvent.startTimeMillis = this.mClock.currentTimeMillis();\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n this.mCurrentConnectionEvent.mRouterFingerPrint.updateFromWifiConfiguration(config);\n this.mCurrentConnectionEvent.mConfigBssid = WifiLastResortWatchdog.BSSID_ANY;\n this.mCurrentConnectionEvent.mRealStartTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mWifiState = this.mWifiState;\n this.mCurrentConnectionEvent.mScreenOn = this.mScreenOn;\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n }\n\n public void setConnectionEventRoamType(int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n }\n }\n }\n\n public void setConnectionScanDetail(ScanDetail scanDetail) {\n synchronized (this.mLock) {\n if (!(this.mCurrentConnectionEvent == null || scanDetail == null)) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n if (!(networkDetail == null || scanResult == null || this.mCurrentConnectionEvent.mConfigSsid == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(\"\\\"\" + networkDetail.getSSID() + \"\\\"\"))) {\n updateMetricsFromNetworkDetail(networkDetail);\n updateMetricsFromScanResult(scanResult);\n }\n }\n }\n }\n\n public void endConnectionEvent(int level2FailureCode, int connectivityFailureCode) {\n int i = 1;\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n boolean result = level2FailureCode == 1 ? connectivityFailureCode == 1 : false;\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent connectionEvent = this.mCurrentConnectionEvent.mConnectionEvent;\n if (!result) {\n i = 0;\n }\n connectionEvent.connectionResult = i;\n this.mCurrentConnectionEvent.mRealEndTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mConnectionEvent.durationTakenToConnectMillis = (int) (this.mCurrentConnectionEvent.mRealEndTime - this.mCurrentConnectionEvent.mRealStartTime);\n this.mCurrentConnectionEvent.mConnectionEvent.level2FailureCode = level2FailureCode;\n this.mCurrentConnectionEvent.mConnectionEvent.connectivityLevelFailureCode = connectivityFailureCode;\n this.mCurrentConnectionEvent = null;\n }\n }\n }\n\n private void updateMetricsFromNetworkDetail(NetworkDetail networkDetail) {\n int connectionWifiMode;\n int dtimInterval = networkDetail.getDtimInterval();\n if (dtimInterval > 0) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.dtim = dtimInterval;\n }\n switch(networkDetail.getWifiMode()) {\n case 0:\n connectionWifiMode = 0;\n break;\n case 1:\n connectionWifiMode = 1;\n break;\n case 2:\n connectionWifiMode = 2;\n break;\n case 3:\n connectionWifiMode = 3;\n break;\n case 4:\n connectionWifiMode = 4;\n break;\n case 5:\n connectionWifiMode = 5;\n break;\n default:\n connectionWifiMode = 6;\n break;\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.routerTechnology = connectionWifiMode;\n }\n\n private void updateMetricsFromScanResult(ScanResult scanResult) {\n this.mCurrentConnectionEvent.mConnectionEvent.signalStrength = scanResult.level;\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n this.mCurrentConnectionEvent.mConfigBssid = scanResult.BSSID;\n if (scanResult.capabilities != null) {\n if (scanResult.capabilities.contains(\"WEP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"PSK\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"EAP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n }\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.channelInfo = scanResult.frequency;\n }\n\n void setNumSavedNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numSavedNetworks = num;\n }\n }\n\n void setNumOpenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numOpenNetworks = num;\n }\n }\n\n void setNumPersonalNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPersonalNetworks = num;\n }\n }\n\n void setNumEnterpriseNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numEnterpriseNetworks = num;\n }\n }\n\n void setNumHiddenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numHiddenNetworks = num;\n }\n }\n\n void setNumPasspointNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPasspointNetworks = num;\n }\n }\n\n void setNumNetworksAddedByUser(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByUser = num;\n }\n }\n\n void setNumNetworksAddedByApps(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByApps = num;\n }\n }\n\n void setIsLocationEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isLocationEnabled = enabled;\n }\n }\n\n void setIsScanningAlwaysEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isScanningAlwaysEnabled = enabled;\n }\n }\n\n public void incrementNonEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numNonEmptyScanResults++;\n }\n }\n\n public void incrementEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numEmptyScanResults++;\n }\n }\n\n public void incrementBackgroundScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numBackgroundScans++;\n }\n }\n\n public int getBackgroundScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numBackgroundScans;\n }\n return i;\n }\n\n public void incrementOneshotScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numOneshotScans++;\n }\n incrementWifiSystemScanStateCount(this.mWifiState, this.mScreenOn);\n }\n\n public int getOneshotScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numOneshotScans;\n }\n return i;\n }\n\n private String returnCodeToString(int scanReturnCode) {\n switch(scanReturnCode) {\n case 0:\n return \"SCAN_UNKNOWN\";\n case 1:\n return \"SCAN_SUCCESS\";\n case 2:\n return \"SCAN_FAILURE_INTERRUPTED\";\n case 3:\n return \"SCAN_FAILURE_INVALID_CONFIGURATION\";\n case 4:\n return \"FAILURE_WIFI_DISABLED\";\n default:\n return \"\";\n }\n }\n\n public void incrementScanReturnEntry(int scanReturnCode, int countToAdd) {\n synchronized (this.mLock) {\n this.mScanReturnEntries.put(scanReturnCode, this.mScanReturnEntries.get(scanReturnCode) + countToAdd);\n }\n }\n\n public int getScanReturnEntry(int scanReturnCode) {\n int i;\n synchronized (this.mLock) {\n i = this.mScanReturnEntries.get(scanReturnCode);\n }\n return i;\n }\n\n private String wifiSystemStateToString(int state) {\n switch(state) {\n case 0:\n return \"WIFI_UNKNOWN\";\n case 1:\n return \"WIFI_DISABLED\";\n case 2:\n return \"WIFI_DISCONNECTED\";\n case 3:\n return \"WIFI_ASSOCIATED\";\n default:\n return \"default\";\n }\n }\n\n public void incrementWifiSystemScanStateCount(int state, boolean screenOn) {\n synchronized (this.mLock) {\n int index = (state * 2) + (screenOn ? 1 : 0);\n this.mWifiSystemStateEntries.put(index, this.mWifiSystemStateEntries.get(index) + 1);\n }\n }\n\n public int getSystemStateCount(int state, boolean screenOn) {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiSystemStateEntries.get((state * 2) + (screenOn ? 1 : 0));\n }\n return i;\n }\n\n public void incrementNumLastResortWatchdogTriggers() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggers++;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAssociationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAssociationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAuthenticationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadDhcpNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadDhcpNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadOtherNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadOtherNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogAvailableNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogAvailableNetworksTotal += count;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAssociation() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAssociation++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAuthentication() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAuthentication++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadDhcp() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadDhcp++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadOther() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadOther++;\n }\n }\n\n ", "post_mask_code": "{\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoBad++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundBad++;\n }\n }\n\n public void incrementRssiPollRssiCount(int rssi) {\n if (rssi >= MIN_RSSI_POLL && rssi <= 0) {\n synchronized (this.mLock) {\n this.mRssiPollCounts.put(rssi, this.mRssiPollCounts.get(rssi) + 1);\n }\n }\n }\n\n public void incrementNumLastResortWatchdogSuccesses() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogSuccesses++;\n }\n }\n\n public void incrementAlertReasonCount(int reason) {\n if (reason > 64 || reason < 0) {\n reason = 0;\n }\n synchronized (this.mLock) {\n this.mWifiAlertReasonCounts.put(reason, this.mWifiAlertReasonCounts.get(reason) + 1);\n }\n }\n\n public void countScanResults(List scanDetails) {\n if (scanDetails != null) {\n int totalResults = 0;\n int openNetworks = 0;\n int personalNetworks = 0;\n int enterpriseNetworks = 0;\n int hiddenNetworks = 0;\n int hotspot2r1Networks = 0;\n int hotspot2r2Networks = 0;\n for (ScanDetail scanDetail : scanDetails) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n totalResults++;\n if (networkDetail != null) {\n if (networkDetail.isHiddenBeaconFrame()) {\n hiddenNetworks++;\n }\n if (networkDetail.getHSRelease() != null) {\n if (networkDetail.getHSRelease() == HSRelease.R1) {\n hotspot2r1Networks++;\n } else if (networkDetail.getHSRelease() == HSRelease.R2) {\n hotspot2r2Networks++;\n }\n }\n }\n if (!(scanResult == null || scanResult.capabilities == null)) {\n if (scanResult.capabilities.contains(\"EAP\")) {\n enterpriseNetworks++;\n } else if (scanResult.capabilities.contains(\"PSK\") || scanResult.capabilities.contains(\"WEP\")) {\n personalNetworks++;\n } else {\n openNetworks++;\n }\n }\n }\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numTotalScanResults += totalResults;\n wifiLog = this.mWifiLogProto;\n wifiLog.numOpenNetworkScanResults += openNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numPersonalNetworkScanResults += personalNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numEnterpriseNetworkScanResults += enterpriseNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHiddenNetworkScanResults += hiddenNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R1NetworkScanResults += hotspot2r1Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R2NetworkScanResults += hotspot2r2Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numScans++;\n }\n }\n }\n\n public void incrementWifiScoreCount(int score) {\n if (score >= 0 && score <= 5) {\n synchronized (this.mLock) {\n this.mWifiScoreCounts.put(score, this.mWifiScoreCounts.get(score) + 1);\n }\n }\n }\n\n public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {\n synchronized (this.mLock) {\n int i;\n if (args != null) {\n if (args.length > 0 && PROTO_DUMP_ARG.equals(args[0])) {\n consolidateProto(true);\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (this.mCurrentConnectionEvent != event) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n String metricsProtoDump = Base64.encodeToString(MessageNano.toByteArray(this.mWifiLogProto), 0);\n if (args.length <= 1 || !CLEAN_DUMP_ARG.equals(args[1])) {\n pw.println(\"WifiMetrics:\");\n pw.println(metricsProtoDump);\n pw.println(\"EndWifiMetrics\");\n } else {\n pw.print(metricsProtoDump);\n }\n clear();\n }\n }\n pw.println(\"WifiMetrics:\");\n pw.println(\"mConnectionEvents:\");\n for (ConnectionEvent event2 : this.mConnectionEventList) {\n String eventLine = event2.toString();\n if (event2 == this.mCurrentConnectionEvent) {\n eventLine = eventLine + \"CURRENTLY OPEN EVENT\";\n }\n pw.println(eventLine);\n }\n pw.println(\"mWifiLogProto.numSavedNetworks=\" + this.mWifiLogProto.numSavedNetworks);\n pw.println(\"mWifiLogProto.numOpenNetworks=\" + this.mWifiLogProto.numOpenNetworks);\n pw.println(\"mWifiLogProto.numPersonalNetworks=\" + this.mWifiLogProto.numPersonalNetworks);\n pw.println(\"mWifiLogProto.numEnterpriseNetworks=\" + this.mWifiLogProto.numEnterpriseNetworks);\n pw.println(\"mWifiLogProto.numHiddenNetworks=\" + this.mWifiLogProto.numHiddenNetworks);\n pw.println(\"mWifiLogProto.numPasspointNetworks=\" + this.mWifiLogProto.numPasspointNetworks);\n pw.println(\"mWifiLogProto.isLocationEnabled=\" + this.mWifiLogProto.isLocationEnabled);\n pw.println(\"mWifiLogProto.isScanningAlwaysEnabled=\" + this.mWifiLogProto.isScanningAlwaysEnabled);\n pw.println(\"mWifiLogProto.numNetworksAddedByUser=\" + this.mWifiLogProto.numNetworksAddedByUser);\n pw.println(\"mWifiLogProto.numNetworksAddedByApps=\" + this.mWifiLogProto.numNetworksAddedByApps);\n pw.println(\"mWifiLogProto.numNonEmptyScanResults=\" + this.mWifiLogProto.numNonEmptyScanResults);\n pw.println(\"mWifiLogProto.numEmptyScanResults=\" + this.mWifiLogProto.numEmptyScanResults);\n pw.println(\"mWifiLogProto.numOneshotScans=\" + this.mWifiLogProto.numOneshotScans);\n pw.println(\"mWifiLogProto.numBackgroundScans=\" + this.mWifiLogProto.numBackgroundScans);\n pw.println(\"mScanReturnEntries:\");\n pw.println(\" SCAN_UNKNOWN: \" + getScanReturnEntry(0));\n pw.println(\" SCAN_SUCCESS: \" + getScanReturnEntry(1));\n pw.println(\" SCAN_FAILURE_INTERRUPTED: \" + getScanReturnEntry(2));\n pw.println(\" SCAN_FAILURE_INVALID_CONFIGURATION: \" + getScanReturnEntry(3));\n pw.println(\" FAILURE_WIFI_DISABLED: \" + getScanReturnEntry(4));\n pw.println(\"mSystemStateEntries: : \");\n pw.println(\" WIFI_UNKNOWN ON: \" + getSystemStateCount(0, true));\n pw.println(\" WIFI_DISABLED ON: \" + getSystemStateCount(1, true));\n pw.println(\" WIFI_DISCONNECTED ON: \" + getSystemStateCount(2, true));\n pw.println(\" WIFI_ASSOCIATED ON: \" + getSystemStateCount(3, true));\n pw.println(\" WIFI_UNKNOWN OFF: \" + getSystemStateCount(0, false));\n pw.println(\" WIFI_DISABLED OFF: \" + getSystemStateCount(1, false));\n pw.println(\" WIFI_DISCONNECTED OFF: \" + getSystemStateCount(2, false));\n pw.println(\" WIFI_ASSOCIATED OFF: \" + getSystemStateCount(3, false));\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoGood=\" + this.mWifiLogProto.numConnectivityWatchdogPnoGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoBad=\" + this.mWifiLogProto.numConnectivityWatchdogPnoBad);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundGood=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundBad=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundBad);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggers=\" + this.mWifiLogProto.numLastResortWatchdogTriggers);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadOther=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadOther);\n pw.println(\"mWifiLogProto.numLastResortWatchdogSuccesses=\" + this.mWifiLogProto.numLastResortWatchdogSuccesses);\n pw.println(\"mWifiLogProto.recordDurationSec=\" + ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec));\n pw.println(\"mWifiLogProto.rssiPollRssiCount: Printing counts for [-127, 0]\");\n StringBuilder sb = new StringBuilder();\n for (i = MIN_RSSI_POLL; i <= 0; i++) {\n sb.append(this.mRssiPollCounts.get(i)).append(\" \");\n }\n pw.println(\" \" + sb.toString());\n pw.print(\"mWifiLogProto.alertReasonCounts=\");\n sb.setLength(0);\n for (i = 0; i <= 64; i++) {\n int count = this.mWifiAlertReasonCounts.get(i);\n if (count > 0) {\n sb.append(\"(\").append(i).append(\",\").append(count).append(\"),\");\n }\n }\n if (sb.length() > 1) {\n sb.setLength(sb.length() - 1);\n pw.println(sb.toString());\n } else {\n pw.println(\"()\");\n }\n pw.println(\"mWifiLogProto.numTotalScanResults=\" + this.mWifiLogProto.numTotalScanResults);\n pw.println(\"mWifiLogProto.numOpenNetworkScanResults=\" + this.mWifiLogProto.numOpenNetworkScanResults);\n pw.println(\"mWifiLogProto.numPersonalNetworkScanResults=\" + this.mWifiLogProto.numPersonalNetworkScanResults);\n pw.println(\"mWifiLogProto.numEnterpriseNetworkScanResults=\" + this.mWifiLogProto.numEnterpriseNetworkScanResults);\n pw.println(\"mWifiLogProto.numHiddenNetworkScanResults=\" + this.mWifiLogProto.numHiddenNetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R1NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R1NetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R2NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R2NetworkScanResults);\n pw.println(\"mWifiLogProto.numScans=\" + this.mWifiLogProto.numScans);\n pw.println(\"mWifiLogProto.WifiScoreCount: [0, 5]\");\n for (i = 0; i <= 5; i++) {\n pw.print(this.mWifiScoreCounts.get(i) + \" \");\n }\n pw.print(\"\\n\");\n }\n }\n\n private void consolidateProto(boolean incremental) {\n List events = new ArrayList();\n List rssis = new ArrayList();\n List alertReasons = new ArrayList();\n List scores = new ArrayList();\n synchronized (this.mLock) {\n int i;\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (!(incremental && (this.mCurrentConnectionEvent == event || event.mConnectionEvent.automaticBugReportTaken))) {\n events.add(event.mConnectionEvent);\n if (incremental) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n }\n if (events.size() > 0) {\n this.mWifiLogProto.connectionEvent = (com.android.server.wifi.WifiMetricsProto.ConnectionEvent[]) events.toArray(this.mWifiLogProto.connectionEvent);\n }\n this.mWifiLogProto.scanReturnEntries = new ScanReturnEntry[this.mScanReturnEntries.size()];\n for (i = 0; i < this.mScanReturnEntries.size(); i++) {\n this.mWifiLogProto.scanReturnEntries[i] = new ScanReturnEntry();\n this.mWifiLogProto.scanReturnEntries[i].scanReturnCode = this.mScanReturnEntries.keyAt(i);\n this.mWifiLogProto.scanReturnEntries[i].scanResultsCount = this.mScanReturnEntries.valueAt(i);\n }\n this.mWifiLogProto.wifiSystemStateEntries = new WifiSystemStateEntry[this.mWifiSystemStateEntries.size()];\n for (i = 0; i < this.mWifiSystemStateEntries.size(); i++) {\n this.mWifiLogProto.wifiSystemStateEntries[i] = new WifiSystemStateEntry();\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiState = this.mWifiSystemStateEntries.keyAt(i) / 2;\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiStateCount = this.mWifiSystemStateEntries.valueAt(i);\n this.mWifiLogProto.wifiSystemStateEntries[i].isScreenOn = this.mWifiSystemStateEntries.keyAt(i) % 2 > 0;\n }\n this.mWifiLogProto.recordDurationSec = (int) ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec);\n for (i = 0; i < this.mRssiPollCounts.size(); i++) {\n RssiPollCount keyVal = new RssiPollCount();\n keyVal.rssi = this.mRssiPollCounts.keyAt(i);\n keyVal.count = this.mRssiPollCounts.valueAt(i);\n rssis.add(keyVal);\n }\n this.mWifiLogProto.rssiPollRssiCount = (RssiPollCount[]) rssis.toArray(this.mWifiLogProto.rssiPollRssiCount);\n for (i = 0; i < this.mWifiAlertReasonCounts.size(); i++) {\n AlertReasonCount keyVal2 = new AlertReasonCount();\n keyVal2.reason = this.mWifiAlertReasonCounts.keyAt(i);\n keyVal2.count = this.mWifiAlertReasonCounts.valueAt(i);\n alertReasons.add(keyVal2);\n }\n this.mWifiLogProto.alertReasonCount = (AlertReasonCount[]) alertReasons.toArray(this.mWifiLogProto.alertReasonCount);\n for (int score = 0; score < this.mWifiScoreCounts.size(); score++) {\n WifiScoreCount keyVal3 = new WifiScoreCount();\n keyVal3.score = this.mWifiScoreCounts.keyAt(score);\n keyVal3.count = this.mWifiScoreCounts.valueAt(score);\n scores.add(keyVal3);\n }\n this.mWifiLogProto.wifiScoreCount = (WifiScoreCount[]) scores.toArray(this.mWifiLogProto.wifiScoreCount);\n }\n }\n\n private void clear() {\n synchronized (this.mLock) {\n this.mConnectionEventList.clear();\n if (this.mCurrentConnectionEvent != null) {\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n this.mScanReturnEntries.clear();\n this.mWifiSystemStateEntries.clear();\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n this.mRssiPollCounts.clear();\n this.mWifiAlertReasonCounts.clear();\n this.mWifiScoreCounts.clear();\n this.mWifiLogProto.clear();\n }\n }\n\n public void setScreenState(boolean screenOn) {\n synchronized (this.mLock) {\n this.mScreenOn = screenOn;\n }\n }\n\n public void setWifiState(int wifiState) {\n synchronized (this.mLock) {\n this.mWifiState = wifiState;\n }\n }\n}\n"} {"task_id": "Java_688", "language": "Java", "task_type": "method_body", "source_file": "java/github/dstmath/OppoFramework/A1_7_1_1/src/main/java/com/android/server/wifi/WifiMetrics.java", "mask_start_position": 23627, "mask_end_position": 23804, "canonical_solution": "{\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogAvailableNetworksTotal += count;\n }\n }", "pre_mask_code": "package com.android.server.wifi;\n\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiConfiguration;\nimport android.util.Base64;\nimport android.util.SparseIntArray;\nimport com.android.server.wifi.WifiMetricsProto.AlertReasonCount;\nimport com.android.server.wifi.WifiMetricsProto.RssiPollCount;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.ScanReturnEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.WifiSystemStateEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiScoreCount;\nimport com.android.server.wifi.hotspot2.NetworkDetail;\nimport com.android.server.wifi.hotspot2.NetworkDetail.HSRelease;\nimport com.google.protobuf.nano.MessageNano;\nimport java.io.FileDescriptor;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.List;\n\npublic class WifiMetrics {\n\n public static final String CLEAN_DUMP_ARG = \"clean\";\n\n private static final boolean DBG = false;\n\n private static final int MAX_CONNECTION_EVENTS = 256;\n\n private static final int MAX_RSSI_POLL = 0;\n\n private static final int MAX_WIFI_SCORE = 5;\n\n private static final int MIN_RSSI_POLL = -127;\n\n private static final int MIN_WIFI_SCORE = 0;\n\n public static final String PROTO_DUMP_ARG = \"wifiMetricsProto\";\n\n private static final int SCREEN_OFF = 0;\n\n private static final int SCREEN_ON = 1;\n\n private static final String TAG = \"WifiMetrics\";\n\n private Clock mClock;\n\n private final List mConnectionEventList = new ArrayList();\n\n private ConnectionEvent mCurrentConnectionEvent;\n\n private final Object mLock = new Object();\n\n private long mRecordStartTimeSec;\n\n private final SparseIntArray mRssiPollCounts = new SparseIntArray();\n\n private final SparseIntArray mScanReturnEntries = new SparseIntArray();\n\n private boolean mScreenOn;\n\n private final SparseIntArray mWifiAlertReasonCounts = new SparseIntArray();\n\n private final WifiLog mWifiLogProto = new WifiLog();\n\n private final SparseIntArray mWifiScoreCounts = new SparseIntArray();\n\n private int mWifiState;\n\n private final SparseIntArray mWifiSystemStateEntries = new SparseIntArray();\n\n class ConnectionEvent {\n\n public static final int FAILURE_ASSOCIATION_REJECTION = 2;\n\n public static final int FAILURE_AUTHENTICATION_FAILURE = 3;\n\n public static final int FAILURE_CONNECT_NETWORK_FAILED = 5;\n\n public static final int FAILURE_DHCP = 10;\n\n public static final int FAILURE_NETWORK_DISCONNECTION = 6;\n\n public static final int FAILURE_NEW_CONNECTION_ATTEMPT = 7;\n\n public static final int FAILURE_NONE = 1;\n\n public static final int FAILURE_REDUNDANT_CONNECTION_ATTEMPT = 8;\n\n public static final int FAILURE_ROAM_TIMEOUT = 9;\n\n public static final int FAILURE_SSID_TEMP_DISABLED = 4;\n\n public static final int FAILURE_UNKNOWN = 0;\n\n private String mConfigBssid;\n\n private String mConfigSsid;\n\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent mConnectionEvent;\n\n private long mRealEndTime;\n\n private long mRealStartTime;\n\n RouterFingerPrint mRouterFingerPrint;\n\n private boolean mScreenOn;\n\n private int mWifiState;\n\n /* synthetic */\n ConnectionEvent(WifiMetrics this$0, ConnectionEvent connectionEvent) {\n this();\n }\n\n private ConnectionEvent() {\n this.mConnectionEvent = new com.android.server.wifi.WifiMetricsProto.ConnectionEvent();\n this.mRealEndTime = 0;\n this.mRealStartTime = 0;\n this.mRouterFingerPrint = new RouterFingerPrint();\n this.mConnectionEvent.routerFingerprint = this.mRouterFingerPrint.mRouterFingerPrintProto;\n this.mConfigSsid = \"\";\n this.mConfigBssid = \"\";\n this.mWifiState = 0;\n this.mScreenOn = false;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"startTime=\");\n Calendar c = Calendar.getInstance();\n synchronized (WifiMetrics.this.mLock) {\n String str;\n c.setTimeInMillis(this.mConnectionEvent.startTimeMillis);\n if (this.mConnectionEvent.startTimeMillis == 0) {\n str = \" \";\n } else {\n str = String.format(\"%tm-%td %tH:%tM:%tS.%tL\", new Object[] { c, c, c, c, c, c });\n }\n sb.append(str);\n sb.append(\", SSID=\");\n sb.append(this.mConfigSsid);\n sb.append(\", BSSID=\");\n sb.append(this.mConfigBssid);\n sb.append(\", durationMillis=\");\n sb.append(this.mConnectionEvent.durationTakenToConnectMillis);\n sb.append(\", roamType=\");\n switch(this.mConnectionEvent.roamType) {\n case 1:\n sb.append(\"ROAM_NONE\");\n break;\n case 2:\n sb.append(\"ROAM_DBDC\");\n break;\n case 3:\n sb.append(\"ROAM_ENTERPRISE\");\n break;\n case 4:\n sb.append(\"ROAM_USER_SELECTED\");\n break;\n case 5:\n sb.append(\"ROAM_UNRELATED\");\n break;\n default:\n sb.append(\"ROAM_UNKNOWN\");\n break;\n }\n sb.append(\", connectionResult=\");\n sb.append(this.mConnectionEvent.connectionResult);\n sb.append(\", level2FailureCode=\");\n switch(this.mConnectionEvent.level2FailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"ASSOCIATION_REJECTION\");\n break;\n case 3:\n sb.append(\"AUTHENTICATION_FAILURE\");\n break;\n case 4:\n sb.append(\"SSID_TEMP_DISABLED\");\n break;\n case 5:\n sb.append(\"CONNECT_NETWORK_FAILED\");\n break;\n case 6:\n sb.append(\"NETWORK_DISCONNECTION\");\n break;\n case 7:\n sb.append(\"NEW_CONNECTION_ATTEMPT\");\n break;\n case 8:\n sb.append(\"REDUNDANT_CONNECTION_ATTEMPT\");\n break;\n case 9:\n sb.append(\"ROAM_TIMEOUT\");\n break;\n case 10:\n sb.append(\"DHCP\");\n break;\n }\n sb.append(\"UNKNOWN\");\n sb.append(\", connectivityLevelFailureCode=\");\n switch(this.mConnectionEvent.connectivityLevelFailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"DHCP\");\n break;\n case 3:\n sb.append(\"NO_INTERNET\");\n break;\n case 4:\n sb.append(\"UNWANTED\");\n break;\n default:\n sb.append(\"UNKNOWN\");\n break;\n }\n sb.append(\", signalStrength=\");\n sb.append(this.mConnectionEvent.signalStrength);\n sb.append(\", wifiState=\");\n switch(this.mWifiState) {\n case 1:\n sb.append(\"WIFI_DISABLED\");\n break;\n case 2:\n sb.append(\"WIFI_DISCONNECTED\");\n break;\n case 3:\n sb.append(\"WIFI_ASSOCIATED\");\n break;\n default:\n sb.append(\"WIFI_UNKNOWN\");\n break;\n }\n sb.append(\", screenOn=\");\n sb.append(this.mScreenOn);\n sb.append(\". mRouterFingerprint: \");\n sb.append(this.mRouterFingerPrint.toString());\n }\n return sb.toString();\n }\n }\n\n class RouterFingerPrint {\n\n private com.android.server.wifi.WifiMetricsProto.RouterFingerPrint mRouterFingerPrintProto = new com.android.server.wifi.WifiMetricsProto.RouterFingerPrint();\n\n RouterFingerPrint() {\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n synchronized (WifiMetrics.this.mLock) {\n sb.append(\"mConnectionEvent.roamType=\").append(this.mRouterFingerPrintProto.roamType);\n sb.append(\", mChannelInfo=\").append(this.mRouterFingerPrintProto.channelInfo);\n sb.append(\", mDtim=\").append(this.mRouterFingerPrintProto.dtim);\n sb.append(\", mAuthentication=\").append(this.mRouterFingerPrintProto.authentication);\n sb.append(\", mHidden=\").append(this.mRouterFingerPrintProto.hidden);\n sb.append(\", mRouterTechnology=\").append(this.mRouterFingerPrintProto.routerTechnology);\n sb.append(\", mSupportsIpv6=\").append(this.mRouterFingerPrintProto.supportsIpv6);\n }\n return sb.toString();\n }\n\n public void updateFromWifiConfiguration(WifiConfiguration config) {\n synchronized (WifiMetrics.this.mLock) {\n if (config != null) {\n this.mRouterFingerPrintProto.hidden = config.hiddenSSID;\n if (config.dtimInterval > 0) {\n this.mRouterFingerPrintProto.dtim = config.dtimInterval;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mConfigSsid = config.SSID;\n if (config.allowedKeyManagement != null && config.allowedKeyManagement.get(0)) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n } else if (config.isEnterprise()) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n } else {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.passpoint = config.isPasspoint();\n ScanResult candidate = config.getNetworkSelectionStatus().getCandidate();\n if (candidate != null) {\n WifiMetrics.this.updateMetricsFromScanResult(candidate);\n }\n }\n }\n }\n }\n\n public WifiMetrics(Clock clock) {\n this.mClock = clock;\n this.mCurrentConnectionEvent = null;\n this.mScreenOn = true;\n this.mWifiState = 1;\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n }\n\n public void startConnectionEvent(WifiConfiguration config, String targetBSSID, int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n if (this.mCurrentConnectionEvent.mConfigSsid == null || this.mCurrentConnectionEvent.mConfigBssid == null || config == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(config.SSID) || !(this.mCurrentConnectionEvent.mConfigBssid.equals(WifiLastResortWatchdog.BSSID_ANY) || this.mCurrentConnectionEvent.mConfigBssid.equals(targetBSSID))) {\n endConnectionEvent(7, 1);\n } else {\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n endConnectionEvent(8, 1);\n }\n }\n while (this.mConnectionEventList.size() >= 256) {\n this.mConnectionEventList.remove(0);\n }\n this.mCurrentConnectionEvent = new ConnectionEvent(this, null);\n this.mCurrentConnectionEvent.mConnectionEvent.startTimeMillis = this.mClock.currentTimeMillis();\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n this.mCurrentConnectionEvent.mRouterFingerPrint.updateFromWifiConfiguration(config);\n this.mCurrentConnectionEvent.mConfigBssid = WifiLastResortWatchdog.BSSID_ANY;\n this.mCurrentConnectionEvent.mRealStartTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mWifiState = this.mWifiState;\n this.mCurrentConnectionEvent.mScreenOn = this.mScreenOn;\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n }\n\n public void setConnectionEventRoamType(int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n }\n }\n }\n\n public void setConnectionScanDetail(ScanDetail scanDetail) {\n synchronized (this.mLock) {\n if (!(this.mCurrentConnectionEvent == null || scanDetail == null)) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n if (!(networkDetail == null || scanResult == null || this.mCurrentConnectionEvent.mConfigSsid == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(\"\\\"\" + networkDetail.getSSID() + \"\\\"\"))) {\n updateMetricsFromNetworkDetail(networkDetail);\n updateMetricsFromScanResult(scanResult);\n }\n }\n }\n }\n\n public void endConnectionEvent(int level2FailureCode, int connectivityFailureCode) {\n int i = 1;\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n boolean result = level2FailureCode == 1 ? connectivityFailureCode == 1 : false;\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent connectionEvent = this.mCurrentConnectionEvent.mConnectionEvent;\n if (!result) {\n i = 0;\n }\n connectionEvent.connectionResult = i;\n this.mCurrentConnectionEvent.mRealEndTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mConnectionEvent.durationTakenToConnectMillis = (int) (this.mCurrentConnectionEvent.mRealEndTime - this.mCurrentConnectionEvent.mRealStartTime);\n this.mCurrentConnectionEvent.mConnectionEvent.level2FailureCode = level2FailureCode;\n this.mCurrentConnectionEvent.mConnectionEvent.connectivityLevelFailureCode = connectivityFailureCode;\n this.mCurrentConnectionEvent = null;\n }\n }\n }\n\n private void updateMetricsFromNetworkDetail(NetworkDetail networkDetail) {\n int connectionWifiMode;\n int dtimInterval = networkDetail.getDtimInterval();\n if (dtimInterval > 0) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.dtim = dtimInterval;\n }\n switch(networkDetail.getWifiMode()) {\n case 0:\n connectionWifiMode = 0;\n break;\n case 1:\n connectionWifiMode = 1;\n break;\n case 2:\n connectionWifiMode = 2;\n break;\n case 3:\n connectionWifiMode = 3;\n break;\n case 4:\n connectionWifiMode = 4;\n break;\n case 5:\n connectionWifiMode = 5;\n break;\n default:\n connectionWifiMode = 6;\n break;\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.routerTechnology = connectionWifiMode;\n }\n\n private void updateMetricsFromScanResult(ScanResult scanResult) {\n this.mCurrentConnectionEvent.mConnectionEvent.signalStrength = scanResult.level;\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n this.mCurrentConnectionEvent.mConfigBssid = scanResult.BSSID;\n if (scanResult.capabilities != null) {\n if (scanResult.capabilities.contains(\"WEP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"PSK\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"EAP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n }\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.channelInfo = scanResult.frequency;\n }\n\n void setNumSavedNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numSavedNetworks = num;\n }\n }\n\n void setNumOpenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numOpenNetworks = num;\n }\n }\n\n void setNumPersonalNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPersonalNetworks = num;\n }\n }\n\n void setNumEnterpriseNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numEnterpriseNetworks = num;\n }\n }\n\n void setNumHiddenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numHiddenNetworks = num;\n }\n }\n\n void setNumPasspointNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPasspointNetworks = num;\n }\n }\n\n void setNumNetworksAddedByUser(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByUser = num;\n }\n }\n\n void setNumNetworksAddedByApps(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByApps = num;\n }\n }\n\n void setIsLocationEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isLocationEnabled = enabled;\n }\n }\n\n void setIsScanningAlwaysEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isScanningAlwaysEnabled = enabled;\n }\n }\n\n public void incrementNonEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numNonEmptyScanResults++;\n }\n }\n\n public void incrementEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numEmptyScanResults++;\n }\n }\n\n public void incrementBackgroundScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numBackgroundScans++;\n }\n }\n\n public int getBackgroundScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numBackgroundScans;\n }\n return i;\n }\n\n public void incrementOneshotScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numOneshotScans++;\n }\n incrementWifiSystemScanStateCount(this.mWifiState, this.mScreenOn);\n }\n\n public int getOneshotScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numOneshotScans;\n }\n return i;\n }\n\n private String returnCodeToString(int scanReturnCode) {\n switch(scanReturnCode) {\n case 0:\n return \"SCAN_UNKNOWN\";\n case 1:\n return \"SCAN_SUCCESS\";\n case 2:\n return \"SCAN_FAILURE_INTERRUPTED\";\n case 3:\n return \"SCAN_FAILURE_INVALID_CONFIGURATION\";\n case 4:\n return \"FAILURE_WIFI_DISABLED\";\n default:\n return \"\";\n }\n }\n\n public void incrementScanReturnEntry(int scanReturnCode, int countToAdd) {\n synchronized (this.mLock) {\n this.mScanReturnEntries.put(scanReturnCode, this.mScanReturnEntries.get(scanReturnCode) + countToAdd);\n }\n }\n\n public int getScanReturnEntry(int scanReturnCode) {\n int i;\n synchronized (this.mLock) {\n i = this.mScanReturnEntries.get(scanReturnCode);\n }\n return i;\n }\n\n private String wifiSystemStateToString(int state) {\n switch(state) {\n case 0:\n return \"WIFI_UNKNOWN\";\n case 1:\n return \"WIFI_DISABLED\";\n case 2:\n return \"WIFI_DISCONNECTED\";\n case 3:\n return \"WIFI_ASSOCIATED\";\n default:\n return \"default\";\n }\n }\n\n public void incrementWifiSystemScanStateCount(int state, boolean screenOn) {\n synchronized (this.mLock) {\n int index = (state * 2) + (screenOn ? 1 : 0);\n this.mWifiSystemStateEntries.put(index, this.mWifiSystemStateEntries.get(index) + 1);\n }\n }\n\n public int getSystemStateCount(int state, boolean screenOn) {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiSystemStateEntries.get((state * 2) + (screenOn ? 1 : 0));\n }\n return i;\n }\n\n public void incrementNumLastResortWatchdogTriggers() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggers++;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAssociationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAssociationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAuthenticationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadDhcpNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadDhcpNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadOtherNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadOtherNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogAvailableNetworksTotal(int count) ", "post_mask_code": "\n\n public void incrementNumLastResortWatchdogTriggersWithBadAssociation() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAssociation++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAuthentication() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAuthentication++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadDhcp() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadDhcp++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadOther() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadOther++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoBad++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundBad++;\n }\n }\n\n public void incrementRssiPollRssiCount(int rssi) {\n if (rssi >= MIN_RSSI_POLL && rssi <= 0) {\n synchronized (this.mLock) {\n this.mRssiPollCounts.put(rssi, this.mRssiPollCounts.get(rssi) + 1);\n }\n }\n }\n\n public void incrementNumLastResortWatchdogSuccesses() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogSuccesses++;\n }\n }\n\n public void incrementAlertReasonCount(int reason) {\n if (reason > 64 || reason < 0) {\n reason = 0;\n }\n synchronized (this.mLock) {\n this.mWifiAlertReasonCounts.put(reason, this.mWifiAlertReasonCounts.get(reason) + 1);\n }\n }\n\n public void countScanResults(List scanDetails) {\n if (scanDetails != null) {\n int totalResults = 0;\n int openNetworks = 0;\n int personalNetworks = 0;\n int enterpriseNetworks = 0;\n int hiddenNetworks = 0;\n int hotspot2r1Networks = 0;\n int hotspot2r2Networks = 0;\n for (ScanDetail scanDetail : scanDetails) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n totalResults++;\n if (networkDetail != null) {\n if (networkDetail.isHiddenBeaconFrame()) {\n hiddenNetworks++;\n }\n if (networkDetail.getHSRelease() != null) {\n if (networkDetail.getHSRelease() == HSRelease.R1) {\n hotspot2r1Networks++;\n } else if (networkDetail.getHSRelease() == HSRelease.R2) {\n hotspot2r2Networks++;\n }\n }\n }\n if (!(scanResult == null || scanResult.capabilities == null)) {\n if (scanResult.capabilities.contains(\"EAP\")) {\n enterpriseNetworks++;\n } else if (scanResult.capabilities.contains(\"PSK\") || scanResult.capabilities.contains(\"WEP\")) {\n personalNetworks++;\n } else {\n openNetworks++;\n }\n }\n }\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numTotalScanResults += totalResults;\n wifiLog = this.mWifiLogProto;\n wifiLog.numOpenNetworkScanResults += openNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numPersonalNetworkScanResults += personalNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numEnterpriseNetworkScanResults += enterpriseNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHiddenNetworkScanResults += hiddenNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R1NetworkScanResults += hotspot2r1Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R2NetworkScanResults += hotspot2r2Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numScans++;\n }\n }\n }\n\n public void incrementWifiScoreCount(int score) {\n if (score >= 0 && score <= 5) {\n synchronized (this.mLock) {\n this.mWifiScoreCounts.put(score, this.mWifiScoreCounts.get(score) + 1);\n }\n }\n }\n\n public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {\n synchronized (this.mLock) {\n int i;\n if (args != null) {\n if (args.length > 0 && PROTO_DUMP_ARG.equals(args[0])) {\n consolidateProto(true);\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (this.mCurrentConnectionEvent != event) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n String metricsProtoDump = Base64.encodeToString(MessageNano.toByteArray(this.mWifiLogProto), 0);\n if (args.length <= 1 || !CLEAN_DUMP_ARG.equals(args[1])) {\n pw.println(\"WifiMetrics:\");\n pw.println(metricsProtoDump);\n pw.println(\"EndWifiMetrics\");\n } else {\n pw.print(metricsProtoDump);\n }\n clear();\n }\n }\n pw.println(\"WifiMetrics:\");\n pw.println(\"mConnectionEvents:\");\n for (ConnectionEvent event2 : this.mConnectionEventList) {\n String eventLine = event2.toString();\n if (event2 == this.mCurrentConnectionEvent) {\n eventLine = eventLine + \"CURRENTLY OPEN EVENT\";\n }\n pw.println(eventLine);\n }\n pw.println(\"mWifiLogProto.numSavedNetworks=\" + this.mWifiLogProto.numSavedNetworks);\n pw.println(\"mWifiLogProto.numOpenNetworks=\" + this.mWifiLogProto.numOpenNetworks);\n pw.println(\"mWifiLogProto.numPersonalNetworks=\" + this.mWifiLogProto.numPersonalNetworks);\n pw.println(\"mWifiLogProto.numEnterpriseNetworks=\" + this.mWifiLogProto.numEnterpriseNetworks);\n pw.println(\"mWifiLogProto.numHiddenNetworks=\" + this.mWifiLogProto.numHiddenNetworks);\n pw.println(\"mWifiLogProto.numPasspointNetworks=\" + this.mWifiLogProto.numPasspointNetworks);\n pw.println(\"mWifiLogProto.isLocationEnabled=\" + this.mWifiLogProto.isLocationEnabled);\n pw.println(\"mWifiLogProto.isScanningAlwaysEnabled=\" + this.mWifiLogProto.isScanningAlwaysEnabled);\n pw.println(\"mWifiLogProto.numNetworksAddedByUser=\" + this.mWifiLogProto.numNetworksAddedByUser);\n pw.println(\"mWifiLogProto.numNetworksAddedByApps=\" + this.mWifiLogProto.numNetworksAddedByApps);\n pw.println(\"mWifiLogProto.numNonEmptyScanResults=\" + this.mWifiLogProto.numNonEmptyScanResults);\n pw.println(\"mWifiLogProto.numEmptyScanResults=\" + this.mWifiLogProto.numEmptyScanResults);\n pw.println(\"mWifiLogProto.numOneshotScans=\" + this.mWifiLogProto.numOneshotScans);\n pw.println(\"mWifiLogProto.numBackgroundScans=\" + this.mWifiLogProto.numBackgroundScans);\n pw.println(\"mScanReturnEntries:\");\n pw.println(\" SCAN_UNKNOWN: \" + getScanReturnEntry(0));\n pw.println(\" SCAN_SUCCESS: \" + getScanReturnEntry(1));\n pw.println(\" SCAN_FAILURE_INTERRUPTED: \" + getScanReturnEntry(2));\n pw.println(\" SCAN_FAILURE_INVALID_CONFIGURATION: \" + getScanReturnEntry(3));\n pw.println(\" FAILURE_WIFI_DISABLED: \" + getScanReturnEntry(4));\n pw.println(\"mSystemStateEntries: : \");\n pw.println(\" WIFI_UNKNOWN ON: \" + getSystemStateCount(0, true));\n pw.println(\" WIFI_DISABLED ON: \" + getSystemStateCount(1, true));\n pw.println(\" WIFI_DISCONNECTED ON: \" + getSystemStateCount(2, true));\n pw.println(\" WIFI_ASSOCIATED ON: \" + getSystemStateCount(3, true));\n pw.println(\" WIFI_UNKNOWN OFF: \" + getSystemStateCount(0, false));\n pw.println(\" WIFI_DISABLED OFF: \" + getSystemStateCount(1, false));\n pw.println(\" WIFI_DISCONNECTED OFF: \" + getSystemStateCount(2, false));\n pw.println(\" WIFI_ASSOCIATED OFF: \" + getSystemStateCount(3, false));\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoGood=\" + this.mWifiLogProto.numConnectivityWatchdogPnoGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoBad=\" + this.mWifiLogProto.numConnectivityWatchdogPnoBad);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundGood=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundBad=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundBad);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggers=\" + this.mWifiLogProto.numLastResortWatchdogTriggers);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadOther=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadOther);\n pw.println(\"mWifiLogProto.numLastResortWatchdogSuccesses=\" + this.mWifiLogProto.numLastResortWatchdogSuccesses);\n pw.println(\"mWifiLogProto.recordDurationSec=\" + ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec));\n pw.println(\"mWifiLogProto.rssiPollRssiCount: Printing counts for [-127, 0]\");\n StringBuilder sb = new StringBuilder();\n for (i = MIN_RSSI_POLL; i <= 0; i++) {\n sb.append(this.mRssiPollCounts.get(i)).append(\" \");\n }\n pw.println(\" \" + sb.toString());\n pw.print(\"mWifiLogProto.alertReasonCounts=\");\n sb.setLength(0);\n for (i = 0; i <= 64; i++) {\n int count = this.mWifiAlertReasonCounts.get(i);\n if (count > 0) {\n sb.append(\"(\").append(i).append(\",\").append(count).append(\"),\");\n }\n }\n if (sb.length() > 1) {\n sb.setLength(sb.length() - 1);\n pw.println(sb.toString());\n } else {\n pw.println(\"()\");\n }\n pw.println(\"mWifiLogProto.numTotalScanResults=\" + this.mWifiLogProto.numTotalScanResults);\n pw.println(\"mWifiLogProto.numOpenNetworkScanResults=\" + this.mWifiLogProto.numOpenNetworkScanResults);\n pw.println(\"mWifiLogProto.numPersonalNetworkScanResults=\" + this.mWifiLogProto.numPersonalNetworkScanResults);\n pw.println(\"mWifiLogProto.numEnterpriseNetworkScanResults=\" + this.mWifiLogProto.numEnterpriseNetworkScanResults);\n pw.println(\"mWifiLogProto.numHiddenNetworkScanResults=\" + this.mWifiLogProto.numHiddenNetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R1NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R1NetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R2NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R2NetworkScanResults);\n pw.println(\"mWifiLogProto.numScans=\" + this.mWifiLogProto.numScans);\n pw.println(\"mWifiLogProto.WifiScoreCount: [0, 5]\");\n for (i = 0; i <= 5; i++) {\n pw.print(this.mWifiScoreCounts.get(i) + \" \");\n }\n pw.print(\"\\n\");\n }\n }\n\n private void consolidateProto(boolean incremental) {\n List events = new ArrayList();\n List rssis = new ArrayList();\n List alertReasons = new ArrayList();\n List scores = new ArrayList();\n synchronized (this.mLock) {\n int i;\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (!(incremental && (this.mCurrentConnectionEvent == event || event.mConnectionEvent.automaticBugReportTaken))) {\n events.add(event.mConnectionEvent);\n if (incremental) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n }\n if (events.size() > 0) {\n this.mWifiLogProto.connectionEvent = (com.android.server.wifi.WifiMetricsProto.ConnectionEvent[]) events.toArray(this.mWifiLogProto.connectionEvent);\n }\n this.mWifiLogProto.scanReturnEntries = new ScanReturnEntry[this.mScanReturnEntries.size()];\n for (i = 0; i < this.mScanReturnEntries.size(); i++) {\n this.mWifiLogProto.scanReturnEntries[i] = new ScanReturnEntry();\n this.mWifiLogProto.scanReturnEntries[i].scanReturnCode = this.mScanReturnEntries.keyAt(i);\n this.mWifiLogProto.scanReturnEntries[i].scanResultsCount = this.mScanReturnEntries.valueAt(i);\n }\n this.mWifiLogProto.wifiSystemStateEntries = new WifiSystemStateEntry[this.mWifiSystemStateEntries.size()];\n for (i = 0; i < this.mWifiSystemStateEntries.size(); i++) {\n this.mWifiLogProto.wifiSystemStateEntries[i] = new WifiSystemStateEntry();\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiState = this.mWifiSystemStateEntries.keyAt(i) / 2;\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiStateCount = this.mWifiSystemStateEntries.valueAt(i);\n this.mWifiLogProto.wifiSystemStateEntries[i].isScreenOn = this.mWifiSystemStateEntries.keyAt(i) % 2 > 0;\n }\n this.mWifiLogProto.recordDurationSec = (int) ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec);\n for (i = 0; i < this.mRssiPollCounts.size(); i++) {\n RssiPollCount keyVal = new RssiPollCount();\n keyVal.rssi = this.mRssiPollCounts.keyAt(i);\n keyVal.count = this.mRssiPollCounts.valueAt(i);\n rssis.add(keyVal);\n }\n this.mWifiLogProto.rssiPollRssiCount = (RssiPollCount[]) rssis.toArray(this.mWifiLogProto.rssiPollRssiCount);\n for (i = 0; i < this.mWifiAlertReasonCounts.size(); i++) {\n AlertReasonCount keyVal2 = new AlertReasonCount();\n keyVal2.reason = this.mWifiAlertReasonCounts.keyAt(i);\n keyVal2.count = this.mWifiAlertReasonCounts.valueAt(i);\n alertReasons.add(keyVal2);\n }\n this.mWifiLogProto.alertReasonCount = (AlertReasonCount[]) alertReasons.toArray(this.mWifiLogProto.alertReasonCount);\n for (int score = 0; score < this.mWifiScoreCounts.size(); score++) {\n WifiScoreCount keyVal3 = new WifiScoreCount();\n keyVal3.score = this.mWifiScoreCounts.keyAt(score);\n keyVal3.count = this.mWifiScoreCounts.valueAt(score);\n scores.add(keyVal3);\n }\n this.mWifiLogProto.wifiScoreCount = (WifiScoreCount[]) scores.toArray(this.mWifiLogProto.wifiScoreCount);\n }\n }\n\n private void clear() {\n synchronized (this.mLock) {\n this.mConnectionEventList.clear();\n if (this.mCurrentConnectionEvent != null) {\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n this.mScanReturnEntries.clear();\n this.mWifiSystemStateEntries.clear();\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n this.mRssiPollCounts.clear();\n this.mWifiAlertReasonCounts.clear();\n this.mWifiScoreCounts.clear();\n this.mWifiLogProto.clear();\n }\n }\n\n public void setScreenState(boolean screenOn) {\n synchronized (this.mLock) {\n this.mScreenOn = screenOn;\n }\n }\n\n public void setWifiState(int wifiState) {\n synchronized (this.mLock) {\n this.mWifiState = wifiState;\n }\n }\n}\n"} {"task_id": "Java_689", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/dstmath/OppoFramework/A1_7_1_1/src/main/java/com/android/server/wifi/WifiMetrics.java", "mask_start_position": 25736, "mask_end_position": 25736, "canonical_solution": "", "pre_mask_code": "package com.android.server.wifi;\n\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiConfiguration;\nimport android.util.Base64;\nimport android.util.SparseIntArray;\nimport com.android.server.wifi.WifiMetricsProto.AlertReasonCount;\nimport com.android.server.wifi.WifiMetricsProto.RssiPollCount;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.ScanReturnEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.WifiSystemStateEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiScoreCount;\nimport com.android.server.wifi.hotspot2.NetworkDetail;\nimport com.android.server.wifi.hotspot2.NetworkDetail.HSRelease;\nimport com.google.protobuf.nano.MessageNano;\nimport java.io.FileDescriptor;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.List;\n\npublic class WifiMetrics {\n\n public static final String CLEAN_DUMP_ARG = \"clean\";\n\n private static final boolean DBG = false;\n\n private static final int MAX_CONNECTION_EVENTS = 256;\n\n private static final int MAX_RSSI_POLL = 0;\n\n private static final int MAX_WIFI_SCORE = 5;\n\n private static final int MIN_RSSI_POLL = -127;\n\n private static final int MIN_WIFI_SCORE = 0;\n\n public static final String PROTO_DUMP_ARG = \"wifiMetricsProto\";\n\n private static final int SCREEN_OFF = 0;\n\n private static final int SCREEN_ON = 1;\n\n private static final String TAG = \"WifiMetrics\";\n\n private Clock mClock;\n\n private final List mConnectionEventList = new ArrayList();\n\n private ConnectionEvent mCurrentConnectionEvent;\n\n private final Object mLock = new Object();\n\n private long mRecordStartTimeSec;\n\n private final SparseIntArray mRssiPollCounts = new SparseIntArray();\n\n private final SparseIntArray mScanReturnEntries = new SparseIntArray();\n\n private boolean mScreenOn;\n\n private final SparseIntArray mWifiAlertReasonCounts = new SparseIntArray();\n\n private final WifiLog mWifiLogProto = new WifiLog();\n\n private final SparseIntArray mWifiScoreCounts = new SparseIntArray();\n\n private int mWifiState;\n\n private final SparseIntArray mWifiSystemStateEntries = new SparseIntArray();\n\n class ConnectionEvent {\n\n public static final int FAILURE_ASSOCIATION_REJECTION = 2;\n\n public static final int FAILURE_AUTHENTICATION_FAILURE = 3;\n\n public static final int FAILURE_CONNECT_NETWORK_FAILED = 5;\n\n public static final int FAILURE_DHCP = 10;\n\n public static final int FAILURE_NETWORK_DISCONNECTION = 6;\n\n public static final int FAILURE_NEW_CONNECTION_ATTEMPT = 7;\n\n public static final int FAILURE_NONE = 1;\n\n public static final int FAILURE_REDUNDANT_CONNECTION_ATTEMPT = 8;\n\n public static final int FAILURE_ROAM_TIMEOUT = 9;\n\n public static final int FAILURE_SSID_TEMP_DISABLED = 4;\n\n public static final int FAILURE_UNKNOWN = 0;\n\n private String mConfigBssid;\n\n private String mConfigSsid;\n\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent mConnectionEvent;\n\n private long mRealEndTime;\n\n private long mRealStartTime;\n\n RouterFingerPrint mRouterFingerPrint;\n\n private boolean mScreenOn;\n\n private int mWifiState;\n\n /* synthetic */\n ConnectionEvent(WifiMetrics this$0, ConnectionEvent connectionEvent) {\n this();\n }\n\n private ConnectionEvent() {\n this.mConnectionEvent = new com.android.server.wifi.WifiMetricsProto.ConnectionEvent();\n this.mRealEndTime = 0;\n this.mRealStartTime = 0;\n this.mRouterFingerPrint = new RouterFingerPrint();\n this.mConnectionEvent.routerFingerprint = this.mRouterFingerPrint.mRouterFingerPrintProto;\n this.mConfigSsid = \"\";\n this.mConfigBssid = \"\";\n this.mWifiState = 0;\n this.mScreenOn = false;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"startTime=\");\n Calendar c = Calendar.getInstance();\n synchronized (WifiMetrics.this.mLock) {\n String str;\n c.setTimeInMillis(this.mConnectionEvent.startTimeMillis);\n if (this.mConnectionEvent.startTimeMillis == 0) {\n str = \" \";\n } else {\n str = String.format(\"%tm-%td %tH:%tM:%tS.%tL\", new Object[] { c, c, c, c, c, c });\n }\n sb.append(str);\n sb.append(\", SSID=\");\n sb.append(this.mConfigSsid);\n sb.append(\", BSSID=\");\n sb.append(this.mConfigBssid);\n sb.append(\", durationMillis=\");\n sb.append(this.mConnectionEvent.durationTakenToConnectMillis);\n sb.append(\", roamType=\");\n switch(this.mConnectionEvent.roamType) {\n case 1:\n sb.append(\"ROAM_NONE\");\n break;\n case 2:\n sb.append(\"ROAM_DBDC\");\n break;\n case 3:\n sb.append(\"ROAM_ENTERPRISE\");\n break;\n case 4:\n sb.append(\"ROAM_USER_SELECTED\");\n break;\n case 5:\n sb.append(\"ROAM_UNRELATED\");\n break;\n default:\n sb.append(\"ROAM_UNKNOWN\");\n break;\n }\n sb.append(\", connectionResult=\");\n sb.append(this.mConnectionEvent.connectionResult);\n sb.append(\", level2FailureCode=\");\n switch(this.mConnectionEvent.level2FailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"ASSOCIATION_REJECTION\");\n break;\n case 3:\n sb.append(\"AUTHENTICATION_FAILURE\");\n break;\n case 4:\n sb.append(\"SSID_TEMP_DISABLED\");\n break;\n case 5:\n sb.append(\"CONNECT_NETWORK_FAILED\");\n break;\n case 6:\n sb.append(\"NETWORK_DISCONNECTION\");\n break;\n case 7:\n sb.append(\"NEW_CONNECTION_ATTEMPT\");\n break;\n case 8:\n sb.append(\"REDUNDANT_CONNECTION_ATTEMPT\");\n break;\n case 9:\n sb.append(\"ROAM_TIMEOUT\");\n break;\n case 10:\n sb.append(\"DHCP\");\n break;\n }\n sb.append(\"UNKNOWN\");\n sb.append(\", connectivityLevelFailureCode=\");\n switch(this.mConnectionEvent.connectivityLevelFailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"DHCP\");\n break;\n case 3:\n sb.append(\"NO_INTERNET\");\n break;\n case 4:\n sb.append(\"UNWANTED\");\n break;\n default:\n sb.append(\"UNKNOWN\");\n break;\n }\n sb.append(\", signalStrength=\");\n sb.append(this.mConnectionEvent.signalStrength);\n sb.append(\", wifiState=\");\n switch(this.mWifiState) {\n case 1:\n sb.append(\"WIFI_DISABLED\");\n break;\n case 2:\n sb.append(\"WIFI_DISCONNECTED\");\n break;\n case 3:\n sb.append(\"WIFI_ASSOCIATED\");\n break;\n default:\n sb.append(\"WIFI_UNKNOWN\");\n break;\n }\n sb.append(\", screenOn=\");\n sb.append(this.mScreenOn);\n sb.append(\". mRouterFingerprint: \");\n sb.append(this.mRouterFingerPrint.toString());\n }\n return sb.toString();\n }\n }\n\n class RouterFingerPrint {\n\n private com.android.server.wifi.WifiMetricsProto.RouterFingerPrint mRouterFingerPrintProto = new com.android.server.wifi.WifiMetricsProto.RouterFingerPrint();\n\n RouterFingerPrint() {\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n synchronized (WifiMetrics.this.mLock) {\n sb.append(\"mConnectionEvent.roamType=\").append(this.mRouterFingerPrintProto.roamType);\n sb.append(\", mChannelInfo=\").append(this.mRouterFingerPrintProto.channelInfo);\n sb.append(\", mDtim=\").append(this.mRouterFingerPrintProto.dtim);\n sb.append(\", mAuthentication=\").append(this.mRouterFingerPrintProto.authentication);\n sb.append(\", mHidden=\").append(this.mRouterFingerPrintProto.hidden);\n sb.append(\", mRouterTechnology=\").append(this.mRouterFingerPrintProto.routerTechnology);\n sb.append(\", mSupportsIpv6=\").append(this.mRouterFingerPrintProto.supportsIpv6);\n }\n return sb.toString();\n }\n\n public void updateFromWifiConfiguration(WifiConfiguration config) {\n synchronized (WifiMetrics.this.mLock) {\n if (config != null) {\n this.mRouterFingerPrintProto.hidden = config.hiddenSSID;\n if (config.dtimInterval > 0) {\n this.mRouterFingerPrintProto.dtim = config.dtimInterval;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mConfigSsid = config.SSID;\n if (config.allowedKeyManagement != null && config.allowedKeyManagement.get(0)) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n } else if (config.isEnterprise()) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n } else {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.passpoint = config.isPasspoint();\n ScanResult candidate = config.getNetworkSelectionStatus().getCandidate();\n if (candidate != null) {\n WifiMetrics.this.updateMetricsFromScanResult(candidate);\n }\n }\n }\n }\n }\n\n public WifiMetrics(Clock clock) {\n this.mClock = clock;\n this.mCurrentConnectionEvent = null;\n this.mScreenOn = true;\n this.mWifiState = 1;\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n }\n\n public void startConnectionEvent(WifiConfiguration config, String targetBSSID, int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n if (this.mCurrentConnectionEvent.mConfigSsid == null || this.mCurrentConnectionEvent.mConfigBssid == null || config == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(config.SSID) || !(this.mCurrentConnectionEvent.mConfigBssid.equals(WifiLastResortWatchdog.BSSID_ANY) || this.mCurrentConnectionEvent.mConfigBssid.equals(targetBSSID))) {\n endConnectionEvent(7, 1);\n } else {\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n endConnectionEvent(8, 1);\n }\n }\n while (this.mConnectionEventList.size() >= 256) {\n this.mConnectionEventList.remove(0);\n }\n this.mCurrentConnectionEvent = new ConnectionEvent(this, null);\n this.mCurrentConnectionEvent.mConnectionEvent.startTimeMillis = this.mClock.currentTimeMillis();\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n this.mCurrentConnectionEvent.mRouterFingerPrint.updateFromWifiConfiguration(config);\n this.mCurrentConnectionEvent.mConfigBssid = WifiLastResortWatchdog.BSSID_ANY;\n this.mCurrentConnectionEvent.mRealStartTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mWifiState = this.mWifiState;\n this.mCurrentConnectionEvent.mScreenOn = this.mScreenOn;\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n }\n\n public void setConnectionEventRoamType(int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n }\n }\n }\n\n public void setConnectionScanDetail(ScanDetail scanDetail) {\n synchronized (this.mLock) {\n if (!(this.mCurrentConnectionEvent == null || scanDetail == null)) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n if (!(networkDetail == null || scanResult == null || this.mCurrentConnectionEvent.mConfigSsid == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(\"\\\"\" + networkDetail.getSSID() + \"\\\"\"))) {\n updateMetricsFromNetworkDetail(networkDetail);\n updateMetricsFromScanResult(scanResult);\n }\n }\n }\n }\n\n public void endConnectionEvent(int level2FailureCode, int connectivityFailureCode) {\n int i = 1;\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n boolean result = level2FailureCode == 1 ? connectivityFailureCode == 1 : false;\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent connectionEvent = this.mCurrentConnectionEvent.mConnectionEvent;\n if (!result) {\n i = 0;\n }\n connectionEvent.connectionResult = i;\n this.mCurrentConnectionEvent.mRealEndTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mConnectionEvent.durationTakenToConnectMillis = (int) (this.mCurrentConnectionEvent.mRealEndTime - this.mCurrentConnectionEvent.mRealStartTime);\n this.mCurrentConnectionEvent.mConnectionEvent.level2FailureCode = level2FailureCode;\n this.mCurrentConnectionEvent.mConnectionEvent.connectivityLevelFailureCode = connectivityFailureCode;\n this.mCurrentConnectionEvent = null;\n }\n }\n }\n\n private void updateMetricsFromNetworkDetail(NetworkDetail networkDetail) {\n int connectionWifiMode;\n int dtimInterval = networkDetail.getDtimInterval();\n if (dtimInterval > 0) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.dtim = dtimInterval;\n }\n switch(networkDetail.getWifiMode()) {\n case 0:\n connectionWifiMode = 0;\n break;\n case 1:\n connectionWifiMode = 1;\n break;\n case 2:\n connectionWifiMode = 2;\n break;\n case 3:\n connectionWifiMode = 3;\n break;\n case 4:\n connectionWifiMode = 4;\n break;\n case 5:\n connectionWifiMode = 5;\n break;\n default:\n connectionWifiMode = 6;\n break;\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.routerTechnology = connectionWifiMode;\n }\n\n private void updateMetricsFromScanResult(ScanResult scanResult) {\n this.mCurrentConnectionEvent.mConnectionEvent.signalStrength = scanResult.level;\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n this.mCurrentConnectionEvent.mConfigBssid = scanResult.BSSID;\n if (scanResult.capabilities != null) {\n if (scanResult.capabilities.contains(\"WEP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"PSK\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"EAP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n }\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.channelInfo = scanResult.frequency;\n }\n\n void setNumSavedNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numSavedNetworks = num;\n }\n }\n\n void setNumOpenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numOpenNetworks = num;\n }\n }\n\n void setNumPersonalNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPersonalNetworks = num;\n }\n }\n\n void setNumEnterpriseNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numEnterpriseNetworks = num;\n }\n }\n\n void setNumHiddenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numHiddenNetworks = num;\n }\n }\n\n void setNumPasspointNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPasspointNetworks = num;\n }\n }\n\n void setNumNetworksAddedByUser(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByUser = num;\n }\n }\n\n void setNumNetworksAddedByApps(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByApps = num;\n }\n }\n\n void setIsLocationEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isLocationEnabled = enabled;\n }\n }\n\n void setIsScanningAlwaysEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isScanningAlwaysEnabled = enabled;\n }\n }\n\n public void incrementNonEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numNonEmptyScanResults++;\n }\n }\n\n public void incrementEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numEmptyScanResults++;\n }\n }\n\n public void incrementBackgroundScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numBackgroundScans++;\n }\n }\n\n public int getBackgroundScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numBackgroundScans;\n }\n return i;\n }\n\n public void incrementOneshotScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numOneshotScans++;\n }\n incrementWifiSystemScanStateCount(this.mWifiState, this.mScreenOn);\n }\n\n public int getOneshotScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numOneshotScans;\n }\n return i;\n }\n\n private String returnCodeToString(int scanReturnCode) {\n switch(scanReturnCode) {\n case 0:\n return \"SCAN_UNKNOWN\";\n case 1:\n return \"SCAN_SUCCESS\";\n case 2:\n return \"SCAN_FAILURE_INTERRUPTED\";\n case 3:\n return \"SCAN_FAILURE_INVALID_CONFIGURATION\";\n case 4:\n return \"FAILURE_WIFI_DISABLED\";\n default:\n return \"\";\n }\n }\n\n public void incrementScanReturnEntry(int scanReturnCode, int countToAdd) {\n synchronized (this.mLock) {\n this.mScanReturnEntries.put(scanReturnCode, this.mScanReturnEntries.get(scanReturnCode) + countToAdd);\n }\n }\n\n public int getScanReturnEntry(int scanReturnCode) {\n int i;\n synchronized (this.mLock) {\n i = this.mScanReturnEntries.get(scanReturnCode);\n }\n return i;\n }\n\n private String wifiSystemStateToString(int state) {\n switch(state) {\n case 0:\n return \"WIFI_UNKNOWN\";\n case 1:\n return \"WIFI_DISABLED\";\n case 2:\n return \"WIFI_DISCONNECTED\";\n case 3:\n return \"WIFI_ASSOCIATED\";\n default:\n return \"default\";\n }\n }\n\n public void incrementWifiSystemScanStateCount(int state, boolean screenOn) {\n synchronized (this.mLock) {\n int index = (state * 2) + (screenOn ? 1 : 0);\n this.mWifiSystemStateEntries.put(index, this.mWifiSystemStateEntries.get(index) + 1);\n }\n }\n\n public int getSystemStateCount(int state, boolean screenOn) {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiSystemStateEntries.get((state * 2) + (screenOn ? 1 : 0));\n }\n return i;\n }\n\n public void incrementNumLastResortWatchdogTriggers() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggers++;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAssociationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAssociationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAuthenticationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadDhcpNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadDhcpNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadOtherNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadOtherNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogAvailableNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogAvailableNetworksTotal += count;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAssociation() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAssociation++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAuthentication() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAuthentication++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadDhcp() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadDhcp++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadOther() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadOther++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoBad++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundBad++;\n }\n }\n\n public void incrementRssiPollRssiCount(int rssi) {", "post_mask_code": "\n if (rssi >= MIN_RSSI_POLL && rssi <= 0) {\n synchronized (this.mLock) {\n this.mRssiPollCounts.put(rssi, this.mRssiPollCounts.get(rssi) + 1);\n }\n }\n }\n\n public void incrementNumLastResortWatchdogSuccesses() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogSuccesses++;\n }\n }\n\n public void incrementAlertReasonCount(int reason) {\n if (reason > 64 || reason < 0) {\n reason = 0;\n }\n synchronized (this.mLock) {\n this.mWifiAlertReasonCounts.put(reason, this.mWifiAlertReasonCounts.get(reason) + 1);\n }\n }\n\n public void countScanResults(List scanDetails) {\n if (scanDetails != null) {\n int totalResults = 0;\n int openNetworks = 0;\n int personalNetworks = 0;\n int enterpriseNetworks = 0;\n int hiddenNetworks = 0;\n int hotspot2r1Networks = 0;\n int hotspot2r2Networks = 0;\n for (ScanDetail scanDetail : scanDetails) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n totalResults++;\n if (networkDetail != null) {\n if (networkDetail.isHiddenBeaconFrame()) {\n hiddenNetworks++;\n }\n if (networkDetail.getHSRelease() != null) {\n if (networkDetail.getHSRelease() == HSRelease.R1) {\n hotspot2r1Networks++;\n } else if (networkDetail.getHSRelease() == HSRelease.R2) {\n hotspot2r2Networks++;\n }\n }\n }\n if (!(scanResult == null || scanResult.capabilities == null)) {\n if (scanResult.capabilities.contains(\"EAP\")) {\n enterpriseNetworks++;\n } else if (scanResult.capabilities.contains(\"PSK\") || scanResult.capabilities.contains(\"WEP\")) {\n personalNetworks++;\n } else {\n openNetworks++;\n }\n }\n }\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numTotalScanResults += totalResults;\n wifiLog = this.mWifiLogProto;\n wifiLog.numOpenNetworkScanResults += openNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numPersonalNetworkScanResults += personalNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numEnterpriseNetworkScanResults += enterpriseNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHiddenNetworkScanResults += hiddenNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R1NetworkScanResults += hotspot2r1Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R2NetworkScanResults += hotspot2r2Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numScans++;\n }\n }\n }\n\n public void incrementWifiScoreCount(int score) {\n if (score >= 0 && score <= 5) {\n synchronized (this.mLock) {\n this.mWifiScoreCounts.put(score, this.mWifiScoreCounts.get(score) + 1);\n }\n }\n }\n\n public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {\n synchronized (this.mLock) {\n int i;\n if (args != null) {\n if (args.length > 0 && PROTO_DUMP_ARG.equals(args[0])) {\n consolidateProto(true);\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (this.mCurrentConnectionEvent != event) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n String metricsProtoDump = Base64.encodeToString(MessageNano.toByteArray(this.mWifiLogProto), 0);\n if (args.length <= 1 || !CLEAN_DUMP_ARG.equals(args[1])) {\n pw.println(\"WifiMetrics:\");\n pw.println(metricsProtoDump);\n pw.println(\"EndWifiMetrics\");\n } else {\n pw.print(metricsProtoDump);\n }\n clear();\n }\n }\n pw.println(\"WifiMetrics:\");\n pw.println(\"mConnectionEvents:\");\n for (ConnectionEvent event2 : this.mConnectionEventList) {\n String eventLine = event2.toString();\n if (event2 == this.mCurrentConnectionEvent) {\n eventLine = eventLine + \"CURRENTLY OPEN EVENT\";\n }\n pw.println(eventLine);\n }\n pw.println(\"mWifiLogProto.numSavedNetworks=\" + this.mWifiLogProto.numSavedNetworks);\n pw.println(\"mWifiLogProto.numOpenNetworks=\" + this.mWifiLogProto.numOpenNetworks);\n pw.println(\"mWifiLogProto.numPersonalNetworks=\" + this.mWifiLogProto.numPersonalNetworks);\n pw.println(\"mWifiLogProto.numEnterpriseNetworks=\" + this.mWifiLogProto.numEnterpriseNetworks);\n pw.println(\"mWifiLogProto.numHiddenNetworks=\" + this.mWifiLogProto.numHiddenNetworks);\n pw.println(\"mWifiLogProto.numPasspointNetworks=\" + this.mWifiLogProto.numPasspointNetworks);\n pw.println(\"mWifiLogProto.isLocationEnabled=\" + this.mWifiLogProto.isLocationEnabled);\n pw.println(\"mWifiLogProto.isScanningAlwaysEnabled=\" + this.mWifiLogProto.isScanningAlwaysEnabled);\n pw.println(\"mWifiLogProto.numNetworksAddedByUser=\" + this.mWifiLogProto.numNetworksAddedByUser);\n pw.println(\"mWifiLogProto.numNetworksAddedByApps=\" + this.mWifiLogProto.numNetworksAddedByApps);\n pw.println(\"mWifiLogProto.numNonEmptyScanResults=\" + this.mWifiLogProto.numNonEmptyScanResults);\n pw.println(\"mWifiLogProto.numEmptyScanResults=\" + this.mWifiLogProto.numEmptyScanResults);\n pw.println(\"mWifiLogProto.numOneshotScans=\" + this.mWifiLogProto.numOneshotScans);\n pw.println(\"mWifiLogProto.numBackgroundScans=\" + this.mWifiLogProto.numBackgroundScans);\n pw.println(\"mScanReturnEntries:\");\n pw.println(\" SCAN_UNKNOWN: \" + getScanReturnEntry(0));\n pw.println(\" SCAN_SUCCESS: \" + getScanReturnEntry(1));\n pw.println(\" SCAN_FAILURE_INTERRUPTED: \" + getScanReturnEntry(2));\n pw.println(\" SCAN_FAILURE_INVALID_CONFIGURATION: \" + getScanReturnEntry(3));\n pw.println(\" FAILURE_WIFI_DISABLED: \" + getScanReturnEntry(4));\n pw.println(\"mSystemStateEntries: : \");\n pw.println(\" WIFI_UNKNOWN ON: \" + getSystemStateCount(0, true));\n pw.println(\" WIFI_DISABLED ON: \" + getSystemStateCount(1, true));\n pw.println(\" WIFI_DISCONNECTED ON: \" + getSystemStateCount(2, true));\n pw.println(\" WIFI_ASSOCIATED ON: \" + getSystemStateCount(3, true));\n pw.println(\" WIFI_UNKNOWN OFF: \" + getSystemStateCount(0, false));\n pw.println(\" WIFI_DISABLED OFF: \" + getSystemStateCount(1, false));\n pw.println(\" WIFI_DISCONNECTED OFF: \" + getSystemStateCount(2, false));\n pw.println(\" WIFI_ASSOCIATED OFF: \" + getSystemStateCount(3, false));\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoGood=\" + this.mWifiLogProto.numConnectivityWatchdogPnoGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoBad=\" + this.mWifiLogProto.numConnectivityWatchdogPnoBad);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundGood=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundBad=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundBad);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggers=\" + this.mWifiLogProto.numLastResortWatchdogTriggers);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadOther=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadOther);\n pw.println(\"mWifiLogProto.numLastResortWatchdogSuccesses=\" + this.mWifiLogProto.numLastResortWatchdogSuccesses);\n pw.println(\"mWifiLogProto.recordDurationSec=\" + ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec));\n pw.println(\"mWifiLogProto.rssiPollRssiCount: Printing counts for [-127, 0]\");\n StringBuilder sb = new StringBuilder();\n for (i = MIN_RSSI_POLL; i <= 0; i++) {\n sb.append(this.mRssiPollCounts.get(i)).append(\" \");\n }\n pw.println(\" \" + sb.toString());\n pw.print(\"mWifiLogProto.alertReasonCounts=\");\n sb.setLength(0);\n for (i = 0; i <= 64; i++) {\n int count = this.mWifiAlertReasonCounts.get(i);\n if (count > 0) {\n sb.append(\"(\").append(i).append(\",\").append(count).append(\"),\");\n }\n }\n if (sb.length() > 1) {\n sb.setLength(sb.length() - 1);\n pw.println(sb.toString());\n } else {\n pw.println(\"()\");\n }\n pw.println(\"mWifiLogProto.numTotalScanResults=\" + this.mWifiLogProto.numTotalScanResults);\n pw.println(\"mWifiLogProto.numOpenNetworkScanResults=\" + this.mWifiLogProto.numOpenNetworkScanResults);\n pw.println(\"mWifiLogProto.numPersonalNetworkScanResults=\" + this.mWifiLogProto.numPersonalNetworkScanResults);\n pw.println(\"mWifiLogProto.numEnterpriseNetworkScanResults=\" + this.mWifiLogProto.numEnterpriseNetworkScanResults);\n pw.println(\"mWifiLogProto.numHiddenNetworkScanResults=\" + this.mWifiLogProto.numHiddenNetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R1NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R1NetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R2NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R2NetworkScanResults);\n pw.println(\"mWifiLogProto.numScans=\" + this.mWifiLogProto.numScans);\n pw.println(\"mWifiLogProto.WifiScoreCount: [0, 5]\");\n for (i = 0; i <= 5; i++) {\n pw.print(this.mWifiScoreCounts.get(i) + \" \");\n }\n pw.print(\"\\n\");\n }\n }\n\n private void consolidateProto(boolean incremental) {\n List events = new ArrayList();\n List rssis = new ArrayList();\n List alertReasons = new ArrayList();\n List scores = new ArrayList();\n synchronized (this.mLock) {\n int i;\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (!(incremental && (this.mCurrentConnectionEvent == event || event.mConnectionEvent.automaticBugReportTaken))) {\n events.add(event.mConnectionEvent);\n if (incremental) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n }\n if (events.size() > 0) {\n this.mWifiLogProto.connectionEvent = (com.android.server.wifi.WifiMetricsProto.ConnectionEvent[]) events.toArray(this.mWifiLogProto.connectionEvent);\n }\n this.mWifiLogProto.scanReturnEntries = new ScanReturnEntry[this.mScanReturnEntries.size()];\n for (i = 0; i < this.mScanReturnEntries.size(); i++) {\n this.mWifiLogProto.scanReturnEntries[i] = new ScanReturnEntry();\n this.mWifiLogProto.scanReturnEntries[i].scanReturnCode = this.mScanReturnEntries.keyAt(i);\n this.mWifiLogProto.scanReturnEntries[i].scanResultsCount = this.mScanReturnEntries.valueAt(i);\n }\n this.mWifiLogProto.wifiSystemStateEntries = new WifiSystemStateEntry[this.mWifiSystemStateEntries.size()];\n for (i = 0; i < this.mWifiSystemStateEntries.size(); i++) {\n this.mWifiLogProto.wifiSystemStateEntries[i] = new WifiSystemStateEntry();\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiState = this.mWifiSystemStateEntries.keyAt(i) / 2;\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiStateCount = this.mWifiSystemStateEntries.valueAt(i);\n this.mWifiLogProto.wifiSystemStateEntries[i].isScreenOn = this.mWifiSystemStateEntries.keyAt(i) % 2 > 0;\n }\n this.mWifiLogProto.recordDurationSec = (int) ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec);\n for (i = 0; i < this.mRssiPollCounts.size(); i++) {\n RssiPollCount keyVal = new RssiPollCount();\n keyVal.rssi = this.mRssiPollCounts.keyAt(i);\n keyVal.count = this.mRssiPollCounts.valueAt(i);\n rssis.add(keyVal);\n }\n this.mWifiLogProto.rssiPollRssiCount = (RssiPollCount[]) rssis.toArray(this.mWifiLogProto.rssiPollRssiCount);\n for (i = 0; i < this.mWifiAlertReasonCounts.size(); i++) {\n AlertReasonCount keyVal2 = new AlertReasonCount();\n keyVal2.reason = this.mWifiAlertReasonCounts.keyAt(i);\n keyVal2.count = this.mWifiAlertReasonCounts.valueAt(i);\n alertReasons.add(keyVal2);\n }\n this.mWifiLogProto.alertReasonCount = (AlertReasonCount[]) alertReasons.toArray(this.mWifiLogProto.alertReasonCount);\n for (int score = 0; score < this.mWifiScoreCounts.size(); score++) {\n WifiScoreCount keyVal3 = new WifiScoreCount();\n keyVal3.score = this.mWifiScoreCounts.keyAt(score);\n keyVal3.count = this.mWifiScoreCounts.valueAt(score);\n scores.add(keyVal3);\n }\n this.mWifiLogProto.wifiScoreCount = (WifiScoreCount[]) scores.toArray(this.mWifiLogProto.wifiScoreCount);\n }\n }\n\n private void clear() {\n synchronized (this.mLock) {\n this.mConnectionEventList.clear();\n if (this.mCurrentConnectionEvent != null) {\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n this.mScanReturnEntries.clear();\n this.mWifiSystemStateEntries.clear();\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n this.mRssiPollCounts.clear();\n this.mWifiAlertReasonCounts.clear();\n this.mWifiScoreCounts.clear();\n this.mWifiLogProto.clear();\n }\n }\n\n public void setScreenState(boolean screenOn) {\n synchronized (this.mLock) {\n this.mScreenOn = screenOn;\n }\n }\n\n public void setWifiState(int wifiState) {\n synchronized (this.mLock) {\n this.mWifiState = wifiState;\n }\n }\n}\n"} {"task_id": "Java_690", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/dstmath/OppoFramework/A1_7_1_1/src/main/java/com/android/server/wifi/WifiMetrics.java", "mask_start_position": 25745, "mask_end_position": 25934, "canonical_solution": "if (rssi >= MIN_RSSI_POLL && rssi <= 0) {\n synchronized (this.mLock) {\n this.mRssiPollCounts.put(rssi, this.mRssiPollCounts.get(rssi) + 1);\n }\n }", "pre_mask_code": "package com.android.server.wifi;\n\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiConfiguration;\nimport android.util.Base64;\nimport android.util.SparseIntArray;\nimport com.android.server.wifi.WifiMetricsProto.AlertReasonCount;\nimport com.android.server.wifi.WifiMetricsProto.RssiPollCount;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.ScanReturnEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.WifiSystemStateEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiScoreCount;\nimport com.android.server.wifi.hotspot2.NetworkDetail;\nimport com.android.server.wifi.hotspot2.NetworkDetail.HSRelease;\nimport com.google.protobuf.nano.MessageNano;\nimport java.io.FileDescriptor;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.List;\n\npublic class WifiMetrics {\n\n public static final String CLEAN_DUMP_ARG = \"clean\";\n\n private static final boolean DBG = false;\n\n private static final int MAX_CONNECTION_EVENTS = 256;\n\n private static final int MAX_RSSI_POLL = 0;\n\n private static final int MAX_WIFI_SCORE = 5;\n\n private static final int MIN_RSSI_POLL = -127;\n\n private static final int MIN_WIFI_SCORE = 0;\n\n public static final String PROTO_DUMP_ARG = \"wifiMetricsProto\";\n\n private static final int SCREEN_OFF = 0;\n\n private static final int SCREEN_ON = 1;\n\n private static final String TAG = \"WifiMetrics\";\n\n private Clock mClock;\n\n private final List mConnectionEventList = new ArrayList();\n\n private ConnectionEvent mCurrentConnectionEvent;\n\n private final Object mLock = new Object();\n\n private long mRecordStartTimeSec;\n\n private final SparseIntArray mRssiPollCounts = new SparseIntArray();\n\n private final SparseIntArray mScanReturnEntries = new SparseIntArray();\n\n private boolean mScreenOn;\n\n private final SparseIntArray mWifiAlertReasonCounts = new SparseIntArray();\n\n private final WifiLog mWifiLogProto = new WifiLog();\n\n private final SparseIntArray mWifiScoreCounts = new SparseIntArray();\n\n private int mWifiState;\n\n private final SparseIntArray mWifiSystemStateEntries = new SparseIntArray();\n\n class ConnectionEvent {\n\n public static final int FAILURE_ASSOCIATION_REJECTION = 2;\n\n public static final int FAILURE_AUTHENTICATION_FAILURE = 3;\n\n public static final int FAILURE_CONNECT_NETWORK_FAILED = 5;\n\n public static final int FAILURE_DHCP = 10;\n\n public static final int FAILURE_NETWORK_DISCONNECTION = 6;\n\n public static final int FAILURE_NEW_CONNECTION_ATTEMPT = 7;\n\n public static final int FAILURE_NONE = 1;\n\n public static final int FAILURE_REDUNDANT_CONNECTION_ATTEMPT = 8;\n\n public static final int FAILURE_ROAM_TIMEOUT = 9;\n\n public static final int FAILURE_SSID_TEMP_DISABLED = 4;\n\n public static final int FAILURE_UNKNOWN = 0;\n\n private String mConfigBssid;\n\n private String mConfigSsid;\n\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent mConnectionEvent;\n\n private long mRealEndTime;\n\n private long mRealStartTime;\n\n RouterFingerPrint mRouterFingerPrint;\n\n private boolean mScreenOn;\n\n private int mWifiState;\n\n /* synthetic */\n ConnectionEvent(WifiMetrics this$0, ConnectionEvent connectionEvent) {\n this();\n }\n\n private ConnectionEvent() {\n this.mConnectionEvent = new com.android.server.wifi.WifiMetricsProto.ConnectionEvent();\n this.mRealEndTime = 0;\n this.mRealStartTime = 0;\n this.mRouterFingerPrint = new RouterFingerPrint();\n this.mConnectionEvent.routerFingerprint = this.mRouterFingerPrint.mRouterFingerPrintProto;\n this.mConfigSsid = \"\";\n this.mConfigBssid = \"\";\n this.mWifiState = 0;\n this.mScreenOn = false;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"startTime=\");\n Calendar c = Calendar.getInstance();\n synchronized (WifiMetrics.this.mLock) {\n String str;\n c.setTimeInMillis(this.mConnectionEvent.startTimeMillis);\n if (this.mConnectionEvent.startTimeMillis == 0) {\n str = \" \";\n } else {\n str = String.format(\"%tm-%td %tH:%tM:%tS.%tL\", new Object[] { c, c, c, c, c, c });\n }\n sb.append(str);\n sb.append(\", SSID=\");\n sb.append(this.mConfigSsid);\n sb.append(\", BSSID=\");\n sb.append(this.mConfigBssid);\n sb.append(\", durationMillis=\");\n sb.append(this.mConnectionEvent.durationTakenToConnectMillis);\n sb.append(\", roamType=\");\n switch(this.mConnectionEvent.roamType) {\n case 1:\n sb.append(\"ROAM_NONE\");\n break;\n case 2:\n sb.append(\"ROAM_DBDC\");\n break;\n case 3:\n sb.append(\"ROAM_ENTERPRISE\");\n break;\n case 4:\n sb.append(\"ROAM_USER_SELECTED\");\n break;\n case 5:\n sb.append(\"ROAM_UNRELATED\");\n break;\n default:\n sb.append(\"ROAM_UNKNOWN\");\n break;\n }\n sb.append(\", connectionResult=\");\n sb.append(this.mConnectionEvent.connectionResult);\n sb.append(\", level2FailureCode=\");\n switch(this.mConnectionEvent.level2FailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"ASSOCIATION_REJECTION\");\n break;\n case 3:\n sb.append(\"AUTHENTICATION_FAILURE\");\n break;\n case 4:\n sb.append(\"SSID_TEMP_DISABLED\");\n break;\n case 5:\n sb.append(\"CONNECT_NETWORK_FAILED\");\n break;\n case 6:\n sb.append(\"NETWORK_DISCONNECTION\");\n break;\n case 7:\n sb.append(\"NEW_CONNECTION_ATTEMPT\");\n break;\n case 8:\n sb.append(\"REDUNDANT_CONNECTION_ATTEMPT\");\n break;\n case 9:\n sb.append(\"ROAM_TIMEOUT\");\n break;\n case 10:\n sb.append(\"DHCP\");\n break;\n }\n sb.append(\"UNKNOWN\");\n sb.append(\", connectivityLevelFailureCode=\");\n switch(this.mConnectionEvent.connectivityLevelFailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"DHCP\");\n break;\n case 3:\n sb.append(\"NO_INTERNET\");\n break;\n case 4:\n sb.append(\"UNWANTED\");\n break;\n default:\n sb.append(\"UNKNOWN\");\n break;\n }\n sb.append(\", signalStrength=\");\n sb.append(this.mConnectionEvent.signalStrength);\n sb.append(\", wifiState=\");\n switch(this.mWifiState) {\n case 1:\n sb.append(\"WIFI_DISABLED\");\n break;\n case 2:\n sb.append(\"WIFI_DISCONNECTED\");\n break;\n case 3:\n sb.append(\"WIFI_ASSOCIATED\");\n break;\n default:\n sb.append(\"WIFI_UNKNOWN\");\n break;\n }\n sb.append(\", screenOn=\");\n sb.append(this.mScreenOn);\n sb.append(\". mRouterFingerprint: \");\n sb.append(this.mRouterFingerPrint.toString());\n }\n return sb.toString();\n }\n }\n\n class RouterFingerPrint {\n\n private com.android.server.wifi.WifiMetricsProto.RouterFingerPrint mRouterFingerPrintProto = new com.android.server.wifi.WifiMetricsProto.RouterFingerPrint();\n\n RouterFingerPrint() {\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n synchronized (WifiMetrics.this.mLock) {\n sb.append(\"mConnectionEvent.roamType=\").append(this.mRouterFingerPrintProto.roamType);\n sb.append(\", mChannelInfo=\").append(this.mRouterFingerPrintProto.channelInfo);\n sb.append(\", mDtim=\").append(this.mRouterFingerPrintProto.dtim);\n sb.append(\", mAuthentication=\").append(this.mRouterFingerPrintProto.authentication);\n sb.append(\", mHidden=\").append(this.mRouterFingerPrintProto.hidden);\n sb.append(\", mRouterTechnology=\").append(this.mRouterFingerPrintProto.routerTechnology);\n sb.append(\", mSupportsIpv6=\").append(this.mRouterFingerPrintProto.supportsIpv6);\n }\n return sb.toString();\n }\n\n public void updateFromWifiConfiguration(WifiConfiguration config) {\n synchronized (WifiMetrics.this.mLock) {\n if (config != null) {\n this.mRouterFingerPrintProto.hidden = config.hiddenSSID;\n if (config.dtimInterval > 0) {\n this.mRouterFingerPrintProto.dtim = config.dtimInterval;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mConfigSsid = config.SSID;\n if (config.allowedKeyManagement != null && config.allowedKeyManagement.get(0)) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n } else if (config.isEnterprise()) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n } else {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.passpoint = config.isPasspoint();\n ScanResult candidate = config.getNetworkSelectionStatus().getCandidate();\n if (candidate != null) {\n WifiMetrics.this.updateMetricsFromScanResult(candidate);\n }\n }\n }\n }\n }\n\n public WifiMetrics(Clock clock) {\n this.mClock = clock;\n this.mCurrentConnectionEvent = null;\n this.mScreenOn = true;\n this.mWifiState = 1;\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n }\n\n public void startConnectionEvent(WifiConfiguration config, String targetBSSID, int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n if (this.mCurrentConnectionEvent.mConfigSsid == null || this.mCurrentConnectionEvent.mConfigBssid == null || config == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(config.SSID) || !(this.mCurrentConnectionEvent.mConfigBssid.equals(WifiLastResortWatchdog.BSSID_ANY) || this.mCurrentConnectionEvent.mConfigBssid.equals(targetBSSID))) {\n endConnectionEvent(7, 1);\n } else {\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n endConnectionEvent(8, 1);\n }\n }\n while (this.mConnectionEventList.size() >= 256) {\n this.mConnectionEventList.remove(0);\n }\n this.mCurrentConnectionEvent = new ConnectionEvent(this, null);\n this.mCurrentConnectionEvent.mConnectionEvent.startTimeMillis = this.mClock.currentTimeMillis();\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n this.mCurrentConnectionEvent.mRouterFingerPrint.updateFromWifiConfiguration(config);\n this.mCurrentConnectionEvent.mConfigBssid = WifiLastResortWatchdog.BSSID_ANY;\n this.mCurrentConnectionEvent.mRealStartTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mWifiState = this.mWifiState;\n this.mCurrentConnectionEvent.mScreenOn = this.mScreenOn;\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n }\n\n public void setConnectionEventRoamType(int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n }\n }\n }\n\n public void setConnectionScanDetail(ScanDetail scanDetail) {\n synchronized (this.mLock) {\n if (!(this.mCurrentConnectionEvent == null || scanDetail == null)) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n if (!(networkDetail == null || scanResult == null || this.mCurrentConnectionEvent.mConfigSsid == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(\"\\\"\" + networkDetail.getSSID() + \"\\\"\"))) {\n updateMetricsFromNetworkDetail(networkDetail);\n updateMetricsFromScanResult(scanResult);\n }\n }\n }\n }\n\n public void endConnectionEvent(int level2FailureCode, int connectivityFailureCode) {\n int i = 1;\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n boolean result = level2FailureCode == 1 ? connectivityFailureCode == 1 : false;\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent connectionEvent = this.mCurrentConnectionEvent.mConnectionEvent;\n if (!result) {\n i = 0;\n }\n connectionEvent.connectionResult = i;\n this.mCurrentConnectionEvent.mRealEndTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mConnectionEvent.durationTakenToConnectMillis = (int) (this.mCurrentConnectionEvent.mRealEndTime - this.mCurrentConnectionEvent.mRealStartTime);\n this.mCurrentConnectionEvent.mConnectionEvent.level2FailureCode = level2FailureCode;\n this.mCurrentConnectionEvent.mConnectionEvent.connectivityLevelFailureCode = connectivityFailureCode;\n this.mCurrentConnectionEvent = null;\n }\n }\n }\n\n private void updateMetricsFromNetworkDetail(NetworkDetail networkDetail) {\n int connectionWifiMode;\n int dtimInterval = networkDetail.getDtimInterval();\n if (dtimInterval > 0) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.dtim = dtimInterval;\n }\n switch(networkDetail.getWifiMode()) {\n case 0:\n connectionWifiMode = 0;\n break;\n case 1:\n connectionWifiMode = 1;\n break;\n case 2:\n connectionWifiMode = 2;\n break;\n case 3:\n connectionWifiMode = 3;\n break;\n case 4:\n connectionWifiMode = 4;\n break;\n case 5:\n connectionWifiMode = 5;\n break;\n default:\n connectionWifiMode = 6;\n break;\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.routerTechnology = connectionWifiMode;\n }\n\n private void updateMetricsFromScanResult(ScanResult scanResult) {\n this.mCurrentConnectionEvent.mConnectionEvent.signalStrength = scanResult.level;\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n this.mCurrentConnectionEvent.mConfigBssid = scanResult.BSSID;\n if (scanResult.capabilities != null) {\n if (scanResult.capabilities.contains(\"WEP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"PSK\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"EAP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n }\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.channelInfo = scanResult.frequency;\n }\n\n void setNumSavedNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numSavedNetworks = num;\n }\n }\n\n void setNumOpenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numOpenNetworks = num;\n }\n }\n\n void setNumPersonalNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPersonalNetworks = num;\n }\n }\n\n void setNumEnterpriseNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numEnterpriseNetworks = num;\n }\n }\n\n void setNumHiddenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numHiddenNetworks = num;\n }\n }\n\n void setNumPasspointNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPasspointNetworks = num;\n }\n }\n\n void setNumNetworksAddedByUser(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByUser = num;\n }\n }\n\n void setNumNetworksAddedByApps(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByApps = num;\n }\n }\n\n void setIsLocationEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isLocationEnabled = enabled;\n }\n }\n\n void setIsScanningAlwaysEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isScanningAlwaysEnabled = enabled;\n }\n }\n\n public void incrementNonEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numNonEmptyScanResults++;\n }\n }\n\n public void incrementEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numEmptyScanResults++;\n }\n }\n\n public void incrementBackgroundScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numBackgroundScans++;\n }\n }\n\n public int getBackgroundScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numBackgroundScans;\n }\n return i;\n }\n\n public void incrementOneshotScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numOneshotScans++;\n }\n incrementWifiSystemScanStateCount(this.mWifiState, this.mScreenOn);\n }\n\n public int getOneshotScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numOneshotScans;\n }\n return i;\n }\n\n private String returnCodeToString(int scanReturnCode) {\n switch(scanReturnCode) {\n case 0:\n return \"SCAN_UNKNOWN\";\n case 1:\n return \"SCAN_SUCCESS\";\n case 2:\n return \"SCAN_FAILURE_INTERRUPTED\";\n case 3:\n return \"SCAN_FAILURE_INVALID_CONFIGURATION\";\n case 4:\n return \"FAILURE_WIFI_DISABLED\";\n default:\n return \"\";\n }\n }\n\n public void incrementScanReturnEntry(int scanReturnCode, int countToAdd) {\n synchronized (this.mLock) {\n this.mScanReturnEntries.put(scanReturnCode, this.mScanReturnEntries.get(scanReturnCode) + countToAdd);\n }\n }\n\n public int getScanReturnEntry(int scanReturnCode) {\n int i;\n synchronized (this.mLock) {\n i = this.mScanReturnEntries.get(scanReturnCode);\n }\n return i;\n }\n\n private String wifiSystemStateToString(int state) {\n switch(state) {\n case 0:\n return \"WIFI_UNKNOWN\";\n case 1:\n return \"WIFI_DISABLED\";\n case 2:\n return \"WIFI_DISCONNECTED\";\n case 3:\n return \"WIFI_ASSOCIATED\";\n default:\n return \"default\";\n }\n }\n\n public void incrementWifiSystemScanStateCount(int state, boolean screenOn) {\n synchronized (this.mLock) {\n int index = (state * 2) + (screenOn ? 1 : 0);\n this.mWifiSystemStateEntries.put(index, this.mWifiSystemStateEntries.get(index) + 1);\n }\n }\n\n public int getSystemStateCount(int state, boolean screenOn) {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiSystemStateEntries.get((state * 2) + (screenOn ? 1 : 0));\n }\n return i;\n }\n\n public void incrementNumLastResortWatchdogTriggers() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggers++;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAssociationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAssociationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAuthenticationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadDhcpNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadDhcpNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadOtherNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadOtherNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogAvailableNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogAvailableNetworksTotal += count;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAssociation() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAssociation++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAuthentication() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAuthentication++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadDhcp() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadDhcp++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadOther() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadOther++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoBad++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundBad++;\n }\n }\n\n public void incrementRssiPollRssiCount(int rssi) {\n ", "post_mask_code": "\n }\n\n public void incrementNumLastResortWatchdogSuccesses() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogSuccesses++;\n }\n }\n\n public void incrementAlertReasonCount(int reason) {\n if (reason > 64 || reason < 0) {\n reason = 0;\n }\n synchronized (this.mLock) {\n this.mWifiAlertReasonCounts.put(reason, this.mWifiAlertReasonCounts.get(reason) + 1);\n }\n }\n\n public void countScanResults(List scanDetails) {\n if (scanDetails != null) {\n int totalResults = 0;\n int openNetworks = 0;\n int personalNetworks = 0;\n int enterpriseNetworks = 0;\n int hiddenNetworks = 0;\n int hotspot2r1Networks = 0;\n int hotspot2r2Networks = 0;\n for (ScanDetail scanDetail : scanDetails) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n totalResults++;\n if (networkDetail != null) {\n if (networkDetail.isHiddenBeaconFrame()) {\n hiddenNetworks++;\n }\n if (networkDetail.getHSRelease() != null) {\n if (networkDetail.getHSRelease() == HSRelease.R1) {\n hotspot2r1Networks++;\n } else if (networkDetail.getHSRelease() == HSRelease.R2) {\n hotspot2r2Networks++;\n }\n }\n }\n if (!(scanResult == null || scanResult.capabilities == null)) {\n if (scanResult.capabilities.contains(\"EAP\")) {\n enterpriseNetworks++;\n } else if (scanResult.capabilities.contains(\"PSK\") || scanResult.capabilities.contains(\"WEP\")) {\n personalNetworks++;\n } else {\n openNetworks++;\n }\n }\n }\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numTotalScanResults += totalResults;\n wifiLog = this.mWifiLogProto;\n wifiLog.numOpenNetworkScanResults += openNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numPersonalNetworkScanResults += personalNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numEnterpriseNetworkScanResults += enterpriseNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHiddenNetworkScanResults += hiddenNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R1NetworkScanResults += hotspot2r1Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R2NetworkScanResults += hotspot2r2Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numScans++;\n }\n }\n }\n\n public void incrementWifiScoreCount(int score) {\n if (score >= 0 && score <= 5) {\n synchronized (this.mLock) {\n this.mWifiScoreCounts.put(score, this.mWifiScoreCounts.get(score) + 1);\n }\n }\n }\n\n public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {\n synchronized (this.mLock) {\n int i;\n if (args != null) {\n if (args.length > 0 && PROTO_DUMP_ARG.equals(args[0])) {\n consolidateProto(true);\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (this.mCurrentConnectionEvent != event) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n String metricsProtoDump = Base64.encodeToString(MessageNano.toByteArray(this.mWifiLogProto), 0);\n if (args.length <= 1 || !CLEAN_DUMP_ARG.equals(args[1])) {\n pw.println(\"WifiMetrics:\");\n pw.println(metricsProtoDump);\n pw.println(\"EndWifiMetrics\");\n } else {\n pw.print(metricsProtoDump);\n }\n clear();\n }\n }\n pw.println(\"WifiMetrics:\");\n pw.println(\"mConnectionEvents:\");\n for (ConnectionEvent event2 : this.mConnectionEventList) {\n String eventLine = event2.toString();\n if (event2 == this.mCurrentConnectionEvent) {\n eventLine = eventLine + \"CURRENTLY OPEN EVENT\";\n }\n pw.println(eventLine);\n }\n pw.println(\"mWifiLogProto.numSavedNetworks=\" + this.mWifiLogProto.numSavedNetworks);\n pw.println(\"mWifiLogProto.numOpenNetworks=\" + this.mWifiLogProto.numOpenNetworks);\n pw.println(\"mWifiLogProto.numPersonalNetworks=\" + this.mWifiLogProto.numPersonalNetworks);\n pw.println(\"mWifiLogProto.numEnterpriseNetworks=\" + this.mWifiLogProto.numEnterpriseNetworks);\n pw.println(\"mWifiLogProto.numHiddenNetworks=\" + this.mWifiLogProto.numHiddenNetworks);\n pw.println(\"mWifiLogProto.numPasspointNetworks=\" + this.mWifiLogProto.numPasspointNetworks);\n pw.println(\"mWifiLogProto.isLocationEnabled=\" + this.mWifiLogProto.isLocationEnabled);\n pw.println(\"mWifiLogProto.isScanningAlwaysEnabled=\" + this.mWifiLogProto.isScanningAlwaysEnabled);\n pw.println(\"mWifiLogProto.numNetworksAddedByUser=\" + this.mWifiLogProto.numNetworksAddedByUser);\n pw.println(\"mWifiLogProto.numNetworksAddedByApps=\" + this.mWifiLogProto.numNetworksAddedByApps);\n pw.println(\"mWifiLogProto.numNonEmptyScanResults=\" + this.mWifiLogProto.numNonEmptyScanResults);\n pw.println(\"mWifiLogProto.numEmptyScanResults=\" + this.mWifiLogProto.numEmptyScanResults);\n pw.println(\"mWifiLogProto.numOneshotScans=\" + this.mWifiLogProto.numOneshotScans);\n pw.println(\"mWifiLogProto.numBackgroundScans=\" + this.mWifiLogProto.numBackgroundScans);\n pw.println(\"mScanReturnEntries:\");\n pw.println(\" SCAN_UNKNOWN: \" + getScanReturnEntry(0));\n pw.println(\" SCAN_SUCCESS: \" + getScanReturnEntry(1));\n pw.println(\" SCAN_FAILURE_INTERRUPTED: \" + getScanReturnEntry(2));\n pw.println(\" SCAN_FAILURE_INVALID_CONFIGURATION: \" + getScanReturnEntry(3));\n pw.println(\" FAILURE_WIFI_DISABLED: \" + getScanReturnEntry(4));\n pw.println(\"mSystemStateEntries: : \");\n pw.println(\" WIFI_UNKNOWN ON: \" + getSystemStateCount(0, true));\n pw.println(\" WIFI_DISABLED ON: \" + getSystemStateCount(1, true));\n pw.println(\" WIFI_DISCONNECTED ON: \" + getSystemStateCount(2, true));\n pw.println(\" WIFI_ASSOCIATED ON: \" + getSystemStateCount(3, true));\n pw.println(\" WIFI_UNKNOWN OFF: \" + getSystemStateCount(0, false));\n pw.println(\" WIFI_DISABLED OFF: \" + getSystemStateCount(1, false));\n pw.println(\" WIFI_DISCONNECTED OFF: \" + getSystemStateCount(2, false));\n pw.println(\" WIFI_ASSOCIATED OFF: \" + getSystemStateCount(3, false));\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoGood=\" + this.mWifiLogProto.numConnectivityWatchdogPnoGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoBad=\" + this.mWifiLogProto.numConnectivityWatchdogPnoBad);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundGood=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundBad=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundBad);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggers=\" + this.mWifiLogProto.numLastResortWatchdogTriggers);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadOther=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadOther);\n pw.println(\"mWifiLogProto.numLastResortWatchdogSuccesses=\" + this.mWifiLogProto.numLastResortWatchdogSuccesses);\n pw.println(\"mWifiLogProto.recordDurationSec=\" + ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec));\n pw.println(\"mWifiLogProto.rssiPollRssiCount: Printing counts for [-127, 0]\");\n StringBuilder sb = new StringBuilder();\n for (i = MIN_RSSI_POLL; i <= 0; i++) {\n sb.append(this.mRssiPollCounts.get(i)).append(\" \");\n }\n pw.println(\" \" + sb.toString());\n pw.print(\"mWifiLogProto.alertReasonCounts=\");\n sb.setLength(0);\n for (i = 0; i <= 64; i++) {\n int count = this.mWifiAlertReasonCounts.get(i);\n if (count > 0) {\n sb.append(\"(\").append(i).append(\",\").append(count).append(\"),\");\n }\n }\n if (sb.length() > 1) {\n sb.setLength(sb.length() - 1);\n pw.println(sb.toString());\n } else {\n pw.println(\"()\");\n }\n pw.println(\"mWifiLogProto.numTotalScanResults=\" + this.mWifiLogProto.numTotalScanResults);\n pw.println(\"mWifiLogProto.numOpenNetworkScanResults=\" + this.mWifiLogProto.numOpenNetworkScanResults);\n pw.println(\"mWifiLogProto.numPersonalNetworkScanResults=\" + this.mWifiLogProto.numPersonalNetworkScanResults);\n pw.println(\"mWifiLogProto.numEnterpriseNetworkScanResults=\" + this.mWifiLogProto.numEnterpriseNetworkScanResults);\n pw.println(\"mWifiLogProto.numHiddenNetworkScanResults=\" + this.mWifiLogProto.numHiddenNetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R1NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R1NetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R2NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R2NetworkScanResults);\n pw.println(\"mWifiLogProto.numScans=\" + this.mWifiLogProto.numScans);\n pw.println(\"mWifiLogProto.WifiScoreCount: [0, 5]\");\n for (i = 0; i <= 5; i++) {\n pw.print(this.mWifiScoreCounts.get(i) + \" \");\n }\n pw.print(\"\\n\");\n }\n }\n\n private void consolidateProto(boolean incremental) {\n List events = new ArrayList();\n List rssis = new ArrayList();\n List alertReasons = new ArrayList();\n List scores = new ArrayList();\n synchronized (this.mLock) {\n int i;\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (!(incremental && (this.mCurrentConnectionEvent == event || event.mConnectionEvent.automaticBugReportTaken))) {\n events.add(event.mConnectionEvent);\n if (incremental) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n }\n if (events.size() > 0) {\n this.mWifiLogProto.connectionEvent = (com.android.server.wifi.WifiMetricsProto.ConnectionEvent[]) events.toArray(this.mWifiLogProto.connectionEvent);\n }\n this.mWifiLogProto.scanReturnEntries = new ScanReturnEntry[this.mScanReturnEntries.size()];\n for (i = 0; i < this.mScanReturnEntries.size(); i++) {\n this.mWifiLogProto.scanReturnEntries[i] = new ScanReturnEntry();\n this.mWifiLogProto.scanReturnEntries[i].scanReturnCode = this.mScanReturnEntries.keyAt(i);\n this.mWifiLogProto.scanReturnEntries[i].scanResultsCount = this.mScanReturnEntries.valueAt(i);\n }\n this.mWifiLogProto.wifiSystemStateEntries = new WifiSystemStateEntry[this.mWifiSystemStateEntries.size()];\n for (i = 0; i < this.mWifiSystemStateEntries.size(); i++) {\n this.mWifiLogProto.wifiSystemStateEntries[i] = new WifiSystemStateEntry();\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiState = this.mWifiSystemStateEntries.keyAt(i) / 2;\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiStateCount = this.mWifiSystemStateEntries.valueAt(i);\n this.mWifiLogProto.wifiSystemStateEntries[i].isScreenOn = this.mWifiSystemStateEntries.keyAt(i) % 2 > 0;\n }\n this.mWifiLogProto.recordDurationSec = (int) ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec);\n for (i = 0; i < this.mRssiPollCounts.size(); i++) {\n RssiPollCount keyVal = new RssiPollCount();\n keyVal.rssi = this.mRssiPollCounts.keyAt(i);\n keyVal.count = this.mRssiPollCounts.valueAt(i);\n rssis.add(keyVal);\n }\n this.mWifiLogProto.rssiPollRssiCount = (RssiPollCount[]) rssis.toArray(this.mWifiLogProto.rssiPollRssiCount);\n for (i = 0; i < this.mWifiAlertReasonCounts.size(); i++) {\n AlertReasonCount keyVal2 = new AlertReasonCount();\n keyVal2.reason = this.mWifiAlertReasonCounts.keyAt(i);\n keyVal2.count = this.mWifiAlertReasonCounts.valueAt(i);\n alertReasons.add(keyVal2);\n }\n this.mWifiLogProto.alertReasonCount = (AlertReasonCount[]) alertReasons.toArray(this.mWifiLogProto.alertReasonCount);\n for (int score = 0; score < this.mWifiScoreCounts.size(); score++) {\n WifiScoreCount keyVal3 = new WifiScoreCount();\n keyVal3.score = this.mWifiScoreCounts.keyAt(score);\n keyVal3.count = this.mWifiScoreCounts.valueAt(score);\n scores.add(keyVal3);\n }\n this.mWifiLogProto.wifiScoreCount = (WifiScoreCount[]) scores.toArray(this.mWifiLogProto.wifiScoreCount);\n }\n }\n\n private void clear() {\n synchronized (this.mLock) {\n this.mConnectionEventList.clear();\n if (this.mCurrentConnectionEvent != null) {\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n this.mScanReturnEntries.clear();\n this.mWifiSystemStateEntries.clear();\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n this.mRssiPollCounts.clear();\n this.mWifiAlertReasonCounts.clear();\n this.mWifiScoreCounts.clear();\n this.mWifiLogProto.clear();\n }\n }\n\n public void setScreenState(boolean screenOn) {\n synchronized (this.mLock) {\n this.mScreenOn = screenOn;\n }\n }\n\n public void setWifiState(int wifiState) {\n synchronized (this.mLock) {\n this.mWifiState = wifiState;\n }\n }\n}\n"} {"task_id": "Java_691", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/dstmath/OppoFramework/A1_7_1_1/src/main/java/com/android/server/wifi/WifiMetrics.java", "mask_start_position": 25939, "mask_end_position": 25940, "canonical_solution": "}", "pre_mask_code": "package com.android.server.wifi;\n\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiConfiguration;\nimport android.util.Base64;\nimport android.util.SparseIntArray;\nimport com.android.server.wifi.WifiMetricsProto.AlertReasonCount;\nimport com.android.server.wifi.WifiMetricsProto.RssiPollCount;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.ScanReturnEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.WifiSystemStateEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiScoreCount;\nimport com.android.server.wifi.hotspot2.NetworkDetail;\nimport com.android.server.wifi.hotspot2.NetworkDetail.HSRelease;\nimport com.google.protobuf.nano.MessageNano;\nimport java.io.FileDescriptor;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.List;\n\npublic class WifiMetrics {\n\n public static final String CLEAN_DUMP_ARG = \"clean\";\n\n private static final boolean DBG = false;\n\n private static final int MAX_CONNECTION_EVENTS = 256;\n\n private static final int MAX_RSSI_POLL = 0;\n\n private static final int MAX_WIFI_SCORE = 5;\n\n private static final int MIN_RSSI_POLL = -127;\n\n private static final int MIN_WIFI_SCORE = 0;\n\n public static final String PROTO_DUMP_ARG = \"wifiMetricsProto\";\n\n private static final int SCREEN_OFF = 0;\n\n private static final int SCREEN_ON = 1;\n\n private static final String TAG = \"WifiMetrics\";\n\n private Clock mClock;\n\n private final List mConnectionEventList = new ArrayList();\n\n private ConnectionEvent mCurrentConnectionEvent;\n\n private final Object mLock = new Object();\n\n private long mRecordStartTimeSec;\n\n private final SparseIntArray mRssiPollCounts = new SparseIntArray();\n\n private final SparseIntArray mScanReturnEntries = new SparseIntArray();\n\n private boolean mScreenOn;\n\n private final SparseIntArray mWifiAlertReasonCounts = new SparseIntArray();\n\n private final WifiLog mWifiLogProto = new WifiLog();\n\n private final SparseIntArray mWifiScoreCounts = new SparseIntArray();\n\n private int mWifiState;\n\n private final SparseIntArray mWifiSystemStateEntries = new SparseIntArray();\n\n class ConnectionEvent {\n\n public static final int FAILURE_ASSOCIATION_REJECTION = 2;\n\n public static final int FAILURE_AUTHENTICATION_FAILURE = 3;\n\n public static final int FAILURE_CONNECT_NETWORK_FAILED = 5;\n\n public static final int FAILURE_DHCP = 10;\n\n public static final int FAILURE_NETWORK_DISCONNECTION = 6;\n\n public static final int FAILURE_NEW_CONNECTION_ATTEMPT = 7;\n\n public static final int FAILURE_NONE = 1;\n\n public static final int FAILURE_REDUNDANT_CONNECTION_ATTEMPT = 8;\n\n public static final int FAILURE_ROAM_TIMEOUT = 9;\n\n public static final int FAILURE_SSID_TEMP_DISABLED = 4;\n\n public static final int FAILURE_UNKNOWN = 0;\n\n private String mConfigBssid;\n\n private String mConfigSsid;\n\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent mConnectionEvent;\n\n private long mRealEndTime;\n\n private long mRealStartTime;\n\n RouterFingerPrint mRouterFingerPrint;\n\n private boolean mScreenOn;\n\n private int mWifiState;\n\n /* synthetic */\n ConnectionEvent(WifiMetrics this$0, ConnectionEvent connectionEvent) {\n this();\n }\n\n private ConnectionEvent() {\n this.mConnectionEvent = new com.android.server.wifi.WifiMetricsProto.ConnectionEvent();\n this.mRealEndTime = 0;\n this.mRealStartTime = 0;\n this.mRouterFingerPrint = new RouterFingerPrint();\n this.mConnectionEvent.routerFingerprint = this.mRouterFingerPrint.mRouterFingerPrintProto;\n this.mConfigSsid = \"\";\n this.mConfigBssid = \"\";\n this.mWifiState = 0;\n this.mScreenOn = false;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"startTime=\");\n Calendar c = Calendar.getInstance();\n synchronized (WifiMetrics.this.mLock) {\n String str;\n c.setTimeInMillis(this.mConnectionEvent.startTimeMillis);\n if (this.mConnectionEvent.startTimeMillis == 0) {\n str = \" \";\n } else {\n str = String.format(\"%tm-%td %tH:%tM:%tS.%tL\", new Object[] { c, c, c, c, c, c });\n }\n sb.append(str);\n sb.append(\", SSID=\");\n sb.append(this.mConfigSsid);\n sb.append(\", BSSID=\");\n sb.append(this.mConfigBssid);\n sb.append(\", durationMillis=\");\n sb.append(this.mConnectionEvent.durationTakenToConnectMillis);\n sb.append(\", roamType=\");\n switch(this.mConnectionEvent.roamType) {\n case 1:\n sb.append(\"ROAM_NONE\");\n break;\n case 2:\n sb.append(\"ROAM_DBDC\");\n break;\n case 3:\n sb.append(\"ROAM_ENTERPRISE\");\n break;\n case 4:\n sb.append(\"ROAM_USER_SELECTED\");\n break;\n case 5:\n sb.append(\"ROAM_UNRELATED\");\n break;\n default:\n sb.append(\"ROAM_UNKNOWN\");\n break;\n }\n sb.append(\", connectionResult=\");\n sb.append(this.mConnectionEvent.connectionResult);\n sb.append(\", level2FailureCode=\");\n switch(this.mConnectionEvent.level2FailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"ASSOCIATION_REJECTION\");\n break;\n case 3:\n sb.append(\"AUTHENTICATION_FAILURE\");\n break;\n case 4:\n sb.append(\"SSID_TEMP_DISABLED\");\n break;\n case 5:\n sb.append(\"CONNECT_NETWORK_FAILED\");\n break;\n case 6:\n sb.append(\"NETWORK_DISCONNECTION\");\n break;\n case 7:\n sb.append(\"NEW_CONNECTION_ATTEMPT\");\n break;\n case 8:\n sb.append(\"REDUNDANT_CONNECTION_ATTEMPT\");\n break;\n case 9:\n sb.append(\"ROAM_TIMEOUT\");\n break;\n case 10:\n sb.append(\"DHCP\");\n break;\n }\n sb.append(\"UNKNOWN\");\n sb.append(\", connectivityLevelFailureCode=\");\n switch(this.mConnectionEvent.connectivityLevelFailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"DHCP\");\n break;\n case 3:\n sb.append(\"NO_INTERNET\");\n break;\n case 4:\n sb.append(\"UNWANTED\");\n break;\n default:\n sb.append(\"UNKNOWN\");\n break;\n }\n sb.append(\", signalStrength=\");\n sb.append(this.mConnectionEvent.signalStrength);\n sb.append(\", wifiState=\");\n switch(this.mWifiState) {\n case 1:\n sb.append(\"WIFI_DISABLED\");\n break;\n case 2:\n sb.append(\"WIFI_DISCONNECTED\");\n break;\n case 3:\n sb.append(\"WIFI_ASSOCIATED\");\n break;\n default:\n sb.append(\"WIFI_UNKNOWN\");\n break;\n }\n sb.append(\", screenOn=\");\n sb.append(this.mScreenOn);\n sb.append(\". mRouterFingerprint: \");\n sb.append(this.mRouterFingerPrint.toString());\n }\n return sb.toString();\n }\n }\n\n class RouterFingerPrint {\n\n private com.android.server.wifi.WifiMetricsProto.RouterFingerPrint mRouterFingerPrintProto = new com.android.server.wifi.WifiMetricsProto.RouterFingerPrint();\n\n RouterFingerPrint() {\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n synchronized (WifiMetrics.this.mLock) {\n sb.append(\"mConnectionEvent.roamType=\").append(this.mRouterFingerPrintProto.roamType);\n sb.append(\", mChannelInfo=\").append(this.mRouterFingerPrintProto.channelInfo);\n sb.append(\", mDtim=\").append(this.mRouterFingerPrintProto.dtim);\n sb.append(\", mAuthentication=\").append(this.mRouterFingerPrintProto.authentication);\n sb.append(\", mHidden=\").append(this.mRouterFingerPrintProto.hidden);\n sb.append(\", mRouterTechnology=\").append(this.mRouterFingerPrintProto.routerTechnology);\n sb.append(\", mSupportsIpv6=\").append(this.mRouterFingerPrintProto.supportsIpv6);\n }\n return sb.toString();\n }\n\n public void updateFromWifiConfiguration(WifiConfiguration config) {\n synchronized (WifiMetrics.this.mLock) {\n if (config != null) {\n this.mRouterFingerPrintProto.hidden = config.hiddenSSID;\n if (config.dtimInterval > 0) {\n this.mRouterFingerPrintProto.dtim = config.dtimInterval;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mConfigSsid = config.SSID;\n if (config.allowedKeyManagement != null && config.allowedKeyManagement.get(0)) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n } else if (config.isEnterprise()) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n } else {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.passpoint = config.isPasspoint();\n ScanResult candidate = config.getNetworkSelectionStatus().getCandidate();\n if (candidate != null) {\n WifiMetrics.this.updateMetricsFromScanResult(candidate);\n }\n }\n }\n }\n }\n\n public WifiMetrics(Clock clock) {\n this.mClock = clock;\n this.mCurrentConnectionEvent = null;\n this.mScreenOn = true;\n this.mWifiState = 1;\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n }\n\n public void startConnectionEvent(WifiConfiguration config, String targetBSSID, int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n if (this.mCurrentConnectionEvent.mConfigSsid == null || this.mCurrentConnectionEvent.mConfigBssid == null || config == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(config.SSID) || !(this.mCurrentConnectionEvent.mConfigBssid.equals(WifiLastResortWatchdog.BSSID_ANY) || this.mCurrentConnectionEvent.mConfigBssid.equals(targetBSSID))) {\n endConnectionEvent(7, 1);\n } else {\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n endConnectionEvent(8, 1);\n }\n }\n while (this.mConnectionEventList.size() >= 256) {\n this.mConnectionEventList.remove(0);\n }\n this.mCurrentConnectionEvent = new ConnectionEvent(this, null);\n this.mCurrentConnectionEvent.mConnectionEvent.startTimeMillis = this.mClock.currentTimeMillis();\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n this.mCurrentConnectionEvent.mRouterFingerPrint.updateFromWifiConfiguration(config);\n this.mCurrentConnectionEvent.mConfigBssid = WifiLastResortWatchdog.BSSID_ANY;\n this.mCurrentConnectionEvent.mRealStartTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mWifiState = this.mWifiState;\n this.mCurrentConnectionEvent.mScreenOn = this.mScreenOn;\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n }\n\n public void setConnectionEventRoamType(int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n }\n }\n }\n\n public void setConnectionScanDetail(ScanDetail scanDetail) {\n synchronized (this.mLock) {\n if (!(this.mCurrentConnectionEvent == null || scanDetail == null)) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n if (!(networkDetail == null || scanResult == null || this.mCurrentConnectionEvent.mConfigSsid == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(\"\\\"\" + networkDetail.getSSID() + \"\\\"\"))) {\n updateMetricsFromNetworkDetail(networkDetail);\n updateMetricsFromScanResult(scanResult);\n }\n }\n }\n }\n\n public void endConnectionEvent(int level2FailureCode, int connectivityFailureCode) {\n int i = 1;\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n boolean result = level2FailureCode == 1 ? connectivityFailureCode == 1 : false;\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent connectionEvent = this.mCurrentConnectionEvent.mConnectionEvent;\n if (!result) {\n i = 0;\n }\n connectionEvent.connectionResult = i;\n this.mCurrentConnectionEvent.mRealEndTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mConnectionEvent.durationTakenToConnectMillis = (int) (this.mCurrentConnectionEvent.mRealEndTime - this.mCurrentConnectionEvent.mRealStartTime);\n this.mCurrentConnectionEvent.mConnectionEvent.level2FailureCode = level2FailureCode;\n this.mCurrentConnectionEvent.mConnectionEvent.connectivityLevelFailureCode = connectivityFailureCode;\n this.mCurrentConnectionEvent = null;\n }\n }\n }\n\n private void updateMetricsFromNetworkDetail(NetworkDetail networkDetail) {\n int connectionWifiMode;\n int dtimInterval = networkDetail.getDtimInterval();\n if (dtimInterval > 0) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.dtim = dtimInterval;\n }\n switch(networkDetail.getWifiMode()) {\n case 0:\n connectionWifiMode = 0;\n break;\n case 1:\n connectionWifiMode = 1;\n break;\n case 2:\n connectionWifiMode = 2;\n break;\n case 3:\n connectionWifiMode = 3;\n break;\n case 4:\n connectionWifiMode = 4;\n break;\n case 5:\n connectionWifiMode = 5;\n break;\n default:\n connectionWifiMode = 6;\n break;\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.routerTechnology = connectionWifiMode;\n }\n\n private void updateMetricsFromScanResult(ScanResult scanResult) {\n this.mCurrentConnectionEvent.mConnectionEvent.signalStrength = scanResult.level;\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n this.mCurrentConnectionEvent.mConfigBssid = scanResult.BSSID;\n if (scanResult.capabilities != null) {\n if (scanResult.capabilities.contains(\"WEP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"PSK\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"EAP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n }\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.channelInfo = scanResult.frequency;\n }\n\n void setNumSavedNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numSavedNetworks = num;\n }\n }\n\n void setNumOpenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numOpenNetworks = num;\n }\n }\n\n void setNumPersonalNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPersonalNetworks = num;\n }\n }\n\n void setNumEnterpriseNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numEnterpriseNetworks = num;\n }\n }\n\n void setNumHiddenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numHiddenNetworks = num;\n }\n }\n\n void setNumPasspointNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPasspointNetworks = num;\n }\n }\n\n void setNumNetworksAddedByUser(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByUser = num;\n }\n }\n\n void setNumNetworksAddedByApps(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByApps = num;\n }\n }\n\n void setIsLocationEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isLocationEnabled = enabled;\n }\n }\n\n void setIsScanningAlwaysEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isScanningAlwaysEnabled = enabled;\n }\n }\n\n public void incrementNonEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numNonEmptyScanResults++;\n }\n }\n\n public void incrementEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numEmptyScanResults++;\n }\n }\n\n public void incrementBackgroundScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numBackgroundScans++;\n }\n }\n\n public int getBackgroundScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numBackgroundScans;\n }\n return i;\n }\n\n public void incrementOneshotScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numOneshotScans++;\n }\n incrementWifiSystemScanStateCount(this.mWifiState, this.mScreenOn);\n }\n\n public int getOneshotScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numOneshotScans;\n }\n return i;\n }\n\n private String returnCodeToString(int scanReturnCode) {\n switch(scanReturnCode) {\n case 0:\n return \"SCAN_UNKNOWN\";\n case 1:\n return \"SCAN_SUCCESS\";\n case 2:\n return \"SCAN_FAILURE_INTERRUPTED\";\n case 3:\n return \"SCAN_FAILURE_INVALID_CONFIGURATION\";\n case 4:\n return \"FAILURE_WIFI_DISABLED\";\n default:\n return \"\";\n }\n }\n\n public void incrementScanReturnEntry(int scanReturnCode, int countToAdd) {\n synchronized (this.mLock) {\n this.mScanReturnEntries.put(scanReturnCode, this.mScanReturnEntries.get(scanReturnCode) + countToAdd);\n }\n }\n\n public int getScanReturnEntry(int scanReturnCode) {\n int i;\n synchronized (this.mLock) {\n i = this.mScanReturnEntries.get(scanReturnCode);\n }\n return i;\n }\n\n private String wifiSystemStateToString(int state) {\n switch(state) {\n case 0:\n return \"WIFI_UNKNOWN\";\n case 1:\n return \"WIFI_DISABLED\";\n case 2:\n return \"WIFI_DISCONNECTED\";\n case 3:\n return \"WIFI_ASSOCIATED\";\n default:\n return \"default\";\n }\n }\n\n public void incrementWifiSystemScanStateCount(int state, boolean screenOn) {\n synchronized (this.mLock) {\n int index = (state * 2) + (screenOn ? 1 : 0);\n this.mWifiSystemStateEntries.put(index, this.mWifiSystemStateEntries.get(index) + 1);\n }\n }\n\n public int getSystemStateCount(int state, boolean screenOn) {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiSystemStateEntries.get((state * 2) + (screenOn ? 1 : 0));\n }\n return i;\n }\n\n public void incrementNumLastResortWatchdogTriggers() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggers++;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAssociationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAssociationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAuthenticationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadDhcpNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadDhcpNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadOtherNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadOtherNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogAvailableNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogAvailableNetworksTotal += count;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAssociation() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAssociation++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAuthentication() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAuthentication++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadDhcp() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadDhcp++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadOther() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadOther++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoBad++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundBad++;\n }\n }\n\n public void incrementRssiPollRssiCount(int rssi) {\n if (rssi >= MIN_RSSI_POLL && rssi <= 0) {\n synchronized (this.mLock) {\n this.mRssiPollCounts.put(rssi, this.mRssiPollCounts.get(rssi) + 1);\n }\n }\n ", "post_mask_code": "\n\n public void incrementNumLastResortWatchdogSuccesses() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogSuccesses++;\n }\n }\n\n public void incrementAlertReasonCount(int reason) {\n if (reason > 64 || reason < 0) {\n reason = 0;\n }\n synchronized (this.mLock) {\n this.mWifiAlertReasonCounts.put(reason, this.mWifiAlertReasonCounts.get(reason) + 1);\n }\n }\n\n public void countScanResults(List scanDetails) {\n if (scanDetails != null) {\n int totalResults = 0;\n int openNetworks = 0;\n int personalNetworks = 0;\n int enterpriseNetworks = 0;\n int hiddenNetworks = 0;\n int hotspot2r1Networks = 0;\n int hotspot2r2Networks = 0;\n for (ScanDetail scanDetail : scanDetails) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n totalResults++;\n if (networkDetail != null) {\n if (networkDetail.isHiddenBeaconFrame()) {\n hiddenNetworks++;\n }\n if (networkDetail.getHSRelease() != null) {\n if (networkDetail.getHSRelease() == HSRelease.R1) {\n hotspot2r1Networks++;\n } else if (networkDetail.getHSRelease() == HSRelease.R2) {\n hotspot2r2Networks++;\n }\n }\n }\n if (!(scanResult == null || scanResult.capabilities == null)) {\n if (scanResult.capabilities.contains(\"EAP\")) {\n enterpriseNetworks++;\n } else if (scanResult.capabilities.contains(\"PSK\") || scanResult.capabilities.contains(\"WEP\")) {\n personalNetworks++;\n } else {\n openNetworks++;\n }\n }\n }\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numTotalScanResults += totalResults;\n wifiLog = this.mWifiLogProto;\n wifiLog.numOpenNetworkScanResults += openNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numPersonalNetworkScanResults += personalNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numEnterpriseNetworkScanResults += enterpriseNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHiddenNetworkScanResults += hiddenNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R1NetworkScanResults += hotspot2r1Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R2NetworkScanResults += hotspot2r2Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numScans++;\n }\n }\n }\n\n public void incrementWifiScoreCount(int score) {\n if (score >= 0 && score <= 5) {\n synchronized (this.mLock) {\n this.mWifiScoreCounts.put(score, this.mWifiScoreCounts.get(score) + 1);\n }\n }\n }\n\n public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {\n synchronized (this.mLock) {\n int i;\n if (args != null) {\n if (args.length > 0 && PROTO_DUMP_ARG.equals(args[0])) {\n consolidateProto(true);\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (this.mCurrentConnectionEvent != event) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n String metricsProtoDump = Base64.encodeToString(MessageNano.toByteArray(this.mWifiLogProto), 0);\n if (args.length <= 1 || !CLEAN_DUMP_ARG.equals(args[1])) {\n pw.println(\"WifiMetrics:\");\n pw.println(metricsProtoDump);\n pw.println(\"EndWifiMetrics\");\n } else {\n pw.print(metricsProtoDump);\n }\n clear();\n }\n }\n pw.println(\"WifiMetrics:\");\n pw.println(\"mConnectionEvents:\");\n for (ConnectionEvent event2 : this.mConnectionEventList) {\n String eventLine = event2.toString();\n if (event2 == this.mCurrentConnectionEvent) {\n eventLine = eventLine + \"CURRENTLY OPEN EVENT\";\n }\n pw.println(eventLine);\n }\n pw.println(\"mWifiLogProto.numSavedNetworks=\" + this.mWifiLogProto.numSavedNetworks);\n pw.println(\"mWifiLogProto.numOpenNetworks=\" + this.mWifiLogProto.numOpenNetworks);\n pw.println(\"mWifiLogProto.numPersonalNetworks=\" + this.mWifiLogProto.numPersonalNetworks);\n pw.println(\"mWifiLogProto.numEnterpriseNetworks=\" + this.mWifiLogProto.numEnterpriseNetworks);\n pw.println(\"mWifiLogProto.numHiddenNetworks=\" + this.mWifiLogProto.numHiddenNetworks);\n pw.println(\"mWifiLogProto.numPasspointNetworks=\" + this.mWifiLogProto.numPasspointNetworks);\n pw.println(\"mWifiLogProto.isLocationEnabled=\" + this.mWifiLogProto.isLocationEnabled);\n pw.println(\"mWifiLogProto.isScanningAlwaysEnabled=\" + this.mWifiLogProto.isScanningAlwaysEnabled);\n pw.println(\"mWifiLogProto.numNetworksAddedByUser=\" + this.mWifiLogProto.numNetworksAddedByUser);\n pw.println(\"mWifiLogProto.numNetworksAddedByApps=\" + this.mWifiLogProto.numNetworksAddedByApps);\n pw.println(\"mWifiLogProto.numNonEmptyScanResults=\" + this.mWifiLogProto.numNonEmptyScanResults);\n pw.println(\"mWifiLogProto.numEmptyScanResults=\" + this.mWifiLogProto.numEmptyScanResults);\n pw.println(\"mWifiLogProto.numOneshotScans=\" + this.mWifiLogProto.numOneshotScans);\n pw.println(\"mWifiLogProto.numBackgroundScans=\" + this.mWifiLogProto.numBackgroundScans);\n pw.println(\"mScanReturnEntries:\");\n pw.println(\" SCAN_UNKNOWN: \" + getScanReturnEntry(0));\n pw.println(\" SCAN_SUCCESS: \" + getScanReturnEntry(1));\n pw.println(\" SCAN_FAILURE_INTERRUPTED: \" + getScanReturnEntry(2));\n pw.println(\" SCAN_FAILURE_INVALID_CONFIGURATION: \" + getScanReturnEntry(3));\n pw.println(\" FAILURE_WIFI_DISABLED: \" + getScanReturnEntry(4));\n pw.println(\"mSystemStateEntries: : \");\n pw.println(\" WIFI_UNKNOWN ON: \" + getSystemStateCount(0, true));\n pw.println(\" WIFI_DISABLED ON: \" + getSystemStateCount(1, true));\n pw.println(\" WIFI_DISCONNECTED ON: \" + getSystemStateCount(2, true));\n pw.println(\" WIFI_ASSOCIATED ON: \" + getSystemStateCount(3, true));\n pw.println(\" WIFI_UNKNOWN OFF: \" + getSystemStateCount(0, false));\n pw.println(\" WIFI_DISABLED OFF: \" + getSystemStateCount(1, false));\n pw.println(\" WIFI_DISCONNECTED OFF: \" + getSystemStateCount(2, false));\n pw.println(\" WIFI_ASSOCIATED OFF: \" + getSystemStateCount(3, false));\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoGood=\" + this.mWifiLogProto.numConnectivityWatchdogPnoGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoBad=\" + this.mWifiLogProto.numConnectivityWatchdogPnoBad);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundGood=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundBad=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundBad);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggers=\" + this.mWifiLogProto.numLastResortWatchdogTriggers);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadOther=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadOther);\n pw.println(\"mWifiLogProto.numLastResortWatchdogSuccesses=\" + this.mWifiLogProto.numLastResortWatchdogSuccesses);\n pw.println(\"mWifiLogProto.recordDurationSec=\" + ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec));\n pw.println(\"mWifiLogProto.rssiPollRssiCount: Printing counts for [-127, 0]\");\n StringBuilder sb = new StringBuilder();\n for (i = MIN_RSSI_POLL; i <= 0; i++) {\n sb.append(this.mRssiPollCounts.get(i)).append(\" \");\n }\n pw.println(\" \" + sb.toString());\n pw.print(\"mWifiLogProto.alertReasonCounts=\");\n sb.setLength(0);\n for (i = 0; i <= 64; i++) {\n int count = this.mWifiAlertReasonCounts.get(i);\n if (count > 0) {\n sb.append(\"(\").append(i).append(\",\").append(count).append(\"),\");\n }\n }\n if (sb.length() > 1) {\n sb.setLength(sb.length() - 1);\n pw.println(sb.toString());\n } else {\n pw.println(\"()\");\n }\n pw.println(\"mWifiLogProto.numTotalScanResults=\" + this.mWifiLogProto.numTotalScanResults);\n pw.println(\"mWifiLogProto.numOpenNetworkScanResults=\" + this.mWifiLogProto.numOpenNetworkScanResults);\n pw.println(\"mWifiLogProto.numPersonalNetworkScanResults=\" + this.mWifiLogProto.numPersonalNetworkScanResults);\n pw.println(\"mWifiLogProto.numEnterpriseNetworkScanResults=\" + this.mWifiLogProto.numEnterpriseNetworkScanResults);\n pw.println(\"mWifiLogProto.numHiddenNetworkScanResults=\" + this.mWifiLogProto.numHiddenNetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R1NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R1NetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R2NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R2NetworkScanResults);\n pw.println(\"mWifiLogProto.numScans=\" + this.mWifiLogProto.numScans);\n pw.println(\"mWifiLogProto.WifiScoreCount: [0, 5]\");\n for (i = 0; i <= 5; i++) {\n pw.print(this.mWifiScoreCounts.get(i) + \" \");\n }\n pw.print(\"\\n\");\n }\n }\n\n private void consolidateProto(boolean incremental) {\n List events = new ArrayList();\n List rssis = new ArrayList();\n List alertReasons = new ArrayList();\n List scores = new ArrayList();\n synchronized (this.mLock) {\n int i;\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (!(incremental && (this.mCurrentConnectionEvent == event || event.mConnectionEvent.automaticBugReportTaken))) {\n events.add(event.mConnectionEvent);\n if (incremental) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n }\n if (events.size() > 0) {\n this.mWifiLogProto.connectionEvent = (com.android.server.wifi.WifiMetricsProto.ConnectionEvent[]) events.toArray(this.mWifiLogProto.connectionEvent);\n }\n this.mWifiLogProto.scanReturnEntries = new ScanReturnEntry[this.mScanReturnEntries.size()];\n for (i = 0; i < this.mScanReturnEntries.size(); i++) {\n this.mWifiLogProto.scanReturnEntries[i] = new ScanReturnEntry();\n this.mWifiLogProto.scanReturnEntries[i].scanReturnCode = this.mScanReturnEntries.keyAt(i);\n this.mWifiLogProto.scanReturnEntries[i].scanResultsCount = this.mScanReturnEntries.valueAt(i);\n }\n this.mWifiLogProto.wifiSystemStateEntries = new WifiSystemStateEntry[this.mWifiSystemStateEntries.size()];\n for (i = 0; i < this.mWifiSystemStateEntries.size(); i++) {\n this.mWifiLogProto.wifiSystemStateEntries[i] = new WifiSystemStateEntry();\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiState = this.mWifiSystemStateEntries.keyAt(i) / 2;\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiStateCount = this.mWifiSystemStateEntries.valueAt(i);\n this.mWifiLogProto.wifiSystemStateEntries[i].isScreenOn = this.mWifiSystemStateEntries.keyAt(i) % 2 > 0;\n }\n this.mWifiLogProto.recordDurationSec = (int) ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec);\n for (i = 0; i < this.mRssiPollCounts.size(); i++) {\n RssiPollCount keyVal = new RssiPollCount();\n keyVal.rssi = this.mRssiPollCounts.keyAt(i);\n keyVal.count = this.mRssiPollCounts.valueAt(i);\n rssis.add(keyVal);\n }\n this.mWifiLogProto.rssiPollRssiCount = (RssiPollCount[]) rssis.toArray(this.mWifiLogProto.rssiPollRssiCount);\n for (i = 0; i < this.mWifiAlertReasonCounts.size(); i++) {\n AlertReasonCount keyVal2 = new AlertReasonCount();\n keyVal2.reason = this.mWifiAlertReasonCounts.keyAt(i);\n keyVal2.count = this.mWifiAlertReasonCounts.valueAt(i);\n alertReasons.add(keyVal2);\n }\n this.mWifiLogProto.alertReasonCount = (AlertReasonCount[]) alertReasons.toArray(this.mWifiLogProto.alertReasonCount);\n for (int score = 0; score < this.mWifiScoreCounts.size(); score++) {\n WifiScoreCount keyVal3 = new WifiScoreCount();\n keyVal3.score = this.mWifiScoreCounts.keyAt(score);\n keyVal3.count = this.mWifiScoreCounts.valueAt(score);\n scores.add(keyVal3);\n }\n this.mWifiLogProto.wifiScoreCount = (WifiScoreCount[]) scores.toArray(this.mWifiLogProto.wifiScoreCount);\n }\n }\n\n private void clear() {\n synchronized (this.mLock) {\n this.mConnectionEventList.clear();\n if (this.mCurrentConnectionEvent != null) {\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n this.mScanReturnEntries.clear();\n this.mWifiSystemStateEntries.clear();\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n this.mRssiPollCounts.clear();\n this.mWifiAlertReasonCounts.clear();\n this.mWifiScoreCounts.clear();\n this.mWifiLogProto.clear();\n }\n }\n\n public void setScreenState(boolean screenOn) {\n synchronized (this.mLock) {\n this.mScreenOn = screenOn;\n }\n }\n\n public void setWifiState(int wifiState) {\n synchronized (this.mLock) {\n this.mWifiState = wifiState;\n }\n }\n}\n"} {"task_id": "Java_692", "language": "Java", "task_type": "single_line", "source_file": "java/github/dstmath/OppoFramework/A1_7_1_1/src/main/java/com/android/server/wifi/WifiMetrics.java", "mask_start_position": 16536, "mask_end_position": 16563, "canonical_solution": "ology = connectionWifiMode;", "pre_mask_code": "package com.android.server.wifi;\n\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiConfiguration;\nimport android.util.Base64;\nimport android.util.SparseIntArray;\nimport com.android.server.wifi.WifiMetricsProto.AlertReasonCount;\nimport com.android.server.wifi.WifiMetricsProto.RssiPollCount;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.ScanReturnEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.WifiSystemStateEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiScoreCount;\nimport com.android.server.wifi.hotspot2.NetworkDetail;\nimport com.android.server.wifi.hotspot2.NetworkDetail.HSRelease;\nimport com.google.protobuf.nano.MessageNano;\nimport java.io.FileDescriptor;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.List;\n\npublic class WifiMetrics {\n\n public static final String CLEAN_DUMP_ARG = \"clean\";\n\n private static final boolean DBG = false;\n\n private static final int MAX_CONNECTION_EVENTS = 256;\n\n private static final int MAX_RSSI_POLL = 0;\n\n private static final int MAX_WIFI_SCORE = 5;\n\n private static final int MIN_RSSI_POLL = -127;\n\n private static final int MIN_WIFI_SCORE = 0;\n\n public static final String PROTO_DUMP_ARG = \"wifiMetricsProto\";\n\n private static final int SCREEN_OFF = 0;\n\n private static final int SCREEN_ON = 1;\n\n private static final String TAG = \"WifiMetrics\";\n\n private Clock mClock;\n\n private final List mConnectionEventList = new ArrayList();\n\n private ConnectionEvent mCurrentConnectionEvent;\n\n private final Object mLock = new Object();\n\n private long mRecordStartTimeSec;\n\n private final SparseIntArray mRssiPollCounts = new SparseIntArray();\n\n private final SparseIntArray mScanReturnEntries = new SparseIntArray();\n\n private boolean mScreenOn;\n\n private final SparseIntArray mWifiAlertReasonCounts = new SparseIntArray();\n\n private final WifiLog mWifiLogProto = new WifiLog();\n\n private final SparseIntArray mWifiScoreCounts = new SparseIntArray();\n\n private int mWifiState;\n\n private final SparseIntArray mWifiSystemStateEntries = new SparseIntArray();\n\n class ConnectionEvent {\n\n public static final int FAILURE_ASSOCIATION_REJECTION = 2;\n\n public static final int FAILURE_AUTHENTICATION_FAILURE = 3;\n\n public static final int FAILURE_CONNECT_NETWORK_FAILED = 5;\n\n public static final int FAILURE_DHCP = 10;\n\n public static final int FAILURE_NETWORK_DISCONNECTION = 6;\n\n public static final int FAILURE_NEW_CONNECTION_ATTEMPT = 7;\n\n public static final int FAILURE_NONE = 1;\n\n public static final int FAILURE_REDUNDANT_CONNECTION_ATTEMPT = 8;\n\n public static final int FAILURE_ROAM_TIMEOUT = 9;\n\n public static final int FAILURE_SSID_TEMP_DISABLED = 4;\n\n public static final int FAILURE_UNKNOWN = 0;\n\n private String mConfigBssid;\n\n private String mConfigSsid;\n\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent mConnectionEvent;\n\n private long mRealEndTime;\n\n private long mRealStartTime;\n\n RouterFingerPrint mRouterFingerPrint;\n\n private boolean mScreenOn;\n\n private int mWifiState;\n\n /* synthetic */\n ConnectionEvent(WifiMetrics this$0, ConnectionEvent connectionEvent) {\n this();\n }\n\n private ConnectionEvent() {\n this.mConnectionEvent = new com.android.server.wifi.WifiMetricsProto.ConnectionEvent();\n this.mRealEndTime = 0;\n this.mRealStartTime = 0;\n this.mRouterFingerPrint = new RouterFingerPrint();\n this.mConnectionEvent.routerFingerprint = this.mRouterFingerPrint.mRouterFingerPrintProto;\n this.mConfigSsid = \"\";\n this.mConfigBssid = \"\";\n this.mWifiState = 0;\n this.mScreenOn = false;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"startTime=\");\n Calendar c = Calendar.getInstance();\n synchronized (WifiMetrics.this.mLock) {\n String str;\n c.setTimeInMillis(this.mConnectionEvent.startTimeMillis);\n if (this.mConnectionEvent.startTimeMillis == 0) {\n str = \" \";\n } else {\n str = String.format(\"%tm-%td %tH:%tM:%tS.%tL\", new Object[] { c, c, c, c, c, c });\n }\n sb.append(str);\n sb.append(\", SSID=\");\n sb.append(this.mConfigSsid);\n sb.append(\", BSSID=\");\n sb.append(this.mConfigBssid);\n sb.append(\", durationMillis=\");\n sb.append(this.mConnectionEvent.durationTakenToConnectMillis);\n sb.append(\", roamType=\");\n switch(this.mConnectionEvent.roamType) {\n case 1:\n sb.append(\"ROAM_NONE\");\n break;\n case 2:\n sb.append(\"ROAM_DBDC\");\n break;\n case 3:\n sb.append(\"ROAM_ENTERPRISE\");\n break;\n case 4:\n sb.append(\"ROAM_USER_SELECTED\");\n break;\n case 5:\n sb.append(\"ROAM_UNRELATED\");\n break;\n default:\n sb.append(\"ROAM_UNKNOWN\");\n break;\n }\n sb.append(\", connectionResult=\");\n sb.append(this.mConnectionEvent.connectionResult);\n sb.append(\", level2FailureCode=\");\n switch(this.mConnectionEvent.level2FailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"ASSOCIATION_REJECTION\");\n break;\n case 3:\n sb.append(\"AUTHENTICATION_FAILURE\");\n break;\n case 4:\n sb.append(\"SSID_TEMP_DISABLED\");\n break;\n case 5:\n sb.append(\"CONNECT_NETWORK_FAILED\");\n break;\n case 6:\n sb.append(\"NETWORK_DISCONNECTION\");\n break;\n case 7:\n sb.append(\"NEW_CONNECTION_ATTEMPT\");\n break;\n case 8:\n sb.append(\"REDUNDANT_CONNECTION_ATTEMPT\");\n break;\n case 9:\n sb.append(\"ROAM_TIMEOUT\");\n break;\n case 10:\n sb.append(\"DHCP\");\n break;\n }\n sb.append(\"UNKNOWN\");\n sb.append(\", connectivityLevelFailureCode=\");\n switch(this.mConnectionEvent.connectivityLevelFailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"DHCP\");\n break;\n case 3:\n sb.append(\"NO_INTERNET\");\n break;\n case 4:\n sb.append(\"UNWANTED\");\n break;\n default:\n sb.append(\"UNKNOWN\");\n break;\n }\n sb.append(\", signalStrength=\");\n sb.append(this.mConnectionEvent.signalStrength);\n sb.append(\", wifiState=\");\n switch(this.mWifiState) {\n case 1:\n sb.append(\"WIFI_DISABLED\");\n break;\n case 2:\n sb.append(\"WIFI_DISCONNECTED\");\n break;\n case 3:\n sb.append(\"WIFI_ASSOCIATED\");\n break;\n default:\n sb.append(\"WIFI_UNKNOWN\");\n break;\n }\n sb.append(\", screenOn=\");\n sb.append(this.mScreenOn);\n sb.append(\". mRouterFingerprint: \");\n sb.append(this.mRouterFingerPrint.toString());\n }\n return sb.toString();\n }\n }\n\n class RouterFingerPrint {\n\n private com.android.server.wifi.WifiMetricsProto.RouterFingerPrint mRouterFingerPrintProto = new com.android.server.wifi.WifiMetricsProto.RouterFingerPrint();\n\n RouterFingerPrint() {\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n synchronized (WifiMetrics.this.mLock) {\n sb.append(\"mConnectionEvent.roamType=\").append(this.mRouterFingerPrintProto.roamType);\n sb.append(\", mChannelInfo=\").append(this.mRouterFingerPrintProto.channelInfo);\n sb.append(\", mDtim=\").append(this.mRouterFingerPrintProto.dtim);\n sb.append(\", mAuthentication=\").append(this.mRouterFingerPrintProto.authentication);\n sb.append(\", mHidden=\").append(this.mRouterFingerPrintProto.hidden);\n sb.append(\", mRouterTechnology=\").append(this.mRouterFingerPrintProto.routerTechnology);\n sb.append(\", mSupportsIpv6=\").append(this.mRouterFingerPrintProto.supportsIpv6);\n }\n return sb.toString();\n }\n\n public void updateFromWifiConfiguration(WifiConfiguration config) {\n synchronized (WifiMetrics.this.mLock) {\n if (config != null) {\n this.mRouterFingerPrintProto.hidden = config.hiddenSSID;\n if (config.dtimInterval > 0) {\n this.mRouterFingerPrintProto.dtim = config.dtimInterval;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mConfigSsid = config.SSID;\n if (config.allowedKeyManagement != null && config.allowedKeyManagement.get(0)) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n } else if (config.isEnterprise()) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n } else {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.passpoint = config.isPasspoint();\n ScanResult candidate = config.getNetworkSelectionStatus().getCandidate();\n if (candidate != null) {\n WifiMetrics.this.updateMetricsFromScanResult(candidate);\n }\n }\n }\n }\n }\n\n public WifiMetrics(Clock clock) {\n this.mClock = clock;\n this.mCurrentConnectionEvent = null;\n this.mScreenOn = true;\n this.mWifiState = 1;\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n }\n\n public void startConnectionEvent(WifiConfiguration config, String targetBSSID, int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n if (this.mCurrentConnectionEvent.mConfigSsid == null || this.mCurrentConnectionEvent.mConfigBssid == null || config == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(config.SSID) || !(this.mCurrentConnectionEvent.mConfigBssid.equals(WifiLastResortWatchdog.BSSID_ANY) || this.mCurrentConnectionEvent.mConfigBssid.equals(targetBSSID))) {\n endConnectionEvent(7, 1);\n } else {\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n endConnectionEvent(8, 1);\n }\n }\n while (this.mConnectionEventList.size() >= 256) {\n this.mConnectionEventList.remove(0);\n }\n this.mCurrentConnectionEvent = new ConnectionEvent(this, null);\n this.mCurrentConnectionEvent.mConnectionEvent.startTimeMillis = this.mClock.currentTimeMillis();\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n this.mCurrentConnectionEvent.mRouterFingerPrint.updateFromWifiConfiguration(config);\n this.mCurrentConnectionEvent.mConfigBssid = WifiLastResortWatchdog.BSSID_ANY;\n this.mCurrentConnectionEvent.mRealStartTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mWifiState = this.mWifiState;\n this.mCurrentConnectionEvent.mScreenOn = this.mScreenOn;\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n }\n\n public void setConnectionEventRoamType(int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n }\n }\n }\n\n public void setConnectionScanDetail(ScanDetail scanDetail) {\n synchronized (this.mLock) {\n if (!(this.mCurrentConnectionEvent == null || scanDetail == null)) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n if (!(networkDetail == null || scanResult == null || this.mCurrentConnectionEvent.mConfigSsid == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(\"\\\"\" + networkDetail.getSSID() + \"\\\"\"))) {\n updateMetricsFromNetworkDetail(networkDetail);\n updateMetricsFromScanResult(scanResult);\n }\n }\n }\n }\n\n public void endConnectionEvent(int level2FailureCode, int connectivityFailureCode) {\n int i = 1;\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n boolean result = level2FailureCode == 1 ? connectivityFailureCode == 1 : false;\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent connectionEvent = this.mCurrentConnectionEvent.mConnectionEvent;\n if (!result) {\n i = 0;\n }\n connectionEvent.connectionResult = i;\n this.mCurrentConnectionEvent.mRealEndTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mConnectionEvent.durationTakenToConnectMillis = (int) (this.mCurrentConnectionEvent.mRealEndTime - this.mCurrentConnectionEvent.mRealStartTime);\n this.mCurrentConnectionEvent.mConnectionEvent.level2FailureCode = level2FailureCode;\n this.mCurrentConnectionEvent.mConnectionEvent.connectivityLevelFailureCode = connectivityFailureCode;\n this.mCurrentConnectionEvent = null;\n }\n }\n }\n\n private void updateMetricsFromNetworkDetail(NetworkDetail networkDetail) {\n int connectionWifiMode;\n int dtimInterval = networkDetail.getDtimInterval();\n if (dtimInterval > 0) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.dtim = dtimInterval;\n }\n switch(networkDetail.getWifiMode()) {\n case 0:\n connectionWifiMode = 0;\n break;\n case 1:\n connectionWifiMode = 1;\n break;\n case 2:\n connectionWifiMode = 2;\n break;\n case 3:\n connectionWifiMode = 3;\n break;\n case 4:\n connectionWifiMode = 4;\n break;\n case 5:\n connectionWifiMode = 5;\n break;\n default:\n connectionWifiMode = 6;\n break;\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.routerTechn", "post_mask_code": "\n }\n\n private void updateMetricsFromScanResult(ScanResult scanResult) {\n this.mCurrentConnectionEvent.mConnectionEvent.signalStrength = scanResult.level;\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n this.mCurrentConnectionEvent.mConfigBssid = scanResult.BSSID;\n if (scanResult.capabilities != null) {\n if (scanResult.capabilities.contains(\"WEP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"PSK\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"EAP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n }\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.channelInfo = scanResult.frequency;\n }\n\n void setNumSavedNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numSavedNetworks = num;\n }\n }\n\n void setNumOpenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numOpenNetworks = num;\n }\n }\n\n void setNumPersonalNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPersonalNetworks = num;\n }\n }\n\n void setNumEnterpriseNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numEnterpriseNetworks = num;\n }\n }\n\n void setNumHiddenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numHiddenNetworks = num;\n }\n }\n\n void setNumPasspointNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPasspointNetworks = num;\n }\n }\n\n void setNumNetworksAddedByUser(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByUser = num;\n }\n }\n\n void setNumNetworksAddedByApps(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByApps = num;\n }\n }\n\n void setIsLocationEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isLocationEnabled = enabled;\n }\n }\n\n void setIsScanningAlwaysEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isScanningAlwaysEnabled = enabled;\n }\n }\n\n public void incrementNonEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numNonEmptyScanResults++;\n }\n }\n\n public void incrementEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numEmptyScanResults++;\n }\n }\n\n public void incrementBackgroundScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numBackgroundScans++;\n }\n }\n\n public int getBackgroundScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numBackgroundScans;\n }\n return i;\n }\n\n public void incrementOneshotScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numOneshotScans++;\n }\n incrementWifiSystemScanStateCount(this.mWifiState, this.mScreenOn);\n }\n\n public int getOneshotScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numOneshotScans;\n }\n return i;\n }\n\n private String returnCodeToString(int scanReturnCode) {\n switch(scanReturnCode) {\n case 0:\n return \"SCAN_UNKNOWN\";\n case 1:\n return \"SCAN_SUCCESS\";\n case 2:\n return \"SCAN_FAILURE_INTERRUPTED\";\n case 3:\n return \"SCAN_FAILURE_INVALID_CONFIGURATION\";\n case 4:\n return \"FAILURE_WIFI_DISABLED\";\n default:\n return \"\";\n }\n }\n\n public void incrementScanReturnEntry(int scanReturnCode, int countToAdd) {\n synchronized (this.mLock) {\n this.mScanReturnEntries.put(scanReturnCode, this.mScanReturnEntries.get(scanReturnCode) + countToAdd);\n }\n }\n\n public int getScanReturnEntry(int scanReturnCode) {\n int i;\n synchronized (this.mLock) {\n i = this.mScanReturnEntries.get(scanReturnCode);\n }\n return i;\n }\n\n private String wifiSystemStateToString(int state) {\n switch(state) {\n case 0:\n return \"WIFI_UNKNOWN\";\n case 1:\n return \"WIFI_DISABLED\";\n case 2:\n return \"WIFI_DISCONNECTED\";\n case 3:\n return \"WIFI_ASSOCIATED\";\n default:\n return \"default\";\n }\n }\n\n public void incrementWifiSystemScanStateCount(int state, boolean screenOn) {\n synchronized (this.mLock) {\n int index = (state * 2) + (screenOn ? 1 : 0);\n this.mWifiSystemStateEntries.put(index, this.mWifiSystemStateEntries.get(index) + 1);\n }\n }\n\n public int getSystemStateCount(int state, boolean screenOn) {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiSystemStateEntries.get((state * 2) + (screenOn ? 1 : 0));\n }\n return i;\n }\n\n public void incrementNumLastResortWatchdogTriggers() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggers++;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAssociationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAssociationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAuthenticationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadDhcpNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadDhcpNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadOtherNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadOtherNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogAvailableNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogAvailableNetworksTotal += count;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAssociation() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAssociation++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAuthentication() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAuthentication++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadDhcp() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadDhcp++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadOther() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadOther++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoBad++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundBad++;\n }\n }\n\n public void incrementRssiPollRssiCount(int rssi) {\n if (rssi >= MIN_RSSI_POLL && rssi <= 0) {\n synchronized (this.mLock) {\n this.mRssiPollCounts.put(rssi, this.mRssiPollCounts.get(rssi) + 1);\n }\n }\n }\n\n public void incrementNumLastResortWatchdogSuccesses() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogSuccesses++;\n }\n }\n\n public void incrementAlertReasonCount(int reason) {\n if (reason > 64 || reason < 0) {\n reason = 0;\n }\n synchronized (this.mLock) {\n this.mWifiAlertReasonCounts.put(reason, this.mWifiAlertReasonCounts.get(reason) + 1);\n }\n }\n\n public void countScanResults(List scanDetails) {\n if (scanDetails != null) {\n int totalResults = 0;\n int openNetworks = 0;\n int personalNetworks = 0;\n int enterpriseNetworks = 0;\n int hiddenNetworks = 0;\n int hotspot2r1Networks = 0;\n int hotspot2r2Networks = 0;\n for (ScanDetail scanDetail : scanDetails) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n totalResults++;\n if (networkDetail != null) {\n if (networkDetail.isHiddenBeaconFrame()) {\n hiddenNetworks++;\n }\n if (networkDetail.getHSRelease() != null) {\n if (networkDetail.getHSRelease() == HSRelease.R1) {\n hotspot2r1Networks++;\n } else if (networkDetail.getHSRelease() == HSRelease.R2) {\n hotspot2r2Networks++;\n }\n }\n }\n if (!(scanResult == null || scanResult.capabilities == null)) {\n if (scanResult.capabilities.contains(\"EAP\")) {\n enterpriseNetworks++;\n } else if (scanResult.capabilities.contains(\"PSK\") || scanResult.capabilities.contains(\"WEP\")) {\n personalNetworks++;\n } else {\n openNetworks++;\n }\n }\n }\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numTotalScanResults += totalResults;\n wifiLog = this.mWifiLogProto;\n wifiLog.numOpenNetworkScanResults += openNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numPersonalNetworkScanResults += personalNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numEnterpriseNetworkScanResults += enterpriseNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHiddenNetworkScanResults += hiddenNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R1NetworkScanResults += hotspot2r1Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R2NetworkScanResults += hotspot2r2Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numScans++;\n }\n }\n }\n\n public void incrementWifiScoreCount(int score) {\n if (score >= 0 && score <= 5) {\n synchronized (this.mLock) {\n this.mWifiScoreCounts.put(score, this.mWifiScoreCounts.get(score) + 1);\n }\n }\n }\n\n public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {\n synchronized (this.mLock) {\n int i;\n if (args != null) {\n if (args.length > 0 && PROTO_DUMP_ARG.equals(args[0])) {\n consolidateProto(true);\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (this.mCurrentConnectionEvent != event) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n String metricsProtoDump = Base64.encodeToString(MessageNano.toByteArray(this.mWifiLogProto), 0);\n if (args.length <= 1 || !CLEAN_DUMP_ARG.equals(args[1])) {\n pw.println(\"WifiMetrics:\");\n pw.println(metricsProtoDump);\n pw.println(\"EndWifiMetrics\");\n } else {\n pw.print(metricsProtoDump);\n }\n clear();\n }\n }\n pw.println(\"WifiMetrics:\");\n pw.println(\"mConnectionEvents:\");\n for (ConnectionEvent event2 : this.mConnectionEventList) {\n String eventLine = event2.toString();\n if (event2 == this.mCurrentConnectionEvent) {\n eventLine = eventLine + \"CURRENTLY OPEN EVENT\";\n }\n pw.println(eventLine);\n }\n pw.println(\"mWifiLogProto.numSavedNetworks=\" + this.mWifiLogProto.numSavedNetworks);\n pw.println(\"mWifiLogProto.numOpenNetworks=\" + this.mWifiLogProto.numOpenNetworks);\n pw.println(\"mWifiLogProto.numPersonalNetworks=\" + this.mWifiLogProto.numPersonalNetworks);\n pw.println(\"mWifiLogProto.numEnterpriseNetworks=\" + this.mWifiLogProto.numEnterpriseNetworks);\n pw.println(\"mWifiLogProto.numHiddenNetworks=\" + this.mWifiLogProto.numHiddenNetworks);\n pw.println(\"mWifiLogProto.numPasspointNetworks=\" + this.mWifiLogProto.numPasspointNetworks);\n pw.println(\"mWifiLogProto.isLocationEnabled=\" + this.mWifiLogProto.isLocationEnabled);\n pw.println(\"mWifiLogProto.isScanningAlwaysEnabled=\" + this.mWifiLogProto.isScanningAlwaysEnabled);\n pw.println(\"mWifiLogProto.numNetworksAddedByUser=\" + this.mWifiLogProto.numNetworksAddedByUser);\n pw.println(\"mWifiLogProto.numNetworksAddedByApps=\" + this.mWifiLogProto.numNetworksAddedByApps);\n pw.println(\"mWifiLogProto.numNonEmptyScanResults=\" + this.mWifiLogProto.numNonEmptyScanResults);\n pw.println(\"mWifiLogProto.numEmptyScanResults=\" + this.mWifiLogProto.numEmptyScanResults);\n pw.println(\"mWifiLogProto.numOneshotScans=\" + this.mWifiLogProto.numOneshotScans);\n pw.println(\"mWifiLogProto.numBackgroundScans=\" + this.mWifiLogProto.numBackgroundScans);\n pw.println(\"mScanReturnEntries:\");\n pw.println(\" SCAN_UNKNOWN: \" + getScanReturnEntry(0));\n pw.println(\" SCAN_SUCCESS: \" + getScanReturnEntry(1));\n pw.println(\" SCAN_FAILURE_INTERRUPTED: \" + getScanReturnEntry(2));\n pw.println(\" SCAN_FAILURE_INVALID_CONFIGURATION: \" + getScanReturnEntry(3));\n pw.println(\" FAILURE_WIFI_DISABLED: \" + getScanReturnEntry(4));\n pw.println(\"mSystemStateEntries: : \");\n pw.println(\" WIFI_UNKNOWN ON: \" + getSystemStateCount(0, true));\n pw.println(\" WIFI_DISABLED ON: \" + getSystemStateCount(1, true));\n pw.println(\" WIFI_DISCONNECTED ON: \" + getSystemStateCount(2, true));\n pw.println(\" WIFI_ASSOCIATED ON: \" + getSystemStateCount(3, true));\n pw.println(\" WIFI_UNKNOWN OFF: \" + getSystemStateCount(0, false));\n pw.println(\" WIFI_DISABLED OFF: \" + getSystemStateCount(1, false));\n pw.println(\" WIFI_DISCONNECTED OFF: \" + getSystemStateCount(2, false));\n pw.println(\" WIFI_ASSOCIATED OFF: \" + getSystemStateCount(3, false));\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoGood=\" + this.mWifiLogProto.numConnectivityWatchdogPnoGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoBad=\" + this.mWifiLogProto.numConnectivityWatchdogPnoBad);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundGood=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundBad=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundBad);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggers=\" + this.mWifiLogProto.numLastResortWatchdogTriggers);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadOther=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadOther);\n pw.println(\"mWifiLogProto.numLastResortWatchdogSuccesses=\" + this.mWifiLogProto.numLastResortWatchdogSuccesses);\n pw.println(\"mWifiLogProto.recordDurationSec=\" + ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec));\n pw.println(\"mWifiLogProto.rssiPollRssiCount: Printing counts for [-127, 0]\");\n StringBuilder sb = new StringBuilder();\n for (i = MIN_RSSI_POLL; i <= 0; i++) {\n sb.append(this.mRssiPollCounts.get(i)).append(\" \");\n }\n pw.println(\" \" + sb.toString());\n pw.print(\"mWifiLogProto.alertReasonCounts=\");\n sb.setLength(0);\n for (i = 0; i <= 64; i++) {\n int count = this.mWifiAlertReasonCounts.get(i);\n if (count > 0) {\n sb.append(\"(\").append(i).append(\",\").append(count).append(\"),\");\n }\n }\n if (sb.length() > 1) {\n sb.setLength(sb.length() - 1);\n pw.println(sb.toString());\n } else {\n pw.println(\"()\");\n }\n pw.println(\"mWifiLogProto.numTotalScanResults=\" + this.mWifiLogProto.numTotalScanResults);\n pw.println(\"mWifiLogProto.numOpenNetworkScanResults=\" + this.mWifiLogProto.numOpenNetworkScanResults);\n pw.println(\"mWifiLogProto.numPersonalNetworkScanResults=\" + this.mWifiLogProto.numPersonalNetworkScanResults);\n pw.println(\"mWifiLogProto.numEnterpriseNetworkScanResults=\" + this.mWifiLogProto.numEnterpriseNetworkScanResults);\n pw.println(\"mWifiLogProto.numHiddenNetworkScanResults=\" + this.mWifiLogProto.numHiddenNetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R1NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R1NetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R2NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R2NetworkScanResults);\n pw.println(\"mWifiLogProto.numScans=\" + this.mWifiLogProto.numScans);\n pw.println(\"mWifiLogProto.WifiScoreCount: [0, 5]\");\n for (i = 0; i <= 5; i++) {\n pw.print(this.mWifiScoreCounts.get(i) + \" \");\n }\n pw.print(\"\\n\");\n }\n }\n\n private void consolidateProto(boolean incremental) {\n List events = new ArrayList();\n List rssis = new ArrayList();\n List alertReasons = new ArrayList();\n List scores = new ArrayList();\n synchronized (this.mLock) {\n int i;\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (!(incremental && (this.mCurrentConnectionEvent == event || event.mConnectionEvent.automaticBugReportTaken))) {\n events.add(event.mConnectionEvent);\n if (incremental) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n }\n if (events.size() > 0) {\n this.mWifiLogProto.connectionEvent = (com.android.server.wifi.WifiMetricsProto.ConnectionEvent[]) events.toArray(this.mWifiLogProto.connectionEvent);\n }\n this.mWifiLogProto.scanReturnEntries = new ScanReturnEntry[this.mScanReturnEntries.size()];\n for (i = 0; i < this.mScanReturnEntries.size(); i++) {\n this.mWifiLogProto.scanReturnEntries[i] = new ScanReturnEntry();\n this.mWifiLogProto.scanReturnEntries[i].scanReturnCode = this.mScanReturnEntries.keyAt(i);\n this.mWifiLogProto.scanReturnEntries[i].scanResultsCount = this.mScanReturnEntries.valueAt(i);\n }\n this.mWifiLogProto.wifiSystemStateEntries = new WifiSystemStateEntry[this.mWifiSystemStateEntries.size()];\n for (i = 0; i < this.mWifiSystemStateEntries.size(); i++) {\n this.mWifiLogProto.wifiSystemStateEntries[i] = new WifiSystemStateEntry();\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiState = this.mWifiSystemStateEntries.keyAt(i) / 2;\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiStateCount = this.mWifiSystemStateEntries.valueAt(i);\n this.mWifiLogProto.wifiSystemStateEntries[i].isScreenOn = this.mWifiSystemStateEntries.keyAt(i) % 2 > 0;\n }\n this.mWifiLogProto.recordDurationSec = (int) ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec);\n for (i = 0; i < this.mRssiPollCounts.size(); i++) {\n RssiPollCount keyVal = new RssiPollCount();\n keyVal.rssi = this.mRssiPollCounts.keyAt(i);\n keyVal.count = this.mRssiPollCounts.valueAt(i);\n rssis.add(keyVal);\n }\n this.mWifiLogProto.rssiPollRssiCount = (RssiPollCount[]) rssis.toArray(this.mWifiLogProto.rssiPollRssiCount);\n for (i = 0; i < this.mWifiAlertReasonCounts.size(); i++) {\n AlertReasonCount keyVal2 = new AlertReasonCount();\n keyVal2.reason = this.mWifiAlertReasonCounts.keyAt(i);\n keyVal2.count = this.mWifiAlertReasonCounts.valueAt(i);\n alertReasons.add(keyVal2);\n }\n this.mWifiLogProto.alertReasonCount = (AlertReasonCount[]) alertReasons.toArray(this.mWifiLogProto.alertReasonCount);\n for (int score = 0; score < this.mWifiScoreCounts.size(); score++) {\n WifiScoreCount keyVal3 = new WifiScoreCount();\n keyVal3.score = this.mWifiScoreCounts.keyAt(score);\n keyVal3.count = this.mWifiScoreCounts.valueAt(score);\n scores.add(keyVal3);\n }\n this.mWifiLogProto.wifiScoreCount = (WifiScoreCount[]) scores.toArray(this.mWifiLogProto.wifiScoreCount);\n }\n }\n\n private void clear() {\n synchronized (this.mLock) {\n this.mConnectionEventList.clear();\n if (this.mCurrentConnectionEvent != null) {\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n this.mScanReturnEntries.clear();\n this.mWifiSystemStateEntries.clear();\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n this.mRssiPollCounts.clear();\n this.mWifiAlertReasonCounts.clear();\n this.mWifiScoreCounts.clear();\n this.mWifiLogProto.clear();\n }\n }\n\n public void setScreenState(boolean screenOn) {\n synchronized (this.mLock) {\n this.mScreenOn = screenOn;\n }\n }\n\n public void setWifiState(int wifiState) {\n synchronized (this.mLock) {\n this.mWifiState = wifiState;\n }\n }\n}\n"} {"task_id": "Java_693", "language": "Java", "task_type": "if_statement", "source_file": "java/github/dstmath/OppoFramework/A1_7_1_1/src/main/java/com/android/server/wifi/WifiMetrics.java", "mask_start_position": 27613, "mask_end_position": 28059, "canonical_solution": "if (!(scanResult == null || scanResult.capabilities == null)) {\n if (scanResult.capabilities.contains(\"EAP\")) {\n enterpriseNetworks++;\n } else if (scanResult.capabilities.contains(\"PSK\") || scanResult.capabilities.contains(\"WEP\")) {\n personalNetworks++;\n } else {\n openNetworks++;\n }\n }", "pre_mask_code": "package com.android.server.wifi;\n\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiConfiguration;\nimport android.util.Base64;\nimport android.util.SparseIntArray;\nimport com.android.server.wifi.WifiMetricsProto.AlertReasonCount;\nimport com.android.server.wifi.WifiMetricsProto.RssiPollCount;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.ScanReturnEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.WifiSystemStateEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiScoreCount;\nimport com.android.server.wifi.hotspot2.NetworkDetail;\nimport com.android.server.wifi.hotspot2.NetworkDetail.HSRelease;\nimport com.google.protobuf.nano.MessageNano;\nimport java.io.FileDescriptor;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.List;\n\npublic class WifiMetrics {\n\n public static final String CLEAN_DUMP_ARG = \"clean\";\n\n private static final boolean DBG = false;\n\n private static final int MAX_CONNECTION_EVENTS = 256;\n\n private static final int MAX_RSSI_POLL = 0;\n\n private static final int MAX_WIFI_SCORE = 5;\n\n private static final int MIN_RSSI_POLL = -127;\n\n private static final int MIN_WIFI_SCORE = 0;\n\n public static final String PROTO_DUMP_ARG = \"wifiMetricsProto\";\n\n private static final int SCREEN_OFF = 0;\n\n private static final int SCREEN_ON = 1;\n\n private static final String TAG = \"WifiMetrics\";\n\n private Clock mClock;\n\n private final List mConnectionEventList = new ArrayList();\n\n private ConnectionEvent mCurrentConnectionEvent;\n\n private final Object mLock = new Object();\n\n private long mRecordStartTimeSec;\n\n private final SparseIntArray mRssiPollCounts = new SparseIntArray();\n\n private final SparseIntArray mScanReturnEntries = new SparseIntArray();\n\n private boolean mScreenOn;\n\n private final SparseIntArray mWifiAlertReasonCounts = new SparseIntArray();\n\n private final WifiLog mWifiLogProto = new WifiLog();\n\n private final SparseIntArray mWifiScoreCounts = new SparseIntArray();\n\n private int mWifiState;\n\n private final SparseIntArray mWifiSystemStateEntries = new SparseIntArray();\n\n class ConnectionEvent {\n\n public static final int FAILURE_ASSOCIATION_REJECTION = 2;\n\n public static final int FAILURE_AUTHENTICATION_FAILURE = 3;\n\n public static final int FAILURE_CONNECT_NETWORK_FAILED = 5;\n\n public static final int FAILURE_DHCP = 10;\n\n public static final int FAILURE_NETWORK_DISCONNECTION = 6;\n\n public static final int FAILURE_NEW_CONNECTION_ATTEMPT = 7;\n\n public static final int FAILURE_NONE = 1;\n\n public static final int FAILURE_REDUNDANT_CONNECTION_ATTEMPT = 8;\n\n public static final int FAILURE_ROAM_TIMEOUT = 9;\n\n public static final int FAILURE_SSID_TEMP_DISABLED = 4;\n\n public static final int FAILURE_UNKNOWN = 0;\n\n private String mConfigBssid;\n\n private String mConfigSsid;\n\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent mConnectionEvent;\n\n private long mRealEndTime;\n\n private long mRealStartTime;\n\n RouterFingerPrint mRouterFingerPrint;\n\n private boolean mScreenOn;\n\n private int mWifiState;\n\n /* synthetic */\n ConnectionEvent(WifiMetrics this$0, ConnectionEvent connectionEvent) {\n this();\n }\n\n private ConnectionEvent() {\n this.mConnectionEvent = new com.android.server.wifi.WifiMetricsProto.ConnectionEvent();\n this.mRealEndTime = 0;\n this.mRealStartTime = 0;\n this.mRouterFingerPrint = new RouterFingerPrint();\n this.mConnectionEvent.routerFingerprint = this.mRouterFingerPrint.mRouterFingerPrintProto;\n this.mConfigSsid = \"\";\n this.mConfigBssid = \"\";\n this.mWifiState = 0;\n this.mScreenOn = false;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"startTime=\");\n Calendar c = Calendar.getInstance();\n synchronized (WifiMetrics.this.mLock) {\n String str;\n c.setTimeInMillis(this.mConnectionEvent.startTimeMillis);\n if (this.mConnectionEvent.startTimeMillis == 0) {\n str = \" \";\n } else {\n str = String.format(\"%tm-%td %tH:%tM:%tS.%tL\", new Object[] { c, c, c, c, c, c });\n }\n sb.append(str);\n sb.append(\", SSID=\");\n sb.append(this.mConfigSsid);\n sb.append(\", BSSID=\");\n sb.append(this.mConfigBssid);\n sb.append(\", durationMillis=\");\n sb.append(this.mConnectionEvent.durationTakenToConnectMillis);\n sb.append(\", roamType=\");\n switch(this.mConnectionEvent.roamType) {\n case 1:\n sb.append(\"ROAM_NONE\");\n break;\n case 2:\n sb.append(\"ROAM_DBDC\");\n break;\n case 3:\n sb.append(\"ROAM_ENTERPRISE\");\n break;\n case 4:\n sb.append(\"ROAM_USER_SELECTED\");\n break;\n case 5:\n sb.append(\"ROAM_UNRELATED\");\n break;\n default:\n sb.append(\"ROAM_UNKNOWN\");\n break;\n }\n sb.append(\", connectionResult=\");\n sb.append(this.mConnectionEvent.connectionResult);\n sb.append(\", level2FailureCode=\");\n switch(this.mConnectionEvent.level2FailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"ASSOCIATION_REJECTION\");\n break;\n case 3:\n sb.append(\"AUTHENTICATION_FAILURE\");\n break;\n case 4:\n sb.append(\"SSID_TEMP_DISABLED\");\n break;\n case 5:\n sb.append(\"CONNECT_NETWORK_FAILED\");\n break;\n case 6:\n sb.append(\"NETWORK_DISCONNECTION\");\n break;\n case 7:\n sb.append(\"NEW_CONNECTION_ATTEMPT\");\n break;\n case 8:\n sb.append(\"REDUNDANT_CONNECTION_ATTEMPT\");\n break;\n case 9:\n sb.append(\"ROAM_TIMEOUT\");\n break;\n case 10:\n sb.append(\"DHCP\");\n break;\n }\n sb.append(\"UNKNOWN\");\n sb.append(\", connectivityLevelFailureCode=\");\n switch(this.mConnectionEvent.connectivityLevelFailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"DHCP\");\n break;\n case 3:\n sb.append(\"NO_INTERNET\");\n break;\n case 4:\n sb.append(\"UNWANTED\");\n break;\n default:\n sb.append(\"UNKNOWN\");\n break;\n }\n sb.append(\", signalStrength=\");\n sb.append(this.mConnectionEvent.signalStrength);\n sb.append(\", wifiState=\");\n switch(this.mWifiState) {\n case 1:\n sb.append(\"WIFI_DISABLED\");\n break;\n case 2:\n sb.append(\"WIFI_DISCONNECTED\");\n break;\n case 3:\n sb.append(\"WIFI_ASSOCIATED\");\n break;\n default:\n sb.append(\"WIFI_UNKNOWN\");\n break;\n }\n sb.append(\", screenOn=\");\n sb.append(this.mScreenOn);\n sb.append(\". mRouterFingerprint: \");\n sb.append(this.mRouterFingerPrint.toString());\n }\n return sb.toString();\n }\n }\n\n class RouterFingerPrint {\n\n private com.android.server.wifi.WifiMetricsProto.RouterFingerPrint mRouterFingerPrintProto = new com.android.server.wifi.WifiMetricsProto.RouterFingerPrint();\n\n RouterFingerPrint() {\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n synchronized (WifiMetrics.this.mLock) {\n sb.append(\"mConnectionEvent.roamType=\").append(this.mRouterFingerPrintProto.roamType);\n sb.append(\", mChannelInfo=\").append(this.mRouterFingerPrintProto.channelInfo);\n sb.append(\", mDtim=\").append(this.mRouterFingerPrintProto.dtim);\n sb.append(\", mAuthentication=\").append(this.mRouterFingerPrintProto.authentication);\n sb.append(\", mHidden=\").append(this.mRouterFingerPrintProto.hidden);\n sb.append(\", mRouterTechnology=\").append(this.mRouterFingerPrintProto.routerTechnology);\n sb.append(\", mSupportsIpv6=\").append(this.mRouterFingerPrintProto.supportsIpv6);\n }\n return sb.toString();\n }\n\n public void updateFromWifiConfiguration(WifiConfiguration config) {\n synchronized (WifiMetrics.this.mLock) {\n if (config != null) {\n this.mRouterFingerPrintProto.hidden = config.hiddenSSID;\n if (config.dtimInterval > 0) {\n this.mRouterFingerPrintProto.dtim = config.dtimInterval;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mConfigSsid = config.SSID;\n if (config.allowedKeyManagement != null && config.allowedKeyManagement.get(0)) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n } else if (config.isEnterprise()) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n } else {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.passpoint = config.isPasspoint();\n ScanResult candidate = config.getNetworkSelectionStatus().getCandidate();\n if (candidate != null) {\n WifiMetrics.this.updateMetricsFromScanResult(candidate);\n }\n }\n }\n }\n }\n\n public WifiMetrics(Clock clock) {\n this.mClock = clock;\n this.mCurrentConnectionEvent = null;\n this.mScreenOn = true;\n this.mWifiState = 1;\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n }\n\n public void startConnectionEvent(WifiConfiguration config, String targetBSSID, int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n if (this.mCurrentConnectionEvent.mConfigSsid == null || this.mCurrentConnectionEvent.mConfigBssid == null || config == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(config.SSID) || !(this.mCurrentConnectionEvent.mConfigBssid.equals(WifiLastResortWatchdog.BSSID_ANY) || this.mCurrentConnectionEvent.mConfigBssid.equals(targetBSSID))) {\n endConnectionEvent(7, 1);\n } else {\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n endConnectionEvent(8, 1);\n }\n }\n while (this.mConnectionEventList.size() >= 256) {\n this.mConnectionEventList.remove(0);\n }\n this.mCurrentConnectionEvent = new ConnectionEvent(this, null);\n this.mCurrentConnectionEvent.mConnectionEvent.startTimeMillis = this.mClock.currentTimeMillis();\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n this.mCurrentConnectionEvent.mRouterFingerPrint.updateFromWifiConfiguration(config);\n this.mCurrentConnectionEvent.mConfigBssid = WifiLastResortWatchdog.BSSID_ANY;\n this.mCurrentConnectionEvent.mRealStartTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mWifiState = this.mWifiState;\n this.mCurrentConnectionEvent.mScreenOn = this.mScreenOn;\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n }\n\n public void setConnectionEventRoamType(int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n }\n }\n }\n\n public void setConnectionScanDetail(ScanDetail scanDetail) {\n synchronized (this.mLock) {\n if (!(this.mCurrentConnectionEvent == null || scanDetail == null)) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n if (!(networkDetail == null || scanResult == null || this.mCurrentConnectionEvent.mConfigSsid == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(\"\\\"\" + networkDetail.getSSID() + \"\\\"\"))) {\n updateMetricsFromNetworkDetail(networkDetail);\n updateMetricsFromScanResult(scanResult);\n }\n }\n }\n }\n\n public void endConnectionEvent(int level2FailureCode, int connectivityFailureCode) {\n int i = 1;\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n boolean result = level2FailureCode == 1 ? connectivityFailureCode == 1 : false;\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent connectionEvent = this.mCurrentConnectionEvent.mConnectionEvent;\n if (!result) {\n i = 0;\n }\n connectionEvent.connectionResult = i;\n this.mCurrentConnectionEvent.mRealEndTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mConnectionEvent.durationTakenToConnectMillis = (int) (this.mCurrentConnectionEvent.mRealEndTime - this.mCurrentConnectionEvent.mRealStartTime);\n this.mCurrentConnectionEvent.mConnectionEvent.level2FailureCode = level2FailureCode;\n this.mCurrentConnectionEvent.mConnectionEvent.connectivityLevelFailureCode = connectivityFailureCode;\n this.mCurrentConnectionEvent = null;\n }\n }\n }\n\n private void updateMetricsFromNetworkDetail(NetworkDetail networkDetail) {\n int connectionWifiMode;\n int dtimInterval = networkDetail.getDtimInterval();\n if (dtimInterval > 0) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.dtim = dtimInterval;\n }\n switch(networkDetail.getWifiMode()) {\n case 0:\n connectionWifiMode = 0;\n break;\n case 1:\n connectionWifiMode = 1;\n break;\n case 2:\n connectionWifiMode = 2;\n break;\n case 3:\n connectionWifiMode = 3;\n break;\n case 4:\n connectionWifiMode = 4;\n break;\n case 5:\n connectionWifiMode = 5;\n break;\n default:\n connectionWifiMode = 6;\n break;\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.routerTechnology = connectionWifiMode;\n }\n\n private void updateMetricsFromScanResult(ScanResult scanResult) {\n this.mCurrentConnectionEvent.mConnectionEvent.signalStrength = scanResult.level;\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n this.mCurrentConnectionEvent.mConfigBssid = scanResult.BSSID;\n if (scanResult.capabilities != null) {\n if (scanResult.capabilities.contains(\"WEP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"PSK\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"EAP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n }\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.channelInfo = scanResult.frequency;\n }\n\n void setNumSavedNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numSavedNetworks = num;\n }\n }\n\n void setNumOpenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numOpenNetworks = num;\n }\n }\n\n void setNumPersonalNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPersonalNetworks = num;\n }\n }\n\n void setNumEnterpriseNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numEnterpriseNetworks = num;\n }\n }\n\n void setNumHiddenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numHiddenNetworks = num;\n }\n }\n\n void setNumPasspointNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPasspointNetworks = num;\n }\n }\n\n void setNumNetworksAddedByUser(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByUser = num;\n }\n }\n\n void setNumNetworksAddedByApps(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByApps = num;\n }\n }\n\n void setIsLocationEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isLocationEnabled = enabled;\n }\n }\n\n void setIsScanningAlwaysEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isScanningAlwaysEnabled = enabled;\n }\n }\n\n public void incrementNonEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numNonEmptyScanResults++;\n }\n }\n\n public void incrementEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numEmptyScanResults++;\n }\n }\n\n public void incrementBackgroundScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numBackgroundScans++;\n }\n }\n\n public int getBackgroundScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numBackgroundScans;\n }\n return i;\n }\n\n public void incrementOneshotScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numOneshotScans++;\n }\n incrementWifiSystemScanStateCount(this.mWifiState, this.mScreenOn);\n }\n\n public int getOneshotScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numOneshotScans;\n }\n return i;\n }\n\n private String returnCodeToString(int scanReturnCode) {\n switch(scanReturnCode) {\n case 0:\n return \"SCAN_UNKNOWN\";\n case 1:\n return \"SCAN_SUCCESS\";\n case 2:\n return \"SCAN_FAILURE_INTERRUPTED\";\n case 3:\n return \"SCAN_FAILURE_INVALID_CONFIGURATION\";\n case 4:\n return \"FAILURE_WIFI_DISABLED\";\n default:\n return \"\";\n }\n }\n\n public void incrementScanReturnEntry(int scanReturnCode, int countToAdd) {\n synchronized (this.mLock) {\n this.mScanReturnEntries.put(scanReturnCode, this.mScanReturnEntries.get(scanReturnCode) + countToAdd);\n }\n }\n\n public int getScanReturnEntry(int scanReturnCode) {\n int i;\n synchronized (this.mLock) {\n i = this.mScanReturnEntries.get(scanReturnCode);\n }\n return i;\n }\n\n private String wifiSystemStateToString(int state) {\n switch(state) {\n case 0:\n return \"WIFI_UNKNOWN\";\n case 1:\n return \"WIFI_DISABLED\";\n case 2:\n return \"WIFI_DISCONNECTED\";\n case 3:\n return \"WIFI_ASSOCIATED\";\n default:\n return \"default\";\n }\n }\n\n public void incrementWifiSystemScanStateCount(int state, boolean screenOn) {\n synchronized (this.mLock) {\n int index = (state * 2) + (screenOn ? 1 : 0);\n this.mWifiSystemStateEntries.put(index, this.mWifiSystemStateEntries.get(index) + 1);\n }\n }\n\n public int getSystemStateCount(int state, boolean screenOn) {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiSystemStateEntries.get((state * 2) + (screenOn ? 1 : 0));\n }\n return i;\n }\n\n public void incrementNumLastResortWatchdogTriggers() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggers++;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAssociationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAssociationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAuthenticationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadDhcpNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadDhcpNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadOtherNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadOtherNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogAvailableNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogAvailableNetworksTotal += count;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAssociation() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAssociation++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAuthentication() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAuthentication++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadDhcp() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadDhcp++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadOther() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadOther++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoBad++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundBad++;\n }\n }\n\n public void incrementRssiPollRssiCount(int rssi) {\n if (rssi >= MIN_RSSI_POLL && rssi <= 0) {\n synchronized (this.mLock) {\n this.mRssiPollCounts.put(rssi, this.mRssiPollCounts.get(rssi) + 1);\n }\n }\n }\n\n public void incrementNumLastResortWatchdogSuccesses() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogSuccesses++;\n }\n }\n\n public void incrementAlertReasonCount(int reason) {\n if (reason > 64 || reason < 0) {\n reason = 0;\n }\n synchronized (this.mLock) {\n this.mWifiAlertReasonCounts.put(reason, this.mWifiAlertReasonCounts.get(reason) + 1);\n }\n }\n\n public void countScanResults(List scanDetails) {\n if (scanDetails != null) {\n int totalResults = 0;\n int openNetworks = 0;\n int personalNetworks = 0;\n int enterpriseNetworks = 0;\n int hiddenNetworks = 0;\n int hotspot2r1Networks = 0;\n int hotspot2r2Networks = 0;\n for (ScanDetail scanDetail : scanDetails) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n totalResults++;\n if (networkDetail != null) {\n if (networkDetail.isHiddenBeaconFrame()) {\n hiddenNetworks++;\n }\n if (networkDetail.getHSRelease() != null) {\n if (networkDetail.getHSRelease() == HSRelease.R1) {\n hotspot2r1Networks++;\n } else if (networkDetail.getHSRelease() == HSRelease.R2) {\n hotspot2r2Networks++;\n }\n }\n }\n ", "post_mask_code": "\n }\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numTotalScanResults += totalResults;\n wifiLog = this.mWifiLogProto;\n wifiLog.numOpenNetworkScanResults += openNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numPersonalNetworkScanResults += personalNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numEnterpriseNetworkScanResults += enterpriseNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHiddenNetworkScanResults += hiddenNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R1NetworkScanResults += hotspot2r1Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R2NetworkScanResults += hotspot2r2Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numScans++;\n }\n }\n }\n\n public void incrementWifiScoreCount(int score) {\n if (score >= 0 && score <= 5) {\n synchronized (this.mLock) {\n this.mWifiScoreCounts.put(score, this.mWifiScoreCounts.get(score) + 1);\n }\n }\n }\n\n public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {\n synchronized (this.mLock) {\n int i;\n if (args != null) {\n if (args.length > 0 && PROTO_DUMP_ARG.equals(args[0])) {\n consolidateProto(true);\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (this.mCurrentConnectionEvent != event) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n String metricsProtoDump = Base64.encodeToString(MessageNano.toByteArray(this.mWifiLogProto), 0);\n if (args.length <= 1 || !CLEAN_DUMP_ARG.equals(args[1])) {\n pw.println(\"WifiMetrics:\");\n pw.println(metricsProtoDump);\n pw.println(\"EndWifiMetrics\");\n } else {\n pw.print(metricsProtoDump);\n }\n clear();\n }\n }\n pw.println(\"WifiMetrics:\");\n pw.println(\"mConnectionEvents:\");\n for (ConnectionEvent event2 : this.mConnectionEventList) {\n String eventLine = event2.toString();\n if (event2 == this.mCurrentConnectionEvent) {\n eventLine = eventLine + \"CURRENTLY OPEN EVENT\";\n }\n pw.println(eventLine);\n }\n pw.println(\"mWifiLogProto.numSavedNetworks=\" + this.mWifiLogProto.numSavedNetworks);\n pw.println(\"mWifiLogProto.numOpenNetworks=\" + this.mWifiLogProto.numOpenNetworks);\n pw.println(\"mWifiLogProto.numPersonalNetworks=\" + this.mWifiLogProto.numPersonalNetworks);\n pw.println(\"mWifiLogProto.numEnterpriseNetworks=\" + this.mWifiLogProto.numEnterpriseNetworks);\n pw.println(\"mWifiLogProto.numHiddenNetworks=\" + this.mWifiLogProto.numHiddenNetworks);\n pw.println(\"mWifiLogProto.numPasspointNetworks=\" + this.mWifiLogProto.numPasspointNetworks);\n pw.println(\"mWifiLogProto.isLocationEnabled=\" + this.mWifiLogProto.isLocationEnabled);\n pw.println(\"mWifiLogProto.isScanningAlwaysEnabled=\" + this.mWifiLogProto.isScanningAlwaysEnabled);\n pw.println(\"mWifiLogProto.numNetworksAddedByUser=\" + this.mWifiLogProto.numNetworksAddedByUser);\n pw.println(\"mWifiLogProto.numNetworksAddedByApps=\" + this.mWifiLogProto.numNetworksAddedByApps);\n pw.println(\"mWifiLogProto.numNonEmptyScanResults=\" + this.mWifiLogProto.numNonEmptyScanResults);\n pw.println(\"mWifiLogProto.numEmptyScanResults=\" + this.mWifiLogProto.numEmptyScanResults);\n pw.println(\"mWifiLogProto.numOneshotScans=\" + this.mWifiLogProto.numOneshotScans);\n pw.println(\"mWifiLogProto.numBackgroundScans=\" + this.mWifiLogProto.numBackgroundScans);\n pw.println(\"mScanReturnEntries:\");\n pw.println(\" SCAN_UNKNOWN: \" + getScanReturnEntry(0));\n pw.println(\" SCAN_SUCCESS: \" + getScanReturnEntry(1));\n pw.println(\" SCAN_FAILURE_INTERRUPTED: \" + getScanReturnEntry(2));\n pw.println(\" SCAN_FAILURE_INVALID_CONFIGURATION: \" + getScanReturnEntry(3));\n pw.println(\" FAILURE_WIFI_DISABLED: \" + getScanReturnEntry(4));\n pw.println(\"mSystemStateEntries: : \");\n pw.println(\" WIFI_UNKNOWN ON: \" + getSystemStateCount(0, true));\n pw.println(\" WIFI_DISABLED ON: \" + getSystemStateCount(1, true));\n pw.println(\" WIFI_DISCONNECTED ON: \" + getSystemStateCount(2, true));\n pw.println(\" WIFI_ASSOCIATED ON: \" + getSystemStateCount(3, true));\n pw.println(\" WIFI_UNKNOWN OFF: \" + getSystemStateCount(0, false));\n pw.println(\" WIFI_DISABLED OFF: \" + getSystemStateCount(1, false));\n pw.println(\" WIFI_DISCONNECTED OFF: \" + getSystemStateCount(2, false));\n pw.println(\" WIFI_ASSOCIATED OFF: \" + getSystemStateCount(3, false));\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoGood=\" + this.mWifiLogProto.numConnectivityWatchdogPnoGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoBad=\" + this.mWifiLogProto.numConnectivityWatchdogPnoBad);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundGood=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundBad=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundBad);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggers=\" + this.mWifiLogProto.numLastResortWatchdogTriggers);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadOther=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadOther);\n pw.println(\"mWifiLogProto.numLastResortWatchdogSuccesses=\" + this.mWifiLogProto.numLastResortWatchdogSuccesses);\n pw.println(\"mWifiLogProto.recordDurationSec=\" + ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec));\n pw.println(\"mWifiLogProto.rssiPollRssiCount: Printing counts for [-127, 0]\");\n StringBuilder sb = new StringBuilder();\n for (i = MIN_RSSI_POLL; i <= 0; i++) {\n sb.append(this.mRssiPollCounts.get(i)).append(\" \");\n }\n pw.println(\" \" + sb.toString());\n pw.print(\"mWifiLogProto.alertReasonCounts=\");\n sb.setLength(0);\n for (i = 0; i <= 64; i++) {\n int count = this.mWifiAlertReasonCounts.get(i);\n if (count > 0) {\n sb.append(\"(\").append(i).append(\",\").append(count).append(\"),\");\n }\n }\n if (sb.length() > 1) {\n sb.setLength(sb.length() - 1);\n pw.println(sb.toString());\n } else {\n pw.println(\"()\");\n }\n pw.println(\"mWifiLogProto.numTotalScanResults=\" + this.mWifiLogProto.numTotalScanResults);\n pw.println(\"mWifiLogProto.numOpenNetworkScanResults=\" + this.mWifiLogProto.numOpenNetworkScanResults);\n pw.println(\"mWifiLogProto.numPersonalNetworkScanResults=\" + this.mWifiLogProto.numPersonalNetworkScanResults);\n pw.println(\"mWifiLogProto.numEnterpriseNetworkScanResults=\" + this.mWifiLogProto.numEnterpriseNetworkScanResults);\n pw.println(\"mWifiLogProto.numHiddenNetworkScanResults=\" + this.mWifiLogProto.numHiddenNetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R1NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R1NetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R2NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R2NetworkScanResults);\n pw.println(\"mWifiLogProto.numScans=\" + this.mWifiLogProto.numScans);\n pw.println(\"mWifiLogProto.WifiScoreCount: [0, 5]\");\n for (i = 0; i <= 5; i++) {\n pw.print(this.mWifiScoreCounts.get(i) + \" \");\n }\n pw.print(\"\\n\");\n }\n }\n\n private void consolidateProto(boolean incremental) {\n List events = new ArrayList();\n List rssis = new ArrayList();\n List alertReasons = new ArrayList();\n List scores = new ArrayList();\n synchronized (this.mLock) {\n int i;\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (!(incremental && (this.mCurrentConnectionEvent == event || event.mConnectionEvent.automaticBugReportTaken))) {\n events.add(event.mConnectionEvent);\n if (incremental) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n }\n if (events.size() > 0) {\n this.mWifiLogProto.connectionEvent = (com.android.server.wifi.WifiMetricsProto.ConnectionEvent[]) events.toArray(this.mWifiLogProto.connectionEvent);\n }\n this.mWifiLogProto.scanReturnEntries = new ScanReturnEntry[this.mScanReturnEntries.size()];\n for (i = 0; i < this.mScanReturnEntries.size(); i++) {\n this.mWifiLogProto.scanReturnEntries[i] = new ScanReturnEntry();\n this.mWifiLogProto.scanReturnEntries[i].scanReturnCode = this.mScanReturnEntries.keyAt(i);\n this.mWifiLogProto.scanReturnEntries[i].scanResultsCount = this.mScanReturnEntries.valueAt(i);\n }\n this.mWifiLogProto.wifiSystemStateEntries = new WifiSystemStateEntry[this.mWifiSystemStateEntries.size()];\n for (i = 0; i < this.mWifiSystemStateEntries.size(); i++) {\n this.mWifiLogProto.wifiSystemStateEntries[i] = new WifiSystemStateEntry();\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiState = this.mWifiSystemStateEntries.keyAt(i) / 2;\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiStateCount = this.mWifiSystemStateEntries.valueAt(i);\n this.mWifiLogProto.wifiSystemStateEntries[i].isScreenOn = this.mWifiSystemStateEntries.keyAt(i) % 2 > 0;\n }\n this.mWifiLogProto.recordDurationSec = (int) ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec);\n for (i = 0; i < this.mRssiPollCounts.size(); i++) {\n RssiPollCount keyVal = new RssiPollCount();\n keyVal.rssi = this.mRssiPollCounts.keyAt(i);\n keyVal.count = this.mRssiPollCounts.valueAt(i);\n rssis.add(keyVal);\n }\n this.mWifiLogProto.rssiPollRssiCount = (RssiPollCount[]) rssis.toArray(this.mWifiLogProto.rssiPollRssiCount);\n for (i = 0; i < this.mWifiAlertReasonCounts.size(); i++) {\n AlertReasonCount keyVal2 = new AlertReasonCount();\n keyVal2.reason = this.mWifiAlertReasonCounts.keyAt(i);\n keyVal2.count = this.mWifiAlertReasonCounts.valueAt(i);\n alertReasons.add(keyVal2);\n }\n this.mWifiLogProto.alertReasonCount = (AlertReasonCount[]) alertReasons.toArray(this.mWifiLogProto.alertReasonCount);\n for (int score = 0; score < this.mWifiScoreCounts.size(); score++) {\n WifiScoreCount keyVal3 = new WifiScoreCount();\n keyVal3.score = this.mWifiScoreCounts.keyAt(score);\n keyVal3.count = this.mWifiScoreCounts.valueAt(score);\n scores.add(keyVal3);\n }\n this.mWifiLogProto.wifiScoreCount = (WifiScoreCount[]) scores.toArray(this.mWifiLogProto.wifiScoreCount);\n }\n }\n\n private void clear() {\n synchronized (this.mLock) {\n this.mConnectionEventList.clear();\n if (this.mCurrentConnectionEvent != null) {\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n this.mScanReturnEntries.clear();\n this.mWifiSystemStateEntries.clear();\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n this.mRssiPollCounts.clear();\n this.mWifiAlertReasonCounts.clear();\n this.mWifiScoreCounts.clear();\n this.mWifiLogProto.clear();\n }\n }\n\n public void setScreenState(boolean screenOn) {\n synchronized (this.mLock) {\n this.mScreenOn = screenOn;\n }\n }\n\n public void setWifiState(int wifiState) {\n synchronized (this.mLock) {\n this.mWifiState = wifiState;\n }\n }\n}\n"} {"task_id": "Java_694", "language": "Java", "task_type": "switch_case", "source_file": "java/github/dstmath/OppoFramework/A1_7_1_1/src/main/java/com/android/server/wifi/WifiMetrics.java", "mask_start_position": 20461, "mask_end_position": 20890, "canonical_solution": "switch(scanReturnCode) {\n case 0:\n return \"SCAN_UNKNOWN\";\n case 1:\n return \"SCAN_SUCCESS\";\n case 2:\n return \"SCAN_FAILURE_INTERRUPTED\";\n case 3:\n return \"SCAN_FAILURE_INVALID_CONFIGURATION\";\n case 4:\n return \"FAILURE_WIFI_DISABLED\";\n default:\n return \"\";\n }", "pre_mask_code": "package com.android.server.wifi;\n\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiConfiguration;\nimport android.util.Base64;\nimport android.util.SparseIntArray;\nimport com.android.server.wifi.WifiMetricsProto.AlertReasonCount;\nimport com.android.server.wifi.WifiMetricsProto.RssiPollCount;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.ScanReturnEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.WifiSystemStateEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiScoreCount;\nimport com.android.server.wifi.hotspot2.NetworkDetail;\nimport com.android.server.wifi.hotspot2.NetworkDetail.HSRelease;\nimport com.google.protobuf.nano.MessageNano;\nimport java.io.FileDescriptor;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.List;\n\npublic class WifiMetrics {\n\n public static final String CLEAN_DUMP_ARG = \"clean\";\n\n private static final boolean DBG = false;\n\n private static final int MAX_CONNECTION_EVENTS = 256;\n\n private static final int MAX_RSSI_POLL = 0;\n\n private static final int MAX_WIFI_SCORE = 5;\n\n private static final int MIN_RSSI_POLL = -127;\n\n private static final int MIN_WIFI_SCORE = 0;\n\n public static final String PROTO_DUMP_ARG = \"wifiMetricsProto\";\n\n private static final int SCREEN_OFF = 0;\n\n private static final int SCREEN_ON = 1;\n\n private static final String TAG = \"WifiMetrics\";\n\n private Clock mClock;\n\n private final List mConnectionEventList = new ArrayList();\n\n private ConnectionEvent mCurrentConnectionEvent;\n\n private final Object mLock = new Object();\n\n private long mRecordStartTimeSec;\n\n private final SparseIntArray mRssiPollCounts = new SparseIntArray();\n\n private final SparseIntArray mScanReturnEntries = new SparseIntArray();\n\n private boolean mScreenOn;\n\n private final SparseIntArray mWifiAlertReasonCounts = new SparseIntArray();\n\n private final WifiLog mWifiLogProto = new WifiLog();\n\n private final SparseIntArray mWifiScoreCounts = new SparseIntArray();\n\n private int mWifiState;\n\n private final SparseIntArray mWifiSystemStateEntries = new SparseIntArray();\n\n class ConnectionEvent {\n\n public static final int FAILURE_ASSOCIATION_REJECTION = 2;\n\n public static final int FAILURE_AUTHENTICATION_FAILURE = 3;\n\n public static final int FAILURE_CONNECT_NETWORK_FAILED = 5;\n\n public static final int FAILURE_DHCP = 10;\n\n public static final int FAILURE_NETWORK_DISCONNECTION = 6;\n\n public static final int FAILURE_NEW_CONNECTION_ATTEMPT = 7;\n\n public static final int FAILURE_NONE = 1;\n\n public static final int FAILURE_REDUNDANT_CONNECTION_ATTEMPT = 8;\n\n public static final int FAILURE_ROAM_TIMEOUT = 9;\n\n public static final int FAILURE_SSID_TEMP_DISABLED = 4;\n\n public static final int FAILURE_UNKNOWN = 0;\n\n private String mConfigBssid;\n\n private String mConfigSsid;\n\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent mConnectionEvent;\n\n private long mRealEndTime;\n\n private long mRealStartTime;\n\n RouterFingerPrint mRouterFingerPrint;\n\n private boolean mScreenOn;\n\n private int mWifiState;\n\n /* synthetic */\n ConnectionEvent(WifiMetrics this$0, ConnectionEvent connectionEvent) {\n this();\n }\n\n private ConnectionEvent() {\n this.mConnectionEvent = new com.android.server.wifi.WifiMetricsProto.ConnectionEvent();\n this.mRealEndTime = 0;\n this.mRealStartTime = 0;\n this.mRouterFingerPrint = new RouterFingerPrint();\n this.mConnectionEvent.routerFingerprint = this.mRouterFingerPrint.mRouterFingerPrintProto;\n this.mConfigSsid = \"\";\n this.mConfigBssid = \"\";\n this.mWifiState = 0;\n this.mScreenOn = false;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"startTime=\");\n Calendar c = Calendar.getInstance();\n synchronized (WifiMetrics.this.mLock) {\n String str;\n c.setTimeInMillis(this.mConnectionEvent.startTimeMillis);\n if (this.mConnectionEvent.startTimeMillis == 0) {\n str = \" \";\n } else {\n str = String.format(\"%tm-%td %tH:%tM:%tS.%tL\", new Object[] { c, c, c, c, c, c });\n }\n sb.append(str);\n sb.append(\", SSID=\");\n sb.append(this.mConfigSsid);\n sb.append(\", BSSID=\");\n sb.append(this.mConfigBssid);\n sb.append(\", durationMillis=\");\n sb.append(this.mConnectionEvent.durationTakenToConnectMillis);\n sb.append(\", roamType=\");\n switch(this.mConnectionEvent.roamType) {\n case 1:\n sb.append(\"ROAM_NONE\");\n break;\n case 2:\n sb.append(\"ROAM_DBDC\");\n break;\n case 3:\n sb.append(\"ROAM_ENTERPRISE\");\n break;\n case 4:\n sb.append(\"ROAM_USER_SELECTED\");\n break;\n case 5:\n sb.append(\"ROAM_UNRELATED\");\n break;\n default:\n sb.append(\"ROAM_UNKNOWN\");\n break;\n }\n sb.append(\", connectionResult=\");\n sb.append(this.mConnectionEvent.connectionResult);\n sb.append(\", level2FailureCode=\");\n switch(this.mConnectionEvent.level2FailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"ASSOCIATION_REJECTION\");\n break;\n case 3:\n sb.append(\"AUTHENTICATION_FAILURE\");\n break;\n case 4:\n sb.append(\"SSID_TEMP_DISABLED\");\n break;\n case 5:\n sb.append(\"CONNECT_NETWORK_FAILED\");\n break;\n case 6:\n sb.append(\"NETWORK_DISCONNECTION\");\n break;\n case 7:\n sb.append(\"NEW_CONNECTION_ATTEMPT\");\n break;\n case 8:\n sb.append(\"REDUNDANT_CONNECTION_ATTEMPT\");\n break;\n case 9:\n sb.append(\"ROAM_TIMEOUT\");\n break;\n case 10:\n sb.append(\"DHCP\");\n break;\n }\n sb.append(\"UNKNOWN\");\n sb.append(\", connectivityLevelFailureCode=\");\n switch(this.mConnectionEvent.connectivityLevelFailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"DHCP\");\n break;\n case 3:\n sb.append(\"NO_INTERNET\");\n break;\n case 4:\n sb.append(\"UNWANTED\");\n break;\n default:\n sb.append(\"UNKNOWN\");\n break;\n }\n sb.append(\", signalStrength=\");\n sb.append(this.mConnectionEvent.signalStrength);\n sb.append(\", wifiState=\");\n switch(this.mWifiState) {\n case 1:\n sb.append(\"WIFI_DISABLED\");\n break;\n case 2:\n sb.append(\"WIFI_DISCONNECTED\");\n break;\n case 3:\n sb.append(\"WIFI_ASSOCIATED\");\n break;\n default:\n sb.append(\"WIFI_UNKNOWN\");\n break;\n }\n sb.append(\", screenOn=\");\n sb.append(this.mScreenOn);\n sb.append(\". mRouterFingerprint: \");\n sb.append(this.mRouterFingerPrint.toString());\n }\n return sb.toString();\n }\n }\n\n class RouterFingerPrint {\n\n private com.android.server.wifi.WifiMetricsProto.RouterFingerPrint mRouterFingerPrintProto = new com.android.server.wifi.WifiMetricsProto.RouterFingerPrint();\n\n RouterFingerPrint() {\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n synchronized (WifiMetrics.this.mLock) {\n sb.append(\"mConnectionEvent.roamType=\").append(this.mRouterFingerPrintProto.roamType);\n sb.append(\", mChannelInfo=\").append(this.mRouterFingerPrintProto.channelInfo);\n sb.append(\", mDtim=\").append(this.mRouterFingerPrintProto.dtim);\n sb.append(\", mAuthentication=\").append(this.mRouterFingerPrintProto.authentication);\n sb.append(\", mHidden=\").append(this.mRouterFingerPrintProto.hidden);\n sb.append(\", mRouterTechnology=\").append(this.mRouterFingerPrintProto.routerTechnology);\n sb.append(\", mSupportsIpv6=\").append(this.mRouterFingerPrintProto.supportsIpv6);\n }\n return sb.toString();\n }\n\n public void updateFromWifiConfiguration(WifiConfiguration config) {\n synchronized (WifiMetrics.this.mLock) {\n if (config != null) {\n this.mRouterFingerPrintProto.hidden = config.hiddenSSID;\n if (config.dtimInterval > 0) {\n this.mRouterFingerPrintProto.dtim = config.dtimInterval;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mConfigSsid = config.SSID;\n if (config.allowedKeyManagement != null && config.allowedKeyManagement.get(0)) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n } else if (config.isEnterprise()) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n } else {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.passpoint = config.isPasspoint();\n ScanResult candidate = config.getNetworkSelectionStatus().getCandidate();\n if (candidate != null) {\n WifiMetrics.this.updateMetricsFromScanResult(candidate);\n }\n }\n }\n }\n }\n\n public WifiMetrics(Clock clock) {\n this.mClock = clock;\n this.mCurrentConnectionEvent = null;\n this.mScreenOn = true;\n this.mWifiState = 1;\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n }\n\n public void startConnectionEvent(WifiConfiguration config, String targetBSSID, int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n if (this.mCurrentConnectionEvent.mConfigSsid == null || this.mCurrentConnectionEvent.mConfigBssid == null || config == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(config.SSID) || !(this.mCurrentConnectionEvent.mConfigBssid.equals(WifiLastResortWatchdog.BSSID_ANY) || this.mCurrentConnectionEvent.mConfigBssid.equals(targetBSSID))) {\n endConnectionEvent(7, 1);\n } else {\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n endConnectionEvent(8, 1);\n }\n }\n while (this.mConnectionEventList.size() >= 256) {\n this.mConnectionEventList.remove(0);\n }\n this.mCurrentConnectionEvent = new ConnectionEvent(this, null);\n this.mCurrentConnectionEvent.mConnectionEvent.startTimeMillis = this.mClock.currentTimeMillis();\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n this.mCurrentConnectionEvent.mRouterFingerPrint.updateFromWifiConfiguration(config);\n this.mCurrentConnectionEvent.mConfigBssid = WifiLastResortWatchdog.BSSID_ANY;\n this.mCurrentConnectionEvent.mRealStartTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mWifiState = this.mWifiState;\n this.mCurrentConnectionEvent.mScreenOn = this.mScreenOn;\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n }\n\n public void setConnectionEventRoamType(int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n }\n }\n }\n\n public void setConnectionScanDetail(ScanDetail scanDetail) {\n synchronized (this.mLock) {\n if (!(this.mCurrentConnectionEvent == null || scanDetail == null)) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n if (!(networkDetail == null || scanResult == null || this.mCurrentConnectionEvent.mConfigSsid == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(\"\\\"\" + networkDetail.getSSID() + \"\\\"\"))) {\n updateMetricsFromNetworkDetail(networkDetail);\n updateMetricsFromScanResult(scanResult);\n }\n }\n }\n }\n\n public void endConnectionEvent(int level2FailureCode, int connectivityFailureCode) {\n int i = 1;\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n boolean result = level2FailureCode == 1 ? connectivityFailureCode == 1 : false;\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent connectionEvent = this.mCurrentConnectionEvent.mConnectionEvent;\n if (!result) {\n i = 0;\n }\n connectionEvent.connectionResult = i;\n this.mCurrentConnectionEvent.mRealEndTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mConnectionEvent.durationTakenToConnectMillis = (int) (this.mCurrentConnectionEvent.mRealEndTime - this.mCurrentConnectionEvent.mRealStartTime);\n this.mCurrentConnectionEvent.mConnectionEvent.level2FailureCode = level2FailureCode;\n this.mCurrentConnectionEvent.mConnectionEvent.connectivityLevelFailureCode = connectivityFailureCode;\n this.mCurrentConnectionEvent = null;\n }\n }\n }\n\n private void updateMetricsFromNetworkDetail(NetworkDetail networkDetail) {\n int connectionWifiMode;\n int dtimInterval = networkDetail.getDtimInterval();\n if (dtimInterval > 0) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.dtim = dtimInterval;\n }\n switch(networkDetail.getWifiMode()) {\n case 0:\n connectionWifiMode = 0;\n break;\n case 1:\n connectionWifiMode = 1;\n break;\n case 2:\n connectionWifiMode = 2;\n break;\n case 3:\n connectionWifiMode = 3;\n break;\n case 4:\n connectionWifiMode = 4;\n break;\n case 5:\n connectionWifiMode = 5;\n break;\n default:\n connectionWifiMode = 6;\n break;\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.routerTechnology = connectionWifiMode;\n }\n\n private void updateMetricsFromScanResult(ScanResult scanResult) {\n this.mCurrentConnectionEvent.mConnectionEvent.signalStrength = scanResult.level;\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n this.mCurrentConnectionEvent.mConfigBssid = scanResult.BSSID;\n if (scanResult.capabilities != null) {\n if (scanResult.capabilities.contains(\"WEP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"PSK\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"EAP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n }\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.channelInfo = scanResult.frequency;\n }\n\n void setNumSavedNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numSavedNetworks = num;\n }\n }\n\n void setNumOpenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numOpenNetworks = num;\n }\n }\n\n void setNumPersonalNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPersonalNetworks = num;\n }\n }\n\n void setNumEnterpriseNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numEnterpriseNetworks = num;\n }\n }\n\n void setNumHiddenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numHiddenNetworks = num;\n }\n }\n\n void setNumPasspointNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPasspointNetworks = num;\n }\n }\n\n void setNumNetworksAddedByUser(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByUser = num;\n }\n }\n\n void setNumNetworksAddedByApps(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByApps = num;\n }\n }\n\n void setIsLocationEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isLocationEnabled = enabled;\n }\n }\n\n void setIsScanningAlwaysEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isScanningAlwaysEnabled = enabled;\n }\n }\n\n public void incrementNonEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numNonEmptyScanResults++;\n }\n }\n\n public void incrementEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numEmptyScanResults++;\n }\n }\n\n public void incrementBackgroundScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numBackgroundScans++;\n }\n }\n\n public int getBackgroundScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numBackgroundScans;\n }\n return i;\n }\n\n public void incrementOneshotScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numOneshotScans++;\n }\n incrementWifiSystemScanStateCount(this.mWifiState, this.mScreenOn);\n }\n\n public int getOneshotScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numOneshotScans;\n }\n return i;\n }\n\n private String returnCodeToString(int scanReturnCode) {\n ", "post_mask_code": "\n }\n\n public void incrementScanReturnEntry(int scanReturnCode, int countToAdd) {\n synchronized (this.mLock) {\n this.mScanReturnEntries.put(scanReturnCode, this.mScanReturnEntries.get(scanReturnCode) + countToAdd);\n }\n }\n\n public int getScanReturnEntry(int scanReturnCode) {\n int i;\n synchronized (this.mLock) {\n i = this.mScanReturnEntries.get(scanReturnCode);\n }\n return i;\n }\n\n private String wifiSystemStateToString(int state) {\n switch(state) {\n case 0:\n return \"WIFI_UNKNOWN\";\n case 1:\n return \"WIFI_DISABLED\";\n case 2:\n return \"WIFI_DISCONNECTED\";\n case 3:\n return \"WIFI_ASSOCIATED\";\n default:\n return \"default\";\n }\n }\n\n public void incrementWifiSystemScanStateCount(int state, boolean screenOn) {\n synchronized (this.mLock) {\n int index = (state * 2) + (screenOn ? 1 : 0);\n this.mWifiSystemStateEntries.put(index, this.mWifiSystemStateEntries.get(index) + 1);\n }\n }\n\n public int getSystemStateCount(int state, boolean screenOn) {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiSystemStateEntries.get((state * 2) + (screenOn ? 1 : 0));\n }\n return i;\n }\n\n public void incrementNumLastResortWatchdogTriggers() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggers++;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAssociationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAssociationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAuthenticationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadDhcpNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadDhcpNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadOtherNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadOtherNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogAvailableNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogAvailableNetworksTotal += count;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAssociation() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAssociation++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAuthentication() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAuthentication++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadDhcp() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadDhcp++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadOther() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadOther++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoBad++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundBad++;\n }\n }\n\n public void incrementRssiPollRssiCount(int rssi) {\n if (rssi >= MIN_RSSI_POLL && rssi <= 0) {\n synchronized (this.mLock) {\n this.mRssiPollCounts.put(rssi, this.mRssiPollCounts.get(rssi) + 1);\n }\n }\n }\n\n public void incrementNumLastResortWatchdogSuccesses() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogSuccesses++;\n }\n }\n\n public void incrementAlertReasonCount(int reason) {\n if (reason > 64 || reason < 0) {\n reason = 0;\n }\n synchronized (this.mLock) {\n this.mWifiAlertReasonCounts.put(reason, this.mWifiAlertReasonCounts.get(reason) + 1);\n }\n }\n\n public void countScanResults(List scanDetails) {\n if (scanDetails != null) {\n int totalResults = 0;\n int openNetworks = 0;\n int personalNetworks = 0;\n int enterpriseNetworks = 0;\n int hiddenNetworks = 0;\n int hotspot2r1Networks = 0;\n int hotspot2r2Networks = 0;\n for (ScanDetail scanDetail : scanDetails) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n totalResults++;\n if (networkDetail != null) {\n if (networkDetail.isHiddenBeaconFrame()) {\n hiddenNetworks++;\n }\n if (networkDetail.getHSRelease() != null) {\n if (networkDetail.getHSRelease() == HSRelease.R1) {\n hotspot2r1Networks++;\n } else if (networkDetail.getHSRelease() == HSRelease.R2) {\n hotspot2r2Networks++;\n }\n }\n }\n if (!(scanResult == null || scanResult.capabilities == null)) {\n if (scanResult.capabilities.contains(\"EAP\")) {\n enterpriseNetworks++;\n } else if (scanResult.capabilities.contains(\"PSK\") || scanResult.capabilities.contains(\"WEP\")) {\n personalNetworks++;\n } else {\n openNetworks++;\n }\n }\n }\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numTotalScanResults += totalResults;\n wifiLog = this.mWifiLogProto;\n wifiLog.numOpenNetworkScanResults += openNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numPersonalNetworkScanResults += personalNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numEnterpriseNetworkScanResults += enterpriseNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHiddenNetworkScanResults += hiddenNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R1NetworkScanResults += hotspot2r1Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R2NetworkScanResults += hotspot2r2Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numScans++;\n }\n }\n }\n\n public void incrementWifiScoreCount(int score) {\n if (score >= 0 && score <= 5) {\n synchronized (this.mLock) {\n this.mWifiScoreCounts.put(score, this.mWifiScoreCounts.get(score) + 1);\n }\n }\n }\n\n public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {\n synchronized (this.mLock) {\n int i;\n if (args != null) {\n if (args.length > 0 && PROTO_DUMP_ARG.equals(args[0])) {\n consolidateProto(true);\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (this.mCurrentConnectionEvent != event) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n String metricsProtoDump = Base64.encodeToString(MessageNano.toByteArray(this.mWifiLogProto), 0);\n if (args.length <= 1 || !CLEAN_DUMP_ARG.equals(args[1])) {\n pw.println(\"WifiMetrics:\");\n pw.println(metricsProtoDump);\n pw.println(\"EndWifiMetrics\");\n } else {\n pw.print(metricsProtoDump);\n }\n clear();\n }\n }\n pw.println(\"WifiMetrics:\");\n pw.println(\"mConnectionEvents:\");\n for (ConnectionEvent event2 : this.mConnectionEventList) {\n String eventLine = event2.toString();\n if (event2 == this.mCurrentConnectionEvent) {\n eventLine = eventLine + \"CURRENTLY OPEN EVENT\";\n }\n pw.println(eventLine);\n }\n pw.println(\"mWifiLogProto.numSavedNetworks=\" + this.mWifiLogProto.numSavedNetworks);\n pw.println(\"mWifiLogProto.numOpenNetworks=\" + this.mWifiLogProto.numOpenNetworks);\n pw.println(\"mWifiLogProto.numPersonalNetworks=\" + this.mWifiLogProto.numPersonalNetworks);\n pw.println(\"mWifiLogProto.numEnterpriseNetworks=\" + this.mWifiLogProto.numEnterpriseNetworks);\n pw.println(\"mWifiLogProto.numHiddenNetworks=\" + this.mWifiLogProto.numHiddenNetworks);\n pw.println(\"mWifiLogProto.numPasspointNetworks=\" + this.mWifiLogProto.numPasspointNetworks);\n pw.println(\"mWifiLogProto.isLocationEnabled=\" + this.mWifiLogProto.isLocationEnabled);\n pw.println(\"mWifiLogProto.isScanningAlwaysEnabled=\" + this.mWifiLogProto.isScanningAlwaysEnabled);\n pw.println(\"mWifiLogProto.numNetworksAddedByUser=\" + this.mWifiLogProto.numNetworksAddedByUser);\n pw.println(\"mWifiLogProto.numNetworksAddedByApps=\" + this.mWifiLogProto.numNetworksAddedByApps);\n pw.println(\"mWifiLogProto.numNonEmptyScanResults=\" + this.mWifiLogProto.numNonEmptyScanResults);\n pw.println(\"mWifiLogProto.numEmptyScanResults=\" + this.mWifiLogProto.numEmptyScanResults);\n pw.println(\"mWifiLogProto.numOneshotScans=\" + this.mWifiLogProto.numOneshotScans);\n pw.println(\"mWifiLogProto.numBackgroundScans=\" + this.mWifiLogProto.numBackgroundScans);\n pw.println(\"mScanReturnEntries:\");\n pw.println(\" SCAN_UNKNOWN: \" + getScanReturnEntry(0));\n pw.println(\" SCAN_SUCCESS: \" + getScanReturnEntry(1));\n pw.println(\" SCAN_FAILURE_INTERRUPTED: \" + getScanReturnEntry(2));\n pw.println(\" SCAN_FAILURE_INVALID_CONFIGURATION: \" + getScanReturnEntry(3));\n pw.println(\" FAILURE_WIFI_DISABLED: \" + getScanReturnEntry(4));\n pw.println(\"mSystemStateEntries: : \");\n pw.println(\" WIFI_UNKNOWN ON: \" + getSystemStateCount(0, true));\n pw.println(\" WIFI_DISABLED ON: \" + getSystemStateCount(1, true));\n pw.println(\" WIFI_DISCONNECTED ON: \" + getSystemStateCount(2, true));\n pw.println(\" WIFI_ASSOCIATED ON: \" + getSystemStateCount(3, true));\n pw.println(\" WIFI_UNKNOWN OFF: \" + getSystemStateCount(0, false));\n pw.println(\" WIFI_DISABLED OFF: \" + getSystemStateCount(1, false));\n pw.println(\" WIFI_DISCONNECTED OFF: \" + getSystemStateCount(2, false));\n pw.println(\" WIFI_ASSOCIATED OFF: \" + getSystemStateCount(3, false));\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoGood=\" + this.mWifiLogProto.numConnectivityWatchdogPnoGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoBad=\" + this.mWifiLogProto.numConnectivityWatchdogPnoBad);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundGood=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundBad=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundBad);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggers=\" + this.mWifiLogProto.numLastResortWatchdogTriggers);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadOther=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadOther);\n pw.println(\"mWifiLogProto.numLastResortWatchdogSuccesses=\" + this.mWifiLogProto.numLastResortWatchdogSuccesses);\n pw.println(\"mWifiLogProto.recordDurationSec=\" + ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec));\n pw.println(\"mWifiLogProto.rssiPollRssiCount: Printing counts for [-127, 0]\");\n StringBuilder sb = new StringBuilder();\n for (i = MIN_RSSI_POLL; i <= 0; i++) {\n sb.append(this.mRssiPollCounts.get(i)).append(\" \");\n }\n pw.println(\" \" + sb.toString());\n pw.print(\"mWifiLogProto.alertReasonCounts=\");\n sb.setLength(0);\n for (i = 0; i <= 64; i++) {\n int count = this.mWifiAlertReasonCounts.get(i);\n if (count > 0) {\n sb.append(\"(\").append(i).append(\",\").append(count).append(\"),\");\n }\n }\n if (sb.length() > 1) {\n sb.setLength(sb.length() - 1);\n pw.println(sb.toString());\n } else {\n pw.println(\"()\");\n }\n pw.println(\"mWifiLogProto.numTotalScanResults=\" + this.mWifiLogProto.numTotalScanResults);\n pw.println(\"mWifiLogProto.numOpenNetworkScanResults=\" + this.mWifiLogProto.numOpenNetworkScanResults);\n pw.println(\"mWifiLogProto.numPersonalNetworkScanResults=\" + this.mWifiLogProto.numPersonalNetworkScanResults);\n pw.println(\"mWifiLogProto.numEnterpriseNetworkScanResults=\" + this.mWifiLogProto.numEnterpriseNetworkScanResults);\n pw.println(\"mWifiLogProto.numHiddenNetworkScanResults=\" + this.mWifiLogProto.numHiddenNetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R1NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R1NetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R2NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R2NetworkScanResults);\n pw.println(\"mWifiLogProto.numScans=\" + this.mWifiLogProto.numScans);\n pw.println(\"mWifiLogProto.WifiScoreCount: [0, 5]\");\n for (i = 0; i <= 5; i++) {\n pw.print(this.mWifiScoreCounts.get(i) + \" \");\n }\n pw.print(\"\\n\");\n }\n }\n\n private void consolidateProto(boolean incremental) {\n List events = new ArrayList();\n List rssis = new ArrayList();\n List alertReasons = new ArrayList();\n List scores = new ArrayList();\n synchronized (this.mLock) {\n int i;\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (!(incremental && (this.mCurrentConnectionEvent == event || event.mConnectionEvent.automaticBugReportTaken))) {\n events.add(event.mConnectionEvent);\n if (incremental) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n }\n if (events.size() > 0) {\n this.mWifiLogProto.connectionEvent = (com.android.server.wifi.WifiMetricsProto.ConnectionEvent[]) events.toArray(this.mWifiLogProto.connectionEvent);\n }\n this.mWifiLogProto.scanReturnEntries = new ScanReturnEntry[this.mScanReturnEntries.size()];\n for (i = 0; i < this.mScanReturnEntries.size(); i++) {\n this.mWifiLogProto.scanReturnEntries[i] = new ScanReturnEntry();\n this.mWifiLogProto.scanReturnEntries[i].scanReturnCode = this.mScanReturnEntries.keyAt(i);\n this.mWifiLogProto.scanReturnEntries[i].scanResultsCount = this.mScanReturnEntries.valueAt(i);\n }\n this.mWifiLogProto.wifiSystemStateEntries = new WifiSystemStateEntry[this.mWifiSystemStateEntries.size()];\n for (i = 0; i < this.mWifiSystemStateEntries.size(); i++) {\n this.mWifiLogProto.wifiSystemStateEntries[i] = new WifiSystemStateEntry();\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiState = this.mWifiSystemStateEntries.keyAt(i) / 2;\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiStateCount = this.mWifiSystemStateEntries.valueAt(i);\n this.mWifiLogProto.wifiSystemStateEntries[i].isScreenOn = this.mWifiSystemStateEntries.keyAt(i) % 2 > 0;\n }\n this.mWifiLogProto.recordDurationSec = (int) ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec);\n for (i = 0; i < this.mRssiPollCounts.size(); i++) {\n RssiPollCount keyVal = new RssiPollCount();\n keyVal.rssi = this.mRssiPollCounts.keyAt(i);\n keyVal.count = this.mRssiPollCounts.valueAt(i);\n rssis.add(keyVal);\n }\n this.mWifiLogProto.rssiPollRssiCount = (RssiPollCount[]) rssis.toArray(this.mWifiLogProto.rssiPollRssiCount);\n for (i = 0; i < this.mWifiAlertReasonCounts.size(); i++) {\n AlertReasonCount keyVal2 = new AlertReasonCount();\n keyVal2.reason = this.mWifiAlertReasonCounts.keyAt(i);\n keyVal2.count = this.mWifiAlertReasonCounts.valueAt(i);\n alertReasons.add(keyVal2);\n }\n this.mWifiLogProto.alertReasonCount = (AlertReasonCount[]) alertReasons.toArray(this.mWifiLogProto.alertReasonCount);\n for (int score = 0; score < this.mWifiScoreCounts.size(); score++) {\n WifiScoreCount keyVal3 = new WifiScoreCount();\n keyVal3.score = this.mWifiScoreCounts.keyAt(score);\n keyVal3.count = this.mWifiScoreCounts.valueAt(score);\n scores.add(keyVal3);\n }\n this.mWifiLogProto.wifiScoreCount = (WifiScoreCount[]) scores.toArray(this.mWifiLogProto.wifiScoreCount);\n }\n }\n\n private void clear() {\n synchronized (this.mLock) {\n this.mConnectionEventList.clear();\n if (this.mCurrentConnectionEvent != null) {\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n this.mScanReturnEntries.clear();\n this.mWifiSystemStateEntries.clear();\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n this.mRssiPollCounts.clear();\n this.mWifiAlertReasonCounts.clear();\n this.mWifiScoreCounts.clear();\n this.mWifiLogProto.clear();\n }\n }\n\n public void setScreenState(boolean screenOn) {\n synchronized (this.mLock) {\n this.mScreenOn = screenOn;\n }\n }\n\n public void setWifiState(int wifiState) {\n synchronized (this.mLock) {\n this.mWifiState = wifiState;\n }\n }\n}\n"} {"task_id": "Java_695", "language": "Java", "task_type": "for_statement", "source_file": "java/github/dstmath/OppoFramework/A1_7_1_1/src/main/java/com/android/server/wifi/WifiMetrics.java", "mask_start_position": 35887, "mask_end_position": 36007, "canonical_solution": "for (i = MIN_RSSI_POLL; i <= 0; i++) {\n sb.append(this.mRssiPollCounts.get(i)).append(\" \");\n }", "pre_mask_code": "package com.android.server.wifi;\n\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiConfiguration;\nimport android.util.Base64;\nimport android.util.SparseIntArray;\nimport com.android.server.wifi.WifiMetricsProto.AlertReasonCount;\nimport com.android.server.wifi.WifiMetricsProto.RssiPollCount;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.ScanReturnEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.WifiSystemStateEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiScoreCount;\nimport com.android.server.wifi.hotspot2.NetworkDetail;\nimport com.android.server.wifi.hotspot2.NetworkDetail.HSRelease;\nimport com.google.protobuf.nano.MessageNano;\nimport java.io.FileDescriptor;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.List;\n\npublic class WifiMetrics {\n\n public static final String CLEAN_DUMP_ARG = \"clean\";\n\n private static final boolean DBG = false;\n\n private static final int MAX_CONNECTION_EVENTS = 256;\n\n private static final int MAX_RSSI_POLL = 0;\n\n private static final int MAX_WIFI_SCORE = 5;\n\n private static final int MIN_RSSI_POLL = -127;\n\n private static final int MIN_WIFI_SCORE = 0;\n\n public static final String PROTO_DUMP_ARG = \"wifiMetricsProto\";\n\n private static final int SCREEN_OFF = 0;\n\n private static final int SCREEN_ON = 1;\n\n private static final String TAG = \"WifiMetrics\";\n\n private Clock mClock;\n\n private final List mConnectionEventList = new ArrayList();\n\n private ConnectionEvent mCurrentConnectionEvent;\n\n private final Object mLock = new Object();\n\n private long mRecordStartTimeSec;\n\n private final SparseIntArray mRssiPollCounts = new SparseIntArray();\n\n private final SparseIntArray mScanReturnEntries = new SparseIntArray();\n\n private boolean mScreenOn;\n\n private final SparseIntArray mWifiAlertReasonCounts = new SparseIntArray();\n\n private final WifiLog mWifiLogProto = new WifiLog();\n\n private final SparseIntArray mWifiScoreCounts = new SparseIntArray();\n\n private int mWifiState;\n\n private final SparseIntArray mWifiSystemStateEntries = new SparseIntArray();\n\n class ConnectionEvent {\n\n public static final int FAILURE_ASSOCIATION_REJECTION = 2;\n\n public static final int FAILURE_AUTHENTICATION_FAILURE = 3;\n\n public static final int FAILURE_CONNECT_NETWORK_FAILED = 5;\n\n public static final int FAILURE_DHCP = 10;\n\n public static final int FAILURE_NETWORK_DISCONNECTION = 6;\n\n public static final int FAILURE_NEW_CONNECTION_ATTEMPT = 7;\n\n public static final int FAILURE_NONE = 1;\n\n public static final int FAILURE_REDUNDANT_CONNECTION_ATTEMPT = 8;\n\n public static final int FAILURE_ROAM_TIMEOUT = 9;\n\n public static final int FAILURE_SSID_TEMP_DISABLED = 4;\n\n public static final int FAILURE_UNKNOWN = 0;\n\n private String mConfigBssid;\n\n private String mConfigSsid;\n\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent mConnectionEvent;\n\n private long mRealEndTime;\n\n private long mRealStartTime;\n\n RouterFingerPrint mRouterFingerPrint;\n\n private boolean mScreenOn;\n\n private int mWifiState;\n\n /* synthetic */\n ConnectionEvent(WifiMetrics this$0, ConnectionEvent connectionEvent) {\n this();\n }\n\n private ConnectionEvent() {\n this.mConnectionEvent = new com.android.server.wifi.WifiMetricsProto.ConnectionEvent();\n this.mRealEndTime = 0;\n this.mRealStartTime = 0;\n this.mRouterFingerPrint = new RouterFingerPrint();\n this.mConnectionEvent.routerFingerprint = this.mRouterFingerPrint.mRouterFingerPrintProto;\n this.mConfigSsid = \"\";\n this.mConfigBssid = \"\";\n this.mWifiState = 0;\n this.mScreenOn = false;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"startTime=\");\n Calendar c = Calendar.getInstance();\n synchronized (WifiMetrics.this.mLock) {\n String str;\n c.setTimeInMillis(this.mConnectionEvent.startTimeMillis);\n if (this.mConnectionEvent.startTimeMillis == 0) {\n str = \" \";\n } else {\n str = String.format(\"%tm-%td %tH:%tM:%tS.%tL\", new Object[] { c, c, c, c, c, c });\n }\n sb.append(str);\n sb.append(\", SSID=\");\n sb.append(this.mConfigSsid);\n sb.append(\", BSSID=\");\n sb.append(this.mConfigBssid);\n sb.append(\", durationMillis=\");\n sb.append(this.mConnectionEvent.durationTakenToConnectMillis);\n sb.append(\", roamType=\");\n switch(this.mConnectionEvent.roamType) {\n case 1:\n sb.append(\"ROAM_NONE\");\n break;\n case 2:\n sb.append(\"ROAM_DBDC\");\n break;\n case 3:\n sb.append(\"ROAM_ENTERPRISE\");\n break;\n case 4:\n sb.append(\"ROAM_USER_SELECTED\");\n break;\n case 5:\n sb.append(\"ROAM_UNRELATED\");\n break;\n default:\n sb.append(\"ROAM_UNKNOWN\");\n break;\n }\n sb.append(\", connectionResult=\");\n sb.append(this.mConnectionEvent.connectionResult);\n sb.append(\", level2FailureCode=\");\n switch(this.mConnectionEvent.level2FailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"ASSOCIATION_REJECTION\");\n break;\n case 3:\n sb.append(\"AUTHENTICATION_FAILURE\");\n break;\n case 4:\n sb.append(\"SSID_TEMP_DISABLED\");\n break;\n case 5:\n sb.append(\"CONNECT_NETWORK_FAILED\");\n break;\n case 6:\n sb.append(\"NETWORK_DISCONNECTION\");\n break;\n case 7:\n sb.append(\"NEW_CONNECTION_ATTEMPT\");\n break;\n case 8:\n sb.append(\"REDUNDANT_CONNECTION_ATTEMPT\");\n break;\n case 9:\n sb.append(\"ROAM_TIMEOUT\");\n break;\n case 10:\n sb.append(\"DHCP\");\n break;\n }\n sb.append(\"UNKNOWN\");\n sb.append(\", connectivityLevelFailureCode=\");\n switch(this.mConnectionEvent.connectivityLevelFailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"DHCP\");\n break;\n case 3:\n sb.append(\"NO_INTERNET\");\n break;\n case 4:\n sb.append(\"UNWANTED\");\n break;\n default:\n sb.append(\"UNKNOWN\");\n break;\n }\n sb.append(\", signalStrength=\");\n sb.append(this.mConnectionEvent.signalStrength);\n sb.append(\", wifiState=\");\n switch(this.mWifiState) {\n case 1:\n sb.append(\"WIFI_DISABLED\");\n break;\n case 2:\n sb.append(\"WIFI_DISCONNECTED\");\n break;\n case 3:\n sb.append(\"WIFI_ASSOCIATED\");\n break;\n default:\n sb.append(\"WIFI_UNKNOWN\");\n break;\n }\n sb.append(\", screenOn=\");\n sb.append(this.mScreenOn);\n sb.append(\". mRouterFingerprint: \");\n sb.append(this.mRouterFingerPrint.toString());\n }\n return sb.toString();\n }\n }\n\n class RouterFingerPrint {\n\n private com.android.server.wifi.WifiMetricsProto.RouterFingerPrint mRouterFingerPrintProto = new com.android.server.wifi.WifiMetricsProto.RouterFingerPrint();\n\n RouterFingerPrint() {\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n synchronized (WifiMetrics.this.mLock) {\n sb.append(\"mConnectionEvent.roamType=\").append(this.mRouterFingerPrintProto.roamType);\n sb.append(\", mChannelInfo=\").append(this.mRouterFingerPrintProto.channelInfo);\n sb.append(\", mDtim=\").append(this.mRouterFingerPrintProto.dtim);\n sb.append(\", mAuthentication=\").append(this.mRouterFingerPrintProto.authentication);\n sb.append(\", mHidden=\").append(this.mRouterFingerPrintProto.hidden);\n sb.append(\", mRouterTechnology=\").append(this.mRouterFingerPrintProto.routerTechnology);\n sb.append(\", mSupportsIpv6=\").append(this.mRouterFingerPrintProto.supportsIpv6);\n }\n return sb.toString();\n }\n\n public void updateFromWifiConfiguration(WifiConfiguration config) {\n synchronized (WifiMetrics.this.mLock) {\n if (config != null) {\n this.mRouterFingerPrintProto.hidden = config.hiddenSSID;\n if (config.dtimInterval > 0) {\n this.mRouterFingerPrintProto.dtim = config.dtimInterval;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mConfigSsid = config.SSID;\n if (config.allowedKeyManagement != null && config.allowedKeyManagement.get(0)) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n } else if (config.isEnterprise()) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n } else {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.passpoint = config.isPasspoint();\n ScanResult candidate = config.getNetworkSelectionStatus().getCandidate();\n if (candidate != null) {\n WifiMetrics.this.updateMetricsFromScanResult(candidate);\n }\n }\n }\n }\n }\n\n public WifiMetrics(Clock clock) {\n this.mClock = clock;\n this.mCurrentConnectionEvent = null;\n this.mScreenOn = true;\n this.mWifiState = 1;\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n }\n\n public void startConnectionEvent(WifiConfiguration config, String targetBSSID, int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n if (this.mCurrentConnectionEvent.mConfigSsid == null || this.mCurrentConnectionEvent.mConfigBssid == null || config == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(config.SSID) || !(this.mCurrentConnectionEvent.mConfigBssid.equals(WifiLastResortWatchdog.BSSID_ANY) || this.mCurrentConnectionEvent.mConfigBssid.equals(targetBSSID))) {\n endConnectionEvent(7, 1);\n } else {\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n endConnectionEvent(8, 1);\n }\n }\n while (this.mConnectionEventList.size() >= 256) {\n this.mConnectionEventList.remove(0);\n }\n this.mCurrentConnectionEvent = new ConnectionEvent(this, null);\n this.mCurrentConnectionEvent.mConnectionEvent.startTimeMillis = this.mClock.currentTimeMillis();\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n this.mCurrentConnectionEvent.mRouterFingerPrint.updateFromWifiConfiguration(config);\n this.mCurrentConnectionEvent.mConfigBssid = WifiLastResortWatchdog.BSSID_ANY;\n this.mCurrentConnectionEvent.mRealStartTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mWifiState = this.mWifiState;\n this.mCurrentConnectionEvent.mScreenOn = this.mScreenOn;\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n }\n\n public void setConnectionEventRoamType(int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n }\n }\n }\n\n public void setConnectionScanDetail(ScanDetail scanDetail) {\n synchronized (this.mLock) {\n if (!(this.mCurrentConnectionEvent == null || scanDetail == null)) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n if (!(networkDetail == null || scanResult == null || this.mCurrentConnectionEvent.mConfigSsid == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(\"\\\"\" + networkDetail.getSSID() + \"\\\"\"))) {\n updateMetricsFromNetworkDetail(networkDetail);\n updateMetricsFromScanResult(scanResult);\n }\n }\n }\n }\n\n public void endConnectionEvent(int level2FailureCode, int connectivityFailureCode) {\n int i = 1;\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n boolean result = level2FailureCode == 1 ? connectivityFailureCode == 1 : false;\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent connectionEvent = this.mCurrentConnectionEvent.mConnectionEvent;\n if (!result) {\n i = 0;\n }\n connectionEvent.connectionResult = i;\n this.mCurrentConnectionEvent.mRealEndTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mConnectionEvent.durationTakenToConnectMillis = (int) (this.mCurrentConnectionEvent.mRealEndTime - this.mCurrentConnectionEvent.mRealStartTime);\n this.mCurrentConnectionEvent.mConnectionEvent.level2FailureCode = level2FailureCode;\n this.mCurrentConnectionEvent.mConnectionEvent.connectivityLevelFailureCode = connectivityFailureCode;\n this.mCurrentConnectionEvent = null;\n }\n }\n }\n\n private void updateMetricsFromNetworkDetail(NetworkDetail networkDetail) {\n int connectionWifiMode;\n int dtimInterval = networkDetail.getDtimInterval();\n if (dtimInterval > 0) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.dtim = dtimInterval;\n }\n switch(networkDetail.getWifiMode()) {\n case 0:\n connectionWifiMode = 0;\n break;\n case 1:\n connectionWifiMode = 1;\n break;\n case 2:\n connectionWifiMode = 2;\n break;\n case 3:\n connectionWifiMode = 3;\n break;\n case 4:\n connectionWifiMode = 4;\n break;\n case 5:\n connectionWifiMode = 5;\n break;\n default:\n connectionWifiMode = 6;\n break;\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.routerTechnology = connectionWifiMode;\n }\n\n private void updateMetricsFromScanResult(ScanResult scanResult) {\n this.mCurrentConnectionEvent.mConnectionEvent.signalStrength = scanResult.level;\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n this.mCurrentConnectionEvent.mConfigBssid = scanResult.BSSID;\n if (scanResult.capabilities != null) {\n if (scanResult.capabilities.contains(\"WEP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"PSK\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"EAP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n }\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.channelInfo = scanResult.frequency;\n }\n\n void setNumSavedNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numSavedNetworks = num;\n }\n }\n\n void setNumOpenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numOpenNetworks = num;\n }\n }\n\n void setNumPersonalNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPersonalNetworks = num;\n }\n }\n\n void setNumEnterpriseNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numEnterpriseNetworks = num;\n }\n }\n\n void setNumHiddenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numHiddenNetworks = num;\n }\n }\n\n void setNumPasspointNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPasspointNetworks = num;\n }\n }\n\n void setNumNetworksAddedByUser(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByUser = num;\n }\n }\n\n void setNumNetworksAddedByApps(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByApps = num;\n }\n }\n\n void setIsLocationEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isLocationEnabled = enabled;\n }\n }\n\n void setIsScanningAlwaysEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isScanningAlwaysEnabled = enabled;\n }\n }\n\n public void incrementNonEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numNonEmptyScanResults++;\n }\n }\n\n public void incrementEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numEmptyScanResults++;\n }\n }\n\n public void incrementBackgroundScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numBackgroundScans++;\n }\n }\n\n public int getBackgroundScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numBackgroundScans;\n }\n return i;\n }\n\n public void incrementOneshotScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numOneshotScans++;\n }\n incrementWifiSystemScanStateCount(this.mWifiState, this.mScreenOn);\n }\n\n public int getOneshotScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numOneshotScans;\n }\n return i;\n }\n\n private String returnCodeToString(int scanReturnCode) {\n switch(scanReturnCode) {\n case 0:\n return \"SCAN_UNKNOWN\";\n case 1:\n return \"SCAN_SUCCESS\";\n case 2:\n return \"SCAN_FAILURE_INTERRUPTED\";\n case 3:\n return \"SCAN_FAILURE_INVALID_CONFIGURATION\";\n case 4:\n return \"FAILURE_WIFI_DISABLED\";\n default:\n return \"\";\n }\n }\n\n public void incrementScanReturnEntry(int scanReturnCode, int countToAdd) {\n synchronized (this.mLock) {\n this.mScanReturnEntries.put(scanReturnCode, this.mScanReturnEntries.get(scanReturnCode) + countToAdd);\n }\n }\n\n public int getScanReturnEntry(int scanReturnCode) {\n int i;\n synchronized (this.mLock) {\n i = this.mScanReturnEntries.get(scanReturnCode);\n }\n return i;\n }\n\n private String wifiSystemStateToString(int state) {\n switch(state) {\n case 0:\n return \"WIFI_UNKNOWN\";\n case 1:\n return \"WIFI_DISABLED\";\n case 2:\n return \"WIFI_DISCONNECTED\";\n case 3:\n return \"WIFI_ASSOCIATED\";\n default:\n return \"default\";\n }\n }\n\n public void incrementWifiSystemScanStateCount(int state, boolean screenOn) {\n synchronized (this.mLock) {\n int index = (state * 2) + (screenOn ? 1 : 0);\n this.mWifiSystemStateEntries.put(index, this.mWifiSystemStateEntries.get(index) + 1);\n }\n }\n\n public int getSystemStateCount(int state, boolean screenOn) {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiSystemStateEntries.get((state * 2) + (screenOn ? 1 : 0));\n }\n return i;\n }\n\n public void incrementNumLastResortWatchdogTriggers() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggers++;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAssociationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAssociationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAuthenticationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadDhcpNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadDhcpNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadOtherNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadOtherNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogAvailableNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogAvailableNetworksTotal += count;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAssociation() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAssociation++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAuthentication() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAuthentication++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadDhcp() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadDhcp++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadOther() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadOther++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoBad++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundBad++;\n }\n }\n\n public void incrementRssiPollRssiCount(int rssi) {\n if (rssi >= MIN_RSSI_POLL && rssi <= 0) {\n synchronized (this.mLock) {\n this.mRssiPollCounts.put(rssi, this.mRssiPollCounts.get(rssi) + 1);\n }\n }\n }\n\n public void incrementNumLastResortWatchdogSuccesses() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogSuccesses++;\n }\n }\n\n public void incrementAlertReasonCount(int reason) {\n if (reason > 64 || reason < 0) {\n reason = 0;\n }\n synchronized (this.mLock) {\n this.mWifiAlertReasonCounts.put(reason, this.mWifiAlertReasonCounts.get(reason) + 1);\n }\n }\n\n public void countScanResults(List scanDetails) {\n if (scanDetails != null) {\n int totalResults = 0;\n int openNetworks = 0;\n int personalNetworks = 0;\n int enterpriseNetworks = 0;\n int hiddenNetworks = 0;\n int hotspot2r1Networks = 0;\n int hotspot2r2Networks = 0;\n for (ScanDetail scanDetail : scanDetails) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n totalResults++;\n if (networkDetail != null) {\n if (networkDetail.isHiddenBeaconFrame()) {\n hiddenNetworks++;\n }\n if (networkDetail.getHSRelease() != null) {\n if (networkDetail.getHSRelease() == HSRelease.R1) {\n hotspot2r1Networks++;\n } else if (networkDetail.getHSRelease() == HSRelease.R2) {\n hotspot2r2Networks++;\n }\n }\n }\n if (!(scanResult == null || scanResult.capabilities == null)) {\n if (scanResult.capabilities.contains(\"EAP\")) {\n enterpriseNetworks++;\n } else if (scanResult.capabilities.contains(\"PSK\") || scanResult.capabilities.contains(\"WEP\")) {\n personalNetworks++;\n } else {\n openNetworks++;\n }\n }\n }\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numTotalScanResults += totalResults;\n wifiLog = this.mWifiLogProto;\n wifiLog.numOpenNetworkScanResults += openNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numPersonalNetworkScanResults += personalNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numEnterpriseNetworkScanResults += enterpriseNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHiddenNetworkScanResults += hiddenNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R1NetworkScanResults += hotspot2r1Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R2NetworkScanResults += hotspot2r2Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numScans++;\n }\n }\n }\n\n public void incrementWifiScoreCount(int score) {\n if (score >= 0 && score <= 5) {\n synchronized (this.mLock) {\n this.mWifiScoreCounts.put(score, this.mWifiScoreCounts.get(score) + 1);\n }\n }\n }\n\n public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {\n synchronized (this.mLock) {\n int i;\n if (args != null) {\n if (args.length > 0 && PROTO_DUMP_ARG.equals(args[0])) {\n consolidateProto(true);\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (this.mCurrentConnectionEvent != event) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n String metricsProtoDump = Base64.encodeToString(MessageNano.toByteArray(this.mWifiLogProto), 0);\n if (args.length <= 1 || !CLEAN_DUMP_ARG.equals(args[1])) {\n pw.println(\"WifiMetrics:\");\n pw.println(metricsProtoDump);\n pw.println(\"EndWifiMetrics\");\n } else {\n pw.print(metricsProtoDump);\n }\n clear();\n }\n }\n pw.println(\"WifiMetrics:\");\n pw.println(\"mConnectionEvents:\");\n for (ConnectionEvent event2 : this.mConnectionEventList) {\n String eventLine = event2.toString();\n if (event2 == this.mCurrentConnectionEvent) {\n eventLine = eventLine + \"CURRENTLY OPEN EVENT\";\n }\n pw.println(eventLine);\n }\n pw.println(\"mWifiLogProto.numSavedNetworks=\" + this.mWifiLogProto.numSavedNetworks);\n pw.println(\"mWifiLogProto.numOpenNetworks=\" + this.mWifiLogProto.numOpenNetworks);\n pw.println(\"mWifiLogProto.numPersonalNetworks=\" + this.mWifiLogProto.numPersonalNetworks);\n pw.println(\"mWifiLogProto.numEnterpriseNetworks=\" + this.mWifiLogProto.numEnterpriseNetworks);\n pw.println(\"mWifiLogProto.numHiddenNetworks=\" + this.mWifiLogProto.numHiddenNetworks);\n pw.println(\"mWifiLogProto.numPasspointNetworks=\" + this.mWifiLogProto.numPasspointNetworks);\n pw.println(\"mWifiLogProto.isLocationEnabled=\" + this.mWifiLogProto.isLocationEnabled);\n pw.println(\"mWifiLogProto.isScanningAlwaysEnabled=\" + this.mWifiLogProto.isScanningAlwaysEnabled);\n pw.println(\"mWifiLogProto.numNetworksAddedByUser=\" + this.mWifiLogProto.numNetworksAddedByUser);\n pw.println(\"mWifiLogProto.numNetworksAddedByApps=\" + this.mWifiLogProto.numNetworksAddedByApps);\n pw.println(\"mWifiLogProto.numNonEmptyScanResults=\" + this.mWifiLogProto.numNonEmptyScanResults);\n pw.println(\"mWifiLogProto.numEmptyScanResults=\" + this.mWifiLogProto.numEmptyScanResults);\n pw.println(\"mWifiLogProto.numOneshotScans=\" + this.mWifiLogProto.numOneshotScans);\n pw.println(\"mWifiLogProto.numBackgroundScans=\" + this.mWifiLogProto.numBackgroundScans);\n pw.println(\"mScanReturnEntries:\");\n pw.println(\" SCAN_UNKNOWN: \" + getScanReturnEntry(0));\n pw.println(\" SCAN_SUCCESS: \" + getScanReturnEntry(1));\n pw.println(\" SCAN_FAILURE_INTERRUPTED: \" + getScanReturnEntry(2));\n pw.println(\" SCAN_FAILURE_INVALID_CONFIGURATION: \" + getScanReturnEntry(3));\n pw.println(\" FAILURE_WIFI_DISABLED: \" + getScanReturnEntry(4));\n pw.println(\"mSystemStateEntries: : \");\n pw.println(\" WIFI_UNKNOWN ON: \" + getSystemStateCount(0, true));\n pw.println(\" WIFI_DISABLED ON: \" + getSystemStateCount(1, true));\n pw.println(\" WIFI_DISCONNECTED ON: \" + getSystemStateCount(2, true));\n pw.println(\" WIFI_ASSOCIATED ON: \" + getSystemStateCount(3, true));\n pw.println(\" WIFI_UNKNOWN OFF: \" + getSystemStateCount(0, false));\n pw.println(\" WIFI_DISABLED OFF: \" + getSystemStateCount(1, false));\n pw.println(\" WIFI_DISCONNECTED OFF: \" + getSystemStateCount(2, false));\n pw.println(\" WIFI_ASSOCIATED OFF: \" + getSystemStateCount(3, false));\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoGood=\" + this.mWifiLogProto.numConnectivityWatchdogPnoGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoBad=\" + this.mWifiLogProto.numConnectivityWatchdogPnoBad);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundGood=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundBad=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundBad);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggers=\" + this.mWifiLogProto.numLastResortWatchdogTriggers);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadOther=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadOther);\n pw.println(\"mWifiLogProto.numLastResortWatchdogSuccesses=\" + this.mWifiLogProto.numLastResortWatchdogSuccesses);\n pw.println(\"mWifiLogProto.recordDurationSec=\" + ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec));\n pw.println(\"mWifiLogProto.rssiPollRssiCount: Printing counts for [-127, 0]\");\n StringBuilder sb = new StringBuilder();\n ", "post_mask_code": "\n pw.println(\" \" + sb.toString());\n pw.print(\"mWifiLogProto.alertReasonCounts=\");\n sb.setLength(0);\n for (i = 0; i <= 64; i++) {\n int count = this.mWifiAlertReasonCounts.get(i);\n if (count > 0) {\n sb.append(\"(\").append(i).append(\",\").append(count).append(\"),\");\n }\n }\n if (sb.length() > 1) {\n sb.setLength(sb.length() - 1);\n pw.println(sb.toString());\n } else {\n pw.println(\"()\");\n }\n pw.println(\"mWifiLogProto.numTotalScanResults=\" + this.mWifiLogProto.numTotalScanResults);\n pw.println(\"mWifiLogProto.numOpenNetworkScanResults=\" + this.mWifiLogProto.numOpenNetworkScanResults);\n pw.println(\"mWifiLogProto.numPersonalNetworkScanResults=\" + this.mWifiLogProto.numPersonalNetworkScanResults);\n pw.println(\"mWifiLogProto.numEnterpriseNetworkScanResults=\" + this.mWifiLogProto.numEnterpriseNetworkScanResults);\n pw.println(\"mWifiLogProto.numHiddenNetworkScanResults=\" + this.mWifiLogProto.numHiddenNetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R1NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R1NetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R2NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R2NetworkScanResults);\n pw.println(\"mWifiLogProto.numScans=\" + this.mWifiLogProto.numScans);\n pw.println(\"mWifiLogProto.WifiScoreCount: [0, 5]\");\n for (i = 0; i <= 5; i++) {\n pw.print(this.mWifiScoreCounts.get(i) + \" \");\n }\n pw.print(\"\\n\");\n }\n }\n\n private void consolidateProto(boolean incremental) {\n List events = new ArrayList();\n List rssis = new ArrayList();\n List alertReasons = new ArrayList();\n List scores = new ArrayList();\n synchronized (this.mLock) {\n int i;\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (!(incremental && (this.mCurrentConnectionEvent == event || event.mConnectionEvent.automaticBugReportTaken))) {\n events.add(event.mConnectionEvent);\n if (incremental) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n }\n if (events.size() > 0) {\n this.mWifiLogProto.connectionEvent = (com.android.server.wifi.WifiMetricsProto.ConnectionEvent[]) events.toArray(this.mWifiLogProto.connectionEvent);\n }\n this.mWifiLogProto.scanReturnEntries = new ScanReturnEntry[this.mScanReturnEntries.size()];\n for (i = 0; i < this.mScanReturnEntries.size(); i++) {\n this.mWifiLogProto.scanReturnEntries[i] = new ScanReturnEntry();\n this.mWifiLogProto.scanReturnEntries[i].scanReturnCode = this.mScanReturnEntries.keyAt(i);\n this.mWifiLogProto.scanReturnEntries[i].scanResultsCount = this.mScanReturnEntries.valueAt(i);\n }\n this.mWifiLogProto.wifiSystemStateEntries = new WifiSystemStateEntry[this.mWifiSystemStateEntries.size()];\n for (i = 0; i < this.mWifiSystemStateEntries.size(); i++) {\n this.mWifiLogProto.wifiSystemStateEntries[i] = new WifiSystemStateEntry();\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiState = this.mWifiSystemStateEntries.keyAt(i) / 2;\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiStateCount = this.mWifiSystemStateEntries.valueAt(i);\n this.mWifiLogProto.wifiSystemStateEntries[i].isScreenOn = this.mWifiSystemStateEntries.keyAt(i) % 2 > 0;\n }\n this.mWifiLogProto.recordDurationSec = (int) ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec);\n for (i = 0; i < this.mRssiPollCounts.size(); i++) {\n RssiPollCount keyVal = new RssiPollCount();\n keyVal.rssi = this.mRssiPollCounts.keyAt(i);\n keyVal.count = this.mRssiPollCounts.valueAt(i);\n rssis.add(keyVal);\n }\n this.mWifiLogProto.rssiPollRssiCount = (RssiPollCount[]) rssis.toArray(this.mWifiLogProto.rssiPollRssiCount);\n for (i = 0; i < this.mWifiAlertReasonCounts.size(); i++) {\n AlertReasonCount keyVal2 = new AlertReasonCount();\n keyVal2.reason = this.mWifiAlertReasonCounts.keyAt(i);\n keyVal2.count = this.mWifiAlertReasonCounts.valueAt(i);\n alertReasons.add(keyVal2);\n }\n this.mWifiLogProto.alertReasonCount = (AlertReasonCount[]) alertReasons.toArray(this.mWifiLogProto.alertReasonCount);\n for (int score = 0; score < this.mWifiScoreCounts.size(); score++) {\n WifiScoreCount keyVal3 = new WifiScoreCount();\n keyVal3.score = this.mWifiScoreCounts.keyAt(score);\n keyVal3.count = this.mWifiScoreCounts.valueAt(score);\n scores.add(keyVal3);\n }\n this.mWifiLogProto.wifiScoreCount = (WifiScoreCount[]) scores.toArray(this.mWifiLogProto.wifiScoreCount);\n }\n }\n\n private void clear() {\n synchronized (this.mLock) {\n this.mConnectionEventList.clear();\n if (this.mCurrentConnectionEvent != null) {\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n this.mScanReturnEntries.clear();\n this.mWifiSystemStateEntries.clear();\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n this.mRssiPollCounts.clear();\n this.mWifiAlertReasonCounts.clear();\n this.mWifiScoreCounts.clear();\n this.mWifiLogProto.clear();\n }\n }\n\n public void setScreenState(boolean screenOn) {\n synchronized (this.mLock) {\n this.mScreenOn = screenOn;\n }\n }\n\n public void setWifiState(int wifiState) {\n synchronized (this.mLock) {\n this.mWifiState = wifiState;\n }\n }\n}\n"} {"task_id": "Java_696", "language": "Java", "task_type": "while_statement", "source_file": "java/github/dstmath/OppoFramework/A1_7_1_1/src/main/java/com/android/server/wifi/WifiMetrics.java", "mask_start_position": 12403, "mask_end_position": 12519, "canonical_solution": "while (this.mConnectionEventList.size() >= 256) {\n this.mConnectionEventList.remove(0);\n }", "pre_mask_code": "package com.android.server.wifi;\n\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiConfiguration;\nimport android.util.Base64;\nimport android.util.SparseIntArray;\nimport com.android.server.wifi.WifiMetricsProto.AlertReasonCount;\nimport com.android.server.wifi.WifiMetricsProto.RssiPollCount;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.ScanReturnEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.WifiSystemStateEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiScoreCount;\nimport com.android.server.wifi.hotspot2.NetworkDetail;\nimport com.android.server.wifi.hotspot2.NetworkDetail.HSRelease;\nimport com.google.protobuf.nano.MessageNano;\nimport java.io.FileDescriptor;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.List;\n\npublic class WifiMetrics {\n\n public static final String CLEAN_DUMP_ARG = \"clean\";\n\n private static final boolean DBG = false;\n\n private static final int MAX_CONNECTION_EVENTS = 256;\n\n private static final int MAX_RSSI_POLL = 0;\n\n private static final int MAX_WIFI_SCORE = 5;\n\n private static final int MIN_RSSI_POLL = -127;\n\n private static final int MIN_WIFI_SCORE = 0;\n\n public static final String PROTO_DUMP_ARG = \"wifiMetricsProto\";\n\n private static final int SCREEN_OFF = 0;\n\n private static final int SCREEN_ON = 1;\n\n private static final String TAG = \"WifiMetrics\";\n\n private Clock mClock;\n\n private final List mConnectionEventList = new ArrayList();\n\n private ConnectionEvent mCurrentConnectionEvent;\n\n private final Object mLock = new Object();\n\n private long mRecordStartTimeSec;\n\n private final SparseIntArray mRssiPollCounts = new SparseIntArray();\n\n private final SparseIntArray mScanReturnEntries = new SparseIntArray();\n\n private boolean mScreenOn;\n\n private final SparseIntArray mWifiAlertReasonCounts = new SparseIntArray();\n\n private final WifiLog mWifiLogProto = new WifiLog();\n\n private final SparseIntArray mWifiScoreCounts = new SparseIntArray();\n\n private int mWifiState;\n\n private final SparseIntArray mWifiSystemStateEntries = new SparseIntArray();\n\n class ConnectionEvent {\n\n public static final int FAILURE_ASSOCIATION_REJECTION = 2;\n\n public static final int FAILURE_AUTHENTICATION_FAILURE = 3;\n\n public static final int FAILURE_CONNECT_NETWORK_FAILED = 5;\n\n public static final int FAILURE_DHCP = 10;\n\n public static final int FAILURE_NETWORK_DISCONNECTION = 6;\n\n public static final int FAILURE_NEW_CONNECTION_ATTEMPT = 7;\n\n public static final int FAILURE_NONE = 1;\n\n public static final int FAILURE_REDUNDANT_CONNECTION_ATTEMPT = 8;\n\n public static final int FAILURE_ROAM_TIMEOUT = 9;\n\n public static final int FAILURE_SSID_TEMP_DISABLED = 4;\n\n public static final int FAILURE_UNKNOWN = 0;\n\n private String mConfigBssid;\n\n private String mConfigSsid;\n\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent mConnectionEvent;\n\n private long mRealEndTime;\n\n private long mRealStartTime;\n\n RouterFingerPrint mRouterFingerPrint;\n\n private boolean mScreenOn;\n\n private int mWifiState;\n\n /* synthetic */\n ConnectionEvent(WifiMetrics this$0, ConnectionEvent connectionEvent) {\n this();\n }\n\n private ConnectionEvent() {\n this.mConnectionEvent = new com.android.server.wifi.WifiMetricsProto.ConnectionEvent();\n this.mRealEndTime = 0;\n this.mRealStartTime = 0;\n this.mRouterFingerPrint = new RouterFingerPrint();\n this.mConnectionEvent.routerFingerprint = this.mRouterFingerPrint.mRouterFingerPrintProto;\n this.mConfigSsid = \"\";\n this.mConfigBssid = \"\";\n this.mWifiState = 0;\n this.mScreenOn = false;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"startTime=\");\n Calendar c = Calendar.getInstance();\n synchronized (WifiMetrics.this.mLock) {\n String str;\n c.setTimeInMillis(this.mConnectionEvent.startTimeMillis);\n if (this.mConnectionEvent.startTimeMillis == 0) {\n str = \" \";\n } else {\n str = String.format(\"%tm-%td %tH:%tM:%tS.%tL\", new Object[] { c, c, c, c, c, c });\n }\n sb.append(str);\n sb.append(\", SSID=\");\n sb.append(this.mConfigSsid);\n sb.append(\", BSSID=\");\n sb.append(this.mConfigBssid);\n sb.append(\", durationMillis=\");\n sb.append(this.mConnectionEvent.durationTakenToConnectMillis);\n sb.append(\", roamType=\");\n switch(this.mConnectionEvent.roamType) {\n case 1:\n sb.append(\"ROAM_NONE\");\n break;\n case 2:\n sb.append(\"ROAM_DBDC\");\n break;\n case 3:\n sb.append(\"ROAM_ENTERPRISE\");\n break;\n case 4:\n sb.append(\"ROAM_USER_SELECTED\");\n break;\n case 5:\n sb.append(\"ROAM_UNRELATED\");\n break;\n default:\n sb.append(\"ROAM_UNKNOWN\");\n break;\n }\n sb.append(\", connectionResult=\");\n sb.append(this.mConnectionEvent.connectionResult);\n sb.append(\", level2FailureCode=\");\n switch(this.mConnectionEvent.level2FailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"ASSOCIATION_REJECTION\");\n break;\n case 3:\n sb.append(\"AUTHENTICATION_FAILURE\");\n break;\n case 4:\n sb.append(\"SSID_TEMP_DISABLED\");\n break;\n case 5:\n sb.append(\"CONNECT_NETWORK_FAILED\");\n break;\n case 6:\n sb.append(\"NETWORK_DISCONNECTION\");\n break;\n case 7:\n sb.append(\"NEW_CONNECTION_ATTEMPT\");\n break;\n case 8:\n sb.append(\"REDUNDANT_CONNECTION_ATTEMPT\");\n break;\n case 9:\n sb.append(\"ROAM_TIMEOUT\");\n break;\n case 10:\n sb.append(\"DHCP\");\n break;\n }\n sb.append(\"UNKNOWN\");\n sb.append(\", connectivityLevelFailureCode=\");\n switch(this.mConnectionEvent.connectivityLevelFailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"DHCP\");\n break;\n case 3:\n sb.append(\"NO_INTERNET\");\n break;\n case 4:\n sb.append(\"UNWANTED\");\n break;\n default:\n sb.append(\"UNKNOWN\");\n break;\n }\n sb.append(\", signalStrength=\");\n sb.append(this.mConnectionEvent.signalStrength);\n sb.append(\", wifiState=\");\n switch(this.mWifiState) {\n case 1:\n sb.append(\"WIFI_DISABLED\");\n break;\n case 2:\n sb.append(\"WIFI_DISCONNECTED\");\n break;\n case 3:\n sb.append(\"WIFI_ASSOCIATED\");\n break;\n default:\n sb.append(\"WIFI_UNKNOWN\");\n break;\n }\n sb.append(\", screenOn=\");\n sb.append(this.mScreenOn);\n sb.append(\". mRouterFingerprint: \");\n sb.append(this.mRouterFingerPrint.toString());\n }\n return sb.toString();\n }\n }\n\n class RouterFingerPrint {\n\n private com.android.server.wifi.WifiMetricsProto.RouterFingerPrint mRouterFingerPrintProto = new com.android.server.wifi.WifiMetricsProto.RouterFingerPrint();\n\n RouterFingerPrint() {\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n synchronized (WifiMetrics.this.mLock) {\n sb.append(\"mConnectionEvent.roamType=\").append(this.mRouterFingerPrintProto.roamType);\n sb.append(\", mChannelInfo=\").append(this.mRouterFingerPrintProto.channelInfo);\n sb.append(\", mDtim=\").append(this.mRouterFingerPrintProto.dtim);\n sb.append(\", mAuthentication=\").append(this.mRouterFingerPrintProto.authentication);\n sb.append(\", mHidden=\").append(this.mRouterFingerPrintProto.hidden);\n sb.append(\", mRouterTechnology=\").append(this.mRouterFingerPrintProto.routerTechnology);\n sb.append(\", mSupportsIpv6=\").append(this.mRouterFingerPrintProto.supportsIpv6);\n }\n return sb.toString();\n }\n\n public void updateFromWifiConfiguration(WifiConfiguration config) {\n synchronized (WifiMetrics.this.mLock) {\n if (config != null) {\n this.mRouterFingerPrintProto.hidden = config.hiddenSSID;\n if (config.dtimInterval > 0) {\n this.mRouterFingerPrintProto.dtim = config.dtimInterval;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mConfigSsid = config.SSID;\n if (config.allowedKeyManagement != null && config.allowedKeyManagement.get(0)) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n } else if (config.isEnterprise()) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n } else {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.passpoint = config.isPasspoint();\n ScanResult candidate = config.getNetworkSelectionStatus().getCandidate();\n if (candidate != null) {\n WifiMetrics.this.updateMetricsFromScanResult(candidate);\n }\n }\n }\n }\n }\n\n public WifiMetrics(Clock clock) {\n this.mClock = clock;\n this.mCurrentConnectionEvent = null;\n this.mScreenOn = true;\n this.mWifiState = 1;\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n }\n\n public void startConnectionEvent(WifiConfiguration config, String targetBSSID, int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n if (this.mCurrentConnectionEvent.mConfigSsid == null || this.mCurrentConnectionEvent.mConfigBssid == null || config == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(config.SSID) || !(this.mCurrentConnectionEvent.mConfigBssid.equals(WifiLastResortWatchdog.BSSID_ANY) || this.mCurrentConnectionEvent.mConfigBssid.equals(targetBSSID))) {\n endConnectionEvent(7, 1);\n } else {\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n endConnectionEvent(8, 1);\n }\n }\n ", "post_mask_code": "\n this.mCurrentConnectionEvent = new ConnectionEvent(this, null);\n this.mCurrentConnectionEvent.mConnectionEvent.startTimeMillis = this.mClock.currentTimeMillis();\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n this.mCurrentConnectionEvent.mRouterFingerPrint.updateFromWifiConfiguration(config);\n this.mCurrentConnectionEvent.mConfigBssid = WifiLastResortWatchdog.BSSID_ANY;\n this.mCurrentConnectionEvent.mRealStartTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mWifiState = this.mWifiState;\n this.mCurrentConnectionEvent.mScreenOn = this.mScreenOn;\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n }\n\n public void setConnectionEventRoamType(int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n }\n }\n }\n\n public void setConnectionScanDetail(ScanDetail scanDetail) {\n synchronized (this.mLock) {\n if (!(this.mCurrentConnectionEvent == null || scanDetail == null)) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n if (!(networkDetail == null || scanResult == null || this.mCurrentConnectionEvent.mConfigSsid == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(\"\\\"\" + networkDetail.getSSID() + \"\\\"\"))) {\n updateMetricsFromNetworkDetail(networkDetail);\n updateMetricsFromScanResult(scanResult);\n }\n }\n }\n }\n\n public void endConnectionEvent(int level2FailureCode, int connectivityFailureCode) {\n int i = 1;\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n boolean result = level2FailureCode == 1 ? connectivityFailureCode == 1 : false;\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent connectionEvent = this.mCurrentConnectionEvent.mConnectionEvent;\n if (!result) {\n i = 0;\n }\n connectionEvent.connectionResult = i;\n this.mCurrentConnectionEvent.mRealEndTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mConnectionEvent.durationTakenToConnectMillis = (int) (this.mCurrentConnectionEvent.mRealEndTime - this.mCurrentConnectionEvent.mRealStartTime);\n this.mCurrentConnectionEvent.mConnectionEvent.level2FailureCode = level2FailureCode;\n this.mCurrentConnectionEvent.mConnectionEvent.connectivityLevelFailureCode = connectivityFailureCode;\n this.mCurrentConnectionEvent = null;\n }\n }\n }\n\n private void updateMetricsFromNetworkDetail(NetworkDetail networkDetail) {\n int connectionWifiMode;\n int dtimInterval = networkDetail.getDtimInterval();\n if (dtimInterval > 0) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.dtim = dtimInterval;\n }\n switch(networkDetail.getWifiMode()) {\n case 0:\n connectionWifiMode = 0;\n break;\n case 1:\n connectionWifiMode = 1;\n break;\n case 2:\n connectionWifiMode = 2;\n break;\n case 3:\n connectionWifiMode = 3;\n break;\n case 4:\n connectionWifiMode = 4;\n break;\n case 5:\n connectionWifiMode = 5;\n break;\n default:\n connectionWifiMode = 6;\n break;\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.routerTechnology = connectionWifiMode;\n }\n\n private void updateMetricsFromScanResult(ScanResult scanResult) {\n this.mCurrentConnectionEvent.mConnectionEvent.signalStrength = scanResult.level;\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n this.mCurrentConnectionEvent.mConfigBssid = scanResult.BSSID;\n if (scanResult.capabilities != null) {\n if (scanResult.capabilities.contains(\"WEP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"PSK\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"EAP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n }\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.channelInfo = scanResult.frequency;\n }\n\n void setNumSavedNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numSavedNetworks = num;\n }\n }\n\n void setNumOpenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numOpenNetworks = num;\n }\n }\n\n void setNumPersonalNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPersonalNetworks = num;\n }\n }\n\n void setNumEnterpriseNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numEnterpriseNetworks = num;\n }\n }\n\n void setNumHiddenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numHiddenNetworks = num;\n }\n }\n\n void setNumPasspointNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPasspointNetworks = num;\n }\n }\n\n void setNumNetworksAddedByUser(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByUser = num;\n }\n }\n\n void setNumNetworksAddedByApps(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByApps = num;\n }\n }\n\n void setIsLocationEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isLocationEnabled = enabled;\n }\n }\n\n void setIsScanningAlwaysEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isScanningAlwaysEnabled = enabled;\n }\n }\n\n public void incrementNonEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numNonEmptyScanResults++;\n }\n }\n\n public void incrementEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numEmptyScanResults++;\n }\n }\n\n public void incrementBackgroundScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numBackgroundScans++;\n }\n }\n\n public int getBackgroundScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numBackgroundScans;\n }\n return i;\n }\n\n public void incrementOneshotScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numOneshotScans++;\n }\n incrementWifiSystemScanStateCount(this.mWifiState, this.mScreenOn);\n }\n\n public int getOneshotScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numOneshotScans;\n }\n return i;\n }\n\n private String returnCodeToString(int scanReturnCode) {\n switch(scanReturnCode) {\n case 0:\n return \"SCAN_UNKNOWN\";\n case 1:\n return \"SCAN_SUCCESS\";\n case 2:\n return \"SCAN_FAILURE_INTERRUPTED\";\n case 3:\n return \"SCAN_FAILURE_INVALID_CONFIGURATION\";\n case 4:\n return \"FAILURE_WIFI_DISABLED\";\n default:\n return \"\";\n }\n }\n\n public void incrementScanReturnEntry(int scanReturnCode, int countToAdd) {\n synchronized (this.mLock) {\n this.mScanReturnEntries.put(scanReturnCode, this.mScanReturnEntries.get(scanReturnCode) + countToAdd);\n }\n }\n\n public int getScanReturnEntry(int scanReturnCode) {\n int i;\n synchronized (this.mLock) {\n i = this.mScanReturnEntries.get(scanReturnCode);\n }\n return i;\n }\n\n private String wifiSystemStateToString(int state) {\n switch(state) {\n case 0:\n return \"WIFI_UNKNOWN\";\n case 1:\n return \"WIFI_DISABLED\";\n case 2:\n return \"WIFI_DISCONNECTED\";\n case 3:\n return \"WIFI_ASSOCIATED\";\n default:\n return \"default\";\n }\n }\n\n public void incrementWifiSystemScanStateCount(int state, boolean screenOn) {\n synchronized (this.mLock) {\n int index = (state * 2) + (screenOn ? 1 : 0);\n this.mWifiSystemStateEntries.put(index, this.mWifiSystemStateEntries.get(index) + 1);\n }\n }\n\n public int getSystemStateCount(int state, boolean screenOn) {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiSystemStateEntries.get((state * 2) + (screenOn ? 1 : 0));\n }\n return i;\n }\n\n public void incrementNumLastResortWatchdogTriggers() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggers++;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAssociationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAssociationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAuthenticationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadDhcpNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadDhcpNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadOtherNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadOtherNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogAvailableNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogAvailableNetworksTotal += count;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAssociation() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAssociation++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAuthentication() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAuthentication++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadDhcp() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadDhcp++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadOther() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadOther++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoBad++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundBad++;\n }\n }\n\n public void incrementRssiPollRssiCount(int rssi) {\n if (rssi >= MIN_RSSI_POLL && rssi <= 0) {\n synchronized (this.mLock) {\n this.mRssiPollCounts.put(rssi, this.mRssiPollCounts.get(rssi) + 1);\n }\n }\n }\n\n public void incrementNumLastResortWatchdogSuccesses() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogSuccesses++;\n }\n }\n\n public void incrementAlertReasonCount(int reason) {\n if (reason > 64 || reason < 0) {\n reason = 0;\n }\n synchronized (this.mLock) {\n this.mWifiAlertReasonCounts.put(reason, this.mWifiAlertReasonCounts.get(reason) + 1);\n }\n }\n\n public void countScanResults(List scanDetails) {\n if (scanDetails != null) {\n int totalResults = 0;\n int openNetworks = 0;\n int personalNetworks = 0;\n int enterpriseNetworks = 0;\n int hiddenNetworks = 0;\n int hotspot2r1Networks = 0;\n int hotspot2r2Networks = 0;\n for (ScanDetail scanDetail : scanDetails) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n totalResults++;\n if (networkDetail != null) {\n if (networkDetail.isHiddenBeaconFrame()) {\n hiddenNetworks++;\n }\n if (networkDetail.getHSRelease() != null) {\n if (networkDetail.getHSRelease() == HSRelease.R1) {\n hotspot2r1Networks++;\n } else if (networkDetail.getHSRelease() == HSRelease.R2) {\n hotspot2r2Networks++;\n }\n }\n }\n if (!(scanResult == null || scanResult.capabilities == null)) {\n if (scanResult.capabilities.contains(\"EAP\")) {\n enterpriseNetworks++;\n } else if (scanResult.capabilities.contains(\"PSK\") || scanResult.capabilities.contains(\"WEP\")) {\n personalNetworks++;\n } else {\n openNetworks++;\n }\n }\n }\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numTotalScanResults += totalResults;\n wifiLog = this.mWifiLogProto;\n wifiLog.numOpenNetworkScanResults += openNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numPersonalNetworkScanResults += personalNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numEnterpriseNetworkScanResults += enterpriseNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHiddenNetworkScanResults += hiddenNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R1NetworkScanResults += hotspot2r1Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R2NetworkScanResults += hotspot2r2Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numScans++;\n }\n }\n }\n\n public void incrementWifiScoreCount(int score) {\n if (score >= 0 && score <= 5) {\n synchronized (this.mLock) {\n this.mWifiScoreCounts.put(score, this.mWifiScoreCounts.get(score) + 1);\n }\n }\n }\n\n public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {\n synchronized (this.mLock) {\n int i;\n if (args != null) {\n if (args.length > 0 && PROTO_DUMP_ARG.equals(args[0])) {\n consolidateProto(true);\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (this.mCurrentConnectionEvent != event) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n String metricsProtoDump = Base64.encodeToString(MessageNano.toByteArray(this.mWifiLogProto), 0);\n if (args.length <= 1 || !CLEAN_DUMP_ARG.equals(args[1])) {\n pw.println(\"WifiMetrics:\");\n pw.println(metricsProtoDump);\n pw.println(\"EndWifiMetrics\");\n } else {\n pw.print(metricsProtoDump);\n }\n clear();\n }\n }\n pw.println(\"WifiMetrics:\");\n pw.println(\"mConnectionEvents:\");\n for (ConnectionEvent event2 : this.mConnectionEventList) {\n String eventLine = event2.toString();\n if (event2 == this.mCurrentConnectionEvent) {\n eventLine = eventLine + \"CURRENTLY OPEN EVENT\";\n }\n pw.println(eventLine);\n }\n pw.println(\"mWifiLogProto.numSavedNetworks=\" + this.mWifiLogProto.numSavedNetworks);\n pw.println(\"mWifiLogProto.numOpenNetworks=\" + this.mWifiLogProto.numOpenNetworks);\n pw.println(\"mWifiLogProto.numPersonalNetworks=\" + this.mWifiLogProto.numPersonalNetworks);\n pw.println(\"mWifiLogProto.numEnterpriseNetworks=\" + this.mWifiLogProto.numEnterpriseNetworks);\n pw.println(\"mWifiLogProto.numHiddenNetworks=\" + this.mWifiLogProto.numHiddenNetworks);\n pw.println(\"mWifiLogProto.numPasspointNetworks=\" + this.mWifiLogProto.numPasspointNetworks);\n pw.println(\"mWifiLogProto.isLocationEnabled=\" + this.mWifiLogProto.isLocationEnabled);\n pw.println(\"mWifiLogProto.isScanningAlwaysEnabled=\" + this.mWifiLogProto.isScanningAlwaysEnabled);\n pw.println(\"mWifiLogProto.numNetworksAddedByUser=\" + this.mWifiLogProto.numNetworksAddedByUser);\n pw.println(\"mWifiLogProto.numNetworksAddedByApps=\" + this.mWifiLogProto.numNetworksAddedByApps);\n pw.println(\"mWifiLogProto.numNonEmptyScanResults=\" + this.mWifiLogProto.numNonEmptyScanResults);\n pw.println(\"mWifiLogProto.numEmptyScanResults=\" + this.mWifiLogProto.numEmptyScanResults);\n pw.println(\"mWifiLogProto.numOneshotScans=\" + this.mWifiLogProto.numOneshotScans);\n pw.println(\"mWifiLogProto.numBackgroundScans=\" + this.mWifiLogProto.numBackgroundScans);\n pw.println(\"mScanReturnEntries:\");\n pw.println(\" SCAN_UNKNOWN: \" + getScanReturnEntry(0));\n pw.println(\" SCAN_SUCCESS: \" + getScanReturnEntry(1));\n pw.println(\" SCAN_FAILURE_INTERRUPTED: \" + getScanReturnEntry(2));\n pw.println(\" SCAN_FAILURE_INVALID_CONFIGURATION: \" + getScanReturnEntry(3));\n pw.println(\" FAILURE_WIFI_DISABLED: \" + getScanReturnEntry(4));\n pw.println(\"mSystemStateEntries: : \");\n pw.println(\" WIFI_UNKNOWN ON: \" + getSystemStateCount(0, true));\n pw.println(\" WIFI_DISABLED ON: \" + getSystemStateCount(1, true));\n pw.println(\" WIFI_DISCONNECTED ON: \" + getSystemStateCount(2, true));\n pw.println(\" WIFI_ASSOCIATED ON: \" + getSystemStateCount(3, true));\n pw.println(\" WIFI_UNKNOWN OFF: \" + getSystemStateCount(0, false));\n pw.println(\" WIFI_DISABLED OFF: \" + getSystemStateCount(1, false));\n pw.println(\" WIFI_DISCONNECTED OFF: \" + getSystemStateCount(2, false));\n pw.println(\" WIFI_ASSOCIATED OFF: \" + getSystemStateCount(3, false));\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoGood=\" + this.mWifiLogProto.numConnectivityWatchdogPnoGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoBad=\" + this.mWifiLogProto.numConnectivityWatchdogPnoBad);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundGood=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundBad=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundBad);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggers=\" + this.mWifiLogProto.numLastResortWatchdogTriggers);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadOther=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadOther);\n pw.println(\"mWifiLogProto.numLastResortWatchdogSuccesses=\" + this.mWifiLogProto.numLastResortWatchdogSuccesses);\n pw.println(\"mWifiLogProto.recordDurationSec=\" + ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec));\n pw.println(\"mWifiLogProto.rssiPollRssiCount: Printing counts for [-127, 0]\");\n StringBuilder sb = new StringBuilder();\n for (i = MIN_RSSI_POLL; i <= 0; i++) {\n sb.append(this.mRssiPollCounts.get(i)).append(\" \");\n }\n pw.println(\" \" + sb.toString());\n pw.print(\"mWifiLogProto.alertReasonCounts=\");\n sb.setLength(0);\n for (i = 0; i <= 64; i++) {\n int count = this.mWifiAlertReasonCounts.get(i);\n if (count > 0) {\n sb.append(\"(\").append(i).append(\",\").append(count).append(\"),\");\n }\n }\n if (sb.length() > 1) {\n sb.setLength(sb.length() - 1);\n pw.println(sb.toString());\n } else {\n pw.println(\"()\");\n }\n pw.println(\"mWifiLogProto.numTotalScanResults=\" + this.mWifiLogProto.numTotalScanResults);\n pw.println(\"mWifiLogProto.numOpenNetworkScanResults=\" + this.mWifiLogProto.numOpenNetworkScanResults);\n pw.println(\"mWifiLogProto.numPersonalNetworkScanResults=\" + this.mWifiLogProto.numPersonalNetworkScanResults);\n pw.println(\"mWifiLogProto.numEnterpriseNetworkScanResults=\" + this.mWifiLogProto.numEnterpriseNetworkScanResults);\n pw.println(\"mWifiLogProto.numHiddenNetworkScanResults=\" + this.mWifiLogProto.numHiddenNetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R1NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R1NetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R2NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R2NetworkScanResults);\n pw.println(\"mWifiLogProto.numScans=\" + this.mWifiLogProto.numScans);\n pw.println(\"mWifiLogProto.WifiScoreCount: [0, 5]\");\n for (i = 0; i <= 5; i++) {\n pw.print(this.mWifiScoreCounts.get(i) + \" \");\n }\n pw.print(\"\\n\");\n }\n }\n\n private void consolidateProto(boolean incremental) {\n List events = new ArrayList();\n List rssis = new ArrayList();\n List alertReasons = new ArrayList();\n List scores = new ArrayList();\n synchronized (this.mLock) {\n int i;\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (!(incremental && (this.mCurrentConnectionEvent == event || event.mConnectionEvent.automaticBugReportTaken))) {\n events.add(event.mConnectionEvent);\n if (incremental) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n }\n if (events.size() > 0) {\n this.mWifiLogProto.connectionEvent = (com.android.server.wifi.WifiMetricsProto.ConnectionEvent[]) events.toArray(this.mWifiLogProto.connectionEvent);\n }\n this.mWifiLogProto.scanReturnEntries = new ScanReturnEntry[this.mScanReturnEntries.size()];\n for (i = 0; i < this.mScanReturnEntries.size(); i++) {\n this.mWifiLogProto.scanReturnEntries[i] = new ScanReturnEntry();\n this.mWifiLogProto.scanReturnEntries[i].scanReturnCode = this.mScanReturnEntries.keyAt(i);\n this.mWifiLogProto.scanReturnEntries[i].scanResultsCount = this.mScanReturnEntries.valueAt(i);\n }\n this.mWifiLogProto.wifiSystemStateEntries = new WifiSystemStateEntry[this.mWifiSystemStateEntries.size()];\n for (i = 0; i < this.mWifiSystemStateEntries.size(); i++) {\n this.mWifiLogProto.wifiSystemStateEntries[i] = new WifiSystemStateEntry();\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiState = this.mWifiSystemStateEntries.keyAt(i) / 2;\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiStateCount = this.mWifiSystemStateEntries.valueAt(i);\n this.mWifiLogProto.wifiSystemStateEntries[i].isScreenOn = this.mWifiSystemStateEntries.keyAt(i) % 2 > 0;\n }\n this.mWifiLogProto.recordDurationSec = (int) ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec);\n for (i = 0; i < this.mRssiPollCounts.size(); i++) {\n RssiPollCount keyVal = new RssiPollCount();\n keyVal.rssi = this.mRssiPollCounts.keyAt(i);\n keyVal.count = this.mRssiPollCounts.valueAt(i);\n rssis.add(keyVal);\n }\n this.mWifiLogProto.rssiPollRssiCount = (RssiPollCount[]) rssis.toArray(this.mWifiLogProto.rssiPollRssiCount);\n for (i = 0; i < this.mWifiAlertReasonCounts.size(); i++) {\n AlertReasonCount keyVal2 = new AlertReasonCount();\n keyVal2.reason = this.mWifiAlertReasonCounts.keyAt(i);\n keyVal2.count = this.mWifiAlertReasonCounts.valueAt(i);\n alertReasons.add(keyVal2);\n }\n this.mWifiLogProto.alertReasonCount = (AlertReasonCount[]) alertReasons.toArray(this.mWifiLogProto.alertReasonCount);\n for (int score = 0; score < this.mWifiScoreCounts.size(); score++) {\n WifiScoreCount keyVal3 = new WifiScoreCount();\n keyVal3.score = this.mWifiScoreCounts.keyAt(score);\n keyVal3.count = this.mWifiScoreCounts.valueAt(score);\n scores.add(keyVal3);\n }\n this.mWifiLogProto.wifiScoreCount = (WifiScoreCount[]) scores.toArray(this.mWifiLogProto.wifiScoreCount);\n }\n }\n\n private void clear() {\n synchronized (this.mLock) {\n this.mConnectionEventList.clear();\n if (this.mCurrentConnectionEvent != null) {\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n this.mScanReturnEntries.clear();\n this.mWifiSystemStateEntries.clear();\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n this.mRssiPollCounts.clear();\n this.mWifiAlertReasonCounts.clear();\n this.mWifiScoreCounts.clear();\n this.mWifiLogProto.clear();\n }\n }\n\n public void setScreenState(boolean screenOn) {\n synchronized (this.mLock) {\n this.mScreenOn = screenOn;\n }\n }\n\n public void setWifiState(int wifiState) {\n synchronized (this.mLock) {\n this.mWifiState = wifiState;\n }\n }\n}\n"} {"task_id": "Java_697", "language": "Java", "task_type": "empty", "source_file": "java/github/dstmath/OppoFramework/A1_7_1_1/src/main/java/com/android/server/wifi/WifiMetrics.java", "mask_start_position": 40087, "mask_end_position": 40087, "canonical_solution": "", "pre_mask_code": "package com.android.server.wifi;\n\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiConfiguration;\nimport android.util.Base64;\nimport android.util.SparseIntArray;\nimport com.android.server.wifi.WifiMetricsProto.AlertReasonCount;\nimport com.android.server.wifi.WifiMetricsProto.RssiPollCount;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.ScanReturnEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiLog.WifiSystemStateEntry;\nimport com.android.server.wifi.WifiMetricsProto.WifiScoreCount;\nimport com.android.server.wifi.hotspot2.NetworkDetail;\nimport com.android.server.wifi.hotspot2.NetworkDetail.HSRelease;\nimport com.google.protobuf.nano.MessageNano;\nimport java.io.FileDescriptor;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.List;\n\npublic class WifiMetrics {\n\n public static final String CLEAN_DUMP_ARG = \"clean\";\n\n private static final boolean DBG = false;\n\n private static final int MAX_CONNECTION_EVENTS = 256;\n\n private static final int MAX_RSSI_POLL = 0;\n\n private static final int MAX_WIFI_SCORE = 5;\n\n private static final int MIN_RSSI_POLL = -127;\n\n private static final int MIN_WIFI_SCORE = 0;\n\n public static final String PROTO_DUMP_ARG = \"wifiMetricsProto\";\n\n private static final int SCREEN_OFF = 0;\n\n private static final int SCREEN_ON = 1;\n\n private static final String TAG = \"WifiMetrics\";\n\n private Clock mClock;\n\n private final List mConnectionEventList = new ArrayList();\n\n private ConnectionEvent mCurrentConnectionEvent;\n\n private final Object mLock = new Object();\n\n private long mRecordStartTimeSec;\n\n private final SparseIntArray mRssiPollCounts = new SparseIntArray();\n\n private final SparseIntArray mScanReturnEntries = new SparseIntArray();\n\n private boolean mScreenOn;\n\n private final SparseIntArray mWifiAlertReasonCounts = new SparseIntArray();\n\n private final WifiLog mWifiLogProto = new WifiLog();\n\n private final SparseIntArray mWifiScoreCounts = new SparseIntArray();\n\n private int mWifiState;\n\n private final SparseIntArray mWifiSystemStateEntries = new SparseIntArray();\n\n class ConnectionEvent {\n\n public static final int FAILURE_ASSOCIATION_REJECTION = 2;\n\n public static final int FAILURE_AUTHENTICATION_FAILURE = 3;\n\n public static final int FAILURE_CONNECT_NETWORK_FAILED = 5;\n\n public static final int FAILURE_DHCP = 10;\n\n public static final int FAILURE_NETWORK_DISCONNECTION = 6;\n\n public static final int FAILURE_NEW_CONNECTION_ATTEMPT = 7;\n\n public static final int FAILURE_NONE = 1;\n\n public static final int FAILURE_REDUNDANT_CONNECTION_ATTEMPT = 8;\n\n public static final int FAILURE_ROAM_TIMEOUT = 9;\n\n public static final int FAILURE_SSID_TEMP_DISABLED = 4;\n\n public static final int FAILURE_UNKNOWN = 0;\n\n private String mConfigBssid;\n\n private String mConfigSsid;\n\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent mConnectionEvent;\n\n private long mRealEndTime;\n\n private long mRealStartTime;\n\n RouterFingerPrint mRouterFingerPrint;\n\n private boolean mScreenOn;\n\n private int mWifiState;\n\n /* synthetic */\n ConnectionEvent(WifiMetrics this$0, ConnectionEvent connectionEvent) {\n this();\n }\n\n private ConnectionEvent() {\n this.mConnectionEvent = new com.android.server.wifi.WifiMetricsProto.ConnectionEvent();\n this.mRealEndTime = 0;\n this.mRealStartTime = 0;\n this.mRouterFingerPrint = new RouterFingerPrint();\n this.mConnectionEvent.routerFingerprint = this.mRouterFingerPrint.mRouterFingerPrintProto;\n this.mConfigSsid = \"\";\n this.mConfigBssid = \"\";\n this.mWifiState = 0;\n this.mScreenOn = false;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"startTime=\");\n Calendar c = Calendar.getInstance();\n synchronized (WifiMetrics.this.mLock) {\n String str;\n c.setTimeInMillis(this.mConnectionEvent.startTimeMillis);\n if (this.mConnectionEvent.startTimeMillis == 0) {\n str = \" \";\n } else {\n str = String.format(\"%tm-%td %tH:%tM:%tS.%tL\", new Object[] { c, c, c, c, c, c });\n }\n sb.append(str);\n sb.append(\", SSID=\");\n sb.append(this.mConfigSsid);\n sb.append(\", BSSID=\");\n sb.append(this.mConfigBssid);\n sb.append(\", durationMillis=\");\n sb.append(this.mConnectionEvent.durationTakenToConnectMillis);\n sb.append(\", roamType=\");\n switch(this.mConnectionEvent.roamType) {\n case 1:\n sb.append(\"ROAM_NONE\");\n break;\n case 2:\n sb.append(\"ROAM_DBDC\");\n break;\n case 3:\n sb.append(\"ROAM_ENTERPRISE\");\n break;\n case 4:\n sb.append(\"ROAM_USER_SELECTED\");\n break;\n case 5:\n sb.append(\"ROAM_UNRELATED\");\n break;\n default:\n sb.append(\"ROAM_UNKNOWN\");\n break;\n }\n sb.append(\", connectionResult=\");\n sb.append(this.mConnectionEvent.connectionResult);\n sb.append(\", level2FailureCode=\");\n switch(this.mConnectionEvent.level2FailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"ASSOCIATION_REJECTION\");\n break;\n case 3:\n sb.append(\"AUTHENTICATION_FAILURE\");\n break;\n case 4:\n sb.append(\"SSID_TEMP_DISABLED\");\n break;\n case 5:\n sb.append(\"CONNECT_NETWORK_FAILED\");\n break;\n case 6:\n sb.append(\"NETWORK_DISCONNECTION\");\n break;\n case 7:\n sb.append(\"NEW_CONNECTION_ATTEMPT\");\n break;\n case 8:\n sb.append(\"REDUNDANT_CONNECTION_ATTEMPT\");\n break;\n case 9:\n sb.append(\"ROAM_TIMEOUT\");\n break;\n case 10:\n sb.append(\"DHCP\");\n break;\n }\n sb.append(\"UNKNOWN\");\n sb.append(\", connectivityLevelFailureCode=\");\n switch(this.mConnectionEvent.connectivityLevelFailureCode) {\n case 1:\n sb.append(\"NONE\");\n break;\n case 2:\n sb.append(\"DHCP\");\n break;\n case 3:\n sb.append(\"NO_INTERNET\");\n break;\n case 4:\n sb.append(\"UNWANTED\");\n break;\n default:\n sb.append(\"UNKNOWN\");\n break;\n }\n sb.append(\", signalStrength=\");\n sb.append(this.mConnectionEvent.signalStrength);\n sb.append(\", wifiState=\");\n switch(this.mWifiState) {\n case 1:\n sb.append(\"WIFI_DISABLED\");\n break;\n case 2:\n sb.append(\"WIFI_DISCONNECTED\");\n break;\n case 3:\n sb.append(\"WIFI_ASSOCIATED\");\n break;\n default:\n sb.append(\"WIFI_UNKNOWN\");\n break;\n }\n sb.append(\", screenOn=\");\n sb.append(this.mScreenOn);\n sb.append(\". mRouterFingerprint: \");\n sb.append(this.mRouterFingerPrint.toString());\n }\n return sb.toString();\n }\n }\n\n class RouterFingerPrint {\n\n private com.android.server.wifi.WifiMetricsProto.RouterFingerPrint mRouterFingerPrintProto = new com.android.server.wifi.WifiMetricsProto.RouterFingerPrint();\n\n RouterFingerPrint() {\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n synchronized (WifiMetrics.this.mLock) {\n sb.append(\"mConnectionEvent.roamType=\").append(this.mRouterFingerPrintProto.roamType);\n sb.append(\", mChannelInfo=\").append(this.mRouterFingerPrintProto.channelInfo);\n sb.append(\", mDtim=\").append(this.mRouterFingerPrintProto.dtim);\n sb.append(\", mAuthentication=\").append(this.mRouterFingerPrintProto.authentication);\n sb.append(\", mHidden=\").append(this.mRouterFingerPrintProto.hidden);\n sb.append(\", mRouterTechnology=\").append(this.mRouterFingerPrintProto.routerTechnology);\n sb.append(\", mSupportsIpv6=\").append(this.mRouterFingerPrintProto.supportsIpv6);\n }\n return sb.toString();\n }\n\n public void updateFromWifiConfiguration(WifiConfiguration config) {\n synchronized (WifiMetrics.this.mLock) {\n if (config != null) {\n this.mRouterFingerPrintProto.hidden = config.hiddenSSID;\n if (config.dtimInterval > 0) {\n this.mRouterFingerPrintProto.dtim = config.dtimInterval;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mConfigSsid = config.SSID;\n if (config.allowedKeyManagement != null && config.allowedKeyManagement.get(0)) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n } else if (config.isEnterprise()) {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n } else {\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n }\n WifiMetrics.this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.passpoint = config.isPasspoint();\n ScanResult candidate = config.getNetworkSelectionStatus().getCandidate();\n if (candidate != null) {\n WifiMetrics.this.updateMetricsFromScanResult(candidate);\n }\n }\n }\n }\n }\n\n public WifiMetrics(Clock clock) {\n this.mClock = clock;\n this.mCurrentConnectionEvent = null;\n this.mScreenOn = true;\n this.mWifiState = 1;\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n }\n\n public void startConnectionEvent(WifiConfiguration config, String targetBSSID, int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n if (this.mCurrentConnectionEvent.mConfigSsid == null || this.mCurrentConnectionEvent.mConfigBssid == null || config == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(config.SSID) || !(this.mCurrentConnectionEvent.mConfigBssid.equals(WifiLastResortWatchdog.BSSID_ANY) || this.mCurrentConnectionEvent.mConfigBssid.equals(targetBSSID))) {\n endConnectionEvent(7, 1);\n } else {\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n endConnectionEvent(8, 1);\n }\n }\n while (this.mConnectionEventList.size() >= 256) {\n this.mConnectionEventList.remove(0);\n }\n this.mCurrentConnectionEvent = new ConnectionEvent(this, null);\n this.mCurrentConnectionEvent.mConnectionEvent.startTimeMillis = this.mClock.currentTimeMillis();\n this.mCurrentConnectionEvent.mConfigBssid = targetBSSID;\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n this.mCurrentConnectionEvent.mRouterFingerPrint.updateFromWifiConfiguration(config);\n this.mCurrentConnectionEvent.mConfigBssid = WifiLastResortWatchdog.BSSID_ANY;\n this.mCurrentConnectionEvent.mRealStartTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mWifiState = this.mWifiState;\n this.mCurrentConnectionEvent.mScreenOn = this.mScreenOn;\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n }\n\n public void setConnectionEventRoamType(int roamType) {\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n this.mCurrentConnectionEvent.mConnectionEvent.roamType = roamType;\n }\n }\n }\n\n public void setConnectionScanDetail(ScanDetail scanDetail) {\n synchronized (this.mLock) {\n if (!(this.mCurrentConnectionEvent == null || scanDetail == null)) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n if (!(networkDetail == null || scanResult == null || this.mCurrentConnectionEvent.mConfigSsid == null || !this.mCurrentConnectionEvent.mConfigSsid.equals(\"\\\"\" + networkDetail.getSSID() + \"\\\"\"))) {\n updateMetricsFromNetworkDetail(networkDetail);\n updateMetricsFromScanResult(scanResult);\n }\n }\n }\n }\n\n public void endConnectionEvent(int level2FailureCode, int connectivityFailureCode) {\n int i = 1;\n synchronized (this.mLock) {\n if (this.mCurrentConnectionEvent != null) {\n boolean result = level2FailureCode == 1 ? connectivityFailureCode == 1 : false;\n com.android.server.wifi.WifiMetricsProto.ConnectionEvent connectionEvent = this.mCurrentConnectionEvent.mConnectionEvent;\n if (!result) {\n i = 0;\n }\n connectionEvent.connectionResult = i;\n this.mCurrentConnectionEvent.mRealEndTime = this.mClock.elapsedRealtime();\n this.mCurrentConnectionEvent.mConnectionEvent.durationTakenToConnectMillis = (int) (this.mCurrentConnectionEvent.mRealEndTime - this.mCurrentConnectionEvent.mRealStartTime);\n this.mCurrentConnectionEvent.mConnectionEvent.level2FailureCode = level2FailureCode;\n this.mCurrentConnectionEvent.mConnectionEvent.connectivityLevelFailureCode = connectivityFailureCode;\n this.mCurrentConnectionEvent = null;\n }\n }\n }\n\n private void updateMetricsFromNetworkDetail(NetworkDetail networkDetail) {\n int connectionWifiMode;\n int dtimInterval = networkDetail.getDtimInterval();\n if (dtimInterval > 0) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.dtim = dtimInterval;\n }\n switch(networkDetail.getWifiMode()) {\n case 0:\n connectionWifiMode = 0;\n break;\n case 1:\n connectionWifiMode = 1;\n break;\n case 2:\n connectionWifiMode = 2;\n break;\n case 3:\n connectionWifiMode = 3;\n break;\n case 4:\n connectionWifiMode = 4;\n break;\n case 5:\n connectionWifiMode = 5;\n break;\n default:\n connectionWifiMode = 6;\n break;\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.routerTechnology = connectionWifiMode;\n }\n\n private void updateMetricsFromScanResult(ScanResult scanResult) {\n this.mCurrentConnectionEvent.mConnectionEvent.signalStrength = scanResult.level;\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 1;\n this.mCurrentConnectionEvent.mConfigBssid = scanResult.BSSID;\n if (scanResult.capabilities != null) {\n if (scanResult.capabilities.contains(\"WEP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"PSK\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 2;\n } else if (scanResult.capabilities.contains(\"EAP\")) {\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.authentication = 3;\n }\n }\n this.mCurrentConnectionEvent.mRouterFingerPrint.mRouterFingerPrintProto.channelInfo = scanResult.frequency;\n }\n\n void setNumSavedNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numSavedNetworks = num;\n }\n }\n\n void setNumOpenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numOpenNetworks = num;\n }\n }\n\n void setNumPersonalNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPersonalNetworks = num;\n }\n }\n\n void setNumEnterpriseNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numEnterpriseNetworks = num;\n }\n }\n\n void setNumHiddenNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numHiddenNetworks = num;\n }\n }\n\n void setNumPasspointNetworks(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numPasspointNetworks = num;\n }\n }\n\n void setNumNetworksAddedByUser(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByUser = num;\n }\n }\n\n void setNumNetworksAddedByApps(int num) {\n synchronized (this.mLock) {\n this.mWifiLogProto.numNetworksAddedByApps = num;\n }\n }\n\n void setIsLocationEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isLocationEnabled = enabled;\n }\n }\n\n void setIsScanningAlwaysEnabled(boolean enabled) {\n synchronized (this.mLock) {\n this.mWifiLogProto.isScanningAlwaysEnabled = enabled;\n }\n }\n\n public void incrementNonEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numNonEmptyScanResults++;\n }\n }\n\n public void incrementEmptyScanResultCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numEmptyScanResults++;\n }\n }\n\n public void incrementBackgroundScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numBackgroundScans++;\n }\n }\n\n public int getBackgroundScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numBackgroundScans;\n }\n return i;\n }\n\n public void incrementOneshotScanCount() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numOneshotScans++;\n }\n incrementWifiSystemScanStateCount(this.mWifiState, this.mScreenOn);\n }\n\n public int getOneshotScanCount() {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiLogProto.numOneshotScans;\n }\n return i;\n }\n\n private String returnCodeToString(int scanReturnCode) {\n switch(scanReturnCode) {\n case 0:\n return \"SCAN_UNKNOWN\";\n case 1:\n return \"SCAN_SUCCESS\";\n case 2:\n return \"SCAN_FAILURE_INTERRUPTED\";\n case 3:\n return \"SCAN_FAILURE_INVALID_CONFIGURATION\";\n case 4:\n return \"FAILURE_WIFI_DISABLED\";\n default:\n return \"\";\n }\n }\n\n public void incrementScanReturnEntry(int scanReturnCode, int countToAdd) {\n synchronized (this.mLock) {\n this.mScanReturnEntries.put(scanReturnCode, this.mScanReturnEntries.get(scanReturnCode) + countToAdd);\n }\n }\n\n public int getScanReturnEntry(int scanReturnCode) {\n int i;\n synchronized (this.mLock) {\n i = this.mScanReturnEntries.get(scanReturnCode);\n }\n return i;\n }\n\n private String wifiSystemStateToString(int state) {\n switch(state) {\n case 0:\n return \"WIFI_UNKNOWN\";\n case 1:\n return \"WIFI_DISABLED\";\n case 2:\n return \"WIFI_DISCONNECTED\";\n case 3:\n return \"WIFI_ASSOCIATED\";\n default:\n return \"default\";\n }\n }\n\n public void incrementWifiSystemScanStateCount(int state, boolean screenOn) {\n synchronized (this.mLock) {\n int index = (state * 2) + (screenOn ? 1 : 0);\n this.mWifiSystemStateEntries.put(index, this.mWifiSystemStateEntries.get(index) + 1);\n }\n }\n\n public int getSystemStateCount(int state, boolean screenOn) {\n int i;\n synchronized (this.mLock) {\n i = this.mWifiSystemStateEntries.get((state * 2) + (screenOn ? 1 : 0));\n }\n return i;\n }\n\n public void incrementNumLastResortWatchdogTriggers() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggers++;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAssociationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAssociationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadAuthenticationNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadAuthenticationNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadDhcpNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadDhcpNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogBadOtherNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogBadOtherNetworksTotal += count;\n }\n }\n\n public void addCountToNumLastResortWatchdogAvailableNetworksTotal(int count) {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogAvailableNetworksTotal += count;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAssociation() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAssociation++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadAuthentication() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadAuthentication++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadDhcp() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadDhcp++;\n }\n }\n\n public void incrementNumLastResortWatchdogTriggersWithBadOther() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogTriggersWithBadOther++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogPnoBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogPnoBad++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundGood() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundGood++;\n }\n }\n\n public void incrementNumConnectivityWatchdogBackgroundBad() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numConnectivityWatchdogBackgroundBad++;\n }\n }\n\n public void incrementRssiPollRssiCount(int rssi) {\n if (rssi >= MIN_RSSI_POLL && rssi <= 0) {\n synchronized (this.mLock) {\n this.mRssiPollCounts.put(rssi, this.mRssiPollCounts.get(rssi) + 1);\n }\n }\n }\n\n public void incrementNumLastResortWatchdogSuccesses() {\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numLastResortWatchdogSuccesses++;\n }\n }\n\n public void incrementAlertReasonCount(int reason) {\n if (reason > 64 || reason < 0) {\n reason = 0;\n }\n synchronized (this.mLock) {\n this.mWifiAlertReasonCounts.put(reason, this.mWifiAlertReasonCounts.get(reason) + 1);\n }\n }\n\n public void countScanResults(List scanDetails) {\n if (scanDetails != null) {\n int totalResults = 0;\n int openNetworks = 0;\n int personalNetworks = 0;\n int enterpriseNetworks = 0;\n int hiddenNetworks = 0;\n int hotspot2r1Networks = 0;\n int hotspot2r2Networks = 0;\n for (ScanDetail scanDetail : scanDetails) {\n NetworkDetail networkDetail = scanDetail.getNetworkDetail();\n ScanResult scanResult = scanDetail.getScanResult();\n totalResults++;\n if (networkDetail != null) {\n if (networkDetail.isHiddenBeaconFrame()) {\n hiddenNetworks++;\n }\n if (networkDetail.getHSRelease() != null) {\n if (networkDetail.getHSRelease() == HSRelease.R1) {\n hotspot2r1Networks++;\n } else if (networkDetail.getHSRelease() == HSRelease.R2) {\n hotspot2r2Networks++;\n }\n }\n }\n if (!(scanResult == null || scanResult.capabilities == null)) {\n if (scanResult.capabilities.contains(\"EAP\")) {\n enterpriseNetworks++;\n } else if (scanResult.capabilities.contains(\"PSK\") || scanResult.capabilities.contains(\"WEP\")) {\n personalNetworks++;\n } else {\n openNetworks++;\n }\n }\n }\n synchronized (this.mLock) {\n WifiLog wifiLog = this.mWifiLogProto;\n wifiLog.numTotalScanResults += totalResults;\n wifiLog = this.mWifiLogProto;\n wifiLog.numOpenNetworkScanResults += openNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numPersonalNetworkScanResults += personalNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numEnterpriseNetworkScanResults += enterpriseNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHiddenNetworkScanResults += hiddenNetworks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R1NetworkScanResults += hotspot2r1Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numHotspot2R2NetworkScanResults += hotspot2r2Networks;\n wifiLog = this.mWifiLogProto;\n wifiLog.numScans++;\n }\n }\n }\n\n public void incrementWifiScoreCount(int score) {\n if (score >= 0 && score <= 5) {\n synchronized (this.mLock) {\n this.mWifiScoreCounts.put(score, this.mWifiScoreCounts.get(score) + 1);\n }\n }\n }\n\n public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {\n synchronized (this.mLock) {\n int i;\n if (args != null) {\n if (args.length > 0 && PROTO_DUMP_ARG.equals(args[0])) {\n consolidateProto(true);\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (this.mCurrentConnectionEvent != event) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n String metricsProtoDump = Base64.encodeToString(MessageNano.toByteArray(this.mWifiLogProto), 0);\n if (args.length <= 1 || !CLEAN_DUMP_ARG.equals(args[1])) {\n pw.println(\"WifiMetrics:\");\n pw.println(metricsProtoDump);\n pw.println(\"EndWifiMetrics\");\n } else {\n pw.print(metricsProtoDump);\n }\n clear();\n }\n }\n pw.println(\"WifiMetrics:\");\n pw.println(\"mConnectionEvents:\");\n for (ConnectionEvent event2 : this.mConnectionEventList) {\n String eventLine = event2.toString();\n if (event2 == this.mCurrentConnectionEvent) {\n eventLine = eventLine + \"CURRENTLY OPEN EVENT\";\n }\n pw.println(eventLine);\n }\n pw.println(\"mWifiLogProto.numSavedNetworks=\" + this.mWifiLogProto.numSavedNetworks);\n pw.println(\"mWifiLogProto.numOpenNetworks=\" + this.mWifiLogProto.numOpenNetworks);\n pw.println(\"mWifiLogProto.numPersonalNetworks=\" + this.mWifiLogProto.numPersonalNetworks);\n pw.println(\"mWifiLogProto.numEnterpriseNetworks=\" + this.mWifiLogProto.numEnterpriseNetworks);\n pw.println(\"mWifiLogProto.numHiddenNetworks=\" + this.mWifiLogProto.numHiddenNetworks);\n pw.println(\"mWifiLogProto.numPasspointNetworks=\" + this.mWifiLogProto.numPasspointNetworks);\n pw.println(\"mWifiLogProto.isLocationEnabled=\" + this.mWifiLogProto.isLocationEnabled);\n pw.println(\"mWifiLogProto.isScanningAlwaysEnabled=\" + this.mWifiLogProto.isScanningAlwaysEnabled);\n pw.println(\"mWifiLogProto.numNetworksAddedByUser=\" + this.mWifiLogProto.numNetworksAddedByUser);\n pw.println(\"mWifiLogProto.numNetworksAddedByApps=\" + this.mWifiLogProto.numNetworksAddedByApps);\n pw.println(\"mWifiLogProto.numNonEmptyScanResults=\" + this.mWifiLogProto.numNonEmptyScanResults);\n pw.println(\"mWifiLogProto.numEmptyScanResults=\" + this.mWifiLogProto.numEmptyScanResults);\n pw.println(\"mWifiLogProto.numOneshotScans=\" + this.mWifiLogProto.numOneshotScans);\n pw.println(\"mWifiLogProto.numBackgroundScans=\" + this.mWifiLogProto.numBackgroundScans);\n pw.println(\"mScanReturnEntries:\");\n pw.println(\" SCAN_UNKNOWN: \" + getScanReturnEntry(0));\n pw.println(\" SCAN_SUCCESS: \" + getScanReturnEntry(1));\n pw.println(\" SCAN_FAILURE_INTERRUPTED: \" + getScanReturnEntry(2));\n pw.println(\" SCAN_FAILURE_INVALID_CONFIGURATION: \" + getScanReturnEntry(3));\n pw.println(\" FAILURE_WIFI_DISABLED: \" + getScanReturnEntry(4));\n pw.println(\"mSystemStateEntries: : \");\n pw.println(\" WIFI_UNKNOWN ON: \" + getSystemStateCount(0, true));\n pw.println(\" WIFI_DISABLED ON: \" + getSystemStateCount(1, true));\n pw.println(\" WIFI_DISCONNECTED ON: \" + getSystemStateCount(2, true));\n pw.println(\" WIFI_ASSOCIATED ON: \" + getSystemStateCount(3, true));\n pw.println(\" WIFI_UNKNOWN OFF: \" + getSystemStateCount(0, false));\n pw.println(\" WIFI_DISABLED OFF: \" + getSystemStateCount(1, false));\n pw.println(\" WIFI_DISCONNECTED OFF: \" + getSystemStateCount(2, false));\n pw.println(\" WIFI_ASSOCIATED OFF: \" + getSystemStateCount(3, false));\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoGood=\" + this.mWifiLogProto.numConnectivityWatchdogPnoGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogPnoBad=\" + this.mWifiLogProto.numConnectivityWatchdogPnoBad);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundGood=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundGood);\n pw.println(\"mWifiLogProto.numConnectivityWatchdogBackgroundBad=\" + this.mWifiLogProto.numConnectivityWatchdogBackgroundBad);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggers=\" + this.mWifiLogProto.numLastResortWatchdogTriggers);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAssociationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadAuthenticationNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadDhcpNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogBadOtherNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal=\" + this.mWifiLogProto.numLastResortWatchdogAvailableNetworksTotal);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAssociation);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadAuthentication);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadDhcp);\n pw.println(\"mWifiLogProto.numLastResortWatchdogTriggersWithBadOther=\" + this.mWifiLogProto.numLastResortWatchdogTriggersWithBadOther);\n pw.println(\"mWifiLogProto.numLastResortWatchdogSuccesses=\" + this.mWifiLogProto.numLastResortWatchdogSuccesses);\n pw.println(\"mWifiLogProto.recordDurationSec=\" + ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec));\n pw.println(\"mWifiLogProto.rssiPollRssiCount: Printing counts for [-127, 0]\");\n StringBuilder sb = new StringBuilder();\n for (i = MIN_RSSI_POLL; i <= 0; i++) {\n sb.append(this.mRssiPollCounts.get(i)).append(\" \");\n }\n pw.println(\" \" + sb.toString());\n pw.print(\"mWifiLogProto.alertReasonCounts=\");\n sb.setLength(0);\n for (i = 0; i <= 64; i++) {\n int count = this.mWifiAlertReasonCounts.get(i);\n if (count > 0) {\n sb.append(\"(\").append(i).append(\",\").append(count).append(\"),\");\n }\n }\n if (sb.length() > 1) {\n sb.setLength(sb.length() - 1);\n pw.println(sb.toString());\n } else {\n pw.println(\"()\");\n }\n pw.println(\"mWifiLogProto.numTotalScanResults=\" + this.mWifiLogProto.numTotalScanResults);\n pw.println(\"mWifiLogProto.numOpenNetworkScanResults=\" + this.mWifiLogProto.numOpenNetworkScanResults);\n pw.println(\"mWifiLogProto.numPersonalNetworkScanResults=\" + this.mWifiLogProto.numPersonalNetworkScanResults);\n pw.println(\"mWifiLogProto.numEnterpriseNetworkScanResults=\" + this.mWifiLogProto.numEnterpriseNetworkScanResults);\n pw.println(\"mWifiLogProto.numHiddenNetworkScanResults=\" + this.mWifiLogProto.numHiddenNetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R1NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R1NetworkScanResults);\n pw.println(\"mWifiLogProto.numHotspot2R2NetworkScanResults=\" + this.mWifiLogProto.numHotspot2R2NetworkScanResults);\n pw.println(\"mWifiLogProto.numScans=\" + this.mWifiLogProto.numScans);\n pw.println(\"mWifiLogProto.WifiScoreCount: [0, 5]\");\n for (i = 0; i <= 5; i++) {\n pw.print(this.mWifiScoreCounts.get(i) + \" \");\n }\n pw.print(\"\\n\");\n }\n }\n\n private void consolidateProto(boolean incremental) {\n List events = new ArrayList();\n List rssis = new ArrayList();\n List alertReasons = new ArrayList();\n List scores = new ArrayList();\n synchronized (this.mLock) {\n int i;\n for (ConnectionEvent event : this.mConnectionEventList) {\n if (!(incremental && (this.mCurrentConnectionEvent == event || event.mConnectionEvent.automaticBugReportTaken))) {\n events.add(event.mConnectionEvent);\n if (incremental) {\n event.mConnectionEvent.automaticBugReportTaken = true;\n }\n }\n }\n if (events.size() > 0) {\n this.mWifiLogProto.connectionEvent = (com.android.server.wifi.WifiMetricsProto.ConnectionEvent[]) events.toArray(this.mWifiLogProto.connectionEvent);\n }\n this.mWifiLogProto.scanReturnEntries = new ScanReturnEntry[this.mScanReturnEntries.size()];\n for (i = 0; i < this.mScanReturnEntries.size(); i++) {\n this.mWifiLogProto.scanReturnEntries[i] = new ScanReturnEntry();\n this.mWifiLogProto.scanReturnEntries[i].scanReturnCode = this.mScanReturnEntries.keyAt(i);\n this.mWifiLogProto.scanReturnEntries[i].scanResultsCount = this.mScanReturnEntries.valueAt(i);\n }\n this.mWifiLogProto.wifiSystemStateEntries = new WifiSystemStateEntry[this.mWifiSystemStateEntries.size()];\n for (i = 0; i < this.mWifiSystemStateEntries.size(); i++) {\n this.mWifiLogProto.wifiSystemStateEntries[i] = new WifiSystemStateEntry();\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiState = this.mWifiSystemStateEntries.keyAt(i) / 2;\n this.mWifiLogProto.wifiSystemStateEntries[i].wifiStateCount = this.mWifiSystemStateEntries.valueAt(i);\n this.mWifiLogProto.wifiSystemStateEntries[i].isScreenOn = this.mWifiSystemStateEntries.keyAt(i) % 2 > 0;\n }\n this.mWifiLogProto.recordDurationSec = (int) ((this.mClock.elapsedRealtime() / 1000) - this.mRecordStartTimeSec);\n for (i = 0; i < this.mRssiPollCounts.size(); i++) {\n", "post_mask_code": " RssiPollCount keyVal = new RssiPollCount();\n keyVal.rssi = this.mRssiPollCounts.keyAt(i);\n keyVal.count = this.mRssiPollCounts.valueAt(i);\n rssis.add(keyVal);\n }\n this.mWifiLogProto.rssiPollRssiCount = (RssiPollCount[]) rssis.toArray(this.mWifiLogProto.rssiPollRssiCount);\n for (i = 0; i < this.mWifiAlertReasonCounts.size(); i++) {\n AlertReasonCount keyVal2 = new AlertReasonCount();\n keyVal2.reason = this.mWifiAlertReasonCounts.keyAt(i);\n keyVal2.count = this.mWifiAlertReasonCounts.valueAt(i);\n alertReasons.add(keyVal2);\n }\n this.mWifiLogProto.alertReasonCount = (AlertReasonCount[]) alertReasons.toArray(this.mWifiLogProto.alertReasonCount);\n for (int score = 0; score < this.mWifiScoreCounts.size(); score++) {\n WifiScoreCount keyVal3 = new WifiScoreCount();\n keyVal3.score = this.mWifiScoreCounts.keyAt(score);\n keyVal3.count = this.mWifiScoreCounts.valueAt(score);\n scores.add(keyVal3);\n }\n this.mWifiLogProto.wifiScoreCount = (WifiScoreCount[]) scores.toArray(this.mWifiLogProto.wifiScoreCount);\n }\n }\n\n private void clear() {\n synchronized (this.mLock) {\n this.mConnectionEventList.clear();\n if (this.mCurrentConnectionEvent != null) {\n this.mConnectionEventList.add(this.mCurrentConnectionEvent);\n }\n this.mScanReturnEntries.clear();\n this.mWifiSystemStateEntries.clear();\n this.mRecordStartTimeSec = this.mClock.elapsedRealtime() / 1000;\n this.mRssiPollCounts.clear();\n this.mWifiAlertReasonCounts.clear();\n this.mWifiScoreCounts.clear();\n this.mWifiLogProto.clear();\n }\n }\n\n public void setScreenState(boolean screenOn) {\n synchronized (this.mLock) {\n this.mScreenOn = screenOn;\n }\n }\n\n public void setWifiState(int wifiState) {\n synchronized (this.mLock) {\n this.mWifiState = wifiState;\n }\n }\n}\n"} {"task_id": "Java_698", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/metron/metron-interface/metron-rest-client/src/main/java/org/apache/metron/rest/model/pcap/Proto.java", "mask_start_position": 1296, "mask_end_position": 1320, "canonical_solution": "public String getHide() ", "pre_mask_code": "package org.apache.metron.rest.model.pcap;\n\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;\nimport java.util.List;\nimport java.util.Objects;\n\npublic class Proto {\n\n @JacksonXmlProperty(isAttribute = true)\n private String name;\n\n @JacksonXmlProperty(isAttribute = true)\n private String pos;\n\n @JacksonXmlProperty(isAttribute = true)\n private String showname;\n\n @JacksonXmlProperty(isAttribute = true)\n private String size;\n\n @JacksonXmlProperty(isAttribute = true)\n private String hide;\n\n @JacksonXmlProperty(localName = \"field\")\n @JacksonXmlElementWrapper(useWrapping = false)\n private List fields;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getPos() {\n return pos;\n }\n\n public void setPos(String pos) {\n this.pos = pos;\n }\n\n public String getShowname() {\n return showname;\n }\n\n public void setShowname(String showname) {\n this.showname = showname;\n }\n\n public String getSize() {\n return size;\n }\n\n public void setSize(String size) {\n this.size = size;\n }\n\n ", "post_mask_code": "{\n return hide;\n }\n\n public void setHide(String hide) {\n this.hide = hide;\n }\n\n public List getFields() {\n return fields;\n }\n\n public void setFields(List fields) {\n this.fields = fields;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n Proto proto = (Proto) o;\n return Objects.equals(name, proto.name) && Objects.equals(pos, proto.pos) && Objects.equals(showname, proto.showname) && Objects.equals(size, proto.size) && Objects.equals(hide, proto.hide) && Objects.equals(fields, proto.fields);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, pos, showname, size, hide, fields);\n }\n}\n"} {"task_id": "Java_699", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/metron/metron-interface/metron-rest-client/src/main/java/org/apache/metron/rest/model/pcap/Proto.java", "mask_start_position": 1535, "mask_end_position": 1572, "canonical_solution": "{\n this.fields = fields;\n }", "pre_mask_code": "package org.apache.metron.rest.model.pcap;\n\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;\nimport java.util.List;\nimport java.util.Objects;\n\npublic class Proto {\n\n @JacksonXmlProperty(isAttribute = true)\n private String name;\n\n @JacksonXmlProperty(isAttribute = true)\n private String pos;\n\n @JacksonXmlProperty(isAttribute = true)\n private String showname;\n\n @JacksonXmlProperty(isAttribute = true)\n private String size;\n\n @JacksonXmlProperty(isAttribute = true)\n private String hide;\n\n @JacksonXmlProperty(localName = \"field\")\n @JacksonXmlElementWrapper(useWrapping = false)\n private List fields;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getPos() {\n return pos;\n }\n\n public void setPos(String pos) {\n this.pos = pos;\n }\n\n public String getShowname() {\n return showname;\n }\n\n public void setShowname(String showname) {\n this.showname = showname;\n }\n\n public String getSize() {\n return size;\n }\n\n public void setSize(String size) {\n this.size = size;\n }\n\n public String getHide() {\n return hide;\n }\n\n public void setHide(String hide) {\n this.hide = hide;\n }\n\n public List getFields() {\n return fields;\n }\n\n public void setFields(List fields) ", "post_mask_code": "\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n Proto proto = (Proto) o;\n return Objects.equals(name, proto.name) && Objects.equals(pos, proto.pos) && Objects.equals(showname, proto.showname) && Objects.equals(size, proto.size) && Objects.equals(hide, proto.hide) && Objects.equals(fields, proto.fields);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, pos, showname, size, hide, fields);\n }\n}\n"} {"task_id": "Java_700", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/metron/metron-interface/metron-rest-client/src/main/java/org/apache/metron/rest/model/pcap/Proto.java", "mask_start_position": 1625, "mask_end_position": 1673, "canonical_solution": "\n if (this == o)\n return true;", "pre_mask_code": "package org.apache.metron.rest.model.pcap;\n\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;\nimport java.util.List;\nimport java.util.Objects;\n\npublic class Proto {\n\n @JacksonXmlProperty(isAttribute = true)\n private String name;\n\n @JacksonXmlProperty(isAttribute = true)\n private String pos;\n\n @JacksonXmlProperty(isAttribute = true)\n private String showname;\n\n @JacksonXmlProperty(isAttribute = true)\n private String size;\n\n @JacksonXmlProperty(isAttribute = true)\n private String hide;\n\n @JacksonXmlProperty(localName = \"field\")\n @JacksonXmlElementWrapper(useWrapping = false)\n private List fields;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getPos() {\n return pos;\n }\n\n public void setPos(String pos) {\n this.pos = pos;\n }\n\n public String getShowname() {\n return showname;\n }\n\n public void setShowname(String showname) {\n this.showname = showname;\n }\n\n public String getSize() {\n return size;\n }\n\n public void setSize(String size) {\n this.size = size;\n }\n\n public String getHide() {\n return hide;\n }\n\n public void setHide(String hide) {\n this.hide = hide;\n }\n\n public List getFields() {\n return fields;\n }\n\n public void setFields(List fields) {\n this.fields = fields;\n }\n\n @Override\n public boolean equals(Object o) {", "post_mask_code": "\n if (o == null || getClass() != o.getClass())\n return false;\n Proto proto = (Proto) o;\n return Objects.equals(name, proto.name) && Objects.equals(pos, proto.pos) && Objects.equals(showname, proto.showname) && Objects.equals(size, proto.size) && Objects.equals(hide, proto.hide) && Objects.equals(fields, proto.fields);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, pos, showname, size, hide, fields);\n }\n}\n"} {"task_id": "Java_701", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/metron/metron-interface/metron-rest-client/src/main/java/org/apache/metron/rest/model/pcap/Proto.java", "mask_start_position": 1682, "mask_end_position": 1785, "canonical_solution": "if (o == null || getClass() != o.getClass())\n return false;\n Proto proto = (Proto) o;", "pre_mask_code": "package org.apache.metron.rest.model.pcap;\n\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;\nimport java.util.List;\nimport java.util.Objects;\n\npublic class Proto {\n\n @JacksonXmlProperty(isAttribute = true)\n private String name;\n\n @JacksonXmlProperty(isAttribute = true)\n private String pos;\n\n @JacksonXmlProperty(isAttribute = true)\n private String showname;\n\n @JacksonXmlProperty(isAttribute = true)\n private String size;\n\n @JacksonXmlProperty(isAttribute = true)\n private String hide;\n\n @JacksonXmlProperty(localName = \"field\")\n @JacksonXmlElementWrapper(useWrapping = false)\n private List fields;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getPos() {\n return pos;\n }\n\n public void setPos(String pos) {\n this.pos = pos;\n }\n\n public String getShowname() {\n return showname;\n }\n\n public void setShowname(String showname) {\n this.showname = showname;\n }\n\n public String getSize() {\n return size;\n }\n\n public void setSize(String size) {\n this.size = size;\n }\n\n public String getHide() {\n return hide;\n }\n\n public void setHide(String hide) {\n this.hide = hide;\n }\n\n public List getFields() {\n return fields;\n }\n\n public void setFields(List fields) {\n this.fields = fields;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n ", "post_mask_code": "\n return Objects.equals(name, proto.name) && Objects.equals(pos, proto.pos) && Objects.equals(showname, proto.showname) && Objects.equals(size, proto.size) && Objects.equals(hide, proto.hide) && Objects.equals(fields, proto.fields);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, pos, showname, size, hide, fields);\n }\n}\n"} {"task_id": "Java_702", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/metron/metron-interface/metron-rest-client/src/main/java/org/apache/metron/rest/model/pcap/Proto.java", "mask_start_position": 1794, "mask_end_position": 2030, "canonical_solution": "return Objects.equals(name, proto.name) && Objects.equals(pos, proto.pos) && Objects.equals(showname, proto.showname) && Objects.equals(size, proto.size) && Objects.equals(hide, proto.hide) && Objects.equals(fields, proto.fields);\n }", "pre_mask_code": "package org.apache.metron.rest.model.pcap;\n\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;\nimport java.util.List;\nimport java.util.Objects;\n\npublic class Proto {\n\n @JacksonXmlProperty(isAttribute = true)\n private String name;\n\n @JacksonXmlProperty(isAttribute = true)\n private String pos;\n\n @JacksonXmlProperty(isAttribute = true)\n private String showname;\n\n @JacksonXmlProperty(isAttribute = true)\n private String size;\n\n @JacksonXmlProperty(isAttribute = true)\n private String hide;\n\n @JacksonXmlProperty(localName = \"field\")\n @JacksonXmlElementWrapper(useWrapping = false)\n private List fields;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getPos() {\n return pos;\n }\n\n public void setPos(String pos) {\n this.pos = pos;\n }\n\n public String getShowname() {\n return showname;\n }\n\n public void setShowname(String showname) {\n this.showname = showname;\n }\n\n public String getSize() {\n return size;\n }\n\n public void setSize(String size) {\n this.size = size;\n }\n\n public String getHide() {\n return hide;\n }\n\n public void setHide(String hide) {\n this.hide = hide;\n }\n\n public List getFields() {\n return fields;\n }\n\n public void setFields(List fields) {\n this.fields = fields;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n Proto proto = (Proto) o;\n ", "post_mask_code": "\n\n @Override\n public int hashCode() {\n return Objects.hash(name, pos, showname, size, hide, fields);\n }\n}\n"} {"task_id": "Java_703", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/metron/metron-interface/metron-rest-client/src/main/java/org/apache/metron/rest/model/pcap/Proto.java", "mask_start_position": 1473, "mask_end_position": 1481, "canonical_solution": " fields;", "pre_mask_code": "package org.apache.metron.rest.model.pcap;\n\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;\nimport java.util.List;\nimport java.util.Objects;\n\npublic class Proto {\n\n @JacksonXmlProperty(isAttribute = true)\n private String name;\n\n @JacksonXmlProperty(isAttribute = true)\n private String pos;\n\n @JacksonXmlProperty(isAttribute = true)\n private String showname;\n\n @JacksonXmlProperty(isAttribute = true)\n private String size;\n\n @JacksonXmlProperty(isAttribute = true)\n private String hide;\n\n @JacksonXmlProperty(localName = \"field\")\n @JacksonXmlElementWrapper(useWrapping = false)\n private List fields;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getPos() {\n return pos;\n }\n\n public void setPos(String pos) {\n this.pos = pos;\n }\n\n public String getShowname() {\n return showname;\n }\n\n public void setShowname(String showname) {\n this.showname = showname;\n }\n\n public String getSize() {\n return size;\n }\n\n public void setSize(String size) {\n this.size = size;\n }\n\n public String getHide() {\n return hide;\n }\n\n public void setHide(String hide) {\n this.hide = hide;\n }\n\n public List getFields() {\n return", "post_mask_code": "\n }\n\n public void setFields(List fields) {\n this.fields = fields;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n Proto proto = (Proto) o;\n return Objects.equals(name, proto.name) && Objects.equals(pos, proto.pos) && Objects.equals(showname, proto.showname) && Objects.equals(size, proto.size) && Objects.equals(hide, proto.hide) && Objects.equals(fields, proto.fields);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, pos, showname, size, hide, fields);\n }\n}\n"} {"task_id": "Java_704", "language": "Java", "task_type": "if_statement", "source_file": "java/github/apache/metron/metron-interface/metron-rest-client/src/main/java/org/apache/metron/rest/model/pcap/Proto.java", "mask_start_position": 1634, "mask_end_position": 1673, "canonical_solution": "if (this == o)\n return true;", "pre_mask_code": "package org.apache.metron.rest.model.pcap;\n\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;\nimport java.util.List;\nimport java.util.Objects;\n\npublic class Proto {\n\n @JacksonXmlProperty(isAttribute = true)\n private String name;\n\n @JacksonXmlProperty(isAttribute = true)\n private String pos;\n\n @JacksonXmlProperty(isAttribute = true)\n private String showname;\n\n @JacksonXmlProperty(isAttribute = true)\n private String size;\n\n @JacksonXmlProperty(isAttribute = true)\n private String hide;\n\n @JacksonXmlProperty(localName = \"field\")\n @JacksonXmlElementWrapper(useWrapping = false)\n private List fields;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getPos() {\n return pos;\n }\n\n public void setPos(String pos) {\n this.pos = pos;\n }\n\n public String getShowname() {\n return showname;\n }\n\n public void setShowname(String showname) {\n this.showname = showname;\n }\n\n public String getSize() {\n return size;\n }\n\n public void setSize(String size) {\n this.size = size;\n }\n\n public String getHide() {\n return hide;\n }\n\n public void setHide(String hide) {\n this.hide = hide;\n }\n\n public List getFields() {\n return fields;\n }\n\n public void setFields(List fields) {\n this.fields = fields;\n }\n\n @Override\n public boolean equals(Object o) {\n ", "post_mask_code": "\n if (o == null || getClass() != o.getClass())\n return false;\n Proto proto = (Proto) o;\n return Objects.equals(name, proto.name) && Objects.equals(pos, proto.pos) && Objects.equals(showname, proto.showname) && Objects.equals(size, proto.size) && Objects.equals(hide, proto.hide) && Objects.equals(fields, proto.fields);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, pos, showname, size, hide, fields);\n }\n}\n"} {"task_id": "Java_705", "language": "Java", "task_type": "empty", "source_file": "java/github/apache/metron/metron-interface/metron-rest-client/src/main/java/org/apache/metron/rest/model/pcap/Proto.java", "mask_start_position": 1124, "mask_end_position": 1124, "canonical_solution": "", "pre_mask_code": "package org.apache.metron.rest.model.pcap;\n\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;\nimport com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;\nimport java.util.List;\nimport java.util.Objects;\n\npublic class Proto {\n\n @JacksonXmlProperty(isAttribute = true)\n private String name;\n\n @JacksonXmlProperty(isAttribute = true)\n private String pos;\n\n @JacksonXmlProperty(isAttribute = true)\n private String showname;\n\n @JacksonXmlProperty(isAttribute = true)\n private String size;\n\n @JacksonXmlProperty(isAttribute = true)\n private String hide;\n\n @JacksonXmlProperty(localName = \"field\")\n @JacksonXmlElementWrapper(useWrapping = false)\n private List fields;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getPos() {\n return pos;\n }\n\n public void setPos(String pos) {\n this.pos = pos;\n }\n\n public String getShowname() {\n return showname;\n }\n\n public void setShowname(String showname) {\n ", "post_mask_code": " this.showname = showname;\n }\n\n public String getSize() {\n return size;\n }\n\n public void setSize(String size) {\n this.size = size;\n }\n\n public String getHide() {\n return hide;\n }\n\n public void setHide(String hide) {\n this.hide = hide;\n }\n\n public List getFields() {\n return fields;\n }\n\n public void setFields(List fields) {\n this.fields = fields;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n Proto proto = (Proto) o;\n return Objects.equals(name, proto.name) && Objects.equals(pos, proto.pos) && Objects.equals(showname, proto.showname) && Objects.equals(size, proto.size) && Objects.equals(hide, proto.hide) && Objects.equals(fields, proto.fields);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, pos, showname, size, hide, fields);\n }\n}\n"} {"task_id": "Java_706", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Spoutcraft/Spoutcraft/src/main/java/org/spoutcraft/client/gui/minimap/ColorToggleCheckBox.java", "mask_start_position": 410, "mask_end_position": 452, "canonical_solution": "@Override\n public void onButtonClick() ", "pre_mask_code": "/*\n * This file is part of Spoutcraft.\n *\n */\npackage org.spoutcraft.client.gui.minimap;\n\nimport org.spoutcraft.api.gui.GenericCheckBox;\n\npublic class ColorToggleCheckBox extends GenericCheckBox {\n\n public ColorToggleCheckBox() {\n super(\"Black and White\");\n setChecked(!MinimapConfig.getInstance().isColor());\n setTooltip(\"Black and White\\nRemoves color from the minimap.\");\n }\n\n ", "post_mask_code": "{\n MinimapConfig.getInstance().setColor(!isChecked());\n }\n}\n"} {"task_id": "Java_707", "language": "Java", "task_type": "method_body", "source_file": "java/github/Spoutcraft/Spoutcraft/src/main/java/org/spoutcraft/client/gui/minimap/ColorToggleCheckBox.java", "mask_start_position": 452, "mask_end_position": 519, "canonical_solution": "{\n MinimapConfig.getInstance().setColor(!isChecked());\n }", "pre_mask_code": "/*\n * This file is part of Spoutcraft.\n *\n */\npackage org.spoutcraft.client.gui.minimap;\n\nimport org.spoutcraft.api.gui.GenericCheckBox;\n\npublic class ColorToggleCheckBox extends GenericCheckBox {\n\n public ColorToggleCheckBox() {\n super(\"Black and White\");\n setChecked(!MinimapConfig.getInstance().isColor());\n setTooltip(\"Black and White\\nRemoves color from the minimap.\");\n }\n\n @Override\n public void onButtonClick() ", "post_mask_code": "\n}\n"} {"task_id": "Java_708", "language": "Java", "task_type": "single_line", "source_file": "java/github/Spoutcraft/Spoutcraft/src/main/java/org/spoutcraft/client/gui/minimap/ColorToggleCheckBox.java", "mask_start_position": 483, "mask_end_position": 513, "canonical_solution": "ance().setColor(!isChecked());", "pre_mask_code": "/*\n * This file is part of Spoutcraft.\n *\n */\npackage org.spoutcraft.client.gui.minimap;\n\nimport org.spoutcraft.api.gui.GenericCheckBox;\n\npublic class ColorToggleCheckBox extends GenericCheckBox {\n\n public ColorToggleCheckBox() {\n super(\"Black and White\");\n setChecked(!MinimapConfig.getInstance().isColor());\n setTooltip(\"Black and White\\nRemoves color from the minimap.\");\n }\n\n @Override\n public void onButtonClick() {\n MinimapConfig.getInst", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_709", "language": "Java", "task_type": "empty", "source_file": "java/github/Spoutcraft/Spoutcraft/src/main/java/org/spoutcraft/client/gui/minimap/ColorToggleCheckBox.java", "mask_start_position": 114, "mask_end_position": 114, "canonical_solution": "", "pre_mask_code": "/*\n * This file is part of Spoutcraft.\n *\n */\npackage org.spoutcraft.client.gui.minimap;\n\nimport org.spoutcraft.ap", "post_mask_code": "i.gui.GenericCheckBox;\n\npublic class ColorToggleCheckBox extends GenericCheckBox {\n\n public ColorToggleCheckBox() {\n super(\"Black and White\");\n setChecked(!MinimapConfig.getInstance().isColor());\n setTooltip(\"Black and White\\nRemoves color from the minimap.\");\n }\n\n @Override\n public void onButtonClick() {\n MinimapConfig.getInstance().setColor(!isChecked());\n }\n}\n"} {"task_id": "Java_710", "language": "Java", "task_type": "method_signature", "source_file": "java/github/hawkular/hawkular-metrics/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/TempTablesCleaner.java", "mask_start_position": 1085, "mask_end_position": 1103, "canonical_solution": "public void run() ", "pre_mask_code": "package org.hawkular.metrics.core.service;\n\nimport java.util.concurrent.TimeUnit;\nimport org.hawkular.rx.cassandra.driver.RxSession;\nimport org.jboss.logging.Logger;\nimport org.joda.time.Days;\nimport com.datastax.driver.core.PreparedStatement;\nimport rx.Observable;\nimport rx.schedulers.Schedulers;\n\n/**\n * @author jsanda\n */\npublic class TempTablesCleaner {\n\n private static Logger logger = Logger.getLogger(TempTablesCleaner.class);\n\n private RxSession session;\n\n private PreparedStatement findTables;\n\n private long ttl;\n\n private DataAccessImpl dataAccess;\n\n private volatile boolean finished;\n\n private static final String DROP_TABLE_CQL = \"DROP TABLE IF EXISTS %s\";\n\n public TempTablesCleaner(RxSession session, DataAccessImpl dataAccess, String keyspace, int ttl) {\n this.session = session;\n this.dataAccess = dataAccess;\n this.ttl = Days.days(ttl).toStandardDuration().getMillis();\n findTables = session.getSession().prepare(\"SELECT table_name FROM system_schema.tables WHERE keyspace_name = '\" + keyspace + \"'\");\n }\n\n ", "post_mask_code": "{\n logger.info(\"Checking for expired temp tables\");\n Observable.interval(1, TimeUnit.DAYS, Schedulers.io()).takeUntil(i -> finished).flatMap(i -> session.execute(findTables.bind())).compose(applyRetryPolicy()).flatMap(Observable::from).filter(row -> row.getString(0).startsWith(DataAccessImpl.TEMP_TABLE_NAME_PROTOTYPE)).map(row -> row.getString(0)).filter(this::isTableExpired).flatMap(this::dropTable).subscribe(table -> logger.infof(\"Dropped table %s\", table), t -> logger.warn(\"Cleaning temp tables failed\", t), () -> logger.infof(\"Finished cleaning expired temp tables\"));\n }\n\n public void shutdown() {\n finished = true;\n }\n\n private Observable.Transformer applyRetryPolicy() {\n return tObservable -> tObservable.retryWhen(observable -> {\n Integer maxRetries = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-retries\", 10);\n Integer maxDelay = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-delay\", 300);\n Observable range = Observable.range(1, maxRetries);\n Observable> zipWith = observable.zipWith(range, (t, i) -> {\n int delay = Math.min((int) Math.pow(2, i), maxDelay);\n logger.debugf(t, \"The findTables query failed. Attempting retry # %d seconds\", delay);\n return Observable.timer(delay, TimeUnit.SECONDS).onBackpressureDrop();\n });\n return Observable.merge(zipWith);\n });\n }\n\n private boolean isTableExpired(String table) {\n Long timestamp = dataAccess.tableToMapKey(table);\n return timestamp < (System.currentTimeMillis() - ttl);\n }\n\n private Observable dropTable(String table) {\n return session.execute(String.format(DROP_TABLE_CQL, table)).map(resultSet -> table).onErrorResumeNext(t -> {\n // If there is an error, we do not retry because it is possible that the table has already been\n // dropped. We will instead wait until findTables runs again and retry dropping the table then\n // if dropping it did indeed fail for some reason.\n logger.infof(t, \"Failed to drop %s\", table);\n return Observable.empty();\n });\n }\n}\n"} {"task_id": "Java_711", "language": "Java", "task_type": "method_body", "source_file": "java/github/hawkular/hawkular-metrics/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/TempTablesCleaner.java", "mask_start_position": 2659, "mask_end_position": 2787, "canonical_solution": "{\n Long timestamp = dataAccess.tableToMapKey(table);\n return timestamp < (System.currentTimeMillis() - ttl);\n }", "pre_mask_code": "package org.hawkular.metrics.core.service;\n\nimport java.util.concurrent.TimeUnit;\nimport org.hawkular.rx.cassandra.driver.RxSession;\nimport org.jboss.logging.Logger;\nimport org.joda.time.Days;\nimport com.datastax.driver.core.PreparedStatement;\nimport rx.Observable;\nimport rx.schedulers.Schedulers;\n\n/**\n * @author jsanda\n */\npublic class TempTablesCleaner {\n\n private static Logger logger = Logger.getLogger(TempTablesCleaner.class);\n\n private RxSession session;\n\n private PreparedStatement findTables;\n\n private long ttl;\n\n private DataAccessImpl dataAccess;\n\n private volatile boolean finished;\n\n private static final String DROP_TABLE_CQL = \"DROP TABLE IF EXISTS %s\";\n\n public TempTablesCleaner(RxSession session, DataAccessImpl dataAccess, String keyspace, int ttl) {\n this.session = session;\n this.dataAccess = dataAccess;\n this.ttl = Days.days(ttl).toStandardDuration().getMillis();\n findTables = session.getSession().prepare(\"SELECT table_name FROM system_schema.tables WHERE keyspace_name = '\" + keyspace + \"'\");\n }\n\n public void run() {\n logger.info(\"Checking for expired temp tables\");\n Observable.interval(1, TimeUnit.DAYS, Schedulers.io()).takeUntil(i -> finished).flatMap(i -> session.execute(findTables.bind())).compose(applyRetryPolicy()).flatMap(Observable::from).filter(row -> row.getString(0).startsWith(DataAccessImpl.TEMP_TABLE_NAME_PROTOTYPE)).map(row -> row.getString(0)).filter(this::isTableExpired).flatMap(this::dropTable).subscribe(table -> logger.infof(\"Dropped table %s\", table), t -> logger.warn(\"Cleaning temp tables failed\", t), () -> logger.infof(\"Finished cleaning expired temp tables\"));\n }\n\n public void shutdown() {\n finished = true;\n }\n\n private Observable.Transformer applyRetryPolicy() {\n return tObservable -> tObservable.retryWhen(observable -> {\n Integer maxRetries = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-retries\", 10);\n Integer maxDelay = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-delay\", 300);\n Observable range = Observable.range(1, maxRetries);\n Observable> zipWith = observable.zipWith(range, (t, i) -> {\n int delay = Math.min((int) Math.pow(2, i), maxDelay);\n logger.debugf(t, \"The findTables query failed. Attempting retry # %d seconds\", delay);\n return Observable.timer(delay, TimeUnit.SECONDS).onBackpressureDrop();\n });\n return Observable.merge(zipWith);\n });\n }\n\n private boolean isTableExpired(String table) ", "post_mask_code": "\n\n private Observable dropTable(String table) {\n return session.execute(String.format(DROP_TABLE_CQL, table)).map(resultSet -> table).onErrorResumeNext(t -> {\n // If there is an error, we do not retry because it is possible that the table has already been\n // dropped. We will instead wait until findTables runs again and retry dropping the table then\n // if dropping it did indeed fail for some reason.\n logger.infof(t, \"Failed to drop %s\", table);\n return Observable.empty();\n });\n }\n}\n"} {"task_id": "Java_712", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/hawkular/hawkular-metrics/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/TempTablesCleaner.java", "mask_start_position": 2845, "mask_end_position": 2845, "canonical_solution": "", "pre_mask_code": "package org.hawkular.metrics.core.service;\n\nimport java.util.concurrent.TimeUnit;\nimport org.hawkular.rx.cassandra.driver.RxSession;\nimport org.jboss.logging.Logger;\nimport org.joda.time.Days;\nimport com.datastax.driver.core.PreparedStatement;\nimport rx.Observable;\nimport rx.schedulers.Schedulers;\n\n/**\n * @author jsanda\n */\npublic class TempTablesCleaner {\n\n private static Logger logger = Logger.getLogger(TempTablesCleaner.class);\n\n private RxSession session;\n\n private PreparedStatement findTables;\n\n private long ttl;\n\n private DataAccessImpl dataAccess;\n\n private volatile boolean finished;\n\n private static final String DROP_TABLE_CQL = \"DROP TABLE IF EXISTS %s\";\n\n public TempTablesCleaner(RxSession session, DataAccessImpl dataAccess, String keyspace, int ttl) {\n this.session = session;\n this.dataAccess = dataAccess;\n this.ttl = Days.days(ttl).toStandardDuration().getMillis();\n findTables = session.getSession().prepare(\"SELECT table_name FROM system_schema.tables WHERE keyspace_name = '\" + keyspace + \"'\");\n }\n\n public void run() {\n logger.info(\"Checking for expired temp tables\");\n Observable.interval(1, TimeUnit.DAYS, Schedulers.io()).takeUntil(i -> finished).flatMap(i -> session.execute(findTables.bind())).compose(applyRetryPolicy()).flatMap(Observable::from).filter(row -> row.getString(0).startsWith(DataAccessImpl.TEMP_TABLE_NAME_PROTOTYPE)).map(row -> row.getString(0)).filter(this::isTableExpired).flatMap(this::dropTable).subscribe(table -> logger.infof(\"Dropped table %s\", table), t -> logger.warn(\"Cleaning temp tables failed\", t), () -> logger.infof(\"Finished cleaning expired temp tables\"));\n }\n\n public void shutdown() {\n finished = true;\n }\n\n private Observable.Transformer applyRetryPolicy() {\n return tObservable -> tObservable.retryWhen(observable -> {\n Integer maxRetries = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-retries\", 10);\n Integer maxDelay = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-delay\", 300);\n Observable range = Observable.range(1, maxRetries);\n Observable> zipWith = observable.zipWith(range, (t, i) -> {\n int delay = Math.min((int) Math.pow(2, i), maxDelay);\n logger.debugf(t, \"The findTables query failed. Attempting retry # %d seconds\", delay);\n return Observable.timer(delay, TimeUnit.SECONDS).onBackpressureDrop();\n });\n return Observable.merge(zipWith);\n });\n }\n\n private boolean isTableExpired(String table) {\n Long timestamp = dataAccess.tableToMapKey(table);\n return timestamp < (System.currentTimeMillis() - ttl);\n }\n\n private Observable dropTable(String table) {", "post_mask_code": "\n return session.execute(String.format(DROP_TABLE_CQL, table)).map(resultSet -> table).onErrorResumeNext(t -> {\n // If there is an error, we do not retry because it is possible that the table has already been\n // dropped. We will instead wait until findTables runs again and retry dropping the table then\n // if dropping it did indeed fail for some reason.\n logger.infof(t, \"Failed to drop %s\", table);\n return Observable.empty();\n });\n }\n}\n"} {"task_id": "Java_713", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/hawkular/hawkular-metrics/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/TempTablesCleaner.java", "mask_start_position": 2854, "mask_end_position": 3349, "canonical_solution": "return session.execute(String.format(DROP_TABLE_CQL, table)).map(resultSet -> table).onErrorResumeNext(t -> {\n // If there is an error, we do not retry because it is possible that the table has already been\n // dropped. We will instead wait until findTables runs again and retry dropping the table then\n // if dropping it did indeed fail for some reason.\n logger.infof(t, \"Failed to drop %s\", table);\n return Observable.empty();\n });", "pre_mask_code": "package org.hawkular.metrics.core.service;\n\nimport java.util.concurrent.TimeUnit;\nimport org.hawkular.rx.cassandra.driver.RxSession;\nimport org.jboss.logging.Logger;\nimport org.joda.time.Days;\nimport com.datastax.driver.core.PreparedStatement;\nimport rx.Observable;\nimport rx.schedulers.Schedulers;\n\n/**\n * @author jsanda\n */\npublic class TempTablesCleaner {\n\n private static Logger logger = Logger.getLogger(TempTablesCleaner.class);\n\n private RxSession session;\n\n private PreparedStatement findTables;\n\n private long ttl;\n\n private DataAccessImpl dataAccess;\n\n private volatile boolean finished;\n\n private static final String DROP_TABLE_CQL = \"DROP TABLE IF EXISTS %s\";\n\n public TempTablesCleaner(RxSession session, DataAccessImpl dataAccess, String keyspace, int ttl) {\n this.session = session;\n this.dataAccess = dataAccess;\n this.ttl = Days.days(ttl).toStandardDuration().getMillis();\n findTables = session.getSession().prepare(\"SELECT table_name FROM system_schema.tables WHERE keyspace_name = '\" + keyspace + \"'\");\n }\n\n public void run() {\n logger.info(\"Checking for expired temp tables\");\n Observable.interval(1, TimeUnit.DAYS, Schedulers.io()).takeUntil(i -> finished).flatMap(i -> session.execute(findTables.bind())).compose(applyRetryPolicy()).flatMap(Observable::from).filter(row -> row.getString(0).startsWith(DataAccessImpl.TEMP_TABLE_NAME_PROTOTYPE)).map(row -> row.getString(0)).filter(this::isTableExpired).flatMap(this::dropTable).subscribe(table -> logger.infof(\"Dropped table %s\", table), t -> logger.warn(\"Cleaning temp tables failed\", t), () -> logger.infof(\"Finished cleaning expired temp tables\"));\n }\n\n public void shutdown() {\n finished = true;\n }\n\n private Observable.Transformer applyRetryPolicy() {\n return tObservable -> tObservable.retryWhen(observable -> {\n Integer maxRetries = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-retries\", 10);\n Integer maxDelay = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-delay\", 300);\n Observable range = Observable.range(1, maxRetries);\n Observable> zipWith = observable.zipWith(range, (t, i) -> {\n int delay = Math.min((int) Math.pow(2, i), maxDelay);\n logger.debugf(t, \"The findTables query failed. Attempting retry # %d seconds\", delay);\n return Observable.timer(delay, TimeUnit.SECONDS).onBackpressureDrop();\n });\n return Observable.merge(zipWith);\n });\n }\n\n private boolean isTableExpired(String table) {\n Long timestamp = dataAccess.tableToMapKey(table);\n return timestamp < (System.currentTimeMillis() - ttl);\n }\n\n private Observable dropTable(String table) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_714", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/hawkular/hawkular-metrics/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/TempTablesCleaner.java", "mask_start_position": 3354, "mask_end_position": 3355, "canonical_solution": "}", "pre_mask_code": "package org.hawkular.metrics.core.service;\n\nimport java.util.concurrent.TimeUnit;\nimport org.hawkular.rx.cassandra.driver.RxSession;\nimport org.jboss.logging.Logger;\nimport org.joda.time.Days;\nimport com.datastax.driver.core.PreparedStatement;\nimport rx.Observable;\nimport rx.schedulers.Schedulers;\n\n/**\n * @author jsanda\n */\npublic class TempTablesCleaner {\n\n private static Logger logger = Logger.getLogger(TempTablesCleaner.class);\n\n private RxSession session;\n\n private PreparedStatement findTables;\n\n private long ttl;\n\n private DataAccessImpl dataAccess;\n\n private volatile boolean finished;\n\n private static final String DROP_TABLE_CQL = \"DROP TABLE IF EXISTS %s\";\n\n public TempTablesCleaner(RxSession session, DataAccessImpl dataAccess, String keyspace, int ttl) {\n this.session = session;\n this.dataAccess = dataAccess;\n this.ttl = Days.days(ttl).toStandardDuration().getMillis();\n findTables = session.getSession().prepare(\"SELECT table_name FROM system_schema.tables WHERE keyspace_name = '\" + keyspace + \"'\");\n }\n\n public void run() {\n logger.info(\"Checking for expired temp tables\");\n Observable.interval(1, TimeUnit.DAYS, Schedulers.io()).takeUntil(i -> finished).flatMap(i -> session.execute(findTables.bind())).compose(applyRetryPolicy()).flatMap(Observable::from).filter(row -> row.getString(0).startsWith(DataAccessImpl.TEMP_TABLE_NAME_PROTOTYPE)).map(row -> row.getString(0)).filter(this::isTableExpired).flatMap(this::dropTable).subscribe(table -> logger.infof(\"Dropped table %s\", table), t -> logger.warn(\"Cleaning temp tables failed\", t), () -> logger.infof(\"Finished cleaning expired temp tables\"));\n }\n\n public void shutdown() {\n finished = true;\n }\n\n private Observable.Transformer applyRetryPolicy() {\n return tObservable -> tObservable.retryWhen(observable -> {\n Integer maxRetries = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-retries\", 10);\n Integer maxDelay = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-delay\", 300);\n Observable range = Observable.range(1, maxRetries);\n Observable> zipWith = observable.zipWith(range, (t, i) -> {\n int delay = Math.min((int) Math.pow(2, i), maxDelay);\n logger.debugf(t, \"The findTables query failed. Attempting retry # %d seconds\", delay);\n return Observable.timer(delay, TimeUnit.SECONDS).onBackpressureDrop();\n });\n return Observable.merge(zipWith);\n });\n }\n\n private boolean isTableExpired(String table) {\n Long timestamp = dataAccess.tableToMapKey(table);\n return timestamp < (System.currentTimeMillis() - ttl);\n }\n\n private Observable dropTable(String table) {\n return session.execute(String.format(DROP_TABLE_CQL, table)).map(resultSet -> table).onErrorResumeNext(t -> {\n // If there is an error, we do not retry because it is possible that the table has already been\n // dropped. We will instead wait until findTables runs again and retry dropping the table then\n // if dropping it did indeed fail for some reason.\n logger.infof(t, \"Failed to drop %s\", table);\n return Observable.empty();\n });\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_715", "language": "Java", "task_type": "single_line", "source_file": "java/github/hawkular/hawkular-metrics/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/TempTablesCleaner.java", "mask_start_position": 1117, "mask_end_position": 1161, "canonical_solution": "er.info(\"Checking for expired temp tables\");", "pre_mask_code": "package org.hawkular.metrics.core.service;\n\nimport java.util.concurrent.TimeUnit;\nimport org.hawkular.rx.cassandra.driver.RxSession;\nimport org.jboss.logging.Logger;\nimport org.joda.time.Days;\nimport com.datastax.driver.core.PreparedStatement;\nimport rx.Observable;\nimport rx.schedulers.Schedulers;\n\n/**\n * @author jsanda\n */\npublic class TempTablesCleaner {\n\n private static Logger logger = Logger.getLogger(TempTablesCleaner.class);\n\n private RxSession session;\n\n private PreparedStatement findTables;\n\n private long ttl;\n\n private DataAccessImpl dataAccess;\n\n private volatile boolean finished;\n\n private static final String DROP_TABLE_CQL = \"DROP TABLE IF EXISTS %s\";\n\n public TempTablesCleaner(RxSession session, DataAccessImpl dataAccess, String keyspace, int ttl) {\n this.session = session;\n this.dataAccess = dataAccess;\n this.ttl = Days.days(ttl).toStandardDuration().getMillis();\n findTables = session.getSession().prepare(\"SELECT table_name FROM system_schema.tables WHERE keyspace_name = '\" + keyspace + \"'\");\n }\n\n public void run() {\n logg", "post_mask_code": "\n Observable.interval(1, TimeUnit.DAYS, Schedulers.io()).takeUntil(i -> finished).flatMap(i -> session.execute(findTables.bind())).compose(applyRetryPolicy()).flatMap(Observable::from).filter(row -> row.getString(0).startsWith(DataAccessImpl.TEMP_TABLE_NAME_PROTOTYPE)).map(row -> row.getString(0)).filter(this::isTableExpired).flatMap(this::dropTable).subscribe(table -> logger.infof(\"Dropped table %s\", table), t -> logger.warn(\"Cleaning temp tables failed\", t), () -> logger.infof(\"Finished cleaning expired temp tables\"));\n }\n\n public void shutdown() {\n finished = true;\n }\n\n private Observable.Transformer applyRetryPolicy() {\n return tObservable -> tObservable.retryWhen(observable -> {\n Integer maxRetries = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-retries\", 10);\n Integer maxDelay = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-delay\", 300);\n Observable range = Observable.range(1, maxRetries);\n Observable> zipWith = observable.zipWith(range, (t, i) -> {\n int delay = Math.min((int) Math.pow(2, i), maxDelay);\n logger.debugf(t, \"The findTables query failed. Attempting retry # %d seconds\", delay);\n return Observable.timer(delay, TimeUnit.SECONDS).onBackpressureDrop();\n });\n return Observable.merge(zipWith);\n });\n }\n\n private boolean isTableExpired(String table) {\n Long timestamp = dataAccess.tableToMapKey(table);\n return timestamp < (System.currentTimeMillis() - ttl);\n }\n\n private Observable dropTable(String table) {\n return session.execute(String.format(DROP_TABLE_CQL, table)).map(resultSet -> table).onErrorResumeNext(t -> {\n // If there is an error, we do not retry because it is possible that the table has already been\n // dropped. We will instead wait until findTables runs again and retry dropping the table then\n // if dropping it did indeed fail for some reason.\n logger.infof(t, \"Failed to drop %s\", table);\n return Observable.empty();\n });\n }\n}\n"} {"task_id": "Java_716", "language": "Java", "task_type": "empty", "source_file": "java/github/hawkular/hawkular-metrics/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/TempTablesCleaner.java", "mask_start_position": 2858, "mask_end_position": 2858, "canonical_solution": "", "pre_mask_code": "package org.hawkular.metrics.core.service;\n\nimport java.util.concurrent.TimeUnit;\nimport org.hawkular.rx.cassandra.driver.RxSession;\nimport org.jboss.logging.Logger;\nimport org.joda.time.Days;\nimport com.datastax.driver.core.PreparedStatement;\nimport rx.Observable;\nimport rx.schedulers.Schedulers;\n\n/**\n * @author jsanda\n */\npublic class TempTablesCleaner {\n\n private static Logger logger = Logger.getLogger(TempTablesCleaner.class);\n\n private RxSession session;\n\n private PreparedStatement findTables;\n\n private long ttl;\n\n private DataAccessImpl dataAccess;\n\n private volatile boolean finished;\n\n private static final String DROP_TABLE_CQL = \"DROP TABLE IF EXISTS %s\";\n\n public TempTablesCleaner(RxSession session, DataAccessImpl dataAccess, String keyspace, int ttl) {\n this.session = session;\n this.dataAccess = dataAccess;\n this.ttl = Days.days(ttl).toStandardDuration().getMillis();\n findTables = session.getSession().prepare(\"SELECT table_name FROM system_schema.tables WHERE keyspace_name = '\" + keyspace + \"'\");\n }\n\n public void run() {\n logger.info(\"Checking for expired temp tables\");\n Observable.interval(1, TimeUnit.DAYS, Schedulers.io()).takeUntil(i -> finished).flatMap(i -> session.execute(findTables.bind())).compose(applyRetryPolicy()).flatMap(Observable::from).filter(row -> row.getString(0).startsWith(DataAccessImpl.TEMP_TABLE_NAME_PROTOTYPE)).map(row -> row.getString(0)).filter(this::isTableExpired).flatMap(this::dropTable).subscribe(table -> logger.infof(\"Dropped table %s\", table), t -> logger.warn(\"Cleaning temp tables failed\", t), () -> logger.infof(\"Finished cleaning expired temp tables\"));\n }\n\n public void shutdown() {\n finished = true;\n }\n\n private Observable.Transformer applyRetryPolicy() {\n return tObservable -> tObservable.retryWhen(observable -> {\n Integer maxRetries = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-retries\", 10);\n Integer maxDelay = Integer.getInteger(\"hawkular.metrics.temp-table-cleaner.max-delay\", 300);\n Observable range = Observable.range(1, maxRetries);\n Observable> zipWith = observable.zipWith(range, (t, i) -> {\n int delay = Math.min((int) Math.pow(2, i), maxDelay);\n logger.debugf(t, \"The findTables query failed. Attempting retry # %d seconds\", delay);\n return Observable.timer(delay, TimeUnit.SECONDS).onBackpressureDrop();\n });\n return Observable.merge(zipWith);\n });\n }\n\n private boolean isTableExpired(String table) {\n Long timestamp = dataAccess.tableToMapKey(table);\n return timestamp < (System.currentTimeMillis() - ttl);\n }\n\n private Observable dropTable(String table) {\n retu", "post_mask_code": "rn session.execute(String.format(DROP_TABLE_CQL, table)).map(resultSet -> table).onErrorResumeNext(t -> {\n // If there is an error, we do not retry because it is possible that the table has already been\n // dropped. We will instead wait until findTables runs again and retry dropping the table then\n // if dropping it did indeed fail for some reason.\n logger.infof(t, \"Failed to drop %s\", table);\n return Observable.empty();\n });\n }\n}\n"} {"task_id": "Java_717", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/airavata/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/entities/airavataworkflowcatalog/ApplicationErrorPK.java", "mask_start_position": 355, "mask_end_position": 394, "canonical_solution": "public void setErrorId(String errorId) ", "pre_mask_code": "package org.apache.airavata.registry.core.entities.airavataworkflowcatalog;\n\nimport java.io.Serializable;\nimport java.util.Objects;\n\npublic class ApplicationErrorPK implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private String errorId;\n\n private String applicationId;\n\n public ApplicationErrorPK() {\n }\n\n ", "post_mask_code": "{\n this.errorId = errorId;\n }\n\n public void setApplicationId(String applicationId) {\n this.applicationId = applicationId;\n }\n\n public String getErrorId() {\n return errorId;\n }\n\n public String getApplicationId() {\n return applicationId;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ApplicationErrorPK that = (ApplicationErrorPK) o;\n return Objects.equals(errorId, that.errorId) && Objects.equals(applicationId, that.applicationId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(errorId, applicationId);\n }\n}\n"} {"task_id": "Java_718", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/airavata/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/entities/airavataworkflowcatalog/ApplicationErrorPK.java", "mask_start_position": 490, "mask_end_position": 541, "canonical_solution": "{\n this.applicationId = applicationId;\n }", "pre_mask_code": "package org.apache.airavata.registry.core.entities.airavataworkflowcatalog;\n\nimport java.io.Serializable;\nimport java.util.Objects;\n\npublic class ApplicationErrorPK implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private String errorId;\n\n private String applicationId;\n\n public ApplicationErrorPK() {\n }\n\n public void setErrorId(String errorId) {\n this.errorId = errorId;\n }\n\n public void setApplicationId(String applicationId) ", "post_mask_code": "\n\n public String getErrorId() {\n return errorId;\n }\n\n public String getApplicationId() {\n return applicationId;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ApplicationErrorPK that = (ApplicationErrorPK) o;\n return Objects.equals(errorId, that.errorId) && Objects.equals(applicationId, that.applicationId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(errorId, applicationId);\n }\n}\n"} {"task_id": "Java_719", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/airavata/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/entities/airavataworkflowcatalog/ApplicationErrorPK.java", "mask_start_position": 734, "mask_end_position": 782, "canonical_solution": "\n if (this == o)\n return true;", "pre_mask_code": "package org.apache.airavata.registry.core.entities.airavataworkflowcatalog;\n\nimport java.io.Serializable;\nimport java.util.Objects;\n\npublic class ApplicationErrorPK implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private String errorId;\n\n private String applicationId;\n\n public ApplicationErrorPK() {\n }\n\n public void setErrorId(String errorId) {\n this.errorId = errorId;\n }\n\n public void setApplicationId(String applicationId) {\n this.applicationId = applicationId;\n }\n\n public String getErrorId() {\n return errorId;\n }\n\n public String getApplicationId() {\n return applicationId;\n }\n\n @Override\n public boolean equals(Object o) {", "post_mask_code": "\n if (o == null || getClass() != o.getClass())\n return false;\n ApplicationErrorPK that = (ApplicationErrorPK) o;\n return Objects.equals(errorId, that.errorId) && Objects.equals(applicationId, that.applicationId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(errorId, applicationId);\n }\n}\n"} {"task_id": "Java_720", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/airavata/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/entities/airavataworkflowcatalog/ApplicationErrorPK.java", "mask_start_position": 791, "mask_end_position": 919, "canonical_solution": "if (o == null || getClass() != o.getClass())\n return false;\n ApplicationErrorPK that = (ApplicationErrorPK) o;", "pre_mask_code": "package org.apache.airavata.registry.core.entities.airavataworkflowcatalog;\n\nimport java.io.Serializable;\nimport java.util.Objects;\n\npublic class ApplicationErrorPK implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private String errorId;\n\n private String applicationId;\n\n public ApplicationErrorPK() {\n }\n\n public void setErrorId(String errorId) {\n this.errorId = errorId;\n }\n\n public void setApplicationId(String applicationId) {\n this.applicationId = applicationId;\n }\n\n public String getErrorId() {\n return errorId;\n }\n\n public String getApplicationId() {\n return applicationId;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n ", "post_mask_code": "\n return Objects.equals(errorId, that.errorId) && Objects.equals(applicationId, that.applicationId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(errorId, applicationId);\n }\n}\n"} {"task_id": "Java_721", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/airavata/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/entities/airavataworkflowcatalog/ApplicationErrorPK.java", "mask_start_position": 928, "mask_end_position": 1032, "canonical_solution": "return Objects.equals(errorId, that.errorId) && Objects.equals(applicationId, that.applicationId);\n }", "pre_mask_code": "package org.apache.airavata.registry.core.entities.airavataworkflowcatalog;\n\nimport java.io.Serializable;\nimport java.util.Objects;\n\npublic class ApplicationErrorPK implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private String errorId;\n\n private String applicationId;\n\n public ApplicationErrorPK() {\n }\n\n public void setErrorId(String errorId) {\n this.errorId = errorId;\n }\n\n public void setApplicationId(String applicationId) {\n this.applicationId = applicationId;\n }\n\n public String getErrorId() {\n return errorId;\n }\n\n public String getApplicationId() {\n return applicationId;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ApplicationErrorPK that = (ApplicationErrorPK) o;\n ", "post_mask_code": "\n\n @Override\n public int hashCode() {\n return Objects.hash(errorId, applicationId);\n }\n}\n"} {"task_id": "Java_722", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/airavata/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/entities/airavataworkflowcatalog/ApplicationErrorPK.java", "mask_start_position": 891, "mask_end_position": 919, "canonical_solution": "at = (ApplicationErrorPK) o;", "pre_mask_code": "package org.apache.airavata.registry.core.entities.airavataworkflowcatalog;\n\nimport java.io.Serializable;\nimport java.util.Objects;\n\npublic class ApplicationErrorPK implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private String errorId;\n\n private String applicationId;\n\n public ApplicationErrorPK() {\n }\n\n public void setErrorId(String errorId) {\n this.errorId = errorId;\n }\n\n public void setApplicationId(String applicationId) {\n this.applicationId = applicationId;\n }\n\n public String getErrorId() {\n return errorId;\n }\n\n public String getApplicationId() {\n return applicationId;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ApplicationErrorPK th", "post_mask_code": "\n return Objects.equals(errorId, that.errorId) && Objects.equals(applicationId, that.applicationId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(errorId, applicationId);\n }\n}\n"} {"task_id": "Java_723", "language": "Java", "task_type": "if_statement", "source_file": "java/github/apache/airavata/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/entities/airavataworkflowcatalog/ApplicationErrorPK.java", "mask_start_position": 743, "mask_end_position": 782, "canonical_solution": "if (this == o)\n return true;", "pre_mask_code": "package org.apache.airavata.registry.core.entities.airavataworkflowcatalog;\n\nimport java.io.Serializable;\nimport java.util.Objects;\n\npublic class ApplicationErrorPK implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private String errorId;\n\n private String applicationId;\n\n public ApplicationErrorPK() {\n }\n\n public void setErrorId(String errorId) {\n this.errorId = errorId;\n }\n\n public void setApplicationId(String applicationId) {\n this.applicationId = applicationId;\n }\n\n public String getErrorId() {\n return errorId;\n }\n\n public String getApplicationId() {\n return applicationId;\n }\n\n @Override\n public boolean equals(Object o) {\n ", "post_mask_code": "\n if (o == null || getClass() != o.getClass())\n return false;\n ApplicationErrorPK that = (ApplicationErrorPK) o;\n return Objects.equals(errorId, that.errorId) && Objects.equals(applicationId, that.applicationId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(errorId, applicationId);\n }\n}\n"} {"task_id": "Java_724", "language": "Java", "task_type": "empty", "source_file": "java/github/apache/airavata/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/entities/airavataworkflowcatalog/ApplicationErrorPK.java", "mask_start_position": 421, "mask_end_position": 421, "canonical_solution": "", "pre_mask_code": "package org.apache.airavata.registry.core.entities.airavataworkflowcatalog;\n\nimport java.io.Serializable;\nimport java.util.Objects;\n\npublic class ApplicationErrorPK implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private String errorId;\n\n private String applicationId;\n\n public ApplicationErrorPK() {\n }\n\n public void setErrorId(String errorId) {\n this.errorId = er", "post_mask_code": "rorId;\n }\n\n public void setApplicationId(String applicationId) {\n this.applicationId = applicationId;\n }\n\n public String getErrorId() {\n return errorId;\n }\n\n public String getApplicationId() {\n return applicationId;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ApplicationErrorPK that = (ApplicationErrorPK) o;\n return Objects.equals(errorId, that.errorId) && Objects.equals(applicationId, that.applicationId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(errorId, applicationId);\n }\n}\n"} {"task_id": "Java_725", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SecUSo/privacy-friendly-wifi-manager/app/src/main/java/org/secuso/privacyfriendlywifimanager/view/adapter/DialogWifiListAdapter.java", "mask_start_position": 1587, "mask_end_position": 1645, "canonical_solution": "public void onListItemClicked(WifiLocationEntry newEntry) ", "pre_mask_code": "package org.secuso.privacyfriendlywifimanager.view.adapter;\n\nimport android.content.DialogInterface;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport org.secuso.privacyfriendlywifimanager.logic.types.WifiLocationEntry;\nimport org.secuso.privacyfriendlywifimanager.logic.util.IOnDialogClosedListener;\nimport org.secuso.privacyfriendlywifimanager.logic.util.StaticContext;\nimport org.secuso.privacyfriendlywifimanager.view.viewholder.DialogWifiItemViewHolder;\nimport java.util.List;\nimport secuso.org.privacyfriendlywifi.R;\n\n/**\n * Adapter for WiFis in a dialog.\n */\npublic class DialogWifiListAdapter extends RecyclerView.Adapter {\n\n private final IOnDialogClosedListener listener;\n\n private List knownWifis;\n\n public DialogWifiListAdapter(List knownWifis, IOnDialogClosedListener listener) {\n this.knownWifis = knownWifis;\n this.listener = listener;\n }\n\n @Override\n public DialogWifiItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View v = LayoutInflater.from(StaticContext.getContext()).inflate(R.layout.list_item_dialog_wifilist, parent, false);\n return new DialogWifiItemViewHolder(v);\n }\n\n @Override\n public void onBindViewHolder(DialogWifiItemViewHolder holder, int position) {\n holder.setupItem(this.knownWifis.get(position), this);\n }\n\n @Override\n public int getItemCount() {\n return this.knownWifis.size();\n }\n\n ", "post_mask_code": "{\n this.listener.onDialogClosed(DialogInterface.BUTTON_POSITIVE, newEntry);\n }\n}\n"} {"task_id": "Java_726", "language": "Java", "task_type": "method_body", "source_file": "java/github/SecUSo/privacy-friendly-wifi-manager/app/src/main/java/org/secuso/privacyfriendlywifimanager/view/adapter/DialogWifiListAdapter.java", "mask_start_position": 1535, "mask_end_position": 1581, "canonical_solution": "{\n return this.knownWifis.size();\n }", "pre_mask_code": "package org.secuso.privacyfriendlywifimanager.view.adapter;\n\nimport android.content.DialogInterface;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport org.secuso.privacyfriendlywifimanager.logic.types.WifiLocationEntry;\nimport org.secuso.privacyfriendlywifimanager.logic.util.IOnDialogClosedListener;\nimport org.secuso.privacyfriendlywifimanager.logic.util.StaticContext;\nimport org.secuso.privacyfriendlywifimanager.view.viewholder.DialogWifiItemViewHolder;\nimport java.util.List;\nimport secuso.org.privacyfriendlywifi.R;\n\n/**\n * Adapter for WiFis in a dialog.\n */\npublic class DialogWifiListAdapter extends RecyclerView.Adapter {\n\n private final IOnDialogClosedListener listener;\n\n private List knownWifis;\n\n public DialogWifiListAdapter(List knownWifis, IOnDialogClosedListener listener) {\n this.knownWifis = knownWifis;\n this.listener = listener;\n }\n\n @Override\n public DialogWifiItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View v = LayoutInflater.from(StaticContext.getContext()).inflate(R.layout.list_item_dialog_wifilist, parent, false);\n return new DialogWifiItemViewHolder(v);\n }\n\n @Override\n public void onBindViewHolder(DialogWifiItemViewHolder holder, int position) {\n holder.setupItem(this.knownWifis.get(position), this);\n }\n\n @Override\n public int getItemCount() ", "post_mask_code": "\n\n public void onListItemClicked(WifiLocationEntry newEntry) {\n this.listener.onDialogClosed(DialogInterface.BUTTON_POSITIVE, newEntry);\n }\n}\n"} {"task_id": "Java_727", "language": "Java", "task_type": "single_line", "source_file": "java/github/SecUSo/privacy-friendly-wifi-manager/app/src/main/java/org/secuso/privacyfriendlywifimanager/view/adapter/DialogWifiListAdapter.java", "mask_start_position": 1722, "mask_end_position": 1727, "canonical_solution": "try);", "pre_mask_code": "package org.secuso.privacyfriendlywifimanager.view.adapter;\n\nimport android.content.DialogInterface;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport org.secuso.privacyfriendlywifimanager.logic.types.WifiLocationEntry;\nimport org.secuso.privacyfriendlywifimanager.logic.util.IOnDialogClosedListener;\nimport org.secuso.privacyfriendlywifimanager.logic.util.StaticContext;\nimport org.secuso.privacyfriendlywifimanager.view.viewholder.DialogWifiItemViewHolder;\nimport java.util.List;\nimport secuso.org.privacyfriendlywifi.R;\n\n/**\n * Adapter for WiFis in a dialog.\n */\npublic class DialogWifiListAdapter extends RecyclerView.Adapter {\n\n private final IOnDialogClosedListener listener;\n\n private List knownWifis;\n\n public DialogWifiListAdapter(List knownWifis, IOnDialogClosedListener listener) {\n this.knownWifis = knownWifis;\n this.listener = listener;\n }\n\n @Override\n public DialogWifiItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View v = LayoutInflater.from(StaticContext.getContext()).inflate(R.layout.list_item_dialog_wifilist, parent, false);\n return new DialogWifiItemViewHolder(v);\n }\n\n @Override\n public void onBindViewHolder(DialogWifiItemViewHolder holder, int position) {\n holder.setupItem(this.knownWifis.get(position), this);\n }\n\n @Override\n public int getItemCount() {\n return this.knownWifis.size();\n }\n\n public void onListItemClicked(WifiLocationEntry newEntry) {\n this.listener.onDialogClosed(DialogInterface.BUTTON_POSITIVE, newEn", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_728", "language": "Java", "task_type": "empty", "source_file": "java/github/SecUSo/privacy-friendly-wifi-manager/app/src/main/java/org/secuso/privacyfriendlywifimanager/view/adapter/DialogWifiListAdapter.java", "mask_start_position": 457, "mask_end_position": 457, "canonical_solution": "", "pre_mask_code": "package org.secuso.privacyfriendlywifimanager.view.adapter;\n\nimport android.content.DialogInterface;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport org.secuso.privacyfriendlywifimanager.logic.types.WifiLocationEntry;\nimport org.secuso.privacyfriendlywifimanager.logic.util.IOnDialogClosedListener;\nimport org.secuso.privacyfriendlywifimanager.logic.util.Sta", "post_mask_code": "ticContext;\nimport org.secuso.privacyfriendlywifimanager.view.viewholder.DialogWifiItemViewHolder;\nimport java.util.List;\nimport secuso.org.privacyfriendlywifi.R;\n\n/**\n * Adapter for WiFis in a dialog.\n */\npublic class DialogWifiListAdapter extends RecyclerView.Adapter {\n\n private final IOnDialogClosedListener listener;\n\n private List knownWifis;\n\n public DialogWifiListAdapter(List knownWifis, IOnDialogClosedListener listener) {\n this.knownWifis = knownWifis;\n this.listener = listener;\n }\n\n @Override\n public DialogWifiItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View v = LayoutInflater.from(StaticContext.getContext()).inflate(R.layout.list_item_dialog_wifilist, parent, false);\n return new DialogWifiItemViewHolder(v);\n }\n\n @Override\n public void onBindViewHolder(DialogWifiItemViewHolder holder, int position) {\n holder.setupItem(this.knownWifis.get(position), this);\n }\n\n @Override\n public int getItemCount() {\n return this.knownWifis.size();\n }\n\n public void onListItemClicked(WifiLocationEntry newEntry) {\n this.listener.onDialogClosed(DialogInterface.BUTTON_POSITIVE, newEntry);\n }\n}\n"} {"task_id": "Java_729", "language": "Java", "task_type": "method_signature", "source_file": "java/github/payara/Payara/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java", "mask_start_position": 830, "mask_end_position": 857, "canonical_solution": "public String getContext() ", "pre_mask_code": "/*\n * ErrorMsg.java\n *\n * Created on April 3, 2000\n */\npackage com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc;\n\nimport java.util.ResourceBundle;\nimport com.sun.jdo.api.persistence.support.JDOQueryException;\nimport com.sun.jdo.api.persistence.support.JDOFatalInternalException;\nimport com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException;\nimport com.sun.jdo.spi.persistence.utility.logging.Logger;\nimport org.glassfish.persistence.common.I18NHelper;\n\n/**\n * @author Michael Bouschen\n * @version 0.1\n */\npublic class ErrorMsg {\n\n protected String context = null;\n\n /**\n * I18N support\n */\n protected final static ResourceBundle messages = I18NHelper.loadBundle(ErrorMsg.class);\n\n /**\n * The logger\n */\n private static Logger logger = LogHelperQueryCompilerJDO.getLogger();\n\n ", "post_mask_code": "{\n return context;\n }\n\n public void setContext(String name) {\n context = name;\n }\n\n /**\n * Indicates an error situation.\n * @param line line number\n * @param col column number\n * @param msg error message\n */\n public void error(int line, int col, String msg) throws JDOQueryException {\n JDOQueryException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"error\", ex);\n throw ex;\n }\n\n /**\n * Indicates that a feature is not supported by the current release.\n * @param line line number\n * @param col column number\n * @param msg message\n */\n public void unsupported(int line, int col, String msg) throws JDOUnsupportedOptionException {\n JDOUnsupportedOptionException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"unsupported\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg, Exception nested) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg, nested);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n}\n"} {"task_id": "Java_730", "language": "Java", "task_type": "method_body", "source_file": "java/github/payara/Payara/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java", "mask_start_position": 3355, "mask_end_position": 3510, "canonical_solution": "{\n JDOFatalInternalException ex = new JDOFatalInternalException(msg);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }", "pre_mask_code": "/*\n * ErrorMsg.java\n *\n * Created on April 3, 2000\n */\npackage com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc;\n\nimport java.util.ResourceBundle;\nimport com.sun.jdo.api.persistence.support.JDOQueryException;\nimport com.sun.jdo.api.persistence.support.JDOFatalInternalException;\nimport com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException;\nimport com.sun.jdo.spi.persistence.utility.logging.Logger;\nimport org.glassfish.persistence.common.I18NHelper;\n\n/**\n * @author Michael Bouschen\n * @version 0.1\n */\npublic class ErrorMsg {\n\n protected String context = null;\n\n /**\n * I18N support\n */\n protected final static ResourceBundle messages = I18NHelper.loadBundle(ErrorMsg.class);\n\n /**\n * The logger\n */\n private static Logger logger = LogHelperQueryCompilerJDO.getLogger();\n\n public String getContext() {\n return context;\n }\n\n public void setContext(String name) {\n context = name;\n }\n\n /**\n * Indicates an error situation.\n * @param line line number\n * @param col column number\n * @param msg error message\n */\n public void error(int line, int col, String msg) throws JDOQueryException {\n JDOQueryException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"error\", ex);\n throw ex;\n }\n\n /**\n * Indicates that a feature is not supported by the current release.\n * @param line line number\n * @param col column number\n * @param msg message\n */\n public void unsupported(int line, int col, String msg) throws JDOUnsupportedOptionException {\n JDOUnsupportedOptionException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"unsupported\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg) throws JDOFatalInternalException ", "post_mask_code": "\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg, Exception nested) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg, nested);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n}\n"} {"task_id": "Java_731", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/payara/Payara/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java", "mask_start_position": 2296, "mask_end_position": 2338, "canonical_solution": "\n JDOUnsupportedOptionException ex;", "pre_mask_code": "/*\n * ErrorMsg.java\n *\n * Created on April 3, 2000\n */\npackage com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc;\n\nimport java.util.ResourceBundle;\nimport com.sun.jdo.api.persistence.support.JDOQueryException;\nimport com.sun.jdo.api.persistence.support.JDOFatalInternalException;\nimport com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException;\nimport com.sun.jdo.spi.persistence.utility.logging.Logger;\nimport org.glassfish.persistence.common.I18NHelper;\n\n/**\n * @author Michael Bouschen\n * @version 0.1\n */\npublic class ErrorMsg {\n\n protected String context = null;\n\n /**\n * I18N support\n */\n protected final static ResourceBundle messages = I18NHelper.loadBundle(ErrorMsg.class);\n\n /**\n * The logger\n */\n private static Logger logger = LogHelperQueryCompilerJDO.getLogger();\n\n public String getContext() {\n return context;\n }\n\n public void setContext(String name) {\n context = name;\n }\n\n /**\n * Indicates an error situation.\n * @param line line number\n * @param col column number\n * @param msg error message\n */\n public void error(int line, int col, String msg) throws JDOQueryException {\n JDOQueryException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"error\", ex);\n throw ex;\n }\n\n /**\n * Indicates that a feature is not supported by the current release.\n * @param line line number\n * @param col column number\n * @param msg message\n */\n public void unsupported(int line, int col, String msg) throws JDOUnsupportedOptionException {", "post_mask_code": "\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"unsupported\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg, Exception nested) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg, nested);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n}\n"} {"task_id": "Java_732", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/payara/Payara/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java", "mask_start_position": 2347, "mask_end_position": 3155, "canonical_solution": "if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"unsupported\", ex);", "pre_mask_code": "/*\n * ErrorMsg.java\n *\n * Created on April 3, 2000\n */\npackage com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc;\n\nimport java.util.ResourceBundle;\nimport com.sun.jdo.api.persistence.support.JDOQueryException;\nimport com.sun.jdo.api.persistence.support.JDOFatalInternalException;\nimport com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException;\nimport com.sun.jdo.spi.persistence.utility.logging.Logger;\nimport org.glassfish.persistence.common.I18NHelper;\n\n/**\n * @author Michael Bouschen\n * @version 0.1\n */\npublic class ErrorMsg {\n\n protected String context = null;\n\n /**\n * I18N support\n */\n protected final static ResourceBundle messages = I18NHelper.loadBundle(ErrorMsg.class);\n\n /**\n * The logger\n */\n private static Logger logger = LogHelperQueryCompilerJDO.getLogger();\n\n public String getContext() {\n return context;\n }\n\n public void setContext(String name) {\n context = name;\n }\n\n /**\n * Indicates an error situation.\n * @param line line number\n * @param col column number\n * @param msg error message\n */\n public void error(int line, int col, String msg) throws JDOQueryException {\n JDOQueryException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"error\", ex);\n throw ex;\n }\n\n /**\n * Indicates that a feature is not supported by the current release.\n * @param line line number\n * @param col column number\n * @param msg message\n */\n public void unsupported(int line, int col, String msg) throws JDOUnsupportedOptionException {\n JDOUnsupportedOptionException ex;\n ", "post_mask_code": "\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg, Exception nested) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg, nested);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n}\n"} {"task_id": "Java_733", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/payara/Payara/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java", "mask_start_position": 3164, "mask_end_position": 3179, "canonical_solution": "throw ex;\n }", "pre_mask_code": "/*\n * ErrorMsg.java\n *\n * Created on April 3, 2000\n */\npackage com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc;\n\nimport java.util.ResourceBundle;\nimport com.sun.jdo.api.persistence.support.JDOQueryException;\nimport com.sun.jdo.api.persistence.support.JDOFatalInternalException;\nimport com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException;\nimport com.sun.jdo.spi.persistence.utility.logging.Logger;\nimport org.glassfish.persistence.common.I18NHelper;\n\n/**\n * @author Michael Bouschen\n * @version 0.1\n */\npublic class ErrorMsg {\n\n protected String context = null;\n\n /**\n * I18N support\n */\n protected final static ResourceBundle messages = I18NHelper.loadBundle(ErrorMsg.class);\n\n /**\n * The logger\n */\n private static Logger logger = LogHelperQueryCompilerJDO.getLogger();\n\n public String getContext() {\n return context;\n }\n\n public void setContext(String name) {\n context = name;\n }\n\n /**\n * Indicates an error situation.\n * @param line line number\n * @param col column number\n * @param msg error message\n */\n public void error(int line, int col, String msg) throws JDOQueryException {\n JDOQueryException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"error\", ex);\n throw ex;\n }\n\n /**\n * Indicates that a feature is not supported by the current release.\n * @param line line number\n * @param col column number\n * @param msg message\n */\n public void unsupported(int line, int col, String msg) throws JDOUnsupportedOptionException {\n JDOUnsupportedOptionException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"unsupported\", ex);\n ", "post_mask_code": "\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg, Exception nested) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg, nested);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n}\n"} {"task_id": "Java_734", "language": "Java", "task_type": "single_line", "source_file": "java/github/payara/Payara/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java", "mask_start_position": 873, "mask_end_position": 882, "canonical_solution": " context;", "pre_mask_code": "/*\n * ErrorMsg.java\n *\n * Created on April 3, 2000\n */\npackage com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc;\n\nimport java.util.ResourceBundle;\nimport com.sun.jdo.api.persistence.support.JDOQueryException;\nimport com.sun.jdo.api.persistence.support.JDOFatalInternalException;\nimport com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException;\nimport com.sun.jdo.spi.persistence.utility.logging.Logger;\nimport org.glassfish.persistence.common.I18NHelper;\n\n/**\n * @author Michael Bouschen\n * @version 0.1\n */\npublic class ErrorMsg {\n\n protected String context = null;\n\n /**\n * I18N support\n */\n protected final static ResourceBundle messages = I18NHelper.loadBundle(ErrorMsg.class);\n\n /**\n * The logger\n */\n private static Logger logger = LogHelperQueryCompilerJDO.getLogger();\n\n public String getContext() {\n return", "post_mask_code": "\n }\n\n public void setContext(String name) {\n context = name;\n }\n\n /**\n * Indicates an error situation.\n * @param line line number\n * @param col column number\n * @param msg error message\n */\n public void error(int line, int col, String msg) throws JDOQueryException {\n JDOQueryException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"error\", ex);\n throw ex;\n }\n\n /**\n * Indicates that a feature is not supported by the current release.\n * @param line line number\n * @param col column number\n * @param msg message\n */\n public void unsupported(int line, int col, String msg) throws JDOUnsupportedOptionException {\n JDOUnsupportedOptionException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"unsupported\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg, Exception nested) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg, nested);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n}\n"} {"task_id": "Java_735", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/payara/Payara/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java", "mask_start_position": 3623, "mask_end_position": 3867, "canonical_solution": "public void fatal(String msg, Exception nested) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg, nested);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }", "pre_mask_code": "/*\n * ErrorMsg.java\n *\n * Created on April 3, 2000\n */\npackage com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc;\n\nimport java.util.ResourceBundle;\nimport com.sun.jdo.api.persistence.support.JDOQueryException;\nimport com.sun.jdo.api.persistence.support.JDOFatalInternalException;\nimport com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException;\nimport com.sun.jdo.spi.persistence.utility.logging.Logger;\nimport org.glassfish.persistence.common.I18NHelper;\n\n/**\n * @author Michael Bouschen\n * @version 0.1\n */\npublic class ErrorMsg {\n\n protected String context = null;\n\n /**\n * I18N support\n */\n protected final static ResourceBundle messages = I18NHelper.loadBundle(ErrorMsg.class);\n\n /**\n * The logger\n */\n private static Logger logger = LogHelperQueryCompilerJDO.getLogger();\n\n public String getContext() {\n return context;\n }\n\n public void setContext(String name) {\n context = name;\n }\n\n /**\n * Indicates an error situation.\n * @param line line number\n * @param col column number\n * @param msg error message\n */\n public void error(int line, int col, String msg) throws JDOQueryException {\n JDOQueryException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"error\", ex);\n throw ex;\n }\n\n /**\n * Indicates that a feature is not supported by the current release.\n * @param line line number\n * @param col column number\n * @param msg message\n */\n public void unsupported(int line, int col, String msg) throws JDOUnsupportedOptionException {\n JDOUnsupportedOptionException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"unsupported\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_736", "language": "Java", "task_type": "if_statement", "source_file": "java/github/payara/Payara/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java", "mask_start_position": 2631, "mask_end_position": 3094, "canonical_solution": "if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }", "pre_mask_code": "/*\n * ErrorMsg.java\n *\n * Created on April 3, 2000\n */\npackage com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc;\n\nimport java.util.ResourceBundle;\nimport com.sun.jdo.api.persistence.support.JDOQueryException;\nimport com.sun.jdo.api.persistence.support.JDOFatalInternalException;\nimport com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException;\nimport com.sun.jdo.spi.persistence.utility.logging.Logger;\nimport org.glassfish.persistence.common.I18NHelper;\n\n/**\n * @author Michael Bouschen\n * @version 0.1\n */\npublic class ErrorMsg {\n\n protected String context = null;\n\n /**\n * I18N support\n */\n protected final static ResourceBundle messages = I18NHelper.loadBundle(ErrorMsg.class);\n\n /**\n * The logger\n */\n private static Logger logger = LogHelperQueryCompilerJDO.getLogger();\n\n public String getContext() {\n return context;\n }\n\n public void setContext(String name) {\n context = name;\n }\n\n /**\n * Indicates an error situation.\n * @param line line number\n * @param col column number\n * @param msg error message\n */\n public void error(int line, int col, String msg) throws JDOQueryException {\n JDOQueryException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"error\", ex);\n throw ex;\n }\n\n /**\n * Indicates that a feature is not supported by the current release.\n * @param line line number\n * @param col column number\n * @param msg message\n */\n public void unsupported(int line, int col, String msg) throws JDOUnsupportedOptionException {\n JDOUnsupportedOptionException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else ", "post_mask_code": "\n logger.throwing(\"jqlc.ErrorMsg\", \"unsupported\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg, Exception nested) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg, nested);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n}\n"} {"task_id": "Java_737", "language": "Java", "task_type": "empty", "source_file": "java/github/payara/Payara/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java", "mask_start_position": 3401, "mask_end_position": 3401, "canonical_solution": "", "pre_mask_code": "/*\n * ErrorMsg.java\n *\n * Created on April 3, 2000\n */\npackage com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc;\n\nimport java.util.ResourceBundle;\nimport com.sun.jdo.api.persistence.support.JDOQueryException;\nimport com.sun.jdo.api.persistence.support.JDOFatalInternalException;\nimport com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException;\nimport com.sun.jdo.spi.persistence.utility.logging.Logger;\nimport org.glassfish.persistence.common.I18NHelper;\n\n/**\n * @author Michael Bouschen\n * @version 0.1\n */\npublic class ErrorMsg {\n\n protected String context = null;\n\n /**\n * I18N support\n */\n protected final static ResourceBundle messages = I18NHelper.loadBundle(ErrorMsg.class);\n\n /**\n * The logger\n */\n private static Logger logger = LogHelperQueryCompilerJDO.getLogger();\n\n public String getContext() {\n return context;\n }\n\n public void setContext(String name) {\n context = name;\n }\n\n /**\n * Indicates an error situation.\n * @param line line number\n * @param col column number\n * @param msg error message\n */\n public void error(int line, int col, String msg) throws JDOQueryException {\n JDOQueryException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOQueryException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"error\", ex);\n throw ex;\n }\n\n /**\n * Indicates that a feature is not supported by the current release.\n * @param line line number\n * @param col column number\n * @param msg message\n */\n public void unsupported(int line, int col, String msg) throws JDOUnsupportedOptionException {\n JDOUnsupportedOptionException ex;\n if (line > 1) {\n // include line and column info\n Object[] args = { context, line, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msglinecolumn\", // NOI18N\n args));\n } else if (col > 0) {\n // include column info\n Object[] args = { context, col, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msgcolumn\", // NOI18N\n args));\n } else {\n Object[] args = { context, msg };\n ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, \"jqlc.errormsg.generic.msg\", // NOI18N\n args));\n }\n logger.throwing(\"jqlc.ErrorMsg\", \"unsupported\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new J", "post_mask_code": "DOFatalInternalException(msg);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n\n /**\n * Indicates a fatal situation (implementation error).\n * @param msg error message\n */\n public void fatal(String msg, Exception nested) throws JDOFatalInternalException {\n JDOFatalInternalException ex = new JDOFatalInternalException(msg, nested);\n logger.throwing(\"jqlc.ErrorMsg\", \"fatal\", ex);\n throw ex;\n }\n}\n"} {"task_id": "Java_738", "language": "Java", "task_type": "method_signature", "source_file": "java/github/raydac/java-binary-block-parser/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPCustomFieldTypeProcessorAggregator.java", "mask_start_position": 1716, "mask_end_position": 1872, "canonical_solution": "@Override\n public boolean isAllowed(final JBBPFieldTypeParameterContainer fieldType, final String fieldName, final int extraData, final boolean isArray) ", "pre_mask_code": "package com.igormaznitsa.jbbp.utils;\n\nimport static com.igormaznitsa.jbbp.utils.JBBPUtils.ARRAY_STRING_EMPTY;\nimport com.igormaznitsa.jbbp.JBBPCustomFieldTypeProcessor;\nimport com.igormaznitsa.jbbp.compiler.JBBPNamedFieldInfo;\nimport com.igormaznitsa.jbbp.compiler.tokenizer.JBBPFieldTypeParameterContainer;\nimport com.igormaznitsa.jbbp.io.JBBPBitInputStream;\nimport com.igormaznitsa.jbbp.io.JBBPBitOrder;\nimport com.igormaznitsa.jbbp.model.JBBPAbstractField;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * The Aggregator allows to join several custom field type processors.\n *\n * @since 1.2.0\n */\npublic class JBBPCustomFieldTypeProcessorAggregator implements JBBPCustomFieldTypeProcessor {\n\n private final Map customTypeMap;\n\n private final String[] types;\n\n /**\n * Constructor.\n *\n * @param processors processors which should be joined.\n */\n public JBBPCustomFieldTypeProcessorAggregator(final JBBPCustomFieldTypeProcessor... processors) {\n this.customTypeMap = new HashMap<>();\n for (final JBBPCustomFieldTypeProcessor p : processors) {\n for (final String s : p.getCustomFieldTypes()) {\n JBBPUtils.assertNotNull(s, \"Type must not be null\");\n if (this.customTypeMap.containsKey(s)) {\n throw new IllegalArgumentException(\"Detected duplicated field type [\" + s + ']');\n }\n this.customTypeMap.put(s, p);\n }\n }\n this.types = this.customTypeMap.keySet().toArray(ARRAY_STRING_EMPTY);\n }\n\n @Override\n public String[] getCustomFieldTypes() {\n return this.types;\n }\n\n ", "post_mask_code": "{\n return this.customTypeMap.get(fieldType.getTypeName()).isAllowed(fieldType, fieldName, extraData, isArray);\n }\n\n @Override\n public JBBPAbstractField readCustomFieldType(JBBPBitInputStream in, JBBPBitOrder bitOrder, int parserFlags, JBBPFieldTypeParameterContainer fieldType, JBBPNamedFieldInfo fieldName, int extraData, boolean readWholeStream, int arrayLength) throws IOException {\n return this.customTypeMap.get(fieldType.getTypeName()).readCustomFieldType(in, bitOrder, parserFlags, fieldType, fieldName, extraData, readWholeStream, arrayLength);\n }\n}\n"} {"task_id": "Java_739", "language": "Java", "task_type": "method_body", "source_file": "java/github/raydac/java-binary-block-parser/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPCustomFieldTypeProcessorAggregator.java", "mask_start_position": 1872, "mask_end_position": 1995, "canonical_solution": "{\n return this.customTypeMap.get(fieldType.getTypeName()).isAllowed(fieldType, fieldName, extraData, isArray);\n }", "pre_mask_code": "package com.igormaznitsa.jbbp.utils;\n\nimport static com.igormaznitsa.jbbp.utils.JBBPUtils.ARRAY_STRING_EMPTY;\nimport com.igormaznitsa.jbbp.JBBPCustomFieldTypeProcessor;\nimport com.igormaznitsa.jbbp.compiler.JBBPNamedFieldInfo;\nimport com.igormaznitsa.jbbp.compiler.tokenizer.JBBPFieldTypeParameterContainer;\nimport com.igormaznitsa.jbbp.io.JBBPBitInputStream;\nimport com.igormaznitsa.jbbp.io.JBBPBitOrder;\nimport com.igormaznitsa.jbbp.model.JBBPAbstractField;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * The Aggregator allows to join several custom field type processors.\n *\n * @since 1.2.0\n */\npublic class JBBPCustomFieldTypeProcessorAggregator implements JBBPCustomFieldTypeProcessor {\n\n private final Map customTypeMap;\n\n private final String[] types;\n\n /**\n * Constructor.\n *\n * @param processors processors which should be joined.\n */\n public JBBPCustomFieldTypeProcessorAggregator(final JBBPCustomFieldTypeProcessor... processors) {\n this.customTypeMap = new HashMap<>();\n for (final JBBPCustomFieldTypeProcessor p : processors) {\n for (final String s : p.getCustomFieldTypes()) {\n JBBPUtils.assertNotNull(s, \"Type must not be null\");\n if (this.customTypeMap.containsKey(s)) {\n throw new IllegalArgumentException(\"Detected duplicated field type [\" + s + ']');\n }\n this.customTypeMap.put(s, p);\n }\n }\n this.types = this.customTypeMap.keySet().toArray(ARRAY_STRING_EMPTY);\n }\n\n @Override\n public String[] getCustomFieldTypes() {\n return this.types;\n }\n\n @Override\n public boolean isAllowed(final JBBPFieldTypeParameterContainer fieldType, final String fieldName, final int extraData, final boolean isArray) ", "post_mask_code": "\n\n @Override\n public JBBPAbstractField readCustomFieldType(JBBPBitInputStream in, JBBPBitOrder bitOrder, int parserFlags, JBBPFieldTypeParameterContainer fieldType, JBBPNamedFieldInfo fieldName, int extraData, boolean readWholeStream, int arrayLength) throws IOException {\n return this.customTypeMap.get(fieldType.getTypeName()).readCustomFieldType(in, bitOrder, parserFlags, fieldType, fieldName, extraData, readWholeStream, arrayLength);\n }\n}\n"} {"task_id": "Java_740", "language": "Java", "task_type": "single_line", "source_file": "java/github/raydac/java-binary-block-parser/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPCustomFieldTypeProcessorAggregator.java", "mask_start_position": 1695, "mask_end_position": 1704, "canonical_solution": "is.types;", "pre_mask_code": "package com.igormaznitsa.jbbp.utils;\n\nimport static com.igormaznitsa.jbbp.utils.JBBPUtils.ARRAY_STRING_EMPTY;\nimport com.igormaznitsa.jbbp.JBBPCustomFieldTypeProcessor;\nimport com.igormaznitsa.jbbp.compiler.JBBPNamedFieldInfo;\nimport com.igormaznitsa.jbbp.compiler.tokenizer.JBBPFieldTypeParameterContainer;\nimport com.igormaznitsa.jbbp.io.JBBPBitInputStream;\nimport com.igormaznitsa.jbbp.io.JBBPBitOrder;\nimport com.igormaznitsa.jbbp.model.JBBPAbstractField;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * The Aggregator allows to join several custom field type processors.\n *\n * @since 1.2.0\n */\npublic class JBBPCustomFieldTypeProcessorAggregator implements JBBPCustomFieldTypeProcessor {\n\n private final Map customTypeMap;\n\n private final String[] types;\n\n /**\n * Constructor.\n *\n * @param processors processors which should be joined.\n */\n public JBBPCustomFieldTypeProcessorAggregator(final JBBPCustomFieldTypeProcessor... processors) {\n this.customTypeMap = new HashMap<>();\n for (final JBBPCustomFieldTypeProcessor p : processors) {\n for (final String s : p.getCustomFieldTypes()) {\n JBBPUtils.assertNotNull(s, \"Type must not be null\");\n if (this.customTypeMap.containsKey(s)) {\n throw new IllegalArgumentException(\"Detected duplicated field type [\" + s + ']');\n }\n this.customTypeMap.put(s, p);\n }\n }\n this.types = this.customTypeMap.keySet().toArray(ARRAY_STRING_EMPTY);\n }\n\n @Override\n public String[] getCustomFieldTypes() {\n return th", "post_mask_code": "\n }\n\n @Override\n public boolean isAllowed(final JBBPFieldTypeParameterContainer fieldType, final String fieldName, final int extraData, final boolean isArray) {\n return this.customTypeMap.get(fieldType.getTypeName()).isAllowed(fieldType, fieldName, extraData, isArray);\n }\n\n @Override\n public JBBPAbstractField readCustomFieldType(JBBPBitInputStream in, JBBPBitOrder bitOrder, int parserFlags, JBBPFieldTypeParameterContainer fieldType, JBBPNamedFieldInfo fieldName, int extraData, boolean readWholeStream, int arrayLength) throws IOException {\n return this.customTypeMap.get(fieldType.getTypeName()).readCustomFieldType(in, bitOrder, parserFlags, fieldType, fieldName, extraData, readWholeStream, arrayLength);\n }\n}\n"} {"task_id": "Java_741", "language": "Java", "task_type": "if_statement", "source_file": "java/github/raydac/java-binary-block-parser/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPCustomFieldTypeProcessorAggregator.java", "mask_start_position": 1304, "mask_end_position": 1464, "canonical_solution": "if (this.customTypeMap.containsKey(s)) {\n throw new IllegalArgumentException(\"Detected duplicated field type [\" + s + ']');\n }", "pre_mask_code": "package com.igormaznitsa.jbbp.utils;\n\nimport static com.igormaznitsa.jbbp.utils.JBBPUtils.ARRAY_STRING_EMPTY;\nimport com.igormaznitsa.jbbp.JBBPCustomFieldTypeProcessor;\nimport com.igormaznitsa.jbbp.compiler.JBBPNamedFieldInfo;\nimport com.igormaznitsa.jbbp.compiler.tokenizer.JBBPFieldTypeParameterContainer;\nimport com.igormaznitsa.jbbp.io.JBBPBitInputStream;\nimport com.igormaznitsa.jbbp.io.JBBPBitOrder;\nimport com.igormaznitsa.jbbp.model.JBBPAbstractField;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * The Aggregator allows to join several custom field type processors.\n *\n * @since 1.2.0\n */\npublic class JBBPCustomFieldTypeProcessorAggregator implements JBBPCustomFieldTypeProcessor {\n\n private final Map customTypeMap;\n\n private final String[] types;\n\n /**\n * Constructor.\n *\n * @param processors processors which should be joined.\n */\n public JBBPCustomFieldTypeProcessorAggregator(final JBBPCustomFieldTypeProcessor... processors) {\n this.customTypeMap = new HashMap<>();\n for (final JBBPCustomFieldTypeProcessor p : processors) {\n for (final String s : p.getCustomFieldTypes()) {\n JBBPUtils.assertNotNull(s, \"Type must not be null\");\n ", "post_mask_code": "\n this.customTypeMap.put(s, p);\n }\n }\n this.types = this.customTypeMap.keySet().toArray(ARRAY_STRING_EMPTY);\n }\n\n @Override\n public String[] getCustomFieldTypes() {\n return this.types;\n }\n\n @Override\n public boolean isAllowed(final JBBPFieldTypeParameterContainer fieldType, final String fieldName, final int extraData, final boolean isArray) {\n return this.customTypeMap.get(fieldType.getTypeName()).isAllowed(fieldType, fieldName, extraData, isArray);\n }\n\n @Override\n public JBBPAbstractField readCustomFieldType(JBBPBitInputStream in, JBBPBitOrder bitOrder, int parserFlags, JBBPFieldTypeParameterContainer fieldType, JBBPNamedFieldInfo fieldName, int extraData, boolean readWholeStream, int arrayLength) throws IOException {\n return this.customTypeMap.get(fieldType.getTypeName()).readCustomFieldType(in, bitOrder, parserFlags, fieldType, fieldName, extraData, readWholeStream, arrayLength);\n }\n}\n"} {"task_id": "Java_742", "language": "Java", "task_type": "empty", "source_file": "java/github/raydac/java-binary-block-parser/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPCustomFieldTypeProcessorAggregator.java", "mask_start_position": 1493, "mask_end_position": 1493, "canonical_solution": "", "pre_mask_code": "package com.igormaznitsa.jbbp.utils;\n\nimport static com.igormaznitsa.jbbp.utils.JBBPUtils.ARRAY_STRING_EMPTY;\nimport com.igormaznitsa.jbbp.JBBPCustomFieldTypeProcessor;\nimport com.igormaznitsa.jbbp.compiler.JBBPNamedFieldInfo;\nimport com.igormaznitsa.jbbp.compiler.tokenizer.JBBPFieldTypeParameterContainer;\nimport com.igormaznitsa.jbbp.io.JBBPBitInputStream;\nimport com.igormaznitsa.jbbp.io.JBBPBitOrder;\nimport com.igormaznitsa.jbbp.model.JBBPAbstractField;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * The Aggregator allows to join several custom field type processors.\n *\n * @since 1.2.0\n */\npublic class JBBPCustomFieldTypeProcessorAggregator implements JBBPCustomFieldTypeProcessor {\n\n private final Map customTypeMap;\n\n private final String[] types;\n\n /**\n * Constructor.\n *\n * @param processors processors which should be joined.\n */\n public JBBPCustomFieldTypeProcessorAggregator(final JBBPCustomFieldTypeProcessor... processors) {\n this.customTypeMap = new HashMap<>();\n for (final JBBPCustomFieldTypeProcessor p : processors) {\n for (final String s : p.getCustomFieldTypes()) {\n JBBPUtils.assertNotNull(s, \"Type must not be null\");\n if (this.customTypeMap.containsKey(s)) {\n throw new IllegalArgumentException(\"Detected duplicated field type [\" + s + ']');\n }\n this.customT", "post_mask_code": "ypeMap.put(s, p);\n }\n }\n this.types = this.customTypeMap.keySet().toArray(ARRAY_STRING_EMPTY);\n }\n\n @Override\n public String[] getCustomFieldTypes() {\n return this.types;\n }\n\n @Override\n public boolean isAllowed(final JBBPFieldTypeParameterContainer fieldType, final String fieldName, final int extraData, final boolean isArray) {\n return this.customTypeMap.get(fieldType.getTypeName()).isAllowed(fieldType, fieldName, extraData, isArray);\n }\n\n @Override\n public JBBPAbstractField readCustomFieldType(JBBPBitInputStream in, JBBPBitOrder bitOrder, int parserFlags, JBBPFieldTypeParameterContainer fieldType, JBBPNamedFieldInfo fieldName, int extraData, boolean readWholeStream, int arrayLength) throws IOException {\n return this.customTypeMap.get(fieldType.getTypeName()).readCustomFieldType(in, bitOrder, parserFlags, fieldType, fieldName, extraData, readWholeStream, arrayLength);\n }\n}\n"} {"task_id": "Java_743", "language": "Java", "task_type": "method_signature", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/work/integration/testapp/ToastWorker.java", "mask_start_position": 1132, "mask_end_position": 1172, "canonical_solution": "@Override\n public void run() ", "pre_mask_code": "package androidx.work.integration.testapp;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport android.widget.Toast;\nimport androidx.work.Data;\nimport androidx.work.OneTimeWorkRequest;\nimport androidx.work.Worker;\n\n/**\n * A {@link Worker} that shows a given Toast.\n */\npublic class ToastWorker extends Worker {\n\n static final String ARG_MESSAGE = \"message\";\n\n /**\n * Create a {@link OneTimeWorkRequest.Builder} with the given message.\n *\n * @param message The toast message to display\n * @return A {@link OneTimeWorkRequest.Builder}\n */\n public static OneTimeWorkRequest.Builder create(String message) {\n Data input = new Data.Builder().putString(ARG_MESSAGE, message).build();\n return new OneTimeWorkRequest.Builder(ToastWorker.class).setInputData(input);\n }\n\n @Override\n @NonNull\n public Result doWork() {\n Data input = getInputData();\n final String message = input.getString(ARG_MESSAGE, \"completed!\");\n new Handler(Looper.getMainLooper()).post(new Runnable() {\n\n ", "post_mask_code": "{\n Log.d(\"ToastWorker\", message);\n Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();\n }\n });\n return Result.SUCCESS;\n }\n}\n"} {"task_id": "Java_744", "language": "Java", "task_type": "method_body", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/work/integration/testapp/ToastWorker.java", "mask_start_position": 939, "mask_end_position": 1376, "canonical_solution": "{\n Data input = getInputData();\n final String message = input.getString(ARG_MESSAGE, \"completed!\");\n new Handler(Looper.getMainLooper()).post(new Runnable() {\n\n @Override\n public void run() {\n Log.d(\"ToastWorker\", message);\n Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();\n }\n });\n return Result.SUCCESS;\n }", "pre_mask_code": "package androidx.work.integration.testapp;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport android.widget.Toast;\nimport androidx.work.Data;\nimport androidx.work.OneTimeWorkRequest;\nimport androidx.work.Worker;\n\n/**\n * A {@link Worker} that shows a given Toast.\n */\npublic class ToastWorker extends Worker {\n\n static final String ARG_MESSAGE = \"message\";\n\n /**\n * Create a {@link OneTimeWorkRequest.Builder} with the given message.\n *\n * @param message The toast message to display\n * @return A {@link OneTimeWorkRequest.Builder}\n */\n public static OneTimeWorkRequest.Builder create(String message) {\n Data input = new Data.Builder().putString(ARG_MESSAGE, message).build();\n return new OneTimeWorkRequest.Builder(ToastWorker.class).setInputData(input);\n }\n\n @Override\n @NonNull\n public Result doWork() ", "post_mask_code": "\n}\n"} {"task_id": "Java_745", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/work/integration/testapp/ToastWorker.java", "mask_start_position": 940, "mask_end_position": 977, "canonical_solution": "\n Data input = getInputData();", "pre_mask_code": "package androidx.work.integration.testapp;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport android.widget.Toast;\nimport androidx.work.Data;\nimport androidx.work.OneTimeWorkRequest;\nimport androidx.work.Worker;\n\n/**\n * A {@link Worker} that shows a given Toast.\n */\npublic class ToastWorker extends Worker {\n\n static final String ARG_MESSAGE = \"message\";\n\n /**\n * Create a {@link OneTimeWorkRequest.Builder} with the given message.\n *\n * @param message The toast message to display\n * @return A {@link OneTimeWorkRequest.Builder}\n */\n public static OneTimeWorkRequest.Builder create(String message) {\n Data input = new Data.Builder().putString(ARG_MESSAGE, message).build();\n return new OneTimeWorkRequest.Builder(ToastWorker.class).setInputData(input);\n }\n\n @Override\n @NonNull\n public Result doWork() {", "post_mask_code": "\n final String message = input.getString(ARG_MESSAGE, \"completed!\");\n new Handler(Looper.getMainLooper()).post(new Runnable() {\n\n @Override\n public void run() {\n Log.d(\"ToastWorker\", message);\n Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();\n }\n });\n return Result.SUCCESS;\n }\n}\n"} {"task_id": "Java_746", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/work/integration/testapp/ToastWorker.java", "mask_start_position": 986, "mask_end_position": 1339, "canonical_solution": "final String message = input.getString(ARG_MESSAGE, \"completed!\");\n new Handler(Looper.getMainLooper()).post(new Runnable() {\n\n @Override\n public void run() {\n Log.d(\"ToastWorker\", message);\n Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();\n }\n });", "pre_mask_code": "package androidx.work.integration.testapp;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport android.widget.Toast;\nimport androidx.work.Data;\nimport androidx.work.OneTimeWorkRequest;\nimport androidx.work.Worker;\n\n/**\n * A {@link Worker} that shows a given Toast.\n */\npublic class ToastWorker extends Worker {\n\n static final String ARG_MESSAGE = \"message\";\n\n /**\n * Create a {@link OneTimeWorkRequest.Builder} with the given message.\n *\n * @param message The toast message to display\n * @return A {@link OneTimeWorkRequest.Builder}\n */\n public static OneTimeWorkRequest.Builder create(String message) {\n Data input = new Data.Builder().putString(ARG_MESSAGE, message).build();\n return new OneTimeWorkRequest.Builder(ToastWorker.class).setInputData(input);\n }\n\n @Override\n @NonNull\n public Result doWork() {\n Data input = getInputData();\n ", "post_mask_code": "\n return Result.SUCCESS;\n }\n}\n"} {"task_id": "Java_747", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/work/integration/testapp/ToastWorker.java", "mask_start_position": 1348, "mask_end_position": 1376, "canonical_solution": "return Result.SUCCESS;\n }", "pre_mask_code": "package androidx.work.integration.testapp;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport android.widget.Toast;\nimport androidx.work.Data;\nimport androidx.work.OneTimeWorkRequest;\nimport androidx.work.Worker;\n\n/**\n * A {@link Worker} that shows a given Toast.\n */\npublic class ToastWorker extends Worker {\n\n static final String ARG_MESSAGE = \"message\";\n\n /**\n * Create a {@link OneTimeWorkRequest.Builder} with the given message.\n *\n * @param message The toast message to display\n * @return A {@link OneTimeWorkRequest.Builder}\n */\n public static OneTimeWorkRequest.Builder create(String message) {\n Data input = new Data.Builder().putString(ARG_MESSAGE, message).build();\n return new OneTimeWorkRequest.Builder(ToastWorker.class).setInputData(input);\n }\n\n @Override\n @NonNull\n public Result doWork() {\n Data input = getInputData();\n final String message = input.getString(ARG_MESSAGE, \"completed!\");\n new Handler(Looper.getMainLooper()).post(new Runnable() {\n\n @Override\n public void run() {\n Log.d(\"ToastWorker\", message);\n Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();\n }\n });\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_748", "language": "Java", "task_type": "single_line", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/work/integration/testapp/ToastWorker.java", "mask_start_position": 1027, "mask_end_position": 1052, "canonical_solution": "G_MESSAGE, \"completed!\");", "pre_mask_code": "package androidx.work.integration.testapp;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport android.widget.Toast;\nimport androidx.work.Data;\nimport androidx.work.OneTimeWorkRequest;\nimport androidx.work.Worker;\n\n/**\n * A {@link Worker} that shows a given Toast.\n */\npublic class ToastWorker extends Worker {\n\n static final String ARG_MESSAGE = \"message\";\n\n /**\n * Create a {@link OneTimeWorkRequest.Builder} with the given message.\n *\n * @param message The toast message to display\n * @return A {@link OneTimeWorkRequest.Builder}\n */\n public static OneTimeWorkRequest.Builder create(String message) {\n Data input = new Data.Builder().putString(ARG_MESSAGE, message).build();\n return new OneTimeWorkRequest.Builder(ToastWorker.class).setInputData(input);\n }\n\n @Override\n @NonNull\n public Result doWork() {\n Data input = getInputData();\n final String message = input.getString(AR", "post_mask_code": "\n new Handler(Looper.getMainLooper()).post(new Runnable() {\n\n @Override\n public void run() {\n Log.d(\"ToastWorker\", message);\n Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();\n }\n });\n return Result.SUCCESS;\n }\n}\n"} {"task_id": "Java_749", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/work/integration/testapp/ToastWorker.java", "mask_start_position": 645, "mask_end_position": 883, "canonical_solution": "public static OneTimeWorkRequest.Builder create(String message) {\n Data input = new Data.Builder().putString(ARG_MESSAGE, message).build();\n return new OneTimeWorkRequest.Builder(ToastWorker.class).setInputData(input);\n }", "pre_mask_code": "package androidx.work.integration.testapp;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport android.widget.Toast;\nimport androidx.work.Data;\nimport androidx.work.OneTimeWorkRequest;\nimport androidx.work.Worker;\n\n/**\n * A {@link Worker} that shows a given Toast.\n */\npublic class ToastWorker extends Worker {\n\n static final String ARG_MESSAGE = \"message\";\n\n /**\n * Create a {@link OneTimeWorkRequest.Builder} with the given message.\n *\n * @param message The toast message to display\n * @return A {@link OneTimeWorkRequest.Builder}\n */\n ", "post_mask_code": "\n\n @Override\n @NonNull\n public Result doWork() {\n Data input = getInputData();\n final String message = input.getString(ARG_MESSAGE, \"completed!\");\n new Handler(Looper.getMainLooper()).post(new Runnable() {\n\n @Override\n public void run() {\n Log.d(\"ToastWorker\", message);\n Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();\n }\n });\n return Result.SUCCESS;\n }\n}\n"} {"task_id": "Java_750", "language": "Java", "task_type": "empty", "source_file": "java/github/yuchuangu85/Android_Framework_Source/androidx/work/integration/testapp/ToastWorker.java", "mask_start_position": 1261, "mask_end_position": 1261, "canonical_solution": "", "pre_mask_code": "package androidx.work.integration.testapp;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport android.widget.Toast;\nimport androidx.work.Data;\nimport androidx.work.OneTimeWorkRequest;\nimport androidx.work.Worker;\n\n/**\n * A {@link Worker} that shows a given Toast.\n */\npublic class ToastWorker extends Worker {\n\n static final String ARG_MESSAGE = \"message\";\n\n /**\n * Create a {@link OneTimeWorkRequest.Builder} with the given message.\n *\n * @param message The toast message to display\n * @return A {@link OneTimeWorkRequest.Builder}\n */\n public static OneTimeWorkRequest.Builder create(String message) {\n Data input = new Data.Builder().putString(ARG_MESSAGE, message).build();\n return new OneTimeWorkRequest.Builder(ToastWorker.class).setInputData(input);\n }\n\n @Override\n @NonNull\n public Result doWork() {\n Data input = getInputData();\n final String message = input.getString(ARG_MESSAGE, \"completed!\");\n new Handler(Looper.getMainLooper()).post(new Runnable() {\n\n @Override\n public void run() {\n Log.d(\"ToastWorker\", message);\n Toast.makeText(getApplic", "post_mask_code": "ationContext(), message, Toast.LENGTH_SHORT).show();\n }\n });\n return Result.SUCCESS;\n }\n}\n"} {"task_id": "Java_751", "language": "Java", "task_type": "method_signature", "source_file": "java/github/amodeus-science/amod/src/main/java/amodeus/socket/SocketHost.java", "mask_start_position": 1531, "mask_end_position": 1587, "canonical_solution": "public static void main(String[] args) throws Exception ", "pre_mask_code": "package amodeus.socket;\n\nimport java.io.File;\nimport java.util.Objects;\nimport amodeus.amodeus.analysis.Analysis;\nimport amodeus.amodeus.options.ScenarioOptions;\nimport amodeus.amodeus.options.ScenarioOptionsBase;\nimport amodeus.amodeus.prep.LegCount;\nimport amodeus.amodeus.util.io.MultiFileTools;\nimport amodeus.amodeus.util.matsim.xml.ConfigDispatcherChanger;\nimport amodeus.amodeus.util.matsim.xml.ConfigVehiclesChanger;\nimport amodeus.amodeus.util.net.StringServerSocket;\nimport amodeus.amodeus.util.net.StringSocket;\nimport amodeus.amodeus.video.VideoGenerator;\nimport org.matsim.amodeus.config.AmodeusModeConfig;\nimport amodeus.socket.core.ScoreParameters;\nimport amodeus.socket.core.SocketDispatcherHost;\nimport amodeus.socket.core.SocketScoreElement;\nimport ch.ethz.idsc.tensor.RealScalar;\nimport ch.ethz.idsc.tensor.Scalar;\nimport ch.ethz.idsc.tensor.Tensor;\nimport ch.ethz.idsc.tensor.Tensors;\nimport ch.ethz.idsc.tensor.red.Total;\nimport ch.ethz.idsc.tensor.sca.Round;\n\n// TODO refactor and shorten @clruch\n/**\n * host that runs in container.\n * a client can connect to a running host via TCP/IP\n *\n * Usage:\n * java -cp target/amod-VERSION.jar amod.socket.SocketHost [city]\n */\npublic enum SocketHost {\n ;\n\n public static final int PORT = 9382;\n\n private static final String ENV_SCENARIO = \"SCENARIO\";\n\n private static final String ENV_FLEET_SIZE = \"FLEET_SIZE\";\n\n private static final String ENV_REQUESTS_SIZE = \"REQUESTS_SIZE\";\n\n private static final String ENV_VIDEO_EXPORT = \"VIDEO_EXPORT\";\n\n ", "post_mask_code": "{\n File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();\n run(workingDirectory);\n }\n\n public static void run(File workingDirectory) throws Exception {\n System.out.println(\"Using scenario directory: \" + workingDirectory);\n StringSocket stringSocket = null;\n /**\n * open String server and wait for initial command\n */\n try (StringServerSocket serverSocket = new StringServerSocket(PORT)) {\n stringSocket = serverSocket.getSocketWait();\n // only allow one connection\n serverSocket.close();\n String readLine = stringSocket.readLine();\n Tensor config = Tensors.fromString(readLine);\n System.out.println(\"SocketHost config: \" + config);\n Thread.sleep(1000);\n String scenarioTag = config.Get(0).toString();\n {\n String env = System.getenv(ENV_SCENARIO);\n if (Objects.nonNull(env))\n env = scenarioTag;\n }\n /**\n * download the chosen scenario\n */\n SocketScenarioResource.extract(scenarioTag, workingDirectory);\n /**\n * setup environment variables\n */\n StaticHelper.setup();\n /**\n * run first part of scenario preparer\n */\n SocketPreparer preparer = new SocketPreparer(workingDirectory);\n /**\n * get number of requests in population\n */\n long numReq = LegCount.of(preparer.getPopulation(), AmodeusModeConfig.DEFAULT_MODE);\n Scalar nominalFleetSize = Round.of(RealScalar.of(numReq).multiply(ScoreParameters.GLOBAL.gamma));\n Tensor initialInfo = Tensors.of(RealScalar.of(numReq), preparer.getBoundingBox(), nominalFleetSize);\n /**\n * send initial data: {numberRequests,boundingBox}\n */\n stringSocket.writeln(initialInfo);\n /**\n * get additional information\n */\n String readLine2 = stringSocket.readLine();\n Tensor config2 = Tensors.fromString(readLine2);\n int numReqDes = config2.Get(0).number().intValue();\n int fleetSize = config2.Get(1).number().intValue();\n {\n String env = System.getenv(ENV_REQUESTS_SIZE);\n if (Objects.nonNull(env))\n try {\n numReqDes = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n {\n String env = System.getenv(ENV_FLEET_SIZE);\n if (Objects.nonNull(env))\n try {\n fleetSize = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n /**\n * run second part of preparer\n */\n preparer.run2(numReqDes);\n /**\n * run with socket dispatcher\n */\n ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());\n String simConfigPath = scenarioOptions.getSimulationConfigName();\n ConfigDispatcherChanger.change(simConfigPath, SocketDispatcherHost.class.getSimpleName());\n ConfigVehiclesChanger.change(simConfigPath, fleetSize);\n SocketServer socketServer = new SocketServer();\n socketServer.simulate(stringSocket, numReqDes, workingDirectory);\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * analyze and send final score\n */\n Analysis analysis = // \n Analysis.// \n setup(// \n socketServer.getScenarioOptions(), socketServer.getOutputDirectory(), socketServer.getNetwork(), preparer.getDatabase());\n SocketScoreElement socketScoreElement = new SocketScoreElement(fleetSize, numReqDes, preparer.getDatabase());\n analysis.addAnalysisElement(socketScoreElement);\n SocketExport socketExport = new SocketExport(socketScoreElement);\n analysis.addAnalysisExport(socketExport);\n SocketHtmlReport socketHtmlReport = new SocketHtmlReport(socketScoreElement);\n analysis.addHtmlElement(socketHtmlReport);\n analysis.run();\n {\n /**\n * create a video if environment variable is set\n */\n String env = System.getenv(ENV_VIDEO_EXPORT);\n if (Objects.nonNull(env) && env.equalsIgnoreCase(\"true\"))\n new VideoGenerator(workingDirectory).start();\n }\n /**\n * send final score,\n * {total waiting time, total distance with customer, total empty distance}\n */\n stringSocket.writeln(Total.of(socketScoreElement.getScoreDiffHistory()));\n } catch (Exception exception) {\n shutdown(stringSocket);\n throw exception;\n }\n }\n\n private static void shutdown(StringSocket stringSocket) throws Exception {\n if (Objects.nonNull(stringSocket)) {\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * send fictitious costs\n */\n stringSocket.writeln(StaticHelper.FAILURE_SCORE);\n }\n }\n}\n"} {"task_id": "Java_752", "language": "Java", "task_type": "method_body", "source_file": "java/github/amodeus-science/amod/src/main/java/amodeus/socket/SocketHost.java", "mask_start_position": 6967, "mask_end_position": 7289, "canonical_solution": "{\n if (Objects.nonNull(stringSocket)) {\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * send fictitious costs\n */\n stringSocket.writeln(StaticHelper.FAILURE_SCORE);\n }\n }", "pre_mask_code": "package amodeus.socket;\n\nimport java.io.File;\nimport java.util.Objects;\nimport amodeus.amodeus.analysis.Analysis;\nimport amodeus.amodeus.options.ScenarioOptions;\nimport amodeus.amodeus.options.ScenarioOptionsBase;\nimport amodeus.amodeus.prep.LegCount;\nimport amodeus.amodeus.util.io.MultiFileTools;\nimport amodeus.amodeus.util.matsim.xml.ConfigDispatcherChanger;\nimport amodeus.amodeus.util.matsim.xml.ConfigVehiclesChanger;\nimport amodeus.amodeus.util.net.StringServerSocket;\nimport amodeus.amodeus.util.net.StringSocket;\nimport amodeus.amodeus.video.VideoGenerator;\nimport org.matsim.amodeus.config.AmodeusModeConfig;\nimport amodeus.socket.core.ScoreParameters;\nimport amodeus.socket.core.SocketDispatcherHost;\nimport amodeus.socket.core.SocketScoreElement;\nimport ch.ethz.idsc.tensor.RealScalar;\nimport ch.ethz.idsc.tensor.Scalar;\nimport ch.ethz.idsc.tensor.Tensor;\nimport ch.ethz.idsc.tensor.Tensors;\nimport ch.ethz.idsc.tensor.red.Total;\nimport ch.ethz.idsc.tensor.sca.Round;\n\n// TODO refactor and shorten @clruch\n/**\n * host that runs in container.\n * a client can connect to a running host via TCP/IP\n *\n * Usage:\n * java -cp target/amod-VERSION.jar amod.socket.SocketHost [city]\n */\npublic enum SocketHost {\n ;\n\n public static final int PORT = 9382;\n\n private static final String ENV_SCENARIO = \"SCENARIO\";\n\n private static final String ENV_FLEET_SIZE = \"FLEET_SIZE\";\n\n private static final String ENV_REQUESTS_SIZE = \"REQUESTS_SIZE\";\n\n private static final String ENV_VIDEO_EXPORT = \"VIDEO_EXPORT\";\n\n public static void main(String[] args) throws Exception {\n File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();\n run(workingDirectory);\n }\n\n public static void run(File workingDirectory) throws Exception {\n System.out.println(\"Using scenario directory: \" + workingDirectory);\n StringSocket stringSocket = null;\n /**\n * open String server and wait for initial command\n */\n try (StringServerSocket serverSocket = new StringServerSocket(PORT)) {\n stringSocket = serverSocket.getSocketWait();\n // only allow one connection\n serverSocket.close();\n String readLine = stringSocket.readLine();\n Tensor config = Tensors.fromString(readLine);\n System.out.println(\"SocketHost config: \" + config);\n Thread.sleep(1000);\n String scenarioTag = config.Get(0).toString();\n {\n String env = System.getenv(ENV_SCENARIO);\n if (Objects.nonNull(env))\n env = scenarioTag;\n }\n /**\n * download the chosen scenario\n */\n SocketScenarioResource.extract(scenarioTag, workingDirectory);\n /**\n * setup environment variables\n */\n StaticHelper.setup();\n /**\n * run first part of scenario preparer\n */\n SocketPreparer preparer = new SocketPreparer(workingDirectory);\n /**\n * get number of requests in population\n */\n long numReq = LegCount.of(preparer.getPopulation(), AmodeusModeConfig.DEFAULT_MODE);\n Scalar nominalFleetSize = Round.of(RealScalar.of(numReq).multiply(ScoreParameters.GLOBAL.gamma));\n Tensor initialInfo = Tensors.of(RealScalar.of(numReq), preparer.getBoundingBox(), nominalFleetSize);\n /**\n * send initial data: {numberRequests,boundingBox}\n */\n stringSocket.writeln(initialInfo);\n /**\n * get additional information\n */\n String readLine2 = stringSocket.readLine();\n Tensor config2 = Tensors.fromString(readLine2);\n int numReqDes = config2.Get(0).number().intValue();\n int fleetSize = config2.Get(1).number().intValue();\n {\n String env = System.getenv(ENV_REQUESTS_SIZE);\n if (Objects.nonNull(env))\n try {\n numReqDes = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n {\n String env = System.getenv(ENV_FLEET_SIZE);\n if (Objects.nonNull(env))\n try {\n fleetSize = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n /**\n * run second part of preparer\n */\n preparer.run2(numReqDes);\n /**\n * run with socket dispatcher\n */\n ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());\n String simConfigPath = scenarioOptions.getSimulationConfigName();\n ConfigDispatcherChanger.change(simConfigPath, SocketDispatcherHost.class.getSimpleName());\n ConfigVehiclesChanger.change(simConfigPath, fleetSize);\n SocketServer socketServer = new SocketServer();\n socketServer.simulate(stringSocket, numReqDes, workingDirectory);\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * analyze and send final score\n */\n Analysis analysis = // \n Analysis.// \n setup(// \n socketServer.getScenarioOptions(), socketServer.getOutputDirectory(), socketServer.getNetwork(), preparer.getDatabase());\n SocketScoreElement socketScoreElement = new SocketScoreElement(fleetSize, numReqDes, preparer.getDatabase());\n analysis.addAnalysisElement(socketScoreElement);\n SocketExport socketExport = new SocketExport(socketScoreElement);\n analysis.addAnalysisExport(socketExport);\n SocketHtmlReport socketHtmlReport = new SocketHtmlReport(socketScoreElement);\n analysis.addHtmlElement(socketHtmlReport);\n analysis.run();\n {\n /**\n * create a video if environment variable is set\n */\n String env = System.getenv(ENV_VIDEO_EXPORT);\n if (Objects.nonNull(env) && env.equalsIgnoreCase(\"true\"))\n new VideoGenerator(workingDirectory).start();\n }\n /**\n * send final score,\n * {total waiting time, total distance with customer, total empty distance}\n */\n stringSocket.writeln(Total.of(socketScoreElement.getScoreDiffHistory()));\n } catch (Exception exception) {\n shutdown(stringSocket);\n throw exception;\n }\n }\n\n private static void shutdown(StringSocket stringSocket) throws Exception ", "post_mask_code": "\n}\n"} {"task_id": "Java_753", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/amodeus-science/amod/src/main/java/amodeus/socket/SocketHost.java", "mask_start_position": 6968, "mask_end_position": 6968, "canonical_solution": "", "pre_mask_code": "package amodeus.socket;\n\nimport java.io.File;\nimport java.util.Objects;\nimport amodeus.amodeus.analysis.Analysis;\nimport amodeus.amodeus.options.ScenarioOptions;\nimport amodeus.amodeus.options.ScenarioOptionsBase;\nimport amodeus.amodeus.prep.LegCount;\nimport amodeus.amodeus.util.io.MultiFileTools;\nimport amodeus.amodeus.util.matsim.xml.ConfigDispatcherChanger;\nimport amodeus.amodeus.util.matsim.xml.ConfigVehiclesChanger;\nimport amodeus.amodeus.util.net.StringServerSocket;\nimport amodeus.amodeus.util.net.StringSocket;\nimport amodeus.amodeus.video.VideoGenerator;\nimport org.matsim.amodeus.config.AmodeusModeConfig;\nimport amodeus.socket.core.ScoreParameters;\nimport amodeus.socket.core.SocketDispatcherHost;\nimport amodeus.socket.core.SocketScoreElement;\nimport ch.ethz.idsc.tensor.RealScalar;\nimport ch.ethz.idsc.tensor.Scalar;\nimport ch.ethz.idsc.tensor.Tensor;\nimport ch.ethz.idsc.tensor.Tensors;\nimport ch.ethz.idsc.tensor.red.Total;\nimport ch.ethz.idsc.tensor.sca.Round;\n\n// TODO refactor and shorten @clruch\n/**\n * host that runs in container.\n * a client can connect to a running host via TCP/IP\n *\n * Usage:\n * java -cp target/amod-VERSION.jar amod.socket.SocketHost [city]\n */\npublic enum SocketHost {\n ;\n\n public static final int PORT = 9382;\n\n private static final String ENV_SCENARIO = \"SCENARIO\";\n\n private static final String ENV_FLEET_SIZE = \"FLEET_SIZE\";\n\n private static final String ENV_REQUESTS_SIZE = \"REQUESTS_SIZE\";\n\n private static final String ENV_VIDEO_EXPORT = \"VIDEO_EXPORT\";\n\n public static void main(String[] args) throws Exception {\n File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();\n run(workingDirectory);\n }\n\n public static void run(File workingDirectory) throws Exception {\n System.out.println(\"Using scenario directory: \" + workingDirectory);\n StringSocket stringSocket = null;\n /**\n * open String server and wait for initial command\n */\n try (StringServerSocket serverSocket = new StringServerSocket(PORT)) {\n stringSocket = serverSocket.getSocketWait();\n // only allow one connection\n serverSocket.close();\n String readLine = stringSocket.readLine();\n Tensor config = Tensors.fromString(readLine);\n System.out.println(\"SocketHost config: \" + config);\n Thread.sleep(1000);\n String scenarioTag = config.Get(0).toString();\n {\n String env = System.getenv(ENV_SCENARIO);\n if (Objects.nonNull(env))\n env = scenarioTag;\n }\n /**\n * download the chosen scenario\n */\n SocketScenarioResource.extract(scenarioTag, workingDirectory);\n /**\n * setup environment variables\n */\n StaticHelper.setup();\n /**\n * run first part of scenario preparer\n */\n SocketPreparer preparer = new SocketPreparer(workingDirectory);\n /**\n * get number of requests in population\n */\n long numReq = LegCount.of(preparer.getPopulation(), AmodeusModeConfig.DEFAULT_MODE);\n Scalar nominalFleetSize = Round.of(RealScalar.of(numReq).multiply(ScoreParameters.GLOBAL.gamma));\n Tensor initialInfo = Tensors.of(RealScalar.of(numReq), preparer.getBoundingBox(), nominalFleetSize);\n /**\n * send initial data: {numberRequests,boundingBox}\n */\n stringSocket.writeln(initialInfo);\n /**\n * get additional information\n */\n String readLine2 = stringSocket.readLine();\n Tensor config2 = Tensors.fromString(readLine2);\n int numReqDes = config2.Get(0).number().intValue();\n int fleetSize = config2.Get(1).number().intValue();\n {\n String env = System.getenv(ENV_REQUESTS_SIZE);\n if (Objects.nonNull(env))\n try {\n numReqDes = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n {\n String env = System.getenv(ENV_FLEET_SIZE);\n if (Objects.nonNull(env))\n try {\n fleetSize = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n /**\n * run second part of preparer\n */\n preparer.run2(numReqDes);\n /**\n * run with socket dispatcher\n */\n ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());\n String simConfigPath = scenarioOptions.getSimulationConfigName();\n ConfigDispatcherChanger.change(simConfigPath, SocketDispatcherHost.class.getSimpleName());\n ConfigVehiclesChanger.change(simConfigPath, fleetSize);\n SocketServer socketServer = new SocketServer();\n socketServer.simulate(stringSocket, numReqDes, workingDirectory);\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * analyze and send final score\n */\n Analysis analysis = // \n Analysis.// \n setup(// \n socketServer.getScenarioOptions(), socketServer.getOutputDirectory(), socketServer.getNetwork(), preparer.getDatabase());\n SocketScoreElement socketScoreElement = new SocketScoreElement(fleetSize, numReqDes, preparer.getDatabase());\n analysis.addAnalysisElement(socketScoreElement);\n SocketExport socketExport = new SocketExport(socketScoreElement);\n analysis.addAnalysisExport(socketExport);\n SocketHtmlReport socketHtmlReport = new SocketHtmlReport(socketScoreElement);\n analysis.addHtmlElement(socketHtmlReport);\n analysis.run();\n {\n /**\n * create a video if environment variable is set\n */\n String env = System.getenv(ENV_VIDEO_EXPORT);\n if (Objects.nonNull(env) && env.equalsIgnoreCase(\"true\"))\n new VideoGenerator(workingDirectory).start();\n }\n /**\n * send final score,\n * {total waiting time, total distance with customer, total empty distance}\n */\n stringSocket.writeln(Total.of(socketScoreElement.getScoreDiffHistory()));\n } catch (Exception exception) {\n shutdown(stringSocket);\n throw exception;\n }\n }\n\n private static void shutdown(StringSocket stringSocket) throws Exception {", "post_mask_code": "\n if (Objects.nonNull(stringSocket)) {\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * send fictitious costs\n */\n stringSocket.writeln(StaticHelper.FAILURE_SCORE);\n }\n }\n}\n"} {"task_id": "Java_754", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/amodeus-science/amod/src/main/java/amodeus/socket/SocketHost.java", "mask_start_position": 6977, "mask_end_position": 7283, "canonical_solution": "if (Objects.nonNull(stringSocket)) {\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * send fictitious costs\n */\n stringSocket.writeln(StaticHelper.FAILURE_SCORE);\n }", "pre_mask_code": "package amodeus.socket;\n\nimport java.io.File;\nimport java.util.Objects;\nimport amodeus.amodeus.analysis.Analysis;\nimport amodeus.amodeus.options.ScenarioOptions;\nimport amodeus.amodeus.options.ScenarioOptionsBase;\nimport amodeus.amodeus.prep.LegCount;\nimport amodeus.amodeus.util.io.MultiFileTools;\nimport amodeus.amodeus.util.matsim.xml.ConfigDispatcherChanger;\nimport amodeus.amodeus.util.matsim.xml.ConfigVehiclesChanger;\nimport amodeus.amodeus.util.net.StringServerSocket;\nimport amodeus.amodeus.util.net.StringSocket;\nimport amodeus.amodeus.video.VideoGenerator;\nimport org.matsim.amodeus.config.AmodeusModeConfig;\nimport amodeus.socket.core.ScoreParameters;\nimport amodeus.socket.core.SocketDispatcherHost;\nimport amodeus.socket.core.SocketScoreElement;\nimport ch.ethz.idsc.tensor.RealScalar;\nimport ch.ethz.idsc.tensor.Scalar;\nimport ch.ethz.idsc.tensor.Tensor;\nimport ch.ethz.idsc.tensor.Tensors;\nimport ch.ethz.idsc.tensor.red.Total;\nimport ch.ethz.idsc.tensor.sca.Round;\n\n// TODO refactor and shorten @clruch\n/**\n * host that runs in container.\n * a client can connect to a running host via TCP/IP\n *\n * Usage:\n * java -cp target/amod-VERSION.jar amod.socket.SocketHost [city]\n */\npublic enum SocketHost {\n ;\n\n public static final int PORT = 9382;\n\n private static final String ENV_SCENARIO = \"SCENARIO\";\n\n private static final String ENV_FLEET_SIZE = \"FLEET_SIZE\";\n\n private static final String ENV_REQUESTS_SIZE = \"REQUESTS_SIZE\";\n\n private static final String ENV_VIDEO_EXPORT = \"VIDEO_EXPORT\";\n\n public static void main(String[] args) throws Exception {\n File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();\n run(workingDirectory);\n }\n\n public static void run(File workingDirectory) throws Exception {\n System.out.println(\"Using scenario directory: \" + workingDirectory);\n StringSocket stringSocket = null;\n /**\n * open String server and wait for initial command\n */\n try (StringServerSocket serverSocket = new StringServerSocket(PORT)) {\n stringSocket = serverSocket.getSocketWait();\n // only allow one connection\n serverSocket.close();\n String readLine = stringSocket.readLine();\n Tensor config = Tensors.fromString(readLine);\n System.out.println(\"SocketHost config: \" + config);\n Thread.sleep(1000);\n String scenarioTag = config.Get(0).toString();\n {\n String env = System.getenv(ENV_SCENARIO);\n if (Objects.nonNull(env))\n env = scenarioTag;\n }\n /**\n * download the chosen scenario\n */\n SocketScenarioResource.extract(scenarioTag, workingDirectory);\n /**\n * setup environment variables\n */\n StaticHelper.setup();\n /**\n * run first part of scenario preparer\n */\n SocketPreparer preparer = new SocketPreparer(workingDirectory);\n /**\n * get number of requests in population\n */\n long numReq = LegCount.of(preparer.getPopulation(), AmodeusModeConfig.DEFAULT_MODE);\n Scalar nominalFleetSize = Round.of(RealScalar.of(numReq).multiply(ScoreParameters.GLOBAL.gamma));\n Tensor initialInfo = Tensors.of(RealScalar.of(numReq), preparer.getBoundingBox(), nominalFleetSize);\n /**\n * send initial data: {numberRequests,boundingBox}\n */\n stringSocket.writeln(initialInfo);\n /**\n * get additional information\n */\n String readLine2 = stringSocket.readLine();\n Tensor config2 = Tensors.fromString(readLine2);\n int numReqDes = config2.Get(0).number().intValue();\n int fleetSize = config2.Get(1).number().intValue();\n {\n String env = System.getenv(ENV_REQUESTS_SIZE);\n if (Objects.nonNull(env))\n try {\n numReqDes = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n {\n String env = System.getenv(ENV_FLEET_SIZE);\n if (Objects.nonNull(env))\n try {\n fleetSize = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n /**\n * run second part of preparer\n */\n preparer.run2(numReqDes);\n /**\n * run with socket dispatcher\n */\n ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());\n String simConfigPath = scenarioOptions.getSimulationConfigName();\n ConfigDispatcherChanger.change(simConfigPath, SocketDispatcherHost.class.getSimpleName());\n ConfigVehiclesChanger.change(simConfigPath, fleetSize);\n SocketServer socketServer = new SocketServer();\n socketServer.simulate(stringSocket, numReqDes, workingDirectory);\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * analyze and send final score\n */\n Analysis analysis = // \n Analysis.// \n setup(// \n socketServer.getScenarioOptions(), socketServer.getOutputDirectory(), socketServer.getNetwork(), preparer.getDatabase());\n SocketScoreElement socketScoreElement = new SocketScoreElement(fleetSize, numReqDes, preparer.getDatabase());\n analysis.addAnalysisElement(socketScoreElement);\n SocketExport socketExport = new SocketExport(socketScoreElement);\n analysis.addAnalysisExport(socketExport);\n SocketHtmlReport socketHtmlReport = new SocketHtmlReport(socketScoreElement);\n analysis.addHtmlElement(socketHtmlReport);\n analysis.run();\n {\n /**\n * create a video if environment variable is set\n */\n String env = System.getenv(ENV_VIDEO_EXPORT);\n if (Objects.nonNull(env) && env.equalsIgnoreCase(\"true\"))\n new VideoGenerator(workingDirectory).start();\n }\n /**\n * send final score,\n * {total waiting time, total distance with customer, total empty distance}\n */\n stringSocket.writeln(Total.of(socketScoreElement.getScoreDiffHistory()));\n } catch (Exception exception) {\n shutdown(stringSocket);\n throw exception;\n }\n }\n\n private static void shutdown(StringSocket stringSocket) throws Exception {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_755", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/amodeus-science/amod/src/main/java/amodeus/socket/SocketHost.java", "mask_start_position": 7288, "mask_end_position": 7289, "canonical_solution": "}", "pre_mask_code": "package amodeus.socket;\n\nimport java.io.File;\nimport java.util.Objects;\nimport amodeus.amodeus.analysis.Analysis;\nimport amodeus.amodeus.options.ScenarioOptions;\nimport amodeus.amodeus.options.ScenarioOptionsBase;\nimport amodeus.amodeus.prep.LegCount;\nimport amodeus.amodeus.util.io.MultiFileTools;\nimport amodeus.amodeus.util.matsim.xml.ConfigDispatcherChanger;\nimport amodeus.amodeus.util.matsim.xml.ConfigVehiclesChanger;\nimport amodeus.amodeus.util.net.StringServerSocket;\nimport amodeus.amodeus.util.net.StringSocket;\nimport amodeus.amodeus.video.VideoGenerator;\nimport org.matsim.amodeus.config.AmodeusModeConfig;\nimport amodeus.socket.core.ScoreParameters;\nimport amodeus.socket.core.SocketDispatcherHost;\nimport amodeus.socket.core.SocketScoreElement;\nimport ch.ethz.idsc.tensor.RealScalar;\nimport ch.ethz.idsc.tensor.Scalar;\nimport ch.ethz.idsc.tensor.Tensor;\nimport ch.ethz.idsc.tensor.Tensors;\nimport ch.ethz.idsc.tensor.red.Total;\nimport ch.ethz.idsc.tensor.sca.Round;\n\n// TODO refactor and shorten @clruch\n/**\n * host that runs in container.\n * a client can connect to a running host via TCP/IP\n *\n * Usage:\n * java -cp target/amod-VERSION.jar amod.socket.SocketHost [city]\n */\npublic enum SocketHost {\n ;\n\n public static final int PORT = 9382;\n\n private static final String ENV_SCENARIO = \"SCENARIO\";\n\n private static final String ENV_FLEET_SIZE = \"FLEET_SIZE\";\n\n private static final String ENV_REQUESTS_SIZE = \"REQUESTS_SIZE\";\n\n private static final String ENV_VIDEO_EXPORT = \"VIDEO_EXPORT\";\n\n public static void main(String[] args) throws Exception {\n File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();\n run(workingDirectory);\n }\n\n public static void run(File workingDirectory) throws Exception {\n System.out.println(\"Using scenario directory: \" + workingDirectory);\n StringSocket stringSocket = null;\n /**\n * open String server and wait for initial command\n */\n try (StringServerSocket serverSocket = new StringServerSocket(PORT)) {\n stringSocket = serverSocket.getSocketWait();\n // only allow one connection\n serverSocket.close();\n String readLine = stringSocket.readLine();\n Tensor config = Tensors.fromString(readLine);\n System.out.println(\"SocketHost config: \" + config);\n Thread.sleep(1000);\n String scenarioTag = config.Get(0).toString();\n {\n String env = System.getenv(ENV_SCENARIO);\n if (Objects.nonNull(env))\n env = scenarioTag;\n }\n /**\n * download the chosen scenario\n */\n SocketScenarioResource.extract(scenarioTag, workingDirectory);\n /**\n * setup environment variables\n */\n StaticHelper.setup();\n /**\n * run first part of scenario preparer\n */\n SocketPreparer preparer = new SocketPreparer(workingDirectory);\n /**\n * get number of requests in population\n */\n long numReq = LegCount.of(preparer.getPopulation(), AmodeusModeConfig.DEFAULT_MODE);\n Scalar nominalFleetSize = Round.of(RealScalar.of(numReq).multiply(ScoreParameters.GLOBAL.gamma));\n Tensor initialInfo = Tensors.of(RealScalar.of(numReq), preparer.getBoundingBox(), nominalFleetSize);\n /**\n * send initial data: {numberRequests,boundingBox}\n */\n stringSocket.writeln(initialInfo);\n /**\n * get additional information\n */\n String readLine2 = stringSocket.readLine();\n Tensor config2 = Tensors.fromString(readLine2);\n int numReqDes = config2.Get(0).number().intValue();\n int fleetSize = config2.Get(1).number().intValue();\n {\n String env = System.getenv(ENV_REQUESTS_SIZE);\n if (Objects.nonNull(env))\n try {\n numReqDes = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n {\n String env = System.getenv(ENV_FLEET_SIZE);\n if (Objects.nonNull(env))\n try {\n fleetSize = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n /**\n * run second part of preparer\n */\n preparer.run2(numReqDes);\n /**\n * run with socket dispatcher\n */\n ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());\n String simConfigPath = scenarioOptions.getSimulationConfigName();\n ConfigDispatcherChanger.change(simConfigPath, SocketDispatcherHost.class.getSimpleName());\n ConfigVehiclesChanger.change(simConfigPath, fleetSize);\n SocketServer socketServer = new SocketServer();\n socketServer.simulate(stringSocket, numReqDes, workingDirectory);\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * analyze and send final score\n */\n Analysis analysis = // \n Analysis.// \n setup(// \n socketServer.getScenarioOptions(), socketServer.getOutputDirectory(), socketServer.getNetwork(), preparer.getDatabase());\n SocketScoreElement socketScoreElement = new SocketScoreElement(fleetSize, numReqDes, preparer.getDatabase());\n analysis.addAnalysisElement(socketScoreElement);\n SocketExport socketExport = new SocketExport(socketScoreElement);\n analysis.addAnalysisExport(socketExport);\n SocketHtmlReport socketHtmlReport = new SocketHtmlReport(socketScoreElement);\n analysis.addHtmlElement(socketHtmlReport);\n analysis.run();\n {\n /**\n * create a video if environment variable is set\n */\n String env = System.getenv(ENV_VIDEO_EXPORT);\n if (Objects.nonNull(env) && env.equalsIgnoreCase(\"true\"))\n new VideoGenerator(workingDirectory).start();\n }\n /**\n * send final score,\n * {total waiting time, total distance with customer, total empty distance}\n */\n stringSocket.writeln(Total.of(socketScoreElement.getScoreDiffHistory()));\n } catch (Exception exception) {\n shutdown(stringSocket);\n throw exception;\n }\n }\n\n private static void shutdown(StringSocket stringSocket) throws Exception {\n if (Objects.nonNull(stringSocket)) {\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * send fictitious costs\n */\n stringSocket.writeln(StaticHelper.FAILURE_SCORE);\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_756", "language": "Java", "task_type": "single_line", "source_file": "java/github/amodeus-science/amod/src/main/java/amodeus/socket/SocketHost.java", "mask_start_position": 1664, "mask_end_position": 1665, "canonical_solution": ";", "pre_mask_code": "package amodeus.socket;\n\nimport java.io.File;\nimport java.util.Objects;\nimport amodeus.amodeus.analysis.Analysis;\nimport amodeus.amodeus.options.ScenarioOptions;\nimport amodeus.amodeus.options.ScenarioOptionsBase;\nimport amodeus.amodeus.prep.LegCount;\nimport amodeus.amodeus.util.io.MultiFileTools;\nimport amodeus.amodeus.util.matsim.xml.ConfigDispatcherChanger;\nimport amodeus.amodeus.util.matsim.xml.ConfigVehiclesChanger;\nimport amodeus.amodeus.util.net.StringServerSocket;\nimport amodeus.amodeus.util.net.StringSocket;\nimport amodeus.amodeus.video.VideoGenerator;\nimport org.matsim.amodeus.config.AmodeusModeConfig;\nimport amodeus.socket.core.ScoreParameters;\nimport amodeus.socket.core.SocketDispatcherHost;\nimport amodeus.socket.core.SocketScoreElement;\nimport ch.ethz.idsc.tensor.RealScalar;\nimport ch.ethz.idsc.tensor.Scalar;\nimport ch.ethz.idsc.tensor.Tensor;\nimport ch.ethz.idsc.tensor.Tensors;\nimport ch.ethz.idsc.tensor.red.Total;\nimport ch.ethz.idsc.tensor.sca.Round;\n\n// TODO refactor and shorten @clruch\n/**\n * host that runs in container.\n * a client can connect to a running host via TCP/IP\n *\n * Usage:\n * java -cp target/amod-VERSION.jar amod.socket.SocketHost [city]\n */\npublic enum SocketHost {\n ;\n\n public static final int PORT = 9382;\n\n private static final String ENV_SCENARIO = \"SCENARIO\";\n\n private static final String ENV_FLEET_SIZE = \"FLEET_SIZE\";\n\n private static final String ENV_REQUESTS_SIZE = \"REQUESTS_SIZE\";\n\n private static final String ENV_VIDEO_EXPORT = \"VIDEO_EXPORT\";\n\n public static void main(String[] args) throws Exception {\n File workingDirectory = MultiFileTools.getDefaultWorkingDirectory()", "post_mask_code": "\n run(workingDirectory);\n }\n\n public static void run(File workingDirectory) throws Exception {\n System.out.println(\"Using scenario directory: \" + workingDirectory);\n StringSocket stringSocket = null;\n /**\n * open String server and wait for initial command\n */\n try (StringServerSocket serverSocket = new StringServerSocket(PORT)) {\n stringSocket = serverSocket.getSocketWait();\n // only allow one connection\n serverSocket.close();\n String readLine = stringSocket.readLine();\n Tensor config = Tensors.fromString(readLine);\n System.out.println(\"SocketHost config: \" + config);\n Thread.sleep(1000);\n String scenarioTag = config.Get(0).toString();\n {\n String env = System.getenv(ENV_SCENARIO);\n if (Objects.nonNull(env))\n env = scenarioTag;\n }\n /**\n * download the chosen scenario\n */\n SocketScenarioResource.extract(scenarioTag, workingDirectory);\n /**\n * setup environment variables\n */\n StaticHelper.setup();\n /**\n * run first part of scenario preparer\n */\n SocketPreparer preparer = new SocketPreparer(workingDirectory);\n /**\n * get number of requests in population\n */\n long numReq = LegCount.of(preparer.getPopulation(), AmodeusModeConfig.DEFAULT_MODE);\n Scalar nominalFleetSize = Round.of(RealScalar.of(numReq).multiply(ScoreParameters.GLOBAL.gamma));\n Tensor initialInfo = Tensors.of(RealScalar.of(numReq), preparer.getBoundingBox(), nominalFleetSize);\n /**\n * send initial data: {numberRequests,boundingBox}\n */\n stringSocket.writeln(initialInfo);\n /**\n * get additional information\n */\n String readLine2 = stringSocket.readLine();\n Tensor config2 = Tensors.fromString(readLine2);\n int numReqDes = config2.Get(0).number().intValue();\n int fleetSize = config2.Get(1).number().intValue();\n {\n String env = System.getenv(ENV_REQUESTS_SIZE);\n if (Objects.nonNull(env))\n try {\n numReqDes = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n {\n String env = System.getenv(ENV_FLEET_SIZE);\n if (Objects.nonNull(env))\n try {\n fleetSize = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n /**\n * run second part of preparer\n */\n preparer.run2(numReqDes);\n /**\n * run with socket dispatcher\n */\n ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());\n String simConfigPath = scenarioOptions.getSimulationConfigName();\n ConfigDispatcherChanger.change(simConfigPath, SocketDispatcherHost.class.getSimpleName());\n ConfigVehiclesChanger.change(simConfigPath, fleetSize);\n SocketServer socketServer = new SocketServer();\n socketServer.simulate(stringSocket, numReqDes, workingDirectory);\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * analyze and send final score\n */\n Analysis analysis = // \n Analysis.// \n setup(// \n socketServer.getScenarioOptions(), socketServer.getOutputDirectory(), socketServer.getNetwork(), preparer.getDatabase());\n SocketScoreElement socketScoreElement = new SocketScoreElement(fleetSize, numReqDes, preparer.getDatabase());\n analysis.addAnalysisElement(socketScoreElement);\n SocketExport socketExport = new SocketExport(socketScoreElement);\n analysis.addAnalysisExport(socketExport);\n SocketHtmlReport socketHtmlReport = new SocketHtmlReport(socketScoreElement);\n analysis.addHtmlElement(socketHtmlReport);\n analysis.run();\n {\n /**\n * create a video if environment variable is set\n */\n String env = System.getenv(ENV_VIDEO_EXPORT);\n if (Objects.nonNull(env) && env.equalsIgnoreCase(\"true\"))\n new VideoGenerator(workingDirectory).start();\n }\n /**\n * send final score,\n * {total waiting time, total distance with customer, total empty distance}\n */\n stringSocket.writeln(Total.of(socketScoreElement.getScoreDiffHistory()));\n } catch (Exception exception) {\n shutdown(stringSocket);\n throw exception;\n }\n }\n\n private static void shutdown(StringSocket stringSocket) throws Exception {\n if (Objects.nonNull(stringSocket)) {\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * send fictitious costs\n */\n stringSocket.writeln(StaticHelper.FAILURE_SCORE);\n }\n }\n}\n"} {"task_id": "Java_757", "language": "Java", "task_type": "if_statement", "source_file": "java/github/amodeus-science/amod/src/main/java/amodeus/socket/SocketHost.java", "mask_start_position": 6977, "mask_end_position": 7283, "canonical_solution": "if (Objects.nonNull(stringSocket)) {\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * send fictitious costs\n */\n stringSocket.writeln(StaticHelper.FAILURE_SCORE);\n }", "pre_mask_code": "package amodeus.socket;\n\nimport java.io.File;\nimport java.util.Objects;\nimport amodeus.amodeus.analysis.Analysis;\nimport amodeus.amodeus.options.ScenarioOptions;\nimport amodeus.amodeus.options.ScenarioOptionsBase;\nimport amodeus.amodeus.prep.LegCount;\nimport amodeus.amodeus.util.io.MultiFileTools;\nimport amodeus.amodeus.util.matsim.xml.ConfigDispatcherChanger;\nimport amodeus.amodeus.util.matsim.xml.ConfigVehiclesChanger;\nimport amodeus.amodeus.util.net.StringServerSocket;\nimport amodeus.amodeus.util.net.StringSocket;\nimport amodeus.amodeus.video.VideoGenerator;\nimport org.matsim.amodeus.config.AmodeusModeConfig;\nimport amodeus.socket.core.ScoreParameters;\nimport amodeus.socket.core.SocketDispatcherHost;\nimport amodeus.socket.core.SocketScoreElement;\nimport ch.ethz.idsc.tensor.RealScalar;\nimport ch.ethz.idsc.tensor.Scalar;\nimport ch.ethz.idsc.tensor.Tensor;\nimport ch.ethz.idsc.tensor.Tensors;\nimport ch.ethz.idsc.tensor.red.Total;\nimport ch.ethz.idsc.tensor.sca.Round;\n\n// TODO refactor and shorten @clruch\n/**\n * host that runs in container.\n * a client can connect to a running host via TCP/IP\n *\n * Usage:\n * java -cp target/amod-VERSION.jar amod.socket.SocketHost [city]\n */\npublic enum SocketHost {\n ;\n\n public static final int PORT = 9382;\n\n private static final String ENV_SCENARIO = \"SCENARIO\";\n\n private static final String ENV_FLEET_SIZE = \"FLEET_SIZE\";\n\n private static final String ENV_REQUESTS_SIZE = \"REQUESTS_SIZE\";\n\n private static final String ENV_VIDEO_EXPORT = \"VIDEO_EXPORT\";\n\n public static void main(String[] args) throws Exception {\n File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();\n run(workingDirectory);\n }\n\n public static void run(File workingDirectory) throws Exception {\n System.out.println(\"Using scenario directory: \" + workingDirectory);\n StringSocket stringSocket = null;\n /**\n * open String server and wait for initial command\n */\n try (StringServerSocket serverSocket = new StringServerSocket(PORT)) {\n stringSocket = serverSocket.getSocketWait();\n // only allow one connection\n serverSocket.close();\n String readLine = stringSocket.readLine();\n Tensor config = Tensors.fromString(readLine);\n System.out.println(\"SocketHost config: \" + config);\n Thread.sleep(1000);\n String scenarioTag = config.Get(0).toString();\n {\n String env = System.getenv(ENV_SCENARIO);\n if (Objects.nonNull(env))\n env = scenarioTag;\n }\n /**\n * download the chosen scenario\n */\n SocketScenarioResource.extract(scenarioTag, workingDirectory);\n /**\n * setup environment variables\n */\n StaticHelper.setup();\n /**\n * run first part of scenario preparer\n */\n SocketPreparer preparer = new SocketPreparer(workingDirectory);\n /**\n * get number of requests in population\n */\n long numReq = LegCount.of(preparer.getPopulation(), AmodeusModeConfig.DEFAULT_MODE);\n Scalar nominalFleetSize = Round.of(RealScalar.of(numReq).multiply(ScoreParameters.GLOBAL.gamma));\n Tensor initialInfo = Tensors.of(RealScalar.of(numReq), preparer.getBoundingBox(), nominalFleetSize);\n /**\n * send initial data: {numberRequests,boundingBox}\n */\n stringSocket.writeln(initialInfo);\n /**\n * get additional information\n */\n String readLine2 = stringSocket.readLine();\n Tensor config2 = Tensors.fromString(readLine2);\n int numReqDes = config2.Get(0).number().intValue();\n int fleetSize = config2.Get(1).number().intValue();\n {\n String env = System.getenv(ENV_REQUESTS_SIZE);\n if (Objects.nonNull(env))\n try {\n numReqDes = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n {\n String env = System.getenv(ENV_FLEET_SIZE);\n if (Objects.nonNull(env))\n try {\n fleetSize = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n /**\n * run second part of preparer\n */\n preparer.run2(numReqDes);\n /**\n * run with socket dispatcher\n */\n ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());\n String simConfigPath = scenarioOptions.getSimulationConfigName();\n ConfigDispatcherChanger.change(simConfigPath, SocketDispatcherHost.class.getSimpleName());\n ConfigVehiclesChanger.change(simConfigPath, fleetSize);\n SocketServer socketServer = new SocketServer();\n socketServer.simulate(stringSocket, numReqDes, workingDirectory);\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * analyze and send final score\n */\n Analysis analysis = // \n Analysis.// \n setup(// \n socketServer.getScenarioOptions(), socketServer.getOutputDirectory(), socketServer.getNetwork(), preparer.getDatabase());\n SocketScoreElement socketScoreElement = new SocketScoreElement(fleetSize, numReqDes, preparer.getDatabase());\n analysis.addAnalysisElement(socketScoreElement);\n SocketExport socketExport = new SocketExport(socketScoreElement);\n analysis.addAnalysisExport(socketExport);\n SocketHtmlReport socketHtmlReport = new SocketHtmlReport(socketScoreElement);\n analysis.addHtmlElement(socketHtmlReport);\n analysis.run();\n {\n /**\n * create a video if environment variable is set\n */\n String env = System.getenv(ENV_VIDEO_EXPORT);\n if (Objects.nonNull(env) && env.equalsIgnoreCase(\"true\"))\n new VideoGenerator(workingDirectory).start();\n }\n /**\n * send final score,\n * {total waiting time, total distance with customer, total empty distance}\n */\n stringSocket.writeln(Total.of(socketScoreElement.getScoreDiffHistory()));\n } catch (Exception exception) {\n shutdown(stringSocket);\n throw exception;\n }\n }\n\n private static void shutdown(StringSocket stringSocket) throws Exception {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_758", "language": "Java", "task_type": "try_statement", "source_file": "java/github/amodeus-science/amod/src/main/java/amodeus/socket/SocketHost.java", "mask_start_position": 4385, "mask_end_position": 4576, "canonical_solution": "try {\n fleetSize = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }", "pre_mask_code": "package amodeus.socket;\n\nimport java.io.File;\nimport java.util.Objects;\nimport amodeus.amodeus.analysis.Analysis;\nimport amodeus.amodeus.options.ScenarioOptions;\nimport amodeus.amodeus.options.ScenarioOptionsBase;\nimport amodeus.amodeus.prep.LegCount;\nimport amodeus.amodeus.util.io.MultiFileTools;\nimport amodeus.amodeus.util.matsim.xml.ConfigDispatcherChanger;\nimport amodeus.amodeus.util.matsim.xml.ConfigVehiclesChanger;\nimport amodeus.amodeus.util.net.StringServerSocket;\nimport amodeus.amodeus.util.net.StringSocket;\nimport amodeus.amodeus.video.VideoGenerator;\nimport org.matsim.amodeus.config.AmodeusModeConfig;\nimport amodeus.socket.core.ScoreParameters;\nimport amodeus.socket.core.SocketDispatcherHost;\nimport amodeus.socket.core.SocketScoreElement;\nimport ch.ethz.idsc.tensor.RealScalar;\nimport ch.ethz.idsc.tensor.Scalar;\nimport ch.ethz.idsc.tensor.Tensor;\nimport ch.ethz.idsc.tensor.Tensors;\nimport ch.ethz.idsc.tensor.red.Total;\nimport ch.ethz.idsc.tensor.sca.Round;\n\n// TODO refactor and shorten @clruch\n/**\n * host that runs in container.\n * a client can connect to a running host via TCP/IP\n *\n * Usage:\n * java -cp target/amod-VERSION.jar amod.socket.SocketHost [city]\n */\npublic enum SocketHost {\n ;\n\n public static final int PORT = 9382;\n\n private static final String ENV_SCENARIO = \"SCENARIO\";\n\n private static final String ENV_FLEET_SIZE = \"FLEET_SIZE\";\n\n private static final String ENV_REQUESTS_SIZE = \"REQUESTS_SIZE\";\n\n private static final String ENV_VIDEO_EXPORT = \"VIDEO_EXPORT\";\n\n public static void main(String[] args) throws Exception {\n File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();\n run(workingDirectory);\n }\n\n public static void run(File workingDirectory) throws Exception {\n System.out.println(\"Using scenario directory: \" + workingDirectory);\n StringSocket stringSocket = null;\n /**\n * open String server and wait for initial command\n */\n try (StringServerSocket serverSocket = new StringServerSocket(PORT)) {\n stringSocket = serverSocket.getSocketWait();\n // only allow one connection\n serverSocket.close();\n String readLine = stringSocket.readLine();\n Tensor config = Tensors.fromString(readLine);\n System.out.println(\"SocketHost config: \" + config);\n Thread.sleep(1000);\n String scenarioTag = config.Get(0).toString();\n {\n String env = System.getenv(ENV_SCENARIO);\n if (Objects.nonNull(env))\n env = scenarioTag;\n }\n /**\n * download the chosen scenario\n */\n SocketScenarioResource.extract(scenarioTag, workingDirectory);\n /**\n * setup environment variables\n */\n StaticHelper.setup();\n /**\n * run first part of scenario preparer\n */\n SocketPreparer preparer = new SocketPreparer(workingDirectory);\n /**\n * get number of requests in population\n */\n long numReq = LegCount.of(preparer.getPopulation(), AmodeusModeConfig.DEFAULT_MODE);\n Scalar nominalFleetSize = Round.of(RealScalar.of(numReq).multiply(ScoreParameters.GLOBAL.gamma));\n Tensor initialInfo = Tensors.of(RealScalar.of(numReq), preparer.getBoundingBox(), nominalFleetSize);\n /**\n * send initial data: {numberRequests,boundingBox}\n */\n stringSocket.writeln(initialInfo);\n /**\n * get additional information\n */\n String readLine2 = stringSocket.readLine();\n Tensor config2 = Tensors.fromString(readLine2);\n int numReqDes = config2.Get(0).number().intValue();\n int fleetSize = config2.Get(1).number().intValue();\n {\n String env = System.getenv(ENV_REQUESTS_SIZE);\n if (Objects.nonNull(env))\n try {\n numReqDes = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n {\n String env = System.getenv(ENV_FLEET_SIZE);\n if (Objects.nonNull(env))\n ", "post_mask_code": "\n }\n /**\n * run second part of preparer\n */\n preparer.run2(numReqDes);\n /**\n * run with socket dispatcher\n */\n ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());\n String simConfigPath = scenarioOptions.getSimulationConfigName();\n ConfigDispatcherChanger.change(simConfigPath, SocketDispatcherHost.class.getSimpleName());\n ConfigVehiclesChanger.change(simConfigPath, fleetSize);\n SocketServer socketServer = new SocketServer();\n socketServer.simulate(stringSocket, numReqDes, workingDirectory);\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * analyze and send final score\n */\n Analysis analysis = // \n Analysis.// \n setup(// \n socketServer.getScenarioOptions(), socketServer.getOutputDirectory(), socketServer.getNetwork(), preparer.getDatabase());\n SocketScoreElement socketScoreElement = new SocketScoreElement(fleetSize, numReqDes, preparer.getDatabase());\n analysis.addAnalysisElement(socketScoreElement);\n SocketExport socketExport = new SocketExport(socketScoreElement);\n analysis.addAnalysisExport(socketExport);\n SocketHtmlReport socketHtmlReport = new SocketHtmlReport(socketScoreElement);\n analysis.addHtmlElement(socketHtmlReport);\n analysis.run();\n {\n /**\n * create a video if environment variable is set\n */\n String env = System.getenv(ENV_VIDEO_EXPORT);\n if (Objects.nonNull(env) && env.equalsIgnoreCase(\"true\"))\n new VideoGenerator(workingDirectory).start();\n }\n /**\n * send final score,\n * {total waiting time, total distance with customer, total empty distance}\n */\n stringSocket.writeln(Total.of(socketScoreElement.getScoreDiffHistory()));\n } catch (Exception exception) {\n shutdown(stringSocket);\n throw exception;\n }\n }\n\n private static void shutdown(StringSocket stringSocket) throws Exception {\n if (Objects.nonNull(stringSocket)) {\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * send fictitious costs\n */\n stringSocket.writeln(StaticHelper.FAILURE_SCORE);\n }\n }\n}\n"} {"task_id": "Java_759", "language": "Java", "task_type": "empty", "source_file": "java/github/amodeus-science/amod/src/main/java/amodeus/socket/SocketHost.java", "mask_start_position": 2386, "mask_end_position": 2386, "canonical_solution": "", "pre_mask_code": "package amodeus.socket;\n\nimport java.io.File;\nimport java.util.Objects;\nimport amodeus.amodeus.analysis.Analysis;\nimport amodeus.amodeus.options.ScenarioOptions;\nimport amodeus.amodeus.options.ScenarioOptionsBase;\nimport amodeus.amodeus.prep.LegCount;\nimport amodeus.amodeus.util.io.MultiFileTools;\nimport amodeus.amodeus.util.matsim.xml.ConfigDispatcherChanger;\nimport amodeus.amodeus.util.matsim.xml.ConfigVehiclesChanger;\nimport amodeus.amodeus.util.net.StringServerSocket;\nimport amodeus.amodeus.util.net.StringSocket;\nimport amodeus.amodeus.video.VideoGenerator;\nimport org.matsim.amodeus.config.AmodeusModeConfig;\nimport amodeus.socket.core.ScoreParameters;\nimport amodeus.socket.core.SocketDispatcherHost;\nimport amodeus.socket.core.SocketScoreElement;\nimport ch.ethz.idsc.tensor.RealScalar;\nimport ch.ethz.idsc.tensor.Scalar;\nimport ch.ethz.idsc.tensor.Tensor;\nimport ch.ethz.idsc.tensor.Tensors;\nimport ch.ethz.idsc.tensor.red.Total;\nimport ch.ethz.idsc.tensor.sca.Round;\n\n// TODO refactor and shorten @clruch\n/**\n * host that runs in container.\n * a client can connect to a running host via TCP/IP\n *\n * Usage:\n * java -cp target/amod-VERSION.jar amod.socket.SocketHost [city]\n */\npublic enum SocketHost {\n ;\n\n public static final int PORT = 9382;\n\n private static final String ENV_SCENARIO = \"SCENARIO\";\n\n private static final String ENV_FLEET_SIZE = \"FLEET_SIZE\";\n\n private static final String ENV_REQUESTS_SIZE = \"REQUESTS_SIZE\";\n\n private static final String ENV_VIDEO_EXPORT = \"VIDEO_EXPORT\";\n\n public static void main(String[] args) throws Exception {\n File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();\n run(workingDirectory);\n }\n\n public static void run(File workingDirectory) throws Exception {\n System.out.println(\"Using scenario directory: \" + workingDirectory);\n StringSocket stringSocket = null;\n /**\n * open String server and wait for initial command\n */\n try (StringServerSocket serverSocket = new StringServerSocket(PORT)) {\n stringSocket = serverSocket.getSocketWait();\n // only allow one connection\n serverSocket.close();\n String readLine = stringSocket.readLine();\n Tensor config = Tensors.fromString(readLine);\n System.out.println(\"SocketHost config: \" + config);\n Thread.slee", "post_mask_code": "p(1000);\n String scenarioTag = config.Get(0).toString();\n {\n String env = System.getenv(ENV_SCENARIO);\n if (Objects.nonNull(env))\n env = scenarioTag;\n }\n /**\n * download the chosen scenario\n */\n SocketScenarioResource.extract(scenarioTag, workingDirectory);\n /**\n * setup environment variables\n */\n StaticHelper.setup();\n /**\n * run first part of scenario preparer\n */\n SocketPreparer preparer = new SocketPreparer(workingDirectory);\n /**\n * get number of requests in population\n */\n long numReq = LegCount.of(preparer.getPopulation(), AmodeusModeConfig.DEFAULT_MODE);\n Scalar nominalFleetSize = Round.of(RealScalar.of(numReq).multiply(ScoreParameters.GLOBAL.gamma));\n Tensor initialInfo = Tensors.of(RealScalar.of(numReq), preparer.getBoundingBox(), nominalFleetSize);\n /**\n * send initial data: {numberRequests,boundingBox}\n */\n stringSocket.writeln(initialInfo);\n /**\n * get additional information\n */\n String readLine2 = stringSocket.readLine();\n Tensor config2 = Tensors.fromString(readLine2);\n int numReqDes = config2.Get(0).number().intValue();\n int fleetSize = config2.Get(1).number().intValue();\n {\n String env = System.getenv(ENV_REQUESTS_SIZE);\n if (Objects.nonNull(env))\n try {\n numReqDes = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n {\n String env = System.getenv(ENV_FLEET_SIZE);\n if (Objects.nonNull(env))\n try {\n fleetSize = Integer.parseInt(env);\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n /**\n * run second part of preparer\n */\n preparer.run2(numReqDes);\n /**\n * run with socket dispatcher\n */\n ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());\n String simConfigPath = scenarioOptions.getSimulationConfigName();\n ConfigDispatcherChanger.change(simConfigPath, SocketDispatcherHost.class.getSimpleName());\n ConfigVehiclesChanger.change(simConfigPath, fleetSize);\n SocketServer socketServer = new SocketServer();\n socketServer.simulate(stringSocket, numReqDes, workingDirectory);\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * analyze and send final score\n */\n Analysis analysis = // \n Analysis.// \n setup(// \n socketServer.getScenarioOptions(), socketServer.getOutputDirectory(), socketServer.getNetwork(), preparer.getDatabase());\n SocketScoreElement socketScoreElement = new SocketScoreElement(fleetSize, numReqDes, preparer.getDatabase());\n analysis.addAnalysisElement(socketScoreElement);\n SocketExport socketExport = new SocketExport(socketScoreElement);\n analysis.addAnalysisExport(socketExport);\n SocketHtmlReport socketHtmlReport = new SocketHtmlReport(socketScoreElement);\n analysis.addHtmlElement(socketHtmlReport);\n analysis.run();\n {\n /**\n * create a video if environment variable is set\n */\n String env = System.getenv(ENV_VIDEO_EXPORT);\n if (Objects.nonNull(env) && env.equalsIgnoreCase(\"true\"))\n new VideoGenerator(workingDirectory).start();\n }\n /**\n * send final score,\n * {total waiting time, total distance with customer, total empty distance}\n */\n stringSocket.writeln(Total.of(socketScoreElement.getScoreDiffHistory()));\n } catch (Exception exception) {\n shutdown(stringSocket);\n throw exception;\n }\n }\n\n private static void shutdown(StringSocket stringSocket) throws Exception {\n if (Objects.nonNull(stringSocket)) {\n /**\n * send empty tensor \"{}\" to stop\n */\n stringSocket.writeln(Tensors.empty());\n /**\n * send fictitious costs\n */\n stringSocket.writeln(StaticHelper.FAILURE_SCORE);\n }\n }\n}\n"} {"task_id": "Java_760", "language": "Java", "task_type": "method_signature", "source_file": "java/github/flowable/flowable-engine/modules/flowable-engine-common/src/main/java/org/flowable/common/engine/impl/scripting/BeansResolverFactory.java", "mask_start_position": 708, "mask_end_position": 752, "canonical_solution": "@Override\n public Object get(Object key) ", "pre_mask_code": "package org.flowable.common.engine.impl.scripting;\n\nimport org.flowable.common.engine.impl.AbstractEngineConfiguration;\nimport org.flowable.variable.api.delegate.VariableScope;\n\n/**\n * @author Tom Baeyens\n */\npublic class BeansResolverFactory implements ResolverFactory, Resolver {\n\n protected AbstractEngineConfiguration engineConfiguration;\n\n @Override\n public Resolver createResolver(AbstractEngineConfiguration processEngineConfiguration, VariableScope variableScope) {\n this.engineConfiguration = processEngineConfiguration;\n return this;\n }\n\n @Override\n public boolean containsKey(Object key) {\n return engineConfiguration.getBeans().containsKey(key);\n }\n\n ", "post_mask_code": "{\n return engineConfiguration.getBeans().get(key);\n }\n}\n"} {"task_id": "Java_761", "language": "Java", "task_type": "method_body", "source_file": "java/github/flowable/flowable-engine/modules/flowable-engine-common/src/main/java/org/flowable/common/engine/impl/scripting/BeansResolverFactory.java", "mask_start_position": 752, "mask_end_position": 815, "canonical_solution": "{\n return engineConfiguration.getBeans().get(key);\n }", "pre_mask_code": "package org.flowable.common.engine.impl.scripting;\n\nimport org.flowable.common.engine.impl.AbstractEngineConfiguration;\nimport org.flowable.variable.api.delegate.VariableScope;\n\n/**\n * @author Tom Baeyens\n */\npublic class BeansResolverFactory implements ResolverFactory, Resolver {\n\n protected AbstractEngineConfiguration engineConfiguration;\n\n @Override\n public Resolver createResolver(AbstractEngineConfiguration processEngineConfiguration, VariableScope variableScope) {\n this.engineConfiguration = processEngineConfiguration;\n return this;\n }\n\n @Override\n public boolean containsKey(Object key) {\n return engineConfiguration.getBeans().containsKey(key);\n }\n\n @Override\n public Object get(Object key) ", "post_mask_code": "\n}\n"} {"task_id": "Java_762", "language": "Java", "task_type": "single_line", "source_file": "java/github/flowable/flowable-engine/modules/flowable-engine-common/src/main/java/org/flowable/common/engine/impl/scripting/BeansResolverFactory.java", "mask_start_position": 794, "mask_end_position": 809, "canonical_solution": "ans().get(key);", "pre_mask_code": "package org.flowable.common.engine.impl.scripting;\n\nimport org.flowable.common.engine.impl.AbstractEngineConfiguration;\nimport org.flowable.variable.api.delegate.VariableScope;\n\n/**\n * @author Tom Baeyens\n */\npublic class BeansResolverFactory implements ResolverFactory, Resolver {\n\n protected AbstractEngineConfiguration engineConfiguration;\n\n @Override\n public Resolver createResolver(AbstractEngineConfiguration processEngineConfiguration, VariableScope variableScope) {\n this.engineConfiguration = processEngineConfiguration;\n return this;\n }\n\n @Override\n public boolean containsKey(Object key) {\n return engineConfiguration.getBeans().containsKey(key);\n }\n\n @Override\n public Object get(Object key) {\n return engineConfiguration.getBe", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_763", "language": "Java", "task_type": "empty", "source_file": "java/github/flowable/flowable-engine/modules/flowable-engine-common/src/main/java/org/flowable/common/engine/impl/scripting/BeansResolverFactory.java", "mask_start_position": 20, "mask_end_position": 20, "canonical_solution": "", "pre_mask_code": "package org.flowable", "post_mask_code": ".common.engine.impl.scripting;\n\nimport org.flowable.common.engine.impl.AbstractEngineConfiguration;\nimport org.flowable.variable.api.delegate.VariableScope;\n\n/**\n * @author Tom Baeyens\n */\npublic class BeansResolverFactory implements ResolverFactory, Resolver {\n\n protected AbstractEngineConfiguration engineConfiguration;\n\n @Override\n public Resolver createResolver(AbstractEngineConfiguration processEngineConfiguration, VariableScope variableScope) {\n this.engineConfiguration = processEngineConfiguration;\n return this;\n }\n\n @Override\n public boolean containsKey(Object key) {\n return engineConfiguration.getBeans().containsKey(key);\n }\n\n @Override\n public Object get(Object key) {\n return engineConfiguration.getBeans().get(key);\n }\n}\n"} {"task_id": "Java_764", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Plastix/Forage/app/src/main/java/io/github/plastix/forage/data/sensor/AzimuthAsyncEmitter.java", "mask_start_position": 983, "mask_end_position": 1043, "canonical_solution": "@Override\n public void call(AsyncEmitter emitter) ", "pre_mask_code": "package io.github.plastix.forage.data.sensor;\n\nimport android.hardware.Sensor;\nimport android.hardware.SensorEvent;\nimport android.hardware.SensorEventListener;\nimport android.hardware.SensorManager;\nimport android.support.annotation.NonNull;\nimport android.view.WindowManager;\nimport javax.inject.Inject;\nimport io.github.plastix.forage.util.AngleUtils;\nimport rx.AsyncEmitter;\nimport rx.functions.Action1;\n\npublic class AzimuthAsyncEmitter implements Action1> {\n\n private SensorManager sensorManager;\n\n private WindowManager windowManager;\n\n private Sensor compass;\n\n private float[] orientation;\n\n private float[] rMat;\n\n @Inject\n public AzimuthAsyncEmitter(@NonNull SensorManager sensorManager, @NonNull WindowManager windowManager) {\n this.sensorManager = sensorManager;\n this.windowManager = windowManager;\n this.orientation = new float[3];\n this.rMat = new float[9];\n this.compass = null;\n }\n\n ", "post_mask_code": "{\n compass = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);\n if (compass != null) {\n SensorEventListener sensorEventListener = new SensorEventListener() {\n\n @Override\n public void onSensorChanged(SensorEvent event) {\n if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {\n // Calculate the rotation matrix\n SensorManager.getRotationMatrixFromVector(rMat, event.values);\n // Compass direction is result[0]\n float[] result = SensorManager.getOrientation(rMat, orientation);\n float azimuth = (float) (Math.toDegrees(result[0]));\n azimuth += AngleUtils.getRotationOffset(windowManager);\n emitter.onNext(azimuth);\n }\n }\n\n @Override\n public void onAccuracyChanged(Sensor sensor, int i) {\n // No op\n }\n };\n sensorManager.registerListener(sensorEventListener, compass, SensorManager.SENSOR_DELAY_GAME);\n emitter.setCancellation(() -> sensorManager.unregisterListener(sensorEventListener, compass));\n } else {\n emitter.onError(new SensorUnavailableException(\"Compass Sensor not available!\"));\n }\n }\n}\n"} {"task_id": "Java_765", "language": "Java", "task_type": "method_body", "source_file": "java/github/Plastix/Forage/app/src/main/java/io/github/plastix/forage/data/sensor/AzimuthAsyncEmitter.java", "mask_start_position": 2043, "mask_end_position": 2091, "canonical_solution": "{\n // No op\n }", "pre_mask_code": "package io.github.plastix.forage.data.sensor;\n\nimport android.hardware.Sensor;\nimport android.hardware.SensorEvent;\nimport android.hardware.SensorEventListener;\nimport android.hardware.SensorManager;\nimport android.support.annotation.NonNull;\nimport android.view.WindowManager;\nimport javax.inject.Inject;\nimport io.github.plastix.forage.util.AngleUtils;\nimport rx.AsyncEmitter;\nimport rx.functions.Action1;\n\npublic class AzimuthAsyncEmitter implements Action1> {\n\n private SensorManager sensorManager;\n\n private WindowManager windowManager;\n\n private Sensor compass;\n\n private float[] orientation;\n\n private float[] rMat;\n\n @Inject\n public AzimuthAsyncEmitter(@NonNull SensorManager sensorManager, @NonNull WindowManager windowManager) {\n this.sensorManager = sensorManager;\n this.windowManager = windowManager;\n this.orientation = new float[3];\n this.rMat = new float[9];\n this.compass = null;\n }\n\n @Override\n public void call(AsyncEmitter emitter) {\n compass = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);\n if (compass != null) {\n SensorEventListener sensorEventListener = new SensorEventListener() {\n\n @Override\n public void onSensorChanged(SensorEvent event) {\n if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {\n // Calculate the rotation matrix\n SensorManager.getRotationMatrixFromVector(rMat, event.values);\n // Compass direction is result[0]\n float[] result = SensorManager.getOrientation(rMat, orientation);\n float azimuth = (float) (Math.toDegrees(result[0]));\n azimuth += AngleUtils.getRotationOffset(windowManager);\n emitter.onNext(azimuth);\n }\n }\n\n @Override\n public void onAccuracyChanged(Sensor sensor, int i) ", "post_mask_code": "\n };\n sensorManager.registerListener(sensorEventListener, compass, SensorManager.SENSOR_DELAY_GAME);\n emitter.setCancellation(() -> sensorManager.unregisterListener(sensorEventListener, compass));\n } else {\n emitter.onError(new SensorUnavailableException(\"Compass Sensor not available!\"));\n }\n }\n}\n"} {"task_id": "Java_766", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Plastix/Forage/app/src/main/java/io/github/plastix/forage/data/sensor/AzimuthAsyncEmitter.java", "mask_start_position": 1328, "mask_end_position": 1328, "canonical_solution": "", "pre_mask_code": "package io.github.plastix.forage.data.sensor;\n\nimport android.hardware.Sensor;\nimport android.hardware.SensorEvent;\nimport android.hardware.SensorEventListener;\nimport android.hardware.SensorManager;\nimport android.support.annotation.NonNull;\nimport android.view.WindowManager;\nimport javax.inject.Inject;\nimport io.github.plastix.forage.util.AngleUtils;\nimport rx.AsyncEmitter;\nimport rx.functions.Action1;\n\npublic class AzimuthAsyncEmitter implements Action1> {\n\n private SensorManager sensorManager;\n\n private WindowManager windowManager;\n\n private Sensor compass;\n\n private float[] orientation;\n\n private float[] rMat;\n\n @Inject\n public AzimuthAsyncEmitter(@NonNull SensorManager sensorManager, @NonNull WindowManager windowManager) {\n this.sensorManager = sensorManager;\n this.windowManager = windowManager;\n this.orientation = new float[3];\n this.rMat = new float[9];\n this.compass = null;\n }\n\n @Override\n public void call(AsyncEmitter emitter) {\n compass = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);\n if (compass != null) {\n SensorEventListener sensorEventListener = new SensorEventListener() {\n\n @Override\n public void onSensorChanged(SensorEvent event) {", "post_mask_code": "\n if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {\n // Calculate the rotation matrix\n SensorManager.getRotationMatrixFromVector(rMat, event.values);\n // Compass direction is result[0]\n float[] result = SensorManager.getOrientation(rMat, orientation);\n float azimuth = (float) (Math.toDegrees(result[0]));\n azimuth += AngleUtils.getRotationOffset(windowManager);\n emitter.onNext(azimuth);\n }\n }\n\n @Override\n public void onAccuracyChanged(Sensor sensor, int i) {\n // No op\n }\n };\n sensorManager.registerListener(sensorEventListener, compass, SensorManager.SENSOR_DELAY_GAME);\n emitter.setCancellation(() -> sensorManager.unregisterListener(sensorEventListener, compass));\n } else {\n emitter.onError(new SensorUnavailableException(\"Compass Sensor not available!\"));\n }\n }\n}\n"} {"task_id": "Java_767", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Plastix/Forage/app/src/main/java/io/github/plastix/forage/data/sensor/AzimuthAsyncEmitter.java", "mask_start_position": 1349, "mask_end_position": 1929, "canonical_solution": "if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {\n // Calculate the rotation matrix\n SensorManager.getRotationMatrixFromVector(rMat, event.values);\n // Compass direction is result[0]\n float[] result = SensorManager.getOrientation(rMat, orientation);\n float azimuth = (float) (Math.toDegrees(result[0]));\n azimuth += AngleUtils.getRotationOffset(windowManager);\n emitter.onNext(azimuth);\n }", "pre_mask_code": "package io.github.plastix.forage.data.sensor;\n\nimport android.hardware.Sensor;\nimport android.hardware.SensorEvent;\nimport android.hardware.SensorEventListener;\nimport android.hardware.SensorManager;\nimport android.support.annotation.NonNull;\nimport android.view.WindowManager;\nimport javax.inject.Inject;\nimport io.github.plastix.forage.util.AngleUtils;\nimport rx.AsyncEmitter;\nimport rx.functions.Action1;\n\npublic class AzimuthAsyncEmitter implements Action1> {\n\n private SensorManager sensorManager;\n\n private WindowManager windowManager;\n\n private Sensor compass;\n\n private float[] orientation;\n\n private float[] rMat;\n\n @Inject\n public AzimuthAsyncEmitter(@NonNull SensorManager sensorManager, @NonNull WindowManager windowManager) {\n this.sensorManager = sensorManager;\n this.windowManager = windowManager;\n this.orientation = new float[3];\n this.rMat = new float[9];\n this.compass = null;\n }\n\n @Override\n public void call(AsyncEmitter emitter) {\n compass = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);\n if (compass != null) {\n SensorEventListener sensorEventListener = new SensorEventListener() {\n\n @Override\n public void onSensorChanged(SensorEvent event) {\n ", "post_mask_code": "\n }\n\n @Override\n public void onAccuracyChanged(Sensor sensor, int i) {\n // No op\n }\n };\n sensorManager.registerListener(sensorEventListener, compass, SensorManager.SENSOR_DELAY_GAME);\n emitter.setCancellation(() -> sensorManager.unregisterListener(sensorEventListener, compass));\n } else {\n emitter.onError(new SensorUnavailableException(\"Compass Sensor not available!\"));\n }\n }\n}\n"} {"task_id": "Java_768", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Plastix/Forage/app/src/main/java/io/github/plastix/forage/data/sensor/AzimuthAsyncEmitter.java", "mask_start_position": 1946, "mask_end_position": 1947, "canonical_solution": "}", "pre_mask_code": "package io.github.plastix.forage.data.sensor;\n\nimport android.hardware.Sensor;\nimport android.hardware.SensorEvent;\nimport android.hardware.SensorEventListener;\nimport android.hardware.SensorManager;\nimport android.support.annotation.NonNull;\nimport android.view.WindowManager;\nimport javax.inject.Inject;\nimport io.github.plastix.forage.util.AngleUtils;\nimport rx.AsyncEmitter;\nimport rx.functions.Action1;\n\npublic class AzimuthAsyncEmitter implements Action1> {\n\n private SensorManager sensorManager;\n\n private WindowManager windowManager;\n\n private Sensor compass;\n\n private float[] orientation;\n\n private float[] rMat;\n\n @Inject\n public AzimuthAsyncEmitter(@NonNull SensorManager sensorManager, @NonNull WindowManager windowManager) {\n this.sensorManager = sensorManager;\n this.windowManager = windowManager;\n this.orientation = new float[3];\n this.rMat = new float[9];\n this.compass = null;\n }\n\n @Override\n public void call(AsyncEmitter emitter) {\n compass = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);\n if (compass != null) {\n SensorEventListener sensorEventListener = new SensorEventListener() {\n\n @Override\n public void onSensorChanged(SensorEvent event) {\n if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {\n // Calculate the rotation matrix\n SensorManager.getRotationMatrixFromVector(rMat, event.values);\n // Compass direction is result[0]\n float[] result = SensorManager.getOrientation(rMat, orientation);\n float azimuth = (float) (Math.toDegrees(result[0]));\n azimuth += AngleUtils.getRotationOffset(windowManager);\n emitter.onNext(azimuth);\n }\n ", "post_mask_code": "\n\n @Override\n public void onAccuracyChanged(Sensor sensor, int i) {\n // No op\n }\n };\n sensorManager.registerListener(sensorEventListener, compass, SensorManager.SENSOR_DELAY_GAME);\n emitter.setCancellation(() -> sensorManager.unregisterListener(sensorEventListener, compass));\n } else {\n emitter.onError(new SensorUnavailableException(\"Compass Sensor not available!\"));\n }\n }\n}\n"} {"task_id": "Java_769", "language": "Java", "task_type": "single_line", "source_file": "java/github/Plastix/Forage/app/src/main/java/io/github/plastix/forage/data/sensor/AzimuthAsyncEmitter.java", "mask_start_position": 1090, "mask_end_position": 1123, "canonical_solution": "sor(Sensor.TYPE_ROTATION_VECTOR);", "pre_mask_code": "package io.github.plastix.forage.data.sensor;\n\nimport android.hardware.Sensor;\nimport android.hardware.SensorEvent;\nimport android.hardware.SensorEventListener;\nimport android.hardware.SensorManager;\nimport android.support.annotation.NonNull;\nimport android.view.WindowManager;\nimport javax.inject.Inject;\nimport io.github.plastix.forage.util.AngleUtils;\nimport rx.AsyncEmitter;\nimport rx.functions.Action1;\n\npublic class AzimuthAsyncEmitter implements Action1> {\n\n private SensorManager sensorManager;\n\n private WindowManager windowManager;\n\n private Sensor compass;\n\n private float[] orientation;\n\n private float[] rMat;\n\n @Inject\n public AzimuthAsyncEmitter(@NonNull SensorManager sensorManager, @NonNull WindowManager windowManager) {\n this.sensorManager = sensorManager;\n this.windowManager = windowManager;\n this.orientation = new float[3];\n this.rMat = new float[9];\n this.compass = null;\n }\n\n @Override\n public void call(AsyncEmitter emitter) {\n compass = sensorManager.getDefaultSen", "post_mask_code": "\n if (compass != null) {\n SensorEventListener sensorEventListener = new SensorEventListener() {\n\n @Override\n public void onSensorChanged(SensorEvent event) {\n if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {\n // Calculate the rotation matrix\n SensorManager.getRotationMatrixFromVector(rMat, event.values);\n // Compass direction is result[0]\n float[] result = SensorManager.getOrientation(rMat, orientation);\n float azimuth = (float) (Math.toDegrees(result[0]));\n azimuth += AngleUtils.getRotationOffset(windowManager);\n emitter.onNext(azimuth);\n }\n }\n\n @Override\n public void onAccuracyChanged(Sensor sensor, int i) {\n // No op\n }\n };\n sensorManager.registerListener(sensorEventListener, compass, SensorManager.SENSOR_DELAY_GAME);\n emitter.setCancellation(() -> sensorManager.unregisterListener(sensorEventListener, compass));\n } else {\n emitter.onError(new SensorUnavailableException(\"Compass Sensor not available!\"));\n }\n }\n}\n"} {"task_id": "Java_770", "language": "Java", "task_type": "empty", "source_file": "java/github/Plastix/Forage/app/src/main/java/io/github/plastix/forage/data/sensor/AzimuthAsyncEmitter.java", "mask_start_position": 504, "mask_end_position": 504, "canonical_solution": "", "pre_mask_code": "package io.github.plastix.forage.data.sensor;\n\nimport android.hardware.Sensor;\nimport android.hardware.SensorEvent;\nimport android.hardware.SensorEventListener;\nimport android.hardware.SensorManager;\nimport android.support.annotation.NonNull;\nimport android.view.WindowManager;\nimport javax.inject.Inject;\nimport io.github.plastix.forage.util.AngleUtils;\nimport rx.AsyncEmitter;\nimport rx.functions.Action1;\n\npublic class AzimuthAsyncEmitter implements Action1> {\n\n private SensorM", "post_mask_code": "anager sensorManager;\n\n private WindowManager windowManager;\n\n private Sensor compass;\n\n private float[] orientation;\n\n private float[] rMat;\n\n @Inject\n public AzimuthAsyncEmitter(@NonNull SensorManager sensorManager, @NonNull WindowManager windowManager) {\n this.sensorManager = sensorManager;\n this.windowManager = windowManager;\n this.orientation = new float[3];\n this.rMat = new float[9];\n this.compass = null;\n }\n\n @Override\n public void call(AsyncEmitter emitter) {\n compass = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);\n if (compass != null) {\n SensorEventListener sensorEventListener = new SensorEventListener() {\n\n @Override\n public void onSensorChanged(SensorEvent event) {\n if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {\n // Calculate the rotation matrix\n SensorManager.getRotationMatrixFromVector(rMat, event.values);\n // Compass direction is result[0]\n float[] result = SensorManager.getOrientation(rMat, orientation);\n float azimuth = (float) (Math.toDegrees(result[0]));\n azimuth += AngleUtils.getRotationOffset(windowManager);\n emitter.onNext(azimuth);\n }\n }\n\n @Override\n public void onAccuracyChanged(Sensor sensor, int i) {\n // No op\n }\n };\n sensorManager.registerListener(sensorEventListener, compass, SensorManager.SENSOR_DELAY_GAME);\n emitter.setCancellation(() -> sensorManager.unregisterListener(sensorEventListener, compass));\n } else {\n emitter.onError(new SensorUnavailableException(\"Compass Sensor not available!\"));\n }\n }\n}\n"} {"task_id": "Java_771", "language": "Java", "task_type": "method_signature", "source_file": "java/github/CoprHD/coprhd-controller/dbclient/src/main/java/com/emc/storageos/db/client/upgrade/callbacks/ExportGroupTypeConverter.java", "mask_start_position": 978, "mask_end_position": 1048, "canonical_solution": "@Override\n public void process() throws MigrationCallbackException ", "pre_mask_code": "/*\n * All Rights Reserved\n */\npackage com.emc.storageos.db.client.upgrade.callbacks;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.emc.storageos.db.client.DbClient;\nimport com.emc.storageos.db.client.model.ExportGroup;\nimport com.emc.storageos.db.client.model.ExportGroup.ExportGroupType;\nimport com.emc.storageos.db.client.upgrade.BaseCustomMigrationCallback;\nimport com.emc.storageos.svcs.errorhandling.resources.MigrationCallbackException;\n\n/**\n * Migration handler to convert value of type field for an export group, from\n * Exclusive to Initiator.\n */\npublic class ExportGroupTypeConverter extends BaseCustomMigrationCallback {\n\n private static final Logger log = LoggerFactory.getLogger(ExportGroupTypeConverter.class);\n\n private static final String TYPE_FIELD_NAME = \"type\";\n\n private static final String OLD_TYPE_VALUE = \"Exclusive\";\n\n ", "post_mask_code": "{\n log.info(\"Handle ExportGroup type conversion\");\n DbClient dbClient = getDbClient();\n List exportGroupURIs = dbClient.queryByType(ExportGroup.class, false);\n Iterator exportGroupsIter = dbClient.queryIterativeObjectField(ExportGroup.class, TYPE_FIELD_NAME, exportGroupURIs);\n List exportGroups = new ArrayList();\n while (exportGroupsIter.hasNext()) {\n ExportGroup exportGroup = exportGroupsIter.next();\n String exportGroupId = exportGroup.getId().toString();\n log.info(\"Examining ExportGroup (id={}) for upgrade\", exportGroupId);\n String type = exportGroup.getType();\n if (type.equals(OLD_TYPE_VALUE)) {\n exportGroup.setType(ExportGroupType.Initiator.name());\n log.info(\"Reset export group type for export group (id={})\", exportGroupId);\n exportGroups.add(exportGroup);\n }\n }\n dbClient.persistObject(exportGroups);\n }\n}\n"} {"task_id": "Java_772", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/CoprHD/coprhd-controller/dbclient/src/main/java/com/emc/storageos/db/client/upgrade/callbacks/ExportGroupTypeConverter.java", "mask_start_position": 1049, "mask_end_position": 1148, "canonical_solution": "\n log.info(\"Handle ExportGroup type conversion\");\n DbClient dbClient = getDbClient();", "pre_mask_code": "/*\n * All Rights Reserved\n */\npackage com.emc.storageos.db.client.upgrade.callbacks;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.emc.storageos.db.client.DbClient;\nimport com.emc.storageos.db.client.model.ExportGroup;\nimport com.emc.storageos.db.client.model.ExportGroup.ExportGroupType;\nimport com.emc.storageos.db.client.upgrade.BaseCustomMigrationCallback;\nimport com.emc.storageos.svcs.errorhandling.resources.MigrationCallbackException;\n\n/**\n * Migration handler to convert value of type field for an export group, from\n * Exclusive to Initiator.\n */\npublic class ExportGroupTypeConverter extends BaseCustomMigrationCallback {\n\n private static final Logger log = LoggerFactory.getLogger(ExportGroupTypeConverter.class);\n\n private static final String TYPE_FIELD_NAME = \"type\";\n\n private static final String OLD_TYPE_VALUE = \"Exclusive\";\n\n @Override\n public void process() throws MigrationCallbackException {", "post_mask_code": "\n List exportGroupURIs = dbClient.queryByType(ExportGroup.class, false);\n Iterator exportGroupsIter = dbClient.queryIterativeObjectField(ExportGroup.class, TYPE_FIELD_NAME, exportGroupURIs);\n List exportGroups = new ArrayList();\n while (exportGroupsIter.hasNext()) {\n ExportGroup exportGroup = exportGroupsIter.next();\n String exportGroupId = exportGroup.getId().toString();\n log.info(\"Examining ExportGroup (id={}) for upgrade\", exportGroupId);\n String type = exportGroup.getType();\n if (type.equals(OLD_TYPE_VALUE)) {\n exportGroup.setType(ExportGroupType.Initiator.name());\n log.info(\"Reset export group type for export group (id={})\", exportGroupId);\n exportGroups.add(exportGroup);\n }\n }\n dbClient.persistObject(exportGroups);\n }\n}\n"} {"task_id": "Java_773", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/CoprHD/coprhd-controller/dbclient/src/main/java/com/emc/storageos/db/client/upgrade/callbacks/ExportGroupTypeConverter.java", "mask_start_position": 1157, "mask_end_position": 1441, "canonical_solution": "List exportGroupURIs = dbClient.queryByType(ExportGroup.class, false);\n Iterator exportGroupsIter = dbClient.queryIterativeObjectField(ExportGroup.class, TYPE_FIELD_NAME, exportGroupURIs);\n List exportGroups = new ArrayList();", "pre_mask_code": "/*\n * All Rights Reserved\n */\npackage com.emc.storageos.db.client.upgrade.callbacks;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.emc.storageos.db.client.DbClient;\nimport com.emc.storageos.db.client.model.ExportGroup;\nimport com.emc.storageos.db.client.model.ExportGroup.ExportGroupType;\nimport com.emc.storageos.db.client.upgrade.BaseCustomMigrationCallback;\nimport com.emc.storageos.svcs.errorhandling.resources.MigrationCallbackException;\n\n/**\n * Migration handler to convert value of type field for an export group, from\n * Exclusive to Initiator.\n */\npublic class ExportGroupTypeConverter extends BaseCustomMigrationCallback {\n\n private static final Logger log = LoggerFactory.getLogger(ExportGroupTypeConverter.class);\n\n private static final String TYPE_FIELD_NAME = \"type\";\n\n private static final String OLD_TYPE_VALUE = \"Exclusive\";\n\n @Override\n public void process() throws MigrationCallbackException {\n log.info(\"Handle ExportGroup type conversion\");\n DbClient dbClient = getDbClient();\n ", "post_mask_code": "\n while (exportGroupsIter.hasNext()) {\n ExportGroup exportGroup = exportGroupsIter.next();\n String exportGroupId = exportGroup.getId().toString();\n log.info(\"Examining ExportGroup (id={}) for upgrade\", exportGroupId);\n String type = exportGroup.getType();\n if (type.equals(OLD_TYPE_VALUE)) {\n exportGroup.setType(ExportGroupType.Initiator.name());\n log.info(\"Reset export group type for export group (id={})\", exportGroupId);\n exportGroups.add(exportGroup);\n }\n }\n dbClient.persistObject(exportGroups);\n }\n}\n"} {"task_id": "Java_774", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/CoprHD/coprhd-controller/dbclient/src/main/java/com/emc/storageos/db/client/upgrade/callbacks/ExportGroupTypeConverter.java", "mask_start_position": 1450, "mask_end_position": 2081, "canonical_solution": "while (exportGroupsIter.hasNext()) {\n ExportGroup exportGroup = exportGroupsIter.next();\n String exportGroupId = exportGroup.getId().toString();\n log.info(\"Examining ExportGroup (id={}) for upgrade\", exportGroupId);\n String type = exportGroup.getType();\n if (type.equals(OLD_TYPE_VALUE)) {\n exportGroup.setType(ExportGroupType.Initiator.name());\n log.info(\"Reset export group type for export group (id={})\", exportGroupId);\n exportGroups.add(exportGroup);\n }\n }\n dbClient.persistObject(exportGroups);\n }", "pre_mask_code": "/*\n * All Rights Reserved\n */\npackage com.emc.storageos.db.client.upgrade.callbacks;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.emc.storageos.db.client.DbClient;\nimport com.emc.storageos.db.client.model.ExportGroup;\nimport com.emc.storageos.db.client.model.ExportGroup.ExportGroupType;\nimport com.emc.storageos.db.client.upgrade.BaseCustomMigrationCallback;\nimport com.emc.storageos.svcs.errorhandling.resources.MigrationCallbackException;\n\n/**\n * Migration handler to convert value of type field for an export group, from\n * Exclusive to Initiator.\n */\npublic class ExportGroupTypeConverter extends BaseCustomMigrationCallback {\n\n private static final Logger log = LoggerFactory.getLogger(ExportGroupTypeConverter.class);\n\n private static final String TYPE_FIELD_NAME = \"type\";\n\n private static final String OLD_TYPE_VALUE = \"Exclusive\";\n\n @Override\n public void process() throws MigrationCallbackException {\n log.info(\"Handle ExportGroup type conversion\");\n DbClient dbClient = getDbClient();\n List exportGroupURIs = dbClient.queryByType(ExportGroup.class, false);\n Iterator exportGroupsIter = dbClient.queryIterativeObjectField(ExportGroup.class, TYPE_FIELD_NAME, exportGroupURIs);\n List exportGroups = new ArrayList();\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_775", "language": "Java", "task_type": "single_line", "source_file": "java/github/CoprHD/coprhd-controller/dbclient/src/main/java/com/emc/storageos/db/client/upgrade/callbacks/ExportGroupTypeConverter.java", "mask_start_position": 2054, "mask_end_position": 2075, "canonical_solution": "Object(exportGroups);", "pre_mask_code": "/*\n * All Rights Reserved\n */\npackage com.emc.storageos.db.client.upgrade.callbacks;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.emc.storageos.db.client.DbClient;\nimport com.emc.storageos.db.client.model.ExportGroup;\nimport com.emc.storageos.db.client.model.ExportGroup.ExportGroupType;\nimport com.emc.storageos.db.client.upgrade.BaseCustomMigrationCallback;\nimport com.emc.storageos.svcs.errorhandling.resources.MigrationCallbackException;\n\n/**\n * Migration handler to convert value of type field for an export group, from\n * Exclusive to Initiator.\n */\npublic class ExportGroupTypeConverter extends BaseCustomMigrationCallback {\n\n private static final Logger log = LoggerFactory.getLogger(ExportGroupTypeConverter.class);\n\n private static final String TYPE_FIELD_NAME = \"type\";\n\n private static final String OLD_TYPE_VALUE = \"Exclusive\";\n\n @Override\n public void process() throws MigrationCallbackException {\n log.info(\"Handle ExportGroup type conversion\");\n DbClient dbClient = getDbClient();\n List exportGroupURIs = dbClient.queryByType(ExportGroup.class, false);\n Iterator exportGroupsIter = dbClient.queryIterativeObjectField(ExportGroup.class, TYPE_FIELD_NAME, exportGroupURIs);\n List exportGroups = new ArrayList();\n while (exportGroupsIter.hasNext()) {\n ExportGroup exportGroup = exportGroupsIter.next();\n String exportGroupId = exportGroup.getId().toString();\n log.info(\"Examining ExportGroup (id={}) for upgrade\", exportGroupId);\n String type = exportGroup.getType();\n if (type.equals(OLD_TYPE_VALUE)) {\n exportGroup.setType(ExportGroupType.Initiator.name());\n log.info(\"Reset export group type for export group (id={})\", exportGroupId);\n exportGroups.add(exportGroup);\n }\n }\n dbClient.persist", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_776", "language": "Java", "task_type": "if_statement", "source_file": "java/github/CoprHD/coprhd-controller/dbclient/src/main/java/com/emc/storageos/db/client/upgrade/callbacks/ExportGroupTypeConverter.java", "mask_start_position": 1760, "mask_end_position": 2019, "canonical_solution": "if (type.equals(OLD_TYPE_VALUE)) {\n exportGroup.setType(ExportGroupType.Initiator.name());\n log.info(\"Reset export group type for export group (id={})\", exportGroupId);\n exportGroups.add(exportGroup);\n }", "pre_mask_code": "/*\n * All Rights Reserved\n */\npackage com.emc.storageos.db.client.upgrade.callbacks;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.emc.storageos.db.client.DbClient;\nimport com.emc.storageos.db.client.model.ExportGroup;\nimport com.emc.storageos.db.client.model.ExportGroup.ExportGroupType;\nimport com.emc.storageos.db.client.upgrade.BaseCustomMigrationCallback;\nimport com.emc.storageos.svcs.errorhandling.resources.MigrationCallbackException;\n\n/**\n * Migration handler to convert value of type field for an export group, from\n * Exclusive to Initiator.\n */\npublic class ExportGroupTypeConverter extends BaseCustomMigrationCallback {\n\n private static final Logger log = LoggerFactory.getLogger(ExportGroupTypeConverter.class);\n\n private static final String TYPE_FIELD_NAME = \"type\";\n\n private static final String OLD_TYPE_VALUE = \"Exclusive\";\n\n @Override\n public void process() throws MigrationCallbackException {\n log.info(\"Handle ExportGroup type conversion\");\n DbClient dbClient = getDbClient();\n List exportGroupURIs = dbClient.queryByType(ExportGroup.class, false);\n Iterator exportGroupsIter = dbClient.queryIterativeObjectField(ExportGroup.class, TYPE_FIELD_NAME, exportGroupURIs);\n List exportGroups = new ArrayList();\n while (exportGroupsIter.hasNext()) {\n ExportGroup exportGroup = exportGroupsIter.next();\n String exportGroupId = exportGroup.getId().toString();\n log.info(\"Examining ExportGroup (id={}) for upgrade\", exportGroupId);\n String type = exportGroup.getType();\n ", "post_mask_code": "\n }\n dbClient.persistObject(exportGroups);\n }\n}\n"} {"task_id": "Java_777", "language": "Java", "task_type": "empty", "source_file": "java/github/CoprHD/coprhd-controller/dbclient/src/main/java/com/emc/storageos/db/client/upgrade/callbacks/ExportGroupTypeConverter.java", "mask_start_position": 1161, "mask_end_position": 1161, "canonical_solution": "", "pre_mask_code": "/*\n * All Rights Reserved\n */\npackage com.emc.storageos.db.client.upgrade.callbacks;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.emc.storageos.db.client.DbClient;\nimport com.emc.storageos.db.client.model.ExportGroup;\nimport com.emc.storageos.db.client.model.ExportGroup.ExportGroupType;\nimport com.emc.storageos.db.client.upgrade.BaseCustomMigrationCallback;\nimport com.emc.storageos.svcs.errorhandling.resources.MigrationCallbackException;\n\n/**\n * Migration handler to convert value of type field for an export group, from\n * Exclusive to Initiator.\n */\npublic class ExportGroupTypeConverter extends BaseCustomMigrationCallback {\n\n private static final Logger log = LoggerFactory.getLogger(ExportGroupTypeConverter.class);\n\n private static final String TYPE_FIELD_NAME = \"type\";\n\n private static final String OLD_TYPE_VALUE = \"Exclusive\";\n\n @Override\n public void process() throws MigrationCallbackException {\n log.info(\"Handle ExportGroup type conversion\");\n DbClient dbClient = getDbClient();\n List", "post_mask_code": " exportGroupURIs = dbClient.queryByType(ExportGroup.class, false);\n Iterator exportGroupsIter = dbClient.queryIterativeObjectField(ExportGroup.class, TYPE_FIELD_NAME, exportGroupURIs);\n List exportGroups = new ArrayList();\n while (exportGroupsIter.hasNext()) {\n ExportGroup exportGroup = exportGroupsIter.next();\n String exportGroupId = exportGroup.getId().toString();\n log.info(\"Examining ExportGroup (id={}) for upgrade\", exportGroupId);\n String type = exportGroup.getType();\n if (type.equals(OLD_TYPE_VALUE)) {\n exportGroup.setType(ExportGroupType.Initiator.name());\n log.info(\"Reset export group type for export group (id={})\", exportGroupId);\n exportGroups.add(exportGroup);\n }\n }\n dbClient.persistObject(exportGroups);\n }\n}\n"} {"task_id": "Java_778", "language": "Java", "task_type": "method_signature", "source_file": "java/github/OceanLabs/Android-Print-SDK/KitePrintSDK/src/main/java/ly/kite/widget/AnchorableImageView.java", "mask_start_position": 3495, "mask_end_position": 3535, "canonical_solution": "public void setAnchorPoint(float point) ", "pre_mask_code": "/**\n * **************************************************\n *\n * AnchorableImageView.java\n *\n * All rights reserved.\n *\n * This view displays an image anchored to its top.\n *\n * ***************************************************\n */\npackage ly.kite.widget;\n\nimport android.content.Context;\nimport android.graphics.Canvas;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.view.Gravity;\nimport android.widget.ImageView;\n\npublic class AnchorableImageView extends ImageView {\n\n @SuppressWarnings(\"unused\")\n private static final String LOG_TAG = \"AnchorableImageView\";\n\n private int mAnchorGravity;\n\n private float mAnchorPoint;\n\n private boolean mAnchored;\n\n private int mLeft;\n\n private int mTop;\n\n private int mRight;\n\n private int mBottom;\n\n public AnchorableImageView(Context context) {\n super(context);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n /**\n * **************************************************\n *\n * Sets the drawable.\n *\n * ***************************************************\n */\n @Override\n public void setImageDrawable(Drawable drawable) {\n super.setImageDrawable(drawable);\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n }\n\n /**\n * **************************************************\n *\n * Called when the size changes.\n *\n * ***************************************************\n */\n @Override\n public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {\n super.onSizeChanged(width, height, oldWidth, oldHeight);\n if (mAnchored)\n calculateDrawableBounds(width, height);\n }\n\n /**\n * **************************************************\n *\n * Draws the image view.\n *\n * ***************************************************\n */\n @Override\n public void onDraw(Canvas canvas) {\n if (mAnchored) {\n // Get the image\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n // Draw the image onto the canvas\n drawable.setBounds(mLeft, mTop, mRight, mBottom);\n drawable.draw(canvas);\n } else {\n super.onDraw(canvas);\n }\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor gravity.\n *\n * ***************************************************\n */\n public void setAnchorGravity(int gravity) {\n mAnchorGravity = gravity;\n if (gravity == Gravity.LEFT || gravity == Gravity.TOP || gravity == Gravity.RIGHT || gravity == Gravity.BOTTOM) {\n mAnchored = true;\n calculateDrawableBounds(getWidth(), getHeight());\n } else {\n mAnchored = false;\n }\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor point. This is the point on the image\n * (as a proportion of the image size) that is fixed to\n * the anchor position (defined by the gravity).\n *\n * Has no effect if the anchor gravity is not set.\n *\n * ***************************************************\n */\n ", "post_mask_code": "{\n mAnchorPoint = point;\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Calculates the drawable bounds.\n *\n * TODO: Factor in the anchor point\n *\n * ***************************************************\n */\n private void calculateDrawableBounds(int viewWidth, int viewHeight) {\n // Make sure we have all the details we need\n if (viewWidth < 1 || viewHeight < 1)\n return;\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n int drawableWidth = drawable.getIntrinsicWidth();\n int drawableHeight = drawable.getIntrinsicHeight();\n if (drawableWidth < 1 || drawableHeight < 1)\n return;\n int viewHalfWidth = (int) (viewWidth * 0.5f);\n int viewHalfHeight = (int) (viewHeight * 0.5f);\n // Since we are being anchored, we have the option of filling the entire view, or\n // fitting inside it. Work out which from the scale type.\n ScaleType scaleType = getScaleType();\n boolean fillView = (scaleType == ScaleType.CENTER_CROP || scaleType == ScaleType.CENTER.FIT_END || scaleType == ScaleType.FIT_XY);\n // Calculate the scale factor according to whether we're filling the view or not\n float widthScaleFactor = (float) viewWidth / (float) drawableWidth;\n float heightScaleFactor = (float) viewHeight / (float) drawableHeight;\n float scaleFactor;\n if (fillView) {\n scaleFactor = Math.max(widthScaleFactor, heightScaleFactor);\n } else {\n scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);\n }\n int scaledDrawableWidth = (int) (drawableWidth * scaleFactor);\n int scaledDrawableHeight = (int) (drawableHeight * scaleFactor);\n int scaledDrawableHalfWidth = (int) (scaledDrawableWidth * 0.5f);\n int scaledDrawableHalfHeight = (int) (scaledDrawableHeight * 0.5f);\n // Once we've determined what the anchor gravity is, calculate the bounds\n // of the image to match.\n if (mAnchorGravity == Gravity.LEFT) {\n mLeft = 0;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = scaledDrawableWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.TOP) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = 0;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = scaledDrawableHeight;\n } else if (mAnchorGravity == Gravity.RIGHT) {\n mLeft = viewWidth - scaledDrawableWidth;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = viewWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.BOTTOM) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = viewHeight - scaledDrawableHeight;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = viewHeight;\n }\n }\n}\n"} {"task_id": "Java_779", "language": "Java", "task_type": "method_body", "source_file": "java/github/OceanLabs/Android-Print-SDK/KitePrintSDK/src/main/java/ly/kite/widget/AnchorableImageView.java", "mask_start_position": 3535, "mask_end_position": 3679, "canonical_solution": "{\n mAnchorPoint = point;\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n invalidate();\n }", "pre_mask_code": "/**\n * **************************************************\n *\n * AnchorableImageView.java\n *\n * All rights reserved.\n *\n * This view displays an image anchored to its top.\n *\n * ***************************************************\n */\npackage ly.kite.widget;\n\nimport android.content.Context;\nimport android.graphics.Canvas;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.view.Gravity;\nimport android.widget.ImageView;\n\npublic class AnchorableImageView extends ImageView {\n\n @SuppressWarnings(\"unused\")\n private static final String LOG_TAG = \"AnchorableImageView\";\n\n private int mAnchorGravity;\n\n private float mAnchorPoint;\n\n private boolean mAnchored;\n\n private int mLeft;\n\n private int mTop;\n\n private int mRight;\n\n private int mBottom;\n\n public AnchorableImageView(Context context) {\n super(context);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n /**\n * **************************************************\n *\n * Sets the drawable.\n *\n * ***************************************************\n */\n @Override\n public void setImageDrawable(Drawable drawable) {\n super.setImageDrawable(drawable);\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n }\n\n /**\n * **************************************************\n *\n * Called when the size changes.\n *\n * ***************************************************\n */\n @Override\n public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {\n super.onSizeChanged(width, height, oldWidth, oldHeight);\n if (mAnchored)\n calculateDrawableBounds(width, height);\n }\n\n /**\n * **************************************************\n *\n * Draws the image view.\n *\n * ***************************************************\n */\n @Override\n public void onDraw(Canvas canvas) {\n if (mAnchored) {\n // Get the image\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n // Draw the image onto the canvas\n drawable.setBounds(mLeft, mTop, mRight, mBottom);\n drawable.draw(canvas);\n } else {\n super.onDraw(canvas);\n }\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor gravity.\n *\n * ***************************************************\n */\n public void setAnchorGravity(int gravity) {\n mAnchorGravity = gravity;\n if (gravity == Gravity.LEFT || gravity == Gravity.TOP || gravity == Gravity.RIGHT || gravity == Gravity.BOTTOM) {\n mAnchored = true;\n calculateDrawableBounds(getWidth(), getHeight());\n } else {\n mAnchored = false;\n }\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor point. This is the point on the image\n * (as a proportion of the image size) that is fixed to\n * the anchor position (defined by the gravity).\n *\n * Has no effect if the anchor gravity is not set.\n *\n * ***************************************************\n */\n public void setAnchorPoint(float point) ", "post_mask_code": "\n\n /**\n * **************************************************\n *\n * Calculates the drawable bounds.\n *\n * TODO: Factor in the anchor point\n *\n * ***************************************************\n */\n private void calculateDrawableBounds(int viewWidth, int viewHeight) {\n // Make sure we have all the details we need\n if (viewWidth < 1 || viewHeight < 1)\n return;\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n int drawableWidth = drawable.getIntrinsicWidth();\n int drawableHeight = drawable.getIntrinsicHeight();\n if (drawableWidth < 1 || drawableHeight < 1)\n return;\n int viewHalfWidth = (int) (viewWidth * 0.5f);\n int viewHalfHeight = (int) (viewHeight * 0.5f);\n // Since we are being anchored, we have the option of filling the entire view, or\n // fitting inside it. Work out which from the scale type.\n ScaleType scaleType = getScaleType();\n boolean fillView = (scaleType == ScaleType.CENTER_CROP || scaleType == ScaleType.CENTER.FIT_END || scaleType == ScaleType.FIT_XY);\n // Calculate the scale factor according to whether we're filling the view or not\n float widthScaleFactor = (float) viewWidth / (float) drawableWidth;\n float heightScaleFactor = (float) viewHeight / (float) drawableHeight;\n float scaleFactor;\n if (fillView) {\n scaleFactor = Math.max(widthScaleFactor, heightScaleFactor);\n } else {\n scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);\n }\n int scaledDrawableWidth = (int) (drawableWidth * scaleFactor);\n int scaledDrawableHeight = (int) (drawableHeight * scaleFactor);\n int scaledDrawableHalfWidth = (int) (scaledDrawableWidth * 0.5f);\n int scaledDrawableHalfHeight = (int) (scaledDrawableHeight * 0.5f);\n // Once we've determined what the anchor gravity is, calculate the bounds\n // of the image to match.\n if (mAnchorGravity == Gravity.LEFT) {\n mLeft = 0;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = scaledDrawableWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.TOP) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = 0;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = scaledDrawableHeight;\n } else if (mAnchorGravity == Gravity.RIGHT) {\n mLeft = viewWidth - scaledDrawableWidth;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = viewWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.BOTTOM) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = viewHeight - scaledDrawableHeight;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = viewHeight;\n }\n }\n}\n"} {"task_id": "Java_780", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/OceanLabs/Android-Print-SDK/KitePrintSDK/src/main/java/ly/kite/widget/AnchorableImageView.java", "mask_start_position": 2768, "mask_end_position": 2802, "canonical_solution": "\n mAnchorGravity = gravity;", "pre_mask_code": "/**\n * **************************************************\n *\n * AnchorableImageView.java\n *\n * All rights reserved.\n *\n * This view displays an image anchored to its top.\n *\n * ***************************************************\n */\npackage ly.kite.widget;\n\nimport android.content.Context;\nimport android.graphics.Canvas;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.view.Gravity;\nimport android.widget.ImageView;\n\npublic class AnchorableImageView extends ImageView {\n\n @SuppressWarnings(\"unused\")\n private static final String LOG_TAG = \"AnchorableImageView\";\n\n private int mAnchorGravity;\n\n private float mAnchorPoint;\n\n private boolean mAnchored;\n\n private int mLeft;\n\n private int mTop;\n\n private int mRight;\n\n private int mBottom;\n\n public AnchorableImageView(Context context) {\n super(context);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n /**\n * **************************************************\n *\n * Sets the drawable.\n *\n * ***************************************************\n */\n @Override\n public void setImageDrawable(Drawable drawable) {\n super.setImageDrawable(drawable);\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n }\n\n /**\n * **************************************************\n *\n * Called when the size changes.\n *\n * ***************************************************\n */\n @Override\n public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {\n super.onSizeChanged(width, height, oldWidth, oldHeight);\n if (mAnchored)\n calculateDrawableBounds(width, height);\n }\n\n /**\n * **************************************************\n *\n * Draws the image view.\n *\n * ***************************************************\n */\n @Override\n public void onDraw(Canvas canvas) {\n if (mAnchored) {\n // Get the image\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n // Draw the image onto the canvas\n drawable.setBounds(mLeft, mTop, mRight, mBottom);\n drawable.draw(canvas);\n } else {\n super.onDraw(canvas);\n }\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor gravity.\n *\n * ***************************************************\n */\n public void setAnchorGravity(int gravity) {", "post_mask_code": "\n if (gravity == Gravity.LEFT || gravity == Gravity.TOP || gravity == Gravity.RIGHT || gravity == Gravity.BOTTOM) {\n mAnchored = true;\n calculateDrawableBounds(getWidth(), getHeight());\n } else {\n mAnchored = false;\n }\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor point. This is the point on the image\n * (as a proportion of the image size) that is fixed to\n * the anchor position (defined by the gravity).\n *\n * Has no effect if the anchor gravity is not set.\n *\n * ***************************************************\n */\n public void setAnchorPoint(float point) {\n mAnchorPoint = point;\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Calculates the drawable bounds.\n *\n * TODO: Factor in the anchor point\n *\n * ***************************************************\n */\n private void calculateDrawableBounds(int viewWidth, int viewHeight) {\n // Make sure we have all the details we need\n if (viewWidth < 1 || viewHeight < 1)\n return;\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n int drawableWidth = drawable.getIntrinsicWidth();\n int drawableHeight = drawable.getIntrinsicHeight();\n if (drawableWidth < 1 || drawableHeight < 1)\n return;\n int viewHalfWidth = (int) (viewWidth * 0.5f);\n int viewHalfHeight = (int) (viewHeight * 0.5f);\n // Since we are being anchored, we have the option of filling the entire view, or\n // fitting inside it. Work out which from the scale type.\n ScaleType scaleType = getScaleType();\n boolean fillView = (scaleType == ScaleType.CENTER_CROP || scaleType == ScaleType.CENTER.FIT_END || scaleType == ScaleType.FIT_XY);\n // Calculate the scale factor according to whether we're filling the view or not\n float widthScaleFactor = (float) viewWidth / (float) drawableWidth;\n float heightScaleFactor = (float) viewHeight / (float) drawableHeight;\n float scaleFactor;\n if (fillView) {\n scaleFactor = Math.max(widthScaleFactor, heightScaleFactor);\n } else {\n scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);\n }\n int scaledDrawableWidth = (int) (drawableWidth * scaleFactor);\n int scaledDrawableHeight = (int) (drawableHeight * scaleFactor);\n int scaledDrawableHalfWidth = (int) (scaledDrawableWidth * 0.5f);\n int scaledDrawableHalfHeight = (int) (scaledDrawableHeight * 0.5f);\n // Once we've determined what the anchor gravity is, calculate the bounds\n // of the image to match.\n if (mAnchorGravity == Gravity.LEFT) {\n mLeft = 0;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = scaledDrawableWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.TOP) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = 0;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = scaledDrawableHeight;\n } else if (mAnchorGravity == Gravity.RIGHT) {\n mLeft = viewWidth - scaledDrawableWidth;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = viewWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.BOTTOM) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = viewHeight - scaledDrawableHeight;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = viewHeight;\n }\n }\n}\n"} {"task_id": "Java_781", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/OceanLabs/Android-Print-SDK/KitePrintSDK/src/main/java/ly/kite/widget/AnchorableImageView.java", "mask_start_position": 2811, "mask_end_position": 3074, "canonical_solution": "if (gravity == Gravity.LEFT || gravity == Gravity.TOP || gravity == Gravity.RIGHT || gravity == Gravity.BOTTOM) {\n mAnchored = true;\n calculateDrawableBounds(getWidth(), getHeight());\n } else {\n mAnchored = false;\n }", "pre_mask_code": "/**\n * **************************************************\n *\n * AnchorableImageView.java\n *\n * All rights reserved.\n *\n * This view displays an image anchored to its top.\n *\n * ***************************************************\n */\npackage ly.kite.widget;\n\nimport android.content.Context;\nimport android.graphics.Canvas;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.view.Gravity;\nimport android.widget.ImageView;\n\npublic class AnchorableImageView extends ImageView {\n\n @SuppressWarnings(\"unused\")\n private static final String LOG_TAG = \"AnchorableImageView\";\n\n private int mAnchorGravity;\n\n private float mAnchorPoint;\n\n private boolean mAnchored;\n\n private int mLeft;\n\n private int mTop;\n\n private int mRight;\n\n private int mBottom;\n\n public AnchorableImageView(Context context) {\n super(context);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n /**\n * **************************************************\n *\n * Sets the drawable.\n *\n * ***************************************************\n */\n @Override\n public void setImageDrawable(Drawable drawable) {\n super.setImageDrawable(drawable);\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n }\n\n /**\n * **************************************************\n *\n * Called when the size changes.\n *\n * ***************************************************\n */\n @Override\n public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {\n super.onSizeChanged(width, height, oldWidth, oldHeight);\n if (mAnchored)\n calculateDrawableBounds(width, height);\n }\n\n /**\n * **************************************************\n *\n * Draws the image view.\n *\n * ***************************************************\n */\n @Override\n public void onDraw(Canvas canvas) {\n if (mAnchored) {\n // Get the image\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n // Draw the image onto the canvas\n drawable.setBounds(mLeft, mTop, mRight, mBottom);\n drawable.draw(canvas);\n } else {\n super.onDraw(canvas);\n }\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor gravity.\n *\n * ***************************************************\n */\n public void setAnchorGravity(int gravity) {\n mAnchorGravity = gravity;\n ", "post_mask_code": "\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor point. This is the point on the image\n * (as a proportion of the image size) that is fixed to\n * the anchor position (defined by the gravity).\n *\n * Has no effect if the anchor gravity is not set.\n *\n * ***************************************************\n */\n public void setAnchorPoint(float point) {\n mAnchorPoint = point;\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Calculates the drawable bounds.\n *\n * TODO: Factor in the anchor point\n *\n * ***************************************************\n */\n private void calculateDrawableBounds(int viewWidth, int viewHeight) {\n // Make sure we have all the details we need\n if (viewWidth < 1 || viewHeight < 1)\n return;\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n int drawableWidth = drawable.getIntrinsicWidth();\n int drawableHeight = drawable.getIntrinsicHeight();\n if (drawableWidth < 1 || drawableHeight < 1)\n return;\n int viewHalfWidth = (int) (viewWidth * 0.5f);\n int viewHalfHeight = (int) (viewHeight * 0.5f);\n // Since we are being anchored, we have the option of filling the entire view, or\n // fitting inside it. Work out which from the scale type.\n ScaleType scaleType = getScaleType();\n boolean fillView = (scaleType == ScaleType.CENTER_CROP || scaleType == ScaleType.CENTER.FIT_END || scaleType == ScaleType.FIT_XY);\n // Calculate the scale factor according to whether we're filling the view or not\n float widthScaleFactor = (float) viewWidth / (float) drawableWidth;\n float heightScaleFactor = (float) viewHeight / (float) drawableHeight;\n float scaleFactor;\n if (fillView) {\n scaleFactor = Math.max(widthScaleFactor, heightScaleFactor);\n } else {\n scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);\n }\n int scaledDrawableWidth = (int) (drawableWidth * scaleFactor);\n int scaledDrawableHeight = (int) (drawableHeight * scaleFactor);\n int scaledDrawableHalfWidth = (int) (scaledDrawableWidth * 0.5f);\n int scaledDrawableHalfHeight = (int) (scaledDrawableHeight * 0.5f);\n // Once we've determined what the anchor gravity is, calculate the bounds\n // of the image to match.\n if (mAnchorGravity == Gravity.LEFT) {\n mLeft = 0;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = scaledDrawableWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.TOP) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = 0;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = scaledDrawableHeight;\n } else if (mAnchorGravity == Gravity.RIGHT) {\n mLeft = viewWidth - scaledDrawableWidth;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = viewWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.BOTTOM) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = viewHeight - scaledDrawableHeight;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = viewHeight;\n }\n }\n}\n"} {"task_id": "Java_782", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/OceanLabs/Android-Print-SDK/KitePrintSDK/src/main/java/ly/kite/widget/AnchorableImageView.java", "mask_start_position": 3083, "mask_end_position": 3102, "canonical_solution": "invalidate();\n }", "pre_mask_code": "/**\n * **************************************************\n *\n * AnchorableImageView.java\n *\n * All rights reserved.\n *\n * This view displays an image anchored to its top.\n *\n * ***************************************************\n */\npackage ly.kite.widget;\n\nimport android.content.Context;\nimport android.graphics.Canvas;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.view.Gravity;\nimport android.widget.ImageView;\n\npublic class AnchorableImageView extends ImageView {\n\n @SuppressWarnings(\"unused\")\n private static final String LOG_TAG = \"AnchorableImageView\";\n\n private int mAnchorGravity;\n\n private float mAnchorPoint;\n\n private boolean mAnchored;\n\n private int mLeft;\n\n private int mTop;\n\n private int mRight;\n\n private int mBottom;\n\n public AnchorableImageView(Context context) {\n super(context);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n /**\n * **************************************************\n *\n * Sets the drawable.\n *\n * ***************************************************\n */\n @Override\n public void setImageDrawable(Drawable drawable) {\n super.setImageDrawable(drawable);\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n }\n\n /**\n * **************************************************\n *\n * Called when the size changes.\n *\n * ***************************************************\n */\n @Override\n public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {\n super.onSizeChanged(width, height, oldWidth, oldHeight);\n if (mAnchored)\n calculateDrawableBounds(width, height);\n }\n\n /**\n * **************************************************\n *\n * Draws the image view.\n *\n * ***************************************************\n */\n @Override\n public void onDraw(Canvas canvas) {\n if (mAnchored) {\n // Get the image\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n // Draw the image onto the canvas\n drawable.setBounds(mLeft, mTop, mRight, mBottom);\n drawable.draw(canvas);\n } else {\n super.onDraw(canvas);\n }\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor gravity.\n *\n * ***************************************************\n */\n public void setAnchorGravity(int gravity) {\n mAnchorGravity = gravity;\n if (gravity == Gravity.LEFT || gravity == Gravity.TOP || gravity == Gravity.RIGHT || gravity == Gravity.BOTTOM) {\n mAnchored = true;\n calculateDrawableBounds(getWidth(), getHeight());\n } else {\n mAnchored = false;\n }\n ", "post_mask_code": "\n\n /**\n * **************************************************\n *\n * Sets the anchor point. This is the point on the image\n * (as a proportion of the image size) that is fixed to\n * the anchor position (defined by the gravity).\n *\n * Has no effect if the anchor gravity is not set.\n *\n * ***************************************************\n */\n public void setAnchorPoint(float point) {\n mAnchorPoint = point;\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Calculates the drawable bounds.\n *\n * TODO: Factor in the anchor point\n *\n * ***************************************************\n */\n private void calculateDrawableBounds(int viewWidth, int viewHeight) {\n // Make sure we have all the details we need\n if (viewWidth < 1 || viewHeight < 1)\n return;\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n int drawableWidth = drawable.getIntrinsicWidth();\n int drawableHeight = drawable.getIntrinsicHeight();\n if (drawableWidth < 1 || drawableHeight < 1)\n return;\n int viewHalfWidth = (int) (viewWidth * 0.5f);\n int viewHalfHeight = (int) (viewHeight * 0.5f);\n // Since we are being anchored, we have the option of filling the entire view, or\n // fitting inside it. Work out which from the scale type.\n ScaleType scaleType = getScaleType();\n boolean fillView = (scaleType == ScaleType.CENTER_CROP || scaleType == ScaleType.CENTER.FIT_END || scaleType == ScaleType.FIT_XY);\n // Calculate the scale factor according to whether we're filling the view or not\n float widthScaleFactor = (float) viewWidth / (float) drawableWidth;\n float heightScaleFactor = (float) viewHeight / (float) drawableHeight;\n float scaleFactor;\n if (fillView) {\n scaleFactor = Math.max(widthScaleFactor, heightScaleFactor);\n } else {\n scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);\n }\n int scaledDrawableWidth = (int) (drawableWidth * scaleFactor);\n int scaledDrawableHeight = (int) (drawableHeight * scaleFactor);\n int scaledDrawableHalfWidth = (int) (scaledDrawableWidth * 0.5f);\n int scaledDrawableHalfHeight = (int) (scaledDrawableHeight * 0.5f);\n // Once we've determined what the anchor gravity is, calculate the bounds\n // of the image to match.\n if (mAnchorGravity == Gravity.LEFT) {\n mLeft = 0;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = scaledDrawableWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.TOP) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = 0;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = scaledDrawableHeight;\n } else if (mAnchorGravity == Gravity.RIGHT) {\n mLeft = viewWidth - scaledDrawableWidth;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = viewWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.BOTTOM) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = viewHeight - scaledDrawableHeight;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = viewHeight;\n }\n }\n}\n"} {"task_id": "Java_783", "language": "Java", "task_type": "single_line", "source_file": "java/github/OceanLabs/Android-Print-SDK/KitePrintSDK/src/main/java/ly/kite/widget/AnchorableImageView.java", "mask_start_position": 4238, "mask_end_position": 4258, "canonical_solution": "getIntrinsicWidth();", "pre_mask_code": "/**\n * **************************************************\n *\n * AnchorableImageView.java\n *\n * All rights reserved.\n *\n * This view displays an image anchored to its top.\n *\n * ***************************************************\n */\npackage ly.kite.widget;\n\nimport android.content.Context;\nimport android.graphics.Canvas;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.view.Gravity;\nimport android.widget.ImageView;\n\npublic class AnchorableImageView extends ImageView {\n\n @SuppressWarnings(\"unused\")\n private static final String LOG_TAG = \"AnchorableImageView\";\n\n private int mAnchorGravity;\n\n private float mAnchorPoint;\n\n private boolean mAnchored;\n\n private int mLeft;\n\n private int mTop;\n\n private int mRight;\n\n private int mBottom;\n\n public AnchorableImageView(Context context) {\n super(context);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n /**\n * **************************************************\n *\n * Sets the drawable.\n *\n * ***************************************************\n */\n @Override\n public void setImageDrawable(Drawable drawable) {\n super.setImageDrawable(drawable);\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n }\n\n /**\n * **************************************************\n *\n * Called when the size changes.\n *\n * ***************************************************\n */\n @Override\n public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {\n super.onSizeChanged(width, height, oldWidth, oldHeight);\n if (mAnchored)\n calculateDrawableBounds(width, height);\n }\n\n /**\n * **************************************************\n *\n * Draws the image view.\n *\n * ***************************************************\n */\n @Override\n public void onDraw(Canvas canvas) {\n if (mAnchored) {\n // Get the image\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n // Draw the image onto the canvas\n drawable.setBounds(mLeft, mTop, mRight, mBottom);\n drawable.draw(canvas);\n } else {\n super.onDraw(canvas);\n }\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor gravity.\n *\n * ***************************************************\n */\n public void setAnchorGravity(int gravity) {\n mAnchorGravity = gravity;\n if (gravity == Gravity.LEFT || gravity == Gravity.TOP || gravity == Gravity.RIGHT || gravity == Gravity.BOTTOM) {\n mAnchored = true;\n calculateDrawableBounds(getWidth(), getHeight());\n } else {\n mAnchored = false;\n }\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor point. This is the point on the image\n * (as a proportion of the image size) that is fixed to\n * the anchor position (defined by the gravity).\n *\n * Has no effect if the anchor gravity is not set.\n *\n * ***************************************************\n */\n public void setAnchorPoint(float point) {\n mAnchorPoint = point;\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Calculates the drawable bounds.\n *\n * TODO: Factor in the anchor point\n *\n * ***************************************************\n */\n private void calculateDrawableBounds(int viewWidth, int viewHeight) {\n // Make sure we have all the details we need\n if (viewWidth < 1 || viewHeight < 1)\n return;\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n int drawableWidth = drawable.", "post_mask_code": "\n int drawableHeight = drawable.getIntrinsicHeight();\n if (drawableWidth < 1 || drawableHeight < 1)\n return;\n int viewHalfWidth = (int) (viewWidth * 0.5f);\n int viewHalfHeight = (int) (viewHeight * 0.5f);\n // Since we are being anchored, we have the option of filling the entire view, or\n // fitting inside it. Work out which from the scale type.\n ScaleType scaleType = getScaleType();\n boolean fillView = (scaleType == ScaleType.CENTER_CROP || scaleType == ScaleType.CENTER.FIT_END || scaleType == ScaleType.FIT_XY);\n // Calculate the scale factor according to whether we're filling the view or not\n float widthScaleFactor = (float) viewWidth / (float) drawableWidth;\n float heightScaleFactor = (float) viewHeight / (float) drawableHeight;\n float scaleFactor;\n if (fillView) {\n scaleFactor = Math.max(widthScaleFactor, heightScaleFactor);\n } else {\n scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);\n }\n int scaledDrawableWidth = (int) (drawableWidth * scaleFactor);\n int scaledDrawableHeight = (int) (drawableHeight * scaleFactor);\n int scaledDrawableHalfWidth = (int) (scaledDrawableWidth * 0.5f);\n int scaledDrawableHalfHeight = (int) (scaledDrawableHeight * 0.5f);\n // Once we've determined what the anchor gravity is, calculate the bounds\n // of the image to match.\n if (mAnchorGravity == Gravity.LEFT) {\n mLeft = 0;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = scaledDrawableWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.TOP) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = 0;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = scaledDrawableHeight;\n } else if (mAnchorGravity == Gravity.RIGHT) {\n mLeft = viewWidth - scaledDrawableWidth;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = viewWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.BOTTOM) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = viewHeight - scaledDrawableHeight;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = viewHeight;\n }\n }\n}\n"} {"task_id": "Java_784", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/OceanLabs/Android-Print-SDK/KitePrintSDK/src/main/java/ly/kite/widget/AnchorableImageView.java", "mask_start_position": 2725, "mask_end_position": 3102, "canonical_solution": "public void setAnchorGravity(int gravity) {\n mAnchorGravity = gravity;\n if (gravity == Gravity.LEFT || gravity == Gravity.TOP || gravity == Gravity.RIGHT || gravity == Gravity.BOTTOM) {\n mAnchored = true;\n calculateDrawableBounds(getWidth(), getHeight());\n } else {\n mAnchored = false;\n }\n invalidate();\n }", "pre_mask_code": "/**\n * **************************************************\n *\n * AnchorableImageView.java\n *\n * All rights reserved.\n *\n * This view displays an image anchored to its top.\n *\n * ***************************************************\n */\npackage ly.kite.widget;\n\nimport android.content.Context;\nimport android.graphics.Canvas;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.view.Gravity;\nimport android.widget.ImageView;\n\npublic class AnchorableImageView extends ImageView {\n\n @SuppressWarnings(\"unused\")\n private static final String LOG_TAG = \"AnchorableImageView\";\n\n private int mAnchorGravity;\n\n private float mAnchorPoint;\n\n private boolean mAnchored;\n\n private int mLeft;\n\n private int mTop;\n\n private int mRight;\n\n private int mBottom;\n\n public AnchorableImageView(Context context) {\n super(context);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n /**\n * **************************************************\n *\n * Sets the drawable.\n *\n * ***************************************************\n */\n @Override\n public void setImageDrawable(Drawable drawable) {\n super.setImageDrawable(drawable);\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n }\n\n /**\n * **************************************************\n *\n * Called when the size changes.\n *\n * ***************************************************\n */\n @Override\n public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {\n super.onSizeChanged(width, height, oldWidth, oldHeight);\n if (mAnchored)\n calculateDrawableBounds(width, height);\n }\n\n /**\n * **************************************************\n *\n * Draws the image view.\n *\n * ***************************************************\n */\n @Override\n public void onDraw(Canvas canvas) {\n if (mAnchored) {\n // Get the image\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n // Draw the image onto the canvas\n drawable.setBounds(mLeft, mTop, mRight, mBottom);\n drawable.draw(canvas);\n } else {\n super.onDraw(canvas);\n }\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor gravity.\n *\n * ***************************************************\n */\n ", "post_mask_code": "\n\n /**\n * **************************************************\n *\n * Sets the anchor point. This is the point on the image\n * (as a proportion of the image size) that is fixed to\n * the anchor position (defined by the gravity).\n *\n * Has no effect if the anchor gravity is not set.\n *\n * ***************************************************\n */\n public void setAnchorPoint(float point) {\n mAnchorPoint = point;\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Calculates the drawable bounds.\n *\n * TODO: Factor in the anchor point\n *\n * ***************************************************\n */\n private void calculateDrawableBounds(int viewWidth, int viewHeight) {\n // Make sure we have all the details we need\n if (viewWidth < 1 || viewHeight < 1)\n return;\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n int drawableWidth = drawable.getIntrinsicWidth();\n int drawableHeight = drawable.getIntrinsicHeight();\n if (drawableWidth < 1 || drawableHeight < 1)\n return;\n int viewHalfWidth = (int) (viewWidth * 0.5f);\n int viewHalfHeight = (int) (viewHeight * 0.5f);\n // Since we are being anchored, we have the option of filling the entire view, or\n // fitting inside it. Work out which from the scale type.\n ScaleType scaleType = getScaleType();\n boolean fillView = (scaleType == ScaleType.CENTER_CROP || scaleType == ScaleType.CENTER.FIT_END || scaleType == ScaleType.FIT_XY);\n // Calculate the scale factor according to whether we're filling the view or not\n float widthScaleFactor = (float) viewWidth / (float) drawableWidth;\n float heightScaleFactor = (float) viewHeight / (float) drawableHeight;\n float scaleFactor;\n if (fillView) {\n scaleFactor = Math.max(widthScaleFactor, heightScaleFactor);\n } else {\n scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);\n }\n int scaledDrawableWidth = (int) (drawableWidth * scaleFactor);\n int scaledDrawableHeight = (int) (drawableHeight * scaleFactor);\n int scaledDrawableHalfWidth = (int) (scaledDrawableWidth * 0.5f);\n int scaledDrawableHalfHeight = (int) (scaledDrawableHeight * 0.5f);\n // Once we've determined what the anchor gravity is, calculate the bounds\n // of the image to match.\n if (mAnchorGravity == Gravity.LEFT) {\n mLeft = 0;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = scaledDrawableWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.TOP) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = 0;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = scaledDrawableHeight;\n } else if (mAnchorGravity == Gravity.RIGHT) {\n mLeft = viewWidth - scaledDrawableWidth;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = viewWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.BOTTOM) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = viewHeight - scaledDrawableHeight;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = viewHeight;\n }\n }\n}\n"} {"task_id": "Java_785", "language": "Java", "task_type": "if_statement", "source_file": "java/github/OceanLabs/Android-Print-SDK/KitePrintSDK/src/main/java/ly/kite/widget/AnchorableImageView.java", "mask_start_position": 5122, "mask_end_position": 5310, "canonical_solution": "if (fillView) {\n scaleFactor = Math.max(widthScaleFactor, heightScaleFactor);\n } else {\n scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);\n }", "pre_mask_code": "/**\n * **************************************************\n *\n * AnchorableImageView.java\n *\n * All rights reserved.\n *\n * This view displays an image anchored to its top.\n *\n * ***************************************************\n */\npackage ly.kite.widget;\n\nimport android.content.Context;\nimport android.graphics.Canvas;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.view.Gravity;\nimport android.widget.ImageView;\n\npublic class AnchorableImageView extends ImageView {\n\n @SuppressWarnings(\"unused\")\n private static final String LOG_TAG = \"AnchorableImageView\";\n\n private int mAnchorGravity;\n\n private float mAnchorPoint;\n\n private boolean mAnchored;\n\n private int mLeft;\n\n private int mTop;\n\n private int mRight;\n\n private int mBottom;\n\n public AnchorableImageView(Context context) {\n super(context);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n /**\n * **************************************************\n *\n * Sets the drawable.\n *\n * ***************************************************\n */\n @Override\n public void setImageDrawable(Drawable drawable) {\n super.setImageDrawable(drawable);\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n }\n\n /**\n * **************************************************\n *\n * Called when the size changes.\n *\n * ***************************************************\n */\n @Override\n public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {\n super.onSizeChanged(width, height, oldWidth, oldHeight);\n if (mAnchored)\n calculateDrawableBounds(width, height);\n }\n\n /**\n * **************************************************\n *\n * Draws the image view.\n *\n * ***************************************************\n */\n @Override\n public void onDraw(Canvas canvas) {\n if (mAnchored) {\n // Get the image\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n // Draw the image onto the canvas\n drawable.setBounds(mLeft, mTop, mRight, mBottom);\n drawable.draw(canvas);\n } else {\n super.onDraw(canvas);\n }\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor gravity.\n *\n * ***************************************************\n */\n public void setAnchorGravity(int gravity) {\n mAnchorGravity = gravity;\n if (gravity == Gravity.LEFT || gravity == Gravity.TOP || gravity == Gravity.RIGHT || gravity == Gravity.BOTTOM) {\n mAnchored = true;\n calculateDrawableBounds(getWidth(), getHeight());\n } else {\n mAnchored = false;\n }\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor point. This is the point on the image\n * (as a proportion of the image size) that is fixed to\n * the anchor position (defined by the gravity).\n *\n * Has no effect if the anchor gravity is not set.\n *\n * ***************************************************\n */\n public void setAnchorPoint(float point) {\n mAnchorPoint = point;\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Calculates the drawable bounds.\n *\n * TODO: Factor in the anchor point\n *\n * ***************************************************\n */\n private void calculateDrawableBounds(int viewWidth, int viewHeight) {\n // Make sure we have all the details we need\n if (viewWidth < 1 || viewHeight < 1)\n return;\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n int drawableWidth = drawable.getIntrinsicWidth();\n int drawableHeight = drawable.getIntrinsicHeight();\n if (drawableWidth < 1 || drawableHeight < 1)\n return;\n int viewHalfWidth = (int) (viewWidth * 0.5f);\n int viewHalfHeight = (int) (viewHeight * 0.5f);\n // Since we are being anchored, we have the option of filling the entire view, or\n // fitting inside it. Work out which from the scale type.\n ScaleType scaleType = getScaleType();\n boolean fillView = (scaleType == ScaleType.CENTER_CROP || scaleType == ScaleType.CENTER.FIT_END || scaleType == ScaleType.FIT_XY);\n // Calculate the scale factor according to whether we're filling the view or not\n float widthScaleFactor = (float) viewWidth / (float) drawableWidth;\n float heightScaleFactor = (float) viewHeight / (float) drawableHeight;\n float scaleFactor;\n ", "post_mask_code": "\n int scaledDrawableWidth = (int) (drawableWidth * scaleFactor);\n int scaledDrawableHeight = (int) (drawableHeight * scaleFactor);\n int scaledDrawableHalfWidth = (int) (scaledDrawableWidth * 0.5f);\n int scaledDrawableHalfHeight = (int) (scaledDrawableHeight * 0.5f);\n // Once we've determined what the anchor gravity is, calculate the bounds\n // of the image to match.\n if (mAnchorGravity == Gravity.LEFT) {\n mLeft = 0;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = scaledDrawableWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.TOP) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = 0;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = scaledDrawableHeight;\n } else if (mAnchorGravity == Gravity.RIGHT) {\n mLeft = viewWidth - scaledDrawableWidth;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = viewWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.BOTTOM) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = viewHeight - scaledDrawableHeight;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = viewHeight;\n }\n }\n}\n"} {"task_id": "Java_786", "language": "Java", "task_type": "empty", "source_file": "java/github/OceanLabs/Android-Print-SDK/KitePrintSDK/src/main/java/ly/kite/widget/AnchorableImageView.java", "mask_start_position": 1531, "mask_end_position": 1531, "canonical_solution": "", "pre_mask_code": "/**\n * **************************************************\n *\n * AnchorableImageView.java\n *\n * All rights reserved.\n *\n * This view displays an image anchored to its top.\n *\n * ***************************************************\n */\npackage ly.kite.widget;\n\nimport android.content.Context;\nimport android.graphics.Canvas;\nimport android.graphics.drawable.Drawable;\nimport android.util.AttributeSet;\nimport android.view.Gravity;\nimport android.widget.ImageView;\n\npublic class AnchorableImageView extends ImageView {\n\n @SuppressWarnings(\"unused\")\n private static final String LOG_TAG = \"AnchorableImageView\";\n\n private int mAnchorGravity;\n\n private float mAnchorPoint;\n\n private boolean mAnchored;\n\n private int mLeft;\n\n private int mTop;\n\n private int mRight;\n\n private int mBottom;\n\n public AnchorableImageView(Context context) {\n super(context);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public AnchorableImageView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n /**\n * **************************************************\n *\n * Sets the drawable.\n *\n * ***************************************************\n */\n @Override\n public void setImageDrawable(Drawable drawable) {\n super.setImageDrawable(drawable);\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n }\n\n /**\n * ******", "post_mask_code": "********************************************\n *\n * Called when the size changes.\n *\n * ***************************************************\n */\n @Override\n public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {\n super.onSizeChanged(width, height, oldWidth, oldHeight);\n if (mAnchored)\n calculateDrawableBounds(width, height);\n }\n\n /**\n * **************************************************\n *\n * Draws the image view.\n *\n * ***************************************************\n */\n @Override\n public void onDraw(Canvas canvas) {\n if (mAnchored) {\n // Get the image\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n // Draw the image onto the canvas\n drawable.setBounds(mLeft, mTop, mRight, mBottom);\n drawable.draw(canvas);\n } else {\n super.onDraw(canvas);\n }\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor gravity.\n *\n * ***************************************************\n */\n public void setAnchorGravity(int gravity) {\n mAnchorGravity = gravity;\n if (gravity == Gravity.LEFT || gravity == Gravity.TOP || gravity == Gravity.RIGHT || gravity == Gravity.BOTTOM) {\n mAnchored = true;\n calculateDrawableBounds(getWidth(), getHeight());\n } else {\n mAnchored = false;\n }\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Sets the anchor point. This is the point on the image\n * (as a proportion of the image size) that is fixed to\n * the anchor position (defined by the gravity).\n *\n * Has no effect if the anchor gravity is not set.\n *\n * ***************************************************\n */\n public void setAnchorPoint(float point) {\n mAnchorPoint = point;\n if (mAnchored)\n calculateDrawableBounds(getWidth(), getHeight());\n invalidate();\n }\n\n /**\n * **************************************************\n *\n * Calculates the drawable bounds.\n *\n * TODO: Factor in the anchor point\n *\n * ***************************************************\n */\n private void calculateDrawableBounds(int viewWidth, int viewHeight) {\n // Make sure we have all the details we need\n if (viewWidth < 1 || viewHeight < 1)\n return;\n Drawable drawable = getDrawable();\n if (drawable == null)\n return;\n int drawableWidth = drawable.getIntrinsicWidth();\n int drawableHeight = drawable.getIntrinsicHeight();\n if (drawableWidth < 1 || drawableHeight < 1)\n return;\n int viewHalfWidth = (int) (viewWidth * 0.5f);\n int viewHalfHeight = (int) (viewHeight * 0.5f);\n // Since we are being anchored, we have the option of filling the entire view, or\n // fitting inside it. Work out which from the scale type.\n ScaleType scaleType = getScaleType();\n boolean fillView = (scaleType == ScaleType.CENTER_CROP || scaleType == ScaleType.CENTER.FIT_END || scaleType == ScaleType.FIT_XY);\n // Calculate the scale factor according to whether we're filling the view or not\n float widthScaleFactor = (float) viewWidth / (float) drawableWidth;\n float heightScaleFactor = (float) viewHeight / (float) drawableHeight;\n float scaleFactor;\n if (fillView) {\n scaleFactor = Math.max(widthScaleFactor, heightScaleFactor);\n } else {\n scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);\n }\n int scaledDrawableWidth = (int) (drawableWidth * scaleFactor);\n int scaledDrawableHeight = (int) (drawableHeight * scaleFactor);\n int scaledDrawableHalfWidth = (int) (scaledDrawableWidth * 0.5f);\n int scaledDrawableHalfHeight = (int) (scaledDrawableHeight * 0.5f);\n // Once we've determined what the anchor gravity is, calculate the bounds\n // of the image to match.\n if (mAnchorGravity == Gravity.LEFT) {\n mLeft = 0;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = scaledDrawableWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.TOP) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = 0;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = scaledDrawableHeight;\n } else if (mAnchorGravity == Gravity.RIGHT) {\n mLeft = viewWidth - scaledDrawableWidth;\n mTop = viewHalfHeight - scaledDrawableHalfHeight;\n mRight = viewWidth;\n mBottom = viewHalfHeight + scaledDrawableHalfHeight;\n } else if (mAnchorGravity == Gravity.BOTTOM) {\n mLeft = viewHalfWidth - scaledDrawableHalfWidth;\n mTop = viewHeight - scaledDrawableHeight;\n mRight = viewHalfWidth + scaledDrawableHalfWidth;\n mBottom = viewHeight;\n }\n }\n}\n"} {"task_id": "Java_787", "language": "Java", "task_type": "method_signature", "source_file": "java/github/sdaschner/jaxrs-analyzer/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java", "mask_start_position": 1625, "mask_end_position": 1751, "canonical_solution": "public static A getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass) ", "pre_mask_code": "package com.sebastian_daschner.jaxrs_analyzer.model;\n\nimport com.sebastian_daschner.jaxrs_analyzer.LogProvider;\nimport com.sebastian_daschner.jaxrs_analyzer.analysis.classes.ContextClassReader;\nimport org.objectweb.asm.Type;\nimport org.objectweb.asm.signature.SignatureReader;\nimport org.objectweb.asm.util.TraceSignatureVisitor;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.TypeVariable;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static com.sebastian_daschner.jaxrs_analyzer.model.Types.*;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\n\n/**\n * Contains Java reflection utility functionality.\n *\n * @author Sebastian Daschner\n */\npublic final class JavaUtils {\n\n public static final String INITIALIZER_NAME = \"\";\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Checks if the given method name is a Java initializer.\n *\n * @param name The method name\n * @return {@code true} if name is an initializer\n */\n public static boolean isInitializerName(final String name) {\n return INITIALIZER_NAME.equals(name);\n }\n\n /**\n * Returns the annotation or {@code null} if the element is not annotated with that type.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n ", "post_mask_code": "{\n final Optional annotation = Stream.of(annotatedElement.getAnnotations()).filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();\n return (A) annotation.orElse(null);\n }\n\n /**\n * Checks if the annotation is present on the annotated element.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class annotationClass) {\n return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName()));\n }\n\n /**\n * Determines the type which is most \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the first type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n */\n public static String determineMostSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineMostSpecific(types[0], types[1]);\n default:\n String currentMostSpecific = determineMostSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentMostSpecific = determineMostSpecific(currentMostSpecific, types[i]);\n }\n return currentMostSpecific;\n }\n }\n\n private static String determineMostSpecific(final String firstType, final String secondType) {\n if (OBJECT.equals(secondType) || firstType.equals(secondType)) {\n return firstType;\n }\n if (OBJECT.equals(firstType))\n return secondType;\n final List firstTypeParameters = getTypeParameters(firstType);\n final List secondTypeParameters = getTypeParameters(secondType);\n final boolean firstTypeParameterized = !firstTypeParameters.isEmpty();\n final boolean secondTypeParameterized = !secondTypeParameters.isEmpty();\n if (firstTypeParameterized || secondTypeParameterized) {\n if (firstTypeParameterized && !secondTypeParameterized) {\n return firstType;\n }\n if (!firstTypeParameterized) {\n return secondType;\n }\n if (firstTypeParameters.size() != secondTypeParameters.size())\n // types parameters are not compatible, no statement can be made\n return firstType;\n for (int i = 0; i < firstTypeParameters.size(); i++) {\n final String firstInner = firstTypeParameters.get(i);\n final String secondInner = secondTypeParameters.get(i);\n if (firstInner.equals(secondInner))\n continue;\n // desired to test against identity, i.e. which object was taken by comparison\n if (firstInner == determineMostSpecific(firstInner, secondInner))\n return firstType;\n return secondType;\n }\n }\n final boolean firstTypeArray = firstType.charAt(0) == '[';\n final boolean secondTypeArray = secondType.charAt(0) == '[';\n if (firstTypeArray || secondTypeArray) {\n if (firstTypeArray && !secondTypeArray) {\n return firstType;\n }\n if (!firstTypeArray) {\n return secondType;\n }\n }\n // check if one type is inherited from other\n if (isAssignableTo(firstType, secondType))\n return firstType;\n if (isAssignableTo(secondType, firstType))\n return secondType;\n return firstType;\n }\n\n /**\n * Determines the type which is least \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the second type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n * @see #determineMostSpecificType(String...)\n */\n public static String determineLeastSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineLeastSpecific(types[0], types[1]);\n default:\n String currentLeastSpecific = determineLeastSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentLeastSpecific = determineLeastSpecific(currentLeastSpecific, types[i]);\n }\n return currentLeastSpecific;\n }\n }\n\n private static String determineLeastSpecific(final String firstType, final String secondType) {\n final String mostSpecificType = determineMostSpecificType(firstType, secondType);\n // has to compare identity to see which String object was taken\n if (mostSpecificType == firstType)\n return secondType;\n return firstType;\n }\n\n /**\n * Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type.\n */\n public static boolean isAssignableTo(final String leftType, final String rightType) {\n if (leftType.equals(rightType))\n return true;\n final boolean firstTypeArray = leftType.charAt(0) == '[';\n if (firstTypeArray ^ rightType.charAt(0) == '[') {\n return false;\n }\n final Class leftClass = loadClassFromType(leftType);\n final Class rightClass = loadClassFromType(rightType);\n if (leftClass == null || rightClass == null)\n return false;\n final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);\n return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));\n }\n\n private static boolean hasTypeParameters(final String type) {\n return type.indexOf('<') >= 0;\n }\n\n /**\n * Converts the given JVM object type signature to a class name. Erasures parametrized types.\n *

\n * Example: {@code Ljava/util/List; -> java/util/List}\n *\n * @throws IllegalArgumentException If the type is not a reference or array type.\n */\n public static String toClassName(final String type) {\n switch(type.charAt(0)) {\n case 'V':\n return CLASS_PRIMITIVE_VOID;\n case 'Z':\n return CLASS_PRIMITIVE_BOOLEAN;\n case 'C':\n return CLASS_PRIMITIVE_CHAR;\n case 'B':\n return CLASS_PRIMITIVE_BYTE;\n case 'S':\n return CLASS_PRIMITIVE_SHORT;\n case 'I':\n return CLASS_PRIMITIVE_INT;\n case 'F':\n return CLASS_PRIMITIVE_FLOAT;\n case 'J':\n return CLASS_PRIMITIVE_LONG;\n case 'D':\n return CLASS_PRIMITIVE_DOUBLE;\n case 'L':\n final int typeParamStart = type.indexOf('<');\n final int endIndex = typeParamStart >= 0 ? typeParamStart : type.indexOf(';');\n return type.substring(1, endIndex);\n case '[':\n case '+':\n case '-':\n return toClassName(type.substring(1));\n case 'T':\n // TODO handle type variables\n return CLASS_OBJECT;\n default:\n throw new IllegalArgumentException(\"Not a type signature: \" + type);\n }\n }\n\n /**\n * Converts the given JVM class name to a type signature.\n *

\n * Example: {@code java/util/List -> Ljava/util/List;}\n */\n public static String toType(final String className) {\n return 'L' + className + ';';\n }\n\n /**\n * Converts the given type signature to a human readable type string.\n *

\n * Example: {@code Ljava/util/Map; -> java.util.Map}\n */\n public static String toReadableType(final String type) {\n final SignatureReader reader = new SignatureReader(type);\n final TraceSignatureVisitor visitor = new TraceSignatureVisitor(0);\n reader.acceptType(visitor);\n return visitor.getDeclaration();\n }\n\n /**\n * Returns the JVM type signature of the given object.\n */\n public static String getType(final Object value) {\n return Type.getDescriptor(value.getClass());\n }\n\n /**\n * Returns the type parameters of the given type. Will be an empty list if the type is not parametrized.\n */\n public static List getTypeParameters(final String type) {\n if (type.charAt(0) != 'L')\n return emptyList();\n int lastStart = type.indexOf('<') + 1;\n final List parameters = new ArrayList<>();\n if (lastStart > 0) {\n int depth = 0;\n for (int i = lastStart; i < type.length() - 2; i++) {\n final char c = type.charAt(i);\n if (c == '<')\n depth++;\n else if (c == '>')\n depth--;\n else if (c == ';' && depth == 0) {\n parameters.add(type.substring(lastStart, i + 1));\n lastStart = i + 1;\n }\n }\n }\n return parameters;\n }\n\n /**\n * Returns the return type of the given method signature. Parametrized types are supported.\n */\n public static String getReturnType(final String methodSignature) {\n return getReturnType(methodSignature, null);\n }\n\n public static String getReturnType(final String methodSignature, final String containedType) {\n final String type = methodSignature.substring(methodSignature.lastIndexOf(')') + 1);\n return resolvePotentialTypeVariables(type, containedType);\n }\n\n private static Map getTypeVariables(final String type) {\n if (type == null)\n return emptyMap();\n final Map variables = new HashMap<>();\n final List actualTypeParameters = getTypeParameters(type);\n final Class loadedClass = loadClassFromType(type);\n if (loadedClass == null) {\n LogProvider.debug(\"could not load class for type \" + type);\n return emptyMap();\n }\n final TypeVariable>[] typeParameters = loadedClass.getTypeParameters();\n for (int i = 0; i < actualTypeParameters.size(); i++) {\n variables.put(typeParameters[i].getName(), actualTypeParameters.get(i));\n }\n return variables;\n }\n\n public static Class loadClassFromName(final String className) {\n switch(className) {\n case CLASS_PRIMITIVE_VOID:\n return int.class;\n case CLASS_PRIMITIVE_BOOLEAN:\n return boolean.class;\n case CLASS_PRIMITIVE_CHAR:\n return char.class;\n case CLASS_PRIMITIVE_BYTE:\n return byte.class;\n case CLASS_PRIMITIVE_SHORT:\n return short.class;\n case CLASS_PRIMITIVE_INT:\n return int.class;\n case CLASS_PRIMITIVE_FLOAT:\n return float.class;\n case CLASS_PRIMITIVE_LONG:\n return long.class;\n case CLASS_PRIMITIVE_DOUBLE:\n return double.class;\n }\n // TODO test for variable types\n try {\n return ContextClassReader.getClassLoader().loadClass(className.replace('/', '.'));\n } catch (ClassNotFoundException e) {\n LogProvider.error(\"Could not load class \" + className);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static Class loadClassFromType(final String type) {\n return loadClassFromName(toClassName(type));\n }\n\n public static Method findMethod(final String className, final String methodName, final String signature) {\n final Class loadedClass = loadClassFromName(className);\n if (loadedClass == null)\n return null;\n return findMethod(loadedClass, methodName, signature);\n }\n\n public static Method findMethod(final Class loadedClass, final String methodName, final String signature) {\n final List parameters = getParameters(signature);\n return Stream.of(loadedClass.getDeclaredMethods()).filter(m -> m.getName().equals(methodName) && m.getParameterCount() == parameters.size() && // return types are not taken into account (could be overloaded method w/ different return type)\n Objects.equals(getParameters(getMethodSignature(m)), parameters)).findAny().orElse(null);\n }\n\n public static String getMethodSignature(final String returnType, final String... parameterTypes) {\n final String parameters = Stream.of(parameterTypes).collect(Collectors.joining());\n return '(' + parameters + ')' + returnType;\n }\n\n public static String getMethodSignature(final Method method) {\n try {\n final Field signatureField = method.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n final String signature = (String) signatureField.get(method);\n if (signature != null)\n return signature;\n return Type.getMethodDescriptor(method);\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access method \" + method);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static String getFieldDescriptor(final Field field, final String containedType) {\n try {\n final Field signatureField = field.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n String signature = (String) signatureField.get(field);\n if (signature != null) {\n return resolvePotentialTypeVariables(signature, containedType);\n }\n return Type.getDescriptor(field.getType());\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access field \" + field);\n LogProvider.debug(e);\n return null;\n }\n }\n\n private static String resolvePotentialTypeVariables(final String signature, final String containedType) {\n // resolve type variables immediately\n if (signature.charAt(0) == 'T' || signature.contains(\" typeVariables = getTypeVariables(containedType);\n StringBuilder builder = new StringBuilder(signature);\n boolean startType = true;\n for (int i = 0; i < builder.length(); i++) {\n if (startType && builder.charAt(i) == 'T') {\n final int end = builder.indexOf(\";\", i);\n final String identifier = builder.substring(i + 1, end);\n final String resolvedVariableType = typeVariables.getOrDefault(identifier, OBJECT);\n builder.replace(i, end + 1, resolvedVariableType);\n i = end;\n continue;\n }\n startType = builder.charAt(i) == '<' || builder.charAt(i) == ';';\n }\n return builder.toString();\n }\n return signature;\n }\n\n /**\n * Returns the parameter types of the given method signature. Parametrized types are supported.\n */\n public static List getParameters(final String methodDesc) {\n if (methodDesc == null)\n return emptyList();\n final char[] buffer = methodDesc.toCharArray();\n final List args = new ArrayList<>();\n // TODO resolve type parameters correctly -> information useful? -> maybe use ASM's SignatureReader/Visitor\n int offset = methodDesc.indexOf('(') + 1;\n while (buffer[offset] != ')') {\n final String type = getNextType(buffer, offset);\n args.add(type);\n offset += type.length();\n }\n // TODO change, see type parameters\n // prevent type parameter identifiers\n final ListIterator iterator = args.listIterator();\n while (iterator.hasNext()) {\n final String arg = iterator.next();\n if (arg.charAt(0) == 'T')\n iterator.set(OBJECT);\n }\n return args;\n }\n\n /**\n * Resolves the given method signatures to an array of (self-contained) Java type descriptions.\n *\n * @param methodDesc The method description signature (can contain type parameters and generics)\n * @return The types as an array with the method parameter types first and the return type as index {@code array.length - 1}\n */\n private static String[] resolveMethodSignature(final String methodDesc) {\n // if starts with '<' -> resolve type parameters\n return null;\n }\n\n private static Map resolveTypeParameters(final String methodDesc) {\n return null;\n }\n\n private static String getNextType(final char[] buf, final int off) {\n switch(buf[off]) {\n case 'V':\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n case 'F':\n case 'J':\n case 'D':\n return String.valueOf(buf[off]);\n case '[':\n int len = 1;\n while (buf[off + len] == '[') {\n len++;\n }\n return getNextType(buf, off, len);\n case 'L':\n // TODO resolve type variables\n case 'T':\n return getNextType(buf, off, 0);\n default:\n throw new IllegalArgumentException(\"Illegal signature provided: \" + new String(buf));\n }\n }\n\n private static String getNextType(char[] buf, int off, int len) {\n int depth = 0;\n if (buf[off + len] == 'L' || buf[off + len] == 'T')\n while (buf[off + len] != ';' || depth != 0) {\n if (buf[off + len] == '<')\n depth++;\n else if (buf[off + len] == '>')\n depth--;\n len++;\n }\n return new String(buf, off, len + 1);\n }\n}\n"} {"task_id": "Java_788", "language": "Java", "task_type": "method_body", "source_file": "java/github/sdaschner/jaxrs-analyzer/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java", "mask_start_position": 20473, "mask_end_position": 20853, "canonical_solution": "{\n int depth = 0;\n if (buf[off + len] == 'L' || buf[off + len] == 'T')\n while (buf[off + len] != ';' || depth != 0) {\n if (buf[off + len] == '<')\n depth++;\n else if (buf[off + len] == '>')\n depth--;\n len++;\n }\n return new String(buf, off, len + 1);\n }", "pre_mask_code": "package com.sebastian_daschner.jaxrs_analyzer.model;\n\nimport com.sebastian_daschner.jaxrs_analyzer.LogProvider;\nimport com.sebastian_daschner.jaxrs_analyzer.analysis.classes.ContextClassReader;\nimport org.objectweb.asm.Type;\nimport org.objectweb.asm.signature.SignatureReader;\nimport org.objectweb.asm.util.TraceSignatureVisitor;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.TypeVariable;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static com.sebastian_daschner.jaxrs_analyzer.model.Types.*;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\n\n/**\n * Contains Java reflection utility functionality.\n *\n * @author Sebastian Daschner\n */\npublic final class JavaUtils {\n\n public static final String INITIALIZER_NAME = \"\";\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Checks if the given method name is a Java initializer.\n *\n * @param name The method name\n * @return {@code true} if name is an initializer\n */\n public static boolean isInitializerName(final String name) {\n return INITIALIZER_NAME.equals(name);\n }\n\n /**\n * Returns the annotation or {@code null} if the element is not annotated with that type.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static A getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass) {\n final Optional annotation = Stream.of(annotatedElement.getAnnotations()).filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();\n return (A) annotation.orElse(null);\n }\n\n /**\n * Checks if the annotation is present on the annotated element.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class annotationClass) {\n return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName()));\n }\n\n /**\n * Determines the type which is most \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the first type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n */\n public static String determineMostSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineMostSpecific(types[0], types[1]);\n default:\n String currentMostSpecific = determineMostSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentMostSpecific = determineMostSpecific(currentMostSpecific, types[i]);\n }\n return currentMostSpecific;\n }\n }\n\n private static String determineMostSpecific(final String firstType, final String secondType) {\n if (OBJECT.equals(secondType) || firstType.equals(secondType)) {\n return firstType;\n }\n if (OBJECT.equals(firstType))\n return secondType;\n final List firstTypeParameters = getTypeParameters(firstType);\n final List secondTypeParameters = getTypeParameters(secondType);\n final boolean firstTypeParameterized = !firstTypeParameters.isEmpty();\n final boolean secondTypeParameterized = !secondTypeParameters.isEmpty();\n if (firstTypeParameterized || secondTypeParameterized) {\n if (firstTypeParameterized && !secondTypeParameterized) {\n return firstType;\n }\n if (!firstTypeParameterized) {\n return secondType;\n }\n if (firstTypeParameters.size() != secondTypeParameters.size())\n // types parameters are not compatible, no statement can be made\n return firstType;\n for (int i = 0; i < firstTypeParameters.size(); i++) {\n final String firstInner = firstTypeParameters.get(i);\n final String secondInner = secondTypeParameters.get(i);\n if (firstInner.equals(secondInner))\n continue;\n // desired to test against identity, i.e. which object was taken by comparison\n if (firstInner == determineMostSpecific(firstInner, secondInner))\n return firstType;\n return secondType;\n }\n }\n final boolean firstTypeArray = firstType.charAt(0) == '[';\n final boolean secondTypeArray = secondType.charAt(0) == '[';\n if (firstTypeArray || secondTypeArray) {\n if (firstTypeArray && !secondTypeArray) {\n return firstType;\n }\n if (!firstTypeArray) {\n return secondType;\n }\n }\n // check if one type is inherited from other\n if (isAssignableTo(firstType, secondType))\n return firstType;\n if (isAssignableTo(secondType, firstType))\n return secondType;\n return firstType;\n }\n\n /**\n * Determines the type which is least \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the second type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n * @see #determineMostSpecificType(String...)\n */\n public static String determineLeastSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineLeastSpecific(types[0], types[1]);\n default:\n String currentLeastSpecific = determineLeastSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentLeastSpecific = determineLeastSpecific(currentLeastSpecific, types[i]);\n }\n return currentLeastSpecific;\n }\n }\n\n private static String determineLeastSpecific(final String firstType, final String secondType) {\n final String mostSpecificType = determineMostSpecificType(firstType, secondType);\n // has to compare identity to see which String object was taken\n if (mostSpecificType == firstType)\n return secondType;\n return firstType;\n }\n\n /**\n * Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type.\n */\n public static boolean isAssignableTo(final String leftType, final String rightType) {\n if (leftType.equals(rightType))\n return true;\n final boolean firstTypeArray = leftType.charAt(0) == '[';\n if (firstTypeArray ^ rightType.charAt(0) == '[') {\n return false;\n }\n final Class leftClass = loadClassFromType(leftType);\n final Class rightClass = loadClassFromType(rightType);\n if (leftClass == null || rightClass == null)\n return false;\n final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);\n return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));\n }\n\n private static boolean hasTypeParameters(final String type) {\n return type.indexOf('<') >= 0;\n }\n\n /**\n * Converts the given JVM object type signature to a class name. Erasures parametrized types.\n *

\n * Example: {@code Ljava/util/List; -> java/util/List}\n *\n * @throws IllegalArgumentException If the type is not a reference or array type.\n */\n public static String toClassName(final String type) {\n switch(type.charAt(0)) {\n case 'V':\n return CLASS_PRIMITIVE_VOID;\n case 'Z':\n return CLASS_PRIMITIVE_BOOLEAN;\n case 'C':\n return CLASS_PRIMITIVE_CHAR;\n case 'B':\n return CLASS_PRIMITIVE_BYTE;\n case 'S':\n return CLASS_PRIMITIVE_SHORT;\n case 'I':\n return CLASS_PRIMITIVE_INT;\n case 'F':\n return CLASS_PRIMITIVE_FLOAT;\n case 'J':\n return CLASS_PRIMITIVE_LONG;\n case 'D':\n return CLASS_PRIMITIVE_DOUBLE;\n case 'L':\n final int typeParamStart = type.indexOf('<');\n final int endIndex = typeParamStart >= 0 ? typeParamStart : type.indexOf(';');\n return type.substring(1, endIndex);\n case '[':\n case '+':\n case '-':\n return toClassName(type.substring(1));\n case 'T':\n // TODO handle type variables\n return CLASS_OBJECT;\n default:\n throw new IllegalArgumentException(\"Not a type signature: \" + type);\n }\n }\n\n /**\n * Converts the given JVM class name to a type signature.\n *

\n * Example: {@code java/util/List -> Ljava/util/List;}\n */\n public static String toType(final String className) {\n return 'L' + className + ';';\n }\n\n /**\n * Converts the given type signature to a human readable type string.\n *

\n * Example: {@code Ljava/util/Map; -> java.util.Map}\n */\n public static String toReadableType(final String type) {\n final SignatureReader reader = new SignatureReader(type);\n final TraceSignatureVisitor visitor = new TraceSignatureVisitor(0);\n reader.acceptType(visitor);\n return visitor.getDeclaration();\n }\n\n /**\n * Returns the JVM type signature of the given object.\n */\n public static String getType(final Object value) {\n return Type.getDescriptor(value.getClass());\n }\n\n /**\n * Returns the type parameters of the given type. Will be an empty list if the type is not parametrized.\n */\n public static List getTypeParameters(final String type) {\n if (type.charAt(0) != 'L')\n return emptyList();\n int lastStart = type.indexOf('<') + 1;\n final List parameters = new ArrayList<>();\n if (lastStart > 0) {\n int depth = 0;\n for (int i = lastStart; i < type.length() - 2; i++) {\n final char c = type.charAt(i);\n if (c == '<')\n depth++;\n else if (c == '>')\n depth--;\n else if (c == ';' && depth == 0) {\n parameters.add(type.substring(lastStart, i + 1));\n lastStart = i + 1;\n }\n }\n }\n return parameters;\n }\n\n /**\n * Returns the return type of the given method signature. Parametrized types are supported.\n */\n public static String getReturnType(final String methodSignature) {\n return getReturnType(methodSignature, null);\n }\n\n public static String getReturnType(final String methodSignature, final String containedType) {\n final String type = methodSignature.substring(methodSignature.lastIndexOf(')') + 1);\n return resolvePotentialTypeVariables(type, containedType);\n }\n\n private static Map getTypeVariables(final String type) {\n if (type == null)\n return emptyMap();\n final Map variables = new HashMap<>();\n final List actualTypeParameters = getTypeParameters(type);\n final Class loadedClass = loadClassFromType(type);\n if (loadedClass == null) {\n LogProvider.debug(\"could not load class for type \" + type);\n return emptyMap();\n }\n final TypeVariable>[] typeParameters = loadedClass.getTypeParameters();\n for (int i = 0; i < actualTypeParameters.size(); i++) {\n variables.put(typeParameters[i].getName(), actualTypeParameters.get(i));\n }\n return variables;\n }\n\n public static Class loadClassFromName(final String className) {\n switch(className) {\n case CLASS_PRIMITIVE_VOID:\n return int.class;\n case CLASS_PRIMITIVE_BOOLEAN:\n return boolean.class;\n case CLASS_PRIMITIVE_CHAR:\n return char.class;\n case CLASS_PRIMITIVE_BYTE:\n return byte.class;\n case CLASS_PRIMITIVE_SHORT:\n return short.class;\n case CLASS_PRIMITIVE_INT:\n return int.class;\n case CLASS_PRIMITIVE_FLOAT:\n return float.class;\n case CLASS_PRIMITIVE_LONG:\n return long.class;\n case CLASS_PRIMITIVE_DOUBLE:\n return double.class;\n }\n // TODO test for variable types\n try {\n return ContextClassReader.getClassLoader().loadClass(className.replace('/', '.'));\n } catch (ClassNotFoundException e) {\n LogProvider.error(\"Could not load class \" + className);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static Class loadClassFromType(final String type) {\n return loadClassFromName(toClassName(type));\n }\n\n public static Method findMethod(final String className, final String methodName, final String signature) {\n final Class loadedClass = loadClassFromName(className);\n if (loadedClass == null)\n return null;\n return findMethod(loadedClass, methodName, signature);\n }\n\n public static Method findMethod(final Class loadedClass, final String methodName, final String signature) {\n final List parameters = getParameters(signature);\n return Stream.of(loadedClass.getDeclaredMethods()).filter(m -> m.getName().equals(methodName) && m.getParameterCount() == parameters.size() && // return types are not taken into account (could be overloaded method w/ different return type)\n Objects.equals(getParameters(getMethodSignature(m)), parameters)).findAny().orElse(null);\n }\n\n public static String getMethodSignature(final String returnType, final String... parameterTypes) {\n final String parameters = Stream.of(parameterTypes).collect(Collectors.joining());\n return '(' + parameters + ')' + returnType;\n }\n\n public static String getMethodSignature(final Method method) {\n try {\n final Field signatureField = method.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n final String signature = (String) signatureField.get(method);\n if (signature != null)\n return signature;\n return Type.getMethodDescriptor(method);\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access method \" + method);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static String getFieldDescriptor(final Field field, final String containedType) {\n try {\n final Field signatureField = field.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n String signature = (String) signatureField.get(field);\n if (signature != null) {\n return resolvePotentialTypeVariables(signature, containedType);\n }\n return Type.getDescriptor(field.getType());\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access field \" + field);\n LogProvider.debug(e);\n return null;\n }\n }\n\n private static String resolvePotentialTypeVariables(final String signature, final String containedType) {\n // resolve type variables immediately\n if (signature.charAt(0) == 'T' || signature.contains(\" typeVariables = getTypeVariables(containedType);\n StringBuilder builder = new StringBuilder(signature);\n boolean startType = true;\n for (int i = 0; i < builder.length(); i++) {\n if (startType && builder.charAt(i) == 'T') {\n final int end = builder.indexOf(\";\", i);\n final String identifier = builder.substring(i + 1, end);\n final String resolvedVariableType = typeVariables.getOrDefault(identifier, OBJECT);\n builder.replace(i, end + 1, resolvedVariableType);\n i = end;\n continue;\n }\n startType = builder.charAt(i) == '<' || builder.charAt(i) == ';';\n }\n return builder.toString();\n }\n return signature;\n }\n\n /**\n * Returns the parameter types of the given method signature. Parametrized types are supported.\n */\n public static List getParameters(final String methodDesc) {\n if (methodDesc == null)\n return emptyList();\n final char[] buffer = methodDesc.toCharArray();\n final List args = new ArrayList<>();\n // TODO resolve type parameters correctly -> information useful? -> maybe use ASM's SignatureReader/Visitor\n int offset = methodDesc.indexOf('(') + 1;\n while (buffer[offset] != ')') {\n final String type = getNextType(buffer, offset);\n args.add(type);\n offset += type.length();\n }\n // TODO change, see type parameters\n // prevent type parameter identifiers\n final ListIterator iterator = args.listIterator();\n while (iterator.hasNext()) {\n final String arg = iterator.next();\n if (arg.charAt(0) == 'T')\n iterator.set(OBJECT);\n }\n return args;\n }\n\n /**\n * Resolves the given method signatures to an array of (self-contained) Java type descriptions.\n *\n * @param methodDesc The method description signature (can contain type parameters and generics)\n * @return The types as an array with the method parameter types first and the return type as index {@code array.length - 1}\n */\n private static String[] resolveMethodSignature(final String methodDesc) {\n // if starts with '<' -> resolve type parameters\n return null;\n }\n\n private static Map resolveTypeParameters(final String methodDesc) {\n return null;\n }\n\n private static String getNextType(final char[] buf, final int off) {\n switch(buf[off]) {\n case 'V':\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n case 'F':\n case 'J':\n case 'D':\n return String.valueOf(buf[off]);\n case '[':\n int len = 1;\n while (buf[off + len] == '[') {\n len++;\n }\n return getNextType(buf, off, len);\n case 'L':\n // TODO resolve type variables\n case 'T':\n return getNextType(buf, off, 0);\n default:\n throw new IllegalArgumentException(\"Illegal signature provided: \" + new String(buf));\n }\n }\n\n private static String getNextType(char[] buf, int off, int len) ", "post_mask_code": "\n}\n"} {"task_id": "Java_789", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/sdaschner/jaxrs-analyzer/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java", "mask_start_position": 2954, "mask_end_position": 2954, "canonical_solution": "", "pre_mask_code": "package com.sebastian_daschner.jaxrs_analyzer.model;\n\nimport com.sebastian_daschner.jaxrs_analyzer.LogProvider;\nimport com.sebastian_daschner.jaxrs_analyzer.analysis.classes.ContextClassReader;\nimport org.objectweb.asm.Type;\nimport org.objectweb.asm.signature.SignatureReader;\nimport org.objectweb.asm.util.TraceSignatureVisitor;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.TypeVariable;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static com.sebastian_daschner.jaxrs_analyzer.model.Types.*;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\n\n/**\n * Contains Java reflection utility functionality.\n *\n * @author Sebastian Daschner\n */\npublic final class JavaUtils {\n\n public static final String INITIALIZER_NAME = \"\";\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Checks if the given method name is a Java initializer.\n *\n * @param name The method name\n * @return {@code true} if name is an initializer\n */\n public static boolean isInitializerName(final String name) {\n return INITIALIZER_NAME.equals(name);\n }\n\n /**\n * Returns the annotation or {@code null} if the element is not annotated with that type.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static A getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass) {\n final Optional annotation = Stream.of(annotatedElement.getAnnotations()).filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();\n return (A) annotation.orElse(null);\n }\n\n /**\n * Checks if the annotation is present on the annotated element.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class annotationClass) {\n return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName()));\n }\n\n /**\n * Determines the type which is most \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the first type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n */\n public static String determineMostSpecificType(final String... types) {", "post_mask_code": "\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineMostSpecific(types[0], types[1]);\n default:\n String currentMostSpecific = determineMostSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentMostSpecific = determineMostSpecific(currentMostSpecific, types[i]);\n }\n return currentMostSpecific;\n }\n }\n\n private static String determineMostSpecific(final String firstType, final String secondType) {\n if (OBJECT.equals(secondType) || firstType.equals(secondType)) {\n return firstType;\n }\n if (OBJECT.equals(firstType))\n return secondType;\n final List firstTypeParameters = getTypeParameters(firstType);\n final List secondTypeParameters = getTypeParameters(secondType);\n final boolean firstTypeParameterized = !firstTypeParameters.isEmpty();\n final boolean secondTypeParameterized = !secondTypeParameters.isEmpty();\n if (firstTypeParameterized || secondTypeParameterized) {\n if (firstTypeParameterized && !secondTypeParameterized) {\n return firstType;\n }\n if (!firstTypeParameterized) {\n return secondType;\n }\n if (firstTypeParameters.size() != secondTypeParameters.size())\n // types parameters are not compatible, no statement can be made\n return firstType;\n for (int i = 0; i < firstTypeParameters.size(); i++) {\n final String firstInner = firstTypeParameters.get(i);\n final String secondInner = secondTypeParameters.get(i);\n if (firstInner.equals(secondInner))\n continue;\n // desired to test against identity, i.e. which object was taken by comparison\n if (firstInner == determineMostSpecific(firstInner, secondInner))\n return firstType;\n return secondType;\n }\n }\n final boolean firstTypeArray = firstType.charAt(0) == '[';\n final boolean secondTypeArray = secondType.charAt(0) == '[';\n if (firstTypeArray || secondTypeArray) {\n if (firstTypeArray && !secondTypeArray) {\n return firstType;\n }\n if (!firstTypeArray) {\n return secondType;\n }\n }\n // check if one type is inherited from other\n if (isAssignableTo(firstType, secondType))\n return firstType;\n if (isAssignableTo(secondType, firstType))\n return secondType;\n return firstType;\n }\n\n /**\n * Determines the type which is least \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the second type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n * @see #determineMostSpecificType(String...)\n */\n public static String determineLeastSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineLeastSpecific(types[0], types[1]);\n default:\n String currentLeastSpecific = determineLeastSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentLeastSpecific = determineLeastSpecific(currentLeastSpecific, types[i]);\n }\n return currentLeastSpecific;\n }\n }\n\n private static String determineLeastSpecific(final String firstType, final String secondType) {\n final String mostSpecificType = determineMostSpecificType(firstType, secondType);\n // has to compare identity to see which String object was taken\n if (mostSpecificType == firstType)\n return secondType;\n return firstType;\n }\n\n /**\n * Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type.\n */\n public static boolean isAssignableTo(final String leftType, final String rightType) {\n if (leftType.equals(rightType))\n return true;\n final boolean firstTypeArray = leftType.charAt(0) == '[';\n if (firstTypeArray ^ rightType.charAt(0) == '[') {\n return false;\n }\n final Class leftClass = loadClassFromType(leftType);\n final Class rightClass = loadClassFromType(rightType);\n if (leftClass == null || rightClass == null)\n return false;\n final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);\n return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));\n }\n\n private static boolean hasTypeParameters(final String type) {\n return type.indexOf('<') >= 0;\n }\n\n /**\n * Converts the given JVM object type signature to a class name. Erasures parametrized types.\n *

\n * Example: {@code Ljava/util/List; -> java/util/List}\n *\n * @throws IllegalArgumentException If the type is not a reference or array type.\n */\n public static String toClassName(final String type) {\n switch(type.charAt(0)) {\n case 'V':\n return CLASS_PRIMITIVE_VOID;\n case 'Z':\n return CLASS_PRIMITIVE_BOOLEAN;\n case 'C':\n return CLASS_PRIMITIVE_CHAR;\n case 'B':\n return CLASS_PRIMITIVE_BYTE;\n case 'S':\n return CLASS_PRIMITIVE_SHORT;\n case 'I':\n return CLASS_PRIMITIVE_INT;\n case 'F':\n return CLASS_PRIMITIVE_FLOAT;\n case 'J':\n return CLASS_PRIMITIVE_LONG;\n case 'D':\n return CLASS_PRIMITIVE_DOUBLE;\n case 'L':\n final int typeParamStart = type.indexOf('<');\n final int endIndex = typeParamStart >= 0 ? typeParamStart : type.indexOf(';');\n return type.substring(1, endIndex);\n case '[':\n case '+':\n case '-':\n return toClassName(type.substring(1));\n case 'T':\n // TODO handle type variables\n return CLASS_OBJECT;\n default:\n throw new IllegalArgumentException(\"Not a type signature: \" + type);\n }\n }\n\n /**\n * Converts the given JVM class name to a type signature.\n *

\n * Example: {@code java/util/List -> Ljava/util/List;}\n */\n public static String toType(final String className) {\n return 'L' + className + ';';\n }\n\n /**\n * Converts the given type signature to a human readable type string.\n *

\n * Example: {@code Ljava/util/Map; -> java.util.Map}\n */\n public static String toReadableType(final String type) {\n final SignatureReader reader = new SignatureReader(type);\n final TraceSignatureVisitor visitor = new TraceSignatureVisitor(0);\n reader.acceptType(visitor);\n return visitor.getDeclaration();\n }\n\n /**\n * Returns the JVM type signature of the given object.\n */\n public static String getType(final Object value) {\n return Type.getDescriptor(value.getClass());\n }\n\n /**\n * Returns the type parameters of the given type. Will be an empty list if the type is not parametrized.\n */\n public static List getTypeParameters(final String type) {\n if (type.charAt(0) != 'L')\n return emptyList();\n int lastStart = type.indexOf('<') + 1;\n final List parameters = new ArrayList<>();\n if (lastStart > 0) {\n int depth = 0;\n for (int i = lastStart; i < type.length() - 2; i++) {\n final char c = type.charAt(i);\n if (c == '<')\n depth++;\n else if (c == '>')\n depth--;\n else if (c == ';' && depth == 0) {\n parameters.add(type.substring(lastStart, i + 1));\n lastStart = i + 1;\n }\n }\n }\n return parameters;\n }\n\n /**\n * Returns the return type of the given method signature. Parametrized types are supported.\n */\n public static String getReturnType(final String methodSignature) {\n return getReturnType(methodSignature, null);\n }\n\n public static String getReturnType(final String methodSignature, final String containedType) {\n final String type = methodSignature.substring(methodSignature.lastIndexOf(')') + 1);\n return resolvePotentialTypeVariables(type, containedType);\n }\n\n private static Map getTypeVariables(final String type) {\n if (type == null)\n return emptyMap();\n final Map variables = new HashMap<>();\n final List actualTypeParameters = getTypeParameters(type);\n final Class loadedClass = loadClassFromType(type);\n if (loadedClass == null) {\n LogProvider.debug(\"could not load class for type \" + type);\n return emptyMap();\n }\n final TypeVariable>[] typeParameters = loadedClass.getTypeParameters();\n for (int i = 0; i < actualTypeParameters.size(); i++) {\n variables.put(typeParameters[i].getName(), actualTypeParameters.get(i));\n }\n return variables;\n }\n\n public static Class loadClassFromName(final String className) {\n switch(className) {\n case CLASS_PRIMITIVE_VOID:\n return int.class;\n case CLASS_PRIMITIVE_BOOLEAN:\n return boolean.class;\n case CLASS_PRIMITIVE_CHAR:\n return char.class;\n case CLASS_PRIMITIVE_BYTE:\n return byte.class;\n case CLASS_PRIMITIVE_SHORT:\n return short.class;\n case CLASS_PRIMITIVE_INT:\n return int.class;\n case CLASS_PRIMITIVE_FLOAT:\n return float.class;\n case CLASS_PRIMITIVE_LONG:\n return long.class;\n case CLASS_PRIMITIVE_DOUBLE:\n return double.class;\n }\n // TODO test for variable types\n try {\n return ContextClassReader.getClassLoader().loadClass(className.replace('/', '.'));\n } catch (ClassNotFoundException e) {\n LogProvider.error(\"Could not load class \" + className);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static Class loadClassFromType(final String type) {\n return loadClassFromName(toClassName(type));\n }\n\n public static Method findMethod(final String className, final String methodName, final String signature) {\n final Class loadedClass = loadClassFromName(className);\n if (loadedClass == null)\n return null;\n return findMethod(loadedClass, methodName, signature);\n }\n\n public static Method findMethod(final Class loadedClass, final String methodName, final String signature) {\n final List parameters = getParameters(signature);\n return Stream.of(loadedClass.getDeclaredMethods()).filter(m -> m.getName().equals(methodName) && m.getParameterCount() == parameters.size() && // return types are not taken into account (could be overloaded method w/ different return type)\n Objects.equals(getParameters(getMethodSignature(m)), parameters)).findAny().orElse(null);\n }\n\n public static String getMethodSignature(final String returnType, final String... parameterTypes) {\n final String parameters = Stream.of(parameterTypes).collect(Collectors.joining());\n return '(' + parameters + ')' + returnType;\n }\n\n public static String getMethodSignature(final Method method) {\n try {\n final Field signatureField = method.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n final String signature = (String) signatureField.get(method);\n if (signature != null)\n return signature;\n return Type.getMethodDescriptor(method);\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access method \" + method);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static String getFieldDescriptor(final Field field, final String containedType) {\n try {\n final Field signatureField = field.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n String signature = (String) signatureField.get(field);\n if (signature != null) {\n return resolvePotentialTypeVariables(signature, containedType);\n }\n return Type.getDescriptor(field.getType());\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access field \" + field);\n LogProvider.debug(e);\n return null;\n }\n }\n\n private static String resolvePotentialTypeVariables(final String signature, final String containedType) {\n // resolve type variables immediately\n if (signature.charAt(0) == 'T' || signature.contains(\" typeVariables = getTypeVariables(containedType);\n StringBuilder builder = new StringBuilder(signature);\n boolean startType = true;\n for (int i = 0; i < builder.length(); i++) {\n if (startType && builder.charAt(i) == 'T') {\n final int end = builder.indexOf(\";\", i);\n final String identifier = builder.substring(i + 1, end);\n final String resolvedVariableType = typeVariables.getOrDefault(identifier, OBJECT);\n builder.replace(i, end + 1, resolvedVariableType);\n i = end;\n continue;\n }\n startType = builder.charAt(i) == '<' || builder.charAt(i) == ';';\n }\n return builder.toString();\n }\n return signature;\n }\n\n /**\n * Returns the parameter types of the given method signature. Parametrized types are supported.\n */\n public static List getParameters(final String methodDesc) {\n if (methodDesc == null)\n return emptyList();\n final char[] buffer = methodDesc.toCharArray();\n final List args = new ArrayList<>();\n // TODO resolve type parameters correctly -> information useful? -> maybe use ASM's SignatureReader/Visitor\n int offset = methodDesc.indexOf('(') + 1;\n while (buffer[offset] != ')') {\n final String type = getNextType(buffer, offset);\n args.add(type);\n offset += type.length();\n }\n // TODO change, see type parameters\n // prevent type parameter identifiers\n final ListIterator iterator = args.listIterator();\n while (iterator.hasNext()) {\n final String arg = iterator.next();\n if (arg.charAt(0) == 'T')\n iterator.set(OBJECT);\n }\n return args;\n }\n\n /**\n * Resolves the given method signatures to an array of (self-contained) Java type descriptions.\n *\n * @param methodDesc The method description signature (can contain type parameters and generics)\n * @return The types as an array with the method parameter types first and the return type as index {@code array.length - 1}\n */\n private static String[] resolveMethodSignature(final String methodDesc) {\n // if starts with '<' -> resolve type parameters\n return null;\n }\n\n private static Map resolveTypeParameters(final String methodDesc) {\n return null;\n }\n\n private static String getNextType(final char[] buf, final int off) {\n switch(buf[off]) {\n case 'V':\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n case 'F':\n case 'J':\n case 'D':\n return String.valueOf(buf[off]);\n case '[':\n int len = 1;\n while (buf[off + len] == '[') {\n len++;\n }\n return getNextType(buf, off, len);\n case 'L':\n // TODO resolve type variables\n case 'T':\n return getNextType(buf, off, 0);\n default:\n throw new IllegalArgumentException(\"Illegal signature provided: \" + new String(buf));\n }\n }\n\n private static String getNextType(char[] buf, int off, int len) {\n int depth = 0;\n if (buf[off + len] == 'L' || buf[off + len] == 'T')\n while (buf[off + len] != ';' || depth != 0) {\n if (buf[off + len] == '<')\n depth++;\n else if (buf[off + len] == '>')\n depth--;\n len++;\n }\n return new String(buf, off, len + 1);\n }\n}\n"} {"task_id": "Java_790", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/sdaschner/jaxrs-analyzer/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java", "mask_start_position": 2963, "mask_end_position": 3570, "canonical_solution": "switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineMostSpecific(types[0], types[1]);\n default:\n String currentMostSpecific = determineMostSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentMostSpecific = determineMostSpecific(currentMostSpecific, types[i]);\n }\n return currentMostSpecific;\n }", "pre_mask_code": "package com.sebastian_daschner.jaxrs_analyzer.model;\n\nimport com.sebastian_daschner.jaxrs_analyzer.LogProvider;\nimport com.sebastian_daschner.jaxrs_analyzer.analysis.classes.ContextClassReader;\nimport org.objectweb.asm.Type;\nimport org.objectweb.asm.signature.SignatureReader;\nimport org.objectweb.asm.util.TraceSignatureVisitor;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.TypeVariable;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static com.sebastian_daschner.jaxrs_analyzer.model.Types.*;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\n\n/**\n * Contains Java reflection utility functionality.\n *\n * @author Sebastian Daschner\n */\npublic final class JavaUtils {\n\n public static final String INITIALIZER_NAME = \"\";\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Checks if the given method name is a Java initializer.\n *\n * @param name The method name\n * @return {@code true} if name is an initializer\n */\n public static boolean isInitializerName(final String name) {\n return INITIALIZER_NAME.equals(name);\n }\n\n /**\n * Returns the annotation or {@code null} if the element is not annotated with that type.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static A getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass) {\n final Optional annotation = Stream.of(annotatedElement.getAnnotations()).filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();\n return (A) annotation.orElse(null);\n }\n\n /**\n * Checks if the annotation is present on the annotated element.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class annotationClass) {\n return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName()));\n }\n\n /**\n * Determines the type which is most \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the first type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n */\n public static String determineMostSpecificType(final String... types) {\n ", "post_mask_code": "\n }\n\n private static String determineMostSpecific(final String firstType, final String secondType) {\n if (OBJECT.equals(secondType) || firstType.equals(secondType)) {\n return firstType;\n }\n if (OBJECT.equals(firstType))\n return secondType;\n final List firstTypeParameters = getTypeParameters(firstType);\n final List secondTypeParameters = getTypeParameters(secondType);\n final boolean firstTypeParameterized = !firstTypeParameters.isEmpty();\n final boolean secondTypeParameterized = !secondTypeParameters.isEmpty();\n if (firstTypeParameterized || secondTypeParameterized) {\n if (firstTypeParameterized && !secondTypeParameterized) {\n return firstType;\n }\n if (!firstTypeParameterized) {\n return secondType;\n }\n if (firstTypeParameters.size() != secondTypeParameters.size())\n // types parameters are not compatible, no statement can be made\n return firstType;\n for (int i = 0; i < firstTypeParameters.size(); i++) {\n final String firstInner = firstTypeParameters.get(i);\n final String secondInner = secondTypeParameters.get(i);\n if (firstInner.equals(secondInner))\n continue;\n // desired to test against identity, i.e. which object was taken by comparison\n if (firstInner == determineMostSpecific(firstInner, secondInner))\n return firstType;\n return secondType;\n }\n }\n final boolean firstTypeArray = firstType.charAt(0) == '[';\n final boolean secondTypeArray = secondType.charAt(0) == '[';\n if (firstTypeArray || secondTypeArray) {\n if (firstTypeArray && !secondTypeArray) {\n return firstType;\n }\n if (!firstTypeArray) {\n return secondType;\n }\n }\n // check if one type is inherited from other\n if (isAssignableTo(firstType, secondType))\n return firstType;\n if (isAssignableTo(secondType, firstType))\n return secondType;\n return firstType;\n }\n\n /**\n * Determines the type which is least \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the second type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n * @see #determineMostSpecificType(String...)\n */\n public static String determineLeastSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineLeastSpecific(types[0], types[1]);\n default:\n String currentLeastSpecific = determineLeastSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentLeastSpecific = determineLeastSpecific(currentLeastSpecific, types[i]);\n }\n return currentLeastSpecific;\n }\n }\n\n private static String determineLeastSpecific(final String firstType, final String secondType) {\n final String mostSpecificType = determineMostSpecificType(firstType, secondType);\n // has to compare identity to see which String object was taken\n if (mostSpecificType == firstType)\n return secondType;\n return firstType;\n }\n\n /**\n * Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type.\n */\n public static boolean isAssignableTo(final String leftType, final String rightType) {\n if (leftType.equals(rightType))\n return true;\n final boolean firstTypeArray = leftType.charAt(0) == '[';\n if (firstTypeArray ^ rightType.charAt(0) == '[') {\n return false;\n }\n final Class leftClass = loadClassFromType(leftType);\n final Class rightClass = loadClassFromType(rightType);\n if (leftClass == null || rightClass == null)\n return false;\n final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);\n return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));\n }\n\n private static boolean hasTypeParameters(final String type) {\n return type.indexOf('<') >= 0;\n }\n\n /**\n * Converts the given JVM object type signature to a class name. Erasures parametrized types.\n *

\n * Example: {@code Ljava/util/List; -> java/util/List}\n *\n * @throws IllegalArgumentException If the type is not a reference or array type.\n */\n public static String toClassName(final String type) {\n switch(type.charAt(0)) {\n case 'V':\n return CLASS_PRIMITIVE_VOID;\n case 'Z':\n return CLASS_PRIMITIVE_BOOLEAN;\n case 'C':\n return CLASS_PRIMITIVE_CHAR;\n case 'B':\n return CLASS_PRIMITIVE_BYTE;\n case 'S':\n return CLASS_PRIMITIVE_SHORT;\n case 'I':\n return CLASS_PRIMITIVE_INT;\n case 'F':\n return CLASS_PRIMITIVE_FLOAT;\n case 'J':\n return CLASS_PRIMITIVE_LONG;\n case 'D':\n return CLASS_PRIMITIVE_DOUBLE;\n case 'L':\n final int typeParamStart = type.indexOf('<');\n final int endIndex = typeParamStart >= 0 ? typeParamStart : type.indexOf(';');\n return type.substring(1, endIndex);\n case '[':\n case '+':\n case '-':\n return toClassName(type.substring(1));\n case 'T':\n // TODO handle type variables\n return CLASS_OBJECT;\n default:\n throw new IllegalArgumentException(\"Not a type signature: \" + type);\n }\n }\n\n /**\n * Converts the given JVM class name to a type signature.\n *

\n * Example: {@code java/util/List -> Ljava/util/List;}\n */\n public static String toType(final String className) {\n return 'L' + className + ';';\n }\n\n /**\n * Converts the given type signature to a human readable type string.\n *

\n * Example: {@code Ljava/util/Map; -> java.util.Map}\n */\n public static String toReadableType(final String type) {\n final SignatureReader reader = new SignatureReader(type);\n final TraceSignatureVisitor visitor = new TraceSignatureVisitor(0);\n reader.acceptType(visitor);\n return visitor.getDeclaration();\n }\n\n /**\n * Returns the JVM type signature of the given object.\n */\n public static String getType(final Object value) {\n return Type.getDescriptor(value.getClass());\n }\n\n /**\n * Returns the type parameters of the given type. Will be an empty list if the type is not parametrized.\n */\n public static List getTypeParameters(final String type) {\n if (type.charAt(0) != 'L')\n return emptyList();\n int lastStart = type.indexOf('<') + 1;\n final List parameters = new ArrayList<>();\n if (lastStart > 0) {\n int depth = 0;\n for (int i = lastStart; i < type.length() - 2; i++) {\n final char c = type.charAt(i);\n if (c == '<')\n depth++;\n else if (c == '>')\n depth--;\n else if (c == ';' && depth == 0) {\n parameters.add(type.substring(lastStart, i + 1));\n lastStart = i + 1;\n }\n }\n }\n return parameters;\n }\n\n /**\n * Returns the return type of the given method signature. Parametrized types are supported.\n */\n public static String getReturnType(final String methodSignature) {\n return getReturnType(methodSignature, null);\n }\n\n public static String getReturnType(final String methodSignature, final String containedType) {\n final String type = methodSignature.substring(methodSignature.lastIndexOf(')') + 1);\n return resolvePotentialTypeVariables(type, containedType);\n }\n\n private static Map getTypeVariables(final String type) {\n if (type == null)\n return emptyMap();\n final Map variables = new HashMap<>();\n final List actualTypeParameters = getTypeParameters(type);\n final Class loadedClass = loadClassFromType(type);\n if (loadedClass == null) {\n LogProvider.debug(\"could not load class for type \" + type);\n return emptyMap();\n }\n final TypeVariable>[] typeParameters = loadedClass.getTypeParameters();\n for (int i = 0; i < actualTypeParameters.size(); i++) {\n variables.put(typeParameters[i].getName(), actualTypeParameters.get(i));\n }\n return variables;\n }\n\n public static Class loadClassFromName(final String className) {\n switch(className) {\n case CLASS_PRIMITIVE_VOID:\n return int.class;\n case CLASS_PRIMITIVE_BOOLEAN:\n return boolean.class;\n case CLASS_PRIMITIVE_CHAR:\n return char.class;\n case CLASS_PRIMITIVE_BYTE:\n return byte.class;\n case CLASS_PRIMITIVE_SHORT:\n return short.class;\n case CLASS_PRIMITIVE_INT:\n return int.class;\n case CLASS_PRIMITIVE_FLOAT:\n return float.class;\n case CLASS_PRIMITIVE_LONG:\n return long.class;\n case CLASS_PRIMITIVE_DOUBLE:\n return double.class;\n }\n // TODO test for variable types\n try {\n return ContextClassReader.getClassLoader().loadClass(className.replace('/', '.'));\n } catch (ClassNotFoundException e) {\n LogProvider.error(\"Could not load class \" + className);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static Class loadClassFromType(final String type) {\n return loadClassFromName(toClassName(type));\n }\n\n public static Method findMethod(final String className, final String methodName, final String signature) {\n final Class loadedClass = loadClassFromName(className);\n if (loadedClass == null)\n return null;\n return findMethod(loadedClass, methodName, signature);\n }\n\n public static Method findMethod(final Class loadedClass, final String methodName, final String signature) {\n final List parameters = getParameters(signature);\n return Stream.of(loadedClass.getDeclaredMethods()).filter(m -> m.getName().equals(methodName) && m.getParameterCount() == parameters.size() && // return types are not taken into account (could be overloaded method w/ different return type)\n Objects.equals(getParameters(getMethodSignature(m)), parameters)).findAny().orElse(null);\n }\n\n public static String getMethodSignature(final String returnType, final String... parameterTypes) {\n final String parameters = Stream.of(parameterTypes).collect(Collectors.joining());\n return '(' + parameters + ')' + returnType;\n }\n\n public static String getMethodSignature(final Method method) {\n try {\n final Field signatureField = method.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n final String signature = (String) signatureField.get(method);\n if (signature != null)\n return signature;\n return Type.getMethodDescriptor(method);\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access method \" + method);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static String getFieldDescriptor(final Field field, final String containedType) {\n try {\n final Field signatureField = field.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n String signature = (String) signatureField.get(field);\n if (signature != null) {\n return resolvePotentialTypeVariables(signature, containedType);\n }\n return Type.getDescriptor(field.getType());\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access field \" + field);\n LogProvider.debug(e);\n return null;\n }\n }\n\n private static String resolvePotentialTypeVariables(final String signature, final String containedType) {\n // resolve type variables immediately\n if (signature.charAt(0) == 'T' || signature.contains(\" typeVariables = getTypeVariables(containedType);\n StringBuilder builder = new StringBuilder(signature);\n boolean startType = true;\n for (int i = 0; i < builder.length(); i++) {\n if (startType && builder.charAt(i) == 'T') {\n final int end = builder.indexOf(\";\", i);\n final String identifier = builder.substring(i + 1, end);\n final String resolvedVariableType = typeVariables.getOrDefault(identifier, OBJECT);\n builder.replace(i, end + 1, resolvedVariableType);\n i = end;\n continue;\n }\n startType = builder.charAt(i) == '<' || builder.charAt(i) == ';';\n }\n return builder.toString();\n }\n return signature;\n }\n\n /**\n * Returns the parameter types of the given method signature. Parametrized types are supported.\n */\n public static List getParameters(final String methodDesc) {\n if (methodDesc == null)\n return emptyList();\n final char[] buffer = methodDesc.toCharArray();\n final List args = new ArrayList<>();\n // TODO resolve type parameters correctly -> information useful? -> maybe use ASM's SignatureReader/Visitor\n int offset = methodDesc.indexOf('(') + 1;\n while (buffer[offset] != ')') {\n final String type = getNextType(buffer, offset);\n args.add(type);\n offset += type.length();\n }\n // TODO change, see type parameters\n // prevent type parameter identifiers\n final ListIterator iterator = args.listIterator();\n while (iterator.hasNext()) {\n final String arg = iterator.next();\n if (arg.charAt(0) == 'T')\n iterator.set(OBJECT);\n }\n return args;\n }\n\n /**\n * Resolves the given method signatures to an array of (self-contained) Java type descriptions.\n *\n * @param methodDesc The method description signature (can contain type parameters and generics)\n * @return The types as an array with the method parameter types first and the return type as index {@code array.length - 1}\n */\n private static String[] resolveMethodSignature(final String methodDesc) {\n // if starts with '<' -> resolve type parameters\n return null;\n }\n\n private static Map resolveTypeParameters(final String methodDesc) {\n return null;\n }\n\n private static String getNextType(final char[] buf, final int off) {\n switch(buf[off]) {\n case 'V':\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n case 'F':\n case 'J':\n case 'D':\n return String.valueOf(buf[off]);\n case '[':\n int len = 1;\n while (buf[off + len] == '[') {\n len++;\n }\n return getNextType(buf, off, len);\n case 'L':\n // TODO resolve type variables\n case 'T':\n return getNextType(buf, off, 0);\n default:\n throw new IllegalArgumentException(\"Illegal signature provided: \" + new String(buf));\n }\n }\n\n private static String getNextType(char[] buf, int off, int len) {\n int depth = 0;\n if (buf[off + len] == 'L' || buf[off + len] == 'T')\n while (buf[off + len] != ';' || depth != 0) {\n if (buf[off + len] == '<')\n depth++;\n else if (buf[off + len] == '>')\n depth--;\n len++;\n }\n return new String(buf, off, len + 1);\n }\n}\n"} {"task_id": "Java_791", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/sdaschner/jaxrs-analyzer/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java", "mask_start_position": 3575, "mask_end_position": 3576, "canonical_solution": "}", "pre_mask_code": "package com.sebastian_daschner.jaxrs_analyzer.model;\n\nimport com.sebastian_daschner.jaxrs_analyzer.LogProvider;\nimport com.sebastian_daschner.jaxrs_analyzer.analysis.classes.ContextClassReader;\nimport org.objectweb.asm.Type;\nimport org.objectweb.asm.signature.SignatureReader;\nimport org.objectweb.asm.util.TraceSignatureVisitor;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.TypeVariable;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static com.sebastian_daschner.jaxrs_analyzer.model.Types.*;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\n\n/**\n * Contains Java reflection utility functionality.\n *\n * @author Sebastian Daschner\n */\npublic final class JavaUtils {\n\n public static final String INITIALIZER_NAME = \"\";\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Checks if the given method name is a Java initializer.\n *\n * @param name The method name\n * @return {@code true} if name is an initializer\n */\n public static boolean isInitializerName(final String name) {\n return INITIALIZER_NAME.equals(name);\n }\n\n /**\n * Returns the annotation or {@code null} if the element is not annotated with that type.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static A getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass) {\n final Optional annotation = Stream.of(annotatedElement.getAnnotations()).filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();\n return (A) annotation.orElse(null);\n }\n\n /**\n * Checks if the annotation is present on the annotated element.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class annotationClass) {\n return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName()));\n }\n\n /**\n * Determines the type which is most \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the first type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n */\n public static String determineMostSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineMostSpecific(types[0], types[1]);\n default:\n String currentMostSpecific = determineMostSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentMostSpecific = determineMostSpecific(currentMostSpecific, types[i]);\n }\n return currentMostSpecific;\n }\n ", "post_mask_code": "\n\n private static String determineMostSpecific(final String firstType, final String secondType) {\n if (OBJECT.equals(secondType) || firstType.equals(secondType)) {\n return firstType;\n }\n if (OBJECT.equals(firstType))\n return secondType;\n final List firstTypeParameters = getTypeParameters(firstType);\n final List secondTypeParameters = getTypeParameters(secondType);\n final boolean firstTypeParameterized = !firstTypeParameters.isEmpty();\n final boolean secondTypeParameterized = !secondTypeParameters.isEmpty();\n if (firstTypeParameterized || secondTypeParameterized) {\n if (firstTypeParameterized && !secondTypeParameterized) {\n return firstType;\n }\n if (!firstTypeParameterized) {\n return secondType;\n }\n if (firstTypeParameters.size() != secondTypeParameters.size())\n // types parameters are not compatible, no statement can be made\n return firstType;\n for (int i = 0; i < firstTypeParameters.size(); i++) {\n final String firstInner = firstTypeParameters.get(i);\n final String secondInner = secondTypeParameters.get(i);\n if (firstInner.equals(secondInner))\n continue;\n // desired to test against identity, i.e. which object was taken by comparison\n if (firstInner == determineMostSpecific(firstInner, secondInner))\n return firstType;\n return secondType;\n }\n }\n final boolean firstTypeArray = firstType.charAt(0) == '[';\n final boolean secondTypeArray = secondType.charAt(0) == '[';\n if (firstTypeArray || secondTypeArray) {\n if (firstTypeArray && !secondTypeArray) {\n return firstType;\n }\n if (!firstTypeArray) {\n return secondType;\n }\n }\n // check if one type is inherited from other\n if (isAssignableTo(firstType, secondType))\n return firstType;\n if (isAssignableTo(secondType, firstType))\n return secondType;\n return firstType;\n }\n\n /**\n * Determines the type which is least \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the second type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n * @see #determineMostSpecificType(String...)\n */\n public static String determineLeastSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineLeastSpecific(types[0], types[1]);\n default:\n String currentLeastSpecific = determineLeastSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentLeastSpecific = determineLeastSpecific(currentLeastSpecific, types[i]);\n }\n return currentLeastSpecific;\n }\n }\n\n private static String determineLeastSpecific(final String firstType, final String secondType) {\n final String mostSpecificType = determineMostSpecificType(firstType, secondType);\n // has to compare identity to see which String object was taken\n if (mostSpecificType == firstType)\n return secondType;\n return firstType;\n }\n\n /**\n * Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type.\n */\n public static boolean isAssignableTo(final String leftType, final String rightType) {\n if (leftType.equals(rightType))\n return true;\n final boolean firstTypeArray = leftType.charAt(0) == '[';\n if (firstTypeArray ^ rightType.charAt(0) == '[') {\n return false;\n }\n final Class leftClass = loadClassFromType(leftType);\n final Class rightClass = loadClassFromType(rightType);\n if (leftClass == null || rightClass == null)\n return false;\n final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);\n return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));\n }\n\n private static boolean hasTypeParameters(final String type) {\n return type.indexOf('<') >= 0;\n }\n\n /**\n * Converts the given JVM object type signature to a class name. Erasures parametrized types.\n *

\n * Example: {@code Ljava/util/List; -> java/util/List}\n *\n * @throws IllegalArgumentException If the type is not a reference or array type.\n */\n public static String toClassName(final String type) {\n switch(type.charAt(0)) {\n case 'V':\n return CLASS_PRIMITIVE_VOID;\n case 'Z':\n return CLASS_PRIMITIVE_BOOLEAN;\n case 'C':\n return CLASS_PRIMITIVE_CHAR;\n case 'B':\n return CLASS_PRIMITIVE_BYTE;\n case 'S':\n return CLASS_PRIMITIVE_SHORT;\n case 'I':\n return CLASS_PRIMITIVE_INT;\n case 'F':\n return CLASS_PRIMITIVE_FLOAT;\n case 'J':\n return CLASS_PRIMITIVE_LONG;\n case 'D':\n return CLASS_PRIMITIVE_DOUBLE;\n case 'L':\n final int typeParamStart = type.indexOf('<');\n final int endIndex = typeParamStart >= 0 ? typeParamStart : type.indexOf(';');\n return type.substring(1, endIndex);\n case '[':\n case '+':\n case '-':\n return toClassName(type.substring(1));\n case 'T':\n // TODO handle type variables\n return CLASS_OBJECT;\n default:\n throw new IllegalArgumentException(\"Not a type signature: \" + type);\n }\n }\n\n /**\n * Converts the given JVM class name to a type signature.\n *

\n * Example: {@code java/util/List -> Ljava/util/List;}\n */\n public static String toType(final String className) {\n return 'L' + className + ';';\n }\n\n /**\n * Converts the given type signature to a human readable type string.\n *

\n * Example: {@code Ljava/util/Map; -> java.util.Map}\n */\n public static String toReadableType(final String type) {\n final SignatureReader reader = new SignatureReader(type);\n final TraceSignatureVisitor visitor = new TraceSignatureVisitor(0);\n reader.acceptType(visitor);\n return visitor.getDeclaration();\n }\n\n /**\n * Returns the JVM type signature of the given object.\n */\n public static String getType(final Object value) {\n return Type.getDescriptor(value.getClass());\n }\n\n /**\n * Returns the type parameters of the given type. Will be an empty list if the type is not parametrized.\n */\n public static List getTypeParameters(final String type) {\n if (type.charAt(0) != 'L')\n return emptyList();\n int lastStart = type.indexOf('<') + 1;\n final List parameters = new ArrayList<>();\n if (lastStart > 0) {\n int depth = 0;\n for (int i = lastStart; i < type.length() - 2; i++) {\n final char c = type.charAt(i);\n if (c == '<')\n depth++;\n else if (c == '>')\n depth--;\n else if (c == ';' && depth == 0) {\n parameters.add(type.substring(lastStart, i + 1));\n lastStart = i + 1;\n }\n }\n }\n return parameters;\n }\n\n /**\n * Returns the return type of the given method signature. Parametrized types are supported.\n */\n public static String getReturnType(final String methodSignature) {\n return getReturnType(methodSignature, null);\n }\n\n public static String getReturnType(final String methodSignature, final String containedType) {\n final String type = methodSignature.substring(methodSignature.lastIndexOf(')') + 1);\n return resolvePotentialTypeVariables(type, containedType);\n }\n\n private static Map getTypeVariables(final String type) {\n if (type == null)\n return emptyMap();\n final Map variables = new HashMap<>();\n final List actualTypeParameters = getTypeParameters(type);\n final Class loadedClass = loadClassFromType(type);\n if (loadedClass == null) {\n LogProvider.debug(\"could not load class for type \" + type);\n return emptyMap();\n }\n final TypeVariable>[] typeParameters = loadedClass.getTypeParameters();\n for (int i = 0; i < actualTypeParameters.size(); i++) {\n variables.put(typeParameters[i].getName(), actualTypeParameters.get(i));\n }\n return variables;\n }\n\n public static Class loadClassFromName(final String className) {\n switch(className) {\n case CLASS_PRIMITIVE_VOID:\n return int.class;\n case CLASS_PRIMITIVE_BOOLEAN:\n return boolean.class;\n case CLASS_PRIMITIVE_CHAR:\n return char.class;\n case CLASS_PRIMITIVE_BYTE:\n return byte.class;\n case CLASS_PRIMITIVE_SHORT:\n return short.class;\n case CLASS_PRIMITIVE_INT:\n return int.class;\n case CLASS_PRIMITIVE_FLOAT:\n return float.class;\n case CLASS_PRIMITIVE_LONG:\n return long.class;\n case CLASS_PRIMITIVE_DOUBLE:\n return double.class;\n }\n // TODO test for variable types\n try {\n return ContextClassReader.getClassLoader().loadClass(className.replace('/', '.'));\n } catch (ClassNotFoundException e) {\n LogProvider.error(\"Could not load class \" + className);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static Class loadClassFromType(final String type) {\n return loadClassFromName(toClassName(type));\n }\n\n public static Method findMethod(final String className, final String methodName, final String signature) {\n final Class loadedClass = loadClassFromName(className);\n if (loadedClass == null)\n return null;\n return findMethod(loadedClass, methodName, signature);\n }\n\n public static Method findMethod(final Class loadedClass, final String methodName, final String signature) {\n final List parameters = getParameters(signature);\n return Stream.of(loadedClass.getDeclaredMethods()).filter(m -> m.getName().equals(methodName) && m.getParameterCount() == parameters.size() && // return types are not taken into account (could be overloaded method w/ different return type)\n Objects.equals(getParameters(getMethodSignature(m)), parameters)).findAny().orElse(null);\n }\n\n public static String getMethodSignature(final String returnType, final String... parameterTypes) {\n final String parameters = Stream.of(parameterTypes).collect(Collectors.joining());\n return '(' + parameters + ')' + returnType;\n }\n\n public static String getMethodSignature(final Method method) {\n try {\n final Field signatureField = method.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n final String signature = (String) signatureField.get(method);\n if (signature != null)\n return signature;\n return Type.getMethodDescriptor(method);\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access method \" + method);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static String getFieldDescriptor(final Field field, final String containedType) {\n try {\n final Field signatureField = field.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n String signature = (String) signatureField.get(field);\n if (signature != null) {\n return resolvePotentialTypeVariables(signature, containedType);\n }\n return Type.getDescriptor(field.getType());\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access field \" + field);\n LogProvider.debug(e);\n return null;\n }\n }\n\n private static String resolvePotentialTypeVariables(final String signature, final String containedType) {\n // resolve type variables immediately\n if (signature.charAt(0) == 'T' || signature.contains(\" typeVariables = getTypeVariables(containedType);\n StringBuilder builder = new StringBuilder(signature);\n boolean startType = true;\n for (int i = 0; i < builder.length(); i++) {\n if (startType && builder.charAt(i) == 'T') {\n final int end = builder.indexOf(\";\", i);\n final String identifier = builder.substring(i + 1, end);\n final String resolvedVariableType = typeVariables.getOrDefault(identifier, OBJECT);\n builder.replace(i, end + 1, resolvedVariableType);\n i = end;\n continue;\n }\n startType = builder.charAt(i) == '<' || builder.charAt(i) == ';';\n }\n return builder.toString();\n }\n return signature;\n }\n\n /**\n * Returns the parameter types of the given method signature. Parametrized types are supported.\n */\n public static List getParameters(final String methodDesc) {\n if (methodDesc == null)\n return emptyList();\n final char[] buffer = methodDesc.toCharArray();\n final List args = new ArrayList<>();\n // TODO resolve type parameters correctly -> information useful? -> maybe use ASM's SignatureReader/Visitor\n int offset = methodDesc.indexOf('(') + 1;\n while (buffer[offset] != ')') {\n final String type = getNextType(buffer, offset);\n args.add(type);\n offset += type.length();\n }\n // TODO change, see type parameters\n // prevent type parameter identifiers\n final ListIterator iterator = args.listIterator();\n while (iterator.hasNext()) {\n final String arg = iterator.next();\n if (arg.charAt(0) == 'T')\n iterator.set(OBJECT);\n }\n return args;\n }\n\n /**\n * Resolves the given method signatures to an array of (self-contained) Java type descriptions.\n *\n * @param methodDesc The method description signature (can contain type parameters and generics)\n * @return The types as an array with the method parameter types first and the return type as index {@code array.length - 1}\n */\n private static String[] resolveMethodSignature(final String methodDesc) {\n // if starts with '<' -> resolve type parameters\n return null;\n }\n\n private static Map resolveTypeParameters(final String methodDesc) {\n return null;\n }\n\n private static String getNextType(final char[] buf, final int off) {\n switch(buf[off]) {\n case 'V':\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n case 'F':\n case 'J':\n case 'D':\n return String.valueOf(buf[off]);\n case '[':\n int len = 1;\n while (buf[off + len] == '[') {\n len++;\n }\n return getNextType(buf, off, len);\n case 'L':\n // TODO resolve type variables\n case 'T':\n return getNextType(buf, off, 0);\n default:\n throw new IllegalArgumentException(\"Illegal signature provided: \" + new String(buf));\n }\n }\n\n private static String getNextType(char[] buf, int off, int len) {\n int depth = 0;\n if (buf[off + len] == 'L' || buf[off + len] == 'T')\n while (buf[off + len] != ';' || depth != 0) {\n if (buf[off + len] == '<')\n depth++;\n else if (buf[off + len] == '>')\n depth--;\n len++;\n }\n return new String(buf, off, len + 1);\n }\n}\n"} {"task_id": "Java_792", "language": "Java", "task_type": "single_line", "source_file": "java/github/sdaschner/jaxrs-analyzer/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java", "mask_start_position": 14466, "mask_end_position": 14495, "canonical_solution": "loadClassFromName(className);", "pre_mask_code": "package com.sebastian_daschner.jaxrs_analyzer.model;\n\nimport com.sebastian_daschner.jaxrs_analyzer.LogProvider;\nimport com.sebastian_daschner.jaxrs_analyzer.analysis.classes.ContextClassReader;\nimport org.objectweb.asm.Type;\nimport org.objectweb.asm.signature.SignatureReader;\nimport org.objectweb.asm.util.TraceSignatureVisitor;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.TypeVariable;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static com.sebastian_daschner.jaxrs_analyzer.model.Types.*;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\n\n/**\n * Contains Java reflection utility functionality.\n *\n * @author Sebastian Daschner\n */\npublic final class JavaUtils {\n\n public static final String INITIALIZER_NAME = \"\";\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Checks if the given method name is a Java initializer.\n *\n * @param name The method name\n * @return {@code true} if name is an initializer\n */\n public static boolean isInitializerName(final String name) {\n return INITIALIZER_NAME.equals(name);\n }\n\n /**\n * Returns the annotation or {@code null} if the element is not annotated with that type.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static A getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass) {\n final Optional annotation = Stream.of(annotatedElement.getAnnotations()).filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();\n return (A) annotation.orElse(null);\n }\n\n /**\n * Checks if the annotation is present on the annotated element.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class annotationClass) {\n return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName()));\n }\n\n /**\n * Determines the type which is most \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the first type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n */\n public static String determineMostSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineMostSpecific(types[0], types[1]);\n default:\n String currentMostSpecific = determineMostSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentMostSpecific = determineMostSpecific(currentMostSpecific, types[i]);\n }\n return currentMostSpecific;\n }\n }\n\n private static String determineMostSpecific(final String firstType, final String secondType) {\n if (OBJECT.equals(secondType) || firstType.equals(secondType)) {\n return firstType;\n }\n if (OBJECT.equals(firstType))\n return secondType;\n final List firstTypeParameters = getTypeParameters(firstType);\n final List secondTypeParameters = getTypeParameters(secondType);\n final boolean firstTypeParameterized = !firstTypeParameters.isEmpty();\n final boolean secondTypeParameterized = !secondTypeParameters.isEmpty();\n if (firstTypeParameterized || secondTypeParameterized) {\n if (firstTypeParameterized && !secondTypeParameterized) {\n return firstType;\n }\n if (!firstTypeParameterized) {\n return secondType;\n }\n if (firstTypeParameters.size() != secondTypeParameters.size())\n // types parameters are not compatible, no statement can be made\n return firstType;\n for (int i = 0; i < firstTypeParameters.size(); i++) {\n final String firstInner = firstTypeParameters.get(i);\n final String secondInner = secondTypeParameters.get(i);\n if (firstInner.equals(secondInner))\n continue;\n // desired to test against identity, i.e. which object was taken by comparison\n if (firstInner == determineMostSpecific(firstInner, secondInner))\n return firstType;\n return secondType;\n }\n }\n final boolean firstTypeArray = firstType.charAt(0) == '[';\n final boolean secondTypeArray = secondType.charAt(0) == '[';\n if (firstTypeArray || secondTypeArray) {\n if (firstTypeArray && !secondTypeArray) {\n return firstType;\n }\n if (!firstTypeArray) {\n return secondType;\n }\n }\n // check if one type is inherited from other\n if (isAssignableTo(firstType, secondType))\n return firstType;\n if (isAssignableTo(secondType, firstType))\n return secondType;\n return firstType;\n }\n\n /**\n * Determines the type which is least \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the second type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n * @see #determineMostSpecificType(String...)\n */\n public static String determineLeastSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineLeastSpecific(types[0], types[1]);\n default:\n String currentLeastSpecific = determineLeastSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentLeastSpecific = determineLeastSpecific(currentLeastSpecific, types[i]);\n }\n return currentLeastSpecific;\n }\n }\n\n private static String determineLeastSpecific(final String firstType, final String secondType) {\n final String mostSpecificType = determineMostSpecificType(firstType, secondType);\n // has to compare identity to see which String object was taken\n if (mostSpecificType == firstType)\n return secondType;\n return firstType;\n }\n\n /**\n * Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type.\n */\n public static boolean isAssignableTo(final String leftType, final String rightType) {\n if (leftType.equals(rightType))\n return true;\n final boolean firstTypeArray = leftType.charAt(0) == '[';\n if (firstTypeArray ^ rightType.charAt(0) == '[') {\n return false;\n }\n final Class leftClass = loadClassFromType(leftType);\n final Class rightClass = loadClassFromType(rightType);\n if (leftClass == null || rightClass == null)\n return false;\n final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);\n return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));\n }\n\n private static boolean hasTypeParameters(final String type) {\n return type.indexOf('<') >= 0;\n }\n\n /**\n * Converts the given JVM object type signature to a class name. Erasures parametrized types.\n *

\n * Example: {@code Ljava/util/List; -> java/util/List}\n *\n * @throws IllegalArgumentException If the type is not a reference or array type.\n */\n public static String toClassName(final String type) {\n switch(type.charAt(0)) {\n case 'V':\n return CLASS_PRIMITIVE_VOID;\n case 'Z':\n return CLASS_PRIMITIVE_BOOLEAN;\n case 'C':\n return CLASS_PRIMITIVE_CHAR;\n case 'B':\n return CLASS_PRIMITIVE_BYTE;\n case 'S':\n return CLASS_PRIMITIVE_SHORT;\n case 'I':\n return CLASS_PRIMITIVE_INT;\n case 'F':\n return CLASS_PRIMITIVE_FLOAT;\n case 'J':\n return CLASS_PRIMITIVE_LONG;\n case 'D':\n return CLASS_PRIMITIVE_DOUBLE;\n case 'L':\n final int typeParamStart = type.indexOf('<');\n final int endIndex = typeParamStart >= 0 ? typeParamStart : type.indexOf(';');\n return type.substring(1, endIndex);\n case '[':\n case '+':\n case '-':\n return toClassName(type.substring(1));\n case 'T':\n // TODO handle type variables\n return CLASS_OBJECT;\n default:\n throw new IllegalArgumentException(\"Not a type signature: \" + type);\n }\n }\n\n /**\n * Converts the given JVM class name to a type signature.\n *

\n * Example: {@code java/util/List -> Ljava/util/List;}\n */\n public static String toType(final String className) {\n return 'L' + className + ';';\n }\n\n /**\n * Converts the given type signature to a human readable type string.\n *

\n * Example: {@code Ljava/util/Map; -> java.util.Map}\n */\n public static String toReadableType(final String type) {\n final SignatureReader reader = new SignatureReader(type);\n final TraceSignatureVisitor visitor = new TraceSignatureVisitor(0);\n reader.acceptType(visitor);\n return visitor.getDeclaration();\n }\n\n /**\n * Returns the JVM type signature of the given object.\n */\n public static String getType(final Object value) {\n return Type.getDescriptor(value.getClass());\n }\n\n /**\n * Returns the type parameters of the given type. Will be an empty list if the type is not parametrized.\n */\n public static List getTypeParameters(final String type) {\n if (type.charAt(0) != 'L')\n return emptyList();\n int lastStart = type.indexOf('<') + 1;\n final List parameters = new ArrayList<>();\n if (lastStart > 0) {\n int depth = 0;\n for (int i = lastStart; i < type.length() - 2; i++) {\n final char c = type.charAt(i);\n if (c == '<')\n depth++;\n else if (c == '>')\n depth--;\n else if (c == ';' && depth == 0) {\n parameters.add(type.substring(lastStart, i + 1));\n lastStart = i + 1;\n }\n }\n }\n return parameters;\n }\n\n /**\n * Returns the return type of the given method signature. Parametrized types are supported.\n */\n public static String getReturnType(final String methodSignature) {\n return getReturnType(methodSignature, null);\n }\n\n public static String getReturnType(final String methodSignature, final String containedType) {\n final String type = methodSignature.substring(methodSignature.lastIndexOf(')') + 1);\n return resolvePotentialTypeVariables(type, containedType);\n }\n\n private static Map getTypeVariables(final String type) {\n if (type == null)\n return emptyMap();\n final Map variables = new HashMap<>();\n final List actualTypeParameters = getTypeParameters(type);\n final Class loadedClass = loadClassFromType(type);\n if (loadedClass == null) {\n LogProvider.debug(\"could not load class for type \" + type);\n return emptyMap();\n }\n final TypeVariable>[] typeParameters = loadedClass.getTypeParameters();\n for (int i = 0; i < actualTypeParameters.size(); i++) {\n variables.put(typeParameters[i].getName(), actualTypeParameters.get(i));\n }\n return variables;\n }\n\n public static Class loadClassFromName(final String className) {\n switch(className) {\n case CLASS_PRIMITIVE_VOID:\n return int.class;\n case CLASS_PRIMITIVE_BOOLEAN:\n return boolean.class;\n case CLASS_PRIMITIVE_CHAR:\n return char.class;\n case CLASS_PRIMITIVE_BYTE:\n return byte.class;\n case CLASS_PRIMITIVE_SHORT:\n return short.class;\n case CLASS_PRIMITIVE_INT:\n return int.class;\n case CLASS_PRIMITIVE_FLOAT:\n return float.class;\n case CLASS_PRIMITIVE_LONG:\n return long.class;\n case CLASS_PRIMITIVE_DOUBLE:\n return double.class;\n }\n // TODO test for variable types\n try {\n return ContextClassReader.getClassLoader().loadClass(className.replace('/', '.'));\n } catch (ClassNotFoundException e) {\n LogProvider.error(\"Could not load class \" + className);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static Class loadClassFromType(final String type) {\n return loadClassFromName(toClassName(type));\n }\n\n public static Method findMethod(final String className, final String methodName, final String signature) {\n final Class loadedClass = ", "post_mask_code": "\n if (loadedClass == null)\n return null;\n return findMethod(loadedClass, methodName, signature);\n }\n\n public static Method findMethod(final Class loadedClass, final String methodName, final String signature) {\n final List parameters = getParameters(signature);\n return Stream.of(loadedClass.getDeclaredMethods()).filter(m -> m.getName().equals(methodName) && m.getParameterCount() == parameters.size() && // return types are not taken into account (could be overloaded method w/ different return type)\n Objects.equals(getParameters(getMethodSignature(m)), parameters)).findAny().orElse(null);\n }\n\n public static String getMethodSignature(final String returnType, final String... parameterTypes) {\n final String parameters = Stream.of(parameterTypes).collect(Collectors.joining());\n return '(' + parameters + ')' + returnType;\n }\n\n public static String getMethodSignature(final Method method) {\n try {\n final Field signatureField = method.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n final String signature = (String) signatureField.get(method);\n if (signature != null)\n return signature;\n return Type.getMethodDescriptor(method);\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access method \" + method);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static String getFieldDescriptor(final Field field, final String containedType) {\n try {\n final Field signatureField = field.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n String signature = (String) signatureField.get(field);\n if (signature != null) {\n return resolvePotentialTypeVariables(signature, containedType);\n }\n return Type.getDescriptor(field.getType());\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access field \" + field);\n LogProvider.debug(e);\n return null;\n }\n }\n\n private static String resolvePotentialTypeVariables(final String signature, final String containedType) {\n // resolve type variables immediately\n if (signature.charAt(0) == 'T' || signature.contains(\" typeVariables = getTypeVariables(containedType);\n StringBuilder builder = new StringBuilder(signature);\n boolean startType = true;\n for (int i = 0; i < builder.length(); i++) {\n if (startType && builder.charAt(i) == 'T') {\n final int end = builder.indexOf(\";\", i);\n final String identifier = builder.substring(i + 1, end);\n final String resolvedVariableType = typeVariables.getOrDefault(identifier, OBJECT);\n builder.replace(i, end + 1, resolvedVariableType);\n i = end;\n continue;\n }\n startType = builder.charAt(i) == '<' || builder.charAt(i) == ';';\n }\n return builder.toString();\n }\n return signature;\n }\n\n /**\n * Returns the parameter types of the given method signature. Parametrized types are supported.\n */\n public static List getParameters(final String methodDesc) {\n if (methodDesc == null)\n return emptyList();\n final char[] buffer = methodDesc.toCharArray();\n final List args = new ArrayList<>();\n // TODO resolve type parameters correctly -> information useful? -> maybe use ASM's SignatureReader/Visitor\n int offset = methodDesc.indexOf('(') + 1;\n while (buffer[offset] != ')') {\n final String type = getNextType(buffer, offset);\n args.add(type);\n offset += type.length();\n }\n // TODO change, see type parameters\n // prevent type parameter identifiers\n final ListIterator iterator = args.listIterator();\n while (iterator.hasNext()) {\n final String arg = iterator.next();\n if (arg.charAt(0) == 'T')\n iterator.set(OBJECT);\n }\n return args;\n }\n\n /**\n * Resolves the given method signatures to an array of (self-contained) Java type descriptions.\n *\n * @param methodDesc The method description signature (can contain type parameters and generics)\n * @return The types as an array with the method parameter types first and the return type as index {@code array.length - 1}\n */\n private static String[] resolveMethodSignature(final String methodDesc) {\n // if starts with '<' -> resolve type parameters\n return null;\n }\n\n private static Map resolveTypeParameters(final String methodDesc) {\n return null;\n }\n\n private static String getNextType(final char[] buf, final int off) {\n switch(buf[off]) {\n case 'V':\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n case 'F':\n case 'J':\n case 'D':\n return String.valueOf(buf[off]);\n case '[':\n int len = 1;\n while (buf[off + len] == '[') {\n len++;\n }\n return getNextType(buf, off, len);\n case 'L':\n // TODO resolve type variables\n case 'T':\n return getNextType(buf, off, 0);\n default:\n throw new IllegalArgumentException(\"Illegal signature provided: \" + new String(buf));\n }\n }\n\n private static String getNextType(char[] buf, int off, int len) {\n int depth = 0;\n if (buf[off + len] == 'L' || buf[off + len] == 'T')\n while (buf[off + len] != ';' || depth != 0) {\n if (buf[off + len] == '<')\n depth++;\n else if (buf[off + len] == '>')\n depth--;\n len++;\n }\n return new String(buf, off, len + 1);\n }\n}\n"} {"task_id": "Java_793", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/sdaschner/jaxrs-analyzer/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java", "mask_start_position": 2257, "mask_end_position": 2543, "canonical_solution": "public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class annotationClass) {\n return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName()));\n }", "pre_mask_code": "package com.sebastian_daschner.jaxrs_analyzer.model;\n\nimport com.sebastian_daschner.jaxrs_analyzer.LogProvider;\nimport com.sebastian_daschner.jaxrs_analyzer.analysis.classes.ContextClassReader;\nimport org.objectweb.asm.Type;\nimport org.objectweb.asm.signature.SignatureReader;\nimport org.objectweb.asm.util.TraceSignatureVisitor;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.TypeVariable;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static com.sebastian_daschner.jaxrs_analyzer.model.Types.*;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\n\n/**\n * Contains Java reflection utility functionality.\n *\n * @author Sebastian Daschner\n */\npublic final class JavaUtils {\n\n public static final String INITIALIZER_NAME = \"\";\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Checks if the given method name is a Java initializer.\n *\n * @param name The method name\n * @return {@code true} if name is an initializer\n */\n public static boolean isInitializerName(final String name) {\n return INITIALIZER_NAME.equals(name);\n }\n\n /**\n * Returns the annotation or {@code null} if the element is not annotated with that type.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static A getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass) {\n final Optional annotation = Stream.of(annotatedElement.getAnnotations()).filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();\n return (A) annotation.orElse(null);\n }\n\n /**\n * Checks if the annotation is present on the annotated element.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n ", "post_mask_code": "\n\n /**\n * Determines the type which is most \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the first type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n */\n public static String determineMostSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineMostSpecific(types[0], types[1]);\n default:\n String currentMostSpecific = determineMostSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentMostSpecific = determineMostSpecific(currentMostSpecific, types[i]);\n }\n return currentMostSpecific;\n }\n }\n\n private static String determineMostSpecific(final String firstType, final String secondType) {\n if (OBJECT.equals(secondType) || firstType.equals(secondType)) {\n return firstType;\n }\n if (OBJECT.equals(firstType))\n return secondType;\n final List firstTypeParameters = getTypeParameters(firstType);\n final List secondTypeParameters = getTypeParameters(secondType);\n final boolean firstTypeParameterized = !firstTypeParameters.isEmpty();\n final boolean secondTypeParameterized = !secondTypeParameters.isEmpty();\n if (firstTypeParameterized || secondTypeParameterized) {\n if (firstTypeParameterized && !secondTypeParameterized) {\n return firstType;\n }\n if (!firstTypeParameterized) {\n return secondType;\n }\n if (firstTypeParameters.size() != secondTypeParameters.size())\n // types parameters are not compatible, no statement can be made\n return firstType;\n for (int i = 0; i < firstTypeParameters.size(); i++) {\n final String firstInner = firstTypeParameters.get(i);\n final String secondInner = secondTypeParameters.get(i);\n if (firstInner.equals(secondInner))\n continue;\n // desired to test against identity, i.e. which object was taken by comparison\n if (firstInner == determineMostSpecific(firstInner, secondInner))\n return firstType;\n return secondType;\n }\n }\n final boolean firstTypeArray = firstType.charAt(0) == '[';\n final boolean secondTypeArray = secondType.charAt(0) == '[';\n if (firstTypeArray || secondTypeArray) {\n if (firstTypeArray && !secondTypeArray) {\n return firstType;\n }\n if (!firstTypeArray) {\n return secondType;\n }\n }\n // check if one type is inherited from other\n if (isAssignableTo(firstType, secondType))\n return firstType;\n if (isAssignableTo(secondType, firstType))\n return secondType;\n return firstType;\n }\n\n /**\n * Determines the type which is least \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the second type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n * @see #determineMostSpecificType(String...)\n */\n public static String determineLeastSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineLeastSpecific(types[0], types[1]);\n default:\n String currentLeastSpecific = determineLeastSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentLeastSpecific = determineLeastSpecific(currentLeastSpecific, types[i]);\n }\n return currentLeastSpecific;\n }\n }\n\n private static String determineLeastSpecific(final String firstType, final String secondType) {\n final String mostSpecificType = determineMostSpecificType(firstType, secondType);\n // has to compare identity to see which String object was taken\n if (mostSpecificType == firstType)\n return secondType;\n return firstType;\n }\n\n /**\n * Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type.\n */\n public static boolean isAssignableTo(final String leftType, final String rightType) {\n if (leftType.equals(rightType))\n return true;\n final boolean firstTypeArray = leftType.charAt(0) == '[';\n if (firstTypeArray ^ rightType.charAt(0) == '[') {\n return false;\n }\n final Class leftClass = loadClassFromType(leftType);\n final Class rightClass = loadClassFromType(rightType);\n if (leftClass == null || rightClass == null)\n return false;\n final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);\n return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));\n }\n\n private static boolean hasTypeParameters(final String type) {\n return type.indexOf('<') >= 0;\n }\n\n /**\n * Converts the given JVM object type signature to a class name. Erasures parametrized types.\n *

\n * Example: {@code Ljava/util/List; -> java/util/List}\n *\n * @throws IllegalArgumentException If the type is not a reference or array type.\n */\n public static String toClassName(final String type) {\n switch(type.charAt(0)) {\n case 'V':\n return CLASS_PRIMITIVE_VOID;\n case 'Z':\n return CLASS_PRIMITIVE_BOOLEAN;\n case 'C':\n return CLASS_PRIMITIVE_CHAR;\n case 'B':\n return CLASS_PRIMITIVE_BYTE;\n case 'S':\n return CLASS_PRIMITIVE_SHORT;\n case 'I':\n return CLASS_PRIMITIVE_INT;\n case 'F':\n return CLASS_PRIMITIVE_FLOAT;\n case 'J':\n return CLASS_PRIMITIVE_LONG;\n case 'D':\n return CLASS_PRIMITIVE_DOUBLE;\n case 'L':\n final int typeParamStart = type.indexOf('<');\n final int endIndex = typeParamStart >= 0 ? typeParamStart : type.indexOf(';');\n return type.substring(1, endIndex);\n case '[':\n case '+':\n case '-':\n return toClassName(type.substring(1));\n case 'T':\n // TODO handle type variables\n return CLASS_OBJECT;\n default:\n throw new IllegalArgumentException(\"Not a type signature: \" + type);\n }\n }\n\n /**\n * Converts the given JVM class name to a type signature.\n *

\n * Example: {@code java/util/List -> Ljava/util/List;}\n */\n public static String toType(final String className) {\n return 'L' + className + ';';\n }\n\n /**\n * Converts the given type signature to a human readable type string.\n *

\n * Example: {@code Ljava/util/Map; -> java.util.Map}\n */\n public static String toReadableType(final String type) {\n final SignatureReader reader = new SignatureReader(type);\n final TraceSignatureVisitor visitor = new TraceSignatureVisitor(0);\n reader.acceptType(visitor);\n return visitor.getDeclaration();\n }\n\n /**\n * Returns the JVM type signature of the given object.\n */\n public static String getType(final Object value) {\n return Type.getDescriptor(value.getClass());\n }\n\n /**\n * Returns the type parameters of the given type. Will be an empty list if the type is not parametrized.\n */\n public static List getTypeParameters(final String type) {\n if (type.charAt(0) != 'L')\n return emptyList();\n int lastStart = type.indexOf('<') + 1;\n final List parameters = new ArrayList<>();\n if (lastStart > 0) {\n int depth = 0;\n for (int i = lastStart; i < type.length() - 2; i++) {\n final char c = type.charAt(i);\n if (c == '<')\n depth++;\n else if (c == '>')\n depth--;\n else if (c == ';' && depth == 0) {\n parameters.add(type.substring(lastStart, i + 1));\n lastStart = i + 1;\n }\n }\n }\n return parameters;\n }\n\n /**\n * Returns the return type of the given method signature. Parametrized types are supported.\n */\n public static String getReturnType(final String methodSignature) {\n return getReturnType(methodSignature, null);\n }\n\n public static String getReturnType(final String methodSignature, final String containedType) {\n final String type = methodSignature.substring(methodSignature.lastIndexOf(')') + 1);\n return resolvePotentialTypeVariables(type, containedType);\n }\n\n private static Map getTypeVariables(final String type) {\n if (type == null)\n return emptyMap();\n final Map variables = new HashMap<>();\n final List actualTypeParameters = getTypeParameters(type);\n final Class loadedClass = loadClassFromType(type);\n if (loadedClass == null) {\n LogProvider.debug(\"could not load class for type \" + type);\n return emptyMap();\n }\n final TypeVariable>[] typeParameters = loadedClass.getTypeParameters();\n for (int i = 0; i < actualTypeParameters.size(); i++) {\n variables.put(typeParameters[i].getName(), actualTypeParameters.get(i));\n }\n return variables;\n }\n\n public static Class loadClassFromName(final String className) {\n switch(className) {\n case CLASS_PRIMITIVE_VOID:\n return int.class;\n case CLASS_PRIMITIVE_BOOLEAN:\n return boolean.class;\n case CLASS_PRIMITIVE_CHAR:\n return char.class;\n case CLASS_PRIMITIVE_BYTE:\n return byte.class;\n case CLASS_PRIMITIVE_SHORT:\n return short.class;\n case CLASS_PRIMITIVE_INT:\n return int.class;\n case CLASS_PRIMITIVE_FLOAT:\n return float.class;\n case CLASS_PRIMITIVE_LONG:\n return long.class;\n case CLASS_PRIMITIVE_DOUBLE:\n return double.class;\n }\n // TODO test for variable types\n try {\n return ContextClassReader.getClassLoader().loadClass(className.replace('/', '.'));\n } catch (ClassNotFoundException e) {\n LogProvider.error(\"Could not load class \" + className);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static Class loadClassFromType(final String type) {\n return loadClassFromName(toClassName(type));\n }\n\n public static Method findMethod(final String className, final String methodName, final String signature) {\n final Class loadedClass = loadClassFromName(className);\n if (loadedClass == null)\n return null;\n return findMethod(loadedClass, methodName, signature);\n }\n\n public static Method findMethod(final Class loadedClass, final String methodName, final String signature) {\n final List parameters = getParameters(signature);\n return Stream.of(loadedClass.getDeclaredMethods()).filter(m -> m.getName().equals(methodName) && m.getParameterCount() == parameters.size() && // return types are not taken into account (could be overloaded method w/ different return type)\n Objects.equals(getParameters(getMethodSignature(m)), parameters)).findAny().orElse(null);\n }\n\n public static String getMethodSignature(final String returnType, final String... parameterTypes) {\n final String parameters = Stream.of(parameterTypes).collect(Collectors.joining());\n return '(' + parameters + ')' + returnType;\n }\n\n public static String getMethodSignature(final Method method) {\n try {\n final Field signatureField = method.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n final String signature = (String) signatureField.get(method);\n if (signature != null)\n return signature;\n return Type.getMethodDescriptor(method);\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access method \" + method);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static String getFieldDescriptor(final Field field, final String containedType) {\n try {\n final Field signatureField = field.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n String signature = (String) signatureField.get(field);\n if (signature != null) {\n return resolvePotentialTypeVariables(signature, containedType);\n }\n return Type.getDescriptor(field.getType());\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access field \" + field);\n LogProvider.debug(e);\n return null;\n }\n }\n\n private static String resolvePotentialTypeVariables(final String signature, final String containedType) {\n // resolve type variables immediately\n if (signature.charAt(0) == 'T' || signature.contains(\" typeVariables = getTypeVariables(containedType);\n StringBuilder builder = new StringBuilder(signature);\n boolean startType = true;\n for (int i = 0; i < builder.length(); i++) {\n if (startType && builder.charAt(i) == 'T') {\n final int end = builder.indexOf(\";\", i);\n final String identifier = builder.substring(i + 1, end);\n final String resolvedVariableType = typeVariables.getOrDefault(identifier, OBJECT);\n builder.replace(i, end + 1, resolvedVariableType);\n i = end;\n continue;\n }\n startType = builder.charAt(i) == '<' || builder.charAt(i) == ';';\n }\n return builder.toString();\n }\n return signature;\n }\n\n /**\n * Returns the parameter types of the given method signature. Parametrized types are supported.\n */\n public static List getParameters(final String methodDesc) {\n if (methodDesc == null)\n return emptyList();\n final char[] buffer = methodDesc.toCharArray();\n final List args = new ArrayList<>();\n // TODO resolve type parameters correctly -> information useful? -> maybe use ASM's SignatureReader/Visitor\n int offset = methodDesc.indexOf('(') + 1;\n while (buffer[offset] != ')') {\n final String type = getNextType(buffer, offset);\n args.add(type);\n offset += type.length();\n }\n // TODO change, see type parameters\n // prevent type parameter identifiers\n final ListIterator iterator = args.listIterator();\n while (iterator.hasNext()) {\n final String arg = iterator.next();\n if (arg.charAt(0) == 'T')\n iterator.set(OBJECT);\n }\n return args;\n }\n\n /**\n * Resolves the given method signatures to an array of (self-contained) Java type descriptions.\n *\n * @param methodDesc The method description signature (can contain type parameters and generics)\n * @return The types as an array with the method parameter types first and the return type as index {@code array.length - 1}\n */\n private static String[] resolveMethodSignature(final String methodDesc) {\n // if starts with '<' -> resolve type parameters\n return null;\n }\n\n private static Map resolveTypeParameters(final String methodDesc) {\n return null;\n }\n\n private static String getNextType(final char[] buf, final int off) {\n switch(buf[off]) {\n case 'V':\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n case 'F':\n case 'J':\n case 'D':\n return String.valueOf(buf[off]);\n case '[':\n int len = 1;\n while (buf[off + len] == '[') {\n len++;\n }\n return getNextType(buf, off, len);\n case 'L':\n // TODO resolve type variables\n case 'T':\n return getNextType(buf, off, 0);\n default:\n throw new IllegalArgumentException(\"Illegal signature provided: \" + new String(buf));\n }\n }\n\n private static String getNextType(char[] buf, int off, int len) {\n int depth = 0;\n if (buf[off + len] == 'L' || buf[off + len] == 'T')\n while (buf[off + len] != ';' || depth != 0) {\n if (buf[off + len] == '<')\n depth++;\n else if (buf[off + len] == '>')\n depth--;\n len++;\n }\n return new String(buf, off, len + 1);\n }\n}\n"} {"task_id": "Java_794", "language": "Java", "task_type": "if_statement", "source_file": "java/github/sdaschner/jaxrs-analyzer/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java", "mask_start_position": 12380, "mask_end_position": 12428, "canonical_solution": "if (type == null)\n return emptyMap();", "pre_mask_code": "package com.sebastian_daschner.jaxrs_analyzer.model;\n\nimport com.sebastian_daschner.jaxrs_analyzer.LogProvider;\nimport com.sebastian_daschner.jaxrs_analyzer.analysis.classes.ContextClassReader;\nimport org.objectweb.asm.Type;\nimport org.objectweb.asm.signature.SignatureReader;\nimport org.objectweb.asm.util.TraceSignatureVisitor;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.TypeVariable;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static com.sebastian_daschner.jaxrs_analyzer.model.Types.*;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\n\n/**\n * Contains Java reflection utility functionality.\n *\n * @author Sebastian Daschner\n */\npublic final class JavaUtils {\n\n public static final String INITIALIZER_NAME = \"\";\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Checks if the given method name is a Java initializer.\n *\n * @param name The method name\n * @return {@code true} if name is an initializer\n */\n public static boolean isInitializerName(final String name) {\n return INITIALIZER_NAME.equals(name);\n }\n\n /**\n * Returns the annotation or {@code null} if the element is not annotated with that type.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static A getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass) {\n final Optional annotation = Stream.of(annotatedElement.getAnnotations()).filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();\n return (A) annotation.orElse(null);\n }\n\n /**\n * Checks if the annotation is present on the annotated element.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class annotationClass) {\n return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName()));\n }\n\n /**\n * Determines the type which is most \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the first type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n */\n public static String determineMostSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineMostSpecific(types[0], types[1]);\n default:\n String currentMostSpecific = determineMostSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentMostSpecific = determineMostSpecific(currentMostSpecific, types[i]);\n }\n return currentMostSpecific;\n }\n }\n\n private static String determineMostSpecific(final String firstType, final String secondType) {\n if (OBJECT.equals(secondType) || firstType.equals(secondType)) {\n return firstType;\n }\n if (OBJECT.equals(firstType))\n return secondType;\n final List firstTypeParameters = getTypeParameters(firstType);\n final List secondTypeParameters = getTypeParameters(secondType);\n final boolean firstTypeParameterized = !firstTypeParameters.isEmpty();\n final boolean secondTypeParameterized = !secondTypeParameters.isEmpty();\n if (firstTypeParameterized || secondTypeParameterized) {\n if (firstTypeParameterized && !secondTypeParameterized) {\n return firstType;\n }\n if (!firstTypeParameterized) {\n return secondType;\n }\n if (firstTypeParameters.size() != secondTypeParameters.size())\n // types parameters are not compatible, no statement can be made\n return firstType;\n for (int i = 0; i < firstTypeParameters.size(); i++) {\n final String firstInner = firstTypeParameters.get(i);\n final String secondInner = secondTypeParameters.get(i);\n if (firstInner.equals(secondInner))\n continue;\n // desired to test against identity, i.e. which object was taken by comparison\n if (firstInner == determineMostSpecific(firstInner, secondInner))\n return firstType;\n return secondType;\n }\n }\n final boolean firstTypeArray = firstType.charAt(0) == '[';\n final boolean secondTypeArray = secondType.charAt(0) == '[';\n if (firstTypeArray || secondTypeArray) {\n if (firstTypeArray && !secondTypeArray) {\n return firstType;\n }\n if (!firstTypeArray) {\n return secondType;\n }\n }\n // check if one type is inherited from other\n if (isAssignableTo(firstType, secondType))\n return firstType;\n if (isAssignableTo(secondType, firstType))\n return secondType;\n return firstType;\n }\n\n /**\n * Determines the type which is least \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the second type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n * @see #determineMostSpecificType(String...)\n */\n public static String determineLeastSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineLeastSpecific(types[0], types[1]);\n default:\n String currentLeastSpecific = determineLeastSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentLeastSpecific = determineLeastSpecific(currentLeastSpecific, types[i]);\n }\n return currentLeastSpecific;\n }\n }\n\n private static String determineLeastSpecific(final String firstType, final String secondType) {\n final String mostSpecificType = determineMostSpecificType(firstType, secondType);\n // has to compare identity to see which String object was taken\n if (mostSpecificType == firstType)\n return secondType;\n return firstType;\n }\n\n /**\n * Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type.\n */\n public static boolean isAssignableTo(final String leftType, final String rightType) {\n if (leftType.equals(rightType))\n return true;\n final boolean firstTypeArray = leftType.charAt(0) == '[';\n if (firstTypeArray ^ rightType.charAt(0) == '[') {\n return false;\n }\n final Class leftClass = loadClassFromType(leftType);\n final Class rightClass = loadClassFromType(rightType);\n if (leftClass == null || rightClass == null)\n return false;\n final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);\n return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));\n }\n\n private static boolean hasTypeParameters(final String type) {\n return type.indexOf('<') >= 0;\n }\n\n /**\n * Converts the given JVM object type signature to a class name. Erasures parametrized types.\n *

\n * Example: {@code Ljava/util/List; -> java/util/List}\n *\n * @throws IllegalArgumentException If the type is not a reference or array type.\n */\n public static String toClassName(final String type) {\n switch(type.charAt(0)) {\n case 'V':\n return CLASS_PRIMITIVE_VOID;\n case 'Z':\n return CLASS_PRIMITIVE_BOOLEAN;\n case 'C':\n return CLASS_PRIMITIVE_CHAR;\n case 'B':\n return CLASS_PRIMITIVE_BYTE;\n case 'S':\n return CLASS_PRIMITIVE_SHORT;\n case 'I':\n return CLASS_PRIMITIVE_INT;\n case 'F':\n return CLASS_PRIMITIVE_FLOAT;\n case 'J':\n return CLASS_PRIMITIVE_LONG;\n case 'D':\n return CLASS_PRIMITIVE_DOUBLE;\n case 'L':\n final int typeParamStart = type.indexOf('<');\n final int endIndex = typeParamStart >= 0 ? typeParamStart : type.indexOf(';');\n return type.substring(1, endIndex);\n case '[':\n case '+':\n case '-':\n return toClassName(type.substring(1));\n case 'T':\n // TODO handle type variables\n return CLASS_OBJECT;\n default:\n throw new IllegalArgumentException(\"Not a type signature: \" + type);\n }\n }\n\n /**\n * Converts the given JVM class name to a type signature.\n *

\n * Example: {@code java/util/List -> Ljava/util/List;}\n */\n public static String toType(final String className) {\n return 'L' + className + ';';\n }\n\n /**\n * Converts the given type signature to a human readable type string.\n *

\n * Example: {@code Ljava/util/Map; -> java.util.Map}\n */\n public static String toReadableType(final String type) {\n final SignatureReader reader = new SignatureReader(type);\n final TraceSignatureVisitor visitor = new TraceSignatureVisitor(0);\n reader.acceptType(visitor);\n return visitor.getDeclaration();\n }\n\n /**\n * Returns the JVM type signature of the given object.\n */\n public static String getType(final Object value) {\n return Type.getDescriptor(value.getClass());\n }\n\n /**\n * Returns the type parameters of the given type. Will be an empty list if the type is not parametrized.\n */\n public static List getTypeParameters(final String type) {\n if (type.charAt(0) != 'L')\n return emptyList();\n int lastStart = type.indexOf('<') + 1;\n final List parameters = new ArrayList<>();\n if (lastStart > 0) {\n int depth = 0;\n for (int i = lastStart; i < type.length() - 2; i++) {\n final char c = type.charAt(i);\n if (c == '<')\n depth++;\n else if (c == '>')\n depth--;\n else if (c == ';' && depth == 0) {\n parameters.add(type.substring(lastStart, i + 1));\n lastStart = i + 1;\n }\n }\n }\n return parameters;\n }\n\n /**\n * Returns the return type of the given method signature. Parametrized types are supported.\n */\n public static String getReturnType(final String methodSignature) {\n return getReturnType(methodSignature, null);\n }\n\n public static String getReturnType(final String methodSignature, final String containedType) {\n final String type = methodSignature.substring(methodSignature.lastIndexOf(')') + 1);\n return resolvePotentialTypeVariables(type, containedType);\n }\n\n private static Map getTypeVariables(final String type) {\n ", "post_mask_code": "\n final Map variables = new HashMap<>();\n final List actualTypeParameters = getTypeParameters(type);\n final Class loadedClass = loadClassFromType(type);\n if (loadedClass == null) {\n LogProvider.debug(\"could not load class for type \" + type);\n return emptyMap();\n }\n final TypeVariable>[] typeParameters = loadedClass.getTypeParameters();\n for (int i = 0; i < actualTypeParameters.size(); i++) {\n variables.put(typeParameters[i].getName(), actualTypeParameters.get(i));\n }\n return variables;\n }\n\n public static Class loadClassFromName(final String className) {\n switch(className) {\n case CLASS_PRIMITIVE_VOID:\n return int.class;\n case CLASS_PRIMITIVE_BOOLEAN:\n return boolean.class;\n case CLASS_PRIMITIVE_CHAR:\n return char.class;\n case CLASS_PRIMITIVE_BYTE:\n return byte.class;\n case CLASS_PRIMITIVE_SHORT:\n return short.class;\n case CLASS_PRIMITIVE_INT:\n return int.class;\n case CLASS_PRIMITIVE_FLOAT:\n return float.class;\n case CLASS_PRIMITIVE_LONG:\n return long.class;\n case CLASS_PRIMITIVE_DOUBLE:\n return double.class;\n }\n // TODO test for variable types\n try {\n return ContextClassReader.getClassLoader().loadClass(className.replace('/', '.'));\n } catch (ClassNotFoundException e) {\n LogProvider.error(\"Could not load class \" + className);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static Class loadClassFromType(final String type) {\n return loadClassFromName(toClassName(type));\n }\n\n public static Method findMethod(final String className, final String methodName, final String signature) {\n final Class loadedClass = loadClassFromName(className);\n if (loadedClass == null)\n return null;\n return findMethod(loadedClass, methodName, signature);\n }\n\n public static Method findMethod(final Class loadedClass, final String methodName, final String signature) {\n final List parameters = getParameters(signature);\n return Stream.of(loadedClass.getDeclaredMethods()).filter(m -> m.getName().equals(methodName) && m.getParameterCount() == parameters.size() && // return types are not taken into account (could be overloaded method w/ different return type)\n Objects.equals(getParameters(getMethodSignature(m)), parameters)).findAny().orElse(null);\n }\n\n public static String getMethodSignature(final String returnType, final String... parameterTypes) {\n final String parameters = Stream.of(parameterTypes).collect(Collectors.joining());\n return '(' + parameters + ')' + returnType;\n }\n\n public static String getMethodSignature(final Method method) {\n try {\n final Field signatureField = method.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n final String signature = (String) signatureField.get(method);\n if (signature != null)\n return signature;\n return Type.getMethodDescriptor(method);\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access method \" + method);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static String getFieldDescriptor(final Field field, final String containedType) {\n try {\n final Field signatureField = field.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n String signature = (String) signatureField.get(field);\n if (signature != null) {\n return resolvePotentialTypeVariables(signature, containedType);\n }\n return Type.getDescriptor(field.getType());\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access field \" + field);\n LogProvider.debug(e);\n return null;\n }\n }\n\n private static String resolvePotentialTypeVariables(final String signature, final String containedType) {\n // resolve type variables immediately\n if (signature.charAt(0) == 'T' || signature.contains(\" typeVariables = getTypeVariables(containedType);\n StringBuilder builder = new StringBuilder(signature);\n boolean startType = true;\n for (int i = 0; i < builder.length(); i++) {\n if (startType && builder.charAt(i) == 'T') {\n final int end = builder.indexOf(\";\", i);\n final String identifier = builder.substring(i + 1, end);\n final String resolvedVariableType = typeVariables.getOrDefault(identifier, OBJECT);\n builder.replace(i, end + 1, resolvedVariableType);\n i = end;\n continue;\n }\n startType = builder.charAt(i) == '<' || builder.charAt(i) == ';';\n }\n return builder.toString();\n }\n return signature;\n }\n\n /**\n * Returns the parameter types of the given method signature. Parametrized types are supported.\n */\n public static List getParameters(final String methodDesc) {\n if (methodDesc == null)\n return emptyList();\n final char[] buffer = methodDesc.toCharArray();\n final List args = new ArrayList<>();\n // TODO resolve type parameters correctly -> information useful? -> maybe use ASM's SignatureReader/Visitor\n int offset = methodDesc.indexOf('(') + 1;\n while (buffer[offset] != ')') {\n final String type = getNextType(buffer, offset);\n args.add(type);\n offset += type.length();\n }\n // TODO change, see type parameters\n // prevent type parameter identifiers\n final ListIterator iterator = args.listIterator();\n while (iterator.hasNext()) {\n final String arg = iterator.next();\n if (arg.charAt(0) == 'T')\n iterator.set(OBJECT);\n }\n return args;\n }\n\n /**\n * Resolves the given method signatures to an array of (self-contained) Java type descriptions.\n *\n * @param methodDesc The method description signature (can contain type parameters and generics)\n * @return The types as an array with the method parameter types first and the return type as index {@code array.length - 1}\n */\n private static String[] resolveMethodSignature(final String methodDesc) {\n // if starts with '<' -> resolve type parameters\n return null;\n }\n\n private static Map resolveTypeParameters(final String methodDesc) {\n return null;\n }\n\n private static String getNextType(final char[] buf, final int off) {\n switch(buf[off]) {\n case 'V':\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n case 'F':\n case 'J':\n case 'D':\n return String.valueOf(buf[off]);\n case '[':\n int len = 1;\n while (buf[off + len] == '[') {\n len++;\n }\n return getNextType(buf, off, len);\n case 'L':\n // TODO resolve type variables\n case 'T':\n return getNextType(buf, off, 0);\n default:\n throw new IllegalArgumentException(\"Illegal signature provided: \" + new String(buf));\n }\n }\n\n private static String getNextType(char[] buf, int off, int len) {\n int depth = 0;\n if (buf[off + len] == 'L' || buf[off + len] == 'T')\n while (buf[off + len] != ';' || depth != 0) {\n if (buf[off + len] == '<')\n depth++;\n else if (buf[off + len] == '>')\n depth--;\n len++;\n }\n return new String(buf, off, len + 1);\n }\n}\n"} {"task_id": "Java_795", "language": "Java", "task_type": "for_statement", "source_file": "java/github/sdaschner/jaxrs-analyzer/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java", "mask_start_position": 3362, "mask_end_position": 3516, "canonical_solution": "for (int i = 2; i < types.length; i++) {\n currentMostSpecific = determineMostSpecific(currentMostSpecific, types[i]);\n }", "pre_mask_code": "package com.sebastian_daschner.jaxrs_analyzer.model;\n\nimport com.sebastian_daschner.jaxrs_analyzer.LogProvider;\nimport com.sebastian_daschner.jaxrs_analyzer.analysis.classes.ContextClassReader;\nimport org.objectweb.asm.Type;\nimport org.objectweb.asm.signature.SignatureReader;\nimport org.objectweb.asm.util.TraceSignatureVisitor;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.TypeVariable;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static com.sebastian_daschner.jaxrs_analyzer.model.Types.*;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\n\n/**\n * Contains Java reflection utility functionality.\n *\n * @author Sebastian Daschner\n */\npublic final class JavaUtils {\n\n public static final String INITIALIZER_NAME = \"\";\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Checks if the given method name is a Java initializer.\n *\n * @param name The method name\n * @return {@code true} if name is an initializer\n */\n public static boolean isInitializerName(final String name) {\n return INITIALIZER_NAME.equals(name);\n }\n\n /**\n * Returns the annotation or {@code null} if the element is not annotated with that type.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static A getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass) {\n final Optional annotation = Stream.of(annotatedElement.getAnnotations()).filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();\n return (A) annotation.orElse(null);\n }\n\n /**\n * Checks if the annotation is present on the annotated element.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class annotationClass) {\n return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName()));\n }\n\n /**\n * Determines the type which is most \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the first type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n */\n public static String determineMostSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineMostSpecific(types[0], types[1]);\n default:\n String currentMostSpecific = determineMostSpecific(types[0], types[1]);\n ", "post_mask_code": "\n return currentMostSpecific;\n }\n }\n\n private static String determineMostSpecific(final String firstType, final String secondType) {\n if (OBJECT.equals(secondType) || firstType.equals(secondType)) {\n return firstType;\n }\n if (OBJECT.equals(firstType))\n return secondType;\n final List firstTypeParameters = getTypeParameters(firstType);\n final List secondTypeParameters = getTypeParameters(secondType);\n final boolean firstTypeParameterized = !firstTypeParameters.isEmpty();\n final boolean secondTypeParameterized = !secondTypeParameters.isEmpty();\n if (firstTypeParameterized || secondTypeParameterized) {\n if (firstTypeParameterized && !secondTypeParameterized) {\n return firstType;\n }\n if (!firstTypeParameterized) {\n return secondType;\n }\n if (firstTypeParameters.size() != secondTypeParameters.size())\n // types parameters are not compatible, no statement can be made\n return firstType;\n for (int i = 0; i < firstTypeParameters.size(); i++) {\n final String firstInner = firstTypeParameters.get(i);\n final String secondInner = secondTypeParameters.get(i);\n if (firstInner.equals(secondInner))\n continue;\n // desired to test against identity, i.e. which object was taken by comparison\n if (firstInner == determineMostSpecific(firstInner, secondInner))\n return firstType;\n return secondType;\n }\n }\n final boolean firstTypeArray = firstType.charAt(0) == '[';\n final boolean secondTypeArray = secondType.charAt(0) == '[';\n if (firstTypeArray || secondTypeArray) {\n if (firstTypeArray && !secondTypeArray) {\n return firstType;\n }\n if (!firstTypeArray) {\n return secondType;\n }\n }\n // check if one type is inherited from other\n if (isAssignableTo(firstType, secondType))\n return firstType;\n if (isAssignableTo(secondType, firstType))\n return secondType;\n return firstType;\n }\n\n /**\n * Determines the type which is least \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the second type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n * @see #determineMostSpecificType(String...)\n */\n public static String determineLeastSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineLeastSpecific(types[0], types[1]);\n default:\n String currentLeastSpecific = determineLeastSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentLeastSpecific = determineLeastSpecific(currentLeastSpecific, types[i]);\n }\n return currentLeastSpecific;\n }\n }\n\n private static String determineLeastSpecific(final String firstType, final String secondType) {\n final String mostSpecificType = determineMostSpecificType(firstType, secondType);\n // has to compare identity to see which String object was taken\n if (mostSpecificType == firstType)\n return secondType;\n return firstType;\n }\n\n /**\n * Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type.\n */\n public static boolean isAssignableTo(final String leftType, final String rightType) {\n if (leftType.equals(rightType))\n return true;\n final boolean firstTypeArray = leftType.charAt(0) == '[';\n if (firstTypeArray ^ rightType.charAt(0) == '[') {\n return false;\n }\n final Class leftClass = loadClassFromType(leftType);\n final Class rightClass = loadClassFromType(rightType);\n if (leftClass == null || rightClass == null)\n return false;\n final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);\n return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));\n }\n\n private static boolean hasTypeParameters(final String type) {\n return type.indexOf('<') >= 0;\n }\n\n /**\n * Converts the given JVM object type signature to a class name. Erasures parametrized types.\n *

\n * Example: {@code Ljava/util/List; -> java/util/List}\n *\n * @throws IllegalArgumentException If the type is not a reference or array type.\n */\n public static String toClassName(final String type) {\n switch(type.charAt(0)) {\n case 'V':\n return CLASS_PRIMITIVE_VOID;\n case 'Z':\n return CLASS_PRIMITIVE_BOOLEAN;\n case 'C':\n return CLASS_PRIMITIVE_CHAR;\n case 'B':\n return CLASS_PRIMITIVE_BYTE;\n case 'S':\n return CLASS_PRIMITIVE_SHORT;\n case 'I':\n return CLASS_PRIMITIVE_INT;\n case 'F':\n return CLASS_PRIMITIVE_FLOAT;\n case 'J':\n return CLASS_PRIMITIVE_LONG;\n case 'D':\n return CLASS_PRIMITIVE_DOUBLE;\n case 'L':\n final int typeParamStart = type.indexOf('<');\n final int endIndex = typeParamStart >= 0 ? typeParamStart : type.indexOf(';');\n return type.substring(1, endIndex);\n case '[':\n case '+':\n case '-':\n return toClassName(type.substring(1));\n case 'T':\n // TODO handle type variables\n return CLASS_OBJECT;\n default:\n throw new IllegalArgumentException(\"Not a type signature: \" + type);\n }\n }\n\n /**\n * Converts the given JVM class name to a type signature.\n *

\n * Example: {@code java/util/List -> Ljava/util/List;}\n */\n public static String toType(final String className) {\n return 'L' + className + ';';\n }\n\n /**\n * Converts the given type signature to a human readable type string.\n *

\n * Example: {@code Ljava/util/Map; -> java.util.Map}\n */\n public static String toReadableType(final String type) {\n final SignatureReader reader = new SignatureReader(type);\n final TraceSignatureVisitor visitor = new TraceSignatureVisitor(0);\n reader.acceptType(visitor);\n return visitor.getDeclaration();\n }\n\n /**\n * Returns the JVM type signature of the given object.\n */\n public static String getType(final Object value) {\n return Type.getDescriptor(value.getClass());\n }\n\n /**\n * Returns the type parameters of the given type. Will be an empty list if the type is not parametrized.\n */\n public static List getTypeParameters(final String type) {\n if (type.charAt(0) != 'L')\n return emptyList();\n int lastStart = type.indexOf('<') + 1;\n final List parameters = new ArrayList<>();\n if (lastStart > 0) {\n int depth = 0;\n for (int i = lastStart; i < type.length() - 2; i++) {\n final char c = type.charAt(i);\n if (c == '<')\n depth++;\n else if (c == '>')\n depth--;\n else if (c == ';' && depth == 0) {\n parameters.add(type.substring(lastStart, i + 1));\n lastStart = i + 1;\n }\n }\n }\n return parameters;\n }\n\n /**\n * Returns the return type of the given method signature. Parametrized types are supported.\n */\n public static String getReturnType(final String methodSignature) {\n return getReturnType(methodSignature, null);\n }\n\n public static String getReturnType(final String methodSignature, final String containedType) {\n final String type = methodSignature.substring(methodSignature.lastIndexOf(')') + 1);\n return resolvePotentialTypeVariables(type, containedType);\n }\n\n private static Map getTypeVariables(final String type) {\n if (type == null)\n return emptyMap();\n final Map variables = new HashMap<>();\n final List actualTypeParameters = getTypeParameters(type);\n final Class loadedClass = loadClassFromType(type);\n if (loadedClass == null) {\n LogProvider.debug(\"could not load class for type \" + type);\n return emptyMap();\n }\n final TypeVariable>[] typeParameters = loadedClass.getTypeParameters();\n for (int i = 0; i < actualTypeParameters.size(); i++) {\n variables.put(typeParameters[i].getName(), actualTypeParameters.get(i));\n }\n return variables;\n }\n\n public static Class loadClassFromName(final String className) {\n switch(className) {\n case CLASS_PRIMITIVE_VOID:\n return int.class;\n case CLASS_PRIMITIVE_BOOLEAN:\n return boolean.class;\n case CLASS_PRIMITIVE_CHAR:\n return char.class;\n case CLASS_PRIMITIVE_BYTE:\n return byte.class;\n case CLASS_PRIMITIVE_SHORT:\n return short.class;\n case CLASS_PRIMITIVE_INT:\n return int.class;\n case CLASS_PRIMITIVE_FLOAT:\n return float.class;\n case CLASS_PRIMITIVE_LONG:\n return long.class;\n case CLASS_PRIMITIVE_DOUBLE:\n return double.class;\n }\n // TODO test for variable types\n try {\n return ContextClassReader.getClassLoader().loadClass(className.replace('/', '.'));\n } catch (ClassNotFoundException e) {\n LogProvider.error(\"Could not load class \" + className);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static Class loadClassFromType(final String type) {\n return loadClassFromName(toClassName(type));\n }\n\n public static Method findMethod(final String className, final String methodName, final String signature) {\n final Class loadedClass = loadClassFromName(className);\n if (loadedClass == null)\n return null;\n return findMethod(loadedClass, methodName, signature);\n }\n\n public static Method findMethod(final Class loadedClass, final String methodName, final String signature) {\n final List parameters = getParameters(signature);\n return Stream.of(loadedClass.getDeclaredMethods()).filter(m -> m.getName().equals(methodName) && m.getParameterCount() == parameters.size() && // return types are not taken into account (could be overloaded method w/ different return type)\n Objects.equals(getParameters(getMethodSignature(m)), parameters)).findAny().orElse(null);\n }\n\n public static String getMethodSignature(final String returnType, final String... parameterTypes) {\n final String parameters = Stream.of(parameterTypes).collect(Collectors.joining());\n return '(' + parameters + ')' + returnType;\n }\n\n public static String getMethodSignature(final Method method) {\n try {\n final Field signatureField = method.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n final String signature = (String) signatureField.get(method);\n if (signature != null)\n return signature;\n return Type.getMethodDescriptor(method);\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access method \" + method);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static String getFieldDescriptor(final Field field, final String containedType) {\n try {\n final Field signatureField = field.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n String signature = (String) signatureField.get(field);\n if (signature != null) {\n return resolvePotentialTypeVariables(signature, containedType);\n }\n return Type.getDescriptor(field.getType());\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access field \" + field);\n LogProvider.debug(e);\n return null;\n }\n }\n\n private static String resolvePotentialTypeVariables(final String signature, final String containedType) {\n // resolve type variables immediately\n if (signature.charAt(0) == 'T' || signature.contains(\" typeVariables = getTypeVariables(containedType);\n StringBuilder builder = new StringBuilder(signature);\n boolean startType = true;\n for (int i = 0; i < builder.length(); i++) {\n if (startType && builder.charAt(i) == 'T') {\n final int end = builder.indexOf(\";\", i);\n final String identifier = builder.substring(i + 1, end);\n final String resolvedVariableType = typeVariables.getOrDefault(identifier, OBJECT);\n builder.replace(i, end + 1, resolvedVariableType);\n i = end;\n continue;\n }\n startType = builder.charAt(i) == '<' || builder.charAt(i) == ';';\n }\n return builder.toString();\n }\n return signature;\n }\n\n /**\n * Returns the parameter types of the given method signature. Parametrized types are supported.\n */\n public static List getParameters(final String methodDesc) {\n if (methodDesc == null)\n return emptyList();\n final char[] buffer = methodDesc.toCharArray();\n final List args = new ArrayList<>();\n // TODO resolve type parameters correctly -> information useful? -> maybe use ASM's SignatureReader/Visitor\n int offset = methodDesc.indexOf('(') + 1;\n while (buffer[offset] != ')') {\n final String type = getNextType(buffer, offset);\n args.add(type);\n offset += type.length();\n }\n // TODO change, see type parameters\n // prevent type parameter identifiers\n final ListIterator iterator = args.listIterator();\n while (iterator.hasNext()) {\n final String arg = iterator.next();\n if (arg.charAt(0) == 'T')\n iterator.set(OBJECT);\n }\n return args;\n }\n\n /**\n * Resolves the given method signatures to an array of (self-contained) Java type descriptions.\n *\n * @param methodDesc The method description signature (can contain type parameters and generics)\n * @return The types as an array with the method parameter types first and the return type as index {@code array.length - 1}\n */\n private static String[] resolveMethodSignature(final String methodDesc) {\n // if starts with '<' -> resolve type parameters\n return null;\n }\n\n private static Map resolveTypeParameters(final String methodDesc) {\n return null;\n }\n\n private static String getNextType(final char[] buf, final int off) {\n switch(buf[off]) {\n case 'V':\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n case 'F':\n case 'J':\n case 'D':\n return String.valueOf(buf[off]);\n case '[':\n int len = 1;\n while (buf[off + len] == '[') {\n len++;\n }\n return getNextType(buf, off, len);\n case 'L':\n // TODO resolve type variables\n case 'T':\n return getNextType(buf, off, 0);\n default:\n throw new IllegalArgumentException(\"Illegal signature provided: \" + new String(buf));\n }\n }\n\n private static String getNextType(char[] buf, int off, int len) {\n int depth = 0;\n if (buf[off + len] == 'L' || buf[off + len] == 'T')\n while (buf[off + len] != ';' || depth != 0) {\n if (buf[off + len] == '<')\n depth++;\n else if (buf[off + len] == '>')\n depth--;\n len++;\n }\n return new String(buf, off, len + 1);\n }\n}\n"} {"task_id": "Java_796", "language": "Java", "task_type": "while_statement", "source_file": "java/github/sdaschner/jaxrs-analyzer/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java", "mask_start_position": 20570, "mask_end_position": 20801, "canonical_solution": "while (buf[off + len] != ';' || depth != 0) {\n if (buf[off + len] == '<')\n depth++;\n else if (buf[off + len] == '>')\n depth--;\n len++;\n }", "pre_mask_code": "package com.sebastian_daschner.jaxrs_analyzer.model;\n\nimport com.sebastian_daschner.jaxrs_analyzer.LogProvider;\nimport com.sebastian_daschner.jaxrs_analyzer.analysis.classes.ContextClassReader;\nimport org.objectweb.asm.Type;\nimport org.objectweb.asm.signature.SignatureReader;\nimport org.objectweb.asm.util.TraceSignatureVisitor;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.TypeVariable;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static com.sebastian_daschner.jaxrs_analyzer.model.Types.*;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\n\n/**\n * Contains Java reflection utility functionality.\n *\n * @author Sebastian Daschner\n */\npublic final class JavaUtils {\n\n public static final String INITIALIZER_NAME = \"\";\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Checks if the given method name is a Java initializer.\n *\n * @param name The method name\n * @return {@code true} if name is an initializer\n */\n public static boolean isInitializerName(final String name) {\n return INITIALIZER_NAME.equals(name);\n }\n\n /**\n * Returns the annotation or {@code null} if the element is not annotated with that type.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static A getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass) {\n final Optional annotation = Stream.of(annotatedElement.getAnnotations()).filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();\n return (A) annotation.orElse(null);\n }\n\n /**\n * Checks if the annotation is present on the annotated element.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class annotationClass) {\n return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName()));\n }\n\n /**\n * Determines the type which is most \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the first type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n */\n public static String determineMostSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineMostSpecific(types[0], types[1]);\n default:\n String currentMostSpecific = determineMostSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentMostSpecific = determineMostSpecific(currentMostSpecific, types[i]);\n }\n return currentMostSpecific;\n }\n }\n\n private static String determineMostSpecific(final String firstType, final String secondType) {\n if (OBJECT.equals(secondType) || firstType.equals(secondType)) {\n return firstType;\n }\n if (OBJECT.equals(firstType))\n return secondType;\n final List firstTypeParameters = getTypeParameters(firstType);\n final List secondTypeParameters = getTypeParameters(secondType);\n final boolean firstTypeParameterized = !firstTypeParameters.isEmpty();\n final boolean secondTypeParameterized = !secondTypeParameters.isEmpty();\n if (firstTypeParameterized || secondTypeParameterized) {\n if (firstTypeParameterized && !secondTypeParameterized) {\n return firstType;\n }\n if (!firstTypeParameterized) {\n return secondType;\n }\n if (firstTypeParameters.size() != secondTypeParameters.size())\n // types parameters are not compatible, no statement can be made\n return firstType;\n for (int i = 0; i < firstTypeParameters.size(); i++) {\n final String firstInner = firstTypeParameters.get(i);\n final String secondInner = secondTypeParameters.get(i);\n if (firstInner.equals(secondInner))\n continue;\n // desired to test against identity, i.e. which object was taken by comparison\n if (firstInner == determineMostSpecific(firstInner, secondInner))\n return firstType;\n return secondType;\n }\n }\n final boolean firstTypeArray = firstType.charAt(0) == '[';\n final boolean secondTypeArray = secondType.charAt(0) == '[';\n if (firstTypeArray || secondTypeArray) {\n if (firstTypeArray && !secondTypeArray) {\n return firstType;\n }\n if (!firstTypeArray) {\n return secondType;\n }\n }\n // check if one type is inherited from other\n if (isAssignableTo(firstType, secondType))\n return firstType;\n if (isAssignableTo(secondType, firstType))\n return secondType;\n return firstType;\n }\n\n /**\n * Determines the type which is least \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the second type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n * @see #determineMostSpecificType(String...)\n */\n public static String determineLeastSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineLeastSpecific(types[0], types[1]);\n default:\n String currentLeastSpecific = determineLeastSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentLeastSpecific = determineLeastSpecific(currentLeastSpecific, types[i]);\n }\n return currentLeastSpecific;\n }\n }\n\n private static String determineLeastSpecific(final String firstType, final String secondType) {\n final String mostSpecificType = determineMostSpecificType(firstType, secondType);\n // has to compare identity to see which String object was taken\n if (mostSpecificType == firstType)\n return secondType;\n return firstType;\n }\n\n /**\n * Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type.\n */\n public static boolean isAssignableTo(final String leftType, final String rightType) {\n if (leftType.equals(rightType))\n return true;\n final boolean firstTypeArray = leftType.charAt(0) == '[';\n if (firstTypeArray ^ rightType.charAt(0) == '[') {\n return false;\n }\n final Class leftClass = loadClassFromType(leftType);\n final Class rightClass = loadClassFromType(rightType);\n if (leftClass == null || rightClass == null)\n return false;\n final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);\n return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));\n }\n\n private static boolean hasTypeParameters(final String type) {\n return type.indexOf('<') >= 0;\n }\n\n /**\n * Converts the given JVM object type signature to a class name. Erasures parametrized types.\n *

\n * Example: {@code Ljava/util/List; -> java/util/List}\n *\n * @throws IllegalArgumentException If the type is not a reference or array type.\n */\n public static String toClassName(final String type) {\n switch(type.charAt(0)) {\n case 'V':\n return CLASS_PRIMITIVE_VOID;\n case 'Z':\n return CLASS_PRIMITIVE_BOOLEAN;\n case 'C':\n return CLASS_PRIMITIVE_CHAR;\n case 'B':\n return CLASS_PRIMITIVE_BYTE;\n case 'S':\n return CLASS_PRIMITIVE_SHORT;\n case 'I':\n return CLASS_PRIMITIVE_INT;\n case 'F':\n return CLASS_PRIMITIVE_FLOAT;\n case 'J':\n return CLASS_PRIMITIVE_LONG;\n case 'D':\n return CLASS_PRIMITIVE_DOUBLE;\n case 'L':\n final int typeParamStart = type.indexOf('<');\n final int endIndex = typeParamStart >= 0 ? typeParamStart : type.indexOf(';');\n return type.substring(1, endIndex);\n case '[':\n case '+':\n case '-':\n return toClassName(type.substring(1));\n case 'T':\n // TODO handle type variables\n return CLASS_OBJECT;\n default:\n throw new IllegalArgumentException(\"Not a type signature: \" + type);\n }\n }\n\n /**\n * Converts the given JVM class name to a type signature.\n *

\n * Example: {@code java/util/List -> Ljava/util/List;}\n */\n public static String toType(final String className) {\n return 'L' + className + ';';\n }\n\n /**\n * Converts the given type signature to a human readable type string.\n *

\n * Example: {@code Ljava/util/Map; -> java.util.Map}\n */\n public static String toReadableType(final String type) {\n final SignatureReader reader = new SignatureReader(type);\n final TraceSignatureVisitor visitor = new TraceSignatureVisitor(0);\n reader.acceptType(visitor);\n return visitor.getDeclaration();\n }\n\n /**\n * Returns the JVM type signature of the given object.\n */\n public static String getType(final Object value) {\n return Type.getDescriptor(value.getClass());\n }\n\n /**\n * Returns the type parameters of the given type. Will be an empty list if the type is not parametrized.\n */\n public static List getTypeParameters(final String type) {\n if (type.charAt(0) != 'L')\n return emptyList();\n int lastStart = type.indexOf('<') + 1;\n final List parameters = new ArrayList<>();\n if (lastStart > 0) {\n int depth = 0;\n for (int i = lastStart; i < type.length() - 2; i++) {\n final char c = type.charAt(i);\n if (c == '<')\n depth++;\n else if (c == '>')\n depth--;\n else if (c == ';' && depth == 0) {\n parameters.add(type.substring(lastStart, i + 1));\n lastStart = i + 1;\n }\n }\n }\n return parameters;\n }\n\n /**\n * Returns the return type of the given method signature. Parametrized types are supported.\n */\n public static String getReturnType(final String methodSignature) {\n return getReturnType(methodSignature, null);\n }\n\n public static String getReturnType(final String methodSignature, final String containedType) {\n final String type = methodSignature.substring(methodSignature.lastIndexOf(')') + 1);\n return resolvePotentialTypeVariables(type, containedType);\n }\n\n private static Map getTypeVariables(final String type) {\n if (type == null)\n return emptyMap();\n final Map variables = new HashMap<>();\n final List actualTypeParameters = getTypeParameters(type);\n final Class loadedClass = loadClassFromType(type);\n if (loadedClass == null) {\n LogProvider.debug(\"could not load class for type \" + type);\n return emptyMap();\n }\n final TypeVariable>[] typeParameters = loadedClass.getTypeParameters();\n for (int i = 0; i < actualTypeParameters.size(); i++) {\n variables.put(typeParameters[i].getName(), actualTypeParameters.get(i));\n }\n return variables;\n }\n\n public static Class loadClassFromName(final String className) {\n switch(className) {\n case CLASS_PRIMITIVE_VOID:\n return int.class;\n case CLASS_PRIMITIVE_BOOLEAN:\n return boolean.class;\n case CLASS_PRIMITIVE_CHAR:\n return char.class;\n case CLASS_PRIMITIVE_BYTE:\n return byte.class;\n case CLASS_PRIMITIVE_SHORT:\n return short.class;\n case CLASS_PRIMITIVE_INT:\n return int.class;\n case CLASS_PRIMITIVE_FLOAT:\n return float.class;\n case CLASS_PRIMITIVE_LONG:\n return long.class;\n case CLASS_PRIMITIVE_DOUBLE:\n return double.class;\n }\n // TODO test for variable types\n try {\n return ContextClassReader.getClassLoader().loadClass(className.replace('/', '.'));\n } catch (ClassNotFoundException e) {\n LogProvider.error(\"Could not load class \" + className);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static Class loadClassFromType(final String type) {\n return loadClassFromName(toClassName(type));\n }\n\n public static Method findMethod(final String className, final String methodName, final String signature) {\n final Class loadedClass = loadClassFromName(className);\n if (loadedClass == null)\n return null;\n return findMethod(loadedClass, methodName, signature);\n }\n\n public static Method findMethod(final Class loadedClass, final String methodName, final String signature) {\n final List parameters = getParameters(signature);\n return Stream.of(loadedClass.getDeclaredMethods()).filter(m -> m.getName().equals(methodName) && m.getParameterCount() == parameters.size() && // return types are not taken into account (could be overloaded method w/ different return type)\n Objects.equals(getParameters(getMethodSignature(m)), parameters)).findAny().orElse(null);\n }\n\n public static String getMethodSignature(final String returnType, final String... parameterTypes) {\n final String parameters = Stream.of(parameterTypes).collect(Collectors.joining());\n return '(' + parameters + ')' + returnType;\n }\n\n public static String getMethodSignature(final Method method) {\n try {\n final Field signatureField = method.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n final String signature = (String) signatureField.get(method);\n if (signature != null)\n return signature;\n return Type.getMethodDescriptor(method);\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access method \" + method);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static String getFieldDescriptor(final Field field, final String containedType) {\n try {\n final Field signatureField = field.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n String signature = (String) signatureField.get(field);\n if (signature != null) {\n return resolvePotentialTypeVariables(signature, containedType);\n }\n return Type.getDescriptor(field.getType());\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access field \" + field);\n LogProvider.debug(e);\n return null;\n }\n }\n\n private static String resolvePotentialTypeVariables(final String signature, final String containedType) {\n // resolve type variables immediately\n if (signature.charAt(0) == 'T' || signature.contains(\" typeVariables = getTypeVariables(containedType);\n StringBuilder builder = new StringBuilder(signature);\n boolean startType = true;\n for (int i = 0; i < builder.length(); i++) {\n if (startType && builder.charAt(i) == 'T') {\n final int end = builder.indexOf(\";\", i);\n final String identifier = builder.substring(i + 1, end);\n final String resolvedVariableType = typeVariables.getOrDefault(identifier, OBJECT);\n builder.replace(i, end + 1, resolvedVariableType);\n i = end;\n continue;\n }\n startType = builder.charAt(i) == '<' || builder.charAt(i) == ';';\n }\n return builder.toString();\n }\n return signature;\n }\n\n /**\n * Returns the parameter types of the given method signature. Parametrized types are supported.\n */\n public static List getParameters(final String methodDesc) {\n if (methodDesc == null)\n return emptyList();\n final char[] buffer = methodDesc.toCharArray();\n final List args = new ArrayList<>();\n // TODO resolve type parameters correctly -> information useful? -> maybe use ASM's SignatureReader/Visitor\n int offset = methodDesc.indexOf('(') + 1;\n while (buffer[offset] != ')') {\n final String type = getNextType(buffer, offset);\n args.add(type);\n offset += type.length();\n }\n // TODO change, see type parameters\n // prevent type parameter identifiers\n final ListIterator iterator = args.listIterator();\n while (iterator.hasNext()) {\n final String arg = iterator.next();\n if (arg.charAt(0) == 'T')\n iterator.set(OBJECT);\n }\n return args;\n }\n\n /**\n * Resolves the given method signatures to an array of (self-contained) Java type descriptions.\n *\n * @param methodDesc The method description signature (can contain type parameters and generics)\n * @return The types as an array with the method parameter types first and the return type as index {@code array.length - 1}\n */\n private static String[] resolveMethodSignature(final String methodDesc) {\n // if starts with '<' -> resolve type parameters\n return null;\n }\n\n private static Map resolveTypeParameters(final String methodDesc) {\n return null;\n }\n\n private static String getNextType(final char[] buf, final int off) {\n switch(buf[off]) {\n case 'V':\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n case 'F':\n case 'J':\n case 'D':\n return String.valueOf(buf[off]);\n case '[':\n int len = 1;\n while (buf[off + len] == '[') {\n len++;\n }\n return getNextType(buf, off, len);\n case 'L':\n // TODO resolve type variables\n case 'T':\n return getNextType(buf, off, 0);\n default:\n throw new IllegalArgumentException(\"Illegal signature provided: \" + new String(buf));\n }\n }\n\n private static String getNextType(char[] buf, int off, int len) {\n int depth = 0;\n if (buf[off + len] == 'L' || buf[off + len] == 'T')\n ", "post_mask_code": "\n return new String(buf, off, len + 1);\n }\n}\n"} {"task_id": "Java_797", "language": "Java", "task_type": "try_statement", "source_file": "java/github/sdaschner/jaxrs-analyzer/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java", "mask_start_position": 13902, "mask_end_position": 14184, "canonical_solution": "try {\n return ContextClassReader.getClassLoader().loadClass(className.replace('/', '.'));\n } catch (ClassNotFoundException e) {\n LogProvider.error(\"Could not load class \" + className);\n LogProvider.debug(e);\n return null;\n }", "pre_mask_code": "package com.sebastian_daschner.jaxrs_analyzer.model;\n\nimport com.sebastian_daschner.jaxrs_analyzer.LogProvider;\nimport com.sebastian_daschner.jaxrs_analyzer.analysis.classes.ContextClassReader;\nimport org.objectweb.asm.Type;\nimport org.objectweb.asm.signature.SignatureReader;\nimport org.objectweb.asm.util.TraceSignatureVisitor;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.TypeVariable;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static com.sebastian_daschner.jaxrs_analyzer.model.Types.*;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\n\n/**\n * Contains Java reflection utility functionality.\n *\n * @author Sebastian Daschner\n */\npublic final class JavaUtils {\n\n public static final String INITIALIZER_NAME = \"\";\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Checks if the given method name is a Java initializer.\n *\n * @param name The method name\n * @return {@code true} if name is an initializer\n */\n public static boolean isInitializerName(final String name) {\n return INITIALIZER_NAME.equals(name);\n }\n\n /**\n * Returns the annotation or {@code null} if the element is not annotated with that type.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static A getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass) {\n final Optional annotation = Stream.of(annotatedElement.getAnnotations()).filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();\n return (A) annotation.orElse(null);\n }\n\n /**\n * Checks if the annotation is present on the annotated element.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class annotationClass) {\n return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName()));\n }\n\n /**\n * Determines the type which is most \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the first type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n */\n public static String determineMostSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineMostSpecific(types[0], types[1]);\n default:\n String currentMostSpecific = determineMostSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentMostSpecific = determineMostSpecific(currentMostSpecific, types[i]);\n }\n return currentMostSpecific;\n }\n }\n\n private static String determineMostSpecific(final String firstType, final String secondType) {\n if (OBJECT.equals(secondType) || firstType.equals(secondType)) {\n return firstType;\n }\n if (OBJECT.equals(firstType))\n return secondType;\n final List firstTypeParameters = getTypeParameters(firstType);\n final List secondTypeParameters = getTypeParameters(secondType);\n final boolean firstTypeParameterized = !firstTypeParameters.isEmpty();\n final boolean secondTypeParameterized = !secondTypeParameters.isEmpty();\n if (firstTypeParameterized || secondTypeParameterized) {\n if (firstTypeParameterized && !secondTypeParameterized) {\n return firstType;\n }\n if (!firstTypeParameterized) {\n return secondType;\n }\n if (firstTypeParameters.size() != secondTypeParameters.size())\n // types parameters are not compatible, no statement can be made\n return firstType;\n for (int i = 0; i < firstTypeParameters.size(); i++) {\n final String firstInner = firstTypeParameters.get(i);\n final String secondInner = secondTypeParameters.get(i);\n if (firstInner.equals(secondInner))\n continue;\n // desired to test against identity, i.e. which object was taken by comparison\n if (firstInner == determineMostSpecific(firstInner, secondInner))\n return firstType;\n return secondType;\n }\n }\n final boolean firstTypeArray = firstType.charAt(0) == '[';\n final boolean secondTypeArray = secondType.charAt(0) == '[';\n if (firstTypeArray || secondTypeArray) {\n if (firstTypeArray && !secondTypeArray) {\n return firstType;\n }\n if (!firstTypeArray) {\n return secondType;\n }\n }\n // check if one type is inherited from other\n if (isAssignableTo(firstType, secondType))\n return firstType;\n if (isAssignableTo(secondType, firstType))\n return secondType;\n return firstType;\n }\n\n /**\n * Determines the type which is least \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the second type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n * @see #determineMostSpecificType(String...)\n */\n public static String determineLeastSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineLeastSpecific(types[0], types[1]);\n default:\n String currentLeastSpecific = determineLeastSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentLeastSpecific = determineLeastSpecific(currentLeastSpecific, types[i]);\n }\n return currentLeastSpecific;\n }\n }\n\n private static String determineLeastSpecific(final String firstType, final String secondType) {\n final String mostSpecificType = determineMostSpecificType(firstType, secondType);\n // has to compare identity to see which String object was taken\n if (mostSpecificType == firstType)\n return secondType;\n return firstType;\n }\n\n /**\n * Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type.\n */\n public static boolean isAssignableTo(final String leftType, final String rightType) {\n if (leftType.equals(rightType))\n return true;\n final boolean firstTypeArray = leftType.charAt(0) == '[';\n if (firstTypeArray ^ rightType.charAt(0) == '[') {\n return false;\n }\n final Class leftClass = loadClassFromType(leftType);\n final Class rightClass = loadClassFromType(rightType);\n if (leftClass == null || rightClass == null)\n return false;\n final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);\n return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));\n }\n\n private static boolean hasTypeParameters(final String type) {\n return type.indexOf('<') >= 0;\n }\n\n /**\n * Converts the given JVM object type signature to a class name. Erasures parametrized types.\n *

\n * Example: {@code Ljava/util/List; -> java/util/List}\n *\n * @throws IllegalArgumentException If the type is not a reference or array type.\n */\n public static String toClassName(final String type) {\n switch(type.charAt(0)) {\n case 'V':\n return CLASS_PRIMITIVE_VOID;\n case 'Z':\n return CLASS_PRIMITIVE_BOOLEAN;\n case 'C':\n return CLASS_PRIMITIVE_CHAR;\n case 'B':\n return CLASS_PRIMITIVE_BYTE;\n case 'S':\n return CLASS_PRIMITIVE_SHORT;\n case 'I':\n return CLASS_PRIMITIVE_INT;\n case 'F':\n return CLASS_PRIMITIVE_FLOAT;\n case 'J':\n return CLASS_PRIMITIVE_LONG;\n case 'D':\n return CLASS_PRIMITIVE_DOUBLE;\n case 'L':\n final int typeParamStart = type.indexOf('<');\n final int endIndex = typeParamStart >= 0 ? typeParamStart : type.indexOf(';');\n return type.substring(1, endIndex);\n case '[':\n case '+':\n case '-':\n return toClassName(type.substring(1));\n case 'T':\n // TODO handle type variables\n return CLASS_OBJECT;\n default:\n throw new IllegalArgumentException(\"Not a type signature: \" + type);\n }\n }\n\n /**\n * Converts the given JVM class name to a type signature.\n *

\n * Example: {@code java/util/List -> Ljava/util/List;}\n */\n public static String toType(final String className) {\n return 'L' + className + ';';\n }\n\n /**\n * Converts the given type signature to a human readable type string.\n *

\n * Example: {@code Ljava/util/Map; -> java.util.Map}\n */\n public static String toReadableType(final String type) {\n final SignatureReader reader = new SignatureReader(type);\n final TraceSignatureVisitor visitor = new TraceSignatureVisitor(0);\n reader.acceptType(visitor);\n return visitor.getDeclaration();\n }\n\n /**\n * Returns the JVM type signature of the given object.\n */\n public static String getType(final Object value) {\n return Type.getDescriptor(value.getClass());\n }\n\n /**\n * Returns the type parameters of the given type. Will be an empty list if the type is not parametrized.\n */\n public static List getTypeParameters(final String type) {\n if (type.charAt(0) != 'L')\n return emptyList();\n int lastStart = type.indexOf('<') + 1;\n final List parameters = new ArrayList<>();\n if (lastStart > 0) {\n int depth = 0;\n for (int i = lastStart; i < type.length() - 2; i++) {\n final char c = type.charAt(i);\n if (c == '<')\n depth++;\n else if (c == '>')\n depth--;\n else if (c == ';' && depth == 0) {\n parameters.add(type.substring(lastStart, i + 1));\n lastStart = i + 1;\n }\n }\n }\n return parameters;\n }\n\n /**\n * Returns the return type of the given method signature. Parametrized types are supported.\n */\n public static String getReturnType(final String methodSignature) {\n return getReturnType(methodSignature, null);\n }\n\n public static String getReturnType(final String methodSignature, final String containedType) {\n final String type = methodSignature.substring(methodSignature.lastIndexOf(')') + 1);\n return resolvePotentialTypeVariables(type, containedType);\n }\n\n private static Map getTypeVariables(final String type) {\n if (type == null)\n return emptyMap();\n final Map variables = new HashMap<>();\n final List actualTypeParameters = getTypeParameters(type);\n final Class loadedClass = loadClassFromType(type);\n if (loadedClass == null) {\n LogProvider.debug(\"could not load class for type \" + type);\n return emptyMap();\n }\n final TypeVariable>[] typeParameters = loadedClass.getTypeParameters();\n for (int i = 0; i < actualTypeParameters.size(); i++) {\n variables.put(typeParameters[i].getName(), actualTypeParameters.get(i));\n }\n return variables;\n }\n\n public static Class loadClassFromName(final String className) {\n switch(className) {\n case CLASS_PRIMITIVE_VOID:\n return int.class;\n case CLASS_PRIMITIVE_BOOLEAN:\n return boolean.class;\n case CLASS_PRIMITIVE_CHAR:\n return char.class;\n case CLASS_PRIMITIVE_BYTE:\n return byte.class;\n case CLASS_PRIMITIVE_SHORT:\n return short.class;\n case CLASS_PRIMITIVE_INT:\n return int.class;\n case CLASS_PRIMITIVE_FLOAT:\n return float.class;\n case CLASS_PRIMITIVE_LONG:\n return long.class;\n case CLASS_PRIMITIVE_DOUBLE:\n return double.class;\n }\n // TODO test for variable types\n ", "post_mask_code": "\n }\n\n public static Class loadClassFromType(final String type) {\n return loadClassFromName(toClassName(type));\n }\n\n public static Method findMethod(final String className, final String methodName, final String signature) {\n final Class loadedClass = loadClassFromName(className);\n if (loadedClass == null)\n return null;\n return findMethod(loadedClass, methodName, signature);\n }\n\n public static Method findMethod(final Class loadedClass, final String methodName, final String signature) {\n final List parameters = getParameters(signature);\n return Stream.of(loadedClass.getDeclaredMethods()).filter(m -> m.getName().equals(methodName) && m.getParameterCount() == parameters.size() && // return types are not taken into account (could be overloaded method w/ different return type)\n Objects.equals(getParameters(getMethodSignature(m)), parameters)).findAny().orElse(null);\n }\n\n public static String getMethodSignature(final String returnType, final String... parameterTypes) {\n final String parameters = Stream.of(parameterTypes).collect(Collectors.joining());\n return '(' + parameters + ')' + returnType;\n }\n\n public static String getMethodSignature(final Method method) {\n try {\n final Field signatureField = method.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n final String signature = (String) signatureField.get(method);\n if (signature != null)\n return signature;\n return Type.getMethodDescriptor(method);\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access method \" + method);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static String getFieldDescriptor(final Field field, final String containedType) {\n try {\n final Field signatureField = field.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n String signature = (String) signatureField.get(field);\n if (signature != null) {\n return resolvePotentialTypeVariables(signature, containedType);\n }\n return Type.getDescriptor(field.getType());\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access field \" + field);\n LogProvider.debug(e);\n return null;\n }\n }\n\n private static String resolvePotentialTypeVariables(final String signature, final String containedType) {\n // resolve type variables immediately\n if (signature.charAt(0) == 'T' || signature.contains(\" typeVariables = getTypeVariables(containedType);\n StringBuilder builder = new StringBuilder(signature);\n boolean startType = true;\n for (int i = 0; i < builder.length(); i++) {\n if (startType && builder.charAt(i) == 'T') {\n final int end = builder.indexOf(\";\", i);\n final String identifier = builder.substring(i + 1, end);\n final String resolvedVariableType = typeVariables.getOrDefault(identifier, OBJECT);\n builder.replace(i, end + 1, resolvedVariableType);\n i = end;\n continue;\n }\n startType = builder.charAt(i) == '<' || builder.charAt(i) == ';';\n }\n return builder.toString();\n }\n return signature;\n }\n\n /**\n * Returns the parameter types of the given method signature. Parametrized types are supported.\n */\n public static List getParameters(final String methodDesc) {\n if (methodDesc == null)\n return emptyList();\n final char[] buffer = methodDesc.toCharArray();\n final List args = new ArrayList<>();\n // TODO resolve type parameters correctly -> information useful? -> maybe use ASM's SignatureReader/Visitor\n int offset = methodDesc.indexOf('(') + 1;\n while (buffer[offset] != ')') {\n final String type = getNextType(buffer, offset);\n args.add(type);\n offset += type.length();\n }\n // TODO change, see type parameters\n // prevent type parameter identifiers\n final ListIterator iterator = args.listIterator();\n while (iterator.hasNext()) {\n final String arg = iterator.next();\n if (arg.charAt(0) == 'T')\n iterator.set(OBJECT);\n }\n return args;\n }\n\n /**\n * Resolves the given method signatures to an array of (self-contained) Java type descriptions.\n *\n * @param methodDesc The method description signature (can contain type parameters and generics)\n * @return The types as an array with the method parameter types first and the return type as index {@code array.length - 1}\n */\n private static String[] resolveMethodSignature(final String methodDesc) {\n // if starts with '<' -> resolve type parameters\n return null;\n }\n\n private static Map resolveTypeParameters(final String methodDesc) {\n return null;\n }\n\n private static String getNextType(final char[] buf, final int off) {\n switch(buf[off]) {\n case 'V':\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n case 'F':\n case 'J':\n case 'D':\n return String.valueOf(buf[off]);\n case '[':\n int len = 1;\n while (buf[off + len] == '[') {\n len++;\n }\n return getNextType(buf, off, len);\n case 'L':\n // TODO resolve type variables\n case 'T':\n return getNextType(buf, off, 0);\n default:\n throw new IllegalArgumentException(\"Illegal signature provided: \" + new String(buf));\n }\n }\n\n private static String getNextType(char[] buf, int off, int len) {\n int depth = 0;\n if (buf[off + len] == 'L' || buf[off + len] == 'T')\n while (buf[off + len] != ';' || depth != 0) {\n if (buf[off + len] == '<')\n depth++;\n else if (buf[off + len] == '>')\n depth--;\n len++;\n }\n return new String(buf, off, len + 1);\n }\n}\n"} {"task_id": "Java_798", "language": "Java", "task_type": "empty", "source_file": "java/github/sdaschner/jaxrs-analyzer/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java", "mask_start_position": 17223, "mask_end_position": 17223, "canonical_solution": "", "pre_mask_code": "package com.sebastian_daschner.jaxrs_analyzer.model;\n\nimport com.sebastian_daschner.jaxrs_analyzer.LogProvider;\nimport com.sebastian_daschner.jaxrs_analyzer.analysis.classes.ContextClassReader;\nimport org.objectweb.asm.Type;\nimport org.objectweb.asm.signature.SignatureReader;\nimport org.objectweb.asm.util.TraceSignatureVisitor;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.TypeVariable;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static com.sebastian_daschner.jaxrs_analyzer.model.Types.*;\nimport static java.util.Collections.emptyList;\nimport static java.util.Collections.emptyMap;\n\n/**\n * Contains Java reflection utility functionality.\n *\n * @author Sebastian Daschner\n */\npublic final class JavaUtils {\n\n public static final String INITIALIZER_NAME = \"\";\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Checks if the given method name is a Java initializer.\n *\n * @param name The method name\n * @return {@code true} if name is an initializer\n */\n public static boolean isInitializerName(final String name) {\n return INITIALIZER_NAME.equals(name);\n }\n\n /**\n * Returns the annotation or {@code null} if the element is not annotated with that type.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static A getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass) {\n final Optional annotation = Stream.of(annotatedElement.getAnnotations()).filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();\n return (A) annotation.orElse(null);\n }\n\n /**\n * Checks if the annotation is present on the annotated element.\n * Note: This step is necessary due to issues with external class loaders (e.g. Maven).\n * The classes may not be identical and are therefore compared by FQ class name.\n */\n public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement, final Class annotationClass) {\n return Stream.of(annotatedElement.getAnnotations()).map(Annotation::annotationType).map(Class::getName).anyMatch(n -> n.equals(annotationClass.getName()));\n }\n\n /**\n * Determines the type which is most \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the first type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n */\n public static String determineMostSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineMostSpecific(types[0], types[1]);\n default:\n String currentMostSpecific = determineMostSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentMostSpecific = determineMostSpecific(currentMostSpecific, types[i]);\n }\n return currentMostSpecific;\n }\n }\n\n private static String determineMostSpecific(final String firstType, final String secondType) {\n if (OBJECT.equals(secondType) || firstType.equals(secondType)) {\n return firstType;\n }\n if (OBJECT.equals(firstType))\n return secondType;\n final List firstTypeParameters = getTypeParameters(firstType);\n final List secondTypeParameters = getTypeParameters(secondType);\n final boolean firstTypeParameterized = !firstTypeParameters.isEmpty();\n final boolean secondTypeParameterized = !secondTypeParameters.isEmpty();\n if (firstTypeParameterized || secondTypeParameterized) {\n if (firstTypeParameterized && !secondTypeParameterized) {\n return firstType;\n }\n if (!firstTypeParameterized) {\n return secondType;\n }\n if (firstTypeParameters.size() != secondTypeParameters.size())\n // types parameters are not compatible, no statement can be made\n return firstType;\n for (int i = 0; i < firstTypeParameters.size(); i++) {\n final String firstInner = firstTypeParameters.get(i);\n final String secondInner = secondTypeParameters.get(i);\n if (firstInner.equals(secondInner))\n continue;\n // desired to test against identity, i.e. which object was taken by comparison\n if (firstInner == determineMostSpecific(firstInner, secondInner))\n return firstType;\n return secondType;\n }\n }\n final boolean firstTypeArray = firstType.charAt(0) == '[';\n final boolean secondTypeArray = secondType.charAt(0) == '[';\n if (firstTypeArray || secondTypeArray) {\n if (firstTypeArray && !secondTypeArray) {\n return firstType;\n }\n if (!firstTypeArray) {\n return secondType;\n }\n }\n // check if one type is inherited from other\n if (isAssignableTo(firstType, secondType))\n return firstType;\n if (isAssignableTo(secondType, firstType))\n return secondType;\n return firstType;\n }\n\n /**\n * Determines the type which is least \"specific\" (i. e. parametrized types are more \"specific\" than generic types,\n * types which are not {@link Object} are less specific). If no exact statement can be made, the second type is chosen.\n *\n * @param types The types\n * @return The most \"specific\" type\n * @see #determineMostSpecificType(String...)\n */\n public static String determineLeastSpecificType(final String... types) {\n switch(types.length) {\n case 0:\n throw new IllegalArgumentException(\"At least one type has to be provided\");\n case 1:\n return types[0];\n case 2:\n return determineLeastSpecific(types[0], types[1]);\n default:\n String currentLeastSpecific = determineLeastSpecific(types[0], types[1]);\n for (int i = 2; i < types.length; i++) {\n currentLeastSpecific = determineLeastSpecific(currentLeastSpecific, types[i]);\n }\n return currentLeastSpecific;\n }\n }\n\n private static String determineLeastSpecific(final String firstType, final String secondType) {\n final String mostSpecificType = determineMostSpecificType(firstType, secondType);\n // has to compare identity to see which String object was taken\n if (mostSpecificType == firstType)\n return secondType;\n return firstType;\n }\n\n /**\n * Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type.\n */\n public static boolean isAssignableTo(final String leftType, final String rightType) {\n if (leftType.equals(rightType))\n return true;\n final boolean firstTypeArray = leftType.charAt(0) == '[';\n if (firstTypeArray ^ rightType.charAt(0) == '[') {\n return false;\n }\n final Class leftClass = loadClassFromType(leftType);\n final Class rightClass = loadClassFromType(rightType);\n if (leftClass == null || rightClass == null)\n return false;\n final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);\n return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));\n }\n\n private static boolean hasTypeParameters(final String type) {\n return type.indexOf('<') >= 0;\n }\n\n /**\n * Converts the given JVM object type signature to a class name. Erasures parametrized types.\n *

\n * Example: {@code Ljava/util/List; -> java/util/List}\n *\n * @throws IllegalArgumentException If the type is not a reference or array type.\n */\n public static String toClassName(final String type) {\n switch(type.charAt(0)) {\n case 'V':\n return CLASS_PRIMITIVE_VOID;\n case 'Z':\n return CLASS_PRIMITIVE_BOOLEAN;\n case 'C':\n return CLASS_PRIMITIVE_CHAR;\n case 'B':\n return CLASS_PRIMITIVE_BYTE;\n case 'S':\n return CLASS_PRIMITIVE_SHORT;\n case 'I':\n return CLASS_PRIMITIVE_INT;\n case 'F':\n return CLASS_PRIMITIVE_FLOAT;\n case 'J':\n return CLASS_PRIMITIVE_LONG;\n case 'D':\n return CLASS_PRIMITIVE_DOUBLE;\n case 'L':\n final int typeParamStart = type.indexOf('<');\n final int endIndex = typeParamStart >= 0 ? typeParamStart : type.indexOf(';');\n return type.substring(1, endIndex);\n case '[':\n case '+':\n case '-':\n return toClassName(type.substring(1));\n case 'T':\n // TODO handle type variables\n return CLASS_OBJECT;\n default:\n throw new IllegalArgumentException(\"Not a type signature: \" + type);\n }\n }\n\n /**\n * Converts the given JVM class name to a type signature.\n *

\n * Example: {@code java/util/List -> Ljava/util/List;}\n */\n public static String toType(final String className) {\n return 'L' + className + ';';\n }\n\n /**\n * Converts the given type signature to a human readable type string.\n *

\n * Example: {@code Ljava/util/Map; -> java.util.Map}\n */\n public static String toReadableType(final String type) {\n final SignatureReader reader = new SignatureReader(type);\n final TraceSignatureVisitor visitor = new TraceSignatureVisitor(0);\n reader.acceptType(visitor);\n return visitor.getDeclaration();\n }\n\n /**\n * Returns the JVM type signature of the given object.\n */\n public static String getType(final Object value) {\n return Type.getDescriptor(value.getClass());\n }\n\n /**\n * Returns the type parameters of the given type. Will be an empty list if the type is not parametrized.\n */\n public static List getTypeParameters(final String type) {\n if (type.charAt(0) != 'L')\n return emptyList();\n int lastStart = type.indexOf('<') + 1;\n final List parameters = new ArrayList<>();\n if (lastStart > 0) {\n int depth = 0;\n for (int i = lastStart; i < type.length() - 2; i++) {\n final char c = type.charAt(i);\n if (c == '<')\n depth++;\n else if (c == '>')\n depth--;\n else if (c == ';' && depth == 0) {\n parameters.add(type.substring(lastStart, i + 1));\n lastStart = i + 1;\n }\n }\n }\n return parameters;\n }\n\n /**\n * Returns the return type of the given method signature. Parametrized types are supported.\n */\n public static String getReturnType(final String methodSignature) {\n return getReturnType(methodSignature, null);\n }\n\n public static String getReturnType(final String methodSignature, final String containedType) {\n final String type = methodSignature.substring(methodSignature.lastIndexOf(')') + 1);\n return resolvePotentialTypeVariables(type, containedType);\n }\n\n private static Map getTypeVariables(final String type) {\n if (type == null)\n return emptyMap();\n final Map variables = new HashMap<>();\n final List actualTypeParameters = getTypeParameters(type);\n final Class loadedClass = loadClassFromType(type);\n if (loadedClass == null) {\n LogProvider.debug(\"could not load class for type \" + type);\n return emptyMap();\n }\n final TypeVariable>[] typeParameters = loadedClass.getTypeParameters();\n for (int i = 0; i < actualTypeParameters.size(); i++) {\n variables.put(typeParameters[i].getName(), actualTypeParameters.get(i));\n }\n return variables;\n }\n\n public static Class loadClassFromName(final String className) {\n switch(className) {\n case CLASS_PRIMITIVE_VOID:\n return int.class;\n case CLASS_PRIMITIVE_BOOLEAN:\n return boolean.class;\n case CLASS_PRIMITIVE_CHAR:\n return char.class;\n case CLASS_PRIMITIVE_BYTE:\n return byte.class;\n case CLASS_PRIMITIVE_SHORT:\n return short.class;\n case CLASS_PRIMITIVE_INT:\n return int.class;\n case CLASS_PRIMITIVE_FLOAT:\n return float.class;\n case CLASS_PRIMITIVE_LONG:\n return long.class;\n case CLASS_PRIMITIVE_DOUBLE:\n return double.class;\n }\n // TODO test for variable types\n try {\n return ContextClassReader.getClassLoader().loadClass(className.replace('/', '.'));\n } catch (ClassNotFoundException e) {\n LogProvider.error(\"Could not load class \" + className);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static Class loadClassFromType(final String type) {\n return loadClassFromName(toClassName(type));\n }\n\n public static Method findMethod(final String className, final String methodName, final String signature) {\n final Class loadedClass = loadClassFromName(className);\n if (loadedClass == null)\n return null;\n return findMethod(loadedClass, methodName, signature);\n }\n\n public static Method findMethod(final Class loadedClass, final String methodName, final String signature) {\n final List parameters = getParameters(signature);\n return Stream.of(loadedClass.getDeclaredMethods()).filter(m -> m.getName().equals(methodName) && m.getParameterCount() == parameters.size() && // return types are not taken into account (could be overloaded method w/ different return type)\n Objects.equals(getParameters(getMethodSignature(m)), parameters)).findAny().orElse(null);\n }\n\n public static String getMethodSignature(final String returnType, final String... parameterTypes) {\n final String parameters = Stream.of(parameterTypes).collect(Collectors.joining());\n return '(' + parameters + ')' + returnType;\n }\n\n public static String getMethodSignature(final Method method) {\n try {\n final Field signatureField = method.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n final String signature = (String) signatureField.get(method);\n if (signature != null)\n return signature;\n return Type.getMethodDescriptor(method);\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access method \" + method);\n LogProvider.debug(e);\n return null;\n }\n }\n\n public static String getFieldDescriptor(final Field field, final String containedType) {\n try {\n final Field signatureField = field.getClass().getDeclaredField(\"signature\");\n signatureField.setAccessible(true);\n String signature = (String) signatureField.get(field);\n if (signature != null) {\n return resolvePotentialTypeVariables(signature, containedType);\n }\n return Type.getDescriptor(field.getType());\n } catch (ReflectiveOperationException e) {\n LogProvider.error(\"Could not access field \" + field);\n LogProvider.debug(e);\n return null;\n }\n }\n\n private static String resolvePotentialTypeVariables(final String signature, final String containedType) {\n // resolve type variables immediately\n if (signature.charAt(0) == 'T' || signature.contains(\" typeVariables = getTypeVariables(containedType);\n StringBuilder builder = new StringBuilder(signature);\n boolean startType = true;\n f", "post_mask_code": "or (int i = 0; i < builder.length(); i++) {\n if (startType && builder.charAt(i) == 'T') {\n final int end = builder.indexOf(\";\", i);\n final String identifier = builder.substring(i + 1, end);\n final String resolvedVariableType = typeVariables.getOrDefault(identifier, OBJECT);\n builder.replace(i, end + 1, resolvedVariableType);\n i = end;\n continue;\n }\n startType = builder.charAt(i) == '<' || builder.charAt(i) == ';';\n }\n return builder.toString();\n }\n return signature;\n }\n\n /**\n * Returns the parameter types of the given method signature. Parametrized types are supported.\n */\n public static List getParameters(final String methodDesc) {\n if (methodDesc == null)\n return emptyList();\n final char[] buffer = methodDesc.toCharArray();\n final List args = new ArrayList<>();\n // TODO resolve type parameters correctly -> information useful? -> maybe use ASM's SignatureReader/Visitor\n int offset = methodDesc.indexOf('(') + 1;\n while (buffer[offset] != ')') {\n final String type = getNextType(buffer, offset);\n args.add(type);\n offset += type.length();\n }\n // TODO change, see type parameters\n // prevent type parameter identifiers\n final ListIterator iterator = args.listIterator();\n while (iterator.hasNext()) {\n final String arg = iterator.next();\n if (arg.charAt(0) == 'T')\n iterator.set(OBJECT);\n }\n return args;\n }\n\n /**\n * Resolves the given method signatures to an array of (self-contained) Java type descriptions.\n *\n * @param methodDesc The method description signature (can contain type parameters and generics)\n * @return The types as an array with the method parameter types first and the return type as index {@code array.length - 1}\n */\n private static String[] resolveMethodSignature(final String methodDesc) {\n // if starts with '<' -> resolve type parameters\n return null;\n }\n\n private static Map resolveTypeParameters(final String methodDesc) {\n return null;\n }\n\n private static String getNextType(final char[] buf, final int off) {\n switch(buf[off]) {\n case 'V':\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n case 'F':\n case 'J':\n case 'D':\n return String.valueOf(buf[off]);\n case '[':\n int len = 1;\n while (buf[off + len] == '[') {\n len++;\n }\n return getNextType(buf, off, len);\n case 'L':\n // TODO resolve type variables\n case 'T':\n return getNextType(buf, off, 0);\n default:\n throw new IllegalArgumentException(\"Illegal signature provided: \" + new String(buf));\n }\n }\n\n private static String getNextType(char[] buf, int off, int len) {\n int depth = 0;\n if (buf[off + len] == 'L' || buf[off + len] == 'T')\n while (buf[off + len] != ';' || depth != 0) {\n if (buf[off + len] == '<')\n depth++;\n else if (buf[off + len] == '>')\n depth--;\n len++;\n }\n return new String(buf, off, len + 1);\n }\n}\n"} {"task_id": "Java_799", "language": "Java", "task_type": "method_signature", "source_file": "java/github/TheNewEconomy/TNE-Bukkit/TNEConversion/src/net/tnemc/conversion/command/ConverterCompleter.java", "mask_start_position": 581, "mask_end_position": 713, "canonical_solution": "@Override\n public LinkedList complete(PlayerProvider sender, Optional search, String argument) ", "pre_mask_code": "package net.tnemc.conversion.command;\n\nimport net.tnemc.commands.core.CommandSearchInformation;\nimport net.tnemc.commands.core.TabCompleter;\nimport net.tnemc.commands.core.provider.PlayerProvider;\nimport net.tnemc.conversion.ConversionModule;\nimport java.util.LinkedList;\nimport java.util.Optional;\n\n/**\n * The New Economy Minecraft Server Plugin\n *

\n * Created by creatorfromhell on 7/25/2021.\n *

\n * Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n * Created by creatorfromhell on 06/30/2017.\n */\npublic class ConverterCompleter implements TabCompleter {\n\n ", "post_mask_code": "{\n LinkedList values = new LinkedList<>();\n for (String str : ConversionModule.instance().manager().getConverters().keySet()) {\n if (!argument.trim().equalsIgnoreCase(\"\")) {\n if (str.startsWith(argument))\n values.add(str);\n }\n values.add(str);\n }\n return values;\n }\n}\n"} {"task_id": "Java_800", "language": "Java", "task_type": "method_body", "source_file": "java/github/TheNewEconomy/TNE-Bukkit/TNEConversion/src/net/tnemc/conversion/command/ConverterCompleter.java", "mask_start_position": 713, "mask_end_position": 1084, "canonical_solution": "{\n LinkedList values = new LinkedList<>();\n for (String str : ConversionModule.instance().manager().getConverters().keySet()) {\n if (!argument.trim().equalsIgnoreCase(\"\")) {\n if (str.startsWith(argument))\n values.add(str);\n }\n values.add(str);\n }\n return values;\n }", "pre_mask_code": "package net.tnemc.conversion.command;\n\nimport net.tnemc.commands.core.CommandSearchInformation;\nimport net.tnemc.commands.core.TabCompleter;\nimport net.tnemc.commands.core.provider.PlayerProvider;\nimport net.tnemc.conversion.ConversionModule;\nimport java.util.LinkedList;\nimport java.util.Optional;\n\n/**\n * The New Economy Minecraft Server Plugin\n *

\n * Created by creatorfromhell on 7/25/2021.\n *

\n * Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n * Created by creatorfromhell on 06/30/2017.\n */\npublic class ConverterCompleter implements TabCompleter {\n\n @Override\n public LinkedList complete(PlayerProvider sender, Optional search, String argument) ", "post_mask_code": "\n}\n"} {"task_id": "Java_801", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/TheNewEconomy/TNE-Bukkit/TNEConversion/src/net/tnemc/conversion/command/ConverterCompleter.java", "mask_start_position": 714, "mask_end_position": 770, "canonical_solution": "\n LinkedList values = new LinkedList<>();", "pre_mask_code": "package net.tnemc.conversion.command;\n\nimport net.tnemc.commands.core.CommandSearchInformation;\nimport net.tnemc.commands.core.TabCompleter;\nimport net.tnemc.commands.core.provider.PlayerProvider;\nimport net.tnemc.conversion.ConversionModule;\nimport java.util.LinkedList;\nimport java.util.Optional;\n\n/**\n * The New Economy Minecraft Server Plugin\n *

\n * Created by creatorfromhell on 7/25/2021.\n *

\n * Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n * Created by creatorfromhell on 06/30/2017.\n */\npublic class ConverterCompleter implements TabCompleter {\n\n @Override\n public LinkedList complete(PlayerProvider sender, Optional search, String argument) {", "post_mask_code": "\n for (String str : ConversionModule.instance().manager().getConverters().keySet()) {\n if (!argument.trim().equalsIgnoreCase(\"\")) {\n if (str.startsWith(argument))\n values.add(str);\n }\n values.add(str);\n }\n return values;\n }\n}\n"} {"task_id": "Java_802", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/TheNewEconomy/TNE-Bukkit/TNEConversion/src/net/tnemc/conversion/command/ConverterCompleter.java", "mask_start_position": 779, "mask_end_position": 1055, "canonical_solution": "for (String str : ConversionModule.instance().manager().getConverters().keySet()) {\n if (!argument.trim().equalsIgnoreCase(\"\")) {\n if (str.startsWith(argument))\n values.add(str);\n }\n values.add(str);\n }", "pre_mask_code": "package net.tnemc.conversion.command;\n\nimport net.tnemc.commands.core.CommandSearchInformation;\nimport net.tnemc.commands.core.TabCompleter;\nimport net.tnemc.commands.core.provider.PlayerProvider;\nimport net.tnemc.conversion.ConversionModule;\nimport java.util.LinkedList;\nimport java.util.Optional;\n\n/**\n * The New Economy Minecraft Server Plugin\n *

\n * Created by creatorfromhell on 7/25/2021.\n *

\n * Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n * Created by creatorfromhell on 06/30/2017.\n */\npublic class ConverterCompleter implements TabCompleter {\n\n @Override\n public LinkedList complete(PlayerProvider sender, Optional search, String argument) {\n LinkedList values = new LinkedList<>();\n ", "post_mask_code": "\n return values;\n }\n}\n"} {"task_id": "Java_803", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/TheNewEconomy/TNE-Bukkit/TNEConversion/src/net/tnemc/conversion/command/ConverterCompleter.java", "mask_start_position": 1064, "mask_end_position": 1084, "canonical_solution": "return values;\n }", "pre_mask_code": "package net.tnemc.conversion.command;\n\nimport net.tnemc.commands.core.CommandSearchInformation;\nimport net.tnemc.commands.core.TabCompleter;\nimport net.tnemc.commands.core.provider.PlayerProvider;\nimport net.tnemc.conversion.ConversionModule;\nimport java.util.LinkedList;\nimport java.util.Optional;\n\n/**\n * The New Economy Minecraft Server Plugin\n *

\n * Created by creatorfromhell on 7/25/2021.\n *

\n * Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n * Created by creatorfromhell on 06/30/2017.\n */\npublic class ConverterCompleter implements TabCompleter {\n\n @Override\n public LinkedList complete(PlayerProvider sender, Optional search, String argument) {\n LinkedList values = new LinkedList<>();\n for (String str : ConversionModule.instance().manager().getConverters().keySet()) {\n if (!argument.trim().equalsIgnoreCase(\"\")) {\n if (str.startsWith(argument))\n values.add(str);\n }\n values.add(str);\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_804", "language": "Java", "task_type": "single_line", "source_file": "java/github/TheNewEconomy/TNE-Bukkit/TNEConversion/src/net/tnemc/conversion/command/ConverterCompleter.java", "mask_start_position": 1077, "mask_end_position": 1078, "canonical_solution": ";", "pre_mask_code": "package net.tnemc.conversion.command;\n\nimport net.tnemc.commands.core.CommandSearchInformation;\nimport net.tnemc.commands.core.TabCompleter;\nimport net.tnemc.commands.core.provider.PlayerProvider;\nimport net.tnemc.conversion.ConversionModule;\nimport java.util.LinkedList;\nimport java.util.Optional;\n\n/**\n * The New Economy Minecraft Server Plugin\n *

\n * Created by creatorfromhell on 7/25/2021.\n *

\n * Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n * Created by creatorfromhell on 06/30/2017.\n */\npublic class ConverterCompleter implements TabCompleter {\n\n @Override\n public LinkedList complete(PlayerProvider sender, Optional search, String argument) {\n LinkedList values = new LinkedList<>();\n for (String str : ConversionModule.instance().manager().getConverters().keySet()) {\n if (!argument.trim().equalsIgnoreCase(\"\")) {\n if (str.startsWith(argument))\n values.add(str);\n }\n values.add(str);\n }\n return values", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_805", "language": "Java", "task_type": "if_statement", "source_file": "java/github/TheNewEconomy/TNE-Bukkit/TNEConversion/src/net/tnemc/conversion/command/ConverterCompleter.java", "mask_start_position": 875, "mask_end_position": 1016, "canonical_solution": "if (!argument.trim().equalsIgnoreCase(\"\")) {\n if (str.startsWith(argument))\n values.add(str);\n }", "pre_mask_code": "package net.tnemc.conversion.command;\n\nimport net.tnemc.commands.core.CommandSearchInformation;\nimport net.tnemc.commands.core.TabCompleter;\nimport net.tnemc.commands.core.provider.PlayerProvider;\nimport net.tnemc.conversion.ConversionModule;\nimport java.util.LinkedList;\nimport java.util.Optional;\n\n/**\n * The New Economy Minecraft Server Plugin\n *

\n * Created by creatorfromhell on 7/25/2021.\n *

\n * Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n * Created by creatorfromhell on 06/30/2017.\n */\npublic class ConverterCompleter implements TabCompleter {\n\n @Override\n public LinkedList complete(PlayerProvider sender, Optional search, String argument) {\n LinkedList values = new LinkedList<>();\n for (String str : ConversionModule.instance().manager().getConverters().keySet()) {\n ", "post_mask_code": "\n values.add(str);\n }\n return values;\n }\n}\n"} {"task_id": "Java_806", "language": "Java", "task_type": "empty", "source_file": "java/github/TheNewEconomy/TNE-Bukkit/TNEConversion/src/net/tnemc/conversion/command/ConverterCompleter.java", "mask_start_position": 850, "mask_end_position": 850, "canonical_solution": "", "pre_mask_code": "package net.tnemc.conversion.command;\n\nimport net.tnemc.commands.core.CommandSearchInformation;\nimport net.tnemc.commands.core.TabCompleter;\nimport net.tnemc.commands.core.provider.PlayerProvider;\nimport net.tnemc.conversion.ConversionModule;\nimport java.util.LinkedList;\nimport java.util.Optional;\n\n/**\n * The New Economy Minecraft Server Plugin\n *

\n * Created by creatorfromhell on 7/25/2021.\n *

\n * Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\n * Created by creatorfromhell on 06/30/2017.\n */\npublic class ConverterCompleter implements TabCompleter {\n\n @Override\n public LinkedList complete(PlayerProvider sender, Optional search, String argument) {\n LinkedList values = new LinkedList<>();\n for (String str : ConversionModule.instance().manager().getConverters()", "post_mask_code": ".keySet()) {\n if (!argument.trim().equalsIgnoreCase(\"\")) {\n if (str.startsWith(argument))\n values.add(str);\n }\n values.add(str);\n }\n return values;\n }\n}\n"} {"task_id": "Java_807", "language": "Java", "task_type": "method_signature", "source_file": "java/github/mycelium-com/wallet-android/mbw/src/main/java/com/mycelium/wallet/external/changelly/AccountAdapter.java", "mask_start_position": 5643, "mask_end_position": 5742, "canonical_solution": "private boolean trySettingReceivingAddress(ViewHolder viewHolder, BitcoinAddress receivingAddress) ", "pre_mask_code": "package com.mycelium.wallet.external.changelly;\n\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.view.Gravity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.mrd.bitlib.model.BitcoinAddress;\nimport com.mycelium.view.Denomination;\nimport com.mycelium.wallet.MbwManager;\nimport com.mycelium.wallet.R;\nimport com.mycelium.wallet.Utils;\nimport com.mycelium.wallet.activity.send.view.SelectableRecyclerView;\nimport com.mycelium.wallet.activity.util.ValueExtensionsKt;\nimport com.mycelium.wapi.wallet.WalletAccount;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class AccountAdapter extends SelectableRecyclerView.SRVAdapter {\n\n public enum AccountUseType {\n\n OUT(R.drawable.sender_recyclerview_item_background_selector_red, R.drawable.recyclerview_item_bottom_rectangle_selector, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_rectangle_height, R.layout.list_item_padding_sending), IN(R.drawable.sender_recyclerview_item_background_selector2, R.drawable.recyclerview_item_top_rectangle_selector, Gravity.TOP | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_triangle_height, R.layout.list_item_padding_receiving);\n\n public int background;\n\n public int gravity;\n\n public int heightRes;\n\n public int indicatorImg;\n\n public int paddingLayout;\n\n AccountUseType(int background, int indicatorImg, int gravity, int height, int paddingLayout) {\n this.background = background;\n this.indicatorImg = indicatorImg;\n this.gravity = gravity;\n this.heightRes = height;\n this.paddingLayout = paddingLayout;\n }\n }\n\n private List items = new ArrayList<>();\n\n private int paddingWidth;\n\n private MbwManager mbwManager;\n\n private AccountUseType accountUseType = AccountUseType.IN;\n\n public void setAccountUseType(AccountUseType accountUseType) {\n this.accountUseType = accountUseType;\n }\n\n public AccountAdapter(MbwManager mbwManager, List> accounts, int paddingWidth) {\n this.mbwManager = mbwManager;\n this.paddingWidth = paddingWidth;\n accounts = Utils.sortAccounts(accounts, mbwManager.getMetadataStorage());\n for (WalletAccount account : accounts) {\n if (account.isExchangeable()) {\n items.add(new Item(account, VIEW_TYPE_ITEM));\n }\n }\n }\n\n public Item getItem(int selectedItem) {\n return items.get(selectedItem);\n }\n\n public static class Item {\n\n public Item(WalletAccount account, int type) {\n this.type = type;\n this.account = account;\n }\n\n public int type;\n\n public WalletAccount account;\n }\n\n @Override\n public int findIndex(Object selected) {\n for (int i = 0; i < items.size(); i++) {\n Item item = items.get(i);\n if (item.account != null && item.account == selected) {\n return i;\n }\n }\n return -1;\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n if (viewType == VIEW_TYPE_ITEM) {\n // create a new view\n View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_fee_lvl, parent, false);\n v.setBackgroundResource(accountUseType.background);\n ImageView imageView = v.findViewById(R.id.rectangle);\n imageView.setImageResource(accountUseType.indicatorImg);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imageView.getLayoutParams();\n layoutParams.gravity = accountUseType.gravity;\n layoutParams.height = parent.getResources().getDimensionPixelSize(accountUseType.heightRes);\n imageView.setLayoutParams(layoutParams);\n ViewHolder viewHolder = new ViewHolder(v);\n viewHolder.valueTextView.setMaxLines(1);\n return viewHolder;\n } else {\n View view = LayoutInflater.from(parent.getContext()).inflate(accountUseType.paddingLayout, parent, false);\n view.setBackgroundResource(accountUseType.background);\n return new PaddingViewHolder(view);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n super.onBindViewHolder(holder, position);\n if (getItemViewType(position) == VIEW_TYPE_ITEM) {\n ViewHolder viewHolder = (ViewHolder) holder;\n Item item = items.get(position);\n viewHolder.categoryTextView.setText(mbwManager.getMetadataStorage().getLabelByAccount(item.account.getId()));\n Denomination denomination = mbwManager.getDenomination(item.account.getCoinType());\n viewHolder.itemTextView.setText(ValueExtensionsKt.toStringWithUnit(item.account.getAccountBalance().confirmed, denomination));\n if (item.account.getReceiveAddress() != null) {\n viewHolder.valueTextView.setText(item.account.getReceiveAddress().toString());\n }\n } else {\n RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();\n layoutParams.width = paddingWidth;\n holder.itemView.setLayoutParams(layoutParams);\n holder.itemView.setVisibility(getItemCount() > 3 || position == 0 ? View.VISIBLE : View.INVISIBLE);\n }\n }\n\n ", "post_mask_code": "{\n if (receivingAddress != null) {\n viewHolder.valueTextView.setText(receivingAddress.toString());\n return true;\n }\n return false;\n }\n\n @Override\n public int getItemViewType(int position) {\n return items.get(position).type;\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n\n public TextView categoryTextView;\n\n public TextView itemTextView;\n\n public TextView valueTextView;\n\n public ViewHolder(View v) {\n super(v);\n categoryTextView = v.findViewById(R.id.categorytextView);\n itemTextView = v.findViewById(R.id.itemTextView);\n valueTextView = v.findViewById(R.id.valueTextView);\n }\n }\n\n public static class PaddingViewHolder extends RecyclerView.ViewHolder {\n\n public PaddingViewHolder(View v) {\n super(v);\n }\n }\n}\n"} {"task_id": "Java_808", "language": "Java", "task_type": "method_body", "source_file": "java/github/mycelium-com/wallet-android/mbw/src/main/java/com/mycelium/wallet/external/changelly/AccountAdapter.java", "mask_start_position": 6076, "mask_end_position": 6112, "canonical_solution": "{\n return items.size();\n }", "pre_mask_code": "package com.mycelium.wallet.external.changelly;\n\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.view.Gravity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.mrd.bitlib.model.BitcoinAddress;\nimport com.mycelium.view.Denomination;\nimport com.mycelium.wallet.MbwManager;\nimport com.mycelium.wallet.R;\nimport com.mycelium.wallet.Utils;\nimport com.mycelium.wallet.activity.send.view.SelectableRecyclerView;\nimport com.mycelium.wallet.activity.util.ValueExtensionsKt;\nimport com.mycelium.wapi.wallet.WalletAccount;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class AccountAdapter extends SelectableRecyclerView.SRVAdapter {\n\n public enum AccountUseType {\n\n OUT(R.drawable.sender_recyclerview_item_background_selector_red, R.drawable.recyclerview_item_bottom_rectangle_selector, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_rectangle_height, R.layout.list_item_padding_sending), IN(R.drawable.sender_recyclerview_item_background_selector2, R.drawable.recyclerview_item_top_rectangle_selector, Gravity.TOP | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_triangle_height, R.layout.list_item_padding_receiving);\n\n public int background;\n\n public int gravity;\n\n public int heightRes;\n\n public int indicatorImg;\n\n public int paddingLayout;\n\n AccountUseType(int background, int indicatorImg, int gravity, int height, int paddingLayout) {\n this.background = background;\n this.indicatorImg = indicatorImg;\n this.gravity = gravity;\n this.heightRes = height;\n this.paddingLayout = paddingLayout;\n }\n }\n\n private List items = new ArrayList<>();\n\n private int paddingWidth;\n\n private MbwManager mbwManager;\n\n private AccountUseType accountUseType = AccountUseType.IN;\n\n public void setAccountUseType(AccountUseType accountUseType) {\n this.accountUseType = accountUseType;\n }\n\n public AccountAdapter(MbwManager mbwManager, List> accounts, int paddingWidth) {\n this.mbwManager = mbwManager;\n this.paddingWidth = paddingWidth;\n accounts = Utils.sortAccounts(accounts, mbwManager.getMetadataStorage());\n for (WalletAccount account : accounts) {\n if (account.isExchangeable()) {\n items.add(new Item(account, VIEW_TYPE_ITEM));\n }\n }\n }\n\n public Item getItem(int selectedItem) {\n return items.get(selectedItem);\n }\n\n public static class Item {\n\n public Item(WalletAccount account, int type) {\n this.type = type;\n this.account = account;\n }\n\n public int type;\n\n public WalletAccount account;\n }\n\n @Override\n public int findIndex(Object selected) {\n for (int i = 0; i < items.size(); i++) {\n Item item = items.get(i);\n if (item.account != null && item.account == selected) {\n return i;\n }\n }\n return -1;\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n if (viewType == VIEW_TYPE_ITEM) {\n // create a new view\n View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_fee_lvl, parent, false);\n v.setBackgroundResource(accountUseType.background);\n ImageView imageView = v.findViewById(R.id.rectangle);\n imageView.setImageResource(accountUseType.indicatorImg);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imageView.getLayoutParams();\n layoutParams.gravity = accountUseType.gravity;\n layoutParams.height = parent.getResources().getDimensionPixelSize(accountUseType.heightRes);\n imageView.setLayoutParams(layoutParams);\n ViewHolder viewHolder = new ViewHolder(v);\n viewHolder.valueTextView.setMaxLines(1);\n return viewHolder;\n } else {\n View view = LayoutInflater.from(parent.getContext()).inflate(accountUseType.paddingLayout, parent, false);\n view.setBackgroundResource(accountUseType.background);\n return new PaddingViewHolder(view);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n super.onBindViewHolder(holder, position);\n if (getItemViewType(position) == VIEW_TYPE_ITEM) {\n ViewHolder viewHolder = (ViewHolder) holder;\n Item item = items.get(position);\n viewHolder.categoryTextView.setText(mbwManager.getMetadataStorage().getLabelByAccount(item.account.getId()));\n Denomination denomination = mbwManager.getDenomination(item.account.getCoinType());\n viewHolder.itemTextView.setText(ValueExtensionsKt.toStringWithUnit(item.account.getAccountBalance().confirmed, denomination));\n if (item.account.getReceiveAddress() != null) {\n viewHolder.valueTextView.setText(item.account.getReceiveAddress().toString());\n }\n } else {\n RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();\n layoutParams.width = paddingWidth;\n holder.itemView.setLayoutParams(layoutParams);\n holder.itemView.setVisibility(getItemCount() > 3 || position == 0 ? View.VISIBLE : View.INVISIBLE);\n }\n }\n\n private boolean trySettingReceivingAddress(ViewHolder viewHolder, BitcoinAddress receivingAddress) {\n if (receivingAddress != null) {\n viewHolder.valueTextView.setText(receivingAddress.toString());\n return true;\n }\n return false;\n }\n\n @Override\n public int getItemViewType(int position) {\n return items.get(position).type;\n }\n\n @Override\n public int getItemCount() ", "post_mask_code": "\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n\n public TextView categoryTextView;\n\n public TextView itemTextView;\n\n public TextView valueTextView;\n\n public ViewHolder(View v) {\n super(v);\n categoryTextView = v.findViewById(R.id.categorytextView);\n itemTextView = v.findViewById(R.id.itemTextView);\n valueTextView = v.findViewById(R.id.valueTextView);\n }\n }\n\n public static class PaddingViewHolder extends RecyclerView.ViewHolder {\n\n public PaddingViewHolder(View v) {\n super(v);\n }\n }\n}\n"} {"task_id": "Java_809", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/mycelium-com/wallet-android/mbw/src/main/java/com/mycelium/wallet/external/changelly/AccountAdapter.java", "mask_start_position": 2977, "mask_end_position": 3182, "canonical_solution": "\n for (int i = 0; i < items.size(); i++) {\n Item item = items.get(i);\n if (item.account != null && item.account == selected) {\n return i;\n }\n }", "pre_mask_code": "package com.mycelium.wallet.external.changelly;\n\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.view.Gravity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.mrd.bitlib.model.BitcoinAddress;\nimport com.mycelium.view.Denomination;\nimport com.mycelium.wallet.MbwManager;\nimport com.mycelium.wallet.R;\nimport com.mycelium.wallet.Utils;\nimport com.mycelium.wallet.activity.send.view.SelectableRecyclerView;\nimport com.mycelium.wallet.activity.util.ValueExtensionsKt;\nimport com.mycelium.wapi.wallet.WalletAccount;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class AccountAdapter extends SelectableRecyclerView.SRVAdapter {\n\n public enum AccountUseType {\n\n OUT(R.drawable.sender_recyclerview_item_background_selector_red, R.drawable.recyclerview_item_bottom_rectangle_selector, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_rectangle_height, R.layout.list_item_padding_sending), IN(R.drawable.sender_recyclerview_item_background_selector2, R.drawable.recyclerview_item_top_rectangle_selector, Gravity.TOP | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_triangle_height, R.layout.list_item_padding_receiving);\n\n public int background;\n\n public int gravity;\n\n public int heightRes;\n\n public int indicatorImg;\n\n public int paddingLayout;\n\n AccountUseType(int background, int indicatorImg, int gravity, int height, int paddingLayout) {\n this.background = background;\n this.indicatorImg = indicatorImg;\n this.gravity = gravity;\n this.heightRes = height;\n this.paddingLayout = paddingLayout;\n }\n }\n\n private List items = new ArrayList<>();\n\n private int paddingWidth;\n\n private MbwManager mbwManager;\n\n private AccountUseType accountUseType = AccountUseType.IN;\n\n public void setAccountUseType(AccountUseType accountUseType) {\n this.accountUseType = accountUseType;\n }\n\n public AccountAdapter(MbwManager mbwManager, List> accounts, int paddingWidth) {\n this.mbwManager = mbwManager;\n this.paddingWidth = paddingWidth;\n accounts = Utils.sortAccounts(accounts, mbwManager.getMetadataStorage());\n for (WalletAccount account : accounts) {\n if (account.isExchangeable()) {\n items.add(new Item(account, VIEW_TYPE_ITEM));\n }\n }\n }\n\n public Item getItem(int selectedItem) {\n return items.get(selectedItem);\n }\n\n public static class Item {\n\n public Item(WalletAccount account, int type) {\n this.type = type;\n this.account = account;\n }\n\n public int type;\n\n public WalletAccount account;\n }\n\n @Override\n public int findIndex(Object selected) {", "post_mask_code": "\n return -1;\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n if (viewType == VIEW_TYPE_ITEM) {\n // create a new view\n View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_fee_lvl, parent, false);\n v.setBackgroundResource(accountUseType.background);\n ImageView imageView = v.findViewById(R.id.rectangle);\n imageView.setImageResource(accountUseType.indicatorImg);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imageView.getLayoutParams();\n layoutParams.gravity = accountUseType.gravity;\n layoutParams.height = parent.getResources().getDimensionPixelSize(accountUseType.heightRes);\n imageView.setLayoutParams(layoutParams);\n ViewHolder viewHolder = new ViewHolder(v);\n viewHolder.valueTextView.setMaxLines(1);\n return viewHolder;\n } else {\n View view = LayoutInflater.from(parent.getContext()).inflate(accountUseType.paddingLayout, parent, false);\n view.setBackgroundResource(accountUseType.background);\n return new PaddingViewHolder(view);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n super.onBindViewHolder(holder, position);\n if (getItemViewType(position) == VIEW_TYPE_ITEM) {\n ViewHolder viewHolder = (ViewHolder) holder;\n Item item = items.get(position);\n viewHolder.categoryTextView.setText(mbwManager.getMetadataStorage().getLabelByAccount(item.account.getId()));\n Denomination denomination = mbwManager.getDenomination(item.account.getCoinType());\n viewHolder.itemTextView.setText(ValueExtensionsKt.toStringWithUnit(item.account.getAccountBalance().confirmed, denomination));\n if (item.account.getReceiveAddress() != null) {\n viewHolder.valueTextView.setText(item.account.getReceiveAddress().toString());\n }\n } else {\n RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();\n layoutParams.width = paddingWidth;\n holder.itemView.setLayoutParams(layoutParams);\n holder.itemView.setVisibility(getItemCount() > 3 || position == 0 ? View.VISIBLE : View.INVISIBLE);\n }\n }\n\n private boolean trySettingReceivingAddress(ViewHolder viewHolder, BitcoinAddress receivingAddress) {\n if (receivingAddress != null) {\n viewHolder.valueTextView.setText(receivingAddress.toString());\n return true;\n }\n return false;\n }\n\n @Override\n public int getItemViewType(int position) {\n return items.get(position).type;\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n\n public TextView categoryTextView;\n\n public TextView itemTextView;\n\n public TextView valueTextView;\n\n public ViewHolder(View v) {\n super(v);\n categoryTextView = v.findViewById(R.id.categorytextView);\n itemTextView = v.findViewById(R.id.itemTextView);\n valueTextView = v.findViewById(R.id.valueTextView);\n }\n }\n\n public static class PaddingViewHolder extends RecyclerView.ViewHolder {\n\n public PaddingViewHolder(View v) {\n super(v);\n }\n }\n}\n"} {"task_id": "Java_810", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/mycelium-com/wallet-android/mbw/src/main/java/com/mycelium/wallet/external/changelly/AccountAdapter.java", "mask_start_position": 3191, "mask_end_position": 3201, "canonical_solution": "return -1;", "pre_mask_code": "package com.mycelium.wallet.external.changelly;\n\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.view.Gravity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.mrd.bitlib.model.BitcoinAddress;\nimport com.mycelium.view.Denomination;\nimport com.mycelium.wallet.MbwManager;\nimport com.mycelium.wallet.R;\nimport com.mycelium.wallet.Utils;\nimport com.mycelium.wallet.activity.send.view.SelectableRecyclerView;\nimport com.mycelium.wallet.activity.util.ValueExtensionsKt;\nimport com.mycelium.wapi.wallet.WalletAccount;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class AccountAdapter extends SelectableRecyclerView.SRVAdapter {\n\n public enum AccountUseType {\n\n OUT(R.drawable.sender_recyclerview_item_background_selector_red, R.drawable.recyclerview_item_bottom_rectangle_selector, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_rectangle_height, R.layout.list_item_padding_sending), IN(R.drawable.sender_recyclerview_item_background_selector2, R.drawable.recyclerview_item_top_rectangle_selector, Gravity.TOP | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_triangle_height, R.layout.list_item_padding_receiving);\n\n public int background;\n\n public int gravity;\n\n public int heightRes;\n\n public int indicatorImg;\n\n public int paddingLayout;\n\n AccountUseType(int background, int indicatorImg, int gravity, int height, int paddingLayout) {\n this.background = background;\n this.indicatorImg = indicatorImg;\n this.gravity = gravity;\n this.heightRes = height;\n this.paddingLayout = paddingLayout;\n }\n }\n\n private List items = new ArrayList<>();\n\n private int paddingWidth;\n\n private MbwManager mbwManager;\n\n private AccountUseType accountUseType = AccountUseType.IN;\n\n public void setAccountUseType(AccountUseType accountUseType) {\n this.accountUseType = accountUseType;\n }\n\n public AccountAdapter(MbwManager mbwManager, List> accounts, int paddingWidth) {\n this.mbwManager = mbwManager;\n this.paddingWidth = paddingWidth;\n accounts = Utils.sortAccounts(accounts, mbwManager.getMetadataStorage());\n for (WalletAccount account : accounts) {\n if (account.isExchangeable()) {\n items.add(new Item(account, VIEW_TYPE_ITEM));\n }\n }\n }\n\n public Item getItem(int selectedItem) {\n return items.get(selectedItem);\n }\n\n public static class Item {\n\n public Item(WalletAccount account, int type) {\n this.type = type;\n this.account = account;\n }\n\n public int type;\n\n public WalletAccount account;\n }\n\n @Override\n public int findIndex(Object selected) {\n for (int i = 0; i < items.size(); i++) {\n Item item = items.get(i);\n if (item.account != null && item.account == selected) {\n return i;\n }\n }\n ", "post_mask_code": "\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n if (viewType == VIEW_TYPE_ITEM) {\n // create a new view\n View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_fee_lvl, parent, false);\n v.setBackgroundResource(accountUseType.background);\n ImageView imageView = v.findViewById(R.id.rectangle);\n imageView.setImageResource(accountUseType.indicatorImg);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imageView.getLayoutParams();\n layoutParams.gravity = accountUseType.gravity;\n layoutParams.height = parent.getResources().getDimensionPixelSize(accountUseType.heightRes);\n imageView.setLayoutParams(layoutParams);\n ViewHolder viewHolder = new ViewHolder(v);\n viewHolder.valueTextView.setMaxLines(1);\n return viewHolder;\n } else {\n View view = LayoutInflater.from(parent.getContext()).inflate(accountUseType.paddingLayout, parent, false);\n view.setBackgroundResource(accountUseType.background);\n return new PaddingViewHolder(view);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n super.onBindViewHolder(holder, position);\n if (getItemViewType(position) == VIEW_TYPE_ITEM) {\n ViewHolder viewHolder = (ViewHolder) holder;\n Item item = items.get(position);\n viewHolder.categoryTextView.setText(mbwManager.getMetadataStorage().getLabelByAccount(item.account.getId()));\n Denomination denomination = mbwManager.getDenomination(item.account.getCoinType());\n viewHolder.itemTextView.setText(ValueExtensionsKt.toStringWithUnit(item.account.getAccountBalance().confirmed, denomination));\n if (item.account.getReceiveAddress() != null) {\n viewHolder.valueTextView.setText(item.account.getReceiveAddress().toString());\n }\n } else {\n RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();\n layoutParams.width = paddingWidth;\n holder.itemView.setLayoutParams(layoutParams);\n holder.itemView.setVisibility(getItemCount() > 3 || position == 0 ? View.VISIBLE : View.INVISIBLE);\n }\n }\n\n private boolean trySettingReceivingAddress(ViewHolder viewHolder, BitcoinAddress receivingAddress) {\n if (receivingAddress != null) {\n viewHolder.valueTextView.setText(receivingAddress.toString());\n return true;\n }\n return false;\n }\n\n @Override\n public int getItemViewType(int position) {\n return items.get(position).type;\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n\n public TextView categoryTextView;\n\n public TextView itemTextView;\n\n public TextView valueTextView;\n\n public ViewHolder(View v) {\n super(v);\n categoryTextView = v.findViewById(R.id.categorytextView);\n itemTextView = v.findViewById(R.id.itemTextView);\n valueTextView = v.findViewById(R.id.valueTextView);\n }\n }\n\n public static class PaddingViewHolder extends RecyclerView.ViewHolder {\n\n public PaddingViewHolder(View v) {\n super(v);\n }\n }\n}\n"} {"task_id": "Java_811", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/mycelium-com/wallet-android/mbw/src/main/java/com/mycelium/wallet/external/changelly/AccountAdapter.java", "mask_start_position": 3206, "mask_end_position": 3207, "canonical_solution": "}", "pre_mask_code": "package com.mycelium.wallet.external.changelly;\n\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.view.Gravity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.mrd.bitlib.model.BitcoinAddress;\nimport com.mycelium.view.Denomination;\nimport com.mycelium.wallet.MbwManager;\nimport com.mycelium.wallet.R;\nimport com.mycelium.wallet.Utils;\nimport com.mycelium.wallet.activity.send.view.SelectableRecyclerView;\nimport com.mycelium.wallet.activity.util.ValueExtensionsKt;\nimport com.mycelium.wapi.wallet.WalletAccount;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class AccountAdapter extends SelectableRecyclerView.SRVAdapter {\n\n public enum AccountUseType {\n\n OUT(R.drawable.sender_recyclerview_item_background_selector_red, R.drawable.recyclerview_item_bottom_rectangle_selector, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_rectangle_height, R.layout.list_item_padding_sending), IN(R.drawable.sender_recyclerview_item_background_selector2, R.drawable.recyclerview_item_top_rectangle_selector, Gravity.TOP | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_triangle_height, R.layout.list_item_padding_receiving);\n\n public int background;\n\n public int gravity;\n\n public int heightRes;\n\n public int indicatorImg;\n\n public int paddingLayout;\n\n AccountUseType(int background, int indicatorImg, int gravity, int height, int paddingLayout) {\n this.background = background;\n this.indicatorImg = indicatorImg;\n this.gravity = gravity;\n this.heightRes = height;\n this.paddingLayout = paddingLayout;\n }\n }\n\n private List items = new ArrayList<>();\n\n private int paddingWidth;\n\n private MbwManager mbwManager;\n\n private AccountUseType accountUseType = AccountUseType.IN;\n\n public void setAccountUseType(AccountUseType accountUseType) {\n this.accountUseType = accountUseType;\n }\n\n public AccountAdapter(MbwManager mbwManager, List> accounts, int paddingWidth) {\n this.mbwManager = mbwManager;\n this.paddingWidth = paddingWidth;\n accounts = Utils.sortAccounts(accounts, mbwManager.getMetadataStorage());\n for (WalletAccount account : accounts) {\n if (account.isExchangeable()) {\n items.add(new Item(account, VIEW_TYPE_ITEM));\n }\n }\n }\n\n public Item getItem(int selectedItem) {\n return items.get(selectedItem);\n }\n\n public static class Item {\n\n public Item(WalletAccount account, int type) {\n this.type = type;\n this.account = account;\n }\n\n public int type;\n\n public WalletAccount account;\n }\n\n @Override\n public int findIndex(Object selected) {\n for (int i = 0; i < items.size(); i++) {\n Item item = items.get(i);\n if (item.account != null && item.account == selected) {\n return i;\n }\n }\n return -1;\n ", "post_mask_code": "\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n if (viewType == VIEW_TYPE_ITEM) {\n // create a new view\n View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_fee_lvl, parent, false);\n v.setBackgroundResource(accountUseType.background);\n ImageView imageView = v.findViewById(R.id.rectangle);\n imageView.setImageResource(accountUseType.indicatorImg);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imageView.getLayoutParams();\n layoutParams.gravity = accountUseType.gravity;\n layoutParams.height = parent.getResources().getDimensionPixelSize(accountUseType.heightRes);\n imageView.setLayoutParams(layoutParams);\n ViewHolder viewHolder = new ViewHolder(v);\n viewHolder.valueTextView.setMaxLines(1);\n return viewHolder;\n } else {\n View view = LayoutInflater.from(parent.getContext()).inflate(accountUseType.paddingLayout, parent, false);\n view.setBackgroundResource(accountUseType.background);\n return new PaddingViewHolder(view);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n super.onBindViewHolder(holder, position);\n if (getItemViewType(position) == VIEW_TYPE_ITEM) {\n ViewHolder viewHolder = (ViewHolder) holder;\n Item item = items.get(position);\n viewHolder.categoryTextView.setText(mbwManager.getMetadataStorage().getLabelByAccount(item.account.getId()));\n Denomination denomination = mbwManager.getDenomination(item.account.getCoinType());\n viewHolder.itemTextView.setText(ValueExtensionsKt.toStringWithUnit(item.account.getAccountBalance().confirmed, denomination));\n if (item.account.getReceiveAddress() != null) {\n viewHolder.valueTextView.setText(item.account.getReceiveAddress().toString());\n }\n } else {\n RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();\n layoutParams.width = paddingWidth;\n holder.itemView.setLayoutParams(layoutParams);\n holder.itemView.setVisibility(getItemCount() > 3 || position == 0 ? View.VISIBLE : View.INVISIBLE);\n }\n }\n\n private boolean trySettingReceivingAddress(ViewHolder viewHolder, BitcoinAddress receivingAddress) {\n if (receivingAddress != null) {\n viewHolder.valueTextView.setText(receivingAddress.toString());\n return true;\n }\n return false;\n }\n\n @Override\n public int getItemViewType(int position) {\n return items.get(position).type;\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n\n public TextView categoryTextView;\n\n public TextView itemTextView;\n\n public TextView valueTextView;\n\n public ViewHolder(View v) {\n super(v);\n categoryTextView = v.findViewById(R.id.categorytextView);\n itemTextView = v.findViewById(R.id.itemTextView);\n valueTextView = v.findViewById(R.id.valueTextView);\n }\n }\n\n public static class PaddingViewHolder extends RecyclerView.ViewHolder {\n\n public PaddingViewHolder(View v) {\n super(v);\n }\n }\n}\n"} {"task_id": "Java_812", "language": "Java", "task_type": "single_line", "source_file": "java/github/mycelium-com/wallet-android/mbw/src/main/java/com/mycelium/wallet/external/changelly/AccountAdapter.java", "mask_start_position": 3193, "mask_end_position": 3201, "canonical_solution": "turn -1;", "pre_mask_code": "package com.mycelium.wallet.external.changelly;\n\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.view.Gravity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.mrd.bitlib.model.BitcoinAddress;\nimport com.mycelium.view.Denomination;\nimport com.mycelium.wallet.MbwManager;\nimport com.mycelium.wallet.R;\nimport com.mycelium.wallet.Utils;\nimport com.mycelium.wallet.activity.send.view.SelectableRecyclerView;\nimport com.mycelium.wallet.activity.util.ValueExtensionsKt;\nimport com.mycelium.wapi.wallet.WalletAccount;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class AccountAdapter extends SelectableRecyclerView.SRVAdapter {\n\n public enum AccountUseType {\n\n OUT(R.drawable.sender_recyclerview_item_background_selector_red, R.drawable.recyclerview_item_bottom_rectangle_selector, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_rectangle_height, R.layout.list_item_padding_sending), IN(R.drawable.sender_recyclerview_item_background_selector2, R.drawable.recyclerview_item_top_rectangle_selector, Gravity.TOP | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_triangle_height, R.layout.list_item_padding_receiving);\n\n public int background;\n\n public int gravity;\n\n public int heightRes;\n\n public int indicatorImg;\n\n public int paddingLayout;\n\n AccountUseType(int background, int indicatorImg, int gravity, int height, int paddingLayout) {\n this.background = background;\n this.indicatorImg = indicatorImg;\n this.gravity = gravity;\n this.heightRes = height;\n this.paddingLayout = paddingLayout;\n }\n }\n\n private List items = new ArrayList<>();\n\n private int paddingWidth;\n\n private MbwManager mbwManager;\n\n private AccountUseType accountUseType = AccountUseType.IN;\n\n public void setAccountUseType(AccountUseType accountUseType) {\n this.accountUseType = accountUseType;\n }\n\n public AccountAdapter(MbwManager mbwManager, List> accounts, int paddingWidth) {\n this.mbwManager = mbwManager;\n this.paddingWidth = paddingWidth;\n accounts = Utils.sortAccounts(accounts, mbwManager.getMetadataStorage());\n for (WalletAccount account : accounts) {\n if (account.isExchangeable()) {\n items.add(new Item(account, VIEW_TYPE_ITEM));\n }\n }\n }\n\n public Item getItem(int selectedItem) {\n return items.get(selectedItem);\n }\n\n public static class Item {\n\n public Item(WalletAccount account, int type) {\n this.type = type;\n this.account = account;\n }\n\n public int type;\n\n public WalletAccount account;\n }\n\n @Override\n public int findIndex(Object selected) {\n for (int i = 0; i < items.size(); i++) {\n Item item = items.get(i);\n if (item.account != null && item.account == selected) {\n return i;\n }\n }\n re", "post_mask_code": "\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n if (viewType == VIEW_TYPE_ITEM) {\n // create a new view\n View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_fee_lvl, parent, false);\n v.setBackgroundResource(accountUseType.background);\n ImageView imageView = v.findViewById(R.id.rectangle);\n imageView.setImageResource(accountUseType.indicatorImg);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imageView.getLayoutParams();\n layoutParams.gravity = accountUseType.gravity;\n layoutParams.height = parent.getResources().getDimensionPixelSize(accountUseType.heightRes);\n imageView.setLayoutParams(layoutParams);\n ViewHolder viewHolder = new ViewHolder(v);\n viewHolder.valueTextView.setMaxLines(1);\n return viewHolder;\n } else {\n View view = LayoutInflater.from(parent.getContext()).inflate(accountUseType.paddingLayout, parent, false);\n view.setBackgroundResource(accountUseType.background);\n return new PaddingViewHolder(view);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n super.onBindViewHolder(holder, position);\n if (getItemViewType(position) == VIEW_TYPE_ITEM) {\n ViewHolder viewHolder = (ViewHolder) holder;\n Item item = items.get(position);\n viewHolder.categoryTextView.setText(mbwManager.getMetadataStorage().getLabelByAccount(item.account.getId()));\n Denomination denomination = mbwManager.getDenomination(item.account.getCoinType());\n viewHolder.itemTextView.setText(ValueExtensionsKt.toStringWithUnit(item.account.getAccountBalance().confirmed, denomination));\n if (item.account.getReceiveAddress() != null) {\n viewHolder.valueTextView.setText(item.account.getReceiveAddress().toString());\n }\n } else {\n RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();\n layoutParams.width = paddingWidth;\n holder.itemView.setLayoutParams(layoutParams);\n holder.itemView.setVisibility(getItemCount() > 3 || position == 0 ? View.VISIBLE : View.INVISIBLE);\n }\n }\n\n private boolean trySettingReceivingAddress(ViewHolder viewHolder, BitcoinAddress receivingAddress) {\n if (receivingAddress != null) {\n viewHolder.valueTextView.setText(receivingAddress.toString());\n return true;\n }\n return false;\n }\n\n @Override\n public int getItemViewType(int position) {\n return items.get(position).type;\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n\n public TextView categoryTextView;\n\n public TextView itemTextView;\n\n public TextView valueTextView;\n\n public ViewHolder(View v) {\n super(v);\n categoryTextView = v.findViewById(R.id.categorytextView);\n itemTextView = v.findViewById(R.id.itemTextView);\n valueTextView = v.findViewById(R.id.valueTextView);\n }\n }\n\n public static class PaddingViewHolder extends RecyclerView.ViewHolder {\n\n public PaddingViewHolder(View v) {\n super(v);\n }\n }\n}\n"} {"task_id": "Java_813", "language": "Java", "task_type": "if_statement", "source_file": "java/github/mycelium-com/wallet-android/mbw/src/main/java/com/mycelium/wallet/external/changelly/AccountAdapter.java", "mask_start_position": 2469, "mask_end_position": 2576, "canonical_solution": "if (account.isExchangeable()) {\n items.add(new Item(account, VIEW_TYPE_ITEM));\n }", "pre_mask_code": "package com.mycelium.wallet.external.changelly;\n\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.view.Gravity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.mrd.bitlib.model.BitcoinAddress;\nimport com.mycelium.view.Denomination;\nimport com.mycelium.wallet.MbwManager;\nimport com.mycelium.wallet.R;\nimport com.mycelium.wallet.Utils;\nimport com.mycelium.wallet.activity.send.view.SelectableRecyclerView;\nimport com.mycelium.wallet.activity.util.ValueExtensionsKt;\nimport com.mycelium.wapi.wallet.WalletAccount;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class AccountAdapter extends SelectableRecyclerView.SRVAdapter {\n\n public enum AccountUseType {\n\n OUT(R.drawable.sender_recyclerview_item_background_selector_red, R.drawable.recyclerview_item_bottom_rectangle_selector, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_rectangle_height, R.layout.list_item_padding_sending), IN(R.drawable.sender_recyclerview_item_background_selector2, R.drawable.recyclerview_item_top_rectangle_selector, Gravity.TOP | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_triangle_height, R.layout.list_item_padding_receiving);\n\n public int background;\n\n public int gravity;\n\n public int heightRes;\n\n public int indicatorImg;\n\n public int paddingLayout;\n\n AccountUseType(int background, int indicatorImg, int gravity, int height, int paddingLayout) {\n this.background = background;\n this.indicatorImg = indicatorImg;\n this.gravity = gravity;\n this.heightRes = height;\n this.paddingLayout = paddingLayout;\n }\n }\n\n private List items = new ArrayList<>();\n\n private int paddingWidth;\n\n private MbwManager mbwManager;\n\n private AccountUseType accountUseType = AccountUseType.IN;\n\n public void setAccountUseType(AccountUseType accountUseType) {\n this.accountUseType = accountUseType;\n }\n\n public AccountAdapter(MbwManager mbwManager, List> accounts, int paddingWidth) {\n this.mbwManager = mbwManager;\n this.paddingWidth = paddingWidth;\n accounts = Utils.sortAccounts(accounts, mbwManager.getMetadataStorage());\n for (WalletAccount account : accounts) {\n ", "post_mask_code": "\n }\n }\n\n public Item getItem(int selectedItem) {\n return items.get(selectedItem);\n }\n\n public static class Item {\n\n public Item(WalletAccount account, int type) {\n this.type = type;\n this.account = account;\n }\n\n public int type;\n\n public WalletAccount account;\n }\n\n @Override\n public int findIndex(Object selected) {\n for (int i = 0; i < items.size(); i++) {\n Item item = items.get(i);\n if (item.account != null && item.account == selected) {\n return i;\n }\n }\n return -1;\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n if (viewType == VIEW_TYPE_ITEM) {\n // create a new view\n View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_fee_lvl, parent, false);\n v.setBackgroundResource(accountUseType.background);\n ImageView imageView = v.findViewById(R.id.rectangle);\n imageView.setImageResource(accountUseType.indicatorImg);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imageView.getLayoutParams();\n layoutParams.gravity = accountUseType.gravity;\n layoutParams.height = parent.getResources().getDimensionPixelSize(accountUseType.heightRes);\n imageView.setLayoutParams(layoutParams);\n ViewHolder viewHolder = new ViewHolder(v);\n viewHolder.valueTextView.setMaxLines(1);\n return viewHolder;\n } else {\n View view = LayoutInflater.from(parent.getContext()).inflate(accountUseType.paddingLayout, parent, false);\n view.setBackgroundResource(accountUseType.background);\n return new PaddingViewHolder(view);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n super.onBindViewHolder(holder, position);\n if (getItemViewType(position) == VIEW_TYPE_ITEM) {\n ViewHolder viewHolder = (ViewHolder) holder;\n Item item = items.get(position);\n viewHolder.categoryTextView.setText(mbwManager.getMetadataStorage().getLabelByAccount(item.account.getId()));\n Denomination denomination = mbwManager.getDenomination(item.account.getCoinType());\n viewHolder.itemTextView.setText(ValueExtensionsKt.toStringWithUnit(item.account.getAccountBalance().confirmed, denomination));\n if (item.account.getReceiveAddress() != null) {\n viewHolder.valueTextView.setText(item.account.getReceiveAddress().toString());\n }\n } else {\n RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();\n layoutParams.width = paddingWidth;\n holder.itemView.setLayoutParams(layoutParams);\n holder.itemView.setVisibility(getItemCount() > 3 || position == 0 ? View.VISIBLE : View.INVISIBLE);\n }\n }\n\n private boolean trySettingReceivingAddress(ViewHolder viewHolder, BitcoinAddress receivingAddress) {\n if (receivingAddress != null) {\n viewHolder.valueTextView.setText(receivingAddress.toString());\n return true;\n }\n return false;\n }\n\n @Override\n public int getItemViewType(int position) {\n return items.get(position).type;\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n\n public TextView categoryTextView;\n\n public TextView itemTextView;\n\n public TextView valueTextView;\n\n public ViewHolder(View v) {\n super(v);\n categoryTextView = v.findViewById(R.id.categorytextView);\n itemTextView = v.findViewById(R.id.itemTextView);\n valueTextView = v.findViewById(R.id.valueTextView);\n }\n }\n\n public static class PaddingViewHolder extends RecyclerView.ViewHolder {\n\n public PaddingViewHolder(View v) {\n super(v);\n }\n }\n}\n"} {"task_id": "Java_814", "language": "Java", "task_type": "for_statement", "source_file": "java/github/mycelium-com/wallet-android/mbw/src/main/java/com/mycelium/wallet/external/changelly/AccountAdapter.java", "mask_start_position": 2986, "mask_end_position": 3182, "canonical_solution": "for (int i = 0; i < items.size(); i++) {\n Item item = items.get(i);\n if (item.account != null && item.account == selected) {\n return i;\n }\n }", "pre_mask_code": "package com.mycelium.wallet.external.changelly;\n\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.view.Gravity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.mrd.bitlib.model.BitcoinAddress;\nimport com.mycelium.view.Denomination;\nimport com.mycelium.wallet.MbwManager;\nimport com.mycelium.wallet.R;\nimport com.mycelium.wallet.Utils;\nimport com.mycelium.wallet.activity.send.view.SelectableRecyclerView;\nimport com.mycelium.wallet.activity.util.ValueExtensionsKt;\nimport com.mycelium.wapi.wallet.WalletAccount;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class AccountAdapter extends SelectableRecyclerView.SRVAdapter {\n\n public enum AccountUseType {\n\n OUT(R.drawable.sender_recyclerview_item_background_selector_red, R.drawable.recyclerview_item_bottom_rectangle_selector, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_rectangle_height, R.layout.list_item_padding_sending), IN(R.drawable.sender_recyclerview_item_background_selector2, R.drawable.recyclerview_item_top_rectangle_selector, Gravity.TOP | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_triangle_height, R.layout.list_item_padding_receiving);\n\n public int background;\n\n public int gravity;\n\n public int heightRes;\n\n public int indicatorImg;\n\n public int paddingLayout;\n\n AccountUseType(int background, int indicatorImg, int gravity, int height, int paddingLayout) {\n this.background = background;\n this.indicatorImg = indicatorImg;\n this.gravity = gravity;\n this.heightRes = height;\n this.paddingLayout = paddingLayout;\n }\n }\n\n private List items = new ArrayList<>();\n\n private int paddingWidth;\n\n private MbwManager mbwManager;\n\n private AccountUseType accountUseType = AccountUseType.IN;\n\n public void setAccountUseType(AccountUseType accountUseType) {\n this.accountUseType = accountUseType;\n }\n\n public AccountAdapter(MbwManager mbwManager, List> accounts, int paddingWidth) {\n this.mbwManager = mbwManager;\n this.paddingWidth = paddingWidth;\n accounts = Utils.sortAccounts(accounts, mbwManager.getMetadataStorage());\n for (WalletAccount account : accounts) {\n if (account.isExchangeable()) {\n items.add(new Item(account, VIEW_TYPE_ITEM));\n }\n }\n }\n\n public Item getItem(int selectedItem) {\n return items.get(selectedItem);\n }\n\n public static class Item {\n\n public Item(WalletAccount account, int type) {\n this.type = type;\n this.account = account;\n }\n\n public int type;\n\n public WalletAccount account;\n }\n\n @Override\n public int findIndex(Object selected) {\n ", "post_mask_code": "\n return -1;\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n if (viewType == VIEW_TYPE_ITEM) {\n // create a new view\n View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_fee_lvl, parent, false);\n v.setBackgroundResource(accountUseType.background);\n ImageView imageView = v.findViewById(R.id.rectangle);\n imageView.setImageResource(accountUseType.indicatorImg);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imageView.getLayoutParams();\n layoutParams.gravity = accountUseType.gravity;\n layoutParams.height = parent.getResources().getDimensionPixelSize(accountUseType.heightRes);\n imageView.setLayoutParams(layoutParams);\n ViewHolder viewHolder = new ViewHolder(v);\n viewHolder.valueTextView.setMaxLines(1);\n return viewHolder;\n } else {\n View view = LayoutInflater.from(parent.getContext()).inflate(accountUseType.paddingLayout, parent, false);\n view.setBackgroundResource(accountUseType.background);\n return new PaddingViewHolder(view);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n super.onBindViewHolder(holder, position);\n if (getItemViewType(position) == VIEW_TYPE_ITEM) {\n ViewHolder viewHolder = (ViewHolder) holder;\n Item item = items.get(position);\n viewHolder.categoryTextView.setText(mbwManager.getMetadataStorage().getLabelByAccount(item.account.getId()));\n Denomination denomination = mbwManager.getDenomination(item.account.getCoinType());\n viewHolder.itemTextView.setText(ValueExtensionsKt.toStringWithUnit(item.account.getAccountBalance().confirmed, denomination));\n if (item.account.getReceiveAddress() != null) {\n viewHolder.valueTextView.setText(item.account.getReceiveAddress().toString());\n }\n } else {\n RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();\n layoutParams.width = paddingWidth;\n holder.itemView.setLayoutParams(layoutParams);\n holder.itemView.setVisibility(getItemCount() > 3 || position == 0 ? View.VISIBLE : View.INVISIBLE);\n }\n }\n\n private boolean trySettingReceivingAddress(ViewHolder viewHolder, BitcoinAddress receivingAddress) {\n if (receivingAddress != null) {\n viewHolder.valueTextView.setText(receivingAddress.toString());\n return true;\n }\n return false;\n }\n\n @Override\n public int getItemViewType(int position) {\n return items.get(position).type;\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n\n public TextView categoryTextView;\n\n public TextView itemTextView;\n\n public TextView valueTextView;\n\n public ViewHolder(View v) {\n super(v);\n categoryTextView = v.findViewById(R.id.categorytextView);\n itemTextView = v.findViewById(R.id.itemTextView);\n valueTextView = v.findViewById(R.id.valueTextView);\n }\n }\n\n public static class PaddingViewHolder extends RecyclerView.ViewHolder {\n\n public PaddingViewHolder(View v) {\n super(v);\n }\n }\n}\n"} {"task_id": "Java_815", "language": "Java", "task_type": "empty", "source_file": "java/github/mycelium-com/wallet-android/mbw/src/main/java/com/mycelium/wallet/external/changelly/AccountAdapter.java", "mask_start_position": 4720, "mask_end_position": 4720, "canonical_solution": "", "pre_mask_code": "package com.mycelium.wallet.external.changelly;\n\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.view.Gravity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.mrd.bitlib.model.BitcoinAddress;\nimport com.mycelium.view.Denomination;\nimport com.mycelium.wallet.MbwManager;\nimport com.mycelium.wallet.R;\nimport com.mycelium.wallet.Utils;\nimport com.mycelium.wallet.activity.send.view.SelectableRecyclerView;\nimport com.mycelium.wallet.activity.util.ValueExtensionsKt;\nimport com.mycelium.wapi.wallet.WalletAccount;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class AccountAdapter extends SelectableRecyclerView.SRVAdapter {\n\n public enum AccountUseType {\n\n OUT(R.drawable.sender_recyclerview_item_background_selector_red, R.drawable.recyclerview_item_bottom_rectangle_selector, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_rectangle_height, R.layout.list_item_padding_sending), IN(R.drawable.sender_recyclerview_item_background_selector2, R.drawable.recyclerview_item_top_rectangle_selector, Gravity.TOP | Gravity.CENTER_HORIZONTAL, R.dimen.recycler_item_triangle_height, R.layout.list_item_padding_receiving);\n\n public int background;\n\n public int gravity;\n\n public int heightRes;\n\n public int indicatorImg;\n\n public int paddingLayout;\n\n AccountUseType(int background, int indicatorImg, int gravity, int height, int paddingLayout) {\n this.background = background;\n this.indicatorImg = indicatorImg;\n this.gravity = gravity;\n this.heightRes = height;\n this.paddingLayout = paddingLayout;\n }\n }\n\n private List items = new ArrayList<>();\n\n private int paddingWidth;\n\n private MbwManager mbwManager;\n\n private AccountUseType accountUseType = AccountUseType.IN;\n\n public void setAccountUseType(AccountUseType accountUseType) {\n this.accountUseType = accountUseType;\n }\n\n public AccountAdapter(MbwManager mbwManager, List> accounts, int paddingWidth) {\n this.mbwManager = mbwManager;\n this.paddingWidth = paddingWidth;\n accounts = Utils.sortAccounts(accounts, mbwManager.getMetadataStorage());\n for (WalletAccount account : accounts) {\n if (account.isExchangeable()) {\n items.add(new Item(account, VIEW_TYPE_ITEM));\n }\n }\n }\n\n public Item getItem(int selectedItem) {\n return items.get(selectedItem);\n }\n\n public static class Item {\n\n public Item(WalletAccount account, int type) {\n this.type = type;\n this.account = account;\n }\n\n public int type;\n\n public WalletAccount account;\n }\n\n @Override\n public int findIndex(Object selected) {\n for (int i = 0; i < items.size(); i++) {\n Item item = items.get(i);\n if (item.account != null && item.account == selected) {\n return i;\n }\n }\n return -1;\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n if (viewType == VIEW_TYPE_ITEM) {\n // create a new view\n View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_fee_lvl, parent, false);\n v.setBackgroundResource(accountUseType.background);\n ImageView imageView = v.findViewById(R.id.rectangle);\n imageView.setImageResource(accountUseType.indicatorImg);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imageView.getLayoutParams();\n layoutParams.gravity = accountUseType.gravity;\n layoutParams.height = parent.getResources().getDimensionPixelSize(accountUseType.heightRes);\n imageView.setLayoutParams(layoutParams);\n ViewHolder viewHolder = new ViewHolder(v);\n viewHolder.valueTextView.setMaxLines(1);\n return viewHolder;\n } else {\n View view = LayoutInflater.from(parent.getContext()).inflate(accountUseType.paddingLayout, parent, false);\n view.setBackgroundResource(accountUseType.background);\n return new PaddingViewHolder(view);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n super.onBindViewHolder(holder, position);\n if (getItemViewType(position) == VIEW_TYPE_ITEM) {\n ViewHolder viewHolder = (ViewHolder) holder;\n Item ite", "post_mask_code": "m = items.get(position);\n viewHolder.categoryTextView.setText(mbwManager.getMetadataStorage().getLabelByAccount(item.account.getId()));\n Denomination denomination = mbwManager.getDenomination(item.account.getCoinType());\n viewHolder.itemTextView.setText(ValueExtensionsKt.toStringWithUnit(item.account.getAccountBalance().confirmed, denomination));\n if (item.account.getReceiveAddress() != null) {\n viewHolder.valueTextView.setText(item.account.getReceiveAddress().toString());\n }\n } else {\n RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();\n layoutParams.width = paddingWidth;\n holder.itemView.setLayoutParams(layoutParams);\n holder.itemView.setVisibility(getItemCount() > 3 || position == 0 ? View.VISIBLE : View.INVISIBLE);\n }\n }\n\n private boolean trySettingReceivingAddress(ViewHolder viewHolder, BitcoinAddress receivingAddress) {\n if (receivingAddress != null) {\n viewHolder.valueTextView.setText(receivingAddress.toString());\n return true;\n }\n return false;\n }\n\n @Override\n public int getItemViewType(int position) {\n return items.get(position).type;\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n\n public TextView categoryTextView;\n\n public TextView itemTextView;\n\n public TextView valueTextView;\n\n public ViewHolder(View v) {\n super(v);\n categoryTextView = v.findViewById(R.id.categorytextView);\n itemTextView = v.findViewById(R.id.itemTextView);\n valueTextView = v.findViewById(R.id.valueTextView);\n }\n }\n\n public static class PaddingViewHolder extends RecyclerView.ViewHolder {\n\n public PaddingViewHolder(View v) {\n super(v);\n }\n }\n}\n"} {"task_id": "Java_816", "language": "Java", "task_type": "empty", "source_file": "java/github/Talend/components/components/components-snowflake/components-snowflake-definition/src/main/java/org/talend/components/snowflake/tsnowflakeconnection/AuthenticationType.java", "mask_start_position": 224, "mask_end_position": 224, "canonical_solution": "", "pre_mask_code": "// This source code is available under agreement available at\n// %InstallDIR%\\features\\org.talend.rcp.branding.%PRODUCTNAME%\\%PRODUCTNAME%license.txt\n// You should have received a copy of the agreement\n// along with this pro", "post_mask_code": "gram; if not, write to Talend SA\n// 9 rue Pages 92150 Suresnes, France\npackage org.talend.components.snowflake.tsnowflakeconnection;\n\npublic enum AuthenticationType {\n\n BASIC, KEY_PAIR, OAUTH\n}\n"} {"task_id": "Java_817", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/sinnerschrader/aem-react/core/src/main/java/com/sinnerschrader/aem/react/loader/ScriptCollectionLoader.java", "mask_start_position": 297, "mask_end_position": 338, "canonical_solution": "public Iterator iterator();", "pre_mask_code": "package com.sinnerschrader.aem.react.loader;\n\nimport java.util.Iterator;\n\n/**\n * This loader returns all scripts that should be installed in the script\n * context.\n *\n * @author stemey\n */\npublic interface ScriptCollectionLoader {\n\n /**\n * get all scripts\n *\n * @return\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_818", "language": "Java", "task_type": "empty", "source_file": "java/github/sinnerschrader/aem-react/core/src/main/java/com/sinnerschrader/aem/react/loader/ScriptCollectionLoader.java", "mask_start_position": 225, "mask_end_position": 225, "canonical_solution": "", "pre_mask_code": "package com.sinnerschrader.aem.react.loader;\n\nimport java.util.Iterator;\n\n/**\n * This loader returns all scripts that should be installed in the script\n * context.\n *\n * @author stemey\n */\npublic interface ScriptCollectionLoa", "post_mask_code": "der {\n\n /**\n * get all scripts\n *\n * @return\n */\n public Iterator iterator();\n}\n"} {"task_id": "Java_819", "language": "Java", "task_type": "method_signature", "source_file": "java/github/opensearch-project/OpenSearch/server/src/main/java/org/opensearch/index/query/support/QueryParsers.java", "mask_start_position": 931, "mask_end_position": 1043, "canonical_solution": "public static void setRewriteMethod(MultiTermQuery query, @Nullable MultiTermQuery.RewriteMethod rewriteMethod) ", "pre_mask_code": "/*\n *\n * The OpenSearch Contributors require contributions made to\n */\npackage org.opensearch.index.query.support;\n\nimport org.apache.lucene.search.MultiTermQuery;\nimport org.opensearch.common.Nullable;\nimport org.opensearch.common.ParseField;\nimport org.opensearch.common.xcontent.DeprecationHandler;\n\npublic final class QueryParsers {\n\n public static final ParseField CONSTANT_SCORE = new ParseField(\"constant_score\");\n\n public static final ParseField SCORING_BOOLEAN = new ParseField(\"scoring_boolean\");\n\n public static final ParseField CONSTANT_SCORE_BOOLEAN = new ParseField(\"constant_score_boolean\");\n\n public static final ParseField TOP_TERMS = new ParseField(\"top_terms_\");\n\n public static final ParseField TOP_TERMS_BOOST = new ParseField(\"top_terms_boost_\");\n\n public static final ParseField TOP_TERMS_BLENDED_FREQS = new ParseField(\"top_terms_blended_freqs_\");\n\n private QueryParsers() {\n }\n\n ", "post_mask_code": "{\n if (rewriteMethod == null) {\n return;\n }\n query.setRewriteMethod(rewriteMethod);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, DeprecationHandler deprecationHandler) {\n return parseRewriteMethod(rewriteMethod, MultiTermQuery.CONSTANT_SCORE_REWRITE, deprecationHandler);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, @Nullable MultiTermQuery.RewriteMethod defaultRewriteMethod, DeprecationHandler deprecationHandler) {\n if (rewriteMethod == null) {\n return defaultRewriteMethod;\n }\n if (CONSTANT_SCORE.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_REWRITE;\n }\n if (SCORING_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.SCORING_BOOLEAN_REWRITE;\n }\n if (CONSTANT_SCORE_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE;\n }\n int firstDigit = -1;\n for (int i = 0; i < rewriteMethod.length(); ++i) {\n if (Character.isDigit(rewriteMethod.charAt(i))) {\n firstDigit = i;\n break;\n }\n }\n if (firstDigit >= 0) {\n final int size = Integer.parseInt(rewriteMethod.substring(firstDigit));\n String rewriteMethodName = rewriteMethod.substring(0, firstDigit);\n if (TOP_TERMS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BOOST.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BLENDED_FREQS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBlendedFreqScoringRewrite(size);\n }\n }\n throw new IllegalArgumentException(\"Failed to parse rewrite_method [\" + rewriteMethod + \"]\");\n }\n}\n"} {"task_id": "Java_820", "language": "Java", "task_type": "method_body", "source_file": "java/github/opensearch-project/OpenSearch/server/src/main/java/org/opensearch/index/query/support/QueryParsers.java", "mask_start_position": 1303, "mask_end_position": 1419, "canonical_solution": "{\n return parseRewriteMethod(rewriteMethod, MultiTermQuery.CONSTANT_SCORE_REWRITE, deprecationHandler);\n }", "pre_mask_code": "/*\n *\n * The OpenSearch Contributors require contributions made to\n */\npackage org.opensearch.index.query.support;\n\nimport org.apache.lucene.search.MultiTermQuery;\nimport org.opensearch.common.Nullable;\nimport org.opensearch.common.ParseField;\nimport org.opensearch.common.xcontent.DeprecationHandler;\n\npublic final class QueryParsers {\n\n public static final ParseField CONSTANT_SCORE = new ParseField(\"constant_score\");\n\n public static final ParseField SCORING_BOOLEAN = new ParseField(\"scoring_boolean\");\n\n public static final ParseField CONSTANT_SCORE_BOOLEAN = new ParseField(\"constant_score_boolean\");\n\n public static final ParseField TOP_TERMS = new ParseField(\"top_terms_\");\n\n public static final ParseField TOP_TERMS_BOOST = new ParseField(\"top_terms_boost_\");\n\n public static final ParseField TOP_TERMS_BLENDED_FREQS = new ParseField(\"top_terms_blended_freqs_\");\n\n private QueryParsers() {\n }\n\n public static void setRewriteMethod(MultiTermQuery query, @Nullable MultiTermQuery.RewriteMethod rewriteMethod) {\n if (rewriteMethod == null) {\n return;\n }\n query.setRewriteMethod(rewriteMethod);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, DeprecationHandler deprecationHandler) ", "post_mask_code": "\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, @Nullable MultiTermQuery.RewriteMethod defaultRewriteMethod, DeprecationHandler deprecationHandler) {\n if (rewriteMethod == null) {\n return defaultRewriteMethod;\n }\n if (CONSTANT_SCORE.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_REWRITE;\n }\n if (SCORING_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.SCORING_BOOLEAN_REWRITE;\n }\n if (CONSTANT_SCORE_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE;\n }\n int firstDigit = -1;\n for (int i = 0; i < rewriteMethod.length(); ++i) {\n if (Character.isDigit(rewriteMethod.charAt(i))) {\n firstDigit = i;\n break;\n }\n }\n if (firstDigit >= 0) {\n final int size = Integer.parseInt(rewriteMethod.substring(firstDigit));\n String rewriteMethodName = rewriteMethod.substring(0, firstDigit);\n if (TOP_TERMS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BOOST.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BLENDED_FREQS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBlendedFreqScoringRewrite(size);\n }\n }\n throw new IllegalArgumentException(\"Failed to parse rewrite_method [\" + rewriteMethod + \"]\");\n }\n}\n"} {"task_id": "Java_821", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/opensearch-project/OpenSearch/server/src/main/java/org/opensearch/index/query/support/QueryParsers.java", "mask_start_position": 1620, "mask_end_position": 1988, "canonical_solution": "\n if (rewriteMethod == null) {\n return defaultRewriteMethod;\n }\n if (CONSTANT_SCORE.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_REWRITE;\n }\n if (SCORING_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.SCORING_BOOLEAN_REWRITE;\n }", "pre_mask_code": "/*\n *\n * The OpenSearch Contributors require contributions made to\n */\npackage org.opensearch.index.query.support;\n\nimport org.apache.lucene.search.MultiTermQuery;\nimport org.opensearch.common.Nullable;\nimport org.opensearch.common.ParseField;\nimport org.opensearch.common.xcontent.DeprecationHandler;\n\npublic final class QueryParsers {\n\n public static final ParseField CONSTANT_SCORE = new ParseField(\"constant_score\");\n\n public static final ParseField SCORING_BOOLEAN = new ParseField(\"scoring_boolean\");\n\n public static final ParseField CONSTANT_SCORE_BOOLEAN = new ParseField(\"constant_score_boolean\");\n\n public static final ParseField TOP_TERMS = new ParseField(\"top_terms_\");\n\n public static final ParseField TOP_TERMS_BOOST = new ParseField(\"top_terms_boost_\");\n\n public static final ParseField TOP_TERMS_BLENDED_FREQS = new ParseField(\"top_terms_blended_freqs_\");\n\n private QueryParsers() {\n }\n\n public static void setRewriteMethod(MultiTermQuery query, @Nullable MultiTermQuery.RewriteMethod rewriteMethod) {\n if (rewriteMethod == null) {\n return;\n }\n query.setRewriteMethod(rewriteMethod);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, DeprecationHandler deprecationHandler) {\n return parseRewriteMethod(rewriteMethod, MultiTermQuery.CONSTANT_SCORE_REWRITE, deprecationHandler);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, @Nullable MultiTermQuery.RewriteMethod defaultRewriteMethod, DeprecationHandler deprecationHandler) {", "post_mask_code": "\n if (CONSTANT_SCORE_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE;\n }\n int firstDigit = -1;\n for (int i = 0; i < rewriteMethod.length(); ++i) {\n if (Character.isDigit(rewriteMethod.charAt(i))) {\n firstDigit = i;\n break;\n }\n }\n if (firstDigit >= 0) {\n final int size = Integer.parseInt(rewriteMethod.substring(firstDigit));\n String rewriteMethodName = rewriteMethod.substring(0, firstDigit);\n if (TOP_TERMS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BOOST.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BLENDED_FREQS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBlendedFreqScoringRewrite(size);\n }\n }\n throw new IllegalArgumentException(\"Failed to parse rewrite_method [\" + rewriteMethod + \"]\");\n }\n}\n"} {"task_id": "Java_822", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/opensearch-project/OpenSearch/server/src/main/java/org/opensearch/index/query/support/QueryParsers.java", "mask_start_position": 1997, "mask_end_position": 2372, "canonical_solution": "if (CONSTANT_SCORE_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE;\n }\n int firstDigit = -1;\n for (int i = 0; i < rewriteMethod.length(); ++i) {\n if (Character.isDigit(rewriteMethod.charAt(i))) {\n firstDigit = i;\n break;\n }\n }", "pre_mask_code": "/*\n *\n * The OpenSearch Contributors require contributions made to\n */\npackage org.opensearch.index.query.support;\n\nimport org.apache.lucene.search.MultiTermQuery;\nimport org.opensearch.common.Nullable;\nimport org.opensearch.common.ParseField;\nimport org.opensearch.common.xcontent.DeprecationHandler;\n\npublic final class QueryParsers {\n\n public static final ParseField CONSTANT_SCORE = new ParseField(\"constant_score\");\n\n public static final ParseField SCORING_BOOLEAN = new ParseField(\"scoring_boolean\");\n\n public static final ParseField CONSTANT_SCORE_BOOLEAN = new ParseField(\"constant_score_boolean\");\n\n public static final ParseField TOP_TERMS = new ParseField(\"top_terms_\");\n\n public static final ParseField TOP_TERMS_BOOST = new ParseField(\"top_terms_boost_\");\n\n public static final ParseField TOP_TERMS_BLENDED_FREQS = new ParseField(\"top_terms_blended_freqs_\");\n\n private QueryParsers() {\n }\n\n public static void setRewriteMethod(MultiTermQuery query, @Nullable MultiTermQuery.RewriteMethod rewriteMethod) {\n if (rewriteMethod == null) {\n return;\n }\n query.setRewriteMethod(rewriteMethod);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, DeprecationHandler deprecationHandler) {\n return parseRewriteMethod(rewriteMethod, MultiTermQuery.CONSTANT_SCORE_REWRITE, deprecationHandler);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, @Nullable MultiTermQuery.RewriteMethod defaultRewriteMethod, DeprecationHandler deprecationHandler) {\n if (rewriteMethod == null) {\n return defaultRewriteMethod;\n }\n if (CONSTANT_SCORE.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_REWRITE;\n }\n if (SCORING_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.SCORING_BOOLEAN_REWRITE;\n }\n ", "post_mask_code": "\n if (firstDigit >= 0) {\n final int size = Integer.parseInt(rewriteMethod.substring(firstDigit));\n String rewriteMethodName = rewriteMethod.substring(0, firstDigit);\n if (TOP_TERMS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BOOST.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BLENDED_FREQS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBlendedFreqScoringRewrite(size);\n }\n }\n throw new IllegalArgumentException(\"Failed to parse rewrite_method [\" + rewriteMethod + \"]\");\n }\n}\n"} {"task_id": "Java_823", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/opensearch-project/OpenSearch/server/src/main/java/org/opensearch/index/query/support/QueryParsers.java", "mask_start_position": 2381, "mask_end_position": 3221, "canonical_solution": "if (firstDigit >= 0) {\n final int size = Integer.parseInt(rewriteMethod.substring(firstDigit));\n String rewriteMethodName = rewriteMethod.substring(0, firstDigit);\n if (TOP_TERMS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BOOST.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BLENDED_FREQS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBlendedFreqScoringRewrite(size);\n }\n }\n throw new IllegalArgumentException(\"Failed to parse rewrite_method [\" + rewriteMethod + \"]\");\n }", "pre_mask_code": "/*\n *\n * The OpenSearch Contributors require contributions made to\n */\npackage org.opensearch.index.query.support;\n\nimport org.apache.lucene.search.MultiTermQuery;\nimport org.opensearch.common.Nullable;\nimport org.opensearch.common.ParseField;\nimport org.opensearch.common.xcontent.DeprecationHandler;\n\npublic final class QueryParsers {\n\n public static final ParseField CONSTANT_SCORE = new ParseField(\"constant_score\");\n\n public static final ParseField SCORING_BOOLEAN = new ParseField(\"scoring_boolean\");\n\n public static final ParseField CONSTANT_SCORE_BOOLEAN = new ParseField(\"constant_score_boolean\");\n\n public static final ParseField TOP_TERMS = new ParseField(\"top_terms_\");\n\n public static final ParseField TOP_TERMS_BOOST = new ParseField(\"top_terms_boost_\");\n\n public static final ParseField TOP_TERMS_BLENDED_FREQS = new ParseField(\"top_terms_blended_freqs_\");\n\n private QueryParsers() {\n }\n\n public static void setRewriteMethod(MultiTermQuery query, @Nullable MultiTermQuery.RewriteMethod rewriteMethod) {\n if (rewriteMethod == null) {\n return;\n }\n query.setRewriteMethod(rewriteMethod);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, DeprecationHandler deprecationHandler) {\n return parseRewriteMethod(rewriteMethod, MultiTermQuery.CONSTANT_SCORE_REWRITE, deprecationHandler);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, @Nullable MultiTermQuery.RewriteMethod defaultRewriteMethod, DeprecationHandler deprecationHandler) {\n if (rewriteMethod == null) {\n return defaultRewriteMethod;\n }\n if (CONSTANT_SCORE.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_REWRITE;\n }\n if (SCORING_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.SCORING_BOOLEAN_REWRITE;\n }\n if (CONSTANT_SCORE_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE;\n }\n int firstDigit = -1;\n for (int i = 0; i < rewriteMethod.length(); ++i) {\n if (Character.isDigit(rewriteMethod.charAt(i))) {\n firstDigit = i;\n break;\n }\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_824", "language": "Java", "task_type": "single_line", "source_file": "java/github/opensearch-project/OpenSearch/server/src/main/java/org/opensearch/index/query/support/QueryParsers.java", "mask_start_position": 2171, "mask_end_position": 2172, "canonical_solution": ";", "pre_mask_code": "/*\n *\n * The OpenSearch Contributors require contributions made to\n */\npackage org.opensearch.index.query.support;\n\nimport org.apache.lucene.search.MultiTermQuery;\nimport org.opensearch.common.Nullable;\nimport org.opensearch.common.ParseField;\nimport org.opensearch.common.xcontent.DeprecationHandler;\n\npublic final class QueryParsers {\n\n public static final ParseField CONSTANT_SCORE = new ParseField(\"constant_score\");\n\n public static final ParseField SCORING_BOOLEAN = new ParseField(\"scoring_boolean\");\n\n public static final ParseField CONSTANT_SCORE_BOOLEAN = new ParseField(\"constant_score_boolean\");\n\n public static final ParseField TOP_TERMS = new ParseField(\"top_terms_\");\n\n public static final ParseField TOP_TERMS_BOOST = new ParseField(\"top_terms_boost_\");\n\n public static final ParseField TOP_TERMS_BLENDED_FREQS = new ParseField(\"top_terms_blended_freqs_\");\n\n private QueryParsers() {\n }\n\n public static void setRewriteMethod(MultiTermQuery query, @Nullable MultiTermQuery.RewriteMethod rewriteMethod) {\n if (rewriteMethod == null) {\n return;\n }\n query.setRewriteMethod(rewriteMethod);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, DeprecationHandler deprecationHandler) {\n return parseRewriteMethod(rewriteMethod, MultiTermQuery.CONSTANT_SCORE_REWRITE, deprecationHandler);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, @Nullable MultiTermQuery.RewriteMethod defaultRewriteMethod, DeprecationHandler deprecationHandler) {\n if (rewriteMethod == null) {\n return defaultRewriteMethod;\n }\n if (CONSTANT_SCORE.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_REWRITE;\n }\n if (SCORING_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.SCORING_BOOLEAN_REWRITE;\n }\n if (CONSTANT_SCORE_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE;\n }\n int firstDigit = -1", "post_mask_code": "\n for (int i = 0; i < rewriteMethod.length(); ++i) {\n if (Character.isDigit(rewriteMethod.charAt(i))) {\n firstDigit = i;\n break;\n }\n }\n if (firstDigit >= 0) {\n final int size = Integer.parseInt(rewriteMethod.substring(firstDigit));\n String rewriteMethodName = rewriteMethod.substring(0, firstDigit);\n if (TOP_TERMS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BOOST.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BLENDED_FREQS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBlendedFreqScoringRewrite(size);\n }\n }\n throw new IllegalArgumentException(\"Failed to parse rewrite_method [\" + rewriteMethod + \"]\");\n }\n}\n"} {"task_id": "Java_825", "language": "Java", "task_type": "if_statement", "source_file": "java/github/opensearch-project/OpenSearch/server/src/main/java/org/opensearch/index/query/support/QueryParsers.java", "mask_start_position": 2751, "mask_end_position": 2918, "canonical_solution": "if (TOP_TERMS_BOOST.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(size);\n }", "pre_mask_code": "/*\n *\n * The OpenSearch Contributors require contributions made to\n */\npackage org.opensearch.index.query.support;\n\nimport org.apache.lucene.search.MultiTermQuery;\nimport org.opensearch.common.Nullable;\nimport org.opensearch.common.ParseField;\nimport org.opensearch.common.xcontent.DeprecationHandler;\n\npublic final class QueryParsers {\n\n public static final ParseField CONSTANT_SCORE = new ParseField(\"constant_score\");\n\n public static final ParseField SCORING_BOOLEAN = new ParseField(\"scoring_boolean\");\n\n public static final ParseField CONSTANT_SCORE_BOOLEAN = new ParseField(\"constant_score_boolean\");\n\n public static final ParseField TOP_TERMS = new ParseField(\"top_terms_\");\n\n public static final ParseField TOP_TERMS_BOOST = new ParseField(\"top_terms_boost_\");\n\n public static final ParseField TOP_TERMS_BLENDED_FREQS = new ParseField(\"top_terms_blended_freqs_\");\n\n private QueryParsers() {\n }\n\n public static void setRewriteMethod(MultiTermQuery query, @Nullable MultiTermQuery.RewriteMethod rewriteMethod) {\n if (rewriteMethod == null) {\n return;\n }\n query.setRewriteMethod(rewriteMethod);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, DeprecationHandler deprecationHandler) {\n return parseRewriteMethod(rewriteMethod, MultiTermQuery.CONSTANT_SCORE_REWRITE, deprecationHandler);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, @Nullable MultiTermQuery.RewriteMethod defaultRewriteMethod, DeprecationHandler deprecationHandler) {\n if (rewriteMethod == null) {\n return defaultRewriteMethod;\n }\n if (CONSTANT_SCORE.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_REWRITE;\n }\n if (SCORING_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.SCORING_BOOLEAN_REWRITE;\n }\n if (CONSTANT_SCORE_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE;\n }\n int firstDigit = -1;\n for (int i = 0; i < rewriteMethod.length(); ++i) {\n if (Character.isDigit(rewriteMethod.charAt(i))) {\n firstDigit = i;\n break;\n }\n }\n if (firstDigit >= 0) {\n final int size = Integer.parseInt(rewriteMethod.substring(firstDigit));\n String rewriteMethodName = rewriteMethod.substring(0, firstDigit);\n if (TOP_TERMS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(size);\n }\n ", "post_mask_code": "\n if (TOP_TERMS_BLENDED_FREQS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBlendedFreqScoringRewrite(size);\n }\n }\n throw new IllegalArgumentException(\"Failed to parse rewrite_method [\" + rewriteMethod + \"]\");\n }\n}\n"} {"task_id": "Java_826", "language": "Java", "task_type": "for_statement", "source_file": "java/github/opensearch-project/OpenSearch/server/src/main/java/org/opensearch/index/query/support/QueryParsers.java", "mask_start_position": 2181, "mask_end_position": 2372, "canonical_solution": "for (int i = 0; i < rewriteMethod.length(); ++i) {\n if (Character.isDigit(rewriteMethod.charAt(i))) {\n firstDigit = i;\n break;\n }\n }", "pre_mask_code": "/*\n *\n * The OpenSearch Contributors require contributions made to\n */\npackage org.opensearch.index.query.support;\n\nimport org.apache.lucene.search.MultiTermQuery;\nimport org.opensearch.common.Nullable;\nimport org.opensearch.common.ParseField;\nimport org.opensearch.common.xcontent.DeprecationHandler;\n\npublic final class QueryParsers {\n\n public static final ParseField CONSTANT_SCORE = new ParseField(\"constant_score\");\n\n public static final ParseField SCORING_BOOLEAN = new ParseField(\"scoring_boolean\");\n\n public static final ParseField CONSTANT_SCORE_BOOLEAN = new ParseField(\"constant_score_boolean\");\n\n public static final ParseField TOP_TERMS = new ParseField(\"top_terms_\");\n\n public static final ParseField TOP_TERMS_BOOST = new ParseField(\"top_terms_boost_\");\n\n public static final ParseField TOP_TERMS_BLENDED_FREQS = new ParseField(\"top_terms_blended_freqs_\");\n\n private QueryParsers() {\n }\n\n public static void setRewriteMethod(MultiTermQuery query, @Nullable MultiTermQuery.RewriteMethod rewriteMethod) {\n if (rewriteMethod == null) {\n return;\n }\n query.setRewriteMethod(rewriteMethod);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, DeprecationHandler deprecationHandler) {\n return parseRewriteMethod(rewriteMethod, MultiTermQuery.CONSTANT_SCORE_REWRITE, deprecationHandler);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, @Nullable MultiTermQuery.RewriteMethod defaultRewriteMethod, DeprecationHandler deprecationHandler) {\n if (rewriteMethod == null) {\n return defaultRewriteMethod;\n }\n if (CONSTANT_SCORE.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_REWRITE;\n }\n if (SCORING_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.SCORING_BOOLEAN_REWRITE;\n }\n if (CONSTANT_SCORE_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE;\n }\n int firstDigit = -1;\n ", "post_mask_code": "\n if (firstDigit >= 0) {\n final int size = Integer.parseInt(rewriteMethod.substring(firstDigit));\n String rewriteMethodName = rewriteMethod.substring(0, firstDigit);\n if (TOP_TERMS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BOOST.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BLENDED_FREQS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBlendedFreqScoringRewrite(size);\n }\n }\n throw new IllegalArgumentException(\"Failed to parse rewrite_method [\" + rewriteMethod + \"]\");\n }\n}\n"} {"task_id": "Java_827", "language": "Java", "task_type": "empty", "source_file": "java/github/opensearch-project/OpenSearch/server/src/main/java/org/opensearch/index/query/support/QueryParsers.java", "mask_start_position": 2485, "mask_end_position": 2485, "canonical_solution": "", "pre_mask_code": "/*\n *\n * The OpenSearch Contributors require contributions made to\n */\npackage org.opensearch.index.query.support;\n\nimport org.apache.lucene.search.MultiTermQuery;\nimport org.opensearch.common.Nullable;\nimport org.opensearch.common.ParseField;\nimport org.opensearch.common.xcontent.DeprecationHandler;\n\npublic final class QueryParsers {\n\n public static final ParseField CONSTANT_SCORE = new ParseField(\"constant_score\");\n\n public static final ParseField SCORING_BOOLEAN = new ParseField(\"scoring_boolean\");\n\n public static final ParseField CONSTANT_SCORE_BOOLEAN = new ParseField(\"constant_score_boolean\");\n\n public static final ParseField TOP_TERMS = new ParseField(\"top_terms_\");\n\n public static final ParseField TOP_TERMS_BOOST = new ParseField(\"top_terms_boost_\");\n\n public static final ParseField TOP_TERMS_BLENDED_FREQS = new ParseField(\"top_terms_blended_freqs_\");\n\n private QueryParsers() {\n }\n\n public static void setRewriteMethod(MultiTermQuery query, @Nullable MultiTermQuery.RewriteMethod rewriteMethod) {\n if (rewriteMethod == null) {\n return;\n }\n query.setRewriteMethod(rewriteMethod);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, DeprecationHandler deprecationHandler) {\n return parseRewriteMethod(rewriteMethod, MultiTermQuery.CONSTANT_SCORE_REWRITE, deprecationHandler);\n }\n\n public static MultiTermQuery.RewriteMethod parseRewriteMethod(@Nullable String rewriteMethod, @Nullable MultiTermQuery.RewriteMethod defaultRewriteMethod, DeprecationHandler deprecationHandler) {\n if (rewriteMethod == null) {\n return defaultRewriteMethod;\n }\n if (CONSTANT_SCORE.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_REWRITE;\n }\n if (SCORING_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.SCORING_BOOLEAN_REWRITE;\n }\n if (CONSTANT_SCORE_BOOLEAN.match(rewriteMethod, deprecationHandler)) {\n return MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE;\n }\n int firstDigit = -1;\n for (int i = 0; i < rewriteMethod.length(); ++i) {\n if (Character.isDigit(rewriteMethod.charAt(i))) {\n firstDigit = i;\n break;\n }\n }\n if (firstDigit >= 0) {\n final int size = Integer.parseInt(rewriteMethod.substring(firstDigit)", "post_mask_code": ");\n String rewriteMethodName = rewriteMethod.substring(0, firstDigit);\n if (TOP_TERMS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BOOST.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(size);\n }\n if (TOP_TERMS_BLENDED_FREQS.match(rewriteMethodName, deprecationHandler)) {\n return new MultiTermQuery.TopTermsBlendedFreqScoringRewrite(size);\n }\n }\n throw new IllegalArgumentException(\"Failed to parse rewrite_method [\" + rewriteMethod + \"]\");\n }\n}\n"} {"task_id": "Java_828", "language": "Java", "task_type": "empty", "source_file": "java/github/polarking/jss7-attack-simulator/inap/inap-api/src/main/java/org/mobicents/protocols/ss7/inap/api/EsiBcsm/OrigAttemptAuthorized.java", "mask_start_position": 90, "mask_end_position": 90, "canonical_solution": "", "pre_mask_code": "/*\n * TeleStax, Open Source Cloud Communications\n * full listing of individual contributor", "post_mask_code": "s.\n *\n */\npackage org.mobicents.protocols.ss7.inap.api.EsiBcsm;\n\nimport java.io.Serializable;\n\n/**\n * \n * origAttemptAuthorized [16] SEQUENCE {\n * -- no specific info defined\n * ...\n * },\n * \n *\n * @author sergey vetyutnev\n */\npublic interface OrigAttemptAuthorized extends Serializable {\n}\n"} {"task_id": "Java_829", "language": "Java", "task_type": "method_signature", "source_file": "java/github/likaiyuan559/TouchEffects/toucheffectslib/src/main/java/com/lky/toucheffectsmodule/effects_adapter/TouchShakeAdapter.java", "mask_start_position": 1810, "mask_end_position": 1876, "canonical_solution": "@Override\n protected Animator createExtinctAnimator(View view) ", "pre_mask_code": "package com.lky.toucheffectsmodule.effects_adapter;\n\nimport android.animation.Animator;\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.util.AttributeSet;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport com.lky.toucheffectsmodule.R;\n\npublic class TouchShakeAdapter extends EffectsAdapter {\n\n private float mTranslateValue;\n\n @Override\n public void initAttr(Context context, AttributeSet attrs) {\n TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TouchEffectsView);\n mAnimationDuration = ta.getResourceId(R.styleable.TouchEffectsView_animation_duration, 150);\n }\n\n @Override\n public void runAnimator(View view, Canvas canvas) {\n canvas.translate(view.getWidth() * mTranslateValue, 0);\n }\n\n @Override\n public void dispatchDraw(View view, Canvas canvas) {\n }\n\n @Override\n public void drawForeground(View view, Canvas canvas) {\n }\n\n @Override\n public boolean onTouch(View view, MotionEvent motionEvent, View.OnClickListener onClickListener, View.OnLongClickListener onLongClickListener) {\n switch(motionEvent.getAction()) {\n case MotionEvent.ACTION_DOWN:\n engineAnimator(view);\n break;\n }\n return false;\n }\n\n @Override\n protected Animator createEngineAnimator(View view) {\n ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, -0.1f, 0f, 0.1f, 0f, -0.1f, 0f);\n valueAnimator.setDuration(mAnimationDuration);\n valueAnimator.addUpdateListener(animation -> {\n mTranslateValue = (float) animation.getAnimatedValue();\n view.invalidate();\n });\n return valueAnimator;\n }\n\n ", "post_mask_code": "{\n return null;\n }\n}\n"} {"task_id": "Java_830", "language": "Java", "task_type": "method_body", "source_file": "java/github/likaiyuan559/TouchEffects/toucheffectslib/src/main/java/com/lky/toucheffectsmodule/effects_adapter/TouchShakeAdapter.java", "mask_start_position": 1876, "mask_end_position": 1904, "canonical_solution": "{\n return null;\n }", "pre_mask_code": "package com.lky.toucheffectsmodule.effects_adapter;\n\nimport android.animation.Animator;\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.util.AttributeSet;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport com.lky.toucheffectsmodule.R;\n\npublic class TouchShakeAdapter extends EffectsAdapter {\n\n private float mTranslateValue;\n\n @Override\n public void initAttr(Context context, AttributeSet attrs) {\n TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TouchEffectsView);\n mAnimationDuration = ta.getResourceId(R.styleable.TouchEffectsView_animation_duration, 150);\n }\n\n @Override\n public void runAnimator(View view, Canvas canvas) {\n canvas.translate(view.getWidth() * mTranslateValue, 0);\n }\n\n @Override\n public void dispatchDraw(View view, Canvas canvas) {\n }\n\n @Override\n public void drawForeground(View view, Canvas canvas) {\n }\n\n @Override\n public boolean onTouch(View view, MotionEvent motionEvent, View.OnClickListener onClickListener, View.OnLongClickListener onLongClickListener) {\n switch(motionEvent.getAction()) {\n case MotionEvent.ACTION_DOWN:\n engineAnimator(view);\n break;\n }\n return false;\n }\n\n @Override\n protected Animator createEngineAnimator(View view) {\n ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, -0.1f, 0f, 0.1f, 0f, -0.1f, 0f);\n valueAnimator.setDuration(mAnimationDuration);\n valueAnimator.addUpdateListener(animation -> {\n mTranslateValue = (float) animation.getAnimatedValue();\n view.invalidate();\n });\n return valueAnimator;\n }\n\n @Override\n protected Animator createExtinctAnimator(View view) ", "post_mask_code": "\n}\n"} {"task_id": "Java_831", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/likaiyuan559/TouchEffects/toucheffectslib/src/main/java/com/lky/toucheffectsmodule/effects_adapter/TouchShakeAdapter.java", "mask_start_position": 1195, "mask_end_position": 1350, "canonical_solution": "\n switch(motionEvent.getAction()) {\n case MotionEvent.ACTION_DOWN:\n engineAnimator(view);\n break;\n }", "pre_mask_code": "package com.lky.toucheffectsmodule.effects_adapter;\n\nimport android.animation.Animator;\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.util.AttributeSet;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport com.lky.toucheffectsmodule.R;\n\npublic class TouchShakeAdapter extends EffectsAdapter {\n\n private float mTranslateValue;\n\n @Override\n public void initAttr(Context context, AttributeSet attrs) {\n TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TouchEffectsView);\n mAnimationDuration = ta.getResourceId(R.styleable.TouchEffectsView_animation_duration, 150);\n }\n\n @Override\n public void runAnimator(View view, Canvas canvas) {\n canvas.translate(view.getWidth() * mTranslateValue, 0);\n }\n\n @Override\n public void dispatchDraw(View view, Canvas canvas) {\n }\n\n @Override\n public void drawForeground(View view, Canvas canvas) {\n }\n\n @Override\n public boolean onTouch(View view, MotionEvent motionEvent, View.OnClickListener onClickListener, View.OnLongClickListener onLongClickListener) {", "post_mask_code": "\n return false;\n }\n\n @Override\n protected Animator createEngineAnimator(View view) {\n ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, -0.1f, 0f, 0.1f, 0f, -0.1f, 0f);\n valueAnimator.setDuration(mAnimationDuration);\n valueAnimator.addUpdateListener(animation -> {\n mTranslateValue = (float) animation.getAnimatedValue();\n view.invalidate();\n });\n return valueAnimator;\n }\n\n @Override\n protected Animator createExtinctAnimator(View view) {\n return null;\n }\n}\n"} {"task_id": "Java_832", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/likaiyuan559/TouchEffects/toucheffectslib/src/main/java/com/lky/toucheffectsmodule/effects_adapter/TouchShakeAdapter.java", "mask_start_position": 1359, "mask_end_position": 1372, "canonical_solution": "return false;", "pre_mask_code": "package com.lky.toucheffectsmodule.effects_adapter;\n\nimport android.animation.Animator;\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.util.AttributeSet;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport com.lky.toucheffectsmodule.R;\n\npublic class TouchShakeAdapter extends EffectsAdapter {\n\n private float mTranslateValue;\n\n @Override\n public void initAttr(Context context, AttributeSet attrs) {\n TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TouchEffectsView);\n mAnimationDuration = ta.getResourceId(R.styleable.TouchEffectsView_animation_duration, 150);\n }\n\n @Override\n public void runAnimator(View view, Canvas canvas) {\n canvas.translate(view.getWidth() * mTranslateValue, 0);\n }\n\n @Override\n public void dispatchDraw(View view, Canvas canvas) {\n }\n\n @Override\n public void drawForeground(View view, Canvas canvas) {\n }\n\n @Override\n public boolean onTouch(View view, MotionEvent motionEvent, View.OnClickListener onClickListener, View.OnLongClickListener onLongClickListener) {\n switch(motionEvent.getAction()) {\n case MotionEvent.ACTION_DOWN:\n engineAnimator(view);\n break;\n }\n ", "post_mask_code": "\n }\n\n @Override\n protected Animator createEngineAnimator(View view) {\n ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, -0.1f, 0f, 0.1f, 0f, -0.1f, 0f);\n valueAnimator.setDuration(mAnimationDuration);\n valueAnimator.addUpdateListener(animation -> {\n mTranslateValue = (float) animation.getAnimatedValue();\n view.invalidate();\n });\n return valueAnimator;\n }\n\n @Override\n protected Animator createExtinctAnimator(View view) {\n return null;\n }\n}\n"} {"task_id": "Java_833", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/likaiyuan559/TouchEffects/toucheffectslib/src/main/java/com/lky/toucheffectsmodule/effects_adapter/TouchShakeAdapter.java", "mask_start_position": 1377, "mask_end_position": 1378, "canonical_solution": "}", "pre_mask_code": "package com.lky.toucheffectsmodule.effects_adapter;\n\nimport android.animation.Animator;\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.util.AttributeSet;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport com.lky.toucheffectsmodule.R;\n\npublic class TouchShakeAdapter extends EffectsAdapter {\n\n private float mTranslateValue;\n\n @Override\n public void initAttr(Context context, AttributeSet attrs) {\n TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TouchEffectsView);\n mAnimationDuration = ta.getResourceId(R.styleable.TouchEffectsView_animation_duration, 150);\n }\n\n @Override\n public void runAnimator(View view, Canvas canvas) {\n canvas.translate(view.getWidth() * mTranslateValue, 0);\n }\n\n @Override\n public void dispatchDraw(View view, Canvas canvas) {\n }\n\n @Override\n public void drawForeground(View view, Canvas canvas) {\n }\n\n @Override\n public boolean onTouch(View view, MotionEvent motionEvent, View.OnClickListener onClickListener, View.OnLongClickListener onLongClickListener) {\n switch(motionEvent.getAction()) {\n case MotionEvent.ACTION_DOWN:\n engineAnimator(view);\n break;\n }\n return false;\n ", "post_mask_code": "\n\n @Override\n protected Animator createEngineAnimator(View view) {\n ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, -0.1f, 0f, 0.1f, 0f, -0.1f, 0f);\n valueAnimator.setDuration(mAnimationDuration);\n valueAnimator.addUpdateListener(animation -> {\n mTranslateValue = (float) animation.getAnimatedValue();\n view.invalidate();\n });\n return valueAnimator;\n }\n\n @Override\n protected Animator createExtinctAnimator(View view) {\n return null;\n }\n}\n"} {"task_id": "Java_834", "language": "Java", "task_type": "single_line", "source_file": "java/github/likaiyuan559/TouchEffects/toucheffectslib/src/main/java/com/lky/toucheffectsmodule/effects_adapter/TouchShakeAdapter.java", "mask_start_position": 565, "mask_end_position": 625, "canonical_solution": "obtainStyledAttributes(attrs, R.styleable.TouchEffectsView);", "pre_mask_code": "package com.lky.toucheffectsmodule.effects_adapter;\n\nimport android.animation.Animator;\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.util.AttributeSet;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport com.lky.toucheffectsmodule.R;\n\npublic class TouchShakeAdapter extends EffectsAdapter {\n\n private float mTranslateValue;\n\n @Override\n public void initAttr(Context context, AttributeSet attrs) {\n TypedArray ta = context.", "post_mask_code": "\n mAnimationDuration = ta.getResourceId(R.styleable.TouchEffectsView_animation_duration, 150);\n }\n\n @Override\n public void runAnimator(View view, Canvas canvas) {\n canvas.translate(view.getWidth() * mTranslateValue, 0);\n }\n\n @Override\n public void dispatchDraw(View view, Canvas canvas) {\n }\n\n @Override\n public void drawForeground(View view, Canvas canvas) {\n }\n\n @Override\n public boolean onTouch(View view, MotionEvent motionEvent, View.OnClickListener onClickListener, View.OnLongClickListener onLongClickListener) {\n switch(motionEvent.getAction()) {\n case MotionEvent.ACTION_DOWN:\n engineAnimator(view);\n break;\n }\n return false;\n }\n\n @Override\n protected Animator createEngineAnimator(View view) {\n ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, -0.1f, 0f, 0.1f, 0f, -0.1f, 0f);\n valueAnimator.setDuration(mAnimationDuration);\n valueAnimator.addUpdateListener(animation -> {\n mTranslateValue = (float) animation.getAnimatedValue();\n view.invalidate();\n });\n return valueAnimator;\n }\n\n @Override\n protected Animator createExtinctAnimator(View view) {\n return null;\n }\n}\n"} {"task_id": "Java_835", "language": "Java", "task_type": "switch_case", "source_file": "java/github/likaiyuan559/TouchEffects/toucheffectslib/src/main/java/com/lky/toucheffectsmodule/effects_adapter/TouchShakeAdapter.java", "mask_start_position": 1204, "mask_end_position": 1350, "canonical_solution": "switch(motionEvent.getAction()) {\n case MotionEvent.ACTION_DOWN:\n engineAnimator(view);\n break;\n }", "pre_mask_code": "package com.lky.toucheffectsmodule.effects_adapter;\n\nimport android.animation.Animator;\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.util.AttributeSet;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport com.lky.toucheffectsmodule.R;\n\npublic class TouchShakeAdapter extends EffectsAdapter {\n\n private float mTranslateValue;\n\n @Override\n public void initAttr(Context context, AttributeSet attrs) {\n TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TouchEffectsView);\n mAnimationDuration = ta.getResourceId(R.styleable.TouchEffectsView_animation_duration, 150);\n }\n\n @Override\n public void runAnimator(View view, Canvas canvas) {\n canvas.translate(view.getWidth() * mTranslateValue, 0);\n }\n\n @Override\n public void dispatchDraw(View view, Canvas canvas) {\n }\n\n @Override\n public void drawForeground(View view, Canvas canvas) {\n }\n\n @Override\n public boolean onTouch(View view, MotionEvent motionEvent, View.OnClickListener onClickListener, View.OnLongClickListener onLongClickListener) {\n ", "post_mask_code": "\n return false;\n }\n\n @Override\n protected Animator createEngineAnimator(View view) {\n ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, -0.1f, 0f, 0.1f, 0f, -0.1f, 0f);\n valueAnimator.setDuration(mAnimationDuration);\n valueAnimator.addUpdateListener(animation -> {\n mTranslateValue = (float) animation.getAnimatedValue();\n view.invalidate();\n });\n return valueAnimator;\n }\n\n @Override\n protected Animator createExtinctAnimator(View view) {\n return null;\n }\n}\n"} {"task_id": "Java_836", "language": "Java", "task_type": "empty", "source_file": "java/github/likaiyuan559/TouchEffects/toucheffectslib/src/main/java/com/lky/toucheffectsmodule/effects_adapter/TouchShakeAdapter.java", "mask_start_position": 1071, "mask_end_position": 1071, "canonical_solution": "", "pre_mask_code": "package com.lky.toucheffectsmodule.effects_adapter;\n\nimport android.animation.Animator;\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.util.AttributeSet;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport com.lky.toucheffectsmodule.R;\n\npublic class TouchShakeAdapter extends EffectsAdapter {\n\n private float mTranslateValue;\n\n @Override\n public void initAttr(Context context, AttributeSet attrs) {\n TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TouchEffectsView);\n mAnimationDuration = ta.getResourceId(R.styleable.TouchEffectsView_animation_duration, 150);\n }\n\n @Override\n public void runAnimator(View view, Canvas canvas) {\n canvas.translate(view.getWidth() * mTranslateValue, 0);\n }\n\n @Override\n public void dispatchDraw(View view, Canvas canvas) {\n }\n\n @Override\n public void drawForeground(View view, Canvas canvas) {\n }\n\n @Override\n public boolean onTou", "post_mask_code": "ch(View view, MotionEvent motionEvent, View.OnClickListener onClickListener, View.OnLongClickListener onLongClickListener) {\n switch(motionEvent.getAction()) {\n case MotionEvent.ACTION_DOWN:\n engineAnimator(view);\n break;\n }\n return false;\n }\n\n @Override\n protected Animator createEngineAnimator(View view) {\n ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, -0.1f, 0f, 0.1f, 0f, -0.1f, 0f);\n valueAnimator.setDuration(mAnimationDuration);\n valueAnimator.addUpdateListener(animation -> {\n mTranslateValue = (float) animation.getAnimatedValue();\n view.invalidate();\n });\n return valueAnimator;\n }\n\n @Override\n protected Animator createExtinctAnimator(View view) {\n return null;\n }\n}\n"} {"task_id": "Java_837", "language": "Java", "task_type": "empty", "source_file": "java/github/Funwayguy/BetterQuesting/src/main/java/betterquesting/api2/client/gui/panels/IGuiPanel.java", "mask_start_position": 359, "mask_end_position": 359, "canonical_solution": "", "pre_mask_code": "package betterquesting.api2.client.gui.panels;\n\nimport java.util.List;\nimport betterquesting.api2.client.gui.misc.IGuiRect;\n\npublic interface IGuiPanel {\n\n IGuiRect getTransform();\n\n void initPanel();\n\n void setEnabled(boolean state);\n\n boolean isEnabled();\n\n void drawPanel(int mx, int my, float partialTick);\n\n boolean onMouseClick(int mx,", "post_mask_code": " int my, int button);\n\n boolean onMouseRelease(int mx, int my, int button);\n\n boolean onMouseScroll(int mx, int my, int scroll);\n\n boolean onKeyTyped(char c, int keycode);\n\n List getTooltip(int mx, int my);\n}\n"} {"task_id": "Java_838", "language": "Java", "task_type": "method_signature", "source_file": "java/github/oVirt/moVirt/moVirt/src/main/java/org/ovirt/mobile/movirt/ui/auth/connectionsettings/ConnectionSettingsActivity.java", "mask_start_position": 6581, "mask_end_position": 6652, "canonical_solution": "@Override\n public void showLoginInProgress(boolean loginInProgress) ", "pre_mask_code": "package org.ovirt.mobile.movirt.ui.auth.connectionsettings;\n\nimport android.app.DialogFragment;\nimport android.content.Intent;\nimport android.content.res.ColorStateList;\nimport android.graphics.Color;\nimport android.support.design.widget.FloatingActionButton;\nimport android.text.InputType;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.MultiAutoCompleteTextView;\nimport android.widget.ProgressBar;\nimport org.androidannotations.annotations.AfterViews;\nimport org.androidannotations.annotations.Bean;\nimport org.androidannotations.annotations.Click;\nimport org.androidannotations.annotations.EActivity;\nimport org.androidannotations.annotations.OptionsItem;\nimport org.androidannotations.annotations.ViewById;\nimport org.ovirt.mobile.movirt.Constants;\nimport org.ovirt.mobile.movirt.R;\nimport org.ovirt.mobile.movirt.auth.account.data.MovirtAccount;\nimport org.ovirt.mobile.movirt.ui.PresenterBroadcastAwareActivity;\nimport org.ovirt.mobile.movirt.ui.UiUtils;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity_;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.dialog.FixApiPathDialogFragment;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.SmallMistakeException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongApiPathException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongArgumentException;\nimport org.ovirt.mobile.movirt.util.message.CommonMessageHelper;\nimport org.ovirt.mobile.movirt.util.message.ErrorType;\n\n@EActivity(R.layout.activity_connection_settings)\npublic class ConnectionSettingsActivity extends PresenterBroadcastAwareActivity implements ConnectionSettingsContract.View {\n\n private static final String TAG = ConnectionSettingsActivity.class.getSimpleName();\n\n private static final String[] URL_COMPLETE = { \"http://\", \"https://\", \"ovirt-engine/api\", \"80\", \"443\", \"api\" };\n\n private static final String[] USERNAME_COMPLETE = { \"admin@\", \"internal\", \"admin@internal\" };\n\n @ViewById\n MultiAutoCompleteTextView txtEndpoint;\n\n @ViewById\n MultiAutoCompleteTextView txtUsername;\n\n @ViewById\n EditText txtPassword;\n\n @ViewById\n ImageView passwordVisibility;\n\n @ViewById\n ProgressBar authProgress;\n\n @ViewById\n FloatingActionButton btnCreate;\n\n @ViewById\n Button btnAdvanced;\n\n @Bean\n CommonMessageHelper commonMessageHelper;\n\n private ConnectionSettingsContract.Presenter presenter;\n\n @AfterViews\n void init() {\n initView();\n presenter = ConnectionSettingsPresenter_.getInstance_(getApplicationContext()).setView(this).setAccount(getIntent().getParcelableExtra(Constants.ACCOUNT_KEY)).initialize();\n }\n\n private void initView() {\n btnCreate.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.material_green_300)));\n ArrayAdapter urlAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, URL_COMPLETE);\n txtEndpoint.setAdapter(urlAdapter);\n txtEndpoint.setTokenizer(UiUtils.getUrlTokenizer());\n ArrayAdapter usernameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, USERNAME_COMPLETE);\n txtUsername.setAdapter(usernameAdapter);\n txtUsername.setTokenizer(UiUtils.getUsernameTokenizer());\n passwordVisibility.setOnTouchListener((view, event) -> {\n switch(event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackgroundColor(UiUtils.addAlphaToColor(Color.WHITE, 0.25f));\n imgView.invalidate();\n break;\n }\n case MotionEvent.ACTION_UP:\n case MotionEvent.ACTION_CANCEL:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackground(null);\n imgView.invalidate();\n break;\n }\n }\n return false;\n });\n }\n\n public ConnectionSettingsContract.Presenter getPresenter() {\n return presenter;\n }\n\n @Click(R.id.passwordVisibility)\n void togglePasswordVisibility() {\n presenter.togglePasswordVisibility();\n }\n\n @Click(R.id.btnCreate)\n void login() {\n try {\n LoginInfo loginInfo = new LoginInfo(txtEndpoint.getText().toString(), txtUsername.getText().toString(), txtPassword.getText().toString(), // admin only now\n true);\n presenter.sanitizeAndCheckLoginInfo(loginInfo);\n // background call\n presenter.login(loginInfo);\n } catch (SmallMistakeException e) {\n commonMessageHelper.showToast(e.getMessage());\n } catch (WrongArgumentException e) {\n commonMessageHelper.showError(e.getAccount(), ErrorType.USER, e.getMessage());\n } catch (WrongApiPathException e) {\n DialogFragment apiPathDialog = FixApiPathDialogFragment.newInstance(e.getAccount().getName(), e.getLoginInfo());\n // fires login\n apiPathDialog.show(getFragmentManager(), \"apiPathDialog\");\n }\n }\n\n @Override\n public void setPasswordVisibility(boolean visibility) {\n passwordVisibility.setImageResource(visibility ? R.drawable.ic_visibility_white_24dp : R.drawable.ic_visibility_off_white_24dp);\n txtPassword.setInputType(visibility ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);\n }\n\n @Override\n public void displayUserName(String userName) {\n txtUsername.setText(userName);\n }\n\n @Override\n public void displayPassword(String password) {\n txtPassword.setText(password);\n }\n\n @Override\n public void displayApiUrl(String apiUrl) {\n txtEndpoint.setText(apiUrl);\n }\n\n @Override\n public void displayTitle(String title) {\n setTitle(getString(R.string.title_activity_account_connection_settings, title));\n }\n\n @Click(R.id.btnAdvanced)\n public void btnAdvancedClicked() {\n presenter.onCertificateManagementClicked(txtEndpoint.getText().toString());\n }\n\n ", "post_mask_code": "{\n boolean enabled = !loginInProgress;\n txtEndpoint.setEnabled(enabled);\n txtUsername.setEnabled(enabled);\n txtPassword.setEnabled(enabled);\n passwordVisibility.setEnabled(enabled);\n btnAdvanced.setEnabled(enabled);\n btnCreate.setEnabled(enabled);\n btnCreate.setVisibility(loginInProgress ? View.GONE : View.VISIBLE);\n authProgress.setVisibility(loginInProgress ? View.VISIBLE : View.GONE);\n }\n\n @Override\n public void startCertificateManagementActivity(MovirtAccount account, String apiUrl) {\n Intent intent = new Intent(this, CertificateManagementActivity_.class);\n intent.putExtra(Constants.ACCOUNT_KEY, account);\n intent.putExtra(CertificateManagementActivity.LOAD_CA_FROM, apiUrl);\n startActivity(intent);\n }\n\n @OptionsItem(android.R.id.home)\n public void homeSelected() {\n onBackPressed();\n }\n}\n"} {"task_id": "Java_839", "language": "Java", "task_type": "method_body", "source_file": "java/github/oVirt/moVirt/moVirt/src/main/java/org/ovirt/mobile/movirt/ui/auth/connectionsettings/ConnectionSettingsActivity.java", "mask_start_position": 7216, "mask_end_position": 7468, "canonical_solution": "{\n Intent intent = new Intent(this, CertificateManagementActivity_.class);\n intent.putExtra(Constants.ACCOUNT_KEY, account);\n intent.putExtra(CertificateManagementActivity.LOAD_CA_FROM, apiUrl);\n startActivity(intent);\n }", "pre_mask_code": "package org.ovirt.mobile.movirt.ui.auth.connectionsettings;\n\nimport android.app.DialogFragment;\nimport android.content.Intent;\nimport android.content.res.ColorStateList;\nimport android.graphics.Color;\nimport android.support.design.widget.FloatingActionButton;\nimport android.text.InputType;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.MultiAutoCompleteTextView;\nimport android.widget.ProgressBar;\nimport org.androidannotations.annotations.AfterViews;\nimport org.androidannotations.annotations.Bean;\nimport org.androidannotations.annotations.Click;\nimport org.androidannotations.annotations.EActivity;\nimport org.androidannotations.annotations.OptionsItem;\nimport org.androidannotations.annotations.ViewById;\nimport org.ovirt.mobile.movirt.Constants;\nimport org.ovirt.mobile.movirt.R;\nimport org.ovirt.mobile.movirt.auth.account.data.MovirtAccount;\nimport org.ovirt.mobile.movirt.ui.PresenterBroadcastAwareActivity;\nimport org.ovirt.mobile.movirt.ui.UiUtils;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity_;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.dialog.FixApiPathDialogFragment;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.SmallMistakeException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongApiPathException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongArgumentException;\nimport org.ovirt.mobile.movirt.util.message.CommonMessageHelper;\nimport org.ovirt.mobile.movirt.util.message.ErrorType;\n\n@EActivity(R.layout.activity_connection_settings)\npublic class ConnectionSettingsActivity extends PresenterBroadcastAwareActivity implements ConnectionSettingsContract.View {\n\n private static final String TAG = ConnectionSettingsActivity.class.getSimpleName();\n\n private static final String[] URL_COMPLETE = { \"http://\", \"https://\", \"ovirt-engine/api\", \"80\", \"443\", \"api\" };\n\n private static final String[] USERNAME_COMPLETE = { \"admin@\", \"internal\", \"admin@internal\" };\n\n @ViewById\n MultiAutoCompleteTextView txtEndpoint;\n\n @ViewById\n MultiAutoCompleteTextView txtUsername;\n\n @ViewById\n EditText txtPassword;\n\n @ViewById\n ImageView passwordVisibility;\n\n @ViewById\n ProgressBar authProgress;\n\n @ViewById\n FloatingActionButton btnCreate;\n\n @ViewById\n Button btnAdvanced;\n\n @Bean\n CommonMessageHelper commonMessageHelper;\n\n private ConnectionSettingsContract.Presenter presenter;\n\n @AfterViews\n void init() {\n initView();\n presenter = ConnectionSettingsPresenter_.getInstance_(getApplicationContext()).setView(this).setAccount(getIntent().getParcelableExtra(Constants.ACCOUNT_KEY)).initialize();\n }\n\n private void initView() {\n btnCreate.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.material_green_300)));\n ArrayAdapter urlAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, URL_COMPLETE);\n txtEndpoint.setAdapter(urlAdapter);\n txtEndpoint.setTokenizer(UiUtils.getUrlTokenizer());\n ArrayAdapter usernameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, USERNAME_COMPLETE);\n txtUsername.setAdapter(usernameAdapter);\n txtUsername.setTokenizer(UiUtils.getUsernameTokenizer());\n passwordVisibility.setOnTouchListener((view, event) -> {\n switch(event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackgroundColor(UiUtils.addAlphaToColor(Color.WHITE, 0.25f));\n imgView.invalidate();\n break;\n }\n case MotionEvent.ACTION_UP:\n case MotionEvent.ACTION_CANCEL:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackground(null);\n imgView.invalidate();\n break;\n }\n }\n return false;\n });\n }\n\n public ConnectionSettingsContract.Presenter getPresenter() {\n return presenter;\n }\n\n @Click(R.id.passwordVisibility)\n void togglePasswordVisibility() {\n presenter.togglePasswordVisibility();\n }\n\n @Click(R.id.btnCreate)\n void login() {\n try {\n LoginInfo loginInfo = new LoginInfo(txtEndpoint.getText().toString(), txtUsername.getText().toString(), txtPassword.getText().toString(), // admin only now\n true);\n presenter.sanitizeAndCheckLoginInfo(loginInfo);\n // background call\n presenter.login(loginInfo);\n } catch (SmallMistakeException e) {\n commonMessageHelper.showToast(e.getMessage());\n } catch (WrongArgumentException e) {\n commonMessageHelper.showError(e.getAccount(), ErrorType.USER, e.getMessage());\n } catch (WrongApiPathException e) {\n DialogFragment apiPathDialog = FixApiPathDialogFragment.newInstance(e.getAccount().getName(), e.getLoginInfo());\n // fires login\n apiPathDialog.show(getFragmentManager(), \"apiPathDialog\");\n }\n }\n\n @Override\n public void setPasswordVisibility(boolean visibility) {\n passwordVisibility.setImageResource(visibility ? R.drawable.ic_visibility_white_24dp : R.drawable.ic_visibility_off_white_24dp);\n txtPassword.setInputType(visibility ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);\n }\n\n @Override\n public void displayUserName(String userName) {\n txtUsername.setText(userName);\n }\n\n @Override\n public void displayPassword(String password) {\n txtPassword.setText(password);\n }\n\n @Override\n public void displayApiUrl(String apiUrl) {\n txtEndpoint.setText(apiUrl);\n }\n\n @Override\n public void displayTitle(String title) {\n setTitle(getString(R.string.title_activity_account_connection_settings, title));\n }\n\n @Click(R.id.btnAdvanced)\n public void btnAdvancedClicked() {\n presenter.onCertificateManagementClicked(txtEndpoint.getText().toString());\n }\n\n @Override\n public void showLoginInProgress(boolean loginInProgress) {\n boolean enabled = !loginInProgress;\n txtEndpoint.setEnabled(enabled);\n txtUsername.setEnabled(enabled);\n txtPassword.setEnabled(enabled);\n passwordVisibility.setEnabled(enabled);\n btnAdvanced.setEnabled(enabled);\n btnCreate.setEnabled(enabled);\n btnCreate.setVisibility(loginInProgress ? View.GONE : View.VISIBLE);\n authProgress.setVisibility(loginInProgress ? View.VISIBLE : View.GONE);\n }\n\n @Override\n public void startCertificateManagementActivity(MovirtAccount account, String apiUrl) ", "post_mask_code": "\n\n @OptionsItem(android.R.id.home)\n public void homeSelected() {\n onBackPressed();\n }\n}\n"} {"task_id": "Java_840", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/oVirt/moVirt/moVirt/src/main/java/org/ovirt/mobile/movirt/ui/auth/connectionsettings/ConnectionSettingsActivity.java", "mask_start_position": 3007, "mask_end_position": 3296, "canonical_solution": "\n btnCreate.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.material_green_300)));\n ArrayAdapter urlAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, URL_COMPLETE);\n txtEndpoint.setAdapter(urlAdapter);", "pre_mask_code": "package org.ovirt.mobile.movirt.ui.auth.connectionsettings;\n\nimport android.app.DialogFragment;\nimport android.content.Intent;\nimport android.content.res.ColorStateList;\nimport android.graphics.Color;\nimport android.support.design.widget.FloatingActionButton;\nimport android.text.InputType;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.MultiAutoCompleteTextView;\nimport android.widget.ProgressBar;\nimport org.androidannotations.annotations.AfterViews;\nimport org.androidannotations.annotations.Bean;\nimport org.androidannotations.annotations.Click;\nimport org.androidannotations.annotations.EActivity;\nimport org.androidannotations.annotations.OptionsItem;\nimport org.androidannotations.annotations.ViewById;\nimport org.ovirt.mobile.movirt.Constants;\nimport org.ovirt.mobile.movirt.R;\nimport org.ovirt.mobile.movirt.auth.account.data.MovirtAccount;\nimport org.ovirt.mobile.movirt.ui.PresenterBroadcastAwareActivity;\nimport org.ovirt.mobile.movirt.ui.UiUtils;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity_;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.dialog.FixApiPathDialogFragment;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.SmallMistakeException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongApiPathException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongArgumentException;\nimport org.ovirt.mobile.movirt.util.message.CommonMessageHelper;\nimport org.ovirt.mobile.movirt.util.message.ErrorType;\n\n@EActivity(R.layout.activity_connection_settings)\npublic class ConnectionSettingsActivity extends PresenterBroadcastAwareActivity implements ConnectionSettingsContract.View {\n\n private static final String TAG = ConnectionSettingsActivity.class.getSimpleName();\n\n private static final String[] URL_COMPLETE = { \"http://\", \"https://\", \"ovirt-engine/api\", \"80\", \"443\", \"api\" };\n\n private static final String[] USERNAME_COMPLETE = { \"admin@\", \"internal\", \"admin@internal\" };\n\n @ViewById\n MultiAutoCompleteTextView txtEndpoint;\n\n @ViewById\n MultiAutoCompleteTextView txtUsername;\n\n @ViewById\n EditText txtPassword;\n\n @ViewById\n ImageView passwordVisibility;\n\n @ViewById\n ProgressBar authProgress;\n\n @ViewById\n FloatingActionButton btnCreate;\n\n @ViewById\n Button btnAdvanced;\n\n @Bean\n CommonMessageHelper commonMessageHelper;\n\n private ConnectionSettingsContract.Presenter presenter;\n\n @AfterViews\n void init() {\n initView();\n presenter = ConnectionSettingsPresenter_.getInstance_(getApplicationContext()).setView(this).setAccount(getIntent().getParcelableExtra(Constants.ACCOUNT_KEY)).initialize();\n }\n\n private void initView() {", "post_mask_code": "\n txtEndpoint.setTokenizer(UiUtils.getUrlTokenizer());\n ArrayAdapter usernameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, USERNAME_COMPLETE);\n txtUsername.setAdapter(usernameAdapter);\n txtUsername.setTokenizer(UiUtils.getUsernameTokenizer());\n passwordVisibility.setOnTouchListener((view, event) -> {\n switch(event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackgroundColor(UiUtils.addAlphaToColor(Color.WHITE, 0.25f));\n imgView.invalidate();\n break;\n }\n case MotionEvent.ACTION_UP:\n case MotionEvent.ACTION_CANCEL:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackground(null);\n imgView.invalidate();\n break;\n }\n }\n return false;\n });\n }\n\n public ConnectionSettingsContract.Presenter getPresenter() {\n return presenter;\n }\n\n @Click(R.id.passwordVisibility)\n void togglePasswordVisibility() {\n presenter.togglePasswordVisibility();\n }\n\n @Click(R.id.btnCreate)\n void login() {\n try {\n LoginInfo loginInfo = new LoginInfo(txtEndpoint.getText().toString(), txtUsername.getText().toString(), txtPassword.getText().toString(), // admin only now\n true);\n presenter.sanitizeAndCheckLoginInfo(loginInfo);\n // background call\n presenter.login(loginInfo);\n } catch (SmallMistakeException e) {\n commonMessageHelper.showToast(e.getMessage());\n } catch (WrongArgumentException e) {\n commonMessageHelper.showError(e.getAccount(), ErrorType.USER, e.getMessage());\n } catch (WrongApiPathException e) {\n DialogFragment apiPathDialog = FixApiPathDialogFragment.newInstance(e.getAccount().getName(), e.getLoginInfo());\n // fires login\n apiPathDialog.show(getFragmentManager(), \"apiPathDialog\");\n }\n }\n\n @Override\n public void setPasswordVisibility(boolean visibility) {\n passwordVisibility.setImageResource(visibility ? R.drawable.ic_visibility_white_24dp : R.drawable.ic_visibility_off_white_24dp);\n txtPassword.setInputType(visibility ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);\n }\n\n @Override\n public void displayUserName(String userName) {\n txtUsername.setText(userName);\n }\n\n @Override\n public void displayPassword(String password) {\n txtPassword.setText(password);\n }\n\n @Override\n public void displayApiUrl(String apiUrl) {\n txtEndpoint.setText(apiUrl);\n }\n\n @Override\n public void displayTitle(String title) {\n setTitle(getString(R.string.title_activity_account_connection_settings, title));\n }\n\n @Click(R.id.btnAdvanced)\n public void btnAdvancedClicked() {\n presenter.onCertificateManagementClicked(txtEndpoint.getText().toString());\n }\n\n @Override\n public void showLoginInProgress(boolean loginInProgress) {\n boolean enabled = !loginInProgress;\n txtEndpoint.setEnabled(enabled);\n txtUsername.setEnabled(enabled);\n txtPassword.setEnabled(enabled);\n passwordVisibility.setEnabled(enabled);\n btnAdvanced.setEnabled(enabled);\n btnCreate.setEnabled(enabled);\n btnCreate.setVisibility(loginInProgress ? View.GONE : View.VISIBLE);\n authProgress.setVisibility(loginInProgress ? View.VISIBLE : View.GONE);\n }\n\n @Override\n public void startCertificateManagementActivity(MovirtAccount account, String apiUrl) {\n Intent intent = new Intent(this, CertificateManagementActivity_.class);\n intent.putExtra(Constants.ACCOUNT_KEY, account);\n intent.putExtra(CertificateManagementActivity.LOAD_CA_FROM, apiUrl);\n startActivity(intent);\n }\n\n @OptionsItem(android.R.id.home)\n public void homeSelected() {\n onBackPressed();\n }\n}\n"} {"task_id": "Java_841", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/oVirt/moVirt/moVirt/src/main/java/org/ovirt/mobile/movirt/ui/auth/connectionsettings/ConnectionSettingsActivity.java", "mask_start_position": 3305, "mask_end_position": 3543, "canonical_solution": "txtEndpoint.setTokenizer(UiUtils.getUrlTokenizer());\n ArrayAdapter usernameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, USERNAME_COMPLETE);\n txtUsername.setAdapter(usernameAdapter);", "pre_mask_code": "package org.ovirt.mobile.movirt.ui.auth.connectionsettings;\n\nimport android.app.DialogFragment;\nimport android.content.Intent;\nimport android.content.res.ColorStateList;\nimport android.graphics.Color;\nimport android.support.design.widget.FloatingActionButton;\nimport android.text.InputType;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.MultiAutoCompleteTextView;\nimport android.widget.ProgressBar;\nimport org.androidannotations.annotations.AfterViews;\nimport org.androidannotations.annotations.Bean;\nimport org.androidannotations.annotations.Click;\nimport org.androidannotations.annotations.EActivity;\nimport org.androidannotations.annotations.OptionsItem;\nimport org.androidannotations.annotations.ViewById;\nimport org.ovirt.mobile.movirt.Constants;\nimport org.ovirt.mobile.movirt.R;\nimport org.ovirt.mobile.movirt.auth.account.data.MovirtAccount;\nimport org.ovirt.mobile.movirt.ui.PresenterBroadcastAwareActivity;\nimport org.ovirt.mobile.movirt.ui.UiUtils;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity_;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.dialog.FixApiPathDialogFragment;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.SmallMistakeException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongApiPathException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongArgumentException;\nimport org.ovirt.mobile.movirt.util.message.CommonMessageHelper;\nimport org.ovirt.mobile.movirt.util.message.ErrorType;\n\n@EActivity(R.layout.activity_connection_settings)\npublic class ConnectionSettingsActivity extends PresenterBroadcastAwareActivity implements ConnectionSettingsContract.View {\n\n private static final String TAG = ConnectionSettingsActivity.class.getSimpleName();\n\n private static final String[] URL_COMPLETE = { \"http://\", \"https://\", \"ovirt-engine/api\", \"80\", \"443\", \"api\" };\n\n private static final String[] USERNAME_COMPLETE = { \"admin@\", \"internal\", \"admin@internal\" };\n\n @ViewById\n MultiAutoCompleteTextView txtEndpoint;\n\n @ViewById\n MultiAutoCompleteTextView txtUsername;\n\n @ViewById\n EditText txtPassword;\n\n @ViewById\n ImageView passwordVisibility;\n\n @ViewById\n ProgressBar authProgress;\n\n @ViewById\n FloatingActionButton btnCreate;\n\n @ViewById\n Button btnAdvanced;\n\n @Bean\n CommonMessageHelper commonMessageHelper;\n\n private ConnectionSettingsContract.Presenter presenter;\n\n @AfterViews\n void init() {\n initView();\n presenter = ConnectionSettingsPresenter_.getInstance_(getApplicationContext()).setView(this).setAccount(getIntent().getParcelableExtra(Constants.ACCOUNT_KEY)).initialize();\n }\n\n private void initView() {\n btnCreate.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.material_green_300)));\n ArrayAdapter urlAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, URL_COMPLETE);\n txtEndpoint.setAdapter(urlAdapter);\n ", "post_mask_code": "\n txtUsername.setTokenizer(UiUtils.getUsernameTokenizer());\n passwordVisibility.setOnTouchListener((view, event) -> {\n switch(event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackgroundColor(UiUtils.addAlphaToColor(Color.WHITE, 0.25f));\n imgView.invalidate();\n break;\n }\n case MotionEvent.ACTION_UP:\n case MotionEvent.ACTION_CANCEL:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackground(null);\n imgView.invalidate();\n break;\n }\n }\n return false;\n });\n }\n\n public ConnectionSettingsContract.Presenter getPresenter() {\n return presenter;\n }\n\n @Click(R.id.passwordVisibility)\n void togglePasswordVisibility() {\n presenter.togglePasswordVisibility();\n }\n\n @Click(R.id.btnCreate)\n void login() {\n try {\n LoginInfo loginInfo = new LoginInfo(txtEndpoint.getText().toString(), txtUsername.getText().toString(), txtPassword.getText().toString(), // admin only now\n true);\n presenter.sanitizeAndCheckLoginInfo(loginInfo);\n // background call\n presenter.login(loginInfo);\n } catch (SmallMistakeException e) {\n commonMessageHelper.showToast(e.getMessage());\n } catch (WrongArgumentException e) {\n commonMessageHelper.showError(e.getAccount(), ErrorType.USER, e.getMessage());\n } catch (WrongApiPathException e) {\n DialogFragment apiPathDialog = FixApiPathDialogFragment.newInstance(e.getAccount().getName(), e.getLoginInfo());\n // fires login\n apiPathDialog.show(getFragmentManager(), \"apiPathDialog\");\n }\n }\n\n @Override\n public void setPasswordVisibility(boolean visibility) {\n passwordVisibility.setImageResource(visibility ? R.drawable.ic_visibility_white_24dp : R.drawable.ic_visibility_off_white_24dp);\n txtPassword.setInputType(visibility ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);\n }\n\n @Override\n public void displayUserName(String userName) {\n txtUsername.setText(userName);\n }\n\n @Override\n public void displayPassword(String password) {\n txtPassword.setText(password);\n }\n\n @Override\n public void displayApiUrl(String apiUrl) {\n txtEndpoint.setText(apiUrl);\n }\n\n @Override\n public void displayTitle(String title) {\n setTitle(getString(R.string.title_activity_account_connection_settings, title));\n }\n\n @Click(R.id.btnAdvanced)\n public void btnAdvancedClicked() {\n presenter.onCertificateManagementClicked(txtEndpoint.getText().toString());\n }\n\n @Override\n public void showLoginInProgress(boolean loginInProgress) {\n boolean enabled = !loginInProgress;\n txtEndpoint.setEnabled(enabled);\n txtUsername.setEnabled(enabled);\n txtPassword.setEnabled(enabled);\n passwordVisibility.setEnabled(enabled);\n btnAdvanced.setEnabled(enabled);\n btnCreate.setEnabled(enabled);\n btnCreate.setVisibility(loginInProgress ? View.GONE : View.VISIBLE);\n authProgress.setVisibility(loginInProgress ? View.VISIBLE : View.GONE);\n }\n\n @Override\n public void startCertificateManagementActivity(MovirtAccount account, String apiUrl) {\n Intent intent = new Intent(this, CertificateManagementActivity_.class);\n intent.putExtra(Constants.ACCOUNT_KEY, account);\n intent.putExtra(CertificateManagementActivity.LOAD_CA_FROM, apiUrl);\n startActivity(intent);\n }\n\n @OptionsItem(android.R.id.home)\n public void homeSelected() {\n onBackPressed();\n }\n}\n"} {"task_id": "Java_842", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/oVirt/moVirt/moVirt/src/main/java/org/ovirt/mobile/movirt/ui/auth/connectionsettings/ConnectionSettingsActivity.java", "mask_start_position": 3552, "mask_end_position": 4426, "canonical_solution": "txtUsername.setTokenizer(UiUtils.getUsernameTokenizer());\n passwordVisibility.setOnTouchListener((view, event) -> {\n switch(event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackgroundColor(UiUtils.addAlphaToColor(Color.WHITE, 0.25f));\n imgView.invalidate();\n break;\n }\n case MotionEvent.ACTION_UP:\n case MotionEvent.ACTION_CANCEL:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackground(null);\n imgView.invalidate();\n break;\n }\n }\n return false;\n });\n }", "pre_mask_code": "package org.ovirt.mobile.movirt.ui.auth.connectionsettings;\n\nimport android.app.DialogFragment;\nimport android.content.Intent;\nimport android.content.res.ColorStateList;\nimport android.graphics.Color;\nimport android.support.design.widget.FloatingActionButton;\nimport android.text.InputType;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.MultiAutoCompleteTextView;\nimport android.widget.ProgressBar;\nimport org.androidannotations.annotations.AfterViews;\nimport org.androidannotations.annotations.Bean;\nimport org.androidannotations.annotations.Click;\nimport org.androidannotations.annotations.EActivity;\nimport org.androidannotations.annotations.OptionsItem;\nimport org.androidannotations.annotations.ViewById;\nimport org.ovirt.mobile.movirt.Constants;\nimport org.ovirt.mobile.movirt.R;\nimport org.ovirt.mobile.movirt.auth.account.data.MovirtAccount;\nimport org.ovirt.mobile.movirt.ui.PresenterBroadcastAwareActivity;\nimport org.ovirt.mobile.movirt.ui.UiUtils;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity_;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.dialog.FixApiPathDialogFragment;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.SmallMistakeException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongApiPathException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongArgumentException;\nimport org.ovirt.mobile.movirt.util.message.CommonMessageHelper;\nimport org.ovirt.mobile.movirt.util.message.ErrorType;\n\n@EActivity(R.layout.activity_connection_settings)\npublic class ConnectionSettingsActivity extends PresenterBroadcastAwareActivity implements ConnectionSettingsContract.View {\n\n private static final String TAG = ConnectionSettingsActivity.class.getSimpleName();\n\n private static final String[] URL_COMPLETE = { \"http://\", \"https://\", \"ovirt-engine/api\", \"80\", \"443\", \"api\" };\n\n private static final String[] USERNAME_COMPLETE = { \"admin@\", \"internal\", \"admin@internal\" };\n\n @ViewById\n MultiAutoCompleteTextView txtEndpoint;\n\n @ViewById\n MultiAutoCompleteTextView txtUsername;\n\n @ViewById\n EditText txtPassword;\n\n @ViewById\n ImageView passwordVisibility;\n\n @ViewById\n ProgressBar authProgress;\n\n @ViewById\n FloatingActionButton btnCreate;\n\n @ViewById\n Button btnAdvanced;\n\n @Bean\n CommonMessageHelper commonMessageHelper;\n\n private ConnectionSettingsContract.Presenter presenter;\n\n @AfterViews\n void init() {\n initView();\n presenter = ConnectionSettingsPresenter_.getInstance_(getApplicationContext()).setView(this).setAccount(getIntent().getParcelableExtra(Constants.ACCOUNT_KEY)).initialize();\n }\n\n private void initView() {\n btnCreate.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.material_green_300)));\n ArrayAdapter urlAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, URL_COMPLETE);\n txtEndpoint.setAdapter(urlAdapter);\n txtEndpoint.setTokenizer(UiUtils.getUrlTokenizer());\n ArrayAdapter usernameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, USERNAME_COMPLETE);\n txtUsername.setAdapter(usernameAdapter);\n ", "post_mask_code": "\n\n public ConnectionSettingsContract.Presenter getPresenter() {\n return presenter;\n }\n\n @Click(R.id.passwordVisibility)\n void togglePasswordVisibility() {\n presenter.togglePasswordVisibility();\n }\n\n @Click(R.id.btnCreate)\n void login() {\n try {\n LoginInfo loginInfo = new LoginInfo(txtEndpoint.getText().toString(), txtUsername.getText().toString(), txtPassword.getText().toString(), // admin only now\n true);\n presenter.sanitizeAndCheckLoginInfo(loginInfo);\n // background call\n presenter.login(loginInfo);\n } catch (SmallMistakeException e) {\n commonMessageHelper.showToast(e.getMessage());\n } catch (WrongArgumentException e) {\n commonMessageHelper.showError(e.getAccount(), ErrorType.USER, e.getMessage());\n } catch (WrongApiPathException e) {\n DialogFragment apiPathDialog = FixApiPathDialogFragment.newInstance(e.getAccount().getName(), e.getLoginInfo());\n // fires login\n apiPathDialog.show(getFragmentManager(), \"apiPathDialog\");\n }\n }\n\n @Override\n public void setPasswordVisibility(boolean visibility) {\n passwordVisibility.setImageResource(visibility ? R.drawable.ic_visibility_white_24dp : R.drawable.ic_visibility_off_white_24dp);\n txtPassword.setInputType(visibility ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);\n }\n\n @Override\n public void displayUserName(String userName) {\n txtUsername.setText(userName);\n }\n\n @Override\n public void displayPassword(String password) {\n txtPassword.setText(password);\n }\n\n @Override\n public void displayApiUrl(String apiUrl) {\n txtEndpoint.setText(apiUrl);\n }\n\n @Override\n public void displayTitle(String title) {\n setTitle(getString(R.string.title_activity_account_connection_settings, title));\n }\n\n @Click(R.id.btnAdvanced)\n public void btnAdvancedClicked() {\n presenter.onCertificateManagementClicked(txtEndpoint.getText().toString());\n }\n\n @Override\n public void showLoginInProgress(boolean loginInProgress) {\n boolean enabled = !loginInProgress;\n txtEndpoint.setEnabled(enabled);\n txtUsername.setEnabled(enabled);\n txtPassword.setEnabled(enabled);\n passwordVisibility.setEnabled(enabled);\n btnAdvanced.setEnabled(enabled);\n btnCreate.setEnabled(enabled);\n btnCreate.setVisibility(loginInProgress ? View.GONE : View.VISIBLE);\n authProgress.setVisibility(loginInProgress ? View.VISIBLE : View.GONE);\n }\n\n @Override\n public void startCertificateManagementActivity(MovirtAccount account, String apiUrl) {\n Intent intent = new Intent(this, CertificateManagementActivity_.class);\n intent.putExtra(Constants.ACCOUNT_KEY, account);\n intent.putExtra(CertificateManagementActivity.LOAD_CA_FROM, apiUrl);\n startActivity(intent);\n }\n\n @OptionsItem(android.R.id.home)\n public void homeSelected() {\n onBackPressed();\n }\n}\n"} {"task_id": "Java_843", "language": "Java", "task_type": "single_line", "source_file": "java/github/oVirt/moVirt/moVirt/src/main/java/org/ovirt/mobile/movirt/ui/auth/connectionsettings/ConnectionSettingsActivity.java", "mask_start_position": 3528, "mask_end_position": 3543, "canonical_solution": "ernameAdapter);", "pre_mask_code": "package org.ovirt.mobile.movirt.ui.auth.connectionsettings;\n\nimport android.app.DialogFragment;\nimport android.content.Intent;\nimport android.content.res.ColorStateList;\nimport android.graphics.Color;\nimport android.support.design.widget.FloatingActionButton;\nimport android.text.InputType;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.MultiAutoCompleteTextView;\nimport android.widget.ProgressBar;\nimport org.androidannotations.annotations.AfterViews;\nimport org.androidannotations.annotations.Bean;\nimport org.androidannotations.annotations.Click;\nimport org.androidannotations.annotations.EActivity;\nimport org.androidannotations.annotations.OptionsItem;\nimport org.androidannotations.annotations.ViewById;\nimport org.ovirt.mobile.movirt.Constants;\nimport org.ovirt.mobile.movirt.R;\nimport org.ovirt.mobile.movirt.auth.account.data.MovirtAccount;\nimport org.ovirt.mobile.movirt.ui.PresenterBroadcastAwareActivity;\nimport org.ovirt.mobile.movirt.ui.UiUtils;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity_;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.dialog.FixApiPathDialogFragment;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.SmallMistakeException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongApiPathException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongArgumentException;\nimport org.ovirt.mobile.movirt.util.message.CommonMessageHelper;\nimport org.ovirt.mobile.movirt.util.message.ErrorType;\n\n@EActivity(R.layout.activity_connection_settings)\npublic class ConnectionSettingsActivity extends PresenterBroadcastAwareActivity implements ConnectionSettingsContract.View {\n\n private static final String TAG = ConnectionSettingsActivity.class.getSimpleName();\n\n private static final String[] URL_COMPLETE = { \"http://\", \"https://\", \"ovirt-engine/api\", \"80\", \"443\", \"api\" };\n\n private static final String[] USERNAME_COMPLETE = { \"admin@\", \"internal\", \"admin@internal\" };\n\n @ViewById\n MultiAutoCompleteTextView txtEndpoint;\n\n @ViewById\n MultiAutoCompleteTextView txtUsername;\n\n @ViewById\n EditText txtPassword;\n\n @ViewById\n ImageView passwordVisibility;\n\n @ViewById\n ProgressBar authProgress;\n\n @ViewById\n FloatingActionButton btnCreate;\n\n @ViewById\n Button btnAdvanced;\n\n @Bean\n CommonMessageHelper commonMessageHelper;\n\n private ConnectionSettingsContract.Presenter presenter;\n\n @AfterViews\n void init() {\n initView();\n presenter = ConnectionSettingsPresenter_.getInstance_(getApplicationContext()).setView(this).setAccount(getIntent().getParcelableExtra(Constants.ACCOUNT_KEY)).initialize();\n }\n\n private void initView() {\n btnCreate.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.material_green_300)));\n ArrayAdapter urlAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, URL_COMPLETE);\n txtEndpoint.setAdapter(urlAdapter);\n txtEndpoint.setTokenizer(UiUtils.getUrlTokenizer());\n ArrayAdapter usernameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, USERNAME_COMPLETE);\n txtUsername.setAdapter(us", "post_mask_code": "\n txtUsername.setTokenizer(UiUtils.getUsernameTokenizer());\n passwordVisibility.setOnTouchListener((view, event) -> {\n switch(event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackgroundColor(UiUtils.addAlphaToColor(Color.WHITE, 0.25f));\n imgView.invalidate();\n break;\n }\n case MotionEvent.ACTION_UP:\n case MotionEvent.ACTION_CANCEL:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackground(null);\n imgView.invalidate();\n break;\n }\n }\n return false;\n });\n }\n\n public ConnectionSettingsContract.Presenter getPresenter() {\n return presenter;\n }\n\n @Click(R.id.passwordVisibility)\n void togglePasswordVisibility() {\n presenter.togglePasswordVisibility();\n }\n\n @Click(R.id.btnCreate)\n void login() {\n try {\n LoginInfo loginInfo = new LoginInfo(txtEndpoint.getText().toString(), txtUsername.getText().toString(), txtPassword.getText().toString(), // admin only now\n true);\n presenter.sanitizeAndCheckLoginInfo(loginInfo);\n // background call\n presenter.login(loginInfo);\n } catch (SmallMistakeException e) {\n commonMessageHelper.showToast(e.getMessage());\n } catch (WrongArgumentException e) {\n commonMessageHelper.showError(e.getAccount(), ErrorType.USER, e.getMessage());\n } catch (WrongApiPathException e) {\n DialogFragment apiPathDialog = FixApiPathDialogFragment.newInstance(e.getAccount().getName(), e.getLoginInfo());\n // fires login\n apiPathDialog.show(getFragmentManager(), \"apiPathDialog\");\n }\n }\n\n @Override\n public void setPasswordVisibility(boolean visibility) {\n passwordVisibility.setImageResource(visibility ? R.drawable.ic_visibility_white_24dp : R.drawable.ic_visibility_off_white_24dp);\n txtPassword.setInputType(visibility ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);\n }\n\n @Override\n public void displayUserName(String userName) {\n txtUsername.setText(userName);\n }\n\n @Override\n public void displayPassword(String password) {\n txtPassword.setText(password);\n }\n\n @Override\n public void displayApiUrl(String apiUrl) {\n txtEndpoint.setText(apiUrl);\n }\n\n @Override\n public void displayTitle(String title) {\n setTitle(getString(R.string.title_activity_account_connection_settings, title));\n }\n\n @Click(R.id.btnAdvanced)\n public void btnAdvancedClicked() {\n presenter.onCertificateManagementClicked(txtEndpoint.getText().toString());\n }\n\n @Override\n public void showLoginInProgress(boolean loginInProgress) {\n boolean enabled = !loginInProgress;\n txtEndpoint.setEnabled(enabled);\n txtUsername.setEnabled(enabled);\n txtPassword.setEnabled(enabled);\n passwordVisibility.setEnabled(enabled);\n btnAdvanced.setEnabled(enabled);\n btnCreate.setEnabled(enabled);\n btnCreate.setVisibility(loginInProgress ? View.GONE : View.VISIBLE);\n authProgress.setVisibility(loginInProgress ? View.VISIBLE : View.GONE);\n }\n\n @Override\n public void startCertificateManagementActivity(MovirtAccount account, String apiUrl) {\n Intent intent = new Intent(this, CertificateManagementActivity_.class);\n intent.putExtra(Constants.ACCOUNT_KEY, account);\n intent.putExtra(CertificateManagementActivity.LOAD_CA_FROM, apiUrl);\n startActivity(intent);\n }\n\n @OptionsItem(android.R.id.home)\n public void homeSelected() {\n onBackPressed();\n }\n}\n"} {"task_id": "Java_844", "language": "Java", "task_type": "empty", "source_file": "java/github/oVirt/moVirt/moVirt/src/main/java/org/ovirt/mobile/movirt/ui/auth/connectionsettings/ConnectionSettingsActivity.java", "mask_start_position": 6753, "mask_end_position": 6753, "canonical_solution": "", "pre_mask_code": "package org.ovirt.mobile.movirt.ui.auth.connectionsettings;\n\nimport android.app.DialogFragment;\nimport android.content.Intent;\nimport android.content.res.ColorStateList;\nimport android.graphics.Color;\nimport android.support.design.widget.FloatingActionButton;\nimport android.text.InputType;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.MultiAutoCompleteTextView;\nimport android.widget.ProgressBar;\nimport org.androidannotations.annotations.AfterViews;\nimport org.androidannotations.annotations.Bean;\nimport org.androidannotations.annotations.Click;\nimport org.androidannotations.annotations.EActivity;\nimport org.androidannotations.annotations.OptionsItem;\nimport org.androidannotations.annotations.ViewById;\nimport org.ovirt.mobile.movirt.Constants;\nimport org.ovirt.mobile.movirt.R;\nimport org.ovirt.mobile.movirt.auth.account.data.MovirtAccount;\nimport org.ovirt.mobile.movirt.ui.PresenterBroadcastAwareActivity;\nimport org.ovirt.mobile.movirt.ui.UiUtils;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity;\nimport org.ovirt.mobile.movirt.ui.auth.certificatemanagement.CertificateManagementActivity_;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.dialog.FixApiPathDialogFragment;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.SmallMistakeException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongApiPathException;\nimport org.ovirt.mobile.movirt.ui.auth.connectionsettings.exception.WrongArgumentException;\nimport org.ovirt.mobile.movirt.util.message.CommonMessageHelper;\nimport org.ovirt.mobile.movirt.util.message.ErrorType;\n\n@EActivity(R.layout.activity_connection_settings)\npublic class ConnectionSettingsActivity extends PresenterBroadcastAwareActivity implements ConnectionSettingsContract.View {\n\n private static final String TAG = ConnectionSettingsActivity.class.getSimpleName();\n\n private static final String[] URL_COMPLETE = { \"http://\", \"https://\", \"ovirt-engine/api\", \"80\", \"443\", \"api\" };\n\n private static final String[] USERNAME_COMPLETE = { \"admin@\", \"internal\", \"admin@internal\" };\n\n @ViewById\n MultiAutoCompleteTextView txtEndpoint;\n\n @ViewById\n MultiAutoCompleteTextView txtUsername;\n\n @ViewById\n EditText txtPassword;\n\n @ViewById\n ImageView passwordVisibility;\n\n @ViewById\n ProgressBar authProgress;\n\n @ViewById\n FloatingActionButton btnCreate;\n\n @ViewById\n Button btnAdvanced;\n\n @Bean\n CommonMessageHelper commonMessageHelper;\n\n private ConnectionSettingsContract.Presenter presenter;\n\n @AfterViews\n void init() {\n initView();\n presenter = ConnectionSettingsPresenter_.getInstance_(getApplicationContext()).setView(this).setAccount(getIntent().getParcelableExtra(Constants.ACCOUNT_KEY)).initialize();\n }\n\n private void initView() {\n btnCreate.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.material_green_300)));\n ArrayAdapter urlAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, URL_COMPLETE);\n txtEndpoint.setAdapter(urlAdapter);\n txtEndpoint.setTokenizer(UiUtils.getUrlTokenizer());\n ArrayAdapter usernameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, USERNAME_COMPLETE);\n txtUsername.setAdapter(usernameAdapter);\n txtUsername.setTokenizer(UiUtils.getUsernameTokenizer());\n passwordVisibility.setOnTouchListener((view, event) -> {\n switch(event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackgroundColor(UiUtils.addAlphaToColor(Color.WHITE, 0.25f));\n imgView.invalidate();\n break;\n }\n case MotionEvent.ACTION_UP:\n case MotionEvent.ACTION_CANCEL:\n {\n ImageView imgView = (ImageView) view;\n imgView.setBackground(null);\n imgView.invalidate();\n break;\n }\n }\n return false;\n });\n }\n\n public ConnectionSettingsContract.Presenter getPresenter() {\n return presenter;\n }\n\n @Click(R.id.passwordVisibility)\n void togglePasswordVisibility() {\n presenter.togglePasswordVisibility();\n }\n\n @Click(R.id.btnCreate)\n void login() {\n try {\n LoginInfo loginInfo = new LoginInfo(txtEndpoint.getText().toString(), txtUsername.getText().toString(), txtPassword.getText().toString(), // admin only now\n true);\n presenter.sanitizeAndCheckLoginInfo(loginInfo);\n // background call\n presenter.login(loginInfo);\n } catch (SmallMistakeException e) {\n commonMessageHelper.showToast(e.getMessage());\n } catch (WrongArgumentException e) {\n commonMessageHelper.showError(e.getAccount(), ErrorType.USER, e.getMessage());\n } catch (WrongApiPathException e) {\n DialogFragment apiPathDialog = FixApiPathDialogFragment.newInstance(e.getAccount().getName(), e.getLoginInfo());\n // fires login\n apiPathDialog.show(getFragmentManager(), \"apiPathDialog\");\n }\n }\n\n @Override\n public void setPasswordVisibility(boolean visibility) {\n passwordVisibility.setImageResource(visibility ? R.drawable.ic_visibility_white_24dp : R.drawable.ic_visibility_off_white_24dp);\n txtPassword.setInputType(visibility ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);\n }\n\n @Override\n public void displayUserName(String userName) {\n txtUsername.setText(userName);\n }\n\n @Override\n public void displayPassword(String password) {\n txtPassword.setText(password);\n }\n\n @Override\n public void displayApiUrl(String apiUrl) {\n txtEndpoint.setText(apiUrl);\n }\n\n @Override\n public void displayTitle(String title) {\n setTitle(getString(R.string.title_activity_account_connection_settings, title));\n }\n\n @Click(R.id.btnAdvanced)\n public void btnAdvancedClicked() {\n presenter.onCertificateManagementClicked(txtEndpoint.getText().toString());\n }\n\n @Override\n public void showLoginInProgress(boolean loginInProgress) {\n boolean enabled = !loginInProgress;\n txtEndpoint.setEnabled(enabled);\n txtUse", "post_mask_code": "rname.setEnabled(enabled);\n txtPassword.setEnabled(enabled);\n passwordVisibility.setEnabled(enabled);\n btnAdvanced.setEnabled(enabled);\n btnCreate.setEnabled(enabled);\n btnCreate.setVisibility(loginInProgress ? View.GONE : View.VISIBLE);\n authProgress.setVisibility(loginInProgress ? View.VISIBLE : View.GONE);\n }\n\n @Override\n public void startCertificateManagementActivity(MovirtAccount account, String apiUrl) {\n Intent intent = new Intent(this, CertificateManagementActivity_.class);\n intent.putExtra(Constants.ACCOUNT_KEY, account);\n intent.putExtra(CertificateManagementActivity.LOAD_CA_FROM, apiUrl);\n startActivity(intent);\n }\n\n @OptionsItem(android.R.id.home)\n public void homeSelected() {\n onBackPressed();\n }\n}\n"} {"task_id": "Java_845", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/czyzby/gdx-lml/lml/src/main/java/com/github/czyzby/lml/parser/LmlParser.java", "mask_start_position": 1606, "mask_end_position": 1642, "canonical_solution": "void setSyntax(LmlSyntax lmlSyntax);", "pre_mask_code": "package com.github.czyzby.lml.parser;\n\nimport com.badlogic.gdx.files.FileHandle;\nimport com.badlogic.gdx.scenes.scene2d.Actor;\nimport com.badlogic.gdx.scenes.scene2d.Stage;\nimport com.badlogic.gdx.utils.Array;\nimport com.badlogic.gdx.utils.ObjectMap;\nimport com.github.czyzby.lml.parser.action.ActorConsumer;\n\n/**\n * Common interface for all LML parsers. Provides methods allowing to configure template parsing. Note that\n * implementations are consider NOT thread-safe and templates should be either handled by multiple parsers or one by\n * one.\n *\n * @author MJ\n * @see com.github.czyzby.lml.parser.impl.DefaultLmlParser\n */\npublic interface LmlParser {\n\n /**\n * @param lmlData contains references to skins, bundles and preferences needed to parse LML templates. Cannot be\n * null.\n */\n void setData(LmlData lmlData);\n\n /**\n * @return data container with references to skins, bundles and preferences needed to parse LML templates.\n */\n LmlData getData();\n\n /**\n * @param templateReader will become parser's reader, used to process raw text data. Cannot be null.\n */\n void setTemplateReader(LmlTemplateReader templateReader);\n\n /**\n * @return direct access to template reader used by the LML parser. Templates should not be appended directly to\n * the reader, especially during templates parsing - this object is mostly for internal parser's use.\n */\n LmlTemplateReader getTemplateReader();\n\n /**\n * @param lmlSyntax will become current LML syntax, determining how templates are parsed. Cannot be null.\n */\n ", "post_mask_code": "\n\n /**\n * @return current used template syntax. Can be safely modified most of the time, but generally should be left\n * alone if template parsing is currently in progress.\n */\n LmlSyntax getSyntax();\n\n /**\n * @param styleSheet will be used to provide default values for tags' attributes.\n */\n void setStyleSheet(LmlStyleSheet styleSheet);\n\n /**\n * @return style sheet currently used to provide default values for tags' attributes. Can safely modified.\n */\n LmlStyleSheet getStyleSheet();\n\n /**\n * @return true if parser is strict and throws errors for unknown tags, attributes, etc.\n */\n boolean isStrict();\n\n /**\n * @param strict if true, parser throws errors for unknown tags, attributes, etc. Set to false for more HTML-like\n * feel of everything generally working even if something is terribly wrong.\n */\n void setStrict(boolean strict);\n\n /**\n * @param nestedComments if true, comments are nested and NEED to be valid. In HTML, comments are not nested, so\n * commenting-out a whole file full of other comments is problematic; this is also the default behavior\n * of LML, since this way comments you don't need to validate all your tags (for example, you might open\n * a comment tag by mistake inside another comment). However, if you're sure you'll keep for comments\n * clean and need a way to quickly comment-out huge portions of templates, set this value to true.\n */\n void setNestedComments(boolean nestedComments);\n\n /**\n * @param lmlTemplate will be parsed.\n * @return parsed root actors, in the order that they appear in the template.\n */\n Array parseTemplate(String lmlTemplate);\n\n /**\n * @param lmlTemplateFile will be read and parsed.\n * @return parsed root actors, in the order that they appear in the template.\n */\n Array parseTemplate(FileHandle lmlTemplateFile);\n\n /**\n * @param styleSheet LML style sheet code. Will be processed.\n * @see #getStyleSheet()\n */\n void parseStyleSheet(String styleSheet);\n\n /**\n * @param styleSheetFile path to a file storing LML style sheet code. Will be processed.\n * @see #getStyleSheet()\n */\n void parseStyleSheet(FileHandle styleSheetFile);\n\n /**\n * @param stage will have the parsed actors appended.\n * @param lmlTemplate will be parsed. Actors parsed from the template will be added directly into the stage.\n */\n void fillStage(Stage stage, String lmlTemplate);\n\n /**\n * @param stage will have the parsed actors appended.\n * @param lmlTemplateFile will be read and parsed. Actors parsed from the template will be added directly into the\n * stage.\n */\n void fillStage(Stage stage, FileHandle lmlTemplateFile);\n\n /**\n * @param view an instance of view object, containing annotated fields and methods that need to be filled and\n * invoked. See LML annotations for more data.\n * @param lmlTemplate will be parsed.\n * @return array of actors parsed from the template.\n * @see LmlView\n * @param class of the view to be initiated.\n */\n Array createView(View view, String lmlTemplate);\n\n /**\n * @param view an instance of view object, containing annotated fields and methods that need to be filled and\n * invoked. See LML annotations for more data.\n * @param lmlTemplateFile will be read and parsed.\n * @return array of actors parsed from the template.\n * @see LmlView\n * @param class of the view to be initiated.\n */\n Array createView(View view, FileHandle lmlTemplateFile);\n\n /**\n * @param viewClass class of the view, containing annotated fields and methods that need to be filled and invoked.\n * See LML annotations for more data.\n * @param lmlTemplate will be parsed.\n * @return a new instance of the view, created with no-argument constructor and filled.\n * @see LmlView\n * @param class of the view to be initiated.\n */\n View createView(Class viewClass, String lmlTemplate);\n\n /**\n * @param viewClass class of the view, containing annotated fields and methods that need to be filled and invoked.\n * See LML annotations for more data.\n * @param lmlTemplateFile will be read and parsed.\n * @return a new instance of the view, created with no-argument constructor and filled.\n * @see LmlView\n * @param class of the view to be initiated.\n */\n View createView(Class viewClass, FileHandle lmlTemplateFile);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual string value.\n * @return parsed string value.\n */\n String parseString(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual float value.\n * @return parsed float value.\n */\n float parseFloat(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual int value.\n * @return parsed int value.\n */\n int parseInt(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual boolean value.\n * @return parsed boolean value.\n */\n boolean parseBoolean(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual array value.\n * @return string value separated and parsed as an array of values according to syntax rules. Note that arrays do\n * NOT fully parse its elements: for example, an array of bundle texts will be split from a raw string to an\n * actual Java array of strings, but will not be immediately converted to formatted bundle lines. This is\n * because arrays are mostly either used by macros or processed further by tag or attribute parsers. Only\n * ranges and actions are parsed.\n */\n String[] parseArray(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual string value.\n * @return string value separated and parsed as an array of values according to syntax rules. On contrary to\n * {@link #parseArray(String)}, this method fully evaluates each array element.\n */\n String[] fullyParseArray(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual action object.\n * @return action referenced with the raw data. Might be null.\n */\n ActorConsumer parseAction(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual string value.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return parsed string value.\n */\n String parseString(String rawLmlData, Object forActor);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual float value.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return parsed float value.\n */\n float parseFloat(String rawLmlData, Object forActor);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual int value.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return parsed int value.\n */\n int parseInt(String rawLmlData, Object forActor);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual boolean value.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return parsed boolean value.\n */\n boolean parseBoolean(String rawLmlData, Object forActor);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual array value.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return string value separated and parsed as an array of values according to syntax rules. Note that arrays do\n * NOT fully parse its elements: for example, an array of bundle texts will be split from a raw string to an\n * actual Java array of strings, but will not be immediately converted to formatted bundle lines. This is\n * because arrays are mostly either used by macros or processed further by tag or attribute parsers. Only\n * ranges and actions are parsed.\n */\n String[] parseArray(String rawLmlData, Object forActor);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual string value.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return string value separated and parsed as an array of values according to syntax rules. On contrary to\n * {@link #parseArray(String, Object)}, this method fully evaluates each array element.\n */\n String[] fullyParseArray(String rawLmlData, Object forActor);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual action object.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return action referenced with the raw data. Might be null.\n * @param type of actor that can be consumed by the action. Performs an unchecked cast, might not\n * actually match consumed actor type - the user should be reference correct actions that can actually\n * process the selected actor.\n */\n ActorConsumer parseAction(String rawLmlData, ActorType forActor);\n\n /**\n * @return direct access to map containing all previously parsed actors that had their ID set with \"id\" tag\n * attribute. This map is filled during template parsing. Since the actual, internal map is returned with\n * this method, it can be used to clear the actors map if you no longer want to keep references to actors,\n * but need the parser itself for further use. The map is not cleared internally: previously parsed actors\n * will be still available if not other widgets override their ID. Note that by default, this map ignores\n * string case - actor mapped to \"myId\" would be also returned for \"myid\", \"MYID\", \"MyID\", etc.\n */\n ObjectMap getActorsMappedByIds();\n\n /**\n * Constructs a complex and (hopefully) meaningful exception message with currently parsed line number.\n *\n * @param message description of the error.\n */\n void throwError(String message);\n\n /**\n * Constructs a complex and (hopefully) meaningful exception message with currently parsed line number.\n *\n * @param message description of the error.\n * @param optionalCause original cause of the message.\n */\n void throwError(String message, Throwable optionalCause);\n\n /**\n * Constructs a complex and (hopefully) meaningful exception message with currently parsed line number. Exception\n * is created and thrown only if the parser is strict.\n *\n * @param message description of the error.\n */\n void throwErrorIfStrict(String message);\n\n /**\n * Constructs a complex and (hopefully) meaningful exception message with currently parsed line number. Exception\n * is created and thrown only if the parser is strict.\n *\n * @param message description of the error.\n * @param optionalCause original cause of the message.\n */\n void throwErrorIfStrict(String message, Throwable optionalCause);\n\n /**\n * Utility internal method. If parsing is currently in progress, this method allows to append the actor to the\n * result collection that will be eventually returned (or used to fill stage/view).\n *\n * @param actor will be added to the result collection and optionally mapped by its ID, if it has one.\n */\n void addActor(Actor actor);\n\n /**\n * @param listener will be invoked after each parsed template. If returns {@link LmlParserListener#REMOVE}, will be\n * removed after invocation.\n */\n void doBeforeParsing(LmlParserListener listener);\n\n /**\n * @param listener will be invoked after each parsed template. If returns {@link LmlParserListener#REMOVE}, will be\n * removed after invocation.\n */\n void doAfterParsing(LmlParserListener listener);\n}\n"} {"task_id": "Java_846", "language": "Java", "task_type": "empty", "source_file": "java/github/czyzby/gdx-lml/lml/src/main/java/com/github/czyzby/lml/parser/LmlParser.java", "mask_start_position": 3234, "mask_end_position": 3234, "canonical_solution": "", "pre_mask_code": "package com.github.czyzby.lml.parser;\n\nimport com.badlogic.gdx.files.FileHandle;\nimport com.badlogic.gdx.scenes.scene2d.Actor;\nimport com.badlogic.gdx.scenes.scene2d.Stage;\nimport com.badlogic.gdx.utils.Array;\nimport com.badlogic.gdx.utils.ObjectMap;\nimport com.github.czyzby.lml.parser.action.ActorConsumer;\n\n/**\n * Common interface for all LML parsers. Provides methods allowing to configure template parsing. Note that\n * implementations are consider NOT thread-safe and templates should be either handled by multiple parsers or one by\n * one.\n *\n * @author MJ\n * @see com.github.czyzby.lml.parser.impl.DefaultLmlParser\n */\npublic interface LmlParser {\n\n /**\n * @param lmlData contains references to skins, bundles and preferences needed to parse LML templates. Cannot be\n * null.\n */\n void setData(LmlData lmlData);\n\n /**\n * @return data container with references to skins, bundles and preferences needed to parse LML templates.\n */\n LmlData getData();\n\n /**\n * @param templateReader will become parser's reader, used to process raw text data. Cannot be null.\n */\n void setTemplateReader(LmlTemplateReader templateReader);\n\n /**\n * @return direct access to template reader used by the LML parser. Templates should not be appended directly to\n * the reader, especially during templates parsing - this object is mostly for internal parser's use.\n */\n LmlTemplateReader getTemplateReader();\n\n /**\n * @param lmlSyntax will become current LML syntax, determining how templates are parsed. Cannot be null.\n */\n void setSyntax(LmlSyntax lmlSyntax);\n\n /**\n * @return current used template syntax. Can be safely modified most of the time, but generally should be left\n * alone if template parsing is currently in progress.\n */\n LmlSyntax getSyntax();\n\n /**\n * @param styleSheet will be used to provide default values for tags' attributes.\n */\n void setStyleSheet(LmlStyleSheet styleSheet);\n\n /**\n * @return style sheet currently used to provide default values for tags' attributes. Can safely modified.\n */\n LmlStyleSheet getStyleSheet();\n\n /**\n * @return true if parser is strict and throws errors for unknown tags, attributes, etc.\n */\n boolean isStrict();\n\n /**\n * @param strict if true, parser throws errors for unknown tags, attributes, etc. Set to false for more HTML-like\n * feel of everything generally working even if something is terribly wrong.\n */\n void setStrict(boolean strict);\n\n /**\n * @param nestedComments if true, comments are nested and NEED to be valid. In HTML, comments are not nested, so\n * commenting-out a whole file full of other comments is problematic; this is also the default behavior\n * of LML, since this way comments you don't need to validate all your tags (for example, you might open\n * a comment tag by mistake inside another comment). However, if you're sure you'll keep for comments\n * clean and need a way to quickly comment-out huge portions of templates, set this value to true.\n */\n void setNestedComments(boolean nestedComment", "post_mask_code": "s);\n\n /**\n * @param lmlTemplate will be parsed.\n * @return parsed root actors, in the order that they appear in the template.\n */\n Array parseTemplate(String lmlTemplate);\n\n /**\n * @param lmlTemplateFile will be read and parsed.\n * @return parsed root actors, in the order that they appear in the template.\n */\n Array parseTemplate(FileHandle lmlTemplateFile);\n\n /**\n * @param styleSheet LML style sheet code. Will be processed.\n * @see #getStyleSheet()\n */\n void parseStyleSheet(String styleSheet);\n\n /**\n * @param styleSheetFile path to a file storing LML style sheet code. Will be processed.\n * @see #getStyleSheet()\n */\n void parseStyleSheet(FileHandle styleSheetFile);\n\n /**\n * @param stage will have the parsed actors appended.\n * @param lmlTemplate will be parsed. Actors parsed from the template will be added directly into the stage.\n */\n void fillStage(Stage stage, String lmlTemplate);\n\n /**\n * @param stage will have the parsed actors appended.\n * @param lmlTemplateFile will be read and parsed. Actors parsed from the template will be added directly into the\n * stage.\n */\n void fillStage(Stage stage, FileHandle lmlTemplateFile);\n\n /**\n * @param view an instance of view object, containing annotated fields and methods that need to be filled and\n * invoked. See LML annotations for more data.\n * @param lmlTemplate will be parsed.\n * @return array of actors parsed from the template.\n * @see LmlView\n * @param class of the view to be initiated.\n */\n Array createView(View view, String lmlTemplate);\n\n /**\n * @param view an instance of view object, containing annotated fields and methods that need to be filled and\n * invoked. See LML annotations for more data.\n * @param lmlTemplateFile will be read and parsed.\n * @return array of actors parsed from the template.\n * @see LmlView\n * @param class of the view to be initiated.\n */\n Array createView(View view, FileHandle lmlTemplateFile);\n\n /**\n * @param viewClass class of the view, containing annotated fields and methods that need to be filled and invoked.\n * See LML annotations for more data.\n * @param lmlTemplate will be parsed.\n * @return a new instance of the view, created with no-argument constructor and filled.\n * @see LmlView\n * @param class of the view to be initiated.\n */\n View createView(Class viewClass, String lmlTemplate);\n\n /**\n * @param viewClass class of the view, containing annotated fields and methods that need to be filled and invoked.\n * See LML annotations for more data.\n * @param lmlTemplateFile will be read and parsed.\n * @return a new instance of the view, created with no-argument constructor and filled.\n * @see LmlView\n * @param class of the view to be initiated.\n */\n View createView(Class viewClass, FileHandle lmlTemplateFile);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual string value.\n * @return parsed string value.\n */\n String parseString(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual float value.\n * @return parsed float value.\n */\n float parseFloat(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual int value.\n * @return parsed int value.\n */\n int parseInt(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual boolean value.\n * @return parsed boolean value.\n */\n boolean parseBoolean(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual array value.\n * @return string value separated and parsed as an array of values according to syntax rules. Note that arrays do\n * NOT fully parse its elements: for example, an array of bundle texts will be split from a raw string to an\n * actual Java array of strings, but will not be immediately converted to formatted bundle lines. This is\n * because arrays are mostly either used by macros or processed further by tag or attribute parsers. Only\n * ranges and actions are parsed.\n */\n String[] parseArray(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual string value.\n * @return string value separated and parsed as an array of values according to syntax rules. On contrary to\n * {@link #parseArray(String)}, this method fully evaluates each array element.\n */\n String[] fullyParseArray(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual action object.\n * @return action referenced with the raw data. Might be null.\n */\n ActorConsumer parseAction(String rawLmlData);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual string value.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return parsed string value.\n */\n String parseString(String rawLmlData, Object forActor);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual float value.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return parsed float value.\n */\n float parseFloat(String rawLmlData, Object forActor);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual int value.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return parsed int value.\n */\n int parseInt(String rawLmlData, Object forActor);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual boolean value.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return parsed boolean value.\n */\n boolean parseBoolean(String rawLmlData, Object forActor);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual array value.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return string value separated and parsed as an array of values according to syntax rules. Note that arrays do\n * NOT fully parse its elements: for example, an array of bundle texts will be split from a raw string to an\n * actual Java array of strings, but will not be immediately converted to formatted bundle lines. This is\n * because arrays are mostly either used by macros or processed further by tag or attribute parsers. Only\n * ranges and actions are parsed.\n */\n String[] parseArray(String rawLmlData, Object forActor);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual string value.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return string value separated and parsed as an array of values according to syntax rules. On contrary to\n * {@link #parseArray(String, Object)}, this method fully evaluates each array element.\n */\n String[] fullyParseArray(String rawLmlData, Object forActor);\n\n /**\n * Mostly for internal use, although can be very useful for checking how each text part is parsed in your current\n * parser setup or in custom attributes.\n *\n * @param rawLmlData unparsed part of LML template that should be parsed to actual action object.\n * @param forActor some types of data (for example: method invocations) require a parameter to be properly\n * retrieved. Although for most types this object is optional, others might produce invalid results\n * without it or even will not work at all.\n * @return action referenced with the raw data. Might be null.\n * @param type of actor that can be consumed by the action. Performs an unchecked cast, might not\n * actually match consumed actor type - the user should be reference correct actions that can actually\n * process the selected actor.\n */\n ActorConsumer parseAction(String rawLmlData, ActorType forActor);\n\n /**\n * @return direct access to map containing all previously parsed actors that had their ID set with \"id\" tag\n * attribute. This map is filled during template parsing. Since the actual, internal map is returned with\n * this method, it can be used to clear the actors map if you no longer want to keep references to actors,\n * but need the parser itself for further use. The map is not cleared internally: previously parsed actors\n * will be still available if not other widgets override their ID. Note that by default, this map ignores\n * string case - actor mapped to \"myId\" would be also returned for \"myid\", \"MYID\", \"MyID\", etc.\n */\n ObjectMap getActorsMappedByIds();\n\n /**\n * Constructs a complex and (hopefully) meaningful exception message with currently parsed line number.\n *\n * @param message description of the error.\n */\n void throwError(String message);\n\n /**\n * Constructs a complex and (hopefully) meaningful exception message with currently parsed line number.\n *\n * @param message description of the error.\n * @param optionalCause original cause of the message.\n */\n void throwError(String message, Throwable optionalCause);\n\n /**\n * Constructs a complex and (hopefully) meaningful exception message with currently parsed line number. Exception\n * is created and thrown only if the parser is strict.\n *\n * @param message description of the error.\n */\n void throwErrorIfStrict(String message);\n\n /**\n * Constructs a complex and (hopefully) meaningful exception message with currently parsed line number. Exception\n * is created and thrown only if the parser is strict.\n *\n * @param message description of the error.\n * @param optionalCause original cause of the message.\n */\n void throwErrorIfStrict(String message, Throwable optionalCause);\n\n /**\n * Utility internal method. If parsing is currently in progress, this method allows to append the actor to the\n * result collection that will be eventually returned (or used to fill stage/view).\n *\n * @param actor will be added to the result collection and optionally mapped by its ID, if it has one.\n */\n void addActor(Actor actor);\n\n /**\n * @param listener will be invoked after each parsed template. If returns {@link LmlParserListener#REMOVE}, will be\n * removed after invocation.\n */\n void doBeforeParsing(LmlParserListener listener);\n\n /**\n * @param listener will be invoked after each parsed template. If returns {@link LmlParserListener#REMOVE}, will be\n * removed after invocation.\n */\n void doAfterParsing(LmlParserListener listener);\n}\n"} {"task_id": "Java_847", "language": "Java", "task_type": "method_signature", "source_file": "java/github/qndroid/CommonLibrary/CommonHttpLibrary/src/com/nineoldandroids/view/ViewPropertyAnimatorICS.java", "mask_start_position": 7185, "mask_end_position": 7249, "canonical_solution": "@Override\n public ViewPropertyAnimator scaleXBy(float value) ", "pre_mask_code": "package com.nineoldandroids.view;\n\nimport java.lang.ref.WeakReference;\nimport android.view.View;\nimport android.view.animation.Interpolator;\nimport com.nineoldandroids.animation.Animator.AnimatorListener;\n\n/**\n * *******************************************************\n * @文件名称:ViewPropertyAnimatorICS.java\n * @文件作者:renzhiqiang\n * @创建时间:2015年9月28日 下午11:11:12\n * @文件描述:API11以后实现view.ViewPropertyAnimator\n * @修改历史:2015年9月28日创建初始版本\n * ********************************************************\n */\nclass ViewPropertyAnimatorICS extends ViewPropertyAnimator {\n\n /**\n * A value to be returned when the WeakReference holding the native implementation\n * returns null\n */\n private final static long RETURN_WHEN_NULL = -1L;\n\n /**\n * A WeakReference holding the native implementation of ViewPropertyAnimator\n */\n private final WeakReference mNative;\n\n ViewPropertyAnimatorICS(View view) {\n mNative = new WeakReference(view.animate());\n }\n\n @Override\n public ViewPropertyAnimator setDuration(long duration) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setDuration(duration);\n }\n return this;\n }\n\n @Override\n public long getDuration() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getDuration();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setStartDelay(long startDelay) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setStartDelay(startDelay);\n }\n return this;\n }\n\n @Override\n public long getStartDelay() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getStartDelay();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setInterpolator(Interpolator interpolator) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setInterpolator(interpolator);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator setListener(final AnimatorListener listener) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n if (listener == null) {\n n.setListener(null);\n } else {\n n.setListener(new android.animation.Animator.AnimatorListener() {\n\n @Override\n public void onAnimationStart(android.animation.Animator animation) {\n listener.onAnimationStart(null);\n }\n\n @Override\n public void onAnimationRepeat(android.animation.Animator animation) {\n listener.onAnimationRepeat(null);\n }\n\n @Override\n public void onAnimationEnd(android.animation.Animator animation) {\n listener.onAnimationEnd(null);\n }\n\n @Override\n public void onAnimationCancel(android.animation.Animator animation) {\n listener.onAnimationCancel(null);\n }\n });\n }\n }\n return this;\n }\n\n @Override\n public void start() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.start();\n }\n }\n\n @Override\n public void cancel() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.cancel();\n }\n }\n\n @Override\n public ViewPropertyAnimator x(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.x(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator xBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.xBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator y(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.y(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator yBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.yBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotation(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotation(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleX(value);\n }\n return this;\n }\n\n ", "post_mask_code": "{\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alpha(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alpha(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alphaBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alphaBy(value);\n }\n return this;\n }\n}\n"} {"task_id": "Java_848", "language": "Java", "task_type": "method_body", "source_file": "java/github/qndroid/CommonLibrary/CommonHttpLibrary/src/com/nineoldandroids/view/ViewPropertyAnimatorICS.java", "mask_start_position": 4072, "mask_end_position": 4222, "canonical_solution": "{\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.xBy(value);\n }\n return this;\n }", "pre_mask_code": "package com.nineoldandroids.view;\n\nimport java.lang.ref.WeakReference;\nimport android.view.View;\nimport android.view.animation.Interpolator;\nimport com.nineoldandroids.animation.Animator.AnimatorListener;\n\n/**\n * *******************************************************\n * @文件名称:ViewPropertyAnimatorICS.java\n * @文件作者:renzhiqiang\n * @创建时间:2015年9月28日 下午11:11:12\n * @文件描述:API11以后实现view.ViewPropertyAnimator\n * @修改历史:2015年9月28日创建初始版本\n * ********************************************************\n */\nclass ViewPropertyAnimatorICS extends ViewPropertyAnimator {\n\n /**\n * A value to be returned when the WeakReference holding the native implementation\n * returns null\n */\n private final static long RETURN_WHEN_NULL = -1L;\n\n /**\n * A WeakReference holding the native implementation of ViewPropertyAnimator\n */\n private final WeakReference mNative;\n\n ViewPropertyAnimatorICS(View view) {\n mNative = new WeakReference(view.animate());\n }\n\n @Override\n public ViewPropertyAnimator setDuration(long duration) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setDuration(duration);\n }\n return this;\n }\n\n @Override\n public long getDuration() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getDuration();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setStartDelay(long startDelay) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setStartDelay(startDelay);\n }\n return this;\n }\n\n @Override\n public long getStartDelay() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getStartDelay();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setInterpolator(Interpolator interpolator) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setInterpolator(interpolator);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator setListener(final AnimatorListener listener) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n if (listener == null) {\n n.setListener(null);\n } else {\n n.setListener(new android.animation.Animator.AnimatorListener() {\n\n @Override\n public void onAnimationStart(android.animation.Animator animation) {\n listener.onAnimationStart(null);\n }\n\n @Override\n public void onAnimationRepeat(android.animation.Animator animation) {\n listener.onAnimationRepeat(null);\n }\n\n @Override\n public void onAnimationEnd(android.animation.Animator animation) {\n listener.onAnimationEnd(null);\n }\n\n @Override\n public void onAnimationCancel(android.animation.Animator animation) {\n listener.onAnimationCancel(null);\n }\n });\n }\n }\n return this;\n }\n\n @Override\n public void start() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.start();\n }\n }\n\n @Override\n public void cancel() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.cancel();\n }\n }\n\n @Override\n public ViewPropertyAnimator x(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.x(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator xBy(float value) ", "post_mask_code": "\n\n @Override\n public ViewPropertyAnimator y(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.y(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator yBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.yBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotation(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotation(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alpha(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alpha(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alphaBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alphaBy(value);\n }\n return this;\n }\n}\n"} {"task_id": "Java_849", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/qndroid/CommonLibrary/CommonHttpLibrary/src/com/nineoldandroids/view/ViewPropertyAnimatorICS.java", "mask_start_position": 5174, "mask_end_position": 5235, "canonical_solution": "\n android.view.ViewPropertyAnimator n = mNative.get();", "pre_mask_code": "package com.nineoldandroids.view;\n\nimport java.lang.ref.WeakReference;\nimport android.view.View;\nimport android.view.animation.Interpolator;\nimport com.nineoldandroids.animation.Animator.AnimatorListener;\n\n/**\n * *******************************************************\n * @文件名称:ViewPropertyAnimatorICS.java\n * @文件作者:renzhiqiang\n * @创建时间:2015年9月28日 下午11:11:12\n * @文件描述:API11以后实现view.ViewPropertyAnimator\n * @修改历史:2015年9月28日创建初始版本\n * ********************************************************\n */\nclass ViewPropertyAnimatorICS extends ViewPropertyAnimator {\n\n /**\n * A value to be returned when the WeakReference holding the native implementation\n * returns null\n */\n private final static long RETURN_WHEN_NULL = -1L;\n\n /**\n * A WeakReference holding the native implementation of ViewPropertyAnimator\n */\n private final WeakReference mNative;\n\n ViewPropertyAnimatorICS(View view) {\n mNative = new WeakReference(view.animate());\n }\n\n @Override\n public ViewPropertyAnimator setDuration(long duration) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setDuration(duration);\n }\n return this;\n }\n\n @Override\n public long getDuration() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getDuration();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setStartDelay(long startDelay) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setStartDelay(startDelay);\n }\n return this;\n }\n\n @Override\n public long getStartDelay() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getStartDelay();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setInterpolator(Interpolator interpolator) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setInterpolator(interpolator);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator setListener(final AnimatorListener listener) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n if (listener == null) {\n n.setListener(null);\n } else {\n n.setListener(new android.animation.Animator.AnimatorListener() {\n\n @Override\n public void onAnimationStart(android.animation.Animator animation) {\n listener.onAnimationStart(null);\n }\n\n @Override\n public void onAnimationRepeat(android.animation.Animator animation) {\n listener.onAnimationRepeat(null);\n }\n\n @Override\n public void onAnimationEnd(android.animation.Animator animation) {\n listener.onAnimationEnd(null);\n }\n\n @Override\n public void onAnimationCancel(android.animation.Animator animation) {\n listener.onAnimationCancel(null);\n }\n });\n }\n }\n return this;\n }\n\n @Override\n public void start() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.start();\n }\n }\n\n @Override\n public void cancel() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.cancel();\n }\n }\n\n @Override\n public ViewPropertyAnimator x(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.x(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator xBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.xBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator y(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.y(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator yBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.yBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotation(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotation(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationX(float value) {", "post_mask_code": "\n if (n != null) {\n n.rotationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alpha(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alpha(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alphaBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alphaBy(value);\n }\n return this;\n }\n}\n"} {"task_id": "Java_850", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/qndroid/CommonLibrary/CommonHttpLibrary/src/com/nineoldandroids/view/ViewPropertyAnimatorICS.java", "mask_start_position": 5244, "mask_end_position": 5302, "canonical_solution": "if (n != null) {\n n.rotationX(value);\n }", "pre_mask_code": "package com.nineoldandroids.view;\n\nimport java.lang.ref.WeakReference;\nimport android.view.View;\nimport android.view.animation.Interpolator;\nimport com.nineoldandroids.animation.Animator.AnimatorListener;\n\n/**\n * *******************************************************\n * @文件名称:ViewPropertyAnimatorICS.java\n * @文件作者:renzhiqiang\n * @创建时间:2015年9月28日 下午11:11:12\n * @文件描述:API11以后实现view.ViewPropertyAnimator\n * @修改历史:2015年9月28日创建初始版本\n * ********************************************************\n */\nclass ViewPropertyAnimatorICS extends ViewPropertyAnimator {\n\n /**\n * A value to be returned when the WeakReference holding the native implementation\n * returns null\n */\n private final static long RETURN_WHEN_NULL = -1L;\n\n /**\n * A WeakReference holding the native implementation of ViewPropertyAnimator\n */\n private final WeakReference mNative;\n\n ViewPropertyAnimatorICS(View view) {\n mNative = new WeakReference(view.animate());\n }\n\n @Override\n public ViewPropertyAnimator setDuration(long duration) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setDuration(duration);\n }\n return this;\n }\n\n @Override\n public long getDuration() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getDuration();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setStartDelay(long startDelay) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setStartDelay(startDelay);\n }\n return this;\n }\n\n @Override\n public long getStartDelay() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getStartDelay();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setInterpolator(Interpolator interpolator) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setInterpolator(interpolator);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator setListener(final AnimatorListener listener) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n if (listener == null) {\n n.setListener(null);\n } else {\n n.setListener(new android.animation.Animator.AnimatorListener() {\n\n @Override\n public void onAnimationStart(android.animation.Animator animation) {\n listener.onAnimationStart(null);\n }\n\n @Override\n public void onAnimationRepeat(android.animation.Animator animation) {\n listener.onAnimationRepeat(null);\n }\n\n @Override\n public void onAnimationEnd(android.animation.Animator animation) {\n listener.onAnimationEnd(null);\n }\n\n @Override\n public void onAnimationCancel(android.animation.Animator animation) {\n listener.onAnimationCancel(null);\n }\n });\n }\n }\n return this;\n }\n\n @Override\n public void start() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.start();\n }\n }\n\n @Override\n public void cancel() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.cancel();\n }\n }\n\n @Override\n public ViewPropertyAnimator x(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.x(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator xBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.xBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator y(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.y(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator yBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.yBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotation(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotation(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n ", "post_mask_code": "\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alpha(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alpha(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alphaBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alphaBy(value);\n }\n return this;\n }\n}\n"} {"task_id": "Java_851", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/qndroid/CommonLibrary/CommonHttpLibrary/src/com/nineoldandroids/view/ViewPropertyAnimatorICS.java", "mask_start_position": 5311, "mask_end_position": 5329, "canonical_solution": "return this;\n }", "pre_mask_code": "package com.nineoldandroids.view;\n\nimport java.lang.ref.WeakReference;\nimport android.view.View;\nimport android.view.animation.Interpolator;\nimport com.nineoldandroids.animation.Animator.AnimatorListener;\n\n/**\n * *******************************************************\n * @文件名称:ViewPropertyAnimatorICS.java\n * @文件作者:renzhiqiang\n * @创建时间:2015年9月28日 下午11:11:12\n * @文件描述:API11以后实现view.ViewPropertyAnimator\n * @修改历史:2015年9月28日创建初始版本\n * ********************************************************\n */\nclass ViewPropertyAnimatorICS extends ViewPropertyAnimator {\n\n /**\n * A value to be returned when the WeakReference holding the native implementation\n * returns null\n */\n private final static long RETURN_WHEN_NULL = -1L;\n\n /**\n * A WeakReference holding the native implementation of ViewPropertyAnimator\n */\n private final WeakReference mNative;\n\n ViewPropertyAnimatorICS(View view) {\n mNative = new WeakReference(view.animate());\n }\n\n @Override\n public ViewPropertyAnimator setDuration(long duration) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setDuration(duration);\n }\n return this;\n }\n\n @Override\n public long getDuration() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getDuration();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setStartDelay(long startDelay) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setStartDelay(startDelay);\n }\n return this;\n }\n\n @Override\n public long getStartDelay() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getStartDelay();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setInterpolator(Interpolator interpolator) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setInterpolator(interpolator);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator setListener(final AnimatorListener listener) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n if (listener == null) {\n n.setListener(null);\n } else {\n n.setListener(new android.animation.Animator.AnimatorListener() {\n\n @Override\n public void onAnimationStart(android.animation.Animator animation) {\n listener.onAnimationStart(null);\n }\n\n @Override\n public void onAnimationRepeat(android.animation.Animator animation) {\n listener.onAnimationRepeat(null);\n }\n\n @Override\n public void onAnimationEnd(android.animation.Animator animation) {\n listener.onAnimationEnd(null);\n }\n\n @Override\n public void onAnimationCancel(android.animation.Animator animation) {\n listener.onAnimationCancel(null);\n }\n });\n }\n }\n return this;\n }\n\n @Override\n public void start() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.start();\n }\n }\n\n @Override\n public void cancel() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.cancel();\n }\n }\n\n @Override\n public ViewPropertyAnimator x(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.x(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator xBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.xBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator y(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.y(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator yBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.yBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotation(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotation(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationX(value);\n }\n ", "post_mask_code": "\n\n @Override\n public ViewPropertyAnimator rotationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alpha(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alpha(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alphaBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alphaBy(value);\n }\n return this;\n }\n}\n"} {"task_id": "Java_852", "language": "Java", "task_type": "single_line", "source_file": "java/github/qndroid/CommonLibrary/CommonHttpLibrary/src/com/nineoldandroids/view/ViewPropertyAnimatorICS.java", "mask_start_position": 1379, "mask_end_position": 1403, "canonical_solution": "mator n = mNative.get();", "pre_mask_code": "package com.nineoldandroids.view;\n\nimport java.lang.ref.WeakReference;\nimport android.view.View;\nimport android.view.animation.Interpolator;\nimport com.nineoldandroids.animation.Animator.AnimatorListener;\n\n/**\n * *******************************************************\n * @文件名称:ViewPropertyAnimatorICS.java\n * @文件作者:renzhiqiang\n * @创建时间:2015年9月28日 下午11:11:12\n * @文件描述:API11以后实现view.ViewPropertyAnimator\n * @修改历史:2015年9月28日创建初始版本\n * ********************************************************\n */\nclass ViewPropertyAnimatorICS extends ViewPropertyAnimator {\n\n /**\n * A value to be returned when the WeakReference holding the native implementation\n * returns null\n */\n private final static long RETURN_WHEN_NULL = -1L;\n\n /**\n * A WeakReference holding the native implementation of ViewPropertyAnimator\n */\n private final WeakReference mNative;\n\n ViewPropertyAnimatorICS(View view) {\n mNative = new WeakReference(view.animate());\n }\n\n @Override\n public ViewPropertyAnimator setDuration(long duration) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setDuration(duration);\n }\n return this;\n }\n\n @Override\n public long getDuration() {\n android.view.ViewPropertyAni", "post_mask_code": "\n if (n != null) {\n return n.getDuration();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setStartDelay(long startDelay) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setStartDelay(startDelay);\n }\n return this;\n }\n\n @Override\n public long getStartDelay() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getStartDelay();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setInterpolator(Interpolator interpolator) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setInterpolator(interpolator);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator setListener(final AnimatorListener listener) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n if (listener == null) {\n n.setListener(null);\n } else {\n n.setListener(new android.animation.Animator.AnimatorListener() {\n\n @Override\n public void onAnimationStart(android.animation.Animator animation) {\n listener.onAnimationStart(null);\n }\n\n @Override\n public void onAnimationRepeat(android.animation.Animator animation) {\n listener.onAnimationRepeat(null);\n }\n\n @Override\n public void onAnimationEnd(android.animation.Animator animation) {\n listener.onAnimationEnd(null);\n }\n\n @Override\n public void onAnimationCancel(android.animation.Animator animation) {\n listener.onAnimationCancel(null);\n }\n });\n }\n }\n return this;\n }\n\n @Override\n public void start() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.start();\n }\n }\n\n @Override\n public void cancel() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.cancel();\n }\n }\n\n @Override\n public ViewPropertyAnimator x(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.x(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator xBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.xBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator y(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.y(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator yBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.yBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotation(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotation(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alpha(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alpha(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alphaBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alphaBy(value);\n }\n return this;\n }\n}\n"} {"task_id": "Java_853", "language": "Java", "task_type": "if_statement", "source_file": "java/github/qndroid/CommonLibrary/CommonHttpLibrary/src/com/nineoldandroids/view/ViewPropertyAnimatorICS.java", "mask_start_position": 5244, "mask_end_position": 5302, "canonical_solution": "if (n != null) {\n n.rotationX(value);\n }", "pre_mask_code": "package com.nineoldandroids.view;\n\nimport java.lang.ref.WeakReference;\nimport android.view.View;\nimport android.view.animation.Interpolator;\nimport com.nineoldandroids.animation.Animator.AnimatorListener;\n\n/**\n * *******************************************************\n * @文件名称:ViewPropertyAnimatorICS.java\n * @文件作者:renzhiqiang\n * @创建时间:2015年9月28日 下午11:11:12\n * @文件描述:API11以后实现view.ViewPropertyAnimator\n * @修改历史:2015年9月28日创建初始版本\n * ********************************************************\n */\nclass ViewPropertyAnimatorICS extends ViewPropertyAnimator {\n\n /**\n * A value to be returned when the WeakReference holding the native implementation\n * returns null\n */\n private final static long RETURN_WHEN_NULL = -1L;\n\n /**\n * A WeakReference holding the native implementation of ViewPropertyAnimator\n */\n private final WeakReference mNative;\n\n ViewPropertyAnimatorICS(View view) {\n mNative = new WeakReference(view.animate());\n }\n\n @Override\n public ViewPropertyAnimator setDuration(long duration) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setDuration(duration);\n }\n return this;\n }\n\n @Override\n public long getDuration() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getDuration();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setStartDelay(long startDelay) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setStartDelay(startDelay);\n }\n return this;\n }\n\n @Override\n public long getStartDelay() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getStartDelay();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setInterpolator(Interpolator interpolator) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setInterpolator(interpolator);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator setListener(final AnimatorListener listener) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n if (listener == null) {\n n.setListener(null);\n } else {\n n.setListener(new android.animation.Animator.AnimatorListener() {\n\n @Override\n public void onAnimationStart(android.animation.Animator animation) {\n listener.onAnimationStart(null);\n }\n\n @Override\n public void onAnimationRepeat(android.animation.Animator animation) {\n listener.onAnimationRepeat(null);\n }\n\n @Override\n public void onAnimationEnd(android.animation.Animator animation) {\n listener.onAnimationEnd(null);\n }\n\n @Override\n public void onAnimationCancel(android.animation.Animator animation) {\n listener.onAnimationCancel(null);\n }\n });\n }\n }\n return this;\n }\n\n @Override\n public void start() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.start();\n }\n }\n\n @Override\n public void cancel() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.cancel();\n }\n }\n\n @Override\n public ViewPropertyAnimator x(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.x(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator xBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.xBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator y(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.y(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator yBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.yBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotation(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotation(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n ", "post_mask_code": "\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alpha(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alpha(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alphaBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alphaBy(value);\n }\n return this;\n }\n}\n"} {"task_id": "Java_854", "language": "Java", "task_type": "empty", "source_file": "java/github/qndroid/CommonLibrary/CommonHttpLibrary/src/com/nineoldandroids/view/ViewPropertyAnimatorICS.java", "mask_start_position": 4200, "mask_end_position": 4200, "canonical_solution": "", "pre_mask_code": "package com.nineoldandroids.view;\n\nimport java.lang.ref.WeakReference;\nimport android.view.View;\nimport android.view.animation.Interpolator;\nimport com.nineoldandroids.animation.Animator.AnimatorListener;\n\n/**\n * *******************************************************\n * @文件名称:ViewPropertyAnimatorICS.java\n * @文件作者:renzhiqiang\n * @创建时间:2015年9月28日 下午11:11:12\n * @文件描述:API11以后实现view.ViewPropertyAnimator\n * @修改历史:2015年9月28日创建初始版本\n * ********************************************************\n */\nclass ViewPropertyAnimatorICS extends ViewPropertyAnimator {\n\n /**\n * A value to be returned when the WeakReference holding the native implementation\n * returns null\n */\n private final static long RETURN_WHEN_NULL = -1L;\n\n /**\n * A WeakReference holding the native implementation of ViewPropertyAnimator\n */\n private final WeakReference mNative;\n\n ViewPropertyAnimatorICS(View view) {\n mNative = new WeakReference(view.animate());\n }\n\n @Override\n public ViewPropertyAnimator setDuration(long duration) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setDuration(duration);\n }\n return this;\n }\n\n @Override\n public long getDuration() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getDuration();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setStartDelay(long startDelay) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setStartDelay(startDelay);\n }\n return this;\n }\n\n @Override\n public long getStartDelay() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n return n.getStartDelay();\n }\n return RETURN_WHEN_NULL;\n }\n\n @Override\n public ViewPropertyAnimator setInterpolator(Interpolator interpolator) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.setInterpolator(interpolator);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator setListener(final AnimatorListener listener) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n if (listener == null) {\n n.setListener(null);\n } else {\n n.setListener(new android.animation.Animator.AnimatorListener() {\n\n @Override\n public void onAnimationStart(android.animation.Animator animation) {\n listener.onAnimationStart(null);\n }\n\n @Override\n public void onAnimationRepeat(android.animation.Animator animation) {\n listener.onAnimationRepeat(null);\n }\n\n @Override\n public void onAnimationEnd(android.animation.Animator animation) {\n listener.onAnimationEnd(null);\n }\n\n @Override\n public void onAnimationCancel(android.animation.Animator animation) {\n listener.onAnimationCancel(null);\n }\n });\n }\n }\n return this;\n }\n\n @Override\n public void start() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.start();\n }\n }\n\n @Override\n public void cancel() {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.cancel();\n }\n }\n\n @Override\n public ViewPropertyAnimator x(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.x(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator xBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.xBy(value);\n }\n ", "post_mask_code": " return this;\n }\n\n @Override\n public ViewPropertyAnimator y(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.y(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator yBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.yBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotation(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotation(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator rotationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.rotationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator translationYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.translationYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleX(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleX(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleXBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleXBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleY(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleY(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator scaleYBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.scaleYBy(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alpha(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alpha(value);\n }\n return this;\n }\n\n @Override\n public ViewPropertyAnimator alphaBy(float value) {\n android.view.ViewPropertyAnimator n = mNative.get();\n if (n != null) {\n n.alphaBy(value);\n }\n return this;\n }\n}\n"} {"task_id": "Java_855", "language": "Java", "task_type": "method_signature", "source_file": "java/github/PacktPublishing/Java-Coding-Problems/Chapter11/P214_ForkJoinSum/src/modern/challenge/Main.java", "mask_start_position": 286, "mask_end_position": 325, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "package modern.challenge;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.concurrent.ForkJoinPool;\nimport java.util.logging.Logger;\n\npublic class Main {\n\n private static final Logger logger = Logger.getLogger(Main.class.getName());\n\n ", "post_mask_code": "{\n System.setProperty(\"java.util.logging.SimpleFormatter.format\", \"[%1$tT] [%4$-7s] %5$s %n\");\n int noOfProcessors = Runtime.getRuntime().availableProcessors();\n logger.info(() -> \"Available processors: \" + noOfProcessors);\n ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();\n int initialPoolSize = forkJoinPool.getPoolSize();\n int commonPoolParallelism = ForkJoinPool.getCommonPoolParallelism();\n logger.info(() -> \"Common Pool parallelism :\" + commonPoolParallelism);\n logger.info(() -> \"Common Pool size before:\" + initialPoolSize);\n Random rnd = new Random();\n List list = new ArrayList<>();\n for (int i = 0; i < 200; i++) {\n list.add(1 + rnd.nextInt(10));\n }\n SumRecursiveTask sumRecursiveTask = new SumRecursiveTask(list);\n Integer sumAll = forkJoinPool.invoke(sumRecursiveTask);\n logger.info(() -> \"Final sum: \" + sumAll);\n int afterPoolSize = forkJoinPool.getPoolSize();\n logger.info(() -> \"Common Pool size after :\" + afterPoolSize);\n }\n}\n"} {"task_id": "Java_856", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/PacktPublishing/Java-Coding-Problems/Chapter11/P214_ForkJoinSum/src/modern/challenge/Main.java", "mask_start_position": 326, "mask_end_position": 690, "canonical_solution": "\n System.setProperty(\"java.util.logging.SimpleFormatter.format\", \"[%1$tT] [%4$-7s] %5$s %n\");\n int noOfProcessors = Runtime.getRuntime().availableProcessors();\n logger.info(() -> \"Available processors: \" + noOfProcessors);\n ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();\n int initialPoolSize = forkJoinPool.getPoolSize();", "pre_mask_code": "package modern.challenge;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.concurrent.ForkJoinPool;\nimport java.util.logging.Logger;\n\npublic class Main {\n\n private static final Logger logger = Logger.getLogger(Main.class.getName());\n\n public static void main(String[] args) {", "post_mask_code": "\n int commonPoolParallelism = ForkJoinPool.getCommonPoolParallelism();\n logger.info(() -> \"Common Pool parallelism :\" + commonPoolParallelism);\n logger.info(() -> \"Common Pool size before:\" + initialPoolSize);\n Random rnd = new Random();\n List list = new ArrayList<>();\n for (int i = 0; i < 200; i++) {\n list.add(1 + rnd.nextInt(10));\n }\n SumRecursiveTask sumRecursiveTask = new SumRecursiveTask(list);\n Integer sumAll = forkJoinPool.invoke(sumRecursiveTask);\n logger.info(() -> \"Final sum: \" + sumAll);\n int afterPoolSize = forkJoinPool.getPoolSize();\n logger.info(() -> \"Common Pool size after :\" + afterPoolSize);\n }\n}\n"} {"task_id": "Java_857", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/PacktPublishing/Java-Coding-Problems/Chapter11/P214_ForkJoinSum/src/modern/challenge/Main.java", "mask_start_position": 699, "mask_end_position": 1096, "canonical_solution": "int commonPoolParallelism = ForkJoinPool.getCommonPoolParallelism();\n logger.info(() -> \"Common Pool parallelism :\" + commonPoolParallelism);\n logger.info(() -> \"Common Pool size before:\" + initialPoolSize);\n Random rnd = new Random();\n List list = new ArrayList<>();\n for (int i = 0; i < 200; i++) {\n list.add(1 + rnd.nextInt(10));\n }", "pre_mask_code": "package modern.challenge;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.concurrent.ForkJoinPool;\nimport java.util.logging.Logger;\n\npublic class Main {\n\n private static final Logger logger = Logger.getLogger(Main.class.getName());\n\n public static void main(String[] args) {\n System.setProperty(\"java.util.logging.SimpleFormatter.format\", \"[%1$tT] [%4$-7s] %5$s %n\");\n int noOfProcessors = Runtime.getRuntime().availableProcessors();\n logger.info(() -> \"Available processors: \" + noOfProcessors);\n ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();\n int initialPoolSize = forkJoinPool.getPoolSize();\n ", "post_mask_code": "\n SumRecursiveTask sumRecursiveTask = new SumRecursiveTask(list);\n Integer sumAll = forkJoinPool.invoke(sumRecursiveTask);\n logger.info(() -> \"Final sum: \" + sumAll);\n int afterPoolSize = forkJoinPool.getPoolSize();\n logger.info(() -> \"Common Pool size after :\" + afterPoolSize);\n }\n}\n"} {"task_id": "Java_858", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/PacktPublishing/Java-Coding-Problems/Chapter11/P214_ForkJoinSum/src/modern/challenge/Main.java", "mask_start_position": 1105, "mask_end_position": 1417, "canonical_solution": "SumRecursiveTask sumRecursiveTask = new SumRecursiveTask(list);\n Integer sumAll = forkJoinPool.invoke(sumRecursiveTask);\n logger.info(() -> \"Final sum: \" + sumAll);\n int afterPoolSize = forkJoinPool.getPoolSize();\n logger.info(() -> \"Common Pool size after :\" + afterPoolSize);\n }", "pre_mask_code": "package modern.challenge;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.concurrent.ForkJoinPool;\nimport java.util.logging.Logger;\n\npublic class Main {\n\n private static final Logger logger = Logger.getLogger(Main.class.getName());\n\n public static void main(String[] args) {\n System.setProperty(\"java.util.logging.SimpleFormatter.format\", \"[%1$tT] [%4$-7s] %5$s %n\");\n int noOfProcessors = Runtime.getRuntime().availableProcessors();\n logger.info(() -> \"Available processors: \" + noOfProcessors);\n ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();\n int initialPoolSize = forkJoinPool.getPoolSize();\n int commonPoolParallelism = ForkJoinPool.getCommonPoolParallelism();\n logger.info(() -> \"Common Pool parallelism :\" + commonPoolParallelism);\n logger.info(() -> \"Common Pool size before:\" + initialPoolSize);\n Random rnd = new Random();\n List list = new ArrayList<>();\n for (int i = 0; i < 200; i++) {\n list.add(1 + rnd.nextInt(10));\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_859", "language": "Java", "task_type": "single_line", "source_file": "java/github/PacktPublishing/Java-Coding-Problems/Chapter11/P214_ForkJoinSum/src/modern/challenge/Main.java", "mask_start_position": 918, "mask_end_position": 920, "canonical_solution": ");", "pre_mask_code": "package modern.challenge;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.concurrent.ForkJoinPool;\nimport java.util.logging.Logger;\n\npublic class Main {\n\n private static final Logger logger = Logger.getLogger(Main.class.getName());\n\n public static void main(String[] args) {\n System.setProperty(\"java.util.logging.SimpleFormatter.format\", \"[%1$tT] [%4$-7s] %5$s %n\");\n int noOfProcessors = Runtime.getRuntime().availableProcessors();\n logger.info(() -> \"Available processors: \" + noOfProcessors);\n ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();\n int initialPoolSize = forkJoinPool.getPoolSize();\n int commonPoolParallelism = ForkJoinPool.getCommonPoolParallelism();\n logger.info(() -> \"Common Pool parallelism :\" + commonPoolParallelism);\n logger.info(() -> \"Common Pool size before:\" + initialPoolSize", "post_mask_code": "\n Random rnd = new Random();\n List list = new ArrayList<>();\n for (int i = 0; i < 200; i++) {\n list.add(1 + rnd.nextInt(10));\n }\n SumRecursiveTask sumRecursiveTask = new SumRecursiveTask(list);\n Integer sumAll = forkJoinPool.invoke(sumRecursiveTask);\n logger.info(() -> \"Final sum: \" + sumAll);\n int afterPoolSize = forkJoinPool.getPoolSize();\n logger.info(() -> \"Common Pool size after :\" + afterPoolSize);\n }\n}\n"} {"task_id": "Java_860", "language": "Java", "task_type": "for_statement", "source_file": "java/github/PacktPublishing/Java-Coding-Problems/Chapter11/P214_ForkJoinSum/src/modern/challenge/Main.java", "mask_start_position": 1012, "mask_end_position": 1096, "canonical_solution": "for (int i = 0; i < 200; i++) {\n list.add(1 + rnd.nextInt(10));\n }", "pre_mask_code": "package modern.challenge;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.concurrent.ForkJoinPool;\nimport java.util.logging.Logger;\n\npublic class Main {\n\n private static final Logger logger = Logger.getLogger(Main.class.getName());\n\n public static void main(String[] args) {\n System.setProperty(\"java.util.logging.SimpleFormatter.format\", \"[%1$tT] [%4$-7s] %5$s %n\");\n int noOfProcessors = Runtime.getRuntime().availableProcessors();\n logger.info(() -> \"Available processors: \" + noOfProcessors);\n ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();\n int initialPoolSize = forkJoinPool.getPoolSize();\n int commonPoolParallelism = ForkJoinPool.getCommonPoolParallelism();\n logger.info(() -> \"Common Pool parallelism :\" + commonPoolParallelism);\n logger.info(() -> \"Common Pool size before:\" + initialPoolSize);\n Random rnd = new Random();\n List list = new ArrayList<>();\n ", "post_mask_code": "\n SumRecursiveTask sumRecursiveTask = new SumRecursiveTask(list);\n Integer sumAll = forkJoinPool.invoke(sumRecursiveTask);\n logger.info(() -> \"Final sum: \" + sumAll);\n int afterPoolSize = forkJoinPool.getPoolSize();\n logger.info(() -> \"Common Pool size after :\" + afterPoolSize);\n }\n}\n"} {"task_id": "Java_861", "language": "Java", "task_type": "empty", "source_file": "java/github/PacktPublishing/Java-Coding-Problems/Chapter11/P214_ForkJoinSum/src/modern/challenge/Main.java", "mask_start_position": 210, "mask_end_position": 210, "canonical_solution": "", "pre_mask_code": "package modern.challenge;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.concurrent.ForkJoinPool;\nimport java.util.logging.Logger;\n\npublic class Main {\n\n privat", "post_mask_code": "e static final Logger logger = Logger.getLogger(Main.class.getName());\n\n public static void main(String[] args) {\n System.setProperty(\"java.util.logging.SimpleFormatter.format\", \"[%1$tT] [%4$-7s] %5$s %n\");\n int noOfProcessors = Runtime.getRuntime().availableProcessors();\n logger.info(() -> \"Available processors: \" + noOfProcessors);\n ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();\n int initialPoolSize = forkJoinPool.getPoolSize();\n int commonPoolParallelism = ForkJoinPool.getCommonPoolParallelism();\n logger.info(() -> \"Common Pool parallelism :\" + commonPoolParallelism);\n logger.info(() -> \"Common Pool size before:\" + initialPoolSize);\n Random rnd = new Random();\n List list = new ArrayList<>();\n for (int i = 0; i < 200; i++) {\n list.add(1 + rnd.nextInt(10));\n }\n SumRecursiveTask sumRecursiveTask = new SumRecursiveTask(list);\n Integer sumAll = forkJoinPool.invoke(sumRecursiveTask);\n logger.info(() -> \"Final sum: \" + sumAll);\n int afterPoolSize = forkJoinPool.getPoolSize();\n logger.info(() -> \"Common Pool size after :\" + afterPoolSize);\n }\n}\n"} {"task_id": "Java_862", "language": "Java", "task_type": "method_signature", "source_file": "java/github/hazelcast/hazelcast/hazelcast/src/main/java/com/hazelcast/internal/hotrestart/NoOpHotRestartService.java", "mask_start_position": 900, "mask_end_position": 950, "canonical_solution": "@Override\n public boolean isHotBackupEnabled() ", "pre_mask_code": "package com.hazelcast.internal.hotrestart;\n\nimport com.hazelcast.hotrestart.HotRestartService;\nimport com.hazelcast.persistence.BackupTaskState;\nimport com.hazelcast.persistence.BackupTaskStatus;\n\n/**\n * Empty implementation of HotRestartService to avoid null checks. This will provide default behaviour when hot restart is\n * not available or not enabled.\n */\npublic class NoOpHotRestartService implements HotRestartService {\n\n private static final BackupTaskStatus NO_TASK_BACKUP_STATUS = new BackupTaskStatus(BackupTaskState.NO_TASK, 0, 0);\n\n @Override\n public void backup() {\n }\n\n @Override\n public void backup(long backupSeq) {\n }\n\n @Override\n public BackupTaskStatus getBackupTaskStatus() {\n return NO_TASK_BACKUP_STATUS;\n }\n\n @Override\n public void interruptLocalBackupTask() {\n }\n\n @Override\n public void interruptBackupTask() {\n }\n\n ", "post_mask_code": "{\n return false;\n }\n\n @Override\n public boolean isBackupEnabled() {\n return false;\n }\n\n @Override\n public String getBackupDirectory() {\n return null;\n }\n}\n"} {"task_id": "Java_863", "language": "Java", "task_type": "method_body", "source_file": "java/github/hazelcast/hazelcast/hazelcast/src/main/java/com/hazelcast/internal/hotrestart/NoOpHotRestartService.java", "mask_start_position": 826, "mask_end_position": 833, "canonical_solution": "{\n }", "pre_mask_code": "package com.hazelcast.internal.hotrestart;\n\nimport com.hazelcast.hotrestart.HotRestartService;\nimport com.hazelcast.persistence.BackupTaskState;\nimport com.hazelcast.persistence.BackupTaskStatus;\n\n/**\n * Empty implementation of HotRestartService to avoid null checks. This will provide default behaviour when hot restart is\n * not available or not enabled.\n */\npublic class NoOpHotRestartService implements HotRestartService {\n\n private static final BackupTaskStatus NO_TASK_BACKUP_STATUS = new BackupTaskStatus(BackupTaskState.NO_TASK, 0, 0);\n\n @Override\n public void backup() {\n }\n\n @Override\n public void backup(long backupSeq) {\n }\n\n @Override\n public BackupTaskStatus getBackupTaskStatus() {\n return NO_TASK_BACKUP_STATUS;\n }\n\n @Override\n public void interruptLocalBackupTask() ", "post_mask_code": "\n\n @Override\n public void interruptBackupTask() {\n }\n\n @Override\n public boolean isHotBackupEnabled() {\n return false;\n }\n\n @Override\n public boolean isBackupEnabled() {\n return false;\n }\n\n @Override\n public String getBackupDirectory() {\n return null;\n }\n}\n"} {"task_id": "Java_864", "language": "Java", "task_type": "single_line", "source_file": "java/github/hazelcast/hazelcast/hazelcast/src/main/java/com/hazelcast/internal/hotrestart/NoOpHotRestartService.java", "mask_start_position": 960, "mask_end_position": 973, "canonical_solution": "return false;", "pre_mask_code": "package com.hazelcast.internal.hotrestart;\n\nimport com.hazelcast.hotrestart.HotRestartService;\nimport com.hazelcast.persistence.BackupTaskState;\nimport com.hazelcast.persistence.BackupTaskStatus;\n\n/**\n * Empty implementation of HotRestartService to avoid null checks. This will provide default behaviour when hot restart is\n * not available or not enabled.\n */\npublic class NoOpHotRestartService implements HotRestartService {\n\n private static final BackupTaskStatus NO_TASK_BACKUP_STATUS = new BackupTaskStatus(BackupTaskState.NO_TASK, 0, 0);\n\n @Override\n public void backup() {\n }\n\n @Override\n public void backup(long backupSeq) {\n }\n\n @Override\n public BackupTaskStatus getBackupTaskStatus() {\n return NO_TASK_BACKUP_STATUS;\n }\n\n @Override\n public void interruptLocalBackupTask() {\n }\n\n @Override\n public void interruptBackupTask() {\n }\n\n @Override\n public boolean isHotBackupEnabled() {\n ", "post_mask_code": "\n }\n\n @Override\n public boolean isBackupEnabled() {\n return false;\n }\n\n @Override\n public String getBackupDirectory() {\n return null;\n }\n}\n"} {"task_id": "Java_865", "language": "Java", "task_type": "empty", "source_file": "java/github/hazelcast/hazelcast/hazelcast/src/main/java/com/hazelcast/internal/hotrestart/NoOpHotRestartService.java", "mask_start_position": 631, "mask_end_position": 631, "canonical_solution": "", "pre_mask_code": "package com.hazelcast.internal.hotrestart;\n\nimport com.hazelcast.hotrestart.HotRestartService;\nimport com.hazelcast.persistence.BackupTaskState;\nimport com.hazelcast.persistence.BackupTaskStatus;\n\n/**\n * Empty implementation of HotRestartService to avoid null checks. This will provide default behaviour when hot restart is\n * not available or not enabled.\n */\npublic class NoOpHotRestartService implements HotRestartService {\n\n private static final BackupTaskStatus NO_TASK_BACKUP_STATUS = new BackupTaskStatus(BackupTaskState.NO_TASK, 0, 0);\n\n @Override\n public void backup() {\n }\n\n @Override\n public void backu", "post_mask_code": "p(long backupSeq) {\n }\n\n @Override\n public BackupTaskStatus getBackupTaskStatus() {\n return NO_TASK_BACKUP_STATUS;\n }\n\n @Override\n public void interruptLocalBackupTask() {\n }\n\n @Override\n public void interruptBackupTask() {\n }\n\n @Override\n public boolean isHotBackupEnabled() {\n return false;\n }\n\n @Override\n public boolean isBackupEnabled() {\n return false;\n }\n\n @Override\n public String getBackupDirectory() {\n return null;\n }\n}\n"} {"task_id": "Java_866", "language": "Java", "task_type": "method_signature", "source_file": "java/github/estatio/estatio/estatioapp/app/src/main/java/org/estatio/module/task/dom/policy/EnforceTaskAssignmentPolicySubscriber.java", "mask_start_position": 3329, "mask_end_position": 3542, "canonical_solution": ", STT extends StateTransitionType, S extends State> Optional applyPolicy(final Class stateTransitionClass, final DO entityOrViewModel) ", "pre_mask_code": "package org.estatio.module.task.dom.policy;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\nimport javax.inject.Inject;\nimport com.google.common.collect.Lists;\nimport com.google.common.eventbus.Subscribe;\nimport org.axonframework.eventhandling.annotation.EventHandler;\nimport org.apache.isis.applib.annotation.DomainService;\nimport org.apache.isis.applib.annotation.DomainServiceLayout;\nimport org.apache.isis.applib.annotation.NatureOfService;\nimport org.apache.isis.applib.services.metamodel.MetaModelService3;\nimport org.estatio.module.base.spiimpl.togglz.EstatioTogglzFeature;\nimport org.estatio.module.task.dom.state.State;\nimport org.estatio.module.task.dom.state.StateTransition;\nimport org.estatio.module.task.dom.state.StateTransitionService;\nimport org.estatio.module.task.dom.state.StateTransitionType;\nimport org.estatio.module.task.dom.task.Task;\nimport org.estatio.module.task.dom.task.Task_mixinActAbstract;\nimport org.estatio.module.task.dom.triggers.DomainObject_triggerAbstract;\nimport org.estatio.module.party.dom.Person;\nimport org.estatio.module.party.dom.PersonRepository;\nimport org.estatio.module.party.dom.role.PartyRole;\nimport org.estatio.module.party.dom.role.PartyRoleType;\nimport org.estatio.module.party.dom.role.PartyRoleTypeRepository;\n\n@DomainService(nature = NatureOfService.DOMAIN)\n@DomainServiceLayout(menuOrder = \"1\")\npublic class EnforceTaskAssignmentPolicySubscriber extends org.apache.isis.applib.AbstractSubscriber {\n\n public static interface WithStateTransitionClass {\n\n Class getStateTransitionClass();\n }\n\n @EventHandler\n @Subscribe\n public void on(Task_mixinActAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Task task = (Task) ev.getMixedIn();\n final StateTransition transition = stateTransitionService.findFor(task);\n if (transition == null) {\n // shouldn't occur\n return;\n }\n final Class taskTransitionClass = stateTransitionService.transitionClassFor(transition.getTransitionType());\n if (stateTransitionClass != taskTransitionClass) {\n // just ignore; this mixin action on task doesn't apply to the domain object that the task applies to.\n // or, maybe should hide (and then we can delete code in the subtypes of the mixinAbstract\n return;\n }\n final Object domainObject = transition.getDomainObject();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n @EventHandler\n @Subscribe\n public void on(DomainObject_triggerAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Object domainObject = ev.getMixedIn();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n private void applyPolicy(final Class stateTransitionClass, final Object domainObject, final org.apache.isis.applib.services.eventbus.ActionDomainEvent evv) {\n Optional reasonIfAny = applyPolicy(stateTransitionClass, domainObject);\n reasonIfAny.ifPresent(evv::disable);\n }\n\n ", "post_mask_code": "{\n if (EstatioTogglzFeature.ApproveByProxy.isActive()) {\n return Optional.empty();\n }\n final DO entity = unwrapIfRequired(entityOrViewModel);\n final ST pendingTransition = stateTransitionService.pendingTransitionOf(entity, stateTransitionClass);\n if (pendingTransition == null) {\n return Optional.empty();\n }\n final Task task = pendingTransition.getTask();\n if (task == null) {\n return Optional.empty();\n }\n final Person meAsPerson = personRepository.me();\n if (meAsPerson == null) {\n return Optional.of(\"Could not locate Person for current user\");\n }\n List meAsPersonRoleTypes = Lists.newArrayList(meAsPerson.getRoles()).stream().map(PartyRole::getRoleType).collect(Collectors.toList());\n // // if meAsPerson is incoming invoice manager and was allowed to reject previous state, still allow for correction\n // first guard: meAsPerson always needs the PartyRoleType the task is assigned to\n if (!meAsPersonRoleTypes.contains(task.getAssignedTo())) {\n return Optional.of(String.format(\"Task assigned to '%s' role\", task.getAssignedTo().getKey()));\n }\n // second guard: if the task is assigned to a specific person it needs to be meAsPerson\n final Person taskAssignedTo = task.getPersonAssignedTo();\n if (taskAssignedTo == null || taskAssignedTo == meAsPerson) {\n return Optional.empty();\n } else {\n return Optional.of(String.format(\"Task assigned to %s\", taskAssignedTo.getReference()));\n }\n }\n\n private DO unwrapIfRequired(final DO entityOrViewModel) {\n final DO entity;\n if (entityOrViewModel instanceof ViewModelWrapper) {\n final ViewModelWrapper entityOrViewModel1 = (ViewModelWrapper) entityOrViewModel;\n entity = (DO) entityOrViewModel1.getDomainObject();\n } else {\n entity = entityOrViewModel;\n }\n return entity;\n }\n\n @Inject\n MetaModelService3 metaModelService3;\n\n @Inject\n StateTransitionService stateTransitionService;\n\n @Inject\n PersonRepository personRepository;\n\n @Inject\n PartyRoleTypeRepository partyRoleTypeRepository;\n}\n"} {"task_id": "Java_867", "language": "Java", "task_type": "method_body", "source_file": "java/github/estatio/estatio/estatioapp/app/src/main/java/org/estatio/module/task/dom/policy/EnforceTaskAssignmentPolicySubscriber.java", "mask_start_position": 3183, "mask_end_position": 3323, "canonical_solution": "{\n Optional reasonIfAny = applyPolicy(stateTransitionClass, domainObject);\n reasonIfAny.ifPresent(evv::disable);\n }", "pre_mask_code": "package org.estatio.module.task.dom.policy;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\nimport javax.inject.Inject;\nimport com.google.common.collect.Lists;\nimport com.google.common.eventbus.Subscribe;\nimport org.axonframework.eventhandling.annotation.EventHandler;\nimport org.apache.isis.applib.annotation.DomainService;\nimport org.apache.isis.applib.annotation.DomainServiceLayout;\nimport org.apache.isis.applib.annotation.NatureOfService;\nimport org.apache.isis.applib.services.metamodel.MetaModelService3;\nimport org.estatio.module.base.spiimpl.togglz.EstatioTogglzFeature;\nimport org.estatio.module.task.dom.state.State;\nimport org.estatio.module.task.dom.state.StateTransition;\nimport org.estatio.module.task.dom.state.StateTransitionService;\nimport org.estatio.module.task.dom.state.StateTransitionType;\nimport org.estatio.module.task.dom.task.Task;\nimport org.estatio.module.task.dom.task.Task_mixinActAbstract;\nimport org.estatio.module.task.dom.triggers.DomainObject_triggerAbstract;\nimport org.estatio.module.party.dom.Person;\nimport org.estatio.module.party.dom.PersonRepository;\nimport org.estatio.module.party.dom.role.PartyRole;\nimport org.estatio.module.party.dom.role.PartyRoleType;\nimport org.estatio.module.party.dom.role.PartyRoleTypeRepository;\n\n@DomainService(nature = NatureOfService.DOMAIN)\n@DomainServiceLayout(menuOrder = \"1\")\npublic class EnforceTaskAssignmentPolicySubscriber extends org.apache.isis.applib.AbstractSubscriber {\n\n public static interface WithStateTransitionClass {\n\n Class getStateTransitionClass();\n }\n\n @EventHandler\n @Subscribe\n public void on(Task_mixinActAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Task task = (Task) ev.getMixedIn();\n final StateTransition transition = stateTransitionService.findFor(task);\n if (transition == null) {\n // shouldn't occur\n return;\n }\n final Class taskTransitionClass = stateTransitionService.transitionClassFor(transition.getTransitionType());\n if (stateTransitionClass != taskTransitionClass) {\n // just ignore; this mixin action on task doesn't apply to the domain object that the task applies to.\n // or, maybe should hide (and then we can delete code in the subtypes of the mixinAbstract\n return;\n }\n final Object domainObject = transition.getDomainObject();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n @EventHandler\n @Subscribe\n public void on(DomainObject_triggerAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Object domainObject = ev.getMixedIn();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n private void applyPolicy(final Class stateTransitionClass, final Object domainObject, final org.apache.isis.applib.services.eventbus.ActionDomainEvent evv) ", "post_mask_code": "\n\n , STT extends StateTransitionType, S extends State> Optional applyPolicy(final Class stateTransitionClass, final DO entityOrViewModel) {\n if (EstatioTogglzFeature.ApproveByProxy.isActive()) {\n return Optional.empty();\n }\n final DO entity = unwrapIfRequired(entityOrViewModel);\n final ST pendingTransition = stateTransitionService.pendingTransitionOf(entity, stateTransitionClass);\n if (pendingTransition == null) {\n return Optional.empty();\n }\n final Task task = pendingTransition.getTask();\n if (task == null) {\n return Optional.empty();\n }\n final Person meAsPerson = personRepository.me();\n if (meAsPerson == null) {\n return Optional.of(\"Could not locate Person for current user\");\n }\n List meAsPersonRoleTypes = Lists.newArrayList(meAsPerson.getRoles()).stream().map(PartyRole::getRoleType).collect(Collectors.toList());\n // // if meAsPerson is incoming invoice manager and was allowed to reject previous state, still allow for correction\n // first guard: meAsPerson always needs the PartyRoleType the task is assigned to\n if (!meAsPersonRoleTypes.contains(task.getAssignedTo())) {\n return Optional.of(String.format(\"Task assigned to '%s' role\", task.getAssignedTo().getKey()));\n }\n // second guard: if the task is assigned to a specific person it needs to be meAsPerson\n final Person taskAssignedTo = task.getPersonAssignedTo();\n if (taskAssignedTo == null || taskAssignedTo == meAsPerson) {\n return Optional.empty();\n } else {\n return Optional.of(String.format(\"Task assigned to %s\", taskAssignedTo.getReference()));\n }\n }\n\n private DO unwrapIfRequired(final DO entityOrViewModel) {\n final DO entity;\n if (entityOrViewModel instanceof ViewModelWrapper) {\n final ViewModelWrapper entityOrViewModel1 = (ViewModelWrapper) entityOrViewModel;\n entity = (DO) entityOrViewModel1.getDomainObject();\n } else {\n entity = entityOrViewModel;\n }\n return entity;\n }\n\n @Inject\n MetaModelService3 metaModelService3;\n\n @Inject\n StateTransitionService stateTransitionService;\n\n @Inject\n PersonRepository personRepository;\n\n @Inject\n PartyRoleTypeRepository partyRoleTypeRepository;\n}\n"} {"task_id": "Java_868", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/estatio/estatio/estatioapp/app/src/main/java/org/estatio/module/task/dom/policy/EnforceTaskAssignmentPolicySubscriber.java", "mask_start_position": 3543, "mask_end_position": 3969, "canonical_solution": "\n if (EstatioTogglzFeature.ApproveByProxy.isActive()) {\n return Optional.empty();\n }\n final DO entity = unwrapIfRequired(entityOrViewModel);\n final ST pendingTransition = stateTransitionService.pendingTransitionOf(entity, stateTransitionClass);\n if (pendingTransition == null) {\n return Optional.empty();\n }\n final Task task = pendingTransition.getTask();", "pre_mask_code": "package org.estatio.module.task.dom.policy;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\nimport javax.inject.Inject;\nimport com.google.common.collect.Lists;\nimport com.google.common.eventbus.Subscribe;\nimport org.axonframework.eventhandling.annotation.EventHandler;\nimport org.apache.isis.applib.annotation.DomainService;\nimport org.apache.isis.applib.annotation.DomainServiceLayout;\nimport org.apache.isis.applib.annotation.NatureOfService;\nimport org.apache.isis.applib.services.metamodel.MetaModelService3;\nimport org.estatio.module.base.spiimpl.togglz.EstatioTogglzFeature;\nimport org.estatio.module.task.dom.state.State;\nimport org.estatio.module.task.dom.state.StateTransition;\nimport org.estatio.module.task.dom.state.StateTransitionService;\nimport org.estatio.module.task.dom.state.StateTransitionType;\nimport org.estatio.module.task.dom.task.Task;\nimport org.estatio.module.task.dom.task.Task_mixinActAbstract;\nimport org.estatio.module.task.dom.triggers.DomainObject_triggerAbstract;\nimport org.estatio.module.party.dom.Person;\nimport org.estatio.module.party.dom.PersonRepository;\nimport org.estatio.module.party.dom.role.PartyRole;\nimport org.estatio.module.party.dom.role.PartyRoleType;\nimport org.estatio.module.party.dom.role.PartyRoleTypeRepository;\n\n@DomainService(nature = NatureOfService.DOMAIN)\n@DomainServiceLayout(menuOrder = \"1\")\npublic class EnforceTaskAssignmentPolicySubscriber extends org.apache.isis.applib.AbstractSubscriber {\n\n public static interface WithStateTransitionClass {\n\n Class getStateTransitionClass();\n }\n\n @EventHandler\n @Subscribe\n public void on(Task_mixinActAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Task task = (Task) ev.getMixedIn();\n final StateTransition transition = stateTransitionService.findFor(task);\n if (transition == null) {\n // shouldn't occur\n return;\n }\n final Class taskTransitionClass = stateTransitionService.transitionClassFor(transition.getTransitionType());\n if (stateTransitionClass != taskTransitionClass) {\n // just ignore; this mixin action on task doesn't apply to the domain object that the task applies to.\n // or, maybe should hide (and then we can delete code in the subtypes of the mixinAbstract\n return;\n }\n final Object domainObject = transition.getDomainObject();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n @EventHandler\n @Subscribe\n public void on(DomainObject_triggerAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Object domainObject = ev.getMixedIn();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n private void applyPolicy(final Class stateTransitionClass, final Object domainObject, final org.apache.isis.applib.services.eventbus.ActionDomainEvent evv) {\n Optional reasonIfAny = applyPolicy(stateTransitionClass, domainObject);\n reasonIfAny.ifPresent(evv::disable);\n }\n\n , STT extends StateTransitionType, S extends State> Optional applyPolicy(final Class stateTransitionClass, final DO entityOrViewModel) {", "post_mask_code": "\n if (task == null) {\n return Optional.empty();\n }\n final Person meAsPerson = personRepository.me();\n if (meAsPerson == null) {\n return Optional.of(\"Could not locate Person for current user\");\n }\n List meAsPersonRoleTypes = Lists.newArrayList(meAsPerson.getRoles()).stream().map(PartyRole::getRoleType).collect(Collectors.toList());\n // // if meAsPerson is incoming invoice manager and was allowed to reject previous state, still allow for correction\n // first guard: meAsPerson always needs the PartyRoleType the task is assigned to\n if (!meAsPersonRoleTypes.contains(task.getAssignedTo())) {\n return Optional.of(String.format(\"Task assigned to '%s' role\", task.getAssignedTo().getKey()));\n }\n // second guard: if the task is assigned to a specific person it needs to be meAsPerson\n final Person taskAssignedTo = task.getPersonAssignedTo();\n if (taskAssignedTo == null || taskAssignedTo == meAsPerson) {\n return Optional.empty();\n } else {\n return Optional.of(String.format(\"Task assigned to %s\", taskAssignedTo.getReference()));\n }\n }\n\n private DO unwrapIfRequired(final DO entityOrViewModel) {\n final DO entity;\n if (entityOrViewModel instanceof ViewModelWrapper) {\n final ViewModelWrapper entityOrViewModel1 = (ViewModelWrapper) entityOrViewModel;\n entity = (DO) entityOrViewModel1.getDomainObject();\n } else {\n entity = entityOrViewModel;\n }\n return entity;\n }\n\n @Inject\n MetaModelService3 metaModelService3;\n\n @Inject\n StateTransitionService stateTransitionService;\n\n @Inject\n PersonRepository personRepository;\n\n @Inject\n PartyRoleTypeRepository partyRoleTypeRepository;\n}\n"} {"task_id": "Java_869", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/estatio/estatio/estatioapp/app/src/main/java/org/estatio/module/task/dom/policy/EnforceTaskAssignmentPolicySubscriber.java", "mask_start_position": 3978, "mask_end_position": 4505, "canonical_solution": "if (task == null) {\n return Optional.empty();\n }\n final Person meAsPerson = personRepository.me();\n if (meAsPerson == null) {\n return Optional.of(\"Could not locate Person for current user\");\n }\n List meAsPersonRoleTypes = Lists.newArrayList(meAsPerson.getRoles()).stream().map(PartyRole::getRoleType).collect(Collectors.toList());\n // // if meAsPerson is incoming invoice manager and was allowed to reject previous state, still allow for correction", "pre_mask_code": "package org.estatio.module.task.dom.policy;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\nimport javax.inject.Inject;\nimport com.google.common.collect.Lists;\nimport com.google.common.eventbus.Subscribe;\nimport org.axonframework.eventhandling.annotation.EventHandler;\nimport org.apache.isis.applib.annotation.DomainService;\nimport org.apache.isis.applib.annotation.DomainServiceLayout;\nimport org.apache.isis.applib.annotation.NatureOfService;\nimport org.apache.isis.applib.services.metamodel.MetaModelService3;\nimport org.estatio.module.base.spiimpl.togglz.EstatioTogglzFeature;\nimport org.estatio.module.task.dom.state.State;\nimport org.estatio.module.task.dom.state.StateTransition;\nimport org.estatio.module.task.dom.state.StateTransitionService;\nimport org.estatio.module.task.dom.state.StateTransitionType;\nimport org.estatio.module.task.dom.task.Task;\nimport org.estatio.module.task.dom.task.Task_mixinActAbstract;\nimport org.estatio.module.task.dom.triggers.DomainObject_triggerAbstract;\nimport org.estatio.module.party.dom.Person;\nimport org.estatio.module.party.dom.PersonRepository;\nimport org.estatio.module.party.dom.role.PartyRole;\nimport org.estatio.module.party.dom.role.PartyRoleType;\nimport org.estatio.module.party.dom.role.PartyRoleTypeRepository;\n\n@DomainService(nature = NatureOfService.DOMAIN)\n@DomainServiceLayout(menuOrder = \"1\")\npublic class EnforceTaskAssignmentPolicySubscriber extends org.apache.isis.applib.AbstractSubscriber {\n\n public static interface WithStateTransitionClass {\n\n Class getStateTransitionClass();\n }\n\n @EventHandler\n @Subscribe\n public void on(Task_mixinActAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Task task = (Task) ev.getMixedIn();\n final StateTransition transition = stateTransitionService.findFor(task);\n if (transition == null) {\n // shouldn't occur\n return;\n }\n final Class taskTransitionClass = stateTransitionService.transitionClassFor(transition.getTransitionType());\n if (stateTransitionClass != taskTransitionClass) {\n // just ignore; this mixin action on task doesn't apply to the domain object that the task applies to.\n // or, maybe should hide (and then we can delete code in the subtypes of the mixinAbstract\n return;\n }\n final Object domainObject = transition.getDomainObject();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n @EventHandler\n @Subscribe\n public void on(DomainObject_triggerAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Object domainObject = ev.getMixedIn();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n private void applyPolicy(final Class stateTransitionClass, final Object domainObject, final org.apache.isis.applib.services.eventbus.ActionDomainEvent evv) {\n Optional reasonIfAny = applyPolicy(stateTransitionClass, domainObject);\n reasonIfAny.ifPresent(evv::disable);\n }\n\n , STT extends StateTransitionType, S extends State> Optional applyPolicy(final Class stateTransitionClass, final DO entityOrViewModel) {\n if (EstatioTogglzFeature.ApproveByProxy.isActive()) {\n return Optional.empty();\n }\n final DO entity = unwrapIfRequired(entityOrViewModel);\n final ST pendingTransition = stateTransitionService.pendingTransitionOf(entity, stateTransitionClass);\n if (pendingTransition == null) {\n return Optional.empty();\n }\n final Task task = pendingTransition.getTask();\n ", "post_mask_code": "\n // first guard: meAsPerson always needs the PartyRoleType the task is assigned to\n if (!meAsPersonRoleTypes.contains(task.getAssignedTo())) {\n return Optional.of(String.format(\"Task assigned to '%s' role\", task.getAssignedTo().getKey()));\n }\n // second guard: if the task is assigned to a specific person it needs to be meAsPerson\n final Person taskAssignedTo = task.getPersonAssignedTo();\n if (taskAssignedTo == null || taskAssignedTo == meAsPerson) {\n return Optional.empty();\n } else {\n return Optional.of(String.format(\"Task assigned to %s\", taskAssignedTo.getReference()));\n }\n }\n\n private DO unwrapIfRequired(final DO entityOrViewModel) {\n final DO entity;\n if (entityOrViewModel instanceof ViewModelWrapper) {\n final ViewModelWrapper entityOrViewModel1 = (ViewModelWrapper) entityOrViewModel;\n entity = (DO) entityOrViewModel1.getDomainObject();\n } else {\n entity = entityOrViewModel;\n }\n return entity;\n }\n\n @Inject\n MetaModelService3 metaModelService3;\n\n @Inject\n StateTransitionService stateTransitionService;\n\n @Inject\n PersonRepository personRepository;\n\n @Inject\n PartyRoleTypeRepository partyRoleTypeRepository;\n}\n"} {"task_id": "Java_870", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/estatio/estatio/estatioapp/app/src/main/java/org/estatio/module/task/dom/policy/EnforceTaskAssignmentPolicySubscriber.java", "mask_start_position": 4514, "mask_end_position": 5183, "canonical_solution": "// first guard: meAsPerson always needs the PartyRoleType the task is assigned to\n if (!meAsPersonRoleTypes.contains(task.getAssignedTo())) {\n return Optional.of(String.format(\"Task assigned to '%s' role\", task.getAssignedTo().getKey()));\n }\n // second guard: if the task is assigned to a specific person it needs to be meAsPerson\n final Person taskAssignedTo = task.getPersonAssignedTo();\n if (taskAssignedTo == null || taskAssignedTo == meAsPerson) {\n return Optional.empty();\n } else {\n return Optional.of(String.format(\"Task assigned to %s\", taskAssignedTo.getReference()));\n }\n }", "pre_mask_code": "package org.estatio.module.task.dom.policy;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\nimport javax.inject.Inject;\nimport com.google.common.collect.Lists;\nimport com.google.common.eventbus.Subscribe;\nimport org.axonframework.eventhandling.annotation.EventHandler;\nimport org.apache.isis.applib.annotation.DomainService;\nimport org.apache.isis.applib.annotation.DomainServiceLayout;\nimport org.apache.isis.applib.annotation.NatureOfService;\nimport org.apache.isis.applib.services.metamodel.MetaModelService3;\nimport org.estatio.module.base.spiimpl.togglz.EstatioTogglzFeature;\nimport org.estatio.module.task.dom.state.State;\nimport org.estatio.module.task.dom.state.StateTransition;\nimport org.estatio.module.task.dom.state.StateTransitionService;\nimport org.estatio.module.task.dom.state.StateTransitionType;\nimport org.estatio.module.task.dom.task.Task;\nimport org.estatio.module.task.dom.task.Task_mixinActAbstract;\nimport org.estatio.module.task.dom.triggers.DomainObject_triggerAbstract;\nimport org.estatio.module.party.dom.Person;\nimport org.estatio.module.party.dom.PersonRepository;\nimport org.estatio.module.party.dom.role.PartyRole;\nimport org.estatio.module.party.dom.role.PartyRoleType;\nimport org.estatio.module.party.dom.role.PartyRoleTypeRepository;\n\n@DomainService(nature = NatureOfService.DOMAIN)\n@DomainServiceLayout(menuOrder = \"1\")\npublic class EnforceTaskAssignmentPolicySubscriber extends org.apache.isis.applib.AbstractSubscriber {\n\n public static interface WithStateTransitionClass {\n\n Class getStateTransitionClass();\n }\n\n @EventHandler\n @Subscribe\n public void on(Task_mixinActAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Task task = (Task) ev.getMixedIn();\n final StateTransition transition = stateTransitionService.findFor(task);\n if (transition == null) {\n // shouldn't occur\n return;\n }\n final Class taskTransitionClass = stateTransitionService.transitionClassFor(transition.getTransitionType());\n if (stateTransitionClass != taskTransitionClass) {\n // just ignore; this mixin action on task doesn't apply to the domain object that the task applies to.\n // or, maybe should hide (and then we can delete code in the subtypes of the mixinAbstract\n return;\n }\n final Object domainObject = transition.getDomainObject();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n @EventHandler\n @Subscribe\n public void on(DomainObject_triggerAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Object domainObject = ev.getMixedIn();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n private void applyPolicy(final Class stateTransitionClass, final Object domainObject, final org.apache.isis.applib.services.eventbus.ActionDomainEvent evv) {\n Optional reasonIfAny = applyPolicy(stateTransitionClass, domainObject);\n reasonIfAny.ifPresent(evv::disable);\n }\n\n , STT extends StateTransitionType, S extends State> Optional applyPolicy(final Class stateTransitionClass, final DO entityOrViewModel) {\n if (EstatioTogglzFeature.ApproveByProxy.isActive()) {\n return Optional.empty();\n }\n final DO entity = unwrapIfRequired(entityOrViewModel);\n final ST pendingTransition = stateTransitionService.pendingTransitionOf(entity, stateTransitionClass);\n if (pendingTransition == null) {\n return Optional.empty();\n }\n final Task task = pendingTransition.getTask();\n if (task == null) {\n return Optional.empty();\n }\n final Person meAsPerson = personRepository.me();\n if (meAsPerson == null) {\n return Optional.of(\"Could not locate Person for current user\");\n }\n List meAsPersonRoleTypes = Lists.newArrayList(meAsPerson.getRoles()).stream().map(PartyRole::getRoleType).collect(Collectors.toList());\n // // if meAsPerson is incoming invoice manager and was allowed to reject previous state, still allow for correction\n ", "post_mask_code": "\n\n private DO unwrapIfRequired(final DO entityOrViewModel) {\n final DO entity;\n if (entityOrViewModel instanceof ViewModelWrapper) {\n final ViewModelWrapper entityOrViewModel1 = (ViewModelWrapper) entityOrViewModel;\n entity = (DO) entityOrViewModel1.getDomainObject();\n } else {\n entity = entityOrViewModel;\n }\n return entity;\n }\n\n @Inject\n MetaModelService3 metaModelService3;\n\n @Inject\n StateTransitionService stateTransitionService;\n\n @Inject\n PersonRepository personRepository;\n\n @Inject\n PartyRoleTypeRepository partyRoleTypeRepository;\n}\n"} {"task_id": "Java_871", "language": "Java", "task_type": "single_line", "source_file": "java/github/estatio/estatio/estatioapp/app/src/main/java/org/estatio/module/task/dom/policy/EnforceTaskAssignmentPolicySubscriber.java", "mask_start_position": 4095, "mask_end_position": 4101, "canonical_solution": ".me();", "pre_mask_code": "package org.estatio.module.task.dom.policy;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\nimport javax.inject.Inject;\nimport com.google.common.collect.Lists;\nimport com.google.common.eventbus.Subscribe;\nimport org.axonframework.eventhandling.annotation.EventHandler;\nimport org.apache.isis.applib.annotation.DomainService;\nimport org.apache.isis.applib.annotation.DomainServiceLayout;\nimport org.apache.isis.applib.annotation.NatureOfService;\nimport org.apache.isis.applib.services.metamodel.MetaModelService3;\nimport org.estatio.module.base.spiimpl.togglz.EstatioTogglzFeature;\nimport org.estatio.module.task.dom.state.State;\nimport org.estatio.module.task.dom.state.StateTransition;\nimport org.estatio.module.task.dom.state.StateTransitionService;\nimport org.estatio.module.task.dom.state.StateTransitionType;\nimport org.estatio.module.task.dom.task.Task;\nimport org.estatio.module.task.dom.task.Task_mixinActAbstract;\nimport org.estatio.module.task.dom.triggers.DomainObject_triggerAbstract;\nimport org.estatio.module.party.dom.Person;\nimport org.estatio.module.party.dom.PersonRepository;\nimport org.estatio.module.party.dom.role.PartyRole;\nimport org.estatio.module.party.dom.role.PartyRoleType;\nimport org.estatio.module.party.dom.role.PartyRoleTypeRepository;\n\n@DomainService(nature = NatureOfService.DOMAIN)\n@DomainServiceLayout(menuOrder = \"1\")\npublic class EnforceTaskAssignmentPolicySubscriber extends org.apache.isis.applib.AbstractSubscriber {\n\n public static interface WithStateTransitionClass {\n\n Class getStateTransitionClass();\n }\n\n @EventHandler\n @Subscribe\n public void on(Task_mixinActAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Task task = (Task) ev.getMixedIn();\n final StateTransition transition = stateTransitionService.findFor(task);\n if (transition == null) {\n // shouldn't occur\n return;\n }\n final Class taskTransitionClass = stateTransitionService.transitionClassFor(transition.getTransitionType());\n if (stateTransitionClass != taskTransitionClass) {\n // just ignore; this mixin action on task doesn't apply to the domain object that the task applies to.\n // or, maybe should hide (and then we can delete code in the subtypes of the mixinAbstract\n return;\n }\n final Object domainObject = transition.getDomainObject();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n @EventHandler\n @Subscribe\n public void on(DomainObject_triggerAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Object domainObject = ev.getMixedIn();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n private void applyPolicy(final Class stateTransitionClass, final Object domainObject, final org.apache.isis.applib.services.eventbus.ActionDomainEvent evv) {\n Optional reasonIfAny = applyPolicy(stateTransitionClass, domainObject);\n reasonIfAny.ifPresent(evv::disable);\n }\n\n , STT extends StateTransitionType, S extends State> Optional applyPolicy(final Class stateTransitionClass, final DO entityOrViewModel) {\n if (EstatioTogglzFeature.ApproveByProxy.isActive()) {\n return Optional.empty();\n }\n final DO entity = unwrapIfRequired(entityOrViewModel);\n final ST pendingTransition = stateTransitionService.pendingTransitionOf(entity, stateTransitionClass);\n if (pendingTransition == null) {\n return Optional.empty();\n }\n final Task task = pendingTransition.getTask();\n if (task == null) {\n return Optional.empty();\n }\n final Person meAsPerson = personRepository", "post_mask_code": "\n if (meAsPerson == null) {\n return Optional.of(\"Could not locate Person for current user\");\n }\n List meAsPersonRoleTypes = Lists.newArrayList(meAsPerson.getRoles()).stream().map(PartyRole::getRoleType).collect(Collectors.toList());\n // // if meAsPerson is incoming invoice manager and was allowed to reject previous state, still allow for correction\n // first guard: meAsPerson always needs the PartyRoleType the task is assigned to\n if (!meAsPersonRoleTypes.contains(task.getAssignedTo())) {\n return Optional.of(String.format(\"Task assigned to '%s' role\", task.getAssignedTo().getKey()));\n }\n // second guard: if the task is assigned to a specific person it needs to be meAsPerson\n final Person taskAssignedTo = task.getPersonAssignedTo();\n if (taskAssignedTo == null || taskAssignedTo == meAsPerson) {\n return Optional.empty();\n } else {\n return Optional.of(String.format(\"Task assigned to %s\", taskAssignedTo.getReference()));\n }\n }\n\n private DO unwrapIfRequired(final DO entityOrViewModel) {\n final DO entity;\n if (entityOrViewModel instanceof ViewModelWrapper) {\n final ViewModelWrapper entityOrViewModel1 = (ViewModelWrapper) entityOrViewModel;\n entity = (DO) entityOrViewModel1.getDomainObject();\n } else {\n entity = entityOrViewModel;\n }\n return entity;\n }\n\n @Inject\n MetaModelService3 metaModelService3;\n\n @Inject\n StateTransitionService stateTransitionService;\n\n @Inject\n PersonRepository personRepository;\n\n @Inject\n PartyRoleTypeRepository partyRoleTypeRepository;\n}\n"} {"task_id": "Java_872", "language": "Java", "task_type": "if_statement", "source_file": "java/github/estatio/estatio/estatioapp/app/src/main/java/org/estatio/module/task/dom/policy/EnforceTaskAssignmentPolicySubscriber.java", "mask_start_position": 2754, "mask_end_position": 2825, "canonical_solution": "if (ev.getSemantics().isSafeInNature()) {\n return;\n }", "pre_mask_code": "package org.estatio.module.task.dom.policy;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\nimport javax.inject.Inject;\nimport com.google.common.collect.Lists;\nimport com.google.common.eventbus.Subscribe;\nimport org.axonframework.eventhandling.annotation.EventHandler;\nimport org.apache.isis.applib.annotation.DomainService;\nimport org.apache.isis.applib.annotation.DomainServiceLayout;\nimport org.apache.isis.applib.annotation.NatureOfService;\nimport org.apache.isis.applib.services.metamodel.MetaModelService3;\nimport org.estatio.module.base.spiimpl.togglz.EstatioTogglzFeature;\nimport org.estatio.module.task.dom.state.State;\nimport org.estatio.module.task.dom.state.StateTransition;\nimport org.estatio.module.task.dom.state.StateTransitionService;\nimport org.estatio.module.task.dom.state.StateTransitionType;\nimport org.estatio.module.task.dom.task.Task;\nimport org.estatio.module.task.dom.task.Task_mixinActAbstract;\nimport org.estatio.module.task.dom.triggers.DomainObject_triggerAbstract;\nimport org.estatio.module.party.dom.Person;\nimport org.estatio.module.party.dom.PersonRepository;\nimport org.estatio.module.party.dom.role.PartyRole;\nimport org.estatio.module.party.dom.role.PartyRoleType;\nimport org.estatio.module.party.dom.role.PartyRoleTypeRepository;\n\n@DomainService(nature = NatureOfService.DOMAIN)\n@DomainServiceLayout(menuOrder = \"1\")\npublic class EnforceTaskAssignmentPolicySubscriber extends org.apache.isis.applib.AbstractSubscriber {\n\n public static interface WithStateTransitionClass {\n\n Class getStateTransitionClass();\n }\n\n @EventHandler\n @Subscribe\n public void on(Task_mixinActAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Task task = (Task) ev.getMixedIn();\n final StateTransition transition = stateTransitionService.findFor(task);\n if (transition == null) {\n // shouldn't occur\n return;\n }\n final Class taskTransitionClass = stateTransitionService.transitionClassFor(transition.getTransitionType());\n if (stateTransitionClass != taskTransitionClass) {\n // just ignore; this mixin action on task doesn't apply to the domain object that the task applies to.\n // or, maybe should hide (and then we can delete code in the subtypes of the mixinAbstract\n return;\n }\n final Object domainObject = transition.getDomainObject();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n @EventHandler\n @Subscribe\n public void on(DomainObject_triggerAbstract.ActionDomainEvent ev) {\n ", "post_mask_code": "\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Object domainObject = ev.getMixedIn();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n private void applyPolicy(final Class stateTransitionClass, final Object domainObject, final org.apache.isis.applib.services.eventbus.ActionDomainEvent evv) {\n Optional reasonIfAny = applyPolicy(stateTransitionClass, domainObject);\n reasonIfAny.ifPresent(evv::disable);\n }\n\n , STT extends StateTransitionType, S extends State> Optional applyPolicy(final Class stateTransitionClass, final DO entityOrViewModel) {\n if (EstatioTogglzFeature.ApproveByProxy.isActive()) {\n return Optional.empty();\n }\n final DO entity = unwrapIfRequired(entityOrViewModel);\n final ST pendingTransition = stateTransitionService.pendingTransitionOf(entity, stateTransitionClass);\n if (pendingTransition == null) {\n return Optional.empty();\n }\n final Task task = pendingTransition.getTask();\n if (task == null) {\n return Optional.empty();\n }\n final Person meAsPerson = personRepository.me();\n if (meAsPerson == null) {\n return Optional.of(\"Could not locate Person for current user\");\n }\n List meAsPersonRoleTypes = Lists.newArrayList(meAsPerson.getRoles()).stream().map(PartyRole::getRoleType).collect(Collectors.toList());\n // // if meAsPerson is incoming invoice manager and was allowed to reject previous state, still allow for correction\n // first guard: meAsPerson always needs the PartyRoleType the task is assigned to\n if (!meAsPersonRoleTypes.contains(task.getAssignedTo())) {\n return Optional.of(String.format(\"Task assigned to '%s' role\", task.getAssignedTo().getKey()));\n }\n // second guard: if the task is assigned to a specific person it needs to be meAsPerson\n final Person taskAssignedTo = task.getPersonAssignedTo();\n if (taskAssignedTo == null || taskAssignedTo == meAsPerson) {\n return Optional.empty();\n } else {\n return Optional.of(String.format(\"Task assigned to %s\", taskAssignedTo.getReference()));\n }\n }\n\n private DO unwrapIfRequired(final DO entityOrViewModel) {\n final DO entity;\n if (entityOrViewModel instanceof ViewModelWrapper) {\n final ViewModelWrapper entityOrViewModel1 = (ViewModelWrapper) entityOrViewModel;\n entity = (DO) entityOrViewModel1.getDomainObject();\n } else {\n entity = entityOrViewModel;\n }\n return entity;\n }\n\n @Inject\n MetaModelService3 metaModelService3;\n\n @Inject\n StateTransitionService stateTransitionService;\n\n @Inject\n PersonRepository personRepository;\n\n @Inject\n PartyRoleTypeRepository partyRoleTypeRepository;\n}\n"} {"task_id": "Java_873", "language": "Java", "task_type": "empty", "source_file": "java/github/estatio/estatio/estatioapp/app/src/main/java/org/estatio/module/task/dom/policy/EnforceTaskAssignmentPolicySubscriber.java", "mask_start_position": 5597, "mask_end_position": 5597, "canonical_solution": "", "pre_mask_code": "package org.estatio.module.task.dom.policy;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\nimport javax.inject.Inject;\nimport com.google.common.collect.Lists;\nimport com.google.common.eventbus.Subscribe;\nimport org.axonframework.eventhandling.annotation.EventHandler;\nimport org.apache.isis.applib.annotation.DomainService;\nimport org.apache.isis.applib.annotation.DomainServiceLayout;\nimport org.apache.isis.applib.annotation.NatureOfService;\nimport org.apache.isis.applib.services.metamodel.MetaModelService3;\nimport org.estatio.module.base.spiimpl.togglz.EstatioTogglzFeature;\nimport org.estatio.module.task.dom.state.State;\nimport org.estatio.module.task.dom.state.StateTransition;\nimport org.estatio.module.task.dom.state.StateTransitionService;\nimport org.estatio.module.task.dom.state.StateTransitionType;\nimport org.estatio.module.task.dom.task.Task;\nimport org.estatio.module.task.dom.task.Task_mixinActAbstract;\nimport org.estatio.module.task.dom.triggers.DomainObject_triggerAbstract;\nimport org.estatio.module.party.dom.Person;\nimport org.estatio.module.party.dom.PersonRepository;\nimport org.estatio.module.party.dom.role.PartyRole;\nimport org.estatio.module.party.dom.role.PartyRoleType;\nimport org.estatio.module.party.dom.role.PartyRoleTypeRepository;\n\n@DomainService(nature = NatureOfService.DOMAIN)\n@DomainServiceLayout(menuOrder = \"1\")\npublic class EnforceTaskAssignmentPolicySubscriber extends org.apache.isis.applib.AbstractSubscriber {\n\n public static interface WithStateTransitionClass {\n\n Class getStateTransitionClass();\n }\n\n @EventHandler\n @Subscribe\n public void on(Task_mixinActAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Task task = (Task) ev.getMixedIn();\n final StateTransition transition = stateTransitionService.findFor(task);\n if (transition == null) {\n // shouldn't occur\n return;\n }\n final Class taskTransitionClass = stateTransitionService.transitionClassFor(transition.getTransitionType());\n if (stateTransitionClass != taskTransitionClass) {\n // just ignore; this mixin action on task doesn't apply to the domain object that the task applies to.\n // or, maybe should hide (and then we can delete code in the subtypes of the mixinAbstract\n return;\n }\n final Object domainObject = transition.getDomainObject();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n @EventHandler\n @Subscribe\n public void on(DomainObject_triggerAbstract.ActionDomainEvent ev) {\n if (ev.getSemantics().isSafeInNature()) {\n return;\n }\n final Class stateTransitionClass = ev.getStateTransitionClass();\n final Object domainObject = ev.getMixedIn();\n applyPolicy(stateTransitionClass, domainObject, ev);\n }\n\n private void applyPolicy(final Class stateTransitionClass, final Object domainObject, final org.apache.isis.applib.services.eventbus.ActionDomainEvent evv) {\n Optional reasonIfAny = applyPolicy(stateTransitionClass, domainObject);\n reasonIfAny.ifPresent(evv::disable);\n }\n\n , STT extends StateTransitionType, S extends State> Optional applyPolicy(final Class stateTransitionClass, final DO entityOrViewModel) {\n if (EstatioTogglzFeature.ApproveByProxy.isActive()) {\n return Optional.empty();\n }\n final DO entity = unwrapIfRequired(entityOrViewModel);\n final ST pendingTransition = stateTransitionService.pendingTransitionOf(entity, stateTransitionClass);\n if (pendingTransition == null) {\n return Optional.empty();\n }\n final Task task = pendingTransition.getTask();\n if (task == null) {\n return Optional.empty();\n }\n final Person meAsPerson = personRepository.me();\n if (meAsPerson == null) {\n return Optional.of(\"Could not locate Person for current user\");\n }\n List meAsPersonRoleTypes = Lists.newArrayList(meAsPerson.getRoles()).stream().map(PartyRole::getRoleType).collect(Collectors.toList());\n // // if meAsPerson is incoming invoice manager and was allowed to reject previous state, still allow for correction\n // first guard: meAsPerson always needs the PartyRoleType the task is assigned to\n if (!meAsPersonRoleTypes.contains(task.getAssignedTo())) {\n return Optional.of(String.format(\"Task assigned to '%s' role\", task.getAssignedTo().getKey()));\n }\n // second guard: if the task is assigned to a specific person it needs to be meAsPerson\n final Person taskAssignedTo = task.getPersonAssignedTo();\n if (taskAssignedTo == null || taskAssignedTo == meAsPerson) {\n return Optional.empty();\n } else {\n return Optional.of(String.format(\"Task assigned to %s\", taskAssignedTo.getReference()));\n }\n }\n\n private DO unwrapIfRequired(final DO entityOrViewModel) {\n final DO entity;\n if (entityOrViewModel instanceof ViewModelWrapper) {\n final ViewModelWrapper entityOrViewModel1 = (ViewModelWrapper) entityOrViewModel;\n entity = (DO) entityOrViewModel1.getDomainObject();\n } else {\n entity = entityOrViewModel;\n }\n return entity;\n }\n\n ", "post_mask_code": "@Inject\n MetaModelService3 metaModelService3;\n\n @Inject\n StateTransitionService stateTransitionService;\n\n @Inject\n PersonRepository personRepository;\n\n @Inject\n PartyRoleTypeRepository partyRoleTypeRepository;\n}\n"} {"task_id": "Java_874", "language": "Java", "task_type": "method_signature", "source_file": "java/github/levans/Open-Quark/src/CAL_Libraries/src/org/openquark/cal/foreignsupport/module/Summary/Math.java", "mask_start_position": 339, "mask_end_position": 375, "canonical_solution": "public static final double random() ", "pre_mask_code": "/*\n * All rights reserved.\n * \n */\npackage org.openquark.cal.foreignsupport.module.Summary;\n\nimport java.util.Random;\n\n/**\n * @author Jawright\n * The Math class provides access to standard Java mathmatics functions for the\n * Summary module.\n */\npublic final class Math {\n\n private static final Random rndGenerator = new Random();\n\n ", "post_mask_code": "{\n return rndGenerator.nextDouble();\n }\n}\n"} {"task_id": "Java_875", "language": "Java", "task_type": "method_body", "source_file": "java/github/levans/Open-Quark/src/CAL_Libraries/src/org/openquark/cal/foreignsupport/module/Summary/Math.java", "mask_start_position": 375, "mask_end_position": 424, "canonical_solution": "{\n return rndGenerator.nextDouble();\n }", "pre_mask_code": "/*\n * All rights reserved.\n * \n */\npackage org.openquark.cal.foreignsupport.module.Summary;\n\nimport java.util.Random;\n\n/**\n * @author Jawright\n * The Math class provides access to standard Java mathmatics functions for the\n * Summary module.\n */\npublic final class Math {\n\n private static final Random rndGenerator = new Random();\n\n public static final double random() ", "post_mask_code": "\n}\n"} {"task_id": "Java_876", "language": "Java", "task_type": "single_line", "source_file": "java/github/levans/Open-Quark/src/CAL_Libraries/src/org/openquark/cal/foreignsupport/module/Summary/Math.java", "mask_start_position": 398, "mask_end_position": 418, "canonical_solution": "erator.nextDouble();", "pre_mask_code": "/*\n * All rights reserved.\n * \n */\npackage org.openquark.cal.foreignsupport.module.Summary;\n\nimport java.util.Random;\n\n/**\n * @author Jawright\n * The Math class provides access to standard Java mathmatics functions for the\n * Summary module.\n */\npublic final class Math {\n\n private static final Random rndGenerator = new Random();\n\n public static final double random() {\n return rndGen", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_877", "language": "Java", "task_type": "empty", "source_file": "java/github/levans/Open-Quark/src/CAL_Libraries/src/org/openquark/cal/foreignsupport/module/Summary/Math.java", "mask_start_position": 108, "mask_end_position": 108, "canonical_solution": "", "pre_mask_code": "/*\n * All rights reserved.\n * \n */\npackage org.openquark.cal.foreignsupport.module.Summary;\n\nimport java.uti", "post_mask_code": "l.Random;\n\n/**\n * @author Jawright\n * The Math class provides access to standard Java mathmatics functions for the\n * Summary module.\n */\npublic final class Math {\n\n private static final Random rndGenerator = new Random();\n\n public static final double random() {\n return rndGenerator.nextDouble();\n }\n}\n"} {"task_id": "Java_878", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ra4king/LWJGL-OpenGL-Tutorials/src/com/ra4king/opengl/arcsynthesis/gl33/chapter5/example2/Example5_2.java", "mask_start_position": 481, "mask_end_position": 520, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "package com.ra4king.opengl.arcsynthesis.gl33.chapter5.example2;\n\nimport static org.lwjgl.opengl.GL11.*;\nimport static org.lwjgl.opengl.GL15.*;\nimport static org.lwjgl.opengl.GL20.*;\nimport static org.lwjgl.opengl.GL30.*;\nimport static org.lwjgl.opengl.GL32.*;\nimport java.nio.FloatBuffer;\nimport java.nio.ShortBuffer;\nimport org.lwjgl.BufferUtils;\nimport com.ra4king.opengl.GLProgram;\nimport com.ra4king.opengl.util.ShaderProgram;\n\npublic class Example5_2 extends GLProgram {\n\n ", "post_mask_code": "{\n new Example5_2().run(true);\n }\n\n private final float RIGHT_EXTENT = 0.8f;\n\n private final float LEFT_EXTENT = -RIGHT_EXTENT;\n\n private final float TOP_EXTENT = 0.2f;\n\n private final float MIDDLE_EXTENT = 0;\n\n private final float BOTTOM_EXTENT = -TOP_EXTENT;\n\n private final float FRONT_EXTENT = -1.25f;\n\n private final float REAR_EXTENT = -1.75f;\n\n private final float[] GREEN_COLOR = { 0.75f, 0.75f, 1, 1 };\n\n private final float[] BLUE_COLOR = { 0, 0.5f, 0, 1 };\n\n private final float[] RED_COLOR = { 1, 0, 0, 1 };\n\n private final float[] GREY_COLOR = { 0.8f, 0.8f, 0.8f, 1 };\n\n private final float[] BROWN_COLOR = { 0.5f, 0.5f, 0, 1 };\n\n private float[] data = { // Object 1 positions\n LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, // Object 2 positions\n TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, // Object 1 colors\n GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], // Object 2 colors\n RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3] };\n\n private final short[] indices = { 0, 2, 1, 3, 2, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 11, 13, 12, 14, 16, 15, 17, 16, 14 };\n\n private ShaderProgram program;\n\n private int offsetUniform;\n\n private int vao;\n\n private FloatBuffer perspectiveMatrix;\n\n private int perspectiveMatrixUniform;\n\n private float frustumScale = 1;\n\n public Example5_2() {\n super(\"Example 5.2 - Base Vertex Overlap\", 500, 500, true);\n }\n\n @Override\n public void init() {\n glClearColor(0, 0, 0, 0);\n program = new ShaderProgram(readFromFile(\"example5.2.vert\"), readFromFile(\"example5.2.frag\"));\n offsetUniform = program.getUniformLocation(\"offset\");\n perspectiveMatrixUniform = program.getUniformLocation(\"perspectiveMatrix\");\n float zNear = 1, zFar = 3;\n perspectiveMatrix = BufferUtils.createFloatBuffer(16);\n perspectiveMatrix.put(0, frustumScale);\n perspectiveMatrix.put(5, frustumScale);\n perspectiveMatrix.put(10, (zFar + zNear) / (zNear - zFar));\n perspectiveMatrix.put(14, (2 * zFar * zNear) / (zNear - zFar));\n perspectiveMatrix.put(11, -1);\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);\n program.end();\n int vbo1 = glGenBuffers();\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glBufferData(GL_ARRAY_BUFFER, (FloatBuffer) BufferUtils.createFloatBuffer(data.length).put(data).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n int vbo2 = glGenBuffers();\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, (ShortBuffer) BufferUtils.createShortBuffer(indices.length).put(indices).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n vao = glGenVertexArrays();\n glBindVertexArray(vao);\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);\n glVertexAttribPointer(1, 4, GL_FLOAT, false, 0, 36 * 3 * 4);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBindVertexArray(0);\n glEnable(GL_CULL_FACE);\n glCullFace(GL_BACK);\n glFrontFace(GL_CW);\n }\n\n @Override\n public void resized() {\n super.resized();\n perspectiveMatrix.put(0, frustumScale / ((float) getWidth() / getHeight()));\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);\n program.end();\n }\n\n @Override\n public void render() {\n glClear(GL_COLOR_BUFFER_BIT);\n program.begin();\n glBindVertexArray(vao);\n glUniform3f(offsetUniform, 0, 0, 0);\n glDrawElements(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0);\n glUniform3f(offsetUniform, 0, 0, -1);\n glDrawElementsBaseVertex(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0, 36 / 2);\n glBindVertexArray(0);\n program.end();\n }\n}\n"} {"task_id": "Java_879", "language": "Java", "task_type": "method_body", "source_file": "java/github/ra4king/LWJGL-OpenGL-Tutorials/src/com/ra4king/opengl/arcsynthesis/gl33/chapter5/example2/Example5_2.java", "mask_start_position": 7330, "mask_end_position": 7573, "canonical_solution": "{\n super.resized();\n perspectiveMatrix.put(0, frustumScale / ((float) getWidth() / getHeight()));\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);\n program.end();\n }", "pre_mask_code": "package com.ra4king.opengl.arcsynthesis.gl33.chapter5.example2;\n\nimport static org.lwjgl.opengl.GL11.*;\nimport static org.lwjgl.opengl.GL15.*;\nimport static org.lwjgl.opengl.GL20.*;\nimport static org.lwjgl.opengl.GL30.*;\nimport static org.lwjgl.opengl.GL32.*;\nimport java.nio.FloatBuffer;\nimport java.nio.ShortBuffer;\nimport org.lwjgl.BufferUtils;\nimport com.ra4king.opengl.GLProgram;\nimport com.ra4king.opengl.util.ShaderProgram;\n\npublic class Example5_2 extends GLProgram {\n\n public static void main(String[] args) {\n new Example5_2().run(true);\n }\n\n private final float RIGHT_EXTENT = 0.8f;\n\n private final float LEFT_EXTENT = -RIGHT_EXTENT;\n\n private final float TOP_EXTENT = 0.2f;\n\n private final float MIDDLE_EXTENT = 0;\n\n private final float BOTTOM_EXTENT = -TOP_EXTENT;\n\n private final float FRONT_EXTENT = -1.25f;\n\n private final float REAR_EXTENT = -1.75f;\n\n private final float[] GREEN_COLOR = { 0.75f, 0.75f, 1, 1 };\n\n private final float[] BLUE_COLOR = { 0, 0.5f, 0, 1 };\n\n private final float[] RED_COLOR = { 1, 0, 0, 1 };\n\n private final float[] GREY_COLOR = { 0.8f, 0.8f, 0.8f, 1 };\n\n private final float[] BROWN_COLOR = { 0.5f, 0.5f, 0, 1 };\n\n private float[] data = { // Object 1 positions\n LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, // Object 2 positions\n TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, // Object 1 colors\n GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], // Object 2 colors\n RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3] };\n\n private final short[] indices = { 0, 2, 1, 3, 2, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 11, 13, 12, 14, 16, 15, 17, 16, 14 };\n\n private ShaderProgram program;\n\n private int offsetUniform;\n\n private int vao;\n\n private FloatBuffer perspectiveMatrix;\n\n private int perspectiveMatrixUniform;\n\n private float frustumScale = 1;\n\n public Example5_2() {\n super(\"Example 5.2 - Base Vertex Overlap\", 500, 500, true);\n }\n\n @Override\n public void init() {\n glClearColor(0, 0, 0, 0);\n program = new ShaderProgram(readFromFile(\"example5.2.vert\"), readFromFile(\"example5.2.frag\"));\n offsetUniform = program.getUniformLocation(\"offset\");\n perspectiveMatrixUniform = program.getUniformLocation(\"perspectiveMatrix\");\n float zNear = 1, zFar = 3;\n perspectiveMatrix = BufferUtils.createFloatBuffer(16);\n perspectiveMatrix.put(0, frustumScale);\n perspectiveMatrix.put(5, frustumScale);\n perspectiveMatrix.put(10, (zFar + zNear) / (zNear - zFar));\n perspectiveMatrix.put(14, (2 * zFar * zNear) / (zNear - zFar));\n perspectiveMatrix.put(11, -1);\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);\n program.end();\n int vbo1 = glGenBuffers();\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glBufferData(GL_ARRAY_BUFFER, (FloatBuffer) BufferUtils.createFloatBuffer(data.length).put(data).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n int vbo2 = glGenBuffers();\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, (ShortBuffer) BufferUtils.createShortBuffer(indices.length).put(indices).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n vao = glGenVertexArrays();\n glBindVertexArray(vao);\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);\n glVertexAttribPointer(1, 4, GL_FLOAT, false, 0, 36 * 3 * 4);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBindVertexArray(0);\n glEnable(GL_CULL_FACE);\n glCullFace(GL_BACK);\n glFrontFace(GL_CW);\n }\n\n @Override\n public void resized() ", "post_mask_code": "\n\n @Override\n public void render() {\n glClear(GL_COLOR_BUFFER_BIT);\n program.begin();\n glBindVertexArray(vao);\n glUniform3f(offsetUniform, 0, 0, 0);\n glDrawElements(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0);\n glUniform3f(offsetUniform, 0, 0, -1);\n glDrawElementsBaseVertex(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0, 36 / 2);\n glBindVertexArray(0);\n program.end();\n }\n}\n"} {"task_id": "Java_880", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/ra4king/LWJGL-OpenGL-Tutorials/src/com/ra4king/opengl/arcsynthesis/gl33/chapter5/example2/Example5_2.java", "mask_start_position": 7331, "mask_end_position": 7441, "canonical_solution": "\n super.resized();\n perspectiveMatrix.put(0, frustumScale / ((float) getWidth() / getHeight()));", "pre_mask_code": "package com.ra4king.opengl.arcsynthesis.gl33.chapter5.example2;\n\nimport static org.lwjgl.opengl.GL11.*;\nimport static org.lwjgl.opengl.GL15.*;\nimport static org.lwjgl.opengl.GL20.*;\nimport static org.lwjgl.opengl.GL30.*;\nimport static org.lwjgl.opengl.GL32.*;\nimport java.nio.FloatBuffer;\nimport java.nio.ShortBuffer;\nimport org.lwjgl.BufferUtils;\nimport com.ra4king.opengl.GLProgram;\nimport com.ra4king.opengl.util.ShaderProgram;\n\npublic class Example5_2 extends GLProgram {\n\n public static void main(String[] args) {\n new Example5_2().run(true);\n }\n\n private final float RIGHT_EXTENT = 0.8f;\n\n private final float LEFT_EXTENT = -RIGHT_EXTENT;\n\n private final float TOP_EXTENT = 0.2f;\n\n private final float MIDDLE_EXTENT = 0;\n\n private final float BOTTOM_EXTENT = -TOP_EXTENT;\n\n private final float FRONT_EXTENT = -1.25f;\n\n private final float REAR_EXTENT = -1.75f;\n\n private final float[] GREEN_COLOR = { 0.75f, 0.75f, 1, 1 };\n\n private final float[] BLUE_COLOR = { 0, 0.5f, 0, 1 };\n\n private final float[] RED_COLOR = { 1, 0, 0, 1 };\n\n private final float[] GREY_COLOR = { 0.8f, 0.8f, 0.8f, 1 };\n\n private final float[] BROWN_COLOR = { 0.5f, 0.5f, 0, 1 };\n\n private float[] data = { // Object 1 positions\n LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, // Object 2 positions\n TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, // Object 1 colors\n GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], // Object 2 colors\n RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3] };\n\n private final short[] indices = { 0, 2, 1, 3, 2, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 11, 13, 12, 14, 16, 15, 17, 16, 14 };\n\n private ShaderProgram program;\n\n private int offsetUniform;\n\n private int vao;\n\n private FloatBuffer perspectiveMatrix;\n\n private int perspectiveMatrixUniform;\n\n private float frustumScale = 1;\n\n public Example5_2() {\n super(\"Example 5.2 - Base Vertex Overlap\", 500, 500, true);\n }\n\n @Override\n public void init() {\n glClearColor(0, 0, 0, 0);\n program = new ShaderProgram(readFromFile(\"example5.2.vert\"), readFromFile(\"example5.2.frag\"));\n offsetUniform = program.getUniformLocation(\"offset\");\n perspectiveMatrixUniform = program.getUniformLocation(\"perspectiveMatrix\");\n float zNear = 1, zFar = 3;\n perspectiveMatrix = BufferUtils.createFloatBuffer(16);\n perspectiveMatrix.put(0, frustumScale);\n perspectiveMatrix.put(5, frustumScale);\n perspectiveMatrix.put(10, (zFar + zNear) / (zNear - zFar));\n perspectiveMatrix.put(14, (2 * zFar * zNear) / (zNear - zFar));\n perspectiveMatrix.put(11, -1);\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);\n program.end();\n int vbo1 = glGenBuffers();\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glBufferData(GL_ARRAY_BUFFER, (FloatBuffer) BufferUtils.createFloatBuffer(data.length).put(data).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n int vbo2 = glGenBuffers();\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, (ShortBuffer) BufferUtils.createShortBuffer(indices.length).put(indices).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n vao = glGenVertexArrays();\n glBindVertexArray(vao);\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);\n glVertexAttribPointer(1, 4, GL_FLOAT, false, 0, 36 * 3 * 4);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBindVertexArray(0);\n glEnable(GL_CULL_FACE);\n glCullFace(GL_BACK);\n glFrontFace(GL_CW);\n }\n\n @Override\n public void resized() {", "post_mask_code": "\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);\n program.end();\n }\n\n @Override\n public void render() {\n glClear(GL_COLOR_BUFFER_BIT);\n program.begin();\n glBindVertexArray(vao);\n glUniform3f(offsetUniform, 0, 0, 0);\n glDrawElements(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0);\n glUniform3f(offsetUniform, 0, 0, -1);\n glDrawElementsBaseVertex(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0, 36 / 2);\n glBindVertexArray(0);\n program.end();\n }\n}\n"} {"task_id": "Java_881", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/ra4king/LWJGL-OpenGL-Tutorials/src/com/ra4king/opengl/arcsynthesis/gl33/chapter5/example2/Example5_2.java", "mask_start_position": 7450, "mask_end_position": 7544, "canonical_solution": "program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);", "pre_mask_code": "package com.ra4king.opengl.arcsynthesis.gl33.chapter5.example2;\n\nimport static org.lwjgl.opengl.GL11.*;\nimport static org.lwjgl.opengl.GL15.*;\nimport static org.lwjgl.opengl.GL20.*;\nimport static org.lwjgl.opengl.GL30.*;\nimport static org.lwjgl.opengl.GL32.*;\nimport java.nio.FloatBuffer;\nimport java.nio.ShortBuffer;\nimport org.lwjgl.BufferUtils;\nimport com.ra4king.opengl.GLProgram;\nimport com.ra4king.opengl.util.ShaderProgram;\n\npublic class Example5_2 extends GLProgram {\n\n public static void main(String[] args) {\n new Example5_2().run(true);\n }\n\n private final float RIGHT_EXTENT = 0.8f;\n\n private final float LEFT_EXTENT = -RIGHT_EXTENT;\n\n private final float TOP_EXTENT = 0.2f;\n\n private final float MIDDLE_EXTENT = 0;\n\n private final float BOTTOM_EXTENT = -TOP_EXTENT;\n\n private final float FRONT_EXTENT = -1.25f;\n\n private final float REAR_EXTENT = -1.75f;\n\n private final float[] GREEN_COLOR = { 0.75f, 0.75f, 1, 1 };\n\n private final float[] BLUE_COLOR = { 0, 0.5f, 0, 1 };\n\n private final float[] RED_COLOR = { 1, 0, 0, 1 };\n\n private final float[] GREY_COLOR = { 0.8f, 0.8f, 0.8f, 1 };\n\n private final float[] BROWN_COLOR = { 0.5f, 0.5f, 0, 1 };\n\n private float[] data = { // Object 1 positions\n LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, // Object 2 positions\n TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, // Object 1 colors\n GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], // Object 2 colors\n RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3] };\n\n private final short[] indices = { 0, 2, 1, 3, 2, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 11, 13, 12, 14, 16, 15, 17, 16, 14 };\n\n private ShaderProgram program;\n\n private int offsetUniform;\n\n private int vao;\n\n private FloatBuffer perspectiveMatrix;\n\n private int perspectiveMatrixUniform;\n\n private float frustumScale = 1;\n\n public Example5_2() {\n super(\"Example 5.2 - Base Vertex Overlap\", 500, 500, true);\n }\n\n @Override\n public void init() {\n glClearColor(0, 0, 0, 0);\n program = new ShaderProgram(readFromFile(\"example5.2.vert\"), readFromFile(\"example5.2.frag\"));\n offsetUniform = program.getUniformLocation(\"offset\");\n perspectiveMatrixUniform = program.getUniformLocation(\"perspectiveMatrix\");\n float zNear = 1, zFar = 3;\n perspectiveMatrix = BufferUtils.createFloatBuffer(16);\n perspectiveMatrix.put(0, frustumScale);\n perspectiveMatrix.put(5, frustumScale);\n perspectiveMatrix.put(10, (zFar + zNear) / (zNear - zFar));\n perspectiveMatrix.put(14, (2 * zFar * zNear) / (zNear - zFar));\n perspectiveMatrix.put(11, -1);\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);\n program.end();\n int vbo1 = glGenBuffers();\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glBufferData(GL_ARRAY_BUFFER, (FloatBuffer) BufferUtils.createFloatBuffer(data.length).put(data).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n int vbo2 = glGenBuffers();\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, (ShortBuffer) BufferUtils.createShortBuffer(indices.length).put(indices).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n vao = glGenVertexArrays();\n glBindVertexArray(vao);\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);\n glVertexAttribPointer(1, 4, GL_FLOAT, false, 0, 36 * 3 * 4);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBindVertexArray(0);\n glEnable(GL_CULL_FACE);\n glCullFace(GL_BACK);\n glFrontFace(GL_CW);\n }\n\n @Override\n public void resized() {\n super.resized();\n perspectiveMatrix.put(0, frustumScale / ((float) getWidth() / getHeight()));\n ", "post_mask_code": "\n program.end();\n }\n\n @Override\n public void render() {\n glClear(GL_COLOR_BUFFER_BIT);\n program.begin();\n glBindVertexArray(vao);\n glUniform3f(offsetUniform, 0, 0, 0);\n glDrawElements(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0);\n glUniform3f(offsetUniform, 0, 0, -1);\n glDrawElementsBaseVertex(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0, 36 / 2);\n glBindVertexArray(0);\n program.end();\n }\n}\n"} {"task_id": "Java_882", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/ra4king/LWJGL-OpenGL-Tutorials/src/com/ra4king/opengl/arcsynthesis/gl33/chapter5/example2/Example5_2.java", "mask_start_position": 7553, "mask_end_position": 7573, "canonical_solution": "program.end();\n }", "pre_mask_code": "package com.ra4king.opengl.arcsynthesis.gl33.chapter5.example2;\n\nimport static org.lwjgl.opengl.GL11.*;\nimport static org.lwjgl.opengl.GL15.*;\nimport static org.lwjgl.opengl.GL20.*;\nimport static org.lwjgl.opengl.GL30.*;\nimport static org.lwjgl.opengl.GL32.*;\nimport java.nio.FloatBuffer;\nimport java.nio.ShortBuffer;\nimport org.lwjgl.BufferUtils;\nimport com.ra4king.opengl.GLProgram;\nimport com.ra4king.opengl.util.ShaderProgram;\n\npublic class Example5_2 extends GLProgram {\n\n public static void main(String[] args) {\n new Example5_2().run(true);\n }\n\n private final float RIGHT_EXTENT = 0.8f;\n\n private final float LEFT_EXTENT = -RIGHT_EXTENT;\n\n private final float TOP_EXTENT = 0.2f;\n\n private final float MIDDLE_EXTENT = 0;\n\n private final float BOTTOM_EXTENT = -TOP_EXTENT;\n\n private final float FRONT_EXTENT = -1.25f;\n\n private final float REAR_EXTENT = -1.75f;\n\n private final float[] GREEN_COLOR = { 0.75f, 0.75f, 1, 1 };\n\n private final float[] BLUE_COLOR = { 0, 0.5f, 0, 1 };\n\n private final float[] RED_COLOR = { 1, 0, 0, 1 };\n\n private final float[] GREY_COLOR = { 0.8f, 0.8f, 0.8f, 1 };\n\n private final float[] BROWN_COLOR = { 0.5f, 0.5f, 0, 1 };\n\n private float[] data = { // Object 1 positions\n LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, // Object 2 positions\n TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, // Object 1 colors\n GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], // Object 2 colors\n RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3] };\n\n private final short[] indices = { 0, 2, 1, 3, 2, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 11, 13, 12, 14, 16, 15, 17, 16, 14 };\n\n private ShaderProgram program;\n\n private int offsetUniform;\n\n private int vao;\n\n private FloatBuffer perspectiveMatrix;\n\n private int perspectiveMatrixUniform;\n\n private float frustumScale = 1;\n\n public Example5_2() {\n super(\"Example 5.2 - Base Vertex Overlap\", 500, 500, true);\n }\n\n @Override\n public void init() {\n glClearColor(0, 0, 0, 0);\n program = new ShaderProgram(readFromFile(\"example5.2.vert\"), readFromFile(\"example5.2.frag\"));\n offsetUniform = program.getUniformLocation(\"offset\");\n perspectiveMatrixUniform = program.getUniformLocation(\"perspectiveMatrix\");\n float zNear = 1, zFar = 3;\n perspectiveMatrix = BufferUtils.createFloatBuffer(16);\n perspectiveMatrix.put(0, frustumScale);\n perspectiveMatrix.put(5, frustumScale);\n perspectiveMatrix.put(10, (zFar + zNear) / (zNear - zFar));\n perspectiveMatrix.put(14, (2 * zFar * zNear) / (zNear - zFar));\n perspectiveMatrix.put(11, -1);\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);\n program.end();\n int vbo1 = glGenBuffers();\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glBufferData(GL_ARRAY_BUFFER, (FloatBuffer) BufferUtils.createFloatBuffer(data.length).put(data).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n int vbo2 = glGenBuffers();\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, (ShortBuffer) BufferUtils.createShortBuffer(indices.length).put(indices).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n vao = glGenVertexArrays();\n glBindVertexArray(vao);\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);\n glVertexAttribPointer(1, 4, GL_FLOAT, false, 0, 36 * 3 * 4);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBindVertexArray(0);\n glEnable(GL_CULL_FACE);\n glCullFace(GL_BACK);\n glFrontFace(GL_CW);\n }\n\n @Override\n public void resized() {\n super.resized();\n perspectiveMatrix.put(0, frustumScale / ((float) getWidth() / getHeight()));\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);\n ", "post_mask_code": "\n\n @Override\n public void render() {\n glClear(GL_COLOR_BUFFER_BIT);\n program.begin();\n glBindVertexArray(vao);\n glUniform3f(offsetUniform, 0, 0, 0);\n glDrawElements(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0);\n glUniform3f(offsetUniform, 0, 0, -1);\n glDrawElementsBaseVertex(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0, 36 / 2);\n glBindVertexArray(0);\n program.end();\n }\n}\n"} {"task_id": "Java_883", "language": "Java", "task_type": "single_line", "source_file": "java/github/ra4king/LWJGL-OpenGL-Tutorials/src/com/ra4king/opengl/arcsynthesis/gl33/chapter5/example2/Example5_2.java", "mask_start_position": 6228, "mask_end_position": 6236, "canonical_solution": "Matrix);", "pre_mask_code": "package com.ra4king.opengl.arcsynthesis.gl33.chapter5.example2;\n\nimport static org.lwjgl.opengl.GL11.*;\nimport static org.lwjgl.opengl.GL15.*;\nimport static org.lwjgl.opengl.GL20.*;\nimport static org.lwjgl.opengl.GL30.*;\nimport static org.lwjgl.opengl.GL32.*;\nimport java.nio.FloatBuffer;\nimport java.nio.ShortBuffer;\nimport org.lwjgl.BufferUtils;\nimport com.ra4king.opengl.GLProgram;\nimport com.ra4king.opengl.util.ShaderProgram;\n\npublic class Example5_2 extends GLProgram {\n\n public static void main(String[] args) {\n new Example5_2().run(true);\n }\n\n private final float RIGHT_EXTENT = 0.8f;\n\n private final float LEFT_EXTENT = -RIGHT_EXTENT;\n\n private final float TOP_EXTENT = 0.2f;\n\n private final float MIDDLE_EXTENT = 0;\n\n private final float BOTTOM_EXTENT = -TOP_EXTENT;\n\n private final float FRONT_EXTENT = -1.25f;\n\n private final float REAR_EXTENT = -1.75f;\n\n private final float[] GREEN_COLOR = { 0.75f, 0.75f, 1, 1 };\n\n private final float[] BLUE_COLOR = { 0, 0.5f, 0, 1 };\n\n private final float[] RED_COLOR = { 1, 0, 0, 1 };\n\n private final float[] GREY_COLOR = { 0.8f, 0.8f, 0.8f, 1 };\n\n private final float[] BROWN_COLOR = { 0.5f, 0.5f, 0, 1 };\n\n private float[] data = { // Object 1 positions\n LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, // Object 2 positions\n TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, // Object 1 colors\n GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], // Object 2 colors\n RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3] };\n\n private final short[] indices = { 0, 2, 1, 3, 2, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 11, 13, 12, 14, 16, 15, 17, 16, 14 };\n\n private ShaderProgram program;\n\n private int offsetUniform;\n\n private int vao;\n\n private FloatBuffer perspectiveMatrix;\n\n private int perspectiveMatrixUniform;\n\n private float frustumScale = 1;\n\n public Example5_2() {\n super(\"Example 5.2 - Base Vertex Overlap\", 500, 500, true);\n }\n\n @Override\n public void init() {\n glClearColor(0, 0, 0, 0);\n program = new ShaderProgram(readFromFile(\"example5.2.vert\"), readFromFile(\"example5.2.frag\"));\n offsetUniform = program.getUniformLocation(\"offset\");\n perspectiveMatrixUniform = program.getUniformLocation(\"perspectiveMatrix\");\n float zNear = 1, zFar = 3;\n perspectiveMatrix = BufferUtils.createFloatBuffer(16);\n perspectiveMatrix.put(0, frustumScale);\n perspectiveMatrix.put(5, frustumScale);\n perspectiveMatrix.put(10, (zFar + zNear) / (zNear - zFar));\n perspectiveMatrix.put(14, (2 * zFar * zNear) / (zNear - zFar));\n perspectiveMatrix.put(11, -1);\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspective", "post_mask_code": "\n program.end();\n int vbo1 = glGenBuffers();\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glBufferData(GL_ARRAY_BUFFER, (FloatBuffer) BufferUtils.createFloatBuffer(data.length).put(data).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n int vbo2 = glGenBuffers();\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, (ShortBuffer) BufferUtils.createShortBuffer(indices.length).put(indices).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n vao = glGenVertexArrays();\n glBindVertexArray(vao);\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);\n glVertexAttribPointer(1, 4, GL_FLOAT, false, 0, 36 * 3 * 4);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBindVertexArray(0);\n glEnable(GL_CULL_FACE);\n glCullFace(GL_BACK);\n glFrontFace(GL_CW);\n }\n\n @Override\n public void resized() {\n super.resized();\n perspectiveMatrix.put(0, frustumScale / ((float) getWidth() / getHeight()));\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);\n program.end();\n }\n\n @Override\n public void render() {\n glClear(GL_COLOR_BUFFER_BIT);\n program.begin();\n glBindVertexArray(vao);\n glUniform3f(offsetUniform, 0, 0, 0);\n glDrawElements(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0);\n glUniform3f(offsetUniform, 0, 0, -1);\n glDrawElementsBaseVertex(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0, 36 / 2);\n glBindVertexArray(0);\n program.end();\n }\n}\n"} {"task_id": "Java_884", "language": "Java", "task_type": "empty", "source_file": "java/github/ra4king/LWJGL-OpenGL-Tutorials/src/com/ra4king/opengl/arcsynthesis/gl33/chapter5/example2/Example5_2.java", "mask_start_position": 2320, "mask_end_position": 2320, "canonical_solution": "", "pre_mask_code": "package com.ra4king.opengl.arcsynthesis.gl33.chapter5.example2;\n\nimport static org.lwjgl.opengl.GL11.*;\nimport static org.lwjgl.opengl.GL15.*;\nimport static org.lwjgl.opengl.GL20.*;\nimport static org.lwjgl.opengl.GL30.*;\nimport static org.lwjgl.opengl.GL32.*;\nimport java.nio.FloatBuffer;\nimport java.nio.ShortBuffer;\nimport org.lwjgl.BufferUtils;\nimport com.ra4king.opengl.GLProgram;\nimport com.ra4king.opengl.util.ShaderProgram;\n\npublic class Example5_2 extends GLProgram {\n\n public static void main(String[] args) {\n new Example5_2().run(true);\n }\n\n private final float RIGHT_EXTENT = 0.8f;\n\n private final float LEFT_EXTENT = -RIGHT_EXTENT;\n\n private final float TOP_EXTENT = 0.2f;\n\n private final float MIDDLE_EXTENT = 0;\n\n private final float BOTTOM_EXTENT = -TOP_EXTENT;\n\n private final float FRONT_EXTENT = -1.25f;\n\n private final float REAR_EXTENT = -1.75f;\n\n private final float[] GREEN_COLOR = { 0.75f, 0.75f, 1, 1 };\n\n private final float[] BLUE_COLOR = { 0, 0.5f, 0, 1 };\n\n private final float[] RED_COLOR = { 1, 0, 0, 1 };\n\n private final float[] GREY_COLOR = { 0.8f, 0.8f, 0.8f, 1 };\n\n private final float[] BROWN_COLOR = { 0.5f, 0.5f, 0, 1 };\n\n private float[] data = { // Object 1 positions\n LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, // Object 2 positions\n TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM", "post_mask_code": "_EXTENT, LEFT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, // Object 1 colors\n GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], // Object 2 colors\n RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3], GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3] };\n\n private final short[] indices = { 0, 2, 1, 3, 2, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 11, 13, 12, 14, 16, 15, 17, 16, 14 };\n\n private ShaderProgram program;\n\n private int offsetUniform;\n\n private int vao;\n\n private FloatBuffer perspectiveMatrix;\n\n private int perspectiveMatrixUniform;\n\n private float frustumScale = 1;\n\n public Example5_2() {\n super(\"Example 5.2 - Base Vertex Overlap\", 500, 500, true);\n }\n\n @Override\n public void init() {\n glClearColor(0, 0, 0, 0);\n program = new ShaderProgram(readFromFile(\"example5.2.vert\"), readFromFile(\"example5.2.frag\"));\n offsetUniform = program.getUniformLocation(\"offset\");\n perspectiveMatrixUniform = program.getUniformLocation(\"perspectiveMatrix\");\n float zNear = 1, zFar = 3;\n perspectiveMatrix = BufferUtils.createFloatBuffer(16);\n perspectiveMatrix.put(0, frustumScale);\n perspectiveMatrix.put(5, frustumScale);\n perspectiveMatrix.put(10, (zFar + zNear) / (zNear - zFar));\n perspectiveMatrix.put(14, (2 * zFar * zNear) / (zNear - zFar));\n perspectiveMatrix.put(11, -1);\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);\n program.end();\n int vbo1 = glGenBuffers();\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glBufferData(GL_ARRAY_BUFFER, (FloatBuffer) BufferUtils.createFloatBuffer(data.length).put(data).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n int vbo2 = glGenBuffers();\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, (ShortBuffer) BufferUtils.createShortBuffer(indices.length).put(indices).flip(), GL_STATIC_DRAW);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n vao = glGenVertexArrays();\n glBindVertexArray(vao);\n glBindBuffer(GL_ARRAY_BUFFER, vbo1);\n glEnableVertexAttribArray(0);\n glEnableVertexAttribArray(1);\n glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);\n glVertexAttribPointer(1, 4, GL_FLOAT, false, 0, 36 * 3 * 4);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo2);\n glBindVertexArray(0);\n glEnable(GL_CULL_FACE);\n glCullFace(GL_BACK);\n glFrontFace(GL_CW);\n }\n\n @Override\n public void resized() {\n super.resized();\n perspectiveMatrix.put(0, frustumScale / ((float) getWidth() / getHeight()));\n program.begin();\n glUniformMatrix4(perspectiveMatrixUniform, false, perspectiveMatrix);\n program.end();\n }\n\n @Override\n public void render() {\n glClear(GL_COLOR_BUFFER_BIT);\n program.begin();\n glBindVertexArray(vao);\n glUniform3f(offsetUniform, 0, 0, 0);\n glDrawElements(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0);\n glUniform3f(offsetUniform, 0, 0, -1);\n glDrawElementsBaseVertex(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, 0, 36 / 2);\n glBindVertexArray(0);\n program.end();\n }\n}\n"} {"task_id": "Java_885", "language": "Java", "task_type": "method_signature", "source_file": "java/github/mzmine/mzmine2/src/main/java/net/sf/mzmine/modules/rawdatamethods/peakpicking/msms/MsMsPeakPickerModule.java", "mask_start_position": 915, "mask_end_position": 973, "canonical_solution": "@Override\n @Nonnull\n public String getDescription() ", "pre_mask_code": "/*\n * \n * This file is part of MZmine 2.\n * \n */\npackage net.sf.mzmine.modules.rawdatamethods.peakpicking.msms;\n\nimport java.util.Collection;\nimport javax.annotation.Nonnull;\nimport net.sf.mzmine.datamodel.MZmineProject;\nimport net.sf.mzmine.datamodel.RawDataFile;\nimport net.sf.mzmine.modules.MZmineModuleCategory;\nimport net.sf.mzmine.modules.MZmineProcessingModule;\nimport net.sf.mzmine.parameters.ParameterSet;\nimport net.sf.mzmine.taskcontrol.Task;\nimport net.sf.mzmine.util.ExitCode;\n\npublic class MsMsPeakPickerModule implements MZmineProcessingModule {\n\n private static final String MODULE_NAME = \"MS/MS peaklist builder\";\n\n private static final String MODULE_DESCRIPTION = \"This module looks through the whole raw data for MS2 scans and makes a list of chromatographic peaks using the precursor mass.\";\n\n @Override\n @Nonnull\n public String getName() {\n return MODULE_NAME;\n }\n\n ", "post_mask_code": "{\n return MODULE_DESCRIPTION;\n }\n\n @Override\n @Nonnull\n public ExitCode runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters, @Nonnull Collection tasks) {\n RawDataFile[] dataFiles = parameters.getParameter(MsMsPeakPickerParameters.dataFiles).getValue().getMatchingRawDataFiles();\n for (RawDataFile dataFile : dataFiles) {\n Task newTask = new MsMsPeakPickingTask(project, dataFile, parameters);\n tasks.add(newTask);\n }\n return ExitCode.OK;\n }\n\n @Override\n @Nonnull\n public MZmineModuleCategory getModuleCategory() {\n return MZmineModuleCategory.PEAKPICKING;\n }\n\n @Override\n @Nonnull\n public Class getParameterSetClass() {\n return MsMsPeakPickerParameters.class;\n }\n}\n"} {"task_id": "Java_886", "language": "Java", "task_type": "method_body", "source_file": "java/github/mzmine/mzmine2/src/main/java/net/sf/mzmine/modules/rawdatamethods/peakpicking/msms/MsMsPeakPickerModule.java", "mask_start_position": 1595, "mask_end_position": 1651, "canonical_solution": "{\n return MZmineModuleCategory.PEAKPICKING;\n }", "pre_mask_code": "/*\n * \n * This file is part of MZmine 2.\n * \n */\npackage net.sf.mzmine.modules.rawdatamethods.peakpicking.msms;\n\nimport java.util.Collection;\nimport javax.annotation.Nonnull;\nimport net.sf.mzmine.datamodel.MZmineProject;\nimport net.sf.mzmine.datamodel.RawDataFile;\nimport net.sf.mzmine.modules.MZmineModuleCategory;\nimport net.sf.mzmine.modules.MZmineProcessingModule;\nimport net.sf.mzmine.parameters.ParameterSet;\nimport net.sf.mzmine.taskcontrol.Task;\nimport net.sf.mzmine.util.ExitCode;\n\npublic class MsMsPeakPickerModule implements MZmineProcessingModule {\n\n private static final String MODULE_NAME = \"MS/MS peaklist builder\";\n\n private static final String MODULE_DESCRIPTION = \"This module looks through the whole raw data for MS2 scans and makes a list of chromatographic peaks using the precursor mass.\";\n\n @Override\n @Nonnull\n public String getName() {\n return MODULE_NAME;\n }\n\n @Override\n @Nonnull\n public String getDescription() {\n return MODULE_DESCRIPTION;\n }\n\n @Override\n @Nonnull\n public ExitCode runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters, @Nonnull Collection tasks) {\n RawDataFile[] dataFiles = parameters.getParameter(MsMsPeakPickerParameters.dataFiles).getValue().getMatchingRawDataFiles();\n for (RawDataFile dataFile : dataFiles) {\n Task newTask = new MsMsPeakPickingTask(project, dataFile, parameters);\n tasks.add(newTask);\n }\n return ExitCode.OK;\n }\n\n @Override\n @Nonnull\n public MZmineModuleCategory getModuleCategory() ", "post_mask_code": "\n\n @Override\n @Nonnull\n public Class getParameterSetClass() {\n return MsMsPeakPickerParameters.class;\n }\n}\n"} {"task_id": "Java_887", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/mzmine/mzmine2/src/main/java/net/sf/mzmine/modules/rawdatamethods/peakpicking/msms/MsMsPeakPickerModule.java", "mask_start_position": 1174, "mask_end_position": 1306, "canonical_solution": "\n RawDataFile[] dataFiles = parameters.getParameter(MsMsPeakPickerParameters.dataFiles).getValue().getMatchingRawDataFiles();", "pre_mask_code": "/*\n * \n * This file is part of MZmine 2.\n * \n */\npackage net.sf.mzmine.modules.rawdatamethods.peakpicking.msms;\n\nimport java.util.Collection;\nimport javax.annotation.Nonnull;\nimport net.sf.mzmine.datamodel.MZmineProject;\nimport net.sf.mzmine.datamodel.RawDataFile;\nimport net.sf.mzmine.modules.MZmineModuleCategory;\nimport net.sf.mzmine.modules.MZmineProcessingModule;\nimport net.sf.mzmine.parameters.ParameterSet;\nimport net.sf.mzmine.taskcontrol.Task;\nimport net.sf.mzmine.util.ExitCode;\n\npublic class MsMsPeakPickerModule implements MZmineProcessingModule {\n\n private static final String MODULE_NAME = \"MS/MS peaklist builder\";\n\n private static final String MODULE_DESCRIPTION = \"This module looks through the whole raw data for MS2 scans and makes a list of chromatographic peaks using the precursor mass.\";\n\n @Override\n @Nonnull\n public String getName() {\n return MODULE_NAME;\n }\n\n @Override\n @Nonnull\n public String getDescription() {\n return MODULE_DESCRIPTION;\n }\n\n @Override\n @Nonnull\n public ExitCode runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters, @Nonnull Collection tasks) {", "post_mask_code": "\n for (RawDataFile dataFile : dataFiles) {\n Task newTask = new MsMsPeakPickingTask(project, dataFile, parameters);\n tasks.add(newTask);\n }\n return ExitCode.OK;\n }\n\n @Override\n @Nonnull\n public MZmineModuleCategory getModuleCategory() {\n return MZmineModuleCategory.PEAKPICKING;\n }\n\n @Override\n @Nonnull\n public Class getParameterSetClass() {\n return MsMsPeakPickerParameters.class;\n }\n}\n"} {"task_id": "Java_888", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/mzmine/mzmine2/src/main/java/net/sf/mzmine/modules/rawdatamethods/peakpicking/msms/MsMsPeakPickerModule.java", "mask_start_position": 1315, "mask_end_position": 1480, "canonical_solution": "for (RawDataFile dataFile : dataFiles) {\n Task newTask = new MsMsPeakPickingTask(project, dataFile, parameters);\n tasks.add(newTask);\n }", "pre_mask_code": "/*\n * \n * This file is part of MZmine 2.\n * \n */\npackage net.sf.mzmine.modules.rawdatamethods.peakpicking.msms;\n\nimport java.util.Collection;\nimport javax.annotation.Nonnull;\nimport net.sf.mzmine.datamodel.MZmineProject;\nimport net.sf.mzmine.datamodel.RawDataFile;\nimport net.sf.mzmine.modules.MZmineModuleCategory;\nimport net.sf.mzmine.modules.MZmineProcessingModule;\nimport net.sf.mzmine.parameters.ParameterSet;\nimport net.sf.mzmine.taskcontrol.Task;\nimport net.sf.mzmine.util.ExitCode;\n\npublic class MsMsPeakPickerModule implements MZmineProcessingModule {\n\n private static final String MODULE_NAME = \"MS/MS peaklist builder\";\n\n private static final String MODULE_DESCRIPTION = \"This module looks through the whole raw data for MS2 scans and makes a list of chromatographic peaks using the precursor mass.\";\n\n @Override\n @Nonnull\n public String getName() {\n return MODULE_NAME;\n }\n\n @Override\n @Nonnull\n public String getDescription() {\n return MODULE_DESCRIPTION;\n }\n\n @Override\n @Nonnull\n public ExitCode runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters, @Nonnull Collection tasks) {\n RawDataFile[] dataFiles = parameters.getParameter(MsMsPeakPickerParameters.dataFiles).getValue().getMatchingRawDataFiles();\n ", "post_mask_code": "\n return ExitCode.OK;\n }\n\n @Override\n @Nonnull\n public MZmineModuleCategory getModuleCategory() {\n return MZmineModuleCategory.PEAKPICKING;\n }\n\n @Override\n @Nonnull\n public Class getParameterSetClass() {\n return MsMsPeakPickerParameters.class;\n }\n}\n"} {"task_id": "Java_889", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/mzmine/mzmine2/src/main/java/net/sf/mzmine/modules/rawdatamethods/peakpicking/msms/MsMsPeakPickerModule.java", "mask_start_position": 1489, "mask_end_position": 1514, "canonical_solution": "return ExitCode.OK;\n }", "pre_mask_code": "/*\n * \n * This file is part of MZmine 2.\n * \n */\npackage net.sf.mzmine.modules.rawdatamethods.peakpicking.msms;\n\nimport java.util.Collection;\nimport javax.annotation.Nonnull;\nimport net.sf.mzmine.datamodel.MZmineProject;\nimport net.sf.mzmine.datamodel.RawDataFile;\nimport net.sf.mzmine.modules.MZmineModuleCategory;\nimport net.sf.mzmine.modules.MZmineProcessingModule;\nimport net.sf.mzmine.parameters.ParameterSet;\nimport net.sf.mzmine.taskcontrol.Task;\nimport net.sf.mzmine.util.ExitCode;\n\npublic class MsMsPeakPickerModule implements MZmineProcessingModule {\n\n private static final String MODULE_NAME = \"MS/MS peaklist builder\";\n\n private static final String MODULE_DESCRIPTION = \"This module looks through the whole raw data for MS2 scans and makes a list of chromatographic peaks using the precursor mass.\";\n\n @Override\n @Nonnull\n public String getName() {\n return MODULE_NAME;\n }\n\n @Override\n @Nonnull\n public String getDescription() {\n return MODULE_DESCRIPTION;\n }\n\n @Override\n @Nonnull\n public ExitCode runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters, @Nonnull Collection tasks) {\n RawDataFile[] dataFiles = parameters.getParameter(MsMsPeakPickerParameters.dataFiles).getValue().getMatchingRawDataFiles();\n for (RawDataFile dataFile : dataFiles) {\n Task newTask = new MsMsPeakPickingTask(project, dataFile, parameters);\n tasks.add(newTask);\n }\n ", "post_mask_code": "\n\n @Override\n @Nonnull\n public MZmineModuleCategory getModuleCategory() {\n return MZmineModuleCategory.PEAKPICKING;\n }\n\n @Override\n @Nonnull\n public Class getParameterSetClass() {\n return MsMsPeakPickerParameters.class;\n }\n}\n"} {"task_id": "Java_890", "language": "Java", "task_type": "single_line", "source_file": "java/github/mzmine/mzmine2/src/main/java/net/sf/mzmine/modules/rawdatamethods/peakpicking/msms/MsMsPeakPickerModule.java", "mask_start_position": 1197, "mask_end_position": 1306, "canonical_solution": "dataFiles = parameters.getParameter(MsMsPeakPickerParameters.dataFiles).getValue().getMatchingRawDataFiles();", "pre_mask_code": "/*\n * \n * This file is part of MZmine 2.\n * \n */\npackage net.sf.mzmine.modules.rawdatamethods.peakpicking.msms;\n\nimport java.util.Collection;\nimport javax.annotation.Nonnull;\nimport net.sf.mzmine.datamodel.MZmineProject;\nimport net.sf.mzmine.datamodel.RawDataFile;\nimport net.sf.mzmine.modules.MZmineModuleCategory;\nimport net.sf.mzmine.modules.MZmineProcessingModule;\nimport net.sf.mzmine.parameters.ParameterSet;\nimport net.sf.mzmine.taskcontrol.Task;\nimport net.sf.mzmine.util.ExitCode;\n\npublic class MsMsPeakPickerModule implements MZmineProcessingModule {\n\n private static final String MODULE_NAME = \"MS/MS peaklist builder\";\n\n private static final String MODULE_DESCRIPTION = \"This module looks through the whole raw data for MS2 scans and makes a list of chromatographic peaks using the precursor mass.\";\n\n @Override\n @Nonnull\n public String getName() {\n return MODULE_NAME;\n }\n\n @Override\n @Nonnull\n public String getDescription() {\n return MODULE_DESCRIPTION;\n }\n\n @Override\n @Nonnull\n public ExitCode runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters, @Nonnull Collection tasks) {\n RawDataFile[] ", "post_mask_code": "\n for (RawDataFile dataFile : dataFiles) {\n Task newTask = new MsMsPeakPickingTask(project, dataFile, parameters);\n tasks.add(newTask);\n }\n return ExitCode.OK;\n }\n\n @Override\n @Nonnull\n public MZmineModuleCategory getModuleCategory() {\n return MZmineModuleCategory.PEAKPICKING;\n }\n\n @Override\n @Nonnull\n public Class getParameterSetClass() {\n return MsMsPeakPickerParameters.class;\n }\n}\n"} {"task_id": "Java_891", "language": "Java", "task_type": "empty", "source_file": "java/github/mzmine/mzmine2/src/main/java/net/sf/mzmine/modules/rawdatamethods/peakpicking/msms/MsMsPeakPickerModule.java", "mask_start_position": 157, "mask_end_position": 157, "canonical_solution": "", "pre_mask_code": "/*\n * \n * This file is part of MZmine 2.\n * \n */\npackage net.sf.mzmine.modules.rawdatamethods.peakpicking.msms;\n\nimport java.util.Collection;\nimport javax.an", "post_mask_code": "notation.Nonnull;\nimport net.sf.mzmine.datamodel.MZmineProject;\nimport net.sf.mzmine.datamodel.RawDataFile;\nimport net.sf.mzmine.modules.MZmineModuleCategory;\nimport net.sf.mzmine.modules.MZmineProcessingModule;\nimport net.sf.mzmine.parameters.ParameterSet;\nimport net.sf.mzmine.taskcontrol.Task;\nimport net.sf.mzmine.util.ExitCode;\n\npublic class MsMsPeakPickerModule implements MZmineProcessingModule {\n\n private static final String MODULE_NAME = \"MS/MS peaklist builder\";\n\n private static final String MODULE_DESCRIPTION = \"This module looks through the whole raw data for MS2 scans and makes a list of chromatographic peaks using the precursor mass.\";\n\n @Override\n @Nonnull\n public String getName() {\n return MODULE_NAME;\n }\n\n @Override\n @Nonnull\n public String getDescription() {\n return MODULE_DESCRIPTION;\n }\n\n @Override\n @Nonnull\n public ExitCode runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters, @Nonnull Collection tasks) {\n RawDataFile[] dataFiles = parameters.getParameter(MsMsPeakPickerParameters.dataFiles).getValue().getMatchingRawDataFiles();\n for (RawDataFile dataFile : dataFiles) {\n Task newTask = new MsMsPeakPickingTask(project, dataFile, parameters);\n tasks.add(newTask);\n }\n return ExitCode.OK;\n }\n\n @Override\n @Nonnull\n public MZmineModuleCategory getModuleCategory() {\n return MZmineModuleCategory.PEAKPICKING;\n }\n\n @Override\n @Nonnull\n public Class getParameterSetClass() {\n return MsMsPeakPickerParameters.class;\n }\n}\n"} {"task_id": "Java_892", "language": "Java", "task_type": "method_signature", "source_file": "java/github/morganstanley/SilverKing/src/com/ms/silverking/cloud/dht/net/IPAliasMap.java", "mask_start_position": 8577, "mask_end_position": 8667, "canonical_solution": "public void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort) ", "pre_mask_code": "package com.ms.silverking.cloud.dht.net;\n\nimport java.net.InetSocketAddress;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport com.google.common.collect.ImmutableMap;\nimport com.ms.silverking.collection.CollectionUtil;\nimport com.ms.silverking.collection.HashedSetMap;\nimport com.ms.silverking.log.Log;\nimport com.ms.silverking.net.AddrAndPort;\nimport com.ms.silverking.net.IPAndPort;\n\n/**\n * Background: Under \"normal\" operation, each SK daemon has a fixed port bound to a single IP address. The port\n * is the same for all daemons. This implies that only a single daemon may run per server. It also implies that all\n * traffic will go over a single interface.\n *

\n * IP aliasing allows us to overcome these limitations. IP aliasing does this in two ways:\n * 1) The aliasing feature can be used to allow a daemon to be identified by a \"fake\" IPAndPort. This IPAndPort is\n * used in the topology and almost all of the rest of the code as if it were a real IP. This IPAliasMap class is\n * used by MessageGroupBase (and a few other classes) to translate this IPAndPort into an actual IPAndPort when\n * communication needs to take place. By design, most of the code is unaware of this translation.\n * 2) The aliasing feature allows traffic to be distributed across multiple interfaces. This is done by associating\n * multiple interfaces with an actual IPAndPort. In this case, MessageGroupBase will translate the usual IPAndPort\n * into one of the many remote interfaces in a round-robin fashion.\n *

\n * Terminology: for consistency in the above two cases, this class calls the IP address used to identify a daemon\n * the \"daemon IP\" or \"daemon\" for short. Note that the port is fixed to the SK instance port for this case.\n * Each of the one or more IPAndPorts associated with a daemon IP is called an \"interface IP and port\" or\n * \"interface\" for short. The \"interface IP and port\" are always a real IP and port. The daemon IP is \"fake\"\n * for case 1, but an actual IP for case 2.\n *

\n * For case (1) each daemon IP acts as an alias, and has a single interface IP and port to which it is associated.\n * For case (2) each daemon IP has several interface IPAndPorts with which it is associated.\n *

\n * Colloquially, for case (1) we can call the daemon IP an \"alias\". We don't do that in this code to avoid confusion\n * with case (2) where we could call the interface IP and ports aliases. (The daemon IP is real in this case.)\n *

\n * Notes on case (1) - setting up \"aliases\"/fake IP addresses for each daemon IP.\n * - the topology, host groups, etc, must be composed of these daemon IPs, not interface IPs\n * - the DHT config must have an ipAliasMap field in the form ipAliasMap={daemonIp=interfaceIp:port}\n * As mentioned previously, the vast majority of the code will use this daemon IP as if it were the actual IP.\n * In addition, users will only use the daemon IP.\n *

\n * All translation between daemon IP and interface IP and ports will take place in this class.\n * Clients will select a daemon IP address from the topology as their preferredServer. This is dealiased in\n * DHTSessionImpl to an interface IP and port, to which the client communicates.\n * Aliasing also allows nodes to deviate from the fixed port in DHT config; such nodes would require an alias\n * map entry which maps a fake IP to the port actually in use for a given address. The node itself must be passed\n * -port N on the command line at start up in order to run on a port different to that specified in DHT config.\n * This also allows many nodes to run on the same machine; several daemon IP entries in the maps could exist,\n * which resolve to the same host, but with unique ports. Note that each daemon IP must be unique in this case\n *

\n * It is not required that all nodes have an alias identity, so long as it is consistent between the topology\n * and host group files, and such nodes can be omitted from the alias map. The alias resolution, when it\n * does not find an entry for such a node, would leave the address unchanged and clients/servers would proceed\n * to try and connect directly\n *

\n * Notes on case 2:\n * When aliasing is used to support multi-homing, each daemon IP will be associated with\n * several interface and ports, and the dht config will have an entry of the\n * form: ipAliasMap={daemonIp=interfaceIp:port,...}. Note that all ports must be the same for case 2.\n * The ports may also be omitted.\n */\npublic class IPAliasMap {\n\n // one-to-many\n private final Map daemonToInterfaces;\n\n // many-to-one\n private final Map interfaceToDaemon;\n\n private final HashedSetMap interfaceIPToDaemons;\n\n // used for round-robin between aliases\n private final AtomicInteger interfaceIndex;\n\n // (e.g. for distributing traffic across multi-homed interfaces)\n private static final boolean logDaemonToInterfaceMapping = true;\n\n private static final boolean logInterfaceToDaemonMapping = true;\n\n public IPAliasMap(Map daemonToInterfaces) {\n interfaceToDaemon = new ConcurrentHashMap<>();\n interfaceIPToDaemons = new HashedSetMap<>();\n if (daemonToInterfaces == null) {\n this.daemonToInterfaces = ImmutableMap.of();\n interfaceIndex = null;\n } else {\n sanityCheckMap(daemonToInterfaces);\n this.daemonToInterfaces = new ConcurrentHashMap<>();\n interfaceIndex = new AtomicInteger();\n this.daemonToInterfaces.putAll(daemonToInterfaces);\n if (logDaemonToInterfaceMapping) {\n IPAliasingUtil.logAliasMap(daemonToInterfaces);\n }\n addReverseMappings(daemonToInterfaces);\n }\n }\n\n public static IPAliasMap identityMap() {\n return new IPAliasMap(null);\n }\n\n private void sanityCheckMap(Map daemonToInterfaces) {\n ensureDaemonPortsMatch(daemonToInterfaces);\n }\n\n private void ensureDaemonPortsMatch(Map daemonToInterfaces) {\n int daemonPort;\n daemonPort = -1;\n for (IPAndPort daemonIPAndPort : daemonToInterfaces.keySet()) {\n if (daemonPort < 0) {\n daemonPort = daemonIPAndPort.getPort();\n } else {\n if (daemonIPAndPort.getPort() != daemonPort) {\n throw new RuntimeException(\"IPAliasMap daemon ports must all be the same\");\n }\n }\n }\n }\n\n public Map getDaemonToInterfacesMap() {\n return ImmutableMap.copyOf(daemonToInterfaces);\n }\n\n public Map getInterfaceToDaemonMap() {\n return ImmutableMap.copyOf(interfaceToDaemon);\n }\n\n public AddrAndPort daemonToInterface(AddrAndPort daemon) {\n AddrAndPort[] interfaces;\n interfaces = daemonToInterfaces.get(daemon);\n if (interfaces != null) {\n // Below is random. For now we implement round robin instead\n // Round robin\n return interfaces[interfaceIndex.getAndIncrement() % interfaces.length];\n } else {\n return daemon;\n }\n }\n\n public IPAndPort interfaceToDaemon(InetSocketAddress interfaceIPAndPort) {\n return interfaceToDaemon(new IPAndPort(interfaceIPAndPort));\n }\n\n public IPAndPort interfaceToDaemon(IPAndPort interfaceIPAndPort) {\n IPAndPort daemon;\n daemon = interfaceToDaemon.get(interfaceIPAndPort);\n return daemon != null ? daemon : interfaceIPAndPort;\n }\n\n /**\n * For all entries in the daemonToInterfaces argument, update the\n * reverse map. That is, update the interfaceToDaemon map with\n * the corresponding mappings.\n *\n * @param daemonToInterfaces the forward map to reverse\n */\n private void addReverseMappings(Map daemonToInterfaces) {\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n addInterfacesToDaemon(entry.getValue(), entry.getKey());\n }\n }\n\n // only used at startup\n private void addInterfacesToDaemon(IPAndPort[] interfaces, IPAndPort daemon) {\n for (IPAndPort interfaceIPAndPort : interfaces) {\n addInterfaceToDaemon(interfaceIPAndPort, daemon, false);\n addIPToDaemonMapping(interfaceIPAndPort.getIPAsString(), daemon);\n }\n }\n\n // used at runtime to map reverse connections\n ", "post_mask_code": "{\n addInterfaceToDaemon(interfaceIPAndPort, daemonIPAndPort, true);\n }\n\n private void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort, boolean allowRemapping) {\n IPAndPort prev;\n prev = interfaceToDaemon.put(interfaceIPAndPort, daemonIPAndPort);\n if (logInterfaceToDaemonMapping && (prev == null || !prev.equals(daemonIPAndPort))) {\n Log.infof(\"IPAliasMap adding interfaceIPAndPort=>daemonIPAndPort: %s=>%s\", interfaceIPAndPort, daemonIPAndPort);\n }\n if (!allowRemapping && prev != null && !prev.equals(daemonIPAndPort)) {\n throw new RuntimeException(\"Interface maps to multiple daemons: \" + interfaceIPAndPort);\n }\n }\n\n private void addIPToDaemonMapping(String ip, IPAndPort daemonIPAndPort) {\n interfaceIPToDaemons.addValue(ip, daemonIPAndPort);\n }\n\n /**\n * Given an interface ip, randomly select one of the possibly many associated daemons\n *\n * @param ip\n * @return\n */\n public IPAndPort interfaceIPToRandomDaemon(String ip) {\n return interfaceIPToDaemons.getAnyValue(ip);\n }\n\n /**\n * If an interface ip uniquely identifies a daemon ip, return that daemon\n *\n * @param ip\n * @return the uniquely associated daemon\n */\n public IPAndPort interfaceIPToDaemon_ifUnique(String ip) {\n Set daemonIPAndPorts;\n daemonIPAndPorts = interfaceIPToDaemons.getSet(ip);\n if (daemonIPAndPorts == null || daemonIPAndPorts.size() > 1) {\n return null;\n } else {\n return daemonIPAndPorts.iterator().next();\n }\n }\n\n @Override\n public String toString() {\n StringBuffer sb;\n sb = new StringBuffer();\n sb.append(\"{\");\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n sb.append(String.format(\"%s -> [\", entry.getKey()));\n for (IPAndPort _interface : entry.getValue()) {\n sb.append(_interface + \" \");\n }\n sb.append(\"]\\n\");\n }\n sb.append(\"}\");\n return sb.toString() + \"\\n\" + CollectionUtil.mapToString(interfaceToDaemon);\n }\n}\n"} {"task_id": "Java_893", "language": "Java", "task_type": "method_body", "source_file": "java/github/morganstanley/SilverKing/src/com/ms/silverking/cloud/dht/net/IPAliasMap.java", "mask_start_position": 6016, "mask_end_position": 6075, "canonical_solution": "{\n ensureDaemonPortsMatch(daemonToInterfaces);\n }", "pre_mask_code": "package com.ms.silverking.cloud.dht.net;\n\nimport java.net.InetSocketAddress;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport com.google.common.collect.ImmutableMap;\nimport com.ms.silverking.collection.CollectionUtil;\nimport com.ms.silverking.collection.HashedSetMap;\nimport com.ms.silverking.log.Log;\nimport com.ms.silverking.net.AddrAndPort;\nimport com.ms.silverking.net.IPAndPort;\n\n/**\n * Background: Under \"normal\" operation, each SK daemon has a fixed port bound to a single IP address. The port\n * is the same for all daemons. This implies that only a single daemon may run per server. It also implies that all\n * traffic will go over a single interface.\n *

\n * IP aliasing allows us to overcome these limitations. IP aliasing does this in two ways:\n * 1) The aliasing feature can be used to allow a daemon to be identified by a \"fake\" IPAndPort. This IPAndPort is\n * used in the topology and almost all of the rest of the code as if it were a real IP. This IPAliasMap class is\n * used by MessageGroupBase (and a few other classes) to translate this IPAndPort into an actual IPAndPort when\n * communication needs to take place. By design, most of the code is unaware of this translation.\n * 2) The aliasing feature allows traffic to be distributed across multiple interfaces. This is done by associating\n * multiple interfaces with an actual IPAndPort. In this case, MessageGroupBase will translate the usual IPAndPort\n * into one of the many remote interfaces in a round-robin fashion.\n *

\n * Terminology: for consistency in the above two cases, this class calls the IP address used to identify a daemon\n * the \"daemon IP\" or \"daemon\" for short. Note that the port is fixed to the SK instance port for this case.\n * Each of the one or more IPAndPorts associated with a daemon IP is called an \"interface IP and port\" or\n * \"interface\" for short. The \"interface IP and port\" are always a real IP and port. The daemon IP is \"fake\"\n * for case 1, but an actual IP for case 2.\n *

\n * For case (1) each daemon IP acts as an alias, and has a single interface IP and port to which it is associated.\n * For case (2) each daemon IP has several interface IPAndPorts with which it is associated.\n *

\n * Colloquially, for case (1) we can call the daemon IP an \"alias\". We don't do that in this code to avoid confusion\n * with case (2) where we could call the interface IP and ports aliases. (The daemon IP is real in this case.)\n *

\n * Notes on case (1) - setting up \"aliases\"/fake IP addresses for each daemon IP.\n * - the topology, host groups, etc, must be composed of these daemon IPs, not interface IPs\n * - the DHT config must have an ipAliasMap field in the form ipAliasMap={daemonIp=interfaceIp:port}\n * As mentioned previously, the vast majority of the code will use this daemon IP as if it were the actual IP.\n * In addition, users will only use the daemon IP.\n *

\n * All translation between daemon IP and interface IP and ports will take place in this class.\n * Clients will select a daemon IP address from the topology as their preferredServer. This is dealiased in\n * DHTSessionImpl to an interface IP and port, to which the client communicates.\n * Aliasing also allows nodes to deviate from the fixed port in DHT config; such nodes would require an alias\n * map entry which maps a fake IP to the port actually in use for a given address. The node itself must be passed\n * -port N on the command line at start up in order to run on a port different to that specified in DHT config.\n * This also allows many nodes to run on the same machine; several daemon IP entries in the maps could exist,\n * which resolve to the same host, but with unique ports. Note that each daemon IP must be unique in this case\n *

\n * It is not required that all nodes have an alias identity, so long as it is consistent between the topology\n * and host group files, and such nodes can be omitted from the alias map. The alias resolution, when it\n * does not find an entry for such a node, would leave the address unchanged and clients/servers would proceed\n * to try and connect directly\n *

\n * Notes on case 2:\n * When aliasing is used to support multi-homing, each daemon IP will be associated with\n * several interface and ports, and the dht config will have an entry of the\n * form: ipAliasMap={daemonIp=interfaceIp:port,...}. Note that all ports must be the same for case 2.\n * The ports may also be omitted.\n */\npublic class IPAliasMap {\n\n // one-to-many\n private final Map daemonToInterfaces;\n\n // many-to-one\n private final Map interfaceToDaemon;\n\n private final HashedSetMap interfaceIPToDaemons;\n\n // used for round-robin between aliases\n private final AtomicInteger interfaceIndex;\n\n // (e.g. for distributing traffic across multi-homed interfaces)\n private static final boolean logDaemonToInterfaceMapping = true;\n\n private static final boolean logInterfaceToDaemonMapping = true;\n\n public IPAliasMap(Map daemonToInterfaces) {\n interfaceToDaemon = new ConcurrentHashMap<>();\n interfaceIPToDaemons = new HashedSetMap<>();\n if (daemonToInterfaces == null) {\n this.daemonToInterfaces = ImmutableMap.of();\n interfaceIndex = null;\n } else {\n sanityCheckMap(daemonToInterfaces);\n this.daemonToInterfaces = new ConcurrentHashMap<>();\n interfaceIndex = new AtomicInteger();\n this.daemonToInterfaces.putAll(daemonToInterfaces);\n if (logDaemonToInterfaceMapping) {\n IPAliasingUtil.logAliasMap(daemonToInterfaces);\n }\n addReverseMappings(daemonToInterfaces);\n }\n }\n\n public static IPAliasMap identityMap() {\n return new IPAliasMap(null);\n }\n\n private void sanityCheckMap(Map daemonToInterfaces) ", "post_mask_code": "\n\n private void ensureDaemonPortsMatch(Map daemonToInterfaces) {\n int daemonPort;\n daemonPort = -1;\n for (IPAndPort daemonIPAndPort : daemonToInterfaces.keySet()) {\n if (daemonPort < 0) {\n daemonPort = daemonIPAndPort.getPort();\n } else {\n if (daemonIPAndPort.getPort() != daemonPort) {\n throw new RuntimeException(\"IPAliasMap daemon ports must all be the same\");\n }\n }\n }\n }\n\n public Map getDaemonToInterfacesMap() {\n return ImmutableMap.copyOf(daemonToInterfaces);\n }\n\n public Map getInterfaceToDaemonMap() {\n return ImmutableMap.copyOf(interfaceToDaemon);\n }\n\n public AddrAndPort daemonToInterface(AddrAndPort daemon) {\n AddrAndPort[] interfaces;\n interfaces = daemonToInterfaces.get(daemon);\n if (interfaces != null) {\n // Below is random. For now we implement round robin instead\n // Round robin\n return interfaces[interfaceIndex.getAndIncrement() % interfaces.length];\n } else {\n return daemon;\n }\n }\n\n public IPAndPort interfaceToDaemon(InetSocketAddress interfaceIPAndPort) {\n return interfaceToDaemon(new IPAndPort(interfaceIPAndPort));\n }\n\n public IPAndPort interfaceToDaemon(IPAndPort interfaceIPAndPort) {\n IPAndPort daemon;\n daemon = interfaceToDaemon.get(interfaceIPAndPort);\n return daemon != null ? daemon : interfaceIPAndPort;\n }\n\n /**\n * For all entries in the daemonToInterfaces argument, update the\n * reverse map. That is, update the interfaceToDaemon map with\n * the corresponding mappings.\n *\n * @param daemonToInterfaces the forward map to reverse\n */\n private void addReverseMappings(Map daemonToInterfaces) {\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n addInterfacesToDaemon(entry.getValue(), entry.getKey());\n }\n }\n\n // only used at startup\n private void addInterfacesToDaemon(IPAndPort[] interfaces, IPAndPort daemon) {\n for (IPAndPort interfaceIPAndPort : interfaces) {\n addInterfaceToDaemon(interfaceIPAndPort, daemon, false);\n addIPToDaemonMapping(interfaceIPAndPort.getIPAsString(), daemon);\n }\n }\n\n // used at runtime to map reverse connections\n public void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort) {\n addInterfaceToDaemon(interfaceIPAndPort, daemonIPAndPort, true);\n }\n\n private void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort, boolean allowRemapping) {\n IPAndPort prev;\n prev = interfaceToDaemon.put(interfaceIPAndPort, daemonIPAndPort);\n if (logInterfaceToDaemonMapping && (prev == null || !prev.equals(daemonIPAndPort))) {\n Log.infof(\"IPAliasMap adding interfaceIPAndPort=>daemonIPAndPort: %s=>%s\", interfaceIPAndPort, daemonIPAndPort);\n }\n if (!allowRemapping && prev != null && !prev.equals(daemonIPAndPort)) {\n throw new RuntimeException(\"Interface maps to multiple daemons: \" + interfaceIPAndPort);\n }\n }\n\n private void addIPToDaemonMapping(String ip, IPAndPort daemonIPAndPort) {\n interfaceIPToDaemons.addValue(ip, daemonIPAndPort);\n }\n\n /**\n * Given an interface ip, randomly select one of the possibly many associated daemons\n *\n * @param ip\n * @return\n */\n public IPAndPort interfaceIPToRandomDaemon(String ip) {\n return interfaceIPToDaemons.getAnyValue(ip);\n }\n\n /**\n * If an interface ip uniquely identifies a daemon ip, return that daemon\n *\n * @param ip\n * @return the uniquely associated daemon\n */\n public IPAndPort interfaceIPToDaemon_ifUnique(String ip) {\n Set daemonIPAndPorts;\n daemonIPAndPorts = interfaceIPToDaemons.getSet(ip);\n if (daemonIPAndPorts == null || daemonIPAndPorts.size() > 1) {\n return null;\n } else {\n return daemonIPAndPorts.iterator().next();\n }\n }\n\n @Override\n public String toString() {\n StringBuffer sb;\n sb = new StringBuffer();\n sb.append(\"{\");\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n sb.append(String.format(\"%s -> [\", entry.getKey()));\n for (IPAndPort _interface : entry.getValue()) {\n sb.append(_interface + \" \");\n }\n sb.append(\"]\\n\");\n }\n sb.append(\"}\");\n return sb.toString() + \"\\n\" + CollectionUtil.mapToString(interfaceToDaemon);\n }\n}\n"} {"task_id": "Java_894", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/morganstanley/SilverKing/src/com/ms/silverking/cloud/dht/net/IPAliasMap.java", "mask_start_position": 10363, "mask_end_position": 10421, "canonical_solution": "\n StringBuffer sb;\n sb = new StringBuffer();", "pre_mask_code": "package com.ms.silverking.cloud.dht.net;\n\nimport java.net.InetSocketAddress;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport com.google.common.collect.ImmutableMap;\nimport com.ms.silverking.collection.CollectionUtil;\nimport com.ms.silverking.collection.HashedSetMap;\nimport com.ms.silverking.log.Log;\nimport com.ms.silverking.net.AddrAndPort;\nimport com.ms.silverking.net.IPAndPort;\n\n/**\n * Background: Under \"normal\" operation, each SK daemon has a fixed port bound to a single IP address. The port\n * is the same for all daemons. This implies that only a single daemon may run per server. It also implies that all\n * traffic will go over a single interface.\n *

\n * IP aliasing allows us to overcome these limitations. IP aliasing does this in two ways:\n * 1) The aliasing feature can be used to allow a daemon to be identified by a \"fake\" IPAndPort. This IPAndPort is\n * used in the topology and almost all of the rest of the code as if it were a real IP. This IPAliasMap class is\n * used by MessageGroupBase (and a few other classes) to translate this IPAndPort into an actual IPAndPort when\n * communication needs to take place. By design, most of the code is unaware of this translation.\n * 2) The aliasing feature allows traffic to be distributed across multiple interfaces. This is done by associating\n * multiple interfaces with an actual IPAndPort. In this case, MessageGroupBase will translate the usual IPAndPort\n * into one of the many remote interfaces in a round-robin fashion.\n *

\n * Terminology: for consistency in the above two cases, this class calls the IP address used to identify a daemon\n * the \"daemon IP\" or \"daemon\" for short. Note that the port is fixed to the SK instance port for this case.\n * Each of the one or more IPAndPorts associated with a daemon IP is called an \"interface IP and port\" or\n * \"interface\" for short. The \"interface IP and port\" are always a real IP and port. The daemon IP is \"fake\"\n * for case 1, but an actual IP for case 2.\n *

\n * For case (1) each daemon IP acts as an alias, and has a single interface IP and port to which it is associated.\n * For case (2) each daemon IP has several interface IPAndPorts with which it is associated.\n *

\n * Colloquially, for case (1) we can call the daemon IP an \"alias\". We don't do that in this code to avoid confusion\n * with case (2) where we could call the interface IP and ports aliases. (The daemon IP is real in this case.)\n *

\n * Notes on case (1) - setting up \"aliases\"/fake IP addresses for each daemon IP.\n * - the topology, host groups, etc, must be composed of these daemon IPs, not interface IPs\n * - the DHT config must have an ipAliasMap field in the form ipAliasMap={daemonIp=interfaceIp:port}\n * As mentioned previously, the vast majority of the code will use this daemon IP as if it were the actual IP.\n * In addition, users will only use the daemon IP.\n *

\n * All translation between daemon IP and interface IP and ports will take place in this class.\n * Clients will select a daemon IP address from the topology as their preferredServer. This is dealiased in\n * DHTSessionImpl to an interface IP and port, to which the client communicates.\n * Aliasing also allows nodes to deviate from the fixed port in DHT config; such nodes would require an alias\n * map entry which maps a fake IP to the port actually in use for a given address. The node itself must be passed\n * -port N on the command line at start up in order to run on a port different to that specified in DHT config.\n * This also allows many nodes to run on the same machine; several daemon IP entries in the maps could exist,\n * which resolve to the same host, but with unique ports. Note that each daemon IP must be unique in this case\n *

\n * It is not required that all nodes have an alias identity, so long as it is consistent between the topology\n * and host group files, and such nodes can be omitted from the alias map. The alias resolution, when it\n * does not find an entry for such a node, would leave the address unchanged and clients/servers would proceed\n * to try and connect directly\n *

\n * Notes on case 2:\n * When aliasing is used to support multi-homing, each daemon IP will be associated with\n * several interface and ports, and the dht config will have an entry of the\n * form: ipAliasMap={daemonIp=interfaceIp:port,...}. Note that all ports must be the same for case 2.\n * The ports may also be omitted.\n */\npublic class IPAliasMap {\n\n // one-to-many\n private final Map daemonToInterfaces;\n\n // many-to-one\n private final Map interfaceToDaemon;\n\n private final HashedSetMap interfaceIPToDaemons;\n\n // used for round-robin between aliases\n private final AtomicInteger interfaceIndex;\n\n // (e.g. for distributing traffic across multi-homed interfaces)\n private static final boolean logDaemonToInterfaceMapping = true;\n\n private static final boolean logInterfaceToDaemonMapping = true;\n\n public IPAliasMap(Map daemonToInterfaces) {\n interfaceToDaemon = new ConcurrentHashMap<>();\n interfaceIPToDaemons = new HashedSetMap<>();\n if (daemonToInterfaces == null) {\n this.daemonToInterfaces = ImmutableMap.of();\n interfaceIndex = null;\n } else {\n sanityCheckMap(daemonToInterfaces);\n this.daemonToInterfaces = new ConcurrentHashMap<>();\n interfaceIndex = new AtomicInteger();\n this.daemonToInterfaces.putAll(daemonToInterfaces);\n if (logDaemonToInterfaceMapping) {\n IPAliasingUtil.logAliasMap(daemonToInterfaces);\n }\n addReverseMappings(daemonToInterfaces);\n }\n }\n\n public static IPAliasMap identityMap() {\n return new IPAliasMap(null);\n }\n\n private void sanityCheckMap(Map daemonToInterfaces) {\n ensureDaemonPortsMatch(daemonToInterfaces);\n }\n\n private void ensureDaemonPortsMatch(Map daemonToInterfaces) {\n int daemonPort;\n daemonPort = -1;\n for (IPAndPort daemonIPAndPort : daemonToInterfaces.keySet()) {\n if (daemonPort < 0) {\n daemonPort = daemonIPAndPort.getPort();\n } else {\n if (daemonIPAndPort.getPort() != daemonPort) {\n throw new RuntimeException(\"IPAliasMap daemon ports must all be the same\");\n }\n }\n }\n }\n\n public Map getDaemonToInterfacesMap() {\n return ImmutableMap.copyOf(daemonToInterfaces);\n }\n\n public Map getInterfaceToDaemonMap() {\n return ImmutableMap.copyOf(interfaceToDaemon);\n }\n\n public AddrAndPort daemonToInterface(AddrAndPort daemon) {\n AddrAndPort[] interfaces;\n interfaces = daemonToInterfaces.get(daemon);\n if (interfaces != null) {\n // Below is random. For now we implement round robin instead\n // Round robin\n return interfaces[interfaceIndex.getAndIncrement() % interfaces.length];\n } else {\n return daemon;\n }\n }\n\n public IPAndPort interfaceToDaemon(InetSocketAddress interfaceIPAndPort) {\n return interfaceToDaemon(new IPAndPort(interfaceIPAndPort));\n }\n\n public IPAndPort interfaceToDaemon(IPAndPort interfaceIPAndPort) {\n IPAndPort daemon;\n daemon = interfaceToDaemon.get(interfaceIPAndPort);\n return daemon != null ? daemon : interfaceIPAndPort;\n }\n\n /**\n * For all entries in the daemonToInterfaces argument, update the\n * reverse map. That is, update the interfaceToDaemon map with\n * the corresponding mappings.\n *\n * @param daemonToInterfaces the forward map to reverse\n */\n private void addReverseMappings(Map daemonToInterfaces) {\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n addInterfacesToDaemon(entry.getValue(), entry.getKey());\n }\n }\n\n // only used at startup\n private void addInterfacesToDaemon(IPAndPort[] interfaces, IPAndPort daemon) {\n for (IPAndPort interfaceIPAndPort : interfaces) {\n addInterfaceToDaemon(interfaceIPAndPort, daemon, false);\n addIPToDaemonMapping(interfaceIPAndPort.getIPAsString(), daemon);\n }\n }\n\n // used at runtime to map reverse connections\n public void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort) {\n addInterfaceToDaemon(interfaceIPAndPort, daemonIPAndPort, true);\n }\n\n private void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort, boolean allowRemapping) {\n IPAndPort prev;\n prev = interfaceToDaemon.put(interfaceIPAndPort, daemonIPAndPort);\n if (logInterfaceToDaemonMapping && (prev == null || !prev.equals(daemonIPAndPort))) {\n Log.infof(\"IPAliasMap adding interfaceIPAndPort=>daemonIPAndPort: %s=>%s\", interfaceIPAndPort, daemonIPAndPort);\n }\n if (!allowRemapping && prev != null && !prev.equals(daemonIPAndPort)) {\n throw new RuntimeException(\"Interface maps to multiple daemons: \" + interfaceIPAndPort);\n }\n }\n\n private void addIPToDaemonMapping(String ip, IPAndPort daemonIPAndPort) {\n interfaceIPToDaemons.addValue(ip, daemonIPAndPort);\n }\n\n /**\n * Given an interface ip, randomly select one of the possibly many associated daemons\n *\n * @param ip\n * @return\n */\n public IPAndPort interfaceIPToRandomDaemon(String ip) {\n return interfaceIPToDaemons.getAnyValue(ip);\n }\n\n /**\n * If an interface ip uniquely identifies a daemon ip, return that daemon\n *\n * @param ip\n * @return the uniquely associated daemon\n */\n public IPAndPort interfaceIPToDaemon_ifUnique(String ip) {\n Set daemonIPAndPorts;\n daemonIPAndPorts = interfaceIPToDaemons.getSet(ip);\n if (daemonIPAndPorts == null || daemonIPAndPorts.size() > 1) {\n return null;\n } else {\n return daemonIPAndPorts.iterator().next();\n }\n }\n\n @Override\n public String toString() {", "post_mask_code": "\n sb.append(\"{\");\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n sb.append(String.format(\"%s -> [\", entry.getKey()));\n for (IPAndPort _interface : entry.getValue()) {\n sb.append(_interface + \" \");\n }\n sb.append(\"]\\n\");\n }\n sb.append(\"}\");\n return sb.toString() + \"\\n\" + CollectionUtil.mapToString(interfaceToDaemon);\n }\n}\n"} {"task_id": "Java_895", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/morganstanley/SilverKing/src/com/ms/silverking/cloud/dht/net/IPAliasMap.java", "mask_start_position": 10430, "mask_end_position": 10757, "canonical_solution": "sb.append(\"{\");\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n sb.append(String.format(\"%s -> [\", entry.getKey()));\n for (IPAndPort _interface : entry.getValue()) {\n sb.append(_interface + \" \");\n }\n sb.append(\"]\\n\");\n }", "pre_mask_code": "package com.ms.silverking.cloud.dht.net;\n\nimport java.net.InetSocketAddress;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport com.google.common.collect.ImmutableMap;\nimport com.ms.silverking.collection.CollectionUtil;\nimport com.ms.silverking.collection.HashedSetMap;\nimport com.ms.silverking.log.Log;\nimport com.ms.silverking.net.AddrAndPort;\nimport com.ms.silverking.net.IPAndPort;\n\n/**\n * Background: Under \"normal\" operation, each SK daemon has a fixed port bound to a single IP address. The port\n * is the same for all daemons. This implies that only a single daemon may run per server. It also implies that all\n * traffic will go over a single interface.\n *

\n * IP aliasing allows us to overcome these limitations. IP aliasing does this in two ways:\n * 1) The aliasing feature can be used to allow a daemon to be identified by a \"fake\" IPAndPort. This IPAndPort is\n * used in the topology and almost all of the rest of the code as if it were a real IP. This IPAliasMap class is\n * used by MessageGroupBase (and a few other classes) to translate this IPAndPort into an actual IPAndPort when\n * communication needs to take place. By design, most of the code is unaware of this translation.\n * 2) The aliasing feature allows traffic to be distributed across multiple interfaces. This is done by associating\n * multiple interfaces with an actual IPAndPort. In this case, MessageGroupBase will translate the usual IPAndPort\n * into one of the many remote interfaces in a round-robin fashion.\n *

\n * Terminology: for consistency in the above two cases, this class calls the IP address used to identify a daemon\n * the \"daemon IP\" or \"daemon\" for short. Note that the port is fixed to the SK instance port for this case.\n * Each of the one or more IPAndPorts associated with a daemon IP is called an \"interface IP and port\" or\n * \"interface\" for short. The \"interface IP and port\" are always a real IP and port. The daemon IP is \"fake\"\n * for case 1, but an actual IP for case 2.\n *

\n * For case (1) each daemon IP acts as an alias, and has a single interface IP and port to which it is associated.\n * For case (2) each daemon IP has several interface IPAndPorts with which it is associated.\n *

\n * Colloquially, for case (1) we can call the daemon IP an \"alias\". We don't do that in this code to avoid confusion\n * with case (2) where we could call the interface IP and ports aliases. (The daemon IP is real in this case.)\n *

\n * Notes on case (1) - setting up \"aliases\"/fake IP addresses for each daemon IP.\n * - the topology, host groups, etc, must be composed of these daemon IPs, not interface IPs\n * - the DHT config must have an ipAliasMap field in the form ipAliasMap={daemonIp=interfaceIp:port}\n * As mentioned previously, the vast majority of the code will use this daemon IP as if it were the actual IP.\n * In addition, users will only use the daemon IP.\n *

\n * All translation between daemon IP and interface IP and ports will take place in this class.\n * Clients will select a daemon IP address from the topology as their preferredServer. This is dealiased in\n * DHTSessionImpl to an interface IP and port, to which the client communicates.\n * Aliasing also allows nodes to deviate from the fixed port in DHT config; such nodes would require an alias\n * map entry which maps a fake IP to the port actually in use for a given address. The node itself must be passed\n * -port N on the command line at start up in order to run on a port different to that specified in DHT config.\n * This also allows many nodes to run on the same machine; several daemon IP entries in the maps could exist,\n * which resolve to the same host, but with unique ports. Note that each daemon IP must be unique in this case\n *

\n * It is not required that all nodes have an alias identity, so long as it is consistent between the topology\n * and host group files, and such nodes can be omitted from the alias map. The alias resolution, when it\n * does not find an entry for such a node, would leave the address unchanged and clients/servers would proceed\n * to try and connect directly\n *

\n * Notes on case 2:\n * When aliasing is used to support multi-homing, each daemon IP will be associated with\n * several interface and ports, and the dht config will have an entry of the\n * form: ipAliasMap={daemonIp=interfaceIp:port,...}. Note that all ports must be the same for case 2.\n * The ports may also be omitted.\n */\npublic class IPAliasMap {\n\n // one-to-many\n private final Map daemonToInterfaces;\n\n // many-to-one\n private final Map interfaceToDaemon;\n\n private final HashedSetMap interfaceIPToDaemons;\n\n // used for round-robin between aliases\n private final AtomicInteger interfaceIndex;\n\n // (e.g. for distributing traffic across multi-homed interfaces)\n private static final boolean logDaemonToInterfaceMapping = true;\n\n private static final boolean logInterfaceToDaemonMapping = true;\n\n public IPAliasMap(Map daemonToInterfaces) {\n interfaceToDaemon = new ConcurrentHashMap<>();\n interfaceIPToDaemons = new HashedSetMap<>();\n if (daemonToInterfaces == null) {\n this.daemonToInterfaces = ImmutableMap.of();\n interfaceIndex = null;\n } else {\n sanityCheckMap(daemonToInterfaces);\n this.daemonToInterfaces = new ConcurrentHashMap<>();\n interfaceIndex = new AtomicInteger();\n this.daemonToInterfaces.putAll(daemonToInterfaces);\n if (logDaemonToInterfaceMapping) {\n IPAliasingUtil.logAliasMap(daemonToInterfaces);\n }\n addReverseMappings(daemonToInterfaces);\n }\n }\n\n public static IPAliasMap identityMap() {\n return new IPAliasMap(null);\n }\n\n private void sanityCheckMap(Map daemonToInterfaces) {\n ensureDaemonPortsMatch(daemonToInterfaces);\n }\n\n private void ensureDaemonPortsMatch(Map daemonToInterfaces) {\n int daemonPort;\n daemonPort = -1;\n for (IPAndPort daemonIPAndPort : daemonToInterfaces.keySet()) {\n if (daemonPort < 0) {\n daemonPort = daemonIPAndPort.getPort();\n } else {\n if (daemonIPAndPort.getPort() != daemonPort) {\n throw new RuntimeException(\"IPAliasMap daemon ports must all be the same\");\n }\n }\n }\n }\n\n public Map getDaemonToInterfacesMap() {\n return ImmutableMap.copyOf(daemonToInterfaces);\n }\n\n public Map getInterfaceToDaemonMap() {\n return ImmutableMap.copyOf(interfaceToDaemon);\n }\n\n public AddrAndPort daemonToInterface(AddrAndPort daemon) {\n AddrAndPort[] interfaces;\n interfaces = daemonToInterfaces.get(daemon);\n if (interfaces != null) {\n // Below is random. For now we implement round robin instead\n // Round robin\n return interfaces[interfaceIndex.getAndIncrement() % interfaces.length];\n } else {\n return daemon;\n }\n }\n\n public IPAndPort interfaceToDaemon(InetSocketAddress interfaceIPAndPort) {\n return interfaceToDaemon(new IPAndPort(interfaceIPAndPort));\n }\n\n public IPAndPort interfaceToDaemon(IPAndPort interfaceIPAndPort) {\n IPAndPort daemon;\n daemon = interfaceToDaemon.get(interfaceIPAndPort);\n return daemon != null ? daemon : interfaceIPAndPort;\n }\n\n /**\n * For all entries in the daemonToInterfaces argument, update the\n * reverse map. That is, update the interfaceToDaemon map with\n * the corresponding mappings.\n *\n * @param daemonToInterfaces the forward map to reverse\n */\n private void addReverseMappings(Map daemonToInterfaces) {\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n addInterfacesToDaemon(entry.getValue(), entry.getKey());\n }\n }\n\n // only used at startup\n private void addInterfacesToDaemon(IPAndPort[] interfaces, IPAndPort daemon) {\n for (IPAndPort interfaceIPAndPort : interfaces) {\n addInterfaceToDaemon(interfaceIPAndPort, daemon, false);\n addIPToDaemonMapping(interfaceIPAndPort.getIPAsString(), daemon);\n }\n }\n\n // used at runtime to map reverse connections\n public void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort) {\n addInterfaceToDaemon(interfaceIPAndPort, daemonIPAndPort, true);\n }\n\n private void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort, boolean allowRemapping) {\n IPAndPort prev;\n prev = interfaceToDaemon.put(interfaceIPAndPort, daemonIPAndPort);\n if (logInterfaceToDaemonMapping && (prev == null || !prev.equals(daemonIPAndPort))) {\n Log.infof(\"IPAliasMap adding interfaceIPAndPort=>daemonIPAndPort: %s=>%s\", interfaceIPAndPort, daemonIPAndPort);\n }\n if (!allowRemapping && prev != null && !prev.equals(daemonIPAndPort)) {\n throw new RuntimeException(\"Interface maps to multiple daemons: \" + interfaceIPAndPort);\n }\n }\n\n private void addIPToDaemonMapping(String ip, IPAndPort daemonIPAndPort) {\n interfaceIPToDaemons.addValue(ip, daemonIPAndPort);\n }\n\n /**\n * Given an interface ip, randomly select one of the possibly many associated daemons\n *\n * @param ip\n * @return\n */\n public IPAndPort interfaceIPToRandomDaemon(String ip) {\n return interfaceIPToDaemons.getAnyValue(ip);\n }\n\n /**\n * If an interface ip uniquely identifies a daemon ip, return that daemon\n *\n * @param ip\n * @return the uniquely associated daemon\n */\n public IPAndPort interfaceIPToDaemon_ifUnique(String ip) {\n Set daemonIPAndPorts;\n daemonIPAndPorts = interfaceIPToDaemons.getSet(ip);\n if (daemonIPAndPorts == null || daemonIPAndPorts.size() > 1) {\n return null;\n } else {\n return daemonIPAndPorts.iterator().next();\n }\n }\n\n @Override\n public String toString() {\n StringBuffer sb;\n sb = new StringBuffer();\n ", "post_mask_code": "\n sb.append(\"}\");\n return sb.toString() + \"\\n\" + CollectionUtil.mapToString(interfaceToDaemon);\n }\n}\n"} {"task_id": "Java_896", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/morganstanley/SilverKing/src/com/ms/silverking/cloud/dht/net/IPAliasMap.java", "mask_start_position": 10766, "mask_end_position": 10872, "canonical_solution": "sb.append(\"}\");\n return sb.toString() + \"\\n\" + CollectionUtil.mapToString(interfaceToDaemon);\n }", "pre_mask_code": "package com.ms.silverking.cloud.dht.net;\n\nimport java.net.InetSocketAddress;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport com.google.common.collect.ImmutableMap;\nimport com.ms.silverking.collection.CollectionUtil;\nimport com.ms.silverking.collection.HashedSetMap;\nimport com.ms.silverking.log.Log;\nimport com.ms.silverking.net.AddrAndPort;\nimport com.ms.silverking.net.IPAndPort;\n\n/**\n * Background: Under \"normal\" operation, each SK daemon has a fixed port bound to a single IP address. The port\n * is the same for all daemons. This implies that only a single daemon may run per server. It also implies that all\n * traffic will go over a single interface.\n *

\n * IP aliasing allows us to overcome these limitations. IP aliasing does this in two ways:\n * 1) The aliasing feature can be used to allow a daemon to be identified by a \"fake\" IPAndPort. This IPAndPort is\n * used in the topology and almost all of the rest of the code as if it were a real IP. This IPAliasMap class is\n * used by MessageGroupBase (and a few other classes) to translate this IPAndPort into an actual IPAndPort when\n * communication needs to take place. By design, most of the code is unaware of this translation.\n * 2) The aliasing feature allows traffic to be distributed across multiple interfaces. This is done by associating\n * multiple interfaces with an actual IPAndPort. In this case, MessageGroupBase will translate the usual IPAndPort\n * into one of the many remote interfaces in a round-robin fashion.\n *

\n * Terminology: for consistency in the above two cases, this class calls the IP address used to identify a daemon\n * the \"daemon IP\" or \"daemon\" for short. Note that the port is fixed to the SK instance port for this case.\n * Each of the one or more IPAndPorts associated with a daemon IP is called an \"interface IP and port\" or\n * \"interface\" for short. The \"interface IP and port\" are always a real IP and port. The daemon IP is \"fake\"\n * for case 1, but an actual IP for case 2.\n *

\n * For case (1) each daemon IP acts as an alias, and has a single interface IP and port to which it is associated.\n * For case (2) each daemon IP has several interface IPAndPorts with which it is associated.\n *

\n * Colloquially, for case (1) we can call the daemon IP an \"alias\". We don't do that in this code to avoid confusion\n * with case (2) where we could call the interface IP and ports aliases. (The daemon IP is real in this case.)\n *

\n * Notes on case (1) - setting up \"aliases\"/fake IP addresses for each daemon IP.\n * - the topology, host groups, etc, must be composed of these daemon IPs, not interface IPs\n * - the DHT config must have an ipAliasMap field in the form ipAliasMap={daemonIp=interfaceIp:port}\n * As mentioned previously, the vast majority of the code will use this daemon IP as if it were the actual IP.\n * In addition, users will only use the daemon IP.\n *

\n * All translation between daemon IP and interface IP and ports will take place in this class.\n * Clients will select a daemon IP address from the topology as their preferredServer. This is dealiased in\n * DHTSessionImpl to an interface IP and port, to which the client communicates.\n * Aliasing also allows nodes to deviate from the fixed port in DHT config; such nodes would require an alias\n * map entry which maps a fake IP to the port actually in use for a given address. The node itself must be passed\n * -port N on the command line at start up in order to run on a port different to that specified in DHT config.\n * This also allows many nodes to run on the same machine; several daemon IP entries in the maps could exist,\n * which resolve to the same host, but with unique ports. Note that each daemon IP must be unique in this case\n *

\n * It is not required that all nodes have an alias identity, so long as it is consistent between the topology\n * and host group files, and such nodes can be omitted from the alias map. The alias resolution, when it\n * does not find an entry for such a node, would leave the address unchanged and clients/servers would proceed\n * to try and connect directly\n *

\n * Notes on case 2:\n * When aliasing is used to support multi-homing, each daemon IP will be associated with\n * several interface and ports, and the dht config will have an entry of the\n * form: ipAliasMap={daemonIp=interfaceIp:port,...}. Note that all ports must be the same for case 2.\n * The ports may also be omitted.\n */\npublic class IPAliasMap {\n\n // one-to-many\n private final Map daemonToInterfaces;\n\n // many-to-one\n private final Map interfaceToDaemon;\n\n private final HashedSetMap interfaceIPToDaemons;\n\n // used for round-robin between aliases\n private final AtomicInteger interfaceIndex;\n\n // (e.g. for distributing traffic across multi-homed interfaces)\n private static final boolean logDaemonToInterfaceMapping = true;\n\n private static final boolean logInterfaceToDaemonMapping = true;\n\n public IPAliasMap(Map daemonToInterfaces) {\n interfaceToDaemon = new ConcurrentHashMap<>();\n interfaceIPToDaemons = new HashedSetMap<>();\n if (daemonToInterfaces == null) {\n this.daemonToInterfaces = ImmutableMap.of();\n interfaceIndex = null;\n } else {\n sanityCheckMap(daemonToInterfaces);\n this.daemonToInterfaces = new ConcurrentHashMap<>();\n interfaceIndex = new AtomicInteger();\n this.daemonToInterfaces.putAll(daemonToInterfaces);\n if (logDaemonToInterfaceMapping) {\n IPAliasingUtil.logAliasMap(daemonToInterfaces);\n }\n addReverseMappings(daemonToInterfaces);\n }\n }\n\n public static IPAliasMap identityMap() {\n return new IPAliasMap(null);\n }\n\n private void sanityCheckMap(Map daemonToInterfaces) {\n ensureDaemonPortsMatch(daemonToInterfaces);\n }\n\n private void ensureDaemonPortsMatch(Map daemonToInterfaces) {\n int daemonPort;\n daemonPort = -1;\n for (IPAndPort daemonIPAndPort : daemonToInterfaces.keySet()) {\n if (daemonPort < 0) {\n daemonPort = daemonIPAndPort.getPort();\n } else {\n if (daemonIPAndPort.getPort() != daemonPort) {\n throw new RuntimeException(\"IPAliasMap daemon ports must all be the same\");\n }\n }\n }\n }\n\n public Map getDaemonToInterfacesMap() {\n return ImmutableMap.copyOf(daemonToInterfaces);\n }\n\n public Map getInterfaceToDaemonMap() {\n return ImmutableMap.copyOf(interfaceToDaemon);\n }\n\n public AddrAndPort daemonToInterface(AddrAndPort daemon) {\n AddrAndPort[] interfaces;\n interfaces = daemonToInterfaces.get(daemon);\n if (interfaces != null) {\n // Below is random. For now we implement round robin instead\n // Round robin\n return interfaces[interfaceIndex.getAndIncrement() % interfaces.length];\n } else {\n return daemon;\n }\n }\n\n public IPAndPort interfaceToDaemon(InetSocketAddress interfaceIPAndPort) {\n return interfaceToDaemon(new IPAndPort(interfaceIPAndPort));\n }\n\n public IPAndPort interfaceToDaemon(IPAndPort interfaceIPAndPort) {\n IPAndPort daemon;\n daemon = interfaceToDaemon.get(interfaceIPAndPort);\n return daemon != null ? daemon : interfaceIPAndPort;\n }\n\n /**\n * For all entries in the daemonToInterfaces argument, update the\n * reverse map. That is, update the interfaceToDaemon map with\n * the corresponding mappings.\n *\n * @param daemonToInterfaces the forward map to reverse\n */\n private void addReverseMappings(Map daemonToInterfaces) {\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n addInterfacesToDaemon(entry.getValue(), entry.getKey());\n }\n }\n\n // only used at startup\n private void addInterfacesToDaemon(IPAndPort[] interfaces, IPAndPort daemon) {\n for (IPAndPort interfaceIPAndPort : interfaces) {\n addInterfaceToDaemon(interfaceIPAndPort, daemon, false);\n addIPToDaemonMapping(interfaceIPAndPort.getIPAsString(), daemon);\n }\n }\n\n // used at runtime to map reverse connections\n public void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort) {\n addInterfaceToDaemon(interfaceIPAndPort, daemonIPAndPort, true);\n }\n\n private void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort, boolean allowRemapping) {\n IPAndPort prev;\n prev = interfaceToDaemon.put(interfaceIPAndPort, daemonIPAndPort);\n if (logInterfaceToDaemonMapping && (prev == null || !prev.equals(daemonIPAndPort))) {\n Log.infof(\"IPAliasMap adding interfaceIPAndPort=>daemonIPAndPort: %s=>%s\", interfaceIPAndPort, daemonIPAndPort);\n }\n if (!allowRemapping && prev != null && !prev.equals(daemonIPAndPort)) {\n throw new RuntimeException(\"Interface maps to multiple daemons: \" + interfaceIPAndPort);\n }\n }\n\n private void addIPToDaemonMapping(String ip, IPAndPort daemonIPAndPort) {\n interfaceIPToDaemons.addValue(ip, daemonIPAndPort);\n }\n\n /**\n * Given an interface ip, randomly select one of the possibly many associated daemons\n *\n * @param ip\n * @return\n */\n public IPAndPort interfaceIPToRandomDaemon(String ip) {\n return interfaceIPToDaemons.getAnyValue(ip);\n }\n\n /**\n * If an interface ip uniquely identifies a daemon ip, return that daemon\n *\n * @param ip\n * @return the uniquely associated daemon\n */\n public IPAndPort interfaceIPToDaemon_ifUnique(String ip) {\n Set daemonIPAndPorts;\n daemonIPAndPorts = interfaceIPToDaemons.getSet(ip);\n if (daemonIPAndPorts == null || daemonIPAndPorts.size() > 1) {\n return null;\n } else {\n return daemonIPAndPorts.iterator().next();\n }\n }\n\n @Override\n public String toString() {\n StringBuffer sb;\n sb = new StringBuffer();\n sb.append(\"{\");\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n sb.append(String.format(\"%s -> [\", entry.getKey()));\n for (IPAndPort _interface : entry.getValue()) {\n sb.append(_interface + \" \");\n }\n sb.append(\"]\\n\");\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_897", "language": "Java", "task_type": "single_line", "source_file": "java/github/morganstanley/SilverKing/src/com/ms/silverking/cloud/dht/net/IPAliasMap.java", "mask_start_position": 6033, "mask_end_position": 6069, "canonical_solution": "aemonPortsMatch(daemonToInterfaces);", "pre_mask_code": "package com.ms.silverking.cloud.dht.net;\n\nimport java.net.InetSocketAddress;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport com.google.common.collect.ImmutableMap;\nimport com.ms.silverking.collection.CollectionUtil;\nimport com.ms.silverking.collection.HashedSetMap;\nimport com.ms.silverking.log.Log;\nimport com.ms.silverking.net.AddrAndPort;\nimport com.ms.silverking.net.IPAndPort;\n\n/**\n * Background: Under \"normal\" operation, each SK daemon has a fixed port bound to a single IP address. The port\n * is the same for all daemons. This implies that only a single daemon may run per server. It also implies that all\n * traffic will go over a single interface.\n *

\n * IP aliasing allows us to overcome these limitations. IP aliasing does this in two ways:\n * 1) The aliasing feature can be used to allow a daemon to be identified by a \"fake\" IPAndPort. This IPAndPort is\n * used in the topology and almost all of the rest of the code as if it were a real IP. This IPAliasMap class is\n * used by MessageGroupBase (and a few other classes) to translate this IPAndPort into an actual IPAndPort when\n * communication needs to take place. By design, most of the code is unaware of this translation.\n * 2) The aliasing feature allows traffic to be distributed across multiple interfaces. This is done by associating\n * multiple interfaces with an actual IPAndPort. In this case, MessageGroupBase will translate the usual IPAndPort\n * into one of the many remote interfaces in a round-robin fashion.\n *

\n * Terminology: for consistency in the above two cases, this class calls the IP address used to identify a daemon\n * the \"daemon IP\" or \"daemon\" for short. Note that the port is fixed to the SK instance port for this case.\n * Each of the one or more IPAndPorts associated with a daemon IP is called an \"interface IP and port\" or\n * \"interface\" for short. The \"interface IP and port\" are always a real IP and port. The daemon IP is \"fake\"\n * for case 1, but an actual IP for case 2.\n *

\n * For case (1) each daemon IP acts as an alias, and has a single interface IP and port to which it is associated.\n * For case (2) each daemon IP has several interface IPAndPorts with which it is associated.\n *

\n * Colloquially, for case (1) we can call the daemon IP an \"alias\". We don't do that in this code to avoid confusion\n * with case (2) where we could call the interface IP and ports aliases. (The daemon IP is real in this case.)\n *

\n * Notes on case (1) - setting up \"aliases\"/fake IP addresses for each daemon IP.\n * - the topology, host groups, etc, must be composed of these daemon IPs, not interface IPs\n * - the DHT config must have an ipAliasMap field in the form ipAliasMap={daemonIp=interfaceIp:port}\n * As mentioned previously, the vast majority of the code will use this daemon IP as if it were the actual IP.\n * In addition, users will only use the daemon IP.\n *

\n * All translation between daemon IP and interface IP and ports will take place in this class.\n * Clients will select a daemon IP address from the topology as their preferredServer. This is dealiased in\n * DHTSessionImpl to an interface IP and port, to which the client communicates.\n * Aliasing also allows nodes to deviate from the fixed port in DHT config; such nodes would require an alias\n * map entry which maps a fake IP to the port actually in use for a given address. The node itself must be passed\n * -port N on the command line at start up in order to run on a port different to that specified in DHT config.\n * This also allows many nodes to run on the same machine; several daemon IP entries in the maps could exist,\n * which resolve to the same host, but with unique ports. Note that each daemon IP must be unique in this case\n *

\n * It is not required that all nodes have an alias identity, so long as it is consistent between the topology\n * and host group files, and such nodes can be omitted from the alias map. The alias resolution, when it\n * does not find an entry for such a node, would leave the address unchanged and clients/servers would proceed\n * to try and connect directly\n *

\n * Notes on case 2:\n * When aliasing is used to support multi-homing, each daemon IP will be associated with\n * several interface and ports, and the dht config will have an entry of the\n * form: ipAliasMap={daemonIp=interfaceIp:port,...}. Note that all ports must be the same for case 2.\n * The ports may also be omitted.\n */\npublic class IPAliasMap {\n\n // one-to-many\n private final Map daemonToInterfaces;\n\n // many-to-one\n private final Map interfaceToDaemon;\n\n private final HashedSetMap interfaceIPToDaemons;\n\n // used for round-robin between aliases\n private final AtomicInteger interfaceIndex;\n\n // (e.g. for distributing traffic across multi-homed interfaces)\n private static final boolean logDaemonToInterfaceMapping = true;\n\n private static final boolean logInterfaceToDaemonMapping = true;\n\n public IPAliasMap(Map daemonToInterfaces) {\n interfaceToDaemon = new ConcurrentHashMap<>();\n interfaceIPToDaemons = new HashedSetMap<>();\n if (daemonToInterfaces == null) {\n this.daemonToInterfaces = ImmutableMap.of();\n interfaceIndex = null;\n } else {\n sanityCheckMap(daemonToInterfaces);\n this.daemonToInterfaces = new ConcurrentHashMap<>();\n interfaceIndex = new AtomicInteger();\n this.daemonToInterfaces.putAll(daemonToInterfaces);\n if (logDaemonToInterfaceMapping) {\n IPAliasingUtil.logAliasMap(daemonToInterfaces);\n }\n addReverseMappings(daemonToInterfaces);\n }\n }\n\n public static IPAliasMap identityMap() {\n return new IPAliasMap(null);\n }\n\n private void sanityCheckMap(Map daemonToInterfaces) {\n ensureD", "post_mask_code": "\n }\n\n private void ensureDaemonPortsMatch(Map daemonToInterfaces) {\n int daemonPort;\n daemonPort = -1;\n for (IPAndPort daemonIPAndPort : daemonToInterfaces.keySet()) {\n if (daemonPort < 0) {\n daemonPort = daemonIPAndPort.getPort();\n } else {\n if (daemonIPAndPort.getPort() != daemonPort) {\n throw new RuntimeException(\"IPAliasMap daemon ports must all be the same\");\n }\n }\n }\n }\n\n public Map getDaemonToInterfacesMap() {\n return ImmutableMap.copyOf(daemonToInterfaces);\n }\n\n public Map getInterfaceToDaemonMap() {\n return ImmutableMap.copyOf(interfaceToDaemon);\n }\n\n public AddrAndPort daemonToInterface(AddrAndPort daemon) {\n AddrAndPort[] interfaces;\n interfaces = daemonToInterfaces.get(daemon);\n if (interfaces != null) {\n // Below is random. For now we implement round robin instead\n // Round robin\n return interfaces[interfaceIndex.getAndIncrement() % interfaces.length];\n } else {\n return daemon;\n }\n }\n\n public IPAndPort interfaceToDaemon(InetSocketAddress interfaceIPAndPort) {\n return interfaceToDaemon(new IPAndPort(interfaceIPAndPort));\n }\n\n public IPAndPort interfaceToDaemon(IPAndPort interfaceIPAndPort) {\n IPAndPort daemon;\n daemon = interfaceToDaemon.get(interfaceIPAndPort);\n return daemon != null ? daemon : interfaceIPAndPort;\n }\n\n /**\n * For all entries in the daemonToInterfaces argument, update the\n * reverse map. That is, update the interfaceToDaemon map with\n * the corresponding mappings.\n *\n * @param daemonToInterfaces the forward map to reverse\n */\n private void addReverseMappings(Map daemonToInterfaces) {\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n addInterfacesToDaemon(entry.getValue(), entry.getKey());\n }\n }\n\n // only used at startup\n private void addInterfacesToDaemon(IPAndPort[] interfaces, IPAndPort daemon) {\n for (IPAndPort interfaceIPAndPort : interfaces) {\n addInterfaceToDaemon(interfaceIPAndPort, daemon, false);\n addIPToDaemonMapping(interfaceIPAndPort.getIPAsString(), daemon);\n }\n }\n\n // used at runtime to map reverse connections\n public void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort) {\n addInterfaceToDaemon(interfaceIPAndPort, daemonIPAndPort, true);\n }\n\n private void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort, boolean allowRemapping) {\n IPAndPort prev;\n prev = interfaceToDaemon.put(interfaceIPAndPort, daemonIPAndPort);\n if (logInterfaceToDaemonMapping && (prev == null || !prev.equals(daemonIPAndPort))) {\n Log.infof(\"IPAliasMap adding interfaceIPAndPort=>daemonIPAndPort: %s=>%s\", interfaceIPAndPort, daemonIPAndPort);\n }\n if (!allowRemapping && prev != null && !prev.equals(daemonIPAndPort)) {\n throw new RuntimeException(\"Interface maps to multiple daemons: \" + interfaceIPAndPort);\n }\n }\n\n private void addIPToDaemonMapping(String ip, IPAndPort daemonIPAndPort) {\n interfaceIPToDaemons.addValue(ip, daemonIPAndPort);\n }\n\n /**\n * Given an interface ip, randomly select one of the possibly many associated daemons\n *\n * @param ip\n * @return\n */\n public IPAndPort interfaceIPToRandomDaemon(String ip) {\n return interfaceIPToDaemons.getAnyValue(ip);\n }\n\n /**\n * If an interface ip uniquely identifies a daemon ip, return that daemon\n *\n * @param ip\n * @return the uniquely associated daemon\n */\n public IPAndPort interfaceIPToDaemon_ifUnique(String ip) {\n Set daemonIPAndPorts;\n daemonIPAndPorts = interfaceIPToDaemons.getSet(ip);\n if (daemonIPAndPorts == null || daemonIPAndPorts.size() > 1) {\n return null;\n } else {\n return daemonIPAndPorts.iterator().next();\n }\n }\n\n @Override\n public String toString() {\n StringBuffer sb;\n sb = new StringBuffer();\n sb.append(\"{\");\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n sb.append(String.format(\"%s -> [\", entry.getKey()));\n for (IPAndPort _interface : entry.getValue()) {\n sb.append(_interface + \" \");\n }\n sb.append(\"]\\n\");\n }\n sb.append(\"}\");\n return sb.toString() + \"\\n\" + CollectionUtil.mapToString(interfaceToDaemon);\n }\n}\n"} {"task_id": "Java_898", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/morganstanley/SilverKing/src/com/ms/silverking/cloud/dht/net/IPAliasMap.java", "mask_start_position": 9974, "mask_end_position": 10317, "canonical_solution": "public IPAndPort interfaceIPToDaemon_ifUnique(String ip) {\n Set daemonIPAndPorts;\n daemonIPAndPorts = interfaceIPToDaemons.getSet(ip);\n if (daemonIPAndPorts == null || daemonIPAndPorts.size() > 1) {\n return null;\n } else {\n return daemonIPAndPorts.iterator().next();\n }\n }", "pre_mask_code": "package com.ms.silverking.cloud.dht.net;\n\nimport java.net.InetSocketAddress;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport com.google.common.collect.ImmutableMap;\nimport com.ms.silverking.collection.CollectionUtil;\nimport com.ms.silverking.collection.HashedSetMap;\nimport com.ms.silverking.log.Log;\nimport com.ms.silverking.net.AddrAndPort;\nimport com.ms.silverking.net.IPAndPort;\n\n/**\n * Background: Under \"normal\" operation, each SK daemon has a fixed port bound to a single IP address. The port\n * is the same for all daemons. This implies that only a single daemon may run per server. It also implies that all\n * traffic will go over a single interface.\n *

\n * IP aliasing allows us to overcome these limitations. IP aliasing does this in two ways:\n * 1) The aliasing feature can be used to allow a daemon to be identified by a \"fake\" IPAndPort. This IPAndPort is\n * used in the topology and almost all of the rest of the code as if it were a real IP. This IPAliasMap class is\n * used by MessageGroupBase (and a few other classes) to translate this IPAndPort into an actual IPAndPort when\n * communication needs to take place. By design, most of the code is unaware of this translation.\n * 2) The aliasing feature allows traffic to be distributed across multiple interfaces. This is done by associating\n * multiple interfaces with an actual IPAndPort. In this case, MessageGroupBase will translate the usual IPAndPort\n * into one of the many remote interfaces in a round-robin fashion.\n *

\n * Terminology: for consistency in the above two cases, this class calls the IP address used to identify a daemon\n * the \"daemon IP\" or \"daemon\" for short. Note that the port is fixed to the SK instance port for this case.\n * Each of the one or more IPAndPorts associated with a daemon IP is called an \"interface IP and port\" or\n * \"interface\" for short. The \"interface IP and port\" are always a real IP and port. The daemon IP is \"fake\"\n * for case 1, but an actual IP for case 2.\n *

\n * For case (1) each daemon IP acts as an alias, and has a single interface IP and port to which it is associated.\n * For case (2) each daemon IP has several interface IPAndPorts with which it is associated.\n *

\n * Colloquially, for case (1) we can call the daemon IP an \"alias\". We don't do that in this code to avoid confusion\n * with case (2) where we could call the interface IP and ports aliases. (The daemon IP is real in this case.)\n *

\n * Notes on case (1) - setting up \"aliases\"/fake IP addresses for each daemon IP.\n * - the topology, host groups, etc, must be composed of these daemon IPs, not interface IPs\n * - the DHT config must have an ipAliasMap field in the form ipAliasMap={daemonIp=interfaceIp:port}\n * As mentioned previously, the vast majority of the code will use this daemon IP as if it were the actual IP.\n * In addition, users will only use the daemon IP.\n *

\n * All translation between daemon IP and interface IP and ports will take place in this class.\n * Clients will select a daemon IP address from the topology as their preferredServer. This is dealiased in\n * DHTSessionImpl to an interface IP and port, to which the client communicates.\n * Aliasing also allows nodes to deviate from the fixed port in DHT config; such nodes would require an alias\n * map entry which maps a fake IP to the port actually in use for a given address. The node itself must be passed\n * -port N on the command line at start up in order to run on a port different to that specified in DHT config.\n * This also allows many nodes to run on the same machine; several daemon IP entries in the maps could exist,\n * which resolve to the same host, but with unique ports. Note that each daemon IP must be unique in this case\n *

\n * It is not required that all nodes have an alias identity, so long as it is consistent between the topology\n * and host group files, and such nodes can be omitted from the alias map. The alias resolution, when it\n * does not find an entry for such a node, would leave the address unchanged and clients/servers would proceed\n * to try and connect directly\n *

\n * Notes on case 2:\n * When aliasing is used to support multi-homing, each daemon IP will be associated with\n * several interface and ports, and the dht config will have an entry of the\n * form: ipAliasMap={daemonIp=interfaceIp:port,...}. Note that all ports must be the same for case 2.\n * The ports may also be omitted.\n */\npublic class IPAliasMap {\n\n // one-to-many\n private final Map daemonToInterfaces;\n\n // many-to-one\n private final Map interfaceToDaemon;\n\n private final HashedSetMap interfaceIPToDaemons;\n\n // used for round-robin between aliases\n private final AtomicInteger interfaceIndex;\n\n // (e.g. for distributing traffic across multi-homed interfaces)\n private static final boolean logDaemonToInterfaceMapping = true;\n\n private static final boolean logInterfaceToDaemonMapping = true;\n\n public IPAliasMap(Map daemonToInterfaces) {\n interfaceToDaemon = new ConcurrentHashMap<>();\n interfaceIPToDaemons = new HashedSetMap<>();\n if (daemonToInterfaces == null) {\n this.daemonToInterfaces = ImmutableMap.of();\n interfaceIndex = null;\n } else {\n sanityCheckMap(daemonToInterfaces);\n this.daemonToInterfaces = new ConcurrentHashMap<>();\n interfaceIndex = new AtomicInteger();\n this.daemonToInterfaces.putAll(daemonToInterfaces);\n if (logDaemonToInterfaceMapping) {\n IPAliasingUtil.logAliasMap(daemonToInterfaces);\n }\n addReverseMappings(daemonToInterfaces);\n }\n }\n\n public static IPAliasMap identityMap() {\n return new IPAliasMap(null);\n }\n\n private void sanityCheckMap(Map daemonToInterfaces) {\n ensureDaemonPortsMatch(daemonToInterfaces);\n }\n\n private void ensureDaemonPortsMatch(Map daemonToInterfaces) {\n int daemonPort;\n daemonPort = -1;\n for (IPAndPort daemonIPAndPort : daemonToInterfaces.keySet()) {\n if (daemonPort < 0) {\n daemonPort = daemonIPAndPort.getPort();\n } else {\n if (daemonIPAndPort.getPort() != daemonPort) {\n throw new RuntimeException(\"IPAliasMap daemon ports must all be the same\");\n }\n }\n }\n }\n\n public Map getDaemonToInterfacesMap() {\n return ImmutableMap.copyOf(daemonToInterfaces);\n }\n\n public Map getInterfaceToDaemonMap() {\n return ImmutableMap.copyOf(interfaceToDaemon);\n }\n\n public AddrAndPort daemonToInterface(AddrAndPort daemon) {\n AddrAndPort[] interfaces;\n interfaces = daemonToInterfaces.get(daemon);\n if (interfaces != null) {\n // Below is random. For now we implement round robin instead\n // Round robin\n return interfaces[interfaceIndex.getAndIncrement() % interfaces.length];\n } else {\n return daemon;\n }\n }\n\n public IPAndPort interfaceToDaemon(InetSocketAddress interfaceIPAndPort) {\n return interfaceToDaemon(new IPAndPort(interfaceIPAndPort));\n }\n\n public IPAndPort interfaceToDaemon(IPAndPort interfaceIPAndPort) {\n IPAndPort daemon;\n daemon = interfaceToDaemon.get(interfaceIPAndPort);\n return daemon != null ? daemon : interfaceIPAndPort;\n }\n\n /**\n * For all entries in the daemonToInterfaces argument, update the\n * reverse map. That is, update the interfaceToDaemon map with\n * the corresponding mappings.\n *\n * @param daemonToInterfaces the forward map to reverse\n */\n private void addReverseMappings(Map daemonToInterfaces) {\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n addInterfacesToDaemon(entry.getValue(), entry.getKey());\n }\n }\n\n // only used at startup\n private void addInterfacesToDaemon(IPAndPort[] interfaces, IPAndPort daemon) {\n for (IPAndPort interfaceIPAndPort : interfaces) {\n addInterfaceToDaemon(interfaceIPAndPort, daemon, false);\n addIPToDaemonMapping(interfaceIPAndPort.getIPAsString(), daemon);\n }\n }\n\n // used at runtime to map reverse connections\n public void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort) {\n addInterfaceToDaemon(interfaceIPAndPort, daemonIPAndPort, true);\n }\n\n private void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort, boolean allowRemapping) {\n IPAndPort prev;\n prev = interfaceToDaemon.put(interfaceIPAndPort, daemonIPAndPort);\n if (logInterfaceToDaemonMapping && (prev == null || !prev.equals(daemonIPAndPort))) {\n Log.infof(\"IPAliasMap adding interfaceIPAndPort=>daemonIPAndPort: %s=>%s\", interfaceIPAndPort, daemonIPAndPort);\n }\n if (!allowRemapping && prev != null && !prev.equals(daemonIPAndPort)) {\n throw new RuntimeException(\"Interface maps to multiple daemons: \" + interfaceIPAndPort);\n }\n }\n\n private void addIPToDaemonMapping(String ip, IPAndPort daemonIPAndPort) {\n interfaceIPToDaemons.addValue(ip, daemonIPAndPort);\n }\n\n /**\n * Given an interface ip, randomly select one of the possibly many associated daemons\n *\n * @param ip\n * @return\n */\n public IPAndPort interfaceIPToRandomDaemon(String ip) {\n return interfaceIPToDaemons.getAnyValue(ip);\n }\n\n /**\n * If an interface ip uniquely identifies a daemon ip, return that daemon\n *\n * @param ip\n * @return the uniquely associated daemon\n */\n ", "post_mask_code": "\n\n @Override\n public String toString() {\n StringBuffer sb;\n sb = new StringBuffer();\n sb.append(\"{\");\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n sb.append(String.format(\"%s -> [\", entry.getKey()));\n for (IPAndPort _interface : entry.getValue()) {\n sb.append(_interface + \" \");\n }\n sb.append(\"]\\n\");\n }\n sb.append(\"}\");\n return sb.toString() + \"\\n\" + CollectionUtil.mapToString(interfaceToDaemon);\n }\n}\n"} {"task_id": "Java_899", "language": "Java", "task_type": "if_statement", "source_file": "java/github/morganstanley/SilverKing/src/com/ms/silverking/cloud/dht/net/IPAliasMap.java", "mask_start_position": 7023, "mask_end_position": 7287, "canonical_solution": "if (interfaces != null) {\n // Below is random. For now we implement round robin instead\n // Round robin\n return interfaces[interfaceIndex.getAndIncrement() % interfaces.length];\n } else {\n return daemon;\n }", "pre_mask_code": "package com.ms.silverking.cloud.dht.net;\n\nimport java.net.InetSocketAddress;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport com.google.common.collect.ImmutableMap;\nimport com.ms.silverking.collection.CollectionUtil;\nimport com.ms.silverking.collection.HashedSetMap;\nimport com.ms.silverking.log.Log;\nimport com.ms.silverking.net.AddrAndPort;\nimport com.ms.silverking.net.IPAndPort;\n\n/**\n * Background: Under \"normal\" operation, each SK daemon has a fixed port bound to a single IP address. The port\n * is the same for all daemons. This implies that only a single daemon may run per server. It also implies that all\n * traffic will go over a single interface.\n *

\n * IP aliasing allows us to overcome these limitations. IP aliasing does this in two ways:\n * 1) The aliasing feature can be used to allow a daemon to be identified by a \"fake\" IPAndPort. This IPAndPort is\n * used in the topology and almost all of the rest of the code as if it were a real IP. This IPAliasMap class is\n * used by MessageGroupBase (and a few other classes) to translate this IPAndPort into an actual IPAndPort when\n * communication needs to take place. By design, most of the code is unaware of this translation.\n * 2) The aliasing feature allows traffic to be distributed across multiple interfaces. This is done by associating\n * multiple interfaces with an actual IPAndPort. In this case, MessageGroupBase will translate the usual IPAndPort\n * into one of the many remote interfaces in a round-robin fashion.\n *

\n * Terminology: for consistency in the above two cases, this class calls the IP address used to identify a daemon\n * the \"daemon IP\" or \"daemon\" for short. Note that the port is fixed to the SK instance port for this case.\n * Each of the one or more IPAndPorts associated with a daemon IP is called an \"interface IP and port\" or\n * \"interface\" for short. The \"interface IP and port\" are always a real IP and port. The daemon IP is \"fake\"\n * for case 1, but an actual IP for case 2.\n *

\n * For case (1) each daemon IP acts as an alias, and has a single interface IP and port to which it is associated.\n * For case (2) each daemon IP has several interface IPAndPorts with which it is associated.\n *

\n * Colloquially, for case (1) we can call the daemon IP an \"alias\". We don't do that in this code to avoid confusion\n * with case (2) where we could call the interface IP and ports aliases. (The daemon IP is real in this case.)\n *

\n * Notes on case (1) - setting up \"aliases\"/fake IP addresses for each daemon IP.\n * - the topology, host groups, etc, must be composed of these daemon IPs, not interface IPs\n * - the DHT config must have an ipAliasMap field in the form ipAliasMap={daemonIp=interfaceIp:port}\n * As mentioned previously, the vast majority of the code will use this daemon IP as if it were the actual IP.\n * In addition, users will only use the daemon IP.\n *

\n * All translation between daemon IP and interface IP and ports will take place in this class.\n * Clients will select a daemon IP address from the topology as their preferredServer. This is dealiased in\n * DHTSessionImpl to an interface IP and port, to which the client communicates.\n * Aliasing also allows nodes to deviate from the fixed port in DHT config; such nodes would require an alias\n * map entry which maps a fake IP to the port actually in use for a given address. The node itself must be passed\n * -port N on the command line at start up in order to run on a port different to that specified in DHT config.\n * This also allows many nodes to run on the same machine; several daemon IP entries in the maps could exist,\n * which resolve to the same host, but with unique ports. Note that each daemon IP must be unique in this case\n *

\n * It is not required that all nodes have an alias identity, so long as it is consistent between the topology\n * and host group files, and such nodes can be omitted from the alias map. The alias resolution, when it\n * does not find an entry for such a node, would leave the address unchanged and clients/servers would proceed\n * to try and connect directly\n *

\n * Notes on case 2:\n * When aliasing is used to support multi-homing, each daemon IP will be associated with\n * several interface and ports, and the dht config will have an entry of the\n * form: ipAliasMap={daemonIp=interfaceIp:port,...}. Note that all ports must be the same for case 2.\n * The ports may also be omitted.\n */\npublic class IPAliasMap {\n\n // one-to-many\n private final Map daemonToInterfaces;\n\n // many-to-one\n private final Map interfaceToDaemon;\n\n private final HashedSetMap interfaceIPToDaemons;\n\n // used for round-robin between aliases\n private final AtomicInteger interfaceIndex;\n\n // (e.g. for distributing traffic across multi-homed interfaces)\n private static final boolean logDaemonToInterfaceMapping = true;\n\n private static final boolean logInterfaceToDaemonMapping = true;\n\n public IPAliasMap(Map daemonToInterfaces) {\n interfaceToDaemon = new ConcurrentHashMap<>();\n interfaceIPToDaemons = new HashedSetMap<>();\n if (daemonToInterfaces == null) {\n this.daemonToInterfaces = ImmutableMap.of();\n interfaceIndex = null;\n } else {\n sanityCheckMap(daemonToInterfaces);\n this.daemonToInterfaces = new ConcurrentHashMap<>();\n interfaceIndex = new AtomicInteger();\n this.daemonToInterfaces.putAll(daemonToInterfaces);\n if (logDaemonToInterfaceMapping) {\n IPAliasingUtil.logAliasMap(daemonToInterfaces);\n }\n addReverseMappings(daemonToInterfaces);\n }\n }\n\n public static IPAliasMap identityMap() {\n return new IPAliasMap(null);\n }\n\n private void sanityCheckMap(Map daemonToInterfaces) {\n ensureDaemonPortsMatch(daemonToInterfaces);\n }\n\n private void ensureDaemonPortsMatch(Map daemonToInterfaces) {\n int daemonPort;\n daemonPort = -1;\n for (IPAndPort daemonIPAndPort : daemonToInterfaces.keySet()) {\n if (daemonPort < 0) {\n daemonPort = daemonIPAndPort.getPort();\n } else {\n if (daemonIPAndPort.getPort() != daemonPort) {\n throw new RuntimeException(\"IPAliasMap daemon ports must all be the same\");\n }\n }\n }\n }\n\n public Map getDaemonToInterfacesMap() {\n return ImmutableMap.copyOf(daemonToInterfaces);\n }\n\n public Map getInterfaceToDaemonMap() {\n return ImmutableMap.copyOf(interfaceToDaemon);\n }\n\n public AddrAndPort daemonToInterface(AddrAndPort daemon) {\n AddrAndPort[] interfaces;\n interfaces = daemonToInterfaces.get(daemon);\n ", "post_mask_code": "\n }\n\n public IPAndPort interfaceToDaemon(InetSocketAddress interfaceIPAndPort) {\n return interfaceToDaemon(new IPAndPort(interfaceIPAndPort));\n }\n\n public IPAndPort interfaceToDaemon(IPAndPort interfaceIPAndPort) {\n IPAndPort daemon;\n daemon = interfaceToDaemon.get(interfaceIPAndPort);\n return daemon != null ? daemon : interfaceIPAndPort;\n }\n\n /**\n * For all entries in the daemonToInterfaces argument, update the\n * reverse map. That is, update the interfaceToDaemon map with\n * the corresponding mappings.\n *\n * @param daemonToInterfaces the forward map to reverse\n */\n private void addReverseMappings(Map daemonToInterfaces) {\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n addInterfacesToDaemon(entry.getValue(), entry.getKey());\n }\n }\n\n // only used at startup\n private void addInterfacesToDaemon(IPAndPort[] interfaces, IPAndPort daemon) {\n for (IPAndPort interfaceIPAndPort : interfaces) {\n addInterfaceToDaemon(interfaceIPAndPort, daemon, false);\n addIPToDaemonMapping(interfaceIPAndPort.getIPAsString(), daemon);\n }\n }\n\n // used at runtime to map reverse connections\n public void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort) {\n addInterfaceToDaemon(interfaceIPAndPort, daemonIPAndPort, true);\n }\n\n private void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort, boolean allowRemapping) {\n IPAndPort prev;\n prev = interfaceToDaemon.put(interfaceIPAndPort, daemonIPAndPort);\n if (logInterfaceToDaemonMapping && (prev == null || !prev.equals(daemonIPAndPort))) {\n Log.infof(\"IPAliasMap adding interfaceIPAndPort=>daemonIPAndPort: %s=>%s\", interfaceIPAndPort, daemonIPAndPort);\n }\n if (!allowRemapping && prev != null && !prev.equals(daemonIPAndPort)) {\n throw new RuntimeException(\"Interface maps to multiple daemons: \" + interfaceIPAndPort);\n }\n }\n\n private void addIPToDaemonMapping(String ip, IPAndPort daemonIPAndPort) {\n interfaceIPToDaemons.addValue(ip, daemonIPAndPort);\n }\n\n /**\n * Given an interface ip, randomly select one of the possibly many associated daemons\n *\n * @param ip\n * @return\n */\n public IPAndPort interfaceIPToRandomDaemon(String ip) {\n return interfaceIPToDaemons.getAnyValue(ip);\n }\n\n /**\n * If an interface ip uniquely identifies a daemon ip, return that daemon\n *\n * @param ip\n * @return the uniquely associated daemon\n */\n public IPAndPort interfaceIPToDaemon_ifUnique(String ip) {\n Set daemonIPAndPorts;\n daemonIPAndPorts = interfaceIPToDaemons.getSet(ip);\n if (daemonIPAndPorts == null || daemonIPAndPorts.size() > 1) {\n return null;\n } else {\n return daemonIPAndPorts.iterator().next();\n }\n }\n\n @Override\n public String toString() {\n StringBuffer sb;\n sb = new StringBuffer();\n sb.append(\"{\");\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n sb.append(String.format(\"%s -> [\", entry.getKey()));\n for (IPAndPort _interface : entry.getValue()) {\n sb.append(_interface + \" \");\n }\n sb.append(\"]\\n\");\n }\n sb.append(\"}\");\n return sb.toString() + \"\\n\" + CollectionUtil.mapToString(interfaceToDaemon);\n }\n}\n"} {"task_id": "Java_900", "language": "Java", "task_type": "empty", "source_file": "java/github/morganstanley/SilverKing/src/com/ms/silverking/cloud/dht/net/IPAliasMap.java", "mask_start_position": 9630, "mask_end_position": 9630, "canonical_solution": "", "pre_mask_code": "package com.ms.silverking.cloud.dht.net;\n\nimport java.net.InetSocketAddress;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport com.google.common.collect.ImmutableMap;\nimport com.ms.silverking.collection.CollectionUtil;\nimport com.ms.silverking.collection.HashedSetMap;\nimport com.ms.silverking.log.Log;\nimport com.ms.silverking.net.AddrAndPort;\nimport com.ms.silverking.net.IPAndPort;\n\n/**\n * Background: Under \"normal\" operation, each SK daemon has a fixed port bound to a single IP address. The port\n * is the same for all daemons. This implies that only a single daemon may run per server. It also implies that all\n * traffic will go over a single interface.\n *

\n * IP aliasing allows us to overcome these limitations. IP aliasing does this in two ways:\n * 1) The aliasing feature can be used to allow a daemon to be identified by a \"fake\" IPAndPort. This IPAndPort is\n * used in the topology and almost all of the rest of the code as if it were a real IP. This IPAliasMap class is\n * used by MessageGroupBase (and a few other classes) to translate this IPAndPort into an actual IPAndPort when\n * communication needs to take place. By design, most of the code is unaware of this translation.\n * 2) The aliasing feature allows traffic to be distributed across multiple interfaces. This is done by associating\n * multiple interfaces with an actual IPAndPort. In this case, MessageGroupBase will translate the usual IPAndPort\n * into one of the many remote interfaces in a round-robin fashion.\n *

\n * Terminology: for consistency in the above two cases, this class calls the IP address used to identify a daemon\n * the \"daemon IP\" or \"daemon\" for short. Note that the port is fixed to the SK instance port for this case.\n * Each of the one or more IPAndPorts associated with a daemon IP is called an \"interface IP and port\" or\n * \"interface\" for short. The \"interface IP and port\" are always a real IP and port. The daemon IP is \"fake\"\n * for case 1, but an actual IP for case 2.\n *

\n * For case (1) each daemon IP acts as an alias, and has a single interface IP and port to which it is associated.\n * For case (2) each daemon IP has several interface IPAndPorts with which it is associated.\n *

\n * Colloquially, for case (1) we can call the daemon IP an \"alias\". We don't do that in this code to avoid confusion\n * with case (2) where we could call the interface IP and ports aliases. (The daemon IP is real in this case.)\n *

\n * Notes on case (1) - setting up \"aliases\"/fake IP addresses for each daemon IP.\n * - the topology, host groups, etc, must be composed of these daemon IPs, not interface IPs\n * - the DHT config must have an ipAliasMap field in the form ipAliasMap={daemonIp=interfaceIp:port}\n * As mentioned previously, the vast majority of the code will use this daemon IP as if it were the actual IP.\n * In addition, users will only use the daemon IP.\n *

\n * All translation between daemon IP and interface IP and ports will take place in this class.\n * Clients will select a daemon IP address from the topology as their preferredServer. This is dealiased in\n * DHTSessionImpl to an interface IP and port, to which the client communicates.\n * Aliasing also allows nodes to deviate from the fixed port in DHT config; such nodes would require an alias\n * map entry which maps a fake IP to the port actually in use for a given address. The node itself must be passed\n * -port N on the command line at start up in order to run on a port different to that specified in DHT config.\n * This also allows many nodes to run on the same machine; several daemon IP entries in the maps could exist,\n * which resolve to the same host, but with unique ports. Note that each daemon IP must be unique in this case\n *

\n * It is not required that all nodes have an alias identity, so long as it is consistent between the topology\n * and host group files, and such nodes can be omitted from the alias map. The alias resolution, when it\n * does not find an entry for such a node, would leave the address unchanged and clients/servers would proceed\n * to try and connect directly\n *

\n * Notes on case 2:\n * When aliasing is used to support multi-homing, each daemon IP will be associated with\n * several interface and ports, and the dht config will have an entry of the\n * form: ipAliasMap={daemonIp=interfaceIp:port,...}. Note that all ports must be the same for case 2.\n * The ports may also be omitted.\n */\npublic class IPAliasMap {\n\n // one-to-many\n private final Map daemonToInterfaces;\n\n // many-to-one\n private final Map interfaceToDaemon;\n\n private final HashedSetMap interfaceIPToDaemons;\n\n // used for round-robin between aliases\n private final AtomicInteger interfaceIndex;\n\n // (e.g. for distributing traffic across multi-homed interfaces)\n private static final boolean logDaemonToInterfaceMapping = true;\n\n private static final boolean logInterfaceToDaemonMapping = true;\n\n public IPAliasMap(Map daemonToInterfaces) {\n interfaceToDaemon = new ConcurrentHashMap<>();\n interfaceIPToDaemons = new HashedSetMap<>();\n if (daemonToInterfaces == null) {\n this.daemonToInterfaces = ImmutableMap.of();\n interfaceIndex = null;\n } else {\n sanityCheckMap(daemonToInterfaces);\n this.daemonToInterfaces = new ConcurrentHashMap<>();\n interfaceIndex = new AtomicInteger();\n this.daemonToInterfaces.putAll(daemonToInterfaces);\n if (logDaemonToInterfaceMapping) {\n IPAliasingUtil.logAliasMap(daemonToInterfaces);\n }\n addReverseMappings(daemonToInterfaces);\n }\n }\n\n public static IPAliasMap identityMap() {\n return new IPAliasMap(null);\n }\n\n private void sanityCheckMap(Map daemonToInterfaces) {\n ensureDaemonPortsMatch(daemonToInterfaces);\n }\n\n private void ensureDaemonPortsMatch(Map daemonToInterfaces) {\n int daemonPort;\n daemonPort = -1;\n for (IPAndPort daemonIPAndPort : daemonToInterfaces.keySet()) {\n if (daemonPort < 0) {\n daemonPort = daemonIPAndPort.getPort();\n } else {\n if (daemonIPAndPort.getPort() != daemonPort) {\n throw new RuntimeException(\"IPAliasMap daemon ports must all be the same\");\n }\n }\n }\n }\n\n public Map getDaemonToInterfacesMap() {\n return ImmutableMap.copyOf(daemonToInterfaces);\n }\n\n public Map getInterfaceToDaemonMap() {\n return ImmutableMap.copyOf(interfaceToDaemon);\n }\n\n public AddrAndPort daemonToInterface(AddrAndPort daemon) {\n AddrAndPort[] interfaces;\n interfaces = daemonToInterfaces.get(daemon);\n if (interfaces != null) {\n // Below is random. For now we implement round robin instead\n // Round robin\n return interfaces[interfaceIndex.getAndIncrement() % interfaces.length];\n } else {\n return daemon;\n }\n }\n\n public IPAndPort interfaceToDaemon(InetSocketAddress interfaceIPAndPort) {\n return interfaceToDaemon(new IPAndPort(interfaceIPAndPort));\n }\n\n public IPAndPort interfaceToDaemon(IPAndPort interfaceIPAndPort) {\n IPAndPort daemon;\n daemon = interfaceToDaemon.get(interfaceIPAndPort);\n return daemon != null ? daemon : interfaceIPAndPort;\n }\n\n /**\n * For all entries in the daemonToInterfaces argument, update the\n * reverse map. That is, update the interfaceToDaemon map with\n * the corresponding mappings.\n *\n * @param daemonToInterfaces the forward map to reverse\n */\n private void addReverseMappings(Map daemonToInterfaces) {\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n addInterfacesToDaemon(entry.getValue(), entry.getKey());\n }\n }\n\n // only used at startup\n private void addInterfacesToDaemon(IPAndPort[] interfaces, IPAndPort daemon) {\n for (IPAndPort interfaceIPAndPort : interfaces) {\n addInterfaceToDaemon(interfaceIPAndPort, daemon, false);\n addIPToDaemonMapping(interfaceIPAndPort.getIPAsString(), daemon);\n }\n }\n\n // used at runtime to map reverse connections\n public void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort) {\n addInterfaceToDaemon(interfaceIPAndPort, daemonIPAndPort, true);\n }\n\n private void addInterfaceToDaemon(IPAndPort interfaceIPAndPort, IPAndPort daemonIPAndPort, boolean allowRemapping) {\n IPAndPort prev;\n prev = interfaceToDaemon.put(interfaceIPAndPort, daemonIPAndPort);\n if (logInterfaceToDaemonMapping && (prev == null || !prev.equals(daemonIPAndPort))) {\n Log.infof(\"IPAliasMap adding interfaceIPAndPort=>daemonIPAndPort: %s=>%s\", interfaceIPAndPort, daemonIPAndPort);\n }\n if (!allowRemapping && prev != null && !prev.equals(daemonIPAndPort)) {\n throw new RuntimeException(\"Interface maps to multiple daemons: \" + interfaceIPAndPort);\n }\n }\n\n private void addIPToDaemonMapping(String ip, IPAndPort daemonIPAndPort) {\n interfaceIPToDaemons.addValue(ip, daemonIPAndPort);\n }\n\n /**\n * Given an interface ip, randomly select one of the possibly many associated", "post_mask_code": " daemons\n *\n * @param ip\n * @return\n */\n public IPAndPort interfaceIPToRandomDaemon(String ip) {\n return interfaceIPToDaemons.getAnyValue(ip);\n }\n\n /**\n * If an interface ip uniquely identifies a daemon ip, return that daemon\n *\n * @param ip\n * @return the uniquely associated daemon\n */\n public IPAndPort interfaceIPToDaemon_ifUnique(String ip) {\n Set daemonIPAndPorts;\n daemonIPAndPorts = interfaceIPToDaemons.getSet(ip);\n if (daemonIPAndPorts == null || daemonIPAndPorts.size() > 1) {\n return null;\n } else {\n return daemonIPAndPorts.iterator().next();\n }\n }\n\n @Override\n public String toString() {\n StringBuffer sb;\n sb = new StringBuffer();\n sb.append(\"{\");\n for (Map.Entry entry : daemonToInterfaces.entrySet()) {\n sb.append(String.format(\"%s -> [\", entry.getKey()));\n for (IPAndPort _interface : entry.getValue()) {\n sb.append(_interface + \" \");\n }\n sb.append(\"]\\n\");\n }\n sb.append(\"}\");\n return sb.toString() + \"\\n\" + CollectionUtil.mapToString(interfaceToDaemon);\n }\n}\n"} {"task_id": "Java_901", "language": "Java", "task_type": "method_signature", "source_file": "java/github/strapdata/elassandra/server/src/main/java/org/elasticsearch/gateway/PrimaryShardAllocator.java", "mask_start_position": 9654, "mask_end_position": 9837, "canonical_solution": "private static List buildNodeDecisions(NodesToAllocate nodesToAllocate, FetchResult fetchedShardData, Set inSyncAllocationIds) ", "pre_mask_code": "package org.elasticsearch.gateway;\n\nimport org.apache.logging.log4j.Logger;\nimport org.apache.logging.log4j.message.ParameterizedMessage;\nimport org.elasticsearch.cluster.metadata.IndexMetaData;\nimport org.elasticsearch.cluster.node.DiscoveryNode;\nimport org.elasticsearch.cluster.routing.RecoverySource;\nimport org.elasticsearch.cluster.routing.RoutingNode;\nimport org.elasticsearch.cluster.routing.RoutingNodes;\nimport org.elasticsearch.cluster.routing.ShardRouting;\nimport org.elasticsearch.cluster.routing.UnassignedInfo.AllocationStatus;\nimport org.elasticsearch.cluster.routing.allocation.AllocateUnassignedDecision;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult.ShardStoreInfo;\nimport org.elasticsearch.cluster.routing.allocation.RoutingAllocation;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision.Type;\nimport org.elasticsearch.env.ShardLockObtainFailedException;\nimport org.elasticsearch.gateway.AsyncShardFetch.FetchResult;\nimport org.elasticsearch.gateway.TransportNodesListGatewayStartedShards.NodeGatewayStartedShards;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\n/**\n * The primary shard allocator allocates unassigned primary shards to nodes that hold\n * valid copies of the unassigned primaries. It does this by iterating over all unassigned\n * primary shards in the routing table and fetching shard metadata from each node in the cluster\n * that holds a copy of the shard. The shard metadata from each node is compared against the\n * set of valid allocation IDs and for all valid shard copies (if any), the primary shard allocator\n * executes the allocation deciders to chose a copy to assign the primary shard to.\n *\n * Note that the PrimaryShardAllocator does *not* allocate primaries on index creation\n * (see {@link org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator}),\n * nor does it allocate primaries when a primary shard failed and there is a valid replica\n * copy that can immediately be promoted to primary, as this takes place in {@link RoutingNodes#failShard}.\n */\npublic abstract class PrimaryShardAllocator extends BaseGatewayShardAllocator {\n\n /**\n * Is the allocator responsible for allocating the given {@link ShardRouting}?\n */\n private static boolean isResponsibleFor(final ShardRouting shard) {\n return // must be primary\n shard.primary() && // must be unassigned\n shard.unassigned() && // only handle either an existing store or a snapshot recovery\n (shard.recoverySource().getType() == RecoverySource.Type.EXISTING_STORE || shard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT);\n }\n\n @Override\n public AllocateUnassignedDecision makeAllocationDecision(final ShardRouting unassignedShard, final RoutingAllocation allocation, final Logger logger) {\n if (isResponsibleFor(unassignedShard) == false) {\n // this allocator is not responsible for allocating this shard\n return AllocateUnassignedDecision.NOT_TAKEN;\n }\n final boolean explain = allocation.debugDecision();\n final FetchResult shardState = fetchData(unassignedShard, allocation);\n if (shardState.hasData() == false) {\n allocation.setHasPendingAsyncFetch();\n List nodeDecisions = null;\n if (explain) {\n nodeDecisions = buildDecisionsForAllNodes(unassignedShard, allocation);\n }\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeDecisions);\n }\n // don't create a new IndexSetting object for every shard as this could cause a lot of garbage\n // on cluster restart if we allocate a boat load of shards\n final IndexMetaData indexMetaData = allocation.metaData().getIndexSafe(unassignedShard.index());\n final Set inSyncAllocationIds = indexMetaData.inSyncAllocationIds(unassignedShard.id());\n final boolean snapshotRestore = unassignedShard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT;\n assert inSyncAllocationIds.isEmpty() == false;\n // use in-sync allocation ids to select nodes\n final NodeShardsResult nodeShardsResult = buildNodeShardsResult(unassignedShard, snapshotRestore, allocation.getIgnoreNodes(unassignedShard.shardId()), inSyncAllocationIds, shardState, logger);\n final boolean enoughAllocationsFound = nodeShardsResult.orderedAllocationCandidates.size() > 0;\n logger.debug(\"[{}][{}]: found {} allocation candidates of {} based on allocation ids: [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.orderedAllocationCandidates.size(), unassignedShard, inSyncAllocationIds);\n if (enoughAllocationsFound == false) {\n if (snapshotRestore) {\n // let BalancedShardsAllocator take care of allocating this shard\n logger.debug(\"[{}][{}]: missing local data, will restore from [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard.recoverySource());\n return AllocateUnassignedDecision.NOT_TAKEN;\n } else {\n // We have a shard that was previously allocated, but we could not find a valid shard copy to allocate the primary.\n // We could just be waiting for the node that holds the primary to start back up, in which case the allocation for\n // this shard will be picked up when the node joins and we do another allocation reroute\n logger.debug(\"[{}][{}]: not allocating, number_of_allocated_shards_found [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.allocationsFound);\n return AllocateUnassignedDecision.no(AllocationStatus.NO_VALID_SHARD_COPY, explain ? buildNodeDecisions(null, shardState, inSyncAllocationIds) : null);\n }\n }\n NodesToAllocate nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, false);\n DiscoveryNode node = null;\n String allocationId = null;\n boolean throttled = false;\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, decidedNode.nodeShardState.getNode());\n node = decidedNode.nodeShardState.getNode();\n allocationId = decidedNode.nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() && !nodesToAllocate.noNodeShards.isEmpty()) {\n // The deciders returned a NO decision for all nodes with shard copies, so we check if primary shard\n // can be force-allocated to one of the nodes.\n nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, true);\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n final DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n final NodeGatewayStartedShards nodeShardState = decidedNode.nodeShardState;\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodeShardState.getNode());\n node = nodeShardState.getNode();\n allocationId = nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() == false) {\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n } else {\n logger.debug(\"[{}][{}]: forced primary allocation denied [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard);\n }\n } else {\n // we are throttling this, since we are allowed to allocate to this node but there are enough allocations\n // taking place on the node currently, ignore it for now\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n }\n List nodeResults = null;\n if (explain) {\n nodeResults = buildNodeDecisions(nodesToAllocate, shardState, inSyncAllocationIds);\n }\n if (allocation.hasPendingAsyncFetch()) {\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeResults);\n } else if (node != null) {\n return AllocateUnassignedDecision.yes(node, allocationId, nodeResults, false);\n } else if (throttled) {\n return AllocateUnassignedDecision.throttle(nodeResults);\n } else {\n return AllocateUnassignedDecision.no(AllocationStatus.DECIDERS_NO, nodeResults, true);\n }\n }\n\n /**\n * Builds a map of nodes to the corresponding allocation decisions for those nodes.\n */\n ", "post_mask_code": "{\n List nodeResults = new ArrayList<>();\n Collection ineligibleShards;\n if (nodesToAllocate != null) {\n final Set discoNodes = new HashSet<>();\n nodeResults.addAll(Stream.of(nodesToAllocate.yesNodeShards, nodesToAllocate.throttleNodeShards, nodesToAllocate.noNodeShards).flatMap(Collection::stream).map(dnode -> {\n discoNodes.add(dnode.nodeShardState.getNode());\n return new NodeAllocationResult(dnode.nodeShardState.getNode(), shardStoreInfo(dnode.nodeShardState, inSyncAllocationIds), dnode.decision);\n }).collect(Collectors.toList()));\n ineligibleShards = fetchedShardData.getData().values().stream().filter(shardData -> discoNodes.contains(shardData.getNode()) == false).collect(Collectors.toList());\n } else {\n // there were no shard copies that were eligible for being assigned the allocation,\n // so all fetched shard data are ineligible shards\n ineligibleShards = fetchedShardData.getData().values();\n }\n nodeResults.addAll(ineligibleShards.stream().map(shardData -> new NodeAllocationResult(shardData.getNode(), shardStoreInfo(shardData, inSyncAllocationIds), null)).collect(Collectors.toList()));\n return nodeResults;\n }\n\n private static ShardStoreInfo shardStoreInfo(NodeGatewayStartedShards nodeShardState, Set inSyncAllocationIds) {\n final Exception storeErr = nodeShardState.storeException();\n final boolean inSync = nodeShardState.allocationId() != null && inSyncAllocationIds.contains(nodeShardState.allocationId());\n return new ShardStoreInfo(nodeShardState.allocationId(), inSync, storeErr);\n }\n\n private static final Comparator NO_STORE_EXCEPTION_FIRST_COMPARATOR = Comparator.comparing((NodeGatewayStartedShards state) -> state.storeException() == null).reversed();\n\n private static final Comparator PRIMARY_FIRST_COMPARATOR = Comparator.comparing(NodeGatewayStartedShards::primary).reversed();\n\n /**\n * Builds a list of nodes. If matchAnyShard is set to false, only nodes that have an allocation id matching\n * inSyncAllocationIds are added to the list. Otherwise, any node that has a shard is added to the list, but\n * entries with matching allocation id are always at the front of the list.\n */\n protected static NodeShardsResult buildNodeShardsResult(ShardRouting shard, boolean matchAnyShard, Set ignoreNodes, Set inSyncAllocationIds, FetchResult shardState, Logger logger) {\n List nodeShardStates = new ArrayList<>();\n int numberOfAllocationsFound = 0;\n for (NodeGatewayStartedShards nodeShardState : shardState.getData().values()) {\n DiscoveryNode node = nodeShardState.getNode();\n String allocationId = nodeShardState.allocationId();\n if (ignoreNodes.contains(node.getId())) {\n continue;\n }\n if (nodeShardState.storeException() == null) {\n if (allocationId == null) {\n logger.trace(\"[{}] on node [{}] has no shard state information\", shard, nodeShardState.getNode());\n } else {\n logger.trace(\"[{}] on node [{}] has allocation id [{}]\", shard, nodeShardState.getNode(), allocationId);\n }\n } else {\n final String finalAllocationId = allocationId;\n if (nodeShardState.storeException() instanceof ShardLockObtainFailedException) {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened as it's locked, treating as valid shard\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n } else {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened, treating as no allocation id\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n allocationId = null;\n }\n }\n if (allocationId != null) {\n assert nodeShardState.storeException() == null || nodeShardState.storeException() instanceof ShardLockObtainFailedException : \"only allow store that can be opened or that throws a ShardLockObtainFailedException while being opened but got a \" + \"store throwing \" + nodeShardState.storeException();\n numberOfAllocationsFound++;\n if (matchAnyShard || inSyncAllocationIds.contains(nodeShardState.allocationId())) {\n nodeShardStates.add(nodeShardState);\n }\n }\n }\n // allocation preference\n final Comparator comparator;\n if (matchAnyShard) {\n // prefer shards with matching allocation ids\n Comparator matchingAllocationsFirst = Comparator.comparing((NodeGatewayStartedShards state) -> inSyncAllocationIds.contains(state.allocationId())).reversed();\n comparator = matchingAllocationsFirst.thenComparing(NO_STORE_EXCEPTION_FIRST_COMPARATOR).thenComparing(PRIMARY_FIRST_COMPARATOR);\n } else {\n comparator = NO_STORE_EXCEPTION_FIRST_COMPARATOR.thenComparing(PRIMARY_FIRST_COMPARATOR);\n }\n nodeShardStates.sort(comparator);\n if (logger.isTraceEnabled()) {\n logger.trace(\"{} candidates for allocation: {}\", shard, nodeShardStates.stream().map(s -> s.getNode().getName()).collect(Collectors.joining(\", \")));\n }\n return new NodeShardsResult(nodeShardStates, numberOfAllocationsFound);\n }\n\n /**\n * Split the list of node shard states into groups yes/no/throttle based on allocation deciders\n */\n private NodesToAllocate buildNodesToAllocate(RoutingAllocation allocation, List nodeShardStates, ShardRouting shardRouting, boolean forceAllocate) {\n List yesNodeShards = new ArrayList<>();\n List throttledNodeShards = new ArrayList<>();\n List noNodeShards = new ArrayList<>();\n for (NodeGatewayStartedShards nodeShardState : nodeShardStates) {\n RoutingNode node = allocation.routingNodes().node(nodeShardState.getNode().getId());\n if (node == null) {\n continue;\n }\n Decision decision = forceAllocate ? allocation.deciders().canForceAllocatePrimary(shardRouting, node, allocation) : allocation.deciders().canAllocate(shardRouting, node, allocation);\n DecidedNode decidedNode = new DecidedNode(nodeShardState, decision);\n if (decision.type() == Type.THROTTLE) {\n throttledNodeShards.add(decidedNode);\n } else if (decision.type() == Type.NO) {\n noNodeShards.add(decidedNode);\n } else {\n yesNodeShards.add(decidedNode);\n }\n }\n return new NodesToAllocate(Collections.unmodifiableList(yesNodeShards), Collections.unmodifiableList(throttledNodeShards), Collections.unmodifiableList(noNodeShards));\n }\n\n protected abstract FetchResult fetchData(ShardRouting shard, RoutingAllocation allocation);\n\n private static class NodeShardsResult {\n\n final List orderedAllocationCandidates;\n\n final int allocationsFound;\n\n NodeShardsResult(List orderedAllocationCandidates, int allocationsFound) {\n this.orderedAllocationCandidates = orderedAllocationCandidates;\n this.allocationsFound = allocationsFound;\n }\n }\n\n static class NodesToAllocate {\n\n final List yesNodeShards;\n\n final List throttleNodeShards;\n\n final List noNodeShards;\n\n NodesToAllocate(List yesNodeShards, List throttleNodeShards, List noNodeShards) {\n this.yesNodeShards = yesNodeShards;\n this.throttleNodeShards = throttleNodeShards;\n this.noNodeShards = noNodeShards;\n }\n }\n\n /**\n * This class encapsulates the shard state retrieved from a node and the decision that was made\n * by the allocator for allocating to the node that holds the shard copy.\n */\n private static class DecidedNode {\n\n final NodeGatewayStartedShards nodeShardState;\n\n final Decision decision;\n\n private DecidedNode(NodeGatewayStartedShards nodeShardState, Decision decision) {\n this.nodeShardState = nodeShardState;\n this.decision = decision;\n }\n }\n}\n"} {"task_id": "Java_902", "language": "Java", "task_type": "method_body", "source_file": "java/github/strapdata/elassandra/server/src/main/java/org/elasticsearch/gateway/PrimaryShardAllocator.java", "mask_start_position": 2676, "mask_end_position": 3009, "canonical_solution": "{\n return // must be primary\n shard.primary() && // must be unassigned\n shard.unassigned() && // only handle either an existing store or a snapshot recovery\n (shard.recoverySource().getType() == RecoverySource.Type.EXISTING_STORE || shard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT);\n }", "pre_mask_code": "package org.elasticsearch.gateway;\n\nimport org.apache.logging.log4j.Logger;\nimport org.apache.logging.log4j.message.ParameterizedMessage;\nimport org.elasticsearch.cluster.metadata.IndexMetaData;\nimport org.elasticsearch.cluster.node.DiscoveryNode;\nimport org.elasticsearch.cluster.routing.RecoverySource;\nimport org.elasticsearch.cluster.routing.RoutingNode;\nimport org.elasticsearch.cluster.routing.RoutingNodes;\nimport org.elasticsearch.cluster.routing.ShardRouting;\nimport org.elasticsearch.cluster.routing.UnassignedInfo.AllocationStatus;\nimport org.elasticsearch.cluster.routing.allocation.AllocateUnassignedDecision;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult.ShardStoreInfo;\nimport org.elasticsearch.cluster.routing.allocation.RoutingAllocation;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision.Type;\nimport org.elasticsearch.env.ShardLockObtainFailedException;\nimport org.elasticsearch.gateway.AsyncShardFetch.FetchResult;\nimport org.elasticsearch.gateway.TransportNodesListGatewayStartedShards.NodeGatewayStartedShards;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\n/**\n * The primary shard allocator allocates unassigned primary shards to nodes that hold\n * valid copies of the unassigned primaries. It does this by iterating over all unassigned\n * primary shards in the routing table and fetching shard metadata from each node in the cluster\n * that holds a copy of the shard. The shard metadata from each node is compared against the\n * set of valid allocation IDs and for all valid shard copies (if any), the primary shard allocator\n * executes the allocation deciders to chose a copy to assign the primary shard to.\n *\n * Note that the PrimaryShardAllocator does *not* allocate primaries on index creation\n * (see {@link org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator}),\n * nor does it allocate primaries when a primary shard failed and there is a valid replica\n * copy that can immediately be promoted to primary, as this takes place in {@link RoutingNodes#failShard}.\n */\npublic abstract class PrimaryShardAllocator extends BaseGatewayShardAllocator {\n\n /**\n * Is the allocator responsible for allocating the given {@link ShardRouting}?\n */\n private static boolean isResponsibleFor(final ShardRouting shard) ", "post_mask_code": "\n\n @Override\n public AllocateUnassignedDecision makeAllocationDecision(final ShardRouting unassignedShard, final RoutingAllocation allocation, final Logger logger) {\n if (isResponsibleFor(unassignedShard) == false) {\n // this allocator is not responsible for allocating this shard\n return AllocateUnassignedDecision.NOT_TAKEN;\n }\n final boolean explain = allocation.debugDecision();\n final FetchResult shardState = fetchData(unassignedShard, allocation);\n if (shardState.hasData() == false) {\n allocation.setHasPendingAsyncFetch();\n List nodeDecisions = null;\n if (explain) {\n nodeDecisions = buildDecisionsForAllNodes(unassignedShard, allocation);\n }\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeDecisions);\n }\n // don't create a new IndexSetting object for every shard as this could cause a lot of garbage\n // on cluster restart if we allocate a boat load of shards\n final IndexMetaData indexMetaData = allocation.metaData().getIndexSafe(unassignedShard.index());\n final Set inSyncAllocationIds = indexMetaData.inSyncAllocationIds(unassignedShard.id());\n final boolean snapshotRestore = unassignedShard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT;\n assert inSyncAllocationIds.isEmpty() == false;\n // use in-sync allocation ids to select nodes\n final NodeShardsResult nodeShardsResult = buildNodeShardsResult(unassignedShard, snapshotRestore, allocation.getIgnoreNodes(unassignedShard.shardId()), inSyncAllocationIds, shardState, logger);\n final boolean enoughAllocationsFound = nodeShardsResult.orderedAllocationCandidates.size() > 0;\n logger.debug(\"[{}][{}]: found {} allocation candidates of {} based on allocation ids: [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.orderedAllocationCandidates.size(), unassignedShard, inSyncAllocationIds);\n if (enoughAllocationsFound == false) {\n if (snapshotRestore) {\n // let BalancedShardsAllocator take care of allocating this shard\n logger.debug(\"[{}][{}]: missing local data, will restore from [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard.recoverySource());\n return AllocateUnassignedDecision.NOT_TAKEN;\n } else {\n // We have a shard that was previously allocated, but we could not find a valid shard copy to allocate the primary.\n // We could just be waiting for the node that holds the primary to start back up, in which case the allocation for\n // this shard will be picked up when the node joins and we do another allocation reroute\n logger.debug(\"[{}][{}]: not allocating, number_of_allocated_shards_found [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.allocationsFound);\n return AllocateUnassignedDecision.no(AllocationStatus.NO_VALID_SHARD_COPY, explain ? buildNodeDecisions(null, shardState, inSyncAllocationIds) : null);\n }\n }\n NodesToAllocate nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, false);\n DiscoveryNode node = null;\n String allocationId = null;\n boolean throttled = false;\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, decidedNode.nodeShardState.getNode());\n node = decidedNode.nodeShardState.getNode();\n allocationId = decidedNode.nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() && !nodesToAllocate.noNodeShards.isEmpty()) {\n // The deciders returned a NO decision for all nodes with shard copies, so we check if primary shard\n // can be force-allocated to one of the nodes.\n nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, true);\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n final DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n final NodeGatewayStartedShards nodeShardState = decidedNode.nodeShardState;\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodeShardState.getNode());\n node = nodeShardState.getNode();\n allocationId = nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() == false) {\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n } else {\n logger.debug(\"[{}][{}]: forced primary allocation denied [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard);\n }\n } else {\n // we are throttling this, since we are allowed to allocate to this node but there are enough allocations\n // taking place on the node currently, ignore it for now\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n }\n List nodeResults = null;\n if (explain) {\n nodeResults = buildNodeDecisions(nodesToAllocate, shardState, inSyncAllocationIds);\n }\n if (allocation.hasPendingAsyncFetch()) {\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeResults);\n } else if (node != null) {\n return AllocateUnassignedDecision.yes(node, allocationId, nodeResults, false);\n } else if (throttled) {\n return AllocateUnassignedDecision.throttle(nodeResults);\n } else {\n return AllocateUnassignedDecision.no(AllocationStatus.DECIDERS_NO, nodeResults, true);\n }\n }\n\n /**\n * Builds a map of nodes to the corresponding allocation decisions for those nodes.\n */\n private static List buildNodeDecisions(NodesToAllocate nodesToAllocate, FetchResult fetchedShardData, Set inSyncAllocationIds) {\n List nodeResults = new ArrayList<>();\n Collection ineligibleShards;\n if (nodesToAllocate != null) {\n final Set discoNodes = new HashSet<>();\n nodeResults.addAll(Stream.of(nodesToAllocate.yesNodeShards, nodesToAllocate.throttleNodeShards, nodesToAllocate.noNodeShards).flatMap(Collection::stream).map(dnode -> {\n discoNodes.add(dnode.nodeShardState.getNode());\n return new NodeAllocationResult(dnode.nodeShardState.getNode(), shardStoreInfo(dnode.nodeShardState, inSyncAllocationIds), dnode.decision);\n }).collect(Collectors.toList()));\n ineligibleShards = fetchedShardData.getData().values().stream().filter(shardData -> discoNodes.contains(shardData.getNode()) == false).collect(Collectors.toList());\n } else {\n // there were no shard copies that were eligible for being assigned the allocation,\n // so all fetched shard data are ineligible shards\n ineligibleShards = fetchedShardData.getData().values();\n }\n nodeResults.addAll(ineligibleShards.stream().map(shardData -> new NodeAllocationResult(shardData.getNode(), shardStoreInfo(shardData, inSyncAllocationIds), null)).collect(Collectors.toList()));\n return nodeResults;\n }\n\n private static ShardStoreInfo shardStoreInfo(NodeGatewayStartedShards nodeShardState, Set inSyncAllocationIds) {\n final Exception storeErr = nodeShardState.storeException();\n final boolean inSync = nodeShardState.allocationId() != null && inSyncAllocationIds.contains(nodeShardState.allocationId());\n return new ShardStoreInfo(nodeShardState.allocationId(), inSync, storeErr);\n }\n\n private static final Comparator NO_STORE_EXCEPTION_FIRST_COMPARATOR = Comparator.comparing((NodeGatewayStartedShards state) -> state.storeException() == null).reversed();\n\n private static final Comparator PRIMARY_FIRST_COMPARATOR = Comparator.comparing(NodeGatewayStartedShards::primary).reversed();\n\n /**\n * Builds a list of nodes. If matchAnyShard is set to false, only nodes that have an allocation id matching\n * inSyncAllocationIds are added to the list. Otherwise, any node that has a shard is added to the list, but\n * entries with matching allocation id are always at the front of the list.\n */\n protected static NodeShardsResult buildNodeShardsResult(ShardRouting shard, boolean matchAnyShard, Set ignoreNodes, Set inSyncAllocationIds, FetchResult shardState, Logger logger) {\n List nodeShardStates = new ArrayList<>();\n int numberOfAllocationsFound = 0;\n for (NodeGatewayStartedShards nodeShardState : shardState.getData().values()) {\n DiscoveryNode node = nodeShardState.getNode();\n String allocationId = nodeShardState.allocationId();\n if (ignoreNodes.contains(node.getId())) {\n continue;\n }\n if (nodeShardState.storeException() == null) {\n if (allocationId == null) {\n logger.trace(\"[{}] on node [{}] has no shard state information\", shard, nodeShardState.getNode());\n } else {\n logger.trace(\"[{}] on node [{}] has allocation id [{}]\", shard, nodeShardState.getNode(), allocationId);\n }\n } else {\n final String finalAllocationId = allocationId;\n if (nodeShardState.storeException() instanceof ShardLockObtainFailedException) {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened as it's locked, treating as valid shard\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n } else {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened, treating as no allocation id\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n allocationId = null;\n }\n }\n if (allocationId != null) {\n assert nodeShardState.storeException() == null || nodeShardState.storeException() instanceof ShardLockObtainFailedException : \"only allow store that can be opened or that throws a ShardLockObtainFailedException while being opened but got a \" + \"store throwing \" + nodeShardState.storeException();\n numberOfAllocationsFound++;\n if (matchAnyShard || inSyncAllocationIds.contains(nodeShardState.allocationId())) {\n nodeShardStates.add(nodeShardState);\n }\n }\n }\n // allocation preference\n final Comparator comparator;\n if (matchAnyShard) {\n // prefer shards with matching allocation ids\n Comparator matchingAllocationsFirst = Comparator.comparing((NodeGatewayStartedShards state) -> inSyncAllocationIds.contains(state.allocationId())).reversed();\n comparator = matchingAllocationsFirst.thenComparing(NO_STORE_EXCEPTION_FIRST_COMPARATOR).thenComparing(PRIMARY_FIRST_COMPARATOR);\n } else {\n comparator = NO_STORE_EXCEPTION_FIRST_COMPARATOR.thenComparing(PRIMARY_FIRST_COMPARATOR);\n }\n nodeShardStates.sort(comparator);\n if (logger.isTraceEnabled()) {\n logger.trace(\"{} candidates for allocation: {}\", shard, nodeShardStates.stream().map(s -> s.getNode().getName()).collect(Collectors.joining(\", \")));\n }\n return new NodeShardsResult(nodeShardStates, numberOfAllocationsFound);\n }\n\n /**\n * Split the list of node shard states into groups yes/no/throttle based on allocation deciders\n */\n private NodesToAllocate buildNodesToAllocate(RoutingAllocation allocation, List nodeShardStates, ShardRouting shardRouting, boolean forceAllocate) {\n List yesNodeShards = new ArrayList<>();\n List throttledNodeShards = new ArrayList<>();\n List noNodeShards = new ArrayList<>();\n for (NodeGatewayStartedShards nodeShardState : nodeShardStates) {\n RoutingNode node = allocation.routingNodes().node(nodeShardState.getNode().getId());\n if (node == null) {\n continue;\n }\n Decision decision = forceAllocate ? allocation.deciders().canForceAllocatePrimary(shardRouting, node, allocation) : allocation.deciders().canAllocate(shardRouting, node, allocation);\n DecidedNode decidedNode = new DecidedNode(nodeShardState, decision);\n if (decision.type() == Type.THROTTLE) {\n throttledNodeShards.add(decidedNode);\n } else if (decision.type() == Type.NO) {\n noNodeShards.add(decidedNode);\n } else {\n yesNodeShards.add(decidedNode);\n }\n }\n return new NodesToAllocate(Collections.unmodifiableList(yesNodeShards), Collections.unmodifiableList(throttledNodeShards), Collections.unmodifiableList(noNodeShards));\n }\n\n protected abstract FetchResult fetchData(ShardRouting shard, RoutingAllocation allocation);\n\n private static class NodeShardsResult {\n\n final List orderedAllocationCandidates;\n\n final int allocationsFound;\n\n NodeShardsResult(List orderedAllocationCandidates, int allocationsFound) {\n this.orderedAllocationCandidates = orderedAllocationCandidates;\n this.allocationsFound = allocationsFound;\n }\n }\n\n static class NodesToAllocate {\n\n final List yesNodeShards;\n\n final List throttleNodeShards;\n\n final List noNodeShards;\n\n NodesToAllocate(List yesNodeShards, List throttleNodeShards, List noNodeShards) {\n this.yesNodeShards = yesNodeShards;\n this.throttleNodeShards = throttleNodeShards;\n this.noNodeShards = noNodeShards;\n }\n }\n\n /**\n * This class encapsulates the shard state retrieved from a node and the decision that was made\n * by the allocator for allocating to the node that holds the shard copy.\n */\n private static class DecidedNode {\n\n final NodeGatewayStartedShards nodeShardState;\n\n final Decision decision;\n\n private DecidedNode(NodeGatewayStartedShards nodeShardState, Decision decision) {\n this.nodeShardState = nodeShardState;\n this.decision = decision;\n }\n }\n}\n"} {"task_id": "Java_903", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/strapdata/elassandra/server/src/main/java/org/elasticsearch/gateway/PrimaryShardAllocator.java", "mask_start_position": 9838, "mask_end_position": 9969, "canonical_solution": "\n List nodeResults = new ArrayList<>();\n Collection ineligibleShards;", "pre_mask_code": "package org.elasticsearch.gateway;\n\nimport org.apache.logging.log4j.Logger;\nimport org.apache.logging.log4j.message.ParameterizedMessage;\nimport org.elasticsearch.cluster.metadata.IndexMetaData;\nimport org.elasticsearch.cluster.node.DiscoveryNode;\nimport org.elasticsearch.cluster.routing.RecoverySource;\nimport org.elasticsearch.cluster.routing.RoutingNode;\nimport org.elasticsearch.cluster.routing.RoutingNodes;\nimport org.elasticsearch.cluster.routing.ShardRouting;\nimport org.elasticsearch.cluster.routing.UnassignedInfo.AllocationStatus;\nimport org.elasticsearch.cluster.routing.allocation.AllocateUnassignedDecision;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult.ShardStoreInfo;\nimport org.elasticsearch.cluster.routing.allocation.RoutingAllocation;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision.Type;\nimport org.elasticsearch.env.ShardLockObtainFailedException;\nimport org.elasticsearch.gateway.AsyncShardFetch.FetchResult;\nimport org.elasticsearch.gateway.TransportNodesListGatewayStartedShards.NodeGatewayStartedShards;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\n/**\n * The primary shard allocator allocates unassigned primary shards to nodes that hold\n * valid copies of the unassigned primaries. It does this by iterating over all unassigned\n * primary shards in the routing table and fetching shard metadata from each node in the cluster\n * that holds a copy of the shard. The shard metadata from each node is compared against the\n * set of valid allocation IDs and for all valid shard copies (if any), the primary shard allocator\n * executes the allocation deciders to chose a copy to assign the primary shard to.\n *\n * Note that the PrimaryShardAllocator does *not* allocate primaries on index creation\n * (see {@link org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator}),\n * nor does it allocate primaries when a primary shard failed and there is a valid replica\n * copy that can immediately be promoted to primary, as this takes place in {@link RoutingNodes#failShard}.\n */\npublic abstract class PrimaryShardAllocator extends BaseGatewayShardAllocator {\n\n /**\n * Is the allocator responsible for allocating the given {@link ShardRouting}?\n */\n private static boolean isResponsibleFor(final ShardRouting shard) {\n return // must be primary\n shard.primary() && // must be unassigned\n shard.unassigned() && // only handle either an existing store or a snapshot recovery\n (shard.recoverySource().getType() == RecoverySource.Type.EXISTING_STORE || shard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT);\n }\n\n @Override\n public AllocateUnassignedDecision makeAllocationDecision(final ShardRouting unassignedShard, final RoutingAllocation allocation, final Logger logger) {\n if (isResponsibleFor(unassignedShard) == false) {\n // this allocator is not responsible for allocating this shard\n return AllocateUnassignedDecision.NOT_TAKEN;\n }\n final boolean explain = allocation.debugDecision();\n final FetchResult shardState = fetchData(unassignedShard, allocation);\n if (shardState.hasData() == false) {\n allocation.setHasPendingAsyncFetch();\n List nodeDecisions = null;\n if (explain) {\n nodeDecisions = buildDecisionsForAllNodes(unassignedShard, allocation);\n }\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeDecisions);\n }\n // don't create a new IndexSetting object for every shard as this could cause a lot of garbage\n // on cluster restart if we allocate a boat load of shards\n final IndexMetaData indexMetaData = allocation.metaData().getIndexSafe(unassignedShard.index());\n final Set inSyncAllocationIds = indexMetaData.inSyncAllocationIds(unassignedShard.id());\n final boolean snapshotRestore = unassignedShard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT;\n assert inSyncAllocationIds.isEmpty() == false;\n // use in-sync allocation ids to select nodes\n final NodeShardsResult nodeShardsResult = buildNodeShardsResult(unassignedShard, snapshotRestore, allocation.getIgnoreNodes(unassignedShard.shardId()), inSyncAllocationIds, shardState, logger);\n final boolean enoughAllocationsFound = nodeShardsResult.orderedAllocationCandidates.size() > 0;\n logger.debug(\"[{}][{}]: found {} allocation candidates of {} based on allocation ids: [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.orderedAllocationCandidates.size(), unassignedShard, inSyncAllocationIds);\n if (enoughAllocationsFound == false) {\n if (snapshotRestore) {\n // let BalancedShardsAllocator take care of allocating this shard\n logger.debug(\"[{}][{}]: missing local data, will restore from [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard.recoverySource());\n return AllocateUnassignedDecision.NOT_TAKEN;\n } else {\n // We have a shard that was previously allocated, but we could not find a valid shard copy to allocate the primary.\n // We could just be waiting for the node that holds the primary to start back up, in which case the allocation for\n // this shard will be picked up when the node joins and we do another allocation reroute\n logger.debug(\"[{}][{}]: not allocating, number_of_allocated_shards_found [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.allocationsFound);\n return AllocateUnassignedDecision.no(AllocationStatus.NO_VALID_SHARD_COPY, explain ? buildNodeDecisions(null, shardState, inSyncAllocationIds) : null);\n }\n }\n NodesToAllocate nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, false);\n DiscoveryNode node = null;\n String allocationId = null;\n boolean throttled = false;\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, decidedNode.nodeShardState.getNode());\n node = decidedNode.nodeShardState.getNode();\n allocationId = decidedNode.nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() && !nodesToAllocate.noNodeShards.isEmpty()) {\n // The deciders returned a NO decision for all nodes with shard copies, so we check if primary shard\n // can be force-allocated to one of the nodes.\n nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, true);\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n final DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n final NodeGatewayStartedShards nodeShardState = decidedNode.nodeShardState;\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodeShardState.getNode());\n node = nodeShardState.getNode();\n allocationId = nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() == false) {\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n } else {\n logger.debug(\"[{}][{}]: forced primary allocation denied [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard);\n }\n } else {\n // we are throttling this, since we are allowed to allocate to this node but there are enough allocations\n // taking place on the node currently, ignore it for now\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n }\n List nodeResults = null;\n if (explain) {\n nodeResults = buildNodeDecisions(nodesToAllocate, shardState, inSyncAllocationIds);\n }\n if (allocation.hasPendingAsyncFetch()) {\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeResults);\n } else if (node != null) {\n return AllocateUnassignedDecision.yes(node, allocationId, nodeResults, false);\n } else if (throttled) {\n return AllocateUnassignedDecision.throttle(nodeResults);\n } else {\n return AllocateUnassignedDecision.no(AllocationStatus.DECIDERS_NO, nodeResults, true);\n }\n }\n\n /**\n * Builds a map of nodes to the corresponding allocation decisions for those nodes.\n */\n private static List buildNodeDecisions(NodesToAllocate nodesToAllocate, FetchResult fetchedShardData, Set inSyncAllocationIds) {", "post_mask_code": "\n if (nodesToAllocate != null) {\n final Set discoNodes = new HashSet<>();\n nodeResults.addAll(Stream.of(nodesToAllocate.yesNodeShards, nodesToAllocate.throttleNodeShards, nodesToAllocate.noNodeShards).flatMap(Collection::stream).map(dnode -> {\n discoNodes.add(dnode.nodeShardState.getNode());\n return new NodeAllocationResult(dnode.nodeShardState.getNode(), shardStoreInfo(dnode.nodeShardState, inSyncAllocationIds), dnode.decision);\n }).collect(Collectors.toList()));\n ineligibleShards = fetchedShardData.getData().values().stream().filter(shardData -> discoNodes.contains(shardData.getNode()) == false).collect(Collectors.toList());\n } else {\n // there were no shard copies that were eligible for being assigned the allocation,\n // so all fetched shard data are ineligible shards\n ineligibleShards = fetchedShardData.getData().values();\n }\n nodeResults.addAll(ineligibleShards.stream().map(shardData -> new NodeAllocationResult(shardData.getNode(), shardStoreInfo(shardData, inSyncAllocationIds), null)).collect(Collectors.toList()));\n return nodeResults;\n }\n\n private static ShardStoreInfo shardStoreInfo(NodeGatewayStartedShards nodeShardState, Set inSyncAllocationIds) {\n final Exception storeErr = nodeShardState.storeException();\n final boolean inSync = nodeShardState.allocationId() != null && inSyncAllocationIds.contains(nodeShardState.allocationId());\n return new ShardStoreInfo(nodeShardState.allocationId(), inSync, storeErr);\n }\n\n private static final Comparator NO_STORE_EXCEPTION_FIRST_COMPARATOR = Comparator.comparing((NodeGatewayStartedShards state) -> state.storeException() == null).reversed();\n\n private static final Comparator PRIMARY_FIRST_COMPARATOR = Comparator.comparing(NodeGatewayStartedShards::primary).reversed();\n\n /**\n * Builds a list of nodes. If matchAnyShard is set to false, only nodes that have an allocation id matching\n * inSyncAllocationIds are added to the list. Otherwise, any node that has a shard is added to the list, but\n * entries with matching allocation id are always at the front of the list.\n */\n protected static NodeShardsResult buildNodeShardsResult(ShardRouting shard, boolean matchAnyShard, Set ignoreNodes, Set inSyncAllocationIds, FetchResult shardState, Logger logger) {\n List nodeShardStates = new ArrayList<>();\n int numberOfAllocationsFound = 0;\n for (NodeGatewayStartedShards nodeShardState : shardState.getData().values()) {\n DiscoveryNode node = nodeShardState.getNode();\n String allocationId = nodeShardState.allocationId();\n if (ignoreNodes.contains(node.getId())) {\n continue;\n }\n if (nodeShardState.storeException() == null) {\n if (allocationId == null) {\n logger.trace(\"[{}] on node [{}] has no shard state information\", shard, nodeShardState.getNode());\n } else {\n logger.trace(\"[{}] on node [{}] has allocation id [{}]\", shard, nodeShardState.getNode(), allocationId);\n }\n } else {\n final String finalAllocationId = allocationId;\n if (nodeShardState.storeException() instanceof ShardLockObtainFailedException) {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened as it's locked, treating as valid shard\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n } else {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened, treating as no allocation id\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n allocationId = null;\n }\n }\n if (allocationId != null) {\n assert nodeShardState.storeException() == null || nodeShardState.storeException() instanceof ShardLockObtainFailedException : \"only allow store that can be opened or that throws a ShardLockObtainFailedException while being opened but got a \" + \"store throwing \" + nodeShardState.storeException();\n numberOfAllocationsFound++;\n if (matchAnyShard || inSyncAllocationIds.contains(nodeShardState.allocationId())) {\n nodeShardStates.add(nodeShardState);\n }\n }\n }\n // allocation preference\n final Comparator comparator;\n if (matchAnyShard) {\n // prefer shards with matching allocation ids\n Comparator matchingAllocationsFirst = Comparator.comparing((NodeGatewayStartedShards state) -> inSyncAllocationIds.contains(state.allocationId())).reversed();\n comparator = matchingAllocationsFirst.thenComparing(NO_STORE_EXCEPTION_FIRST_COMPARATOR).thenComparing(PRIMARY_FIRST_COMPARATOR);\n } else {\n comparator = NO_STORE_EXCEPTION_FIRST_COMPARATOR.thenComparing(PRIMARY_FIRST_COMPARATOR);\n }\n nodeShardStates.sort(comparator);\n if (logger.isTraceEnabled()) {\n logger.trace(\"{} candidates for allocation: {}\", shard, nodeShardStates.stream().map(s -> s.getNode().getName()).collect(Collectors.joining(\", \")));\n }\n return new NodeShardsResult(nodeShardStates, numberOfAllocationsFound);\n }\n\n /**\n * Split the list of node shard states into groups yes/no/throttle based on allocation deciders\n */\n private NodesToAllocate buildNodesToAllocate(RoutingAllocation allocation, List nodeShardStates, ShardRouting shardRouting, boolean forceAllocate) {\n List yesNodeShards = new ArrayList<>();\n List throttledNodeShards = new ArrayList<>();\n List noNodeShards = new ArrayList<>();\n for (NodeGatewayStartedShards nodeShardState : nodeShardStates) {\n RoutingNode node = allocation.routingNodes().node(nodeShardState.getNode().getId());\n if (node == null) {\n continue;\n }\n Decision decision = forceAllocate ? allocation.deciders().canForceAllocatePrimary(shardRouting, node, allocation) : allocation.deciders().canAllocate(shardRouting, node, allocation);\n DecidedNode decidedNode = new DecidedNode(nodeShardState, decision);\n if (decision.type() == Type.THROTTLE) {\n throttledNodeShards.add(decidedNode);\n } else if (decision.type() == Type.NO) {\n noNodeShards.add(decidedNode);\n } else {\n yesNodeShards.add(decidedNode);\n }\n }\n return new NodesToAllocate(Collections.unmodifiableList(yesNodeShards), Collections.unmodifiableList(throttledNodeShards), Collections.unmodifiableList(noNodeShards));\n }\n\n protected abstract FetchResult fetchData(ShardRouting shard, RoutingAllocation allocation);\n\n private static class NodeShardsResult {\n\n final List orderedAllocationCandidates;\n\n final int allocationsFound;\n\n NodeShardsResult(List orderedAllocationCandidates, int allocationsFound) {\n this.orderedAllocationCandidates = orderedAllocationCandidates;\n this.allocationsFound = allocationsFound;\n }\n }\n\n static class NodesToAllocate {\n\n final List yesNodeShards;\n\n final List throttleNodeShards;\n\n final List noNodeShards;\n\n NodesToAllocate(List yesNodeShards, List throttleNodeShards, List noNodeShards) {\n this.yesNodeShards = yesNodeShards;\n this.throttleNodeShards = throttleNodeShards;\n this.noNodeShards = noNodeShards;\n }\n }\n\n /**\n * This class encapsulates the shard state retrieved from a node and the decision that was made\n * by the allocator for allocating to the node that holds the shard copy.\n */\n private static class DecidedNode {\n\n final NodeGatewayStartedShards nodeShardState;\n\n final Decision decision;\n\n private DecidedNode(NodeGatewayStartedShards nodeShardState, Decision decision) {\n this.nodeShardState = nodeShardState;\n this.decision = decision;\n }\n }\n}\n"} {"task_id": "Java_904", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/strapdata/elassandra/server/src/main/java/org/elasticsearch/gateway/PrimaryShardAllocator.java", "mask_start_position": 9978, "mask_end_position": 11155, "canonical_solution": "if (nodesToAllocate != null) {\n final Set discoNodes = new HashSet<>();\n nodeResults.addAll(Stream.of(nodesToAllocate.yesNodeShards, nodesToAllocate.throttleNodeShards, nodesToAllocate.noNodeShards).flatMap(Collection::stream).map(dnode -> {\n discoNodes.add(dnode.nodeShardState.getNode());\n return new NodeAllocationResult(dnode.nodeShardState.getNode(), shardStoreInfo(dnode.nodeShardState, inSyncAllocationIds), dnode.decision);\n }).collect(Collectors.toList()));\n ineligibleShards = fetchedShardData.getData().values().stream().filter(shardData -> discoNodes.contains(shardData.getNode()) == false).collect(Collectors.toList());\n } else {\n // there were no shard copies that were eligible for being assigned the allocation,\n // so all fetched shard data are ineligible shards\n ineligibleShards = fetchedShardData.getData().values();\n }\n nodeResults.addAll(ineligibleShards.stream().map(shardData -> new NodeAllocationResult(shardData.getNode(), shardStoreInfo(shardData, inSyncAllocationIds), null)).collect(Collectors.toList()));", "pre_mask_code": "package org.elasticsearch.gateway;\n\nimport org.apache.logging.log4j.Logger;\nimport org.apache.logging.log4j.message.ParameterizedMessage;\nimport org.elasticsearch.cluster.metadata.IndexMetaData;\nimport org.elasticsearch.cluster.node.DiscoveryNode;\nimport org.elasticsearch.cluster.routing.RecoverySource;\nimport org.elasticsearch.cluster.routing.RoutingNode;\nimport org.elasticsearch.cluster.routing.RoutingNodes;\nimport org.elasticsearch.cluster.routing.ShardRouting;\nimport org.elasticsearch.cluster.routing.UnassignedInfo.AllocationStatus;\nimport org.elasticsearch.cluster.routing.allocation.AllocateUnassignedDecision;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult.ShardStoreInfo;\nimport org.elasticsearch.cluster.routing.allocation.RoutingAllocation;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision.Type;\nimport org.elasticsearch.env.ShardLockObtainFailedException;\nimport org.elasticsearch.gateway.AsyncShardFetch.FetchResult;\nimport org.elasticsearch.gateway.TransportNodesListGatewayStartedShards.NodeGatewayStartedShards;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\n/**\n * The primary shard allocator allocates unassigned primary shards to nodes that hold\n * valid copies of the unassigned primaries. It does this by iterating over all unassigned\n * primary shards in the routing table and fetching shard metadata from each node in the cluster\n * that holds a copy of the shard. The shard metadata from each node is compared against the\n * set of valid allocation IDs and for all valid shard copies (if any), the primary shard allocator\n * executes the allocation deciders to chose a copy to assign the primary shard to.\n *\n * Note that the PrimaryShardAllocator does *not* allocate primaries on index creation\n * (see {@link org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator}),\n * nor does it allocate primaries when a primary shard failed and there is a valid replica\n * copy that can immediately be promoted to primary, as this takes place in {@link RoutingNodes#failShard}.\n */\npublic abstract class PrimaryShardAllocator extends BaseGatewayShardAllocator {\n\n /**\n * Is the allocator responsible for allocating the given {@link ShardRouting}?\n */\n private static boolean isResponsibleFor(final ShardRouting shard) {\n return // must be primary\n shard.primary() && // must be unassigned\n shard.unassigned() && // only handle either an existing store or a snapshot recovery\n (shard.recoverySource().getType() == RecoverySource.Type.EXISTING_STORE || shard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT);\n }\n\n @Override\n public AllocateUnassignedDecision makeAllocationDecision(final ShardRouting unassignedShard, final RoutingAllocation allocation, final Logger logger) {\n if (isResponsibleFor(unassignedShard) == false) {\n // this allocator is not responsible for allocating this shard\n return AllocateUnassignedDecision.NOT_TAKEN;\n }\n final boolean explain = allocation.debugDecision();\n final FetchResult shardState = fetchData(unassignedShard, allocation);\n if (shardState.hasData() == false) {\n allocation.setHasPendingAsyncFetch();\n List nodeDecisions = null;\n if (explain) {\n nodeDecisions = buildDecisionsForAllNodes(unassignedShard, allocation);\n }\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeDecisions);\n }\n // don't create a new IndexSetting object for every shard as this could cause a lot of garbage\n // on cluster restart if we allocate a boat load of shards\n final IndexMetaData indexMetaData = allocation.metaData().getIndexSafe(unassignedShard.index());\n final Set inSyncAllocationIds = indexMetaData.inSyncAllocationIds(unassignedShard.id());\n final boolean snapshotRestore = unassignedShard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT;\n assert inSyncAllocationIds.isEmpty() == false;\n // use in-sync allocation ids to select nodes\n final NodeShardsResult nodeShardsResult = buildNodeShardsResult(unassignedShard, snapshotRestore, allocation.getIgnoreNodes(unassignedShard.shardId()), inSyncAllocationIds, shardState, logger);\n final boolean enoughAllocationsFound = nodeShardsResult.orderedAllocationCandidates.size() > 0;\n logger.debug(\"[{}][{}]: found {} allocation candidates of {} based on allocation ids: [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.orderedAllocationCandidates.size(), unassignedShard, inSyncAllocationIds);\n if (enoughAllocationsFound == false) {\n if (snapshotRestore) {\n // let BalancedShardsAllocator take care of allocating this shard\n logger.debug(\"[{}][{}]: missing local data, will restore from [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard.recoverySource());\n return AllocateUnassignedDecision.NOT_TAKEN;\n } else {\n // We have a shard that was previously allocated, but we could not find a valid shard copy to allocate the primary.\n // We could just be waiting for the node that holds the primary to start back up, in which case the allocation for\n // this shard will be picked up when the node joins and we do another allocation reroute\n logger.debug(\"[{}][{}]: not allocating, number_of_allocated_shards_found [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.allocationsFound);\n return AllocateUnassignedDecision.no(AllocationStatus.NO_VALID_SHARD_COPY, explain ? buildNodeDecisions(null, shardState, inSyncAllocationIds) : null);\n }\n }\n NodesToAllocate nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, false);\n DiscoveryNode node = null;\n String allocationId = null;\n boolean throttled = false;\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, decidedNode.nodeShardState.getNode());\n node = decidedNode.nodeShardState.getNode();\n allocationId = decidedNode.nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() && !nodesToAllocate.noNodeShards.isEmpty()) {\n // The deciders returned a NO decision for all nodes with shard copies, so we check if primary shard\n // can be force-allocated to one of the nodes.\n nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, true);\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n final DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n final NodeGatewayStartedShards nodeShardState = decidedNode.nodeShardState;\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodeShardState.getNode());\n node = nodeShardState.getNode();\n allocationId = nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() == false) {\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n } else {\n logger.debug(\"[{}][{}]: forced primary allocation denied [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard);\n }\n } else {\n // we are throttling this, since we are allowed to allocate to this node but there are enough allocations\n // taking place on the node currently, ignore it for now\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n }\n List nodeResults = null;\n if (explain) {\n nodeResults = buildNodeDecisions(nodesToAllocate, shardState, inSyncAllocationIds);\n }\n if (allocation.hasPendingAsyncFetch()) {\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeResults);\n } else if (node != null) {\n return AllocateUnassignedDecision.yes(node, allocationId, nodeResults, false);\n } else if (throttled) {\n return AllocateUnassignedDecision.throttle(nodeResults);\n } else {\n return AllocateUnassignedDecision.no(AllocationStatus.DECIDERS_NO, nodeResults, true);\n }\n }\n\n /**\n * Builds a map of nodes to the corresponding allocation decisions for those nodes.\n */\n private static List buildNodeDecisions(NodesToAllocate nodesToAllocate, FetchResult fetchedShardData, Set inSyncAllocationIds) {\n List nodeResults = new ArrayList<>();\n Collection ineligibleShards;\n ", "post_mask_code": "\n return nodeResults;\n }\n\n private static ShardStoreInfo shardStoreInfo(NodeGatewayStartedShards nodeShardState, Set inSyncAllocationIds) {\n final Exception storeErr = nodeShardState.storeException();\n final boolean inSync = nodeShardState.allocationId() != null && inSyncAllocationIds.contains(nodeShardState.allocationId());\n return new ShardStoreInfo(nodeShardState.allocationId(), inSync, storeErr);\n }\n\n private static final Comparator NO_STORE_EXCEPTION_FIRST_COMPARATOR = Comparator.comparing((NodeGatewayStartedShards state) -> state.storeException() == null).reversed();\n\n private static final Comparator PRIMARY_FIRST_COMPARATOR = Comparator.comparing(NodeGatewayStartedShards::primary).reversed();\n\n /**\n * Builds a list of nodes. If matchAnyShard is set to false, only nodes that have an allocation id matching\n * inSyncAllocationIds are added to the list. Otherwise, any node that has a shard is added to the list, but\n * entries with matching allocation id are always at the front of the list.\n */\n protected static NodeShardsResult buildNodeShardsResult(ShardRouting shard, boolean matchAnyShard, Set ignoreNodes, Set inSyncAllocationIds, FetchResult shardState, Logger logger) {\n List nodeShardStates = new ArrayList<>();\n int numberOfAllocationsFound = 0;\n for (NodeGatewayStartedShards nodeShardState : shardState.getData().values()) {\n DiscoveryNode node = nodeShardState.getNode();\n String allocationId = nodeShardState.allocationId();\n if (ignoreNodes.contains(node.getId())) {\n continue;\n }\n if (nodeShardState.storeException() == null) {\n if (allocationId == null) {\n logger.trace(\"[{}] on node [{}] has no shard state information\", shard, nodeShardState.getNode());\n } else {\n logger.trace(\"[{}] on node [{}] has allocation id [{}]\", shard, nodeShardState.getNode(), allocationId);\n }\n } else {\n final String finalAllocationId = allocationId;\n if (nodeShardState.storeException() instanceof ShardLockObtainFailedException) {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened as it's locked, treating as valid shard\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n } else {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened, treating as no allocation id\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n allocationId = null;\n }\n }\n if (allocationId != null) {\n assert nodeShardState.storeException() == null || nodeShardState.storeException() instanceof ShardLockObtainFailedException : \"only allow store that can be opened or that throws a ShardLockObtainFailedException while being opened but got a \" + \"store throwing \" + nodeShardState.storeException();\n numberOfAllocationsFound++;\n if (matchAnyShard || inSyncAllocationIds.contains(nodeShardState.allocationId())) {\n nodeShardStates.add(nodeShardState);\n }\n }\n }\n // allocation preference\n final Comparator comparator;\n if (matchAnyShard) {\n // prefer shards with matching allocation ids\n Comparator matchingAllocationsFirst = Comparator.comparing((NodeGatewayStartedShards state) -> inSyncAllocationIds.contains(state.allocationId())).reversed();\n comparator = matchingAllocationsFirst.thenComparing(NO_STORE_EXCEPTION_FIRST_COMPARATOR).thenComparing(PRIMARY_FIRST_COMPARATOR);\n } else {\n comparator = NO_STORE_EXCEPTION_FIRST_COMPARATOR.thenComparing(PRIMARY_FIRST_COMPARATOR);\n }\n nodeShardStates.sort(comparator);\n if (logger.isTraceEnabled()) {\n logger.trace(\"{} candidates for allocation: {}\", shard, nodeShardStates.stream().map(s -> s.getNode().getName()).collect(Collectors.joining(\", \")));\n }\n return new NodeShardsResult(nodeShardStates, numberOfAllocationsFound);\n }\n\n /**\n * Split the list of node shard states into groups yes/no/throttle based on allocation deciders\n */\n private NodesToAllocate buildNodesToAllocate(RoutingAllocation allocation, List nodeShardStates, ShardRouting shardRouting, boolean forceAllocate) {\n List yesNodeShards = new ArrayList<>();\n List throttledNodeShards = new ArrayList<>();\n List noNodeShards = new ArrayList<>();\n for (NodeGatewayStartedShards nodeShardState : nodeShardStates) {\n RoutingNode node = allocation.routingNodes().node(nodeShardState.getNode().getId());\n if (node == null) {\n continue;\n }\n Decision decision = forceAllocate ? allocation.deciders().canForceAllocatePrimary(shardRouting, node, allocation) : allocation.deciders().canAllocate(shardRouting, node, allocation);\n DecidedNode decidedNode = new DecidedNode(nodeShardState, decision);\n if (decision.type() == Type.THROTTLE) {\n throttledNodeShards.add(decidedNode);\n } else if (decision.type() == Type.NO) {\n noNodeShards.add(decidedNode);\n } else {\n yesNodeShards.add(decidedNode);\n }\n }\n return new NodesToAllocate(Collections.unmodifiableList(yesNodeShards), Collections.unmodifiableList(throttledNodeShards), Collections.unmodifiableList(noNodeShards));\n }\n\n protected abstract FetchResult fetchData(ShardRouting shard, RoutingAllocation allocation);\n\n private static class NodeShardsResult {\n\n final List orderedAllocationCandidates;\n\n final int allocationsFound;\n\n NodeShardsResult(List orderedAllocationCandidates, int allocationsFound) {\n this.orderedAllocationCandidates = orderedAllocationCandidates;\n this.allocationsFound = allocationsFound;\n }\n }\n\n static class NodesToAllocate {\n\n final List yesNodeShards;\n\n final List throttleNodeShards;\n\n final List noNodeShards;\n\n NodesToAllocate(List yesNodeShards, List throttleNodeShards, List noNodeShards) {\n this.yesNodeShards = yesNodeShards;\n this.throttleNodeShards = throttleNodeShards;\n this.noNodeShards = noNodeShards;\n }\n }\n\n /**\n * This class encapsulates the shard state retrieved from a node and the decision that was made\n * by the allocator for allocating to the node that holds the shard copy.\n */\n private static class DecidedNode {\n\n final NodeGatewayStartedShards nodeShardState;\n\n final Decision decision;\n\n private DecidedNode(NodeGatewayStartedShards nodeShardState, Decision decision) {\n this.nodeShardState = nodeShardState;\n this.decision = decision;\n }\n }\n}\n"} {"task_id": "Java_905", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/strapdata/elassandra/server/src/main/java/org/elasticsearch/gateway/PrimaryShardAllocator.java", "mask_start_position": 11164, "mask_end_position": 11189, "canonical_solution": "return nodeResults;\n }", "pre_mask_code": "package org.elasticsearch.gateway;\n\nimport org.apache.logging.log4j.Logger;\nimport org.apache.logging.log4j.message.ParameterizedMessage;\nimport org.elasticsearch.cluster.metadata.IndexMetaData;\nimport org.elasticsearch.cluster.node.DiscoveryNode;\nimport org.elasticsearch.cluster.routing.RecoverySource;\nimport org.elasticsearch.cluster.routing.RoutingNode;\nimport org.elasticsearch.cluster.routing.RoutingNodes;\nimport org.elasticsearch.cluster.routing.ShardRouting;\nimport org.elasticsearch.cluster.routing.UnassignedInfo.AllocationStatus;\nimport org.elasticsearch.cluster.routing.allocation.AllocateUnassignedDecision;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult.ShardStoreInfo;\nimport org.elasticsearch.cluster.routing.allocation.RoutingAllocation;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision.Type;\nimport org.elasticsearch.env.ShardLockObtainFailedException;\nimport org.elasticsearch.gateway.AsyncShardFetch.FetchResult;\nimport org.elasticsearch.gateway.TransportNodesListGatewayStartedShards.NodeGatewayStartedShards;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\n/**\n * The primary shard allocator allocates unassigned primary shards to nodes that hold\n * valid copies of the unassigned primaries. It does this by iterating over all unassigned\n * primary shards in the routing table and fetching shard metadata from each node in the cluster\n * that holds a copy of the shard. The shard metadata from each node is compared against the\n * set of valid allocation IDs and for all valid shard copies (if any), the primary shard allocator\n * executes the allocation deciders to chose a copy to assign the primary shard to.\n *\n * Note that the PrimaryShardAllocator does *not* allocate primaries on index creation\n * (see {@link org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator}),\n * nor does it allocate primaries when a primary shard failed and there is a valid replica\n * copy that can immediately be promoted to primary, as this takes place in {@link RoutingNodes#failShard}.\n */\npublic abstract class PrimaryShardAllocator extends BaseGatewayShardAllocator {\n\n /**\n * Is the allocator responsible for allocating the given {@link ShardRouting}?\n */\n private static boolean isResponsibleFor(final ShardRouting shard) {\n return // must be primary\n shard.primary() && // must be unassigned\n shard.unassigned() && // only handle either an existing store or a snapshot recovery\n (shard.recoverySource().getType() == RecoverySource.Type.EXISTING_STORE || shard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT);\n }\n\n @Override\n public AllocateUnassignedDecision makeAllocationDecision(final ShardRouting unassignedShard, final RoutingAllocation allocation, final Logger logger) {\n if (isResponsibleFor(unassignedShard) == false) {\n // this allocator is not responsible for allocating this shard\n return AllocateUnassignedDecision.NOT_TAKEN;\n }\n final boolean explain = allocation.debugDecision();\n final FetchResult shardState = fetchData(unassignedShard, allocation);\n if (shardState.hasData() == false) {\n allocation.setHasPendingAsyncFetch();\n List nodeDecisions = null;\n if (explain) {\n nodeDecisions = buildDecisionsForAllNodes(unassignedShard, allocation);\n }\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeDecisions);\n }\n // don't create a new IndexSetting object for every shard as this could cause a lot of garbage\n // on cluster restart if we allocate a boat load of shards\n final IndexMetaData indexMetaData = allocation.metaData().getIndexSafe(unassignedShard.index());\n final Set inSyncAllocationIds = indexMetaData.inSyncAllocationIds(unassignedShard.id());\n final boolean snapshotRestore = unassignedShard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT;\n assert inSyncAllocationIds.isEmpty() == false;\n // use in-sync allocation ids to select nodes\n final NodeShardsResult nodeShardsResult = buildNodeShardsResult(unassignedShard, snapshotRestore, allocation.getIgnoreNodes(unassignedShard.shardId()), inSyncAllocationIds, shardState, logger);\n final boolean enoughAllocationsFound = nodeShardsResult.orderedAllocationCandidates.size() > 0;\n logger.debug(\"[{}][{}]: found {} allocation candidates of {} based on allocation ids: [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.orderedAllocationCandidates.size(), unassignedShard, inSyncAllocationIds);\n if (enoughAllocationsFound == false) {\n if (snapshotRestore) {\n // let BalancedShardsAllocator take care of allocating this shard\n logger.debug(\"[{}][{}]: missing local data, will restore from [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard.recoverySource());\n return AllocateUnassignedDecision.NOT_TAKEN;\n } else {\n // We have a shard that was previously allocated, but we could not find a valid shard copy to allocate the primary.\n // We could just be waiting for the node that holds the primary to start back up, in which case the allocation for\n // this shard will be picked up when the node joins and we do another allocation reroute\n logger.debug(\"[{}][{}]: not allocating, number_of_allocated_shards_found [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.allocationsFound);\n return AllocateUnassignedDecision.no(AllocationStatus.NO_VALID_SHARD_COPY, explain ? buildNodeDecisions(null, shardState, inSyncAllocationIds) : null);\n }\n }\n NodesToAllocate nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, false);\n DiscoveryNode node = null;\n String allocationId = null;\n boolean throttled = false;\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, decidedNode.nodeShardState.getNode());\n node = decidedNode.nodeShardState.getNode();\n allocationId = decidedNode.nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() && !nodesToAllocate.noNodeShards.isEmpty()) {\n // The deciders returned a NO decision for all nodes with shard copies, so we check if primary shard\n // can be force-allocated to one of the nodes.\n nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, true);\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n final DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n final NodeGatewayStartedShards nodeShardState = decidedNode.nodeShardState;\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodeShardState.getNode());\n node = nodeShardState.getNode();\n allocationId = nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() == false) {\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n } else {\n logger.debug(\"[{}][{}]: forced primary allocation denied [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard);\n }\n } else {\n // we are throttling this, since we are allowed to allocate to this node but there are enough allocations\n // taking place on the node currently, ignore it for now\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n }\n List nodeResults = null;\n if (explain) {\n nodeResults = buildNodeDecisions(nodesToAllocate, shardState, inSyncAllocationIds);\n }\n if (allocation.hasPendingAsyncFetch()) {\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeResults);\n } else if (node != null) {\n return AllocateUnassignedDecision.yes(node, allocationId, nodeResults, false);\n } else if (throttled) {\n return AllocateUnassignedDecision.throttle(nodeResults);\n } else {\n return AllocateUnassignedDecision.no(AllocationStatus.DECIDERS_NO, nodeResults, true);\n }\n }\n\n /**\n * Builds a map of nodes to the corresponding allocation decisions for those nodes.\n */\n private static List buildNodeDecisions(NodesToAllocate nodesToAllocate, FetchResult fetchedShardData, Set inSyncAllocationIds) {\n List nodeResults = new ArrayList<>();\n Collection ineligibleShards;\n if (nodesToAllocate != null) {\n final Set discoNodes = new HashSet<>();\n nodeResults.addAll(Stream.of(nodesToAllocate.yesNodeShards, nodesToAllocate.throttleNodeShards, nodesToAllocate.noNodeShards).flatMap(Collection::stream).map(dnode -> {\n discoNodes.add(dnode.nodeShardState.getNode());\n return new NodeAllocationResult(dnode.nodeShardState.getNode(), shardStoreInfo(dnode.nodeShardState, inSyncAllocationIds), dnode.decision);\n }).collect(Collectors.toList()));\n ineligibleShards = fetchedShardData.getData().values().stream().filter(shardData -> discoNodes.contains(shardData.getNode()) == false).collect(Collectors.toList());\n } else {\n // there were no shard copies that were eligible for being assigned the allocation,\n // so all fetched shard data are ineligible shards\n ineligibleShards = fetchedShardData.getData().values();\n }\n nodeResults.addAll(ineligibleShards.stream().map(shardData -> new NodeAllocationResult(shardData.getNode(), shardStoreInfo(shardData, inSyncAllocationIds), null)).collect(Collectors.toList()));\n ", "post_mask_code": "\n\n private static ShardStoreInfo shardStoreInfo(NodeGatewayStartedShards nodeShardState, Set inSyncAllocationIds) {\n final Exception storeErr = nodeShardState.storeException();\n final boolean inSync = nodeShardState.allocationId() != null && inSyncAllocationIds.contains(nodeShardState.allocationId());\n return new ShardStoreInfo(nodeShardState.allocationId(), inSync, storeErr);\n }\n\n private static final Comparator NO_STORE_EXCEPTION_FIRST_COMPARATOR = Comparator.comparing((NodeGatewayStartedShards state) -> state.storeException() == null).reversed();\n\n private static final Comparator PRIMARY_FIRST_COMPARATOR = Comparator.comparing(NodeGatewayStartedShards::primary).reversed();\n\n /**\n * Builds a list of nodes. If matchAnyShard is set to false, only nodes that have an allocation id matching\n * inSyncAllocationIds are added to the list. Otherwise, any node that has a shard is added to the list, but\n * entries with matching allocation id are always at the front of the list.\n */\n protected static NodeShardsResult buildNodeShardsResult(ShardRouting shard, boolean matchAnyShard, Set ignoreNodes, Set inSyncAllocationIds, FetchResult shardState, Logger logger) {\n List nodeShardStates = new ArrayList<>();\n int numberOfAllocationsFound = 0;\n for (NodeGatewayStartedShards nodeShardState : shardState.getData().values()) {\n DiscoveryNode node = nodeShardState.getNode();\n String allocationId = nodeShardState.allocationId();\n if (ignoreNodes.contains(node.getId())) {\n continue;\n }\n if (nodeShardState.storeException() == null) {\n if (allocationId == null) {\n logger.trace(\"[{}] on node [{}] has no shard state information\", shard, nodeShardState.getNode());\n } else {\n logger.trace(\"[{}] on node [{}] has allocation id [{}]\", shard, nodeShardState.getNode(), allocationId);\n }\n } else {\n final String finalAllocationId = allocationId;\n if (nodeShardState.storeException() instanceof ShardLockObtainFailedException) {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened as it's locked, treating as valid shard\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n } else {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened, treating as no allocation id\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n allocationId = null;\n }\n }\n if (allocationId != null) {\n assert nodeShardState.storeException() == null || nodeShardState.storeException() instanceof ShardLockObtainFailedException : \"only allow store that can be opened or that throws a ShardLockObtainFailedException while being opened but got a \" + \"store throwing \" + nodeShardState.storeException();\n numberOfAllocationsFound++;\n if (matchAnyShard || inSyncAllocationIds.contains(nodeShardState.allocationId())) {\n nodeShardStates.add(nodeShardState);\n }\n }\n }\n // allocation preference\n final Comparator comparator;\n if (matchAnyShard) {\n // prefer shards with matching allocation ids\n Comparator matchingAllocationsFirst = Comparator.comparing((NodeGatewayStartedShards state) -> inSyncAllocationIds.contains(state.allocationId())).reversed();\n comparator = matchingAllocationsFirst.thenComparing(NO_STORE_EXCEPTION_FIRST_COMPARATOR).thenComparing(PRIMARY_FIRST_COMPARATOR);\n } else {\n comparator = NO_STORE_EXCEPTION_FIRST_COMPARATOR.thenComparing(PRIMARY_FIRST_COMPARATOR);\n }\n nodeShardStates.sort(comparator);\n if (logger.isTraceEnabled()) {\n logger.trace(\"{} candidates for allocation: {}\", shard, nodeShardStates.stream().map(s -> s.getNode().getName()).collect(Collectors.joining(\", \")));\n }\n return new NodeShardsResult(nodeShardStates, numberOfAllocationsFound);\n }\n\n /**\n * Split the list of node shard states into groups yes/no/throttle based on allocation deciders\n */\n private NodesToAllocate buildNodesToAllocate(RoutingAllocation allocation, List nodeShardStates, ShardRouting shardRouting, boolean forceAllocate) {\n List yesNodeShards = new ArrayList<>();\n List throttledNodeShards = new ArrayList<>();\n List noNodeShards = new ArrayList<>();\n for (NodeGatewayStartedShards nodeShardState : nodeShardStates) {\n RoutingNode node = allocation.routingNodes().node(nodeShardState.getNode().getId());\n if (node == null) {\n continue;\n }\n Decision decision = forceAllocate ? allocation.deciders().canForceAllocatePrimary(shardRouting, node, allocation) : allocation.deciders().canAllocate(shardRouting, node, allocation);\n DecidedNode decidedNode = new DecidedNode(nodeShardState, decision);\n if (decision.type() == Type.THROTTLE) {\n throttledNodeShards.add(decidedNode);\n } else if (decision.type() == Type.NO) {\n noNodeShards.add(decidedNode);\n } else {\n yesNodeShards.add(decidedNode);\n }\n }\n return new NodesToAllocate(Collections.unmodifiableList(yesNodeShards), Collections.unmodifiableList(throttledNodeShards), Collections.unmodifiableList(noNodeShards));\n }\n\n protected abstract FetchResult fetchData(ShardRouting shard, RoutingAllocation allocation);\n\n private static class NodeShardsResult {\n\n final List orderedAllocationCandidates;\n\n final int allocationsFound;\n\n NodeShardsResult(List orderedAllocationCandidates, int allocationsFound) {\n this.orderedAllocationCandidates = orderedAllocationCandidates;\n this.allocationsFound = allocationsFound;\n }\n }\n\n static class NodesToAllocate {\n\n final List yesNodeShards;\n\n final List throttleNodeShards;\n\n final List noNodeShards;\n\n NodesToAllocate(List yesNodeShards, List throttleNodeShards, List noNodeShards) {\n this.yesNodeShards = yesNodeShards;\n this.throttleNodeShards = throttleNodeShards;\n this.noNodeShards = noNodeShards;\n }\n }\n\n /**\n * This class encapsulates the shard state retrieved from a node and the decision that was made\n * by the allocator for allocating to the node that holds the shard copy.\n */\n private static class DecidedNode {\n\n final NodeGatewayStartedShards nodeShardState;\n\n final Decision decision;\n\n private DecidedNode(NodeGatewayStartedShards nodeShardState, Decision decision) {\n this.nodeShardState = nodeShardState;\n this.decision = decision;\n }\n }\n}\n"} {"task_id": "Java_906", "language": "Java", "task_type": "single_line", "source_file": "java/github/strapdata/elassandra/server/src/main/java/org/elasticsearch/gateway/PrimaryShardAllocator.java", "mask_start_position": 8892, "mask_end_position": 8906, "canonical_solution": "esults = null;", "pre_mask_code": "package org.elasticsearch.gateway;\n\nimport org.apache.logging.log4j.Logger;\nimport org.apache.logging.log4j.message.ParameterizedMessage;\nimport org.elasticsearch.cluster.metadata.IndexMetaData;\nimport org.elasticsearch.cluster.node.DiscoveryNode;\nimport org.elasticsearch.cluster.routing.RecoverySource;\nimport org.elasticsearch.cluster.routing.RoutingNode;\nimport org.elasticsearch.cluster.routing.RoutingNodes;\nimport org.elasticsearch.cluster.routing.ShardRouting;\nimport org.elasticsearch.cluster.routing.UnassignedInfo.AllocationStatus;\nimport org.elasticsearch.cluster.routing.allocation.AllocateUnassignedDecision;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult.ShardStoreInfo;\nimport org.elasticsearch.cluster.routing.allocation.RoutingAllocation;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision.Type;\nimport org.elasticsearch.env.ShardLockObtainFailedException;\nimport org.elasticsearch.gateway.AsyncShardFetch.FetchResult;\nimport org.elasticsearch.gateway.TransportNodesListGatewayStartedShards.NodeGatewayStartedShards;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\n/**\n * The primary shard allocator allocates unassigned primary shards to nodes that hold\n * valid copies of the unassigned primaries. It does this by iterating over all unassigned\n * primary shards in the routing table and fetching shard metadata from each node in the cluster\n * that holds a copy of the shard. The shard metadata from each node is compared against the\n * set of valid allocation IDs and for all valid shard copies (if any), the primary shard allocator\n * executes the allocation deciders to chose a copy to assign the primary shard to.\n *\n * Note that the PrimaryShardAllocator does *not* allocate primaries on index creation\n * (see {@link org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator}),\n * nor does it allocate primaries when a primary shard failed and there is a valid replica\n * copy that can immediately be promoted to primary, as this takes place in {@link RoutingNodes#failShard}.\n */\npublic abstract class PrimaryShardAllocator extends BaseGatewayShardAllocator {\n\n /**\n * Is the allocator responsible for allocating the given {@link ShardRouting}?\n */\n private static boolean isResponsibleFor(final ShardRouting shard) {\n return // must be primary\n shard.primary() && // must be unassigned\n shard.unassigned() && // only handle either an existing store or a snapshot recovery\n (shard.recoverySource().getType() == RecoverySource.Type.EXISTING_STORE || shard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT);\n }\n\n @Override\n public AllocateUnassignedDecision makeAllocationDecision(final ShardRouting unassignedShard, final RoutingAllocation allocation, final Logger logger) {\n if (isResponsibleFor(unassignedShard) == false) {\n // this allocator is not responsible for allocating this shard\n return AllocateUnassignedDecision.NOT_TAKEN;\n }\n final boolean explain = allocation.debugDecision();\n final FetchResult shardState = fetchData(unassignedShard, allocation);\n if (shardState.hasData() == false) {\n allocation.setHasPendingAsyncFetch();\n List nodeDecisions = null;\n if (explain) {\n nodeDecisions = buildDecisionsForAllNodes(unassignedShard, allocation);\n }\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeDecisions);\n }\n // don't create a new IndexSetting object for every shard as this could cause a lot of garbage\n // on cluster restart if we allocate a boat load of shards\n final IndexMetaData indexMetaData = allocation.metaData().getIndexSafe(unassignedShard.index());\n final Set inSyncAllocationIds = indexMetaData.inSyncAllocationIds(unassignedShard.id());\n final boolean snapshotRestore = unassignedShard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT;\n assert inSyncAllocationIds.isEmpty() == false;\n // use in-sync allocation ids to select nodes\n final NodeShardsResult nodeShardsResult = buildNodeShardsResult(unassignedShard, snapshotRestore, allocation.getIgnoreNodes(unassignedShard.shardId()), inSyncAllocationIds, shardState, logger);\n final boolean enoughAllocationsFound = nodeShardsResult.orderedAllocationCandidates.size() > 0;\n logger.debug(\"[{}][{}]: found {} allocation candidates of {} based on allocation ids: [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.orderedAllocationCandidates.size(), unassignedShard, inSyncAllocationIds);\n if (enoughAllocationsFound == false) {\n if (snapshotRestore) {\n // let BalancedShardsAllocator take care of allocating this shard\n logger.debug(\"[{}][{}]: missing local data, will restore from [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard.recoverySource());\n return AllocateUnassignedDecision.NOT_TAKEN;\n } else {\n // We have a shard that was previously allocated, but we could not find a valid shard copy to allocate the primary.\n // We could just be waiting for the node that holds the primary to start back up, in which case the allocation for\n // this shard will be picked up when the node joins and we do another allocation reroute\n logger.debug(\"[{}][{}]: not allocating, number_of_allocated_shards_found [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.allocationsFound);\n return AllocateUnassignedDecision.no(AllocationStatus.NO_VALID_SHARD_COPY, explain ? buildNodeDecisions(null, shardState, inSyncAllocationIds) : null);\n }\n }\n NodesToAllocate nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, false);\n DiscoveryNode node = null;\n String allocationId = null;\n boolean throttled = false;\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, decidedNode.nodeShardState.getNode());\n node = decidedNode.nodeShardState.getNode();\n allocationId = decidedNode.nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() && !nodesToAllocate.noNodeShards.isEmpty()) {\n // The deciders returned a NO decision for all nodes with shard copies, so we check if primary shard\n // can be force-allocated to one of the nodes.\n nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, true);\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n final DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n final NodeGatewayStartedShards nodeShardState = decidedNode.nodeShardState;\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodeShardState.getNode());\n node = nodeShardState.getNode();\n allocationId = nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() == false) {\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n } else {\n logger.debug(\"[{}][{}]: forced primary allocation denied [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard);\n }\n } else {\n // we are throttling this, since we are allowed to allocate to this node but there are enough allocations\n // taking place on the node currently, ignore it for now\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n }\n List nodeR", "post_mask_code": "\n if (explain) {\n nodeResults = buildNodeDecisions(nodesToAllocate, shardState, inSyncAllocationIds);\n }\n if (allocation.hasPendingAsyncFetch()) {\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeResults);\n } else if (node != null) {\n return AllocateUnassignedDecision.yes(node, allocationId, nodeResults, false);\n } else if (throttled) {\n return AllocateUnassignedDecision.throttle(nodeResults);\n } else {\n return AllocateUnassignedDecision.no(AllocationStatus.DECIDERS_NO, nodeResults, true);\n }\n }\n\n /**\n * Builds a map of nodes to the corresponding allocation decisions for those nodes.\n */\n private static List buildNodeDecisions(NodesToAllocate nodesToAllocate, FetchResult fetchedShardData, Set inSyncAllocationIds) {\n List nodeResults = new ArrayList<>();\n Collection ineligibleShards;\n if (nodesToAllocate != null) {\n final Set discoNodes = new HashSet<>();\n nodeResults.addAll(Stream.of(nodesToAllocate.yesNodeShards, nodesToAllocate.throttleNodeShards, nodesToAllocate.noNodeShards).flatMap(Collection::stream).map(dnode -> {\n discoNodes.add(dnode.nodeShardState.getNode());\n return new NodeAllocationResult(dnode.nodeShardState.getNode(), shardStoreInfo(dnode.nodeShardState, inSyncAllocationIds), dnode.decision);\n }).collect(Collectors.toList()));\n ineligibleShards = fetchedShardData.getData().values().stream().filter(shardData -> discoNodes.contains(shardData.getNode()) == false).collect(Collectors.toList());\n } else {\n // there were no shard copies that were eligible for being assigned the allocation,\n // so all fetched shard data are ineligible shards\n ineligibleShards = fetchedShardData.getData().values();\n }\n nodeResults.addAll(ineligibleShards.stream().map(shardData -> new NodeAllocationResult(shardData.getNode(), shardStoreInfo(shardData, inSyncAllocationIds), null)).collect(Collectors.toList()));\n return nodeResults;\n }\n\n private static ShardStoreInfo shardStoreInfo(NodeGatewayStartedShards nodeShardState, Set inSyncAllocationIds) {\n final Exception storeErr = nodeShardState.storeException();\n final boolean inSync = nodeShardState.allocationId() != null && inSyncAllocationIds.contains(nodeShardState.allocationId());\n return new ShardStoreInfo(nodeShardState.allocationId(), inSync, storeErr);\n }\n\n private static final Comparator NO_STORE_EXCEPTION_FIRST_COMPARATOR = Comparator.comparing((NodeGatewayStartedShards state) -> state.storeException() == null).reversed();\n\n private static final Comparator PRIMARY_FIRST_COMPARATOR = Comparator.comparing(NodeGatewayStartedShards::primary).reversed();\n\n /**\n * Builds a list of nodes. If matchAnyShard is set to false, only nodes that have an allocation id matching\n * inSyncAllocationIds are added to the list. Otherwise, any node that has a shard is added to the list, but\n * entries with matching allocation id are always at the front of the list.\n */\n protected static NodeShardsResult buildNodeShardsResult(ShardRouting shard, boolean matchAnyShard, Set ignoreNodes, Set inSyncAllocationIds, FetchResult shardState, Logger logger) {\n List nodeShardStates = new ArrayList<>();\n int numberOfAllocationsFound = 0;\n for (NodeGatewayStartedShards nodeShardState : shardState.getData().values()) {\n DiscoveryNode node = nodeShardState.getNode();\n String allocationId = nodeShardState.allocationId();\n if (ignoreNodes.contains(node.getId())) {\n continue;\n }\n if (nodeShardState.storeException() == null) {\n if (allocationId == null) {\n logger.trace(\"[{}] on node [{}] has no shard state information\", shard, nodeShardState.getNode());\n } else {\n logger.trace(\"[{}] on node [{}] has allocation id [{}]\", shard, nodeShardState.getNode(), allocationId);\n }\n } else {\n final String finalAllocationId = allocationId;\n if (nodeShardState.storeException() instanceof ShardLockObtainFailedException) {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened as it's locked, treating as valid shard\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n } else {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened, treating as no allocation id\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n allocationId = null;\n }\n }\n if (allocationId != null) {\n assert nodeShardState.storeException() == null || nodeShardState.storeException() instanceof ShardLockObtainFailedException : \"only allow store that can be opened or that throws a ShardLockObtainFailedException while being opened but got a \" + \"store throwing \" + nodeShardState.storeException();\n numberOfAllocationsFound++;\n if (matchAnyShard || inSyncAllocationIds.contains(nodeShardState.allocationId())) {\n nodeShardStates.add(nodeShardState);\n }\n }\n }\n // allocation preference\n final Comparator comparator;\n if (matchAnyShard) {\n // prefer shards with matching allocation ids\n Comparator matchingAllocationsFirst = Comparator.comparing((NodeGatewayStartedShards state) -> inSyncAllocationIds.contains(state.allocationId())).reversed();\n comparator = matchingAllocationsFirst.thenComparing(NO_STORE_EXCEPTION_FIRST_COMPARATOR).thenComparing(PRIMARY_FIRST_COMPARATOR);\n } else {\n comparator = NO_STORE_EXCEPTION_FIRST_COMPARATOR.thenComparing(PRIMARY_FIRST_COMPARATOR);\n }\n nodeShardStates.sort(comparator);\n if (logger.isTraceEnabled()) {\n logger.trace(\"{} candidates for allocation: {}\", shard, nodeShardStates.stream().map(s -> s.getNode().getName()).collect(Collectors.joining(\", \")));\n }\n return new NodeShardsResult(nodeShardStates, numberOfAllocationsFound);\n }\n\n /**\n * Split the list of node shard states into groups yes/no/throttle based on allocation deciders\n */\n private NodesToAllocate buildNodesToAllocate(RoutingAllocation allocation, List nodeShardStates, ShardRouting shardRouting, boolean forceAllocate) {\n List yesNodeShards = new ArrayList<>();\n List throttledNodeShards = new ArrayList<>();\n List noNodeShards = new ArrayList<>();\n for (NodeGatewayStartedShards nodeShardState : nodeShardStates) {\n RoutingNode node = allocation.routingNodes().node(nodeShardState.getNode().getId());\n if (node == null) {\n continue;\n }\n Decision decision = forceAllocate ? allocation.deciders().canForceAllocatePrimary(shardRouting, node, allocation) : allocation.deciders().canAllocate(shardRouting, node, allocation);\n DecidedNode decidedNode = new DecidedNode(nodeShardState, decision);\n if (decision.type() == Type.THROTTLE) {\n throttledNodeShards.add(decidedNode);\n } else if (decision.type() == Type.NO) {\n noNodeShards.add(decidedNode);\n } else {\n yesNodeShards.add(decidedNode);\n }\n }\n return new NodesToAllocate(Collections.unmodifiableList(yesNodeShards), Collections.unmodifiableList(throttledNodeShards), Collections.unmodifiableList(noNodeShards));\n }\n\n protected abstract FetchResult fetchData(ShardRouting shard, RoutingAllocation allocation);\n\n private static class NodeShardsResult {\n\n final List orderedAllocationCandidates;\n\n final int allocationsFound;\n\n NodeShardsResult(List orderedAllocationCandidates, int allocationsFound) {\n this.orderedAllocationCandidates = orderedAllocationCandidates;\n this.allocationsFound = allocationsFound;\n }\n }\n\n static class NodesToAllocate {\n\n final List yesNodeShards;\n\n final List throttleNodeShards;\n\n final List noNodeShards;\n\n NodesToAllocate(List yesNodeShards, List throttleNodeShards, List noNodeShards) {\n this.yesNodeShards = yesNodeShards;\n this.throttleNodeShards = throttleNodeShards;\n this.noNodeShards = noNodeShards;\n }\n }\n\n /**\n * This class encapsulates the shard state retrieved from a node and the decision that was made\n * by the allocator for allocating to the node that holds the shard copy.\n */\n private static class DecidedNode {\n\n final NodeGatewayStartedShards nodeShardState;\n\n final Decision decision;\n\n private DecidedNode(NodeGatewayStartedShards nodeShardState, Decision decision) {\n this.nodeShardState = nodeShardState;\n this.decision = decision;\n }\n }\n}\n"} {"task_id": "Java_907", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/strapdata/elassandra/server/src/main/java/org/elasticsearch/gateway/PrimaryShardAllocator.java", "mask_start_position": 2610, "mask_end_position": 3009, "canonical_solution": "private static boolean isResponsibleFor(final ShardRouting shard) {\n return // must be primary\n shard.primary() && // must be unassigned\n shard.unassigned() && // only handle either an existing store or a snapshot recovery\n (shard.recoverySource().getType() == RecoverySource.Type.EXISTING_STORE || shard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT);\n }", "pre_mask_code": "package org.elasticsearch.gateway;\n\nimport org.apache.logging.log4j.Logger;\nimport org.apache.logging.log4j.message.ParameterizedMessage;\nimport org.elasticsearch.cluster.metadata.IndexMetaData;\nimport org.elasticsearch.cluster.node.DiscoveryNode;\nimport org.elasticsearch.cluster.routing.RecoverySource;\nimport org.elasticsearch.cluster.routing.RoutingNode;\nimport org.elasticsearch.cluster.routing.RoutingNodes;\nimport org.elasticsearch.cluster.routing.ShardRouting;\nimport org.elasticsearch.cluster.routing.UnassignedInfo.AllocationStatus;\nimport org.elasticsearch.cluster.routing.allocation.AllocateUnassignedDecision;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult.ShardStoreInfo;\nimport org.elasticsearch.cluster.routing.allocation.RoutingAllocation;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision.Type;\nimport org.elasticsearch.env.ShardLockObtainFailedException;\nimport org.elasticsearch.gateway.AsyncShardFetch.FetchResult;\nimport org.elasticsearch.gateway.TransportNodesListGatewayStartedShards.NodeGatewayStartedShards;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\n/**\n * The primary shard allocator allocates unassigned primary shards to nodes that hold\n * valid copies of the unassigned primaries. It does this by iterating over all unassigned\n * primary shards in the routing table and fetching shard metadata from each node in the cluster\n * that holds a copy of the shard. The shard metadata from each node is compared against the\n * set of valid allocation IDs and for all valid shard copies (if any), the primary shard allocator\n * executes the allocation deciders to chose a copy to assign the primary shard to.\n *\n * Note that the PrimaryShardAllocator does *not* allocate primaries on index creation\n * (see {@link org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator}),\n * nor does it allocate primaries when a primary shard failed and there is a valid replica\n * copy that can immediately be promoted to primary, as this takes place in {@link RoutingNodes#failShard}.\n */\npublic abstract class PrimaryShardAllocator extends BaseGatewayShardAllocator {\n\n /**\n * Is the allocator responsible for allocating the given {@link ShardRouting}?\n */\n ", "post_mask_code": "\n\n @Override\n public AllocateUnassignedDecision makeAllocationDecision(final ShardRouting unassignedShard, final RoutingAllocation allocation, final Logger logger) {\n if (isResponsibleFor(unassignedShard) == false) {\n // this allocator is not responsible for allocating this shard\n return AllocateUnassignedDecision.NOT_TAKEN;\n }\n final boolean explain = allocation.debugDecision();\n final FetchResult shardState = fetchData(unassignedShard, allocation);\n if (shardState.hasData() == false) {\n allocation.setHasPendingAsyncFetch();\n List nodeDecisions = null;\n if (explain) {\n nodeDecisions = buildDecisionsForAllNodes(unassignedShard, allocation);\n }\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeDecisions);\n }\n // don't create a new IndexSetting object for every shard as this could cause a lot of garbage\n // on cluster restart if we allocate a boat load of shards\n final IndexMetaData indexMetaData = allocation.metaData().getIndexSafe(unassignedShard.index());\n final Set inSyncAllocationIds = indexMetaData.inSyncAllocationIds(unassignedShard.id());\n final boolean snapshotRestore = unassignedShard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT;\n assert inSyncAllocationIds.isEmpty() == false;\n // use in-sync allocation ids to select nodes\n final NodeShardsResult nodeShardsResult = buildNodeShardsResult(unassignedShard, snapshotRestore, allocation.getIgnoreNodes(unassignedShard.shardId()), inSyncAllocationIds, shardState, logger);\n final boolean enoughAllocationsFound = nodeShardsResult.orderedAllocationCandidates.size() > 0;\n logger.debug(\"[{}][{}]: found {} allocation candidates of {} based on allocation ids: [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.orderedAllocationCandidates.size(), unassignedShard, inSyncAllocationIds);\n if (enoughAllocationsFound == false) {\n if (snapshotRestore) {\n // let BalancedShardsAllocator take care of allocating this shard\n logger.debug(\"[{}][{}]: missing local data, will restore from [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard.recoverySource());\n return AllocateUnassignedDecision.NOT_TAKEN;\n } else {\n // We have a shard that was previously allocated, but we could not find a valid shard copy to allocate the primary.\n // We could just be waiting for the node that holds the primary to start back up, in which case the allocation for\n // this shard will be picked up when the node joins and we do another allocation reroute\n logger.debug(\"[{}][{}]: not allocating, number_of_allocated_shards_found [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.allocationsFound);\n return AllocateUnassignedDecision.no(AllocationStatus.NO_VALID_SHARD_COPY, explain ? buildNodeDecisions(null, shardState, inSyncAllocationIds) : null);\n }\n }\n NodesToAllocate nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, false);\n DiscoveryNode node = null;\n String allocationId = null;\n boolean throttled = false;\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, decidedNode.nodeShardState.getNode());\n node = decidedNode.nodeShardState.getNode();\n allocationId = decidedNode.nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() && !nodesToAllocate.noNodeShards.isEmpty()) {\n // The deciders returned a NO decision for all nodes with shard copies, so we check if primary shard\n // can be force-allocated to one of the nodes.\n nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, true);\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n final DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n final NodeGatewayStartedShards nodeShardState = decidedNode.nodeShardState;\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodeShardState.getNode());\n node = nodeShardState.getNode();\n allocationId = nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() == false) {\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n } else {\n logger.debug(\"[{}][{}]: forced primary allocation denied [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard);\n }\n } else {\n // we are throttling this, since we are allowed to allocate to this node but there are enough allocations\n // taking place on the node currently, ignore it for now\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n }\n List nodeResults = null;\n if (explain) {\n nodeResults = buildNodeDecisions(nodesToAllocate, shardState, inSyncAllocationIds);\n }\n if (allocation.hasPendingAsyncFetch()) {\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeResults);\n } else if (node != null) {\n return AllocateUnassignedDecision.yes(node, allocationId, nodeResults, false);\n } else if (throttled) {\n return AllocateUnassignedDecision.throttle(nodeResults);\n } else {\n return AllocateUnassignedDecision.no(AllocationStatus.DECIDERS_NO, nodeResults, true);\n }\n }\n\n /**\n * Builds a map of nodes to the corresponding allocation decisions for those nodes.\n */\n private static List buildNodeDecisions(NodesToAllocate nodesToAllocate, FetchResult fetchedShardData, Set inSyncAllocationIds) {\n List nodeResults = new ArrayList<>();\n Collection ineligibleShards;\n if (nodesToAllocate != null) {\n final Set discoNodes = new HashSet<>();\n nodeResults.addAll(Stream.of(nodesToAllocate.yesNodeShards, nodesToAllocate.throttleNodeShards, nodesToAllocate.noNodeShards).flatMap(Collection::stream).map(dnode -> {\n discoNodes.add(dnode.nodeShardState.getNode());\n return new NodeAllocationResult(dnode.nodeShardState.getNode(), shardStoreInfo(dnode.nodeShardState, inSyncAllocationIds), dnode.decision);\n }).collect(Collectors.toList()));\n ineligibleShards = fetchedShardData.getData().values().stream().filter(shardData -> discoNodes.contains(shardData.getNode()) == false).collect(Collectors.toList());\n } else {\n // there were no shard copies that were eligible for being assigned the allocation,\n // so all fetched shard data are ineligible shards\n ineligibleShards = fetchedShardData.getData().values();\n }\n nodeResults.addAll(ineligibleShards.stream().map(shardData -> new NodeAllocationResult(shardData.getNode(), shardStoreInfo(shardData, inSyncAllocationIds), null)).collect(Collectors.toList()));\n return nodeResults;\n }\n\n private static ShardStoreInfo shardStoreInfo(NodeGatewayStartedShards nodeShardState, Set inSyncAllocationIds) {\n final Exception storeErr = nodeShardState.storeException();\n final boolean inSync = nodeShardState.allocationId() != null && inSyncAllocationIds.contains(nodeShardState.allocationId());\n return new ShardStoreInfo(nodeShardState.allocationId(), inSync, storeErr);\n }\n\n private static final Comparator NO_STORE_EXCEPTION_FIRST_COMPARATOR = Comparator.comparing((NodeGatewayStartedShards state) -> state.storeException() == null).reversed();\n\n private static final Comparator PRIMARY_FIRST_COMPARATOR = Comparator.comparing(NodeGatewayStartedShards::primary).reversed();\n\n /**\n * Builds a list of nodes. If matchAnyShard is set to false, only nodes that have an allocation id matching\n * inSyncAllocationIds are added to the list. Otherwise, any node that has a shard is added to the list, but\n * entries with matching allocation id are always at the front of the list.\n */\n protected static NodeShardsResult buildNodeShardsResult(ShardRouting shard, boolean matchAnyShard, Set ignoreNodes, Set inSyncAllocationIds, FetchResult shardState, Logger logger) {\n List nodeShardStates = new ArrayList<>();\n int numberOfAllocationsFound = 0;\n for (NodeGatewayStartedShards nodeShardState : shardState.getData().values()) {\n DiscoveryNode node = nodeShardState.getNode();\n String allocationId = nodeShardState.allocationId();\n if (ignoreNodes.contains(node.getId())) {\n continue;\n }\n if (nodeShardState.storeException() == null) {\n if (allocationId == null) {\n logger.trace(\"[{}] on node [{}] has no shard state information\", shard, nodeShardState.getNode());\n } else {\n logger.trace(\"[{}] on node [{}] has allocation id [{}]\", shard, nodeShardState.getNode(), allocationId);\n }\n } else {\n final String finalAllocationId = allocationId;\n if (nodeShardState.storeException() instanceof ShardLockObtainFailedException) {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened as it's locked, treating as valid shard\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n } else {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened, treating as no allocation id\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n allocationId = null;\n }\n }\n if (allocationId != null) {\n assert nodeShardState.storeException() == null || nodeShardState.storeException() instanceof ShardLockObtainFailedException : \"only allow store that can be opened or that throws a ShardLockObtainFailedException while being opened but got a \" + \"store throwing \" + nodeShardState.storeException();\n numberOfAllocationsFound++;\n if (matchAnyShard || inSyncAllocationIds.contains(nodeShardState.allocationId())) {\n nodeShardStates.add(nodeShardState);\n }\n }\n }\n // allocation preference\n final Comparator comparator;\n if (matchAnyShard) {\n // prefer shards with matching allocation ids\n Comparator matchingAllocationsFirst = Comparator.comparing((NodeGatewayStartedShards state) -> inSyncAllocationIds.contains(state.allocationId())).reversed();\n comparator = matchingAllocationsFirst.thenComparing(NO_STORE_EXCEPTION_FIRST_COMPARATOR).thenComparing(PRIMARY_FIRST_COMPARATOR);\n } else {\n comparator = NO_STORE_EXCEPTION_FIRST_COMPARATOR.thenComparing(PRIMARY_FIRST_COMPARATOR);\n }\n nodeShardStates.sort(comparator);\n if (logger.isTraceEnabled()) {\n logger.trace(\"{} candidates for allocation: {}\", shard, nodeShardStates.stream().map(s -> s.getNode().getName()).collect(Collectors.joining(\", \")));\n }\n return new NodeShardsResult(nodeShardStates, numberOfAllocationsFound);\n }\n\n /**\n * Split the list of node shard states into groups yes/no/throttle based on allocation deciders\n */\n private NodesToAllocate buildNodesToAllocate(RoutingAllocation allocation, List nodeShardStates, ShardRouting shardRouting, boolean forceAllocate) {\n List yesNodeShards = new ArrayList<>();\n List throttledNodeShards = new ArrayList<>();\n List noNodeShards = new ArrayList<>();\n for (NodeGatewayStartedShards nodeShardState : nodeShardStates) {\n RoutingNode node = allocation.routingNodes().node(nodeShardState.getNode().getId());\n if (node == null) {\n continue;\n }\n Decision decision = forceAllocate ? allocation.deciders().canForceAllocatePrimary(shardRouting, node, allocation) : allocation.deciders().canAllocate(shardRouting, node, allocation);\n DecidedNode decidedNode = new DecidedNode(nodeShardState, decision);\n if (decision.type() == Type.THROTTLE) {\n throttledNodeShards.add(decidedNode);\n } else if (decision.type() == Type.NO) {\n noNodeShards.add(decidedNode);\n } else {\n yesNodeShards.add(decidedNode);\n }\n }\n return new NodesToAllocate(Collections.unmodifiableList(yesNodeShards), Collections.unmodifiableList(throttledNodeShards), Collections.unmodifiableList(noNodeShards));\n }\n\n protected abstract FetchResult fetchData(ShardRouting shard, RoutingAllocation allocation);\n\n private static class NodeShardsResult {\n\n final List orderedAllocationCandidates;\n\n final int allocationsFound;\n\n NodeShardsResult(List orderedAllocationCandidates, int allocationsFound) {\n this.orderedAllocationCandidates = orderedAllocationCandidates;\n this.allocationsFound = allocationsFound;\n }\n }\n\n static class NodesToAllocate {\n\n final List yesNodeShards;\n\n final List throttleNodeShards;\n\n final List noNodeShards;\n\n NodesToAllocate(List yesNodeShards, List throttleNodeShards, List noNodeShards) {\n this.yesNodeShards = yesNodeShards;\n this.throttleNodeShards = throttleNodeShards;\n this.noNodeShards = noNodeShards;\n }\n }\n\n /**\n * This class encapsulates the shard state retrieved from a node and the decision that was made\n * by the allocator for allocating to the node that holds the shard copy.\n */\n private static class DecidedNode {\n\n final NodeGatewayStartedShards nodeShardState;\n\n final Decision decision;\n\n private DecidedNode(NodeGatewayStartedShards nodeShardState, Decision decision) {\n this.nodeShardState = nodeShardState;\n this.decision = decision;\n }\n }\n}\n"} {"task_id": "Java_908", "language": "Java", "task_type": "if_statement", "source_file": "java/github/strapdata/elassandra/server/src/main/java/org/elasticsearch/gateway/PrimaryShardAllocator.java", "mask_start_position": 3554, "mask_end_position": 3943, "canonical_solution": "if (shardState.hasData() == false) {\n allocation.setHasPendingAsyncFetch();\n List nodeDecisions = null;\n if (explain) {\n nodeDecisions = buildDecisionsForAllNodes(unassignedShard, allocation);\n }\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeDecisions);\n }", "pre_mask_code": "package org.elasticsearch.gateway;\n\nimport org.apache.logging.log4j.Logger;\nimport org.apache.logging.log4j.message.ParameterizedMessage;\nimport org.elasticsearch.cluster.metadata.IndexMetaData;\nimport org.elasticsearch.cluster.node.DiscoveryNode;\nimport org.elasticsearch.cluster.routing.RecoverySource;\nimport org.elasticsearch.cluster.routing.RoutingNode;\nimport org.elasticsearch.cluster.routing.RoutingNodes;\nimport org.elasticsearch.cluster.routing.ShardRouting;\nimport org.elasticsearch.cluster.routing.UnassignedInfo.AllocationStatus;\nimport org.elasticsearch.cluster.routing.allocation.AllocateUnassignedDecision;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult.ShardStoreInfo;\nimport org.elasticsearch.cluster.routing.allocation.RoutingAllocation;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision.Type;\nimport org.elasticsearch.env.ShardLockObtainFailedException;\nimport org.elasticsearch.gateway.AsyncShardFetch.FetchResult;\nimport org.elasticsearch.gateway.TransportNodesListGatewayStartedShards.NodeGatewayStartedShards;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\n/**\n * The primary shard allocator allocates unassigned primary shards to nodes that hold\n * valid copies of the unassigned primaries. It does this by iterating over all unassigned\n * primary shards in the routing table and fetching shard metadata from each node in the cluster\n * that holds a copy of the shard. The shard metadata from each node is compared against the\n * set of valid allocation IDs and for all valid shard copies (if any), the primary shard allocator\n * executes the allocation deciders to chose a copy to assign the primary shard to.\n *\n * Note that the PrimaryShardAllocator does *not* allocate primaries on index creation\n * (see {@link org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator}),\n * nor does it allocate primaries when a primary shard failed and there is a valid replica\n * copy that can immediately be promoted to primary, as this takes place in {@link RoutingNodes#failShard}.\n */\npublic abstract class PrimaryShardAllocator extends BaseGatewayShardAllocator {\n\n /**\n * Is the allocator responsible for allocating the given {@link ShardRouting}?\n */\n private static boolean isResponsibleFor(final ShardRouting shard) {\n return // must be primary\n shard.primary() && // must be unassigned\n shard.unassigned() && // only handle either an existing store or a snapshot recovery\n (shard.recoverySource().getType() == RecoverySource.Type.EXISTING_STORE || shard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT);\n }\n\n @Override\n public AllocateUnassignedDecision makeAllocationDecision(final ShardRouting unassignedShard, final RoutingAllocation allocation, final Logger logger) {\n if (isResponsibleFor(unassignedShard) == false) {\n // this allocator is not responsible for allocating this shard\n return AllocateUnassignedDecision.NOT_TAKEN;\n }\n final boolean explain = allocation.debugDecision();\n final FetchResult shardState = fetchData(unassignedShard, allocation);\n ", "post_mask_code": "\n // don't create a new IndexSetting object for every shard as this could cause a lot of garbage\n // on cluster restart if we allocate a boat load of shards\n final IndexMetaData indexMetaData = allocation.metaData().getIndexSafe(unassignedShard.index());\n final Set inSyncAllocationIds = indexMetaData.inSyncAllocationIds(unassignedShard.id());\n final boolean snapshotRestore = unassignedShard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT;\n assert inSyncAllocationIds.isEmpty() == false;\n // use in-sync allocation ids to select nodes\n final NodeShardsResult nodeShardsResult = buildNodeShardsResult(unassignedShard, snapshotRestore, allocation.getIgnoreNodes(unassignedShard.shardId()), inSyncAllocationIds, shardState, logger);\n final boolean enoughAllocationsFound = nodeShardsResult.orderedAllocationCandidates.size() > 0;\n logger.debug(\"[{}][{}]: found {} allocation candidates of {} based on allocation ids: [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.orderedAllocationCandidates.size(), unassignedShard, inSyncAllocationIds);\n if (enoughAllocationsFound == false) {\n if (snapshotRestore) {\n // let BalancedShardsAllocator take care of allocating this shard\n logger.debug(\"[{}][{}]: missing local data, will restore from [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard.recoverySource());\n return AllocateUnassignedDecision.NOT_TAKEN;\n } else {\n // We have a shard that was previously allocated, but we could not find a valid shard copy to allocate the primary.\n // We could just be waiting for the node that holds the primary to start back up, in which case the allocation for\n // this shard will be picked up when the node joins and we do another allocation reroute\n logger.debug(\"[{}][{}]: not allocating, number_of_allocated_shards_found [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.allocationsFound);\n return AllocateUnassignedDecision.no(AllocationStatus.NO_VALID_SHARD_COPY, explain ? buildNodeDecisions(null, shardState, inSyncAllocationIds) : null);\n }\n }\n NodesToAllocate nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, false);\n DiscoveryNode node = null;\n String allocationId = null;\n boolean throttled = false;\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, decidedNode.nodeShardState.getNode());\n node = decidedNode.nodeShardState.getNode();\n allocationId = decidedNode.nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() && !nodesToAllocate.noNodeShards.isEmpty()) {\n // The deciders returned a NO decision for all nodes with shard copies, so we check if primary shard\n // can be force-allocated to one of the nodes.\n nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, true);\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n final DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n final NodeGatewayStartedShards nodeShardState = decidedNode.nodeShardState;\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodeShardState.getNode());\n node = nodeShardState.getNode();\n allocationId = nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() == false) {\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n } else {\n logger.debug(\"[{}][{}]: forced primary allocation denied [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard);\n }\n } else {\n // we are throttling this, since we are allowed to allocate to this node but there are enough allocations\n // taking place on the node currently, ignore it for now\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n }\n List nodeResults = null;\n if (explain) {\n nodeResults = buildNodeDecisions(nodesToAllocate, shardState, inSyncAllocationIds);\n }\n if (allocation.hasPendingAsyncFetch()) {\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeResults);\n } else if (node != null) {\n return AllocateUnassignedDecision.yes(node, allocationId, nodeResults, false);\n } else if (throttled) {\n return AllocateUnassignedDecision.throttle(nodeResults);\n } else {\n return AllocateUnassignedDecision.no(AllocationStatus.DECIDERS_NO, nodeResults, true);\n }\n }\n\n /**\n * Builds a map of nodes to the corresponding allocation decisions for those nodes.\n */\n private static List buildNodeDecisions(NodesToAllocate nodesToAllocate, FetchResult fetchedShardData, Set inSyncAllocationIds) {\n List nodeResults = new ArrayList<>();\n Collection ineligibleShards;\n if (nodesToAllocate != null) {\n final Set discoNodes = new HashSet<>();\n nodeResults.addAll(Stream.of(nodesToAllocate.yesNodeShards, nodesToAllocate.throttleNodeShards, nodesToAllocate.noNodeShards).flatMap(Collection::stream).map(dnode -> {\n discoNodes.add(dnode.nodeShardState.getNode());\n return new NodeAllocationResult(dnode.nodeShardState.getNode(), shardStoreInfo(dnode.nodeShardState, inSyncAllocationIds), dnode.decision);\n }).collect(Collectors.toList()));\n ineligibleShards = fetchedShardData.getData().values().stream().filter(shardData -> discoNodes.contains(shardData.getNode()) == false).collect(Collectors.toList());\n } else {\n // there were no shard copies that were eligible for being assigned the allocation,\n // so all fetched shard data are ineligible shards\n ineligibleShards = fetchedShardData.getData().values();\n }\n nodeResults.addAll(ineligibleShards.stream().map(shardData -> new NodeAllocationResult(shardData.getNode(), shardStoreInfo(shardData, inSyncAllocationIds), null)).collect(Collectors.toList()));\n return nodeResults;\n }\n\n private static ShardStoreInfo shardStoreInfo(NodeGatewayStartedShards nodeShardState, Set inSyncAllocationIds) {\n final Exception storeErr = nodeShardState.storeException();\n final boolean inSync = nodeShardState.allocationId() != null && inSyncAllocationIds.contains(nodeShardState.allocationId());\n return new ShardStoreInfo(nodeShardState.allocationId(), inSync, storeErr);\n }\n\n private static final Comparator NO_STORE_EXCEPTION_FIRST_COMPARATOR = Comparator.comparing((NodeGatewayStartedShards state) -> state.storeException() == null).reversed();\n\n private static final Comparator PRIMARY_FIRST_COMPARATOR = Comparator.comparing(NodeGatewayStartedShards::primary).reversed();\n\n /**\n * Builds a list of nodes. If matchAnyShard is set to false, only nodes that have an allocation id matching\n * inSyncAllocationIds are added to the list. Otherwise, any node that has a shard is added to the list, but\n * entries with matching allocation id are always at the front of the list.\n */\n protected static NodeShardsResult buildNodeShardsResult(ShardRouting shard, boolean matchAnyShard, Set ignoreNodes, Set inSyncAllocationIds, FetchResult shardState, Logger logger) {\n List nodeShardStates = new ArrayList<>();\n int numberOfAllocationsFound = 0;\n for (NodeGatewayStartedShards nodeShardState : shardState.getData().values()) {\n DiscoveryNode node = nodeShardState.getNode();\n String allocationId = nodeShardState.allocationId();\n if (ignoreNodes.contains(node.getId())) {\n continue;\n }\n if (nodeShardState.storeException() == null) {\n if (allocationId == null) {\n logger.trace(\"[{}] on node [{}] has no shard state information\", shard, nodeShardState.getNode());\n } else {\n logger.trace(\"[{}] on node [{}] has allocation id [{}]\", shard, nodeShardState.getNode(), allocationId);\n }\n } else {\n final String finalAllocationId = allocationId;\n if (nodeShardState.storeException() instanceof ShardLockObtainFailedException) {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened as it's locked, treating as valid shard\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n } else {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened, treating as no allocation id\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n allocationId = null;\n }\n }\n if (allocationId != null) {\n assert nodeShardState.storeException() == null || nodeShardState.storeException() instanceof ShardLockObtainFailedException : \"only allow store that can be opened or that throws a ShardLockObtainFailedException while being opened but got a \" + \"store throwing \" + nodeShardState.storeException();\n numberOfAllocationsFound++;\n if (matchAnyShard || inSyncAllocationIds.contains(nodeShardState.allocationId())) {\n nodeShardStates.add(nodeShardState);\n }\n }\n }\n // allocation preference\n final Comparator comparator;\n if (matchAnyShard) {\n // prefer shards with matching allocation ids\n Comparator matchingAllocationsFirst = Comparator.comparing((NodeGatewayStartedShards state) -> inSyncAllocationIds.contains(state.allocationId())).reversed();\n comparator = matchingAllocationsFirst.thenComparing(NO_STORE_EXCEPTION_FIRST_COMPARATOR).thenComparing(PRIMARY_FIRST_COMPARATOR);\n } else {\n comparator = NO_STORE_EXCEPTION_FIRST_COMPARATOR.thenComparing(PRIMARY_FIRST_COMPARATOR);\n }\n nodeShardStates.sort(comparator);\n if (logger.isTraceEnabled()) {\n logger.trace(\"{} candidates for allocation: {}\", shard, nodeShardStates.stream().map(s -> s.getNode().getName()).collect(Collectors.joining(\", \")));\n }\n return new NodeShardsResult(nodeShardStates, numberOfAllocationsFound);\n }\n\n /**\n * Split the list of node shard states into groups yes/no/throttle based on allocation deciders\n */\n private NodesToAllocate buildNodesToAllocate(RoutingAllocation allocation, List nodeShardStates, ShardRouting shardRouting, boolean forceAllocate) {\n List yesNodeShards = new ArrayList<>();\n List throttledNodeShards = new ArrayList<>();\n List noNodeShards = new ArrayList<>();\n for (NodeGatewayStartedShards nodeShardState : nodeShardStates) {\n RoutingNode node = allocation.routingNodes().node(nodeShardState.getNode().getId());\n if (node == null) {\n continue;\n }\n Decision decision = forceAllocate ? allocation.deciders().canForceAllocatePrimary(shardRouting, node, allocation) : allocation.deciders().canAllocate(shardRouting, node, allocation);\n DecidedNode decidedNode = new DecidedNode(nodeShardState, decision);\n if (decision.type() == Type.THROTTLE) {\n throttledNodeShards.add(decidedNode);\n } else if (decision.type() == Type.NO) {\n noNodeShards.add(decidedNode);\n } else {\n yesNodeShards.add(decidedNode);\n }\n }\n return new NodesToAllocate(Collections.unmodifiableList(yesNodeShards), Collections.unmodifiableList(throttledNodeShards), Collections.unmodifiableList(noNodeShards));\n }\n\n protected abstract FetchResult fetchData(ShardRouting shard, RoutingAllocation allocation);\n\n private static class NodeShardsResult {\n\n final List orderedAllocationCandidates;\n\n final int allocationsFound;\n\n NodeShardsResult(List orderedAllocationCandidates, int allocationsFound) {\n this.orderedAllocationCandidates = orderedAllocationCandidates;\n this.allocationsFound = allocationsFound;\n }\n }\n\n static class NodesToAllocate {\n\n final List yesNodeShards;\n\n final List throttleNodeShards;\n\n final List noNodeShards;\n\n NodesToAllocate(List yesNodeShards, List throttleNodeShards, List noNodeShards) {\n this.yesNodeShards = yesNodeShards;\n this.throttleNodeShards = throttleNodeShards;\n this.noNodeShards = noNodeShards;\n }\n }\n\n /**\n * This class encapsulates the shard state retrieved from a node and the decision that was made\n * by the allocator for allocating to the node that holds the shard copy.\n */\n private static class DecidedNode {\n\n final NodeGatewayStartedShards nodeShardState;\n\n final Decision decision;\n\n private DecidedNode(NodeGatewayStartedShards nodeShardState, Decision decision) {\n this.nodeShardState = nodeShardState;\n this.decision = decision;\n }\n }\n}\n"} {"task_id": "Java_909", "language": "Java", "task_type": "empty", "source_file": "java/github/strapdata/elassandra/server/src/main/java/org/elasticsearch/gateway/PrimaryShardAllocator.java", "mask_start_position": 4155, "mask_end_position": 4155, "canonical_solution": "", "pre_mask_code": "package org.elasticsearch.gateway;\n\nimport org.apache.logging.log4j.Logger;\nimport org.apache.logging.log4j.message.ParameterizedMessage;\nimport org.elasticsearch.cluster.metadata.IndexMetaData;\nimport org.elasticsearch.cluster.node.DiscoveryNode;\nimport org.elasticsearch.cluster.routing.RecoverySource;\nimport org.elasticsearch.cluster.routing.RoutingNode;\nimport org.elasticsearch.cluster.routing.RoutingNodes;\nimport org.elasticsearch.cluster.routing.ShardRouting;\nimport org.elasticsearch.cluster.routing.UnassignedInfo.AllocationStatus;\nimport org.elasticsearch.cluster.routing.allocation.AllocateUnassignedDecision;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult;\nimport org.elasticsearch.cluster.routing.allocation.NodeAllocationResult.ShardStoreInfo;\nimport org.elasticsearch.cluster.routing.allocation.RoutingAllocation;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision;\nimport org.elasticsearch.cluster.routing.allocation.decider.Decision.Type;\nimport org.elasticsearch.env.ShardLockObtainFailedException;\nimport org.elasticsearch.gateway.AsyncShardFetch.FetchResult;\nimport org.elasticsearch.gateway.TransportNodesListGatewayStartedShards.NodeGatewayStartedShards;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\n/**\n * The primary shard allocator allocates unassigned primary shards to nodes that hold\n * valid copies of the unassigned primaries. It does this by iterating over all unassigned\n * primary shards in the routing table and fetching shard metadata from each node in the cluster\n * that holds a copy of the shard. The shard metadata from each node is compared against the\n * set of valid allocation IDs and for all valid shard copies (if any), the primary shard allocator\n * executes the allocation deciders to chose a copy to assign the primary shard to.\n *\n * Note that the PrimaryShardAllocator does *not* allocate primaries on index creation\n * (see {@link org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator}),\n * nor does it allocate primaries when a primary shard failed and there is a valid replica\n * copy that can immediately be promoted to primary, as this takes place in {@link RoutingNodes#failShard}.\n */\npublic abstract class PrimaryShardAllocator extends BaseGatewayShardAllocator {\n\n /**\n * Is the allocator responsible for allocating the given {@link ShardRouting}?\n */\n private static boolean isResponsibleFor(final ShardRouting shard) {\n return // must be primary\n shard.primary() && // must be unassigned\n shard.unassigned() && // only handle either an existing store or a snapshot recovery\n (shard.recoverySource().getType() == RecoverySource.Type.EXISTING_STORE || shard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT);\n }\n\n @Override\n public AllocateUnassignedDecision makeAllocationDecision(final ShardRouting unassignedShard, final RoutingAllocation allocation, final Logger logger) {\n if (isResponsibleFor(unassignedShard) == false) {\n // this allocator is not responsible for allocating this shard\n return AllocateUnassignedDecision.NOT_TAKEN;\n }\n final boolean explain = allocation.debugDecision();\n final FetchResult shardState = fetchData(unassignedShard, allocation);\n if (shardState.hasData() == false) {\n allocation.setHasPendingAsyncFetch();\n List nodeDecisions = null;\n if (explain) {\n nodeDecisions = buildDecisionsForAllNodes(unassignedShard, allocation);\n }\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeDecisions);\n }\n // don't create a new IndexSetting object for every shard as this could cause a lot of garbage\n // on cluster restart if we allocate a boat load of shards\n final IndexMetaData indexMetaData", "post_mask_code": " = allocation.metaData().getIndexSafe(unassignedShard.index());\n final Set inSyncAllocationIds = indexMetaData.inSyncAllocationIds(unassignedShard.id());\n final boolean snapshotRestore = unassignedShard.recoverySource().getType() == RecoverySource.Type.SNAPSHOT;\n assert inSyncAllocationIds.isEmpty() == false;\n // use in-sync allocation ids to select nodes\n final NodeShardsResult nodeShardsResult = buildNodeShardsResult(unassignedShard, snapshotRestore, allocation.getIgnoreNodes(unassignedShard.shardId()), inSyncAllocationIds, shardState, logger);\n final boolean enoughAllocationsFound = nodeShardsResult.orderedAllocationCandidates.size() > 0;\n logger.debug(\"[{}][{}]: found {} allocation candidates of {} based on allocation ids: [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.orderedAllocationCandidates.size(), unassignedShard, inSyncAllocationIds);\n if (enoughAllocationsFound == false) {\n if (snapshotRestore) {\n // let BalancedShardsAllocator take care of allocating this shard\n logger.debug(\"[{}][{}]: missing local data, will restore from [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard.recoverySource());\n return AllocateUnassignedDecision.NOT_TAKEN;\n } else {\n // We have a shard that was previously allocated, but we could not find a valid shard copy to allocate the primary.\n // We could just be waiting for the node that holds the primary to start back up, in which case the allocation for\n // this shard will be picked up when the node joins and we do another allocation reroute\n logger.debug(\"[{}][{}]: not allocating, number_of_allocated_shards_found [{}]\", unassignedShard.index(), unassignedShard.id(), nodeShardsResult.allocationsFound);\n return AllocateUnassignedDecision.no(AllocationStatus.NO_VALID_SHARD_COPY, explain ? buildNodeDecisions(null, shardState, inSyncAllocationIds) : null);\n }\n }\n NodesToAllocate nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, false);\n DiscoveryNode node = null;\n String allocationId = null;\n boolean throttled = false;\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, decidedNode.nodeShardState.getNode());\n node = decidedNode.nodeShardState.getNode();\n allocationId = decidedNode.nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() && !nodesToAllocate.noNodeShards.isEmpty()) {\n // The deciders returned a NO decision for all nodes with shard copies, so we check if primary shard\n // can be force-allocated to one of the nodes.\n nodesToAllocate = buildNodesToAllocate(allocation, nodeShardsResult.orderedAllocationCandidates, unassignedShard, true);\n if (nodesToAllocate.yesNodeShards.isEmpty() == false) {\n final DecidedNode decidedNode = nodesToAllocate.yesNodeShards.get(0);\n final NodeGatewayStartedShards nodeShardState = decidedNode.nodeShardState;\n logger.debug(\"[{}][{}]: allocating [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodeShardState.getNode());\n node = nodeShardState.getNode();\n allocationId = nodeShardState.allocationId();\n } else if (nodesToAllocate.throttleNodeShards.isEmpty() == false) {\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on forced primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n } else {\n logger.debug(\"[{}][{}]: forced primary allocation denied [{}]\", unassignedShard.index(), unassignedShard.id(), unassignedShard);\n }\n } else {\n // we are throttling this, since we are allowed to allocate to this node but there are enough allocations\n // taking place on the node currently, ignore it for now\n logger.debug(\"[{}][{}]: throttling allocation [{}] to [{}] on primary allocation\", unassignedShard.index(), unassignedShard.id(), unassignedShard, nodesToAllocate.throttleNodeShards);\n throttled = true;\n }\n List nodeResults = null;\n if (explain) {\n nodeResults = buildNodeDecisions(nodesToAllocate, shardState, inSyncAllocationIds);\n }\n if (allocation.hasPendingAsyncFetch()) {\n return AllocateUnassignedDecision.no(AllocationStatus.FETCHING_SHARD_DATA, nodeResults);\n } else if (node != null) {\n return AllocateUnassignedDecision.yes(node, allocationId, nodeResults, false);\n } else if (throttled) {\n return AllocateUnassignedDecision.throttle(nodeResults);\n } else {\n return AllocateUnassignedDecision.no(AllocationStatus.DECIDERS_NO, nodeResults, true);\n }\n }\n\n /**\n * Builds a map of nodes to the corresponding allocation decisions for those nodes.\n */\n private static List buildNodeDecisions(NodesToAllocate nodesToAllocate, FetchResult fetchedShardData, Set inSyncAllocationIds) {\n List nodeResults = new ArrayList<>();\n Collection ineligibleShards;\n if (nodesToAllocate != null) {\n final Set discoNodes = new HashSet<>();\n nodeResults.addAll(Stream.of(nodesToAllocate.yesNodeShards, nodesToAllocate.throttleNodeShards, nodesToAllocate.noNodeShards).flatMap(Collection::stream).map(dnode -> {\n discoNodes.add(dnode.nodeShardState.getNode());\n return new NodeAllocationResult(dnode.nodeShardState.getNode(), shardStoreInfo(dnode.nodeShardState, inSyncAllocationIds), dnode.decision);\n }).collect(Collectors.toList()));\n ineligibleShards = fetchedShardData.getData().values().stream().filter(shardData -> discoNodes.contains(shardData.getNode()) == false).collect(Collectors.toList());\n } else {\n // there were no shard copies that were eligible for being assigned the allocation,\n // so all fetched shard data are ineligible shards\n ineligibleShards = fetchedShardData.getData().values();\n }\n nodeResults.addAll(ineligibleShards.stream().map(shardData -> new NodeAllocationResult(shardData.getNode(), shardStoreInfo(shardData, inSyncAllocationIds), null)).collect(Collectors.toList()));\n return nodeResults;\n }\n\n private static ShardStoreInfo shardStoreInfo(NodeGatewayStartedShards nodeShardState, Set inSyncAllocationIds) {\n final Exception storeErr = nodeShardState.storeException();\n final boolean inSync = nodeShardState.allocationId() != null && inSyncAllocationIds.contains(nodeShardState.allocationId());\n return new ShardStoreInfo(nodeShardState.allocationId(), inSync, storeErr);\n }\n\n private static final Comparator NO_STORE_EXCEPTION_FIRST_COMPARATOR = Comparator.comparing((NodeGatewayStartedShards state) -> state.storeException() == null).reversed();\n\n private static final Comparator PRIMARY_FIRST_COMPARATOR = Comparator.comparing(NodeGatewayStartedShards::primary).reversed();\n\n /**\n * Builds a list of nodes. If matchAnyShard is set to false, only nodes that have an allocation id matching\n * inSyncAllocationIds are added to the list. Otherwise, any node that has a shard is added to the list, but\n * entries with matching allocation id are always at the front of the list.\n */\n protected static NodeShardsResult buildNodeShardsResult(ShardRouting shard, boolean matchAnyShard, Set ignoreNodes, Set inSyncAllocationIds, FetchResult shardState, Logger logger) {\n List nodeShardStates = new ArrayList<>();\n int numberOfAllocationsFound = 0;\n for (NodeGatewayStartedShards nodeShardState : shardState.getData().values()) {\n DiscoveryNode node = nodeShardState.getNode();\n String allocationId = nodeShardState.allocationId();\n if (ignoreNodes.contains(node.getId())) {\n continue;\n }\n if (nodeShardState.storeException() == null) {\n if (allocationId == null) {\n logger.trace(\"[{}] on node [{}] has no shard state information\", shard, nodeShardState.getNode());\n } else {\n logger.trace(\"[{}] on node [{}] has allocation id [{}]\", shard, nodeShardState.getNode(), allocationId);\n }\n } else {\n final String finalAllocationId = allocationId;\n if (nodeShardState.storeException() instanceof ShardLockObtainFailedException) {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened as it's locked, treating as valid shard\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n } else {\n logger.trace(() -> new ParameterizedMessage(\"[{}] on node [{}] has allocation id [{}] but the store can not be \" + \"opened, treating as no allocation id\", shard, nodeShardState.getNode(), finalAllocationId), nodeShardState.storeException());\n allocationId = null;\n }\n }\n if (allocationId != null) {\n assert nodeShardState.storeException() == null || nodeShardState.storeException() instanceof ShardLockObtainFailedException : \"only allow store that can be opened or that throws a ShardLockObtainFailedException while being opened but got a \" + \"store throwing \" + nodeShardState.storeException();\n numberOfAllocationsFound++;\n if (matchAnyShard || inSyncAllocationIds.contains(nodeShardState.allocationId())) {\n nodeShardStates.add(nodeShardState);\n }\n }\n }\n // allocation preference\n final Comparator comparator;\n if (matchAnyShard) {\n // prefer shards with matching allocation ids\n Comparator matchingAllocationsFirst = Comparator.comparing((NodeGatewayStartedShards state) -> inSyncAllocationIds.contains(state.allocationId())).reversed();\n comparator = matchingAllocationsFirst.thenComparing(NO_STORE_EXCEPTION_FIRST_COMPARATOR).thenComparing(PRIMARY_FIRST_COMPARATOR);\n } else {\n comparator = NO_STORE_EXCEPTION_FIRST_COMPARATOR.thenComparing(PRIMARY_FIRST_COMPARATOR);\n }\n nodeShardStates.sort(comparator);\n if (logger.isTraceEnabled()) {\n logger.trace(\"{} candidates for allocation: {}\", shard, nodeShardStates.stream().map(s -> s.getNode().getName()).collect(Collectors.joining(\", \")));\n }\n return new NodeShardsResult(nodeShardStates, numberOfAllocationsFound);\n }\n\n /**\n * Split the list of node shard states into groups yes/no/throttle based on allocation deciders\n */\n private NodesToAllocate buildNodesToAllocate(RoutingAllocation allocation, List nodeShardStates, ShardRouting shardRouting, boolean forceAllocate) {\n List yesNodeShards = new ArrayList<>();\n List throttledNodeShards = new ArrayList<>();\n List noNodeShards = new ArrayList<>();\n for (NodeGatewayStartedShards nodeShardState : nodeShardStates) {\n RoutingNode node = allocation.routingNodes().node(nodeShardState.getNode().getId());\n if (node == null) {\n continue;\n }\n Decision decision = forceAllocate ? allocation.deciders().canForceAllocatePrimary(shardRouting, node, allocation) : allocation.deciders().canAllocate(shardRouting, node, allocation);\n DecidedNode decidedNode = new DecidedNode(nodeShardState, decision);\n if (decision.type() == Type.THROTTLE) {\n throttledNodeShards.add(decidedNode);\n } else if (decision.type() == Type.NO) {\n noNodeShards.add(decidedNode);\n } else {\n yesNodeShards.add(decidedNode);\n }\n }\n return new NodesToAllocate(Collections.unmodifiableList(yesNodeShards), Collections.unmodifiableList(throttledNodeShards), Collections.unmodifiableList(noNodeShards));\n }\n\n protected abstract FetchResult fetchData(ShardRouting shard, RoutingAllocation allocation);\n\n private static class NodeShardsResult {\n\n final List orderedAllocationCandidates;\n\n final int allocationsFound;\n\n NodeShardsResult(List orderedAllocationCandidates, int allocationsFound) {\n this.orderedAllocationCandidates = orderedAllocationCandidates;\n this.allocationsFound = allocationsFound;\n }\n }\n\n static class NodesToAllocate {\n\n final List yesNodeShards;\n\n final List throttleNodeShards;\n\n final List noNodeShards;\n\n NodesToAllocate(List yesNodeShards, List throttleNodeShards, List noNodeShards) {\n this.yesNodeShards = yesNodeShards;\n this.throttleNodeShards = throttleNodeShards;\n this.noNodeShards = noNodeShards;\n }\n }\n\n /**\n * This class encapsulates the shard state retrieved from a node and the decision that was made\n * by the allocator for allocating to the node that holds the shard copy.\n */\n private static class DecidedNode {\n\n final NodeGatewayStartedShards nodeShardState;\n\n final Decision decision;\n\n private DecidedNode(NodeGatewayStartedShards nodeShardState, Decision decision) {\n this.nodeShardState = nodeShardState;\n this.decision = decision;\n }\n }\n}\n"} {"task_id": "Java_910", "language": "Java", "task_type": "empty", "source_file": "java/github/justified/tedis/tedis-replicator/src/main/java/com/taobao/common/tedis/replicator/manage/OpenReplicatorPlugin.java", "mask_start_position": 714, "mask_end_position": 714, "canonical_solution": "", "pre_mask_code": "package com.taobao.common.tedis.replicator.manage;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport com.taobao.common.tedis.replicator.ReplicatorException;\nimport com.taobao.common.tedis.replicator.ReplicatorProperties;\nimport com.taobao.common.tedis.replicator.conf.ReplicatorRuntime;\n\npublic interface OpenReplicatorPlugin {\n\n public void prepare(ReplicatorContext context) throws ReplicatorException;\n\n public void release() throws ReplicatorException;\n\n public void configure(ReplicatorProperties properties) throws ReplicatorException;\n\n public void online(ReplicatorProperties params) throws Exception;\n\n public void offline(ReplicatorProperties params) throws Ex", "post_mask_code": "ception;\n\n public void offlineDeferred(ReplicatorProperties params) throws Exception;\n\n public String flush(long timeout) throws Exception;\n\n public boolean waitForAppliedEvent(String event, long timeout) throws Exception;\n\n public HashMap status() throws Exception;\n\n public List> statusList(String name) throws Exception;\n\n public static final String STATUS_LAST_APPLIED = \"last-applied\";\n\n public static final String STATUS_LAST_RECEIVED = \"last-received\";\n\n public ReplicatorRuntime getReplicatorRuntime();\n}\n"} {"task_id": "Java_911", "language": "Java", "task_type": "empty", "source_file": "java/github/PeteManchester/MediaPlayer/com.upnp.mediaplayer/src/org/rpi/channel/ChannelAV.java", "mask_start_position": 153, "mask_end_position": 153, "canonical_solution": "", "pre_mask_code": "package org.rpi.channel;\n\nimport org.apache.log4j.Logger;\n\npublic class ChannelAV extends ChannelBase {\n\n private static final Logger LOG = Logger.get", "post_mask_code": "Logger(ChannelPlayList.class);\n\n public ChannelAV(String uri, String metadata, int id) {\n super(uri, metadata, id);\n }\n}\n"} {"task_id": "Java_912", "language": "Java", "task_type": "method_signature", "source_file": "java/github/odnoklassniki/one-nio/src/one/nio/serial/DataStream.java", "mask_start_position": 1213, "mask_end_position": 1235, "canonical_solution": "public byte[] array() ", "pre_mask_code": "package one.nio.serial;\n\nimport one.nio.mem.DirectMemory;\nimport one.nio.util.Utf8;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport java.nio.ByteBuffer;\nimport static one.nio.util.JavaInternals.*;\n\npublic class DataStream implements ObjectInput, ObjectOutput {\n\n protected static final byte REF_NULL = -1;\n\n protected static final byte REF_RECURSIVE = -2;\n\n protected static final byte REF_RECURSIVE2 = -3;\n\n protected static final byte REF_EMBEDDED = -4;\n\n protected static final byte FIRST_APP_UID = -10;\n\n protected byte[] array;\n\n protected long address;\n\n protected long limit;\n\n protected long offset;\n\n public DataStream(int capacity) {\n this(new byte[capacity], byteArrayOffset, capacity);\n }\n\n public DataStream(byte[] array) {\n this(array, byteArrayOffset, array.length);\n }\n\n public DataStream(long address, long length) {\n this(null, address, length);\n }\n\n protected DataStream(byte[] array, long address, long length) {\n this.array = array;\n this.address = address;\n this.limit = address + length;\n this.offset = address;\n }\n\n ", "post_mask_code": "{\n return array;\n }\n\n public long address() {\n return address;\n }\n\n public int count() {\n return (int) (offset - address);\n }\n\n public void write(int b) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) b);\n }\n\n public void write(byte[] b) throws IOException {\n long offset = alloc(b.length);\n unsafe.copyMemory(b, byteArrayOffset, array, offset, b.length);\n }\n\n public void write(byte[] b, int off, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(b, byteArrayOffset + off, array, offset, len);\n }\n\n public void writeBoolean(boolean v) throws IOException {\n long offset = alloc(1);\n unsafe.putBoolean(array, offset, v);\n }\n\n public void writeByte(int v) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) v);\n }\n\n public void writeShort(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putShort(array, offset, Short.reverseBytes((short) v));\n }\n\n public void writeChar(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putChar(array, offset, Character.reverseBytes((char) v));\n }\n\n public void writeInt(int v) throws IOException {\n long offset = alloc(4);\n unsafe.putInt(array, offset, Integer.reverseBytes(v));\n }\n\n public void writeLong(long v) throws IOException {\n long offset = alloc(8);\n unsafe.putLong(array, offset, Long.reverseBytes(v));\n }\n\n public void writeFloat(float v) throws IOException {\n writeInt(Float.floatToRawIntBits(v));\n }\n\n public void writeDouble(double v) throws IOException {\n writeLong(Double.doubleToRawLongBits(v));\n }\n\n public void writeBytes(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length);\n for (int i = 0; i < length; i++) {\n unsafe.putByte(array, offset++, (byte) s.charAt(i));\n }\n }\n\n public void writeChars(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length * 2);\n for (int i = 0; i < length; i++) {\n unsafe.putChar(array, offset, Character.reverseBytes(s.charAt(i)));\n offset += 2;\n }\n }\n\n public void writeUTF(String s) throws IOException {\n int utfLength = Utf8.length(s);\n if (utfLength <= 0x7fff) {\n writeShort(utfLength);\n } else {\n writeInt(utfLength | 0x80000000);\n }\n long offset = alloc(utfLength);\n Utf8.write(s, array, offset);\n }\n\n @SuppressWarnings(\"unchecked\")\n public void writeObject(Object obj) throws IOException {\n if (obj == null) {\n writeByte(REF_NULL);\n } else {\n Serializer serializer = Repository.get(obj.getClass());\n if (serializer.uid < 0) {\n writeByte((byte) serializer.uid);\n } else {\n writeLong(serializer.uid);\n }\n serializer.write(obj, this);\n }\n }\n\n public void write(ByteBuffer src) throws IOException {\n int len = src.remaining();\n long offset = alloc(len);\n if (src.hasArray()) {\n unsafe.copyMemory(src.array(), byteArrayOffset + src.arrayOffset() + src.position(), array, offset, len);\n } else {\n unsafe.copyMemory(null, DirectMemory.getAddress(src) + src.position(), array, offset, len);\n }\n src.position(src.limit());\n }\n\n public void writeFrom(long address, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(null, address, array, offset, len);\n }\n\n public int read() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int read(byte[] b) throws IOException {\n readFully(b);\n return b.length;\n }\n\n public int read(byte[] b, int off, int len) throws IOException {\n readFully(b, off, len);\n return len;\n }\n\n public void readFully(byte[] b) throws IOException {\n unsafe.copyMemory(array, alloc(b.length), b, byteArrayOffset, b.length);\n }\n\n public void readFully(byte[] b, int off, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), b, byteArrayOffset + off, len);\n }\n\n public long skip(long n) throws IOException {\n alloc((int) n);\n return n;\n }\n\n public int skipBytes(int n) throws IOException {\n alloc(n);\n return n;\n }\n\n public boolean readBoolean() throws IOException {\n return unsafe.getBoolean(array, alloc(1));\n }\n\n public byte readByte() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int readUnsignedByte() throws IOException {\n return unsafe.getByte(array, alloc(1)) & 0xff;\n }\n\n public short readShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2)));\n }\n\n public int readUnsignedShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2))) & 0xffff;\n }\n\n public char readChar() throws IOException {\n return Character.reverseBytes(unsafe.getChar(array, alloc(2)));\n }\n\n public int readInt() throws IOException {\n return Integer.reverseBytes(unsafe.getInt(array, alloc(4)));\n }\n\n public long readLong() throws IOException {\n return Long.reverseBytes(unsafe.getLong(array, alloc(8)));\n }\n\n public float readFloat() throws IOException {\n return Float.intBitsToFloat(readInt());\n }\n\n public double readDouble() throws IOException {\n return Double.longBitsToDouble(readLong());\n }\n\n public String readLine() throws IOException {\n for (long ptr = offset; ptr < limit; ptr++) {\n if (unsafe.getByte(array, ptr) == '\\n') {\n int length = (int) (ptr - offset);\n int cr = length > 0 && unsafe.getByte(array, ptr - 1) == '\\r' ? 1 : 0;\n return Utf8.read(array, alloc(length + 1), length - cr);\n }\n }\n // The last line without CR\n int length = (int) (limit - offset);\n return length > 0 ? Utf8.read(array, alloc(length), length) : null;\n }\n\n public String readUTF() throws IOException {\n int length = readUnsignedShort();\n if (length == 0) {\n return \"\";\n }\n if (length > 0x7fff) {\n length = (length & 0x7fff) << 16 | readUnsignedShort();\n }\n return Utf8.read(array, alloc(length), length);\n }\n\n public Object readObject() throws IOException, ClassNotFoundException {\n Serializer serializer;\n byte b = readByte();\n if (b >= 0) {\n offset--;\n serializer = Repository.requestSerializer(readLong());\n } else if (b == REF_NULL) {\n return null;\n } else {\n serializer = Repository.requestBootstrapSerializer(b);\n }\n return serializer.read(this);\n }\n\n public void read(ByteBuffer dst) throws IOException {\n int len = dst.remaining();\n long offset = alloc(len);\n if (dst.hasArray()) {\n unsafe.copyMemory(array, offset, dst.array(), byteArrayOffset + dst.arrayOffset() + dst.position(), len);\n } else {\n unsafe.copyMemory(array, offset, null, DirectMemory.getAddress(dst) + dst.position(), len);\n }\n dst.position(dst.limit());\n }\n\n public void readTo(long address, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), null, address, len);\n }\n\n public ByteBuffer byteBuffer(int len) throws IOException {\n long offset = alloc(len);\n if (array != null) {\n return ByteBuffer.wrap(array, (int) (offset - byteArrayOffset), len);\n } else {\n return DirectMemory.wrap(offset, len);\n }\n }\n\n public int available() {\n return (int) (limit - offset);\n }\n\n public void flush() throws IOException {\n // Nothing to do\n }\n\n public void close() throws IOException {\n // Nothing to do\n }\n\n public void register(Object obj) {\n // Nothing to do\n }\n\n public Closeable newScope() {\n return null;\n }\n\n protected long alloc(int size) throws IOException {\n long currentOffset = offset;\n if ((offset = currentOffset + size) > limit) {\n throw new IndexOutOfBoundsException();\n }\n return currentOffset;\n }\n}\n"} {"task_id": "Java_913", "language": "Java", "task_type": "method_body", "source_file": "java/github/odnoklassniki/one-nio/src/one/nio/serial/DataStream.java", "mask_start_position": 4442, "mask_end_position": 4832, "canonical_solution": "{\n int len = src.remaining();\n long offset = alloc(len);\n if (src.hasArray()) {\n unsafe.copyMemory(src.array(), byteArrayOffset + src.arrayOffset() + src.position(), array, offset, len);\n } else {\n unsafe.copyMemory(null, DirectMemory.getAddress(src) + src.position(), array, offset, len);\n }\n src.position(src.limit());\n }", "pre_mask_code": "package one.nio.serial;\n\nimport one.nio.mem.DirectMemory;\nimport one.nio.util.Utf8;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport java.nio.ByteBuffer;\nimport static one.nio.util.JavaInternals.*;\n\npublic class DataStream implements ObjectInput, ObjectOutput {\n\n protected static final byte REF_NULL = -1;\n\n protected static final byte REF_RECURSIVE = -2;\n\n protected static final byte REF_RECURSIVE2 = -3;\n\n protected static final byte REF_EMBEDDED = -4;\n\n protected static final byte FIRST_APP_UID = -10;\n\n protected byte[] array;\n\n protected long address;\n\n protected long limit;\n\n protected long offset;\n\n public DataStream(int capacity) {\n this(new byte[capacity], byteArrayOffset, capacity);\n }\n\n public DataStream(byte[] array) {\n this(array, byteArrayOffset, array.length);\n }\n\n public DataStream(long address, long length) {\n this(null, address, length);\n }\n\n protected DataStream(byte[] array, long address, long length) {\n this.array = array;\n this.address = address;\n this.limit = address + length;\n this.offset = address;\n }\n\n public byte[] array() {\n return array;\n }\n\n public long address() {\n return address;\n }\n\n public int count() {\n return (int) (offset - address);\n }\n\n public void write(int b) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) b);\n }\n\n public void write(byte[] b) throws IOException {\n long offset = alloc(b.length);\n unsafe.copyMemory(b, byteArrayOffset, array, offset, b.length);\n }\n\n public void write(byte[] b, int off, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(b, byteArrayOffset + off, array, offset, len);\n }\n\n public void writeBoolean(boolean v) throws IOException {\n long offset = alloc(1);\n unsafe.putBoolean(array, offset, v);\n }\n\n public void writeByte(int v) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) v);\n }\n\n public void writeShort(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putShort(array, offset, Short.reverseBytes((short) v));\n }\n\n public void writeChar(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putChar(array, offset, Character.reverseBytes((char) v));\n }\n\n public void writeInt(int v) throws IOException {\n long offset = alloc(4);\n unsafe.putInt(array, offset, Integer.reverseBytes(v));\n }\n\n public void writeLong(long v) throws IOException {\n long offset = alloc(8);\n unsafe.putLong(array, offset, Long.reverseBytes(v));\n }\n\n public void writeFloat(float v) throws IOException {\n writeInt(Float.floatToRawIntBits(v));\n }\n\n public void writeDouble(double v) throws IOException {\n writeLong(Double.doubleToRawLongBits(v));\n }\n\n public void writeBytes(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length);\n for (int i = 0; i < length; i++) {\n unsafe.putByte(array, offset++, (byte) s.charAt(i));\n }\n }\n\n public void writeChars(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length * 2);\n for (int i = 0; i < length; i++) {\n unsafe.putChar(array, offset, Character.reverseBytes(s.charAt(i)));\n offset += 2;\n }\n }\n\n public void writeUTF(String s) throws IOException {\n int utfLength = Utf8.length(s);\n if (utfLength <= 0x7fff) {\n writeShort(utfLength);\n } else {\n writeInt(utfLength | 0x80000000);\n }\n long offset = alloc(utfLength);\n Utf8.write(s, array, offset);\n }\n\n @SuppressWarnings(\"unchecked\")\n public void writeObject(Object obj) throws IOException {\n if (obj == null) {\n writeByte(REF_NULL);\n } else {\n Serializer serializer = Repository.get(obj.getClass());\n if (serializer.uid < 0) {\n writeByte((byte) serializer.uid);\n } else {\n writeLong(serializer.uid);\n }\n serializer.write(obj, this);\n }\n }\n\n public void write(ByteBuffer src) throws IOException ", "post_mask_code": "\n\n public void writeFrom(long address, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(null, address, array, offset, len);\n }\n\n public int read() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int read(byte[] b) throws IOException {\n readFully(b);\n return b.length;\n }\n\n public int read(byte[] b, int off, int len) throws IOException {\n readFully(b, off, len);\n return len;\n }\n\n public void readFully(byte[] b) throws IOException {\n unsafe.copyMemory(array, alloc(b.length), b, byteArrayOffset, b.length);\n }\n\n public void readFully(byte[] b, int off, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), b, byteArrayOffset + off, len);\n }\n\n public long skip(long n) throws IOException {\n alloc((int) n);\n return n;\n }\n\n public int skipBytes(int n) throws IOException {\n alloc(n);\n return n;\n }\n\n public boolean readBoolean() throws IOException {\n return unsafe.getBoolean(array, alloc(1));\n }\n\n public byte readByte() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int readUnsignedByte() throws IOException {\n return unsafe.getByte(array, alloc(1)) & 0xff;\n }\n\n public short readShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2)));\n }\n\n public int readUnsignedShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2))) & 0xffff;\n }\n\n public char readChar() throws IOException {\n return Character.reverseBytes(unsafe.getChar(array, alloc(2)));\n }\n\n public int readInt() throws IOException {\n return Integer.reverseBytes(unsafe.getInt(array, alloc(4)));\n }\n\n public long readLong() throws IOException {\n return Long.reverseBytes(unsafe.getLong(array, alloc(8)));\n }\n\n public float readFloat() throws IOException {\n return Float.intBitsToFloat(readInt());\n }\n\n public double readDouble() throws IOException {\n return Double.longBitsToDouble(readLong());\n }\n\n public String readLine() throws IOException {\n for (long ptr = offset; ptr < limit; ptr++) {\n if (unsafe.getByte(array, ptr) == '\\n') {\n int length = (int) (ptr - offset);\n int cr = length > 0 && unsafe.getByte(array, ptr - 1) == '\\r' ? 1 : 0;\n return Utf8.read(array, alloc(length + 1), length - cr);\n }\n }\n // The last line without CR\n int length = (int) (limit - offset);\n return length > 0 ? Utf8.read(array, alloc(length), length) : null;\n }\n\n public String readUTF() throws IOException {\n int length = readUnsignedShort();\n if (length == 0) {\n return \"\";\n }\n if (length > 0x7fff) {\n length = (length & 0x7fff) << 16 | readUnsignedShort();\n }\n return Utf8.read(array, alloc(length), length);\n }\n\n public Object readObject() throws IOException, ClassNotFoundException {\n Serializer serializer;\n byte b = readByte();\n if (b >= 0) {\n offset--;\n serializer = Repository.requestSerializer(readLong());\n } else if (b == REF_NULL) {\n return null;\n } else {\n serializer = Repository.requestBootstrapSerializer(b);\n }\n return serializer.read(this);\n }\n\n public void read(ByteBuffer dst) throws IOException {\n int len = dst.remaining();\n long offset = alloc(len);\n if (dst.hasArray()) {\n unsafe.copyMemory(array, offset, dst.array(), byteArrayOffset + dst.arrayOffset() + dst.position(), len);\n } else {\n unsafe.copyMemory(array, offset, null, DirectMemory.getAddress(dst) + dst.position(), len);\n }\n dst.position(dst.limit());\n }\n\n public void readTo(long address, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), null, address, len);\n }\n\n public ByteBuffer byteBuffer(int len) throws IOException {\n long offset = alloc(len);\n if (array != null) {\n return ByteBuffer.wrap(array, (int) (offset - byteArrayOffset), len);\n } else {\n return DirectMemory.wrap(offset, len);\n }\n }\n\n public int available() {\n return (int) (limit - offset);\n }\n\n public void flush() throws IOException {\n // Nothing to do\n }\n\n public void close() throws IOException {\n // Nothing to do\n }\n\n public void register(Object obj) {\n // Nothing to do\n }\n\n public Closeable newScope() {\n return null;\n }\n\n protected long alloc(int size) throws IOException {\n long currentOffset = offset;\n if ((offset = currentOffset + size) > limit) {\n throw new IndexOutOfBoundsException();\n }\n return currentOffset;\n }\n}\n"} {"task_id": "Java_914", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/odnoklassniki/one-nio/src/one/nio/serial/DataStream.java", "mask_start_position": 3103, "mask_end_position": 3136, "canonical_solution": "\n int length = s.length();", "pre_mask_code": "package one.nio.serial;\n\nimport one.nio.mem.DirectMemory;\nimport one.nio.util.Utf8;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport java.nio.ByteBuffer;\nimport static one.nio.util.JavaInternals.*;\n\npublic class DataStream implements ObjectInput, ObjectOutput {\n\n protected static final byte REF_NULL = -1;\n\n protected static final byte REF_RECURSIVE = -2;\n\n protected static final byte REF_RECURSIVE2 = -3;\n\n protected static final byte REF_EMBEDDED = -4;\n\n protected static final byte FIRST_APP_UID = -10;\n\n protected byte[] array;\n\n protected long address;\n\n protected long limit;\n\n protected long offset;\n\n public DataStream(int capacity) {\n this(new byte[capacity], byteArrayOffset, capacity);\n }\n\n public DataStream(byte[] array) {\n this(array, byteArrayOffset, array.length);\n }\n\n public DataStream(long address, long length) {\n this(null, address, length);\n }\n\n protected DataStream(byte[] array, long address, long length) {\n this.array = array;\n this.address = address;\n this.limit = address + length;\n this.offset = address;\n }\n\n public byte[] array() {\n return array;\n }\n\n public long address() {\n return address;\n }\n\n public int count() {\n return (int) (offset - address);\n }\n\n public void write(int b) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) b);\n }\n\n public void write(byte[] b) throws IOException {\n long offset = alloc(b.length);\n unsafe.copyMemory(b, byteArrayOffset, array, offset, b.length);\n }\n\n public void write(byte[] b, int off, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(b, byteArrayOffset + off, array, offset, len);\n }\n\n public void writeBoolean(boolean v) throws IOException {\n long offset = alloc(1);\n unsafe.putBoolean(array, offset, v);\n }\n\n public void writeByte(int v) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) v);\n }\n\n public void writeShort(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putShort(array, offset, Short.reverseBytes((short) v));\n }\n\n public void writeChar(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putChar(array, offset, Character.reverseBytes((char) v));\n }\n\n public void writeInt(int v) throws IOException {\n long offset = alloc(4);\n unsafe.putInt(array, offset, Integer.reverseBytes(v));\n }\n\n public void writeLong(long v) throws IOException {\n long offset = alloc(8);\n unsafe.putLong(array, offset, Long.reverseBytes(v));\n }\n\n public void writeFloat(float v) throws IOException {\n writeInt(Float.floatToRawIntBits(v));\n }\n\n public void writeDouble(double v) throws IOException {\n writeLong(Double.doubleToRawLongBits(v));\n }\n\n public void writeBytes(String s) throws IOException {", "post_mask_code": "\n long offset = alloc(length);\n for (int i = 0; i < length; i++) {\n unsafe.putByte(array, offset++, (byte) s.charAt(i));\n }\n }\n\n public void writeChars(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length * 2);\n for (int i = 0; i < length; i++) {\n unsafe.putChar(array, offset, Character.reverseBytes(s.charAt(i)));\n offset += 2;\n }\n }\n\n public void writeUTF(String s) throws IOException {\n int utfLength = Utf8.length(s);\n if (utfLength <= 0x7fff) {\n writeShort(utfLength);\n } else {\n writeInt(utfLength | 0x80000000);\n }\n long offset = alloc(utfLength);\n Utf8.write(s, array, offset);\n }\n\n @SuppressWarnings(\"unchecked\")\n public void writeObject(Object obj) throws IOException {\n if (obj == null) {\n writeByte(REF_NULL);\n } else {\n Serializer serializer = Repository.get(obj.getClass());\n if (serializer.uid < 0) {\n writeByte((byte) serializer.uid);\n } else {\n writeLong(serializer.uid);\n }\n serializer.write(obj, this);\n }\n }\n\n public void write(ByteBuffer src) throws IOException {\n int len = src.remaining();\n long offset = alloc(len);\n if (src.hasArray()) {\n unsafe.copyMemory(src.array(), byteArrayOffset + src.arrayOffset() + src.position(), array, offset, len);\n } else {\n unsafe.copyMemory(null, DirectMemory.getAddress(src) + src.position(), array, offset, len);\n }\n src.position(src.limit());\n }\n\n public void writeFrom(long address, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(null, address, array, offset, len);\n }\n\n public int read() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int read(byte[] b) throws IOException {\n readFully(b);\n return b.length;\n }\n\n public int read(byte[] b, int off, int len) throws IOException {\n readFully(b, off, len);\n return len;\n }\n\n public void readFully(byte[] b) throws IOException {\n unsafe.copyMemory(array, alloc(b.length), b, byteArrayOffset, b.length);\n }\n\n public void readFully(byte[] b, int off, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), b, byteArrayOffset + off, len);\n }\n\n public long skip(long n) throws IOException {\n alloc((int) n);\n return n;\n }\n\n public int skipBytes(int n) throws IOException {\n alloc(n);\n return n;\n }\n\n public boolean readBoolean() throws IOException {\n return unsafe.getBoolean(array, alloc(1));\n }\n\n public byte readByte() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int readUnsignedByte() throws IOException {\n return unsafe.getByte(array, alloc(1)) & 0xff;\n }\n\n public short readShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2)));\n }\n\n public int readUnsignedShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2))) & 0xffff;\n }\n\n public char readChar() throws IOException {\n return Character.reverseBytes(unsafe.getChar(array, alloc(2)));\n }\n\n public int readInt() throws IOException {\n return Integer.reverseBytes(unsafe.getInt(array, alloc(4)));\n }\n\n public long readLong() throws IOException {\n return Long.reverseBytes(unsafe.getLong(array, alloc(8)));\n }\n\n public float readFloat() throws IOException {\n return Float.intBitsToFloat(readInt());\n }\n\n public double readDouble() throws IOException {\n return Double.longBitsToDouble(readLong());\n }\n\n public String readLine() throws IOException {\n for (long ptr = offset; ptr < limit; ptr++) {\n if (unsafe.getByte(array, ptr) == '\\n') {\n int length = (int) (ptr - offset);\n int cr = length > 0 && unsafe.getByte(array, ptr - 1) == '\\r' ? 1 : 0;\n return Utf8.read(array, alloc(length + 1), length - cr);\n }\n }\n // The last line without CR\n int length = (int) (limit - offset);\n return length > 0 ? Utf8.read(array, alloc(length), length) : null;\n }\n\n public String readUTF() throws IOException {\n int length = readUnsignedShort();\n if (length == 0) {\n return \"\";\n }\n if (length > 0x7fff) {\n length = (length & 0x7fff) << 16 | readUnsignedShort();\n }\n return Utf8.read(array, alloc(length), length);\n }\n\n public Object readObject() throws IOException, ClassNotFoundException {\n Serializer serializer;\n byte b = readByte();\n if (b >= 0) {\n offset--;\n serializer = Repository.requestSerializer(readLong());\n } else if (b == REF_NULL) {\n return null;\n } else {\n serializer = Repository.requestBootstrapSerializer(b);\n }\n return serializer.read(this);\n }\n\n public void read(ByteBuffer dst) throws IOException {\n int len = dst.remaining();\n long offset = alloc(len);\n if (dst.hasArray()) {\n unsafe.copyMemory(array, offset, dst.array(), byteArrayOffset + dst.arrayOffset() + dst.position(), len);\n } else {\n unsafe.copyMemory(array, offset, null, DirectMemory.getAddress(dst) + dst.position(), len);\n }\n dst.position(dst.limit());\n }\n\n public void readTo(long address, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), null, address, len);\n }\n\n public ByteBuffer byteBuffer(int len) throws IOException {\n long offset = alloc(len);\n if (array != null) {\n return ByteBuffer.wrap(array, (int) (offset - byteArrayOffset), len);\n } else {\n return DirectMemory.wrap(offset, len);\n }\n }\n\n public int available() {\n return (int) (limit - offset);\n }\n\n public void flush() throws IOException {\n // Nothing to do\n }\n\n public void close() throws IOException {\n // Nothing to do\n }\n\n public void register(Object obj) {\n // Nothing to do\n }\n\n public Closeable newScope() {\n return null;\n }\n\n protected long alloc(int size) throws IOException {\n long currentOffset = offset;\n if ((offset = currentOffset + size) > limit) {\n throw new IndexOutOfBoundsException();\n }\n return currentOffset;\n }\n}\n"} {"task_id": "Java_915", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/odnoklassniki/one-nio/src/one/nio/serial/DataStream.java", "mask_start_position": 3145, "mask_end_position": 3173, "canonical_solution": "long offset = alloc(length);", "pre_mask_code": "package one.nio.serial;\n\nimport one.nio.mem.DirectMemory;\nimport one.nio.util.Utf8;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport java.nio.ByteBuffer;\nimport static one.nio.util.JavaInternals.*;\n\npublic class DataStream implements ObjectInput, ObjectOutput {\n\n protected static final byte REF_NULL = -1;\n\n protected static final byte REF_RECURSIVE = -2;\n\n protected static final byte REF_RECURSIVE2 = -3;\n\n protected static final byte REF_EMBEDDED = -4;\n\n protected static final byte FIRST_APP_UID = -10;\n\n protected byte[] array;\n\n protected long address;\n\n protected long limit;\n\n protected long offset;\n\n public DataStream(int capacity) {\n this(new byte[capacity], byteArrayOffset, capacity);\n }\n\n public DataStream(byte[] array) {\n this(array, byteArrayOffset, array.length);\n }\n\n public DataStream(long address, long length) {\n this(null, address, length);\n }\n\n protected DataStream(byte[] array, long address, long length) {\n this.array = array;\n this.address = address;\n this.limit = address + length;\n this.offset = address;\n }\n\n public byte[] array() {\n return array;\n }\n\n public long address() {\n return address;\n }\n\n public int count() {\n return (int) (offset - address);\n }\n\n public void write(int b) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) b);\n }\n\n public void write(byte[] b) throws IOException {\n long offset = alloc(b.length);\n unsafe.copyMemory(b, byteArrayOffset, array, offset, b.length);\n }\n\n public void write(byte[] b, int off, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(b, byteArrayOffset + off, array, offset, len);\n }\n\n public void writeBoolean(boolean v) throws IOException {\n long offset = alloc(1);\n unsafe.putBoolean(array, offset, v);\n }\n\n public void writeByte(int v) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) v);\n }\n\n public void writeShort(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putShort(array, offset, Short.reverseBytes((short) v));\n }\n\n public void writeChar(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putChar(array, offset, Character.reverseBytes((char) v));\n }\n\n public void writeInt(int v) throws IOException {\n long offset = alloc(4);\n unsafe.putInt(array, offset, Integer.reverseBytes(v));\n }\n\n public void writeLong(long v) throws IOException {\n long offset = alloc(8);\n unsafe.putLong(array, offset, Long.reverseBytes(v));\n }\n\n public void writeFloat(float v) throws IOException {\n writeInt(Float.floatToRawIntBits(v));\n }\n\n public void writeDouble(double v) throws IOException {\n writeLong(Double.doubleToRawLongBits(v));\n }\n\n public void writeBytes(String s) throws IOException {\n int length = s.length();\n ", "post_mask_code": "\n for (int i = 0; i < length; i++) {\n unsafe.putByte(array, offset++, (byte) s.charAt(i));\n }\n }\n\n public void writeChars(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length * 2);\n for (int i = 0; i < length; i++) {\n unsafe.putChar(array, offset, Character.reverseBytes(s.charAt(i)));\n offset += 2;\n }\n }\n\n public void writeUTF(String s) throws IOException {\n int utfLength = Utf8.length(s);\n if (utfLength <= 0x7fff) {\n writeShort(utfLength);\n } else {\n writeInt(utfLength | 0x80000000);\n }\n long offset = alloc(utfLength);\n Utf8.write(s, array, offset);\n }\n\n @SuppressWarnings(\"unchecked\")\n public void writeObject(Object obj) throws IOException {\n if (obj == null) {\n writeByte(REF_NULL);\n } else {\n Serializer serializer = Repository.get(obj.getClass());\n if (serializer.uid < 0) {\n writeByte((byte) serializer.uid);\n } else {\n writeLong(serializer.uid);\n }\n serializer.write(obj, this);\n }\n }\n\n public void write(ByteBuffer src) throws IOException {\n int len = src.remaining();\n long offset = alloc(len);\n if (src.hasArray()) {\n unsafe.copyMemory(src.array(), byteArrayOffset + src.arrayOffset() + src.position(), array, offset, len);\n } else {\n unsafe.copyMemory(null, DirectMemory.getAddress(src) + src.position(), array, offset, len);\n }\n src.position(src.limit());\n }\n\n public void writeFrom(long address, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(null, address, array, offset, len);\n }\n\n public int read() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int read(byte[] b) throws IOException {\n readFully(b);\n return b.length;\n }\n\n public int read(byte[] b, int off, int len) throws IOException {\n readFully(b, off, len);\n return len;\n }\n\n public void readFully(byte[] b) throws IOException {\n unsafe.copyMemory(array, alloc(b.length), b, byteArrayOffset, b.length);\n }\n\n public void readFully(byte[] b, int off, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), b, byteArrayOffset + off, len);\n }\n\n public long skip(long n) throws IOException {\n alloc((int) n);\n return n;\n }\n\n public int skipBytes(int n) throws IOException {\n alloc(n);\n return n;\n }\n\n public boolean readBoolean() throws IOException {\n return unsafe.getBoolean(array, alloc(1));\n }\n\n public byte readByte() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int readUnsignedByte() throws IOException {\n return unsafe.getByte(array, alloc(1)) & 0xff;\n }\n\n public short readShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2)));\n }\n\n public int readUnsignedShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2))) & 0xffff;\n }\n\n public char readChar() throws IOException {\n return Character.reverseBytes(unsafe.getChar(array, alloc(2)));\n }\n\n public int readInt() throws IOException {\n return Integer.reverseBytes(unsafe.getInt(array, alloc(4)));\n }\n\n public long readLong() throws IOException {\n return Long.reverseBytes(unsafe.getLong(array, alloc(8)));\n }\n\n public float readFloat() throws IOException {\n return Float.intBitsToFloat(readInt());\n }\n\n public double readDouble() throws IOException {\n return Double.longBitsToDouble(readLong());\n }\n\n public String readLine() throws IOException {\n for (long ptr = offset; ptr < limit; ptr++) {\n if (unsafe.getByte(array, ptr) == '\\n') {\n int length = (int) (ptr - offset);\n int cr = length > 0 && unsafe.getByte(array, ptr - 1) == '\\r' ? 1 : 0;\n return Utf8.read(array, alloc(length + 1), length - cr);\n }\n }\n // The last line without CR\n int length = (int) (limit - offset);\n return length > 0 ? Utf8.read(array, alloc(length), length) : null;\n }\n\n public String readUTF() throws IOException {\n int length = readUnsignedShort();\n if (length == 0) {\n return \"\";\n }\n if (length > 0x7fff) {\n length = (length & 0x7fff) << 16 | readUnsignedShort();\n }\n return Utf8.read(array, alloc(length), length);\n }\n\n public Object readObject() throws IOException, ClassNotFoundException {\n Serializer serializer;\n byte b = readByte();\n if (b >= 0) {\n offset--;\n serializer = Repository.requestSerializer(readLong());\n } else if (b == REF_NULL) {\n return null;\n } else {\n serializer = Repository.requestBootstrapSerializer(b);\n }\n return serializer.read(this);\n }\n\n public void read(ByteBuffer dst) throws IOException {\n int len = dst.remaining();\n long offset = alloc(len);\n if (dst.hasArray()) {\n unsafe.copyMemory(array, offset, dst.array(), byteArrayOffset + dst.arrayOffset() + dst.position(), len);\n } else {\n unsafe.copyMemory(array, offset, null, DirectMemory.getAddress(dst) + dst.position(), len);\n }\n dst.position(dst.limit());\n }\n\n public void readTo(long address, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), null, address, len);\n }\n\n public ByteBuffer byteBuffer(int len) throws IOException {\n long offset = alloc(len);\n if (array != null) {\n return ByteBuffer.wrap(array, (int) (offset - byteArrayOffset), len);\n } else {\n return DirectMemory.wrap(offset, len);\n }\n }\n\n public int available() {\n return (int) (limit - offset);\n }\n\n public void flush() throws IOException {\n // Nothing to do\n }\n\n public void close() throws IOException {\n // Nothing to do\n }\n\n public void register(Object obj) {\n // Nothing to do\n }\n\n public Closeable newScope() {\n return null;\n }\n\n protected long alloc(int size) throws IOException {\n long currentOffset = offset;\n if ((offset = currentOffset + size) > limit) {\n throw new IndexOutOfBoundsException();\n }\n return currentOffset;\n }\n}\n"} {"task_id": "Java_916", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/odnoklassniki/one-nio/src/one/nio/serial/DataStream.java", "mask_start_position": 3182, "mask_end_position": 3297, "canonical_solution": "for (int i = 0; i < length; i++) {\n unsafe.putByte(array, offset++, (byte) s.charAt(i));\n }\n }", "pre_mask_code": "package one.nio.serial;\n\nimport one.nio.mem.DirectMemory;\nimport one.nio.util.Utf8;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport java.nio.ByteBuffer;\nimport static one.nio.util.JavaInternals.*;\n\npublic class DataStream implements ObjectInput, ObjectOutput {\n\n protected static final byte REF_NULL = -1;\n\n protected static final byte REF_RECURSIVE = -2;\n\n protected static final byte REF_RECURSIVE2 = -3;\n\n protected static final byte REF_EMBEDDED = -4;\n\n protected static final byte FIRST_APP_UID = -10;\n\n protected byte[] array;\n\n protected long address;\n\n protected long limit;\n\n protected long offset;\n\n public DataStream(int capacity) {\n this(new byte[capacity], byteArrayOffset, capacity);\n }\n\n public DataStream(byte[] array) {\n this(array, byteArrayOffset, array.length);\n }\n\n public DataStream(long address, long length) {\n this(null, address, length);\n }\n\n protected DataStream(byte[] array, long address, long length) {\n this.array = array;\n this.address = address;\n this.limit = address + length;\n this.offset = address;\n }\n\n public byte[] array() {\n return array;\n }\n\n public long address() {\n return address;\n }\n\n public int count() {\n return (int) (offset - address);\n }\n\n public void write(int b) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) b);\n }\n\n public void write(byte[] b) throws IOException {\n long offset = alloc(b.length);\n unsafe.copyMemory(b, byteArrayOffset, array, offset, b.length);\n }\n\n public void write(byte[] b, int off, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(b, byteArrayOffset + off, array, offset, len);\n }\n\n public void writeBoolean(boolean v) throws IOException {\n long offset = alloc(1);\n unsafe.putBoolean(array, offset, v);\n }\n\n public void writeByte(int v) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) v);\n }\n\n public void writeShort(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putShort(array, offset, Short.reverseBytes((short) v));\n }\n\n public void writeChar(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putChar(array, offset, Character.reverseBytes((char) v));\n }\n\n public void writeInt(int v) throws IOException {\n long offset = alloc(4);\n unsafe.putInt(array, offset, Integer.reverseBytes(v));\n }\n\n public void writeLong(long v) throws IOException {\n long offset = alloc(8);\n unsafe.putLong(array, offset, Long.reverseBytes(v));\n }\n\n public void writeFloat(float v) throws IOException {\n writeInt(Float.floatToRawIntBits(v));\n }\n\n public void writeDouble(double v) throws IOException {\n writeLong(Double.doubleToRawLongBits(v));\n }\n\n public void writeBytes(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length);\n ", "post_mask_code": "\n\n public void writeChars(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length * 2);\n for (int i = 0; i < length; i++) {\n unsafe.putChar(array, offset, Character.reverseBytes(s.charAt(i)));\n offset += 2;\n }\n }\n\n public void writeUTF(String s) throws IOException {\n int utfLength = Utf8.length(s);\n if (utfLength <= 0x7fff) {\n writeShort(utfLength);\n } else {\n writeInt(utfLength | 0x80000000);\n }\n long offset = alloc(utfLength);\n Utf8.write(s, array, offset);\n }\n\n @SuppressWarnings(\"unchecked\")\n public void writeObject(Object obj) throws IOException {\n if (obj == null) {\n writeByte(REF_NULL);\n } else {\n Serializer serializer = Repository.get(obj.getClass());\n if (serializer.uid < 0) {\n writeByte((byte) serializer.uid);\n } else {\n writeLong(serializer.uid);\n }\n serializer.write(obj, this);\n }\n }\n\n public void write(ByteBuffer src) throws IOException {\n int len = src.remaining();\n long offset = alloc(len);\n if (src.hasArray()) {\n unsafe.copyMemory(src.array(), byteArrayOffset + src.arrayOffset() + src.position(), array, offset, len);\n } else {\n unsafe.copyMemory(null, DirectMemory.getAddress(src) + src.position(), array, offset, len);\n }\n src.position(src.limit());\n }\n\n public void writeFrom(long address, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(null, address, array, offset, len);\n }\n\n public int read() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int read(byte[] b) throws IOException {\n readFully(b);\n return b.length;\n }\n\n public int read(byte[] b, int off, int len) throws IOException {\n readFully(b, off, len);\n return len;\n }\n\n public void readFully(byte[] b) throws IOException {\n unsafe.copyMemory(array, alloc(b.length), b, byteArrayOffset, b.length);\n }\n\n public void readFully(byte[] b, int off, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), b, byteArrayOffset + off, len);\n }\n\n public long skip(long n) throws IOException {\n alloc((int) n);\n return n;\n }\n\n public int skipBytes(int n) throws IOException {\n alloc(n);\n return n;\n }\n\n public boolean readBoolean() throws IOException {\n return unsafe.getBoolean(array, alloc(1));\n }\n\n public byte readByte() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int readUnsignedByte() throws IOException {\n return unsafe.getByte(array, alloc(1)) & 0xff;\n }\n\n public short readShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2)));\n }\n\n public int readUnsignedShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2))) & 0xffff;\n }\n\n public char readChar() throws IOException {\n return Character.reverseBytes(unsafe.getChar(array, alloc(2)));\n }\n\n public int readInt() throws IOException {\n return Integer.reverseBytes(unsafe.getInt(array, alloc(4)));\n }\n\n public long readLong() throws IOException {\n return Long.reverseBytes(unsafe.getLong(array, alloc(8)));\n }\n\n public float readFloat() throws IOException {\n return Float.intBitsToFloat(readInt());\n }\n\n public double readDouble() throws IOException {\n return Double.longBitsToDouble(readLong());\n }\n\n public String readLine() throws IOException {\n for (long ptr = offset; ptr < limit; ptr++) {\n if (unsafe.getByte(array, ptr) == '\\n') {\n int length = (int) (ptr - offset);\n int cr = length > 0 && unsafe.getByte(array, ptr - 1) == '\\r' ? 1 : 0;\n return Utf8.read(array, alloc(length + 1), length - cr);\n }\n }\n // The last line without CR\n int length = (int) (limit - offset);\n return length > 0 ? Utf8.read(array, alloc(length), length) : null;\n }\n\n public String readUTF() throws IOException {\n int length = readUnsignedShort();\n if (length == 0) {\n return \"\";\n }\n if (length > 0x7fff) {\n length = (length & 0x7fff) << 16 | readUnsignedShort();\n }\n return Utf8.read(array, alloc(length), length);\n }\n\n public Object readObject() throws IOException, ClassNotFoundException {\n Serializer serializer;\n byte b = readByte();\n if (b >= 0) {\n offset--;\n serializer = Repository.requestSerializer(readLong());\n } else if (b == REF_NULL) {\n return null;\n } else {\n serializer = Repository.requestBootstrapSerializer(b);\n }\n return serializer.read(this);\n }\n\n public void read(ByteBuffer dst) throws IOException {\n int len = dst.remaining();\n long offset = alloc(len);\n if (dst.hasArray()) {\n unsafe.copyMemory(array, offset, dst.array(), byteArrayOffset + dst.arrayOffset() + dst.position(), len);\n } else {\n unsafe.copyMemory(array, offset, null, DirectMemory.getAddress(dst) + dst.position(), len);\n }\n dst.position(dst.limit());\n }\n\n public void readTo(long address, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), null, address, len);\n }\n\n public ByteBuffer byteBuffer(int len) throws IOException {\n long offset = alloc(len);\n if (array != null) {\n return ByteBuffer.wrap(array, (int) (offset - byteArrayOffset), len);\n } else {\n return DirectMemory.wrap(offset, len);\n }\n }\n\n public int available() {\n return (int) (limit - offset);\n }\n\n public void flush() throws IOException {\n // Nothing to do\n }\n\n public void close() throws IOException {\n // Nothing to do\n }\n\n public void register(Object obj) {\n // Nothing to do\n }\n\n public Closeable newScope() {\n return null;\n }\n\n protected long alloc(int size) throws IOException {\n long currentOffset = offset;\n if ((offset = currentOffset + size) > limit) {\n throw new IndexOutOfBoundsException();\n }\n return currentOffset;\n }\n}\n"} {"task_id": "Java_917", "language": "Java", "task_type": "single_line", "source_file": "java/github/odnoklassniki/one-nio/src/one/nio/serial/DataStream.java", "mask_start_position": 6419, "mask_end_position": 6428, "canonical_solution": "& 0xffff;", "pre_mask_code": "package one.nio.serial;\n\nimport one.nio.mem.DirectMemory;\nimport one.nio.util.Utf8;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport java.nio.ByteBuffer;\nimport static one.nio.util.JavaInternals.*;\n\npublic class DataStream implements ObjectInput, ObjectOutput {\n\n protected static final byte REF_NULL = -1;\n\n protected static final byte REF_RECURSIVE = -2;\n\n protected static final byte REF_RECURSIVE2 = -3;\n\n protected static final byte REF_EMBEDDED = -4;\n\n protected static final byte FIRST_APP_UID = -10;\n\n protected byte[] array;\n\n protected long address;\n\n protected long limit;\n\n protected long offset;\n\n public DataStream(int capacity) {\n this(new byte[capacity], byteArrayOffset, capacity);\n }\n\n public DataStream(byte[] array) {\n this(array, byteArrayOffset, array.length);\n }\n\n public DataStream(long address, long length) {\n this(null, address, length);\n }\n\n protected DataStream(byte[] array, long address, long length) {\n this.array = array;\n this.address = address;\n this.limit = address + length;\n this.offset = address;\n }\n\n public byte[] array() {\n return array;\n }\n\n public long address() {\n return address;\n }\n\n public int count() {\n return (int) (offset - address);\n }\n\n public void write(int b) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) b);\n }\n\n public void write(byte[] b) throws IOException {\n long offset = alloc(b.length);\n unsafe.copyMemory(b, byteArrayOffset, array, offset, b.length);\n }\n\n public void write(byte[] b, int off, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(b, byteArrayOffset + off, array, offset, len);\n }\n\n public void writeBoolean(boolean v) throws IOException {\n long offset = alloc(1);\n unsafe.putBoolean(array, offset, v);\n }\n\n public void writeByte(int v) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) v);\n }\n\n public void writeShort(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putShort(array, offset, Short.reverseBytes((short) v));\n }\n\n public void writeChar(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putChar(array, offset, Character.reverseBytes((char) v));\n }\n\n public void writeInt(int v) throws IOException {\n long offset = alloc(4);\n unsafe.putInt(array, offset, Integer.reverseBytes(v));\n }\n\n public void writeLong(long v) throws IOException {\n long offset = alloc(8);\n unsafe.putLong(array, offset, Long.reverseBytes(v));\n }\n\n public void writeFloat(float v) throws IOException {\n writeInt(Float.floatToRawIntBits(v));\n }\n\n public void writeDouble(double v) throws IOException {\n writeLong(Double.doubleToRawLongBits(v));\n }\n\n public void writeBytes(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length);\n for (int i = 0; i < length; i++) {\n unsafe.putByte(array, offset++, (byte) s.charAt(i));\n }\n }\n\n public void writeChars(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length * 2);\n for (int i = 0; i < length; i++) {\n unsafe.putChar(array, offset, Character.reverseBytes(s.charAt(i)));\n offset += 2;\n }\n }\n\n public void writeUTF(String s) throws IOException {\n int utfLength = Utf8.length(s);\n if (utfLength <= 0x7fff) {\n writeShort(utfLength);\n } else {\n writeInt(utfLength | 0x80000000);\n }\n long offset = alloc(utfLength);\n Utf8.write(s, array, offset);\n }\n\n @SuppressWarnings(\"unchecked\")\n public void writeObject(Object obj) throws IOException {\n if (obj == null) {\n writeByte(REF_NULL);\n } else {\n Serializer serializer = Repository.get(obj.getClass());\n if (serializer.uid < 0) {\n writeByte((byte) serializer.uid);\n } else {\n writeLong(serializer.uid);\n }\n serializer.write(obj, this);\n }\n }\n\n public void write(ByteBuffer src) throws IOException {\n int len = src.remaining();\n long offset = alloc(len);\n if (src.hasArray()) {\n unsafe.copyMemory(src.array(), byteArrayOffset + src.arrayOffset() + src.position(), array, offset, len);\n } else {\n unsafe.copyMemory(null, DirectMemory.getAddress(src) + src.position(), array, offset, len);\n }\n src.position(src.limit());\n }\n\n public void writeFrom(long address, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(null, address, array, offset, len);\n }\n\n public int read() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int read(byte[] b) throws IOException {\n readFully(b);\n return b.length;\n }\n\n public int read(byte[] b, int off, int len) throws IOException {\n readFully(b, off, len);\n return len;\n }\n\n public void readFully(byte[] b) throws IOException {\n unsafe.copyMemory(array, alloc(b.length), b, byteArrayOffset, b.length);\n }\n\n public void readFully(byte[] b, int off, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), b, byteArrayOffset + off, len);\n }\n\n public long skip(long n) throws IOException {\n alloc((int) n);\n return n;\n }\n\n public int skipBytes(int n) throws IOException {\n alloc(n);\n return n;\n }\n\n public boolean readBoolean() throws IOException {\n return unsafe.getBoolean(array, alloc(1));\n }\n\n public byte readByte() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int readUnsignedByte() throws IOException {\n return unsafe.getByte(array, alloc(1)) & 0xff;\n }\n\n public short readShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2)));\n }\n\n public int readUnsignedShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2))) ", "post_mask_code": "\n }\n\n public char readChar() throws IOException {\n return Character.reverseBytes(unsafe.getChar(array, alloc(2)));\n }\n\n public int readInt() throws IOException {\n return Integer.reverseBytes(unsafe.getInt(array, alloc(4)));\n }\n\n public long readLong() throws IOException {\n return Long.reverseBytes(unsafe.getLong(array, alloc(8)));\n }\n\n public float readFloat() throws IOException {\n return Float.intBitsToFloat(readInt());\n }\n\n public double readDouble() throws IOException {\n return Double.longBitsToDouble(readLong());\n }\n\n public String readLine() throws IOException {\n for (long ptr = offset; ptr < limit; ptr++) {\n if (unsafe.getByte(array, ptr) == '\\n') {\n int length = (int) (ptr - offset);\n int cr = length > 0 && unsafe.getByte(array, ptr - 1) == '\\r' ? 1 : 0;\n return Utf8.read(array, alloc(length + 1), length - cr);\n }\n }\n // The last line without CR\n int length = (int) (limit - offset);\n return length > 0 ? Utf8.read(array, alloc(length), length) : null;\n }\n\n public String readUTF() throws IOException {\n int length = readUnsignedShort();\n if (length == 0) {\n return \"\";\n }\n if (length > 0x7fff) {\n length = (length & 0x7fff) << 16 | readUnsignedShort();\n }\n return Utf8.read(array, alloc(length), length);\n }\n\n public Object readObject() throws IOException, ClassNotFoundException {\n Serializer serializer;\n byte b = readByte();\n if (b >= 0) {\n offset--;\n serializer = Repository.requestSerializer(readLong());\n } else if (b == REF_NULL) {\n return null;\n } else {\n serializer = Repository.requestBootstrapSerializer(b);\n }\n return serializer.read(this);\n }\n\n public void read(ByteBuffer dst) throws IOException {\n int len = dst.remaining();\n long offset = alloc(len);\n if (dst.hasArray()) {\n unsafe.copyMemory(array, offset, dst.array(), byteArrayOffset + dst.arrayOffset() + dst.position(), len);\n } else {\n unsafe.copyMemory(array, offset, null, DirectMemory.getAddress(dst) + dst.position(), len);\n }\n dst.position(dst.limit());\n }\n\n public void readTo(long address, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), null, address, len);\n }\n\n public ByteBuffer byteBuffer(int len) throws IOException {\n long offset = alloc(len);\n if (array != null) {\n return ByteBuffer.wrap(array, (int) (offset - byteArrayOffset), len);\n } else {\n return DirectMemory.wrap(offset, len);\n }\n }\n\n public int available() {\n return (int) (limit - offset);\n }\n\n public void flush() throws IOException {\n // Nothing to do\n }\n\n public void close() throws IOException {\n // Nothing to do\n }\n\n public void register(Object obj) {\n // Nothing to do\n }\n\n public Closeable newScope() {\n return null;\n }\n\n protected long alloc(int size) throws IOException {\n long currentOffset = offset;\n if ((offset = currentOffset + size) > limit) {\n throw new IndexOutOfBoundsException();\n }\n return currentOffset;\n }\n}\n"} {"task_id": "Java_918", "language": "Java", "task_type": "if_statement", "source_file": "java/github/odnoklassniki/one-nio/src/one/nio/serial/DataStream.java", "mask_start_position": 9694, "mask_end_position": 9801, "canonical_solution": "if ((offset = currentOffset + size) > limit) {\n throw new IndexOutOfBoundsException();\n }", "pre_mask_code": "package one.nio.serial;\n\nimport one.nio.mem.DirectMemory;\nimport one.nio.util.Utf8;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport java.nio.ByteBuffer;\nimport static one.nio.util.JavaInternals.*;\n\npublic class DataStream implements ObjectInput, ObjectOutput {\n\n protected static final byte REF_NULL = -1;\n\n protected static final byte REF_RECURSIVE = -2;\n\n protected static final byte REF_RECURSIVE2 = -3;\n\n protected static final byte REF_EMBEDDED = -4;\n\n protected static final byte FIRST_APP_UID = -10;\n\n protected byte[] array;\n\n protected long address;\n\n protected long limit;\n\n protected long offset;\n\n public DataStream(int capacity) {\n this(new byte[capacity], byteArrayOffset, capacity);\n }\n\n public DataStream(byte[] array) {\n this(array, byteArrayOffset, array.length);\n }\n\n public DataStream(long address, long length) {\n this(null, address, length);\n }\n\n protected DataStream(byte[] array, long address, long length) {\n this.array = array;\n this.address = address;\n this.limit = address + length;\n this.offset = address;\n }\n\n public byte[] array() {\n return array;\n }\n\n public long address() {\n return address;\n }\n\n public int count() {\n return (int) (offset - address);\n }\n\n public void write(int b) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) b);\n }\n\n public void write(byte[] b) throws IOException {\n long offset = alloc(b.length);\n unsafe.copyMemory(b, byteArrayOffset, array, offset, b.length);\n }\n\n public void write(byte[] b, int off, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(b, byteArrayOffset + off, array, offset, len);\n }\n\n public void writeBoolean(boolean v) throws IOException {\n long offset = alloc(1);\n unsafe.putBoolean(array, offset, v);\n }\n\n public void writeByte(int v) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) v);\n }\n\n public void writeShort(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putShort(array, offset, Short.reverseBytes((short) v));\n }\n\n public void writeChar(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putChar(array, offset, Character.reverseBytes((char) v));\n }\n\n public void writeInt(int v) throws IOException {\n long offset = alloc(4);\n unsafe.putInt(array, offset, Integer.reverseBytes(v));\n }\n\n public void writeLong(long v) throws IOException {\n long offset = alloc(8);\n unsafe.putLong(array, offset, Long.reverseBytes(v));\n }\n\n public void writeFloat(float v) throws IOException {\n writeInt(Float.floatToRawIntBits(v));\n }\n\n public void writeDouble(double v) throws IOException {\n writeLong(Double.doubleToRawLongBits(v));\n }\n\n public void writeBytes(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length);\n for (int i = 0; i < length; i++) {\n unsafe.putByte(array, offset++, (byte) s.charAt(i));\n }\n }\n\n public void writeChars(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length * 2);\n for (int i = 0; i < length; i++) {\n unsafe.putChar(array, offset, Character.reverseBytes(s.charAt(i)));\n offset += 2;\n }\n }\n\n public void writeUTF(String s) throws IOException {\n int utfLength = Utf8.length(s);\n if (utfLength <= 0x7fff) {\n writeShort(utfLength);\n } else {\n writeInt(utfLength | 0x80000000);\n }\n long offset = alloc(utfLength);\n Utf8.write(s, array, offset);\n }\n\n @SuppressWarnings(\"unchecked\")\n public void writeObject(Object obj) throws IOException {\n if (obj == null) {\n writeByte(REF_NULL);\n } else {\n Serializer serializer = Repository.get(obj.getClass());\n if (serializer.uid < 0) {\n writeByte((byte) serializer.uid);\n } else {\n writeLong(serializer.uid);\n }\n serializer.write(obj, this);\n }\n }\n\n public void write(ByteBuffer src) throws IOException {\n int len = src.remaining();\n long offset = alloc(len);\n if (src.hasArray()) {\n unsafe.copyMemory(src.array(), byteArrayOffset + src.arrayOffset() + src.position(), array, offset, len);\n } else {\n unsafe.copyMemory(null, DirectMemory.getAddress(src) + src.position(), array, offset, len);\n }\n src.position(src.limit());\n }\n\n public void writeFrom(long address, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(null, address, array, offset, len);\n }\n\n public int read() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int read(byte[] b) throws IOException {\n readFully(b);\n return b.length;\n }\n\n public int read(byte[] b, int off, int len) throws IOException {\n readFully(b, off, len);\n return len;\n }\n\n public void readFully(byte[] b) throws IOException {\n unsafe.copyMemory(array, alloc(b.length), b, byteArrayOffset, b.length);\n }\n\n public void readFully(byte[] b, int off, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), b, byteArrayOffset + off, len);\n }\n\n public long skip(long n) throws IOException {\n alloc((int) n);\n return n;\n }\n\n public int skipBytes(int n) throws IOException {\n alloc(n);\n return n;\n }\n\n public boolean readBoolean() throws IOException {\n return unsafe.getBoolean(array, alloc(1));\n }\n\n public byte readByte() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int readUnsignedByte() throws IOException {\n return unsafe.getByte(array, alloc(1)) & 0xff;\n }\n\n public short readShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2)));\n }\n\n public int readUnsignedShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2))) & 0xffff;\n }\n\n public char readChar() throws IOException {\n return Character.reverseBytes(unsafe.getChar(array, alloc(2)));\n }\n\n public int readInt() throws IOException {\n return Integer.reverseBytes(unsafe.getInt(array, alloc(4)));\n }\n\n public long readLong() throws IOException {\n return Long.reverseBytes(unsafe.getLong(array, alloc(8)));\n }\n\n public float readFloat() throws IOException {\n return Float.intBitsToFloat(readInt());\n }\n\n public double readDouble() throws IOException {\n return Double.longBitsToDouble(readLong());\n }\n\n public String readLine() throws IOException {\n for (long ptr = offset; ptr < limit; ptr++) {\n if (unsafe.getByte(array, ptr) == '\\n') {\n int length = (int) (ptr - offset);\n int cr = length > 0 && unsafe.getByte(array, ptr - 1) == '\\r' ? 1 : 0;\n return Utf8.read(array, alloc(length + 1), length - cr);\n }\n }\n // The last line without CR\n int length = (int) (limit - offset);\n return length > 0 ? Utf8.read(array, alloc(length), length) : null;\n }\n\n public String readUTF() throws IOException {\n int length = readUnsignedShort();\n if (length == 0) {\n return \"\";\n }\n if (length > 0x7fff) {\n length = (length & 0x7fff) << 16 | readUnsignedShort();\n }\n return Utf8.read(array, alloc(length), length);\n }\n\n public Object readObject() throws IOException, ClassNotFoundException {\n Serializer serializer;\n byte b = readByte();\n if (b >= 0) {\n offset--;\n serializer = Repository.requestSerializer(readLong());\n } else if (b == REF_NULL) {\n return null;\n } else {\n serializer = Repository.requestBootstrapSerializer(b);\n }\n return serializer.read(this);\n }\n\n public void read(ByteBuffer dst) throws IOException {\n int len = dst.remaining();\n long offset = alloc(len);\n if (dst.hasArray()) {\n unsafe.copyMemory(array, offset, dst.array(), byteArrayOffset + dst.arrayOffset() + dst.position(), len);\n } else {\n unsafe.copyMemory(array, offset, null, DirectMemory.getAddress(dst) + dst.position(), len);\n }\n dst.position(dst.limit());\n }\n\n public void readTo(long address, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), null, address, len);\n }\n\n public ByteBuffer byteBuffer(int len) throws IOException {\n long offset = alloc(len);\n if (array != null) {\n return ByteBuffer.wrap(array, (int) (offset - byteArrayOffset), len);\n } else {\n return DirectMemory.wrap(offset, len);\n }\n }\n\n public int available() {\n return (int) (limit - offset);\n }\n\n public void flush() throws IOException {\n // Nothing to do\n }\n\n public void close() throws IOException {\n // Nothing to do\n }\n\n public void register(Object obj) {\n // Nothing to do\n }\n\n public Closeable newScope() {\n return null;\n }\n\n protected long alloc(int size) throws IOException {\n long currentOffset = offset;\n ", "post_mask_code": "\n return currentOffset;\n }\n}\n"} {"task_id": "Java_919", "language": "Java", "task_type": "for_statement", "source_file": "java/github/odnoklassniki/one-nio/src/one/nio/serial/DataStream.java", "mask_start_position": 3439, "mask_end_position": 3588, "canonical_solution": "for (int i = 0; i < length; i++) {\n unsafe.putChar(array, offset, Character.reverseBytes(s.charAt(i)));\n offset += 2;\n }", "pre_mask_code": "package one.nio.serial;\n\nimport one.nio.mem.DirectMemory;\nimport one.nio.util.Utf8;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport java.nio.ByteBuffer;\nimport static one.nio.util.JavaInternals.*;\n\npublic class DataStream implements ObjectInput, ObjectOutput {\n\n protected static final byte REF_NULL = -1;\n\n protected static final byte REF_RECURSIVE = -2;\n\n protected static final byte REF_RECURSIVE2 = -3;\n\n protected static final byte REF_EMBEDDED = -4;\n\n protected static final byte FIRST_APP_UID = -10;\n\n protected byte[] array;\n\n protected long address;\n\n protected long limit;\n\n protected long offset;\n\n public DataStream(int capacity) {\n this(new byte[capacity], byteArrayOffset, capacity);\n }\n\n public DataStream(byte[] array) {\n this(array, byteArrayOffset, array.length);\n }\n\n public DataStream(long address, long length) {\n this(null, address, length);\n }\n\n protected DataStream(byte[] array, long address, long length) {\n this.array = array;\n this.address = address;\n this.limit = address + length;\n this.offset = address;\n }\n\n public byte[] array() {\n return array;\n }\n\n public long address() {\n return address;\n }\n\n public int count() {\n return (int) (offset - address);\n }\n\n public void write(int b) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) b);\n }\n\n public void write(byte[] b) throws IOException {\n long offset = alloc(b.length);\n unsafe.copyMemory(b, byteArrayOffset, array, offset, b.length);\n }\n\n public void write(byte[] b, int off, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(b, byteArrayOffset + off, array, offset, len);\n }\n\n public void writeBoolean(boolean v) throws IOException {\n long offset = alloc(1);\n unsafe.putBoolean(array, offset, v);\n }\n\n public void writeByte(int v) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) v);\n }\n\n public void writeShort(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putShort(array, offset, Short.reverseBytes((short) v));\n }\n\n public void writeChar(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putChar(array, offset, Character.reverseBytes((char) v));\n }\n\n public void writeInt(int v) throws IOException {\n long offset = alloc(4);\n unsafe.putInt(array, offset, Integer.reverseBytes(v));\n }\n\n public void writeLong(long v) throws IOException {\n long offset = alloc(8);\n unsafe.putLong(array, offset, Long.reverseBytes(v));\n }\n\n public void writeFloat(float v) throws IOException {\n writeInt(Float.floatToRawIntBits(v));\n }\n\n public void writeDouble(double v) throws IOException {\n writeLong(Double.doubleToRawLongBits(v));\n }\n\n public void writeBytes(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length);\n for (int i = 0; i < length; i++) {\n unsafe.putByte(array, offset++, (byte) s.charAt(i));\n }\n }\n\n public void writeChars(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length * 2);\n ", "post_mask_code": "\n }\n\n public void writeUTF(String s) throws IOException {\n int utfLength = Utf8.length(s);\n if (utfLength <= 0x7fff) {\n writeShort(utfLength);\n } else {\n writeInt(utfLength | 0x80000000);\n }\n long offset = alloc(utfLength);\n Utf8.write(s, array, offset);\n }\n\n @SuppressWarnings(\"unchecked\")\n public void writeObject(Object obj) throws IOException {\n if (obj == null) {\n writeByte(REF_NULL);\n } else {\n Serializer serializer = Repository.get(obj.getClass());\n if (serializer.uid < 0) {\n writeByte((byte) serializer.uid);\n } else {\n writeLong(serializer.uid);\n }\n serializer.write(obj, this);\n }\n }\n\n public void write(ByteBuffer src) throws IOException {\n int len = src.remaining();\n long offset = alloc(len);\n if (src.hasArray()) {\n unsafe.copyMemory(src.array(), byteArrayOffset + src.arrayOffset() + src.position(), array, offset, len);\n } else {\n unsafe.copyMemory(null, DirectMemory.getAddress(src) + src.position(), array, offset, len);\n }\n src.position(src.limit());\n }\n\n public void writeFrom(long address, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(null, address, array, offset, len);\n }\n\n public int read() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int read(byte[] b) throws IOException {\n readFully(b);\n return b.length;\n }\n\n public int read(byte[] b, int off, int len) throws IOException {\n readFully(b, off, len);\n return len;\n }\n\n public void readFully(byte[] b) throws IOException {\n unsafe.copyMemory(array, alloc(b.length), b, byteArrayOffset, b.length);\n }\n\n public void readFully(byte[] b, int off, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), b, byteArrayOffset + off, len);\n }\n\n public long skip(long n) throws IOException {\n alloc((int) n);\n return n;\n }\n\n public int skipBytes(int n) throws IOException {\n alloc(n);\n return n;\n }\n\n public boolean readBoolean() throws IOException {\n return unsafe.getBoolean(array, alloc(1));\n }\n\n public byte readByte() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int readUnsignedByte() throws IOException {\n return unsafe.getByte(array, alloc(1)) & 0xff;\n }\n\n public short readShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2)));\n }\n\n public int readUnsignedShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2))) & 0xffff;\n }\n\n public char readChar() throws IOException {\n return Character.reverseBytes(unsafe.getChar(array, alloc(2)));\n }\n\n public int readInt() throws IOException {\n return Integer.reverseBytes(unsafe.getInt(array, alloc(4)));\n }\n\n public long readLong() throws IOException {\n return Long.reverseBytes(unsafe.getLong(array, alloc(8)));\n }\n\n public float readFloat() throws IOException {\n return Float.intBitsToFloat(readInt());\n }\n\n public double readDouble() throws IOException {\n return Double.longBitsToDouble(readLong());\n }\n\n public String readLine() throws IOException {\n for (long ptr = offset; ptr < limit; ptr++) {\n if (unsafe.getByte(array, ptr) == '\\n') {\n int length = (int) (ptr - offset);\n int cr = length > 0 && unsafe.getByte(array, ptr - 1) == '\\r' ? 1 : 0;\n return Utf8.read(array, alloc(length + 1), length - cr);\n }\n }\n // The last line without CR\n int length = (int) (limit - offset);\n return length > 0 ? Utf8.read(array, alloc(length), length) : null;\n }\n\n public String readUTF() throws IOException {\n int length = readUnsignedShort();\n if (length == 0) {\n return \"\";\n }\n if (length > 0x7fff) {\n length = (length & 0x7fff) << 16 | readUnsignedShort();\n }\n return Utf8.read(array, alloc(length), length);\n }\n\n public Object readObject() throws IOException, ClassNotFoundException {\n Serializer serializer;\n byte b = readByte();\n if (b >= 0) {\n offset--;\n serializer = Repository.requestSerializer(readLong());\n } else if (b == REF_NULL) {\n return null;\n } else {\n serializer = Repository.requestBootstrapSerializer(b);\n }\n return serializer.read(this);\n }\n\n public void read(ByteBuffer dst) throws IOException {\n int len = dst.remaining();\n long offset = alloc(len);\n if (dst.hasArray()) {\n unsafe.copyMemory(array, offset, dst.array(), byteArrayOffset + dst.arrayOffset() + dst.position(), len);\n } else {\n unsafe.copyMemory(array, offset, null, DirectMemory.getAddress(dst) + dst.position(), len);\n }\n dst.position(dst.limit());\n }\n\n public void readTo(long address, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), null, address, len);\n }\n\n public ByteBuffer byteBuffer(int len) throws IOException {\n long offset = alloc(len);\n if (array != null) {\n return ByteBuffer.wrap(array, (int) (offset - byteArrayOffset), len);\n } else {\n return DirectMemory.wrap(offset, len);\n }\n }\n\n public int available() {\n return (int) (limit - offset);\n }\n\n public void flush() throws IOException {\n // Nothing to do\n }\n\n public void close() throws IOException {\n // Nothing to do\n }\n\n public void register(Object obj) {\n // Nothing to do\n }\n\n public Closeable newScope() {\n return null;\n }\n\n protected long alloc(int size) throws IOException {\n long currentOffset = offset;\n if ((offset = currentOffset + size) > limit) {\n throw new IndexOutOfBoundsException();\n }\n return currentOffset;\n }\n}\n"} {"task_id": "Java_920", "language": "Java", "task_type": "empty", "source_file": "java/github/odnoklassniki/one-nio/src/one/nio/serial/DataStream.java", "mask_start_position": 5547, "mask_end_position": 5547, "canonical_solution": "", "pre_mask_code": "package one.nio.serial;\n\nimport one.nio.mem.DirectMemory;\nimport one.nio.util.Utf8;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport java.nio.ByteBuffer;\nimport static one.nio.util.JavaInternals.*;\n\npublic class DataStream implements ObjectInput, ObjectOutput {\n\n protected static final byte REF_NULL = -1;\n\n protected static final byte REF_RECURSIVE = -2;\n\n protected static final byte REF_RECURSIVE2 = -3;\n\n protected static final byte REF_EMBEDDED = -4;\n\n protected static final byte FIRST_APP_UID = -10;\n\n protected byte[] array;\n\n protected long address;\n\n protected long limit;\n\n protected long offset;\n\n public DataStream(int capacity) {\n this(new byte[capacity], byteArrayOffset, capacity);\n }\n\n public DataStream(byte[] array) {\n this(array, byteArrayOffset, array.length);\n }\n\n public DataStream(long address, long length) {\n this(null, address, length);\n }\n\n protected DataStream(byte[] array, long address, long length) {\n this.array = array;\n this.address = address;\n this.limit = address + length;\n this.offset = address;\n }\n\n public byte[] array() {\n return array;\n }\n\n public long address() {\n return address;\n }\n\n public int count() {\n return (int) (offset - address);\n }\n\n public void write(int b) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) b);\n }\n\n public void write(byte[] b) throws IOException {\n long offset = alloc(b.length);\n unsafe.copyMemory(b, byteArrayOffset, array, offset, b.length);\n }\n\n public void write(byte[] b, int off, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(b, byteArrayOffset + off, array, offset, len);\n }\n\n public void writeBoolean(boolean v) throws IOException {\n long offset = alloc(1);\n unsafe.putBoolean(array, offset, v);\n }\n\n public void writeByte(int v) throws IOException {\n long offset = alloc(1);\n unsafe.putByte(array, offset, (byte) v);\n }\n\n public void writeShort(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putShort(array, offset, Short.reverseBytes((short) v));\n }\n\n public void writeChar(int v) throws IOException {\n long offset = alloc(2);\n unsafe.putChar(array, offset, Character.reverseBytes((char) v));\n }\n\n public void writeInt(int v) throws IOException {\n long offset = alloc(4);\n unsafe.putInt(array, offset, Integer.reverseBytes(v));\n }\n\n public void writeLong(long v) throws IOException {\n long offset = alloc(8);\n unsafe.putLong(array, offset, Long.reverseBytes(v));\n }\n\n public void writeFloat(float v) throws IOException {\n writeInt(Float.floatToRawIntBits(v));\n }\n\n public void writeDouble(double v) throws IOException {\n writeLong(Double.doubleToRawLongBits(v));\n }\n\n public void writeBytes(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length);\n for (int i = 0; i < length; i++) {\n unsafe.putByte(array, offset++, (byte) s.charAt(i));\n }\n }\n\n public void writeChars(String s) throws IOException {\n int length = s.length();\n long offset = alloc(length * 2);\n for (int i = 0; i < length; i++) {\n unsafe.putChar(array, offset, Character.reverseBytes(s.charAt(i)));\n offset += 2;\n }\n }\n\n public void writeUTF(String s) throws IOException {\n int utfLength = Utf8.length(s);\n if (utfLength <= 0x7fff) {\n writeShort(utfLength);\n } else {\n writeInt(utfLength | 0x80000000);\n }\n long offset = alloc(utfLength);\n Utf8.write(s, array, offset);\n }\n\n @SuppressWarnings(\"unchecked\")\n public void writeObject(Object obj) throws IOException {\n if (obj == null) {\n writeByte(REF_NULL);\n } else {\n Serializer serializer = Repository.get(obj.getClass());\n if (serializer.uid < 0) {\n writeByte((byte) serializer.uid);\n } else {\n writeLong(serializer.uid);\n }\n serializer.write(obj, this);\n }\n }\n\n public void write(ByteBuffer src) throws IOException {\n int len = src.remaining();\n long offset = alloc(len);\n if (src.hasArray()) {\n unsafe.copyMemory(src.array(), byteArrayOffset + src.arrayOffset() + src.position(), array, offset, len);\n } else {\n unsafe.copyMemory(null, DirectMemory.getAddress(src) + src.position(), array, offset, len);\n }\n src.position(src.limit());\n }\n\n public void writeFrom(long address, int len) throws IOException {\n long offset = alloc(len);\n unsafe.copyMemory(null, address, array, offset, len);\n }\n\n public int read() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int read(byte[] b) throws IOException {\n readFully(b);\n return b.length;\n }\n\n public int read(byte[] b, int off, int len) throws IOException {\n readFully(b, off, len);\n return len;\n }\n\n public void readFully(byte[] b) throws IOException {\n unsafe.copyMemory(array, alloc(b.length), b, byteArrayOffset, b.length);\n }\n\n public void readFully(byte[] b, int off, int len) throws IOE", "post_mask_code": "xception {\n unsafe.copyMemory(array, alloc(len), b, byteArrayOffset + off, len);\n }\n\n public long skip(long n) throws IOException {\n alloc((int) n);\n return n;\n }\n\n public int skipBytes(int n) throws IOException {\n alloc(n);\n return n;\n }\n\n public boolean readBoolean() throws IOException {\n return unsafe.getBoolean(array, alloc(1));\n }\n\n public byte readByte() throws IOException {\n return unsafe.getByte(array, alloc(1));\n }\n\n public int readUnsignedByte() throws IOException {\n return unsafe.getByte(array, alloc(1)) & 0xff;\n }\n\n public short readShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2)));\n }\n\n public int readUnsignedShort() throws IOException {\n return Short.reverseBytes(unsafe.getShort(array, alloc(2))) & 0xffff;\n }\n\n public char readChar() throws IOException {\n return Character.reverseBytes(unsafe.getChar(array, alloc(2)));\n }\n\n public int readInt() throws IOException {\n return Integer.reverseBytes(unsafe.getInt(array, alloc(4)));\n }\n\n public long readLong() throws IOException {\n return Long.reverseBytes(unsafe.getLong(array, alloc(8)));\n }\n\n public float readFloat() throws IOException {\n return Float.intBitsToFloat(readInt());\n }\n\n public double readDouble() throws IOException {\n return Double.longBitsToDouble(readLong());\n }\n\n public String readLine() throws IOException {\n for (long ptr = offset; ptr < limit; ptr++) {\n if (unsafe.getByte(array, ptr) == '\\n') {\n int length = (int) (ptr - offset);\n int cr = length > 0 && unsafe.getByte(array, ptr - 1) == '\\r' ? 1 : 0;\n return Utf8.read(array, alloc(length + 1), length - cr);\n }\n }\n // The last line without CR\n int length = (int) (limit - offset);\n return length > 0 ? Utf8.read(array, alloc(length), length) : null;\n }\n\n public String readUTF() throws IOException {\n int length = readUnsignedShort();\n if (length == 0) {\n return \"\";\n }\n if (length > 0x7fff) {\n length = (length & 0x7fff) << 16 | readUnsignedShort();\n }\n return Utf8.read(array, alloc(length), length);\n }\n\n public Object readObject() throws IOException, ClassNotFoundException {\n Serializer serializer;\n byte b = readByte();\n if (b >= 0) {\n offset--;\n serializer = Repository.requestSerializer(readLong());\n } else if (b == REF_NULL) {\n return null;\n } else {\n serializer = Repository.requestBootstrapSerializer(b);\n }\n return serializer.read(this);\n }\n\n public void read(ByteBuffer dst) throws IOException {\n int len = dst.remaining();\n long offset = alloc(len);\n if (dst.hasArray()) {\n unsafe.copyMemory(array, offset, dst.array(), byteArrayOffset + dst.arrayOffset() + dst.position(), len);\n } else {\n unsafe.copyMemory(array, offset, null, DirectMemory.getAddress(dst) + dst.position(), len);\n }\n dst.position(dst.limit());\n }\n\n public void readTo(long address, int len) throws IOException {\n unsafe.copyMemory(array, alloc(len), null, address, len);\n }\n\n public ByteBuffer byteBuffer(int len) throws IOException {\n long offset = alloc(len);\n if (array != null) {\n return ByteBuffer.wrap(array, (int) (offset - byteArrayOffset), len);\n } else {\n return DirectMemory.wrap(offset, len);\n }\n }\n\n public int available() {\n return (int) (limit - offset);\n }\n\n public void flush() throws IOException {\n // Nothing to do\n }\n\n public void close() throws IOException {\n // Nothing to do\n }\n\n public void register(Object obj) {\n // Nothing to do\n }\n\n public Closeable newScope() {\n return null;\n }\n\n protected long alloc(int size) throws IOException {\n long currentOffset = offset;\n if ((offset = currentOffset + size) > limit) {\n throw new IndexOutOfBoundsException();\n }\n return currentOffset;\n }\n}\n"} {"task_id": "Java_921", "language": "Java", "task_type": "method_signature", "source_file": "java/github/speedment/speedment/common-parent/logger/src/main/java/com/speedment/common/logger/internal/SystemOutLoggerFactory.java", "mask_start_position": 203, "mask_end_position": 288, "canonical_solution": "@Override\n public SystemOutLogger make(String binding, LoggerFormatter formatter) ", "pre_mask_code": "package com.speedment.common.logger.internal;\n\nimport com.speedment.common.logger.LoggerFormatter;\n\n/**\n * @author pemi\n */\npublic final class SystemOutLoggerFactory extends AbstractLoggerFactory {\n\n ", "post_mask_code": "{\n return new SystemOutLogger(binding, formatter);\n }\n\n @Override\n public Class loggerClass() {\n return SystemOutLogger.class;\n }\n}\n"} {"task_id": "Java_922", "language": "Java", "task_type": "method_body", "source_file": "java/github/speedment/speedment/common-parent/logger/src/main/java/com/speedment/common/logger/internal/SystemOutLoggerFactory.java", "mask_start_position": 415, "mask_end_position": 460, "canonical_solution": "{\n return SystemOutLogger.class;\n }", "pre_mask_code": "package com.speedment.common.logger.internal;\n\nimport com.speedment.common.logger.LoggerFormatter;\n\n/**\n * @author pemi\n */\npublic final class SystemOutLoggerFactory extends AbstractLoggerFactory {\n\n @Override\n public SystemOutLogger make(String binding, LoggerFormatter formatter) {\n return new SystemOutLogger(binding, formatter);\n }\n\n @Override\n public Class loggerClass() ", "post_mask_code": "\n}\n"} {"task_id": "Java_923", "language": "Java", "task_type": "single_line", "source_file": "java/github/speedment/speedment/common-parent/logger/src/main/java/com/speedment/common/logger/internal/SystemOutLoggerFactory.java", "mask_start_position": 344, "mask_end_position": 345, "canonical_solution": ";", "pre_mask_code": "package com.speedment.common.logger.internal;\n\nimport com.speedment.common.logger.LoggerFormatter;\n\n/**\n * @author pemi\n */\npublic final class SystemOutLoggerFactory extends AbstractLoggerFactory {\n\n @Override\n public SystemOutLogger make(String binding, LoggerFormatter formatter) {\n return new SystemOutLogger(binding, formatter)", "post_mask_code": "\n }\n\n @Override\n public Class loggerClass() {\n return SystemOutLogger.class;\n }\n}\n"} {"task_id": "Java_924", "language": "Java", "task_type": "empty", "source_file": "java/github/speedment/speedment/common-parent/logger/src/main/java/com/speedment/common/logger/internal/SystemOutLoggerFactory.java", "mask_start_position": 93, "mask_end_position": 93, "canonical_solution": "", "pre_mask_code": "package com.speedment.common.logger.internal;\n\nimport com.speedment.common.logger.LoggerForma", "post_mask_code": "tter;\n\n/**\n * @author pemi\n */\npublic final class SystemOutLoggerFactory extends AbstractLoggerFactory {\n\n @Override\n public SystemOutLogger make(String binding, LoggerFormatter formatter) {\n return new SystemOutLogger(binding, formatter);\n }\n\n @Override\n public Class loggerClass() {\n return SystemOutLogger.class;\n }\n}\n"} {"task_id": "Java_925", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cwi-swat/recaf/recaf-runtime/src/main/java/recaf/paper/full/FullMuJavaDirect.java", "mask_start_position": 265, "mask_end_position": 311, "canonical_solution": "@Override\n default MuJava base() ", "pre_mask_code": "package recaf.paper.full;\n\nimport recaf.paper.expr.IEval;\nimport recaf.paper.stm.IExec;\nimport recaf.paper.stm.MuJava;\nimport recaf.paper.stm.MuJavaBase;\n\npublic interface FullMuJavaDirect extends FullMuJava, MuStmIEvalJavaAdapter {\n\n ", "post_mask_code": "{\n return new MuJavaBase() {\n };\n }\n}\n"} {"task_id": "Java_926", "language": "Java", "task_type": "method_body", "source_file": "java/github/cwi-swat/recaf/recaf-runtime/src/main/java/recaf/paper/full/FullMuJavaDirect.java", "mask_start_position": 311, "mask_end_position": 366, "canonical_solution": "{\n return new MuJavaBase() {\n };\n }", "pre_mask_code": "package recaf.paper.full;\n\nimport recaf.paper.expr.IEval;\nimport recaf.paper.stm.IExec;\nimport recaf.paper.stm.MuJava;\nimport recaf.paper.stm.MuJavaBase;\n\npublic interface FullMuJavaDirect extends FullMuJava, MuStmIEvalJavaAdapter {\n\n @Override\n default MuJava base() ", "post_mask_code": "\n}\n"} {"task_id": "Java_927", "language": "Java", "task_type": "empty", "source_file": "java/github/cwi-swat/recaf/recaf-runtime/src/main/java/recaf/paper/full/FullMuJavaDirect.java", "mask_start_position": 91, "mask_end_position": 91, "canonical_solution": "", "pre_mask_code": "package recaf.paper.full;\n\nimport recaf.paper.expr.IEval;\nimport recaf.paper.stm.IExec;\nimp", "post_mask_code": "ort recaf.paper.stm.MuJava;\nimport recaf.paper.stm.MuJavaBase;\n\npublic interface FullMuJavaDirect extends FullMuJava, MuStmIEvalJavaAdapter {\n\n @Override\n default MuJava base() {\n return new MuJavaBase() {\n };\n }\n}\n"} {"task_id": "Java_928", "language": "Java", "task_type": "method_signature", "source_file": "java/github/RSenApps/Commandr-Android/phone/src/com/RSen/Commandr/builtincommands/UnsilenceRingerCommand.java", "mask_start_position": 1133, "mask_end_position": 1172, "canonical_solution": "@Override\n public String getTitle() ", "pre_mask_code": "package com.RSen.Commandr.builtincommands;\n\nimport android.content.Context;\nimport android.media.AudioManager;\nimport com.RSen.Commandr.R;\nimport com.RSen.Commandr.core.MostWantedCommand;\n\n/**\n * @author Ryan Senanayake\n * Commandr for Google Now\n * FlashlightCommand.java\n * @version 1.0\n * 5/28/14\n */\npublic class UnsilenceRingerCommand extends MostWantedCommand {\n\n private static String TITLE;\n\n private static String DEFAULT_PHRASE;\n\n public UnsilenceRingerCommand(Context ctx) {\n DEFAULT_PHRASE = ctx.getString(R.string.unsilence_ringer_phrase);\n TITLE = ctx.getString(R.string.unsilence_ringer_title);\n }\n\n /**\n * Execute this command (turn on flashlight)\n */\n @Override\n public void execute(Context context, String predicate) {\n AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);\n }\n\n /**\n * It is enabled if the phone has a flash feature\n */\n @Override\n public boolean isAvailable(Context context) {\n return true;\n }\n\n ", "post_mask_code": "{\n return TITLE;\n }\n\n @Override\n public String getDefaultPhrase() {\n return DEFAULT_PHRASE;\n }\n}\n"} {"task_id": "Java_929", "language": "Java", "task_type": "method_body", "source_file": "java/github/RSenApps/Commandr-Android/phone/src/com/RSen/Commandr/builtincommands/UnsilenceRingerCommand.java", "mask_start_position": 1254, "mask_end_position": 1292, "canonical_solution": "{\n return DEFAULT_PHRASE;\n }", "pre_mask_code": "package com.RSen.Commandr.builtincommands;\n\nimport android.content.Context;\nimport android.media.AudioManager;\nimport com.RSen.Commandr.R;\nimport com.RSen.Commandr.core.MostWantedCommand;\n\n/**\n * @author Ryan Senanayake\n * Commandr for Google Now\n * FlashlightCommand.java\n * @version 1.0\n * 5/28/14\n */\npublic class UnsilenceRingerCommand extends MostWantedCommand {\n\n private static String TITLE;\n\n private static String DEFAULT_PHRASE;\n\n public UnsilenceRingerCommand(Context ctx) {\n DEFAULT_PHRASE = ctx.getString(R.string.unsilence_ringer_phrase);\n TITLE = ctx.getString(R.string.unsilence_ringer_title);\n }\n\n /**\n * Execute this command (turn on flashlight)\n */\n @Override\n public void execute(Context context, String predicate) {\n AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);\n }\n\n /**\n * It is enabled if the phone has a flash feature\n */\n @Override\n public boolean isAvailable(Context context) {\n return true;\n }\n\n @Override\n public String getTitle() {\n return TITLE;\n }\n\n @Override\n public String getDefaultPhrase() ", "post_mask_code": "\n}\n"} {"task_id": "Java_930", "language": "Java", "task_type": "single_line", "source_file": "java/github/RSenApps/Commandr-Android/phone/src/com/RSen/Commandr/builtincommands/UnsilenceRingerCommand.java", "mask_start_position": 1115, "mask_end_position": 1121, "canonical_solution": " true;", "pre_mask_code": "package com.RSen.Commandr.builtincommands;\n\nimport android.content.Context;\nimport android.media.AudioManager;\nimport com.RSen.Commandr.R;\nimport com.RSen.Commandr.core.MostWantedCommand;\n\n/**\n * @author Ryan Senanayake\n * Commandr for Google Now\n * FlashlightCommand.java\n * @version 1.0\n * 5/28/14\n */\npublic class UnsilenceRingerCommand extends MostWantedCommand {\n\n private static String TITLE;\n\n private static String DEFAULT_PHRASE;\n\n public UnsilenceRingerCommand(Context ctx) {\n DEFAULT_PHRASE = ctx.getString(R.string.unsilence_ringer_phrase);\n TITLE = ctx.getString(R.string.unsilence_ringer_title);\n }\n\n /**\n * Execute this command (turn on flashlight)\n */\n @Override\n public void execute(Context context, String predicate) {\n AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);\n }\n\n /**\n * It is enabled if the phone has a flash feature\n */\n @Override\n public boolean isAvailable(Context context) {\n return", "post_mask_code": "\n }\n\n @Override\n public String getTitle() {\n return TITLE;\n }\n\n @Override\n public String getDefaultPhrase() {\n return DEFAULT_PHRASE;\n }\n}\n"} {"task_id": "Java_931", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/RSenApps/Commandr-Android/phone/src/com/RSen/Commandr/builtincommands/UnsilenceRingerCommand.java", "mask_start_position": 1041, "mask_end_position": 1127, "canonical_solution": "@Override\n public boolean isAvailable(Context context) {\n return true;\n }", "pre_mask_code": "package com.RSen.Commandr.builtincommands;\n\nimport android.content.Context;\nimport android.media.AudioManager;\nimport com.RSen.Commandr.R;\nimport com.RSen.Commandr.core.MostWantedCommand;\n\n/**\n * @author Ryan Senanayake\n * Commandr for Google Now\n * FlashlightCommand.java\n * @version 1.0\n * 5/28/14\n */\npublic class UnsilenceRingerCommand extends MostWantedCommand {\n\n private static String TITLE;\n\n private static String DEFAULT_PHRASE;\n\n public UnsilenceRingerCommand(Context ctx) {\n DEFAULT_PHRASE = ctx.getString(R.string.unsilence_ringer_phrase);\n TITLE = ctx.getString(R.string.unsilence_ringer_title);\n }\n\n /**\n * Execute this command (turn on flashlight)\n */\n @Override\n public void execute(Context context, String predicate) {\n AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);\n }\n\n /**\n * It is enabled if the phone has a flash feature\n */\n ", "post_mask_code": "\n\n @Override\n public String getTitle() {\n return TITLE;\n }\n\n @Override\n public String getDefaultPhrase() {\n return DEFAULT_PHRASE;\n }\n}\n"} {"task_id": "Java_932", "language": "Java", "task_type": "empty", "source_file": "java/github/RSenApps/Commandr-Android/phone/src/com/RSen/Commandr/builtincommands/UnsilenceRingerCommand.java", "mask_start_position": 962, "mask_end_position": 962, "canonical_solution": "", "pre_mask_code": "package com.RSen.Commandr.builtincommands;\n\nimport android.content.Context;\nimport android.media.AudioManager;\nimport com.RSen.Commandr.R;\nimport com.RSen.Commandr.core.MostWantedCommand;\n\n/**\n * @author Ryan Senanayake\n * Commandr for Google Now\n * FlashlightCommand.java\n * @version 1.0\n * 5/28/14\n */\npublic class UnsilenceRingerCommand extends MostWantedCommand {\n\n private static String TITLE;\n\n private static String DEFAULT_PHRASE;\n\n public UnsilenceRingerCommand(Context ctx) {\n DEFAULT_PHRASE = ctx.getString(R.string.unsilence_ringer_phrase);\n TITLE = ctx.getString(R.string.unsilence_ringer_title);\n }\n\n /**\n * Execute this command (turn on flashlight)\n */\n @Override\n public void execute(Context context, String predicate) {\n AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);\n ", "post_mask_code": " }\n\n /**\n * It is enabled if the phone has a flash feature\n */\n @Override\n public boolean isAvailable(Context context) {\n return true;\n }\n\n @Override\n public String getTitle() {\n return TITLE;\n }\n\n @Override\n public String getDefaultPhrase() {\n return DEFAULT_PHRASE;\n }\n}\n"} {"task_id": "Java_933", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openstreetmap/osmosis/osmosis-pgsimple/src/main/java/org/openstreetmap/osmosis/pgsimple/v0_6/impl/WayNodeMapper.java", "mask_start_position": 509, "mask_end_position": 559, "canonical_solution": "@Override\n public String getParentEntityName() ", "pre_mask_code": "package org.openstreetmap.osmosis.pgsimple.v0_6.impl;\n\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.openstreetmap.osmosis.core.OsmosisRuntimeException;\nimport org.openstreetmap.osmosis.core.database.DbOrderedFeature;\nimport org.openstreetmap.osmosis.core.domain.v0_6.WayNode;\n\n/**\n * Reads and writes way nodes to jdbc classes.\n *\n * @author Brett Henderson\n */\npublic class WayNodeMapper extends EntityFeatureMapper> {\n\n ", "post_mask_code": "{\n return \"way\";\n }\n\n @Override\n public String getEntityName() {\n return \"way_nodes\";\n }\n\n @Override\n public String getSqlSelect(boolean filterByEntityId, boolean orderBy) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"SELECT way_id AS entity_id, node_id, sequence_id FROM \");\n resultSql.append(\"way_nodes f\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE entity_id = ?\");\n }\n if (orderBy) {\n resultSql.append(getSqlDefaultOrderBy());\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDefaultOrderBy() {\n return super.getSqlDefaultOrderBy() + \", sequence_id\";\n }\n\n @Override\n public String getSqlInsert(int rowCount) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"INSERT INTO way_nodes (\");\n resultSql.append(\"way_id, node_id, sequence_id) VALUES \");\n for (int row = 0; row < rowCount; row++) {\n if (row > 0) {\n resultSql.append(\", \");\n }\n resultSql.append(\"(?, ?, ?)\");\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDelete(boolean filterByEntityId) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"DELETE FROM way_nodes\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE \").append(\"way_id = ?\");\n }\n return resultSql.toString();\n }\n\n @Override\n public DbOrderedFeature buildEntity(ResultSet resultSet) {\n try {\n return new DbOrderedFeature(resultSet.getLong(\"entity_id\"), new WayNode(resultSet.getLong(\"node_id\")), resultSet.getInt(\"sequence_id\"));\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to build a way node from the current recordset row.\", e);\n }\n }\n\n @Override\n public int populateEntityParameters(PreparedStatement statement, int initialIndex, DbOrderedFeature entityFeature) {\n try {\n int prmIndex;\n WayNode wayNode;\n wayNode = entityFeature.getFeature();\n prmIndex = initialIndex;\n statement.setLong(prmIndex++, entityFeature.getEntityId());\n statement.setLong(prmIndex++, wayNode.getNodeId());\n statement.setInt(prmIndex++, entityFeature.getSequenceId());\n return prmIndex;\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to populate way node parameters for way \" + entityFeature.getEntityId() + \".\", e);\n }\n }\n}\n"} {"task_id": "Java_934", "language": "Java", "task_type": "method_body", "source_file": "java/github/openstreetmap/osmosis/osmosis-pgsimple/src/main/java/org/openstreetmap/osmosis/pgsimple/v0_6/impl/WayNodeMapper.java", "mask_start_position": 763, "mask_end_position": 1189, "canonical_solution": "{\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"SELECT way_id AS entity_id, node_id, sequence_id FROM \");\n resultSql.append(\"way_nodes f\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE entity_id = ?\");\n }\n if (orderBy) {\n resultSql.append(getSqlDefaultOrderBy());\n }\n return resultSql.toString();\n }", "pre_mask_code": "package org.openstreetmap.osmosis.pgsimple.v0_6.impl;\n\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.openstreetmap.osmosis.core.OsmosisRuntimeException;\nimport org.openstreetmap.osmosis.core.database.DbOrderedFeature;\nimport org.openstreetmap.osmosis.core.domain.v0_6.WayNode;\n\n/**\n * Reads and writes way nodes to jdbc classes.\n *\n * @author Brett Henderson\n */\npublic class WayNodeMapper extends EntityFeatureMapper> {\n\n @Override\n public String getParentEntityName() {\n return \"way\";\n }\n\n @Override\n public String getEntityName() {\n return \"way_nodes\";\n }\n\n @Override\n public String getSqlSelect(boolean filterByEntityId, boolean orderBy) ", "post_mask_code": "\n\n @Override\n public String getSqlDefaultOrderBy() {\n return super.getSqlDefaultOrderBy() + \", sequence_id\";\n }\n\n @Override\n public String getSqlInsert(int rowCount) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"INSERT INTO way_nodes (\");\n resultSql.append(\"way_id, node_id, sequence_id) VALUES \");\n for (int row = 0; row < rowCount; row++) {\n if (row > 0) {\n resultSql.append(\", \");\n }\n resultSql.append(\"(?, ?, ?)\");\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDelete(boolean filterByEntityId) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"DELETE FROM way_nodes\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE \").append(\"way_id = ?\");\n }\n return resultSql.toString();\n }\n\n @Override\n public DbOrderedFeature buildEntity(ResultSet resultSet) {\n try {\n return new DbOrderedFeature(resultSet.getLong(\"entity_id\"), new WayNode(resultSet.getLong(\"node_id\")), resultSet.getInt(\"sequence_id\"));\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to build a way node from the current recordset row.\", e);\n }\n }\n\n @Override\n public int populateEntityParameters(PreparedStatement statement, int initialIndex, DbOrderedFeature entityFeature) {\n try {\n int prmIndex;\n WayNode wayNode;\n wayNode = entityFeature.getFeature();\n prmIndex = initialIndex;\n statement.setLong(prmIndex++, entityFeature.getEntityId());\n statement.setLong(prmIndex++, wayNode.getNodeId());\n statement.setInt(prmIndex++, entityFeature.getSequenceId());\n return prmIndex;\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to populate way node parameters for way \" + entityFeature.getEntityId() + \".\", e);\n }\n }\n}\n"} {"task_id": "Java_935", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/openstreetmap/osmosis/osmosis-pgsimple/src/main/java/org/openstreetmap/osmosis/pgsimple/v0_6/impl/WayNodeMapper.java", "mask_start_position": 764, "mask_end_position": 838, "canonical_solution": "\n StringBuilder resultSql;\n resultSql = new StringBuilder();", "pre_mask_code": "package org.openstreetmap.osmosis.pgsimple.v0_6.impl;\n\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.openstreetmap.osmosis.core.OsmosisRuntimeException;\nimport org.openstreetmap.osmosis.core.database.DbOrderedFeature;\nimport org.openstreetmap.osmosis.core.domain.v0_6.WayNode;\n\n/**\n * Reads and writes way nodes to jdbc classes.\n *\n * @author Brett Henderson\n */\npublic class WayNodeMapper extends EntityFeatureMapper> {\n\n @Override\n public String getParentEntityName() {\n return \"way\";\n }\n\n @Override\n public String getEntityName() {\n return \"way_nodes\";\n }\n\n @Override\n public String getSqlSelect(boolean filterByEntityId, boolean orderBy) {", "post_mask_code": "\n resultSql.append(\"SELECT way_id AS entity_id, node_id, sequence_id FROM \");\n resultSql.append(\"way_nodes f\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE entity_id = ?\");\n }\n if (orderBy) {\n resultSql.append(getSqlDefaultOrderBy());\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDefaultOrderBy() {\n return super.getSqlDefaultOrderBy() + \", sequence_id\";\n }\n\n @Override\n public String getSqlInsert(int rowCount) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"INSERT INTO way_nodes (\");\n resultSql.append(\"way_id, node_id, sequence_id) VALUES \");\n for (int row = 0; row < rowCount; row++) {\n if (row > 0) {\n resultSql.append(\", \");\n }\n resultSql.append(\"(?, ?, ?)\");\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDelete(boolean filterByEntityId) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"DELETE FROM way_nodes\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE \").append(\"way_id = ?\");\n }\n return resultSql.toString();\n }\n\n @Override\n public DbOrderedFeature buildEntity(ResultSet resultSet) {\n try {\n return new DbOrderedFeature(resultSet.getLong(\"entity_id\"), new WayNode(resultSet.getLong(\"node_id\")), resultSet.getInt(\"sequence_id\"));\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to build a way node from the current recordset row.\", e);\n }\n }\n\n @Override\n public int populateEntityParameters(PreparedStatement statement, int initialIndex, DbOrderedFeature entityFeature) {\n try {\n int prmIndex;\n WayNode wayNode;\n wayNode = entityFeature.getFeature();\n prmIndex = initialIndex;\n statement.setLong(prmIndex++, entityFeature.getEntityId());\n statement.setLong(prmIndex++, wayNode.getNodeId());\n statement.setInt(prmIndex++, entityFeature.getSequenceId());\n return prmIndex;\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to populate way node parameters for way \" + entityFeature.getEntityId() + \".\", e);\n }\n }\n}\n"} {"task_id": "Java_936", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/openstreetmap/osmosis/osmosis-pgsimple/src/main/java/org/openstreetmap/osmosis/pgsimple/v0_6/impl/WayNodeMapper.java", "mask_start_position": 847, "mask_end_position": 1059, "canonical_solution": "resultSql.append(\"SELECT way_id AS entity_id, node_id, sequence_id FROM \");\n resultSql.append(\"way_nodes f\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE entity_id = ?\");\n }", "pre_mask_code": "package org.openstreetmap.osmosis.pgsimple.v0_6.impl;\n\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.openstreetmap.osmosis.core.OsmosisRuntimeException;\nimport org.openstreetmap.osmosis.core.database.DbOrderedFeature;\nimport org.openstreetmap.osmosis.core.domain.v0_6.WayNode;\n\n/**\n * Reads and writes way nodes to jdbc classes.\n *\n * @author Brett Henderson\n */\npublic class WayNodeMapper extends EntityFeatureMapper> {\n\n @Override\n public String getParentEntityName() {\n return \"way\";\n }\n\n @Override\n public String getEntityName() {\n return \"way_nodes\";\n }\n\n @Override\n public String getSqlSelect(boolean filterByEntityId, boolean orderBy) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n ", "post_mask_code": "\n if (orderBy) {\n resultSql.append(getSqlDefaultOrderBy());\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDefaultOrderBy() {\n return super.getSqlDefaultOrderBy() + \", sequence_id\";\n }\n\n @Override\n public String getSqlInsert(int rowCount) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"INSERT INTO way_nodes (\");\n resultSql.append(\"way_id, node_id, sequence_id) VALUES \");\n for (int row = 0; row < rowCount; row++) {\n if (row > 0) {\n resultSql.append(\", \");\n }\n resultSql.append(\"(?, ?, ?)\");\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDelete(boolean filterByEntityId) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"DELETE FROM way_nodes\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE \").append(\"way_id = ?\");\n }\n return resultSql.toString();\n }\n\n @Override\n public DbOrderedFeature buildEntity(ResultSet resultSet) {\n try {\n return new DbOrderedFeature(resultSet.getLong(\"entity_id\"), new WayNode(resultSet.getLong(\"node_id\")), resultSet.getInt(\"sequence_id\"));\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to build a way node from the current recordset row.\", e);\n }\n }\n\n @Override\n public int populateEntityParameters(PreparedStatement statement, int initialIndex, DbOrderedFeature entityFeature) {\n try {\n int prmIndex;\n WayNode wayNode;\n wayNode = entityFeature.getFeature();\n prmIndex = initialIndex;\n statement.setLong(prmIndex++, entityFeature.getEntityId());\n statement.setLong(prmIndex++, wayNode.getNodeId());\n statement.setInt(prmIndex++, entityFeature.getSequenceId());\n return prmIndex;\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to populate way node parameters for way \" + entityFeature.getEntityId() + \".\", e);\n }\n }\n}\n"} {"task_id": "Java_937", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/openstreetmap/osmosis/osmosis-pgsimple/src/main/java/org/openstreetmap/osmosis/pgsimple/v0_6/impl/WayNodeMapper.java", "mask_start_position": 1068, "mask_end_position": 1189, "canonical_solution": "if (orderBy) {\n resultSql.append(getSqlDefaultOrderBy());\n }\n return resultSql.toString();\n }", "pre_mask_code": "package org.openstreetmap.osmosis.pgsimple.v0_6.impl;\n\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.openstreetmap.osmosis.core.OsmosisRuntimeException;\nimport org.openstreetmap.osmosis.core.database.DbOrderedFeature;\nimport org.openstreetmap.osmosis.core.domain.v0_6.WayNode;\n\n/**\n * Reads and writes way nodes to jdbc classes.\n *\n * @author Brett Henderson\n */\npublic class WayNodeMapper extends EntityFeatureMapper> {\n\n @Override\n public String getParentEntityName() {\n return \"way\";\n }\n\n @Override\n public String getEntityName() {\n return \"way_nodes\";\n }\n\n @Override\n public String getSqlSelect(boolean filterByEntityId, boolean orderBy) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"SELECT way_id AS entity_id, node_id, sequence_id FROM \");\n resultSql.append(\"way_nodes f\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE entity_id = ?\");\n }\n ", "post_mask_code": "\n\n @Override\n public String getSqlDefaultOrderBy() {\n return super.getSqlDefaultOrderBy() + \", sequence_id\";\n }\n\n @Override\n public String getSqlInsert(int rowCount) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"INSERT INTO way_nodes (\");\n resultSql.append(\"way_id, node_id, sequence_id) VALUES \");\n for (int row = 0; row < rowCount; row++) {\n if (row > 0) {\n resultSql.append(\", \");\n }\n resultSql.append(\"(?, ?, ?)\");\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDelete(boolean filterByEntityId) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"DELETE FROM way_nodes\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE \").append(\"way_id = ?\");\n }\n return resultSql.toString();\n }\n\n @Override\n public DbOrderedFeature buildEntity(ResultSet resultSet) {\n try {\n return new DbOrderedFeature(resultSet.getLong(\"entity_id\"), new WayNode(resultSet.getLong(\"node_id\")), resultSet.getInt(\"sequence_id\"));\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to build a way node from the current recordset row.\", e);\n }\n }\n\n @Override\n public int populateEntityParameters(PreparedStatement statement, int initialIndex, DbOrderedFeature entityFeature) {\n try {\n int prmIndex;\n WayNode wayNode;\n wayNode = entityFeature.getFeature();\n prmIndex = initialIndex;\n statement.setLong(prmIndex++, entityFeature.getEntityId());\n statement.setLong(prmIndex++, wayNode.getNodeId());\n statement.setInt(prmIndex++, entityFeature.getSequenceId());\n return prmIndex;\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to populate way node parameters for way \" + entityFeature.getEntityId() + \".\", e);\n }\n }\n}\n"} {"task_id": "Java_938", "language": "Java", "task_type": "single_line", "source_file": "java/github/openstreetmap/osmosis/osmosis-pgsimple/src/main/java/org/openstreetmap/osmosis/pgsimple/v0_6/impl/WayNodeMapper.java", "mask_start_position": 868, "mask_end_position": 922, "canonical_solution": "ECT way_id AS entity_id, node_id, sequence_id FROM \");", "pre_mask_code": "package org.openstreetmap.osmosis.pgsimple.v0_6.impl;\n\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.openstreetmap.osmosis.core.OsmosisRuntimeException;\nimport org.openstreetmap.osmosis.core.database.DbOrderedFeature;\nimport org.openstreetmap.osmosis.core.domain.v0_6.WayNode;\n\n/**\n * Reads and writes way nodes to jdbc classes.\n *\n * @author Brett Henderson\n */\npublic class WayNodeMapper extends EntityFeatureMapper> {\n\n @Override\n public String getParentEntityName() {\n return \"way\";\n }\n\n @Override\n public String getEntityName() {\n return \"way_nodes\";\n }\n\n @Override\n public String getSqlSelect(boolean filterByEntityId, boolean orderBy) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"SEL", "post_mask_code": "\n resultSql.append(\"way_nodes f\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE entity_id = ?\");\n }\n if (orderBy) {\n resultSql.append(getSqlDefaultOrderBy());\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDefaultOrderBy() {\n return super.getSqlDefaultOrderBy() + \", sequence_id\";\n }\n\n @Override\n public String getSqlInsert(int rowCount) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"INSERT INTO way_nodes (\");\n resultSql.append(\"way_id, node_id, sequence_id) VALUES \");\n for (int row = 0; row < rowCount; row++) {\n if (row > 0) {\n resultSql.append(\", \");\n }\n resultSql.append(\"(?, ?, ?)\");\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDelete(boolean filterByEntityId) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"DELETE FROM way_nodes\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE \").append(\"way_id = ?\");\n }\n return resultSql.toString();\n }\n\n @Override\n public DbOrderedFeature buildEntity(ResultSet resultSet) {\n try {\n return new DbOrderedFeature(resultSet.getLong(\"entity_id\"), new WayNode(resultSet.getLong(\"node_id\")), resultSet.getInt(\"sequence_id\"));\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to build a way node from the current recordset row.\", e);\n }\n }\n\n @Override\n public int populateEntityParameters(PreparedStatement statement, int initialIndex, DbOrderedFeature entityFeature) {\n try {\n int prmIndex;\n WayNode wayNode;\n wayNode = entityFeature.getFeature();\n prmIndex = initialIndex;\n statement.setLong(prmIndex++, entityFeature.getEntityId());\n statement.setLong(prmIndex++, wayNode.getNodeId());\n statement.setInt(prmIndex++, entityFeature.getSequenceId());\n return prmIndex;\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to populate way node parameters for way \" + entityFeature.getEntityId() + \".\", e);\n }\n }\n}\n"} {"task_id": "Java_939", "language": "Java", "task_type": "if_statement", "source_file": "java/github/openstreetmap/osmosis/osmosis-pgsimple/src/main/java/org/openstreetmap/osmosis/pgsimple/v0_6/impl/WayNodeMapper.java", "mask_start_position": 1068, "mask_end_position": 1146, "canonical_solution": "if (orderBy) {\n resultSql.append(getSqlDefaultOrderBy());\n }", "pre_mask_code": "package org.openstreetmap.osmosis.pgsimple.v0_6.impl;\n\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.openstreetmap.osmosis.core.OsmosisRuntimeException;\nimport org.openstreetmap.osmosis.core.database.DbOrderedFeature;\nimport org.openstreetmap.osmosis.core.domain.v0_6.WayNode;\n\n/**\n * Reads and writes way nodes to jdbc classes.\n *\n * @author Brett Henderson\n */\npublic class WayNodeMapper extends EntityFeatureMapper> {\n\n @Override\n public String getParentEntityName() {\n return \"way\";\n }\n\n @Override\n public String getEntityName() {\n return \"way_nodes\";\n }\n\n @Override\n public String getSqlSelect(boolean filterByEntityId, boolean orderBy) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"SELECT way_id AS entity_id, node_id, sequence_id FROM \");\n resultSql.append(\"way_nodes f\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE entity_id = ?\");\n }\n ", "post_mask_code": "\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDefaultOrderBy() {\n return super.getSqlDefaultOrderBy() + \", sequence_id\";\n }\n\n @Override\n public String getSqlInsert(int rowCount) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"INSERT INTO way_nodes (\");\n resultSql.append(\"way_id, node_id, sequence_id) VALUES \");\n for (int row = 0; row < rowCount; row++) {\n if (row > 0) {\n resultSql.append(\", \");\n }\n resultSql.append(\"(?, ?, ?)\");\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDelete(boolean filterByEntityId) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"DELETE FROM way_nodes\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE \").append(\"way_id = ?\");\n }\n return resultSql.toString();\n }\n\n @Override\n public DbOrderedFeature buildEntity(ResultSet resultSet) {\n try {\n return new DbOrderedFeature(resultSet.getLong(\"entity_id\"), new WayNode(resultSet.getLong(\"node_id\")), resultSet.getInt(\"sequence_id\"));\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to build a way node from the current recordset row.\", e);\n }\n }\n\n @Override\n public int populateEntityParameters(PreparedStatement statement, int initialIndex, DbOrderedFeature entityFeature) {\n try {\n int prmIndex;\n WayNode wayNode;\n wayNode = entityFeature.getFeature();\n prmIndex = initialIndex;\n statement.setLong(prmIndex++, entityFeature.getEntityId());\n statement.setLong(prmIndex++, wayNode.getNodeId());\n statement.setInt(prmIndex++, entityFeature.getSequenceId());\n return prmIndex;\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to populate way node parameters for way \" + entityFeature.getEntityId() + \".\", e);\n }\n }\n}\n"} {"task_id": "Java_940", "language": "Java", "task_type": "for_statement", "source_file": "java/github/openstreetmap/osmosis/osmosis-pgsimple/src/main/java/org/openstreetmap/osmosis/pgsimple/v0_6/impl/WayNodeMapper.java", "mask_start_position": 1581, "mask_end_position": 1757, "canonical_solution": "for (int row = 0; row < rowCount; row++) {\n if (row > 0) {\n resultSql.append(\", \");\n }\n resultSql.append(\"(?, ?, ?)\");\n }", "pre_mask_code": "package org.openstreetmap.osmosis.pgsimple.v0_6.impl;\n\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.openstreetmap.osmosis.core.OsmosisRuntimeException;\nimport org.openstreetmap.osmosis.core.database.DbOrderedFeature;\nimport org.openstreetmap.osmosis.core.domain.v0_6.WayNode;\n\n/**\n * Reads and writes way nodes to jdbc classes.\n *\n * @author Brett Henderson\n */\npublic class WayNodeMapper extends EntityFeatureMapper> {\n\n @Override\n public String getParentEntityName() {\n return \"way\";\n }\n\n @Override\n public String getEntityName() {\n return \"way_nodes\";\n }\n\n @Override\n public String getSqlSelect(boolean filterByEntityId, boolean orderBy) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"SELECT way_id AS entity_id, node_id, sequence_id FROM \");\n resultSql.append(\"way_nodes f\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE entity_id = ?\");\n }\n if (orderBy) {\n resultSql.append(getSqlDefaultOrderBy());\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDefaultOrderBy() {\n return super.getSqlDefaultOrderBy() + \", sequence_id\";\n }\n\n @Override\n public String getSqlInsert(int rowCount) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"INSERT INTO way_nodes (\");\n resultSql.append(\"way_id, node_id, sequence_id) VALUES \");\n ", "post_mask_code": "\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDelete(boolean filterByEntityId) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"DELETE FROM way_nodes\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE \").append(\"way_id = ?\");\n }\n return resultSql.toString();\n }\n\n @Override\n public DbOrderedFeature buildEntity(ResultSet resultSet) {\n try {\n return new DbOrderedFeature(resultSet.getLong(\"entity_id\"), new WayNode(resultSet.getLong(\"node_id\")), resultSet.getInt(\"sequence_id\"));\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to build a way node from the current recordset row.\", e);\n }\n }\n\n @Override\n public int populateEntityParameters(PreparedStatement statement, int initialIndex, DbOrderedFeature entityFeature) {\n try {\n int prmIndex;\n WayNode wayNode;\n wayNode = entityFeature.getFeature();\n prmIndex = initialIndex;\n statement.setLong(prmIndex++, entityFeature.getEntityId());\n statement.setLong(prmIndex++, wayNode.getNodeId());\n statement.setInt(prmIndex++, entityFeature.getSequenceId());\n return prmIndex;\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to populate way node parameters for way \" + entityFeature.getEntityId() + \".\", e);\n }\n }\n}\n"} {"task_id": "Java_941", "language": "Java", "task_type": "try_statement", "source_file": "java/github/openstreetmap/osmosis/osmosis-pgsimple/src/main/java/org/openstreetmap/osmosis/pgsimple/v0_6/impl/WayNodeMapper.java", "mask_start_position": 2242, "mask_end_position": 2562, "canonical_solution": "try {\n return new DbOrderedFeature(resultSet.getLong(\"entity_id\"), new WayNode(resultSet.getLong(\"node_id\")), resultSet.getInt(\"sequence_id\"));\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to build a way node from the current recordset row.\", e);\n }", "pre_mask_code": "package org.openstreetmap.osmosis.pgsimple.v0_6.impl;\n\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.openstreetmap.osmosis.core.OsmosisRuntimeException;\nimport org.openstreetmap.osmosis.core.database.DbOrderedFeature;\nimport org.openstreetmap.osmosis.core.domain.v0_6.WayNode;\n\n/**\n * Reads and writes way nodes to jdbc classes.\n *\n * @author Brett Henderson\n */\npublic class WayNodeMapper extends EntityFeatureMapper> {\n\n @Override\n public String getParentEntityName() {\n return \"way\";\n }\n\n @Override\n public String getEntityName() {\n return \"way_nodes\";\n }\n\n @Override\n public String getSqlSelect(boolean filterByEntityId, boolean orderBy) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"SELECT way_id AS entity_id, node_id, sequence_id FROM \");\n resultSql.append(\"way_nodes f\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE entity_id = ?\");\n }\n if (orderBy) {\n resultSql.append(getSqlDefaultOrderBy());\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDefaultOrderBy() {\n return super.getSqlDefaultOrderBy() + \", sequence_id\";\n }\n\n @Override\n public String getSqlInsert(int rowCount) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"INSERT INTO way_nodes (\");\n resultSql.append(\"way_id, node_id, sequence_id) VALUES \");\n for (int row = 0; row < rowCount; row++) {\n if (row > 0) {\n resultSql.append(\", \");\n }\n resultSql.append(\"(?, ?, ?)\");\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDelete(boolean filterByEntityId) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"DELETE FROM way_nodes\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE \").append(\"way_id = ?\");\n }\n return resultSql.toString();\n }\n\n @Override\n public DbOrderedFeature buildEntity(ResultSet resultSet) {\n ", "post_mask_code": "\n }\n\n @Override\n public int populateEntityParameters(PreparedStatement statement, int initialIndex, DbOrderedFeature entityFeature) {\n try {\n int prmIndex;\n WayNode wayNode;\n wayNode = entityFeature.getFeature();\n prmIndex = initialIndex;\n statement.setLong(prmIndex++, entityFeature.getEntityId());\n statement.setLong(prmIndex++, wayNode.getNodeId());\n statement.setInt(prmIndex++, entityFeature.getSequenceId());\n return prmIndex;\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to populate way node parameters for way \" + entityFeature.getEntityId() + \".\", e);\n }\n }\n}\n"} {"task_id": "Java_942", "language": "Java", "task_type": "empty", "source_file": "java/github/openstreetmap/osmosis/osmosis-pgsimple/src/main/java/org/openstreetmap/osmosis/pgsimple/v0_6/impl/WayNodeMapper.java", "mask_start_position": 1371, "mask_end_position": 1371, "canonical_solution": "", "pre_mask_code": "package org.openstreetmap.osmosis.pgsimple.v0_6.impl;\n\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.openstreetmap.osmosis.core.OsmosisRuntimeException;\nimport org.openstreetmap.osmosis.core.database.DbOrderedFeature;\nimport org.openstreetmap.osmosis.core.domain.v0_6.WayNode;\n\n/**\n * Reads and writes way nodes to jdbc classes.\n *\n * @author Brett Henderson\n */\npublic class WayNodeMapper extends EntityFeatureMapper> {\n\n @Override\n public String getParentEntityName() {\n return \"way\";\n }\n\n @Override\n public String getEntityName() {\n return \"way_nodes\";\n }\n\n @Override\n public String getSqlSelect(boolean filterByEntityId, boolean orderBy) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"SELECT way_id AS entity_id, node_id, sequence_id FROM \");\n resultSql.append(\"way_nodes f\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE entity_id = ?\");\n }\n if (orderBy) {\n resultSql.append(getSqlDefaultOrderBy());\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDefaultOrderBy() {\n return super.getSqlDefaultOrderBy() + \", sequence_id\";\n }\n\n @Override\n public String getSqlInsert(int rowC", "post_mask_code": "ount) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"INSERT INTO way_nodes (\");\n resultSql.append(\"way_id, node_id, sequence_id) VALUES \");\n for (int row = 0; row < rowCount; row++) {\n if (row > 0) {\n resultSql.append(\", \");\n }\n resultSql.append(\"(?, ?, ?)\");\n }\n return resultSql.toString();\n }\n\n @Override\n public String getSqlDelete(boolean filterByEntityId) {\n StringBuilder resultSql;\n resultSql = new StringBuilder();\n resultSql.append(\"DELETE FROM way_nodes\");\n if (filterByEntityId) {\n resultSql.append(\" WHERE \").append(\"way_id = ?\");\n }\n return resultSql.toString();\n }\n\n @Override\n public DbOrderedFeature buildEntity(ResultSet resultSet) {\n try {\n return new DbOrderedFeature(resultSet.getLong(\"entity_id\"), new WayNode(resultSet.getLong(\"node_id\")), resultSet.getInt(\"sequence_id\"));\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to build a way node from the current recordset row.\", e);\n }\n }\n\n @Override\n public int populateEntityParameters(PreparedStatement statement, int initialIndex, DbOrderedFeature entityFeature) {\n try {\n int prmIndex;\n WayNode wayNode;\n wayNode = entityFeature.getFeature();\n prmIndex = initialIndex;\n statement.setLong(prmIndex++, entityFeature.getEntityId());\n statement.setLong(prmIndex++, wayNode.getNodeId());\n statement.setInt(prmIndex++, entityFeature.getSequenceId());\n return prmIndex;\n } catch (SQLException e) {\n throw new OsmosisRuntimeException(\"Unable to populate way node parameters for way \" + entityFeature.getEntityId() + \".\", e);\n }\n }\n}\n"} {"task_id": "Java_943", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/geode/geode-for-redis/src/main/java/org/apache/geode/redis/internal/data/KeyHashUtil.java", "mask_start_position": 437, "mask_end_position": 480, "canonical_solution": "public static short slotForKey(byte[] key) ", "pre_mask_code": "package org.apache.geode.redis.internal.data;\n\nimport static org.apache.geode.redis.internal.RegionProvider.REDIS_SLOTS;\nimport org.apache.geode.redis.internal.executor.cluster.CRC16;\n\n/**\n * Utility for parsing the hashtags in a redis key and computing the redis slot of the key.\n */\npublic class KeyHashUtil {\n\n /**\n * Compute the slot of a given redis key\n *\n * @return the slot, a value between 0 and 16K.\n */\n ", "post_mask_code": "{\n int startHashtag;\n int endHashtag;\n for (startHashtag = 0; startHashtag < key.length; startHashtag++) {\n if (key[startHashtag] == '{') {\n break;\n }\n }\n // No starting hashtag, hash the whole thing\n if (startHashtag == key.length) {\n return crc16(key, 0, key.length);\n }\n for (endHashtag = startHashtag + 1; endHashtag < key.length; endHashtag++) {\n if (key[endHashtag] == '}') {\n break;\n }\n }\n // No ending hashtag, or empty hashtag. Hash the whole thing.\n if (endHashtag == key.length || endHashtag == startHashtag + 1) {\n return crc16(key, 0, key.length);\n }\n return crc16(key, startHashtag + 1, endHashtag);\n }\n\n private static short crc16(byte[] key, int start, int end) {\n return (short) (CRC16.calculate(key, start, end) & (REDIS_SLOTS - 1));\n }\n}\n"} {"task_id": "Java_944", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/geode/geode-for-redis/src/main/java/org/apache/geode/redis/internal/data/KeyHashUtil.java", "mask_start_position": 1351, "mask_end_position": 1437, "canonical_solution": "{\n return (short) (CRC16.calculate(key, start, end) & (REDIS_SLOTS - 1));\n }", "pre_mask_code": "package org.apache.geode.redis.internal.data;\n\nimport static org.apache.geode.redis.internal.RegionProvider.REDIS_SLOTS;\nimport org.apache.geode.redis.internal.executor.cluster.CRC16;\n\n/**\n * Utility for parsing the hashtags in a redis key and computing the redis slot of the key.\n */\npublic class KeyHashUtil {\n\n /**\n * Compute the slot of a given redis key\n *\n * @return the slot, a value between 0 and 16K.\n */\n public static short slotForKey(byte[] key) {\n int startHashtag;\n int endHashtag;\n for (startHashtag = 0; startHashtag < key.length; startHashtag++) {\n if (key[startHashtag] == '{') {\n break;\n }\n }\n // No starting hashtag, hash the whole thing\n if (startHashtag == key.length) {\n return crc16(key, 0, key.length);\n }\n for (endHashtag = startHashtag + 1; endHashtag < key.length; endHashtag++) {\n if (key[endHashtag] == '}') {\n break;\n }\n }\n // No ending hashtag, or empty hashtag. Hash the whole thing.\n if (endHashtag == key.length || endHashtag == startHashtag + 1) {\n return crc16(key, 0, key.length);\n }\n return crc16(key, startHashtag + 1, endHashtag);\n }\n\n private static short crc16(byte[] key, int start, int end) ", "post_mask_code": "\n}\n"} {"task_id": "Java_945", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/geode/geode-for-redis/src/main/java/org/apache/geode/redis/internal/data/KeyHashUtil.java", "mask_start_position": 481, "mask_end_position": 698, "canonical_solution": "\n int startHashtag;\n int endHashtag;\n for (startHashtag = 0; startHashtag < key.length; startHashtag++) {\n if (key[startHashtag] == '{') {\n break;\n }\n }", "pre_mask_code": "package org.apache.geode.redis.internal.data;\n\nimport static org.apache.geode.redis.internal.RegionProvider.REDIS_SLOTS;\nimport org.apache.geode.redis.internal.executor.cluster.CRC16;\n\n/**\n * Utility for parsing the hashtags in a redis key and computing the redis slot of the key.\n */\npublic class KeyHashUtil {\n\n /**\n * Compute the slot of a given redis key\n *\n * @return the slot, a value between 0 and 16K.\n */\n public static short slotForKey(byte[] key) {", "post_mask_code": "\n // No starting hashtag, hash the whole thing\n if (startHashtag == key.length) {\n return crc16(key, 0, key.length);\n }\n for (endHashtag = startHashtag + 1; endHashtag < key.length; endHashtag++) {\n if (key[endHashtag] == '}') {\n break;\n }\n }\n // No ending hashtag, or empty hashtag. Hash the whole thing.\n if (endHashtag == key.length || endHashtag == startHashtag + 1) {\n return crc16(key, 0, key.length);\n }\n return crc16(key, startHashtag + 1, endHashtag);\n }\n\n private static short crc16(byte[] key, int start, int end) {\n return (short) (CRC16.calculate(key, start, end) & (REDIS_SLOTS - 1));\n }\n}\n"} {"task_id": "Java_946", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/geode/geode-for-redis/src/main/java/org/apache/geode/redis/internal/data/KeyHashUtil.java", "mask_start_position": 707, "mask_end_position": 1023, "canonical_solution": "// No starting hashtag, hash the whole thing\n if (startHashtag == key.length) {\n return crc16(key, 0, key.length);\n }\n for (endHashtag = startHashtag + 1; endHashtag < key.length; endHashtag++) {\n if (key[endHashtag] == '}') {\n break;\n }\n }", "pre_mask_code": "package org.apache.geode.redis.internal.data;\n\nimport static org.apache.geode.redis.internal.RegionProvider.REDIS_SLOTS;\nimport org.apache.geode.redis.internal.executor.cluster.CRC16;\n\n/**\n * Utility for parsing the hashtags in a redis key and computing the redis slot of the key.\n */\npublic class KeyHashUtil {\n\n /**\n * Compute the slot of a given redis key\n *\n * @return the slot, a value between 0 and 16K.\n */\n public static short slotForKey(byte[] key) {\n int startHashtag;\n int endHashtag;\n for (startHashtag = 0; startHashtag < key.length; startHashtag++) {\n if (key[startHashtag] == '{') {\n break;\n }\n }\n ", "post_mask_code": "\n // No ending hashtag, or empty hashtag. Hash the whole thing.\n if (endHashtag == key.length || endHashtag == startHashtag + 1) {\n return crc16(key, 0, key.length);\n }\n return crc16(key, startHashtag + 1, endHashtag);\n }\n\n private static short crc16(byte[] key, int start, int end) {\n return (short) (CRC16.calculate(key, start, end) & (REDIS_SLOTS - 1));\n }\n}\n"} {"task_id": "Java_947", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/geode/geode-for-redis/src/main/java/org/apache/geode/redis/internal/data/KeyHashUtil.java", "mask_start_position": 1032, "mask_end_position": 1286, "canonical_solution": "// No ending hashtag, or empty hashtag. Hash the whole thing.\n if (endHashtag == key.length || endHashtag == startHashtag + 1) {\n return crc16(key, 0, key.length);\n }\n return crc16(key, startHashtag + 1, endHashtag);\n }", "pre_mask_code": "package org.apache.geode.redis.internal.data;\n\nimport static org.apache.geode.redis.internal.RegionProvider.REDIS_SLOTS;\nimport org.apache.geode.redis.internal.executor.cluster.CRC16;\n\n/**\n * Utility for parsing the hashtags in a redis key and computing the redis slot of the key.\n */\npublic class KeyHashUtil {\n\n /**\n * Compute the slot of a given redis key\n *\n * @return the slot, a value between 0 and 16K.\n */\n public static short slotForKey(byte[] key) {\n int startHashtag;\n int endHashtag;\n for (startHashtag = 0; startHashtag < key.length; startHashtag++) {\n if (key[startHashtag] == '{') {\n break;\n }\n }\n // No starting hashtag, hash the whole thing\n if (startHashtag == key.length) {\n return crc16(key, 0, key.length);\n }\n for (endHashtag = startHashtag + 1; endHashtag < key.length; endHashtag++) {\n if (key[endHashtag] == '}') {\n break;\n }\n }\n ", "post_mask_code": "\n\n private static short crc16(byte[] key, int start, int end) {\n return (short) (CRC16.calculate(key, start, end) & (REDIS_SLOTS - 1));\n }\n}\n"} {"task_id": "Java_948", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/geode/geode-for-redis/src/main/java/org/apache/geode/redis/internal/data/KeyHashUtil.java", "mask_start_position": 1239, "mask_end_position": 1280, "canonical_solution": "crc16(key, startHashtag + 1, endHashtag);", "pre_mask_code": "package org.apache.geode.redis.internal.data;\n\nimport static org.apache.geode.redis.internal.RegionProvider.REDIS_SLOTS;\nimport org.apache.geode.redis.internal.executor.cluster.CRC16;\n\n/**\n * Utility for parsing the hashtags in a redis key and computing the redis slot of the key.\n */\npublic class KeyHashUtil {\n\n /**\n * Compute the slot of a given redis key\n *\n * @return the slot, a value between 0 and 16K.\n */\n public static short slotForKey(byte[] key) {\n int startHashtag;\n int endHashtag;\n for (startHashtag = 0; startHashtag < key.length; startHashtag++) {\n if (key[startHashtag] == '{') {\n break;\n }\n }\n // No starting hashtag, hash the whole thing\n if (startHashtag == key.length) {\n return crc16(key, 0, key.length);\n }\n for (endHashtag = startHashtag + 1; endHashtag < key.length; endHashtag++) {\n if (key[endHashtag] == '}') {\n break;\n }\n }\n // No ending hashtag, or empty hashtag. Hash the whole thing.\n if (endHashtag == key.length || endHashtag == startHashtag + 1) {\n return crc16(key, 0, key.length);\n }\n return ", "post_mask_code": "\n }\n\n private static short crc16(byte[] key, int start, int end) {\n return (short) (CRC16.calculate(key, start, end) & (REDIS_SLOTS - 1));\n }\n}\n"} {"task_id": "Java_949", "language": "Java", "task_type": "if_statement", "source_file": "java/github/apache/geode/geode-for-redis/src/main/java/org/apache/geode/redis/internal/data/KeyHashUtil.java", "mask_start_position": 947, "mask_end_position": 1013, "canonical_solution": "if (key[endHashtag] == '}') {\n break;\n }", "pre_mask_code": "package org.apache.geode.redis.internal.data;\n\nimport static org.apache.geode.redis.internal.RegionProvider.REDIS_SLOTS;\nimport org.apache.geode.redis.internal.executor.cluster.CRC16;\n\n/**\n * Utility for parsing the hashtags in a redis key and computing the redis slot of the key.\n */\npublic class KeyHashUtil {\n\n /**\n * Compute the slot of a given redis key\n *\n * @return the slot, a value between 0 and 16K.\n */\n public static short slotForKey(byte[] key) {\n int startHashtag;\n int endHashtag;\n for (startHashtag = 0; startHashtag < key.length; startHashtag++) {\n if (key[startHashtag] == '{') {\n break;\n }\n }\n // No starting hashtag, hash the whole thing\n if (startHashtag == key.length) {\n return crc16(key, 0, key.length);\n }\n for (endHashtag = startHashtag + 1; endHashtag < key.length; endHashtag++) {\n ", "post_mask_code": "\n }\n // No ending hashtag, or empty hashtag. Hash the whole thing.\n if (endHashtag == key.length || endHashtag == startHashtag + 1) {\n return crc16(key, 0, key.length);\n }\n return crc16(key, startHashtag + 1, endHashtag);\n }\n\n private static short crc16(byte[] key, int start, int end) {\n return (short) (CRC16.calculate(key, start, end) & (REDIS_SLOTS - 1));\n }\n}\n"} {"task_id": "Java_950", "language": "Java", "task_type": "for_statement", "source_file": "java/github/apache/geode/geode-for-redis/src/main/java/org/apache/geode/redis/internal/data/KeyHashUtil.java", "mask_start_position": 540, "mask_end_position": 698, "canonical_solution": "for (startHashtag = 0; startHashtag < key.length; startHashtag++) {\n if (key[startHashtag] == '{') {\n break;\n }\n }", "pre_mask_code": "package org.apache.geode.redis.internal.data;\n\nimport static org.apache.geode.redis.internal.RegionProvider.REDIS_SLOTS;\nimport org.apache.geode.redis.internal.executor.cluster.CRC16;\n\n/**\n * Utility for parsing the hashtags in a redis key and computing the redis slot of the key.\n */\npublic class KeyHashUtil {\n\n /**\n * Compute the slot of a given redis key\n *\n * @return the slot, a value between 0 and 16K.\n */\n public static short slotForKey(byte[] key) {\n int startHashtag;\n int endHashtag;\n ", "post_mask_code": "\n // No starting hashtag, hash the whole thing\n if (startHashtag == key.length) {\n return crc16(key, 0, key.length);\n }\n for (endHashtag = startHashtag + 1; endHashtag < key.length; endHashtag++) {\n if (key[endHashtag] == '}') {\n break;\n }\n }\n // No ending hashtag, or empty hashtag. Hash the whole thing.\n if (endHashtag == key.length || endHashtag == startHashtag + 1) {\n return crc16(key, 0, key.length);\n }\n return crc16(key, startHashtag + 1, endHashtag);\n }\n\n private static short crc16(byte[] key, int start, int end) {\n return (short) (CRC16.calculate(key, start, end) & (REDIS_SLOTS - 1));\n }\n}\n"} {"task_id": "Java_951", "language": "Java", "task_type": "empty", "source_file": "java/github/apache/geode/geode-for-redis/src/main/java/org/apache/geode/redis/internal/data/KeyHashUtil.java", "mask_start_position": 1269, "mask_end_position": 1269, "canonical_solution": "", "pre_mask_code": "package org.apache.geode.redis.internal.data;\n\nimport static org.apache.geode.redis.internal.RegionProvider.REDIS_SLOTS;\nimport org.apache.geode.redis.internal.executor.cluster.CRC16;\n\n/**\n * Utility for parsing the hashtags in a redis key and computing the redis slot of the key.\n */\npublic class KeyHashUtil {\n\n /**\n * Compute the slot of a given redis key\n *\n * @return the slot, a value between 0 and 16K.\n */\n public static short slotForKey(byte[] key) {\n int startHashtag;\n int endHashtag;\n for (startHashtag = 0; startHashtag < key.length; startHashtag++) {\n if (key[startHashtag] == '{') {\n break;\n }\n }\n // No starting hashtag, hash the whole thing\n if (startHashtag == key.length) {\n return crc16(key, 0, key.length);\n }\n for (endHashtag = startHashtag + 1; endHashtag < key.length; endHashtag++) {\n if (key[endHashtag] == '}') {\n break;\n }\n }\n // No ending hashtag, or empty hashtag. Hash the whole thing.\n if (endHashtag == key.length || endHashtag == startHashtag + 1) {\n return crc16(key, 0, key.length);\n }\n return crc16(key, startHashtag + 1, e", "post_mask_code": "ndHashtag);\n }\n\n private static short crc16(byte[] key, int start, int end) {\n return (short) (CRC16.calculate(key, start, end) & (REDIS_SLOTS - 1));\n }\n}\n"} {"task_id": "Java_952", "language": "Java", "task_type": "method_signature", "source_file": "java/github/confluentinc/ksql/ksqldb-serde/src/main/java/io/confluent/ksql/serde/delimited/KsqlDelimitedSerializer.java", "mask_start_position": 3932, "mask_end_position": 3992, "canonical_solution": "private static String handleDecimal(final BigDecimal value) ", "pre_mask_code": "package io.confluent.ksql.serde.delimited;\n\nimport io.confluent.ksql.schema.ksql.PersistenceSchema;\nimport io.confluent.ksql.schema.ksql.SimpleColumn;\nimport io.confluent.ksql.serde.SerdeUtils;\nimport java.io.StringWriter;\nimport java.math.BigDecimal;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.sql.Date;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Base64;\nimport java.util.Base64.Encoder;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport org.apache.commons.csv.CSVFormat;\nimport org.apache.commons.csv.CSVPrinter;\nimport org.apache.kafka.common.errors.SerializationException;\nimport org.apache.kafka.common.serialization.Serializer;\n\nclass KsqlDelimitedSerializer implements Serializer> {\n\n private static Encoder BASE64_ENCODER = Base64.getEncoder();\n\n private final PersistenceSchema schema;\n\n private final CSVFormat csvFormat;\n\n KsqlDelimitedSerializer(final PersistenceSchema schema, final CSVFormat csvFormat) {\n this.schema = Objects.requireNonNull(schema, \"schema\");\n this.csvFormat = Objects.requireNonNull(csvFormat, \"csvFormat\");\n }\n\n @Override\n public void configure(final Map map, final boolean b) {\n }\n\n @Override\n public byte[] serialize(final String topic, final List data) {\n if (data == null) {\n return null;\n }\n try {\n final StringWriter stringWriter = new StringWriter();\n final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);\n csvPrinter.printRecord(() -> new FieldIterator(data, schema));\n final String result = stringWriter.toString();\n return result.substring(0, result.length() - 2).getBytes(StandardCharsets.UTF_8);\n } catch (final Exception e) {\n throw new SerializationException(\"Error serializing CSV message\", e);\n }\n }\n\n @Override\n public void close() {\n }\n\n private static class FieldIterator implements Iterator {\n\n private final Iterator dataIt;\n\n private final Iterator columnIt;\n\n FieldIterator(final List data, final PersistenceSchema schema) {\n this.dataIt = data.iterator();\n this.columnIt = schema.columns().iterator();\n }\n\n @Override\n public boolean hasNext() {\n return columnIt.hasNext();\n }\n\n @Override\n public Object next() {\n final Object value = dataIt.next();\n final SimpleColumn column = columnIt.next();\n switch(column.type().baseType()) {\n case DECIMAL:\n return handleDecimal((BigDecimal) value);\n case BYTES:\n return handleBytes((ByteBuffer) value);\n case TIME:\n return handleTime((Time) value);\n case DATE:\n return handleDate((Date) value);\n case TIMESTAMP:\n return handleTimestamp((Timestamp) value);\n default:\n return value;\n }\n }\n\n private static String handleBytes(final ByteBuffer value) {\n // Return base64 encoding\n return value == null ? null : BASE64_ENCODER.encodeToString(value.array());\n }\n\n private static Integer handleTime(final Time value) {\n // Return milliseconds\n return value == null ? null : (int) value.getTime();\n }\n\n private static Integer handleDate(final Date value) {\n // Return epoch days\n return value == null ? null : SerdeUtils.toEpochDays(value);\n }\n\n private static Long handleTimestamp(final Timestamp value) {\n // Return milliseconds\n return value == null ? null : value.getTime();\n }\n\n ", "post_mask_code": "{\n // Avoid scientific notation for now:\n return value.toPlainString();\n }\n }\n}\n"} {"task_id": "Java_953", "language": "Java", "task_type": "method_body", "source_file": "java/github/confluentinc/ksql/ksqldb-serde/src/main/java/io/confluent/ksql/serde/delimited/KsqlDelimitedSerializer.java", "mask_start_position": 3458, "mask_end_position": 3569, "canonical_solution": "{\n // Return milliseconds\n return value == null ? null : (int) value.getTime();\n }", "pre_mask_code": "package io.confluent.ksql.serde.delimited;\n\nimport io.confluent.ksql.schema.ksql.PersistenceSchema;\nimport io.confluent.ksql.schema.ksql.SimpleColumn;\nimport io.confluent.ksql.serde.SerdeUtils;\nimport java.io.StringWriter;\nimport java.math.BigDecimal;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.sql.Date;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Base64;\nimport java.util.Base64.Encoder;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport org.apache.commons.csv.CSVFormat;\nimport org.apache.commons.csv.CSVPrinter;\nimport org.apache.kafka.common.errors.SerializationException;\nimport org.apache.kafka.common.serialization.Serializer;\n\nclass KsqlDelimitedSerializer implements Serializer> {\n\n private static Encoder BASE64_ENCODER = Base64.getEncoder();\n\n private final PersistenceSchema schema;\n\n private final CSVFormat csvFormat;\n\n KsqlDelimitedSerializer(final PersistenceSchema schema, final CSVFormat csvFormat) {\n this.schema = Objects.requireNonNull(schema, \"schema\");\n this.csvFormat = Objects.requireNonNull(csvFormat, \"csvFormat\");\n }\n\n @Override\n public void configure(final Map map, final boolean b) {\n }\n\n @Override\n public byte[] serialize(final String topic, final List data) {\n if (data == null) {\n return null;\n }\n try {\n final StringWriter stringWriter = new StringWriter();\n final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);\n csvPrinter.printRecord(() -> new FieldIterator(data, schema));\n final String result = stringWriter.toString();\n return result.substring(0, result.length() - 2).getBytes(StandardCharsets.UTF_8);\n } catch (final Exception e) {\n throw new SerializationException(\"Error serializing CSV message\", e);\n }\n }\n\n @Override\n public void close() {\n }\n\n private static class FieldIterator implements Iterator {\n\n private final Iterator dataIt;\n\n private final Iterator columnIt;\n\n FieldIterator(final List data, final PersistenceSchema schema) {\n this.dataIt = data.iterator();\n this.columnIt = schema.columns().iterator();\n }\n\n @Override\n public boolean hasNext() {\n return columnIt.hasNext();\n }\n\n @Override\n public Object next() {\n final Object value = dataIt.next();\n final SimpleColumn column = columnIt.next();\n switch(column.type().baseType()) {\n case DECIMAL:\n return handleDecimal((BigDecimal) value);\n case BYTES:\n return handleBytes((ByteBuffer) value);\n case TIME:\n return handleTime((Time) value);\n case DATE:\n return handleDate((Date) value);\n case TIMESTAMP:\n return handleTimestamp((Timestamp) value);\n default:\n return value;\n }\n }\n\n private static String handleBytes(final ByteBuffer value) {\n // Return base64 encoding\n return value == null ? null : BASE64_ENCODER.encodeToString(value.array());\n }\n\n private static Integer handleTime(final Time value) ", "post_mask_code": "\n\n private static Integer handleDate(final Date value) {\n // Return epoch days\n return value == null ? null : SerdeUtils.toEpochDays(value);\n }\n\n private static Long handleTimestamp(final Timestamp value) {\n // Return milliseconds\n return value == null ? null : value.getTime();\n }\n\n private static String handleDecimal(final BigDecimal value) {\n // Avoid scientific notation for now:\n return value.toPlainString();\n }\n }\n}\n"} {"task_id": "Java_954", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/confluentinc/ksql/ksqldb-serde/src/main/java/io/confluent/ksql/serde/delimited/KsqlDelimitedSerializer.java", "mask_start_position": 2521, "mask_end_position": 2569, "canonical_solution": "\n final Object value = dataIt.next();", "pre_mask_code": "package io.confluent.ksql.serde.delimited;\n\nimport io.confluent.ksql.schema.ksql.PersistenceSchema;\nimport io.confluent.ksql.schema.ksql.SimpleColumn;\nimport io.confluent.ksql.serde.SerdeUtils;\nimport java.io.StringWriter;\nimport java.math.BigDecimal;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.sql.Date;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Base64;\nimport java.util.Base64.Encoder;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport org.apache.commons.csv.CSVFormat;\nimport org.apache.commons.csv.CSVPrinter;\nimport org.apache.kafka.common.errors.SerializationException;\nimport org.apache.kafka.common.serialization.Serializer;\n\nclass KsqlDelimitedSerializer implements Serializer> {\n\n private static Encoder BASE64_ENCODER = Base64.getEncoder();\n\n private final PersistenceSchema schema;\n\n private final CSVFormat csvFormat;\n\n KsqlDelimitedSerializer(final PersistenceSchema schema, final CSVFormat csvFormat) {\n this.schema = Objects.requireNonNull(schema, \"schema\");\n this.csvFormat = Objects.requireNonNull(csvFormat, \"csvFormat\");\n }\n\n @Override\n public void configure(final Map map, final boolean b) {\n }\n\n @Override\n public byte[] serialize(final String topic, final List data) {\n if (data == null) {\n return null;\n }\n try {\n final StringWriter stringWriter = new StringWriter();\n final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);\n csvPrinter.printRecord(() -> new FieldIterator(data, schema));\n final String result = stringWriter.toString();\n return result.substring(0, result.length() - 2).getBytes(StandardCharsets.UTF_8);\n } catch (final Exception e) {\n throw new SerializationException(\"Error serializing CSV message\", e);\n }\n }\n\n @Override\n public void close() {\n }\n\n private static class FieldIterator implements Iterator {\n\n private final Iterator dataIt;\n\n private final Iterator columnIt;\n\n FieldIterator(final List data, final PersistenceSchema schema) {\n this.dataIt = data.iterator();\n this.columnIt = schema.columns().iterator();\n }\n\n @Override\n public boolean hasNext() {\n return columnIt.hasNext();\n }\n\n @Override\n public Object next() {", "post_mask_code": "\n final SimpleColumn column = columnIt.next();\n switch(column.type().baseType()) {\n case DECIMAL:\n return handleDecimal((BigDecimal) value);\n case BYTES:\n return handleBytes((ByteBuffer) value);\n case TIME:\n return handleTime((Time) value);\n case DATE:\n return handleDate((Date) value);\n case TIMESTAMP:\n return handleTimestamp((Timestamp) value);\n default:\n return value;\n }\n }\n\n private static String handleBytes(final ByteBuffer value) {\n // Return base64 encoding\n return value == null ? null : BASE64_ENCODER.encodeToString(value.array());\n }\n\n private static Integer handleTime(final Time value) {\n // Return milliseconds\n return value == null ? null : (int) value.getTime();\n }\n\n private static Integer handleDate(final Date value) {\n // Return epoch days\n return value == null ? null : SerdeUtils.toEpochDays(value);\n }\n\n private static Long handleTimestamp(final Timestamp value) {\n // Return milliseconds\n return value == null ? null : value.getTime();\n }\n\n private static String handleDecimal(final BigDecimal value) {\n // Avoid scientific notation for now:\n return value.toPlainString();\n }\n }\n}\n"} {"task_id": "Java_955", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/confluentinc/ksql/ksqldb-serde/src/main/java/io/confluent/ksql/serde/delimited/KsqlDelimitedSerializer.java", "mask_start_position": 2582, "mask_end_position": 2626, "canonical_solution": "final SimpleColumn column = columnIt.next();", "pre_mask_code": "package io.confluent.ksql.serde.delimited;\n\nimport io.confluent.ksql.schema.ksql.PersistenceSchema;\nimport io.confluent.ksql.schema.ksql.SimpleColumn;\nimport io.confluent.ksql.serde.SerdeUtils;\nimport java.io.StringWriter;\nimport java.math.BigDecimal;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.sql.Date;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Base64;\nimport java.util.Base64.Encoder;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport org.apache.commons.csv.CSVFormat;\nimport org.apache.commons.csv.CSVPrinter;\nimport org.apache.kafka.common.errors.SerializationException;\nimport org.apache.kafka.common.serialization.Serializer;\n\nclass KsqlDelimitedSerializer implements Serializer> {\n\n private static Encoder BASE64_ENCODER = Base64.getEncoder();\n\n private final PersistenceSchema schema;\n\n private final CSVFormat csvFormat;\n\n KsqlDelimitedSerializer(final PersistenceSchema schema, final CSVFormat csvFormat) {\n this.schema = Objects.requireNonNull(schema, \"schema\");\n this.csvFormat = Objects.requireNonNull(csvFormat, \"csvFormat\");\n }\n\n @Override\n public void configure(final Map map, final boolean b) {\n }\n\n @Override\n public byte[] serialize(final String topic, final List data) {\n if (data == null) {\n return null;\n }\n try {\n final StringWriter stringWriter = new StringWriter();\n final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);\n csvPrinter.printRecord(() -> new FieldIterator(data, schema));\n final String result = stringWriter.toString();\n return result.substring(0, result.length() - 2).getBytes(StandardCharsets.UTF_8);\n } catch (final Exception e) {\n throw new SerializationException(\"Error serializing CSV message\", e);\n }\n }\n\n @Override\n public void close() {\n }\n\n private static class FieldIterator implements Iterator {\n\n private final Iterator dataIt;\n\n private final Iterator columnIt;\n\n FieldIterator(final List data, final PersistenceSchema schema) {\n this.dataIt = data.iterator();\n this.columnIt = schema.columns().iterator();\n }\n\n @Override\n public boolean hasNext() {\n return columnIt.hasNext();\n }\n\n @Override\n public Object next() {\n final Object value = dataIt.next();\n ", "post_mask_code": "\n switch(column.type().baseType()) {\n case DECIMAL:\n return handleDecimal((BigDecimal) value);\n case BYTES:\n return handleBytes((ByteBuffer) value);\n case TIME:\n return handleTime((Time) value);\n case DATE:\n return handleDate((Date) value);\n case TIMESTAMP:\n return handleTimestamp((Timestamp) value);\n default:\n return value;\n }\n }\n\n private static String handleBytes(final ByteBuffer value) {\n // Return base64 encoding\n return value == null ? null : BASE64_ENCODER.encodeToString(value.array());\n }\n\n private static Integer handleTime(final Time value) {\n // Return milliseconds\n return value == null ? null : (int) value.getTime();\n }\n\n private static Integer handleDate(final Date value) {\n // Return epoch days\n return value == null ? null : SerdeUtils.toEpochDays(value);\n }\n\n private static Long handleTimestamp(final Timestamp value) {\n // Return milliseconds\n return value == null ? null : value.getTime();\n }\n\n private static String handleDecimal(final BigDecimal value) {\n // Avoid scientific notation for now:\n return value.toPlainString();\n }\n }\n}\n"} {"task_id": "Java_956", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/confluentinc/ksql/ksqldb-serde/src/main/java/io/confluent/ksql/serde/delimited/KsqlDelimitedSerializer.java", "mask_start_position": 2639, "mask_end_position": 3191, "canonical_solution": "switch(column.type().baseType()) {\n case DECIMAL:\n return handleDecimal((BigDecimal) value);\n case BYTES:\n return handleBytes((ByteBuffer) value);\n case TIME:\n return handleTime((Time) value);\n case DATE:\n return handleDate((Date) value);\n case TIMESTAMP:\n return handleTimestamp((Timestamp) value);\n default:\n return value;\n }\n }", "pre_mask_code": "package io.confluent.ksql.serde.delimited;\n\nimport io.confluent.ksql.schema.ksql.PersistenceSchema;\nimport io.confluent.ksql.schema.ksql.SimpleColumn;\nimport io.confluent.ksql.serde.SerdeUtils;\nimport java.io.StringWriter;\nimport java.math.BigDecimal;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.sql.Date;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Base64;\nimport java.util.Base64.Encoder;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport org.apache.commons.csv.CSVFormat;\nimport org.apache.commons.csv.CSVPrinter;\nimport org.apache.kafka.common.errors.SerializationException;\nimport org.apache.kafka.common.serialization.Serializer;\n\nclass KsqlDelimitedSerializer implements Serializer> {\n\n private static Encoder BASE64_ENCODER = Base64.getEncoder();\n\n private final PersistenceSchema schema;\n\n private final CSVFormat csvFormat;\n\n KsqlDelimitedSerializer(final PersistenceSchema schema, final CSVFormat csvFormat) {\n this.schema = Objects.requireNonNull(schema, \"schema\");\n this.csvFormat = Objects.requireNonNull(csvFormat, \"csvFormat\");\n }\n\n @Override\n public void configure(final Map map, final boolean b) {\n }\n\n @Override\n public byte[] serialize(final String topic, final List data) {\n if (data == null) {\n return null;\n }\n try {\n final StringWriter stringWriter = new StringWriter();\n final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);\n csvPrinter.printRecord(() -> new FieldIterator(data, schema));\n final String result = stringWriter.toString();\n return result.substring(0, result.length() - 2).getBytes(StandardCharsets.UTF_8);\n } catch (final Exception e) {\n throw new SerializationException(\"Error serializing CSV message\", e);\n }\n }\n\n @Override\n public void close() {\n }\n\n private static class FieldIterator implements Iterator {\n\n private final Iterator dataIt;\n\n private final Iterator columnIt;\n\n FieldIterator(final List data, final PersistenceSchema schema) {\n this.dataIt = data.iterator();\n this.columnIt = schema.columns().iterator();\n }\n\n @Override\n public boolean hasNext() {\n return columnIt.hasNext();\n }\n\n @Override\n public Object next() {\n final Object value = dataIt.next();\n final SimpleColumn column = columnIt.next();\n ", "post_mask_code": "\n\n private static String handleBytes(final ByteBuffer value) {\n // Return base64 encoding\n return value == null ? null : BASE64_ENCODER.encodeToString(value.array());\n }\n\n private static Integer handleTime(final Time value) {\n // Return milliseconds\n return value == null ? null : (int) value.getTime();\n }\n\n private static Integer handleDate(final Date value) {\n // Return epoch days\n return value == null ? null : SerdeUtils.toEpochDays(value);\n }\n\n private static Long handleTimestamp(final Timestamp value) {\n // Return milliseconds\n return value == null ? null : value.getTime();\n }\n\n private static String handleDecimal(final BigDecimal value) {\n // Avoid scientific notation for now:\n return value.toPlainString();\n }\n }\n}\n"} {"task_id": "Java_957", "language": "Java", "task_type": "single_line", "source_file": "java/github/confluentinc/ksql/ksqldb-serde/src/main/java/io/confluent/ksql/serde/delimited/KsqlDelimitedSerializer.java", "mask_start_position": 2623, "mask_end_position": 2626, "canonical_solution": "();", "pre_mask_code": "package io.confluent.ksql.serde.delimited;\n\nimport io.confluent.ksql.schema.ksql.PersistenceSchema;\nimport io.confluent.ksql.schema.ksql.SimpleColumn;\nimport io.confluent.ksql.serde.SerdeUtils;\nimport java.io.StringWriter;\nimport java.math.BigDecimal;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.sql.Date;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Base64;\nimport java.util.Base64.Encoder;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport org.apache.commons.csv.CSVFormat;\nimport org.apache.commons.csv.CSVPrinter;\nimport org.apache.kafka.common.errors.SerializationException;\nimport org.apache.kafka.common.serialization.Serializer;\n\nclass KsqlDelimitedSerializer implements Serializer> {\n\n private static Encoder BASE64_ENCODER = Base64.getEncoder();\n\n private final PersistenceSchema schema;\n\n private final CSVFormat csvFormat;\n\n KsqlDelimitedSerializer(final PersistenceSchema schema, final CSVFormat csvFormat) {\n this.schema = Objects.requireNonNull(schema, \"schema\");\n this.csvFormat = Objects.requireNonNull(csvFormat, \"csvFormat\");\n }\n\n @Override\n public void configure(final Map map, final boolean b) {\n }\n\n @Override\n public byte[] serialize(final String topic, final List data) {\n if (data == null) {\n return null;\n }\n try {\n final StringWriter stringWriter = new StringWriter();\n final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);\n csvPrinter.printRecord(() -> new FieldIterator(data, schema));\n final String result = stringWriter.toString();\n return result.substring(0, result.length() - 2).getBytes(StandardCharsets.UTF_8);\n } catch (final Exception e) {\n throw new SerializationException(\"Error serializing CSV message\", e);\n }\n }\n\n @Override\n public void close() {\n }\n\n private static class FieldIterator implements Iterator {\n\n private final Iterator dataIt;\n\n private final Iterator columnIt;\n\n FieldIterator(final List data, final PersistenceSchema schema) {\n this.dataIt = data.iterator();\n this.columnIt = schema.columns().iterator();\n }\n\n @Override\n public boolean hasNext() {\n return columnIt.hasNext();\n }\n\n @Override\n public Object next() {\n final Object value = dataIt.next();\n final SimpleColumn column = columnIt.next", "post_mask_code": "\n switch(column.type().baseType()) {\n case DECIMAL:\n return handleDecimal((BigDecimal) value);\n case BYTES:\n return handleBytes((ByteBuffer) value);\n case TIME:\n return handleTime((Time) value);\n case DATE:\n return handleDate((Date) value);\n case TIMESTAMP:\n return handleTimestamp((Timestamp) value);\n default:\n return value;\n }\n }\n\n private static String handleBytes(final ByteBuffer value) {\n // Return base64 encoding\n return value == null ? null : BASE64_ENCODER.encodeToString(value.array());\n }\n\n private static Integer handleTime(final Time value) {\n // Return milliseconds\n return value == null ? null : (int) value.getTime();\n }\n\n private static Integer handleDate(final Date value) {\n // Return epoch days\n return value == null ? null : SerdeUtils.toEpochDays(value);\n }\n\n private static Long handleTimestamp(final Timestamp value) {\n // Return milliseconds\n return value == null ? null : value.getTime();\n }\n\n private static String handleDecimal(final BigDecimal value) {\n // Avoid scientific notation for now:\n return value.toPlainString();\n }\n }\n}\n"} {"task_id": "Java_958", "language": "Java", "task_type": "if_statement", "source_file": "java/github/confluentinc/ksql/ksqldb-serde/src/main/java/io/confluent/ksql/serde/delimited/KsqlDelimitedSerializer.java", "mask_start_position": 1384, "mask_end_position": 1438, "canonical_solution": "if (data == null) {\n return null;\n }", "pre_mask_code": "package io.confluent.ksql.serde.delimited;\n\nimport io.confluent.ksql.schema.ksql.PersistenceSchema;\nimport io.confluent.ksql.schema.ksql.SimpleColumn;\nimport io.confluent.ksql.serde.SerdeUtils;\nimport java.io.StringWriter;\nimport java.math.BigDecimal;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.sql.Date;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Base64;\nimport java.util.Base64.Encoder;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport org.apache.commons.csv.CSVFormat;\nimport org.apache.commons.csv.CSVPrinter;\nimport org.apache.kafka.common.errors.SerializationException;\nimport org.apache.kafka.common.serialization.Serializer;\n\nclass KsqlDelimitedSerializer implements Serializer> {\n\n private static Encoder BASE64_ENCODER = Base64.getEncoder();\n\n private final PersistenceSchema schema;\n\n private final CSVFormat csvFormat;\n\n KsqlDelimitedSerializer(final PersistenceSchema schema, final CSVFormat csvFormat) {\n this.schema = Objects.requireNonNull(schema, \"schema\");\n this.csvFormat = Objects.requireNonNull(csvFormat, \"csvFormat\");\n }\n\n @Override\n public void configure(final Map map, final boolean b) {\n }\n\n @Override\n public byte[] serialize(final String topic, final List data) {\n ", "post_mask_code": "\n try {\n final StringWriter stringWriter = new StringWriter();\n final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);\n csvPrinter.printRecord(() -> new FieldIterator(data, schema));\n final String result = stringWriter.toString();\n return result.substring(0, result.length() - 2).getBytes(StandardCharsets.UTF_8);\n } catch (final Exception e) {\n throw new SerializationException(\"Error serializing CSV message\", e);\n }\n }\n\n @Override\n public void close() {\n }\n\n private static class FieldIterator implements Iterator {\n\n private final Iterator dataIt;\n\n private final Iterator columnIt;\n\n FieldIterator(final List data, final PersistenceSchema schema) {\n this.dataIt = data.iterator();\n this.columnIt = schema.columns().iterator();\n }\n\n @Override\n public boolean hasNext() {\n return columnIt.hasNext();\n }\n\n @Override\n public Object next() {\n final Object value = dataIt.next();\n final SimpleColumn column = columnIt.next();\n switch(column.type().baseType()) {\n case DECIMAL:\n return handleDecimal((BigDecimal) value);\n case BYTES:\n return handleBytes((ByteBuffer) value);\n case TIME:\n return handleTime((Time) value);\n case DATE:\n return handleDate((Date) value);\n case TIMESTAMP:\n return handleTimestamp((Timestamp) value);\n default:\n return value;\n }\n }\n\n private static String handleBytes(final ByteBuffer value) {\n // Return base64 encoding\n return value == null ? null : BASE64_ENCODER.encodeToString(value.array());\n }\n\n private static Integer handleTime(final Time value) {\n // Return milliseconds\n return value == null ? null : (int) value.getTime();\n }\n\n private static Integer handleDate(final Date value) {\n // Return epoch days\n return value == null ? null : SerdeUtils.toEpochDays(value);\n }\n\n private static Long handleTimestamp(final Timestamp value) {\n // Return milliseconds\n return value == null ? null : value.getTime();\n }\n\n private static String handleDecimal(final BigDecimal value) {\n // Avoid scientific notation for now:\n return value.toPlainString();\n }\n }\n}\n"} {"task_id": "Java_959", "language": "Java", "task_type": "empty", "source_file": "java/github/confluentinc/ksql/ksqldb-serde/src/main/java/io/confluent/ksql/serde/delimited/KsqlDelimitedSerializer.java", "mask_start_position": 3578, "mask_end_position": 3578, "canonical_solution": "", "pre_mask_code": "package io.confluent.ksql.serde.delimited;\n\nimport io.confluent.ksql.schema.ksql.PersistenceSchema;\nimport io.confluent.ksql.schema.ksql.SimpleColumn;\nimport io.confluent.ksql.serde.SerdeUtils;\nimport java.io.StringWriter;\nimport java.math.BigDecimal;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.sql.Date;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Base64;\nimport java.util.Base64.Encoder;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport org.apache.commons.csv.CSVFormat;\nimport org.apache.commons.csv.CSVPrinter;\nimport org.apache.kafka.common.errors.SerializationException;\nimport org.apache.kafka.common.serialization.Serializer;\n\nclass KsqlDelimitedSerializer implements Serializer> {\n\n private static Encoder BASE64_ENCODER = Base64.getEncoder();\n\n private final PersistenceSchema schema;\n\n private final CSVFormat csvFormat;\n\n KsqlDelimitedSerializer(final PersistenceSchema schema, final CSVFormat csvFormat) {\n this.schema = Objects.requireNonNull(schema, \"schema\");\n this.csvFormat = Objects.requireNonNull(csvFormat, \"csvFormat\");\n }\n\n @Override\n public void configure(final Map map, final boolean b) {\n }\n\n @Override\n public byte[] serialize(final String topic, final List data) {\n if (data == null) {\n return null;\n }\n try {\n final StringWriter stringWriter = new StringWriter();\n final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);\n csvPrinter.printRecord(() -> new FieldIterator(data, schema));\n final String result = stringWriter.toString();\n return result.substring(0, result.length() - 2).getBytes(StandardCharsets.UTF_8);\n } catch (final Exception e) {\n throw new SerializationException(\"Error serializing CSV message\", e);\n }\n }\n\n @Override\n public void close() {\n }\n\n private static class FieldIterator implements Iterator {\n\n private final Iterator dataIt;\n\n private final Iterator columnIt;\n\n FieldIterator(final List data, final PersistenceSchema schema) {\n this.dataIt = data.iterator();\n this.columnIt = schema.columns().iterator();\n }\n\n @Override\n public boolean hasNext() {\n return columnIt.hasNext();\n }\n\n @Override\n public Object next() {\n final Object value = dataIt.next();\n final SimpleColumn column = columnIt.next();\n switch(column.type().baseType()) {\n case DECIMAL:\n return handleDecimal((BigDecimal) value);\n case BYTES:\n return handleBytes((ByteBuffer) value);\n case TIME:\n return handleTime((Time) value);\n case DATE:\n return handleDate((Date) value);\n case TIMESTAMP:\n return handleTimestamp((Timestamp) value);\n default:\n return value;\n }\n }\n\n private static String handleBytes(final ByteBuffer value) {\n // Return base64 encoding\n return value == null ? null : BASE64_ENCODER.encodeToString(value.array());\n }\n\n private static Integer handleTime(final Time value) {\n // Return milliseconds\n return value == null ? null : (int) value.getTime();\n }\n\n ", "post_mask_code": " private static Integer handleDate(final Date value) {\n // Return epoch days\n return value == null ? null : SerdeUtils.toEpochDays(value);\n }\n\n private static Long handleTimestamp(final Timestamp value) {\n // Return milliseconds\n return value == null ? null : value.getTime();\n }\n\n private static String handleDecimal(final BigDecimal value) {\n // Avoid scientific notation for now:\n return value.toPlainString();\n }\n }\n}\n"} {"task_id": "Java_960", "language": "Java", "task_type": "method_signature", "source_file": "java/github/spearce/jgit/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RelativeDateFormatterTest.java", "mask_start_position": 3034, "mask_end_position": 3074, "canonical_solution": "@Test\n public void testFormatYears() ", "pre_mask_code": "/*\n * and other copyright owners as documented in the project's IP log.\n *\n *\n * All rights reserved.\n *\n */\npackage org.eclipse.jgit.util;\n\nimport static org.eclipse.jgit.util.RelativeDateFormatter.DAY_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.HOUR_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.MINUTE_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.SECOND_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.YEAR_IN_MILLIS;\nimport static org.junit.Assert.assertEquals;\nimport java.util.Date;\nimport org.eclipse.jgit.junit.MockSystemReader;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\npublic class RelativeDateFormatterTest {\n\n @Before\n public void setUp() {\n SystemReader.setInstance(new MockSystemReader());\n }\n\n @After\n public void tearDown() {\n SystemReader.setInstance(null);\n }\n\n private static void assertFormat(long ageFromNow, long timeUnit, String expectedFormat) {\n Date d = new Date(SystemReader.getInstance().getCurrentTime() - ageFromNow * timeUnit);\n String s = RelativeDateFormatter.format(d);\n assertEquals(expectedFormat, s);\n }\n\n @Test\n public void testFuture() {\n assertFormat(-100, YEAR_IN_MILLIS, \"in the future\");\n assertFormat(-1, SECOND_IN_MILLIS, \"in the future\");\n }\n\n @Test\n public void testFormatSeconds() {\n assertFormat(1, SECOND_IN_MILLIS, \"1 seconds ago\");\n assertFormat(89, SECOND_IN_MILLIS, \"89 seconds ago\");\n }\n\n @Test\n public void testFormatMinutes() {\n assertFormat(90, SECOND_IN_MILLIS, \"2 minutes ago\");\n assertFormat(3, MINUTE_IN_MILLIS, \"3 minutes ago\");\n assertFormat(60, MINUTE_IN_MILLIS, \"60 minutes ago\");\n assertFormat(89, MINUTE_IN_MILLIS, \"89 minutes ago\");\n }\n\n @Test\n public void testFormatHours() {\n assertFormat(90, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(149, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(35, HOUR_IN_MILLIS, \"35 hours ago\");\n }\n\n @Test\n public void testFormatDays() {\n assertFormat(36, HOUR_IN_MILLIS, \"2 days ago\");\n assertFormat(13, DAY_IN_MILLIS, \"13 days ago\");\n }\n\n @Test\n public void testFormatWeeks() {\n assertFormat(14, DAY_IN_MILLIS, \"2 weeks ago\");\n assertFormat(69, DAY_IN_MILLIS, \"10 weeks ago\");\n }\n\n @Test\n public void testFormatMonths() {\n assertFormat(70, DAY_IN_MILLIS, \"2 months ago\");\n assertFormat(75, DAY_IN_MILLIS, \"3 months ago\");\n assertFormat(364, DAY_IN_MILLIS, \"12 months ago\");\n }\n\n @Test\n public void testFormatYearsMonths() {\n assertFormat(366, DAY_IN_MILLIS, \"1 year ago\");\n assertFormat(380, DAY_IN_MILLIS, \"1 year, 1 month ago\");\n assertFormat(410, DAY_IN_MILLIS, \"1 year, 2 months ago\");\n assertFormat(2, YEAR_IN_MILLIS, \"2 years ago\");\n assertFormat(1824, DAY_IN_MILLIS, \"4 years, 12 months ago\");\n }\n\n ", "post_mask_code": "{\n assertFormat(5, YEAR_IN_MILLIS, \"5 years ago\");\n assertFormat(60, YEAR_IN_MILLIS, \"60 years ago\");\n }\n}\n"} {"task_id": "Java_961", "language": "Java", "task_type": "method_body", "source_file": "java/github/spearce/jgit/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RelativeDateFormatterTest.java", "mask_start_position": 1916, "mask_end_position": 2100, "canonical_solution": "{\n assertFormat(90, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(149, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(35, HOUR_IN_MILLIS, \"35 hours ago\");\n }", "pre_mask_code": "/*\n * and other copyright owners as documented in the project's IP log.\n *\n *\n * All rights reserved.\n *\n */\npackage org.eclipse.jgit.util;\n\nimport static org.eclipse.jgit.util.RelativeDateFormatter.DAY_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.HOUR_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.MINUTE_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.SECOND_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.YEAR_IN_MILLIS;\nimport static org.junit.Assert.assertEquals;\nimport java.util.Date;\nimport org.eclipse.jgit.junit.MockSystemReader;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\npublic class RelativeDateFormatterTest {\n\n @Before\n public void setUp() {\n SystemReader.setInstance(new MockSystemReader());\n }\n\n @After\n public void tearDown() {\n SystemReader.setInstance(null);\n }\n\n private static void assertFormat(long ageFromNow, long timeUnit, String expectedFormat) {\n Date d = new Date(SystemReader.getInstance().getCurrentTime() - ageFromNow * timeUnit);\n String s = RelativeDateFormatter.format(d);\n assertEquals(expectedFormat, s);\n }\n\n @Test\n public void testFuture() {\n assertFormat(-100, YEAR_IN_MILLIS, \"in the future\");\n assertFormat(-1, SECOND_IN_MILLIS, \"in the future\");\n }\n\n @Test\n public void testFormatSeconds() {\n assertFormat(1, SECOND_IN_MILLIS, \"1 seconds ago\");\n assertFormat(89, SECOND_IN_MILLIS, \"89 seconds ago\");\n }\n\n @Test\n public void testFormatMinutes() {\n assertFormat(90, SECOND_IN_MILLIS, \"2 minutes ago\");\n assertFormat(3, MINUTE_IN_MILLIS, \"3 minutes ago\");\n assertFormat(60, MINUTE_IN_MILLIS, \"60 minutes ago\");\n assertFormat(89, MINUTE_IN_MILLIS, \"89 minutes ago\");\n }\n\n @Test\n public void testFormatHours() ", "post_mask_code": "\n\n @Test\n public void testFormatDays() {\n assertFormat(36, HOUR_IN_MILLIS, \"2 days ago\");\n assertFormat(13, DAY_IN_MILLIS, \"13 days ago\");\n }\n\n @Test\n public void testFormatWeeks() {\n assertFormat(14, DAY_IN_MILLIS, \"2 weeks ago\");\n assertFormat(69, DAY_IN_MILLIS, \"10 weeks ago\");\n }\n\n @Test\n public void testFormatMonths() {\n assertFormat(70, DAY_IN_MILLIS, \"2 months ago\");\n assertFormat(75, DAY_IN_MILLIS, \"3 months ago\");\n assertFormat(364, DAY_IN_MILLIS, \"12 months ago\");\n }\n\n @Test\n public void testFormatYearsMonths() {\n assertFormat(366, DAY_IN_MILLIS, \"1 year ago\");\n assertFormat(380, DAY_IN_MILLIS, \"1 year, 1 month ago\");\n assertFormat(410, DAY_IN_MILLIS, \"1 year, 2 months ago\");\n assertFormat(2, YEAR_IN_MILLIS, \"2 years ago\");\n assertFormat(1824, DAY_IN_MILLIS, \"4 years, 12 months ago\");\n }\n\n @Test\n public void testFormatYears() {\n assertFormat(5, YEAR_IN_MILLIS, \"5 years ago\");\n assertFormat(60, YEAR_IN_MILLIS, \"60 years ago\");\n }\n}\n"} {"task_id": "Java_962", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/spearce/jgit/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RelativeDateFormatterTest.java", "mask_start_position": 2710, "mask_end_position": 2831, "canonical_solution": "\n assertFormat(366, DAY_IN_MILLIS, \"1 year ago\");\n assertFormat(380, DAY_IN_MILLIS, \"1 year, 1 month ago\");", "pre_mask_code": "/*\n * and other copyright owners as documented in the project's IP log.\n *\n *\n * All rights reserved.\n *\n */\npackage org.eclipse.jgit.util;\n\nimport static org.eclipse.jgit.util.RelativeDateFormatter.DAY_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.HOUR_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.MINUTE_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.SECOND_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.YEAR_IN_MILLIS;\nimport static org.junit.Assert.assertEquals;\nimport java.util.Date;\nimport org.eclipse.jgit.junit.MockSystemReader;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\npublic class RelativeDateFormatterTest {\n\n @Before\n public void setUp() {\n SystemReader.setInstance(new MockSystemReader());\n }\n\n @After\n public void tearDown() {\n SystemReader.setInstance(null);\n }\n\n private static void assertFormat(long ageFromNow, long timeUnit, String expectedFormat) {\n Date d = new Date(SystemReader.getInstance().getCurrentTime() - ageFromNow * timeUnit);\n String s = RelativeDateFormatter.format(d);\n assertEquals(expectedFormat, s);\n }\n\n @Test\n public void testFuture() {\n assertFormat(-100, YEAR_IN_MILLIS, \"in the future\");\n assertFormat(-1, SECOND_IN_MILLIS, \"in the future\");\n }\n\n @Test\n public void testFormatSeconds() {\n assertFormat(1, SECOND_IN_MILLIS, \"1 seconds ago\");\n assertFormat(89, SECOND_IN_MILLIS, \"89 seconds ago\");\n }\n\n @Test\n public void testFormatMinutes() {\n assertFormat(90, SECOND_IN_MILLIS, \"2 minutes ago\");\n assertFormat(3, MINUTE_IN_MILLIS, \"3 minutes ago\");\n assertFormat(60, MINUTE_IN_MILLIS, \"60 minutes ago\");\n assertFormat(89, MINUTE_IN_MILLIS, \"89 minutes ago\");\n }\n\n @Test\n public void testFormatHours() {\n assertFormat(90, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(149, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(35, HOUR_IN_MILLIS, \"35 hours ago\");\n }\n\n @Test\n public void testFormatDays() {\n assertFormat(36, HOUR_IN_MILLIS, \"2 days ago\");\n assertFormat(13, DAY_IN_MILLIS, \"13 days ago\");\n }\n\n @Test\n public void testFormatWeeks() {\n assertFormat(14, DAY_IN_MILLIS, \"2 weeks ago\");\n assertFormat(69, DAY_IN_MILLIS, \"10 weeks ago\");\n }\n\n @Test\n public void testFormatMonths() {\n assertFormat(70, DAY_IN_MILLIS, \"2 months ago\");\n assertFormat(75, DAY_IN_MILLIS, \"3 months ago\");\n assertFormat(364, DAY_IN_MILLIS, \"12 months ago\");\n }\n\n @Test\n public void testFormatYearsMonths() {", "post_mask_code": "\n assertFormat(410, DAY_IN_MILLIS, \"1 year, 2 months ago\");\n assertFormat(2, YEAR_IN_MILLIS, \"2 years ago\");\n assertFormat(1824, DAY_IN_MILLIS, \"4 years, 12 months ago\");\n }\n\n @Test\n public void testFormatYears() {\n assertFormat(5, YEAR_IN_MILLIS, \"5 years ago\");\n assertFormat(60, YEAR_IN_MILLIS, \"60 years ago\");\n }\n}\n"} {"task_id": "Java_963", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/spearce/jgit/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RelativeDateFormatterTest.java", "mask_start_position": 2840, "mask_end_position": 2953, "canonical_solution": "assertFormat(410, DAY_IN_MILLIS, \"1 year, 2 months ago\");\n assertFormat(2, YEAR_IN_MILLIS, \"2 years ago\");", "pre_mask_code": "/*\n * and other copyright owners as documented in the project's IP log.\n *\n *\n * All rights reserved.\n *\n */\npackage org.eclipse.jgit.util;\n\nimport static org.eclipse.jgit.util.RelativeDateFormatter.DAY_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.HOUR_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.MINUTE_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.SECOND_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.YEAR_IN_MILLIS;\nimport static org.junit.Assert.assertEquals;\nimport java.util.Date;\nimport org.eclipse.jgit.junit.MockSystemReader;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\npublic class RelativeDateFormatterTest {\n\n @Before\n public void setUp() {\n SystemReader.setInstance(new MockSystemReader());\n }\n\n @After\n public void tearDown() {\n SystemReader.setInstance(null);\n }\n\n private static void assertFormat(long ageFromNow, long timeUnit, String expectedFormat) {\n Date d = new Date(SystemReader.getInstance().getCurrentTime() - ageFromNow * timeUnit);\n String s = RelativeDateFormatter.format(d);\n assertEquals(expectedFormat, s);\n }\n\n @Test\n public void testFuture() {\n assertFormat(-100, YEAR_IN_MILLIS, \"in the future\");\n assertFormat(-1, SECOND_IN_MILLIS, \"in the future\");\n }\n\n @Test\n public void testFormatSeconds() {\n assertFormat(1, SECOND_IN_MILLIS, \"1 seconds ago\");\n assertFormat(89, SECOND_IN_MILLIS, \"89 seconds ago\");\n }\n\n @Test\n public void testFormatMinutes() {\n assertFormat(90, SECOND_IN_MILLIS, \"2 minutes ago\");\n assertFormat(3, MINUTE_IN_MILLIS, \"3 minutes ago\");\n assertFormat(60, MINUTE_IN_MILLIS, \"60 minutes ago\");\n assertFormat(89, MINUTE_IN_MILLIS, \"89 minutes ago\");\n }\n\n @Test\n public void testFormatHours() {\n assertFormat(90, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(149, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(35, HOUR_IN_MILLIS, \"35 hours ago\");\n }\n\n @Test\n public void testFormatDays() {\n assertFormat(36, HOUR_IN_MILLIS, \"2 days ago\");\n assertFormat(13, DAY_IN_MILLIS, \"13 days ago\");\n }\n\n @Test\n public void testFormatWeeks() {\n assertFormat(14, DAY_IN_MILLIS, \"2 weeks ago\");\n assertFormat(69, DAY_IN_MILLIS, \"10 weeks ago\");\n }\n\n @Test\n public void testFormatMonths() {\n assertFormat(70, DAY_IN_MILLIS, \"2 months ago\");\n assertFormat(75, DAY_IN_MILLIS, \"3 months ago\");\n assertFormat(364, DAY_IN_MILLIS, \"12 months ago\");\n }\n\n @Test\n public void testFormatYearsMonths() {\n assertFormat(366, DAY_IN_MILLIS, \"1 year ago\");\n assertFormat(380, DAY_IN_MILLIS, \"1 year, 1 month ago\");\n ", "post_mask_code": "\n assertFormat(1824, DAY_IN_MILLIS, \"4 years, 12 months ago\");\n }\n\n @Test\n public void testFormatYears() {\n assertFormat(5, YEAR_IN_MILLIS, \"5 years ago\");\n assertFormat(60, YEAR_IN_MILLIS, \"60 years ago\");\n }\n}\n"} {"task_id": "Java_964", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/spearce/jgit/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RelativeDateFormatterTest.java", "mask_start_position": 2962, "mask_end_position": 3028, "canonical_solution": "assertFormat(1824, DAY_IN_MILLIS, \"4 years, 12 months ago\");\n }", "pre_mask_code": "/*\n * and other copyright owners as documented in the project's IP log.\n *\n *\n * All rights reserved.\n *\n */\npackage org.eclipse.jgit.util;\n\nimport static org.eclipse.jgit.util.RelativeDateFormatter.DAY_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.HOUR_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.MINUTE_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.SECOND_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.YEAR_IN_MILLIS;\nimport static org.junit.Assert.assertEquals;\nimport java.util.Date;\nimport org.eclipse.jgit.junit.MockSystemReader;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\npublic class RelativeDateFormatterTest {\n\n @Before\n public void setUp() {\n SystemReader.setInstance(new MockSystemReader());\n }\n\n @After\n public void tearDown() {\n SystemReader.setInstance(null);\n }\n\n private static void assertFormat(long ageFromNow, long timeUnit, String expectedFormat) {\n Date d = new Date(SystemReader.getInstance().getCurrentTime() - ageFromNow * timeUnit);\n String s = RelativeDateFormatter.format(d);\n assertEquals(expectedFormat, s);\n }\n\n @Test\n public void testFuture() {\n assertFormat(-100, YEAR_IN_MILLIS, \"in the future\");\n assertFormat(-1, SECOND_IN_MILLIS, \"in the future\");\n }\n\n @Test\n public void testFormatSeconds() {\n assertFormat(1, SECOND_IN_MILLIS, \"1 seconds ago\");\n assertFormat(89, SECOND_IN_MILLIS, \"89 seconds ago\");\n }\n\n @Test\n public void testFormatMinutes() {\n assertFormat(90, SECOND_IN_MILLIS, \"2 minutes ago\");\n assertFormat(3, MINUTE_IN_MILLIS, \"3 minutes ago\");\n assertFormat(60, MINUTE_IN_MILLIS, \"60 minutes ago\");\n assertFormat(89, MINUTE_IN_MILLIS, \"89 minutes ago\");\n }\n\n @Test\n public void testFormatHours() {\n assertFormat(90, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(149, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(35, HOUR_IN_MILLIS, \"35 hours ago\");\n }\n\n @Test\n public void testFormatDays() {\n assertFormat(36, HOUR_IN_MILLIS, \"2 days ago\");\n assertFormat(13, DAY_IN_MILLIS, \"13 days ago\");\n }\n\n @Test\n public void testFormatWeeks() {\n assertFormat(14, DAY_IN_MILLIS, \"2 weeks ago\");\n assertFormat(69, DAY_IN_MILLIS, \"10 weeks ago\");\n }\n\n @Test\n public void testFormatMonths() {\n assertFormat(70, DAY_IN_MILLIS, \"2 months ago\");\n assertFormat(75, DAY_IN_MILLIS, \"3 months ago\");\n assertFormat(364, DAY_IN_MILLIS, \"12 months ago\");\n }\n\n @Test\n public void testFormatYearsMonths() {\n assertFormat(366, DAY_IN_MILLIS, \"1 year ago\");\n assertFormat(380, DAY_IN_MILLIS, \"1 year, 1 month ago\");\n assertFormat(410, DAY_IN_MILLIS, \"1 year, 2 months ago\");\n assertFormat(2, YEAR_IN_MILLIS, \"2 years ago\");\n ", "post_mask_code": "\n\n @Test\n public void testFormatYears() {\n assertFormat(5, YEAR_IN_MILLIS, \"5 years ago\");\n assertFormat(60, YEAR_IN_MILLIS, \"60 years ago\");\n }\n}\n"} {"task_id": "Java_965", "language": "Java", "task_type": "single_line", "source_file": "java/github/spearce/jgit/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RelativeDateFormatterTest.java", "mask_start_position": 1758, "mask_end_position": 1802, "canonical_solution": "mat(60, MINUTE_IN_MILLIS, \"60 minutes ago\");", "pre_mask_code": "/*\n * and other copyright owners as documented in the project's IP log.\n *\n *\n * All rights reserved.\n *\n */\npackage org.eclipse.jgit.util;\n\nimport static org.eclipse.jgit.util.RelativeDateFormatter.DAY_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.HOUR_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.MINUTE_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.SECOND_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.YEAR_IN_MILLIS;\nimport static org.junit.Assert.assertEquals;\nimport java.util.Date;\nimport org.eclipse.jgit.junit.MockSystemReader;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\npublic class RelativeDateFormatterTest {\n\n @Before\n public void setUp() {\n SystemReader.setInstance(new MockSystemReader());\n }\n\n @After\n public void tearDown() {\n SystemReader.setInstance(null);\n }\n\n private static void assertFormat(long ageFromNow, long timeUnit, String expectedFormat) {\n Date d = new Date(SystemReader.getInstance().getCurrentTime() - ageFromNow * timeUnit);\n String s = RelativeDateFormatter.format(d);\n assertEquals(expectedFormat, s);\n }\n\n @Test\n public void testFuture() {\n assertFormat(-100, YEAR_IN_MILLIS, \"in the future\");\n assertFormat(-1, SECOND_IN_MILLIS, \"in the future\");\n }\n\n @Test\n public void testFormatSeconds() {\n assertFormat(1, SECOND_IN_MILLIS, \"1 seconds ago\");\n assertFormat(89, SECOND_IN_MILLIS, \"89 seconds ago\");\n }\n\n @Test\n public void testFormatMinutes() {\n assertFormat(90, SECOND_IN_MILLIS, \"2 minutes ago\");\n assertFormat(3, MINUTE_IN_MILLIS, \"3 minutes ago\");\n assertFor", "post_mask_code": "\n assertFormat(89, MINUTE_IN_MILLIS, \"89 minutes ago\");\n }\n\n @Test\n public void testFormatHours() {\n assertFormat(90, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(149, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(35, HOUR_IN_MILLIS, \"35 hours ago\");\n }\n\n @Test\n public void testFormatDays() {\n assertFormat(36, HOUR_IN_MILLIS, \"2 days ago\");\n assertFormat(13, DAY_IN_MILLIS, \"13 days ago\");\n }\n\n @Test\n public void testFormatWeeks() {\n assertFormat(14, DAY_IN_MILLIS, \"2 weeks ago\");\n assertFormat(69, DAY_IN_MILLIS, \"10 weeks ago\");\n }\n\n @Test\n public void testFormatMonths() {\n assertFormat(70, DAY_IN_MILLIS, \"2 months ago\");\n assertFormat(75, DAY_IN_MILLIS, \"3 months ago\");\n assertFormat(364, DAY_IN_MILLIS, \"12 months ago\");\n }\n\n @Test\n public void testFormatYearsMonths() {\n assertFormat(366, DAY_IN_MILLIS, \"1 year ago\");\n assertFormat(380, DAY_IN_MILLIS, \"1 year, 1 month ago\");\n assertFormat(410, DAY_IN_MILLIS, \"1 year, 2 months ago\");\n assertFormat(2, YEAR_IN_MILLIS, \"2 years ago\");\n assertFormat(1824, DAY_IN_MILLIS, \"4 years, 12 months ago\");\n }\n\n @Test\n public void testFormatYears() {\n assertFormat(5, YEAR_IN_MILLIS, \"5 years ago\");\n assertFormat(60, YEAR_IN_MILLIS, \"60 years ago\");\n }\n}\n"} {"task_id": "Java_966", "language": "Java", "task_type": "empty", "source_file": "java/github/spearce/jgit/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/RelativeDateFormatterTest.java", "mask_start_position": 1259, "mask_end_position": 1259, "canonical_solution": "", "pre_mask_code": "/*\n * and other copyright owners as documented in the project's IP log.\n *\n *\n * All rights reserved.\n *\n */\npackage org.eclipse.jgit.util;\n\nimport static org.eclipse.jgit.util.RelativeDateFormatter.DAY_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.HOUR_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.MINUTE_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.SECOND_IN_MILLIS;\nimport static org.eclipse.jgit.util.RelativeDateFormatter.YEAR_IN_MILLIS;\nimport static org.junit.Assert.assertEquals;\nimport java.util.Date;\nimport org.eclipse.jgit.junit.MockSystemReader;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\npublic class RelativeDateFormatterTest {\n\n @Before\n public void setUp() {\n SystemReader.setInstance(new MockSystemReader());\n }\n\n @After\n public void tearDown() {\n SystemReader.setInstance(null);\n }\n\n private static void assertFormat(long ageFromNow, long timeUnit, String expectedFormat) {\n Date d = new Date(SystemReader.getInstance().getCurrentTime() - ageFromNow * timeUnit);\n String s = RelativeDateFormatter.format(d);\n assertEquals(expectedFormat, s);\n }\n\n @Test\n public void testFutu", "post_mask_code": "re() {\n assertFormat(-100, YEAR_IN_MILLIS, \"in the future\");\n assertFormat(-1, SECOND_IN_MILLIS, \"in the future\");\n }\n\n @Test\n public void testFormatSeconds() {\n assertFormat(1, SECOND_IN_MILLIS, \"1 seconds ago\");\n assertFormat(89, SECOND_IN_MILLIS, \"89 seconds ago\");\n }\n\n @Test\n public void testFormatMinutes() {\n assertFormat(90, SECOND_IN_MILLIS, \"2 minutes ago\");\n assertFormat(3, MINUTE_IN_MILLIS, \"3 minutes ago\");\n assertFormat(60, MINUTE_IN_MILLIS, \"60 minutes ago\");\n assertFormat(89, MINUTE_IN_MILLIS, \"89 minutes ago\");\n }\n\n @Test\n public void testFormatHours() {\n assertFormat(90, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(149, MINUTE_IN_MILLIS, \"2 hours ago\");\n assertFormat(35, HOUR_IN_MILLIS, \"35 hours ago\");\n }\n\n @Test\n public void testFormatDays() {\n assertFormat(36, HOUR_IN_MILLIS, \"2 days ago\");\n assertFormat(13, DAY_IN_MILLIS, \"13 days ago\");\n }\n\n @Test\n public void testFormatWeeks() {\n assertFormat(14, DAY_IN_MILLIS, \"2 weeks ago\");\n assertFormat(69, DAY_IN_MILLIS, \"10 weeks ago\");\n }\n\n @Test\n public void testFormatMonths() {\n assertFormat(70, DAY_IN_MILLIS, \"2 months ago\");\n assertFormat(75, DAY_IN_MILLIS, \"3 months ago\");\n assertFormat(364, DAY_IN_MILLIS, \"12 months ago\");\n }\n\n @Test\n public void testFormatYearsMonths() {\n assertFormat(366, DAY_IN_MILLIS, \"1 year ago\");\n assertFormat(380, DAY_IN_MILLIS, \"1 year, 1 month ago\");\n assertFormat(410, DAY_IN_MILLIS, \"1 year, 2 months ago\");\n assertFormat(2, YEAR_IN_MILLIS, \"2 years ago\");\n assertFormat(1824, DAY_IN_MILLIS, \"4 years, 12 months ago\");\n }\n\n @Test\n public void testFormatYears() {\n assertFormat(5, YEAR_IN_MILLIS, \"5 years ago\");\n assertFormat(60, YEAR_IN_MILLIS, \"60 years ago\");\n }\n}\n"} {"task_id": "Java_967", "language": "Java", "task_type": "empty", "source_file": "java/github/eclipse-ee4j/eclipselink/jpa/eclipselink.jpa.test/src/it/java/org/eclipse/persistence/testing/models/jpa/ddlgeneration/Money.java", "mask_start_position": 162, "mask_end_position": 162, "canonical_solution": "", "pre_mask_code": "// 07/17/2009 - tware - added tests for DDL generation of maps\npackage org.eclipse.persistence.testing.models.jpa.ddlgeneration;\n\nimport java.math.BigDecimal;\n\npu", "post_mask_code": "blic class Money {\n\n private BigDecimal amount;\n\n private Currency currency;\n\n public Money() {\n }\n\n public Money(BigDecimal amount, Currency currency) {\n super();\n this.amount = amount;\n this.currency = currency;\n }\n}\n"} {"task_id": "Java_968", "language": "Java", "task_type": "method_signature", "source_file": "java/github/llmhyy/evosuite-plus-plus/client/src/main/java/org/evosuite/graphs/FloydWarshall.java", "mask_start_position": 2752, "mask_end_position": 2780, "canonical_solution": "public double getDiameter() ", "pre_mask_code": "/**\n * This file is part of EvoSuite.\n */\n/*\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation,\n * Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\nimport java.util.*;\nimport org.jgrapht.*;\n\n/**\n * The \n * Floyd-Warshall algorithm finds all shortest paths (all n^2 of them) in\n * O(n^3) time. This also works out the graph diameter during the process.\n *\n * @author Tom Larkworthy\n */\npublic class FloydWarshall {\n\n int nextIndex = 0;\n\n HashMap indices;\n\n double[][] d;\n\n double diameter;\n\n /**\n * Constructs the shortest path array for the given graph.\n *\n * @param g input graph\n * @param a V object.\n * @param a E object.\n */\n public FloydWarshall(Graph g) {\n int sz = g.vertexSet().size();\n d = new double[sz][sz];\n indices = new HashMap();\n // Initialise distance to infinity, or the neighbours weight, or 0 if\n // same\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n if (v1 == v2) {\n d[index(v1)][index(v2)] = 0;\n } else {\n E e = g.getEdge(v1, v2);\n if (e == null) {\n d[index(v1)][index(v2)] = Double.POSITIVE_INFINITY;\n } else {\n d[index(v1)][index(v2)] = g.getEdgeWeight(e);\n }\n }\n }\n }\n // now iterate k times\n for (int k = 0; k < sz; k++) {\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n d[index(v1)][index(v2)] = Math.min(d[index(v1)][index(v2)], d[index(v1)][k] + d[k][index(v2)]);\n if (Double.POSITIVE_INFINITY != d[index(v1)][index(v2)])\n diameter = Math.max(diameter, d[index(v1)][index(v2)]);\n }\n }\n }\n }\n\n /**\n * Retrieves the shortest distance between two vertices.\n *\n * @param v1 first vertex\n * @param v2 second vertex\n * @return distance, or positive infinity if no path\n */\n public double shortestDistance(V v1, V v2) {\n return d[index(v1)][index(v2)];\n }\n\n ", "post_mask_code": "{\n return diameter;\n }\n\n private int index(V vertex) {\n Integer index = indices.get(vertex);\n if (index == null) {\n indices.put(vertex, nextIndex);\n index = nextIndex++;\n }\n return index;\n }\n}\n// End FloydWarshallShortestPaths.java\n"} {"task_id": "Java_969", "language": "Java", "task_type": "method_body", "source_file": "java/github/llmhyy/evosuite-plus-plus/client/src/main/java/org/evosuite/graphs/FloydWarshall.java", "mask_start_position": 2699, "mask_end_position": 2746, "canonical_solution": "{\n return d[index(v1)][index(v2)];\n }", "pre_mask_code": "/**\n * This file is part of EvoSuite.\n */\n/*\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation,\n * Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\nimport java.util.*;\nimport org.jgrapht.*;\n\n/**\n * The \n * Floyd-Warshall algorithm finds all shortest paths (all n^2 of them) in\n * O(n^3) time. This also works out the graph diameter during the process.\n *\n * @author Tom Larkworthy\n */\npublic class FloydWarshall {\n\n int nextIndex = 0;\n\n HashMap indices;\n\n double[][] d;\n\n double diameter;\n\n /**\n * Constructs the shortest path array for the given graph.\n *\n * @param g input graph\n * @param a V object.\n * @param a E object.\n */\n public FloydWarshall(Graph g) {\n int sz = g.vertexSet().size();\n d = new double[sz][sz];\n indices = new HashMap();\n // Initialise distance to infinity, or the neighbours weight, or 0 if\n // same\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n if (v1 == v2) {\n d[index(v1)][index(v2)] = 0;\n } else {\n E e = g.getEdge(v1, v2);\n if (e == null) {\n d[index(v1)][index(v2)] = Double.POSITIVE_INFINITY;\n } else {\n d[index(v1)][index(v2)] = g.getEdgeWeight(e);\n }\n }\n }\n }\n // now iterate k times\n for (int k = 0; k < sz; k++) {\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n d[index(v1)][index(v2)] = Math.min(d[index(v1)][index(v2)], d[index(v1)][k] + d[k][index(v2)]);\n if (Double.POSITIVE_INFINITY != d[index(v1)][index(v2)])\n diameter = Math.max(diameter, d[index(v1)][index(v2)]);\n }\n }\n }\n }\n\n /**\n * Retrieves the shortest distance between two vertices.\n *\n * @param v1 first vertex\n * @param v2 second vertex\n * @return distance, or positive infinity if no path\n */\n public double shortestDistance(V v1, V v2) ", "post_mask_code": "\n\n public double getDiameter() {\n return diameter;\n }\n\n private int index(V vertex) {\n Integer index = indices.get(vertex);\n if (index == null) {\n indices.put(vertex, nextIndex);\n index = nextIndex++;\n }\n return index;\n }\n}\n// End FloydWarshallShortestPaths.java\n"} {"task_id": "Java_970", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/llmhyy/evosuite-plus-plus/client/src/main/java/org/evosuite/graphs/FloydWarshall.java", "mask_start_position": 2847, "mask_end_position": 2892, "canonical_solution": "\n Integer index = indices.get(vertex);", "pre_mask_code": "/**\n * This file is part of EvoSuite.\n */\n/*\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation,\n * Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\nimport java.util.*;\nimport org.jgrapht.*;\n\n/**\n * The \n * Floyd-Warshall algorithm finds all shortest paths (all n^2 of them) in\n * O(n^3) time. This also works out the graph diameter during the process.\n *\n * @author Tom Larkworthy\n */\npublic class FloydWarshall {\n\n int nextIndex = 0;\n\n HashMap indices;\n\n double[][] d;\n\n double diameter;\n\n /**\n * Constructs the shortest path array for the given graph.\n *\n * @param g input graph\n * @param a V object.\n * @param a E object.\n */\n public FloydWarshall(Graph g) {\n int sz = g.vertexSet().size();\n d = new double[sz][sz];\n indices = new HashMap();\n // Initialise distance to infinity, or the neighbours weight, or 0 if\n // same\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n if (v1 == v2) {\n d[index(v1)][index(v2)] = 0;\n } else {\n E e = g.getEdge(v1, v2);\n if (e == null) {\n d[index(v1)][index(v2)] = Double.POSITIVE_INFINITY;\n } else {\n d[index(v1)][index(v2)] = g.getEdgeWeight(e);\n }\n }\n }\n }\n // now iterate k times\n for (int k = 0; k < sz; k++) {\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n d[index(v1)][index(v2)] = Math.min(d[index(v1)][index(v2)], d[index(v1)][k] + d[k][index(v2)]);\n if (Double.POSITIVE_INFINITY != d[index(v1)][index(v2)])\n diameter = Math.max(diameter, d[index(v1)][index(v2)]);\n }\n }\n }\n }\n\n /**\n * Retrieves the shortest distance between two vertices.\n *\n * @param v1 first vertex\n * @param v2 second vertex\n * @return distance, or positive infinity if no path\n */\n public double shortestDistance(V v1, V v2) {\n return d[index(v1)][index(v2)];\n }\n\n public double getDiameter() {\n return diameter;\n }\n\n private int index(V vertex) {", "post_mask_code": "\n if (index == null) {\n indices.put(vertex, nextIndex);\n index = nextIndex++;\n }\n return index;\n }\n}\n// End FloydWarshallShortestPaths.java\n"} {"task_id": "Java_971", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/llmhyy/evosuite-plus-plus/client/src/main/java/org/evosuite/graphs/FloydWarshall.java", "mask_start_position": 2901, "mask_end_position": 3008, "canonical_solution": "if (index == null) {\n indices.put(vertex, nextIndex);\n index = nextIndex++;\n }", "pre_mask_code": "/**\n * This file is part of EvoSuite.\n */\n/*\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation,\n * Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\nimport java.util.*;\nimport org.jgrapht.*;\n\n/**\n * The \n * Floyd-Warshall algorithm finds all shortest paths (all n^2 of them) in\n * O(n^3) time. This also works out the graph diameter during the process.\n *\n * @author Tom Larkworthy\n */\npublic class FloydWarshall {\n\n int nextIndex = 0;\n\n HashMap indices;\n\n double[][] d;\n\n double diameter;\n\n /**\n * Constructs the shortest path array for the given graph.\n *\n * @param g input graph\n * @param a V object.\n * @param a E object.\n */\n public FloydWarshall(Graph g) {\n int sz = g.vertexSet().size();\n d = new double[sz][sz];\n indices = new HashMap();\n // Initialise distance to infinity, or the neighbours weight, or 0 if\n // same\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n if (v1 == v2) {\n d[index(v1)][index(v2)] = 0;\n } else {\n E e = g.getEdge(v1, v2);\n if (e == null) {\n d[index(v1)][index(v2)] = Double.POSITIVE_INFINITY;\n } else {\n d[index(v1)][index(v2)] = g.getEdgeWeight(e);\n }\n }\n }\n }\n // now iterate k times\n for (int k = 0; k < sz; k++) {\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n d[index(v1)][index(v2)] = Math.min(d[index(v1)][index(v2)], d[index(v1)][k] + d[k][index(v2)]);\n if (Double.POSITIVE_INFINITY != d[index(v1)][index(v2)])\n diameter = Math.max(diameter, d[index(v1)][index(v2)]);\n }\n }\n }\n }\n\n /**\n * Retrieves the shortest distance between two vertices.\n *\n * @param v1 first vertex\n * @param v2 second vertex\n * @return distance, or positive infinity if no path\n */\n public double shortestDistance(V v1, V v2) {\n return d[index(v1)][index(v2)];\n }\n\n public double getDiameter() {\n return diameter;\n }\n\n private int index(V vertex) {\n Integer index = indices.get(vertex);\n ", "post_mask_code": "\n return index;\n }\n}\n// End FloydWarshallShortestPaths.java\n"} {"task_id": "Java_972", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/llmhyy/evosuite-plus-plus/client/src/main/java/org/evosuite/graphs/FloydWarshall.java", "mask_start_position": 3017, "mask_end_position": 3036, "canonical_solution": "return index;\n }", "pre_mask_code": "/**\n * This file is part of EvoSuite.\n */\n/*\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation,\n * Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\nimport java.util.*;\nimport org.jgrapht.*;\n\n/**\n * The \n * Floyd-Warshall algorithm finds all shortest paths (all n^2 of them) in\n * O(n^3) time. This also works out the graph diameter during the process.\n *\n * @author Tom Larkworthy\n */\npublic class FloydWarshall {\n\n int nextIndex = 0;\n\n HashMap indices;\n\n double[][] d;\n\n double diameter;\n\n /**\n * Constructs the shortest path array for the given graph.\n *\n * @param g input graph\n * @param a V object.\n * @param a E object.\n */\n public FloydWarshall(Graph g) {\n int sz = g.vertexSet().size();\n d = new double[sz][sz];\n indices = new HashMap();\n // Initialise distance to infinity, or the neighbours weight, or 0 if\n // same\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n if (v1 == v2) {\n d[index(v1)][index(v2)] = 0;\n } else {\n E e = g.getEdge(v1, v2);\n if (e == null) {\n d[index(v1)][index(v2)] = Double.POSITIVE_INFINITY;\n } else {\n d[index(v1)][index(v2)] = g.getEdgeWeight(e);\n }\n }\n }\n }\n // now iterate k times\n for (int k = 0; k < sz; k++) {\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n d[index(v1)][index(v2)] = Math.min(d[index(v1)][index(v2)], d[index(v1)][k] + d[k][index(v2)]);\n if (Double.POSITIVE_INFINITY != d[index(v1)][index(v2)])\n diameter = Math.max(diameter, d[index(v1)][index(v2)]);\n }\n }\n }\n }\n\n /**\n * Retrieves the shortest distance between two vertices.\n *\n * @param v1 first vertex\n * @param v2 second vertex\n * @return distance, or positive infinity if no path\n */\n public double shortestDistance(V v1, V v2) {\n return d[index(v1)][index(v2)];\n }\n\n public double getDiameter() {\n return diameter;\n }\n\n private int index(V vertex) {\n Integer index = indices.get(vertex);\n if (index == null) {\n indices.put(vertex, nextIndex);\n index = nextIndex++;\n }\n ", "post_mask_code": "\n}\n// End FloydWarshallShortestPaths.java\n"} {"task_id": "Java_973", "language": "Java", "task_type": "single_line", "source_file": "java/github/llmhyy/evosuite-plus-plus/client/src/main/java/org/evosuite/graphs/FloydWarshall.java", "mask_start_position": 2863, "mask_end_position": 2892, "canonical_solution": " index = indices.get(vertex);", "pre_mask_code": "/**\n * This file is part of EvoSuite.\n */\n/*\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation,\n * Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\nimport java.util.*;\nimport org.jgrapht.*;\n\n/**\n * The \n * Floyd-Warshall algorithm finds all shortest paths (all n^2 of them) in\n * O(n^3) time. This also works out the graph diameter during the process.\n *\n * @author Tom Larkworthy\n */\npublic class FloydWarshall {\n\n int nextIndex = 0;\n\n HashMap indices;\n\n double[][] d;\n\n double diameter;\n\n /**\n * Constructs the shortest path array for the given graph.\n *\n * @param g input graph\n * @param a V object.\n * @param a E object.\n */\n public FloydWarshall(Graph g) {\n int sz = g.vertexSet().size();\n d = new double[sz][sz];\n indices = new HashMap();\n // Initialise distance to infinity, or the neighbours weight, or 0 if\n // same\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n if (v1 == v2) {\n d[index(v1)][index(v2)] = 0;\n } else {\n E e = g.getEdge(v1, v2);\n if (e == null) {\n d[index(v1)][index(v2)] = Double.POSITIVE_INFINITY;\n } else {\n d[index(v1)][index(v2)] = g.getEdgeWeight(e);\n }\n }\n }\n }\n // now iterate k times\n for (int k = 0; k < sz; k++) {\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n d[index(v1)][index(v2)] = Math.min(d[index(v1)][index(v2)], d[index(v1)][k] + d[k][index(v2)]);\n if (Double.POSITIVE_INFINITY != d[index(v1)][index(v2)])\n diameter = Math.max(diameter, d[index(v1)][index(v2)]);\n }\n }\n }\n }\n\n /**\n * Retrieves the shortest distance between two vertices.\n *\n * @param v1 first vertex\n * @param v2 second vertex\n * @return distance, or positive infinity if no path\n */\n public double shortestDistance(V v1, V v2) {\n return d[index(v1)][index(v2)];\n }\n\n public double getDiameter() {\n return diameter;\n }\n\n private int index(V vertex) {\n Integer", "post_mask_code": "\n if (index == null) {\n indices.put(vertex, nextIndex);\n index = nextIndex++;\n }\n return index;\n }\n}\n// End FloydWarshallShortestPaths.java\n"} {"task_id": "Java_974", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/llmhyy/evosuite-plus-plus/client/src/main/java/org/evosuite/graphs/FloydWarshall.java", "mask_start_position": 2656, "mask_end_position": 2746, "canonical_solution": "public double shortestDistance(V v1, V v2) {\n return d[index(v1)][index(v2)];\n }", "pre_mask_code": "/**\n * This file is part of EvoSuite.\n */\n/*\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation,\n * Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\nimport java.util.*;\nimport org.jgrapht.*;\n\n/**\n * The \n * Floyd-Warshall algorithm finds all shortest paths (all n^2 of them) in\n * O(n^3) time. This also works out the graph diameter during the process.\n *\n * @author Tom Larkworthy\n */\npublic class FloydWarshall {\n\n int nextIndex = 0;\n\n HashMap indices;\n\n double[][] d;\n\n double diameter;\n\n /**\n * Constructs the shortest path array for the given graph.\n *\n * @param g input graph\n * @param a V object.\n * @param a E object.\n */\n public FloydWarshall(Graph g) {\n int sz = g.vertexSet().size();\n d = new double[sz][sz];\n indices = new HashMap();\n // Initialise distance to infinity, or the neighbours weight, or 0 if\n // same\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n if (v1 == v2) {\n d[index(v1)][index(v2)] = 0;\n } else {\n E e = g.getEdge(v1, v2);\n if (e == null) {\n d[index(v1)][index(v2)] = Double.POSITIVE_INFINITY;\n } else {\n d[index(v1)][index(v2)] = g.getEdgeWeight(e);\n }\n }\n }\n }\n // now iterate k times\n for (int k = 0; k < sz; k++) {\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n d[index(v1)][index(v2)] = Math.min(d[index(v1)][index(v2)], d[index(v1)][k] + d[k][index(v2)]);\n if (Double.POSITIVE_INFINITY != d[index(v1)][index(v2)])\n diameter = Math.max(diameter, d[index(v1)][index(v2)]);\n }\n }\n }\n }\n\n /**\n * Retrieves the shortest distance between two vertices.\n *\n * @param v1 first vertex\n * @param v2 second vertex\n * @return distance, or positive infinity if no path\n */\n ", "post_mask_code": "\n\n public double getDiameter() {\n return diameter;\n }\n\n private int index(V vertex) {\n Integer index = indices.get(vertex);\n if (index == null) {\n indices.put(vertex, nextIndex);\n index = nextIndex++;\n }\n return index;\n }\n}\n// End FloydWarshallShortestPaths.java\n"} {"task_id": "Java_975", "language": "Java", "task_type": "if_statement", "source_file": "java/github/llmhyy/evosuite-plus-plus/client/src/main/java/org/evosuite/graphs/FloydWarshall.java", "mask_start_position": 2264, "mask_end_position": 2400, "canonical_solution": "if (Double.POSITIVE_INFINITY != d[index(v1)][index(v2)])\n diameter = Math.max(diameter, d[index(v1)][index(v2)]);", "pre_mask_code": "/**\n * This file is part of EvoSuite.\n */\n/*\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation,\n * Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\nimport java.util.*;\nimport org.jgrapht.*;\n\n/**\n * The \n * Floyd-Warshall algorithm finds all shortest paths (all n^2 of them) in\n * O(n^3) time. This also works out the graph diameter during the process.\n *\n * @author Tom Larkworthy\n */\npublic class FloydWarshall {\n\n int nextIndex = 0;\n\n HashMap indices;\n\n double[][] d;\n\n double diameter;\n\n /**\n * Constructs the shortest path array for the given graph.\n *\n * @param g input graph\n * @param a V object.\n * @param a E object.\n */\n public FloydWarshall(Graph g) {\n int sz = g.vertexSet().size();\n d = new double[sz][sz];\n indices = new HashMap();\n // Initialise distance to infinity, or the neighbours weight, or 0 if\n // same\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n if (v1 == v2) {\n d[index(v1)][index(v2)] = 0;\n } else {\n E e = g.getEdge(v1, v2);\n if (e == null) {\n d[index(v1)][index(v2)] = Double.POSITIVE_INFINITY;\n } else {\n d[index(v1)][index(v2)] = g.getEdgeWeight(e);\n }\n }\n }\n }\n // now iterate k times\n for (int k = 0; k < sz; k++) {\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n d[index(v1)][index(v2)] = Math.min(d[index(v1)][index(v2)], d[index(v1)][k] + d[k][index(v2)]);\n ", "post_mask_code": "\n }\n }\n }\n }\n\n /**\n * Retrieves the shortest distance between two vertices.\n *\n * @param v1 first vertex\n * @param v2 second vertex\n * @return distance, or positive infinity if no path\n */\n public double shortestDistance(V v1, V v2) {\n return d[index(v1)][index(v2)];\n }\n\n public double getDiameter() {\n return diameter;\n }\n\n private int index(V vertex) {\n Integer index = indices.get(vertex);\n if (index == null) {\n indices.put(vertex, nextIndex);\n index = nextIndex++;\n }\n return index;\n }\n}\n// End FloydWarshallShortestPaths.java\n"} {"task_id": "Java_976", "language": "Java", "task_type": "for_statement", "source_file": "java/github/llmhyy/evosuite-plus-plus/client/src/main/java/org/evosuite/graphs/FloydWarshall.java", "mask_start_position": 2011, "mask_end_position": 2442, "canonical_solution": "for (int k = 0; k < sz; k++) {\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n d[index(v1)][index(v2)] = Math.min(d[index(v1)][index(v2)], d[index(v1)][k] + d[k][index(v2)]);\n if (Double.POSITIVE_INFINITY != d[index(v1)][index(v2)])\n diameter = Math.max(diameter, d[index(v1)][index(v2)]);\n }\n }\n }", "pre_mask_code": "/**\n * This file is part of EvoSuite.\n */\n/*\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation,\n * Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\nimport java.util.*;\nimport org.jgrapht.*;\n\n/**\n * The \n * Floyd-Warshall algorithm finds all shortest paths (all n^2 of them) in\n * O(n^3) time. This also works out the graph diameter during the process.\n *\n * @author Tom Larkworthy\n */\npublic class FloydWarshall {\n\n int nextIndex = 0;\n\n HashMap indices;\n\n double[][] d;\n\n double diameter;\n\n /**\n * Constructs the shortest path array for the given graph.\n *\n * @param g input graph\n * @param a V object.\n * @param a E object.\n */\n public FloydWarshall(Graph g) {\n int sz = g.vertexSet().size();\n d = new double[sz][sz];\n indices = new HashMap();\n // Initialise distance to infinity, or the neighbours weight, or 0 if\n // same\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n if (v1 == v2) {\n d[index(v1)][index(v2)] = 0;\n } else {\n E e = g.getEdge(v1, v2);\n if (e == null) {\n d[index(v1)][index(v2)] = Double.POSITIVE_INFINITY;\n } else {\n d[index(v1)][index(v2)] = g.getEdgeWeight(e);\n }\n }\n }\n }\n // now iterate k times\n ", "post_mask_code": "\n }\n\n /**\n * Retrieves the shortest distance between two vertices.\n *\n * @param v1 first vertex\n * @param v2 second vertex\n * @return distance, or positive infinity if no path\n */\n public double shortestDistance(V v1, V v2) {\n return d[index(v1)][index(v2)];\n }\n\n public double getDiameter() {\n return diameter;\n }\n\n private int index(V vertex) {\n Integer index = indices.get(vertex);\n if (index == null) {\n indices.put(vertex, nextIndex);\n index = nextIndex++;\n }\n return index;\n }\n}\n// End FloydWarshallShortestPaths.java\n"} {"task_id": "Java_977", "language": "Java", "task_type": "empty", "source_file": "java/github/llmhyy/evosuite-plus-plus/client/src/main/java/org/evosuite/graphs/FloydWarshall.java", "mask_start_position": 2383, "mask_end_position": 2383, "canonical_solution": "", "pre_mask_code": "/**\n * This file is part of EvoSuite.\n */\n/*\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation,\n * Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\nimport java.util.*;\nimport org.jgrapht.*;\n\n/**\n * The \n * Floyd-Warshall algorithm finds all shortest paths (all n^2 of them) in\n * O(n^3) time. This also works out the graph diameter during the process.\n *\n * @author Tom Larkworthy\n */\npublic class FloydWarshall {\n\n int nextIndex = 0;\n\n HashMap indices;\n\n double[][] d;\n\n double diameter;\n\n /**\n * Constructs the shortest path array for the given graph.\n *\n * @param g input graph\n * @param a V object.\n * @param a E object.\n */\n public FloydWarshall(Graph g) {\n int sz = g.vertexSet().size();\n d = new double[sz][sz];\n indices = new HashMap();\n // Initialise distance to infinity, or the neighbours weight, or 0 if\n // same\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n if (v1 == v2) {\n d[index(v1)][index(v2)] = 0;\n } else {\n E e = g.getEdge(v1, v2);\n if (e == null) {\n d[index(v1)][index(v2)] = Double.POSITIVE_INFINITY;\n } else {\n d[index(v1)][index(v2)] = g.getEdgeWeight(e);\n }\n }\n }\n }\n // now iterate k times\n for (int k = 0; k < sz; k++) {\n for (V v1 : g.vertexSet()) {\n for (V v2 : g.vertexSet()) {\n d[index(v1)][index(v2)] = Math.min(d[index(v1)][index(v2)], d[index(v1)][k] + d[k][index(v2)]);\n if (Double.POSITIVE_INFINITY != d[index(v1)][index(v2)])\n diameter = Math.max(diameter, d[index(", "post_mask_code": "v1)][index(v2)]);\n }\n }\n }\n }\n\n /**\n * Retrieves the shortest distance between two vertices.\n *\n * @param v1 first vertex\n * @param v2 second vertex\n * @return distance, or positive infinity if no path\n */\n public double shortestDistance(V v1, V v2) {\n return d[index(v1)][index(v2)];\n }\n\n public double getDiameter() {\n return diameter;\n }\n\n private int index(V vertex) {\n Integer index = indices.get(vertex);\n if (index == null) {\n indices.put(vertex, nextIndex);\n index = nextIndex++;\n }\n return index;\n }\n}\n// End FloydWarshallShortestPaths.java\n"} {"task_id": "Java_978", "language": "Java", "task_type": "empty", "source_file": "java/github/JiangJibo/rocketmq/client/src/main/java/org/apache/rocketmq/client/consumer/listener/ConsumeConcurrentlyStatus.java", "mask_start_position": 111, "mask_end_position": 111, "canonical_solution": "", "pre_mask_code": "package org.apache.rocketmq.client.consumer.listener;\n\npublic enum ConsumeConcurrentlyStatus {\n\n /**\n * ", "post_mask_code": "Success consumption\n */\n CONSUME_SUCCESS,\n /**\n * Failure consumption,later try to consume\n */\n RECONSUME_LATER\n}\n"} {"task_id": "Java_979", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Trilarion/freerails/src/main/java/freerails/client/KeyCodeToOneTileMoveVector.java", "mask_start_position": 1801, "mask_end_position": 1896, "canonical_solution": "public static TileTransition getInstanceMappedToKey(int keycode) throws NoSuchElementException ", "pre_mask_code": "package freerails.client;\n\nimport freerails.model.terrain.TileTransition;\nimport java.awt.event.KeyEvent;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\n/**\n * Maps keys to OneTileMoveVectors.\n */\npublic class KeyCodeToOneTileMoveVector {\n\n private static final Map keycode2vector = new HashMap<>();\n\n static {\n // Set up key mappings...\n // Num pad with num lock on\n keycode2vector.put(KeyEvent.VK_NUMPAD1, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD2, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD3, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD4, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD6, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD7, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD8, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD9, TileTransition.NORTH_EAST);\n // Num pad with num lock off\n keycode2vector.put(KeyEvent.VK_END, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_DOWN, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_PAGE_DOWN, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_LEFT, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_RIGHT, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_HOME, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_UP, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_PAGE_UP, TileTransition.NORTH_EAST);\n }\n\n private KeyCodeToOneTileMoveVector() {\n }\n\n /**\n * Returns the OneTileMoveVector that is mapped to the specified keycode.\n */\n ", "post_mask_code": "{\n Integer integer = keycode;\n if (!keycode2vector.containsKey(integer)) {\n throw new NoSuchElementException(String.valueOf(keycode));\n }\n return keycode2vector.get(integer);\n }\n}\n"} {"task_id": "Java_980", "language": "Java", "task_type": "method_body", "source_file": "java/github/Trilarion/freerails/src/main/java/freerails/client/KeyCodeToOneTileMoveVector.java", "mask_start_position": 1896, "mask_end_position": 2115, "canonical_solution": "{\n Integer integer = keycode;\n if (!keycode2vector.containsKey(integer)) {\n throw new NoSuchElementException(String.valueOf(keycode));\n }\n return keycode2vector.get(integer);\n }", "pre_mask_code": "package freerails.client;\n\nimport freerails.model.terrain.TileTransition;\nimport java.awt.event.KeyEvent;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\n/**\n * Maps keys to OneTileMoveVectors.\n */\npublic class KeyCodeToOneTileMoveVector {\n\n private static final Map keycode2vector = new HashMap<>();\n\n static {\n // Set up key mappings...\n // Num pad with num lock on\n keycode2vector.put(KeyEvent.VK_NUMPAD1, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD2, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD3, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD4, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD6, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD7, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD8, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD9, TileTransition.NORTH_EAST);\n // Num pad with num lock off\n keycode2vector.put(KeyEvent.VK_END, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_DOWN, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_PAGE_DOWN, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_LEFT, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_RIGHT, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_HOME, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_UP, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_PAGE_UP, TileTransition.NORTH_EAST);\n }\n\n private KeyCodeToOneTileMoveVector() {\n }\n\n /**\n * Returns the OneTileMoveVector that is mapped to the specified keycode.\n */\n public static TileTransition getInstanceMappedToKey(int keycode) throws NoSuchElementException ", "post_mask_code": "\n}\n"} {"task_id": "Java_981", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Trilarion/freerails/src/main/java/freerails/client/KeyCodeToOneTileMoveVector.java", "mask_start_position": 1897, "mask_end_position": 1932, "canonical_solution": "\n Integer integer = keycode;", "pre_mask_code": "package freerails.client;\n\nimport freerails.model.terrain.TileTransition;\nimport java.awt.event.KeyEvent;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\n/**\n * Maps keys to OneTileMoveVectors.\n */\npublic class KeyCodeToOneTileMoveVector {\n\n private static final Map keycode2vector = new HashMap<>();\n\n static {\n // Set up key mappings...\n // Num pad with num lock on\n keycode2vector.put(KeyEvent.VK_NUMPAD1, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD2, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD3, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD4, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD6, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD7, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD8, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD9, TileTransition.NORTH_EAST);\n // Num pad with num lock off\n keycode2vector.put(KeyEvent.VK_END, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_DOWN, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_PAGE_DOWN, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_LEFT, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_RIGHT, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_HOME, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_UP, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_PAGE_UP, TileTransition.NORTH_EAST);\n }\n\n private KeyCodeToOneTileMoveVector() {\n }\n\n /**\n * Returns the OneTileMoveVector that is mapped to the specified keycode.\n */\n public static TileTransition getInstanceMappedToKey(int keycode) throws NoSuchElementException {", "post_mask_code": "\n if (!keycode2vector.containsKey(integer)) {\n throw new NoSuchElementException(String.valueOf(keycode));\n }\n return keycode2vector.get(integer);\n }\n}\n"} {"task_id": "Java_982", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Trilarion/freerails/src/main/java/freerails/client/KeyCodeToOneTileMoveVector.java", "mask_start_position": 1941, "mask_end_position": 2065, "canonical_solution": "if (!keycode2vector.containsKey(integer)) {\n throw new NoSuchElementException(String.valueOf(keycode));\n }", "pre_mask_code": "package freerails.client;\n\nimport freerails.model.terrain.TileTransition;\nimport java.awt.event.KeyEvent;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\n/**\n * Maps keys to OneTileMoveVectors.\n */\npublic class KeyCodeToOneTileMoveVector {\n\n private static final Map keycode2vector = new HashMap<>();\n\n static {\n // Set up key mappings...\n // Num pad with num lock on\n keycode2vector.put(KeyEvent.VK_NUMPAD1, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD2, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD3, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD4, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD6, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD7, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD8, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD9, TileTransition.NORTH_EAST);\n // Num pad with num lock off\n keycode2vector.put(KeyEvent.VK_END, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_DOWN, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_PAGE_DOWN, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_LEFT, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_RIGHT, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_HOME, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_UP, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_PAGE_UP, TileTransition.NORTH_EAST);\n }\n\n private KeyCodeToOneTileMoveVector() {\n }\n\n /**\n * Returns the OneTileMoveVector that is mapped to the specified keycode.\n */\n public static TileTransition getInstanceMappedToKey(int keycode) throws NoSuchElementException {\n Integer integer = keycode;\n ", "post_mask_code": "\n return keycode2vector.get(integer);\n }\n}\n"} {"task_id": "Java_983", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Trilarion/freerails/src/main/java/freerails/client/KeyCodeToOneTileMoveVector.java", "mask_start_position": 2074, "mask_end_position": 2115, "canonical_solution": "return keycode2vector.get(integer);\n }", "pre_mask_code": "package freerails.client;\n\nimport freerails.model.terrain.TileTransition;\nimport java.awt.event.KeyEvent;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\n/**\n * Maps keys to OneTileMoveVectors.\n */\npublic class KeyCodeToOneTileMoveVector {\n\n private static final Map keycode2vector = new HashMap<>();\n\n static {\n // Set up key mappings...\n // Num pad with num lock on\n keycode2vector.put(KeyEvent.VK_NUMPAD1, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD2, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD3, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD4, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD6, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD7, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD8, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD9, TileTransition.NORTH_EAST);\n // Num pad with num lock off\n keycode2vector.put(KeyEvent.VK_END, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_DOWN, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_PAGE_DOWN, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_LEFT, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_RIGHT, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_HOME, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_UP, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_PAGE_UP, TileTransition.NORTH_EAST);\n }\n\n private KeyCodeToOneTileMoveVector() {\n }\n\n /**\n * Returns the OneTileMoveVector that is mapped to the specified keycode.\n */\n public static TileTransition getInstanceMappedToKey(int keycode) throws NoSuchElementException {\n Integer integer = keycode;\n if (!keycode2vector.containsKey(integer)) {\n throw new NoSuchElementException(String.valueOf(keycode));\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_984", "language": "Java", "task_type": "single_line", "source_file": "java/github/Trilarion/freerails/src/main/java/freerails/client/KeyCodeToOneTileMoveVector.java", "mask_start_position": 2093, "mask_end_position": 2109, "canonical_solution": "or.get(integer);", "pre_mask_code": "package freerails.client;\n\nimport freerails.model.terrain.TileTransition;\nimport java.awt.event.KeyEvent;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\n/**\n * Maps keys to OneTileMoveVectors.\n */\npublic class KeyCodeToOneTileMoveVector {\n\n private static final Map keycode2vector = new HashMap<>();\n\n static {\n // Set up key mappings...\n // Num pad with num lock on\n keycode2vector.put(KeyEvent.VK_NUMPAD1, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD2, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD3, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD4, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD6, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD7, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD8, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD9, TileTransition.NORTH_EAST);\n // Num pad with num lock off\n keycode2vector.put(KeyEvent.VK_END, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_DOWN, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_PAGE_DOWN, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_LEFT, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_RIGHT, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_HOME, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_UP, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_PAGE_UP, TileTransition.NORTH_EAST);\n }\n\n private KeyCodeToOneTileMoveVector() {\n }\n\n /**\n * Returns the OneTileMoveVector that is mapped to the specified keycode.\n */\n public static TileTransition getInstanceMappedToKey(int keycode) throws NoSuchElementException {\n Integer integer = keycode;\n if (!keycode2vector.containsKey(integer)) {\n throw new NoSuchElementException(String.valueOf(keycode));\n }\n return keycode2vect", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_985", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Trilarion/freerails/src/main/java/freerails/client/KeyCodeToOneTileMoveVector.java", "mask_start_position": 1801, "mask_end_position": 2115, "canonical_solution": "public static TileTransition getInstanceMappedToKey(int keycode) throws NoSuchElementException {\n Integer integer = keycode;\n if (!keycode2vector.containsKey(integer)) {\n throw new NoSuchElementException(String.valueOf(keycode));\n }\n return keycode2vector.get(integer);\n }", "pre_mask_code": "package freerails.client;\n\nimport freerails.model.terrain.TileTransition;\nimport java.awt.event.KeyEvent;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\n/**\n * Maps keys to OneTileMoveVectors.\n */\npublic class KeyCodeToOneTileMoveVector {\n\n private static final Map keycode2vector = new HashMap<>();\n\n static {\n // Set up key mappings...\n // Num pad with num lock on\n keycode2vector.put(KeyEvent.VK_NUMPAD1, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD2, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD3, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD4, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD6, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD7, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD8, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD9, TileTransition.NORTH_EAST);\n // Num pad with num lock off\n keycode2vector.put(KeyEvent.VK_END, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_DOWN, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_PAGE_DOWN, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_LEFT, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_RIGHT, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_HOME, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_UP, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_PAGE_UP, TileTransition.NORTH_EAST);\n }\n\n private KeyCodeToOneTileMoveVector() {\n }\n\n /**\n * Returns the OneTileMoveVector that is mapped to the specified keycode.\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_986", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Trilarion/freerails/src/main/java/freerails/client/KeyCodeToOneTileMoveVector.java", "mask_start_position": 1941, "mask_end_position": 2065, "canonical_solution": "if (!keycode2vector.containsKey(integer)) {\n throw new NoSuchElementException(String.valueOf(keycode));\n }", "pre_mask_code": "package freerails.client;\n\nimport freerails.model.terrain.TileTransition;\nimport java.awt.event.KeyEvent;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\n/**\n * Maps keys to OneTileMoveVectors.\n */\npublic class KeyCodeToOneTileMoveVector {\n\n private static final Map keycode2vector = new HashMap<>();\n\n static {\n // Set up key mappings...\n // Num pad with num lock on\n keycode2vector.put(KeyEvent.VK_NUMPAD1, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD2, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD3, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD4, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD6, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD7, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD8, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD9, TileTransition.NORTH_EAST);\n // Num pad with num lock off\n keycode2vector.put(KeyEvent.VK_END, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_DOWN, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_PAGE_DOWN, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_LEFT, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_RIGHT, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_HOME, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_UP, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_PAGE_UP, TileTransition.NORTH_EAST);\n }\n\n private KeyCodeToOneTileMoveVector() {\n }\n\n /**\n * Returns the OneTileMoveVector that is mapped to the specified keycode.\n */\n public static TileTransition getInstanceMappedToKey(int keycode) throws NoSuchElementException {\n Integer integer = keycode;\n ", "post_mask_code": "\n return keycode2vector.get(integer);\n }\n}\n"} {"task_id": "Java_987", "language": "Java", "task_type": "empty", "source_file": "java/github/Trilarion/freerails/src/main/java/freerails/client/KeyCodeToOneTileMoveVector.java", "mask_start_position": 354, "mask_end_position": 354, "canonical_solution": "", "pre_mask_code": "package freerails.client;\n\nimport freerails.model.terrain.TileTransition;\nimport java.awt.event.KeyEvent;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\n/**\n * Maps keys to OneTileMoveVectors.\n */\npublic class KeyCodeToOneTileMoveVector {\n\n private static final Map keycode2vector = ", "post_mask_code": "new HashMap<>();\n\n static {\n // Set up key mappings...\n // Num pad with num lock on\n keycode2vector.put(KeyEvent.VK_NUMPAD1, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD2, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD3, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD4, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD6, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_NUMPAD7, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_NUMPAD8, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_NUMPAD9, TileTransition.NORTH_EAST);\n // Num pad with num lock off\n keycode2vector.put(KeyEvent.VK_END, TileTransition.SOUTH_WEST);\n keycode2vector.put(KeyEvent.VK_DOWN, TileTransition.SOUTH);\n keycode2vector.put(KeyEvent.VK_PAGE_DOWN, TileTransition.SOUTH_EAST);\n keycode2vector.put(KeyEvent.VK_LEFT, TileTransition.WEST);\n keycode2vector.put(KeyEvent.VK_RIGHT, TileTransition.EAST);\n keycode2vector.put(KeyEvent.VK_HOME, TileTransition.NORTH_WEST);\n keycode2vector.put(KeyEvent.VK_UP, TileTransition.NORTH);\n keycode2vector.put(KeyEvent.VK_PAGE_UP, TileTransition.NORTH_EAST);\n }\n\n private KeyCodeToOneTileMoveVector() {\n }\n\n /**\n * Returns the OneTileMoveVector that is mapped to the specified keycode.\n */\n public static TileTransition getInstanceMappedToKey(int keycode) throws NoSuchElementException {\n Integer integer = keycode;\n if (!keycode2vector.containsKey(integer)) {\n throw new NoSuchElementException(String.valueOf(keycode));\n }\n return keycode2vector.get(integer);\n }\n}\n"} {"task_id": "Java_988", "language": "Java", "task_type": "method_signature", "source_file": "java/github/LonamiWebs/Stringlate/src/core/src/main/java/io/github/lonamiwebs/stringlate/classes/sources/GitSource.java", "mask_start_position": 4142, "mask_end_position": 4207, "canonical_solution": "@Override\n public Resources getResources(final String locale) ", "pre_mask_code": "package io.github.lonamiwebs.stringlate.classes.sources;\n\nimport net.gsantner.opoc.util.FileUtils;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport io.github.lonamiwebs.stringlate.classes.Messenger;\nimport io.github.lonamiwebs.stringlate.classes.git.GitCloneProgressCallback;\nimport io.github.lonamiwebs.stringlate.classes.git.GitWrapper;\nimport io.github.lonamiwebs.stringlate.classes.resources.Resources;\nimport io.github.lonamiwebs.stringlate.classes.resources.tags.ResTag;\nimport io.github.lonamiwebs.stringlate.interfaces.StringsSource;\n\npublic class GitSource implements StringsSource {\n\n private File mWorkDir;\n\n private final String mGitUrl, mBranch;\n\n private final HashMap> mLocaleFiles;\n\n private GitCloneProgressCallback mCloneCallback;\n\n private boolean mCancelled;\n\n private File iconFile;\n\n // Match locale from \"values-(…)/strings.xml\"\n private final static Pattern VALUES_LOCALE_PATTERN = Pattern.compile(\"values(?:-([\\\\w-]+))?/.+?\\\\.xml\");\n\n private static final Pattern DO_NOT_TRANSLATE = Pattern.compile(\"(?:do?[ _-]*no?t?|[u|i]n)[ _-]*trans(?:lat(?:e|able))?\");\n\n public GitSource(final String gitUrl, final String branch) {\n mGitUrl = gitUrl;\n mBranch = branch;\n mLocaleFiles = new HashMap<>();\n }\n\n @Override\n public boolean setup(final SourceSettings settings, final File workDir, final int desiredIconDpi, final Messenger.OnSyncProgress callback) {\n callback.onUpdate(1, 0f);\n settings.set(\"git_url\", mGitUrl);\n mWorkDir = workDir;\n // 2. Clone the repository itself\n mCloneCallback = new GitCloneProgressCallback(callback);\n if (!GitWrapper.cloneRepo(mGitUrl, mWorkDir, mBranch, mCloneCallback) || mCancelled) {\n // TODO These messages are still useful, show them somehow?\n return false;\n }\n // Cache all the repository resources here for faster look-up on upcoming methods\n final GitWrapper.RepositoryResources repoResources = GitWrapper.findUsefulResources(mWorkDir);\n final ArrayList resourceFiles = GitWrapper.searchAndroidResources(repoResources);\n if (resourceFiles.isEmpty() || mCancelled) {\n return false;\n }\n // Save the branches of this repository\n settings.setArray(\"remote_branches\", GitWrapper.getBranches(mWorkDir));\n iconFile = GitWrapper.findProperIcon(repoResources, desiredIconDpi);\n // Iterate over all the found resources to sort them by locale\n for (File resourceFile : resourceFiles) {\n Matcher m = VALUES_LOCALE_PATTERN.matcher(resourceFile.getAbsolutePath());\n // Ensure that we can tell the locale from the path (otherwise it's invalid)\n if (m.find()) {\n if (m.group(1) == null) {\n // Default locale\n // If the file name is something like \"do not translate\", skip it\n if (DO_NOT_TRANSLATE.matcher(resourceFile.getName()).find())\n continue;\n }\n // TODO Can I use .getOrDefault()? It shows an error so let's not risk\n if (!mLocaleFiles.containsKey(m.group(1)))\n mLocaleFiles.put(m.group(1), new ArrayList());\n mLocaleFiles.get(m.group(1)).add(resourceFile);\n }\n }\n settings.set(\"translation_service\", GitWrapper.mayUseTranslationServices(repoResources));\n return !mCancelled;\n }\n\n @Override\n public void cancel() {\n if (mCloneCallback != null) {\n mCloneCallback.cancel();\n }\n mCancelled = true;\n }\n\n @Override\n public String getName() {\n return \"git\";\n }\n\n @Override\n public List getLocales() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.size());\n for (String locale : mLocaleFiles.keySet()) if (locale != null)\n result.add(locale);\n return result;\n }\n\n ", "post_mask_code": "{\n final Resources result = Resources.empty();\n for (File file : mLocaleFiles.get(locale)) {\n for (ResTag rt : Resources.fromFile(file)) result.addTag(rt);\n }\n return result;\n }\n\n @Override\n public List getDefaultResources() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.get(null).size());\n for (File file : mLocaleFiles.get(null)) result.add(getDefaultResourceName(file));\n return result;\n }\n\n @Override\n public Resources getDefaultResource(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return Resources.fromFile(file);\n throw new IllegalArgumentException(\"No default resources were found with that name\");\n }\n\n @Override\n public String getDefaultResourceXml(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return FileUtils.readTextFile(file);\n throw new IllegalArgumentException(\"No XML was found with that name\");\n }\n\n @Override\n public File getIcon() {\n return iconFile;\n }\n\n private String getDefaultResourceName(final File file) {\n return file.getAbsolutePath().substring(mWorkDir.getAbsolutePath().length() + 1);\n }\n\n @Override\n public void dispose() {\n FileUtils.deleteRecursive(mWorkDir);\n mLocaleFiles.clear();\n iconFile = null;\n }\n}\n"} {"task_id": "Java_989", "language": "Java", "task_type": "method_body", "source_file": "java/github/LonamiWebs/Stringlate/src/core/src/main/java/io/github/lonamiwebs/stringlate/classes/sources/GitSource.java", "mask_start_position": 3841, "mask_end_position": 3870, "canonical_solution": "{\n return \"git\";\n }", "pre_mask_code": "package io.github.lonamiwebs.stringlate.classes.sources;\n\nimport net.gsantner.opoc.util.FileUtils;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport io.github.lonamiwebs.stringlate.classes.Messenger;\nimport io.github.lonamiwebs.stringlate.classes.git.GitCloneProgressCallback;\nimport io.github.lonamiwebs.stringlate.classes.git.GitWrapper;\nimport io.github.lonamiwebs.stringlate.classes.resources.Resources;\nimport io.github.lonamiwebs.stringlate.classes.resources.tags.ResTag;\nimport io.github.lonamiwebs.stringlate.interfaces.StringsSource;\n\npublic class GitSource implements StringsSource {\n\n private File mWorkDir;\n\n private final String mGitUrl, mBranch;\n\n private final HashMap> mLocaleFiles;\n\n private GitCloneProgressCallback mCloneCallback;\n\n private boolean mCancelled;\n\n private File iconFile;\n\n // Match locale from \"values-(…)/strings.xml\"\n private final static Pattern VALUES_LOCALE_PATTERN = Pattern.compile(\"values(?:-([\\\\w-]+))?/.+?\\\\.xml\");\n\n private static final Pattern DO_NOT_TRANSLATE = Pattern.compile(\"(?:do?[ _-]*no?t?|[u|i]n)[ _-]*trans(?:lat(?:e|able))?\");\n\n public GitSource(final String gitUrl, final String branch) {\n mGitUrl = gitUrl;\n mBranch = branch;\n mLocaleFiles = new HashMap<>();\n }\n\n @Override\n public boolean setup(final SourceSettings settings, final File workDir, final int desiredIconDpi, final Messenger.OnSyncProgress callback) {\n callback.onUpdate(1, 0f);\n settings.set(\"git_url\", mGitUrl);\n mWorkDir = workDir;\n // 2. Clone the repository itself\n mCloneCallback = new GitCloneProgressCallback(callback);\n if (!GitWrapper.cloneRepo(mGitUrl, mWorkDir, mBranch, mCloneCallback) || mCancelled) {\n // TODO These messages are still useful, show them somehow?\n return false;\n }\n // Cache all the repository resources here for faster look-up on upcoming methods\n final GitWrapper.RepositoryResources repoResources = GitWrapper.findUsefulResources(mWorkDir);\n final ArrayList resourceFiles = GitWrapper.searchAndroidResources(repoResources);\n if (resourceFiles.isEmpty() || mCancelled) {\n return false;\n }\n // Save the branches of this repository\n settings.setArray(\"remote_branches\", GitWrapper.getBranches(mWorkDir));\n iconFile = GitWrapper.findProperIcon(repoResources, desiredIconDpi);\n // Iterate over all the found resources to sort them by locale\n for (File resourceFile : resourceFiles) {\n Matcher m = VALUES_LOCALE_PATTERN.matcher(resourceFile.getAbsolutePath());\n // Ensure that we can tell the locale from the path (otherwise it's invalid)\n if (m.find()) {\n if (m.group(1) == null) {\n // Default locale\n // If the file name is something like \"do not translate\", skip it\n if (DO_NOT_TRANSLATE.matcher(resourceFile.getName()).find())\n continue;\n }\n // TODO Can I use .getOrDefault()? It shows an error so let's not risk\n if (!mLocaleFiles.containsKey(m.group(1)))\n mLocaleFiles.put(m.group(1), new ArrayList());\n mLocaleFiles.get(m.group(1)).add(resourceFile);\n }\n }\n settings.set(\"translation_service\", GitWrapper.mayUseTranslationServices(repoResources));\n return !mCancelled;\n }\n\n @Override\n public void cancel() {\n if (mCloneCallback != null) {\n mCloneCallback.cancel();\n }\n mCancelled = true;\n }\n\n @Override\n public String getName() ", "post_mask_code": "\n\n @Override\n public List getLocales() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.size());\n for (String locale : mLocaleFiles.keySet()) if (locale != null)\n result.add(locale);\n return result;\n }\n\n @Override\n public Resources getResources(final String locale) {\n final Resources result = Resources.empty();\n for (File file : mLocaleFiles.get(locale)) {\n for (ResTag rt : Resources.fromFile(file)) result.addTag(rt);\n }\n return result;\n }\n\n @Override\n public List getDefaultResources() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.get(null).size());\n for (File file : mLocaleFiles.get(null)) result.add(getDefaultResourceName(file));\n return result;\n }\n\n @Override\n public Resources getDefaultResource(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return Resources.fromFile(file);\n throw new IllegalArgumentException(\"No default resources were found with that name\");\n }\n\n @Override\n public String getDefaultResourceXml(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return FileUtils.readTextFile(file);\n throw new IllegalArgumentException(\"No XML was found with that name\");\n }\n\n @Override\n public File getIcon() {\n return iconFile;\n }\n\n private String getDefaultResourceName(final File file) {\n return file.getAbsolutePath().substring(mWorkDir.getAbsolutePath().length() + 1);\n }\n\n @Override\n public void dispose() {\n FileUtils.deleteRecursive(mWorkDir);\n mLocaleFiles.clear();\n iconFile = null;\n }\n}\n"} {"task_id": "Java_990", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/LonamiWebs/Stringlate/src/core/src/main/java/io/github/lonamiwebs/stringlate/classes/sources/GitSource.java", "mask_start_position": 4208, "mask_end_position": 4260, "canonical_solution": "\n final Resources result = Resources.empty();", "pre_mask_code": "package io.github.lonamiwebs.stringlate.classes.sources;\n\nimport net.gsantner.opoc.util.FileUtils;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport io.github.lonamiwebs.stringlate.classes.Messenger;\nimport io.github.lonamiwebs.stringlate.classes.git.GitCloneProgressCallback;\nimport io.github.lonamiwebs.stringlate.classes.git.GitWrapper;\nimport io.github.lonamiwebs.stringlate.classes.resources.Resources;\nimport io.github.lonamiwebs.stringlate.classes.resources.tags.ResTag;\nimport io.github.lonamiwebs.stringlate.interfaces.StringsSource;\n\npublic class GitSource implements StringsSource {\n\n private File mWorkDir;\n\n private final String mGitUrl, mBranch;\n\n private final HashMap> mLocaleFiles;\n\n private GitCloneProgressCallback mCloneCallback;\n\n private boolean mCancelled;\n\n private File iconFile;\n\n // Match locale from \"values-(…)/strings.xml\"\n private final static Pattern VALUES_LOCALE_PATTERN = Pattern.compile(\"values(?:-([\\\\w-]+))?/.+?\\\\.xml\");\n\n private static final Pattern DO_NOT_TRANSLATE = Pattern.compile(\"(?:do?[ _-]*no?t?|[u|i]n)[ _-]*trans(?:lat(?:e|able))?\");\n\n public GitSource(final String gitUrl, final String branch) {\n mGitUrl = gitUrl;\n mBranch = branch;\n mLocaleFiles = new HashMap<>();\n }\n\n @Override\n public boolean setup(final SourceSettings settings, final File workDir, final int desiredIconDpi, final Messenger.OnSyncProgress callback) {\n callback.onUpdate(1, 0f);\n settings.set(\"git_url\", mGitUrl);\n mWorkDir = workDir;\n // 2. Clone the repository itself\n mCloneCallback = new GitCloneProgressCallback(callback);\n if (!GitWrapper.cloneRepo(mGitUrl, mWorkDir, mBranch, mCloneCallback) || mCancelled) {\n // TODO These messages are still useful, show them somehow?\n return false;\n }\n // Cache all the repository resources here for faster look-up on upcoming methods\n final GitWrapper.RepositoryResources repoResources = GitWrapper.findUsefulResources(mWorkDir);\n final ArrayList resourceFiles = GitWrapper.searchAndroidResources(repoResources);\n if (resourceFiles.isEmpty() || mCancelled) {\n return false;\n }\n // Save the branches of this repository\n settings.setArray(\"remote_branches\", GitWrapper.getBranches(mWorkDir));\n iconFile = GitWrapper.findProperIcon(repoResources, desiredIconDpi);\n // Iterate over all the found resources to sort them by locale\n for (File resourceFile : resourceFiles) {\n Matcher m = VALUES_LOCALE_PATTERN.matcher(resourceFile.getAbsolutePath());\n // Ensure that we can tell the locale from the path (otherwise it's invalid)\n if (m.find()) {\n if (m.group(1) == null) {\n // Default locale\n // If the file name is something like \"do not translate\", skip it\n if (DO_NOT_TRANSLATE.matcher(resourceFile.getName()).find())\n continue;\n }\n // TODO Can I use .getOrDefault()? It shows an error so let's not risk\n if (!mLocaleFiles.containsKey(m.group(1)))\n mLocaleFiles.put(m.group(1), new ArrayList());\n mLocaleFiles.get(m.group(1)).add(resourceFile);\n }\n }\n settings.set(\"translation_service\", GitWrapper.mayUseTranslationServices(repoResources));\n return !mCancelled;\n }\n\n @Override\n public void cancel() {\n if (mCloneCallback != null) {\n mCloneCallback.cancel();\n }\n mCancelled = true;\n }\n\n @Override\n public String getName() {\n return \"git\";\n }\n\n @Override\n public List getLocales() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.size());\n for (String locale : mLocaleFiles.keySet()) if (locale != null)\n result.add(locale);\n return result;\n }\n\n @Override\n public Resources getResources(final String locale) {", "post_mask_code": "\n for (File file : mLocaleFiles.get(locale)) {\n for (ResTag rt : Resources.fromFile(file)) result.addTag(rt);\n }\n return result;\n }\n\n @Override\n public List getDefaultResources() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.get(null).size());\n for (File file : mLocaleFiles.get(null)) result.add(getDefaultResourceName(file));\n return result;\n }\n\n @Override\n public Resources getDefaultResource(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return Resources.fromFile(file);\n throw new IllegalArgumentException(\"No default resources were found with that name\");\n }\n\n @Override\n public String getDefaultResourceXml(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return FileUtils.readTextFile(file);\n throw new IllegalArgumentException(\"No XML was found with that name\");\n }\n\n @Override\n public File getIcon() {\n return iconFile;\n }\n\n private String getDefaultResourceName(final File file) {\n return file.getAbsolutePath().substring(mWorkDir.getAbsolutePath().length() + 1);\n }\n\n @Override\n public void dispose() {\n FileUtils.deleteRecursive(mWorkDir);\n mLocaleFiles.clear();\n iconFile = null;\n }\n}\n"} {"task_id": "Java_991", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/LonamiWebs/Stringlate/src/core/src/main/java/io/github/lonamiwebs/stringlate/classes/sources/GitSource.java", "mask_start_position": 4269, "mask_end_position": 4397, "canonical_solution": "for (File file : mLocaleFiles.get(locale)) {\n for (ResTag rt : Resources.fromFile(file)) result.addTag(rt);\n }", "pre_mask_code": "package io.github.lonamiwebs.stringlate.classes.sources;\n\nimport net.gsantner.opoc.util.FileUtils;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport io.github.lonamiwebs.stringlate.classes.Messenger;\nimport io.github.lonamiwebs.stringlate.classes.git.GitCloneProgressCallback;\nimport io.github.lonamiwebs.stringlate.classes.git.GitWrapper;\nimport io.github.lonamiwebs.stringlate.classes.resources.Resources;\nimport io.github.lonamiwebs.stringlate.classes.resources.tags.ResTag;\nimport io.github.lonamiwebs.stringlate.interfaces.StringsSource;\n\npublic class GitSource implements StringsSource {\n\n private File mWorkDir;\n\n private final String mGitUrl, mBranch;\n\n private final HashMap> mLocaleFiles;\n\n private GitCloneProgressCallback mCloneCallback;\n\n private boolean mCancelled;\n\n private File iconFile;\n\n // Match locale from \"values-(…)/strings.xml\"\n private final static Pattern VALUES_LOCALE_PATTERN = Pattern.compile(\"values(?:-([\\\\w-]+))?/.+?\\\\.xml\");\n\n private static final Pattern DO_NOT_TRANSLATE = Pattern.compile(\"(?:do?[ _-]*no?t?|[u|i]n)[ _-]*trans(?:lat(?:e|able))?\");\n\n public GitSource(final String gitUrl, final String branch) {\n mGitUrl = gitUrl;\n mBranch = branch;\n mLocaleFiles = new HashMap<>();\n }\n\n @Override\n public boolean setup(final SourceSettings settings, final File workDir, final int desiredIconDpi, final Messenger.OnSyncProgress callback) {\n callback.onUpdate(1, 0f);\n settings.set(\"git_url\", mGitUrl);\n mWorkDir = workDir;\n // 2. Clone the repository itself\n mCloneCallback = new GitCloneProgressCallback(callback);\n if (!GitWrapper.cloneRepo(mGitUrl, mWorkDir, mBranch, mCloneCallback) || mCancelled) {\n // TODO These messages are still useful, show them somehow?\n return false;\n }\n // Cache all the repository resources here for faster look-up on upcoming methods\n final GitWrapper.RepositoryResources repoResources = GitWrapper.findUsefulResources(mWorkDir);\n final ArrayList resourceFiles = GitWrapper.searchAndroidResources(repoResources);\n if (resourceFiles.isEmpty() || mCancelled) {\n return false;\n }\n // Save the branches of this repository\n settings.setArray(\"remote_branches\", GitWrapper.getBranches(mWorkDir));\n iconFile = GitWrapper.findProperIcon(repoResources, desiredIconDpi);\n // Iterate over all the found resources to sort them by locale\n for (File resourceFile : resourceFiles) {\n Matcher m = VALUES_LOCALE_PATTERN.matcher(resourceFile.getAbsolutePath());\n // Ensure that we can tell the locale from the path (otherwise it's invalid)\n if (m.find()) {\n if (m.group(1) == null) {\n // Default locale\n // If the file name is something like \"do not translate\", skip it\n if (DO_NOT_TRANSLATE.matcher(resourceFile.getName()).find())\n continue;\n }\n // TODO Can I use .getOrDefault()? It shows an error so let's not risk\n if (!mLocaleFiles.containsKey(m.group(1)))\n mLocaleFiles.put(m.group(1), new ArrayList());\n mLocaleFiles.get(m.group(1)).add(resourceFile);\n }\n }\n settings.set(\"translation_service\", GitWrapper.mayUseTranslationServices(repoResources));\n return !mCancelled;\n }\n\n @Override\n public void cancel() {\n if (mCloneCallback != null) {\n mCloneCallback.cancel();\n }\n mCancelled = true;\n }\n\n @Override\n public String getName() {\n return \"git\";\n }\n\n @Override\n public List getLocales() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.size());\n for (String locale : mLocaleFiles.keySet()) if (locale != null)\n result.add(locale);\n return result;\n }\n\n @Override\n public Resources getResources(final String locale) {\n final Resources result = Resources.empty();\n ", "post_mask_code": "\n return result;\n }\n\n @Override\n public List getDefaultResources() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.get(null).size());\n for (File file : mLocaleFiles.get(null)) result.add(getDefaultResourceName(file));\n return result;\n }\n\n @Override\n public Resources getDefaultResource(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return Resources.fromFile(file);\n throw new IllegalArgumentException(\"No default resources were found with that name\");\n }\n\n @Override\n public String getDefaultResourceXml(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return FileUtils.readTextFile(file);\n throw new IllegalArgumentException(\"No XML was found with that name\");\n }\n\n @Override\n public File getIcon() {\n return iconFile;\n }\n\n private String getDefaultResourceName(final File file) {\n return file.getAbsolutePath().substring(mWorkDir.getAbsolutePath().length() + 1);\n }\n\n @Override\n public void dispose() {\n FileUtils.deleteRecursive(mWorkDir);\n mLocaleFiles.clear();\n iconFile = null;\n }\n}\n"} {"task_id": "Java_992", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/LonamiWebs/Stringlate/src/core/src/main/java/io/github/lonamiwebs/stringlate/classes/sources/GitSource.java", "mask_start_position": 4406, "mask_end_position": 4426, "canonical_solution": "return result;\n }", "pre_mask_code": "package io.github.lonamiwebs.stringlate.classes.sources;\n\nimport net.gsantner.opoc.util.FileUtils;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport io.github.lonamiwebs.stringlate.classes.Messenger;\nimport io.github.lonamiwebs.stringlate.classes.git.GitCloneProgressCallback;\nimport io.github.lonamiwebs.stringlate.classes.git.GitWrapper;\nimport io.github.lonamiwebs.stringlate.classes.resources.Resources;\nimport io.github.lonamiwebs.stringlate.classes.resources.tags.ResTag;\nimport io.github.lonamiwebs.stringlate.interfaces.StringsSource;\n\npublic class GitSource implements StringsSource {\n\n private File mWorkDir;\n\n private final String mGitUrl, mBranch;\n\n private final HashMap> mLocaleFiles;\n\n private GitCloneProgressCallback mCloneCallback;\n\n private boolean mCancelled;\n\n private File iconFile;\n\n // Match locale from \"values-(…)/strings.xml\"\n private final static Pattern VALUES_LOCALE_PATTERN = Pattern.compile(\"values(?:-([\\\\w-]+))?/.+?\\\\.xml\");\n\n private static final Pattern DO_NOT_TRANSLATE = Pattern.compile(\"(?:do?[ _-]*no?t?|[u|i]n)[ _-]*trans(?:lat(?:e|able))?\");\n\n public GitSource(final String gitUrl, final String branch) {\n mGitUrl = gitUrl;\n mBranch = branch;\n mLocaleFiles = new HashMap<>();\n }\n\n @Override\n public boolean setup(final SourceSettings settings, final File workDir, final int desiredIconDpi, final Messenger.OnSyncProgress callback) {\n callback.onUpdate(1, 0f);\n settings.set(\"git_url\", mGitUrl);\n mWorkDir = workDir;\n // 2. Clone the repository itself\n mCloneCallback = new GitCloneProgressCallback(callback);\n if (!GitWrapper.cloneRepo(mGitUrl, mWorkDir, mBranch, mCloneCallback) || mCancelled) {\n // TODO These messages are still useful, show them somehow?\n return false;\n }\n // Cache all the repository resources here for faster look-up on upcoming methods\n final GitWrapper.RepositoryResources repoResources = GitWrapper.findUsefulResources(mWorkDir);\n final ArrayList resourceFiles = GitWrapper.searchAndroidResources(repoResources);\n if (resourceFiles.isEmpty() || mCancelled) {\n return false;\n }\n // Save the branches of this repository\n settings.setArray(\"remote_branches\", GitWrapper.getBranches(mWorkDir));\n iconFile = GitWrapper.findProperIcon(repoResources, desiredIconDpi);\n // Iterate over all the found resources to sort them by locale\n for (File resourceFile : resourceFiles) {\n Matcher m = VALUES_LOCALE_PATTERN.matcher(resourceFile.getAbsolutePath());\n // Ensure that we can tell the locale from the path (otherwise it's invalid)\n if (m.find()) {\n if (m.group(1) == null) {\n // Default locale\n // If the file name is something like \"do not translate\", skip it\n if (DO_NOT_TRANSLATE.matcher(resourceFile.getName()).find())\n continue;\n }\n // TODO Can I use .getOrDefault()? It shows an error so let's not risk\n if (!mLocaleFiles.containsKey(m.group(1)))\n mLocaleFiles.put(m.group(1), new ArrayList());\n mLocaleFiles.get(m.group(1)).add(resourceFile);\n }\n }\n settings.set(\"translation_service\", GitWrapper.mayUseTranslationServices(repoResources));\n return !mCancelled;\n }\n\n @Override\n public void cancel() {\n if (mCloneCallback != null) {\n mCloneCallback.cancel();\n }\n mCancelled = true;\n }\n\n @Override\n public String getName() {\n return \"git\";\n }\n\n @Override\n public List getLocales() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.size());\n for (String locale : mLocaleFiles.keySet()) if (locale != null)\n result.add(locale);\n return result;\n }\n\n @Override\n public Resources getResources(final String locale) {\n final Resources result = Resources.empty();\n for (File file : mLocaleFiles.get(locale)) {\n for (ResTag rt : Resources.fromFile(file)) result.addTag(rt);\n }\n ", "post_mask_code": "\n\n @Override\n public List getDefaultResources() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.get(null).size());\n for (File file : mLocaleFiles.get(null)) result.add(getDefaultResourceName(file));\n return result;\n }\n\n @Override\n public Resources getDefaultResource(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return Resources.fromFile(file);\n throw new IllegalArgumentException(\"No default resources were found with that name\");\n }\n\n @Override\n public String getDefaultResourceXml(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return FileUtils.readTextFile(file);\n throw new IllegalArgumentException(\"No XML was found with that name\");\n }\n\n @Override\n public File getIcon() {\n return iconFile;\n }\n\n private String getDefaultResourceName(final File file) {\n return file.getAbsolutePath().substring(mWorkDir.getAbsolutePath().length() + 1);\n }\n\n @Override\n public void dispose() {\n FileUtils.deleteRecursive(mWorkDir);\n mLocaleFiles.clear();\n iconFile = null;\n }\n}\n"} {"task_id": "Java_993", "language": "Java", "task_type": "single_line", "source_file": "java/github/LonamiWebs/Stringlate/src/core/src/main/java/io/github/lonamiwebs/stringlate/classes/sources/GitSource.java", "mask_start_position": 4991, "mask_end_position": 5003, "canonical_solution": "that name\");", "pre_mask_code": "package io.github.lonamiwebs.stringlate.classes.sources;\n\nimport net.gsantner.opoc.util.FileUtils;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport io.github.lonamiwebs.stringlate.classes.Messenger;\nimport io.github.lonamiwebs.stringlate.classes.git.GitCloneProgressCallback;\nimport io.github.lonamiwebs.stringlate.classes.git.GitWrapper;\nimport io.github.lonamiwebs.stringlate.classes.resources.Resources;\nimport io.github.lonamiwebs.stringlate.classes.resources.tags.ResTag;\nimport io.github.lonamiwebs.stringlate.interfaces.StringsSource;\n\npublic class GitSource implements StringsSource {\n\n private File mWorkDir;\n\n private final String mGitUrl, mBranch;\n\n private final HashMap> mLocaleFiles;\n\n private GitCloneProgressCallback mCloneCallback;\n\n private boolean mCancelled;\n\n private File iconFile;\n\n // Match locale from \"values-(…)/strings.xml\"\n private final static Pattern VALUES_LOCALE_PATTERN = Pattern.compile(\"values(?:-([\\\\w-]+))?/.+?\\\\.xml\");\n\n private static final Pattern DO_NOT_TRANSLATE = Pattern.compile(\"(?:do?[ _-]*no?t?|[u|i]n)[ _-]*trans(?:lat(?:e|able))?\");\n\n public GitSource(final String gitUrl, final String branch) {\n mGitUrl = gitUrl;\n mBranch = branch;\n mLocaleFiles = new HashMap<>();\n }\n\n @Override\n public boolean setup(final SourceSettings settings, final File workDir, final int desiredIconDpi, final Messenger.OnSyncProgress callback) {\n callback.onUpdate(1, 0f);\n settings.set(\"git_url\", mGitUrl);\n mWorkDir = workDir;\n // 2. Clone the repository itself\n mCloneCallback = new GitCloneProgressCallback(callback);\n if (!GitWrapper.cloneRepo(mGitUrl, mWorkDir, mBranch, mCloneCallback) || mCancelled) {\n // TODO These messages are still useful, show them somehow?\n return false;\n }\n // Cache all the repository resources here for faster look-up on upcoming methods\n final GitWrapper.RepositoryResources repoResources = GitWrapper.findUsefulResources(mWorkDir);\n final ArrayList resourceFiles = GitWrapper.searchAndroidResources(repoResources);\n if (resourceFiles.isEmpty() || mCancelled) {\n return false;\n }\n // Save the branches of this repository\n settings.setArray(\"remote_branches\", GitWrapper.getBranches(mWorkDir));\n iconFile = GitWrapper.findProperIcon(repoResources, desiredIconDpi);\n // Iterate over all the found resources to sort them by locale\n for (File resourceFile : resourceFiles) {\n Matcher m = VALUES_LOCALE_PATTERN.matcher(resourceFile.getAbsolutePath());\n // Ensure that we can tell the locale from the path (otherwise it's invalid)\n if (m.find()) {\n if (m.group(1) == null) {\n // Default locale\n // If the file name is something like \"do not translate\", skip it\n if (DO_NOT_TRANSLATE.matcher(resourceFile.getName()).find())\n continue;\n }\n // TODO Can I use .getOrDefault()? It shows an error so let's not risk\n if (!mLocaleFiles.containsKey(m.group(1)))\n mLocaleFiles.put(m.group(1), new ArrayList());\n mLocaleFiles.get(m.group(1)).add(resourceFile);\n }\n }\n settings.set(\"translation_service\", GitWrapper.mayUseTranslationServices(repoResources));\n return !mCancelled;\n }\n\n @Override\n public void cancel() {\n if (mCloneCallback != null) {\n mCloneCallback.cancel();\n }\n mCancelled = true;\n }\n\n @Override\n public String getName() {\n return \"git\";\n }\n\n @Override\n public List getLocales() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.size());\n for (String locale : mLocaleFiles.keySet()) if (locale != null)\n result.add(locale);\n return result;\n }\n\n @Override\n public Resources getResources(final String locale) {\n final Resources result = Resources.empty();\n for (File file : mLocaleFiles.get(locale)) {\n for (ResTag rt : Resources.fromFile(file)) result.addTag(rt);\n }\n return result;\n }\n\n @Override\n public List getDefaultResources() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.get(null).size());\n for (File file : mLocaleFiles.get(null)) result.add(getDefaultResourceName(file));\n return result;\n }\n\n @Override\n public Resources getDefaultResource(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return Resources.fromFile(file);\n throw new IllegalArgumentException(\"No default resources were found with ", "post_mask_code": "\n }\n\n @Override\n public String getDefaultResourceXml(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return FileUtils.readTextFile(file);\n throw new IllegalArgumentException(\"No XML was found with that name\");\n }\n\n @Override\n public File getIcon() {\n return iconFile;\n }\n\n private String getDefaultResourceName(final File file) {\n return file.getAbsolutePath().substring(mWorkDir.getAbsolutePath().length() + 1);\n }\n\n @Override\n public void dispose() {\n FileUtils.deleteRecursive(mWorkDir);\n mLocaleFiles.clear();\n iconFile = null;\n }\n}\n"} {"task_id": "Java_994", "language": "Java", "task_type": "if_statement", "source_file": "java/github/LonamiWebs/Stringlate/src/core/src/main/java/io/github/lonamiwebs/stringlate/classes/sources/GitSource.java", "mask_start_position": 4818, "mask_end_position": 4909, "canonical_solution": "if (getDefaultResourceName(file).equals(name))\n return Resources.fromFile(file);", "pre_mask_code": "package io.github.lonamiwebs.stringlate.classes.sources;\n\nimport net.gsantner.opoc.util.FileUtils;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport io.github.lonamiwebs.stringlate.classes.Messenger;\nimport io.github.lonamiwebs.stringlate.classes.git.GitCloneProgressCallback;\nimport io.github.lonamiwebs.stringlate.classes.git.GitWrapper;\nimport io.github.lonamiwebs.stringlate.classes.resources.Resources;\nimport io.github.lonamiwebs.stringlate.classes.resources.tags.ResTag;\nimport io.github.lonamiwebs.stringlate.interfaces.StringsSource;\n\npublic class GitSource implements StringsSource {\n\n private File mWorkDir;\n\n private final String mGitUrl, mBranch;\n\n private final HashMap> mLocaleFiles;\n\n private GitCloneProgressCallback mCloneCallback;\n\n private boolean mCancelled;\n\n private File iconFile;\n\n // Match locale from \"values-(…)/strings.xml\"\n private final static Pattern VALUES_LOCALE_PATTERN = Pattern.compile(\"values(?:-([\\\\w-]+))?/.+?\\\\.xml\");\n\n private static final Pattern DO_NOT_TRANSLATE = Pattern.compile(\"(?:do?[ _-]*no?t?|[u|i]n)[ _-]*trans(?:lat(?:e|able))?\");\n\n public GitSource(final String gitUrl, final String branch) {\n mGitUrl = gitUrl;\n mBranch = branch;\n mLocaleFiles = new HashMap<>();\n }\n\n @Override\n public boolean setup(final SourceSettings settings, final File workDir, final int desiredIconDpi, final Messenger.OnSyncProgress callback) {\n callback.onUpdate(1, 0f);\n settings.set(\"git_url\", mGitUrl);\n mWorkDir = workDir;\n // 2. Clone the repository itself\n mCloneCallback = new GitCloneProgressCallback(callback);\n if (!GitWrapper.cloneRepo(mGitUrl, mWorkDir, mBranch, mCloneCallback) || mCancelled) {\n // TODO These messages are still useful, show them somehow?\n return false;\n }\n // Cache all the repository resources here for faster look-up on upcoming methods\n final GitWrapper.RepositoryResources repoResources = GitWrapper.findUsefulResources(mWorkDir);\n final ArrayList resourceFiles = GitWrapper.searchAndroidResources(repoResources);\n if (resourceFiles.isEmpty() || mCancelled) {\n return false;\n }\n // Save the branches of this repository\n settings.setArray(\"remote_branches\", GitWrapper.getBranches(mWorkDir));\n iconFile = GitWrapper.findProperIcon(repoResources, desiredIconDpi);\n // Iterate over all the found resources to sort them by locale\n for (File resourceFile : resourceFiles) {\n Matcher m = VALUES_LOCALE_PATTERN.matcher(resourceFile.getAbsolutePath());\n // Ensure that we can tell the locale from the path (otherwise it's invalid)\n if (m.find()) {\n if (m.group(1) == null) {\n // Default locale\n // If the file name is something like \"do not translate\", skip it\n if (DO_NOT_TRANSLATE.matcher(resourceFile.getName()).find())\n continue;\n }\n // TODO Can I use .getOrDefault()? It shows an error so let's not risk\n if (!mLocaleFiles.containsKey(m.group(1)))\n mLocaleFiles.put(m.group(1), new ArrayList());\n mLocaleFiles.get(m.group(1)).add(resourceFile);\n }\n }\n settings.set(\"translation_service\", GitWrapper.mayUseTranslationServices(repoResources));\n return !mCancelled;\n }\n\n @Override\n public void cancel() {\n if (mCloneCallback != null) {\n mCloneCallback.cancel();\n }\n mCancelled = true;\n }\n\n @Override\n public String getName() {\n return \"git\";\n }\n\n @Override\n public List getLocales() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.size());\n for (String locale : mLocaleFiles.keySet()) if (locale != null)\n result.add(locale);\n return result;\n }\n\n @Override\n public Resources getResources(final String locale) {\n final Resources result = Resources.empty();\n for (File file : mLocaleFiles.get(locale)) {\n for (ResTag rt : Resources.fromFile(file)) result.addTag(rt);\n }\n return result;\n }\n\n @Override\n public List getDefaultResources() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.get(null).size());\n for (File file : mLocaleFiles.get(null)) result.add(getDefaultResourceName(file));\n return result;\n }\n\n @Override\n public Resources getDefaultResource(String name) {\n for (File file : mLocaleFiles.get(null)) ", "post_mask_code": "\n throw new IllegalArgumentException(\"No default resources were found with that name\");\n }\n\n @Override\n public String getDefaultResourceXml(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return FileUtils.readTextFile(file);\n throw new IllegalArgumentException(\"No XML was found with that name\");\n }\n\n @Override\n public File getIcon() {\n return iconFile;\n }\n\n private String getDefaultResourceName(final File file) {\n return file.getAbsolutePath().substring(mWorkDir.getAbsolutePath().length() + 1);\n }\n\n @Override\n public void dispose() {\n FileUtils.deleteRecursive(mWorkDir);\n mLocaleFiles.clear();\n iconFile = null;\n }\n}\n"} {"task_id": "Java_995", "language": "Java", "task_type": "empty", "source_file": "java/github/LonamiWebs/Stringlate/src/core/src/main/java/io/github/lonamiwebs/stringlate/classes/sources/GitSource.java", "mask_start_position": 3674, "mask_end_position": 3674, "canonical_solution": "", "pre_mask_code": "package io.github.lonamiwebs.stringlate.classes.sources;\n\nimport net.gsantner.opoc.util.FileUtils;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport io.github.lonamiwebs.stringlate.classes.Messenger;\nimport io.github.lonamiwebs.stringlate.classes.git.GitCloneProgressCallback;\nimport io.github.lonamiwebs.stringlate.classes.git.GitWrapper;\nimport io.github.lonamiwebs.stringlate.classes.resources.Resources;\nimport io.github.lonamiwebs.stringlate.classes.resources.tags.ResTag;\nimport io.github.lonamiwebs.stringlate.interfaces.StringsSource;\n\npublic class GitSource implements StringsSource {\n\n private File mWorkDir;\n\n private final String mGitUrl, mBranch;\n\n private final HashMap> mLocaleFiles;\n\n private GitCloneProgressCallback mCloneCallback;\n\n private boolean mCancelled;\n\n private File iconFile;\n\n // Match locale from \"values-(…)/strings.xml\"\n private final static Pattern VALUES_LOCALE_PATTERN = Pattern.compile(\"values(?:-([\\\\w-]+))?/.+?\\\\.xml\");\n\n private static final Pattern DO_NOT_TRANSLATE = Pattern.compile(\"(?:do?[ _-]*no?t?|[u|i]n)[ _-]*trans(?:lat(?:e|able))?\");\n\n public GitSource(final String gitUrl, final String branch) {\n mGitUrl = gitUrl;\n mBranch = branch;\n mLocaleFiles = new HashMap<>();\n }\n\n @Override\n public boolean setup(final SourceSettings settings, final File workDir, final int desiredIconDpi, final Messenger.OnSyncProgress callback) {\n callback.onUpdate(1, 0f);\n settings.set(\"git_url\", mGitUrl);\n mWorkDir = workDir;\n // 2. Clone the repository itself\n mCloneCallback = new GitCloneProgressCallback(callback);\n if (!GitWrapper.cloneRepo(mGitUrl, mWorkDir, mBranch, mCloneCallback) || mCancelled) {\n // TODO These messages are still useful, show them somehow?\n return false;\n }\n // Cache all the repository resources here for faster look-up on upcoming methods\n final GitWrapper.RepositoryResources repoResources = GitWrapper.findUsefulResources(mWorkDir);\n final ArrayList resourceFiles = GitWrapper.searchAndroidResources(repoResources);\n if (resourceFiles.isEmpty() || mCancelled) {\n return false;\n }\n // Save the branches of this repository\n settings.setArray(\"remote_branches\", GitWrapper.getBranches(mWorkDir));\n iconFile = GitWrapper.findProperIcon(repoResources, desiredIconDpi);\n // Iterate over all the found resources to sort them by locale\n for (File resourceFile : resourceFiles) {\n Matcher m = VALUES_LOCALE_PATTERN.matcher(resourceFile.getAbsolutePath());\n // Ensure that we can tell the locale from the path (otherwise it's invalid)\n if (m.find()) {\n if (m.group(1) == null) {\n // Default locale\n // If the file name is something like \"do not translate\", skip it\n if (DO_NOT_TRANSLATE.matcher(resourceFile.getName()).find())\n continue;\n }\n // TODO Can I use .getOrDefault()? It shows an error so let's not risk\n if (!mLocaleFiles.containsKey(m.group(1)))\n mLocaleFiles.put(m.group(1), new ArrayList());\n mLocaleFiles.get(m.group(1)).add(resourceFile);\n }\n }\n settings.set(\"translation_service\", GitWrapper.mayUseTranslationServices(repoResources));\n return !mCancelled;\n }\n\n @Override\n public void cance", "post_mask_code": "l() {\n if (mCloneCallback != null) {\n mCloneCallback.cancel();\n }\n mCancelled = true;\n }\n\n @Override\n public String getName() {\n return \"git\";\n }\n\n @Override\n public List getLocales() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.size());\n for (String locale : mLocaleFiles.keySet()) if (locale != null)\n result.add(locale);\n return result;\n }\n\n @Override\n public Resources getResources(final String locale) {\n final Resources result = Resources.empty();\n for (File file : mLocaleFiles.get(locale)) {\n for (ResTag rt : Resources.fromFile(file)) result.addTag(rt);\n }\n return result;\n }\n\n @Override\n public List getDefaultResources() {\n final ArrayList result = new ArrayList<>(mLocaleFiles.get(null).size());\n for (File file : mLocaleFiles.get(null)) result.add(getDefaultResourceName(file));\n return result;\n }\n\n @Override\n public Resources getDefaultResource(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return Resources.fromFile(file);\n throw new IllegalArgumentException(\"No default resources were found with that name\");\n }\n\n @Override\n public String getDefaultResourceXml(String name) {\n for (File file : mLocaleFiles.get(null)) if (getDefaultResourceName(file).equals(name))\n return FileUtils.readTextFile(file);\n throw new IllegalArgumentException(\"No XML was found with that name\");\n }\n\n @Override\n public File getIcon() {\n return iconFile;\n }\n\n private String getDefaultResourceName(final File file) {\n return file.getAbsolutePath().substring(mWorkDir.getAbsolutePath().length() + 1);\n }\n\n @Override\n public void dispose() {\n FileUtils.deleteRecursive(mWorkDir);\n mLocaleFiles.clear();\n iconFile = null;\n }\n}\n"} {"task_id": "Java_996", "language": "Java", "task_type": "empty", "source_file": "java/github/eclipse-ee4j/jersey/tests/integration/servlet-2.5-inflector-1/src/main/java/org/glassfish/jersey/tests/integration/servlet_25_inflector_1/MyApplication.java", "mask_start_position": 136, "mask_end_position": 136, "canonical_solution": "", "pre_mask_code": "package org.glassfish.jersey.tests.integration.servlet_25_inflector_1;\n\nimport org.glassfish.jersey.server.ResourceConfig;\nimport org.gl", "post_mask_code": "assfish.jersey.server.model.Resource;\n\n/**\n * @author Michal Gajdos\n */\npublic class MyApplication extends ResourceConfig {\n\n public MyApplication() {\n final Resource.Builder resourceBuilder = Resource.builder(\"resource\");\n resourceBuilder.addChildResource(\"class\").addMethod(\"GET\").handledBy(MyInflector.class);\n resourceBuilder.addChildResource(\"instance\").addMethod(\"GET\").handledBy(new MyInflector());\n registerResources(resourceBuilder.build());\n }\n}\n"} {"task_id": "Java_997", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/ByteBufferExpander.java", "mask_start_position": 642, "mask_end_position": 669, "canonical_solution": "public ByteBuffer buffer() ", "pre_mask_code": "package org.apache.ignite.internal.processors.cache.persistence.wal;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport org.apache.ignite.internal.util.GridUnsafe;\n\n/**\n * ByteBuffer wrapper for dynamically expand buffer size.\n */\npublic class ByteBufferExpander implements AutoCloseable {\n\n /**\n * Byte buffer\n */\n private ByteBuffer buf;\n\n /**\n * @param initSize Initial size.\n * @param order Byte order.\n */\n public ByteBufferExpander(int initSize, ByteOrder order) {\n ByteBuffer buffer = GridUnsafe.allocateBuffer(initSize);\n buffer.order(order);\n buf = buffer;\n }\n\n ", "post_mask_code": "{\n return buf;\n }\n\n /**\n * Expands current byte buffer to the requested size.\n *\n * @return ByteBuffer with requested size.\n */\n public ByteBuffer expand(int size) {\n assert buf.capacity() < size;\n int pos = buf.position();\n int lim = buf.limit();\n ByteBuffer newBuf = GridUnsafe.reallocateBuffer(buf, size);\n newBuf.order(buf.order());\n newBuf.position(pos);\n newBuf.limit(lim);\n buf = newBuf;\n return newBuf;\n }\n\n @Override\n public void close() {\n GridUnsafe.freeBuffer(buf);\n }\n}\n"} {"task_id": "Java_998", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/ByteBufferExpander.java", "mask_start_position": 669, "mask_end_position": 696, "canonical_solution": "{\n return buf;\n }", "pre_mask_code": "package org.apache.ignite.internal.processors.cache.persistence.wal;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport org.apache.ignite.internal.util.GridUnsafe;\n\n/**\n * ByteBuffer wrapper for dynamically expand buffer size.\n */\npublic class ByteBufferExpander implements AutoCloseable {\n\n /**\n * Byte buffer\n */\n private ByteBuffer buf;\n\n /**\n * @param initSize Initial size.\n * @param order Byte order.\n */\n public ByteBufferExpander(int initSize, ByteOrder order) {\n ByteBuffer buffer = GridUnsafe.allocateBuffer(initSize);\n buffer.order(order);\n buf = buffer;\n }\n\n public ByteBuffer buffer() ", "post_mask_code": "\n\n /**\n * Expands current byte buffer to the requested size.\n *\n * @return ByteBuffer with requested size.\n */\n public ByteBuffer expand(int size) {\n assert buf.capacity() < size;\n int pos = buf.position();\n int lim = buf.limit();\n ByteBuffer newBuf = GridUnsafe.reallocateBuffer(buf, size);\n newBuf.order(buf.order());\n newBuf.position(pos);\n newBuf.limit(lim);\n buf = newBuf;\n return newBuf;\n }\n\n @Override\n public void close() {\n GridUnsafe.freeBuffer(buf);\n }\n}\n"} {"task_id": "Java_999", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/ByteBufferExpander.java", "mask_start_position": 866, "mask_end_position": 969, "canonical_solution": "\n assert buf.capacity() < size;\n int pos = buf.position();\n int lim = buf.limit();", "pre_mask_code": "package org.apache.ignite.internal.processors.cache.persistence.wal;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport org.apache.ignite.internal.util.GridUnsafe;\n\n/**\n * ByteBuffer wrapper for dynamically expand buffer size.\n */\npublic class ByteBufferExpander implements AutoCloseable {\n\n /**\n * Byte buffer\n */\n private ByteBuffer buf;\n\n /**\n * @param initSize Initial size.\n * @param order Byte order.\n */\n public ByteBufferExpander(int initSize, ByteOrder order) {\n ByteBuffer buffer = GridUnsafe.allocateBuffer(initSize);\n buffer.order(order);\n buf = buffer;\n }\n\n public ByteBuffer buffer() {\n return buf;\n }\n\n /**\n * Expands current byte buffer to the requested size.\n *\n * @return ByteBuffer with requested size.\n */\n public ByteBuffer expand(int size) {", "post_mask_code": "\n ByteBuffer newBuf = GridUnsafe.reallocateBuffer(buf, size);\n newBuf.order(buf.order());\n newBuf.position(pos);\n newBuf.limit(lim);\n buf = newBuf;\n return newBuf;\n }\n\n @Override\n public void close() {\n GridUnsafe.freeBuffer(buf);\n }\n}\n"} {"task_id": "Java_1000", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/ByteBufferExpander.java", "mask_start_position": 978, "mask_end_position": 1102, "canonical_solution": "ByteBuffer newBuf = GridUnsafe.reallocateBuffer(buf, size);\n newBuf.order(buf.order());\n newBuf.position(pos);", "pre_mask_code": "package org.apache.ignite.internal.processors.cache.persistence.wal;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport org.apache.ignite.internal.util.GridUnsafe;\n\n/**\n * ByteBuffer wrapper for dynamically expand buffer size.\n */\npublic class ByteBufferExpander implements AutoCloseable {\n\n /**\n * Byte buffer\n */\n private ByteBuffer buf;\n\n /**\n * @param initSize Initial size.\n * @param order Byte order.\n */\n public ByteBufferExpander(int initSize, ByteOrder order) {\n ByteBuffer buffer = GridUnsafe.allocateBuffer(initSize);\n buffer.order(order);\n buf = buffer;\n }\n\n public ByteBuffer buffer() {\n return buf;\n }\n\n /**\n * Expands current byte buffer to the requested size.\n *\n * @return ByteBuffer with requested size.\n */\n public ByteBuffer expand(int size) {\n assert buf.capacity() < size;\n int pos = buf.position();\n int lim = buf.limit();\n ", "post_mask_code": "\n newBuf.limit(lim);\n buf = newBuf;\n return newBuf;\n }\n\n @Override\n public void close() {\n GridUnsafe.freeBuffer(buf);\n }\n}\n"} {"task_id": "Java_1001", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/ByteBufferExpander.java", "mask_start_position": 1111, "mask_end_position": 1180, "canonical_solution": "newBuf.limit(lim);\n buf = newBuf;\n return newBuf;\n }", "pre_mask_code": "package org.apache.ignite.internal.processors.cache.persistence.wal;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport org.apache.ignite.internal.util.GridUnsafe;\n\n/**\n * ByteBuffer wrapper for dynamically expand buffer size.\n */\npublic class ByteBufferExpander implements AutoCloseable {\n\n /**\n * Byte buffer\n */\n private ByteBuffer buf;\n\n /**\n * @param initSize Initial size.\n * @param order Byte order.\n */\n public ByteBufferExpander(int initSize, ByteOrder order) {\n ByteBuffer buffer = GridUnsafe.allocateBuffer(initSize);\n buffer.order(order);\n buf = buffer;\n }\n\n public ByteBuffer buffer() {\n return buf;\n }\n\n /**\n * Expands current byte buffer to the requested size.\n *\n * @return ByteBuffer with requested size.\n */\n public ByteBuffer expand(int size) {\n assert buf.capacity() < size;\n int pos = buf.position();\n int lim = buf.limit();\n ByteBuffer newBuf = GridUnsafe.reallocateBuffer(buf, size);\n newBuf.order(buf.order());\n newBuf.position(pos);\n ", "post_mask_code": "\n\n @Override\n public void close() {\n GridUnsafe.freeBuffer(buf);\n }\n}\n"} {"task_id": "Java_1002", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/ByteBufferExpander.java", "mask_start_position": 885, "mask_end_position": 904, "canonical_solution": ".capacity() < size;", "pre_mask_code": "package org.apache.ignite.internal.processors.cache.persistence.wal;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport org.apache.ignite.internal.util.GridUnsafe;\n\n/**\n * ByteBuffer wrapper for dynamically expand buffer size.\n */\npublic class ByteBufferExpander implements AutoCloseable {\n\n /**\n * Byte buffer\n */\n private ByteBuffer buf;\n\n /**\n * @param initSize Initial size.\n * @param order Byte order.\n */\n public ByteBufferExpander(int initSize, ByteOrder order) {\n ByteBuffer buffer = GridUnsafe.allocateBuffer(initSize);\n buffer.order(order);\n buf = buffer;\n }\n\n public ByteBuffer buffer() {\n return buf;\n }\n\n /**\n * Expands current byte buffer to the requested size.\n *\n * @return ByteBuffer with requested size.\n */\n public ByteBuffer expand(int size) {\n assert buf", "post_mask_code": "\n int pos = buf.position();\n int lim = buf.limit();\n ByteBuffer newBuf = GridUnsafe.reallocateBuffer(buf, size);\n newBuf.order(buf.order());\n newBuf.position(pos);\n newBuf.limit(lim);\n buf = newBuf;\n return newBuf;\n }\n\n @Override\n public void close() {\n GridUnsafe.freeBuffer(buf);\n }\n}\n"} {"task_id": "Java_1003", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/ByteBufferExpander.java", "mask_start_position": 830, "mask_end_position": 1180, "canonical_solution": "public ByteBuffer expand(int size) {\n assert buf.capacity() < size;\n int pos = buf.position();\n int lim = buf.limit();\n ByteBuffer newBuf = GridUnsafe.reallocateBuffer(buf, size);\n newBuf.order(buf.order());\n newBuf.position(pos);\n newBuf.limit(lim);\n buf = newBuf;\n return newBuf;\n }", "pre_mask_code": "package org.apache.ignite.internal.processors.cache.persistence.wal;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport org.apache.ignite.internal.util.GridUnsafe;\n\n/**\n * ByteBuffer wrapper for dynamically expand buffer size.\n */\npublic class ByteBufferExpander implements AutoCloseable {\n\n /**\n * Byte buffer\n */\n private ByteBuffer buf;\n\n /**\n * @param initSize Initial size.\n * @param order Byte order.\n */\n public ByteBufferExpander(int initSize, ByteOrder order) {\n ByteBuffer buffer = GridUnsafe.allocateBuffer(initSize);\n buffer.order(order);\n buf = buffer;\n }\n\n public ByteBuffer buffer() {\n return buf;\n }\n\n /**\n * Expands current byte buffer to the requested size.\n *\n * @return ByteBuffer with requested size.\n */\n ", "post_mask_code": "\n\n @Override\n public void close() {\n GridUnsafe.freeBuffer(buf);\n }\n}\n"} {"task_id": "Java_1004", "language": "Java", "task_type": "empty", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/ByteBufferExpander.java", "mask_start_position": 58, "mask_end_position": 58, "canonical_solution": "", "pre_mask_code": "package org.apache.ignite.internal.processors.cache.persis", "post_mask_code": "tence.wal;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport org.apache.ignite.internal.util.GridUnsafe;\n\n/**\n * ByteBuffer wrapper for dynamically expand buffer size.\n */\npublic class ByteBufferExpander implements AutoCloseable {\n\n /**\n * Byte buffer\n */\n private ByteBuffer buf;\n\n /**\n * @param initSize Initial size.\n * @param order Byte order.\n */\n public ByteBufferExpander(int initSize, ByteOrder order) {\n ByteBuffer buffer = GridUnsafe.allocateBuffer(initSize);\n buffer.order(order);\n buf = buffer;\n }\n\n public ByteBuffer buffer() {\n return buf;\n }\n\n /**\n * Expands current byte buffer to the requested size.\n *\n * @return ByteBuffer with requested size.\n */\n public ByteBuffer expand(int size) {\n assert buf.capacity() < size;\n int pos = buf.position();\n int lim = buf.limit();\n ByteBuffer newBuf = GridUnsafe.reallocateBuffer(buf, size);\n newBuf.order(buf.order());\n newBuf.position(pos);\n newBuf.limit(lim);\n buf = newBuf;\n return newBuf;\n }\n\n @Override\n public void close() {\n GridUnsafe.freeBuffer(buf);\n }\n}\n"} {"task_id": "Java_1005", "language": "Java", "task_type": "method_signature", "source_file": "java/github/PacktPublishing/Spring-5.0-Cookbook/Chapter06/ch06/src/main/java/org/packt/functional/codes/service/impl/EmployeeDataService.java", "mask_start_position": 497, "mask_end_position": 531, "canonical_solution": "public List startList() ", "pre_mask_code": "package org.packt.functional.codes.service.impl;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\nimport org.packt.functional.codes.model.data.Employee;\nimport org.springframework.stereotype.Service;\n\n@Service(\"employeeDataService\")\npublic class EmployeeDataService {\n\n public Employee createEmployee() {\n Supplier newEmp = Employee::new;\n return newEmp.get();\n }\n\n ", "post_mask_code": "{\n Supplier> newList = ArrayList::new;\n return newList.get();\n }\n\n public Date convertBday(long bdayLong) {\n Function bday = Date::new;\n return bday.apply(bdayLong);\n }\n}\n"} {"task_id": "Java_1006", "language": "Java", "task_type": "method_body", "source_file": "java/github/PacktPublishing/Spring-5.0-Cookbook/Chapter06/ch06/src/main/java/org/packt/functional/codes/service/impl/EmployeeDataService.java", "mask_start_position": 672, "mask_end_position": 763, "canonical_solution": "{\n Function bday = Date::new;\n return bday.apply(bdayLong);\n }", "pre_mask_code": "package org.packt.functional.codes.service.impl;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\nimport org.packt.functional.codes.model.data.Employee;\nimport org.springframework.stereotype.Service;\n\n@Service(\"employeeDataService\")\npublic class EmployeeDataService {\n\n public Employee createEmployee() {\n Supplier newEmp = Employee::new;\n return newEmp.get();\n }\n\n public List startList() {\n Supplier> newList = ArrayList::new;\n return newList.get();\n }\n\n public Date convertBday(long bdayLong) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1007", "language": "Java", "task_type": "single_line", "source_file": "java/github/PacktPublishing/Spring-5.0-Cookbook/Chapter06/ch06/src/main/java/org/packt/functional/codes/service/impl/EmployeeDataService.java", "mask_start_position": 470, "mask_end_position": 485, "canonical_solution": "n newEmp.get();", "pre_mask_code": "package org.packt.functional.codes.service.impl;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\nimport org.packt.functional.codes.model.data.Employee;\nimport org.springframework.stereotype.Service;\n\n@Service(\"employeeDataService\")\npublic class EmployeeDataService {\n\n public Employee createEmployee() {\n Supplier newEmp = Employee::new;\n retur", "post_mask_code": "\n }\n\n public List startList() {\n Supplier> newList = ArrayList::new;\n return newList.get();\n }\n\n public Date convertBday(long bdayLong) {\n Function bday = Date::new;\n return bday.apply(bdayLong);\n }\n}\n"} {"task_id": "Java_1008", "language": "Java", "task_type": "empty", "source_file": "java/github/PacktPublishing/Spring-5.0-Cookbook/Chapter06/ch06/src/main/java/org/packt/functional/codes/service/impl/EmployeeDataService.java", "mask_start_position": 78, "mask_end_position": 78, "canonical_solution": "", "pre_mask_code": "package org.packt.functional.codes.service.impl;\n\nimport java.util.ArrayList;\n", "post_mask_code": "import java.util.Date;\nimport java.util.List;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\nimport org.packt.functional.codes.model.data.Employee;\nimport org.springframework.stereotype.Service;\n\n@Service(\"employeeDataService\")\npublic class EmployeeDataService {\n\n public Employee createEmployee() {\n Supplier newEmp = Employee::new;\n return newEmp.get();\n }\n\n public List startList() {\n Supplier> newList = ArrayList::new;\n return newList.get();\n }\n\n public Date convertBday(long bdayLong) {\n Function bday = Date::new;\n return bday.apply(bdayLong);\n }\n}\n"} {"task_id": "Java_1009", "language": "Java", "task_type": "method_signature", "source_file": "java/github/AingCreation/Aion-Project-5.1/AL-Game/src/com/aionemu/gameserver/dataholders/AssembledNpcsData.java", "mask_start_position": 902, "mask_end_position": 953, "canonical_solution": "void afterUnmarshal(Unmarshaller u, Object parent) ", "pre_mask_code": "/*\n * This file is part of aion-lightning \n *\n */\npackage com.aionemu.gameserver.dataholders;\n\nimport com.aionemu.gameserver.model.templates.assemblednpc.AssembledNpcTemplate;\nimport java.util.List;\nimport java.util.Map;\nimport javax.xml.bind.Unmarshaller;\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport javolution.util.FastMap;\n\n/**\n * @author xTz\n */\n@XmlRootElement(name = \"assembled_npcs\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class AssembledNpcsData {\n\n @XmlElement(name = \"assembled_npc\", type = AssembledNpcTemplate.class)\n private List templates;\n\n private final Map assembledNpcsTemplates = new FastMap().shared();\n\n ", "post_mask_code": "{\n for (AssembledNpcTemplate template : templates) {\n assembledNpcsTemplates.put(template.getNr(), template);\n }\n templates.clear();\n templates = null;\n }\n\n public int size() {\n return assembledNpcsTemplates.size();\n }\n\n public AssembledNpcTemplate getAssembledNpcTemplate(Integer i) {\n return assembledNpcsTemplates.get(i);\n }\n}\n"} {"task_id": "Java_1010", "language": "Java", "task_type": "method_body", "source_file": "java/github/AingCreation/Aion-Project-5.1/AL-Game/src/com/aionemu/gameserver/dataholders/AssembledNpcsData.java", "mask_start_position": 1173, "mask_end_position": 1226, "canonical_solution": "{\n return assembledNpcsTemplates.size();\n }", "pre_mask_code": "/*\n * This file is part of aion-lightning \n *\n */\npackage com.aionemu.gameserver.dataholders;\n\nimport com.aionemu.gameserver.model.templates.assemblednpc.AssembledNpcTemplate;\nimport java.util.List;\nimport java.util.Map;\nimport javax.xml.bind.Unmarshaller;\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport javolution.util.FastMap;\n\n/**\n * @author xTz\n */\n@XmlRootElement(name = \"assembled_npcs\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class AssembledNpcsData {\n\n @XmlElement(name = \"assembled_npc\", type = AssembledNpcTemplate.class)\n private List templates;\n\n private final Map assembledNpcsTemplates = new FastMap().shared();\n\n void afterUnmarshal(Unmarshaller u, Object parent) {\n for (AssembledNpcTemplate template : templates) {\n assembledNpcsTemplates.put(template.getNr(), template);\n }\n templates.clear();\n templates = null;\n }\n\n public int size() ", "post_mask_code": "\n\n public AssembledNpcTemplate getAssembledNpcTemplate(Integer i) {\n return assembledNpcsTemplates.get(i);\n }\n}\n"} {"task_id": "Java_1011", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/AingCreation/Aion-Project-5.1/AL-Game/src/com/aionemu/gameserver/dataholders/AssembledNpcsData.java", "mask_start_position": 954, "mask_end_position": 1090, "canonical_solution": "\n for (AssembledNpcTemplate template : templates) {\n assembledNpcsTemplates.put(template.getNr(), template);\n }", "pre_mask_code": "/*\n * This file is part of aion-lightning \n *\n */\npackage com.aionemu.gameserver.dataholders;\n\nimport com.aionemu.gameserver.model.templates.assemblednpc.AssembledNpcTemplate;\nimport java.util.List;\nimport java.util.Map;\nimport javax.xml.bind.Unmarshaller;\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport javolution.util.FastMap;\n\n/**\n * @author xTz\n */\n@XmlRootElement(name = \"assembled_npcs\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class AssembledNpcsData {\n\n @XmlElement(name = \"assembled_npc\", type = AssembledNpcTemplate.class)\n private List templates;\n\n private final Map assembledNpcsTemplates = new FastMap().shared();\n\n void afterUnmarshal(Unmarshaller u, Object parent) {", "post_mask_code": "\n templates.clear();\n templates = null;\n }\n\n public int size() {\n return assembledNpcsTemplates.size();\n }\n\n public AssembledNpcTemplate getAssembledNpcTemplate(Integer i) {\n return assembledNpcsTemplates.get(i);\n }\n}\n"} {"task_id": "Java_1012", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/AingCreation/Aion-Project-5.1/AL-Game/src/com/aionemu/gameserver/dataholders/AssembledNpcsData.java", "mask_start_position": 1099, "mask_end_position": 1117, "canonical_solution": "templates.clear();", "pre_mask_code": "/*\n * This file is part of aion-lightning \n *\n */\npackage com.aionemu.gameserver.dataholders;\n\nimport com.aionemu.gameserver.model.templates.assemblednpc.AssembledNpcTemplate;\nimport java.util.List;\nimport java.util.Map;\nimport javax.xml.bind.Unmarshaller;\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport javolution.util.FastMap;\n\n/**\n * @author xTz\n */\n@XmlRootElement(name = \"assembled_npcs\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class AssembledNpcsData {\n\n @XmlElement(name = \"assembled_npc\", type = AssembledNpcTemplate.class)\n private List templates;\n\n private final Map assembledNpcsTemplates = new FastMap().shared();\n\n void afterUnmarshal(Unmarshaller u, Object parent) {\n for (AssembledNpcTemplate template : templates) {\n assembledNpcsTemplates.put(template.getNr(), template);\n }\n ", "post_mask_code": "\n templates = null;\n }\n\n public int size() {\n return assembledNpcsTemplates.size();\n }\n\n public AssembledNpcTemplate getAssembledNpcTemplate(Integer i) {\n return assembledNpcsTemplates.get(i);\n }\n}\n"} {"task_id": "Java_1013", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/AingCreation/Aion-Project-5.1/AL-Game/src/com/aionemu/gameserver/dataholders/AssembledNpcsData.java", "mask_start_position": 1126, "mask_end_position": 1149, "canonical_solution": "templates = null;\n }", "pre_mask_code": "/*\n * This file is part of aion-lightning \n *\n */\npackage com.aionemu.gameserver.dataholders;\n\nimport com.aionemu.gameserver.model.templates.assemblednpc.AssembledNpcTemplate;\nimport java.util.List;\nimport java.util.Map;\nimport javax.xml.bind.Unmarshaller;\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport javolution.util.FastMap;\n\n/**\n * @author xTz\n */\n@XmlRootElement(name = \"assembled_npcs\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class AssembledNpcsData {\n\n @XmlElement(name = \"assembled_npc\", type = AssembledNpcTemplate.class)\n private List templates;\n\n private final Map assembledNpcsTemplates = new FastMap().shared();\n\n void afterUnmarshal(Unmarshaller u, Object parent) {\n for (AssembledNpcTemplate template : templates) {\n assembledNpcsTemplates.put(template.getNr(), template);\n }\n templates.clear();\n ", "post_mask_code": "\n\n public int size() {\n return assembledNpcsTemplates.size();\n }\n\n public AssembledNpcTemplate getAssembledNpcTemplate(Integer i) {\n return assembledNpcsTemplates.get(i);\n }\n}\n"} {"task_id": "Java_1014", "language": "Java", "task_type": "single_line", "source_file": "java/github/AingCreation/Aion-Project-5.1/AL-Game/src/com/aionemu/gameserver/dataholders/AssembledNpcsData.java", "mask_start_position": 1115, "mask_end_position": 1117, "canonical_solution": ");", "pre_mask_code": "/*\n * This file is part of aion-lightning \n *\n */\npackage com.aionemu.gameserver.dataholders;\n\nimport com.aionemu.gameserver.model.templates.assemblednpc.AssembledNpcTemplate;\nimport java.util.List;\nimport java.util.Map;\nimport javax.xml.bind.Unmarshaller;\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport javolution.util.FastMap;\n\n/**\n * @author xTz\n */\n@XmlRootElement(name = \"assembled_npcs\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class AssembledNpcsData {\n\n @XmlElement(name = \"assembled_npc\", type = AssembledNpcTemplate.class)\n private List templates;\n\n private final Map assembledNpcsTemplates = new FastMap().shared();\n\n void afterUnmarshal(Unmarshaller u, Object parent) {\n for (AssembledNpcTemplate template : templates) {\n assembledNpcsTemplates.put(template.getNr(), template);\n }\n templates.clear(", "post_mask_code": "\n templates = null;\n }\n\n public int size() {\n return assembledNpcsTemplates.size();\n }\n\n public AssembledNpcTemplate getAssembledNpcTemplate(Integer i) {\n return assembledNpcsTemplates.get(i);\n }\n}\n"} {"task_id": "Java_1015", "language": "Java", "task_type": "empty", "source_file": "java/github/AingCreation/Aion-Project-5.1/AL-Game/src/com/aionemu/gameserver/dataholders/AssembledNpcsData.java", "mask_start_position": 1242, "mask_end_position": 1242, "canonical_solution": "", "pre_mask_code": "/*\n * This file is part of aion-lightning \n *\n */\npackage com.aionemu.gameserver.dataholders;\n\nimport com.aionemu.gameserver.model.templates.assemblednpc.AssembledNpcTemplate;\nimport java.util.List;\nimport java.util.Map;\nimport javax.xml.bind.Unmarshaller;\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\nimport javolution.util.FastMap;\n\n/**\n * @author xTz\n */\n@XmlRootElement(name = \"assembled_npcs\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class AssembledNpcsData {\n\n @XmlElement(name = \"assembled_npc\", type = AssembledNpcTemplate.class)\n private List templates;\n\n private final Map assembledNpcsTemplates = new FastMap().shared();\n\n void afterUnmarshal(Unmarshaller u, Object parent) {\n for (AssembledNpcTemplate template : templates) {\n assembledNpcsTemplates.put(template.getNr(), template);\n }\n templates.clear();\n templates = null;\n }\n\n public int size() {\n return assembledNpcsTemplates.size();\n }\n\n public Ass", "post_mask_code": "embledNpcTemplate getAssembledNpcTemplate(Integer i) {\n return assembledNpcsTemplates.get(i);\n }\n}\n"} {"task_id": "Java_1016", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse/jetty.project/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/PatternRule.java", "mask_start_position": 561, "mask_end_position": 588, "canonical_solution": "public String getPattern() ", "pre_mask_code": "package org.eclipse.jetty.rewrite.handler;\n\nimport java.io.IOException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.eclipse.jetty.http.pathmap.ServletPathSpec;\n\n/**\n * Abstract rule that use a {@link ServletPathSpec} for pattern matching. It uses the\n * servlet pattern syntax.\n */\npublic abstract class PatternRule extends Rule {\n\n protected String _pattern;\n\n protected PatternRule() {\n }\n\n protected PatternRule(String pattern) {\n this();\n setPattern(pattern);\n }\n\n ", "post_mask_code": "{\n return _pattern;\n }\n\n /**\n * Sets the rule pattern.\n *\n * @param pattern the pattern\n */\n public void setPattern(String pattern) {\n _pattern = pattern;\n }\n\n @Override\n public String matchAndApply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException {\n if (ServletPathSpec.match(_pattern, target)) {\n return apply(target, request, response);\n }\n return null;\n }\n\n /**\n * Apply the rule to the request\n *\n * @param target field to attempt match\n * @param request request object\n * @param response response object\n * @return The target (possible updated)\n * @throws IOException exceptions dealing with operating on request or response objects\n */\n protected abstract String apply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException;\n\n /**\n * Returns the rule pattern.\n */\n @Override\n public String toString() {\n return super.toString() + \"[\" + _pattern + \"]\";\n }\n}\n"} {"task_id": "Java_1017", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse/jetty.project/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/PatternRule.java", "mask_start_position": 927, "mask_end_position": 1073, "canonical_solution": "{\n if (ServletPathSpec.match(_pattern, target)) {\n return apply(target, request, response);\n }\n return null;\n }", "pre_mask_code": "package org.eclipse.jetty.rewrite.handler;\n\nimport java.io.IOException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.eclipse.jetty.http.pathmap.ServletPathSpec;\n\n/**\n * Abstract rule that use a {@link ServletPathSpec} for pattern matching. It uses the\n * servlet pattern syntax.\n */\npublic abstract class PatternRule extends Rule {\n\n protected String _pattern;\n\n protected PatternRule() {\n }\n\n protected PatternRule(String pattern) {\n this();\n setPattern(pattern);\n }\n\n public String getPattern() {\n return _pattern;\n }\n\n /**\n * Sets the rule pattern.\n *\n * @param pattern the pattern\n */\n public void setPattern(String pattern) {\n _pattern = pattern;\n }\n\n @Override\n public String matchAndApply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException ", "post_mask_code": "\n\n /**\n * Apply the rule to the request\n *\n * @param target field to attempt match\n * @param request request object\n * @param response response object\n * @return The target (possible updated)\n * @throws IOException exceptions dealing with operating on request or response objects\n */\n protected abstract String apply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException;\n\n /**\n * Returns the rule pattern.\n */\n @Override\n public String toString() {\n return super.toString() + \"[\" + _pattern + \"]\";\n }\n}\n"} {"task_id": "Java_1018", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse/jetty.project/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/PatternRule.java", "mask_start_position": 1056, "mask_end_position": 1067, "canonical_solution": "eturn null;", "pre_mask_code": "package org.eclipse.jetty.rewrite.handler;\n\nimport java.io.IOException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.eclipse.jetty.http.pathmap.ServletPathSpec;\n\n/**\n * Abstract rule that use a {@link ServletPathSpec} for pattern matching. It uses the\n * servlet pattern syntax.\n */\npublic abstract class PatternRule extends Rule {\n\n protected String _pattern;\n\n protected PatternRule() {\n }\n\n protected PatternRule(String pattern) {\n this();\n setPattern(pattern);\n }\n\n public String getPattern() {\n return _pattern;\n }\n\n /**\n * Sets the rule pattern.\n *\n * @param pattern the pattern\n */\n public void setPattern(String pattern) {\n _pattern = pattern;\n }\n\n @Override\n public String matchAndApply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException {\n if (ServletPathSpec.match(_pattern, target)) {\n return apply(target, request, response);\n }\n r", "post_mask_code": "\n }\n\n /**\n * Apply the rule to the request\n *\n * @param target field to attempt match\n * @param request request object\n * @param response response object\n * @return The target (possible updated)\n * @throws IOException exceptions dealing with operating on request or response objects\n */\n protected abstract String apply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException;\n\n /**\n * Returns the rule pattern.\n */\n @Override\n public String toString() {\n return super.toString() + \"[\" + _pattern + \"]\";\n }\n}\n"} {"task_id": "Java_1019", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/eclipse/jetty.project/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/PatternRule.java", "mask_start_position": 713, "mask_end_position": 787, "canonical_solution": "public void setPattern(String pattern) {\n _pattern = pattern;\n }", "pre_mask_code": "package org.eclipse.jetty.rewrite.handler;\n\nimport java.io.IOException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.eclipse.jetty.http.pathmap.ServletPathSpec;\n\n/**\n * Abstract rule that use a {@link ServletPathSpec} for pattern matching. It uses the\n * servlet pattern syntax.\n */\npublic abstract class PatternRule extends Rule {\n\n protected String _pattern;\n\n protected PatternRule() {\n }\n\n protected PatternRule(String pattern) {\n this();\n setPattern(pattern);\n }\n\n public String getPattern() {\n return _pattern;\n }\n\n /**\n * Sets the rule pattern.\n *\n * @param pattern the pattern\n */\n ", "post_mask_code": "\n\n @Override\n public String matchAndApply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException {\n if (ServletPathSpec.match(_pattern, target)) {\n return apply(target, request, response);\n }\n return null;\n }\n\n /**\n * Apply the rule to the request\n *\n * @param target field to attempt match\n * @param request request object\n * @param response response object\n * @return The target (possible updated)\n * @throws IOException exceptions dealing with operating on request or response objects\n */\n protected abstract String apply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException;\n\n /**\n * Returns the rule pattern.\n */\n @Override\n public String toString() {\n return super.toString() + \"[\" + _pattern + \"]\";\n }\n}\n"} {"task_id": "Java_1020", "language": "Java", "task_type": "if_statement", "source_file": "java/github/eclipse/jetty.project/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/PatternRule.java", "mask_start_position": 937, "mask_end_position": 1046, "canonical_solution": "if (ServletPathSpec.match(_pattern, target)) {\n return apply(target, request, response);\n }", "pre_mask_code": "package org.eclipse.jetty.rewrite.handler;\n\nimport java.io.IOException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.eclipse.jetty.http.pathmap.ServletPathSpec;\n\n/**\n * Abstract rule that use a {@link ServletPathSpec} for pattern matching. It uses the\n * servlet pattern syntax.\n */\npublic abstract class PatternRule extends Rule {\n\n protected String _pattern;\n\n protected PatternRule() {\n }\n\n protected PatternRule(String pattern) {\n this();\n setPattern(pattern);\n }\n\n public String getPattern() {\n return _pattern;\n }\n\n /**\n * Sets the rule pattern.\n *\n * @param pattern the pattern\n */\n public void setPattern(String pattern) {\n _pattern = pattern;\n }\n\n @Override\n public String matchAndApply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException {\n ", "post_mask_code": "\n return null;\n }\n\n /**\n * Apply the rule to the request\n *\n * @param target field to attempt match\n * @param request request object\n * @param response response object\n * @return The target (possible updated)\n * @throws IOException exceptions dealing with operating on request or response objects\n */\n protected abstract String apply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException;\n\n /**\n * Returns the rule pattern.\n */\n @Override\n public String toString() {\n return super.toString() + \"[\" + _pattern + \"]\";\n }\n}\n"} {"task_id": "Java_1021", "language": "Java", "task_type": "empty", "source_file": "java/github/eclipse/jetty.project/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/PatternRule.java", "mask_start_position": 529, "mask_end_position": 529, "canonical_solution": "", "pre_mask_code": "package org.eclipse.jetty.rewrite.handler;\n\nimport java.io.IOException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.eclipse.jetty.http.pathmap.ServletPathSpec;\n\n/**\n * Abstract rule that use a {@link ServletPathSpec} for pattern matching. It uses the\n * servlet pattern syntax.\n */\npublic abstract class PatternRule extends Rule {\n\n protected String _pattern;\n\n protected PatternRule() {\n }\n\n protected PatternRule(String pattern) {\n this();\n ", "post_mask_code": "setPattern(pattern);\n }\n\n public String getPattern() {\n return _pattern;\n }\n\n /**\n * Sets the rule pattern.\n *\n * @param pattern the pattern\n */\n public void setPattern(String pattern) {\n _pattern = pattern;\n }\n\n @Override\n public String matchAndApply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException {\n if (ServletPathSpec.match(_pattern, target)) {\n return apply(target, request, response);\n }\n return null;\n }\n\n /**\n * Apply the rule to the request\n *\n * @param target field to attempt match\n * @param request request object\n * @param response response object\n * @return The target (possible updated)\n * @throws IOException exceptions dealing with operating on request or response objects\n */\n protected abstract String apply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException;\n\n /**\n * Returns the rule pattern.\n */\n @Override\n public String toString() {\n return super.toString() + \"[\" + _pattern + \"]\";\n }\n}\n"} {"task_id": "Java_1022", "language": "Java", "task_type": "method_signature", "source_file": "java/github/saket/Dank/app/src/main/java/me/saket/dank/ui/subreddit/SubredditSubmissionsAdapter.java", "mask_start_position": 5186, "mask_end_position": 5293, "canonical_solution": "@SuppressLint(\"UseSparseArrays\")\n private static void findCollidingIds(List rows) ", "pre_mask_code": "package me.saket.dank.ui.subreddit;\n\nimport android.annotation.SuppressLint;\nimport android.support.annotation.CheckResult;\nimport android.support.v7.util.DiffUtil;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.ViewGroup;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport javax.inject.Inject;\nimport io.reactivex.Observable;\nimport io.reactivex.functions.Consumer;\nimport me.saket.dank.data.SwipeEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionClickEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionThumbnailClickEvent;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel.SubmissionRowUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmission;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmissionPagination;\nimport me.saket.dank.utils.InfinitelyScrollableRecyclerViewAdapter;\nimport me.saket.dank.utils.Pair;\nimport me.saket.dank.utils.RecyclerViewArrayAdapter;\nimport me.saket.dank.walkthrough.SubmissionGestureWalkthroughProceedEvent;\nimport me.saket.dank.walkthrough.SubmissionGesturesWalkthrough;\n\npublic class SubredditSubmissionsAdapter extends RecyclerViewArrayAdapter implements Consumer, DiffUtil.DiffResult>>, InfinitelyScrollableRecyclerViewAdapter {\n\n public static final int ADAPTER_ID_PAGINATION_FOOTER = -99;\n\n public static final long ADAPTER_ID_GESTURES_WALKTHROUGH = -98;\n\n private static final SubmissionRowUiModel.Type[] VIEW_TYPES = SubmissionRowUiModel.Type.values();\n\n private final Map childAdapters;\n\n private final SubredditSubmission.Adapter submissionAdapter;\n\n private final SubredditSubmissionPagination.Adapter paginationAdapter;\n\n private final SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter;\n\n @Inject\n public SubredditSubmissionsAdapter(SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter, SubredditSubmission.Adapter submissionAdapter, SubredditSubmissionPagination.Adapter paginationAdapter) {\n childAdapters = new HashMap<>(4);\n childAdapters.put(SubmissionRowUiModel.Type.GESTURES_WALKTHROUGH, gestureWalkthroughAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.SUBMISSION, submissionAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.PAGINATION_FOOTER, paginationAdapter);\n this.gestureWalkthroughAdapter = gestureWalkthroughAdapter;\n this.paginationAdapter = paginationAdapter;\n this.submissionAdapter = submissionAdapter;\n setHasStableIds(true);\n }\n\n @CheckResult\n public Observable submissionClicks() {\n return submissionAdapter.submissionClicks();\n }\n\n @CheckResult\n public Observable gestureWalkthroughProceedClicks() {\n return gestureWalkthroughAdapter.proceedClicks();\n }\n\n @CheckResult\n public Observable thumbnailClicks() {\n return submissionAdapter.thumbnailClicks();\n }\n\n @CheckResult\n public Observable swipeEvents() {\n return submissionAdapter.swipeEvents();\n }\n\n @CheckResult\n public Observable paginationFailureRetryClicks() {\n return paginationAdapter.failureRetryClicks();\n }\n\n @Override\n public long getItemId(int position) {\n return getItem(position).adapterId();\n }\n\n @Override\n public int getItemCountMinusDecorators() {\n int itemCount = getItemCount();\n if (itemCount > 1 && getItem(itemCount - 1).type() == SubmissionRowUiModel.Type.PAGINATION_FOOTER) {\n itemCount = itemCount - 1;\n }\n return itemCount;\n }\n\n @Override\n public int getItemViewType(int position) {\n return getItem(position).type().ordinal();\n }\n\n @Override\n protected RecyclerView.ViewHolder onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) {\n return childAdapters.get(VIEW_TYPES[viewType]).onCreateViewHolder(inflater, parent);\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {\n if (payloads.isEmpty()) {\n super.onBindViewHolder(holder, position, payloads);\n } else {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position), payloads);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position));\n }\n\n @Override\n public void accept(Pair, DiffUtil.DiffResult> pair) {\n findCollidingIds(pair.first());\n updateData(pair.first());\n pair.second().dispatchUpdatesTo(this);\n }\n\n ", "post_mask_code": "{\n Map ids = new HashMap<>(rows.size(), 1f);\n for (SubmissionRowUiModel row : rows) {\n if (ids.containsKey(row.adapterId())) {\n SubmissionRowUiModel existing = ids.get(row.adapterId());\n throw new AssertionError(\"ID collision between \" + existing + \" and \" + row);\n }\n ids.put(row.adapterId(), row);\n }\n }\n}\n"} {"task_id": "Java_1023", "language": "Java", "task_type": "method_body", "source_file": "java/github/saket/Dank/app/src/main/java/me/saket/dank/ui/subreddit/SubredditSubmissionsAdapter.java", "mask_start_position": 4197, "mask_end_position": 4297, "canonical_solution": "{\n return childAdapters.get(VIEW_TYPES[viewType]).onCreateViewHolder(inflater, parent);\n }", "pre_mask_code": "package me.saket.dank.ui.subreddit;\n\nimport android.annotation.SuppressLint;\nimport android.support.annotation.CheckResult;\nimport android.support.v7.util.DiffUtil;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.ViewGroup;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport javax.inject.Inject;\nimport io.reactivex.Observable;\nimport io.reactivex.functions.Consumer;\nimport me.saket.dank.data.SwipeEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionClickEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionThumbnailClickEvent;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel.SubmissionRowUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmission;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmissionPagination;\nimport me.saket.dank.utils.InfinitelyScrollableRecyclerViewAdapter;\nimport me.saket.dank.utils.Pair;\nimport me.saket.dank.utils.RecyclerViewArrayAdapter;\nimport me.saket.dank.walkthrough.SubmissionGestureWalkthroughProceedEvent;\nimport me.saket.dank.walkthrough.SubmissionGesturesWalkthrough;\n\npublic class SubredditSubmissionsAdapter extends RecyclerViewArrayAdapter implements Consumer, DiffUtil.DiffResult>>, InfinitelyScrollableRecyclerViewAdapter {\n\n public static final int ADAPTER_ID_PAGINATION_FOOTER = -99;\n\n public static final long ADAPTER_ID_GESTURES_WALKTHROUGH = -98;\n\n private static final SubmissionRowUiModel.Type[] VIEW_TYPES = SubmissionRowUiModel.Type.values();\n\n private final Map childAdapters;\n\n private final SubredditSubmission.Adapter submissionAdapter;\n\n private final SubredditSubmissionPagination.Adapter paginationAdapter;\n\n private final SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter;\n\n @Inject\n public SubredditSubmissionsAdapter(SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter, SubredditSubmission.Adapter submissionAdapter, SubredditSubmissionPagination.Adapter paginationAdapter) {\n childAdapters = new HashMap<>(4);\n childAdapters.put(SubmissionRowUiModel.Type.GESTURES_WALKTHROUGH, gestureWalkthroughAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.SUBMISSION, submissionAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.PAGINATION_FOOTER, paginationAdapter);\n this.gestureWalkthroughAdapter = gestureWalkthroughAdapter;\n this.paginationAdapter = paginationAdapter;\n this.submissionAdapter = submissionAdapter;\n setHasStableIds(true);\n }\n\n @CheckResult\n public Observable submissionClicks() {\n return submissionAdapter.submissionClicks();\n }\n\n @CheckResult\n public Observable gestureWalkthroughProceedClicks() {\n return gestureWalkthroughAdapter.proceedClicks();\n }\n\n @CheckResult\n public Observable thumbnailClicks() {\n return submissionAdapter.thumbnailClicks();\n }\n\n @CheckResult\n public Observable swipeEvents() {\n return submissionAdapter.swipeEvents();\n }\n\n @CheckResult\n public Observable paginationFailureRetryClicks() {\n return paginationAdapter.failureRetryClicks();\n }\n\n @Override\n public long getItemId(int position) {\n return getItem(position).adapterId();\n }\n\n @Override\n public int getItemCountMinusDecorators() {\n int itemCount = getItemCount();\n if (itemCount > 1 && getItem(itemCount - 1).type() == SubmissionRowUiModel.Type.PAGINATION_FOOTER) {\n itemCount = itemCount - 1;\n }\n return itemCount;\n }\n\n @Override\n public int getItemViewType(int position) {\n return getItem(position).type().ordinal();\n }\n\n @Override\n protected RecyclerView.ViewHolder onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) ", "post_mask_code": "\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {\n if (payloads.isEmpty()) {\n super.onBindViewHolder(holder, position, payloads);\n } else {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position), payloads);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position));\n }\n\n @Override\n public void accept(Pair, DiffUtil.DiffResult> pair) {\n findCollidingIds(pair.first());\n updateData(pair.first());\n pair.second().dispatchUpdatesTo(this);\n }\n\n @SuppressLint(\"UseSparseArrays\")\n private static void findCollidingIds(List rows) {\n Map ids = new HashMap<>(rows.size(), 1f);\n for (SubmissionRowUiModel row : rows) {\n if (ids.containsKey(row.adapterId())) {\n SubmissionRowUiModel existing = ids.get(row.adapterId());\n throw new AssertionError(\"ID collision between \" + existing + \" and \" + row);\n }\n ids.put(row.adapterId(), row);\n }\n }\n}\n"} {"task_id": "Java_1024", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/saket/Dank/app/src/main/java/me/saket/dank/ui/subreddit/SubredditSubmissionsAdapter.java", "mask_start_position": 4416, "mask_end_position": 4416, "canonical_solution": "", "pre_mask_code": "package me.saket.dank.ui.subreddit;\n\nimport android.annotation.SuppressLint;\nimport android.support.annotation.CheckResult;\nimport android.support.v7.util.DiffUtil;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.ViewGroup;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport javax.inject.Inject;\nimport io.reactivex.Observable;\nimport io.reactivex.functions.Consumer;\nimport me.saket.dank.data.SwipeEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionClickEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionThumbnailClickEvent;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel.SubmissionRowUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmission;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmissionPagination;\nimport me.saket.dank.utils.InfinitelyScrollableRecyclerViewAdapter;\nimport me.saket.dank.utils.Pair;\nimport me.saket.dank.utils.RecyclerViewArrayAdapter;\nimport me.saket.dank.walkthrough.SubmissionGestureWalkthroughProceedEvent;\nimport me.saket.dank.walkthrough.SubmissionGesturesWalkthrough;\n\npublic class SubredditSubmissionsAdapter extends RecyclerViewArrayAdapter implements Consumer, DiffUtil.DiffResult>>, InfinitelyScrollableRecyclerViewAdapter {\n\n public static final int ADAPTER_ID_PAGINATION_FOOTER = -99;\n\n public static final long ADAPTER_ID_GESTURES_WALKTHROUGH = -98;\n\n private static final SubmissionRowUiModel.Type[] VIEW_TYPES = SubmissionRowUiModel.Type.values();\n\n private final Map childAdapters;\n\n private final SubredditSubmission.Adapter submissionAdapter;\n\n private final SubredditSubmissionPagination.Adapter paginationAdapter;\n\n private final SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter;\n\n @Inject\n public SubredditSubmissionsAdapter(SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter, SubredditSubmission.Adapter submissionAdapter, SubredditSubmissionPagination.Adapter paginationAdapter) {\n childAdapters = new HashMap<>(4);\n childAdapters.put(SubmissionRowUiModel.Type.GESTURES_WALKTHROUGH, gestureWalkthroughAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.SUBMISSION, submissionAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.PAGINATION_FOOTER, paginationAdapter);\n this.gestureWalkthroughAdapter = gestureWalkthroughAdapter;\n this.paginationAdapter = paginationAdapter;\n this.submissionAdapter = submissionAdapter;\n setHasStableIds(true);\n }\n\n @CheckResult\n public Observable submissionClicks() {\n return submissionAdapter.submissionClicks();\n }\n\n @CheckResult\n public Observable gestureWalkthroughProceedClicks() {\n return gestureWalkthroughAdapter.proceedClicks();\n }\n\n @CheckResult\n public Observable thumbnailClicks() {\n return submissionAdapter.thumbnailClicks();\n }\n\n @CheckResult\n public Observable swipeEvents() {\n return submissionAdapter.swipeEvents();\n }\n\n @CheckResult\n public Observable paginationFailureRetryClicks() {\n return paginationAdapter.failureRetryClicks();\n }\n\n @Override\n public long getItemId(int position) {\n return getItem(position).adapterId();\n }\n\n @Override\n public int getItemCountMinusDecorators() {\n int itemCount = getItemCount();\n if (itemCount > 1 && getItem(itemCount - 1).type() == SubmissionRowUiModel.Type.PAGINATION_FOOTER) {\n itemCount = itemCount - 1;\n }\n return itemCount;\n }\n\n @Override\n public int getItemViewType(int position) {\n return getItem(position).type().ordinal();\n }\n\n @Override\n protected RecyclerView.ViewHolder onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) {\n return childAdapters.get(VIEW_TYPES[viewType]).onCreateViewHolder(inflater, parent);\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {", "post_mask_code": "\n if (payloads.isEmpty()) {\n super.onBindViewHolder(holder, position, payloads);\n } else {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position), payloads);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position));\n }\n\n @Override\n public void accept(Pair, DiffUtil.DiffResult> pair) {\n findCollidingIds(pair.first());\n updateData(pair.first());\n pair.second().dispatchUpdatesTo(this);\n }\n\n @SuppressLint(\"UseSparseArrays\")\n private static void findCollidingIds(List rows) {\n Map ids = new HashMap<>(rows.size(), 1f);\n for (SubmissionRowUiModel row : rows) {\n if (ids.containsKey(row.adapterId())) {\n SubmissionRowUiModel existing = ids.get(row.adapterId());\n throw new AssertionError(\"ID collision between \" + existing + \" and \" + row);\n }\n ids.put(row.adapterId(), row);\n }\n }\n}\n"} {"task_id": "Java_1025", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/saket/Dank/app/src/main/java/me/saket/dank/ui/subreddit/SubredditSubmissionsAdapter.java", "mask_start_position": 4425, "mask_end_position": 4702, "canonical_solution": "if (payloads.isEmpty()) {\n super.onBindViewHolder(holder, position, payloads);\n } else {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position), payloads);\n }", "pre_mask_code": "package me.saket.dank.ui.subreddit;\n\nimport android.annotation.SuppressLint;\nimport android.support.annotation.CheckResult;\nimport android.support.v7.util.DiffUtil;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.ViewGroup;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport javax.inject.Inject;\nimport io.reactivex.Observable;\nimport io.reactivex.functions.Consumer;\nimport me.saket.dank.data.SwipeEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionClickEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionThumbnailClickEvent;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel.SubmissionRowUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmission;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmissionPagination;\nimport me.saket.dank.utils.InfinitelyScrollableRecyclerViewAdapter;\nimport me.saket.dank.utils.Pair;\nimport me.saket.dank.utils.RecyclerViewArrayAdapter;\nimport me.saket.dank.walkthrough.SubmissionGestureWalkthroughProceedEvent;\nimport me.saket.dank.walkthrough.SubmissionGesturesWalkthrough;\n\npublic class SubredditSubmissionsAdapter extends RecyclerViewArrayAdapter implements Consumer, DiffUtil.DiffResult>>, InfinitelyScrollableRecyclerViewAdapter {\n\n public static final int ADAPTER_ID_PAGINATION_FOOTER = -99;\n\n public static final long ADAPTER_ID_GESTURES_WALKTHROUGH = -98;\n\n private static final SubmissionRowUiModel.Type[] VIEW_TYPES = SubmissionRowUiModel.Type.values();\n\n private final Map childAdapters;\n\n private final SubredditSubmission.Adapter submissionAdapter;\n\n private final SubredditSubmissionPagination.Adapter paginationAdapter;\n\n private final SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter;\n\n @Inject\n public SubredditSubmissionsAdapter(SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter, SubredditSubmission.Adapter submissionAdapter, SubredditSubmissionPagination.Adapter paginationAdapter) {\n childAdapters = new HashMap<>(4);\n childAdapters.put(SubmissionRowUiModel.Type.GESTURES_WALKTHROUGH, gestureWalkthroughAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.SUBMISSION, submissionAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.PAGINATION_FOOTER, paginationAdapter);\n this.gestureWalkthroughAdapter = gestureWalkthroughAdapter;\n this.paginationAdapter = paginationAdapter;\n this.submissionAdapter = submissionAdapter;\n setHasStableIds(true);\n }\n\n @CheckResult\n public Observable submissionClicks() {\n return submissionAdapter.submissionClicks();\n }\n\n @CheckResult\n public Observable gestureWalkthroughProceedClicks() {\n return gestureWalkthroughAdapter.proceedClicks();\n }\n\n @CheckResult\n public Observable thumbnailClicks() {\n return submissionAdapter.thumbnailClicks();\n }\n\n @CheckResult\n public Observable swipeEvents() {\n return submissionAdapter.swipeEvents();\n }\n\n @CheckResult\n public Observable paginationFailureRetryClicks() {\n return paginationAdapter.failureRetryClicks();\n }\n\n @Override\n public long getItemId(int position) {\n return getItem(position).adapterId();\n }\n\n @Override\n public int getItemCountMinusDecorators() {\n int itemCount = getItemCount();\n if (itemCount > 1 && getItem(itemCount - 1).type() == SubmissionRowUiModel.Type.PAGINATION_FOOTER) {\n itemCount = itemCount - 1;\n }\n return itemCount;\n }\n\n @Override\n public int getItemViewType(int position) {\n return getItem(position).type().ordinal();\n }\n\n @Override\n protected RecyclerView.ViewHolder onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) {\n return childAdapters.get(VIEW_TYPES[viewType]).onCreateViewHolder(inflater, parent);\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {\n ", "post_mask_code": "\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position));\n }\n\n @Override\n public void accept(Pair, DiffUtil.DiffResult> pair) {\n findCollidingIds(pair.first());\n updateData(pair.first());\n pair.second().dispatchUpdatesTo(this);\n }\n\n @SuppressLint(\"UseSparseArrays\")\n private static void findCollidingIds(List rows) {\n Map ids = new HashMap<>(rows.size(), 1f);\n for (SubmissionRowUiModel row : rows) {\n if (ids.containsKey(row.adapterId())) {\n SubmissionRowUiModel existing = ids.get(row.adapterId());\n throw new AssertionError(\"ID collision between \" + existing + \" and \" + row);\n }\n ids.put(row.adapterId(), row);\n }\n }\n}\n"} {"task_id": "Java_1026", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/saket/Dank/app/src/main/java/me/saket/dank/ui/subreddit/SubredditSubmissionsAdapter.java", "mask_start_position": 4707, "mask_end_position": 4708, "canonical_solution": "}", "pre_mask_code": "package me.saket.dank.ui.subreddit;\n\nimport android.annotation.SuppressLint;\nimport android.support.annotation.CheckResult;\nimport android.support.v7.util.DiffUtil;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.ViewGroup;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport javax.inject.Inject;\nimport io.reactivex.Observable;\nimport io.reactivex.functions.Consumer;\nimport me.saket.dank.data.SwipeEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionClickEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionThumbnailClickEvent;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel.SubmissionRowUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmission;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmissionPagination;\nimport me.saket.dank.utils.InfinitelyScrollableRecyclerViewAdapter;\nimport me.saket.dank.utils.Pair;\nimport me.saket.dank.utils.RecyclerViewArrayAdapter;\nimport me.saket.dank.walkthrough.SubmissionGestureWalkthroughProceedEvent;\nimport me.saket.dank.walkthrough.SubmissionGesturesWalkthrough;\n\npublic class SubredditSubmissionsAdapter extends RecyclerViewArrayAdapter implements Consumer, DiffUtil.DiffResult>>, InfinitelyScrollableRecyclerViewAdapter {\n\n public static final int ADAPTER_ID_PAGINATION_FOOTER = -99;\n\n public static final long ADAPTER_ID_GESTURES_WALKTHROUGH = -98;\n\n private static final SubmissionRowUiModel.Type[] VIEW_TYPES = SubmissionRowUiModel.Type.values();\n\n private final Map childAdapters;\n\n private final SubredditSubmission.Adapter submissionAdapter;\n\n private final SubredditSubmissionPagination.Adapter paginationAdapter;\n\n private final SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter;\n\n @Inject\n public SubredditSubmissionsAdapter(SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter, SubredditSubmission.Adapter submissionAdapter, SubredditSubmissionPagination.Adapter paginationAdapter) {\n childAdapters = new HashMap<>(4);\n childAdapters.put(SubmissionRowUiModel.Type.GESTURES_WALKTHROUGH, gestureWalkthroughAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.SUBMISSION, submissionAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.PAGINATION_FOOTER, paginationAdapter);\n this.gestureWalkthroughAdapter = gestureWalkthroughAdapter;\n this.paginationAdapter = paginationAdapter;\n this.submissionAdapter = submissionAdapter;\n setHasStableIds(true);\n }\n\n @CheckResult\n public Observable submissionClicks() {\n return submissionAdapter.submissionClicks();\n }\n\n @CheckResult\n public Observable gestureWalkthroughProceedClicks() {\n return gestureWalkthroughAdapter.proceedClicks();\n }\n\n @CheckResult\n public Observable thumbnailClicks() {\n return submissionAdapter.thumbnailClicks();\n }\n\n @CheckResult\n public Observable swipeEvents() {\n return submissionAdapter.swipeEvents();\n }\n\n @CheckResult\n public Observable paginationFailureRetryClicks() {\n return paginationAdapter.failureRetryClicks();\n }\n\n @Override\n public long getItemId(int position) {\n return getItem(position).adapterId();\n }\n\n @Override\n public int getItemCountMinusDecorators() {\n int itemCount = getItemCount();\n if (itemCount > 1 && getItem(itemCount - 1).type() == SubmissionRowUiModel.Type.PAGINATION_FOOTER) {\n itemCount = itemCount - 1;\n }\n return itemCount;\n }\n\n @Override\n public int getItemViewType(int position) {\n return getItem(position).type().ordinal();\n }\n\n @Override\n protected RecyclerView.ViewHolder onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) {\n return childAdapters.get(VIEW_TYPES[viewType]).onCreateViewHolder(inflater, parent);\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {\n if (payloads.isEmpty()) {\n super.onBindViewHolder(holder, position, payloads);\n } else {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position), payloads);\n }\n ", "post_mask_code": "\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position));\n }\n\n @Override\n public void accept(Pair, DiffUtil.DiffResult> pair) {\n findCollidingIds(pair.first());\n updateData(pair.first());\n pair.second().dispatchUpdatesTo(this);\n }\n\n @SuppressLint(\"UseSparseArrays\")\n private static void findCollidingIds(List rows) {\n Map ids = new HashMap<>(rows.size(), 1f);\n for (SubmissionRowUiModel row : rows) {\n if (ids.containsKey(row.adapterId())) {\n SubmissionRowUiModel existing = ids.get(row.adapterId());\n throw new AssertionError(\"ID collision between \" + existing + \" and \" + row);\n }\n ids.put(row.adapterId(), row);\n }\n }\n}\n"} {"task_id": "Java_1027", "language": "Java", "task_type": "single_line", "source_file": "java/github/saket/Dank/app/src/main/java/me/saket/dank/ui/subreddit/SubredditSubmissionsAdapter.java", "mask_start_position": 3395, "mask_end_position": 3404, "canonical_solution": "Events();", "pre_mask_code": "package me.saket.dank.ui.subreddit;\n\nimport android.annotation.SuppressLint;\nimport android.support.annotation.CheckResult;\nimport android.support.v7.util.DiffUtil;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.ViewGroup;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport javax.inject.Inject;\nimport io.reactivex.Observable;\nimport io.reactivex.functions.Consumer;\nimport me.saket.dank.data.SwipeEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionClickEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionThumbnailClickEvent;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel.SubmissionRowUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmission;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmissionPagination;\nimport me.saket.dank.utils.InfinitelyScrollableRecyclerViewAdapter;\nimport me.saket.dank.utils.Pair;\nimport me.saket.dank.utils.RecyclerViewArrayAdapter;\nimport me.saket.dank.walkthrough.SubmissionGestureWalkthroughProceedEvent;\nimport me.saket.dank.walkthrough.SubmissionGesturesWalkthrough;\n\npublic class SubredditSubmissionsAdapter extends RecyclerViewArrayAdapter implements Consumer, DiffUtil.DiffResult>>, InfinitelyScrollableRecyclerViewAdapter {\n\n public static final int ADAPTER_ID_PAGINATION_FOOTER = -99;\n\n public static final long ADAPTER_ID_GESTURES_WALKTHROUGH = -98;\n\n private static final SubmissionRowUiModel.Type[] VIEW_TYPES = SubmissionRowUiModel.Type.values();\n\n private final Map childAdapters;\n\n private final SubredditSubmission.Adapter submissionAdapter;\n\n private final SubredditSubmissionPagination.Adapter paginationAdapter;\n\n private final SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter;\n\n @Inject\n public SubredditSubmissionsAdapter(SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter, SubredditSubmission.Adapter submissionAdapter, SubredditSubmissionPagination.Adapter paginationAdapter) {\n childAdapters = new HashMap<>(4);\n childAdapters.put(SubmissionRowUiModel.Type.GESTURES_WALKTHROUGH, gestureWalkthroughAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.SUBMISSION, submissionAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.PAGINATION_FOOTER, paginationAdapter);\n this.gestureWalkthroughAdapter = gestureWalkthroughAdapter;\n this.paginationAdapter = paginationAdapter;\n this.submissionAdapter = submissionAdapter;\n setHasStableIds(true);\n }\n\n @CheckResult\n public Observable submissionClicks() {\n return submissionAdapter.submissionClicks();\n }\n\n @CheckResult\n public Observable gestureWalkthroughProceedClicks() {\n return gestureWalkthroughAdapter.proceedClicks();\n }\n\n @CheckResult\n public Observable thumbnailClicks() {\n return submissionAdapter.thumbnailClicks();\n }\n\n @CheckResult\n public Observable swipeEvents() {\n return submissionAdapter.swipe", "post_mask_code": "\n }\n\n @CheckResult\n public Observable paginationFailureRetryClicks() {\n return paginationAdapter.failureRetryClicks();\n }\n\n @Override\n public long getItemId(int position) {\n return getItem(position).adapterId();\n }\n\n @Override\n public int getItemCountMinusDecorators() {\n int itemCount = getItemCount();\n if (itemCount > 1 && getItem(itemCount - 1).type() == SubmissionRowUiModel.Type.PAGINATION_FOOTER) {\n itemCount = itemCount - 1;\n }\n return itemCount;\n }\n\n @Override\n public int getItemViewType(int position) {\n return getItem(position).type().ordinal();\n }\n\n @Override\n protected RecyclerView.ViewHolder onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) {\n return childAdapters.get(VIEW_TYPES[viewType]).onCreateViewHolder(inflater, parent);\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {\n if (payloads.isEmpty()) {\n super.onBindViewHolder(holder, position, payloads);\n } else {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position), payloads);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position));\n }\n\n @Override\n public void accept(Pair, DiffUtil.DiffResult> pair) {\n findCollidingIds(pair.first());\n updateData(pair.first());\n pair.second().dispatchUpdatesTo(this);\n }\n\n @SuppressLint(\"UseSparseArrays\")\n private static void findCollidingIds(List rows) {\n Map ids = new HashMap<>(rows.size(), 1f);\n for (SubmissionRowUiModel row : rows) {\n if (ids.containsKey(row.adapterId())) {\n SubmissionRowUiModel existing = ids.get(row.adapterId());\n throw new AssertionError(\"ID collision between \" + existing + \" and \" + row);\n }\n ids.put(row.adapterId(), row);\n }\n }\n}\n"} {"task_id": "Java_1028", "language": "Java", "task_type": "if_statement", "source_file": "java/github/saket/Dank/app/src/main/java/me/saket/dank/ui/subreddit/SubredditSubmissionsAdapter.java", "mask_start_position": 5433, "mask_end_position": 5654, "canonical_solution": "if (ids.containsKey(row.adapterId())) {\n SubmissionRowUiModel existing = ids.get(row.adapterId());\n throw new AssertionError(\"ID collision between \" + existing + \" and \" + row);\n }", "pre_mask_code": "package me.saket.dank.ui.subreddit;\n\nimport android.annotation.SuppressLint;\nimport android.support.annotation.CheckResult;\nimport android.support.v7.util.DiffUtil;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.ViewGroup;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport javax.inject.Inject;\nimport io.reactivex.Observable;\nimport io.reactivex.functions.Consumer;\nimport me.saket.dank.data.SwipeEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionClickEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionThumbnailClickEvent;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel.SubmissionRowUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmission;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmissionPagination;\nimport me.saket.dank.utils.InfinitelyScrollableRecyclerViewAdapter;\nimport me.saket.dank.utils.Pair;\nimport me.saket.dank.utils.RecyclerViewArrayAdapter;\nimport me.saket.dank.walkthrough.SubmissionGestureWalkthroughProceedEvent;\nimport me.saket.dank.walkthrough.SubmissionGesturesWalkthrough;\n\npublic class SubredditSubmissionsAdapter extends RecyclerViewArrayAdapter implements Consumer, DiffUtil.DiffResult>>, InfinitelyScrollableRecyclerViewAdapter {\n\n public static final int ADAPTER_ID_PAGINATION_FOOTER = -99;\n\n public static final long ADAPTER_ID_GESTURES_WALKTHROUGH = -98;\n\n private static final SubmissionRowUiModel.Type[] VIEW_TYPES = SubmissionRowUiModel.Type.values();\n\n private final Map childAdapters;\n\n private final SubredditSubmission.Adapter submissionAdapter;\n\n private final SubredditSubmissionPagination.Adapter paginationAdapter;\n\n private final SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter;\n\n @Inject\n public SubredditSubmissionsAdapter(SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter, SubredditSubmission.Adapter submissionAdapter, SubredditSubmissionPagination.Adapter paginationAdapter) {\n childAdapters = new HashMap<>(4);\n childAdapters.put(SubmissionRowUiModel.Type.GESTURES_WALKTHROUGH, gestureWalkthroughAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.SUBMISSION, submissionAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.PAGINATION_FOOTER, paginationAdapter);\n this.gestureWalkthroughAdapter = gestureWalkthroughAdapter;\n this.paginationAdapter = paginationAdapter;\n this.submissionAdapter = submissionAdapter;\n setHasStableIds(true);\n }\n\n @CheckResult\n public Observable submissionClicks() {\n return submissionAdapter.submissionClicks();\n }\n\n @CheckResult\n public Observable gestureWalkthroughProceedClicks() {\n return gestureWalkthroughAdapter.proceedClicks();\n }\n\n @CheckResult\n public Observable thumbnailClicks() {\n return submissionAdapter.thumbnailClicks();\n }\n\n @CheckResult\n public Observable swipeEvents() {\n return submissionAdapter.swipeEvents();\n }\n\n @CheckResult\n public Observable paginationFailureRetryClicks() {\n return paginationAdapter.failureRetryClicks();\n }\n\n @Override\n public long getItemId(int position) {\n return getItem(position).adapterId();\n }\n\n @Override\n public int getItemCountMinusDecorators() {\n int itemCount = getItemCount();\n if (itemCount > 1 && getItem(itemCount - 1).type() == SubmissionRowUiModel.Type.PAGINATION_FOOTER) {\n itemCount = itemCount - 1;\n }\n return itemCount;\n }\n\n @Override\n public int getItemViewType(int position) {\n return getItem(position).type().ordinal();\n }\n\n @Override\n protected RecyclerView.ViewHolder onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) {\n return childAdapters.get(VIEW_TYPES[viewType]).onCreateViewHolder(inflater, parent);\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {\n if (payloads.isEmpty()) {\n super.onBindViewHolder(holder, position, payloads);\n } else {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position), payloads);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position));\n }\n\n @Override\n public void accept(Pair, DiffUtil.DiffResult> pair) {\n findCollidingIds(pair.first());\n updateData(pair.first());\n pair.second().dispatchUpdatesTo(this);\n }\n\n @SuppressLint(\"UseSparseArrays\")\n private static void findCollidingIds(List rows) {\n Map ids = new HashMap<>(rows.size(), 1f);\n for (SubmissionRowUiModel row : rows) {\n ", "post_mask_code": "\n ids.put(row.adapterId(), row);\n }\n }\n}\n"} {"task_id": "Java_1029", "language": "Java", "task_type": "empty", "source_file": "java/github/saket/Dank/app/src/main/java/me/saket/dank/ui/subreddit/SubredditSubmissionsAdapter.java", "mask_start_position": 5162, "mask_end_position": 5162, "canonical_solution": "", "pre_mask_code": "package me.saket.dank.ui.subreddit;\n\nimport android.annotation.SuppressLint;\nimport android.support.annotation.CheckResult;\nimport android.support.v7.util.DiffUtil;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.ViewGroup;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport javax.inject.Inject;\nimport io.reactivex.Observable;\nimport io.reactivex.functions.Consumer;\nimport me.saket.dank.data.SwipeEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionClickEvent;\nimport me.saket.dank.ui.subreddit.events.SubredditSubmissionThumbnailClickEvent;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditScreenUiModel.SubmissionRowUiModel;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmission;\nimport me.saket.dank.ui.subreddit.uimodels.SubredditSubmissionPagination;\nimport me.saket.dank.utils.InfinitelyScrollableRecyclerViewAdapter;\nimport me.saket.dank.utils.Pair;\nimport me.saket.dank.utils.RecyclerViewArrayAdapter;\nimport me.saket.dank.walkthrough.SubmissionGestureWalkthroughProceedEvent;\nimport me.saket.dank.walkthrough.SubmissionGesturesWalkthrough;\n\npublic class SubredditSubmissionsAdapter extends RecyclerViewArrayAdapter implements Consumer, DiffUtil.DiffResult>>, InfinitelyScrollableRecyclerViewAdapter {\n\n public static final int ADAPTER_ID_PAGINATION_FOOTER = -99;\n\n public static final long ADAPTER_ID_GESTURES_WALKTHROUGH = -98;\n\n private static final SubmissionRowUiModel.Type[] VIEW_TYPES = SubmissionRowUiModel.Type.values();\n\n private final Map childAdapters;\n\n private final SubredditSubmission.Adapter submissionAdapter;\n\n private final SubredditSubmissionPagination.Adapter paginationAdapter;\n\n private final SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter;\n\n @Inject\n public SubredditSubmissionsAdapter(SubmissionGesturesWalkthrough.Adapter gestureWalkthroughAdapter, SubredditSubmission.Adapter submissionAdapter, SubredditSubmissionPagination.Adapter paginationAdapter) {\n childAdapters = new HashMap<>(4);\n childAdapters.put(SubmissionRowUiModel.Type.GESTURES_WALKTHROUGH, gestureWalkthroughAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.SUBMISSION, submissionAdapter);\n childAdapters.put(SubmissionRowUiModel.Type.PAGINATION_FOOTER, paginationAdapter);\n this.gestureWalkthroughAdapter = gestureWalkthroughAdapter;\n this.paginationAdapter = paginationAdapter;\n this.submissionAdapter = submissionAdapter;\n setHasStableIds(true);\n }\n\n @CheckResult\n public Observable submissionClicks() {\n return submissionAdapter.submissionClicks();\n }\n\n @CheckResult\n public Observable gestureWalkthroughProceedClicks() {\n return gestureWalkthroughAdapter.proceedClicks();\n }\n\n @CheckResult\n public Observable thumbnailClicks() {\n return submissionAdapter.thumbnailClicks();\n }\n\n @CheckResult\n public Observable swipeEvents() {\n return submissionAdapter.swipeEvents();\n }\n\n @CheckResult\n public Observable paginationFailureRetryClicks() {\n return paginationAdapter.failureRetryClicks();\n }\n\n @Override\n public long getItemId(int position) {\n return getItem(position).adapterId();\n }\n\n @Override\n public int getItemCountMinusDecorators() {\n int itemCount = getItemCount();\n if (itemCount > 1 && getItem(itemCount - 1).type() == SubmissionRowUiModel.Type.PAGINATION_FOOTER) {\n itemCount = itemCount - 1;\n }\n return itemCount;\n }\n\n @Override\n public int getItemViewType(int position) {\n return getItem(position).type().ordinal();\n }\n\n @Override\n protected RecyclerView.ViewHolder onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) {\n return childAdapters.get(VIEW_TYPES[viewType]).onCreateViewHolder(inflater, parent);\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {\n if (payloads.isEmpty()) {\n super.onBindViewHolder(holder, position, payloads);\n } else {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position), payloads);\n }\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n // noinspection unchecked\n childAdapters.get(VIEW_TYPES[holder.getItemViewType()]).onBindViewHolder(holder, getItem(position));\n }\n\n @Override\n public void accept(Pair, DiffUtil.DiffResult> pair) {\n findCollidingIds(pair.first());\n updateData(pair.first());\n pair.second().dispatchUpda", "post_mask_code": "tesTo(this);\n }\n\n @SuppressLint(\"UseSparseArrays\")\n private static void findCollidingIds(List rows) {\n Map ids = new HashMap<>(rows.size(), 1f);\n for (SubmissionRowUiModel row : rows) {\n if (ids.containsKey(row.adapterId())) {\n SubmissionRowUiModel existing = ids.get(row.adapterId());\n throw new AssertionError(\"ID collision between \" + existing + \" and \" + row);\n }\n ids.put(row.adapterId(), row);\n }\n }\n}\n"} {"task_id": "Java_1030", "language": "Java", "task_type": "method_signature", "source_file": "java/github/JetBrains/jdk8u_jdk/src/share/classes/javax/swing/Popup.java", "mask_start_position": 3483, "mask_end_position": 3539, "canonical_solution": "@SuppressWarnings(\"deprecation\")\n public void hide() ", "pre_mask_code": "package javax.swing;\n\nimport java.awt.*;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport sun.awt.ModalExclude;\nimport sun.awt.SunToolkit;\n\n/**\n * Popups are used to display a Component to the user, typically\n * on top of all the other Components in a particular containment\n * hierarchy. Popups have a very small life cycle. Once you\n * have obtained a Popup, and hidden it (invoked the\n * hide method), you should no longer\n * invoke any methods on it. This allows the PopupFactory to cache\n * Popups for later use.\n *

\n * The general contract is that if you need to change the size of the\n * Component, or location of the Popup, you should\n * obtain a new Popup.\n *

\n * Popup does not descend from Component, rather\n * implementations of Popup are responsible for creating\n * and maintaining their own Components to render the\n * requested Component to the user.\n *

\n * You typically do not explicitly create an instance of Popup,\n * instead obtain one from a PopupFactory.\n *\n * @see PopupFactory\n *\n * @since 1.4\n */\npublic class Popup {\n\n /**\n * The Component representing the Popup.\n */\n private Component component;\n\n /**\n * Creates a Popup for the Component owner\n * containing the Component contents. owner\n * is used to determine which Window the new\n * Popup will parent the Component the\n * Popup creates to.\n * A null owner implies there is no valid parent.\n * x and\n * y specify the preferred initial location to place\n * the Popup at. Based on screen size, or other paramaters,\n * the Popup may not display at x and\n * y.\n *\n * @param owner Component mouse coordinates are relative to, may be null\n * @param contents Contents of the Popup\n * @param x Initial x screen coordinate\n * @param y Initial y screen coordinate\n * @exception IllegalArgumentException if contents is null\n */\n protected Popup(Component owner, Component contents, int x, int y) {\n this();\n if (contents == null) {\n throw new IllegalArgumentException(\"Contents must be non-null\");\n }\n reset(owner, contents, x, y);\n }\n\n /**\n * Creates a Popup. This is provided for subclasses.\n */\n protected Popup() {\n }\n\n /**\n * Makes the Popup visible. If the Popup is\n * currently visible, this has no effect.\n */\n @SuppressWarnings(\"deprecation\")\n public void show() {\n Component component = getComponent();\n if (component != null) {\n component.show();\n }\n }\n\n /**\n * Hides and disposes of the Popup. Once a Popup\n * has been disposed you should no longer invoke methods on it. A\n * disposed Popup may be reclaimed and later used\n * based on the PopupFactory. As such, if you invoke methods\n * on a disposed Popup, indeterminate\n * behavior will result.\n */\n ", "post_mask_code": "{\n Component component = getComponent();\n if (component instanceof JWindow) {\n component.hide();\n ((JWindow) component).getContentPane().removeAll();\n }\n dispose();\n }\n\n /**\n * Frees any resources the Popup may be holding onto.\n */\n void dispose() {\n Component component = getComponent();\n Window window = SwingUtilities.getWindowAncestor(component);\n if (component instanceof JWindow) {\n ((Window) component).dispose();\n component = null;\n }\n // If our parent is a DefaultFrame, we need to dispose it, too.\n if (window instanceof DefaultFrame) {\n window.dispose();\n }\n }\n\n /**\n * Resets the Popup to an initial state.\n */\n void reset(Component owner, Component contents, int ownerX, int ownerY) {\n if (getComponent() == null) {\n component = createComponent(owner);\n }\n Component c = getComponent();\n if (c instanceof JWindow) {\n JWindow component = (JWindow) getComponent();\n component.setLocation(ownerX, ownerY);\n component.getContentPane().add(contents, BorderLayout.CENTER);\n component.invalidate();\n component.validate();\n if (component.isVisible()) {\n // Do not call pack() if window is not visible to\n // avoid early native peer creation\n pack();\n }\n }\n }\n\n /**\n * Causes the Popup to be sized to fit the preferred size\n * of the Component it contains.\n */\n void pack() {\n Component component = getComponent();\n if (component instanceof Window) {\n ((Window) component).pack();\n }\n }\n\n /**\n * Returns the Window to use as the parent of the\n * Window created for the Popup. This creates\n * a new DefaultFrame, if necessary.\n */\n private Window getParentWindow(Component owner) {\n Window window = null;\n if (owner instanceof Window) {\n window = (Window) owner;\n } else if (owner != null) {\n window = SwingUtilities.getWindowAncestor(owner);\n }\n if (window == null) {\n window = new DefaultFrame();\n }\n return window;\n }\n\n /**\n * Creates the Component to use as the parent of the Popup.\n * The default implementation creates a Window, subclasses\n * should override.\n */\n Component createComponent(Component owner) {\n if (GraphicsEnvironment.isHeadless()) {\n // Generally not useful, bail.\n return null;\n }\n return new HeavyWeightWindow(getParentWindow(owner));\n }\n\n /**\n * Returns the Component returned from\n * createComponent that will hold the Popup.\n */\n Component getComponent() {\n return component;\n }\n\n /**\n * Component used to house window.\n */\n static class HeavyWeightWindow extends JWindow implements ModalExclude {\n\n HeavyWeightWindow(Window parent) {\n super(parent);\n setFocusableWindowState(false);\n if (AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(\"jbre.popupwindow.settype\") != null)) {\n setType(Window.Type.POPUP);\n }\n // Popups are typically transient and most likely won't benefit\n // from true double buffering. Turn it off here.\n getRootPane().setUseTrueDoubleBuffering(false);\n // Try to set \"always-on-top\" for the popup window.\n // Applets usually don't have sufficient permissions to do it.\n // In this case simply ignore the exception.\n try {\n setAlwaysOnTop(true);\n } catch (SecurityException se) {\n // setAlwaysOnTop is restricted,\n // the exception is ignored\n }\n }\n\n public void update(Graphics g) {\n paint(g);\n }\n\n public void show() {\n this.pack();\n if (getWidth() > 0 && getHeight() > 0) {\n super.show();\n }\n }\n }\n\n /**\n * Used if no valid Window ancestor of the supplied owner is found.\n *

\n * PopupFactory uses this as a way to know when the Popup shouldn't\n * be cached based on the Window.\n */\n static class DefaultFrame extends Frame {\n }\n}\n"} {"task_id": "Java_1031", "language": "Java", "task_type": "method_body", "source_file": "java/github/JetBrains/jdk8u_jdk/src/share/classes/javax/swing/Popup.java", "mask_start_position": 5638, "mask_end_position": 5963, "canonical_solution": "{\n Window window = null;\n if (owner instanceof Window) {\n window = (Window) owner;\n } else if (owner != null) {\n window = SwingUtilities.getWindowAncestor(owner);\n }\n if (window == null) {\n window = new DefaultFrame();\n }\n return window;\n }", "pre_mask_code": "package javax.swing;\n\nimport java.awt.*;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport sun.awt.ModalExclude;\nimport sun.awt.SunToolkit;\n\n/**\n * Popups are used to display a Component to the user, typically\n * on top of all the other Components in a particular containment\n * hierarchy. Popups have a very small life cycle. Once you\n * have obtained a Popup, and hidden it (invoked the\n * hide method), you should no longer\n * invoke any methods on it. This allows the PopupFactory to cache\n * Popups for later use.\n *

\n * The general contract is that if you need to change the size of the\n * Component, or location of the Popup, you should\n * obtain a new Popup.\n *

\n * Popup does not descend from Component, rather\n * implementations of Popup are responsible for creating\n * and maintaining their own Components to render the\n * requested Component to the user.\n *

\n * You typically do not explicitly create an instance of Popup,\n * instead obtain one from a PopupFactory.\n *\n * @see PopupFactory\n *\n * @since 1.4\n */\npublic class Popup {\n\n /**\n * The Component representing the Popup.\n */\n private Component component;\n\n /**\n * Creates a Popup for the Component owner\n * containing the Component contents. owner\n * is used to determine which Window the new\n * Popup will parent the Component the\n * Popup creates to.\n * A null owner implies there is no valid parent.\n * x and\n * y specify the preferred initial location to place\n * the Popup at. Based on screen size, or other paramaters,\n * the Popup may not display at x and\n * y.\n *\n * @param owner Component mouse coordinates are relative to, may be null\n * @param contents Contents of the Popup\n * @param x Initial x screen coordinate\n * @param y Initial y screen coordinate\n * @exception IllegalArgumentException if contents is null\n */\n protected Popup(Component owner, Component contents, int x, int y) {\n this();\n if (contents == null) {\n throw new IllegalArgumentException(\"Contents must be non-null\");\n }\n reset(owner, contents, x, y);\n }\n\n /**\n * Creates a Popup. This is provided for subclasses.\n */\n protected Popup() {\n }\n\n /**\n * Makes the Popup visible. If the Popup is\n * currently visible, this has no effect.\n */\n @SuppressWarnings(\"deprecation\")\n public void show() {\n Component component = getComponent();\n if (component != null) {\n component.show();\n }\n }\n\n /**\n * Hides and disposes of the Popup. Once a Popup\n * has been disposed you should no longer invoke methods on it. A\n * disposed Popup may be reclaimed and later used\n * based on the PopupFactory. As such, if you invoke methods\n * on a disposed Popup, indeterminate\n * behavior will result.\n */\n @SuppressWarnings(\"deprecation\")\n public void hide() {\n Component component = getComponent();\n if (component instanceof JWindow) {\n component.hide();\n ((JWindow) component).getContentPane().removeAll();\n }\n dispose();\n }\n\n /**\n * Frees any resources the Popup may be holding onto.\n */\n void dispose() {\n Component component = getComponent();\n Window window = SwingUtilities.getWindowAncestor(component);\n if (component instanceof JWindow) {\n ((Window) component).dispose();\n component = null;\n }\n // If our parent is a DefaultFrame, we need to dispose it, too.\n if (window instanceof DefaultFrame) {\n window.dispose();\n }\n }\n\n /**\n * Resets the Popup to an initial state.\n */\n void reset(Component owner, Component contents, int ownerX, int ownerY) {\n if (getComponent() == null) {\n component = createComponent(owner);\n }\n Component c = getComponent();\n if (c instanceof JWindow) {\n JWindow component = (JWindow) getComponent();\n component.setLocation(ownerX, ownerY);\n component.getContentPane().add(contents, BorderLayout.CENTER);\n component.invalidate();\n component.validate();\n if (component.isVisible()) {\n // Do not call pack() if window is not visible to\n // avoid early native peer creation\n pack();\n }\n }\n }\n\n /**\n * Causes the Popup to be sized to fit the preferred size\n * of the Component it contains.\n */\n void pack() {\n Component component = getComponent();\n if (component instanceof Window) {\n ((Window) component).pack();\n }\n }\n\n /**\n * Returns the Window to use as the parent of the\n * Window created for the Popup. This creates\n * a new DefaultFrame, if necessary.\n */\n private Window getParentWindow(Component owner) ", "post_mask_code": "\n\n /**\n * Creates the Component to use as the parent of the Popup.\n * The default implementation creates a Window, subclasses\n * should override.\n */\n Component createComponent(Component owner) {\n if (GraphicsEnvironment.isHeadless()) {\n // Generally not useful, bail.\n return null;\n }\n return new HeavyWeightWindow(getParentWindow(owner));\n }\n\n /**\n * Returns the Component returned from\n * createComponent that will hold the Popup.\n */\n Component getComponent() {\n return component;\n }\n\n /**\n * Component used to house window.\n */\n static class HeavyWeightWindow extends JWindow implements ModalExclude {\n\n HeavyWeightWindow(Window parent) {\n super(parent);\n setFocusableWindowState(false);\n if (AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(\"jbre.popupwindow.settype\") != null)) {\n setType(Window.Type.POPUP);\n }\n // Popups are typically transient and most likely won't benefit\n // from true double buffering. Turn it off here.\n getRootPane().setUseTrueDoubleBuffering(false);\n // Try to set \"always-on-top\" for the popup window.\n // Applets usually don't have sufficient permissions to do it.\n // In this case simply ignore the exception.\n try {\n setAlwaysOnTop(true);\n } catch (SecurityException se) {\n // setAlwaysOnTop is restricted,\n // the exception is ignored\n }\n }\n\n public void update(Graphics g) {\n paint(g);\n }\n\n public void show() {\n this.pack();\n if (getWidth() > 0 && getHeight() > 0) {\n super.show();\n }\n }\n }\n\n /**\n * Used if no valid Window ancestor of the supplied owner is found.\n *

\n * PopupFactory uses this as a way to know when the Popup shouldn't\n * be cached based on the Window.\n */\n static class DefaultFrame extends Frame {\n }\n}\n"} {"task_id": "Java_1032", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/JetBrains/jdk8u_jdk/src/share/classes/javax/swing/Popup.java", "mask_start_position": 6206, "mask_end_position": 6332, "canonical_solution": "\n if (GraphicsEnvironment.isHeadless()) {\n // Generally not useful, bail.\n return null;\n }", "pre_mask_code": "package javax.swing;\n\nimport java.awt.*;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport sun.awt.ModalExclude;\nimport sun.awt.SunToolkit;\n\n/**\n * Popups are used to display a Component to the user, typically\n * on top of all the other Components in a particular containment\n * hierarchy. Popups have a very small life cycle. Once you\n * have obtained a Popup, and hidden it (invoked the\n * hide method), you should no longer\n * invoke any methods on it. This allows the PopupFactory to cache\n * Popups for later use.\n *

\n * The general contract is that if you need to change the size of the\n * Component, or location of the Popup, you should\n * obtain a new Popup.\n *

\n * Popup does not descend from Component, rather\n * implementations of Popup are responsible for creating\n * and maintaining their own Components to render the\n * requested Component to the user.\n *

\n * You typically do not explicitly create an instance of Popup,\n * instead obtain one from a PopupFactory.\n *\n * @see PopupFactory\n *\n * @since 1.4\n */\npublic class Popup {\n\n /**\n * The Component representing the Popup.\n */\n private Component component;\n\n /**\n * Creates a Popup for the Component owner\n * containing the Component contents. owner\n * is used to determine which Window the new\n * Popup will parent the Component the\n * Popup creates to.\n * A null owner implies there is no valid parent.\n * x and\n * y specify the preferred initial location to place\n * the Popup at. Based on screen size, or other paramaters,\n * the Popup may not display at x and\n * y.\n *\n * @param owner Component mouse coordinates are relative to, may be null\n * @param contents Contents of the Popup\n * @param x Initial x screen coordinate\n * @param y Initial y screen coordinate\n * @exception IllegalArgumentException if contents is null\n */\n protected Popup(Component owner, Component contents, int x, int y) {\n this();\n if (contents == null) {\n throw new IllegalArgumentException(\"Contents must be non-null\");\n }\n reset(owner, contents, x, y);\n }\n\n /**\n * Creates a Popup. This is provided for subclasses.\n */\n protected Popup() {\n }\n\n /**\n * Makes the Popup visible. If the Popup is\n * currently visible, this has no effect.\n */\n @SuppressWarnings(\"deprecation\")\n public void show() {\n Component component = getComponent();\n if (component != null) {\n component.show();\n }\n }\n\n /**\n * Hides and disposes of the Popup. Once a Popup\n * has been disposed you should no longer invoke methods on it. A\n * disposed Popup may be reclaimed and later used\n * based on the PopupFactory. As such, if you invoke methods\n * on a disposed Popup, indeterminate\n * behavior will result.\n */\n @SuppressWarnings(\"deprecation\")\n public void hide() {\n Component component = getComponent();\n if (component instanceof JWindow) {\n component.hide();\n ((JWindow) component).getContentPane().removeAll();\n }\n dispose();\n }\n\n /**\n * Frees any resources the Popup may be holding onto.\n */\n void dispose() {\n Component component = getComponent();\n Window window = SwingUtilities.getWindowAncestor(component);\n if (component instanceof JWindow) {\n ((Window) component).dispose();\n component = null;\n }\n // If our parent is a DefaultFrame, we need to dispose it, too.\n if (window instanceof DefaultFrame) {\n window.dispose();\n }\n }\n\n /**\n * Resets the Popup to an initial state.\n */\n void reset(Component owner, Component contents, int ownerX, int ownerY) {\n if (getComponent() == null) {\n component = createComponent(owner);\n }\n Component c = getComponent();\n if (c instanceof JWindow) {\n JWindow component = (JWindow) getComponent();\n component.setLocation(ownerX, ownerY);\n component.getContentPane().add(contents, BorderLayout.CENTER);\n component.invalidate();\n component.validate();\n if (component.isVisible()) {\n // Do not call pack() if window is not visible to\n // avoid early native peer creation\n pack();\n }\n }\n }\n\n /**\n * Causes the Popup to be sized to fit the preferred size\n * of the Component it contains.\n */\n void pack() {\n Component component = getComponent();\n if (component instanceof Window) {\n ((Window) component).pack();\n }\n }\n\n /**\n * Returns the Window to use as the parent of the\n * Window created for the Popup. This creates\n * a new DefaultFrame, if necessary.\n */\n private Window getParentWindow(Component owner) {\n Window window = null;\n if (owner instanceof Window) {\n window = (Window) owner;\n } else if (owner != null) {\n window = SwingUtilities.getWindowAncestor(owner);\n }\n if (window == null) {\n window = new DefaultFrame();\n }\n return window;\n }\n\n /**\n * Creates the Component to use as the parent of the Popup.\n * The default implementation creates a Window, subclasses\n * should override.\n */\n Component createComponent(Component owner) {", "post_mask_code": "\n return new HeavyWeightWindow(getParentWindow(owner));\n }\n\n /**\n * Returns the Component returned from\n * createComponent that will hold the Popup.\n */\n Component getComponent() {\n return component;\n }\n\n /**\n * Component used to house window.\n */\n static class HeavyWeightWindow extends JWindow implements ModalExclude {\n\n HeavyWeightWindow(Window parent) {\n super(parent);\n setFocusableWindowState(false);\n if (AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(\"jbre.popupwindow.settype\") != null)) {\n setType(Window.Type.POPUP);\n }\n // Popups are typically transient and most likely won't benefit\n // from true double buffering. Turn it off here.\n getRootPane().setUseTrueDoubleBuffering(false);\n // Try to set \"always-on-top\" for the popup window.\n // Applets usually don't have sufficient permissions to do it.\n // In this case simply ignore the exception.\n try {\n setAlwaysOnTop(true);\n } catch (SecurityException se) {\n // setAlwaysOnTop is restricted,\n // the exception is ignored\n }\n }\n\n public void update(Graphics g) {\n paint(g);\n }\n\n public void show() {\n this.pack();\n if (getWidth() > 0 && getHeight() > 0) {\n super.show();\n }\n }\n }\n\n /**\n * Used if no valid Window ancestor of the supplied owner is found.\n *

\n * PopupFactory uses this as a way to know when the Popup shouldn't\n * be cached based on the Window.\n */\n static class DefaultFrame extends Frame {\n }\n}\n"} {"task_id": "Java_1033", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/JetBrains/jdk8u_jdk/src/share/classes/javax/swing/Popup.java", "mask_start_position": 6341, "mask_end_position": 6394, "canonical_solution": "return new HeavyWeightWindow(getParentWindow(owner));", "pre_mask_code": "package javax.swing;\n\nimport java.awt.*;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport sun.awt.ModalExclude;\nimport sun.awt.SunToolkit;\n\n/**\n * Popups are used to display a Component to the user, typically\n * on top of all the other Components in a particular containment\n * hierarchy. Popups have a very small life cycle. Once you\n * have obtained a Popup, and hidden it (invoked the\n * hide method), you should no longer\n * invoke any methods on it. This allows the PopupFactory to cache\n * Popups for later use.\n *

\n * The general contract is that if you need to change the size of the\n * Component, or location of the Popup, you should\n * obtain a new Popup.\n *

\n * Popup does not descend from Component, rather\n * implementations of Popup are responsible for creating\n * and maintaining their own Components to render the\n * requested Component to the user.\n *

\n * You typically do not explicitly create an instance of Popup,\n * instead obtain one from a PopupFactory.\n *\n * @see PopupFactory\n *\n * @since 1.4\n */\npublic class Popup {\n\n /**\n * The Component representing the Popup.\n */\n private Component component;\n\n /**\n * Creates a Popup for the Component owner\n * containing the Component contents. owner\n * is used to determine which Window the new\n * Popup will parent the Component the\n * Popup creates to.\n * A null owner implies there is no valid parent.\n * x and\n * y specify the preferred initial location to place\n * the Popup at. Based on screen size, or other paramaters,\n * the Popup may not display at x and\n * y.\n *\n * @param owner Component mouse coordinates are relative to, may be null\n * @param contents Contents of the Popup\n * @param x Initial x screen coordinate\n * @param y Initial y screen coordinate\n * @exception IllegalArgumentException if contents is null\n */\n protected Popup(Component owner, Component contents, int x, int y) {\n this();\n if (contents == null) {\n throw new IllegalArgumentException(\"Contents must be non-null\");\n }\n reset(owner, contents, x, y);\n }\n\n /**\n * Creates a Popup. This is provided for subclasses.\n */\n protected Popup() {\n }\n\n /**\n * Makes the Popup visible. If the Popup is\n * currently visible, this has no effect.\n */\n @SuppressWarnings(\"deprecation\")\n public void show() {\n Component component = getComponent();\n if (component != null) {\n component.show();\n }\n }\n\n /**\n * Hides and disposes of the Popup. Once a Popup\n * has been disposed you should no longer invoke methods on it. A\n * disposed Popup may be reclaimed and later used\n * based on the PopupFactory. As such, if you invoke methods\n * on a disposed Popup, indeterminate\n * behavior will result.\n */\n @SuppressWarnings(\"deprecation\")\n public void hide() {\n Component component = getComponent();\n if (component instanceof JWindow) {\n component.hide();\n ((JWindow) component).getContentPane().removeAll();\n }\n dispose();\n }\n\n /**\n * Frees any resources the Popup may be holding onto.\n */\n void dispose() {\n Component component = getComponent();\n Window window = SwingUtilities.getWindowAncestor(component);\n if (component instanceof JWindow) {\n ((Window) component).dispose();\n component = null;\n }\n // If our parent is a DefaultFrame, we need to dispose it, too.\n if (window instanceof DefaultFrame) {\n window.dispose();\n }\n }\n\n /**\n * Resets the Popup to an initial state.\n */\n void reset(Component owner, Component contents, int ownerX, int ownerY) {\n if (getComponent() == null) {\n component = createComponent(owner);\n }\n Component c = getComponent();\n if (c instanceof JWindow) {\n JWindow component = (JWindow) getComponent();\n component.setLocation(ownerX, ownerY);\n component.getContentPane().add(contents, BorderLayout.CENTER);\n component.invalidate();\n component.validate();\n if (component.isVisible()) {\n // Do not call pack() if window is not visible to\n // avoid early native peer creation\n pack();\n }\n }\n }\n\n /**\n * Causes the Popup to be sized to fit the preferred size\n * of the Component it contains.\n */\n void pack() {\n Component component = getComponent();\n if (component instanceof Window) {\n ((Window) component).pack();\n }\n }\n\n /**\n * Returns the Window to use as the parent of the\n * Window created for the Popup. This creates\n * a new DefaultFrame, if necessary.\n */\n private Window getParentWindow(Component owner) {\n Window window = null;\n if (owner instanceof Window) {\n window = (Window) owner;\n } else if (owner != null) {\n window = SwingUtilities.getWindowAncestor(owner);\n }\n if (window == null) {\n window = new DefaultFrame();\n }\n return window;\n }\n\n /**\n * Creates the Component to use as the parent of the Popup.\n * The default implementation creates a Window, subclasses\n * should override.\n */\n Component createComponent(Component owner) {\n if (GraphicsEnvironment.isHeadless()) {\n // Generally not useful, bail.\n return null;\n }\n ", "post_mask_code": "\n }\n\n /**\n * Returns the Component returned from\n * createComponent that will hold the Popup.\n */\n Component getComponent() {\n return component;\n }\n\n /**\n * Component used to house window.\n */\n static class HeavyWeightWindow extends JWindow implements ModalExclude {\n\n HeavyWeightWindow(Window parent) {\n super(parent);\n setFocusableWindowState(false);\n if (AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(\"jbre.popupwindow.settype\") != null)) {\n setType(Window.Type.POPUP);\n }\n // Popups are typically transient and most likely won't benefit\n // from true double buffering. Turn it off here.\n getRootPane().setUseTrueDoubleBuffering(false);\n // Try to set \"always-on-top\" for the popup window.\n // Applets usually don't have sufficient permissions to do it.\n // In this case simply ignore the exception.\n try {\n setAlwaysOnTop(true);\n } catch (SecurityException se) {\n // setAlwaysOnTop is restricted,\n // the exception is ignored\n }\n }\n\n public void update(Graphics g) {\n paint(g);\n }\n\n public void show() {\n this.pack();\n if (getWidth() > 0 && getHeight() > 0) {\n super.show();\n }\n }\n }\n\n /**\n * Used if no valid Window ancestor of the supplied owner is found.\n *

\n * PopupFactory uses this as a way to know when the Popup shouldn't\n * be cached based on the Window.\n */\n static class DefaultFrame extends Frame {\n }\n}\n"} {"task_id": "Java_1034", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/JetBrains/jdk8u_jdk/src/share/classes/javax/swing/Popup.java", "mask_start_position": 6399, "mask_end_position": 6400, "canonical_solution": "}", "pre_mask_code": "package javax.swing;\n\nimport java.awt.*;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport sun.awt.ModalExclude;\nimport sun.awt.SunToolkit;\n\n/**\n * Popups are used to display a Component to the user, typically\n * on top of all the other Components in a particular containment\n * hierarchy. Popups have a very small life cycle. Once you\n * have obtained a Popup, and hidden it (invoked the\n * hide method), you should no longer\n * invoke any methods on it. This allows the PopupFactory to cache\n * Popups for later use.\n *

\n * The general contract is that if you need to change the size of the\n * Component, or location of the Popup, you should\n * obtain a new Popup.\n *

\n * Popup does not descend from Component, rather\n * implementations of Popup are responsible for creating\n * and maintaining their own Components to render the\n * requested Component to the user.\n *

\n * You typically do not explicitly create an instance of Popup,\n * instead obtain one from a PopupFactory.\n *\n * @see PopupFactory\n *\n * @since 1.4\n */\npublic class Popup {\n\n /**\n * The Component representing the Popup.\n */\n private Component component;\n\n /**\n * Creates a Popup for the Component owner\n * containing the Component contents. owner\n * is used to determine which Window the new\n * Popup will parent the Component the\n * Popup creates to.\n * A null owner implies there is no valid parent.\n * x and\n * y specify the preferred initial location to place\n * the Popup at. Based on screen size, or other paramaters,\n * the Popup may not display at x and\n * y.\n *\n * @param owner Component mouse coordinates are relative to, may be null\n * @param contents Contents of the Popup\n * @param x Initial x screen coordinate\n * @param y Initial y screen coordinate\n * @exception IllegalArgumentException if contents is null\n */\n protected Popup(Component owner, Component contents, int x, int y) {\n this();\n if (contents == null) {\n throw new IllegalArgumentException(\"Contents must be non-null\");\n }\n reset(owner, contents, x, y);\n }\n\n /**\n * Creates a Popup. This is provided for subclasses.\n */\n protected Popup() {\n }\n\n /**\n * Makes the Popup visible. If the Popup is\n * currently visible, this has no effect.\n */\n @SuppressWarnings(\"deprecation\")\n public void show() {\n Component component = getComponent();\n if (component != null) {\n component.show();\n }\n }\n\n /**\n * Hides and disposes of the Popup. Once a Popup\n * has been disposed you should no longer invoke methods on it. A\n * disposed Popup may be reclaimed and later used\n * based on the PopupFactory. As such, if you invoke methods\n * on a disposed Popup, indeterminate\n * behavior will result.\n */\n @SuppressWarnings(\"deprecation\")\n public void hide() {\n Component component = getComponent();\n if (component instanceof JWindow) {\n component.hide();\n ((JWindow) component).getContentPane().removeAll();\n }\n dispose();\n }\n\n /**\n * Frees any resources the Popup may be holding onto.\n */\n void dispose() {\n Component component = getComponent();\n Window window = SwingUtilities.getWindowAncestor(component);\n if (component instanceof JWindow) {\n ((Window) component).dispose();\n component = null;\n }\n // If our parent is a DefaultFrame, we need to dispose it, too.\n if (window instanceof DefaultFrame) {\n window.dispose();\n }\n }\n\n /**\n * Resets the Popup to an initial state.\n */\n void reset(Component owner, Component contents, int ownerX, int ownerY) {\n if (getComponent() == null) {\n component = createComponent(owner);\n }\n Component c = getComponent();\n if (c instanceof JWindow) {\n JWindow component = (JWindow) getComponent();\n component.setLocation(ownerX, ownerY);\n component.getContentPane().add(contents, BorderLayout.CENTER);\n component.invalidate();\n component.validate();\n if (component.isVisible()) {\n // Do not call pack() if window is not visible to\n // avoid early native peer creation\n pack();\n }\n }\n }\n\n /**\n * Causes the Popup to be sized to fit the preferred size\n * of the Component it contains.\n */\n void pack() {\n Component component = getComponent();\n if (component instanceof Window) {\n ((Window) component).pack();\n }\n }\n\n /**\n * Returns the Window to use as the parent of the\n * Window created for the Popup. This creates\n * a new DefaultFrame, if necessary.\n */\n private Window getParentWindow(Component owner) {\n Window window = null;\n if (owner instanceof Window) {\n window = (Window) owner;\n } else if (owner != null) {\n window = SwingUtilities.getWindowAncestor(owner);\n }\n if (window == null) {\n window = new DefaultFrame();\n }\n return window;\n }\n\n /**\n * Creates the Component to use as the parent of the Popup.\n * The default implementation creates a Window, subclasses\n * should override.\n */\n Component createComponent(Component owner) {\n if (GraphicsEnvironment.isHeadless()) {\n // Generally not useful, bail.\n return null;\n }\n return new HeavyWeightWindow(getParentWindow(owner));\n ", "post_mask_code": "\n\n /**\n * Returns the Component returned from\n * createComponent that will hold the Popup.\n */\n Component getComponent() {\n return component;\n }\n\n /**\n * Component used to house window.\n */\n static class HeavyWeightWindow extends JWindow implements ModalExclude {\n\n HeavyWeightWindow(Window parent) {\n super(parent);\n setFocusableWindowState(false);\n if (AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(\"jbre.popupwindow.settype\") != null)) {\n setType(Window.Type.POPUP);\n }\n // Popups are typically transient and most likely won't benefit\n // from true double buffering. Turn it off here.\n getRootPane().setUseTrueDoubleBuffering(false);\n // Try to set \"always-on-top\" for the popup window.\n // Applets usually don't have sufficient permissions to do it.\n // In this case simply ignore the exception.\n try {\n setAlwaysOnTop(true);\n } catch (SecurityException se) {\n // setAlwaysOnTop is restricted,\n // the exception is ignored\n }\n }\n\n public void update(Graphics g) {\n paint(g);\n }\n\n public void show() {\n this.pack();\n if (getWidth() > 0 && getHeight() > 0) {\n super.show();\n }\n }\n }\n\n /**\n * Used if no valid Window ancestor of the supplied owner is found.\n *

\n * PopupFactory uses this as a way to know when the Popup shouldn't\n * be cached based on the Window.\n */\n static class DefaultFrame extends Frame {\n }\n}\n"} {"task_id": "Java_1035", "language": "Java", "task_type": "single_line", "source_file": "java/github/JetBrains/jdk8u_jdk/src/share/classes/javax/swing/Popup.java", "mask_start_position": 7729, "mask_end_position": 7732, "canonical_solution": "g);", "pre_mask_code": "package javax.swing;\n\nimport java.awt.*;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport sun.awt.ModalExclude;\nimport sun.awt.SunToolkit;\n\n/**\n * Popups are used to display a Component to the user, typically\n * on top of all the other Components in a particular containment\n * hierarchy. Popups have a very small life cycle. Once you\n * have obtained a Popup, and hidden it (invoked the\n * hide method), you should no longer\n * invoke any methods on it. This allows the PopupFactory to cache\n * Popups for later use.\n *

\n * The general contract is that if you need to change the size of the\n * Component, or location of the Popup, you should\n * obtain a new Popup.\n *

\n * Popup does not descend from Component, rather\n * implementations of Popup are responsible for creating\n * and maintaining their own Components to render the\n * requested Component to the user.\n *

\n * You typically do not explicitly create an instance of Popup,\n * instead obtain one from a PopupFactory.\n *\n * @see PopupFactory\n *\n * @since 1.4\n */\npublic class Popup {\n\n /**\n * The Component representing the Popup.\n */\n private Component component;\n\n /**\n * Creates a Popup for the Component owner\n * containing the Component contents. owner\n * is used to determine which Window the new\n * Popup will parent the Component the\n * Popup creates to.\n * A null owner implies there is no valid parent.\n * x and\n * y specify the preferred initial location to place\n * the Popup at. Based on screen size, or other paramaters,\n * the Popup may not display at x and\n * y.\n *\n * @param owner Component mouse coordinates are relative to, may be null\n * @param contents Contents of the Popup\n * @param x Initial x screen coordinate\n * @param y Initial y screen coordinate\n * @exception IllegalArgumentException if contents is null\n */\n protected Popup(Component owner, Component contents, int x, int y) {\n this();\n if (contents == null) {\n throw new IllegalArgumentException(\"Contents must be non-null\");\n }\n reset(owner, contents, x, y);\n }\n\n /**\n * Creates a Popup. This is provided for subclasses.\n */\n protected Popup() {\n }\n\n /**\n * Makes the Popup visible. If the Popup is\n * currently visible, this has no effect.\n */\n @SuppressWarnings(\"deprecation\")\n public void show() {\n Component component = getComponent();\n if (component != null) {\n component.show();\n }\n }\n\n /**\n * Hides and disposes of the Popup. Once a Popup\n * has been disposed you should no longer invoke methods on it. A\n * disposed Popup may be reclaimed and later used\n * based on the PopupFactory. As such, if you invoke methods\n * on a disposed Popup, indeterminate\n * behavior will result.\n */\n @SuppressWarnings(\"deprecation\")\n public void hide() {\n Component component = getComponent();\n if (component instanceof JWindow) {\n component.hide();\n ((JWindow) component).getContentPane().removeAll();\n }\n dispose();\n }\n\n /**\n * Frees any resources the Popup may be holding onto.\n */\n void dispose() {\n Component component = getComponent();\n Window window = SwingUtilities.getWindowAncestor(component);\n if (component instanceof JWindow) {\n ((Window) component).dispose();\n component = null;\n }\n // If our parent is a DefaultFrame, we need to dispose it, too.\n if (window instanceof DefaultFrame) {\n window.dispose();\n }\n }\n\n /**\n * Resets the Popup to an initial state.\n */\n void reset(Component owner, Component contents, int ownerX, int ownerY) {\n if (getComponent() == null) {\n component = createComponent(owner);\n }\n Component c = getComponent();\n if (c instanceof JWindow) {\n JWindow component = (JWindow) getComponent();\n component.setLocation(ownerX, ownerY);\n component.getContentPane().add(contents, BorderLayout.CENTER);\n component.invalidate();\n component.validate();\n if (component.isVisible()) {\n // Do not call pack() if window is not visible to\n // avoid early native peer creation\n pack();\n }\n }\n }\n\n /**\n * Causes the Popup to be sized to fit the preferred size\n * of the Component it contains.\n */\n void pack() {\n Component component = getComponent();\n if (component instanceof Window) {\n ((Window) component).pack();\n }\n }\n\n /**\n * Returns the Window to use as the parent of the\n * Window created for the Popup. This creates\n * a new DefaultFrame, if necessary.\n */\n private Window getParentWindow(Component owner) {\n Window window = null;\n if (owner instanceof Window) {\n window = (Window) owner;\n } else if (owner != null) {\n window = SwingUtilities.getWindowAncestor(owner);\n }\n if (window == null) {\n window = new DefaultFrame();\n }\n return window;\n }\n\n /**\n * Creates the Component to use as the parent of the Popup.\n * The default implementation creates a Window, subclasses\n * should override.\n */\n Component createComponent(Component owner) {\n if (GraphicsEnvironment.isHeadless()) {\n // Generally not useful, bail.\n return null;\n }\n return new HeavyWeightWindow(getParentWindow(owner));\n }\n\n /**\n * Returns the Component returned from\n * createComponent that will hold the Popup.\n */\n Component getComponent() {\n return component;\n }\n\n /**\n * Component used to house window.\n */\n static class HeavyWeightWindow extends JWindow implements ModalExclude {\n\n HeavyWeightWindow(Window parent) {\n super(parent);\n setFocusableWindowState(false);\n if (AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(\"jbre.popupwindow.settype\") != null)) {\n setType(Window.Type.POPUP);\n }\n // Popups are typically transient and most likely won't benefit\n // from true double buffering. Turn it off here.\n getRootPane().setUseTrueDoubleBuffering(false);\n // Try to set \"always-on-top\" for the popup window.\n // Applets usually don't have sufficient permissions to do it.\n // In this case simply ignore the exception.\n try {\n setAlwaysOnTop(true);\n } catch (SecurityException se) {\n // setAlwaysOnTop is restricted,\n // the exception is ignored\n }\n }\n\n public void update(Graphics g) {\n paint(", "post_mask_code": "\n }\n\n public void show() {\n this.pack();\n if (getWidth() > 0 && getHeight() > 0) {\n super.show();\n }\n }\n }\n\n /**\n * Used if no valid Window ancestor of the supplied owner is found.\n *

\n * PopupFactory uses this as a way to know when the Popup shouldn't\n * be cached based on the Window.\n */\n static class DefaultFrame extends Frame {\n }\n}\n"} {"task_id": "Java_1036", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/JetBrains/jdk8u_jdk/src/share/classes/javax/swing/Popup.java", "mask_start_position": 6553, "mask_end_position": 6611, "canonical_solution": "Component getComponent() {\n return component;\n }", "pre_mask_code": "package javax.swing;\n\nimport java.awt.*;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport sun.awt.ModalExclude;\nimport sun.awt.SunToolkit;\n\n/**\n * Popups are used to display a Component to the user, typically\n * on top of all the other Components in a particular containment\n * hierarchy. Popups have a very small life cycle. Once you\n * have obtained a Popup, and hidden it (invoked the\n * hide method), you should no longer\n * invoke any methods on it. This allows the PopupFactory to cache\n * Popups for later use.\n *

\n * The general contract is that if you need to change the size of the\n * Component, or location of the Popup, you should\n * obtain a new Popup.\n *

\n * Popup does not descend from Component, rather\n * implementations of Popup are responsible for creating\n * and maintaining their own Components to render the\n * requested Component to the user.\n *

\n * You typically do not explicitly create an instance of Popup,\n * instead obtain one from a PopupFactory.\n *\n * @see PopupFactory\n *\n * @since 1.4\n */\npublic class Popup {\n\n /**\n * The Component representing the Popup.\n */\n private Component component;\n\n /**\n * Creates a Popup for the Component owner\n * containing the Component contents. owner\n * is used to determine which Window the new\n * Popup will parent the Component the\n * Popup creates to.\n * A null owner implies there is no valid parent.\n * x and\n * y specify the preferred initial location to place\n * the Popup at. Based on screen size, or other paramaters,\n * the Popup may not display at x and\n * y.\n *\n * @param owner Component mouse coordinates are relative to, may be null\n * @param contents Contents of the Popup\n * @param x Initial x screen coordinate\n * @param y Initial y screen coordinate\n * @exception IllegalArgumentException if contents is null\n */\n protected Popup(Component owner, Component contents, int x, int y) {\n this();\n if (contents == null) {\n throw new IllegalArgumentException(\"Contents must be non-null\");\n }\n reset(owner, contents, x, y);\n }\n\n /**\n * Creates a Popup. This is provided for subclasses.\n */\n protected Popup() {\n }\n\n /**\n * Makes the Popup visible. If the Popup is\n * currently visible, this has no effect.\n */\n @SuppressWarnings(\"deprecation\")\n public void show() {\n Component component = getComponent();\n if (component != null) {\n component.show();\n }\n }\n\n /**\n * Hides and disposes of the Popup. Once a Popup\n * has been disposed you should no longer invoke methods on it. A\n * disposed Popup may be reclaimed and later used\n * based on the PopupFactory. As such, if you invoke methods\n * on a disposed Popup, indeterminate\n * behavior will result.\n */\n @SuppressWarnings(\"deprecation\")\n public void hide() {\n Component component = getComponent();\n if (component instanceof JWindow) {\n component.hide();\n ((JWindow) component).getContentPane().removeAll();\n }\n dispose();\n }\n\n /**\n * Frees any resources the Popup may be holding onto.\n */\n void dispose() {\n Component component = getComponent();\n Window window = SwingUtilities.getWindowAncestor(component);\n if (component instanceof JWindow) {\n ((Window) component).dispose();\n component = null;\n }\n // If our parent is a DefaultFrame, we need to dispose it, too.\n if (window instanceof DefaultFrame) {\n window.dispose();\n }\n }\n\n /**\n * Resets the Popup to an initial state.\n */\n void reset(Component owner, Component contents, int ownerX, int ownerY) {\n if (getComponent() == null) {\n component = createComponent(owner);\n }\n Component c = getComponent();\n if (c instanceof JWindow) {\n JWindow component = (JWindow) getComponent();\n component.setLocation(ownerX, ownerY);\n component.getContentPane().add(contents, BorderLayout.CENTER);\n component.invalidate();\n component.validate();\n if (component.isVisible()) {\n // Do not call pack() if window is not visible to\n // avoid early native peer creation\n pack();\n }\n }\n }\n\n /**\n * Causes the Popup to be sized to fit the preferred size\n * of the Component it contains.\n */\n void pack() {\n Component component = getComponent();\n if (component instanceof Window) {\n ((Window) component).pack();\n }\n }\n\n /**\n * Returns the Window to use as the parent of the\n * Window created for the Popup. This creates\n * a new DefaultFrame, if necessary.\n */\n private Window getParentWindow(Component owner) {\n Window window = null;\n if (owner instanceof Window) {\n window = (Window) owner;\n } else if (owner != null) {\n window = SwingUtilities.getWindowAncestor(owner);\n }\n if (window == null) {\n window = new DefaultFrame();\n }\n return window;\n }\n\n /**\n * Creates the Component to use as the parent of the Popup.\n * The default implementation creates a Window, subclasses\n * should override.\n */\n Component createComponent(Component owner) {\n if (GraphicsEnvironment.isHeadless()) {\n // Generally not useful, bail.\n return null;\n }\n return new HeavyWeightWindow(getParentWindow(owner));\n }\n\n /**\n * Returns the Component returned from\n * createComponent that will hold the Popup.\n */\n ", "post_mask_code": "\n\n /**\n * Component used to house window.\n */\n static class HeavyWeightWindow extends JWindow implements ModalExclude {\n\n HeavyWeightWindow(Window parent) {\n super(parent);\n setFocusableWindowState(false);\n if (AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(\"jbre.popupwindow.settype\") != null)) {\n setType(Window.Type.POPUP);\n }\n // Popups are typically transient and most likely won't benefit\n // from true double buffering. Turn it off here.\n getRootPane().setUseTrueDoubleBuffering(false);\n // Try to set \"always-on-top\" for the popup window.\n // Applets usually don't have sufficient permissions to do it.\n // In this case simply ignore the exception.\n try {\n setAlwaysOnTop(true);\n } catch (SecurityException se) {\n // setAlwaysOnTop is restricted,\n // the exception is ignored\n }\n }\n\n public void update(Graphics g) {\n paint(g);\n }\n\n public void show() {\n this.pack();\n if (getWidth() > 0 && getHeight() > 0) {\n super.show();\n }\n }\n }\n\n /**\n * Used if no valid Window ancestor of the supplied owner is found.\n *

\n * PopupFactory uses this as a way to know when the Popup shouldn't\n * be cached based on the Window.\n */\n static class DefaultFrame extends Frame {\n }\n}\n"} {"task_id": "Java_1037", "language": "Java", "task_type": "if_statement", "source_file": "java/github/JetBrains/jdk8u_jdk/src/share/classes/javax/swing/Popup.java", "mask_start_position": 5862, "mask_end_position": 5934, "canonical_solution": "if (window == null) {\n window = new DefaultFrame();\n }", "pre_mask_code": "package javax.swing;\n\nimport java.awt.*;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport sun.awt.ModalExclude;\nimport sun.awt.SunToolkit;\n\n/**\n * Popups are used to display a Component to the user, typically\n * on top of all the other Components in a particular containment\n * hierarchy. Popups have a very small life cycle. Once you\n * have obtained a Popup, and hidden it (invoked the\n * hide method), you should no longer\n * invoke any methods on it. This allows the PopupFactory to cache\n * Popups for later use.\n *

\n * The general contract is that if you need to change the size of the\n * Component, or location of the Popup, you should\n * obtain a new Popup.\n *

\n * Popup does not descend from Component, rather\n * implementations of Popup are responsible for creating\n * and maintaining their own Components to render the\n * requested Component to the user.\n *

\n * You typically do not explicitly create an instance of Popup,\n * instead obtain one from a PopupFactory.\n *\n * @see PopupFactory\n *\n * @since 1.4\n */\npublic class Popup {\n\n /**\n * The Component representing the Popup.\n */\n private Component component;\n\n /**\n * Creates a Popup for the Component owner\n * containing the Component contents. owner\n * is used to determine which Window the new\n * Popup will parent the Component the\n * Popup creates to.\n * A null owner implies there is no valid parent.\n * x and\n * y specify the preferred initial location to place\n * the Popup at. Based on screen size, or other paramaters,\n * the Popup may not display at x and\n * y.\n *\n * @param owner Component mouse coordinates are relative to, may be null\n * @param contents Contents of the Popup\n * @param x Initial x screen coordinate\n * @param y Initial y screen coordinate\n * @exception IllegalArgumentException if contents is null\n */\n protected Popup(Component owner, Component contents, int x, int y) {\n this();\n if (contents == null) {\n throw new IllegalArgumentException(\"Contents must be non-null\");\n }\n reset(owner, contents, x, y);\n }\n\n /**\n * Creates a Popup. This is provided for subclasses.\n */\n protected Popup() {\n }\n\n /**\n * Makes the Popup visible. If the Popup is\n * currently visible, this has no effect.\n */\n @SuppressWarnings(\"deprecation\")\n public void show() {\n Component component = getComponent();\n if (component != null) {\n component.show();\n }\n }\n\n /**\n * Hides and disposes of the Popup. Once a Popup\n * has been disposed you should no longer invoke methods on it. A\n * disposed Popup may be reclaimed and later used\n * based on the PopupFactory. As such, if you invoke methods\n * on a disposed Popup, indeterminate\n * behavior will result.\n */\n @SuppressWarnings(\"deprecation\")\n public void hide() {\n Component component = getComponent();\n if (component instanceof JWindow) {\n component.hide();\n ((JWindow) component).getContentPane().removeAll();\n }\n dispose();\n }\n\n /**\n * Frees any resources the Popup may be holding onto.\n */\n void dispose() {\n Component component = getComponent();\n Window window = SwingUtilities.getWindowAncestor(component);\n if (component instanceof JWindow) {\n ((Window) component).dispose();\n component = null;\n }\n // If our parent is a DefaultFrame, we need to dispose it, too.\n if (window instanceof DefaultFrame) {\n window.dispose();\n }\n }\n\n /**\n * Resets the Popup to an initial state.\n */\n void reset(Component owner, Component contents, int ownerX, int ownerY) {\n if (getComponent() == null) {\n component = createComponent(owner);\n }\n Component c = getComponent();\n if (c instanceof JWindow) {\n JWindow component = (JWindow) getComponent();\n component.setLocation(ownerX, ownerY);\n component.getContentPane().add(contents, BorderLayout.CENTER);\n component.invalidate();\n component.validate();\n if (component.isVisible()) {\n // Do not call pack() if window is not visible to\n // avoid early native peer creation\n pack();\n }\n }\n }\n\n /**\n * Causes the Popup to be sized to fit the preferred size\n * of the Component it contains.\n */\n void pack() {\n Component component = getComponent();\n if (component instanceof Window) {\n ((Window) component).pack();\n }\n }\n\n /**\n * Returns the Window to use as the parent of the\n * Window created for the Popup. This creates\n * a new DefaultFrame, if necessary.\n */\n private Window getParentWindow(Component owner) {\n Window window = null;\n if (owner instanceof Window) {\n window = (Window) owner;\n } else if (owner != null) {\n window = SwingUtilities.getWindowAncestor(owner);\n }\n ", "post_mask_code": "\n return window;\n }\n\n /**\n * Creates the Component to use as the parent of the Popup.\n * The default implementation creates a Window, subclasses\n * should override.\n */\n Component createComponent(Component owner) {\n if (GraphicsEnvironment.isHeadless()) {\n // Generally not useful, bail.\n return null;\n }\n return new HeavyWeightWindow(getParentWindow(owner));\n }\n\n /**\n * Returns the Component returned from\n * createComponent that will hold the Popup.\n */\n Component getComponent() {\n return component;\n }\n\n /**\n * Component used to house window.\n */\n static class HeavyWeightWindow extends JWindow implements ModalExclude {\n\n HeavyWeightWindow(Window parent) {\n super(parent);\n setFocusableWindowState(false);\n if (AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(\"jbre.popupwindow.settype\") != null)) {\n setType(Window.Type.POPUP);\n }\n // Popups are typically transient and most likely won't benefit\n // from true double buffering. Turn it off here.\n getRootPane().setUseTrueDoubleBuffering(false);\n // Try to set \"always-on-top\" for the popup window.\n // Applets usually don't have sufficient permissions to do it.\n // In this case simply ignore the exception.\n try {\n setAlwaysOnTop(true);\n } catch (SecurityException se) {\n // setAlwaysOnTop is restricted,\n // the exception is ignored\n }\n }\n\n public void update(Graphics g) {\n paint(g);\n }\n\n public void show() {\n this.pack();\n if (getWidth() > 0 && getHeight() > 0) {\n super.show();\n }\n }\n }\n\n /**\n * Used if no valid Window ancestor of the supplied owner is found.\n *

\n * PopupFactory uses this as a way to know when the Popup shouldn't\n * be cached based on the Window.\n */\n static class DefaultFrame extends Frame {\n }\n}\n"} {"task_id": "Java_1038", "language": "Java", "task_type": "try_statement", "source_file": "java/github/JetBrains/jdk8u_jdk/src/share/classes/javax/swing/Popup.java", "mask_start_position": 7463, "mask_end_position": 7658, "canonical_solution": "try {\n setAlwaysOnTop(true);\n } catch (SecurityException se) {\n // setAlwaysOnTop is restricted,\n // the exception is ignored\n }", "pre_mask_code": "package javax.swing;\n\nimport java.awt.*;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport sun.awt.ModalExclude;\nimport sun.awt.SunToolkit;\n\n/**\n * Popups are used to display a Component to the user, typically\n * on top of all the other Components in a particular containment\n * hierarchy. Popups have a very small life cycle. Once you\n * have obtained a Popup, and hidden it (invoked the\n * hide method), you should no longer\n * invoke any methods on it. This allows the PopupFactory to cache\n * Popups for later use.\n *

\n * The general contract is that if you need to change the size of the\n * Component, or location of the Popup, you should\n * obtain a new Popup.\n *

\n * Popup does not descend from Component, rather\n * implementations of Popup are responsible for creating\n * and maintaining their own Components to render the\n * requested Component to the user.\n *

\n * You typically do not explicitly create an instance of Popup,\n * instead obtain one from a PopupFactory.\n *\n * @see PopupFactory\n *\n * @since 1.4\n */\npublic class Popup {\n\n /**\n * The Component representing the Popup.\n */\n private Component component;\n\n /**\n * Creates a Popup for the Component owner\n * containing the Component contents. owner\n * is used to determine which Window the new\n * Popup will parent the Component the\n * Popup creates to.\n * A null owner implies there is no valid parent.\n * x and\n * y specify the preferred initial location to place\n * the Popup at. Based on screen size, or other paramaters,\n * the Popup may not display at x and\n * y.\n *\n * @param owner Component mouse coordinates are relative to, may be null\n * @param contents Contents of the Popup\n * @param x Initial x screen coordinate\n * @param y Initial y screen coordinate\n * @exception IllegalArgumentException if contents is null\n */\n protected Popup(Component owner, Component contents, int x, int y) {\n this();\n if (contents == null) {\n throw new IllegalArgumentException(\"Contents must be non-null\");\n }\n reset(owner, contents, x, y);\n }\n\n /**\n * Creates a Popup. This is provided for subclasses.\n */\n protected Popup() {\n }\n\n /**\n * Makes the Popup visible. If the Popup is\n * currently visible, this has no effect.\n */\n @SuppressWarnings(\"deprecation\")\n public void show() {\n Component component = getComponent();\n if (component != null) {\n component.show();\n }\n }\n\n /**\n * Hides and disposes of the Popup. Once a Popup\n * has been disposed you should no longer invoke methods on it. A\n * disposed Popup may be reclaimed and later used\n * based on the PopupFactory. As such, if you invoke methods\n * on a disposed Popup, indeterminate\n * behavior will result.\n */\n @SuppressWarnings(\"deprecation\")\n public void hide() {\n Component component = getComponent();\n if (component instanceof JWindow) {\n component.hide();\n ((JWindow) component).getContentPane().removeAll();\n }\n dispose();\n }\n\n /**\n * Frees any resources the Popup may be holding onto.\n */\n void dispose() {\n Component component = getComponent();\n Window window = SwingUtilities.getWindowAncestor(component);\n if (component instanceof JWindow) {\n ((Window) component).dispose();\n component = null;\n }\n // If our parent is a DefaultFrame, we need to dispose it, too.\n if (window instanceof DefaultFrame) {\n window.dispose();\n }\n }\n\n /**\n * Resets the Popup to an initial state.\n */\n void reset(Component owner, Component contents, int ownerX, int ownerY) {\n if (getComponent() == null) {\n component = createComponent(owner);\n }\n Component c = getComponent();\n if (c instanceof JWindow) {\n JWindow component = (JWindow) getComponent();\n component.setLocation(ownerX, ownerY);\n component.getContentPane().add(contents, BorderLayout.CENTER);\n component.invalidate();\n component.validate();\n if (component.isVisible()) {\n // Do not call pack() if window is not visible to\n // avoid early native peer creation\n pack();\n }\n }\n }\n\n /**\n * Causes the Popup to be sized to fit the preferred size\n * of the Component it contains.\n */\n void pack() {\n Component component = getComponent();\n if (component instanceof Window) {\n ((Window) component).pack();\n }\n }\n\n /**\n * Returns the Window to use as the parent of the\n * Window created for the Popup. This creates\n * a new DefaultFrame, if necessary.\n */\n private Window getParentWindow(Component owner) {\n Window window = null;\n if (owner instanceof Window) {\n window = (Window) owner;\n } else if (owner != null) {\n window = SwingUtilities.getWindowAncestor(owner);\n }\n if (window == null) {\n window = new DefaultFrame();\n }\n return window;\n }\n\n /**\n * Creates the Component to use as the parent of the Popup.\n * The default implementation creates a Window, subclasses\n * should override.\n */\n Component createComponent(Component owner) {\n if (GraphicsEnvironment.isHeadless()) {\n // Generally not useful, bail.\n return null;\n }\n return new HeavyWeightWindow(getParentWindow(owner));\n }\n\n /**\n * Returns the Component returned from\n * createComponent that will hold the Popup.\n */\n Component getComponent() {\n return component;\n }\n\n /**\n * Component used to house window.\n */\n static class HeavyWeightWindow extends JWindow implements ModalExclude {\n\n HeavyWeightWindow(Window parent) {\n super(parent);\n setFocusableWindowState(false);\n if (AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(\"jbre.popupwindow.settype\") != null)) {\n setType(Window.Type.POPUP);\n }\n // Popups are typically transient and most likely won't benefit\n // from true double buffering. Turn it off here.\n getRootPane().setUseTrueDoubleBuffering(false);\n // Try to set \"always-on-top\" for the popup window.\n // Applets usually don't have sufficient permissions to do it.\n // In this case simply ignore the exception.\n ", "post_mask_code": "\n }\n\n public void update(Graphics g) {\n paint(g);\n }\n\n public void show() {\n this.pack();\n if (getWidth() > 0 && getHeight() > 0) {\n super.show();\n }\n }\n }\n\n /**\n * Used if no valid Window ancestor of the supplied owner is found.\n *

\n * PopupFactory uses this as a way to know when the Popup shouldn't\n * be cached based on the Window.\n */\n static class DefaultFrame extends Frame {\n }\n}\n"} {"task_id": "Java_1039", "language": "Java", "task_type": "empty", "source_file": "java/github/JetBrains/jdk8u_jdk/src/share/classes/javax/swing/Popup.java", "mask_start_position": 6096, "mask_end_position": 6096, "canonical_solution": "", "pre_mask_code": "package javax.swing;\n\nimport java.awt.*;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport sun.awt.ModalExclude;\nimport sun.awt.SunToolkit;\n\n/**\n * Popups are used to display a Component to the user, typically\n * on top of all the other Components in a particular containment\n * hierarchy. Popups have a very small life cycle. Once you\n * have obtained a Popup, and hidden it (invoked the\n * hide method), you should no longer\n * invoke any methods on it. This allows the PopupFactory to cache\n * Popups for later use.\n *

\n * The general contract is that if you need to change the size of the\n * Component, or location of the Popup, you should\n * obtain a new Popup.\n *

\n * Popup does not descend from Component, rather\n * implementations of Popup are responsible for creating\n * and maintaining their own Components to render the\n * requested Component to the user.\n *

\n * You typically do not explicitly create an instance of Popup,\n * instead obtain one from a PopupFactory.\n *\n * @see PopupFactory\n *\n * @since 1.4\n */\npublic class Popup {\n\n /**\n * The Component representing the Popup.\n */\n private Component component;\n\n /**\n * Creates a Popup for the Component owner\n * containing the Component contents. owner\n * is used to determine which Window the new\n * Popup will parent the Component the\n * Popup creates to.\n * A null owner implies there is no valid parent.\n * x and\n * y specify the preferred initial location to place\n * the Popup at. Based on screen size, or other paramaters,\n * the Popup may not display at x and\n * y.\n *\n * @param owner Component mouse coordinates are relative to, may be null\n * @param contents Contents of the Popup\n * @param x Initial x screen coordinate\n * @param y Initial y screen coordinate\n * @exception IllegalArgumentException if contents is null\n */\n protected Popup(Component owner, Component contents, int x, int y) {\n this();\n if (contents == null) {\n throw new IllegalArgumentException(\"Contents must be non-null\");\n }\n reset(owner, contents, x, y);\n }\n\n /**\n * Creates a Popup. This is provided for subclasses.\n */\n protected Popup() {\n }\n\n /**\n * Makes the Popup visible. If the Popup is\n * currently visible, this has no effect.\n */\n @SuppressWarnings(\"deprecation\")\n public void show() {\n Component component = getComponent();\n if (component != null) {\n component.show();\n }\n }\n\n /**\n * Hides and disposes of the Popup. Once a Popup\n * has been disposed you should no longer invoke methods on it. A\n * disposed Popup may be reclaimed and later used\n * based on the PopupFactory. As such, if you invoke methods\n * on a disposed Popup, indeterminate\n * behavior will result.\n */\n @SuppressWarnings(\"deprecation\")\n public void hide() {\n Component component = getComponent();\n if (component instanceof JWindow) {\n component.hide();\n ((JWindow) component).getContentPane().removeAll();\n }\n dispose();\n }\n\n /**\n * Frees any resources the Popup may be holding onto.\n */\n void dispose() {\n Component component = getComponent();\n Window window = SwingUtilities.getWindowAncestor(component);\n if (component instanceof JWindow) {\n ((Window) component).dispose();\n component = null;\n }\n // If our parent is a DefaultFrame, we need to dispose it, too.\n if (window instanceof DefaultFrame) {\n window.dispose();\n }\n }\n\n /**\n * Resets the Popup to an initial state.\n */\n void reset(Component owner, Component contents, int ownerX, int ownerY) {\n if (getComponent() == null) {\n component = createComponent(owner);\n }\n Component c = getComponent();\n if (c instanceof JWindow) {\n JWindow component = (JWindow) getComponent();\n component.setLocation(ownerX, ownerY);\n component.getContentPane().add(contents, BorderLayout.CENTER);\n component.invalidate();\n component.validate();\n if (component.isVisible()) {\n // Do not call pack() if window is not visible to\n // avoid early native peer creation\n pack();\n }\n }\n }\n\n /**\n * Causes the Popup to be sized to fit the preferred size\n * of the Component it contains.\n */\n void pack() {\n Component component = getComponent();\n if (component instanceof Window) {\n ((Window) component).pack();\n }\n }\n\n /**\n * Returns the Window to use as the parent of the\n * Window created for the Popup. This creates\n * a new DefaultFrame, if necessary.\n */\n private Window getParentWindow(Component owner) {\n Window window = null;\n if (owner instanceof Window) {\n window = (Window) owner;\n } else if (owner != null) {\n window = SwingUtilities.getWindowAncestor(owner);\n }\n if (window == null) {\n window = new DefaultFrame();\n }\n return window;\n }\n\n /**\n * Creates the Component to use as the parent of the Popup.\n * The default implementation creates a Window, subclasses\n * should override.\n */\n Component createComponent(Component owner) {\n if (GraphicsEnvironment.isHeadless()) {\n // Generally not useful, bail.\n return null;\n }\n return new HeavyWeightWindow(getParentWindow(owner));\n }\n\n /**\n * Returns the Component returned from\n * createComponent that will hold the Popup.\n */\n Component getComponent() {\n return component;\n }\n\n /**\n * Component used to house window.\n */\n static class HeavyWeightWindow extends JWindow implements ModalExclude {\n\n HeavyWeightWindow(Window parent) {\n super(parent);\n setFocusableWindowState(false);\n if (AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(\"jbre.popupwindow.settype\") != null)) {\n setType(Window.Type.POPUP);\n }\n // Popups are typically transient and most likely won't benefit\n // from true double buffering. Turn it off here.\n getRootPane().setUseTrueDoubleBuffering(false);\n // Try to set \"always-on-top\" for the popup window.\n // Applets usually don't have sufficient permissions to do it.\n // In this case simply ignore the exception.\n try {\n setAlwaysOnTop(true);\n } catch (SecurityException se) {\n // setAlwaysOnTop is restricted,\n // the exception is ignored\n }\n }\n\n public void update(Graphics g) {\n paint(g);\n }\n\n public void show() {\n this.pack();\n if (getWidth() > 0 && getHeight() > 0) {\n super.show();\n }\n }\n }\n\n /**\n * Used if no valid Window ancestor of the supplied owner is found.\n *

\n * PopupFactory uses this as a way to know when the Popup shouldn't\n * be cached based on the Window.\n */\n static class DefaultFrame extends Frame {\n }\n}\n"} {"task_id": "Java_1040", "language": "Java", "task_type": "method_signature", "source_file": "java/github/albfan/jmeld/src/main/java/org/jmeld/model/LevenshteinTableModel.java", "mask_start_position": 16266, "mask_end_position": 16325, "canonical_solution": "public void setCurrentRevision(JMRevision currentRevision) ", "pre_mask_code": "package org.jmeld.model;\n\nimport org.jmeld.diff.JMChunk;\nimport org.jmeld.diff.JMDelta;\nimport org.jmeld.diff.JMRevision;\nimport org.jmeld.ui.BufferDiffPanel;\nimport org.jmeld.ui.FilePanel;\nimport org.jmeld.ui.text.BufferDocumentIF;\nimport org.jmeld.ui.util.Colors;\nimport javax.swing.*;\nimport javax.swing.border.Border;\nimport javax.swing.border.CompoundBorder;\nimport javax.swing.border.MatteBorder;\nimport javax.swing.table.DefaultTableCellRenderer;\nimport javax.swing.table.DefaultTableModel;\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\n\n/**\n * Modelo de levenstein\n * User: alberto\n * Date: 7/12/12\n * Time: 16:40\n */\npublic class LevenshteinTableModel extends DefaultTableModel {\n\n String origin;\n\n String destiny;\n\n private JMRevision currentRevision;\n\n private FilePanel[] filePanels;\n\n private HashMap routeDiff;\n\n private HashMap borderChunks;\n\n private HashMap borderSelections;\n\n private boolean showSelectionPath;\n\n public void buildModel() {\n if (!isAllDataAvaliable()) {\n return;\n }\n borderSelections = new HashMap<>();\n setDataVector(newVector(origin.length() + 2), newVector(destiny.length() + 2));\n buildSolutionPath();\n int rowCount = getRowCount();\n int columnCount = getColumnCount();\n for (int columna = 0; columna < columnCount; columna++) {\n if (columna < 2) {\n setValueAt(\"\", 0, columna);\n } else {\n setValueAt(destiny.charAt(columna - 2), 0, columna);\n }\n }\n for (int fila = 0; fila < rowCount; fila++) {\n if (fila < 2) {\n setValueAt(\"\", fila, 0);\n } else {\n setValueAt(origin.charAt(fila - 2), fila, 0);\n }\n }\n int minLength = rowCount > columnCount ? columnCount : rowCount;\n for (int diagonal = 1; diagonal < minLength; diagonal++) {\n if (diagonal == 1) {\n setValueAt(0, diagonal, diagonal);\n } else {\n Object o = getValueAt(diagonal - 1, diagonal - 1);\n int incremento;\n if (origin.charAt(diagonal - 2) == destiny.charAt(diagonal - 2)) {\n incremento = 0;\n } else {\n incremento = 1;\n }\n setValueAt((Integer) o + incremento, diagonal, diagonal);\n }\n for (int columna = diagonal + 1; columna < columnCount; columna++) {\n setValueAt((Integer) getValueAt(diagonal, columna - 1) + 1, diagonal, columna);\n }\n for (int fila = diagonal + 1; fila < rowCount; fila++) {\n setValueAt((Integer) getValueAt(fila - 1, diagonal) + 1, fila, diagonal);\n }\n }\n }\n\n private boolean isAllDataAvaliable() {\n return getFilePanels() != null && getCurrentRevision() != null && origin != null && destiny != null;\n }\n\n class ColorPoint extends Point {\n\n Color color;\n\n public ColorPoint(int x, int y, Color color) {\n super(x, y);\n this.color = color;\n }\n }\n\n private void buildSolutionPath() {\n BufferDocumentIF originalBufferDocument = filePanels[BufferDiffPanel.LEFT].getBufferDocument();\n BufferDocumentIF revisedBufferDocument = filePanels[BufferDiffPanel.RIGHT].getBufferDocument();\n java.util.List deltas = currentRevision.getDeltas();\n routeDiff = new HashMap<>();\n borderChunks = new HashMap<>();\n int xOffset = 0;\n int yOffset = 0;\n for (Iterator iterator = deltas.iterator(); iterator.hasNext(); ) {\n JMDelta next = iterator.next();\n JMChunk original = next.getOriginal();\n JMChunk revised = next.getRevised();\n int originalLines = originalBufferDocument.getNumberOfLines();\n int revisedLines = revisedBufferDocument.getNumberOfLines();\n int offsetForLineOriginal;\n if (original.getAnchor() == originalLines) {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor() - 1) + 1;\n } else {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor());\n }\n int offsetForLineRevised;\n if (revised.getAnchor() == revisedLines) {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor() - 1) + 1;\n } else {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor());\n }\n for (int i = 0; i < offsetForLineOriginal - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n if (next.isAdd()) {\n int lineNumber = revised.getAnchor() + revised.getSize() - 1;\n int yOffsetForLineEnd = revisedBufferDocument.getOffsetForLine(lineNumber) + +revisedBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < yOffsetForLineEnd - offsetForLineRevised; i++) {\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 2, 0, Color.BLACK);\n } else if (i == yOffsetForLineEnd - offsetForLineRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 2, 0, Color.BLACK);\n }\n Point point = new Point(offsetForLineOriginal - 1, i + offsetForLineRevised);\n addBorderChunks(point, border);\n routeDiff.put(point, Colors.ADDED);\n }\n xOffset = offsetForLineOriginal;\n yOffset = yOffsetForLineEnd;\n } else if (next.isDelete()) {\n int lineNumber = original.getAnchor() + original.getSize() - 1;\n int xOffsetForLine = originalBufferDocument.getOffsetForLine(lineNumber) + originalBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < xOffsetForLine - offsetForLineOriginal; i++) {\n Point point = new Point(i + offsetForLineOriginal, offsetForLineRevised - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 0, 2, Color.BLACK);\n } else if (i == xOffsetForLine - offsetForLineOriginal - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 2, 0, 2, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset = xOffsetForLine;\n yOffset = offsetForLineRevised;\n } else if (next.isChange()) {\n List changedDeltas = next.getChangeRevision().getDeltas();\n xOffset = offsetForLineOriginal;\n yOffset = offsetForLineRevised;\n for (Iterator jmDeltaIterator = changedDeltas.iterator(); jmDeltaIterator.hasNext(); ) {\n JMDelta changeDelta = jmDeltaIterator.next();\n JMChunk originalChange = changeDelta.getOriginal();\n JMChunk revisedChange = changeDelta.getRevised();\n int sameChars = originalChange.getAnchor() - xOffset;\n for (int i = 0; i < sameChars; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n xOffset += sameChars;\n yOffset += sameChars;\n int removeFromOrigin = originalChange.getSize();\n int addFromRevised = revisedChange.getSize();\n for (int i = 0; i < removeFromOrigin; i++) {\n Point point = new Point(i + xOffset, yOffset - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == removeFromOrigin - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 0, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(new Point(i + xOffset, yOffset - 1 + addFromRevised), border);\n border = BorderFactory.createMatteBorder(0, 2, 0, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset += removeFromOrigin;\n if (addFromRevised == 0) {\n Point point = new Point(xOffset - 1, yOffset - 1);\n MatteBorder border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(point, border);\n }\n for (int i = 0; i < addFromRevised; i++) {\n Point point = new Point(xOffset - 1, i + yOffset);\n routeDiff.put(point, Colors.ADDED);\n MatteBorder border;\n if (i == 0 && removeFromOrigin == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i - 1 + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(0, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n yOffset += addFromRevised;\n }\n }\n }\n int xSize = originalBufferDocument.getDocument().getLength();\n for (int i = 0; i < xSize - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n }\n\n private void addBorderChunks(Point point, MatteBorder border) {\n MatteBorder oldborder = borderChunks.get(point);\n if (oldborder != null) {\n Insets oldborderInsets = oldborder.getBorderInsets();\n Insets borderInsets = border.getBorderInsets();\n if (oldborderInsets.top == 0 && borderInsets.top > 0) {\n oldborderInsets.top = borderInsets.top;\n }\n if (oldborderInsets.left == 0 && borderInsets.left > 0) {\n oldborderInsets.left = borderInsets.left;\n }\n if (oldborderInsets.right == 0 && borderInsets.right > 0) {\n oldborderInsets.right = borderInsets.right;\n }\n if (oldborderInsets.bottom == 0 && borderInsets.bottom > 0) {\n oldborderInsets.bottom = borderInsets.bottom;\n }\n border = BorderFactory.createMatteBorder(oldborderInsets.top, oldborderInsets.left, oldborderInsets.bottom, oldborderInsets.right, border.getMatteColor());\n }\n borderChunks.put(point, border);\n }\n\n private Vector newVector(int size) {\n Vector vector = new Vector(size);\n vector.setSize(size);\n return vector;\n }\n\n public String getOrigin() {\n return origin;\n }\n\n public void setOrigin(String origin) {\n this.origin = origin;\n buildModel();\n }\n\n public String getDestiny() {\n return destiny;\n }\n\n public void setDestiny(String destiny) {\n this.destiny = destiny;\n buildModel();\n }\n\n public DefaultTableCellRenderer getCellRenderer() {\n return new DefaultTableCellRenderer() {\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n if (\"\\n\".equals(value.toString())) {\n value = \"\\\\n\";\n }\n Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n Color background = Color.WHITE;\n if (row < 2 && column < 2) {\n if (row == column) {\n background = Color.GREEN;\n } else {\n background = Color.BLUE;\n }\n } else {\n if (row > 1) {\n if (column > 1) {\n if (origin.charAt(row - 2) == destiny.charAt(column - 2)) {\n background = Color.ORANGE;\n }\n }\n }\n if (row == 0 || column == 0) {\n background = new Color(0x550099FF, true);\n }\n }\n if (isSelected || table.isColumnSelected(column)) {\n Color newColor = Color.CYAN;\n Color mixColor = Color.WHITE;\n background = new Color(background.getRed() * newColor.getRed() / mixColor.getRed(), background.getGreen() * newColor.getGreen() / mixColor.getGreen(), background.getBlue() * newColor.getBlue() / mixColor.getBlue());\n }\n Point point = new Point(row - 2, column - 2);\n if (showSelectionPath) {\n Color color = routeDiff.get(point);\n if (color != null) {\n background = color;\n }\n }\n Border border = borderChunks.get(point);\n Border borderSelection = borderSelections.get(point);\n if (border == null) {\n if (borderSelection != null) {\n border = borderSelection;\n }\n } else {\n if (borderSelection != null) {\n border = new CompoundBorder(border, borderSelection);\n }\n }\n if (border != null) {\n ((JLabel) tableCellRendererComponent).setBorder(border);\n }\n tableCellRendererComponent.setBackground(background);\n ((JLabel) tableCellRendererComponent).setHorizontalAlignment(SwingConstants.CENTER);\n return tableCellRendererComponent;\n }\n };\n }\n\n ", "post_mask_code": "{\n this.currentRevision = currentRevision;\n buildModel();\n }\n\n public JMRevision getCurrentRevision() {\n return currentRevision;\n }\n\n public void setFilePanels(FilePanel[] filePanels) {\n this.filePanels = filePanels;\n buildModel();\n }\n\n public FilePanel[] getFilePanels() {\n return filePanels;\n }\n\n public boolean isShowSelectionPath() {\n return showSelectionPath;\n }\n\n public void setShowSelectionPath(boolean showSelectionPath) {\n this.showSelectionPath = showSelectionPath;\n }\n\n public HashMap getBorderSelections() {\n return borderSelections;\n }\n\n public void setBorderSelections(HashMap borderSelection) {\n this.borderSelections = borderSelection;\n }\n}\n"} {"task_id": "Java_1041", "language": "Java", "task_type": "method_body", "source_file": "java/github/albfan/jmeld/src/main/java/org/jmeld/model/LevenshteinTableModel.java", "mask_start_position": 12960, "mask_end_position": 13062, "canonical_solution": "{\n Vector vector = new Vector(size);\n vector.setSize(size);\n return vector;\n }", "pre_mask_code": "package org.jmeld.model;\n\nimport org.jmeld.diff.JMChunk;\nimport org.jmeld.diff.JMDelta;\nimport org.jmeld.diff.JMRevision;\nimport org.jmeld.ui.BufferDiffPanel;\nimport org.jmeld.ui.FilePanel;\nimport org.jmeld.ui.text.BufferDocumentIF;\nimport org.jmeld.ui.util.Colors;\nimport javax.swing.*;\nimport javax.swing.border.Border;\nimport javax.swing.border.CompoundBorder;\nimport javax.swing.border.MatteBorder;\nimport javax.swing.table.DefaultTableCellRenderer;\nimport javax.swing.table.DefaultTableModel;\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\n\n/**\n * Modelo de levenstein\n * User: alberto\n * Date: 7/12/12\n * Time: 16:40\n */\npublic class LevenshteinTableModel extends DefaultTableModel {\n\n String origin;\n\n String destiny;\n\n private JMRevision currentRevision;\n\n private FilePanel[] filePanels;\n\n private HashMap routeDiff;\n\n private HashMap borderChunks;\n\n private HashMap borderSelections;\n\n private boolean showSelectionPath;\n\n public void buildModel() {\n if (!isAllDataAvaliable()) {\n return;\n }\n borderSelections = new HashMap<>();\n setDataVector(newVector(origin.length() + 2), newVector(destiny.length() + 2));\n buildSolutionPath();\n int rowCount = getRowCount();\n int columnCount = getColumnCount();\n for (int columna = 0; columna < columnCount; columna++) {\n if (columna < 2) {\n setValueAt(\"\", 0, columna);\n } else {\n setValueAt(destiny.charAt(columna - 2), 0, columna);\n }\n }\n for (int fila = 0; fila < rowCount; fila++) {\n if (fila < 2) {\n setValueAt(\"\", fila, 0);\n } else {\n setValueAt(origin.charAt(fila - 2), fila, 0);\n }\n }\n int minLength = rowCount > columnCount ? columnCount : rowCount;\n for (int diagonal = 1; diagonal < minLength; diagonal++) {\n if (diagonal == 1) {\n setValueAt(0, diagonal, diagonal);\n } else {\n Object o = getValueAt(diagonal - 1, diagonal - 1);\n int incremento;\n if (origin.charAt(diagonal - 2) == destiny.charAt(diagonal - 2)) {\n incremento = 0;\n } else {\n incremento = 1;\n }\n setValueAt((Integer) o + incremento, diagonal, diagonal);\n }\n for (int columna = diagonal + 1; columna < columnCount; columna++) {\n setValueAt((Integer) getValueAt(diagonal, columna - 1) + 1, diagonal, columna);\n }\n for (int fila = diagonal + 1; fila < rowCount; fila++) {\n setValueAt((Integer) getValueAt(fila - 1, diagonal) + 1, fila, diagonal);\n }\n }\n }\n\n private boolean isAllDataAvaliable() {\n return getFilePanels() != null && getCurrentRevision() != null && origin != null && destiny != null;\n }\n\n class ColorPoint extends Point {\n\n Color color;\n\n public ColorPoint(int x, int y, Color color) {\n super(x, y);\n this.color = color;\n }\n }\n\n private void buildSolutionPath() {\n BufferDocumentIF originalBufferDocument = filePanels[BufferDiffPanel.LEFT].getBufferDocument();\n BufferDocumentIF revisedBufferDocument = filePanels[BufferDiffPanel.RIGHT].getBufferDocument();\n java.util.List deltas = currentRevision.getDeltas();\n routeDiff = new HashMap<>();\n borderChunks = new HashMap<>();\n int xOffset = 0;\n int yOffset = 0;\n for (Iterator iterator = deltas.iterator(); iterator.hasNext(); ) {\n JMDelta next = iterator.next();\n JMChunk original = next.getOriginal();\n JMChunk revised = next.getRevised();\n int originalLines = originalBufferDocument.getNumberOfLines();\n int revisedLines = revisedBufferDocument.getNumberOfLines();\n int offsetForLineOriginal;\n if (original.getAnchor() == originalLines) {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor() - 1) + 1;\n } else {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor());\n }\n int offsetForLineRevised;\n if (revised.getAnchor() == revisedLines) {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor() - 1) + 1;\n } else {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor());\n }\n for (int i = 0; i < offsetForLineOriginal - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n if (next.isAdd()) {\n int lineNumber = revised.getAnchor() + revised.getSize() - 1;\n int yOffsetForLineEnd = revisedBufferDocument.getOffsetForLine(lineNumber) + +revisedBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < yOffsetForLineEnd - offsetForLineRevised; i++) {\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 2, 0, Color.BLACK);\n } else if (i == yOffsetForLineEnd - offsetForLineRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 2, 0, Color.BLACK);\n }\n Point point = new Point(offsetForLineOriginal - 1, i + offsetForLineRevised);\n addBorderChunks(point, border);\n routeDiff.put(point, Colors.ADDED);\n }\n xOffset = offsetForLineOriginal;\n yOffset = yOffsetForLineEnd;\n } else if (next.isDelete()) {\n int lineNumber = original.getAnchor() + original.getSize() - 1;\n int xOffsetForLine = originalBufferDocument.getOffsetForLine(lineNumber) + originalBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < xOffsetForLine - offsetForLineOriginal; i++) {\n Point point = new Point(i + offsetForLineOriginal, offsetForLineRevised - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 0, 2, Color.BLACK);\n } else if (i == xOffsetForLine - offsetForLineOriginal - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 2, 0, 2, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset = xOffsetForLine;\n yOffset = offsetForLineRevised;\n } else if (next.isChange()) {\n List changedDeltas = next.getChangeRevision().getDeltas();\n xOffset = offsetForLineOriginal;\n yOffset = offsetForLineRevised;\n for (Iterator jmDeltaIterator = changedDeltas.iterator(); jmDeltaIterator.hasNext(); ) {\n JMDelta changeDelta = jmDeltaIterator.next();\n JMChunk originalChange = changeDelta.getOriginal();\n JMChunk revisedChange = changeDelta.getRevised();\n int sameChars = originalChange.getAnchor() - xOffset;\n for (int i = 0; i < sameChars; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n xOffset += sameChars;\n yOffset += sameChars;\n int removeFromOrigin = originalChange.getSize();\n int addFromRevised = revisedChange.getSize();\n for (int i = 0; i < removeFromOrigin; i++) {\n Point point = new Point(i + xOffset, yOffset - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == removeFromOrigin - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 0, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(new Point(i + xOffset, yOffset - 1 + addFromRevised), border);\n border = BorderFactory.createMatteBorder(0, 2, 0, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset += removeFromOrigin;\n if (addFromRevised == 0) {\n Point point = new Point(xOffset - 1, yOffset - 1);\n MatteBorder border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(point, border);\n }\n for (int i = 0; i < addFromRevised; i++) {\n Point point = new Point(xOffset - 1, i + yOffset);\n routeDiff.put(point, Colors.ADDED);\n MatteBorder border;\n if (i == 0 && removeFromOrigin == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i - 1 + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(0, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n yOffset += addFromRevised;\n }\n }\n }\n int xSize = originalBufferDocument.getDocument().getLength();\n for (int i = 0; i < xSize - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n }\n\n private void addBorderChunks(Point point, MatteBorder border) {\n MatteBorder oldborder = borderChunks.get(point);\n if (oldborder != null) {\n Insets oldborderInsets = oldborder.getBorderInsets();\n Insets borderInsets = border.getBorderInsets();\n if (oldborderInsets.top == 0 && borderInsets.top > 0) {\n oldborderInsets.top = borderInsets.top;\n }\n if (oldborderInsets.left == 0 && borderInsets.left > 0) {\n oldborderInsets.left = borderInsets.left;\n }\n if (oldborderInsets.right == 0 && borderInsets.right > 0) {\n oldborderInsets.right = borderInsets.right;\n }\n if (oldborderInsets.bottom == 0 && borderInsets.bottom > 0) {\n oldborderInsets.bottom = borderInsets.bottom;\n }\n border = BorderFactory.createMatteBorder(oldborderInsets.top, oldborderInsets.left, oldborderInsets.bottom, oldborderInsets.right, border.getMatteColor());\n }\n borderChunks.put(point, border);\n }\n\n private Vector newVector(int size) ", "post_mask_code": "\n\n public String getOrigin() {\n return origin;\n }\n\n public void setOrigin(String origin) {\n this.origin = origin;\n buildModel();\n }\n\n public String getDestiny() {\n return destiny;\n }\n\n public void setDestiny(String destiny) {\n this.destiny = destiny;\n buildModel();\n }\n\n public DefaultTableCellRenderer getCellRenderer() {\n return new DefaultTableCellRenderer() {\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n if (\"\\n\".equals(value.toString())) {\n value = \"\\\\n\";\n }\n Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n Color background = Color.WHITE;\n if (row < 2 && column < 2) {\n if (row == column) {\n background = Color.GREEN;\n } else {\n background = Color.BLUE;\n }\n } else {\n if (row > 1) {\n if (column > 1) {\n if (origin.charAt(row - 2) == destiny.charAt(column - 2)) {\n background = Color.ORANGE;\n }\n }\n }\n if (row == 0 || column == 0) {\n background = new Color(0x550099FF, true);\n }\n }\n if (isSelected || table.isColumnSelected(column)) {\n Color newColor = Color.CYAN;\n Color mixColor = Color.WHITE;\n background = new Color(background.getRed() * newColor.getRed() / mixColor.getRed(), background.getGreen() * newColor.getGreen() / mixColor.getGreen(), background.getBlue() * newColor.getBlue() / mixColor.getBlue());\n }\n Point point = new Point(row - 2, column - 2);\n if (showSelectionPath) {\n Color color = routeDiff.get(point);\n if (color != null) {\n background = color;\n }\n }\n Border border = borderChunks.get(point);\n Border borderSelection = borderSelections.get(point);\n if (border == null) {\n if (borderSelection != null) {\n border = borderSelection;\n }\n } else {\n if (borderSelection != null) {\n border = new CompoundBorder(border, borderSelection);\n }\n }\n if (border != null) {\n ((JLabel) tableCellRendererComponent).setBorder(border);\n }\n tableCellRendererComponent.setBackground(background);\n ((JLabel) tableCellRendererComponent).setHorizontalAlignment(SwingConstants.CENTER);\n return tableCellRendererComponent;\n }\n };\n }\n\n public void setCurrentRevision(JMRevision currentRevision) {\n this.currentRevision = currentRevision;\n buildModel();\n }\n\n public JMRevision getCurrentRevision() {\n return currentRevision;\n }\n\n public void setFilePanels(FilePanel[] filePanels) {\n this.filePanels = filePanels;\n buildModel();\n }\n\n public FilePanel[] getFilePanels() {\n return filePanels;\n }\n\n public boolean isShowSelectionPath() {\n return showSelectionPath;\n }\n\n public void setShowSelectionPath(boolean showSelectionPath) {\n this.showSelectionPath = showSelectionPath;\n }\n\n public HashMap getBorderSelections() {\n return borderSelections;\n }\n\n public void setBorderSelections(HashMap borderSelection) {\n this.borderSelections = borderSelection;\n }\n}\n"} {"task_id": "Java_1042", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/albfan/jmeld/src/main/java/org/jmeld/model/LevenshteinTableModel.java", "mask_start_position": 3248, "mask_end_position": 3526, "canonical_solution": "\n BufferDocumentIF originalBufferDocument = filePanels[BufferDiffPanel.LEFT].getBufferDocument();\n BufferDocumentIF revisedBufferDocument = filePanels[BufferDiffPanel.RIGHT].getBufferDocument();\n java.util.List deltas = currentRevision.getDeltas();", "pre_mask_code": "package org.jmeld.model;\n\nimport org.jmeld.diff.JMChunk;\nimport org.jmeld.diff.JMDelta;\nimport org.jmeld.diff.JMRevision;\nimport org.jmeld.ui.BufferDiffPanel;\nimport org.jmeld.ui.FilePanel;\nimport org.jmeld.ui.text.BufferDocumentIF;\nimport org.jmeld.ui.util.Colors;\nimport javax.swing.*;\nimport javax.swing.border.Border;\nimport javax.swing.border.CompoundBorder;\nimport javax.swing.border.MatteBorder;\nimport javax.swing.table.DefaultTableCellRenderer;\nimport javax.swing.table.DefaultTableModel;\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\n\n/**\n * Modelo de levenstein\n * User: alberto\n * Date: 7/12/12\n * Time: 16:40\n */\npublic class LevenshteinTableModel extends DefaultTableModel {\n\n String origin;\n\n String destiny;\n\n private JMRevision currentRevision;\n\n private FilePanel[] filePanels;\n\n private HashMap routeDiff;\n\n private HashMap borderChunks;\n\n private HashMap borderSelections;\n\n private boolean showSelectionPath;\n\n public void buildModel() {\n if (!isAllDataAvaliable()) {\n return;\n }\n borderSelections = new HashMap<>();\n setDataVector(newVector(origin.length() + 2), newVector(destiny.length() + 2));\n buildSolutionPath();\n int rowCount = getRowCount();\n int columnCount = getColumnCount();\n for (int columna = 0; columna < columnCount; columna++) {\n if (columna < 2) {\n setValueAt(\"\", 0, columna);\n } else {\n setValueAt(destiny.charAt(columna - 2), 0, columna);\n }\n }\n for (int fila = 0; fila < rowCount; fila++) {\n if (fila < 2) {\n setValueAt(\"\", fila, 0);\n } else {\n setValueAt(origin.charAt(fila - 2), fila, 0);\n }\n }\n int minLength = rowCount > columnCount ? columnCount : rowCount;\n for (int diagonal = 1; diagonal < minLength; diagonal++) {\n if (diagonal == 1) {\n setValueAt(0, diagonal, diagonal);\n } else {\n Object o = getValueAt(diagonal - 1, diagonal - 1);\n int incremento;\n if (origin.charAt(diagonal - 2) == destiny.charAt(diagonal - 2)) {\n incremento = 0;\n } else {\n incremento = 1;\n }\n setValueAt((Integer) o + incremento, diagonal, diagonal);\n }\n for (int columna = diagonal + 1; columna < columnCount; columna++) {\n setValueAt((Integer) getValueAt(diagonal, columna - 1) + 1, diagonal, columna);\n }\n for (int fila = diagonal + 1; fila < rowCount; fila++) {\n setValueAt((Integer) getValueAt(fila - 1, diagonal) + 1, fila, diagonal);\n }\n }\n }\n\n private boolean isAllDataAvaliable() {\n return getFilePanels() != null && getCurrentRevision() != null && origin != null && destiny != null;\n }\n\n class ColorPoint extends Point {\n\n Color color;\n\n public ColorPoint(int x, int y, Color color) {\n super(x, y);\n this.color = color;\n }\n }\n\n private void buildSolutionPath() {", "post_mask_code": "\n routeDiff = new HashMap<>();\n borderChunks = new HashMap<>();\n int xOffset = 0;\n int yOffset = 0;\n for (Iterator iterator = deltas.iterator(); iterator.hasNext(); ) {\n JMDelta next = iterator.next();\n JMChunk original = next.getOriginal();\n JMChunk revised = next.getRevised();\n int originalLines = originalBufferDocument.getNumberOfLines();\n int revisedLines = revisedBufferDocument.getNumberOfLines();\n int offsetForLineOriginal;\n if (original.getAnchor() == originalLines) {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor() - 1) + 1;\n } else {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor());\n }\n int offsetForLineRevised;\n if (revised.getAnchor() == revisedLines) {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor() - 1) + 1;\n } else {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor());\n }\n for (int i = 0; i < offsetForLineOriginal - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n if (next.isAdd()) {\n int lineNumber = revised.getAnchor() + revised.getSize() - 1;\n int yOffsetForLineEnd = revisedBufferDocument.getOffsetForLine(lineNumber) + +revisedBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < yOffsetForLineEnd - offsetForLineRevised; i++) {\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 2, 0, Color.BLACK);\n } else if (i == yOffsetForLineEnd - offsetForLineRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 2, 0, Color.BLACK);\n }\n Point point = new Point(offsetForLineOriginal - 1, i + offsetForLineRevised);\n addBorderChunks(point, border);\n routeDiff.put(point, Colors.ADDED);\n }\n xOffset = offsetForLineOriginal;\n yOffset = yOffsetForLineEnd;\n } else if (next.isDelete()) {\n int lineNumber = original.getAnchor() + original.getSize() - 1;\n int xOffsetForLine = originalBufferDocument.getOffsetForLine(lineNumber) + originalBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < xOffsetForLine - offsetForLineOriginal; i++) {\n Point point = new Point(i + offsetForLineOriginal, offsetForLineRevised - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 0, 2, Color.BLACK);\n } else if (i == xOffsetForLine - offsetForLineOriginal - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 2, 0, 2, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset = xOffsetForLine;\n yOffset = offsetForLineRevised;\n } else if (next.isChange()) {\n List changedDeltas = next.getChangeRevision().getDeltas();\n xOffset = offsetForLineOriginal;\n yOffset = offsetForLineRevised;\n for (Iterator jmDeltaIterator = changedDeltas.iterator(); jmDeltaIterator.hasNext(); ) {\n JMDelta changeDelta = jmDeltaIterator.next();\n JMChunk originalChange = changeDelta.getOriginal();\n JMChunk revisedChange = changeDelta.getRevised();\n int sameChars = originalChange.getAnchor() - xOffset;\n for (int i = 0; i < sameChars; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n xOffset += sameChars;\n yOffset += sameChars;\n int removeFromOrigin = originalChange.getSize();\n int addFromRevised = revisedChange.getSize();\n for (int i = 0; i < removeFromOrigin; i++) {\n Point point = new Point(i + xOffset, yOffset - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == removeFromOrigin - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 0, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(new Point(i + xOffset, yOffset - 1 + addFromRevised), border);\n border = BorderFactory.createMatteBorder(0, 2, 0, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset += removeFromOrigin;\n if (addFromRevised == 0) {\n Point point = new Point(xOffset - 1, yOffset - 1);\n MatteBorder border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(point, border);\n }\n for (int i = 0; i < addFromRevised; i++) {\n Point point = new Point(xOffset - 1, i + yOffset);\n routeDiff.put(point, Colors.ADDED);\n MatteBorder border;\n if (i == 0 && removeFromOrigin == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i - 1 + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(0, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n yOffset += addFromRevised;\n }\n }\n }\n int xSize = originalBufferDocument.getDocument().getLength();\n for (int i = 0; i < xSize - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n }\n\n private void addBorderChunks(Point point, MatteBorder border) {\n MatteBorder oldborder = borderChunks.get(point);\n if (oldborder != null) {\n Insets oldborderInsets = oldborder.getBorderInsets();\n Insets borderInsets = border.getBorderInsets();\n if (oldborderInsets.top == 0 && borderInsets.top > 0) {\n oldborderInsets.top = borderInsets.top;\n }\n if (oldborderInsets.left == 0 && borderInsets.left > 0) {\n oldborderInsets.left = borderInsets.left;\n }\n if (oldborderInsets.right == 0 && borderInsets.right > 0) {\n oldborderInsets.right = borderInsets.right;\n }\n if (oldborderInsets.bottom == 0 && borderInsets.bottom > 0) {\n oldborderInsets.bottom = borderInsets.bottom;\n }\n border = BorderFactory.createMatteBorder(oldborderInsets.top, oldborderInsets.left, oldborderInsets.bottom, oldborderInsets.right, border.getMatteColor());\n }\n borderChunks.put(point, border);\n }\n\n private Vector newVector(int size) {\n Vector vector = new Vector(size);\n vector.setSize(size);\n return vector;\n }\n\n public String getOrigin() {\n return origin;\n }\n\n public void setOrigin(String origin) {\n this.origin = origin;\n buildModel();\n }\n\n public String getDestiny() {\n return destiny;\n }\n\n public void setDestiny(String destiny) {\n this.destiny = destiny;\n buildModel();\n }\n\n public DefaultTableCellRenderer getCellRenderer() {\n return new DefaultTableCellRenderer() {\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n if (\"\\n\".equals(value.toString())) {\n value = \"\\\\n\";\n }\n Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n Color background = Color.WHITE;\n if (row < 2 && column < 2) {\n if (row == column) {\n background = Color.GREEN;\n } else {\n background = Color.BLUE;\n }\n } else {\n if (row > 1) {\n if (column > 1) {\n if (origin.charAt(row - 2) == destiny.charAt(column - 2)) {\n background = Color.ORANGE;\n }\n }\n }\n if (row == 0 || column == 0) {\n background = new Color(0x550099FF, true);\n }\n }\n if (isSelected || table.isColumnSelected(column)) {\n Color newColor = Color.CYAN;\n Color mixColor = Color.WHITE;\n background = new Color(background.getRed() * newColor.getRed() / mixColor.getRed(), background.getGreen() * newColor.getGreen() / mixColor.getGreen(), background.getBlue() * newColor.getBlue() / mixColor.getBlue());\n }\n Point point = new Point(row - 2, column - 2);\n if (showSelectionPath) {\n Color color = routeDiff.get(point);\n if (color != null) {\n background = color;\n }\n }\n Border border = borderChunks.get(point);\n Border borderSelection = borderSelections.get(point);\n if (border == null) {\n if (borderSelection != null) {\n border = borderSelection;\n }\n } else {\n if (borderSelection != null) {\n border = new CompoundBorder(border, borderSelection);\n }\n }\n if (border != null) {\n ((JLabel) tableCellRendererComponent).setBorder(border);\n }\n tableCellRendererComponent.setBackground(background);\n ((JLabel) tableCellRendererComponent).setHorizontalAlignment(SwingConstants.CENTER);\n return tableCellRendererComponent;\n }\n };\n }\n\n public void setCurrentRevision(JMRevision currentRevision) {\n this.currentRevision = currentRevision;\n buildModel();\n }\n\n public JMRevision getCurrentRevision() {\n return currentRevision;\n }\n\n public void setFilePanels(FilePanel[] filePanels) {\n this.filePanels = filePanels;\n buildModel();\n }\n\n public FilePanel[] getFilePanels() {\n return filePanels;\n }\n\n public boolean isShowSelectionPath() {\n return showSelectionPath;\n }\n\n public void setShowSelectionPath(boolean showSelectionPath) {\n this.showSelectionPath = showSelectionPath;\n }\n\n public HashMap getBorderSelections() {\n return borderSelections;\n }\n\n public void setBorderSelections(HashMap borderSelection) {\n this.borderSelections = borderSelection;\n }\n}\n"} {"task_id": "Java_1043", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/albfan/jmeld/src/main/java/org/jmeld/model/LevenshteinTableModel.java", "mask_start_position": 3535, "mask_end_position": 3653, "canonical_solution": "routeDiff = new HashMap<>();\n borderChunks = new HashMap<>();\n int xOffset = 0;\n int yOffset = 0;", "pre_mask_code": "package org.jmeld.model;\n\nimport org.jmeld.diff.JMChunk;\nimport org.jmeld.diff.JMDelta;\nimport org.jmeld.diff.JMRevision;\nimport org.jmeld.ui.BufferDiffPanel;\nimport org.jmeld.ui.FilePanel;\nimport org.jmeld.ui.text.BufferDocumentIF;\nimport org.jmeld.ui.util.Colors;\nimport javax.swing.*;\nimport javax.swing.border.Border;\nimport javax.swing.border.CompoundBorder;\nimport javax.swing.border.MatteBorder;\nimport javax.swing.table.DefaultTableCellRenderer;\nimport javax.swing.table.DefaultTableModel;\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\n\n/**\n * Modelo de levenstein\n * User: alberto\n * Date: 7/12/12\n * Time: 16:40\n */\npublic class LevenshteinTableModel extends DefaultTableModel {\n\n String origin;\n\n String destiny;\n\n private JMRevision currentRevision;\n\n private FilePanel[] filePanels;\n\n private HashMap routeDiff;\n\n private HashMap borderChunks;\n\n private HashMap borderSelections;\n\n private boolean showSelectionPath;\n\n public void buildModel() {\n if (!isAllDataAvaliable()) {\n return;\n }\n borderSelections = new HashMap<>();\n setDataVector(newVector(origin.length() + 2), newVector(destiny.length() + 2));\n buildSolutionPath();\n int rowCount = getRowCount();\n int columnCount = getColumnCount();\n for (int columna = 0; columna < columnCount; columna++) {\n if (columna < 2) {\n setValueAt(\"\", 0, columna);\n } else {\n setValueAt(destiny.charAt(columna - 2), 0, columna);\n }\n }\n for (int fila = 0; fila < rowCount; fila++) {\n if (fila < 2) {\n setValueAt(\"\", fila, 0);\n } else {\n setValueAt(origin.charAt(fila - 2), fila, 0);\n }\n }\n int minLength = rowCount > columnCount ? columnCount : rowCount;\n for (int diagonal = 1; diagonal < minLength; diagonal++) {\n if (diagonal == 1) {\n setValueAt(0, diagonal, diagonal);\n } else {\n Object o = getValueAt(diagonal - 1, diagonal - 1);\n int incremento;\n if (origin.charAt(diagonal - 2) == destiny.charAt(diagonal - 2)) {\n incremento = 0;\n } else {\n incremento = 1;\n }\n setValueAt((Integer) o + incremento, diagonal, diagonal);\n }\n for (int columna = diagonal + 1; columna < columnCount; columna++) {\n setValueAt((Integer) getValueAt(diagonal, columna - 1) + 1, diagonal, columna);\n }\n for (int fila = diagonal + 1; fila < rowCount; fila++) {\n setValueAt((Integer) getValueAt(fila - 1, diagonal) + 1, fila, diagonal);\n }\n }\n }\n\n private boolean isAllDataAvaliable() {\n return getFilePanels() != null && getCurrentRevision() != null && origin != null && destiny != null;\n }\n\n class ColorPoint extends Point {\n\n Color color;\n\n public ColorPoint(int x, int y, Color color) {\n super(x, y);\n this.color = color;\n }\n }\n\n private void buildSolutionPath() {\n BufferDocumentIF originalBufferDocument = filePanels[BufferDiffPanel.LEFT].getBufferDocument();\n BufferDocumentIF revisedBufferDocument = filePanels[BufferDiffPanel.RIGHT].getBufferDocument();\n java.util.List deltas = currentRevision.getDeltas();\n ", "post_mask_code": "\n for (Iterator iterator = deltas.iterator(); iterator.hasNext(); ) {\n JMDelta next = iterator.next();\n JMChunk original = next.getOriginal();\n JMChunk revised = next.getRevised();\n int originalLines = originalBufferDocument.getNumberOfLines();\n int revisedLines = revisedBufferDocument.getNumberOfLines();\n int offsetForLineOriginal;\n if (original.getAnchor() == originalLines) {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor() - 1) + 1;\n } else {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor());\n }\n int offsetForLineRevised;\n if (revised.getAnchor() == revisedLines) {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor() - 1) + 1;\n } else {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor());\n }\n for (int i = 0; i < offsetForLineOriginal - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n if (next.isAdd()) {\n int lineNumber = revised.getAnchor() + revised.getSize() - 1;\n int yOffsetForLineEnd = revisedBufferDocument.getOffsetForLine(lineNumber) + +revisedBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < yOffsetForLineEnd - offsetForLineRevised; i++) {\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 2, 0, Color.BLACK);\n } else if (i == yOffsetForLineEnd - offsetForLineRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 2, 0, Color.BLACK);\n }\n Point point = new Point(offsetForLineOriginal - 1, i + offsetForLineRevised);\n addBorderChunks(point, border);\n routeDiff.put(point, Colors.ADDED);\n }\n xOffset = offsetForLineOriginal;\n yOffset = yOffsetForLineEnd;\n } else if (next.isDelete()) {\n int lineNumber = original.getAnchor() + original.getSize() - 1;\n int xOffsetForLine = originalBufferDocument.getOffsetForLine(lineNumber) + originalBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < xOffsetForLine - offsetForLineOriginal; i++) {\n Point point = new Point(i + offsetForLineOriginal, offsetForLineRevised - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 0, 2, Color.BLACK);\n } else if (i == xOffsetForLine - offsetForLineOriginal - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 2, 0, 2, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset = xOffsetForLine;\n yOffset = offsetForLineRevised;\n } else if (next.isChange()) {\n List changedDeltas = next.getChangeRevision().getDeltas();\n xOffset = offsetForLineOriginal;\n yOffset = offsetForLineRevised;\n for (Iterator jmDeltaIterator = changedDeltas.iterator(); jmDeltaIterator.hasNext(); ) {\n JMDelta changeDelta = jmDeltaIterator.next();\n JMChunk originalChange = changeDelta.getOriginal();\n JMChunk revisedChange = changeDelta.getRevised();\n int sameChars = originalChange.getAnchor() - xOffset;\n for (int i = 0; i < sameChars; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n xOffset += sameChars;\n yOffset += sameChars;\n int removeFromOrigin = originalChange.getSize();\n int addFromRevised = revisedChange.getSize();\n for (int i = 0; i < removeFromOrigin; i++) {\n Point point = new Point(i + xOffset, yOffset - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == removeFromOrigin - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 0, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(new Point(i + xOffset, yOffset - 1 + addFromRevised), border);\n border = BorderFactory.createMatteBorder(0, 2, 0, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset += removeFromOrigin;\n if (addFromRevised == 0) {\n Point point = new Point(xOffset - 1, yOffset - 1);\n MatteBorder border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(point, border);\n }\n for (int i = 0; i < addFromRevised; i++) {\n Point point = new Point(xOffset - 1, i + yOffset);\n routeDiff.put(point, Colors.ADDED);\n MatteBorder border;\n if (i == 0 && removeFromOrigin == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i - 1 + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(0, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n yOffset += addFromRevised;\n }\n }\n }\n int xSize = originalBufferDocument.getDocument().getLength();\n for (int i = 0; i < xSize - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n }\n\n private void addBorderChunks(Point point, MatteBorder border) {\n MatteBorder oldborder = borderChunks.get(point);\n if (oldborder != null) {\n Insets oldborderInsets = oldborder.getBorderInsets();\n Insets borderInsets = border.getBorderInsets();\n if (oldborderInsets.top == 0 && borderInsets.top > 0) {\n oldborderInsets.top = borderInsets.top;\n }\n if (oldborderInsets.left == 0 && borderInsets.left > 0) {\n oldborderInsets.left = borderInsets.left;\n }\n if (oldborderInsets.right == 0 && borderInsets.right > 0) {\n oldborderInsets.right = borderInsets.right;\n }\n if (oldborderInsets.bottom == 0 && borderInsets.bottom > 0) {\n oldborderInsets.bottom = borderInsets.bottom;\n }\n border = BorderFactory.createMatteBorder(oldborderInsets.top, oldborderInsets.left, oldborderInsets.bottom, oldborderInsets.right, border.getMatteColor());\n }\n borderChunks.put(point, border);\n }\n\n private Vector newVector(int size) {\n Vector vector = new Vector(size);\n vector.setSize(size);\n return vector;\n }\n\n public String getOrigin() {\n return origin;\n }\n\n public void setOrigin(String origin) {\n this.origin = origin;\n buildModel();\n }\n\n public String getDestiny() {\n return destiny;\n }\n\n public void setDestiny(String destiny) {\n this.destiny = destiny;\n buildModel();\n }\n\n public DefaultTableCellRenderer getCellRenderer() {\n return new DefaultTableCellRenderer() {\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n if (\"\\n\".equals(value.toString())) {\n value = \"\\\\n\";\n }\n Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n Color background = Color.WHITE;\n if (row < 2 && column < 2) {\n if (row == column) {\n background = Color.GREEN;\n } else {\n background = Color.BLUE;\n }\n } else {\n if (row > 1) {\n if (column > 1) {\n if (origin.charAt(row - 2) == destiny.charAt(column - 2)) {\n background = Color.ORANGE;\n }\n }\n }\n if (row == 0 || column == 0) {\n background = new Color(0x550099FF, true);\n }\n }\n if (isSelected || table.isColumnSelected(column)) {\n Color newColor = Color.CYAN;\n Color mixColor = Color.WHITE;\n background = new Color(background.getRed() * newColor.getRed() / mixColor.getRed(), background.getGreen() * newColor.getGreen() / mixColor.getGreen(), background.getBlue() * newColor.getBlue() / mixColor.getBlue());\n }\n Point point = new Point(row - 2, column - 2);\n if (showSelectionPath) {\n Color color = routeDiff.get(point);\n if (color != null) {\n background = color;\n }\n }\n Border border = borderChunks.get(point);\n Border borderSelection = borderSelections.get(point);\n if (border == null) {\n if (borderSelection != null) {\n border = borderSelection;\n }\n } else {\n if (borderSelection != null) {\n border = new CompoundBorder(border, borderSelection);\n }\n }\n if (border != null) {\n ((JLabel) tableCellRendererComponent).setBorder(border);\n }\n tableCellRendererComponent.setBackground(background);\n ((JLabel) tableCellRendererComponent).setHorizontalAlignment(SwingConstants.CENTER);\n return tableCellRendererComponent;\n }\n };\n }\n\n public void setCurrentRevision(JMRevision currentRevision) {\n this.currentRevision = currentRevision;\n buildModel();\n }\n\n public JMRevision getCurrentRevision() {\n return currentRevision;\n }\n\n public void setFilePanels(FilePanel[] filePanels) {\n this.filePanels = filePanels;\n buildModel();\n }\n\n public FilePanel[] getFilePanels() {\n return filePanels;\n }\n\n public boolean isShowSelectionPath() {\n return showSelectionPath;\n }\n\n public void setShowSelectionPath(boolean showSelectionPath) {\n this.showSelectionPath = showSelectionPath;\n }\n\n public HashMap getBorderSelections() {\n return borderSelections;\n }\n\n public void setBorderSelections(HashMap borderSelection) {\n this.borderSelections = borderSelection;\n }\n}\n"} {"task_id": "Java_1044", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/albfan/jmeld/src/main/java/org/jmeld/model/LevenshteinTableModel.java", "mask_start_position": 3662, "mask_end_position": 11833, "canonical_solution": "for (Iterator iterator = deltas.iterator(); iterator.hasNext(); ) {\n JMDelta next = iterator.next();\n JMChunk original = next.getOriginal();\n JMChunk revised = next.getRevised();\n int originalLines = originalBufferDocument.getNumberOfLines();\n int revisedLines = revisedBufferDocument.getNumberOfLines();\n int offsetForLineOriginal;\n if (original.getAnchor() == originalLines) {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor() - 1) + 1;\n } else {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor());\n }\n int offsetForLineRevised;\n if (revised.getAnchor() == revisedLines) {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor() - 1) + 1;\n } else {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor());\n }\n for (int i = 0; i < offsetForLineOriginal - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n if (next.isAdd()) {\n int lineNumber = revised.getAnchor() + revised.getSize() - 1;\n int yOffsetForLineEnd = revisedBufferDocument.getOffsetForLine(lineNumber) + +revisedBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < yOffsetForLineEnd - offsetForLineRevised; i++) {\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 2, 0, Color.BLACK);\n } else if (i == yOffsetForLineEnd - offsetForLineRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 2, 0, Color.BLACK);\n }\n Point point = new Point(offsetForLineOriginal - 1, i + offsetForLineRevised);\n addBorderChunks(point, border);\n routeDiff.put(point, Colors.ADDED);\n }\n xOffset = offsetForLineOriginal;\n yOffset = yOffsetForLineEnd;\n } else if (next.isDelete()) {\n int lineNumber = original.getAnchor() + original.getSize() - 1;\n int xOffsetForLine = originalBufferDocument.getOffsetForLine(lineNumber) + originalBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < xOffsetForLine - offsetForLineOriginal; i++) {\n Point point = new Point(i + offsetForLineOriginal, offsetForLineRevised - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 0, 2, Color.BLACK);\n } else if (i == xOffsetForLine - offsetForLineOriginal - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 2, 0, 2, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset = xOffsetForLine;\n yOffset = offsetForLineRevised;\n } else if (next.isChange()) {\n List changedDeltas = next.getChangeRevision().getDeltas();\n xOffset = offsetForLineOriginal;\n yOffset = offsetForLineRevised;\n for (Iterator jmDeltaIterator = changedDeltas.iterator(); jmDeltaIterator.hasNext(); ) {\n JMDelta changeDelta = jmDeltaIterator.next();\n JMChunk originalChange = changeDelta.getOriginal();\n JMChunk revisedChange = changeDelta.getRevised();\n int sameChars = originalChange.getAnchor() - xOffset;\n for (int i = 0; i < sameChars; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n xOffset += sameChars;\n yOffset += sameChars;\n int removeFromOrigin = originalChange.getSize();\n int addFromRevised = revisedChange.getSize();\n for (int i = 0; i < removeFromOrigin; i++) {\n Point point = new Point(i + xOffset, yOffset - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == removeFromOrigin - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 0, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(new Point(i + xOffset, yOffset - 1 + addFromRevised), border);\n border = BorderFactory.createMatteBorder(0, 2, 0, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset += removeFromOrigin;\n if (addFromRevised == 0) {\n Point point = new Point(xOffset - 1, yOffset - 1);\n MatteBorder border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(point, border);\n }\n for (int i = 0; i < addFromRevised; i++) {\n Point point = new Point(xOffset - 1, i + yOffset);\n routeDiff.put(point, Colors.ADDED);\n MatteBorder border;\n if (i == 0 && removeFromOrigin == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i - 1 + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(0, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n yOffset += addFromRevised;\n }\n }\n }\n int xSize = originalBufferDocument.getDocument().getLength();\n for (int i = 0; i < xSize - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n }", "pre_mask_code": "package org.jmeld.model;\n\nimport org.jmeld.diff.JMChunk;\nimport org.jmeld.diff.JMDelta;\nimport org.jmeld.diff.JMRevision;\nimport org.jmeld.ui.BufferDiffPanel;\nimport org.jmeld.ui.FilePanel;\nimport org.jmeld.ui.text.BufferDocumentIF;\nimport org.jmeld.ui.util.Colors;\nimport javax.swing.*;\nimport javax.swing.border.Border;\nimport javax.swing.border.CompoundBorder;\nimport javax.swing.border.MatteBorder;\nimport javax.swing.table.DefaultTableCellRenderer;\nimport javax.swing.table.DefaultTableModel;\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\n\n/**\n * Modelo de levenstein\n * User: alberto\n * Date: 7/12/12\n * Time: 16:40\n */\npublic class LevenshteinTableModel extends DefaultTableModel {\n\n String origin;\n\n String destiny;\n\n private JMRevision currentRevision;\n\n private FilePanel[] filePanels;\n\n private HashMap routeDiff;\n\n private HashMap borderChunks;\n\n private HashMap borderSelections;\n\n private boolean showSelectionPath;\n\n public void buildModel() {\n if (!isAllDataAvaliable()) {\n return;\n }\n borderSelections = new HashMap<>();\n setDataVector(newVector(origin.length() + 2), newVector(destiny.length() + 2));\n buildSolutionPath();\n int rowCount = getRowCount();\n int columnCount = getColumnCount();\n for (int columna = 0; columna < columnCount; columna++) {\n if (columna < 2) {\n setValueAt(\"\", 0, columna);\n } else {\n setValueAt(destiny.charAt(columna - 2), 0, columna);\n }\n }\n for (int fila = 0; fila < rowCount; fila++) {\n if (fila < 2) {\n setValueAt(\"\", fila, 0);\n } else {\n setValueAt(origin.charAt(fila - 2), fila, 0);\n }\n }\n int minLength = rowCount > columnCount ? columnCount : rowCount;\n for (int diagonal = 1; diagonal < minLength; diagonal++) {\n if (diagonal == 1) {\n setValueAt(0, diagonal, diagonal);\n } else {\n Object o = getValueAt(diagonal - 1, diagonal - 1);\n int incremento;\n if (origin.charAt(diagonal - 2) == destiny.charAt(diagonal - 2)) {\n incremento = 0;\n } else {\n incremento = 1;\n }\n setValueAt((Integer) o + incremento, diagonal, diagonal);\n }\n for (int columna = diagonal + 1; columna < columnCount; columna++) {\n setValueAt((Integer) getValueAt(diagonal, columna - 1) + 1, diagonal, columna);\n }\n for (int fila = diagonal + 1; fila < rowCount; fila++) {\n setValueAt((Integer) getValueAt(fila - 1, diagonal) + 1, fila, diagonal);\n }\n }\n }\n\n private boolean isAllDataAvaliable() {\n return getFilePanels() != null && getCurrentRevision() != null && origin != null && destiny != null;\n }\n\n class ColorPoint extends Point {\n\n Color color;\n\n public ColorPoint(int x, int y, Color color) {\n super(x, y);\n this.color = color;\n }\n }\n\n private void buildSolutionPath() {\n BufferDocumentIF originalBufferDocument = filePanels[BufferDiffPanel.LEFT].getBufferDocument();\n BufferDocumentIF revisedBufferDocument = filePanels[BufferDiffPanel.RIGHT].getBufferDocument();\n java.util.List deltas = currentRevision.getDeltas();\n routeDiff = new HashMap<>();\n borderChunks = new HashMap<>();\n int xOffset = 0;\n int yOffset = 0;\n ", "post_mask_code": "\n\n private void addBorderChunks(Point point, MatteBorder border) {\n MatteBorder oldborder = borderChunks.get(point);\n if (oldborder != null) {\n Insets oldborderInsets = oldborder.getBorderInsets();\n Insets borderInsets = border.getBorderInsets();\n if (oldborderInsets.top == 0 && borderInsets.top > 0) {\n oldborderInsets.top = borderInsets.top;\n }\n if (oldborderInsets.left == 0 && borderInsets.left > 0) {\n oldborderInsets.left = borderInsets.left;\n }\n if (oldborderInsets.right == 0 && borderInsets.right > 0) {\n oldborderInsets.right = borderInsets.right;\n }\n if (oldborderInsets.bottom == 0 && borderInsets.bottom > 0) {\n oldborderInsets.bottom = borderInsets.bottom;\n }\n border = BorderFactory.createMatteBorder(oldborderInsets.top, oldborderInsets.left, oldborderInsets.bottom, oldborderInsets.right, border.getMatteColor());\n }\n borderChunks.put(point, border);\n }\n\n private Vector newVector(int size) {\n Vector vector = new Vector(size);\n vector.setSize(size);\n return vector;\n }\n\n public String getOrigin() {\n return origin;\n }\n\n public void setOrigin(String origin) {\n this.origin = origin;\n buildModel();\n }\n\n public String getDestiny() {\n return destiny;\n }\n\n public void setDestiny(String destiny) {\n this.destiny = destiny;\n buildModel();\n }\n\n public DefaultTableCellRenderer getCellRenderer() {\n return new DefaultTableCellRenderer() {\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n if (\"\\n\".equals(value.toString())) {\n value = \"\\\\n\";\n }\n Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n Color background = Color.WHITE;\n if (row < 2 && column < 2) {\n if (row == column) {\n background = Color.GREEN;\n } else {\n background = Color.BLUE;\n }\n } else {\n if (row > 1) {\n if (column > 1) {\n if (origin.charAt(row - 2) == destiny.charAt(column - 2)) {\n background = Color.ORANGE;\n }\n }\n }\n if (row == 0 || column == 0) {\n background = new Color(0x550099FF, true);\n }\n }\n if (isSelected || table.isColumnSelected(column)) {\n Color newColor = Color.CYAN;\n Color mixColor = Color.WHITE;\n background = new Color(background.getRed() * newColor.getRed() / mixColor.getRed(), background.getGreen() * newColor.getGreen() / mixColor.getGreen(), background.getBlue() * newColor.getBlue() / mixColor.getBlue());\n }\n Point point = new Point(row - 2, column - 2);\n if (showSelectionPath) {\n Color color = routeDiff.get(point);\n if (color != null) {\n background = color;\n }\n }\n Border border = borderChunks.get(point);\n Border borderSelection = borderSelections.get(point);\n if (border == null) {\n if (borderSelection != null) {\n border = borderSelection;\n }\n } else {\n if (borderSelection != null) {\n border = new CompoundBorder(border, borderSelection);\n }\n }\n if (border != null) {\n ((JLabel) tableCellRendererComponent).setBorder(border);\n }\n tableCellRendererComponent.setBackground(background);\n ((JLabel) tableCellRendererComponent).setHorizontalAlignment(SwingConstants.CENTER);\n return tableCellRendererComponent;\n }\n };\n }\n\n public void setCurrentRevision(JMRevision currentRevision) {\n this.currentRevision = currentRevision;\n buildModel();\n }\n\n public JMRevision getCurrentRevision() {\n return currentRevision;\n }\n\n public void setFilePanels(FilePanel[] filePanels) {\n this.filePanels = filePanels;\n buildModel();\n }\n\n public FilePanel[] getFilePanels() {\n return filePanels;\n }\n\n public boolean isShowSelectionPath() {\n return showSelectionPath;\n }\n\n public void setShowSelectionPath(boolean showSelectionPath) {\n this.showSelectionPath = showSelectionPath;\n }\n\n public HashMap getBorderSelections() {\n return borderSelections;\n }\n\n public void setBorderSelections(HashMap borderSelection) {\n this.borderSelections = borderSelection;\n }\n}\n"} {"task_id": "Java_1045", "language": "Java", "task_type": "single_line", "source_file": "java/github/albfan/jmeld/src/main/java/org/jmeld/model/LevenshteinTableModel.java", "mask_start_position": 13961, "mask_end_position": 13967, "canonical_solution": "WHITE;", "pre_mask_code": "package org.jmeld.model;\n\nimport org.jmeld.diff.JMChunk;\nimport org.jmeld.diff.JMDelta;\nimport org.jmeld.diff.JMRevision;\nimport org.jmeld.ui.BufferDiffPanel;\nimport org.jmeld.ui.FilePanel;\nimport org.jmeld.ui.text.BufferDocumentIF;\nimport org.jmeld.ui.util.Colors;\nimport javax.swing.*;\nimport javax.swing.border.Border;\nimport javax.swing.border.CompoundBorder;\nimport javax.swing.border.MatteBorder;\nimport javax.swing.table.DefaultTableCellRenderer;\nimport javax.swing.table.DefaultTableModel;\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\n\n/**\n * Modelo de levenstein\n * User: alberto\n * Date: 7/12/12\n * Time: 16:40\n */\npublic class LevenshteinTableModel extends DefaultTableModel {\n\n String origin;\n\n String destiny;\n\n private JMRevision currentRevision;\n\n private FilePanel[] filePanels;\n\n private HashMap routeDiff;\n\n private HashMap borderChunks;\n\n private HashMap borderSelections;\n\n private boolean showSelectionPath;\n\n public void buildModel() {\n if (!isAllDataAvaliable()) {\n return;\n }\n borderSelections = new HashMap<>();\n setDataVector(newVector(origin.length() + 2), newVector(destiny.length() + 2));\n buildSolutionPath();\n int rowCount = getRowCount();\n int columnCount = getColumnCount();\n for (int columna = 0; columna < columnCount; columna++) {\n if (columna < 2) {\n setValueAt(\"\", 0, columna);\n } else {\n setValueAt(destiny.charAt(columna - 2), 0, columna);\n }\n }\n for (int fila = 0; fila < rowCount; fila++) {\n if (fila < 2) {\n setValueAt(\"\", fila, 0);\n } else {\n setValueAt(origin.charAt(fila - 2), fila, 0);\n }\n }\n int minLength = rowCount > columnCount ? columnCount : rowCount;\n for (int diagonal = 1; diagonal < minLength; diagonal++) {\n if (diagonal == 1) {\n setValueAt(0, diagonal, diagonal);\n } else {\n Object o = getValueAt(diagonal - 1, diagonal - 1);\n int incremento;\n if (origin.charAt(diagonal - 2) == destiny.charAt(diagonal - 2)) {\n incremento = 0;\n } else {\n incremento = 1;\n }\n setValueAt((Integer) o + incremento, diagonal, diagonal);\n }\n for (int columna = diagonal + 1; columna < columnCount; columna++) {\n setValueAt((Integer) getValueAt(diagonal, columna - 1) + 1, diagonal, columna);\n }\n for (int fila = diagonal + 1; fila < rowCount; fila++) {\n setValueAt((Integer) getValueAt(fila - 1, diagonal) + 1, fila, diagonal);\n }\n }\n }\n\n private boolean isAllDataAvaliable() {\n return getFilePanels() != null && getCurrentRevision() != null && origin != null && destiny != null;\n }\n\n class ColorPoint extends Point {\n\n Color color;\n\n public ColorPoint(int x, int y, Color color) {\n super(x, y);\n this.color = color;\n }\n }\n\n private void buildSolutionPath() {\n BufferDocumentIF originalBufferDocument = filePanels[BufferDiffPanel.LEFT].getBufferDocument();\n BufferDocumentIF revisedBufferDocument = filePanels[BufferDiffPanel.RIGHT].getBufferDocument();\n java.util.List deltas = currentRevision.getDeltas();\n routeDiff = new HashMap<>();\n borderChunks = new HashMap<>();\n int xOffset = 0;\n int yOffset = 0;\n for (Iterator iterator = deltas.iterator(); iterator.hasNext(); ) {\n JMDelta next = iterator.next();\n JMChunk original = next.getOriginal();\n JMChunk revised = next.getRevised();\n int originalLines = originalBufferDocument.getNumberOfLines();\n int revisedLines = revisedBufferDocument.getNumberOfLines();\n int offsetForLineOriginal;\n if (original.getAnchor() == originalLines) {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor() - 1) + 1;\n } else {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor());\n }\n int offsetForLineRevised;\n if (revised.getAnchor() == revisedLines) {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor() - 1) + 1;\n } else {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor());\n }\n for (int i = 0; i < offsetForLineOriginal - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n if (next.isAdd()) {\n int lineNumber = revised.getAnchor() + revised.getSize() - 1;\n int yOffsetForLineEnd = revisedBufferDocument.getOffsetForLine(lineNumber) + +revisedBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < yOffsetForLineEnd - offsetForLineRevised; i++) {\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 2, 0, Color.BLACK);\n } else if (i == yOffsetForLineEnd - offsetForLineRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 2, 0, Color.BLACK);\n }\n Point point = new Point(offsetForLineOriginal - 1, i + offsetForLineRevised);\n addBorderChunks(point, border);\n routeDiff.put(point, Colors.ADDED);\n }\n xOffset = offsetForLineOriginal;\n yOffset = yOffsetForLineEnd;\n } else if (next.isDelete()) {\n int lineNumber = original.getAnchor() + original.getSize() - 1;\n int xOffsetForLine = originalBufferDocument.getOffsetForLine(lineNumber) + originalBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < xOffsetForLine - offsetForLineOriginal; i++) {\n Point point = new Point(i + offsetForLineOriginal, offsetForLineRevised - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 0, 2, Color.BLACK);\n } else if (i == xOffsetForLine - offsetForLineOriginal - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 2, 0, 2, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset = xOffsetForLine;\n yOffset = offsetForLineRevised;\n } else if (next.isChange()) {\n List changedDeltas = next.getChangeRevision().getDeltas();\n xOffset = offsetForLineOriginal;\n yOffset = offsetForLineRevised;\n for (Iterator jmDeltaIterator = changedDeltas.iterator(); jmDeltaIterator.hasNext(); ) {\n JMDelta changeDelta = jmDeltaIterator.next();\n JMChunk originalChange = changeDelta.getOriginal();\n JMChunk revisedChange = changeDelta.getRevised();\n int sameChars = originalChange.getAnchor() - xOffset;\n for (int i = 0; i < sameChars; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n xOffset += sameChars;\n yOffset += sameChars;\n int removeFromOrigin = originalChange.getSize();\n int addFromRevised = revisedChange.getSize();\n for (int i = 0; i < removeFromOrigin; i++) {\n Point point = new Point(i + xOffset, yOffset - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == removeFromOrigin - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 0, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(new Point(i + xOffset, yOffset - 1 + addFromRevised), border);\n border = BorderFactory.createMatteBorder(0, 2, 0, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset += removeFromOrigin;\n if (addFromRevised == 0) {\n Point point = new Point(xOffset - 1, yOffset - 1);\n MatteBorder border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(point, border);\n }\n for (int i = 0; i < addFromRevised; i++) {\n Point point = new Point(xOffset - 1, i + yOffset);\n routeDiff.put(point, Colors.ADDED);\n MatteBorder border;\n if (i == 0 && removeFromOrigin == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i - 1 + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(0, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n yOffset += addFromRevised;\n }\n }\n }\n int xSize = originalBufferDocument.getDocument().getLength();\n for (int i = 0; i < xSize - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n }\n\n private void addBorderChunks(Point point, MatteBorder border) {\n MatteBorder oldborder = borderChunks.get(point);\n if (oldborder != null) {\n Insets oldborderInsets = oldborder.getBorderInsets();\n Insets borderInsets = border.getBorderInsets();\n if (oldborderInsets.top == 0 && borderInsets.top > 0) {\n oldborderInsets.top = borderInsets.top;\n }\n if (oldborderInsets.left == 0 && borderInsets.left > 0) {\n oldborderInsets.left = borderInsets.left;\n }\n if (oldborderInsets.right == 0 && borderInsets.right > 0) {\n oldborderInsets.right = borderInsets.right;\n }\n if (oldborderInsets.bottom == 0 && borderInsets.bottom > 0) {\n oldborderInsets.bottom = borderInsets.bottom;\n }\n border = BorderFactory.createMatteBorder(oldborderInsets.top, oldborderInsets.left, oldborderInsets.bottom, oldborderInsets.right, border.getMatteColor());\n }\n borderChunks.put(point, border);\n }\n\n private Vector newVector(int size) {\n Vector vector = new Vector(size);\n vector.setSize(size);\n return vector;\n }\n\n public String getOrigin() {\n return origin;\n }\n\n public void setOrigin(String origin) {\n this.origin = origin;\n buildModel();\n }\n\n public String getDestiny() {\n return destiny;\n }\n\n public void setDestiny(String destiny) {\n this.destiny = destiny;\n buildModel();\n }\n\n public DefaultTableCellRenderer getCellRenderer() {\n return new DefaultTableCellRenderer() {\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n if (\"\\n\".equals(value.toString())) {\n value = \"\\\\n\";\n }\n Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n Color background = Color.", "post_mask_code": "\n if (row < 2 && column < 2) {\n if (row == column) {\n background = Color.GREEN;\n } else {\n background = Color.BLUE;\n }\n } else {\n if (row > 1) {\n if (column > 1) {\n if (origin.charAt(row - 2) == destiny.charAt(column - 2)) {\n background = Color.ORANGE;\n }\n }\n }\n if (row == 0 || column == 0) {\n background = new Color(0x550099FF, true);\n }\n }\n if (isSelected || table.isColumnSelected(column)) {\n Color newColor = Color.CYAN;\n Color mixColor = Color.WHITE;\n background = new Color(background.getRed() * newColor.getRed() / mixColor.getRed(), background.getGreen() * newColor.getGreen() / mixColor.getGreen(), background.getBlue() * newColor.getBlue() / mixColor.getBlue());\n }\n Point point = new Point(row - 2, column - 2);\n if (showSelectionPath) {\n Color color = routeDiff.get(point);\n if (color != null) {\n background = color;\n }\n }\n Border border = borderChunks.get(point);\n Border borderSelection = borderSelections.get(point);\n if (border == null) {\n if (borderSelection != null) {\n border = borderSelection;\n }\n } else {\n if (borderSelection != null) {\n border = new CompoundBorder(border, borderSelection);\n }\n }\n if (border != null) {\n ((JLabel) tableCellRendererComponent).setBorder(border);\n }\n tableCellRendererComponent.setBackground(background);\n ((JLabel) tableCellRendererComponent).setHorizontalAlignment(SwingConstants.CENTER);\n return tableCellRendererComponent;\n }\n };\n }\n\n public void setCurrentRevision(JMRevision currentRevision) {\n this.currentRevision = currentRevision;\n buildModel();\n }\n\n public JMRevision getCurrentRevision() {\n return currentRevision;\n }\n\n public void setFilePanels(FilePanel[] filePanels) {\n this.filePanels = filePanels;\n buildModel();\n }\n\n public FilePanel[] getFilePanels() {\n return filePanels;\n }\n\n public boolean isShowSelectionPath() {\n return showSelectionPath;\n }\n\n public void setShowSelectionPath(boolean showSelectionPath) {\n this.showSelectionPath = showSelectionPath;\n }\n\n public HashMap getBorderSelections() {\n return borderSelections;\n }\n\n public void setBorderSelections(HashMap borderSelection) {\n this.borderSelections = borderSelection;\n }\n}\n"} {"task_id": "Java_1046", "language": "Java", "task_type": "if_statement", "source_file": "java/github/albfan/jmeld/src/main/java/org/jmeld/model/LevenshteinTableModel.java", "mask_start_position": 15288, "mask_end_position": 15374, "canonical_solution": "if (color != null) {\n background = color;\n }", "pre_mask_code": "package org.jmeld.model;\n\nimport org.jmeld.diff.JMChunk;\nimport org.jmeld.diff.JMDelta;\nimport org.jmeld.diff.JMRevision;\nimport org.jmeld.ui.BufferDiffPanel;\nimport org.jmeld.ui.FilePanel;\nimport org.jmeld.ui.text.BufferDocumentIF;\nimport org.jmeld.ui.util.Colors;\nimport javax.swing.*;\nimport javax.swing.border.Border;\nimport javax.swing.border.CompoundBorder;\nimport javax.swing.border.MatteBorder;\nimport javax.swing.table.DefaultTableCellRenderer;\nimport javax.swing.table.DefaultTableModel;\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\n\n/**\n * Modelo de levenstein\n * User: alberto\n * Date: 7/12/12\n * Time: 16:40\n */\npublic class LevenshteinTableModel extends DefaultTableModel {\n\n String origin;\n\n String destiny;\n\n private JMRevision currentRevision;\n\n private FilePanel[] filePanels;\n\n private HashMap routeDiff;\n\n private HashMap borderChunks;\n\n private HashMap borderSelections;\n\n private boolean showSelectionPath;\n\n public void buildModel() {\n if (!isAllDataAvaliable()) {\n return;\n }\n borderSelections = new HashMap<>();\n setDataVector(newVector(origin.length() + 2), newVector(destiny.length() + 2));\n buildSolutionPath();\n int rowCount = getRowCount();\n int columnCount = getColumnCount();\n for (int columna = 0; columna < columnCount; columna++) {\n if (columna < 2) {\n setValueAt(\"\", 0, columna);\n } else {\n setValueAt(destiny.charAt(columna - 2), 0, columna);\n }\n }\n for (int fila = 0; fila < rowCount; fila++) {\n if (fila < 2) {\n setValueAt(\"\", fila, 0);\n } else {\n setValueAt(origin.charAt(fila - 2), fila, 0);\n }\n }\n int minLength = rowCount > columnCount ? columnCount : rowCount;\n for (int diagonal = 1; diagonal < minLength; diagonal++) {\n if (diagonal == 1) {\n setValueAt(0, diagonal, diagonal);\n } else {\n Object o = getValueAt(diagonal - 1, diagonal - 1);\n int incremento;\n if (origin.charAt(diagonal - 2) == destiny.charAt(diagonal - 2)) {\n incremento = 0;\n } else {\n incremento = 1;\n }\n setValueAt((Integer) o + incremento, diagonal, diagonal);\n }\n for (int columna = diagonal + 1; columna < columnCount; columna++) {\n setValueAt((Integer) getValueAt(diagonal, columna - 1) + 1, diagonal, columna);\n }\n for (int fila = diagonal + 1; fila < rowCount; fila++) {\n setValueAt((Integer) getValueAt(fila - 1, diagonal) + 1, fila, diagonal);\n }\n }\n }\n\n private boolean isAllDataAvaliable() {\n return getFilePanels() != null && getCurrentRevision() != null && origin != null && destiny != null;\n }\n\n class ColorPoint extends Point {\n\n Color color;\n\n public ColorPoint(int x, int y, Color color) {\n super(x, y);\n this.color = color;\n }\n }\n\n private void buildSolutionPath() {\n BufferDocumentIF originalBufferDocument = filePanels[BufferDiffPanel.LEFT].getBufferDocument();\n BufferDocumentIF revisedBufferDocument = filePanels[BufferDiffPanel.RIGHT].getBufferDocument();\n java.util.List deltas = currentRevision.getDeltas();\n routeDiff = new HashMap<>();\n borderChunks = new HashMap<>();\n int xOffset = 0;\n int yOffset = 0;\n for (Iterator iterator = deltas.iterator(); iterator.hasNext(); ) {\n JMDelta next = iterator.next();\n JMChunk original = next.getOriginal();\n JMChunk revised = next.getRevised();\n int originalLines = originalBufferDocument.getNumberOfLines();\n int revisedLines = revisedBufferDocument.getNumberOfLines();\n int offsetForLineOriginal;\n if (original.getAnchor() == originalLines) {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor() - 1) + 1;\n } else {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor());\n }\n int offsetForLineRevised;\n if (revised.getAnchor() == revisedLines) {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor() - 1) + 1;\n } else {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor());\n }\n for (int i = 0; i < offsetForLineOriginal - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n if (next.isAdd()) {\n int lineNumber = revised.getAnchor() + revised.getSize() - 1;\n int yOffsetForLineEnd = revisedBufferDocument.getOffsetForLine(lineNumber) + +revisedBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < yOffsetForLineEnd - offsetForLineRevised; i++) {\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 2, 0, Color.BLACK);\n } else if (i == yOffsetForLineEnd - offsetForLineRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 2, 0, Color.BLACK);\n }\n Point point = new Point(offsetForLineOriginal - 1, i + offsetForLineRevised);\n addBorderChunks(point, border);\n routeDiff.put(point, Colors.ADDED);\n }\n xOffset = offsetForLineOriginal;\n yOffset = yOffsetForLineEnd;\n } else if (next.isDelete()) {\n int lineNumber = original.getAnchor() + original.getSize() - 1;\n int xOffsetForLine = originalBufferDocument.getOffsetForLine(lineNumber) + originalBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < xOffsetForLine - offsetForLineOriginal; i++) {\n Point point = new Point(i + offsetForLineOriginal, offsetForLineRevised - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 0, 2, Color.BLACK);\n } else if (i == xOffsetForLine - offsetForLineOriginal - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 2, 0, 2, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset = xOffsetForLine;\n yOffset = offsetForLineRevised;\n } else if (next.isChange()) {\n List changedDeltas = next.getChangeRevision().getDeltas();\n xOffset = offsetForLineOriginal;\n yOffset = offsetForLineRevised;\n for (Iterator jmDeltaIterator = changedDeltas.iterator(); jmDeltaIterator.hasNext(); ) {\n JMDelta changeDelta = jmDeltaIterator.next();\n JMChunk originalChange = changeDelta.getOriginal();\n JMChunk revisedChange = changeDelta.getRevised();\n int sameChars = originalChange.getAnchor() - xOffset;\n for (int i = 0; i < sameChars; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n xOffset += sameChars;\n yOffset += sameChars;\n int removeFromOrigin = originalChange.getSize();\n int addFromRevised = revisedChange.getSize();\n for (int i = 0; i < removeFromOrigin; i++) {\n Point point = new Point(i + xOffset, yOffset - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == removeFromOrigin - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 0, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(new Point(i + xOffset, yOffset - 1 + addFromRevised), border);\n border = BorderFactory.createMatteBorder(0, 2, 0, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset += removeFromOrigin;\n if (addFromRevised == 0) {\n Point point = new Point(xOffset - 1, yOffset - 1);\n MatteBorder border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(point, border);\n }\n for (int i = 0; i < addFromRevised; i++) {\n Point point = new Point(xOffset - 1, i + yOffset);\n routeDiff.put(point, Colors.ADDED);\n MatteBorder border;\n if (i == 0 && removeFromOrigin == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i - 1 + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(0, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n yOffset += addFromRevised;\n }\n }\n }\n int xSize = originalBufferDocument.getDocument().getLength();\n for (int i = 0; i < xSize - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n }\n\n private void addBorderChunks(Point point, MatteBorder border) {\n MatteBorder oldborder = borderChunks.get(point);\n if (oldborder != null) {\n Insets oldborderInsets = oldborder.getBorderInsets();\n Insets borderInsets = border.getBorderInsets();\n if (oldborderInsets.top == 0 && borderInsets.top > 0) {\n oldborderInsets.top = borderInsets.top;\n }\n if (oldborderInsets.left == 0 && borderInsets.left > 0) {\n oldborderInsets.left = borderInsets.left;\n }\n if (oldborderInsets.right == 0 && borderInsets.right > 0) {\n oldborderInsets.right = borderInsets.right;\n }\n if (oldborderInsets.bottom == 0 && borderInsets.bottom > 0) {\n oldborderInsets.bottom = borderInsets.bottom;\n }\n border = BorderFactory.createMatteBorder(oldborderInsets.top, oldborderInsets.left, oldborderInsets.bottom, oldborderInsets.right, border.getMatteColor());\n }\n borderChunks.put(point, border);\n }\n\n private Vector newVector(int size) {\n Vector vector = new Vector(size);\n vector.setSize(size);\n return vector;\n }\n\n public String getOrigin() {\n return origin;\n }\n\n public void setOrigin(String origin) {\n this.origin = origin;\n buildModel();\n }\n\n public String getDestiny() {\n return destiny;\n }\n\n public void setDestiny(String destiny) {\n this.destiny = destiny;\n buildModel();\n }\n\n public DefaultTableCellRenderer getCellRenderer() {\n return new DefaultTableCellRenderer() {\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n if (\"\\n\".equals(value.toString())) {\n value = \"\\\\n\";\n }\n Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n Color background = Color.WHITE;\n if (row < 2 && column < 2) {\n if (row == column) {\n background = Color.GREEN;\n } else {\n background = Color.BLUE;\n }\n } else {\n if (row > 1) {\n if (column > 1) {\n if (origin.charAt(row - 2) == destiny.charAt(column - 2)) {\n background = Color.ORANGE;\n }\n }\n }\n if (row == 0 || column == 0) {\n background = new Color(0x550099FF, true);\n }\n }\n if (isSelected || table.isColumnSelected(column)) {\n Color newColor = Color.CYAN;\n Color mixColor = Color.WHITE;\n background = new Color(background.getRed() * newColor.getRed() / mixColor.getRed(), background.getGreen() * newColor.getGreen() / mixColor.getGreen(), background.getBlue() * newColor.getBlue() / mixColor.getBlue());\n }\n Point point = new Point(row - 2, column - 2);\n if (showSelectionPath) {\n Color color = routeDiff.get(point);\n ", "post_mask_code": "\n }\n Border border = borderChunks.get(point);\n Border borderSelection = borderSelections.get(point);\n if (border == null) {\n if (borderSelection != null) {\n border = borderSelection;\n }\n } else {\n if (borderSelection != null) {\n border = new CompoundBorder(border, borderSelection);\n }\n }\n if (border != null) {\n ((JLabel) tableCellRendererComponent).setBorder(border);\n }\n tableCellRendererComponent.setBackground(background);\n ((JLabel) tableCellRendererComponent).setHorizontalAlignment(SwingConstants.CENTER);\n return tableCellRendererComponent;\n }\n };\n }\n\n public void setCurrentRevision(JMRevision currentRevision) {\n this.currentRevision = currentRevision;\n buildModel();\n }\n\n public JMRevision getCurrentRevision() {\n return currentRevision;\n }\n\n public void setFilePanels(FilePanel[] filePanels) {\n this.filePanels = filePanels;\n buildModel();\n }\n\n public FilePanel[] getFilePanels() {\n return filePanels;\n }\n\n public boolean isShowSelectionPath() {\n return showSelectionPath;\n }\n\n public void setShowSelectionPath(boolean showSelectionPath) {\n this.showSelectionPath = showSelectionPath;\n }\n\n public HashMap getBorderSelections() {\n return borderSelections;\n }\n\n public void setBorderSelections(HashMap borderSelection) {\n this.borderSelections = borderSelection;\n }\n}\n"} {"task_id": "Java_1047", "language": "Java", "task_type": "for_statement", "source_file": "java/github/albfan/jmeld/src/main/java/org/jmeld/model/LevenshteinTableModel.java", "mask_start_position": 2493, "mask_end_position": 2671, "canonical_solution": "for (int columna = diagonal + 1; columna < columnCount; columna++) {\n setValueAt((Integer) getValueAt(diagonal, columna - 1) + 1, diagonal, columna);\n }", "pre_mask_code": "package org.jmeld.model;\n\nimport org.jmeld.diff.JMChunk;\nimport org.jmeld.diff.JMDelta;\nimport org.jmeld.diff.JMRevision;\nimport org.jmeld.ui.BufferDiffPanel;\nimport org.jmeld.ui.FilePanel;\nimport org.jmeld.ui.text.BufferDocumentIF;\nimport org.jmeld.ui.util.Colors;\nimport javax.swing.*;\nimport javax.swing.border.Border;\nimport javax.swing.border.CompoundBorder;\nimport javax.swing.border.MatteBorder;\nimport javax.swing.table.DefaultTableCellRenderer;\nimport javax.swing.table.DefaultTableModel;\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\n\n/**\n * Modelo de levenstein\n * User: alberto\n * Date: 7/12/12\n * Time: 16:40\n */\npublic class LevenshteinTableModel extends DefaultTableModel {\n\n String origin;\n\n String destiny;\n\n private JMRevision currentRevision;\n\n private FilePanel[] filePanels;\n\n private HashMap routeDiff;\n\n private HashMap borderChunks;\n\n private HashMap borderSelections;\n\n private boolean showSelectionPath;\n\n public void buildModel() {\n if (!isAllDataAvaliable()) {\n return;\n }\n borderSelections = new HashMap<>();\n setDataVector(newVector(origin.length() + 2), newVector(destiny.length() + 2));\n buildSolutionPath();\n int rowCount = getRowCount();\n int columnCount = getColumnCount();\n for (int columna = 0; columna < columnCount; columna++) {\n if (columna < 2) {\n setValueAt(\"\", 0, columna);\n } else {\n setValueAt(destiny.charAt(columna - 2), 0, columna);\n }\n }\n for (int fila = 0; fila < rowCount; fila++) {\n if (fila < 2) {\n setValueAt(\"\", fila, 0);\n } else {\n setValueAt(origin.charAt(fila - 2), fila, 0);\n }\n }\n int minLength = rowCount > columnCount ? columnCount : rowCount;\n for (int diagonal = 1; diagonal < minLength; diagonal++) {\n if (diagonal == 1) {\n setValueAt(0, diagonal, diagonal);\n } else {\n Object o = getValueAt(diagonal - 1, diagonal - 1);\n int incremento;\n if (origin.charAt(diagonal - 2) == destiny.charAt(diagonal - 2)) {\n incremento = 0;\n } else {\n incremento = 1;\n }\n setValueAt((Integer) o + incremento, diagonal, diagonal);\n }\n ", "post_mask_code": "\n for (int fila = diagonal + 1; fila < rowCount; fila++) {\n setValueAt((Integer) getValueAt(fila - 1, diagonal) + 1, fila, diagonal);\n }\n }\n }\n\n private boolean isAllDataAvaliable() {\n return getFilePanels() != null && getCurrentRevision() != null && origin != null && destiny != null;\n }\n\n class ColorPoint extends Point {\n\n Color color;\n\n public ColorPoint(int x, int y, Color color) {\n super(x, y);\n this.color = color;\n }\n }\n\n private void buildSolutionPath() {\n BufferDocumentIF originalBufferDocument = filePanels[BufferDiffPanel.LEFT].getBufferDocument();\n BufferDocumentIF revisedBufferDocument = filePanels[BufferDiffPanel.RIGHT].getBufferDocument();\n java.util.List deltas = currentRevision.getDeltas();\n routeDiff = new HashMap<>();\n borderChunks = new HashMap<>();\n int xOffset = 0;\n int yOffset = 0;\n for (Iterator iterator = deltas.iterator(); iterator.hasNext(); ) {\n JMDelta next = iterator.next();\n JMChunk original = next.getOriginal();\n JMChunk revised = next.getRevised();\n int originalLines = originalBufferDocument.getNumberOfLines();\n int revisedLines = revisedBufferDocument.getNumberOfLines();\n int offsetForLineOriginal;\n if (original.getAnchor() == originalLines) {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor() - 1) + 1;\n } else {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor());\n }\n int offsetForLineRevised;\n if (revised.getAnchor() == revisedLines) {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor() - 1) + 1;\n } else {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor());\n }\n for (int i = 0; i < offsetForLineOriginal - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n if (next.isAdd()) {\n int lineNumber = revised.getAnchor() + revised.getSize() - 1;\n int yOffsetForLineEnd = revisedBufferDocument.getOffsetForLine(lineNumber) + +revisedBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < yOffsetForLineEnd - offsetForLineRevised; i++) {\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 2, 0, Color.BLACK);\n } else if (i == yOffsetForLineEnd - offsetForLineRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 2, 0, Color.BLACK);\n }\n Point point = new Point(offsetForLineOriginal - 1, i + offsetForLineRevised);\n addBorderChunks(point, border);\n routeDiff.put(point, Colors.ADDED);\n }\n xOffset = offsetForLineOriginal;\n yOffset = yOffsetForLineEnd;\n } else if (next.isDelete()) {\n int lineNumber = original.getAnchor() + original.getSize() - 1;\n int xOffsetForLine = originalBufferDocument.getOffsetForLine(lineNumber) + originalBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < xOffsetForLine - offsetForLineOriginal; i++) {\n Point point = new Point(i + offsetForLineOriginal, offsetForLineRevised - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 0, 2, Color.BLACK);\n } else if (i == xOffsetForLine - offsetForLineOriginal - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 2, 0, 2, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset = xOffsetForLine;\n yOffset = offsetForLineRevised;\n } else if (next.isChange()) {\n List changedDeltas = next.getChangeRevision().getDeltas();\n xOffset = offsetForLineOriginal;\n yOffset = offsetForLineRevised;\n for (Iterator jmDeltaIterator = changedDeltas.iterator(); jmDeltaIterator.hasNext(); ) {\n JMDelta changeDelta = jmDeltaIterator.next();\n JMChunk originalChange = changeDelta.getOriginal();\n JMChunk revisedChange = changeDelta.getRevised();\n int sameChars = originalChange.getAnchor() - xOffset;\n for (int i = 0; i < sameChars; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n xOffset += sameChars;\n yOffset += sameChars;\n int removeFromOrigin = originalChange.getSize();\n int addFromRevised = revisedChange.getSize();\n for (int i = 0; i < removeFromOrigin; i++) {\n Point point = new Point(i + xOffset, yOffset - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == removeFromOrigin - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 0, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(new Point(i + xOffset, yOffset - 1 + addFromRevised), border);\n border = BorderFactory.createMatteBorder(0, 2, 0, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset += removeFromOrigin;\n if (addFromRevised == 0) {\n Point point = new Point(xOffset - 1, yOffset - 1);\n MatteBorder border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(point, border);\n }\n for (int i = 0; i < addFromRevised; i++) {\n Point point = new Point(xOffset - 1, i + yOffset);\n routeDiff.put(point, Colors.ADDED);\n MatteBorder border;\n if (i == 0 && removeFromOrigin == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i - 1 + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(0, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n yOffset += addFromRevised;\n }\n }\n }\n int xSize = originalBufferDocument.getDocument().getLength();\n for (int i = 0; i < xSize - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n }\n\n private void addBorderChunks(Point point, MatteBorder border) {\n MatteBorder oldborder = borderChunks.get(point);\n if (oldborder != null) {\n Insets oldborderInsets = oldborder.getBorderInsets();\n Insets borderInsets = border.getBorderInsets();\n if (oldborderInsets.top == 0 && borderInsets.top > 0) {\n oldborderInsets.top = borderInsets.top;\n }\n if (oldborderInsets.left == 0 && borderInsets.left > 0) {\n oldborderInsets.left = borderInsets.left;\n }\n if (oldborderInsets.right == 0 && borderInsets.right > 0) {\n oldborderInsets.right = borderInsets.right;\n }\n if (oldborderInsets.bottom == 0 && borderInsets.bottom > 0) {\n oldborderInsets.bottom = borderInsets.bottom;\n }\n border = BorderFactory.createMatteBorder(oldborderInsets.top, oldborderInsets.left, oldborderInsets.bottom, oldborderInsets.right, border.getMatteColor());\n }\n borderChunks.put(point, border);\n }\n\n private Vector newVector(int size) {\n Vector vector = new Vector(size);\n vector.setSize(size);\n return vector;\n }\n\n public String getOrigin() {\n return origin;\n }\n\n public void setOrigin(String origin) {\n this.origin = origin;\n buildModel();\n }\n\n public String getDestiny() {\n return destiny;\n }\n\n public void setDestiny(String destiny) {\n this.destiny = destiny;\n buildModel();\n }\n\n public DefaultTableCellRenderer getCellRenderer() {\n return new DefaultTableCellRenderer() {\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n if (\"\\n\".equals(value.toString())) {\n value = \"\\\\n\";\n }\n Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n Color background = Color.WHITE;\n if (row < 2 && column < 2) {\n if (row == column) {\n background = Color.GREEN;\n } else {\n background = Color.BLUE;\n }\n } else {\n if (row > 1) {\n if (column > 1) {\n if (origin.charAt(row - 2) == destiny.charAt(column - 2)) {\n background = Color.ORANGE;\n }\n }\n }\n if (row == 0 || column == 0) {\n background = new Color(0x550099FF, true);\n }\n }\n if (isSelected || table.isColumnSelected(column)) {\n Color newColor = Color.CYAN;\n Color mixColor = Color.WHITE;\n background = new Color(background.getRed() * newColor.getRed() / mixColor.getRed(), background.getGreen() * newColor.getGreen() / mixColor.getGreen(), background.getBlue() * newColor.getBlue() / mixColor.getBlue());\n }\n Point point = new Point(row - 2, column - 2);\n if (showSelectionPath) {\n Color color = routeDiff.get(point);\n if (color != null) {\n background = color;\n }\n }\n Border border = borderChunks.get(point);\n Border borderSelection = borderSelections.get(point);\n if (border == null) {\n if (borderSelection != null) {\n border = borderSelection;\n }\n } else {\n if (borderSelection != null) {\n border = new CompoundBorder(border, borderSelection);\n }\n }\n if (border != null) {\n ((JLabel) tableCellRendererComponent).setBorder(border);\n }\n tableCellRendererComponent.setBackground(background);\n ((JLabel) tableCellRendererComponent).setHorizontalAlignment(SwingConstants.CENTER);\n return tableCellRendererComponent;\n }\n };\n }\n\n public void setCurrentRevision(JMRevision currentRevision) {\n this.currentRevision = currentRevision;\n buildModel();\n }\n\n public JMRevision getCurrentRevision() {\n return currentRevision;\n }\n\n public void setFilePanels(FilePanel[] filePanels) {\n this.filePanels = filePanels;\n buildModel();\n }\n\n public FilePanel[] getFilePanels() {\n return filePanels;\n }\n\n public boolean isShowSelectionPath() {\n return showSelectionPath;\n }\n\n public void setShowSelectionPath(boolean showSelectionPath) {\n this.showSelectionPath = showSelectionPath;\n }\n\n public HashMap getBorderSelections() {\n return borderSelections;\n }\n\n public void setBorderSelections(HashMap borderSelection) {\n this.borderSelections = borderSelection;\n }\n}\n"} {"task_id": "Java_1048", "language": "Java", "task_type": "empty", "source_file": "java/github/albfan/jmeld/src/main/java/org/jmeld/model/LevenshteinTableModel.java", "mask_start_position": 3767, "mask_end_position": 3767, "canonical_solution": "", "pre_mask_code": "package org.jmeld.model;\n\nimport org.jmeld.diff.JMChunk;\nimport org.jmeld.diff.JMDelta;\nimport org.jmeld.diff.JMRevision;\nimport org.jmeld.ui.BufferDiffPanel;\nimport org.jmeld.ui.FilePanel;\nimport org.jmeld.ui.text.BufferDocumentIF;\nimport org.jmeld.ui.util.Colors;\nimport javax.swing.*;\nimport javax.swing.border.Border;\nimport javax.swing.border.CompoundBorder;\nimport javax.swing.border.MatteBorder;\nimport javax.swing.table.DefaultTableCellRenderer;\nimport javax.swing.table.DefaultTableModel;\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\n\n/**\n * Modelo de levenstein\n * User: alberto\n * Date: 7/12/12\n * Time: 16:40\n */\npublic class LevenshteinTableModel extends DefaultTableModel {\n\n String origin;\n\n String destiny;\n\n private JMRevision currentRevision;\n\n private FilePanel[] filePanels;\n\n private HashMap routeDiff;\n\n private HashMap borderChunks;\n\n private HashMap borderSelections;\n\n private boolean showSelectionPath;\n\n public void buildModel() {\n if (!isAllDataAvaliable()) {\n return;\n }\n borderSelections = new HashMap<>();\n setDataVector(newVector(origin.length() + 2), newVector(destiny.length() + 2));\n buildSolutionPath();\n int rowCount = getRowCount();\n int columnCount = getColumnCount();\n for (int columna = 0; columna < columnCount; columna++) {\n if (columna < 2) {\n setValueAt(\"\", 0, columna);\n } else {\n setValueAt(destiny.charAt(columna - 2), 0, columna);\n }\n }\n for (int fila = 0; fila < rowCount; fila++) {\n if (fila < 2) {\n setValueAt(\"\", fila, 0);\n } else {\n setValueAt(origin.charAt(fila - 2), fila, 0);\n }\n }\n int minLength = rowCount > columnCount ? columnCount : rowCount;\n for (int diagonal = 1; diagonal < minLength; diagonal++) {\n if (diagonal == 1) {\n setValueAt(0, diagonal, diagonal);\n } else {\n Object o = getValueAt(diagonal - 1, diagonal - 1);\n int incremento;\n if (origin.charAt(diagonal - 2) == destiny.charAt(diagonal - 2)) {\n incremento = 0;\n } else {\n incremento = 1;\n }\n setValueAt((Integer) o + incremento, diagonal, diagonal);\n }\n for (int columna = diagonal + 1; columna < columnCount; columna++) {\n setValueAt((Integer) getValueAt(diagonal, columna - 1) + 1, diagonal, columna);\n }\n for (int fila = diagonal + 1; fila < rowCount; fila++) {\n setValueAt((Integer) getValueAt(fila - 1, diagonal) + 1, fila, diagonal);\n }\n }\n }\n\n private boolean isAllDataAvaliable() {\n return getFilePanels() != null && getCurrentRevision() != null && origin != null && destiny != null;\n }\n\n class ColorPoint extends Point {\n\n Color color;\n\n public ColorPoint(int x, int y, Color color) {\n super(x, y);\n this.color = color;\n }\n }\n\n private void buildSolutionPath() {\n BufferDocumentIF originalBufferDocument = filePanels[BufferDiffPanel.LEFT].getBufferDocument();\n BufferDocumentIF revisedBufferDocument = filePanels[BufferDiffPanel.RIGHT].getBufferDocument();\n java.util.List deltas = currentRevision.getDeltas();\n routeDiff = new HashMap<>();\n borderChunks = new HashMap<>();\n int xOffset = 0;\n int yOffset = 0;\n for (Iterator iterator = deltas.iterator(); iterator.hasNext(); ) {\n JMDelta next = i", "post_mask_code": "terator.next();\n JMChunk original = next.getOriginal();\n JMChunk revised = next.getRevised();\n int originalLines = originalBufferDocument.getNumberOfLines();\n int revisedLines = revisedBufferDocument.getNumberOfLines();\n int offsetForLineOriginal;\n if (original.getAnchor() == originalLines) {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor() - 1) + 1;\n } else {\n offsetForLineOriginal = originalBufferDocument.getOffsetForLine(original.getAnchor());\n }\n int offsetForLineRevised;\n if (revised.getAnchor() == revisedLines) {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor() - 1) + 1;\n } else {\n offsetForLineRevised = revisedBufferDocument.getOffsetForLine(revised.getAnchor());\n }\n for (int i = 0; i < offsetForLineOriginal - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n if (next.isAdd()) {\n int lineNumber = revised.getAnchor() + revised.getSize() - 1;\n int yOffsetForLineEnd = revisedBufferDocument.getOffsetForLine(lineNumber) + +revisedBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < yOffsetForLineEnd - offsetForLineRevised; i++) {\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 2, 0, Color.BLACK);\n } else if (i == yOffsetForLineEnd - offsetForLineRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 2, 0, Color.BLACK);\n }\n Point point = new Point(offsetForLineOriginal - 1, i + offsetForLineRevised);\n addBorderChunks(point, border);\n routeDiff.put(point, Colors.ADDED);\n }\n xOffset = offsetForLineOriginal;\n yOffset = yOffsetForLineEnd;\n } else if (next.isDelete()) {\n int lineNumber = original.getAnchor() + original.getSize() - 1;\n int xOffsetForLine = originalBufferDocument.getOffsetForLine(lineNumber) + originalBufferDocument.getLineText(lineNumber).length();\n for (int i = 0; i < xOffsetForLine - offsetForLineOriginal; i++) {\n Point point = new Point(i + offsetForLineOriginal, offsetForLineRevised - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n border = BorderFactory.createMatteBorder(2, 2, 0, 2, Color.BLACK);\n } else if (i == xOffsetForLine - offsetForLineOriginal - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 2, 0, 2, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset = xOffsetForLine;\n yOffset = offsetForLineRevised;\n } else if (next.isChange()) {\n List changedDeltas = next.getChangeRevision().getDeltas();\n xOffset = offsetForLineOriginal;\n yOffset = offsetForLineRevised;\n for (Iterator jmDeltaIterator = changedDeltas.iterator(); jmDeltaIterator.hasNext(); ) {\n JMDelta changeDelta = jmDeltaIterator.next();\n JMChunk originalChange = changeDelta.getOriginal();\n JMChunk revisedChange = changeDelta.getRevised();\n int sameChars = originalChange.getAnchor() - xOffset;\n for (int i = 0; i < sameChars; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n xOffset += sameChars;\n yOffset += sameChars;\n int removeFromOrigin = originalChange.getSize();\n int addFromRevised = revisedChange.getSize();\n for (int i = 0; i < removeFromOrigin; i++) {\n Point point = new Point(i + xOffset, yOffset - 1);\n routeDiff.put(point, Colors.DELETED);\n MatteBorder border;\n if (i == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == removeFromOrigin - 1) {\n border = BorderFactory.createMatteBorder(0, 2, 2, 0, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(new Point(i + xOffset, yOffset - 1 + addFromRevised), border);\n border = BorderFactory.createMatteBorder(0, 2, 0, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n xOffset += removeFromOrigin;\n if (addFromRevised == 0) {\n Point point = new Point(xOffset - 1, yOffset - 1);\n MatteBorder border = BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK);\n addBorderChunks(point, border);\n }\n for (int i = 0; i < addFromRevised; i++) {\n Point point = new Point(xOffset - 1, i + yOffset);\n routeDiff.put(point, Colors.ADDED);\n MatteBorder border;\n if (i == 0 && removeFromOrigin == 0) {\n for (int j = 0; j < addFromRevised; j++) {\n if (j == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK);\n }\n addBorderChunks(new Point(i - 1 + xOffset, yOffset + j), border);\n }\n border = BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK);\n addBorderChunks(point, border);\n }\n if (i == addFromRevised - 1) {\n border = BorderFactory.createMatteBorder(0, 0, 2, 2, Color.BLACK);\n } else {\n border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.BLACK);\n }\n addBorderChunks(point, border);\n }\n yOffset += addFromRevised;\n }\n }\n }\n int xSize = originalBufferDocument.getDocument().getLength();\n for (int i = 0; i < xSize - xOffset; i++) {\n routeDiff.put(new Point(i + xOffset, i + yOffset), Color.GRAY);\n }\n }\n\n private void addBorderChunks(Point point, MatteBorder border) {\n MatteBorder oldborder = borderChunks.get(point);\n if (oldborder != null) {\n Insets oldborderInsets = oldborder.getBorderInsets();\n Insets borderInsets = border.getBorderInsets();\n if (oldborderInsets.top == 0 && borderInsets.top > 0) {\n oldborderInsets.top = borderInsets.top;\n }\n if (oldborderInsets.left == 0 && borderInsets.left > 0) {\n oldborderInsets.left = borderInsets.left;\n }\n if (oldborderInsets.right == 0 && borderInsets.right > 0) {\n oldborderInsets.right = borderInsets.right;\n }\n if (oldborderInsets.bottom == 0 && borderInsets.bottom > 0) {\n oldborderInsets.bottom = borderInsets.bottom;\n }\n border = BorderFactory.createMatteBorder(oldborderInsets.top, oldborderInsets.left, oldborderInsets.bottom, oldborderInsets.right, border.getMatteColor());\n }\n borderChunks.put(point, border);\n }\n\n private Vector newVector(int size) {\n Vector vector = new Vector(size);\n vector.setSize(size);\n return vector;\n }\n\n public String getOrigin() {\n return origin;\n }\n\n public void setOrigin(String origin) {\n this.origin = origin;\n buildModel();\n }\n\n public String getDestiny() {\n return destiny;\n }\n\n public void setDestiny(String destiny) {\n this.destiny = destiny;\n buildModel();\n }\n\n public DefaultTableCellRenderer getCellRenderer() {\n return new DefaultTableCellRenderer() {\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n if (\"\\n\".equals(value.toString())) {\n value = \"\\\\n\";\n }\n Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n Color background = Color.WHITE;\n if (row < 2 && column < 2) {\n if (row == column) {\n background = Color.GREEN;\n } else {\n background = Color.BLUE;\n }\n } else {\n if (row > 1) {\n if (column > 1) {\n if (origin.charAt(row - 2) == destiny.charAt(column - 2)) {\n background = Color.ORANGE;\n }\n }\n }\n if (row == 0 || column == 0) {\n background = new Color(0x550099FF, true);\n }\n }\n if (isSelected || table.isColumnSelected(column)) {\n Color newColor = Color.CYAN;\n Color mixColor = Color.WHITE;\n background = new Color(background.getRed() * newColor.getRed() / mixColor.getRed(), background.getGreen() * newColor.getGreen() / mixColor.getGreen(), background.getBlue() * newColor.getBlue() / mixColor.getBlue());\n }\n Point point = new Point(row - 2, column - 2);\n if (showSelectionPath) {\n Color color = routeDiff.get(point);\n if (color != null) {\n background = color;\n }\n }\n Border border = borderChunks.get(point);\n Border borderSelection = borderSelections.get(point);\n if (border == null) {\n if (borderSelection != null) {\n border = borderSelection;\n }\n } else {\n if (borderSelection != null) {\n border = new CompoundBorder(border, borderSelection);\n }\n }\n if (border != null) {\n ((JLabel) tableCellRendererComponent).setBorder(border);\n }\n tableCellRendererComponent.setBackground(background);\n ((JLabel) tableCellRendererComponent).setHorizontalAlignment(SwingConstants.CENTER);\n return tableCellRendererComponent;\n }\n };\n }\n\n public void setCurrentRevision(JMRevision currentRevision) {\n this.currentRevision = currentRevision;\n buildModel();\n }\n\n public JMRevision getCurrentRevision() {\n return currentRevision;\n }\n\n public void setFilePanels(FilePanel[] filePanels) {\n this.filePanels = filePanels;\n buildModel();\n }\n\n public FilePanel[] getFilePanels() {\n return filePanels;\n }\n\n public boolean isShowSelectionPath() {\n return showSelectionPath;\n }\n\n public void setShowSelectionPath(boolean showSelectionPath) {\n this.showSelectionPath = showSelectionPath;\n }\n\n public HashMap getBorderSelections() {\n return borderSelections;\n }\n\n public void setBorderSelections(HashMap borderSelection) {\n this.borderSelections = borderSelection;\n }\n}\n"} {"task_id": "Java_1049", "language": "Java", "task_type": "method_signature", "source_file": "java/github/DMinerJackie/prefuse-visualization-tool/src/prefuse/visual/tuple/TableEdgeItem.java", "mask_start_position": 1469, "mask_end_position": 1497, "canonical_solution": "public boolean isDirected() ", "pre_mask_code": "package prefuse.visual.tuple;\n\nimport prefuse.data.Graph;\nimport prefuse.data.Node;\nimport prefuse.data.Table;\nimport prefuse.data.io.GraphMLReader.GraphMLHandler;\nimport prefuse.visual.EdgeItem;\nimport prefuse.visual.NodeItem;\n\n/**\n * EdgeItem implementation that used data values from a backing VisualTable of\n * edges.\n *\n * @author jeffrey heer\n */\npublic class TableEdgeItem extends TableVisualItem implements EdgeItem {\n\n protected Graph m_graph;\n\n /**\n * Initialize a new TableEdgeItem for the given graph, table, and row. This\n * method is used by the appropriate TupleManager instance, and should not\n * be called directly by client code, unless by a client-supplied custom\n * TupleManager.\n *\n * @param table\n * the backing VisualTable\n * @param graph\n * the backing VisualGraph\n * @param row\n * the row in the node table to which this Edge instance\n * corresponds.\n */\n protected void init(Table table, Graph graph, int row) {\n m_table = table;\n m_graph = graph;\n m_row = m_table.isValidRow(row) ? row : -1;\n }\n\n /**\n * @see prefuse.data.Edge#getGraph()\n */\n public Graph getGraph() {\n return m_graph;\n }\n\n public void setDirected(Boolean directed) {\n this.set(GraphMLHandler.DIRID, directed);\n }\n\n /**\n * @see prefuse.data.Edge#isDirected()\n */\n ", "post_mask_code": "{\n Object value = null;\n Boolean directed = m_graph.isDirected();\n try {\n value = this.get(GraphMLHandler.DIRID);\n } catch (Exception e) {\n }\n if (directed == null) {\n if (value != null) {\n if (\"TRUE\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"FALSE\".equals(value.toString().toUpperCase())) {\n directed = false;\n } else if (\"1\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"0\".equals(value.toString().toUpperCase())) {\n directed = false;\n }\n } else {\n directed = false;\n }\n }\n return directed;\n }\n\n /**\n * @see prefuse.data.Edge#getSourceNode()\n */\n public Node getSourceNode() {\n return m_graph.getSourceNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getTargetNode()\n */\n public Node getTargetNode() {\n return m_graph.getTargetNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getAdjacentNode(prefuse.data.Node)\n */\n public Node getAdjacentNode(Node n) {\n return m_graph.getAdjacentNode(this, n);\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getSourceItem()\n */\n public NodeItem getSourceItem() {\n return (NodeItem) getSourceNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getTargetItem()\n */\n public NodeItem getTargetItem() {\n return (NodeItem) getTargetNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getAdjacentItem(prefuse.visual.NodeItem)\n */\n public NodeItem getAdjacentItem(NodeItem n) {\n return (NodeItem) getAdjacentNode(n);\n }\n}\n// end of class TableEdgeItem\n"} {"task_id": "Java_1050", "language": "Java", "task_type": "method_body", "source_file": "java/github/DMinerJackie/prefuse-visualization-tool/src/prefuse/visual/tuple/TableEdgeItem.java", "mask_start_position": 1347, "mask_end_position": 1404, "canonical_solution": "{\n this.set(GraphMLHandler.DIRID, directed);\n }", "pre_mask_code": "package prefuse.visual.tuple;\n\nimport prefuse.data.Graph;\nimport prefuse.data.Node;\nimport prefuse.data.Table;\nimport prefuse.data.io.GraphMLReader.GraphMLHandler;\nimport prefuse.visual.EdgeItem;\nimport prefuse.visual.NodeItem;\n\n/**\n * EdgeItem implementation that used data values from a backing VisualTable of\n * edges.\n *\n * @author jeffrey heer\n */\npublic class TableEdgeItem extends TableVisualItem implements EdgeItem {\n\n protected Graph m_graph;\n\n /**\n * Initialize a new TableEdgeItem for the given graph, table, and row. This\n * method is used by the appropriate TupleManager instance, and should not\n * be called directly by client code, unless by a client-supplied custom\n * TupleManager.\n *\n * @param table\n * the backing VisualTable\n * @param graph\n * the backing VisualGraph\n * @param row\n * the row in the node table to which this Edge instance\n * corresponds.\n */\n protected void init(Table table, Graph graph, int row) {\n m_table = table;\n m_graph = graph;\n m_row = m_table.isValidRow(row) ? row : -1;\n }\n\n /**\n * @see prefuse.data.Edge#getGraph()\n */\n public Graph getGraph() {\n return m_graph;\n }\n\n public void setDirected(Boolean directed) ", "post_mask_code": "\n\n /**\n * @see prefuse.data.Edge#isDirected()\n */\n public boolean isDirected() {\n Object value = null;\n Boolean directed = m_graph.isDirected();\n try {\n value = this.get(GraphMLHandler.DIRID);\n } catch (Exception e) {\n }\n if (directed == null) {\n if (value != null) {\n if (\"TRUE\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"FALSE\".equals(value.toString().toUpperCase())) {\n directed = false;\n } else if (\"1\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"0\".equals(value.toString().toUpperCase())) {\n directed = false;\n }\n } else {\n directed = false;\n }\n }\n return directed;\n }\n\n /**\n * @see prefuse.data.Edge#getSourceNode()\n */\n public Node getSourceNode() {\n return m_graph.getSourceNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getTargetNode()\n */\n public Node getTargetNode() {\n return m_graph.getTargetNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getAdjacentNode(prefuse.data.Node)\n */\n public Node getAdjacentNode(Node n) {\n return m_graph.getAdjacentNode(this, n);\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getSourceItem()\n */\n public NodeItem getSourceItem() {\n return (NodeItem) getSourceNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getTargetItem()\n */\n public NodeItem getTargetItem() {\n return (NodeItem) getTargetNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getAdjacentItem(prefuse.visual.NodeItem)\n */\n public NodeItem getAdjacentItem(NodeItem n) {\n return (NodeItem) getAdjacentNode(n);\n }\n}\n// end of class TableEdgeItem\n"} {"task_id": "Java_1051", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/DMinerJackie/prefuse-visualization-tool/src/prefuse/visual/tuple/TableEdgeItem.java", "mask_start_position": 1498, "mask_end_position": 1576, "canonical_solution": "\n Object value = null;\n Boolean directed = m_graph.isDirected();", "pre_mask_code": "package prefuse.visual.tuple;\n\nimport prefuse.data.Graph;\nimport prefuse.data.Node;\nimport prefuse.data.Table;\nimport prefuse.data.io.GraphMLReader.GraphMLHandler;\nimport prefuse.visual.EdgeItem;\nimport prefuse.visual.NodeItem;\n\n/**\n * EdgeItem implementation that used data values from a backing VisualTable of\n * edges.\n *\n * @author jeffrey heer\n */\npublic class TableEdgeItem extends TableVisualItem implements EdgeItem {\n\n protected Graph m_graph;\n\n /**\n * Initialize a new TableEdgeItem for the given graph, table, and row. This\n * method is used by the appropriate TupleManager instance, and should not\n * be called directly by client code, unless by a client-supplied custom\n * TupleManager.\n *\n * @param table\n * the backing VisualTable\n * @param graph\n * the backing VisualGraph\n * @param row\n * the row in the node table to which this Edge instance\n * corresponds.\n */\n protected void init(Table table, Graph graph, int row) {\n m_table = table;\n m_graph = graph;\n m_row = m_table.isValidRow(row) ? row : -1;\n }\n\n /**\n * @see prefuse.data.Edge#getGraph()\n */\n public Graph getGraph() {\n return m_graph;\n }\n\n public void setDirected(Boolean directed) {\n this.set(GraphMLHandler.DIRID, directed);\n }\n\n /**\n * @see prefuse.data.Edge#isDirected()\n */\n public boolean isDirected() {", "post_mask_code": "\n try {\n value = this.get(GraphMLHandler.DIRID);\n } catch (Exception e) {\n }\n if (directed == null) {\n if (value != null) {\n if (\"TRUE\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"FALSE\".equals(value.toString().toUpperCase())) {\n directed = false;\n } else if (\"1\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"0\".equals(value.toString().toUpperCase())) {\n directed = false;\n }\n } else {\n directed = false;\n }\n }\n return directed;\n }\n\n /**\n * @see prefuse.data.Edge#getSourceNode()\n */\n public Node getSourceNode() {\n return m_graph.getSourceNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getTargetNode()\n */\n public Node getTargetNode() {\n return m_graph.getTargetNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getAdjacentNode(prefuse.data.Node)\n */\n public Node getAdjacentNode(Node n) {\n return m_graph.getAdjacentNode(this, n);\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getSourceItem()\n */\n public NodeItem getSourceItem() {\n return (NodeItem) getSourceNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getTargetItem()\n */\n public NodeItem getTargetItem() {\n return (NodeItem) getTargetNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getAdjacentItem(prefuse.visual.NodeItem)\n */\n public NodeItem getAdjacentItem(NodeItem n) {\n return (NodeItem) getAdjacentNode(n);\n }\n}\n// end of class TableEdgeItem\n"} {"task_id": "Java_1052", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/DMinerJackie/prefuse-visualization-tool/src/prefuse/visual/tuple/TableEdgeItem.java", "mask_start_position": 1585, "mask_end_position": 2288, "canonical_solution": "try {\n value = this.get(GraphMLHandler.DIRID);\n } catch (Exception e) {\n }\n if (directed == null) {\n if (value != null) {\n if (\"TRUE\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"FALSE\".equals(value.toString().toUpperCase())) {\n directed = false;\n } else if (\"1\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"0\".equals(value.toString().toUpperCase())) {\n directed = false;\n }\n } else {\n directed = false;\n }\n }", "pre_mask_code": "package prefuse.visual.tuple;\n\nimport prefuse.data.Graph;\nimport prefuse.data.Node;\nimport prefuse.data.Table;\nimport prefuse.data.io.GraphMLReader.GraphMLHandler;\nimport prefuse.visual.EdgeItem;\nimport prefuse.visual.NodeItem;\n\n/**\n * EdgeItem implementation that used data values from a backing VisualTable of\n * edges.\n *\n * @author jeffrey heer\n */\npublic class TableEdgeItem extends TableVisualItem implements EdgeItem {\n\n protected Graph m_graph;\n\n /**\n * Initialize a new TableEdgeItem for the given graph, table, and row. This\n * method is used by the appropriate TupleManager instance, and should not\n * be called directly by client code, unless by a client-supplied custom\n * TupleManager.\n *\n * @param table\n * the backing VisualTable\n * @param graph\n * the backing VisualGraph\n * @param row\n * the row in the node table to which this Edge instance\n * corresponds.\n */\n protected void init(Table table, Graph graph, int row) {\n m_table = table;\n m_graph = graph;\n m_row = m_table.isValidRow(row) ? row : -1;\n }\n\n /**\n * @see prefuse.data.Edge#getGraph()\n */\n public Graph getGraph() {\n return m_graph;\n }\n\n public void setDirected(Boolean directed) {\n this.set(GraphMLHandler.DIRID, directed);\n }\n\n /**\n * @see prefuse.data.Edge#isDirected()\n */\n public boolean isDirected() {\n Object value = null;\n Boolean directed = m_graph.isDirected();\n ", "post_mask_code": "\n return directed;\n }\n\n /**\n * @see prefuse.data.Edge#getSourceNode()\n */\n public Node getSourceNode() {\n return m_graph.getSourceNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getTargetNode()\n */\n public Node getTargetNode() {\n return m_graph.getTargetNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getAdjacentNode(prefuse.data.Node)\n */\n public Node getAdjacentNode(Node n) {\n return m_graph.getAdjacentNode(this, n);\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getSourceItem()\n */\n public NodeItem getSourceItem() {\n return (NodeItem) getSourceNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getTargetItem()\n */\n public NodeItem getTargetItem() {\n return (NodeItem) getTargetNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getAdjacentItem(prefuse.visual.NodeItem)\n */\n public NodeItem getAdjacentItem(NodeItem n) {\n return (NodeItem) getAdjacentNode(n);\n }\n}\n// end of class TableEdgeItem\n"} {"task_id": "Java_1053", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/DMinerJackie/prefuse-visualization-tool/src/prefuse/visual/tuple/TableEdgeItem.java", "mask_start_position": 2297, "mask_end_position": 2319, "canonical_solution": "return directed;\n }", "pre_mask_code": "package prefuse.visual.tuple;\n\nimport prefuse.data.Graph;\nimport prefuse.data.Node;\nimport prefuse.data.Table;\nimport prefuse.data.io.GraphMLReader.GraphMLHandler;\nimport prefuse.visual.EdgeItem;\nimport prefuse.visual.NodeItem;\n\n/**\n * EdgeItem implementation that used data values from a backing VisualTable of\n * edges.\n *\n * @author jeffrey heer\n */\npublic class TableEdgeItem extends TableVisualItem implements EdgeItem {\n\n protected Graph m_graph;\n\n /**\n * Initialize a new TableEdgeItem for the given graph, table, and row. This\n * method is used by the appropriate TupleManager instance, and should not\n * be called directly by client code, unless by a client-supplied custom\n * TupleManager.\n *\n * @param table\n * the backing VisualTable\n * @param graph\n * the backing VisualGraph\n * @param row\n * the row in the node table to which this Edge instance\n * corresponds.\n */\n protected void init(Table table, Graph graph, int row) {\n m_table = table;\n m_graph = graph;\n m_row = m_table.isValidRow(row) ? row : -1;\n }\n\n /**\n * @see prefuse.data.Edge#getGraph()\n */\n public Graph getGraph() {\n return m_graph;\n }\n\n public void setDirected(Boolean directed) {\n this.set(GraphMLHandler.DIRID, directed);\n }\n\n /**\n * @see prefuse.data.Edge#isDirected()\n */\n public boolean isDirected() {\n Object value = null;\n Boolean directed = m_graph.isDirected();\n try {\n value = this.get(GraphMLHandler.DIRID);\n } catch (Exception e) {\n }\n if (directed == null) {\n if (value != null) {\n if (\"TRUE\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"FALSE\".equals(value.toString().toUpperCase())) {\n directed = false;\n } else if (\"1\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"0\".equals(value.toString().toUpperCase())) {\n directed = false;\n }\n } else {\n directed = false;\n }\n }\n ", "post_mask_code": "\n\n /**\n * @see prefuse.data.Edge#getSourceNode()\n */\n public Node getSourceNode() {\n return m_graph.getSourceNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getTargetNode()\n */\n public Node getTargetNode() {\n return m_graph.getTargetNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getAdjacentNode(prefuse.data.Node)\n */\n public Node getAdjacentNode(Node n) {\n return m_graph.getAdjacentNode(this, n);\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getSourceItem()\n */\n public NodeItem getSourceItem() {\n return (NodeItem) getSourceNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getTargetItem()\n */\n public NodeItem getTargetItem() {\n return (NodeItem) getTargetNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getAdjacentItem(prefuse.visual.NodeItem)\n */\n public NodeItem getAdjacentItem(NodeItem n) {\n return (NodeItem) getAdjacentNode(n);\n }\n}\n// end of class TableEdgeItem\n"} {"task_id": "Java_1054", "language": "Java", "task_type": "single_line", "source_file": "java/github/DMinerJackie/prefuse-visualization-tool/src/prefuse/visual/tuple/TableEdgeItem.java", "mask_start_position": 3083, "mask_end_position": 3098, "canonical_solution": "etTargetNode();", "pre_mask_code": "package prefuse.visual.tuple;\n\nimport prefuse.data.Graph;\nimport prefuse.data.Node;\nimport prefuse.data.Table;\nimport prefuse.data.io.GraphMLReader.GraphMLHandler;\nimport prefuse.visual.EdgeItem;\nimport prefuse.visual.NodeItem;\n\n/**\n * EdgeItem implementation that used data values from a backing VisualTable of\n * edges.\n *\n * @author jeffrey heer\n */\npublic class TableEdgeItem extends TableVisualItem implements EdgeItem {\n\n protected Graph m_graph;\n\n /**\n * Initialize a new TableEdgeItem for the given graph, table, and row. This\n * method is used by the appropriate TupleManager instance, and should not\n * be called directly by client code, unless by a client-supplied custom\n * TupleManager.\n *\n * @param table\n * the backing VisualTable\n * @param graph\n * the backing VisualGraph\n * @param row\n * the row in the node table to which this Edge instance\n * corresponds.\n */\n protected void init(Table table, Graph graph, int row) {\n m_table = table;\n m_graph = graph;\n m_row = m_table.isValidRow(row) ? row : -1;\n }\n\n /**\n * @see prefuse.data.Edge#getGraph()\n */\n public Graph getGraph() {\n return m_graph;\n }\n\n public void setDirected(Boolean directed) {\n this.set(GraphMLHandler.DIRID, directed);\n }\n\n /**\n * @see prefuse.data.Edge#isDirected()\n */\n public boolean isDirected() {\n Object value = null;\n Boolean directed = m_graph.isDirected();\n try {\n value = this.get(GraphMLHandler.DIRID);\n } catch (Exception e) {\n }\n if (directed == null) {\n if (value != null) {\n if (\"TRUE\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"FALSE\".equals(value.toString().toUpperCase())) {\n directed = false;\n } else if (\"1\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"0\".equals(value.toString().toUpperCase())) {\n directed = false;\n }\n } else {\n directed = false;\n }\n }\n return directed;\n }\n\n /**\n * @see prefuse.data.Edge#getSourceNode()\n */\n public Node getSourceNode() {\n return m_graph.getSourceNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getTargetNode()\n */\n public Node getTargetNode() {\n return m_graph.getTargetNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getAdjacentNode(prefuse.data.Node)\n */\n public Node getAdjacentNode(Node n) {\n return m_graph.getAdjacentNode(this, n);\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getSourceItem()\n */\n public NodeItem getSourceItem() {\n return (NodeItem) getSourceNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getTargetItem()\n */\n public NodeItem getTargetItem() {\n return (NodeItem) g", "post_mask_code": "\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getAdjacentItem(prefuse.visual.NodeItem)\n */\n public NodeItem getAdjacentItem(NodeItem n) {\n return (NodeItem) getAdjacentNode(n);\n }\n}\n// end of class TableEdgeItem\n"} {"task_id": "Java_1055", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/DMinerJackie/prefuse-visualization-tool/src/prefuse/visual/tuple/TableEdgeItem.java", "mask_start_position": 1017, "mask_end_position": 1181, "canonical_solution": "protected void init(Table table, Graph graph, int row) {\n m_table = table;\n m_graph = graph;\n m_row = m_table.isValidRow(row) ? row : -1;\n }", "pre_mask_code": "package prefuse.visual.tuple;\n\nimport prefuse.data.Graph;\nimport prefuse.data.Node;\nimport prefuse.data.Table;\nimport prefuse.data.io.GraphMLReader.GraphMLHandler;\nimport prefuse.visual.EdgeItem;\nimport prefuse.visual.NodeItem;\n\n/**\n * EdgeItem implementation that used data values from a backing VisualTable of\n * edges.\n *\n * @author jeffrey heer\n */\npublic class TableEdgeItem extends TableVisualItem implements EdgeItem {\n\n protected Graph m_graph;\n\n /**\n * Initialize a new TableEdgeItem for the given graph, table, and row. This\n * method is used by the appropriate TupleManager instance, and should not\n * be called directly by client code, unless by a client-supplied custom\n * TupleManager.\n *\n * @param table\n * the backing VisualTable\n * @param graph\n * the backing VisualGraph\n * @param row\n * the row in the node table to which this Edge instance\n * corresponds.\n */\n ", "post_mask_code": "\n\n /**\n * @see prefuse.data.Edge#getGraph()\n */\n public Graph getGraph() {\n return m_graph;\n }\n\n public void setDirected(Boolean directed) {\n this.set(GraphMLHandler.DIRID, directed);\n }\n\n /**\n * @see prefuse.data.Edge#isDirected()\n */\n public boolean isDirected() {\n Object value = null;\n Boolean directed = m_graph.isDirected();\n try {\n value = this.get(GraphMLHandler.DIRID);\n } catch (Exception e) {\n }\n if (directed == null) {\n if (value != null) {\n if (\"TRUE\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"FALSE\".equals(value.toString().toUpperCase())) {\n directed = false;\n } else if (\"1\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"0\".equals(value.toString().toUpperCase())) {\n directed = false;\n }\n } else {\n directed = false;\n }\n }\n return directed;\n }\n\n /**\n * @see prefuse.data.Edge#getSourceNode()\n */\n public Node getSourceNode() {\n return m_graph.getSourceNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getTargetNode()\n */\n public Node getTargetNode() {\n return m_graph.getTargetNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getAdjacentNode(prefuse.data.Node)\n */\n public Node getAdjacentNode(Node n) {\n return m_graph.getAdjacentNode(this, n);\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getSourceItem()\n */\n public NodeItem getSourceItem() {\n return (NodeItem) getSourceNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getTargetItem()\n */\n public NodeItem getTargetItem() {\n return (NodeItem) getTargetNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getAdjacentItem(prefuse.visual.NodeItem)\n */\n public NodeItem getAdjacentItem(NodeItem n) {\n return (NodeItem) getAdjacentNode(n);\n }\n}\n// end of class TableEdgeItem\n"} {"task_id": "Java_1056", "language": "Java", "task_type": "if_statement", "source_file": "java/github/DMinerJackie/prefuse-visualization-tool/src/prefuse/visual/tuple/TableEdgeItem.java", "mask_start_position": 2104, "mask_end_position": 2209, "canonical_solution": "if (\"0\".equals(value.toString().toUpperCase())) {\n directed = false;\n }", "pre_mask_code": "package prefuse.visual.tuple;\n\nimport prefuse.data.Graph;\nimport prefuse.data.Node;\nimport prefuse.data.Table;\nimport prefuse.data.io.GraphMLReader.GraphMLHandler;\nimport prefuse.visual.EdgeItem;\nimport prefuse.visual.NodeItem;\n\n/**\n * EdgeItem implementation that used data values from a backing VisualTable of\n * edges.\n *\n * @author jeffrey heer\n */\npublic class TableEdgeItem extends TableVisualItem implements EdgeItem {\n\n protected Graph m_graph;\n\n /**\n * Initialize a new TableEdgeItem for the given graph, table, and row. This\n * method is used by the appropriate TupleManager instance, and should not\n * be called directly by client code, unless by a client-supplied custom\n * TupleManager.\n *\n * @param table\n * the backing VisualTable\n * @param graph\n * the backing VisualGraph\n * @param row\n * the row in the node table to which this Edge instance\n * corresponds.\n */\n protected void init(Table table, Graph graph, int row) {\n m_table = table;\n m_graph = graph;\n m_row = m_table.isValidRow(row) ? row : -1;\n }\n\n /**\n * @see prefuse.data.Edge#getGraph()\n */\n public Graph getGraph() {\n return m_graph;\n }\n\n public void setDirected(Boolean directed) {\n this.set(GraphMLHandler.DIRID, directed);\n }\n\n /**\n * @see prefuse.data.Edge#isDirected()\n */\n public boolean isDirected() {\n Object value = null;\n Boolean directed = m_graph.isDirected();\n try {\n value = this.get(GraphMLHandler.DIRID);\n } catch (Exception e) {\n }\n if (directed == null) {\n if (value != null) {\n if (\"TRUE\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"FALSE\".equals(value.toString().toUpperCase())) {\n directed = false;\n } else if (\"1\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else ", "post_mask_code": "\n } else {\n directed = false;\n }\n }\n return directed;\n }\n\n /**\n * @see prefuse.data.Edge#getSourceNode()\n */\n public Node getSourceNode() {\n return m_graph.getSourceNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getTargetNode()\n */\n public Node getTargetNode() {\n return m_graph.getTargetNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getAdjacentNode(prefuse.data.Node)\n */\n public Node getAdjacentNode(Node n) {\n return m_graph.getAdjacentNode(this, n);\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getSourceItem()\n */\n public NodeItem getSourceItem() {\n return (NodeItem) getSourceNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getTargetItem()\n */\n public NodeItem getTargetItem() {\n return (NodeItem) getTargetNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getAdjacentItem(prefuse.visual.NodeItem)\n */\n public NodeItem getAdjacentItem(NodeItem n) {\n return (NodeItem) getAdjacentNode(n);\n }\n}\n// end of class TableEdgeItem\n"} {"task_id": "Java_1057", "language": "Java", "task_type": "try_statement", "source_file": "java/github/DMinerJackie/prefuse-visualization-tool/src/prefuse/visual/tuple/TableEdgeItem.java", "mask_start_position": 1585, "mask_end_position": 1684, "canonical_solution": "try {\n value = this.get(GraphMLHandler.DIRID);\n } catch (Exception e) {\n }", "pre_mask_code": "package prefuse.visual.tuple;\n\nimport prefuse.data.Graph;\nimport prefuse.data.Node;\nimport prefuse.data.Table;\nimport prefuse.data.io.GraphMLReader.GraphMLHandler;\nimport prefuse.visual.EdgeItem;\nimport prefuse.visual.NodeItem;\n\n/**\n * EdgeItem implementation that used data values from a backing VisualTable of\n * edges.\n *\n * @author jeffrey heer\n */\npublic class TableEdgeItem extends TableVisualItem implements EdgeItem {\n\n protected Graph m_graph;\n\n /**\n * Initialize a new TableEdgeItem for the given graph, table, and row. This\n * method is used by the appropriate TupleManager instance, and should not\n * be called directly by client code, unless by a client-supplied custom\n * TupleManager.\n *\n * @param table\n * the backing VisualTable\n * @param graph\n * the backing VisualGraph\n * @param row\n * the row in the node table to which this Edge instance\n * corresponds.\n */\n protected void init(Table table, Graph graph, int row) {\n m_table = table;\n m_graph = graph;\n m_row = m_table.isValidRow(row) ? row : -1;\n }\n\n /**\n * @see prefuse.data.Edge#getGraph()\n */\n public Graph getGraph() {\n return m_graph;\n }\n\n public void setDirected(Boolean directed) {\n this.set(GraphMLHandler.DIRID, directed);\n }\n\n /**\n * @see prefuse.data.Edge#isDirected()\n */\n public boolean isDirected() {\n Object value = null;\n Boolean directed = m_graph.isDirected();\n ", "post_mask_code": "\n if (directed == null) {\n if (value != null) {\n if (\"TRUE\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"FALSE\".equals(value.toString().toUpperCase())) {\n directed = false;\n } else if (\"1\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"0\".equals(value.toString().toUpperCase())) {\n directed = false;\n }\n } else {\n directed = false;\n }\n }\n return directed;\n }\n\n /**\n * @see prefuse.data.Edge#getSourceNode()\n */\n public Node getSourceNode() {\n return m_graph.getSourceNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getTargetNode()\n */\n public Node getTargetNode() {\n return m_graph.getTargetNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getAdjacentNode(prefuse.data.Node)\n */\n public Node getAdjacentNode(Node n) {\n return m_graph.getAdjacentNode(this, n);\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getSourceItem()\n */\n public NodeItem getSourceItem() {\n return (NodeItem) getSourceNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getTargetItem()\n */\n public NodeItem getTargetItem() {\n return (NodeItem) getTargetNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getAdjacentItem(prefuse.visual.NodeItem)\n */\n public NodeItem getAdjacentItem(NodeItem n) {\n return (NodeItem) getAdjacentNode(n);\n }\n}\n// end of class TableEdgeItem\n"} {"task_id": "Java_1058", "language": "Java", "task_type": "empty", "source_file": "java/github/DMinerJackie/prefuse-visualization-tool/src/prefuse/visual/tuple/TableEdgeItem.java", "mask_start_position": 2764, "mask_end_position": 2764, "canonical_solution": "", "pre_mask_code": "package prefuse.visual.tuple;\n\nimport prefuse.data.Graph;\nimport prefuse.data.Node;\nimport prefuse.data.Table;\nimport prefuse.data.io.GraphMLReader.GraphMLHandler;\nimport prefuse.visual.EdgeItem;\nimport prefuse.visual.NodeItem;\n\n/**\n * EdgeItem implementation that used data values from a backing VisualTable of\n * edges.\n *\n * @author jeffrey heer\n */\npublic class TableEdgeItem extends TableVisualItem implements EdgeItem {\n\n protected Graph m_graph;\n\n /**\n * Initialize a new TableEdgeItem for the given graph, table, and row. This\n * method is used by the appropriate TupleManager instance, and should not\n * be called directly by client code, unless by a client-supplied custom\n * TupleManager.\n *\n * @param table\n * the backing VisualTable\n * @param graph\n * the backing VisualGraph\n * @param row\n * the row in the node table to which this Edge instance\n * corresponds.\n */\n protected void init(Table table, Graph graph, int row) {\n m_table = table;\n m_graph = graph;\n m_row = m_table.isValidRow(row) ? row : -1;\n }\n\n /**\n * @see prefuse.data.Edge#getGraph()\n */\n public Graph getGraph() {\n return m_graph;\n }\n\n public void setDirected(Boolean directed) {\n this.set(GraphMLHandler.DIRID, directed);\n }\n\n /**\n * @see prefuse.data.Edge#isDirected()\n */\n public boolean isDirected() {\n Object value = null;\n Boolean directed = m_graph.isDirected();\n try {\n value = this.get(GraphMLHandler.DIRID);\n } catch (Exception e) {\n }\n if (directed == null) {\n if (value != null) {\n if (\"TRUE\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"FALSE\".equals(value.toString().toUpperCase())) {\n directed = false;\n } else if (\"1\".equals(value.toString().toUpperCase())) {\n directed = true;\n } else if (\"0\".equals(value.toString().toUpperCase())) {\n directed = false;\n }\n } else {\n directed = false;\n }\n }\n return directed;\n }\n\n /**\n * @see prefuse.data.Edge#getSourceNode()\n */\n public Node getSourceNode() {\n return m_graph.getSourceNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getTargetNode()\n */\n public Node getTargetNode() {\n return m_graph.getTargetNode(this);\n }\n\n /**\n * @see prefuse.data.Edge#getAdjacentNode(prefuse.data.Node)\n */\n public Node getAdjacentNode(Node n) {\n return m_graph.get", "post_mask_code": "AdjacentNode(this, n);\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getSourceItem()\n */\n public NodeItem getSourceItem() {\n return (NodeItem) getSourceNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getTargetItem()\n */\n public NodeItem getTargetItem() {\n return (NodeItem) getTargetNode();\n }\n\n /**\n * @see prefuse.visual.EdgeItem#getAdjacentItem(prefuse.visual.NodeItem)\n */\n public NodeItem getAdjacentItem(NodeItem n) {\n return (NodeItem) getAdjacentNode(n);\n }\n}\n// end of class TableEdgeItem\n"} {"task_id": "Java_1059", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cookiengineer/lycheejs/lycheejs/bin/runtime/html-webview/android-toolchain/gradle/src/core/org/gradle/api/tasks/SourceTask.java", "mask_start_position": 2442, "mask_end_position": 2495, "canonical_solution": "public SourceTask exclude(Iterable excludes) ", "pre_mask_code": "package org.gradle.api.tasks;\n\nimport groovy.lang.Closure;\nimport org.gradle.api.file.FileTree;\nimport org.gradle.api.file.FileTreeElement;\nimport org.gradle.api.internal.ConventionTask;\nimport org.gradle.api.specs.Spec;\nimport org.gradle.api.tasks.util.PatternFilterable;\nimport org.gradle.api.tasks.util.PatternSet;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * A {@code SourceTask} performs some operation on source files.\n */\npublic class SourceTask extends ConventionTask implements PatternFilterable {\n\n protected final List source = new ArrayList();\n\n private final PatternFilterable patternSet = new PatternSet();\n\n /**\n * Returns the source for this task, after the include and exclude patterns have been applied. Ignores source files which do not exist.\n *\n * @return The source.\n */\n @InputFiles\n @SkipWhenEmpty\n public FileTree getSource() {\n FileTree src = getProject().files(new ArrayList(this.source)).getAsFileTree();\n return src == null ? getProject().files().getAsFileTree() : src.matching(patternSet);\n }\n\n /**\n * Sets the source for this task. The given source object is evaluated as per {@link org.gradle.api.Project#files(Object...)}.\n *\n * @param source The source.\n */\n public void setSource(Object source) {\n this.source.clear();\n this.source.add(source);\n }\n\n /**\n * Adds some source to this task. The given source objects will be evaluated as per {@link org.gradle.api.Project#files(Object...)}.\n *\n * @param sources The source to add\n * @return this\n */\n public SourceTask source(Object... sources) {\n for (Object source : sources) {\n this.source.add(source);\n }\n return this;\n }\n\n public SourceTask include(String... includes) {\n patternSet.include(includes);\n return this;\n }\n\n public SourceTask include(Iterable includes) {\n patternSet.include(includes);\n return this;\n }\n\n public SourceTask include(Spec includeSpec) {\n patternSet.include(includeSpec);\n return this;\n }\n\n public SourceTask include(Closure includeSpec) {\n patternSet.include(includeSpec);\n return this;\n }\n\n public SourceTask exclude(String... excludes) {\n patternSet.exclude(excludes);\n return this;\n }\n\n ", "post_mask_code": "{\n patternSet.exclude(excludes);\n return this;\n }\n\n public SourceTask exclude(Spec excludeSpec) {\n patternSet.exclude(excludeSpec);\n return this;\n }\n\n public SourceTask exclude(Closure excludeSpec) {\n patternSet.exclude(excludeSpec);\n return this;\n }\n\n public Set getIncludes() {\n return patternSet.getIncludes();\n }\n\n public SourceTask setIncludes(Iterable includes) {\n patternSet.setIncludes(includes);\n return this;\n }\n\n public Set getExcludes() {\n return patternSet.getExcludes();\n }\n\n public SourceTask setExcludes(Iterable excludes) {\n patternSet.setExcludes(excludes);\n return this;\n }\n}\n"} {"task_id": "Java_1060", "language": "Java", "task_type": "method_body", "source_file": "java/github/cookiengineer/lycheejs/lycheejs/bin/runtime/html-webview/android-toolchain/gradle/src/core/org/gradle/api/tasks/SourceTask.java", "mask_start_position": 1363, "mask_end_position": 1432, "canonical_solution": "{\n this.source.clear();\n this.source.add(source);\n }", "pre_mask_code": "package org.gradle.api.tasks;\n\nimport groovy.lang.Closure;\nimport org.gradle.api.file.FileTree;\nimport org.gradle.api.file.FileTreeElement;\nimport org.gradle.api.internal.ConventionTask;\nimport org.gradle.api.specs.Spec;\nimport org.gradle.api.tasks.util.PatternFilterable;\nimport org.gradle.api.tasks.util.PatternSet;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * A {@code SourceTask} performs some operation on source files.\n */\npublic class SourceTask extends ConventionTask implements PatternFilterable {\n\n protected final List source = new ArrayList();\n\n private final PatternFilterable patternSet = new PatternSet();\n\n /**\n * Returns the source for this task, after the include and exclude patterns have been applied. Ignores source files which do not exist.\n *\n * @return The source.\n */\n @InputFiles\n @SkipWhenEmpty\n public FileTree getSource() {\n FileTree src = getProject().files(new ArrayList(this.source)).getAsFileTree();\n return src == null ? getProject().files().getAsFileTree() : src.matching(patternSet);\n }\n\n /**\n * Sets the source for this task. The given source object is evaluated as per {@link org.gradle.api.Project#files(Object...)}.\n *\n * @param source The source.\n */\n public void setSource(Object source) ", "post_mask_code": "\n\n /**\n * Adds some source to this task. The given source objects will be evaluated as per {@link org.gradle.api.Project#files(Object...)}.\n *\n * @param sources The source to add\n * @return this\n */\n public SourceTask source(Object... sources) {\n for (Object source : sources) {\n this.source.add(source);\n }\n return this;\n }\n\n public SourceTask include(String... includes) {\n patternSet.include(includes);\n return this;\n }\n\n public SourceTask include(Iterable includes) {\n patternSet.include(includes);\n return this;\n }\n\n public SourceTask include(Spec includeSpec) {\n patternSet.include(includeSpec);\n return this;\n }\n\n public SourceTask include(Closure includeSpec) {\n patternSet.include(includeSpec);\n return this;\n }\n\n public SourceTask exclude(String... excludes) {\n patternSet.exclude(excludes);\n return this;\n }\n\n public SourceTask exclude(Iterable excludes) {\n patternSet.exclude(excludes);\n return this;\n }\n\n public SourceTask exclude(Spec excludeSpec) {\n patternSet.exclude(excludeSpec);\n return this;\n }\n\n public SourceTask exclude(Closure excludeSpec) {\n patternSet.exclude(excludeSpec);\n return this;\n }\n\n public Set getIncludes() {\n return patternSet.getIncludes();\n }\n\n public SourceTask setIncludes(Iterable includes) {\n patternSet.setIncludes(includes);\n return this;\n }\n\n public Set getExcludes() {\n return patternSet.getExcludes();\n }\n\n public SourceTask setExcludes(Iterable excludes) {\n patternSet.setExcludes(excludes);\n return this;\n }\n}\n"} {"task_id": "Java_1061", "language": "Java", "task_type": "single_line", "source_file": "java/github/cookiengineer/lycheejs/lycheejs/bin/runtime/html-webview/android-toolchain/gradle/src/core/org/gradle/api/tasks/SourceTask.java", "mask_start_position": 1378, "mask_end_position": 1393, "canonical_solution": "source.clear();", "pre_mask_code": "package org.gradle.api.tasks;\n\nimport groovy.lang.Closure;\nimport org.gradle.api.file.FileTree;\nimport org.gradle.api.file.FileTreeElement;\nimport org.gradle.api.internal.ConventionTask;\nimport org.gradle.api.specs.Spec;\nimport org.gradle.api.tasks.util.PatternFilterable;\nimport org.gradle.api.tasks.util.PatternSet;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * A {@code SourceTask} performs some operation on source files.\n */\npublic class SourceTask extends ConventionTask implements PatternFilterable {\n\n protected final List source = new ArrayList();\n\n private final PatternFilterable patternSet = new PatternSet();\n\n /**\n * Returns the source for this task, after the include and exclude patterns have been applied. Ignores source files which do not exist.\n *\n * @return The source.\n */\n @InputFiles\n @SkipWhenEmpty\n public FileTree getSource() {\n FileTree src = getProject().files(new ArrayList(this.source)).getAsFileTree();\n return src == null ? getProject().files().getAsFileTree() : src.matching(patternSet);\n }\n\n /**\n * Sets the source for this task. The given source object is evaluated as per {@link org.gradle.api.Project#files(Object...)}.\n *\n * @param source The source.\n */\n public void setSource(Object source) {\n this.", "post_mask_code": "\n this.source.add(source);\n }\n\n /**\n * Adds some source to this task. The given source objects will be evaluated as per {@link org.gradle.api.Project#files(Object...)}.\n *\n * @param sources The source to add\n * @return this\n */\n public SourceTask source(Object... sources) {\n for (Object source : sources) {\n this.source.add(source);\n }\n return this;\n }\n\n public SourceTask include(String... includes) {\n patternSet.include(includes);\n return this;\n }\n\n public SourceTask include(Iterable includes) {\n patternSet.include(includes);\n return this;\n }\n\n public SourceTask include(Spec includeSpec) {\n patternSet.include(includeSpec);\n return this;\n }\n\n public SourceTask include(Closure includeSpec) {\n patternSet.include(includeSpec);\n return this;\n }\n\n public SourceTask exclude(String... excludes) {\n patternSet.exclude(excludes);\n return this;\n }\n\n public SourceTask exclude(Iterable excludes) {\n patternSet.exclude(excludes);\n return this;\n }\n\n public SourceTask exclude(Spec excludeSpec) {\n patternSet.exclude(excludeSpec);\n return this;\n }\n\n public SourceTask exclude(Closure excludeSpec) {\n patternSet.exclude(excludeSpec);\n return this;\n }\n\n public Set getIncludes() {\n return patternSet.getIncludes();\n }\n\n public SourceTask setIncludes(Iterable includes) {\n patternSet.setIncludes(includes);\n return this;\n }\n\n public Set getExcludes() {\n return patternSet.getExcludes();\n }\n\n public SourceTask setExcludes(Iterable excludes) {\n patternSet.setExcludes(excludes);\n return this;\n }\n}\n"} {"task_id": "Java_1062", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/cookiengineer/lycheejs/lycheejs/bin/runtime/html-webview/android-toolchain/gradle/src/core/org/gradle/api/tasks/SourceTask.java", "mask_start_position": 1658, "mask_end_position": 1817, "canonical_solution": "public SourceTask source(Object... sources) {\n for (Object source : sources) {\n this.source.add(source);\n }\n return this;\n }", "pre_mask_code": "package org.gradle.api.tasks;\n\nimport groovy.lang.Closure;\nimport org.gradle.api.file.FileTree;\nimport org.gradle.api.file.FileTreeElement;\nimport org.gradle.api.internal.ConventionTask;\nimport org.gradle.api.specs.Spec;\nimport org.gradle.api.tasks.util.PatternFilterable;\nimport org.gradle.api.tasks.util.PatternSet;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * A {@code SourceTask} performs some operation on source files.\n */\npublic class SourceTask extends ConventionTask implements PatternFilterable {\n\n protected final List source = new ArrayList();\n\n private final PatternFilterable patternSet = new PatternSet();\n\n /**\n * Returns the source for this task, after the include and exclude patterns have been applied. Ignores source files which do not exist.\n *\n * @return The source.\n */\n @InputFiles\n @SkipWhenEmpty\n public FileTree getSource() {\n FileTree src = getProject().files(new ArrayList(this.source)).getAsFileTree();\n return src == null ? getProject().files().getAsFileTree() : src.matching(patternSet);\n }\n\n /**\n * Sets the source for this task. The given source object is evaluated as per {@link org.gradle.api.Project#files(Object...)}.\n *\n * @param source The source.\n */\n public void setSource(Object source) {\n this.source.clear();\n this.source.add(source);\n }\n\n /**\n * Adds some source to this task. The given source objects will be evaluated as per {@link org.gradle.api.Project#files(Object...)}.\n *\n * @param sources The source to add\n * @return this\n */\n ", "post_mask_code": "\n\n public SourceTask include(String... includes) {\n patternSet.include(includes);\n return this;\n }\n\n public SourceTask include(Iterable includes) {\n patternSet.include(includes);\n return this;\n }\n\n public SourceTask include(Spec includeSpec) {\n patternSet.include(includeSpec);\n return this;\n }\n\n public SourceTask include(Closure includeSpec) {\n patternSet.include(includeSpec);\n return this;\n }\n\n public SourceTask exclude(String... excludes) {\n patternSet.exclude(excludes);\n return this;\n }\n\n public SourceTask exclude(Iterable excludes) {\n patternSet.exclude(excludes);\n return this;\n }\n\n public SourceTask exclude(Spec excludeSpec) {\n patternSet.exclude(excludeSpec);\n return this;\n }\n\n public SourceTask exclude(Closure excludeSpec) {\n patternSet.exclude(excludeSpec);\n return this;\n }\n\n public Set getIncludes() {\n return patternSet.getIncludes();\n }\n\n public SourceTask setIncludes(Iterable includes) {\n patternSet.setIncludes(includes);\n return this;\n }\n\n public Set getExcludes() {\n return patternSet.getExcludes();\n }\n\n public SourceTask setExcludes(Iterable excludes) {\n patternSet.setExcludes(excludes);\n return this;\n }\n}\n"} {"task_id": "Java_1063", "language": "Java", "task_type": "empty", "source_file": "java/github/cookiengineer/lycheejs/lycheejs/bin/runtime/html-webview/android-toolchain/gradle/src/core/org/gradle/api/tasks/SourceTask.java", "mask_start_position": 3200, "mask_end_position": 3200, "canonical_solution": "", "pre_mask_code": "package org.gradle.api.tasks;\n\nimport groovy.lang.Closure;\nimport org.gradle.api.file.FileTree;\nimport org.gradle.api.file.FileTreeElement;\nimport org.gradle.api.internal.ConventionTask;\nimport org.gradle.api.specs.Spec;\nimport org.gradle.api.tasks.util.PatternFilterable;\nimport org.gradle.api.tasks.util.PatternSet;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * A {@code SourceTask} performs some operation on source files.\n */\npublic class SourceTask extends ConventionTask implements PatternFilterable {\n\n protected final List source = new ArrayList();\n\n private final PatternFilterable patternSet = new PatternSet();\n\n /**\n * Returns the source for this task, after the include and exclude patterns have been applied. Ignores source files which do not exist.\n *\n * @return The source.\n */\n @InputFiles\n @SkipWhenEmpty\n public FileTree getSource() {\n FileTree src = getProject().files(new ArrayList(this.source)).getAsFileTree();\n return src == null ? getProject().files().getAsFileTree() : src.matching(patternSet);\n }\n\n /**\n * Sets the source for this task. The given source object is evaluated as per {@link org.gradle.api.Project#files(Object...)}.\n *\n * @param source The source.\n */\n public void setSource(Object source) {\n this.source.clear();\n this.source.add(source);\n }\n\n /**\n * Adds some source to this task. The given source objects will be evaluated as per {@link org.gradle.api.Project#files(Object...)}.\n *\n * @param sources The source to add\n * @return this\n */\n public SourceTask source(Object... sources) {\n for (Object source : sources) {\n this.source.add(source);\n }\n return this;\n }\n\n public SourceTask include(String... includes) {\n patternSet.include(includes);\n return this;\n }\n\n public SourceTask include(Iterable includes) {\n patternSet.include(includes);\n return this;\n }\n\n public SourceTask include(Spec includeSpec) {\n patternSet.include(includeSpec);\n return this;\n }\n\n public SourceTask include(Closure includeSpec) {\n patternSet.include(includeSpec);\n return this;\n }\n\n public SourceTask exclude(String... excludes) {\n patternSet.exclude(excludes);\n return this;\n }\n\n public SourceTask exclude(Iterable excludes) {\n patternSet.exclude(excludes);\n return this;\n }\n\n public SourceTask exclude(Spec excludeSpec) {\n patternSet.exclude(excludeSpec);\n return this;\n }\n\n public SourceTask exclude(Closure excludeSpec) {\n patternSet.exclude(excludeSpec);\n return this;\n }\n\n public Set getIncludes() {\n return patternSet.getIncludes();\n }\n\n public SourceTask setIncludes(Iterable includes) {\n patternSet.setIncludes(includes);\n return this;\n }\n\n public Set getExcludes() {\n return patternSet.getExcludes();\n }\n\n public SourceTask setExcludes(Iterable excludes) {\n p", "post_mask_code": "atternSet.setExcludes(excludes);\n return this;\n }\n}\n"} {"task_id": "Java_1064", "language": "Java", "task_type": "method_signature", "source_file": "java/github/dbeaver/dbeaver/plugins/org.jkiss.dbeaver.ext.generic/src/org/jkiss/dbeaver/ext/generic/model/GenericTableType.java", "mask_start_position": 548, "mask_end_position": 607, "canonical_solution": "@Nullable\n @Override\n public String getDescription() ", "pre_mask_code": "/*\n * DBeaver - Universal Database Manager\n *\n */\npackage org.jkiss.dbeaver.ext.generic.model;\n\nimport org.jkiss.code.NotNull;\nimport org.jkiss.code.Nullable;\nimport org.jkiss.dbeaver.model.DBPDataSource;\nimport org.jkiss.dbeaver.model.struct.DBSObject;\n\n/**\n * Table type\n */\npublic class GenericTableType implements DBSObject {\n\n private GenericDataSource dataSource;\n\n private String name;\n\n public GenericTableType(GenericDataSource dataSource, String name) {\n this.dataSource = dataSource;\n this.name = name;\n }\n\n ", "post_mask_code": "{\n return null;\n }\n\n @Override\n public DBSObject getParentObject() {\n return dataSource.getContainer();\n }\n\n @NotNull\n @Override\n public DBPDataSource getDataSource() {\n return dataSource;\n }\n\n @NotNull\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public boolean isPersisted() {\n return true;\n }\n}\n"} {"task_id": "Java_1065", "language": "Java", "task_type": "method_body", "source_file": "java/github/dbeaver/dbeaver/plugins/org.jkiss.dbeaver.ext.generic/src/org/jkiss/dbeaver/ext/generic/model/GenericTableType.java", "mask_start_position": 607, "mask_end_position": 635, "canonical_solution": "{\n return null;\n }", "pre_mask_code": "/*\n * DBeaver - Universal Database Manager\n *\n */\npackage org.jkiss.dbeaver.ext.generic.model;\n\nimport org.jkiss.code.NotNull;\nimport org.jkiss.code.Nullable;\nimport org.jkiss.dbeaver.model.DBPDataSource;\nimport org.jkiss.dbeaver.model.struct.DBSObject;\n\n/**\n * Table type\n */\npublic class GenericTableType implements DBSObject {\n\n private GenericDataSource dataSource;\n\n private String name;\n\n public GenericTableType(GenericDataSource dataSource, String name) {\n this.dataSource = dataSource;\n this.name = name;\n }\n\n @Nullable\n @Override\n public String getDescription() ", "post_mask_code": "\n\n @Override\n public DBSObject getParentObject() {\n return dataSource.getContainer();\n }\n\n @NotNull\n @Override\n public DBPDataSource getDataSource() {\n return dataSource;\n }\n\n @NotNull\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public boolean isPersisted() {\n return true;\n }\n}\n"} {"task_id": "Java_1066", "language": "Java", "task_type": "single_line", "source_file": "java/github/dbeaver/dbeaver/plugins/org.jkiss.dbeaver.ext.generic/src/org/jkiss/dbeaver/ext/generic/model/GenericTableType.java", "mask_start_position": 997, "mask_end_position": 999, "canonical_solution": "e;", "pre_mask_code": "/*\n * DBeaver - Universal Database Manager\n *\n */\npackage org.jkiss.dbeaver.ext.generic.model;\n\nimport org.jkiss.code.NotNull;\nimport org.jkiss.code.Nullable;\nimport org.jkiss.dbeaver.model.DBPDataSource;\nimport org.jkiss.dbeaver.model.struct.DBSObject;\n\n/**\n * Table type\n */\npublic class GenericTableType implements DBSObject {\n\n private GenericDataSource dataSource;\n\n private String name;\n\n public GenericTableType(GenericDataSource dataSource, String name) {\n this.dataSource = dataSource;\n this.name = name;\n }\n\n @Nullable\n @Override\n public String getDescription() {\n return null;\n }\n\n @Override\n public DBSObject getParentObject() {\n return dataSource.getContainer();\n }\n\n @NotNull\n @Override\n public DBPDataSource getDataSource() {\n return dataSource;\n }\n\n @NotNull\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public boolean isPersisted() {\n return tru", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1067", "language": "Java", "task_type": "empty", "source_file": "java/github/dbeaver/dbeaver/plugins/org.jkiss.dbeaver.ext.generic/src/org/jkiss/dbeaver/ext/generic/model/GenericTableType.java", "mask_start_position": 762, "mask_end_position": 762, "canonical_solution": "", "pre_mask_code": "/*\n * DBeaver - Universal Database Manager\n *\n */\npackage org.jkiss.dbeaver.ext.generic.model;\n\nimport org.jkiss.code.NotNull;\nimport org.jkiss.code.Nullable;\nimport org.jkiss.dbeaver.model.DBPDataSource;\nimport org.jkiss.dbeaver.model.struct.DBSObject;\n\n/**\n * Table type\n */\npublic class GenericTableType implements DBSObject {\n\n private GenericDataSource dataSource;\n\n private String name;\n\n public GenericTableType(GenericDataSource dataSource, String name) {\n this.dataSource = dataSource;\n this.name = name;\n }\n\n @Nullable\n @Override\n public String getDescription() {\n return null;\n }\n\n @Override\n public DBSObject getParentObject() {\n return dataSource.getContainer();\n }\n\n @NotNull\n @Ove", "post_mask_code": "rride\n public DBPDataSource getDataSource() {\n return dataSource;\n }\n\n @NotNull\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public boolean isPersisted() {\n return true;\n }\n}\n"} {"task_id": "Java_1068", "language": "Java", "task_type": "method_signature", "source_file": "java/github/open-osrs/runelite/runescape-client/src/main/java/PcmPlayer.java", "mask_start_position": 3456, "mask_end_position": 3601, "canonical_solution": "@ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1407514911\")\n @Export(\"close\")\n protected void close() ", "pre_mask_code": "import java.util.concurrent.ScheduledExecutorService;\nimport net.runelite.mapping.Export;\nimport net.runelite.mapping.Implements;\nimport net.runelite.mapping.ObfuscatedGetter;\nimport net.runelite.mapping.ObfuscatedName;\nimport net.runelite.mapping.ObfuscatedSignature;\nimport net.runelite.rs.ScriptOpcodes;\n\n@ObfuscatedName(\"aq\")\n@Implements(\"PcmPlayer\")\npublic class PcmPlayer {\n\n @ObfuscatedName(\"sm\")\n @ObfuscatedGetter(intValue = 2053999609)\n static int field284;\n\n @ObfuscatedName(\"m\")\n @ObfuscatedGetter(intValue = 1333600085)\n public static int field279;\n\n @ObfuscatedName(\"k\")\n @Export(\"PcmPlayer_stereo\")\n public static boolean PcmPlayer_stereo;\n\n @ObfuscatedName(\"a\")\n @Export(\"soundSystemExecutor\")\n static ScheduledExecutorService soundSystemExecutor;\n\n @ObfuscatedName(\"e\")\n @ObfuscatedGetter(intValue = 234394993)\n public static int field283;\n\n @ObfuscatedName(\"v\")\n @Export(\"samples\")\n protected int[] samples;\n\n @ObfuscatedName(\"s\")\n @ObfuscatedSignature(descriptor = \"Lav;\")\n @Export(\"stream\")\n PcmStream stream;\n\n @ObfuscatedName(\"c\")\n @ObfuscatedGetter(intValue = -1215690509)\n int field269;\n\n @ObfuscatedName(\"b\")\n @ObfuscatedGetter(longValue = 2700493498205354685L)\n @Export(\"timeMs\")\n long timeMs;\n\n @ObfuscatedName(\"x\")\n @ObfuscatedGetter(intValue = 1537731573)\n @Export(\"capacity\")\n int capacity;\n\n @ObfuscatedName(\"p\")\n @ObfuscatedGetter(intValue = -1674723661)\n int field272;\n\n @ObfuscatedName(\"z\")\n @ObfuscatedGetter(intValue = 1001923267)\n int field265;\n\n @ObfuscatedName(\"h\")\n @ObfuscatedGetter(longValue = -2229248515898476515L)\n long field274;\n\n @ObfuscatedName(\"o\")\n @ObfuscatedGetter(intValue = 352319831)\n int field275;\n\n @ObfuscatedName(\"r\")\n @ObfuscatedGetter(intValue = 998812825)\n int field262;\n\n @ObfuscatedName(\"n\")\n @ObfuscatedGetter(intValue = -388583705)\n int field277;\n\n @ObfuscatedName(\"u\")\n @ObfuscatedGetter(longValue = -1357881854631939735L)\n long field278;\n\n @ObfuscatedName(\"d\")\n boolean field266;\n\n @ObfuscatedName(\"ay\")\n @ObfuscatedGetter(intValue = 461057869)\n int field281;\n\n @ObfuscatedName(\"al\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field286;\n\n @ObfuscatedName(\"ao\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field282;\n\n protected PcmPlayer() {\n this.field269 = 32;\n this.timeMs = UserComparator4.method2406();\n this.field274 = 0L;\n this.field275 = 0;\n this.field262 = 0;\n this.field277 = 0;\n this.field278 = 0L;\n this.field266 = true;\n this.field281 = 0;\n this.field286 = new PcmStream[8];\n this.field282 = new PcmStream[8];\n }\n\n @ObfuscatedName(\"l\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1783507069\")\n @Export(\"init\")\n protected void init() throws Exception {\n }\n\n @ObfuscatedName(\"q\")\n @ObfuscatedSignature(descriptor = \"(IB)V\", garbageValue = \"15\")\n @Export(\"open\")\n protected void open(int var1) throws Exception {\n }\n\n @ObfuscatedName(\"f\")\n @ObfuscatedSignature(descriptor = \"(I)I\", garbageValue = \"-625452134\")\n @Export(\"position\")\n protected int position() throws Exception {\n return this.capacity;\n }\n\n @ObfuscatedName(\"j\")\n @Export(\"write\")\n protected void write() throws Exception {\n }\n\n ", "post_mask_code": "{\n }\n\n @ObfuscatedName(\"k\")\n @ObfuscatedSignature(descriptor = \"(B)V\", garbageValue = \"-115\")\n @Export(\"discard\")\n protected void discard() throws Exception {\n }\n\n @ObfuscatedName(\"o\")\n @ObfuscatedSignature(descriptor = \"(Lav;I)V\", garbageValue = \"1536652372\")\n @Export(\"setStream\")\n public final synchronized void setStream(PcmStream var1) {\n this.stream = var1;\n }\n\n @ObfuscatedName(\"r\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1578748771\")\n @Export(\"run\")\n public final synchronized void run() {\n if (this.samples != null) {\n long var1 = UserComparator4.method2406();\n try {\n if (0L != this.field274) {\n if (var1 < this.field274) {\n return;\n }\n this.open(this.capacity);\n this.field274 = 0L;\n this.field266 = true;\n }\n int var3 = this.position();\n if (this.field277 - var3 > this.field275) {\n this.field275 = this.field277 - var3;\n }\n int var4 = this.field272 + this.field265;\n if (var4 + 256 > 16384) {\n var4 = 16128;\n }\n if (var4 + 256 > this.capacity) {\n this.capacity += 1024;\n if (this.capacity > 16384) {\n this.capacity = 16384;\n }\n this.close();\n this.open(this.capacity);\n var3 = 0;\n this.field266 = true;\n if (var4 + 256 > this.capacity) {\n var4 = this.capacity - 256;\n this.field265 = var4 - this.field272;\n }\n }\n while (var3 < var4) {\n this.fill(this.samples, 256);\n this.write();\n var3 += 256;\n }\n if (var1 > this.field278) {\n if (!this.field266) {\n if (this.field275 == 0 && this.field262 == 0) {\n this.close();\n this.field274 = var1 + 2000L;\n return;\n }\n this.field265 = Math.min(this.field262, this.field275);\n this.field262 = this.field275;\n } else {\n this.field266 = false;\n }\n this.field275 = 0;\n this.field278 = var1 + 2000L;\n }\n this.field277 = var3;\n } catch (Exception var7) {\n this.close();\n this.field274 = var1 + 2000L;\n }\n try {\n if (var1 > this.timeMs + 500000L) {\n var1 = this.timeMs;\n }\n while (var1 > 5000L + this.timeMs) {\n this.skip(256);\n this.timeMs += (long) (256000 / field279);\n }\n } catch (Exception var6) {\n this.timeMs = var1;\n }\n }\n }\n\n @ObfuscatedName(\"n\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1285587409\")\n public final void method696() {\n this.field266 = true;\n }\n\n @ObfuscatedName(\"u\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1511155327\")\n @Export(\"tryDiscard\")\n public final synchronized void tryDiscard() {\n this.field266 = true;\n try {\n this.discard();\n } catch (Exception var2) {\n this.close();\n this.field274 = UserComparator4.method2406() + 2000L;\n }\n }\n\n @ObfuscatedName(\"d\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"25571035\")\n @Export(\"shutdown\")\n public final synchronized void shutdown() {\n if (Skeleton.soundSystem != null) {\n boolean var1 = true;\n for (int var2 = 0; var2 < 2; ++var2) {\n if (this == Skeleton.soundSystem.players[var2]) {\n Skeleton.soundSystem.players[var2] = null;\n }\n if (Skeleton.soundSystem.players[var2] != null) {\n var1 = false;\n }\n }\n if (var1) {\n soundSystemExecutor.shutdownNow();\n soundSystemExecutor = null;\n Skeleton.soundSystem = null;\n }\n }\n this.close();\n this.samples = null;\n }\n\n @ObfuscatedName(\"ab\")\n @ObfuscatedSignature(descriptor = \"(II)V\", garbageValue = \"4570450\")\n @Export(\"skip\")\n final void skip(int var1) {\n this.field281 -= var1;\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.skip(var1);\n }\n }\n\n @ObfuscatedName(\"ad\")\n @Export(\"fill\")\n final void fill(int[] var1, int var2) {\n int var3 = var2;\n if (PcmPlayer_stereo) {\n var3 = var2 << 1;\n }\n class321.clearIntArray(var1, 0, var3);\n this.field281 -= var2;\n if (this.stream != null && this.field281 <= 0) {\n this.field281 += field279 >> 4;\n class12.PcmStream_disable(this.stream);\n this.method711(this.stream, this.stream.vmethod944());\n int var4 = 0;\n int var5 = 255;\n int var6;\n PcmStream var10;\n label108: for (var6 = 7; var5 != 0; --var6) {\n int var7;\n int var8;\n if (var6 < 0) {\n var7 = var6 & 3;\n var8 = -(var6 >> 2);\n } else {\n var7 = var6;\n var8 = 0;\n }\n for (int var9 = var5 >>> var7 & 286331153; var9 != 0; var9 >>>= 4) {\n if ((var9 & 1) != 0) {\n var5 &= ~(1 << var7);\n var10 = null;\n PcmStream var11 = this.field286[var7];\n label102: while (true) {\n while (true) {\n if (var11 == null) {\n break label102;\n }\n AbstractSound var12 = var11.sound;\n if (var12 != null && var12.position > var8) {\n var5 |= 1 << var7;\n var10 = var11;\n var11 = var11.after;\n } else {\n var11.active = true;\n int var13 = var11.vmethod4889();\n var4 += var13;\n if (var12 != null) {\n var12.position += var13;\n }\n if (var4 >= this.field269) {\n break label108;\n }\n PcmStream var14 = var11.firstSubStream();\n if (var14 != null) {\n for (int var15 = var11.field335; var14 != null; var14 = var11.nextSubStream()) {\n this.method711(var14, var15 * var14.vmethod944() >> 8);\n }\n }\n PcmStream var18 = var11.after;\n var11.after = null;\n if (var10 == null) {\n this.field286[var7] = var18;\n } else {\n var10.after = var18;\n }\n if (var18 == null) {\n this.field282[var7] = var10;\n }\n var11 = var18;\n }\n }\n }\n }\n var7 += 4;\n ++var8;\n }\n }\n for (var6 = 0; var6 < 8; ++var6) {\n PcmStream var16 = this.field286[var6];\n PcmStream[] var17 = this.field286;\n this.field282[var6] = null;\n for (var17[var6] = null; var16 != null; var16 = var10) {\n var10 = var16.after;\n var16.after = null;\n }\n }\n }\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.fill(var1, 0, var2);\n }\n this.timeMs = UserComparator4.method2406();\n }\n\n @ObfuscatedName(\"ak\")\n @ObfuscatedSignature(descriptor = \"(Lav;II)V\", garbageValue = \"589893178\")\n final void method711(PcmStream var1, int var2) {\n int var3 = var2 >> 5;\n PcmStream var4 = this.field282[var3];\n if (var4 == null) {\n this.field286[var3] = var1;\n } else {\n var4.after = var1;\n }\n this.field282[var3] = var1;\n var1.field335 = var2;\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Lfp;\", garbageValue = \"1715478775\")\n static HorizontalAlignment[] method702() {\n return new HorizontalAlignment[] { HorizontalAlignment.field1708, HorizontalAlignment.field1707, HorizontalAlignment.HorizontalAlignment_centered };\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Ljm;\", garbageValue = \"1452483568\")\n public static class283[] method744() {\n return new class283[] { class283.field3648, class283.field3646, class283.field3649, class283.field3647 };\n }\n\n @ObfuscatedName(\"w\")\n @ObfuscatedSignature(descriptor = \"(ILbe;ZI)I\", garbageValue = \"1564904197\")\n static int method697(int var0, Script var1, boolean var2) {\n Widget var3;\n if (var0 >= 2000) {\n var0 -= 1000;\n var3 = HealthBarUpdate.getWidget(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n } else {\n var3 = var2 ? WorldMapDecoration.scriptDotWidget : class245.scriptActiveWidget;\n }\n String var4 = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n int[] var5 = null;\n if (var4.length() > 0 && var4.charAt(var4.length() - 1) == 'Y') {\n int var6 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var6 > 0) {\n for (var5 = new int[var6]; var6-- > 0; var5[var6] = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]) {\n }\n }\n var4 = var4.substring(0, var4.length() - 1);\n }\n Object[] var8 = new Object[var4.length() + 1];\n int var7;\n for (var7 = var8.length - 1; var7 >= 1; --var7) {\n if (var4.charAt(var7 - 1) == 's') {\n var8[var7] = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n } else {\n var8[var7] = new Integer(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n }\n }\n var7 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var7 != -1) {\n var8[0] = new Integer(var7);\n } else {\n var8 = null;\n }\n if (var0 == ScriptOpcodes.CC_SETONCLICK) {\n var3.onClick = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONHOLD) {\n var3.onHold = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRELEASE) {\n var3.onRelease = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEOVER) {\n var3.onMouseOver = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSELEAVE) {\n var3.onMouseLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAG) {\n var3.onDrag = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETLEAVE) {\n var3.onTargetLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONVARTRANSMIT) {\n var3.onVarTransmit = var8;\n var3.varTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTIMER) {\n var3.onTimer = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONOP) {\n var3.onOp = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAGCOMPLETE) {\n var3.onDragComplete = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLICKREPEAT) {\n var3.onClickRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEREPEAT) {\n var3.onMouseRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONINVTRANSMIT) {\n var3.onInvTransmit = var8;\n var3.invTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONSTATTRANSMIT) {\n var3.onStatTransmit = var8;\n var3.statTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETENTER) {\n var3.onTargetEnter = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSCROLLWHEEL) {\n var3.onScroll = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCHATTRANSMIT) {\n var3.onChatTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONKEY) {\n var3.onKey = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONFRIENDTRANSMIT) {\n var3.onFriendTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANTRANSMIT) {\n var3.onClanTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMISCTRANSMIT) {\n var3.onMiscTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDIALOGABORT) {\n var3.onDialogAbort = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSUBCHANGE) {\n var3.onSubChange = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSTOCKTRANSMIT) {\n var3.onStockTransmit = var8;\n } else if (var0 == 1426) {\n var3.field3168 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRESIZE) {\n var3.onResize = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANSETTINGSTRANSMIT) {\n var3.field3161 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANCHANNELTRANSMIT) {\n var3.field3163 = var8;\n } else if (var0 == 1430) {\n var3.field3157 = var8;\n } else {\n if (var0 != 1431) {\n return 2;\n }\n var3.field3158 = var8;\n }\n var3.hasListener = true;\n return 1;\n }\n\n @ObfuscatedName(\"ff\")\n @ObfuscatedSignature(descriptor = \"(III)V\", garbageValue = \"-856147347\")\n static void method741(int var0, int var1) {\n if (WorldMapDecorationType.clientPreferences.musicVolume != 0 && var0 != -1) {\n class67.method1886(class4.archive11, var0, 0, WorldMapDecorationType.clientPreferences.musicVolume, false);\n Client.field663 = true;\n }\n }\n}\n"} {"task_id": "Java_1069", "language": "Java", "task_type": "method_body", "source_file": "java/github/open-osrs/runelite/runescape-client/src/main/java/PcmPlayer.java", "mask_start_position": 3135, "mask_end_position": 3142, "canonical_solution": "{\n }", "pre_mask_code": "import java.util.concurrent.ScheduledExecutorService;\nimport net.runelite.mapping.Export;\nimport net.runelite.mapping.Implements;\nimport net.runelite.mapping.ObfuscatedGetter;\nimport net.runelite.mapping.ObfuscatedName;\nimport net.runelite.mapping.ObfuscatedSignature;\nimport net.runelite.rs.ScriptOpcodes;\n\n@ObfuscatedName(\"aq\")\n@Implements(\"PcmPlayer\")\npublic class PcmPlayer {\n\n @ObfuscatedName(\"sm\")\n @ObfuscatedGetter(intValue = 2053999609)\n static int field284;\n\n @ObfuscatedName(\"m\")\n @ObfuscatedGetter(intValue = 1333600085)\n public static int field279;\n\n @ObfuscatedName(\"k\")\n @Export(\"PcmPlayer_stereo\")\n public static boolean PcmPlayer_stereo;\n\n @ObfuscatedName(\"a\")\n @Export(\"soundSystemExecutor\")\n static ScheduledExecutorService soundSystemExecutor;\n\n @ObfuscatedName(\"e\")\n @ObfuscatedGetter(intValue = 234394993)\n public static int field283;\n\n @ObfuscatedName(\"v\")\n @Export(\"samples\")\n protected int[] samples;\n\n @ObfuscatedName(\"s\")\n @ObfuscatedSignature(descriptor = \"Lav;\")\n @Export(\"stream\")\n PcmStream stream;\n\n @ObfuscatedName(\"c\")\n @ObfuscatedGetter(intValue = -1215690509)\n int field269;\n\n @ObfuscatedName(\"b\")\n @ObfuscatedGetter(longValue = 2700493498205354685L)\n @Export(\"timeMs\")\n long timeMs;\n\n @ObfuscatedName(\"x\")\n @ObfuscatedGetter(intValue = 1537731573)\n @Export(\"capacity\")\n int capacity;\n\n @ObfuscatedName(\"p\")\n @ObfuscatedGetter(intValue = -1674723661)\n int field272;\n\n @ObfuscatedName(\"z\")\n @ObfuscatedGetter(intValue = 1001923267)\n int field265;\n\n @ObfuscatedName(\"h\")\n @ObfuscatedGetter(longValue = -2229248515898476515L)\n long field274;\n\n @ObfuscatedName(\"o\")\n @ObfuscatedGetter(intValue = 352319831)\n int field275;\n\n @ObfuscatedName(\"r\")\n @ObfuscatedGetter(intValue = 998812825)\n int field262;\n\n @ObfuscatedName(\"n\")\n @ObfuscatedGetter(intValue = -388583705)\n int field277;\n\n @ObfuscatedName(\"u\")\n @ObfuscatedGetter(longValue = -1357881854631939735L)\n long field278;\n\n @ObfuscatedName(\"d\")\n boolean field266;\n\n @ObfuscatedName(\"ay\")\n @ObfuscatedGetter(intValue = 461057869)\n int field281;\n\n @ObfuscatedName(\"al\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field286;\n\n @ObfuscatedName(\"ao\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field282;\n\n protected PcmPlayer() {\n this.field269 = 32;\n this.timeMs = UserComparator4.method2406();\n this.field274 = 0L;\n this.field275 = 0;\n this.field262 = 0;\n this.field277 = 0;\n this.field278 = 0L;\n this.field266 = true;\n this.field281 = 0;\n this.field286 = new PcmStream[8];\n this.field282 = new PcmStream[8];\n }\n\n @ObfuscatedName(\"l\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1783507069\")\n @Export(\"init\")\n protected void init() throws Exception {\n }\n\n @ObfuscatedName(\"q\")\n @ObfuscatedSignature(descriptor = \"(IB)V\", garbageValue = \"15\")\n @Export(\"open\")\n protected void open(int var1) throws Exception ", "post_mask_code": "\n\n @ObfuscatedName(\"f\")\n @ObfuscatedSignature(descriptor = \"(I)I\", garbageValue = \"-625452134\")\n @Export(\"position\")\n protected int position() throws Exception {\n return this.capacity;\n }\n\n @ObfuscatedName(\"j\")\n @Export(\"write\")\n protected void write() throws Exception {\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1407514911\")\n @Export(\"close\")\n protected void close() {\n }\n\n @ObfuscatedName(\"k\")\n @ObfuscatedSignature(descriptor = \"(B)V\", garbageValue = \"-115\")\n @Export(\"discard\")\n protected void discard() throws Exception {\n }\n\n @ObfuscatedName(\"o\")\n @ObfuscatedSignature(descriptor = \"(Lav;I)V\", garbageValue = \"1536652372\")\n @Export(\"setStream\")\n public final synchronized void setStream(PcmStream var1) {\n this.stream = var1;\n }\n\n @ObfuscatedName(\"r\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1578748771\")\n @Export(\"run\")\n public final synchronized void run() {\n if (this.samples != null) {\n long var1 = UserComparator4.method2406();\n try {\n if (0L != this.field274) {\n if (var1 < this.field274) {\n return;\n }\n this.open(this.capacity);\n this.field274 = 0L;\n this.field266 = true;\n }\n int var3 = this.position();\n if (this.field277 - var3 > this.field275) {\n this.field275 = this.field277 - var3;\n }\n int var4 = this.field272 + this.field265;\n if (var4 + 256 > 16384) {\n var4 = 16128;\n }\n if (var4 + 256 > this.capacity) {\n this.capacity += 1024;\n if (this.capacity > 16384) {\n this.capacity = 16384;\n }\n this.close();\n this.open(this.capacity);\n var3 = 0;\n this.field266 = true;\n if (var4 + 256 > this.capacity) {\n var4 = this.capacity - 256;\n this.field265 = var4 - this.field272;\n }\n }\n while (var3 < var4) {\n this.fill(this.samples, 256);\n this.write();\n var3 += 256;\n }\n if (var1 > this.field278) {\n if (!this.field266) {\n if (this.field275 == 0 && this.field262 == 0) {\n this.close();\n this.field274 = var1 + 2000L;\n return;\n }\n this.field265 = Math.min(this.field262, this.field275);\n this.field262 = this.field275;\n } else {\n this.field266 = false;\n }\n this.field275 = 0;\n this.field278 = var1 + 2000L;\n }\n this.field277 = var3;\n } catch (Exception var7) {\n this.close();\n this.field274 = var1 + 2000L;\n }\n try {\n if (var1 > this.timeMs + 500000L) {\n var1 = this.timeMs;\n }\n while (var1 > 5000L + this.timeMs) {\n this.skip(256);\n this.timeMs += (long) (256000 / field279);\n }\n } catch (Exception var6) {\n this.timeMs = var1;\n }\n }\n }\n\n @ObfuscatedName(\"n\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1285587409\")\n public final void method696() {\n this.field266 = true;\n }\n\n @ObfuscatedName(\"u\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1511155327\")\n @Export(\"tryDiscard\")\n public final synchronized void tryDiscard() {\n this.field266 = true;\n try {\n this.discard();\n } catch (Exception var2) {\n this.close();\n this.field274 = UserComparator4.method2406() + 2000L;\n }\n }\n\n @ObfuscatedName(\"d\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"25571035\")\n @Export(\"shutdown\")\n public final synchronized void shutdown() {\n if (Skeleton.soundSystem != null) {\n boolean var1 = true;\n for (int var2 = 0; var2 < 2; ++var2) {\n if (this == Skeleton.soundSystem.players[var2]) {\n Skeleton.soundSystem.players[var2] = null;\n }\n if (Skeleton.soundSystem.players[var2] != null) {\n var1 = false;\n }\n }\n if (var1) {\n soundSystemExecutor.shutdownNow();\n soundSystemExecutor = null;\n Skeleton.soundSystem = null;\n }\n }\n this.close();\n this.samples = null;\n }\n\n @ObfuscatedName(\"ab\")\n @ObfuscatedSignature(descriptor = \"(II)V\", garbageValue = \"4570450\")\n @Export(\"skip\")\n final void skip(int var1) {\n this.field281 -= var1;\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.skip(var1);\n }\n }\n\n @ObfuscatedName(\"ad\")\n @Export(\"fill\")\n final void fill(int[] var1, int var2) {\n int var3 = var2;\n if (PcmPlayer_stereo) {\n var3 = var2 << 1;\n }\n class321.clearIntArray(var1, 0, var3);\n this.field281 -= var2;\n if (this.stream != null && this.field281 <= 0) {\n this.field281 += field279 >> 4;\n class12.PcmStream_disable(this.stream);\n this.method711(this.stream, this.stream.vmethod944());\n int var4 = 0;\n int var5 = 255;\n int var6;\n PcmStream var10;\n label108: for (var6 = 7; var5 != 0; --var6) {\n int var7;\n int var8;\n if (var6 < 0) {\n var7 = var6 & 3;\n var8 = -(var6 >> 2);\n } else {\n var7 = var6;\n var8 = 0;\n }\n for (int var9 = var5 >>> var7 & 286331153; var9 != 0; var9 >>>= 4) {\n if ((var9 & 1) != 0) {\n var5 &= ~(1 << var7);\n var10 = null;\n PcmStream var11 = this.field286[var7];\n label102: while (true) {\n while (true) {\n if (var11 == null) {\n break label102;\n }\n AbstractSound var12 = var11.sound;\n if (var12 != null && var12.position > var8) {\n var5 |= 1 << var7;\n var10 = var11;\n var11 = var11.after;\n } else {\n var11.active = true;\n int var13 = var11.vmethod4889();\n var4 += var13;\n if (var12 != null) {\n var12.position += var13;\n }\n if (var4 >= this.field269) {\n break label108;\n }\n PcmStream var14 = var11.firstSubStream();\n if (var14 != null) {\n for (int var15 = var11.field335; var14 != null; var14 = var11.nextSubStream()) {\n this.method711(var14, var15 * var14.vmethod944() >> 8);\n }\n }\n PcmStream var18 = var11.after;\n var11.after = null;\n if (var10 == null) {\n this.field286[var7] = var18;\n } else {\n var10.after = var18;\n }\n if (var18 == null) {\n this.field282[var7] = var10;\n }\n var11 = var18;\n }\n }\n }\n }\n var7 += 4;\n ++var8;\n }\n }\n for (var6 = 0; var6 < 8; ++var6) {\n PcmStream var16 = this.field286[var6];\n PcmStream[] var17 = this.field286;\n this.field282[var6] = null;\n for (var17[var6] = null; var16 != null; var16 = var10) {\n var10 = var16.after;\n var16.after = null;\n }\n }\n }\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.fill(var1, 0, var2);\n }\n this.timeMs = UserComparator4.method2406();\n }\n\n @ObfuscatedName(\"ak\")\n @ObfuscatedSignature(descriptor = \"(Lav;II)V\", garbageValue = \"589893178\")\n final void method711(PcmStream var1, int var2) {\n int var3 = var2 >> 5;\n PcmStream var4 = this.field282[var3];\n if (var4 == null) {\n this.field286[var3] = var1;\n } else {\n var4.after = var1;\n }\n this.field282[var3] = var1;\n var1.field335 = var2;\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Lfp;\", garbageValue = \"1715478775\")\n static HorizontalAlignment[] method702() {\n return new HorizontalAlignment[] { HorizontalAlignment.field1708, HorizontalAlignment.field1707, HorizontalAlignment.HorizontalAlignment_centered };\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Ljm;\", garbageValue = \"1452483568\")\n public static class283[] method744() {\n return new class283[] { class283.field3648, class283.field3646, class283.field3649, class283.field3647 };\n }\n\n @ObfuscatedName(\"w\")\n @ObfuscatedSignature(descriptor = \"(ILbe;ZI)I\", garbageValue = \"1564904197\")\n static int method697(int var0, Script var1, boolean var2) {\n Widget var3;\n if (var0 >= 2000) {\n var0 -= 1000;\n var3 = HealthBarUpdate.getWidget(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n } else {\n var3 = var2 ? WorldMapDecoration.scriptDotWidget : class245.scriptActiveWidget;\n }\n String var4 = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n int[] var5 = null;\n if (var4.length() > 0 && var4.charAt(var4.length() - 1) == 'Y') {\n int var6 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var6 > 0) {\n for (var5 = new int[var6]; var6-- > 0; var5[var6] = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]) {\n }\n }\n var4 = var4.substring(0, var4.length() - 1);\n }\n Object[] var8 = new Object[var4.length() + 1];\n int var7;\n for (var7 = var8.length - 1; var7 >= 1; --var7) {\n if (var4.charAt(var7 - 1) == 's') {\n var8[var7] = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n } else {\n var8[var7] = new Integer(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n }\n }\n var7 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var7 != -1) {\n var8[0] = new Integer(var7);\n } else {\n var8 = null;\n }\n if (var0 == ScriptOpcodes.CC_SETONCLICK) {\n var3.onClick = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONHOLD) {\n var3.onHold = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRELEASE) {\n var3.onRelease = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEOVER) {\n var3.onMouseOver = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSELEAVE) {\n var3.onMouseLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAG) {\n var3.onDrag = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETLEAVE) {\n var3.onTargetLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONVARTRANSMIT) {\n var3.onVarTransmit = var8;\n var3.varTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTIMER) {\n var3.onTimer = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONOP) {\n var3.onOp = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAGCOMPLETE) {\n var3.onDragComplete = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLICKREPEAT) {\n var3.onClickRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEREPEAT) {\n var3.onMouseRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONINVTRANSMIT) {\n var3.onInvTransmit = var8;\n var3.invTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONSTATTRANSMIT) {\n var3.onStatTransmit = var8;\n var3.statTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETENTER) {\n var3.onTargetEnter = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSCROLLWHEEL) {\n var3.onScroll = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCHATTRANSMIT) {\n var3.onChatTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONKEY) {\n var3.onKey = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONFRIENDTRANSMIT) {\n var3.onFriendTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANTRANSMIT) {\n var3.onClanTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMISCTRANSMIT) {\n var3.onMiscTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDIALOGABORT) {\n var3.onDialogAbort = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSUBCHANGE) {\n var3.onSubChange = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSTOCKTRANSMIT) {\n var3.onStockTransmit = var8;\n } else if (var0 == 1426) {\n var3.field3168 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRESIZE) {\n var3.onResize = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANSETTINGSTRANSMIT) {\n var3.field3161 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANCHANNELTRANSMIT) {\n var3.field3163 = var8;\n } else if (var0 == 1430) {\n var3.field3157 = var8;\n } else {\n if (var0 != 1431) {\n return 2;\n }\n var3.field3158 = var8;\n }\n var3.hasListener = true;\n return 1;\n }\n\n @ObfuscatedName(\"ff\")\n @ObfuscatedSignature(descriptor = \"(III)V\", garbageValue = \"-856147347\")\n static void method741(int var0, int var1) {\n if (WorldMapDecorationType.clientPreferences.musicVolume != 0 && var0 != -1) {\n class67.method1886(class4.archive11, var0, 0, WorldMapDecorationType.clientPreferences.musicVolume, false);\n Client.field663 = true;\n }\n }\n}\n"} {"task_id": "Java_1070", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/open-osrs/runelite/runescape-client/src/main/java/PcmPlayer.java", "mask_start_position": 4170, "mask_end_position": 4170, "canonical_solution": "", "pre_mask_code": "import java.util.concurrent.ScheduledExecutorService;\nimport net.runelite.mapping.Export;\nimport net.runelite.mapping.Implements;\nimport net.runelite.mapping.ObfuscatedGetter;\nimport net.runelite.mapping.ObfuscatedName;\nimport net.runelite.mapping.ObfuscatedSignature;\nimport net.runelite.rs.ScriptOpcodes;\n\n@ObfuscatedName(\"aq\")\n@Implements(\"PcmPlayer\")\npublic class PcmPlayer {\n\n @ObfuscatedName(\"sm\")\n @ObfuscatedGetter(intValue = 2053999609)\n static int field284;\n\n @ObfuscatedName(\"m\")\n @ObfuscatedGetter(intValue = 1333600085)\n public static int field279;\n\n @ObfuscatedName(\"k\")\n @Export(\"PcmPlayer_stereo\")\n public static boolean PcmPlayer_stereo;\n\n @ObfuscatedName(\"a\")\n @Export(\"soundSystemExecutor\")\n static ScheduledExecutorService soundSystemExecutor;\n\n @ObfuscatedName(\"e\")\n @ObfuscatedGetter(intValue = 234394993)\n public static int field283;\n\n @ObfuscatedName(\"v\")\n @Export(\"samples\")\n protected int[] samples;\n\n @ObfuscatedName(\"s\")\n @ObfuscatedSignature(descriptor = \"Lav;\")\n @Export(\"stream\")\n PcmStream stream;\n\n @ObfuscatedName(\"c\")\n @ObfuscatedGetter(intValue = -1215690509)\n int field269;\n\n @ObfuscatedName(\"b\")\n @ObfuscatedGetter(longValue = 2700493498205354685L)\n @Export(\"timeMs\")\n long timeMs;\n\n @ObfuscatedName(\"x\")\n @ObfuscatedGetter(intValue = 1537731573)\n @Export(\"capacity\")\n int capacity;\n\n @ObfuscatedName(\"p\")\n @ObfuscatedGetter(intValue = -1674723661)\n int field272;\n\n @ObfuscatedName(\"z\")\n @ObfuscatedGetter(intValue = 1001923267)\n int field265;\n\n @ObfuscatedName(\"h\")\n @ObfuscatedGetter(longValue = -2229248515898476515L)\n long field274;\n\n @ObfuscatedName(\"o\")\n @ObfuscatedGetter(intValue = 352319831)\n int field275;\n\n @ObfuscatedName(\"r\")\n @ObfuscatedGetter(intValue = 998812825)\n int field262;\n\n @ObfuscatedName(\"n\")\n @ObfuscatedGetter(intValue = -388583705)\n int field277;\n\n @ObfuscatedName(\"u\")\n @ObfuscatedGetter(longValue = -1357881854631939735L)\n long field278;\n\n @ObfuscatedName(\"d\")\n boolean field266;\n\n @ObfuscatedName(\"ay\")\n @ObfuscatedGetter(intValue = 461057869)\n int field281;\n\n @ObfuscatedName(\"al\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field286;\n\n @ObfuscatedName(\"ao\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field282;\n\n protected PcmPlayer() {\n this.field269 = 32;\n this.timeMs = UserComparator4.method2406();\n this.field274 = 0L;\n this.field275 = 0;\n this.field262 = 0;\n this.field277 = 0;\n this.field278 = 0L;\n this.field266 = true;\n this.field281 = 0;\n this.field286 = new PcmStream[8];\n this.field282 = new PcmStream[8];\n }\n\n @ObfuscatedName(\"l\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1783507069\")\n @Export(\"init\")\n protected void init() throws Exception {\n }\n\n @ObfuscatedName(\"q\")\n @ObfuscatedSignature(descriptor = \"(IB)V\", garbageValue = \"15\")\n @Export(\"open\")\n protected void open(int var1) throws Exception {\n }\n\n @ObfuscatedName(\"f\")\n @ObfuscatedSignature(descriptor = \"(I)I\", garbageValue = \"-625452134\")\n @Export(\"position\")\n protected int position() throws Exception {\n return this.capacity;\n }\n\n @ObfuscatedName(\"j\")\n @Export(\"write\")\n protected void write() throws Exception {\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1407514911\")\n @Export(\"close\")\n protected void close() {\n }\n\n @ObfuscatedName(\"k\")\n @ObfuscatedSignature(descriptor = \"(B)V\", garbageValue = \"-115\")\n @Export(\"discard\")\n protected void discard() throws Exception {\n }\n\n @ObfuscatedName(\"o\")\n @ObfuscatedSignature(descriptor = \"(Lav;I)V\", garbageValue = \"1536652372\")\n @Export(\"setStream\")\n public final synchronized void setStream(PcmStream var1) {\n this.stream = var1;\n }\n\n @ObfuscatedName(\"r\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1578748771\")\n @Export(\"run\")\n public final synchronized void run() {", "post_mask_code": "\n if (this.samples != null) {\n long var1 = UserComparator4.method2406();\n try {\n if (0L != this.field274) {\n if (var1 < this.field274) {\n return;\n }\n this.open(this.capacity);\n this.field274 = 0L;\n this.field266 = true;\n }\n int var3 = this.position();\n if (this.field277 - var3 > this.field275) {\n this.field275 = this.field277 - var3;\n }\n int var4 = this.field272 + this.field265;\n if (var4 + 256 > 16384) {\n var4 = 16128;\n }\n if (var4 + 256 > this.capacity) {\n this.capacity += 1024;\n if (this.capacity > 16384) {\n this.capacity = 16384;\n }\n this.close();\n this.open(this.capacity);\n var3 = 0;\n this.field266 = true;\n if (var4 + 256 > this.capacity) {\n var4 = this.capacity - 256;\n this.field265 = var4 - this.field272;\n }\n }\n while (var3 < var4) {\n this.fill(this.samples, 256);\n this.write();\n var3 += 256;\n }\n if (var1 > this.field278) {\n if (!this.field266) {\n if (this.field275 == 0 && this.field262 == 0) {\n this.close();\n this.field274 = var1 + 2000L;\n return;\n }\n this.field265 = Math.min(this.field262, this.field275);\n this.field262 = this.field275;\n } else {\n this.field266 = false;\n }\n this.field275 = 0;\n this.field278 = var1 + 2000L;\n }\n this.field277 = var3;\n } catch (Exception var7) {\n this.close();\n this.field274 = var1 + 2000L;\n }\n try {\n if (var1 > this.timeMs + 500000L) {\n var1 = this.timeMs;\n }\n while (var1 > 5000L + this.timeMs) {\n this.skip(256);\n this.timeMs += (long) (256000 / field279);\n }\n } catch (Exception var6) {\n this.timeMs = var1;\n }\n }\n }\n\n @ObfuscatedName(\"n\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1285587409\")\n public final void method696() {\n this.field266 = true;\n }\n\n @ObfuscatedName(\"u\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1511155327\")\n @Export(\"tryDiscard\")\n public final synchronized void tryDiscard() {\n this.field266 = true;\n try {\n this.discard();\n } catch (Exception var2) {\n this.close();\n this.field274 = UserComparator4.method2406() + 2000L;\n }\n }\n\n @ObfuscatedName(\"d\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"25571035\")\n @Export(\"shutdown\")\n public final synchronized void shutdown() {\n if (Skeleton.soundSystem != null) {\n boolean var1 = true;\n for (int var2 = 0; var2 < 2; ++var2) {\n if (this == Skeleton.soundSystem.players[var2]) {\n Skeleton.soundSystem.players[var2] = null;\n }\n if (Skeleton.soundSystem.players[var2] != null) {\n var1 = false;\n }\n }\n if (var1) {\n soundSystemExecutor.shutdownNow();\n soundSystemExecutor = null;\n Skeleton.soundSystem = null;\n }\n }\n this.close();\n this.samples = null;\n }\n\n @ObfuscatedName(\"ab\")\n @ObfuscatedSignature(descriptor = \"(II)V\", garbageValue = \"4570450\")\n @Export(\"skip\")\n final void skip(int var1) {\n this.field281 -= var1;\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.skip(var1);\n }\n }\n\n @ObfuscatedName(\"ad\")\n @Export(\"fill\")\n final void fill(int[] var1, int var2) {\n int var3 = var2;\n if (PcmPlayer_stereo) {\n var3 = var2 << 1;\n }\n class321.clearIntArray(var1, 0, var3);\n this.field281 -= var2;\n if (this.stream != null && this.field281 <= 0) {\n this.field281 += field279 >> 4;\n class12.PcmStream_disable(this.stream);\n this.method711(this.stream, this.stream.vmethod944());\n int var4 = 0;\n int var5 = 255;\n int var6;\n PcmStream var10;\n label108: for (var6 = 7; var5 != 0; --var6) {\n int var7;\n int var8;\n if (var6 < 0) {\n var7 = var6 & 3;\n var8 = -(var6 >> 2);\n } else {\n var7 = var6;\n var8 = 0;\n }\n for (int var9 = var5 >>> var7 & 286331153; var9 != 0; var9 >>>= 4) {\n if ((var9 & 1) != 0) {\n var5 &= ~(1 << var7);\n var10 = null;\n PcmStream var11 = this.field286[var7];\n label102: while (true) {\n while (true) {\n if (var11 == null) {\n break label102;\n }\n AbstractSound var12 = var11.sound;\n if (var12 != null && var12.position > var8) {\n var5 |= 1 << var7;\n var10 = var11;\n var11 = var11.after;\n } else {\n var11.active = true;\n int var13 = var11.vmethod4889();\n var4 += var13;\n if (var12 != null) {\n var12.position += var13;\n }\n if (var4 >= this.field269) {\n break label108;\n }\n PcmStream var14 = var11.firstSubStream();\n if (var14 != null) {\n for (int var15 = var11.field335; var14 != null; var14 = var11.nextSubStream()) {\n this.method711(var14, var15 * var14.vmethod944() >> 8);\n }\n }\n PcmStream var18 = var11.after;\n var11.after = null;\n if (var10 == null) {\n this.field286[var7] = var18;\n } else {\n var10.after = var18;\n }\n if (var18 == null) {\n this.field282[var7] = var10;\n }\n var11 = var18;\n }\n }\n }\n }\n var7 += 4;\n ++var8;\n }\n }\n for (var6 = 0; var6 < 8; ++var6) {\n PcmStream var16 = this.field286[var6];\n PcmStream[] var17 = this.field286;\n this.field282[var6] = null;\n for (var17[var6] = null; var16 != null; var16 = var10) {\n var10 = var16.after;\n var16.after = null;\n }\n }\n }\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.fill(var1, 0, var2);\n }\n this.timeMs = UserComparator4.method2406();\n }\n\n @ObfuscatedName(\"ak\")\n @ObfuscatedSignature(descriptor = \"(Lav;II)V\", garbageValue = \"589893178\")\n final void method711(PcmStream var1, int var2) {\n int var3 = var2 >> 5;\n PcmStream var4 = this.field282[var3];\n if (var4 == null) {\n this.field286[var3] = var1;\n } else {\n var4.after = var1;\n }\n this.field282[var3] = var1;\n var1.field335 = var2;\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Lfp;\", garbageValue = \"1715478775\")\n static HorizontalAlignment[] method702() {\n return new HorizontalAlignment[] { HorizontalAlignment.field1708, HorizontalAlignment.field1707, HorizontalAlignment.HorizontalAlignment_centered };\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Ljm;\", garbageValue = \"1452483568\")\n public static class283[] method744() {\n return new class283[] { class283.field3648, class283.field3646, class283.field3649, class283.field3647 };\n }\n\n @ObfuscatedName(\"w\")\n @ObfuscatedSignature(descriptor = \"(ILbe;ZI)I\", garbageValue = \"1564904197\")\n static int method697(int var0, Script var1, boolean var2) {\n Widget var3;\n if (var0 >= 2000) {\n var0 -= 1000;\n var3 = HealthBarUpdate.getWidget(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n } else {\n var3 = var2 ? WorldMapDecoration.scriptDotWidget : class245.scriptActiveWidget;\n }\n String var4 = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n int[] var5 = null;\n if (var4.length() > 0 && var4.charAt(var4.length() - 1) == 'Y') {\n int var6 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var6 > 0) {\n for (var5 = new int[var6]; var6-- > 0; var5[var6] = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]) {\n }\n }\n var4 = var4.substring(0, var4.length() - 1);\n }\n Object[] var8 = new Object[var4.length() + 1];\n int var7;\n for (var7 = var8.length - 1; var7 >= 1; --var7) {\n if (var4.charAt(var7 - 1) == 's') {\n var8[var7] = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n } else {\n var8[var7] = new Integer(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n }\n }\n var7 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var7 != -1) {\n var8[0] = new Integer(var7);\n } else {\n var8 = null;\n }\n if (var0 == ScriptOpcodes.CC_SETONCLICK) {\n var3.onClick = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONHOLD) {\n var3.onHold = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRELEASE) {\n var3.onRelease = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEOVER) {\n var3.onMouseOver = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSELEAVE) {\n var3.onMouseLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAG) {\n var3.onDrag = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETLEAVE) {\n var3.onTargetLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONVARTRANSMIT) {\n var3.onVarTransmit = var8;\n var3.varTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTIMER) {\n var3.onTimer = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONOP) {\n var3.onOp = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAGCOMPLETE) {\n var3.onDragComplete = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLICKREPEAT) {\n var3.onClickRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEREPEAT) {\n var3.onMouseRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONINVTRANSMIT) {\n var3.onInvTransmit = var8;\n var3.invTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONSTATTRANSMIT) {\n var3.onStatTransmit = var8;\n var3.statTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETENTER) {\n var3.onTargetEnter = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSCROLLWHEEL) {\n var3.onScroll = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCHATTRANSMIT) {\n var3.onChatTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONKEY) {\n var3.onKey = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONFRIENDTRANSMIT) {\n var3.onFriendTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANTRANSMIT) {\n var3.onClanTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMISCTRANSMIT) {\n var3.onMiscTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDIALOGABORT) {\n var3.onDialogAbort = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSUBCHANGE) {\n var3.onSubChange = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSTOCKTRANSMIT) {\n var3.onStockTransmit = var8;\n } else if (var0 == 1426) {\n var3.field3168 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRESIZE) {\n var3.onResize = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANSETTINGSTRANSMIT) {\n var3.field3161 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANCHANNELTRANSMIT) {\n var3.field3163 = var8;\n } else if (var0 == 1430) {\n var3.field3157 = var8;\n } else {\n if (var0 != 1431) {\n return 2;\n }\n var3.field3158 = var8;\n }\n var3.hasListener = true;\n return 1;\n }\n\n @ObfuscatedName(\"ff\")\n @ObfuscatedSignature(descriptor = \"(III)V\", garbageValue = \"-856147347\")\n static void method741(int var0, int var1) {\n if (WorldMapDecorationType.clientPreferences.musicVolume != 0 && var0 != -1) {\n class67.method1886(class4.archive11, var0, 0, WorldMapDecorationType.clientPreferences.musicVolume, false);\n Client.field663 = true;\n }\n }\n}\n"} {"task_id": "Java_1071", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/open-osrs/runelite/runescape-client/src/main/java/PcmPlayer.java", "mask_start_position": 4179, "mask_end_position": 6869, "canonical_solution": "if (this.samples != null) {\n long var1 = UserComparator4.method2406();\n try {\n if (0L != this.field274) {\n if (var1 < this.field274) {\n return;\n }\n this.open(this.capacity);\n this.field274 = 0L;\n this.field266 = true;\n }\n int var3 = this.position();\n if (this.field277 - var3 > this.field275) {\n this.field275 = this.field277 - var3;\n }\n int var4 = this.field272 + this.field265;\n if (var4 + 256 > 16384) {\n var4 = 16128;\n }\n if (var4 + 256 > this.capacity) {\n this.capacity += 1024;\n if (this.capacity > 16384) {\n this.capacity = 16384;\n }\n this.close();\n this.open(this.capacity);\n var3 = 0;\n this.field266 = true;\n if (var4 + 256 > this.capacity) {\n var4 = this.capacity - 256;\n this.field265 = var4 - this.field272;\n }\n }\n while (var3 < var4) {\n this.fill(this.samples, 256);\n this.write();\n var3 += 256;\n }\n if (var1 > this.field278) {\n if (!this.field266) {\n if (this.field275 == 0 && this.field262 == 0) {\n this.close();\n this.field274 = var1 + 2000L;\n return;\n }\n this.field265 = Math.min(this.field262, this.field275);\n this.field262 = this.field275;\n } else {\n this.field266 = false;\n }\n this.field275 = 0;\n this.field278 = var1 + 2000L;\n }\n this.field277 = var3;\n } catch (Exception var7) {\n this.close();\n this.field274 = var1 + 2000L;\n }\n try {\n if (var1 > this.timeMs + 500000L) {\n var1 = this.timeMs;\n }\n while (var1 > 5000L + this.timeMs) {\n this.skip(256);\n this.timeMs += (long) (256000 / field279);\n }\n } catch (Exception var6) {\n this.timeMs = var1;\n }\n }", "pre_mask_code": "import java.util.concurrent.ScheduledExecutorService;\nimport net.runelite.mapping.Export;\nimport net.runelite.mapping.Implements;\nimport net.runelite.mapping.ObfuscatedGetter;\nimport net.runelite.mapping.ObfuscatedName;\nimport net.runelite.mapping.ObfuscatedSignature;\nimport net.runelite.rs.ScriptOpcodes;\n\n@ObfuscatedName(\"aq\")\n@Implements(\"PcmPlayer\")\npublic class PcmPlayer {\n\n @ObfuscatedName(\"sm\")\n @ObfuscatedGetter(intValue = 2053999609)\n static int field284;\n\n @ObfuscatedName(\"m\")\n @ObfuscatedGetter(intValue = 1333600085)\n public static int field279;\n\n @ObfuscatedName(\"k\")\n @Export(\"PcmPlayer_stereo\")\n public static boolean PcmPlayer_stereo;\n\n @ObfuscatedName(\"a\")\n @Export(\"soundSystemExecutor\")\n static ScheduledExecutorService soundSystemExecutor;\n\n @ObfuscatedName(\"e\")\n @ObfuscatedGetter(intValue = 234394993)\n public static int field283;\n\n @ObfuscatedName(\"v\")\n @Export(\"samples\")\n protected int[] samples;\n\n @ObfuscatedName(\"s\")\n @ObfuscatedSignature(descriptor = \"Lav;\")\n @Export(\"stream\")\n PcmStream stream;\n\n @ObfuscatedName(\"c\")\n @ObfuscatedGetter(intValue = -1215690509)\n int field269;\n\n @ObfuscatedName(\"b\")\n @ObfuscatedGetter(longValue = 2700493498205354685L)\n @Export(\"timeMs\")\n long timeMs;\n\n @ObfuscatedName(\"x\")\n @ObfuscatedGetter(intValue = 1537731573)\n @Export(\"capacity\")\n int capacity;\n\n @ObfuscatedName(\"p\")\n @ObfuscatedGetter(intValue = -1674723661)\n int field272;\n\n @ObfuscatedName(\"z\")\n @ObfuscatedGetter(intValue = 1001923267)\n int field265;\n\n @ObfuscatedName(\"h\")\n @ObfuscatedGetter(longValue = -2229248515898476515L)\n long field274;\n\n @ObfuscatedName(\"o\")\n @ObfuscatedGetter(intValue = 352319831)\n int field275;\n\n @ObfuscatedName(\"r\")\n @ObfuscatedGetter(intValue = 998812825)\n int field262;\n\n @ObfuscatedName(\"n\")\n @ObfuscatedGetter(intValue = -388583705)\n int field277;\n\n @ObfuscatedName(\"u\")\n @ObfuscatedGetter(longValue = -1357881854631939735L)\n long field278;\n\n @ObfuscatedName(\"d\")\n boolean field266;\n\n @ObfuscatedName(\"ay\")\n @ObfuscatedGetter(intValue = 461057869)\n int field281;\n\n @ObfuscatedName(\"al\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field286;\n\n @ObfuscatedName(\"ao\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field282;\n\n protected PcmPlayer() {\n this.field269 = 32;\n this.timeMs = UserComparator4.method2406();\n this.field274 = 0L;\n this.field275 = 0;\n this.field262 = 0;\n this.field277 = 0;\n this.field278 = 0L;\n this.field266 = true;\n this.field281 = 0;\n this.field286 = new PcmStream[8];\n this.field282 = new PcmStream[8];\n }\n\n @ObfuscatedName(\"l\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1783507069\")\n @Export(\"init\")\n protected void init() throws Exception {\n }\n\n @ObfuscatedName(\"q\")\n @ObfuscatedSignature(descriptor = \"(IB)V\", garbageValue = \"15\")\n @Export(\"open\")\n protected void open(int var1) throws Exception {\n }\n\n @ObfuscatedName(\"f\")\n @ObfuscatedSignature(descriptor = \"(I)I\", garbageValue = \"-625452134\")\n @Export(\"position\")\n protected int position() throws Exception {\n return this.capacity;\n }\n\n @ObfuscatedName(\"j\")\n @Export(\"write\")\n protected void write() throws Exception {\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1407514911\")\n @Export(\"close\")\n protected void close() {\n }\n\n @ObfuscatedName(\"k\")\n @ObfuscatedSignature(descriptor = \"(B)V\", garbageValue = \"-115\")\n @Export(\"discard\")\n protected void discard() throws Exception {\n }\n\n @ObfuscatedName(\"o\")\n @ObfuscatedSignature(descriptor = \"(Lav;I)V\", garbageValue = \"1536652372\")\n @Export(\"setStream\")\n public final synchronized void setStream(PcmStream var1) {\n this.stream = var1;\n }\n\n @ObfuscatedName(\"r\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1578748771\")\n @Export(\"run\")\n public final synchronized void run() {\n ", "post_mask_code": "\n }\n\n @ObfuscatedName(\"n\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1285587409\")\n public final void method696() {\n this.field266 = true;\n }\n\n @ObfuscatedName(\"u\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1511155327\")\n @Export(\"tryDiscard\")\n public final synchronized void tryDiscard() {\n this.field266 = true;\n try {\n this.discard();\n } catch (Exception var2) {\n this.close();\n this.field274 = UserComparator4.method2406() + 2000L;\n }\n }\n\n @ObfuscatedName(\"d\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"25571035\")\n @Export(\"shutdown\")\n public final synchronized void shutdown() {\n if (Skeleton.soundSystem != null) {\n boolean var1 = true;\n for (int var2 = 0; var2 < 2; ++var2) {\n if (this == Skeleton.soundSystem.players[var2]) {\n Skeleton.soundSystem.players[var2] = null;\n }\n if (Skeleton.soundSystem.players[var2] != null) {\n var1 = false;\n }\n }\n if (var1) {\n soundSystemExecutor.shutdownNow();\n soundSystemExecutor = null;\n Skeleton.soundSystem = null;\n }\n }\n this.close();\n this.samples = null;\n }\n\n @ObfuscatedName(\"ab\")\n @ObfuscatedSignature(descriptor = \"(II)V\", garbageValue = \"4570450\")\n @Export(\"skip\")\n final void skip(int var1) {\n this.field281 -= var1;\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.skip(var1);\n }\n }\n\n @ObfuscatedName(\"ad\")\n @Export(\"fill\")\n final void fill(int[] var1, int var2) {\n int var3 = var2;\n if (PcmPlayer_stereo) {\n var3 = var2 << 1;\n }\n class321.clearIntArray(var1, 0, var3);\n this.field281 -= var2;\n if (this.stream != null && this.field281 <= 0) {\n this.field281 += field279 >> 4;\n class12.PcmStream_disable(this.stream);\n this.method711(this.stream, this.stream.vmethod944());\n int var4 = 0;\n int var5 = 255;\n int var6;\n PcmStream var10;\n label108: for (var6 = 7; var5 != 0; --var6) {\n int var7;\n int var8;\n if (var6 < 0) {\n var7 = var6 & 3;\n var8 = -(var6 >> 2);\n } else {\n var7 = var6;\n var8 = 0;\n }\n for (int var9 = var5 >>> var7 & 286331153; var9 != 0; var9 >>>= 4) {\n if ((var9 & 1) != 0) {\n var5 &= ~(1 << var7);\n var10 = null;\n PcmStream var11 = this.field286[var7];\n label102: while (true) {\n while (true) {\n if (var11 == null) {\n break label102;\n }\n AbstractSound var12 = var11.sound;\n if (var12 != null && var12.position > var8) {\n var5 |= 1 << var7;\n var10 = var11;\n var11 = var11.after;\n } else {\n var11.active = true;\n int var13 = var11.vmethod4889();\n var4 += var13;\n if (var12 != null) {\n var12.position += var13;\n }\n if (var4 >= this.field269) {\n break label108;\n }\n PcmStream var14 = var11.firstSubStream();\n if (var14 != null) {\n for (int var15 = var11.field335; var14 != null; var14 = var11.nextSubStream()) {\n this.method711(var14, var15 * var14.vmethod944() >> 8);\n }\n }\n PcmStream var18 = var11.after;\n var11.after = null;\n if (var10 == null) {\n this.field286[var7] = var18;\n } else {\n var10.after = var18;\n }\n if (var18 == null) {\n this.field282[var7] = var10;\n }\n var11 = var18;\n }\n }\n }\n }\n var7 += 4;\n ++var8;\n }\n }\n for (var6 = 0; var6 < 8; ++var6) {\n PcmStream var16 = this.field286[var6];\n PcmStream[] var17 = this.field286;\n this.field282[var6] = null;\n for (var17[var6] = null; var16 != null; var16 = var10) {\n var10 = var16.after;\n var16.after = null;\n }\n }\n }\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.fill(var1, 0, var2);\n }\n this.timeMs = UserComparator4.method2406();\n }\n\n @ObfuscatedName(\"ak\")\n @ObfuscatedSignature(descriptor = \"(Lav;II)V\", garbageValue = \"589893178\")\n final void method711(PcmStream var1, int var2) {\n int var3 = var2 >> 5;\n PcmStream var4 = this.field282[var3];\n if (var4 == null) {\n this.field286[var3] = var1;\n } else {\n var4.after = var1;\n }\n this.field282[var3] = var1;\n var1.field335 = var2;\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Lfp;\", garbageValue = \"1715478775\")\n static HorizontalAlignment[] method702() {\n return new HorizontalAlignment[] { HorizontalAlignment.field1708, HorizontalAlignment.field1707, HorizontalAlignment.HorizontalAlignment_centered };\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Ljm;\", garbageValue = \"1452483568\")\n public static class283[] method744() {\n return new class283[] { class283.field3648, class283.field3646, class283.field3649, class283.field3647 };\n }\n\n @ObfuscatedName(\"w\")\n @ObfuscatedSignature(descriptor = \"(ILbe;ZI)I\", garbageValue = \"1564904197\")\n static int method697(int var0, Script var1, boolean var2) {\n Widget var3;\n if (var0 >= 2000) {\n var0 -= 1000;\n var3 = HealthBarUpdate.getWidget(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n } else {\n var3 = var2 ? WorldMapDecoration.scriptDotWidget : class245.scriptActiveWidget;\n }\n String var4 = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n int[] var5 = null;\n if (var4.length() > 0 && var4.charAt(var4.length() - 1) == 'Y') {\n int var6 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var6 > 0) {\n for (var5 = new int[var6]; var6-- > 0; var5[var6] = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]) {\n }\n }\n var4 = var4.substring(0, var4.length() - 1);\n }\n Object[] var8 = new Object[var4.length() + 1];\n int var7;\n for (var7 = var8.length - 1; var7 >= 1; --var7) {\n if (var4.charAt(var7 - 1) == 's') {\n var8[var7] = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n } else {\n var8[var7] = new Integer(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n }\n }\n var7 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var7 != -1) {\n var8[0] = new Integer(var7);\n } else {\n var8 = null;\n }\n if (var0 == ScriptOpcodes.CC_SETONCLICK) {\n var3.onClick = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONHOLD) {\n var3.onHold = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRELEASE) {\n var3.onRelease = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEOVER) {\n var3.onMouseOver = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSELEAVE) {\n var3.onMouseLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAG) {\n var3.onDrag = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETLEAVE) {\n var3.onTargetLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONVARTRANSMIT) {\n var3.onVarTransmit = var8;\n var3.varTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTIMER) {\n var3.onTimer = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONOP) {\n var3.onOp = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAGCOMPLETE) {\n var3.onDragComplete = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLICKREPEAT) {\n var3.onClickRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEREPEAT) {\n var3.onMouseRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONINVTRANSMIT) {\n var3.onInvTransmit = var8;\n var3.invTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONSTATTRANSMIT) {\n var3.onStatTransmit = var8;\n var3.statTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETENTER) {\n var3.onTargetEnter = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSCROLLWHEEL) {\n var3.onScroll = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCHATTRANSMIT) {\n var3.onChatTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONKEY) {\n var3.onKey = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONFRIENDTRANSMIT) {\n var3.onFriendTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANTRANSMIT) {\n var3.onClanTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMISCTRANSMIT) {\n var3.onMiscTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDIALOGABORT) {\n var3.onDialogAbort = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSUBCHANGE) {\n var3.onSubChange = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSTOCKTRANSMIT) {\n var3.onStockTransmit = var8;\n } else if (var0 == 1426) {\n var3.field3168 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRESIZE) {\n var3.onResize = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANSETTINGSTRANSMIT) {\n var3.field3161 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANCHANNELTRANSMIT) {\n var3.field3163 = var8;\n } else if (var0 == 1430) {\n var3.field3157 = var8;\n } else {\n if (var0 != 1431) {\n return 2;\n }\n var3.field3158 = var8;\n }\n var3.hasListener = true;\n return 1;\n }\n\n @ObfuscatedName(\"ff\")\n @ObfuscatedSignature(descriptor = \"(III)V\", garbageValue = \"-856147347\")\n static void method741(int var0, int var1) {\n if (WorldMapDecorationType.clientPreferences.musicVolume != 0 && var0 != -1) {\n class67.method1886(class4.archive11, var0, 0, WorldMapDecorationType.clientPreferences.musicVolume, false);\n Client.field663 = true;\n }\n }\n}\n"} {"task_id": "Java_1072", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/open-osrs/runelite/runescape-client/src/main/java/PcmPlayer.java", "mask_start_position": 6874, "mask_end_position": 6875, "canonical_solution": "}", "pre_mask_code": "import java.util.concurrent.ScheduledExecutorService;\nimport net.runelite.mapping.Export;\nimport net.runelite.mapping.Implements;\nimport net.runelite.mapping.ObfuscatedGetter;\nimport net.runelite.mapping.ObfuscatedName;\nimport net.runelite.mapping.ObfuscatedSignature;\nimport net.runelite.rs.ScriptOpcodes;\n\n@ObfuscatedName(\"aq\")\n@Implements(\"PcmPlayer\")\npublic class PcmPlayer {\n\n @ObfuscatedName(\"sm\")\n @ObfuscatedGetter(intValue = 2053999609)\n static int field284;\n\n @ObfuscatedName(\"m\")\n @ObfuscatedGetter(intValue = 1333600085)\n public static int field279;\n\n @ObfuscatedName(\"k\")\n @Export(\"PcmPlayer_stereo\")\n public static boolean PcmPlayer_stereo;\n\n @ObfuscatedName(\"a\")\n @Export(\"soundSystemExecutor\")\n static ScheduledExecutorService soundSystemExecutor;\n\n @ObfuscatedName(\"e\")\n @ObfuscatedGetter(intValue = 234394993)\n public static int field283;\n\n @ObfuscatedName(\"v\")\n @Export(\"samples\")\n protected int[] samples;\n\n @ObfuscatedName(\"s\")\n @ObfuscatedSignature(descriptor = \"Lav;\")\n @Export(\"stream\")\n PcmStream stream;\n\n @ObfuscatedName(\"c\")\n @ObfuscatedGetter(intValue = -1215690509)\n int field269;\n\n @ObfuscatedName(\"b\")\n @ObfuscatedGetter(longValue = 2700493498205354685L)\n @Export(\"timeMs\")\n long timeMs;\n\n @ObfuscatedName(\"x\")\n @ObfuscatedGetter(intValue = 1537731573)\n @Export(\"capacity\")\n int capacity;\n\n @ObfuscatedName(\"p\")\n @ObfuscatedGetter(intValue = -1674723661)\n int field272;\n\n @ObfuscatedName(\"z\")\n @ObfuscatedGetter(intValue = 1001923267)\n int field265;\n\n @ObfuscatedName(\"h\")\n @ObfuscatedGetter(longValue = -2229248515898476515L)\n long field274;\n\n @ObfuscatedName(\"o\")\n @ObfuscatedGetter(intValue = 352319831)\n int field275;\n\n @ObfuscatedName(\"r\")\n @ObfuscatedGetter(intValue = 998812825)\n int field262;\n\n @ObfuscatedName(\"n\")\n @ObfuscatedGetter(intValue = -388583705)\n int field277;\n\n @ObfuscatedName(\"u\")\n @ObfuscatedGetter(longValue = -1357881854631939735L)\n long field278;\n\n @ObfuscatedName(\"d\")\n boolean field266;\n\n @ObfuscatedName(\"ay\")\n @ObfuscatedGetter(intValue = 461057869)\n int field281;\n\n @ObfuscatedName(\"al\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field286;\n\n @ObfuscatedName(\"ao\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field282;\n\n protected PcmPlayer() {\n this.field269 = 32;\n this.timeMs = UserComparator4.method2406();\n this.field274 = 0L;\n this.field275 = 0;\n this.field262 = 0;\n this.field277 = 0;\n this.field278 = 0L;\n this.field266 = true;\n this.field281 = 0;\n this.field286 = new PcmStream[8];\n this.field282 = new PcmStream[8];\n }\n\n @ObfuscatedName(\"l\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1783507069\")\n @Export(\"init\")\n protected void init() throws Exception {\n }\n\n @ObfuscatedName(\"q\")\n @ObfuscatedSignature(descriptor = \"(IB)V\", garbageValue = \"15\")\n @Export(\"open\")\n protected void open(int var1) throws Exception {\n }\n\n @ObfuscatedName(\"f\")\n @ObfuscatedSignature(descriptor = \"(I)I\", garbageValue = \"-625452134\")\n @Export(\"position\")\n protected int position() throws Exception {\n return this.capacity;\n }\n\n @ObfuscatedName(\"j\")\n @Export(\"write\")\n protected void write() throws Exception {\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1407514911\")\n @Export(\"close\")\n protected void close() {\n }\n\n @ObfuscatedName(\"k\")\n @ObfuscatedSignature(descriptor = \"(B)V\", garbageValue = \"-115\")\n @Export(\"discard\")\n protected void discard() throws Exception {\n }\n\n @ObfuscatedName(\"o\")\n @ObfuscatedSignature(descriptor = \"(Lav;I)V\", garbageValue = \"1536652372\")\n @Export(\"setStream\")\n public final synchronized void setStream(PcmStream var1) {\n this.stream = var1;\n }\n\n @ObfuscatedName(\"r\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1578748771\")\n @Export(\"run\")\n public final synchronized void run() {\n if (this.samples != null) {\n long var1 = UserComparator4.method2406();\n try {\n if (0L != this.field274) {\n if (var1 < this.field274) {\n return;\n }\n this.open(this.capacity);\n this.field274 = 0L;\n this.field266 = true;\n }\n int var3 = this.position();\n if (this.field277 - var3 > this.field275) {\n this.field275 = this.field277 - var3;\n }\n int var4 = this.field272 + this.field265;\n if (var4 + 256 > 16384) {\n var4 = 16128;\n }\n if (var4 + 256 > this.capacity) {\n this.capacity += 1024;\n if (this.capacity > 16384) {\n this.capacity = 16384;\n }\n this.close();\n this.open(this.capacity);\n var3 = 0;\n this.field266 = true;\n if (var4 + 256 > this.capacity) {\n var4 = this.capacity - 256;\n this.field265 = var4 - this.field272;\n }\n }\n while (var3 < var4) {\n this.fill(this.samples, 256);\n this.write();\n var3 += 256;\n }\n if (var1 > this.field278) {\n if (!this.field266) {\n if (this.field275 == 0 && this.field262 == 0) {\n this.close();\n this.field274 = var1 + 2000L;\n return;\n }\n this.field265 = Math.min(this.field262, this.field275);\n this.field262 = this.field275;\n } else {\n this.field266 = false;\n }\n this.field275 = 0;\n this.field278 = var1 + 2000L;\n }\n this.field277 = var3;\n } catch (Exception var7) {\n this.close();\n this.field274 = var1 + 2000L;\n }\n try {\n if (var1 > this.timeMs + 500000L) {\n var1 = this.timeMs;\n }\n while (var1 > 5000L + this.timeMs) {\n this.skip(256);\n this.timeMs += (long) (256000 / field279);\n }\n } catch (Exception var6) {\n this.timeMs = var1;\n }\n }\n ", "post_mask_code": "\n\n @ObfuscatedName(\"n\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1285587409\")\n public final void method696() {\n this.field266 = true;\n }\n\n @ObfuscatedName(\"u\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1511155327\")\n @Export(\"tryDiscard\")\n public final synchronized void tryDiscard() {\n this.field266 = true;\n try {\n this.discard();\n } catch (Exception var2) {\n this.close();\n this.field274 = UserComparator4.method2406() + 2000L;\n }\n }\n\n @ObfuscatedName(\"d\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"25571035\")\n @Export(\"shutdown\")\n public final synchronized void shutdown() {\n if (Skeleton.soundSystem != null) {\n boolean var1 = true;\n for (int var2 = 0; var2 < 2; ++var2) {\n if (this == Skeleton.soundSystem.players[var2]) {\n Skeleton.soundSystem.players[var2] = null;\n }\n if (Skeleton.soundSystem.players[var2] != null) {\n var1 = false;\n }\n }\n if (var1) {\n soundSystemExecutor.shutdownNow();\n soundSystemExecutor = null;\n Skeleton.soundSystem = null;\n }\n }\n this.close();\n this.samples = null;\n }\n\n @ObfuscatedName(\"ab\")\n @ObfuscatedSignature(descriptor = \"(II)V\", garbageValue = \"4570450\")\n @Export(\"skip\")\n final void skip(int var1) {\n this.field281 -= var1;\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.skip(var1);\n }\n }\n\n @ObfuscatedName(\"ad\")\n @Export(\"fill\")\n final void fill(int[] var1, int var2) {\n int var3 = var2;\n if (PcmPlayer_stereo) {\n var3 = var2 << 1;\n }\n class321.clearIntArray(var1, 0, var3);\n this.field281 -= var2;\n if (this.stream != null && this.field281 <= 0) {\n this.field281 += field279 >> 4;\n class12.PcmStream_disable(this.stream);\n this.method711(this.stream, this.stream.vmethod944());\n int var4 = 0;\n int var5 = 255;\n int var6;\n PcmStream var10;\n label108: for (var6 = 7; var5 != 0; --var6) {\n int var7;\n int var8;\n if (var6 < 0) {\n var7 = var6 & 3;\n var8 = -(var6 >> 2);\n } else {\n var7 = var6;\n var8 = 0;\n }\n for (int var9 = var5 >>> var7 & 286331153; var9 != 0; var9 >>>= 4) {\n if ((var9 & 1) != 0) {\n var5 &= ~(1 << var7);\n var10 = null;\n PcmStream var11 = this.field286[var7];\n label102: while (true) {\n while (true) {\n if (var11 == null) {\n break label102;\n }\n AbstractSound var12 = var11.sound;\n if (var12 != null && var12.position > var8) {\n var5 |= 1 << var7;\n var10 = var11;\n var11 = var11.after;\n } else {\n var11.active = true;\n int var13 = var11.vmethod4889();\n var4 += var13;\n if (var12 != null) {\n var12.position += var13;\n }\n if (var4 >= this.field269) {\n break label108;\n }\n PcmStream var14 = var11.firstSubStream();\n if (var14 != null) {\n for (int var15 = var11.field335; var14 != null; var14 = var11.nextSubStream()) {\n this.method711(var14, var15 * var14.vmethod944() >> 8);\n }\n }\n PcmStream var18 = var11.after;\n var11.after = null;\n if (var10 == null) {\n this.field286[var7] = var18;\n } else {\n var10.after = var18;\n }\n if (var18 == null) {\n this.field282[var7] = var10;\n }\n var11 = var18;\n }\n }\n }\n }\n var7 += 4;\n ++var8;\n }\n }\n for (var6 = 0; var6 < 8; ++var6) {\n PcmStream var16 = this.field286[var6];\n PcmStream[] var17 = this.field286;\n this.field282[var6] = null;\n for (var17[var6] = null; var16 != null; var16 = var10) {\n var10 = var16.after;\n var16.after = null;\n }\n }\n }\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.fill(var1, 0, var2);\n }\n this.timeMs = UserComparator4.method2406();\n }\n\n @ObfuscatedName(\"ak\")\n @ObfuscatedSignature(descriptor = \"(Lav;II)V\", garbageValue = \"589893178\")\n final void method711(PcmStream var1, int var2) {\n int var3 = var2 >> 5;\n PcmStream var4 = this.field282[var3];\n if (var4 == null) {\n this.field286[var3] = var1;\n } else {\n var4.after = var1;\n }\n this.field282[var3] = var1;\n var1.field335 = var2;\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Lfp;\", garbageValue = \"1715478775\")\n static HorizontalAlignment[] method702() {\n return new HorizontalAlignment[] { HorizontalAlignment.field1708, HorizontalAlignment.field1707, HorizontalAlignment.HorizontalAlignment_centered };\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Ljm;\", garbageValue = \"1452483568\")\n public static class283[] method744() {\n return new class283[] { class283.field3648, class283.field3646, class283.field3649, class283.field3647 };\n }\n\n @ObfuscatedName(\"w\")\n @ObfuscatedSignature(descriptor = \"(ILbe;ZI)I\", garbageValue = \"1564904197\")\n static int method697(int var0, Script var1, boolean var2) {\n Widget var3;\n if (var0 >= 2000) {\n var0 -= 1000;\n var3 = HealthBarUpdate.getWidget(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n } else {\n var3 = var2 ? WorldMapDecoration.scriptDotWidget : class245.scriptActiveWidget;\n }\n String var4 = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n int[] var5 = null;\n if (var4.length() > 0 && var4.charAt(var4.length() - 1) == 'Y') {\n int var6 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var6 > 0) {\n for (var5 = new int[var6]; var6-- > 0; var5[var6] = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]) {\n }\n }\n var4 = var4.substring(0, var4.length() - 1);\n }\n Object[] var8 = new Object[var4.length() + 1];\n int var7;\n for (var7 = var8.length - 1; var7 >= 1; --var7) {\n if (var4.charAt(var7 - 1) == 's') {\n var8[var7] = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n } else {\n var8[var7] = new Integer(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n }\n }\n var7 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var7 != -1) {\n var8[0] = new Integer(var7);\n } else {\n var8 = null;\n }\n if (var0 == ScriptOpcodes.CC_SETONCLICK) {\n var3.onClick = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONHOLD) {\n var3.onHold = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRELEASE) {\n var3.onRelease = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEOVER) {\n var3.onMouseOver = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSELEAVE) {\n var3.onMouseLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAG) {\n var3.onDrag = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETLEAVE) {\n var3.onTargetLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONVARTRANSMIT) {\n var3.onVarTransmit = var8;\n var3.varTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTIMER) {\n var3.onTimer = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONOP) {\n var3.onOp = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAGCOMPLETE) {\n var3.onDragComplete = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLICKREPEAT) {\n var3.onClickRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEREPEAT) {\n var3.onMouseRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONINVTRANSMIT) {\n var3.onInvTransmit = var8;\n var3.invTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONSTATTRANSMIT) {\n var3.onStatTransmit = var8;\n var3.statTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETENTER) {\n var3.onTargetEnter = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSCROLLWHEEL) {\n var3.onScroll = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCHATTRANSMIT) {\n var3.onChatTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONKEY) {\n var3.onKey = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONFRIENDTRANSMIT) {\n var3.onFriendTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANTRANSMIT) {\n var3.onClanTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMISCTRANSMIT) {\n var3.onMiscTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDIALOGABORT) {\n var3.onDialogAbort = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSUBCHANGE) {\n var3.onSubChange = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSTOCKTRANSMIT) {\n var3.onStockTransmit = var8;\n } else if (var0 == 1426) {\n var3.field3168 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRESIZE) {\n var3.onResize = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANSETTINGSTRANSMIT) {\n var3.field3161 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANCHANNELTRANSMIT) {\n var3.field3163 = var8;\n } else if (var0 == 1430) {\n var3.field3157 = var8;\n } else {\n if (var0 != 1431) {\n return 2;\n }\n var3.field3158 = var8;\n }\n var3.hasListener = true;\n return 1;\n }\n\n @ObfuscatedName(\"ff\")\n @ObfuscatedSignature(descriptor = \"(III)V\", garbageValue = \"-856147347\")\n static void method741(int var0, int var1) {\n if (WorldMapDecorationType.clientPreferences.musicVolume != 0 && var0 != -1) {\n class67.method1886(class4.archive11, var0, 0, WorldMapDecorationType.clientPreferences.musicVolume, false);\n Client.field663 = true;\n }\n }\n}\n"} {"task_id": "Java_1073", "language": "Java", "task_type": "single_line", "source_file": "java/github/open-osrs/runelite/runescape-client/src/main/java/PcmPlayer.java", "mask_start_position": 8441, "mask_end_position": 8448, "canonical_solution": "= var1;", "pre_mask_code": "import java.util.concurrent.ScheduledExecutorService;\nimport net.runelite.mapping.Export;\nimport net.runelite.mapping.Implements;\nimport net.runelite.mapping.ObfuscatedGetter;\nimport net.runelite.mapping.ObfuscatedName;\nimport net.runelite.mapping.ObfuscatedSignature;\nimport net.runelite.rs.ScriptOpcodes;\n\n@ObfuscatedName(\"aq\")\n@Implements(\"PcmPlayer\")\npublic class PcmPlayer {\n\n @ObfuscatedName(\"sm\")\n @ObfuscatedGetter(intValue = 2053999609)\n static int field284;\n\n @ObfuscatedName(\"m\")\n @ObfuscatedGetter(intValue = 1333600085)\n public static int field279;\n\n @ObfuscatedName(\"k\")\n @Export(\"PcmPlayer_stereo\")\n public static boolean PcmPlayer_stereo;\n\n @ObfuscatedName(\"a\")\n @Export(\"soundSystemExecutor\")\n static ScheduledExecutorService soundSystemExecutor;\n\n @ObfuscatedName(\"e\")\n @ObfuscatedGetter(intValue = 234394993)\n public static int field283;\n\n @ObfuscatedName(\"v\")\n @Export(\"samples\")\n protected int[] samples;\n\n @ObfuscatedName(\"s\")\n @ObfuscatedSignature(descriptor = \"Lav;\")\n @Export(\"stream\")\n PcmStream stream;\n\n @ObfuscatedName(\"c\")\n @ObfuscatedGetter(intValue = -1215690509)\n int field269;\n\n @ObfuscatedName(\"b\")\n @ObfuscatedGetter(longValue = 2700493498205354685L)\n @Export(\"timeMs\")\n long timeMs;\n\n @ObfuscatedName(\"x\")\n @ObfuscatedGetter(intValue = 1537731573)\n @Export(\"capacity\")\n int capacity;\n\n @ObfuscatedName(\"p\")\n @ObfuscatedGetter(intValue = -1674723661)\n int field272;\n\n @ObfuscatedName(\"z\")\n @ObfuscatedGetter(intValue = 1001923267)\n int field265;\n\n @ObfuscatedName(\"h\")\n @ObfuscatedGetter(longValue = -2229248515898476515L)\n long field274;\n\n @ObfuscatedName(\"o\")\n @ObfuscatedGetter(intValue = 352319831)\n int field275;\n\n @ObfuscatedName(\"r\")\n @ObfuscatedGetter(intValue = 998812825)\n int field262;\n\n @ObfuscatedName(\"n\")\n @ObfuscatedGetter(intValue = -388583705)\n int field277;\n\n @ObfuscatedName(\"u\")\n @ObfuscatedGetter(longValue = -1357881854631939735L)\n long field278;\n\n @ObfuscatedName(\"d\")\n boolean field266;\n\n @ObfuscatedName(\"ay\")\n @ObfuscatedGetter(intValue = 461057869)\n int field281;\n\n @ObfuscatedName(\"al\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field286;\n\n @ObfuscatedName(\"ao\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field282;\n\n protected PcmPlayer() {\n this.field269 = 32;\n this.timeMs = UserComparator4.method2406();\n this.field274 = 0L;\n this.field275 = 0;\n this.field262 = 0;\n this.field277 = 0;\n this.field278 = 0L;\n this.field266 = true;\n this.field281 = 0;\n this.field286 = new PcmStream[8];\n this.field282 = new PcmStream[8];\n }\n\n @ObfuscatedName(\"l\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1783507069\")\n @Export(\"init\")\n protected void init() throws Exception {\n }\n\n @ObfuscatedName(\"q\")\n @ObfuscatedSignature(descriptor = \"(IB)V\", garbageValue = \"15\")\n @Export(\"open\")\n protected void open(int var1) throws Exception {\n }\n\n @ObfuscatedName(\"f\")\n @ObfuscatedSignature(descriptor = \"(I)I\", garbageValue = \"-625452134\")\n @Export(\"position\")\n protected int position() throws Exception {\n return this.capacity;\n }\n\n @ObfuscatedName(\"j\")\n @Export(\"write\")\n protected void write() throws Exception {\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1407514911\")\n @Export(\"close\")\n protected void close() {\n }\n\n @ObfuscatedName(\"k\")\n @ObfuscatedSignature(descriptor = \"(B)V\", garbageValue = \"-115\")\n @Export(\"discard\")\n protected void discard() throws Exception {\n }\n\n @ObfuscatedName(\"o\")\n @ObfuscatedSignature(descriptor = \"(Lav;I)V\", garbageValue = \"1536652372\")\n @Export(\"setStream\")\n public final synchronized void setStream(PcmStream var1) {\n this.stream = var1;\n }\n\n @ObfuscatedName(\"r\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1578748771\")\n @Export(\"run\")\n public final synchronized void run() {\n if (this.samples != null) {\n long var1 = UserComparator4.method2406();\n try {\n if (0L != this.field274) {\n if (var1 < this.field274) {\n return;\n }\n this.open(this.capacity);\n this.field274 = 0L;\n this.field266 = true;\n }\n int var3 = this.position();\n if (this.field277 - var3 > this.field275) {\n this.field275 = this.field277 - var3;\n }\n int var4 = this.field272 + this.field265;\n if (var4 + 256 > 16384) {\n var4 = 16128;\n }\n if (var4 + 256 > this.capacity) {\n this.capacity += 1024;\n if (this.capacity > 16384) {\n this.capacity = 16384;\n }\n this.close();\n this.open(this.capacity);\n var3 = 0;\n this.field266 = true;\n if (var4 + 256 > this.capacity) {\n var4 = this.capacity - 256;\n this.field265 = var4 - this.field272;\n }\n }\n while (var3 < var4) {\n this.fill(this.samples, 256);\n this.write();\n var3 += 256;\n }\n if (var1 > this.field278) {\n if (!this.field266) {\n if (this.field275 == 0 && this.field262 == 0) {\n this.close();\n this.field274 = var1 + 2000L;\n return;\n }\n this.field265 = Math.min(this.field262, this.field275);\n this.field262 = this.field275;\n } else {\n this.field266 = false;\n }\n this.field275 = 0;\n this.field278 = var1 + 2000L;\n }\n this.field277 = var3;\n } catch (Exception var7) {\n this.close();\n this.field274 = var1 + 2000L;\n }\n try {\n if (var1 > this.timeMs + 500000L) {\n var1 = this.timeMs;\n }\n while (var1 > 5000L + this.timeMs) {\n this.skip(256);\n this.timeMs += (long) (256000 / field279);\n }\n } catch (Exception var6) {\n this.timeMs = var1;\n }\n }\n }\n\n @ObfuscatedName(\"n\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1285587409\")\n public final void method696() {\n this.field266 = true;\n }\n\n @ObfuscatedName(\"u\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1511155327\")\n @Export(\"tryDiscard\")\n public final synchronized void tryDiscard() {\n this.field266 = true;\n try {\n this.discard();\n } catch (Exception var2) {\n this.close();\n this.field274 = UserComparator4.method2406() + 2000L;\n }\n }\n\n @ObfuscatedName(\"d\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"25571035\")\n @Export(\"shutdown\")\n public final synchronized void shutdown() {\n if (Skeleton.soundSystem != null) {\n boolean var1 = true;\n for (int var2 = 0; var2 < 2; ++var2) {\n if (this == Skeleton.soundSystem.players[var2]) {\n Skeleton.soundSystem.players[var2] = null;\n }\n if (Skeleton.soundSystem.players[var2] != null) {\n var1 = false;\n }\n }\n if (var1) {\n soundSystemExecutor.shutdownNow();\n soundSystemExecutor = null;\n Skeleton.soundSystem = null;\n }\n }\n this.close();\n this.samples = null;\n }\n\n @ObfuscatedName(\"ab\")\n @ObfuscatedSignature(descriptor = \"(II)V\", garbageValue = \"4570450\")\n @Export(\"skip\")\n final void skip(int var1) {\n this.field281 -", "post_mask_code": "\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.skip(var1);\n }\n }\n\n @ObfuscatedName(\"ad\")\n @Export(\"fill\")\n final void fill(int[] var1, int var2) {\n int var3 = var2;\n if (PcmPlayer_stereo) {\n var3 = var2 << 1;\n }\n class321.clearIntArray(var1, 0, var3);\n this.field281 -= var2;\n if (this.stream != null && this.field281 <= 0) {\n this.field281 += field279 >> 4;\n class12.PcmStream_disable(this.stream);\n this.method711(this.stream, this.stream.vmethod944());\n int var4 = 0;\n int var5 = 255;\n int var6;\n PcmStream var10;\n label108: for (var6 = 7; var5 != 0; --var6) {\n int var7;\n int var8;\n if (var6 < 0) {\n var7 = var6 & 3;\n var8 = -(var6 >> 2);\n } else {\n var7 = var6;\n var8 = 0;\n }\n for (int var9 = var5 >>> var7 & 286331153; var9 != 0; var9 >>>= 4) {\n if ((var9 & 1) != 0) {\n var5 &= ~(1 << var7);\n var10 = null;\n PcmStream var11 = this.field286[var7];\n label102: while (true) {\n while (true) {\n if (var11 == null) {\n break label102;\n }\n AbstractSound var12 = var11.sound;\n if (var12 != null && var12.position > var8) {\n var5 |= 1 << var7;\n var10 = var11;\n var11 = var11.after;\n } else {\n var11.active = true;\n int var13 = var11.vmethod4889();\n var4 += var13;\n if (var12 != null) {\n var12.position += var13;\n }\n if (var4 >= this.field269) {\n break label108;\n }\n PcmStream var14 = var11.firstSubStream();\n if (var14 != null) {\n for (int var15 = var11.field335; var14 != null; var14 = var11.nextSubStream()) {\n this.method711(var14, var15 * var14.vmethod944() >> 8);\n }\n }\n PcmStream var18 = var11.after;\n var11.after = null;\n if (var10 == null) {\n this.field286[var7] = var18;\n } else {\n var10.after = var18;\n }\n if (var18 == null) {\n this.field282[var7] = var10;\n }\n var11 = var18;\n }\n }\n }\n }\n var7 += 4;\n ++var8;\n }\n }\n for (var6 = 0; var6 < 8; ++var6) {\n PcmStream var16 = this.field286[var6];\n PcmStream[] var17 = this.field286;\n this.field282[var6] = null;\n for (var17[var6] = null; var16 != null; var16 = var10) {\n var10 = var16.after;\n var16.after = null;\n }\n }\n }\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.fill(var1, 0, var2);\n }\n this.timeMs = UserComparator4.method2406();\n }\n\n @ObfuscatedName(\"ak\")\n @ObfuscatedSignature(descriptor = \"(Lav;II)V\", garbageValue = \"589893178\")\n final void method711(PcmStream var1, int var2) {\n int var3 = var2 >> 5;\n PcmStream var4 = this.field282[var3];\n if (var4 == null) {\n this.field286[var3] = var1;\n } else {\n var4.after = var1;\n }\n this.field282[var3] = var1;\n var1.field335 = var2;\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Lfp;\", garbageValue = \"1715478775\")\n static HorizontalAlignment[] method702() {\n return new HorizontalAlignment[] { HorizontalAlignment.field1708, HorizontalAlignment.field1707, HorizontalAlignment.HorizontalAlignment_centered };\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Ljm;\", garbageValue = \"1452483568\")\n public static class283[] method744() {\n return new class283[] { class283.field3648, class283.field3646, class283.field3649, class283.field3647 };\n }\n\n @ObfuscatedName(\"w\")\n @ObfuscatedSignature(descriptor = \"(ILbe;ZI)I\", garbageValue = \"1564904197\")\n static int method697(int var0, Script var1, boolean var2) {\n Widget var3;\n if (var0 >= 2000) {\n var0 -= 1000;\n var3 = HealthBarUpdate.getWidget(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n } else {\n var3 = var2 ? WorldMapDecoration.scriptDotWidget : class245.scriptActiveWidget;\n }\n String var4 = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n int[] var5 = null;\n if (var4.length() > 0 && var4.charAt(var4.length() - 1) == 'Y') {\n int var6 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var6 > 0) {\n for (var5 = new int[var6]; var6-- > 0; var5[var6] = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]) {\n }\n }\n var4 = var4.substring(0, var4.length() - 1);\n }\n Object[] var8 = new Object[var4.length() + 1];\n int var7;\n for (var7 = var8.length - 1; var7 >= 1; --var7) {\n if (var4.charAt(var7 - 1) == 's') {\n var8[var7] = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n } else {\n var8[var7] = new Integer(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n }\n }\n var7 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var7 != -1) {\n var8[0] = new Integer(var7);\n } else {\n var8 = null;\n }\n if (var0 == ScriptOpcodes.CC_SETONCLICK) {\n var3.onClick = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONHOLD) {\n var3.onHold = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRELEASE) {\n var3.onRelease = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEOVER) {\n var3.onMouseOver = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSELEAVE) {\n var3.onMouseLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAG) {\n var3.onDrag = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETLEAVE) {\n var3.onTargetLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONVARTRANSMIT) {\n var3.onVarTransmit = var8;\n var3.varTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTIMER) {\n var3.onTimer = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONOP) {\n var3.onOp = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAGCOMPLETE) {\n var3.onDragComplete = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLICKREPEAT) {\n var3.onClickRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEREPEAT) {\n var3.onMouseRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONINVTRANSMIT) {\n var3.onInvTransmit = var8;\n var3.invTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONSTATTRANSMIT) {\n var3.onStatTransmit = var8;\n var3.statTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETENTER) {\n var3.onTargetEnter = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSCROLLWHEEL) {\n var3.onScroll = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCHATTRANSMIT) {\n var3.onChatTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONKEY) {\n var3.onKey = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONFRIENDTRANSMIT) {\n var3.onFriendTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANTRANSMIT) {\n var3.onClanTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMISCTRANSMIT) {\n var3.onMiscTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDIALOGABORT) {\n var3.onDialogAbort = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSUBCHANGE) {\n var3.onSubChange = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSTOCKTRANSMIT) {\n var3.onStockTransmit = var8;\n } else if (var0 == 1426) {\n var3.field3168 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRESIZE) {\n var3.onResize = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANSETTINGSTRANSMIT) {\n var3.field3161 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANCHANNELTRANSMIT) {\n var3.field3163 = var8;\n } else if (var0 == 1430) {\n var3.field3157 = var8;\n } else {\n if (var0 != 1431) {\n return 2;\n }\n var3.field3158 = var8;\n }\n var3.hasListener = true;\n return 1;\n }\n\n @ObfuscatedName(\"ff\")\n @ObfuscatedSignature(descriptor = \"(III)V\", garbageValue = \"-856147347\")\n static void method741(int var0, int var1) {\n if (WorldMapDecorationType.clientPreferences.musicVolume != 0 && var0 != -1) {\n class67.method1886(class4.archive11, var0, 0, WorldMapDecorationType.clientPreferences.musicVolume, false);\n Client.field663 = true;\n }\n }\n}\n"} {"task_id": "Java_1074", "language": "Java", "task_type": "if_statement", "source_file": "java/github/open-osrs/runelite/runescape-client/src/main/java/PcmPlayer.java", "mask_start_position": 18935, "mask_end_position": 19179, "canonical_solution": "if (WorldMapDecorationType.clientPreferences.musicVolume != 0 && var0 != -1) {\n class67.method1886(class4.archive11, var0, 0, WorldMapDecorationType.clientPreferences.musicVolume, false);\n Client.field663 = true;\n }", "pre_mask_code": "import java.util.concurrent.ScheduledExecutorService;\nimport net.runelite.mapping.Export;\nimport net.runelite.mapping.Implements;\nimport net.runelite.mapping.ObfuscatedGetter;\nimport net.runelite.mapping.ObfuscatedName;\nimport net.runelite.mapping.ObfuscatedSignature;\nimport net.runelite.rs.ScriptOpcodes;\n\n@ObfuscatedName(\"aq\")\n@Implements(\"PcmPlayer\")\npublic class PcmPlayer {\n\n @ObfuscatedName(\"sm\")\n @ObfuscatedGetter(intValue = 2053999609)\n static int field284;\n\n @ObfuscatedName(\"m\")\n @ObfuscatedGetter(intValue = 1333600085)\n public static int field279;\n\n @ObfuscatedName(\"k\")\n @Export(\"PcmPlayer_stereo\")\n public static boolean PcmPlayer_stereo;\n\n @ObfuscatedName(\"a\")\n @Export(\"soundSystemExecutor\")\n static ScheduledExecutorService soundSystemExecutor;\n\n @ObfuscatedName(\"e\")\n @ObfuscatedGetter(intValue = 234394993)\n public static int field283;\n\n @ObfuscatedName(\"v\")\n @Export(\"samples\")\n protected int[] samples;\n\n @ObfuscatedName(\"s\")\n @ObfuscatedSignature(descriptor = \"Lav;\")\n @Export(\"stream\")\n PcmStream stream;\n\n @ObfuscatedName(\"c\")\n @ObfuscatedGetter(intValue = -1215690509)\n int field269;\n\n @ObfuscatedName(\"b\")\n @ObfuscatedGetter(longValue = 2700493498205354685L)\n @Export(\"timeMs\")\n long timeMs;\n\n @ObfuscatedName(\"x\")\n @ObfuscatedGetter(intValue = 1537731573)\n @Export(\"capacity\")\n int capacity;\n\n @ObfuscatedName(\"p\")\n @ObfuscatedGetter(intValue = -1674723661)\n int field272;\n\n @ObfuscatedName(\"z\")\n @ObfuscatedGetter(intValue = 1001923267)\n int field265;\n\n @ObfuscatedName(\"h\")\n @ObfuscatedGetter(longValue = -2229248515898476515L)\n long field274;\n\n @ObfuscatedName(\"o\")\n @ObfuscatedGetter(intValue = 352319831)\n int field275;\n\n @ObfuscatedName(\"r\")\n @ObfuscatedGetter(intValue = 998812825)\n int field262;\n\n @ObfuscatedName(\"n\")\n @ObfuscatedGetter(intValue = -388583705)\n int field277;\n\n @ObfuscatedName(\"u\")\n @ObfuscatedGetter(longValue = -1357881854631939735L)\n long field278;\n\n @ObfuscatedName(\"d\")\n boolean field266;\n\n @ObfuscatedName(\"ay\")\n @ObfuscatedGetter(intValue = 461057869)\n int field281;\n\n @ObfuscatedName(\"al\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field286;\n\n @ObfuscatedName(\"ao\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field282;\n\n protected PcmPlayer() {\n this.field269 = 32;\n this.timeMs = UserComparator4.method2406();\n this.field274 = 0L;\n this.field275 = 0;\n this.field262 = 0;\n this.field277 = 0;\n this.field278 = 0L;\n this.field266 = true;\n this.field281 = 0;\n this.field286 = new PcmStream[8];\n this.field282 = new PcmStream[8];\n }\n\n @ObfuscatedName(\"l\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1783507069\")\n @Export(\"init\")\n protected void init() throws Exception {\n }\n\n @ObfuscatedName(\"q\")\n @ObfuscatedSignature(descriptor = \"(IB)V\", garbageValue = \"15\")\n @Export(\"open\")\n protected void open(int var1) throws Exception {\n }\n\n @ObfuscatedName(\"f\")\n @ObfuscatedSignature(descriptor = \"(I)I\", garbageValue = \"-625452134\")\n @Export(\"position\")\n protected int position() throws Exception {\n return this.capacity;\n }\n\n @ObfuscatedName(\"j\")\n @Export(\"write\")\n protected void write() throws Exception {\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1407514911\")\n @Export(\"close\")\n protected void close() {\n }\n\n @ObfuscatedName(\"k\")\n @ObfuscatedSignature(descriptor = \"(B)V\", garbageValue = \"-115\")\n @Export(\"discard\")\n protected void discard() throws Exception {\n }\n\n @ObfuscatedName(\"o\")\n @ObfuscatedSignature(descriptor = \"(Lav;I)V\", garbageValue = \"1536652372\")\n @Export(\"setStream\")\n public final synchronized void setStream(PcmStream var1) {\n this.stream = var1;\n }\n\n @ObfuscatedName(\"r\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1578748771\")\n @Export(\"run\")\n public final synchronized void run() {\n if (this.samples != null) {\n long var1 = UserComparator4.method2406();\n try {\n if (0L != this.field274) {\n if (var1 < this.field274) {\n return;\n }\n this.open(this.capacity);\n this.field274 = 0L;\n this.field266 = true;\n }\n int var3 = this.position();\n if (this.field277 - var3 > this.field275) {\n this.field275 = this.field277 - var3;\n }\n int var4 = this.field272 + this.field265;\n if (var4 + 256 > 16384) {\n var4 = 16128;\n }\n if (var4 + 256 > this.capacity) {\n this.capacity += 1024;\n if (this.capacity > 16384) {\n this.capacity = 16384;\n }\n this.close();\n this.open(this.capacity);\n var3 = 0;\n this.field266 = true;\n if (var4 + 256 > this.capacity) {\n var4 = this.capacity - 256;\n this.field265 = var4 - this.field272;\n }\n }\n while (var3 < var4) {\n this.fill(this.samples, 256);\n this.write();\n var3 += 256;\n }\n if (var1 > this.field278) {\n if (!this.field266) {\n if (this.field275 == 0 && this.field262 == 0) {\n this.close();\n this.field274 = var1 + 2000L;\n return;\n }\n this.field265 = Math.min(this.field262, this.field275);\n this.field262 = this.field275;\n } else {\n this.field266 = false;\n }\n this.field275 = 0;\n this.field278 = var1 + 2000L;\n }\n this.field277 = var3;\n } catch (Exception var7) {\n this.close();\n this.field274 = var1 + 2000L;\n }\n try {\n if (var1 > this.timeMs + 500000L) {\n var1 = this.timeMs;\n }\n while (var1 > 5000L + this.timeMs) {\n this.skip(256);\n this.timeMs += (long) (256000 / field279);\n }\n } catch (Exception var6) {\n this.timeMs = var1;\n }\n }\n }\n\n @ObfuscatedName(\"n\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1285587409\")\n public final void method696() {\n this.field266 = true;\n }\n\n @ObfuscatedName(\"u\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1511155327\")\n @Export(\"tryDiscard\")\n public final synchronized void tryDiscard() {\n this.field266 = true;\n try {\n this.discard();\n } catch (Exception var2) {\n this.close();\n this.field274 = UserComparator4.method2406() + 2000L;\n }\n }\n\n @ObfuscatedName(\"d\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"25571035\")\n @Export(\"shutdown\")\n public final synchronized void shutdown() {\n if (Skeleton.soundSystem != null) {\n boolean var1 = true;\n for (int var2 = 0; var2 < 2; ++var2) {\n if (this == Skeleton.soundSystem.players[var2]) {\n Skeleton.soundSystem.players[var2] = null;\n }\n if (Skeleton.soundSystem.players[var2] != null) {\n var1 = false;\n }\n }\n if (var1) {\n soundSystemExecutor.shutdownNow();\n soundSystemExecutor = null;\n Skeleton.soundSystem = null;\n }\n }\n this.close();\n this.samples = null;\n }\n\n @ObfuscatedName(\"ab\")\n @ObfuscatedSignature(descriptor = \"(II)V\", garbageValue = \"4570450\")\n @Export(\"skip\")\n final void skip(int var1) {\n this.field281 -= var1;\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.skip(var1);\n }\n }\n\n @ObfuscatedName(\"ad\")\n @Export(\"fill\")\n final void fill(int[] var1, int var2) {\n int var3 = var2;\n if (PcmPlayer_stereo) {\n var3 = var2 << 1;\n }\n class321.clearIntArray(var1, 0, var3);\n this.field281 -= var2;\n if (this.stream != null && this.field281 <= 0) {\n this.field281 += field279 >> 4;\n class12.PcmStream_disable(this.stream);\n this.method711(this.stream, this.stream.vmethod944());\n int var4 = 0;\n int var5 = 255;\n int var6;\n PcmStream var10;\n label108: for (var6 = 7; var5 != 0; --var6) {\n int var7;\n int var8;\n if (var6 < 0) {\n var7 = var6 & 3;\n var8 = -(var6 >> 2);\n } else {\n var7 = var6;\n var8 = 0;\n }\n for (int var9 = var5 >>> var7 & 286331153; var9 != 0; var9 >>>= 4) {\n if ((var9 & 1) != 0) {\n var5 &= ~(1 << var7);\n var10 = null;\n PcmStream var11 = this.field286[var7];\n label102: while (true) {\n while (true) {\n if (var11 == null) {\n break label102;\n }\n AbstractSound var12 = var11.sound;\n if (var12 != null && var12.position > var8) {\n var5 |= 1 << var7;\n var10 = var11;\n var11 = var11.after;\n } else {\n var11.active = true;\n int var13 = var11.vmethod4889();\n var4 += var13;\n if (var12 != null) {\n var12.position += var13;\n }\n if (var4 >= this.field269) {\n break label108;\n }\n PcmStream var14 = var11.firstSubStream();\n if (var14 != null) {\n for (int var15 = var11.field335; var14 != null; var14 = var11.nextSubStream()) {\n this.method711(var14, var15 * var14.vmethod944() >> 8);\n }\n }\n PcmStream var18 = var11.after;\n var11.after = null;\n if (var10 == null) {\n this.field286[var7] = var18;\n } else {\n var10.after = var18;\n }\n if (var18 == null) {\n this.field282[var7] = var10;\n }\n var11 = var18;\n }\n }\n }\n }\n var7 += 4;\n ++var8;\n }\n }\n for (var6 = 0; var6 < 8; ++var6) {\n PcmStream var16 = this.field286[var6];\n PcmStream[] var17 = this.field286;\n this.field282[var6] = null;\n for (var17[var6] = null; var16 != null; var16 = var10) {\n var10 = var16.after;\n var16.after = null;\n }\n }\n }\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.fill(var1, 0, var2);\n }\n this.timeMs = UserComparator4.method2406();\n }\n\n @ObfuscatedName(\"ak\")\n @ObfuscatedSignature(descriptor = \"(Lav;II)V\", garbageValue = \"589893178\")\n final void method711(PcmStream var1, int var2) {\n int var3 = var2 >> 5;\n PcmStream var4 = this.field282[var3];\n if (var4 == null) {\n this.field286[var3] = var1;\n } else {\n var4.after = var1;\n }\n this.field282[var3] = var1;\n var1.field335 = var2;\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Lfp;\", garbageValue = \"1715478775\")\n static HorizontalAlignment[] method702() {\n return new HorizontalAlignment[] { HorizontalAlignment.field1708, HorizontalAlignment.field1707, HorizontalAlignment.HorizontalAlignment_centered };\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Ljm;\", garbageValue = \"1452483568\")\n public static class283[] method744() {\n return new class283[] { class283.field3648, class283.field3646, class283.field3649, class283.field3647 };\n }\n\n @ObfuscatedName(\"w\")\n @ObfuscatedSignature(descriptor = \"(ILbe;ZI)I\", garbageValue = \"1564904197\")\n static int method697(int var0, Script var1, boolean var2) {\n Widget var3;\n if (var0 >= 2000) {\n var0 -= 1000;\n var3 = HealthBarUpdate.getWidget(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n } else {\n var3 = var2 ? WorldMapDecoration.scriptDotWidget : class245.scriptActiveWidget;\n }\n String var4 = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n int[] var5 = null;\n if (var4.length() > 0 && var4.charAt(var4.length() - 1) == 'Y') {\n int var6 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var6 > 0) {\n for (var5 = new int[var6]; var6-- > 0; var5[var6] = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]) {\n }\n }\n var4 = var4.substring(0, var4.length() - 1);\n }\n Object[] var8 = new Object[var4.length() + 1];\n int var7;\n for (var7 = var8.length - 1; var7 >= 1; --var7) {\n if (var4.charAt(var7 - 1) == 's') {\n var8[var7] = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n } else {\n var8[var7] = new Integer(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n }\n }\n var7 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var7 != -1) {\n var8[0] = new Integer(var7);\n } else {\n var8 = null;\n }\n if (var0 == ScriptOpcodes.CC_SETONCLICK) {\n var3.onClick = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONHOLD) {\n var3.onHold = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRELEASE) {\n var3.onRelease = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEOVER) {\n var3.onMouseOver = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSELEAVE) {\n var3.onMouseLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAG) {\n var3.onDrag = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETLEAVE) {\n var3.onTargetLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONVARTRANSMIT) {\n var3.onVarTransmit = var8;\n var3.varTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTIMER) {\n var3.onTimer = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONOP) {\n var3.onOp = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAGCOMPLETE) {\n var3.onDragComplete = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLICKREPEAT) {\n var3.onClickRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEREPEAT) {\n var3.onMouseRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONINVTRANSMIT) {\n var3.onInvTransmit = var8;\n var3.invTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONSTATTRANSMIT) {\n var3.onStatTransmit = var8;\n var3.statTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETENTER) {\n var3.onTargetEnter = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSCROLLWHEEL) {\n var3.onScroll = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCHATTRANSMIT) {\n var3.onChatTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONKEY) {\n var3.onKey = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONFRIENDTRANSMIT) {\n var3.onFriendTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANTRANSMIT) {\n var3.onClanTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMISCTRANSMIT) {\n var3.onMiscTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDIALOGABORT) {\n var3.onDialogAbort = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSUBCHANGE) {\n var3.onSubChange = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSTOCKTRANSMIT) {\n var3.onStockTransmit = var8;\n } else if (var0 == 1426) {\n var3.field3168 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRESIZE) {\n var3.onResize = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANSETTINGSTRANSMIT) {\n var3.field3161 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANCHANNELTRANSMIT) {\n var3.field3163 = var8;\n } else if (var0 == 1430) {\n var3.field3157 = var8;\n } else {\n if (var0 != 1431) {\n return 2;\n }\n var3.field3158 = var8;\n }\n var3.hasListener = true;\n return 1;\n }\n\n @ObfuscatedName(\"ff\")\n @ObfuscatedSignature(descriptor = \"(III)V\", garbageValue = \"-856147347\")\n static void method741(int var0, int var1) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1075", "language": "Java", "task_type": "for_statement", "source_file": "java/github/open-osrs/runelite/runescape-client/src/main/java/PcmPlayer.java", "mask_start_position": 12338, "mask_end_position": 12493, "canonical_solution": "for (var17[var6] = null; var16 != null; var16 = var10) {\n var10 = var16.after;\n var16.after = null;\n }", "pre_mask_code": "import java.util.concurrent.ScheduledExecutorService;\nimport net.runelite.mapping.Export;\nimport net.runelite.mapping.Implements;\nimport net.runelite.mapping.ObfuscatedGetter;\nimport net.runelite.mapping.ObfuscatedName;\nimport net.runelite.mapping.ObfuscatedSignature;\nimport net.runelite.rs.ScriptOpcodes;\n\n@ObfuscatedName(\"aq\")\n@Implements(\"PcmPlayer\")\npublic class PcmPlayer {\n\n @ObfuscatedName(\"sm\")\n @ObfuscatedGetter(intValue = 2053999609)\n static int field284;\n\n @ObfuscatedName(\"m\")\n @ObfuscatedGetter(intValue = 1333600085)\n public static int field279;\n\n @ObfuscatedName(\"k\")\n @Export(\"PcmPlayer_stereo\")\n public static boolean PcmPlayer_stereo;\n\n @ObfuscatedName(\"a\")\n @Export(\"soundSystemExecutor\")\n static ScheduledExecutorService soundSystemExecutor;\n\n @ObfuscatedName(\"e\")\n @ObfuscatedGetter(intValue = 234394993)\n public static int field283;\n\n @ObfuscatedName(\"v\")\n @Export(\"samples\")\n protected int[] samples;\n\n @ObfuscatedName(\"s\")\n @ObfuscatedSignature(descriptor = \"Lav;\")\n @Export(\"stream\")\n PcmStream stream;\n\n @ObfuscatedName(\"c\")\n @ObfuscatedGetter(intValue = -1215690509)\n int field269;\n\n @ObfuscatedName(\"b\")\n @ObfuscatedGetter(longValue = 2700493498205354685L)\n @Export(\"timeMs\")\n long timeMs;\n\n @ObfuscatedName(\"x\")\n @ObfuscatedGetter(intValue = 1537731573)\n @Export(\"capacity\")\n int capacity;\n\n @ObfuscatedName(\"p\")\n @ObfuscatedGetter(intValue = -1674723661)\n int field272;\n\n @ObfuscatedName(\"z\")\n @ObfuscatedGetter(intValue = 1001923267)\n int field265;\n\n @ObfuscatedName(\"h\")\n @ObfuscatedGetter(longValue = -2229248515898476515L)\n long field274;\n\n @ObfuscatedName(\"o\")\n @ObfuscatedGetter(intValue = 352319831)\n int field275;\n\n @ObfuscatedName(\"r\")\n @ObfuscatedGetter(intValue = 998812825)\n int field262;\n\n @ObfuscatedName(\"n\")\n @ObfuscatedGetter(intValue = -388583705)\n int field277;\n\n @ObfuscatedName(\"u\")\n @ObfuscatedGetter(longValue = -1357881854631939735L)\n long field278;\n\n @ObfuscatedName(\"d\")\n boolean field266;\n\n @ObfuscatedName(\"ay\")\n @ObfuscatedGetter(intValue = 461057869)\n int field281;\n\n @ObfuscatedName(\"al\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field286;\n\n @ObfuscatedName(\"ao\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field282;\n\n protected PcmPlayer() {\n this.field269 = 32;\n this.timeMs = UserComparator4.method2406();\n this.field274 = 0L;\n this.field275 = 0;\n this.field262 = 0;\n this.field277 = 0;\n this.field278 = 0L;\n this.field266 = true;\n this.field281 = 0;\n this.field286 = new PcmStream[8];\n this.field282 = new PcmStream[8];\n }\n\n @ObfuscatedName(\"l\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1783507069\")\n @Export(\"init\")\n protected void init() throws Exception {\n }\n\n @ObfuscatedName(\"q\")\n @ObfuscatedSignature(descriptor = \"(IB)V\", garbageValue = \"15\")\n @Export(\"open\")\n protected void open(int var1) throws Exception {\n }\n\n @ObfuscatedName(\"f\")\n @ObfuscatedSignature(descriptor = \"(I)I\", garbageValue = \"-625452134\")\n @Export(\"position\")\n protected int position() throws Exception {\n return this.capacity;\n }\n\n @ObfuscatedName(\"j\")\n @Export(\"write\")\n protected void write() throws Exception {\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1407514911\")\n @Export(\"close\")\n protected void close() {\n }\n\n @ObfuscatedName(\"k\")\n @ObfuscatedSignature(descriptor = \"(B)V\", garbageValue = \"-115\")\n @Export(\"discard\")\n protected void discard() throws Exception {\n }\n\n @ObfuscatedName(\"o\")\n @ObfuscatedSignature(descriptor = \"(Lav;I)V\", garbageValue = \"1536652372\")\n @Export(\"setStream\")\n public final synchronized void setStream(PcmStream var1) {\n this.stream = var1;\n }\n\n @ObfuscatedName(\"r\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1578748771\")\n @Export(\"run\")\n public final synchronized void run() {\n if (this.samples != null) {\n long var1 = UserComparator4.method2406();\n try {\n if (0L != this.field274) {\n if (var1 < this.field274) {\n return;\n }\n this.open(this.capacity);\n this.field274 = 0L;\n this.field266 = true;\n }\n int var3 = this.position();\n if (this.field277 - var3 > this.field275) {\n this.field275 = this.field277 - var3;\n }\n int var4 = this.field272 + this.field265;\n if (var4 + 256 > 16384) {\n var4 = 16128;\n }\n if (var4 + 256 > this.capacity) {\n this.capacity += 1024;\n if (this.capacity > 16384) {\n this.capacity = 16384;\n }\n this.close();\n this.open(this.capacity);\n var3 = 0;\n this.field266 = true;\n if (var4 + 256 > this.capacity) {\n var4 = this.capacity - 256;\n this.field265 = var4 - this.field272;\n }\n }\n while (var3 < var4) {\n this.fill(this.samples, 256);\n this.write();\n var3 += 256;\n }\n if (var1 > this.field278) {\n if (!this.field266) {\n if (this.field275 == 0 && this.field262 == 0) {\n this.close();\n this.field274 = var1 + 2000L;\n return;\n }\n this.field265 = Math.min(this.field262, this.field275);\n this.field262 = this.field275;\n } else {\n this.field266 = false;\n }\n this.field275 = 0;\n this.field278 = var1 + 2000L;\n }\n this.field277 = var3;\n } catch (Exception var7) {\n this.close();\n this.field274 = var1 + 2000L;\n }\n try {\n if (var1 > this.timeMs + 500000L) {\n var1 = this.timeMs;\n }\n while (var1 > 5000L + this.timeMs) {\n this.skip(256);\n this.timeMs += (long) (256000 / field279);\n }\n } catch (Exception var6) {\n this.timeMs = var1;\n }\n }\n }\n\n @ObfuscatedName(\"n\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1285587409\")\n public final void method696() {\n this.field266 = true;\n }\n\n @ObfuscatedName(\"u\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1511155327\")\n @Export(\"tryDiscard\")\n public final synchronized void tryDiscard() {\n this.field266 = true;\n try {\n this.discard();\n } catch (Exception var2) {\n this.close();\n this.field274 = UserComparator4.method2406() + 2000L;\n }\n }\n\n @ObfuscatedName(\"d\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"25571035\")\n @Export(\"shutdown\")\n public final synchronized void shutdown() {\n if (Skeleton.soundSystem != null) {\n boolean var1 = true;\n for (int var2 = 0; var2 < 2; ++var2) {\n if (this == Skeleton.soundSystem.players[var2]) {\n Skeleton.soundSystem.players[var2] = null;\n }\n if (Skeleton.soundSystem.players[var2] != null) {\n var1 = false;\n }\n }\n if (var1) {\n soundSystemExecutor.shutdownNow();\n soundSystemExecutor = null;\n Skeleton.soundSystem = null;\n }\n }\n this.close();\n this.samples = null;\n }\n\n @ObfuscatedName(\"ab\")\n @ObfuscatedSignature(descriptor = \"(II)V\", garbageValue = \"4570450\")\n @Export(\"skip\")\n final void skip(int var1) {\n this.field281 -= var1;\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.skip(var1);\n }\n }\n\n @ObfuscatedName(\"ad\")\n @Export(\"fill\")\n final void fill(int[] var1, int var2) {\n int var3 = var2;\n if (PcmPlayer_stereo) {\n var3 = var2 << 1;\n }\n class321.clearIntArray(var1, 0, var3);\n this.field281 -= var2;\n if (this.stream != null && this.field281 <= 0) {\n this.field281 += field279 >> 4;\n class12.PcmStream_disable(this.stream);\n this.method711(this.stream, this.stream.vmethod944());\n int var4 = 0;\n int var5 = 255;\n int var6;\n PcmStream var10;\n label108: for (var6 = 7; var5 != 0; --var6) {\n int var7;\n int var8;\n if (var6 < 0) {\n var7 = var6 & 3;\n var8 = -(var6 >> 2);\n } else {\n var7 = var6;\n var8 = 0;\n }\n for (int var9 = var5 >>> var7 & 286331153; var9 != 0; var9 >>>= 4) {\n if ((var9 & 1) != 0) {\n var5 &= ~(1 << var7);\n var10 = null;\n PcmStream var11 = this.field286[var7];\n label102: while (true) {\n while (true) {\n if (var11 == null) {\n break label102;\n }\n AbstractSound var12 = var11.sound;\n if (var12 != null && var12.position > var8) {\n var5 |= 1 << var7;\n var10 = var11;\n var11 = var11.after;\n } else {\n var11.active = true;\n int var13 = var11.vmethod4889();\n var4 += var13;\n if (var12 != null) {\n var12.position += var13;\n }\n if (var4 >= this.field269) {\n break label108;\n }\n PcmStream var14 = var11.firstSubStream();\n if (var14 != null) {\n for (int var15 = var11.field335; var14 != null; var14 = var11.nextSubStream()) {\n this.method711(var14, var15 * var14.vmethod944() >> 8);\n }\n }\n PcmStream var18 = var11.after;\n var11.after = null;\n if (var10 == null) {\n this.field286[var7] = var18;\n } else {\n var10.after = var18;\n }\n if (var18 == null) {\n this.field282[var7] = var10;\n }\n var11 = var18;\n }\n }\n }\n }\n var7 += 4;\n ++var8;\n }\n }\n for (var6 = 0; var6 < 8; ++var6) {\n PcmStream var16 = this.field286[var6];\n PcmStream[] var17 = this.field286;\n this.field282[var6] = null;\n ", "post_mask_code": "\n }\n }\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.fill(var1, 0, var2);\n }\n this.timeMs = UserComparator4.method2406();\n }\n\n @ObfuscatedName(\"ak\")\n @ObfuscatedSignature(descriptor = \"(Lav;II)V\", garbageValue = \"589893178\")\n final void method711(PcmStream var1, int var2) {\n int var3 = var2 >> 5;\n PcmStream var4 = this.field282[var3];\n if (var4 == null) {\n this.field286[var3] = var1;\n } else {\n var4.after = var1;\n }\n this.field282[var3] = var1;\n var1.field335 = var2;\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Lfp;\", garbageValue = \"1715478775\")\n static HorizontalAlignment[] method702() {\n return new HorizontalAlignment[] { HorizontalAlignment.field1708, HorizontalAlignment.field1707, HorizontalAlignment.HorizontalAlignment_centered };\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Ljm;\", garbageValue = \"1452483568\")\n public static class283[] method744() {\n return new class283[] { class283.field3648, class283.field3646, class283.field3649, class283.field3647 };\n }\n\n @ObfuscatedName(\"w\")\n @ObfuscatedSignature(descriptor = \"(ILbe;ZI)I\", garbageValue = \"1564904197\")\n static int method697(int var0, Script var1, boolean var2) {\n Widget var3;\n if (var0 >= 2000) {\n var0 -= 1000;\n var3 = HealthBarUpdate.getWidget(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n } else {\n var3 = var2 ? WorldMapDecoration.scriptDotWidget : class245.scriptActiveWidget;\n }\n String var4 = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n int[] var5 = null;\n if (var4.length() > 0 && var4.charAt(var4.length() - 1) == 'Y') {\n int var6 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var6 > 0) {\n for (var5 = new int[var6]; var6-- > 0; var5[var6] = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]) {\n }\n }\n var4 = var4.substring(0, var4.length() - 1);\n }\n Object[] var8 = new Object[var4.length() + 1];\n int var7;\n for (var7 = var8.length - 1; var7 >= 1; --var7) {\n if (var4.charAt(var7 - 1) == 's') {\n var8[var7] = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n } else {\n var8[var7] = new Integer(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n }\n }\n var7 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var7 != -1) {\n var8[0] = new Integer(var7);\n } else {\n var8 = null;\n }\n if (var0 == ScriptOpcodes.CC_SETONCLICK) {\n var3.onClick = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONHOLD) {\n var3.onHold = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRELEASE) {\n var3.onRelease = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEOVER) {\n var3.onMouseOver = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSELEAVE) {\n var3.onMouseLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAG) {\n var3.onDrag = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETLEAVE) {\n var3.onTargetLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONVARTRANSMIT) {\n var3.onVarTransmit = var8;\n var3.varTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTIMER) {\n var3.onTimer = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONOP) {\n var3.onOp = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAGCOMPLETE) {\n var3.onDragComplete = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLICKREPEAT) {\n var3.onClickRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEREPEAT) {\n var3.onMouseRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONINVTRANSMIT) {\n var3.onInvTransmit = var8;\n var3.invTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONSTATTRANSMIT) {\n var3.onStatTransmit = var8;\n var3.statTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETENTER) {\n var3.onTargetEnter = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSCROLLWHEEL) {\n var3.onScroll = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCHATTRANSMIT) {\n var3.onChatTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONKEY) {\n var3.onKey = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONFRIENDTRANSMIT) {\n var3.onFriendTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANTRANSMIT) {\n var3.onClanTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMISCTRANSMIT) {\n var3.onMiscTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDIALOGABORT) {\n var3.onDialogAbort = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSUBCHANGE) {\n var3.onSubChange = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSTOCKTRANSMIT) {\n var3.onStockTransmit = var8;\n } else if (var0 == 1426) {\n var3.field3168 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRESIZE) {\n var3.onResize = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANSETTINGSTRANSMIT) {\n var3.field3161 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANCHANNELTRANSMIT) {\n var3.field3163 = var8;\n } else if (var0 == 1430) {\n var3.field3157 = var8;\n } else {\n if (var0 != 1431) {\n return 2;\n }\n var3.field3158 = var8;\n }\n var3.hasListener = true;\n return 1;\n }\n\n @ObfuscatedName(\"ff\")\n @ObfuscatedSignature(descriptor = \"(III)V\", garbageValue = \"-856147347\")\n static void method741(int var0, int var1) {\n if (WorldMapDecorationType.clientPreferences.musicVolume != 0 && var0 != -1) {\n class67.method1886(class4.archive11, var0, 0, WorldMapDecorationType.clientPreferences.musicVolume, false);\n Client.field663 = true;\n }\n }\n}\n"} {"task_id": "Java_1076", "language": "Java", "task_type": "while_statement", "source_file": "java/github/open-osrs/runelite/runescape-client/src/main/java/PcmPlayer.java", "mask_start_position": 6617, "mask_end_position": 6770, "canonical_solution": "while (var1 > 5000L + this.timeMs) {\n this.skip(256);\n this.timeMs += (long) (256000 / field279);\n }", "pre_mask_code": "import java.util.concurrent.ScheduledExecutorService;\nimport net.runelite.mapping.Export;\nimport net.runelite.mapping.Implements;\nimport net.runelite.mapping.ObfuscatedGetter;\nimport net.runelite.mapping.ObfuscatedName;\nimport net.runelite.mapping.ObfuscatedSignature;\nimport net.runelite.rs.ScriptOpcodes;\n\n@ObfuscatedName(\"aq\")\n@Implements(\"PcmPlayer\")\npublic class PcmPlayer {\n\n @ObfuscatedName(\"sm\")\n @ObfuscatedGetter(intValue = 2053999609)\n static int field284;\n\n @ObfuscatedName(\"m\")\n @ObfuscatedGetter(intValue = 1333600085)\n public static int field279;\n\n @ObfuscatedName(\"k\")\n @Export(\"PcmPlayer_stereo\")\n public static boolean PcmPlayer_stereo;\n\n @ObfuscatedName(\"a\")\n @Export(\"soundSystemExecutor\")\n static ScheduledExecutorService soundSystemExecutor;\n\n @ObfuscatedName(\"e\")\n @ObfuscatedGetter(intValue = 234394993)\n public static int field283;\n\n @ObfuscatedName(\"v\")\n @Export(\"samples\")\n protected int[] samples;\n\n @ObfuscatedName(\"s\")\n @ObfuscatedSignature(descriptor = \"Lav;\")\n @Export(\"stream\")\n PcmStream stream;\n\n @ObfuscatedName(\"c\")\n @ObfuscatedGetter(intValue = -1215690509)\n int field269;\n\n @ObfuscatedName(\"b\")\n @ObfuscatedGetter(longValue = 2700493498205354685L)\n @Export(\"timeMs\")\n long timeMs;\n\n @ObfuscatedName(\"x\")\n @ObfuscatedGetter(intValue = 1537731573)\n @Export(\"capacity\")\n int capacity;\n\n @ObfuscatedName(\"p\")\n @ObfuscatedGetter(intValue = -1674723661)\n int field272;\n\n @ObfuscatedName(\"z\")\n @ObfuscatedGetter(intValue = 1001923267)\n int field265;\n\n @ObfuscatedName(\"h\")\n @ObfuscatedGetter(longValue = -2229248515898476515L)\n long field274;\n\n @ObfuscatedName(\"o\")\n @ObfuscatedGetter(intValue = 352319831)\n int field275;\n\n @ObfuscatedName(\"r\")\n @ObfuscatedGetter(intValue = 998812825)\n int field262;\n\n @ObfuscatedName(\"n\")\n @ObfuscatedGetter(intValue = -388583705)\n int field277;\n\n @ObfuscatedName(\"u\")\n @ObfuscatedGetter(longValue = -1357881854631939735L)\n long field278;\n\n @ObfuscatedName(\"d\")\n boolean field266;\n\n @ObfuscatedName(\"ay\")\n @ObfuscatedGetter(intValue = 461057869)\n int field281;\n\n @ObfuscatedName(\"al\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field286;\n\n @ObfuscatedName(\"ao\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field282;\n\n protected PcmPlayer() {\n this.field269 = 32;\n this.timeMs = UserComparator4.method2406();\n this.field274 = 0L;\n this.field275 = 0;\n this.field262 = 0;\n this.field277 = 0;\n this.field278 = 0L;\n this.field266 = true;\n this.field281 = 0;\n this.field286 = new PcmStream[8];\n this.field282 = new PcmStream[8];\n }\n\n @ObfuscatedName(\"l\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1783507069\")\n @Export(\"init\")\n protected void init() throws Exception {\n }\n\n @ObfuscatedName(\"q\")\n @ObfuscatedSignature(descriptor = \"(IB)V\", garbageValue = \"15\")\n @Export(\"open\")\n protected void open(int var1) throws Exception {\n }\n\n @ObfuscatedName(\"f\")\n @ObfuscatedSignature(descriptor = \"(I)I\", garbageValue = \"-625452134\")\n @Export(\"position\")\n protected int position() throws Exception {\n return this.capacity;\n }\n\n @ObfuscatedName(\"j\")\n @Export(\"write\")\n protected void write() throws Exception {\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1407514911\")\n @Export(\"close\")\n protected void close() {\n }\n\n @ObfuscatedName(\"k\")\n @ObfuscatedSignature(descriptor = \"(B)V\", garbageValue = \"-115\")\n @Export(\"discard\")\n protected void discard() throws Exception {\n }\n\n @ObfuscatedName(\"o\")\n @ObfuscatedSignature(descriptor = \"(Lav;I)V\", garbageValue = \"1536652372\")\n @Export(\"setStream\")\n public final synchronized void setStream(PcmStream var1) {\n this.stream = var1;\n }\n\n @ObfuscatedName(\"r\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1578748771\")\n @Export(\"run\")\n public final synchronized void run() {\n if (this.samples != null) {\n long var1 = UserComparator4.method2406();\n try {\n if (0L != this.field274) {\n if (var1 < this.field274) {\n return;\n }\n this.open(this.capacity);\n this.field274 = 0L;\n this.field266 = true;\n }\n int var3 = this.position();\n if (this.field277 - var3 > this.field275) {\n this.field275 = this.field277 - var3;\n }\n int var4 = this.field272 + this.field265;\n if (var4 + 256 > 16384) {\n var4 = 16128;\n }\n if (var4 + 256 > this.capacity) {\n this.capacity += 1024;\n if (this.capacity > 16384) {\n this.capacity = 16384;\n }\n this.close();\n this.open(this.capacity);\n var3 = 0;\n this.field266 = true;\n if (var4 + 256 > this.capacity) {\n var4 = this.capacity - 256;\n this.field265 = var4 - this.field272;\n }\n }\n while (var3 < var4) {\n this.fill(this.samples, 256);\n this.write();\n var3 += 256;\n }\n if (var1 > this.field278) {\n if (!this.field266) {\n if (this.field275 == 0 && this.field262 == 0) {\n this.close();\n this.field274 = var1 + 2000L;\n return;\n }\n this.field265 = Math.min(this.field262, this.field275);\n this.field262 = this.field275;\n } else {\n this.field266 = false;\n }\n this.field275 = 0;\n this.field278 = var1 + 2000L;\n }\n this.field277 = var3;\n } catch (Exception var7) {\n this.close();\n this.field274 = var1 + 2000L;\n }\n try {\n if (var1 > this.timeMs + 500000L) {\n var1 = this.timeMs;\n }\n ", "post_mask_code": "\n } catch (Exception var6) {\n this.timeMs = var1;\n }\n }\n }\n\n @ObfuscatedName(\"n\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1285587409\")\n public final void method696() {\n this.field266 = true;\n }\n\n @ObfuscatedName(\"u\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1511155327\")\n @Export(\"tryDiscard\")\n public final synchronized void tryDiscard() {\n this.field266 = true;\n try {\n this.discard();\n } catch (Exception var2) {\n this.close();\n this.field274 = UserComparator4.method2406() + 2000L;\n }\n }\n\n @ObfuscatedName(\"d\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"25571035\")\n @Export(\"shutdown\")\n public final synchronized void shutdown() {\n if (Skeleton.soundSystem != null) {\n boolean var1 = true;\n for (int var2 = 0; var2 < 2; ++var2) {\n if (this == Skeleton.soundSystem.players[var2]) {\n Skeleton.soundSystem.players[var2] = null;\n }\n if (Skeleton.soundSystem.players[var2] != null) {\n var1 = false;\n }\n }\n if (var1) {\n soundSystemExecutor.shutdownNow();\n soundSystemExecutor = null;\n Skeleton.soundSystem = null;\n }\n }\n this.close();\n this.samples = null;\n }\n\n @ObfuscatedName(\"ab\")\n @ObfuscatedSignature(descriptor = \"(II)V\", garbageValue = \"4570450\")\n @Export(\"skip\")\n final void skip(int var1) {\n this.field281 -= var1;\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.skip(var1);\n }\n }\n\n @ObfuscatedName(\"ad\")\n @Export(\"fill\")\n final void fill(int[] var1, int var2) {\n int var3 = var2;\n if (PcmPlayer_stereo) {\n var3 = var2 << 1;\n }\n class321.clearIntArray(var1, 0, var3);\n this.field281 -= var2;\n if (this.stream != null && this.field281 <= 0) {\n this.field281 += field279 >> 4;\n class12.PcmStream_disable(this.stream);\n this.method711(this.stream, this.stream.vmethod944());\n int var4 = 0;\n int var5 = 255;\n int var6;\n PcmStream var10;\n label108: for (var6 = 7; var5 != 0; --var6) {\n int var7;\n int var8;\n if (var6 < 0) {\n var7 = var6 & 3;\n var8 = -(var6 >> 2);\n } else {\n var7 = var6;\n var8 = 0;\n }\n for (int var9 = var5 >>> var7 & 286331153; var9 != 0; var9 >>>= 4) {\n if ((var9 & 1) != 0) {\n var5 &= ~(1 << var7);\n var10 = null;\n PcmStream var11 = this.field286[var7];\n label102: while (true) {\n while (true) {\n if (var11 == null) {\n break label102;\n }\n AbstractSound var12 = var11.sound;\n if (var12 != null && var12.position > var8) {\n var5 |= 1 << var7;\n var10 = var11;\n var11 = var11.after;\n } else {\n var11.active = true;\n int var13 = var11.vmethod4889();\n var4 += var13;\n if (var12 != null) {\n var12.position += var13;\n }\n if (var4 >= this.field269) {\n break label108;\n }\n PcmStream var14 = var11.firstSubStream();\n if (var14 != null) {\n for (int var15 = var11.field335; var14 != null; var14 = var11.nextSubStream()) {\n this.method711(var14, var15 * var14.vmethod944() >> 8);\n }\n }\n PcmStream var18 = var11.after;\n var11.after = null;\n if (var10 == null) {\n this.field286[var7] = var18;\n } else {\n var10.after = var18;\n }\n if (var18 == null) {\n this.field282[var7] = var10;\n }\n var11 = var18;\n }\n }\n }\n }\n var7 += 4;\n ++var8;\n }\n }\n for (var6 = 0; var6 < 8; ++var6) {\n PcmStream var16 = this.field286[var6];\n PcmStream[] var17 = this.field286;\n this.field282[var6] = null;\n for (var17[var6] = null; var16 != null; var16 = var10) {\n var10 = var16.after;\n var16.after = null;\n }\n }\n }\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.fill(var1, 0, var2);\n }\n this.timeMs = UserComparator4.method2406();\n }\n\n @ObfuscatedName(\"ak\")\n @ObfuscatedSignature(descriptor = \"(Lav;II)V\", garbageValue = \"589893178\")\n final void method711(PcmStream var1, int var2) {\n int var3 = var2 >> 5;\n PcmStream var4 = this.field282[var3];\n if (var4 == null) {\n this.field286[var3] = var1;\n } else {\n var4.after = var1;\n }\n this.field282[var3] = var1;\n var1.field335 = var2;\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Lfp;\", garbageValue = \"1715478775\")\n static HorizontalAlignment[] method702() {\n return new HorizontalAlignment[] { HorizontalAlignment.field1708, HorizontalAlignment.field1707, HorizontalAlignment.HorizontalAlignment_centered };\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Ljm;\", garbageValue = \"1452483568\")\n public static class283[] method744() {\n return new class283[] { class283.field3648, class283.field3646, class283.field3649, class283.field3647 };\n }\n\n @ObfuscatedName(\"w\")\n @ObfuscatedSignature(descriptor = \"(ILbe;ZI)I\", garbageValue = \"1564904197\")\n static int method697(int var0, Script var1, boolean var2) {\n Widget var3;\n if (var0 >= 2000) {\n var0 -= 1000;\n var3 = HealthBarUpdate.getWidget(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n } else {\n var3 = var2 ? WorldMapDecoration.scriptDotWidget : class245.scriptActiveWidget;\n }\n String var4 = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n int[] var5 = null;\n if (var4.length() > 0 && var4.charAt(var4.length() - 1) == 'Y') {\n int var6 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var6 > 0) {\n for (var5 = new int[var6]; var6-- > 0; var5[var6] = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]) {\n }\n }\n var4 = var4.substring(0, var4.length() - 1);\n }\n Object[] var8 = new Object[var4.length() + 1];\n int var7;\n for (var7 = var8.length - 1; var7 >= 1; --var7) {\n if (var4.charAt(var7 - 1) == 's') {\n var8[var7] = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n } else {\n var8[var7] = new Integer(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n }\n }\n var7 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var7 != -1) {\n var8[0] = new Integer(var7);\n } else {\n var8 = null;\n }\n if (var0 == ScriptOpcodes.CC_SETONCLICK) {\n var3.onClick = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONHOLD) {\n var3.onHold = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRELEASE) {\n var3.onRelease = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEOVER) {\n var3.onMouseOver = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSELEAVE) {\n var3.onMouseLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAG) {\n var3.onDrag = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETLEAVE) {\n var3.onTargetLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONVARTRANSMIT) {\n var3.onVarTransmit = var8;\n var3.varTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTIMER) {\n var3.onTimer = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONOP) {\n var3.onOp = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAGCOMPLETE) {\n var3.onDragComplete = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLICKREPEAT) {\n var3.onClickRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEREPEAT) {\n var3.onMouseRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONINVTRANSMIT) {\n var3.onInvTransmit = var8;\n var3.invTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONSTATTRANSMIT) {\n var3.onStatTransmit = var8;\n var3.statTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETENTER) {\n var3.onTargetEnter = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSCROLLWHEEL) {\n var3.onScroll = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCHATTRANSMIT) {\n var3.onChatTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONKEY) {\n var3.onKey = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONFRIENDTRANSMIT) {\n var3.onFriendTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANTRANSMIT) {\n var3.onClanTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMISCTRANSMIT) {\n var3.onMiscTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDIALOGABORT) {\n var3.onDialogAbort = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSUBCHANGE) {\n var3.onSubChange = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSTOCKTRANSMIT) {\n var3.onStockTransmit = var8;\n } else if (var0 == 1426) {\n var3.field3168 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRESIZE) {\n var3.onResize = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANSETTINGSTRANSMIT) {\n var3.field3161 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANCHANNELTRANSMIT) {\n var3.field3163 = var8;\n } else if (var0 == 1430) {\n var3.field3157 = var8;\n } else {\n if (var0 != 1431) {\n return 2;\n }\n var3.field3158 = var8;\n }\n var3.hasListener = true;\n return 1;\n }\n\n @ObfuscatedName(\"ff\")\n @ObfuscatedSignature(descriptor = \"(III)V\", garbageValue = \"-856147347\")\n static void method741(int var0, int var1) {\n if (WorldMapDecorationType.clientPreferences.musicVolume != 0 && var0 != -1) {\n class67.method1886(class4.archive11, var0, 0, WorldMapDecorationType.clientPreferences.musicVolume, false);\n Client.field663 = true;\n }\n }\n}\n"} {"task_id": "Java_1077", "language": "Java", "task_type": "try_statement", "source_file": "java/github/open-osrs/runelite/runescape-client/src/main/java/PcmPlayer.java", "mask_start_position": 6485, "mask_end_position": 6859, "canonical_solution": "try {\n if (var1 > this.timeMs + 500000L) {\n var1 = this.timeMs;\n }\n while (var1 > 5000L + this.timeMs) {\n this.skip(256);\n this.timeMs += (long) (256000 / field279);\n }\n } catch (Exception var6) {\n this.timeMs = var1;\n }", "pre_mask_code": "import java.util.concurrent.ScheduledExecutorService;\nimport net.runelite.mapping.Export;\nimport net.runelite.mapping.Implements;\nimport net.runelite.mapping.ObfuscatedGetter;\nimport net.runelite.mapping.ObfuscatedName;\nimport net.runelite.mapping.ObfuscatedSignature;\nimport net.runelite.rs.ScriptOpcodes;\n\n@ObfuscatedName(\"aq\")\n@Implements(\"PcmPlayer\")\npublic class PcmPlayer {\n\n @ObfuscatedName(\"sm\")\n @ObfuscatedGetter(intValue = 2053999609)\n static int field284;\n\n @ObfuscatedName(\"m\")\n @ObfuscatedGetter(intValue = 1333600085)\n public static int field279;\n\n @ObfuscatedName(\"k\")\n @Export(\"PcmPlayer_stereo\")\n public static boolean PcmPlayer_stereo;\n\n @ObfuscatedName(\"a\")\n @Export(\"soundSystemExecutor\")\n static ScheduledExecutorService soundSystemExecutor;\n\n @ObfuscatedName(\"e\")\n @ObfuscatedGetter(intValue = 234394993)\n public static int field283;\n\n @ObfuscatedName(\"v\")\n @Export(\"samples\")\n protected int[] samples;\n\n @ObfuscatedName(\"s\")\n @ObfuscatedSignature(descriptor = \"Lav;\")\n @Export(\"stream\")\n PcmStream stream;\n\n @ObfuscatedName(\"c\")\n @ObfuscatedGetter(intValue = -1215690509)\n int field269;\n\n @ObfuscatedName(\"b\")\n @ObfuscatedGetter(longValue = 2700493498205354685L)\n @Export(\"timeMs\")\n long timeMs;\n\n @ObfuscatedName(\"x\")\n @ObfuscatedGetter(intValue = 1537731573)\n @Export(\"capacity\")\n int capacity;\n\n @ObfuscatedName(\"p\")\n @ObfuscatedGetter(intValue = -1674723661)\n int field272;\n\n @ObfuscatedName(\"z\")\n @ObfuscatedGetter(intValue = 1001923267)\n int field265;\n\n @ObfuscatedName(\"h\")\n @ObfuscatedGetter(longValue = -2229248515898476515L)\n long field274;\n\n @ObfuscatedName(\"o\")\n @ObfuscatedGetter(intValue = 352319831)\n int field275;\n\n @ObfuscatedName(\"r\")\n @ObfuscatedGetter(intValue = 998812825)\n int field262;\n\n @ObfuscatedName(\"n\")\n @ObfuscatedGetter(intValue = -388583705)\n int field277;\n\n @ObfuscatedName(\"u\")\n @ObfuscatedGetter(longValue = -1357881854631939735L)\n long field278;\n\n @ObfuscatedName(\"d\")\n boolean field266;\n\n @ObfuscatedName(\"ay\")\n @ObfuscatedGetter(intValue = 461057869)\n int field281;\n\n @ObfuscatedName(\"al\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field286;\n\n @ObfuscatedName(\"ao\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field282;\n\n protected PcmPlayer() {\n this.field269 = 32;\n this.timeMs = UserComparator4.method2406();\n this.field274 = 0L;\n this.field275 = 0;\n this.field262 = 0;\n this.field277 = 0;\n this.field278 = 0L;\n this.field266 = true;\n this.field281 = 0;\n this.field286 = new PcmStream[8];\n this.field282 = new PcmStream[8];\n }\n\n @ObfuscatedName(\"l\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1783507069\")\n @Export(\"init\")\n protected void init() throws Exception {\n }\n\n @ObfuscatedName(\"q\")\n @ObfuscatedSignature(descriptor = \"(IB)V\", garbageValue = \"15\")\n @Export(\"open\")\n protected void open(int var1) throws Exception {\n }\n\n @ObfuscatedName(\"f\")\n @ObfuscatedSignature(descriptor = \"(I)I\", garbageValue = \"-625452134\")\n @Export(\"position\")\n protected int position() throws Exception {\n return this.capacity;\n }\n\n @ObfuscatedName(\"j\")\n @Export(\"write\")\n protected void write() throws Exception {\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1407514911\")\n @Export(\"close\")\n protected void close() {\n }\n\n @ObfuscatedName(\"k\")\n @ObfuscatedSignature(descriptor = \"(B)V\", garbageValue = \"-115\")\n @Export(\"discard\")\n protected void discard() throws Exception {\n }\n\n @ObfuscatedName(\"o\")\n @ObfuscatedSignature(descriptor = \"(Lav;I)V\", garbageValue = \"1536652372\")\n @Export(\"setStream\")\n public final synchronized void setStream(PcmStream var1) {\n this.stream = var1;\n }\n\n @ObfuscatedName(\"r\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1578748771\")\n @Export(\"run\")\n public final synchronized void run() {\n if (this.samples != null) {\n long var1 = UserComparator4.method2406();\n try {\n if (0L != this.field274) {\n if (var1 < this.field274) {\n return;\n }\n this.open(this.capacity);\n this.field274 = 0L;\n this.field266 = true;\n }\n int var3 = this.position();\n if (this.field277 - var3 > this.field275) {\n this.field275 = this.field277 - var3;\n }\n int var4 = this.field272 + this.field265;\n if (var4 + 256 > 16384) {\n var4 = 16128;\n }\n if (var4 + 256 > this.capacity) {\n this.capacity += 1024;\n if (this.capacity > 16384) {\n this.capacity = 16384;\n }\n this.close();\n this.open(this.capacity);\n var3 = 0;\n this.field266 = true;\n if (var4 + 256 > this.capacity) {\n var4 = this.capacity - 256;\n this.field265 = var4 - this.field272;\n }\n }\n while (var3 < var4) {\n this.fill(this.samples, 256);\n this.write();\n var3 += 256;\n }\n if (var1 > this.field278) {\n if (!this.field266) {\n if (this.field275 == 0 && this.field262 == 0) {\n this.close();\n this.field274 = var1 + 2000L;\n return;\n }\n this.field265 = Math.min(this.field262, this.field275);\n this.field262 = this.field275;\n } else {\n this.field266 = false;\n }\n this.field275 = 0;\n this.field278 = var1 + 2000L;\n }\n this.field277 = var3;\n } catch (Exception var7) {\n this.close();\n this.field274 = var1 + 2000L;\n }\n ", "post_mask_code": "\n }\n }\n\n @ObfuscatedName(\"n\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1285587409\")\n public final void method696() {\n this.field266 = true;\n }\n\n @ObfuscatedName(\"u\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1511155327\")\n @Export(\"tryDiscard\")\n public final synchronized void tryDiscard() {\n this.field266 = true;\n try {\n this.discard();\n } catch (Exception var2) {\n this.close();\n this.field274 = UserComparator4.method2406() + 2000L;\n }\n }\n\n @ObfuscatedName(\"d\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"25571035\")\n @Export(\"shutdown\")\n public final synchronized void shutdown() {\n if (Skeleton.soundSystem != null) {\n boolean var1 = true;\n for (int var2 = 0; var2 < 2; ++var2) {\n if (this == Skeleton.soundSystem.players[var2]) {\n Skeleton.soundSystem.players[var2] = null;\n }\n if (Skeleton.soundSystem.players[var2] != null) {\n var1 = false;\n }\n }\n if (var1) {\n soundSystemExecutor.shutdownNow();\n soundSystemExecutor = null;\n Skeleton.soundSystem = null;\n }\n }\n this.close();\n this.samples = null;\n }\n\n @ObfuscatedName(\"ab\")\n @ObfuscatedSignature(descriptor = \"(II)V\", garbageValue = \"4570450\")\n @Export(\"skip\")\n final void skip(int var1) {\n this.field281 -= var1;\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.skip(var1);\n }\n }\n\n @ObfuscatedName(\"ad\")\n @Export(\"fill\")\n final void fill(int[] var1, int var2) {\n int var3 = var2;\n if (PcmPlayer_stereo) {\n var3 = var2 << 1;\n }\n class321.clearIntArray(var1, 0, var3);\n this.field281 -= var2;\n if (this.stream != null && this.field281 <= 0) {\n this.field281 += field279 >> 4;\n class12.PcmStream_disable(this.stream);\n this.method711(this.stream, this.stream.vmethod944());\n int var4 = 0;\n int var5 = 255;\n int var6;\n PcmStream var10;\n label108: for (var6 = 7; var5 != 0; --var6) {\n int var7;\n int var8;\n if (var6 < 0) {\n var7 = var6 & 3;\n var8 = -(var6 >> 2);\n } else {\n var7 = var6;\n var8 = 0;\n }\n for (int var9 = var5 >>> var7 & 286331153; var9 != 0; var9 >>>= 4) {\n if ((var9 & 1) != 0) {\n var5 &= ~(1 << var7);\n var10 = null;\n PcmStream var11 = this.field286[var7];\n label102: while (true) {\n while (true) {\n if (var11 == null) {\n break label102;\n }\n AbstractSound var12 = var11.sound;\n if (var12 != null && var12.position > var8) {\n var5 |= 1 << var7;\n var10 = var11;\n var11 = var11.after;\n } else {\n var11.active = true;\n int var13 = var11.vmethod4889();\n var4 += var13;\n if (var12 != null) {\n var12.position += var13;\n }\n if (var4 >= this.field269) {\n break label108;\n }\n PcmStream var14 = var11.firstSubStream();\n if (var14 != null) {\n for (int var15 = var11.field335; var14 != null; var14 = var11.nextSubStream()) {\n this.method711(var14, var15 * var14.vmethod944() >> 8);\n }\n }\n PcmStream var18 = var11.after;\n var11.after = null;\n if (var10 == null) {\n this.field286[var7] = var18;\n } else {\n var10.after = var18;\n }\n if (var18 == null) {\n this.field282[var7] = var10;\n }\n var11 = var18;\n }\n }\n }\n }\n var7 += 4;\n ++var8;\n }\n }\n for (var6 = 0; var6 < 8; ++var6) {\n PcmStream var16 = this.field286[var6];\n PcmStream[] var17 = this.field286;\n this.field282[var6] = null;\n for (var17[var6] = null; var16 != null; var16 = var10) {\n var10 = var16.after;\n var16.after = null;\n }\n }\n }\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.fill(var1, 0, var2);\n }\n this.timeMs = UserComparator4.method2406();\n }\n\n @ObfuscatedName(\"ak\")\n @ObfuscatedSignature(descriptor = \"(Lav;II)V\", garbageValue = \"589893178\")\n final void method711(PcmStream var1, int var2) {\n int var3 = var2 >> 5;\n PcmStream var4 = this.field282[var3];\n if (var4 == null) {\n this.field286[var3] = var1;\n } else {\n var4.after = var1;\n }\n this.field282[var3] = var1;\n var1.field335 = var2;\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Lfp;\", garbageValue = \"1715478775\")\n static HorizontalAlignment[] method702() {\n return new HorizontalAlignment[] { HorizontalAlignment.field1708, HorizontalAlignment.field1707, HorizontalAlignment.HorizontalAlignment_centered };\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Ljm;\", garbageValue = \"1452483568\")\n public static class283[] method744() {\n return new class283[] { class283.field3648, class283.field3646, class283.field3649, class283.field3647 };\n }\n\n @ObfuscatedName(\"w\")\n @ObfuscatedSignature(descriptor = \"(ILbe;ZI)I\", garbageValue = \"1564904197\")\n static int method697(int var0, Script var1, boolean var2) {\n Widget var3;\n if (var0 >= 2000) {\n var0 -= 1000;\n var3 = HealthBarUpdate.getWidget(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n } else {\n var3 = var2 ? WorldMapDecoration.scriptDotWidget : class245.scriptActiveWidget;\n }\n String var4 = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n int[] var5 = null;\n if (var4.length() > 0 && var4.charAt(var4.length() - 1) == 'Y') {\n int var6 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var6 > 0) {\n for (var5 = new int[var6]; var6-- > 0; var5[var6] = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]) {\n }\n }\n var4 = var4.substring(0, var4.length() - 1);\n }\n Object[] var8 = new Object[var4.length() + 1];\n int var7;\n for (var7 = var8.length - 1; var7 >= 1; --var7) {\n if (var4.charAt(var7 - 1) == 's') {\n var8[var7] = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n } else {\n var8[var7] = new Integer(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n }\n }\n var7 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var7 != -1) {\n var8[0] = new Integer(var7);\n } else {\n var8 = null;\n }\n if (var0 == ScriptOpcodes.CC_SETONCLICK) {\n var3.onClick = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONHOLD) {\n var3.onHold = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRELEASE) {\n var3.onRelease = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEOVER) {\n var3.onMouseOver = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSELEAVE) {\n var3.onMouseLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAG) {\n var3.onDrag = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETLEAVE) {\n var3.onTargetLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONVARTRANSMIT) {\n var3.onVarTransmit = var8;\n var3.varTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTIMER) {\n var3.onTimer = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONOP) {\n var3.onOp = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAGCOMPLETE) {\n var3.onDragComplete = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLICKREPEAT) {\n var3.onClickRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEREPEAT) {\n var3.onMouseRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONINVTRANSMIT) {\n var3.onInvTransmit = var8;\n var3.invTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONSTATTRANSMIT) {\n var3.onStatTransmit = var8;\n var3.statTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETENTER) {\n var3.onTargetEnter = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSCROLLWHEEL) {\n var3.onScroll = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCHATTRANSMIT) {\n var3.onChatTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONKEY) {\n var3.onKey = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONFRIENDTRANSMIT) {\n var3.onFriendTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANTRANSMIT) {\n var3.onClanTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMISCTRANSMIT) {\n var3.onMiscTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDIALOGABORT) {\n var3.onDialogAbort = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSUBCHANGE) {\n var3.onSubChange = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSTOCKTRANSMIT) {\n var3.onStockTransmit = var8;\n } else if (var0 == 1426) {\n var3.field3168 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRESIZE) {\n var3.onResize = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANSETTINGSTRANSMIT) {\n var3.field3161 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANCHANNELTRANSMIT) {\n var3.field3163 = var8;\n } else if (var0 == 1430) {\n var3.field3157 = var8;\n } else {\n if (var0 != 1431) {\n return 2;\n }\n var3.field3158 = var8;\n }\n var3.hasListener = true;\n return 1;\n }\n\n @ObfuscatedName(\"ff\")\n @ObfuscatedSignature(descriptor = \"(III)V\", garbageValue = \"-856147347\")\n static void method741(int var0, int var1) {\n if (WorldMapDecorationType.clientPreferences.musicVolume != 0 && var0 != -1) {\n class67.method1886(class4.archive11, var0, 0, WorldMapDecorationType.clientPreferences.musicVolume, false);\n Client.field663 = true;\n }\n }\n}\n"} {"task_id": "Java_1078", "language": "Java", "task_type": "empty", "source_file": "java/github/open-osrs/runelite/runescape-client/src/main/java/PcmPlayer.java", "mask_start_position": 4519, "mask_end_position": 4519, "canonical_solution": "", "pre_mask_code": "import java.util.concurrent.ScheduledExecutorService;\nimport net.runelite.mapping.Export;\nimport net.runelite.mapping.Implements;\nimport net.runelite.mapping.ObfuscatedGetter;\nimport net.runelite.mapping.ObfuscatedName;\nimport net.runelite.mapping.ObfuscatedSignature;\nimport net.runelite.rs.ScriptOpcodes;\n\n@ObfuscatedName(\"aq\")\n@Implements(\"PcmPlayer\")\npublic class PcmPlayer {\n\n @ObfuscatedName(\"sm\")\n @ObfuscatedGetter(intValue = 2053999609)\n static int field284;\n\n @ObfuscatedName(\"m\")\n @ObfuscatedGetter(intValue = 1333600085)\n public static int field279;\n\n @ObfuscatedName(\"k\")\n @Export(\"PcmPlayer_stereo\")\n public static boolean PcmPlayer_stereo;\n\n @ObfuscatedName(\"a\")\n @Export(\"soundSystemExecutor\")\n static ScheduledExecutorService soundSystemExecutor;\n\n @ObfuscatedName(\"e\")\n @ObfuscatedGetter(intValue = 234394993)\n public static int field283;\n\n @ObfuscatedName(\"v\")\n @Export(\"samples\")\n protected int[] samples;\n\n @ObfuscatedName(\"s\")\n @ObfuscatedSignature(descriptor = \"Lav;\")\n @Export(\"stream\")\n PcmStream stream;\n\n @ObfuscatedName(\"c\")\n @ObfuscatedGetter(intValue = -1215690509)\n int field269;\n\n @ObfuscatedName(\"b\")\n @ObfuscatedGetter(longValue = 2700493498205354685L)\n @Export(\"timeMs\")\n long timeMs;\n\n @ObfuscatedName(\"x\")\n @ObfuscatedGetter(intValue = 1537731573)\n @Export(\"capacity\")\n int capacity;\n\n @ObfuscatedName(\"p\")\n @ObfuscatedGetter(intValue = -1674723661)\n int field272;\n\n @ObfuscatedName(\"z\")\n @ObfuscatedGetter(intValue = 1001923267)\n int field265;\n\n @ObfuscatedName(\"h\")\n @ObfuscatedGetter(longValue = -2229248515898476515L)\n long field274;\n\n @ObfuscatedName(\"o\")\n @ObfuscatedGetter(intValue = 352319831)\n int field275;\n\n @ObfuscatedName(\"r\")\n @ObfuscatedGetter(intValue = 998812825)\n int field262;\n\n @ObfuscatedName(\"n\")\n @ObfuscatedGetter(intValue = -388583705)\n int field277;\n\n @ObfuscatedName(\"u\")\n @ObfuscatedGetter(longValue = -1357881854631939735L)\n long field278;\n\n @ObfuscatedName(\"d\")\n boolean field266;\n\n @ObfuscatedName(\"ay\")\n @ObfuscatedGetter(intValue = 461057869)\n int field281;\n\n @ObfuscatedName(\"al\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field286;\n\n @ObfuscatedName(\"ao\")\n @ObfuscatedSignature(descriptor = \"[Lav;\")\n PcmStream[] field282;\n\n protected PcmPlayer() {\n this.field269 = 32;\n this.timeMs = UserComparator4.method2406();\n this.field274 = 0L;\n this.field275 = 0;\n this.field262 = 0;\n this.field277 = 0;\n this.field278 = 0L;\n this.field266 = true;\n this.field281 = 0;\n this.field286 = new PcmStream[8];\n this.field282 = new PcmStream[8];\n }\n\n @ObfuscatedName(\"l\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1783507069\")\n @Export(\"init\")\n protected void init() throws Exception {\n }\n\n @ObfuscatedName(\"q\")\n @ObfuscatedSignature(descriptor = \"(IB)V\", garbageValue = \"15\")\n @Export(\"open\")\n protected void open(int var1) throws Exception {\n }\n\n @ObfuscatedName(\"f\")\n @ObfuscatedSignature(descriptor = \"(I)I\", garbageValue = \"-625452134\")\n @Export(\"position\")\n protected int position() throws Exception {\n return this.capacity;\n }\n\n @ObfuscatedName(\"j\")\n @Export(\"write\")\n protected void write() throws Exception {\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1407514911\")\n @Export(\"close\")\n protected void close() {\n }\n\n @ObfuscatedName(\"k\")\n @ObfuscatedSignature(descriptor = \"(B)V\", garbageValue = \"-115\")\n @Export(\"discard\")\n protected void discard() throws Exception {\n }\n\n @ObfuscatedName(\"o\")\n @ObfuscatedSignature(descriptor = \"(Lav;I)V\", garbageValue = \"1536652372\")\n @Export(\"setStream\")\n public final synchronized void setStream(PcmStream var1) {\n this.stream = var1;\n }\n\n @ObfuscatedName(\"r\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"1578748771\")\n @Export(\"run\")\n public final synchronized void run() {\n if (this.samples != null) {\n long var1 = UserComparator4.method2406();\n try {\n if (0L != this.field274) {\n if (var1 < this.field274) {\n return;\n }\n this.open(this.capacity);\n this.field274 = 0L;\n ", "post_mask_code": " this.field266 = true;\n }\n int var3 = this.position();\n if (this.field277 - var3 > this.field275) {\n this.field275 = this.field277 - var3;\n }\n int var4 = this.field272 + this.field265;\n if (var4 + 256 > 16384) {\n var4 = 16128;\n }\n if (var4 + 256 > this.capacity) {\n this.capacity += 1024;\n if (this.capacity > 16384) {\n this.capacity = 16384;\n }\n this.close();\n this.open(this.capacity);\n var3 = 0;\n this.field266 = true;\n if (var4 + 256 > this.capacity) {\n var4 = this.capacity - 256;\n this.field265 = var4 - this.field272;\n }\n }\n while (var3 < var4) {\n this.fill(this.samples, 256);\n this.write();\n var3 += 256;\n }\n if (var1 > this.field278) {\n if (!this.field266) {\n if (this.field275 == 0 && this.field262 == 0) {\n this.close();\n this.field274 = var1 + 2000L;\n return;\n }\n this.field265 = Math.min(this.field262, this.field275);\n this.field262 = this.field275;\n } else {\n this.field266 = false;\n }\n this.field275 = 0;\n this.field278 = var1 + 2000L;\n }\n this.field277 = var3;\n } catch (Exception var7) {\n this.close();\n this.field274 = var1 + 2000L;\n }\n try {\n if (var1 > this.timeMs + 500000L) {\n var1 = this.timeMs;\n }\n while (var1 > 5000L + this.timeMs) {\n this.skip(256);\n this.timeMs += (long) (256000 / field279);\n }\n } catch (Exception var6) {\n this.timeMs = var1;\n }\n }\n }\n\n @ObfuscatedName(\"n\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1285587409\")\n public final void method696() {\n this.field266 = true;\n }\n\n @ObfuscatedName(\"u\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"-1511155327\")\n @Export(\"tryDiscard\")\n public final synchronized void tryDiscard() {\n this.field266 = true;\n try {\n this.discard();\n } catch (Exception var2) {\n this.close();\n this.field274 = UserComparator4.method2406() + 2000L;\n }\n }\n\n @ObfuscatedName(\"d\")\n @ObfuscatedSignature(descriptor = \"(I)V\", garbageValue = \"25571035\")\n @Export(\"shutdown\")\n public final synchronized void shutdown() {\n if (Skeleton.soundSystem != null) {\n boolean var1 = true;\n for (int var2 = 0; var2 < 2; ++var2) {\n if (this == Skeleton.soundSystem.players[var2]) {\n Skeleton.soundSystem.players[var2] = null;\n }\n if (Skeleton.soundSystem.players[var2] != null) {\n var1 = false;\n }\n }\n if (var1) {\n soundSystemExecutor.shutdownNow();\n soundSystemExecutor = null;\n Skeleton.soundSystem = null;\n }\n }\n this.close();\n this.samples = null;\n }\n\n @ObfuscatedName(\"ab\")\n @ObfuscatedSignature(descriptor = \"(II)V\", garbageValue = \"4570450\")\n @Export(\"skip\")\n final void skip(int var1) {\n this.field281 -= var1;\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.skip(var1);\n }\n }\n\n @ObfuscatedName(\"ad\")\n @Export(\"fill\")\n final void fill(int[] var1, int var2) {\n int var3 = var2;\n if (PcmPlayer_stereo) {\n var3 = var2 << 1;\n }\n class321.clearIntArray(var1, 0, var3);\n this.field281 -= var2;\n if (this.stream != null && this.field281 <= 0) {\n this.field281 += field279 >> 4;\n class12.PcmStream_disable(this.stream);\n this.method711(this.stream, this.stream.vmethod944());\n int var4 = 0;\n int var5 = 255;\n int var6;\n PcmStream var10;\n label108: for (var6 = 7; var5 != 0; --var6) {\n int var7;\n int var8;\n if (var6 < 0) {\n var7 = var6 & 3;\n var8 = -(var6 >> 2);\n } else {\n var7 = var6;\n var8 = 0;\n }\n for (int var9 = var5 >>> var7 & 286331153; var9 != 0; var9 >>>= 4) {\n if ((var9 & 1) != 0) {\n var5 &= ~(1 << var7);\n var10 = null;\n PcmStream var11 = this.field286[var7];\n label102: while (true) {\n while (true) {\n if (var11 == null) {\n break label102;\n }\n AbstractSound var12 = var11.sound;\n if (var12 != null && var12.position > var8) {\n var5 |= 1 << var7;\n var10 = var11;\n var11 = var11.after;\n } else {\n var11.active = true;\n int var13 = var11.vmethod4889();\n var4 += var13;\n if (var12 != null) {\n var12.position += var13;\n }\n if (var4 >= this.field269) {\n break label108;\n }\n PcmStream var14 = var11.firstSubStream();\n if (var14 != null) {\n for (int var15 = var11.field335; var14 != null; var14 = var11.nextSubStream()) {\n this.method711(var14, var15 * var14.vmethod944() >> 8);\n }\n }\n PcmStream var18 = var11.after;\n var11.after = null;\n if (var10 == null) {\n this.field286[var7] = var18;\n } else {\n var10.after = var18;\n }\n if (var18 == null) {\n this.field282[var7] = var10;\n }\n var11 = var18;\n }\n }\n }\n }\n var7 += 4;\n ++var8;\n }\n }\n for (var6 = 0; var6 < 8; ++var6) {\n PcmStream var16 = this.field286[var6];\n PcmStream[] var17 = this.field286;\n this.field282[var6] = null;\n for (var17[var6] = null; var16 != null; var16 = var10) {\n var10 = var16.after;\n var16.after = null;\n }\n }\n }\n if (this.field281 < 0) {\n this.field281 = 0;\n }\n if (this.stream != null) {\n this.stream.fill(var1, 0, var2);\n }\n this.timeMs = UserComparator4.method2406();\n }\n\n @ObfuscatedName(\"ak\")\n @ObfuscatedSignature(descriptor = \"(Lav;II)V\", garbageValue = \"589893178\")\n final void method711(PcmStream var1, int var2) {\n int var3 = var2 >> 5;\n PcmStream var4 = this.field282[var3];\n if (var4 == null) {\n this.field286[var3] = var1;\n } else {\n var4.after = var1;\n }\n this.field282[var3] = var1;\n var1.field335 = var2;\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Lfp;\", garbageValue = \"1715478775\")\n static HorizontalAlignment[] method702() {\n return new HorizontalAlignment[] { HorizontalAlignment.field1708, HorizontalAlignment.field1707, HorizontalAlignment.HorizontalAlignment_centered };\n }\n\n @ObfuscatedName(\"m\")\n @ObfuscatedSignature(descriptor = \"(I)[Ljm;\", garbageValue = \"1452483568\")\n public static class283[] method744() {\n return new class283[] { class283.field3648, class283.field3646, class283.field3649, class283.field3647 };\n }\n\n @ObfuscatedName(\"w\")\n @ObfuscatedSignature(descriptor = \"(ILbe;ZI)I\", garbageValue = \"1564904197\")\n static int method697(int var0, Script var1, boolean var2) {\n Widget var3;\n if (var0 >= 2000) {\n var0 -= 1000;\n var3 = HealthBarUpdate.getWidget(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n } else {\n var3 = var2 ? WorldMapDecoration.scriptDotWidget : class245.scriptActiveWidget;\n }\n String var4 = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n int[] var5 = null;\n if (var4.length() > 0 && var4.charAt(var4.length() - 1) == 'Y') {\n int var6 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var6 > 0) {\n for (var5 = new int[var6]; var6-- > 0; var5[var6] = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]) {\n }\n }\n var4 = var4.substring(0, var4.length() - 1);\n }\n Object[] var8 = new Object[var4.length() + 1];\n int var7;\n for (var7 = var8.length - 1; var7 >= 1; --var7) {\n if (var4.charAt(var7 - 1) == 's') {\n var8[var7] = Interpreter.Interpreter_stringStack[--class54.Interpreter_stringStackSize];\n } else {\n var8[var7] = new Integer(Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize]);\n }\n }\n var7 = Interpreter.Interpreter_intStack[--AbstractByteArrayCopier.Interpreter_intStackSize];\n if (var7 != -1) {\n var8[0] = new Integer(var7);\n } else {\n var8 = null;\n }\n if (var0 == ScriptOpcodes.CC_SETONCLICK) {\n var3.onClick = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONHOLD) {\n var3.onHold = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRELEASE) {\n var3.onRelease = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEOVER) {\n var3.onMouseOver = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSELEAVE) {\n var3.onMouseLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAG) {\n var3.onDrag = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETLEAVE) {\n var3.onTargetLeave = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONVARTRANSMIT) {\n var3.onVarTransmit = var8;\n var3.varTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTIMER) {\n var3.onTimer = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONOP) {\n var3.onOp = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDRAGCOMPLETE) {\n var3.onDragComplete = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLICKREPEAT) {\n var3.onClickRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMOUSEREPEAT) {\n var3.onMouseRepeat = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONINVTRANSMIT) {\n var3.onInvTransmit = var8;\n var3.invTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONSTATTRANSMIT) {\n var3.onStatTransmit = var8;\n var3.statTransmitTriggers = var5;\n } else if (var0 == ScriptOpcodes.CC_SETONTARGETENTER) {\n var3.onTargetEnter = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSCROLLWHEEL) {\n var3.onScroll = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCHATTRANSMIT) {\n var3.onChatTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONKEY) {\n var3.onKey = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONFRIENDTRANSMIT) {\n var3.onFriendTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANTRANSMIT) {\n var3.onClanTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONMISCTRANSMIT) {\n var3.onMiscTransmit = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONDIALOGABORT) {\n var3.onDialogAbort = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSUBCHANGE) {\n var3.onSubChange = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONSTOCKTRANSMIT) {\n var3.onStockTransmit = var8;\n } else if (var0 == 1426) {\n var3.field3168 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONRESIZE) {\n var3.onResize = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANSETTINGSTRANSMIT) {\n var3.field3161 = var8;\n } else if (var0 == ScriptOpcodes.CC_SETONCLANCHANNELTRANSMIT) {\n var3.field3163 = var8;\n } else if (var0 == 1430) {\n var3.field3157 = var8;\n } else {\n if (var0 != 1431) {\n return 2;\n }\n var3.field3158 = var8;\n }\n var3.hasListener = true;\n return 1;\n }\n\n @ObfuscatedName(\"ff\")\n @ObfuscatedSignature(descriptor = \"(III)V\", garbageValue = \"-856147347\")\n static void method741(int var0, int var1) {\n if (WorldMapDecorationType.clientPreferences.musicVolume != 0 && var0 != -1) {\n class67.method1886(class4.archive11, var0, 0, WorldMapDecorationType.clientPreferences.musicVolume, false);\n Client.field663 = true;\n }\n }\n}\n"} {"task_id": "Java_1079", "language": "Java", "task_type": "method_signature", "source_file": "java/github/DantSu/ESCPOS-ThermalPrinter-Android/escposprinter/src/main/java/com/dantsu/escposprinter/connection/tcp/TcpConnection.java", "mask_start_position": 1390, "mask_end_position": 1419, "canonical_solution": "public boolean isConnected() ", "pre_mask_code": "package com.dantsu.escposprinter.connection.tcp;\n\nimport com.dantsu.escposprinter.connection.DeviceConnection;\nimport com.dantsu.escposprinter.exceptions.EscPosConnectionException;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\n\npublic class TcpConnection extends DeviceConnection {\n\n private Socket socket = null;\n\n private String address;\n\n private int port;\n\n private int timeout;\n\n /**\n * Create un instance of TcpConnection.\n *\n * @param address IP address of the device\n * @param port Port of the device\n */\n public TcpConnection(String address, int port) {\n this(address, port, 30);\n }\n\n /**\n * Create un instance of TcpConnection.\n *\n * Overload of the above function TcpConnection()\n * Include timeout parameter in milliseconds.\n *\n * @param address IP address of the device\n * @param port Port of the device\n * @param timeout Timeout in milliseconds to establish a connection\n */\n public TcpConnection(String address, int port, int timeout) {\n super();\n this.address = address;\n this.port = port;\n this.timeout = timeout;\n }\n\n /**\n * Check if the TCP device is connected by socket.\n *\n * @return true if is connected\n */\n ", "post_mask_code": "{\n return this.socket != null && this.socket.isConnected() && super.isConnected();\n }\n\n /**\n * Start socket connection with the TCP device.\n */\n public TcpConnection connect() throws EscPosConnectionException {\n if (this.isConnected()) {\n return this;\n }\n try {\n this.socket = new Socket();\n this.socket.connect(new InetSocketAddress(InetAddress.getByName(this.address), this.port), this.timeout);\n this.outputStream = this.socket.getOutputStream();\n this.data = new byte[0];\n } catch (IOException e) {\n e.printStackTrace();\n this.disconnect();\n throw new EscPosConnectionException(\"Unable to connect to TCP device.\");\n }\n return this;\n }\n\n /**\n * Close the socket connection with the TCP device.\n */\n public TcpConnection disconnect() {\n this.data = new byte[0];\n if (this.outputStream != null) {\n try {\n this.outputStream.close();\n this.outputStream = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n if (this.socket != null) {\n try {\n this.socket.close();\n this.socket = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return this;\n }\n}\n"} {"task_id": "Java_1080", "language": "Java", "task_type": "method_body", "source_file": "java/github/DantSu/ESCPOS-ThermalPrinter-Android/escposprinter/src/main/java/com/dantsu/escposprinter/connection/tcp/TcpConnection.java", "mask_start_position": 1419, "mask_end_position": 1514, "canonical_solution": "{\n return this.socket != null && this.socket.isConnected() && super.isConnected();\n }", "pre_mask_code": "package com.dantsu.escposprinter.connection.tcp;\n\nimport com.dantsu.escposprinter.connection.DeviceConnection;\nimport com.dantsu.escposprinter.exceptions.EscPosConnectionException;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\n\npublic class TcpConnection extends DeviceConnection {\n\n private Socket socket = null;\n\n private String address;\n\n private int port;\n\n private int timeout;\n\n /**\n * Create un instance of TcpConnection.\n *\n * @param address IP address of the device\n * @param port Port of the device\n */\n public TcpConnection(String address, int port) {\n this(address, port, 30);\n }\n\n /**\n * Create un instance of TcpConnection.\n *\n * Overload of the above function TcpConnection()\n * Include timeout parameter in milliseconds.\n *\n * @param address IP address of the device\n * @param port Port of the device\n * @param timeout Timeout in milliseconds to establish a connection\n */\n public TcpConnection(String address, int port, int timeout) {\n super();\n this.address = address;\n this.port = port;\n this.timeout = timeout;\n }\n\n /**\n * Check if the TCP device is connected by socket.\n *\n * @return true if is connected\n */\n public boolean isConnected() ", "post_mask_code": "\n\n /**\n * Start socket connection with the TCP device.\n */\n public TcpConnection connect() throws EscPosConnectionException {\n if (this.isConnected()) {\n return this;\n }\n try {\n this.socket = new Socket();\n this.socket.connect(new InetSocketAddress(InetAddress.getByName(this.address), this.port), this.timeout);\n this.outputStream = this.socket.getOutputStream();\n this.data = new byte[0];\n } catch (IOException e) {\n e.printStackTrace();\n this.disconnect();\n throw new EscPosConnectionException(\"Unable to connect to TCP device.\");\n }\n return this;\n }\n\n /**\n * Close the socket connection with the TCP device.\n */\n public TcpConnection disconnect() {\n this.data = new byte[0];\n if (this.outputStream != null) {\n try {\n this.outputStream.close();\n this.outputStream = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n if (this.socket != null) {\n try {\n this.socket.close();\n this.socket = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return this;\n }\n}\n"} {"task_id": "Java_1081", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/DantSu/ESCPOS-ThermalPrinter-Android/escposprinter/src/main/java/com/dantsu/escposprinter/connection/tcp/TcpConnection.java", "mask_start_position": 2327, "mask_end_position": 2360, "canonical_solution": "\n this.data = new byte[0];", "pre_mask_code": "package com.dantsu.escposprinter.connection.tcp;\n\nimport com.dantsu.escposprinter.connection.DeviceConnection;\nimport com.dantsu.escposprinter.exceptions.EscPosConnectionException;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\n\npublic class TcpConnection extends DeviceConnection {\n\n private Socket socket = null;\n\n private String address;\n\n private int port;\n\n private int timeout;\n\n /**\n * Create un instance of TcpConnection.\n *\n * @param address IP address of the device\n * @param port Port of the device\n */\n public TcpConnection(String address, int port) {\n this(address, port, 30);\n }\n\n /**\n * Create un instance of TcpConnection.\n *\n * Overload of the above function TcpConnection()\n * Include timeout parameter in milliseconds.\n *\n * @param address IP address of the device\n * @param port Port of the device\n * @param timeout Timeout in milliseconds to establish a connection\n */\n public TcpConnection(String address, int port, int timeout) {\n super();\n this.address = address;\n this.port = port;\n this.timeout = timeout;\n }\n\n /**\n * Check if the TCP device is connected by socket.\n *\n * @return true if is connected\n */\n public boolean isConnected() {\n return this.socket != null && this.socket.isConnected() && super.isConnected();\n }\n\n /**\n * Start socket connection with the TCP device.\n */\n public TcpConnection connect() throws EscPosConnectionException {\n if (this.isConnected()) {\n return this;\n }\n try {\n this.socket = new Socket();\n this.socket.connect(new InetSocketAddress(InetAddress.getByName(this.address), this.port), this.timeout);\n this.outputStream = this.socket.getOutputStream();\n this.data = new byte[0];\n } catch (IOException e) {\n e.printStackTrace();\n this.disconnect();\n throw new EscPosConnectionException(\"Unable to connect to TCP device.\");\n }\n return this;\n }\n\n /**\n * Close the socket connection with the TCP device.\n */\n public TcpConnection disconnect() {", "post_mask_code": "\n if (this.outputStream != null) {\n try {\n this.outputStream.close();\n this.outputStream = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n if (this.socket != null) {\n try {\n this.socket.close();\n this.socket = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return this;\n }\n}\n"} {"task_id": "Java_1082", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/DantSu/ESCPOS-ThermalPrinter-Android/escposprinter/src/main/java/com/dantsu/escposprinter/connection/tcp/TcpConnection.java", "mask_start_position": 2369, "mask_end_position": 2828, "canonical_solution": "if (this.outputStream != null) {\n try {\n this.outputStream.close();\n this.outputStream = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n if (this.socket != null) {\n try {\n this.socket.close();\n this.socket = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }", "pre_mask_code": "package com.dantsu.escposprinter.connection.tcp;\n\nimport com.dantsu.escposprinter.connection.DeviceConnection;\nimport com.dantsu.escposprinter.exceptions.EscPosConnectionException;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\n\npublic class TcpConnection extends DeviceConnection {\n\n private Socket socket = null;\n\n private String address;\n\n private int port;\n\n private int timeout;\n\n /**\n * Create un instance of TcpConnection.\n *\n * @param address IP address of the device\n * @param port Port of the device\n */\n public TcpConnection(String address, int port) {\n this(address, port, 30);\n }\n\n /**\n * Create un instance of TcpConnection.\n *\n * Overload of the above function TcpConnection()\n * Include timeout parameter in milliseconds.\n *\n * @param address IP address of the device\n * @param port Port of the device\n * @param timeout Timeout in milliseconds to establish a connection\n */\n public TcpConnection(String address, int port, int timeout) {\n super();\n this.address = address;\n this.port = port;\n this.timeout = timeout;\n }\n\n /**\n * Check if the TCP device is connected by socket.\n *\n * @return true if is connected\n */\n public boolean isConnected() {\n return this.socket != null && this.socket.isConnected() && super.isConnected();\n }\n\n /**\n * Start socket connection with the TCP device.\n */\n public TcpConnection connect() throws EscPosConnectionException {\n if (this.isConnected()) {\n return this;\n }\n try {\n this.socket = new Socket();\n this.socket.connect(new InetSocketAddress(InetAddress.getByName(this.address), this.port), this.timeout);\n this.outputStream = this.socket.getOutputStream();\n this.data = new byte[0];\n } catch (IOException e) {\n e.printStackTrace();\n this.disconnect();\n throw new EscPosConnectionException(\"Unable to connect to TCP device.\");\n }\n return this;\n }\n\n /**\n * Close the socket connection with the TCP device.\n */\n public TcpConnection disconnect() {\n this.data = new byte[0];\n ", "post_mask_code": "\n return this;\n }\n}\n"} {"task_id": "Java_1083", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/DantSu/ESCPOS-ThermalPrinter-Android/escposprinter/src/main/java/com/dantsu/escposprinter/connection/tcp/TcpConnection.java", "mask_start_position": 2837, "mask_end_position": 2855, "canonical_solution": "return this;\n }", "pre_mask_code": "package com.dantsu.escposprinter.connection.tcp;\n\nimport com.dantsu.escposprinter.connection.DeviceConnection;\nimport com.dantsu.escposprinter.exceptions.EscPosConnectionException;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\n\npublic class TcpConnection extends DeviceConnection {\n\n private Socket socket = null;\n\n private String address;\n\n private int port;\n\n private int timeout;\n\n /**\n * Create un instance of TcpConnection.\n *\n * @param address IP address of the device\n * @param port Port of the device\n */\n public TcpConnection(String address, int port) {\n this(address, port, 30);\n }\n\n /**\n * Create un instance of TcpConnection.\n *\n * Overload of the above function TcpConnection()\n * Include timeout parameter in milliseconds.\n *\n * @param address IP address of the device\n * @param port Port of the device\n * @param timeout Timeout in milliseconds to establish a connection\n */\n public TcpConnection(String address, int port, int timeout) {\n super();\n this.address = address;\n this.port = port;\n this.timeout = timeout;\n }\n\n /**\n * Check if the TCP device is connected by socket.\n *\n * @return true if is connected\n */\n public boolean isConnected() {\n return this.socket != null && this.socket.isConnected() && super.isConnected();\n }\n\n /**\n * Start socket connection with the TCP device.\n */\n public TcpConnection connect() throws EscPosConnectionException {\n if (this.isConnected()) {\n return this;\n }\n try {\n this.socket = new Socket();\n this.socket.connect(new InetSocketAddress(InetAddress.getByName(this.address), this.port), this.timeout);\n this.outputStream = this.socket.getOutputStream();\n this.data = new byte[0];\n } catch (IOException e) {\n e.printStackTrace();\n this.disconnect();\n throw new EscPosConnectionException(\"Unable to connect to TCP device.\");\n }\n return this;\n }\n\n /**\n * Close the socket connection with the TCP device.\n */\n public TcpConnection disconnect() {\n this.data = new byte[0];\n if (this.outputStream != null) {\n try {\n this.outputStream.close();\n this.outputStream = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n if (this.socket != null) {\n try {\n this.socket.close();\n this.socket = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1084", "language": "Java", "task_type": "single_line", "source_file": "java/github/DantSu/ESCPOS-ThermalPrinter-Android/escposprinter/src/main/java/com/dantsu/escposprinter/connection/tcp/TcpConnection.java", "mask_start_position": 1431, "mask_end_position": 1508, "canonical_solution": "turn this.socket != null && this.socket.isConnected() && super.isConnected();", "pre_mask_code": "package com.dantsu.escposprinter.connection.tcp;\n\nimport com.dantsu.escposprinter.connection.DeviceConnection;\nimport com.dantsu.escposprinter.exceptions.EscPosConnectionException;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\n\npublic class TcpConnection extends DeviceConnection {\n\n private Socket socket = null;\n\n private String address;\n\n private int port;\n\n private int timeout;\n\n /**\n * Create un instance of TcpConnection.\n *\n * @param address IP address of the device\n * @param port Port of the device\n */\n public TcpConnection(String address, int port) {\n this(address, port, 30);\n }\n\n /**\n * Create un instance of TcpConnection.\n *\n * Overload of the above function TcpConnection()\n * Include timeout parameter in milliseconds.\n *\n * @param address IP address of the device\n * @param port Port of the device\n * @param timeout Timeout in milliseconds to establish a connection\n */\n public TcpConnection(String address, int port, int timeout) {\n super();\n this.address = address;\n this.port = port;\n this.timeout = timeout;\n }\n\n /**\n * Check if the TCP device is connected by socket.\n *\n * @return true if is connected\n */\n public boolean isConnected() {\n re", "post_mask_code": "\n }\n\n /**\n * Start socket connection with the TCP device.\n */\n public TcpConnection connect() throws EscPosConnectionException {\n if (this.isConnected()) {\n return this;\n }\n try {\n this.socket = new Socket();\n this.socket.connect(new InetSocketAddress(InetAddress.getByName(this.address), this.port), this.timeout);\n this.outputStream = this.socket.getOutputStream();\n this.data = new byte[0];\n } catch (IOException e) {\n e.printStackTrace();\n this.disconnect();\n throw new EscPosConnectionException(\"Unable to connect to TCP device.\");\n }\n return this;\n }\n\n /**\n * Close the socket connection with the TCP device.\n */\n public TcpConnection disconnect() {\n this.data = new byte[0];\n if (this.outputStream != null) {\n try {\n this.outputStream.close();\n this.outputStream = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n if (this.socket != null) {\n try {\n this.socket.close();\n this.socket = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return this;\n }\n}\n"} {"task_id": "Java_1085", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/DantSu/ESCPOS-ThermalPrinter-Android/escposprinter/src/main/java/com/dantsu/escposprinter/connection/tcp/TcpConnection.java", "mask_start_position": 1390, "mask_end_position": 1514, "canonical_solution": "public boolean isConnected() {\n return this.socket != null && this.socket.isConnected() && super.isConnected();\n }", "pre_mask_code": "package com.dantsu.escposprinter.connection.tcp;\n\nimport com.dantsu.escposprinter.connection.DeviceConnection;\nimport com.dantsu.escposprinter.exceptions.EscPosConnectionException;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\n\npublic class TcpConnection extends DeviceConnection {\n\n private Socket socket = null;\n\n private String address;\n\n private int port;\n\n private int timeout;\n\n /**\n * Create un instance of TcpConnection.\n *\n * @param address IP address of the device\n * @param port Port of the device\n */\n public TcpConnection(String address, int port) {\n this(address, port, 30);\n }\n\n /**\n * Create un instance of TcpConnection.\n *\n * Overload of the above function TcpConnection()\n * Include timeout parameter in milliseconds.\n *\n * @param address IP address of the device\n * @param port Port of the device\n * @param timeout Timeout in milliseconds to establish a connection\n */\n public TcpConnection(String address, int port, int timeout) {\n super();\n this.address = address;\n this.port = port;\n this.timeout = timeout;\n }\n\n /**\n * Check if the TCP device is connected by socket.\n *\n * @return true if is connected\n */\n ", "post_mask_code": "\n\n /**\n * Start socket connection with the TCP device.\n */\n public TcpConnection connect() throws EscPosConnectionException {\n if (this.isConnected()) {\n return this;\n }\n try {\n this.socket = new Socket();\n this.socket.connect(new InetSocketAddress(InetAddress.getByName(this.address), this.port), this.timeout);\n this.outputStream = this.socket.getOutputStream();\n this.data = new byte[0];\n } catch (IOException e) {\n e.printStackTrace();\n this.disconnect();\n throw new EscPosConnectionException(\"Unable to connect to TCP device.\");\n }\n return this;\n }\n\n /**\n * Close the socket connection with the TCP device.\n */\n public TcpConnection disconnect() {\n this.data = new byte[0];\n if (this.outputStream != null) {\n try {\n this.outputStream.close();\n this.outputStream = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n if (this.socket != null) {\n try {\n this.socket.close();\n this.socket = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return this;\n }\n}\n"} {"task_id": "Java_1086", "language": "Java", "task_type": "if_statement", "source_file": "java/github/DantSu/ESCPOS-ThermalPrinter-Android/escposprinter/src/main/java/com/dantsu/escposprinter/connection/tcp/TcpConnection.java", "mask_start_position": 1662, "mask_end_position": 1722, "canonical_solution": "if (this.isConnected()) {\n return this;\n }", "pre_mask_code": "package com.dantsu.escposprinter.connection.tcp;\n\nimport com.dantsu.escposprinter.connection.DeviceConnection;\nimport com.dantsu.escposprinter.exceptions.EscPosConnectionException;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\n\npublic class TcpConnection extends DeviceConnection {\n\n private Socket socket = null;\n\n private String address;\n\n private int port;\n\n private int timeout;\n\n /**\n * Create un instance of TcpConnection.\n *\n * @param address IP address of the device\n * @param port Port of the device\n */\n public TcpConnection(String address, int port) {\n this(address, port, 30);\n }\n\n /**\n * Create un instance of TcpConnection.\n *\n * Overload of the above function TcpConnection()\n * Include timeout parameter in milliseconds.\n *\n * @param address IP address of the device\n * @param port Port of the device\n * @param timeout Timeout in milliseconds to establish a connection\n */\n public TcpConnection(String address, int port, int timeout) {\n super();\n this.address = address;\n this.port = port;\n this.timeout = timeout;\n }\n\n /**\n * Check if the TCP device is connected by socket.\n *\n * @return true if is connected\n */\n public boolean isConnected() {\n return this.socket != null && this.socket.isConnected() && super.isConnected();\n }\n\n /**\n * Start socket connection with the TCP device.\n */\n public TcpConnection connect() throws EscPosConnectionException {\n ", "post_mask_code": "\n try {\n this.socket = new Socket();\n this.socket.connect(new InetSocketAddress(InetAddress.getByName(this.address), this.port), this.timeout);\n this.outputStream = this.socket.getOutputStream();\n this.data = new byte[0];\n } catch (IOException e) {\n e.printStackTrace();\n this.disconnect();\n throw new EscPosConnectionException(\"Unable to connect to TCP device.\");\n }\n return this;\n }\n\n /**\n * Close the socket connection with the TCP device.\n */\n public TcpConnection disconnect() {\n this.data = new byte[0];\n if (this.outputStream != null) {\n try {\n this.outputStream.close();\n this.outputStream = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n if (this.socket != null) {\n try {\n this.socket.close();\n this.socket = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return this;\n }\n}\n"} {"task_id": "Java_1087", "language": "Java", "task_type": "try_statement", "source_file": "java/github/DantSu/ESCPOS-ThermalPrinter-Android/escposprinter/src/main/java/com/dantsu/escposprinter/connection/tcp/TcpConnection.java", "mask_start_position": 2414, "mask_end_position": 2593, "canonical_solution": "try {\n this.outputStream.close();\n this.outputStream = null;\n } catch (IOException e) {\n e.printStackTrace();\n }", "pre_mask_code": "package com.dantsu.escposprinter.connection.tcp;\n\nimport com.dantsu.escposprinter.connection.DeviceConnection;\nimport com.dantsu.escposprinter.exceptions.EscPosConnectionException;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\n\npublic class TcpConnection extends DeviceConnection {\n\n private Socket socket = null;\n\n private String address;\n\n private int port;\n\n private int timeout;\n\n /**\n * Create un instance of TcpConnection.\n *\n * @param address IP address of the device\n * @param port Port of the device\n */\n public TcpConnection(String address, int port) {\n this(address, port, 30);\n }\n\n /**\n * Create un instance of TcpConnection.\n *\n * Overload of the above function TcpConnection()\n * Include timeout parameter in milliseconds.\n *\n * @param address IP address of the device\n * @param port Port of the device\n * @param timeout Timeout in milliseconds to establish a connection\n */\n public TcpConnection(String address, int port, int timeout) {\n super();\n this.address = address;\n this.port = port;\n this.timeout = timeout;\n }\n\n /**\n * Check if the TCP device is connected by socket.\n *\n * @return true if is connected\n */\n public boolean isConnected() {\n return this.socket != null && this.socket.isConnected() && super.isConnected();\n }\n\n /**\n * Start socket connection with the TCP device.\n */\n public TcpConnection connect() throws EscPosConnectionException {\n if (this.isConnected()) {\n return this;\n }\n try {\n this.socket = new Socket();\n this.socket.connect(new InetSocketAddress(InetAddress.getByName(this.address), this.port), this.timeout);\n this.outputStream = this.socket.getOutputStream();\n this.data = new byte[0];\n } catch (IOException e) {\n e.printStackTrace();\n this.disconnect();\n throw new EscPosConnectionException(\"Unable to connect to TCP device.\");\n }\n return this;\n }\n\n /**\n * Close the socket connection with the TCP device.\n */\n public TcpConnection disconnect() {\n this.data = new byte[0];\n if (this.outputStream != null) {\n ", "post_mask_code": "\n }\n if (this.socket != null) {\n try {\n this.socket.close();\n this.socket = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return this;\n }\n}\n"} {"task_id": "Java_1088", "language": "Java", "task_type": "empty", "source_file": "java/github/DantSu/ESCPOS-ThermalPrinter-Android/escposprinter/src/main/java/com/dantsu/escposprinter/connection/tcp/TcpConnection.java", "mask_start_position": 511, "mask_end_position": 511, "canonical_solution": "", "pre_mask_code": "package com.dantsu.escposprinter.connection.tcp;\n\nimport com.dantsu.escposprinter.connection.DeviceConnection;\nimport com.dantsu.escposprinter.exceptions.EscPosConnectionException;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\n\npublic class TcpConnection extends DeviceConnection {\n\n private Socket socket = null;\n\n private String address;\n\n private int port;\n\n private int timeout;\n\n /", "post_mask_code": "**\n * Create un instance of TcpConnection.\n *\n * @param address IP address of the device\n * @param port Port of the device\n */\n public TcpConnection(String address, int port) {\n this(address, port, 30);\n }\n\n /**\n * Create un instance of TcpConnection.\n *\n * Overload of the above function TcpConnection()\n * Include timeout parameter in milliseconds.\n *\n * @param address IP address of the device\n * @param port Port of the device\n * @param timeout Timeout in milliseconds to establish a connection\n */\n public TcpConnection(String address, int port, int timeout) {\n super();\n this.address = address;\n this.port = port;\n this.timeout = timeout;\n }\n\n /**\n * Check if the TCP device is connected by socket.\n *\n * @return true if is connected\n */\n public boolean isConnected() {\n return this.socket != null && this.socket.isConnected() && super.isConnected();\n }\n\n /**\n * Start socket connection with the TCP device.\n */\n public TcpConnection connect() throws EscPosConnectionException {\n if (this.isConnected()) {\n return this;\n }\n try {\n this.socket = new Socket();\n this.socket.connect(new InetSocketAddress(InetAddress.getByName(this.address), this.port), this.timeout);\n this.outputStream = this.socket.getOutputStream();\n this.data = new byte[0];\n } catch (IOException e) {\n e.printStackTrace();\n this.disconnect();\n throw new EscPosConnectionException(\"Unable to connect to TCP device.\");\n }\n return this;\n }\n\n /**\n * Close the socket connection with the TCP device.\n */\n public TcpConnection disconnect() {\n this.data = new byte[0];\n if (this.outputStream != null) {\n try {\n this.outputStream.close();\n this.outputStream = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n if (this.socket != null) {\n try {\n this.socket.close();\n this.socket = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return this;\n }\n}\n"} {"task_id": "Java_1089", "language": "Java", "task_type": "method_signature", "source_file": "java/github/tlaplus/tlaplus/toolbox/org.lamport.tla.toolbox.editor.basic/src/org/lamport/tla/toolbox/editor/basic/TLAReconcilingStrategy.java", "mask_start_position": 4876, "mask_end_position": 4953, "canonical_solution": "@Override\n public void setProgressMonitor(final IProgressMonitor monitor) ", "pre_mask_code": "package org.lamport.tla.toolbox.editor.basic;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.FindReplaceDocumentAdapter;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.IDocumentExtension3;\nimport org.eclipse.jface.text.IRegion;\nimport org.eclipse.jface.text.Position;\nimport org.eclipse.jface.text.reconciler.DirtyRegion;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategy;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;\nimport org.eclipse.jface.text.source.Annotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;\nimport org.eclipse.jface.text.source.projection.ProjectionViewer;\nimport org.eclipse.jface.util.IPropertyChangeListener;\nimport org.eclipse.jface.util.PropertyChangeEvent;\nimport org.eclipse.ui.PlatformUI;\nimport org.lamport.tla.toolbox.editor.basic.pcal.IPCalReservedWords;\nimport org.lamport.tla.toolbox.util.pref.IPreferenceConstants;\nimport org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;\n\n/**\n * We create this reconciling strategy for at least two reasons:\n * \t. having our custom source viewer configuration not use its super class' reconciler frees us from spell checking\n * \t\tmarkup\n * \t. to find fold locations for:\n * \t\t\t. block commments\n * \t\t\t. PlusCal code\n */\npublic class TLAReconcilingStrategy implements IPropertyChangeListener, IReconcilingStrategy, IReconcilingStrategyExtension {\n\n // Per BoxedCommentHandler, a delimiter is \"(\" followed by three \"*\", then 0-N \"*\", and finally suffixed with \")\"\n private static final String BLOCK_COMMENT_DELIMITER_REGEX = \"^[ \\\\t]*\\\\(\\\\*{3}\\\\**\\\\)\\\\s*$\";\n\n private static final String SINGLE_LINE_COMMENT = \"^[ \\\\t]*\\\\\\\\\\\\*\";\n\n private static final String PCAL_TRANSLATION_PREFIX_REGEX = \"^\\\\\\\\\\\\*+ BEGIN TRANSLATION.*$\";\n\n private static final String PCAL_TRANSLATION_SUFFIX_REGEX = \"^\\\\\\\\\\\\*+ END TRANSLATION.*$\";\n\n private IDocument document;\n\n /* the currently displayed projection annotations */\n protected final List currentAnnotations;\n\n /* the editor we're bound to */\n private TLAEditor editor;\n\n /* the underlying source viewer */\n private ProjectionViewer projectionViewer;\n\n private final AtomicBoolean foldBlockComments;\n\n private final AtomicBoolean foldPlusCalAlgorithm;\n\n private final AtomicBoolean foldTranslatedPlusCalBlock;\n\n public TLAReconcilingStrategy() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.addPropertyChangeListener(this);\n currentAnnotations = new ArrayList<>();\n foldBlockComments = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS));\n foldPlusCalAlgorithm = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM));\n foldTranslatedPlusCalBlock = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED));\n }\n\n public void dispose() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.removePropertyChangeListener(this);\n }\n\n @Override\n public void propertyChange(final PropertyChangeEvent event) {\n final boolean reconcile;\n if (IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS.equals(event.getProperty())) {\n foldBlockComments.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM.equals(event.getProperty())) {\n foldPlusCalAlgorithm.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED.equals(event.getProperty())) {\n foldTranslatedPlusCalBlock.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else {\n reconcile = false;\n }\n if (reconcile) {\n reconcile(null, null, null);\n }\n }\n\n @Override\n public void reconcile(final IRegion partition) {\n reconcile(partition, null, null);\n }\n\n @Override\n public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {\n reconcile(null, dirtyRegion, subRegion);\n }\n\n @Override\n public void setDocument(final IDocument id) {\n document = id;\n }\n\n @Override\n public void initialReconcile() {\n reconcile(null, null, null);\n }\n\n ", "post_mask_code": "{\n }\n\n /**\n * Sets the editor to which we're bound; this is required for communicating folding projections.\n *\n * @param editor\n */\n public void setEditor(final TLAEditor tlaEditor) {\n editor = tlaEditor;\n }\n\n /**\n * Sets the projection viewer for which we're reconciling.\n *\n * @param viewer\n */\n public void setProjectionViewer(final ProjectionViewer viewer) {\n projectionViewer = viewer;\n projectionViewer.setData(getClass().toString(), this);\n }\n\n private void reconcile(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n if (editor != null) {\n final HashMap regionMap = determineFoldingRegions(partition, dirtyRegion, subRegion);\n final Annotation[] deletions;\n final HashMap regionsToAdd = new HashMap<>();\n synchronized (currentAnnotations) {\n for (final Map.Entry me : regionMap.entrySet()) {\n if (!currentAnnotations.remove(me.getKey())) {\n regionsToAdd.put(me.getKey(), me.getValue());\n }\n }\n deletions = currentAnnotations.toArray(new Annotation[currentAnnotations.size()]);\n currentAnnotations.clear();\n currentAnnotations.addAll(regionMap.keySet());\n }\n PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\n\n public void run() {\n editor.modifyProjectionAnnotations(deletions, regionsToAdd);\n if (projectionViewer != null) {\n final ProjectionAnnotationModel model = projectionViewer.getProjectionAnnotationModel();\n final boolean block = foldBlockComments.get();\n final boolean pcal = foldPlusCalAlgorithm.get();\n final boolean translated = foldTranslatedPlusCalBlock.get();\n // We could do even more optimization than this, but this is better than none.\n if (block || pcal || translated) {\n for (final TLCProjectionAnnotation annotation : currentAnnotations) {\n final boolean collapse;\n switch(annotation.getTLCType()) {\n case BLOCK_COMMENT:\n collapse = block;\n break;\n case PCAL_BLOCK:\n collapse = pcal;\n break;\n default:\n collapse = translated;\n }\n if (collapse) {\n model.collapse(annotation);\n }\n }\n }\n }\n }\n });\n }\n }\n\n /**\n * Once upon a time (the original version of this,) document partitioning was performed via\n * \t{@link IDocumentExtension3#computePartitioning(String, int, int, boolean)} and it did a\n * \tterrible job. Now, instead, we're using the Eclipse {@link FindReplaceDocumentAdapter} class.\n */\n private HashMap determineFoldingRegions(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n // TODO use regions for tracking in optimizations on re-parses\n final HashMap additions = new HashMap<>();\n final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(document);\n // PCal location\n try {\n IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);\n if (find == null) {\n find = search.find(0, \"--\" + IPCalReservedWords.FAIR, true, true, false, false);\n }\n if (find != null) {\n final int pcalStartLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\(\\\\*\", false, true, false, true);\n if (find != null) {\n final int startLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\s?\\\\*+\\\\)$\", true, true, false, true);\n addProjectionAdditionToMap(additions, startLocation, find, AnnotationType.PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Translated PCal location\n try {\n IRegion find = search.find(0, PCAL_TRANSLATION_PREFIX_REGEX, true, true, false, true);\n if (find != null) {\n final int translationStartLocation = find.getOffset();\n find = search.find(translationStartLocation, PCAL_TRANSLATION_SUFFIX_REGEX, true, true, false, true);\n if (find != null) {\n addProjectionAdditionToMap(additions, translationStartLocation, find, AnnotationType.TRANSLATED_PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Block comment locations\n try {\n boolean inBlock = false;\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n while (find != null) {\n if (inBlock) {\n addProjectionAdditionToMap(additions, lastFoundIndex, find, AnnotationType.BLOCK_COMMENT);\n }\n inBlock = !inBlock;\n lastFoundIndex = find.getOffset();\n find = search.find((lastFoundIndex + find.getLength()), BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n }\n } catch (final BadLocationException ble) {\n }\n // 2 or more consecutive single line comments\n try {\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, SINGLE_LINE_COMMENT, true, true, false, true);\n int contiguousLineCount = 1;\n int firstMatchingOffset = -1;\n while (find != null) {\n if (firstMatchingOffset == -1) {\n firstMatchingOffset = find.getOffset();\n }\n lastFoundIndex = find.getOffset();\n final IRegion lineEnding = search.find((lastFoundIndex + find.getLength()), \"\\\\n\", true, true, false, true);\n if (lineEnding != null) {\n lastFoundIndex = lineEnding.getOffset();\n find = search.find((lastFoundIndex + 1), SINGLE_LINE_COMMENT, true, true, false, true);\n } else {\n // In this case the document has ended without a newline (but with a comment)\n lastFoundIndex += find.getLength();\n find = null;\n }\n boolean addProjection = (contiguousLineCount > 1);\n boolean reset = true;\n if ((find != null) && (find.getOffset() == (lastFoundIndex + 1))) {\n contiguousLineCount++;\n addProjection = false;\n reset = false;\n }\n if (addProjection) {\n addProjectionAdditionToMap(additions, firstMatchingOffset, lastFoundIndex, AnnotationType.MULTIPLE_SINGLE_LINE_COMMENT);\n }\n if (reset) {\n contiguousLineCount = 1;\n firstMatchingOffset = -1;\n }\n }\n } catch (final BadLocationException ble) {\n }\n return additions;\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final IRegion find, final AnnotationType type) throws BadLocationException {\n if (find != null) {\n final int endLocation = find.getOffset() + find.getLength() + 1;\n addProjectionAdditionToMap(additions, startLocation, endLocation, type);\n }\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final int endLocation, final AnnotationType type) throws BadLocationException {\n final int length = endLocation - startLocation;\n // +1 to cover the newline\n final int positionLength = length + ((document.getLength() > endLocation) ? 1 : 0);\n final Position position = new Position(startLocation, positionLength);\n additions.put(new TLCProjectionAnnotation(document.get(startLocation, length), type), position);\n }\n\n private enum AnnotationType {\n\n BLOCK_COMMENT, MULTIPLE_SINGLE_LINE_COMMENT, PCAL_BLOCK, TRANSLATED_PCAL_BLOCK\n }\n\n // Nothing in the ProjectionAnnotation hierarchy implements equals/hashCode, we'd like such things to exist\n // for reconciliation; also we denote classifications of annotations for folding groups.\n private static class TLCProjectionAnnotation extends ProjectionAnnotation {\n\n private final AnnotationType type;\n\n TLCProjectionAnnotation(final String text, final AnnotationType annotationType) {\n setText(text);\n type = annotationType;\n }\n\n AnnotationType getTLCType() {\n return type;\n }\n\n @Override\n public boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n if (!Annotation.class.isAssignableFrom(other.getClass())) {\n return false;\n }\n final Annotation otherAnnotation = (Annotation) other;\n final String otherText = otherAnnotation.getText();\n return Objects.equals(getText(), otherText);\n }\n\n @Override\n public int hashCode() {\n final String text = getText();\n if (text == null) {\n return 0;\n }\n return text.hashCode();\n }\n }\n}\n"} {"task_id": "Java_1090", "language": "Java", "task_type": "method_body", "source_file": "java/github/tlaplus/tlaplus/toolbox/org.lamport.tla.toolbox.editor.basic/src/org/lamport/tla/toolbox/editor/basic/TLAReconcilingStrategy.java", "mask_start_position": 14714, "mask_end_position": 14750, "canonical_solution": "{\n return type;\n }", "pre_mask_code": "package org.lamport.tla.toolbox.editor.basic;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.FindReplaceDocumentAdapter;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.IDocumentExtension3;\nimport org.eclipse.jface.text.IRegion;\nimport org.eclipse.jface.text.Position;\nimport org.eclipse.jface.text.reconciler.DirtyRegion;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategy;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;\nimport org.eclipse.jface.text.source.Annotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;\nimport org.eclipse.jface.text.source.projection.ProjectionViewer;\nimport org.eclipse.jface.util.IPropertyChangeListener;\nimport org.eclipse.jface.util.PropertyChangeEvent;\nimport org.eclipse.ui.PlatformUI;\nimport org.lamport.tla.toolbox.editor.basic.pcal.IPCalReservedWords;\nimport org.lamport.tla.toolbox.util.pref.IPreferenceConstants;\nimport org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;\n\n/**\n * We create this reconciling strategy for at least two reasons:\n * \t. having our custom source viewer configuration not use its super class' reconciler frees us from spell checking\n * \t\tmarkup\n * \t. to find fold locations for:\n * \t\t\t. block commments\n * \t\t\t. PlusCal code\n */\npublic class TLAReconcilingStrategy implements IPropertyChangeListener, IReconcilingStrategy, IReconcilingStrategyExtension {\n\n // Per BoxedCommentHandler, a delimiter is \"(\" followed by three \"*\", then 0-N \"*\", and finally suffixed with \")\"\n private static final String BLOCK_COMMENT_DELIMITER_REGEX = \"^[ \\\\t]*\\\\(\\\\*{3}\\\\**\\\\)\\\\s*$\";\n\n private static final String SINGLE_LINE_COMMENT = \"^[ \\\\t]*\\\\\\\\\\\\*\";\n\n private static final String PCAL_TRANSLATION_PREFIX_REGEX = \"^\\\\\\\\\\\\*+ BEGIN TRANSLATION.*$\";\n\n private static final String PCAL_TRANSLATION_SUFFIX_REGEX = \"^\\\\\\\\\\\\*+ END TRANSLATION.*$\";\n\n private IDocument document;\n\n /* the currently displayed projection annotations */\n protected final List currentAnnotations;\n\n /* the editor we're bound to */\n private TLAEditor editor;\n\n /* the underlying source viewer */\n private ProjectionViewer projectionViewer;\n\n private final AtomicBoolean foldBlockComments;\n\n private final AtomicBoolean foldPlusCalAlgorithm;\n\n private final AtomicBoolean foldTranslatedPlusCalBlock;\n\n public TLAReconcilingStrategy() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.addPropertyChangeListener(this);\n currentAnnotations = new ArrayList<>();\n foldBlockComments = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS));\n foldPlusCalAlgorithm = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM));\n foldTranslatedPlusCalBlock = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED));\n }\n\n public void dispose() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.removePropertyChangeListener(this);\n }\n\n @Override\n public void propertyChange(final PropertyChangeEvent event) {\n final boolean reconcile;\n if (IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS.equals(event.getProperty())) {\n foldBlockComments.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM.equals(event.getProperty())) {\n foldPlusCalAlgorithm.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED.equals(event.getProperty())) {\n foldTranslatedPlusCalBlock.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else {\n reconcile = false;\n }\n if (reconcile) {\n reconcile(null, null, null);\n }\n }\n\n @Override\n public void reconcile(final IRegion partition) {\n reconcile(partition, null, null);\n }\n\n @Override\n public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {\n reconcile(null, dirtyRegion, subRegion);\n }\n\n @Override\n public void setDocument(final IDocument id) {\n document = id;\n }\n\n @Override\n public void initialReconcile() {\n reconcile(null, null, null);\n }\n\n @Override\n public void setProgressMonitor(final IProgressMonitor monitor) {\n }\n\n /**\n * Sets the editor to which we're bound; this is required for communicating folding projections.\n *\n * @param editor\n */\n public void setEditor(final TLAEditor tlaEditor) {\n editor = tlaEditor;\n }\n\n /**\n * Sets the projection viewer for which we're reconciling.\n *\n * @param viewer\n */\n public void setProjectionViewer(final ProjectionViewer viewer) {\n projectionViewer = viewer;\n projectionViewer.setData(getClass().toString(), this);\n }\n\n private void reconcile(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n if (editor != null) {\n final HashMap regionMap = determineFoldingRegions(partition, dirtyRegion, subRegion);\n final Annotation[] deletions;\n final HashMap regionsToAdd = new HashMap<>();\n synchronized (currentAnnotations) {\n for (final Map.Entry me : regionMap.entrySet()) {\n if (!currentAnnotations.remove(me.getKey())) {\n regionsToAdd.put(me.getKey(), me.getValue());\n }\n }\n deletions = currentAnnotations.toArray(new Annotation[currentAnnotations.size()]);\n currentAnnotations.clear();\n currentAnnotations.addAll(regionMap.keySet());\n }\n PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\n\n public void run() {\n editor.modifyProjectionAnnotations(deletions, regionsToAdd);\n if (projectionViewer != null) {\n final ProjectionAnnotationModel model = projectionViewer.getProjectionAnnotationModel();\n final boolean block = foldBlockComments.get();\n final boolean pcal = foldPlusCalAlgorithm.get();\n final boolean translated = foldTranslatedPlusCalBlock.get();\n // We could do even more optimization than this, but this is better than none.\n if (block || pcal || translated) {\n for (final TLCProjectionAnnotation annotation : currentAnnotations) {\n final boolean collapse;\n switch(annotation.getTLCType()) {\n case BLOCK_COMMENT:\n collapse = block;\n break;\n case PCAL_BLOCK:\n collapse = pcal;\n break;\n default:\n collapse = translated;\n }\n if (collapse) {\n model.collapse(annotation);\n }\n }\n }\n }\n }\n });\n }\n }\n\n /**\n * Once upon a time (the original version of this,) document partitioning was performed via\n * \t{@link IDocumentExtension3#computePartitioning(String, int, int, boolean)} and it did a\n * \tterrible job. Now, instead, we're using the Eclipse {@link FindReplaceDocumentAdapter} class.\n */\n private HashMap determineFoldingRegions(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n // TODO use regions for tracking in optimizations on re-parses\n final HashMap additions = new HashMap<>();\n final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(document);\n // PCal location\n try {\n IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);\n if (find == null) {\n find = search.find(0, \"--\" + IPCalReservedWords.FAIR, true, true, false, false);\n }\n if (find != null) {\n final int pcalStartLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\(\\\\*\", false, true, false, true);\n if (find != null) {\n final int startLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\s?\\\\*+\\\\)$\", true, true, false, true);\n addProjectionAdditionToMap(additions, startLocation, find, AnnotationType.PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Translated PCal location\n try {\n IRegion find = search.find(0, PCAL_TRANSLATION_PREFIX_REGEX, true, true, false, true);\n if (find != null) {\n final int translationStartLocation = find.getOffset();\n find = search.find(translationStartLocation, PCAL_TRANSLATION_SUFFIX_REGEX, true, true, false, true);\n if (find != null) {\n addProjectionAdditionToMap(additions, translationStartLocation, find, AnnotationType.TRANSLATED_PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Block comment locations\n try {\n boolean inBlock = false;\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n while (find != null) {\n if (inBlock) {\n addProjectionAdditionToMap(additions, lastFoundIndex, find, AnnotationType.BLOCK_COMMENT);\n }\n inBlock = !inBlock;\n lastFoundIndex = find.getOffset();\n find = search.find((lastFoundIndex + find.getLength()), BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n }\n } catch (final BadLocationException ble) {\n }\n // 2 or more consecutive single line comments\n try {\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, SINGLE_LINE_COMMENT, true, true, false, true);\n int contiguousLineCount = 1;\n int firstMatchingOffset = -1;\n while (find != null) {\n if (firstMatchingOffset == -1) {\n firstMatchingOffset = find.getOffset();\n }\n lastFoundIndex = find.getOffset();\n final IRegion lineEnding = search.find((lastFoundIndex + find.getLength()), \"\\\\n\", true, true, false, true);\n if (lineEnding != null) {\n lastFoundIndex = lineEnding.getOffset();\n find = search.find((lastFoundIndex + 1), SINGLE_LINE_COMMENT, true, true, false, true);\n } else {\n // In this case the document has ended without a newline (but with a comment)\n lastFoundIndex += find.getLength();\n find = null;\n }\n boolean addProjection = (contiguousLineCount > 1);\n boolean reset = true;\n if ((find != null) && (find.getOffset() == (lastFoundIndex + 1))) {\n contiguousLineCount++;\n addProjection = false;\n reset = false;\n }\n if (addProjection) {\n addProjectionAdditionToMap(additions, firstMatchingOffset, lastFoundIndex, AnnotationType.MULTIPLE_SINGLE_LINE_COMMENT);\n }\n if (reset) {\n contiguousLineCount = 1;\n firstMatchingOffset = -1;\n }\n }\n } catch (final BadLocationException ble) {\n }\n return additions;\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final IRegion find, final AnnotationType type) throws BadLocationException {\n if (find != null) {\n final int endLocation = find.getOffset() + find.getLength() + 1;\n addProjectionAdditionToMap(additions, startLocation, endLocation, type);\n }\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final int endLocation, final AnnotationType type) throws BadLocationException {\n final int length = endLocation - startLocation;\n // +1 to cover the newline\n final int positionLength = length + ((document.getLength() > endLocation) ? 1 : 0);\n final Position position = new Position(startLocation, positionLength);\n additions.put(new TLCProjectionAnnotation(document.get(startLocation, length), type), position);\n }\n\n private enum AnnotationType {\n\n BLOCK_COMMENT, MULTIPLE_SINGLE_LINE_COMMENT, PCAL_BLOCK, TRANSLATED_PCAL_BLOCK\n }\n\n // Nothing in the ProjectionAnnotation hierarchy implements equals/hashCode, we'd like such things to exist\n // for reconciliation; also we denote classifications of annotations for folding groups.\n private static class TLCProjectionAnnotation extends ProjectionAnnotation {\n\n private final AnnotationType type;\n\n TLCProjectionAnnotation(final String text, final AnnotationType annotationType) {\n setText(text);\n type = annotationType;\n }\n\n AnnotationType getTLCType() ", "post_mask_code": "\n\n @Override\n public boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n if (!Annotation.class.isAssignableFrom(other.getClass())) {\n return false;\n }\n final Annotation otherAnnotation = (Annotation) other;\n final String otherText = otherAnnotation.getText();\n return Objects.equals(getText(), otherText);\n }\n\n @Override\n public int hashCode() {\n final String text = getText();\n if (text == null) {\n return 0;\n }\n return text.hashCode();\n }\n }\n}\n"} {"task_id": "Java_1091", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/tlaplus/tlaplus/toolbox/org.lamport.tla.toolbox.editor.basic/src/org/lamport/tla/toolbox/editor/basic/TLAReconcilingStrategy.java", "mask_start_position": 8610, "mask_end_position": 8884, "canonical_solution": "\n // TODO use regions for tracking in optimizations on re-parses\n final HashMap additions = new HashMap<>();\n final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(document);\n // PCal location", "pre_mask_code": "package org.lamport.tla.toolbox.editor.basic;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.FindReplaceDocumentAdapter;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.IDocumentExtension3;\nimport org.eclipse.jface.text.IRegion;\nimport org.eclipse.jface.text.Position;\nimport org.eclipse.jface.text.reconciler.DirtyRegion;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategy;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;\nimport org.eclipse.jface.text.source.Annotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;\nimport org.eclipse.jface.text.source.projection.ProjectionViewer;\nimport org.eclipse.jface.util.IPropertyChangeListener;\nimport org.eclipse.jface.util.PropertyChangeEvent;\nimport org.eclipse.ui.PlatformUI;\nimport org.lamport.tla.toolbox.editor.basic.pcal.IPCalReservedWords;\nimport org.lamport.tla.toolbox.util.pref.IPreferenceConstants;\nimport org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;\n\n/**\n * We create this reconciling strategy for at least two reasons:\n * \t. having our custom source viewer configuration not use its super class' reconciler frees us from spell checking\n * \t\tmarkup\n * \t. to find fold locations for:\n * \t\t\t. block commments\n * \t\t\t. PlusCal code\n */\npublic class TLAReconcilingStrategy implements IPropertyChangeListener, IReconcilingStrategy, IReconcilingStrategyExtension {\n\n // Per BoxedCommentHandler, a delimiter is \"(\" followed by three \"*\", then 0-N \"*\", and finally suffixed with \")\"\n private static final String BLOCK_COMMENT_DELIMITER_REGEX = \"^[ \\\\t]*\\\\(\\\\*{3}\\\\**\\\\)\\\\s*$\";\n\n private static final String SINGLE_LINE_COMMENT = \"^[ \\\\t]*\\\\\\\\\\\\*\";\n\n private static final String PCAL_TRANSLATION_PREFIX_REGEX = \"^\\\\\\\\\\\\*+ BEGIN TRANSLATION.*$\";\n\n private static final String PCAL_TRANSLATION_SUFFIX_REGEX = \"^\\\\\\\\\\\\*+ END TRANSLATION.*$\";\n\n private IDocument document;\n\n /* the currently displayed projection annotations */\n protected final List currentAnnotations;\n\n /* the editor we're bound to */\n private TLAEditor editor;\n\n /* the underlying source viewer */\n private ProjectionViewer projectionViewer;\n\n private final AtomicBoolean foldBlockComments;\n\n private final AtomicBoolean foldPlusCalAlgorithm;\n\n private final AtomicBoolean foldTranslatedPlusCalBlock;\n\n public TLAReconcilingStrategy() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.addPropertyChangeListener(this);\n currentAnnotations = new ArrayList<>();\n foldBlockComments = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS));\n foldPlusCalAlgorithm = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM));\n foldTranslatedPlusCalBlock = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED));\n }\n\n public void dispose() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.removePropertyChangeListener(this);\n }\n\n @Override\n public void propertyChange(final PropertyChangeEvent event) {\n final boolean reconcile;\n if (IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS.equals(event.getProperty())) {\n foldBlockComments.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM.equals(event.getProperty())) {\n foldPlusCalAlgorithm.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED.equals(event.getProperty())) {\n foldTranslatedPlusCalBlock.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else {\n reconcile = false;\n }\n if (reconcile) {\n reconcile(null, null, null);\n }\n }\n\n @Override\n public void reconcile(final IRegion partition) {\n reconcile(partition, null, null);\n }\n\n @Override\n public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {\n reconcile(null, dirtyRegion, subRegion);\n }\n\n @Override\n public void setDocument(final IDocument id) {\n document = id;\n }\n\n @Override\n public void initialReconcile() {\n reconcile(null, null, null);\n }\n\n @Override\n public void setProgressMonitor(final IProgressMonitor monitor) {\n }\n\n /**\n * Sets the editor to which we're bound; this is required for communicating folding projections.\n *\n * @param editor\n */\n public void setEditor(final TLAEditor tlaEditor) {\n editor = tlaEditor;\n }\n\n /**\n * Sets the projection viewer for which we're reconciling.\n *\n * @param viewer\n */\n public void setProjectionViewer(final ProjectionViewer viewer) {\n projectionViewer = viewer;\n projectionViewer.setData(getClass().toString(), this);\n }\n\n private void reconcile(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n if (editor != null) {\n final HashMap regionMap = determineFoldingRegions(partition, dirtyRegion, subRegion);\n final Annotation[] deletions;\n final HashMap regionsToAdd = new HashMap<>();\n synchronized (currentAnnotations) {\n for (final Map.Entry me : regionMap.entrySet()) {\n if (!currentAnnotations.remove(me.getKey())) {\n regionsToAdd.put(me.getKey(), me.getValue());\n }\n }\n deletions = currentAnnotations.toArray(new Annotation[currentAnnotations.size()]);\n currentAnnotations.clear();\n currentAnnotations.addAll(regionMap.keySet());\n }\n PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\n\n public void run() {\n editor.modifyProjectionAnnotations(deletions, regionsToAdd);\n if (projectionViewer != null) {\n final ProjectionAnnotationModel model = projectionViewer.getProjectionAnnotationModel();\n final boolean block = foldBlockComments.get();\n final boolean pcal = foldPlusCalAlgorithm.get();\n final boolean translated = foldTranslatedPlusCalBlock.get();\n // We could do even more optimization than this, but this is better than none.\n if (block || pcal || translated) {\n for (final TLCProjectionAnnotation annotation : currentAnnotations) {\n final boolean collapse;\n switch(annotation.getTLCType()) {\n case BLOCK_COMMENT:\n collapse = block;\n break;\n case PCAL_BLOCK:\n collapse = pcal;\n break;\n default:\n collapse = translated;\n }\n if (collapse) {\n model.collapse(annotation);\n }\n }\n }\n }\n }\n });\n }\n }\n\n /**\n * Once upon a time (the original version of this,) document partitioning was performed via\n * \t{@link IDocumentExtension3#computePartitioning(String, int, int, boolean)} and it did a\n * \tterrible job. Now, instead, we're using the Eclipse {@link FindReplaceDocumentAdapter} class.\n */\n private HashMap determineFoldingRegions(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {", "post_mask_code": "\n try {\n IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);\n if (find == null) {\n find = search.find(0, \"--\" + IPCalReservedWords.FAIR, true, true, false, false);\n }\n if (find != null) {\n final int pcalStartLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\(\\\\*\", false, true, false, true);\n if (find != null) {\n final int startLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\s?\\\\*+\\\\)$\", true, true, false, true);\n addProjectionAdditionToMap(additions, startLocation, find, AnnotationType.PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Translated PCal location\n try {\n IRegion find = search.find(0, PCAL_TRANSLATION_PREFIX_REGEX, true, true, false, true);\n if (find != null) {\n final int translationStartLocation = find.getOffset();\n find = search.find(translationStartLocation, PCAL_TRANSLATION_SUFFIX_REGEX, true, true, false, true);\n if (find != null) {\n addProjectionAdditionToMap(additions, translationStartLocation, find, AnnotationType.TRANSLATED_PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Block comment locations\n try {\n boolean inBlock = false;\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n while (find != null) {\n if (inBlock) {\n addProjectionAdditionToMap(additions, lastFoundIndex, find, AnnotationType.BLOCK_COMMENT);\n }\n inBlock = !inBlock;\n lastFoundIndex = find.getOffset();\n find = search.find((lastFoundIndex + find.getLength()), BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n }\n } catch (final BadLocationException ble) {\n }\n // 2 or more consecutive single line comments\n try {\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, SINGLE_LINE_COMMENT, true, true, false, true);\n int contiguousLineCount = 1;\n int firstMatchingOffset = -1;\n while (find != null) {\n if (firstMatchingOffset == -1) {\n firstMatchingOffset = find.getOffset();\n }\n lastFoundIndex = find.getOffset();\n final IRegion lineEnding = search.find((lastFoundIndex + find.getLength()), \"\\\\n\", true, true, false, true);\n if (lineEnding != null) {\n lastFoundIndex = lineEnding.getOffset();\n find = search.find((lastFoundIndex + 1), SINGLE_LINE_COMMENT, true, true, false, true);\n } else {\n // In this case the document has ended without a newline (but with a comment)\n lastFoundIndex += find.getLength();\n find = null;\n }\n boolean addProjection = (contiguousLineCount > 1);\n boolean reset = true;\n if ((find != null) && (find.getOffset() == (lastFoundIndex + 1))) {\n contiguousLineCount++;\n addProjection = false;\n reset = false;\n }\n if (addProjection) {\n addProjectionAdditionToMap(additions, firstMatchingOffset, lastFoundIndex, AnnotationType.MULTIPLE_SINGLE_LINE_COMMENT);\n }\n if (reset) {\n contiguousLineCount = 1;\n firstMatchingOffset = -1;\n }\n }\n } catch (final BadLocationException ble) {\n }\n return additions;\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final IRegion find, final AnnotationType type) throws BadLocationException {\n if (find != null) {\n final int endLocation = find.getOffset() + find.getLength() + 1;\n addProjectionAdditionToMap(additions, startLocation, endLocation, type);\n }\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final int endLocation, final AnnotationType type) throws BadLocationException {\n final int length = endLocation - startLocation;\n // +1 to cover the newline\n final int positionLength = length + ((document.getLength() > endLocation) ? 1 : 0);\n final Position position = new Position(startLocation, positionLength);\n additions.put(new TLCProjectionAnnotation(document.get(startLocation, length), type), position);\n }\n\n private enum AnnotationType {\n\n BLOCK_COMMENT, MULTIPLE_SINGLE_LINE_COMMENT, PCAL_BLOCK, TRANSLATED_PCAL_BLOCK\n }\n\n // Nothing in the ProjectionAnnotation hierarchy implements equals/hashCode, we'd like such things to exist\n // for reconciliation; also we denote classifications of annotations for folding groups.\n private static class TLCProjectionAnnotation extends ProjectionAnnotation {\n\n private final AnnotationType type;\n\n TLCProjectionAnnotation(final String text, final AnnotationType annotationType) {\n setText(text);\n type = annotationType;\n }\n\n AnnotationType getTLCType() {\n return type;\n }\n\n @Override\n public boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n if (!Annotation.class.isAssignableFrom(other.getClass())) {\n return false;\n }\n final Annotation otherAnnotation = (Annotation) other;\n final String otherText = otherAnnotation.getText();\n return Objects.equals(getText(), otherText);\n }\n\n @Override\n public int hashCode() {\n final String text = getText();\n if (text == null) {\n return 0;\n }\n return text.hashCode();\n }\n }\n}\n"} {"task_id": "Java_1092", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/tlaplus/tlaplus/toolbox/org.lamport.tla.toolbox.editor.basic/src/org/lamport/tla/toolbox/editor/basic/TLAReconcilingStrategy.java", "mask_start_position": 8893, "mask_end_position": 10392, "canonical_solution": "try {\n IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);\n if (find == null) {\n find = search.find(0, \"--\" + IPCalReservedWords.FAIR, true, true, false, false);\n }\n if (find != null) {\n final int pcalStartLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\(\\\\*\", false, true, false, true);\n if (find != null) {\n final int startLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\s?\\\\*+\\\\)$\", true, true, false, true);\n addProjectionAdditionToMap(additions, startLocation, find, AnnotationType.PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Translated PCal location\n try {\n IRegion find = search.find(0, PCAL_TRANSLATION_PREFIX_REGEX, true, true, false, true);\n if (find != null) {\n final int translationStartLocation = find.getOffset();\n find = search.find(translationStartLocation, PCAL_TRANSLATION_SUFFIX_REGEX, true, true, false, true);\n if (find != null) {\n addProjectionAdditionToMap(additions, translationStartLocation, find, AnnotationType.TRANSLATED_PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Block comment locations", "pre_mask_code": "package org.lamport.tla.toolbox.editor.basic;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.FindReplaceDocumentAdapter;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.IDocumentExtension3;\nimport org.eclipse.jface.text.IRegion;\nimport org.eclipse.jface.text.Position;\nimport org.eclipse.jface.text.reconciler.DirtyRegion;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategy;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;\nimport org.eclipse.jface.text.source.Annotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;\nimport org.eclipse.jface.text.source.projection.ProjectionViewer;\nimport org.eclipse.jface.util.IPropertyChangeListener;\nimport org.eclipse.jface.util.PropertyChangeEvent;\nimport org.eclipse.ui.PlatformUI;\nimport org.lamport.tla.toolbox.editor.basic.pcal.IPCalReservedWords;\nimport org.lamport.tla.toolbox.util.pref.IPreferenceConstants;\nimport org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;\n\n/**\n * We create this reconciling strategy for at least two reasons:\n * \t. having our custom source viewer configuration not use its super class' reconciler frees us from spell checking\n * \t\tmarkup\n * \t. to find fold locations for:\n * \t\t\t. block commments\n * \t\t\t. PlusCal code\n */\npublic class TLAReconcilingStrategy implements IPropertyChangeListener, IReconcilingStrategy, IReconcilingStrategyExtension {\n\n // Per BoxedCommentHandler, a delimiter is \"(\" followed by three \"*\", then 0-N \"*\", and finally suffixed with \")\"\n private static final String BLOCK_COMMENT_DELIMITER_REGEX = \"^[ \\\\t]*\\\\(\\\\*{3}\\\\**\\\\)\\\\s*$\";\n\n private static final String SINGLE_LINE_COMMENT = \"^[ \\\\t]*\\\\\\\\\\\\*\";\n\n private static final String PCAL_TRANSLATION_PREFIX_REGEX = \"^\\\\\\\\\\\\*+ BEGIN TRANSLATION.*$\";\n\n private static final String PCAL_TRANSLATION_SUFFIX_REGEX = \"^\\\\\\\\\\\\*+ END TRANSLATION.*$\";\n\n private IDocument document;\n\n /* the currently displayed projection annotations */\n protected final List currentAnnotations;\n\n /* the editor we're bound to */\n private TLAEditor editor;\n\n /* the underlying source viewer */\n private ProjectionViewer projectionViewer;\n\n private final AtomicBoolean foldBlockComments;\n\n private final AtomicBoolean foldPlusCalAlgorithm;\n\n private final AtomicBoolean foldTranslatedPlusCalBlock;\n\n public TLAReconcilingStrategy() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.addPropertyChangeListener(this);\n currentAnnotations = new ArrayList<>();\n foldBlockComments = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS));\n foldPlusCalAlgorithm = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM));\n foldTranslatedPlusCalBlock = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED));\n }\n\n public void dispose() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.removePropertyChangeListener(this);\n }\n\n @Override\n public void propertyChange(final PropertyChangeEvent event) {\n final boolean reconcile;\n if (IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS.equals(event.getProperty())) {\n foldBlockComments.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM.equals(event.getProperty())) {\n foldPlusCalAlgorithm.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED.equals(event.getProperty())) {\n foldTranslatedPlusCalBlock.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else {\n reconcile = false;\n }\n if (reconcile) {\n reconcile(null, null, null);\n }\n }\n\n @Override\n public void reconcile(final IRegion partition) {\n reconcile(partition, null, null);\n }\n\n @Override\n public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {\n reconcile(null, dirtyRegion, subRegion);\n }\n\n @Override\n public void setDocument(final IDocument id) {\n document = id;\n }\n\n @Override\n public void initialReconcile() {\n reconcile(null, null, null);\n }\n\n @Override\n public void setProgressMonitor(final IProgressMonitor monitor) {\n }\n\n /**\n * Sets the editor to which we're bound; this is required for communicating folding projections.\n *\n * @param editor\n */\n public void setEditor(final TLAEditor tlaEditor) {\n editor = tlaEditor;\n }\n\n /**\n * Sets the projection viewer for which we're reconciling.\n *\n * @param viewer\n */\n public void setProjectionViewer(final ProjectionViewer viewer) {\n projectionViewer = viewer;\n projectionViewer.setData(getClass().toString(), this);\n }\n\n private void reconcile(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n if (editor != null) {\n final HashMap regionMap = determineFoldingRegions(partition, dirtyRegion, subRegion);\n final Annotation[] deletions;\n final HashMap regionsToAdd = new HashMap<>();\n synchronized (currentAnnotations) {\n for (final Map.Entry me : regionMap.entrySet()) {\n if (!currentAnnotations.remove(me.getKey())) {\n regionsToAdd.put(me.getKey(), me.getValue());\n }\n }\n deletions = currentAnnotations.toArray(new Annotation[currentAnnotations.size()]);\n currentAnnotations.clear();\n currentAnnotations.addAll(regionMap.keySet());\n }\n PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\n\n public void run() {\n editor.modifyProjectionAnnotations(deletions, regionsToAdd);\n if (projectionViewer != null) {\n final ProjectionAnnotationModel model = projectionViewer.getProjectionAnnotationModel();\n final boolean block = foldBlockComments.get();\n final boolean pcal = foldPlusCalAlgorithm.get();\n final boolean translated = foldTranslatedPlusCalBlock.get();\n // We could do even more optimization than this, but this is better than none.\n if (block || pcal || translated) {\n for (final TLCProjectionAnnotation annotation : currentAnnotations) {\n final boolean collapse;\n switch(annotation.getTLCType()) {\n case BLOCK_COMMENT:\n collapse = block;\n break;\n case PCAL_BLOCK:\n collapse = pcal;\n break;\n default:\n collapse = translated;\n }\n if (collapse) {\n model.collapse(annotation);\n }\n }\n }\n }\n }\n });\n }\n }\n\n /**\n * Once upon a time (the original version of this,) document partitioning was performed via\n * \t{@link IDocumentExtension3#computePartitioning(String, int, int, boolean)} and it did a\n * \tterrible job. Now, instead, we're using the Eclipse {@link FindReplaceDocumentAdapter} class.\n */\n private HashMap determineFoldingRegions(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n // TODO use regions for tracking in optimizations on re-parses\n final HashMap additions = new HashMap<>();\n final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(document);\n // PCal location\n ", "post_mask_code": "\n try {\n boolean inBlock = false;\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n while (find != null) {\n if (inBlock) {\n addProjectionAdditionToMap(additions, lastFoundIndex, find, AnnotationType.BLOCK_COMMENT);\n }\n inBlock = !inBlock;\n lastFoundIndex = find.getOffset();\n find = search.find((lastFoundIndex + find.getLength()), BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n }\n } catch (final BadLocationException ble) {\n }\n // 2 or more consecutive single line comments\n try {\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, SINGLE_LINE_COMMENT, true, true, false, true);\n int contiguousLineCount = 1;\n int firstMatchingOffset = -1;\n while (find != null) {\n if (firstMatchingOffset == -1) {\n firstMatchingOffset = find.getOffset();\n }\n lastFoundIndex = find.getOffset();\n final IRegion lineEnding = search.find((lastFoundIndex + find.getLength()), \"\\\\n\", true, true, false, true);\n if (lineEnding != null) {\n lastFoundIndex = lineEnding.getOffset();\n find = search.find((lastFoundIndex + 1), SINGLE_LINE_COMMENT, true, true, false, true);\n } else {\n // In this case the document has ended without a newline (but with a comment)\n lastFoundIndex += find.getLength();\n find = null;\n }\n boolean addProjection = (contiguousLineCount > 1);\n boolean reset = true;\n if ((find != null) && (find.getOffset() == (lastFoundIndex + 1))) {\n contiguousLineCount++;\n addProjection = false;\n reset = false;\n }\n if (addProjection) {\n addProjectionAdditionToMap(additions, firstMatchingOffset, lastFoundIndex, AnnotationType.MULTIPLE_SINGLE_LINE_COMMENT);\n }\n if (reset) {\n contiguousLineCount = 1;\n firstMatchingOffset = -1;\n }\n }\n } catch (final BadLocationException ble) {\n }\n return additions;\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final IRegion find, final AnnotationType type) throws BadLocationException {\n if (find != null) {\n final int endLocation = find.getOffset() + find.getLength() + 1;\n addProjectionAdditionToMap(additions, startLocation, endLocation, type);\n }\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final int endLocation, final AnnotationType type) throws BadLocationException {\n final int length = endLocation - startLocation;\n // +1 to cover the newline\n final int positionLength = length + ((document.getLength() > endLocation) ? 1 : 0);\n final Position position = new Position(startLocation, positionLength);\n additions.put(new TLCProjectionAnnotation(document.get(startLocation, length), type), position);\n }\n\n private enum AnnotationType {\n\n BLOCK_COMMENT, MULTIPLE_SINGLE_LINE_COMMENT, PCAL_BLOCK, TRANSLATED_PCAL_BLOCK\n }\n\n // Nothing in the ProjectionAnnotation hierarchy implements equals/hashCode, we'd like such things to exist\n // for reconciliation; also we denote classifications of annotations for folding groups.\n private static class TLCProjectionAnnotation extends ProjectionAnnotation {\n\n private final AnnotationType type;\n\n TLCProjectionAnnotation(final String text, final AnnotationType annotationType) {\n setText(text);\n type = annotationType;\n }\n\n AnnotationType getTLCType() {\n return type;\n }\n\n @Override\n public boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n if (!Annotation.class.isAssignableFrom(other.getClass())) {\n return false;\n }\n final Annotation otherAnnotation = (Annotation) other;\n final String otherText = otherAnnotation.getText();\n return Objects.equals(getText(), otherText);\n }\n\n @Override\n public int hashCode() {\n final String text = getText();\n if (text == null) {\n return 0;\n }\n return text.hashCode();\n }\n }\n}\n"} {"task_id": "Java_1093", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/tlaplus/tlaplus/toolbox/org.lamport.tla.toolbox.editor.basic/src/org/lamport/tla/toolbox/editor/basic/TLAReconcilingStrategy.java", "mask_start_position": 10401, "mask_end_position": 13066, "canonical_solution": "try {\n boolean inBlock = false;\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n while (find != null) {\n if (inBlock) {\n addProjectionAdditionToMap(additions, lastFoundIndex, find, AnnotationType.BLOCK_COMMENT);\n }\n inBlock = !inBlock;\n lastFoundIndex = find.getOffset();\n find = search.find((lastFoundIndex + find.getLength()), BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n }\n } catch (final BadLocationException ble) {\n }\n // 2 or more consecutive single line comments\n try {\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, SINGLE_LINE_COMMENT, true, true, false, true);\n int contiguousLineCount = 1;\n int firstMatchingOffset = -1;\n while (find != null) {\n if (firstMatchingOffset == -1) {\n firstMatchingOffset = find.getOffset();\n }\n lastFoundIndex = find.getOffset();\n final IRegion lineEnding = search.find((lastFoundIndex + find.getLength()), \"\\\\n\", true, true, false, true);\n if (lineEnding != null) {\n lastFoundIndex = lineEnding.getOffset();\n find = search.find((lastFoundIndex + 1), SINGLE_LINE_COMMENT, true, true, false, true);\n } else {\n // In this case the document has ended without a newline (but with a comment)\n lastFoundIndex += find.getLength();\n find = null;\n }\n boolean addProjection = (contiguousLineCount > 1);\n boolean reset = true;\n if ((find != null) && (find.getOffset() == (lastFoundIndex + 1))) {\n contiguousLineCount++;\n addProjection = false;\n reset = false;\n }\n if (addProjection) {\n addProjectionAdditionToMap(additions, firstMatchingOffset, lastFoundIndex, AnnotationType.MULTIPLE_SINGLE_LINE_COMMENT);\n }\n if (reset) {\n contiguousLineCount = 1;\n firstMatchingOffset = -1;\n }\n }\n } catch (final BadLocationException ble) {\n }\n return additions;\n }", "pre_mask_code": "package org.lamport.tla.toolbox.editor.basic;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.FindReplaceDocumentAdapter;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.IDocumentExtension3;\nimport org.eclipse.jface.text.IRegion;\nimport org.eclipse.jface.text.Position;\nimport org.eclipse.jface.text.reconciler.DirtyRegion;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategy;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;\nimport org.eclipse.jface.text.source.Annotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;\nimport org.eclipse.jface.text.source.projection.ProjectionViewer;\nimport org.eclipse.jface.util.IPropertyChangeListener;\nimport org.eclipse.jface.util.PropertyChangeEvent;\nimport org.eclipse.ui.PlatformUI;\nimport org.lamport.tla.toolbox.editor.basic.pcal.IPCalReservedWords;\nimport org.lamport.tla.toolbox.util.pref.IPreferenceConstants;\nimport org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;\n\n/**\n * We create this reconciling strategy for at least two reasons:\n * \t. having our custom source viewer configuration not use its super class' reconciler frees us from spell checking\n * \t\tmarkup\n * \t. to find fold locations for:\n * \t\t\t. block commments\n * \t\t\t. PlusCal code\n */\npublic class TLAReconcilingStrategy implements IPropertyChangeListener, IReconcilingStrategy, IReconcilingStrategyExtension {\n\n // Per BoxedCommentHandler, a delimiter is \"(\" followed by three \"*\", then 0-N \"*\", and finally suffixed with \")\"\n private static final String BLOCK_COMMENT_DELIMITER_REGEX = \"^[ \\\\t]*\\\\(\\\\*{3}\\\\**\\\\)\\\\s*$\";\n\n private static final String SINGLE_LINE_COMMENT = \"^[ \\\\t]*\\\\\\\\\\\\*\";\n\n private static final String PCAL_TRANSLATION_PREFIX_REGEX = \"^\\\\\\\\\\\\*+ BEGIN TRANSLATION.*$\";\n\n private static final String PCAL_TRANSLATION_SUFFIX_REGEX = \"^\\\\\\\\\\\\*+ END TRANSLATION.*$\";\n\n private IDocument document;\n\n /* the currently displayed projection annotations */\n protected final List currentAnnotations;\n\n /* the editor we're bound to */\n private TLAEditor editor;\n\n /* the underlying source viewer */\n private ProjectionViewer projectionViewer;\n\n private final AtomicBoolean foldBlockComments;\n\n private final AtomicBoolean foldPlusCalAlgorithm;\n\n private final AtomicBoolean foldTranslatedPlusCalBlock;\n\n public TLAReconcilingStrategy() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.addPropertyChangeListener(this);\n currentAnnotations = new ArrayList<>();\n foldBlockComments = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS));\n foldPlusCalAlgorithm = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM));\n foldTranslatedPlusCalBlock = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED));\n }\n\n public void dispose() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.removePropertyChangeListener(this);\n }\n\n @Override\n public void propertyChange(final PropertyChangeEvent event) {\n final boolean reconcile;\n if (IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS.equals(event.getProperty())) {\n foldBlockComments.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM.equals(event.getProperty())) {\n foldPlusCalAlgorithm.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED.equals(event.getProperty())) {\n foldTranslatedPlusCalBlock.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else {\n reconcile = false;\n }\n if (reconcile) {\n reconcile(null, null, null);\n }\n }\n\n @Override\n public void reconcile(final IRegion partition) {\n reconcile(partition, null, null);\n }\n\n @Override\n public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {\n reconcile(null, dirtyRegion, subRegion);\n }\n\n @Override\n public void setDocument(final IDocument id) {\n document = id;\n }\n\n @Override\n public void initialReconcile() {\n reconcile(null, null, null);\n }\n\n @Override\n public void setProgressMonitor(final IProgressMonitor monitor) {\n }\n\n /**\n * Sets the editor to which we're bound; this is required for communicating folding projections.\n *\n * @param editor\n */\n public void setEditor(final TLAEditor tlaEditor) {\n editor = tlaEditor;\n }\n\n /**\n * Sets the projection viewer for which we're reconciling.\n *\n * @param viewer\n */\n public void setProjectionViewer(final ProjectionViewer viewer) {\n projectionViewer = viewer;\n projectionViewer.setData(getClass().toString(), this);\n }\n\n private void reconcile(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n if (editor != null) {\n final HashMap regionMap = determineFoldingRegions(partition, dirtyRegion, subRegion);\n final Annotation[] deletions;\n final HashMap regionsToAdd = new HashMap<>();\n synchronized (currentAnnotations) {\n for (final Map.Entry me : regionMap.entrySet()) {\n if (!currentAnnotations.remove(me.getKey())) {\n regionsToAdd.put(me.getKey(), me.getValue());\n }\n }\n deletions = currentAnnotations.toArray(new Annotation[currentAnnotations.size()]);\n currentAnnotations.clear();\n currentAnnotations.addAll(regionMap.keySet());\n }\n PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\n\n public void run() {\n editor.modifyProjectionAnnotations(deletions, regionsToAdd);\n if (projectionViewer != null) {\n final ProjectionAnnotationModel model = projectionViewer.getProjectionAnnotationModel();\n final boolean block = foldBlockComments.get();\n final boolean pcal = foldPlusCalAlgorithm.get();\n final boolean translated = foldTranslatedPlusCalBlock.get();\n // We could do even more optimization than this, but this is better than none.\n if (block || pcal || translated) {\n for (final TLCProjectionAnnotation annotation : currentAnnotations) {\n final boolean collapse;\n switch(annotation.getTLCType()) {\n case BLOCK_COMMENT:\n collapse = block;\n break;\n case PCAL_BLOCK:\n collapse = pcal;\n break;\n default:\n collapse = translated;\n }\n if (collapse) {\n model.collapse(annotation);\n }\n }\n }\n }\n }\n });\n }\n }\n\n /**\n * Once upon a time (the original version of this,) document partitioning was performed via\n * \t{@link IDocumentExtension3#computePartitioning(String, int, int, boolean)} and it did a\n * \tterrible job. Now, instead, we're using the Eclipse {@link FindReplaceDocumentAdapter} class.\n */\n private HashMap determineFoldingRegions(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n // TODO use regions for tracking in optimizations on re-parses\n final HashMap additions = new HashMap<>();\n final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(document);\n // PCal location\n try {\n IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);\n if (find == null) {\n find = search.find(0, \"--\" + IPCalReservedWords.FAIR, true, true, false, false);\n }\n if (find != null) {\n final int pcalStartLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\(\\\\*\", false, true, false, true);\n if (find != null) {\n final int startLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\s?\\\\*+\\\\)$\", true, true, false, true);\n addProjectionAdditionToMap(additions, startLocation, find, AnnotationType.PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Translated PCal location\n try {\n IRegion find = search.find(0, PCAL_TRANSLATION_PREFIX_REGEX, true, true, false, true);\n if (find != null) {\n final int translationStartLocation = find.getOffset();\n find = search.find(translationStartLocation, PCAL_TRANSLATION_SUFFIX_REGEX, true, true, false, true);\n if (find != null) {\n addProjectionAdditionToMap(additions, translationStartLocation, find, AnnotationType.TRANSLATED_PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Block comment locations\n ", "post_mask_code": "\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final IRegion find, final AnnotationType type) throws BadLocationException {\n if (find != null) {\n final int endLocation = find.getOffset() + find.getLength() + 1;\n addProjectionAdditionToMap(additions, startLocation, endLocation, type);\n }\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final int endLocation, final AnnotationType type) throws BadLocationException {\n final int length = endLocation - startLocation;\n // +1 to cover the newline\n final int positionLength = length + ((document.getLength() > endLocation) ? 1 : 0);\n final Position position = new Position(startLocation, positionLength);\n additions.put(new TLCProjectionAnnotation(document.get(startLocation, length), type), position);\n }\n\n private enum AnnotationType {\n\n BLOCK_COMMENT, MULTIPLE_SINGLE_LINE_COMMENT, PCAL_BLOCK, TRANSLATED_PCAL_BLOCK\n }\n\n // Nothing in the ProjectionAnnotation hierarchy implements equals/hashCode, we'd like such things to exist\n // for reconciliation; also we denote classifications of annotations for folding groups.\n private static class TLCProjectionAnnotation extends ProjectionAnnotation {\n\n private final AnnotationType type;\n\n TLCProjectionAnnotation(final String text, final AnnotationType annotationType) {\n setText(text);\n type = annotationType;\n }\n\n AnnotationType getTLCType() {\n return type;\n }\n\n @Override\n public boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n if (!Annotation.class.isAssignableFrom(other.getClass())) {\n return false;\n }\n final Annotation otherAnnotation = (Annotation) other;\n final String otherText = otherAnnotation.getText();\n return Objects.equals(getText(), otherText);\n }\n\n @Override\n public int hashCode() {\n final String text = getText();\n if (text == null) {\n return 0;\n }\n return text.hashCode();\n }\n }\n}\n"} {"task_id": "Java_1094", "language": "Java", "task_type": "single_line", "source_file": "java/github/tlaplus/tlaplus/toolbox/org.lamport.tla.toolbox.editor.basic/src/org/lamport/tla/toolbox/editor/basic/TLAReconcilingStrategy.java", "mask_start_position": 5464, "mask_end_position": 5470, "canonical_solution": "this);", "pre_mask_code": "package org.lamport.tla.toolbox.editor.basic;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.FindReplaceDocumentAdapter;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.IDocumentExtension3;\nimport org.eclipse.jface.text.IRegion;\nimport org.eclipse.jface.text.Position;\nimport org.eclipse.jface.text.reconciler.DirtyRegion;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategy;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;\nimport org.eclipse.jface.text.source.Annotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;\nimport org.eclipse.jface.text.source.projection.ProjectionViewer;\nimport org.eclipse.jface.util.IPropertyChangeListener;\nimport org.eclipse.jface.util.PropertyChangeEvent;\nimport org.eclipse.ui.PlatformUI;\nimport org.lamport.tla.toolbox.editor.basic.pcal.IPCalReservedWords;\nimport org.lamport.tla.toolbox.util.pref.IPreferenceConstants;\nimport org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;\n\n/**\n * We create this reconciling strategy for at least two reasons:\n * \t. having our custom source viewer configuration not use its super class' reconciler frees us from spell checking\n * \t\tmarkup\n * \t. to find fold locations for:\n * \t\t\t. block commments\n * \t\t\t. PlusCal code\n */\npublic class TLAReconcilingStrategy implements IPropertyChangeListener, IReconcilingStrategy, IReconcilingStrategyExtension {\n\n // Per BoxedCommentHandler, a delimiter is \"(\" followed by three \"*\", then 0-N \"*\", and finally suffixed with \")\"\n private static final String BLOCK_COMMENT_DELIMITER_REGEX = \"^[ \\\\t]*\\\\(\\\\*{3}\\\\**\\\\)\\\\s*$\";\n\n private static final String SINGLE_LINE_COMMENT = \"^[ \\\\t]*\\\\\\\\\\\\*\";\n\n private static final String PCAL_TRANSLATION_PREFIX_REGEX = \"^\\\\\\\\\\\\*+ BEGIN TRANSLATION.*$\";\n\n private static final String PCAL_TRANSLATION_SUFFIX_REGEX = \"^\\\\\\\\\\\\*+ END TRANSLATION.*$\";\n\n private IDocument document;\n\n /* the currently displayed projection annotations */\n protected final List currentAnnotations;\n\n /* the editor we're bound to */\n private TLAEditor editor;\n\n /* the underlying source viewer */\n private ProjectionViewer projectionViewer;\n\n private final AtomicBoolean foldBlockComments;\n\n private final AtomicBoolean foldPlusCalAlgorithm;\n\n private final AtomicBoolean foldTranslatedPlusCalBlock;\n\n public TLAReconcilingStrategy() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.addPropertyChangeListener(this);\n currentAnnotations = new ArrayList<>();\n foldBlockComments = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS));\n foldPlusCalAlgorithm = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM));\n foldTranslatedPlusCalBlock = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED));\n }\n\n public void dispose() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.removePropertyChangeListener(this);\n }\n\n @Override\n public void propertyChange(final PropertyChangeEvent event) {\n final boolean reconcile;\n if (IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS.equals(event.getProperty())) {\n foldBlockComments.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM.equals(event.getProperty())) {\n foldPlusCalAlgorithm.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED.equals(event.getProperty())) {\n foldTranslatedPlusCalBlock.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else {\n reconcile = false;\n }\n if (reconcile) {\n reconcile(null, null, null);\n }\n }\n\n @Override\n public void reconcile(final IRegion partition) {\n reconcile(partition, null, null);\n }\n\n @Override\n public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {\n reconcile(null, dirtyRegion, subRegion);\n }\n\n @Override\n public void setDocument(final IDocument id) {\n document = id;\n }\n\n @Override\n public void initialReconcile() {\n reconcile(null, null, null);\n }\n\n @Override\n public void setProgressMonitor(final IProgressMonitor monitor) {\n }\n\n /**\n * Sets the editor to which we're bound; this is required for communicating folding projections.\n *\n * @param editor\n */\n public void setEditor(final TLAEditor tlaEditor) {\n editor = tlaEditor;\n }\n\n /**\n * Sets the projection viewer for which we're reconciling.\n *\n * @param viewer\n */\n public void setProjectionViewer(final ProjectionViewer viewer) {\n projectionViewer = viewer;\n projectionViewer.setData(getClass().toString(), ", "post_mask_code": "\n }\n\n private void reconcile(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n if (editor != null) {\n final HashMap regionMap = determineFoldingRegions(partition, dirtyRegion, subRegion);\n final Annotation[] deletions;\n final HashMap regionsToAdd = new HashMap<>();\n synchronized (currentAnnotations) {\n for (final Map.Entry me : regionMap.entrySet()) {\n if (!currentAnnotations.remove(me.getKey())) {\n regionsToAdd.put(me.getKey(), me.getValue());\n }\n }\n deletions = currentAnnotations.toArray(new Annotation[currentAnnotations.size()]);\n currentAnnotations.clear();\n currentAnnotations.addAll(regionMap.keySet());\n }\n PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\n\n public void run() {\n editor.modifyProjectionAnnotations(deletions, regionsToAdd);\n if (projectionViewer != null) {\n final ProjectionAnnotationModel model = projectionViewer.getProjectionAnnotationModel();\n final boolean block = foldBlockComments.get();\n final boolean pcal = foldPlusCalAlgorithm.get();\n final boolean translated = foldTranslatedPlusCalBlock.get();\n // We could do even more optimization than this, but this is better than none.\n if (block || pcal || translated) {\n for (final TLCProjectionAnnotation annotation : currentAnnotations) {\n final boolean collapse;\n switch(annotation.getTLCType()) {\n case BLOCK_COMMENT:\n collapse = block;\n break;\n case PCAL_BLOCK:\n collapse = pcal;\n break;\n default:\n collapse = translated;\n }\n if (collapse) {\n model.collapse(annotation);\n }\n }\n }\n }\n }\n });\n }\n }\n\n /**\n * Once upon a time (the original version of this,) document partitioning was performed via\n * \t{@link IDocumentExtension3#computePartitioning(String, int, int, boolean)} and it did a\n * \tterrible job. Now, instead, we're using the Eclipse {@link FindReplaceDocumentAdapter} class.\n */\n private HashMap determineFoldingRegions(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n // TODO use regions for tracking in optimizations on re-parses\n final HashMap additions = new HashMap<>();\n final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(document);\n // PCal location\n try {\n IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);\n if (find == null) {\n find = search.find(0, \"--\" + IPCalReservedWords.FAIR, true, true, false, false);\n }\n if (find != null) {\n final int pcalStartLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\(\\\\*\", false, true, false, true);\n if (find != null) {\n final int startLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\s?\\\\*+\\\\)$\", true, true, false, true);\n addProjectionAdditionToMap(additions, startLocation, find, AnnotationType.PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Translated PCal location\n try {\n IRegion find = search.find(0, PCAL_TRANSLATION_PREFIX_REGEX, true, true, false, true);\n if (find != null) {\n final int translationStartLocation = find.getOffset();\n find = search.find(translationStartLocation, PCAL_TRANSLATION_SUFFIX_REGEX, true, true, false, true);\n if (find != null) {\n addProjectionAdditionToMap(additions, translationStartLocation, find, AnnotationType.TRANSLATED_PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Block comment locations\n try {\n boolean inBlock = false;\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n while (find != null) {\n if (inBlock) {\n addProjectionAdditionToMap(additions, lastFoundIndex, find, AnnotationType.BLOCK_COMMENT);\n }\n inBlock = !inBlock;\n lastFoundIndex = find.getOffset();\n find = search.find((lastFoundIndex + find.getLength()), BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n }\n } catch (final BadLocationException ble) {\n }\n // 2 or more consecutive single line comments\n try {\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, SINGLE_LINE_COMMENT, true, true, false, true);\n int contiguousLineCount = 1;\n int firstMatchingOffset = -1;\n while (find != null) {\n if (firstMatchingOffset == -1) {\n firstMatchingOffset = find.getOffset();\n }\n lastFoundIndex = find.getOffset();\n final IRegion lineEnding = search.find((lastFoundIndex + find.getLength()), \"\\\\n\", true, true, false, true);\n if (lineEnding != null) {\n lastFoundIndex = lineEnding.getOffset();\n find = search.find((lastFoundIndex + 1), SINGLE_LINE_COMMENT, true, true, false, true);\n } else {\n // In this case the document has ended without a newline (but with a comment)\n lastFoundIndex += find.getLength();\n find = null;\n }\n boolean addProjection = (contiguousLineCount > 1);\n boolean reset = true;\n if ((find != null) && (find.getOffset() == (lastFoundIndex + 1))) {\n contiguousLineCount++;\n addProjection = false;\n reset = false;\n }\n if (addProjection) {\n addProjectionAdditionToMap(additions, firstMatchingOffset, lastFoundIndex, AnnotationType.MULTIPLE_SINGLE_LINE_COMMENT);\n }\n if (reset) {\n contiguousLineCount = 1;\n firstMatchingOffset = -1;\n }\n }\n } catch (final BadLocationException ble) {\n }\n return additions;\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final IRegion find, final AnnotationType type) throws BadLocationException {\n if (find != null) {\n final int endLocation = find.getOffset() + find.getLength() + 1;\n addProjectionAdditionToMap(additions, startLocation, endLocation, type);\n }\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final int endLocation, final AnnotationType type) throws BadLocationException {\n final int length = endLocation - startLocation;\n // +1 to cover the newline\n final int positionLength = length + ((document.getLength() > endLocation) ? 1 : 0);\n final Position position = new Position(startLocation, positionLength);\n additions.put(new TLCProjectionAnnotation(document.get(startLocation, length), type), position);\n }\n\n private enum AnnotationType {\n\n BLOCK_COMMENT, MULTIPLE_SINGLE_LINE_COMMENT, PCAL_BLOCK, TRANSLATED_PCAL_BLOCK\n }\n\n // Nothing in the ProjectionAnnotation hierarchy implements equals/hashCode, we'd like such things to exist\n // for reconciliation; also we denote classifications of annotations for folding groups.\n private static class TLCProjectionAnnotation extends ProjectionAnnotation {\n\n private final AnnotationType type;\n\n TLCProjectionAnnotation(final String text, final AnnotationType annotationType) {\n setText(text);\n type = annotationType;\n }\n\n AnnotationType getTLCType() {\n return type;\n }\n\n @Override\n public boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n if (!Annotation.class.isAssignableFrom(other.getClass())) {\n return false;\n }\n final Annotation otherAnnotation = (Annotation) other;\n final String otherText = otherAnnotation.getText();\n return Objects.equals(getText(), otherText);\n }\n\n @Override\n public int hashCode() {\n final String text = getText();\n if (text == null) {\n return 0;\n }\n return text.hashCode();\n }\n }\n}\n"} {"task_id": "Java_1095", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/tlaplus/tlaplus/toolbox/org.lamport.tla.toolbox.editor.basic/src/org/lamport/tla/toolbox/editor/basic/TLAReconcilingStrategy.java", "mask_start_position": 5308, "mask_end_position": 5476, "canonical_solution": "public void setProjectionViewer(final ProjectionViewer viewer) {\n projectionViewer = viewer;\n projectionViewer.setData(getClass().toString(), this);\n }", "pre_mask_code": "package org.lamport.tla.toolbox.editor.basic;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.FindReplaceDocumentAdapter;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.IDocumentExtension3;\nimport org.eclipse.jface.text.IRegion;\nimport org.eclipse.jface.text.Position;\nimport org.eclipse.jface.text.reconciler.DirtyRegion;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategy;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;\nimport org.eclipse.jface.text.source.Annotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;\nimport org.eclipse.jface.text.source.projection.ProjectionViewer;\nimport org.eclipse.jface.util.IPropertyChangeListener;\nimport org.eclipse.jface.util.PropertyChangeEvent;\nimport org.eclipse.ui.PlatformUI;\nimport org.lamport.tla.toolbox.editor.basic.pcal.IPCalReservedWords;\nimport org.lamport.tla.toolbox.util.pref.IPreferenceConstants;\nimport org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;\n\n/**\n * We create this reconciling strategy for at least two reasons:\n * \t. having our custom source viewer configuration not use its super class' reconciler frees us from spell checking\n * \t\tmarkup\n * \t. to find fold locations for:\n * \t\t\t. block commments\n * \t\t\t. PlusCal code\n */\npublic class TLAReconcilingStrategy implements IPropertyChangeListener, IReconcilingStrategy, IReconcilingStrategyExtension {\n\n // Per BoxedCommentHandler, a delimiter is \"(\" followed by three \"*\", then 0-N \"*\", and finally suffixed with \")\"\n private static final String BLOCK_COMMENT_DELIMITER_REGEX = \"^[ \\\\t]*\\\\(\\\\*{3}\\\\**\\\\)\\\\s*$\";\n\n private static final String SINGLE_LINE_COMMENT = \"^[ \\\\t]*\\\\\\\\\\\\*\";\n\n private static final String PCAL_TRANSLATION_PREFIX_REGEX = \"^\\\\\\\\\\\\*+ BEGIN TRANSLATION.*$\";\n\n private static final String PCAL_TRANSLATION_SUFFIX_REGEX = \"^\\\\\\\\\\\\*+ END TRANSLATION.*$\";\n\n private IDocument document;\n\n /* the currently displayed projection annotations */\n protected final List currentAnnotations;\n\n /* the editor we're bound to */\n private TLAEditor editor;\n\n /* the underlying source viewer */\n private ProjectionViewer projectionViewer;\n\n private final AtomicBoolean foldBlockComments;\n\n private final AtomicBoolean foldPlusCalAlgorithm;\n\n private final AtomicBoolean foldTranslatedPlusCalBlock;\n\n public TLAReconcilingStrategy() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.addPropertyChangeListener(this);\n currentAnnotations = new ArrayList<>();\n foldBlockComments = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS));\n foldPlusCalAlgorithm = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM));\n foldTranslatedPlusCalBlock = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED));\n }\n\n public void dispose() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.removePropertyChangeListener(this);\n }\n\n @Override\n public void propertyChange(final PropertyChangeEvent event) {\n final boolean reconcile;\n if (IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS.equals(event.getProperty())) {\n foldBlockComments.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM.equals(event.getProperty())) {\n foldPlusCalAlgorithm.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED.equals(event.getProperty())) {\n foldTranslatedPlusCalBlock.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else {\n reconcile = false;\n }\n if (reconcile) {\n reconcile(null, null, null);\n }\n }\n\n @Override\n public void reconcile(final IRegion partition) {\n reconcile(partition, null, null);\n }\n\n @Override\n public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {\n reconcile(null, dirtyRegion, subRegion);\n }\n\n @Override\n public void setDocument(final IDocument id) {\n document = id;\n }\n\n @Override\n public void initialReconcile() {\n reconcile(null, null, null);\n }\n\n @Override\n public void setProgressMonitor(final IProgressMonitor monitor) {\n }\n\n /**\n * Sets the editor to which we're bound; this is required for communicating folding projections.\n *\n * @param editor\n */\n public void setEditor(final TLAEditor tlaEditor) {\n editor = tlaEditor;\n }\n\n /**\n * Sets the projection viewer for which we're reconciling.\n *\n * @param viewer\n */\n ", "post_mask_code": "\n\n private void reconcile(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n if (editor != null) {\n final HashMap regionMap = determineFoldingRegions(partition, dirtyRegion, subRegion);\n final Annotation[] deletions;\n final HashMap regionsToAdd = new HashMap<>();\n synchronized (currentAnnotations) {\n for (final Map.Entry me : regionMap.entrySet()) {\n if (!currentAnnotations.remove(me.getKey())) {\n regionsToAdd.put(me.getKey(), me.getValue());\n }\n }\n deletions = currentAnnotations.toArray(new Annotation[currentAnnotations.size()]);\n currentAnnotations.clear();\n currentAnnotations.addAll(regionMap.keySet());\n }\n PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\n\n public void run() {\n editor.modifyProjectionAnnotations(deletions, regionsToAdd);\n if (projectionViewer != null) {\n final ProjectionAnnotationModel model = projectionViewer.getProjectionAnnotationModel();\n final boolean block = foldBlockComments.get();\n final boolean pcal = foldPlusCalAlgorithm.get();\n final boolean translated = foldTranslatedPlusCalBlock.get();\n // We could do even more optimization than this, but this is better than none.\n if (block || pcal || translated) {\n for (final TLCProjectionAnnotation annotation : currentAnnotations) {\n final boolean collapse;\n switch(annotation.getTLCType()) {\n case BLOCK_COMMENT:\n collapse = block;\n break;\n case PCAL_BLOCK:\n collapse = pcal;\n break;\n default:\n collapse = translated;\n }\n if (collapse) {\n model.collapse(annotation);\n }\n }\n }\n }\n }\n });\n }\n }\n\n /**\n * Once upon a time (the original version of this,) document partitioning was performed via\n * \t{@link IDocumentExtension3#computePartitioning(String, int, int, boolean)} and it did a\n * \tterrible job. Now, instead, we're using the Eclipse {@link FindReplaceDocumentAdapter} class.\n */\n private HashMap determineFoldingRegions(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n // TODO use regions for tracking in optimizations on re-parses\n final HashMap additions = new HashMap<>();\n final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(document);\n // PCal location\n try {\n IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);\n if (find == null) {\n find = search.find(0, \"--\" + IPCalReservedWords.FAIR, true, true, false, false);\n }\n if (find != null) {\n final int pcalStartLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\(\\\\*\", false, true, false, true);\n if (find != null) {\n final int startLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\s?\\\\*+\\\\)$\", true, true, false, true);\n addProjectionAdditionToMap(additions, startLocation, find, AnnotationType.PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Translated PCal location\n try {\n IRegion find = search.find(0, PCAL_TRANSLATION_PREFIX_REGEX, true, true, false, true);\n if (find != null) {\n final int translationStartLocation = find.getOffset();\n find = search.find(translationStartLocation, PCAL_TRANSLATION_SUFFIX_REGEX, true, true, false, true);\n if (find != null) {\n addProjectionAdditionToMap(additions, translationStartLocation, find, AnnotationType.TRANSLATED_PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Block comment locations\n try {\n boolean inBlock = false;\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n while (find != null) {\n if (inBlock) {\n addProjectionAdditionToMap(additions, lastFoundIndex, find, AnnotationType.BLOCK_COMMENT);\n }\n inBlock = !inBlock;\n lastFoundIndex = find.getOffset();\n find = search.find((lastFoundIndex + find.getLength()), BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n }\n } catch (final BadLocationException ble) {\n }\n // 2 or more consecutive single line comments\n try {\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, SINGLE_LINE_COMMENT, true, true, false, true);\n int contiguousLineCount = 1;\n int firstMatchingOffset = -1;\n while (find != null) {\n if (firstMatchingOffset == -1) {\n firstMatchingOffset = find.getOffset();\n }\n lastFoundIndex = find.getOffset();\n final IRegion lineEnding = search.find((lastFoundIndex + find.getLength()), \"\\\\n\", true, true, false, true);\n if (lineEnding != null) {\n lastFoundIndex = lineEnding.getOffset();\n find = search.find((lastFoundIndex + 1), SINGLE_LINE_COMMENT, true, true, false, true);\n } else {\n // In this case the document has ended without a newline (but with a comment)\n lastFoundIndex += find.getLength();\n find = null;\n }\n boolean addProjection = (contiguousLineCount > 1);\n boolean reset = true;\n if ((find != null) && (find.getOffset() == (lastFoundIndex + 1))) {\n contiguousLineCount++;\n addProjection = false;\n reset = false;\n }\n if (addProjection) {\n addProjectionAdditionToMap(additions, firstMatchingOffset, lastFoundIndex, AnnotationType.MULTIPLE_SINGLE_LINE_COMMENT);\n }\n if (reset) {\n contiguousLineCount = 1;\n firstMatchingOffset = -1;\n }\n }\n } catch (final BadLocationException ble) {\n }\n return additions;\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final IRegion find, final AnnotationType type) throws BadLocationException {\n if (find != null) {\n final int endLocation = find.getOffset() + find.getLength() + 1;\n addProjectionAdditionToMap(additions, startLocation, endLocation, type);\n }\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final int endLocation, final AnnotationType type) throws BadLocationException {\n final int length = endLocation - startLocation;\n // +1 to cover the newline\n final int positionLength = length + ((document.getLength() > endLocation) ? 1 : 0);\n final Position position = new Position(startLocation, positionLength);\n additions.put(new TLCProjectionAnnotation(document.get(startLocation, length), type), position);\n }\n\n private enum AnnotationType {\n\n BLOCK_COMMENT, MULTIPLE_SINGLE_LINE_COMMENT, PCAL_BLOCK, TRANSLATED_PCAL_BLOCK\n }\n\n // Nothing in the ProjectionAnnotation hierarchy implements equals/hashCode, we'd like such things to exist\n // for reconciliation; also we denote classifications of annotations for folding groups.\n private static class TLCProjectionAnnotation extends ProjectionAnnotation {\n\n private final AnnotationType type;\n\n TLCProjectionAnnotation(final String text, final AnnotationType annotationType) {\n setText(text);\n type = annotationType;\n }\n\n AnnotationType getTLCType() {\n return type;\n }\n\n @Override\n public boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n if (!Annotation.class.isAssignableFrom(other.getClass())) {\n return false;\n }\n final Annotation otherAnnotation = (Annotation) other;\n final String otherText = otherAnnotation.getText();\n return Objects.equals(getText(), otherText);\n }\n\n @Override\n public int hashCode() {\n final String text = getText();\n if (text == null) {\n return 0;\n }\n return text.hashCode();\n }\n }\n}\n"} {"task_id": "Java_1096", "language": "Java", "task_type": "if_statement", "source_file": "java/github/tlaplus/tlaplus/toolbox/org.lamport.tla.toolbox.editor.basic/src/org/lamport/tla/toolbox/editor/basic/TLAReconcilingStrategy.java", "mask_start_position": 4338, "mask_end_position": 4405, "canonical_solution": "if (reconcile) {\n reconcile(null, null, null);\n }", "pre_mask_code": "package org.lamport.tla.toolbox.editor.basic;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.FindReplaceDocumentAdapter;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.IDocumentExtension3;\nimport org.eclipse.jface.text.IRegion;\nimport org.eclipse.jface.text.Position;\nimport org.eclipse.jface.text.reconciler.DirtyRegion;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategy;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;\nimport org.eclipse.jface.text.source.Annotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;\nimport org.eclipse.jface.text.source.projection.ProjectionViewer;\nimport org.eclipse.jface.util.IPropertyChangeListener;\nimport org.eclipse.jface.util.PropertyChangeEvent;\nimport org.eclipse.ui.PlatformUI;\nimport org.lamport.tla.toolbox.editor.basic.pcal.IPCalReservedWords;\nimport org.lamport.tla.toolbox.util.pref.IPreferenceConstants;\nimport org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;\n\n/**\n * We create this reconciling strategy for at least two reasons:\n * \t. having our custom source viewer configuration not use its super class' reconciler frees us from spell checking\n * \t\tmarkup\n * \t. to find fold locations for:\n * \t\t\t. block commments\n * \t\t\t. PlusCal code\n */\npublic class TLAReconcilingStrategy implements IPropertyChangeListener, IReconcilingStrategy, IReconcilingStrategyExtension {\n\n // Per BoxedCommentHandler, a delimiter is \"(\" followed by three \"*\", then 0-N \"*\", and finally suffixed with \")\"\n private static final String BLOCK_COMMENT_DELIMITER_REGEX = \"^[ \\\\t]*\\\\(\\\\*{3}\\\\**\\\\)\\\\s*$\";\n\n private static final String SINGLE_LINE_COMMENT = \"^[ \\\\t]*\\\\\\\\\\\\*\";\n\n private static final String PCAL_TRANSLATION_PREFIX_REGEX = \"^\\\\\\\\\\\\*+ BEGIN TRANSLATION.*$\";\n\n private static final String PCAL_TRANSLATION_SUFFIX_REGEX = \"^\\\\\\\\\\\\*+ END TRANSLATION.*$\";\n\n private IDocument document;\n\n /* the currently displayed projection annotations */\n protected final List currentAnnotations;\n\n /* the editor we're bound to */\n private TLAEditor editor;\n\n /* the underlying source viewer */\n private ProjectionViewer projectionViewer;\n\n private final AtomicBoolean foldBlockComments;\n\n private final AtomicBoolean foldPlusCalAlgorithm;\n\n private final AtomicBoolean foldTranslatedPlusCalBlock;\n\n public TLAReconcilingStrategy() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.addPropertyChangeListener(this);\n currentAnnotations = new ArrayList<>();\n foldBlockComments = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS));\n foldPlusCalAlgorithm = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM));\n foldTranslatedPlusCalBlock = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED));\n }\n\n public void dispose() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.removePropertyChangeListener(this);\n }\n\n @Override\n public void propertyChange(final PropertyChangeEvent event) {\n final boolean reconcile;\n if (IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS.equals(event.getProperty())) {\n foldBlockComments.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM.equals(event.getProperty())) {\n foldPlusCalAlgorithm.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED.equals(event.getProperty())) {\n foldTranslatedPlusCalBlock.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else {\n reconcile = false;\n }\n ", "post_mask_code": "\n }\n\n @Override\n public void reconcile(final IRegion partition) {\n reconcile(partition, null, null);\n }\n\n @Override\n public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {\n reconcile(null, dirtyRegion, subRegion);\n }\n\n @Override\n public void setDocument(final IDocument id) {\n document = id;\n }\n\n @Override\n public void initialReconcile() {\n reconcile(null, null, null);\n }\n\n @Override\n public void setProgressMonitor(final IProgressMonitor monitor) {\n }\n\n /**\n * Sets the editor to which we're bound; this is required for communicating folding projections.\n *\n * @param editor\n */\n public void setEditor(final TLAEditor tlaEditor) {\n editor = tlaEditor;\n }\n\n /**\n * Sets the projection viewer for which we're reconciling.\n *\n * @param viewer\n */\n public void setProjectionViewer(final ProjectionViewer viewer) {\n projectionViewer = viewer;\n projectionViewer.setData(getClass().toString(), this);\n }\n\n private void reconcile(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n if (editor != null) {\n final HashMap regionMap = determineFoldingRegions(partition, dirtyRegion, subRegion);\n final Annotation[] deletions;\n final HashMap regionsToAdd = new HashMap<>();\n synchronized (currentAnnotations) {\n for (final Map.Entry me : regionMap.entrySet()) {\n if (!currentAnnotations.remove(me.getKey())) {\n regionsToAdd.put(me.getKey(), me.getValue());\n }\n }\n deletions = currentAnnotations.toArray(new Annotation[currentAnnotations.size()]);\n currentAnnotations.clear();\n currentAnnotations.addAll(regionMap.keySet());\n }\n PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\n\n public void run() {\n editor.modifyProjectionAnnotations(deletions, regionsToAdd);\n if (projectionViewer != null) {\n final ProjectionAnnotationModel model = projectionViewer.getProjectionAnnotationModel();\n final boolean block = foldBlockComments.get();\n final boolean pcal = foldPlusCalAlgorithm.get();\n final boolean translated = foldTranslatedPlusCalBlock.get();\n // We could do even more optimization than this, but this is better than none.\n if (block || pcal || translated) {\n for (final TLCProjectionAnnotation annotation : currentAnnotations) {\n final boolean collapse;\n switch(annotation.getTLCType()) {\n case BLOCK_COMMENT:\n collapse = block;\n break;\n case PCAL_BLOCK:\n collapse = pcal;\n break;\n default:\n collapse = translated;\n }\n if (collapse) {\n model.collapse(annotation);\n }\n }\n }\n }\n }\n });\n }\n }\n\n /**\n * Once upon a time (the original version of this,) document partitioning was performed via\n * \t{@link IDocumentExtension3#computePartitioning(String, int, int, boolean)} and it did a\n * \tterrible job. Now, instead, we're using the Eclipse {@link FindReplaceDocumentAdapter} class.\n */\n private HashMap determineFoldingRegions(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n // TODO use regions for tracking in optimizations on re-parses\n final HashMap additions = new HashMap<>();\n final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(document);\n // PCal location\n try {\n IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);\n if (find == null) {\n find = search.find(0, \"--\" + IPCalReservedWords.FAIR, true, true, false, false);\n }\n if (find != null) {\n final int pcalStartLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\(\\\\*\", false, true, false, true);\n if (find != null) {\n final int startLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\s?\\\\*+\\\\)$\", true, true, false, true);\n addProjectionAdditionToMap(additions, startLocation, find, AnnotationType.PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Translated PCal location\n try {\n IRegion find = search.find(0, PCAL_TRANSLATION_PREFIX_REGEX, true, true, false, true);\n if (find != null) {\n final int translationStartLocation = find.getOffset();\n find = search.find(translationStartLocation, PCAL_TRANSLATION_SUFFIX_REGEX, true, true, false, true);\n if (find != null) {\n addProjectionAdditionToMap(additions, translationStartLocation, find, AnnotationType.TRANSLATED_PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Block comment locations\n try {\n boolean inBlock = false;\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n while (find != null) {\n if (inBlock) {\n addProjectionAdditionToMap(additions, lastFoundIndex, find, AnnotationType.BLOCK_COMMENT);\n }\n inBlock = !inBlock;\n lastFoundIndex = find.getOffset();\n find = search.find((lastFoundIndex + find.getLength()), BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n }\n } catch (final BadLocationException ble) {\n }\n // 2 or more consecutive single line comments\n try {\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, SINGLE_LINE_COMMENT, true, true, false, true);\n int contiguousLineCount = 1;\n int firstMatchingOffset = -1;\n while (find != null) {\n if (firstMatchingOffset == -1) {\n firstMatchingOffset = find.getOffset();\n }\n lastFoundIndex = find.getOffset();\n final IRegion lineEnding = search.find((lastFoundIndex + find.getLength()), \"\\\\n\", true, true, false, true);\n if (lineEnding != null) {\n lastFoundIndex = lineEnding.getOffset();\n find = search.find((lastFoundIndex + 1), SINGLE_LINE_COMMENT, true, true, false, true);\n } else {\n // In this case the document has ended without a newline (but with a comment)\n lastFoundIndex += find.getLength();\n find = null;\n }\n boolean addProjection = (contiguousLineCount > 1);\n boolean reset = true;\n if ((find != null) && (find.getOffset() == (lastFoundIndex + 1))) {\n contiguousLineCount++;\n addProjection = false;\n reset = false;\n }\n if (addProjection) {\n addProjectionAdditionToMap(additions, firstMatchingOffset, lastFoundIndex, AnnotationType.MULTIPLE_SINGLE_LINE_COMMENT);\n }\n if (reset) {\n contiguousLineCount = 1;\n firstMatchingOffset = -1;\n }\n }\n } catch (final BadLocationException ble) {\n }\n return additions;\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final IRegion find, final AnnotationType type) throws BadLocationException {\n if (find != null) {\n final int endLocation = find.getOffset() + find.getLength() + 1;\n addProjectionAdditionToMap(additions, startLocation, endLocation, type);\n }\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final int endLocation, final AnnotationType type) throws BadLocationException {\n final int length = endLocation - startLocation;\n // +1 to cover the newline\n final int positionLength = length + ((document.getLength() > endLocation) ? 1 : 0);\n final Position position = new Position(startLocation, positionLength);\n additions.put(new TLCProjectionAnnotation(document.get(startLocation, length), type), position);\n }\n\n private enum AnnotationType {\n\n BLOCK_COMMENT, MULTIPLE_SINGLE_LINE_COMMENT, PCAL_BLOCK, TRANSLATED_PCAL_BLOCK\n }\n\n // Nothing in the ProjectionAnnotation hierarchy implements equals/hashCode, we'd like such things to exist\n // for reconciliation; also we denote classifications of annotations for folding groups.\n private static class TLCProjectionAnnotation extends ProjectionAnnotation {\n\n private final AnnotationType type;\n\n TLCProjectionAnnotation(final String text, final AnnotationType annotationType) {\n setText(text);\n type = annotationType;\n }\n\n AnnotationType getTLCType() {\n return type;\n }\n\n @Override\n public boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n if (!Annotation.class.isAssignableFrom(other.getClass())) {\n return false;\n }\n final Annotation otherAnnotation = (Annotation) other;\n final String otherText = otherAnnotation.getText();\n return Objects.equals(getText(), otherText);\n }\n\n @Override\n public int hashCode() {\n final String text = getText();\n if (text == null) {\n return 0;\n }\n return text.hashCode();\n }\n }\n}\n"} {"task_id": "Java_1097", "language": "Java", "task_type": "switch_case", "source_file": "java/github/tlaplus/tlaplus/toolbox/org.lamport.tla.toolbox.editor.basic/src/org/lamport/tla/toolbox/editor/basic/TLAReconcilingStrategy.java", "mask_start_position": 7370, "mask_end_position": 7863, "canonical_solution": "switch(annotation.getTLCType()) {\n case BLOCK_COMMENT:\n collapse = block;\n break;\n case PCAL_BLOCK:\n collapse = pcal;\n break;\n default:\n collapse = translated;\n }", "pre_mask_code": "package org.lamport.tla.toolbox.editor.basic;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.FindReplaceDocumentAdapter;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.IDocumentExtension3;\nimport org.eclipse.jface.text.IRegion;\nimport org.eclipse.jface.text.Position;\nimport org.eclipse.jface.text.reconciler.DirtyRegion;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategy;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;\nimport org.eclipse.jface.text.source.Annotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;\nimport org.eclipse.jface.text.source.projection.ProjectionViewer;\nimport org.eclipse.jface.util.IPropertyChangeListener;\nimport org.eclipse.jface.util.PropertyChangeEvent;\nimport org.eclipse.ui.PlatformUI;\nimport org.lamport.tla.toolbox.editor.basic.pcal.IPCalReservedWords;\nimport org.lamport.tla.toolbox.util.pref.IPreferenceConstants;\nimport org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;\n\n/**\n * We create this reconciling strategy for at least two reasons:\n * \t. having our custom source viewer configuration not use its super class' reconciler frees us from spell checking\n * \t\tmarkup\n * \t. to find fold locations for:\n * \t\t\t. block commments\n * \t\t\t. PlusCal code\n */\npublic class TLAReconcilingStrategy implements IPropertyChangeListener, IReconcilingStrategy, IReconcilingStrategyExtension {\n\n // Per BoxedCommentHandler, a delimiter is \"(\" followed by three \"*\", then 0-N \"*\", and finally suffixed with \")\"\n private static final String BLOCK_COMMENT_DELIMITER_REGEX = \"^[ \\\\t]*\\\\(\\\\*{3}\\\\**\\\\)\\\\s*$\";\n\n private static final String SINGLE_LINE_COMMENT = \"^[ \\\\t]*\\\\\\\\\\\\*\";\n\n private static final String PCAL_TRANSLATION_PREFIX_REGEX = \"^\\\\\\\\\\\\*+ BEGIN TRANSLATION.*$\";\n\n private static final String PCAL_TRANSLATION_SUFFIX_REGEX = \"^\\\\\\\\\\\\*+ END TRANSLATION.*$\";\n\n private IDocument document;\n\n /* the currently displayed projection annotations */\n protected final List currentAnnotations;\n\n /* the editor we're bound to */\n private TLAEditor editor;\n\n /* the underlying source viewer */\n private ProjectionViewer projectionViewer;\n\n private final AtomicBoolean foldBlockComments;\n\n private final AtomicBoolean foldPlusCalAlgorithm;\n\n private final AtomicBoolean foldTranslatedPlusCalBlock;\n\n public TLAReconcilingStrategy() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.addPropertyChangeListener(this);\n currentAnnotations = new ArrayList<>();\n foldBlockComments = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS));\n foldPlusCalAlgorithm = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM));\n foldTranslatedPlusCalBlock = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED));\n }\n\n public void dispose() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.removePropertyChangeListener(this);\n }\n\n @Override\n public void propertyChange(final PropertyChangeEvent event) {\n final boolean reconcile;\n if (IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS.equals(event.getProperty())) {\n foldBlockComments.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM.equals(event.getProperty())) {\n foldPlusCalAlgorithm.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED.equals(event.getProperty())) {\n foldTranslatedPlusCalBlock.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else {\n reconcile = false;\n }\n if (reconcile) {\n reconcile(null, null, null);\n }\n }\n\n @Override\n public void reconcile(final IRegion partition) {\n reconcile(partition, null, null);\n }\n\n @Override\n public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {\n reconcile(null, dirtyRegion, subRegion);\n }\n\n @Override\n public void setDocument(final IDocument id) {\n document = id;\n }\n\n @Override\n public void initialReconcile() {\n reconcile(null, null, null);\n }\n\n @Override\n public void setProgressMonitor(final IProgressMonitor monitor) {\n }\n\n /**\n * Sets the editor to which we're bound; this is required for communicating folding projections.\n *\n * @param editor\n */\n public void setEditor(final TLAEditor tlaEditor) {\n editor = tlaEditor;\n }\n\n /**\n * Sets the projection viewer for which we're reconciling.\n *\n * @param viewer\n */\n public void setProjectionViewer(final ProjectionViewer viewer) {\n projectionViewer = viewer;\n projectionViewer.setData(getClass().toString(), this);\n }\n\n private void reconcile(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n if (editor != null) {\n final HashMap regionMap = determineFoldingRegions(partition, dirtyRegion, subRegion);\n final Annotation[] deletions;\n final HashMap regionsToAdd = new HashMap<>();\n synchronized (currentAnnotations) {\n for (final Map.Entry me : regionMap.entrySet()) {\n if (!currentAnnotations.remove(me.getKey())) {\n regionsToAdd.put(me.getKey(), me.getValue());\n }\n }\n deletions = currentAnnotations.toArray(new Annotation[currentAnnotations.size()]);\n currentAnnotations.clear();\n currentAnnotations.addAll(regionMap.keySet());\n }\n PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\n\n public void run() {\n editor.modifyProjectionAnnotations(deletions, regionsToAdd);\n if (projectionViewer != null) {\n final ProjectionAnnotationModel model = projectionViewer.getProjectionAnnotationModel();\n final boolean block = foldBlockComments.get();\n final boolean pcal = foldPlusCalAlgorithm.get();\n final boolean translated = foldTranslatedPlusCalBlock.get();\n // We could do even more optimization than this, but this is better than none.\n if (block || pcal || translated) {\n for (final TLCProjectionAnnotation annotation : currentAnnotations) {\n final boolean collapse;\n ", "post_mask_code": "\n if (collapse) {\n model.collapse(annotation);\n }\n }\n }\n }\n }\n });\n }\n }\n\n /**\n * Once upon a time (the original version of this,) document partitioning was performed via\n * \t{@link IDocumentExtension3#computePartitioning(String, int, int, boolean)} and it did a\n * \tterrible job. Now, instead, we're using the Eclipse {@link FindReplaceDocumentAdapter} class.\n */\n private HashMap determineFoldingRegions(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n // TODO use regions for tracking in optimizations on re-parses\n final HashMap additions = new HashMap<>();\n final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(document);\n // PCal location\n try {\n IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);\n if (find == null) {\n find = search.find(0, \"--\" + IPCalReservedWords.FAIR, true, true, false, false);\n }\n if (find != null) {\n final int pcalStartLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\(\\\\*\", false, true, false, true);\n if (find != null) {\n final int startLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\s?\\\\*+\\\\)$\", true, true, false, true);\n addProjectionAdditionToMap(additions, startLocation, find, AnnotationType.PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Translated PCal location\n try {\n IRegion find = search.find(0, PCAL_TRANSLATION_PREFIX_REGEX, true, true, false, true);\n if (find != null) {\n final int translationStartLocation = find.getOffset();\n find = search.find(translationStartLocation, PCAL_TRANSLATION_SUFFIX_REGEX, true, true, false, true);\n if (find != null) {\n addProjectionAdditionToMap(additions, translationStartLocation, find, AnnotationType.TRANSLATED_PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Block comment locations\n try {\n boolean inBlock = false;\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n while (find != null) {\n if (inBlock) {\n addProjectionAdditionToMap(additions, lastFoundIndex, find, AnnotationType.BLOCK_COMMENT);\n }\n inBlock = !inBlock;\n lastFoundIndex = find.getOffset();\n find = search.find((lastFoundIndex + find.getLength()), BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n }\n } catch (final BadLocationException ble) {\n }\n // 2 or more consecutive single line comments\n try {\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, SINGLE_LINE_COMMENT, true, true, false, true);\n int contiguousLineCount = 1;\n int firstMatchingOffset = -1;\n while (find != null) {\n if (firstMatchingOffset == -1) {\n firstMatchingOffset = find.getOffset();\n }\n lastFoundIndex = find.getOffset();\n final IRegion lineEnding = search.find((lastFoundIndex + find.getLength()), \"\\\\n\", true, true, false, true);\n if (lineEnding != null) {\n lastFoundIndex = lineEnding.getOffset();\n find = search.find((lastFoundIndex + 1), SINGLE_LINE_COMMENT, true, true, false, true);\n } else {\n // In this case the document has ended without a newline (but with a comment)\n lastFoundIndex += find.getLength();\n find = null;\n }\n boolean addProjection = (contiguousLineCount > 1);\n boolean reset = true;\n if ((find != null) && (find.getOffset() == (lastFoundIndex + 1))) {\n contiguousLineCount++;\n addProjection = false;\n reset = false;\n }\n if (addProjection) {\n addProjectionAdditionToMap(additions, firstMatchingOffset, lastFoundIndex, AnnotationType.MULTIPLE_SINGLE_LINE_COMMENT);\n }\n if (reset) {\n contiguousLineCount = 1;\n firstMatchingOffset = -1;\n }\n }\n } catch (final BadLocationException ble) {\n }\n return additions;\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final IRegion find, final AnnotationType type) throws BadLocationException {\n if (find != null) {\n final int endLocation = find.getOffset() + find.getLength() + 1;\n addProjectionAdditionToMap(additions, startLocation, endLocation, type);\n }\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final int endLocation, final AnnotationType type) throws BadLocationException {\n final int length = endLocation - startLocation;\n // +1 to cover the newline\n final int positionLength = length + ((document.getLength() > endLocation) ? 1 : 0);\n final Position position = new Position(startLocation, positionLength);\n additions.put(new TLCProjectionAnnotation(document.get(startLocation, length), type), position);\n }\n\n private enum AnnotationType {\n\n BLOCK_COMMENT, MULTIPLE_SINGLE_LINE_COMMENT, PCAL_BLOCK, TRANSLATED_PCAL_BLOCK\n }\n\n // Nothing in the ProjectionAnnotation hierarchy implements equals/hashCode, we'd like such things to exist\n // for reconciliation; also we denote classifications of annotations for folding groups.\n private static class TLCProjectionAnnotation extends ProjectionAnnotation {\n\n private final AnnotationType type;\n\n TLCProjectionAnnotation(final String text, final AnnotationType annotationType) {\n setText(text);\n type = annotationType;\n }\n\n AnnotationType getTLCType() {\n return type;\n }\n\n @Override\n public boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n if (!Annotation.class.isAssignableFrom(other.getClass())) {\n return false;\n }\n final Annotation otherAnnotation = (Annotation) other;\n final String otherText = otherAnnotation.getText();\n return Objects.equals(getText(), otherText);\n }\n\n @Override\n public int hashCode() {\n final String text = getText();\n if (text == null) {\n return 0;\n }\n return text.hashCode();\n }\n }\n}\n"} {"task_id": "Java_1098", "language": "Java", "task_type": "while_statement", "source_file": "java/github/tlaplus/tlaplus/toolbox/org.lamport.tla.toolbox.editor.basic/src/org/lamport/tla/toolbox/editor/basic/TLAReconcilingStrategy.java", "mask_start_position": 10680, "mask_end_position": 11092, "canonical_solution": "while (find != null) {\n if (inBlock) {\n addProjectionAdditionToMap(additions, lastFoundIndex, find, AnnotationType.BLOCK_COMMENT);\n }\n inBlock = !inBlock;\n lastFoundIndex = find.getOffset();\n find = search.find((lastFoundIndex + find.getLength()), BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n }", "pre_mask_code": "package org.lamport.tla.toolbox.editor.basic;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.FindReplaceDocumentAdapter;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.IDocumentExtension3;\nimport org.eclipse.jface.text.IRegion;\nimport org.eclipse.jface.text.Position;\nimport org.eclipse.jface.text.reconciler.DirtyRegion;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategy;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;\nimport org.eclipse.jface.text.source.Annotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;\nimport org.eclipse.jface.text.source.projection.ProjectionViewer;\nimport org.eclipse.jface.util.IPropertyChangeListener;\nimport org.eclipse.jface.util.PropertyChangeEvent;\nimport org.eclipse.ui.PlatformUI;\nimport org.lamport.tla.toolbox.editor.basic.pcal.IPCalReservedWords;\nimport org.lamport.tla.toolbox.util.pref.IPreferenceConstants;\nimport org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;\n\n/**\n * We create this reconciling strategy for at least two reasons:\n * \t. having our custom source viewer configuration not use its super class' reconciler frees us from spell checking\n * \t\tmarkup\n * \t. to find fold locations for:\n * \t\t\t. block commments\n * \t\t\t. PlusCal code\n */\npublic class TLAReconcilingStrategy implements IPropertyChangeListener, IReconcilingStrategy, IReconcilingStrategyExtension {\n\n // Per BoxedCommentHandler, a delimiter is \"(\" followed by three \"*\", then 0-N \"*\", and finally suffixed with \")\"\n private static final String BLOCK_COMMENT_DELIMITER_REGEX = \"^[ \\\\t]*\\\\(\\\\*{3}\\\\**\\\\)\\\\s*$\";\n\n private static final String SINGLE_LINE_COMMENT = \"^[ \\\\t]*\\\\\\\\\\\\*\";\n\n private static final String PCAL_TRANSLATION_PREFIX_REGEX = \"^\\\\\\\\\\\\*+ BEGIN TRANSLATION.*$\";\n\n private static final String PCAL_TRANSLATION_SUFFIX_REGEX = \"^\\\\\\\\\\\\*+ END TRANSLATION.*$\";\n\n private IDocument document;\n\n /* the currently displayed projection annotations */\n protected final List currentAnnotations;\n\n /* the editor we're bound to */\n private TLAEditor editor;\n\n /* the underlying source viewer */\n private ProjectionViewer projectionViewer;\n\n private final AtomicBoolean foldBlockComments;\n\n private final AtomicBoolean foldPlusCalAlgorithm;\n\n private final AtomicBoolean foldTranslatedPlusCalBlock;\n\n public TLAReconcilingStrategy() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.addPropertyChangeListener(this);\n currentAnnotations = new ArrayList<>();\n foldBlockComments = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS));\n foldPlusCalAlgorithm = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM));\n foldTranslatedPlusCalBlock = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED));\n }\n\n public void dispose() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.removePropertyChangeListener(this);\n }\n\n @Override\n public void propertyChange(final PropertyChangeEvent event) {\n final boolean reconcile;\n if (IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS.equals(event.getProperty())) {\n foldBlockComments.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM.equals(event.getProperty())) {\n foldPlusCalAlgorithm.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED.equals(event.getProperty())) {\n foldTranslatedPlusCalBlock.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else {\n reconcile = false;\n }\n if (reconcile) {\n reconcile(null, null, null);\n }\n }\n\n @Override\n public void reconcile(final IRegion partition) {\n reconcile(partition, null, null);\n }\n\n @Override\n public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {\n reconcile(null, dirtyRegion, subRegion);\n }\n\n @Override\n public void setDocument(final IDocument id) {\n document = id;\n }\n\n @Override\n public void initialReconcile() {\n reconcile(null, null, null);\n }\n\n @Override\n public void setProgressMonitor(final IProgressMonitor monitor) {\n }\n\n /**\n * Sets the editor to which we're bound; this is required for communicating folding projections.\n *\n * @param editor\n */\n public void setEditor(final TLAEditor tlaEditor) {\n editor = tlaEditor;\n }\n\n /**\n * Sets the projection viewer for which we're reconciling.\n *\n * @param viewer\n */\n public void setProjectionViewer(final ProjectionViewer viewer) {\n projectionViewer = viewer;\n projectionViewer.setData(getClass().toString(), this);\n }\n\n private void reconcile(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n if (editor != null) {\n final HashMap regionMap = determineFoldingRegions(partition, dirtyRegion, subRegion);\n final Annotation[] deletions;\n final HashMap regionsToAdd = new HashMap<>();\n synchronized (currentAnnotations) {\n for (final Map.Entry me : regionMap.entrySet()) {\n if (!currentAnnotations.remove(me.getKey())) {\n regionsToAdd.put(me.getKey(), me.getValue());\n }\n }\n deletions = currentAnnotations.toArray(new Annotation[currentAnnotations.size()]);\n currentAnnotations.clear();\n currentAnnotations.addAll(regionMap.keySet());\n }\n PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\n\n public void run() {\n editor.modifyProjectionAnnotations(deletions, regionsToAdd);\n if (projectionViewer != null) {\n final ProjectionAnnotationModel model = projectionViewer.getProjectionAnnotationModel();\n final boolean block = foldBlockComments.get();\n final boolean pcal = foldPlusCalAlgorithm.get();\n final boolean translated = foldTranslatedPlusCalBlock.get();\n // We could do even more optimization than this, but this is better than none.\n if (block || pcal || translated) {\n for (final TLCProjectionAnnotation annotation : currentAnnotations) {\n final boolean collapse;\n switch(annotation.getTLCType()) {\n case BLOCK_COMMENT:\n collapse = block;\n break;\n case PCAL_BLOCK:\n collapse = pcal;\n break;\n default:\n collapse = translated;\n }\n if (collapse) {\n model.collapse(annotation);\n }\n }\n }\n }\n }\n });\n }\n }\n\n /**\n * Once upon a time (the original version of this,) document partitioning was performed via\n * \t{@link IDocumentExtension3#computePartitioning(String, int, int, boolean)} and it did a\n * \tterrible job. Now, instead, we're using the Eclipse {@link FindReplaceDocumentAdapter} class.\n */\n private HashMap determineFoldingRegions(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n // TODO use regions for tracking in optimizations on re-parses\n final HashMap additions = new HashMap<>();\n final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(document);\n // PCal location\n try {\n IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);\n if (find == null) {\n find = search.find(0, \"--\" + IPCalReservedWords.FAIR, true, true, false, false);\n }\n if (find != null) {\n final int pcalStartLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\(\\\\*\", false, true, false, true);\n if (find != null) {\n final int startLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\s?\\\\*+\\\\)$\", true, true, false, true);\n addProjectionAdditionToMap(additions, startLocation, find, AnnotationType.PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Translated PCal location\n try {\n IRegion find = search.find(0, PCAL_TRANSLATION_PREFIX_REGEX, true, true, false, true);\n if (find != null) {\n final int translationStartLocation = find.getOffset();\n find = search.find(translationStartLocation, PCAL_TRANSLATION_SUFFIX_REGEX, true, true, false, true);\n if (find != null) {\n addProjectionAdditionToMap(additions, translationStartLocation, find, AnnotationType.TRANSLATED_PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Block comment locations\n try {\n boolean inBlock = false;\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n ", "post_mask_code": "\n } catch (final BadLocationException ble) {\n }\n // 2 or more consecutive single line comments\n try {\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, SINGLE_LINE_COMMENT, true, true, false, true);\n int contiguousLineCount = 1;\n int firstMatchingOffset = -1;\n while (find != null) {\n if (firstMatchingOffset == -1) {\n firstMatchingOffset = find.getOffset();\n }\n lastFoundIndex = find.getOffset();\n final IRegion lineEnding = search.find((lastFoundIndex + find.getLength()), \"\\\\n\", true, true, false, true);\n if (lineEnding != null) {\n lastFoundIndex = lineEnding.getOffset();\n find = search.find((lastFoundIndex + 1), SINGLE_LINE_COMMENT, true, true, false, true);\n } else {\n // In this case the document has ended without a newline (but with a comment)\n lastFoundIndex += find.getLength();\n find = null;\n }\n boolean addProjection = (contiguousLineCount > 1);\n boolean reset = true;\n if ((find != null) && (find.getOffset() == (lastFoundIndex + 1))) {\n contiguousLineCount++;\n addProjection = false;\n reset = false;\n }\n if (addProjection) {\n addProjectionAdditionToMap(additions, firstMatchingOffset, lastFoundIndex, AnnotationType.MULTIPLE_SINGLE_LINE_COMMENT);\n }\n if (reset) {\n contiguousLineCount = 1;\n firstMatchingOffset = -1;\n }\n }\n } catch (final BadLocationException ble) {\n }\n return additions;\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final IRegion find, final AnnotationType type) throws BadLocationException {\n if (find != null) {\n final int endLocation = find.getOffset() + find.getLength() + 1;\n addProjectionAdditionToMap(additions, startLocation, endLocation, type);\n }\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final int endLocation, final AnnotationType type) throws BadLocationException {\n final int length = endLocation - startLocation;\n // +1 to cover the newline\n final int positionLength = length + ((document.getLength() > endLocation) ? 1 : 0);\n final Position position = new Position(startLocation, positionLength);\n additions.put(new TLCProjectionAnnotation(document.get(startLocation, length), type), position);\n }\n\n private enum AnnotationType {\n\n BLOCK_COMMENT, MULTIPLE_SINGLE_LINE_COMMENT, PCAL_BLOCK, TRANSLATED_PCAL_BLOCK\n }\n\n // Nothing in the ProjectionAnnotation hierarchy implements equals/hashCode, we'd like such things to exist\n // for reconciliation; also we denote classifications of annotations for folding groups.\n private static class TLCProjectionAnnotation extends ProjectionAnnotation {\n\n private final AnnotationType type;\n\n TLCProjectionAnnotation(final String text, final AnnotationType annotationType) {\n setText(text);\n type = annotationType;\n }\n\n AnnotationType getTLCType() {\n return type;\n }\n\n @Override\n public boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n if (!Annotation.class.isAssignableFrom(other.getClass())) {\n return false;\n }\n final Annotation otherAnnotation = (Annotation) other;\n final String otherText = otherAnnotation.getText();\n return Objects.equals(getText(), otherText);\n }\n\n @Override\n public int hashCode() {\n final String text = getText();\n if (text == null) {\n return 0;\n }\n return text.hashCode();\n }\n }\n}\n"} {"task_id": "Java_1099", "language": "Java", "task_type": "empty", "source_file": "java/github/tlaplus/tlaplus/toolbox/org.lamport.tla.toolbox.editor.basic/src/org/lamport/tla/toolbox/editor/basic/TLAReconcilingStrategy.java", "mask_start_position": 15422, "mask_end_position": 15422, "canonical_solution": "", "pre_mask_code": "package org.lamport.tla.toolbox.editor.basic;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.FindReplaceDocumentAdapter;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.IDocumentExtension3;\nimport org.eclipse.jface.text.IRegion;\nimport org.eclipse.jface.text.Position;\nimport org.eclipse.jface.text.reconciler.DirtyRegion;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategy;\nimport org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;\nimport org.eclipse.jface.text.source.Annotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotation;\nimport org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;\nimport org.eclipse.jface.text.source.projection.ProjectionViewer;\nimport org.eclipse.jface.util.IPropertyChangeListener;\nimport org.eclipse.jface.util.PropertyChangeEvent;\nimport org.eclipse.ui.PlatformUI;\nimport org.lamport.tla.toolbox.editor.basic.pcal.IPCalReservedWords;\nimport org.lamport.tla.toolbox.util.pref.IPreferenceConstants;\nimport org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;\n\n/**\n * We create this reconciling strategy for at least two reasons:\n * \t. having our custom source viewer configuration not use its super class' reconciler frees us from spell checking\n * \t\tmarkup\n * \t. to find fold locations for:\n * \t\t\t. block commments\n * \t\t\t. PlusCal code\n */\npublic class TLAReconcilingStrategy implements IPropertyChangeListener, IReconcilingStrategy, IReconcilingStrategyExtension {\n\n // Per BoxedCommentHandler, a delimiter is \"(\" followed by three \"*\", then 0-N \"*\", and finally suffixed with \")\"\n private static final String BLOCK_COMMENT_DELIMITER_REGEX = \"^[ \\\\t]*\\\\(\\\\*{3}\\\\**\\\\)\\\\s*$\";\n\n private static final String SINGLE_LINE_COMMENT = \"^[ \\\\t]*\\\\\\\\\\\\*\";\n\n private static final String PCAL_TRANSLATION_PREFIX_REGEX = \"^\\\\\\\\\\\\*+ BEGIN TRANSLATION.*$\";\n\n private static final String PCAL_TRANSLATION_SUFFIX_REGEX = \"^\\\\\\\\\\\\*+ END TRANSLATION.*$\";\n\n private IDocument document;\n\n /* the currently displayed projection annotations */\n protected final List currentAnnotations;\n\n /* the editor we're bound to */\n private TLAEditor editor;\n\n /* the underlying source viewer */\n private ProjectionViewer projectionViewer;\n\n private final AtomicBoolean foldBlockComments;\n\n private final AtomicBoolean foldPlusCalAlgorithm;\n\n private final AtomicBoolean foldTranslatedPlusCalBlock;\n\n public TLAReconcilingStrategy() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.addPropertyChangeListener(this);\n currentAnnotations = new ArrayList<>();\n foldBlockComments = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS));\n foldPlusCalAlgorithm = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM));\n foldTranslatedPlusCalBlock = new AtomicBoolean(store.getBoolean(IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED));\n }\n\n public void dispose() {\n final IPreferenceStore store = PreferenceStoreHelper.getInstancePreferenceStore();\n store.removePropertyChangeListener(this);\n }\n\n @Override\n public void propertyChange(final PropertyChangeEvent event) {\n final boolean reconcile;\n if (IPreferenceConstants.I_FOLDING_BLOCK_COMMENTS.equals(event.getProperty())) {\n foldBlockComments.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_ALGORITHM.equals(event.getProperty())) {\n foldPlusCalAlgorithm.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else if (IPreferenceConstants.I_FOLDING_PCAL_TRANSLATED.equals(event.getProperty())) {\n foldTranslatedPlusCalBlock.set(((Boolean) event.getNewValue()).booleanValue());\n reconcile = true;\n } else {\n reconcile = false;\n }\n if (reconcile) {\n reconcile(null, null, null);\n }\n }\n\n @Override\n public void reconcile(final IRegion partition) {\n reconcile(partition, null, null);\n }\n\n @Override\n public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {\n reconcile(null, dirtyRegion, subRegion);\n }\n\n @Override\n public void setDocument(final IDocument id) {\n document = id;\n }\n\n @Override\n public void initialReconcile() {\n reconcile(null, null, null);\n }\n\n @Override\n public void setProgressMonitor(final IProgressMonitor monitor) {\n }\n\n /**\n * Sets the editor to which we're bound; this is required for communicating folding projections.\n *\n * @param editor\n */\n public void setEditor(final TLAEditor tlaEditor) {\n editor = tlaEditor;\n }\n\n /**\n * Sets the projection viewer for which we're reconciling.\n *\n * @param viewer\n */\n public void setProjectionViewer(final ProjectionViewer viewer) {\n projectionViewer = viewer;\n projectionViewer.setData(getClass().toString(), this);\n }\n\n private void reconcile(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n if (editor != null) {\n final HashMap regionMap = determineFoldingRegions(partition, dirtyRegion, subRegion);\n final Annotation[] deletions;\n final HashMap regionsToAdd = new HashMap<>();\n synchronized (currentAnnotations) {\n for (final Map.Entry me : regionMap.entrySet()) {\n if (!currentAnnotations.remove(me.getKey())) {\n regionsToAdd.put(me.getKey(), me.getValue());\n }\n }\n deletions = currentAnnotations.toArray(new Annotation[currentAnnotations.size()]);\n currentAnnotations.clear();\n currentAnnotations.addAll(regionMap.keySet());\n }\n PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\n\n public void run() {\n editor.modifyProjectionAnnotations(deletions, regionsToAdd);\n if (projectionViewer != null) {\n final ProjectionAnnotationModel model = projectionViewer.getProjectionAnnotationModel();\n final boolean block = foldBlockComments.get();\n final boolean pcal = foldPlusCalAlgorithm.get();\n final boolean translated = foldTranslatedPlusCalBlock.get();\n // We could do even more optimization than this, but this is better than none.\n if (block || pcal || translated) {\n for (final TLCProjectionAnnotation annotation : currentAnnotations) {\n final boolean collapse;\n switch(annotation.getTLCType()) {\n case BLOCK_COMMENT:\n collapse = block;\n break;\n case PCAL_BLOCK:\n collapse = pcal;\n break;\n default:\n collapse = translated;\n }\n if (collapse) {\n model.collapse(annotation);\n }\n }\n }\n }\n }\n });\n }\n }\n\n /**\n * Once upon a time (the original version of this,) document partitioning was performed via\n * \t{@link IDocumentExtension3#computePartitioning(String, int, int, boolean)} and it did a\n * \tterrible job. Now, instead, we're using the Eclipse {@link FindReplaceDocumentAdapter} class.\n */\n private HashMap determineFoldingRegions(final IRegion partition, final DirtyRegion dirtyRegion, final IRegion subRegion) {\n // TODO use regions for tracking in optimizations on re-parses\n final HashMap additions = new HashMap<>();\n final FindReplaceDocumentAdapter search = new FindReplaceDocumentAdapter(document);\n // PCal location\n try {\n IRegion find = search.find(0, IPCalReservedWords.ALGORITHM, true, true, false, false);\n if (find == null) {\n find = search.find(0, \"--\" + IPCalReservedWords.FAIR, true, true, false, false);\n }\n if (find != null) {\n final int pcalStartLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\(\\\\*\", false, true, false, true);\n if (find != null) {\n final int startLocation = find.getOffset();\n find = search.find(pcalStartLocation, \"^\\\\s?\\\\*+\\\\)$\", true, true, false, true);\n addProjectionAdditionToMap(additions, startLocation, find, AnnotationType.PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Translated PCal location\n try {\n IRegion find = search.find(0, PCAL_TRANSLATION_PREFIX_REGEX, true, true, false, true);\n if (find != null) {\n final int translationStartLocation = find.getOffset();\n find = search.find(translationStartLocation, PCAL_TRANSLATION_SUFFIX_REGEX, true, true, false, true);\n if (find != null) {\n addProjectionAdditionToMap(additions, translationStartLocation, find, AnnotationType.TRANSLATED_PCAL_BLOCK);\n }\n }\n } catch (final BadLocationException ble) {\n }\n // Block comment locations\n try {\n boolean inBlock = false;\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n while (find != null) {\n if (inBlock) {\n addProjectionAdditionToMap(additions, lastFoundIndex, find, AnnotationType.BLOCK_COMMENT);\n }\n inBlock = !inBlock;\n lastFoundIndex = find.getOffset();\n find = search.find((lastFoundIndex + find.getLength()), BLOCK_COMMENT_DELIMITER_REGEX, true, true, false, true);\n }\n } catch (final BadLocationException ble) {\n }\n // 2 or more consecutive single line comments\n try {\n // TODO future optimizations based on DocumentEvents' locations\n int lastFoundIndex = 0;\n IRegion find = search.find(lastFoundIndex, SINGLE_LINE_COMMENT, true, true, false, true);\n int contiguousLineCount = 1;\n int firstMatchingOffset = -1;\n while (find != null) {\n if (firstMatchingOffset == -1) {\n firstMatchingOffset = find.getOffset();\n }\n lastFoundIndex = find.getOffset();\n final IRegion lineEnding = search.find((lastFoundIndex + find.getLength()), \"\\\\n\", true, true, false, true);\n if (lineEnding != null) {\n lastFoundIndex = lineEnding.getOffset();\n find = search.find((lastFoundIndex + 1), SINGLE_LINE_COMMENT, true, true, false, true);\n } else {\n // In this case the document has ended without a newline (but with a comment)\n lastFoundIndex += find.getLength();\n find = null;\n }\n boolean addProjection = (contiguousLineCount > 1);\n boolean reset = true;\n if ((find != null) && (find.getOffset() == (lastFoundIndex + 1))) {\n contiguousLineCount++;\n addProjection = false;\n reset = false;\n }\n if (addProjection) {\n addProjectionAdditionToMap(additions, firstMatchingOffset, lastFoundIndex, AnnotationType.MULTIPLE_SINGLE_LINE_COMMENT);\n }\n if (reset) {\n contiguousLineCount = 1;\n firstMatchingOffset = -1;\n }\n }\n } catch (final BadLocationException ble) {\n }\n return additions;\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final IRegion find, final AnnotationType type) throws BadLocationException {\n if (find != null) {\n final int endLocation = find.getOffset() + find.getLength() + 1;\n addProjectionAdditionToMap(additions, startLocation, endLocation, type);\n }\n }\n\n private void addProjectionAdditionToMap(final Map additions, final int startLocation, final int endLocation, final AnnotationType type) throws BadLocationException {\n final int length = endLocation - startLocation;\n // +1 to cover the newline\n final int positionLength = length + ((document.getLength() > endLocation) ? 1 : 0);\n final Position position = new Position(startLocation, positionLength);\n additions.put(new TLCProjectionAnnotation(document.get(startLocation, length), type), position);\n }\n\n private enum AnnotationType {\n\n BLOCK_COMMENT, MULTIPLE_SINGLE_LINE_COMMENT, PCAL_BLOCK, TRANSLATED_PCAL_BLOCK\n }\n\n // Nothing in the ProjectionAnnotation hierarchy implements equals/hashCode, we'd like such things to exist\n // for reconciliation; also we denote classifications of annotations for folding groups.\n private static class TLCProjectionAnnotation extends ProjectionAnnotation {\n\n private final AnnotationType type;\n\n TLCProjectionAnnotation(final String text, final AnnotationType annotationType) {\n setText(text);\n type = annotationType;\n }\n\n AnnotationType getTLCType() {\n return type;\n }\n\n @Override\n public boolean equals(final Object other) {\n if (other == null) {\n return false;\n }\n if (!Annotation.class.isAssignableFrom(other.getClass())) {\n return false;\n }\n final Annotation otherAnnotation = (Annotation) other;\n final String otherText = otherAnnotation.getText();\n return Objects.equals(getText(), otherText);\n }\n\n @Override\n public int hashCode() {\n final String text = getText();\n if (text == null) {\n return 0;\n }\n return text.hashCode();\n ", "post_mask_code": " }\n }\n}\n"} {"task_id": "Java_1100", "language": "Java", "task_type": "empty", "source_file": "java/github/wrlu/FridaHooker/app/src/main/java/com/wrlus/fridahooker/view/ProgressCallback.java", "mask_start_position": 126, "mask_end_position": 126, "canonical_solution": "", "pre_mask_code": "package com.wrlus.fridahooker.view;\n\npublic interface ProgressCallback {\n\n void setProgress(int progressBarId, double perce", "post_mask_code": "ntage);\n}\n"} {"task_id": "Java_1101", "language": "Java", "task_type": "empty", "source_file": "java/github/rosmord/jsesh/jsesh/src/main/java/jsesh/mdc/ParserErrorManager.java", "mask_start_position": 2, "mask_end_position": 2, "canonical_solution": "", "pre_mask_code": "pa", "post_mask_code": "ckage jsesh.mdc;\n\n/**\n * ParserErrorManager.java\n *\n * Created: Thu Jun 13 15:01:39 2002\n *\n * @author Serge ROSMORDUC\n */\npublic interface ParserErrorManager {\n\n MDCSyntaxError buildError(String message);\n}\n// ParserErrorManager\n"} {"task_id": "Java_1102", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Impro-Visor/Impro-Visor/src/imp/roadmap/brickdictionary/BrickLibrary.java", "mask_start_position": 15462, "mask_end_position": 15492, "canonical_solution": "public long getCost(String t) ", "pre_mask_code": "/**\n * This Java Class is part of the Impro-Visor Application\n */\npackage imp.roadmap.brickdictionary;\n\nimport imp.roadmap.cykparser.PostProcessor;\nimport imp.data.ChordSymbol;\nimport imp.util.ErrorLog;\nimport java.util.Collection;\nimport polya.*;\nimport java.io.*;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.Set;\n\n/**\n * purpose: Methods relating to the brick library (dictionary)\n * @author Zachary Merritt\n */\npublic class BrickLibrary {\n\n /**\n * Keyword used in defining bricks in a dictionary.\n */\n public static final String DEF_BRICK = \"defbrick\";\n\n /**\n * This is the conjunction to be used to describe appendages to Cadences\n * such as Overrun and Dropback\n */\n public static String CONJUNCTION = \" + \";\n\n /**\n * The name for an Overrun\n */\n public static String OVERRUN = \"Overrun\";\n\n /**\n * The name for a Dropback\n */\n public static String DROPBACK = \"Dropback\";\n\n // Lists of key names, with indices corresponding to numeric key value\n private static final String[] KEY_NAME_ARRAY = { \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\" };\n\n private static final String[] KEY_NAME_ARRAY_SHARPS = { \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\" };\n\n // the default cost of a type with no cost specified\n private static final long DEFAULT_COST = 40;\n\n // the string describing an invisible brick's type\n public static final String INVISIBLE = \"Invisible\";\n\n // all bricks\n private LinkedHashMap> brickMap;\n\n // brick costs by type\n private LinkedHashMap costMap;\n\n // the postprocessing unit\n public PostProcessor processor;\n\n /**\n * BrickLibrary / 0\n * Default constructor for an empty BrickLibrary with no specified types\n */\n public BrickLibrary() {\n brickMap = new LinkedHashMap>();\n costMap = new LinkedHashMap();\n }\n\n /**\n * getNames\n * Returns the list of the names of all bricks stored in the dictionary\n * @return an array of Strings\n */\n public String[] getNames() {\n return brickMap.keySet().toArray(new String[0]);\n }\n\n /**\n * addBrickDefinition\n * When a new brick is created in the library, adds its contents to the\n * current brickMap and adds its definition to the dictionary file\n * @param brick, a newly created Brick\n */\n public void addBrickDefinition(Brick brick, String dictionaryFilename) {\n // add the brick to the current BrickLibrary\n boolean added = addBrick(brick);\n if (!added)\n return;\n Brick definitionBrick = new Brick(brick);\n // make a properly-formatted brick definition\n Polylist defn = definitionBrick.toBrickDefinition();\n String defnString = defn.toString();\n if (!brick.getVariant().equals(\"\"))\n defnString.replaceFirst(\" \\\\(\", \"\\\\(\");\n defnString = defnString.replaceAll(\" \\\\(\", \"\\n \\\\(\");\n // write out the string with the definition to the end of the file\n try {\n FileOutputStream out = new FileOutputStream(dictionaryFilename, true);\n out.write(\"\\n\".getBytes());\n out.write(defnString.getBytes());\n out.write(\"\\n\".getBytes());\n out.close();\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Cannot write to dictionary\");\n }\n }\n\n /**\n * addBrick\n * Adds a brick to the library's brickMap\n * @param brick, a created Brick\n */\n public boolean addBrick(Brick brick) {\n if (brickMap.containsKey(brick.getName())) {\n // first, we check if the brick is a duplicate or just a brick with\n // an already-used name but a different qualifier. Presently, a\n // doubly-defined brick will have both definitions added to the\n // dictionary but will warn a user if the two definitions are\n LinkedList sameStemList = brickMap.get(brick.getName());\n for (Brick sameStem : sameStemList) {\n if (sameStem.getVariant().equals(brick.getVariant())) {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary already contains \" + brick.getName() + \"(\" + brick.getVariant() + \"): will not\" + \" add to dictionary\", true);\n return false;\n }\n }\n sameStemList.add(brick);\n } else {\n // adding a brick with a new brickname\n LinkedList brickList = new LinkedList();\n brickList.add(brick);\n this.brickMap.put(brick.name, brickList);\n }\n // special rule for creating overruns\n if (brick.getType().equals(\"Cadence\")) {\n String overrunName = brick.getName() + CONJUNCTION + OVERRUN;\n long overrunKeyNum = brick.getKey();\n String overrunType = OVERRUN;\n String overrunMode = brick.getMode();\n String overrunQualifier = brick.getVariant();\n // take blocks from regular cadence and add the next chord\n // in the circle of fifths with the same quality as the\n // resolution\n ArrayList overrunBlocks = new ArrayList();\n overrunBlocks.add(brick);\n ArrayList chords = brick.flattenBlock();\n ChordBlock prevChord = chords.get(chords.size() - 1);\n ChordBlock overrunChord = new ChordBlock(prevChord.transposeName(5), prevChord.getDuration());\n overrunBlocks.add(overrunChord);\n // make a new brick from this list of blocks\n Brick overrun = new Brick(overrunName, overrunQualifier, overrunKeyNum, overrunType, overrunBlocks, overrunMode);\n addBrick(overrun);\n String dropbackName = brick.getName() + CONJUNCTION + DROPBACK;\n long dropbackKeyNum = brick.getKey();\n String dropbackType = DROPBACK;\n String dropbackMode = brick.getMode();\n String dropbackQualifier = brick.getVariant();\n // take blocks from regular cadence and add a relative VI dominant\n // to form a dropback.\n // FIX: This is not the only possible dropback!!\n // For example, we want to allow iii-IV's major and minor.\n ArrayList dropbackBlocks = new ArrayList();\n dropbackBlocks.add(brick);\n String dropbackChordName = keyNumToName((brick.getKey() + 9) % 12);\n /* I think it was wrong to include this in the first place:\n \n if (dropbackMode.equals(\"minor\"))\n dropbackChordName += \"7b5\";\n else\n */\n dropbackChordName += 7;\n ChordBlock dropbackChord = new ChordBlock(dropbackChordName, prevChord.getDuration());\n dropbackBlocks.add(dropbackChord);\n // make a new brick from this list of blocks\n Brick dropback = new Brick(dropbackName, dropbackQualifier, dropbackKeyNum, dropbackType, dropbackBlocks, dropbackMode);\n addBrick(dropback);\n }\n return true;\n }\n\n /**\n * getBrick (definition)\n * Gets the default Brick with the given name from the dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k) {\n if (brickMap.containsKey(s)) {\n LinkedList possibleBricks = brickMap.get(s);\n for (Brick oldBrick : possibleBricks) if (!oldBrick.getType().equals(INVISIBLE)) {\n Brick brick = new Brick(oldBrick);\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n }\n }\n // if no brick is returned\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s + \" with qualifier \" + q, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with duration)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = new Brick(brickMap.get(s).getFirst());\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * hasBrick\n * Checks if a Brick with a given name is in the dictionary\n * @param s, the Brick name\n * @return a boolean\n */\n public boolean hasBrick(String s) {\n return (brickMap.containsKey(s));\n }\n\n /**\n * getFullMap\n * Gets the list of all Bricks in the dictionary as a single collection\n * @return a Collection of Bricks\n */\n public Collection getFullMap() {\n LinkedList values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n values.addAll(brickname);\n }\n return values;\n }\n\n /**\n * getMap\n * Gets the organized list of all Bricks in the dictionary\n * @return a LinkedList of LinkedLists of Bricks\n */\n public LinkedList> getMap() {\n LinkedList> values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n LinkedList newlist = new LinkedList();\n for (Brick brick : brickname) if (!brick.getType().equals(INVISIBLE))\n newlist.add(brick);\n if (!newlist.isEmpty())\n values.add(newlist);\n }\n return values;\n }\n\n /**\n * removeBrick\n * Removes all Bricks matching a given Brick from the dictionary\n * @param brick, the Brick to be removed itself\n */\n public void removeBrick(Brick brick) {\n this.brickMap.remove(brick.name);\n }\n\n /**\n * removeBrick\n * Removes all Bricks with a given name from the dictionary\n * @param brickName, the name of the Brick(s) to be removed\n */\n public void removeBrick(String brickName) {\n this.brickMap.remove(brickName);\n }\n\n /**\n * exileBrick\n * Takes a Brick out of the visible brick library\n * @param brick, the brick to remove\n */\n public void exileBrick(Brick brick, String dictionaryFilename) {\n // define the search term (the name) for the given brick\n String brickType = \" \" + brick.getType() + \" \";\n String brickDefHead = DEF_BRICK + dashed(brick.getName());\n String qualifier = brick.getVariant();\n if (!qualifier.isEmpty())\n brickDefHead += \"(\" + qualifier + \")\";\n brickDefHead += \" \";\n // open the file and read in its contents\n try {\n File dictionary = new File(dictionaryFilename);\n FileReader in = new FileReader(dictionary);\n BufferedReader reader = new BufferedReader(in);\n String line = reader.readLine();\n String newfile = \"\";\n while (line != null) {\n // Exiling a brick is just taking the type and changing it\n // to be invisible\n if (line.contains(brickDefHead)) {\n line = line.replaceFirst(brickType, \" \" + INVISIBLE + \" \");\n }\n newfile += line + \"\\r\\n\";\n line = reader.readLine();\n }\n // write out the modified dictionary\n FileWriter writer = new FileWriter(dictionaryFilename);\n writer.write(newfile);\n writer.close();\n processDictionary(dictionaryFilename);\n } catch (IOException ioe) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not modify brick in dictionary\");\n }\n }\n\n /**\n * printDictionary\n * Prints every brick in the dictionary to System.err\n */\n public void printDictionary() {\n Iterator iter = getFullMap().iterator();\n while (iter.hasNext()) {\n Brick currentBrick = (Brick) iter.next();\n currentBrick.printBrick();\n }\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the default cost\n * @param t, a type, a String\n */\n public void addType(String t) {\n costMap.put(t, DEFAULT_COST);\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the specified cost\n * @param t, a type, a String\n * @param c, a cost, a long\n */\n public void addType(String t, long c) {\n costMap.put(t, c);\n }\n\n /**\n * getCost\n * Gets the cost associated with the given type\n * @param t, the type whose cost is desired (a String)\n * @return the cost, a long\n */\n ", "post_mask_code": "{\n if (!hasType(t))\n ErrorLog.log(ErrorLog.SEVERE, \"Type does not exist, will register\" + \"as an invisible brick: \" + t);\n return costMap.get(t);\n }\n\n /**\n * hasType\n * Checks if a given type is contained in the dictionary\n * @param t, a type (a String)\n * @return a boolean\n */\n public boolean hasType(String t) {\n return costMap.containsKey(t);\n }\n\n /**\n * getTypes\n * Gets the list of all types in the dictionary\n * @return an array of Strings of types\n */\n public String[] getTypes() {\n return costMap.keySet().toArray(new String[0]);\n }\n\n /**\n * isValidKey\n * Checks if a given key's name actually describes a key\n * @param keyName, a key's name as a String\n * @return a boolean\n */\n public static Boolean isValidKey(String keyName) {\n return keyName.equals(\"C\") || keyName.equals(\"B#\") || keyName.equals(\"C#\") || keyName.equals(\"Db\") || keyName.equals(\"D\") || keyName.equals(\"D#\") || keyName.equals(\"Eb\") || keyName.equals(\"E\") || keyName.equals(\"Fb\") || keyName.equals(\"F\") || keyName.equals(\"E#\") || keyName.equals(\"F#\") || keyName.equals(\"Gb\") || keyName.equals(\"G\") || keyName.equals(\"G#\") || keyName.equals(\"Ab\") || keyName.equals(\"A\") || keyName.equals(\"A#\") || keyName.equals(\"Bb\") || keyName.equals(\"B\") || keyName.equals(\"Cb\");\n }\n\n /**\n * keyNameToNum\n * Takes a key by name and returns the long describing that key\n * @param keyName, a key as a String\n * @return the same key as a long\n */\n public static long keyNameToNum(String keyName) {\n if (keyName.equals(\"\"))\n return -1;\n if (keyName.equals(\"C\") || keyName.equals(\"B#\"))\n return 0;\n if (keyName.equals(\"C#\") || keyName.equals(\"Db\"))\n return 1;\n if (keyName.equals(\"D\"))\n return 2;\n if (keyName.equals(\"D#\") || keyName.equals(\"Eb\"))\n return 3;\n if (keyName.equals(\"E\") || keyName.equals(\"Fb\"))\n return 4;\n if (keyName.equals(\"F\") || keyName.equals(\"E#\"))\n return 5;\n if (keyName.equals(\"F#\") || keyName.equals(\"Gb\"))\n return 6;\n if (keyName.equals(\"G\"))\n return 7;\n if (keyName.equals(\"G#\") || keyName.equals(\"Ab\"))\n return 8;\n if (keyName.equals(\"A\"))\n return 9;\n if (keyName.equals(\"A#\") || keyName.equals(\"Bb\"))\n return 10;\n if (keyName.equals(\"B\") || keyName.equals(\"Cb\"))\n return 11;\n else {\n ErrorLog.log(ErrorLog.SEVERE, \"Incorrect key formatting: \" + keyName);\n return -1;\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and converts it to a key as a String with flats if\n * accidentals are necessary\n * @param keyNum, a long describing a key\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY[(int) keyNum];\n } else if (keyNum == -1)\n return \"\";\n else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and whether or not to use sharps and converts it\n * to a key as a String\n * @param keyNum, a long describing a key\n * @boolean sharps, a boolean describing whether or not to use sharps\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum, boolean sharps) {\n if (sharps) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY_SHARPS[(int) keyNum];\n } else if (keyNum == -1) {\n return \"\";\n } else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n } else {\n return keyNumToName(keyNum);\n }\n }\n\n /**\n * processDictionary\n * Reads in all the dictionary information in the file to define appropriate\n * objects in the BrickDictionary.\n * @throws IOException\n */\n public void processDictionary(String dictionaryFilename) throws IOException {\n FileInputStream fis = new FileInputStream(dictionaryFilename);\n Tokenizer in = new Tokenizer(fis);\n in.slashSlashComments(true);\n in.slashStarComments(true);\n Object token;\n ArrayList equivalenceRules = new ArrayList();\n ArrayList diatonicRules = new ArrayList();\n LinkedHashMap> polymap = new LinkedHashMap>();\n brickMap.clear();\n // Read in S expressions until end of file is reached\n while ((token = in.nextSexp()) != Tokenizer.eof) {\n if (token instanceof Polylist) {\n Polylist contents = (Polylist) token;\n // Check that polylist has enough fields to be a brick\n // Needs BlockType (i.e. DEF_BRICK), name, key, and contents\n if (contents.length() < 2) {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for\" + \" a BrickDictionary item: \" + contents, true);\n } else {\n String blockCategory = contents.first().toString();\n contents = contents.rest();\n // Equivalence rules for the postprocessor\n if (blockCategory.equals(\"equiv\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty equivalence \" + \"rule in dictionary\");\n } else {\n Polylist chords = ChordSymbol.chordSymbolsFromStrings(contents);\n equivalenceRules.add(chords);\n }\n } else // Diatonic rules for the postprocessor\n if (blockCategory.equals(\"diatonic\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty diatonic \" + \"rule in dictionary\");\n } else {\n String modeTag = contents.first().toString();\n contents = contents.rest();\n Polylist p = ChordSymbol.chordSymbolsFromStrings(contents);\n p = p.cons(modeTag);\n diatonicRules.add(p);\n }\n } else // Type definitions with costs\n if (blockCategory.equals(\"brick-type\")) {\n if (contents.length() != 2 && contents.length() != 1)\n ErrorLog.log(ErrorLog.WARNING, \"Not a correct \" + \"brick-type declaration: \" + contents);\n else {\n String type = contents.first().toString();\n contents = contents.rest();\n if (contents.isEmpty()) {\n addType(type);\n } else {\n Object cost = contents.first();\n if (cost instanceof Long)\n addType(type, (Long) cost);\n else {\n ErrorLog.log(ErrorLog.WARNING, \"Incorrect \" + \"cost for brick type: \" + type);\n addType(type);\n }\n }\n }\n } else // Brick definitions themselves\n if (blockCategory.equals(DEF_BRICK) && contents.length() > 4) {\n // read in the information as a saved polylist to be\n // constructed properly as a Brick later\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n if (polymap.containsKey(brickName))\n polymap.get(brickName).add((Polylist) token);\n else {\n LinkedList newKey = new LinkedList();\n newKey.add((Polylist) token);\n polymap.put(brickName, newKey);\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper type for \" + \"a BrickDictionary item: \" + token, true);\n }\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for \" + \"a token: \" + token, true);\n }\n }\n // for each set of bricks with the same name\n for (LinkedList brickStem : polymap.values()) {\n // for each unprocessed brick definition\n for (Polylist contents : brickStem) {\n // pull out the name, qualifier, and contents\n contents = contents.rest();\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n String brickQualifier = \"\";\n if (contents.first() instanceof Polylist) {\n brickQualifier = ((Polylist) contents.first()).toStringSansParens();\n contents = contents.rest();\n }\n String brickMode = contents.first().toString();\n contents = contents.rest();\n String brickType = contents.first().toString();\n contents = contents.rest();\n if (!hasType(brickType))\n ErrorLog.log(ErrorLog.WARNING, brickName + \" is of \" + \"uninitialized type \" + brickType + \"; will register as non-brick\");\n String brickKeyString = contents.first().toString();\n contents = contents.rest();\n long brickKeyNum = keyNameToNum(brickKeyString);\n // add the brick, recursively defining subbricks\n Brick currentBrick = new Brick(brickName, brickQualifier, brickKeyNum, brickType, contents, this, brickMode, polymap);\n addBrick(currentBrick);\n }\n }\n // initialize the postprocessor with the rules for diatonic key checking\n processor = new PostProcessor(equivalenceRules, diatonicRules);\n }\n\n /**\n * dashless\n * Helper function to remove dashes from brick names\n * @param s, a String\n * @return a String with dashes replaced with spaces\n */\n public static String dashless(String s) {\n return s.replace('-', ' ');\n }\n\n public static String dashed(String s) {\n return s.replace(' ', '-');\n }\n\n /**\n * writeDictionary\n * Writes out an entire dictionary of definitions. Currently deprecated.\n * @param filename, the file to write to\n */\n public void writeDictionary(String filename) {\n FileWriter fstream;\n try {\n fstream = new FileWriter(filename);\n BufferedWriter out = new BufferedWriter(fstream);\n out.write(\"\\\\\\\\ Type Definitions\\n\\n\");\n Set types = costMap.keySet();\n for (String type : types) {\n long cost = costMap.get(type);\n Polylist brickType = Polylist.list(\"brick-type\", type, cost);\n out.write(brickType.toString());\n out.write(\"\\n\");\n }\n out.write(\"\\n\\n\\\\\\\\ Brick Definitions\\n\\n\");\n for (Brick brick : getFullMap()) {\n out.write(brick.toPolylist().toString());\n out.write(\"\\n\\n\");\n }\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not write dictionary file.\");\n }\n }\n // end of class BrickLibrary\n}\n"} {"task_id": "Java_1103", "language": "Java", "task_type": "method_body", "source_file": "java/github/Impro-Visor/Impro-Visor/src/imp/roadmap/brickdictionary/BrickLibrary.java", "mask_start_position": 11307, "mask_end_position": 11356, "canonical_solution": "{\n return (brickMap.containsKey(s));\n }", "pre_mask_code": "/**\n * This Java Class is part of the Impro-Visor Application\n */\npackage imp.roadmap.brickdictionary;\n\nimport imp.roadmap.cykparser.PostProcessor;\nimport imp.data.ChordSymbol;\nimport imp.util.ErrorLog;\nimport java.util.Collection;\nimport polya.*;\nimport java.io.*;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.Set;\n\n/**\n * purpose: Methods relating to the brick library (dictionary)\n * @author Zachary Merritt\n */\npublic class BrickLibrary {\n\n /**\n * Keyword used in defining bricks in a dictionary.\n */\n public static final String DEF_BRICK = \"defbrick\";\n\n /**\n * This is the conjunction to be used to describe appendages to Cadences\n * such as Overrun and Dropback\n */\n public static String CONJUNCTION = \" + \";\n\n /**\n * The name for an Overrun\n */\n public static String OVERRUN = \"Overrun\";\n\n /**\n * The name for a Dropback\n */\n public static String DROPBACK = \"Dropback\";\n\n // Lists of key names, with indices corresponding to numeric key value\n private static final String[] KEY_NAME_ARRAY = { \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\" };\n\n private static final String[] KEY_NAME_ARRAY_SHARPS = { \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\" };\n\n // the default cost of a type with no cost specified\n private static final long DEFAULT_COST = 40;\n\n // the string describing an invisible brick's type\n public static final String INVISIBLE = \"Invisible\";\n\n // all bricks\n private LinkedHashMap> brickMap;\n\n // brick costs by type\n private LinkedHashMap costMap;\n\n // the postprocessing unit\n public PostProcessor processor;\n\n /**\n * BrickLibrary / 0\n * Default constructor for an empty BrickLibrary with no specified types\n */\n public BrickLibrary() {\n brickMap = new LinkedHashMap>();\n costMap = new LinkedHashMap();\n }\n\n /**\n * getNames\n * Returns the list of the names of all bricks stored in the dictionary\n * @return an array of Strings\n */\n public String[] getNames() {\n return brickMap.keySet().toArray(new String[0]);\n }\n\n /**\n * addBrickDefinition\n * When a new brick is created in the library, adds its contents to the\n * current brickMap and adds its definition to the dictionary file\n * @param brick, a newly created Brick\n */\n public void addBrickDefinition(Brick brick, String dictionaryFilename) {\n // add the brick to the current BrickLibrary\n boolean added = addBrick(brick);\n if (!added)\n return;\n Brick definitionBrick = new Brick(brick);\n // make a properly-formatted brick definition\n Polylist defn = definitionBrick.toBrickDefinition();\n String defnString = defn.toString();\n if (!brick.getVariant().equals(\"\"))\n defnString.replaceFirst(\" \\\\(\", \"\\\\(\");\n defnString = defnString.replaceAll(\" \\\\(\", \"\\n \\\\(\");\n // write out the string with the definition to the end of the file\n try {\n FileOutputStream out = new FileOutputStream(dictionaryFilename, true);\n out.write(\"\\n\".getBytes());\n out.write(defnString.getBytes());\n out.write(\"\\n\".getBytes());\n out.close();\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Cannot write to dictionary\");\n }\n }\n\n /**\n * addBrick\n * Adds a brick to the library's brickMap\n * @param brick, a created Brick\n */\n public boolean addBrick(Brick brick) {\n if (brickMap.containsKey(brick.getName())) {\n // first, we check if the brick is a duplicate or just a brick with\n // an already-used name but a different qualifier. Presently, a\n // doubly-defined brick will have both definitions added to the\n // dictionary but will warn a user if the two definitions are\n LinkedList sameStemList = brickMap.get(brick.getName());\n for (Brick sameStem : sameStemList) {\n if (sameStem.getVariant().equals(brick.getVariant())) {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary already contains \" + brick.getName() + \"(\" + brick.getVariant() + \"): will not\" + \" add to dictionary\", true);\n return false;\n }\n }\n sameStemList.add(brick);\n } else {\n // adding a brick with a new brickname\n LinkedList brickList = new LinkedList();\n brickList.add(brick);\n this.brickMap.put(brick.name, brickList);\n }\n // special rule for creating overruns\n if (brick.getType().equals(\"Cadence\")) {\n String overrunName = brick.getName() + CONJUNCTION + OVERRUN;\n long overrunKeyNum = brick.getKey();\n String overrunType = OVERRUN;\n String overrunMode = brick.getMode();\n String overrunQualifier = brick.getVariant();\n // take blocks from regular cadence and add the next chord\n // in the circle of fifths with the same quality as the\n // resolution\n ArrayList overrunBlocks = new ArrayList();\n overrunBlocks.add(brick);\n ArrayList chords = brick.flattenBlock();\n ChordBlock prevChord = chords.get(chords.size() - 1);\n ChordBlock overrunChord = new ChordBlock(prevChord.transposeName(5), prevChord.getDuration());\n overrunBlocks.add(overrunChord);\n // make a new brick from this list of blocks\n Brick overrun = new Brick(overrunName, overrunQualifier, overrunKeyNum, overrunType, overrunBlocks, overrunMode);\n addBrick(overrun);\n String dropbackName = brick.getName() + CONJUNCTION + DROPBACK;\n long dropbackKeyNum = brick.getKey();\n String dropbackType = DROPBACK;\n String dropbackMode = brick.getMode();\n String dropbackQualifier = brick.getVariant();\n // take blocks from regular cadence and add a relative VI dominant\n // to form a dropback.\n // FIX: This is not the only possible dropback!!\n // For example, we want to allow iii-IV's major and minor.\n ArrayList dropbackBlocks = new ArrayList();\n dropbackBlocks.add(brick);\n String dropbackChordName = keyNumToName((brick.getKey() + 9) % 12);\n /* I think it was wrong to include this in the first place:\n \n if (dropbackMode.equals(\"minor\"))\n dropbackChordName += \"7b5\";\n else\n */\n dropbackChordName += 7;\n ChordBlock dropbackChord = new ChordBlock(dropbackChordName, prevChord.getDuration());\n dropbackBlocks.add(dropbackChord);\n // make a new brick from this list of blocks\n Brick dropback = new Brick(dropbackName, dropbackQualifier, dropbackKeyNum, dropbackType, dropbackBlocks, dropbackMode);\n addBrick(dropback);\n }\n return true;\n }\n\n /**\n * getBrick (definition)\n * Gets the default Brick with the given name from the dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k) {\n if (brickMap.containsKey(s)) {\n LinkedList possibleBricks = brickMap.get(s);\n for (Brick oldBrick : possibleBricks) if (!oldBrick.getType().equals(INVISIBLE)) {\n Brick brick = new Brick(oldBrick);\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n }\n }\n // if no brick is returned\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s + \" with qualifier \" + q, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with duration)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = new Brick(brickMap.get(s).getFirst());\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * hasBrick\n * Checks if a Brick with a given name is in the dictionary\n * @param s, the Brick name\n * @return a boolean\n */\n public boolean hasBrick(String s) ", "post_mask_code": "\n\n /**\n * getFullMap\n * Gets the list of all Bricks in the dictionary as a single collection\n * @return a Collection of Bricks\n */\n public Collection getFullMap() {\n LinkedList values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n values.addAll(brickname);\n }\n return values;\n }\n\n /**\n * getMap\n * Gets the organized list of all Bricks in the dictionary\n * @return a LinkedList of LinkedLists of Bricks\n */\n public LinkedList> getMap() {\n LinkedList> values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n LinkedList newlist = new LinkedList();\n for (Brick brick : brickname) if (!brick.getType().equals(INVISIBLE))\n newlist.add(brick);\n if (!newlist.isEmpty())\n values.add(newlist);\n }\n return values;\n }\n\n /**\n * removeBrick\n * Removes all Bricks matching a given Brick from the dictionary\n * @param brick, the Brick to be removed itself\n */\n public void removeBrick(Brick brick) {\n this.brickMap.remove(brick.name);\n }\n\n /**\n * removeBrick\n * Removes all Bricks with a given name from the dictionary\n * @param brickName, the name of the Brick(s) to be removed\n */\n public void removeBrick(String brickName) {\n this.brickMap.remove(brickName);\n }\n\n /**\n * exileBrick\n * Takes a Brick out of the visible brick library\n * @param brick, the brick to remove\n */\n public void exileBrick(Brick brick, String dictionaryFilename) {\n // define the search term (the name) for the given brick\n String brickType = \" \" + brick.getType() + \" \";\n String brickDefHead = DEF_BRICK + dashed(brick.getName());\n String qualifier = brick.getVariant();\n if (!qualifier.isEmpty())\n brickDefHead += \"(\" + qualifier + \")\";\n brickDefHead += \" \";\n // open the file and read in its contents\n try {\n File dictionary = new File(dictionaryFilename);\n FileReader in = new FileReader(dictionary);\n BufferedReader reader = new BufferedReader(in);\n String line = reader.readLine();\n String newfile = \"\";\n while (line != null) {\n // Exiling a brick is just taking the type and changing it\n // to be invisible\n if (line.contains(brickDefHead)) {\n line = line.replaceFirst(brickType, \" \" + INVISIBLE + \" \");\n }\n newfile += line + \"\\r\\n\";\n line = reader.readLine();\n }\n // write out the modified dictionary\n FileWriter writer = new FileWriter(dictionaryFilename);\n writer.write(newfile);\n writer.close();\n processDictionary(dictionaryFilename);\n } catch (IOException ioe) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not modify brick in dictionary\");\n }\n }\n\n /**\n * printDictionary\n * Prints every brick in the dictionary to System.err\n */\n public void printDictionary() {\n Iterator iter = getFullMap().iterator();\n while (iter.hasNext()) {\n Brick currentBrick = (Brick) iter.next();\n currentBrick.printBrick();\n }\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the default cost\n * @param t, a type, a String\n */\n public void addType(String t) {\n costMap.put(t, DEFAULT_COST);\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the specified cost\n * @param t, a type, a String\n * @param c, a cost, a long\n */\n public void addType(String t, long c) {\n costMap.put(t, c);\n }\n\n /**\n * getCost\n * Gets the cost associated with the given type\n * @param t, the type whose cost is desired (a String)\n * @return the cost, a long\n */\n public long getCost(String t) {\n if (!hasType(t))\n ErrorLog.log(ErrorLog.SEVERE, \"Type does not exist, will register\" + \"as an invisible brick: \" + t);\n return costMap.get(t);\n }\n\n /**\n * hasType\n * Checks if a given type is contained in the dictionary\n * @param t, a type (a String)\n * @return a boolean\n */\n public boolean hasType(String t) {\n return costMap.containsKey(t);\n }\n\n /**\n * getTypes\n * Gets the list of all types in the dictionary\n * @return an array of Strings of types\n */\n public String[] getTypes() {\n return costMap.keySet().toArray(new String[0]);\n }\n\n /**\n * isValidKey\n * Checks if a given key's name actually describes a key\n * @param keyName, a key's name as a String\n * @return a boolean\n */\n public static Boolean isValidKey(String keyName) {\n return keyName.equals(\"C\") || keyName.equals(\"B#\") || keyName.equals(\"C#\") || keyName.equals(\"Db\") || keyName.equals(\"D\") || keyName.equals(\"D#\") || keyName.equals(\"Eb\") || keyName.equals(\"E\") || keyName.equals(\"Fb\") || keyName.equals(\"F\") || keyName.equals(\"E#\") || keyName.equals(\"F#\") || keyName.equals(\"Gb\") || keyName.equals(\"G\") || keyName.equals(\"G#\") || keyName.equals(\"Ab\") || keyName.equals(\"A\") || keyName.equals(\"A#\") || keyName.equals(\"Bb\") || keyName.equals(\"B\") || keyName.equals(\"Cb\");\n }\n\n /**\n * keyNameToNum\n * Takes a key by name and returns the long describing that key\n * @param keyName, a key as a String\n * @return the same key as a long\n */\n public static long keyNameToNum(String keyName) {\n if (keyName.equals(\"\"))\n return -1;\n if (keyName.equals(\"C\") || keyName.equals(\"B#\"))\n return 0;\n if (keyName.equals(\"C#\") || keyName.equals(\"Db\"))\n return 1;\n if (keyName.equals(\"D\"))\n return 2;\n if (keyName.equals(\"D#\") || keyName.equals(\"Eb\"))\n return 3;\n if (keyName.equals(\"E\") || keyName.equals(\"Fb\"))\n return 4;\n if (keyName.equals(\"F\") || keyName.equals(\"E#\"))\n return 5;\n if (keyName.equals(\"F#\") || keyName.equals(\"Gb\"))\n return 6;\n if (keyName.equals(\"G\"))\n return 7;\n if (keyName.equals(\"G#\") || keyName.equals(\"Ab\"))\n return 8;\n if (keyName.equals(\"A\"))\n return 9;\n if (keyName.equals(\"A#\") || keyName.equals(\"Bb\"))\n return 10;\n if (keyName.equals(\"B\") || keyName.equals(\"Cb\"))\n return 11;\n else {\n ErrorLog.log(ErrorLog.SEVERE, \"Incorrect key formatting: \" + keyName);\n return -1;\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and converts it to a key as a String with flats if\n * accidentals are necessary\n * @param keyNum, a long describing a key\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY[(int) keyNum];\n } else if (keyNum == -1)\n return \"\";\n else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and whether or not to use sharps and converts it\n * to a key as a String\n * @param keyNum, a long describing a key\n * @boolean sharps, a boolean describing whether or not to use sharps\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum, boolean sharps) {\n if (sharps) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY_SHARPS[(int) keyNum];\n } else if (keyNum == -1) {\n return \"\";\n } else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n } else {\n return keyNumToName(keyNum);\n }\n }\n\n /**\n * processDictionary\n * Reads in all the dictionary information in the file to define appropriate\n * objects in the BrickDictionary.\n * @throws IOException\n */\n public void processDictionary(String dictionaryFilename) throws IOException {\n FileInputStream fis = new FileInputStream(dictionaryFilename);\n Tokenizer in = new Tokenizer(fis);\n in.slashSlashComments(true);\n in.slashStarComments(true);\n Object token;\n ArrayList equivalenceRules = new ArrayList();\n ArrayList diatonicRules = new ArrayList();\n LinkedHashMap> polymap = new LinkedHashMap>();\n brickMap.clear();\n // Read in S expressions until end of file is reached\n while ((token = in.nextSexp()) != Tokenizer.eof) {\n if (token instanceof Polylist) {\n Polylist contents = (Polylist) token;\n // Check that polylist has enough fields to be a brick\n // Needs BlockType (i.e. DEF_BRICK), name, key, and contents\n if (contents.length() < 2) {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for\" + \" a BrickDictionary item: \" + contents, true);\n } else {\n String blockCategory = contents.first().toString();\n contents = contents.rest();\n // Equivalence rules for the postprocessor\n if (blockCategory.equals(\"equiv\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty equivalence \" + \"rule in dictionary\");\n } else {\n Polylist chords = ChordSymbol.chordSymbolsFromStrings(contents);\n equivalenceRules.add(chords);\n }\n } else // Diatonic rules for the postprocessor\n if (blockCategory.equals(\"diatonic\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty diatonic \" + \"rule in dictionary\");\n } else {\n String modeTag = contents.first().toString();\n contents = contents.rest();\n Polylist p = ChordSymbol.chordSymbolsFromStrings(contents);\n p = p.cons(modeTag);\n diatonicRules.add(p);\n }\n } else // Type definitions with costs\n if (blockCategory.equals(\"brick-type\")) {\n if (contents.length() != 2 && contents.length() != 1)\n ErrorLog.log(ErrorLog.WARNING, \"Not a correct \" + \"brick-type declaration: \" + contents);\n else {\n String type = contents.first().toString();\n contents = contents.rest();\n if (contents.isEmpty()) {\n addType(type);\n } else {\n Object cost = contents.first();\n if (cost instanceof Long)\n addType(type, (Long) cost);\n else {\n ErrorLog.log(ErrorLog.WARNING, \"Incorrect \" + \"cost for brick type: \" + type);\n addType(type);\n }\n }\n }\n } else // Brick definitions themselves\n if (blockCategory.equals(DEF_BRICK) && contents.length() > 4) {\n // read in the information as a saved polylist to be\n // constructed properly as a Brick later\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n if (polymap.containsKey(brickName))\n polymap.get(brickName).add((Polylist) token);\n else {\n LinkedList newKey = new LinkedList();\n newKey.add((Polylist) token);\n polymap.put(brickName, newKey);\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper type for \" + \"a BrickDictionary item: \" + token, true);\n }\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for \" + \"a token: \" + token, true);\n }\n }\n // for each set of bricks with the same name\n for (LinkedList brickStem : polymap.values()) {\n // for each unprocessed brick definition\n for (Polylist contents : brickStem) {\n // pull out the name, qualifier, and contents\n contents = contents.rest();\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n String brickQualifier = \"\";\n if (contents.first() instanceof Polylist) {\n brickQualifier = ((Polylist) contents.first()).toStringSansParens();\n contents = contents.rest();\n }\n String brickMode = contents.first().toString();\n contents = contents.rest();\n String brickType = contents.first().toString();\n contents = contents.rest();\n if (!hasType(brickType))\n ErrorLog.log(ErrorLog.WARNING, brickName + \" is of \" + \"uninitialized type \" + brickType + \"; will register as non-brick\");\n String brickKeyString = contents.first().toString();\n contents = contents.rest();\n long brickKeyNum = keyNameToNum(brickKeyString);\n // add the brick, recursively defining subbricks\n Brick currentBrick = new Brick(brickName, brickQualifier, brickKeyNum, brickType, contents, this, brickMode, polymap);\n addBrick(currentBrick);\n }\n }\n // initialize the postprocessor with the rules for diatonic key checking\n processor = new PostProcessor(equivalenceRules, diatonicRules);\n }\n\n /**\n * dashless\n * Helper function to remove dashes from brick names\n * @param s, a String\n * @return a String with dashes replaced with spaces\n */\n public static String dashless(String s) {\n return s.replace('-', ' ');\n }\n\n public static String dashed(String s) {\n return s.replace(' ', '-');\n }\n\n /**\n * writeDictionary\n * Writes out an entire dictionary of definitions. Currently deprecated.\n * @param filename, the file to write to\n */\n public void writeDictionary(String filename) {\n FileWriter fstream;\n try {\n fstream = new FileWriter(filename);\n BufferedWriter out = new BufferedWriter(fstream);\n out.write(\"\\\\\\\\ Type Definitions\\n\\n\");\n Set types = costMap.keySet();\n for (String type : types) {\n long cost = costMap.get(type);\n Polylist brickType = Polylist.list(\"brick-type\", type, cost);\n out.write(brickType.toString());\n out.write(\"\\n\");\n }\n out.write(\"\\n\\n\\\\\\\\ Brick Definitions\\n\\n\");\n for (Brick brick : getFullMap()) {\n out.write(brick.toPolylist().toString());\n out.write(\"\\n\\n\");\n }\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not write dictionary file.\");\n }\n }\n // end of class BrickLibrary\n}\n"} {"task_id": "Java_1104", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Impro-Visor/Impro-Visor/src/imp/roadmap/brickdictionary/BrickLibrary.java", "mask_start_position": 13079, "mask_end_position": 13267, "canonical_solution": "\n // define the search term (the name) for the given brick\n String brickType = \" \" + brick.getType() + \" \";\n String brickDefHead = DEF_BRICK + dashed(brick.getName());", "pre_mask_code": "/**\n * This Java Class is part of the Impro-Visor Application\n */\npackage imp.roadmap.brickdictionary;\n\nimport imp.roadmap.cykparser.PostProcessor;\nimport imp.data.ChordSymbol;\nimport imp.util.ErrorLog;\nimport java.util.Collection;\nimport polya.*;\nimport java.io.*;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.Set;\n\n/**\n * purpose: Methods relating to the brick library (dictionary)\n * @author Zachary Merritt\n */\npublic class BrickLibrary {\n\n /**\n * Keyword used in defining bricks in a dictionary.\n */\n public static final String DEF_BRICK = \"defbrick\";\n\n /**\n * This is the conjunction to be used to describe appendages to Cadences\n * such as Overrun and Dropback\n */\n public static String CONJUNCTION = \" + \";\n\n /**\n * The name for an Overrun\n */\n public static String OVERRUN = \"Overrun\";\n\n /**\n * The name for a Dropback\n */\n public static String DROPBACK = \"Dropback\";\n\n // Lists of key names, with indices corresponding to numeric key value\n private static final String[] KEY_NAME_ARRAY = { \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\" };\n\n private static final String[] KEY_NAME_ARRAY_SHARPS = { \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\" };\n\n // the default cost of a type with no cost specified\n private static final long DEFAULT_COST = 40;\n\n // the string describing an invisible brick's type\n public static final String INVISIBLE = \"Invisible\";\n\n // all bricks\n private LinkedHashMap> brickMap;\n\n // brick costs by type\n private LinkedHashMap costMap;\n\n // the postprocessing unit\n public PostProcessor processor;\n\n /**\n * BrickLibrary / 0\n * Default constructor for an empty BrickLibrary with no specified types\n */\n public BrickLibrary() {\n brickMap = new LinkedHashMap>();\n costMap = new LinkedHashMap();\n }\n\n /**\n * getNames\n * Returns the list of the names of all bricks stored in the dictionary\n * @return an array of Strings\n */\n public String[] getNames() {\n return brickMap.keySet().toArray(new String[0]);\n }\n\n /**\n * addBrickDefinition\n * When a new brick is created in the library, adds its contents to the\n * current brickMap and adds its definition to the dictionary file\n * @param brick, a newly created Brick\n */\n public void addBrickDefinition(Brick brick, String dictionaryFilename) {\n // add the brick to the current BrickLibrary\n boolean added = addBrick(brick);\n if (!added)\n return;\n Brick definitionBrick = new Brick(brick);\n // make a properly-formatted brick definition\n Polylist defn = definitionBrick.toBrickDefinition();\n String defnString = defn.toString();\n if (!brick.getVariant().equals(\"\"))\n defnString.replaceFirst(\" \\\\(\", \"\\\\(\");\n defnString = defnString.replaceAll(\" \\\\(\", \"\\n \\\\(\");\n // write out the string with the definition to the end of the file\n try {\n FileOutputStream out = new FileOutputStream(dictionaryFilename, true);\n out.write(\"\\n\".getBytes());\n out.write(defnString.getBytes());\n out.write(\"\\n\".getBytes());\n out.close();\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Cannot write to dictionary\");\n }\n }\n\n /**\n * addBrick\n * Adds a brick to the library's brickMap\n * @param brick, a created Brick\n */\n public boolean addBrick(Brick brick) {\n if (brickMap.containsKey(brick.getName())) {\n // first, we check if the brick is a duplicate or just a brick with\n // an already-used name but a different qualifier. Presently, a\n // doubly-defined brick will have both definitions added to the\n // dictionary but will warn a user if the two definitions are\n LinkedList sameStemList = brickMap.get(brick.getName());\n for (Brick sameStem : sameStemList) {\n if (sameStem.getVariant().equals(brick.getVariant())) {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary already contains \" + brick.getName() + \"(\" + brick.getVariant() + \"): will not\" + \" add to dictionary\", true);\n return false;\n }\n }\n sameStemList.add(brick);\n } else {\n // adding a brick with a new brickname\n LinkedList brickList = new LinkedList();\n brickList.add(brick);\n this.brickMap.put(brick.name, brickList);\n }\n // special rule for creating overruns\n if (brick.getType().equals(\"Cadence\")) {\n String overrunName = brick.getName() + CONJUNCTION + OVERRUN;\n long overrunKeyNum = brick.getKey();\n String overrunType = OVERRUN;\n String overrunMode = brick.getMode();\n String overrunQualifier = brick.getVariant();\n // take blocks from regular cadence and add the next chord\n // in the circle of fifths with the same quality as the\n // resolution\n ArrayList overrunBlocks = new ArrayList();\n overrunBlocks.add(brick);\n ArrayList chords = brick.flattenBlock();\n ChordBlock prevChord = chords.get(chords.size() - 1);\n ChordBlock overrunChord = new ChordBlock(prevChord.transposeName(5), prevChord.getDuration());\n overrunBlocks.add(overrunChord);\n // make a new brick from this list of blocks\n Brick overrun = new Brick(overrunName, overrunQualifier, overrunKeyNum, overrunType, overrunBlocks, overrunMode);\n addBrick(overrun);\n String dropbackName = brick.getName() + CONJUNCTION + DROPBACK;\n long dropbackKeyNum = brick.getKey();\n String dropbackType = DROPBACK;\n String dropbackMode = brick.getMode();\n String dropbackQualifier = brick.getVariant();\n // take blocks from regular cadence and add a relative VI dominant\n // to form a dropback.\n // FIX: This is not the only possible dropback!!\n // For example, we want to allow iii-IV's major and minor.\n ArrayList dropbackBlocks = new ArrayList();\n dropbackBlocks.add(brick);\n String dropbackChordName = keyNumToName((brick.getKey() + 9) % 12);\n /* I think it was wrong to include this in the first place:\n \n if (dropbackMode.equals(\"minor\"))\n dropbackChordName += \"7b5\";\n else\n */\n dropbackChordName += 7;\n ChordBlock dropbackChord = new ChordBlock(dropbackChordName, prevChord.getDuration());\n dropbackBlocks.add(dropbackChord);\n // make a new brick from this list of blocks\n Brick dropback = new Brick(dropbackName, dropbackQualifier, dropbackKeyNum, dropbackType, dropbackBlocks, dropbackMode);\n addBrick(dropback);\n }\n return true;\n }\n\n /**\n * getBrick (definition)\n * Gets the default Brick with the given name from the dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k) {\n if (brickMap.containsKey(s)) {\n LinkedList possibleBricks = brickMap.get(s);\n for (Brick oldBrick : possibleBricks) if (!oldBrick.getType().equals(INVISIBLE)) {\n Brick brick = new Brick(oldBrick);\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n }\n }\n // if no brick is returned\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s + \" with qualifier \" + q, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with duration)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = new Brick(brickMap.get(s).getFirst());\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * hasBrick\n * Checks if a Brick with a given name is in the dictionary\n * @param s, the Brick name\n * @return a boolean\n */\n public boolean hasBrick(String s) {\n return (brickMap.containsKey(s));\n }\n\n /**\n * getFullMap\n * Gets the list of all Bricks in the dictionary as a single collection\n * @return a Collection of Bricks\n */\n public Collection getFullMap() {\n LinkedList values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n values.addAll(brickname);\n }\n return values;\n }\n\n /**\n * getMap\n * Gets the organized list of all Bricks in the dictionary\n * @return a LinkedList of LinkedLists of Bricks\n */\n public LinkedList> getMap() {\n LinkedList> values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n LinkedList newlist = new LinkedList();\n for (Brick brick : brickname) if (!brick.getType().equals(INVISIBLE))\n newlist.add(brick);\n if (!newlist.isEmpty())\n values.add(newlist);\n }\n return values;\n }\n\n /**\n * removeBrick\n * Removes all Bricks matching a given Brick from the dictionary\n * @param brick, the Brick to be removed itself\n */\n public void removeBrick(Brick brick) {\n this.brickMap.remove(brick.name);\n }\n\n /**\n * removeBrick\n * Removes all Bricks with a given name from the dictionary\n * @param brickName, the name of the Brick(s) to be removed\n */\n public void removeBrick(String brickName) {\n this.brickMap.remove(brickName);\n }\n\n /**\n * exileBrick\n * Takes a Brick out of the visible brick library\n * @param brick, the brick to remove\n */\n public void exileBrick(Brick brick, String dictionaryFilename) {", "post_mask_code": "\n String qualifier = brick.getVariant();\n if (!qualifier.isEmpty())\n brickDefHead += \"(\" + qualifier + \")\";\n brickDefHead += \" \";\n // open the file and read in its contents\n try {\n File dictionary = new File(dictionaryFilename);\n FileReader in = new FileReader(dictionary);\n BufferedReader reader = new BufferedReader(in);\n String line = reader.readLine();\n String newfile = \"\";\n while (line != null) {\n // Exiling a brick is just taking the type and changing it\n // to be invisible\n if (line.contains(brickDefHead)) {\n line = line.replaceFirst(brickType, \" \" + INVISIBLE + \" \");\n }\n newfile += line + \"\\r\\n\";\n line = reader.readLine();\n }\n // write out the modified dictionary\n FileWriter writer = new FileWriter(dictionaryFilename);\n writer.write(newfile);\n writer.close();\n processDictionary(dictionaryFilename);\n } catch (IOException ioe) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not modify brick in dictionary\");\n }\n }\n\n /**\n * printDictionary\n * Prints every brick in the dictionary to System.err\n */\n public void printDictionary() {\n Iterator iter = getFullMap().iterator();\n while (iter.hasNext()) {\n Brick currentBrick = (Brick) iter.next();\n currentBrick.printBrick();\n }\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the default cost\n * @param t, a type, a String\n */\n public void addType(String t) {\n costMap.put(t, DEFAULT_COST);\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the specified cost\n * @param t, a type, a String\n * @param c, a cost, a long\n */\n public void addType(String t, long c) {\n costMap.put(t, c);\n }\n\n /**\n * getCost\n * Gets the cost associated with the given type\n * @param t, the type whose cost is desired (a String)\n * @return the cost, a long\n */\n public long getCost(String t) {\n if (!hasType(t))\n ErrorLog.log(ErrorLog.SEVERE, \"Type does not exist, will register\" + \"as an invisible brick: \" + t);\n return costMap.get(t);\n }\n\n /**\n * hasType\n * Checks if a given type is contained in the dictionary\n * @param t, a type (a String)\n * @return a boolean\n */\n public boolean hasType(String t) {\n return costMap.containsKey(t);\n }\n\n /**\n * getTypes\n * Gets the list of all types in the dictionary\n * @return an array of Strings of types\n */\n public String[] getTypes() {\n return costMap.keySet().toArray(new String[0]);\n }\n\n /**\n * isValidKey\n * Checks if a given key's name actually describes a key\n * @param keyName, a key's name as a String\n * @return a boolean\n */\n public static Boolean isValidKey(String keyName) {\n return keyName.equals(\"C\") || keyName.equals(\"B#\") || keyName.equals(\"C#\") || keyName.equals(\"Db\") || keyName.equals(\"D\") || keyName.equals(\"D#\") || keyName.equals(\"Eb\") || keyName.equals(\"E\") || keyName.equals(\"Fb\") || keyName.equals(\"F\") || keyName.equals(\"E#\") || keyName.equals(\"F#\") || keyName.equals(\"Gb\") || keyName.equals(\"G\") || keyName.equals(\"G#\") || keyName.equals(\"Ab\") || keyName.equals(\"A\") || keyName.equals(\"A#\") || keyName.equals(\"Bb\") || keyName.equals(\"B\") || keyName.equals(\"Cb\");\n }\n\n /**\n * keyNameToNum\n * Takes a key by name and returns the long describing that key\n * @param keyName, a key as a String\n * @return the same key as a long\n */\n public static long keyNameToNum(String keyName) {\n if (keyName.equals(\"\"))\n return -1;\n if (keyName.equals(\"C\") || keyName.equals(\"B#\"))\n return 0;\n if (keyName.equals(\"C#\") || keyName.equals(\"Db\"))\n return 1;\n if (keyName.equals(\"D\"))\n return 2;\n if (keyName.equals(\"D#\") || keyName.equals(\"Eb\"))\n return 3;\n if (keyName.equals(\"E\") || keyName.equals(\"Fb\"))\n return 4;\n if (keyName.equals(\"F\") || keyName.equals(\"E#\"))\n return 5;\n if (keyName.equals(\"F#\") || keyName.equals(\"Gb\"))\n return 6;\n if (keyName.equals(\"G\"))\n return 7;\n if (keyName.equals(\"G#\") || keyName.equals(\"Ab\"))\n return 8;\n if (keyName.equals(\"A\"))\n return 9;\n if (keyName.equals(\"A#\") || keyName.equals(\"Bb\"))\n return 10;\n if (keyName.equals(\"B\") || keyName.equals(\"Cb\"))\n return 11;\n else {\n ErrorLog.log(ErrorLog.SEVERE, \"Incorrect key formatting: \" + keyName);\n return -1;\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and converts it to a key as a String with flats if\n * accidentals are necessary\n * @param keyNum, a long describing a key\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY[(int) keyNum];\n } else if (keyNum == -1)\n return \"\";\n else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and whether or not to use sharps and converts it\n * to a key as a String\n * @param keyNum, a long describing a key\n * @boolean sharps, a boolean describing whether or not to use sharps\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum, boolean sharps) {\n if (sharps) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY_SHARPS[(int) keyNum];\n } else if (keyNum == -1) {\n return \"\";\n } else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n } else {\n return keyNumToName(keyNum);\n }\n }\n\n /**\n * processDictionary\n * Reads in all the dictionary information in the file to define appropriate\n * objects in the BrickDictionary.\n * @throws IOException\n */\n public void processDictionary(String dictionaryFilename) throws IOException {\n FileInputStream fis = new FileInputStream(dictionaryFilename);\n Tokenizer in = new Tokenizer(fis);\n in.slashSlashComments(true);\n in.slashStarComments(true);\n Object token;\n ArrayList equivalenceRules = new ArrayList();\n ArrayList diatonicRules = new ArrayList();\n LinkedHashMap> polymap = new LinkedHashMap>();\n brickMap.clear();\n // Read in S expressions until end of file is reached\n while ((token = in.nextSexp()) != Tokenizer.eof) {\n if (token instanceof Polylist) {\n Polylist contents = (Polylist) token;\n // Check that polylist has enough fields to be a brick\n // Needs BlockType (i.e. DEF_BRICK), name, key, and contents\n if (contents.length() < 2) {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for\" + \" a BrickDictionary item: \" + contents, true);\n } else {\n String blockCategory = contents.first().toString();\n contents = contents.rest();\n // Equivalence rules for the postprocessor\n if (blockCategory.equals(\"equiv\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty equivalence \" + \"rule in dictionary\");\n } else {\n Polylist chords = ChordSymbol.chordSymbolsFromStrings(contents);\n equivalenceRules.add(chords);\n }\n } else // Diatonic rules for the postprocessor\n if (blockCategory.equals(\"diatonic\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty diatonic \" + \"rule in dictionary\");\n } else {\n String modeTag = contents.first().toString();\n contents = contents.rest();\n Polylist p = ChordSymbol.chordSymbolsFromStrings(contents);\n p = p.cons(modeTag);\n diatonicRules.add(p);\n }\n } else // Type definitions with costs\n if (blockCategory.equals(\"brick-type\")) {\n if (contents.length() != 2 && contents.length() != 1)\n ErrorLog.log(ErrorLog.WARNING, \"Not a correct \" + \"brick-type declaration: \" + contents);\n else {\n String type = contents.first().toString();\n contents = contents.rest();\n if (contents.isEmpty()) {\n addType(type);\n } else {\n Object cost = contents.first();\n if (cost instanceof Long)\n addType(type, (Long) cost);\n else {\n ErrorLog.log(ErrorLog.WARNING, \"Incorrect \" + \"cost for brick type: \" + type);\n addType(type);\n }\n }\n }\n } else // Brick definitions themselves\n if (blockCategory.equals(DEF_BRICK) && contents.length() > 4) {\n // read in the information as a saved polylist to be\n // constructed properly as a Brick later\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n if (polymap.containsKey(brickName))\n polymap.get(brickName).add((Polylist) token);\n else {\n LinkedList newKey = new LinkedList();\n newKey.add((Polylist) token);\n polymap.put(brickName, newKey);\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper type for \" + \"a BrickDictionary item: \" + token, true);\n }\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for \" + \"a token: \" + token, true);\n }\n }\n // for each set of bricks with the same name\n for (LinkedList brickStem : polymap.values()) {\n // for each unprocessed brick definition\n for (Polylist contents : brickStem) {\n // pull out the name, qualifier, and contents\n contents = contents.rest();\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n String brickQualifier = \"\";\n if (contents.first() instanceof Polylist) {\n brickQualifier = ((Polylist) contents.first()).toStringSansParens();\n contents = contents.rest();\n }\n String brickMode = contents.first().toString();\n contents = contents.rest();\n String brickType = contents.first().toString();\n contents = contents.rest();\n if (!hasType(brickType))\n ErrorLog.log(ErrorLog.WARNING, brickName + \" is of \" + \"uninitialized type \" + brickType + \"; will register as non-brick\");\n String brickKeyString = contents.first().toString();\n contents = contents.rest();\n long brickKeyNum = keyNameToNum(brickKeyString);\n // add the brick, recursively defining subbricks\n Brick currentBrick = new Brick(brickName, brickQualifier, brickKeyNum, brickType, contents, this, brickMode, polymap);\n addBrick(currentBrick);\n }\n }\n // initialize the postprocessor with the rules for diatonic key checking\n processor = new PostProcessor(equivalenceRules, diatonicRules);\n }\n\n /**\n * dashless\n * Helper function to remove dashes from brick names\n * @param s, a String\n * @return a String with dashes replaced with spaces\n */\n public static String dashless(String s) {\n return s.replace('-', ' ');\n }\n\n public static String dashed(String s) {\n return s.replace(' ', '-');\n }\n\n /**\n * writeDictionary\n * Writes out an entire dictionary of definitions. Currently deprecated.\n * @param filename, the file to write to\n */\n public void writeDictionary(String filename) {\n FileWriter fstream;\n try {\n fstream = new FileWriter(filename);\n BufferedWriter out = new BufferedWriter(fstream);\n out.write(\"\\\\\\\\ Type Definitions\\n\\n\");\n Set types = costMap.keySet();\n for (String type : types) {\n long cost = costMap.get(type);\n Polylist brickType = Polylist.list(\"brick-type\", type, cost);\n out.write(brickType.toString());\n out.write(\"\\n\");\n }\n out.write(\"\\n\\n\\\\\\\\ Brick Definitions\\n\\n\");\n for (Brick brick : getFullMap()) {\n out.write(brick.toPolylist().toString());\n out.write(\"\\n\\n\");\n }\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not write dictionary file.\");\n }\n }\n // end of class BrickLibrary\n}\n"} {"task_id": "Java_1105", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Impro-Visor/Impro-Visor/src/imp/roadmap/brickdictionary/BrickLibrary.java", "mask_start_position": 13276, "mask_end_position": 13428, "canonical_solution": "String qualifier = brick.getVariant();\n if (!qualifier.isEmpty())\n brickDefHead += \"(\" + qualifier + \")\";\n brickDefHead += \" \";", "pre_mask_code": "/**\n * This Java Class is part of the Impro-Visor Application\n */\npackage imp.roadmap.brickdictionary;\n\nimport imp.roadmap.cykparser.PostProcessor;\nimport imp.data.ChordSymbol;\nimport imp.util.ErrorLog;\nimport java.util.Collection;\nimport polya.*;\nimport java.io.*;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.Set;\n\n/**\n * purpose: Methods relating to the brick library (dictionary)\n * @author Zachary Merritt\n */\npublic class BrickLibrary {\n\n /**\n * Keyword used in defining bricks in a dictionary.\n */\n public static final String DEF_BRICK = \"defbrick\";\n\n /**\n * This is the conjunction to be used to describe appendages to Cadences\n * such as Overrun and Dropback\n */\n public static String CONJUNCTION = \" + \";\n\n /**\n * The name for an Overrun\n */\n public static String OVERRUN = \"Overrun\";\n\n /**\n * The name for a Dropback\n */\n public static String DROPBACK = \"Dropback\";\n\n // Lists of key names, with indices corresponding to numeric key value\n private static final String[] KEY_NAME_ARRAY = { \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\" };\n\n private static final String[] KEY_NAME_ARRAY_SHARPS = { \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\" };\n\n // the default cost of a type with no cost specified\n private static final long DEFAULT_COST = 40;\n\n // the string describing an invisible brick's type\n public static final String INVISIBLE = \"Invisible\";\n\n // all bricks\n private LinkedHashMap> brickMap;\n\n // brick costs by type\n private LinkedHashMap costMap;\n\n // the postprocessing unit\n public PostProcessor processor;\n\n /**\n * BrickLibrary / 0\n * Default constructor for an empty BrickLibrary with no specified types\n */\n public BrickLibrary() {\n brickMap = new LinkedHashMap>();\n costMap = new LinkedHashMap();\n }\n\n /**\n * getNames\n * Returns the list of the names of all bricks stored in the dictionary\n * @return an array of Strings\n */\n public String[] getNames() {\n return brickMap.keySet().toArray(new String[0]);\n }\n\n /**\n * addBrickDefinition\n * When a new brick is created in the library, adds its contents to the\n * current brickMap and adds its definition to the dictionary file\n * @param brick, a newly created Brick\n */\n public void addBrickDefinition(Brick brick, String dictionaryFilename) {\n // add the brick to the current BrickLibrary\n boolean added = addBrick(brick);\n if (!added)\n return;\n Brick definitionBrick = new Brick(brick);\n // make a properly-formatted brick definition\n Polylist defn = definitionBrick.toBrickDefinition();\n String defnString = defn.toString();\n if (!brick.getVariant().equals(\"\"))\n defnString.replaceFirst(\" \\\\(\", \"\\\\(\");\n defnString = defnString.replaceAll(\" \\\\(\", \"\\n \\\\(\");\n // write out the string with the definition to the end of the file\n try {\n FileOutputStream out = new FileOutputStream(dictionaryFilename, true);\n out.write(\"\\n\".getBytes());\n out.write(defnString.getBytes());\n out.write(\"\\n\".getBytes());\n out.close();\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Cannot write to dictionary\");\n }\n }\n\n /**\n * addBrick\n * Adds a brick to the library's brickMap\n * @param brick, a created Brick\n */\n public boolean addBrick(Brick brick) {\n if (brickMap.containsKey(brick.getName())) {\n // first, we check if the brick is a duplicate or just a brick with\n // an already-used name but a different qualifier. Presently, a\n // doubly-defined brick will have both definitions added to the\n // dictionary but will warn a user if the two definitions are\n LinkedList sameStemList = brickMap.get(brick.getName());\n for (Brick sameStem : sameStemList) {\n if (sameStem.getVariant().equals(brick.getVariant())) {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary already contains \" + brick.getName() + \"(\" + brick.getVariant() + \"): will not\" + \" add to dictionary\", true);\n return false;\n }\n }\n sameStemList.add(brick);\n } else {\n // adding a brick with a new brickname\n LinkedList brickList = new LinkedList();\n brickList.add(brick);\n this.brickMap.put(brick.name, brickList);\n }\n // special rule for creating overruns\n if (brick.getType().equals(\"Cadence\")) {\n String overrunName = brick.getName() + CONJUNCTION + OVERRUN;\n long overrunKeyNum = brick.getKey();\n String overrunType = OVERRUN;\n String overrunMode = brick.getMode();\n String overrunQualifier = brick.getVariant();\n // take blocks from regular cadence and add the next chord\n // in the circle of fifths with the same quality as the\n // resolution\n ArrayList overrunBlocks = new ArrayList();\n overrunBlocks.add(brick);\n ArrayList chords = brick.flattenBlock();\n ChordBlock prevChord = chords.get(chords.size() - 1);\n ChordBlock overrunChord = new ChordBlock(prevChord.transposeName(5), prevChord.getDuration());\n overrunBlocks.add(overrunChord);\n // make a new brick from this list of blocks\n Brick overrun = new Brick(overrunName, overrunQualifier, overrunKeyNum, overrunType, overrunBlocks, overrunMode);\n addBrick(overrun);\n String dropbackName = brick.getName() + CONJUNCTION + DROPBACK;\n long dropbackKeyNum = brick.getKey();\n String dropbackType = DROPBACK;\n String dropbackMode = brick.getMode();\n String dropbackQualifier = brick.getVariant();\n // take blocks from regular cadence and add a relative VI dominant\n // to form a dropback.\n // FIX: This is not the only possible dropback!!\n // For example, we want to allow iii-IV's major and minor.\n ArrayList dropbackBlocks = new ArrayList();\n dropbackBlocks.add(brick);\n String dropbackChordName = keyNumToName((brick.getKey() + 9) % 12);\n /* I think it was wrong to include this in the first place:\n \n if (dropbackMode.equals(\"minor\"))\n dropbackChordName += \"7b5\";\n else\n */\n dropbackChordName += 7;\n ChordBlock dropbackChord = new ChordBlock(dropbackChordName, prevChord.getDuration());\n dropbackBlocks.add(dropbackChord);\n // make a new brick from this list of blocks\n Brick dropback = new Brick(dropbackName, dropbackQualifier, dropbackKeyNum, dropbackType, dropbackBlocks, dropbackMode);\n addBrick(dropback);\n }\n return true;\n }\n\n /**\n * getBrick (definition)\n * Gets the default Brick with the given name from the dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k) {\n if (brickMap.containsKey(s)) {\n LinkedList possibleBricks = brickMap.get(s);\n for (Brick oldBrick : possibleBricks) if (!oldBrick.getType().equals(INVISIBLE)) {\n Brick brick = new Brick(oldBrick);\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n }\n }\n // if no brick is returned\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s + \" with qualifier \" + q, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with duration)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = new Brick(brickMap.get(s).getFirst());\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * hasBrick\n * Checks if a Brick with a given name is in the dictionary\n * @param s, the Brick name\n * @return a boolean\n */\n public boolean hasBrick(String s) {\n return (brickMap.containsKey(s));\n }\n\n /**\n * getFullMap\n * Gets the list of all Bricks in the dictionary as a single collection\n * @return a Collection of Bricks\n */\n public Collection getFullMap() {\n LinkedList values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n values.addAll(brickname);\n }\n return values;\n }\n\n /**\n * getMap\n * Gets the organized list of all Bricks in the dictionary\n * @return a LinkedList of LinkedLists of Bricks\n */\n public LinkedList> getMap() {\n LinkedList> values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n LinkedList newlist = new LinkedList();\n for (Brick brick : brickname) if (!brick.getType().equals(INVISIBLE))\n newlist.add(brick);\n if (!newlist.isEmpty())\n values.add(newlist);\n }\n return values;\n }\n\n /**\n * removeBrick\n * Removes all Bricks matching a given Brick from the dictionary\n * @param brick, the Brick to be removed itself\n */\n public void removeBrick(Brick brick) {\n this.brickMap.remove(brick.name);\n }\n\n /**\n * removeBrick\n * Removes all Bricks with a given name from the dictionary\n * @param brickName, the name of the Brick(s) to be removed\n */\n public void removeBrick(String brickName) {\n this.brickMap.remove(brickName);\n }\n\n /**\n * exileBrick\n * Takes a Brick out of the visible brick library\n * @param brick, the brick to remove\n */\n public void exileBrick(Brick brick, String dictionaryFilename) {\n // define the search term (the name) for the given brick\n String brickType = \" \" + brick.getType() + \" \";\n String brickDefHead = DEF_BRICK + dashed(brick.getName());\n ", "post_mask_code": "\n // open the file and read in its contents\n try {\n File dictionary = new File(dictionaryFilename);\n FileReader in = new FileReader(dictionary);\n BufferedReader reader = new BufferedReader(in);\n String line = reader.readLine();\n String newfile = \"\";\n while (line != null) {\n // Exiling a brick is just taking the type and changing it\n // to be invisible\n if (line.contains(brickDefHead)) {\n line = line.replaceFirst(brickType, \" \" + INVISIBLE + \" \");\n }\n newfile += line + \"\\r\\n\";\n line = reader.readLine();\n }\n // write out the modified dictionary\n FileWriter writer = new FileWriter(dictionaryFilename);\n writer.write(newfile);\n writer.close();\n processDictionary(dictionaryFilename);\n } catch (IOException ioe) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not modify brick in dictionary\");\n }\n }\n\n /**\n * printDictionary\n * Prints every brick in the dictionary to System.err\n */\n public void printDictionary() {\n Iterator iter = getFullMap().iterator();\n while (iter.hasNext()) {\n Brick currentBrick = (Brick) iter.next();\n currentBrick.printBrick();\n }\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the default cost\n * @param t, a type, a String\n */\n public void addType(String t) {\n costMap.put(t, DEFAULT_COST);\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the specified cost\n * @param t, a type, a String\n * @param c, a cost, a long\n */\n public void addType(String t, long c) {\n costMap.put(t, c);\n }\n\n /**\n * getCost\n * Gets the cost associated with the given type\n * @param t, the type whose cost is desired (a String)\n * @return the cost, a long\n */\n public long getCost(String t) {\n if (!hasType(t))\n ErrorLog.log(ErrorLog.SEVERE, \"Type does not exist, will register\" + \"as an invisible brick: \" + t);\n return costMap.get(t);\n }\n\n /**\n * hasType\n * Checks if a given type is contained in the dictionary\n * @param t, a type (a String)\n * @return a boolean\n */\n public boolean hasType(String t) {\n return costMap.containsKey(t);\n }\n\n /**\n * getTypes\n * Gets the list of all types in the dictionary\n * @return an array of Strings of types\n */\n public String[] getTypes() {\n return costMap.keySet().toArray(new String[0]);\n }\n\n /**\n * isValidKey\n * Checks if a given key's name actually describes a key\n * @param keyName, a key's name as a String\n * @return a boolean\n */\n public static Boolean isValidKey(String keyName) {\n return keyName.equals(\"C\") || keyName.equals(\"B#\") || keyName.equals(\"C#\") || keyName.equals(\"Db\") || keyName.equals(\"D\") || keyName.equals(\"D#\") || keyName.equals(\"Eb\") || keyName.equals(\"E\") || keyName.equals(\"Fb\") || keyName.equals(\"F\") || keyName.equals(\"E#\") || keyName.equals(\"F#\") || keyName.equals(\"Gb\") || keyName.equals(\"G\") || keyName.equals(\"G#\") || keyName.equals(\"Ab\") || keyName.equals(\"A\") || keyName.equals(\"A#\") || keyName.equals(\"Bb\") || keyName.equals(\"B\") || keyName.equals(\"Cb\");\n }\n\n /**\n * keyNameToNum\n * Takes a key by name and returns the long describing that key\n * @param keyName, a key as a String\n * @return the same key as a long\n */\n public static long keyNameToNum(String keyName) {\n if (keyName.equals(\"\"))\n return -1;\n if (keyName.equals(\"C\") || keyName.equals(\"B#\"))\n return 0;\n if (keyName.equals(\"C#\") || keyName.equals(\"Db\"))\n return 1;\n if (keyName.equals(\"D\"))\n return 2;\n if (keyName.equals(\"D#\") || keyName.equals(\"Eb\"))\n return 3;\n if (keyName.equals(\"E\") || keyName.equals(\"Fb\"))\n return 4;\n if (keyName.equals(\"F\") || keyName.equals(\"E#\"))\n return 5;\n if (keyName.equals(\"F#\") || keyName.equals(\"Gb\"))\n return 6;\n if (keyName.equals(\"G\"))\n return 7;\n if (keyName.equals(\"G#\") || keyName.equals(\"Ab\"))\n return 8;\n if (keyName.equals(\"A\"))\n return 9;\n if (keyName.equals(\"A#\") || keyName.equals(\"Bb\"))\n return 10;\n if (keyName.equals(\"B\") || keyName.equals(\"Cb\"))\n return 11;\n else {\n ErrorLog.log(ErrorLog.SEVERE, \"Incorrect key formatting: \" + keyName);\n return -1;\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and converts it to a key as a String with flats if\n * accidentals are necessary\n * @param keyNum, a long describing a key\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY[(int) keyNum];\n } else if (keyNum == -1)\n return \"\";\n else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and whether or not to use sharps and converts it\n * to a key as a String\n * @param keyNum, a long describing a key\n * @boolean sharps, a boolean describing whether or not to use sharps\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum, boolean sharps) {\n if (sharps) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY_SHARPS[(int) keyNum];\n } else if (keyNum == -1) {\n return \"\";\n } else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n } else {\n return keyNumToName(keyNum);\n }\n }\n\n /**\n * processDictionary\n * Reads in all the dictionary information in the file to define appropriate\n * objects in the BrickDictionary.\n * @throws IOException\n */\n public void processDictionary(String dictionaryFilename) throws IOException {\n FileInputStream fis = new FileInputStream(dictionaryFilename);\n Tokenizer in = new Tokenizer(fis);\n in.slashSlashComments(true);\n in.slashStarComments(true);\n Object token;\n ArrayList equivalenceRules = new ArrayList();\n ArrayList diatonicRules = new ArrayList();\n LinkedHashMap> polymap = new LinkedHashMap>();\n brickMap.clear();\n // Read in S expressions until end of file is reached\n while ((token = in.nextSexp()) != Tokenizer.eof) {\n if (token instanceof Polylist) {\n Polylist contents = (Polylist) token;\n // Check that polylist has enough fields to be a brick\n // Needs BlockType (i.e. DEF_BRICK), name, key, and contents\n if (contents.length() < 2) {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for\" + \" a BrickDictionary item: \" + contents, true);\n } else {\n String blockCategory = contents.first().toString();\n contents = contents.rest();\n // Equivalence rules for the postprocessor\n if (blockCategory.equals(\"equiv\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty equivalence \" + \"rule in dictionary\");\n } else {\n Polylist chords = ChordSymbol.chordSymbolsFromStrings(contents);\n equivalenceRules.add(chords);\n }\n } else // Diatonic rules for the postprocessor\n if (blockCategory.equals(\"diatonic\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty diatonic \" + \"rule in dictionary\");\n } else {\n String modeTag = contents.first().toString();\n contents = contents.rest();\n Polylist p = ChordSymbol.chordSymbolsFromStrings(contents);\n p = p.cons(modeTag);\n diatonicRules.add(p);\n }\n } else // Type definitions with costs\n if (blockCategory.equals(\"brick-type\")) {\n if (contents.length() != 2 && contents.length() != 1)\n ErrorLog.log(ErrorLog.WARNING, \"Not a correct \" + \"brick-type declaration: \" + contents);\n else {\n String type = contents.first().toString();\n contents = contents.rest();\n if (contents.isEmpty()) {\n addType(type);\n } else {\n Object cost = contents.first();\n if (cost instanceof Long)\n addType(type, (Long) cost);\n else {\n ErrorLog.log(ErrorLog.WARNING, \"Incorrect \" + \"cost for brick type: \" + type);\n addType(type);\n }\n }\n }\n } else // Brick definitions themselves\n if (blockCategory.equals(DEF_BRICK) && contents.length() > 4) {\n // read in the information as a saved polylist to be\n // constructed properly as a Brick later\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n if (polymap.containsKey(brickName))\n polymap.get(brickName).add((Polylist) token);\n else {\n LinkedList newKey = new LinkedList();\n newKey.add((Polylist) token);\n polymap.put(brickName, newKey);\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper type for \" + \"a BrickDictionary item: \" + token, true);\n }\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for \" + \"a token: \" + token, true);\n }\n }\n // for each set of bricks with the same name\n for (LinkedList brickStem : polymap.values()) {\n // for each unprocessed brick definition\n for (Polylist contents : brickStem) {\n // pull out the name, qualifier, and contents\n contents = contents.rest();\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n String brickQualifier = \"\";\n if (contents.first() instanceof Polylist) {\n brickQualifier = ((Polylist) contents.first()).toStringSansParens();\n contents = contents.rest();\n }\n String brickMode = contents.first().toString();\n contents = contents.rest();\n String brickType = contents.first().toString();\n contents = contents.rest();\n if (!hasType(brickType))\n ErrorLog.log(ErrorLog.WARNING, brickName + \" is of \" + \"uninitialized type \" + brickType + \"; will register as non-brick\");\n String brickKeyString = contents.first().toString();\n contents = contents.rest();\n long brickKeyNum = keyNameToNum(brickKeyString);\n // add the brick, recursively defining subbricks\n Brick currentBrick = new Brick(brickName, brickQualifier, brickKeyNum, brickType, contents, this, brickMode, polymap);\n addBrick(currentBrick);\n }\n }\n // initialize the postprocessor with the rules for diatonic key checking\n processor = new PostProcessor(equivalenceRules, diatonicRules);\n }\n\n /**\n * dashless\n * Helper function to remove dashes from brick names\n * @param s, a String\n * @return a String with dashes replaced with spaces\n */\n public static String dashless(String s) {\n return s.replace('-', ' ');\n }\n\n public static String dashed(String s) {\n return s.replace(' ', '-');\n }\n\n /**\n * writeDictionary\n * Writes out an entire dictionary of definitions. Currently deprecated.\n * @param filename, the file to write to\n */\n public void writeDictionary(String filename) {\n FileWriter fstream;\n try {\n fstream = new FileWriter(filename);\n BufferedWriter out = new BufferedWriter(fstream);\n out.write(\"\\\\\\\\ Type Definitions\\n\\n\");\n Set types = costMap.keySet();\n for (String type : types) {\n long cost = costMap.get(type);\n Polylist brickType = Polylist.list(\"brick-type\", type, cost);\n out.write(brickType.toString());\n out.write(\"\\n\");\n }\n out.write(\"\\n\\n\\\\\\\\ Brick Definitions\\n\\n\");\n for (Brick brick : getFullMap()) {\n out.write(brick.toPolylist().toString());\n out.write(\"\\n\\n\");\n }\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not write dictionary file.\");\n }\n }\n // end of class BrickLibrary\n}\n"} {"task_id": "Java_1106", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Impro-Visor/Impro-Visor/src/imp/roadmap/brickdictionary/BrickLibrary.java", "mask_start_position": 13437, "mask_end_position": 14504, "canonical_solution": "// open the file and read in its contents\n try {\n File dictionary = new File(dictionaryFilename);\n FileReader in = new FileReader(dictionary);\n BufferedReader reader = new BufferedReader(in);\n String line = reader.readLine();\n String newfile = \"\";\n while (line != null) {\n // Exiling a brick is just taking the type and changing it\n // to be invisible\n if (line.contains(brickDefHead)) {\n line = line.replaceFirst(brickType, \" \" + INVISIBLE + \" \");\n }\n newfile += line + \"\\r\\n\";\n line = reader.readLine();\n }\n // write out the modified dictionary\n FileWriter writer = new FileWriter(dictionaryFilename);\n writer.write(newfile);\n writer.close();\n processDictionary(dictionaryFilename);\n } catch (IOException ioe) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not modify brick in dictionary\");\n }\n }", "pre_mask_code": "/**\n * This Java Class is part of the Impro-Visor Application\n */\npackage imp.roadmap.brickdictionary;\n\nimport imp.roadmap.cykparser.PostProcessor;\nimport imp.data.ChordSymbol;\nimport imp.util.ErrorLog;\nimport java.util.Collection;\nimport polya.*;\nimport java.io.*;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.Set;\n\n/**\n * purpose: Methods relating to the brick library (dictionary)\n * @author Zachary Merritt\n */\npublic class BrickLibrary {\n\n /**\n * Keyword used in defining bricks in a dictionary.\n */\n public static final String DEF_BRICK = \"defbrick\";\n\n /**\n * This is the conjunction to be used to describe appendages to Cadences\n * such as Overrun and Dropback\n */\n public static String CONJUNCTION = \" + \";\n\n /**\n * The name for an Overrun\n */\n public static String OVERRUN = \"Overrun\";\n\n /**\n * The name for a Dropback\n */\n public static String DROPBACK = \"Dropback\";\n\n // Lists of key names, with indices corresponding to numeric key value\n private static final String[] KEY_NAME_ARRAY = { \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\" };\n\n private static final String[] KEY_NAME_ARRAY_SHARPS = { \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\" };\n\n // the default cost of a type with no cost specified\n private static final long DEFAULT_COST = 40;\n\n // the string describing an invisible brick's type\n public static final String INVISIBLE = \"Invisible\";\n\n // all bricks\n private LinkedHashMap> brickMap;\n\n // brick costs by type\n private LinkedHashMap costMap;\n\n // the postprocessing unit\n public PostProcessor processor;\n\n /**\n * BrickLibrary / 0\n * Default constructor for an empty BrickLibrary with no specified types\n */\n public BrickLibrary() {\n brickMap = new LinkedHashMap>();\n costMap = new LinkedHashMap();\n }\n\n /**\n * getNames\n * Returns the list of the names of all bricks stored in the dictionary\n * @return an array of Strings\n */\n public String[] getNames() {\n return brickMap.keySet().toArray(new String[0]);\n }\n\n /**\n * addBrickDefinition\n * When a new brick is created in the library, adds its contents to the\n * current brickMap and adds its definition to the dictionary file\n * @param brick, a newly created Brick\n */\n public void addBrickDefinition(Brick brick, String dictionaryFilename) {\n // add the brick to the current BrickLibrary\n boolean added = addBrick(brick);\n if (!added)\n return;\n Brick definitionBrick = new Brick(brick);\n // make a properly-formatted brick definition\n Polylist defn = definitionBrick.toBrickDefinition();\n String defnString = defn.toString();\n if (!brick.getVariant().equals(\"\"))\n defnString.replaceFirst(\" \\\\(\", \"\\\\(\");\n defnString = defnString.replaceAll(\" \\\\(\", \"\\n \\\\(\");\n // write out the string with the definition to the end of the file\n try {\n FileOutputStream out = new FileOutputStream(dictionaryFilename, true);\n out.write(\"\\n\".getBytes());\n out.write(defnString.getBytes());\n out.write(\"\\n\".getBytes());\n out.close();\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Cannot write to dictionary\");\n }\n }\n\n /**\n * addBrick\n * Adds a brick to the library's brickMap\n * @param brick, a created Brick\n */\n public boolean addBrick(Brick brick) {\n if (brickMap.containsKey(brick.getName())) {\n // first, we check if the brick is a duplicate or just a brick with\n // an already-used name but a different qualifier. Presently, a\n // doubly-defined brick will have both definitions added to the\n // dictionary but will warn a user if the two definitions are\n LinkedList sameStemList = brickMap.get(brick.getName());\n for (Brick sameStem : sameStemList) {\n if (sameStem.getVariant().equals(brick.getVariant())) {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary already contains \" + brick.getName() + \"(\" + brick.getVariant() + \"): will not\" + \" add to dictionary\", true);\n return false;\n }\n }\n sameStemList.add(brick);\n } else {\n // adding a brick with a new brickname\n LinkedList brickList = new LinkedList();\n brickList.add(brick);\n this.brickMap.put(brick.name, brickList);\n }\n // special rule for creating overruns\n if (brick.getType().equals(\"Cadence\")) {\n String overrunName = brick.getName() + CONJUNCTION + OVERRUN;\n long overrunKeyNum = brick.getKey();\n String overrunType = OVERRUN;\n String overrunMode = brick.getMode();\n String overrunQualifier = brick.getVariant();\n // take blocks from regular cadence and add the next chord\n // in the circle of fifths with the same quality as the\n // resolution\n ArrayList overrunBlocks = new ArrayList();\n overrunBlocks.add(brick);\n ArrayList chords = brick.flattenBlock();\n ChordBlock prevChord = chords.get(chords.size() - 1);\n ChordBlock overrunChord = new ChordBlock(prevChord.transposeName(5), prevChord.getDuration());\n overrunBlocks.add(overrunChord);\n // make a new brick from this list of blocks\n Brick overrun = new Brick(overrunName, overrunQualifier, overrunKeyNum, overrunType, overrunBlocks, overrunMode);\n addBrick(overrun);\n String dropbackName = brick.getName() + CONJUNCTION + DROPBACK;\n long dropbackKeyNum = brick.getKey();\n String dropbackType = DROPBACK;\n String dropbackMode = brick.getMode();\n String dropbackQualifier = brick.getVariant();\n // take blocks from regular cadence and add a relative VI dominant\n // to form a dropback.\n // FIX: This is not the only possible dropback!!\n // For example, we want to allow iii-IV's major and minor.\n ArrayList dropbackBlocks = new ArrayList();\n dropbackBlocks.add(brick);\n String dropbackChordName = keyNumToName((brick.getKey() + 9) % 12);\n /* I think it was wrong to include this in the first place:\n \n if (dropbackMode.equals(\"minor\"))\n dropbackChordName += \"7b5\";\n else\n */\n dropbackChordName += 7;\n ChordBlock dropbackChord = new ChordBlock(dropbackChordName, prevChord.getDuration());\n dropbackBlocks.add(dropbackChord);\n // make a new brick from this list of blocks\n Brick dropback = new Brick(dropbackName, dropbackQualifier, dropbackKeyNum, dropbackType, dropbackBlocks, dropbackMode);\n addBrick(dropback);\n }\n return true;\n }\n\n /**\n * getBrick (definition)\n * Gets the default Brick with the given name from the dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k) {\n if (brickMap.containsKey(s)) {\n LinkedList possibleBricks = brickMap.get(s);\n for (Brick oldBrick : possibleBricks) if (!oldBrick.getType().equals(INVISIBLE)) {\n Brick brick = new Brick(oldBrick);\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n }\n }\n // if no brick is returned\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s + \" with qualifier \" + q, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with duration)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = new Brick(brickMap.get(s).getFirst());\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * hasBrick\n * Checks if a Brick with a given name is in the dictionary\n * @param s, the Brick name\n * @return a boolean\n */\n public boolean hasBrick(String s) {\n return (brickMap.containsKey(s));\n }\n\n /**\n * getFullMap\n * Gets the list of all Bricks in the dictionary as a single collection\n * @return a Collection of Bricks\n */\n public Collection getFullMap() {\n LinkedList values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n values.addAll(brickname);\n }\n return values;\n }\n\n /**\n * getMap\n * Gets the organized list of all Bricks in the dictionary\n * @return a LinkedList of LinkedLists of Bricks\n */\n public LinkedList> getMap() {\n LinkedList> values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n LinkedList newlist = new LinkedList();\n for (Brick brick : brickname) if (!brick.getType().equals(INVISIBLE))\n newlist.add(brick);\n if (!newlist.isEmpty())\n values.add(newlist);\n }\n return values;\n }\n\n /**\n * removeBrick\n * Removes all Bricks matching a given Brick from the dictionary\n * @param brick, the Brick to be removed itself\n */\n public void removeBrick(Brick brick) {\n this.brickMap.remove(brick.name);\n }\n\n /**\n * removeBrick\n * Removes all Bricks with a given name from the dictionary\n * @param brickName, the name of the Brick(s) to be removed\n */\n public void removeBrick(String brickName) {\n this.brickMap.remove(brickName);\n }\n\n /**\n * exileBrick\n * Takes a Brick out of the visible brick library\n * @param brick, the brick to remove\n */\n public void exileBrick(Brick brick, String dictionaryFilename) {\n // define the search term (the name) for the given brick\n String brickType = \" \" + brick.getType() + \" \";\n String brickDefHead = DEF_BRICK + dashed(brick.getName());\n String qualifier = brick.getVariant();\n if (!qualifier.isEmpty())\n brickDefHead += \"(\" + qualifier + \")\";\n brickDefHead += \" \";\n ", "post_mask_code": "\n\n /**\n * printDictionary\n * Prints every brick in the dictionary to System.err\n */\n public void printDictionary() {\n Iterator iter = getFullMap().iterator();\n while (iter.hasNext()) {\n Brick currentBrick = (Brick) iter.next();\n currentBrick.printBrick();\n }\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the default cost\n * @param t, a type, a String\n */\n public void addType(String t) {\n costMap.put(t, DEFAULT_COST);\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the specified cost\n * @param t, a type, a String\n * @param c, a cost, a long\n */\n public void addType(String t, long c) {\n costMap.put(t, c);\n }\n\n /**\n * getCost\n * Gets the cost associated with the given type\n * @param t, the type whose cost is desired (a String)\n * @return the cost, a long\n */\n public long getCost(String t) {\n if (!hasType(t))\n ErrorLog.log(ErrorLog.SEVERE, \"Type does not exist, will register\" + \"as an invisible brick: \" + t);\n return costMap.get(t);\n }\n\n /**\n * hasType\n * Checks if a given type is contained in the dictionary\n * @param t, a type (a String)\n * @return a boolean\n */\n public boolean hasType(String t) {\n return costMap.containsKey(t);\n }\n\n /**\n * getTypes\n * Gets the list of all types in the dictionary\n * @return an array of Strings of types\n */\n public String[] getTypes() {\n return costMap.keySet().toArray(new String[0]);\n }\n\n /**\n * isValidKey\n * Checks if a given key's name actually describes a key\n * @param keyName, a key's name as a String\n * @return a boolean\n */\n public static Boolean isValidKey(String keyName) {\n return keyName.equals(\"C\") || keyName.equals(\"B#\") || keyName.equals(\"C#\") || keyName.equals(\"Db\") || keyName.equals(\"D\") || keyName.equals(\"D#\") || keyName.equals(\"Eb\") || keyName.equals(\"E\") || keyName.equals(\"Fb\") || keyName.equals(\"F\") || keyName.equals(\"E#\") || keyName.equals(\"F#\") || keyName.equals(\"Gb\") || keyName.equals(\"G\") || keyName.equals(\"G#\") || keyName.equals(\"Ab\") || keyName.equals(\"A\") || keyName.equals(\"A#\") || keyName.equals(\"Bb\") || keyName.equals(\"B\") || keyName.equals(\"Cb\");\n }\n\n /**\n * keyNameToNum\n * Takes a key by name and returns the long describing that key\n * @param keyName, a key as a String\n * @return the same key as a long\n */\n public static long keyNameToNum(String keyName) {\n if (keyName.equals(\"\"))\n return -1;\n if (keyName.equals(\"C\") || keyName.equals(\"B#\"))\n return 0;\n if (keyName.equals(\"C#\") || keyName.equals(\"Db\"))\n return 1;\n if (keyName.equals(\"D\"))\n return 2;\n if (keyName.equals(\"D#\") || keyName.equals(\"Eb\"))\n return 3;\n if (keyName.equals(\"E\") || keyName.equals(\"Fb\"))\n return 4;\n if (keyName.equals(\"F\") || keyName.equals(\"E#\"))\n return 5;\n if (keyName.equals(\"F#\") || keyName.equals(\"Gb\"))\n return 6;\n if (keyName.equals(\"G\"))\n return 7;\n if (keyName.equals(\"G#\") || keyName.equals(\"Ab\"))\n return 8;\n if (keyName.equals(\"A\"))\n return 9;\n if (keyName.equals(\"A#\") || keyName.equals(\"Bb\"))\n return 10;\n if (keyName.equals(\"B\") || keyName.equals(\"Cb\"))\n return 11;\n else {\n ErrorLog.log(ErrorLog.SEVERE, \"Incorrect key formatting: \" + keyName);\n return -1;\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and converts it to a key as a String with flats if\n * accidentals are necessary\n * @param keyNum, a long describing a key\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY[(int) keyNum];\n } else if (keyNum == -1)\n return \"\";\n else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and whether or not to use sharps and converts it\n * to a key as a String\n * @param keyNum, a long describing a key\n * @boolean sharps, a boolean describing whether or not to use sharps\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum, boolean sharps) {\n if (sharps) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY_SHARPS[(int) keyNum];\n } else if (keyNum == -1) {\n return \"\";\n } else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n } else {\n return keyNumToName(keyNum);\n }\n }\n\n /**\n * processDictionary\n * Reads in all the dictionary information in the file to define appropriate\n * objects in the BrickDictionary.\n * @throws IOException\n */\n public void processDictionary(String dictionaryFilename) throws IOException {\n FileInputStream fis = new FileInputStream(dictionaryFilename);\n Tokenizer in = new Tokenizer(fis);\n in.slashSlashComments(true);\n in.slashStarComments(true);\n Object token;\n ArrayList equivalenceRules = new ArrayList();\n ArrayList diatonicRules = new ArrayList();\n LinkedHashMap> polymap = new LinkedHashMap>();\n brickMap.clear();\n // Read in S expressions until end of file is reached\n while ((token = in.nextSexp()) != Tokenizer.eof) {\n if (token instanceof Polylist) {\n Polylist contents = (Polylist) token;\n // Check that polylist has enough fields to be a brick\n // Needs BlockType (i.e. DEF_BRICK), name, key, and contents\n if (contents.length() < 2) {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for\" + \" a BrickDictionary item: \" + contents, true);\n } else {\n String blockCategory = contents.first().toString();\n contents = contents.rest();\n // Equivalence rules for the postprocessor\n if (blockCategory.equals(\"equiv\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty equivalence \" + \"rule in dictionary\");\n } else {\n Polylist chords = ChordSymbol.chordSymbolsFromStrings(contents);\n equivalenceRules.add(chords);\n }\n } else // Diatonic rules for the postprocessor\n if (blockCategory.equals(\"diatonic\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty diatonic \" + \"rule in dictionary\");\n } else {\n String modeTag = contents.first().toString();\n contents = contents.rest();\n Polylist p = ChordSymbol.chordSymbolsFromStrings(contents);\n p = p.cons(modeTag);\n diatonicRules.add(p);\n }\n } else // Type definitions with costs\n if (blockCategory.equals(\"brick-type\")) {\n if (contents.length() != 2 && contents.length() != 1)\n ErrorLog.log(ErrorLog.WARNING, \"Not a correct \" + \"brick-type declaration: \" + contents);\n else {\n String type = contents.first().toString();\n contents = contents.rest();\n if (contents.isEmpty()) {\n addType(type);\n } else {\n Object cost = contents.first();\n if (cost instanceof Long)\n addType(type, (Long) cost);\n else {\n ErrorLog.log(ErrorLog.WARNING, \"Incorrect \" + \"cost for brick type: \" + type);\n addType(type);\n }\n }\n }\n } else // Brick definitions themselves\n if (blockCategory.equals(DEF_BRICK) && contents.length() > 4) {\n // read in the information as a saved polylist to be\n // constructed properly as a Brick later\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n if (polymap.containsKey(brickName))\n polymap.get(brickName).add((Polylist) token);\n else {\n LinkedList newKey = new LinkedList();\n newKey.add((Polylist) token);\n polymap.put(brickName, newKey);\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper type for \" + \"a BrickDictionary item: \" + token, true);\n }\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for \" + \"a token: \" + token, true);\n }\n }\n // for each set of bricks with the same name\n for (LinkedList brickStem : polymap.values()) {\n // for each unprocessed brick definition\n for (Polylist contents : brickStem) {\n // pull out the name, qualifier, and contents\n contents = contents.rest();\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n String brickQualifier = \"\";\n if (contents.first() instanceof Polylist) {\n brickQualifier = ((Polylist) contents.first()).toStringSansParens();\n contents = contents.rest();\n }\n String brickMode = contents.first().toString();\n contents = contents.rest();\n String brickType = contents.first().toString();\n contents = contents.rest();\n if (!hasType(brickType))\n ErrorLog.log(ErrorLog.WARNING, brickName + \" is of \" + \"uninitialized type \" + brickType + \"; will register as non-brick\");\n String brickKeyString = contents.first().toString();\n contents = contents.rest();\n long brickKeyNum = keyNameToNum(brickKeyString);\n // add the brick, recursively defining subbricks\n Brick currentBrick = new Brick(brickName, brickQualifier, brickKeyNum, brickType, contents, this, brickMode, polymap);\n addBrick(currentBrick);\n }\n }\n // initialize the postprocessor with the rules for diatonic key checking\n processor = new PostProcessor(equivalenceRules, diatonicRules);\n }\n\n /**\n * dashless\n * Helper function to remove dashes from brick names\n * @param s, a String\n * @return a String with dashes replaced with spaces\n */\n public static String dashless(String s) {\n return s.replace('-', ' ');\n }\n\n public static String dashed(String s) {\n return s.replace(' ', '-');\n }\n\n /**\n * writeDictionary\n * Writes out an entire dictionary of definitions. Currently deprecated.\n * @param filename, the file to write to\n */\n public void writeDictionary(String filename) {\n FileWriter fstream;\n try {\n fstream = new FileWriter(filename);\n BufferedWriter out = new BufferedWriter(fstream);\n out.write(\"\\\\\\\\ Type Definitions\\n\\n\");\n Set types = costMap.keySet();\n for (String type : types) {\n long cost = costMap.get(type);\n Polylist brickType = Polylist.list(\"brick-type\", type, cost);\n out.write(brickType.toString());\n out.write(\"\\n\");\n }\n out.write(\"\\n\\n\\\\\\\\ Brick Definitions\\n\\n\");\n for (Brick brick : getFullMap()) {\n out.write(brick.toPolylist().toString());\n out.write(\"\\n\\n\");\n }\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not write dictionary file.\");\n }\n }\n // end of class BrickLibrary\n}\n"} {"task_id": "Java_1107", "language": "Java", "task_type": "single_line", "source_file": "java/github/Impro-Visor/Impro-Visor/src/imp/roadmap/brickdictionary/BrickLibrary.java", "mask_start_position": 26668, "mask_end_position": 26682, "canonical_solution": "riter fstream;", "pre_mask_code": "/**\n * This Java Class is part of the Impro-Visor Application\n */\npackage imp.roadmap.brickdictionary;\n\nimport imp.roadmap.cykparser.PostProcessor;\nimport imp.data.ChordSymbol;\nimport imp.util.ErrorLog;\nimport java.util.Collection;\nimport polya.*;\nimport java.io.*;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.Set;\n\n/**\n * purpose: Methods relating to the brick library (dictionary)\n * @author Zachary Merritt\n */\npublic class BrickLibrary {\n\n /**\n * Keyword used in defining bricks in a dictionary.\n */\n public static final String DEF_BRICK = \"defbrick\";\n\n /**\n * This is the conjunction to be used to describe appendages to Cadences\n * such as Overrun and Dropback\n */\n public static String CONJUNCTION = \" + \";\n\n /**\n * The name for an Overrun\n */\n public static String OVERRUN = \"Overrun\";\n\n /**\n * The name for a Dropback\n */\n public static String DROPBACK = \"Dropback\";\n\n // Lists of key names, with indices corresponding to numeric key value\n private static final String[] KEY_NAME_ARRAY = { \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\" };\n\n private static final String[] KEY_NAME_ARRAY_SHARPS = { \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\" };\n\n // the default cost of a type with no cost specified\n private static final long DEFAULT_COST = 40;\n\n // the string describing an invisible brick's type\n public static final String INVISIBLE = \"Invisible\";\n\n // all bricks\n private LinkedHashMap> brickMap;\n\n // brick costs by type\n private LinkedHashMap costMap;\n\n // the postprocessing unit\n public PostProcessor processor;\n\n /**\n * BrickLibrary / 0\n * Default constructor for an empty BrickLibrary with no specified types\n */\n public BrickLibrary() {\n brickMap = new LinkedHashMap>();\n costMap = new LinkedHashMap();\n }\n\n /**\n * getNames\n * Returns the list of the names of all bricks stored in the dictionary\n * @return an array of Strings\n */\n public String[] getNames() {\n return brickMap.keySet().toArray(new String[0]);\n }\n\n /**\n * addBrickDefinition\n * When a new brick is created in the library, adds its contents to the\n * current brickMap and adds its definition to the dictionary file\n * @param brick, a newly created Brick\n */\n public void addBrickDefinition(Brick brick, String dictionaryFilename) {\n // add the brick to the current BrickLibrary\n boolean added = addBrick(brick);\n if (!added)\n return;\n Brick definitionBrick = new Brick(brick);\n // make a properly-formatted brick definition\n Polylist defn = definitionBrick.toBrickDefinition();\n String defnString = defn.toString();\n if (!brick.getVariant().equals(\"\"))\n defnString.replaceFirst(\" \\\\(\", \"\\\\(\");\n defnString = defnString.replaceAll(\" \\\\(\", \"\\n \\\\(\");\n // write out the string with the definition to the end of the file\n try {\n FileOutputStream out = new FileOutputStream(dictionaryFilename, true);\n out.write(\"\\n\".getBytes());\n out.write(defnString.getBytes());\n out.write(\"\\n\".getBytes());\n out.close();\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Cannot write to dictionary\");\n }\n }\n\n /**\n * addBrick\n * Adds a brick to the library's brickMap\n * @param brick, a created Brick\n */\n public boolean addBrick(Brick brick) {\n if (brickMap.containsKey(brick.getName())) {\n // first, we check if the brick is a duplicate or just a brick with\n // an already-used name but a different qualifier. Presently, a\n // doubly-defined brick will have both definitions added to the\n // dictionary but will warn a user if the two definitions are\n LinkedList sameStemList = brickMap.get(brick.getName());\n for (Brick sameStem : sameStemList) {\n if (sameStem.getVariant().equals(brick.getVariant())) {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary already contains \" + brick.getName() + \"(\" + brick.getVariant() + \"): will not\" + \" add to dictionary\", true);\n return false;\n }\n }\n sameStemList.add(brick);\n } else {\n // adding a brick with a new brickname\n LinkedList brickList = new LinkedList();\n brickList.add(brick);\n this.brickMap.put(brick.name, brickList);\n }\n // special rule for creating overruns\n if (brick.getType().equals(\"Cadence\")) {\n String overrunName = brick.getName() + CONJUNCTION + OVERRUN;\n long overrunKeyNum = brick.getKey();\n String overrunType = OVERRUN;\n String overrunMode = brick.getMode();\n String overrunQualifier = brick.getVariant();\n // take blocks from regular cadence and add the next chord\n // in the circle of fifths with the same quality as the\n // resolution\n ArrayList overrunBlocks = new ArrayList();\n overrunBlocks.add(brick);\n ArrayList chords = brick.flattenBlock();\n ChordBlock prevChord = chords.get(chords.size() - 1);\n ChordBlock overrunChord = new ChordBlock(prevChord.transposeName(5), prevChord.getDuration());\n overrunBlocks.add(overrunChord);\n // make a new brick from this list of blocks\n Brick overrun = new Brick(overrunName, overrunQualifier, overrunKeyNum, overrunType, overrunBlocks, overrunMode);\n addBrick(overrun);\n String dropbackName = brick.getName() + CONJUNCTION + DROPBACK;\n long dropbackKeyNum = brick.getKey();\n String dropbackType = DROPBACK;\n String dropbackMode = brick.getMode();\n String dropbackQualifier = brick.getVariant();\n // take blocks from regular cadence and add a relative VI dominant\n // to form a dropback.\n // FIX: This is not the only possible dropback!!\n // For example, we want to allow iii-IV's major and minor.\n ArrayList dropbackBlocks = new ArrayList();\n dropbackBlocks.add(brick);\n String dropbackChordName = keyNumToName((brick.getKey() + 9) % 12);\n /* I think it was wrong to include this in the first place:\n \n if (dropbackMode.equals(\"minor\"))\n dropbackChordName += \"7b5\";\n else\n */\n dropbackChordName += 7;\n ChordBlock dropbackChord = new ChordBlock(dropbackChordName, prevChord.getDuration());\n dropbackBlocks.add(dropbackChord);\n // make a new brick from this list of blocks\n Brick dropback = new Brick(dropbackName, dropbackQualifier, dropbackKeyNum, dropbackType, dropbackBlocks, dropbackMode);\n addBrick(dropback);\n }\n return true;\n }\n\n /**\n * getBrick (definition)\n * Gets the default Brick with the given name from the dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k) {\n if (brickMap.containsKey(s)) {\n LinkedList possibleBricks = brickMap.get(s);\n for (Brick oldBrick : possibleBricks) if (!oldBrick.getType().equals(INVISIBLE)) {\n Brick brick = new Brick(oldBrick);\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n }\n }\n // if no brick is returned\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s + \" with qualifier \" + q, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with duration)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = new Brick(brickMap.get(s).getFirst());\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * hasBrick\n * Checks if a Brick with a given name is in the dictionary\n * @param s, the Brick name\n * @return a boolean\n */\n public boolean hasBrick(String s) {\n return (brickMap.containsKey(s));\n }\n\n /**\n * getFullMap\n * Gets the list of all Bricks in the dictionary as a single collection\n * @return a Collection of Bricks\n */\n public Collection getFullMap() {\n LinkedList values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n values.addAll(brickname);\n }\n return values;\n }\n\n /**\n * getMap\n * Gets the organized list of all Bricks in the dictionary\n * @return a LinkedList of LinkedLists of Bricks\n */\n public LinkedList> getMap() {\n LinkedList> values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n LinkedList newlist = new LinkedList();\n for (Brick brick : brickname) if (!brick.getType().equals(INVISIBLE))\n newlist.add(brick);\n if (!newlist.isEmpty())\n values.add(newlist);\n }\n return values;\n }\n\n /**\n * removeBrick\n * Removes all Bricks matching a given Brick from the dictionary\n * @param brick, the Brick to be removed itself\n */\n public void removeBrick(Brick brick) {\n this.brickMap.remove(brick.name);\n }\n\n /**\n * removeBrick\n * Removes all Bricks with a given name from the dictionary\n * @param brickName, the name of the Brick(s) to be removed\n */\n public void removeBrick(String brickName) {\n this.brickMap.remove(brickName);\n }\n\n /**\n * exileBrick\n * Takes a Brick out of the visible brick library\n * @param brick, the brick to remove\n */\n public void exileBrick(Brick brick, String dictionaryFilename) {\n // define the search term (the name) for the given brick\n String brickType = \" \" + brick.getType() + \" \";\n String brickDefHead = DEF_BRICK + dashed(brick.getName());\n String qualifier = brick.getVariant();\n if (!qualifier.isEmpty())\n brickDefHead += \"(\" + qualifier + \")\";\n brickDefHead += \" \";\n // open the file and read in its contents\n try {\n File dictionary = new File(dictionaryFilename);\n FileReader in = new FileReader(dictionary);\n BufferedReader reader = new BufferedReader(in);\n String line = reader.readLine();\n String newfile = \"\";\n while (line != null) {\n // Exiling a brick is just taking the type and changing it\n // to be invisible\n if (line.contains(brickDefHead)) {\n line = line.replaceFirst(brickType, \" \" + INVISIBLE + \" \");\n }\n newfile += line + \"\\r\\n\";\n line = reader.readLine();\n }\n // write out the modified dictionary\n FileWriter writer = new FileWriter(dictionaryFilename);\n writer.write(newfile);\n writer.close();\n processDictionary(dictionaryFilename);\n } catch (IOException ioe) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not modify brick in dictionary\");\n }\n }\n\n /**\n * printDictionary\n * Prints every brick in the dictionary to System.err\n */\n public void printDictionary() {\n Iterator iter = getFullMap().iterator();\n while (iter.hasNext()) {\n Brick currentBrick = (Brick) iter.next();\n currentBrick.printBrick();\n }\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the default cost\n * @param t, a type, a String\n */\n public void addType(String t) {\n costMap.put(t, DEFAULT_COST);\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the specified cost\n * @param t, a type, a String\n * @param c, a cost, a long\n */\n public void addType(String t, long c) {\n costMap.put(t, c);\n }\n\n /**\n * getCost\n * Gets the cost associated with the given type\n * @param t, the type whose cost is desired (a String)\n * @return the cost, a long\n */\n public long getCost(String t) {\n if (!hasType(t))\n ErrorLog.log(ErrorLog.SEVERE, \"Type does not exist, will register\" + \"as an invisible brick: \" + t);\n return costMap.get(t);\n }\n\n /**\n * hasType\n * Checks if a given type is contained in the dictionary\n * @param t, a type (a String)\n * @return a boolean\n */\n public boolean hasType(String t) {\n return costMap.containsKey(t);\n }\n\n /**\n * getTypes\n * Gets the list of all types in the dictionary\n * @return an array of Strings of types\n */\n public String[] getTypes() {\n return costMap.keySet().toArray(new String[0]);\n }\n\n /**\n * isValidKey\n * Checks if a given key's name actually describes a key\n * @param keyName, a key's name as a String\n * @return a boolean\n */\n public static Boolean isValidKey(String keyName) {\n return keyName.equals(\"C\") || keyName.equals(\"B#\") || keyName.equals(\"C#\") || keyName.equals(\"Db\") || keyName.equals(\"D\") || keyName.equals(\"D#\") || keyName.equals(\"Eb\") || keyName.equals(\"E\") || keyName.equals(\"Fb\") || keyName.equals(\"F\") || keyName.equals(\"E#\") || keyName.equals(\"F#\") || keyName.equals(\"Gb\") || keyName.equals(\"G\") || keyName.equals(\"G#\") || keyName.equals(\"Ab\") || keyName.equals(\"A\") || keyName.equals(\"A#\") || keyName.equals(\"Bb\") || keyName.equals(\"B\") || keyName.equals(\"Cb\");\n }\n\n /**\n * keyNameToNum\n * Takes a key by name and returns the long describing that key\n * @param keyName, a key as a String\n * @return the same key as a long\n */\n public static long keyNameToNum(String keyName) {\n if (keyName.equals(\"\"))\n return -1;\n if (keyName.equals(\"C\") || keyName.equals(\"B#\"))\n return 0;\n if (keyName.equals(\"C#\") || keyName.equals(\"Db\"))\n return 1;\n if (keyName.equals(\"D\"))\n return 2;\n if (keyName.equals(\"D#\") || keyName.equals(\"Eb\"))\n return 3;\n if (keyName.equals(\"E\") || keyName.equals(\"Fb\"))\n return 4;\n if (keyName.equals(\"F\") || keyName.equals(\"E#\"))\n return 5;\n if (keyName.equals(\"F#\") || keyName.equals(\"Gb\"))\n return 6;\n if (keyName.equals(\"G\"))\n return 7;\n if (keyName.equals(\"G#\") || keyName.equals(\"Ab\"))\n return 8;\n if (keyName.equals(\"A\"))\n return 9;\n if (keyName.equals(\"A#\") || keyName.equals(\"Bb\"))\n return 10;\n if (keyName.equals(\"B\") || keyName.equals(\"Cb\"))\n return 11;\n else {\n ErrorLog.log(ErrorLog.SEVERE, \"Incorrect key formatting: \" + keyName);\n return -1;\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and converts it to a key as a String with flats if\n * accidentals are necessary\n * @param keyNum, a long describing a key\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY[(int) keyNum];\n } else if (keyNum == -1)\n return \"\";\n else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and whether or not to use sharps and converts it\n * to a key as a String\n * @param keyNum, a long describing a key\n * @boolean sharps, a boolean describing whether or not to use sharps\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum, boolean sharps) {\n if (sharps) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY_SHARPS[(int) keyNum];\n } else if (keyNum == -1) {\n return \"\";\n } else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n } else {\n return keyNumToName(keyNum);\n }\n }\n\n /**\n * processDictionary\n * Reads in all the dictionary information in the file to define appropriate\n * objects in the BrickDictionary.\n * @throws IOException\n */\n public void processDictionary(String dictionaryFilename) throws IOException {\n FileInputStream fis = new FileInputStream(dictionaryFilename);\n Tokenizer in = new Tokenizer(fis);\n in.slashSlashComments(true);\n in.slashStarComments(true);\n Object token;\n ArrayList equivalenceRules = new ArrayList();\n ArrayList diatonicRules = new ArrayList();\n LinkedHashMap> polymap = new LinkedHashMap>();\n brickMap.clear();\n // Read in S expressions until end of file is reached\n while ((token = in.nextSexp()) != Tokenizer.eof) {\n if (token instanceof Polylist) {\n Polylist contents = (Polylist) token;\n // Check that polylist has enough fields to be a brick\n // Needs BlockType (i.e. DEF_BRICK), name, key, and contents\n if (contents.length() < 2) {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for\" + \" a BrickDictionary item: \" + contents, true);\n } else {\n String blockCategory = contents.first().toString();\n contents = contents.rest();\n // Equivalence rules for the postprocessor\n if (blockCategory.equals(\"equiv\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty equivalence \" + \"rule in dictionary\");\n } else {\n Polylist chords = ChordSymbol.chordSymbolsFromStrings(contents);\n equivalenceRules.add(chords);\n }\n } else // Diatonic rules for the postprocessor\n if (blockCategory.equals(\"diatonic\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty diatonic \" + \"rule in dictionary\");\n } else {\n String modeTag = contents.first().toString();\n contents = contents.rest();\n Polylist p = ChordSymbol.chordSymbolsFromStrings(contents);\n p = p.cons(modeTag);\n diatonicRules.add(p);\n }\n } else // Type definitions with costs\n if (blockCategory.equals(\"brick-type\")) {\n if (contents.length() != 2 && contents.length() != 1)\n ErrorLog.log(ErrorLog.WARNING, \"Not a correct \" + \"brick-type declaration: \" + contents);\n else {\n String type = contents.first().toString();\n contents = contents.rest();\n if (contents.isEmpty()) {\n addType(type);\n } else {\n Object cost = contents.first();\n if (cost instanceof Long)\n addType(type, (Long) cost);\n else {\n ErrorLog.log(ErrorLog.WARNING, \"Incorrect \" + \"cost for brick type: \" + type);\n addType(type);\n }\n }\n }\n } else // Brick definitions themselves\n if (blockCategory.equals(DEF_BRICK) && contents.length() > 4) {\n // read in the information as a saved polylist to be\n // constructed properly as a Brick later\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n if (polymap.containsKey(brickName))\n polymap.get(brickName).add((Polylist) token);\n else {\n LinkedList newKey = new LinkedList();\n newKey.add((Polylist) token);\n polymap.put(brickName, newKey);\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper type for \" + \"a BrickDictionary item: \" + token, true);\n }\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for \" + \"a token: \" + token, true);\n }\n }\n // for each set of bricks with the same name\n for (LinkedList brickStem : polymap.values()) {\n // for each unprocessed brick definition\n for (Polylist contents : brickStem) {\n // pull out the name, qualifier, and contents\n contents = contents.rest();\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n String brickQualifier = \"\";\n if (contents.first() instanceof Polylist) {\n brickQualifier = ((Polylist) contents.first()).toStringSansParens();\n contents = contents.rest();\n }\n String brickMode = contents.first().toString();\n contents = contents.rest();\n String brickType = contents.first().toString();\n contents = contents.rest();\n if (!hasType(brickType))\n ErrorLog.log(ErrorLog.WARNING, brickName + \" is of \" + \"uninitialized type \" + brickType + \"; will register as non-brick\");\n String brickKeyString = contents.first().toString();\n contents = contents.rest();\n long brickKeyNum = keyNameToNum(brickKeyString);\n // add the brick, recursively defining subbricks\n Brick currentBrick = new Brick(brickName, brickQualifier, brickKeyNum, brickType, contents, this, brickMode, polymap);\n addBrick(currentBrick);\n }\n }\n // initialize the postprocessor with the rules for diatonic key checking\n processor = new PostProcessor(equivalenceRules, diatonicRules);\n }\n\n /**\n * dashless\n * Helper function to remove dashes from brick names\n * @param s, a String\n * @return a String with dashes replaced with spaces\n */\n public static String dashless(String s) {\n return s.replace('-', ' ');\n }\n\n public static String dashed(String s) {\n return s.replace(' ', '-');\n }\n\n /**\n * writeDictionary\n * Writes out an entire dictionary of definitions. Currently deprecated.\n * @param filename, the file to write to\n */\n public void writeDictionary(String filename) {\n FileW", "post_mask_code": "\n try {\n fstream = new FileWriter(filename);\n BufferedWriter out = new BufferedWriter(fstream);\n out.write(\"\\\\\\\\ Type Definitions\\n\\n\");\n Set types = costMap.keySet();\n for (String type : types) {\n long cost = costMap.get(type);\n Polylist brickType = Polylist.list(\"brick-type\", type, cost);\n out.write(brickType.toString());\n out.write(\"\\n\");\n }\n out.write(\"\\n\\n\\\\\\\\ Brick Definitions\\n\\n\");\n for (Brick brick : getFullMap()) {\n out.write(brick.toPolylist().toString());\n out.write(\"\\n\\n\");\n }\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not write dictionary file.\");\n }\n }\n // end of class BrickLibrary\n}\n"} {"task_id": "Java_1108", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Impro-Visor/Impro-Visor/src/imp/roadmap/brickdictionary/BrickLibrary.java", "mask_start_position": 14607, "mask_end_position": 14829, "canonical_solution": "public void printDictionary() {\n Iterator iter = getFullMap().iterator();\n while (iter.hasNext()) {\n Brick currentBrick = (Brick) iter.next();\n currentBrick.printBrick();\n }\n }", "pre_mask_code": "/**\n * This Java Class is part of the Impro-Visor Application\n */\npackage imp.roadmap.brickdictionary;\n\nimport imp.roadmap.cykparser.PostProcessor;\nimport imp.data.ChordSymbol;\nimport imp.util.ErrorLog;\nimport java.util.Collection;\nimport polya.*;\nimport java.io.*;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.Set;\n\n/**\n * purpose: Methods relating to the brick library (dictionary)\n * @author Zachary Merritt\n */\npublic class BrickLibrary {\n\n /**\n * Keyword used in defining bricks in a dictionary.\n */\n public static final String DEF_BRICK = \"defbrick\";\n\n /**\n * This is the conjunction to be used to describe appendages to Cadences\n * such as Overrun and Dropback\n */\n public static String CONJUNCTION = \" + \";\n\n /**\n * The name for an Overrun\n */\n public static String OVERRUN = \"Overrun\";\n\n /**\n * The name for a Dropback\n */\n public static String DROPBACK = \"Dropback\";\n\n // Lists of key names, with indices corresponding to numeric key value\n private static final String[] KEY_NAME_ARRAY = { \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\" };\n\n private static final String[] KEY_NAME_ARRAY_SHARPS = { \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\" };\n\n // the default cost of a type with no cost specified\n private static final long DEFAULT_COST = 40;\n\n // the string describing an invisible brick's type\n public static final String INVISIBLE = \"Invisible\";\n\n // all bricks\n private LinkedHashMap> brickMap;\n\n // brick costs by type\n private LinkedHashMap costMap;\n\n // the postprocessing unit\n public PostProcessor processor;\n\n /**\n * BrickLibrary / 0\n * Default constructor for an empty BrickLibrary with no specified types\n */\n public BrickLibrary() {\n brickMap = new LinkedHashMap>();\n costMap = new LinkedHashMap();\n }\n\n /**\n * getNames\n * Returns the list of the names of all bricks stored in the dictionary\n * @return an array of Strings\n */\n public String[] getNames() {\n return brickMap.keySet().toArray(new String[0]);\n }\n\n /**\n * addBrickDefinition\n * When a new brick is created in the library, adds its contents to the\n * current brickMap and adds its definition to the dictionary file\n * @param brick, a newly created Brick\n */\n public void addBrickDefinition(Brick brick, String dictionaryFilename) {\n // add the brick to the current BrickLibrary\n boolean added = addBrick(brick);\n if (!added)\n return;\n Brick definitionBrick = new Brick(brick);\n // make a properly-formatted brick definition\n Polylist defn = definitionBrick.toBrickDefinition();\n String defnString = defn.toString();\n if (!brick.getVariant().equals(\"\"))\n defnString.replaceFirst(\" \\\\(\", \"\\\\(\");\n defnString = defnString.replaceAll(\" \\\\(\", \"\\n \\\\(\");\n // write out the string with the definition to the end of the file\n try {\n FileOutputStream out = new FileOutputStream(dictionaryFilename, true);\n out.write(\"\\n\".getBytes());\n out.write(defnString.getBytes());\n out.write(\"\\n\".getBytes());\n out.close();\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Cannot write to dictionary\");\n }\n }\n\n /**\n * addBrick\n * Adds a brick to the library's brickMap\n * @param brick, a created Brick\n */\n public boolean addBrick(Brick brick) {\n if (brickMap.containsKey(brick.getName())) {\n // first, we check if the brick is a duplicate or just a brick with\n // an already-used name but a different qualifier. Presently, a\n // doubly-defined brick will have both definitions added to the\n // dictionary but will warn a user if the two definitions are\n LinkedList sameStemList = brickMap.get(brick.getName());\n for (Brick sameStem : sameStemList) {\n if (sameStem.getVariant().equals(brick.getVariant())) {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary already contains \" + brick.getName() + \"(\" + brick.getVariant() + \"): will not\" + \" add to dictionary\", true);\n return false;\n }\n }\n sameStemList.add(brick);\n } else {\n // adding a brick with a new brickname\n LinkedList brickList = new LinkedList();\n brickList.add(brick);\n this.brickMap.put(brick.name, brickList);\n }\n // special rule for creating overruns\n if (brick.getType().equals(\"Cadence\")) {\n String overrunName = brick.getName() + CONJUNCTION + OVERRUN;\n long overrunKeyNum = brick.getKey();\n String overrunType = OVERRUN;\n String overrunMode = brick.getMode();\n String overrunQualifier = brick.getVariant();\n // take blocks from regular cadence and add the next chord\n // in the circle of fifths with the same quality as the\n // resolution\n ArrayList overrunBlocks = new ArrayList();\n overrunBlocks.add(brick);\n ArrayList chords = brick.flattenBlock();\n ChordBlock prevChord = chords.get(chords.size() - 1);\n ChordBlock overrunChord = new ChordBlock(prevChord.transposeName(5), prevChord.getDuration());\n overrunBlocks.add(overrunChord);\n // make a new brick from this list of blocks\n Brick overrun = new Brick(overrunName, overrunQualifier, overrunKeyNum, overrunType, overrunBlocks, overrunMode);\n addBrick(overrun);\n String dropbackName = brick.getName() + CONJUNCTION + DROPBACK;\n long dropbackKeyNum = brick.getKey();\n String dropbackType = DROPBACK;\n String dropbackMode = brick.getMode();\n String dropbackQualifier = brick.getVariant();\n // take blocks from regular cadence and add a relative VI dominant\n // to form a dropback.\n // FIX: This is not the only possible dropback!!\n // For example, we want to allow iii-IV's major and minor.\n ArrayList dropbackBlocks = new ArrayList();\n dropbackBlocks.add(brick);\n String dropbackChordName = keyNumToName((brick.getKey() + 9) % 12);\n /* I think it was wrong to include this in the first place:\n \n if (dropbackMode.equals(\"minor\"))\n dropbackChordName += \"7b5\";\n else\n */\n dropbackChordName += 7;\n ChordBlock dropbackChord = new ChordBlock(dropbackChordName, prevChord.getDuration());\n dropbackBlocks.add(dropbackChord);\n // make a new brick from this list of blocks\n Brick dropback = new Brick(dropbackName, dropbackQualifier, dropbackKeyNum, dropbackType, dropbackBlocks, dropbackMode);\n addBrick(dropback);\n }\n return true;\n }\n\n /**\n * getBrick (definition)\n * Gets the default Brick with the given name from the dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k) {\n if (brickMap.containsKey(s)) {\n LinkedList possibleBricks = brickMap.get(s);\n for (Brick oldBrick : possibleBricks) if (!oldBrick.getType().equals(INVISIBLE)) {\n Brick brick = new Brick(oldBrick);\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n }\n }\n // if no brick is returned\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s + \" with qualifier \" + q, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with duration)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = new Brick(brickMap.get(s).getFirst());\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * hasBrick\n * Checks if a Brick with a given name is in the dictionary\n * @param s, the Brick name\n * @return a boolean\n */\n public boolean hasBrick(String s) {\n return (brickMap.containsKey(s));\n }\n\n /**\n * getFullMap\n * Gets the list of all Bricks in the dictionary as a single collection\n * @return a Collection of Bricks\n */\n public Collection getFullMap() {\n LinkedList values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n values.addAll(brickname);\n }\n return values;\n }\n\n /**\n * getMap\n * Gets the organized list of all Bricks in the dictionary\n * @return a LinkedList of LinkedLists of Bricks\n */\n public LinkedList> getMap() {\n LinkedList> values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n LinkedList newlist = new LinkedList();\n for (Brick brick : brickname) if (!brick.getType().equals(INVISIBLE))\n newlist.add(brick);\n if (!newlist.isEmpty())\n values.add(newlist);\n }\n return values;\n }\n\n /**\n * removeBrick\n * Removes all Bricks matching a given Brick from the dictionary\n * @param brick, the Brick to be removed itself\n */\n public void removeBrick(Brick brick) {\n this.brickMap.remove(brick.name);\n }\n\n /**\n * removeBrick\n * Removes all Bricks with a given name from the dictionary\n * @param brickName, the name of the Brick(s) to be removed\n */\n public void removeBrick(String brickName) {\n this.brickMap.remove(brickName);\n }\n\n /**\n * exileBrick\n * Takes a Brick out of the visible brick library\n * @param brick, the brick to remove\n */\n public void exileBrick(Brick brick, String dictionaryFilename) {\n // define the search term (the name) for the given brick\n String brickType = \" \" + brick.getType() + \" \";\n String brickDefHead = DEF_BRICK + dashed(brick.getName());\n String qualifier = brick.getVariant();\n if (!qualifier.isEmpty())\n brickDefHead += \"(\" + qualifier + \")\";\n brickDefHead += \" \";\n // open the file and read in its contents\n try {\n File dictionary = new File(dictionaryFilename);\n FileReader in = new FileReader(dictionary);\n BufferedReader reader = new BufferedReader(in);\n String line = reader.readLine();\n String newfile = \"\";\n while (line != null) {\n // Exiling a brick is just taking the type and changing it\n // to be invisible\n if (line.contains(brickDefHead)) {\n line = line.replaceFirst(brickType, \" \" + INVISIBLE + \" \");\n }\n newfile += line + \"\\r\\n\";\n line = reader.readLine();\n }\n // write out the modified dictionary\n FileWriter writer = new FileWriter(dictionaryFilename);\n writer.write(newfile);\n writer.close();\n processDictionary(dictionaryFilename);\n } catch (IOException ioe) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not modify brick in dictionary\");\n }\n }\n\n /**\n * printDictionary\n * Prints every brick in the dictionary to System.err\n */\n ", "post_mask_code": "\n\n /**\n * addType\n * Adds a given type to the dictionary with the default cost\n * @param t, a type, a String\n */\n public void addType(String t) {\n costMap.put(t, DEFAULT_COST);\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the specified cost\n * @param t, a type, a String\n * @param c, a cost, a long\n */\n public void addType(String t, long c) {\n costMap.put(t, c);\n }\n\n /**\n * getCost\n * Gets the cost associated with the given type\n * @param t, the type whose cost is desired (a String)\n * @return the cost, a long\n */\n public long getCost(String t) {\n if (!hasType(t))\n ErrorLog.log(ErrorLog.SEVERE, \"Type does not exist, will register\" + \"as an invisible brick: \" + t);\n return costMap.get(t);\n }\n\n /**\n * hasType\n * Checks if a given type is contained in the dictionary\n * @param t, a type (a String)\n * @return a boolean\n */\n public boolean hasType(String t) {\n return costMap.containsKey(t);\n }\n\n /**\n * getTypes\n * Gets the list of all types in the dictionary\n * @return an array of Strings of types\n */\n public String[] getTypes() {\n return costMap.keySet().toArray(new String[0]);\n }\n\n /**\n * isValidKey\n * Checks if a given key's name actually describes a key\n * @param keyName, a key's name as a String\n * @return a boolean\n */\n public static Boolean isValidKey(String keyName) {\n return keyName.equals(\"C\") || keyName.equals(\"B#\") || keyName.equals(\"C#\") || keyName.equals(\"Db\") || keyName.equals(\"D\") || keyName.equals(\"D#\") || keyName.equals(\"Eb\") || keyName.equals(\"E\") || keyName.equals(\"Fb\") || keyName.equals(\"F\") || keyName.equals(\"E#\") || keyName.equals(\"F#\") || keyName.equals(\"Gb\") || keyName.equals(\"G\") || keyName.equals(\"G#\") || keyName.equals(\"Ab\") || keyName.equals(\"A\") || keyName.equals(\"A#\") || keyName.equals(\"Bb\") || keyName.equals(\"B\") || keyName.equals(\"Cb\");\n }\n\n /**\n * keyNameToNum\n * Takes a key by name and returns the long describing that key\n * @param keyName, a key as a String\n * @return the same key as a long\n */\n public static long keyNameToNum(String keyName) {\n if (keyName.equals(\"\"))\n return -1;\n if (keyName.equals(\"C\") || keyName.equals(\"B#\"))\n return 0;\n if (keyName.equals(\"C#\") || keyName.equals(\"Db\"))\n return 1;\n if (keyName.equals(\"D\"))\n return 2;\n if (keyName.equals(\"D#\") || keyName.equals(\"Eb\"))\n return 3;\n if (keyName.equals(\"E\") || keyName.equals(\"Fb\"))\n return 4;\n if (keyName.equals(\"F\") || keyName.equals(\"E#\"))\n return 5;\n if (keyName.equals(\"F#\") || keyName.equals(\"Gb\"))\n return 6;\n if (keyName.equals(\"G\"))\n return 7;\n if (keyName.equals(\"G#\") || keyName.equals(\"Ab\"))\n return 8;\n if (keyName.equals(\"A\"))\n return 9;\n if (keyName.equals(\"A#\") || keyName.equals(\"Bb\"))\n return 10;\n if (keyName.equals(\"B\") || keyName.equals(\"Cb\"))\n return 11;\n else {\n ErrorLog.log(ErrorLog.SEVERE, \"Incorrect key formatting: \" + keyName);\n return -1;\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and converts it to a key as a String with flats if\n * accidentals are necessary\n * @param keyNum, a long describing a key\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY[(int) keyNum];\n } else if (keyNum == -1)\n return \"\";\n else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and whether or not to use sharps and converts it\n * to a key as a String\n * @param keyNum, a long describing a key\n * @boolean sharps, a boolean describing whether or not to use sharps\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum, boolean sharps) {\n if (sharps) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY_SHARPS[(int) keyNum];\n } else if (keyNum == -1) {\n return \"\";\n } else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n } else {\n return keyNumToName(keyNum);\n }\n }\n\n /**\n * processDictionary\n * Reads in all the dictionary information in the file to define appropriate\n * objects in the BrickDictionary.\n * @throws IOException\n */\n public void processDictionary(String dictionaryFilename) throws IOException {\n FileInputStream fis = new FileInputStream(dictionaryFilename);\n Tokenizer in = new Tokenizer(fis);\n in.slashSlashComments(true);\n in.slashStarComments(true);\n Object token;\n ArrayList equivalenceRules = new ArrayList();\n ArrayList diatonicRules = new ArrayList();\n LinkedHashMap> polymap = new LinkedHashMap>();\n brickMap.clear();\n // Read in S expressions until end of file is reached\n while ((token = in.nextSexp()) != Tokenizer.eof) {\n if (token instanceof Polylist) {\n Polylist contents = (Polylist) token;\n // Check that polylist has enough fields to be a brick\n // Needs BlockType (i.e. DEF_BRICK), name, key, and contents\n if (contents.length() < 2) {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for\" + \" a BrickDictionary item: \" + contents, true);\n } else {\n String blockCategory = contents.first().toString();\n contents = contents.rest();\n // Equivalence rules for the postprocessor\n if (blockCategory.equals(\"equiv\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty equivalence \" + \"rule in dictionary\");\n } else {\n Polylist chords = ChordSymbol.chordSymbolsFromStrings(contents);\n equivalenceRules.add(chords);\n }\n } else // Diatonic rules for the postprocessor\n if (blockCategory.equals(\"diatonic\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty diatonic \" + \"rule in dictionary\");\n } else {\n String modeTag = contents.first().toString();\n contents = contents.rest();\n Polylist p = ChordSymbol.chordSymbolsFromStrings(contents);\n p = p.cons(modeTag);\n diatonicRules.add(p);\n }\n } else // Type definitions with costs\n if (blockCategory.equals(\"brick-type\")) {\n if (contents.length() != 2 && contents.length() != 1)\n ErrorLog.log(ErrorLog.WARNING, \"Not a correct \" + \"brick-type declaration: \" + contents);\n else {\n String type = contents.first().toString();\n contents = contents.rest();\n if (contents.isEmpty()) {\n addType(type);\n } else {\n Object cost = contents.first();\n if (cost instanceof Long)\n addType(type, (Long) cost);\n else {\n ErrorLog.log(ErrorLog.WARNING, \"Incorrect \" + \"cost for brick type: \" + type);\n addType(type);\n }\n }\n }\n } else // Brick definitions themselves\n if (blockCategory.equals(DEF_BRICK) && contents.length() > 4) {\n // read in the information as a saved polylist to be\n // constructed properly as a Brick later\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n if (polymap.containsKey(brickName))\n polymap.get(brickName).add((Polylist) token);\n else {\n LinkedList newKey = new LinkedList();\n newKey.add((Polylist) token);\n polymap.put(brickName, newKey);\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper type for \" + \"a BrickDictionary item: \" + token, true);\n }\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for \" + \"a token: \" + token, true);\n }\n }\n // for each set of bricks with the same name\n for (LinkedList brickStem : polymap.values()) {\n // for each unprocessed brick definition\n for (Polylist contents : brickStem) {\n // pull out the name, qualifier, and contents\n contents = contents.rest();\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n String brickQualifier = \"\";\n if (contents.first() instanceof Polylist) {\n brickQualifier = ((Polylist) contents.first()).toStringSansParens();\n contents = contents.rest();\n }\n String brickMode = contents.first().toString();\n contents = contents.rest();\n String brickType = contents.first().toString();\n contents = contents.rest();\n if (!hasType(brickType))\n ErrorLog.log(ErrorLog.WARNING, brickName + \" is of \" + \"uninitialized type \" + brickType + \"; will register as non-brick\");\n String brickKeyString = contents.first().toString();\n contents = contents.rest();\n long brickKeyNum = keyNameToNum(brickKeyString);\n // add the brick, recursively defining subbricks\n Brick currentBrick = new Brick(brickName, brickQualifier, brickKeyNum, brickType, contents, this, brickMode, polymap);\n addBrick(currentBrick);\n }\n }\n // initialize the postprocessor with the rules for diatonic key checking\n processor = new PostProcessor(equivalenceRules, diatonicRules);\n }\n\n /**\n * dashless\n * Helper function to remove dashes from brick names\n * @param s, a String\n * @return a String with dashes replaced with spaces\n */\n public static String dashless(String s) {\n return s.replace('-', ' ');\n }\n\n public static String dashed(String s) {\n return s.replace(' ', '-');\n }\n\n /**\n * writeDictionary\n * Writes out an entire dictionary of definitions. Currently deprecated.\n * @param filename, the file to write to\n */\n public void writeDictionary(String filename) {\n FileWriter fstream;\n try {\n fstream = new FileWriter(filename);\n BufferedWriter out = new BufferedWriter(fstream);\n out.write(\"\\\\\\\\ Type Definitions\\n\\n\");\n Set types = costMap.keySet();\n for (String type : types) {\n long cost = costMap.get(type);\n Polylist brickType = Polylist.list(\"brick-type\", type, cost);\n out.write(brickType.toString());\n out.write(\"\\n\");\n }\n out.write(\"\\n\\n\\\\\\\\ Brick Definitions\\n\\n\");\n for (Brick brick : getFullMap()) {\n out.write(brick.toPolylist().toString());\n out.write(\"\\n\\n\");\n }\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not write dictionary file.\");\n }\n }\n // end of class BrickLibrary\n}\n"} {"task_id": "Java_1109", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Impro-Visor/Impro-Visor/src/imp/roadmap/brickdictionary/BrickLibrary.java", "mask_start_position": 7767, "mask_end_position": 7971, "canonical_solution": "if (!oldBrick.getType().equals(INVISIBLE)) {\n Brick brick = new Brick(oldBrick);\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n }", "pre_mask_code": "/**\n * This Java Class is part of the Impro-Visor Application\n */\npackage imp.roadmap.brickdictionary;\n\nimport imp.roadmap.cykparser.PostProcessor;\nimport imp.data.ChordSymbol;\nimport imp.util.ErrorLog;\nimport java.util.Collection;\nimport polya.*;\nimport java.io.*;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.Set;\n\n/**\n * purpose: Methods relating to the brick library (dictionary)\n * @author Zachary Merritt\n */\npublic class BrickLibrary {\n\n /**\n * Keyword used in defining bricks in a dictionary.\n */\n public static final String DEF_BRICK = \"defbrick\";\n\n /**\n * This is the conjunction to be used to describe appendages to Cadences\n * such as Overrun and Dropback\n */\n public static String CONJUNCTION = \" + \";\n\n /**\n * The name for an Overrun\n */\n public static String OVERRUN = \"Overrun\";\n\n /**\n * The name for a Dropback\n */\n public static String DROPBACK = \"Dropback\";\n\n // Lists of key names, with indices corresponding to numeric key value\n private static final String[] KEY_NAME_ARRAY = { \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\" };\n\n private static final String[] KEY_NAME_ARRAY_SHARPS = { \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\" };\n\n // the default cost of a type with no cost specified\n private static final long DEFAULT_COST = 40;\n\n // the string describing an invisible brick's type\n public static final String INVISIBLE = \"Invisible\";\n\n // all bricks\n private LinkedHashMap> brickMap;\n\n // brick costs by type\n private LinkedHashMap costMap;\n\n // the postprocessing unit\n public PostProcessor processor;\n\n /**\n * BrickLibrary / 0\n * Default constructor for an empty BrickLibrary with no specified types\n */\n public BrickLibrary() {\n brickMap = new LinkedHashMap>();\n costMap = new LinkedHashMap();\n }\n\n /**\n * getNames\n * Returns the list of the names of all bricks stored in the dictionary\n * @return an array of Strings\n */\n public String[] getNames() {\n return brickMap.keySet().toArray(new String[0]);\n }\n\n /**\n * addBrickDefinition\n * When a new brick is created in the library, adds its contents to the\n * current brickMap and adds its definition to the dictionary file\n * @param brick, a newly created Brick\n */\n public void addBrickDefinition(Brick brick, String dictionaryFilename) {\n // add the brick to the current BrickLibrary\n boolean added = addBrick(brick);\n if (!added)\n return;\n Brick definitionBrick = new Brick(brick);\n // make a properly-formatted brick definition\n Polylist defn = definitionBrick.toBrickDefinition();\n String defnString = defn.toString();\n if (!brick.getVariant().equals(\"\"))\n defnString.replaceFirst(\" \\\\(\", \"\\\\(\");\n defnString = defnString.replaceAll(\" \\\\(\", \"\\n \\\\(\");\n // write out the string with the definition to the end of the file\n try {\n FileOutputStream out = new FileOutputStream(dictionaryFilename, true);\n out.write(\"\\n\".getBytes());\n out.write(defnString.getBytes());\n out.write(\"\\n\".getBytes());\n out.close();\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Cannot write to dictionary\");\n }\n }\n\n /**\n * addBrick\n * Adds a brick to the library's brickMap\n * @param brick, a created Brick\n */\n public boolean addBrick(Brick brick) {\n if (brickMap.containsKey(brick.getName())) {\n // first, we check if the brick is a duplicate or just a brick with\n // an already-used name but a different qualifier. Presently, a\n // doubly-defined brick will have both definitions added to the\n // dictionary but will warn a user if the two definitions are\n LinkedList sameStemList = brickMap.get(brick.getName());\n for (Brick sameStem : sameStemList) {\n if (sameStem.getVariant().equals(brick.getVariant())) {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary already contains \" + brick.getName() + \"(\" + brick.getVariant() + \"): will not\" + \" add to dictionary\", true);\n return false;\n }\n }\n sameStemList.add(brick);\n } else {\n // adding a brick with a new brickname\n LinkedList brickList = new LinkedList();\n brickList.add(brick);\n this.brickMap.put(brick.name, brickList);\n }\n // special rule for creating overruns\n if (brick.getType().equals(\"Cadence\")) {\n String overrunName = brick.getName() + CONJUNCTION + OVERRUN;\n long overrunKeyNum = brick.getKey();\n String overrunType = OVERRUN;\n String overrunMode = brick.getMode();\n String overrunQualifier = brick.getVariant();\n // take blocks from regular cadence and add the next chord\n // in the circle of fifths with the same quality as the\n // resolution\n ArrayList overrunBlocks = new ArrayList();\n overrunBlocks.add(brick);\n ArrayList chords = brick.flattenBlock();\n ChordBlock prevChord = chords.get(chords.size() - 1);\n ChordBlock overrunChord = new ChordBlock(prevChord.transposeName(5), prevChord.getDuration());\n overrunBlocks.add(overrunChord);\n // make a new brick from this list of blocks\n Brick overrun = new Brick(overrunName, overrunQualifier, overrunKeyNum, overrunType, overrunBlocks, overrunMode);\n addBrick(overrun);\n String dropbackName = brick.getName() + CONJUNCTION + DROPBACK;\n long dropbackKeyNum = brick.getKey();\n String dropbackType = DROPBACK;\n String dropbackMode = brick.getMode();\n String dropbackQualifier = brick.getVariant();\n // take blocks from regular cadence and add a relative VI dominant\n // to form a dropback.\n // FIX: This is not the only possible dropback!!\n // For example, we want to allow iii-IV's major and minor.\n ArrayList dropbackBlocks = new ArrayList();\n dropbackBlocks.add(brick);\n String dropbackChordName = keyNumToName((brick.getKey() + 9) % 12);\n /* I think it was wrong to include this in the first place:\n \n if (dropbackMode.equals(\"minor\"))\n dropbackChordName += \"7b5\";\n else\n */\n dropbackChordName += 7;\n ChordBlock dropbackChord = new ChordBlock(dropbackChordName, prevChord.getDuration());\n dropbackBlocks.add(dropbackChord);\n // make a new brick from this list of blocks\n Brick dropback = new Brick(dropbackName, dropbackQualifier, dropbackKeyNum, dropbackType, dropbackBlocks, dropbackMode);\n addBrick(dropback);\n }\n return true;\n }\n\n /**\n * getBrick (definition)\n * Gets the default Brick with the given name from the dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k) {\n if (brickMap.containsKey(s)) {\n LinkedList possibleBricks = brickMap.get(s);\n for (Brick oldBrick : possibleBricks) ", "post_mask_code": "\n }\n // if no brick is returned\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s + \" with qualifier \" + q, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with duration)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = new Brick(brickMap.get(s).getFirst());\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * hasBrick\n * Checks if a Brick with a given name is in the dictionary\n * @param s, the Brick name\n * @return a boolean\n */\n public boolean hasBrick(String s) {\n return (brickMap.containsKey(s));\n }\n\n /**\n * getFullMap\n * Gets the list of all Bricks in the dictionary as a single collection\n * @return a Collection of Bricks\n */\n public Collection getFullMap() {\n LinkedList values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n values.addAll(brickname);\n }\n return values;\n }\n\n /**\n * getMap\n * Gets the organized list of all Bricks in the dictionary\n * @return a LinkedList of LinkedLists of Bricks\n */\n public LinkedList> getMap() {\n LinkedList> values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n LinkedList newlist = new LinkedList();\n for (Brick brick : brickname) if (!brick.getType().equals(INVISIBLE))\n newlist.add(brick);\n if (!newlist.isEmpty())\n values.add(newlist);\n }\n return values;\n }\n\n /**\n * removeBrick\n * Removes all Bricks matching a given Brick from the dictionary\n * @param brick, the Brick to be removed itself\n */\n public void removeBrick(Brick brick) {\n this.brickMap.remove(brick.name);\n }\n\n /**\n * removeBrick\n * Removes all Bricks with a given name from the dictionary\n * @param brickName, the name of the Brick(s) to be removed\n */\n public void removeBrick(String brickName) {\n this.brickMap.remove(brickName);\n }\n\n /**\n * exileBrick\n * Takes a Brick out of the visible brick library\n * @param brick, the brick to remove\n */\n public void exileBrick(Brick brick, String dictionaryFilename) {\n // define the search term (the name) for the given brick\n String brickType = \" \" + brick.getType() + \" \";\n String brickDefHead = DEF_BRICK + dashed(brick.getName());\n String qualifier = brick.getVariant();\n if (!qualifier.isEmpty())\n brickDefHead += \"(\" + qualifier + \")\";\n brickDefHead += \" \";\n // open the file and read in its contents\n try {\n File dictionary = new File(dictionaryFilename);\n FileReader in = new FileReader(dictionary);\n BufferedReader reader = new BufferedReader(in);\n String line = reader.readLine();\n String newfile = \"\";\n while (line != null) {\n // Exiling a brick is just taking the type and changing it\n // to be invisible\n if (line.contains(brickDefHead)) {\n line = line.replaceFirst(brickType, \" \" + INVISIBLE + \" \");\n }\n newfile += line + \"\\r\\n\";\n line = reader.readLine();\n }\n // write out the modified dictionary\n FileWriter writer = new FileWriter(dictionaryFilename);\n writer.write(newfile);\n writer.close();\n processDictionary(dictionaryFilename);\n } catch (IOException ioe) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not modify brick in dictionary\");\n }\n }\n\n /**\n * printDictionary\n * Prints every brick in the dictionary to System.err\n */\n public void printDictionary() {\n Iterator iter = getFullMap().iterator();\n while (iter.hasNext()) {\n Brick currentBrick = (Brick) iter.next();\n currentBrick.printBrick();\n }\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the default cost\n * @param t, a type, a String\n */\n public void addType(String t) {\n costMap.put(t, DEFAULT_COST);\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the specified cost\n * @param t, a type, a String\n * @param c, a cost, a long\n */\n public void addType(String t, long c) {\n costMap.put(t, c);\n }\n\n /**\n * getCost\n * Gets the cost associated with the given type\n * @param t, the type whose cost is desired (a String)\n * @return the cost, a long\n */\n public long getCost(String t) {\n if (!hasType(t))\n ErrorLog.log(ErrorLog.SEVERE, \"Type does not exist, will register\" + \"as an invisible brick: \" + t);\n return costMap.get(t);\n }\n\n /**\n * hasType\n * Checks if a given type is contained in the dictionary\n * @param t, a type (a String)\n * @return a boolean\n */\n public boolean hasType(String t) {\n return costMap.containsKey(t);\n }\n\n /**\n * getTypes\n * Gets the list of all types in the dictionary\n * @return an array of Strings of types\n */\n public String[] getTypes() {\n return costMap.keySet().toArray(new String[0]);\n }\n\n /**\n * isValidKey\n * Checks if a given key's name actually describes a key\n * @param keyName, a key's name as a String\n * @return a boolean\n */\n public static Boolean isValidKey(String keyName) {\n return keyName.equals(\"C\") || keyName.equals(\"B#\") || keyName.equals(\"C#\") || keyName.equals(\"Db\") || keyName.equals(\"D\") || keyName.equals(\"D#\") || keyName.equals(\"Eb\") || keyName.equals(\"E\") || keyName.equals(\"Fb\") || keyName.equals(\"F\") || keyName.equals(\"E#\") || keyName.equals(\"F#\") || keyName.equals(\"Gb\") || keyName.equals(\"G\") || keyName.equals(\"G#\") || keyName.equals(\"Ab\") || keyName.equals(\"A\") || keyName.equals(\"A#\") || keyName.equals(\"Bb\") || keyName.equals(\"B\") || keyName.equals(\"Cb\");\n }\n\n /**\n * keyNameToNum\n * Takes a key by name and returns the long describing that key\n * @param keyName, a key as a String\n * @return the same key as a long\n */\n public static long keyNameToNum(String keyName) {\n if (keyName.equals(\"\"))\n return -1;\n if (keyName.equals(\"C\") || keyName.equals(\"B#\"))\n return 0;\n if (keyName.equals(\"C#\") || keyName.equals(\"Db\"))\n return 1;\n if (keyName.equals(\"D\"))\n return 2;\n if (keyName.equals(\"D#\") || keyName.equals(\"Eb\"))\n return 3;\n if (keyName.equals(\"E\") || keyName.equals(\"Fb\"))\n return 4;\n if (keyName.equals(\"F\") || keyName.equals(\"E#\"))\n return 5;\n if (keyName.equals(\"F#\") || keyName.equals(\"Gb\"))\n return 6;\n if (keyName.equals(\"G\"))\n return 7;\n if (keyName.equals(\"G#\") || keyName.equals(\"Ab\"))\n return 8;\n if (keyName.equals(\"A\"))\n return 9;\n if (keyName.equals(\"A#\") || keyName.equals(\"Bb\"))\n return 10;\n if (keyName.equals(\"B\") || keyName.equals(\"Cb\"))\n return 11;\n else {\n ErrorLog.log(ErrorLog.SEVERE, \"Incorrect key formatting: \" + keyName);\n return -1;\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and converts it to a key as a String with flats if\n * accidentals are necessary\n * @param keyNum, a long describing a key\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY[(int) keyNum];\n } else if (keyNum == -1)\n return \"\";\n else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and whether or not to use sharps and converts it\n * to a key as a String\n * @param keyNum, a long describing a key\n * @boolean sharps, a boolean describing whether or not to use sharps\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum, boolean sharps) {\n if (sharps) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY_SHARPS[(int) keyNum];\n } else if (keyNum == -1) {\n return \"\";\n } else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n } else {\n return keyNumToName(keyNum);\n }\n }\n\n /**\n * processDictionary\n * Reads in all the dictionary information in the file to define appropriate\n * objects in the BrickDictionary.\n * @throws IOException\n */\n public void processDictionary(String dictionaryFilename) throws IOException {\n FileInputStream fis = new FileInputStream(dictionaryFilename);\n Tokenizer in = new Tokenizer(fis);\n in.slashSlashComments(true);\n in.slashStarComments(true);\n Object token;\n ArrayList equivalenceRules = new ArrayList();\n ArrayList diatonicRules = new ArrayList();\n LinkedHashMap> polymap = new LinkedHashMap>();\n brickMap.clear();\n // Read in S expressions until end of file is reached\n while ((token = in.nextSexp()) != Tokenizer.eof) {\n if (token instanceof Polylist) {\n Polylist contents = (Polylist) token;\n // Check that polylist has enough fields to be a brick\n // Needs BlockType (i.e. DEF_BRICK), name, key, and contents\n if (contents.length() < 2) {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for\" + \" a BrickDictionary item: \" + contents, true);\n } else {\n String blockCategory = contents.first().toString();\n contents = contents.rest();\n // Equivalence rules for the postprocessor\n if (blockCategory.equals(\"equiv\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty equivalence \" + \"rule in dictionary\");\n } else {\n Polylist chords = ChordSymbol.chordSymbolsFromStrings(contents);\n equivalenceRules.add(chords);\n }\n } else // Diatonic rules for the postprocessor\n if (blockCategory.equals(\"diatonic\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty diatonic \" + \"rule in dictionary\");\n } else {\n String modeTag = contents.first().toString();\n contents = contents.rest();\n Polylist p = ChordSymbol.chordSymbolsFromStrings(contents);\n p = p.cons(modeTag);\n diatonicRules.add(p);\n }\n } else // Type definitions with costs\n if (blockCategory.equals(\"brick-type\")) {\n if (contents.length() != 2 && contents.length() != 1)\n ErrorLog.log(ErrorLog.WARNING, \"Not a correct \" + \"brick-type declaration: \" + contents);\n else {\n String type = contents.first().toString();\n contents = contents.rest();\n if (contents.isEmpty()) {\n addType(type);\n } else {\n Object cost = contents.first();\n if (cost instanceof Long)\n addType(type, (Long) cost);\n else {\n ErrorLog.log(ErrorLog.WARNING, \"Incorrect \" + \"cost for brick type: \" + type);\n addType(type);\n }\n }\n }\n } else // Brick definitions themselves\n if (blockCategory.equals(DEF_BRICK) && contents.length() > 4) {\n // read in the information as a saved polylist to be\n // constructed properly as a Brick later\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n if (polymap.containsKey(brickName))\n polymap.get(brickName).add((Polylist) token);\n else {\n LinkedList newKey = new LinkedList();\n newKey.add((Polylist) token);\n polymap.put(brickName, newKey);\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper type for \" + \"a BrickDictionary item: \" + token, true);\n }\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for \" + \"a token: \" + token, true);\n }\n }\n // for each set of bricks with the same name\n for (LinkedList brickStem : polymap.values()) {\n // for each unprocessed brick definition\n for (Polylist contents : brickStem) {\n // pull out the name, qualifier, and contents\n contents = contents.rest();\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n String brickQualifier = \"\";\n if (contents.first() instanceof Polylist) {\n brickQualifier = ((Polylist) contents.first()).toStringSansParens();\n contents = contents.rest();\n }\n String brickMode = contents.first().toString();\n contents = contents.rest();\n String brickType = contents.first().toString();\n contents = contents.rest();\n if (!hasType(brickType))\n ErrorLog.log(ErrorLog.WARNING, brickName + \" is of \" + \"uninitialized type \" + brickType + \"; will register as non-brick\");\n String brickKeyString = contents.first().toString();\n contents = contents.rest();\n long brickKeyNum = keyNameToNum(brickKeyString);\n // add the brick, recursively defining subbricks\n Brick currentBrick = new Brick(brickName, brickQualifier, brickKeyNum, brickType, contents, this, brickMode, polymap);\n addBrick(currentBrick);\n }\n }\n // initialize the postprocessor with the rules for diatonic key checking\n processor = new PostProcessor(equivalenceRules, diatonicRules);\n }\n\n /**\n * dashless\n * Helper function to remove dashes from brick names\n * @param s, a String\n * @return a String with dashes replaced with spaces\n */\n public static String dashless(String s) {\n return s.replace('-', ' ');\n }\n\n public static String dashed(String s) {\n return s.replace(' ', '-');\n }\n\n /**\n * writeDictionary\n * Writes out an entire dictionary of definitions. Currently deprecated.\n * @param filename, the file to write to\n */\n public void writeDictionary(String filename) {\n FileWriter fstream;\n try {\n fstream = new FileWriter(filename);\n BufferedWriter out = new BufferedWriter(fstream);\n out.write(\"\\\\\\\\ Type Definitions\\n\\n\");\n Set types = costMap.keySet();\n for (String type : types) {\n long cost = costMap.get(type);\n Polylist brickType = Polylist.list(\"brick-type\", type, cost);\n out.write(brickType.toString());\n out.write(\"\\n\");\n }\n out.write(\"\\n\\n\\\\\\\\ Brick Definitions\\n\\n\");\n for (Brick brick : getFullMap()) {\n out.write(brick.toPolylist().toString());\n out.write(\"\\n\\n\");\n }\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not write dictionary file.\");\n }\n }\n // end of class BrickLibrary\n}\n"} {"task_id": "Java_1110", "language": "Java", "task_type": "while_statement", "source_file": "java/github/Impro-Visor/Impro-Visor/src/imp/roadmap/brickdictionary/BrickLibrary.java", "mask_start_position": 14696, "mask_end_position": 14823, "canonical_solution": "while (iter.hasNext()) {\n Brick currentBrick = (Brick) iter.next();\n currentBrick.printBrick();\n }", "pre_mask_code": "/**\n * This Java Class is part of the Impro-Visor Application\n */\npackage imp.roadmap.brickdictionary;\n\nimport imp.roadmap.cykparser.PostProcessor;\nimport imp.data.ChordSymbol;\nimport imp.util.ErrorLog;\nimport java.util.Collection;\nimport polya.*;\nimport java.io.*;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.Set;\n\n/**\n * purpose: Methods relating to the brick library (dictionary)\n * @author Zachary Merritt\n */\npublic class BrickLibrary {\n\n /**\n * Keyword used in defining bricks in a dictionary.\n */\n public static final String DEF_BRICK = \"defbrick\";\n\n /**\n * This is the conjunction to be used to describe appendages to Cadences\n * such as Overrun and Dropback\n */\n public static String CONJUNCTION = \" + \";\n\n /**\n * The name for an Overrun\n */\n public static String OVERRUN = \"Overrun\";\n\n /**\n * The name for a Dropback\n */\n public static String DROPBACK = \"Dropback\";\n\n // Lists of key names, with indices corresponding to numeric key value\n private static final String[] KEY_NAME_ARRAY = { \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\" };\n\n private static final String[] KEY_NAME_ARRAY_SHARPS = { \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\" };\n\n // the default cost of a type with no cost specified\n private static final long DEFAULT_COST = 40;\n\n // the string describing an invisible brick's type\n public static final String INVISIBLE = \"Invisible\";\n\n // all bricks\n private LinkedHashMap> brickMap;\n\n // brick costs by type\n private LinkedHashMap costMap;\n\n // the postprocessing unit\n public PostProcessor processor;\n\n /**\n * BrickLibrary / 0\n * Default constructor for an empty BrickLibrary with no specified types\n */\n public BrickLibrary() {\n brickMap = new LinkedHashMap>();\n costMap = new LinkedHashMap();\n }\n\n /**\n * getNames\n * Returns the list of the names of all bricks stored in the dictionary\n * @return an array of Strings\n */\n public String[] getNames() {\n return brickMap.keySet().toArray(new String[0]);\n }\n\n /**\n * addBrickDefinition\n * When a new brick is created in the library, adds its contents to the\n * current brickMap and adds its definition to the dictionary file\n * @param brick, a newly created Brick\n */\n public void addBrickDefinition(Brick brick, String dictionaryFilename) {\n // add the brick to the current BrickLibrary\n boolean added = addBrick(brick);\n if (!added)\n return;\n Brick definitionBrick = new Brick(brick);\n // make a properly-formatted brick definition\n Polylist defn = definitionBrick.toBrickDefinition();\n String defnString = defn.toString();\n if (!brick.getVariant().equals(\"\"))\n defnString.replaceFirst(\" \\\\(\", \"\\\\(\");\n defnString = defnString.replaceAll(\" \\\\(\", \"\\n \\\\(\");\n // write out the string with the definition to the end of the file\n try {\n FileOutputStream out = new FileOutputStream(dictionaryFilename, true);\n out.write(\"\\n\".getBytes());\n out.write(defnString.getBytes());\n out.write(\"\\n\".getBytes());\n out.close();\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Cannot write to dictionary\");\n }\n }\n\n /**\n * addBrick\n * Adds a brick to the library's brickMap\n * @param brick, a created Brick\n */\n public boolean addBrick(Brick brick) {\n if (brickMap.containsKey(brick.getName())) {\n // first, we check if the brick is a duplicate or just a brick with\n // an already-used name but a different qualifier. Presently, a\n // doubly-defined brick will have both definitions added to the\n // dictionary but will warn a user if the two definitions are\n LinkedList sameStemList = brickMap.get(brick.getName());\n for (Brick sameStem : sameStemList) {\n if (sameStem.getVariant().equals(brick.getVariant())) {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary already contains \" + brick.getName() + \"(\" + brick.getVariant() + \"): will not\" + \" add to dictionary\", true);\n return false;\n }\n }\n sameStemList.add(brick);\n } else {\n // adding a brick with a new brickname\n LinkedList brickList = new LinkedList();\n brickList.add(brick);\n this.brickMap.put(brick.name, brickList);\n }\n // special rule for creating overruns\n if (brick.getType().equals(\"Cadence\")) {\n String overrunName = brick.getName() + CONJUNCTION + OVERRUN;\n long overrunKeyNum = brick.getKey();\n String overrunType = OVERRUN;\n String overrunMode = brick.getMode();\n String overrunQualifier = brick.getVariant();\n // take blocks from regular cadence and add the next chord\n // in the circle of fifths with the same quality as the\n // resolution\n ArrayList overrunBlocks = new ArrayList();\n overrunBlocks.add(brick);\n ArrayList chords = brick.flattenBlock();\n ChordBlock prevChord = chords.get(chords.size() - 1);\n ChordBlock overrunChord = new ChordBlock(prevChord.transposeName(5), prevChord.getDuration());\n overrunBlocks.add(overrunChord);\n // make a new brick from this list of blocks\n Brick overrun = new Brick(overrunName, overrunQualifier, overrunKeyNum, overrunType, overrunBlocks, overrunMode);\n addBrick(overrun);\n String dropbackName = brick.getName() + CONJUNCTION + DROPBACK;\n long dropbackKeyNum = brick.getKey();\n String dropbackType = DROPBACK;\n String dropbackMode = brick.getMode();\n String dropbackQualifier = brick.getVariant();\n // take blocks from regular cadence and add a relative VI dominant\n // to form a dropback.\n // FIX: This is not the only possible dropback!!\n // For example, we want to allow iii-IV's major and minor.\n ArrayList dropbackBlocks = new ArrayList();\n dropbackBlocks.add(brick);\n String dropbackChordName = keyNumToName((brick.getKey() + 9) % 12);\n /* I think it was wrong to include this in the first place:\n \n if (dropbackMode.equals(\"minor\"))\n dropbackChordName += \"7b5\";\n else\n */\n dropbackChordName += 7;\n ChordBlock dropbackChord = new ChordBlock(dropbackChordName, prevChord.getDuration());\n dropbackBlocks.add(dropbackChord);\n // make a new brick from this list of blocks\n Brick dropback = new Brick(dropbackName, dropbackQualifier, dropbackKeyNum, dropbackType, dropbackBlocks, dropbackMode);\n addBrick(dropback);\n }\n return true;\n }\n\n /**\n * getBrick (definition)\n * Gets the default Brick with the given name from the dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k) {\n if (brickMap.containsKey(s)) {\n LinkedList possibleBricks = brickMap.get(s);\n for (Brick oldBrick : possibleBricks) if (!oldBrick.getType().equals(INVISIBLE)) {\n Brick brick = new Brick(oldBrick);\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n }\n }\n // if no brick is returned\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s + \" with qualifier \" + q, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with duration)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = new Brick(brickMap.get(s).getFirst());\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * hasBrick\n * Checks if a Brick with a given name is in the dictionary\n * @param s, the Brick name\n * @return a boolean\n */\n public boolean hasBrick(String s) {\n return (brickMap.containsKey(s));\n }\n\n /**\n * getFullMap\n * Gets the list of all Bricks in the dictionary as a single collection\n * @return a Collection of Bricks\n */\n public Collection getFullMap() {\n LinkedList values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n values.addAll(brickname);\n }\n return values;\n }\n\n /**\n * getMap\n * Gets the organized list of all Bricks in the dictionary\n * @return a LinkedList of LinkedLists of Bricks\n */\n public LinkedList> getMap() {\n LinkedList> values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n LinkedList newlist = new LinkedList();\n for (Brick brick : brickname) if (!brick.getType().equals(INVISIBLE))\n newlist.add(brick);\n if (!newlist.isEmpty())\n values.add(newlist);\n }\n return values;\n }\n\n /**\n * removeBrick\n * Removes all Bricks matching a given Brick from the dictionary\n * @param brick, the Brick to be removed itself\n */\n public void removeBrick(Brick brick) {\n this.brickMap.remove(brick.name);\n }\n\n /**\n * removeBrick\n * Removes all Bricks with a given name from the dictionary\n * @param brickName, the name of the Brick(s) to be removed\n */\n public void removeBrick(String brickName) {\n this.brickMap.remove(brickName);\n }\n\n /**\n * exileBrick\n * Takes a Brick out of the visible brick library\n * @param brick, the brick to remove\n */\n public void exileBrick(Brick brick, String dictionaryFilename) {\n // define the search term (the name) for the given brick\n String brickType = \" \" + brick.getType() + \" \";\n String brickDefHead = DEF_BRICK + dashed(brick.getName());\n String qualifier = brick.getVariant();\n if (!qualifier.isEmpty())\n brickDefHead += \"(\" + qualifier + \")\";\n brickDefHead += \" \";\n // open the file and read in its contents\n try {\n File dictionary = new File(dictionaryFilename);\n FileReader in = new FileReader(dictionary);\n BufferedReader reader = new BufferedReader(in);\n String line = reader.readLine();\n String newfile = \"\";\n while (line != null) {\n // Exiling a brick is just taking the type and changing it\n // to be invisible\n if (line.contains(brickDefHead)) {\n line = line.replaceFirst(brickType, \" \" + INVISIBLE + \" \");\n }\n newfile += line + \"\\r\\n\";\n line = reader.readLine();\n }\n // write out the modified dictionary\n FileWriter writer = new FileWriter(dictionaryFilename);\n writer.write(newfile);\n writer.close();\n processDictionary(dictionaryFilename);\n } catch (IOException ioe) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not modify brick in dictionary\");\n }\n }\n\n /**\n * printDictionary\n * Prints every brick in the dictionary to System.err\n */\n public void printDictionary() {\n Iterator iter = getFullMap().iterator();\n ", "post_mask_code": "\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the default cost\n * @param t, a type, a String\n */\n public void addType(String t) {\n costMap.put(t, DEFAULT_COST);\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the specified cost\n * @param t, a type, a String\n * @param c, a cost, a long\n */\n public void addType(String t, long c) {\n costMap.put(t, c);\n }\n\n /**\n * getCost\n * Gets the cost associated with the given type\n * @param t, the type whose cost is desired (a String)\n * @return the cost, a long\n */\n public long getCost(String t) {\n if (!hasType(t))\n ErrorLog.log(ErrorLog.SEVERE, \"Type does not exist, will register\" + \"as an invisible brick: \" + t);\n return costMap.get(t);\n }\n\n /**\n * hasType\n * Checks if a given type is contained in the dictionary\n * @param t, a type (a String)\n * @return a boolean\n */\n public boolean hasType(String t) {\n return costMap.containsKey(t);\n }\n\n /**\n * getTypes\n * Gets the list of all types in the dictionary\n * @return an array of Strings of types\n */\n public String[] getTypes() {\n return costMap.keySet().toArray(new String[0]);\n }\n\n /**\n * isValidKey\n * Checks if a given key's name actually describes a key\n * @param keyName, a key's name as a String\n * @return a boolean\n */\n public static Boolean isValidKey(String keyName) {\n return keyName.equals(\"C\") || keyName.equals(\"B#\") || keyName.equals(\"C#\") || keyName.equals(\"Db\") || keyName.equals(\"D\") || keyName.equals(\"D#\") || keyName.equals(\"Eb\") || keyName.equals(\"E\") || keyName.equals(\"Fb\") || keyName.equals(\"F\") || keyName.equals(\"E#\") || keyName.equals(\"F#\") || keyName.equals(\"Gb\") || keyName.equals(\"G\") || keyName.equals(\"G#\") || keyName.equals(\"Ab\") || keyName.equals(\"A\") || keyName.equals(\"A#\") || keyName.equals(\"Bb\") || keyName.equals(\"B\") || keyName.equals(\"Cb\");\n }\n\n /**\n * keyNameToNum\n * Takes a key by name and returns the long describing that key\n * @param keyName, a key as a String\n * @return the same key as a long\n */\n public static long keyNameToNum(String keyName) {\n if (keyName.equals(\"\"))\n return -1;\n if (keyName.equals(\"C\") || keyName.equals(\"B#\"))\n return 0;\n if (keyName.equals(\"C#\") || keyName.equals(\"Db\"))\n return 1;\n if (keyName.equals(\"D\"))\n return 2;\n if (keyName.equals(\"D#\") || keyName.equals(\"Eb\"))\n return 3;\n if (keyName.equals(\"E\") || keyName.equals(\"Fb\"))\n return 4;\n if (keyName.equals(\"F\") || keyName.equals(\"E#\"))\n return 5;\n if (keyName.equals(\"F#\") || keyName.equals(\"Gb\"))\n return 6;\n if (keyName.equals(\"G\"))\n return 7;\n if (keyName.equals(\"G#\") || keyName.equals(\"Ab\"))\n return 8;\n if (keyName.equals(\"A\"))\n return 9;\n if (keyName.equals(\"A#\") || keyName.equals(\"Bb\"))\n return 10;\n if (keyName.equals(\"B\") || keyName.equals(\"Cb\"))\n return 11;\n else {\n ErrorLog.log(ErrorLog.SEVERE, \"Incorrect key formatting: \" + keyName);\n return -1;\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and converts it to a key as a String with flats if\n * accidentals are necessary\n * @param keyNum, a long describing a key\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY[(int) keyNum];\n } else if (keyNum == -1)\n return \"\";\n else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and whether or not to use sharps and converts it\n * to a key as a String\n * @param keyNum, a long describing a key\n * @boolean sharps, a boolean describing whether or not to use sharps\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum, boolean sharps) {\n if (sharps) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY_SHARPS[(int) keyNum];\n } else if (keyNum == -1) {\n return \"\";\n } else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n } else {\n return keyNumToName(keyNum);\n }\n }\n\n /**\n * processDictionary\n * Reads in all the dictionary information in the file to define appropriate\n * objects in the BrickDictionary.\n * @throws IOException\n */\n public void processDictionary(String dictionaryFilename) throws IOException {\n FileInputStream fis = new FileInputStream(dictionaryFilename);\n Tokenizer in = new Tokenizer(fis);\n in.slashSlashComments(true);\n in.slashStarComments(true);\n Object token;\n ArrayList equivalenceRules = new ArrayList();\n ArrayList diatonicRules = new ArrayList();\n LinkedHashMap> polymap = new LinkedHashMap>();\n brickMap.clear();\n // Read in S expressions until end of file is reached\n while ((token = in.nextSexp()) != Tokenizer.eof) {\n if (token instanceof Polylist) {\n Polylist contents = (Polylist) token;\n // Check that polylist has enough fields to be a brick\n // Needs BlockType (i.e. DEF_BRICK), name, key, and contents\n if (contents.length() < 2) {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for\" + \" a BrickDictionary item: \" + contents, true);\n } else {\n String blockCategory = contents.first().toString();\n contents = contents.rest();\n // Equivalence rules for the postprocessor\n if (blockCategory.equals(\"equiv\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty equivalence \" + \"rule in dictionary\");\n } else {\n Polylist chords = ChordSymbol.chordSymbolsFromStrings(contents);\n equivalenceRules.add(chords);\n }\n } else // Diatonic rules for the postprocessor\n if (blockCategory.equals(\"diatonic\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty diatonic \" + \"rule in dictionary\");\n } else {\n String modeTag = contents.first().toString();\n contents = contents.rest();\n Polylist p = ChordSymbol.chordSymbolsFromStrings(contents);\n p = p.cons(modeTag);\n diatonicRules.add(p);\n }\n } else // Type definitions with costs\n if (blockCategory.equals(\"brick-type\")) {\n if (contents.length() != 2 && contents.length() != 1)\n ErrorLog.log(ErrorLog.WARNING, \"Not a correct \" + \"brick-type declaration: \" + contents);\n else {\n String type = contents.first().toString();\n contents = contents.rest();\n if (contents.isEmpty()) {\n addType(type);\n } else {\n Object cost = contents.first();\n if (cost instanceof Long)\n addType(type, (Long) cost);\n else {\n ErrorLog.log(ErrorLog.WARNING, \"Incorrect \" + \"cost for brick type: \" + type);\n addType(type);\n }\n }\n }\n } else // Brick definitions themselves\n if (blockCategory.equals(DEF_BRICK) && contents.length() > 4) {\n // read in the information as a saved polylist to be\n // constructed properly as a Brick later\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n if (polymap.containsKey(brickName))\n polymap.get(brickName).add((Polylist) token);\n else {\n LinkedList newKey = new LinkedList();\n newKey.add((Polylist) token);\n polymap.put(brickName, newKey);\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper type for \" + \"a BrickDictionary item: \" + token, true);\n }\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for \" + \"a token: \" + token, true);\n }\n }\n // for each set of bricks with the same name\n for (LinkedList brickStem : polymap.values()) {\n // for each unprocessed brick definition\n for (Polylist contents : brickStem) {\n // pull out the name, qualifier, and contents\n contents = contents.rest();\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n String brickQualifier = \"\";\n if (contents.first() instanceof Polylist) {\n brickQualifier = ((Polylist) contents.first()).toStringSansParens();\n contents = contents.rest();\n }\n String brickMode = contents.first().toString();\n contents = contents.rest();\n String brickType = contents.first().toString();\n contents = contents.rest();\n if (!hasType(brickType))\n ErrorLog.log(ErrorLog.WARNING, brickName + \" is of \" + \"uninitialized type \" + brickType + \"; will register as non-brick\");\n String brickKeyString = contents.first().toString();\n contents = contents.rest();\n long brickKeyNum = keyNameToNum(brickKeyString);\n // add the brick, recursively defining subbricks\n Brick currentBrick = new Brick(brickName, brickQualifier, brickKeyNum, brickType, contents, this, brickMode, polymap);\n addBrick(currentBrick);\n }\n }\n // initialize the postprocessor with the rules for diatonic key checking\n processor = new PostProcessor(equivalenceRules, diatonicRules);\n }\n\n /**\n * dashless\n * Helper function to remove dashes from brick names\n * @param s, a String\n * @return a String with dashes replaced with spaces\n */\n public static String dashless(String s) {\n return s.replace('-', ' ');\n }\n\n public static String dashed(String s) {\n return s.replace(' ', '-');\n }\n\n /**\n * writeDictionary\n * Writes out an entire dictionary of definitions. Currently deprecated.\n * @param filename, the file to write to\n */\n public void writeDictionary(String filename) {\n FileWriter fstream;\n try {\n fstream = new FileWriter(filename);\n BufferedWriter out = new BufferedWriter(fstream);\n out.write(\"\\\\\\\\ Type Definitions\\n\\n\");\n Set types = costMap.keySet();\n for (String type : types) {\n long cost = costMap.get(type);\n Polylist brickType = Polylist.list(\"brick-type\", type, cost);\n out.write(brickType.toString());\n out.write(\"\\n\");\n }\n out.write(\"\\n\\n\\\\\\\\ Brick Definitions\\n\\n\");\n for (Brick brick : getFullMap()) {\n out.write(brick.toPolylist().toString());\n out.write(\"\\n\\n\");\n }\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not write dictionary file.\");\n }\n }\n // end of class BrickLibrary\n}\n"} {"task_id": "Java_1111", "language": "Java", "task_type": "try_statement", "source_file": "java/github/Impro-Visor/Impro-Visor/src/imp/roadmap/brickdictionary/BrickLibrary.java", "mask_start_position": 3211, "mask_end_position": 3568, "canonical_solution": "try {\n FileOutputStream out = new FileOutputStream(dictionaryFilename, true);\n out.write(\"\\n\".getBytes());\n out.write(defnString.getBytes());\n out.write(\"\\n\".getBytes());\n out.close();\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Cannot write to dictionary\");\n }", "pre_mask_code": "/**\n * This Java Class is part of the Impro-Visor Application\n */\npackage imp.roadmap.brickdictionary;\n\nimport imp.roadmap.cykparser.PostProcessor;\nimport imp.data.ChordSymbol;\nimport imp.util.ErrorLog;\nimport java.util.Collection;\nimport polya.*;\nimport java.io.*;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.Set;\n\n/**\n * purpose: Methods relating to the brick library (dictionary)\n * @author Zachary Merritt\n */\npublic class BrickLibrary {\n\n /**\n * Keyword used in defining bricks in a dictionary.\n */\n public static final String DEF_BRICK = \"defbrick\";\n\n /**\n * This is the conjunction to be used to describe appendages to Cadences\n * such as Overrun and Dropback\n */\n public static String CONJUNCTION = \" + \";\n\n /**\n * The name for an Overrun\n */\n public static String OVERRUN = \"Overrun\";\n\n /**\n * The name for a Dropback\n */\n public static String DROPBACK = \"Dropback\";\n\n // Lists of key names, with indices corresponding to numeric key value\n private static final String[] KEY_NAME_ARRAY = { \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\" };\n\n private static final String[] KEY_NAME_ARRAY_SHARPS = { \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\" };\n\n // the default cost of a type with no cost specified\n private static final long DEFAULT_COST = 40;\n\n // the string describing an invisible brick's type\n public static final String INVISIBLE = \"Invisible\";\n\n // all bricks\n private LinkedHashMap> brickMap;\n\n // brick costs by type\n private LinkedHashMap costMap;\n\n // the postprocessing unit\n public PostProcessor processor;\n\n /**\n * BrickLibrary / 0\n * Default constructor for an empty BrickLibrary with no specified types\n */\n public BrickLibrary() {\n brickMap = new LinkedHashMap>();\n costMap = new LinkedHashMap();\n }\n\n /**\n * getNames\n * Returns the list of the names of all bricks stored in the dictionary\n * @return an array of Strings\n */\n public String[] getNames() {\n return brickMap.keySet().toArray(new String[0]);\n }\n\n /**\n * addBrickDefinition\n * When a new brick is created in the library, adds its contents to the\n * current brickMap and adds its definition to the dictionary file\n * @param brick, a newly created Brick\n */\n public void addBrickDefinition(Brick brick, String dictionaryFilename) {\n // add the brick to the current BrickLibrary\n boolean added = addBrick(brick);\n if (!added)\n return;\n Brick definitionBrick = new Brick(brick);\n // make a properly-formatted brick definition\n Polylist defn = definitionBrick.toBrickDefinition();\n String defnString = defn.toString();\n if (!brick.getVariant().equals(\"\"))\n defnString.replaceFirst(\" \\\\(\", \"\\\\(\");\n defnString = defnString.replaceAll(\" \\\\(\", \"\\n \\\\(\");\n // write out the string with the definition to the end of the file\n ", "post_mask_code": "\n }\n\n /**\n * addBrick\n * Adds a brick to the library's brickMap\n * @param brick, a created Brick\n */\n public boolean addBrick(Brick brick) {\n if (brickMap.containsKey(brick.getName())) {\n // first, we check if the brick is a duplicate or just a brick with\n // an already-used name but a different qualifier. Presently, a\n // doubly-defined brick will have both definitions added to the\n // dictionary but will warn a user if the two definitions are\n LinkedList sameStemList = brickMap.get(brick.getName());\n for (Brick sameStem : sameStemList) {\n if (sameStem.getVariant().equals(brick.getVariant())) {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary already contains \" + brick.getName() + \"(\" + brick.getVariant() + \"): will not\" + \" add to dictionary\", true);\n return false;\n }\n }\n sameStemList.add(brick);\n } else {\n // adding a brick with a new brickname\n LinkedList brickList = new LinkedList();\n brickList.add(brick);\n this.brickMap.put(brick.name, brickList);\n }\n // special rule for creating overruns\n if (brick.getType().equals(\"Cadence\")) {\n String overrunName = brick.getName() + CONJUNCTION + OVERRUN;\n long overrunKeyNum = brick.getKey();\n String overrunType = OVERRUN;\n String overrunMode = brick.getMode();\n String overrunQualifier = brick.getVariant();\n // take blocks from regular cadence and add the next chord\n // in the circle of fifths with the same quality as the\n // resolution\n ArrayList overrunBlocks = new ArrayList();\n overrunBlocks.add(brick);\n ArrayList chords = brick.flattenBlock();\n ChordBlock prevChord = chords.get(chords.size() - 1);\n ChordBlock overrunChord = new ChordBlock(prevChord.transposeName(5), prevChord.getDuration());\n overrunBlocks.add(overrunChord);\n // make a new brick from this list of blocks\n Brick overrun = new Brick(overrunName, overrunQualifier, overrunKeyNum, overrunType, overrunBlocks, overrunMode);\n addBrick(overrun);\n String dropbackName = brick.getName() + CONJUNCTION + DROPBACK;\n long dropbackKeyNum = brick.getKey();\n String dropbackType = DROPBACK;\n String dropbackMode = brick.getMode();\n String dropbackQualifier = brick.getVariant();\n // take blocks from regular cadence and add a relative VI dominant\n // to form a dropback.\n // FIX: This is not the only possible dropback!!\n // For example, we want to allow iii-IV's major and minor.\n ArrayList dropbackBlocks = new ArrayList();\n dropbackBlocks.add(brick);\n String dropbackChordName = keyNumToName((brick.getKey() + 9) % 12);\n /* I think it was wrong to include this in the first place:\n \n if (dropbackMode.equals(\"minor\"))\n dropbackChordName += \"7b5\";\n else\n */\n dropbackChordName += 7;\n ChordBlock dropbackChord = new ChordBlock(dropbackChordName, prevChord.getDuration());\n dropbackBlocks.add(dropbackChord);\n // make a new brick from this list of blocks\n Brick dropback = new Brick(dropbackName, dropbackQualifier, dropbackKeyNum, dropbackType, dropbackBlocks, dropbackMode);\n addBrick(dropback);\n }\n return true;\n }\n\n /**\n * getBrick (definition)\n * Gets the default Brick with the given name from the dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k) {\n if (brickMap.containsKey(s)) {\n LinkedList possibleBricks = brickMap.get(s);\n for (Brick oldBrick : possibleBricks) if (!oldBrick.getType().equals(INVISIBLE)) {\n Brick brick = new Brick(oldBrick);\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n }\n }\n // if no brick is returned\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s + \" with qualifier \" + q, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with duration)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = new Brick(brickMap.get(s).getFirst());\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * hasBrick\n * Checks if a Brick with a given name is in the dictionary\n * @param s, the Brick name\n * @return a boolean\n */\n public boolean hasBrick(String s) {\n return (brickMap.containsKey(s));\n }\n\n /**\n * getFullMap\n * Gets the list of all Bricks in the dictionary as a single collection\n * @return a Collection of Bricks\n */\n public Collection getFullMap() {\n LinkedList values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n values.addAll(brickname);\n }\n return values;\n }\n\n /**\n * getMap\n * Gets the organized list of all Bricks in the dictionary\n * @return a LinkedList of LinkedLists of Bricks\n */\n public LinkedList> getMap() {\n LinkedList> values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n LinkedList newlist = new LinkedList();\n for (Brick brick : brickname) if (!brick.getType().equals(INVISIBLE))\n newlist.add(brick);\n if (!newlist.isEmpty())\n values.add(newlist);\n }\n return values;\n }\n\n /**\n * removeBrick\n * Removes all Bricks matching a given Brick from the dictionary\n * @param brick, the Brick to be removed itself\n */\n public void removeBrick(Brick brick) {\n this.brickMap.remove(brick.name);\n }\n\n /**\n * removeBrick\n * Removes all Bricks with a given name from the dictionary\n * @param brickName, the name of the Brick(s) to be removed\n */\n public void removeBrick(String brickName) {\n this.brickMap.remove(brickName);\n }\n\n /**\n * exileBrick\n * Takes a Brick out of the visible brick library\n * @param brick, the brick to remove\n */\n public void exileBrick(Brick brick, String dictionaryFilename) {\n // define the search term (the name) for the given brick\n String brickType = \" \" + brick.getType() + \" \";\n String brickDefHead = DEF_BRICK + dashed(brick.getName());\n String qualifier = brick.getVariant();\n if (!qualifier.isEmpty())\n brickDefHead += \"(\" + qualifier + \")\";\n brickDefHead += \" \";\n // open the file and read in its contents\n try {\n File dictionary = new File(dictionaryFilename);\n FileReader in = new FileReader(dictionary);\n BufferedReader reader = new BufferedReader(in);\n String line = reader.readLine();\n String newfile = \"\";\n while (line != null) {\n // Exiling a brick is just taking the type and changing it\n // to be invisible\n if (line.contains(brickDefHead)) {\n line = line.replaceFirst(brickType, \" \" + INVISIBLE + \" \");\n }\n newfile += line + \"\\r\\n\";\n line = reader.readLine();\n }\n // write out the modified dictionary\n FileWriter writer = new FileWriter(dictionaryFilename);\n writer.write(newfile);\n writer.close();\n processDictionary(dictionaryFilename);\n } catch (IOException ioe) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not modify brick in dictionary\");\n }\n }\n\n /**\n * printDictionary\n * Prints every brick in the dictionary to System.err\n */\n public void printDictionary() {\n Iterator iter = getFullMap().iterator();\n while (iter.hasNext()) {\n Brick currentBrick = (Brick) iter.next();\n currentBrick.printBrick();\n }\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the default cost\n * @param t, a type, a String\n */\n public void addType(String t) {\n costMap.put(t, DEFAULT_COST);\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the specified cost\n * @param t, a type, a String\n * @param c, a cost, a long\n */\n public void addType(String t, long c) {\n costMap.put(t, c);\n }\n\n /**\n * getCost\n * Gets the cost associated with the given type\n * @param t, the type whose cost is desired (a String)\n * @return the cost, a long\n */\n public long getCost(String t) {\n if (!hasType(t))\n ErrorLog.log(ErrorLog.SEVERE, \"Type does not exist, will register\" + \"as an invisible brick: \" + t);\n return costMap.get(t);\n }\n\n /**\n * hasType\n * Checks if a given type is contained in the dictionary\n * @param t, a type (a String)\n * @return a boolean\n */\n public boolean hasType(String t) {\n return costMap.containsKey(t);\n }\n\n /**\n * getTypes\n * Gets the list of all types in the dictionary\n * @return an array of Strings of types\n */\n public String[] getTypes() {\n return costMap.keySet().toArray(new String[0]);\n }\n\n /**\n * isValidKey\n * Checks if a given key's name actually describes a key\n * @param keyName, a key's name as a String\n * @return a boolean\n */\n public static Boolean isValidKey(String keyName) {\n return keyName.equals(\"C\") || keyName.equals(\"B#\") || keyName.equals(\"C#\") || keyName.equals(\"Db\") || keyName.equals(\"D\") || keyName.equals(\"D#\") || keyName.equals(\"Eb\") || keyName.equals(\"E\") || keyName.equals(\"Fb\") || keyName.equals(\"F\") || keyName.equals(\"E#\") || keyName.equals(\"F#\") || keyName.equals(\"Gb\") || keyName.equals(\"G\") || keyName.equals(\"G#\") || keyName.equals(\"Ab\") || keyName.equals(\"A\") || keyName.equals(\"A#\") || keyName.equals(\"Bb\") || keyName.equals(\"B\") || keyName.equals(\"Cb\");\n }\n\n /**\n * keyNameToNum\n * Takes a key by name and returns the long describing that key\n * @param keyName, a key as a String\n * @return the same key as a long\n */\n public static long keyNameToNum(String keyName) {\n if (keyName.equals(\"\"))\n return -1;\n if (keyName.equals(\"C\") || keyName.equals(\"B#\"))\n return 0;\n if (keyName.equals(\"C#\") || keyName.equals(\"Db\"))\n return 1;\n if (keyName.equals(\"D\"))\n return 2;\n if (keyName.equals(\"D#\") || keyName.equals(\"Eb\"))\n return 3;\n if (keyName.equals(\"E\") || keyName.equals(\"Fb\"))\n return 4;\n if (keyName.equals(\"F\") || keyName.equals(\"E#\"))\n return 5;\n if (keyName.equals(\"F#\") || keyName.equals(\"Gb\"))\n return 6;\n if (keyName.equals(\"G\"))\n return 7;\n if (keyName.equals(\"G#\") || keyName.equals(\"Ab\"))\n return 8;\n if (keyName.equals(\"A\"))\n return 9;\n if (keyName.equals(\"A#\") || keyName.equals(\"Bb\"))\n return 10;\n if (keyName.equals(\"B\") || keyName.equals(\"Cb\"))\n return 11;\n else {\n ErrorLog.log(ErrorLog.SEVERE, \"Incorrect key formatting: \" + keyName);\n return -1;\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and converts it to a key as a String with flats if\n * accidentals are necessary\n * @param keyNum, a long describing a key\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY[(int) keyNum];\n } else if (keyNum == -1)\n return \"\";\n else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and whether or not to use sharps and converts it\n * to a key as a String\n * @param keyNum, a long describing a key\n * @boolean sharps, a boolean describing whether or not to use sharps\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum, boolean sharps) {\n if (sharps) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY_SHARPS[(int) keyNum];\n } else if (keyNum == -1) {\n return \"\";\n } else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n } else {\n return keyNumToName(keyNum);\n }\n }\n\n /**\n * processDictionary\n * Reads in all the dictionary information in the file to define appropriate\n * objects in the BrickDictionary.\n * @throws IOException\n */\n public void processDictionary(String dictionaryFilename) throws IOException {\n FileInputStream fis = new FileInputStream(dictionaryFilename);\n Tokenizer in = new Tokenizer(fis);\n in.slashSlashComments(true);\n in.slashStarComments(true);\n Object token;\n ArrayList equivalenceRules = new ArrayList();\n ArrayList diatonicRules = new ArrayList();\n LinkedHashMap> polymap = new LinkedHashMap>();\n brickMap.clear();\n // Read in S expressions until end of file is reached\n while ((token = in.nextSexp()) != Tokenizer.eof) {\n if (token instanceof Polylist) {\n Polylist contents = (Polylist) token;\n // Check that polylist has enough fields to be a brick\n // Needs BlockType (i.e. DEF_BRICK), name, key, and contents\n if (contents.length() < 2) {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for\" + \" a BrickDictionary item: \" + contents, true);\n } else {\n String blockCategory = contents.first().toString();\n contents = contents.rest();\n // Equivalence rules for the postprocessor\n if (blockCategory.equals(\"equiv\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty equivalence \" + \"rule in dictionary\");\n } else {\n Polylist chords = ChordSymbol.chordSymbolsFromStrings(contents);\n equivalenceRules.add(chords);\n }\n } else // Diatonic rules for the postprocessor\n if (blockCategory.equals(\"diatonic\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty diatonic \" + \"rule in dictionary\");\n } else {\n String modeTag = contents.first().toString();\n contents = contents.rest();\n Polylist p = ChordSymbol.chordSymbolsFromStrings(contents);\n p = p.cons(modeTag);\n diatonicRules.add(p);\n }\n } else // Type definitions with costs\n if (blockCategory.equals(\"brick-type\")) {\n if (contents.length() != 2 && contents.length() != 1)\n ErrorLog.log(ErrorLog.WARNING, \"Not a correct \" + \"brick-type declaration: \" + contents);\n else {\n String type = contents.first().toString();\n contents = contents.rest();\n if (contents.isEmpty()) {\n addType(type);\n } else {\n Object cost = contents.first();\n if (cost instanceof Long)\n addType(type, (Long) cost);\n else {\n ErrorLog.log(ErrorLog.WARNING, \"Incorrect \" + \"cost for brick type: \" + type);\n addType(type);\n }\n }\n }\n } else // Brick definitions themselves\n if (blockCategory.equals(DEF_BRICK) && contents.length() > 4) {\n // read in the information as a saved polylist to be\n // constructed properly as a Brick later\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n if (polymap.containsKey(brickName))\n polymap.get(brickName).add((Polylist) token);\n else {\n LinkedList newKey = new LinkedList();\n newKey.add((Polylist) token);\n polymap.put(brickName, newKey);\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper type for \" + \"a BrickDictionary item: \" + token, true);\n }\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for \" + \"a token: \" + token, true);\n }\n }\n // for each set of bricks with the same name\n for (LinkedList brickStem : polymap.values()) {\n // for each unprocessed brick definition\n for (Polylist contents : brickStem) {\n // pull out the name, qualifier, and contents\n contents = contents.rest();\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n String brickQualifier = \"\";\n if (contents.first() instanceof Polylist) {\n brickQualifier = ((Polylist) contents.first()).toStringSansParens();\n contents = contents.rest();\n }\n String brickMode = contents.first().toString();\n contents = contents.rest();\n String brickType = contents.first().toString();\n contents = contents.rest();\n if (!hasType(brickType))\n ErrorLog.log(ErrorLog.WARNING, brickName + \" is of \" + \"uninitialized type \" + brickType + \"; will register as non-brick\");\n String brickKeyString = contents.first().toString();\n contents = contents.rest();\n long brickKeyNum = keyNameToNum(brickKeyString);\n // add the brick, recursively defining subbricks\n Brick currentBrick = new Brick(brickName, brickQualifier, brickKeyNum, brickType, contents, this, brickMode, polymap);\n addBrick(currentBrick);\n }\n }\n // initialize the postprocessor with the rules for diatonic key checking\n processor = new PostProcessor(equivalenceRules, diatonicRules);\n }\n\n /**\n * dashless\n * Helper function to remove dashes from brick names\n * @param s, a String\n * @return a String with dashes replaced with spaces\n */\n public static String dashless(String s) {\n return s.replace('-', ' ');\n }\n\n public static String dashed(String s) {\n return s.replace(' ', '-');\n }\n\n /**\n * writeDictionary\n * Writes out an entire dictionary of definitions. Currently deprecated.\n * @param filename, the file to write to\n */\n public void writeDictionary(String filename) {\n FileWriter fstream;\n try {\n fstream = new FileWriter(filename);\n BufferedWriter out = new BufferedWriter(fstream);\n out.write(\"\\\\\\\\ Type Definitions\\n\\n\");\n Set types = costMap.keySet();\n for (String type : types) {\n long cost = costMap.get(type);\n Polylist brickType = Polylist.list(\"brick-type\", type, cost);\n out.write(brickType.toString());\n out.write(\"\\n\");\n }\n out.write(\"\\n\\n\\\\\\\\ Brick Definitions\\n\\n\");\n for (Brick brick : getFullMap()) {\n out.write(brick.toPolylist().toString());\n out.write(\"\\n\\n\");\n }\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not write dictionary file.\");\n }\n }\n // end of class BrickLibrary\n}\n"} {"task_id": "Java_1112", "language": "Java", "task_type": "empty", "source_file": "java/github/Impro-Visor/Impro-Visor/src/imp/roadmap/brickdictionary/BrickLibrary.java", "mask_start_position": 208, "mask_end_position": 208, "canonical_solution": "", "pre_mask_code": "/**\n * This Java Class is part of the Impro-Visor Application\n */\npackage imp.roadmap.brickdictionary;\n\nimport imp.roadmap.cykparser.PostProcessor;\nimport imp.data.ChordSymbol;\nimport imp.util.ErrorLog;\nimpor", "post_mask_code": "t java.util.Collection;\nimport polya.*;\nimport java.io.*;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.Set;\n\n/**\n * purpose: Methods relating to the brick library (dictionary)\n * @author Zachary Merritt\n */\npublic class BrickLibrary {\n\n /**\n * Keyword used in defining bricks in a dictionary.\n */\n public static final String DEF_BRICK = \"defbrick\";\n\n /**\n * This is the conjunction to be used to describe appendages to Cadences\n * such as Overrun and Dropback\n */\n public static String CONJUNCTION = \" + \";\n\n /**\n * The name for an Overrun\n */\n public static String OVERRUN = \"Overrun\";\n\n /**\n * The name for a Dropback\n */\n public static String DROPBACK = \"Dropback\";\n\n // Lists of key names, with indices corresponding to numeric key value\n private static final String[] KEY_NAME_ARRAY = { \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\" };\n\n private static final String[] KEY_NAME_ARRAY_SHARPS = { \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\" };\n\n // the default cost of a type with no cost specified\n private static final long DEFAULT_COST = 40;\n\n // the string describing an invisible brick's type\n public static final String INVISIBLE = \"Invisible\";\n\n // all bricks\n private LinkedHashMap> brickMap;\n\n // brick costs by type\n private LinkedHashMap costMap;\n\n // the postprocessing unit\n public PostProcessor processor;\n\n /**\n * BrickLibrary / 0\n * Default constructor for an empty BrickLibrary with no specified types\n */\n public BrickLibrary() {\n brickMap = new LinkedHashMap>();\n costMap = new LinkedHashMap();\n }\n\n /**\n * getNames\n * Returns the list of the names of all bricks stored in the dictionary\n * @return an array of Strings\n */\n public String[] getNames() {\n return brickMap.keySet().toArray(new String[0]);\n }\n\n /**\n * addBrickDefinition\n * When a new brick is created in the library, adds its contents to the\n * current brickMap and adds its definition to the dictionary file\n * @param brick, a newly created Brick\n */\n public void addBrickDefinition(Brick brick, String dictionaryFilename) {\n // add the brick to the current BrickLibrary\n boolean added = addBrick(brick);\n if (!added)\n return;\n Brick definitionBrick = new Brick(brick);\n // make a properly-formatted brick definition\n Polylist defn = definitionBrick.toBrickDefinition();\n String defnString = defn.toString();\n if (!brick.getVariant().equals(\"\"))\n defnString.replaceFirst(\" \\\\(\", \"\\\\(\");\n defnString = defnString.replaceAll(\" \\\\(\", \"\\n \\\\(\");\n // write out the string with the definition to the end of the file\n try {\n FileOutputStream out = new FileOutputStream(dictionaryFilename, true);\n out.write(\"\\n\".getBytes());\n out.write(defnString.getBytes());\n out.write(\"\\n\".getBytes());\n out.close();\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Cannot write to dictionary\");\n }\n }\n\n /**\n * addBrick\n * Adds a brick to the library's brickMap\n * @param brick, a created Brick\n */\n public boolean addBrick(Brick brick) {\n if (brickMap.containsKey(brick.getName())) {\n // first, we check if the brick is a duplicate or just a brick with\n // an already-used name but a different qualifier. Presently, a\n // doubly-defined brick will have both definitions added to the\n // dictionary but will warn a user if the two definitions are\n LinkedList sameStemList = brickMap.get(brick.getName());\n for (Brick sameStem : sameStemList) {\n if (sameStem.getVariant().equals(brick.getVariant())) {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary already contains \" + brick.getName() + \"(\" + brick.getVariant() + \"): will not\" + \" add to dictionary\", true);\n return false;\n }\n }\n sameStemList.add(brick);\n } else {\n // adding a brick with a new brickname\n LinkedList brickList = new LinkedList();\n brickList.add(brick);\n this.brickMap.put(brick.name, brickList);\n }\n // special rule for creating overruns\n if (brick.getType().equals(\"Cadence\")) {\n String overrunName = brick.getName() + CONJUNCTION + OVERRUN;\n long overrunKeyNum = brick.getKey();\n String overrunType = OVERRUN;\n String overrunMode = brick.getMode();\n String overrunQualifier = brick.getVariant();\n // take blocks from regular cadence and add the next chord\n // in the circle of fifths with the same quality as the\n // resolution\n ArrayList overrunBlocks = new ArrayList();\n overrunBlocks.add(brick);\n ArrayList chords = brick.flattenBlock();\n ChordBlock prevChord = chords.get(chords.size() - 1);\n ChordBlock overrunChord = new ChordBlock(prevChord.transposeName(5), prevChord.getDuration());\n overrunBlocks.add(overrunChord);\n // make a new brick from this list of blocks\n Brick overrun = new Brick(overrunName, overrunQualifier, overrunKeyNum, overrunType, overrunBlocks, overrunMode);\n addBrick(overrun);\n String dropbackName = brick.getName() + CONJUNCTION + DROPBACK;\n long dropbackKeyNum = brick.getKey();\n String dropbackType = DROPBACK;\n String dropbackMode = brick.getMode();\n String dropbackQualifier = brick.getVariant();\n // take blocks from regular cadence and add a relative VI dominant\n // to form a dropback.\n // FIX: This is not the only possible dropback!!\n // For example, we want to allow iii-IV's major and minor.\n ArrayList dropbackBlocks = new ArrayList();\n dropbackBlocks.add(brick);\n String dropbackChordName = keyNumToName((brick.getKey() + 9) % 12);\n /* I think it was wrong to include this in the first place:\n \n if (dropbackMode.equals(\"minor\"))\n dropbackChordName += \"7b5\";\n else\n */\n dropbackChordName += 7;\n ChordBlock dropbackChord = new ChordBlock(dropbackChordName, prevChord.getDuration());\n dropbackBlocks.add(dropbackChord);\n // make a new brick from this list of blocks\n Brick dropback = new Brick(dropbackName, dropbackQualifier, dropbackKeyNum, dropbackType, dropbackBlocks, dropbackMode);\n addBrick(dropback);\n }\n return true;\n }\n\n /**\n * getBrick (definition)\n * Gets the default Brick with the given name from the dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k) {\n if (brickMap.containsKey(s)) {\n LinkedList possibleBricks = brickMap.get(s);\n for (Brick oldBrick : possibleBricks) if (!oldBrick.getType().equals(INVISIBLE)) {\n Brick brick = new Brick(oldBrick);\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n }\n }\n // if no brick is returned\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s + \" with qualifier \" + q, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with duration)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = new Brick(brickMap.get(s).getFirst());\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * getBrick (with qualifier)\n * Gets a particular Brick with a given name and qualifier from the\n * dictionary in key k\n * @param s, the retrieved Brick's name, a String\n * @param q, the retrieved Brick's qualifier, a String\n * @param k, the retrieved Brick's key, a long\n * @param d, the duration of the Brick, an int\n * @return the transposed Brick\n */\n public Brick getBrick(String s, String q, long k, int d) {\n if (brickMap.containsKey(s)) {\n Brick brick = null;\n for (Brick b : brickMap.get(s)) if (b.getVariant().equals(q)) {\n brick = new Brick(b);\n break;\n }\n if (brick != null) {\n brick.transpose((k - brick.getKey() + 12) % 12);\n brick.setDuration(d);\n return brick;\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Dictionary does not contain \" + s, true);\n return null;\n }\n }\n\n /**\n * hasBrick\n * Checks if a Brick with a given name is in the dictionary\n * @param s, the Brick name\n * @return a boolean\n */\n public boolean hasBrick(String s) {\n return (brickMap.containsKey(s));\n }\n\n /**\n * getFullMap\n * Gets the list of all Bricks in the dictionary as a single collection\n * @return a Collection of Bricks\n */\n public Collection getFullMap() {\n LinkedList values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n values.addAll(brickname);\n }\n return values;\n }\n\n /**\n * getMap\n * Gets the organized list of all Bricks in the dictionary\n * @return a LinkedList of LinkedLists of Bricks\n */\n public LinkedList> getMap() {\n LinkedList> values = new LinkedList();\n for (LinkedList brickname : brickMap.values()) {\n LinkedList newlist = new LinkedList();\n for (Brick brick : brickname) if (!brick.getType().equals(INVISIBLE))\n newlist.add(brick);\n if (!newlist.isEmpty())\n values.add(newlist);\n }\n return values;\n }\n\n /**\n * removeBrick\n * Removes all Bricks matching a given Brick from the dictionary\n * @param brick, the Brick to be removed itself\n */\n public void removeBrick(Brick brick) {\n this.brickMap.remove(brick.name);\n }\n\n /**\n * removeBrick\n * Removes all Bricks with a given name from the dictionary\n * @param brickName, the name of the Brick(s) to be removed\n */\n public void removeBrick(String brickName) {\n this.brickMap.remove(brickName);\n }\n\n /**\n * exileBrick\n * Takes a Brick out of the visible brick library\n * @param brick, the brick to remove\n */\n public void exileBrick(Brick brick, String dictionaryFilename) {\n // define the search term (the name) for the given brick\n String brickType = \" \" + brick.getType() + \" \";\n String brickDefHead = DEF_BRICK + dashed(brick.getName());\n String qualifier = brick.getVariant();\n if (!qualifier.isEmpty())\n brickDefHead += \"(\" + qualifier + \")\";\n brickDefHead += \" \";\n // open the file and read in its contents\n try {\n File dictionary = new File(dictionaryFilename);\n FileReader in = new FileReader(dictionary);\n BufferedReader reader = new BufferedReader(in);\n String line = reader.readLine();\n String newfile = \"\";\n while (line != null) {\n // Exiling a brick is just taking the type and changing it\n // to be invisible\n if (line.contains(brickDefHead)) {\n line = line.replaceFirst(brickType, \" \" + INVISIBLE + \" \");\n }\n newfile += line + \"\\r\\n\";\n line = reader.readLine();\n }\n // write out the modified dictionary\n FileWriter writer = new FileWriter(dictionaryFilename);\n writer.write(newfile);\n writer.close();\n processDictionary(dictionaryFilename);\n } catch (IOException ioe) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not modify brick in dictionary\");\n }\n }\n\n /**\n * printDictionary\n * Prints every brick in the dictionary to System.err\n */\n public void printDictionary() {\n Iterator iter = getFullMap().iterator();\n while (iter.hasNext()) {\n Brick currentBrick = (Brick) iter.next();\n currentBrick.printBrick();\n }\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the default cost\n * @param t, a type, a String\n */\n public void addType(String t) {\n costMap.put(t, DEFAULT_COST);\n }\n\n /**\n * addType\n * Adds a given type to the dictionary with the specified cost\n * @param t, a type, a String\n * @param c, a cost, a long\n */\n public void addType(String t, long c) {\n costMap.put(t, c);\n }\n\n /**\n * getCost\n * Gets the cost associated with the given type\n * @param t, the type whose cost is desired (a String)\n * @return the cost, a long\n */\n public long getCost(String t) {\n if (!hasType(t))\n ErrorLog.log(ErrorLog.SEVERE, \"Type does not exist, will register\" + \"as an invisible brick: \" + t);\n return costMap.get(t);\n }\n\n /**\n * hasType\n * Checks if a given type is contained in the dictionary\n * @param t, a type (a String)\n * @return a boolean\n */\n public boolean hasType(String t) {\n return costMap.containsKey(t);\n }\n\n /**\n * getTypes\n * Gets the list of all types in the dictionary\n * @return an array of Strings of types\n */\n public String[] getTypes() {\n return costMap.keySet().toArray(new String[0]);\n }\n\n /**\n * isValidKey\n * Checks if a given key's name actually describes a key\n * @param keyName, a key's name as a String\n * @return a boolean\n */\n public static Boolean isValidKey(String keyName) {\n return keyName.equals(\"C\") || keyName.equals(\"B#\") || keyName.equals(\"C#\") || keyName.equals(\"Db\") || keyName.equals(\"D\") || keyName.equals(\"D#\") || keyName.equals(\"Eb\") || keyName.equals(\"E\") || keyName.equals(\"Fb\") || keyName.equals(\"F\") || keyName.equals(\"E#\") || keyName.equals(\"F#\") || keyName.equals(\"Gb\") || keyName.equals(\"G\") || keyName.equals(\"G#\") || keyName.equals(\"Ab\") || keyName.equals(\"A\") || keyName.equals(\"A#\") || keyName.equals(\"Bb\") || keyName.equals(\"B\") || keyName.equals(\"Cb\");\n }\n\n /**\n * keyNameToNum\n * Takes a key by name and returns the long describing that key\n * @param keyName, a key as a String\n * @return the same key as a long\n */\n public static long keyNameToNum(String keyName) {\n if (keyName.equals(\"\"))\n return -1;\n if (keyName.equals(\"C\") || keyName.equals(\"B#\"))\n return 0;\n if (keyName.equals(\"C#\") || keyName.equals(\"Db\"))\n return 1;\n if (keyName.equals(\"D\"))\n return 2;\n if (keyName.equals(\"D#\") || keyName.equals(\"Eb\"))\n return 3;\n if (keyName.equals(\"E\") || keyName.equals(\"Fb\"))\n return 4;\n if (keyName.equals(\"F\") || keyName.equals(\"E#\"))\n return 5;\n if (keyName.equals(\"F#\") || keyName.equals(\"Gb\"))\n return 6;\n if (keyName.equals(\"G\"))\n return 7;\n if (keyName.equals(\"G#\") || keyName.equals(\"Ab\"))\n return 8;\n if (keyName.equals(\"A\"))\n return 9;\n if (keyName.equals(\"A#\") || keyName.equals(\"Bb\"))\n return 10;\n if (keyName.equals(\"B\") || keyName.equals(\"Cb\"))\n return 11;\n else {\n ErrorLog.log(ErrorLog.SEVERE, \"Incorrect key formatting: \" + keyName);\n return -1;\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and converts it to a key as a String with flats if\n * accidentals are necessary\n * @param keyNum, a long describing a key\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY[(int) keyNum];\n } else if (keyNum == -1)\n return \"\";\n else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n }\n\n /**\n * keyNumToName\n * Takes a key as a long and whether or not to use sharps and converts it\n * to a key as a String\n * @param keyNum, a long describing a key\n * @boolean sharps, a boolean describing whether or not to use sharps\n * @return a String of the same key\n */\n public static String keyNumToName(long keyNum, boolean sharps) {\n if (sharps) {\n if (keyNum >= 0 && keyNum < 12) {\n return KEY_NAME_ARRAY_SHARPS[(int) keyNum];\n } else if (keyNum == -1) {\n return \"\";\n } else {\n ErrorLog.log(ErrorLog.FATAL, \"Internal: Incorrect key number: \" + keyNum);\n return \"\";\n }\n } else {\n return keyNumToName(keyNum);\n }\n }\n\n /**\n * processDictionary\n * Reads in all the dictionary information in the file to define appropriate\n * objects in the BrickDictionary.\n * @throws IOException\n */\n public void processDictionary(String dictionaryFilename) throws IOException {\n FileInputStream fis = new FileInputStream(dictionaryFilename);\n Tokenizer in = new Tokenizer(fis);\n in.slashSlashComments(true);\n in.slashStarComments(true);\n Object token;\n ArrayList equivalenceRules = new ArrayList();\n ArrayList diatonicRules = new ArrayList();\n LinkedHashMap> polymap = new LinkedHashMap>();\n brickMap.clear();\n // Read in S expressions until end of file is reached\n while ((token = in.nextSexp()) != Tokenizer.eof) {\n if (token instanceof Polylist) {\n Polylist contents = (Polylist) token;\n // Check that polylist has enough fields to be a brick\n // Needs BlockType (i.e. DEF_BRICK), name, key, and contents\n if (contents.length() < 2) {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for\" + \" a BrickDictionary item: \" + contents, true);\n } else {\n String blockCategory = contents.first().toString();\n contents = contents.rest();\n // Equivalence rules for the postprocessor\n if (blockCategory.equals(\"equiv\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty equivalence \" + \"rule in dictionary\");\n } else {\n Polylist chords = ChordSymbol.chordSymbolsFromStrings(contents);\n equivalenceRules.add(chords);\n }\n } else // Diatonic rules for the postprocessor\n if (blockCategory.equals(\"diatonic\")) {\n if (contents.isEmpty()) {\n ErrorLog.log(ErrorLog.WARNING, \"Empty diatonic \" + \"rule in dictionary\");\n } else {\n String modeTag = contents.first().toString();\n contents = contents.rest();\n Polylist p = ChordSymbol.chordSymbolsFromStrings(contents);\n p = p.cons(modeTag);\n diatonicRules.add(p);\n }\n } else // Type definitions with costs\n if (blockCategory.equals(\"brick-type\")) {\n if (contents.length() != 2 && contents.length() != 1)\n ErrorLog.log(ErrorLog.WARNING, \"Not a correct \" + \"brick-type declaration: \" + contents);\n else {\n String type = contents.first().toString();\n contents = contents.rest();\n if (contents.isEmpty()) {\n addType(type);\n } else {\n Object cost = contents.first();\n if (cost instanceof Long)\n addType(type, (Long) cost);\n else {\n ErrorLog.log(ErrorLog.WARNING, \"Incorrect \" + \"cost for brick type: \" + type);\n addType(type);\n }\n }\n }\n } else // Brick definitions themselves\n if (blockCategory.equals(DEF_BRICK) && contents.length() > 4) {\n // read in the information as a saved polylist to be\n // constructed properly as a Brick later\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n if (polymap.containsKey(brickName))\n polymap.get(brickName).add((Polylist) token);\n else {\n LinkedList newKey = new LinkedList();\n newKey.add((Polylist) token);\n polymap.put(brickName, newKey);\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper type for \" + \"a BrickDictionary item: \" + token, true);\n }\n }\n } else {\n ErrorLog.log(ErrorLog.WARNING, \"Improper formatting for \" + \"a token: \" + token, true);\n }\n }\n // for each set of bricks with the same name\n for (LinkedList brickStem : polymap.values()) {\n // for each unprocessed brick definition\n for (Polylist contents : brickStem) {\n // pull out the name, qualifier, and contents\n contents = contents.rest();\n String brickName = dashless(contents.first().toString());\n contents = contents.rest();\n String brickQualifier = \"\";\n if (contents.first() instanceof Polylist) {\n brickQualifier = ((Polylist) contents.first()).toStringSansParens();\n contents = contents.rest();\n }\n String brickMode = contents.first().toString();\n contents = contents.rest();\n String brickType = contents.first().toString();\n contents = contents.rest();\n if (!hasType(brickType))\n ErrorLog.log(ErrorLog.WARNING, brickName + \" is of \" + \"uninitialized type \" + brickType + \"; will register as non-brick\");\n String brickKeyString = contents.first().toString();\n contents = contents.rest();\n long brickKeyNum = keyNameToNum(brickKeyString);\n // add the brick, recursively defining subbricks\n Brick currentBrick = new Brick(brickName, brickQualifier, brickKeyNum, brickType, contents, this, brickMode, polymap);\n addBrick(currentBrick);\n }\n }\n // initialize the postprocessor with the rules for diatonic key checking\n processor = new PostProcessor(equivalenceRules, diatonicRules);\n }\n\n /**\n * dashless\n * Helper function to remove dashes from brick names\n * @param s, a String\n * @return a String with dashes replaced with spaces\n */\n public static String dashless(String s) {\n return s.replace('-', ' ');\n }\n\n public static String dashed(String s) {\n return s.replace(' ', '-');\n }\n\n /**\n * writeDictionary\n * Writes out an entire dictionary of definitions. Currently deprecated.\n * @param filename, the file to write to\n */\n public void writeDictionary(String filename) {\n FileWriter fstream;\n try {\n fstream = new FileWriter(filename);\n BufferedWriter out = new BufferedWriter(fstream);\n out.write(\"\\\\\\\\ Type Definitions\\n\\n\");\n Set types = costMap.keySet();\n for (String type : types) {\n long cost = costMap.get(type);\n Polylist brickType = Polylist.list(\"brick-type\", type, cost);\n out.write(brickType.toString());\n out.write(\"\\n\");\n }\n out.write(\"\\n\\n\\\\\\\\ Brick Definitions\\n\\n\");\n for (Brick brick : getFullMap()) {\n out.write(brick.toPolylist().toString());\n out.write(\"\\n\\n\");\n }\n } catch (IOException ex) {\n ErrorLog.log(ErrorLog.SEVERE, \"Could not write dictionary file.\");\n }\n }\n // end of class BrickLibrary\n}\n"} {"task_id": "Java_1113", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse/birt/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ParameterMetaData.java", "mask_start_position": 866, "mask_end_position": 925, "canonical_solution": "public int getParameterMode(int param) throws OdaException ", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * Megha Nidhi Dahal - initial API and implementation and/or initial documentation\n * Actuate Corporation - code cleanup\n * *****************************************************************************\n */\npackage org.eclipse.birt.report.data.oda.excel.impl;\n\nimport org.eclipse.birt.report.data.oda.excel.impl.util.DataTypes;\nimport org.eclipse.datatools.connectivity.oda.IParameterMetaData;\nimport org.eclipse.datatools.connectivity.oda.OdaException;\n\n/**\n * Implementation class of IParameterMetaData for Excel ODA runtime driver,\n * which does not currently support input nor output parameters.\n */\npublic class ParameterMetaData implements IParameterMetaData {\n\n public int getParameterCount() throws OdaException {\n return 0;\n }\n\n ", "post_mask_code": "{\n return IParameterMetaData.parameterModeUnknown;\n }\n\n public String getParameterName(int param) throws OdaException {\n // name is not available\n return null;\n }\n\n public int getParameterType(int param) throws OdaException {\n return DataTypes.getTypeCode(null);\n }\n\n /*\n\t * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#\n\t * getParameterTypeName(int)\n\t */\n public String getParameterTypeName(int param) throws OdaException {\n int nativeTypeCode = getParameterType(param);\n return DataTypes.getNativeDataTypeName(nativeTypeCode);\n }\n\n public int getPrecision(int param) throws OdaException {\n return -1;\n }\n\n /*\n\t * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#getScale(int)\n\t */\n public int getScale(int param) throws OdaException {\n return -1;\n }\n\n public int isNullable(int param) throws OdaException {\n return IParameterMetaData.parameterNullableUnknown;\n }\n}\n"} {"task_id": "Java_1114", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse/birt/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ParameterMetaData.java", "mask_start_position": 1862, "mask_end_position": 1929, "canonical_solution": "{\n return IParameterMetaData.parameterNullableUnknown;\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * Megha Nidhi Dahal - initial API and implementation and/or initial documentation\n * Actuate Corporation - code cleanup\n * *****************************************************************************\n */\npackage org.eclipse.birt.report.data.oda.excel.impl;\n\nimport org.eclipse.birt.report.data.oda.excel.impl.util.DataTypes;\nimport org.eclipse.datatools.connectivity.oda.IParameterMetaData;\nimport org.eclipse.datatools.connectivity.oda.OdaException;\n\n/**\n * Implementation class of IParameterMetaData for Excel ODA runtime driver,\n * which does not currently support input nor output parameters.\n */\npublic class ParameterMetaData implements IParameterMetaData {\n\n public int getParameterCount() throws OdaException {\n return 0;\n }\n\n public int getParameterMode(int param) throws OdaException {\n return IParameterMetaData.parameterModeUnknown;\n }\n\n public String getParameterName(int param) throws OdaException {\n // name is not available\n return null;\n }\n\n public int getParameterType(int param) throws OdaException {\n return DataTypes.getTypeCode(null);\n }\n\n /*\n\t * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#\n\t * getParameterTypeName(int)\n\t */\n public String getParameterTypeName(int param) throws OdaException {\n int nativeTypeCode = getParameterType(param);\n return DataTypes.getNativeDataTypeName(nativeTypeCode);\n }\n\n public int getPrecision(int param) throws OdaException {\n return -1;\n }\n\n /*\n\t * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#getScale(int)\n\t */\n public int getScale(int param) throws OdaException {\n return -1;\n }\n\n public int isNullable(int param) throws OdaException ", "post_mask_code": "\n}\n"} {"task_id": "Java_1115", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse/birt/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ParameterMetaData.java", "mask_start_position": 1225, "mask_end_position": 1227, "canonical_solution": ");", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * Megha Nidhi Dahal - initial API and implementation and/or initial documentation\n * Actuate Corporation - code cleanup\n * *****************************************************************************\n */\npackage org.eclipse.birt.report.data.oda.excel.impl;\n\nimport org.eclipse.birt.report.data.oda.excel.impl.util.DataTypes;\nimport org.eclipse.datatools.connectivity.oda.IParameterMetaData;\nimport org.eclipse.datatools.connectivity.oda.OdaException;\n\n/**\n * Implementation class of IParameterMetaData for Excel ODA runtime driver,\n * which does not currently support input nor output parameters.\n */\npublic class ParameterMetaData implements IParameterMetaData {\n\n public int getParameterCount() throws OdaException {\n return 0;\n }\n\n public int getParameterMode(int param) throws OdaException {\n return IParameterMetaData.parameterModeUnknown;\n }\n\n public String getParameterName(int param) throws OdaException {\n // name is not available\n return null;\n }\n\n public int getParameterType(int param) throws OdaException {\n return DataTypes.getTypeCode(null", "post_mask_code": "\n }\n\n /*\n\t * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#\n\t * getParameterTypeName(int)\n\t */\n public String getParameterTypeName(int param) throws OdaException {\n int nativeTypeCode = getParameterType(param);\n return DataTypes.getNativeDataTypeName(nativeTypeCode);\n }\n\n public int getPrecision(int param) throws OdaException {\n return -1;\n }\n\n /*\n\t * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#getScale(int)\n\t */\n public int getScale(int param) throws OdaException {\n return -1;\n }\n\n public int isNullable(int param) throws OdaException {\n return IParameterMetaData.parameterNullableUnknown;\n }\n}\n"} {"task_id": "Java_1116", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/eclipse/birt/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ParameterMetaData.java", "mask_start_position": 1726, "mask_end_position": 1803, "canonical_solution": "public int getScale(int param) throws OdaException {\n return -1;\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * Megha Nidhi Dahal - initial API and implementation and/or initial documentation\n * Actuate Corporation - code cleanup\n * *****************************************************************************\n */\npackage org.eclipse.birt.report.data.oda.excel.impl;\n\nimport org.eclipse.birt.report.data.oda.excel.impl.util.DataTypes;\nimport org.eclipse.datatools.connectivity.oda.IParameterMetaData;\nimport org.eclipse.datatools.connectivity.oda.OdaException;\n\n/**\n * Implementation class of IParameterMetaData for Excel ODA runtime driver,\n * which does not currently support input nor output parameters.\n */\npublic class ParameterMetaData implements IParameterMetaData {\n\n public int getParameterCount() throws OdaException {\n return 0;\n }\n\n public int getParameterMode(int param) throws OdaException {\n return IParameterMetaData.parameterModeUnknown;\n }\n\n public String getParameterName(int param) throws OdaException {\n // name is not available\n return null;\n }\n\n public int getParameterType(int param) throws OdaException {\n return DataTypes.getTypeCode(null);\n }\n\n /*\n\t * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#\n\t * getParameterTypeName(int)\n\t */\n public String getParameterTypeName(int param) throws OdaException {\n int nativeTypeCode = getParameterType(param);\n return DataTypes.getNativeDataTypeName(nativeTypeCode);\n }\n\n public int getPrecision(int param) throws OdaException {\n return -1;\n }\n\n /*\n\t * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#getScale(int)\n\t */\n ", "post_mask_code": "\n\n public int isNullable(int param) throws OdaException {\n return IParameterMetaData.parameterNullableUnknown;\n }\n}\n"} {"task_id": "Java_1117", "language": "Java", "task_type": "empty", "source_file": "java/github/eclipse/birt/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ParameterMetaData.java", "mask_start_position": 806, "mask_end_position": 806, "canonical_solution": "", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * Megha Nidhi Dahal - initial API and implementation and/or initial documentation\n * Actuate Corporation - code cleanup\n * *****************************************************************************\n */\npackage org.eclipse.birt.report.data.oda.excel.impl;\n\nimport org.eclipse.birt.report.data.oda.excel.impl.util.DataTypes;\nimport org.eclipse.datatools.connectivity.oda.IParameterMetaData;\nimport org.eclipse.datatools.connectivity.oda.OdaException;\n\n/**\n * Implementation class of IParameterMetaData for Excel ODA runtime driver,\n * which does not currently support input nor output parameters.\n */\npublic class ParameterMetaData implements IParameterMetaData {\n\n public int getParamete", "post_mask_code": "rCount() throws OdaException {\n return 0;\n }\n\n public int getParameterMode(int param) throws OdaException {\n return IParameterMetaData.parameterModeUnknown;\n }\n\n public String getParameterName(int param) throws OdaException {\n // name is not available\n return null;\n }\n\n public int getParameterType(int param) throws OdaException {\n return DataTypes.getTypeCode(null);\n }\n\n /*\n\t * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#\n\t * getParameterTypeName(int)\n\t */\n public String getParameterTypeName(int param) throws OdaException {\n int nativeTypeCode = getParameterType(param);\n return DataTypes.getNativeDataTypeName(nativeTypeCode);\n }\n\n public int getPrecision(int param) throws OdaException {\n return -1;\n }\n\n /*\n\t * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#getScale(int)\n\t */\n public int getScale(int param) throws OdaException {\n return -1;\n }\n\n public int isNullable(int param) throws OdaException {\n return IParameterMetaData.parameterNullableUnknown;\n }\n}\n"} {"task_id": "Java_1118", "language": "Java", "task_type": "method_signature", "source_file": "java/github/slimjar/slimjar/slimjar/src/main/java/io/github/slimjar/resolver/mirrors/SimpleMirrorSelector.java", "mask_start_position": 1567, "mask_end_position": 1629, "canonical_solution": "private static boolean isCentral(final Repository repository) ", "pre_mask_code": "package io.github.slimjar.resolver.mirrors;\n\nimport io.github.slimjar.resolver.data.Mirror;\nimport io.github.slimjar.resolver.data.Repository;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\npublic final class SimpleMirrorSelector implements MirrorSelector {\n\n public static final String DEFAULT_CENTRAL_MIRROR_URL = \"http://example.com\";\n\n public static final String CENTRAL_URL = \"http://example.com\";\n\n public static final String ALT_CENTRAL_URL = \"http://example.com\";\n\n private static final Collection CENTRAL_REPO = Arrays.asList(CENTRAL_URL, ALT_CENTRAL_URL);\n\n private final Collection centralMirrors;\n\n public SimpleMirrorSelector(final Collection centralMirrors) {\n this.centralMirrors = centralMirrors;\n }\n\n @Override\n public Collection select(final Collection mainRepositories, final Collection mirrors) throws MalformedURLException {\n final Collection originals = mirrors.stream().map(Mirror::getOriginal).collect(Collectors.toSet());\n final Collection resolved = mainRepositories.stream().filter(repo -> !originals.contains(repo.getUrl())).filter(repo -> !isCentral(repo)).collect(Collectors.toSet());\n final Collection mirrored = mirrors.stream().map(Mirror::getMirroring).map(Repository::new).collect(Collectors.toSet());\n resolved.addAll(mirrored);\n resolved.addAll(centralMirrors);\n return resolved;\n }\n\n ", "post_mask_code": "{\n final String url = repository.getUrl().toString();\n return CENTRAL_REPO.contains(url);\n }\n}\n"} {"task_id": "Java_1119", "language": "Java", "task_type": "method_body", "source_file": "java/github/slimjar/slimjar/slimjar/src/main/java/io/github/slimjar/resolver/mirrors/SimpleMirrorSelector.java", "mask_start_position": 1629, "mask_end_position": 1738, "canonical_solution": "{\n final String url = repository.getUrl().toString();\n return CENTRAL_REPO.contains(url);\n }", "pre_mask_code": "package io.github.slimjar.resolver.mirrors;\n\nimport io.github.slimjar.resolver.data.Mirror;\nimport io.github.slimjar.resolver.data.Repository;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\npublic final class SimpleMirrorSelector implements MirrorSelector {\n\n public static final String DEFAULT_CENTRAL_MIRROR_URL = \"http://example.com\";\n\n public static final String CENTRAL_URL = \"http://example.com\";\n\n public static final String ALT_CENTRAL_URL = \"http://example.com\";\n\n private static final Collection CENTRAL_REPO = Arrays.asList(CENTRAL_URL, ALT_CENTRAL_URL);\n\n private final Collection centralMirrors;\n\n public SimpleMirrorSelector(final Collection centralMirrors) {\n this.centralMirrors = centralMirrors;\n }\n\n @Override\n public Collection select(final Collection mainRepositories, final Collection mirrors) throws MalformedURLException {\n final Collection originals = mirrors.stream().map(Mirror::getOriginal).collect(Collectors.toSet());\n final Collection resolved = mainRepositories.stream().filter(repo -> !originals.contains(repo.getUrl())).filter(repo -> !isCentral(repo)).collect(Collectors.toSet());\n final Collection mirrored = mirrors.stream().map(Mirror::getMirroring).map(Repository::new).collect(Collectors.toSet());\n resolved.addAll(mirrored);\n resolved.addAll(centralMirrors);\n return resolved;\n }\n\n private static boolean isCentral(final Repository repository) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1120", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/slimjar/slimjar/slimjar/src/main/java/io/github/slimjar/resolver/mirrors/SimpleMirrorSelector.java", "mask_start_position": 1013, "mask_end_position": 1313, "canonical_solution": "\n final Collection originals = mirrors.stream().map(Mirror::getOriginal).collect(Collectors.toSet());\n final Collection resolved = mainRepositories.stream().filter(repo -> !originals.contains(repo.getUrl())).filter(repo -> !isCentral(repo)).collect(Collectors.toSet());", "pre_mask_code": "package io.github.slimjar.resolver.mirrors;\n\nimport io.github.slimjar.resolver.data.Mirror;\nimport io.github.slimjar.resolver.data.Repository;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\npublic final class SimpleMirrorSelector implements MirrorSelector {\n\n public static final String DEFAULT_CENTRAL_MIRROR_URL = \"http://example.com\";\n\n public static final String CENTRAL_URL = \"http://example.com\";\n\n public static final String ALT_CENTRAL_URL = \"http://example.com\";\n\n private static final Collection CENTRAL_REPO = Arrays.asList(CENTRAL_URL, ALT_CENTRAL_URL);\n\n private final Collection centralMirrors;\n\n public SimpleMirrorSelector(final Collection centralMirrors) {\n this.centralMirrors = centralMirrors;\n }\n\n @Override\n public Collection select(final Collection mainRepositories, final Collection mirrors) throws MalformedURLException {", "post_mask_code": "\n final Collection mirrored = mirrors.stream().map(Mirror::getMirroring).map(Repository::new).collect(Collectors.toSet());\n resolved.addAll(mirrored);\n resolved.addAll(centralMirrors);\n return resolved;\n }\n\n private static boolean isCentral(final Repository repository) {\n final String url = repository.getUrl().toString();\n return CENTRAL_REPO.contains(url);\n }\n}\n"} {"task_id": "Java_1121", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/slimjar/slimjar/slimjar/src/main/java/io/github/slimjar/resolver/mirrors/SimpleMirrorSelector.java", "mask_start_position": 1322, "mask_end_position": 1489, "canonical_solution": "final Collection mirrored = mirrors.stream().map(Mirror::getMirroring).map(Repository::new).collect(Collectors.toSet());\n resolved.addAll(mirrored);", "pre_mask_code": "package io.github.slimjar.resolver.mirrors;\n\nimport io.github.slimjar.resolver.data.Mirror;\nimport io.github.slimjar.resolver.data.Repository;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\npublic final class SimpleMirrorSelector implements MirrorSelector {\n\n public static final String DEFAULT_CENTRAL_MIRROR_URL = \"http://example.com\";\n\n public static final String CENTRAL_URL = \"http://example.com\";\n\n public static final String ALT_CENTRAL_URL = \"http://example.com\";\n\n private static final Collection CENTRAL_REPO = Arrays.asList(CENTRAL_URL, ALT_CENTRAL_URL);\n\n private final Collection centralMirrors;\n\n public SimpleMirrorSelector(final Collection centralMirrors) {\n this.centralMirrors = centralMirrors;\n }\n\n @Override\n public Collection select(final Collection mainRepositories, final Collection mirrors) throws MalformedURLException {\n final Collection originals = mirrors.stream().map(Mirror::getOriginal).collect(Collectors.toSet());\n final Collection resolved = mainRepositories.stream().filter(repo -> !originals.contains(repo.getUrl())).filter(repo -> !isCentral(repo)).collect(Collectors.toSet());\n ", "post_mask_code": "\n resolved.addAll(centralMirrors);\n return resolved;\n }\n\n private static boolean isCentral(final Repository repository) {\n final String url = repository.getUrl().toString();\n return CENTRAL_REPO.contains(url);\n }\n}\n"} {"task_id": "Java_1122", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/slimjar/slimjar/slimjar/src/main/java/io/github/slimjar/resolver/mirrors/SimpleMirrorSelector.java", "mask_start_position": 1498, "mask_end_position": 1561, "canonical_solution": "resolved.addAll(centralMirrors);\n return resolved;\n }", "pre_mask_code": "package io.github.slimjar.resolver.mirrors;\n\nimport io.github.slimjar.resolver.data.Mirror;\nimport io.github.slimjar.resolver.data.Repository;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\npublic final class SimpleMirrorSelector implements MirrorSelector {\n\n public static final String DEFAULT_CENTRAL_MIRROR_URL = \"http://example.com\";\n\n public static final String CENTRAL_URL = \"http://example.com\";\n\n public static final String ALT_CENTRAL_URL = \"http://example.com\";\n\n private static final Collection CENTRAL_REPO = Arrays.asList(CENTRAL_URL, ALT_CENTRAL_URL);\n\n private final Collection centralMirrors;\n\n public SimpleMirrorSelector(final Collection centralMirrors) {\n this.centralMirrors = centralMirrors;\n }\n\n @Override\n public Collection select(final Collection mainRepositories, final Collection mirrors) throws MalformedURLException {\n final Collection originals = mirrors.stream().map(Mirror::getOriginal).collect(Collectors.toSet());\n final Collection resolved = mainRepositories.stream().filter(repo -> !originals.contains(repo.getUrl())).filter(repo -> !isCentral(repo)).collect(Collectors.toSet());\n final Collection mirrored = mirrors.stream().map(Mirror::getMirroring).map(Repository::new).collect(Collectors.toSet());\n resolved.addAll(mirrored);\n ", "post_mask_code": "\n\n private static boolean isCentral(final Repository repository) {\n final String url = repository.getUrl().toString();\n return CENTRAL_REPO.contains(url);\n }\n}\n"} {"task_id": "Java_1123", "language": "Java", "task_type": "single_line", "source_file": "java/github/slimjar/slimjar/slimjar/src/main/java/io/github/slimjar/resolver/mirrors/SimpleMirrorSelector.java", "mask_start_position": 1547, "mask_end_position": 1555, "canonical_solution": "esolved;", "pre_mask_code": "package io.github.slimjar.resolver.mirrors;\n\nimport io.github.slimjar.resolver.data.Mirror;\nimport io.github.slimjar.resolver.data.Repository;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\npublic final class SimpleMirrorSelector implements MirrorSelector {\n\n public static final String DEFAULT_CENTRAL_MIRROR_URL = \"http://example.com\";\n\n public static final String CENTRAL_URL = \"http://example.com\";\n\n public static final String ALT_CENTRAL_URL = \"http://example.com\";\n\n private static final Collection CENTRAL_REPO = Arrays.asList(CENTRAL_URL, ALT_CENTRAL_URL);\n\n private final Collection centralMirrors;\n\n public SimpleMirrorSelector(final Collection centralMirrors) {\n this.centralMirrors = centralMirrors;\n }\n\n @Override\n public Collection select(final Collection mainRepositories, final Collection mirrors) throws MalformedURLException {\n final Collection originals = mirrors.stream().map(Mirror::getOriginal).collect(Collectors.toSet());\n final Collection resolved = mainRepositories.stream().filter(repo -> !originals.contains(repo.getUrl())).filter(repo -> !isCentral(repo)).collect(Collectors.toSet());\n final Collection mirrored = mirrors.stream().map(Mirror::getMirroring).map(Repository::new).collect(Collectors.toSet());\n resolved.addAll(mirrored);\n resolved.addAll(centralMirrors);\n return r", "post_mask_code": "\n }\n\n private static boolean isCentral(final Repository repository) {\n final String url = repository.getUrl().toString();\n return CENTRAL_REPO.contains(url);\n }\n}\n"} {"task_id": "Java_1124", "language": "Java", "task_type": "empty", "source_file": "java/github/slimjar/slimjar/slimjar/src/main/java/io/github/slimjar/resolver/mirrors/SimpleMirrorSelector.java", "mask_start_position": 617, "mask_end_position": 617, "canonical_solution": "", "pre_mask_code": "package io.github.slimjar.resolver.mirrors;\n\nimport io.github.slimjar.resolver.data.Mirror;\nimport io.github.slimjar.resolver.data.Repository;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\npublic final class SimpleMirrorSelector implements MirrorSelector {\n\n public static final String DEFAULT_CENTRAL_MIRROR_URL = \"http://example.com\";\n\n public static final String CENTRAL_URL = \"http://example.com\";\n\n public static final String ALT_CENTRAL_URL = \"http://example.com\";\n\n private static final Collection CENTRAL_REPO = Arrays", "post_mask_code": ".asList(CENTRAL_URL, ALT_CENTRAL_URL);\n\n private final Collection centralMirrors;\n\n public SimpleMirrorSelector(final Collection centralMirrors) {\n this.centralMirrors = centralMirrors;\n }\n\n @Override\n public Collection select(final Collection mainRepositories, final Collection mirrors) throws MalformedURLException {\n final Collection originals = mirrors.stream().map(Mirror::getOriginal).collect(Collectors.toSet());\n final Collection resolved = mainRepositories.stream().filter(repo -> !originals.contains(repo.getUrl())).filter(repo -> !isCentral(repo)).collect(Collectors.toSet());\n final Collection mirrored = mirrors.stream().map(Mirror::getMirroring).map(Repository::new).collect(Collectors.toSet());\n resolved.addAll(mirrored);\n resolved.addAll(centralMirrors);\n return resolved;\n }\n\n private static boolean isCentral(final Repository repository) {\n final String url = repository.getUrl().toString();\n return CENTRAL_REPO.contains(url);\n }\n}\n"} {"task_id": "Java_1125", "language": "Java", "task_type": "method_signature", "source_file": "java/github/projectlombok/lombok/src/core/lombok/javac/LombokOptions.java", "mask_start_position": 1477, "mask_end_position": 1515, "canonical_solution": "public void deleteLombokAnnotations() ", "pre_mask_code": "package lombok.javac;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport lombok.delombok.FormatPreferences;\nimport lombok.delombok.LombokOptionsFactory;\nimport com.sun.tools.javac.tree.JCTree.JCCompilationUnit;\nimport com.sun.tools.javac.util.Context;\nimport com.sun.tools.javac.util.Options;\n\npublic abstract class LombokOptions extends Options {\n\n private boolean deleteLombokAnnotations = false;\n\n private final Set changed = new HashSet();\n\n private FormatPreferences formatPreferences = new FormatPreferences(null);\n\n public boolean isChanged(JCCompilationUnit ast) {\n return changed.contains(ast);\n }\n\n public void setFormatPreferences(FormatPreferences formatPreferences) {\n this.formatPreferences = formatPreferences;\n }\n\n public FormatPreferences getFormatPreferences() {\n return this.formatPreferences;\n }\n\n public static void markChanged(Context context, JCCompilationUnit ast) {\n LombokOptions options = LombokOptionsFactory.getDelombokOptions(context);\n options.changed.add(ast);\n }\n\n public static boolean shouldDeleteLombokAnnotations(Context context) {\n LombokOptions options = LombokOptionsFactory.getDelombokOptions(context);\n return options.deleteLombokAnnotations;\n }\n\n protected LombokOptions(Context context) {\n super(context);\n }\n\n public abstract void putJavacOption(String optionName, String value);\n\n ", "post_mask_code": "{\n this.deleteLombokAnnotations = true;\n }\n}\n"} {"task_id": "Java_1126", "language": "Java", "task_type": "method_body", "source_file": "java/github/projectlombok/lombok/src/core/lombok/javac/LombokOptions.java", "mask_start_position": 983, "mask_end_position": 1106, "canonical_solution": "{\n LombokOptions options = LombokOptionsFactory.getDelombokOptions(context);\n options.changed.add(ast);\n }", "pre_mask_code": "package lombok.javac;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport lombok.delombok.FormatPreferences;\nimport lombok.delombok.LombokOptionsFactory;\nimport com.sun.tools.javac.tree.JCTree.JCCompilationUnit;\nimport com.sun.tools.javac.util.Context;\nimport com.sun.tools.javac.util.Options;\n\npublic abstract class LombokOptions extends Options {\n\n private boolean deleteLombokAnnotations = false;\n\n private final Set changed = new HashSet();\n\n private FormatPreferences formatPreferences = new FormatPreferences(null);\n\n public boolean isChanged(JCCompilationUnit ast) {\n return changed.contains(ast);\n }\n\n public void setFormatPreferences(FormatPreferences formatPreferences) {\n this.formatPreferences = formatPreferences;\n }\n\n public FormatPreferences getFormatPreferences() {\n return this.formatPreferences;\n }\n\n public static void markChanged(Context context, JCCompilationUnit ast) ", "post_mask_code": "\n\n public static boolean shouldDeleteLombokAnnotations(Context context) {\n LombokOptions options = LombokOptionsFactory.getDelombokOptions(context);\n return options.deleteLombokAnnotations;\n }\n\n protected LombokOptions(Context context) {\n super(context);\n }\n\n public abstract void putJavacOption(String optionName, String value);\n\n public void deleteLombokAnnotations() {\n this.deleteLombokAnnotations = true;\n }\n}\n"} {"task_id": "Java_1127", "language": "Java", "task_type": "single_line", "source_file": "java/github/projectlombok/lombok/src/core/lombok/javac/LombokOptions.java", "mask_start_position": 1087, "mask_end_position": 1100, "canonical_solution": "ged.add(ast);", "pre_mask_code": "package lombok.javac;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport lombok.delombok.FormatPreferences;\nimport lombok.delombok.LombokOptionsFactory;\nimport com.sun.tools.javac.tree.JCTree.JCCompilationUnit;\nimport com.sun.tools.javac.util.Context;\nimport com.sun.tools.javac.util.Options;\n\npublic abstract class LombokOptions extends Options {\n\n private boolean deleteLombokAnnotations = false;\n\n private final Set changed = new HashSet();\n\n private FormatPreferences formatPreferences = new FormatPreferences(null);\n\n public boolean isChanged(JCCompilationUnit ast) {\n return changed.contains(ast);\n }\n\n public void setFormatPreferences(FormatPreferences formatPreferences) {\n this.formatPreferences = formatPreferences;\n }\n\n public FormatPreferences getFormatPreferences() {\n return this.formatPreferences;\n }\n\n public static void markChanged(Context context, JCCompilationUnit ast) {\n LombokOptions options = LombokOptionsFactory.getDelombokOptions(context);\n options.chan", "post_mask_code": "\n }\n\n public static boolean shouldDeleteLombokAnnotations(Context context) {\n LombokOptions options = LombokOptionsFactory.getDelombokOptions(context);\n return options.deleteLombokAnnotations;\n }\n\n protected LombokOptions(Context context) {\n super(context);\n }\n\n public abstract void putJavacOption(String optionName, String value);\n\n public void deleteLombokAnnotations() {\n this.deleteLombokAnnotations = true;\n }\n}\n"} {"task_id": "Java_1128", "language": "Java", "task_type": "empty", "source_file": "java/github/projectlombok/lombok/src/core/lombok/javac/LombokOptions.java", "mask_start_position": 15, "mask_end_position": 15, "canonical_solution": "", "pre_mask_code": "package lombok.", "post_mask_code": "javac;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport lombok.delombok.FormatPreferences;\nimport lombok.delombok.LombokOptionsFactory;\nimport com.sun.tools.javac.tree.JCTree.JCCompilationUnit;\nimport com.sun.tools.javac.util.Context;\nimport com.sun.tools.javac.util.Options;\n\npublic abstract class LombokOptions extends Options {\n\n private boolean deleteLombokAnnotations = false;\n\n private final Set changed = new HashSet();\n\n private FormatPreferences formatPreferences = new FormatPreferences(null);\n\n public boolean isChanged(JCCompilationUnit ast) {\n return changed.contains(ast);\n }\n\n public void setFormatPreferences(FormatPreferences formatPreferences) {\n this.formatPreferences = formatPreferences;\n }\n\n public FormatPreferences getFormatPreferences() {\n return this.formatPreferences;\n }\n\n public static void markChanged(Context context, JCCompilationUnit ast) {\n LombokOptions options = LombokOptionsFactory.getDelombokOptions(context);\n options.changed.add(ast);\n }\n\n public static boolean shouldDeleteLombokAnnotations(Context context) {\n LombokOptions options = LombokOptionsFactory.getDelombokOptions(context);\n return options.deleteLombokAnnotations;\n }\n\n protected LombokOptions(Context context) {\n super(context);\n }\n\n public abstract void putJavacOption(String optionName, String value);\n\n public void deleteLombokAnnotations() {\n this.deleteLombokAnnotations = true;\n }\n}\n"} {"task_id": "Java_1129", "language": "Java", "task_type": "empty", "source_file": "java/github/OvercastNetwork/ProjectAres/Util/core/src/main/java/tc/oc/commons/core/inspect/InspectionException.java", "mask_start_position": 261, "mask_end_position": 261, "canonical_solution": "", "pre_mask_code": "package tc.oc.commons.core.inspect;\n\npublic class InspectionException extends Exception {\n\n public InspectionException(String message) {\n super(message);\n }\n\n public InspectionException(String message, Throwable cause) {\n super(message, c", "post_mask_code": "ause);\n }\n}\n"} {"task_id": "Java_1130", "language": "Java", "task_type": "method_signature", "source_file": "java/github/berndruecker/flowing-retail-old/order/src/main/java/io/flowing/retail/order/domain/OrderRepository.java", "mask_start_position": 518, "mask_end_position": 556, "canonical_solution": "public void persistOrder(Order order) ", "pre_mask_code": "package io.flowing.retail.order.domain;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport io.flowing.retail.order.flow.entitystate.OrderWithState;\n\npublic class OrderRepository {\n\n public static OrderRepository instance = new OrderRepository();\n\n private HashMap orderStorage = new HashMap();\n\n private HashMap orderWithStateStorage = new HashMap();\n\n /**\n * get the order for the specified orderId\n */\n ", "post_mask_code": "{\n orderStorage.put(order.getId(), order);\n }\n\n /**\n * get the order for the specified orderId\n */\n public Order getOrder(String orderId) {\n return orderStorage.get(orderId);\n }\n\n /**\n * Find orders. Currently no filter is required for simple examples\n *\n * @return all stored orders\n */\n public Collection findOrders() {\n return orderStorage.values();\n }\n\n public void persistOrder(OrderWithState order) {\n orderWithStateStorage.put(order.getId(), order);\n }\n\n public OrderWithState getOrderWithState(String orderId) {\n return (OrderWithState) orderWithStateStorage.get(orderId);\n }\n\n public Collection findOrdersWithState() {\n return orderWithStateStorage.values();\n }\n}\n"} {"task_id": "Java_1131", "language": "Java", "task_type": "method_body", "source_file": "java/github/berndruecker/flowing-retail-old/order/src/main/java/io/flowing/retail/order/domain/OrderRepository.java", "mask_start_position": 949, "mask_end_position": 994, "canonical_solution": "{\n return orderStorage.values();\n }", "pre_mask_code": "package io.flowing.retail.order.domain;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport io.flowing.retail.order.flow.entitystate.OrderWithState;\n\npublic class OrderRepository {\n\n public static OrderRepository instance = new OrderRepository();\n\n private HashMap orderStorage = new HashMap();\n\n private HashMap orderWithStateStorage = new HashMap();\n\n /**\n * get the order for the specified orderId\n */\n public void persistOrder(Order order) {\n orderStorage.put(order.getId(), order);\n }\n\n /**\n * get the order for the specified orderId\n */\n public Order getOrder(String orderId) {\n return orderStorage.get(orderId);\n }\n\n /**\n * Find orders. Currently no filter is required for simple examples\n *\n * @return all stored orders\n */\n public Collection findOrders() ", "post_mask_code": "\n\n public void persistOrder(OrderWithState order) {\n orderWithStateStorage.put(order.getId(), order);\n }\n\n public OrderWithState getOrderWithState(String orderId) {\n return (OrderWithState) orderWithStateStorage.get(orderId);\n }\n\n public Collection findOrdersWithState() {\n return orderWithStateStorage.values();\n }\n}\n"} {"task_id": "Java_1132", "language": "Java", "task_type": "single_line", "source_file": "java/github/berndruecker/flowing-retail-old/order/src/main/java/io/flowing/retail/order/domain/OrderRepository.java", "mask_start_position": 604, "mask_end_position": 605, "canonical_solution": ";", "pre_mask_code": "package io.flowing.retail.order.domain;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport io.flowing.retail.order.flow.entitystate.OrderWithState;\n\npublic class OrderRepository {\n\n public static OrderRepository instance = new OrderRepository();\n\n private HashMap orderStorage = new HashMap();\n\n private HashMap orderWithStateStorage = new HashMap();\n\n /**\n * get the order for the specified orderId\n */\n public void persistOrder(Order order) {\n orderStorage.put(order.getId(), order)", "post_mask_code": "\n }\n\n /**\n * get the order for the specified orderId\n */\n public Order getOrder(String orderId) {\n return orderStorage.get(orderId);\n }\n\n /**\n * Find orders. Currently no filter is required for simple examples\n *\n * @return all stored orders\n */\n public Collection findOrders() {\n return orderStorage.values();\n }\n\n public void persistOrder(OrderWithState order) {\n orderWithStateStorage.put(order.getId(), order);\n }\n\n public OrderWithState getOrderWithState(String orderId) {\n return (OrderWithState) orderWithStateStorage.get(orderId);\n }\n\n public Collection findOrdersWithState() {\n return orderWithStateStorage.values();\n }\n}\n"} {"task_id": "Java_1133", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/berndruecker/flowing-retail-old/order/src/main/java/io/flowing/retail/order/domain/OrderRepository.java", "mask_start_position": 680, "mask_end_position": 767, "canonical_solution": "public Order getOrder(String orderId) {\n return orderStorage.get(orderId);\n }", "pre_mask_code": "package io.flowing.retail.order.domain;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport io.flowing.retail.order.flow.entitystate.OrderWithState;\n\npublic class OrderRepository {\n\n public static OrderRepository instance = new OrderRepository();\n\n private HashMap orderStorage = new HashMap();\n\n private HashMap orderWithStateStorage = new HashMap();\n\n /**\n * get the order for the specified orderId\n */\n public void persistOrder(Order order) {\n orderStorage.put(order.getId(), order);\n }\n\n /**\n * get the order for the specified orderId\n */\n ", "post_mask_code": "\n\n /**\n * Find orders. Currently no filter is required for simple examples\n *\n * @return all stored orders\n */\n public Collection findOrders() {\n return orderStorage.values();\n }\n\n public void persistOrder(OrderWithState order) {\n orderWithStateStorage.put(order.getId(), order);\n }\n\n public OrderWithState getOrderWithState(String orderId) {\n return (OrderWithState) orderWithStateStorage.get(orderId);\n }\n\n public Collection findOrdersWithState() {\n return orderWithStateStorage.values();\n }\n}\n"} {"task_id": "Java_1134", "language": "Java", "task_type": "empty", "source_file": "java/github/berndruecker/flowing-retail-old/order/src/main/java/io/flowing/retail/order/domain/OrderRepository.java", "mask_start_position": 573, "mask_end_position": 573, "canonical_solution": "", "pre_mask_code": "package io.flowing.retail.order.domain;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport io.flowing.retail.order.flow.entitystate.OrderWithState;\n\npublic class OrderRepository {\n\n public static OrderRepository instance = new OrderRepository();\n\n private HashMap orderStorage = new HashMap();\n\n private HashMap orderWithStateStorage = new HashMap();\n\n /**\n * get the order for the specified orderId\n */\n public void persistOrder(Order order) {\n orderSt", "post_mask_code": "orage.put(order.getId(), order);\n }\n\n /**\n * get the order for the specified orderId\n */\n public Order getOrder(String orderId) {\n return orderStorage.get(orderId);\n }\n\n /**\n * Find orders. Currently no filter is required for simple examples\n *\n * @return all stored orders\n */\n public Collection findOrders() {\n return orderStorage.values();\n }\n\n public void persistOrder(OrderWithState order) {\n orderWithStateStorage.put(order.getId(), order);\n }\n\n public OrderWithState getOrderWithState(String orderId) {\n return (OrderWithState) orderWithStateStorage.get(orderId);\n }\n\n public Collection findOrdersWithState() {\n return orderWithStateStorage.values();\n }\n}\n"} {"task_id": "Java_1135", "language": "Java", "task_type": "method_signature", "source_file": "java/github/tysqapp/tysq-android/lib/special/lib_multi_download/src/main/java/com/abc/lib_multi_download/okhttp/interceptor/LogInterceptor.java", "mask_start_position": 5182, "mask_end_position": 5268, "canonical_solution": "private void appendKeyAndValue(StringBuilder stringBuilder, String key, String value) ", "pre_mask_code": "package com.abc.lib_multi_download.okhttp.interceptor;\n\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport com.abc.lib_multi_download.BuildConfig;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport okhttp3.Interceptor;\nimport okhttp3.Request;\nimport okhttp3.RequestBody;\nimport okhttp3.Response;\nimport okio.Buffer;\nimport okio.BufferedSource;\n\npublic class LogInterceptor implements Interceptor {\n\n private static final String COLON = \": \";\n\n private final static String TOP_LEFT_LINE = \"┌\";\n\n private final static String MIDDLE_LINE = \"├\";\n\n private final static String BOTTOM_LEFT_LINE = \"└\";\n\n private final static String CRLF = \"\\r\\n\";\n\n private final static String VERTICAL_LINE = \"│\";\n\n private final static String HORIZONTAL_LINE = \"─\";\n\n private final static boolean isShow = BuildConfig.BUILD_TYPE.equals(\"debug\");\n\n private static final Charset UTF8 = Charset.forName(\"UTF-8\");\n\n private final Random random = new Random();\n\n @Override\n public Response intercept(@NonNull Chain chain) throws IOException {\n int requestId = random.nextInt(1000000);\n Request request = chain.request();\n buildRequestLog(requestId, request);\n long reqTime = System.currentTimeMillis();\n Response response = chain.proceed(request);\n String url = request.url().uri().toString();\n buildResponseLog(requestId, url, reqTime, response);\n return response;\n }\n\n private void buildRequestLog(int requestId, Request request) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------request------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"url\", request.url().uri().toString());\n appendKeyAndValue(stringBuilder, \"method\", request.method());\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = request.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(request.body() == null ? \"It's empty body\" : bodyToString(request.body())).append(CRLF);\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void buildResponseLog(int requestId, String url, long reqTime, Response response) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------response------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"time\", System.currentTimeMillis() - reqTime + \"\");\n appendKeyAndValue(stringBuilder, \"url\", url);\n appendKeyAndValue(stringBuilder, \"message\", response.message());\n appendKeyAndValue(stringBuilder, \"code\", response.code() + \"\");\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = response.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n try {\n String body;\n if (response.body() == null || response.body().contentLength() == 0) {\n body = \"It's empty body\";\n } else {\n BufferedSource source = response.body().source();\n source.request(Long.MAX_VALUE);\n body = source.buffer().clone().readString(UTF8);\n }\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(body).append(CRLF);\n } catch (IOException e) {\n e.printStackTrace();\n }\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n ", "post_mask_code": "{\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(key).append(COLON).append(value).append(CRLF);\n }\n\n protected String bodyToString(final RequestBody request) {\n try {\n final Buffer buffer = new Buffer();\n if (request == null) {\n return \"\";\n }\n request.writeTo(buffer);\n return buffer.readUtf8();\n } catch (final IOException e) {\n e.printStackTrace();\n return \"\";\n }\n }\n}\n"} {"task_id": "Java_1136", "language": "Java", "task_type": "method_body", "source_file": "java/github/tysqapp/tysq-android/lib/special/lib_multi_download/src/main/java/com/abc/lib_multi_download/okhttp/interceptor/LogInterceptor.java", "mask_start_position": 5268, "mask_end_position": 5385, "canonical_solution": "{\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(key).append(COLON).append(value).append(CRLF);\n }", "pre_mask_code": "package com.abc.lib_multi_download.okhttp.interceptor;\n\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport com.abc.lib_multi_download.BuildConfig;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport okhttp3.Interceptor;\nimport okhttp3.Request;\nimport okhttp3.RequestBody;\nimport okhttp3.Response;\nimport okio.Buffer;\nimport okio.BufferedSource;\n\npublic class LogInterceptor implements Interceptor {\n\n private static final String COLON = \": \";\n\n private final static String TOP_LEFT_LINE = \"┌\";\n\n private final static String MIDDLE_LINE = \"├\";\n\n private final static String BOTTOM_LEFT_LINE = \"└\";\n\n private final static String CRLF = \"\\r\\n\";\n\n private final static String VERTICAL_LINE = \"│\";\n\n private final static String HORIZONTAL_LINE = \"─\";\n\n private final static boolean isShow = BuildConfig.BUILD_TYPE.equals(\"debug\");\n\n private static final Charset UTF8 = Charset.forName(\"UTF-8\");\n\n private final Random random = new Random();\n\n @Override\n public Response intercept(@NonNull Chain chain) throws IOException {\n int requestId = random.nextInt(1000000);\n Request request = chain.request();\n buildRequestLog(requestId, request);\n long reqTime = System.currentTimeMillis();\n Response response = chain.proceed(request);\n String url = request.url().uri().toString();\n buildResponseLog(requestId, url, reqTime, response);\n return response;\n }\n\n private void buildRequestLog(int requestId, Request request) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------request------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"url\", request.url().uri().toString());\n appendKeyAndValue(stringBuilder, \"method\", request.method());\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = request.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(request.body() == null ? \"It's empty body\" : bodyToString(request.body())).append(CRLF);\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void buildResponseLog(int requestId, String url, long reqTime, Response response) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------response------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"time\", System.currentTimeMillis() - reqTime + \"\");\n appendKeyAndValue(stringBuilder, \"url\", url);\n appendKeyAndValue(stringBuilder, \"message\", response.message());\n appendKeyAndValue(stringBuilder, \"code\", response.code() + \"\");\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = response.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n try {\n String body;\n if (response.body() == null || response.body().contentLength() == 0) {\n body = \"It's empty body\";\n } else {\n BufferedSource source = response.body().source();\n source.request(Long.MAX_VALUE);\n body = source.buffer().clone().readString(UTF8);\n }\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(body).append(CRLF);\n } catch (IOException e) {\n e.printStackTrace();\n }\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void appendKeyAndValue(StringBuilder stringBuilder, String key, String value) ", "post_mask_code": "\n\n protected String bodyToString(final RequestBody request) {\n try {\n final Buffer buffer = new Buffer();\n if (request == null) {\n return \"\";\n }\n request.writeTo(buffer);\n return buffer.readUtf8();\n } catch (final IOException e) {\n e.printStackTrace();\n return \"\";\n }\n }\n}\n"} {"task_id": "Java_1137", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/tysqapp/tysq-android/lib/special/lib_multi_download/src/main/java/com/abc/lib_multi_download/okhttp/interceptor/LogInterceptor.java", "mask_start_position": 1616, "mask_end_position": 1977, "canonical_solution": "\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------request------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");", "pre_mask_code": "package com.abc.lib_multi_download.okhttp.interceptor;\n\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport com.abc.lib_multi_download.BuildConfig;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport okhttp3.Interceptor;\nimport okhttp3.Request;\nimport okhttp3.RequestBody;\nimport okhttp3.Response;\nimport okio.Buffer;\nimport okio.BufferedSource;\n\npublic class LogInterceptor implements Interceptor {\n\n private static final String COLON = \": \";\n\n private final static String TOP_LEFT_LINE = \"┌\";\n\n private final static String MIDDLE_LINE = \"├\";\n\n private final static String BOTTOM_LEFT_LINE = \"└\";\n\n private final static String CRLF = \"\\r\\n\";\n\n private final static String VERTICAL_LINE = \"│\";\n\n private final static String HORIZONTAL_LINE = \"─\";\n\n private final static boolean isShow = BuildConfig.BUILD_TYPE.equals(\"debug\");\n\n private static final Charset UTF8 = Charset.forName(\"UTF-8\");\n\n private final Random random = new Random();\n\n @Override\n public Response intercept(@NonNull Chain chain) throws IOException {\n int requestId = random.nextInt(1000000);\n Request request = chain.request();\n buildRequestLog(requestId, request);\n long reqTime = System.currentTimeMillis();\n Response response = chain.proceed(request);\n String url = request.url().uri().toString();\n buildResponseLog(requestId, url, reqTime, response);\n return response;\n }\n\n private void buildRequestLog(int requestId, Request request) {", "post_mask_code": "\n appendKeyAndValue(stringBuilder, \"url\", request.url().uri().toString());\n appendKeyAndValue(stringBuilder, \"method\", request.method());\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = request.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(request.body() == null ? \"It's empty body\" : bodyToString(request.body())).append(CRLF);\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void buildResponseLog(int requestId, String url, long reqTime, Response response) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------response------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"time\", System.currentTimeMillis() - reqTime + \"\");\n appendKeyAndValue(stringBuilder, \"url\", url);\n appendKeyAndValue(stringBuilder, \"message\", response.message());\n appendKeyAndValue(stringBuilder, \"code\", response.code() + \"\");\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = response.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n try {\n String body;\n if (response.body() == null || response.body().contentLength() == 0) {\n body = \"It's empty body\";\n } else {\n BufferedSource source = response.body().source();\n source.request(Long.MAX_VALUE);\n body = source.buffer().clone().readString(UTF8);\n }\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(body).append(CRLF);\n } catch (IOException e) {\n e.printStackTrace();\n }\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void appendKeyAndValue(StringBuilder stringBuilder, String key, String value) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(key).append(COLON).append(value).append(CRLF);\n }\n\n protected String bodyToString(final RequestBody request) {\n try {\n final Buffer buffer = new Buffer();\n if (request == null) {\n return \"\";\n }\n request.writeTo(buffer);\n return buffer.readUtf8();\n } catch (final IOException e) {\n e.printStackTrace();\n return \"\";\n }\n }\n}\n"} {"task_id": "Java_1138", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/tysqapp/tysq-android/lib/special/lib_multi_download/src/main/java/com/abc/lib_multi_download/okhttp/interceptor/LogInterceptor.java", "mask_start_position": 1986, "mask_end_position": 2356, "canonical_solution": "appendKeyAndValue(stringBuilder, \"url\", request.url().uri().toString());\n appendKeyAndValue(stringBuilder, \"method\", request.method());\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = request.headers().toMultimap();", "pre_mask_code": "package com.abc.lib_multi_download.okhttp.interceptor;\n\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport com.abc.lib_multi_download.BuildConfig;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport okhttp3.Interceptor;\nimport okhttp3.Request;\nimport okhttp3.RequestBody;\nimport okhttp3.Response;\nimport okio.Buffer;\nimport okio.BufferedSource;\n\npublic class LogInterceptor implements Interceptor {\n\n private static final String COLON = \": \";\n\n private final static String TOP_LEFT_LINE = \"┌\";\n\n private final static String MIDDLE_LINE = \"├\";\n\n private final static String BOTTOM_LEFT_LINE = \"└\";\n\n private final static String CRLF = \"\\r\\n\";\n\n private final static String VERTICAL_LINE = \"│\";\n\n private final static String HORIZONTAL_LINE = \"─\";\n\n private final static boolean isShow = BuildConfig.BUILD_TYPE.equals(\"debug\");\n\n private static final Charset UTF8 = Charset.forName(\"UTF-8\");\n\n private final Random random = new Random();\n\n @Override\n public Response intercept(@NonNull Chain chain) throws IOException {\n int requestId = random.nextInt(1000000);\n Request request = chain.request();\n buildRequestLog(requestId, request);\n long reqTime = System.currentTimeMillis();\n Response response = chain.proceed(request);\n String url = request.url().uri().toString();\n buildResponseLog(requestId, url, reqTime, response);\n return response;\n }\n\n private void buildRequestLog(int requestId, Request request) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------request------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n ", "post_mask_code": "\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(request.body() == null ? \"It's empty body\" : bodyToString(request.body())).append(CRLF);\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void buildResponseLog(int requestId, String url, long reqTime, Response response) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------response------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"time\", System.currentTimeMillis() - reqTime + \"\");\n appendKeyAndValue(stringBuilder, \"url\", url);\n appendKeyAndValue(stringBuilder, \"message\", response.message());\n appendKeyAndValue(stringBuilder, \"code\", response.code() + \"\");\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = response.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n try {\n String body;\n if (response.body() == null || response.body().contentLength() == 0) {\n body = \"It's empty body\";\n } else {\n BufferedSource source = response.body().source();\n source.request(Long.MAX_VALUE);\n body = source.buffer().clone().readString(UTF8);\n }\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(body).append(CRLF);\n } catch (IOException e) {\n e.printStackTrace();\n }\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void appendKeyAndValue(StringBuilder stringBuilder, String key, String value) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(key).append(COLON).append(value).append(CRLF);\n }\n\n protected String bodyToString(final RequestBody request) {\n try {\n final Buffer buffer = new Buffer();\n if (request == null) {\n return \"\";\n }\n request.writeTo(buffer);\n return buffer.readUtf8();\n } catch (final IOException e) {\n e.printStackTrace();\n return \"\";\n }\n }\n}\n"} {"task_id": "Java_1139", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/tysqapp/tysq-android/lib/special/lib_multi_download/src/main/java/com/abc/lib_multi_download/okhttp/interceptor/LogInterceptor.java", "mask_start_position": 2365, "mask_end_position": 3081, "canonical_solution": "for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(request.body() == null ? \"It's empty body\" : bodyToString(request.body())).append(CRLF);\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }", "pre_mask_code": "package com.abc.lib_multi_download.okhttp.interceptor;\n\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport com.abc.lib_multi_download.BuildConfig;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport okhttp3.Interceptor;\nimport okhttp3.Request;\nimport okhttp3.RequestBody;\nimport okhttp3.Response;\nimport okio.Buffer;\nimport okio.BufferedSource;\n\npublic class LogInterceptor implements Interceptor {\n\n private static final String COLON = \": \";\n\n private final static String TOP_LEFT_LINE = \"┌\";\n\n private final static String MIDDLE_LINE = \"├\";\n\n private final static String BOTTOM_LEFT_LINE = \"└\";\n\n private final static String CRLF = \"\\r\\n\";\n\n private final static String VERTICAL_LINE = \"│\";\n\n private final static String HORIZONTAL_LINE = \"─\";\n\n private final static boolean isShow = BuildConfig.BUILD_TYPE.equals(\"debug\");\n\n private static final Charset UTF8 = Charset.forName(\"UTF-8\");\n\n private final Random random = new Random();\n\n @Override\n public Response intercept(@NonNull Chain chain) throws IOException {\n int requestId = random.nextInt(1000000);\n Request request = chain.request();\n buildRequestLog(requestId, request);\n long reqTime = System.currentTimeMillis();\n Response response = chain.proceed(request);\n String url = request.url().uri().toString();\n buildResponseLog(requestId, url, reqTime, response);\n return response;\n }\n\n private void buildRequestLog(int requestId, Request request) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------request------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"url\", request.url().uri().toString());\n appendKeyAndValue(stringBuilder, \"method\", request.method());\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = request.headers().toMultimap();\n ", "post_mask_code": "\n\n private void buildResponseLog(int requestId, String url, long reqTime, Response response) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------response------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"time\", System.currentTimeMillis() - reqTime + \"\");\n appendKeyAndValue(stringBuilder, \"url\", url);\n appendKeyAndValue(stringBuilder, \"message\", response.message());\n appendKeyAndValue(stringBuilder, \"code\", response.code() + \"\");\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = response.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n try {\n String body;\n if (response.body() == null || response.body().contentLength() == 0) {\n body = \"It's empty body\";\n } else {\n BufferedSource source = response.body().source();\n source.request(Long.MAX_VALUE);\n body = source.buffer().clone().readString(UTF8);\n }\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(body).append(CRLF);\n } catch (IOException e) {\n e.printStackTrace();\n }\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void appendKeyAndValue(StringBuilder stringBuilder, String key, String value) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(key).append(COLON).append(value).append(CRLF);\n }\n\n protected String bodyToString(final RequestBody request) {\n try {\n final Buffer buffer = new Buffer();\n if (request == null) {\n return \"\";\n }\n request.writeTo(buffer);\n return buffer.readUtf8();\n } catch (final IOException e) {\n e.printStackTrace();\n return \"\";\n }\n }\n}\n"} {"task_id": "Java_1140", "language": "Java", "task_type": "single_line", "source_file": "java/github/tysqapp/tysq-android/lib/special/lib_multi_download/src/main/java/com/abc/lib_multi_download/okhttp/interceptor/LogInterceptor.java", "mask_start_position": 2272, "mask_end_position": 2278, "canonical_solution": "CRLF);", "pre_mask_code": "package com.abc.lib_multi_download.okhttp.interceptor;\n\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport com.abc.lib_multi_download.BuildConfig;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport okhttp3.Interceptor;\nimport okhttp3.Request;\nimport okhttp3.RequestBody;\nimport okhttp3.Response;\nimport okio.Buffer;\nimport okio.BufferedSource;\n\npublic class LogInterceptor implements Interceptor {\n\n private static final String COLON = \": \";\n\n private final static String TOP_LEFT_LINE = \"┌\";\n\n private final static String MIDDLE_LINE = \"├\";\n\n private final static String BOTTOM_LEFT_LINE = \"└\";\n\n private final static String CRLF = \"\\r\\n\";\n\n private final static String VERTICAL_LINE = \"│\";\n\n private final static String HORIZONTAL_LINE = \"─\";\n\n private final static boolean isShow = BuildConfig.BUILD_TYPE.equals(\"debug\");\n\n private static final Charset UTF8 = Charset.forName(\"UTF-8\");\n\n private final Random random = new Random();\n\n @Override\n public Response intercept(@NonNull Chain chain) throws IOException {\n int requestId = random.nextInt(1000000);\n Request request = chain.request();\n buildRequestLog(requestId, request);\n long reqTime = System.currentTimeMillis();\n Response response = chain.proceed(request);\n String url = request.url().uri().toString();\n buildResponseLog(requestId, url, reqTime, response);\n return response;\n }\n\n private void buildRequestLog(int requestId, Request request) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------request------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"url\", request.url().uri().toString());\n appendKeyAndValue(stringBuilder, \"method\", request.method());\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(", "post_mask_code": "\n Map> headerMap = request.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(request.body() == null ? \"It's empty body\" : bodyToString(request.body())).append(CRLF);\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void buildResponseLog(int requestId, String url, long reqTime, Response response) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------response------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"time\", System.currentTimeMillis() - reqTime + \"\");\n appendKeyAndValue(stringBuilder, \"url\", url);\n appendKeyAndValue(stringBuilder, \"message\", response.message());\n appendKeyAndValue(stringBuilder, \"code\", response.code() + \"\");\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = response.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n try {\n String body;\n if (response.body() == null || response.body().contentLength() == 0) {\n body = \"It's empty body\";\n } else {\n BufferedSource source = response.body().source();\n source.request(Long.MAX_VALUE);\n body = source.buffer().clone().readString(UTF8);\n }\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(body).append(CRLF);\n } catch (IOException e) {\n e.printStackTrace();\n }\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void appendKeyAndValue(StringBuilder stringBuilder, String key, String value) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(key).append(COLON).append(value).append(CRLF);\n }\n\n protected String bodyToString(final RequestBody request) {\n try {\n final Buffer buffer = new Buffer();\n if (request == null) {\n return \"\";\n }\n request.writeTo(buffer);\n return buffer.readUtf8();\n } catch (final IOException e) {\n e.printStackTrace();\n return \"\";\n }\n }\n}\n"} {"task_id": "Java_1141", "language": "Java", "task_type": "if_statement", "source_file": "java/github/tysqapp/tysq-android/lib/special/lib_multi_download/src/main/java/com/abc/lib_multi_download/okhttp/interceptor/LogInterceptor.java", "mask_start_position": 1625, "mask_end_position": 1669, "canonical_solution": "if (!isShow) {\n return;\n }", "pre_mask_code": "package com.abc.lib_multi_download.okhttp.interceptor;\n\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport com.abc.lib_multi_download.BuildConfig;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport okhttp3.Interceptor;\nimport okhttp3.Request;\nimport okhttp3.RequestBody;\nimport okhttp3.Response;\nimport okio.Buffer;\nimport okio.BufferedSource;\n\npublic class LogInterceptor implements Interceptor {\n\n private static final String COLON = \": \";\n\n private final static String TOP_LEFT_LINE = \"┌\";\n\n private final static String MIDDLE_LINE = \"├\";\n\n private final static String BOTTOM_LEFT_LINE = \"└\";\n\n private final static String CRLF = \"\\r\\n\";\n\n private final static String VERTICAL_LINE = \"│\";\n\n private final static String HORIZONTAL_LINE = \"─\";\n\n private final static boolean isShow = BuildConfig.BUILD_TYPE.equals(\"debug\");\n\n private static final Charset UTF8 = Charset.forName(\"UTF-8\");\n\n private final Random random = new Random();\n\n @Override\n public Response intercept(@NonNull Chain chain) throws IOException {\n int requestId = random.nextInt(1000000);\n Request request = chain.request();\n buildRequestLog(requestId, request);\n long reqTime = System.currentTimeMillis();\n Response response = chain.proceed(request);\n String url = request.url().uri().toString();\n buildResponseLog(requestId, url, reqTime, response);\n return response;\n }\n\n private void buildRequestLog(int requestId, Request request) {\n ", "post_mask_code": "\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------request------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"url\", request.url().uri().toString());\n appendKeyAndValue(stringBuilder, \"method\", request.method());\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = request.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(request.body() == null ? \"It's empty body\" : bodyToString(request.body())).append(CRLF);\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void buildResponseLog(int requestId, String url, long reqTime, Response response) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------response------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"time\", System.currentTimeMillis() - reqTime + \"\");\n appendKeyAndValue(stringBuilder, \"url\", url);\n appendKeyAndValue(stringBuilder, \"message\", response.message());\n appendKeyAndValue(stringBuilder, \"code\", response.code() + \"\");\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = response.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n try {\n String body;\n if (response.body() == null || response.body().contentLength() == 0) {\n body = \"It's empty body\";\n } else {\n BufferedSource source = response.body().source();\n source.request(Long.MAX_VALUE);\n body = source.buffer().clone().readString(UTF8);\n }\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(body).append(CRLF);\n } catch (IOException e) {\n e.printStackTrace();\n }\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void appendKeyAndValue(StringBuilder stringBuilder, String key, String value) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(key).append(COLON).append(value).append(CRLF);\n }\n\n protected String bodyToString(final RequestBody request) {\n try {\n final Buffer buffer = new Buffer();\n if (request == null) {\n return \"\";\n }\n request.writeTo(buffer);\n return buffer.readUtf8();\n } catch (final IOException e) {\n e.printStackTrace();\n return \"\";\n }\n }\n}\n"} {"task_id": "Java_1142", "language": "Java", "task_type": "try_statement", "source_file": "java/github/tysqapp/tysq-android/lib/special/lib_multi_download/src/main/java/com/abc/lib_multi_download/okhttp/interceptor/LogInterceptor.java", "mask_start_position": 5458, "mask_end_position": 5768, "canonical_solution": "try {\n final Buffer buffer = new Buffer();\n if (request == null) {\n return \"\";\n }\n request.writeTo(buffer);\n return buffer.readUtf8();\n } catch (final IOException e) {\n e.printStackTrace();\n return \"\";\n }", "pre_mask_code": "package com.abc.lib_multi_download.okhttp.interceptor;\n\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport com.abc.lib_multi_download.BuildConfig;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport okhttp3.Interceptor;\nimport okhttp3.Request;\nimport okhttp3.RequestBody;\nimport okhttp3.Response;\nimport okio.Buffer;\nimport okio.BufferedSource;\n\npublic class LogInterceptor implements Interceptor {\n\n private static final String COLON = \": \";\n\n private final static String TOP_LEFT_LINE = \"┌\";\n\n private final static String MIDDLE_LINE = \"├\";\n\n private final static String BOTTOM_LEFT_LINE = \"└\";\n\n private final static String CRLF = \"\\r\\n\";\n\n private final static String VERTICAL_LINE = \"│\";\n\n private final static String HORIZONTAL_LINE = \"─\";\n\n private final static boolean isShow = BuildConfig.BUILD_TYPE.equals(\"debug\");\n\n private static final Charset UTF8 = Charset.forName(\"UTF-8\");\n\n private final Random random = new Random();\n\n @Override\n public Response intercept(@NonNull Chain chain) throws IOException {\n int requestId = random.nextInt(1000000);\n Request request = chain.request();\n buildRequestLog(requestId, request);\n long reqTime = System.currentTimeMillis();\n Response response = chain.proceed(request);\n String url = request.url().uri().toString();\n buildResponseLog(requestId, url, reqTime, response);\n return response;\n }\n\n private void buildRequestLog(int requestId, Request request) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------request------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"url\", request.url().uri().toString());\n appendKeyAndValue(stringBuilder, \"method\", request.method());\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = request.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(request.body() == null ? \"It's empty body\" : bodyToString(request.body())).append(CRLF);\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void buildResponseLog(int requestId, String url, long reqTime, Response response) {\n if (!isShow) {\n return;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"HTTP Log\").append(CRLF);\n stringBuilder.append(TOP_LEFT_LINE).append(\"------------response------------------------------------------\").append(CRLF);\n appendKeyAndValue(stringBuilder, \"id\", requestId + \"\");\n appendKeyAndValue(stringBuilder, \"time\", System.currentTimeMillis() - reqTime + \"\");\n appendKeyAndValue(stringBuilder, \"url\", url);\n appendKeyAndValue(stringBuilder, \"message\", response.message());\n appendKeyAndValue(stringBuilder, \"code\", response.code() + \"\");\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(\"head params\").append(CRLF);\n Map> headerMap = response.headers().toMultimap();\n for (Map.Entry> entry : headerMap.entrySet()) {\n String key = entry.getKey();\n for (String value : entry.getValue()) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(MIDDLE_LINE).append(key).append(COLON).append(value).append(CRLF);\n }\n }\n stringBuilder.append(VERTICAL_LINE).append(CRLF);\n try {\n String body;\n if (response.body() == null || response.body().contentLength() == 0) {\n body = \"It's empty body\";\n } else {\n BufferedSource source = response.body().source();\n source.request(Long.MAX_VALUE);\n body = source.buffer().clone().readString(UTF8);\n }\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(body).append(CRLF);\n } catch (IOException e) {\n e.printStackTrace();\n }\n stringBuilder.append(BOTTOM_LEFT_LINE).append(\"-----------------------------------------------------------\");\n Log.i(\"LogInterceptor\", stringBuilder.toString());\n }\n\n private void appendKeyAndValue(StringBuilder stringBuilder, String key, String value) {\n stringBuilder.append(VERTICAL_LINE).append(\" \").append(key).append(COLON).append(value).append(CRLF);\n }\n\n protected String bodyToString(final RequestBody request) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1143", "language": "Java", "task_type": "method_signature", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/plugin/report/kvdata/log_13835.java", "mask_start_position": 416, "mask_end_position": 463, "canonical_solution": "protected final int a(int i, Object... objArr) ", "pre_mask_code": "package com.tencent.mm.plugin.report.kvdata;\n\nimport a.a.a.b;\nimport com.tencent.mm.ba.a;\nimport java.util.LinkedList;\n\npublic class log_13835 extends a {\n\n public int clientVersion_;\n\n public String currChatName_;\n\n public int device_;\n\n public int ds_;\n\n public int import_ds_;\n\n public LinkedList oplist_ = new LinkedList();\n\n public long time_stamp_;\n\n public long uin_;\n\n ", "post_mask_code": "{\n if (i == 0) {\n a.a.a.c.a aVar = (a.a.a.c.a) objArr[0];\n if (this.currChatName_ == null) {\n throw new b(\"Not all required fields were included: currChatName_\");\n }\n aVar.dV(1, this.import_ds_);\n aVar.dV(2, this.ds_);\n aVar.C(3, this.uin_);\n aVar.dV(4, this.device_);\n aVar.dV(5, this.clientVersion_);\n aVar.C(6, this.time_stamp_);\n if (this.currChatName_ != null) {\n aVar.e(7, this.currChatName_);\n }\n aVar.d(8, 8, this.oplist_);\n return 0;\n } else if (i == 1) {\n r0 = (((((a.a.a.a.dS(1, this.import_ds_) + 0) + a.a.a.a.dS(2, this.ds_)) + a.a.a.a.B(3, this.uin_)) + a.a.a.a.dS(4, this.device_)) + a.a.a.a.dS(5, this.clientVersion_)) + a.a.a.a.B(6, this.time_stamp_);\n if (this.currChatName_ != null) {\n r0 += a.a.a.b.b.a.f(7, this.currChatName_);\n }\n return r0 + a.a.a.a.c(8, 8, this.oplist_);\n } else if (i == 2) {\n r0 = (byte[]) objArr[0];\n this.oplist_.clear();\n a.a.a.a.a aVar2 = new a.a.a.a.a(r0, unknownTagHandler);\n for (r0 = a.a(aVar2); r0 > 0; r0 = a.a(aVar2)) {\n if (!super.a(aVar2, this, r0)) {\n aVar2.bQL();\n }\n }\n if (this.currChatName_ != null) {\n return 0;\n }\n throw new b(\"Not all required fields were included: currChatName_\");\n } else if (i != 3) {\n return -1;\n } else {\n a.a.a.a.a aVar3 = (a.a.a.a.a) objArr[0];\n log_13835 com_tencent_mm_plugin_report_kvdata_log_13835 = (log_13835) objArr[1];\n int intValue = ((Integer) objArr[2]).intValue();\n switch(intValue) {\n case 1:\n com_tencent_mm_plugin_report_kvdata_log_13835.import_ds_ = aVar3.pMj.mH();\n return 0;\n case 2:\n com_tencent_mm_plugin_report_kvdata_log_13835.ds_ = aVar3.pMj.mH();\n return 0;\n case 3:\n com_tencent_mm_plugin_report_kvdata_log_13835.uin_ = aVar3.pMj.mI();\n return 0;\n case 4:\n com_tencent_mm_plugin_report_kvdata_log_13835.device_ = aVar3.pMj.mH();\n return 0;\n case 5:\n com_tencent_mm_plugin_report_kvdata_log_13835.clientVersion_ = aVar3.pMj.mH();\n return 0;\n case 6:\n com_tencent_mm_plugin_report_kvdata_log_13835.time_stamp_ = aVar3.pMj.mI();\n return 0;\n case 7:\n com_tencent_mm_plugin_report_kvdata_log_13835.currChatName_ = aVar3.pMj.readString();\n return 0;\n case 8:\n LinkedList zQ = aVar3.zQ(intValue);\n int size = zQ.size();\n for (intValue = 0; intValue < size; intValue++) {\n r0 = (byte[]) zQ.get(intValue);\n a iMBehavior = new IMBehavior();\n a.a.a.a.a aVar4 = new a.a.a.a.a(r0, unknownTagHandler);\n for (boolean z = true; z; z = iMBehavior.a(aVar4, iMBehavior, a.a(aVar4))) {\n }\n com_tencent_mm_plugin_report_kvdata_log_13835.oplist_.add(iMBehavior);\n }\n return 0;\n default:\n return -1;\n }\n }\n }\n}\n"} {"task_id": "Java_1144", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/plugin/report/kvdata/log_13835.java", "mask_start_position": 464, "mask_end_position": 464, "canonical_solution": "", "pre_mask_code": "package com.tencent.mm.plugin.report.kvdata;\n\nimport a.a.a.b;\nimport com.tencent.mm.ba.a;\nimport java.util.LinkedList;\n\npublic class log_13835 extends a {\n\n public int clientVersion_;\n\n public String currChatName_;\n\n public int device_;\n\n public int ds_;\n\n public int import_ds_;\n\n public LinkedList oplist_ = new LinkedList();\n\n public long time_stamp_;\n\n public long uin_;\n\n protected final int a(int i, Object... objArr) {", "post_mask_code": "\n if (i == 0) {\n a.a.a.c.a aVar = (a.a.a.c.a) objArr[0];\n if (this.currChatName_ == null) {\n throw new b(\"Not all required fields were included: currChatName_\");\n }\n aVar.dV(1, this.import_ds_);\n aVar.dV(2, this.ds_);\n aVar.C(3, this.uin_);\n aVar.dV(4, this.device_);\n aVar.dV(5, this.clientVersion_);\n aVar.C(6, this.time_stamp_);\n if (this.currChatName_ != null) {\n aVar.e(7, this.currChatName_);\n }\n aVar.d(8, 8, this.oplist_);\n return 0;\n } else if (i == 1) {\n r0 = (((((a.a.a.a.dS(1, this.import_ds_) + 0) + a.a.a.a.dS(2, this.ds_)) + a.a.a.a.B(3, this.uin_)) + a.a.a.a.dS(4, this.device_)) + a.a.a.a.dS(5, this.clientVersion_)) + a.a.a.a.B(6, this.time_stamp_);\n if (this.currChatName_ != null) {\n r0 += a.a.a.b.b.a.f(7, this.currChatName_);\n }\n return r0 + a.a.a.a.c(8, 8, this.oplist_);\n } else if (i == 2) {\n r0 = (byte[]) objArr[0];\n this.oplist_.clear();\n a.a.a.a.a aVar2 = new a.a.a.a.a(r0, unknownTagHandler);\n for (r0 = a.a(aVar2); r0 > 0; r0 = a.a(aVar2)) {\n if (!super.a(aVar2, this, r0)) {\n aVar2.bQL();\n }\n }\n if (this.currChatName_ != null) {\n return 0;\n }\n throw new b(\"Not all required fields were included: currChatName_\");\n } else if (i != 3) {\n return -1;\n } else {\n a.a.a.a.a aVar3 = (a.a.a.a.a) objArr[0];\n log_13835 com_tencent_mm_plugin_report_kvdata_log_13835 = (log_13835) objArr[1];\n int intValue = ((Integer) objArr[2]).intValue();\n switch(intValue) {\n case 1:\n com_tencent_mm_plugin_report_kvdata_log_13835.import_ds_ = aVar3.pMj.mH();\n return 0;\n case 2:\n com_tencent_mm_plugin_report_kvdata_log_13835.ds_ = aVar3.pMj.mH();\n return 0;\n case 3:\n com_tencent_mm_plugin_report_kvdata_log_13835.uin_ = aVar3.pMj.mI();\n return 0;\n case 4:\n com_tencent_mm_plugin_report_kvdata_log_13835.device_ = aVar3.pMj.mH();\n return 0;\n case 5:\n com_tencent_mm_plugin_report_kvdata_log_13835.clientVersion_ = aVar3.pMj.mH();\n return 0;\n case 6:\n com_tencent_mm_plugin_report_kvdata_log_13835.time_stamp_ = aVar3.pMj.mI();\n return 0;\n case 7:\n com_tencent_mm_plugin_report_kvdata_log_13835.currChatName_ = aVar3.pMj.readString();\n return 0;\n case 8:\n LinkedList zQ = aVar3.zQ(intValue);\n int size = zQ.size();\n for (intValue = 0; intValue < size; intValue++) {\n r0 = (byte[]) zQ.get(intValue);\n a iMBehavior = new IMBehavior();\n a.a.a.a.a aVar4 = new a.a.a.a.a(r0, unknownTagHandler);\n for (boolean z = true; z; z = iMBehavior.a(aVar4, iMBehavior, a.a(aVar4))) {\n }\n com_tencent_mm_plugin_report_kvdata_log_13835.oplist_.add(iMBehavior);\n }\n return 0;\n default:\n return -1;\n }\n }\n }\n}\n"} {"task_id": "Java_1145", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/plugin/report/kvdata/log_13835.java", "mask_start_position": 473, "mask_end_position": 4103, "canonical_solution": "if (i == 0) {\n a.a.a.c.a aVar = (a.a.a.c.a) objArr[0];\n if (this.currChatName_ == null) {\n throw new b(\"Not all required fields were included: currChatName_\");\n }\n aVar.dV(1, this.import_ds_);\n aVar.dV(2, this.ds_);\n aVar.C(3, this.uin_);\n aVar.dV(4, this.device_);\n aVar.dV(5, this.clientVersion_);\n aVar.C(6, this.time_stamp_);\n if (this.currChatName_ != null) {\n aVar.e(7, this.currChatName_);\n }\n aVar.d(8, 8, this.oplist_);\n return 0;\n } else if (i == 1) {\n r0 = (((((a.a.a.a.dS(1, this.import_ds_) + 0) + a.a.a.a.dS(2, this.ds_)) + a.a.a.a.B(3, this.uin_)) + a.a.a.a.dS(4, this.device_)) + a.a.a.a.dS(5, this.clientVersion_)) + a.a.a.a.B(6, this.time_stamp_);\n if (this.currChatName_ != null) {\n r0 += a.a.a.b.b.a.f(7, this.currChatName_);\n }\n return r0 + a.a.a.a.c(8, 8, this.oplist_);\n } else if (i == 2) {\n r0 = (byte[]) objArr[0];\n this.oplist_.clear();\n a.a.a.a.a aVar2 = new a.a.a.a.a(r0, unknownTagHandler);\n for (r0 = a.a(aVar2); r0 > 0; r0 = a.a(aVar2)) {\n if (!super.a(aVar2, this, r0)) {\n aVar2.bQL();\n }\n }\n if (this.currChatName_ != null) {\n return 0;\n }\n throw new b(\"Not all required fields were included: currChatName_\");\n } else if (i != 3) {\n return -1;\n } else {\n a.a.a.a.a aVar3 = (a.a.a.a.a) objArr[0];\n log_13835 com_tencent_mm_plugin_report_kvdata_log_13835 = (log_13835) objArr[1];\n int intValue = ((Integer) objArr[2]).intValue();\n switch(intValue) {\n case 1:\n com_tencent_mm_plugin_report_kvdata_log_13835.import_ds_ = aVar3.pMj.mH();\n return 0;\n case 2:\n com_tencent_mm_plugin_report_kvdata_log_13835.ds_ = aVar3.pMj.mH();\n return 0;\n case 3:\n com_tencent_mm_plugin_report_kvdata_log_13835.uin_ = aVar3.pMj.mI();\n return 0;\n case 4:\n com_tencent_mm_plugin_report_kvdata_log_13835.device_ = aVar3.pMj.mH();\n return 0;\n case 5:\n com_tencent_mm_plugin_report_kvdata_log_13835.clientVersion_ = aVar3.pMj.mH();\n return 0;\n case 6:\n com_tencent_mm_plugin_report_kvdata_log_13835.time_stamp_ = aVar3.pMj.mI();\n return 0;\n case 7:\n com_tencent_mm_plugin_report_kvdata_log_13835.currChatName_ = aVar3.pMj.readString();\n return 0;\n case 8:\n LinkedList zQ = aVar3.zQ(intValue);\n int size = zQ.size();\n for (intValue = 0; intValue < size; intValue++) {\n r0 = (byte[]) zQ.get(intValue);\n a iMBehavior = new IMBehavior();\n a.a.a.a.a aVar4 = new a.a.a.a.a(r0, unknownTagHandler);\n for (boolean z = true; z; z = iMBehavior.a(aVar4, iMBehavior, a.a(aVar4))) {\n }\n com_tencent_mm_plugin_report_kvdata_log_13835.oplist_.add(iMBehavior);\n }\n return 0;\n default:\n return -1;\n }\n }", "pre_mask_code": "package com.tencent.mm.plugin.report.kvdata;\n\nimport a.a.a.b;\nimport com.tencent.mm.ba.a;\nimport java.util.LinkedList;\n\npublic class log_13835 extends a {\n\n public int clientVersion_;\n\n public String currChatName_;\n\n public int device_;\n\n public int ds_;\n\n public int import_ds_;\n\n public LinkedList oplist_ = new LinkedList();\n\n public long time_stamp_;\n\n public long uin_;\n\n protected final int a(int i, Object... objArr) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1146", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/plugin/report/kvdata/log_13835.java", "mask_start_position": 4108, "mask_end_position": 4109, "canonical_solution": "}", "pre_mask_code": "package com.tencent.mm.plugin.report.kvdata;\n\nimport a.a.a.b;\nimport com.tencent.mm.ba.a;\nimport java.util.LinkedList;\n\npublic class log_13835 extends a {\n\n public int clientVersion_;\n\n public String currChatName_;\n\n public int device_;\n\n public int ds_;\n\n public int import_ds_;\n\n public LinkedList oplist_ = new LinkedList();\n\n public long time_stamp_;\n\n public long uin_;\n\n protected final int a(int i, Object... objArr) {\n if (i == 0) {\n a.a.a.c.a aVar = (a.a.a.c.a) objArr[0];\n if (this.currChatName_ == null) {\n throw new b(\"Not all required fields were included: currChatName_\");\n }\n aVar.dV(1, this.import_ds_);\n aVar.dV(2, this.ds_);\n aVar.C(3, this.uin_);\n aVar.dV(4, this.device_);\n aVar.dV(5, this.clientVersion_);\n aVar.C(6, this.time_stamp_);\n if (this.currChatName_ != null) {\n aVar.e(7, this.currChatName_);\n }\n aVar.d(8, 8, this.oplist_);\n return 0;\n } else if (i == 1) {\n r0 = (((((a.a.a.a.dS(1, this.import_ds_) + 0) + a.a.a.a.dS(2, this.ds_)) + a.a.a.a.B(3, this.uin_)) + a.a.a.a.dS(4, this.device_)) + a.a.a.a.dS(5, this.clientVersion_)) + a.a.a.a.B(6, this.time_stamp_);\n if (this.currChatName_ != null) {\n r0 += a.a.a.b.b.a.f(7, this.currChatName_);\n }\n return r0 + a.a.a.a.c(8, 8, this.oplist_);\n } else if (i == 2) {\n r0 = (byte[]) objArr[0];\n this.oplist_.clear();\n a.a.a.a.a aVar2 = new a.a.a.a.a(r0, unknownTagHandler);\n for (r0 = a.a(aVar2); r0 > 0; r0 = a.a(aVar2)) {\n if (!super.a(aVar2, this, r0)) {\n aVar2.bQL();\n }\n }\n if (this.currChatName_ != null) {\n return 0;\n }\n throw new b(\"Not all required fields were included: currChatName_\");\n } else if (i != 3) {\n return -1;\n } else {\n a.a.a.a.a aVar3 = (a.a.a.a.a) objArr[0];\n log_13835 com_tencent_mm_plugin_report_kvdata_log_13835 = (log_13835) objArr[1];\n int intValue = ((Integer) objArr[2]).intValue();\n switch(intValue) {\n case 1:\n com_tencent_mm_plugin_report_kvdata_log_13835.import_ds_ = aVar3.pMj.mH();\n return 0;\n case 2:\n com_tencent_mm_plugin_report_kvdata_log_13835.ds_ = aVar3.pMj.mH();\n return 0;\n case 3:\n com_tencent_mm_plugin_report_kvdata_log_13835.uin_ = aVar3.pMj.mI();\n return 0;\n case 4:\n com_tencent_mm_plugin_report_kvdata_log_13835.device_ = aVar3.pMj.mH();\n return 0;\n case 5:\n com_tencent_mm_plugin_report_kvdata_log_13835.clientVersion_ = aVar3.pMj.mH();\n return 0;\n case 6:\n com_tencent_mm_plugin_report_kvdata_log_13835.time_stamp_ = aVar3.pMj.mI();\n return 0;\n case 7:\n com_tencent_mm_plugin_report_kvdata_log_13835.currChatName_ = aVar3.pMj.readString();\n return 0;\n case 8:\n LinkedList zQ = aVar3.zQ(intValue);\n int size = zQ.size();\n for (intValue = 0; intValue < size; intValue++) {\n r0 = (byte[]) zQ.get(intValue);\n a iMBehavior = new IMBehavior();\n a.a.a.a.a aVar4 = new a.a.a.a.a(r0, unknownTagHandler);\n for (boolean z = true; z; z = iMBehavior.a(aVar4, iMBehavior, a.a(aVar4))) {\n }\n com_tencent_mm_plugin_report_kvdata_log_13835.oplist_.add(iMBehavior);\n }\n return 0;\n default:\n return -1;\n }\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1147", "language": "Java", "task_type": "if_statement", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/plugin/report/kvdata/log_13835.java", "mask_start_position": 1342, "mask_end_position": 1449, "canonical_solution": "if (this.currChatName_ != null) {\n r0 += a.a.a.b.b.a.f(7, this.currChatName_);\n }", "pre_mask_code": "package com.tencent.mm.plugin.report.kvdata;\n\nimport a.a.a.b;\nimport com.tencent.mm.ba.a;\nimport java.util.LinkedList;\n\npublic class log_13835 extends a {\n\n public int clientVersion_;\n\n public String currChatName_;\n\n public int device_;\n\n public int ds_;\n\n public int import_ds_;\n\n public LinkedList oplist_ = new LinkedList();\n\n public long time_stamp_;\n\n public long uin_;\n\n protected final int a(int i, Object... objArr) {\n if (i == 0) {\n a.a.a.c.a aVar = (a.a.a.c.a) objArr[0];\n if (this.currChatName_ == null) {\n throw new b(\"Not all required fields were included: currChatName_\");\n }\n aVar.dV(1, this.import_ds_);\n aVar.dV(2, this.ds_);\n aVar.C(3, this.uin_);\n aVar.dV(4, this.device_);\n aVar.dV(5, this.clientVersion_);\n aVar.C(6, this.time_stamp_);\n if (this.currChatName_ != null) {\n aVar.e(7, this.currChatName_);\n }\n aVar.d(8, 8, this.oplist_);\n return 0;\n } else if (i == 1) {\n r0 = (((((a.a.a.a.dS(1, this.import_ds_) + 0) + a.a.a.a.dS(2, this.ds_)) + a.a.a.a.B(3, this.uin_)) + a.a.a.a.dS(4, this.device_)) + a.a.a.a.dS(5, this.clientVersion_)) + a.a.a.a.B(6, this.time_stamp_);\n ", "post_mask_code": "\n return r0 + a.a.a.a.c(8, 8, this.oplist_);\n } else if (i == 2) {\n r0 = (byte[]) objArr[0];\n this.oplist_.clear();\n a.a.a.a.a aVar2 = new a.a.a.a.a(r0, unknownTagHandler);\n for (r0 = a.a(aVar2); r0 > 0; r0 = a.a(aVar2)) {\n if (!super.a(aVar2, this, r0)) {\n aVar2.bQL();\n }\n }\n if (this.currChatName_ != null) {\n return 0;\n }\n throw new b(\"Not all required fields were included: currChatName_\");\n } else if (i != 3) {\n return -1;\n } else {\n a.a.a.a.a aVar3 = (a.a.a.a.a) objArr[0];\n log_13835 com_tencent_mm_plugin_report_kvdata_log_13835 = (log_13835) objArr[1];\n int intValue = ((Integer) objArr[2]).intValue();\n switch(intValue) {\n case 1:\n com_tencent_mm_plugin_report_kvdata_log_13835.import_ds_ = aVar3.pMj.mH();\n return 0;\n case 2:\n com_tencent_mm_plugin_report_kvdata_log_13835.ds_ = aVar3.pMj.mH();\n return 0;\n case 3:\n com_tencent_mm_plugin_report_kvdata_log_13835.uin_ = aVar3.pMj.mI();\n return 0;\n case 4:\n com_tencent_mm_plugin_report_kvdata_log_13835.device_ = aVar3.pMj.mH();\n return 0;\n case 5:\n com_tencent_mm_plugin_report_kvdata_log_13835.clientVersion_ = aVar3.pMj.mH();\n return 0;\n case 6:\n com_tencent_mm_plugin_report_kvdata_log_13835.time_stamp_ = aVar3.pMj.mI();\n return 0;\n case 7:\n com_tencent_mm_plugin_report_kvdata_log_13835.currChatName_ = aVar3.pMj.readString();\n return 0;\n case 8:\n LinkedList zQ = aVar3.zQ(intValue);\n int size = zQ.size();\n for (intValue = 0; intValue < size; intValue++) {\n r0 = (byte[]) zQ.get(intValue);\n a iMBehavior = new IMBehavior();\n a.a.a.a.a aVar4 = new a.a.a.a.a(r0, unknownTagHandler);\n for (boolean z = true; z; z = iMBehavior.a(aVar4, iMBehavior, a.a(aVar4))) {\n }\n com_tencent_mm_plugin_report_kvdata_log_13835.oplist_.add(iMBehavior);\n }\n return 0;\n default:\n return -1;\n }\n }\n }\n}\n"} {"task_id": "Java_1148", "language": "Java", "task_type": "for_statement", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/plugin/report/kvdata/log_13835.java", "mask_start_position": 3507, "mask_end_position": 3993, "canonical_solution": "for (intValue = 0; intValue < size; intValue++) {\n r0 = (byte[]) zQ.get(intValue);\n a iMBehavior = new IMBehavior();\n a.a.a.a.a aVar4 = new a.a.a.a.a(r0, unknownTagHandler);\n for (boolean z = true; z; z = iMBehavior.a(aVar4, iMBehavior, a.a(aVar4))) {\n }\n com_tencent_mm_plugin_report_kvdata_log_13835.oplist_.add(iMBehavior);\n }", "pre_mask_code": "package com.tencent.mm.plugin.report.kvdata;\n\nimport a.a.a.b;\nimport com.tencent.mm.ba.a;\nimport java.util.LinkedList;\n\npublic class log_13835 extends a {\n\n public int clientVersion_;\n\n public String currChatName_;\n\n public int device_;\n\n public int ds_;\n\n public int import_ds_;\n\n public LinkedList oplist_ = new LinkedList();\n\n public long time_stamp_;\n\n public long uin_;\n\n protected final int a(int i, Object... objArr) {\n if (i == 0) {\n a.a.a.c.a aVar = (a.a.a.c.a) objArr[0];\n if (this.currChatName_ == null) {\n throw new b(\"Not all required fields were included: currChatName_\");\n }\n aVar.dV(1, this.import_ds_);\n aVar.dV(2, this.ds_);\n aVar.C(3, this.uin_);\n aVar.dV(4, this.device_);\n aVar.dV(5, this.clientVersion_);\n aVar.C(6, this.time_stamp_);\n if (this.currChatName_ != null) {\n aVar.e(7, this.currChatName_);\n }\n aVar.d(8, 8, this.oplist_);\n return 0;\n } else if (i == 1) {\n r0 = (((((a.a.a.a.dS(1, this.import_ds_) + 0) + a.a.a.a.dS(2, this.ds_)) + a.a.a.a.B(3, this.uin_)) + a.a.a.a.dS(4, this.device_)) + a.a.a.a.dS(5, this.clientVersion_)) + a.a.a.a.B(6, this.time_stamp_);\n if (this.currChatName_ != null) {\n r0 += a.a.a.b.b.a.f(7, this.currChatName_);\n }\n return r0 + a.a.a.a.c(8, 8, this.oplist_);\n } else if (i == 2) {\n r0 = (byte[]) objArr[0];\n this.oplist_.clear();\n a.a.a.a.a aVar2 = new a.a.a.a.a(r0, unknownTagHandler);\n for (r0 = a.a(aVar2); r0 > 0; r0 = a.a(aVar2)) {\n if (!super.a(aVar2, this, r0)) {\n aVar2.bQL();\n }\n }\n if (this.currChatName_ != null) {\n return 0;\n }\n throw new b(\"Not all required fields were included: currChatName_\");\n } else if (i != 3) {\n return -1;\n } else {\n a.a.a.a.a aVar3 = (a.a.a.a.a) objArr[0];\n log_13835 com_tencent_mm_plugin_report_kvdata_log_13835 = (log_13835) objArr[1];\n int intValue = ((Integer) objArr[2]).intValue();\n switch(intValue) {\n case 1:\n com_tencent_mm_plugin_report_kvdata_log_13835.import_ds_ = aVar3.pMj.mH();\n return 0;\n case 2:\n com_tencent_mm_plugin_report_kvdata_log_13835.ds_ = aVar3.pMj.mH();\n return 0;\n case 3:\n com_tencent_mm_plugin_report_kvdata_log_13835.uin_ = aVar3.pMj.mI();\n return 0;\n case 4:\n com_tencent_mm_plugin_report_kvdata_log_13835.device_ = aVar3.pMj.mH();\n return 0;\n case 5:\n com_tencent_mm_plugin_report_kvdata_log_13835.clientVersion_ = aVar3.pMj.mH();\n return 0;\n case 6:\n com_tencent_mm_plugin_report_kvdata_log_13835.time_stamp_ = aVar3.pMj.mI();\n return 0;\n case 7:\n com_tencent_mm_plugin_report_kvdata_log_13835.currChatName_ = aVar3.pMj.readString();\n return 0;\n case 8:\n LinkedList zQ = aVar3.zQ(intValue);\n int size = zQ.size();\n ", "post_mask_code": "\n return 0;\n default:\n return -1;\n }\n }\n }\n}\n"} {"task_id": "Java_1149", "language": "Java", "task_type": "method_signature", "source_file": "java/github/robovm/robovm/rt/external/apache-http/src/org/apache/commons/codec/net/BCodec.java", "mask_start_position": 4576, "mask_end_position": 4635, "canonical_solution": "public Object encode(Object value) throws EncoderException ", "pre_mask_code": "package org.apache.commons.codec.net;\n\nimport java.io.UnsupportedEncodingException;\nimport org.apache.commons.codec.DecoderException;\nimport org.apache.commons.codec.EncoderException;\nimport org.apache.commons.codec.StringDecoder;\nimport org.apache.commons.codec.StringEncoder;\nimport org.apache.commons.codec.binary.Base64;\n\n/**\n *

\n * Identical to the Base64 encoding defined by RFC\n * 1521 and allows a character set to be specified.\n *

\n *\n *

\n * RFC 1522 describes techniques to allow the encoding of non-ASCII\n * text in various portions of a RFC 822 [2] message header, in a manner which is unlikely to confuse existing message\n * handling software.\n *

\n *\n * @see MIME (Multipurpose Internet Mail Extensions) Part Two: Message\n * Header Extensions for Non-ASCII Text\n *\n * @author Apache Software Foundation\n * @since 1.3\n * @version $Id: BCodec.java,v 1.5 2004/04/13 22:46:37 ggregory Exp $\n */\npublic class BCodec extends RFC1522Codec implements StringEncoder, StringDecoder {\n\n /**\n * The default charset used for string decoding and encoding.\n */\n private String charset = StringEncodings.UTF8;\n\n public BCodec() {\n super();\n }\n\n /**\n * Constructor which allows for the selection of a default charset\n *\n * @param charset\n * the default string charset to use.\n *\n * @see JRE character\n * encoding names\n */\n public BCodec(final String charset) {\n super();\n this.charset = charset;\n }\n\n protected String getEncoding() {\n return \"B\";\n }\n\n protected byte[] doEncoding(byte[] bytes) throws EncoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.encodeBase64(bytes);\n }\n\n protected byte[] doDecoding(byte[] bytes) throws DecoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.decodeBase64(bytes);\n }\n\n /**\n * Encodes a string into its Base64 form using the specified charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @param charset\n * the charset for pString\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(final String value, final String charset) throws EncoderException {\n if (value == null) {\n return null;\n }\n try {\n return encodeText(value, charset);\n } catch (UnsupportedEncodingException e) {\n throw new EncoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes a string into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(String value) throws EncoderException {\n if (value == null) {\n return null;\n }\n return encode(value, getDefaultCharset());\n }\n\n /**\n * Decodes a Base64 string into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 string to convert into its original form\n *\n * @return original string\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public String decode(String value) throws DecoderException {\n if (value == null) {\n return null;\n }\n try {\n return decodeText(value);\n } catch (UnsupportedEncodingException e) {\n throw new DecoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes an object into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * object to convert to Base64 form\n * @return Base64 object\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n ", "post_mask_code": "{\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return encode((String) value);\n } else {\n throw new EncoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be encoded using BCodec\");\n }\n }\n\n /**\n * Decodes a Base64 object into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 object to convert into its original form\n *\n * @return original object\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public Object decode(Object value) throws DecoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return decode((String) value);\n } else {\n throw new DecoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be decoded using BCodec\");\n }\n }\n\n /**\n * The default charset used for string decoding and encoding.\n *\n * @return the default string charset.\n */\n public String getDefaultCharset() {\n return this.charset;\n }\n}\n"} {"task_id": "Java_1150", "language": "Java", "task_type": "method_body", "source_file": "java/github/robovm/robovm/rt/external/apache-http/src/org/apache/commons/codec/net/BCodec.java", "mask_start_position": 5921, "mask_end_position": 5957, "canonical_solution": "{\n return this.charset;\n }", "pre_mask_code": "package org.apache.commons.codec.net;\n\nimport java.io.UnsupportedEncodingException;\nimport org.apache.commons.codec.DecoderException;\nimport org.apache.commons.codec.EncoderException;\nimport org.apache.commons.codec.StringDecoder;\nimport org.apache.commons.codec.StringEncoder;\nimport org.apache.commons.codec.binary.Base64;\n\n/**\n *

\n * Identical to the Base64 encoding defined by RFC\n * 1521 and allows a character set to be specified.\n *

\n *\n *

\n * RFC 1522 describes techniques to allow the encoding of non-ASCII\n * text in various portions of a RFC 822 [2] message header, in a manner which is unlikely to confuse existing message\n * handling software.\n *

\n *\n * @see MIME (Multipurpose Internet Mail Extensions) Part Two: Message\n * Header Extensions for Non-ASCII Text\n *\n * @author Apache Software Foundation\n * @since 1.3\n * @version $Id: BCodec.java,v 1.5 2004/04/13 22:46:37 ggregory Exp $\n */\npublic class BCodec extends RFC1522Codec implements StringEncoder, StringDecoder {\n\n /**\n * The default charset used for string decoding and encoding.\n */\n private String charset = StringEncodings.UTF8;\n\n public BCodec() {\n super();\n }\n\n /**\n * Constructor which allows for the selection of a default charset\n *\n * @param charset\n * the default string charset to use.\n *\n * @see JRE character\n * encoding names\n */\n public BCodec(final String charset) {\n super();\n this.charset = charset;\n }\n\n protected String getEncoding() {\n return \"B\";\n }\n\n protected byte[] doEncoding(byte[] bytes) throws EncoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.encodeBase64(bytes);\n }\n\n protected byte[] doDecoding(byte[] bytes) throws DecoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.decodeBase64(bytes);\n }\n\n /**\n * Encodes a string into its Base64 form using the specified charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @param charset\n * the charset for pString\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(final String value, final String charset) throws EncoderException {\n if (value == null) {\n return null;\n }\n try {\n return encodeText(value, charset);\n } catch (UnsupportedEncodingException e) {\n throw new EncoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes a string into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(String value) throws EncoderException {\n if (value == null) {\n return null;\n }\n return encode(value, getDefaultCharset());\n }\n\n /**\n * Decodes a Base64 string into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 string to convert into its original form\n *\n * @return original string\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public String decode(String value) throws DecoderException {\n if (value == null) {\n return null;\n }\n try {\n return decodeText(value);\n } catch (UnsupportedEncodingException e) {\n throw new DecoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes an object into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * object to convert to Base64 form\n * @return Base64 object\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public Object encode(Object value) throws EncoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return encode((String) value);\n } else {\n throw new EncoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be encoded using BCodec\");\n }\n }\n\n /**\n * Decodes a Base64 object into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 object to convert into its original form\n *\n * @return original object\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public Object decode(Object value) throws DecoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return decode((String) value);\n } else {\n throw new DecoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be decoded using BCodec\");\n }\n }\n\n /**\n * The default charset used for string decoding and encoding.\n *\n * @return the default string charset.\n */\n public String getDefaultCharset() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1151", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/robovm/robovm/rt/external/apache-http/src/org/apache/commons/codec/net/BCodec.java", "mask_start_position": 2646, "mask_end_position": 2710, "canonical_solution": "\n if (value == null) {\n return null;\n }", "pre_mask_code": "package org.apache.commons.codec.net;\n\nimport java.io.UnsupportedEncodingException;\nimport org.apache.commons.codec.DecoderException;\nimport org.apache.commons.codec.EncoderException;\nimport org.apache.commons.codec.StringDecoder;\nimport org.apache.commons.codec.StringEncoder;\nimport org.apache.commons.codec.binary.Base64;\n\n/**\n *

\n * Identical to the Base64 encoding defined by RFC\n * 1521 and allows a character set to be specified.\n *

\n *\n *

\n * RFC 1522 describes techniques to allow the encoding of non-ASCII\n * text in various portions of a RFC 822 [2] message header, in a manner which is unlikely to confuse existing message\n * handling software.\n *

\n *\n * @see MIME (Multipurpose Internet Mail Extensions) Part Two: Message\n * Header Extensions for Non-ASCII Text\n *\n * @author Apache Software Foundation\n * @since 1.3\n * @version $Id: BCodec.java,v 1.5 2004/04/13 22:46:37 ggregory Exp $\n */\npublic class BCodec extends RFC1522Codec implements StringEncoder, StringDecoder {\n\n /**\n * The default charset used for string decoding and encoding.\n */\n private String charset = StringEncodings.UTF8;\n\n public BCodec() {\n super();\n }\n\n /**\n * Constructor which allows for the selection of a default charset\n *\n * @param charset\n * the default string charset to use.\n *\n * @see JRE character\n * encoding names\n */\n public BCodec(final String charset) {\n super();\n this.charset = charset;\n }\n\n protected String getEncoding() {\n return \"B\";\n }\n\n protected byte[] doEncoding(byte[] bytes) throws EncoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.encodeBase64(bytes);\n }\n\n protected byte[] doDecoding(byte[] bytes) throws DecoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.decodeBase64(bytes);\n }\n\n /**\n * Encodes a string into its Base64 form using the specified charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @param charset\n * the charset for pString\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(final String value, final String charset) throws EncoderException {", "post_mask_code": "\n try {\n return encodeText(value, charset);\n } catch (UnsupportedEncodingException e) {\n throw new EncoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes a string into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(String value) throws EncoderException {\n if (value == null) {\n return null;\n }\n return encode(value, getDefaultCharset());\n }\n\n /**\n * Decodes a Base64 string into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 string to convert into its original form\n *\n * @return original string\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public String decode(String value) throws DecoderException {\n if (value == null) {\n return null;\n }\n try {\n return decodeText(value);\n } catch (UnsupportedEncodingException e) {\n throw new DecoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes an object into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * object to convert to Base64 form\n * @return Base64 object\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public Object encode(Object value) throws EncoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return encode((String) value);\n } else {\n throw new EncoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be encoded using BCodec\");\n }\n }\n\n /**\n * Decodes a Base64 object into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 object to convert into its original form\n *\n * @return original object\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public Object decode(Object value) throws DecoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return decode((String) value);\n } else {\n throw new DecoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be decoded using BCodec\");\n }\n }\n\n /**\n * The default charset used for string decoding and encoding.\n *\n * @return the default string charset.\n */\n public String getDefaultCharset() {\n return this.charset;\n }\n}\n"} {"task_id": "Java_1152", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/robovm/robovm/rt/external/apache-http/src/org/apache/commons/codec/net/BCodec.java", "mask_start_position": 2719, "mask_end_position": 2888, "canonical_solution": "try {\n return encodeText(value, charset);\n } catch (UnsupportedEncodingException e) {\n throw new EncoderException(e.getMessage());\n }", "pre_mask_code": "package org.apache.commons.codec.net;\n\nimport java.io.UnsupportedEncodingException;\nimport org.apache.commons.codec.DecoderException;\nimport org.apache.commons.codec.EncoderException;\nimport org.apache.commons.codec.StringDecoder;\nimport org.apache.commons.codec.StringEncoder;\nimport org.apache.commons.codec.binary.Base64;\n\n/**\n *

\n * Identical to the Base64 encoding defined by RFC\n * 1521 and allows a character set to be specified.\n *

\n *\n *

\n * RFC 1522 describes techniques to allow the encoding of non-ASCII\n * text in various portions of a RFC 822 [2] message header, in a manner which is unlikely to confuse existing message\n * handling software.\n *

\n *\n * @see MIME (Multipurpose Internet Mail Extensions) Part Two: Message\n * Header Extensions for Non-ASCII Text\n *\n * @author Apache Software Foundation\n * @since 1.3\n * @version $Id: BCodec.java,v 1.5 2004/04/13 22:46:37 ggregory Exp $\n */\npublic class BCodec extends RFC1522Codec implements StringEncoder, StringDecoder {\n\n /**\n * The default charset used for string decoding and encoding.\n */\n private String charset = StringEncodings.UTF8;\n\n public BCodec() {\n super();\n }\n\n /**\n * Constructor which allows for the selection of a default charset\n *\n * @param charset\n * the default string charset to use.\n *\n * @see JRE character\n * encoding names\n */\n public BCodec(final String charset) {\n super();\n this.charset = charset;\n }\n\n protected String getEncoding() {\n return \"B\";\n }\n\n protected byte[] doEncoding(byte[] bytes) throws EncoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.encodeBase64(bytes);\n }\n\n protected byte[] doDecoding(byte[] bytes) throws DecoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.decodeBase64(bytes);\n }\n\n /**\n * Encodes a string into its Base64 form using the specified charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @param charset\n * the charset for pString\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(final String value, final String charset) throws EncoderException {\n if (value == null) {\n return null;\n }\n ", "post_mask_code": "\n }\n\n /**\n * Encodes a string into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(String value) throws EncoderException {\n if (value == null) {\n return null;\n }\n return encode(value, getDefaultCharset());\n }\n\n /**\n * Decodes a Base64 string into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 string to convert into its original form\n *\n * @return original string\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public String decode(String value) throws DecoderException {\n if (value == null) {\n return null;\n }\n try {\n return decodeText(value);\n } catch (UnsupportedEncodingException e) {\n throw new DecoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes an object into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * object to convert to Base64 form\n * @return Base64 object\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public Object encode(Object value) throws EncoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return encode((String) value);\n } else {\n throw new EncoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be encoded using BCodec\");\n }\n }\n\n /**\n * Decodes a Base64 object into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 object to convert into its original form\n *\n * @return original object\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public Object decode(Object value) throws DecoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return decode((String) value);\n } else {\n throw new DecoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be decoded using BCodec\");\n }\n }\n\n /**\n * The default charset used for string decoding and encoding.\n *\n * @return the default string charset.\n */\n public String getDefaultCharset() {\n return this.charset;\n }\n}\n"} {"task_id": "Java_1153", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/robovm/robovm/rt/external/apache-http/src/org/apache/commons/codec/net/BCodec.java", "mask_start_position": 2893, "mask_end_position": 2894, "canonical_solution": "}", "pre_mask_code": "package org.apache.commons.codec.net;\n\nimport java.io.UnsupportedEncodingException;\nimport org.apache.commons.codec.DecoderException;\nimport org.apache.commons.codec.EncoderException;\nimport org.apache.commons.codec.StringDecoder;\nimport org.apache.commons.codec.StringEncoder;\nimport org.apache.commons.codec.binary.Base64;\n\n/**\n *

\n * Identical to the Base64 encoding defined by RFC\n * 1521 and allows a character set to be specified.\n *

\n *\n *

\n * RFC 1522 describes techniques to allow the encoding of non-ASCII\n * text in various portions of a RFC 822 [2] message header, in a manner which is unlikely to confuse existing message\n * handling software.\n *

\n *\n * @see MIME (Multipurpose Internet Mail Extensions) Part Two: Message\n * Header Extensions for Non-ASCII Text\n *\n * @author Apache Software Foundation\n * @since 1.3\n * @version $Id: BCodec.java,v 1.5 2004/04/13 22:46:37 ggregory Exp $\n */\npublic class BCodec extends RFC1522Codec implements StringEncoder, StringDecoder {\n\n /**\n * The default charset used for string decoding and encoding.\n */\n private String charset = StringEncodings.UTF8;\n\n public BCodec() {\n super();\n }\n\n /**\n * Constructor which allows for the selection of a default charset\n *\n * @param charset\n * the default string charset to use.\n *\n * @see JRE character\n * encoding names\n */\n public BCodec(final String charset) {\n super();\n this.charset = charset;\n }\n\n protected String getEncoding() {\n return \"B\";\n }\n\n protected byte[] doEncoding(byte[] bytes) throws EncoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.encodeBase64(bytes);\n }\n\n protected byte[] doDecoding(byte[] bytes) throws DecoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.decodeBase64(bytes);\n }\n\n /**\n * Encodes a string into its Base64 form using the specified charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @param charset\n * the charset for pString\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(final String value, final String charset) throws EncoderException {\n if (value == null) {\n return null;\n }\n try {\n return encodeText(value, charset);\n } catch (UnsupportedEncodingException e) {\n throw new EncoderException(e.getMessage());\n }\n ", "post_mask_code": "\n\n /**\n * Encodes a string into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(String value) throws EncoderException {\n if (value == null) {\n return null;\n }\n return encode(value, getDefaultCharset());\n }\n\n /**\n * Decodes a Base64 string into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 string to convert into its original form\n *\n * @return original string\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public String decode(String value) throws DecoderException {\n if (value == null) {\n return null;\n }\n try {\n return decodeText(value);\n } catch (UnsupportedEncodingException e) {\n throw new DecoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes an object into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * object to convert to Base64 form\n * @return Base64 object\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public Object encode(Object value) throws EncoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return encode((String) value);\n } else {\n throw new EncoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be encoded using BCodec\");\n }\n }\n\n /**\n * Decodes a Base64 object into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 object to convert into its original form\n *\n * @return original object\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public Object decode(Object value) throws DecoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return decode((String) value);\n } else {\n throw new DecoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be decoded using BCodec\");\n }\n }\n\n /**\n * The default charset used for string decoding and encoding.\n *\n * @return the default string charset.\n */\n public String getDefaultCharset() {\n return this.charset;\n }\n}\n"} {"task_id": "Java_1154", "language": "Java", "task_type": "single_line", "source_file": "java/github/robovm/robovm/rt/external/apache-http/src/org/apache/commons/codec/net/BCodec.java", "mask_start_position": 3423, "mask_end_position": 3444, "canonical_solution": "getDefaultCharset());", "pre_mask_code": "package org.apache.commons.codec.net;\n\nimport java.io.UnsupportedEncodingException;\nimport org.apache.commons.codec.DecoderException;\nimport org.apache.commons.codec.EncoderException;\nimport org.apache.commons.codec.StringDecoder;\nimport org.apache.commons.codec.StringEncoder;\nimport org.apache.commons.codec.binary.Base64;\n\n/**\n *

\n * Identical to the Base64 encoding defined by RFC\n * 1521 and allows a character set to be specified.\n *

\n *\n *

\n * RFC 1522 describes techniques to allow the encoding of non-ASCII\n * text in various portions of a RFC 822 [2] message header, in a manner which is unlikely to confuse existing message\n * handling software.\n *

\n *\n * @see MIME (Multipurpose Internet Mail Extensions) Part Two: Message\n * Header Extensions for Non-ASCII Text\n *\n * @author Apache Software Foundation\n * @since 1.3\n * @version $Id: BCodec.java,v 1.5 2004/04/13 22:46:37 ggregory Exp $\n */\npublic class BCodec extends RFC1522Codec implements StringEncoder, StringDecoder {\n\n /**\n * The default charset used for string decoding and encoding.\n */\n private String charset = StringEncodings.UTF8;\n\n public BCodec() {\n super();\n }\n\n /**\n * Constructor which allows for the selection of a default charset\n *\n * @param charset\n * the default string charset to use.\n *\n * @see JRE character\n * encoding names\n */\n public BCodec(final String charset) {\n super();\n this.charset = charset;\n }\n\n protected String getEncoding() {\n return \"B\";\n }\n\n protected byte[] doEncoding(byte[] bytes) throws EncoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.encodeBase64(bytes);\n }\n\n protected byte[] doDecoding(byte[] bytes) throws DecoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.decodeBase64(bytes);\n }\n\n /**\n * Encodes a string into its Base64 form using the specified charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @param charset\n * the charset for pString\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(final String value, final String charset) throws EncoderException {\n if (value == null) {\n return null;\n }\n try {\n return encodeText(value, charset);\n } catch (UnsupportedEncodingException e) {\n throw new EncoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes a string into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(String value) throws EncoderException {\n if (value == null) {\n return null;\n }\n return encode(value, ", "post_mask_code": "\n }\n\n /**\n * Decodes a Base64 string into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 string to convert into its original form\n *\n * @return original string\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public String decode(String value) throws DecoderException {\n if (value == null) {\n return null;\n }\n try {\n return decodeText(value);\n } catch (UnsupportedEncodingException e) {\n throw new DecoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes an object into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * object to convert to Base64 form\n * @return Base64 object\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public Object encode(Object value) throws EncoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return encode((String) value);\n } else {\n throw new EncoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be encoded using BCodec\");\n }\n }\n\n /**\n * Decodes a Base64 object into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 object to convert into its original form\n *\n * @return original object\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public Object decode(Object value) throws DecoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return decode((String) value);\n } else {\n throw new DecoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be decoded using BCodec\");\n }\n }\n\n /**\n * The default charset used for string decoding and encoding.\n *\n * @return the default string charset.\n */\n public String getDefaultCharset() {\n return this.charset;\n }\n}\n"} {"task_id": "Java_1155", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/robovm/robovm/rt/external/apache-http/src/org/apache/commons/codec/net/BCodec.java", "mask_start_position": 5388, "mask_end_position": 5749, "canonical_solution": "public Object decode(Object value) throws DecoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return decode((String) value);\n } else {\n throw new DecoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be decoded using BCodec\");\n }\n }", "pre_mask_code": "package org.apache.commons.codec.net;\n\nimport java.io.UnsupportedEncodingException;\nimport org.apache.commons.codec.DecoderException;\nimport org.apache.commons.codec.EncoderException;\nimport org.apache.commons.codec.StringDecoder;\nimport org.apache.commons.codec.StringEncoder;\nimport org.apache.commons.codec.binary.Base64;\n\n/**\n *

\n * Identical to the Base64 encoding defined by RFC\n * 1521 and allows a character set to be specified.\n *

\n *\n *

\n * RFC 1522 describes techniques to allow the encoding of non-ASCII\n * text in various portions of a RFC 822 [2] message header, in a manner which is unlikely to confuse existing message\n * handling software.\n *

\n *\n * @see MIME (Multipurpose Internet Mail Extensions) Part Two: Message\n * Header Extensions for Non-ASCII Text\n *\n * @author Apache Software Foundation\n * @since 1.3\n * @version $Id: BCodec.java,v 1.5 2004/04/13 22:46:37 ggregory Exp $\n */\npublic class BCodec extends RFC1522Codec implements StringEncoder, StringDecoder {\n\n /**\n * The default charset used for string decoding and encoding.\n */\n private String charset = StringEncodings.UTF8;\n\n public BCodec() {\n super();\n }\n\n /**\n * Constructor which allows for the selection of a default charset\n *\n * @param charset\n * the default string charset to use.\n *\n * @see JRE character\n * encoding names\n */\n public BCodec(final String charset) {\n super();\n this.charset = charset;\n }\n\n protected String getEncoding() {\n return \"B\";\n }\n\n protected byte[] doEncoding(byte[] bytes) throws EncoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.encodeBase64(bytes);\n }\n\n protected byte[] doDecoding(byte[] bytes) throws DecoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.decodeBase64(bytes);\n }\n\n /**\n * Encodes a string into its Base64 form using the specified charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @param charset\n * the charset for pString\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(final String value, final String charset) throws EncoderException {\n if (value == null) {\n return null;\n }\n try {\n return encodeText(value, charset);\n } catch (UnsupportedEncodingException e) {\n throw new EncoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes a string into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(String value) throws EncoderException {\n if (value == null) {\n return null;\n }\n return encode(value, getDefaultCharset());\n }\n\n /**\n * Decodes a Base64 string into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 string to convert into its original form\n *\n * @return original string\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public String decode(String value) throws DecoderException {\n if (value == null) {\n return null;\n }\n try {\n return decodeText(value);\n } catch (UnsupportedEncodingException e) {\n throw new DecoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes an object into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * object to convert to Base64 form\n * @return Base64 object\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public Object encode(Object value) throws EncoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return encode((String) value);\n } else {\n throw new EncoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be encoded using BCodec\");\n }\n }\n\n /**\n * Decodes a Base64 object into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 object to convert into its original form\n *\n * @return original object\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n ", "post_mask_code": "\n\n /**\n * The default charset used for string decoding and encoding.\n *\n * @return the default string charset.\n */\n public String getDefaultCharset() {\n return this.charset;\n }\n}\n"} {"task_id": "Java_1156", "language": "Java", "task_type": "if_statement", "source_file": "java/github/robovm/robovm/rt/external/apache-http/src/org/apache/commons/codec/net/BCodec.java", "mask_start_position": 4645, "mask_end_position": 4931, "canonical_solution": "if (value == null) {\n return null;\n } else if (value instanceof String) {\n return encode((String) value);\n } else {\n throw new EncoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be encoded using BCodec\");\n }", "pre_mask_code": "package org.apache.commons.codec.net;\n\nimport java.io.UnsupportedEncodingException;\nimport org.apache.commons.codec.DecoderException;\nimport org.apache.commons.codec.EncoderException;\nimport org.apache.commons.codec.StringDecoder;\nimport org.apache.commons.codec.StringEncoder;\nimport org.apache.commons.codec.binary.Base64;\n\n/**\n *

\n * Identical to the Base64 encoding defined by RFC\n * 1521 and allows a character set to be specified.\n *

\n *\n *

\n * RFC 1522 describes techniques to allow the encoding of non-ASCII\n * text in various portions of a RFC 822 [2] message header, in a manner which is unlikely to confuse existing message\n * handling software.\n *

\n *\n * @see MIME (Multipurpose Internet Mail Extensions) Part Two: Message\n * Header Extensions for Non-ASCII Text\n *\n * @author Apache Software Foundation\n * @since 1.3\n * @version $Id: BCodec.java,v 1.5 2004/04/13 22:46:37 ggregory Exp $\n */\npublic class BCodec extends RFC1522Codec implements StringEncoder, StringDecoder {\n\n /**\n * The default charset used for string decoding and encoding.\n */\n private String charset = StringEncodings.UTF8;\n\n public BCodec() {\n super();\n }\n\n /**\n * Constructor which allows for the selection of a default charset\n *\n * @param charset\n * the default string charset to use.\n *\n * @see JRE character\n * encoding names\n */\n public BCodec(final String charset) {\n super();\n this.charset = charset;\n }\n\n protected String getEncoding() {\n return \"B\";\n }\n\n protected byte[] doEncoding(byte[] bytes) throws EncoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.encodeBase64(bytes);\n }\n\n protected byte[] doDecoding(byte[] bytes) throws DecoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.decodeBase64(bytes);\n }\n\n /**\n * Encodes a string into its Base64 form using the specified charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @param charset\n * the charset for pString\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(final String value, final String charset) throws EncoderException {\n if (value == null) {\n return null;\n }\n try {\n return encodeText(value, charset);\n } catch (UnsupportedEncodingException e) {\n throw new EncoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes a string into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(String value) throws EncoderException {\n if (value == null) {\n return null;\n }\n return encode(value, getDefaultCharset());\n }\n\n /**\n * Decodes a Base64 string into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 string to convert into its original form\n *\n * @return original string\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public String decode(String value) throws DecoderException {\n if (value == null) {\n return null;\n }\n try {\n return decodeText(value);\n } catch (UnsupportedEncodingException e) {\n throw new DecoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes an object into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * object to convert to Base64 form\n * @return Base64 object\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public Object encode(Object value) throws EncoderException {\n ", "post_mask_code": "\n }\n\n /**\n * Decodes a Base64 object into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 object to convert into its original form\n *\n * @return original object\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public Object decode(Object value) throws DecoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return decode((String) value);\n } else {\n throw new DecoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be decoded using BCodec\");\n }\n }\n\n /**\n * The default charset used for string decoding and encoding.\n *\n * @return the default string charset.\n */\n public String getDefaultCharset() {\n return this.charset;\n }\n}\n"} {"task_id": "Java_1157", "language": "Java", "task_type": "try_statement", "source_file": "java/github/robovm/robovm/rt/external/apache-http/src/org/apache/commons/codec/net/BCodec.java", "mask_start_position": 4034, "mask_end_position": 4194, "canonical_solution": "try {\n return decodeText(value);\n } catch (UnsupportedEncodingException e) {\n throw new DecoderException(e.getMessage());\n }", "pre_mask_code": "package org.apache.commons.codec.net;\n\nimport java.io.UnsupportedEncodingException;\nimport org.apache.commons.codec.DecoderException;\nimport org.apache.commons.codec.EncoderException;\nimport org.apache.commons.codec.StringDecoder;\nimport org.apache.commons.codec.StringEncoder;\nimport org.apache.commons.codec.binary.Base64;\n\n/**\n *

\n * Identical to the Base64 encoding defined by RFC\n * 1521 and allows a character set to be specified.\n *

\n *\n *

\n * RFC 1522 describes techniques to allow the encoding of non-ASCII\n * text in various portions of a RFC 822 [2] message header, in a manner which is unlikely to confuse existing message\n * handling software.\n *

\n *\n * @see MIME (Multipurpose Internet Mail Extensions) Part Two: Message\n * Header Extensions for Non-ASCII Text\n *\n * @author Apache Software Foundation\n * @since 1.3\n * @version $Id: BCodec.java,v 1.5 2004/04/13 22:46:37 ggregory Exp $\n */\npublic class BCodec extends RFC1522Codec implements StringEncoder, StringDecoder {\n\n /**\n * The default charset used for string decoding and encoding.\n */\n private String charset = StringEncodings.UTF8;\n\n public BCodec() {\n super();\n }\n\n /**\n * Constructor which allows for the selection of a default charset\n *\n * @param charset\n * the default string charset to use.\n *\n * @see JRE character\n * encoding names\n */\n public BCodec(final String charset) {\n super();\n this.charset = charset;\n }\n\n protected String getEncoding() {\n return \"B\";\n }\n\n protected byte[] doEncoding(byte[] bytes) throws EncoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.encodeBase64(bytes);\n }\n\n protected byte[] doDecoding(byte[] bytes) throws DecoderException {\n if (bytes == null) {\n return null;\n }\n return Base64.decodeBase64(bytes);\n }\n\n /**\n * Encodes a string into its Base64 form using the specified charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @param charset\n * the charset for pString\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(final String value, final String charset) throws EncoderException {\n if (value == null) {\n return null;\n }\n try {\n return encodeText(value, charset);\n } catch (UnsupportedEncodingException e) {\n throw new EncoderException(e.getMessage());\n }\n }\n\n /**\n * Encodes a string into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * string to convert to Base64 form\n * @return Base64 string\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public String encode(String value) throws EncoderException {\n if (value == null) {\n return null;\n }\n return encode(value, getDefaultCharset());\n }\n\n /**\n * Decodes a Base64 string into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 string to convert into its original form\n *\n * @return original string\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public String decode(String value) throws DecoderException {\n if (value == null) {\n return null;\n }\n ", "post_mask_code": "\n }\n\n /**\n * Encodes an object into its Base64 form using the default charset. Unsafe characters are escaped.\n *\n * @param value\n * object to convert to Base64 form\n * @return Base64 object\n *\n * @throws EncoderException\n * thrown if a failure condition is encountered during the encoding process.\n */\n public Object encode(Object value) throws EncoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return encode((String) value);\n } else {\n throw new EncoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be encoded using BCodec\");\n }\n }\n\n /**\n * Decodes a Base64 object into its original form. Escaped characters are converted back to their original\n * representation.\n *\n * @param value\n * Base64 object to convert into its original form\n *\n * @return original object\n *\n * @throws DecoderException\n * A decoder exception is thrown if a failure condition is encountered during the decode process.\n */\n public Object decode(Object value) throws DecoderException {\n if (value == null) {\n return null;\n } else if (value instanceof String) {\n return decode((String) value);\n } else {\n throw new DecoderException(\"Objects of type \" + value.getClass().getName() + \" cannot be decoded using BCodec\");\n }\n }\n\n /**\n * The default charset used for string decoding and encoding.\n *\n * @return the default string charset.\n */\n public String getDefaultCharset() {\n return this.charset;\n }\n}\n"} {"task_id": "Java_1158", "language": "Java", "task_type": "method_signature", "source_file": "java/github/kubernetes-client/java/fluent/src/main/java/io/kubernetes/client/openapi/models/V2beta2MetricValueStatusFluentImpl.java", "mask_start_position": 1140, "mask_end_position": 1210, "canonical_solution": "public A withAverageUtilization(java.lang.Integer averageUtilization) ", "pre_mask_code": "package io.kubernetes.client.openapi.models;\n\nimport java.lang.Integer;\nimport io.kubernetes.client.fluent.BaseFluent;\nimport io.kubernetes.client.custom.Quantity;\nimport java.lang.Object;\nimport java.lang.String;\nimport java.lang.Boolean;\n\npublic class V2beta2MetricValueStatusFluentImpl> extends io.kubernetes.client.fluent.BaseFluent implements io.kubernetes.client.openapi.models.V2beta2MetricValueStatusFluent {\n\n public V2beta2MetricValueStatusFluentImpl() {\n }\n\n public V2beta2MetricValueStatusFluentImpl(io.kubernetes.client.openapi.models.V2beta2MetricValueStatus instance) {\n this.withAverageUtilization(instance.getAverageUtilization());\n this.withAverageValue(instance.getAverageValue());\n this.withValue(instance.getValue());\n }\n\n private java.lang.Integer averageUtilization;\n\n private io.kubernetes.client.custom.Quantity averageValue;\n\n private io.kubernetes.client.custom.Quantity value;\n\n public java.lang.Integer getAverageUtilization() {\n return this.averageUtilization;\n }\n\n ", "post_mask_code": "{\n this.averageUtilization = averageUtilization;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageUtilization() {\n return this.averageUtilization != null;\n }\n\n public io.kubernetes.client.custom.Quantity getAverageValue() {\n return this.averageValue;\n }\n\n public A withAverageValue(io.kubernetes.client.custom.Quantity averageValue) {\n this.averageValue = averageValue;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageValue() {\n return this.averageValue != null;\n }\n\n public A withNewAverageValue(java.lang.String value) {\n return (A) withAverageValue(new Quantity(value));\n }\n\n public io.kubernetes.client.custom.Quantity getValue() {\n return this.value;\n }\n\n public A withValue(io.kubernetes.client.custom.Quantity value) {\n this.value = value;\n return (A) this;\n }\n\n public java.lang.Boolean hasValue() {\n return this.value != null;\n }\n\n public A withNewValue(java.lang.String value) {\n return (A) withValue(new Quantity(value));\n }\n\n public boolean equals(java.lang.Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n V2beta2MetricValueStatusFluentImpl that = (V2beta2MetricValueStatusFluentImpl) o;\n if (averageUtilization != null ? !averageUtilization.equals(that.averageUtilization) : that.averageUtilization != null)\n return false;\n if (averageValue != null ? !averageValue.equals(that.averageValue) : that.averageValue != null)\n return false;\n if (value != null ? !value.equals(that.value) : that.value != null)\n return false;\n return true;\n }\n\n public int hashCode() {\n return java.util.Objects.hash(averageUtilization, averageValue, value, super.hashCode());\n }\n}\n"} {"task_id": "Java_1159", "language": "Java", "task_type": "method_body", "source_file": "java/github/kubernetes-client/java/fluent/src/main/java/io/kubernetes/client/openapi/models/V2beta2MetricValueStatusFluentImpl.java", "mask_start_position": 1955, "mask_end_position": 1989, "canonical_solution": "{\n return this.value;\n }", "pre_mask_code": "package io.kubernetes.client.openapi.models;\n\nimport java.lang.Integer;\nimport io.kubernetes.client.fluent.BaseFluent;\nimport io.kubernetes.client.custom.Quantity;\nimport java.lang.Object;\nimport java.lang.String;\nimport java.lang.Boolean;\n\npublic class V2beta2MetricValueStatusFluentImpl> extends io.kubernetes.client.fluent.BaseFluent implements io.kubernetes.client.openapi.models.V2beta2MetricValueStatusFluent {\n\n public V2beta2MetricValueStatusFluentImpl() {\n }\n\n public V2beta2MetricValueStatusFluentImpl(io.kubernetes.client.openapi.models.V2beta2MetricValueStatus instance) {\n this.withAverageUtilization(instance.getAverageUtilization());\n this.withAverageValue(instance.getAverageValue());\n this.withValue(instance.getValue());\n }\n\n private java.lang.Integer averageUtilization;\n\n private io.kubernetes.client.custom.Quantity averageValue;\n\n private io.kubernetes.client.custom.Quantity value;\n\n public java.lang.Integer getAverageUtilization() {\n return this.averageUtilization;\n }\n\n public A withAverageUtilization(java.lang.Integer averageUtilization) {\n this.averageUtilization = averageUtilization;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageUtilization() {\n return this.averageUtilization != null;\n }\n\n public io.kubernetes.client.custom.Quantity getAverageValue() {\n return this.averageValue;\n }\n\n public A withAverageValue(io.kubernetes.client.custom.Quantity averageValue) {\n this.averageValue = averageValue;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageValue() {\n return this.averageValue != null;\n }\n\n public A withNewAverageValue(java.lang.String value) {\n return (A) withAverageValue(new Quantity(value));\n }\n\n public io.kubernetes.client.custom.Quantity getValue() ", "post_mask_code": "\n\n public A withValue(io.kubernetes.client.custom.Quantity value) {\n this.value = value;\n return (A) this;\n }\n\n public java.lang.Boolean hasValue() {\n return this.value != null;\n }\n\n public A withNewValue(java.lang.String value) {\n return (A) withValue(new Quantity(value));\n }\n\n public boolean equals(java.lang.Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n V2beta2MetricValueStatusFluentImpl that = (V2beta2MetricValueStatusFluentImpl) o;\n if (averageUtilization != null ? !averageUtilization.equals(that.averageUtilization) : that.averageUtilization != null)\n return false;\n if (averageValue != null ? !averageValue.equals(that.averageValue) : that.averageValue != null)\n return false;\n if (value != null ? !value.equals(that.value) : that.value != null)\n return false;\n return true;\n }\n\n public int hashCode() {\n return java.util.Objects.hash(averageUtilization, averageValue, value, super.hashCode());\n }\n}\n"} {"task_id": "Java_1160", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/kubernetes-client/java/fluent/src/main/java/io/kubernetes/client/openapi/models/V2beta2MetricValueStatusFluentImpl.java", "mask_start_position": 2361, "mask_end_position": 2488, "canonical_solution": "\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;", "pre_mask_code": "package io.kubernetes.client.openapi.models;\n\nimport java.lang.Integer;\nimport io.kubernetes.client.fluent.BaseFluent;\nimport io.kubernetes.client.custom.Quantity;\nimport java.lang.Object;\nimport java.lang.String;\nimport java.lang.Boolean;\n\npublic class V2beta2MetricValueStatusFluentImpl> extends io.kubernetes.client.fluent.BaseFluent implements io.kubernetes.client.openapi.models.V2beta2MetricValueStatusFluent {\n\n public V2beta2MetricValueStatusFluentImpl() {\n }\n\n public V2beta2MetricValueStatusFluentImpl(io.kubernetes.client.openapi.models.V2beta2MetricValueStatus instance) {\n this.withAverageUtilization(instance.getAverageUtilization());\n this.withAverageValue(instance.getAverageValue());\n this.withValue(instance.getValue());\n }\n\n private java.lang.Integer averageUtilization;\n\n private io.kubernetes.client.custom.Quantity averageValue;\n\n private io.kubernetes.client.custom.Quantity value;\n\n public java.lang.Integer getAverageUtilization() {\n return this.averageUtilization;\n }\n\n public A withAverageUtilization(java.lang.Integer averageUtilization) {\n this.averageUtilization = averageUtilization;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageUtilization() {\n return this.averageUtilization != null;\n }\n\n public io.kubernetes.client.custom.Quantity getAverageValue() {\n return this.averageValue;\n }\n\n public A withAverageValue(io.kubernetes.client.custom.Quantity averageValue) {\n this.averageValue = averageValue;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageValue() {\n return this.averageValue != null;\n }\n\n public A withNewAverageValue(java.lang.String value) {\n return (A) withAverageValue(new Quantity(value));\n }\n\n public io.kubernetes.client.custom.Quantity getValue() {\n return this.value;\n }\n\n public A withValue(io.kubernetes.client.custom.Quantity value) {\n this.value = value;\n return (A) this;\n }\n\n public java.lang.Boolean hasValue() {\n return this.value != null;\n }\n\n public A withNewValue(java.lang.String value) {\n return (A) withValue(new Quantity(value));\n }\n\n public boolean equals(java.lang.Object o) {", "post_mask_code": "\n V2beta2MetricValueStatusFluentImpl that = (V2beta2MetricValueStatusFluentImpl) o;\n if (averageUtilization != null ? !averageUtilization.equals(that.averageUtilization) : that.averageUtilization != null)\n return false;\n if (averageValue != null ? !averageValue.equals(that.averageValue) : that.averageValue != null)\n return false;\n if (value != null ? !value.equals(that.value) : that.value != null)\n return false;\n return true;\n }\n\n public int hashCode() {\n return java.util.Objects.hash(averageUtilization, averageValue, value, super.hashCode());\n }\n}\n"} {"task_id": "Java_1161", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/kubernetes-client/java/fluent/src/main/java/io/kubernetes/client/openapi/models/V2beta2MetricValueStatusFluentImpl.java", "mask_start_position": 2497, "mask_end_position": 2862, "canonical_solution": "V2beta2MetricValueStatusFluentImpl that = (V2beta2MetricValueStatusFluentImpl) o;\n if (averageUtilization != null ? !averageUtilization.equals(that.averageUtilization) : that.averageUtilization != null)\n return false;\n if (averageValue != null ? !averageValue.equals(that.averageValue) : that.averageValue != null)\n return false;", "pre_mask_code": "package io.kubernetes.client.openapi.models;\n\nimport java.lang.Integer;\nimport io.kubernetes.client.fluent.BaseFluent;\nimport io.kubernetes.client.custom.Quantity;\nimport java.lang.Object;\nimport java.lang.String;\nimport java.lang.Boolean;\n\npublic class V2beta2MetricValueStatusFluentImpl> extends io.kubernetes.client.fluent.BaseFluent implements io.kubernetes.client.openapi.models.V2beta2MetricValueStatusFluent {\n\n public V2beta2MetricValueStatusFluentImpl() {\n }\n\n public V2beta2MetricValueStatusFluentImpl(io.kubernetes.client.openapi.models.V2beta2MetricValueStatus instance) {\n this.withAverageUtilization(instance.getAverageUtilization());\n this.withAverageValue(instance.getAverageValue());\n this.withValue(instance.getValue());\n }\n\n private java.lang.Integer averageUtilization;\n\n private io.kubernetes.client.custom.Quantity averageValue;\n\n private io.kubernetes.client.custom.Quantity value;\n\n public java.lang.Integer getAverageUtilization() {\n return this.averageUtilization;\n }\n\n public A withAverageUtilization(java.lang.Integer averageUtilization) {\n this.averageUtilization = averageUtilization;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageUtilization() {\n return this.averageUtilization != null;\n }\n\n public io.kubernetes.client.custom.Quantity getAverageValue() {\n return this.averageValue;\n }\n\n public A withAverageValue(io.kubernetes.client.custom.Quantity averageValue) {\n this.averageValue = averageValue;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageValue() {\n return this.averageValue != null;\n }\n\n public A withNewAverageValue(java.lang.String value) {\n return (A) withAverageValue(new Quantity(value));\n }\n\n public io.kubernetes.client.custom.Quantity getValue() {\n return this.value;\n }\n\n public A withValue(io.kubernetes.client.custom.Quantity value) {\n this.value = value;\n return (A) this;\n }\n\n public java.lang.Boolean hasValue() {\n return this.value != null;\n }\n\n public A withNewValue(java.lang.String value) {\n return (A) withValue(new Quantity(value));\n }\n\n public boolean equals(java.lang.Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ", "post_mask_code": "\n if (value != null ? !value.equals(that.value) : that.value != null)\n return false;\n return true;\n }\n\n public int hashCode() {\n return java.util.Objects.hash(averageUtilization, averageValue, value, super.hashCode());\n }\n}\n"} {"task_id": "Java_1162", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/kubernetes-client/java/fluent/src/main/java/io/kubernetes/client/openapi/models/V2beta2MetricValueStatusFluentImpl.java", "mask_start_position": 2871, "mask_end_position": 2991, "canonical_solution": "if (value != null ? !value.equals(that.value) : that.value != null)\n return false;\n return true;\n }", "pre_mask_code": "package io.kubernetes.client.openapi.models;\n\nimport java.lang.Integer;\nimport io.kubernetes.client.fluent.BaseFluent;\nimport io.kubernetes.client.custom.Quantity;\nimport java.lang.Object;\nimport java.lang.String;\nimport java.lang.Boolean;\n\npublic class V2beta2MetricValueStatusFluentImpl> extends io.kubernetes.client.fluent.BaseFluent implements io.kubernetes.client.openapi.models.V2beta2MetricValueStatusFluent {\n\n public V2beta2MetricValueStatusFluentImpl() {\n }\n\n public V2beta2MetricValueStatusFluentImpl(io.kubernetes.client.openapi.models.V2beta2MetricValueStatus instance) {\n this.withAverageUtilization(instance.getAverageUtilization());\n this.withAverageValue(instance.getAverageValue());\n this.withValue(instance.getValue());\n }\n\n private java.lang.Integer averageUtilization;\n\n private io.kubernetes.client.custom.Quantity averageValue;\n\n private io.kubernetes.client.custom.Quantity value;\n\n public java.lang.Integer getAverageUtilization() {\n return this.averageUtilization;\n }\n\n public A withAverageUtilization(java.lang.Integer averageUtilization) {\n this.averageUtilization = averageUtilization;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageUtilization() {\n return this.averageUtilization != null;\n }\n\n public io.kubernetes.client.custom.Quantity getAverageValue() {\n return this.averageValue;\n }\n\n public A withAverageValue(io.kubernetes.client.custom.Quantity averageValue) {\n this.averageValue = averageValue;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageValue() {\n return this.averageValue != null;\n }\n\n public A withNewAverageValue(java.lang.String value) {\n return (A) withAverageValue(new Quantity(value));\n }\n\n public io.kubernetes.client.custom.Quantity getValue() {\n return this.value;\n }\n\n public A withValue(io.kubernetes.client.custom.Quantity value) {\n this.value = value;\n return (A) this;\n }\n\n public java.lang.Boolean hasValue() {\n return this.value != null;\n }\n\n public A withNewValue(java.lang.String value) {\n return (A) withValue(new Quantity(value));\n }\n\n public boolean equals(java.lang.Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n V2beta2MetricValueStatusFluentImpl that = (V2beta2MetricValueStatusFluentImpl) o;\n if (averageUtilization != null ? !averageUtilization.equals(that.averageUtilization) : that.averageUtilization != null)\n return false;\n if (averageValue != null ? !averageValue.equals(that.averageValue) : that.averageValue != null)\n return false;\n ", "post_mask_code": "\n\n public int hashCode() {\n return java.util.Objects.hash(averageUtilization, averageValue, value, super.hashCode());\n }\n}\n"} {"task_id": "Java_1163", "language": "Java", "task_type": "single_line", "source_file": "java/github/kubernetes-client/java/fluent/src/main/java/io/kubernetes/client/openapi/models/V2beta2MetricValueStatusFluentImpl.java", "mask_start_position": 1980, "mask_end_position": 1983, "canonical_solution": "ue;", "pre_mask_code": "package io.kubernetes.client.openapi.models;\n\nimport java.lang.Integer;\nimport io.kubernetes.client.fluent.BaseFluent;\nimport io.kubernetes.client.custom.Quantity;\nimport java.lang.Object;\nimport java.lang.String;\nimport java.lang.Boolean;\n\npublic class V2beta2MetricValueStatusFluentImpl> extends io.kubernetes.client.fluent.BaseFluent implements io.kubernetes.client.openapi.models.V2beta2MetricValueStatusFluent {\n\n public V2beta2MetricValueStatusFluentImpl() {\n }\n\n public V2beta2MetricValueStatusFluentImpl(io.kubernetes.client.openapi.models.V2beta2MetricValueStatus instance) {\n this.withAverageUtilization(instance.getAverageUtilization());\n this.withAverageValue(instance.getAverageValue());\n this.withValue(instance.getValue());\n }\n\n private java.lang.Integer averageUtilization;\n\n private io.kubernetes.client.custom.Quantity averageValue;\n\n private io.kubernetes.client.custom.Quantity value;\n\n public java.lang.Integer getAverageUtilization() {\n return this.averageUtilization;\n }\n\n public A withAverageUtilization(java.lang.Integer averageUtilization) {\n this.averageUtilization = averageUtilization;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageUtilization() {\n return this.averageUtilization != null;\n }\n\n public io.kubernetes.client.custom.Quantity getAverageValue() {\n return this.averageValue;\n }\n\n public A withAverageValue(io.kubernetes.client.custom.Quantity averageValue) {\n this.averageValue = averageValue;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageValue() {\n return this.averageValue != null;\n }\n\n public A withNewAverageValue(java.lang.String value) {\n return (A) withAverageValue(new Quantity(value));\n }\n\n public io.kubernetes.client.custom.Quantity getValue() {\n return this.val", "post_mask_code": "\n }\n\n public A withValue(io.kubernetes.client.custom.Quantity value) {\n this.value = value;\n return (A) this;\n }\n\n public java.lang.Boolean hasValue() {\n return this.value != null;\n }\n\n public A withNewValue(java.lang.String value) {\n return (A) withValue(new Quantity(value));\n }\n\n public boolean equals(java.lang.Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n V2beta2MetricValueStatusFluentImpl that = (V2beta2MetricValueStatusFluentImpl) o;\n if (averageUtilization != null ? !averageUtilization.equals(that.averageUtilization) : that.averageUtilization != null)\n return false;\n if (averageValue != null ? !averageValue.equals(that.averageValue) : that.averageValue != null)\n return false;\n if (value != null ? !value.equals(that.value) : that.value != null)\n return false;\n return true;\n }\n\n public int hashCode() {\n return java.util.Objects.hash(averageUtilization, averageValue, value, super.hashCode());\n }\n}\n"} {"task_id": "Java_1164", "language": "Java", "task_type": "if_statement", "source_file": "java/github/kubernetes-client/java/fluent/src/main/java/io/kubernetes/client/openapi/models/V2beta2MetricValueStatusFluentImpl.java", "mask_start_position": 2871, "mask_end_position": 2964, "canonical_solution": "if (value != null ? !value.equals(that.value) : that.value != null)\n return false;", "pre_mask_code": "package io.kubernetes.client.openapi.models;\n\nimport java.lang.Integer;\nimport io.kubernetes.client.fluent.BaseFluent;\nimport io.kubernetes.client.custom.Quantity;\nimport java.lang.Object;\nimport java.lang.String;\nimport java.lang.Boolean;\n\npublic class V2beta2MetricValueStatusFluentImpl> extends io.kubernetes.client.fluent.BaseFluent implements io.kubernetes.client.openapi.models.V2beta2MetricValueStatusFluent {\n\n public V2beta2MetricValueStatusFluentImpl() {\n }\n\n public V2beta2MetricValueStatusFluentImpl(io.kubernetes.client.openapi.models.V2beta2MetricValueStatus instance) {\n this.withAverageUtilization(instance.getAverageUtilization());\n this.withAverageValue(instance.getAverageValue());\n this.withValue(instance.getValue());\n }\n\n private java.lang.Integer averageUtilization;\n\n private io.kubernetes.client.custom.Quantity averageValue;\n\n private io.kubernetes.client.custom.Quantity value;\n\n public java.lang.Integer getAverageUtilization() {\n return this.averageUtilization;\n }\n\n public A withAverageUtilization(java.lang.Integer averageUtilization) {\n this.averageUtilization = averageUtilization;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageUtilization() {\n return this.averageUtilization != null;\n }\n\n public io.kubernetes.client.custom.Quantity getAverageValue() {\n return this.averageValue;\n }\n\n public A withAverageValue(io.kubernetes.client.custom.Quantity averageValue) {\n this.averageValue = averageValue;\n return (A) this;\n }\n\n public java.lang.Boolean hasAverageValue() {\n return this.averageValue != null;\n }\n\n public A withNewAverageValue(java.lang.String value) {\n return (A) withAverageValue(new Quantity(value));\n }\n\n public io.kubernetes.client.custom.Quantity getValue() {\n return this.value;\n }\n\n public A withValue(io.kubernetes.client.custom.Quantity value) {\n this.value = value;\n return (A) this;\n }\n\n public java.lang.Boolean hasValue() {\n return this.value != null;\n }\n\n public A withNewValue(java.lang.String value) {\n return (A) withValue(new Quantity(value));\n }\n\n public boolean equals(java.lang.Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n V2beta2MetricValueStatusFluentImpl that = (V2beta2MetricValueStatusFluentImpl) o;\n if (averageUtilization != null ? !averageUtilization.equals(that.averageUtilization) : that.averageUtilization != null)\n return false;\n if (averageValue != null ? !averageValue.equals(that.averageValue) : that.averageValue != null)\n return false;\n ", "post_mask_code": "\n return true;\n }\n\n public int hashCode() {\n return java.util.Objects.hash(averageUtilization, averageValue, value, super.hashCode());\n }\n}\n"} {"task_id": "Java_1165", "language": "Java", "task_type": "method_signature", "source_file": "java/github/schrum2/MM-NEAT/src/main/java/edu/southwestern/tasks/mspacman/sensors/directional/distance/farthest/VariableDirectionFarthestIncomingEdibleGhostDistanceBlock.java", "mask_start_position": 595, "mask_end_position": 648, "canonical_solution": "@Override\n public int[] getTargets(GameFacade gf) ", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage edu.southwestern.tasks.mspacman.sensors.directional.distance.farthest;\n\nimport edu.southwestern.tasks.mspacman.facades.GameFacade;\n\n/**\n * @author Jacob Schrum\n */\npublic class VariableDirectionFarthestIncomingEdibleGhostDistanceBlock extends VariableDirectionFarthestDistanceBlock {\n\n public VariableDirectionFarthestIncomingEdibleGhostDistanceBlock(int dir) {\n super(dir);\n }\n\n @Override\n public String getType() {\n return \"Incoming Edible Ghost\";\n }\n\n ", "post_mask_code": "{\n return gf.getIncomingEdibleGhostLocations(dir);\n }\n}\n"} {"task_id": "Java_1166", "language": "Java", "task_type": "method_body", "source_file": "java/github/schrum2/MM-NEAT/src/main/java/edu/southwestern/tasks/mspacman/sensors/directional/distance/farthest/VariableDirectionFarthestIncomingEdibleGhostDistanceBlock.java", "mask_start_position": 648, "mask_end_position": 711, "canonical_solution": "{\n return gf.getIncomingEdibleGhostLocations(dir);\n }", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage edu.southwestern.tasks.mspacman.sensors.directional.distance.farthest;\n\nimport edu.southwestern.tasks.mspacman.facades.GameFacade;\n\n/**\n * @author Jacob Schrum\n */\npublic class VariableDirectionFarthestIncomingEdibleGhostDistanceBlock extends VariableDirectionFarthestDistanceBlock {\n\n public VariableDirectionFarthestIncomingEdibleGhostDistanceBlock(int dir) {\n super(dir);\n }\n\n @Override\n public String getType() {\n return \"Incoming Edible Ghost\";\n }\n\n @Override\n public int[] getTargets(GameFacade gf) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1167", "language": "Java", "task_type": "single_line", "source_file": "java/github/schrum2/MM-NEAT/src/main/java/edu/southwestern/tasks/mspacman/sensors/directional/distance/farthest/VariableDirectionFarthestIncomingEdibleGhostDistanceBlock.java", "mask_start_position": 555, "mask_end_position": 583, "canonical_solution": "urn \"Incoming Edible Ghost\";", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage edu.southwestern.tasks.mspacman.sensors.directional.distance.farthest;\n\nimport edu.southwestern.tasks.mspacman.facades.GameFacade;\n\n/**\n * @author Jacob Schrum\n */\npublic class VariableDirectionFarthestIncomingEdibleGhostDistanceBlock extends VariableDirectionFarthestDistanceBlock {\n\n public VariableDirectionFarthestIncomingEdibleGhostDistanceBlock(int dir) {\n super(dir);\n }\n\n @Override\n public String getType() {\n ret", "post_mask_code": "\n }\n\n @Override\n public int[] getTargets(GameFacade gf) {\n return gf.getIncomingEdibleGhostLocations(dir);\n }\n}\n"} {"task_id": "Java_1168", "language": "Java", "task_type": "method_signature", "source_file": "java/github/javayhu/TinyWeibo/weibo4j-oauth2/examples/weibo4j/examples/comment/GetCommentByMe.java", "mask_start_position": 235, "mask_end_position": 274, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "package weibo4j.examples.comment;\n\nimport weibo4j.Comments;\nimport weibo4j.examples.oauth2.Log;\nimport weibo4j.model.Comment;\nimport weibo4j.model.CommentWapper;\nimport weibo4j.model.WeiboException;\n\npublic class GetCommentByMe {\n\n ", "post_mask_code": "{\n String access_token = args[0];\n Comments cm = new Comments();\n cm.client.setToken(access_token);\n try {\n CommentWapper comment = cm.getCommentByMe();\n for (Comment c : comment.getComments()) {\n Log.logInfo(c.toString());\n }\n System.out.println(comment.getNextCursor());\n System.out.println(comment.getPreviousCursor());\n System.out.println(comment.getTotalNumber());\n System.out.println(comment.getHasvisible());\n } catch (WeiboException e) {\n e.printStackTrace();\n }\n }\n}\n"} {"task_id": "Java_1169", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/javayhu/TinyWeibo/weibo4j-oauth2/examples/weibo4j/examples/comment/GetCommentByMe.java", "mask_start_position": 275, "mask_end_position": 314, "canonical_solution": "\n String access_token = args[0];", "pre_mask_code": "package weibo4j.examples.comment;\n\nimport weibo4j.Comments;\nimport weibo4j.examples.oauth2.Log;\nimport weibo4j.model.Comment;\nimport weibo4j.model.CommentWapper;\nimport weibo4j.model.WeiboException;\n\npublic class GetCommentByMe {\n\n public static void main(String[] args) {", "post_mask_code": "\n Comments cm = new Comments();\n cm.client.setToken(access_token);\n try {\n CommentWapper comment = cm.getCommentByMe();\n for (Comment c : comment.getComments()) {\n Log.logInfo(c.toString());\n }\n System.out.println(comment.getNextCursor());\n System.out.println(comment.getPreviousCursor());\n System.out.println(comment.getTotalNumber());\n System.out.println(comment.getHasvisible());\n } catch (WeiboException e) {\n e.printStackTrace();\n }\n }\n}\n"} {"task_id": "Java_1170", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/javayhu/TinyWeibo/weibo4j-oauth2/examples/weibo4j/examples/comment/GetCommentByMe.java", "mask_start_position": 323, "mask_end_position": 394, "canonical_solution": "Comments cm = new Comments();\n cm.client.setToken(access_token);", "pre_mask_code": "package weibo4j.examples.comment;\n\nimport weibo4j.Comments;\nimport weibo4j.examples.oauth2.Log;\nimport weibo4j.model.Comment;\nimport weibo4j.model.CommentWapper;\nimport weibo4j.model.WeiboException;\n\npublic class GetCommentByMe {\n\n public static void main(String[] args) {\n String access_token = args[0];\n ", "post_mask_code": "\n try {\n CommentWapper comment = cm.getCommentByMe();\n for (Comment c : comment.getComments()) {\n Log.logInfo(c.toString());\n }\n System.out.println(comment.getNextCursor());\n System.out.println(comment.getPreviousCursor());\n System.out.println(comment.getTotalNumber());\n System.out.println(comment.getHasvisible());\n } catch (WeiboException e) {\n e.printStackTrace();\n }\n }\n}\n"} {"task_id": "Java_1171", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/javayhu/TinyWeibo/weibo4j-oauth2/examples/weibo4j/examples/comment/GetCommentByMe.java", "mask_start_position": 403, "mask_end_position": 895, "canonical_solution": "try {\n CommentWapper comment = cm.getCommentByMe();\n for (Comment c : comment.getComments()) {\n Log.logInfo(c.toString());\n }\n System.out.println(comment.getNextCursor());\n System.out.println(comment.getPreviousCursor());\n System.out.println(comment.getTotalNumber());\n System.out.println(comment.getHasvisible());\n } catch (WeiboException e) {\n e.printStackTrace();\n }\n }", "pre_mask_code": "package weibo4j.examples.comment;\n\nimport weibo4j.Comments;\nimport weibo4j.examples.oauth2.Log;\nimport weibo4j.model.Comment;\nimport weibo4j.model.CommentWapper;\nimport weibo4j.model.WeiboException;\n\npublic class GetCommentByMe {\n\n public static void main(String[] args) {\n String access_token = args[0];\n Comments cm = new Comments();\n cm.client.setToken(access_token);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1172", "language": "Java", "task_type": "single_line", "source_file": "java/github/javayhu/TinyWeibo/weibo4j-oauth2/examples/weibo4j/examples/comment/GetCommentByMe.java", "mask_start_position": 336, "mask_end_position": 352, "canonical_solution": " new Comments();", "pre_mask_code": "package weibo4j.examples.comment;\n\nimport weibo4j.Comments;\nimport weibo4j.examples.oauth2.Log;\nimport weibo4j.model.Comment;\nimport weibo4j.model.CommentWapper;\nimport weibo4j.model.WeiboException;\n\npublic class GetCommentByMe {\n\n public static void main(String[] args) {\n String access_token = args[0];\n Comments cm =", "post_mask_code": "\n cm.client.setToken(access_token);\n try {\n CommentWapper comment = cm.getCommentByMe();\n for (Comment c : comment.getComments()) {\n Log.logInfo(c.toString());\n }\n System.out.println(comment.getNextCursor());\n System.out.println(comment.getPreviousCursor());\n System.out.println(comment.getTotalNumber());\n System.out.println(comment.getHasvisible());\n } catch (WeiboException e) {\n e.printStackTrace();\n }\n }\n}\n"} {"task_id": "Java_1173", "language": "Java", "task_type": "try_statement", "source_file": "java/github/javayhu/TinyWeibo/weibo4j-oauth2/examples/weibo4j/examples/comment/GetCommentByMe.java", "mask_start_position": 403, "mask_end_position": 889, "canonical_solution": "try {\n CommentWapper comment = cm.getCommentByMe();\n for (Comment c : comment.getComments()) {\n Log.logInfo(c.toString());\n }\n System.out.println(comment.getNextCursor());\n System.out.println(comment.getPreviousCursor());\n System.out.println(comment.getTotalNumber());\n System.out.println(comment.getHasvisible());\n } catch (WeiboException e) {\n e.printStackTrace();\n }", "pre_mask_code": "package weibo4j.examples.comment;\n\nimport weibo4j.Comments;\nimport weibo4j.examples.oauth2.Log;\nimport weibo4j.model.Comment;\nimport weibo4j.model.CommentWapper;\nimport weibo4j.model.WeiboException;\n\npublic class GetCommentByMe {\n\n public static void main(String[] args) {\n String access_token = args[0];\n Comments cm = new Comments();\n cm.client.setToken(access_token);\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1174", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse/jnosql/communication/communication-column/src/main/java/org/eclipse/jnosql/communication/column/DefaultColumn.java", "mask_start_position": 508, "mask_end_position": 532, "canonical_solution": "public String getName() ", "pre_mask_code": "package org.eclipse.jnosql.communication.column;\n\nimport jakarta.nosql.TypeSupplier;\nimport jakarta.nosql.Value;\nimport jakarta.nosql.column.Column;\nimport org.eclipse.jnosql.communication.Entry;\nimport java.util.Objects;\n\n/**\n * The default implementation of {@link Column}\n */\nfinal class DefaultColumn implements Column, Entry {\n\n private final String name;\n\n private final Value value;\n\n DefaultColumn(String name, Value value) {\n this.name = name;\n this.value = value;\n }\n\n ", "post_mask_code": "{\n return name;\n }\n\n public Value getValue() {\n return value;\n }\n\n @Override\n public T get(Class clazz) {\n return value.get(clazz);\n }\n\n @Override\n public T get(TypeSupplier typeSupplier) {\n return value.get(typeSupplier);\n }\n\n @Override\n public Object get() {\n return value.get();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (!(o instanceof Column)) {\n return false;\n }\n Column that = (Column) o;\n return Objects.equals(name, that.getName()) && Objects.equals(value, that.getValue());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value);\n }\n\n @Override\n public String toString() {\n return \"DefaultColumn{\" + \"name='\" + name + '\\'' + \", value=\" + value + '}';\n }\n}\n"} {"task_id": "Java_1175", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse/jnosql/communication/communication-column/src/main/java/org/eclipse/jnosql/communication/column/DefaultColumn.java", "mask_start_position": 1359, "mask_end_position": 1451, "canonical_solution": "{\n return \"DefaultColumn{\" + \"name='\" + name + '\\'' + \", value=\" + value + '}';\n }", "pre_mask_code": "package org.eclipse.jnosql.communication.column;\n\nimport jakarta.nosql.TypeSupplier;\nimport jakarta.nosql.Value;\nimport jakarta.nosql.column.Column;\nimport org.eclipse.jnosql.communication.Entry;\nimport java.util.Objects;\n\n/**\n * The default implementation of {@link Column}\n */\nfinal class DefaultColumn implements Column, Entry {\n\n private final String name;\n\n private final Value value;\n\n DefaultColumn(String name, Value value) {\n this.name = name;\n this.value = value;\n }\n\n public String getName() {\n return name;\n }\n\n public Value getValue() {\n return value;\n }\n\n @Override\n public T get(Class clazz) {\n return value.get(clazz);\n }\n\n @Override\n public T get(TypeSupplier typeSupplier) {\n return value.get(typeSupplier);\n }\n\n @Override\n public Object get() {\n return value.get();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (!(o instanceof Column)) {\n return false;\n }\n Column that = (Column) o;\n return Objects.equals(name, that.getName()) && Objects.equals(value, that.getValue());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value);\n }\n\n @Override\n public String toString() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1176", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/eclipse/jnosql/communication/communication-column/src/main/java/org/eclipse/jnosql/communication/column/DefaultColumn.java", "mask_start_position": 954, "mask_end_position": 1014, "canonical_solution": "\n if (this == o) {\n return true;\n }", "pre_mask_code": "package org.eclipse.jnosql.communication.column;\n\nimport jakarta.nosql.TypeSupplier;\nimport jakarta.nosql.Value;\nimport jakarta.nosql.column.Column;\nimport org.eclipse.jnosql.communication.Entry;\nimport java.util.Objects;\n\n/**\n * The default implementation of {@link Column}\n */\nfinal class DefaultColumn implements Column, Entry {\n\n private final String name;\n\n private final Value value;\n\n DefaultColumn(String name, Value value) {\n this.name = name;\n this.value = value;\n }\n\n public String getName() {\n return name;\n }\n\n public Value getValue() {\n return value;\n }\n\n @Override\n public T get(Class clazz) {\n return value.get(clazz);\n }\n\n @Override\n public T get(TypeSupplier typeSupplier) {\n return value.get(typeSupplier);\n }\n\n @Override\n public Object get() {\n return value.get();\n }\n\n @Override\n public boolean equals(Object o) {", "post_mask_code": "\n if (!(o instanceof Column)) {\n return false;\n }\n Column that = (Column) o;\n return Objects.equals(name, that.getName()) && Objects.equals(value, that.getValue());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value);\n }\n\n @Override\n public String toString() {\n return \"DefaultColumn{\" + \"name='\" + name + '\\'' + \", value=\" + value + '}';\n }\n}\n"} {"task_id": "Java_1177", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/eclipse/jnosql/communication/communication-column/src/main/java/org/eclipse/jnosql/communication/column/DefaultColumn.java", "mask_start_position": 1023, "mask_end_position": 1122, "canonical_solution": "if (!(o instanceof Column)) {\n return false;\n }\n Column that = (Column) o;", "pre_mask_code": "package org.eclipse.jnosql.communication.column;\n\nimport jakarta.nosql.TypeSupplier;\nimport jakarta.nosql.Value;\nimport jakarta.nosql.column.Column;\nimport org.eclipse.jnosql.communication.Entry;\nimport java.util.Objects;\n\n/**\n * The default implementation of {@link Column}\n */\nfinal class DefaultColumn implements Column, Entry {\n\n private final String name;\n\n private final Value value;\n\n DefaultColumn(String name, Value value) {\n this.name = name;\n this.value = value;\n }\n\n public String getName() {\n return name;\n }\n\n public Value getValue() {\n return value;\n }\n\n @Override\n public T get(Class clazz) {\n return value.get(clazz);\n }\n\n @Override\n public T get(TypeSupplier typeSupplier) {\n return value.get(typeSupplier);\n }\n\n @Override\n public Object get() {\n return value.get();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n ", "post_mask_code": "\n return Objects.equals(name, that.getName()) && Objects.equals(value, that.getValue());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value);\n }\n\n @Override\n public String toString() {\n return \"DefaultColumn{\" + \"name='\" + name + '\\'' + \", value=\" + value + '}';\n }\n}\n"} {"task_id": "Java_1178", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/eclipse/jnosql/communication/communication-column/src/main/java/org/eclipse/jnosql/communication/column/DefaultColumn.java", "mask_start_position": 1131, "mask_end_position": 1223, "canonical_solution": "return Objects.equals(name, that.getName()) && Objects.equals(value, that.getValue());\n }", "pre_mask_code": "package org.eclipse.jnosql.communication.column;\n\nimport jakarta.nosql.TypeSupplier;\nimport jakarta.nosql.Value;\nimport jakarta.nosql.column.Column;\nimport org.eclipse.jnosql.communication.Entry;\nimport java.util.Objects;\n\n/**\n * The default implementation of {@link Column}\n */\nfinal class DefaultColumn implements Column, Entry {\n\n private final String name;\n\n private final Value value;\n\n DefaultColumn(String name, Value value) {\n this.name = name;\n this.value = value;\n }\n\n public String getName() {\n return name;\n }\n\n public Value getValue() {\n return value;\n }\n\n @Override\n public T get(Class clazz) {\n return value.get(clazz);\n }\n\n @Override\n public T get(TypeSupplier typeSupplier) {\n return value.get(typeSupplier);\n }\n\n @Override\n public Object get() {\n return value.get();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (!(o instanceof Column)) {\n return false;\n }\n Column that = (Column) o;\n ", "post_mask_code": "\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value);\n }\n\n @Override\n public String toString() {\n return \"DefaultColumn{\" + \"name='\" + name + '\\'' + \", value=\" + value + '}';\n }\n}\n"} {"task_id": "Java_1179", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse/jnosql/communication/communication-column/src/main/java/org/eclipse/jnosql/communication/column/DefaultColumn.java", "mask_start_position": 550, "mask_end_position": 554, "canonical_solution": "ame;", "pre_mask_code": "package org.eclipse.jnosql.communication.column;\n\nimport jakarta.nosql.TypeSupplier;\nimport jakarta.nosql.Value;\nimport jakarta.nosql.column.Column;\nimport org.eclipse.jnosql.communication.Entry;\nimport java.util.Objects;\n\n/**\n * The default implementation of {@link Column}\n */\nfinal class DefaultColumn implements Column, Entry {\n\n private final String name;\n\n private final Value value;\n\n DefaultColumn(String name, Value value) {\n this.name = name;\n this.value = value;\n }\n\n public String getName() {\n return n", "post_mask_code": "\n }\n\n public Value getValue() {\n return value;\n }\n\n @Override\n public T get(Class clazz) {\n return value.get(clazz);\n }\n\n @Override\n public T get(TypeSupplier typeSupplier) {\n return value.get(typeSupplier);\n }\n\n @Override\n public Object get() {\n return value.get();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (!(o instanceof Column)) {\n return false;\n }\n Column that = (Column) o;\n return Objects.equals(name, that.getName()) && Objects.equals(value, that.getValue());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value);\n }\n\n @Override\n public String toString() {\n return \"DefaultColumn{\" + \"name='\" + name + '\\'' + \", value=\" + value + '}';\n }\n}\n"} {"task_id": "Java_1180", "language": "Java", "task_type": "if_statement", "source_file": "java/github/eclipse/jnosql/communication/communication-column/src/main/java/org/eclipse/jnosql/communication/column/DefaultColumn.java", "mask_start_position": 963, "mask_end_position": 1014, "canonical_solution": "if (this == o) {\n return true;\n }", "pre_mask_code": "package org.eclipse.jnosql.communication.column;\n\nimport jakarta.nosql.TypeSupplier;\nimport jakarta.nosql.Value;\nimport jakarta.nosql.column.Column;\nimport org.eclipse.jnosql.communication.Entry;\nimport java.util.Objects;\n\n/**\n * The default implementation of {@link Column}\n */\nfinal class DefaultColumn implements Column, Entry {\n\n private final String name;\n\n private final Value value;\n\n DefaultColumn(String name, Value value) {\n this.name = name;\n this.value = value;\n }\n\n public String getName() {\n return name;\n }\n\n public Value getValue() {\n return value;\n }\n\n @Override\n public T get(Class clazz) {\n return value.get(clazz);\n }\n\n @Override\n public T get(TypeSupplier typeSupplier) {\n return value.get(typeSupplier);\n }\n\n @Override\n public Object get() {\n return value.get();\n }\n\n @Override\n public boolean equals(Object o) {\n ", "post_mask_code": "\n if (!(o instanceof Column)) {\n return false;\n }\n Column that = (Column) o;\n return Objects.equals(name, that.getName()) && Objects.equals(value, that.getValue());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value);\n }\n\n @Override\n public String toString() {\n return \"DefaultColumn{\" + \"name='\" + name + '\\'' + \", value=\" + value + '}';\n }\n}\n"} {"task_id": "Java_1181", "language": "Java", "task_type": "method_signature", "source_file": "java/github/timebusker/spring-boot/spring-boot-19-Definition-Starter/spring-boot-19-Definition-Starter-Service/src/main/java/cn/timebusker/config/CalculateProperties.java", "mask_start_position": 267, "mask_end_position": 299, "canonical_solution": "public void setScale(int scale) ", "pre_mask_code": "package cn.timebusker.config;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n@ConfigurationProperties(\"calculate\")\npublic class CalculateProperties {\n\n private int scale;\n\n public int getScale() {\n return scale;\n }\n\n ", "post_mask_code": "{\n this.scale = scale;\n }\n}\n"} {"task_id": "Java_1182", "language": "Java", "task_type": "method_body", "source_file": "java/github/timebusker/spring-boot/spring-boot-19-Definition-Starter/spring-boot-19-Definition-Starter-Service/src/main/java/cn/timebusker/config/CalculateProperties.java", "mask_start_position": 232, "mask_end_position": 261, "canonical_solution": "{\n return scale;\n }", "pre_mask_code": "package cn.timebusker.config;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n@ConfigurationProperties(\"calculate\")\npublic class CalculateProperties {\n\n private int scale;\n\n public int getScale() ", "post_mask_code": "\n\n public void setScale(int scale) {\n this.scale = scale;\n }\n}\n"} {"task_id": "Java_1183", "language": "Java", "task_type": "single_line", "source_file": "java/github/timebusker/spring-boot/spring-boot-19-Definition-Starter/spring-boot-19-Definition-Starter-Service/src/main/java/cn/timebusker/config/CalculateProperties.java", "mask_start_position": 321, "mask_end_position": 328, "canonical_solution": " scale;", "pre_mask_code": "package cn.timebusker.config;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n@ConfigurationProperties(\"calculate\")\npublic class CalculateProperties {\n\n private int scale;\n\n public int getScale() {\n return scale;\n }\n\n public void setScale(int scale) {\n this.scale =", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1184", "language": "Java", "task_type": "method_signature", "source_file": "java/github/RDFstar/RDFstarTools/src/main/java/se/liu/ida/rdfstar/tools/conversion/RDFStar2RDF.java", "mask_start_position": 1369, "mask_end_position": 1435, "canonical_solution": "public void convert(String inputFilename, OutputStream outStream) ", "pre_mask_code": "package se.liu.ida.rdfstar.tools.conversion;\n\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.jena.atlas.io.IndentedWriter;\nimport org.apache.jena.graph.Node;\nimport org.apache.jena.graph.NodeFactory;\nimport org.apache.jena.graph.Node_Triple;\nimport org.apache.jena.graph.Triple;\nimport org.apache.jena.riot.RDFParser;\nimport org.apache.jena.riot.lang.LabelToNode;\nimport org.apache.jena.riot.lang.PipedRDFIterator;\nimport org.apache.jena.riot.lang.PipedTriplesStream;\nimport org.apache.jena.riot.out.NodeFormatter;\nimport org.apache.jena.riot.out.NodeFormatterTTL;\nimport org.apache.jena.riot.system.PrefixMap;\nimport org.apache.jena.riot.system.RiotLib;\nimport org.apache.jena.vocabulary.RDF;\nimport se.liu.ida.rdfstar.tools.parser.lang.LangTurtleStar;\n\n/**\n * Conversion of Turtle* files into Turtle such that the resulting\n * RDF data is a reification-based representation of the RDF* data.\n *\n * @author Jesper Eriksson\n * @author Amir Hakim\n * @author Ebba Lindström\n * @author Olaf Hartig\n * @author Robin Keskisärkkä\n */\npublic class RDFStar2RDF {\n\n static protected final int BUFFER_SIZE = 16000;\n\n static protected final boolean EXPLICITILY_ADD_REIFIED_STATEMENTS = true;\n\n ", "post_mask_code": "{\n convert(inputFilename, outStream, null);\n }\n\n public void convert(String inputFilename, OutputStream outStream, String baseIRI) {\n final FirstPass fp = new FirstPass(inputFilename, outStream);\n fp.setBaseIRI(baseIRI);\n fp.execute();\n final FileConverter fc = new FileConverter(inputFilename, outStream, fp.getBaseIRI(), fp.getPrefixMap());\n fc.execute();\n }\n\n protected class FileConverter {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n final protected String baseIRI;\n\n final protected PrefixMap pmap;\n\n // populated during the conversion to record for every reified\n // triple, the blank node that has been created as statement ID\n protected final Map bNodes = new HashMap<>();\n\n protected boolean first_lap = true;\n\n // used to create turtle blocks\n protected Node lastSubject = NodeFactory.createBlankNode();\n\n // used to create turtle blocks\n protected Node lastPredicate = NodeFactory.createBlankNode();\n\n public FileConverter(String inputFilename, OutputStream outStream, String baseIRI, PrefixMap pm) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n this.baseIRI = baseIRI;\n this.pmap = pm;\n }\n\n public void execute() {\n // print all prefixes and the base IRI to the output file\n try (IndentedWriter writer = new IndentedWriter(outStream)) {\n RiotLib.writePrefixes(writer, pmap);\n RiotLib.writeBase(writer, baseIRI);\n // second pass over the file to perform the conversion in a streaming manner\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n final NodeFormatter nFmt = new NodeFormatterTTL(baseIRI, pmap);\n while (it.hasNext()) {\n printTriples(it.next(), writer, nFmt, false);\n }\n it.close();\n executor.shutdown();\n writer.write(\" .\");\n writer.flush();\n }\n }\n\n /**\n * Recursively flattens nested triples and prints in pretty format. One triple at the time.\n */\n protected Node printTriples(Triple triple, IndentedWriter writer, NodeFormatter nFmt, boolean hasParent) {\n Node s = triple.getSubject();\n Node p = triple.getPredicate();\n Node o = triple.getObject();\n if (s instanceof Node_Triple) {\n final Triple subjTriple = ((Node_Triple) s).get();\n s = printTriples(subjTriple, writer, nFmt, true);\n first_lap = false;\n }\n if (o instanceof Node_Triple) {\n final Triple objTriple = ((Node_Triple) o).get();\n o = printTriples(objTriple, writer, nFmt, true);\n first_lap = false;\n }\n // if we have reached here, we are at the deepest level of recursion, or if its not nested at all\n if (hasParent) {\n final Triple hashKey = Triple.create(s, p, o);\n Node bnode;\n if ((bnode = bNodes.get(hashKey)) != null) {\n return bnode;\n } else {\n bnode = NodeFactory.createBlankNode();\n bNodes.put(hashKey, bnode);\n if (!first_lap)\n writer.write(\" .\\n\");\n if (EXPLICITILY_ADD_REIFIED_STATEMENTS) {\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n writer.write(\" .\\n\");\n }\n nFmt.format(writer, bnode);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.type);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.Statement);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.subject);\n writer.write(\" \");\n nFmt.format(writer, s);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.predicate);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.object);\n writer.write(\" \");\n nFmt.format(writer, o);\n lastSubject = bnode;\n lastPredicate = NodeFactory.createBlankNode();\n return bnode;\n }\n } else // Enter here if not nested or top level of recursion\n {\n if (lastSubject.matches(s)) {\n int pad = 0;\n if (lastSubject.isBlank())\n pad = 3;\n if (lastPredicate.matches(p)) {\n writer.write(\" ,\\n\" + StringUtils.leftPad(\"\", s.toString().length() + p.toString().length() + 2 + pad));\n nFmt.format(writer, o);\n } else {\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", s.toString().length() + 1 + pad));\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n } else {\n if (lastSubject.matches(o) || !first_lap)\n writer.write(\" .\\n\");\n else\n first_lap = false;\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n }\n writer.flush();\n lastSubject = s;\n lastPredicate = p;\n first_lap = false;\n // return to the execute method\n return null;\n }\n }\n\n // end of class FileConverter\n /**\n * Performs a first pass over the input file to collect all prefixes.\n */\n protected class FirstPass {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n protected PrefixMap pmap;\n\n protected String baseIRI;\n\n public FirstPass(String inputFilename, OutputStream outStream) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n }\n\n public PrefixMap getPrefixMap() {\n return pmap;\n }\n\n public String getBaseIRI() {\n return baseIRI;\n }\n\n public void setBaseIRI(String baseIRI) {\n this.baseIRI = baseIRI;\n }\n\n public void execute() {\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n // consume the iterator\n while (it.hasNext()) {\n it.next();\n }\n pmap = it.getPrefixes();\n if (baseIRI == null) {\n baseIRI = it.getBaseIri();\n }\n it.close();\n executor.shutdown();\n }\n }\n // end of class FirstPass\n}\n"} {"task_id": "Java_1185", "language": "Java", "task_type": "method_body", "source_file": "java/github/RDFstar/RDFstarTools/src/main/java/se/liu/ida/rdfstar/tools/conversion/RDFStar2RDF.java", "mask_start_position": 9682, "mask_end_position": 9887, "canonical_solution": "{\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }", "pre_mask_code": "package se.liu.ida.rdfstar.tools.conversion;\n\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.jena.atlas.io.IndentedWriter;\nimport org.apache.jena.graph.Node;\nimport org.apache.jena.graph.NodeFactory;\nimport org.apache.jena.graph.Node_Triple;\nimport org.apache.jena.graph.Triple;\nimport org.apache.jena.riot.RDFParser;\nimport org.apache.jena.riot.lang.LabelToNode;\nimport org.apache.jena.riot.lang.PipedRDFIterator;\nimport org.apache.jena.riot.lang.PipedTriplesStream;\nimport org.apache.jena.riot.out.NodeFormatter;\nimport org.apache.jena.riot.out.NodeFormatterTTL;\nimport org.apache.jena.riot.system.PrefixMap;\nimport org.apache.jena.riot.system.RiotLib;\nimport org.apache.jena.vocabulary.RDF;\nimport se.liu.ida.rdfstar.tools.parser.lang.LangTurtleStar;\n\n/**\n * Conversion of Turtle* files into Turtle such that the resulting\n * RDF data is a reification-based representation of the RDF* data.\n *\n * @author Jesper Eriksson\n * @author Amir Hakim\n * @author Ebba Lindström\n * @author Olaf Hartig\n * @author Robin Keskisärkkä\n */\npublic class RDFStar2RDF {\n\n static protected final int BUFFER_SIZE = 16000;\n\n static protected final boolean EXPLICITILY_ADD_REIFIED_STATEMENTS = true;\n\n public void convert(String inputFilename, OutputStream outStream) {\n convert(inputFilename, outStream, null);\n }\n\n public void convert(String inputFilename, OutputStream outStream, String baseIRI) {\n final FirstPass fp = new FirstPass(inputFilename, outStream);\n fp.setBaseIRI(baseIRI);\n fp.execute();\n final FileConverter fc = new FileConverter(inputFilename, outStream, fp.getBaseIRI(), fp.getPrefixMap());\n fc.execute();\n }\n\n protected class FileConverter {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n final protected String baseIRI;\n\n final protected PrefixMap pmap;\n\n // populated during the conversion to record for every reified\n // triple, the blank node that has been created as statement ID\n protected final Map bNodes = new HashMap<>();\n\n protected boolean first_lap = true;\n\n // used to create turtle blocks\n protected Node lastSubject = NodeFactory.createBlankNode();\n\n // used to create turtle blocks\n protected Node lastPredicate = NodeFactory.createBlankNode();\n\n public FileConverter(String inputFilename, OutputStream outStream, String baseIRI, PrefixMap pm) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n this.baseIRI = baseIRI;\n this.pmap = pm;\n }\n\n public void execute() {\n // print all prefixes and the base IRI to the output file\n try (IndentedWriter writer = new IndentedWriter(outStream)) {\n RiotLib.writePrefixes(writer, pmap);\n RiotLib.writeBase(writer, baseIRI);\n // second pass over the file to perform the conversion in a streaming manner\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n final NodeFormatter nFmt = new NodeFormatterTTL(baseIRI, pmap);\n while (it.hasNext()) {\n printTriples(it.next(), writer, nFmt, false);\n }\n it.close();\n executor.shutdown();\n writer.write(\" .\");\n writer.flush();\n }\n }\n\n /**\n * Recursively flattens nested triples and prints in pretty format. One triple at the time.\n */\n protected Node printTriples(Triple triple, IndentedWriter writer, NodeFormatter nFmt, boolean hasParent) {\n Node s = triple.getSubject();\n Node p = triple.getPredicate();\n Node o = triple.getObject();\n if (s instanceof Node_Triple) {\n final Triple subjTriple = ((Node_Triple) s).get();\n s = printTriples(subjTriple, writer, nFmt, true);\n first_lap = false;\n }\n if (o instanceof Node_Triple) {\n final Triple objTriple = ((Node_Triple) o).get();\n o = printTriples(objTriple, writer, nFmt, true);\n first_lap = false;\n }\n // if we have reached here, we are at the deepest level of recursion, or if its not nested at all\n if (hasParent) {\n final Triple hashKey = Triple.create(s, p, o);\n Node bnode;\n if ((bnode = bNodes.get(hashKey)) != null) {\n return bnode;\n } else {\n bnode = NodeFactory.createBlankNode();\n bNodes.put(hashKey, bnode);\n if (!first_lap)\n writer.write(\" .\\n\");\n if (EXPLICITILY_ADD_REIFIED_STATEMENTS) {\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n writer.write(\" .\\n\");\n }\n nFmt.format(writer, bnode);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.type);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.Statement);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.subject);\n writer.write(\" \");\n nFmt.format(writer, s);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.predicate);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.object);\n writer.write(\" \");\n nFmt.format(writer, o);\n lastSubject = bnode;\n lastPredicate = NodeFactory.createBlankNode();\n return bnode;\n }\n } else // Enter here if not nested or top level of recursion\n {\n if (lastSubject.matches(s)) {\n int pad = 0;\n if (lastSubject.isBlank())\n pad = 3;\n if (lastPredicate.matches(p)) {\n writer.write(\" ,\\n\" + StringUtils.leftPad(\"\", s.toString().length() + p.toString().length() + 2 + pad));\n nFmt.format(writer, o);\n } else {\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", s.toString().length() + 1 + pad));\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n } else {\n if (lastSubject.matches(o) || !first_lap)\n writer.write(\" .\\n\");\n else\n first_lap = false;\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n }\n writer.flush();\n lastSubject = s;\n lastPredicate = p;\n first_lap = false;\n // return to the execute method\n return null;\n }\n }\n\n // end of class FileConverter\n /**\n * Performs a first pass over the input file to collect all prefixes.\n */\n protected class FirstPass {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n protected PrefixMap pmap;\n\n protected String baseIRI;\n\n public FirstPass(String inputFilename, OutputStream outStream) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n }\n\n public PrefixMap getPrefixMap() {\n return pmap;\n }\n\n public String getBaseIRI() {\n return baseIRI;\n }\n\n public void setBaseIRI(String baseIRI) {\n this.baseIRI = baseIRI;\n }\n\n public void execute() {\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() ", "post_mask_code": "\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n // consume the iterator\n while (it.hasNext()) {\n it.next();\n }\n pmap = it.getPrefixes();\n if (baseIRI == null) {\n baseIRI = it.getBaseIri();\n }\n it.close();\n executor.shutdown();\n }\n }\n // end of class FirstPass\n}\n"} {"task_id": "Java_1186", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/RDFstar/RDFstarTools/src/main/java/se/liu/ida/rdfstar/tools/conversion/RDFStar2RDF.java", "mask_start_position": 9323, "mask_end_position": 9902, "canonical_solution": "\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };", "pre_mask_code": "package se.liu.ida.rdfstar.tools.conversion;\n\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.jena.atlas.io.IndentedWriter;\nimport org.apache.jena.graph.Node;\nimport org.apache.jena.graph.NodeFactory;\nimport org.apache.jena.graph.Node_Triple;\nimport org.apache.jena.graph.Triple;\nimport org.apache.jena.riot.RDFParser;\nimport org.apache.jena.riot.lang.LabelToNode;\nimport org.apache.jena.riot.lang.PipedRDFIterator;\nimport org.apache.jena.riot.lang.PipedTriplesStream;\nimport org.apache.jena.riot.out.NodeFormatter;\nimport org.apache.jena.riot.out.NodeFormatterTTL;\nimport org.apache.jena.riot.system.PrefixMap;\nimport org.apache.jena.riot.system.RiotLib;\nimport org.apache.jena.vocabulary.RDF;\nimport se.liu.ida.rdfstar.tools.parser.lang.LangTurtleStar;\n\n/**\n * Conversion of Turtle* files into Turtle such that the resulting\n * RDF data is a reification-based representation of the RDF* data.\n *\n * @author Jesper Eriksson\n * @author Amir Hakim\n * @author Ebba Lindström\n * @author Olaf Hartig\n * @author Robin Keskisärkkä\n */\npublic class RDFStar2RDF {\n\n static protected final int BUFFER_SIZE = 16000;\n\n static protected final boolean EXPLICITILY_ADD_REIFIED_STATEMENTS = true;\n\n public void convert(String inputFilename, OutputStream outStream) {\n convert(inputFilename, outStream, null);\n }\n\n public void convert(String inputFilename, OutputStream outStream, String baseIRI) {\n final FirstPass fp = new FirstPass(inputFilename, outStream);\n fp.setBaseIRI(baseIRI);\n fp.execute();\n final FileConverter fc = new FileConverter(inputFilename, outStream, fp.getBaseIRI(), fp.getPrefixMap());\n fc.execute();\n }\n\n protected class FileConverter {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n final protected String baseIRI;\n\n final protected PrefixMap pmap;\n\n // populated during the conversion to record for every reified\n // triple, the blank node that has been created as statement ID\n protected final Map bNodes = new HashMap<>();\n\n protected boolean first_lap = true;\n\n // used to create turtle blocks\n protected Node lastSubject = NodeFactory.createBlankNode();\n\n // used to create turtle blocks\n protected Node lastPredicate = NodeFactory.createBlankNode();\n\n public FileConverter(String inputFilename, OutputStream outStream, String baseIRI, PrefixMap pm) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n this.baseIRI = baseIRI;\n this.pmap = pm;\n }\n\n public void execute() {\n // print all prefixes and the base IRI to the output file\n try (IndentedWriter writer = new IndentedWriter(outStream)) {\n RiotLib.writePrefixes(writer, pmap);\n RiotLib.writeBase(writer, baseIRI);\n // second pass over the file to perform the conversion in a streaming manner\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n final NodeFormatter nFmt = new NodeFormatterTTL(baseIRI, pmap);\n while (it.hasNext()) {\n printTriples(it.next(), writer, nFmt, false);\n }\n it.close();\n executor.shutdown();\n writer.write(\" .\");\n writer.flush();\n }\n }\n\n /**\n * Recursively flattens nested triples and prints in pretty format. One triple at the time.\n */\n protected Node printTriples(Triple triple, IndentedWriter writer, NodeFormatter nFmt, boolean hasParent) {\n Node s = triple.getSubject();\n Node p = triple.getPredicate();\n Node o = triple.getObject();\n if (s instanceof Node_Triple) {\n final Triple subjTriple = ((Node_Triple) s).get();\n s = printTriples(subjTriple, writer, nFmt, true);\n first_lap = false;\n }\n if (o instanceof Node_Triple) {\n final Triple objTriple = ((Node_Triple) o).get();\n o = printTriples(objTriple, writer, nFmt, true);\n first_lap = false;\n }\n // if we have reached here, we are at the deepest level of recursion, or if its not nested at all\n if (hasParent) {\n final Triple hashKey = Triple.create(s, p, o);\n Node bnode;\n if ((bnode = bNodes.get(hashKey)) != null) {\n return bnode;\n } else {\n bnode = NodeFactory.createBlankNode();\n bNodes.put(hashKey, bnode);\n if (!first_lap)\n writer.write(\" .\\n\");\n if (EXPLICITILY_ADD_REIFIED_STATEMENTS) {\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n writer.write(\" .\\n\");\n }\n nFmt.format(writer, bnode);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.type);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.Statement);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.subject);\n writer.write(\" \");\n nFmt.format(writer, s);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.predicate);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.object);\n writer.write(\" \");\n nFmt.format(writer, o);\n lastSubject = bnode;\n lastPredicate = NodeFactory.createBlankNode();\n return bnode;\n }\n } else // Enter here if not nested or top level of recursion\n {\n if (lastSubject.matches(s)) {\n int pad = 0;\n if (lastSubject.isBlank())\n pad = 3;\n if (lastPredicate.matches(p)) {\n writer.write(\" ,\\n\" + StringUtils.leftPad(\"\", s.toString().length() + p.toString().length() + 2 + pad));\n nFmt.format(writer, o);\n } else {\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", s.toString().length() + 1 + pad));\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n } else {\n if (lastSubject.matches(o) || !first_lap)\n writer.write(\" .\\n\");\n else\n first_lap = false;\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n }\n writer.flush();\n lastSubject = s;\n lastPredicate = p;\n first_lap = false;\n // return to the execute method\n return null;\n }\n }\n\n // end of class FileConverter\n /**\n * Performs a first pass over the input file to collect all prefixes.\n */\n protected class FirstPass {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n protected PrefixMap pmap;\n\n protected String baseIRI;\n\n public FirstPass(String inputFilename, OutputStream outStream) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n }\n\n public PrefixMap getPrefixMap() {\n return pmap;\n }\n\n public String getBaseIRI() {\n return baseIRI;\n }\n\n public void setBaseIRI(String baseIRI) {\n this.baseIRI = baseIRI;\n }\n\n public void execute() {", "post_mask_code": "\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n // consume the iterator\n while (it.hasNext()) {\n it.next();\n }\n pmap = it.getPrefixes();\n if (baseIRI == null) {\n baseIRI = it.getBaseIri();\n }\n it.close();\n executor.shutdown();\n }\n }\n // end of class FirstPass\n}\n"} {"task_id": "Java_1187", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/RDFstar/RDFstarTools/src/main/java/se/liu/ida/rdfstar/tools/conversion/RDFStar2RDF.java", "mask_start_position": 9915, "mask_end_position": 10128, "canonical_solution": "final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n // consume the iterator\n while (it.hasNext()) {\n it.next();\n }", "pre_mask_code": "package se.liu.ida.rdfstar.tools.conversion;\n\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.jena.atlas.io.IndentedWriter;\nimport org.apache.jena.graph.Node;\nimport org.apache.jena.graph.NodeFactory;\nimport org.apache.jena.graph.Node_Triple;\nimport org.apache.jena.graph.Triple;\nimport org.apache.jena.riot.RDFParser;\nimport org.apache.jena.riot.lang.LabelToNode;\nimport org.apache.jena.riot.lang.PipedRDFIterator;\nimport org.apache.jena.riot.lang.PipedTriplesStream;\nimport org.apache.jena.riot.out.NodeFormatter;\nimport org.apache.jena.riot.out.NodeFormatterTTL;\nimport org.apache.jena.riot.system.PrefixMap;\nimport org.apache.jena.riot.system.RiotLib;\nimport org.apache.jena.vocabulary.RDF;\nimport se.liu.ida.rdfstar.tools.parser.lang.LangTurtleStar;\n\n/**\n * Conversion of Turtle* files into Turtle such that the resulting\n * RDF data is a reification-based representation of the RDF* data.\n *\n * @author Jesper Eriksson\n * @author Amir Hakim\n * @author Ebba Lindström\n * @author Olaf Hartig\n * @author Robin Keskisärkkä\n */\npublic class RDFStar2RDF {\n\n static protected final int BUFFER_SIZE = 16000;\n\n static protected final boolean EXPLICITILY_ADD_REIFIED_STATEMENTS = true;\n\n public void convert(String inputFilename, OutputStream outStream) {\n convert(inputFilename, outStream, null);\n }\n\n public void convert(String inputFilename, OutputStream outStream, String baseIRI) {\n final FirstPass fp = new FirstPass(inputFilename, outStream);\n fp.setBaseIRI(baseIRI);\n fp.execute();\n final FileConverter fc = new FileConverter(inputFilename, outStream, fp.getBaseIRI(), fp.getPrefixMap());\n fc.execute();\n }\n\n protected class FileConverter {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n final protected String baseIRI;\n\n final protected PrefixMap pmap;\n\n // populated during the conversion to record for every reified\n // triple, the blank node that has been created as statement ID\n protected final Map bNodes = new HashMap<>();\n\n protected boolean first_lap = true;\n\n // used to create turtle blocks\n protected Node lastSubject = NodeFactory.createBlankNode();\n\n // used to create turtle blocks\n protected Node lastPredicate = NodeFactory.createBlankNode();\n\n public FileConverter(String inputFilename, OutputStream outStream, String baseIRI, PrefixMap pm) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n this.baseIRI = baseIRI;\n this.pmap = pm;\n }\n\n public void execute() {\n // print all prefixes and the base IRI to the output file\n try (IndentedWriter writer = new IndentedWriter(outStream)) {\n RiotLib.writePrefixes(writer, pmap);\n RiotLib.writeBase(writer, baseIRI);\n // second pass over the file to perform the conversion in a streaming manner\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n final NodeFormatter nFmt = new NodeFormatterTTL(baseIRI, pmap);\n while (it.hasNext()) {\n printTriples(it.next(), writer, nFmt, false);\n }\n it.close();\n executor.shutdown();\n writer.write(\" .\");\n writer.flush();\n }\n }\n\n /**\n * Recursively flattens nested triples and prints in pretty format. One triple at the time.\n */\n protected Node printTriples(Triple triple, IndentedWriter writer, NodeFormatter nFmt, boolean hasParent) {\n Node s = triple.getSubject();\n Node p = triple.getPredicate();\n Node o = triple.getObject();\n if (s instanceof Node_Triple) {\n final Triple subjTriple = ((Node_Triple) s).get();\n s = printTriples(subjTriple, writer, nFmt, true);\n first_lap = false;\n }\n if (o instanceof Node_Triple) {\n final Triple objTriple = ((Node_Triple) o).get();\n o = printTriples(objTriple, writer, nFmt, true);\n first_lap = false;\n }\n // if we have reached here, we are at the deepest level of recursion, or if its not nested at all\n if (hasParent) {\n final Triple hashKey = Triple.create(s, p, o);\n Node bnode;\n if ((bnode = bNodes.get(hashKey)) != null) {\n return bnode;\n } else {\n bnode = NodeFactory.createBlankNode();\n bNodes.put(hashKey, bnode);\n if (!first_lap)\n writer.write(\" .\\n\");\n if (EXPLICITILY_ADD_REIFIED_STATEMENTS) {\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n writer.write(\" .\\n\");\n }\n nFmt.format(writer, bnode);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.type);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.Statement);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.subject);\n writer.write(\" \");\n nFmt.format(writer, s);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.predicate);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.object);\n writer.write(\" \");\n nFmt.format(writer, o);\n lastSubject = bnode;\n lastPredicate = NodeFactory.createBlankNode();\n return bnode;\n }\n } else // Enter here if not nested or top level of recursion\n {\n if (lastSubject.matches(s)) {\n int pad = 0;\n if (lastSubject.isBlank())\n pad = 3;\n if (lastPredicate.matches(p)) {\n writer.write(\" ,\\n\" + StringUtils.leftPad(\"\", s.toString().length() + p.toString().length() + 2 + pad));\n nFmt.format(writer, o);\n } else {\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", s.toString().length() + 1 + pad));\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n } else {\n if (lastSubject.matches(o) || !first_lap)\n writer.write(\" .\\n\");\n else\n first_lap = false;\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n }\n writer.flush();\n lastSubject = s;\n lastPredicate = p;\n first_lap = false;\n // return to the execute method\n return null;\n }\n }\n\n // end of class FileConverter\n /**\n * Performs a first pass over the input file to collect all prefixes.\n */\n protected class FirstPass {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n protected PrefixMap pmap;\n\n protected String baseIRI;\n\n public FirstPass(String inputFilename, OutputStream outStream) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n }\n\n public PrefixMap getPrefixMap() {\n return pmap;\n }\n\n public String getBaseIRI() {\n return baseIRI;\n }\n\n public void setBaseIRI(String baseIRI) {\n this.baseIRI = baseIRI;\n }\n\n public void execute() {\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n ", "post_mask_code": "\n pmap = it.getPrefixes();\n if (baseIRI == null) {\n baseIRI = it.getBaseIri();\n }\n it.close();\n executor.shutdown();\n }\n }\n // end of class FirstPass\n}\n"} {"task_id": "Java_1188", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/RDFstar/RDFstarTools/src/main/java/se/liu/ida/rdfstar/tools/conversion/RDFStar2RDF.java", "mask_start_position": 10141, "mask_end_position": 10324, "canonical_solution": "pmap = it.getPrefixes();\n if (baseIRI == null) {\n baseIRI = it.getBaseIri();\n }\n it.close();\n executor.shutdown();\n }", "pre_mask_code": "package se.liu.ida.rdfstar.tools.conversion;\n\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.jena.atlas.io.IndentedWriter;\nimport org.apache.jena.graph.Node;\nimport org.apache.jena.graph.NodeFactory;\nimport org.apache.jena.graph.Node_Triple;\nimport org.apache.jena.graph.Triple;\nimport org.apache.jena.riot.RDFParser;\nimport org.apache.jena.riot.lang.LabelToNode;\nimport org.apache.jena.riot.lang.PipedRDFIterator;\nimport org.apache.jena.riot.lang.PipedTriplesStream;\nimport org.apache.jena.riot.out.NodeFormatter;\nimport org.apache.jena.riot.out.NodeFormatterTTL;\nimport org.apache.jena.riot.system.PrefixMap;\nimport org.apache.jena.riot.system.RiotLib;\nimport org.apache.jena.vocabulary.RDF;\nimport se.liu.ida.rdfstar.tools.parser.lang.LangTurtleStar;\n\n/**\n * Conversion of Turtle* files into Turtle such that the resulting\n * RDF data is a reification-based representation of the RDF* data.\n *\n * @author Jesper Eriksson\n * @author Amir Hakim\n * @author Ebba Lindström\n * @author Olaf Hartig\n * @author Robin Keskisärkkä\n */\npublic class RDFStar2RDF {\n\n static protected final int BUFFER_SIZE = 16000;\n\n static protected final boolean EXPLICITILY_ADD_REIFIED_STATEMENTS = true;\n\n public void convert(String inputFilename, OutputStream outStream) {\n convert(inputFilename, outStream, null);\n }\n\n public void convert(String inputFilename, OutputStream outStream, String baseIRI) {\n final FirstPass fp = new FirstPass(inputFilename, outStream);\n fp.setBaseIRI(baseIRI);\n fp.execute();\n final FileConverter fc = new FileConverter(inputFilename, outStream, fp.getBaseIRI(), fp.getPrefixMap());\n fc.execute();\n }\n\n protected class FileConverter {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n final protected String baseIRI;\n\n final protected PrefixMap pmap;\n\n // populated during the conversion to record for every reified\n // triple, the blank node that has been created as statement ID\n protected final Map bNodes = new HashMap<>();\n\n protected boolean first_lap = true;\n\n // used to create turtle blocks\n protected Node lastSubject = NodeFactory.createBlankNode();\n\n // used to create turtle blocks\n protected Node lastPredicate = NodeFactory.createBlankNode();\n\n public FileConverter(String inputFilename, OutputStream outStream, String baseIRI, PrefixMap pm) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n this.baseIRI = baseIRI;\n this.pmap = pm;\n }\n\n public void execute() {\n // print all prefixes and the base IRI to the output file\n try (IndentedWriter writer = new IndentedWriter(outStream)) {\n RiotLib.writePrefixes(writer, pmap);\n RiotLib.writeBase(writer, baseIRI);\n // second pass over the file to perform the conversion in a streaming manner\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n final NodeFormatter nFmt = new NodeFormatterTTL(baseIRI, pmap);\n while (it.hasNext()) {\n printTriples(it.next(), writer, nFmt, false);\n }\n it.close();\n executor.shutdown();\n writer.write(\" .\");\n writer.flush();\n }\n }\n\n /**\n * Recursively flattens nested triples and prints in pretty format. One triple at the time.\n */\n protected Node printTriples(Triple triple, IndentedWriter writer, NodeFormatter nFmt, boolean hasParent) {\n Node s = triple.getSubject();\n Node p = triple.getPredicate();\n Node o = triple.getObject();\n if (s instanceof Node_Triple) {\n final Triple subjTriple = ((Node_Triple) s).get();\n s = printTriples(subjTriple, writer, nFmt, true);\n first_lap = false;\n }\n if (o instanceof Node_Triple) {\n final Triple objTriple = ((Node_Triple) o).get();\n o = printTriples(objTriple, writer, nFmt, true);\n first_lap = false;\n }\n // if we have reached here, we are at the deepest level of recursion, or if its not nested at all\n if (hasParent) {\n final Triple hashKey = Triple.create(s, p, o);\n Node bnode;\n if ((bnode = bNodes.get(hashKey)) != null) {\n return bnode;\n } else {\n bnode = NodeFactory.createBlankNode();\n bNodes.put(hashKey, bnode);\n if (!first_lap)\n writer.write(\" .\\n\");\n if (EXPLICITILY_ADD_REIFIED_STATEMENTS) {\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n writer.write(\" .\\n\");\n }\n nFmt.format(writer, bnode);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.type);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.Statement);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.subject);\n writer.write(\" \");\n nFmt.format(writer, s);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.predicate);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.object);\n writer.write(\" \");\n nFmt.format(writer, o);\n lastSubject = bnode;\n lastPredicate = NodeFactory.createBlankNode();\n return bnode;\n }\n } else // Enter here if not nested or top level of recursion\n {\n if (lastSubject.matches(s)) {\n int pad = 0;\n if (lastSubject.isBlank())\n pad = 3;\n if (lastPredicate.matches(p)) {\n writer.write(\" ,\\n\" + StringUtils.leftPad(\"\", s.toString().length() + p.toString().length() + 2 + pad));\n nFmt.format(writer, o);\n } else {\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", s.toString().length() + 1 + pad));\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n } else {\n if (lastSubject.matches(o) || !first_lap)\n writer.write(\" .\\n\");\n else\n first_lap = false;\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n }\n writer.flush();\n lastSubject = s;\n lastPredicate = p;\n first_lap = false;\n // return to the execute method\n return null;\n }\n }\n\n // end of class FileConverter\n /**\n * Performs a first pass over the input file to collect all prefixes.\n */\n protected class FirstPass {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n protected PrefixMap pmap;\n\n protected String baseIRI;\n\n public FirstPass(String inputFilename, OutputStream outStream) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n }\n\n public PrefixMap getPrefixMap() {\n return pmap;\n }\n\n public String getBaseIRI() {\n return baseIRI;\n }\n\n public void setBaseIRI(String baseIRI) {\n this.baseIRI = baseIRI;\n }\n\n public void execute() {\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n // consume the iterator\n while (it.hasNext()) {\n it.next();\n }\n ", "post_mask_code": "\n }\n // end of class FirstPass\n}\n"} {"task_id": "Java_1189", "language": "Java", "task_type": "single_line", "source_file": "java/github/RDFstar/RDFstarTools/src/main/java/se/liu/ida/rdfstar/tools/conversion/RDFStar2RDF.java", "mask_start_position": 9736, "mask_end_position": 9869, "canonical_solution": "abelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);", "pre_mask_code": "package se.liu.ida.rdfstar.tools.conversion;\n\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.jena.atlas.io.IndentedWriter;\nimport org.apache.jena.graph.Node;\nimport org.apache.jena.graph.NodeFactory;\nimport org.apache.jena.graph.Node_Triple;\nimport org.apache.jena.graph.Triple;\nimport org.apache.jena.riot.RDFParser;\nimport org.apache.jena.riot.lang.LabelToNode;\nimport org.apache.jena.riot.lang.PipedRDFIterator;\nimport org.apache.jena.riot.lang.PipedTriplesStream;\nimport org.apache.jena.riot.out.NodeFormatter;\nimport org.apache.jena.riot.out.NodeFormatterTTL;\nimport org.apache.jena.riot.system.PrefixMap;\nimport org.apache.jena.riot.system.RiotLib;\nimport org.apache.jena.vocabulary.RDF;\nimport se.liu.ida.rdfstar.tools.parser.lang.LangTurtleStar;\n\n/**\n * Conversion of Turtle* files into Turtle such that the resulting\n * RDF data is a reification-based representation of the RDF* data.\n *\n * @author Jesper Eriksson\n * @author Amir Hakim\n * @author Ebba Lindström\n * @author Olaf Hartig\n * @author Robin Keskisärkkä\n */\npublic class RDFStar2RDF {\n\n static protected final int BUFFER_SIZE = 16000;\n\n static protected final boolean EXPLICITILY_ADD_REIFIED_STATEMENTS = true;\n\n public void convert(String inputFilename, OutputStream outStream) {\n convert(inputFilename, outStream, null);\n }\n\n public void convert(String inputFilename, OutputStream outStream, String baseIRI) {\n final FirstPass fp = new FirstPass(inputFilename, outStream);\n fp.setBaseIRI(baseIRI);\n fp.execute();\n final FileConverter fc = new FileConverter(inputFilename, outStream, fp.getBaseIRI(), fp.getPrefixMap());\n fc.execute();\n }\n\n protected class FileConverter {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n final protected String baseIRI;\n\n final protected PrefixMap pmap;\n\n // populated during the conversion to record for every reified\n // triple, the blank node that has been created as statement ID\n protected final Map bNodes = new HashMap<>();\n\n protected boolean first_lap = true;\n\n // used to create turtle blocks\n protected Node lastSubject = NodeFactory.createBlankNode();\n\n // used to create turtle blocks\n protected Node lastPredicate = NodeFactory.createBlankNode();\n\n public FileConverter(String inputFilename, OutputStream outStream, String baseIRI, PrefixMap pm) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n this.baseIRI = baseIRI;\n this.pmap = pm;\n }\n\n public void execute() {\n // print all prefixes and the base IRI to the output file\n try (IndentedWriter writer = new IndentedWriter(outStream)) {\n RiotLib.writePrefixes(writer, pmap);\n RiotLib.writeBase(writer, baseIRI);\n // second pass over the file to perform the conversion in a streaming manner\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n final NodeFormatter nFmt = new NodeFormatterTTL(baseIRI, pmap);\n while (it.hasNext()) {\n printTriples(it.next(), writer, nFmt, false);\n }\n it.close();\n executor.shutdown();\n writer.write(\" .\");\n writer.flush();\n }\n }\n\n /**\n * Recursively flattens nested triples and prints in pretty format. One triple at the time.\n */\n protected Node printTriples(Triple triple, IndentedWriter writer, NodeFormatter nFmt, boolean hasParent) {\n Node s = triple.getSubject();\n Node p = triple.getPredicate();\n Node o = triple.getObject();\n if (s instanceof Node_Triple) {\n final Triple subjTriple = ((Node_Triple) s).get();\n s = printTriples(subjTriple, writer, nFmt, true);\n first_lap = false;\n }\n if (o instanceof Node_Triple) {\n final Triple objTriple = ((Node_Triple) o).get();\n o = printTriples(objTriple, writer, nFmt, true);\n first_lap = false;\n }\n // if we have reached here, we are at the deepest level of recursion, or if its not nested at all\n if (hasParent) {\n final Triple hashKey = Triple.create(s, p, o);\n Node bnode;\n if ((bnode = bNodes.get(hashKey)) != null) {\n return bnode;\n } else {\n bnode = NodeFactory.createBlankNode();\n bNodes.put(hashKey, bnode);\n if (!first_lap)\n writer.write(\" .\\n\");\n if (EXPLICITILY_ADD_REIFIED_STATEMENTS) {\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n writer.write(\" .\\n\");\n }\n nFmt.format(writer, bnode);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.type);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.Statement);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.subject);\n writer.write(\" \");\n nFmt.format(writer, s);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.predicate);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.object);\n writer.write(\" \");\n nFmt.format(writer, o);\n lastSubject = bnode;\n lastPredicate = NodeFactory.createBlankNode();\n return bnode;\n }\n } else // Enter here if not nested or top level of recursion\n {\n if (lastSubject.matches(s)) {\n int pad = 0;\n if (lastSubject.isBlank())\n pad = 3;\n if (lastPredicate.matches(p)) {\n writer.write(\" ,\\n\" + StringUtils.leftPad(\"\", s.toString().length() + p.toString().length() + 2 + pad));\n nFmt.format(writer, o);\n } else {\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", s.toString().length() + 1 + pad));\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n } else {\n if (lastSubject.matches(o) || !first_lap)\n writer.write(\" .\\n\");\n else\n first_lap = false;\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n }\n writer.flush();\n lastSubject = s;\n lastPredicate = p;\n first_lap = false;\n // return to the execute method\n return null;\n }\n }\n\n // end of class FileConverter\n /**\n * Performs a first pass over the input file to collect all prefixes.\n */\n protected class FirstPass {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n protected PrefixMap pmap;\n\n protected String baseIRI;\n\n public FirstPass(String inputFilename, OutputStream outStream) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n }\n\n public PrefixMap getPrefixMap() {\n return pmap;\n }\n\n public String getBaseIRI() {\n return baseIRI;\n }\n\n public void setBaseIRI(String baseIRI) {\n this.baseIRI = baseIRI;\n }\n\n public void execute() {\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(L", "post_mask_code": "\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n // consume the iterator\n while (it.hasNext()) {\n it.next();\n }\n pmap = it.getPrefixes();\n if (baseIRI == null) {\n baseIRI = it.getBaseIri();\n }\n it.close();\n executor.shutdown();\n }\n }\n // end of class FirstPass\n}\n"} {"task_id": "Java_1190", "language": "Java", "task_type": "if_statement", "source_file": "java/github/RDFstar/RDFstarTools/src/main/java/se/liu/ida/rdfstar/tools/conversion/RDFStar2RDF.java", "mask_start_position": 4660, "mask_end_position": 4873, "canonical_solution": "if (s instanceof Node_Triple) {\n final Triple subjTriple = ((Node_Triple) s).get();\n s = printTriples(subjTriple, writer, nFmt, true);\n first_lap = false;\n }", "pre_mask_code": "package se.liu.ida.rdfstar.tools.conversion;\n\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.jena.atlas.io.IndentedWriter;\nimport org.apache.jena.graph.Node;\nimport org.apache.jena.graph.NodeFactory;\nimport org.apache.jena.graph.Node_Triple;\nimport org.apache.jena.graph.Triple;\nimport org.apache.jena.riot.RDFParser;\nimport org.apache.jena.riot.lang.LabelToNode;\nimport org.apache.jena.riot.lang.PipedRDFIterator;\nimport org.apache.jena.riot.lang.PipedTriplesStream;\nimport org.apache.jena.riot.out.NodeFormatter;\nimport org.apache.jena.riot.out.NodeFormatterTTL;\nimport org.apache.jena.riot.system.PrefixMap;\nimport org.apache.jena.riot.system.RiotLib;\nimport org.apache.jena.vocabulary.RDF;\nimport se.liu.ida.rdfstar.tools.parser.lang.LangTurtleStar;\n\n/**\n * Conversion of Turtle* files into Turtle such that the resulting\n * RDF data is a reification-based representation of the RDF* data.\n *\n * @author Jesper Eriksson\n * @author Amir Hakim\n * @author Ebba Lindström\n * @author Olaf Hartig\n * @author Robin Keskisärkkä\n */\npublic class RDFStar2RDF {\n\n static protected final int BUFFER_SIZE = 16000;\n\n static protected final boolean EXPLICITILY_ADD_REIFIED_STATEMENTS = true;\n\n public void convert(String inputFilename, OutputStream outStream) {\n convert(inputFilename, outStream, null);\n }\n\n public void convert(String inputFilename, OutputStream outStream, String baseIRI) {\n final FirstPass fp = new FirstPass(inputFilename, outStream);\n fp.setBaseIRI(baseIRI);\n fp.execute();\n final FileConverter fc = new FileConverter(inputFilename, outStream, fp.getBaseIRI(), fp.getPrefixMap());\n fc.execute();\n }\n\n protected class FileConverter {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n final protected String baseIRI;\n\n final protected PrefixMap pmap;\n\n // populated during the conversion to record for every reified\n // triple, the blank node that has been created as statement ID\n protected final Map bNodes = new HashMap<>();\n\n protected boolean first_lap = true;\n\n // used to create turtle blocks\n protected Node lastSubject = NodeFactory.createBlankNode();\n\n // used to create turtle blocks\n protected Node lastPredicate = NodeFactory.createBlankNode();\n\n public FileConverter(String inputFilename, OutputStream outStream, String baseIRI, PrefixMap pm) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n this.baseIRI = baseIRI;\n this.pmap = pm;\n }\n\n public void execute() {\n // print all prefixes and the base IRI to the output file\n try (IndentedWriter writer = new IndentedWriter(outStream)) {\n RiotLib.writePrefixes(writer, pmap);\n RiotLib.writeBase(writer, baseIRI);\n // second pass over the file to perform the conversion in a streaming manner\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n final NodeFormatter nFmt = new NodeFormatterTTL(baseIRI, pmap);\n while (it.hasNext()) {\n printTriples(it.next(), writer, nFmt, false);\n }\n it.close();\n executor.shutdown();\n writer.write(\" .\");\n writer.flush();\n }\n }\n\n /**\n * Recursively flattens nested triples and prints in pretty format. One triple at the time.\n */\n protected Node printTriples(Triple triple, IndentedWriter writer, NodeFormatter nFmt, boolean hasParent) {\n Node s = triple.getSubject();\n Node p = triple.getPredicate();\n Node o = triple.getObject();\n ", "post_mask_code": "\n if (o instanceof Node_Triple) {\n final Triple objTriple = ((Node_Triple) o).get();\n o = printTriples(objTriple, writer, nFmt, true);\n first_lap = false;\n }\n // if we have reached here, we are at the deepest level of recursion, or if its not nested at all\n if (hasParent) {\n final Triple hashKey = Triple.create(s, p, o);\n Node bnode;\n if ((bnode = bNodes.get(hashKey)) != null) {\n return bnode;\n } else {\n bnode = NodeFactory.createBlankNode();\n bNodes.put(hashKey, bnode);\n if (!first_lap)\n writer.write(\" .\\n\");\n if (EXPLICITILY_ADD_REIFIED_STATEMENTS) {\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n writer.write(\" .\\n\");\n }\n nFmt.format(writer, bnode);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.type);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.Statement);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.subject);\n writer.write(\" \");\n nFmt.format(writer, s);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.predicate);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.object);\n writer.write(\" \");\n nFmt.format(writer, o);\n lastSubject = bnode;\n lastPredicate = NodeFactory.createBlankNode();\n return bnode;\n }\n } else // Enter here if not nested or top level of recursion\n {\n if (lastSubject.matches(s)) {\n int pad = 0;\n if (lastSubject.isBlank())\n pad = 3;\n if (lastPredicate.matches(p)) {\n writer.write(\" ,\\n\" + StringUtils.leftPad(\"\", s.toString().length() + p.toString().length() + 2 + pad));\n nFmt.format(writer, o);\n } else {\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", s.toString().length() + 1 + pad));\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n } else {\n if (lastSubject.matches(o) || !first_lap)\n writer.write(\" .\\n\");\n else\n first_lap = false;\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n }\n writer.flush();\n lastSubject = s;\n lastPredicate = p;\n first_lap = false;\n // return to the execute method\n return null;\n }\n }\n\n // end of class FileConverter\n /**\n * Performs a first pass over the input file to collect all prefixes.\n */\n protected class FirstPass {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n protected PrefixMap pmap;\n\n protected String baseIRI;\n\n public FirstPass(String inputFilename, OutputStream outStream) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n }\n\n public PrefixMap getPrefixMap() {\n return pmap;\n }\n\n public String getBaseIRI() {\n return baseIRI;\n }\n\n public void setBaseIRI(String baseIRI) {\n this.baseIRI = baseIRI;\n }\n\n public void execute() {\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n // consume the iterator\n while (it.hasNext()) {\n it.next();\n }\n pmap = it.getPrefixes();\n if (baseIRI == null) {\n baseIRI = it.getBaseIri();\n }\n it.close();\n executor.shutdown();\n }\n }\n // end of class FirstPass\n}\n"} {"task_id": "Java_1191", "language": "Java", "task_type": "while_statement", "source_file": "java/github/RDFstar/RDFstarTools/src/main/java/se/liu/ida/rdfstar/tools/conversion/RDFStar2RDF.java", "mask_start_position": 4017, "mask_end_position": 4123, "canonical_solution": "while (it.hasNext()) {\n printTriples(it.next(), writer, nFmt, false);\n }", "pre_mask_code": "package se.liu.ida.rdfstar.tools.conversion;\n\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.jena.atlas.io.IndentedWriter;\nimport org.apache.jena.graph.Node;\nimport org.apache.jena.graph.NodeFactory;\nimport org.apache.jena.graph.Node_Triple;\nimport org.apache.jena.graph.Triple;\nimport org.apache.jena.riot.RDFParser;\nimport org.apache.jena.riot.lang.LabelToNode;\nimport org.apache.jena.riot.lang.PipedRDFIterator;\nimport org.apache.jena.riot.lang.PipedTriplesStream;\nimport org.apache.jena.riot.out.NodeFormatter;\nimport org.apache.jena.riot.out.NodeFormatterTTL;\nimport org.apache.jena.riot.system.PrefixMap;\nimport org.apache.jena.riot.system.RiotLib;\nimport org.apache.jena.vocabulary.RDF;\nimport se.liu.ida.rdfstar.tools.parser.lang.LangTurtleStar;\n\n/**\n * Conversion of Turtle* files into Turtle such that the resulting\n * RDF data is a reification-based representation of the RDF* data.\n *\n * @author Jesper Eriksson\n * @author Amir Hakim\n * @author Ebba Lindström\n * @author Olaf Hartig\n * @author Robin Keskisärkkä\n */\npublic class RDFStar2RDF {\n\n static protected final int BUFFER_SIZE = 16000;\n\n static protected final boolean EXPLICITILY_ADD_REIFIED_STATEMENTS = true;\n\n public void convert(String inputFilename, OutputStream outStream) {\n convert(inputFilename, outStream, null);\n }\n\n public void convert(String inputFilename, OutputStream outStream, String baseIRI) {\n final FirstPass fp = new FirstPass(inputFilename, outStream);\n fp.setBaseIRI(baseIRI);\n fp.execute();\n final FileConverter fc = new FileConverter(inputFilename, outStream, fp.getBaseIRI(), fp.getPrefixMap());\n fc.execute();\n }\n\n protected class FileConverter {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n final protected String baseIRI;\n\n final protected PrefixMap pmap;\n\n // populated during the conversion to record for every reified\n // triple, the blank node that has been created as statement ID\n protected final Map bNodes = new HashMap<>();\n\n protected boolean first_lap = true;\n\n // used to create turtle blocks\n protected Node lastSubject = NodeFactory.createBlankNode();\n\n // used to create turtle blocks\n protected Node lastPredicate = NodeFactory.createBlankNode();\n\n public FileConverter(String inputFilename, OutputStream outStream, String baseIRI, PrefixMap pm) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n this.baseIRI = baseIRI;\n this.pmap = pm;\n }\n\n public void execute() {\n // print all prefixes and the base IRI to the output file\n try (IndentedWriter writer = new IndentedWriter(outStream)) {\n RiotLib.writePrefixes(writer, pmap);\n RiotLib.writeBase(writer, baseIRI);\n // second pass over the file to perform the conversion in a streaming manner\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n final NodeFormatter nFmt = new NodeFormatterTTL(baseIRI, pmap);\n ", "post_mask_code": "\n it.close();\n executor.shutdown();\n writer.write(\" .\");\n writer.flush();\n }\n }\n\n /**\n * Recursively flattens nested triples and prints in pretty format. One triple at the time.\n */\n protected Node printTriples(Triple triple, IndentedWriter writer, NodeFormatter nFmt, boolean hasParent) {\n Node s = triple.getSubject();\n Node p = triple.getPredicate();\n Node o = triple.getObject();\n if (s instanceof Node_Triple) {\n final Triple subjTriple = ((Node_Triple) s).get();\n s = printTriples(subjTriple, writer, nFmt, true);\n first_lap = false;\n }\n if (o instanceof Node_Triple) {\n final Triple objTriple = ((Node_Triple) o).get();\n o = printTriples(objTriple, writer, nFmt, true);\n first_lap = false;\n }\n // if we have reached here, we are at the deepest level of recursion, or if its not nested at all\n if (hasParent) {\n final Triple hashKey = Triple.create(s, p, o);\n Node bnode;\n if ((bnode = bNodes.get(hashKey)) != null) {\n return bnode;\n } else {\n bnode = NodeFactory.createBlankNode();\n bNodes.put(hashKey, bnode);\n if (!first_lap)\n writer.write(\" .\\n\");\n if (EXPLICITILY_ADD_REIFIED_STATEMENTS) {\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n writer.write(\" .\\n\");\n }\n nFmt.format(writer, bnode);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.type);\n writer.write(\" \");\n nFmt.format(writer, RDF.Nodes.Statement);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.subject);\n writer.write(\" \");\n nFmt.format(writer, s);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.predicate);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", bnode.toString().length() + 4));\n nFmt.format(writer, RDF.Nodes.object);\n writer.write(\" \");\n nFmt.format(writer, o);\n lastSubject = bnode;\n lastPredicate = NodeFactory.createBlankNode();\n return bnode;\n }\n } else // Enter here if not nested or top level of recursion\n {\n if (lastSubject.matches(s)) {\n int pad = 0;\n if (lastSubject.isBlank())\n pad = 3;\n if (lastPredicate.matches(p)) {\n writer.write(\" ,\\n\" + StringUtils.leftPad(\"\", s.toString().length() + p.toString().length() + 2 + pad));\n nFmt.format(writer, o);\n } else {\n writer.write(\" ;\\n\" + StringUtils.leftPad(\"\", s.toString().length() + 1 + pad));\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n } else {\n if (lastSubject.matches(o) || !first_lap)\n writer.write(\" .\\n\");\n else\n first_lap = false;\n nFmt.format(writer, s);\n writer.write(\" \");\n nFmt.format(writer, p);\n writer.write(\" \");\n nFmt.format(writer, o);\n }\n }\n writer.flush();\n lastSubject = s;\n lastPredicate = p;\n first_lap = false;\n // return to the execute method\n return null;\n }\n }\n\n // end of class FileConverter\n /**\n * Performs a first pass over the input file to collect all prefixes.\n */\n protected class FirstPass {\n\n final protected String inputFilename;\n\n final protected OutputStream outStream;\n\n protected PrefixMap pmap;\n\n protected String baseIRI;\n\n public FirstPass(String inputFilename, OutputStream outStream) {\n this.inputFilename = inputFilename;\n this.outStream = outStream;\n }\n\n public PrefixMap getPrefixMap() {\n return pmap;\n }\n\n public String getBaseIRI() {\n return baseIRI;\n }\n\n public void setBaseIRI(String baseIRI) {\n this.baseIRI = baseIRI;\n }\n\n public void execute() {\n final PipedRDFIterator it = new PipedRDFIterator<>(BUFFER_SIZE);\n final PipedTriplesStream triplesStream = new PipedTriplesStream(it);\n // PipedRDFStream and PipedRDFIterator need to be on different threads\n final Runnable r = new Runnable() {\n\n @Override\n public void run() {\n RDFParser.create().labelToNode(LabelToNode.createUseLabelEncoded()).source(inputFilename).lang(LangTurtleStar.TURTLESTAR).base(baseIRI).build().parse(triplesStream);\n }\n };\n final ExecutorService executor = Executors.newSingleThreadExecutor();\n executor.submit(r);\n // consume the iterator\n while (it.hasNext()) {\n it.next();\n }\n pmap = it.getPrefixes();\n if (baseIRI == null) {\n baseIRI = it.getBaseIri();\n }\n it.close();\n executor.shutdown();\n }\n }\n // end of class FirstPass\n}\n"} {"task_id": "Java_1192", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ShioCMS/shio/src/main/java/com/viglet/shio/graphql/endpoint/ShDefaultGraphQLInvocation.java", "mask_start_position": 1143, "mask_end_position": 1267, "canonical_solution": "@Override\n public CompletableFuture invoke(GraphQLInvocationData invocationData, WebRequest webRequest) ", "pre_mask_code": "package com.viglet.shio.graphql.endpoint;\n\nimport graphql.ExecutionInput;\nimport graphql.ExecutionResult;\nimport graphql.GraphQL;\nimport graphql.spring.web.servlet.ExecutionInputCustomizer;\nimport graphql.spring.web.servlet.GraphQLInvocation;\nimport graphql.spring.web.servlet.GraphQLInvocationData;\nimport org.dataloader.DataLoaderRegistry;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.context.request.WebRequest;\nimport com.viglet.shio.graphql.schema.ShGraphQLSchema;\nimport java.io.IOException;\nimport java.util.concurrent.CompletableFuture;\n\n@Component\npublic class ShDefaultGraphQLInvocation implements GraphQLInvocation {\n\n static final Logger logger = LogManager.getLogger(ShDefaultGraphQLInvocation.class);\n\n @Autowired\n GraphQL graphQL;\n\n @Autowired(required = false)\n DataLoaderRegistry dataLoaderRegistry;\n\n @Autowired\n ExecutionInputCustomizer executionInputCustomizer;\n\n @Autowired\n ShGraphQLSchema shGraphQLSchema;\n\n ", "post_mask_code": "{\n ExecutionInput.Builder executionInputBuilder = ExecutionInput.newExecutionInput().query(invocationData.getQuery()).operationName(invocationData.getOperationName()).variables(invocationData.getVariables());\n if (dataLoaderRegistry != null) {\n executionInputBuilder.dataLoaderRegistry(dataLoaderRegistry);\n }\n ExecutionInput executionInput = executionInputBuilder.build();\n CompletableFuture customizedExecutionInput = executionInputCustomizer.customizeExecutionInput(executionInput, webRequest);\n try {\n shGraphQLSchema.init();\n return customizedExecutionInput.thenCompose(shGraphQLSchema.graphQL()::executeAsync);\n } catch (IOException e) {\n logger.error(\"invoke\", e);\n }\n return customizedExecutionInput.thenCompose(graphQL::executeAsync);\n }\n}\n"} {"task_id": "Java_1193", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/ShioCMS/shio/src/main/java/com/viglet/shio/graphql/endpoint/ShDefaultGraphQLInvocation.java", "mask_start_position": 1268, "mask_end_position": 1608, "canonical_solution": "\n ExecutionInput.Builder executionInputBuilder = ExecutionInput.newExecutionInput().query(invocationData.getQuery()).operationName(invocationData.getOperationName()).variables(invocationData.getVariables());\n if (dataLoaderRegistry != null) {\n executionInputBuilder.dataLoaderRegistry(dataLoaderRegistry);\n }", "pre_mask_code": "package com.viglet.shio.graphql.endpoint;\n\nimport graphql.ExecutionInput;\nimport graphql.ExecutionResult;\nimport graphql.GraphQL;\nimport graphql.spring.web.servlet.ExecutionInputCustomizer;\nimport graphql.spring.web.servlet.GraphQLInvocation;\nimport graphql.spring.web.servlet.GraphQLInvocationData;\nimport org.dataloader.DataLoaderRegistry;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.context.request.WebRequest;\nimport com.viglet.shio.graphql.schema.ShGraphQLSchema;\nimport java.io.IOException;\nimport java.util.concurrent.CompletableFuture;\n\n@Component\npublic class ShDefaultGraphQLInvocation implements GraphQLInvocation {\n\n static final Logger logger = LogManager.getLogger(ShDefaultGraphQLInvocation.class);\n\n @Autowired\n GraphQL graphQL;\n\n @Autowired(required = false)\n DataLoaderRegistry dataLoaderRegistry;\n\n @Autowired\n ExecutionInputCustomizer executionInputCustomizer;\n\n @Autowired\n ShGraphQLSchema shGraphQLSchema;\n\n @Override\n public CompletableFuture invoke(GraphQLInvocationData invocationData, WebRequest webRequest) {", "post_mask_code": "\n ExecutionInput executionInput = executionInputBuilder.build();\n CompletableFuture customizedExecutionInput = executionInputCustomizer.customizeExecutionInput(executionInput, webRequest);\n try {\n shGraphQLSchema.init();\n return customizedExecutionInput.thenCompose(shGraphQLSchema.graphQL()::executeAsync);\n } catch (IOException e) {\n logger.error(\"invoke\", e);\n }\n return customizedExecutionInput.thenCompose(graphQL::executeAsync);\n }\n}\n"} {"task_id": "Java_1194", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/ShioCMS/shio/src/main/java/com/viglet/shio/graphql/endpoint/ShDefaultGraphQLInvocation.java", "mask_start_position": 1617, "mask_end_position": 1826, "canonical_solution": "ExecutionInput executionInput = executionInputBuilder.build();\n CompletableFuture customizedExecutionInput = executionInputCustomizer.customizeExecutionInput(executionInput, webRequest);", "pre_mask_code": "package com.viglet.shio.graphql.endpoint;\n\nimport graphql.ExecutionInput;\nimport graphql.ExecutionResult;\nimport graphql.GraphQL;\nimport graphql.spring.web.servlet.ExecutionInputCustomizer;\nimport graphql.spring.web.servlet.GraphQLInvocation;\nimport graphql.spring.web.servlet.GraphQLInvocationData;\nimport org.dataloader.DataLoaderRegistry;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.context.request.WebRequest;\nimport com.viglet.shio.graphql.schema.ShGraphQLSchema;\nimport java.io.IOException;\nimport java.util.concurrent.CompletableFuture;\n\n@Component\npublic class ShDefaultGraphQLInvocation implements GraphQLInvocation {\n\n static final Logger logger = LogManager.getLogger(ShDefaultGraphQLInvocation.class);\n\n @Autowired\n GraphQL graphQL;\n\n @Autowired(required = false)\n DataLoaderRegistry dataLoaderRegistry;\n\n @Autowired\n ExecutionInputCustomizer executionInputCustomizer;\n\n @Autowired\n ShGraphQLSchema shGraphQLSchema;\n\n @Override\n public CompletableFuture invoke(GraphQLInvocationData invocationData, WebRequest webRequest) {\n ExecutionInput.Builder executionInputBuilder = ExecutionInput.newExecutionInput().query(invocationData.getQuery()).operationName(invocationData.getOperationName()).variables(invocationData.getVariables());\n if (dataLoaderRegistry != null) {\n executionInputBuilder.dataLoaderRegistry(dataLoaderRegistry);\n }\n ", "post_mask_code": "\n try {\n shGraphQLSchema.init();\n return customizedExecutionInput.thenCompose(shGraphQLSchema.graphQL()::executeAsync);\n } catch (IOException e) {\n logger.error(\"invoke\", e);\n }\n return customizedExecutionInput.thenCompose(graphQL::executeAsync);\n }\n}\n"} {"task_id": "Java_1195", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/ShioCMS/shio/src/main/java/com/viglet/shio/graphql/endpoint/ShDefaultGraphQLInvocation.java", "mask_start_position": 1835, "mask_end_position": 2139, "canonical_solution": "try {\n shGraphQLSchema.init();\n return customizedExecutionInput.thenCompose(shGraphQLSchema.graphQL()::executeAsync);\n } catch (IOException e) {\n logger.error(\"invoke\", e);\n }\n return customizedExecutionInput.thenCompose(graphQL::executeAsync);\n }", "pre_mask_code": "package com.viglet.shio.graphql.endpoint;\n\nimport graphql.ExecutionInput;\nimport graphql.ExecutionResult;\nimport graphql.GraphQL;\nimport graphql.spring.web.servlet.ExecutionInputCustomizer;\nimport graphql.spring.web.servlet.GraphQLInvocation;\nimport graphql.spring.web.servlet.GraphQLInvocationData;\nimport org.dataloader.DataLoaderRegistry;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.context.request.WebRequest;\nimport com.viglet.shio.graphql.schema.ShGraphQLSchema;\nimport java.io.IOException;\nimport java.util.concurrent.CompletableFuture;\n\n@Component\npublic class ShDefaultGraphQLInvocation implements GraphQLInvocation {\n\n static final Logger logger = LogManager.getLogger(ShDefaultGraphQLInvocation.class);\n\n @Autowired\n GraphQL graphQL;\n\n @Autowired(required = false)\n DataLoaderRegistry dataLoaderRegistry;\n\n @Autowired\n ExecutionInputCustomizer executionInputCustomizer;\n\n @Autowired\n ShGraphQLSchema shGraphQLSchema;\n\n @Override\n public CompletableFuture invoke(GraphQLInvocationData invocationData, WebRequest webRequest) {\n ExecutionInput.Builder executionInputBuilder = ExecutionInput.newExecutionInput().query(invocationData.getQuery()).operationName(invocationData.getOperationName()).variables(invocationData.getVariables());\n if (dataLoaderRegistry != null) {\n executionInputBuilder.dataLoaderRegistry(dataLoaderRegistry);\n }\n ExecutionInput executionInput = executionInputBuilder.build();\n CompletableFuture customizedExecutionInput = executionInputCustomizer.customizeExecutionInput(executionInput, webRequest);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1196", "language": "Java", "task_type": "single_line", "source_file": "java/github/ShioCMS/shio/src/main/java/com/viglet/shio/graphql/endpoint/ShDefaultGraphQLInvocation.java", "mask_start_position": 1811, "mask_end_position": 1826, "canonical_solution": "t, webRequest);", "pre_mask_code": "package com.viglet.shio.graphql.endpoint;\n\nimport graphql.ExecutionInput;\nimport graphql.ExecutionResult;\nimport graphql.GraphQL;\nimport graphql.spring.web.servlet.ExecutionInputCustomizer;\nimport graphql.spring.web.servlet.GraphQLInvocation;\nimport graphql.spring.web.servlet.GraphQLInvocationData;\nimport org.dataloader.DataLoaderRegistry;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.context.request.WebRequest;\nimport com.viglet.shio.graphql.schema.ShGraphQLSchema;\nimport java.io.IOException;\nimport java.util.concurrent.CompletableFuture;\n\n@Component\npublic class ShDefaultGraphQLInvocation implements GraphQLInvocation {\n\n static final Logger logger = LogManager.getLogger(ShDefaultGraphQLInvocation.class);\n\n @Autowired\n GraphQL graphQL;\n\n @Autowired(required = false)\n DataLoaderRegistry dataLoaderRegistry;\n\n @Autowired\n ExecutionInputCustomizer executionInputCustomizer;\n\n @Autowired\n ShGraphQLSchema shGraphQLSchema;\n\n @Override\n public CompletableFuture invoke(GraphQLInvocationData invocationData, WebRequest webRequest) {\n ExecutionInput.Builder executionInputBuilder = ExecutionInput.newExecutionInput().query(invocationData.getQuery()).operationName(invocationData.getOperationName()).variables(invocationData.getVariables());\n if (dataLoaderRegistry != null) {\n executionInputBuilder.dataLoaderRegistry(dataLoaderRegistry);\n }\n ExecutionInput executionInput = executionInputBuilder.build();\n CompletableFuture customizedExecutionInput = executionInputCustomizer.customizeExecutionInput(executionInpu", "post_mask_code": "\n try {\n shGraphQLSchema.init();\n return customizedExecutionInput.thenCompose(shGraphQLSchema.graphQL()::executeAsync);\n } catch (IOException e) {\n logger.error(\"invoke\", e);\n }\n return customizedExecutionInput.thenCompose(graphQL::executeAsync);\n }\n}\n"} {"task_id": "Java_1197", "language": "Java", "task_type": "if_statement", "source_file": "java/github/ShioCMS/shio/src/main/java/com/viglet/shio/graphql/endpoint/ShDefaultGraphQLInvocation.java", "mask_start_position": 1491, "mask_end_position": 1608, "canonical_solution": "if (dataLoaderRegistry != null) {\n executionInputBuilder.dataLoaderRegistry(dataLoaderRegistry);\n }", "pre_mask_code": "package com.viglet.shio.graphql.endpoint;\n\nimport graphql.ExecutionInput;\nimport graphql.ExecutionResult;\nimport graphql.GraphQL;\nimport graphql.spring.web.servlet.ExecutionInputCustomizer;\nimport graphql.spring.web.servlet.GraphQLInvocation;\nimport graphql.spring.web.servlet.GraphQLInvocationData;\nimport org.dataloader.DataLoaderRegistry;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.context.request.WebRequest;\nimport com.viglet.shio.graphql.schema.ShGraphQLSchema;\nimport java.io.IOException;\nimport java.util.concurrent.CompletableFuture;\n\n@Component\npublic class ShDefaultGraphQLInvocation implements GraphQLInvocation {\n\n static final Logger logger = LogManager.getLogger(ShDefaultGraphQLInvocation.class);\n\n @Autowired\n GraphQL graphQL;\n\n @Autowired(required = false)\n DataLoaderRegistry dataLoaderRegistry;\n\n @Autowired\n ExecutionInputCustomizer executionInputCustomizer;\n\n @Autowired\n ShGraphQLSchema shGraphQLSchema;\n\n @Override\n public CompletableFuture invoke(GraphQLInvocationData invocationData, WebRequest webRequest) {\n ExecutionInput.Builder executionInputBuilder = ExecutionInput.newExecutionInput().query(invocationData.getQuery()).operationName(invocationData.getOperationName()).variables(invocationData.getVariables());\n ", "post_mask_code": "\n ExecutionInput executionInput = executionInputBuilder.build();\n CompletableFuture customizedExecutionInput = executionInputCustomizer.customizeExecutionInput(executionInput, webRequest);\n try {\n shGraphQLSchema.init();\n return customizedExecutionInput.thenCompose(shGraphQLSchema.graphQL()::executeAsync);\n } catch (IOException e) {\n logger.error(\"invoke\", e);\n }\n return customizedExecutionInput.thenCompose(graphQL::executeAsync);\n }\n}\n"} {"task_id": "Java_1198", "language": "Java", "task_type": "try_statement", "source_file": "java/github/ShioCMS/shio/src/main/java/com/viglet/shio/graphql/endpoint/ShDefaultGraphQLInvocation.java", "mask_start_position": 1835, "mask_end_position": 2057, "canonical_solution": "try {\n shGraphQLSchema.init();\n return customizedExecutionInput.thenCompose(shGraphQLSchema.graphQL()::executeAsync);\n } catch (IOException e) {\n logger.error(\"invoke\", e);\n }", "pre_mask_code": "package com.viglet.shio.graphql.endpoint;\n\nimport graphql.ExecutionInput;\nimport graphql.ExecutionResult;\nimport graphql.GraphQL;\nimport graphql.spring.web.servlet.ExecutionInputCustomizer;\nimport graphql.spring.web.servlet.GraphQLInvocation;\nimport graphql.spring.web.servlet.GraphQLInvocationData;\nimport org.dataloader.DataLoaderRegistry;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.context.request.WebRequest;\nimport com.viglet.shio.graphql.schema.ShGraphQLSchema;\nimport java.io.IOException;\nimport java.util.concurrent.CompletableFuture;\n\n@Component\npublic class ShDefaultGraphQLInvocation implements GraphQLInvocation {\n\n static final Logger logger = LogManager.getLogger(ShDefaultGraphQLInvocation.class);\n\n @Autowired\n GraphQL graphQL;\n\n @Autowired(required = false)\n DataLoaderRegistry dataLoaderRegistry;\n\n @Autowired\n ExecutionInputCustomizer executionInputCustomizer;\n\n @Autowired\n ShGraphQLSchema shGraphQLSchema;\n\n @Override\n public CompletableFuture invoke(GraphQLInvocationData invocationData, WebRequest webRequest) {\n ExecutionInput.Builder executionInputBuilder = ExecutionInput.newExecutionInput().query(invocationData.getQuery()).operationName(invocationData.getOperationName()).variables(invocationData.getVariables());\n if (dataLoaderRegistry != null) {\n executionInputBuilder.dataLoaderRegistry(dataLoaderRegistry);\n }\n ExecutionInput executionInput = executionInputBuilder.build();\n CompletableFuture customizedExecutionInput = executionInputCustomizer.customizeExecutionInput(executionInput, webRequest);\n ", "post_mask_code": "\n return customizedExecutionInput.thenCompose(graphQL::executeAsync);\n }\n}\n"} {"task_id": "Java_1199", "language": "Java", "task_type": "method_signature", "source_file": "java/github/oracle/graal/compiler/src/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/FloatingReadPhase.java", "mask_start_position": 17324, "mask_end_position": 17453, "canonical_solution": "@Override\n protected EconomicMap processLoop(LoopBeginNode loop, MemoryMapImpl initialState) ", "pre_mask_code": "package org.graalvm.compiler.phases.common;\n\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.NODE_ADDED;\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.ZERO_USAGES;\nimport static org.graalvm.word.LocationIdentity.any;\nimport java.util.EnumSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.graalvm.collections.EconomicMap;\nimport org.graalvm.collections.EconomicSet;\nimport org.graalvm.collections.Equivalence;\nimport org.graalvm.collections.UnmodifiableMapCursor;\nimport org.graalvm.compiler.core.common.cfg.Loop;\nimport org.graalvm.compiler.debug.DebugCloseable;\nimport org.graalvm.compiler.graph.Graph.NodeEventScope;\nimport org.graalvm.compiler.graph.Node;\nimport org.graalvm.compiler.nodes.AbstractBeginNode;\nimport org.graalvm.compiler.nodes.AbstractMergeNode;\nimport org.graalvm.compiler.nodes.FixedNode;\nimport org.graalvm.compiler.nodes.LoopBeginNode;\nimport org.graalvm.compiler.nodes.LoopEndNode;\nimport org.graalvm.compiler.nodes.LoopExitNode;\nimport org.graalvm.compiler.nodes.PhiNode;\nimport org.graalvm.compiler.nodes.ProxyNode;\nimport org.graalvm.compiler.nodes.ReturnNode;\nimport org.graalvm.compiler.nodes.StartNode;\nimport org.graalvm.compiler.nodes.StructuredGraph;\nimport org.graalvm.compiler.nodes.ValueNodeUtil;\nimport org.graalvm.compiler.nodes.WithExceptionNode;\nimport org.graalvm.compiler.nodes.StructuredGraph.StageFlag;\nimport org.graalvm.compiler.nodes.calc.FloatingNode;\nimport org.graalvm.compiler.nodes.cfg.Block;\nimport org.graalvm.compiler.nodes.cfg.ControlFlowGraph;\nimport org.graalvm.compiler.nodes.cfg.HIRLoop;\nimport org.graalvm.compiler.nodes.memory.FloatableAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingReadNode;\nimport org.graalvm.compiler.nodes.memory.MemoryAccess;\nimport org.graalvm.compiler.nodes.memory.MemoryAnchorNode;\nimport org.graalvm.compiler.nodes.memory.MemoryKill;\nimport org.graalvm.compiler.nodes.memory.MemoryMap;\nimport org.graalvm.compiler.nodes.memory.MemoryMapNode;\nimport org.graalvm.compiler.nodes.memory.MemoryPhiNode;\nimport org.graalvm.compiler.nodes.memory.MultiMemoryKill;\nimport org.graalvm.compiler.nodes.memory.ReadNode;\nimport org.graalvm.compiler.nodes.memory.SingleMemoryKill;\nimport org.graalvm.compiler.nodes.util.GraphUtil;\nimport org.graalvm.compiler.phases.Phase;\nimport org.graalvm.compiler.phases.common.util.EconomicSetNodeEventListener;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.LoopInfo;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.NodeIteratorClosure;\nimport org.graalvm.word.LocationIdentity;\n\npublic class FloatingReadPhase extends Phase {\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public static class MemoryMapImpl implements MemoryMap {\n\n private final EconomicMap lastMemorySnapshot;\n\n public MemoryMapImpl(MemoryMapImpl memoryMap) {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT, memoryMap.lastMemorySnapshot);\n }\n\n public MemoryMapImpl(StartNode start) {\n this();\n lastMemorySnapshot.put(any(), start);\n }\n\n public MemoryMapImpl() {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT);\n }\n\n @Override\n public MemoryKill getLastLocationAccess(LocationIdentity locationIdentity) {\n MemoryKill lastLocationAccess;\n if (locationIdentity.isImmutable()) {\n return null;\n } else {\n lastLocationAccess = lastMemorySnapshot.get(locationIdentity);\n if (lastLocationAccess == null) {\n lastLocationAccess = lastMemorySnapshot.get(any());\n assert lastLocationAccess != null;\n }\n return lastLocationAccess;\n }\n }\n\n @Override\n public Iterable getLocations() {\n return lastMemorySnapshot.getKeys();\n }\n\n public EconomicMap getMap() {\n return lastMemorySnapshot;\n }\n }\n\n public FloatingReadPhase() {\n this(true, false);\n }\n\n /**\n * @param createFloatingReads specifies whether {@link FloatableAccessNode}s like\n * {@link ReadNode} should be converted into floating nodes (e.g.,\n * {@link FloatingReadNode}s) where possible\n * @param createMemoryMapNodes a {@link MemoryMapNode} will be created for each return if this\n * is true\n */\n public FloatingReadPhase(boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n public float codeSizeIncrease() {\n return 1.50f;\n }\n\n /**\n * Removes nodes from a given set that (transitively) have a usage outside the set.\n */\n private static EconomicSet removeExternallyUsedNodes(EconomicSet set) {\n boolean change;\n do {\n change = false;\n for (Iterator iter = set.iterator(); iter.hasNext(); ) {\n Node node = iter.next();\n for (Node usage : node.usages()) {\n if (!set.contains(usage)) {\n change = true;\n iter.remove();\n break;\n }\n }\n }\n } while (change);\n return set;\n }\n\n protected void processNode(FixedNode node, EconomicSet currentState) {\n if (node instanceof SingleMemoryKill) {\n processIdentity(currentState, ((SingleMemoryKill) node).getKilledLocationIdentity());\n } else if (node instanceof MultiMemoryKill) {\n for (LocationIdentity identity : ((MultiMemoryKill) node).getKilledLocationIdentities()) {\n processIdentity(currentState, identity);\n }\n }\n }\n\n private static void processIdentity(EconomicSet currentState, LocationIdentity identity) {\n if (identity.isMutable()) {\n currentState.add(identity);\n }\n }\n\n protected void processBlock(Block b, EconomicSet currentState) {\n for (FixedNode n : b.getNodes()) {\n processNode(n, currentState);\n }\n }\n\n private EconomicSet processLoop(HIRLoop loop, EconomicMap> modifiedInLoops) {\n LoopBeginNode loopBegin = (LoopBeginNode) loop.getHeader().getBeginNode();\n EconomicSet result = modifiedInLoops.get(loopBegin);\n if (result != null) {\n return result;\n }\n result = EconomicSet.create(Equivalence.DEFAULT);\n for (Loop inner : loop.getChildren()) {\n result.addAll(processLoop((HIRLoop) inner, modifiedInLoops));\n }\n for (Block b : loop.getBlocks()) {\n if (b.getLoop() == loop) {\n processBlock(b, result);\n }\n }\n modifiedInLoops.put(loopBegin, result);\n return result;\n }\n\n @Override\n @SuppressWarnings(\"try\")\n protected void run(StructuredGraph graph) {\n EconomicMap> modifiedInLoops = null;\n if (graph.hasLoops()) {\n modifiedInLoops = EconomicMap.create(Equivalence.IDENTITY);\n ControlFlowGraph cfg = ControlFlowGraph.compute(graph, true, true, false, false);\n for (Loop l : cfg.getLoops()) {\n HIRLoop loop = (HIRLoop) l;\n processLoop(loop, modifiedInLoops);\n }\n }\n EconomicSetNodeEventListener listener = new EconomicSetNodeEventListener(EnumSet.of(NODE_ADDED, ZERO_USAGES));\n try (NodeEventScope nes = graph.trackNodeEvents(listener)) {\n ReentrantNodeIterator.apply(new FloatingReadClosure(modifiedInLoops, createFloatingReads, createMemoryMapNodes), graph.start(), new MemoryMapImpl(graph.start()));\n }\n for (Node n : removeExternallyUsedNodes(listener.getNodes())) {\n if (n.isAlive() && n instanceof FloatingNode) {\n n.replaceAtUsages(null);\n GraphUtil.killWithUnusedFloatingInputs(n);\n }\n }\n if (createFloatingReads) {\n assert graph.isBeforeStage(StageFlag.FLOATING_READS);\n graph.setAfterStage(StageFlag.FLOATING_READS);\n }\n }\n\n public static MemoryMapImpl mergeMemoryMaps(AbstractMergeNode merge, List states) {\n MemoryMapImpl newState = new MemoryMapImpl();\n EconomicSet keys = EconomicSet.create(Equivalence.DEFAULT);\n for (MemoryMap other : states) {\n keys.addAll(other.getLocations());\n }\n assert checkNoImmutableLocations(keys);\n for (LocationIdentity key : keys) {\n int mergedStatesCount = 0;\n boolean isPhi = false;\n MemoryKill merged = null;\n for (MemoryMap state : states) {\n MemoryKill last = state.getLastLocationAccess(key);\n if (isPhi) {\n // Fortify: Suppress Null Deference false positive (`isPhi == true` implies\n ((MemoryPhiNode) merged).addInput(ValueNodeUtil.asNode(last));\n } else {\n if (merged == last) {\n // nothing to do\n } else if (merged == null) {\n merged = last;\n } else {\n MemoryPhiNode phi = merge.graph().addWithoutUnique(new MemoryPhiNode(merge, key));\n for (int j = 0; j < mergedStatesCount; j++) {\n phi.addInput(ValueNodeUtil.asNode(merged));\n }\n phi.addInput(ValueNodeUtil.asNode(last));\n merged = phi;\n isPhi = true;\n }\n }\n mergedStatesCount++;\n }\n newState.getMap().put(key, merged);\n }\n return newState;\n }\n\n public static boolean nodeOfMemoryType(Node node) {\n return !(node instanceof MemoryKill) || (node instanceof SingleMemoryKill ^ node instanceof MultiMemoryKill);\n }\n\n private static boolean checkNoImmutableLocations(EconomicSet keys) {\n keys.forEach(t -> {\n assert t.isMutable();\n });\n return true;\n }\n\n public static class FloatingReadClosure extends NodeIteratorClosure {\n\n private final EconomicMap> modifiedInLoops;\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public FloatingReadClosure(EconomicMap> modifiedInLoops, boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.modifiedInLoops = modifiedInLoops;\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n protected MemoryMapImpl processNode(FixedNode node, MemoryMapImpl state) {\n if (node instanceof LoopExitNode) {\n final LoopExitNode loopExitNode = (LoopExitNode) node;\n final EconomicSet modifiedInLoop = modifiedInLoops.get(loopExitNode.loopBegin());\n final boolean anyModified = modifiedInLoop.contains(LocationIdentity.any());\n state.getMap().replaceAll((locationIdentity, memoryNode) -> (anyModified || modifiedInLoop.contains(locationIdentity)) ? ProxyNode.forMemory(memoryNode, loopExitNode, locationIdentity) : memoryNode);\n }\n if (node instanceof MemoryAnchorNode) {\n processAnchor((MemoryAnchorNode) node, state);\n return state;\n }\n if (node instanceof MemoryAccess) {\n processAccess((MemoryAccess) node, state);\n }\n if (createFloatingReads && node instanceof FloatableAccessNode) {\n processFloatable((FloatableAccessNode) node, state);\n }\n if (node instanceof SingleMemoryKill) {\n processCheckpoint((SingleMemoryKill) node, state);\n } else if (node instanceof MultiMemoryKill) {\n processCheckpoint((MultiMemoryKill) node, state);\n }\n assert nodeOfMemoryType(node) : node;\n if (createMemoryMapNodes && node instanceof ReturnNode) {\n ((ReturnNode) node).setMemoryMap(node.graph().unique(new MemoryMapNode(state.getMap())));\n }\n return state;\n }\n\n /**\n * Improve the memory graph by re-wiring all usages of a {@link MemoryAnchorNode} to the\n * real last access location.\n */\n private static void processAnchor(MemoryAnchorNode anchor, MemoryMapImpl state) {\n for (Node node : anchor.usages().snapshot()) {\n if (node instanceof MemoryAccess) {\n MemoryAccess access = (MemoryAccess) node;\n if (access.getLastLocationAccess() == anchor) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(access.getLocationIdentity());\n assert lastLocationAccess != null;\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n }\n if (anchor.hasNoUsages()) {\n anchor.graph().removeFixed(anchor);\n }\n }\n\n private static void processAccess(MemoryAccess access, MemoryMapImpl state) {\n LocationIdentity locationIdentity = access.getLocationIdentity();\n if (!locationIdentity.equals(LocationIdentity.any())) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n\n private static void processCheckpoint(SingleMemoryKill checkpoint, MemoryMapImpl state) {\n processIdentity(checkpoint.getKilledLocationIdentity(), checkpoint, state);\n }\n\n private static void processCheckpoint(MultiMemoryKill checkpoint, MemoryMapImpl state) {\n for (LocationIdentity identity : checkpoint.getKilledLocationIdentities()) {\n processIdentity(identity, checkpoint, state);\n }\n }\n\n private static void processIdentity(LocationIdentity identity, MemoryKill checkpoint, MemoryMapImpl state) {\n if (identity.isAny()) {\n state.getMap().clear();\n }\n if (identity.isMutable()) {\n state.getMap().put(identity, checkpoint);\n }\n }\n\n @SuppressWarnings(\"try\")\n private static void processFloatable(FloatableAccessNode accessNode, MemoryMapImpl state) {\n StructuredGraph graph = accessNode.graph();\n LocationIdentity locationIdentity = accessNode.getLocationIdentity();\n if (accessNode.canFloat()) {\n assert accessNode.getNullCheck() == false;\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n try (DebugCloseable position = accessNode.withNodeSourcePosition()) {\n FloatingAccessNode floatingNode = accessNode.asFloatingNode();\n assert floatingNode.getLastLocationAccess() == lastLocationAccess;\n graph.replaceFixedWithFloating(accessNode, floatingNode);\n }\n }\n }\n\n @Override\n protected MemoryMapImpl merge(AbstractMergeNode merge, List states) {\n return mergeMemoryMaps(merge, states);\n }\n\n @Override\n protected MemoryMapImpl afterSplit(AbstractBeginNode node, MemoryMapImpl oldState) {\n MemoryMapImpl result = new MemoryMapImpl(oldState);\n if (node.predecessor() instanceof WithExceptionNode && node.predecessor() instanceof MemoryKill) {\n /*\n * This WithExceptionNode cannot be the lastLocationAccess for a FloatingReadNode.\n * Since it is both a memory kill and a control flow split, the scheduler cannot\n * schedule anything immediately after the kill. It can only schedule in the normal\n * or exceptional successor - and we have to tell the scheduler here which side it\n * needs to choose by putting in the location identity on both successors.\n */\n LocationIdentity killedLocationIdentity = node.predecessor() instanceof SingleMemoryKill ? ((SingleMemoryKill) node.predecessor()).getKilledLocationIdentity() : LocationIdentity.any();\n result.getMap().put(killedLocationIdentity, (MemoryKill) node);\n }\n return result;\n }\n\n ", "post_mask_code": "{\n EconomicSet modifiedLocations = modifiedInLoops.get(loop);\n EconomicMap phis = EconomicMap.create(Equivalence.DEFAULT);\n if (modifiedLocations.contains(LocationIdentity.any())) {\n // create phis for all locations if ANY is modified in the loop\n modifiedLocations = EconomicSet.create(Equivalence.DEFAULT, modifiedLocations);\n modifiedLocations.addAll(initialState.getMap().getKeys());\n }\n for (LocationIdentity location : modifiedLocations) {\n createMemoryPhi(loop, initialState, phis, location);\n }\n initialState.getMap().putAll(phis);\n LoopInfo loopInfo = ReentrantNodeIterator.processLoop(this, loop, initialState);\n UnmodifiableMapCursor endStateCursor = loopInfo.endStates.getEntries();\n while (endStateCursor.advance()) {\n int endIndex = loop.phiPredecessorIndex(endStateCursor.getKey());\n UnmodifiableMapCursor phiCursor = phis.getEntries();\n while (phiCursor.advance()) {\n LocationIdentity key = phiCursor.getKey();\n PhiNode phi = phiCursor.getValue();\n phi.initializeValueAt(endIndex, ValueNodeUtil.asNode(endStateCursor.getValue().getLastLocationAccess(key)));\n }\n }\n return loopInfo.exitStates;\n }\n\n private static void createMemoryPhi(LoopBeginNode loop, MemoryMapImpl initialState, EconomicMap phis, LocationIdentity location) {\n MemoryPhiNode phi = loop.graph().addWithoutUnique(new MemoryPhiNode(loop, location));\n phi.addInput(ValueNodeUtil.asNode(initialState.getLastLocationAccess(location)));\n phis.put(location, phi);\n }\n }\n}\n"} {"task_id": "Java_1200", "language": "Java", "task_type": "method_body", "source_file": "java/github/oracle/graal/compiler/src/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/FloatingReadPhase.java", "mask_start_position": 16108, "mask_end_position": 16170, "canonical_solution": "{\n return mergeMemoryMaps(merge, states);\n }", "pre_mask_code": "package org.graalvm.compiler.phases.common;\n\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.NODE_ADDED;\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.ZERO_USAGES;\nimport static org.graalvm.word.LocationIdentity.any;\nimport java.util.EnumSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.graalvm.collections.EconomicMap;\nimport org.graalvm.collections.EconomicSet;\nimport org.graalvm.collections.Equivalence;\nimport org.graalvm.collections.UnmodifiableMapCursor;\nimport org.graalvm.compiler.core.common.cfg.Loop;\nimport org.graalvm.compiler.debug.DebugCloseable;\nimport org.graalvm.compiler.graph.Graph.NodeEventScope;\nimport org.graalvm.compiler.graph.Node;\nimport org.graalvm.compiler.nodes.AbstractBeginNode;\nimport org.graalvm.compiler.nodes.AbstractMergeNode;\nimport org.graalvm.compiler.nodes.FixedNode;\nimport org.graalvm.compiler.nodes.LoopBeginNode;\nimport org.graalvm.compiler.nodes.LoopEndNode;\nimport org.graalvm.compiler.nodes.LoopExitNode;\nimport org.graalvm.compiler.nodes.PhiNode;\nimport org.graalvm.compiler.nodes.ProxyNode;\nimport org.graalvm.compiler.nodes.ReturnNode;\nimport org.graalvm.compiler.nodes.StartNode;\nimport org.graalvm.compiler.nodes.StructuredGraph;\nimport org.graalvm.compiler.nodes.ValueNodeUtil;\nimport org.graalvm.compiler.nodes.WithExceptionNode;\nimport org.graalvm.compiler.nodes.StructuredGraph.StageFlag;\nimport org.graalvm.compiler.nodes.calc.FloatingNode;\nimport org.graalvm.compiler.nodes.cfg.Block;\nimport org.graalvm.compiler.nodes.cfg.ControlFlowGraph;\nimport org.graalvm.compiler.nodes.cfg.HIRLoop;\nimport org.graalvm.compiler.nodes.memory.FloatableAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingReadNode;\nimport org.graalvm.compiler.nodes.memory.MemoryAccess;\nimport org.graalvm.compiler.nodes.memory.MemoryAnchorNode;\nimport org.graalvm.compiler.nodes.memory.MemoryKill;\nimport org.graalvm.compiler.nodes.memory.MemoryMap;\nimport org.graalvm.compiler.nodes.memory.MemoryMapNode;\nimport org.graalvm.compiler.nodes.memory.MemoryPhiNode;\nimport org.graalvm.compiler.nodes.memory.MultiMemoryKill;\nimport org.graalvm.compiler.nodes.memory.ReadNode;\nimport org.graalvm.compiler.nodes.memory.SingleMemoryKill;\nimport org.graalvm.compiler.nodes.util.GraphUtil;\nimport org.graalvm.compiler.phases.Phase;\nimport org.graalvm.compiler.phases.common.util.EconomicSetNodeEventListener;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.LoopInfo;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.NodeIteratorClosure;\nimport org.graalvm.word.LocationIdentity;\n\npublic class FloatingReadPhase extends Phase {\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public static class MemoryMapImpl implements MemoryMap {\n\n private final EconomicMap lastMemorySnapshot;\n\n public MemoryMapImpl(MemoryMapImpl memoryMap) {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT, memoryMap.lastMemorySnapshot);\n }\n\n public MemoryMapImpl(StartNode start) {\n this();\n lastMemorySnapshot.put(any(), start);\n }\n\n public MemoryMapImpl() {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT);\n }\n\n @Override\n public MemoryKill getLastLocationAccess(LocationIdentity locationIdentity) {\n MemoryKill lastLocationAccess;\n if (locationIdentity.isImmutable()) {\n return null;\n } else {\n lastLocationAccess = lastMemorySnapshot.get(locationIdentity);\n if (lastLocationAccess == null) {\n lastLocationAccess = lastMemorySnapshot.get(any());\n assert lastLocationAccess != null;\n }\n return lastLocationAccess;\n }\n }\n\n @Override\n public Iterable getLocations() {\n return lastMemorySnapshot.getKeys();\n }\n\n public EconomicMap getMap() {\n return lastMemorySnapshot;\n }\n }\n\n public FloatingReadPhase() {\n this(true, false);\n }\n\n /**\n * @param createFloatingReads specifies whether {@link FloatableAccessNode}s like\n * {@link ReadNode} should be converted into floating nodes (e.g.,\n * {@link FloatingReadNode}s) where possible\n * @param createMemoryMapNodes a {@link MemoryMapNode} will be created for each return if this\n * is true\n */\n public FloatingReadPhase(boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n public float codeSizeIncrease() {\n return 1.50f;\n }\n\n /**\n * Removes nodes from a given set that (transitively) have a usage outside the set.\n */\n private static EconomicSet removeExternallyUsedNodes(EconomicSet set) {\n boolean change;\n do {\n change = false;\n for (Iterator iter = set.iterator(); iter.hasNext(); ) {\n Node node = iter.next();\n for (Node usage : node.usages()) {\n if (!set.contains(usage)) {\n change = true;\n iter.remove();\n break;\n }\n }\n }\n } while (change);\n return set;\n }\n\n protected void processNode(FixedNode node, EconomicSet currentState) {\n if (node instanceof SingleMemoryKill) {\n processIdentity(currentState, ((SingleMemoryKill) node).getKilledLocationIdentity());\n } else if (node instanceof MultiMemoryKill) {\n for (LocationIdentity identity : ((MultiMemoryKill) node).getKilledLocationIdentities()) {\n processIdentity(currentState, identity);\n }\n }\n }\n\n private static void processIdentity(EconomicSet currentState, LocationIdentity identity) {\n if (identity.isMutable()) {\n currentState.add(identity);\n }\n }\n\n protected void processBlock(Block b, EconomicSet currentState) {\n for (FixedNode n : b.getNodes()) {\n processNode(n, currentState);\n }\n }\n\n private EconomicSet processLoop(HIRLoop loop, EconomicMap> modifiedInLoops) {\n LoopBeginNode loopBegin = (LoopBeginNode) loop.getHeader().getBeginNode();\n EconomicSet result = modifiedInLoops.get(loopBegin);\n if (result != null) {\n return result;\n }\n result = EconomicSet.create(Equivalence.DEFAULT);\n for (Loop inner : loop.getChildren()) {\n result.addAll(processLoop((HIRLoop) inner, modifiedInLoops));\n }\n for (Block b : loop.getBlocks()) {\n if (b.getLoop() == loop) {\n processBlock(b, result);\n }\n }\n modifiedInLoops.put(loopBegin, result);\n return result;\n }\n\n @Override\n @SuppressWarnings(\"try\")\n protected void run(StructuredGraph graph) {\n EconomicMap> modifiedInLoops = null;\n if (graph.hasLoops()) {\n modifiedInLoops = EconomicMap.create(Equivalence.IDENTITY);\n ControlFlowGraph cfg = ControlFlowGraph.compute(graph, true, true, false, false);\n for (Loop l : cfg.getLoops()) {\n HIRLoop loop = (HIRLoop) l;\n processLoop(loop, modifiedInLoops);\n }\n }\n EconomicSetNodeEventListener listener = new EconomicSetNodeEventListener(EnumSet.of(NODE_ADDED, ZERO_USAGES));\n try (NodeEventScope nes = graph.trackNodeEvents(listener)) {\n ReentrantNodeIterator.apply(new FloatingReadClosure(modifiedInLoops, createFloatingReads, createMemoryMapNodes), graph.start(), new MemoryMapImpl(graph.start()));\n }\n for (Node n : removeExternallyUsedNodes(listener.getNodes())) {\n if (n.isAlive() && n instanceof FloatingNode) {\n n.replaceAtUsages(null);\n GraphUtil.killWithUnusedFloatingInputs(n);\n }\n }\n if (createFloatingReads) {\n assert graph.isBeforeStage(StageFlag.FLOATING_READS);\n graph.setAfterStage(StageFlag.FLOATING_READS);\n }\n }\n\n public static MemoryMapImpl mergeMemoryMaps(AbstractMergeNode merge, List states) {\n MemoryMapImpl newState = new MemoryMapImpl();\n EconomicSet keys = EconomicSet.create(Equivalence.DEFAULT);\n for (MemoryMap other : states) {\n keys.addAll(other.getLocations());\n }\n assert checkNoImmutableLocations(keys);\n for (LocationIdentity key : keys) {\n int mergedStatesCount = 0;\n boolean isPhi = false;\n MemoryKill merged = null;\n for (MemoryMap state : states) {\n MemoryKill last = state.getLastLocationAccess(key);\n if (isPhi) {\n // Fortify: Suppress Null Deference false positive (`isPhi == true` implies\n ((MemoryPhiNode) merged).addInput(ValueNodeUtil.asNode(last));\n } else {\n if (merged == last) {\n // nothing to do\n } else if (merged == null) {\n merged = last;\n } else {\n MemoryPhiNode phi = merge.graph().addWithoutUnique(new MemoryPhiNode(merge, key));\n for (int j = 0; j < mergedStatesCount; j++) {\n phi.addInput(ValueNodeUtil.asNode(merged));\n }\n phi.addInput(ValueNodeUtil.asNode(last));\n merged = phi;\n isPhi = true;\n }\n }\n mergedStatesCount++;\n }\n newState.getMap().put(key, merged);\n }\n return newState;\n }\n\n public static boolean nodeOfMemoryType(Node node) {\n return !(node instanceof MemoryKill) || (node instanceof SingleMemoryKill ^ node instanceof MultiMemoryKill);\n }\n\n private static boolean checkNoImmutableLocations(EconomicSet keys) {\n keys.forEach(t -> {\n assert t.isMutable();\n });\n return true;\n }\n\n public static class FloatingReadClosure extends NodeIteratorClosure {\n\n private final EconomicMap> modifiedInLoops;\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public FloatingReadClosure(EconomicMap> modifiedInLoops, boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.modifiedInLoops = modifiedInLoops;\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n protected MemoryMapImpl processNode(FixedNode node, MemoryMapImpl state) {\n if (node instanceof LoopExitNode) {\n final LoopExitNode loopExitNode = (LoopExitNode) node;\n final EconomicSet modifiedInLoop = modifiedInLoops.get(loopExitNode.loopBegin());\n final boolean anyModified = modifiedInLoop.contains(LocationIdentity.any());\n state.getMap().replaceAll((locationIdentity, memoryNode) -> (anyModified || modifiedInLoop.contains(locationIdentity)) ? ProxyNode.forMemory(memoryNode, loopExitNode, locationIdentity) : memoryNode);\n }\n if (node instanceof MemoryAnchorNode) {\n processAnchor((MemoryAnchorNode) node, state);\n return state;\n }\n if (node instanceof MemoryAccess) {\n processAccess((MemoryAccess) node, state);\n }\n if (createFloatingReads && node instanceof FloatableAccessNode) {\n processFloatable((FloatableAccessNode) node, state);\n }\n if (node instanceof SingleMemoryKill) {\n processCheckpoint((SingleMemoryKill) node, state);\n } else if (node instanceof MultiMemoryKill) {\n processCheckpoint((MultiMemoryKill) node, state);\n }\n assert nodeOfMemoryType(node) : node;\n if (createMemoryMapNodes && node instanceof ReturnNode) {\n ((ReturnNode) node).setMemoryMap(node.graph().unique(new MemoryMapNode(state.getMap())));\n }\n return state;\n }\n\n /**\n * Improve the memory graph by re-wiring all usages of a {@link MemoryAnchorNode} to the\n * real last access location.\n */\n private static void processAnchor(MemoryAnchorNode anchor, MemoryMapImpl state) {\n for (Node node : anchor.usages().snapshot()) {\n if (node instanceof MemoryAccess) {\n MemoryAccess access = (MemoryAccess) node;\n if (access.getLastLocationAccess() == anchor) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(access.getLocationIdentity());\n assert lastLocationAccess != null;\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n }\n if (anchor.hasNoUsages()) {\n anchor.graph().removeFixed(anchor);\n }\n }\n\n private static void processAccess(MemoryAccess access, MemoryMapImpl state) {\n LocationIdentity locationIdentity = access.getLocationIdentity();\n if (!locationIdentity.equals(LocationIdentity.any())) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n\n private static void processCheckpoint(SingleMemoryKill checkpoint, MemoryMapImpl state) {\n processIdentity(checkpoint.getKilledLocationIdentity(), checkpoint, state);\n }\n\n private static void processCheckpoint(MultiMemoryKill checkpoint, MemoryMapImpl state) {\n for (LocationIdentity identity : checkpoint.getKilledLocationIdentities()) {\n processIdentity(identity, checkpoint, state);\n }\n }\n\n private static void processIdentity(LocationIdentity identity, MemoryKill checkpoint, MemoryMapImpl state) {\n if (identity.isAny()) {\n state.getMap().clear();\n }\n if (identity.isMutable()) {\n state.getMap().put(identity, checkpoint);\n }\n }\n\n @SuppressWarnings(\"try\")\n private static void processFloatable(FloatableAccessNode accessNode, MemoryMapImpl state) {\n StructuredGraph graph = accessNode.graph();\n LocationIdentity locationIdentity = accessNode.getLocationIdentity();\n if (accessNode.canFloat()) {\n assert accessNode.getNullCheck() == false;\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n try (DebugCloseable position = accessNode.withNodeSourcePosition()) {\n FloatingAccessNode floatingNode = accessNode.asFloatingNode();\n assert floatingNode.getLastLocationAccess() == lastLocationAccess;\n graph.replaceFixedWithFloating(accessNode, floatingNode);\n }\n }\n }\n\n @Override\n protected MemoryMapImpl merge(AbstractMergeNode merge, List states) ", "post_mask_code": "\n\n @Override\n protected MemoryMapImpl afterSplit(AbstractBeginNode node, MemoryMapImpl oldState) {\n MemoryMapImpl result = new MemoryMapImpl(oldState);\n if (node.predecessor() instanceof WithExceptionNode && node.predecessor() instanceof MemoryKill) {\n /*\n * This WithExceptionNode cannot be the lastLocationAccess for a FloatingReadNode.\n * Since it is both a memory kill and a control flow split, the scheduler cannot\n * schedule anything immediately after the kill. It can only schedule in the normal\n * or exceptional successor - and we have to tell the scheduler here which side it\n * needs to choose by putting in the location identity on both successors.\n */\n LocationIdentity killedLocationIdentity = node.predecessor() instanceof SingleMemoryKill ? ((SingleMemoryKill) node.predecessor()).getKilledLocationIdentity() : LocationIdentity.any();\n result.getMap().put(killedLocationIdentity, (MemoryKill) node);\n }\n return result;\n }\n\n @Override\n protected EconomicMap processLoop(LoopBeginNode loop, MemoryMapImpl initialState) {\n EconomicSet modifiedLocations = modifiedInLoops.get(loop);\n EconomicMap phis = EconomicMap.create(Equivalence.DEFAULT);\n if (modifiedLocations.contains(LocationIdentity.any())) {\n // create phis for all locations if ANY is modified in the loop\n modifiedLocations = EconomicSet.create(Equivalence.DEFAULT, modifiedLocations);\n modifiedLocations.addAll(initialState.getMap().getKeys());\n }\n for (LocationIdentity location : modifiedLocations) {\n createMemoryPhi(loop, initialState, phis, location);\n }\n initialState.getMap().putAll(phis);\n LoopInfo loopInfo = ReentrantNodeIterator.processLoop(this, loop, initialState);\n UnmodifiableMapCursor endStateCursor = loopInfo.endStates.getEntries();\n while (endStateCursor.advance()) {\n int endIndex = loop.phiPredecessorIndex(endStateCursor.getKey());\n UnmodifiableMapCursor phiCursor = phis.getEntries();\n while (phiCursor.advance()) {\n LocationIdentity key = phiCursor.getKey();\n PhiNode phi = phiCursor.getValue();\n phi.initializeValueAt(endIndex, ValueNodeUtil.asNode(endStateCursor.getValue().getLastLocationAccess(key)));\n }\n }\n return loopInfo.exitStates;\n }\n\n private static void createMemoryPhi(LoopBeginNode loop, MemoryMapImpl initialState, EconomicMap phis, LocationIdentity location) {\n MemoryPhiNode phi = loop.graph().addWithoutUnique(new MemoryPhiNode(loop, location));\n phi.addInput(ValueNodeUtil.asNode(initialState.getLastLocationAccess(location)));\n phis.put(location, phi);\n }\n }\n}\n"} {"task_id": "Java_1201", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/oracle/graal/compiler/src/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/FloatingReadPhase.java", "mask_start_position": 16282, "mask_end_position": 16346, "canonical_solution": "\n MemoryMapImpl result = new MemoryMapImpl(oldState);", "pre_mask_code": "package org.graalvm.compiler.phases.common;\n\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.NODE_ADDED;\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.ZERO_USAGES;\nimport static org.graalvm.word.LocationIdentity.any;\nimport java.util.EnumSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.graalvm.collections.EconomicMap;\nimport org.graalvm.collections.EconomicSet;\nimport org.graalvm.collections.Equivalence;\nimport org.graalvm.collections.UnmodifiableMapCursor;\nimport org.graalvm.compiler.core.common.cfg.Loop;\nimport org.graalvm.compiler.debug.DebugCloseable;\nimport org.graalvm.compiler.graph.Graph.NodeEventScope;\nimport org.graalvm.compiler.graph.Node;\nimport org.graalvm.compiler.nodes.AbstractBeginNode;\nimport org.graalvm.compiler.nodes.AbstractMergeNode;\nimport org.graalvm.compiler.nodes.FixedNode;\nimport org.graalvm.compiler.nodes.LoopBeginNode;\nimport org.graalvm.compiler.nodes.LoopEndNode;\nimport org.graalvm.compiler.nodes.LoopExitNode;\nimport org.graalvm.compiler.nodes.PhiNode;\nimport org.graalvm.compiler.nodes.ProxyNode;\nimport org.graalvm.compiler.nodes.ReturnNode;\nimport org.graalvm.compiler.nodes.StartNode;\nimport org.graalvm.compiler.nodes.StructuredGraph;\nimport org.graalvm.compiler.nodes.ValueNodeUtil;\nimport org.graalvm.compiler.nodes.WithExceptionNode;\nimport org.graalvm.compiler.nodes.StructuredGraph.StageFlag;\nimport org.graalvm.compiler.nodes.calc.FloatingNode;\nimport org.graalvm.compiler.nodes.cfg.Block;\nimport org.graalvm.compiler.nodes.cfg.ControlFlowGraph;\nimport org.graalvm.compiler.nodes.cfg.HIRLoop;\nimport org.graalvm.compiler.nodes.memory.FloatableAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingReadNode;\nimport org.graalvm.compiler.nodes.memory.MemoryAccess;\nimport org.graalvm.compiler.nodes.memory.MemoryAnchorNode;\nimport org.graalvm.compiler.nodes.memory.MemoryKill;\nimport org.graalvm.compiler.nodes.memory.MemoryMap;\nimport org.graalvm.compiler.nodes.memory.MemoryMapNode;\nimport org.graalvm.compiler.nodes.memory.MemoryPhiNode;\nimport org.graalvm.compiler.nodes.memory.MultiMemoryKill;\nimport org.graalvm.compiler.nodes.memory.ReadNode;\nimport org.graalvm.compiler.nodes.memory.SingleMemoryKill;\nimport org.graalvm.compiler.nodes.util.GraphUtil;\nimport org.graalvm.compiler.phases.Phase;\nimport org.graalvm.compiler.phases.common.util.EconomicSetNodeEventListener;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.LoopInfo;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.NodeIteratorClosure;\nimport org.graalvm.word.LocationIdentity;\n\npublic class FloatingReadPhase extends Phase {\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public static class MemoryMapImpl implements MemoryMap {\n\n private final EconomicMap lastMemorySnapshot;\n\n public MemoryMapImpl(MemoryMapImpl memoryMap) {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT, memoryMap.lastMemorySnapshot);\n }\n\n public MemoryMapImpl(StartNode start) {\n this();\n lastMemorySnapshot.put(any(), start);\n }\n\n public MemoryMapImpl() {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT);\n }\n\n @Override\n public MemoryKill getLastLocationAccess(LocationIdentity locationIdentity) {\n MemoryKill lastLocationAccess;\n if (locationIdentity.isImmutable()) {\n return null;\n } else {\n lastLocationAccess = lastMemorySnapshot.get(locationIdentity);\n if (lastLocationAccess == null) {\n lastLocationAccess = lastMemorySnapshot.get(any());\n assert lastLocationAccess != null;\n }\n return lastLocationAccess;\n }\n }\n\n @Override\n public Iterable getLocations() {\n return lastMemorySnapshot.getKeys();\n }\n\n public EconomicMap getMap() {\n return lastMemorySnapshot;\n }\n }\n\n public FloatingReadPhase() {\n this(true, false);\n }\n\n /**\n * @param createFloatingReads specifies whether {@link FloatableAccessNode}s like\n * {@link ReadNode} should be converted into floating nodes (e.g.,\n * {@link FloatingReadNode}s) where possible\n * @param createMemoryMapNodes a {@link MemoryMapNode} will be created for each return if this\n * is true\n */\n public FloatingReadPhase(boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n public float codeSizeIncrease() {\n return 1.50f;\n }\n\n /**\n * Removes nodes from a given set that (transitively) have a usage outside the set.\n */\n private static EconomicSet removeExternallyUsedNodes(EconomicSet set) {\n boolean change;\n do {\n change = false;\n for (Iterator iter = set.iterator(); iter.hasNext(); ) {\n Node node = iter.next();\n for (Node usage : node.usages()) {\n if (!set.contains(usage)) {\n change = true;\n iter.remove();\n break;\n }\n }\n }\n } while (change);\n return set;\n }\n\n protected void processNode(FixedNode node, EconomicSet currentState) {\n if (node instanceof SingleMemoryKill) {\n processIdentity(currentState, ((SingleMemoryKill) node).getKilledLocationIdentity());\n } else if (node instanceof MultiMemoryKill) {\n for (LocationIdentity identity : ((MultiMemoryKill) node).getKilledLocationIdentities()) {\n processIdentity(currentState, identity);\n }\n }\n }\n\n private static void processIdentity(EconomicSet currentState, LocationIdentity identity) {\n if (identity.isMutable()) {\n currentState.add(identity);\n }\n }\n\n protected void processBlock(Block b, EconomicSet currentState) {\n for (FixedNode n : b.getNodes()) {\n processNode(n, currentState);\n }\n }\n\n private EconomicSet processLoop(HIRLoop loop, EconomicMap> modifiedInLoops) {\n LoopBeginNode loopBegin = (LoopBeginNode) loop.getHeader().getBeginNode();\n EconomicSet result = modifiedInLoops.get(loopBegin);\n if (result != null) {\n return result;\n }\n result = EconomicSet.create(Equivalence.DEFAULT);\n for (Loop inner : loop.getChildren()) {\n result.addAll(processLoop((HIRLoop) inner, modifiedInLoops));\n }\n for (Block b : loop.getBlocks()) {\n if (b.getLoop() == loop) {\n processBlock(b, result);\n }\n }\n modifiedInLoops.put(loopBegin, result);\n return result;\n }\n\n @Override\n @SuppressWarnings(\"try\")\n protected void run(StructuredGraph graph) {\n EconomicMap> modifiedInLoops = null;\n if (graph.hasLoops()) {\n modifiedInLoops = EconomicMap.create(Equivalence.IDENTITY);\n ControlFlowGraph cfg = ControlFlowGraph.compute(graph, true, true, false, false);\n for (Loop l : cfg.getLoops()) {\n HIRLoop loop = (HIRLoop) l;\n processLoop(loop, modifiedInLoops);\n }\n }\n EconomicSetNodeEventListener listener = new EconomicSetNodeEventListener(EnumSet.of(NODE_ADDED, ZERO_USAGES));\n try (NodeEventScope nes = graph.trackNodeEvents(listener)) {\n ReentrantNodeIterator.apply(new FloatingReadClosure(modifiedInLoops, createFloatingReads, createMemoryMapNodes), graph.start(), new MemoryMapImpl(graph.start()));\n }\n for (Node n : removeExternallyUsedNodes(listener.getNodes())) {\n if (n.isAlive() && n instanceof FloatingNode) {\n n.replaceAtUsages(null);\n GraphUtil.killWithUnusedFloatingInputs(n);\n }\n }\n if (createFloatingReads) {\n assert graph.isBeforeStage(StageFlag.FLOATING_READS);\n graph.setAfterStage(StageFlag.FLOATING_READS);\n }\n }\n\n public static MemoryMapImpl mergeMemoryMaps(AbstractMergeNode merge, List states) {\n MemoryMapImpl newState = new MemoryMapImpl();\n EconomicSet keys = EconomicSet.create(Equivalence.DEFAULT);\n for (MemoryMap other : states) {\n keys.addAll(other.getLocations());\n }\n assert checkNoImmutableLocations(keys);\n for (LocationIdentity key : keys) {\n int mergedStatesCount = 0;\n boolean isPhi = false;\n MemoryKill merged = null;\n for (MemoryMap state : states) {\n MemoryKill last = state.getLastLocationAccess(key);\n if (isPhi) {\n // Fortify: Suppress Null Deference false positive (`isPhi == true` implies\n ((MemoryPhiNode) merged).addInput(ValueNodeUtil.asNode(last));\n } else {\n if (merged == last) {\n // nothing to do\n } else if (merged == null) {\n merged = last;\n } else {\n MemoryPhiNode phi = merge.graph().addWithoutUnique(new MemoryPhiNode(merge, key));\n for (int j = 0; j < mergedStatesCount; j++) {\n phi.addInput(ValueNodeUtil.asNode(merged));\n }\n phi.addInput(ValueNodeUtil.asNode(last));\n merged = phi;\n isPhi = true;\n }\n }\n mergedStatesCount++;\n }\n newState.getMap().put(key, merged);\n }\n return newState;\n }\n\n public static boolean nodeOfMemoryType(Node node) {\n return !(node instanceof MemoryKill) || (node instanceof SingleMemoryKill ^ node instanceof MultiMemoryKill);\n }\n\n private static boolean checkNoImmutableLocations(EconomicSet keys) {\n keys.forEach(t -> {\n assert t.isMutable();\n });\n return true;\n }\n\n public static class FloatingReadClosure extends NodeIteratorClosure {\n\n private final EconomicMap> modifiedInLoops;\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public FloatingReadClosure(EconomicMap> modifiedInLoops, boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.modifiedInLoops = modifiedInLoops;\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n protected MemoryMapImpl processNode(FixedNode node, MemoryMapImpl state) {\n if (node instanceof LoopExitNode) {\n final LoopExitNode loopExitNode = (LoopExitNode) node;\n final EconomicSet modifiedInLoop = modifiedInLoops.get(loopExitNode.loopBegin());\n final boolean anyModified = modifiedInLoop.contains(LocationIdentity.any());\n state.getMap().replaceAll((locationIdentity, memoryNode) -> (anyModified || modifiedInLoop.contains(locationIdentity)) ? ProxyNode.forMemory(memoryNode, loopExitNode, locationIdentity) : memoryNode);\n }\n if (node instanceof MemoryAnchorNode) {\n processAnchor((MemoryAnchorNode) node, state);\n return state;\n }\n if (node instanceof MemoryAccess) {\n processAccess((MemoryAccess) node, state);\n }\n if (createFloatingReads && node instanceof FloatableAccessNode) {\n processFloatable((FloatableAccessNode) node, state);\n }\n if (node instanceof SingleMemoryKill) {\n processCheckpoint((SingleMemoryKill) node, state);\n } else if (node instanceof MultiMemoryKill) {\n processCheckpoint((MultiMemoryKill) node, state);\n }\n assert nodeOfMemoryType(node) : node;\n if (createMemoryMapNodes && node instanceof ReturnNode) {\n ((ReturnNode) node).setMemoryMap(node.graph().unique(new MemoryMapNode(state.getMap())));\n }\n return state;\n }\n\n /**\n * Improve the memory graph by re-wiring all usages of a {@link MemoryAnchorNode} to the\n * real last access location.\n */\n private static void processAnchor(MemoryAnchorNode anchor, MemoryMapImpl state) {\n for (Node node : anchor.usages().snapshot()) {\n if (node instanceof MemoryAccess) {\n MemoryAccess access = (MemoryAccess) node;\n if (access.getLastLocationAccess() == anchor) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(access.getLocationIdentity());\n assert lastLocationAccess != null;\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n }\n if (anchor.hasNoUsages()) {\n anchor.graph().removeFixed(anchor);\n }\n }\n\n private static void processAccess(MemoryAccess access, MemoryMapImpl state) {\n LocationIdentity locationIdentity = access.getLocationIdentity();\n if (!locationIdentity.equals(LocationIdentity.any())) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n\n private static void processCheckpoint(SingleMemoryKill checkpoint, MemoryMapImpl state) {\n processIdentity(checkpoint.getKilledLocationIdentity(), checkpoint, state);\n }\n\n private static void processCheckpoint(MultiMemoryKill checkpoint, MemoryMapImpl state) {\n for (LocationIdentity identity : checkpoint.getKilledLocationIdentities()) {\n processIdentity(identity, checkpoint, state);\n }\n }\n\n private static void processIdentity(LocationIdentity identity, MemoryKill checkpoint, MemoryMapImpl state) {\n if (identity.isAny()) {\n state.getMap().clear();\n }\n if (identity.isMutable()) {\n state.getMap().put(identity, checkpoint);\n }\n }\n\n @SuppressWarnings(\"try\")\n private static void processFloatable(FloatableAccessNode accessNode, MemoryMapImpl state) {\n StructuredGraph graph = accessNode.graph();\n LocationIdentity locationIdentity = accessNode.getLocationIdentity();\n if (accessNode.canFloat()) {\n assert accessNode.getNullCheck() == false;\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n try (DebugCloseable position = accessNode.withNodeSourcePosition()) {\n FloatingAccessNode floatingNode = accessNode.asFloatingNode();\n assert floatingNode.getLastLocationAccess() == lastLocationAccess;\n graph.replaceFixedWithFloating(accessNode, floatingNode);\n }\n }\n }\n\n @Override\n protected MemoryMapImpl merge(AbstractMergeNode merge, List states) {\n return mergeMemoryMaps(merge, states);\n }\n\n @Override\n protected MemoryMapImpl afterSplit(AbstractBeginNode node, MemoryMapImpl oldState) {", "post_mask_code": "\n if (node.predecessor() instanceof WithExceptionNode && node.predecessor() instanceof MemoryKill) {\n /*\n * This WithExceptionNode cannot be the lastLocationAccess for a FloatingReadNode.\n * Since it is both a memory kill and a control flow split, the scheduler cannot\n * schedule anything immediately after the kill. It can only schedule in the normal\n * or exceptional successor - and we have to tell the scheduler here which side it\n * needs to choose by putting in the location identity on both successors.\n */\n LocationIdentity killedLocationIdentity = node.predecessor() instanceof SingleMemoryKill ? ((SingleMemoryKill) node.predecessor()).getKilledLocationIdentity() : LocationIdentity.any();\n result.getMap().put(killedLocationIdentity, (MemoryKill) node);\n }\n return result;\n }\n\n @Override\n protected EconomicMap processLoop(LoopBeginNode loop, MemoryMapImpl initialState) {\n EconomicSet modifiedLocations = modifiedInLoops.get(loop);\n EconomicMap phis = EconomicMap.create(Equivalence.DEFAULT);\n if (modifiedLocations.contains(LocationIdentity.any())) {\n // create phis for all locations if ANY is modified in the loop\n modifiedLocations = EconomicSet.create(Equivalence.DEFAULT, modifiedLocations);\n modifiedLocations.addAll(initialState.getMap().getKeys());\n }\n for (LocationIdentity location : modifiedLocations) {\n createMemoryPhi(loop, initialState, phis, location);\n }\n initialState.getMap().putAll(phis);\n LoopInfo loopInfo = ReentrantNodeIterator.processLoop(this, loop, initialState);\n UnmodifiableMapCursor endStateCursor = loopInfo.endStates.getEntries();\n while (endStateCursor.advance()) {\n int endIndex = loop.phiPredecessorIndex(endStateCursor.getKey());\n UnmodifiableMapCursor phiCursor = phis.getEntries();\n while (phiCursor.advance()) {\n LocationIdentity key = phiCursor.getKey();\n PhiNode phi = phiCursor.getValue();\n phi.initializeValueAt(endIndex, ValueNodeUtil.asNode(endStateCursor.getValue().getLastLocationAccess(key)));\n }\n }\n return loopInfo.exitStates;\n }\n\n private static void createMemoryPhi(LoopBeginNode loop, MemoryMapImpl initialState, EconomicMap phis, LocationIdentity location) {\n MemoryPhiNode phi = loop.graph().addWithoutUnique(new MemoryPhiNode(loop, location));\n phi.addInput(ValueNodeUtil.asNode(initialState.getLastLocationAccess(location)));\n phis.put(location, phi);\n }\n }\n}\n"} {"task_id": "Java_1202", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/oracle/graal/compiler/src/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/FloatingReadPhase.java", "mask_start_position": 16359, "mask_end_position": 17277, "canonical_solution": "if (node.predecessor() instanceof WithExceptionNode && node.predecessor() instanceof MemoryKill) {\n /*\n * This WithExceptionNode cannot be the lastLocationAccess for a FloatingReadNode.\n * Since it is both a memory kill and a control flow split, the scheduler cannot\n * schedule anything immediately after the kill. It can only schedule in the normal\n * or exceptional successor - and we have to tell the scheduler here which side it\n * needs to choose by putting in the location identity on both successors.\n */\n LocationIdentity killedLocationIdentity = node.predecessor() instanceof SingleMemoryKill ? ((SingleMemoryKill) node.predecessor()).getKilledLocationIdentity() : LocationIdentity.any();\n result.getMap().put(killedLocationIdentity, (MemoryKill) node);\n }", "pre_mask_code": "package org.graalvm.compiler.phases.common;\n\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.NODE_ADDED;\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.ZERO_USAGES;\nimport static org.graalvm.word.LocationIdentity.any;\nimport java.util.EnumSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.graalvm.collections.EconomicMap;\nimport org.graalvm.collections.EconomicSet;\nimport org.graalvm.collections.Equivalence;\nimport org.graalvm.collections.UnmodifiableMapCursor;\nimport org.graalvm.compiler.core.common.cfg.Loop;\nimport org.graalvm.compiler.debug.DebugCloseable;\nimport org.graalvm.compiler.graph.Graph.NodeEventScope;\nimport org.graalvm.compiler.graph.Node;\nimport org.graalvm.compiler.nodes.AbstractBeginNode;\nimport org.graalvm.compiler.nodes.AbstractMergeNode;\nimport org.graalvm.compiler.nodes.FixedNode;\nimport org.graalvm.compiler.nodes.LoopBeginNode;\nimport org.graalvm.compiler.nodes.LoopEndNode;\nimport org.graalvm.compiler.nodes.LoopExitNode;\nimport org.graalvm.compiler.nodes.PhiNode;\nimport org.graalvm.compiler.nodes.ProxyNode;\nimport org.graalvm.compiler.nodes.ReturnNode;\nimport org.graalvm.compiler.nodes.StartNode;\nimport org.graalvm.compiler.nodes.StructuredGraph;\nimport org.graalvm.compiler.nodes.ValueNodeUtil;\nimport org.graalvm.compiler.nodes.WithExceptionNode;\nimport org.graalvm.compiler.nodes.StructuredGraph.StageFlag;\nimport org.graalvm.compiler.nodes.calc.FloatingNode;\nimport org.graalvm.compiler.nodes.cfg.Block;\nimport org.graalvm.compiler.nodes.cfg.ControlFlowGraph;\nimport org.graalvm.compiler.nodes.cfg.HIRLoop;\nimport org.graalvm.compiler.nodes.memory.FloatableAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingReadNode;\nimport org.graalvm.compiler.nodes.memory.MemoryAccess;\nimport org.graalvm.compiler.nodes.memory.MemoryAnchorNode;\nimport org.graalvm.compiler.nodes.memory.MemoryKill;\nimport org.graalvm.compiler.nodes.memory.MemoryMap;\nimport org.graalvm.compiler.nodes.memory.MemoryMapNode;\nimport org.graalvm.compiler.nodes.memory.MemoryPhiNode;\nimport org.graalvm.compiler.nodes.memory.MultiMemoryKill;\nimport org.graalvm.compiler.nodes.memory.ReadNode;\nimport org.graalvm.compiler.nodes.memory.SingleMemoryKill;\nimport org.graalvm.compiler.nodes.util.GraphUtil;\nimport org.graalvm.compiler.phases.Phase;\nimport org.graalvm.compiler.phases.common.util.EconomicSetNodeEventListener;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.LoopInfo;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.NodeIteratorClosure;\nimport org.graalvm.word.LocationIdentity;\n\npublic class FloatingReadPhase extends Phase {\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public static class MemoryMapImpl implements MemoryMap {\n\n private final EconomicMap lastMemorySnapshot;\n\n public MemoryMapImpl(MemoryMapImpl memoryMap) {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT, memoryMap.lastMemorySnapshot);\n }\n\n public MemoryMapImpl(StartNode start) {\n this();\n lastMemorySnapshot.put(any(), start);\n }\n\n public MemoryMapImpl() {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT);\n }\n\n @Override\n public MemoryKill getLastLocationAccess(LocationIdentity locationIdentity) {\n MemoryKill lastLocationAccess;\n if (locationIdentity.isImmutable()) {\n return null;\n } else {\n lastLocationAccess = lastMemorySnapshot.get(locationIdentity);\n if (lastLocationAccess == null) {\n lastLocationAccess = lastMemorySnapshot.get(any());\n assert lastLocationAccess != null;\n }\n return lastLocationAccess;\n }\n }\n\n @Override\n public Iterable getLocations() {\n return lastMemorySnapshot.getKeys();\n }\n\n public EconomicMap getMap() {\n return lastMemorySnapshot;\n }\n }\n\n public FloatingReadPhase() {\n this(true, false);\n }\n\n /**\n * @param createFloatingReads specifies whether {@link FloatableAccessNode}s like\n * {@link ReadNode} should be converted into floating nodes (e.g.,\n * {@link FloatingReadNode}s) where possible\n * @param createMemoryMapNodes a {@link MemoryMapNode} will be created for each return if this\n * is true\n */\n public FloatingReadPhase(boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n public float codeSizeIncrease() {\n return 1.50f;\n }\n\n /**\n * Removes nodes from a given set that (transitively) have a usage outside the set.\n */\n private static EconomicSet removeExternallyUsedNodes(EconomicSet set) {\n boolean change;\n do {\n change = false;\n for (Iterator iter = set.iterator(); iter.hasNext(); ) {\n Node node = iter.next();\n for (Node usage : node.usages()) {\n if (!set.contains(usage)) {\n change = true;\n iter.remove();\n break;\n }\n }\n }\n } while (change);\n return set;\n }\n\n protected void processNode(FixedNode node, EconomicSet currentState) {\n if (node instanceof SingleMemoryKill) {\n processIdentity(currentState, ((SingleMemoryKill) node).getKilledLocationIdentity());\n } else if (node instanceof MultiMemoryKill) {\n for (LocationIdentity identity : ((MultiMemoryKill) node).getKilledLocationIdentities()) {\n processIdentity(currentState, identity);\n }\n }\n }\n\n private static void processIdentity(EconomicSet currentState, LocationIdentity identity) {\n if (identity.isMutable()) {\n currentState.add(identity);\n }\n }\n\n protected void processBlock(Block b, EconomicSet currentState) {\n for (FixedNode n : b.getNodes()) {\n processNode(n, currentState);\n }\n }\n\n private EconomicSet processLoop(HIRLoop loop, EconomicMap> modifiedInLoops) {\n LoopBeginNode loopBegin = (LoopBeginNode) loop.getHeader().getBeginNode();\n EconomicSet result = modifiedInLoops.get(loopBegin);\n if (result != null) {\n return result;\n }\n result = EconomicSet.create(Equivalence.DEFAULT);\n for (Loop inner : loop.getChildren()) {\n result.addAll(processLoop((HIRLoop) inner, modifiedInLoops));\n }\n for (Block b : loop.getBlocks()) {\n if (b.getLoop() == loop) {\n processBlock(b, result);\n }\n }\n modifiedInLoops.put(loopBegin, result);\n return result;\n }\n\n @Override\n @SuppressWarnings(\"try\")\n protected void run(StructuredGraph graph) {\n EconomicMap> modifiedInLoops = null;\n if (graph.hasLoops()) {\n modifiedInLoops = EconomicMap.create(Equivalence.IDENTITY);\n ControlFlowGraph cfg = ControlFlowGraph.compute(graph, true, true, false, false);\n for (Loop l : cfg.getLoops()) {\n HIRLoop loop = (HIRLoop) l;\n processLoop(loop, modifiedInLoops);\n }\n }\n EconomicSetNodeEventListener listener = new EconomicSetNodeEventListener(EnumSet.of(NODE_ADDED, ZERO_USAGES));\n try (NodeEventScope nes = graph.trackNodeEvents(listener)) {\n ReentrantNodeIterator.apply(new FloatingReadClosure(modifiedInLoops, createFloatingReads, createMemoryMapNodes), graph.start(), new MemoryMapImpl(graph.start()));\n }\n for (Node n : removeExternallyUsedNodes(listener.getNodes())) {\n if (n.isAlive() && n instanceof FloatingNode) {\n n.replaceAtUsages(null);\n GraphUtil.killWithUnusedFloatingInputs(n);\n }\n }\n if (createFloatingReads) {\n assert graph.isBeforeStage(StageFlag.FLOATING_READS);\n graph.setAfterStage(StageFlag.FLOATING_READS);\n }\n }\n\n public static MemoryMapImpl mergeMemoryMaps(AbstractMergeNode merge, List states) {\n MemoryMapImpl newState = new MemoryMapImpl();\n EconomicSet keys = EconomicSet.create(Equivalence.DEFAULT);\n for (MemoryMap other : states) {\n keys.addAll(other.getLocations());\n }\n assert checkNoImmutableLocations(keys);\n for (LocationIdentity key : keys) {\n int mergedStatesCount = 0;\n boolean isPhi = false;\n MemoryKill merged = null;\n for (MemoryMap state : states) {\n MemoryKill last = state.getLastLocationAccess(key);\n if (isPhi) {\n // Fortify: Suppress Null Deference false positive (`isPhi == true` implies\n ((MemoryPhiNode) merged).addInput(ValueNodeUtil.asNode(last));\n } else {\n if (merged == last) {\n // nothing to do\n } else if (merged == null) {\n merged = last;\n } else {\n MemoryPhiNode phi = merge.graph().addWithoutUnique(new MemoryPhiNode(merge, key));\n for (int j = 0; j < mergedStatesCount; j++) {\n phi.addInput(ValueNodeUtil.asNode(merged));\n }\n phi.addInput(ValueNodeUtil.asNode(last));\n merged = phi;\n isPhi = true;\n }\n }\n mergedStatesCount++;\n }\n newState.getMap().put(key, merged);\n }\n return newState;\n }\n\n public static boolean nodeOfMemoryType(Node node) {\n return !(node instanceof MemoryKill) || (node instanceof SingleMemoryKill ^ node instanceof MultiMemoryKill);\n }\n\n private static boolean checkNoImmutableLocations(EconomicSet keys) {\n keys.forEach(t -> {\n assert t.isMutable();\n });\n return true;\n }\n\n public static class FloatingReadClosure extends NodeIteratorClosure {\n\n private final EconomicMap> modifiedInLoops;\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public FloatingReadClosure(EconomicMap> modifiedInLoops, boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.modifiedInLoops = modifiedInLoops;\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n protected MemoryMapImpl processNode(FixedNode node, MemoryMapImpl state) {\n if (node instanceof LoopExitNode) {\n final LoopExitNode loopExitNode = (LoopExitNode) node;\n final EconomicSet modifiedInLoop = modifiedInLoops.get(loopExitNode.loopBegin());\n final boolean anyModified = modifiedInLoop.contains(LocationIdentity.any());\n state.getMap().replaceAll((locationIdentity, memoryNode) -> (anyModified || modifiedInLoop.contains(locationIdentity)) ? ProxyNode.forMemory(memoryNode, loopExitNode, locationIdentity) : memoryNode);\n }\n if (node instanceof MemoryAnchorNode) {\n processAnchor((MemoryAnchorNode) node, state);\n return state;\n }\n if (node instanceof MemoryAccess) {\n processAccess((MemoryAccess) node, state);\n }\n if (createFloatingReads && node instanceof FloatableAccessNode) {\n processFloatable((FloatableAccessNode) node, state);\n }\n if (node instanceof SingleMemoryKill) {\n processCheckpoint((SingleMemoryKill) node, state);\n } else if (node instanceof MultiMemoryKill) {\n processCheckpoint((MultiMemoryKill) node, state);\n }\n assert nodeOfMemoryType(node) : node;\n if (createMemoryMapNodes && node instanceof ReturnNode) {\n ((ReturnNode) node).setMemoryMap(node.graph().unique(new MemoryMapNode(state.getMap())));\n }\n return state;\n }\n\n /**\n * Improve the memory graph by re-wiring all usages of a {@link MemoryAnchorNode} to the\n * real last access location.\n */\n private static void processAnchor(MemoryAnchorNode anchor, MemoryMapImpl state) {\n for (Node node : anchor.usages().snapshot()) {\n if (node instanceof MemoryAccess) {\n MemoryAccess access = (MemoryAccess) node;\n if (access.getLastLocationAccess() == anchor) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(access.getLocationIdentity());\n assert lastLocationAccess != null;\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n }\n if (anchor.hasNoUsages()) {\n anchor.graph().removeFixed(anchor);\n }\n }\n\n private static void processAccess(MemoryAccess access, MemoryMapImpl state) {\n LocationIdentity locationIdentity = access.getLocationIdentity();\n if (!locationIdentity.equals(LocationIdentity.any())) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n\n private static void processCheckpoint(SingleMemoryKill checkpoint, MemoryMapImpl state) {\n processIdentity(checkpoint.getKilledLocationIdentity(), checkpoint, state);\n }\n\n private static void processCheckpoint(MultiMemoryKill checkpoint, MemoryMapImpl state) {\n for (LocationIdentity identity : checkpoint.getKilledLocationIdentities()) {\n processIdentity(identity, checkpoint, state);\n }\n }\n\n private static void processIdentity(LocationIdentity identity, MemoryKill checkpoint, MemoryMapImpl state) {\n if (identity.isAny()) {\n state.getMap().clear();\n }\n if (identity.isMutable()) {\n state.getMap().put(identity, checkpoint);\n }\n }\n\n @SuppressWarnings(\"try\")\n private static void processFloatable(FloatableAccessNode accessNode, MemoryMapImpl state) {\n StructuredGraph graph = accessNode.graph();\n LocationIdentity locationIdentity = accessNode.getLocationIdentity();\n if (accessNode.canFloat()) {\n assert accessNode.getNullCheck() == false;\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n try (DebugCloseable position = accessNode.withNodeSourcePosition()) {\n FloatingAccessNode floatingNode = accessNode.asFloatingNode();\n assert floatingNode.getLastLocationAccess() == lastLocationAccess;\n graph.replaceFixedWithFloating(accessNode, floatingNode);\n }\n }\n }\n\n @Override\n protected MemoryMapImpl merge(AbstractMergeNode merge, List states) {\n return mergeMemoryMaps(merge, states);\n }\n\n @Override\n protected MemoryMapImpl afterSplit(AbstractBeginNode node, MemoryMapImpl oldState) {\n MemoryMapImpl result = new MemoryMapImpl(oldState);\n ", "post_mask_code": "\n return result;\n }\n\n @Override\n protected EconomicMap processLoop(LoopBeginNode loop, MemoryMapImpl initialState) {\n EconomicSet modifiedLocations = modifiedInLoops.get(loop);\n EconomicMap phis = EconomicMap.create(Equivalence.DEFAULT);\n if (modifiedLocations.contains(LocationIdentity.any())) {\n // create phis for all locations if ANY is modified in the loop\n modifiedLocations = EconomicSet.create(Equivalence.DEFAULT, modifiedLocations);\n modifiedLocations.addAll(initialState.getMap().getKeys());\n }\n for (LocationIdentity location : modifiedLocations) {\n createMemoryPhi(loop, initialState, phis, location);\n }\n initialState.getMap().putAll(phis);\n LoopInfo loopInfo = ReentrantNodeIterator.processLoop(this, loop, initialState);\n UnmodifiableMapCursor endStateCursor = loopInfo.endStates.getEntries();\n while (endStateCursor.advance()) {\n int endIndex = loop.phiPredecessorIndex(endStateCursor.getKey());\n UnmodifiableMapCursor phiCursor = phis.getEntries();\n while (phiCursor.advance()) {\n LocationIdentity key = phiCursor.getKey();\n PhiNode phi = phiCursor.getValue();\n phi.initializeValueAt(endIndex, ValueNodeUtil.asNode(endStateCursor.getValue().getLastLocationAccess(key)));\n }\n }\n return loopInfo.exitStates;\n }\n\n private static void createMemoryPhi(LoopBeginNode loop, MemoryMapImpl initialState, EconomicMap phis, LocationIdentity location) {\n MemoryPhiNode phi = loop.graph().addWithoutUnique(new MemoryPhiNode(loop, location));\n phi.addInput(ValueNodeUtil.asNode(initialState.getLastLocationAccess(location)));\n phis.put(location, phi);\n }\n }\n}\n"} {"task_id": "Java_1203", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/oracle/graal/compiler/src/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/FloatingReadPhase.java", "mask_start_position": 17290, "mask_end_position": 17314, "canonical_solution": "return result;\n }", "pre_mask_code": "package org.graalvm.compiler.phases.common;\n\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.NODE_ADDED;\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.ZERO_USAGES;\nimport static org.graalvm.word.LocationIdentity.any;\nimport java.util.EnumSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.graalvm.collections.EconomicMap;\nimport org.graalvm.collections.EconomicSet;\nimport org.graalvm.collections.Equivalence;\nimport org.graalvm.collections.UnmodifiableMapCursor;\nimport org.graalvm.compiler.core.common.cfg.Loop;\nimport org.graalvm.compiler.debug.DebugCloseable;\nimport org.graalvm.compiler.graph.Graph.NodeEventScope;\nimport org.graalvm.compiler.graph.Node;\nimport org.graalvm.compiler.nodes.AbstractBeginNode;\nimport org.graalvm.compiler.nodes.AbstractMergeNode;\nimport org.graalvm.compiler.nodes.FixedNode;\nimport org.graalvm.compiler.nodes.LoopBeginNode;\nimport org.graalvm.compiler.nodes.LoopEndNode;\nimport org.graalvm.compiler.nodes.LoopExitNode;\nimport org.graalvm.compiler.nodes.PhiNode;\nimport org.graalvm.compiler.nodes.ProxyNode;\nimport org.graalvm.compiler.nodes.ReturnNode;\nimport org.graalvm.compiler.nodes.StartNode;\nimport org.graalvm.compiler.nodes.StructuredGraph;\nimport org.graalvm.compiler.nodes.ValueNodeUtil;\nimport org.graalvm.compiler.nodes.WithExceptionNode;\nimport org.graalvm.compiler.nodes.StructuredGraph.StageFlag;\nimport org.graalvm.compiler.nodes.calc.FloatingNode;\nimport org.graalvm.compiler.nodes.cfg.Block;\nimport org.graalvm.compiler.nodes.cfg.ControlFlowGraph;\nimport org.graalvm.compiler.nodes.cfg.HIRLoop;\nimport org.graalvm.compiler.nodes.memory.FloatableAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingReadNode;\nimport org.graalvm.compiler.nodes.memory.MemoryAccess;\nimport org.graalvm.compiler.nodes.memory.MemoryAnchorNode;\nimport org.graalvm.compiler.nodes.memory.MemoryKill;\nimport org.graalvm.compiler.nodes.memory.MemoryMap;\nimport org.graalvm.compiler.nodes.memory.MemoryMapNode;\nimport org.graalvm.compiler.nodes.memory.MemoryPhiNode;\nimport org.graalvm.compiler.nodes.memory.MultiMemoryKill;\nimport org.graalvm.compiler.nodes.memory.ReadNode;\nimport org.graalvm.compiler.nodes.memory.SingleMemoryKill;\nimport org.graalvm.compiler.nodes.util.GraphUtil;\nimport org.graalvm.compiler.phases.Phase;\nimport org.graalvm.compiler.phases.common.util.EconomicSetNodeEventListener;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.LoopInfo;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.NodeIteratorClosure;\nimport org.graalvm.word.LocationIdentity;\n\npublic class FloatingReadPhase extends Phase {\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public static class MemoryMapImpl implements MemoryMap {\n\n private final EconomicMap lastMemorySnapshot;\n\n public MemoryMapImpl(MemoryMapImpl memoryMap) {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT, memoryMap.lastMemorySnapshot);\n }\n\n public MemoryMapImpl(StartNode start) {\n this();\n lastMemorySnapshot.put(any(), start);\n }\n\n public MemoryMapImpl() {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT);\n }\n\n @Override\n public MemoryKill getLastLocationAccess(LocationIdentity locationIdentity) {\n MemoryKill lastLocationAccess;\n if (locationIdentity.isImmutable()) {\n return null;\n } else {\n lastLocationAccess = lastMemorySnapshot.get(locationIdentity);\n if (lastLocationAccess == null) {\n lastLocationAccess = lastMemorySnapshot.get(any());\n assert lastLocationAccess != null;\n }\n return lastLocationAccess;\n }\n }\n\n @Override\n public Iterable getLocations() {\n return lastMemorySnapshot.getKeys();\n }\n\n public EconomicMap getMap() {\n return lastMemorySnapshot;\n }\n }\n\n public FloatingReadPhase() {\n this(true, false);\n }\n\n /**\n * @param createFloatingReads specifies whether {@link FloatableAccessNode}s like\n * {@link ReadNode} should be converted into floating nodes (e.g.,\n * {@link FloatingReadNode}s) where possible\n * @param createMemoryMapNodes a {@link MemoryMapNode} will be created for each return if this\n * is true\n */\n public FloatingReadPhase(boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n public float codeSizeIncrease() {\n return 1.50f;\n }\n\n /**\n * Removes nodes from a given set that (transitively) have a usage outside the set.\n */\n private static EconomicSet removeExternallyUsedNodes(EconomicSet set) {\n boolean change;\n do {\n change = false;\n for (Iterator iter = set.iterator(); iter.hasNext(); ) {\n Node node = iter.next();\n for (Node usage : node.usages()) {\n if (!set.contains(usage)) {\n change = true;\n iter.remove();\n break;\n }\n }\n }\n } while (change);\n return set;\n }\n\n protected void processNode(FixedNode node, EconomicSet currentState) {\n if (node instanceof SingleMemoryKill) {\n processIdentity(currentState, ((SingleMemoryKill) node).getKilledLocationIdentity());\n } else if (node instanceof MultiMemoryKill) {\n for (LocationIdentity identity : ((MultiMemoryKill) node).getKilledLocationIdentities()) {\n processIdentity(currentState, identity);\n }\n }\n }\n\n private static void processIdentity(EconomicSet currentState, LocationIdentity identity) {\n if (identity.isMutable()) {\n currentState.add(identity);\n }\n }\n\n protected void processBlock(Block b, EconomicSet currentState) {\n for (FixedNode n : b.getNodes()) {\n processNode(n, currentState);\n }\n }\n\n private EconomicSet processLoop(HIRLoop loop, EconomicMap> modifiedInLoops) {\n LoopBeginNode loopBegin = (LoopBeginNode) loop.getHeader().getBeginNode();\n EconomicSet result = modifiedInLoops.get(loopBegin);\n if (result != null) {\n return result;\n }\n result = EconomicSet.create(Equivalence.DEFAULT);\n for (Loop inner : loop.getChildren()) {\n result.addAll(processLoop((HIRLoop) inner, modifiedInLoops));\n }\n for (Block b : loop.getBlocks()) {\n if (b.getLoop() == loop) {\n processBlock(b, result);\n }\n }\n modifiedInLoops.put(loopBegin, result);\n return result;\n }\n\n @Override\n @SuppressWarnings(\"try\")\n protected void run(StructuredGraph graph) {\n EconomicMap> modifiedInLoops = null;\n if (graph.hasLoops()) {\n modifiedInLoops = EconomicMap.create(Equivalence.IDENTITY);\n ControlFlowGraph cfg = ControlFlowGraph.compute(graph, true, true, false, false);\n for (Loop l : cfg.getLoops()) {\n HIRLoop loop = (HIRLoop) l;\n processLoop(loop, modifiedInLoops);\n }\n }\n EconomicSetNodeEventListener listener = new EconomicSetNodeEventListener(EnumSet.of(NODE_ADDED, ZERO_USAGES));\n try (NodeEventScope nes = graph.trackNodeEvents(listener)) {\n ReentrantNodeIterator.apply(new FloatingReadClosure(modifiedInLoops, createFloatingReads, createMemoryMapNodes), graph.start(), new MemoryMapImpl(graph.start()));\n }\n for (Node n : removeExternallyUsedNodes(listener.getNodes())) {\n if (n.isAlive() && n instanceof FloatingNode) {\n n.replaceAtUsages(null);\n GraphUtil.killWithUnusedFloatingInputs(n);\n }\n }\n if (createFloatingReads) {\n assert graph.isBeforeStage(StageFlag.FLOATING_READS);\n graph.setAfterStage(StageFlag.FLOATING_READS);\n }\n }\n\n public static MemoryMapImpl mergeMemoryMaps(AbstractMergeNode merge, List states) {\n MemoryMapImpl newState = new MemoryMapImpl();\n EconomicSet keys = EconomicSet.create(Equivalence.DEFAULT);\n for (MemoryMap other : states) {\n keys.addAll(other.getLocations());\n }\n assert checkNoImmutableLocations(keys);\n for (LocationIdentity key : keys) {\n int mergedStatesCount = 0;\n boolean isPhi = false;\n MemoryKill merged = null;\n for (MemoryMap state : states) {\n MemoryKill last = state.getLastLocationAccess(key);\n if (isPhi) {\n // Fortify: Suppress Null Deference false positive (`isPhi == true` implies\n ((MemoryPhiNode) merged).addInput(ValueNodeUtil.asNode(last));\n } else {\n if (merged == last) {\n // nothing to do\n } else if (merged == null) {\n merged = last;\n } else {\n MemoryPhiNode phi = merge.graph().addWithoutUnique(new MemoryPhiNode(merge, key));\n for (int j = 0; j < mergedStatesCount; j++) {\n phi.addInput(ValueNodeUtil.asNode(merged));\n }\n phi.addInput(ValueNodeUtil.asNode(last));\n merged = phi;\n isPhi = true;\n }\n }\n mergedStatesCount++;\n }\n newState.getMap().put(key, merged);\n }\n return newState;\n }\n\n public static boolean nodeOfMemoryType(Node node) {\n return !(node instanceof MemoryKill) || (node instanceof SingleMemoryKill ^ node instanceof MultiMemoryKill);\n }\n\n private static boolean checkNoImmutableLocations(EconomicSet keys) {\n keys.forEach(t -> {\n assert t.isMutable();\n });\n return true;\n }\n\n public static class FloatingReadClosure extends NodeIteratorClosure {\n\n private final EconomicMap> modifiedInLoops;\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public FloatingReadClosure(EconomicMap> modifiedInLoops, boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.modifiedInLoops = modifiedInLoops;\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n protected MemoryMapImpl processNode(FixedNode node, MemoryMapImpl state) {\n if (node instanceof LoopExitNode) {\n final LoopExitNode loopExitNode = (LoopExitNode) node;\n final EconomicSet modifiedInLoop = modifiedInLoops.get(loopExitNode.loopBegin());\n final boolean anyModified = modifiedInLoop.contains(LocationIdentity.any());\n state.getMap().replaceAll((locationIdentity, memoryNode) -> (anyModified || modifiedInLoop.contains(locationIdentity)) ? ProxyNode.forMemory(memoryNode, loopExitNode, locationIdentity) : memoryNode);\n }\n if (node instanceof MemoryAnchorNode) {\n processAnchor((MemoryAnchorNode) node, state);\n return state;\n }\n if (node instanceof MemoryAccess) {\n processAccess((MemoryAccess) node, state);\n }\n if (createFloatingReads && node instanceof FloatableAccessNode) {\n processFloatable((FloatableAccessNode) node, state);\n }\n if (node instanceof SingleMemoryKill) {\n processCheckpoint((SingleMemoryKill) node, state);\n } else if (node instanceof MultiMemoryKill) {\n processCheckpoint((MultiMemoryKill) node, state);\n }\n assert nodeOfMemoryType(node) : node;\n if (createMemoryMapNodes && node instanceof ReturnNode) {\n ((ReturnNode) node).setMemoryMap(node.graph().unique(new MemoryMapNode(state.getMap())));\n }\n return state;\n }\n\n /**\n * Improve the memory graph by re-wiring all usages of a {@link MemoryAnchorNode} to the\n * real last access location.\n */\n private static void processAnchor(MemoryAnchorNode anchor, MemoryMapImpl state) {\n for (Node node : anchor.usages().snapshot()) {\n if (node instanceof MemoryAccess) {\n MemoryAccess access = (MemoryAccess) node;\n if (access.getLastLocationAccess() == anchor) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(access.getLocationIdentity());\n assert lastLocationAccess != null;\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n }\n if (anchor.hasNoUsages()) {\n anchor.graph().removeFixed(anchor);\n }\n }\n\n private static void processAccess(MemoryAccess access, MemoryMapImpl state) {\n LocationIdentity locationIdentity = access.getLocationIdentity();\n if (!locationIdentity.equals(LocationIdentity.any())) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n\n private static void processCheckpoint(SingleMemoryKill checkpoint, MemoryMapImpl state) {\n processIdentity(checkpoint.getKilledLocationIdentity(), checkpoint, state);\n }\n\n private static void processCheckpoint(MultiMemoryKill checkpoint, MemoryMapImpl state) {\n for (LocationIdentity identity : checkpoint.getKilledLocationIdentities()) {\n processIdentity(identity, checkpoint, state);\n }\n }\n\n private static void processIdentity(LocationIdentity identity, MemoryKill checkpoint, MemoryMapImpl state) {\n if (identity.isAny()) {\n state.getMap().clear();\n }\n if (identity.isMutable()) {\n state.getMap().put(identity, checkpoint);\n }\n }\n\n @SuppressWarnings(\"try\")\n private static void processFloatable(FloatableAccessNode accessNode, MemoryMapImpl state) {\n StructuredGraph graph = accessNode.graph();\n LocationIdentity locationIdentity = accessNode.getLocationIdentity();\n if (accessNode.canFloat()) {\n assert accessNode.getNullCheck() == false;\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n try (DebugCloseable position = accessNode.withNodeSourcePosition()) {\n FloatingAccessNode floatingNode = accessNode.asFloatingNode();\n assert floatingNode.getLastLocationAccess() == lastLocationAccess;\n graph.replaceFixedWithFloating(accessNode, floatingNode);\n }\n }\n }\n\n @Override\n protected MemoryMapImpl merge(AbstractMergeNode merge, List states) {\n return mergeMemoryMaps(merge, states);\n }\n\n @Override\n protected MemoryMapImpl afterSplit(AbstractBeginNode node, MemoryMapImpl oldState) {\n MemoryMapImpl result = new MemoryMapImpl(oldState);\n if (node.predecessor() instanceof WithExceptionNode && node.predecessor() instanceof MemoryKill) {\n /*\n * This WithExceptionNode cannot be the lastLocationAccess for a FloatingReadNode.\n * Since it is both a memory kill and a control flow split, the scheduler cannot\n * schedule anything immediately after the kill. It can only schedule in the normal\n * or exceptional successor - and we have to tell the scheduler here which side it\n * needs to choose by putting in the location identity on both successors.\n */\n LocationIdentity killedLocationIdentity = node.predecessor() instanceof SingleMemoryKill ? ((SingleMemoryKill) node.predecessor()).getKilledLocationIdentity() : LocationIdentity.any();\n result.getMap().put(killedLocationIdentity, (MemoryKill) node);\n }\n ", "post_mask_code": "\n\n @Override\n protected EconomicMap processLoop(LoopBeginNode loop, MemoryMapImpl initialState) {\n EconomicSet modifiedLocations = modifiedInLoops.get(loop);\n EconomicMap phis = EconomicMap.create(Equivalence.DEFAULT);\n if (modifiedLocations.contains(LocationIdentity.any())) {\n // create phis for all locations if ANY is modified in the loop\n modifiedLocations = EconomicSet.create(Equivalence.DEFAULT, modifiedLocations);\n modifiedLocations.addAll(initialState.getMap().getKeys());\n }\n for (LocationIdentity location : modifiedLocations) {\n createMemoryPhi(loop, initialState, phis, location);\n }\n initialState.getMap().putAll(phis);\n LoopInfo loopInfo = ReentrantNodeIterator.processLoop(this, loop, initialState);\n UnmodifiableMapCursor endStateCursor = loopInfo.endStates.getEntries();\n while (endStateCursor.advance()) {\n int endIndex = loop.phiPredecessorIndex(endStateCursor.getKey());\n UnmodifiableMapCursor phiCursor = phis.getEntries();\n while (phiCursor.advance()) {\n LocationIdentity key = phiCursor.getKey();\n PhiNode phi = phiCursor.getValue();\n phi.initializeValueAt(endIndex, ValueNodeUtil.asNode(endStateCursor.getValue().getLastLocationAccess(key)));\n }\n }\n return loopInfo.exitStates;\n }\n\n private static void createMemoryPhi(LoopBeginNode loop, MemoryMapImpl initialState, EconomicMap phis, LocationIdentity location) {\n MemoryPhiNode phi = loop.graph().addWithoutUnique(new MemoryPhiNode(loop, location));\n phi.addInput(ValueNodeUtil.asNode(initialState.getLastLocationAccess(location)));\n phis.put(location, phi);\n }\n }\n}\n"} {"task_id": "Java_1204", "language": "Java", "task_type": "single_line", "source_file": "java/github/oracle/graal/compiler/src/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/FloatingReadPhase.java", "mask_start_position": 18160, "mask_end_position": 18180, "canonical_solution": "tMap().putAll(phis);", "pre_mask_code": "package org.graalvm.compiler.phases.common;\n\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.NODE_ADDED;\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.ZERO_USAGES;\nimport static org.graalvm.word.LocationIdentity.any;\nimport java.util.EnumSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.graalvm.collections.EconomicMap;\nimport org.graalvm.collections.EconomicSet;\nimport org.graalvm.collections.Equivalence;\nimport org.graalvm.collections.UnmodifiableMapCursor;\nimport org.graalvm.compiler.core.common.cfg.Loop;\nimport org.graalvm.compiler.debug.DebugCloseable;\nimport org.graalvm.compiler.graph.Graph.NodeEventScope;\nimport org.graalvm.compiler.graph.Node;\nimport org.graalvm.compiler.nodes.AbstractBeginNode;\nimport org.graalvm.compiler.nodes.AbstractMergeNode;\nimport org.graalvm.compiler.nodes.FixedNode;\nimport org.graalvm.compiler.nodes.LoopBeginNode;\nimport org.graalvm.compiler.nodes.LoopEndNode;\nimport org.graalvm.compiler.nodes.LoopExitNode;\nimport org.graalvm.compiler.nodes.PhiNode;\nimport org.graalvm.compiler.nodes.ProxyNode;\nimport org.graalvm.compiler.nodes.ReturnNode;\nimport org.graalvm.compiler.nodes.StartNode;\nimport org.graalvm.compiler.nodes.StructuredGraph;\nimport org.graalvm.compiler.nodes.ValueNodeUtil;\nimport org.graalvm.compiler.nodes.WithExceptionNode;\nimport org.graalvm.compiler.nodes.StructuredGraph.StageFlag;\nimport org.graalvm.compiler.nodes.calc.FloatingNode;\nimport org.graalvm.compiler.nodes.cfg.Block;\nimport org.graalvm.compiler.nodes.cfg.ControlFlowGraph;\nimport org.graalvm.compiler.nodes.cfg.HIRLoop;\nimport org.graalvm.compiler.nodes.memory.FloatableAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingReadNode;\nimport org.graalvm.compiler.nodes.memory.MemoryAccess;\nimport org.graalvm.compiler.nodes.memory.MemoryAnchorNode;\nimport org.graalvm.compiler.nodes.memory.MemoryKill;\nimport org.graalvm.compiler.nodes.memory.MemoryMap;\nimport org.graalvm.compiler.nodes.memory.MemoryMapNode;\nimport org.graalvm.compiler.nodes.memory.MemoryPhiNode;\nimport org.graalvm.compiler.nodes.memory.MultiMemoryKill;\nimport org.graalvm.compiler.nodes.memory.ReadNode;\nimport org.graalvm.compiler.nodes.memory.SingleMemoryKill;\nimport org.graalvm.compiler.nodes.util.GraphUtil;\nimport org.graalvm.compiler.phases.Phase;\nimport org.graalvm.compiler.phases.common.util.EconomicSetNodeEventListener;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.LoopInfo;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.NodeIteratorClosure;\nimport org.graalvm.word.LocationIdentity;\n\npublic class FloatingReadPhase extends Phase {\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public static class MemoryMapImpl implements MemoryMap {\n\n private final EconomicMap lastMemorySnapshot;\n\n public MemoryMapImpl(MemoryMapImpl memoryMap) {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT, memoryMap.lastMemorySnapshot);\n }\n\n public MemoryMapImpl(StartNode start) {\n this();\n lastMemorySnapshot.put(any(), start);\n }\n\n public MemoryMapImpl() {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT);\n }\n\n @Override\n public MemoryKill getLastLocationAccess(LocationIdentity locationIdentity) {\n MemoryKill lastLocationAccess;\n if (locationIdentity.isImmutable()) {\n return null;\n } else {\n lastLocationAccess = lastMemorySnapshot.get(locationIdentity);\n if (lastLocationAccess == null) {\n lastLocationAccess = lastMemorySnapshot.get(any());\n assert lastLocationAccess != null;\n }\n return lastLocationAccess;\n }\n }\n\n @Override\n public Iterable getLocations() {\n return lastMemorySnapshot.getKeys();\n }\n\n public EconomicMap getMap() {\n return lastMemorySnapshot;\n }\n }\n\n public FloatingReadPhase() {\n this(true, false);\n }\n\n /**\n * @param createFloatingReads specifies whether {@link FloatableAccessNode}s like\n * {@link ReadNode} should be converted into floating nodes (e.g.,\n * {@link FloatingReadNode}s) where possible\n * @param createMemoryMapNodes a {@link MemoryMapNode} will be created for each return if this\n * is true\n */\n public FloatingReadPhase(boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n public float codeSizeIncrease() {\n return 1.50f;\n }\n\n /**\n * Removes nodes from a given set that (transitively) have a usage outside the set.\n */\n private static EconomicSet removeExternallyUsedNodes(EconomicSet set) {\n boolean change;\n do {\n change = false;\n for (Iterator iter = set.iterator(); iter.hasNext(); ) {\n Node node = iter.next();\n for (Node usage : node.usages()) {\n if (!set.contains(usage)) {\n change = true;\n iter.remove();\n break;\n }\n }\n }\n } while (change);\n return set;\n }\n\n protected void processNode(FixedNode node, EconomicSet currentState) {\n if (node instanceof SingleMemoryKill) {\n processIdentity(currentState, ((SingleMemoryKill) node).getKilledLocationIdentity());\n } else if (node instanceof MultiMemoryKill) {\n for (LocationIdentity identity : ((MultiMemoryKill) node).getKilledLocationIdentities()) {\n processIdentity(currentState, identity);\n }\n }\n }\n\n private static void processIdentity(EconomicSet currentState, LocationIdentity identity) {\n if (identity.isMutable()) {\n currentState.add(identity);\n }\n }\n\n protected void processBlock(Block b, EconomicSet currentState) {\n for (FixedNode n : b.getNodes()) {\n processNode(n, currentState);\n }\n }\n\n private EconomicSet processLoop(HIRLoop loop, EconomicMap> modifiedInLoops) {\n LoopBeginNode loopBegin = (LoopBeginNode) loop.getHeader().getBeginNode();\n EconomicSet result = modifiedInLoops.get(loopBegin);\n if (result != null) {\n return result;\n }\n result = EconomicSet.create(Equivalence.DEFAULT);\n for (Loop inner : loop.getChildren()) {\n result.addAll(processLoop((HIRLoop) inner, modifiedInLoops));\n }\n for (Block b : loop.getBlocks()) {\n if (b.getLoop() == loop) {\n processBlock(b, result);\n }\n }\n modifiedInLoops.put(loopBegin, result);\n return result;\n }\n\n @Override\n @SuppressWarnings(\"try\")\n protected void run(StructuredGraph graph) {\n EconomicMap> modifiedInLoops = null;\n if (graph.hasLoops()) {\n modifiedInLoops = EconomicMap.create(Equivalence.IDENTITY);\n ControlFlowGraph cfg = ControlFlowGraph.compute(graph, true, true, false, false);\n for (Loop l : cfg.getLoops()) {\n HIRLoop loop = (HIRLoop) l;\n processLoop(loop, modifiedInLoops);\n }\n }\n EconomicSetNodeEventListener listener = new EconomicSetNodeEventListener(EnumSet.of(NODE_ADDED, ZERO_USAGES));\n try (NodeEventScope nes = graph.trackNodeEvents(listener)) {\n ReentrantNodeIterator.apply(new FloatingReadClosure(modifiedInLoops, createFloatingReads, createMemoryMapNodes), graph.start(), new MemoryMapImpl(graph.start()));\n }\n for (Node n : removeExternallyUsedNodes(listener.getNodes())) {\n if (n.isAlive() && n instanceof FloatingNode) {\n n.replaceAtUsages(null);\n GraphUtil.killWithUnusedFloatingInputs(n);\n }\n }\n if (createFloatingReads) {\n assert graph.isBeforeStage(StageFlag.FLOATING_READS);\n graph.setAfterStage(StageFlag.FLOATING_READS);\n }\n }\n\n public static MemoryMapImpl mergeMemoryMaps(AbstractMergeNode merge, List states) {\n MemoryMapImpl newState = new MemoryMapImpl();\n EconomicSet keys = EconomicSet.create(Equivalence.DEFAULT);\n for (MemoryMap other : states) {\n keys.addAll(other.getLocations());\n }\n assert checkNoImmutableLocations(keys);\n for (LocationIdentity key : keys) {\n int mergedStatesCount = 0;\n boolean isPhi = false;\n MemoryKill merged = null;\n for (MemoryMap state : states) {\n MemoryKill last = state.getLastLocationAccess(key);\n if (isPhi) {\n // Fortify: Suppress Null Deference false positive (`isPhi == true` implies\n ((MemoryPhiNode) merged).addInput(ValueNodeUtil.asNode(last));\n } else {\n if (merged == last) {\n // nothing to do\n } else if (merged == null) {\n merged = last;\n } else {\n MemoryPhiNode phi = merge.graph().addWithoutUnique(new MemoryPhiNode(merge, key));\n for (int j = 0; j < mergedStatesCount; j++) {\n phi.addInput(ValueNodeUtil.asNode(merged));\n }\n phi.addInput(ValueNodeUtil.asNode(last));\n merged = phi;\n isPhi = true;\n }\n }\n mergedStatesCount++;\n }\n newState.getMap().put(key, merged);\n }\n return newState;\n }\n\n public static boolean nodeOfMemoryType(Node node) {\n return !(node instanceof MemoryKill) || (node instanceof SingleMemoryKill ^ node instanceof MultiMemoryKill);\n }\n\n private static boolean checkNoImmutableLocations(EconomicSet keys) {\n keys.forEach(t -> {\n assert t.isMutable();\n });\n return true;\n }\n\n public static class FloatingReadClosure extends NodeIteratorClosure {\n\n private final EconomicMap> modifiedInLoops;\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public FloatingReadClosure(EconomicMap> modifiedInLoops, boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.modifiedInLoops = modifiedInLoops;\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n protected MemoryMapImpl processNode(FixedNode node, MemoryMapImpl state) {\n if (node instanceof LoopExitNode) {\n final LoopExitNode loopExitNode = (LoopExitNode) node;\n final EconomicSet modifiedInLoop = modifiedInLoops.get(loopExitNode.loopBegin());\n final boolean anyModified = modifiedInLoop.contains(LocationIdentity.any());\n state.getMap().replaceAll((locationIdentity, memoryNode) -> (anyModified || modifiedInLoop.contains(locationIdentity)) ? ProxyNode.forMemory(memoryNode, loopExitNode, locationIdentity) : memoryNode);\n }\n if (node instanceof MemoryAnchorNode) {\n processAnchor((MemoryAnchorNode) node, state);\n return state;\n }\n if (node instanceof MemoryAccess) {\n processAccess((MemoryAccess) node, state);\n }\n if (createFloatingReads && node instanceof FloatableAccessNode) {\n processFloatable((FloatableAccessNode) node, state);\n }\n if (node instanceof SingleMemoryKill) {\n processCheckpoint((SingleMemoryKill) node, state);\n } else if (node instanceof MultiMemoryKill) {\n processCheckpoint((MultiMemoryKill) node, state);\n }\n assert nodeOfMemoryType(node) : node;\n if (createMemoryMapNodes && node instanceof ReturnNode) {\n ((ReturnNode) node).setMemoryMap(node.graph().unique(new MemoryMapNode(state.getMap())));\n }\n return state;\n }\n\n /**\n * Improve the memory graph by re-wiring all usages of a {@link MemoryAnchorNode} to the\n * real last access location.\n */\n private static void processAnchor(MemoryAnchorNode anchor, MemoryMapImpl state) {\n for (Node node : anchor.usages().snapshot()) {\n if (node instanceof MemoryAccess) {\n MemoryAccess access = (MemoryAccess) node;\n if (access.getLastLocationAccess() == anchor) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(access.getLocationIdentity());\n assert lastLocationAccess != null;\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n }\n if (anchor.hasNoUsages()) {\n anchor.graph().removeFixed(anchor);\n }\n }\n\n private static void processAccess(MemoryAccess access, MemoryMapImpl state) {\n LocationIdentity locationIdentity = access.getLocationIdentity();\n if (!locationIdentity.equals(LocationIdentity.any())) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n\n private static void processCheckpoint(SingleMemoryKill checkpoint, MemoryMapImpl state) {\n processIdentity(checkpoint.getKilledLocationIdentity(), checkpoint, state);\n }\n\n private static void processCheckpoint(MultiMemoryKill checkpoint, MemoryMapImpl state) {\n for (LocationIdentity identity : checkpoint.getKilledLocationIdentities()) {\n processIdentity(identity, checkpoint, state);\n }\n }\n\n private static void processIdentity(LocationIdentity identity, MemoryKill checkpoint, MemoryMapImpl state) {\n if (identity.isAny()) {\n state.getMap().clear();\n }\n if (identity.isMutable()) {\n state.getMap().put(identity, checkpoint);\n }\n }\n\n @SuppressWarnings(\"try\")\n private static void processFloatable(FloatableAccessNode accessNode, MemoryMapImpl state) {\n StructuredGraph graph = accessNode.graph();\n LocationIdentity locationIdentity = accessNode.getLocationIdentity();\n if (accessNode.canFloat()) {\n assert accessNode.getNullCheck() == false;\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n try (DebugCloseable position = accessNode.withNodeSourcePosition()) {\n FloatingAccessNode floatingNode = accessNode.asFloatingNode();\n assert floatingNode.getLastLocationAccess() == lastLocationAccess;\n graph.replaceFixedWithFloating(accessNode, floatingNode);\n }\n }\n }\n\n @Override\n protected MemoryMapImpl merge(AbstractMergeNode merge, List states) {\n return mergeMemoryMaps(merge, states);\n }\n\n @Override\n protected MemoryMapImpl afterSplit(AbstractBeginNode node, MemoryMapImpl oldState) {\n MemoryMapImpl result = new MemoryMapImpl(oldState);\n if (node.predecessor() instanceof WithExceptionNode && node.predecessor() instanceof MemoryKill) {\n /*\n * This WithExceptionNode cannot be the lastLocationAccess for a FloatingReadNode.\n * Since it is both a memory kill and a control flow split, the scheduler cannot\n * schedule anything immediately after the kill. It can only schedule in the normal\n * or exceptional successor - and we have to tell the scheduler here which side it\n * needs to choose by putting in the location identity on both successors.\n */\n LocationIdentity killedLocationIdentity = node.predecessor() instanceof SingleMemoryKill ? ((SingleMemoryKill) node.predecessor()).getKilledLocationIdentity() : LocationIdentity.any();\n result.getMap().put(killedLocationIdentity, (MemoryKill) node);\n }\n return result;\n }\n\n @Override\n protected EconomicMap processLoop(LoopBeginNode loop, MemoryMapImpl initialState) {\n EconomicSet modifiedLocations = modifiedInLoops.get(loop);\n EconomicMap phis = EconomicMap.create(Equivalence.DEFAULT);\n if (modifiedLocations.contains(LocationIdentity.any())) {\n // create phis for all locations if ANY is modified in the loop\n modifiedLocations = EconomicSet.create(Equivalence.DEFAULT, modifiedLocations);\n modifiedLocations.addAll(initialState.getMap().getKeys());\n }\n for (LocationIdentity location : modifiedLocations) {\n createMemoryPhi(loop, initialState, phis, location);\n }\n initialState.ge", "post_mask_code": "\n LoopInfo loopInfo = ReentrantNodeIterator.processLoop(this, loop, initialState);\n UnmodifiableMapCursor endStateCursor = loopInfo.endStates.getEntries();\n while (endStateCursor.advance()) {\n int endIndex = loop.phiPredecessorIndex(endStateCursor.getKey());\n UnmodifiableMapCursor phiCursor = phis.getEntries();\n while (phiCursor.advance()) {\n LocationIdentity key = phiCursor.getKey();\n PhiNode phi = phiCursor.getValue();\n phi.initializeValueAt(endIndex, ValueNodeUtil.asNode(endStateCursor.getValue().getLastLocationAccess(key)));\n }\n }\n return loopInfo.exitStates;\n }\n\n private static void createMemoryPhi(LoopBeginNode loop, MemoryMapImpl initialState, EconomicMap phis, LocationIdentity location) {\n MemoryPhiNode phi = loop.graph().addWithoutUnique(new MemoryPhiNode(loop, location));\n phi.addInput(ValueNodeUtil.asNode(initialState.getLastLocationAccess(location)));\n phis.put(location, phi);\n }\n }\n}\n"} {"task_id": "Java_1205", "language": "Java", "task_type": "if_statement", "source_file": "java/github/oracle/graal/compiler/src/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/FloatingReadPhase.java", "mask_start_position": 13352, "mask_end_position": 13806, "canonical_solution": "if (node instanceof MemoryAccess) {\n MemoryAccess access = (MemoryAccess) node;\n if (access.getLastLocationAccess() == anchor) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(access.getLocationIdentity());\n assert lastLocationAccess != null;\n access.setLastLocationAccess(lastLocationAccess);\n }\n }", "pre_mask_code": "package org.graalvm.compiler.phases.common;\n\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.NODE_ADDED;\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.ZERO_USAGES;\nimport static org.graalvm.word.LocationIdentity.any;\nimport java.util.EnumSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.graalvm.collections.EconomicMap;\nimport org.graalvm.collections.EconomicSet;\nimport org.graalvm.collections.Equivalence;\nimport org.graalvm.collections.UnmodifiableMapCursor;\nimport org.graalvm.compiler.core.common.cfg.Loop;\nimport org.graalvm.compiler.debug.DebugCloseable;\nimport org.graalvm.compiler.graph.Graph.NodeEventScope;\nimport org.graalvm.compiler.graph.Node;\nimport org.graalvm.compiler.nodes.AbstractBeginNode;\nimport org.graalvm.compiler.nodes.AbstractMergeNode;\nimport org.graalvm.compiler.nodes.FixedNode;\nimport org.graalvm.compiler.nodes.LoopBeginNode;\nimport org.graalvm.compiler.nodes.LoopEndNode;\nimport org.graalvm.compiler.nodes.LoopExitNode;\nimport org.graalvm.compiler.nodes.PhiNode;\nimport org.graalvm.compiler.nodes.ProxyNode;\nimport org.graalvm.compiler.nodes.ReturnNode;\nimport org.graalvm.compiler.nodes.StartNode;\nimport org.graalvm.compiler.nodes.StructuredGraph;\nimport org.graalvm.compiler.nodes.ValueNodeUtil;\nimport org.graalvm.compiler.nodes.WithExceptionNode;\nimport org.graalvm.compiler.nodes.StructuredGraph.StageFlag;\nimport org.graalvm.compiler.nodes.calc.FloatingNode;\nimport org.graalvm.compiler.nodes.cfg.Block;\nimport org.graalvm.compiler.nodes.cfg.ControlFlowGraph;\nimport org.graalvm.compiler.nodes.cfg.HIRLoop;\nimport org.graalvm.compiler.nodes.memory.FloatableAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingReadNode;\nimport org.graalvm.compiler.nodes.memory.MemoryAccess;\nimport org.graalvm.compiler.nodes.memory.MemoryAnchorNode;\nimport org.graalvm.compiler.nodes.memory.MemoryKill;\nimport org.graalvm.compiler.nodes.memory.MemoryMap;\nimport org.graalvm.compiler.nodes.memory.MemoryMapNode;\nimport org.graalvm.compiler.nodes.memory.MemoryPhiNode;\nimport org.graalvm.compiler.nodes.memory.MultiMemoryKill;\nimport org.graalvm.compiler.nodes.memory.ReadNode;\nimport org.graalvm.compiler.nodes.memory.SingleMemoryKill;\nimport org.graalvm.compiler.nodes.util.GraphUtil;\nimport org.graalvm.compiler.phases.Phase;\nimport org.graalvm.compiler.phases.common.util.EconomicSetNodeEventListener;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.LoopInfo;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.NodeIteratorClosure;\nimport org.graalvm.word.LocationIdentity;\n\npublic class FloatingReadPhase extends Phase {\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public static class MemoryMapImpl implements MemoryMap {\n\n private final EconomicMap lastMemorySnapshot;\n\n public MemoryMapImpl(MemoryMapImpl memoryMap) {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT, memoryMap.lastMemorySnapshot);\n }\n\n public MemoryMapImpl(StartNode start) {\n this();\n lastMemorySnapshot.put(any(), start);\n }\n\n public MemoryMapImpl() {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT);\n }\n\n @Override\n public MemoryKill getLastLocationAccess(LocationIdentity locationIdentity) {\n MemoryKill lastLocationAccess;\n if (locationIdentity.isImmutable()) {\n return null;\n } else {\n lastLocationAccess = lastMemorySnapshot.get(locationIdentity);\n if (lastLocationAccess == null) {\n lastLocationAccess = lastMemorySnapshot.get(any());\n assert lastLocationAccess != null;\n }\n return lastLocationAccess;\n }\n }\n\n @Override\n public Iterable getLocations() {\n return lastMemorySnapshot.getKeys();\n }\n\n public EconomicMap getMap() {\n return lastMemorySnapshot;\n }\n }\n\n public FloatingReadPhase() {\n this(true, false);\n }\n\n /**\n * @param createFloatingReads specifies whether {@link FloatableAccessNode}s like\n * {@link ReadNode} should be converted into floating nodes (e.g.,\n * {@link FloatingReadNode}s) where possible\n * @param createMemoryMapNodes a {@link MemoryMapNode} will be created for each return if this\n * is true\n */\n public FloatingReadPhase(boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n public float codeSizeIncrease() {\n return 1.50f;\n }\n\n /**\n * Removes nodes from a given set that (transitively) have a usage outside the set.\n */\n private static EconomicSet removeExternallyUsedNodes(EconomicSet set) {\n boolean change;\n do {\n change = false;\n for (Iterator iter = set.iterator(); iter.hasNext(); ) {\n Node node = iter.next();\n for (Node usage : node.usages()) {\n if (!set.contains(usage)) {\n change = true;\n iter.remove();\n break;\n }\n }\n }\n } while (change);\n return set;\n }\n\n protected void processNode(FixedNode node, EconomicSet currentState) {\n if (node instanceof SingleMemoryKill) {\n processIdentity(currentState, ((SingleMemoryKill) node).getKilledLocationIdentity());\n } else if (node instanceof MultiMemoryKill) {\n for (LocationIdentity identity : ((MultiMemoryKill) node).getKilledLocationIdentities()) {\n processIdentity(currentState, identity);\n }\n }\n }\n\n private static void processIdentity(EconomicSet currentState, LocationIdentity identity) {\n if (identity.isMutable()) {\n currentState.add(identity);\n }\n }\n\n protected void processBlock(Block b, EconomicSet currentState) {\n for (FixedNode n : b.getNodes()) {\n processNode(n, currentState);\n }\n }\n\n private EconomicSet processLoop(HIRLoop loop, EconomicMap> modifiedInLoops) {\n LoopBeginNode loopBegin = (LoopBeginNode) loop.getHeader().getBeginNode();\n EconomicSet result = modifiedInLoops.get(loopBegin);\n if (result != null) {\n return result;\n }\n result = EconomicSet.create(Equivalence.DEFAULT);\n for (Loop inner : loop.getChildren()) {\n result.addAll(processLoop((HIRLoop) inner, modifiedInLoops));\n }\n for (Block b : loop.getBlocks()) {\n if (b.getLoop() == loop) {\n processBlock(b, result);\n }\n }\n modifiedInLoops.put(loopBegin, result);\n return result;\n }\n\n @Override\n @SuppressWarnings(\"try\")\n protected void run(StructuredGraph graph) {\n EconomicMap> modifiedInLoops = null;\n if (graph.hasLoops()) {\n modifiedInLoops = EconomicMap.create(Equivalence.IDENTITY);\n ControlFlowGraph cfg = ControlFlowGraph.compute(graph, true, true, false, false);\n for (Loop l : cfg.getLoops()) {\n HIRLoop loop = (HIRLoop) l;\n processLoop(loop, modifiedInLoops);\n }\n }\n EconomicSetNodeEventListener listener = new EconomicSetNodeEventListener(EnumSet.of(NODE_ADDED, ZERO_USAGES));\n try (NodeEventScope nes = graph.trackNodeEvents(listener)) {\n ReentrantNodeIterator.apply(new FloatingReadClosure(modifiedInLoops, createFloatingReads, createMemoryMapNodes), graph.start(), new MemoryMapImpl(graph.start()));\n }\n for (Node n : removeExternallyUsedNodes(listener.getNodes())) {\n if (n.isAlive() && n instanceof FloatingNode) {\n n.replaceAtUsages(null);\n GraphUtil.killWithUnusedFloatingInputs(n);\n }\n }\n if (createFloatingReads) {\n assert graph.isBeforeStage(StageFlag.FLOATING_READS);\n graph.setAfterStage(StageFlag.FLOATING_READS);\n }\n }\n\n public static MemoryMapImpl mergeMemoryMaps(AbstractMergeNode merge, List states) {\n MemoryMapImpl newState = new MemoryMapImpl();\n EconomicSet keys = EconomicSet.create(Equivalence.DEFAULT);\n for (MemoryMap other : states) {\n keys.addAll(other.getLocations());\n }\n assert checkNoImmutableLocations(keys);\n for (LocationIdentity key : keys) {\n int mergedStatesCount = 0;\n boolean isPhi = false;\n MemoryKill merged = null;\n for (MemoryMap state : states) {\n MemoryKill last = state.getLastLocationAccess(key);\n if (isPhi) {\n // Fortify: Suppress Null Deference false positive (`isPhi == true` implies\n ((MemoryPhiNode) merged).addInput(ValueNodeUtil.asNode(last));\n } else {\n if (merged == last) {\n // nothing to do\n } else if (merged == null) {\n merged = last;\n } else {\n MemoryPhiNode phi = merge.graph().addWithoutUnique(new MemoryPhiNode(merge, key));\n for (int j = 0; j < mergedStatesCount; j++) {\n phi.addInput(ValueNodeUtil.asNode(merged));\n }\n phi.addInput(ValueNodeUtil.asNode(last));\n merged = phi;\n isPhi = true;\n }\n }\n mergedStatesCount++;\n }\n newState.getMap().put(key, merged);\n }\n return newState;\n }\n\n public static boolean nodeOfMemoryType(Node node) {\n return !(node instanceof MemoryKill) || (node instanceof SingleMemoryKill ^ node instanceof MultiMemoryKill);\n }\n\n private static boolean checkNoImmutableLocations(EconomicSet keys) {\n keys.forEach(t -> {\n assert t.isMutable();\n });\n return true;\n }\n\n public static class FloatingReadClosure extends NodeIteratorClosure {\n\n private final EconomicMap> modifiedInLoops;\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public FloatingReadClosure(EconomicMap> modifiedInLoops, boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.modifiedInLoops = modifiedInLoops;\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n protected MemoryMapImpl processNode(FixedNode node, MemoryMapImpl state) {\n if (node instanceof LoopExitNode) {\n final LoopExitNode loopExitNode = (LoopExitNode) node;\n final EconomicSet modifiedInLoop = modifiedInLoops.get(loopExitNode.loopBegin());\n final boolean anyModified = modifiedInLoop.contains(LocationIdentity.any());\n state.getMap().replaceAll((locationIdentity, memoryNode) -> (anyModified || modifiedInLoop.contains(locationIdentity)) ? ProxyNode.forMemory(memoryNode, loopExitNode, locationIdentity) : memoryNode);\n }\n if (node instanceof MemoryAnchorNode) {\n processAnchor((MemoryAnchorNode) node, state);\n return state;\n }\n if (node instanceof MemoryAccess) {\n processAccess((MemoryAccess) node, state);\n }\n if (createFloatingReads && node instanceof FloatableAccessNode) {\n processFloatable((FloatableAccessNode) node, state);\n }\n if (node instanceof SingleMemoryKill) {\n processCheckpoint((SingleMemoryKill) node, state);\n } else if (node instanceof MultiMemoryKill) {\n processCheckpoint((MultiMemoryKill) node, state);\n }\n assert nodeOfMemoryType(node) : node;\n if (createMemoryMapNodes && node instanceof ReturnNode) {\n ((ReturnNode) node).setMemoryMap(node.graph().unique(new MemoryMapNode(state.getMap())));\n }\n return state;\n }\n\n /**\n * Improve the memory graph by re-wiring all usages of a {@link MemoryAnchorNode} to the\n * real last access location.\n */\n private static void processAnchor(MemoryAnchorNode anchor, MemoryMapImpl state) {\n for (Node node : anchor.usages().snapshot()) {\n ", "post_mask_code": "\n }\n if (anchor.hasNoUsages()) {\n anchor.graph().removeFixed(anchor);\n }\n }\n\n private static void processAccess(MemoryAccess access, MemoryMapImpl state) {\n LocationIdentity locationIdentity = access.getLocationIdentity();\n if (!locationIdentity.equals(LocationIdentity.any())) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n\n private static void processCheckpoint(SingleMemoryKill checkpoint, MemoryMapImpl state) {\n processIdentity(checkpoint.getKilledLocationIdentity(), checkpoint, state);\n }\n\n private static void processCheckpoint(MultiMemoryKill checkpoint, MemoryMapImpl state) {\n for (LocationIdentity identity : checkpoint.getKilledLocationIdentities()) {\n processIdentity(identity, checkpoint, state);\n }\n }\n\n private static void processIdentity(LocationIdentity identity, MemoryKill checkpoint, MemoryMapImpl state) {\n if (identity.isAny()) {\n state.getMap().clear();\n }\n if (identity.isMutable()) {\n state.getMap().put(identity, checkpoint);\n }\n }\n\n @SuppressWarnings(\"try\")\n private static void processFloatable(FloatableAccessNode accessNode, MemoryMapImpl state) {\n StructuredGraph graph = accessNode.graph();\n LocationIdentity locationIdentity = accessNode.getLocationIdentity();\n if (accessNode.canFloat()) {\n assert accessNode.getNullCheck() == false;\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n try (DebugCloseable position = accessNode.withNodeSourcePosition()) {\n FloatingAccessNode floatingNode = accessNode.asFloatingNode();\n assert floatingNode.getLastLocationAccess() == lastLocationAccess;\n graph.replaceFixedWithFloating(accessNode, floatingNode);\n }\n }\n }\n\n @Override\n protected MemoryMapImpl merge(AbstractMergeNode merge, List states) {\n return mergeMemoryMaps(merge, states);\n }\n\n @Override\n protected MemoryMapImpl afterSplit(AbstractBeginNode node, MemoryMapImpl oldState) {\n MemoryMapImpl result = new MemoryMapImpl(oldState);\n if (node.predecessor() instanceof WithExceptionNode && node.predecessor() instanceof MemoryKill) {\n /*\n * This WithExceptionNode cannot be the lastLocationAccess for a FloatingReadNode.\n * Since it is both a memory kill and a control flow split, the scheduler cannot\n * schedule anything immediately after the kill. It can only schedule in the normal\n * or exceptional successor - and we have to tell the scheduler here which side it\n * needs to choose by putting in the location identity on both successors.\n */\n LocationIdentity killedLocationIdentity = node.predecessor() instanceof SingleMemoryKill ? ((SingleMemoryKill) node.predecessor()).getKilledLocationIdentity() : LocationIdentity.any();\n result.getMap().put(killedLocationIdentity, (MemoryKill) node);\n }\n return result;\n }\n\n @Override\n protected EconomicMap processLoop(LoopBeginNode loop, MemoryMapImpl initialState) {\n EconomicSet modifiedLocations = modifiedInLoops.get(loop);\n EconomicMap phis = EconomicMap.create(Equivalence.DEFAULT);\n if (modifiedLocations.contains(LocationIdentity.any())) {\n // create phis for all locations if ANY is modified in the loop\n modifiedLocations = EconomicSet.create(Equivalence.DEFAULT, modifiedLocations);\n modifiedLocations.addAll(initialState.getMap().getKeys());\n }\n for (LocationIdentity location : modifiedLocations) {\n createMemoryPhi(loop, initialState, phis, location);\n }\n initialState.getMap().putAll(phis);\n LoopInfo loopInfo = ReentrantNodeIterator.processLoop(this, loop, initialState);\n UnmodifiableMapCursor endStateCursor = loopInfo.endStates.getEntries();\n while (endStateCursor.advance()) {\n int endIndex = loop.phiPredecessorIndex(endStateCursor.getKey());\n UnmodifiableMapCursor phiCursor = phis.getEntries();\n while (phiCursor.advance()) {\n LocationIdentity key = phiCursor.getKey();\n PhiNode phi = phiCursor.getValue();\n phi.initializeValueAt(endIndex, ValueNodeUtil.asNode(endStateCursor.getValue().getLastLocationAccess(key)));\n }\n }\n return loopInfo.exitStates;\n }\n\n private static void createMemoryPhi(LoopBeginNode loop, MemoryMapImpl initialState, EconomicMap phis, LocationIdentity location) {\n MemoryPhiNode phi = loop.graph().addWithoutUnique(new MemoryPhiNode(loop, location));\n phi.addInput(ValueNodeUtil.asNode(initialState.getLastLocationAccess(location)));\n phis.put(location, phi);\n }\n }\n}\n"} {"task_id": "Java_1206", "language": "Java", "task_type": "for_statement", "source_file": "java/github/oracle/graal/compiler/src/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/FloatingReadPhase.java", "mask_start_position": 9916, "mask_end_position": 10059, "canonical_solution": "for (int j = 0; j < mergedStatesCount; j++) {\n phi.addInput(ValueNodeUtil.asNode(merged));\n }", "pre_mask_code": "package org.graalvm.compiler.phases.common;\n\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.NODE_ADDED;\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.ZERO_USAGES;\nimport static org.graalvm.word.LocationIdentity.any;\nimport java.util.EnumSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.graalvm.collections.EconomicMap;\nimport org.graalvm.collections.EconomicSet;\nimport org.graalvm.collections.Equivalence;\nimport org.graalvm.collections.UnmodifiableMapCursor;\nimport org.graalvm.compiler.core.common.cfg.Loop;\nimport org.graalvm.compiler.debug.DebugCloseable;\nimport org.graalvm.compiler.graph.Graph.NodeEventScope;\nimport org.graalvm.compiler.graph.Node;\nimport org.graalvm.compiler.nodes.AbstractBeginNode;\nimport org.graalvm.compiler.nodes.AbstractMergeNode;\nimport org.graalvm.compiler.nodes.FixedNode;\nimport org.graalvm.compiler.nodes.LoopBeginNode;\nimport org.graalvm.compiler.nodes.LoopEndNode;\nimport org.graalvm.compiler.nodes.LoopExitNode;\nimport org.graalvm.compiler.nodes.PhiNode;\nimport org.graalvm.compiler.nodes.ProxyNode;\nimport org.graalvm.compiler.nodes.ReturnNode;\nimport org.graalvm.compiler.nodes.StartNode;\nimport org.graalvm.compiler.nodes.StructuredGraph;\nimport org.graalvm.compiler.nodes.ValueNodeUtil;\nimport org.graalvm.compiler.nodes.WithExceptionNode;\nimport org.graalvm.compiler.nodes.StructuredGraph.StageFlag;\nimport org.graalvm.compiler.nodes.calc.FloatingNode;\nimport org.graalvm.compiler.nodes.cfg.Block;\nimport org.graalvm.compiler.nodes.cfg.ControlFlowGraph;\nimport org.graalvm.compiler.nodes.cfg.HIRLoop;\nimport org.graalvm.compiler.nodes.memory.FloatableAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingReadNode;\nimport org.graalvm.compiler.nodes.memory.MemoryAccess;\nimport org.graalvm.compiler.nodes.memory.MemoryAnchorNode;\nimport org.graalvm.compiler.nodes.memory.MemoryKill;\nimport org.graalvm.compiler.nodes.memory.MemoryMap;\nimport org.graalvm.compiler.nodes.memory.MemoryMapNode;\nimport org.graalvm.compiler.nodes.memory.MemoryPhiNode;\nimport org.graalvm.compiler.nodes.memory.MultiMemoryKill;\nimport org.graalvm.compiler.nodes.memory.ReadNode;\nimport org.graalvm.compiler.nodes.memory.SingleMemoryKill;\nimport org.graalvm.compiler.nodes.util.GraphUtil;\nimport org.graalvm.compiler.phases.Phase;\nimport org.graalvm.compiler.phases.common.util.EconomicSetNodeEventListener;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.LoopInfo;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.NodeIteratorClosure;\nimport org.graalvm.word.LocationIdentity;\n\npublic class FloatingReadPhase extends Phase {\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public static class MemoryMapImpl implements MemoryMap {\n\n private final EconomicMap lastMemorySnapshot;\n\n public MemoryMapImpl(MemoryMapImpl memoryMap) {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT, memoryMap.lastMemorySnapshot);\n }\n\n public MemoryMapImpl(StartNode start) {\n this();\n lastMemorySnapshot.put(any(), start);\n }\n\n public MemoryMapImpl() {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT);\n }\n\n @Override\n public MemoryKill getLastLocationAccess(LocationIdentity locationIdentity) {\n MemoryKill lastLocationAccess;\n if (locationIdentity.isImmutable()) {\n return null;\n } else {\n lastLocationAccess = lastMemorySnapshot.get(locationIdentity);\n if (lastLocationAccess == null) {\n lastLocationAccess = lastMemorySnapshot.get(any());\n assert lastLocationAccess != null;\n }\n return lastLocationAccess;\n }\n }\n\n @Override\n public Iterable getLocations() {\n return lastMemorySnapshot.getKeys();\n }\n\n public EconomicMap getMap() {\n return lastMemorySnapshot;\n }\n }\n\n public FloatingReadPhase() {\n this(true, false);\n }\n\n /**\n * @param createFloatingReads specifies whether {@link FloatableAccessNode}s like\n * {@link ReadNode} should be converted into floating nodes (e.g.,\n * {@link FloatingReadNode}s) where possible\n * @param createMemoryMapNodes a {@link MemoryMapNode} will be created for each return if this\n * is true\n */\n public FloatingReadPhase(boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n public float codeSizeIncrease() {\n return 1.50f;\n }\n\n /**\n * Removes nodes from a given set that (transitively) have a usage outside the set.\n */\n private static EconomicSet removeExternallyUsedNodes(EconomicSet set) {\n boolean change;\n do {\n change = false;\n for (Iterator iter = set.iterator(); iter.hasNext(); ) {\n Node node = iter.next();\n for (Node usage : node.usages()) {\n if (!set.contains(usage)) {\n change = true;\n iter.remove();\n break;\n }\n }\n }\n } while (change);\n return set;\n }\n\n protected void processNode(FixedNode node, EconomicSet currentState) {\n if (node instanceof SingleMemoryKill) {\n processIdentity(currentState, ((SingleMemoryKill) node).getKilledLocationIdentity());\n } else if (node instanceof MultiMemoryKill) {\n for (LocationIdentity identity : ((MultiMemoryKill) node).getKilledLocationIdentities()) {\n processIdentity(currentState, identity);\n }\n }\n }\n\n private static void processIdentity(EconomicSet currentState, LocationIdentity identity) {\n if (identity.isMutable()) {\n currentState.add(identity);\n }\n }\n\n protected void processBlock(Block b, EconomicSet currentState) {\n for (FixedNode n : b.getNodes()) {\n processNode(n, currentState);\n }\n }\n\n private EconomicSet processLoop(HIRLoop loop, EconomicMap> modifiedInLoops) {\n LoopBeginNode loopBegin = (LoopBeginNode) loop.getHeader().getBeginNode();\n EconomicSet result = modifiedInLoops.get(loopBegin);\n if (result != null) {\n return result;\n }\n result = EconomicSet.create(Equivalence.DEFAULT);\n for (Loop inner : loop.getChildren()) {\n result.addAll(processLoop((HIRLoop) inner, modifiedInLoops));\n }\n for (Block b : loop.getBlocks()) {\n if (b.getLoop() == loop) {\n processBlock(b, result);\n }\n }\n modifiedInLoops.put(loopBegin, result);\n return result;\n }\n\n @Override\n @SuppressWarnings(\"try\")\n protected void run(StructuredGraph graph) {\n EconomicMap> modifiedInLoops = null;\n if (graph.hasLoops()) {\n modifiedInLoops = EconomicMap.create(Equivalence.IDENTITY);\n ControlFlowGraph cfg = ControlFlowGraph.compute(graph, true, true, false, false);\n for (Loop l : cfg.getLoops()) {\n HIRLoop loop = (HIRLoop) l;\n processLoop(loop, modifiedInLoops);\n }\n }\n EconomicSetNodeEventListener listener = new EconomicSetNodeEventListener(EnumSet.of(NODE_ADDED, ZERO_USAGES));\n try (NodeEventScope nes = graph.trackNodeEvents(listener)) {\n ReentrantNodeIterator.apply(new FloatingReadClosure(modifiedInLoops, createFloatingReads, createMemoryMapNodes), graph.start(), new MemoryMapImpl(graph.start()));\n }\n for (Node n : removeExternallyUsedNodes(listener.getNodes())) {\n if (n.isAlive() && n instanceof FloatingNode) {\n n.replaceAtUsages(null);\n GraphUtil.killWithUnusedFloatingInputs(n);\n }\n }\n if (createFloatingReads) {\n assert graph.isBeforeStage(StageFlag.FLOATING_READS);\n graph.setAfterStage(StageFlag.FLOATING_READS);\n }\n }\n\n public static MemoryMapImpl mergeMemoryMaps(AbstractMergeNode merge, List states) {\n MemoryMapImpl newState = new MemoryMapImpl();\n EconomicSet keys = EconomicSet.create(Equivalence.DEFAULT);\n for (MemoryMap other : states) {\n keys.addAll(other.getLocations());\n }\n assert checkNoImmutableLocations(keys);\n for (LocationIdentity key : keys) {\n int mergedStatesCount = 0;\n boolean isPhi = false;\n MemoryKill merged = null;\n for (MemoryMap state : states) {\n MemoryKill last = state.getLastLocationAccess(key);\n if (isPhi) {\n // Fortify: Suppress Null Deference false positive (`isPhi == true` implies\n ((MemoryPhiNode) merged).addInput(ValueNodeUtil.asNode(last));\n } else {\n if (merged == last) {\n // nothing to do\n } else if (merged == null) {\n merged = last;\n } else {\n MemoryPhiNode phi = merge.graph().addWithoutUnique(new MemoryPhiNode(merge, key));\n ", "post_mask_code": "\n phi.addInput(ValueNodeUtil.asNode(last));\n merged = phi;\n isPhi = true;\n }\n }\n mergedStatesCount++;\n }\n newState.getMap().put(key, merged);\n }\n return newState;\n }\n\n public static boolean nodeOfMemoryType(Node node) {\n return !(node instanceof MemoryKill) || (node instanceof SingleMemoryKill ^ node instanceof MultiMemoryKill);\n }\n\n private static boolean checkNoImmutableLocations(EconomicSet keys) {\n keys.forEach(t -> {\n assert t.isMutable();\n });\n return true;\n }\n\n public static class FloatingReadClosure extends NodeIteratorClosure {\n\n private final EconomicMap> modifiedInLoops;\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public FloatingReadClosure(EconomicMap> modifiedInLoops, boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.modifiedInLoops = modifiedInLoops;\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n protected MemoryMapImpl processNode(FixedNode node, MemoryMapImpl state) {\n if (node instanceof LoopExitNode) {\n final LoopExitNode loopExitNode = (LoopExitNode) node;\n final EconomicSet modifiedInLoop = modifiedInLoops.get(loopExitNode.loopBegin());\n final boolean anyModified = modifiedInLoop.contains(LocationIdentity.any());\n state.getMap().replaceAll((locationIdentity, memoryNode) -> (anyModified || modifiedInLoop.contains(locationIdentity)) ? ProxyNode.forMemory(memoryNode, loopExitNode, locationIdentity) : memoryNode);\n }\n if (node instanceof MemoryAnchorNode) {\n processAnchor((MemoryAnchorNode) node, state);\n return state;\n }\n if (node instanceof MemoryAccess) {\n processAccess((MemoryAccess) node, state);\n }\n if (createFloatingReads && node instanceof FloatableAccessNode) {\n processFloatable((FloatableAccessNode) node, state);\n }\n if (node instanceof SingleMemoryKill) {\n processCheckpoint((SingleMemoryKill) node, state);\n } else if (node instanceof MultiMemoryKill) {\n processCheckpoint((MultiMemoryKill) node, state);\n }\n assert nodeOfMemoryType(node) : node;\n if (createMemoryMapNodes && node instanceof ReturnNode) {\n ((ReturnNode) node).setMemoryMap(node.graph().unique(new MemoryMapNode(state.getMap())));\n }\n return state;\n }\n\n /**\n * Improve the memory graph by re-wiring all usages of a {@link MemoryAnchorNode} to the\n * real last access location.\n */\n private static void processAnchor(MemoryAnchorNode anchor, MemoryMapImpl state) {\n for (Node node : anchor.usages().snapshot()) {\n if (node instanceof MemoryAccess) {\n MemoryAccess access = (MemoryAccess) node;\n if (access.getLastLocationAccess() == anchor) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(access.getLocationIdentity());\n assert lastLocationAccess != null;\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n }\n if (anchor.hasNoUsages()) {\n anchor.graph().removeFixed(anchor);\n }\n }\n\n private static void processAccess(MemoryAccess access, MemoryMapImpl state) {\n LocationIdentity locationIdentity = access.getLocationIdentity();\n if (!locationIdentity.equals(LocationIdentity.any())) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n\n private static void processCheckpoint(SingleMemoryKill checkpoint, MemoryMapImpl state) {\n processIdentity(checkpoint.getKilledLocationIdentity(), checkpoint, state);\n }\n\n private static void processCheckpoint(MultiMemoryKill checkpoint, MemoryMapImpl state) {\n for (LocationIdentity identity : checkpoint.getKilledLocationIdentities()) {\n processIdentity(identity, checkpoint, state);\n }\n }\n\n private static void processIdentity(LocationIdentity identity, MemoryKill checkpoint, MemoryMapImpl state) {\n if (identity.isAny()) {\n state.getMap().clear();\n }\n if (identity.isMutable()) {\n state.getMap().put(identity, checkpoint);\n }\n }\n\n @SuppressWarnings(\"try\")\n private static void processFloatable(FloatableAccessNode accessNode, MemoryMapImpl state) {\n StructuredGraph graph = accessNode.graph();\n LocationIdentity locationIdentity = accessNode.getLocationIdentity();\n if (accessNode.canFloat()) {\n assert accessNode.getNullCheck() == false;\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n try (DebugCloseable position = accessNode.withNodeSourcePosition()) {\n FloatingAccessNode floatingNode = accessNode.asFloatingNode();\n assert floatingNode.getLastLocationAccess() == lastLocationAccess;\n graph.replaceFixedWithFloating(accessNode, floatingNode);\n }\n }\n }\n\n @Override\n protected MemoryMapImpl merge(AbstractMergeNode merge, List states) {\n return mergeMemoryMaps(merge, states);\n }\n\n @Override\n protected MemoryMapImpl afterSplit(AbstractBeginNode node, MemoryMapImpl oldState) {\n MemoryMapImpl result = new MemoryMapImpl(oldState);\n if (node.predecessor() instanceof WithExceptionNode && node.predecessor() instanceof MemoryKill) {\n /*\n * This WithExceptionNode cannot be the lastLocationAccess for a FloatingReadNode.\n * Since it is both a memory kill and a control flow split, the scheduler cannot\n * schedule anything immediately after the kill. It can only schedule in the normal\n * or exceptional successor - and we have to tell the scheduler here which side it\n * needs to choose by putting in the location identity on both successors.\n */\n LocationIdentity killedLocationIdentity = node.predecessor() instanceof SingleMemoryKill ? ((SingleMemoryKill) node.predecessor()).getKilledLocationIdentity() : LocationIdentity.any();\n result.getMap().put(killedLocationIdentity, (MemoryKill) node);\n }\n return result;\n }\n\n @Override\n protected EconomicMap processLoop(LoopBeginNode loop, MemoryMapImpl initialState) {\n EconomicSet modifiedLocations = modifiedInLoops.get(loop);\n EconomicMap phis = EconomicMap.create(Equivalence.DEFAULT);\n if (modifiedLocations.contains(LocationIdentity.any())) {\n // create phis for all locations if ANY is modified in the loop\n modifiedLocations = EconomicSet.create(Equivalence.DEFAULT, modifiedLocations);\n modifiedLocations.addAll(initialState.getMap().getKeys());\n }\n for (LocationIdentity location : modifiedLocations) {\n createMemoryPhi(loop, initialState, phis, location);\n }\n initialState.getMap().putAll(phis);\n LoopInfo loopInfo = ReentrantNodeIterator.processLoop(this, loop, initialState);\n UnmodifiableMapCursor endStateCursor = loopInfo.endStates.getEntries();\n while (endStateCursor.advance()) {\n int endIndex = loop.phiPredecessorIndex(endStateCursor.getKey());\n UnmodifiableMapCursor phiCursor = phis.getEntries();\n while (phiCursor.advance()) {\n LocationIdentity key = phiCursor.getKey();\n PhiNode phi = phiCursor.getValue();\n phi.initializeValueAt(endIndex, ValueNodeUtil.asNode(endStateCursor.getValue().getLastLocationAccess(key)));\n }\n }\n return loopInfo.exitStates;\n }\n\n private static void createMemoryPhi(LoopBeginNode loop, MemoryMapImpl initialState, EconomicMap phis, LocationIdentity location) {\n MemoryPhiNode phi = loop.graph().addWithoutUnique(new MemoryPhiNode(loop, location));\n phi.addInput(ValueNodeUtil.asNode(initialState.getLastLocationAccess(location)));\n phis.put(location, phi);\n }\n }\n}\n"} {"task_id": "Java_1207", "language": "Java", "task_type": "while_statement", "source_file": "java/github/oracle/graal/compiler/src/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/FloatingReadPhase.java", "mask_start_position": 18648, "mask_end_position": 18943, "canonical_solution": "while (phiCursor.advance()) {\n LocationIdentity key = phiCursor.getKey();\n PhiNode phi = phiCursor.getValue();\n phi.initializeValueAt(endIndex, ValueNodeUtil.asNode(endStateCursor.getValue().getLastLocationAccess(key)));\n }", "pre_mask_code": "package org.graalvm.compiler.phases.common;\n\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.NODE_ADDED;\nimport static org.graalvm.compiler.graph.Graph.NodeEvent.ZERO_USAGES;\nimport static org.graalvm.word.LocationIdentity.any;\nimport java.util.EnumSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.graalvm.collections.EconomicMap;\nimport org.graalvm.collections.EconomicSet;\nimport org.graalvm.collections.Equivalence;\nimport org.graalvm.collections.UnmodifiableMapCursor;\nimport org.graalvm.compiler.core.common.cfg.Loop;\nimport org.graalvm.compiler.debug.DebugCloseable;\nimport org.graalvm.compiler.graph.Graph.NodeEventScope;\nimport org.graalvm.compiler.graph.Node;\nimport org.graalvm.compiler.nodes.AbstractBeginNode;\nimport org.graalvm.compiler.nodes.AbstractMergeNode;\nimport org.graalvm.compiler.nodes.FixedNode;\nimport org.graalvm.compiler.nodes.LoopBeginNode;\nimport org.graalvm.compiler.nodes.LoopEndNode;\nimport org.graalvm.compiler.nodes.LoopExitNode;\nimport org.graalvm.compiler.nodes.PhiNode;\nimport org.graalvm.compiler.nodes.ProxyNode;\nimport org.graalvm.compiler.nodes.ReturnNode;\nimport org.graalvm.compiler.nodes.StartNode;\nimport org.graalvm.compiler.nodes.StructuredGraph;\nimport org.graalvm.compiler.nodes.ValueNodeUtil;\nimport org.graalvm.compiler.nodes.WithExceptionNode;\nimport org.graalvm.compiler.nodes.StructuredGraph.StageFlag;\nimport org.graalvm.compiler.nodes.calc.FloatingNode;\nimport org.graalvm.compiler.nodes.cfg.Block;\nimport org.graalvm.compiler.nodes.cfg.ControlFlowGraph;\nimport org.graalvm.compiler.nodes.cfg.HIRLoop;\nimport org.graalvm.compiler.nodes.memory.FloatableAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingAccessNode;\nimport org.graalvm.compiler.nodes.memory.FloatingReadNode;\nimport org.graalvm.compiler.nodes.memory.MemoryAccess;\nimport org.graalvm.compiler.nodes.memory.MemoryAnchorNode;\nimport org.graalvm.compiler.nodes.memory.MemoryKill;\nimport org.graalvm.compiler.nodes.memory.MemoryMap;\nimport org.graalvm.compiler.nodes.memory.MemoryMapNode;\nimport org.graalvm.compiler.nodes.memory.MemoryPhiNode;\nimport org.graalvm.compiler.nodes.memory.MultiMemoryKill;\nimport org.graalvm.compiler.nodes.memory.ReadNode;\nimport org.graalvm.compiler.nodes.memory.SingleMemoryKill;\nimport org.graalvm.compiler.nodes.util.GraphUtil;\nimport org.graalvm.compiler.phases.Phase;\nimport org.graalvm.compiler.phases.common.util.EconomicSetNodeEventListener;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.LoopInfo;\nimport org.graalvm.compiler.phases.graph.ReentrantNodeIterator.NodeIteratorClosure;\nimport org.graalvm.word.LocationIdentity;\n\npublic class FloatingReadPhase extends Phase {\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public static class MemoryMapImpl implements MemoryMap {\n\n private final EconomicMap lastMemorySnapshot;\n\n public MemoryMapImpl(MemoryMapImpl memoryMap) {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT, memoryMap.lastMemorySnapshot);\n }\n\n public MemoryMapImpl(StartNode start) {\n this();\n lastMemorySnapshot.put(any(), start);\n }\n\n public MemoryMapImpl() {\n lastMemorySnapshot = EconomicMap.create(Equivalence.DEFAULT);\n }\n\n @Override\n public MemoryKill getLastLocationAccess(LocationIdentity locationIdentity) {\n MemoryKill lastLocationAccess;\n if (locationIdentity.isImmutable()) {\n return null;\n } else {\n lastLocationAccess = lastMemorySnapshot.get(locationIdentity);\n if (lastLocationAccess == null) {\n lastLocationAccess = lastMemorySnapshot.get(any());\n assert lastLocationAccess != null;\n }\n return lastLocationAccess;\n }\n }\n\n @Override\n public Iterable getLocations() {\n return lastMemorySnapshot.getKeys();\n }\n\n public EconomicMap getMap() {\n return lastMemorySnapshot;\n }\n }\n\n public FloatingReadPhase() {\n this(true, false);\n }\n\n /**\n * @param createFloatingReads specifies whether {@link FloatableAccessNode}s like\n * {@link ReadNode} should be converted into floating nodes (e.g.,\n * {@link FloatingReadNode}s) where possible\n * @param createMemoryMapNodes a {@link MemoryMapNode} will be created for each return if this\n * is true\n */\n public FloatingReadPhase(boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n public float codeSizeIncrease() {\n return 1.50f;\n }\n\n /**\n * Removes nodes from a given set that (transitively) have a usage outside the set.\n */\n private static EconomicSet removeExternallyUsedNodes(EconomicSet set) {\n boolean change;\n do {\n change = false;\n for (Iterator iter = set.iterator(); iter.hasNext(); ) {\n Node node = iter.next();\n for (Node usage : node.usages()) {\n if (!set.contains(usage)) {\n change = true;\n iter.remove();\n break;\n }\n }\n }\n } while (change);\n return set;\n }\n\n protected void processNode(FixedNode node, EconomicSet currentState) {\n if (node instanceof SingleMemoryKill) {\n processIdentity(currentState, ((SingleMemoryKill) node).getKilledLocationIdentity());\n } else if (node instanceof MultiMemoryKill) {\n for (LocationIdentity identity : ((MultiMemoryKill) node).getKilledLocationIdentities()) {\n processIdentity(currentState, identity);\n }\n }\n }\n\n private static void processIdentity(EconomicSet currentState, LocationIdentity identity) {\n if (identity.isMutable()) {\n currentState.add(identity);\n }\n }\n\n protected void processBlock(Block b, EconomicSet currentState) {\n for (FixedNode n : b.getNodes()) {\n processNode(n, currentState);\n }\n }\n\n private EconomicSet processLoop(HIRLoop loop, EconomicMap> modifiedInLoops) {\n LoopBeginNode loopBegin = (LoopBeginNode) loop.getHeader().getBeginNode();\n EconomicSet result = modifiedInLoops.get(loopBegin);\n if (result != null) {\n return result;\n }\n result = EconomicSet.create(Equivalence.DEFAULT);\n for (Loop inner : loop.getChildren()) {\n result.addAll(processLoop((HIRLoop) inner, modifiedInLoops));\n }\n for (Block b : loop.getBlocks()) {\n if (b.getLoop() == loop) {\n processBlock(b, result);\n }\n }\n modifiedInLoops.put(loopBegin, result);\n return result;\n }\n\n @Override\n @SuppressWarnings(\"try\")\n protected void run(StructuredGraph graph) {\n EconomicMap> modifiedInLoops = null;\n if (graph.hasLoops()) {\n modifiedInLoops = EconomicMap.create(Equivalence.IDENTITY);\n ControlFlowGraph cfg = ControlFlowGraph.compute(graph, true, true, false, false);\n for (Loop l : cfg.getLoops()) {\n HIRLoop loop = (HIRLoop) l;\n processLoop(loop, modifiedInLoops);\n }\n }\n EconomicSetNodeEventListener listener = new EconomicSetNodeEventListener(EnumSet.of(NODE_ADDED, ZERO_USAGES));\n try (NodeEventScope nes = graph.trackNodeEvents(listener)) {\n ReentrantNodeIterator.apply(new FloatingReadClosure(modifiedInLoops, createFloatingReads, createMemoryMapNodes), graph.start(), new MemoryMapImpl(graph.start()));\n }\n for (Node n : removeExternallyUsedNodes(listener.getNodes())) {\n if (n.isAlive() && n instanceof FloatingNode) {\n n.replaceAtUsages(null);\n GraphUtil.killWithUnusedFloatingInputs(n);\n }\n }\n if (createFloatingReads) {\n assert graph.isBeforeStage(StageFlag.FLOATING_READS);\n graph.setAfterStage(StageFlag.FLOATING_READS);\n }\n }\n\n public static MemoryMapImpl mergeMemoryMaps(AbstractMergeNode merge, List states) {\n MemoryMapImpl newState = new MemoryMapImpl();\n EconomicSet keys = EconomicSet.create(Equivalence.DEFAULT);\n for (MemoryMap other : states) {\n keys.addAll(other.getLocations());\n }\n assert checkNoImmutableLocations(keys);\n for (LocationIdentity key : keys) {\n int mergedStatesCount = 0;\n boolean isPhi = false;\n MemoryKill merged = null;\n for (MemoryMap state : states) {\n MemoryKill last = state.getLastLocationAccess(key);\n if (isPhi) {\n // Fortify: Suppress Null Deference false positive (`isPhi == true` implies\n ((MemoryPhiNode) merged).addInput(ValueNodeUtil.asNode(last));\n } else {\n if (merged == last) {\n // nothing to do\n } else if (merged == null) {\n merged = last;\n } else {\n MemoryPhiNode phi = merge.graph().addWithoutUnique(new MemoryPhiNode(merge, key));\n for (int j = 0; j < mergedStatesCount; j++) {\n phi.addInput(ValueNodeUtil.asNode(merged));\n }\n phi.addInput(ValueNodeUtil.asNode(last));\n merged = phi;\n isPhi = true;\n }\n }\n mergedStatesCount++;\n }\n newState.getMap().put(key, merged);\n }\n return newState;\n }\n\n public static boolean nodeOfMemoryType(Node node) {\n return !(node instanceof MemoryKill) || (node instanceof SingleMemoryKill ^ node instanceof MultiMemoryKill);\n }\n\n private static boolean checkNoImmutableLocations(EconomicSet keys) {\n keys.forEach(t -> {\n assert t.isMutable();\n });\n return true;\n }\n\n public static class FloatingReadClosure extends NodeIteratorClosure {\n\n private final EconomicMap> modifiedInLoops;\n\n private boolean createFloatingReads;\n\n private boolean createMemoryMapNodes;\n\n public FloatingReadClosure(EconomicMap> modifiedInLoops, boolean createFloatingReads, boolean createMemoryMapNodes) {\n this.modifiedInLoops = modifiedInLoops;\n this.createFloatingReads = createFloatingReads;\n this.createMemoryMapNodes = createMemoryMapNodes;\n }\n\n @Override\n protected MemoryMapImpl processNode(FixedNode node, MemoryMapImpl state) {\n if (node instanceof LoopExitNode) {\n final LoopExitNode loopExitNode = (LoopExitNode) node;\n final EconomicSet modifiedInLoop = modifiedInLoops.get(loopExitNode.loopBegin());\n final boolean anyModified = modifiedInLoop.contains(LocationIdentity.any());\n state.getMap().replaceAll((locationIdentity, memoryNode) -> (anyModified || modifiedInLoop.contains(locationIdentity)) ? ProxyNode.forMemory(memoryNode, loopExitNode, locationIdentity) : memoryNode);\n }\n if (node instanceof MemoryAnchorNode) {\n processAnchor((MemoryAnchorNode) node, state);\n return state;\n }\n if (node instanceof MemoryAccess) {\n processAccess((MemoryAccess) node, state);\n }\n if (createFloatingReads && node instanceof FloatableAccessNode) {\n processFloatable((FloatableAccessNode) node, state);\n }\n if (node instanceof SingleMemoryKill) {\n processCheckpoint((SingleMemoryKill) node, state);\n } else if (node instanceof MultiMemoryKill) {\n processCheckpoint((MultiMemoryKill) node, state);\n }\n assert nodeOfMemoryType(node) : node;\n if (createMemoryMapNodes && node instanceof ReturnNode) {\n ((ReturnNode) node).setMemoryMap(node.graph().unique(new MemoryMapNode(state.getMap())));\n }\n return state;\n }\n\n /**\n * Improve the memory graph by re-wiring all usages of a {@link MemoryAnchorNode} to the\n * real last access location.\n */\n private static void processAnchor(MemoryAnchorNode anchor, MemoryMapImpl state) {\n for (Node node : anchor.usages().snapshot()) {\n if (node instanceof MemoryAccess) {\n MemoryAccess access = (MemoryAccess) node;\n if (access.getLastLocationAccess() == anchor) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(access.getLocationIdentity());\n assert lastLocationAccess != null;\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n }\n if (anchor.hasNoUsages()) {\n anchor.graph().removeFixed(anchor);\n }\n }\n\n private static void processAccess(MemoryAccess access, MemoryMapImpl state) {\n LocationIdentity locationIdentity = access.getLocationIdentity();\n if (!locationIdentity.equals(LocationIdentity.any())) {\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n access.setLastLocationAccess(lastLocationAccess);\n }\n }\n\n private static void processCheckpoint(SingleMemoryKill checkpoint, MemoryMapImpl state) {\n processIdentity(checkpoint.getKilledLocationIdentity(), checkpoint, state);\n }\n\n private static void processCheckpoint(MultiMemoryKill checkpoint, MemoryMapImpl state) {\n for (LocationIdentity identity : checkpoint.getKilledLocationIdentities()) {\n processIdentity(identity, checkpoint, state);\n }\n }\n\n private static void processIdentity(LocationIdentity identity, MemoryKill checkpoint, MemoryMapImpl state) {\n if (identity.isAny()) {\n state.getMap().clear();\n }\n if (identity.isMutable()) {\n state.getMap().put(identity, checkpoint);\n }\n }\n\n @SuppressWarnings(\"try\")\n private static void processFloatable(FloatableAccessNode accessNode, MemoryMapImpl state) {\n StructuredGraph graph = accessNode.graph();\n LocationIdentity locationIdentity = accessNode.getLocationIdentity();\n if (accessNode.canFloat()) {\n assert accessNode.getNullCheck() == false;\n MemoryKill lastLocationAccess = state.getLastLocationAccess(locationIdentity);\n try (DebugCloseable position = accessNode.withNodeSourcePosition()) {\n FloatingAccessNode floatingNode = accessNode.asFloatingNode();\n assert floatingNode.getLastLocationAccess() == lastLocationAccess;\n graph.replaceFixedWithFloating(accessNode, floatingNode);\n }\n }\n }\n\n @Override\n protected MemoryMapImpl merge(AbstractMergeNode merge, List states) {\n return mergeMemoryMaps(merge, states);\n }\n\n @Override\n protected MemoryMapImpl afterSplit(AbstractBeginNode node, MemoryMapImpl oldState) {\n MemoryMapImpl result = new MemoryMapImpl(oldState);\n if (node.predecessor() instanceof WithExceptionNode && node.predecessor() instanceof MemoryKill) {\n /*\n * This WithExceptionNode cannot be the lastLocationAccess for a FloatingReadNode.\n * Since it is both a memory kill and a control flow split, the scheduler cannot\n * schedule anything immediately after the kill. It can only schedule in the normal\n * or exceptional successor - and we have to tell the scheduler here which side it\n * needs to choose by putting in the location identity on both successors.\n */\n LocationIdentity killedLocationIdentity = node.predecessor() instanceof SingleMemoryKill ? ((SingleMemoryKill) node.predecessor()).getKilledLocationIdentity() : LocationIdentity.any();\n result.getMap().put(killedLocationIdentity, (MemoryKill) node);\n }\n return result;\n }\n\n @Override\n protected EconomicMap processLoop(LoopBeginNode loop, MemoryMapImpl initialState) {\n EconomicSet modifiedLocations = modifiedInLoops.get(loop);\n EconomicMap phis = EconomicMap.create(Equivalence.DEFAULT);\n if (modifiedLocations.contains(LocationIdentity.any())) {\n // create phis for all locations if ANY is modified in the loop\n modifiedLocations = EconomicSet.create(Equivalence.DEFAULT, modifiedLocations);\n modifiedLocations.addAll(initialState.getMap().getKeys());\n }\n for (LocationIdentity location : modifiedLocations) {\n createMemoryPhi(loop, initialState, phis, location);\n }\n initialState.getMap().putAll(phis);\n LoopInfo loopInfo = ReentrantNodeIterator.processLoop(this, loop, initialState);\n UnmodifiableMapCursor endStateCursor = loopInfo.endStates.getEntries();\n while (endStateCursor.advance()) {\n int endIndex = loop.phiPredecessorIndex(endStateCursor.getKey());\n UnmodifiableMapCursor phiCursor = phis.getEntries();\n ", "post_mask_code": "\n }\n return loopInfo.exitStates;\n }\n\n private static void createMemoryPhi(LoopBeginNode loop, MemoryMapImpl initialState, EconomicMap phis, LocationIdentity location) {\n MemoryPhiNode phi = loop.graph().addWithoutUnique(new MemoryPhiNode(loop, location));\n phi.addInput(ValueNodeUtil.asNode(initialState.getLastLocationAccess(location)));\n phis.put(location, phi);\n }\n }\n}\n"} {"task_id": "Java_1208", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ROS-Mobile/ROS-Mobile-Android/app/src/main/java/com/schneewittchen/rosandroid/utility/WidgetDiffCallback.java", "mask_start_position": 1168, "mask_end_position": 1258, "canonical_solution": "@Override\n public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) ", "pre_mask_code": "package com.schneewittchen.rosandroid.utility;\n\nimport androidx.recyclerview.widget.DiffUtil;\nimport com.schneewittchen.rosandroid.model.entities.widgets.BaseEntity;\nimport java.util.List;\n\n/**\n * TODO: Description\n *\n * @author Nico Studt\n * @version 1.0.1\n * @created on 05.02.20\n * @updated on 24.09.20\n * @modified by Nico Studt\n */\npublic class WidgetDiffCallback extends DiffUtil.Callback {\n\n public static String TAG = WidgetDiffCallback.class.getSimpleName();\n\n List oldWidgets;\n\n List newWidgets;\n\n public WidgetDiffCallback(List newWidgets, List oldWidgets) {\n this.newWidgets = newWidgets;\n this.oldWidgets = oldWidgets;\n }\n\n @Override\n public int getOldListSize() {\n return oldWidgets.size();\n }\n\n @Override\n public int getNewListSize() {\n return newWidgets.size();\n }\n\n @Override\n public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {\n BaseEntity oldWidget = oldWidgets.get(oldItemPosition);\n BaseEntity newWidget = newWidgets.get(newItemPosition);\n return oldWidget.id == newWidget.id;\n }\n\n ", "post_mask_code": "{\n BaseEntity oldWidget = oldWidgets.get(oldItemPosition);\n BaseEntity newWidget = newWidgets.get(newItemPosition);\n return oldWidget.equals(newWidget);\n }\n}\n"} {"task_id": "Java_1209", "language": "Java", "task_type": "method_body", "source_file": "java/github/ROS-Mobile/ROS-Mobile-Android/app/src/main/java/com/schneewittchen/rosandroid/utility/WidgetDiffCallback.java", "mask_start_position": 848, "mask_end_position": 889, "canonical_solution": "{\n return newWidgets.size();\n }", "pre_mask_code": "package com.schneewittchen.rosandroid.utility;\n\nimport androidx.recyclerview.widget.DiffUtil;\nimport com.schneewittchen.rosandroid.model.entities.widgets.BaseEntity;\nimport java.util.List;\n\n/**\n * TODO: Description\n *\n * @author Nico Studt\n * @version 1.0.1\n * @created on 05.02.20\n * @updated on 24.09.20\n * @modified by Nico Studt\n */\npublic class WidgetDiffCallback extends DiffUtil.Callback {\n\n public static String TAG = WidgetDiffCallback.class.getSimpleName();\n\n List oldWidgets;\n\n List newWidgets;\n\n public WidgetDiffCallback(List newWidgets, List oldWidgets) {\n this.newWidgets = newWidgets;\n this.oldWidgets = oldWidgets;\n }\n\n @Override\n public int getOldListSize() {\n return oldWidgets.size();\n }\n\n @Override\n public int getNewListSize() ", "post_mask_code": "\n\n @Override\n public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {\n BaseEntity oldWidget = oldWidgets.get(oldItemPosition);\n BaseEntity newWidget = newWidgets.get(newItemPosition);\n return oldWidget.id == newWidget.id;\n }\n\n @Override\n public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {\n BaseEntity oldWidget = oldWidgets.get(oldItemPosition);\n BaseEntity newWidget = newWidgets.get(newItemPosition);\n return oldWidget.equals(newWidget);\n }\n}\n"} {"task_id": "Java_1210", "language": "Java", "task_type": "single_line", "source_file": "java/github/ROS-Mobile/ROS-Mobile-Android/app/src/main/java/com/schneewittchen/rosandroid/utility/WidgetDiffCallback.java", "mask_start_position": 1064, "mask_end_position": 1111, "canonical_solution": "ty newWidget = newWidgets.get(newItemPosition);", "pre_mask_code": "package com.schneewittchen.rosandroid.utility;\n\nimport androidx.recyclerview.widget.DiffUtil;\nimport com.schneewittchen.rosandroid.model.entities.widgets.BaseEntity;\nimport java.util.List;\n\n/**\n * TODO: Description\n *\n * @author Nico Studt\n * @version 1.0.1\n * @created on 05.02.20\n * @updated on 24.09.20\n * @modified by Nico Studt\n */\npublic class WidgetDiffCallback extends DiffUtil.Callback {\n\n public static String TAG = WidgetDiffCallback.class.getSimpleName();\n\n List oldWidgets;\n\n List newWidgets;\n\n public WidgetDiffCallback(List newWidgets, List oldWidgets) {\n this.newWidgets = newWidgets;\n this.oldWidgets = oldWidgets;\n }\n\n @Override\n public int getOldListSize() {\n return oldWidgets.size();\n }\n\n @Override\n public int getNewListSize() {\n return newWidgets.size();\n }\n\n @Override\n public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {\n BaseEntity oldWidget = oldWidgets.get(oldItemPosition);\n BaseEnti", "post_mask_code": "\n return oldWidget.id == newWidget.id;\n }\n\n @Override\n public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {\n BaseEntity oldWidget = oldWidgets.get(oldItemPosition);\n BaseEntity newWidget = newWidgets.get(newItemPosition);\n return oldWidget.equals(newWidget);\n }\n}\n"} {"task_id": "Java_1211", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/ibinti/bugvm/Binding/apple/src/main/java/com/bugvm/apple/uikit/UIActivityViewController.java", "mask_start_position": 2518, "mask_end_position": 2656, "canonical_solution": "@Deprecated\n @Property(selector = \"completionHandler\")\n @Block\n public native VoidBlock2 getCompletionHandler();", "pre_mask_code": "package com.bugvm.apple.uikit;\n\nimport java.io.*;\nimport java.nio.*;\nimport java.util.*;\nimport com.bugvm.objc.*;\nimport com.bugvm.objc.annotation.*;\nimport com.bugvm.objc.block.*;\nimport com.bugvm.rt.*;\nimport com.bugvm.rt.annotation.*;\nimport com.bugvm.rt.bro.*;\nimport com.bugvm.rt.bro.annotation.*;\nimport com.bugvm.rt.bro.ptr.*;\nimport com.bugvm.apple.foundation.*;\nimport com.bugvm.apple.coreanimation.*;\nimport com.bugvm.apple.coregraphics.*;\nimport com.bugvm.apple.coredata.*;\nimport com.bugvm.apple.coreimage.*;\nimport com.bugvm.apple.coretext.*;\nimport com.bugvm.apple.corelocation.*;\n\n/**\n * @since Available in iOS 6.0 and later.\n */\n@Library(\"UIKit\")\n@NativeClass\npublic class UIActivityViewController extends UIViewController {\n\n public static class UIActivityViewControllerPtr extends Ptr {\n }\n\n static {\n ObjCRuntime.bind(UIActivityViewController.class);\n }\n\n public UIActivityViewController() {\n }\n\n protected UIActivityViewController(SkipInit skipInit) {\n super(skipInit);\n }\n\n public UIActivityViewController(String nibNameOrNil, NSBundle nibBundleOrNil) {\n super((SkipInit) null);\n initObject(init(nibNameOrNil, nibBundleOrNil));\n }\n\n public UIActivityViewController(NSCoder aDecoder) {\n super((SkipInit) null);\n initObject(init(aDecoder));\n }\n\n public UIActivityViewController(NSArray activityItems, NSArray applicationActivities) {\n super((SkipInit) null);\n initObject(init(activityItems, applicationActivities));\n }\n\n public UIActivityViewController(List activityItems, NSArray applicationActivities) {\n super((SkipInit) null);\n NSArray items = new NSMutableArray<>();\n for (Object item : activityItems) {\n if (!(item instanceof NSObject)) {\n if (item instanceof String) {\n items.add(new NSString((String) item));\n } else if (item instanceof Number) {\n items.add(NSNumber.valueOf((Number) item));\n } else {\n throw new IllegalArgumentException(\"Unsupported activity item type: \" + item);\n }\n } else {\n items.add((NSObject) item);\n }\n }\n initObject(init(items, applicationActivities));\n }\n\n /**\n * @since Available in iOS 6.0 and later.\n * @deprecated Deprecated in iOS 8.0.\n */\n ", "post_mask_code": "\n\n /**\n * @since Available in iOS 6.0 and later.\n * @deprecated Deprecated in iOS 8.0.\n */\n @Deprecated\n @Property(selector = \"setCompletionHandler:\")\n public native void setCompletionHandler(@Block VoidBlock2 v);\n\n /**\n * @since Available in iOS 8.0 and later.\n */\n @Property(selector = \"completionWithItemsHandler\")\n @Block\n public native VoidBlock4, NSError> getCompletionWithItemsHandler();\n\n /**\n * @since Available in iOS 8.0 and later.\n */\n @Property(selector = \"setCompletionWithItemsHandler:\")\n public native void setCompletionWithItemsHandler(@Block VoidBlock4, NSError> v);\n\n @Property(selector = \"excludedActivityTypes\")\n @com.bugvm.rt.bro.annotation.Marshaler(NSArray.AsStringListMarshaler.class)\n public native List getExcludedActivityTypes();\n\n @Property(selector = \"setExcludedActivityTypes:\")\n public native void setExcludedActivityTypes(@com.bugvm.rt.bro.annotation.Marshaler(NSArray.AsStringListMarshaler.class) List v);\n\n @Method(selector = \"initWithNibName:bundle:\")\n @Pointer\n protected native long init(String nibNameOrNil, NSBundle nibBundleOrNil);\n\n @Method(selector = \"initWithCoder:\")\n @Pointer\n protected native long init(NSCoder aDecoder);\n\n @Method(selector = \"initWithActivityItems:applicationActivities:\")\n @Pointer\n protected native long init(NSArray activityItems, NSArray applicationActivities);\n}\n"} {"task_id": "Java_1212", "language": "Java", "task_type": "if_statement", "source_file": "java/github/ibinti/bugvm/Binding/apple/src/main/java/com/bugvm/apple/uikit/UIActivityViewController.java", "mask_start_position": 2022, "mask_end_position": 2257, "canonical_solution": "if (item instanceof Number) {\n items.add(NSNumber.valueOf((Number) item));\n } else {\n throw new IllegalArgumentException(\"Unsupported activity item type: \" + item);\n }", "pre_mask_code": "package com.bugvm.apple.uikit;\n\nimport java.io.*;\nimport java.nio.*;\nimport java.util.*;\nimport com.bugvm.objc.*;\nimport com.bugvm.objc.annotation.*;\nimport com.bugvm.objc.block.*;\nimport com.bugvm.rt.*;\nimport com.bugvm.rt.annotation.*;\nimport com.bugvm.rt.bro.*;\nimport com.bugvm.rt.bro.annotation.*;\nimport com.bugvm.rt.bro.ptr.*;\nimport com.bugvm.apple.foundation.*;\nimport com.bugvm.apple.coreanimation.*;\nimport com.bugvm.apple.coregraphics.*;\nimport com.bugvm.apple.coredata.*;\nimport com.bugvm.apple.coreimage.*;\nimport com.bugvm.apple.coretext.*;\nimport com.bugvm.apple.corelocation.*;\n\n/**\n * @since Available in iOS 6.0 and later.\n */\n@Library(\"UIKit\")\n@NativeClass\npublic class UIActivityViewController extends UIViewController {\n\n public static class UIActivityViewControllerPtr extends Ptr {\n }\n\n static {\n ObjCRuntime.bind(UIActivityViewController.class);\n }\n\n public UIActivityViewController() {\n }\n\n protected UIActivityViewController(SkipInit skipInit) {\n super(skipInit);\n }\n\n public UIActivityViewController(String nibNameOrNil, NSBundle nibBundleOrNil) {\n super((SkipInit) null);\n initObject(init(nibNameOrNil, nibBundleOrNil));\n }\n\n public UIActivityViewController(NSCoder aDecoder) {\n super((SkipInit) null);\n initObject(init(aDecoder));\n }\n\n public UIActivityViewController(NSArray activityItems, NSArray applicationActivities) {\n super((SkipInit) null);\n initObject(init(activityItems, applicationActivities));\n }\n\n public UIActivityViewController(List activityItems, NSArray applicationActivities) {\n super((SkipInit) null);\n NSArray items = new NSMutableArray<>();\n for (Object item : activityItems) {\n if (!(item instanceof NSObject)) {\n if (item instanceof String) {\n items.add(new NSString((String) item));\n } else ", "post_mask_code": "\n } else {\n items.add((NSObject) item);\n }\n }\n initObject(init(items, applicationActivities));\n }\n\n /**\n * @since Available in iOS 6.0 and later.\n * @deprecated Deprecated in iOS 8.0.\n */\n @Deprecated\n @Property(selector = \"completionHandler\")\n @Block\n public native VoidBlock2 getCompletionHandler();\n\n /**\n * @since Available in iOS 6.0 and later.\n * @deprecated Deprecated in iOS 8.0.\n */\n @Deprecated\n @Property(selector = \"setCompletionHandler:\")\n public native void setCompletionHandler(@Block VoidBlock2 v);\n\n /**\n * @since Available in iOS 8.0 and later.\n */\n @Property(selector = \"completionWithItemsHandler\")\n @Block\n public native VoidBlock4, NSError> getCompletionWithItemsHandler();\n\n /**\n * @since Available in iOS 8.0 and later.\n */\n @Property(selector = \"setCompletionWithItemsHandler:\")\n public native void setCompletionWithItemsHandler(@Block VoidBlock4, NSError> v);\n\n @Property(selector = \"excludedActivityTypes\")\n @com.bugvm.rt.bro.annotation.Marshaler(NSArray.AsStringListMarshaler.class)\n public native List getExcludedActivityTypes();\n\n @Property(selector = \"setExcludedActivityTypes:\")\n public native void setExcludedActivityTypes(@com.bugvm.rt.bro.annotation.Marshaler(NSArray.AsStringListMarshaler.class) List v);\n\n @Method(selector = \"initWithNibName:bundle:\")\n @Pointer\n protected native long init(String nibNameOrNil, NSBundle nibBundleOrNil);\n\n @Method(selector = \"initWithCoder:\")\n @Pointer\n protected native long init(NSCoder aDecoder);\n\n @Method(selector = \"initWithActivityItems:applicationActivities:\")\n @Pointer\n protected native long init(NSArray activityItems, NSArray applicationActivities);\n}\n"} {"task_id": "Java_1213", "language": "Java", "task_type": "method_signature", "source_file": "java/github/benblaszczak/BobEngine/BobEngine/bobEngine/src/main/java/com/bobbyloujo/bobengine/extra/BobHelper.java", "mask_start_position": 11140, "mask_end_position": 11204, "canonical_solution": "public String getSavedString(String name, final String DEFAULT) ", "pre_mask_code": "/**\n * BobEngine - 2D game engine for Android\n */\npackage com.bobbyloujo.bobengine.extra;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Point;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.WindowManager;\n\n/**\n * This helper class contains some useful functionality for your app.\n *\n * Created by Benjamin on 2/13/2015.\n */\npublic class BobHelper {\n\n // Constants\n final // The flags for immersive mode\n int // The flags for immersive mode\n VISIBILITY = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n\n // Data\n // Real width of the screen in pixels\n private int screenWidth;\n\n // Real height of the screen in pixels\n private int screenHeight;\n\n // Flag that determines if Immersive Mode is in use\n private boolean useImmersive = false;\n\n // Name of shared preferences file for saving data\n private String save = \"save\";\n\n // Objects\n private Activity activity;\n\n private WindowManager wm;\n\n private Point size;\n\n /**\n * You should initialize your BobHelper in or after onCreate() of activity.\n * @param activity - The activity that this BobHelper is tied to.\n */\n @SuppressLint(\"NewApi\")\n public BobHelper(Activity activity) {\n this.activity = activity;\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);\n Log.i(\"info\", Integer.toString(am.getMemoryClass()) + \"MB ram available.\");\n }\n\n public void onResume() {\n if (useImmersive) {\n useImmersiveMode();\n }\n }\n\n /**\n * Uses KitKat's immersive mode. Immersive mode only works on Android 4.4.2\n * and up. There is no need to check for version number when using this\n * method. This method will handle older versions for you.\n */\n @SuppressLint(\"NewApi\")\n public void useImmersiveMode() {\n try {\n // Immersive mode (Will not work on versions prior to 4.4.2)\n // Set the flags for immersive mode\n activity.getWindow().getDecorView().setSystemUiVisibility(VISIBILITY);\n // Add a listener to detect if we have lost immersive mode\n UIChangeListener();\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n // Get -REAL- screen size. This excludes the navbar, which isn't visible\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n useImmersive = true;\n } catch (NoSuchMethodError e) {\n // Immersive mode not supported (Android version < 4.4.2)\n // Get KitKat!\n Log.d(\"BobEngine\", \"Immersive mode not supported. (Android version < 4.4.2)\");\n }\n }\n\n /**\n * This method creates a listener that will detect when immersive mode is\n * lost and get it back. Needs to be called again in onResume.\n */\n @SuppressLint(\"NewApi\")\n private void UIChangeListener() {\n final View decorView = activity.getWindow().getDecorView();\n decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {\n\n @Override\n public void onSystemUiVisibilityChange(int visibility) {\n if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {\n decorView.setSystemUiVisibility(VISIBILITY);\n }\n }\n });\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real width of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the width of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenWidth() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n }\n return screenWidth;\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real height of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the height of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenHeight() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n return screenHeight;\n }\n\n /**\n * Set the save file to use with saveInt()... getSavedInt()... etc.\n * @param fileName\n */\n public void setSaveFile(String fileName) {\n save = fileName;\n }\n\n /**\n * Save an integer value. It can be retrieved even after the application has quit\n * by calling getSavedInt();\n *\n * @param name - name of the saved integer. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveInt(String name, int value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putInt(name, value);\n edit.commit();\n }\n\n /**\n * Save an boolean value. It can be retrieved even after the application has quit\n * by calling getSavedBool();\n *\n * @param name - name of the saved boolean. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveBool(String name, boolean value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putBoolean(name, value);\n edit.commit();\n }\n\n /**\n * Save an float value. It can be retrieved even after the application has quit\n * by calling getSavedFloat();\n *\n * @param name - name of the saved float. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveFloat(String name, float value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putFloat(name, value);\n edit.commit();\n }\n\n /**\n * Save an string value. It can be retrieved even after the application has quit\n * by calling getSavedString();\n *\n * @param name - name of the saved string. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveString(String name, String value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putString(name, value);\n edit.commit();\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, 0);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, 0f);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, false);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, \"\");\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name, final int DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name, final float DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name, final boolean DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n ", "post_mask_code": "{\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, DEFAULT);\n }\n}\n"} {"task_id": "Java_1214", "language": "Java", "task_type": "method_body", "source_file": "java/github/benblaszczak/BobEngine/BobEngine/bobEngine/src/main/java/com/bobbyloujo/bobengine/extra/BobHelper.java", "mask_start_position": 8266, "mask_end_position": 8481, "canonical_solution": "{\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putString(name, value);\n edit.commit();\n }", "pre_mask_code": "/**\n * BobEngine - 2D game engine for Android\n */\npackage com.bobbyloujo.bobengine.extra;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Point;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.WindowManager;\n\n/**\n * This helper class contains some useful functionality for your app.\n *\n * Created by Benjamin on 2/13/2015.\n */\npublic class BobHelper {\n\n // Constants\n final // The flags for immersive mode\n int // The flags for immersive mode\n VISIBILITY = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n\n // Data\n // Real width of the screen in pixels\n private int screenWidth;\n\n // Real height of the screen in pixels\n private int screenHeight;\n\n // Flag that determines if Immersive Mode is in use\n private boolean useImmersive = false;\n\n // Name of shared preferences file for saving data\n private String save = \"save\";\n\n // Objects\n private Activity activity;\n\n private WindowManager wm;\n\n private Point size;\n\n /**\n * You should initialize your BobHelper in or after onCreate() of activity.\n * @param activity - The activity that this BobHelper is tied to.\n */\n @SuppressLint(\"NewApi\")\n public BobHelper(Activity activity) {\n this.activity = activity;\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);\n Log.i(\"info\", Integer.toString(am.getMemoryClass()) + \"MB ram available.\");\n }\n\n public void onResume() {\n if (useImmersive) {\n useImmersiveMode();\n }\n }\n\n /**\n * Uses KitKat's immersive mode. Immersive mode only works on Android 4.4.2\n * and up. There is no need to check for version number when using this\n * method. This method will handle older versions for you.\n */\n @SuppressLint(\"NewApi\")\n public void useImmersiveMode() {\n try {\n // Immersive mode (Will not work on versions prior to 4.4.2)\n // Set the flags for immersive mode\n activity.getWindow().getDecorView().setSystemUiVisibility(VISIBILITY);\n // Add a listener to detect if we have lost immersive mode\n UIChangeListener();\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n // Get -REAL- screen size. This excludes the navbar, which isn't visible\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n useImmersive = true;\n } catch (NoSuchMethodError e) {\n // Immersive mode not supported (Android version < 4.4.2)\n // Get KitKat!\n Log.d(\"BobEngine\", \"Immersive mode not supported. (Android version < 4.4.2)\");\n }\n }\n\n /**\n * This method creates a listener that will detect when immersive mode is\n * lost and get it back. Needs to be called again in onResume.\n */\n @SuppressLint(\"NewApi\")\n private void UIChangeListener() {\n final View decorView = activity.getWindow().getDecorView();\n decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {\n\n @Override\n public void onSystemUiVisibilityChange(int visibility) {\n if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {\n decorView.setSystemUiVisibility(VISIBILITY);\n }\n }\n });\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real width of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the width of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenWidth() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n }\n return screenWidth;\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real height of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the height of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenHeight() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n return screenHeight;\n }\n\n /**\n * Set the save file to use with saveInt()... getSavedInt()... etc.\n * @param fileName\n */\n public void setSaveFile(String fileName) {\n save = fileName;\n }\n\n /**\n * Save an integer value. It can be retrieved even after the application has quit\n * by calling getSavedInt();\n *\n * @param name - name of the saved integer. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveInt(String name, int value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putInt(name, value);\n edit.commit();\n }\n\n /**\n * Save an boolean value. It can be retrieved even after the application has quit\n * by calling getSavedBool();\n *\n * @param name - name of the saved boolean. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveBool(String name, boolean value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putBoolean(name, value);\n edit.commit();\n }\n\n /**\n * Save an float value. It can be retrieved even after the application has quit\n * by calling getSavedFloat();\n *\n * @param name - name of the saved float. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveFloat(String name, float value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putFloat(name, value);\n edit.commit();\n }\n\n /**\n * Save an string value. It can be retrieved even after the application has quit\n * by calling getSavedString();\n *\n * @param name - name of the saved string. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveString(String name, String value) ", "post_mask_code": "\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, 0);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, 0f);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, false);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, \"\");\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name, final int DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name, final float DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name, final boolean DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name, final String DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, DEFAULT);\n }\n}\n"} {"task_id": "Java_1215", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/benblaszczak/BobEngine/BobEngine/bobEngine/src/main/java/com/bobbyloujo/bobengine/extra/BobHelper.java", "mask_start_position": 2775, "mask_end_position": 2775, "canonical_solution": "", "pre_mask_code": "/**\n * BobEngine - 2D game engine for Android\n */\npackage com.bobbyloujo.bobengine.extra;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Point;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.WindowManager;\n\n/**\n * This helper class contains some useful functionality for your app.\n *\n * Created by Benjamin on 2/13/2015.\n */\npublic class BobHelper {\n\n // Constants\n final // The flags for immersive mode\n int // The flags for immersive mode\n VISIBILITY = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n\n // Data\n // Real width of the screen in pixels\n private int screenWidth;\n\n // Real height of the screen in pixels\n private int screenHeight;\n\n // Flag that determines if Immersive Mode is in use\n private boolean useImmersive = false;\n\n // Name of shared preferences file for saving data\n private String save = \"save\";\n\n // Objects\n private Activity activity;\n\n private WindowManager wm;\n\n private Point size;\n\n /**\n * You should initialize your BobHelper in or after onCreate() of activity.\n * @param activity - The activity that this BobHelper is tied to.\n */\n @SuppressLint(\"NewApi\")\n public BobHelper(Activity activity) {\n this.activity = activity;\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);\n Log.i(\"info\", Integer.toString(am.getMemoryClass()) + \"MB ram available.\");\n }\n\n public void onResume() {\n if (useImmersive) {\n useImmersiveMode();\n }\n }\n\n /**\n * Uses KitKat's immersive mode. Immersive mode only works on Android 4.4.2\n * and up. There is no need to check for version number when using this\n * method. This method will handle older versions for you.\n */\n @SuppressLint(\"NewApi\")\n public void useImmersiveMode() {", "post_mask_code": "\n try {\n // Immersive mode (Will not work on versions prior to 4.4.2)\n // Set the flags for immersive mode\n activity.getWindow().getDecorView().setSystemUiVisibility(VISIBILITY);\n // Add a listener to detect if we have lost immersive mode\n UIChangeListener();\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n // Get -REAL- screen size. This excludes the navbar, which isn't visible\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n useImmersive = true;\n } catch (NoSuchMethodError e) {\n // Immersive mode not supported (Android version < 4.4.2)\n // Get KitKat!\n Log.d(\"BobEngine\", \"Immersive mode not supported. (Android version < 4.4.2)\");\n }\n }\n\n /**\n * This method creates a listener that will detect when immersive mode is\n * lost and get it back. Needs to be called again in onResume.\n */\n @SuppressLint(\"NewApi\")\n private void UIChangeListener() {\n final View decorView = activity.getWindow().getDecorView();\n decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {\n\n @Override\n public void onSystemUiVisibilityChange(int visibility) {\n if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {\n decorView.setSystemUiVisibility(VISIBILITY);\n }\n }\n });\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real width of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the width of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenWidth() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n }\n return screenWidth;\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real height of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the height of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenHeight() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n return screenHeight;\n }\n\n /**\n * Set the save file to use with saveInt()... getSavedInt()... etc.\n * @param fileName\n */\n public void setSaveFile(String fileName) {\n save = fileName;\n }\n\n /**\n * Save an integer value. It can be retrieved even after the application has quit\n * by calling getSavedInt();\n *\n * @param name - name of the saved integer. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveInt(String name, int value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putInt(name, value);\n edit.commit();\n }\n\n /**\n * Save an boolean value. It can be retrieved even after the application has quit\n * by calling getSavedBool();\n *\n * @param name - name of the saved boolean. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveBool(String name, boolean value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putBoolean(name, value);\n edit.commit();\n }\n\n /**\n * Save an float value. It can be retrieved even after the application has quit\n * by calling getSavedFloat();\n *\n * @param name - name of the saved float. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveFloat(String name, float value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putFloat(name, value);\n edit.commit();\n }\n\n /**\n * Save an string value. It can be retrieved even after the application has quit\n * by calling getSavedString();\n *\n * @param name - name of the saved string. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveString(String name, String value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putString(name, value);\n edit.commit();\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, 0);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, 0f);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, false);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, \"\");\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name, final int DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name, final float DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name, final boolean DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name, final String DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, DEFAULT);\n }\n}\n"} {"task_id": "Java_1216", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/benblaszczak/BobEngine/BobEngine/bobEngine/src/main/java/com/bobbyloujo/bobengine/extra/BobHelper.java", "mask_start_position": 2784, "mask_end_position": 3691, "canonical_solution": "try {\n // Immersive mode (Will not work on versions prior to 4.4.2)\n // Set the flags for immersive mode\n activity.getWindow().getDecorView().setSystemUiVisibility(VISIBILITY);\n // Add a listener to detect if we have lost immersive mode\n UIChangeListener();\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n // Get -REAL- screen size. This excludes the navbar, which isn't visible\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n useImmersive = true;\n } catch (NoSuchMethodError e) {\n // Immersive mode not supported (Android version < 4.4.2)\n // Get KitKat!\n Log.d(\"BobEngine\", \"Immersive mode not supported. (Android version < 4.4.2)\");\n }", "pre_mask_code": "/**\n * BobEngine - 2D game engine for Android\n */\npackage com.bobbyloujo.bobengine.extra;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Point;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.WindowManager;\n\n/**\n * This helper class contains some useful functionality for your app.\n *\n * Created by Benjamin on 2/13/2015.\n */\npublic class BobHelper {\n\n // Constants\n final // The flags for immersive mode\n int // The flags for immersive mode\n VISIBILITY = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n\n // Data\n // Real width of the screen in pixels\n private int screenWidth;\n\n // Real height of the screen in pixels\n private int screenHeight;\n\n // Flag that determines if Immersive Mode is in use\n private boolean useImmersive = false;\n\n // Name of shared preferences file for saving data\n private String save = \"save\";\n\n // Objects\n private Activity activity;\n\n private WindowManager wm;\n\n private Point size;\n\n /**\n * You should initialize your BobHelper in or after onCreate() of activity.\n * @param activity - The activity that this BobHelper is tied to.\n */\n @SuppressLint(\"NewApi\")\n public BobHelper(Activity activity) {\n this.activity = activity;\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);\n Log.i(\"info\", Integer.toString(am.getMemoryClass()) + \"MB ram available.\");\n }\n\n public void onResume() {\n if (useImmersive) {\n useImmersiveMode();\n }\n }\n\n /**\n * Uses KitKat's immersive mode. Immersive mode only works on Android 4.4.2\n * and up. There is no need to check for version number when using this\n * method. This method will handle older versions for you.\n */\n @SuppressLint(\"NewApi\")\n public void useImmersiveMode() {\n ", "post_mask_code": "\n }\n\n /**\n * This method creates a listener that will detect when immersive mode is\n * lost and get it back. Needs to be called again in onResume.\n */\n @SuppressLint(\"NewApi\")\n private void UIChangeListener() {\n final View decorView = activity.getWindow().getDecorView();\n decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {\n\n @Override\n public void onSystemUiVisibilityChange(int visibility) {\n if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {\n decorView.setSystemUiVisibility(VISIBILITY);\n }\n }\n });\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real width of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the width of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenWidth() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n }\n return screenWidth;\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real height of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the height of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenHeight() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n return screenHeight;\n }\n\n /**\n * Set the save file to use with saveInt()... getSavedInt()... etc.\n * @param fileName\n */\n public void setSaveFile(String fileName) {\n save = fileName;\n }\n\n /**\n * Save an integer value. It can be retrieved even after the application has quit\n * by calling getSavedInt();\n *\n * @param name - name of the saved integer. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveInt(String name, int value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putInt(name, value);\n edit.commit();\n }\n\n /**\n * Save an boolean value. It can be retrieved even after the application has quit\n * by calling getSavedBool();\n *\n * @param name - name of the saved boolean. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveBool(String name, boolean value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putBoolean(name, value);\n edit.commit();\n }\n\n /**\n * Save an float value. It can be retrieved even after the application has quit\n * by calling getSavedFloat();\n *\n * @param name - name of the saved float. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveFloat(String name, float value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putFloat(name, value);\n edit.commit();\n }\n\n /**\n * Save an string value. It can be retrieved even after the application has quit\n * by calling getSavedString();\n *\n * @param name - name of the saved string. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveString(String name, String value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putString(name, value);\n edit.commit();\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, 0);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, 0f);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, false);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, \"\");\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name, final int DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name, final float DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name, final boolean DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name, final String DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, DEFAULT);\n }\n}\n"} {"task_id": "Java_1217", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/benblaszczak/BobEngine/BobEngine/bobEngine/src/main/java/com/bobbyloujo/bobengine/extra/BobHelper.java", "mask_start_position": 3696, "mask_end_position": 3697, "canonical_solution": "}", "pre_mask_code": "/**\n * BobEngine - 2D game engine for Android\n */\npackage com.bobbyloujo.bobengine.extra;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Point;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.WindowManager;\n\n/**\n * This helper class contains some useful functionality for your app.\n *\n * Created by Benjamin on 2/13/2015.\n */\npublic class BobHelper {\n\n // Constants\n final // The flags for immersive mode\n int // The flags for immersive mode\n VISIBILITY = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n\n // Data\n // Real width of the screen in pixels\n private int screenWidth;\n\n // Real height of the screen in pixels\n private int screenHeight;\n\n // Flag that determines if Immersive Mode is in use\n private boolean useImmersive = false;\n\n // Name of shared preferences file for saving data\n private String save = \"save\";\n\n // Objects\n private Activity activity;\n\n private WindowManager wm;\n\n private Point size;\n\n /**\n * You should initialize your BobHelper in or after onCreate() of activity.\n * @param activity - The activity that this BobHelper is tied to.\n */\n @SuppressLint(\"NewApi\")\n public BobHelper(Activity activity) {\n this.activity = activity;\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);\n Log.i(\"info\", Integer.toString(am.getMemoryClass()) + \"MB ram available.\");\n }\n\n public void onResume() {\n if (useImmersive) {\n useImmersiveMode();\n }\n }\n\n /**\n * Uses KitKat's immersive mode. Immersive mode only works on Android 4.4.2\n * and up. There is no need to check for version number when using this\n * method. This method will handle older versions for you.\n */\n @SuppressLint(\"NewApi\")\n public void useImmersiveMode() {\n try {\n // Immersive mode (Will not work on versions prior to 4.4.2)\n // Set the flags for immersive mode\n activity.getWindow().getDecorView().setSystemUiVisibility(VISIBILITY);\n // Add a listener to detect if we have lost immersive mode\n UIChangeListener();\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n // Get -REAL- screen size. This excludes the navbar, which isn't visible\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n useImmersive = true;\n } catch (NoSuchMethodError e) {\n // Immersive mode not supported (Android version < 4.4.2)\n // Get KitKat!\n Log.d(\"BobEngine\", \"Immersive mode not supported. (Android version < 4.4.2)\");\n }\n ", "post_mask_code": "\n\n /**\n * This method creates a listener that will detect when immersive mode is\n * lost and get it back. Needs to be called again in onResume.\n */\n @SuppressLint(\"NewApi\")\n private void UIChangeListener() {\n final View decorView = activity.getWindow().getDecorView();\n decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {\n\n @Override\n public void onSystemUiVisibilityChange(int visibility) {\n if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {\n decorView.setSystemUiVisibility(VISIBILITY);\n }\n }\n });\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real width of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the width of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenWidth() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n }\n return screenWidth;\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real height of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the height of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenHeight() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n return screenHeight;\n }\n\n /**\n * Set the save file to use with saveInt()... getSavedInt()... etc.\n * @param fileName\n */\n public void setSaveFile(String fileName) {\n save = fileName;\n }\n\n /**\n * Save an integer value. It can be retrieved even after the application has quit\n * by calling getSavedInt();\n *\n * @param name - name of the saved integer. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveInt(String name, int value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putInt(name, value);\n edit.commit();\n }\n\n /**\n * Save an boolean value. It can be retrieved even after the application has quit\n * by calling getSavedBool();\n *\n * @param name - name of the saved boolean. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveBool(String name, boolean value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putBoolean(name, value);\n edit.commit();\n }\n\n /**\n * Save an float value. It can be retrieved even after the application has quit\n * by calling getSavedFloat();\n *\n * @param name - name of the saved float. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveFloat(String name, float value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putFloat(name, value);\n edit.commit();\n }\n\n /**\n * Save an string value. It can be retrieved even after the application has quit\n * by calling getSavedString();\n *\n * @param name - name of the saved string. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveString(String name, String value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putString(name, value);\n edit.commit();\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, 0);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, 0f);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, false);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, \"\");\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name, final int DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name, final float DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name, final boolean DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name, final String DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, DEFAULT);\n }\n}\n"} {"task_id": "Java_1218", "language": "Java", "task_type": "single_line", "source_file": "java/github/benblaszczak/BobEngine/BobEngine/bobEngine/src/main/java/com/bobbyloujo/bobengine/extra/BobHelper.java", "mask_start_position": 8787, "mask_end_position": 8812, "canonical_solution": "rn prefs.getInt(name, 0);", "pre_mask_code": "/**\n * BobEngine - 2D game engine for Android\n */\npackage com.bobbyloujo.bobengine.extra;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Point;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.WindowManager;\n\n/**\n * This helper class contains some useful functionality for your app.\n *\n * Created by Benjamin on 2/13/2015.\n */\npublic class BobHelper {\n\n // Constants\n final // The flags for immersive mode\n int // The flags for immersive mode\n VISIBILITY = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n\n // Data\n // Real width of the screen in pixels\n private int screenWidth;\n\n // Real height of the screen in pixels\n private int screenHeight;\n\n // Flag that determines if Immersive Mode is in use\n private boolean useImmersive = false;\n\n // Name of shared preferences file for saving data\n private String save = \"save\";\n\n // Objects\n private Activity activity;\n\n private WindowManager wm;\n\n private Point size;\n\n /**\n * You should initialize your BobHelper in or after onCreate() of activity.\n * @param activity - The activity that this BobHelper is tied to.\n */\n @SuppressLint(\"NewApi\")\n public BobHelper(Activity activity) {\n this.activity = activity;\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);\n Log.i(\"info\", Integer.toString(am.getMemoryClass()) + \"MB ram available.\");\n }\n\n public void onResume() {\n if (useImmersive) {\n useImmersiveMode();\n }\n }\n\n /**\n * Uses KitKat's immersive mode. Immersive mode only works on Android 4.4.2\n * and up. There is no need to check for version number when using this\n * method. This method will handle older versions for you.\n */\n @SuppressLint(\"NewApi\")\n public void useImmersiveMode() {\n try {\n // Immersive mode (Will not work on versions prior to 4.4.2)\n // Set the flags for immersive mode\n activity.getWindow().getDecorView().setSystemUiVisibility(VISIBILITY);\n // Add a listener to detect if we have lost immersive mode\n UIChangeListener();\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n // Get -REAL- screen size. This excludes the navbar, which isn't visible\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n useImmersive = true;\n } catch (NoSuchMethodError e) {\n // Immersive mode not supported (Android version < 4.4.2)\n // Get KitKat!\n Log.d(\"BobEngine\", \"Immersive mode not supported. (Android version < 4.4.2)\");\n }\n }\n\n /**\n * This method creates a listener that will detect when immersive mode is\n * lost and get it back. Needs to be called again in onResume.\n */\n @SuppressLint(\"NewApi\")\n private void UIChangeListener() {\n final View decorView = activity.getWindow().getDecorView();\n decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {\n\n @Override\n public void onSystemUiVisibilityChange(int visibility) {\n if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {\n decorView.setSystemUiVisibility(VISIBILITY);\n }\n }\n });\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real width of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the width of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenWidth() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n }\n return screenWidth;\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real height of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the height of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenHeight() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n return screenHeight;\n }\n\n /**\n * Set the save file to use with saveInt()... getSavedInt()... etc.\n * @param fileName\n */\n public void setSaveFile(String fileName) {\n save = fileName;\n }\n\n /**\n * Save an integer value. It can be retrieved even after the application has quit\n * by calling getSavedInt();\n *\n * @param name - name of the saved integer. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveInt(String name, int value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putInt(name, value);\n edit.commit();\n }\n\n /**\n * Save an boolean value. It can be retrieved even after the application has quit\n * by calling getSavedBool();\n *\n * @param name - name of the saved boolean. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveBool(String name, boolean value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putBoolean(name, value);\n edit.commit();\n }\n\n /**\n * Save an float value. It can be retrieved even after the application has quit\n * by calling getSavedFloat();\n *\n * @param name - name of the saved float. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveFloat(String name, float value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putFloat(name, value);\n edit.commit();\n }\n\n /**\n * Save an string value. It can be retrieved even after the application has quit\n * by calling getSavedString();\n *\n * @param name - name of the saved string. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveString(String name, String value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putString(name, value);\n edit.commit();\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n retu", "post_mask_code": "\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, 0f);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, false);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, \"\");\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name, final int DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name, final float DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name, final boolean DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name, final String DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, DEFAULT);\n }\n}\n"} {"task_id": "Java_1219", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/benblaszczak/BobEngine/BobEngine/bobEngine/src/main/java/com/bobbyloujo/bobengine/extra/BobHelper.java", "mask_start_position": 8981, "mask_end_position": 9163, "canonical_solution": "public float getSavedFloat(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, 0f);\n }", "pre_mask_code": "/**\n * BobEngine - 2D game engine for Android\n */\npackage com.bobbyloujo.bobengine.extra;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Point;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.WindowManager;\n\n/**\n * This helper class contains some useful functionality for your app.\n *\n * Created by Benjamin on 2/13/2015.\n */\npublic class BobHelper {\n\n // Constants\n final // The flags for immersive mode\n int // The flags for immersive mode\n VISIBILITY = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n\n // Data\n // Real width of the screen in pixels\n private int screenWidth;\n\n // Real height of the screen in pixels\n private int screenHeight;\n\n // Flag that determines if Immersive Mode is in use\n private boolean useImmersive = false;\n\n // Name of shared preferences file for saving data\n private String save = \"save\";\n\n // Objects\n private Activity activity;\n\n private WindowManager wm;\n\n private Point size;\n\n /**\n * You should initialize your BobHelper in or after onCreate() of activity.\n * @param activity - The activity that this BobHelper is tied to.\n */\n @SuppressLint(\"NewApi\")\n public BobHelper(Activity activity) {\n this.activity = activity;\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);\n Log.i(\"info\", Integer.toString(am.getMemoryClass()) + \"MB ram available.\");\n }\n\n public void onResume() {\n if (useImmersive) {\n useImmersiveMode();\n }\n }\n\n /**\n * Uses KitKat's immersive mode. Immersive mode only works on Android 4.4.2\n * and up. There is no need to check for version number when using this\n * method. This method will handle older versions for you.\n */\n @SuppressLint(\"NewApi\")\n public void useImmersiveMode() {\n try {\n // Immersive mode (Will not work on versions prior to 4.4.2)\n // Set the flags for immersive mode\n activity.getWindow().getDecorView().setSystemUiVisibility(VISIBILITY);\n // Add a listener to detect if we have lost immersive mode\n UIChangeListener();\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n // Get -REAL- screen size. This excludes the navbar, which isn't visible\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n useImmersive = true;\n } catch (NoSuchMethodError e) {\n // Immersive mode not supported (Android version < 4.4.2)\n // Get KitKat!\n Log.d(\"BobEngine\", \"Immersive mode not supported. (Android version < 4.4.2)\");\n }\n }\n\n /**\n * This method creates a listener that will detect when immersive mode is\n * lost and get it back. Needs to be called again in onResume.\n */\n @SuppressLint(\"NewApi\")\n private void UIChangeListener() {\n final View decorView = activity.getWindow().getDecorView();\n decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {\n\n @Override\n public void onSystemUiVisibilityChange(int visibility) {\n if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {\n decorView.setSystemUiVisibility(VISIBILITY);\n }\n }\n });\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real width of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the width of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenWidth() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n }\n return screenWidth;\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real height of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the height of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenHeight() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n return screenHeight;\n }\n\n /**\n * Set the save file to use with saveInt()... getSavedInt()... etc.\n * @param fileName\n */\n public void setSaveFile(String fileName) {\n save = fileName;\n }\n\n /**\n * Save an integer value. It can be retrieved even after the application has quit\n * by calling getSavedInt();\n *\n * @param name - name of the saved integer. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveInt(String name, int value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putInt(name, value);\n edit.commit();\n }\n\n /**\n * Save an boolean value. It can be retrieved even after the application has quit\n * by calling getSavedBool();\n *\n * @param name - name of the saved boolean. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveBool(String name, boolean value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putBoolean(name, value);\n edit.commit();\n }\n\n /**\n * Save an float value. It can be retrieved even after the application has quit\n * by calling getSavedFloat();\n *\n * @param name - name of the saved float. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveFloat(String name, float value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putFloat(name, value);\n edit.commit();\n }\n\n /**\n * Save an string value. It can be retrieved even after the application has quit\n * by calling getSavedString();\n *\n * @param name - name of the saved string. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveString(String name, String value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putString(name, value);\n edit.commit();\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, 0);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n ", "post_mask_code": "\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, false);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, \"\");\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name, final int DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name, final float DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name, final boolean DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name, final String DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, DEFAULT);\n }\n}\n"} {"task_id": "Java_1220", "language": "Java", "task_type": "if_statement", "source_file": "java/github/benblaszczak/BobEngine/BobEngine/bobEngine/src/main/java/com/bobbyloujo/bobengine/extra/BobHelper.java", "mask_start_position": 4206, "mask_end_position": 4346, "canonical_solution": "if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {\n decorView.setSystemUiVisibility(VISIBILITY);\n }", "pre_mask_code": "/**\n * BobEngine - 2D game engine for Android\n */\npackage com.bobbyloujo.bobengine.extra;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Point;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.WindowManager;\n\n/**\n * This helper class contains some useful functionality for your app.\n *\n * Created by Benjamin on 2/13/2015.\n */\npublic class BobHelper {\n\n // Constants\n final // The flags for immersive mode\n int // The flags for immersive mode\n VISIBILITY = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n\n // Data\n // Real width of the screen in pixels\n private int screenWidth;\n\n // Real height of the screen in pixels\n private int screenHeight;\n\n // Flag that determines if Immersive Mode is in use\n private boolean useImmersive = false;\n\n // Name of shared preferences file for saving data\n private String save = \"save\";\n\n // Objects\n private Activity activity;\n\n private WindowManager wm;\n\n private Point size;\n\n /**\n * You should initialize your BobHelper in or after onCreate() of activity.\n * @param activity - The activity that this BobHelper is tied to.\n */\n @SuppressLint(\"NewApi\")\n public BobHelper(Activity activity) {\n this.activity = activity;\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);\n Log.i(\"info\", Integer.toString(am.getMemoryClass()) + \"MB ram available.\");\n }\n\n public void onResume() {\n if (useImmersive) {\n useImmersiveMode();\n }\n }\n\n /**\n * Uses KitKat's immersive mode. Immersive mode only works on Android 4.4.2\n * and up. There is no need to check for version number when using this\n * method. This method will handle older versions for you.\n */\n @SuppressLint(\"NewApi\")\n public void useImmersiveMode() {\n try {\n // Immersive mode (Will not work on versions prior to 4.4.2)\n // Set the flags for immersive mode\n activity.getWindow().getDecorView().setSystemUiVisibility(VISIBILITY);\n // Add a listener to detect if we have lost immersive mode\n UIChangeListener();\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n // Get -REAL- screen size. This excludes the navbar, which isn't visible\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n useImmersive = true;\n } catch (NoSuchMethodError e) {\n // Immersive mode not supported (Android version < 4.4.2)\n // Get KitKat!\n Log.d(\"BobEngine\", \"Immersive mode not supported. (Android version < 4.4.2)\");\n }\n }\n\n /**\n * This method creates a listener that will detect when immersive mode is\n * lost and get it back. Needs to be called again in onResume.\n */\n @SuppressLint(\"NewApi\")\n private void UIChangeListener() {\n final View decorView = activity.getWindow().getDecorView();\n decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {\n\n @Override\n public void onSystemUiVisibilityChange(int visibility) {\n ", "post_mask_code": "\n }\n });\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real width of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the width of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenWidth() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n }\n return screenWidth;\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real height of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the height of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenHeight() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n return screenHeight;\n }\n\n /**\n * Set the save file to use with saveInt()... getSavedInt()... etc.\n * @param fileName\n */\n public void setSaveFile(String fileName) {\n save = fileName;\n }\n\n /**\n * Save an integer value. It can be retrieved even after the application has quit\n * by calling getSavedInt();\n *\n * @param name - name of the saved integer. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveInt(String name, int value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putInt(name, value);\n edit.commit();\n }\n\n /**\n * Save an boolean value. It can be retrieved even after the application has quit\n * by calling getSavedBool();\n *\n * @param name - name of the saved boolean. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveBool(String name, boolean value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putBoolean(name, value);\n edit.commit();\n }\n\n /**\n * Save an float value. It can be retrieved even after the application has quit\n * by calling getSavedFloat();\n *\n * @param name - name of the saved float. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveFloat(String name, float value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putFloat(name, value);\n edit.commit();\n }\n\n /**\n * Save an string value. It can be retrieved even after the application has quit\n * by calling getSavedString();\n *\n * @param name - name of the saved string. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveString(String name, String value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putString(name, value);\n edit.commit();\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, 0);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, 0f);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, false);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, \"\");\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name, final int DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name, final float DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name, final boolean DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name, final String DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, DEFAULT);\n }\n}\n"} {"task_id": "Java_1221", "language": "Java", "task_type": "try_statement", "source_file": "java/github/benblaszczak/BobEngine/BobEngine/bobEngine/src/main/java/com/bobbyloujo/bobengine/extra/BobHelper.java", "mask_start_position": 5792, "mask_end_position": 6160, "canonical_solution": "try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenHeight = wm.getDefaultDisplay().getHeight();\n }", "pre_mask_code": "/**\n * BobEngine - 2D game engine for Android\n */\npackage com.bobbyloujo.bobengine.extra;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Point;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.WindowManager;\n\n/**\n * This helper class contains some useful functionality for your app.\n *\n * Created by Benjamin on 2/13/2015.\n */\npublic class BobHelper {\n\n // Constants\n final // The flags for immersive mode\n int // The flags for immersive mode\n VISIBILITY = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n\n // Data\n // Real width of the screen in pixels\n private int screenWidth;\n\n // Real height of the screen in pixels\n private int screenHeight;\n\n // Flag that determines if Immersive Mode is in use\n private boolean useImmersive = false;\n\n // Name of shared preferences file for saving data\n private String save = \"save\";\n\n // Objects\n private Activity activity;\n\n private WindowManager wm;\n\n private Point size;\n\n /**\n * You should initialize your BobHelper in or after onCreate() of activity.\n * @param activity - The activity that this BobHelper is tied to.\n */\n @SuppressLint(\"NewApi\")\n public BobHelper(Activity activity) {\n this.activity = activity;\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n screenHeight = wm.getDefaultDisplay().getHeight();\n }\n ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);\n Log.i(\"info\", Integer.toString(am.getMemoryClass()) + \"MB ram available.\");\n }\n\n public void onResume() {\n if (useImmersive) {\n useImmersiveMode();\n }\n }\n\n /**\n * Uses KitKat's immersive mode. Immersive mode only works on Android 4.4.2\n * and up. There is no need to check for version number when using this\n * method. This method will handle older versions for you.\n */\n @SuppressLint(\"NewApi\")\n public void useImmersiveMode() {\n try {\n // Immersive mode (Will not work on versions prior to 4.4.2)\n // Set the flags for immersive mode\n activity.getWindow().getDecorView().setSystemUiVisibility(VISIBILITY);\n // Add a listener to detect if we have lost immersive mode\n UIChangeListener();\n wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);\n size = new Point();\n // Get -REAL- screen size. This excludes the navbar, which isn't visible\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n screenHeight = size.y;\n useImmersive = true;\n } catch (NoSuchMethodError e) {\n // Immersive mode not supported (Android version < 4.4.2)\n // Get KitKat!\n Log.d(\"BobEngine\", \"Immersive mode not supported. (Android version < 4.4.2)\");\n }\n }\n\n /**\n * This method creates a listener that will detect when immersive mode is\n * lost and get it back. Needs to be called again in onResume.\n */\n @SuppressLint(\"NewApi\")\n private void UIChangeListener() {\n final View decorView = activity.getWindow().getDecorView();\n decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {\n\n @Override\n public void onSystemUiVisibilityChange(int visibility) {\n if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {\n decorView.setSystemUiVisibility(VISIBILITY);\n }\n }\n });\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real width of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the width of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenWidth() {\n try {\n // Get screen dimensions\n // New method, might not work on old devices\n wm.getDefaultDisplay().getRealSize(size);\n screenWidth = size.x;\n } catch (NoSuchMethodError er) {\n // If new method didn't work, use depreciated methods\n screenWidth = wm.getDefaultDisplay().getWidth();\n }\n return screenWidth;\n }\n\n /**\n * Returns the width of the screen.
\n *
\n * On devices using API level 13 and higher, this function will return the\n * real height of the screen including things like the navigation bar and\n * title bar.
\n *
\n * BobView includes a function to get just the height of the view.\n *\n * @return - Width of the screen, in pixels.\n */\n @SuppressLint(\"NewApi\")\n @SuppressWarnings(\"deprecation\")\n public int getScreenHeight() {\n ", "post_mask_code": "\n return screenHeight;\n }\n\n /**\n * Set the save file to use with saveInt()... getSavedInt()... etc.\n * @param fileName\n */\n public void setSaveFile(String fileName) {\n save = fileName;\n }\n\n /**\n * Save an integer value. It can be retrieved even after the application has quit\n * by calling getSavedInt();\n *\n * @param name - name of the saved integer. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveInt(String name, int value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putInt(name, value);\n edit.commit();\n }\n\n /**\n * Save an boolean value. It can be retrieved even after the application has quit\n * by calling getSavedBool();\n *\n * @param name - name of the saved boolean. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveBool(String name, boolean value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putBoolean(name, value);\n edit.commit();\n }\n\n /**\n * Save an float value. It can be retrieved even after the application has quit\n * by calling getSavedFloat();\n *\n * @param name - name of the saved float. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveFloat(String name, float value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putFloat(name, value);\n edit.commit();\n }\n\n /**\n * Save an string value. It can be retrieved even after the application has quit\n * by calling getSavedString();\n *\n * @param name - name of the saved string. Will be used for retrieval.\n * @param value - value to save.\n */\n public void saveString(String name, String value) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putString(name, value);\n edit.commit();\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, 0);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, 0f);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, false);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, \"\");\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0 if name doesn't exist.\n */\n public int getSavedInt(String name, final int DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getInt(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. 0f if name doesn't exist.\n */\n public float getSavedFloat(String name, final float DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getFloat(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. false if name doesn't exist.\n */\n public boolean getSavedBool(String name, final boolean DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getBoolean(name, DEFAULT);\n }\n\n /**\n * Get a saved value.\n *\n * @param name - name of the saved value.\n * @return saved value of name. \"\" if name doesn't exist.\n */\n public String getSavedString(String name, final String DEFAULT) {\n SharedPreferences prefs = activity.getSharedPreferences(save, activity.MODE_PRIVATE);\n return prefs.getString(name, DEFAULT);\n }\n}\n"} {"task_id": "Java_1222", "language": "Java", "task_type": "method_signature", "source_file": "java/github/zion223/FastWaiMai/latte-ec/src/main/java/com/zrp/latte/ec/main/index/spec/SpecZoneBean.java", "mask_start_position": 636, "mask_end_position": 662, "canonical_solution": "public void setId(int id) ", "pre_mask_code": "package com.zrp.latte.ec.main.index.spec;\n\nimport com.chad.library.adapter.base.entity.SectionEntity;\n\npublic class SpecZoneBean extends SectionEntity {\n\n private boolean mIsMore = false;\n\n private int mId = -1;\n\n public SpecZoneBean(SpecZoneItemEntity specItemEntity) {\n super(specItemEntity);\n }\n\n public SpecZoneBean(boolean isHeader, String header) {\n super(isHeader, header);\n }\n\n public boolean isMore() {\n return mIsMore;\n }\n\n public void setIsMore(boolean isMore) {\n this.mIsMore = isMore;\n }\n\n public int getId() {\n return mId;\n }\n\n ", "post_mask_code": "{\n this.mId = id;\n }\n}\n"} {"task_id": "Java_1223", "language": "Java", "task_type": "method_body", "source_file": "java/github/zion223/FastWaiMai/latte-ec/src/main/java/com/zrp/latte/ec/main/index/spec/SpecZoneBean.java", "mask_start_position": 540, "mask_end_position": 578, "canonical_solution": "{\n this.mIsMore = isMore;\n }", "pre_mask_code": "package com.zrp.latte.ec.main.index.spec;\n\nimport com.chad.library.adapter.base.entity.SectionEntity;\n\npublic class SpecZoneBean extends SectionEntity {\n\n private boolean mIsMore = false;\n\n private int mId = -1;\n\n public SpecZoneBean(SpecZoneItemEntity specItemEntity) {\n super(specItemEntity);\n }\n\n public SpecZoneBean(boolean isHeader, String header) {\n super(isHeader, header);\n }\n\n public boolean isMore() {\n return mIsMore;\n }\n\n public void setIsMore(boolean isMore) ", "post_mask_code": "\n\n public int getId() {\n return mId;\n }\n\n public void setId(int id) {\n this.mId = id;\n }\n}\n"} {"task_id": "Java_1224", "language": "Java", "task_type": "single_line", "source_file": "java/github/zion223/FastWaiMai/latte-ec/src/main/java/com/zrp/latte/ec/main/index/spec/SpecZoneBean.java", "mask_start_position": 622, "mask_end_position": 624, "canonical_solution": "d;", "pre_mask_code": "package com.zrp.latte.ec.main.index.spec;\n\nimport com.chad.library.adapter.base.entity.SectionEntity;\n\npublic class SpecZoneBean extends SectionEntity {\n\n private boolean mIsMore = false;\n\n private int mId = -1;\n\n public SpecZoneBean(SpecZoneItemEntity specItemEntity) {\n super(specItemEntity);\n }\n\n public SpecZoneBean(boolean isHeader, String header) {\n super(isHeader, header);\n }\n\n public boolean isMore() {\n return mIsMore;\n }\n\n public void setIsMore(boolean isMore) {\n this.mIsMore = isMore;\n }\n\n public int getId() {\n return mI", "post_mask_code": "\n }\n\n public void setId(int id) {\n this.mId = id;\n }\n}\n"} {"task_id": "Java_1225", "language": "Java", "task_type": "method_signature", "source_file": "java/github/wmixvideo/nfe/src/main/java/com/fincatto/documentofiscal/nfe310/webservices/WSLoteEnvio.java", "mask_start_position": 2090, "mask_end_position": 2165, "canonical_solution": "NFLoteEnvioRetornoDados enviaLote(final NFLoteEnvio lote) throws Exception ", "pre_mask_code": "package com.fincatto.documentofiscal.nfe310.webservices;\n\nimport com.fincatto.documentofiscal.DFLog;\nimport com.fincatto.documentofiscal.DFModelo;\nimport com.fincatto.documentofiscal.nfe.NFeConfig;\nimport com.fincatto.documentofiscal.nfe310.classes.NFAutorizador31;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvio;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetorno;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetornoDados;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNota;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNotaInfoSuplementar;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraChave;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraQRCode;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeAutorizacaoLoteResult;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsg;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsgE;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeDadosMsg;\nimport com.fincatto.documentofiscal.utils.DFAssinaturaDigital;\nimport com.fincatto.documentofiscal.validadores.DFXMLValidador;\nimport org.apache.axiom.om.OMElement;\nimport org.apache.axiom.om.impl.builder.StAXOMBuilder;\nimport org.apache.commons.lang3.StringUtils;\nimport javax.xml.stream.XMLInputFactory;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.XMLStreamReader;\nimport java.io.StringReader;\nimport java.util.Iterator;\n\nclass WSLoteEnvio implements DFLog {\n\n private static final String NFE_ELEMENTO = \"NFe\";\n\n private final NFeConfig config;\n\n WSLoteEnvio(final NFeConfig config) {\n this.config = config;\n }\n\n NFLoteEnvioRetorno enviaLoteAssinado(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n return this.comunicaLote(loteAssinadoXml, modelo);\n }\n\n ", "post_mask_code": "{\n final NFLoteEnvio loteAssinado = this.getLoteAssinado(lote);\n // comunica o lote\n final NFLoteEnvioRetorno loteEnvioRetorno = this.comunicaLote(loteAssinado.toString(), loteAssinado.getNotas().get(0).getInfo().getIdentificacao().getModelo());\n return new NFLoteEnvioRetornoDados(loteEnvioRetorno, loteAssinado);\n }\n\n /**\n * Retorna o Lote assinado.\n */\n NFLoteEnvio getLoteAssinado(final NFLoteEnvio lote) throws Exception {\n // adiciona a chave e o dv antes de assinar\n for (final NFNota nota : lote.getNotas()) {\n final NFGeraChave geraChave = new NFGeraChave(nota);\n nota.getInfo().getIdentificacao().setCodigoRandomico(StringUtils.defaultIfBlank(nota.getInfo().getIdentificacao().getCodigoRandomico(), geraChave.geraCodigoRandomico()));\n nota.getInfo().getIdentificacao().setDigitoVerificador(geraChave.getDV());\n nota.getInfo().setIdentificador(geraChave.getChaveAcesso());\n }\n // assina o lote\n final String documentoAssinado = new DFAssinaturaDigital(this.config).assinarDocumento(lote.toString());\n final NFLoteEnvio loteAssinado = this.config.getPersister().read(NFLoteEnvio.class, documentoAssinado);\n // verifica se nao tem NFCe junto com NFe no lote e gera qrcode (apos assinar mesmo, eh assim)\n int qtdNF = 0, qtdNFC = 0;\n for (final NFNota nota : loteAssinado.getNotas()) {\n switch(nota.getInfo().getIdentificacao().getModelo()) {\n case NFE:\n qtdNF++;\n break;\n case NFCE:\n final NFGeraQRCode geraQRCode = new NFGeraQRCode(nota, this.config);\n nota.setInfoSuplementar(new NFNotaInfoSuplementar());\n nota.getInfoSuplementar().setQrCode(geraQRCode.getQRCode());\n qtdNFC++;\n break;\n default:\n throw new IllegalArgumentException(String.format(\"Modelo de nota desconhecida: %s\", nota.getInfo().getIdentificacao().getModelo()));\n }\n }\n // verifica se todas as notas do lote sao do mesmo modelo\n if ((qtdNF > 0) && (qtdNFC > 0)) {\n throw new IllegalArgumentException(\"Lote contendo notas de modelos diferentes!\");\n }\n return loteAssinado;\n }\n\n private NFLoteEnvioRetorno comunicaLote(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n // valida o lote assinado, para verificar se o xsd foi satisfeito, antes de comunicar com a sefaz\n DFXMLValidador.validaLote(loteAssinadoXml);\n // envia o lote para a sefaz\n final OMElement omElement = this.nfeToOMElement(loteAssinadoXml);\n final NfeDadosMsg dados = new NfeDadosMsg();\n dados.setExtraElement(omElement);\n final NfeCabecMsgE cabecalhoSOAP = this.getCabecalhoSOAP();\n this.getLogger().debug(omElement.toString());\n // define o tipo de emissao\n final NFAutorizador31 autorizador = NFAutorizador31.valueOfTipoEmissao(this.config.getTipoEmissao(), this.config.getCUF());\n final String endpoint = DFModelo.NFE.equals(modelo) ? autorizador.getNfeAutorizacao(this.config.getAmbiente()) : autorizador.getNfceAutorizacao(this.config.getAmbiente());\n if (endpoint == null) {\n throw new IllegalArgumentException(\"Nao foi possivel encontrar URL para Autorizacao \" + modelo.name() + \", autorizador \" + autorizador.name());\n }\n final NfeAutorizacaoLoteResult autorizacaoLoteResult = new NfeAutorizacaoStub(endpoint, config).nfeAutorizacaoLote(dados, cabecalhoSOAP);\n final NFLoteEnvioRetorno loteEnvioRetorno = this.config.getPersister().read(NFLoteEnvioRetorno.class, autorizacaoLoteResult.getExtraElement().toString());\n this.getLogger().debug(loteEnvioRetorno.toString());\n return loteEnvioRetorno;\n }\n\n private NfeCabecMsgE getCabecalhoSOAP() {\n final NfeCabecMsg cabecalho = new NfeCabecMsg();\n cabecalho.setCUF(this.config.getCUF().getCodigoIbge());\n cabecalho.setVersaoDados(this.config.getVersao());\n final NfeCabecMsgE cabecalhoSOAP = new NfeCabecMsgE();\n cabecalhoSOAP.setNfeCabecMsg(cabecalho);\n return cabecalhoSOAP;\n }\n\n private OMElement nfeToOMElement(final String documento) throws XMLStreamException {\n final XMLInputFactory factory = XMLInputFactory.newInstance();\n factory.setProperty(XMLInputFactory.IS_COALESCING, false);\n final XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(documento));\n final StAXOMBuilder builder = new StAXOMBuilder(reader);\n final OMElement ome = builder.getDocumentElement();\n final Iterator children = ome.getChildrenWithLocalName(WSLoteEnvio.NFE_ELEMENTO);\n while (children.hasNext()) {\n final OMElement omElement = (OMElement) children.next();\n if ((omElement != null) && (WSLoteEnvio.NFE_ELEMENTO.equals(omElement.getLocalName()))) {\n omElement.addAttribute(\"xmlns\", NFeConfig.NAMESPACE, null);\n }\n }\n return ome;\n }\n}\n"} {"task_id": "Java_1226", "language": "Java", "task_type": "method_body", "source_file": "java/github/wmixvideo/nfe/src/main/java/com/fincatto/documentofiscal/nfe310/webservices/WSLoteEnvio.java", "mask_start_position": 2165, "mask_end_position": 2513, "canonical_solution": "{\n final NFLoteEnvio loteAssinado = this.getLoteAssinado(lote);\n // comunica o lote\n final NFLoteEnvioRetorno loteEnvioRetorno = this.comunicaLote(loteAssinado.toString(), loteAssinado.getNotas().get(0).getInfo().getIdentificacao().getModelo());\n return new NFLoteEnvioRetornoDados(loteEnvioRetorno, loteAssinado);\n }", "pre_mask_code": "package com.fincatto.documentofiscal.nfe310.webservices;\n\nimport com.fincatto.documentofiscal.DFLog;\nimport com.fincatto.documentofiscal.DFModelo;\nimport com.fincatto.documentofiscal.nfe.NFeConfig;\nimport com.fincatto.documentofiscal.nfe310.classes.NFAutorizador31;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvio;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetorno;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetornoDados;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNota;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNotaInfoSuplementar;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraChave;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraQRCode;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeAutorizacaoLoteResult;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsg;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsgE;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeDadosMsg;\nimport com.fincatto.documentofiscal.utils.DFAssinaturaDigital;\nimport com.fincatto.documentofiscal.validadores.DFXMLValidador;\nimport org.apache.axiom.om.OMElement;\nimport org.apache.axiom.om.impl.builder.StAXOMBuilder;\nimport org.apache.commons.lang3.StringUtils;\nimport javax.xml.stream.XMLInputFactory;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.XMLStreamReader;\nimport java.io.StringReader;\nimport java.util.Iterator;\n\nclass WSLoteEnvio implements DFLog {\n\n private static final String NFE_ELEMENTO = \"NFe\";\n\n private final NFeConfig config;\n\n WSLoteEnvio(final NFeConfig config) {\n this.config = config;\n }\n\n NFLoteEnvioRetorno enviaLoteAssinado(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n return this.comunicaLote(loteAssinadoXml, modelo);\n }\n\n NFLoteEnvioRetornoDados enviaLote(final NFLoteEnvio lote) throws Exception ", "post_mask_code": "\n\n /**\n * Retorna o Lote assinado.\n */\n NFLoteEnvio getLoteAssinado(final NFLoteEnvio lote) throws Exception {\n // adiciona a chave e o dv antes de assinar\n for (final NFNota nota : lote.getNotas()) {\n final NFGeraChave geraChave = new NFGeraChave(nota);\n nota.getInfo().getIdentificacao().setCodigoRandomico(StringUtils.defaultIfBlank(nota.getInfo().getIdentificacao().getCodigoRandomico(), geraChave.geraCodigoRandomico()));\n nota.getInfo().getIdentificacao().setDigitoVerificador(geraChave.getDV());\n nota.getInfo().setIdentificador(geraChave.getChaveAcesso());\n }\n // assina o lote\n final String documentoAssinado = new DFAssinaturaDigital(this.config).assinarDocumento(lote.toString());\n final NFLoteEnvio loteAssinado = this.config.getPersister().read(NFLoteEnvio.class, documentoAssinado);\n // verifica se nao tem NFCe junto com NFe no lote e gera qrcode (apos assinar mesmo, eh assim)\n int qtdNF = 0, qtdNFC = 0;\n for (final NFNota nota : loteAssinado.getNotas()) {\n switch(nota.getInfo().getIdentificacao().getModelo()) {\n case NFE:\n qtdNF++;\n break;\n case NFCE:\n final NFGeraQRCode geraQRCode = new NFGeraQRCode(nota, this.config);\n nota.setInfoSuplementar(new NFNotaInfoSuplementar());\n nota.getInfoSuplementar().setQrCode(geraQRCode.getQRCode());\n qtdNFC++;\n break;\n default:\n throw new IllegalArgumentException(String.format(\"Modelo de nota desconhecida: %s\", nota.getInfo().getIdentificacao().getModelo()));\n }\n }\n // verifica se todas as notas do lote sao do mesmo modelo\n if ((qtdNF > 0) && (qtdNFC > 0)) {\n throw new IllegalArgumentException(\"Lote contendo notas de modelos diferentes!\");\n }\n return loteAssinado;\n }\n\n private NFLoteEnvioRetorno comunicaLote(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n // valida o lote assinado, para verificar se o xsd foi satisfeito, antes de comunicar com a sefaz\n DFXMLValidador.validaLote(loteAssinadoXml);\n // envia o lote para a sefaz\n final OMElement omElement = this.nfeToOMElement(loteAssinadoXml);\n final NfeDadosMsg dados = new NfeDadosMsg();\n dados.setExtraElement(omElement);\n final NfeCabecMsgE cabecalhoSOAP = this.getCabecalhoSOAP();\n this.getLogger().debug(omElement.toString());\n // define o tipo de emissao\n final NFAutorizador31 autorizador = NFAutorizador31.valueOfTipoEmissao(this.config.getTipoEmissao(), this.config.getCUF());\n final String endpoint = DFModelo.NFE.equals(modelo) ? autorizador.getNfeAutorizacao(this.config.getAmbiente()) : autorizador.getNfceAutorizacao(this.config.getAmbiente());\n if (endpoint == null) {\n throw new IllegalArgumentException(\"Nao foi possivel encontrar URL para Autorizacao \" + modelo.name() + \", autorizador \" + autorizador.name());\n }\n final NfeAutorizacaoLoteResult autorizacaoLoteResult = new NfeAutorizacaoStub(endpoint, config).nfeAutorizacaoLote(dados, cabecalhoSOAP);\n final NFLoteEnvioRetorno loteEnvioRetorno = this.config.getPersister().read(NFLoteEnvioRetorno.class, autorizacaoLoteResult.getExtraElement().toString());\n this.getLogger().debug(loteEnvioRetorno.toString());\n return loteEnvioRetorno;\n }\n\n private NfeCabecMsgE getCabecalhoSOAP() {\n final NfeCabecMsg cabecalho = new NfeCabecMsg();\n cabecalho.setCUF(this.config.getCUF().getCodigoIbge());\n cabecalho.setVersaoDados(this.config.getVersao());\n final NfeCabecMsgE cabecalhoSOAP = new NfeCabecMsgE();\n cabecalhoSOAP.setNfeCabecMsg(cabecalho);\n return cabecalhoSOAP;\n }\n\n private OMElement nfeToOMElement(final String documento) throws XMLStreamException {\n final XMLInputFactory factory = XMLInputFactory.newInstance();\n factory.setProperty(XMLInputFactory.IS_COALESCING, false);\n final XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(documento));\n final StAXOMBuilder builder = new StAXOMBuilder(reader);\n final OMElement ome = builder.getDocumentElement();\n final Iterator children = ome.getChildrenWithLocalName(WSLoteEnvio.NFE_ELEMENTO);\n while (children.hasNext()) {\n final OMElement omElement = (OMElement) children.next();\n if ((omElement != null) && (WSLoteEnvio.NFE_ELEMENTO.equals(omElement.getLocalName()))) {\n omElement.addAttribute(\"xmlns\", NFeConfig.NAMESPACE, null);\n }\n }\n return ome;\n }\n}\n"} {"task_id": "Java_1227", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/wmixvideo/nfe/src/main/java/com/fincatto/documentofiscal/nfe310/webservices/WSLoteEnvio.java", "mask_start_position": 4652, "mask_end_position": 4974, "canonical_solution": "\n // valida o lote assinado, para verificar se o xsd foi satisfeito, antes de comunicar com a sefaz\n DFXMLValidador.validaLote(loteAssinadoXml);\n // envia o lote para a sefaz\n final OMElement omElement = this.nfeToOMElement(loteAssinadoXml);\n final NfeDadosMsg dados = new NfeDadosMsg();", "pre_mask_code": "package com.fincatto.documentofiscal.nfe310.webservices;\n\nimport com.fincatto.documentofiscal.DFLog;\nimport com.fincatto.documentofiscal.DFModelo;\nimport com.fincatto.documentofiscal.nfe.NFeConfig;\nimport com.fincatto.documentofiscal.nfe310.classes.NFAutorizador31;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvio;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetorno;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetornoDados;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNota;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNotaInfoSuplementar;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraChave;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraQRCode;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeAutorizacaoLoteResult;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsg;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsgE;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeDadosMsg;\nimport com.fincatto.documentofiscal.utils.DFAssinaturaDigital;\nimport com.fincatto.documentofiscal.validadores.DFXMLValidador;\nimport org.apache.axiom.om.OMElement;\nimport org.apache.axiom.om.impl.builder.StAXOMBuilder;\nimport org.apache.commons.lang3.StringUtils;\nimport javax.xml.stream.XMLInputFactory;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.XMLStreamReader;\nimport java.io.StringReader;\nimport java.util.Iterator;\n\nclass WSLoteEnvio implements DFLog {\n\n private static final String NFE_ELEMENTO = \"NFe\";\n\n private final NFeConfig config;\n\n WSLoteEnvio(final NFeConfig config) {\n this.config = config;\n }\n\n NFLoteEnvioRetorno enviaLoteAssinado(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n return this.comunicaLote(loteAssinadoXml, modelo);\n }\n\n NFLoteEnvioRetornoDados enviaLote(final NFLoteEnvio lote) throws Exception {\n final NFLoteEnvio loteAssinado = this.getLoteAssinado(lote);\n // comunica o lote\n final NFLoteEnvioRetorno loteEnvioRetorno = this.comunicaLote(loteAssinado.toString(), loteAssinado.getNotas().get(0).getInfo().getIdentificacao().getModelo());\n return new NFLoteEnvioRetornoDados(loteEnvioRetorno, loteAssinado);\n }\n\n /**\n * Retorna o Lote assinado.\n */\n NFLoteEnvio getLoteAssinado(final NFLoteEnvio lote) throws Exception {\n // adiciona a chave e o dv antes de assinar\n for (final NFNota nota : lote.getNotas()) {\n final NFGeraChave geraChave = new NFGeraChave(nota);\n nota.getInfo().getIdentificacao().setCodigoRandomico(StringUtils.defaultIfBlank(nota.getInfo().getIdentificacao().getCodigoRandomico(), geraChave.geraCodigoRandomico()));\n nota.getInfo().getIdentificacao().setDigitoVerificador(geraChave.getDV());\n nota.getInfo().setIdentificador(geraChave.getChaveAcesso());\n }\n // assina o lote\n final String documentoAssinado = new DFAssinaturaDigital(this.config).assinarDocumento(lote.toString());\n final NFLoteEnvio loteAssinado = this.config.getPersister().read(NFLoteEnvio.class, documentoAssinado);\n // verifica se nao tem NFCe junto com NFe no lote e gera qrcode (apos assinar mesmo, eh assim)\n int qtdNF = 0, qtdNFC = 0;\n for (final NFNota nota : loteAssinado.getNotas()) {\n switch(nota.getInfo().getIdentificacao().getModelo()) {\n case NFE:\n qtdNF++;\n break;\n case NFCE:\n final NFGeraQRCode geraQRCode = new NFGeraQRCode(nota, this.config);\n nota.setInfoSuplementar(new NFNotaInfoSuplementar());\n nota.getInfoSuplementar().setQrCode(geraQRCode.getQRCode());\n qtdNFC++;\n break;\n default:\n throw new IllegalArgumentException(String.format(\"Modelo de nota desconhecida: %s\", nota.getInfo().getIdentificacao().getModelo()));\n }\n }\n // verifica se todas as notas do lote sao do mesmo modelo\n if ((qtdNF > 0) && (qtdNFC > 0)) {\n throw new IllegalArgumentException(\"Lote contendo notas de modelos diferentes!\");\n }\n return loteAssinado;\n }\n\n private NFLoteEnvioRetorno comunicaLote(final String loteAssinadoXml, final DFModelo modelo) throws Exception {", "post_mask_code": "\n dados.setExtraElement(omElement);\n final NfeCabecMsgE cabecalhoSOAP = this.getCabecalhoSOAP();\n this.getLogger().debug(omElement.toString());\n // define o tipo de emissao\n final NFAutorizador31 autorizador = NFAutorizador31.valueOfTipoEmissao(this.config.getTipoEmissao(), this.config.getCUF());\n final String endpoint = DFModelo.NFE.equals(modelo) ? autorizador.getNfeAutorizacao(this.config.getAmbiente()) : autorizador.getNfceAutorizacao(this.config.getAmbiente());\n if (endpoint == null) {\n throw new IllegalArgumentException(\"Nao foi possivel encontrar URL para Autorizacao \" + modelo.name() + \", autorizador \" + autorizador.name());\n }\n final NfeAutorizacaoLoteResult autorizacaoLoteResult = new NfeAutorizacaoStub(endpoint, config).nfeAutorizacaoLote(dados, cabecalhoSOAP);\n final NFLoteEnvioRetorno loteEnvioRetorno = this.config.getPersister().read(NFLoteEnvioRetorno.class, autorizacaoLoteResult.getExtraElement().toString());\n this.getLogger().debug(loteEnvioRetorno.toString());\n return loteEnvioRetorno;\n }\n\n private NfeCabecMsgE getCabecalhoSOAP() {\n final NfeCabecMsg cabecalho = new NfeCabecMsg();\n cabecalho.setCUF(this.config.getCUF().getCodigoIbge());\n cabecalho.setVersaoDados(this.config.getVersao());\n final NfeCabecMsgE cabecalhoSOAP = new NfeCabecMsgE();\n cabecalhoSOAP.setNfeCabecMsg(cabecalho);\n return cabecalhoSOAP;\n }\n\n private OMElement nfeToOMElement(final String documento) throws XMLStreamException {\n final XMLInputFactory factory = XMLInputFactory.newInstance();\n factory.setProperty(XMLInputFactory.IS_COALESCING, false);\n final XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(documento));\n final StAXOMBuilder builder = new StAXOMBuilder(reader);\n final OMElement ome = builder.getDocumentElement();\n final Iterator children = ome.getChildrenWithLocalName(WSLoteEnvio.NFE_ELEMENTO);\n while (children.hasNext()) {\n final OMElement omElement = (OMElement) children.next();\n if ((omElement != null) && (WSLoteEnvio.NFE_ELEMENTO.equals(omElement.getLocalName()))) {\n omElement.addAttribute(\"xmlns\", NFeConfig.NAMESPACE, null);\n }\n }\n return ome;\n }\n}\n"} {"task_id": "Java_1228", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/wmixvideo/nfe/src/main/java/com/fincatto/documentofiscal/nfe310/webservices/WSLoteEnvio.java", "mask_start_position": 4983, "mask_end_position": 5486, "canonical_solution": "dados.setExtraElement(omElement);\n final NfeCabecMsgE cabecalhoSOAP = this.getCabecalhoSOAP();\n this.getLogger().debug(omElement.toString());\n // define o tipo de emissao\n final NFAutorizador31 autorizador = NFAutorizador31.valueOfTipoEmissao(this.config.getTipoEmissao(), this.config.getCUF());\n final String endpoint = DFModelo.NFE.equals(modelo) ? autorizador.getNfeAutorizacao(this.config.getAmbiente()) : autorizador.getNfceAutorizacao(this.config.getAmbiente());", "pre_mask_code": "package com.fincatto.documentofiscal.nfe310.webservices;\n\nimport com.fincatto.documentofiscal.DFLog;\nimport com.fincatto.documentofiscal.DFModelo;\nimport com.fincatto.documentofiscal.nfe.NFeConfig;\nimport com.fincatto.documentofiscal.nfe310.classes.NFAutorizador31;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvio;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetorno;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetornoDados;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNota;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNotaInfoSuplementar;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraChave;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraQRCode;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeAutorizacaoLoteResult;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsg;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsgE;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeDadosMsg;\nimport com.fincatto.documentofiscal.utils.DFAssinaturaDigital;\nimport com.fincatto.documentofiscal.validadores.DFXMLValidador;\nimport org.apache.axiom.om.OMElement;\nimport org.apache.axiom.om.impl.builder.StAXOMBuilder;\nimport org.apache.commons.lang3.StringUtils;\nimport javax.xml.stream.XMLInputFactory;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.XMLStreamReader;\nimport java.io.StringReader;\nimport java.util.Iterator;\n\nclass WSLoteEnvio implements DFLog {\n\n private static final String NFE_ELEMENTO = \"NFe\";\n\n private final NFeConfig config;\n\n WSLoteEnvio(final NFeConfig config) {\n this.config = config;\n }\n\n NFLoteEnvioRetorno enviaLoteAssinado(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n return this.comunicaLote(loteAssinadoXml, modelo);\n }\n\n NFLoteEnvioRetornoDados enviaLote(final NFLoteEnvio lote) throws Exception {\n final NFLoteEnvio loteAssinado = this.getLoteAssinado(lote);\n // comunica o lote\n final NFLoteEnvioRetorno loteEnvioRetorno = this.comunicaLote(loteAssinado.toString(), loteAssinado.getNotas().get(0).getInfo().getIdentificacao().getModelo());\n return new NFLoteEnvioRetornoDados(loteEnvioRetorno, loteAssinado);\n }\n\n /**\n * Retorna o Lote assinado.\n */\n NFLoteEnvio getLoteAssinado(final NFLoteEnvio lote) throws Exception {\n // adiciona a chave e o dv antes de assinar\n for (final NFNota nota : lote.getNotas()) {\n final NFGeraChave geraChave = new NFGeraChave(nota);\n nota.getInfo().getIdentificacao().setCodigoRandomico(StringUtils.defaultIfBlank(nota.getInfo().getIdentificacao().getCodigoRandomico(), geraChave.geraCodigoRandomico()));\n nota.getInfo().getIdentificacao().setDigitoVerificador(geraChave.getDV());\n nota.getInfo().setIdentificador(geraChave.getChaveAcesso());\n }\n // assina o lote\n final String documentoAssinado = new DFAssinaturaDigital(this.config).assinarDocumento(lote.toString());\n final NFLoteEnvio loteAssinado = this.config.getPersister().read(NFLoteEnvio.class, documentoAssinado);\n // verifica se nao tem NFCe junto com NFe no lote e gera qrcode (apos assinar mesmo, eh assim)\n int qtdNF = 0, qtdNFC = 0;\n for (final NFNota nota : loteAssinado.getNotas()) {\n switch(nota.getInfo().getIdentificacao().getModelo()) {\n case NFE:\n qtdNF++;\n break;\n case NFCE:\n final NFGeraQRCode geraQRCode = new NFGeraQRCode(nota, this.config);\n nota.setInfoSuplementar(new NFNotaInfoSuplementar());\n nota.getInfoSuplementar().setQrCode(geraQRCode.getQRCode());\n qtdNFC++;\n break;\n default:\n throw new IllegalArgumentException(String.format(\"Modelo de nota desconhecida: %s\", nota.getInfo().getIdentificacao().getModelo()));\n }\n }\n // verifica se todas as notas do lote sao do mesmo modelo\n if ((qtdNF > 0) && (qtdNFC > 0)) {\n throw new IllegalArgumentException(\"Lote contendo notas de modelos diferentes!\");\n }\n return loteAssinado;\n }\n\n private NFLoteEnvioRetorno comunicaLote(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n // valida o lote assinado, para verificar se o xsd foi satisfeito, antes de comunicar com a sefaz\n DFXMLValidador.validaLote(loteAssinadoXml);\n // envia o lote para a sefaz\n final OMElement omElement = this.nfeToOMElement(loteAssinadoXml);\n final NfeDadosMsg dados = new NfeDadosMsg();\n ", "post_mask_code": "\n if (endpoint == null) {\n throw new IllegalArgumentException(\"Nao foi possivel encontrar URL para Autorizacao \" + modelo.name() + \", autorizador \" + autorizador.name());\n }\n final NfeAutorizacaoLoteResult autorizacaoLoteResult = new NfeAutorizacaoStub(endpoint, config).nfeAutorizacaoLote(dados, cabecalhoSOAP);\n final NFLoteEnvioRetorno loteEnvioRetorno = this.config.getPersister().read(NFLoteEnvioRetorno.class, autorizacaoLoteResult.getExtraElement().toString());\n this.getLogger().debug(loteEnvioRetorno.toString());\n return loteEnvioRetorno;\n }\n\n private NfeCabecMsgE getCabecalhoSOAP() {\n final NfeCabecMsg cabecalho = new NfeCabecMsg();\n cabecalho.setCUF(this.config.getCUF().getCodigoIbge());\n cabecalho.setVersaoDados(this.config.getVersao());\n final NfeCabecMsgE cabecalhoSOAP = new NfeCabecMsgE();\n cabecalhoSOAP.setNfeCabecMsg(cabecalho);\n return cabecalhoSOAP;\n }\n\n private OMElement nfeToOMElement(final String documento) throws XMLStreamException {\n final XMLInputFactory factory = XMLInputFactory.newInstance();\n factory.setProperty(XMLInputFactory.IS_COALESCING, false);\n final XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(documento));\n final StAXOMBuilder builder = new StAXOMBuilder(reader);\n final OMElement ome = builder.getDocumentElement();\n final Iterator children = ome.getChildrenWithLocalName(WSLoteEnvio.NFE_ELEMENTO);\n while (children.hasNext()) {\n final OMElement omElement = (OMElement) children.next();\n if ((omElement != null) && (WSLoteEnvio.NFE_ELEMENTO.equals(omElement.getLocalName()))) {\n omElement.addAttribute(\"xmlns\", NFeConfig.NAMESPACE, null);\n }\n }\n return ome;\n }\n}\n"} {"task_id": "Java_1229", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/wmixvideo/nfe/src/main/java/com/fincatto/documentofiscal/nfe310/webservices/WSLoteEnvio.java", "mask_start_position": 5495, "mask_end_position": 6093, "canonical_solution": "if (endpoint == null) {\n throw new IllegalArgumentException(\"Nao foi possivel encontrar URL para Autorizacao \" + modelo.name() + \", autorizador \" + autorizador.name());\n }\n final NfeAutorizacaoLoteResult autorizacaoLoteResult = new NfeAutorizacaoStub(endpoint, config).nfeAutorizacaoLote(dados, cabecalhoSOAP);\n final NFLoteEnvioRetorno loteEnvioRetorno = this.config.getPersister().read(NFLoteEnvioRetorno.class, autorizacaoLoteResult.getExtraElement().toString());\n this.getLogger().debug(loteEnvioRetorno.toString());\n return loteEnvioRetorno;\n }", "pre_mask_code": "package com.fincatto.documentofiscal.nfe310.webservices;\n\nimport com.fincatto.documentofiscal.DFLog;\nimport com.fincatto.documentofiscal.DFModelo;\nimport com.fincatto.documentofiscal.nfe.NFeConfig;\nimport com.fincatto.documentofiscal.nfe310.classes.NFAutorizador31;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvio;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetorno;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetornoDados;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNota;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNotaInfoSuplementar;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraChave;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraQRCode;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeAutorizacaoLoteResult;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsg;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsgE;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeDadosMsg;\nimport com.fincatto.documentofiscal.utils.DFAssinaturaDigital;\nimport com.fincatto.documentofiscal.validadores.DFXMLValidador;\nimport org.apache.axiom.om.OMElement;\nimport org.apache.axiom.om.impl.builder.StAXOMBuilder;\nimport org.apache.commons.lang3.StringUtils;\nimport javax.xml.stream.XMLInputFactory;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.XMLStreamReader;\nimport java.io.StringReader;\nimport java.util.Iterator;\n\nclass WSLoteEnvio implements DFLog {\n\n private static final String NFE_ELEMENTO = \"NFe\";\n\n private final NFeConfig config;\n\n WSLoteEnvio(final NFeConfig config) {\n this.config = config;\n }\n\n NFLoteEnvioRetorno enviaLoteAssinado(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n return this.comunicaLote(loteAssinadoXml, modelo);\n }\n\n NFLoteEnvioRetornoDados enviaLote(final NFLoteEnvio lote) throws Exception {\n final NFLoteEnvio loteAssinado = this.getLoteAssinado(lote);\n // comunica o lote\n final NFLoteEnvioRetorno loteEnvioRetorno = this.comunicaLote(loteAssinado.toString(), loteAssinado.getNotas().get(0).getInfo().getIdentificacao().getModelo());\n return new NFLoteEnvioRetornoDados(loteEnvioRetorno, loteAssinado);\n }\n\n /**\n * Retorna o Lote assinado.\n */\n NFLoteEnvio getLoteAssinado(final NFLoteEnvio lote) throws Exception {\n // adiciona a chave e o dv antes de assinar\n for (final NFNota nota : lote.getNotas()) {\n final NFGeraChave geraChave = new NFGeraChave(nota);\n nota.getInfo().getIdentificacao().setCodigoRandomico(StringUtils.defaultIfBlank(nota.getInfo().getIdentificacao().getCodigoRandomico(), geraChave.geraCodigoRandomico()));\n nota.getInfo().getIdentificacao().setDigitoVerificador(geraChave.getDV());\n nota.getInfo().setIdentificador(geraChave.getChaveAcesso());\n }\n // assina o lote\n final String documentoAssinado = new DFAssinaturaDigital(this.config).assinarDocumento(lote.toString());\n final NFLoteEnvio loteAssinado = this.config.getPersister().read(NFLoteEnvio.class, documentoAssinado);\n // verifica se nao tem NFCe junto com NFe no lote e gera qrcode (apos assinar mesmo, eh assim)\n int qtdNF = 0, qtdNFC = 0;\n for (final NFNota nota : loteAssinado.getNotas()) {\n switch(nota.getInfo().getIdentificacao().getModelo()) {\n case NFE:\n qtdNF++;\n break;\n case NFCE:\n final NFGeraQRCode geraQRCode = new NFGeraQRCode(nota, this.config);\n nota.setInfoSuplementar(new NFNotaInfoSuplementar());\n nota.getInfoSuplementar().setQrCode(geraQRCode.getQRCode());\n qtdNFC++;\n break;\n default:\n throw new IllegalArgumentException(String.format(\"Modelo de nota desconhecida: %s\", nota.getInfo().getIdentificacao().getModelo()));\n }\n }\n // verifica se todas as notas do lote sao do mesmo modelo\n if ((qtdNF > 0) && (qtdNFC > 0)) {\n throw new IllegalArgumentException(\"Lote contendo notas de modelos diferentes!\");\n }\n return loteAssinado;\n }\n\n private NFLoteEnvioRetorno comunicaLote(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n // valida o lote assinado, para verificar se o xsd foi satisfeito, antes de comunicar com a sefaz\n DFXMLValidador.validaLote(loteAssinadoXml);\n // envia o lote para a sefaz\n final OMElement omElement = this.nfeToOMElement(loteAssinadoXml);\n final NfeDadosMsg dados = new NfeDadosMsg();\n dados.setExtraElement(omElement);\n final NfeCabecMsgE cabecalhoSOAP = this.getCabecalhoSOAP();\n this.getLogger().debug(omElement.toString());\n // define o tipo de emissao\n final NFAutorizador31 autorizador = NFAutorizador31.valueOfTipoEmissao(this.config.getTipoEmissao(), this.config.getCUF());\n final String endpoint = DFModelo.NFE.equals(modelo) ? autorizador.getNfeAutorizacao(this.config.getAmbiente()) : autorizador.getNfceAutorizacao(this.config.getAmbiente());\n ", "post_mask_code": "\n\n private NfeCabecMsgE getCabecalhoSOAP() {\n final NfeCabecMsg cabecalho = new NfeCabecMsg();\n cabecalho.setCUF(this.config.getCUF().getCodigoIbge());\n cabecalho.setVersaoDados(this.config.getVersao());\n final NfeCabecMsgE cabecalhoSOAP = new NfeCabecMsgE();\n cabecalhoSOAP.setNfeCabecMsg(cabecalho);\n return cabecalhoSOAP;\n }\n\n private OMElement nfeToOMElement(final String documento) throws XMLStreamException {\n final XMLInputFactory factory = XMLInputFactory.newInstance();\n factory.setProperty(XMLInputFactory.IS_COALESCING, false);\n final XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(documento));\n final StAXOMBuilder builder = new StAXOMBuilder(reader);\n final OMElement ome = builder.getDocumentElement();\n final Iterator children = ome.getChildrenWithLocalName(WSLoteEnvio.NFE_ELEMENTO);\n while (children.hasNext()) {\n final OMElement omElement = (OMElement) children.next();\n if ((omElement != null) && (WSLoteEnvio.NFE_ELEMENTO.equals(omElement.getLocalName()))) {\n omElement.addAttribute(\"xmlns\", NFeConfig.NAMESPACE, null);\n }\n }\n return ome;\n }\n}\n"} {"task_id": "Java_1230", "language": "Java", "task_type": "single_line", "source_file": "java/github/wmixvideo/nfe/src/main/java/com/fincatto/documentofiscal/nfe310/webservices/WSLoteEnvio.java", "mask_start_position": 4915, "mask_end_position": 4921, "canonical_solution": "oXml);", "pre_mask_code": "package com.fincatto.documentofiscal.nfe310.webservices;\n\nimport com.fincatto.documentofiscal.DFLog;\nimport com.fincatto.documentofiscal.DFModelo;\nimport com.fincatto.documentofiscal.nfe.NFeConfig;\nimport com.fincatto.documentofiscal.nfe310.classes.NFAutorizador31;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvio;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetorno;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetornoDados;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNota;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNotaInfoSuplementar;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraChave;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraQRCode;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeAutorizacaoLoteResult;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsg;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsgE;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeDadosMsg;\nimport com.fincatto.documentofiscal.utils.DFAssinaturaDigital;\nimport com.fincatto.documentofiscal.validadores.DFXMLValidador;\nimport org.apache.axiom.om.OMElement;\nimport org.apache.axiom.om.impl.builder.StAXOMBuilder;\nimport org.apache.commons.lang3.StringUtils;\nimport javax.xml.stream.XMLInputFactory;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.XMLStreamReader;\nimport java.io.StringReader;\nimport java.util.Iterator;\n\nclass WSLoteEnvio implements DFLog {\n\n private static final String NFE_ELEMENTO = \"NFe\";\n\n private final NFeConfig config;\n\n WSLoteEnvio(final NFeConfig config) {\n this.config = config;\n }\n\n NFLoteEnvioRetorno enviaLoteAssinado(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n return this.comunicaLote(loteAssinadoXml, modelo);\n }\n\n NFLoteEnvioRetornoDados enviaLote(final NFLoteEnvio lote) throws Exception {\n final NFLoteEnvio loteAssinado = this.getLoteAssinado(lote);\n // comunica o lote\n final NFLoteEnvioRetorno loteEnvioRetorno = this.comunicaLote(loteAssinado.toString(), loteAssinado.getNotas().get(0).getInfo().getIdentificacao().getModelo());\n return new NFLoteEnvioRetornoDados(loteEnvioRetorno, loteAssinado);\n }\n\n /**\n * Retorna o Lote assinado.\n */\n NFLoteEnvio getLoteAssinado(final NFLoteEnvio lote) throws Exception {\n // adiciona a chave e o dv antes de assinar\n for (final NFNota nota : lote.getNotas()) {\n final NFGeraChave geraChave = new NFGeraChave(nota);\n nota.getInfo().getIdentificacao().setCodigoRandomico(StringUtils.defaultIfBlank(nota.getInfo().getIdentificacao().getCodigoRandomico(), geraChave.geraCodigoRandomico()));\n nota.getInfo().getIdentificacao().setDigitoVerificador(geraChave.getDV());\n nota.getInfo().setIdentificador(geraChave.getChaveAcesso());\n }\n // assina o lote\n final String documentoAssinado = new DFAssinaturaDigital(this.config).assinarDocumento(lote.toString());\n final NFLoteEnvio loteAssinado = this.config.getPersister().read(NFLoteEnvio.class, documentoAssinado);\n // verifica se nao tem NFCe junto com NFe no lote e gera qrcode (apos assinar mesmo, eh assim)\n int qtdNF = 0, qtdNFC = 0;\n for (final NFNota nota : loteAssinado.getNotas()) {\n switch(nota.getInfo().getIdentificacao().getModelo()) {\n case NFE:\n qtdNF++;\n break;\n case NFCE:\n final NFGeraQRCode geraQRCode = new NFGeraQRCode(nota, this.config);\n nota.setInfoSuplementar(new NFNotaInfoSuplementar());\n nota.getInfoSuplementar().setQrCode(geraQRCode.getQRCode());\n qtdNFC++;\n break;\n default:\n throw new IllegalArgumentException(String.format(\"Modelo de nota desconhecida: %s\", nota.getInfo().getIdentificacao().getModelo()));\n }\n }\n // verifica se todas as notas do lote sao do mesmo modelo\n if ((qtdNF > 0) && (qtdNFC > 0)) {\n throw new IllegalArgumentException(\"Lote contendo notas de modelos diferentes!\");\n }\n return loteAssinado;\n }\n\n private NFLoteEnvioRetorno comunicaLote(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n // valida o lote assinado, para verificar se o xsd foi satisfeito, antes de comunicar com a sefaz\n DFXMLValidador.validaLote(loteAssinadoXml);\n // envia o lote para a sefaz\n final OMElement omElement = this.nfeToOMElement(loteAssinad", "post_mask_code": "\n final NfeDadosMsg dados = new NfeDadosMsg();\n dados.setExtraElement(omElement);\n final NfeCabecMsgE cabecalhoSOAP = this.getCabecalhoSOAP();\n this.getLogger().debug(omElement.toString());\n // define o tipo de emissao\n final NFAutorizador31 autorizador = NFAutorizador31.valueOfTipoEmissao(this.config.getTipoEmissao(), this.config.getCUF());\n final String endpoint = DFModelo.NFE.equals(modelo) ? autorizador.getNfeAutorizacao(this.config.getAmbiente()) : autorizador.getNfceAutorizacao(this.config.getAmbiente());\n if (endpoint == null) {\n throw new IllegalArgumentException(\"Nao foi possivel encontrar URL para Autorizacao \" + modelo.name() + \", autorizador \" + autorizador.name());\n }\n final NfeAutorizacaoLoteResult autorizacaoLoteResult = new NfeAutorizacaoStub(endpoint, config).nfeAutorizacaoLote(dados, cabecalhoSOAP);\n final NFLoteEnvioRetorno loteEnvioRetorno = this.config.getPersister().read(NFLoteEnvioRetorno.class, autorizacaoLoteResult.getExtraElement().toString());\n this.getLogger().debug(loteEnvioRetorno.toString());\n return loteEnvioRetorno;\n }\n\n private NfeCabecMsgE getCabecalhoSOAP() {\n final NfeCabecMsg cabecalho = new NfeCabecMsg();\n cabecalho.setCUF(this.config.getCUF().getCodigoIbge());\n cabecalho.setVersaoDados(this.config.getVersao());\n final NfeCabecMsgE cabecalhoSOAP = new NfeCabecMsgE();\n cabecalhoSOAP.setNfeCabecMsg(cabecalho);\n return cabecalhoSOAP;\n }\n\n private OMElement nfeToOMElement(final String documento) throws XMLStreamException {\n final XMLInputFactory factory = XMLInputFactory.newInstance();\n factory.setProperty(XMLInputFactory.IS_COALESCING, false);\n final XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(documento));\n final StAXOMBuilder builder = new StAXOMBuilder(reader);\n final OMElement ome = builder.getDocumentElement();\n final Iterator children = ome.getChildrenWithLocalName(WSLoteEnvio.NFE_ELEMENTO);\n while (children.hasNext()) {\n final OMElement omElement = (OMElement) children.next();\n if ((omElement != null) && (WSLoteEnvio.NFE_ELEMENTO.equals(omElement.getLocalName()))) {\n omElement.addAttribute(\"xmlns\", NFeConfig.NAMESPACE, null);\n }\n }\n return ome;\n }\n}\n"} {"task_id": "Java_1231", "language": "Java", "task_type": "if_statement", "source_file": "java/github/wmixvideo/nfe/src/main/java/com/fincatto/documentofiscal/nfe310/webservices/WSLoteEnvio.java", "mask_start_position": 4362, "mask_end_position": 4500, "canonical_solution": "if ((qtdNF > 0) && (qtdNFC > 0)) {\n throw new IllegalArgumentException(\"Lote contendo notas de modelos diferentes!\");\n }", "pre_mask_code": "package com.fincatto.documentofiscal.nfe310.webservices;\n\nimport com.fincatto.documentofiscal.DFLog;\nimport com.fincatto.documentofiscal.DFModelo;\nimport com.fincatto.documentofiscal.nfe.NFeConfig;\nimport com.fincatto.documentofiscal.nfe310.classes.NFAutorizador31;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvio;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetorno;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetornoDados;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNota;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNotaInfoSuplementar;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraChave;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraQRCode;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeAutorizacaoLoteResult;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsg;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsgE;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeDadosMsg;\nimport com.fincatto.documentofiscal.utils.DFAssinaturaDigital;\nimport com.fincatto.documentofiscal.validadores.DFXMLValidador;\nimport org.apache.axiom.om.OMElement;\nimport org.apache.axiom.om.impl.builder.StAXOMBuilder;\nimport org.apache.commons.lang3.StringUtils;\nimport javax.xml.stream.XMLInputFactory;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.XMLStreamReader;\nimport java.io.StringReader;\nimport java.util.Iterator;\n\nclass WSLoteEnvio implements DFLog {\n\n private static final String NFE_ELEMENTO = \"NFe\";\n\n private final NFeConfig config;\n\n WSLoteEnvio(final NFeConfig config) {\n this.config = config;\n }\n\n NFLoteEnvioRetorno enviaLoteAssinado(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n return this.comunicaLote(loteAssinadoXml, modelo);\n }\n\n NFLoteEnvioRetornoDados enviaLote(final NFLoteEnvio lote) throws Exception {\n final NFLoteEnvio loteAssinado = this.getLoteAssinado(lote);\n // comunica o lote\n final NFLoteEnvioRetorno loteEnvioRetorno = this.comunicaLote(loteAssinado.toString(), loteAssinado.getNotas().get(0).getInfo().getIdentificacao().getModelo());\n return new NFLoteEnvioRetornoDados(loteEnvioRetorno, loteAssinado);\n }\n\n /**\n * Retorna o Lote assinado.\n */\n NFLoteEnvio getLoteAssinado(final NFLoteEnvio lote) throws Exception {\n // adiciona a chave e o dv antes de assinar\n for (final NFNota nota : lote.getNotas()) {\n final NFGeraChave geraChave = new NFGeraChave(nota);\n nota.getInfo().getIdentificacao().setCodigoRandomico(StringUtils.defaultIfBlank(nota.getInfo().getIdentificacao().getCodigoRandomico(), geraChave.geraCodigoRandomico()));\n nota.getInfo().getIdentificacao().setDigitoVerificador(geraChave.getDV());\n nota.getInfo().setIdentificador(geraChave.getChaveAcesso());\n }\n // assina o lote\n final String documentoAssinado = new DFAssinaturaDigital(this.config).assinarDocumento(lote.toString());\n final NFLoteEnvio loteAssinado = this.config.getPersister().read(NFLoteEnvio.class, documentoAssinado);\n // verifica se nao tem NFCe junto com NFe no lote e gera qrcode (apos assinar mesmo, eh assim)\n int qtdNF = 0, qtdNFC = 0;\n for (final NFNota nota : loteAssinado.getNotas()) {\n switch(nota.getInfo().getIdentificacao().getModelo()) {\n case NFE:\n qtdNF++;\n break;\n case NFCE:\n final NFGeraQRCode geraQRCode = new NFGeraQRCode(nota, this.config);\n nota.setInfoSuplementar(new NFNotaInfoSuplementar());\n nota.getInfoSuplementar().setQrCode(geraQRCode.getQRCode());\n qtdNFC++;\n break;\n default:\n throw new IllegalArgumentException(String.format(\"Modelo de nota desconhecida: %s\", nota.getInfo().getIdentificacao().getModelo()));\n }\n }\n // verifica se todas as notas do lote sao do mesmo modelo\n ", "post_mask_code": "\n return loteAssinado;\n }\n\n private NFLoteEnvioRetorno comunicaLote(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n // valida o lote assinado, para verificar se o xsd foi satisfeito, antes de comunicar com a sefaz\n DFXMLValidador.validaLote(loteAssinadoXml);\n // envia o lote para a sefaz\n final OMElement omElement = this.nfeToOMElement(loteAssinadoXml);\n final NfeDadosMsg dados = new NfeDadosMsg();\n dados.setExtraElement(omElement);\n final NfeCabecMsgE cabecalhoSOAP = this.getCabecalhoSOAP();\n this.getLogger().debug(omElement.toString());\n // define o tipo de emissao\n final NFAutorizador31 autorizador = NFAutorizador31.valueOfTipoEmissao(this.config.getTipoEmissao(), this.config.getCUF());\n final String endpoint = DFModelo.NFE.equals(modelo) ? autorizador.getNfeAutorizacao(this.config.getAmbiente()) : autorizador.getNfceAutorizacao(this.config.getAmbiente());\n if (endpoint == null) {\n throw new IllegalArgumentException(\"Nao foi possivel encontrar URL para Autorizacao \" + modelo.name() + \", autorizador \" + autorizador.name());\n }\n final NfeAutorizacaoLoteResult autorizacaoLoteResult = new NfeAutorizacaoStub(endpoint, config).nfeAutorizacaoLote(dados, cabecalhoSOAP);\n final NFLoteEnvioRetorno loteEnvioRetorno = this.config.getPersister().read(NFLoteEnvioRetorno.class, autorizacaoLoteResult.getExtraElement().toString());\n this.getLogger().debug(loteEnvioRetorno.toString());\n return loteEnvioRetorno;\n }\n\n private NfeCabecMsgE getCabecalhoSOAP() {\n final NfeCabecMsg cabecalho = new NfeCabecMsg();\n cabecalho.setCUF(this.config.getCUF().getCodigoIbge());\n cabecalho.setVersaoDados(this.config.getVersao());\n final NfeCabecMsgE cabecalhoSOAP = new NfeCabecMsgE();\n cabecalhoSOAP.setNfeCabecMsg(cabecalho);\n return cabecalhoSOAP;\n }\n\n private OMElement nfeToOMElement(final String documento) throws XMLStreamException {\n final XMLInputFactory factory = XMLInputFactory.newInstance();\n factory.setProperty(XMLInputFactory.IS_COALESCING, false);\n final XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(documento));\n final StAXOMBuilder builder = new StAXOMBuilder(reader);\n final OMElement ome = builder.getDocumentElement();\n final Iterator children = ome.getChildrenWithLocalName(WSLoteEnvio.NFE_ELEMENTO);\n while (children.hasNext()) {\n final OMElement omElement = (OMElement) children.next();\n if ((omElement != null) && (WSLoteEnvio.NFE_ELEMENTO.equals(omElement.getLocalName()))) {\n omElement.addAttribute(\"xmlns\", NFeConfig.NAMESPACE, null);\n }\n }\n return ome;\n }\n}\n"} {"task_id": "Java_1232", "language": "Java", "task_type": "while_statement", "source_file": "java/github/wmixvideo/nfe/src/main/java/com/fincatto/documentofiscal/nfe310/webservices/WSLoteEnvio.java", "mask_start_position": 7022, "mask_end_position": 7321, "canonical_solution": "while (children.hasNext()) {\n final OMElement omElement = (OMElement) children.next();\n if ((omElement != null) && (WSLoteEnvio.NFE_ELEMENTO.equals(omElement.getLocalName()))) {\n omElement.addAttribute(\"xmlns\", NFeConfig.NAMESPACE, null);\n }\n }", "pre_mask_code": "package com.fincatto.documentofiscal.nfe310.webservices;\n\nimport com.fincatto.documentofiscal.DFLog;\nimport com.fincatto.documentofiscal.DFModelo;\nimport com.fincatto.documentofiscal.nfe.NFeConfig;\nimport com.fincatto.documentofiscal.nfe310.classes.NFAutorizador31;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvio;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetorno;\nimport com.fincatto.documentofiscal.nfe310.classes.lote.envio.NFLoteEnvioRetornoDados;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNota;\nimport com.fincatto.documentofiscal.nfe310.classes.nota.NFNotaInfoSuplementar;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraChave;\nimport com.fincatto.documentofiscal.nfe310.utils.NFGeraQRCode;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeAutorizacaoLoteResult;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsg;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeCabecMsgE;\nimport com.fincatto.documentofiscal.nfe310.webservices.gerado.NfeAutorizacaoStub.NfeDadosMsg;\nimport com.fincatto.documentofiscal.utils.DFAssinaturaDigital;\nimport com.fincatto.documentofiscal.validadores.DFXMLValidador;\nimport org.apache.axiom.om.OMElement;\nimport org.apache.axiom.om.impl.builder.StAXOMBuilder;\nimport org.apache.commons.lang3.StringUtils;\nimport javax.xml.stream.XMLInputFactory;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.XMLStreamReader;\nimport java.io.StringReader;\nimport java.util.Iterator;\n\nclass WSLoteEnvio implements DFLog {\n\n private static final String NFE_ELEMENTO = \"NFe\";\n\n private final NFeConfig config;\n\n WSLoteEnvio(final NFeConfig config) {\n this.config = config;\n }\n\n NFLoteEnvioRetorno enviaLoteAssinado(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n return this.comunicaLote(loteAssinadoXml, modelo);\n }\n\n NFLoteEnvioRetornoDados enviaLote(final NFLoteEnvio lote) throws Exception {\n final NFLoteEnvio loteAssinado = this.getLoteAssinado(lote);\n // comunica o lote\n final NFLoteEnvioRetorno loteEnvioRetorno = this.comunicaLote(loteAssinado.toString(), loteAssinado.getNotas().get(0).getInfo().getIdentificacao().getModelo());\n return new NFLoteEnvioRetornoDados(loteEnvioRetorno, loteAssinado);\n }\n\n /**\n * Retorna o Lote assinado.\n */\n NFLoteEnvio getLoteAssinado(final NFLoteEnvio lote) throws Exception {\n // adiciona a chave e o dv antes de assinar\n for (final NFNota nota : lote.getNotas()) {\n final NFGeraChave geraChave = new NFGeraChave(nota);\n nota.getInfo().getIdentificacao().setCodigoRandomico(StringUtils.defaultIfBlank(nota.getInfo().getIdentificacao().getCodigoRandomico(), geraChave.geraCodigoRandomico()));\n nota.getInfo().getIdentificacao().setDigitoVerificador(geraChave.getDV());\n nota.getInfo().setIdentificador(geraChave.getChaveAcesso());\n }\n // assina o lote\n final String documentoAssinado = new DFAssinaturaDigital(this.config).assinarDocumento(lote.toString());\n final NFLoteEnvio loteAssinado = this.config.getPersister().read(NFLoteEnvio.class, documentoAssinado);\n // verifica se nao tem NFCe junto com NFe no lote e gera qrcode (apos assinar mesmo, eh assim)\n int qtdNF = 0, qtdNFC = 0;\n for (final NFNota nota : loteAssinado.getNotas()) {\n switch(nota.getInfo().getIdentificacao().getModelo()) {\n case NFE:\n qtdNF++;\n break;\n case NFCE:\n final NFGeraQRCode geraQRCode = new NFGeraQRCode(nota, this.config);\n nota.setInfoSuplementar(new NFNotaInfoSuplementar());\n nota.getInfoSuplementar().setQrCode(geraQRCode.getQRCode());\n qtdNFC++;\n break;\n default:\n throw new IllegalArgumentException(String.format(\"Modelo de nota desconhecida: %s\", nota.getInfo().getIdentificacao().getModelo()));\n }\n }\n // verifica se todas as notas do lote sao do mesmo modelo\n if ((qtdNF > 0) && (qtdNFC > 0)) {\n throw new IllegalArgumentException(\"Lote contendo notas de modelos diferentes!\");\n }\n return loteAssinado;\n }\n\n private NFLoteEnvioRetorno comunicaLote(final String loteAssinadoXml, final DFModelo modelo) throws Exception {\n // valida o lote assinado, para verificar se o xsd foi satisfeito, antes de comunicar com a sefaz\n DFXMLValidador.validaLote(loteAssinadoXml);\n // envia o lote para a sefaz\n final OMElement omElement = this.nfeToOMElement(loteAssinadoXml);\n final NfeDadosMsg dados = new NfeDadosMsg();\n dados.setExtraElement(omElement);\n final NfeCabecMsgE cabecalhoSOAP = this.getCabecalhoSOAP();\n this.getLogger().debug(omElement.toString());\n // define o tipo de emissao\n final NFAutorizador31 autorizador = NFAutorizador31.valueOfTipoEmissao(this.config.getTipoEmissao(), this.config.getCUF());\n final String endpoint = DFModelo.NFE.equals(modelo) ? autorizador.getNfeAutorizacao(this.config.getAmbiente()) : autorizador.getNfceAutorizacao(this.config.getAmbiente());\n if (endpoint == null) {\n throw new IllegalArgumentException(\"Nao foi possivel encontrar URL para Autorizacao \" + modelo.name() + \", autorizador \" + autorizador.name());\n }\n final NfeAutorizacaoLoteResult autorizacaoLoteResult = new NfeAutorizacaoStub(endpoint, config).nfeAutorizacaoLote(dados, cabecalhoSOAP);\n final NFLoteEnvioRetorno loteEnvioRetorno = this.config.getPersister().read(NFLoteEnvioRetorno.class, autorizacaoLoteResult.getExtraElement().toString());\n this.getLogger().debug(loteEnvioRetorno.toString());\n return loteEnvioRetorno;\n }\n\n private NfeCabecMsgE getCabecalhoSOAP() {\n final NfeCabecMsg cabecalho = new NfeCabecMsg();\n cabecalho.setCUF(this.config.getCUF().getCodigoIbge());\n cabecalho.setVersaoDados(this.config.getVersao());\n final NfeCabecMsgE cabecalhoSOAP = new NfeCabecMsgE();\n cabecalhoSOAP.setNfeCabecMsg(cabecalho);\n return cabecalhoSOAP;\n }\n\n private OMElement nfeToOMElement(final String documento) throws XMLStreamException {\n final XMLInputFactory factory = XMLInputFactory.newInstance();\n factory.setProperty(XMLInputFactory.IS_COALESCING, false);\n final XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(documento));\n final StAXOMBuilder builder = new StAXOMBuilder(reader);\n final OMElement ome = builder.getDocumentElement();\n final Iterator children = ome.getChildrenWithLocalName(WSLoteEnvio.NFE_ELEMENTO);\n ", "post_mask_code": "\n return ome;\n }\n}\n"} {"task_id": "Java_1233", "language": "Java", "task_type": "method_signature", "source_file": "java/github/gomint/gomint/gomint-api/src/main/java/io/gomint/inventory/item/ItemBeetroot.java", "mask_start_position": 359, "mask_end_position": 398, "canonical_solution": "static ItemBeetroot create(int amount) ", "pre_mask_code": "package io.gomint.inventory.item;\n\nimport io.gomint.GoMint;\n\n/**\n * @author geNAZt\n * @version 1.0\n * @stability 3\n */\npublic interface ItemBeetroot extends ItemFood {\n\n /**\n * Create a new item stack with given class and amount\n *\n * @param amount which is used for the creation\n * @return freshly generated item\n */\n ", "post_mask_code": "{\n return GoMint.instance().createItemStack(ItemBeetroot.class, amount);\n }\n}\n"} {"task_id": "Java_1234", "language": "Java", "task_type": "method_body", "source_file": "java/github/gomint/gomint/gomint-api/src/main/java/io/gomint/inventory/item/ItemBeetroot.java", "mask_start_position": 398, "mask_end_position": 483, "canonical_solution": "{\n return GoMint.instance().createItemStack(ItemBeetroot.class, amount);\n }", "pre_mask_code": "package io.gomint.inventory.item;\n\nimport io.gomint.GoMint;\n\n/**\n * @author geNAZt\n * @version 1.0\n * @stability 3\n */\npublic interface ItemBeetroot extends ItemFood {\n\n /**\n * Create a new item stack with given class and amount\n *\n * @param amount which is used for the creation\n * @return freshly generated item\n */\n static ItemBeetroot create(int amount) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1235", "language": "Java", "task_type": "single_line", "source_file": "java/github/gomint/gomint/gomint-api/src/main/java/io/gomint/inventory/item/ItemBeetroot.java", "mask_start_position": 416, "mask_end_position": 477, "canonical_solution": "oMint.instance().createItemStack(ItemBeetroot.class, amount);", "pre_mask_code": "package io.gomint.inventory.item;\n\nimport io.gomint.GoMint;\n\n/**\n * @author geNAZt\n * @version 1.0\n * @stability 3\n */\npublic interface ItemBeetroot extends ItemFood {\n\n /**\n * Create a new item stack with given class and amount\n *\n * @param amount which is used for the creation\n * @return freshly generated item\n */\n static ItemBeetroot create(int amount) {\n return G", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1236", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/gomint/gomint/gomint-api/src/main/java/io/gomint/inventory/item/ItemBeetroot.java", "mask_start_position": 359, "mask_end_position": 483, "canonical_solution": "static ItemBeetroot create(int amount) {\n return GoMint.instance().createItemStack(ItemBeetroot.class, amount);\n }", "pre_mask_code": "package io.gomint.inventory.item;\n\nimport io.gomint.GoMint;\n\n/**\n * @author geNAZt\n * @version 1.0\n * @stability 3\n */\npublic interface ItemBeetroot extends ItemFood {\n\n /**\n * Create a new item stack with given class and amount\n *\n * @param amount which is used for the creation\n * @return freshly generated item\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1237", "language": "Java", "task_type": "method_signature", "source_file": "java/github/linux-china/dubbo3/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dump.java", "mask_start_position": 1497, "mask_end_position": 1566, "canonical_solution": "public void services(Map context) throws IOException ", "pre_mask_code": "package com.alibaba.dubbo.governance.web.sysinfo.module.screen;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.http.HttpServletResponse;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport com.alibaba.dubbo.common.utils.StringUtils;\nimport com.alibaba.dubbo.governance.service.ConsumerService;\nimport com.alibaba.dubbo.governance.service.ProviderService;\nimport com.alibaba.dubbo.governance.web.common.module.screen.Restful;\nimport com.alibaba.dubbo.registry.common.domain.Consumer;\nimport com.alibaba.dubbo.registry.common.domain.Provider;\n\n/**\n * @author tony.chenl\n */\npublic class Dump extends Restful {\n\n @Autowired\n ProviderService providerDAO;\n\n @Autowired\n ConsumerService consumerDAO;\n\n @Autowired\n HttpServletResponse response;\n\n public void noProviders(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = getNoProviders();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services don't have provider\");\n for (String noProvider : sortedService) {\n writer.println(noProvider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n ", "post_mask_code": "{\n PrintWriter writer = response.getWriter();\n List sortedService = providerDAO.findServices();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services\");\n for (String service : sortedService) {\n writer.println(service + (providerDAO.findByService(service).size()));\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void providers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List sortedProviders = new ArrayList();\n for (Provider provider : providers) {\n sortedProviders.add(provider.getUrl() + \" \" + provider.getService());\n }\n Collections.sort(sortedProviders);\n writer.println(sortedProviders.size() + \" provider instance\");\n for (String provider : sortedProviders) {\n writer.println(provider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void consumers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List consumers = consumerDAO.findAll();\n List sortedConsumerss = new ArrayList();\n for (Consumer consumer : consumers) {\n sortedConsumerss.add(consumer.getAddress() + \" \" + consumer.getService());\n }\n Collections.sort(sortedConsumerss);\n writer.println(sortedConsumerss.size() + \" consumer instance\");\n for (String consumer : sortedConsumerss) {\n writer.println(consumer);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void versions(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List consumers = consumerDAO.findAll();\n Set parametersSet = new HashSet();\n Map> versions = new HashMap>();\n for (Provider provider : providers) {\n parametersSet.add(provider.getParameters());\n }\n for (Consumer consumer : consumers) {\n parametersSet.add(consumer.getParameters());\n }\n Iterator temp = parametersSet.iterator();\n while (temp.hasNext()) {\n Map parameter = StringUtils.parseQueryString(temp.next());\n if (parameter != null) {\n String dubboversion = parameter.get(\"dubbo\");\n String app = parameter.get(\"application\");\n if (versions.get(dubboversion) == null) {\n Set apps = new HashSet();\n versions.put(dubboversion, apps);\n }\n versions.get(dubboversion).add(app);\n }\n }\n for (String version : versions.keySet()) {\n writer.println(\"dubbo version: \" + version);\n writer.println(StringUtils.join(versions.get(version), \"\\n\"));\n writer.println(\"\\n\");\n }\n context.put(\"versions\", versions);\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n private List getNoProviders() {\n List providerServices = providerDAO.findServices();\n List consumerServices = consumerDAO.findServices();\n List noProviderServices = new ArrayList();\n if (consumerServices != null) {\n noProviderServices.addAll(consumerServices);\n noProviderServices.removeAll(providerServices);\n }\n return noProviderServices;\n }\n}\n"} {"task_id": "Java_1238", "language": "Java", "task_type": "method_body", "source_file": "java/github/linux-china/dubbo3/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dump.java", "mask_start_position": 4968, "mask_end_position": 5380, "canonical_solution": "{\n List providerServices = providerDAO.findServices();\n List consumerServices = consumerDAO.findServices();\n List noProviderServices = new ArrayList();\n if (consumerServices != null) {\n noProviderServices.addAll(consumerServices);\n noProviderServices.removeAll(providerServices);\n }\n return noProviderServices;\n }", "pre_mask_code": "package com.alibaba.dubbo.governance.web.sysinfo.module.screen;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.http.HttpServletResponse;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport com.alibaba.dubbo.common.utils.StringUtils;\nimport com.alibaba.dubbo.governance.service.ConsumerService;\nimport com.alibaba.dubbo.governance.service.ProviderService;\nimport com.alibaba.dubbo.governance.web.common.module.screen.Restful;\nimport com.alibaba.dubbo.registry.common.domain.Consumer;\nimport com.alibaba.dubbo.registry.common.domain.Provider;\n\n/**\n * @author tony.chenl\n */\npublic class Dump extends Restful {\n\n @Autowired\n ProviderService providerDAO;\n\n @Autowired\n ConsumerService consumerDAO;\n\n @Autowired\n HttpServletResponse response;\n\n public void noProviders(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = getNoProviders();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services don't have provider\");\n for (String noProvider : sortedService) {\n writer.println(noProvider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void services(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = providerDAO.findServices();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services\");\n for (String service : sortedService) {\n writer.println(service + (providerDAO.findByService(service).size()));\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void providers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List sortedProviders = new ArrayList();\n for (Provider provider : providers) {\n sortedProviders.add(provider.getUrl() + \" \" + provider.getService());\n }\n Collections.sort(sortedProviders);\n writer.println(sortedProviders.size() + \" provider instance\");\n for (String provider : sortedProviders) {\n writer.println(provider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void consumers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List consumers = consumerDAO.findAll();\n List sortedConsumerss = new ArrayList();\n for (Consumer consumer : consumers) {\n sortedConsumerss.add(consumer.getAddress() + \" \" + consumer.getService());\n }\n Collections.sort(sortedConsumerss);\n writer.println(sortedConsumerss.size() + \" consumer instance\");\n for (String consumer : sortedConsumerss) {\n writer.println(consumer);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void versions(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List consumers = consumerDAO.findAll();\n Set parametersSet = new HashSet();\n Map> versions = new HashMap>();\n for (Provider provider : providers) {\n parametersSet.add(provider.getParameters());\n }\n for (Consumer consumer : consumers) {\n parametersSet.add(consumer.getParameters());\n }\n Iterator temp = parametersSet.iterator();\n while (temp.hasNext()) {\n Map parameter = StringUtils.parseQueryString(temp.next());\n if (parameter != null) {\n String dubboversion = parameter.get(\"dubbo\");\n String app = parameter.get(\"application\");\n if (versions.get(dubboversion) == null) {\n Set apps = new HashSet();\n versions.put(dubboversion, apps);\n }\n versions.get(dubboversion).add(app);\n }\n }\n for (String version : versions.keySet()) {\n writer.println(\"dubbo version: \" + version);\n writer.println(StringUtils.join(versions.get(version), \"\\n\"));\n writer.println(\"\\n\");\n }\n context.put(\"versions\", versions);\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n private List getNoProviders() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1239", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/linux-china/dubbo3/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dump.java", "mask_start_position": 2755, "mask_end_position": 2929, "canonical_solution": "\n PrintWriter writer = response.getWriter();\n List consumers = consumerDAO.findAll();\n List sortedConsumerss = new ArrayList();", "pre_mask_code": "package com.alibaba.dubbo.governance.web.sysinfo.module.screen;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.http.HttpServletResponse;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport com.alibaba.dubbo.common.utils.StringUtils;\nimport com.alibaba.dubbo.governance.service.ConsumerService;\nimport com.alibaba.dubbo.governance.service.ProviderService;\nimport com.alibaba.dubbo.governance.web.common.module.screen.Restful;\nimport com.alibaba.dubbo.registry.common.domain.Consumer;\nimport com.alibaba.dubbo.registry.common.domain.Provider;\n\n/**\n * @author tony.chenl\n */\npublic class Dump extends Restful {\n\n @Autowired\n ProviderService providerDAO;\n\n @Autowired\n ConsumerService consumerDAO;\n\n @Autowired\n HttpServletResponse response;\n\n public void noProviders(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = getNoProviders();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services don't have provider\");\n for (String noProvider : sortedService) {\n writer.println(noProvider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void services(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = providerDAO.findServices();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services\");\n for (String service : sortedService) {\n writer.println(service + (providerDAO.findByService(service).size()));\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void providers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List sortedProviders = new ArrayList();\n for (Provider provider : providers) {\n sortedProviders.add(provider.getUrl() + \" \" + provider.getService());\n }\n Collections.sort(sortedProviders);\n writer.println(sortedProviders.size() + \" provider instance\");\n for (String provider : sortedProviders) {\n writer.println(provider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void consumers(Map context) throws IOException {", "post_mask_code": "\n for (Consumer consumer : consumers) {\n sortedConsumerss.add(consumer.getAddress() + \" \" + consumer.getService());\n }\n Collections.sort(sortedConsumerss);\n writer.println(sortedConsumerss.size() + \" consumer instance\");\n for (String consumer : sortedConsumerss) {\n writer.println(consumer);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void versions(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List consumers = consumerDAO.findAll();\n Set parametersSet = new HashSet();\n Map> versions = new HashMap>();\n for (Provider provider : providers) {\n parametersSet.add(provider.getParameters());\n }\n for (Consumer consumer : consumers) {\n parametersSet.add(consumer.getParameters());\n }\n Iterator temp = parametersSet.iterator();\n while (temp.hasNext()) {\n Map parameter = StringUtils.parseQueryString(temp.next());\n if (parameter != null) {\n String dubboversion = parameter.get(\"dubbo\");\n String app = parameter.get(\"application\");\n if (versions.get(dubboversion) == null) {\n Set apps = new HashSet();\n versions.put(dubboversion, apps);\n }\n versions.get(dubboversion).add(app);\n }\n }\n for (String version : versions.keySet()) {\n writer.println(\"dubbo version: \" + version);\n writer.println(StringUtils.join(versions.get(version), \"\\n\"));\n writer.println(\"\\n\");\n }\n context.put(\"versions\", versions);\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n private List getNoProviders() {\n List providerServices = providerDAO.findServices();\n List consumerServices = consumerDAO.findServices();\n List noProviderServices = new ArrayList();\n if (consumerServices != null) {\n noProviderServices.addAll(consumerServices);\n noProviderServices.removeAll(providerServices);\n }\n return noProviderServices;\n }\n}\n"} {"task_id": "Java_1240", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/linux-china/dubbo3/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dump.java", "mask_start_position": 2938, "mask_end_position": 3188, "canonical_solution": "for (Consumer consumer : consumers) {\n sortedConsumerss.add(consumer.getAddress() + \" \" + consumer.getService());\n }\n Collections.sort(sortedConsumerss);\n writer.println(sortedConsumerss.size() + \" consumer instance\");", "pre_mask_code": "package com.alibaba.dubbo.governance.web.sysinfo.module.screen;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.http.HttpServletResponse;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport com.alibaba.dubbo.common.utils.StringUtils;\nimport com.alibaba.dubbo.governance.service.ConsumerService;\nimport com.alibaba.dubbo.governance.service.ProviderService;\nimport com.alibaba.dubbo.governance.web.common.module.screen.Restful;\nimport com.alibaba.dubbo.registry.common.domain.Consumer;\nimport com.alibaba.dubbo.registry.common.domain.Provider;\n\n/**\n * @author tony.chenl\n */\npublic class Dump extends Restful {\n\n @Autowired\n ProviderService providerDAO;\n\n @Autowired\n ConsumerService consumerDAO;\n\n @Autowired\n HttpServletResponse response;\n\n public void noProviders(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = getNoProviders();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services don't have provider\");\n for (String noProvider : sortedService) {\n writer.println(noProvider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void services(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = providerDAO.findServices();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services\");\n for (String service : sortedService) {\n writer.println(service + (providerDAO.findByService(service).size()));\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void providers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List sortedProviders = new ArrayList();\n for (Provider provider : providers) {\n sortedProviders.add(provider.getUrl() + \" \" + provider.getService());\n }\n Collections.sort(sortedProviders);\n writer.println(sortedProviders.size() + \" provider instance\");\n for (String provider : sortedProviders) {\n writer.println(provider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void consumers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List consumers = consumerDAO.findAll();\n List sortedConsumerss = new ArrayList();\n ", "post_mask_code": "\n for (String consumer : sortedConsumerss) {\n writer.println(consumer);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void versions(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List consumers = consumerDAO.findAll();\n Set parametersSet = new HashSet();\n Map> versions = new HashMap>();\n for (Provider provider : providers) {\n parametersSet.add(provider.getParameters());\n }\n for (Consumer consumer : consumers) {\n parametersSet.add(consumer.getParameters());\n }\n Iterator temp = parametersSet.iterator();\n while (temp.hasNext()) {\n Map parameter = StringUtils.parseQueryString(temp.next());\n if (parameter != null) {\n String dubboversion = parameter.get(\"dubbo\");\n String app = parameter.get(\"application\");\n if (versions.get(dubboversion) == null) {\n Set apps = new HashSet();\n versions.put(dubboversion, apps);\n }\n versions.get(dubboversion).add(app);\n }\n }\n for (String version : versions.keySet()) {\n writer.println(\"dubbo version: \" + version);\n writer.println(StringUtils.join(versions.get(version), \"\\n\"));\n writer.println(\"\\n\");\n }\n context.put(\"versions\", versions);\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n private List getNoProviders() {\n List providerServices = providerDAO.findServices();\n List consumerServices = consumerDAO.findServices();\n List noProviderServices = new ArrayList();\n if (consumerServices != null) {\n noProviderServices.addAll(consumerServices);\n noProviderServices.removeAll(providerServices);\n }\n return noProviderServices;\n }\n}\n"} {"task_id": "Java_1241", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/linux-china/dubbo3/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dump.java", "mask_start_position": 3197, "mask_end_position": 3364, "canonical_solution": "for (String consumer : sortedConsumerss) {\n writer.println(consumer);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }", "pre_mask_code": "package com.alibaba.dubbo.governance.web.sysinfo.module.screen;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.http.HttpServletResponse;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport com.alibaba.dubbo.common.utils.StringUtils;\nimport com.alibaba.dubbo.governance.service.ConsumerService;\nimport com.alibaba.dubbo.governance.service.ProviderService;\nimport com.alibaba.dubbo.governance.web.common.module.screen.Restful;\nimport com.alibaba.dubbo.registry.common.domain.Consumer;\nimport com.alibaba.dubbo.registry.common.domain.Provider;\n\n/**\n * @author tony.chenl\n */\npublic class Dump extends Restful {\n\n @Autowired\n ProviderService providerDAO;\n\n @Autowired\n ConsumerService consumerDAO;\n\n @Autowired\n HttpServletResponse response;\n\n public void noProviders(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = getNoProviders();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services don't have provider\");\n for (String noProvider : sortedService) {\n writer.println(noProvider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void services(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = providerDAO.findServices();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services\");\n for (String service : sortedService) {\n writer.println(service + (providerDAO.findByService(service).size()));\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void providers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List sortedProviders = new ArrayList();\n for (Provider provider : providers) {\n sortedProviders.add(provider.getUrl() + \" \" + provider.getService());\n }\n Collections.sort(sortedProviders);\n writer.println(sortedProviders.size() + \" provider instance\");\n for (String provider : sortedProviders) {\n writer.println(provider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void consumers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List consumers = consumerDAO.findAll();\n List sortedConsumerss = new ArrayList();\n for (Consumer consumer : consumers) {\n sortedConsumerss.add(consumer.getAddress() + \" \" + consumer.getService());\n }\n Collections.sort(sortedConsumerss);\n writer.println(sortedConsumerss.size() + \" consumer instance\");\n ", "post_mask_code": "\n\n public void versions(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List consumers = consumerDAO.findAll();\n Set parametersSet = new HashSet();\n Map> versions = new HashMap>();\n for (Provider provider : providers) {\n parametersSet.add(provider.getParameters());\n }\n for (Consumer consumer : consumers) {\n parametersSet.add(consumer.getParameters());\n }\n Iterator temp = parametersSet.iterator();\n while (temp.hasNext()) {\n Map parameter = StringUtils.parseQueryString(temp.next());\n if (parameter != null) {\n String dubboversion = parameter.get(\"dubbo\");\n String app = parameter.get(\"application\");\n if (versions.get(dubboversion) == null) {\n Set apps = new HashSet();\n versions.put(dubboversion, apps);\n }\n versions.get(dubboversion).add(app);\n }\n }\n for (String version : versions.keySet()) {\n writer.println(\"dubbo version: \" + version);\n writer.println(StringUtils.join(versions.get(version), \"\\n\"));\n writer.println(\"\\n\");\n }\n context.put(\"versions\", versions);\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n private List getNoProviders() {\n List providerServices = providerDAO.findServices();\n List consumerServices = consumerDAO.findServices();\n List noProviderServices = new ArrayList();\n if (consumerServices != null) {\n noProviderServices.addAll(consumerServices);\n noProviderServices.removeAll(providerServices);\n }\n return noProviderServices;\n }\n}\n"} {"task_id": "Java_1242", "language": "Java", "task_type": "single_line", "source_file": "java/github/linux-china/dubbo3/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dump.java", "mask_start_position": 1773, "mask_end_position": 1784, "canonical_solution": "services\");", "pre_mask_code": "package com.alibaba.dubbo.governance.web.sysinfo.module.screen;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.http.HttpServletResponse;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport com.alibaba.dubbo.common.utils.StringUtils;\nimport com.alibaba.dubbo.governance.service.ConsumerService;\nimport com.alibaba.dubbo.governance.service.ProviderService;\nimport com.alibaba.dubbo.governance.web.common.module.screen.Restful;\nimport com.alibaba.dubbo.registry.common.domain.Consumer;\nimport com.alibaba.dubbo.registry.common.domain.Provider;\n\n/**\n * @author tony.chenl\n */\npublic class Dump extends Restful {\n\n @Autowired\n ProviderService providerDAO;\n\n @Autowired\n ConsumerService consumerDAO;\n\n @Autowired\n HttpServletResponse response;\n\n public void noProviders(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = getNoProviders();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services don't have provider\");\n for (String noProvider : sortedService) {\n writer.println(noProvider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void services(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = providerDAO.findServices();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" ", "post_mask_code": "\n for (String service : sortedService) {\n writer.println(service + (providerDAO.findByService(service).size()));\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void providers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List sortedProviders = new ArrayList();\n for (Provider provider : providers) {\n sortedProviders.add(provider.getUrl() + \" \" + provider.getService());\n }\n Collections.sort(sortedProviders);\n writer.println(sortedProviders.size() + \" provider instance\");\n for (String provider : sortedProviders) {\n writer.println(provider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void consumers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List consumers = consumerDAO.findAll();\n List sortedConsumerss = new ArrayList();\n for (Consumer consumer : consumers) {\n sortedConsumerss.add(consumer.getAddress() + \" \" + consumer.getService());\n }\n Collections.sort(sortedConsumerss);\n writer.println(sortedConsumerss.size() + \" consumer instance\");\n for (String consumer : sortedConsumerss) {\n writer.println(consumer);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void versions(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List consumers = consumerDAO.findAll();\n Set parametersSet = new HashSet();\n Map> versions = new HashMap>();\n for (Provider provider : providers) {\n parametersSet.add(provider.getParameters());\n }\n for (Consumer consumer : consumers) {\n parametersSet.add(consumer.getParameters());\n }\n Iterator temp = parametersSet.iterator();\n while (temp.hasNext()) {\n Map parameter = StringUtils.parseQueryString(temp.next());\n if (parameter != null) {\n String dubboversion = parameter.get(\"dubbo\");\n String app = parameter.get(\"application\");\n if (versions.get(dubboversion) == null) {\n Set apps = new HashSet();\n versions.put(dubboversion, apps);\n }\n versions.get(dubboversion).add(app);\n }\n }\n for (String version : versions.keySet()) {\n writer.println(\"dubbo version: \" + version);\n writer.println(StringUtils.join(versions.get(version), \"\\n\"));\n writer.println(\"\\n\");\n }\n context.put(\"versions\", versions);\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n private List getNoProviders() {\n List providerServices = providerDAO.findServices();\n List consumerServices = consumerDAO.findServices();\n List noProviderServices = new ArrayList();\n if (consumerServices != null) {\n noProviderServices.addAll(consumerServices);\n noProviderServices.removeAll(providerServices);\n }\n return noProviderServices;\n }\n}\n"} {"task_id": "Java_1243", "language": "Java", "task_type": "if_statement", "source_file": "java/github/linux-china/dubbo3/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/sysinfo/module/screen/Dump.java", "mask_start_position": 4163, "mask_end_position": 4567, "canonical_solution": "if (parameter != null) {\n String dubboversion = parameter.get(\"dubbo\");\n String app = parameter.get(\"application\");\n if (versions.get(dubboversion) == null) {\n Set apps = new HashSet();\n versions.put(dubboversion, apps);\n }\n versions.get(dubboversion).add(app);\n }", "pre_mask_code": "package com.alibaba.dubbo.governance.web.sysinfo.module.screen;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.http.HttpServletResponse;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport com.alibaba.dubbo.common.utils.StringUtils;\nimport com.alibaba.dubbo.governance.service.ConsumerService;\nimport com.alibaba.dubbo.governance.service.ProviderService;\nimport com.alibaba.dubbo.governance.web.common.module.screen.Restful;\nimport com.alibaba.dubbo.registry.common.domain.Consumer;\nimport com.alibaba.dubbo.registry.common.domain.Provider;\n\n/**\n * @author tony.chenl\n */\npublic class Dump extends Restful {\n\n @Autowired\n ProviderService providerDAO;\n\n @Autowired\n ConsumerService consumerDAO;\n\n @Autowired\n HttpServletResponse response;\n\n public void noProviders(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = getNoProviders();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services don't have provider\");\n for (String noProvider : sortedService) {\n writer.println(noProvider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void services(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List sortedService = providerDAO.findServices();\n Collections.sort(sortedService);\n writer.println(sortedService.size() + \" services\");\n for (String service : sortedService) {\n writer.println(service + (providerDAO.findByService(service).size()));\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void providers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List sortedProviders = new ArrayList();\n for (Provider provider : providers) {\n sortedProviders.add(provider.getUrl() + \" \" + provider.getService());\n }\n Collections.sort(sortedProviders);\n writer.println(sortedProviders.size() + \" provider instance\");\n for (String provider : sortedProviders) {\n writer.println(provider);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void consumers(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List consumers = consumerDAO.findAll();\n List sortedConsumerss = new ArrayList();\n for (Consumer consumer : consumers) {\n sortedConsumerss.add(consumer.getAddress() + \" \" + consumer.getService());\n }\n Collections.sort(sortedConsumerss);\n writer.println(sortedConsumerss.size() + \" consumer instance\");\n for (String consumer : sortedConsumerss) {\n writer.println(consumer);\n }\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n public void versions(Map context) throws IOException {\n PrintWriter writer = response.getWriter();\n List providers = providerDAO.findAll();\n List consumers = consumerDAO.findAll();\n Set parametersSet = new HashSet();\n Map> versions = new HashMap>();\n for (Provider provider : providers) {\n parametersSet.add(provider.getParameters());\n }\n for (Consumer consumer : consumers) {\n parametersSet.add(consumer.getParameters());\n }\n Iterator temp = parametersSet.iterator();\n while (temp.hasNext()) {\n Map parameter = StringUtils.parseQueryString(temp.next());\n ", "post_mask_code": "\n }\n for (String version : versions.keySet()) {\n writer.println(\"dubbo version: \" + version);\n writer.println(StringUtils.join(versions.get(version), \"\\n\"));\n writer.println(\"\\n\");\n }\n context.put(\"versions\", versions);\n writer.flush();\n response.setContentType(\"text/plain\");\n }\n\n private List getNoProviders() {\n List providerServices = providerDAO.findServices();\n List consumerServices = consumerDAO.findServices();\n List noProviderServices = new ArrayList();\n if (consumerServices != null) {\n noProviderServices.addAll(consumerServices);\n noProviderServices.removeAll(providerServices);\n }\n return noProviderServices;\n }\n}\n"} {"task_id": "Java_1244", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Multy-io/Multy-Android/app/src/main/java/io/multy/ui/fragments/MultisigSettingsFragment.java", "mask_start_position": 2585, "mask_end_position": 2646, "canonical_solution": "@OnClick(R.id.button_delete)\n public void onClickDelete() ", "pre_mask_code": "package io.multy.ui.fragments;\n\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.design.widget.TextInputEditText;\nimport android.support.v7.app.AlertDialog;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\nimport butterknife.OnClick;\nimport io.multy.R;\nimport io.multy.model.entities.wallet.Wallet;\nimport io.multy.ui.activities.CreateMultiSigActivity;\n\npublic class MultisigSettingsFragment extends BaseFragment {\n\n @BindView(R.id.text_signs)\n TextView textSigngs;\n\n @BindView(R.id.edit_name)\n TextInputEditText editName;\n\n @BindView(R.id.image_wallet)\n ImageView imageWallet;\n\n @BindView(R.id.text_wallet_name)\n TextView textWalletName;\n\n @BindView(R.id.text_wallet_address)\n TextView textWalletAddress;\n\n @BindView(R.id.button_delete)\n View buttonDelete;\n\n private Wallet wallet;\n\n private Wallet connectedWallet;\n\n public static MultisigSettingsFragment newInstance(Wallet wallet, Wallet connectedWallet) {\n MultisigSettingsFragment fragment = new MultisigSettingsFragment();\n fragment.setWallet(wallet);\n fragment.setConnectedWallet(connectedWallet);\n return fragment;\n }\n\n @Nullable\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View convertView = inflater.inflate(R.layout.fragment_multisig_settings, container, false);\n ButterKnife.bind(this, convertView);\n fillViews();\n return convertView;\n }\n\n private void fillViews() {\n if (wallet != null && wallet.isValid() && connectedWallet != null && connectedWallet.isValid()) {\n editName.setText(wallet.getWalletName());\n textWalletAddress.setText(connectedWallet.getActiveAddress().getAddress());\n textWalletName.setText(connectedWallet.getWalletName());\n imageWallet.setImageResource(connectedWallet.getIconResourceId());\n textSigngs.setText(wallet.getMultisigWallet().getConfirmations() + \" / \" + wallet.getMultisigWallet().getOwnersCount());\n if (wallet.getMultisigWallet().getDeployStatus() > 2) {\n buttonDelete.setVisibility(View.GONE);\n }\n }\n }\n\n @OnClick(R.id.button_save)\n public void onClickSave() {\n hideFragment();\n }\n\n ", "post_mask_code": "{\n showDeletePrompt();\n }\n\n public void showDeletePrompt() {\n new AlertDialog.Builder(getActivity()).setMessage(R.string.delete_confirm).setPositiveButton(R.string.yes, (dialog, which) -> {\n ((CreateMultiSigActivity) getActivity()).removeWallet();\n dialog.cancel();\n }).setNegativeButton(R.string.no, (dialog, which) -> {\n dialog.cancel();\n hideFragment();\n }).show();\n }\n\n private void hideFragment() {\n getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();\n }\n\n public void setWallet(Wallet wallet) {\n this.wallet = wallet;\n }\n\n public void setConnectedWallet(Wallet connectedWallet) {\n this.connectedWallet = connectedWallet;\n }\n\n @OnClick(R.id.button_cancel)\n void onClickCancel(View view) {\n if (getActivity() != null) {\n view.setEnabled(false);\n getActivity().onBackPressed();\n }\n }\n}\n"} {"task_id": "Java_1245", "language": "Java", "task_type": "method_body", "source_file": "java/github/Multy-io/Multy-Android/app/src/main/java/io/multy/ui/fragments/MultisigSettingsFragment.java", "mask_start_position": 3274, "mask_end_position": 3311, "canonical_solution": "{\n this.wallet = wallet;\n }", "pre_mask_code": "package io.multy.ui.fragments;\n\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.design.widget.TextInputEditText;\nimport android.support.v7.app.AlertDialog;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\nimport butterknife.OnClick;\nimport io.multy.R;\nimport io.multy.model.entities.wallet.Wallet;\nimport io.multy.ui.activities.CreateMultiSigActivity;\n\npublic class MultisigSettingsFragment extends BaseFragment {\n\n @BindView(R.id.text_signs)\n TextView textSigngs;\n\n @BindView(R.id.edit_name)\n TextInputEditText editName;\n\n @BindView(R.id.image_wallet)\n ImageView imageWallet;\n\n @BindView(R.id.text_wallet_name)\n TextView textWalletName;\n\n @BindView(R.id.text_wallet_address)\n TextView textWalletAddress;\n\n @BindView(R.id.button_delete)\n View buttonDelete;\n\n private Wallet wallet;\n\n private Wallet connectedWallet;\n\n public static MultisigSettingsFragment newInstance(Wallet wallet, Wallet connectedWallet) {\n MultisigSettingsFragment fragment = new MultisigSettingsFragment();\n fragment.setWallet(wallet);\n fragment.setConnectedWallet(connectedWallet);\n return fragment;\n }\n\n @Nullable\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View convertView = inflater.inflate(R.layout.fragment_multisig_settings, container, false);\n ButterKnife.bind(this, convertView);\n fillViews();\n return convertView;\n }\n\n private void fillViews() {\n if (wallet != null && wallet.isValid() && connectedWallet != null && connectedWallet.isValid()) {\n editName.setText(wallet.getWalletName());\n textWalletAddress.setText(connectedWallet.getActiveAddress().getAddress());\n textWalletName.setText(connectedWallet.getWalletName());\n imageWallet.setImageResource(connectedWallet.getIconResourceId());\n textSigngs.setText(wallet.getMultisigWallet().getConfirmations() + \" / \" + wallet.getMultisigWallet().getOwnersCount());\n if (wallet.getMultisigWallet().getDeployStatus() > 2) {\n buttonDelete.setVisibility(View.GONE);\n }\n }\n }\n\n @OnClick(R.id.button_save)\n public void onClickSave() {\n hideFragment();\n }\n\n @OnClick(R.id.button_delete)\n public void onClickDelete() {\n showDeletePrompt();\n }\n\n public void showDeletePrompt() {\n new AlertDialog.Builder(getActivity()).setMessage(R.string.delete_confirm).setPositiveButton(R.string.yes, (dialog, which) -> {\n ((CreateMultiSigActivity) getActivity()).removeWallet();\n dialog.cancel();\n }).setNegativeButton(R.string.no, (dialog, which) -> {\n dialog.cancel();\n hideFragment();\n }).show();\n }\n\n private void hideFragment() {\n getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();\n }\n\n public void setWallet(Wallet wallet) ", "post_mask_code": "\n\n public void setConnectedWallet(Wallet connectedWallet) {\n this.connectedWallet = connectedWallet;\n }\n\n @OnClick(R.id.button_cancel)\n void onClickCancel(View view) {\n if (getActivity() != null) {\n view.setEnabled(false);\n getActivity().onBackPressed();\n }\n }\n}\n"} {"task_id": "Java_1246", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Multy-io/Multy-Android/app/src/main/java/io/multy/ui/fragments/MultisigSettingsFragment.java", "mask_start_position": 1803, "mask_end_position": 1803, "canonical_solution": "", "pre_mask_code": "package io.multy.ui.fragments;\n\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.design.widget.TextInputEditText;\nimport android.support.v7.app.AlertDialog;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\nimport butterknife.OnClick;\nimport io.multy.R;\nimport io.multy.model.entities.wallet.Wallet;\nimport io.multy.ui.activities.CreateMultiSigActivity;\n\npublic class MultisigSettingsFragment extends BaseFragment {\n\n @BindView(R.id.text_signs)\n TextView textSigngs;\n\n @BindView(R.id.edit_name)\n TextInputEditText editName;\n\n @BindView(R.id.image_wallet)\n ImageView imageWallet;\n\n @BindView(R.id.text_wallet_name)\n TextView textWalletName;\n\n @BindView(R.id.text_wallet_address)\n TextView textWalletAddress;\n\n @BindView(R.id.button_delete)\n View buttonDelete;\n\n private Wallet wallet;\n\n private Wallet connectedWallet;\n\n public static MultisigSettingsFragment newInstance(Wallet wallet, Wallet connectedWallet) {\n MultisigSettingsFragment fragment = new MultisigSettingsFragment();\n fragment.setWallet(wallet);\n fragment.setConnectedWallet(connectedWallet);\n return fragment;\n }\n\n @Nullable\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View convertView = inflater.inflate(R.layout.fragment_multisig_settings, container, false);\n ButterKnife.bind(this, convertView);\n fillViews();\n return convertView;\n }\n\n private void fillViews() {", "post_mask_code": "\n if (wallet != null && wallet.isValid() && connectedWallet != null && connectedWallet.isValid()) {\n editName.setText(wallet.getWalletName());\n textWalletAddress.setText(connectedWallet.getActiveAddress().getAddress());\n textWalletName.setText(connectedWallet.getWalletName());\n imageWallet.setImageResource(connectedWallet.getIconResourceId());\n textSigngs.setText(wallet.getMultisigWallet().getConfirmations() + \" / \" + wallet.getMultisigWallet().getOwnersCount());\n if (wallet.getMultisigWallet().getDeployStatus() > 2) {\n buttonDelete.setVisibility(View.GONE);\n }\n }\n }\n\n @OnClick(R.id.button_save)\n public void onClickSave() {\n hideFragment();\n }\n\n @OnClick(R.id.button_delete)\n public void onClickDelete() {\n showDeletePrompt();\n }\n\n public void showDeletePrompt() {\n new AlertDialog.Builder(getActivity()).setMessage(R.string.delete_confirm).setPositiveButton(R.string.yes, (dialog, which) -> {\n ((CreateMultiSigActivity) getActivity()).removeWallet();\n dialog.cancel();\n }).setNegativeButton(R.string.no, (dialog, which) -> {\n dialog.cancel();\n hideFragment();\n }).show();\n }\n\n private void hideFragment() {\n getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();\n }\n\n public void setWallet(Wallet wallet) {\n this.wallet = wallet;\n }\n\n public void setConnectedWallet(Wallet connectedWallet) {\n this.connectedWallet = connectedWallet;\n }\n\n @OnClick(R.id.button_cancel)\n void onClickCancel(View view) {\n if (getActivity() != null) {\n view.setEnabled(false);\n getActivity().onBackPressed();\n }\n }\n}\n"} {"task_id": "Java_1247", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Multy-io/Multy-Android/app/src/main/java/io/multy/ui/fragments/MultisigSettingsFragment.java", "mask_start_position": 1812, "mask_end_position": 2479, "canonical_solution": "if (wallet != null && wallet.isValid() && connectedWallet != null && connectedWallet.isValid()) {\n editName.setText(wallet.getWalletName());\n textWalletAddress.setText(connectedWallet.getActiveAddress().getAddress());\n textWalletName.setText(connectedWallet.getWalletName());\n imageWallet.setImageResource(connectedWallet.getIconResourceId());\n textSigngs.setText(wallet.getMultisigWallet().getConfirmations() + \" / \" + wallet.getMultisigWallet().getOwnersCount());\n if (wallet.getMultisigWallet().getDeployStatus() > 2) {\n buttonDelete.setVisibility(View.GONE);\n }\n }", "pre_mask_code": "package io.multy.ui.fragments;\n\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.design.widget.TextInputEditText;\nimport android.support.v7.app.AlertDialog;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\nimport butterknife.OnClick;\nimport io.multy.R;\nimport io.multy.model.entities.wallet.Wallet;\nimport io.multy.ui.activities.CreateMultiSigActivity;\n\npublic class MultisigSettingsFragment extends BaseFragment {\n\n @BindView(R.id.text_signs)\n TextView textSigngs;\n\n @BindView(R.id.edit_name)\n TextInputEditText editName;\n\n @BindView(R.id.image_wallet)\n ImageView imageWallet;\n\n @BindView(R.id.text_wallet_name)\n TextView textWalletName;\n\n @BindView(R.id.text_wallet_address)\n TextView textWalletAddress;\n\n @BindView(R.id.button_delete)\n View buttonDelete;\n\n private Wallet wallet;\n\n private Wallet connectedWallet;\n\n public static MultisigSettingsFragment newInstance(Wallet wallet, Wallet connectedWallet) {\n MultisigSettingsFragment fragment = new MultisigSettingsFragment();\n fragment.setWallet(wallet);\n fragment.setConnectedWallet(connectedWallet);\n return fragment;\n }\n\n @Nullable\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View convertView = inflater.inflate(R.layout.fragment_multisig_settings, container, false);\n ButterKnife.bind(this, convertView);\n fillViews();\n return convertView;\n }\n\n private void fillViews() {\n ", "post_mask_code": "\n }\n\n @OnClick(R.id.button_save)\n public void onClickSave() {\n hideFragment();\n }\n\n @OnClick(R.id.button_delete)\n public void onClickDelete() {\n showDeletePrompt();\n }\n\n public void showDeletePrompt() {\n new AlertDialog.Builder(getActivity()).setMessage(R.string.delete_confirm).setPositiveButton(R.string.yes, (dialog, which) -> {\n ((CreateMultiSigActivity) getActivity()).removeWallet();\n dialog.cancel();\n }).setNegativeButton(R.string.no, (dialog, which) -> {\n dialog.cancel();\n hideFragment();\n }).show();\n }\n\n private void hideFragment() {\n getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();\n }\n\n public void setWallet(Wallet wallet) {\n this.wallet = wallet;\n }\n\n public void setConnectedWallet(Wallet connectedWallet) {\n this.connectedWallet = connectedWallet;\n }\n\n @OnClick(R.id.button_cancel)\n void onClickCancel(View view) {\n if (getActivity() != null) {\n view.setEnabled(false);\n getActivity().onBackPressed();\n }\n }\n}\n"} {"task_id": "Java_1248", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Multy-io/Multy-Android/app/src/main/java/io/multy/ui/fragments/MultisigSettingsFragment.java", "mask_start_position": 2484, "mask_end_position": 2485, "canonical_solution": "}", "pre_mask_code": "package io.multy.ui.fragments;\n\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.design.widget.TextInputEditText;\nimport android.support.v7.app.AlertDialog;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\nimport butterknife.OnClick;\nimport io.multy.R;\nimport io.multy.model.entities.wallet.Wallet;\nimport io.multy.ui.activities.CreateMultiSigActivity;\n\npublic class MultisigSettingsFragment extends BaseFragment {\n\n @BindView(R.id.text_signs)\n TextView textSigngs;\n\n @BindView(R.id.edit_name)\n TextInputEditText editName;\n\n @BindView(R.id.image_wallet)\n ImageView imageWallet;\n\n @BindView(R.id.text_wallet_name)\n TextView textWalletName;\n\n @BindView(R.id.text_wallet_address)\n TextView textWalletAddress;\n\n @BindView(R.id.button_delete)\n View buttonDelete;\n\n private Wallet wallet;\n\n private Wallet connectedWallet;\n\n public static MultisigSettingsFragment newInstance(Wallet wallet, Wallet connectedWallet) {\n MultisigSettingsFragment fragment = new MultisigSettingsFragment();\n fragment.setWallet(wallet);\n fragment.setConnectedWallet(connectedWallet);\n return fragment;\n }\n\n @Nullable\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View convertView = inflater.inflate(R.layout.fragment_multisig_settings, container, false);\n ButterKnife.bind(this, convertView);\n fillViews();\n return convertView;\n }\n\n private void fillViews() {\n if (wallet != null && wallet.isValid() && connectedWallet != null && connectedWallet.isValid()) {\n editName.setText(wallet.getWalletName());\n textWalletAddress.setText(connectedWallet.getActiveAddress().getAddress());\n textWalletName.setText(connectedWallet.getWalletName());\n imageWallet.setImageResource(connectedWallet.getIconResourceId());\n textSigngs.setText(wallet.getMultisigWallet().getConfirmations() + \" / \" + wallet.getMultisigWallet().getOwnersCount());\n if (wallet.getMultisigWallet().getDeployStatus() > 2) {\n buttonDelete.setVisibility(View.GONE);\n }\n }\n ", "post_mask_code": "\n\n @OnClick(R.id.button_save)\n public void onClickSave() {\n hideFragment();\n }\n\n @OnClick(R.id.button_delete)\n public void onClickDelete() {\n showDeletePrompt();\n }\n\n public void showDeletePrompt() {\n new AlertDialog.Builder(getActivity()).setMessage(R.string.delete_confirm).setPositiveButton(R.string.yes, (dialog, which) -> {\n ((CreateMultiSigActivity) getActivity()).removeWallet();\n dialog.cancel();\n }).setNegativeButton(R.string.no, (dialog, which) -> {\n dialog.cancel();\n hideFragment();\n }).show();\n }\n\n private void hideFragment() {\n getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();\n }\n\n public void setWallet(Wallet wallet) {\n this.wallet = wallet;\n }\n\n public void setConnectedWallet(Wallet connectedWallet) {\n this.connectedWallet = connectedWallet;\n }\n\n @OnClick(R.id.button_cancel)\n void onClickCancel(View view) {\n if (getActivity() != null) {\n view.setEnabled(false);\n getActivity().onBackPressed();\n }\n }\n}\n"} {"task_id": "Java_1249", "language": "Java", "task_type": "single_line", "source_file": "java/github/Multy-io/Multy-Android/app/src/main/java/io/multy/ui/fragments/MultisigSettingsFragment.java", "mask_start_position": 1715, "mask_end_position": 1716, "canonical_solution": ";", "pre_mask_code": "package io.multy.ui.fragments;\n\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.design.widget.TextInputEditText;\nimport android.support.v7.app.AlertDialog;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\nimport butterknife.OnClick;\nimport io.multy.R;\nimport io.multy.model.entities.wallet.Wallet;\nimport io.multy.ui.activities.CreateMultiSigActivity;\n\npublic class MultisigSettingsFragment extends BaseFragment {\n\n @BindView(R.id.text_signs)\n TextView textSigngs;\n\n @BindView(R.id.edit_name)\n TextInputEditText editName;\n\n @BindView(R.id.image_wallet)\n ImageView imageWallet;\n\n @BindView(R.id.text_wallet_name)\n TextView textWalletName;\n\n @BindView(R.id.text_wallet_address)\n TextView textWalletAddress;\n\n @BindView(R.id.button_delete)\n View buttonDelete;\n\n private Wallet wallet;\n\n private Wallet connectedWallet;\n\n public static MultisigSettingsFragment newInstance(Wallet wallet, Wallet connectedWallet) {\n MultisigSettingsFragment fragment = new MultisigSettingsFragment();\n fragment.setWallet(wallet);\n fragment.setConnectedWallet(connectedWallet);\n return fragment;\n }\n\n @Nullable\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View convertView = inflater.inflate(R.layout.fragment_multisig_settings, container, false);\n ButterKnife.bind(this, convertView)", "post_mask_code": "\n fillViews();\n return convertView;\n }\n\n private void fillViews() {\n if (wallet != null && wallet.isValid() && connectedWallet != null && connectedWallet.isValid()) {\n editName.setText(wallet.getWalletName());\n textWalletAddress.setText(connectedWallet.getActiveAddress().getAddress());\n textWalletName.setText(connectedWallet.getWalletName());\n imageWallet.setImageResource(connectedWallet.getIconResourceId());\n textSigngs.setText(wallet.getMultisigWallet().getConfirmations() + \" / \" + wallet.getMultisigWallet().getOwnersCount());\n if (wallet.getMultisigWallet().getDeployStatus() > 2) {\n buttonDelete.setVisibility(View.GONE);\n }\n }\n }\n\n @OnClick(R.id.button_save)\n public void onClickSave() {\n hideFragment();\n }\n\n @OnClick(R.id.button_delete)\n public void onClickDelete() {\n showDeletePrompt();\n }\n\n public void showDeletePrompt() {\n new AlertDialog.Builder(getActivity()).setMessage(R.string.delete_confirm).setPositiveButton(R.string.yes, (dialog, which) -> {\n ((CreateMultiSigActivity) getActivity()).removeWallet();\n dialog.cancel();\n }).setNegativeButton(R.string.no, (dialog, which) -> {\n dialog.cancel();\n hideFragment();\n }).show();\n }\n\n private void hideFragment() {\n getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();\n }\n\n public void setWallet(Wallet wallet) {\n this.wallet = wallet;\n }\n\n public void setConnectedWallet(Wallet connectedWallet) {\n this.connectedWallet = connectedWallet;\n }\n\n @OnClick(R.id.button_cancel)\n void onClickCancel(View view) {\n if (getActivity() != null) {\n view.setEnabled(false);\n getActivity().onBackPressed();\n }\n }\n}\n"} {"task_id": "Java_1250", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Multy-io/Multy-Android/app/src/main/java/io/multy/ui/fragments/MultisigSettingsFragment.java", "mask_start_position": 2345, "mask_end_position": 2469, "canonical_solution": "if (wallet.getMultisigWallet().getDeployStatus() > 2) {\n buttonDelete.setVisibility(View.GONE);\n }", "pre_mask_code": "package io.multy.ui.fragments;\n\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.design.widget.TextInputEditText;\nimport android.support.v7.app.AlertDialog;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\nimport butterknife.OnClick;\nimport io.multy.R;\nimport io.multy.model.entities.wallet.Wallet;\nimport io.multy.ui.activities.CreateMultiSigActivity;\n\npublic class MultisigSettingsFragment extends BaseFragment {\n\n @BindView(R.id.text_signs)\n TextView textSigngs;\n\n @BindView(R.id.edit_name)\n TextInputEditText editName;\n\n @BindView(R.id.image_wallet)\n ImageView imageWallet;\n\n @BindView(R.id.text_wallet_name)\n TextView textWalletName;\n\n @BindView(R.id.text_wallet_address)\n TextView textWalletAddress;\n\n @BindView(R.id.button_delete)\n View buttonDelete;\n\n private Wallet wallet;\n\n private Wallet connectedWallet;\n\n public static MultisigSettingsFragment newInstance(Wallet wallet, Wallet connectedWallet) {\n MultisigSettingsFragment fragment = new MultisigSettingsFragment();\n fragment.setWallet(wallet);\n fragment.setConnectedWallet(connectedWallet);\n return fragment;\n }\n\n @Nullable\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View convertView = inflater.inflate(R.layout.fragment_multisig_settings, container, false);\n ButterKnife.bind(this, convertView);\n fillViews();\n return convertView;\n }\n\n private void fillViews() {\n if (wallet != null && wallet.isValid() && connectedWallet != null && connectedWallet.isValid()) {\n editName.setText(wallet.getWalletName());\n textWalletAddress.setText(connectedWallet.getActiveAddress().getAddress());\n textWalletName.setText(connectedWallet.getWalletName());\n imageWallet.setImageResource(connectedWallet.getIconResourceId());\n textSigngs.setText(wallet.getMultisigWallet().getConfirmations() + \" / \" + wallet.getMultisigWallet().getOwnersCount());\n ", "post_mask_code": "\n }\n }\n\n @OnClick(R.id.button_save)\n public void onClickSave() {\n hideFragment();\n }\n\n @OnClick(R.id.button_delete)\n public void onClickDelete() {\n showDeletePrompt();\n }\n\n public void showDeletePrompt() {\n new AlertDialog.Builder(getActivity()).setMessage(R.string.delete_confirm).setPositiveButton(R.string.yes, (dialog, which) -> {\n ((CreateMultiSigActivity) getActivity()).removeWallet();\n dialog.cancel();\n }).setNegativeButton(R.string.no, (dialog, which) -> {\n dialog.cancel();\n hideFragment();\n }).show();\n }\n\n private void hideFragment() {\n getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();\n }\n\n public void setWallet(Wallet wallet) {\n this.wallet = wallet;\n }\n\n public void setConnectedWallet(Wallet connectedWallet) {\n this.connectedWallet = connectedWallet;\n }\n\n @OnClick(R.id.button_cancel)\n void onClickCancel(View view) {\n if (getActivity() != null) {\n view.setEnabled(false);\n getActivity().onBackPressed();\n }\n }\n}\n"} {"task_id": "Java_1251", "language": "Java", "task_type": "method_signature", "source_file": "java/github/OxfordHCC/tracker-control-android/app/src/main/java/net/kollnig/missioncontrol/data/StaticTracker.java", "mask_start_position": 1089, "mask_end_position": 1113, "canonical_solution": "public String getSign() ", "pre_mask_code": "package net.kollnig.missioncontrol.data;\n\nimport androidx.annotation.NonNull;\n\npublic class StaticTracker implements Comparable {\n\n private final String name;\n\n private final String web;\n\n private final int id;\n\n private final String sign;\n\n public StaticTracker(@NonNull String name, String web, Integer id, String sign) {\n name = name.replaceAll(\"[°²?µ]\", \"\");\n this.name = name;\n this.web = web;\n this.id = id;\n this.sign = sign;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n StaticTracker tracker = (StaticTracker) o;\n return id == tracker.id;\n }\n\n @Override\n public int hashCode() {\n return id;\n }\n\n @Override\n public String toString() {\n return name;\n }\n\n public String getName() {\n return name;\n }\n\n public String getWeb() {\n return web;\n }\n\n public Integer getId() {\n return id;\n }\n\n ", "post_mask_code": "{\n return sign;\n }\n\n @Override\n public int compareTo(StaticTracker t) {\n return name.compareTo(t.name);\n }\n}\n"} {"task_id": "Java_1252", "language": "Java", "task_type": "method_body", "source_file": "java/github/OxfordHCC/tracker-control-android/app/src/main/java/net/kollnig/missioncontrol/data/StaticTracker.java", "mask_start_position": 815, "mask_end_position": 841, "canonical_solution": "{\n return id;\n }", "pre_mask_code": "package net.kollnig.missioncontrol.data;\n\nimport androidx.annotation.NonNull;\n\npublic class StaticTracker implements Comparable {\n\n private final String name;\n\n private final String web;\n\n private final int id;\n\n private final String sign;\n\n public StaticTracker(@NonNull String name, String web, Integer id, String sign) {\n name = name.replaceAll(\"[°²?µ]\", \"\");\n this.name = name;\n this.web = web;\n this.id = id;\n this.sign = sign;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n StaticTracker tracker = (StaticTracker) o;\n return id == tracker.id;\n }\n\n @Override\n public int hashCode() ", "post_mask_code": "\n\n @Override\n public String toString() {\n return name;\n }\n\n public String getName() {\n return name;\n }\n\n public String getWeb() {\n return web;\n }\n\n public Integer getId() {\n return id;\n }\n\n public String getSign() {\n return sign;\n }\n\n @Override\n public int compareTo(StaticTracker t) {\n return name.compareTo(t.name);\n }\n}\n"} {"task_id": "Java_1253", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/OxfordHCC/tracker-control-android/app/src/main/java/net/kollnig/missioncontrol/data/StaticTracker.java", "mask_start_position": 556, "mask_end_position": 604, "canonical_solution": "\n if (this == o)\n return true;", "pre_mask_code": "package net.kollnig.missioncontrol.data;\n\nimport androidx.annotation.NonNull;\n\npublic class StaticTracker implements Comparable {\n\n private final String name;\n\n private final String web;\n\n private final int id;\n\n private final String sign;\n\n public StaticTracker(@NonNull String name, String web, Integer id, String sign) {\n name = name.replaceAll(\"[°²?µ]\", \"\");\n this.name = name;\n this.web = web;\n this.id = id;\n this.sign = sign;\n }\n\n @Override\n public boolean equals(Object o) {", "post_mask_code": "\n if (o == null || getClass() != o.getClass())\n return false;\n StaticTracker tracker = (StaticTracker) o;\n return id == tracker.id;\n }\n\n @Override\n public int hashCode() {\n return id;\n }\n\n @Override\n public String toString() {\n return name;\n }\n\n public String getName() {\n return name;\n }\n\n public String getWeb() {\n return web;\n }\n\n public Integer getId() {\n return id;\n }\n\n public String getSign() {\n return sign;\n }\n\n @Override\n public int compareTo(StaticTracker t) {\n return name.compareTo(t.name);\n }\n}\n"} {"task_id": "Java_1254", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/OxfordHCC/tracker-control-android/app/src/main/java/net/kollnig/missioncontrol/data/StaticTracker.java", "mask_start_position": 613, "mask_end_position": 734, "canonical_solution": "if (o == null || getClass() != o.getClass())\n return false;\n StaticTracker tracker = (StaticTracker) o;", "pre_mask_code": "package net.kollnig.missioncontrol.data;\n\nimport androidx.annotation.NonNull;\n\npublic class StaticTracker implements Comparable {\n\n private final String name;\n\n private final String web;\n\n private final int id;\n\n private final String sign;\n\n public StaticTracker(@NonNull String name, String web, Integer id, String sign) {\n name = name.replaceAll(\"[°²?µ]\", \"\");\n this.name = name;\n this.web = web;\n this.id = id;\n this.sign = sign;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n ", "post_mask_code": "\n return id == tracker.id;\n }\n\n @Override\n public int hashCode() {\n return id;\n }\n\n @Override\n public String toString() {\n return name;\n }\n\n public String getName() {\n return name;\n }\n\n public String getWeb() {\n return web;\n }\n\n public Integer getId() {\n return id;\n }\n\n public String getSign() {\n return sign;\n }\n\n @Override\n public int compareTo(StaticTracker t) {\n return name.compareTo(t.name);\n }\n}\n"} {"task_id": "Java_1255", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/OxfordHCC/tracker-control-android/app/src/main/java/net/kollnig/missioncontrol/data/StaticTracker.java", "mask_start_position": 743, "mask_end_position": 773, "canonical_solution": "return id == tracker.id;\n }", "pre_mask_code": "package net.kollnig.missioncontrol.data;\n\nimport androidx.annotation.NonNull;\n\npublic class StaticTracker implements Comparable {\n\n private final String name;\n\n private final String web;\n\n private final int id;\n\n private final String sign;\n\n public StaticTracker(@NonNull String name, String web, Integer id, String sign) {\n name = name.replaceAll(\"[°²?µ]\", \"\");\n this.name = name;\n this.web = web;\n this.id = id;\n this.sign = sign;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n StaticTracker tracker = (StaticTracker) o;\n ", "post_mask_code": "\n\n @Override\n public int hashCode() {\n return id;\n }\n\n @Override\n public String toString() {\n return name;\n }\n\n public String getName() {\n return name;\n }\n\n public String getWeb() {\n return web;\n }\n\n public Integer getId() {\n return id;\n }\n\n public String getSign() {\n return sign;\n }\n\n @Override\n public int compareTo(StaticTracker t) {\n return name.compareTo(t.name);\n }\n}\n"} {"task_id": "Java_1256", "language": "Java", "task_type": "single_line", "source_file": "java/github/OxfordHCC/tracker-control-android/app/src/main/java/net/kollnig/missioncontrol/data/StaticTracker.java", "mask_start_position": 1021, "mask_end_position": 1022, "canonical_solution": ";", "pre_mask_code": "package net.kollnig.missioncontrol.data;\n\nimport androidx.annotation.NonNull;\n\npublic class StaticTracker implements Comparable {\n\n private final String name;\n\n private final String web;\n\n private final int id;\n\n private final String sign;\n\n public StaticTracker(@NonNull String name, String web, Integer id, String sign) {\n name = name.replaceAll(\"[°²?µ]\", \"\");\n this.name = name;\n this.web = web;\n this.id = id;\n this.sign = sign;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n StaticTracker tracker = (StaticTracker) o;\n return id == tracker.id;\n }\n\n @Override\n public int hashCode() {\n return id;\n }\n\n @Override\n public String toString() {\n return name;\n }\n\n public String getName() {\n return name;\n }\n\n public String getWeb() {\n return web", "post_mask_code": "\n }\n\n public Integer getId() {\n return id;\n }\n\n public String getSign() {\n return sign;\n }\n\n @Override\n public int compareTo(StaticTracker t) {\n return name.compareTo(t.name);\n }\n}\n"} {"task_id": "Java_1257", "language": "Java", "task_type": "if_statement", "source_file": "java/github/OxfordHCC/tracker-control-android/app/src/main/java/net/kollnig/missioncontrol/data/StaticTracker.java", "mask_start_position": 613, "mask_end_position": 683, "canonical_solution": "if (o == null || getClass() != o.getClass())\n return false;", "pre_mask_code": "package net.kollnig.missioncontrol.data;\n\nimport androidx.annotation.NonNull;\n\npublic class StaticTracker implements Comparable {\n\n private final String name;\n\n private final String web;\n\n private final int id;\n\n private final String sign;\n\n public StaticTracker(@NonNull String name, String web, Integer id, String sign) {\n name = name.replaceAll(\"[°²?µ]\", \"\");\n this.name = name;\n this.web = web;\n this.id = id;\n this.sign = sign;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n ", "post_mask_code": "\n StaticTracker tracker = (StaticTracker) o;\n return id == tracker.id;\n }\n\n @Override\n public int hashCode() {\n return id;\n }\n\n @Override\n public String toString() {\n return name;\n }\n\n public String getName() {\n return name;\n }\n\n public String getWeb() {\n return web;\n }\n\n public Integer getId() {\n return id;\n }\n\n public String getSign() {\n return sign;\n }\n\n @Override\n public int compareTo(StaticTracker t) {\n return name.compareTo(t.name);\n }\n}\n"} {"task_id": "Java_1258", "language": "Java", "task_type": "method_signature", "source_file": "java/github/wildfly/wildfly/clustering/web/extension/src/main/java/org/wildfly/extension/clustering/web/DistributableWebExtension.java", "mask_start_position": 973, "mask_end_position": 1036, "canonical_solution": "@Override\n public void initialize(ExtensionContext context) ", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source.\n * as indicated by the @author tags. See the copyright.txt file in the\n * distribution for a full listing of individual contributors.\n *\n */\npackage org.wildfly.extension.clustering.web;\n\nimport java.util.EnumSet;\nimport org.jboss.as.clustering.controller.Schema;\nimport org.jboss.as.clustering.controller.descriptions.SubsystemResourceDescriptionResolver;\nimport org.jboss.as.controller.Extension;\nimport org.jboss.as.controller.ExtensionContext;\nimport org.jboss.as.controller.SubsystemRegistration;\nimport org.jboss.as.controller.parsing.ExtensionParsingContext;\nimport org.kohsuke.MetaInfServices;\n\n/**\n * @author Paul Ferraro\n */\n@MetaInfServices(Extension.class)\npublic class DistributableWebExtension implements Extension {\n\n static final String SUBSYSTEM_NAME = \"distributable-web\";\n\n static final SubsystemResourceDescriptionResolver SUBSYSTEM_RESOLVER = new DistributableWebResourceDescriptionResolver();\n\n ", "post_mask_code": "{\n SubsystemRegistration registration = context.registerSubsystem(SUBSYSTEM_NAME, DistributableWebModel.CURRENT.getVersion());\n new DistributableWebResourceDefinition().register(registration);\n registration.registerXMLElementWriter(new DistributableWebXMLParser(DistributableWebSchema.CURRENT));\n }\n\n @Override\n public void initializeParsers(ExtensionParsingContext context) {\n for (Schema schema : EnumSet.allOf(DistributableWebSchema.class)) {\n context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespaceUri(), new DistributableWebXMLParser(schema));\n }\n }\n}\n"} {"task_id": "Java_1259", "language": "Java", "task_type": "method_body", "source_file": "java/github/wildfly/wildfly/clustering/web/extension/src/main/java/org/wildfly/extension/clustering/web/DistributableWebExtension.java", "mask_start_position": 1441, "mask_end_position": 1683, "canonical_solution": "{\n for (Schema schema : EnumSet.allOf(DistributableWebSchema.class)) {\n context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespaceUri(), new DistributableWebXMLParser(schema));\n }\n }", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source.\n * as indicated by the @author tags. See the copyright.txt file in the\n * distribution for a full listing of individual contributors.\n *\n */\npackage org.wildfly.extension.clustering.web;\n\nimport java.util.EnumSet;\nimport org.jboss.as.clustering.controller.Schema;\nimport org.jboss.as.clustering.controller.descriptions.SubsystemResourceDescriptionResolver;\nimport org.jboss.as.controller.Extension;\nimport org.jboss.as.controller.ExtensionContext;\nimport org.jboss.as.controller.SubsystemRegistration;\nimport org.jboss.as.controller.parsing.ExtensionParsingContext;\nimport org.kohsuke.MetaInfServices;\n\n/**\n * @author Paul Ferraro\n */\n@MetaInfServices(Extension.class)\npublic class DistributableWebExtension implements Extension {\n\n static final String SUBSYSTEM_NAME = \"distributable-web\";\n\n static final SubsystemResourceDescriptionResolver SUBSYSTEM_RESOLVER = new DistributableWebResourceDescriptionResolver();\n\n @Override\n public void initialize(ExtensionContext context) {\n SubsystemRegistration registration = context.registerSubsystem(SUBSYSTEM_NAME, DistributableWebModel.CURRENT.getVersion());\n new DistributableWebResourceDefinition().register(registration);\n registration.registerXMLElementWriter(new DistributableWebXMLParser(DistributableWebSchema.CURRENT));\n }\n\n @Override\n public void initializeParsers(ExtensionParsingContext context) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1260", "language": "Java", "task_type": "single_line", "source_file": "java/github/wildfly/wildfly/clustering/web/extension/src/main/java/org/wildfly/extension/clustering/web/DistributableWebExtension.java", "mask_start_position": 1331, "mask_end_position": 1352, "canonical_solution": "eWebSchema.CURRENT));", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source.\n * as indicated by the @author tags. See the copyright.txt file in the\n * distribution for a full listing of individual contributors.\n *\n */\npackage org.wildfly.extension.clustering.web;\n\nimport java.util.EnumSet;\nimport org.jboss.as.clustering.controller.Schema;\nimport org.jboss.as.clustering.controller.descriptions.SubsystemResourceDescriptionResolver;\nimport org.jboss.as.controller.Extension;\nimport org.jboss.as.controller.ExtensionContext;\nimport org.jboss.as.controller.SubsystemRegistration;\nimport org.jboss.as.controller.parsing.ExtensionParsingContext;\nimport org.kohsuke.MetaInfServices;\n\n/**\n * @author Paul Ferraro\n */\n@MetaInfServices(Extension.class)\npublic class DistributableWebExtension implements Extension {\n\n static final String SUBSYSTEM_NAME = \"distributable-web\";\n\n static final SubsystemResourceDescriptionResolver SUBSYSTEM_RESOLVER = new DistributableWebResourceDescriptionResolver();\n\n @Override\n public void initialize(ExtensionContext context) {\n SubsystemRegistration registration = context.registerSubsystem(SUBSYSTEM_NAME, DistributableWebModel.CURRENT.getVersion());\n new DistributableWebResourceDefinition().register(registration);\n registration.registerXMLElementWriter(new DistributableWebXMLParser(Distributabl", "post_mask_code": "\n }\n\n @Override\n public void initializeParsers(ExtensionParsingContext context) {\n for (Schema schema : EnumSet.allOf(DistributableWebSchema.class)) {\n context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespaceUri(), new DistributableWebXMLParser(schema));\n }\n }\n}\n"} {"task_id": "Java_1261", "language": "Java", "task_type": "method_signature", "source_file": "java/github/aliyun/aliyun-openapi-java-sdk/aliyun-java-sdk-sas/src/main/java/com/aliyuncs/sas/transform/v20181203/ModifyRiskSingleResultStatusResponseUnmarshaller.java", "mask_start_position": 246, "mask_end_position": 409, "canonical_solution": "public static ModifyRiskSingleResultStatusResponse unmarshall(ModifyRiskSingleResultStatusResponse modifyRiskSingleResultStatusResponse, UnmarshallerContext _ctx) ", "pre_mask_code": "package com.aliyuncs.sas.transform.v20181203;\n\nimport com.aliyuncs.sas.model.v20181203.ModifyRiskSingleResultStatusResponse;\nimport com.aliyuncs.transform.UnmarshallerContext;\n\npublic class ModifyRiskSingleResultStatusResponseUnmarshaller {\n\n ", "post_mask_code": "{\n modifyRiskSingleResultStatusResponse.setRequestId(_ctx.stringValue(\"ModifyRiskSingleResultStatusResponse.RequestId\"));\n return modifyRiskSingleResultStatusResponse;\n }\n}\n"} {"task_id": "Java_1262", "language": "Java", "task_type": "method_body", "source_file": "java/github/aliyun/aliyun-openapi-java-sdk/aliyun-java-sdk-sas/src/main/java/com/aliyuncs/sas/transform/v20181203/ModifyRiskSingleResultStatusResponseUnmarshaller.java", "mask_start_position": 409, "mask_end_position": 596, "canonical_solution": "{\n modifyRiskSingleResultStatusResponse.setRequestId(_ctx.stringValue(\"ModifyRiskSingleResultStatusResponse.RequestId\"));\n return modifyRiskSingleResultStatusResponse;\n }", "pre_mask_code": "package com.aliyuncs.sas.transform.v20181203;\n\nimport com.aliyuncs.sas.model.v20181203.ModifyRiskSingleResultStatusResponse;\nimport com.aliyuncs.transform.UnmarshallerContext;\n\npublic class ModifyRiskSingleResultStatusResponseUnmarshaller {\n\n public static ModifyRiskSingleResultStatusResponse unmarshall(ModifyRiskSingleResultStatusResponse modifyRiskSingleResultStatusResponse, UnmarshallerContext _ctx) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1263", "language": "Java", "task_type": "single_line", "source_file": "java/github/aliyun/aliyun-openapi-java-sdk/aliyun-java-sdk-sas/src/main/java/com/aliyuncs/sas/transform/v20181203/ModifyRiskSingleResultStatusResponseUnmarshaller.java", "mask_start_position": 555, "mask_end_position": 590, "canonical_solution": "difyRiskSingleResultStatusResponse;", "pre_mask_code": "package com.aliyuncs.sas.transform.v20181203;\n\nimport com.aliyuncs.sas.model.v20181203.ModifyRiskSingleResultStatusResponse;\nimport com.aliyuncs.transform.UnmarshallerContext;\n\npublic class ModifyRiskSingleResultStatusResponseUnmarshaller {\n\n public static ModifyRiskSingleResultStatusResponse unmarshall(ModifyRiskSingleResultStatusResponse modifyRiskSingleResultStatusResponse, UnmarshallerContext _ctx) {\n modifyRiskSingleResultStatusResponse.setRequestId(_ctx.stringValue(\"ModifyRiskSingleResultStatusResponse.RequestId\"));\n return mo", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1264", "language": "Java", "task_type": "method_signature", "source_file": "java/github/pingidentity/ldapsdk/tests/unit/src/com/unboundid/ldap/sdk/controls/ContentSyncRequestModeTestCase.java", "mask_start_position": 526, "mask_end_position": 585, "canonical_solution": "@Test()\n public void testRefreshOnly() throws Exception ", "pre_mask_code": "/*\n * All Rights Reserved.\n */\npackage com.unboundid.ldap.sdk.controls;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.testng.annotations.Test;\nimport com.unboundid.ldap.sdk.LDAPSDKTestCase;\n\n/**\n * This class provides a set of test cases for the\n * {@code ContentSyncRequestMode} class.\n */\npublic final class ContentSyncRequestModeTestCase extends LDAPSDKTestCase {\n\n /**\n * Provides test coverage for the REFRESH_ONLY mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n ", "post_mask_code": "{\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_ONLY;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 1);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides test coverage for the REFRESH_AND_PERSIST mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshAndPersist() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_AND_PERSIST;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 3);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides general test coverage for the enum.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testGeneral() throws Exception {\n for (final ContentSyncRequestMode m : ContentSyncRequestMode.values()) {\n assertNotNull(m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(m.name());\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n try {\n ContentSyncRequestMode.valueOf(\"invalid\");\n fail(\"Expected an exception for an invalid valueOf string\");\n } catch (final Exception e) {\n // This was expected.\n }\n assertNull(ContentSyncRequestMode.valueOf(-1));\n }\n\n /**\n * Tests the {@code forName} method with automated tests based on the actual\n * name of the enum values.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testForNameAutomated() throws Exception {\n for (final ContentSyncRequestMode value : ContentSyncRequestMode.values()) {\n for (final String name : getNames(value.name())) {\n assertNotNull(ContentSyncRequestMode.forName(name));\n assertEquals(ContentSyncRequestMode.forName(name), value);\n }\n }\n assertNull(ContentSyncRequestMode.forName(\"some undefined name\"));\n }\n\n /**\n * Retrieves a set of names for testing the {@code forName} method based on\n * the provided set of names.\n *\n * @param baseNames The base set of names to use to generate the full set of\n * names. It must not be {@code null} or empty.\n *\n * @return The full set of names to use for testing.\n */\n private static Set getNames(final String... baseNames) {\n final HashSet nameSet = new HashSet<>(10);\n for (final String name : baseNames) {\n nameSet.add(name);\n nameSet.add(name.toLowerCase());\n nameSet.add(name.toUpperCase());\n final String nameWithDashesInsteadOfUnderscores = name.replace('_', '-');\n nameSet.add(nameWithDashesInsteadOfUnderscores);\n nameSet.add(nameWithDashesInsteadOfUnderscores.toLowerCase());\n nameSet.add(nameWithDashesInsteadOfUnderscores.toUpperCase());\n final String nameWithUnderscoresInsteadOfDashes = name.replace('-', '_');\n nameSet.add(nameWithUnderscoresInsteadOfDashes);\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toLowerCase());\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toUpperCase());\n final StringBuilder nameWithoutUnderscoresOrDashes = new StringBuilder();\n for (final char c : name.toCharArray()) {\n if ((c != '-') && (c != '_')) {\n nameWithoutUnderscoresOrDashes.append(c);\n }\n }\n nameSet.add(nameWithoutUnderscoresOrDashes.toString());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toLowerCase());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toUpperCase());\n }\n return nameSet;\n }\n}\n"} {"task_id": "Java_1265", "language": "Java", "task_type": "method_body", "source_file": "java/github/pingidentity/ldapsdk/tests/unit/src/com/unboundid/ldap/sdk/controls/ContentSyncRequestModeTestCase.java", "mask_start_position": 1269, "mask_end_position": 1742, "canonical_solution": "{\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_AND_PERSIST;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 3);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }", "pre_mask_code": "/*\n * All Rights Reserved.\n */\npackage com.unboundid.ldap.sdk.controls;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.testng.annotations.Test;\nimport com.unboundid.ldap.sdk.LDAPSDKTestCase;\n\n/**\n * This class provides a set of test cases for the\n * {@code ContentSyncRequestMode} class.\n */\npublic final class ContentSyncRequestModeTestCase extends LDAPSDKTestCase {\n\n /**\n * Provides test coverage for the REFRESH_ONLY mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshOnly() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_ONLY;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 1);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides test coverage for the REFRESH_AND_PERSIST mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshAndPersist() throws Exception ", "post_mask_code": "\n\n /**\n * Provides general test coverage for the enum.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testGeneral() throws Exception {\n for (final ContentSyncRequestMode m : ContentSyncRequestMode.values()) {\n assertNotNull(m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(m.name());\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n try {\n ContentSyncRequestMode.valueOf(\"invalid\");\n fail(\"Expected an exception for an invalid valueOf string\");\n } catch (final Exception e) {\n // This was expected.\n }\n assertNull(ContentSyncRequestMode.valueOf(-1));\n }\n\n /**\n * Tests the {@code forName} method with automated tests based on the actual\n * name of the enum values.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testForNameAutomated() throws Exception {\n for (final ContentSyncRequestMode value : ContentSyncRequestMode.values()) {\n for (final String name : getNames(value.name())) {\n assertNotNull(ContentSyncRequestMode.forName(name));\n assertEquals(ContentSyncRequestMode.forName(name), value);\n }\n }\n assertNull(ContentSyncRequestMode.forName(\"some undefined name\"));\n }\n\n /**\n * Retrieves a set of names for testing the {@code forName} method based on\n * the provided set of names.\n *\n * @param baseNames The base set of names to use to generate the full set of\n * names. It must not be {@code null} or empty.\n *\n * @return The full set of names to use for testing.\n */\n private static Set getNames(final String... baseNames) {\n final HashSet nameSet = new HashSet<>(10);\n for (final String name : baseNames) {\n nameSet.add(name);\n nameSet.add(name.toLowerCase());\n nameSet.add(name.toUpperCase());\n final String nameWithDashesInsteadOfUnderscores = name.replace('_', '-');\n nameSet.add(nameWithDashesInsteadOfUnderscores);\n nameSet.add(nameWithDashesInsteadOfUnderscores.toLowerCase());\n nameSet.add(nameWithDashesInsteadOfUnderscores.toUpperCase());\n final String nameWithUnderscoresInsteadOfDashes = name.replace('-', '_');\n nameSet.add(nameWithUnderscoresInsteadOfDashes);\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toLowerCase());\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toUpperCase());\n final StringBuilder nameWithoutUnderscoresOrDashes = new StringBuilder();\n for (final char c : name.toCharArray()) {\n if ((c != '-') && (c != '_')) {\n nameWithoutUnderscoresOrDashes.append(c);\n }\n }\n nameSet.add(nameWithoutUnderscoresOrDashes.toString());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toLowerCase());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toUpperCase());\n }\n return nameSet;\n }\n}\n"} {"task_id": "Java_1266", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/pingidentity/ldapsdk/tests/unit/src/com/unboundid/ldap/sdk/controls/ContentSyncRequestModeTestCase.java", "mask_start_position": 586, "mask_end_position": 734, "canonical_solution": "\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_ONLY;\n assertNotNull(m.name());\n assertNotNull(m.toString());", "pre_mask_code": "/*\n * All Rights Reserved.\n */\npackage com.unboundid.ldap.sdk.controls;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.testng.annotations.Test;\nimport com.unboundid.ldap.sdk.LDAPSDKTestCase;\n\n/**\n * This class provides a set of test cases for the\n * {@code ContentSyncRequestMode} class.\n */\npublic final class ContentSyncRequestModeTestCase extends LDAPSDKTestCase {\n\n /**\n * Provides test coverage for the REFRESH_ONLY mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshOnly() throws Exception {", "post_mask_code": "\n assertEquals(m.intValue(), 1);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides test coverage for the REFRESH_AND_PERSIST mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshAndPersist() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_AND_PERSIST;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 3);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides general test coverage for the enum.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testGeneral() throws Exception {\n for (final ContentSyncRequestMode m : ContentSyncRequestMode.values()) {\n assertNotNull(m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(m.name());\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n try {\n ContentSyncRequestMode.valueOf(\"invalid\");\n fail(\"Expected an exception for an invalid valueOf string\");\n } catch (final Exception e) {\n // This was expected.\n }\n assertNull(ContentSyncRequestMode.valueOf(-1));\n }\n\n /**\n * Tests the {@code forName} method with automated tests based on the actual\n * name of the enum values.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testForNameAutomated() throws Exception {\n for (final ContentSyncRequestMode value : ContentSyncRequestMode.values()) {\n for (final String name : getNames(value.name())) {\n assertNotNull(ContentSyncRequestMode.forName(name));\n assertEquals(ContentSyncRequestMode.forName(name), value);\n }\n }\n assertNull(ContentSyncRequestMode.forName(\"some undefined name\"));\n }\n\n /**\n * Retrieves a set of names for testing the {@code forName} method based on\n * the provided set of names.\n *\n * @param baseNames The base set of names to use to generate the full set of\n * names. It must not be {@code null} or empty.\n *\n * @return The full set of names to use for testing.\n */\n private static Set getNames(final String... baseNames) {\n final HashSet nameSet = new HashSet<>(10);\n for (final String name : baseNames) {\n nameSet.add(name);\n nameSet.add(name.toLowerCase());\n nameSet.add(name.toUpperCase());\n final String nameWithDashesInsteadOfUnderscores = name.replace('_', '-');\n nameSet.add(nameWithDashesInsteadOfUnderscores);\n nameSet.add(nameWithDashesInsteadOfUnderscores.toLowerCase());\n nameSet.add(nameWithDashesInsteadOfUnderscores.toUpperCase());\n final String nameWithUnderscoresInsteadOfDashes = name.replace('-', '_');\n nameSet.add(nameWithUnderscoresInsteadOfDashes);\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toLowerCase());\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toUpperCase());\n final StringBuilder nameWithoutUnderscoresOrDashes = new StringBuilder();\n for (final char c : name.toCharArray()) {\n if ((c != '-') && (c != '_')) {\n nameWithoutUnderscoresOrDashes.append(c);\n }\n }\n nameSet.add(nameWithoutUnderscoresOrDashes.toString());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toLowerCase());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toUpperCase());\n }\n return nameSet;\n }\n}\n"} {"task_id": "Java_1267", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/pingidentity/ldapsdk/tests/unit/src/com/unboundid/ldap/sdk/controls/ContentSyncRequestModeTestCase.java", "mask_start_position": 743, "mask_end_position": 913, "canonical_solution": "assertEquals(m.intValue(), 1);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);", "pre_mask_code": "/*\n * All Rights Reserved.\n */\npackage com.unboundid.ldap.sdk.controls;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.testng.annotations.Test;\nimport com.unboundid.ldap.sdk.LDAPSDKTestCase;\n\n/**\n * This class provides a set of test cases for the\n * {@code ContentSyncRequestMode} class.\n */\npublic final class ContentSyncRequestModeTestCase extends LDAPSDKTestCase {\n\n /**\n * Provides test coverage for the REFRESH_ONLY mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshOnly() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_ONLY;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n ", "post_mask_code": "\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides test coverage for the REFRESH_AND_PERSIST mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshAndPersist() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_AND_PERSIST;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 3);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides general test coverage for the enum.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testGeneral() throws Exception {\n for (final ContentSyncRequestMode m : ContentSyncRequestMode.values()) {\n assertNotNull(m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(m.name());\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n try {\n ContentSyncRequestMode.valueOf(\"invalid\");\n fail(\"Expected an exception for an invalid valueOf string\");\n } catch (final Exception e) {\n // This was expected.\n }\n assertNull(ContentSyncRequestMode.valueOf(-1));\n }\n\n /**\n * Tests the {@code forName} method with automated tests based on the actual\n * name of the enum values.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testForNameAutomated() throws Exception {\n for (final ContentSyncRequestMode value : ContentSyncRequestMode.values()) {\n for (final String name : getNames(value.name())) {\n assertNotNull(ContentSyncRequestMode.forName(name));\n assertEquals(ContentSyncRequestMode.forName(name), value);\n }\n }\n assertNull(ContentSyncRequestMode.forName(\"some undefined name\"));\n }\n\n /**\n * Retrieves a set of names for testing the {@code forName} method based on\n * the provided set of names.\n *\n * @param baseNames The base set of names to use to generate the full set of\n * names. It must not be {@code null} or empty.\n *\n * @return The full set of names to use for testing.\n */\n private static Set getNames(final String... baseNames) {\n final HashSet nameSet = new HashSet<>(10);\n for (final String name : baseNames) {\n nameSet.add(name);\n nameSet.add(name.toLowerCase());\n nameSet.add(name.toUpperCase());\n final String nameWithDashesInsteadOfUnderscores = name.replace('_', '-');\n nameSet.add(nameWithDashesInsteadOfUnderscores);\n nameSet.add(nameWithDashesInsteadOfUnderscores.toLowerCase());\n nameSet.add(nameWithDashesInsteadOfUnderscores.toUpperCase());\n final String nameWithUnderscoresInsteadOfDashes = name.replace('-', '_');\n nameSet.add(nameWithUnderscoresInsteadOfDashes);\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toLowerCase());\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toUpperCase());\n final StringBuilder nameWithoutUnderscoresOrDashes = new StringBuilder();\n for (final char c : name.toCharArray()) {\n if ((c != '-') && (c != '_')) {\n nameWithoutUnderscoresOrDashes.append(c);\n }\n }\n nameSet.add(nameWithoutUnderscoresOrDashes.toString());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toLowerCase());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toUpperCase());\n }\n return nameSet;\n }\n}\n"} {"task_id": "Java_1268", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/pingidentity/ldapsdk/tests/unit/src/com/unboundid/ldap/sdk/controls/ContentSyncRequestModeTestCase.java", "mask_start_position": 922, "mask_end_position": 1051, "canonical_solution": "assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }", "pre_mask_code": "/*\n * All Rights Reserved.\n */\npackage com.unboundid.ldap.sdk.controls;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.testng.annotations.Test;\nimport com.unboundid.ldap.sdk.LDAPSDKTestCase;\n\n/**\n * This class provides a set of test cases for the\n * {@code ContentSyncRequestMode} class.\n */\npublic final class ContentSyncRequestModeTestCase extends LDAPSDKTestCase {\n\n /**\n * Provides test coverage for the REFRESH_ONLY mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshOnly() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_ONLY;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 1);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n ", "post_mask_code": "\n\n /**\n * Provides test coverage for the REFRESH_AND_PERSIST mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshAndPersist() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_AND_PERSIST;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 3);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides general test coverage for the enum.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testGeneral() throws Exception {\n for (final ContentSyncRequestMode m : ContentSyncRequestMode.values()) {\n assertNotNull(m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(m.name());\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n try {\n ContentSyncRequestMode.valueOf(\"invalid\");\n fail(\"Expected an exception for an invalid valueOf string\");\n } catch (final Exception e) {\n // This was expected.\n }\n assertNull(ContentSyncRequestMode.valueOf(-1));\n }\n\n /**\n * Tests the {@code forName} method with automated tests based on the actual\n * name of the enum values.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testForNameAutomated() throws Exception {\n for (final ContentSyncRequestMode value : ContentSyncRequestMode.values()) {\n for (final String name : getNames(value.name())) {\n assertNotNull(ContentSyncRequestMode.forName(name));\n assertEquals(ContentSyncRequestMode.forName(name), value);\n }\n }\n assertNull(ContentSyncRequestMode.forName(\"some undefined name\"));\n }\n\n /**\n * Retrieves a set of names for testing the {@code forName} method based on\n * the provided set of names.\n *\n * @param baseNames The base set of names to use to generate the full set of\n * names. It must not be {@code null} or empty.\n *\n * @return The full set of names to use for testing.\n */\n private static Set getNames(final String... baseNames) {\n final HashSet nameSet = new HashSet<>(10);\n for (final String name : baseNames) {\n nameSet.add(name);\n nameSet.add(name.toLowerCase());\n nameSet.add(name.toUpperCase());\n final String nameWithDashesInsteadOfUnderscores = name.replace('_', '-');\n nameSet.add(nameWithDashesInsteadOfUnderscores);\n nameSet.add(nameWithDashesInsteadOfUnderscores.toLowerCase());\n nameSet.add(nameWithDashesInsteadOfUnderscores.toUpperCase());\n final String nameWithUnderscoresInsteadOfDashes = name.replace('-', '_');\n nameSet.add(nameWithUnderscoresInsteadOfDashes);\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toLowerCase());\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toUpperCase());\n final StringBuilder nameWithoutUnderscoresOrDashes = new StringBuilder();\n for (final char c : name.toCharArray()) {\n if ((c != '-') && (c != '_')) {\n nameWithoutUnderscoresOrDashes.append(c);\n }\n }\n nameSet.add(nameWithoutUnderscoresOrDashes.toString());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toLowerCase());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toUpperCase());\n }\n return nameSet;\n }\n}\n"} {"task_id": "Java_1269", "language": "Java", "task_type": "single_line", "source_file": "java/github/pingidentity/ldapsdk/tests/unit/src/com/unboundid/ldap/sdk/controls/ContentSyncRequestModeTestCase.java", "mask_start_position": 620, "mask_end_position": 664, "canonical_solution": "ode m = ContentSyncRequestMode.REFRESH_ONLY;", "pre_mask_code": "/*\n * All Rights Reserved.\n */\npackage com.unboundid.ldap.sdk.controls;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.testng.annotations.Test;\nimport com.unboundid.ldap.sdk.LDAPSDKTestCase;\n\n/**\n * This class provides a set of test cases for the\n * {@code ContentSyncRequestMode} class.\n */\npublic final class ContentSyncRequestModeTestCase extends LDAPSDKTestCase {\n\n /**\n * Provides test coverage for the REFRESH_ONLY mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshOnly() throws Exception {\n final ContentSyncRequestM", "post_mask_code": "\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 1);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides test coverage for the REFRESH_AND_PERSIST mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshAndPersist() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_AND_PERSIST;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 3);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides general test coverage for the enum.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testGeneral() throws Exception {\n for (final ContentSyncRequestMode m : ContentSyncRequestMode.values()) {\n assertNotNull(m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(m.name());\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n try {\n ContentSyncRequestMode.valueOf(\"invalid\");\n fail(\"Expected an exception for an invalid valueOf string\");\n } catch (final Exception e) {\n // This was expected.\n }\n assertNull(ContentSyncRequestMode.valueOf(-1));\n }\n\n /**\n * Tests the {@code forName} method with automated tests based on the actual\n * name of the enum values.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testForNameAutomated() throws Exception {\n for (final ContentSyncRequestMode value : ContentSyncRequestMode.values()) {\n for (final String name : getNames(value.name())) {\n assertNotNull(ContentSyncRequestMode.forName(name));\n assertEquals(ContentSyncRequestMode.forName(name), value);\n }\n }\n assertNull(ContentSyncRequestMode.forName(\"some undefined name\"));\n }\n\n /**\n * Retrieves a set of names for testing the {@code forName} method based on\n * the provided set of names.\n *\n * @param baseNames The base set of names to use to generate the full set of\n * names. It must not be {@code null} or empty.\n *\n * @return The full set of names to use for testing.\n */\n private static Set getNames(final String... baseNames) {\n final HashSet nameSet = new HashSet<>(10);\n for (final String name : baseNames) {\n nameSet.add(name);\n nameSet.add(name.toLowerCase());\n nameSet.add(name.toUpperCase());\n final String nameWithDashesInsteadOfUnderscores = name.replace('_', '-');\n nameSet.add(nameWithDashesInsteadOfUnderscores);\n nameSet.add(nameWithDashesInsteadOfUnderscores.toLowerCase());\n nameSet.add(nameWithDashesInsteadOfUnderscores.toUpperCase());\n final String nameWithUnderscoresInsteadOfDashes = name.replace('-', '_');\n nameSet.add(nameWithUnderscoresInsteadOfDashes);\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toLowerCase());\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toUpperCase());\n final StringBuilder nameWithoutUnderscoresOrDashes = new StringBuilder();\n for (final char c : name.toCharArray()) {\n if ((c != '-') && (c != '_')) {\n nameWithoutUnderscoresOrDashes.append(c);\n }\n }\n nameSet.add(nameWithoutUnderscoresOrDashes.toString());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toLowerCase());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toUpperCase());\n }\n return nameSet;\n }\n}\n"} {"task_id": "Java_1270", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/pingidentity/ldapsdk/tests/unit/src/com/unboundid/ldap/sdk/controls/ContentSyncRequestModeTestCase.java", "mask_start_position": 2873, "mask_end_position": 3335, "canonical_solution": "@Test()\n public void testForNameAutomated() throws Exception {\n for (final ContentSyncRequestMode value : ContentSyncRequestMode.values()) {\n for (final String name : getNames(value.name())) {\n assertNotNull(ContentSyncRequestMode.forName(name));\n assertEquals(ContentSyncRequestMode.forName(name), value);\n }\n }\n assertNull(ContentSyncRequestMode.forName(\"some undefined name\"));\n }", "pre_mask_code": "/*\n * All Rights Reserved.\n */\npackage com.unboundid.ldap.sdk.controls;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.testng.annotations.Test;\nimport com.unboundid.ldap.sdk.LDAPSDKTestCase;\n\n/**\n * This class provides a set of test cases for the\n * {@code ContentSyncRequestMode} class.\n */\npublic final class ContentSyncRequestModeTestCase extends LDAPSDKTestCase {\n\n /**\n * Provides test coverage for the REFRESH_ONLY mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshOnly() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_ONLY;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 1);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides test coverage for the REFRESH_AND_PERSIST mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshAndPersist() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_AND_PERSIST;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 3);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides general test coverage for the enum.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testGeneral() throws Exception {\n for (final ContentSyncRequestMode m : ContentSyncRequestMode.values()) {\n assertNotNull(m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(m.name());\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n try {\n ContentSyncRequestMode.valueOf(\"invalid\");\n fail(\"Expected an exception for an invalid valueOf string\");\n } catch (final Exception e) {\n // This was expected.\n }\n assertNull(ContentSyncRequestMode.valueOf(-1));\n }\n\n /**\n * Tests the {@code forName} method with automated tests based on the actual\n * name of the enum values.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n ", "post_mask_code": "\n\n /**\n * Retrieves a set of names for testing the {@code forName} method based on\n * the provided set of names.\n *\n * @param baseNames The base set of names to use to generate the full set of\n * names. It must not be {@code null} or empty.\n *\n * @return The full set of names to use for testing.\n */\n private static Set getNames(final String... baseNames) {\n final HashSet nameSet = new HashSet<>(10);\n for (final String name : baseNames) {\n nameSet.add(name);\n nameSet.add(name.toLowerCase());\n nameSet.add(name.toUpperCase());\n final String nameWithDashesInsteadOfUnderscores = name.replace('_', '-');\n nameSet.add(nameWithDashesInsteadOfUnderscores);\n nameSet.add(nameWithDashesInsteadOfUnderscores.toLowerCase());\n nameSet.add(nameWithDashesInsteadOfUnderscores.toUpperCase());\n final String nameWithUnderscoresInsteadOfDashes = name.replace('-', '_');\n nameSet.add(nameWithUnderscoresInsteadOfDashes);\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toLowerCase());\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toUpperCase());\n final StringBuilder nameWithoutUnderscoresOrDashes = new StringBuilder();\n for (final char c : name.toCharArray()) {\n if ((c != '-') && (c != '_')) {\n nameWithoutUnderscoresOrDashes.append(c);\n }\n }\n nameSet.add(nameWithoutUnderscoresOrDashes.toString());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toLowerCase());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toUpperCase());\n }\n return nameSet;\n }\n}\n"} {"task_id": "Java_1271", "language": "Java", "task_type": "if_statement", "source_file": "java/github/pingidentity/ldapsdk/tests/unit/src/com/unboundid/ldap/sdk/controls/ContentSyncRequestModeTestCase.java", "mask_start_position": 4739, "mask_end_position": 4850, "canonical_solution": "if ((c != '-') && (c != '_')) {\n nameWithoutUnderscoresOrDashes.append(c);\n }", "pre_mask_code": "/*\n * All Rights Reserved.\n */\npackage com.unboundid.ldap.sdk.controls;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.testng.annotations.Test;\nimport com.unboundid.ldap.sdk.LDAPSDKTestCase;\n\n/**\n * This class provides a set of test cases for the\n * {@code ContentSyncRequestMode} class.\n */\npublic final class ContentSyncRequestModeTestCase extends LDAPSDKTestCase {\n\n /**\n * Provides test coverage for the REFRESH_ONLY mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshOnly() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_ONLY;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 1);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides test coverage for the REFRESH_AND_PERSIST mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshAndPersist() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_AND_PERSIST;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 3);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides general test coverage for the enum.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testGeneral() throws Exception {\n for (final ContentSyncRequestMode m : ContentSyncRequestMode.values()) {\n assertNotNull(m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(m.name());\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n try {\n ContentSyncRequestMode.valueOf(\"invalid\");\n fail(\"Expected an exception for an invalid valueOf string\");\n } catch (final Exception e) {\n // This was expected.\n }\n assertNull(ContentSyncRequestMode.valueOf(-1));\n }\n\n /**\n * Tests the {@code forName} method with automated tests based on the actual\n * name of the enum values.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testForNameAutomated() throws Exception {\n for (final ContentSyncRequestMode value : ContentSyncRequestMode.values()) {\n for (final String name : getNames(value.name())) {\n assertNotNull(ContentSyncRequestMode.forName(name));\n assertEquals(ContentSyncRequestMode.forName(name), value);\n }\n }\n assertNull(ContentSyncRequestMode.forName(\"some undefined name\"));\n }\n\n /**\n * Retrieves a set of names for testing the {@code forName} method based on\n * the provided set of names.\n *\n * @param baseNames The base set of names to use to generate the full set of\n * names. It must not be {@code null} or empty.\n *\n * @return The full set of names to use for testing.\n */\n private static Set getNames(final String... baseNames) {\n final HashSet nameSet = new HashSet<>(10);\n for (final String name : baseNames) {\n nameSet.add(name);\n nameSet.add(name.toLowerCase());\n nameSet.add(name.toUpperCase());\n final String nameWithDashesInsteadOfUnderscores = name.replace('_', '-');\n nameSet.add(nameWithDashesInsteadOfUnderscores);\n nameSet.add(nameWithDashesInsteadOfUnderscores.toLowerCase());\n nameSet.add(nameWithDashesInsteadOfUnderscores.toUpperCase());\n final String nameWithUnderscoresInsteadOfDashes = name.replace('-', '_');\n nameSet.add(nameWithUnderscoresInsteadOfDashes);\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toLowerCase());\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toUpperCase());\n final StringBuilder nameWithoutUnderscoresOrDashes = new StringBuilder();\n for (final char c : name.toCharArray()) {\n ", "post_mask_code": "\n }\n nameSet.add(nameWithoutUnderscoresOrDashes.toString());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toLowerCase());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toUpperCase());\n }\n return nameSet;\n }\n}\n"} {"task_id": "Java_1272", "language": "Java", "task_type": "try_statement", "source_file": "java/github/pingidentity/ldapsdk/tests/unit/src/com/unboundid/ldap/sdk/controls/ContentSyncRequestModeTestCase.java", "mask_start_position": 2394, "mask_end_position": 2609, "canonical_solution": "try {\n ContentSyncRequestMode.valueOf(\"invalid\");\n fail(\"Expected an exception for an invalid valueOf string\");\n } catch (final Exception e) {\n // This was expected.\n }", "pre_mask_code": "/*\n * All Rights Reserved.\n */\npackage com.unboundid.ldap.sdk.controls;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.testng.annotations.Test;\nimport com.unboundid.ldap.sdk.LDAPSDKTestCase;\n\n/**\n * This class provides a set of test cases for the\n * {@code ContentSyncRequestMode} class.\n */\npublic final class ContentSyncRequestModeTestCase extends LDAPSDKTestCase {\n\n /**\n * Provides test coverage for the REFRESH_ONLY mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshOnly() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_ONLY;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 1);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides test coverage for the REFRESH_AND_PERSIST mode.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testRefreshAndPersist() throws Exception {\n final ContentSyncRequestMode m = ContentSyncRequestMode.REFRESH_AND_PERSIST;\n assertNotNull(m.name());\n assertNotNull(m.toString());\n assertEquals(m.intValue(), 3);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n\n /**\n * Provides general test coverage for the enum.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testGeneral() throws Exception {\n for (final ContentSyncRequestMode m : ContentSyncRequestMode.values()) {\n assertNotNull(m);\n assertNotNull(ContentSyncRequestMode.valueOf(m.intValue()));\n assertEquals(ContentSyncRequestMode.valueOf(m.intValue()), m);\n assertNotNull(m.name());\n assertNotNull(ContentSyncRequestMode.valueOf(m.name()));\n assertEquals(ContentSyncRequestMode.valueOf(m.name()), m);\n }\n ", "post_mask_code": "\n assertNull(ContentSyncRequestMode.valueOf(-1));\n }\n\n /**\n * Tests the {@code forName} method with automated tests based on the actual\n * name of the enum values.\n *\n * @throws Exception If an unexpected problem occurs.\n */\n @Test()\n public void testForNameAutomated() throws Exception {\n for (final ContentSyncRequestMode value : ContentSyncRequestMode.values()) {\n for (final String name : getNames(value.name())) {\n assertNotNull(ContentSyncRequestMode.forName(name));\n assertEquals(ContentSyncRequestMode.forName(name), value);\n }\n }\n assertNull(ContentSyncRequestMode.forName(\"some undefined name\"));\n }\n\n /**\n * Retrieves a set of names for testing the {@code forName} method based on\n * the provided set of names.\n *\n * @param baseNames The base set of names to use to generate the full set of\n * names. It must not be {@code null} or empty.\n *\n * @return The full set of names to use for testing.\n */\n private static Set getNames(final String... baseNames) {\n final HashSet nameSet = new HashSet<>(10);\n for (final String name : baseNames) {\n nameSet.add(name);\n nameSet.add(name.toLowerCase());\n nameSet.add(name.toUpperCase());\n final String nameWithDashesInsteadOfUnderscores = name.replace('_', '-');\n nameSet.add(nameWithDashesInsteadOfUnderscores);\n nameSet.add(nameWithDashesInsteadOfUnderscores.toLowerCase());\n nameSet.add(nameWithDashesInsteadOfUnderscores.toUpperCase());\n final String nameWithUnderscoresInsteadOfDashes = name.replace('-', '_');\n nameSet.add(nameWithUnderscoresInsteadOfDashes);\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toLowerCase());\n nameSet.add(nameWithUnderscoresInsteadOfDashes.toUpperCase());\n final StringBuilder nameWithoutUnderscoresOrDashes = new StringBuilder();\n for (final char c : name.toCharArray()) {\n if ((c != '-') && (c != '_')) {\n nameWithoutUnderscoresOrDashes.append(c);\n }\n }\n nameSet.add(nameWithoutUnderscoresOrDashes.toString());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toLowerCase());\n nameSet.add(nameWithoutUnderscoresOrDashes.toString().toUpperCase());\n }\n return nameSet;\n }\n}\n"} {"task_id": "Java_1273", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/skywalking-java/apm-sniffer/apm-sdk-plugin/shardingsphere-plugins/sharding-sphere-4.1.0-plugin/src/main/java/org/apache/skywalking/apm/plugin/shardingsphere/v41/define/JDBCRootInvokeInstrumentation.java", "mask_start_position": 1454, "mask_end_position": 1514, "canonical_solution": "@Override\n public String getMethodsInterceptor() ", "pre_mask_code": "package org.apache.skywalking.apm.plugin.shardingsphere.v41.define;\n\nimport net.bytebuddy.description.method.MethodDescription;\nimport net.bytebuddy.matcher.ElementMatcher;\nimport org.apache.skywalking.apm.agent.core.plugin.interceptor.ConstructorInterceptPoint;\nimport org.apache.skywalking.apm.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint;\nimport org.apache.skywalking.apm.agent.core.plugin.match.ClassMatch;\nimport org.apache.skywalking.apm.agent.core.plugin.match.NameMatch;\nimport static net.bytebuddy.matcher.ElementMatchers.named;\n\n/**\n * {@link JDBCRootInvokeInstrumentation} presents that skywalking intercepts. {@link org.apache.shardingsphere.shardingjdbc.executor.AbstractStatementExecutor}.\n */\npublic class JDBCRootInvokeInstrumentation extends AbstractShardingSphere41Instrumentation {\n\n private static final String ENHANCE_CLASS = \"org.apache.shardingsphere.shardingjdbc.executor.AbstractStatementExecutor\";\n\n private static final String JDBC_ROOT_INVOKE_INTERCEPTOR_CLASS = \"org.apache.skywalking.apm.plugin.shardingsphere.v41.JDBCRootInvokeInterceptor\";\n\n @Override\n public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {\n return new InstanceMethodsInterceptPoint[] { new InstanceMethodsInterceptPoint() {\n\n @Override\n public ElementMatcher getMethodsMatcher() {\n return named(\"executeCallback\");\n }\n\n ", "post_mask_code": "{\n return JDBC_ROOT_INVOKE_INTERCEPTOR_CLASS;\n }\n\n @Override\n public boolean isOverrideArgs() {\n return false;\n }\n } };\n }\n\n @Override\n public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {\n return new ConstructorInterceptPoint[0];\n }\n\n @Override\n protected ClassMatch enhanceClass() {\n return NameMatch.byName(ENHANCE_CLASS);\n }\n}\n"} {"task_id": "Java_1274", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/skywalking-java/apm-sniffer/apm-sdk-plugin/shardingsphere-plugins/sharding-sphere-4.1.0-plugin/src/main/java/org/apache/skywalking/apm/plugin/shardingsphere/v41/define/JDBCRootInvokeInstrumentation.java", "mask_start_position": 1920, "mask_end_position": 1975, "canonical_solution": "{\n return NameMatch.byName(ENHANCE_CLASS);\n }", "pre_mask_code": "package org.apache.skywalking.apm.plugin.shardingsphere.v41.define;\n\nimport net.bytebuddy.description.method.MethodDescription;\nimport net.bytebuddy.matcher.ElementMatcher;\nimport org.apache.skywalking.apm.agent.core.plugin.interceptor.ConstructorInterceptPoint;\nimport org.apache.skywalking.apm.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint;\nimport org.apache.skywalking.apm.agent.core.plugin.match.ClassMatch;\nimport org.apache.skywalking.apm.agent.core.plugin.match.NameMatch;\nimport static net.bytebuddy.matcher.ElementMatchers.named;\n\n/**\n * {@link JDBCRootInvokeInstrumentation} presents that skywalking intercepts. {@link org.apache.shardingsphere.shardingjdbc.executor.AbstractStatementExecutor}.\n */\npublic class JDBCRootInvokeInstrumentation extends AbstractShardingSphere41Instrumentation {\n\n private static final String ENHANCE_CLASS = \"org.apache.shardingsphere.shardingjdbc.executor.AbstractStatementExecutor\";\n\n private static final String JDBC_ROOT_INVOKE_INTERCEPTOR_CLASS = \"org.apache.skywalking.apm.plugin.shardingsphere.v41.JDBCRootInvokeInterceptor\";\n\n @Override\n public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {\n return new InstanceMethodsInterceptPoint[] { new InstanceMethodsInterceptPoint() {\n\n @Override\n public ElementMatcher getMethodsMatcher() {\n return named(\"executeCallback\");\n }\n\n @Override\n public String getMethodsInterceptor() {\n return JDBC_ROOT_INVOKE_INTERCEPTOR_CLASS;\n }\n\n @Override\n public boolean isOverrideArgs() {\n return false;\n }\n } };\n }\n\n @Override\n public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {\n return new ConstructorInterceptPoint[0];\n }\n\n @Override\n protected ClassMatch enhanceClass() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1275", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/skywalking-java/apm-sniffer/apm-sdk-plugin/shardingsphere-plugins/sharding-sphere-4.1.0-plugin/src/main/java/org/apache/skywalking/apm/plugin/shardingsphere/v41/define/JDBCRootInvokeInstrumentation.java", "mask_start_position": 1188, "mask_end_position": 1188, "canonical_solution": "", "pre_mask_code": "package org.apache.skywalking.apm.plugin.shardingsphere.v41.define;\n\nimport net.bytebuddy.description.method.MethodDescription;\nimport net.bytebuddy.matcher.ElementMatcher;\nimport org.apache.skywalking.apm.agent.core.plugin.interceptor.ConstructorInterceptPoint;\nimport org.apache.skywalking.apm.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint;\nimport org.apache.skywalking.apm.agent.core.plugin.match.ClassMatch;\nimport org.apache.skywalking.apm.agent.core.plugin.match.NameMatch;\nimport static net.bytebuddy.matcher.ElementMatchers.named;\n\n/**\n * {@link JDBCRootInvokeInstrumentation} presents that skywalking intercepts. {@link org.apache.shardingsphere.shardingjdbc.executor.AbstractStatementExecutor}.\n */\npublic class JDBCRootInvokeInstrumentation extends AbstractShardingSphere41Instrumentation {\n\n private static final String ENHANCE_CLASS = \"org.apache.shardingsphere.shardingjdbc.executor.AbstractStatementExecutor\";\n\n private static final String JDBC_ROOT_INVOKE_INTERCEPTOR_CLASS = \"org.apache.skywalking.apm.plugin.shardingsphere.v41.JDBCRootInvokeInterceptor\";\n\n @Override\n public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {", "post_mask_code": "\n return new InstanceMethodsInterceptPoint[] { new InstanceMethodsInterceptPoint() {\n\n @Override\n public ElementMatcher getMethodsMatcher() {\n return named(\"executeCallback\");\n }\n\n @Override\n public String getMethodsInterceptor() {\n return JDBC_ROOT_INVOKE_INTERCEPTOR_CLASS;\n }\n\n @Override\n public boolean isOverrideArgs() {\n return false;\n }\n } };\n }\n\n @Override\n public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {\n return new ConstructorInterceptPoint[0];\n }\n\n @Override\n protected ClassMatch enhanceClass() {\n return NameMatch.byName(ENHANCE_CLASS);\n }\n}\n"} {"task_id": "Java_1276", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/skywalking-java/apm-sniffer/apm-sdk-plugin/shardingsphere-plugins/sharding-sphere-4.1.0-plugin/src/main/java/org/apache/skywalking/apm/plugin/shardingsphere/v41/define/JDBCRootInvokeInstrumentation.java", "mask_start_position": 1197, "mask_end_position": 1714, "canonical_solution": "return new InstanceMethodsInterceptPoint[] { new InstanceMethodsInterceptPoint() {\n\n @Override\n public ElementMatcher getMethodsMatcher() {\n return named(\"executeCallback\");\n }\n\n @Override\n public String getMethodsInterceptor() {\n return JDBC_ROOT_INVOKE_INTERCEPTOR_CLASS;\n }\n\n @Override\n public boolean isOverrideArgs() {\n return false;\n }\n } };", "pre_mask_code": "package org.apache.skywalking.apm.plugin.shardingsphere.v41.define;\n\nimport net.bytebuddy.description.method.MethodDescription;\nimport net.bytebuddy.matcher.ElementMatcher;\nimport org.apache.skywalking.apm.agent.core.plugin.interceptor.ConstructorInterceptPoint;\nimport org.apache.skywalking.apm.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint;\nimport org.apache.skywalking.apm.agent.core.plugin.match.ClassMatch;\nimport org.apache.skywalking.apm.agent.core.plugin.match.NameMatch;\nimport static net.bytebuddy.matcher.ElementMatchers.named;\n\n/**\n * {@link JDBCRootInvokeInstrumentation} presents that skywalking intercepts. {@link org.apache.shardingsphere.shardingjdbc.executor.AbstractStatementExecutor}.\n */\npublic class JDBCRootInvokeInstrumentation extends AbstractShardingSphere41Instrumentation {\n\n private static final String ENHANCE_CLASS = \"org.apache.shardingsphere.shardingjdbc.executor.AbstractStatementExecutor\";\n\n private static final String JDBC_ROOT_INVOKE_INTERCEPTOR_CLASS = \"org.apache.skywalking.apm.plugin.shardingsphere.v41.JDBCRootInvokeInterceptor\";\n\n @Override\n public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {\n ", "post_mask_code": "\n }\n\n @Override\n public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {\n return new ConstructorInterceptPoint[0];\n }\n\n @Override\n protected ClassMatch enhanceClass() {\n return NameMatch.byName(ENHANCE_CLASS);\n }\n}\n"} {"task_id": "Java_1277", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/skywalking-java/apm-sniffer/apm-sdk-plugin/shardingsphere-plugins/sharding-sphere-4.1.0-plugin/src/main/java/org/apache/skywalking/apm/plugin/shardingsphere/v41/define/JDBCRootInvokeInstrumentation.java", "mask_start_position": 1719, "mask_end_position": 1720, "canonical_solution": "}", "pre_mask_code": "package org.apache.skywalking.apm.plugin.shardingsphere.v41.define;\n\nimport net.bytebuddy.description.method.MethodDescription;\nimport net.bytebuddy.matcher.ElementMatcher;\nimport org.apache.skywalking.apm.agent.core.plugin.interceptor.ConstructorInterceptPoint;\nimport org.apache.skywalking.apm.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint;\nimport org.apache.skywalking.apm.agent.core.plugin.match.ClassMatch;\nimport org.apache.skywalking.apm.agent.core.plugin.match.NameMatch;\nimport static net.bytebuddy.matcher.ElementMatchers.named;\n\n/**\n * {@link JDBCRootInvokeInstrumentation} presents that skywalking intercepts. {@link org.apache.shardingsphere.shardingjdbc.executor.AbstractStatementExecutor}.\n */\npublic class JDBCRootInvokeInstrumentation extends AbstractShardingSphere41Instrumentation {\n\n private static final String ENHANCE_CLASS = \"org.apache.shardingsphere.shardingjdbc.executor.AbstractStatementExecutor\";\n\n private static final String JDBC_ROOT_INVOKE_INTERCEPTOR_CLASS = \"org.apache.skywalking.apm.plugin.shardingsphere.v41.JDBCRootInvokeInterceptor\";\n\n @Override\n public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {\n return new InstanceMethodsInterceptPoint[] { new InstanceMethodsInterceptPoint() {\n\n @Override\n public ElementMatcher getMethodsMatcher() {\n return named(\"executeCallback\");\n }\n\n @Override\n public String getMethodsInterceptor() {\n return JDBC_ROOT_INVOKE_INTERCEPTOR_CLASS;\n }\n\n @Override\n public boolean isOverrideArgs() {\n return false;\n }\n } };\n ", "post_mask_code": "\n\n @Override\n public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {\n return new ConstructorInterceptPoint[0];\n }\n\n @Override\n protected ClassMatch enhanceClass() {\n return NameMatch.byName(ENHANCE_CLASS);\n }\n}\n"} {"task_id": "Java_1278", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/skywalking-java/apm-sniffer/apm-sdk-plugin/shardingsphere-plugins/sharding-sphere-4.1.0-plugin/src/main/java/org/apache/skywalking/apm/plugin/shardingsphere/v41/define/JDBCRootInvokeInstrumentation.java", "mask_start_position": 1937, "mask_end_position": 1969, "canonical_solution": "NameMatch.byName(ENHANCE_CLASS);", "pre_mask_code": "package org.apache.skywalking.apm.plugin.shardingsphere.v41.define;\n\nimport net.bytebuddy.description.method.MethodDescription;\nimport net.bytebuddy.matcher.ElementMatcher;\nimport org.apache.skywalking.apm.agent.core.plugin.interceptor.ConstructorInterceptPoint;\nimport org.apache.skywalking.apm.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint;\nimport org.apache.skywalking.apm.agent.core.plugin.match.ClassMatch;\nimport org.apache.skywalking.apm.agent.core.plugin.match.NameMatch;\nimport static net.bytebuddy.matcher.ElementMatchers.named;\n\n/**\n * {@link JDBCRootInvokeInstrumentation} presents that skywalking intercepts. {@link org.apache.shardingsphere.shardingjdbc.executor.AbstractStatementExecutor}.\n */\npublic class JDBCRootInvokeInstrumentation extends AbstractShardingSphere41Instrumentation {\n\n private static final String ENHANCE_CLASS = \"org.apache.shardingsphere.shardingjdbc.executor.AbstractStatementExecutor\";\n\n private static final String JDBC_ROOT_INVOKE_INTERCEPTOR_CLASS = \"org.apache.skywalking.apm.plugin.shardingsphere.v41.JDBCRootInvokeInterceptor\";\n\n @Override\n public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {\n return new InstanceMethodsInterceptPoint[] { new InstanceMethodsInterceptPoint() {\n\n @Override\n public ElementMatcher getMethodsMatcher() {\n return named(\"executeCallback\");\n }\n\n @Override\n public String getMethodsInterceptor() {\n return JDBC_ROOT_INVOKE_INTERCEPTOR_CLASS;\n }\n\n @Override\n public boolean isOverrideArgs() {\n return false;\n }\n } };\n }\n\n @Override\n public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {\n return new ConstructorInterceptPoint[0];\n }\n\n @Override\n protected ClassMatch enhanceClass() {\n return ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1279", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openjdk/jdk/src/utils/IdealGraphVisualizer/Coordinator/src/main/java/com/sun/hotspot/igv/coordinator/actions/SaveAsAction.java", "mask_start_position": 2623, "mask_end_position": 2676, "canonical_solution": "@Override\n protected boolean enable(Node[] nodes) ", "pre_mask_code": "package com.sun.hotspot.igv.coordinator.actions;\n\nimport com.sun.hotspot.igv.data.GraphDocument;\nimport com.sun.hotspot.igv.data.Group;\nimport com.sun.hotspot.igv.data.serialization.Printer;\nimport com.sun.hotspot.igv.settings.Settings;\nimport java.io.*;\nimport javax.swing.Action;\nimport javax.swing.JFileChooser;\nimport org.openide.nodes.Node;\nimport org.openide.util.HelpCtx;\nimport org.openide.util.NbBundle;\nimport org.openide.util.actions.CookieAction;\nimport org.openide.util.actions.NodeAction;\n\n/**\n * @author Thomas Wuerthinger\n */\npublic final class SaveAsAction extends NodeAction {\n\n public SaveAsAction() {\n putValue(Action.SHORT_DESCRIPTION, \"Save selected groups to XML file...\");\n }\n\n @Override\n protected void performAction(Node[] activatedNodes) {\n GraphDocument doc = new GraphDocument();\n for (Node n : activatedNodes) {\n Group group = n.getLookup().lookup(Group.class);\n doc.addElement(group);\n }\n save(doc);\n }\n\n public static void save(GraphDocument doc) {\n JFileChooser fc = new JFileChooser();\n fc.setFileFilter(ImportAction.getFileFilter());\n fc.setCurrentDirectory(new File(Settings.get().get(Settings.DIRECTORY, Settings.DIRECTORY_DEFAULT)));\n if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {\n File file = fc.getSelectedFile();\n if (!file.getName().contains(\".\")) {\n file = new File(file.getAbsolutePath() + \".xml\");\n }\n File dir = file;\n if (!dir.isDirectory()) {\n dir = dir.getParentFile();\n }\n Settings.get().put(Settings.DIRECTORY, dir.getAbsolutePath());\n try {\n try (Writer writer = new OutputStreamWriter(new FileOutputStream(file))) {\n Printer p = new Printer();\n p.export(writer, doc);\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n protected int mode() {\n return CookieAction.MODE_SOME;\n }\n\n @Override\n public String getName() {\n return NbBundle.getMessage(SaveAsAction.class, \"CTL_SaveAsAction\");\n }\n\n @Override\n protected String iconResource() {\n return \"com/sun/hotspot/igv/coordinator/images/save.png\";\n }\n\n @Override\n public HelpCtx getHelpCtx() {\n return HelpCtx.DEFAULT_HELP;\n }\n\n @Override\n protected boolean asynchronous() {\n return false;\n }\n\n ", "post_mask_code": "{\n int cnt = 0;\n for (Node n : nodes) {\n cnt += n.getLookup().lookupAll(Group.class).size();\n }\n return cnt > 0;\n }\n}\n"} {"task_id": "Java_1280", "language": "Java", "task_type": "method_body", "source_file": "java/github/openjdk/jdk/src/utils/IdealGraphVisualizer/Coordinator/src/main/java/com/sun/hotspot/igv/coordinator/actions/SaveAsAction.java", "mask_start_position": 2235, "mask_end_position": 2318, "canonical_solution": "{\n return NbBundle.getMessage(SaveAsAction.class, \"CTL_SaveAsAction\");\n }", "pre_mask_code": "package com.sun.hotspot.igv.coordinator.actions;\n\nimport com.sun.hotspot.igv.data.GraphDocument;\nimport com.sun.hotspot.igv.data.Group;\nimport com.sun.hotspot.igv.data.serialization.Printer;\nimport com.sun.hotspot.igv.settings.Settings;\nimport java.io.*;\nimport javax.swing.Action;\nimport javax.swing.JFileChooser;\nimport org.openide.nodes.Node;\nimport org.openide.util.HelpCtx;\nimport org.openide.util.NbBundle;\nimport org.openide.util.actions.CookieAction;\nimport org.openide.util.actions.NodeAction;\n\n/**\n * @author Thomas Wuerthinger\n */\npublic final class SaveAsAction extends NodeAction {\n\n public SaveAsAction() {\n putValue(Action.SHORT_DESCRIPTION, \"Save selected groups to XML file...\");\n }\n\n @Override\n protected void performAction(Node[] activatedNodes) {\n GraphDocument doc = new GraphDocument();\n for (Node n : activatedNodes) {\n Group group = n.getLookup().lookup(Group.class);\n doc.addElement(group);\n }\n save(doc);\n }\n\n public static void save(GraphDocument doc) {\n JFileChooser fc = new JFileChooser();\n fc.setFileFilter(ImportAction.getFileFilter());\n fc.setCurrentDirectory(new File(Settings.get().get(Settings.DIRECTORY, Settings.DIRECTORY_DEFAULT)));\n if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {\n File file = fc.getSelectedFile();\n if (!file.getName().contains(\".\")) {\n file = new File(file.getAbsolutePath() + \".xml\");\n }\n File dir = file;\n if (!dir.isDirectory()) {\n dir = dir.getParentFile();\n }\n Settings.get().put(Settings.DIRECTORY, dir.getAbsolutePath());\n try {\n try (Writer writer = new OutputStreamWriter(new FileOutputStream(file))) {\n Printer p = new Printer();\n p.export(writer, doc);\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n protected int mode() {\n return CookieAction.MODE_SOME;\n }\n\n @Override\n public String getName() ", "post_mask_code": "\n\n @Override\n protected String iconResource() {\n return \"com/sun/hotspot/igv/coordinator/images/save.png\";\n }\n\n @Override\n public HelpCtx getHelpCtx() {\n return HelpCtx.DEFAULT_HELP;\n }\n\n @Override\n protected boolean asynchronous() {\n return false;\n }\n\n @Override\n protected boolean enable(Node[] nodes) {\n int cnt = 0;\n for (Node n : nodes) {\n cnt += n.getLookup().lookupAll(Group.class).size();\n }\n return cnt > 0;\n }\n}\n"} {"task_id": "Java_1281", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/openjdk/jdk/src/utils/IdealGraphVisualizer/Coordinator/src/main/java/com/sun/hotspot/igv/coordinator/actions/SaveAsAction.java", "mask_start_position": 785, "mask_end_position": 834, "canonical_solution": "\n GraphDocument doc = new GraphDocument();", "pre_mask_code": "package com.sun.hotspot.igv.coordinator.actions;\n\nimport com.sun.hotspot.igv.data.GraphDocument;\nimport com.sun.hotspot.igv.data.Group;\nimport com.sun.hotspot.igv.data.serialization.Printer;\nimport com.sun.hotspot.igv.settings.Settings;\nimport java.io.*;\nimport javax.swing.Action;\nimport javax.swing.JFileChooser;\nimport org.openide.nodes.Node;\nimport org.openide.util.HelpCtx;\nimport org.openide.util.NbBundle;\nimport org.openide.util.actions.CookieAction;\nimport org.openide.util.actions.NodeAction;\n\n/**\n * @author Thomas Wuerthinger\n */\npublic final class SaveAsAction extends NodeAction {\n\n public SaveAsAction() {\n putValue(Action.SHORT_DESCRIPTION, \"Save selected groups to XML file...\");\n }\n\n @Override\n protected void performAction(Node[] activatedNodes) {", "post_mask_code": "\n for (Node n : activatedNodes) {\n Group group = n.getLookup().lookup(Group.class);\n doc.addElement(group);\n }\n save(doc);\n }\n\n public static void save(GraphDocument doc) {\n JFileChooser fc = new JFileChooser();\n fc.setFileFilter(ImportAction.getFileFilter());\n fc.setCurrentDirectory(new File(Settings.get().get(Settings.DIRECTORY, Settings.DIRECTORY_DEFAULT)));\n if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {\n File file = fc.getSelectedFile();\n if (!file.getName().contains(\".\")) {\n file = new File(file.getAbsolutePath() + \".xml\");\n }\n File dir = file;\n if (!dir.isDirectory()) {\n dir = dir.getParentFile();\n }\n Settings.get().put(Settings.DIRECTORY, dir.getAbsolutePath());\n try {\n try (Writer writer = new OutputStreamWriter(new FileOutputStream(file))) {\n Printer p = new Printer();\n p.export(writer, doc);\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n protected int mode() {\n return CookieAction.MODE_SOME;\n }\n\n @Override\n public String getName() {\n return NbBundle.getMessage(SaveAsAction.class, \"CTL_SaveAsAction\");\n }\n\n @Override\n protected String iconResource() {\n return \"com/sun/hotspot/igv/coordinator/images/save.png\";\n }\n\n @Override\n public HelpCtx getHelpCtx() {\n return HelpCtx.DEFAULT_HELP;\n }\n\n @Override\n protected boolean asynchronous() {\n return false;\n }\n\n @Override\n protected boolean enable(Node[] nodes) {\n int cnt = 0;\n for (Node n : nodes) {\n cnt += n.getLookup().lookupAll(Group.class).size();\n }\n return cnt > 0;\n }\n}\n"} {"task_id": "Java_1282", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/openjdk/jdk/src/utils/IdealGraphVisualizer/Coordinator/src/main/java/com/sun/hotspot/igv/coordinator/actions/SaveAsAction.java", "mask_start_position": 843, "mask_end_position": 980, "canonical_solution": "for (Node n : activatedNodes) {\n Group group = n.getLookup().lookup(Group.class);\n doc.addElement(group);\n }", "pre_mask_code": "package com.sun.hotspot.igv.coordinator.actions;\n\nimport com.sun.hotspot.igv.data.GraphDocument;\nimport com.sun.hotspot.igv.data.Group;\nimport com.sun.hotspot.igv.data.serialization.Printer;\nimport com.sun.hotspot.igv.settings.Settings;\nimport java.io.*;\nimport javax.swing.Action;\nimport javax.swing.JFileChooser;\nimport org.openide.nodes.Node;\nimport org.openide.util.HelpCtx;\nimport org.openide.util.NbBundle;\nimport org.openide.util.actions.CookieAction;\nimport org.openide.util.actions.NodeAction;\n\n/**\n * @author Thomas Wuerthinger\n */\npublic final class SaveAsAction extends NodeAction {\n\n public SaveAsAction() {\n putValue(Action.SHORT_DESCRIPTION, \"Save selected groups to XML file...\");\n }\n\n @Override\n protected void performAction(Node[] activatedNodes) {\n GraphDocument doc = new GraphDocument();\n ", "post_mask_code": "\n save(doc);\n }\n\n public static void save(GraphDocument doc) {\n JFileChooser fc = new JFileChooser();\n fc.setFileFilter(ImportAction.getFileFilter());\n fc.setCurrentDirectory(new File(Settings.get().get(Settings.DIRECTORY, Settings.DIRECTORY_DEFAULT)));\n if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {\n File file = fc.getSelectedFile();\n if (!file.getName().contains(\".\")) {\n file = new File(file.getAbsolutePath() + \".xml\");\n }\n File dir = file;\n if (!dir.isDirectory()) {\n dir = dir.getParentFile();\n }\n Settings.get().put(Settings.DIRECTORY, dir.getAbsolutePath());\n try {\n try (Writer writer = new OutputStreamWriter(new FileOutputStream(file))) {\n Printer p = new Printer();\n p.export(writer, doc);\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n protected int mode() {\n return CookieAction.MODE_SOME;\n }\n\n @Override\n public String getName() {\n return NbBundle.getMessage(SaveAsAction.class, \"CTL_SaveAsAction\");\n }\n\n @Override\n protected String iconResource() {\n return \"com/sun/hotspot/igv/coordinator/images/save.png\";\n }\n\n @Override\n public HelpCtx getHelpCtx() {\n return HelpCtx.DEFAULT_HELP;\n }\n\n @Override\n protected boolean asynchronous() {\n return false;\n }\n\n @Override\n protected boolean enable(Node[] nodes) {\n int cnt = 0;\n for (Node n : nodes) {\n cnt += n.getLookup().lookupAll(Group.class).size();\n }\n return cnt > 0;\n }\n}\n"} {"task_id": "Java_1283", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/openjdk/jdk/src/utils/IdealGraphVisualizer/Coordinator/src/main/java/com/sun/hotspot/igv/coordinator/actions/SaveAsAction.java", "mask_start_position": 989, "mask_end_position": 1005, "canonical_solution": "save(doc);\n }", "pre_mask_code": "package com.sun.hotspot.igv.coordinator.actions;\n\nimport com.sun.hotspot.igv.data.GraphDocument;\nimport com.sun.hotspot.igv.data.Group;\nimport com.sun.hotspot.igv.data.serialization.Printer;\nimport com.sun.hotspot.igv.settings.Settings;\nimport java.io.*;\nimport javax.swing.Action;\nimport javax.swing.JFileChooser;\nimport org.openide.nodes.Node;\nimport org.openide.util.HelpCtx;\nimport org.openide.util.NbBundle;\nimport org.openide.util.actions.CookieAction;\nimport org.openide.util.actions.NodeAction;\n\n/**\n * @author Thomas Wuerthinger\n */\npublic final class SaveAsAction extends NodeAction {\n\n public SaveAsAction() {\n putValue(Action.SHORT_DESCRIPTION, \"Save selected groups to XML file...\");\n }\n\n @Override\n protected void performAction(Node[] activatedNodes) {\n GraphDocument doc = new GraphDocument();\n for (Node n : activatedNodes) {\n Group group = n.getLookup().lookup(Group.class);\n doc.addElement(group);\n }\n ", "post_mask_code": "\n\n public static void save(GraphDocument doc) {\n JFileChooser fc = new JFileChooser();\n fc.setFileFilter(ImportAction.getFileFilter());\n fc.setCurrentDirectory(new File(Settings.get().get(Settings.DIRECTORY, Settings.DIRECTORY_DEFAULT)));\n if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {\n File file = fc.getSelectedFile();\n if (!file.getName().contains(\".\")) {\n file = new File(file.getAbsolutePath() + \".xml\");\n }\n File dir = file;\n if (!dir.isDirectory()) {\n dir = dir.getParentFile();\n }\n Settings.get().put(Settings.DIRECTORY, dir.getAbsolutePath());\n try {\n try (Writer writer = new OutputStreamWriter(new FileOutputStream(file))) {\n Printer p = new Printer();\n p.export(writer, doc);\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n protected int mode() {\n return CookieAction.MODE_SOME;\n }\n\n @Override\n public String getName() {\n return NbBundle.getMessage(SaveAsAction.class, \"CTL_SaveAsAction\");\n }\n\n @Override\n protected String iconResource() {\n return \"com/sun/hotspot/igv/coordinator/images/save.png\";\n }\n\n @Override\n public HelpCtx getHelpCtx() {\n return HelpCtx.DEFAULT_HELP;\n }\n\n @Override\n protected boolean asynchronous() {\n return false;\n }\n\n @Override\n protected boolean enable(Node[] nodes) {\n int cnt = 0;\n for (Node n : nodes) {\n cnt += n.getLookup().lookupAll(Group.class).size();\n }\n return cnt > 0;\n }\n}\n"} {"task_id": "Java_1284", "language": "Java", "task_type": "single_line", "source_file": "java/github/openjdk/jdk/src/utils/IdealGraphVisualizer/Coordinator/src/main/java/com/sun/hotspot/igv/coordinator/actions/SaveAsAction.java", "mask_start_position": 1088, "mask_end_position": 1101, "canonical_solution": "ileChooser();", "pre_mask_code": "package com.sun.hotspot.igv.coordinator.actions;\n\nimport com.sun.hotspot.igv.data.GraphDocument;\nimport com.sun.hotspot.igv.data.Group;\nimport com.sun.hotspot.igv.data.serialization.Printer;\nimport com.sun.hotspot.igv.settings.Settings;\nimport java.io.*;\nimport javax.swing.Action;\nimport javax.swing.JFileChooser;\nimport org.openide.nodes.Node;\nimport org.openide.util.HelpCtx;\nimport org.openide.util.NbBundle;\nimport org.openide.util.actions.CookieAction;\nimport org.openide.util.actions.NodeAction;\n\n/**\n * @author Thomas Wuerthinger\n */\npublic final class SaveAsAction extends NodeAction {\n\n public SaveAsAction() {\n putValue(Action.SHORT_DESCRIPTION, \"Save selected groups to XML file...\");\n }\n\n @Override\n protected void performAction(Node[] activatedNodes) {\n GraphDocument doc = new GraphDocument();\n for (Node n : activatedNodes) {\n Group group = n.getLookup().lookup(Group.class);\n doc.addElement(group);\n }\n save(doc);\n }\n\n public static void save(GraphDocument doc) {\n JFileChooser fc = new JF", "post_mask_code": "\n fc.setFileFilter(ImportAction.getFileFilter());\n fc.setCurrentDirectory(new File(Settings.get().get(Settings.DIRECTORY, Settings.DIRECTORY_DEFAULT)));\n if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {\n File file = fc.getSelectedFile();\n if (!file.getName().contains(\".\")) {\n file = new File(file.getAbsolutePath() + \".xml\");\n }\n File dir = file;\n if (!dir.isDirectory()) {\n dir = dir.getParentFile();\n }\n Settings.get().put(Settings.DIRECTORY, dir.getAbsolutePath());\n try {\n try (Writer writer = new OutputStreamWriter(new FileOutputStream(file))) {\n Printer p = new Printer();\n p.export(writer, doc);\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n protected int mode() {\n return CookieAction.MODE_SOME;\n }\n\n @Override\n public String getName() {\n return NbBundle.getMessage(SaveAsAction.class, \"CTL_SaveAsAction\");\n }\n\n @Override\n protected String iconResource() {\n return \"com/sun/hotspot/igv/coordinator/images/save.png\";\n }\n\n @Override\n public HelpCtx getHelpCtx() {\n return HelpCtx.DEFAULT_HELP;\n }\n\n @Override\n protected boolean asynchronous() {\n return false;\n }\n\n @Override\n protected boolean enable(Node[] nodes) {\n int cnt = 0;\n for (Node n : nodes) {\n cnt += n.getLookup().lookupAll(Group.class).size();\n }\n return cnt > 0;\n }\n}\n"} {"task_id": "Java_1285", "language": "Java", "task_type": "if_statement", "source_file": "java/github/openjdk/jdk/src/utils/IdealGraphVisualizer/Coordinator/src/main/java/com/sun/hotspot/igv/coordinator/actions/SaveAsAction.java", "mask_start_position": 1554, "mask_end_position": 1636, "canonical_solution": "if (!dir.isDirectory()) {\n dir = dir.getParentFile();\n }", "pre_mask_code": "package com.sun.hotspot.igv.coordinator.actions;\n\nimport com.sun.hotspot.igv.data.GraphDocument;\nimport com.sun.hotspot.igv.data.Group;\nimport com.sun.hotspot.igv.data.serialization.Printer;\nimport com.sun.hotspot.igv.settings.Settings;\nimport java.io.*;\nimport javax.swing.Action;\nimport javax.swing.JFileChooser;\nimport org.openide.nodes.Node;\nimport org.openide.util.HelpCtx;\nimport org.openide.util.NbBundle;\nimport org.openide.util.actions.CookieAction;\nimport org.openide.util.actions.NodeAction;\n\n/**\n * @author Thomas Wuerthinger\n */\npublic final class SaveAsAction extends NodeAction {\n\n public SaveAsAction() {\n putValue(Action.SHORT_DESCRIPTION, \"Save selected groups to XML file...\");\n }\n\n @Override\n protected void performAction(Node[] activatedNodes) {\n GraphDocument doc = new GraphDocument();\n for (Node n : activatedNodes) {\n Group group = n.getLookup().lookup(Group.class);\n doc.addElement(group);\n }\n save(doc);\n }\n\n public static void save(GraphDocument doc) {\n JFileChooser fc = new JFileChooser();\n fc.setFileFilter(ImportAction.getFileFilter());\n fc.setCurrentDirectory(new File(Settings.get().get(Settings.DIRECTORY, Settings.DIRECTORY_DEFAULT)));\n if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {\n File file = fc.getSelectedFile();\n if (!file.getName().contains(\".\")) {\n file = new File(file.getAbsolutePath() + \".xml\");\n }\n File dir = file;\n ", "post_mask_code": "\n Settings.get().put(Settings.DIRECTORY, dir.getAbsolutePath());\n try {\n try (Writer writer = new OutputStreamWriter(new FileOutputStream(file))) {\n Printer p = new Printer();\n p.export(writer, doc);\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n protected int mode() {\n return CookieAction.MODE_SOME;\n }\n\n @Override\n public String getName() {\n return NbBundle.getMessage(SaveAsAction.class, \"CTL_SaveAsAction\");\n }\n\n @Override\n protected String iconResource() {\n return \"com/sun/hotspot/igv/coordinator/images/save.png\";\n }\n\n @Override\n public HelpCtx getHelpCtx() {\n return HelpCtx.DEFAULT_HELP;\n }\n\n @Override\n protected boolean asynchronous() {\n return false;\n }\n\n @Override\n protected boolean enable(Node[] nodes) {\n int cnt = 0;\n for (Node n : nodes) {\n cnt += n.getLookup().lookupAll(Group.class).size();\n }\n return cnt > 0;\n }\n}\n"} {"task_id": "Java_1286", "language": "Java", "task_type": "try_statement", "source_file": "java/github/openjdk/jdk/src/utils/IdealGraphVisualizer/Coordinator/src/main/java/com/sun/hotspot/igv/coordinator/actions/SaveAsAction.java", "mask_start_position": 1724, "mask_end_position": 2102, "canonical_solution": "try {\n try (Writer writer = new OutputStreamWriter(new FileOutputStream(file))) {\n Printer p = new Printer();\n p.export(writer, doc);\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }", "pre_mask_code": "package com.sun.hotspot.igv.coordinator.actions;\n\nimport com.sun.hotspot.igv.data.GraphDocument;\nimport com.sun.hotspot.igv.data.Group;\nimport com.sun.hotspot.igv.data.serialization.Printer;\nimport com.sun.hotspot.igv.settings.Settings;\nimport java.io.*;\nimport javax.swing.Action;\nimport javax.swing.JFileChooser;\nimport org.openide.nodes.Node;\nimport org.openide.util.HelpCtx;\nimport org.openide.util.NbBundle;\nimport org.openide.util.actions.CookieAction;\nimport org.openide.util.actions.NodeAction;\n\n/**\n * @author Thomas Wuerthinger\n */\npublic final class SaveAsAction extends NodeAction {\n\n public SaveAsAction() {\n putValue(Action.SHORT_DESCRIPTION, \"Save selected groups to XML file...\");\n }\n\n @Override\n protected void performAction(Node[] activatedNodes) {\n GraphDocument doc = new GraphDocument();\n for (Node n : activatedNodes) {\n Group group = n.getLookup().lookup(Group.class);\n doc.addElement(group);\n }\n save(doc);\n }\n\n public static void save(GraphDocument doc) {\n JFileChooser fc = new JFileChooser();\n fc.setFileFilter(ImportAction.getFileFilter());\n fc.setCurrentDirectory(new File(Settings.get().get(Settings.DIRECTORY, Settings.DIRECTORY_DEFAULT)));\n if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {\n File file = fc.getSelectedFile();\n if (!file.getName().contains(\".\")) {\n file = new File(file.getAbsolutePath() + \".xml\");\n }\n File dir = file;\n if (!dir.isDirectory()) {\n dir = dir.getParentFile();\n }\n Settings.get().put(Settings.DIRECTORY, dir.getAbsolutePath());\n ", "post_mask_code": "\n }\n }\n\n protected int mode() {\n return CookieAction.MODE_SOME;\n }\n\n @Override\n public String getName() {\n return NbBundle.getMessage(SaveAsAction.class, \"CTL_SaveAsAction\");\n }\n\n @Override\n protected String iconResource() {\n return \"com/sun/hotspot/igv/coordinator/images/save.png\";\n }\n\n @Override\n public HelpCtx getHelpCtx() {\n return HelpCtx.DEFAULT_HELP;\n }\n\n @Override\n protected boolean asynchronous() {\n return false;\n }\n\n @Override\n protected boolean enable(Node[] nodes) {\n int cnt = 0;\n for (Node n : nodes) {\n cnt += n.getLookup().lookupAll(Group.class).size();\n }\n return cnt > 0;\n }\n}\n"} {"task_id": "Java_1287", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jeffheaton/encog-java-core/src/main/java/org/encog/ml/genetic/MLMethodGenome.java", "mask_start_position": 1185, "mask_end_position": 1219, "canonical_solution": "public MLEncodable getPhenotype() ", "pre_mask_code": "/*\n * Encog(tm) Core v3.4 - Java Version\n * http://example.com\n * http://example.com\n \n *\n * \n * For more information on Heaton Research copyrights, licenses \n * and trademarks visit:\n * http://example.com\n */\npackage org.encog.ml.genetic;\n\nimport org.encog.ml.MLEncodable;\nimport org.encog.ml.genetic.genome.DoubleArrayGenome;\n\n/**\n * Implements a genome that allows a feedforward neural network to be trained\n * using a genetic algorithm. The chromosome for a feed forward neural network\n * is the weight and bias matrix.\n */\npublic class MLMethodGenome extends DoubleArrayGenome {\n\n private static final long serialVersionUID = 1L;\n\n private MLEncodable phenotype;\n\n /**\n * Construct a neural genome.\n *\n * @param thePhenotype\n * The phenotype to use.\n */\n public MLMethodGenome(final MLEncodable thePhenotype) {\n super(thePhenotype.encodedArrayLength());\n this.phenotype = thePhenotype;\n this.phenotype.encodeToArray(getData());\n }\n\n /**\n * Decode the phenotype.\n */\n public void decode() {\n this.phenotype.decodeFromArray(getData());\n }\n\n /**\n * @return the phenotype\n */\n ", "post_mask_code": "{\n return this.phenotype;\n }\n\n /**\n * @param phenotype\n * the phenotype to set\n */\n public void setPhenotype(final MLEncodable phenotype) {\n this.phenotype = phenotype;\n }\n}\n"} {"task_id": "Java_1288", "language": "Java", "task_type": "method_body", "source_file": "java/github/jeffheaton/encog-java-core/src/main/java/org/encog/ml/genetic/MLMethodGenome.java", "mask_start_position": 1396, "mask_end_position": 1439, "canonical_solution": "{\n this.phenotype = phenotype;\n }", "pre_mask_code": "/*\n * Encog(tm) Core v3.4 - Java Version\n * http://example.com\n * http://example.com\n \n *\n * \n * For more information on Heaton Research copyrights, licenses \n * and trademarks visit:\n * http://example.com\n */\npackage org.encog.ml.genetic;\n\nimport org.encog.ml.MLEncodable;\nimport org.encog.ml.genetic.genome.DoubleArrayGenome;\n\n/**\n * Implements a genome that allows a feedforward neural network to be trained\n * using a genetic algorithm. The chromosome for a feed forward neural network\n * is the weight and bias matrix.\n */\npublic class MLMethodGenome extends DoubleArrayGenome {\n\n private static final long serialVersionUID = 1L;\n\n private MLEncodable phenotype;\n\n /**\n * Construct a neural genome.\n *\n * @param thePhenotype\n * The phenotype to use.\n */\n public MLMethodGenome(final MLEncodable thePhenotype) {\n super(thePhenotype.encodedArrayLength());\n this.phenotype = thePhenotype;\n this.phenotype.encodeToArray(getData());\n }\n\n /**\n * Decode the phenotype.\n */\n public void decode() {\n this.phenotype.decodeFromArray(getData());\n }\n\n /**\n * @return the phenotype\n */\n public MLEncodable getPhenotype() {\n return this.phenotype;\n }\n\n /**\n * @param phenotype\n * the phenotype to set\n */\n public void setPhenotype(final MLEncodable phenotype) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1289", "language": "Java", "task_type": "single_line", "source_file": "java/github/jeffheaton/encog-java-core/src/main/java/org/encog/ml/genetic/MLMethodGenome.java", "mask_start_position": 1429, "mask_end_position": 1433, "canonical_solution": "ype;", "pre_mask_code": "/*\n * Encog(tm) Core v3.4 - Java Version\n * http://example.com\n * http://example.com\n \n *\n * \n * For more information on Heaton Research copyrights, licenses \n * and trademarks visit:\n * http://example.com\n */\npackage org.encog.ml.genetic;\n\nimport org.encog.ml.MLEncodable;\nimport org.encog.ml.genetic.genome.DoubleArrayGenome;\n\n/**\n * Implements a genome that allows a feedforward neural network to be trained\n * using a genetic algorithm. The chromosome for a feed forward neural network\n * is the weight and bias matrix.\n */\npublic class MLMethodGenome extends DoubleArrayGenome {\n\n private static final long serialVersionUID = 1L;\n\n private MLEncodable phenotype;\n\n /**\n * Construct a neural genome.\n *\n * @param thePhenotype\n * The phenotype to use.\n */\n public MLMethodGenome(final MLEncodable thePhenotype) {\n super(thePhenotype.encodedArrayLength());\n this.phenotype = thePhenotype;\n this.phenotype.encodeToArray(getData());\n }\n\n /**\n * Decode the phenotype.\n */\n public void decode() {\n this.phenotype.decodeFromArray(getData());\n }\n\n /**\n * @return the phenotype\n */\n public MLEncodable getPhenotype() {\n return this.phenotype;\n }\n\n /**\n * @param phenotype\n * the phenotype to set\n */\n public void setPhenotype(final MLEncodable phenotype) {\n this.phenotype = phenot", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1290", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/jeffheaton/encog-java-core/src/main/java/org/encog/ml/genetic/MLMethodGenome.java", "mask_start_position": 1185, "mask_end_position": 1257, "canonical_solution": "public MLEncodable getPhenotype() {\n return this.phenotype;\n }", "pre_mask_code": "/*\n * Encog(tm) Core v3.4 - Java Version\n * http://example.com\n * http://example.com\n \n *\n * \n * For more information on Heaton Research copyrights, licenses \n * and trademarks visit:\n * http://example.com\n */\npackage org.encog.ml.genetic;\n\nimport org.encog.ml.MLEncodable;\nimport org.encog.ml.genetic.genome.DoubleArrayGenome;\n\n/**\n * Implements a genome that allows a feedforward neural network to be trained\n * using a genetic algorithm. The chromosome for a feed forward neural network\n * is the weight and bias matrix.\n */\npublic class MLMethodGenome extends DoubleArrayGenome {\n\n private static final long serialVersionUID = 1L;\n\n private MLEncodable phenotype;\n\n /**\n * Construct a neural genome.\n *\n * @param thePhenotype\n * The phenotype to use.\n */\n public MLMethodGenome(final MLEncodable thePhenotype) {\n super(thePhenotype.encodedArrayLength());\n this.phenotype = thePhenotype;\n this.phenotype.encodeToArray(getData());\n }\n\n /**\n * Decode the phenotype.\n */\n public void decode() {\n this.phenotype.decodeFromArray(getData());\n }\n\n /**\n * @return the phenotype\n */\n ", "post_mask_code": "\n\n /**\n * @param phenotype\n * the phenotype to set\n */\n public void setPhenotype(final MLEncodable phenotype) {\n this.phenotype = phenotype;\n }\n}\n"} {"task_id": "Java_1291", "language": "Java", "task_type": "method_signature", "source_file": "java/github/zaki50/android_gradle_template/app/src/androidTest/java/com/example/mytemplate/ModuleTest.java", "mask_start_position": 702, "mask_end_position": 755, "canonical_solution": "@Test\n public void testThatDependencyIsInjected() ", "pre_mask_code": "package com.example.mytemplate;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport javax.inject.Inject;\nimport dagger.Module;\nimport dagger.ObjectGraph;\nimport dagger.Provides;\nimport static org.hamcrest.core.Is.is;\nimport static org.hamcrest.core.IsNull.notNullValue;\nimport static org.junit.Assert.assertThat;\n\npublic class ModuleTest {\n\n @Module(injects = ModuleTest.class)\n static final class MyModule {\n\n @Provides\n SampleModel provideSampleModel() {\n return new SampleModel();\n }\n }\n\n @Inject\n SampleModel mSampleModel;\n\n @Before\n public void setUp() throws Exception {\n ObjectGraph.create(new MyModule()).inject(this);\n }\n\n ", "post_mask_code": "{\n assertThat(mSampleModel, is(notNullValue()));\n }\n}\n"} {"task_id": "Java_1292", "language": "Java", "task_type": "method_body", "source_file": "java/github/zaki50/android_gradle_template/app/src/androidTest/java/com/example/mytemplate/ModuleTest.java", "mask_start_position": 632, "mask_end_position": 696, "canonical_solution": "{\n ObjectGraph.create(new MyModule()).inject(this);\n }", "pre_mask_code": "package com.example.mytemplate;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport javax.inject.Inject;\nimport dagger.Module;\nimport dagger.ObjectGraph;\nimport dagger.Provides;\nimport static org.hamcrest.core.Is.is;\nimport static org.hamcrest.core.IsNull.notNullValue;\nimport static org.junit.Assert.assertThat;\n\npublic class ModuleTest {\n\n @Module(injects = ModuleTest.class)\n static final class MyModule {\n\n @Provides\n SampleModel provideSampleModel() {\n return new SampleModel();\n }\n }\n\n @Inject\n SampleModel mSampleModel;\n\n @Before\n public void setUp() throws Exception ", "post_mask_code": "\n\n @Test\n public void testThatDependencyIsInjected() {\n assertThat(mSampleModel, is(notNullValue()));\n }\n}\n"} {"task_id": "Java_1293", "language": "Java", "task_type": "single_line", "source_file": "java/github/zaki50/android_gradle_template/app/src/androidTest/java/com/example/mytemplate/ModuleTest.java", "mask_start_position": 499, "mask_end_position": 518, "canonical_solution": " new SampleModel();", "pre_mask_code": "package com.example.mytemplate;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport javax.inject.Inject;\nimport dagger.Module;\nimport dagger.ObjectGraph;\nimport dagger.Provides;\nimport static org.hamcrest.core.Is.is;\nimport static org.hamcrest.core.IsNull.notNullValue;\nimport static org.junit.Assert.assertThat;\n\npublic class ModuleTest {\n\n @Module(injects = ModuleTest.class)\n static final class MyModule {\n\n @Provides\n SampleModel provideSampleModel() {\n return", "post_mask_code": "\n }\n }\n\n @Inject\n SampleModel mSampleModel;\n\n @Before\n public void setUp() throws Exception {\n ObjectGraph.create(new MyModule()).inject(this);\n }\n\n @Test\n public void testThatDependencyIsInjected() {\n assertThat(mSampleModel, is(notNullValue()));\n }\n}\n"} {"task_id": "Java_1294", "language": "Java", "task_type": "method_signature", "source_file": "java/github/HaydiKodlayalim/microservice-app/hystrix-dashboard/src/main/java/com/haydikodlayalim/hystrix/HystrixDashboardApplication.java", "mask_start_position": 337, "mask_end_position": 376, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "package com.haydikodlayalim.hystrix;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;\n\n@EnableHystrixDashboard\n@SpringBootApplication\npublic class HystrixDashboardApplication {\n\n ", "post_mask_code": "{\n SpringApplication.run(HystrixDashboardApplication.class, args);\n }\n}\n"} {"task_id": "Java_1295", "language": "Java", "task_type": "method_body", "source_file": "java/github/HaydiKodlayalim/microservice-app/hystrix-dashboard/src/main/java/com/haydikodlayalim/hystrix/HystrixDashboardApplication.java", "mask_start_position": 376, "mask_end_position": 455, "canonical_solution": "{\n SpringApplication.run(HystrixDashboardApplication.class, args);\n }", "pre_mask_code": "package com.haydikodlayalim.hystrix;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;\n\n@EnableHystrixDashboard\n@SpringBootApplication\npublic class HystrixDashboardApplication {\n\n public static void main(String[] args) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1296", "language": "Java", "task_type": "single_line", "source_file": "java/github/HaydiKodlayalim/microservice-app/hystrix-dashboard/src/main/java/com/haydikodlayalim/hystrix/HystrixDashboardApplication.java", "mask_start_position": 392, "mask_end_position": 449, "canonical_solution": "Application.run(HystrixDashboardApplication.class, args);", "pre_mask_code": "package com.haydikodlayalim.hystrix;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;\n\n@EnableHystrixDashboard\n@SpringBootApplication\npublic class HystrixDashboardApplication {\n\n public static void main(String[] args) {\n Spring", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1297", "language": "Java", "task_type": "method_signature", "source_file": "java/github/maxliaops/Java_Web_Examples/12/src/com/dao/ReaderDAO.java", "mask_start_position": 7038, "mask_end_position": 7079, "canonical_solution": "public int delete(ReaderForm readerForm) ", "pre_mask_code": "package com.dao;\n\nimport com.core.ConnDB;\nimport java.util.*;\nimport java.sql.*;\nimport com.actionForm.ReaderForm;\n\npublic class ReaderDAO {\n\n private ConnDB conn = new ConnDB();\n\n // 查询数据\n public Collection query(String strif) {\n ReaderForm readerForm = null;\n Collection readerColl = new ArrayList();\n String sql = \"\";\n if (strif != \"all\" && strif != null && strif != \"\") {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where \" + strif + \"\";\n } else {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id\";\n }\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm = new ReaderForm();\n readerForm.setId(Integer.valueOf(rs.getString(1)));\n readerForm.setName(rs.getString(2));\n readerForm.setSex(rs.getString(3));\n readerForm.setBarcode(rs.getString(4));\n readerForm.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm.setBirthday(birthday == null ? \"\" : birthday);\n readerForm.setPaperType(rs.getString(7));\n readerForm.setPaperNO(rs.getString(8));\n readerForm.setTel(rs.getString(9));\n readerForm.setEmail(rs.getString(10));\n readerForm.setCreateDate(rs.getString(11));\n readerForm.setOperator(rs.getString(12));\n readerForm.setRemark(rs.getString(13));\n readerForm.setTypeid(rs.getInt(14));\n readerForm.setTypename(rs.getString(15));\n readerForm.setNumber(rs.getInt(16));\n readerColl.add(readerForm);\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerColl;\n }\n\n // 用于修改的查询\n public ReaderForm queryM(ReaderForm readerForm) {\n ReaderForm readerForm1 = null;\n String sql = \"\";\n if (readerForm.getId() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.id=\" + readerForm.getId() + \"\";\n } else if (readerForm.getBarcode() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.barcode=\" + readerForm.getBarcode() + \"\";\n }\n System.out.println(\"修改读者信息时的SQL:\" + sql);\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm1 = new ReaderForm();\n readerForm1.setId(Integer.valueOf(rs.getString(1)));\n readerForm1.setName(rs.getString(2));\n readerForm1.setSex(rs.getString(3));\n readerForm1.setBarcode(rs.getString(4));\n readerForm1.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm1.setBirthday(birthday == null ? \"\" : birthday);\n readerForm1.setPaperType(rs.getString(7));\n readerForm1.setPaperNO(rs.getString(8));\n readerForm1.setTel(rs.getString(9));\n readerForm1.setEmail(rs.getString(10));\n readerForm1.setCreateDate(rs.getString(11));\n readerForm1.setOperator(rs.getString(12));\n readerForm1.setRemark(rs.getString(13));\n readerForm1.setTypeid(rs.getInt(14));\n readerForm1.setTypename(rs.getString(15));\n readerForm1.setNumber(rs.getInt(16));\n System.out.println(rs.getString(2));\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerForm1;\n }\n\n // 添加数据\n public int insert(ReaderForm readerForm) {\n String sql1 = \"SELECT * FROM tb_reader WHERE barcode='\" + readerForm.getBarcode() + \"'\";\n ResultSet rs = conn.executeQuery(sql1);\n String sql = \"\";\n int falg = 0;\n try {\n if (rs.next()) {\n falg = 2;\n } else {\n if (readerForm.getBirthday() == \"\") {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n } else {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,birthday,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getBirthday() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n }\n falg = conn.executeUpdate(sql);\n System.out.println(\"添加读者信息的SQL:\" + sql);\n conn.close();\n }\n } catch (SQLException ex) {\n falg = 0;\n }\n System.out.println(\"falg:\" + falg);\n return falg;\n }\n\n // 修改数据\n public int update(ReaderForm readerForm) {\n String sql = \"\";\n if (readerForm.getBirthday() == \"\") {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday=null,paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n } else {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday='\" + readerForm.getBirthday() + \"',paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n }\n int falg = conn.executeUpdate(sql);\n System.out.println(\"修改数据时的SQL:\" + sql);\n conn.close();\n return falg;\n }\n\n // 删除数据\n ", "post_mask_code": "{\n String sql = \"Delete from tb_reader where id=\" + readerForm.getId() + \"\";\n int falg = conn.executeUpdate(sql);\n System.out.println(\"删除时的SQL:\" + sql);\n return falg;\n }\n}\n"} {"task_id": "Java_1298", "language": "Java", "task_type": "method_body", "source_file": "java/github/maxliaops/Java_Web_Examples/12/src/com/dao/ReaderDAO.java", "mask_start_position": 7079, "mask_end_position": 7279, "canonical_solution": "{\n String sql = \"Delete from tb_reader where id=\" + readerForm.getId() + \"\";\n int falg = conn.executeUpdate(sql);\n System.out.println(\"删除时的SQL:\" + sql);\n return falg;\n }", "pre_mask_code": "package com.dao;\n\nimport com.core.ConnDB;\nimport java.util.*;\nimport java.sql.*;\nimport com.actionForm.ReaderForm;\n\npublic class ReaderDAO {\n\n private ConnDB conn = new ConnDB();\n\n // 查询数据\n public Collection query(String strif) {\n ReaderForm readerForm = null;\n Collection readerColl = new ArrayList();\n String sql = \"\";\n if (strif != \"all\" && strif != null && strif != \"\") {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where \" + strif + \"\";\n } else {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id\";\n }\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm = new ReaderForm();\n readerForm.setId(Integer.valueOf(rs.getString(1)));\n readerForm.setName(rs.getString(2));\n readerForm.setSex(rs.getString(3));\n readerForm.setBarcode(rs.getString(4));\n readerForm.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm.setBirthday(birthday == null ? \"\" : birthday);\n readerForm.setPaperType(rs.getString(7));\n readerForm.setPaperNO(rs.getString(8));\n readerForm.setTel(rs.getString(9));\n readerForm.setEmail(rs.getString(10));\n readerForm.setCreateDate(rs.getString(11));\n readerForm.setOperator(rs.getString(12));\n readerForm.setRemark(rs.getString(13));\n readerForm.setTypeid(rs.getInt(14));\n readerForm.setTypename(rs.getString(15));\n readerForm.setNumber(rs.getInt(16));\n readerColl.add(readerForm);\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerColl;\n }\n\n // 用于修改的查询\n public ReaderForm queryM(ReaderForm readerForm) {\n ReaderForm readerForm1 = null;\n String sql = \"\";\n if (readerForm.getId() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.id=\" + readerForm.getId() + \"\";\n } else if (readerForm.getBarcode() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.barcode=\" + readerForm.getBarcode() + \"\";\n }\n System.out.println(\"修改读者信息时的SQL:\" + sql);\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm1 = new ReaderForm();\n readerForm1.setId(Integer.valueOf(rs.getString(1)));\n readerForm1.setName(rs.getString(2));\n readerForm1.setSex(rs.getString(3));\n readerForm1.setBarcode(rs.getString(4));\n readerForm1.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm1.setBirthday(birthday == null ? \"\" : birthday);\n readerForm1.setPaperType(rs.getString(7));\n readerForm1.setPaperNO(rs.getString(8));\n readerForm1.setTel(rs.getString(9));\n readerForm1.setEmail(rs.getString(10));\n readerForm1.setCreateDate(rs.getString(11));\n readerForm1.setOperator(rs.getString(12));\n readerForm1.setRemark(rs.getString(13));\n readerForm1.setTypeid(rs.getInt(14));\n readerForm1.setTypename(rs.getString(15));\n readerForm1.setNumber(rs.getInt(16));\n System.out.println(rs.getString(2));\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerForm1;\n }\n\n // 添加数据\n public int insert(ReaderForm readerForm) {\n String sql1 = \"SELECT * FROM tb_reader WHERE barcode='\" + readerForm.getBarcode() + \"'\";\n ResultSet rs = conn.executeQuery(sql1);\n String sql = \"\";\n int falg = 0;\n try {\n if (rs.next()) {\n falg = 2;\n } else {\n if (readerForm.getBirthday() == \"\") {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n } else {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,birthday,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getBirthday() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n }\n falg = conn.executeUpdate(sql);\n System.out.println(\"添加读者信息的SQL:\" + sql);\n conn.close();\n }\n } catch (SQLException ex) {\n falg = 0;\n }\n System.out.println(\"falg:\" + falg);\n return falg;\n }\n\n // 修改数据\n public int update(ReaderForm readerForm) {\n String sql = \"\";\n if (readerForm.getBirthday() == \"\") {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday=null,paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n } else {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday='\" + readerForm.getBirthday() + \"',paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n }\n int falg = conn.executeUpdate(sql);\n System.out.println(\"修改数据时的SQL:\" + sql);\n conn.close();\n return falg;\n }\n\n // 删除数据\n public int delete(ReaderForm readerForm) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1299", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/maxliaops/Java_Web_Examples/12/src/com/dao/ReaderDAO.java", "mask_start_position": 5851, "mask_end_position": 6879, "canonical_solution": "\n String sql = \"\";\n if (readerForm.getBirthday() == \"\") {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday=null,paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n } else {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday='\" + readerForm.getBirthday() + \"',paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n }", "pre_mask_code": "package com.dao;\n\nimport com.core.ConnDB;\nimport java.util.*;\nimport java.sql.*;\nimport com.actionForm.ReaderForm;\n\npublic class ReaderDAO {\n\n private ConnDB conn = new ConnDB();\n\n // 查询数据\n public Collection query(String strif) {\n ReaderForm readerForm = null;\n Collection readerColl = new ArrayList();\n String sql = \"\";\n if (strif != \"all\" && strif != null && strif != \"\") {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where \" + strif + \"\";\n } else {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id\";\n }\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm = new ReaderForm();\n readerForm.setId(Integer.valueOf(rs.getString(1)));\n readerForm.setName(rs.getString(2));\n readerForm.setSex(rs.getString(3));\n readerForm.setBarcode(rs.getString(4));\n readerForm.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm.setBirthday(birthday == null ? \"\" : birthday);\n readerForm.setPaperType(rs.getString(7));\n readerForm.setPaperNO(rs.getString(8));\n readerForm.setTel(rs.getString(9));\n readerForm.setEmail(rs.getString(10));\n readerForm.setCreateDate(rs.getString(11));\n readerForm.setOperator(rs.getString(12));\n readerForm.setRemark(rs.getString(13));\n readerForm.setTypeid(rs.getInt(14));\n readerForm.setTypename(rs.getString(15));\n readerForm.setNumber(rs.getInt(16));\n readerColl.add(readerForm);\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerColl;\n }\n\n // 用于修改的查询\n public ReaderForm queryM(ReaderForm readerForm) {\n ReaderForm readerForm1 = null;\n String sql = \"\";\n if (readerForm.getId() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.id=\" + readerForm.getId() + \"\";\n } else if (readerForm.getBarcode() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.barcode=\" + readerForm.getBarcode() + \"\";\n }\n System.out.println(\"修改读者信息时的SQL:\" + sql);\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm1 = new ReaderForm();\n readerForm1.setId(Integer.valueOf(rs.getString(1)));\n readerForm1.setName(rs.getString(2));\n readerForm1.setSex(rs.getString(3));\n readerForm1.setBarcode(rs.getString(4));\n readerForm1.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm1.setBirthday(birthday == null ? \"\" : birthday);\n readerForm1.setPaperType(rs.getString(7));\n readerForm1.setPaperNO(rs.getString(8));\n readerForm1.setTel(rs.getString(9));\n readerForm1.setEmail(rs.getString(10));\n readerForm1.setCreateDate(rs.getString(11));\n readerForm1.setOperator(rs.getString(12));\n readerForm1.setRemark(rs.getString(13));\n readerForm1.setTypeid(rs.getInt(14));\n readerForm1.setTypename(rs.getString(15));\n readerForm1.setNumber(rs.getInt(16));\n System.out.println(rs.getString(2));\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerForm1;\n }\n\n // 添加数据\n public int insert(ReaderForm readerForm) {\n String sql1 = \"SELECT * FROM tb_reader WHERE barcode='\" + readerForm.getBarcode() + \"'\";\n ResultSet rs = conn.executeQuery(sql1);\n String sql = \"\";\n int falg = 0;\n try {\n if (rs.next()) {\n falg = 2;\n } else {\n if (readerForm.getBirthday() == \"\") {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n } else {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,birthday,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getBirthday() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n }\n falg = conn.executeUpdate(sql);\n System.out.println(\"添加读者信息的SQL:\" + sql);\n conn.close();\n }\n } catch (SQLException ex) {\n falg = 0;\n }\n System.out.println(\"falg:\" + falg);\n return falg;\n }\n\n // 修改数据\n public int update(ReaderForm readerForm) {", "post_mask_code": "\n int falg = conn.executeUpdate(sql);\n System.out.println(\"修改数据时的SQL:\" + sql);\n conn.close();\n return falg;\n }\n\n // 删除数据\n public int delete(ReaderForm readerForm) {\n String sql = \"Delete from tb_reader where id=\" + readerForm.getId() + \"\";\n int falg = conn.executeUpdate(sql);\n System.out.println(\"删除时的SQL:\" + sql);\n return falg;\n }\n}\n"} {"task_id": "Java_1300", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/maxliaops/Java_Web_Examples/12/src/com/dao/ReaderDAO.java", "mask_start_position": 6888, "mask_end_position": 6971, "canonical_solution": "int falg = conn.executeUpdate(sql);\n System.out.println(\"修改数据时的SQL:\" + sql);", "pre_mask_code": "package com.dao;\n\nimport com.core.ConnDB;\nimport java.util.*;\nimport java.sql.*;\nimport com.actionForm.ReaderForm;\n\npublic class ReaderDAO {\n\n private ConnDB conn = new ConnDB();\n\n // 查询数据\n public Collection query(String strif) {\n ReaderForm readerForm = null;\n Collection readerColl = new ArrayList();\n String sql = \"\";\n if (strif != \"all\" && strif != null && strif != \"\") {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where \" + strif + \"\";\n } else {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id\";\n }\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm = new ReaderForm();\n readerForm.setId(Integer.valueOf(rs.getString(1)));\n readerForm.setName(rs.getString(2));\n readerForm.setSex(rs.getString(3));\n readerForm.setBarcode(rs.getString(4));\n readerForm.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm.setBirthday(birthday == null ? \"\" : birthday);\n readerForm.setPaperType(rs.getString(7));\n readerForm.setPaperNO(rs.getString(8));\n readerForm.setTel(rs.getString(9));\n readerForm.setEmail(rs.getString(10));\n readerForm.setCreateDate(rs.getString(11));\n readerForm.setOperator(rs.getString(12));\n readerForm.setRemark(rs.getString(13));\n readerForm.setTypeid(rs.getInt(14));\n readerForm.setTypename(rs.getString(15));\n readerForm.setNumber(rs.getInt(16));\n readerColl.add(readerForm);\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerColl;\n }\n\n // 用于修改的查询\n public ReaderForm queryM(ReaderForm readerForm) {\n ReaderForm readerForm1 = null;\n String sql = \"\";\n if (readerForm.getId() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.id=\" + readerForm.getId() + \"\";\n } else if (readerForm.getBarcode() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.barcode=\" + readerForm.getBarcode() + \"\";\n }\n System.out.println(\"修改读者信息时的SQL:\" + sql);\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm1 = new ReaderForm();\n readerForm1.setId(Integer.valueOf(rs.getString(1)));\n readerForm1.setName(rs.getString(2));\n readerForm1.setSex(rs.getString(3));\n readerForm1.setBarcode(rs.getString(4));\n readerForm1.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm1.setBirthday(birthday == null ? \"\" : birthday);\n readerForm1.setPaperType(rs.getString(7));\n readerForm1.setPaperNO(rs.getString(8));\n readerForm1.setTel(rs.getString(9));\n readerForm1.setEmail(rs.getString(10));\n readerForm1.setCreateDate(rs.getString(11));\n readerForm1.setOperator(rs.getString(12));\n readerForm1.setRemark(rs.getString(13));\n readerForm1.setTypeid(rs.getInt(14));\n readerForm1.setTypename(rs.getString(15));\n readerForm1.setNumber(rs.getInt(16));\n System.out.println(rs.getString(2));\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerForm1;\n }\n\n // 添加数据\n public int insert(ReaderForm readerForm) {\n String sql1 = \"SELECT * FROM tb_reader WHERE barcode='\" + readerForm.getBarcode() + \"'\";\n ResultSet rs = conn.executeQuery(sql1);\n String sql = \"\";\n int falg = 0;\n try {\n if (rs.next()) {\n falg = 2;\n } else {\n if (readerForm.getBirthday() == \"\") {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n } else {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,birthday,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getBirthday() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n }\n falg = conn.executeUpdate(sql);\n System.out.println(\"添加读者信息的SQL:\" + sql);\n conn.close();\n }\n } catch (SQLException ex) {\n falg = 0;\n }\n System.out.println(\"falg:\" + falg);\n return falg;\n }\n\n // 修改数据\n public int update(ReaderForm readerForm) {\n String sql = \"\";\n if (readerForm.getBirthday() == \"\") {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday=null,paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n } else {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday='\" + readerForm.getBirthday() + \"',paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n }\n ", "post_mask_code": "\n conn.close();\n return falg;\n }\n\n // 删除数据\n public int delete(ReaderForm readerForm) {\n String sql = \"Delete from tb_reader where id=\" + readerForm.getId() + \"\";\n int falg = conn.executeUpdate(sql);\n System.out.println(\"删除时的SQL:\" + sql);\n return falg;\n }\n}\n"} {"task_id": "Java_1301", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/maxliaops/Java_Web_Examples/12/src/com/dao/ReaderDAO.java", "mask_start_position": 6980, "mask_end_position": 7020, "canonical_solution": "conn.close();\n return falg;\n }", "pre_mask_code": "package com.dao;\n\nimport com.core.ConnDB;\nimport java.util.*;\nimport java.sql.*;\nimport com.actionForm.ReaderForm;\n\npublic class ReaderDAO {\n\n private ConnDB conn = new ConnDB();\n\n // 查询数据\n public Collection query(String strif) {\n ReaderForm readerForm = null;\n Collection readerColl = new ArrayList();\n String sql = \"\";\n if (strif != \"all\" && strif != null && strif != \"\") {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where \" + strif + \"\";\n } else {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id\";\n }\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm = new ReaderForm();\n readerForm.setId(Integer.valueOf(rs.getString(1)));\n readerForm.setName(rs.getString(2));\n readerForm.setSex(rs.getString(3));\n readerForm.setBarcode(rs.getString(4));\n readerForm.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm.setBirthday(birthday == null ? \"\" : birthday);\n readerForm.setPaperType(rs.getString(7));\n readerForm.setPaperNO(rs.getString(8));\n readerForm.setTel(rs.getString(9));\n readerForm.setEmail(rs.getString(10));\n readerForm.setCreateDate(rs.getString(11));\n readerForm.setOperator(rs.getString(12));\n readerForm.setRemark(rs.getString(13));\n readerForm.setTypeid(rs.getInt(14));\n readerForm.setTypename(rs.getString(15));\n readerForm.setNumber(rs.getInt(16));\n readerColl.add(readerForm);\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerColl;\n }\n\n // 用于修改的查询\n public ReaderForm queryM(ReaderForm readerForm) {\n ReaderForm readerForm1 = null;\n String sql = \"\";\n if (readerForm.getId() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.id=\" + readerForm.getId() + \"\";\n } else if (readerForm.getBarcode() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.barcode=\" + readerForm.getBarcode() + \"\";\n }\n System.out.println(\"修改读者信息时的SQL:\" + sql);\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm1 = new ReaderForm();\n readerForm1.setId(Integer.valueOf(rs.getString(1)));\n readerForm1.setName(rs.getString(2));\n readerForm1.setSex(rs.getString(3));\n readerForm1.setBarcode(rs.getString(4));\n readerForm1.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm1.setBirthday(birthday == null ? \"\" : birthday);\n readerForm1.setPaperType(rs.getString(7));\n readerForm1.setPaperNO(rs.getString(8));\n readerForm1.setTel(rs.getString(9));\n readerForm1.setEmail(rs.getString(10));\n readerForm1.setCreateDate(rs.getString(11));\n readerForm1.setOperator(rs.getString(12));\n readerForm1.setRemark(rs.getString(13));\n readerForm1.setTypeid(rs.getInt(14));\n readerForm1.setTypename(rs.getString(15));\n readerForm1.setNumber(rs.getInt(16));\n System.out.println(rs.getString(2));\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerForm1;\n }\n\n // 添加数据\n public int insert(ReaderForm readerForm) {\n String sql1 = \"SELECT * FROM tb_reader WHERE barcode='\" + readerForm.getBarcode() + \"'\";\n ResultSet rs = conn.executeQuery(sql1);\n String sql = \"\";\n int falg = 0;\n try {\n if (rs.next()) {\n falg = 2;\n } else {\n if (readerForm.getBirthday() == \"\") {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n } else {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,birthday,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getBirthday() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n }\n falg = conn.executeUpdate(sql);\n System.out.println(\"添加读者信息的SQL:\" + sql);\n conn.close();\n }\n } catch (SQLException ex) {\n falg = 0;\n }\n System.out.println(\"falg:\" + falg);\n return falg;\n }\n\n // 修改数据\n public int update(ReaderForm readerForm) {\n String sql = \"\";\n if (readerForm.getBirthday() == \"\") {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday=null,paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n } else {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday='\" + readerForm.getBirthday() + \"',paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n }\n int falg = conn.executeUpdate(sql);\n System.out.println(\"修改数据时的SQL:\" + sql);\n ", "post_mask_code": "\n\n // 删除数据\n public int delete(ReaderForm readerForm) {\n String sql = \"Delete from tb_reader where id=\" + readerForm.getId() + \"\";\n int falg = conn.executeUpdate(sql);\n System.out.println(\"删除时的SQL:\" + sql);\n return falg;\n }\n}\n"} {"task_id": "Java_1302", "language": "Java", "task_type": "single_line", "source_file": "java/github/maxliaops/Java_Web_Examples/12/src/com/dao/ReaderDAO.java", "mask_start_position": 6934, "mask_end_position": 6971, "canonical_solution": "stem.out.println(\"修改数据时的SQL:\" + sql);", "pre_mask_code": "package com.dao;\n\nimport com.core.ConnDB;\nimport java.util.*;\nimport java.sql.*;\nimport com.actionForm.ReaderForm;\n\npublic class ReaderDAO {\n\n private ConnDB conn = new ConnDB();\n\n // 查询数据\n public Collection query(String strif) {\n ReaderForm readerForm = null;\n Collection readerColl = new ArrayList();\n String sql = \"\";\n if (strif != \"all\" && strif != null && strif != \"\") {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where \" + strif + \"\";\n } else {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id\";\n }\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm = new ReaderForm();\n readerForm.setId(Integer.valueOf(rs.getString(1)));\n readerForm.setName(rs.getString(2));\n readerForm.setSex(rs.getString(3));\n readerForm.setBarcode(rs.getString(4));\n readerForm.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm.setBirthday(birthday == null ? \"\" : birthday);\n readerForm.setPaperType(rs.getString(7));\n readerForm.setPaperNO(rs.getString(8));\n readerForm.setTel(rs.getString(9));\n readerForm.setEmail(rs.getString(10));\n readerForm.setCreateDate(rs.getString(11));\n readerForm.setOperator(rs.getString(12));\n readerForm.setRemark(rs.getString(13));\n readerForm.setTypeid(rs.getInt(14));\n readerForm.setTypename(rs.getString(15));\n readerForm.setNumber(rs.getInt(16));\n readerColl.add(readerForm);\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerColl;\n }\n\n // 用于修改的查询\n public ReaderForm queryM(ReaderForm readerForm) {\n ReaderForm readerForm1 = null;\n String sql = \"\";\n if (readerForm.getId() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.id=\" + readerForm.getId() + \"\";\n } else if (readerForm.getBarcode() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.barcode=\" + readerForm.getBarcode() + \"\";\n }\n System.out.println(\"修改读者信息时的SQL:\" + sql);\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm1 = new ReaderForm();\n readerForm1.setId(Integer.valueOf(rs.getString(1)));\n readerForm1.setName(rs.getString(2));\n readerForm1.setSex(rs.getString(3));\n readerForm1.setBarcode(rs.getString(4));\n readerForm1.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm1.setBirthday(birthday == null ? \"\" : birthday);\n readerForm1.setPaperType(rs.getString(7));\n readerForm1.setPaperNO(rs.getString(8));\n readerForm1.setTel(rs.getString(9));\n readerForm1.setEmail(rs.getString(10));\n readerForm1.setCreateDate(rs.getString(11));\n readerForm1.setOperator(rs.getString(12));\n readerForm1.setRemark(rs.getString(13));\n readerForm1.setTypeid(rs.getInt(14));\n readerForm1.setTypename(rs.getString(15));\n readerForm1.setNumber(rs.getInt(16));\n System.out.println(rs.getString(2));\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerForm1;\n }\n\n // 添加数据\n public int insert(ReaderForm readerForm) {\n String sql1 = \"SELECT * FROM tb_reader WHERE barcode='\" + readerForm.getBarcode() + \"'\";\n ResultSet rs = conn.executeQuery(sql1);\n String sql = \"\";\n int falg = 0;\n try {\n if (rs.next()) {\n falg = 2;\n } else {\n if (readerForm.getBirthday() == \"\") {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n } else {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,birthday,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getBirthday() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n }\n falg = conn.executeUpdate(sql);\n System.out.println(\"添加读者信息的SQL:\" + sql);\n conn.close();\n }\n } catch (SQLException ex) {\n falg = 0;\n }\n System.out.println(\"falg:\" + falg);\n return falg;\n }\n\n // 修改数据\n public int update(ReaderForm readerForm) {\n String sql = \"\";\n if (readerForm.getBirthday() == \"\") {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday=null,paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n } else {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday='\" + readerForm.getBirthday() + \"',paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n }\n int falg = conn.executeUpdate(sql);\n Sy", "post_mask_code": "\n conn.close();\n return falg;\n }\n\n // 删除数据\n public int delete(ReaderForm readerForm) {\n String sql = \"Delete from tb_reader where id=\" + readerForm.getId() + \"\";\n int falg = conn.executeUpdate(sql);\n System.out.println(\"删除时的SQL:\" + sql);\n return falg;\n }\n}\n"} {"task_id": "Java_1303", "language": "Java", "task_type": "if_statement", "source_file": "java/github/maxliaops/Java_Web_Examples/12/src/com/dao/ReaderDAO.java", "mask_start_position": 2134, "mask_end_position": 2557, "canonical_solution": "if (readerForm.getId() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.id=\" + readerForm.getId() + \"\";\n } else if (readerForm.getBarcode() != null) {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where r.barcode=\" + readerForm.getBarcode() + \"\";\n }", "pre_mask_code": "package com.dao;\n\nimport com.core.ConnDB;\nimport java.util.*;\nimport java.sql.*;\nimport com.actionForm.ReaderForm;\n\npublic class ReaderDAO {\n\n private ConnDB conn = new ConnDB();\n\n // 查询数据\n public Collection query(String strif) {\n ReaderForm readerForm = null;\n Collection readerColl = new ArrayList();\n String sql = \"\";\n if (strif != \"all\" && strif != null && strif != \"\") {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id where \" + strif + \"\";\n } else {\n sql = \"select r.*,t.name as typename,t.number from tb_reader r left join tb_readerType t on r.typeid=t.id\";\n }\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm = new ReaderForm();\n readerForm.setId(Integer.valueOf(rs.getString(1)));\n readerForm.setName(rs.getString(2));\n readerForm.setSex(rs.getString(3));\n readerForm.setBarcode(rs.getString(4));\n readerForm.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm.setBirthday(birthday == null ? \"\" : birthday);\n readerForm.setPaperType(rs.getString(7));\n readerForm.setPaperNO(rs.getString(8));\n readerForm.setTel(rs.getString(9));\n readerForm.setEmail(rs.getString(10));\n readerForm.setCreateDate(rs.getString(11));\n readerForm.setOperator(rs.getString(12));\n readerForm.setRemark(rs.getString(13));\n readerForm.setTypeid(rs.getInt(14));\n readerForm.setTypename(rs.getString(15));\n readerForm.setNumber(rs.getInt(16));\n readerColl.add(readerForm);\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerColl;\n }\n\n // 用于修改的查询\n public ReaderForm queryM(ReaderForm readerForm) {\n ReaderForm readerForm1 = null;\n String sql = \"\";\n ", "post_mask_code": "\n System.out.println(\"修改读者信息时的SQL:\" + sql);\n ResultSet rs = conn.executeQuery(sql);\n String birthday = \"\";\n try {\n while (rs.next()) {\n readerForm1 = new ReaderForm();\n readerForm1.setId(Integer.valueOf(rs.getString(1)));\n readerForm1.setName(rs.getString(2));\n readerForm1.setSex(rs.getString(3));\n readerForm1.setBarcode(rs.getString(4));\n readerForm1.setVocation(rs.getString(5));\n birthday = rs.getString(6);\n readerForm1.setBirthday(birthday == null ? \"\" : birthday);\n readerForm1.setPaperType(rs.getString(7));\n readerForm1.setPaperNO(rs.getString(8));\n readerForm1.setTel(rs.getString(9));\n readerForm1.setEmail(rs.getString(10));\n readerForm1.setCreateDate(rs.getString(11));\n readerForm1.setOperator(rs.getString(12));\n readerForm1.setRemark(rs.getString(13));\n readerForm1.setTypeid(rs.getInt(14));\n readerForm1.setTypename(rs.getString(15));\n readerForm1.setNumber(rs.getInt(16));\n System.out.println(rs.getString(2));\n }\n } catch (SQLException ex) {\n }\n conn.close();\n return readerForm1;\n }\n\n // 添加数据\n public int insert(ReaderForm readerForm) {\n String sql1 = \"SELECT * FROM tb_reader WHERE barcode='\" + readerForm.getBarcode() + \"'\";\n ResultSet rs = conn.executeQuery(sql1);\n String sql = \"\";\n int falg = 0;\n try {\n if (rs.next()) {\n falg = 2;\n } else {\n if (readerForm.getBirthday() == \"\") {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n } else {\n sql = \"Insert into tb_reader (name,sex,barcode,vocation,birthday,paperType,paperNO,tel,email,createDate,operator,remark,typeid) values('\" + readerForm.getName() + \"','\" + readerForm.getSex() + \"','\" + readerForm.getBarcode() + \"','\" + readerForm.getVocation() + \"','\" + readerForm.getBirthday() + \"','\" + readerForm.getPaperType() + \"','\" + readerForm.getPaperNO() + \"','\" + readerForm.getTel() + \"','\" + readerForm.getEmail() + \"','\" + readerForm.getCreateDate() + \"','\" + readerForm.getOperator() + \"','\" + readerForm.getRemark() + \"',\" + readerForm.getTypeid() + \")\";\n }\n falg = conn.executeUpdate(sql);\n System.out.println(\"添加读者信息的SQL:\" + sql);\n conn.close();\n }\n } catch (SQLException ex) {\n falg = 0;\n }\n System.out.println(\"falg:\" + falg);\n return falg;\n }\n\n // 修改数据\n public int update(ReaderForm readerForm) {\n String sql = \"\";\n if (readerForm.getBirthday() == \"\") {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday=null,paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n } else {\n sql = \"Update tb_reader set sex='\" + readerForm.getSex() + \"',barcode='\" + readerForm.getBarcode() + \"',vocation='\" + readerForm.getVocation() + \"',birthday='\" + readerForm.getBirthday() + \"',paperType='\" + readerForm.getPaperType() + \"',paperNO='\" + readerForm.getPaperNO() + \"',tel='\" + readerForm.getTel() + \"',email='\" + readerForm.getEmail() + \"',remark='\" + readerForm.getRemark() + \"',typeid=\" + readerForm.getTypeid() + \" where id=\" + readerForm.getId() + \"\";\n }\n int falg = conn.executeUpdate(sql);\n System.out.println(\"修改数据时的SQL:\" + sql);\n conn.close();\n return falg;\n }\n\n // 删除数据\n public int delete(ReaderForm readerForm) {\n String sql = \"Delete from tb_reader where id=\" + readerForm.getId() + \"\";\n int falg = conn.executeUpdate(sql);\n System.out.println(\"删除时的SQL:\" + sql);\n return falg;\n }\n}\n"} {"task_id": "Java_1304", "language": "Java", "task_type": "method_signature", "source_file": "java/github/MyCollab/mycollab/mycollab-web/src/main/java/com/mycollab/module/project/view/reports/TicketCrossProjectsSearchPanel.java", "mask_start_position": 6263, "mask_end_position": 6342, "canonical_solution": "@Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() ", "pre_mask_code": "package com.mycollab.module.project.view.reports;\n\nimport com.google.common.collect.Sets;\nimport com.mycollab.common.i18n.GenericI18Enum;\nimport com.mycollab.db.arguments.SearchField;\nimport com.mycollab.db.query.ConstantValueInjector;\nimport com.mycollab.db.query.Param;\nimport com.mycollab.db.query.SearchFieldInfo;\nimport com.mycollab.module.project.ProjectTypeConstants;\nimport com.mycollab.module.project.domain.criteria.ProjectTicketSearchCriteria;\nimport com.mycollab.module.project.i18n.ProjectReportI18nEnum;\nimport com.mycollab.module.project.ui.components.UserProjectListSelect;\nimport com.mycollab.shell.event.ShellEvent;\nimport com.mycollab.vaadin.EventBusFactory;\nimport com.mycollab.vaadin.UserUIContext;\nimport com.mycollab.vaadin.ui.ELabel;\nimport com.mycollab.vaadin.web.ui.*;\nimport com.vaadin.event.ShortcutAction;\nimport com.vaadin.icons.VaadinIcons;\nimport com.vaadin.ui.*;\nimport com.vaadin.ui.themes.ValoTheme;\nimport org.vaadin.viritin.button.MButton;\nimport org.vaadin.viritin.fields.MTextField;\nimport org.vaadin.viritin.layouts.MHorizontalLayout;\nimport java.util.ArrayList;\nimport java.util.List;\nimport static com.mycollab.common.i18n.QueryI18nEnum.CONTAINS;\nimport static com.mycollab.common.i18n.QueryI18nEnum.IN;\n\n/**\n * @author MyCollab Ltd\n * @since 7.0.0\n */\npublic class TicketCrossProjectsSearchPanel extends DefaultGenericSearchPanel {\n\n private ProjectTicketSearchCriteria searchCriteria;\n\n private static Param[] paramFields = new Param[] { ProjectTicketSearchCriteria.p_name, ProjectTicketSearchCriteria.p_startDate, ProjectTicketSearchCriteria.p_endDate, ProjectTicketSearchCriteria.p_dueDate };\n\n protected ComponentContainer buildSearchTitle() {\n return new MHorizontalLayout(ELabel.html(VaadinIcons.CALENDAR_CLOCK.getHtml() + \" \" + UserUIContext.getMessage(ProjectReportI18nEnum.REPORT_TICKET_ASSIGNMENT)).withStyleName(ValoTheme.LABEL_H2, ValoTheme.LABEL_NO_MARGIN));\n }\n\n @Override\n protected SearchLayout createBasicSearchLayout() {\n return new TicketBasicSearchLayout();\n }\n\n @Override\n protected SearchLayout createAdvancedSearchLayout() {\n return new TicketAdvancedSearchLayout();\n }\n\n private class TicketBasicSearchLayout extends BasicSearchLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TextField nameField;\n\n private CheckBox myItemCheckbox;\n\n private TicketBasicSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this);\n }\n\n public void setNameField(String value) {\n nameField.setValue(value);\n }\n\n @Override\n public ComponentContainer constructBody() {\n MHorizontalLayout basicSearchBody = new MHorizontalLayout().withMargin(true);\n Label nameLbl = new Label(UserUIContext.getMessage(GenericI18Enum.FORM_NAME) + \":\");\n basicSearchBody.with(nameLbl).withAlign(nameLbl, Alignment.MIDDLE_LEFT);\n nameField = new MTextField().withPlaceholder(UserUIContext.getMessage(GenericI18Enum.ACTION_QUERY_BY_TEXT)).withWidth(WebUIConstants.DEFAULT_CONTROL_WIDTH);\n basicSearchBody.with(nameField).withAlign(nameField, Alignment.MIDDLE_CENTER);\n myItemCheckbox = new CheckBox(UserUIContext.getMessage(GenericI18Enum.OPT_MY_ITEMS));\n basicSearchBody.with(myItemCheckbox).withAlign(myItemCheckbox, Alignment.MIDDLE_CENTER);\n MButton searchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_SEARCH), clickEvent -> callSearchAction()).withIcon(VaadinIcons.SEARCH).withStyleName(WebThemes.BUTTON_ACTION).withClickShortcut(ShortcutAction.KeyCode.ENTER);\n basicSearchBody.with(searchBtn).withAlign(searchBtn, Alignment.MIDDLE_LEFT);\n MButton cancelBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_CLEAR), clickEvent -> nameField.setValue(\"\")).withStyleName(WebThemes.BUTTON_OPTION);\n basicSearchBody.with(cancelBtn).withAlign(cancelBtn, Alignment.MIDDLE_CENTER);\n if (canSwitchToAdvanceLayout) {\n MButton advancedSearchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_ADVANCED_SEARCH), clickEvent -> moveToAdvancedSearchLayout()).withStyleName(WebThemes.BUTTON_LINK);\n basicSearchBody.with(advancedSearchBtn).withAlign(advancedSearchBtn, Alignment.MIDDLE_CENTER);\n }\n return basicSearchBody;\n }\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {\n List> searchFieldInfos = new ArrayList<>();\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_name, CONTAINS.name(), ConstantValueInjector.valueOf(nameField.getValue().trim())));\n if (myItemCheckbox.getValue()) {\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_assignee, IN.name(), ConstantValueInjector.valueOf(Sets.newHashSet(UserUIContext.getUsername()))));\n }\n EventBusFactory.getInstance().post(new ShellEvent.AddQueryParam(this, searchFieldInfos));\n searchCriteria = SearchFieldInfo.buildSearchCriteria(ProjectTicketSearchCriteria.class, searchFieldInfos);\n return searchCriteria;\n }\n }\n\n private class TicketAdvancedSearchLayout extends DynamicQueryParamLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TicketAdvancedSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this, ProjectTypeConstants.TICKET);\n }\n\n @Override\n protected Class getType() {\n return ProjectTicketSearchCriteria.class;\n }\n\n @Override\n public Param[] getParamFields() {\n return paramFields;\n }\n\n @Override\n protected Component buildSelectionComp(String fieldId) {\n if (\"projectid\".equals(fieldId)) {\n return new UserProjectListSelect();\n }\n return null;\n }\n\n ", "post_mask_code": "{\n searchCriteria = super.fillUpSearchCriteria();\n return searchCriteria;\n }\n }\n}\n"} {"task_id": "Java_1305", "language": "Java", "task_type": "method_body", "source_file": "java/github/MyCollab/mycollab/mycollab-web/src/main/java/com/mycollab/module/project/view/reports/TicketCrossProjectsSearchPanel.java", "mask_start_position": 6104, "mask_end_position": 6253, "canonical_solution": "{\n if (\"projectid\".equals(fieldId)) {\n return new UserProjectListSelect();\n }\n return null;\n }", "pre_mask_code": "package com.mycollab.module.project.view.reports;\n\nimport com.google.common.collect.Sets;\nimport com.mycollab.common.i18n.GenericI18Enum;\nimport com.mycollab.db.arguments.SearchField;\nimport com.mycollab.db.query.ConstantValueInjector;\nimport com.mycollab.db.query.Param;\nimport com.mycollab.db.query.SearchFieldInfo;\nimport com.mycollab.module.project.ProjectTypeConstants;\nimport com.mycollab.module.project.domain.criteria.ProjectTicketSearchCriteria;\nimport com.mycollab.module.project.i18n.ProjectReportI18nEnum;\nimport com.mycollab.module.project.ui.components.UserProjectListSelect;\nimport com.mycollab.shell.event.ShellEvent;\nimport com.mycollab.vaadin.EventBusFactory;\nimport com.mycollab.vaadin.UserUIContext;\nimport com.mycollab.vaadin.ui.ELabel;\nimport com.mycollab.vaadin.web.ui.*;\nimport com.vaadin.event.ShortcutAction;\nimport com.vaadin.icons.VaadinIcons;\nimport com.vaadin.ui.*;\nimport com.vaadin.ui.themes.ValoTheme;\nimport org.vaadin.viritin.button.MButton;\nimport org.vaadin.viritin.fields.MTextField;\nimport org.vaadin.viritin.layouts.MHorizontalLayout;\nimport java.util.ArrayList;\nimport java.util.List;\nimport static com.mycollab.common.i18n.QueryI18nEnum.CONTAINS;\nimport static com.mycollab.common.i18n.QueryI18nEnum.IN;\n\n/**\n * @author MyCollab Ltd\n * @since 7.0.0\n */\npublic class TicketCrossProjectsSearchPanel extends DefaultGenericSearchPanel {\n\n private ProjectTicketSearchCriteria searchCriteria;\n\n private static Param[] paramFields = new Param[] { ProjectTicketSearchCriteria.p_name, ProjectTicketSearchCriteria.p_startDate, ProjectTicketSearchCriteria.p_endDate, ProjectTicketSearchCriteria.p_dueDate };\n\n protected ComponentContainer buildSearchTitle() {\n return new MHorizontalLayout(ELabel.html(VaadinIcons.CALENDAR_CLOCK.getHtml() + \" \" + UserUIContext.getMessage(ProjectReportI18nEnum.REPORT_TICKET_ASSIGNMENT)).withStyleName(ValoTheme.LABEL_H2, ValoTheme.LABEL_NO_MARGIN));\n }\n\n @Override\n protected SearchLayout createBasicSearchLayout() {\n return new TicketBasicSearchLayout();\n }\n\n @Override\n protected SearchLayout createAdvancedSearchLayout() {\n return new TicketAdvancedSearchLayout();\n }\n\n private class TicketBasicSearchLayout extends BasicSearchLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TextField nameField;\n\n private CheckBox myItemCheckbox;\n\n private TicketBasicSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this);\n }\n\n public void setNameField(String value) {\n nameField.setValue(value);\n }\n\n @Override\n public ComponentContainer constructBody() {\n MHorizontalLayout basicSearchBody = new MHorizontalLayout().withMargin(true);\n Label nameLbl = new Label(UserUIContext.getMessage(GenericI18Enum.FORM_NAME) + \":\");\n basicSearchBody.with(nameLbl).withAlign(nameLbl, Alignment.MIDDLE_LEFT);\n nameField = new MTextField().withPlaceholder(UserUIContext.getMessage(GenericI18Enum.ACTION_QUERY_BY_TEXT)).withWidth(WebUIConstants.DEFAULT_CONTROL_WIDTH);\n basicSearchBody.with(nameField).withAlign(nameField, Alignment.MIDDLE_CENTER);\n myItemCheckbox = new CheckBox(UserUIContext.getMessage(GenericI18Enum.OPT_MY_ITEMS));\n basicSearchBody.with(myItemCheckbox).withAlign(myItemCheckbox, Alignment.MIDDLE_CENTER);\n MButton searchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_SEARCH), clickEvent -> callSearchAction()).withIcon(VaadinIcons.SEARCH).withStyleName(WebThemes.BUTTON_ACTION).withClickShortcut(ShortcutAction.KeyCode.ENTER);\n basicSearchBody.with(searchBtn).withAlign(searchBtn, Alignment.MIDDLE_LEFT);\n MButton cancelBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_CLEAR), clickEvent -> nameField.setValue(\"\")).withStyleName(WebThemes.BUTTON_OPTION);\n basicSearchBody.with(cancelBtn).withAlign(cancelBtn, Alignment.MIDDLE_CENTER);\n if (canSwitchToAdvanceLayout) {\n MButton advancedSearchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_ADVANCED_SEARCH), clickEvent -> moveToAdvancedSearchLayout()).withStyleName(WebThemes.BUTTON_LINK);\n basicSearchBody.with(advancedSearchBtn).withAlign(advancedSearchBtn, Alignment.MIDDLE_CENTER);\n }\n return basicSearchBody;\n }\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {\n List> searchFieldInfos = new ArrayList<>();\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_name, CONTAINS.name(), ConstantValueInjector.valueOf(nameField.getValue().trim())));\n if (myItemCheckbox.getValue()) {\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_assignee, IN.name(), ConstantValueInjector.valueOf(Sets.newHashSet(UserUIContext.getUsername()))));\n }\n EventBusFactory.getInstance().post(new ShellEvent.AddQueryParam(this, searchFieldInfos));\n searchCriteria = SearchFieldInfo.buildSearchCriteria(ProjectTicketSearchCriteria.class, searchFieldInfos);\n return searchCriteria;\n }\n }\n\n private class TicketAdvancedSearchLayout extends DynamicQueryParamLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TicketAdvancedSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this, ProjectTypeConstants.TICKET);\n }\n\n @Override\n protected Class getType() {\n return ProjectTicketSearchCriteria.class;\n }\n\n @Override\n public Param[] getParamFields() {\n return paramFields;\n }\n\n @Override\n protected Component buildSelectionComp(String fieldId) ", "post_mask_code": "\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {\n searchCriteria = super.fillUpSearchCriteria();\n return searchCriteria;\n }\n }\n}\n"} {"task_id": "Java_1306", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/MyCollab/mycollab/mycollab-web/src/main/java/com/mycollab/module/project/view/reports/TicketCrossProjectsSearchPanel.java", "mask_start_position": 4639, "mask_end_position": 4925, "canonical_solution": "\n List> searchFieldInfos = new ArrayList<>();\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_name, CONTAINS.name(), ConstantValueInjector.valueOf(nameField.getValue().trim())));", "pre_mask_code": "package com.mycollab.module.project.view.reports;\n\nimport com.google.common.collect.Sets;\nimport com.mycollab.common.i18n.GenericI18Enum;\nimport com.mycollab.db.arguments.SearchField;\nimport com.mycollab.db.query.ConstantValueInjector;\nimport com.mycollab.db.query.Param;\nimport com.mycollab.db.query.SearchFieldInfo;\nimport com.mycollab.module.project.ProjectTypeConstants;\nimport com.mycollab.module.project.domain.criteria.ProjectTicketSearchCriteria;\nimport com.mycollab.module.project.i18n.ProjectReportI18nEnum;\nimport com.mycollab.module.project.ui.components.UserProjectListSelect;\nimport com.mycollab.shell.event.ShellEvent;\nimport com.mycollab.vaadin.EventBusFactory;\nimport com.mycollab.vaadin.UserUIContext;\nimport com.mycollab.vaadin.ui.ELabel;\nimport com.mycollab.vaadin.web.ui.*;\nimport com.vaadin.event.ShortcutAction;\nimport com.vaadin.icons.VaadinIcons;\nimport com.vaadin.ui.*;\nimport com.vaadin.ui.themes.ValoTheme;\nimport org.vaadin.viritin.button.MButton;\nimport org.vaadin.viritin.fields.MTextField;\nimport org.vaadin.viritin.layouts.MHorizontalLayout;\nimport java.util.ArrayList;\nimport java.util.List;\nimport static com.mycollab.common.i18n.QueryI18nEnum.CONTAINS;\nimport static com.mycollab.common.i18n.QueryI18nEnum.IN;\n\n/**\n * @author MyCollab Ltd\n * @since 7.0.0\n */\npublic class TicketCrossProjectsSearchPanel extends DefaultGenericSearchPanel {\n\n private ProjectTicketSearchCriteria searchCriteria;\n\n private static Param[] paramFields = new Param[] { ProjectTicketSearchCriteria.p_name, ProjectTicketSearchCriteria.p_startDate, ProjectTicketSearchCriteria.p_endDate, ProjectTicketSearchCriteria.p_dueDate };\n\n protected ComponentContainer buildSearchTitle() {\n return new MHorizontalLayout(ELabel.html(VaadinIcons.CALENDAR_CLOCK.getHtml() + \" \" + UserUIContext.getMessage(ProjectReportI18nEnum.REPORT_TICKET_ASSIGNMENT)).withStyleName(ValoTheme.LABEL_H2, ValoTheme.LABEL_NO_MARGIN));\n }\n\n @Override\n protected SearchLayout createBasicSearchLayout() {\n return new TicketBasicSearchLayout();\n }\n\n @Override\n protected SearchLayout createAdvancedSearchLayout() {\n return new TicketAdvancedSearchLayout();\n }\n\n private class TicketBasicSearchLayout extends BasicSearchLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TextField nameField;\n\n private CheckBox myItemCheckbox;\n\n private TicketBasicSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this);\n }\n\n public void setNameField(String value) {\n nameField.setValue(value);\n }\n\n @Override\n public ComponentContainer constructBody() {\n MHorizontalLayout basicSearchBody = new MHorizontalLayout().withMargin(true);\n Label nameLbl = new Label(UserUIContext.getMessage(GenericI18Enum.FORM_NAME) + \":\");\n basicSearchBody.with(nameLbl).withAlign(nameLbl, Alignment.MIDDLE_LEFT);\n nameField = new MTextField().withPlaceholder(UserUIContext.getMessage(GenericI18Enum.ACTION_QUERY_BY_TEXT)).withWidth(WebUIConstants.DEFAULT_CONTROL_WIDTH);\n basicSearchBody.with(nameField).withAlign(nameField, Alignment.MIDDLE_CENTER);\n myItemCheckbox = new CheckBox(UserUIContext.getMessage(GenericI18Enum.OPT_MY_ITEMS));\n basicSearchBody.with(myItemCheckbox).withAlign(myItemCheckbox, Alignment.MIDDLE_CENTER);\n MButton searchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_SEARCH), clickEvent -> callSearchAction()).withIcon(VaadinIcons.SEARCH).withStyleName(WebThemes.BUTTON_ACTION).withClickShortcut(ShortcutAction.KeyCode.ENTER);\n basicSearchBody.with(searchBtn).withAlign(searchBtn, Alignment.MIDDLE_LEFT);\n MButton cancelBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_CLEAR), clickEvent -> nameField.setValue(\"\")).withStyleName(WebThemes.BUTTON_OPTION);\n basicSearchBody.with(cancelBtn).withAlign(cancelBtn, Alignment.MIDDLE_CENTER);\n if (canSwitchToAdvanceLayout) {\n MButton advancedSearchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_ADVANCED_SEARCH), clickEvent -> moveToAdvancedSearchLayout()).withStyleName(WebThemes.BUTTON_LINK);\n basicSearchBody.with(advancedSearchBtn).withAlign(advancedSearchBtn, Alignment.MIDDLE_CENTER);\n }\n return basicSearchBody;\n }\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {", "post_mask_code": "\n if (myItemCheckbox.getValue()) {\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_assignee, IN.name(), ConstantValueInjector.valueOf(Sets.newHashSet(UserUIContext.getUsername()))));\n }\n EventBusFactory.getInstance().post(new ShellEvent.AddQueryParam(this, searchFieldInfos));\n searchCriteria = SearchFieldInfo.buildSearchCriteria(ProjectTicketSearchCriteria.class, searchFieldInfos);\n return searchCriteria;\n }\n }\n\n private class TicketAdvancedSearchLayout extends DynamicQueryParamLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TicketAdvancedSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this, ProjectTypeConstants.TICKET);\n }\n\n @Override\n protected Class getType() {\n return ProjectTicketSearchCriteria.class;\n }\n\n @Override\n public Param[] getParamFields() {\n return paramFields;\n }\n\n @Override\n protected Component buildSelectionComp(String fieldId) {\n if (\"projectid\".equals(fieldId)) {\n return new UserProjectListSelect();\n }\n return null;\n }\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {\n searchCriteria = super.fillUpSearchCriteria();\n return searchCriteria;\n }\n }\n}\n"} {"task_id": "Java_1307", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/MyCollab/mycollab/mycollab-web/src/main/java/com/mycollab/module/project/view/reports/TicketCrossProjectsSearchPanel.java", "mask_start_position": 4938, "mask_end_position": 5290, "canonical_solution": "if (myItemCheckbox.getValue()) {\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_assignee, IN.name(), ConstantValueInjector.valueOf(Sets.newHashSet(UserUIContext.getUsername()))));\n }\n EventBusFactory.getInstance().post(new ShellEvent.AddQueryParam(this, searchFieldInfos));", "pre_mask_code": "package com.mycollab.module.project.view.reports;\n\nimport com.google.common.collect.Sets;\nimport com.mycollab.common.i18n.GenericI18Enum;\nimport com.mycollab.db.arguments.SearchField;\nimport com.mycollab.db.query.ConstantValueInjector;\nimport com.mycollab.db.query.Param;\nimport com.mycollab.db.query.SearchFieldInfo;\nimport com.mycollab.module.project.ProjectTypeConstants;\nimport com.mycollab.module.project.domain.criteria.ProjectTicketSearchCriteria;\nimport com.mycollab.module.project.i18n.ProjectReportI18nEnum;\nimport com.mycollab.module.project.ui.components.UserProjectListSelect;\nimport com.mycollab.shell.event.ShellEvent;\nimport com.mycollab.vaadin.EventBusFactory;\nimport com.mycollab.vaadin.UserUIContext;\nimport com.mycollab.vaadin.ui.ELabel;\nimport com.mycollab.vaadin.web.ui.*;\nimport com.vaadin.event.ShortcutAction;\nimport com.vaadin.icons.VaadinIcons;\nimport com.vaadin.ui.*;\nimport com.vaadin.ui.themes.ValoTheme;\nimport org.vaadin.viritin.button.MButton;\nimport org.vaadin.viritin.fields.MTextField;\nimport org.vaadin.viritin.layouts.MHorizontalLayout;\nimport java.util.ArrayList;\nimport java.util.List;\nimport static com.mycollab.common.i18n.QueryI18nEnum.CONTAINS;\nimport static com.mycollab.common.i18n.QueryI18nEnum.IN;\n\n/**\n * @author MyCollab Ltd\n * @since 7.0.0\n */\npublic class TicketCrossProjectsSearchPanel extends DefaultGenericSearchPanel {\n\n private ProjectTicketSearchCriteria searchCriteria;\n\n private static Param[] paramFields = new Param[] { ProjectTicketSearchCriteria.p_name, ProjectTicketSearchCriteria.p_startDate, ProjectTicketSearchCriteria.p_endDate, ProjectTicketSearchCriteria.p_dueDate };\n\n protected ComponentContainer buildSearchTitle() {\n return new MHorizontalLayout(ELabel.html(VaadinIcons.CALENDAR_CLOCK.getHtml() + \" \" + UserUIContext.getMessage(ProjectReportI18nEnum.REPORT_TICKET_ASSIGNMENT)).withStyleName(ValoTheme.LABEL_H2, ValoTheme.LABEL_NO_MARGIN));\n }\n\n @Override\n protected SearchLayout createBasicSearchLayout() {\n return new TicketBasicSearchLayout();\n }\n\n @Override\n protected SearchLayout createAdvancedSearchLayout() {\n return new TicketAdvancedSearchLayout();\n }\n\n private class TicketBasicSearchLayout extends BasicSearchLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TextField nameField;\n\n private CheckBox myItemCheckbox;\n\n private TicketBasicSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this);\n }\n\n public void setNameField(String value) {\n nameField.setValue(value);\n }\n\n @Override\n public ComponentContainer constructBody() {\n MHorizontalLayout basicSearchBody = new MHorizontalLayout().withMargin(true);\n Label nameLbl = new Label(UserUIContext.getMessage(GenericI18Enum.FORM_NAME) + \":\");\n basicSearchBody.with(nameLbl).withAlign(nameLbl, Alignment.MIDDLE_LEFT);\n nameField = new MTextField().withPlaceholder(UserUIContext.getMessage(GenericI18Enum.ACTION_QUERY_BY_TEXT)).withWidth(WebUIConstants.DEFAULT_CONTROL_WIDTH);\n basicSearchBody.with(nameField).withAlign(nameField, Alignment.MIDDLE_CENTER);\n myItemCheckbox = new CheckBox(UserUIContext.getMessage(GenericI18Enum.OPT_MY_ITEMS));\n basicSearchBody.with(myItemCheckbox).withAlign(myItemCheckbox, Alignment.MIDDLE_CENTER);\n MButton searchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_SEARCH), clickEvent -> callSearchAction()).withIcon(VaadinIcons.SEARCH).withStyleName(WebThemes.BUTTON_ACTION).withClickShortcut(ShortcutAction.KeyCode.ENTER);\n basicSearchBody.with(searchBtn).withAlign(searchBtn, Alignment.MIDDLE_LEFT);\n MButton cancelBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_CLEAR), clickEvent -> nameField.setValue(\"\")).withStyleName(WebThemes.BUTTON_OPTION);\n basicSearchBody.with(cancelBtn).withAlign(cancelBtn, Alignment.MIDDLE_CENTER);\n if (canSwitchToAdvanceLayout) {\n MButton advancedSearchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_ADVANCED_SEARCH), clickEvent -> moveToAdvancedSearchLayout()).withStyleName(WebThemes.BUTTON_LINK);\n basicSearchBody.with(advancedSearchBtn).withAlign(advancedSearchBtn, Alignment.MIDDLE_CENTER);\n }\n return basicSearchBody;\n }\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {\n List> searchFieldInfos = new ArrayList<>();\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_name, CONTAINS.name(), ConstantValueInjector.valueOf(nameField.getValue().trim())));\n ", "post_mask_code": "\n searchCriteria = SearchFieldInfo.buildSearchCriteria(ProjectTicketSearchCriteria.class, searchFieldInfos);\n return searchCriteria;\n }\n }\n\n private class TicketAdvancedSearchLayout extends DynamicQueryParamLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TicketAdvancedSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this, ProjectTypeConstants.TICKET);\n }\n\n @Override\n protected Class getType() {\n return ProjectTicketSearchCriteria.class;\n }\n\n @Override\n public Param[] getParamFields() {\n return paramFields;\n }\n\n @Override\n protected Component buildSelectionComp(String fieldId) {\n if (\"projectid\".equals(fieldId)) {\n return new UserProjectListSelect();\n }\n return null;\n }\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {\n searchCriteria = super.fillUpSearchCriteria();\n return searchCriteria;\n }\n }\n}\n"} {"task_id": "Java_1308", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/MyCollab/mycollab/mycollab-web/src/main/java/com/mycollab/module/project/view/reports/TicketCrossProjectsSearchPanel.java", "mask_start_position": 5303, "mask_end_position": 5454, "canonical_solution": "searchCriteria = SearchFieldInfo.buildSearchCriteria(ProjectTicketSearchCriteria.class, searchFieldInfos);\n return searchCriteria;\n }", "pre_mask_code": "package com.mycollab.module.project.view.reports;\n\nimport com.google.common.collect.Sets;\nimport com.mycollab.common.i18n.GenericI18Enum;\nimport com.mycollab.db.arguments.SearchField;\nimport com.mycollab.db.query.ConstantValueInjector;\nimport com.mycollab.db.query.Param;\nimport com.mycollab.db.query.SearchFieldInfo;\nimport com.mycollab.module.project.ProjectTypeConstants;\nimport com.mycollab.module.project.domain.criteria.ProjectTicketSearchCriteria;\nimport com.mycollab.module.project.i18n.ProjectReportI18nEnum;\nimport com.mycollab.module.project.ui.components.UserProjectListSelect;\nimport com.mycollab.shell.event.ShellEvent;\nimport com.mycollab.vaadin.EventBusFactory;\nimport com.mycollab.vaadin.UserUIContext;\nimport com.mycollab.vaadin.ui.ELabel;\nimport com.mycollab.vaadin.web.ui.*;\nimport com.vaadin.event.ShortcutAction;\nimport com.vaadin.icons.VaadinIcons;\nimport com.vaadin.ui.*;\nimport com.vaadin.ui.themes.ValoTheme;\nimport org.vaadin.viritin.button.MButton;\nimport org.vaadin.viritin.fields.MTextField;\nimport org.vaadin.viritin.layouts.MHorizontalLayout;\nimport java.util.ArrayList;\nimport java.util.List;\nimport static com.mycollab.common.i18n.QueryI18nEnum.CONTAINS;\nimport static com.mycollab.common.i18n.QueryI18nEnum.IN;\n\n/**\n * @author MyCollab Ltd\n * @since 7.0.0\n */\npublic class TicketCrossProjectsSearchPanel extends DefaultGenericSearchPanel {\n\n private ProjectTicketSearchCriteria searchCriteria;\n\n private static Param[] paramFields = new Param[] { ProjectTicketSearchCriteria.p_name, ProjectTicketSearchCriteria.p_startDate, ProjectTicketSearchCriteria.p_endDate, ProjectTicketSearchCriteria.p_dueDate };\n\n protected ComponentContainer buildSearchTitle() {\n return new MHorizontalLayout(ELabel.html(VaadinIcons.CALENDAR_CLOCK.getHtml() + \" \" + UserUIContext.getMessage(ProjectReportI18nEnum.REPORT_TICKET_ASSIGNMENT)).withStyleName(ValoTheme.LABEL_H2, ValoTheme.LABEL_NO_MARGIN));\n }\n\n @Override\n protected SearchLayout createBasicSearchLayout() {\n return new TicketBasicSearchLayout();\n }\n\n @Override\n protected SearchLayout createAdvancedSearchLayout() {\n return new TicketAdvancedSearchLayout();\n }\n\n private class TicketBasicSearchLayout extends BasicSearchLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TextField nameField;\n\n private CheckBox myItemCheckbox;\n\n private TicketBasicSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this);\n }\n\n public void setNameField(String value) {\n nameField.setValue(value);\n }\n\n @Override\n public ComponentContainer constructBody() {\n MHorizontalLayout basicSearchBody = new MHorizontalLayout().withMargin(true);\n Label nameLbl = new Label(UserUIContext.getMessage(GenericI18Enum.FORM_NAME) + \":\");\n basicSearchBody.with(nameLbl).withAlign(nameLbl, Alignment.MIDDLE_LEFT);\n nameField = new MTextField().withPlaceholder(UserUIContext.getMessage(GenericI18Enum.ACTION_QUERY_BY_TEXT)).withWidth(WebUIConstants.DEFAULT_CONTROL_WIDTH);\n basicSearchBody.with(nameField).withAlign(nameField, Alignment.MIDDLE_CENTER);\n myItemCheckbox = new CheckBox(UserUIContext.getMessage(GenericI18Enum.OPT_MY_ITEMS));\n basicSearchBody.with(myItemCheckbox).withAlign(myItemCheckbox, Alignment.MIDDLE_CENTER);\n MButton searchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_SEARCH), clickEvent -> callSearchAction()).withIcon(VaadinIcons.SEARCH).withStyleName(WebThemes.BUTTON_ACTION).withClickShortcut(ShortcutAction.KeyCode.ENTER);\n basicSearchBody.with(searchBtn).withAlign(searchBtn, Alignment.MIDDLE_LEFT);\n MButton cancelBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_CLEAR), clickEvent -> nameField.setValue(\"\")).withStyleName(WebThemes.BUTTON_OPTION);\n basicSearchBody.with(cancelBtn).withAlign(cancelBtn, Alignment.MIDDLE_CENTER);\n if (canSwitchToAdvanceLayout) {\n MButton advancedSearchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_ADVANCED_SEARCH), clickEvent -> moveToAdvancedSearchLayout()).withStyleName(WebThemes.BUTTON_LINK);\n basicSearchBody.with(advancedSearchBtn).withAlign(advancedSearchBtn, Alignment.MIDDLE_CENTER);\n }\n return basicSearchBody;\n }\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {\n List> searchFieldInfos = new ArrayList<>();\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_name, CONTAINS.name(), ConstantValueInjector.valueOf(nameField.getValue().trim())));\n if (myItemCheckbox.getValue()) {\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_assignee, IN.name(), ConstantValueInjector.valueOf(Sets.newHashSet(UserUIContext.getUsername()))));\n }\n EventBusFactory.getInstance().post(new ShellEvent.AddQueryParam(this, searchFieldInfos));\n ", "post_mask_code": "\n }\n\n private class TicketAdvancedSearchLayout extends DynamicQueryParamLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TicketAdvancedSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this, ProjectTypeConstants.TICKET);\n }\n\n @Override\n protected Class getType() {\n return ProjectTicketSearchCriteria.class;\n }\n\n @Override\n public Param[] getParamFields() {\n return paramFields;\n }\n\n @Override\n protected Component buildSelectionComp(String fieldId) {\n if (\"projectid\".equals(fieldId)) {\n return new UserProjectListSelect();\n }\n return null;\n }\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {\n searchCriteria = super.fillUpSearchCriteria();\n return searchCriteria;\n }\n }\n}\n"} {"task_id": "Java_1309", "language": "Java", "task_type": "single_line", "source_file": "java/github/MyCollab/mycollab/mycollab-web/src/main/java/com/mycollab/module/project/view/reports/TicketCrossProjectsSearchPanel.java", "mask_start_position": 2687, "mask_end_position": 2711, "canonical_solution": "meField.setValue(value);", "pre_mask_code": "package com.mycollab.module.project.view.reports;\n\nimport com.google.common.collect.Sets;\nimport com.mycollab.common.i18n.GenericI18Enum;\nimport com.mycollab.db.arguments.SearchField;\nimport com.mycollab.db.query.ConstantValueInjector;\nimport com.mycollab.db.query.Param;\nimport com.mycollab.db.query.SearchFieldInfo;\nimport com.mycollab.module.project.ProjectTypeConstants;\nimport com.mycollab.module.project.domain.criteria.ProjectTicketSearchCriteria;\nimport com.mycollab.module.project.i18n.ProjectReportI18nEnum;\nimport com.mycollab.module.project.ui.components.UserProjectListSelect;\nimport com.mycollab.shell.event.ShellEvent;\nimport com.mycollab.vaadin.EventBusFactory;\nimport com.mycollab.vaadin.UserUIContext;\nimport com.mycollab.vaadin.ui.ELabel;\nimport com.mycollab.vaadin.web.ui.*;\nimport com.vaadin.event.ShortcutAction;\nimport com.vaadin.icons.VaadinIcons;\nimport com.vaadin.ui.*;\nimport com.vaadin.ui.themes.ValoTheme;\nimport org.vaadin.viritin.button.MButton;\nimport org.vaadin.viritin.fields.MTextField;\nimport org.vaadin.viritin.layouts.MHorizontalLayout;\nimport java.util.ArrayList;\nimport java.util.List;\nimport static com.mycollab.common.i18n.QueryI18nEnum.CONTAINS;\nimport static com.mycollab.common.i18n.QueryI18nEnum.IN;\n\n/**\n * @author MyCollab Ltd\n * @since 7.0.0\n */\npublic class TicketCrossProjectsSearchPanel extends DefaultGenericSearchPanel {\n\n private ProjectTicketSearchCriteria searchCriteria;\n\n private static Param[] paramFields = new Param[] { ProjectTicketSearchCriteria.p_name, ProjectTicketSearchCriteria.p_startDate, ProjectTicketSearchCriteria.p_endDate, ProjectTicketSearchCriteria.p_dueDate };\n\n protected ComponentContainer buildSearchTitle() {\n return new MHorizontalLayout(ELabel.html(VaadinIcons.CALENDAR_CLOCK.getHtml() + \" \" + UserUIContext.getMessage(ProjectReportI18nEnum.REPORT_TICKET_ASSIGNMENT)).withStyleName(ValoTheme.LABEL_H2, ValoTheme.LABEL_NO_MARGIN));\n }\n\n @Override\n protected SearchLayout createBasicSearchLayout() {\n return new TicketBasicSearchLayout();\n }\n\n @Override\n protected SearchLayout createAdvancedSearchLayout() {\n return new TicketAdvancedSearchLayout();\n }\n\n private class TicketBasicSearchLayout extends BasicSearchLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TextField nameField;\n\n private CheckBox myItemCheckbox;\n\n private TicketBasicSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this);\n }\n\n public void setNameField(String value) {\n na", "post_mask_code": "\n }\n\n @Override\n public ComponentContainer constructBody() {\n MHorizontalLayout basicSearchBody = new MHorizontalLayout().withMargin(true);\n Label nameLbl = new Label(UserUIContext.getMessage(GenericI18Enum.FORM_NAME) + \":\");\n basicSearchBody.with(nameLbl).withAlign(nameLbl, Alignment.MIDDLE_LEFT);\n nameField = new MTextField().withPlaceholder(UserUIContext.getMessage(GenericI18Enum.ACTION_QUERY_BY_TEXT)).withWidth(WebUIConstants.DEFAULT_CONTROL_WIDTH);\n basicSearchBody.with(nameField).withAlign(nameField, Alignment.MIDDLE_CENTER);\n myItemCheckbox = new CheckBox(UserUIContext.getMessage(GenericI18Enum.OPT_MY_ITEMS));\n basicSearchBody.with(myItemCheckbox).withAlign(myItemCheckbox, Alignment.MIDDLE_CENTER);\n MButton searchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_SEARCH), clickEvent -> callSearchAction()).withIcon(VaadinIcons.SEARCH).withStyleName(WebThemes.BUTTON_ACTION).withClickShortcut(ShortcutAction.KeyCode.ENTER);\n basicSearchBody.with(searchBtn).withAlign(searchBtn, Alignment.MIDDLE_LEFT);\n MButton cancelBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_CLEAR), clickEvent -> nameField.setValue(\"\")).withStyleName(WebThemes.BUTTON_OPTION);\n basicSearchBody.with(cancelBtn).withAlign(cancelBtn, Alignment.MIDDLE_CENTER);\n if (canSwitchToAdvanceLayout) {\n MButton advancedSearchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_ADVANCED_SEARCH), clickEvent -> moveToAdvancedSearchLayout()).withStyleName(WebThemes.BUTTON_LINK);\n basicSearchBody.with(advancedSearchBtn).withAlign(advancedSearchBtn, Alignment.MIDDLE_CENTER);\n }\n return basicSearchBody;\n }\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {\n List> searchFieldInfos = new ArrayList<>();\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_name, CONTAINS.name(), ConstantValueInjector.valueOf(nameField.getValue().trim())));\n if (myItemCheckbox.getValue()) {\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_assignee, IN.name(), ConstantValueInjector.valueOf(Sets.newHashSet(UserUIContext.getUsername()))));\n }\n EventBusFactory.getInstance().post(new ShellEvent.AddQueryParam(this, searchFieldInfos));\n searchCriteria = SearchFieldInfo.buildSearchCriteria(ProjectTicketSearchCriteria.class, searchFieldInfos);\n return searchCriteria;\n }\n }\n\n private class TicketAdvancedSearchLayout extends DynamicQueryParamLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TicketAdvancedSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this, ProjectTypeConstants.TICKET);\n }\n\n @Override\n protected Class getType() {\n return ProjectTicketSearchCriteria.class;\n }\n\n @Override\n public Param[] getParamFields() {\n return paramFields;\n }\n\n @Override\n protected Component buildSelectionComp(String fieldId) {\n if (\"projectid\".equals(fieldId)) {\n return new UserProjectListSelect();\n }\n return null;\n }\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {\n searchCriteria = super.fillUpSearchCriteria();\n return searchCriteria;\n }\n }\n}\n"} {"task_id": "Java_1310", "language": "Java", "task_type": "if_statement", "source_file": "java/github/MyCollab/mycollab/mycollab-web/src/main/java/com/mycollab/module/project/view/reports/TicketCrossProjectsSearchPanel.java", "mask_start_position": 4938, "mask_end_position": 5188, "canonical_solution": "if (myItemCheckbox.getValue()) {\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_assignee, IN.name(), ConstantValueInjector.valueOf(Sets.newHashSet(UserUIContext.getUsername()))));\n }", "pre_mask_code": "package com.mycollab.module.project.view.reports;\n\nimport com.google.common.collect.Sets;\nimport com.mycollab.common.i18n.GenericI18Enum;\nimport com.mycollab.db.arguments.SearchField;\nimport com.mycollab.db.query.ConstantValueInjector;\nimport com.mycollab.db.query.Param;\nimport com.mycollab.db.query.SearchFieldInfo;\nimport com.mycollab.module.project.ProjectTypeConstants;\nimport com.mycollab.module.project.domain.criteria.ProjectTicketSearchCriteria;\nimport com.mycollab.module.project.i18n.ProjectReportI18nEnum;\nimport com.mycollab.module.project.ui.components.UserProjectListSelect;\nimport com.mycollab.shell.event.ShellEvent;\nimport com.mycollab.vaadin.EventBusFactory;\nimport com.mycollab.vaadin.UserUIContext;\nimport com.mycollab.vaadin.ui.ELabel;\nimport com.mycollab.vaadin.web.ui.*;\nimport com.vaadin.event.ShortcutAction;\nimport com.vaadin.icons.VaadinIcons;\nimport com.vaadin.ui.*;\nimport com.vaadin.ui.themes.ValoTheme;\nimport org.vaadin.viritin.button.MButton;\nimport org.vaadin.viritin.fields.MTextField;\nimport org.vaadin.viritin.layouts.MHorizontalLayout;\nimport java.util.ArrayList;\nimport java.util.List;\nimport static com.mycollab.common.i18n.QueryI18nEnum.CONTAINS;\nimport static com.mycollab.common.i18n.QueryI18nEnum.IN;\n\n/**\n * @author MyCollab Ltd\n * @since 7.0.0\n */\npublic class TicketCrossProjectsSearchPanel extends DefaultGenericSearchPanel {\n\n private ProjectTicketSearchCriteria searchCriteria;\n\n private static Param[] paramFields = new Param[] { ProjectTicketSearchCriteria.p_name, ProjectTicketSearchCriteria.p_startDate, ProjectTicketSearchCriteria.p_endDate, ProjectTicketSearchCriteria.p_dueDate };\n\n protected ComponentContainer buildSearchTitle() {\n return new MHorizontalLayout(ELabel.html(VaadinIcons.CALENDAR_CLOCK.getHtml() + \" \" + UserUIContext.getMessage(ProjectReportI18nEnum.REPORT_TICKET_ASSIGNMENT)).withStyleName(ValoTheme.LABEL_H2, ValoTheme.LABEL_NO_MARGIN));\n }\n\n @Override\n protected SearchLayout createBasicSearchLayout() {\n return new TicketBasicSearchLayout();\n }\n\n @Override\n protected SearchLayout createAdvancedSearchLayout() {\n return new TicketAdvancedSearchLayout();\n }\n\n private class TicketBasicSearchLayout extends BasicSearchLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TextField nameField;\n\n private CheckBox myItemCheckbox;\n\n private TicketBasicSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this);\n }\n\n public void setNameField(String value) {\n nameField.setValue(value);\n }\n\n @Override\n public ComponentContainer constructBody() {\n MHorizontalLayout basicSearchBody = new MHorizontalLayout().withMargin(true);\n Label nameLbl = new Label(UserUIContext.getMessage(GenericI18Enum.FORM_NAME) + \":\");\n basicSearchBody.with(nameLbl).withAlign(nameLbl, Alignment.MIDDLE_LEFT);\n nameField = new MTextField().withPlaceholder(UserUIContext.getMessage(GenericI18Enum.ACTION_QUERY_BY_TEXT)).withWidth(WebUIConstants.DEFAULT_CONTROL_WIDTH);\n basicSearchBody.with(nameField).withAlign(nameField, Alignment.MIDDLE_CENTER);\n myItemCheckbox = new CheckBox(UserUIContext.getMessage(GenericI18Enum.OPT_MY_ITEMS));\n basicSearchBody.with(myItemCheckbox).withAlign(myItemCheckbox, Alignment.MIDDLE_CENTER);\n MButton searchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_SEARCH), clickEvent -> callSearchAction()).withIcon(VaadinIcons.SEARCH).withStyleName(WebThemes.BUTTON_ACTION).withClickShortcut(ShortcutAction.KeyCode.ENTER);\n basicSearchBody.with(searchBtn).withAlign(searchBtn, Alignment.MIDDLE_LEFT);\n MButton cancelBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_CLEAR), clickEvent -> nameField.setValue(\"\")).withStyleName(WebThemes.BUTTON_OPTION);\n basicSearchBody.with(cancelBtn).withAlign(cancelBtn, Alignment.MIDDLE_CENTER);\n if (canSwitchToAdvanceLayout) {\n MButton advancedSearchBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_ADVANCED_SEARCH), clickEvent -> moveToAdvancedSearchLayout()).withStyleName(WebThemes.BUTTON_LINK);\n basicSearchBody.with(advancedSearchBtn).withAlign(advancedSearchBtn, Alignment.MIDDLE_CENTER);\n }\n return basicSearchBody;\n }\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {\n List> searchFieldInfos = new ArrayList<>();\n searchFieldInfos.add(new SearchFieldInfo(SearchField.AND, ProjectTicketSearchCriteria.p_name, CONTAINS.name(), ConstantValueInjector.valueOf(nameField.getValue().trim())));\n ", "post_mask_code": "\n EventBusFactory.getInstance().post(new ShellEvent.AddQueryParam(this, searchFieldInfos));\n searchCriteria = SearchFieldInfo.buildSearchCriteria(ProjectTicketSearchCriteria.class, searchFieldInfos);\n return searchCriteria;\n }\n }\n\n private class TicketAdvancedSearchLayout extends DynamicQueryParamLayout {\n\n private static final long serialVersionUID = 1L;\n\n private TicketAdvancedSearchLayout() {\n super(TicketCrossProjectsSearchPanel.this, ProjectTypeConstants.TICKET);\n }\n\n @Override\n protected Class getType() {\n return ProjectTicketSearchCriteria.class;\n }\n\n @Override\n public Param[] getParamFields() {\n return paramFields;\n }\n\n @Override\n protected Component buildSelectionComp(String fieldId) {\n if (\"projectid\".equals(fieldId)) {\n return new UserProjectListSelect();\n }\n return null;\n }\n\n @Override\n protected ProjectTicketSearchCriteria fillUpSearchCriteria() {\n searchCriteria = super.fillUpSearchCriteria();\n return searchCriteria;\n }\n }\n}\n"} {"task_id": "Java_1311", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eccentricdevotion/TARDIS/src/main/java/me/eccentric_nz/TARDIS/enumeration/BiomeLookup.java", "mask_start_position": 1441, "mask_end_position": 1489, "canonical_solution": "public static BiomeLookup getBiome(String data) ", "pre_mask_code": "package me.eccentric_nz.TARDIS.enumeration;\n\nimport com.google.common.collect.Maps;\nimport java.util.Map;\n\n/**\n * @author eccentric_nz\n */\npublic enum BiomeLookup {\n\n CACTUS_B(\"DESERT\", \"DESERT_HILLS\"),\n DIRT_B(\"MOUNTAINS\", \"MODIFIED_GRAVELLY_MOUNTAINS\"),\n PODZOL_B(\"GIANT_TREE_TAIGA\", \"GIANT_TREE_TAIGA_HILLS\"),\n RED_SAND_B(\"BADLANDS\", \"BADLANDS_PLATEAU\"),\n ACACIA_LOG_B(\"SAVANNA\", \"SHATTERED_SAVANNA\"),\n DARK_OAK_LOG_B(\"DARK_FOREST\", \"DARK_FOREST_HILLS\"),\n OAK_LOG_B(\"FOREST\", \"WOODED_HILLS\"),\n SPRUCE_LOG_B(\"TAIGA\", \"TAIGA_HILLS\"),\n BIRCH_LOG_B(\"BIRCH_FOREST\", \"BIRCH_FOREST_HILLS\"),\n JUNGLE_LOG_B(\"JUNGLE\", \"JUNGLE_HILLS\"),\n SAND_B(\"BEACH\", \"SNOWY_BEACH\"),\n SNOW_BLOCK_B(\"SNOWY_TAIGA\", \"SNOWY_TAIGA_HILLS\"),\n WATER_BUCKET_B(\"OCEAN\", \"DEEP_OCEAN\"),\n RED_TULIP_B(\"FLOWER_FOREST\", \"TALL_BIRCH_HILLS\"),\n SUNFLOWER_B(\"PLAINS\", \"SUNFLOWER_PLAINS\"),\n ICE_B(\"SNOWY_TUNDRA\", \"ICE_SPIKES\"),\n MYCELIUM_B(\"MUSHROOM_FIELDS\", \"MUSHROOM_FIELD_SHORE\"),\n LILY_PAD_B(\"SWAMP\", \"SWAMP_HILLS\"),\n BAMBOO_B(\"BAMBOO_JUNGLE\", \"BAMBOO_JUNGLE_HILLS\");\n\n public final static Map BY_REG = Maps.newHashMap();\n\n static {\n for (BiomeLookup bm : values()) {\n BY_REG.put(bm.getRegular(), bm);\n }\n }\n\n String regular;\n\n String upper;\n\n BiomeLookup(String regular, String upper) {\n this.regular = regular;\n this.upper = upper;\n }\n\n ", "post_mask_code": "{\n return BY_REG.get(data);\n }\n\n public String getRegular() {\n return regular;\n }\n\n public String getUpper() {\n return upper;\n }\n}\n"} {"task_id": "Java_1312", "language": "Java", "task_type": "method_body", "source_file": "java/github/eccentricdevotion/TARDIS/src/main/java/me/eccentric_nz/TARDIS/enumeration/BiomeLookup.java", "mask_start_position": 1489, "mask_end_position": 1529, "canonical_solution": "{\n return BY_REG.get(data);\n }", "pre_mask_code": "package me.eccentric_nz.TARDIS.enumeration;\n\nimport com.google.common.collect.Maps;\nimport java.util.Map;\n\n/**\n * @author eccentric_nz\n */\npublic enum BiomeLookup {\n\n CACTUS_B(\"DESERT\", \"DESERT_HILLS\"),\n DIRT_B(\"MOUNTAINS\", \"MODIFIED_GRAVELLY_MOUNTAINS\"),\n PODZOL_B(\"GIANT_TREE_TAIGA\", \"GIANT_TREE_TAIGA_HILLS\"),\n RED_SAND_B(\"BADLANDS\", \"BADLANDS_PLATEAU\"),\n ACACIA_LOG_B(\"SAVANNA\", \"SHATTERED_SAVANNA\"),\n DARK_OAK_LOG_B(\"DARK_FOREST\", \"DARK_FOREST_HILLS\"),\n OAK_LOG_B(\"FOREST\", \"WOODED_HILLS\"),\n SPRUCE_LOG_B(\"TAIGA\", \"TAIGA_HILLS\"),\n BIRCH_LOG_B(\"BIRCH_FOREST\", \"BIRCH_FOREST_HILLS\"),\n JUNGLE_LOG_B(\"JUNGLE\", \"JUNGLE_HILLS\"),\n SAND_B(\"BEACH\", \"SNOWY_BEACH\"),\n SNOW_BLOCK_B(\"SNOWY_TAIGA\", \"SNOWY_TAIGA_HILLS\"),\n WATER_BUCKET_B(\"OCEAN\", \"DEEP_OCEAN\"),\n RED_TULIP_B(\"FLOWER_FOREST\", \"TALL_BIRCH_HILLS\"),\n SUNFLOWER_B(\"PLAINS\", \"SUNFLOWER_PLAINS\"),\n ICE_B(\"SNOWY_TUNDRA\", \"ICE_SPIKES\"),\n MYCELIUM_B(\"MUSHROOM_FIELDS\", \"MUSHROOM_FIELD_SHORE\"),\n LILY_PAD_B(\"SWAMP\", \"SWAMP_HILLS\"),\n BAMBOO_B(\"BAMBOO_JUNGLE\", \"BAMBOO_JUNGLE_HILLS\");\n\n public final static Map BY_REG = Maps.newHashMap();\n\n static {\n for (BiomeLookup bm : values()) {\n BY_REG.put(bm.getRegular(), bm);\n }\n }\n\n String regular;\n\n String upper;\n\n BiomeLookup(String regular, String upper) {\n this.regular = regular;\n this.upper = upper;\n }\n\n public static BiomeLookup getBiome(String data) ", "post_mask_code": "\n\n public String getRegular() {\n return regular;\n }\n\n public String getUpper() {\n return upper;\n }\n}\n"} {"task_id": "Java_1313", "language": "Java", "task_type": "single_line", "source_file": "java/github/eccentricdevotion/TARDIS/src/main/java/me/eccentric_nz/TARDIS/enumeration/BiomeLookup.java", "mask_start_position": 1521, "mask_end_position": 1523, "canonical_solution": ");", "pre_mask_code": "package me.eccentric_nz.TARDIS.enumeration;\n\nimport com.google.common.collect.Maps;\nimport java.util.Map;\n\n/**\n * @author eccentric_nz\n */\npublic enum BiomeLookup {\n\n CACTUS_B(\"DESERT\", \"DESERT_HILLS\"),\n DIRT_B(\"MOUNTAINS\", \"MODIFIED_GRAVELLY_MOUNTAINS\"),\n PODZOL_B(\"GIANT_TREE_TAIGA\", \"GIANT_TREE_TAIGA_HILLS\"),\n RED_SAND_B(\"BADLANDS\", \"BADLANDS_PLATEAU\"),\n ACACIA_LOG_B(\"SAVANNA\", \"SHATTERED_SAVANNA\"),\n DARK_OAK_LOG_B(\"DARK_FOREST\", \"DARK_FOREST_HILLS\"),\n OAK_LOG_B(\"FOREST\", \"WOODED_HILLS\"),\n SPRUCE_LOG_B(\"TAIGA\", \"TAIGA_HILLS\"),\n BIRCH_LOG_B(\"BIRCH_FOREST\", \"BIRCH_FOREST_HILLS\"),\n JUNGLE_LOG_B(\"JUNGLE\", \"JUNGLE_HILLS\"),\n SAND_B(\"BEACH\", \"SNOWY_BEACH\"),\n SNOW_BLOCK_B(\"SNOWY_TAIGA\", \"SNOWY_TAIGA_HILLS\"),\n WATER_BUCKET_B(\"OCEAN\", \"DEEP_OCEAN\"),\n RED_TULIP_B(\"FLOWER_FOREST\", \"TALL_BIRCH_HILLS\"),\n SUNFLOWER_B(\"PLAINS\", \"SUNFLOWER_PLAINS\"),\n ICE_B(\"SNOWY_TUNDRA\", \"ICE_SPIKES\"),\n MYCELIUM_B(\"MUSHROOM_FIELDS\", \"MUSHROOM_FIELD_SHORE\"),\n LILY_PAD_B(\"SWAMP\", \"SWAMP_HILLS\"),\n BAMBOO_B(\"BAMBOO_JUNGLE\", \"BAMBOO_JUNGLE_HILLS\");\n\n public final static Map BY_REG = Maps.newHashMap();\n\n static {\n for (BiomeLookup bm : values()) {\n BY_REG.put(bm.getRegular(), bm);\n }\n }\n\n String regular;\n\n String upper;\n\n BiomeLookup(String regular, String upper) {\n this.regular = regular;\n this.upper = upper;\n }\n\n public static BiomeLookup getBiome(String data) {\n return BY_REG.get(data", "post_mask_code": "\n }\n\n public String getRegular() {\n return regular;\n }\n\n public String getUpper() {\n return upper;\n }\n}\n"} {"task_id": "Java_1314", "language": "Java", "task_type": "method_signature", "source_file": "java/github/indy256/codelibrary/java/graphs/dfs/EulerCycle.java", "mask_start_position": 1865, "mask_end_position": 1945, "canonical_solution": "static void dfs(List[] graph, int[] curEdge, List res, int u) ", "pre_mask_code": "package graphs.dfs;\n\nimport java.util.*;\nimport java.util.stream.Stream;\n\npublic class EulerCycle {\n\n public static List eulerCycleUndirected(List[] graph, int u) {\n Set usedEdges = new HashSet<>();\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, usedEdges, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, Set usedEdges, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add(((long) Math.min(u, v) << 32) + Math.max(u, v)))\n dfs(graph, curEdge, usedEdges, res, v);\n }\n res.add(u);\n }\n\n public static List eulerCycleUndirected2(List[] graph, int u) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n Set usedEdges = new HashSet<>();\n stack.add(u);\n while (!stack.isEmpty()) {\n u = stack.pop();\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add((((long) Math.min(u, v) << 32) + Math.max(u, v)))) {\n stack.push(u);\n u = v;\n }\n }\n res.add(u);\n }\n Collections.reverse(res);\n return res;\n }\n\n public static List eulerCycleDirected(List[] graph, int u) {\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, res, u);\n Collections.reverse(res);\n return res;\n }\n\n ", "post_mask_code": "{\n while (curEdge[u] < graph[u].size()) {\n dfs(graph, curEdge, res, graph[u].get(curEdge[u]++));\n }\n res.add(u);\n }\n\n public static List eulerCycleDirected2(List[] graph, int v) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n stack.add(v);\n while (!stack.isEmpty()) {\n v = stack.pop();\n while (curEdge[v] < graph[v].size()) {\n stack.push(v);\n v = graph[v].get(curEdge[v]++);\n }\n res.add(v);\n }\n Collections.reverse(res);\n return res;\n }\n\n // Usage example\n public static void main(String[] args) {\n int n = 5;\n List[] g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(4);\n g[4].add(1);\n System.out.println(eulerCycleDirected(g, 0));\n System.out.println(eulerCycleDirected2(g, 0));\n n = 5;\n g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(0);\n g[1].add(2);\n g[2].add(1);\n g[2].add(3);\n g[3].add(2);\n g[0].add(3);\n g[3].add(0);\n g[0].add(4);\n g[4].add(0);\n g[1].add(4);\n g[4].add(1);\n g[0].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(1);\n System.out.println(eulerCycleUndirected(g, 2));\n System.out.println(eulerCycleUndirected2(g, 2));\n }\n}\n"} {"task_id": "Java_1315", "language": "Java", "task_type": "method_body", "source_file": "java/github/indy256/codelibrary/java/graphs/dfs/EulerCycle.java", "mask_start_position": 2179, "mask_end_position": 2644, "canonical_solution": "{\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n stack.add(v);\n while (!stack.isEmpty()) {\n v = stack.pop();\n while (curEdge[v] < graph[v].size()) {\n stack.push(v);\n v = graph[v].get(curEdge[v]++);\n }\n res.add(v);\n }\n Collections.reverse(res);\n return res;\n }", "pre_mask_code": "package graphs.dfs;\n\nimport java.util.*;\nimport java.util.stream.Stream;\n\npublic class EulerCycle {\n\n public static List eulerCycleUndirected(List[] graph, int u) {\n Set usedEdges = new HashSet<>();\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, usedEdges, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, Set usedEdges, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add(((long) Math.min(u, v) << 32) + Math.max(u, v)))\n dfs(graph, curEdge, usedEdges, res, v);\n }\n res.add(u);\n }\n\n public static List eulerCycleUndirected2(List[] graph, int u) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n Set usedEdges = new HashSet<>();\n stack.add(u);\n while (!stack.isEmpty()) {\n u = stack.pop();\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add((((long) Math.min(u, v) << 32) + Math.max(u, v)))) {\n stack.push(u);\n u = v;\n }\n }\n res.add(u);\n }\n Collections.reverse(res);\n return res;\n }\n\n public static List eulerCycleDirected(List[] graph, int u) {\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n dfs(graph, curEdge, res, graph[u].get(curEdge[u]++));\n }\n res.add(u);\n }\n\n public static List eulerCycleDirected2(List[] graph, int v) ", "post_mask_code": "\n\n // Usage example\n public static void main(String[] args) {\n int n = 5;\n List[] g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(4);\n g[4].add(1);\n System.out.println(eulerCycleDirected(g, 0));\n System.out.println(eulerCycleDirected2(g, 0));\n n = 5;\n g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(0);\n g[1].add(2);\n g[2].add(1);\n g[2].add(3);\n g[3].add(2);\n g[0].add(3);\n g[3].add(0);\n g[0].add(4);\n g[4].add(0);\n g[1].add(4);\n g[4].add(1);\n g[0].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(1);\n System.out.println(eulerCycleUndirected(g, 2));\n System.out.println(eulerCycleUndirected2(g, 2));\n }\n}\n"} {"task_id": "Java_1316", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/indy256/codelibrary/java/graphs/dfs/EulerCycle.java", "mask_start_position": 2711, "mask_end_position": 3056, "canonical_solution": "\n int n = 5;\n List[] g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(4);\n g[4].add(1);\n System.out.println(eulerCycleDirected(g, 0));\n System.out.println(eulerCycleDirected2(g, 0));", "pre_mask_code": "package graphs.dfs;\n\nimport java.util.*;\nimport java.util.stream.Stream;\n\npublic class EulerCycle {\n\n public static List eulerCycleUndirected(List[] graph, int u) {\n Set usedEdges = new HashSet<>();\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, usedEdges, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, Set usedEdges, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add(((long) Math.min(u, v) << 32) + Math.max(u, v)))\n dfs(graph, curEdge, usedEdges, res, v);\n }\n res.add(u);\n }\n\n public static List eulerCycleUndirected2(List[] graph, int u) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n Set usedEdges = new HashSet<>();\n stack.add(u);\n while (!stack.isEmpty()) {\n u = stack.pop();\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add((((long) Math.min(u, v) << 32) + Math.max(u, v)))) {\n stack.push(u);\n u = v;\n }\n }\n res.add(u);\n }\n Collections.reverse(res);\n return res;\n }\n\n public static List eulerCycleDirected(List[] graph, int u) {\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n dfs(graph, curEdge, res, graph[u].get(curEdge[u]++));\n }\n res.add(u);\n }\n\n public static List eulerCycleDirected2(List[] graph, int v) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n stack.add(v);\n while (!stack.isEmpty()) {\n v = stack.pop();\n while (curEdge[v] < graph[v].size()) {\n stack.push(v);\n v = graph[v].get(curEdge[v]++);\n }\n res.add(v);\n }\n Collections.reverse(res);\n return res;\n }\n\n // Usage example\n public static void main(String[] args) {", "post_mask_code": "\n n = 5;\n g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(0);\n g[1].add(2);\n g[2].add(1);\n g[2].add(3);\n g[3].add(2);\n g[0].add(3);\n g[3].add(0);\n g[0].add(4);\n g[4].add(0);\n g[1].add(4);\n g[4].add(1);\n g[0].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(1);\n System.out.println(eulerCycleUndirected(g, 2));\n System.out.println(eulerCycleUndirected2(g, 2));\n }\n}\n"} {"task_id": "Java_1317", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/indy256/codelibrary/java/graphs/dfs/EulerCycle.java", "mask_start_position": 3065, "mask_end_position": 3314, "canonical_solution": "n = 5;\n g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(0);\n g[1].add(2);\n g[2].add(1);\n g[2].add(3);\n g[3].add(2);\n g[0].add(3);\n g[3].add(0);", "pre_mask_code": "package graphs.dfs;\n\nimport java.util.*;\nimport java.util.stream.Stream;\n\npublic class EulerCycle {\n\n public static List eulerCycleUndirected(List[] graph, int u) {\n Set usedEdges = new HashSet<>();\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, usedEdges, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, Set usedEdges, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add(((long) Math.min(u, v) << 32) + Math.max(u, v)))\n dfs(graph, curEdge, usedEdges, res, v);\n }\n res.add(u);\n }\n\n public static List eulerCycleUndirected2(List[] graph, int u) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n Set usedEdges = new HashSet<>();\n stack.add(u);\n while (!stack.isEmpty()) {\n u = stack.pop();\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add((((long) Math.min(u, v) << 32) + Math.max(u, v)))) {\n stack.push(u);\n u = v;\n }\n }\n res.add(u);\n }\n Collections.reverse(res);\n return res;\n }\n\n public static List eulerCycleDirected(List[] graph, int u) {\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n dfs(graph, curEdge, res, graph[u].get(curEdge[u]++));\n }\n res.add(u);\n }\n\n public static List eulerCycleDirected2(List[] graph, int v) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n stack.add(v);\n while (!stack.isEmpty()) {\n v = stack.pop();\n while (curEdge[v] < graph[v].size()) {\n stack.push(v);\n v = graph[v].get(curEdge[v]++);\n }\n res.add(v);\n }\n Collections.reverse(res);\n return res;\n }\n\n // Usage example\n public static void main(String[] args) {\n int n = 5;\n List[] g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(4);\n g[4].add(1);\n System.out.println(eulerCycleDirected(g, 0));\n System.out.println(eulerCycleDirected2(g, 0));\n ", "post_mask_code": "\n g[0].add(4);\n g[4].add(0);\n g[1].add(4);\n g[4].add(1);\n g[0].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(1);\n System.out.println(eulerCycleUndirected(g, 2));\n System.out.println(eulerCycleUndirected2(g, 2));\n }\n}\n"} {"task_id": "Java_1318", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/indy256/codelibrary/java/graphs/dfs/EulerCycle.java", "mask_start_position": 3323, "mask_end_position": 3601, "canonical_solution": "g[0].add(4);\n g[4].add(0);\n g[1].add(4);\n g[4].add(1);\n g[0].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(1);\n System.out.println(eulerCycleUndirected(g, 2));\n System.out.println(eulerCycleUndirected2(g, 2));\n }", "pre_mask_code": "package graphs.dfs;\n\nimport java.util.*;\nimport java.util.stream.Stream;\n\npublic class EulerCycle {\n\n public static List eulerCycleUndirected(List[] graph, int u) {\n Set usedEdges = new HashSet<>();\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, usedEdges, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, Set usedEdges, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add(((long) Math.min(u, v) << 32) + Math.max(u, v)))\n dfs(graph, curEdge, usedEdges, res, v);\n }\n res.add(u);\n }\n\n public static List eulerCycleUndirected2(List[] graph, int u) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n Set usedEdges = new HashSet<>();\n stack.add(u);\n while (!stack.isEmpty()) {\n u = stack.pop();\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add((((long) Math.min(u, v) << 32) + Math.max(u, v)))) {\n stack.push(u);\n u = v;\n }\n }\n res.add(u);\n }\n Collections.reverse(res);\n return res;\n }\n\n public static List eulerCycleDirected(List[] graph, int u) {\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n dfs(graph, curEdge, res, graph[u].get(curEdge[u]++));\n }\n res.add(u);\n }\n\n public static List eulerCycleDirected2(List[] graph, int v) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n stack.add(v);\n while (!stack.isEmpty()) {\n v = stack.pop();\n while (curEdge[v] < graph[v].size()) {\n stack.push(v);\n v = graph[v].get(curEdge[v]++);\n }\n res.add(v);\n }\n Collections.reverse(res);\n return res;\n }\n\n // Usage example\n public static void main(String[] args) {\n int n = 5;\n List[] g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(4);\n g[4].add(1);\n System.out.println(eulerCycleDirected(g, 0));\n System.out.println(eulerCycleDirected2(g, 0));\n n = 5;\n g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(0);\n g[1].add(2);\n g[2].add(1);\n g[2].add(3);\n g[3].add(2);\n g[0].add(3);\n g[3].add(0);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1319", "language": "Java", "task_type": "single_line", "source_file": "java/github/indy256/codelibrary/java/graphs/dfs/EulerCycle.java", "mask_start_position": 1122, "mask_end_position": 1123, "canonical_solution": ";", "pre_mask_code": "package graphs.dfs;\n\nimport java.util.*;\nimport java.util.stream.Stream;\n\npublic class EulerCycle {\n\n public static List eulerCycleUndirected(List[] graph, int u) {\n Set usedEdges = new HashSet<>();\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, usedEdges, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, Set usedEdges, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add(((long) Math.min(u, v) << 32) + Math.max(u, v)))\n dfs(graph, curEdge, usedEdges, res, v);\n }\n res.add(u);\n }\n\n public static List eulerCycleUndirected2(List[] graph, int u) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n Set usedEdges = new HashSet<>();\n stack.add(u)", "post_mask_code": "\n while (!stack.isEmpty()) {\n u = stack.pop();\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add((((long) Math.min(u, v) << 32) + Math.max(u, v)))) {\n stack.push(u);\n u = v;\n }\n }\n res.add(u);\n }\n Collections.reverse(res);\n return res;\n }\n\n public static List eulerCycleDirected(List[] graph, int u) {\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n dfs(graph, curEdge, res, graph[u].get(curEdge[u]++));\n }\n res.add(u);\n }\n\n public static List eulerCycleDirected2(List[] graph, int v) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n stack.add(v);\n while (!stack.isEmpty()) {\n v = stack.pop();\n while (curEdge[v] < graph[v].size()) {\n stack.push(v);\n v = graph[v].get(curEdge[v]++);\n }\n res.add(v);\n }\n Collections.reverse(res);\n return res;\n }\n\n // Usage example\n public static void main(String[] args) {\n int n = 5;\n List[] g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(4);\n g[4].add(1);\n System.out.println(eulerCycleDirected(g, 0));\n System.out.println(eulerCycleDirected2(g, 0));\n n = 5;\n g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(0);\n g[1].add(2);\n g[2].add(1);\n g[2].add(3);\n g[3].add(2);\n g[0].add(3);\n g[3].add(0);\n g[0].add(4);\n g[4].add(0);\n g[1].add(4);\n g[4].add(1);\n g[0].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(1);\n System.out.println(eulerCycleUndirected(g, 2));\n System.out.println(eulerCycleUndirected2(g, 2));\n }\n}\n"} {"task_id": "Java_1320", "language": "Java", "task_type": "if_statement", "source_file": "java/github/indy256/codelibrary/java/graphs/dfs/EulerCycle.java", "mask_start_position": 1307, "mask_end_position": 1457, "canonical_solution": "if (usedEdges.add((((long) Math.min(u, v) << 32) + Math.max(u, v)))) {\n stack.push(u);\n u = v;\n }", "pre_mask_code": "package graphs.dfs;\n\nimport java.util.*;\nimport java.util.stream.Stream;\n\npublic class EulerCycle {\n\n public static List eulerCycleUndirected(List[] graph, int u) {\n Set usedEdges = new HashSet<>();\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, usedEdges, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, Set usedEdges, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add(((long) Math.min(u, v) << 32) + Math.max(u, v)))\n dfs(graph, curEdge, usedEdges, res, v);\n }\n res.add(u);\n }\n\n public static List eulerCycleUndirected2(List[] graph, int u) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n Set usedEdges = new HashSet<>();\n stack.add(u);\n while (!stack.isEmpty()) {\n u = stack.pop();\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n ", "post_mask_code": "\n }\n res.add(u);\n }\n Collections.reverse(res);\n return res;\n }\n\n public static List eulerCycleDirected(List[] graph, int u) {\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n dfs(graph, curEdge, res, graph[u].get(curEdge[u]++));\n }\n res.add(u);\n }\n\n public static List eulerCycleDirected2(List[] graph, int v) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n stack.add(v);\n while (!stack.isEmpty()) {\n v = stack.pop();\n while (curEdge[v] < graph[v].size()) {\n stack.push(v);\n v = graph[v].get(curEdge[v]++);\n }\n res.add(v);\n }\n Collections.reverse(res);\n return res;\n }\n\n // Usage example\n public static void main(String[] args) {\n int n = 5;\n List[] g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(4);\n g[4].add(1);\n System.out.println(eulerCycleDirected(g, 0));\n System.out.println(eulerCycleDirected2(g, 0));\n n = 5;\n g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(0);\n g[1].add(2);\n g[2].add(1);\n g[2].add(3);\n g[3].add(2);\n g[0].add(3);\n g[3].add(0);\n g[0].add(4);\n g[4].add(0);\n g[1].add(4);\n g[4].add(1);\n g[0].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(1);\n System.out.println(eulerCycleUndirected(g, 2));\n System.out.println(eulerCycleUndirected2(g, 2));\n }\n}\n"} {"task_id": "Java_1321", "language": "Java", "task_type": "while_statement", "source_file": "java/github/indy256/codelibrary/java/graphs/dfs/EulerCycle.java", "mask_start_position": 570, "mask_end_position": 801, "canonical_solution": "while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add(((long) Math.min(u, v) << 32) + Math.max(u, v)))\n dfs(graph, curEdge, usedEdges, res, v);\n }", "pre_mask_code": "package graphs.dfs;\n\nimport java.util.*;\nimport java.util.stream.Stream;\n\npublic class EulerCycle {\n\n public static List eulerCycleUndirected(List[] graph, int u) {\n Set usedEdges = new HashSet<>();\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, usedEdges, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, Set usedEdges, List res, int u) {\n ", "post_mask_code": "\n res.add(u);\n }\n\n public static List eulerCycleUndirected2(List[] graph, int u) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n Set usedEdges = new HashSet<>();\n stack.add(u);\n while (!stack.isEmpty()) {\n u = stack.pop();\n while (curEdge[u] < graph[u].size()) {\n int v = graph[u].get(curEdge[u]++);\n if (usedEdges.add((((long) Math.min(u, v) << 32) + Math.max(u, v)))) {\n stack.push(u);\n u = v;\n }\n }\n res.add(u);\n }\n Collections.reverse(res);\n return res;\n }\n\n public static List eulerCycleDirected(List[] graph, int u) {\n int n = graph.length;\n int[] curEdge = new int[n];\n List res = new ArrayList<>();\n dfs(graph, curEdge, res, u);\n Collections.reverse(res);\n return res;\n }\n\n static void dfs(List[] graph, int[] curEdge, List res, int u) {\n while (curEdge[u] < graph[u].size()) {\n dfs(graph, curEdge, res, graph[u].get(curEdge[u]++));\n }\n res.add(u);\n }\n\n public static List eulerCycleDirected2(List[] graph, int v) {\n int[] curEdge = new int[graph.length];\n List res = new ArrayList<>();\n Stack stack = new Stack<>();\n stack.add(v);\n while (!stack.isEmpty()) {\n v = stack.pop();\n while (curEdge[v] < graph[v].size()) {\n stack.push(v);\n v = graph[v].get(curEdge[v]++);\n }\n res.add(v);\n }\n Collections.reverse(res);\n return res;\n }\n\n // Usage example\n public static void main(String[] args) {\n int n = 5;\n List[] g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(4);\n g[4].add(1);\n System.out.println(eulerCycleDirected(g, 0));\n System.out.println(eulerCycleDirected2(g, 0));\n n = 5;\n g = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);\n g[0].add(1);\n g[1].add(0);\n g[1].add(2);\n g[2].add(1);\n g[2].add(3);\n g[3].add(2);\n g[0].add(3);\n g[3].add(0);\n g[0].add(4);\n g[4].add(0);\n g[1].add(4);\n g[4].add(1);\n g[0].add(2);\n g[2].add(0);\n g[1].add(3);\n g[3].add(1);\n System.out.println(eulerCycleUndirected(g, 2));\n System.out.println(eulerCycleUndirected2(g, 2));\n }\n}\n"} {"task_id": "Java_1322", "language": "Java", "task_type": "method_signature", "source_file": "java/github/usnistgov/iheos-toolkit2/xdstest2-logging/src/main/java/gov/nist/toolkit/testenginelogging/logrepository/LogRepository1.java", "mask_start_position": 2390, "mask_end_position": 2430, "canonical_solution": "public File logDir() throws IOException ", "pre_mask_code": "package gov.nist.toolkit.testenginelogging.logrepository;\n\nimport gov.nist.toolkit.results.client.TestInstance;\nimport gov.nist.toolkit.testenginelogging.client.LogMapDTO;\nimport gov.nist.toolkit.xdsexception.client.XdsException;\nimport gov.nist.toolkit.xdsexception.client.XdsInternalException;\nimport org.apache.log4j.Logger;\nimport java.io.*;\n\n/**\n * A LogRepository is a directory where log files can be stored\n * for an event. This class creates the directory and returns\n * a File handle to the directory. What goes into the directory\n * @author bill\n */\nabstract public class LogRepository1 {\n\n File logDir = null;\n\n // must initialize logDir\n abstract public LogRepository1 getNewLogRepository(String user) throws IOException;\n\n abstract protected Logger getLogger();\n\n protected LogRepository1() {\n }\n\n public void logOut(TestInstance id, LogMapDTO log) throws XdsException {\n getLogger().debug(\"Writing log \" + log.getKeys() + \" to \" + logDir);\n FileOutputStream fos = null;\n ObjectOutputStream out = null;\n try {\n fos = new FileOutputStream(logFile(id));\n out = new ObjectOutputStream(fos);\n out.writeObject(log);\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n } finally {\n try {\n out.close();\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n }\n }\n }\n\n public LogMapDTO logIn(TestInstance id) throws Exception {\n FileInputStream fis = null;\n ObjectInputStream in = null;\n try {\n fis = new FileInputStream(logFile(id));\n in = new ObjectInputStream(fis);\n LogMapDTO map = (LogMapDTO) in.readObject();\n getLogger().debug(\"restoring log \" + map.getKeys() + \" from \" + logDir);\n return map;\n } catch (ClassNotFoundException e) {\n getLogger().debug(\"attempting to restore log \" + \"from \" + logDir);\n throw new XdsInternalException(\"Cannot create model of type LogMapDTO - class not found\", e);\n } finally {\n in.close();\n }\n }\n\n String logFile(TestInstance id) throws IOException {\n return logDir().toString() + File.separator + id.getId();\n }\n\n ", "post_mask_code": "{\n return logDir;\n }\n}\n"} {"task_id": "Java_1323", "language": "Java", "task_type": "method_body", "source_file": "java/github/usnistgov/iheos-toolkit2/xdstest2-logging/src/main/java/gov/nist/toolkit/testenginelogging/logrepository/LogRepository1.java", "mask_start_position": 2430, "mask_end_position": 2460, "canonical_solution": "{\n return logDir;\n }", "pre_mask_code": "package gov.nist.toolkit.testenginelogging.logrepository;\n\nimport gov.nist.toolkit.results.client.TestInstance;\nimport gov.nist.toolkit.testenginelogging.client.LogMapDTO;\nimport gov.nist.toolkit.xdsexception.client.XdsException;\nimport gov.nist.toolkit.xdsexception.client.XdsInternalException;\nimport org.apache.log4j.Logger;\nimport java.io.*;\n\n/**\n * A LogRepository is a directory where log files can be stored\n * for an event. This class creates the directory and returns\n * a File handle to the directory. What goes into the directory\n * @author bill\n */\nabstract public class LogRepository1 {\n\n File logDir = null;\n\n // must initialize logDir\n abstract public LogRepository1 getNewLogRepository(String user) throws IOException;\n\n abstract protected Logger getLogger();\n\n protected LogRepository1() {\n }\n\n public void logOut(TestInstance id, LogMapDTO log) throws XdsException {\n getLogger().debug(\"Writing log \" + log.getKeys() + \" to \" + logDir);\n FileOutputStream fos = null;\n ObjectOutputStream out = null;\n try {\n fos = new FileOutputStream(logFile(id));\n out = new ObjectOutputStream(fos);\n out.writeObject(log);\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n } finally {\n try {\n out.close();\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n }\n }\n }\n\n public LogMapDTO logIn(TestInstance id) throws Exception {\n FileInputStream fis = null;\n ObjectInputStream in = null;\n try {\n fis = new FileInputStream(logFile(id));\n in = new ObjectInputStream(fis);\n LogMapDTO map = (LogMapDTO) in.readObject();\n getLogger().debug(\"restoring log \" + map.getKeys() + \" from \" + logDir);\n return map;\n } catch (ClassNotFoundException e) {\n getLogger().debug(\"attempting to restore log \" + \"from \" + logDir);\n throw new XdsInternalException(\"Cannot create model of type LogMapDTO - class not found\", e);\n } finally {\n in.close();\n }\n }\n\n String logFile(TestInstance id) throws IOException {\n return logDir().toString() + File.separator + id.getId();\n }\n\n public File logDir() throws IOException ", "post_mask_code": "\n}\n"} {"task_id": "Java_1324", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/usnistgov/iheos-toolkit2/xdstest2-logging/src/main/java/gov/nist/toolkit/testenginelogging/logrepository/LogRepository1.java", "mask_start_position": 907, "mask_end_position": 984, "canonical_solution": "\n getLogger().debug(\"Writing log \" + log.getKeys() + \" to \" + logDir);", "pre_mask_code": "package gov.nist.toolkit.testenginelogging.logrepository;\n\nimport gov.nist.toolkit.results.client.TestInstance;\nimport gov.nist.toolkit.testenginelogging.client.LogMapDTO;\nimport gov.nist.toolkit.xdsexception.client.XdsException;\nimport gov.nist.toolkit.xdsexception.client.XdsInternalException;\nimport org.apache.log4j.Logger;\nimport java.io.*;\n\n/**\n * A LogRepository is a directory where log files can be stored\n * for an event. This class creates the directory and returns\n * a File handle to the directory. What goes into the directory\n * @author bill\n */\nabstract public class LogRepository1 {\n\n File logDir = null;\n\n // must initialize logDir\n abstract public LogRepository1 getNewLogRepository(String user) throws IOException;\n\n abstract protected Logger getLogger();\n\n protected LogRepository1() {\n }\n\n public void logOut(TestInstance id, LogMapDTO log) throws XdsException {", "post_mask_code": "\n FileOutputStream fos = null;\n ObjectOutputStream out = null;\n try {\n fos = new FileOutputStream(logFile(id));\n out = new ObjectOutputStream(fos);\n out.writeObject(log);\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n } finally {\n try {\n out.close();\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n }\n }\n }\n\n public LogMapDTO logIn(TestInstance id) throws Exception {\n FileInputStream fis = null;\n ObjectInputStream in = null;\n try {\n fis = new FileInputStream(logFile(id));\n in = new ObjectInputStream(fis);\n LogMapDTO map = (LogMapDTO) in.readObject();\n getLogger().debug(\"restoring log \" + map.getKeys() + \" from \" + logDir);\n return map;\n } catch (ClassNotFoundException e) {\n getLogger().debug(\"attempting to restore log \" + \"from \" + logDir);\n throw new XdsInternalException(\"Cannot create model of type LogMapDTO - class not found\", e);\n } finally {\n in.close();\n }\n }\n\n String logFile(TestInstance id) throws IOException {\n return logDir().toString() + File.separator + id.getId();\n }\n\n public File logDir() throws IOException {\n return logDir;\n }\n}\n"} {"task_id": "Java_1325", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/usnistgov/iheos-toolkit2/xdstest2-logging/src/main/java/gov/nist/toolkit/testenginelogging/logrepository/LogRepository1.java", "mask_start_position": 993, "mask_end_position": 1060, "canonical_solution": "FileOutputStream fos = null;\n ObjectOutputStream out = null;", "pre_mask_code": "package gov.nist.toolkit.testenginelogging.logrepository;\n\nimport gov.nist.toolkit.results.client.TestInstance;\nimport gov.nist.toolkit.testenginelogging.client.LogMapDTO;\nimport gov.nist.toolkit.xdsexception.client.XdsException;\nimport gov.nist.toolkit.xdsexception.client.XdsInternalException;\nimport org.apache.log4j.Logger;\nimport java.io.*;\n\n/**\n * A LogRepository is a directory where log files can be stored\n * for an event. This class creates the directory and returns\n * a File handle to the directory. What goes into the directory\n * @author bill\n */\nabstract public class LogRepository1 {\n\n File logDir = null;\n\n // must initialize logDir\n abstract public LogRepository1 getNewLogRepository(String user) throws IOException;\n\n abstract protected Logger getLogger();\n\n protected LogRepository1() {\n }\n\n public void logOut(TestInstance id, LogMapDTO log) throws XdsException {\n getLogger().debug(\"Writing log \" + log.getKeys() + \" to \" + logDir);\n ", "post_mask_code": "\n try {\n fos = new FileOutputStream(logFile(id));\n out = new ObjectOutputStream(fos);\n out.writeObject(log);\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n } finally {\n try {\n out.close();\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n }\n }\n }\n\n public LogMapDTO logIn(TestInstance id) throws Exception {\n FileInputStream fis = null;\n ObjectInputStream in = null;\n try {\n fis = new FileInputStream(logFile(id));\n in = new ObjectInputStream(fis);\n LogMapDTO map = (LogMapDTO) in.readObject();\n getLogger().debug(\"restoring log \" + map.getKeys() + \" from \" + logDir);\n return map;\n } catch (ClassNotFoundException e) {\n getLogger().debug(\"attempting to restore log \" + \"from \" + logDir);\n throw new XdsInternalException(\"Cannot create model of type LogMapDTO - class not found\", e);\n } finally {\n in.close();\n }\n }\n\n String logFile(TestInstance id) throws IOException {\n return logDir().toString() + File.separator + id.getId();\n }\n\n public File logDir() throws IOException {\n return logDir;\n }\n}\n"} {"task_id": "Java_1326", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/usnistgov/iheos-toolkit2/xdstest2-logging/src/main/java/gov/nist/toolkit/testenginelogging/logrepository/LogRepository1.java", "mask_start_position": 1069, "mask_end_position": 1549, "canonical_solution": "try {\n fos = new FileOutputStream(logFile(id));\n out = new ObjectOutputStream(fos);\n out.writeObject(log);\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n } finally {\n try {\n out.close();\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n }\n }\n }", "pre_mask_code": "package gov.nist.toolkit.testenginelogging.logrepository;\n\nimport gov.nist.toolkit.results.client.TestInstance;\nimport gov.nist.toolkit.testenginelogging.client.LogMapDTO;\nimport gov.nist.toolkit.xdsexception.client.XdsException;\nimport gov.nist.toolkit.xdsexception.client.XdsInternalException;\nimport org.apache.log4j.Logger;\nimport java.io.*;\n\n/**\n * A LogRepository is a directory where log files can be stored\n * for an event. This class creates the directory and returns\n * a File handle to the directory. What goes into the directory\n * @author bill\n */\nabstract public class LogRepository1 {\n\n File logDir = null;\n\n // must initialize logDir\n abstract public LogRepository1 getNewLogRepository(String user) throws IOException;\n\n abstract protected Logger getLogger();\n\n protected LogRepository1() {\n }\n\n public void logOut(TestInstance id, LogMapDTO log) throws XdsException {\n getLogger().debug(\"Writing log \" + log.getKeys() + \" to \" + logDir);\n FileOutputStream fos = null;\n ObjectOutputStream out = null;\n ", "post_mask_code": "\n\n public LogMapDTO logIn(TestInstance id) throws Exception {\n FileInputStream fis = null;\n ObjectInputStream in = null;\n try {\n fis = new FileInputStream(logFile(id));\n in = new ObjectInputStream(fis);\n LogMapDTO map = (LogMapDTO) in.readObject();\n getLogger().debug(\"restoring log \" + map.getKeys() + \" from \" + logDir);\n return map;\n } catch (ClassNotFoundException e) {\n getLogger().debug(\"attempting to restore log \" + \"from \" + logDir);\n throw new XdsInternalException(\"Cannot create model of type LogMapDTO - class not found\", e);\n } finally {\n in.close();\n }\n }\n\n String logFile(TestInstance id) throws IOException {\n return logDir().toString() + File.separator + id.getId();\n }\n\n public File logDir() throws IOException {\n return logDir;\n }\n}\n"} {"task_id": "Java_1327", "language": "Java", "task_type": "single_line", "source_file": "java/github/usnistgov/iheos-toolkit2/xdstest2-logging/src/main/java/gov/nist/toolkit/testenginelogging/logrepository/LogRepository1.java", "mask_start_position": 934, "mask_end_position": 984, "canonical_solution": "\"Writing log \" + log.getKeys() + \" to \" + logDir);", "pre_mask_code": "package gov.nist.toolkit.testenginelogging.logrepository;\n\nimport gov.nist.toolkit.results.client.TestInstance;\nimport gov.nist.toolkit.testenginelogging.client.LogMapDTO;\nimport gov.nist.toolkit.xdsexception.client.XdsException;\nimport gov.nist.toolkit.xdsexception.client.XdsInternalException;\nimport org.apache.log4j.Logger;\nimport java.io.*;\n\n/**\n * A LogRepository is a directory where log files can be stored\n * for an event. This class creates the directory and returns\n * a File handle to the directory. What goes into the directory\n * @author bill\n */\nabstract public class LogRepository1 {\n\n File logDir = null;\n\n // must initialize logDir\n abstract public LogRepository1 getNewLogRepository(String user) throws IOException;\n\n abstract protected Logger getLogger();\n\n protected LogRepository1() {\n }\n\n public void logOut(TestInstance id, LogMapDTO log) throws XdsException {\n getLogger().debug(", "post_mask_code": "\n FileOutputStream fos = null;\n ObjectOutputStream out = null;\n try {\n fos = new FileOutputStream(logFile(id));\n out = new ObjectOutputStream(fos);\n out.writeObject(log);\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n } finally {\n try {\n out.close();\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n }\n }\n }\n\n public LogMapDTO logIn(TestInstance id) throws Exception {\n FileInputStream fis = null;\n ObjectInputStream in = null;\n try {\n fis = new FileInputStream(logFile(id));\n in = new ObjectInputStream(fis);\n LogMapDTO map = (LogMapDTO) in.readObject();\n getLogger().debug(\"restoring log \" + map.getKeys() + \" from \" + logDir);\n return map;\n } catch (ClassNotFoundException e) {\n getLogger().debug(\"attempting to restore log \" + \"from \" + logDir);\n throw new XdsInternalException(\"Cannot create model of type LogMapDTO - class not found\", e);\n } finally {\n in.close();\n }\n }\n\n String logFile(TestInstance id) throws IOException {\n return logDir().toString() + File.separator + id.getId();\n }\n\n public File logDir() throws IOException {\n return logDir;\n }\n}\n"} {"task_id": "Java_1328", "language": "Java", "task_type": "try_statement", "source_file": "java/github/usnistgov/iheos-toolkit2/xdstest2-logging/src/main/java/gov/nist/toolkit/testenginelogging/logrepository/LogRepository1.java", "mask_start_position": 1069, "mask_end_position": 1543, "canonical_solution": "try {\n fos = new FileOutputStream(logFile(id));\n out = new ObjectOutputStream(fos);\n out.writeObject(log);\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n } finally {\n try {\n out.close();\n } catch (IOException e) {\n throw new XdsInternalException(\"Cannot write transaction log file\", e);\n }\n }", "pre_mask_code": "package gov.nist.toolkit.testenginelogging.logrepository;\n\nimport gov.nist.toolkit.results.client.TestInstance;\nimport gov.nist.toolkit.testenginelogging.client.LogMapDTO;\nimport gov.nist.toolkit.xdsexception.client.XdsException;\nimport gov.nist.toolkit.xdsexception.client.XdsInternalException;\nimport org.apache.log4j.Logger;\nimport java.io.*;\n\n/**\n * A LogRepository is a directory where log files can be stored\n * for an event. This class creates the directory and returns\n * a File handle to the directory. What goes into the directory\n * @author bill\n */\nabstract public class LogRepository1 {\n\n File logDir = null;\n\n // must initialize logDir\n abstract public LogRepository1 getNewLogRepository(String user) throws IOException;\n\n abstract protected Logger getLogger();\n\n protected LogRepository1() {\n }\n\n public void logOut(TestInstance id, LogMapDTO log) throws XdsException {\n getLogger().debug(\"Writing log \" + log.getKeys() + \" to \" + logDir);\n FileOutputStream fos = null;\n ObjectOutputStream out = null;\n ", "post_mask_code": "\n }\n\n public LogMapDTO logIn(TestInstance id) throws Exception {\n FileInputStream fis = null;\n ObjectInputStream in = null;\n try {\n fis = new FileInputStream(logFile(id));\n in = new ObjectInputStream(fis);\n LogMapDTO map = (LogMapDTO) in.readObject();\n getLogger().debug(\"restoring log \" + map.getKeys() + \" from \" + logDir);\n return map;\n } catch (ClassNotFoundException e) {\n getLogger().debug(\"attempting to restore log \" + \"from \" + logDir);\n throw new XdsInternalException(\"Cannot create model of type LogMapDTO - class not found\", e);\n } finally {\n in.close();\n }\n }\n\n String logFile(TestInstance id) throws IOException {\n return logDir().toString() + File.separator + id.getId();\n }\n\n public File logDir() throws IOException {\n return logDir;\n }\n}\n"} {"task_id": "Java_1329", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/solr/solr/solrj/src/java/org/apache/solr/client/solrj/io/eval/SplitEvaluator.java", "mask_start_position": 806, "mask_end_position": 871, "canonical_solution": "@Override\n public Object doWork(Object value1, Object value2) ", "pre_mask_code": "package org.apache.solr.client.solrj.io.eval;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamExpression;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamFactory;\n\npublic class SplitEvaluator extends RecursiveObjectEvaluator implements TwoValueWorker {\n\n protected static final long serialVersionUID = 1L;\n\n public SplitEvaluator(StreamExpression expression, StreamFactory factory) throws IOException {\n super(expression, factory);\n if (2 != containedEvaluators.size()) {\n throw new IOException(String.format(Locale.ROOT, \"Invalid expression %s - expecting exactly 2 values but found %d\", expression, containedEvaluators.size()));\n }\n }\n\n ", "post_mask_code": "{\n if (null == value1) {\n return null;\n }\n String s = value1.toString();\n String p = value2.toString();\n String[] tokens = s.split(p, -1);\n List strings = new ArrayList<>(tokens.length);\n for (String tok : tokens) {\n strings.add(tok);\n }\n return strings;\n }\n}\n"} {"task_id": "Java_1330", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/solr/solr/solrj/src/java/org/apache/solr/client/solrj/io/eval/SplitEvaluator.java", "mask_start_position": 871, "mask_end_position": 1224, "canonical_solution": "{\n if (null == value1) {\n return null;\n }\n String s = value1.toString();\n String p = value2.toString();\n String[] tokens = s.split(p, -1);\n List strings = new ArrayList<>(tokens.length);\n for (String tok : tokens) {\n strings.add(tok);\n }\n return strings;\n }", "pre_mask_code": "package org.apache.solr.client.solrj.io.eval;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamExpression;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamFactory;\n\npublic class SplitEvaluator extends RecursiveObjectEvaluator implements TwoValueWorker {\n\n protected static final long serialVersionUID = 1L;\n\n public SplitEvaluator(StreamExpression expression, StreamFactory factory) throws IOException {\n super(expression, factory);\n if (2 != containedEvaluators.size()) {\n throw new IOException(String.format(Locale.ROOT, \"Invalid expression %s - expecting exactly 2 values but found %d\", expression, containedEvaluators.size()));\n }\n }\n\n @Override\n public Object doWork(Object value1, Object value2) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1331", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/solr/solr/solrj/src/java/org/apache/solr/client/solrj/io/eval/SplitEvaluator.java", "mask_start_position": 872, "mask_end_position": 975, "canonical_solution": "\n if (null == value1) {\n return null;\n }\n String s = value1.toString();", "pre_mask_code": "package org.apache.solr.client.solrj.io.eval;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamExpression;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamFactory;\n\npublic class SplitEvaluator extends RecursiveObjectEvaluator implements TwoValueWorker {\n\n protected static final long serialVersionUID = 1L;\n\n public SplitEvaluator(StreamExpression expression, StreamFactory factory) throws IOException {\n super(expression, factory);\n if (2 != containedEvaluators.size()) {\n throw new IOException(String.format(Locale.ROOT, \"Invalid expression %s - expecting exactly 2 values but found %d\", expression, containedEvaluators.size()));\n }\n }\n\n @Override\n public Object doWork(Object value1, Object value2) {", "post_mask_code": "\n String p = value2.toString();\n String[] tokens = s.split(p, -1);\n List strings = new ArrayList<>(tokens.length);\n for (String tok : tokens) {\n strings.add(tok);\n }\n return strings;\n }\n}\n"} {"task_id": "Java_1332", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/solr/solr/solrj/src/java/org/apache/solr/client/solrj/io/eval/SplitEvaluator.java", "mask_start_position": 984, "mask_end_position": 1118, "canonical_solution": "String p = value2.toString();\n String[] tokens = s.split(p, -1);\n List strings = new ArrayList<>(tokens.length);", "pre_mask_code": "package org.apache.solr.client.solrj.io.eval;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamExpression;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamFactory;\n\npublic class SplitEvaluator extends RecursiveObjectEvaluator implements TwoValueWorker {\n\n protected static final long serialVersionUID = 1L;\n\n public SplitEvaluator(StreamExpression expression, StreamFactory factory) throws IOException {\n super(expression, factory);\n if (2 != containedEvaluators.size()) {\n throw new IOException(String.format(Locale.ROOT, \"Invalid expression %s - expecting exactly 2 values but found %d\", expression, containedEvaluators.size()));\n }\n }\n\n @Override\n public Object doWork(Object value1, Object value2) {\n if (null == value1) {\n return null;\n }\n String s = value1.toString();\n ", "post_mask_code": "\n for (String tok : tokens) {\n strings.add(tok);\n }\n return strings;\n }\n}\n"} {"task_id": "Java_1333", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/solr/solr/solrj/src/java/org/apache/solr/client/solrj/io/eval/SplitEvaluator.java", "mask_start_position": 1127, "mask_end_position": 1224, "canonical_solution": "for (String tok : tokens) {\n strings.add(tok);\n }\n return strings;\n }", "pre_mask_code": "package org.apache.solr.client.solrj.io.eval;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamExpression;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamFactory;\n\npublic class SplitEvaluator extends RecursiveObjectEvaluator implements TwoValueWorker {\n\n protected static final long serialVersionUID = 1L;\n\n public SplitEvaluator(StreamExpression expression, StreamFactory factory) throws IOException {\n super(expression, factory);\n if (2 != containedEvaluators.size()) {\n throw new IOException(String.format(Locale.ROOT, \"Invalid expression %s - expecting exactly 2 values but found %d\", expression, containedEvaluators.size()));\n }\n }\n\n @Override\n public Object doWork(Object value1, Object value2) {\n if (null == value1) {\n return null;\n }\n String s = value1.toString();\n String p = value2.toString();\n String[] tokens = s.split(p, -1);\n List strings = new ArrayList<>(tokens.length);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1334", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/solr/solr/solrj/src/java/org/apache/solr/client/solrj/io/eval/SplitEvaluator.java", "mask_start_position": 1205, "mask_end_position": 1218, "canonical_solution": "turn strings;", "pre_mask_code": "package org.apache.solr.client.solrj.io.eval;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamExpression;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamFactory;\n\npublic class SplitEvaluator extends RecursiveObjectEvaluator implements TwoValueWorker {\n\n protected static final long serialVersionUID = 1L;\n\n public SplitEvaluator(StreamExpression expression, StreamFactory factory) throws IOException {\n super(expression, factory);\n if (2 != containedEvaluators.size()) {\n throw new IOException(String.format(Locale.ROOT, \"Invalid expression %s - expecting exactly 2 values but found %d\", expression, containedEvaluators.size()));\n }\n }\n\n @Override\n public Object doWork(Object value1, Object value2) {\n if (null == value1) {\n return null;\n }\n String s = value1.toString();\n String p = value2.toString();\n String[] tokens = s.split(p, -1);\n List strings = new ArrayList<>(tokens.length);\n for (String tok : tokens) {\n strings.add(tok);\n }\n re", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1335", "language": "Java", "task_type": "if_statement", "source_file": "java/github/apache/solr/solr/solrj/src/java/org/apache/solr/client/solrj/io/eval/SplitEvaluator.java", "mask_start_position": 576, "mask_end_position": 794, "canonical_solution": "if (2 != containedEvaluators.size()) {\n throw new IOException(String.format(Locale.ROOT, \"Invalid expression %s - expecting exactly 2 values but found %d\", expression, containedEvaluators.size()));\n }", "pre_mask_code": "package org.apache.solr.client.solrj.io.eval;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamExpression;\nimport org.apache.solr.client.solrj.io.stream.expr.StreamFactory;\n\npublic class SplitEvaluator extends RecursiveObjectEvaluator implements TwoValueWorker {\n\n protected static final long serialVersionUID = 1L;\n\n public SplitEvaluator(StreamExpression expression, StreamFactory factory) throws IOException {\n super(expression, factory);\n ", "post_mask_code": "\n }\n\n @Override\n public Object doWork(Object value1, Object value2) {\n if (null == value1) {\n return null;\n }\n String s = value1.toString();\n String p = value2.toString();\n String[] tokens = s.split(p, -1);\n List strings = new ArrayList<>(tokens.length);\n for (String tok : tokens) {\n strings.add(tok);\n }\n return strings;\n }\n}\n"} {"task_id": "Java_1336", "language": "Java", "task_type": "method_signature", "source_file": "java/github/mongodb/mongo-java-driver/bson/src/main/org/bson/types/Decimal128.java", "mask_start_position": 18652, "mask_end_position": 18694, "canonical_solution": "@Override\n public double doubleValue() ", "pre_mask_code": "package org.bson.types;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.HashSet;\nimport java.util.Set;\nimport static java.math.MathContext.DECIMAL128;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\n\n/**\n * A binary integer decimal representation of a 128-bit decimal value, supporting 34 decimal digits of significand and an exponent range\n * of -6143 to +6144.\n *\n * @since 3.4\n * @see
BSON Decimal128\n * specification\n * @see binary integer decimal\n * @see decimal128 floating-point format\n * @see 754-2008 - IEEE Standard for Floating-Point Arithmetic\n */\npublic final class Decimal128 extends Number implements Comparable {\n\n private static final long serialVersionUID = 4570973266503637887L;\n\n private static final long INFINITY_MASK = 0x7800000000000000L;\n\n private static final long NaN_MASK = 0x7c00000000000000L;\n\n private static final long SIGN_BIT_MASK = 1L << 63;\n\n private static final int MIN_EXPONENT = -6176;\n\n private static final int MAX_EXPONENT = 6111;\n\n private static final int EXPONENT_OFFSET = 6176;\n\n private static final int MAX_BIT_LENGTH = 113;\n\n private static final BigInteger BIG_INT_TEN = new BigInteger(\"10\");\n\n private static final BigInteger BIG_INT_ONE = new BigInteger(\"1\");\n\n private static final BigInteger BIG_INT_ZERO = new BigInteger(\"0\");\n\n private static final Set NaN_STRINGS = new HashSet(singletonList(\"nan\"));\n\n private static final Set NEGATIVE_NaN_STRINGS = new HashSet(singletonList(\"-nan\"));\n\n private static final Set POSITIVE_INFINITY_STRINGS = new HashSet(asList(\"inf\", \"+inf\", \"infinity\", \"+infinity\"));\n\n private static final Set NEGATIVE_INFINITY_STRINGS = new HashSet(asList(\"-inf\", \"-infinity\"));\n\n /**\n * A constant holding the positive infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"Infinity\")}.\n */\n public static final Decimal128 POSITIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK, 0);\n\n /**\n * A constant holding the negative infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-Infinity\")}.\n */\n public static final Decimal128 NEGATIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a negative Not-a-Number (-NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-NaN\")}.\n */\n public static final Decimal128 NEGATIVE_NaN = fromIEEE754BIDEncoding(NaN_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a Not-a-Number (NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"NaN\")}.\n */\n public static final Decimal128 NaN = fromIEEE754BIDEncoding(NaN_MASK, 0);\n\n /**\n * A constant holding a postive zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"0\")}.\n */\n public static final Decimal128 POSITIVE_ZERO = fromIEEE754BIDEncoding(0x3040000000000000L, 0x0000000000000000L);\n\n /**\n * A constant holding a negative zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-0\")}.\n */\n public static final Decimal128 NEGATIVE_ZERO = fromIEEE754BIDEncoding(0xb040000000000000L, 0x0000000000000000L);\n\n private final long high;\n\n private final long low;\n\n /**\n * Returns a Decimal128 value representing the given String.\n *\n * @param value the Decimal128 value represented as a String\n * @return the Decimal128 value representing the given String\n * @throws NumberFormatException if the value is out of the Decimal128 range\n * @see\n * \n * From-String Specification\n */\n public static Decimal128 parse(final String value) {\n String lowerCasedValue = value.toLowerCase();\n if (NaN_STRINGS.contains(lowerCasedValue)) {\n return NaN;\n }\n if (NEGATIVE_NaN_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_NaN;\n }\n if (POSITIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return POSITIVE_INFINITY;\n }\n if (NEGATIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_INFINITY;\n }\n return new Decimal128(new BigDecimal(value), value.charAt(0) == '-');\n }\n\n /**\n * Create an instance with the given high and low order bits representing this Decimal128 as an IEEE 754-2008 128-bit decimal\n * floating point using the BID encoding scheme.\n *\n * @param high the high-order 64 bits\n * @param low the low-order 64 bits\n * @return the Decimal128 value representing the given high and low order bits\n */\n public static Decimal128 fromIEEE754BIDEncoding(final long high, final long low) {\n return new Decimal128(high, low);\n }\n\n /**\n * Constructs a Decimal128 value representing the given long.\n *\n * @param value the Decimal128 value represented as a long\n */\n public Decimal128(final long value) {\n this(new BigDecimal(value, DECIMAL128));\n }\n\n /**\n * Constructs a Decimal128 value representing the given BigDecimal.\n *\n * @param value the Decimal128 value represented as a BigDecimal\n * @throws NumberFormatException if the value is out of the Decimal128 range\n */\n public Decimal128(final BigDecimal value) {\n this(value, value.signum() == -1);\n }\n\n private Decimal128(final long high, final long low) {\n this.high = high;\n this.low = low;\n }\n\n // isNegative is necessary to detect -0, which can't be represented with a BigDecimal\n private Decimal128(final BigDecimal initialValue, final boolean isNegative) {\n long localHigh = 0;\n long localLow = 0;\n BigDecimal value = clampAndRound(initialValue);\n long exponent = -value.scale();\n if ((exponent < MIN_EXPONENT) || (exponent > MAX_EXPONENT)) {\n throw new AssertionError(\"Exponent is out of range for Decimal128 encoding: \" + exponent);\n }\n if (value.unscaledValue().bitLength() > MAX_BIT_LENGTH) {\n throw new AssertionError(\"Unscaled roundedValue is out of range for Decimal128 encoding:\" + value.unscaledValue());\n }\n BigInteger significand = value.unscaledValue().abs();\n int bitLength = significand.bitLength();\n for (int i = 0; i < Math.min(64, bitLength); i++) {\n if (significand.testBit(i)) {\n localLow |= 1L << i;\n }\n }\n for (int i = 64; i < bitLength; i++) {\n if (significand.testBit(i)) {\n localHigh |= 1L << (i - 64);\n }\n }\n long biasedExponent = exponent + EXPONENT_OFFSET;\n localHigh |= biasedExponent << 49;\n if (value.signum() == -1 || isNegative) {\n localHigh |= SIGN_BIT_MASK;\n }\n high = localHigh;\n low = localLow;\n }\n\n private BigDecimal clampAndRound(final BigDecimal initialValue) {\n BigDecimal value;\n if (-initialValue.scale() > MAX_EXPONENT) {\n int diff = -initialValue.scale() - MAX_EXPONENT;\n if (initialValue.unscaledValue().equals(BIG_INT_ZERO)) {\n value = new BigDecimal(initialValue.unscaledValue(), -MAX_EXPONENT);\n } else if (diff + initialValue.precision() > 34) {\n throw new NumberFormatException(\"Exponent is out of range for Decimal128 encoding of \" + initialValue);\n } else {\n BigInteger multiplier = BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().multiply(multiplier), initialValue.scale() + diff);\n }\n } else if (-initialValue.scale() < MIN_EXPONENT) {\n // Increasing a very negative exponent may require decreasing precision, which is rounding\n // Only round exactly (by removing precision that is all zeroes). An exception is thrown if the rounding would be inexact:\n int diff = initialValue.scale() + MIN_EXPONENT;\n int undiscardedPrecision = ensureExactRounding(initialValue, diff);\n BigInteger divisor = undiscardedPrecision == 0 ? BIG_INT_ONE : BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().divide(divisor), initialValue.scale() - diff);\n } else {\n value = initialValue.round(DECIMAL128);\n int extraPrecision = initialValue.precision() - value.precision();\n if (extraPrecision > 0) {\n // Again, only round exactly\n ensureExactRounding(initialValue, extraPrecision);\n }\n }\n return value;\n }\n\n private int ensureExactRounding(final BigDecimal initialValue, final int extraPrecision) {\n String significand = initialValue.unscaledValue().abs().toString();\n int undiscardedPrecision = Math.max(0, significand.length() - extraPrecision);\n for (int i = undiscardedPrecision; i < significand.length(); i++) {\n if (significand.charAt(i) != '0') {\n throw new NumberFormatException(\"Conversion to Decimal128 would require inexact rounding of \" + initialValue);\n }\n }\n return undiscardedPrecision;\n }\n\n /**\n * Gets the high-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the high-order 64 bits of this Decimal128\n */\n public long getHigh() {\n return high;\n }\n\n /**\n * Gets the low-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the low-order 64 bits of this Decimal128\n */\n public long getLow() {\n return low;\n }\n\n /**\n * Gets a BigDecimal that is equivalent to this Decimal128.\n *\n * @return a BigDecimal that is equivalent to this Decimal128\n * @throws ArithmeticException if the Decimal128 value is NaN, Infinity, -Infinity, or -0, none of which can be represented as a\n * BigDecimal\n */\n public BigDecimal bigDecimalValue() {\n if (isNaN()) {\n throw new ArithmeticException(\"NaN can not be converted to a BigDecimal\");\n }\n if (isInfinite()) {\n throw new ArithmeticException(\"Infinity can not be converted to a BigDecimal\");\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n // If the BigDecimal is 0, but the Decimal128 is negative, that means we have -0.\n if (isNegative() && bigDecimal.signum() == 0) {\n throw new ArithmeticException(\"Negative zero can not be converted to a BigDecimal\");\n }\n return bigDecimal;\n }\n\n // Make sure that the argument comes from a call to bigDecimalValueNoNegativeZeroCheck on this instance\n private boolean hasDifferentSign(final BigDecimal bigDecimal) {\n return isNegative() && bigDecimal.signum() == 0;\n }\n\n private boolean isZero(final BigDecimal bigDecimal) {\n return !isNaN() && !isInfinite() && bigDecimal.compareTo(BigDecimal.ZERO) == 0;\n }\n\n private BigDecimal bigDecimalValueNoNegativeZeroCheck() {\n int scale = -getExponent();\n if (twoHighestCombinationBitsAreSet()) {\n return BigDecimal.valueOf(0, scale);\n }\n return new BigDecimal(new BigInteger(isNegative() ? -1 : 1, getBytes()), scale);\n }\n\n // May have leading zeros. Strip them before considering making this method public\n private byte[] getBytes() {\n byte[] bytes = new byte[15];\n long mask = 0x00000000000000ff;\n for (int i = 14; i >= 7; i--) {\n bytes[i] = (byte) ((low & mask) >>> ((14 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x00000000000000ff;\n for (int i = 6; i >= 1; i--) {\n bytes[i] = (byte) ((high & mask) >>> ((6 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x0001000000000000L;\n bytes[0] = (byte) ((high & mask) >>> 48);\n return bytes;\n }\n\n private int getExponent() {\n if (twoHighestCombinationBitsAreSet()) {\n return (int) ((high & 0x1fffe00000000000L) >>> 47) - EXPONENT_OFFSET;\n } else {\n return (int) ((high & 0x7fff800000000000L) >>> 49) - EXPONENT_OFFSET;\n }\n }\n\n private boolean twoHighestCombinationBitsAreSet() {\n return (high & 3L << 61) == 3L << 61;\n }\n\n /**\n * Returns true if this Decimal128 is negative.\n *\n * @return true if this Decimal128 is negative\n */\n public boolean isNegative() {\n return (high & SIGN_BIT_MASK) == SIGN_BIT_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is infinite.\n *\n * @return true if this Decimal128 is infinite\n */\n public boolean isInfinite() {\n return (high & INFINITY_MASK) == INFINITY_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is finite.\n *\n * @return true if this Decimal128 is finite\n */\n public boolean isFinite() {\n return !isInfinite();\n }\n\n /**\n * Returns true if this Decimal128 is Not-A-Number (NaN).\n *\n * @return true if this Decimal128 is Not-A-Number\n */\n public boolean isNaN() {\n return (high & NaN_MASK) == NaN_MASK;\n }\n\n @Override\n public int compareTo(final Decimal128 o) {\n if (isNaN()) {\n return o.isNaN() ? 0 : 1;\n }\n if (isInfinite()) {\n if (isNegative()) {\n if (o.isInfinite() && o.isNegative()) {\n return 0;\n } else {\n return -1;\n }\n } else {\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite() && !o.isNegative()) {\n return 0;\n } else {\n return 1;\n }\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n BigDecimal otherBigDecimal = o.bigDecimalValueNoNegativeZeroCheck();\n if (isZero(bigDecimal) && o.isZero(otherBigDecimal)) {\n if (hasDifferentSign(bigDecimal)) {\n if (o.hasDifferentSign(otherBigDecimal)) {\n return 0;\n } else {\n return -1;\n }\n } else if (o.hasDifferentSign(otherBigDecimal)) {\n return 1;\n }\n }\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite()) {\n if (o.isNegative()) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return bigDecimal.compareTo(otherBigDecimal);\n }\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code int}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code int} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code int}, only the\n * low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0}.\n *\n * @return this {@code Decimal128} converted to a {@code int}.\n * @since 3.10\n */\n @Override\n public int intValue() {\n return (int) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code long}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code long} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code long}, only the\n * low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0L}.\n *\n * @return this {@code Decimal128} converted to a {@code long}.\n * @since 3.10\n */\n @Override\n public long longValue() {\n return (long) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code float}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code float}, it will be converted to {@link Float#NEGATIVE_INFINITY} or\n * {@link Float#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0f}.\n *\n * @return this {@code Decimal128} converted to a {@code float}.\n * @since 3.10\n */\n @Override\n public float floatValue() {\n return (float) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code double}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code double}, it will be converted to {@link Double#NEGATIVE_INFINITY} or\n * {@link Double#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0d}.\n *\n * @return this {@code Decimal128} converted to a {@code double}.\n * @since 3.10\n */\n ", "post_mask_code": "{\n if (isNaN()) {\n return Double.NaN;\n }\n if (isInfinite()) {\n if (isNegative()) {\n return Double.NEGATIVE_INFINITY;\n } else {\n return Double.POSITIVE_INFINITY;\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n if (hasDifferentSign(bigDecimal)) {\n return -0.0d;\n }\n return bigDecimal.doubleValue();\n }\n\n /**\n * Returns true if the encoded representation of this instance is the same as the encoded representation of {@code o}.\n *

\n * One consequence is that, whereas {@code Double.NaN != Double.NaN},\n * {@code new Decimal128(\"NaN\").equals(new Decimal128(\"NaN\")} returns true.\n *

\n *

\n * Another consequence is that, as with BigDecimal, {@code new Decimal128(\"1.0\").equals(new Decimal128(\"1.00\")} returns false,\n * because the precision is not the same and therefore the representation is not the same.\n *

\n *\n * @param o the object to compare for equality\n * @return true if the instances are equal\n */\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Decimal128 that = (Decimal128) o;\n if (high != that.high) {\n return false;\n }\n if (low != that.low) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = (int) (low ^ (low >>> 32));\n result = 31 * result + (int) (high ^ (high >>> 32));\n return result;\n }\n\n /**\n * Returns the String representation of the Decimal128 value.\n *\n * @return the String representation\n * @see \n * To-String Sprecification\n */\n @Override\n public String toString() {\n if (isNaN()) {\n return \"NaN\";\n }\n if (isInfinite()) {\n if (isNegative()) {\n return \"-Infinity\";\n } else {\n return \"Infinity\";\n }\n }\n return toStringWithBigDecimal();\n }\n\n private String toStringWithBigDecimal() {\n StringBuilder buffer = new StringBuilder();\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n String significand = bigDecimal.unscaledValue().abs().toString();\n if (isNegative()) {\n buffer.append('-');\n }\n int exponent = -bigDecimal.scale();\n int adjustedExponent = exponent + (significand.length() - 1);\n if (exponent <= 0 && adjustedExponent >= -6) {\n if (exponent == 0) {\n buffer.append(significand);\n } else {\n int pad = -exponent - significand.length();\n if (pad >= 0) {\n buffer.append('0');\n buffer.append('.');\n for (int i = 0; i < pad; i++) {\n buffer.append('0');\n }\n buffer.append(significand, 0, significand.length());\n } else {\n buffer.append(significand, 0, -pad);\n buffer.append('.');\n buffer.append(significand, -pad, -pad - exponent);\n }\n }\n } else {\n buffer.append(significand.charAt(0));\n if (significand.length() > 1) {\n buffer.append('.');\n buffer.append(significand, 1, significand.length());\n }\n buffer.append('E');\n if (adjustedExponent > 0) {\n buffer.append('+');\n }\n buffer.append(adjustedExponent);\n }\n return buffer.toString();\n }\n}\n"} {"task_id": "Java_1337", "language": "Java", "task_type": "method_body", "source_file": "java/github/mongodb/mongo-java-driver/bson/src/main/org/bson/types/Decimal128.java", "mask_start_position": 12577, "mask_end_position": 12824, "canonical_solution": "{\n if (twoHighestCombinationBitsAreSet()) {\n return (int) ((high & 0x1fffe00000000000L) >>> 47) - EXPONENT_OFFSET;\n } else {\n return (int) ((high & 0x7fff800000000000L) >>> 49) - EXPONENT_OFFSET;\n }\n }", "pre_mask_code": "package org.bson.types;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.HashSet;\nimport java.util.Set;\nimport static java.math.MathContext.DECIMAL128;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\n\n/**\n * A binary integer decimal representation of a 128-bit decimal value, supporting 34 decimal digits of significand and an exponent range\n * of -6143 to +6144.\n *\n * @since 3.4\n * @see BSON Decimal128\n * specification\n * @see binary integer decimal\n * @see decimal128 floating-point format\n * @see 754-2008 - IEEE Standard for Floating-Point Arithmetic\n */\npublic final class Decimal128 extends Number implements Comparable {\n\n private static final long serialVersionUID = 4570973266503637887L;\n\n private static final long INFINITY_MASK = 0x7800000000000000L;\n\n private static final long NaN_MASK = 0x7c00000000000000L;\n\n private static final long SIGN_BIT_MASK = 1L << 63;\n\n private static final int MIN_EXPONENT = -6176;\n\n private static final int MAX_EXPONENT = 6111;\n\n private static final int EXPONENT_OFFSET = 6176;\n\n private static final int MAX_BIT_LENGTH = 113;\n\n private static final BigInteger BIG_INT_TEN = new BigInteger(\"10\");\n\n private static final BigInteger BIG_INT_ONE = new BigInteger(\"1\");\n\n private static final BigInteger BIG_INT_ZERO = new BigInteger(\"0\");\n\n private static final Set NaN_STRINGS = new HashSet(singletonList(\"nan\"));\n\n private static final Set NEGATIVE_NaN_STRINGS = new HashSet(singletonList(\"-nan\"));\n\n private static final Set POSITIVE_INFINITY_STRINGS = new HashSet(asList(\"inf\", \"+inf\", \"infinity\", \"+infinity\"));\n\n private static final Set NEGATIVE_INFINITY_STRINGS = new HashSet(asList(\"-inf\", \"-infinity\"));\n\n /**\n * A constant holding the positive infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"Infinity\")}.\n */\n public static final Decimal128 POSITIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK, 0);\n\n /**\n * A constant holding the negative infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-Infinity\")}.\n */\n public static final Decimal128 NEGATIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a negative Not-a-Number (-NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-NaN\")}.\n */\n public static final Decimal128 NEGATIVE_NaN = fromIEEE754BIDEncoding(NaN_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a Not-a-Number (NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"NaN\")}.\n */\n public static final Decimal128 NaN = fromIEEE754BIDEncoding(NaN_MASK, 0);\n\n /**\n * A constant holding a postive zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"0\")}.\n */\n public static final Decimal128 POSITIVE_ZERO = fromIEEE754BIDEncoding(0x3040000000000000L, 0x0000000000000000L);\n\n /**\n * A constant holding a negative zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-0\")}.\n */\n public static final Decimal128 NEGATIVE_ZERO = fromIEEE754BIDEncoding(0xb040000000000000L, 0x0000000000000000L);\n\n private final long high;\n\n private final long low;\n\n /**\n * Returns a Decimal128 value representing the given String.\n *\n * @param value the Decimal128 value represented as a String\n * @return the Decimal128 value representing the given String\n * @throws NumberFormatException if the value is out of the Decimal128 range\n * @see\n * \n * From-String Specification\n */\n public static Decimal128 parse(final String value) {\n String lowerCasedValue = value.toLowerCase();\n if (NaN_STRINGS.contains(lowerCasedValue)) {\n return NaN;\n }\n if (NEGATIVE_NaN_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_NaN;\n }\n if (POSITIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return POSITIVE_INFINITY;\n }\n if (NEGATIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_INFINITY;\n }\n return new Decimal128(new BigDecimal(value), value.charAt(0) == '-');\n }\n\n /**\n * Create an instance with the given high and low order bits representing this Decimal128 as an IEEE 754-2008 128-bit decimal\n * floating point using the BID encoding scheme.\n *\n * @param high the high-order 64 bits\n * @param low the low-order 64 bits\n * @return the Decimal128 value representing the given high and low order bits\n */\n public static Decimal128 fromIEEE754BIDEncoding(final long high, final long low) {\n return new Decimal128(high, low);\n }\n\n /**\n * Constructs a Decimal128 value representing the given long.\n *\n * @param value the Decimal128 value represented as a long\n */\n public Decimal128(final long value) {\n this(new BigDecimal(value, DECIMAL128));\n }\n\n /**\n * Constructs a Decimal128 value representing the given BigDecimal.\n *\n * @param value the Decimal128 value represented as a BigDecimal\n * @throws NumberFormatException if the value is out of the Decimal128 range\n */\n public Decimal128(final BigDecimal value) {\n this(value, value.signum() == -1);\n }\n\n private Decimal128(final long high, final long low) {\n this.high = high;\n this.low = low;\n }\n\n // isNegative is necessary to detect -0, which can't be represented with a BigDecimal\n private Decimal128(final BigDecimal initialValue, final boolean isNegative) {\n long localHigh = 0;\n long localLow = 0;\n BigDecimal value = clampAndRound(initialValue);\n long exponent = -value.scale();\n if ((exponent < MIN_EXPONENT) || (exponent > MAX_EXPONENT)) {\n throw new AssertionError(\"Exponent is out of range for Decimal128 encoding: \" + exponent);\n }\n if (value.unscaledValue().bitLength() > MAX_BIT_LENGTH) {\n throw new AssertionError(\"Unscaled roundedValue is out of range for Decimal128 encoding:\" + value.unscaledValue());\n }\n BigInteger significand = value.unscaledValue().abs();\n int bitLength = significand.bitLength();\n for (int i = 0; i < Math.min(64, bitLength); i++) {\n if (significand.testBit(i)) {\n localLow |= 1L << i;\n }\n }\n for (int i = 64; i < bitLength; i++) {\n if (significand.testBit(i)) {\n localHigh |= 1L << (i - 64);\n }\n }\n long biasedExponent = exponent + EXPONENT_OFFSET;\n localHigh |= biasedExponent << 49;\n if (value.signum() == -1 || isNegative) {\n localHigh |= SIGN_BIT_MASK;\n }\n high = localHigh;\n low = localLow;\n }\n\n private BigDecimal clampAndRound(final BigDecimal initialValue) {\n BigDecimal value;\n if (-initialValue.scale() > MAX_EXPONENT) {\n int diff = -initialValue.scale() - MAX_EXPONENT;\n if (initialValue.unscaledValue().equals(BIG_INT_ZERO)) {\n value = new BigDecimal(initialValue.unscaledValue(), -MAX_EXPONENT);\n } else if (diff + initialValue.precision() > 34) {\n throw new NumberFormatException(\"Exponent is out of range for Decimal128 encoding of \" + initialValue);\n } else {\n BigInteger multiplier = BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().multiply(multiplier), initialValue.scale() + diff);\n }\n } else if (-initialValue.scale() < MIN_EXPONENT) {\n // Increasing a very negative exponent may require decreasing precision, which is rounding\n // Only round exactly (by removing precision that is all zeroes). An exception is thrown if the rounding would be inexact:\n int diff = initialValue.scale() + MIN_EXPONENT;\n int undiscardedPrecision = ensureExactRounding(initialValue, diff);\n BigInteger divisor = undiscardedPrecision == 0 ? BIG_INT_ONE : BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().divide(divisor), initialValue.scale() - diff);\n } else {\n value = initialValue.round(DECIMAL128);\n int extraPrecision = initialValue.precision() - value.precision();\n if (extraPrecision > 0) {\n // Again, only round exactly\n ensureExactRounding(initialValue, extraPrecision);\n }\n }\n return value;\n }\n\n private int ensureExactRounding(final BigDecimal initialValue, final int extraPrecision) {\n String significand = initialValue.unscaledValue().abs().toString();\n int undiscardedPrecision = Math.max(0, significand.length() - extraPrecision);\n for (int i = undiscardedPrecision; i < significand.length(); i++) {\n if (significand.charAt(i) != '0') {\n throw new NumberFormatException(\"Conversion to Decimal128 would require inexact rounding of \" + initialValue);\n }\n }\n return undiscardedPrecision;\n }\n\n /**\n * Gets the high-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the high-order 64 bits of this Decimal128\n */\n public long getHigh() {\n return high;\n }\n\n /**\n * Gets the low-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the low-order 64 bits of this Decimal128\n */\n public long getLow() {\n return low;\n }\n\n /**\n * Gets a BigDecimal that is equivalent to this Decimal128.\n *\n * @return a BigDecimal that is equivalent to this Decimal128\n * @throws ArithmeticException if the Decimal128 value is NaN, Infinity, -Infinity, or -0, none of which can be represented as a\n * BigDecimal\n */\n public BigDecimal bigDecimalValue() {\n if (isNaN()) {\n throw new ArithmeticException(\"NaN can not be converted to a BigDecimal\");\n }\n if (isInfinite()) {\n throw new ArithmeticException(\"Infinity can not be converted to a BigDecimal\");\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n // If the BigDecimal is 0, but the Decimal128 is negative, that means we have -0.\n if (isNegative() && bigDecimal.signum() == 0) {\n throw new ArithmeticException(\"Negative zero can not be converted to a BigDecimal\");\n }\n return bigDecimal;\n }\n\n // Make sure that the argument comes from a call to bigDecimalValueNoNegativeZeroCheck on this instance\n private boolean hasDifferentSign(final BigDecimal bigDecimal) {\n return isNegative() && bigDecimal.signum() == 0;\n }\n\n private boolean isZero(final BigDecimal bigDecimal) {\n return !isNaN() && !isInfinite() && bigDecimal.compareTo(BigDecimal.ZERO) == 0;\n }\n\n private BigDecimal bigDecimalValueNoNegativeZeroCheck() {\n int scale = -getExponent();\n if (twoHighestCombinationBitsAreSet()) {\n return BigDecimal.valueOf(0, scale);\n }\n return new BigDecimal(new BigInteger(isNegative() ? -1 : 1, getBytes()), scale);\n }\n\n // May have leading zeros. Strip them before considering making this method public\n private byte[] getBytes() {\n byte[] bytes = new byte[15];\n long mask = 0x00000000000000ff;\n for (int i = 14; i >= 7; i--) {\n bytes[i] = (byte) ((low & mask) >>> ((14 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x00000000000000ff;\n for (int i = 6; i >= 1; i--) {\n bytes[i] = (byte) ((high & mask) >>> ((6 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x0001000000000000L;\n bytes[0] = (byte) ((high & mask) >>> 48);\n return bytes;\n }\n\n private int getExponent() ", "post_mask_code": "\n\n private boolean twoHighestCombinationBitsAreSet() {\n return (high & 3L << 61) == 3L << 61;\n }\n\n /**\n * Returns true if this Decimal128 is negative.\n *\n * @return true if this Decimal128 is negative\n */\n public boolean isNegative() {\n return (high & SIGN_BIT_MASK) == SIGN_BIT_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is infinite.\n *\n * @return true if this Decimal128 is infinite\n */\n public boolean isInfinite() {\n return (high & INFINITY_MASK) == INFINITY_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is finite.\n *\n * @return true if this Decimal128 is finite\n */\n public boolean isFinite() {\n return !isInfinite();\n }\n\n /**\n * Returns true if this Decimal128 is Not-A-Number (NaN).\n *\n * @return true if this Decimal128 is Not-A-Number\n */\n public boolean isNaN() {\n return (high & NaN_MASK) == NaN_MASK;\n }\n\n @Override\n public int compareTo(final Decimal128 o) {\n if (isNaN()) {\n return o.isNaN() ? 0 : 1;\n }\n if (isInfinite()) {\n if (isNegative()) {\n if (o.isInfinite() && o.isNegative()) {\n return 0;\n } else {\n return -1;\n }\n } else {\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite() && !o.isNegative()) {\n return 0;\n } else {\n return 1;\n }\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n BigDecimal otherBigDecimal = o.bigDecimalValueNoNegativeZeroCheck();\n if (isZero(bigDecimal) && o.isZero(otherBigDecimal)) {\n if (hasDifferentSign(bigDecimal)) {\n if (o.hasDifferentSign(otherBigDecimal)) {\n return 0;\n } else {\n return -1;\n }\n } else if (o.hasDifferentSign(otherBigDecimal)) {\n return 1;\n }\n }\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite()) {\n if (o.isNegative()) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return bigDecimal.compareTo(otherBigDecimal);\n }\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code int}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code int} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code int}, only the\n * low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0}.\n *\n * @return this {@code Decimal128} converted to a {@code int}.\n * @since 3.10\n */\n @Override\n public int intValue() {\n return (int) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code long}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code long} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code long}, only the\n * low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0L}.\n *\n * @return this {@code Decimal128} converted to a {@code long}.\n * @since 3.10\n */\n @Override\n public long longValue() {\n return (long) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code float}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code float}, it will be converted to {@link Float#NEGATIVE_INFINITY} or\n * {@link Float#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0f}.\n *\n * @return this {@code Decimal128} converted to a {@code float}.\n * @since 3.10\n */\n @Override\n public float floatValue() {\n return (float) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code double}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code double}, it will be converted to {@link Double#NEGATIVE_INFINITY} or\n * {@link Double#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0d}.\n *\n * @return this {@code Decimal128} converted to a {@code double}.\n * @since 3.10\n */\n @Override\n public double doubleValue() {\n if (isNaN()) {\n return Double.NaN;\n }\n if (isInfinite()) {\n if (isNegative()) {\n return Double.NEGATIVE_INFINITY;\n } else {\n return Double.POSITIVE_INFINITY;\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n if (hasDifferentSign(bigDecimal)) {\n return -0.0d;\n }\n return bigDecimal.doubleValue();\n }\n\n /**\n * Returns true if the encoded representation of this instance is the same as the encoded representation of {@code o}.\n *

\n * One consequence is that, whereas {@code Double.NaN != Double.NaN},\n * {@code new Decimal128(\"NaN\").equals(new Decimal128(\"NaN\")} returns true.\n *

\n *

\n * Another consequence is that, as with BigDecimal, {@code new Decimal128(\"1.0\").equals(new Decimal128(\"1.00\")} returns false,\n * because the precision is not the same and therefore the representation is not the same.\n *

\n *\n * @param o the object to compare for equality\n * @return true if the instances are equal\n */\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Decimal128 that = (Decimal128) o;\n if (high != that.high) {\n return false;\n }\n if (low != that.low) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = (int) (low ^ (low >>> 32));\n result = 31 * result + (int) (high ^ (high >>> 32));\n return result;\n }\n\n /**\n * Returns the String representation of the Decimal128 value.\n *\n * @return the String representation\n * @see \n * To-String Sprecification\n */\n @Override\n public String toString() {\n if (isNaN()) {\n return \"NaN\";\n }\n if (isInfinite()) {\n if (isNegative()) {\n return \"-Infinity\";\n } else {\n return \"Infinity\";\n }\n }\n return toStringWithBigDecimal();\n }\n\n private String toStringWithBigDecimal() {\n StringBuilder buffer = new StringBuilder();\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n String significand = bigDecimal.unscaledValue().abs().toString();\n if (isNegative()) {\n buffer.append('-');\n }\n int exponent = -bigDecimal.scale();\n int adjustedExponent = exponent + (significand.length() - 1);\n if (exponent <= 0 && adjustedExponent >= -6) {\n if (exponent == 0) {\n buffer.append(significand);\n } else {\n int pad = -exponent - significand.length();\n if (pad >= 0) {\n buffer.append('0');\n buffer.append('.');\n for (int i = 0; i < pad; i++) {\n buffer.append('0');\n }\n buffer.append(significand, 0, significand.length());\n } else {\n buffer.append(significand, 0, -pad);\n buffer.append('.');\n buffer.append(significand, -pad, -pad - exponent);\n }\n }\n } else {\n buffer.append(significand.charAt(0));\n if (significand.length() > 1) {\n buffer.append('.');\n buffer.append(significand, 1, significand.length());\n }\n buffer.append('E');\n if (adjustedExponent > 0) {\n buffer.append('+');\n }\n buffer.append(adjustedExponent);\n }\n return buffer.toString();\n }\n}\n"} {"task_id": "Java_1338", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/mongodb/mongo-java-driver/bson/src/main/org/bson/types/Decimal128.java", "mask_start_position": 12578, "mask_end_position": 12578, "canonical_solution": "", "pre_mask_code": "package org.bson.types;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.HashSet;\nimport java.util.Set;\nimport static java.math.MathContext.DECIMAL128;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\n\n/**\n * A binary integer decimal representation of a 128-bit decimal value, supporting 34 decimal digits of significand and an exponent range\n * of -6143 to +6144.\n *\n * @since 3.4\n * @see BSON Decimal128\n * specification\n * @see binary integer decimal\n * @see decimal128 floating-point format\n * @see 754-2008 - IEEE Standard for Floating-Point Arithmetic\n */\npublic final class Decimal128 extends Number implements Comparable {\n\n private static final long serialVersionUID = 4570973266503637887L;\n\n private static final long INFINITY_MASK = 0x7800000000000000L;\n\n private static final long NaN_MASK = 0x7c00000000000000L;\n\n private static final long SIGN_BIT_MASK = 1L << 63;\n\n private static final int MIN_EXPONENT = -6176;\n\n private static final int MAX_EXPONENT = 6111;\n\n private static final int EXPONENT_OFFSET = 6176;\n\n private static final int MAX_BIT_LENGTH = 113;\n\n private static final BigInteger BIG_INT_TEN = new BigInteger(\"10\");\n\n private static final BigInteger BIG_INT_ONE = new BigInteger(\"1\");\n\n private static final BigInteger BIG_INT_ZERO = new BigInteger(\"0\");\n\n private static final Set NaN_STRINGS = new HashSet(singletonList(\"nan\"));\n\n private static final Set NEGATIVE_NaN_STRINGS = new HashSet(singletonList(\"-nan\"));\n\n private static final Set POSITIVE_INFINITY_STRINGS = new HashSet(asList(\"inf\", \"+inf\", \"infinity\", \"+infinity\"));\n\n private static final Set NEGATIVE_INFINITY_STRINGS = new HashSet(asList(\"-inf\", \"-infinity\"));\n\n /**\n * A constant holding the positive infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"Infinity\")}.\n */\n public static final Decimal128 POSITIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK, 0);\n\n /**\n * A constant holding the negative infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-Infinity\")}.\n */\n public static final Decimal128 NEGATIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a negative Not-a-Number (-NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-NaN\")}.\n */\n public static final Decimal128 NEGATIVE_NaN = fromIEEE754BIDEncoding(NaN_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a Not-a-Number (NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"NaN\")}.\n */\n public static final Decimal128 NaN = fromIEEE754BIDEncoding(NaN_MASK, 0);\n\n /**\n * A constant holding a postive zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"0\")}.\n */\n public static final Decimal128 POSITIVE_ZERO = fromIEEE754BIDEncoding(0x3040000000000000L, 0x0000000000000000L);\n\n /**\n * A constant holding a negative zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-0\")}.\n */\n public static final Decimal128 NEGATIVE_ZERO = fromIEEE754BIDEncoding(0xb040000000000000L, 0x0000000000000000L);\n\n private final long high;\n\n private final long low;\n\n /**\n * Returns a Decimal128 value representing the given String.\n *\n * @param value the Decimal128 value represented as a String\n * @return the Decimal128 value representing the given String\n * @throws NumberFormatException if the value is out of the Decimal128 range\n * @see\n * \n * From-String Specification\n */\n public static Decimal128 parse(final String value) {\n String lowerCasedValue = value.toLowerCase();\n if (NaN_STRINGS.contains(lowerCasedValue)) {\n return NaN;\n }\n if (NEGATIVE_NaN_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_NaN;\n }\n if (POSITIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return POSITIVE_INFINITY;\n }\n if (NEGATIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_INFINITY;\n }\n return new Decimal128(new BigDecimal(value), value.charAt(0) == '-');\n }\n\n /**\n * Create an instance with the given high and low order bits representing this Decimal128 as an IEEE 754-2008 128-bit decimal\n * floating point using the BID encoding scheme.\n *\n * @param high the high-order 64 bits\n * @param low the low-order 64 bits\n * @return the Decimal128 value representing the given high and low order bits\n */\n public static Decimal128 fromIEEE754BIDEncoding(final long high, final long low) {\n return new Decimal128(high, low);\n }\n\n /**\n * Constructs a Decimal128 value representing the given long.\n *\n * @param value the Decimal128 value represented as a long\n */\n public Decimal128(final long value) {\n this(new BigDecimal(value, DECIMAL128));\n }\n\n /**\n * Constructs a Decimal128 value representing the given BigDecimal.\n *\n * @param value the Decimal128 value represented as a BigDecimal\n * @throws NumberFormatException if the value is out of the Decimal128 range\n */\n public Decimal128(final BigDecimal value) {\n this(value, value.signum() == -1);\n }\n\n private Decimal128(final long high, final long low) {\n this.high = high;\n this.low = low;\n }\n\n // isNegative is necessary to detect -0, which can't be represented with a BigDecimal\n private Decimal128(final BigDecimal initialValue, final boolean isNegative) {\n long localHigh = 0;\n long localLow = 0;\n BigDecimal value = clampAndRound(initialValue);\n long exponent = -value.scale();\n if ((exponent < MIN_EXPONENT) || (exponent > MAX_EXPONENT)) {\n throw new AssertionError(\"Exponent is out of range for Decimal128 encoding: \" + exponent);\n }\n if (value.unscaledValue().bitLength() > MAX_BIT_LENGTH) {\n throw new AssertionError(\"Unscaled roundedValue is out of range for Decimal128 encoding:\" + value.unscaledValue());\n }\n BigInteger significand = value.unscaledValue().abs();\n int bitLength = significand.bitLength();\n for (int i = 0; i < Math.min(64, bitLength); i++) {\n if (significand.testBit(i)) {\n localLow |= 1L << i;\n }\n }\n for (int i = 64; i < bitLength; i++) {\n if (significand.testBit(i)) {\n localHigh |= 1L << (i - 64);\n }\n }\n long biasedExponent = exponent + EXPONENT_OFFSET;\n localHigh |= biasedExponent << 49;\n if (value.signum() == -1 || isNegative) {\n localHigh |= SIGN_BIT_MASK;\n }\n high = localHigh;\n low = localLow;\n }\n\n private BigDecimal clampAndRound(final BigDecimal initialValue) {\n BigDecimal value;\n if (-initialValue.scale() > MAX_EXPONENT) {\n int diff = -initialValue.scale() - MAX_EXPONENT;\n if (initialValue.unscaledValue().equals(BIG_INT_ZERO)) {\n value = new BigDecimal(initialValue.unscaledValue(), -MAX_EXPONENT);\n } else if (diff + initialValue.precision() > 34) {\n throw new NumberFormatException(\"Exponent is out of range for Decimal128 encoding of \" + initialValue);\n } else {\n BigInteger multiplier = BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().multiply(multiplier), initialValue.scale() + diff);\n }\n } else if (-initialValue.scale() < MIN_EXPONENT) {\n // Increasing a very negative exponent may require decreasing precision, which is rounding\n // Only round exactly (by removing precision that is all zeroes). An exception is thrown if the rounding would be inexact:\n int diff = initialValue.scale() + MIN_EXPONENT;\n int undiscardedPrecision = ensureExactRounding(initialValue, diff);\n BigInteger divisor = undiscardedPrecision == 0 ? BIG_INT_ONE : BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().divide(divisor), initialValue.scale() - diff);\n } else {\n value = initialValue.round(DECIMAL128);\n int extraPrecision = initialValue.precision() - value.precision();\n if (extraPrecision > 0) {\n // Again, only round exactly\n ensureExactRounding(initialValue, extraPrecision);\n }\n }\n return value;\n }\n\n private int ensureExactRounding(final BigDecimal initialValue, final int extraPrecision) {\n String significand = initialValue.unscaledValue().abs().toString();\n int undiscardedPrecision = Math.max(0, significand.length() - extraPrecision);\n for (int i = undiscardedPrecision; i < significand.length(); i++) {\n if (significand.charAt(i) != '0') {\n throw new NumberFormatException(\"Conversion to Decimal128 would require inexact rounding of \" + initialValue);\n }\n }\n return undiscardedPrecision;\n }\n\n /**\n * Gets the high-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the high-order 64 bits of this Decimal128\n */\n public long getHigh() {\n return high;\n }\n\n /**\n * Gets the low-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the low-order 64 bits of this Decimal128\n */\n public long getLow() {\n return low;\n }\n\n /**\n * Gets a BigDecimal that is equivalent to this Decimal128.\n *\n * @return a BigDecimal that is equivalent to this Decimal128\n * @throws ArithmeticException if the Decimal128 value is NaN, Infinity, -Infinity, or -0, none of which can be represented as a\n * BigDecimal\n */\n public BigDecimal bigDecimalValue() {\n if (isNaN()) {\n throw new ArithmeticException(\"NaN can not be converted to a BigDecimal\");\n }\n if (isInfinite()) {\n throw new ArithmeticException(\"Infinity can not be converted to a BigDecimal\");\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n // If the BigDecimal is 0, but the Decimal128 is negative, that means we have -0.\n if (isNegative() && bigDecimal.signum() == 0) {\n throw new ArithmeticException(\"Negative zero can not be converted to a BigDecimal\");\n }\n return bigDecimal;\n }\n\n // Make sure that the argument comes from a call to bigDecimalValueNoNegativeZeroCheck on this instance\n private boolean hasDifferentSign(final BigDecimal bigDecimal) {\n return isNegative() && bigDecimal.signum() == 0;\n }\n\n private boolean isZero(final BigDecimal bigDecimal) {\n return !isNaN() && !isInfinite() && bigDecimal.compareTo(BigDecimal.ZERO) == 0;\n }\n\n private BigDecimal bigDecimalValueNoNegativeZeroCheck() {\n int scale = -getExponent();\n if (twoHighestCombinationBitsAreSet()) {\n return BigDecimal.valueOf(0, scale);\n }\n return new BigDecimal(new BigInteger(isNegative() ? -1 : 1, getBytes()), scale);\n }\n\n // May have leading zeros. Strip them before considering making this method public\n private byte[] getBytes() {\n byte[] bytes = new byte[15];\n long mask = 0x00000000000000ff;\n for (int i = 14; i >= 7; i--) {\n bytes[i] = (byte) ((low & mask) >>> ((14 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x00000000000000ff;\n for (int i = 6; i >= 1; i--) {\n bytes[i] = (byte) ((high & mask) >>> ((6 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x0001000000000000L;\n bytes[0] = (byte) ((high & mask) >>> 48);\n return bytes;\n }\n\n private int getExponent() {", "post_mask_code": "\n if (twoHighestCombinationBitsAreSet()) {\n return (int) ((high & 0x1fffe00000000000L) >>> 47) - EXPONENT_OFFSET;\n } else {\n return (int) ((high & 0x7fff800000000000L) >>> 49) - EXPONENT_OFFSET;\n }\n }\n\n private boolean twoHighestCombinationBitsAreSet() {\n return (high & 3L << 61) == 3L << 61;\n }\n\n /**\n * Returns true if this Decimal128 is negative.\n *\n * @return true if this Decimal128 is negative\n */\n public boolean isNegative() {\n return (high & SIGN_BIT_MASK) == SIGN_BIT_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is infinite.\n *\n * @return true if this Decimal128 is infinite\n */\n public boolean isInfinite() {\n return (high & INFINITY_MASK) == INFINITY_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is finite.\n *\n * @return true if this Decimal128 is finite\n */\n public boolean isFinite() {\n return !isInfinite();\n }\n\n /**\n * Returns true if this Decimal128 is Not-A-Number (NaN).\n *\n * @return true if this Decimal128 is Not-A-Number\n */\n public boolean isNaN() {\n return (high & NaN_MASK) == NaN_MASK;\n }\n\n @Override\n public int compareTo(final Decimal128 o) {\n if (isNaN()) {\n return o.isNaN() ? 0 : 1;\n }\n if (isInfinite()) {\n if (isNegative()) {\n if (o.isInfinite() && o.isNegative()) {\n return 0;\n } else {\n return -1;\n }\n } else {\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite() && !o.isNegative()) {\n return 0;\n } else {\n return 1;\n }\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n BigDecimal otherBigDecimal = o.bigDecimalValueNoNegativeZeroCheck();\n if (isZero(bigDecimal) && o.isZero(otherBigDecimal)) {\n if (hasDifferentSign(bigDecimal)) {\n if (o.hasDifferentSign(otherBigDecimal)) {\n return 0;\n } else {\n return -1;\n }\n } else if (o.hasDifferentSign(otherBigDecimal)) {\n return 1;\n }\n }\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite()) {\n if (o.isNegative()) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return bigDecimal.compareTo(otherBigDecimal);\n }\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code int}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code int} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code int}, only the\n * low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0}.\n *\n * @return this {@code Decimal128} converted to a {@code int}.\n * @since 3.10\n */\n @Override\n public int intValue() {\n return (int) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code long}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code long} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code long}, only the\n * low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0L}.\n *\n * @return this {@code Decimal128} converted to a {@code long}.\n * @since 3.10\n */\n @Override\n public long longValue() {\n return (long) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code float}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code float}, it will be converted to {@link Float#NEGATIVE_INFINITY} or\n * {@link Float#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0f}.\n *\n * @return this {@code Decimal128} converted to a {@code float}.\n * @since 3.10\n */\n @Override\n public float floatValue() {\n return (float) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code double}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code double}, it will be converted to {@link Double#NEGATIVE_INFINITY} or\n * {@link Double#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0d}.\n *\n * @return this {@code Decimal128} converted to a {@code double}.\n * @since 3.10\n */\n @Override\n public double doubleValue() {\n if (isNaN()) {\n return Double.NaN;\n }\n if (isInfinite()) {\n if (isNegative()) {\n return Double.NEGATIVE_INFINITY;\n } else {\n return Double.POSITIVE_INFINITY;\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n if (hasDifferentSign(bigDecimal)) {\n return -0.0d;\n }\n return bigDecimal.doubleValue();\n }\n\n /**\n * Returns true if the encoded representation of this instance is the same as the encoded representation of {@code o}.\n *

\n * One consequence is that, whereas {@code Double.NaN != Double.NaN},\n * {@code new Decimal128(\"NaN\").equals(new Decimal128(\"NaN\")} returns true.\n *

\n *

\n * Another consequence is that, as with BigDecimal, {@code new Decimal128(\"1.0\").equals(new Decimal128(\"1.00\")} returns false,\n * because the precision is not the same and therefore the representation is not the same.\n *

\n *\n * @param o the object to compare for equality\n * @return true if the instances are equal\n */\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Decimal128 that = (Decimal128) o;\n if (high != that.high) {\n return false;\n }\n if (low != that.low) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = (int) (low ^ (low >>> 32));\n result = 31 * result + (int) (high ^ (high >>> 32));\n return result;\n }\n\n /**\n * Returns the String representation of the Decimal128 value.\n *\n * @return the String representation\n * @see \n * To-String Sprecification\n */\n @Override\n public String toString() {\n if (isNaN()) {\n return \"NaN\";\n }\n if (isInfinite()) {\n if (isNegative()) {\n return \"-Infinity\";\n } else {\n return \"Infinity\";\n }\n }\n return toStringWithBigDecimal();\n }\n\n private String toStringWithBigDecimal() {\n StringBuilder buffer = new StringBuilder();\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n String significand = bigDecimal.unscaledValue().abs().toString();\n if (isNegative()) {\n buffer.append('-');\n }\n int exponent = -bigDecimal.scale();\n int adjustedExponent = exponent + (significand.length() - 1);\n if (exponent <= 0 && adjustedExponent >= -6) {\n if (exponent == 0) {\n buffer.append(significand);\n } else {\n int pad = -exponent - significand.length();\n if (pad >= 0) {\n buffer.append('0');\n buffer.append('.');\n for (int i = 0; i < pad; i++) {\n buffer.append('0');\n }\n buffer.append(significand, 0, significand.length());\n } else {\n buffer.append(significand, 0, -pad);\n buffer.append('.');\n buffer.append(significand, -pad, -pad - exponent);\n }\n }\n } else {\n buffer.append(significand.charAt(0));\n if (significand.length() > 1) {\n buffer.append('.');\n buffer.append(significand, 1, significand.length());\n }\n buffer.append('E');\n if (adjustedExponent > 0) {\n buffer.append('+');\n }\n buffer.append(adjustedExponent);\n }\n return buffer.toString();\n }\n}\n"} {"task_id": "Java_1339", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/mongodb/mongo-java-driver/bson/src/main/org/bson/types/Decimal128.java", "mask_start_position": 12587, "mask_end_position": 12818, "canonical_solution": "if (twoHighestCombinationBitsAreSet()) {\n return (int) ((high & 0x1fffe00000000000L) >>> 47) - EXPONENT_OFFSET;\n } else {\n return (int) ((high & 0x7fff800000000000L) >>> 49) - EXPONENT_OFFSET;\n }", "pre_mask_code": "package org.bson.types;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.HashSet;\nimport java.util.Set;\nimport static java.math.MathContext.DECIMAL128;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\n\n/**\n * A binary integer decimal representation of a 128-bit decimal value, supporting 34 decimal digits of significand and an exponent range\n * of -6143 to +6144.\n *\n * @since 3.4\n * @see BSON Decimal128\n * specification\n * @see binary integer decimal\n * @see decimal128 floating-point format\n * @see 754-2008 - IEEE Standard for Floating-Point Arithmetic\n */\npublic final class Decimal128 extends Number implements Comparable {\n\n private static final long serialVersionUID = 4570973266503637887L;\n\n private static final long INFINITY_MASK = 0x7800000000000000L;\n\n private static final long NaN_MASK = 0x7c00000000000000L;\n\n private static final long SIGN_BIT_MASK = 1L << 63;\n\n private static final int MIN_EXPONENT = -6176;\n\n private static final int MAX_EXPONENT = 6111;\n\n private static final int EXPONENT_OFFSET = 6176;\n\n private static final int MAX_BIT_LENGTH = 113;\n\n private static final BigInteger BIG_INT_TEN = new BigInteger(\"10\");\n\n private static final BigInteger BIG_INT_ONE = new BigInteger(\"1\");\n\n private static final BigInteger BIG_INT_ZERO = new BigInteger(\"0\");\n\n private static final Set NaN_STRINGS = new HashSet(singletonList(\"nan\"));\n\n private static final Set NEGATIVE_NaN_STRINGS = new HashSet(singletonList(\"-nan\"));\n\n private static final Set POSITIVE_INFINITY_STRINGS = new HashSet(asList(\"inf\", \"+inf\", \"infinity\", \"+infinity\"));\n\n private static final Set NEGATIVE_INFINITY_STRINGS = new HashSet(asList(\"-inf\", \"-infinity\"));\n\n /**\n * A constant holding the positive infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"Infinity\")}.\n */\n public static final Decimal128 POSITIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK, 0);\n\n /**\n * A constant holding the negative infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-Infinity\")}.\n */\n public static final Decimal128 NEGATIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a negative Not-a-Number (-NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-NaN\")}.\n */\n public static final Decimal128 NEGATIVE_NaN = fromIEEE754BIDEncoding(NaN_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a Not-a-Number (NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"NaN\")}.\n */\n public static final Decimal128 NaN = fromIEEE754BIDEncoding(NaN_MASK, 0);\n\n /**\n * A constant holding a postive zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"0\")}.\n */\n public static final Decimal128 POSITIVE_ZERO = fromIEEE754BIDEncoding(0x3040000000000000L, 0x0000000000000000L);\n\n /**\n * A constant holding a negative zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-0\")}.\n */\n public static final Decimal128 NEGATIVE_ZERO = fromIEEE754BIDEncoding(0xb040000000000000L, 0x0000000000000000L);\n\n private final long high;\n\n private final long low;\n\n /**\n * Returns a Decimal128 value representing the given String.\n *\n * @param value the Decimal128 value represented as a String\n * @return the Decimal128 value representing the given String\n * @throws NumberFormatException if the value is out of the Decimal128 range\n * @see\n * \n * From-String Specification\n */\n public static Decimal128 parse(final String value) {\n String lowerCasedValue = value.toLowerCase();\n if (NaN_STRINGS.contains(lowerCasedValue)) {\n return NaN;\n }\n if (NEGATIVE_NaN_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_NaN;\n }\n if (POSITIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return POSITIVE_INFINITY;\n }\n if (NEGATIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_INFINITY;\n }\n return new Decimal128(new BigDecimal(value), value.charAt(0) == '-');\n }\n\n /**\n * Create an instance with the given high and low order bits representing this Decimal128 as an IEEE 754-2008 128-bit decimal\n * floating point using the BID encoding scheme.\n *\n * @param high the high-order 64 bits\n * @param low the low-order 64 bits\n * @return the Decimal128 value representing the given high and low order bits\n */\n public static Decimal128 fromIEEE754BIDEncoding(final long high, final long low) {\n return new Decimal128(high, low);\n }\n\n /**\n * Constructs a Decimal128 value representing the given long.\n *\n * @param value the Decimal128 value represented as a long\n */\n public Decimal128(final long value) {\n this(new BigDecimal(value, DECIMAL128));\n }\n\n /**\n * Constructs a Decimal128 value representing the given BigDecimal.\n *\n * @param value the Decimal128 value represented as a BigDecimal\n * @throws NumberFormatException if the value is out of the Decimal128 range\n */\n public Decimal128(final BigDecimal value) {\n this(value, value.signum() == -1);\n }\n\n private Decimal128(final long high, final long low) {\n this.high = high;\n this.low = low;\n }\n\n // isNegative is necessary to detect -0, which can't be represented with a BigDecimal\n private Decimal128(final BigDecimal initialValue, final boolean isNegative) {\n long localHigh = 0;\n long localLow = 0;\n BigDecimal value = clampAndRound(initialValue);\n long exponent = -value.scale();\n if ((exponent < MIN_EXPONENT) || (exponent > MAX_EXPONENT)) {\n throw new AssertionError(\"Exponent is out of range for Decimal128 encoding: \" + exponent);\n }\n if (value.unscaledValue().bitLength() > MAX_BIT_LENGTH) {\n throw new AssertionError(\"Unscaled roundedValue is out of range for Decimal128 encoding:\" + value.unscaledValue());\n }\n BigInteger significand = value.unscaledValue().abs();\n int bitLength = significand.bitLength();\n for (int i = 0; i < Math.min(64, bitLength); i++) {\n if (significand.testBit(i)) {\n localLow |= 1L << i;\n }\n }\n for (int i = 64; i < bitLength; i++) {\n if (significand.testBit(i)) {\n localHigh |= 1L << (i - 64);\n }\n }\n long biasedExponent = exponent + EXPONENT_OFFSET;\n localHigh |= biasedExponent << 49;\n if (value.signum() == -1 || isNegative) {\n localHigh |= SIGN_BIT_MASK;\n }\n high = localHigh;\n low = localLow;\n }\n\n private BigDecimal clampAndRound(final BigDecimal initialValue) {\n BigDecimal value;\n if (-initialValue.scale() > MAX_EXPONENT) {\n int diff = -initialValue.scale() - MAX_EXPONENT;\n if (initialValue.unscaledValue().equals(BIG_INT_ZERO)) {\n value = new BigDecimal(initialValue.unscaledValue(), -MAX_EXPONENT);\n } else if (diff + initialValue.precision() > 34) {\n throw new NumberFormatException(\"Exponent is out of range for Decimal128 encoding of \" + initialValue);\n } else {\n BigInteger multiplier = BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().multiply(multiplier), initialValue.scale() + diff);\n }\n } else if (-initialValue.scale() < MIN_EXPONENT) {\n // Increasing a very negative exponent may require decreasing precision, which is rounding\n // Only round exactly (by removing precision that is all zeroes). An exception is thrown if the rounding would be inexact:\n int diff = initialValue.scale() + MIN_EXPONENT;\n int undiscardedPrecision = ensureExactRounding(initialValue, diff);\n BigInteger divisor = undiscardedPrecision == 0 ? BIG_INT_ONE : BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().divide(divisor), initialValue.scale() - diff);\n } else {\n value = initialValue.round(DECIMAL128);\n int extraPrecision = initialValue.precision() - value.precision();\n if (extraPrecision > 0) {\n // Again, only round exactly\n ensureExactRounding(initialValue, extraPrecision);\n }\n }\n return value;\n }\n\n private int ensureExactRounding(final BigDecimal initialValue, final int extraPrecision) {\n String significand = initialValue.unscaledValue().abs().toString();\n int undiscardedPrecision = Math.max(0, significand.length() - extraPrecision);\n for (int i = undiscardedPrecision; i < significand.length(); i++) {\n if (significand.charAt(i) != '0') {\n throw new NumberFormatException(\"Conversion to Decimal128 would require inexact rounding of \" + initialValue);\n }\n }\n return undiscardedPrecision;\n }\n\n /**\n * Gets the high-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the high-order 64 bits of this Decimal128\n */\n public long getHigh() {\n return high;\n }\n\n /**\n * Gets the low-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the low-order 64 bits of this Decimal128\n */\n public long getLow() {\n return low;\n }\n\n /**\n * Gets a BigDecimal that is equivalent to this Decimal128.\n *\n * @return a BigDecimal that is equivalent to this Decimal128\n * @throws ArithmeticException if the Decimal128 value is NaN, Infinity, -Infinity, or -0, none of which can be represented as a\n * BigDecimal\n */\n public BigDecimal bigDecimalValue() {\n if (isNaN()) {\n throw new ArithmeticException(\"NaN can not be converted to a BigDecimal\");\n }\n if (isInfinite()) {\n throw new ArithmeticException(\"Infinity can not be converted to a BigDecimal\");\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n // If the BigDecimal is 0, but the Decimal128 is negative, that means we have -0.\n if (isNegative() && bigDecimal.signum() == 0) {\n throw new ArithmeticException(\"Negative zero can not be converted to a BigDecimal\");\n }\n return bigDecimal;\n }\n\n // Make sure that the argument comes from a call to bigDecimalValueNoNegativeZeroCheck on this instance\n private boolean hasDifferentSign(final BigDecimal bigDecimal) {\n return isNegative() && bigDecimal.signum() == 0;\n }\n\n private boolean isZero(final BigDecimal bigDecimal) {\n return !isNaN() && !isInfinite() && bigDecimal.compareTo(BigDecimal.ZERO) == 0;\n }\n\n private BigDecimal bigDecimalValueNoNegativeZeroCheck() {\n int scale = -getExponent();\n if (twoHighestCombinationBitsAreSet()) {\n return BigDecimal.valueOf(0, scale);\n }\n return new BigDecimal(new BigInteger(isNegative() ? -1 : 1, getBytes()), scale);\n }\n\n // May have leading zeros. Strip them before considering making this method public\n private byte[] getBytes() {\n byte[] bytes = new byte[15];\n long mask = 0x00000000000000ff;\n for (int i = 14; i >= 7; i--) {\n bytes[i] = (byte) ((low & mask) >>> ((14 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x00000000000000ff;\n for (int i = 6; i >= 1; i--) {\n bytes[i] = (byte) ((high & mask) >>> ((6 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x0001000000000000L;\n bytes[0] = (byte) ((high & mask) >>> 48);\n return bytes;\n }\n\n private int getExponent() {\n ", "post_mask_code": "\n }\n\n private boolean twoHighestCombinationBitsAreSet() {\n return (high & 3L << 61) == 3L << 61;\n }\n\n /**\n * Returns true if this Decimal128 is negative.\n *\n * @return true if this Decimal128 is negative\n */\n public boolean isNegative() {\n return (high & SIGN_BIT_MASK) == SIGN_BIT_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is infinite.\n *\n * @return true if this Decimal128 is infinite\n */\n public boolean isInfinite() {\n return (high & INFINITY_MASK) == INFINITY_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is finite.\n *\n * @return true if this Decimal128 is finite\n */\n public boolean isFinite() {\n return !isInfinite();\n }\n\n /**\n * Returns true if this Decimal128 is Not-A-Number (NaN).\n *\n * @return true if this Decimal128 is Not-A-Number\n */\n public boolean isNaN() {\n return (high & NaN_MASK) == NaN_MASK;\n }\n\n @Override\n public int compareTo(final Decimal128 o) {\n if (isNaN()) {\n return o.isNaN() ? 0 : 1;\n }\n if (isInfinite()) {\n if (isNegative()) {\n if (o.isInfinite() && o.isNegative()) {\n return 0;\n } else {\n return -1;\n }\n } else {\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite() && !o.isNegative()) {\n return 0;\n } else {\n return 1;\n }\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n BigDecimal otherBigDecimal = o.bigDecimalValueNoNegativeZeroCheck();\n if (isZero(bigDecimal) && o.isZero(otherBigDecimal)) {\n if (hasDifferentSign(bigDecimal)) {\n if (o.hasDifferentSign(otherBigDecimal)) {\n return 0;\n } else {\n return -1;\n }\n } else if (o.hasDifferentSign(otherBigDecimal)) {\n return 1;\n }\n }\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite()) {\n if (o.isNegative()) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return bigDecimal.compareTo(otherBigDecimal);\n }\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code int}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code int} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code int}, only the\n * low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0}.\n *\n * @return this {@code Decimal128} converted to a {@code int}.\n * @since 3.10\n */\n @Override\n public int intValue() {\n return (int) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code long}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code long} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code long}, only the\n * low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0L}.\n *\n * @return this {@code Decimal128} converted to a {@code long}.\n * @since 3.10\n */\n @Override\n public long longValue() {\n return (long) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code float}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code float}, it will be converted to {@link Float#NEGATIVE_INFINITY} or\n * {@link Float#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0f}.\n *\n * @return this {@code Decimal128} converted to a {@code float}.\n * @since 3.10\n */\n @Override\n public float floatValue() {\n return (float) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code double}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code double}, it will be converted to {@link Double#NEGATIVE_INFINITY} or\n * {@link Double#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0d}.\n *\n * @return this {@code Decimal128} converted to a {@code double}.\n * @since 3.10\n */\n @Override\n public double doubleValue() {\n if (isNaN()) {\n return Double.NaN;\n }\n if (isInfinite()) {\n if (isNegative()) {\n return Double.NEGATIVE_INFINITY;\n } else {\n return Double.POSITIVE_INFINITY;\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n if (hasDifferentSign(bigDecimal)) {\n return -0.0d;\n }\n return bigDecimal.doubleValue();\n }\n\n /**\n * Returns true if the encoded representation of this instance is the same as the encoded representation of {@code o}.\n *

\n * One consequence is that, whereas {@code Double.NaN != Double.NaN},\n * {@code new Decimal128(\"NaN\").equals(new Decimal128(\"NaN\")} returns true.\n *

\n *

\n * Another consequence is that, as with BigDecimal, {@code new Decimal128(\"1.0\").equals(new Decimal128(\"1.00\")} returns false,\n * because the precision is not the same and therefore the representation is not the same.\n *

\n *\n * @param o the object to compare for equality\n * @return true if the instances are equal\n */\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Decimal128 that = (Decimal128) o;\n if (high != that.high) {\n return false;\n }\n if (low != that.low) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = (int) (low ^ (low >>> 32));\n result = 31 * result + (int) (high ^ (high >>> 32));\n return result;\n }\n\n /**\n * Returns the String representation of the Decimal128 value.\n *\n * @return the String representation\n * @see \n * To-String Sprecification\n */\n @Override\n public String toString() {\n if (isNaN()) {\n return \"NaN\";\n }\n if (isInfinite()) {\n if (isNegative()) {\n return \"-Infinity\";\n } else {\n return \"Infinity\";\n }\n }\n return toStringWithBigDecimal();\n }\n\n private String toStringWithBigDecimal() {\n StringBuilder buffer = new StringBuilder();\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n String significand = bigDecimal.unscaledValue().abs().toString();\n if (isNegative()) {\n buffer.append('-');\n }\n int exponent = -bigDecimal.scale();\n int adjustedExponent = exponent + (significand.length() - 1);\n if (exponent <= 0 && adjustedExponent >= -6) {\n if (exponent == 0) {\n buffer.append(significand);\n } else {\n int pad = -exponent - significand.length();\n if (pad >= 0) {\n buffer.append('0');\n buffer.append('.');\n for (int i = 0; i < pad; i++) {\n buffer.append('0');\n }\n buffer.append(significand, 0, significand.length());\n } else {\n buffer.append(significand, 0, -pad);\n buffer.append('.');\n buffer.append(significand, -pad, -pad - exponent);\n }\n }\n } else {\n buffer.append(significand.charAt(0));\n if (significand.length() > 1) {\n buffer.append('.');\n buffer.append(significand, 1, significand.length());\n }\n buffer.append('E');\n if (adjustedExponent > 0) {\n buffer.append('+');\n }\n buffer.append(adjustedExponent);\n }\n return buffer.toString();\n }\n}\n"} {"task_id": "Java_1340", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/mongodb/mongo-java-driver/bson/src/main/org/bson/types/Decimal128.java", "mask_start_position": 12823, "mask_end_position": 12824, "canonical_solution": "}", "pre_mask_code": "package org.bson.types;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.HashSet;\nimport java.util.Set;\nimport static java.math.MathContext.DECIMAL128;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\n\n/**\n * A binary integer decimal representation of a 128-bit decimal value, supporting 34 decimal digits of significand and an exponent range\n * of -6143 to +6144.\n *\n * @since 3.4\n * @see BSON Decimal128\n * specification\n * @see binary integer decimal\n * @see decimal128 floating-point format\n * @see 754-2008 - IEEE Standard for Floating-Point Arithmetic\n */\npublic final class Decimal128 extends Number implements Comparable {\n\n private static final long serialVersionUID = 4570973266503637887L;\n\n private static final long INFINITY_MASK = 0x7800000000000000L;\n\n private static final long NaN_MASK = 0x7c00000000000000L;\n\n private static final long SIGN_BIT_MASK = 1L << 63;\n\n private static final int MIN_EXPONENT = -6176;\n\n private static final int MAX_EXPONENT = 6111;\n\n private static final int EXPONENT_OFFSET = 6176;\n\n private static final int MAX_BIT_LENGTH = 113;\n\n private static final BigInteger BIG_INT_TEN = new BigInteger(\"10\");\n\n private static final BigInteger BIG_INT_ONE = new BigInteger(\"1\");\n\n private static final BigInteger BIG_INT_ZERO = new BigInteger(\"0\");\n\n private static final Set NaN_STRINGS = new HashSet(singletonList(\"nan\"));\n\n private static final Set NEGATIVE_NaN_STRINGS = new HashSet(singletonList(\"-nan\"));\n\n private static final Set POSITIVE_INFINITY_STRINGS = new HashSet(asList(\"inf\", \"+inf\", \"infinity\", \"+infinity\"));\n\n private static final Set NEGATIVE_INFINITY_STRINGS = new HashSet(asList(\"-inf\", \"-infinity\"));\n\n /**\n * A constant holding the positive infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"Infinity\")}.\n */\n public static final Decimal128 POSITIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK, 0);\n\n /**\n * A constant holding the negative infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-Infinity\")}.\n */\n public static final Decimal128 NEGATIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a negative Not-a-Number (-NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-NaN\")}.\n */\n public static final Decimal128 NEGATIVE_NaN = fromIEEE754BIDEncoding(NaN_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a Not-a-Number (NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"NaN\")}.\n */\n public static final Decimal128 NaN = fromIEEE754BIDEncoding(NaN_MASK, 0);\n\n /**\n * A constant holding a postive zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"0\")}.\n */\n public static final Decimal128 POSITIVE_ZERO = fromIEEE754BIDEncoding(0x3040000000000000L, 0x0000000000000000L);\n\n /**\n * A constant holding a negative zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-0\")}.\n */\n public static final Decimal128 NEGATIVE_ZERO = fromIEEE754BIDEncoding(0xb040000000000000L, 0x0000000000000000L);\n\n private final long high;\n\n private final long low;\n\n /**\n * Returns a Decimal128 value representing the given String.\n *\n * @param value the Decimal128 value represented as a String\n * @return the Decimal128 value representing the given String\n * @throws NumberFormatException if the value is out of the Decimal128 range\n * @see\n * \n * From-String Specification\n */\n public static Decimal128 parse(final String value) {\n String lowerCasedValue = value.toLowerCase();\n if (NaN_STRINGS.contains(lowerCasedValue)) {\n return NaN;\n }\n if (NEGATIVE_NaN_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_NaN;\n }\n if (POSITIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return POSITIVE_INFINITY;\n }\n if (NEGATIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_INFINITY;\n }\n return new Decimal128(new BigDecimal(value), value.charAt(0) == '-');\n }\n\n /**\n * Create an instance with the given high and low order bits representing this Decimal128 as an IEEE 754-2008 128-bit decimal\n * floating point using the BID encoding scheme.\n *\n * @param high the high-order 64 bits\n * @param low the low-order 64 bits\n * @return the Decimal128 value representing the given high and low order bits\n */\n public static Decimal128 fromIEEE754BIDEncoding(final long high, final long low) {\n return new Decimal128(high, low);\n }\n\n /**\n * Constructs a Decimal128 value representing the given long.\n *\n * @param value the Decimal128 value represented as a long\n */\n public Decimal128(final long value) {\n this(new BigDecimal(value, DECIMAL128));\n }\n\n /**\n * Constructs a Decimal128 value representing the given BigDecimal.\n *\n * @param value the Decimal128 value represented as a BigDecimal\n * @throws NumberFormatException if the value is out of the Decimal128 range\n */\n public Decimal128(final BigDecimal value) {\n this(value, value.signum() == -1);\n }\n\n private Decimal128(final long high, final long low) {\n this.high = high;\n this.low = low;\n }\n\n // isNegative is necessary to detect -0, which can't be represented with a BigDecimal\n private Decimal128(final BigDecimal initialValue, final boolean isNegative) {\n long localHigh = 0;\n long localLow = 0;\n BigDecimal value = clampAndRound(initialValue);\n long exponent = -value.scale();\n if ((exponent < MIN_EXPONENT) || (exponent > MAX_EXPONENT)) {\n throw new AssertionError(\"Exponent is out of range for Decimal128 encoding: \" + exponent);\n }\n if (value.unscaledValue().bitLength() > MAX_BIT_LENGTH) {\n throw new AssertionError(\"Unscaled roundedValue is out of range for Decimal128 encoding:\" + value.unscaledValue());\n }\n BigInteger significand = value.unscaledValue().abs();\n int bitLength = significand.bitLength();\n for (int i = 0; i < Math.min(64, bitLength); i++) {\n if (significand.testBit(i)) {\n localLow |= 1L << i;\n }\n }\n for (int i = 64; i < bitLength; i++) {\n if (significand.testBit(i)) {\n localHigh |= 1L << (i - 64);\n }\n }\n long biasedExponent = exponent + EXPONENT_OFFSET;\n localHigh |= biasedExponent << 49;\n if (value.signum() == -1 || isNegative) {\n localHigh |= SIGN_BIT_MASK;\n }\n high = localHigh;\n low = localLow;\n }\n\n private BigDecimal clampAndRound(final BigDecimal initialValue) {\n BigDecimal value;\n if (-initialValue.scale() > MAX_EXPONENT) {\n int diff = -initialValue.scale() - MAX_EXPONENT;\n if (initialValue.unscaledValue().equals(BIG_INT_ZERO)) {\n value = new BigDecimal(initialValue.unscaledValue(), -MAX_EXPONENT);\n } else if (diff + initialValue.precision() > 34) {\n throw new NumberFormatException(\"Exponent is out of range for Decimal128 encoding of \" + initialValue);\n } else {\n BigInteger multiplier = BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().multiply(multiplier), initialValue.scale() + diff);\n }\n } else if (-initialValue.scale() < MIN_EXPONENT) {\n // Increasing a very negative exponent may require decreasing precision, which is rounding\n // Only round exactly (by removing precision that is all zeroes). An exception is thrown if the rounding would be inexact:\n int diff = initialValue.scale() + MIN_EXPONENT;\n int undiscardedPrecision = ensureExactRounding(initialValue, diff);\n BigInteger divisor = undiscardedPrecision == 0 ? BIG_INT_ONE : BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().divide(divisor), initialValue.scale() - diff);\n } else {\n value = initialValue.round(DECIMAL128);\n int extraPrecision = initialValue.precision() - value.precision();\n if (extraPrecision > 0) {\n // Again, only round exactly\n ensureExactRounding(initialValue, extraPrecision);\n }\n }\n return value;\n }\n\n private int ensureExactRounding(final BigDecimal initialValue, final int extraPrecision) {\n String significand = initialValue.unscaledValue().abs().toString();\n int undiscardedPrecision = Math.max(0, significand.length() - extraPrecision);\n for (int i = undiscardedPrecision; i < significand.length(); i++) {\n if (significand.charAt(i) != '0') {\n throw new NumberFormatException(\"Conversion to Decimal128 would require inexact rounding of \" + initialValue);\n }\n }\n return undiscardedPrecision;\n }\n\n /**\n * Gets the high-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the high-order 64 bits of this Decimal128\n */\n public long getHigh() {\n return high;\n }\n\n /**\n * Gets the low-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the low-order 64 bits of this Decimal128\n */\n public long getLow() {\n return low;\n }\n\n /**\n * Gets a BigDecimal that is equivalent to this Decimal128.\n *\n * @return a BigDecimal that is equivalent to this Decimal128\n * @throws ArithmeticException if the Decimal128 value is NaN, Infinity, -Infinity, or -0, none of which can be represented as a\n * BigDecimal\n */\n public BigDecimal bigDecimalValue() {\n if (isNaN()) {\n throw new ArithmeticException(\"NaN can not be converted to a BigDecimal\");\n }\n if (isInfinite()) {\n throw new ArithmeticException(\"Infinity can not be converted to a BigDecimal\");\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n // If the BigDecimal is 0, but the Decimal128 is negative, that means we have -0.\n if (isNegative() && bigDecimal.signum() == 0) {\n throw new ArithmeticException(\"Negative zero can not be converted to a BigDecimal\");\n }\n return bigDecimal;\n }\n\n // Make sure that the argument comes from a call to bigDecimalValueNoNegativeZeroCheck on this instance\n private boolean hasDifferentSign(final BigDecimal bigDecimal) {\n return isNegative() && bigDecimal.signum() == 0;\n }\n\n private boolean isZero(final BigDecimal bigDecimal) {\n return !isNaN() && !isInfinite() && bigDecimal.compareTo(BigDecimal.ZERO) == 0;\n }\n\n private BigDecimal bigDecimalValueNoNegativeZeroCheck() {\n int scale = -getExponent();\n if (twoHighestCombinationBitsAreSet()) {\n return BigDecimal.valueOf(0, scale);\n }\n return new BigDecimal(new BigInteger(isNegative() ? -1 : 1, getBytes()), scale);\n }\n\n // May have leading zeros. Strip them before considering making this method public\n private byte[] getBytes() {\n byte[] bytes = new byte[15];\n long mask = 0x00000000000000ff;\n for (int i = 14; i >= 7; i--) {\n bytes[i] = (byte) ((low & mask) >>> ((14 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x00000000000000ff;\n for (int i = 6; i >= 1; i--) {\n bytes[i] = (byte) ((high & mask) >>> ((6 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x0001000000000000L;\n bytes[0] = (byte) ((high & mask) >>> 48);\n return bytes;\n }\n\n private int getExponent() {\n if (twoHighestCombinationBitsAreSet()) {\n return (int) ((high & 0x1fffe00000000000L) >>> 47) - EXPONENT_OFFSET;\n } else {\n return (int) ((high & 0x7fff800000000000L) >>> 49) - EXPONENT_OFFSET;\n }\n ", "post_mask_code": "\n\n private boolean twoHighestCombinationBitsAreSet() {\n return (high & 3L << 61) == 3L << 61;\n }\n\n /**\n * Returns true if this Decimal128 is negative.\n *\n * @return true if this Decimal128 is negative\n */\n public boolean isNegative() {\n return (high & SIGN_BIT_MASK) == SIGN_BIT_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is infinite.\n *\n * @return true if this Decimal128 is infinite\n */\n public boolean isInfinite() {\n return (high & INFINITY_MASK) == INFINITY_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is finite.\n *\n * @return true if this Decimal128 is finite\n */\n public boolean isFinite() {\n return !isInfinite();\n }\n\n /**\n * Returns true if this Decimal128 is Not-A-Number (NaN).\n *\n * @return true if this Decimal128 is Not-A-Number\n */\n public boolean isNaN() {\n return (high & NaN_MASK) == NaN_MASK;\n }\n\n @Override\n public int compareTo(final Decimal128 o) {\n if (isNaN()) {\n return o.isNaN() ? 0 : 1;\n }\n if (isInfinite()) {\n if (isNegative()) {\n if (o.isInfinite() && o.isNegative()) {\n return 0;\n } else {\n return -1;\n }\n } else {\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite() && !o.isNegative()) {\n return 0;\n } else {\n return 1;\n }\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n BigDecimal otherBigDecimal = o.bigDecimalValueNoNegativeZeroCheck();\n if (isZero(bigDecimal) && o.isZero(otherBigDecimal)) {\n if (hasDifferentSign(bigDecimal)) {\n if (o.hasDifferentSign(otherBigDecimal)) {\n return 0;\n } else {\n return -1;\n }\n } else if (o.hasDifferentSign(otherBigDecimal)) {\n return 1;\n }\n }\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite()) {\n if (o.isNegative()) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return bigDecimal.compareTo(otherBigDecimal);\n }\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code int}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code int} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code int}, only the\n * low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0}.\n *\n * @return this {@code Decimal128} converted to a {@code int}.\n * @since 3.10\n */\n @Override\n public int intValue() {\n return (int) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code long}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code long} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code long}, only the\n * low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0L}.\n *\n * @return this {@code Decimal128} converted to a {@code long}.\n * @since 3.10\n */\n @Override\n public long longValue() {\n return (long) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code float}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code float}, it will be converted to {@link Float#NEGATIVE_INFINITY} or\n * {@link Float#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0f}.\n *\n * @return this {@code Decimal128} converted to a {@code float}.\n * @since 3.10\n */\n @Override\n public float floatValue() {\n return (float) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code double}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code double}, it will be converted to {@link Double#NEGATIVE_INFINITY} or\n * {@link Double#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0d}.\n *\n * @return this {@code Decimal128} converted to a {@code double}.\n * @since 3.10\n */\n @Override\n public double doubleValue() {\n if (isNaN()) {\n return Double.NaN;\n }\n if (isInfinite()) {\n if (isNegative()) {\n return Double.NEGATIVE_INFINITY;\n } else {\n return Double.POSITIVE_INFINITY;\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n if (hasDifferentSign(bigDecimal)) {\n return -0.0d;\n }\n return bigDecimal.doubleValue();\n }\n\n /**\n * Returns true if the encoded representation of this instance is the same as the encoded representation of {@code o}.\n *

\n * One consequence is that, whereas {@code Double.NaN != Double.NaN},\n * {@code new Decimal128(\"NaN\").equals(new Decimal128(\"NaN\")} returns true.\n *

\n *

\n * Another consequence is that, as with BigDecimal, {@code new Decimal128(\"1.0\").equals(new Decimal128(\"1.00\")} returns false,\n * because the precision is not the same and therefore the representation is not the same.\n *

\n *\n * @param o the object to compare for equality\n * @return true if the instances are equal\n */\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Decimal128 that = (Decimal128) o;\n if (high != that.high) {\n return false;\n }\n if (low != that.low) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = (int) (low ^ (low >>> 32));\n result = 31 * result + (int) (high ^ (high >>> 32));\n return result;\n }\n\n /**\n * Returns the String representation of the Decimal128 value.\n *\n * @return the String representation\n * @see \n * To-String Sprecification\n */\n @Override\n public String toString() {\n if (isNaN()) {\n return \"NaN\";\n }\n if (isInfinite()) {\n if (isNegative()) {\n return \"-Infinity\";\n } else {\n return \"Infinity\";\n }\n }\n return toStringWithBigDecimal();\n }\n\n private String toStringWithBigDecimal() {\n StringBuilder buffer = new StringBuilder();\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n String significand = bigDecimal.unscaledValue().abs().toString();\n if (isNegative()) {\n buffer.append('-');\n }\n int exponent = -bigDecimal.scale();\n int adjustedExponent = exponent + (significand.length() - 1);\n if (exponent <= 0 && adjustedExponent >= -6) {\n if (exponent == 0) {\n buffer.append(significand);\n } else {\n int pad = -exponent - significand.length();\n if (pad >= 0) {\n buffer.append('0');\n buffer.append('.');\n for (int i = 0; i < pad; i++) {\n buffer.append('0');\n }\n buffer.append(significand, 0, significand.length());\n } else {\n buffer.append(significand, 0, -pad);\n buffer.append('.');\n buffer.append(significand, -pad, -pad - exponent);\n }\n }\n } else {\n buffer.append(significand.charAt(0));\n if (significand.length() > 1) {\n buffer.append('.');\n buffer.append(significand, 1, significand.length());\n }\n buffer.append('E');\n if (adjustedExponent > 0) {\n buffer.append('+');\n }\n buffer.append(adjustedExponent);\n }\n return buffer.toString();\n }\n}\n"} {"task_id": "Java_1341", "language": "Java", "task_type": "single_line", "source_file": "java/github/mongodb/mongo-java-driver/bson/src/main/org/bson/types/Decimal128.java", "mask_start_position": 17846, "mask_end_position": 17865, "canonical_solution": "oat) doubleValue();", "pre_mask_code": "package org.bson.types;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.HashSet;\nimport java.util.Set;\nimport static java.math.MathContext.DECIMAL128;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\n\n/**\n * A binary integer decimal representation of a 128-bit decimal value, supporting 34 decimal digits of significand and an exponent range\n * of -6143 to +6144.\n *\n * @since 3.4\n * @see BSON Decimal128\n * specification\n * @see binary integer decimal\n * @see decimal128 floating-point format\n * @see 754-2008 - IEEE Standard for Floating-Point Arithmetic\n */\npublic final class Decimal128 extends Number implements Comparable {\n\n private static final long serialVersionUID = 4570973266503637887L;\n\n private static final long INFINITY_MASK = 0x7800000000000000L;\n\n private static final long NaN_MASK = 0x7c00000000000000L;\n\n private static final long SIGN_BIT_MASK = 1L << 63;\n\n private static final int MIN_EXPONENT = -6176;\n\n private static final int MAX_EXPONENT = 6111;\n\n private static final int EXPONENT_OFFSET = 6176;\n\n private static final int MAX_BIT_LENGTH = 113;\n\n private static final BigInteger BIG_INT_TEN = new BigInteger(\"10\");\n\n private static final BigInteger BIG_INT_ONE = new BigInteger(\"1\");\n\n private static final BigInteger BIG_INT_ZERO = new BigInteger(\"0\");\n\n private static final Set NaN_STRINGS = new HashSet(singletonList(\"nan\"));\n\n private static final Set NEGATIVE_NaN_STRINGS = new HashSet(singletonList(\"-nan\"));\n\n private static final Set POSITIVE_INFINITY_STRINGS = new HashSet(asList(\"inf\", \"+inf\", \"infinity\", \"+infinity\"));\n\n private static final Set NEGATIVE_INFINITY_STRINGS = new HashSet(asList(\"-inf\", \"-infinity\"));\n\n /**\n * A constant holding the positive infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"Infinity\")}.\n */\n public static final Decimal128 POSITIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK, 0);\n\n /**\n * A constant holding the negative infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-Infinity\")}.\n */\n public static final Decimal128 NEGATIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a negative Not-a-Number (-NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-NaN\")}.\n */\n public static final Decimal128 NEGATIVE_NaN = fromIEEE754BIDEncoding(NaN_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a Not-a-Number (NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"NaN\")}.\n */\n public static final Decimal128 NaN = fromIEEE754BIDEncoding(NaN_MASK, 0);\n\n /**\n * A constant holding a postive zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"0\")}.\n */\n public static final Decimal128 POSITIVE_ZERO = fromIEEE754BIDEncoding(0x3040000000000000L, 0x0000000000000000L);\n\n /**\n * A constant holding a negative zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-0\")}.\n */\n public static final Decimal128 NEGATIVE_ZERO = fromIEEE754BIDEncoding(0xb040000000000000L, 0x0000000000000000L);\n\n private final long high;\n\n private final long low;\n\n /**\n * Returns a Decimal128 value representing the given String.\n *\n * @param value the Decimal128 value represented as a String\n * @return the Decimal128 value representing the given String\n * @throws NumberFormatException if the value is out of the Decimal128 range\n * @see\n * \n * From-String Specification\n */\n public static Decimal128 parse(final String value) {\n String lowerCasedValue = value.toLowerCase();\n if (NaN_STRINGS.contains(lowerCasedValue)) {\n return NaN;\n }\n if (NEGATIVE_NaN_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_NaN;\n }\n if (POSITIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return POSITIVE_INFINITY;\n }\n if (NEGATIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_INFINITY;\n }\n return new Decimal128(new BigDecimal(value), value.charAt(0) == '-');\n }\n\n /**\n * Create an instance with the given high and low order bits representing this Decimal128 as an IEEE 754-2008 128-bit decimal\n * floating point using the BID encoding scheme.\n *\n * @param high the high-order 64 bits\n * @param low the low-order 64 bits\n * @return the Decimal128 value representing the given high and low order bits\n */\n public static Decimal128 fromIEEE754BIDEncoding(final long high, final long low) {\n return new Decimal128(high, low);\n }\n\n /**\n * Constructs a Decimal128 value representing the given long.\n *\n * @param value the Decimal128 value represented as a long\n */\n public Decimal128(final long value) {\n this(new BigDecimal(value, DECIMAL128));\n }\n\n /**\n * Constructs a Decimal128 value representing the given BigDecimal.\n *\n * @param value the Decimal128 value represented as a BigDecimal\n * @throws NumberFormatException if the value is out of the Decimal128 range\n */\n public Decimal128(final BigDecimal value) {\n this(value, value.signum() == -1);\n }\n\n private Decimal128(final long high, final long low) {\n this.high = high;\n this.low = low;\n }\n\n // isNegative is necessary to detect -0, which can't be represented with a BigDecimal\n private Decimal128(final BigDecimal initialValue, final boolean isNegative) {\n long localHigh = 0;\n long localLow = 0;\n BigDecimal value = clampAndRound(initialValue);\n long exponent = -value.scale();\n if ((exponent < MIN_EXPONENT) || (exponent > MAX_EXPONENT)) {\n throw new AssertionError(\"Exponent is out of range for Decimal128 encoding: \" + exponent);\n }\n if (value.unscaledValue().bitLength() > MAX_BIT_LENGTH) {\n throw new AssertionError(\"Unscaled roundedValue is out of range for Decimal128 encoding:\" + value.unscaledValue());\n }\n BigInteger significand = value.unscaledValue().abs();\n int bitLength = significand.bitLength();\n for (int i = 0; i < Math.min(64, bitLength); i++) {\n if (significand.testBit(i)) {\n localLow |= 1L << i;\n }\n }\n for (int i = 64; i < bitLength; i++) {\n if (significand.testBit(i)) {\n localHigh |= 1L << (i - 64);\n }\n }\n long biasedExponent = exponent + EXPONENT_OFFSET;\n localHigh |= biasedExponent << 49;\n if (value.signum() == -1 || isNegative) {\n localHigh |= SIGN_BIT_MASK;\n }\n high = localHigh;\n low = localLow;\n }\n\n private BigDecimal clampAndRound(final BigDecimal initialValue) {\n BigDecimal value;\n if (-initialValue.scale() > MAX_EXPONENT) {\n int diff = -initialValue.scale() - MAX_EXPONENT;\n if (initialValue.unscaledValue().equals(BIG_INT_ZERO)) {\n value = new BigDecimal(initialValue.unscaledValue(), -MAX_EXPONENT);\n } else if (diff + initialValue.precision() > 34) {\n throw new NumberFormatException(\"Exponent is out of range for Decimal128 encoding of \" + initialValue);\n } else {\n BigInteger multiplier = BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().multiply(multiplier), initialValue.scale() + diff);\n }\n } else if (-initialValue.scale() < MIN_EXPONENT) {\n // Increasing a very negative exponent may require decreasing precision, which is rounding\n // Only round exactly (by removing precision that is all zeroes). An exception is thrown if the rounding would be inexact:\n int diff = initialValue.scale() + MIN_EXPONENT;\n int undiscardedPrecision = ensureExactRounding(initialValue, diff);\n BigInteger divisor = undiscardedPrecision == 0 ? BIG_INT_ONE : BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().divide(divisor), initialValue.scale() - diff);\n } else {\n value = initialValue.round(DECIMAL128);\n int extraPrecision = initialValue.precision() - value.precision();\n if (extraPrecision > 0) {\n // Again, only round exactly\n ensureExactRounding(initialValue, extraPrecision);\n }\n }\n return value;\n }\n\n private int ensureExactRounding(final BigDecimal initialValue, final int extraPrecision) {\n String significand = initialValue.unscaledValue().abs().toString();\n int undiscardedPrecision = Math.max(0, significand.length() - extraPrecision);\n for (int i = undiscardedPrecision; i < significand.length(); i++) {\n if (significand.charAt(i) != '0') {\n throw new NumberFormatException(\"Conversion to Decimal128 would require inexact rounding of \" + initialValue);\n }\n }\n return undiscardedPrecision;\n }\n\n /**\n * Gets the high-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the high-order 64 bits of this Decimal128\n */\n public long getHigh() {\n return high;\n }\n\n /**\n * Gets the low-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the low-order 64 bits of this Decimal128\n */\n public long getLow() {\n return low;\n }\n\n /**\n * Gets a BigDecimal that is equivalent to this Decimal128.\n *\n * @return a BigDecimal that is equivalent to this Decimal128\n * @throws ArithmeticException if the Decimal128 value is NaN, Infinity, -Infinity, or -0, none of which can be represented as a\n * BigDecimal\n */\n public BigDecimal bigDecimalValue() {\n if (isNaN()) {\n throw new ArithmeticException(\"NaN can not be converted to a BigDecimal\");\n }\n if (isInfinite()) {\n throw new ArithmeticException(\"Infinity can not be converted to a BigDecimal\");\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n // If the BigDecimal is 0, but the Decimal128 is negative, that means we have -0.\n if (isNegative() && bigDecimal.signum() == 0) {\n throw new ArithmeticException(\"Negative zero can not be converted to a BigDecimal\");\n }\n return bigDecimal;\n }\n\n // Make sure that the argument comes from a call to bigDecimalValueNoNegativeZeroCheck on this instance\n private boolean hasDifferentSign(final BigDecimal bigDecimal) {\n return isNegative() && bigDecimal.signum() == 0;\n }\n\n private boolean isZero(final BigDecimal bigDecimal) {\n return !isNaN() && !isInfinite() && bigDecimal.compareTo(BigDecimal.ZERO) == 0;\n }\n\n private BigDecimal bigDecimalValueNoNegativeZeroCheck() {\n int scale = -getExponent();\n if (twoHighestCombinationBitsAreSet()) {\n return BigDecimal.valueOf(0, scale);\n }\n return new BigDecimal(new BigInteger(isNegative() ? -1 : 1, getBytes()), scale);\n }\n\n // May have leading zeros. Strip them before considering making this method public\n private byte[] getBytes() {\n byte[] bytes = new byte[15];\n long mask = 0x00000000000000ff;\n for (int i = 14; i >= 7; i--) {\n bytes[i] = (byte) ((low & mask) >>> ((14 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x00000000000000ff;\n for (int i = 6; i >= 1; i--) {\n bytes[i] = (byte) ((high & mask) >>> ((6 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x0001000000000000L;\n bytes[0] = (byte) ((high & mask) >>> 48);\n return bytes;\n }\n\n private int getExponent() {\n if (twoHighestCombinationBitsAreSet()) {\n return (int) ((high & 0x1fffe00000000000L) >>> 47) - EXPONENT_OFFSET;\n } else {\n return (int) ((high & 0x7fff800000000000L) >>> 49) - EXPONENT_OFFSET;\n }\n }\n\n private boolean twoHighestCombinationBitsAreSet() {\n return (high & 3L << 61) == 3L << 61;\n }\n\n /**\n * Returns true if this Decimal128 is negative.\n *\n * @return true if this Decimal128 is negative\n */\n public boolean isNegative() {\n return (high & SIGN_BIT_MASK) == SIGN_BIT_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is infinite.\n *\n * @return true if this Decimal128 is infinite\n */\n public boolean isInfinite() {\n return (high & INFINITY_MASK) == INFINITY_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is finite.\n *\n * @return true if this Decimal128 is finite\n */\n public boolean isFinite() {\n return !isInfinite();\n }\n\n /**\n * Returns true if this Decimal128 is Not-A-Number (NaN).\n *\n * @return true if this Decimal128 is Not-A-Number\n */\n public boolean isNaN() {\n return (high & NaN_MASK) == NaN_MASK;\n }\n\n @Override\n public int compareTo(final Decimal128 o) {\n if (isNaN()) {\n return o.isNaN() ? 0 : 1;\n }\n if (isInfinite()) {\n if (isNegative()) {\n if (o.isInfinite() && o.isNegative()) {\n return 0;\n } else {\n return -1;\n }\n } else {\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite() && !o.isNegative()) {\n return 0;\n } else {\n return 1;\n }\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n BigDecimal otherBigDecimal = o.bigDecimalValueNoNegativeZeroCheck();\n if (isZero(bigDecimal) && o.isZero(otherBigDecimal)) {\n if (hasDifferentSign(bigDecimal)) {\n if (o.hasDifferentSign(otherBigDecimal)) {\n return 0;\n } else {\n return -1;\n }\n } else if (o.hasDifferentSign(otherBigDecimal)) {\n return 1;\n }\n }\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite()) {\n if (o.isNegative()) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return bigDecimal.compareTo(otherBigDecimal);\n }\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code int}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code int} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code int}, only the\n * low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0}.\n *\n * @return this {@code Decimal128} converted to a {@code int}.\n * @since 3.10\n */\n @Override\n public int intValue() {\n return (int) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code long}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code long} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code long}, only the\n * low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0L}.\n *\n * @return this {@code Decimal128} converted to a {@code long}.\n * @since 3.10\n */\n @Override\n public long longValue() {\n return (long) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code float}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code float}, it will be converted to {@link Float#NEGATIVE_INFINITY} or\n * {@link Float#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0f}.\n *\n * @return this {@code Decimal128} converted to a {@code float}.\n * @since 3.10\n */\n @Override\n public float floatValue() {\n return (fl", "post_mask_code": "\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code double}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code double}, it will be converted to {@link Double#NEGATIVE_INFINITY} or\n * {@link Double#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0d}.\n *\n * @return this {@code Decimal128} converted to a {@code double}.\n * @since 3.10\n */\n @Override\n public double doubleValue() {\n if (isNaN()) {\n return Double.NaN;\n }\n if (isInfinite()) {\n if (isNegative()) {\n return Double.NEGATIVE_INFINITY;\n } else {\n return Double.POSITIVE_INFINITY;\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n if (hasDifferentSign(bigDecimal)) {\n return -0.0d;\n }\n return bigDecimal.doubleValue();\n }\n\n /**\n * Returns true if the encoded representation of this instance is the same as the encoded representation of {@code o}.\n *

\n * One consequence is that, whereas {@code Double.NaN != Double.NaN},\n * {@code new Decimal128(\"NaN\").equals(new Decimal128(\"NaN\")} returns true.\n *

\n *

\n * Another consequence is that, as with BigDecimal, {@code new Decimal128(\"1.0\").equals(new Decimal128(\"1.00\")} returns false,\n * because the precision is not the same and therefore the representation is not the same.\n *

\n *\n * @param o the object to compare for equality\n * @return true if the instances are equal\n */\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Decimal128 that = (Decimal128) o;\n if (high != that.high) {\n return false;\n }\n if (low != that.low) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = (int) (low ^ (low >>> 32));\n result = 31 * result + (int) (high ^ (high >>> 32));\n return result;\n }\n\n /**\n * Returns the String representation of the Decimal128 value.\n *\n * @return the String representation\n * @see \n * To-String Sprecification\n */\n @Override\n public String toString() {\n if (isNaN()) {\n return \"NaN\";\n }\n if (isInfinite()) {\n if (isNegative()) {\n return \"-Infinity\";\n } else {\n return \"Infinity\";\n }\n }\n return toStringWithBigDecimal();\n }\n\n private String toStringWithBigDecimal() {\n StringBuilder buffer = new StringBuilder();\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n String significand = bigDecimal.unscaledValue().abs().toString();\n if (isNegative()) {\n buffer.append('-');\n }\n int exponent = -bigDecimal.scale();\n int adjustedExponent = exponent + (significand.length() - 1);\n if (exponent <= 0 && adjustedExponent >= -6) {\n if (exponent == 0) {\n buffer.append(significand);\n } else {\n int pad = -exponent - significand.length();\n if (pad >= 0) {\n buffer.append('0');\n buffer.append('.');\n for (int i = 0; i < pad; i++) {\n buffer.append('0');\n }\n buffer.append(significand, 0, significand.length());\n } else {\n buffer.append(significand, 0, -pad);\n buffer.append('.');\n buffer.append(significand, -pad, -pad - exponent);\n }\n }\n } else {\n buffer.append(significand.charAt(0));\n if (significand.length() > 1) {\n buffer.append('.');\n buffer.append(significand, 1, significand.length());\n }\n buffer.append('E');\n if (adjustedExponent > 0) {\n buffer.append('+');\n }\n buffer.append(adjustedExponent);\n }\n return buffer.toString();\n }\n}\n"} {"task_id": "Java_1342", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/mongodb/mongo-java-driver/bson/src/main/org/bson/types/Decimal128.java", "mask_start_position": 13288, "mask_end_position": 13379, "canonical_solution": "public boolean isInfinite() {\n return (high & INFINITY_MASK) == INFINITY_MASK;\n }", "pre_mask_code": "package org.bson.types;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.HashSet;\nimport java.util.Set;\nimport static java.math.MathContext.DECIMAL128;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\n\n/**\n * A binary integer decimal representation of a 128-bit decimal value, supporting 34 decimal digits of significand and an exponent range\n * of -6143 to +6144.\n *\n * @since 3.4\n * @see BSON Decimal128\n * specification\n * @see binary integer decimal\n * @see decimal128 floating-point format\n * @see 754-2008 - IEEE Standard for Floating-Point Arithmetic\n */\npublic final class Decimal128 extends Number implements Comparable {\n\n private static final long serialVersionUID = 4570973266503637887L;\n\n private static final long INFINITY_MASK = 0x7800000000000000L;\n\n private static final long NaN_MASK = 0x7c00000000000000L;\n\n private static final long SIGN_BIT_MASK = 1L << 63;\n\n private static final int MIN_EXPONENT = -6176;\n\n private static final int MAX_EXPONENT = 6111;\n\n private static final int EXPONENT_OFFSET = 6176;\n\n private static final int MAX_BIT_LENGTH = 113;\n\n private static final BigInteger BIG_INT_TEN = new BigInteger(\"10\");\n\n private static final BigInteger BIG_INT_ONE = new BigInteger(\"1\");\n\n private static final BigInteger BIG_INT_ZERO = new BigInteger(\"0\");\n\n private static final Set NaN_STRINGS = new HashSet(singletonList(\"nan\"));\n\n private static final Set NEGATIVE_NaN_STRINGS = new HashSet(singletonList(\"-nan\"));\n\n private static final Set POSITIVE_INFINITY_STRINGS = new HashSet(asList(\"inf\", \"+inf\", \"infinity\", \"+infinity\"));\n\n private static final Set NEGATIVE_INFINITY_STRINGS = new HashSet(asList(\"-inf\", \"-infinity\"));\n\n /**\n * A constant holding the positive infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"Infinity\")}.\n */\n public static final Decimal128 POSITIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK, 0);\n\n /**\n * A constant holding the negative infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-Infinity\")}.\n */\n public static final Decimal128 NEGATIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a negative Not-a-Number (-NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-NaN\")}.\n */\n public static final Decimal128 NEGATIVE_NaN = fromIEEE754BIDEncoding(NaN_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a Not-a-Number (NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"NaN\")}.\n */\n public static final Decimal128 NaN = fromIEEE754BIDEncoding(NaN_MASK, 0);\n\n /**\n * A constant holding a postive zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"0\")}.\n */\n public static final Decimal128 POSITIVE_ZERO = fromIEEE754BIDEncoding(0x3040000000000000L, 0x0000000000000000L);\n\n /**\n * A constant holding a negative zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-0\")}.\n */\n public static final Decimal128 NEGATIVE_ZERO = fromIEEE754BIDEncoding(0xb040000000000000L, 0x0000000000000000L);\n\n private final long high;\n\n private final long low;\n\n /**\n * Returns a Decimal128 value representing the given String.\n *\n * @param value the Decimal128 value represented as a String\n * @return the Decimal128 value representing the given String\n * @throws NumberFormatException if the value is out of the Decimal128 range\n * @see\n * \n * From-String Specification\n */\n public static Decimal128 parse(final String value) {\n String lowerCasedValue = value.toLowerCase();\n if (NaN_STRINGS.contains(lowerCasedValue)) {\n return NaN;\n }\n if (NEGATIVE_NaN_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_NaN;\n }\n if (POSITIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return POSITIVE_INFINITY;\n }\n if (NEGATIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_INFINITY;\n }\n return new Decimal128(new BigDecimal(value), value.charAt(0) == '-');\n }\n\n /**\n * Create an instance with the given high and low order bits representing this Decimal128 as an IEEE 754-2008 128-bit decimal\n * floating point using the BID encoding scheme.\n *\n * @param high the high-order 64 bits\n * @param low the low-order 64 bits\n * @return the Decimal128 value representing the given high and low order bits\n */\n public static Decimal128 fromIEEE754BIDEncoding(final long high, final long low) {\n return new Decimal128(high, low);\n }\n\n /**\n * Constructs a Decimal128 value representing the given long.\n *\n * @param value the Decimal128 value represented as a long\n */\n public Decimal128(final long value) {\n this(new BigDecimal(value, DECIMAL128));\n }\n\n /**\n * Constructs a Decimal128 value representing the given BigDecimal.\n *\n * @param value the Decimal128 value represented as a BigDecimal\n * @throws NumberFormatException if the value is out of the Decimal128 range\n */\n public Decimal128(final BigDecimal value) {\n this(value, value.signum() == -1);\n }\n\n private Decimal128(final long high, final long low) {\n this.high = high;\n this.low = low;\n }\n\n // isNegative is necessary to detect -0, which can't be represented with a BigDecimal\n private Decimal128(final BigDecimal initialValue, final boolean isNegative) {\n long localHigh = 0;\n long localLow = 0;\n BigDecimal value = clampAndRound(initialValue);\n long exponent = -value.scale();\n if ((exponent < MIN_EXPONENT) || (exponent > MAX_EXPONENT)) {\n throw new AssertionError(\"Exponent is out of range for Decimal128 encoding: \" + exponent);\n }\n if (value.unscaledValue().bitLength() > MAX_BIT_LENGTH) {\n throw new AssertionError(\"Unscaled roundedValue is out of range for Decimal128 encoding:\" + value.unscaledValue());\n }\n BigInteger significand = value.unscaledValue().abs();\n int bitLength = significand.bitLength();\n for (int i = 0; i < Math.min(64, bitLength); i++) {\n if (significand.testBit(i)) {\n localLow |= 1L << i;\n }\n }\n for (int i = 64; i < bitLength; i++) {\n if (significand.testBit(i)) {\n localHigh |= 1L << (i - 64);\n }\n }\n long biasedExponent = exponent + EXPONENT_OFFSET;\n localHigh |= biasedExponent << 49;\n if (value.signum() == -1 || isNegative) {\n localHigh |= SIGN_BIT_MASK;\n }\n high = localHigh;\n low = localLow;\n }\n\n private BigDecimal clampAndRound(final BigDecimal initialValue) {\n BigDecimal value;\n if (-initialValue.scale() > MAX_EXPONENT) {\n int diff = -initialValue.scale() - MAX_EXPONENT;\n if (initialValue.unscaledValue().equals(BIG_INT_ZERO)) {\n value = new BigDecimal(initialValue.unscaledValue(), -MAX_EXPONENT);\n } else if (diff + initialValue.precision() > 34) {\n throw new NumberFormatException(\"Exponent is out of range for Decimal128 encoding of \" + initialValue);\n } else {\n BigInteger multiplier = BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().multiply(multiplier), initialValue.scale() + diff);\n }\n } else if (-initialValue.scale() < MIN_EXPONENT) {\n // Increasing a very negative exponent may require decreasing precision, which is rounding\n // Only round exactly (by removing precision that is all zeroes). An exception is thrown if the rounding would be inexact:\n int diff = initialValue.scale() + MIN_EXPONENT;\n int undiscardedPrecision = ensureExactRounding(initialValue, diff);\n BigInteger divisor = undiscardedPrecision == 0 ? BIG_INT_ONE : BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().divide(divisor), initialValue.scale() - diff);\n } else {\n value = initialValue.round(DECIMAL128);\n int extraPrecision = initialValue.precision() - value.precision();\n if (extraPrecision > 0) {\n // Again, only round exactly\n ensureExactRounding(initialValue, extraPrecision);\n }\n }\n return value;\n }\n\n private int ensureExactRounding(final BigDecimal initialValue, final int extraPrecision) {\n String significand = initialValue.unscaledValue().abs().toString();\n int undiscardedPrecision = Math.max(0, significand.length() - extraPrecision);\n for (int i = undiscardedPrecision; i < significand.length(); i++) {\n if (significand.charAt(i) != '0') {\n throw new NumberFormatException(\"Conversion to Decimal128 would require inexact rounding of \" + initialValue);\n }\n }\n return undiscardedPrecision;\n }\n\n /**\n * Gets the high-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the high-order 64 bits of this Decimal128\n */\n public long getHigh() {\n return high;\n }\n\n /**\n * Gets the low-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the low-order 64 bits of this Decimal128\n */\n public long getLow() {\n return low;\n }\n\n /**\n * Gets a BigDecimal that is equivalent to this Decimal128.\n *\n * @return a BigDecimal that is equivalent to this Decimal128\n * @throws ArithmeticException if the Decimal128 value is NaN, Infinity, -Infinity, or -0, none of which can be represented as a\n * BigDecimal\n */\n public BigDecimal bigDecimalValue() {\n if (isNaN()) {\n throw new ArithmeticException(\"NaN can not be converted to a BigDecimal\");\n }\n if (isInfinite()) {\n throw new ArithmeticException(\"Infinity can not be converted to a BigDecimal\");\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n // If the BigDecimal is 0, but the Decimal128 is negative, that means we have -0.\n if (isNegative() && bigDecimal.signum() == 0) {\n throw new ArithmeticException(\"Negative zero can not be converted to a BigDecimal\");\n }\n return bigDecimal;\n }\n\n // Make sure that the argument comes from a call to bigDecimalValueNoNegativeZeroCheck on this instance\n private boolean hasDifferentSign(final BigDecimal bigDecimal) {\n return isNegative() && bigDecimal.signum() == 0;\n }\n\n private boolean isZero(final BigDecimal bigDecimal) {\n return !isNaN() && !isInfinite() && bigDecimal.compareTo(BigDecimal.ZERO) == 0;\n }\n\n private BigDecimal bigDecimalValueNoNegativeZeroCheck() {\n int scale = -getExponent();\n if (twoHighestCombinationBitsAreSet()) {\n return BigDecimal.valueOf(0, scale);\n }\n return new BigDecimal(new BigInteger(isNegative() ? -1 : 1, getBytes()), scale);\n }\n\n // May have leading zeros. Strip them before considering making this method public\n private byte[] getBytes() {\n byte[] bytes = new byte[15];\n long mask = 0x00000000000000ff;\n for (int i = 14; i >= 7; i--) {\n bytes[i] = (byte) ((low & mask) >>> ((14 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x00000000000000ff;\n for (int i = 6; i >= 1; i--) {\n bytes[i] = (byte) ((high & mask) >>> ((6 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x0001000000000000L;\n bytes[0] = (byte) ((high & mask) >>> 48);\n return bytes;\n }\n\n private int getExponent() {\n if (twoHighestCombinationBitsAreSet()) {\n return (int) ((high & 0x1fffe00000000000L) >>> 47) - EXPONENT_OFFSET;\n } else {\n return (int) ((high & 0x7fff800000000000L) >>> 49) - EXPONENT_OFFSET;\n }\n }\n\n private boolean twoHighestCombinationBitsAreSet() {\n return (high & 3L << 61) == 3L << 61;\n }\n\n /**\n * Returns true if this Decimal128 is negative.\n *\n * @return true if this Decimal128 is negative\n */\n public boolean isNegative() {\n return (high & SIGN_BIT_MASK) == SIGN_BIT_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is infinite.\n *\n * @return true if this Decimal128 is infinite\n */\n ", "post_mask_code": "\n\n /**\n * Returns true if this Decimal128 is finite.\n *\n * @return true if this Decimal128 is finite\n */\n public boolean isFinite() {\n return !isInfinite();\n }\n\n /**\n * Returns true if this Decimal128 is Not-A-Number (NaN).\n *\n * @return true if this Decimal128 is Not-A-Number\n */\n public boolean isNaN() {\n return (high & NaN_MASK) == NaN_MASK;\n }\n\n @Override\n public int compareTo(final Decimal128 o) {\n if (isNaN()) {\n return o.isNaN() ? 0 : 1;\n }\n if (isInfinite()) {\n if (isNegative()) {\n if (o.isInfinite() && o.isNegative()) {\n return 0;\n } else {\n return -1;\n }\n } else {\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite() && !o.isNegative()) {\n return 0;\n } else {\n return 1;\n }\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n BigDecimal otherBigDecimal = o.bigDecimalValueNoNegativeZeroCheck();\n if (isZero(bigDecimal) && o.isZero(otherBigDecimal)) {\n if (hasDifferentSign(bigDecimal)) {\n if (o.hasDifferentSign(otherBigDecimal)) {\n return 0;\n } else {\n return -1;\n }\n } else if (o.hasDifferentSign(otherBigDecimal)) {\n return 1;\n }\n }\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite()) {\n if (o.isNegative()) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return bigDecimal.compareTo(otherBigDecimal);\n }\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code int}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code int} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code int}, only the\n * low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0}.\n *\n * @return this {@code Decimal128} converted to a {@code int}.\n * @since 3.10\n */\n @Override\n public int intValue() {\n return (int) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code long}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code long} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code long}, only the\n * low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0L}.\n *\n * @return this {@code Decimal128} converted to a {@code long}.\n * @since 3.10\n */\n @Override\n public long longValue() {\n return (long) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code float}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code float}, it will be converted to {@link Float#NEGATIVE_INFINITY} or\n * {@link Float#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0f}.\n *\n * @return this {@code Decimal128} converted to a {@code float}.\n * @since 3.10\n */\n @Override\n public float floatValue() {\n return (float) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code double}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code double}, it will be converted to {@link Double#NEGATIVE_INFINITY} or\n * {@link Double#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0d}.\n *\n * @return this {@code Decimal128} converted to a {@code double}.\n * @since 3.10\n */\n @Override\n public double doubleValue() {\n if (isNaN()) {\n return Double.NaN;\n }\n if (isInfinite()) {\n if (isNegative()) {\n return Double.NEGATIVE_INFINITY;\n } else {\n return Double.POSITIVE_INFINITY;\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n if (hasDifferentSign(bigDecimal)) {\n return -0.0d;\n }\n return bigDecimal.doubleValue();\n }\n\n /**\n * Returns true if the encoded representation of this instance is the same as the encoded representation of {@code o}.\n *

\n * One consequence is that, whereas {@code Double.NaN != Double.NaN},\n * {@code new Decimal128(\"NaN\").equals(new Decimal128(\"NaN\")} returns true.\n *

\n *

\n * Another consequence is that, as with BigDecimal, {@code new Decimal128(\"1.0\").equals(new Decimal128(\"1.00\")} returns false,\n * because the precision is not the same and therefore the representation is not the same.\n *

\n *\n * @param o the object to compare for equality\n * @return true if the instances are equal\n */\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Decimal128 that = (Decimal128) o;\n if (high != that.high) {\n return false;\n }\n if (low != that.low) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = (int) (low ^ (low >>> 32));\n result = 31 * result + (int) (high ^ (high >>> 32));\n return result;\n }\n\n /**\n * Returns the String representation of the Decimal128 value.\n *\n * @return the String representation\n * @see \n * To-String Sprecification\n */\n @Override\n public String toString() {\n if (isNaN()) {\n return \"NaN\";\n }\n if (isInfinite()) {\n if (isNegative()) {\n return \"-Infinity\";\n } else {\n return \"Infinity\";\n }\n }\n return toStringWithBigDecimal();\n }\n\n private String toStringWithBigDecimal() {\n StringBuilder buffer = new StringBuilder();\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n String significand = bigDecimal.unscaledValue().abs().toString();\n if (isNegative()) {\n buffer.append('-');\n }\n int exponent = -bigDecimal.scale();\n int adjustedExponent = exponent + (significand.length() - 1);\n if (exponent <= 0 && adjustedExponent >= -6) {\n if (exponent == 0) {\n buffer.append(significand);\n } else {\n int pad = -exponent - significand.length();\n if (pad >= 0) {\n buffer.append('0');\n buffer.append('.');\n for (int i = 0; i < pad; i++) {\n buffer.append('0');\n }\n buffer.append(significand, 0, significand.length());\n } else {\n buffer.append(significand, 0, -pad);\n buffer.append('.');\n buffer.append(significand, -pad, -pad - exponent);\n }\n }\n } else {\n buffer.append(significand.charAt(0));\n if (significand.length() > 1) {\n buffer.append('.');\n buffer.append(significand, 1, significand.length());\n }\n buffer.append('E');\n if (adjustedExponent > 0) {\n buffer.append('+');\n }\n buffer.append(adjustedExponent);\n }\n return buffer.toString();\n }\n}\n"} {"task_id": "Java_1343", "language": "Java", "task_type": "if_statement", "source_file": "java/github/mongodb/mongo-java-driver/bson/src/main/org/bson/types/Decimal128.java", "mask_start_position": 19957, "mask_end_position": 20039, "canonical_solution": "if (o == null || getClass() != o.getClass()) {\n return false;\n }", "pre_mask_code": "package org.bson.types;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.HashSet;\nimport java.util.Set;\nimport static java.math.MathContext.DECIMAL128;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\n\n/**\n * A binary integer decimal representation of a 128-bit decimal value, supporting 34 decimal digits of significand and an exponent range\n * of -6143 to +6144.\n *\n * @since 3.4\n * @see BSON Decimal128\n * specification\n * @see binary integer decimal\n * @see decimal128 floating-point format\n * @see 754-2008 - IEEE Standard for Floating-Point Arithmetic\n */\npublic final class Decimal128 extends Number implements Comparable {\n\n private static final long serialVersionUID = 4570973266503637887L;\n\n private static final long INFINITY_MASK = 0x7800000000000000L;\n\n private static final long NaN_MASK = 0x7c00000000000000L;\n\n private static final long SIGN_BIT_MASK = 1L << 63;\n\n private static final int MIN_EXPONENT = -6176;\n\n private static final int MAX_EXPONENT = 6111;\n\n private static final int EXPONENT_OFFSET = 6176;\n\n private static final int MAX_BIT_LENGTH = 113;\n\n private static final BigInteger BIG_INT_TEN = new BigInteger(\"10\");\n\n private static final BigInteger BIG_INT_ONE = new BigInteger(\"1\");\n\n private static final BigInteger BIG_INT_ZERO = new BigInteger(\"0\");\n\n private static final Set NaN_STRINGS = new HashSet(singletonList(\"nan\"));\n\n private static final Set NEGATIVE_NaN_STRINGS = new HashSet(singletonList(\"-nan\"));\n\n private static final Set POSITIVE_INFINITY_STRINGS = new HashSet(asList(\"inf\", \"+inf\", \"infinity\", \"+infinity\"));\n\n private static final Set NEGATIVE_INFINITY_STRINGS = new HashSet(asList(\"-inf\", \"-infinity\"));\n\n /**\n * A constant holding the positive infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"Infinity\")}.\n */\n public static final Decimal128 POSITIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK, 0);\n\n /**\n * A constant holding the negative infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-Infinity\")}.\n */\n public static final Decimal128 NEGATIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a negative Not-a-Number (-NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-NaN\")}.\n */\n public static final Decimal128 NEGATIVE_NaN = fromIEEE754BIDEncoding(NaN_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a Not-a-Number (NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"NaN\")}.\n */\n public static final Decimal128 NaN = fromIEEE754BIDEncoding(NaN_MASK, 0);\n\n /**\n * A constant holding a postive zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"0\")}.\n */\n public static final Decimal128 POSITIVE_ZERO = fromIEEE754BIDEncoding(0x3040000000000000L, 0x0000000000000000L);\n\n /**\n * A constant holding a negative zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-0\")}.\n */\n public static final Decimal128 NEGATIVE_ZERO = fromIEEE754BIDEncoding(0xb040000000000000L, 0x0000000000000000L);\n\n private final long high;\n\n private final long low;\n\n /**\n * Returns a Decimal128 value representing the given String.\n *\n * @param value the Decimal128 value represented as a String\n * @return the Decimal128 value representing the given String\n * @throws NumberFormatException if the value is out of the Decimal128 range\n * @see\n * \n * From-String Specification\n */\n public static Decimal128 parse(final String value) {\n String lowerCasedValue = value.toLowerCase();\n if (NaN_STRINGS.contains(lowerCasedValue)) {\n return NaN;\n }\n if (NEGATIVE_NaN_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_NaN;\n }\n if (POSITIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return POSITIVE_INFINITY;\n }\n if (NEGATIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_INFINITY;\n }\n return new Decimal128(new BigDecimal(value), value.charAt(0) == '-');\n }\n\n /**\n * Create an instance with the given high and low order bits representing this Decimal128 as an IEEE 754-2008 128-bit decimal\n * floating point using the BID encoding scheme.\n *\n * @param high the high-order 64 bits\n * @param low the low-order 64 bits\n * @return the Decimal128 value representing the given high and low order bits\n */\n public static Decimal128 fromIEEE754BIDEncoding(final long high, final long low) {\n return new Decimal128(high, low);\n }\n\n /**\n * Constructs a Decimal128 value representing the given long.\n *\n * @param value the Decimal128 value represented as a long\n */\n public Decimal128(final long value) {\n this(new BigDecimal(value, DECIMAL128));\n }\n\n /**\n * Constructs a Decimal128 value representing the given BigDecimal.\n *\n * @param value the Decimal128 value represented as a BigDecimal\n * @throws NumberFormatException if the value is out of the Decimal128 range\n */\n public Decimal128(final BigDecimal value) {\n this(value, value.signum() == -1);\n }\n\n private Decimal128(final long high, final long low) {\n this.high = high;\n this.low = low;\n }\n\n // isNegative is necessary to detect -0, which can't be represented with a BigDecimal\n private Decimal128(final BigDecimal initialValue, final boolean isNegative) {\n long localHigh = 0;\n long localLow = 0;\n BigDecimal value = clampAndRound(initialValue);\n long exponent = -value.scale();\n if ((exponent < MIN_EXPONENT) || (exponent > MAX_EXPONENT)) {\n throw new AssertionError(\"Exponent is out of range for Decimal128 encoding: \" + exponent);\n }\n if (value.unscaledValue().bitLength() > MAX_BIT_LENGTH) {\n throw new AssertionError(\"Unscaled roundedValue is out of range for Decimal128 encoding:\" + value.unscaledValue());\n }\n BigInteger significand = value.unscaledValue().abs();\n int bitLength = significand.bitLength();\n for (int i = 0; i < Math.min(64, bitLength); i++) {\n if (significand.testBit(i)) {\n localLow |= 1L << i;\n }\n }\n for (int i = 64; i < bitLength; i++) {\n if (significand.testBit(i)) {\n localHigh |= 1L << (i - 64);\n }\n }\n long biasedExponent = exponent + EXPONENT_OFFSET;\n localHigh |= biasedExponent << 49;\n if (value.signum() == -1 || isNegative) {\n localHigh |= SIGN_BIT_MASK;\n }\n high = localHigh;\n low = localLow;\n }\n\n private BigDecimal clampAndRound(final BigDecimal initialValue) {\n BigDecimal value;\n if (-initialValue.scale() > MAX_EXPONENT) {\n int diff = -initialValue.scale() - MAX_EXPONENT;\n if (initialValue.unscaledValue().equals(BIG_INT_ZERO)) {\n value = new BigDecimal(initialValue.unscaledValue(), -MAX_EXPONENT);\n } else if (diff + initialValue.precision() > 34) {\n throw new NumberFormatException(\"Exponent is out of range for Decimal128 encoding of \" + initialValue);\n } else {\n BigInteger multiplier = BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().multiply(multiplier), initialValue.scale() + diff);\n }\n } else if (-initialValue.scale() < MIN_EXPONENT) {\n // Increasing a very negative exponent may require decreasing precision, which is rounding\n // Only round exactly (by removing precision that is all zeroes). An exception is thrown if the rounding would be inexact:\n int diff = initialValue.scale() + MIN_EXPONENT;\n int undiscardedPrecision = ensureExactRounding(initialValue, diff);\n BigInteger divisor = undiscardedPrecision == 0 ? BIG_INT_ONE : BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().divide(divisor), initialValue.scale() - diff);\n } else {\n value = initialValue.round(DECIMAL128);\n int extraPrecision = initialValue.precision() - value.precision();\n if (extraPrecision > 0) {\n // Again, only round exactly\n ensureExactRounding(initialValue, extraPrecision);\n }\n }\n return value;\n }\n\n private int ensureExactRounding(final BigDecimal initialValue, final int extraPrecision) {\n String significand = initialValue.unscaledValue().abs().toString();\n int undiscardedPrecision = Math.max(0, significand.length() - extraPrecision);\n for (int i = undiscardedPrecision; i < significand.length(); i++) {\n if (significand.charAt(i) != '0') {\n throw new NumberFormatException(\"Conversion to Decimal128 would require inexact rounding of \" + initialValue);\n }\n }\n return undiscardedPrecision;\n }\n\n /**\n * Gets the high-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the high-order 64 bits of this Decimal128\n */\n public long getHigh() {\n return high;\n }\n\n /**\n * Gets the low-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the low-order 64 bits of this Decimal128\n */\n public long getLow() {\n return low;\n }\n\n /**\n * Gets a BigDecimal that is equivalent to this Decimal128.\n *\n * @return a BigDecimal that is equivalent to this Decimal128\n * @throws ArithmeticException if the Decimal128 value is NaN, Infinity, -Infinity, or -0, none of which can be represented as a\n * BigDecimal\n */\n public BigDecimal bigDecimalValue() {\n if (isNaN()) {\n throw new ArithmeticException(\"NaN can not be converted to a BigDecimal\");\n }\n if (isInfinite()) {\n throw new ArithmeticException(\"Infinity can not be converted to a BigDecimal\");\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n // If the BigDecimal is 0, but the Decimal128 is negative, that means we have -0.\n if (isNegative() && bigDecimal.signum() == 0) {\n throw new ArithmeticException(\"Negative zero can not be converted to a BigDecimal\");\n }\n return bigDecimal;\n }\n\n // Make sure that the argument comes from a call to bigDecimalValueNoNegativeZeroCheck on this instance\n private boolean hasDifferentSign(final BigDecimal bigDecimal) {\n return isNegative() && bigDecimal.signum() == 0;\n }\n\n private boolean isZero(final BigDecimal bigDecimal) {\n return !isNaN() && !isInfinite() && bigDecimal.compareTo(BigDecimal.ZERO) == 0;\n }\n\n private BigDecimal bigDecimalValueNoNegativeZeroCheck() {\n int scale = -getExponent();\n if (twoHighestCombinationBitsAreSet()) {\n return BigDecimal.valueOf(0, scale);\n }\n return new BigDecimal(new BigInteger(isNegative() ? -1 : 1, getBytes()), scale);\n }\n\n // May have leading zeros. Strip them before considering making this method public\n private byte[] getBytes() {\n byte[] bytes = new byte[15];\n long mask = 0x00000000000000ff;\n for (int i = 14; i >= 7; i--) {\n bytes[i] = (byte) ((low & mask) >>> ((14 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x00000000000000ff;\n for (int i = 6; i >= 1; i--) {\n bytes[i] = (byte) ((high & mask) >>> ((6 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x0001000000000000L;\n bytes[0] = (byte) ((high & mask) >>> 48);\n return bytes;\n }\n\n private int getExponent() {\n if (twoHighestCombinationBitsAreSet()) {\n return (int) ((high & 0x1fffe00000000000L) >>> 47) - EXPONENT_OFFSET;\n } else {\n return (int) ((high & 0x7fff800000000000L) >>> 49) - EXPONENT_OFFSET;\n }\n }\n\n private boolean twoHighestCombinationBitsAreSet() {\n return (high & 3L << 61) == 3L << 61;\n }\n\n /**\n * Returns true if this Decimal128 is negative.\n *\n * @return true if this Decimal128 is negative\n */\n public boolean isNegative() {\n return (high & SIGN_BIT_MASK) == SIGN_BIT_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is infinite.\n *\n * @return true if this Decimal128 is infinite\n */\n public boolean isInfinite() {\n return (high & INFINITY_MASK) == INFINITY_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is finite.\n *\n * @return true if this Decimal128 is finite\n */\n public boolean isFinite() {\n return !isInfinite();\n }\n\n /**\n * Returns true if this Decimal128 is Not-A-Number (NaN).\n *\n * @return true if this Decimal128 is Not-A-Number\n */\n public boolean isNaN() {\n return (high & NaN_MASK) == NaN_MASK;\n }\n\n @Override\n public int compareTo(final Decimal128 o) {\n if (isNaN()) {\n return o.isNaN() ? 0 : 1;\n }\n if (isInfinite()) {\n if (isNegative()) {\n if (o.isInfinite() && o.isNegative()) {\n return 0;\n } else {\n return -1;\n }\n } else {\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite() && !o.isNegative()) {\n return 0;\n } else {\n return 1;\n }\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n BigDecimal otherBigDecimal = o.bigDecimalValueNoNegativeZeroCheck();\n if (isZero(bigDecimal) && o.isZero(otherBigDecimal)) {\n if (hasDifferentSign(bigDecimal)) {\n if (o.hasDifferentSign(otherBigDecimal)) {\n return 0;\n } else {\n return -1;\n }\n } else if (o.hasDifferentSign(otherBigDecimal)) {\n return 1;\n }\n }\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite()) {\n if (o.isNegative()) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return bigDecimal.compareTo(otherBigDecimal);\n }\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code int}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code int} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code int}, only the\n * low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0}.\n *\n * @return this {@code Decimal128} converted to a {@code int}.\n * @since 3.10\n */\n @Override\n public int intValue() {\n return (int) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code long}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code long} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code long}, only the\n * low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0L}.\n *\n * @return this {@code Decimal128} converted to a {@code long}.\n * @since 3.10\n */\n @Override\n public long longValue() {\n return (long) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code float}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code float}, it will be converted to {@link Float#NEGATIVE_INFINITY} or\n * {@link Float#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0f}.\n *\n * @return this {@code Decimal128} converted to a {@code float}.\n * @since 3.10\n */\n @Override\n public float floatValue() {\n return (float) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code double}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code double}, it will be converted to {@link Double#NEGATIVE_INFINITY} or\n * {@link Double#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0d}.\n *\n * @return this {@code Decimal128} converted to a {@code double}.\n * @since 3.10\n */\n @Override\n public double doubleValue() {\n if (isNaN()) {\n return Double.NaN;\n }\n if (isInfinite()) {\n if (isNegative()) {\n return Double.NEGATIVE_INFINITY;\n } else {\n return Double.POSITIVE_INFINITY;\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n if (hasDifferentSign(bigDecimal)) {\n return -0.0d;\n }\n return bigDecimal.doubleValue();\n }\n\n /**\n * Returns true if the encoded representation of this instance is the same as the encoded representation of {@code o}.\n *

\n * One consequence is that, whereas {@code Double.NaN != Double.NaN},\n * {@code new Decimal128(\"NaN\").equals(new Decimal128(\"NaN\")} returns true.\n *

\n *

\n * Another consequence is that, as with BigDecimal, {@code new Decimal128(\"1.0\").equals(new Decimal128(\"1.00\")} returns false,\n * because the precision is not the same and therefore the representation is not the same.\n *

\n *\n * @param o the object to compare for equality\n * @return true if the instances are equal\n */\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n ", "post_mask_code": "\n Decimal128 that = (Decimal128) o;\n if (high != that.high) {\n return false;\n }\n if (low != that.low) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = (int) (low ^ (low >>> 32));\n result = 31 * result + (int) (high ^ (high >>> 32));\n return result;\n }\n\n /**\n * Returns the String representation of the Decimal128 value.\n *\n * @return the String representation\n * @see \n * To-String Sprecification\n */\n @Override\n public String toString() {\n if (isNaN()) {\n return \"NaN\";\n }\n if (isInfinite()) {\n if (isNegative()) {\n return \"-Infinity\";\n } else {\n return \"Infinity\";\n }\n }\n return toStringWithBigDecimal();\n }\n\n private String toStringWithBigDecimal() {\n StringBuilder buffer = new StringBuilder();\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n String significand = bigDecimal.unscaledValue().abs().toString();\n if (isNegative()) {\n buffer.append('-');\n }\n int exponent = -bigDecimal.scale();\n int adjustedExponent = exponent + (significand.length() - 1);\n if (exponent <= 0 && adjustedExponent >= -6) {\n if (exponent == 0) {\n buffer.append(significand);\n } else {\n int pad = -exponent - significand.length();\n if (pad >= 0) {\n buffer.append('0');\n buffer.append('.');\n for (int i = 0; i < pad; i++) {\n buffer.append('0');\n }\n buffer.append(significand, 0, significand.length());\n } else {\n buffer.append(significand, 0, -pad);\n buffer.append('.');\n buffer.append(significand, -pad, -pad - exponent);\n }\n }\n } else {\n buffer.append(significand.charAt(0));\n if (significand.length() > 1) {\n buffer.append('.');\n buffer.append(significand, 1, significand.length());\n }\n buffer.append('E');\n if (adjustedExponent > 0) {\n buffer.append('+');\n }\n buffer.append(adjustedExponent);\n }\n return buffer.toString();\n }\n}\n"} {"task_id": "Java_1344", "language": "Java", "task_type": "for_statement", "source_file": "java/github/mongodb/mongo-java-driver/bson/src/main/org/bson/types/Decimal128.java", "mask_start_position": 21739, "mask_end_position": 21836, "canonical_solution": "for (int i = 0; i < pad; i++) {\n buffer.append('0');\n }", "pre_mask_code": "package org.bson.types;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.HashSet;\nimport java.util.Set;\nimport static java.math.MathContext.DECIMAL128;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\n\n/**\n * A binary integer decimal representation of a 128-bit decimal value, supporting 34 decimal digits of significand and an exponent range\n * of -6143 to +6144.\n *\n * @since 3.4\n * @see BSON Decimal128\n * specification\n * @see binary integer decimal\n * @see decimal128 floating-point format\n * @see 754-2008 - IEEE Standard for Floating-Point Arithmetic\n */\npublic final class Decimal128 extends Number implements Comparable {\n\n private static final long serialVersionUID = 4570973266503637887L;\n\n private static final long INFINITY_MASK = 0x7800000000000000L;\n\n private static final long NaN_MASK = 0x7c00000000000000L;\n\n private static final long SIGN_BIT_MASK = 1L << 63;\n\n private static final int MIN_EXPONENT = -6176;\n\n private static final int MAX_EXPONENT = 6111;\n\n private static final int EXPONENT_OFFSET = 6176;\n\n private static final int MAX_BIT_LENGTH = 113;\n\n private static final BigInteger BIG_INT_TEN = new BigInteger(\"10\");\n\n private static final BigInteger BIG_INT_ONE = new BigInteger(\"1\");\n\n private static final BigInteger BIG_INT_ZERO = new BigInteger(\"0\");\n\n private static final Set NaN_STRINGS = new HashSet(singletonList(\"nan\"));\n\n private static final Set NEGATIVE_NaN_STRINGS = new HashSet(singletonList(\"-nan\"));\n\n private static final Set POSITIVE_INFINITY_STRINGS = new HashSet(asList(\"inf\", \"+inf\", \"infinity\", \"+infinity\"));\n\n private static final Set NEGATIVE_INFINITY_STRINGS = new HashSet(asList(\"-inf\", \"-infinity\"));\n\n /**\n * A constant holding the positive infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"Infinity\")}.\n */\n public static final Decimal128 POSITIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK, 0);\n\n /**\n * A constant holding the negative infinity of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-Infinity\")}.\n */\n public static final Decimal128 NEGATIVE_INFINITY = fromIEEE754BIDEncoding(INFINITY_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a negative Not-a-Number (-NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-NaN\")}.\n */\n public static final Decimal128 NEGATIVE_NaN = fromIEEE754BIDEncoding(NaN_MASK | SIGN_BIT_MASK, 0);\n\n /**\n * A constant holding a Not-a-Number (NaN) value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"NaN\")}.\n */\n public static final Decimal128 NaN = fromIEEE754BIDEncoding(NaN_MASK, 0);\n\n /**\n * A constant holding a postive zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"0\")}.\n */\n public static final Decimal128 POSITIVE_ZERO = fromIEEE754BIDEncoding(0x3040000000000000L, 0x0000000000000000L);\n\n /**\n * A constant holding a negative zero value of type {@code Decimal128}. It is equal to the value return by\n * {@code Decimal128.valueOf(\"-0\")}.\n */\n public static final Decimal128 NEGATIVE_ZERO = fromIEEE754BIDEncoding(0xb040000000000000L, 0x0000000000000000L);\n\n private final long high;\n\n private final long low;\n\n /**\n * Returns a Decimal128 value representing the given String.\n *\n * @param value the Decimal128 value represented as a String\n * @return the Decimal128 value representing the given String\n * @throws NumberFormatException if the value is out of the Decimal128 range\n * @see\n * \n * From-String Specification\n */\n public static Decimal128 parse(final String value) {\n String lowerCasedValue = value.toLowerCase();\n if (NaN_STRINGS.contains(lowerCasedValue)) {\n return NaN;\n }\n if (NEGATIVE_NaN_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_NaN;\n }\n if (POSITIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return POSITIVE_INFINITY;\n }\n if (NEGATIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {\n return NEGATIVE_INFINITY;\n }\n return new Decimal128(new BigDecimal(value), value.charAt(0) == '-');\n }\n\n /**\n * Create an instance with the given high and low order bits representing this Decimal128 as an IEEE 754-2008 128-bit decimal\n * floating point using the BID encoding scheme.\n *\n * @param high the high-order 64 bits\n * @param low the low-order 64 bits\n * @return the Decimal128 value representing the given high and low order bits\n */\n public static Decimal128 fromIEEE754BIDEncoding(final long high, final long low) {\n return new Decimal128(high, low);\n }\n\n /**\n * Constructs a Decimal128 value representing the given long.\n *\n * @param value the Decimal128 value represented as a long\n */\n public Decimal128(final long value) {\n this(new BigDecimal(value, DECIMAL128));\n }\n\n /**\n * Constructs a Decimal128 value representing the given BigDecimal.\n *\n * @param value the Decimal128 value represented as a BigDecimal\n * @throws NumberFormatException if the value is out of the Decimal128 range\n */\n public Decimal128(final BigDecimal value) {\n this(value, value.signum() == -1);\n }\n\n private Decimal128(final long high, final long low) {\n this.high = high;\n this.low = low;\n }\n\n // isNegative is necessary to detect -0, which can't be represented with a BigDecimal\n private Decimal128(final BigDecimal initialValue, final boolean isNegative) {\n long localHigh = 0;\n long localLow = 0;\n BigDecimal value = clampAndRound(initialValue);\n long exponent = -value.scale();\n if ((exponent < MIN_EXPONENT) || (exponent > MAX_EXPONENT)) {\n throw new AssertionError(\"Exponent is out of range for Decimal128 encoding: \" + exponent);\n }\n if (value.unscaledValue().bitLength() > MAX_BIT_LENGTH) {\n throw new AssertionError(\"Unscaled roundedValue is out of range for Decimal128 encoding:\" + value.unscaledValue());\n }\n BigInteger significand = value.unscaledValue().abs();\n int bitLength = significand.bitLength();\n for (int i = 0; i < Math.min(64, bitLength); i++) {\n if (significand.testBit(i)) {\n localLow |= 1L << i;\n }\n }\n for (int i = 64; i < bitLength; i++) {\n if (significand.testBit(i)) {\n localHigh |= 1L << (i - 64);\n }\n }\n long biasedExponent = exponent + EXPONENT_OFFSET;\n localHigh |= biasedExponent << 49;\n if (value.signum() == -1 || isNegative) {\n localHigh |= SIGN_BIT_MASK;\n }\n high = localHigh;\n low = localLow;\n }\n\n private BigDecimal clampAndRound(final BigDecimal initialValue) {\n BigDecimal value;\n if (-initialValue.scale() > MAX_EXPONENT) {\n int diff = -initialValue.scale() - MAX_EXPONENT;\n if (initialValue.unscaledValue().equals(BIG_INT_ZERO)) {\n value = new BigDecimal(initialValue.unscaledValue(), -MAX_EXPONENT);\n } else if (diff + initialValue.precision() > 34) {\n throw new NumberFormatException(\"Exponent is out of range for Decimal128 encoding of \" + initialValue);\n } else {\n BigInteger multiplier = BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().multiply(multiplier), initialValue.scale() + diff);\n }\n } else if (-initialValue.scale() < MIN_EXPONENT) {\n // Increasing a very negative exponent may require decreasing precision, which is rounding\n // Only round exactly (by removing precision that is all zeroes). An exception is thrown if the rounding would be inexact:\n int diff = initialValue.scale() + MIN_EXPONENT;\n int undiscardedPrecision = ensureExactRounding(initialValue, diff);\n BigInteger divisor = undiscardedPrecision == 0 ? BIG_INT_ONE : BIG_INT_TEN.pow(diff);\n value = new BigDecimal(initialValue.unscaledValue().divide(divisor), initialValue.scale() - diff);\n } else {\n value = initialValue.round(DECIMAL128);\n int extraPrecision = initialValue.precision() - value.precision();\n if (extraPrecision > 0) {\n // Again, only round exactly\n ensureExactRounding(initialValue, extraPrecision);\n }\n }\n return value;\n }\n\n private int ensureExactRounding(final BigDecimal initialValue, final int extraPrecision) {\n String significand = initialValue.unscaledValue().abs().toString();\n int undiscardedPrecision = Math.max(0, significand.length() - extraPrecision);\n for (int i = undiscardedPrecision; i < significand.length(); i++) {\n if (significand.charAt(i) != '0') {\n throw new NumberFormatException(\"Conversion to Decimal128 would require inexact rounding of \" + initialValue);\n }\n }\n return undiscardedPrecision;\n }\n\n /**\n * Gets the high-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the high-order 64 bits of this Decimal128\n */\n public long getHigh() {\n return high;\n }\n\n /**\n * Gets the low-order 64 bits of the IEEE 754-2008 128-bit decimal floating point encoding for this Decimal128, using the BID encoding\n * scheme.\n *\n * @return the low-order 64 bits of this Decimal128\n */\n public long getLow() {\n return low;\n }\n\n /**\n * Gets a BigDecimal that is equivalent to this Decimal128.\n *\n * @return a BigDecimal that is equivalent to this Decimal128\n * @throws ArithmeticException if the Decimal128 value is NaN, Infinity, -Infinity, or -0, none of which can be represented as a\n * BigDecimal\n */\n public BigDecimal bigDecimalValue() {\n if (isNaN()) {\n throw new ArithmeticException(\"NaN can not be converted to a BigDecimal\");\n }\n if (isInfinite()) {\n throw new ArithmeticException(\"Infinity can not be converted to a BigDecimal\");\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n // If the BigDecimal is 0, but the Decimal128 is negative, that means we have -0.\n if (isNegative() && bigDecimal.signum() == 0) {\n throw new ArithmeticException(\"Negative zero can not be converted to a BigDecimal\");\n }\n return bigDecimal;\n }\n\n // Make sure that the argument comes from a call to bigDecimalValueNoNegativeZeroCheck on this instance\n private boolean hasDifferentSign(final BigDecimal bigDecimal) {\n return isNegative() && bigDecimal.signum() == 0;\n }\n\n private boolean isZero(final BigDecimal bigDecimal) {\n return !isNaN() && !isInfinite() && bigDecimal.compareTo(BigDecimal.ZERO) == 0;\n }\n\n private BigDecimal bigDecimalValueNoNegativeZeroCheck() {\n int scale = -getExponent();\n if (twoHighestCombinationBitsAreSet()) {\n return BigDecimal.valueOf(0, scale);\n }\n return new BigDecimal(new BigInteger(isNegative() ? -1 : 1, getBytes()), scale);\n }\n\n // May have leading zeros. Strip them before considering making this method public\n private byte[] getBytes() {\n byte[] bytes = new byte[15];\n long mask = 0x00000000000000ff;\n for (int i = 14; i >= 7; i--) {\n bytes[i] = (byte) ((low & mask) >>> ((14 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x00000000000000ff;\n for (int i = 6; i >= 1; i--) {\n bytes[i] = (byte) ((high & mask) >>> ((6 - i) << 3));\n mask = mask << 8;\n }\n mask = 0x0001000000000000L;\n bytes[0] = (byte) ((high & mask) >>> 48);\n return bytes;\n }\n\n private int getExponent() {\n if (twoHighestCombinationBitsAreSet()) {\n return (int) ((high & 0x1fffe00000000000L) >>> 47) - EXPONENT_OFFSET;\n } else {\n return (int) ((high & 0x7fff800000000000L) >>> 49) - EXPONENT_OFFSET;\n }\n }\n\n private boolean twoHighestCombinationBitsAreSet() {\n return (high & 3L << 61) == 3L << 61;\n }\n\n /**\n * Returns true if this Decimal128 is negative.\n *\n * @return true if this Decimal128 is negative\n */\n public boolean isNegative() {\n return (high & SIGN_BIT_MASK) == SIGN_BIT_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is infinite.\n *\n * @return true if this Decimal128 is infinite\n */\n public boolean isInfinite() {\n return (high & INFINITY_MASK) == INFINITY_MASK;\n }\n\n /**\n * Returns true if this Decimal128 is finite.\n *\n * @return true if this Decimal128 is finite\n */\n public boolean isFinite() {\n return !isInfinite();\n }\n\n /**\n * Returns true if this Decimal128 is Not-A-Number (NaN).\n *\n * @return true if this Decimal128 is Not-A-Number\n */\n public boolean isNaN() {\n return (high & NaN_MASK) == NaN_MASK;\n }\n\n @Override\n public int compareTo(final Decimal128 o) {\n if (isNaN()) {\n return o.isNaN() ? 0 : 1;\n }\n if (isInfinite()) {\n if (isNegative()) {\n if (o.isInfinite() && o.isNegative()) {\n return 0;\n } else {\n return -1;\n }\n } else {\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite() && !o.isNegative()) {\n return 0;\n } else {\n return 1;\n }\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n BigDecimal otherBigDecimal = o.bigDecimalValueNoNegativeZeroCheck();\n if (isZero(bigDecimal) && o.isZero(otherBigDecimal)) {\n if (hasDifferentSign(bigDecimal)) {\n if (o.hasDifferentSign(otherBigDecimal)) {\n return 0;\n } else {\n return -1;\n }\n } else if (o.hasDifferentSign(otherBigDecimal)) {\n return 1;\n }\n }\n if (o.isNaN()) {\n return -1;\n } else if (o.isInfinite()) {\n if (o.isNegative()) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return bigDecimal.compareTo(otherBigDecimal);\n }\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code int}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code int} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code int}, only the\n * low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0}.\n *\n * @return this {@code Decimal128} converted to a {@code int}.\n * @since 3.10\n */\n @Override\n public int intValue() {\n return (int) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code long}. This conversion is analogous to the narrowing primitive conversion from\n * {@code double} to {@code long} as defined in The Java™ Language Specification: any fractional part of this\n * {@code Decimal128} will be discarded, and if the resulting integral value is too big to fit in a {@code long}, only the\n * low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this\n * {@code Decimal128} value as well as return a result with the opposite sign. Note that {@code #NEGATIVE_ZERO} is converted to\n * {@code 0L}.\n *\n * @return this {@code Decimal128} converted to a {@code long}.\n * @since 3.10\n */\n @Override\n public long longValue() {\n return (long) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code float}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code float}, it will be converted to {@link Float#NEGATIVE_INFINITY} or\n * {@link Float#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0f}.\n *\n * @return this {@code Decimal128} converted to a {@code float}.\n * @since 3.10\n */\n @Override\n public float floatValue() {\n return (float) doubleValue();\n }\n\n /**\n * Converts this {@code Decimal128} to a {@code double}. This conversion is similar to the narrowing primitive conversion from\n * {@code double} to {@code float} as defined in The Java™ Language Specification: if this {@code Decimal128} has\n * too great a magnitude to represent as a {@code double}, it will be converted to {@link Double#NEGATIVE_INFINITY} or\n * {@link Double#POSITIVE_INFINITY} as appropriate. Note that even when the return value is finite, this conversion can lose\n * information about the precision of the {@code Decimal128} value. Note that {@code #NEGATIVE_ZERO} is converted to {@code 0.0d}.\n *\n * @return this {@code Decimal128} converted to a {@code double}.\n * @since 3.10\n */\n @Override\n public double doubleValue() {\n if (isNaN()) {\n return Double.NaN;\n }\n if (isInfinite()) {\n if (isNegative()) {\n return Double.NEGATIVE_INFINITY;\n } else {\n return Double.POSITIVE_INFINITY;\n }\n }\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n if (hasDifferentSign(bigDecimal)) {\n return -0.0d;\n }\n return bigDecimal.doubleValue();\n }\n\n /**\n * Returns true if the encoded representation of this instance is the same as the encoded representation of {@code o}.\n *

\n * One consequence is that, whereas {@code Double.NaN != Double.NaN},\n * {@code new Decimal128(\"NaN\").equals(new Decimal128(\"NaN\")} returns true.\n *

\n *

\n * Another consequence is that, as with BigDecimal, {@code new Decimal128(\"1.0\").equals(new Decimal128(\"1.00\")} returns false,\n * because the precision is not the same and therefore the representation is not the same.\n *

\n *\n * @param o the object to compare for equality\n * @return true if the instances are equal\n */\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Decimal128 that = (Decimal128) o;\n if (high != that.high) {\n return false;\n }\n if (low != that.low) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = (int) (low ^ (low >>> 32));\n result = 31 * result + (int) (high ^ (high >>> 32));\n return result;\n }\n\n /**\n * Returns the String representation of the Decimal128 value.\n *\n * @return the String representation\n * @see \n * To-String Sprecification\n */\n @Override\n public String toString() {\n if (isNaN()) {\n return \"NaN\";\n }\n if (isInfinite()) {\n if (isNegative()) {\n return \"-Infinity\";\n } else {\n return \"Infinity\";\n }\n }\n return toStringWithBigDecimal();\n }\n\n private String toStringWithBigDecimal() {\n StringBuilder buffer = new StringBuilder();\n BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();\n String significand = bigDecimal.unscaledValue().abs().toString();\n if (isNegative()) {\n buffer.append('-');\n }\n int exponent = -bigDecimal.scale();\n int adjustedExponent = exponent + (significand.length() - 1);\n if (exponent <= 0 && adjustedExponent >= -6) {\n if (exponent == 0) {\n buffer.append(significand);\n } else {\n int pad = -exponent - significand.length();\n if (pad >= 0) {\n buffer.append('0');\n buffer.append('.');\n ", "post_mask_code": "\n buffer.append(significand, 0, significand.length());\n } else {\n buffer.append(significand, 0, -pad);\n buffer.append('.');\n buffer.append(significand, -pad, -pad - exponent);\n }\n }\n } else {\n buffer.append(significand.charAt(0));\n if (significand.length() > 1) {\n buffer.append('.');\n buffer.append(significand, 1, significand.length());\n }\n buffer.append('E');\n if (adjustedExponent > 0) {\n buffer.append('+');\n }\n buffer.append(adjustedExponent);\n }\n return buffer.toString();\n }\n}\n"} {"task_id": "Java_1345", "language": "Java", "task_type": "method_signature", "source_file": "java/github/VKCOM/vk-java-sdk/sdk/src/main/java/com/vk/api/sdk/queries/polls/PollsGetPhotoUploadServerQuery.java", "mask_start_position": 1185, "mask_end_position": 1246, "canonical_solution": "public PollsGetPhotoUploadServerQuery ownerId(Integer value) ", "pre_mask_code": "// Autogenerated from vk-api-schema. Please don't edit it manually.\npackage com.vk.api.sdk.queries.polls;\n\nimport com.vk.api.sdk.client.AbstractQueryBuilder;\nimport com.vk.api.sdk.client.VkApiClient;\nimport com.vk.api.sdk.client.actors.UserActor;\nimport com.vk.api.sdk.objects.base.responses.GetUploadServerResponse;\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * Query for Polls.getPhotoUploadServer method\n */\npublic class PollsGetPhotoUploadServerQuery extends AbstractQueryBuilder {\n\n /**\n * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters\n *\n * @param client VK API client\n * @param actor actor with access token\n */\n public PollsGetPhotoUploadServerQuery(VkApiClient client, UserActor actor) {\n super(client, \"polls.getPhotoUploadServer\", GetUploadServerResponse.class);\n accessToken(actor.getAccessToken());\n }\n\n /**\n * Set owner id\n *\n * @param value value of \"owner id\" parameter.\n * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the \"Builder\" pattern.\n */\n ", "post_mask_code": "{\n return unsafeParam(\"owner_id\", value);\n }\n\n @Override\n protected PollsGetPhotoUploadServerQuery getThis() {\n return this;\n }\n\n @Override\n protected List essentialKeys() {\n return Arrays.asList(\"access_token\");\n }\n}\n"} {"task_id": "Java_1346", "language": "Java", "task_type": "method_body", "source_file": "java/github/VKCOM/vk-java-sdk/sdk/src/main/java/com/vk/api/sdk/queries/polls/PollsGetPhotoUploadServerQuery.java", "mask_start_position": 1246, "mask_end_position": 1300, "canonical_solution": "{\n return unsafeParam(\"owner_id\", value);\n }", "pre_mask_code": "// Autogenerated from vk-api-schema. Please don't edit it manually.\npackage com.vk.api.sdk.queries.polls;\n\nimport com.vk.api.sdk.client.AbstractQueryBuilder;\nimport com.vk.api.sdk.client.VkApiClient;\nimport com.vk.api.sdk.client.actors.UserActor;\nimport com.vk.api.sdk.objects.base.responses.GetUploadServerResponse;\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * Query for Polls.getPhotoUploadServer method\n */\npublic class PollsGetPhotoUploadServerQuery extends AbstractQueryBuilder {\n\n /**\n * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters\n *\n * @param client VK API client\n * @param actor actor with access token\n */\n public PollsGetPhotoUploadServerQuery(VkApiClient client, UserActor actor) {\n super(client, \"polls.getPhotoUploadServer\", GetUploadServerResponse.class);\n accessToken(actor.getAccessToken());\n }\n\n /**\n * Set owner id\n *\n * @param value value of \"owner id\" parameter.\n * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the \"Builder\" pattern.\n */\n public PollsGetPhotoUploadServerQuery ownerId(Integer value) ", "post_mask_code": "\n\n @Override\n protected PollsGetPhotoUploadServerQuery getThis() {\n return this;\n }\n\n @Override\n protected List essentialKeys() {\n return Arrays.asList(\"access_token\");\n }\n}\n"} {"task_id": "Java_1347", "language": "Java", "task_type": "single_line", "source_file": "java/github/VKCOM/vk-java-sdk/sdk/src/main/java/com/vk/api/sdk/queries/polls/PollsGetPhotoUploadServerQuery.java", "mask_start_position": 1478, "mask_end_position": 1505, "canonical_solution": "ays.asList(\"access_token\");", "pre_mask_code": "// Autogenerated from vk-api-schema. Please don't edit it manually.\npackage com.vk.api.sdk.queries.polls;\n\nimport com.vk.api.sdk.client.AbstractQueryBuilder;\nimport com.vk.api.sdk.client.VkApiClient;\nimport com.vk.api.sdk.client.actors.UserActor;\nimport com.vk.api.sdk.objects.base.responses.GetUploadServerResponse;\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * Query for Polls.getPhotoUploadServer method\n */\npublic class PollsGetPhotoUploadServerQuery extends AbstractQueryBuilder {\n\n /**\n * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters\n *\n * @param client VK API client\n * @param actor actor with access token\n */\n public PollsGetPhotoUploadServerQuery(VkApiClient client, UserActor actor) {\n super(client, \"polls.getPhotoUploadServer\", GetUploadServerResponse.class);\n accessToken(actor.getAccessToken());\n }\n\n /**\n * Set owner id\n *\n * @param value value of \"owner id\" parameter.\n * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the \"Builder\" pattern.\n */\n public PollsGetPhotoUploadServerQuery ownerId(Integer value) {\n return unsafeParam(\"owner_id\", value);\n }\n\n @Override\n protected PollsGetPhotoUploadServerQuery getThis() {\n return this;\n }\n\n @Override\n protected List essentialKeys() {\n return Arr", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1348", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/VKCOM/vk-java-sdk/sdk/src/main/java/com/vk/api/sdk/queries/polls/PollsGetPhotoUploadServerQuery.java", "mask_start_position": 1185, "mask_end_position": 1300, "canonical_solution": "public PollsGetPhotoUploadServerQuery ownerId(Integer value) {\n return unsafeParam(\"owner_id\", value);\n }", "pre_mask_code": "// Autogenerated from vk-api-schema. Please don't edit it manually.\npackage com.vk.api.sdk.queries.polls;\n\nimport com.vk.api.sdk.client.AbstractQueryBuilder;\nimport com.vk.api.sdk.client.VkApiClient;\nimport com.vk.api.sdk.client.actors.UserActor;\nimport com.vk.api.sdk.objects.base.responses.GetUploadServerResponse;\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * Query for Polls.getPhotoUploadServer method\n */\npublic class PollsGetPhotoUploadServerQuery extends AbstractQueryBuilder {\n\n /**\n * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters\n *\n * @param client VK API client\n * @param actor actor with access token\n */\n public PollsGetPhotoUploadServerQuery(VkApiClient client, UserActor actor) {\n super(client, \"polls.getPhotoUploadServer\", GetUploadServerResponse.class);\n accessToken(actor.getAccessToken());\n }\n\n /**\n * Set owner id\n *\n * @param value value of \"owner id\" parameter.\n * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the \"Builder\" pattern.\n */\n ", "post_mask_code": "\n\n @Override\n protected PollsGetPhotoUploadServerQuery getThis() {\n return this;\n }\n\n @Override\n protected List essentialKeys() {\n return Arrays.asList(\"access_token\");\n }\n}\n"} {"task_id": "Java_1349", "language": "Java", "task_type": "method_signature", "source_file": "java/github/consulo/consulo/modules/base/lang-impl/src/main/java/consulo/roots/impl/property/GeneratedContentFolderPropertyProvider.java", "mask_start_position": 1053, "mask_end_position": 1109, "canonical_solution": "@Nonnull\n @Override\n public Boolean[] getValues() ", "pre_mask_code": "package consulo.roots.impl.property;\n\nimport com.intellij.icons.AllIcons;\nimport com.intellij.openapi.util.Comparing;\nimport consulo.util.dataholder.Key;\nimport consulo.roots.ContentFolderPropertyProvider;\nimport consulo.ui.image.Image;\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\n\n/**\n * @author VISTALL\n * @since 22:01/25.11.13\n */\npublic class GeneratedContentFolderPropertyProvider extends ContentFolderPropertyProvider {\n\n public static final Key IS_GENERATED = Key.create(\"is-generated-root\");\n\n @Nonnull\n @Override\n public Key getKey() {\n return IS_GENERATED;\n }\n\n @Nullable\n @Override\n public Image getLayerIcon(@Nonnull Boolean value) {\n return Comparing.equal(value, Boolean.TRUE) ? AllIcons.Modules.GeneratedMark : null;\n }\n\n @Override\n public Boolean fromString(@Nonnull String value) {\n return Boolean.valueOf(value);\n }\n\n @Override\n public String toString(@Nonnull Boolean value) {\n return value.toString();\n }\n\n ", "post_mask_code": "{\n return new Boolean[] { Boolean.TRUE, Boolean.FALSE };\n }\n}\n"} {"task_id": "Java_1350", "language": "Java", "task_type": "method_body", "source_file": "java/github/consulo/consulo/modules/base/lang-impl/src/main/java/consulo/roots/impl/property/GeneratedContentFolderPropertyProvider.java", "mask_start_position": 1007, "mask_end_position": 1047, "canonical_solution": "{\n return value.toString();\n }", "pre_mask_code": "package consulo.roots.impl.property;\n\nimport com.intellij.icons.AllIcons;\nimport com.intellij.openapi.util.Comparing;\nimport consulo.util.dataholder.Key;\nimport consulo.roots.ContentFolderPropertyProvider;\nimport consulo.ui.image.Image;\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\n\n/**\n * @author VISTALL\n * @since 22:01/25.11.13\n */\npublic class GeneratedContentFolderPropertyProvider extends ContentFolderPropertyProvider {\n\n public static final Key IS_GENERATED = Key.create(\"is-generated-root\");\n\n @Nonnull\n @Override\n public Key getKey() {\n return IS_GENERATED;\n }\n\n @Nullable\n @Override\n public Image getLayerIcon(@Nonnull Boolean value) {\n return Comparing.equal(value, Boolean.TRUE) ? AllIcons.Modules.GeneratedMark : null;\n }\n\n @Override\n public Boolean fromString(@Nonnull String value) {\n return Boolean.valueOf(value);\n }\n\n @Override\n public String toString(@Nonnull Boolean value) ", "post_mask_code": "\n\n @Nonnull\n @Override\n public Boolean[] getValues() {\n return new Boolean[] { Boolean.TRUE, Boolean.FALSE };\n }\n}\n"} {"task_id": "Java_1351", "language": "Java", "task_type": "single_line", "source_file": "java/github/consulo/consulo/modules/base/lang-impl/src/main/java/consulo/roots/impl/property/GeneratedContentFolderPropertyProvider.java", "mask_start_position": 1125, "mask_end_position": 1172, "canonical_solution": " new Boolean[] { Boolean.TRUE, Boolean.FALSE };", "pre_mask_code": "package consulo.roots.impl.property;\n\nimport com.intellij.icons.AllIcons;\nimport com.intellij.openapi.util.Comparing;\nimport consulo.util.dataholder.Key;\nimport consulo.roots.ContentFolderPropertyProvider;\nimport consulo.ui.image.Image;\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\n\n/**\n * @author VISTALL\n * @since 22:01/25.11.13\n */\npublic class GeneratedContentFolderPropertyProvider extends ContentFolderPropertyProvider {\n\n public static final Key IS_GENERATED = Key.create(\"is-generated-root\");\n\n @Nonnull\n @Override\n public Key getKey() {\n return IS_GENERATED;\n }\n\n @Nullable\n @Override\n public Image getLayerIcon(@Nonnull Boolean value) {\n return Comparing.equal(value, Boolean.TRUE) ? AllIcons.Modules.GeneratedMark : null;\n }\n\n @Override\n public Boolean fromString(@Nonnull String value) {\n return Boolean.valueOf(value);\n }\n\n @Override\n public String toString(@Nonnull Boolean value) {\n return value.toString();\n }\n\n @Nonnull\n @Override\n public Boolean[] getValues() {\n return", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1352", "language": "Java", "task_type": "method_signature", "source_file": "java/github/napcs/qedserver/jetty/examples/embedded/src/main/java/org/mortbay/jetty/example/ManyHandlers.java", "mask_start_position": 1188, "mask_end_position": 1331, "canonical_solution": "public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException ", "pre_mask_code": "package org.mortbay.jetty.example;\n\nimport java.io.IOException;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.mortbay.jetty.Connector;\nimport org.mortbay.jetty.Handler;\nimport org.mortbay.jetty.HttpConnection;\nimport org.mortbay.jetty.Request;\nimport org.mortbay.jetty.Server;\nimport org.mortbay.jetty.handler.AbstractHandler;\nimport org.mortbay.jetty.handler.HandlerCollection;\nimport org.mortbay.jetty.nio.SelectChannelConnector;\n\npublic class ManyHandlers {\n\n public static void main(String[] args) throws Exception {\n Server server = new Server();\n Connector connector = new SelectChannelConnector();\n connector.setPort(8080);\n server.setConnectors(new Connector[] { connector });\n Handler param = new ParamHandler();\n Handler hello = new HelloHandler();\n HandlerCollection handlers = new HandlerCollection();\n handlers.setHandlers(new Handler[] { param, hello });\n server.setHandler(handlers);\n server.start();\n server.join();\n }\n\n public static class ParamHandler extends AbstractHandler {\n\n ", "post_mask_code": "{\n System.err.println(request.getParameterMap());\n }\n }\n\n public static class HelloHandler extends AbstractHandler {\n\n public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {\n Request base_request = (request instanceof Request) ? (Request) request : HttpConnection.getCurrentConnection().getRequest();\n base_request.setHandled(true);\n response.setContentType(\"text/html\");\n response.setStatus(HttpServletResponse.SC_OK);\n response.getWriter().println(\"

Hello ManyHandler

\");\n }\n }\n}\n"} {"task_id": "Java_1353", "language": "Java", "task_type": "method_body", "source_file": "java/github/napcs/qedserver/jetty/examples/embedded/src/main/java/org/mortbay/jetty/example/ManyHandlers.java", "mask_start_position": 1624, "mask_end_position": 1997, "canonical_solution": "{\n Request base_request = (request instanceof Request) ? (Request) request : HttpConnection.getCurrentConnection().getRequest();\n base_request.setHandled(true);\n response.setContentType(\"text/html\");\n response.setStatus(HttpServletResponse.SC_OK);\n response.getWriter().println(\"

Hello ManyHandler

\");\n }", "pre_mask_code": "package org.mortbay.jetty.example;\n\nimport java.io.IOException;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.mortbay.jetty.Connector;\nimport org.mortbay.jetty.Handler;\nimport org.mortbay.jetty.HttpConnection;\nimport org.mortbay.jetty.Request;\nimport org.mortbay.jetty.Server;\nimport org.mortbay.jetty.handler.AbstractHandler;\nimport org.mortbay.jetty.handler.HandlerCollection;\nimport org.mortbay.jetty.nio.SelectChannelConnector;\n\npublic class ManyHandlers {\n\n public static void main(String[] args) throws Exception {\n Server server = new Server();\n Connector connector = new SelectChannelConnector();\n connector.setPort(8080);\n server.setConnectors(new Connector[] { connector });\n Handler param = new ParamHandler();\n Handler hello = new HelloHandler();\n HandlerCollection handlers = new HandlerCollection();\n handlers.setHandlers(new Handler[] { param, hello });\n server.setHandler(handlers);\n server.start();\n server.join();\n }\n\n public static class ParamHandler extends AbstractHandler {\n\n public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {\n System.err.println(request.getParameterMap());\n }\n }\n\n public static class HelloHandler extends AbstractHandler {\n\n public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1354", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/napcs/qedserver/jetty/examples/embedded/src/main/java/org/mortbay/jetty/example/ManyHandlers.java", "mask_start_position": 620, "mask_end_position": 812, "canonical_solution": "\n Server server = new Server();\n Connector connector = new SelectChannelConnector();\n connector.setPort(8080);\n server.setConnectors(new Connector[] { connector });", "pre_mask_code": "package org.mortbay.jetty.example;\n\nimport java.io.IOException;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.mortbay.jetty.Connector;\nimport org.mortbay.jetty.Handler;\nimport org.mortbay.jetty.HttpConnection;\nimport org.mortbay.jetty.Request;\nimport org.mortbay.jetty.Server;\nimport org.mortbay.jetty.handler.AbstractHandler;\nimport org.mortbay.jetty.handler.HandlerCollection;\nimport org.mortbay.jetty.nio.SelectChannelConnector;\n\npublic class ManyHandlers {\n\n public static void main(String[] args) throws Exception {", "post_mask_code": "\n Handler param = new ParamHandler();\n Handler hello = new HelloHandler();\n HandlerCollection handlers = new HandlerCollection();\n handlers.setHandlers(new Handler[] { param, hello });\n server.setHandler(handlers);\n server.start();\n server.join();\n }\n\n public static class ParamHandler extends AbstractHandler {\n\n public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {\n System.err.println(request.getParameterMap());\n }\n }\n\n public static class HelloHandler extends AbstractHandler {\n\n public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {\n Request base_request = (request instanceof Request) ? (Request) request : HttpConnection.getCurrentConnection().getRequest();\n base_request.setHandled(true);\n response.setContentType(\"text/html\");\n response.setStatus(HttpServletResponse.SC_OK);\n response.getWriter().println(\"

Hello ManyHandler

\");\n }\n }\n}\n"} {"task_id": "Java_1355", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/napcs/qedserver/jetty/examples/embedded/src/main/java/org/mortbay/jetty/example/ManyHandlers.java", "mask_start_position": 821, "mask_end_position": 1024, "canonical_solution": "Handler param = new ParamHandler();\n Handler hello = new HelloHandler();\n HandlerCollection handlers = new HandlerCollection();\n handlers.setHandlers(new Handler[] { param, hello });", "pre_mask_code": "package org.mortbay.jetty.example;\n\nimport java.io.IOException;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.mortbay.jetty.Connector;\nimport org.mortbay.jetty.Handler;\nimport org.mortbay.jetty.HttpConnection;\nimport org.mortbay.jetty.Request;\nimport org.mortbay.jetty.Server;\nimport org.mortbay.jetty.handler.AbstractHandler;\nimport org.mortbay.jetty.handler.HandlerCollection;\nimport org.mortbay.jetty.nio.SelectChannelConnector;\n\npublic class ManyHandlers {\n\n public static void main(String[] args) throws Exception {\n Server server = new Server();\n Connector connector = new SelectChannelConnector();\n connector.setPort(8080);\n server.setConnectors(new Connector[] { connector });\n ", "post_mask_code": "\n server.setHandler(handlers);\n server.start();\n server.join();\n }\n\n public static class ParamHandler extends AbstractHandler {\n\n public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {\n System.err.println(request.getParameterMap());\n }\n }\n\n public static class HelloHandler extends AbstractHandler {\n\n public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {\n Request base_request = (request instanceof Request) ? (Request) request : HttpConnection.getCurrentConnection().getRequest();\n base_request.setHandled(true);\n response.setContentType(\"text/html\");\n response.setStatus(HttpServletResponse.SC_OK);\n response.getWriter().println(\"

Hello ManyHandler

\");\n }\n }\n}\n"} {"task_id": "Java_1356", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/napcs/qedserver/jetty/examples/embedded/src/main/java/org/mortbay/jetty/example/ManyHandlers.java", "mask_start_position": 1033, "mask_end_position": 1114, "canonical_solution": "server.setHandler(handlers);\n server.start();\n server.join();\n }", "pre_mask_code": "package org.mortbay.jetty.example;\n\nimport java.io.IOException;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.mortbay.jetty.Connector;\nimport org.mortbay.jetty.Handler;\nimport org.mortbay.jetty.HttpConnection;\nimport org.mortbay.jetty.Request;\nimport org.mortbay.jetty.Server;\nimport org.mortbay.jetty.handler.AbstractHandler;\nimport org.mortbay.jetty.handler.HandlerCollection;\nimport org.mortbay.jetty.nio.SelectChannelConnector;\n\npublic class ManyHandlers {\n\n public static void main(String[] args) throws Exception {\n Server server = new Server();\n Connector connector = new SelectChannelConnector();\n connector.setPort(8080);\n server.setConnectors(new Connector[] { connector });\n Handler param = new ParamHandler();\n Handler hello = new HelloHandler();\n HandlerCollection handlers = new HandlerCollection();\n handlers.setHandlers(new Handler[] { param, hello });\n ", "post_mask_code": "\n\n public static class ParamHandler extends AbstractHandler {\n\n public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {\n System.err.println(request.getParameterMap());\n }\n }\n\n public static class HelloHandler extends AbstractHandler {\n\n public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {\n Request base_request = (request instanceof Request) ? (Request) request : HttpConnection.getCurrentConnection().getRequest();\n base_request.setHandled(true);\n response.setContentType(\"text/html\");\n response.setStatus(HttpServletResponse.SC_OK);\n response.getWriter().println(\"

Hello ManyHandler

\");\n }\n }\n}\n"} {"task_id": "Java_1357", "language": "Java", "task_type": "single_line", "source_file": "java/github/napcs/qedserver/jetty/examples/embedded/src/main/java/org/mortbay/jetty/example/ManyHandlers.java", "mask_start_position": 1364, "mask_end_position": 1391, "canonical_solution": "request.getParameterMap());", "pre_mask_code": "package org.mortbay.jetty.example;\n\nimport java.io.IOException;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.mortbay.jetty.Connector;\nimport org.mortbay.jetty.Handler;\nimport org.mortbay.jetty.HttpConnection;\nimport org.mortbay.jetty.Request;\nimport org.mortbay.jetty.Server;\nimport org.mortbay.jetty.handler.AbstractHandler;\nimport org.mortbay.jetty.handler.HandlerCollection;\nimport org.mortbay.jetty.nio.SelectChannelConnector;\n\npublic class ManyHandlers {\n\n public static void main(String[] args) throws Exception {\n Server server = new Server();\n Connector connector = new SelectChannelConnector();\n connector.setPort(8080);\n server.setConnectors(new Connector[] { connector });\n Handler param = new ParamHandler();\n Handler hello = new HelloHandler();\n HandlerCollection handlers = new HandlerCollection();\n handlers.setHandlers(new Handler[] { param, hello });\n server.setHandler(handlers);\n server.start();\n server.join();\n }\n\n public static class ParamHandler extends AbstractHandler {\n\n public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {\n System.err.println(", "post_mask_code": "\n }\n }\n\n public static class HelloHandler extends AbstractHandler {\n\n public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {\n Request base_request = (request instanceof Request) ? (Request) request : HttpConnection.getCurrentConnection().getRequest();\n base_request.setHandled(true);\n response.setContentType(\"text/html\");\n response.setStatus(HttpServletResponse.SC_OK);\n response.getWriter().println(\"

Hello ManyHandler

\");\n }\n }\n}\n"} {"task_id": "Java_1358", "language": "Java", "task_type": "method_signature", "source_file": "java/github/EleTeam/Shop-for-JavaWeb/src/main/java/com/iwc/shop/common/utils/IdGen.java", "mask_start_position": 958, "mask_end_position": 1004, "canonical_solution": "public static String randomBase62(int length) ", "pre_mask_code": "package com.iwc.shop.common.utils;\n\nimport java.io.Serializable;\nimport java.security.SecureRandom;\nimport java.util.UUID;\nimport org.activiti.engine.impl.cfg.IdGenerator;\nimport org.apache.shiro.session.Session;\nimport org.apache.shiro.session.mgt.eis.SessionIdGenerator;\nimport org.springframework.context.annotation.Lazy;\nimport org.springframework.stereotype.Service;\n\n/**\n * 封装各种生成唯一性ID算法的工具类.\n * @author Tony Wong\n * @version 2013-01-15\n */\n@Service\n@Lazy(false)\npublic class IdGen implements IdGenerator, SessionIdGenerator {\n\n private static SecureRandom random = new SecureRandom();\n\n /**\n * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.\n */\n public static String uuid() {\n return UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n }\n\n /**\n * 使用SecureRandom随机生成Long.\n */\n public static long randomLong() {\n return Math.abs(random.nextLong());\n }\n\n /**\n * 基于Base62编码的SecureRandom随机生成bytes.\n */\n ", "post_mask_code": "{\n byte[] randomBytes = new byte[length];\n random.nextBytes(randomBytes);\n return Encodes.encodeBase62(randomBytes);\n }\n\n /**\n * Activiti ID 生成\n */\n @Override\n public String getNextId() {\n return IdGen.uuid();\n }\n\n @Override\n public Serializable generateId(Session session) {\n return IdGen.uuid();\n }\n\n public static void main(String[] args) {\n System.out.println(IdGen.uuid());\n System.out.println(IdGen.uuid().length());\n System.out.println(new IdGen().getNextId());\n for (int i = 0; i < 1000; i++) {\n System.out.println(IdGen.randomLong() + \" \" + IdGen.randomBase62(5));\n }\n }\n}\n"} {"task_id": "Java_1359", "language": "Java", "task_type": "method_body", "source_file": "java/github/EleTeam/Shop-for-JavaWeb/src/main/java/com/iwc/shop/common/utils/IdGen.java", "mask_start_position": 1231, "mask_end_position": 1267, "canonical_solution": "{\n return IdGen.uuid();\n }", "pre_mask_code": "package com.iwc.shop.common.utils;\n\nimport java.io.Serializable;\nimport java.security.SecureRandom;\nimport java.util.UUID;\nimport org.activiti.engine.impl.cfg.IdGenerator;\nimport org.apache.shiro.session.Session;\nimport org.apache.shiro.session.mgt.eis.SessionIdGenerator;\nimport org.springframework.context.annotation.Lazy;\nimport org.springframework.stereotype.Service;\n\n/**\n * 封装各种生成唯一性ID算法的工具类.\n * @author Tony Wong\n * @version 2013-01-15\n */\n@Service\n@Lazy(false)\npublic class IdGen implements IdGenerator, SessionIdGenerator {\n\n private static SecureRandom random = new SecureRandom();\n\n /**\n * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.\n */\n public static String uuid() {\n return UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n }\n\n /**\n * 使用SecureRandom随机生成Long.\n */\n public static long randomLong() {\n return Math.abs(random.nextLong());\n }\n\n /**\n * 基于Base62编码的SecureRandom随机生成bytes.\n */\n public static String randomBase62(int length) {\n byte[] randomBytes = new byte[length];\n random.nextBytes(randomBytes);\n return Encodes.encodeBase62(randomBytes);\n }\n\n /**\n * Activiti ID 生成\n */\n @Override\n public String getNextId() ", "post_mask_code": "\n\n @Override\n public Serializable generateId(Session session) {\n return IdGen.uuid();\n }\n\n public static void main(String[] args) {\n System.out.println(IdGen.uuid());\n System.out.println(IdGen.uuid().length());\n System.out.println(new IdGen().getNextId());\n for (int i = 0; i < 1000; i++) {\n System.out.println(IdGen.randomLong() + \" \" + IdGen.randomBase62(5));\n }\n }\n}\n"} {"task_id": "Java_1360", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/EleTeam/Shop-for-JavaWeb/src/main/java/com/iwc/shop/common/utils/IdGen.java", "mask_start_position": 1417, "mask_end_position": 1459, "canonical_solution": "\n System.out.println(IdGen.uuid());", "pre_mask_code": "package com.iwc.shop.common.utils;\n\nimport java.io.Serializable;\nimport java.security.SecureRandom;\nimport java.util.UUID;\nimport org.activiti.engine.impl.cfg.IdGenerator;\nimport org.apache.shiro.session.Session;\nimport org.apache.shiro.session.mgt.eis.SessionIdGenerator;\nimport org.springframework.context.annotation.Lazy;\nimport org.springframework.stereotype.Service;\n\n/**\n * 封装各种生成唯一性ID算法的工具类.\n * @author Tony Wong\n * @version 2013-01-15\n */\n@Service\n@Lazy(false)\npublic class IdGen implements IdGenerator, SessionIdGenerator {\n\n private static SecureRandom random = new SecureRandom();\n\n /**\n * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.\n */\n public static String uuid() {\n return UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n }\n\n /**\n * 使用SecureRandom随机生成Long.\n */\n public static long randomLong() {\n return Math.abs(random.nextLong());\n }\n\n /**\n * 基于Base62编码的SecureRandom随机生成bytes.\n */\n public static String randomBase62(int length) {\n byte[] randomBytes = new byte[length];\n random.nextBytes(randomBytes);\n return Encodes.encodeBase62(randomBytes);\n }\n\n /**\n * Activiti ID 生成\n */\n @Override\n public String getNextId() {\n return IdGen.uuid();\n }\n\n @Override\n public Serializable generateId(Session session) {\n return IdGen.uuid();\n }\n\n public static void main(String[] args) {", "post_mask_code": "\n System.out.println(IdGen.uuid().length());\n System.out.println(new IdGen().getNextId());\n for (int i = 0; i < 1000; i++) {\n System.out.println(IdGen.randomLong() + \" \" + IdGen.randomBase62(5));\n }\n }\n}\n"} {"task_id": "Java_1361", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/EleTeam/Shop-for-JavaWeb/src/main/java/com/iwc/shop/common/utils/IdGen.java", "mask_start_position": 1468, "mask_end_position": 1563, "canonical_solution": "System.out.println(IdGen.uuid().length());\n System.out.println(new IdGen().getNextId());", "pre_mask_code": "package com.iwc.shop.common.utils;\n\nimport java.io.Serializable;\nimport java.security.SecureRandom;\nimport java.util.UUID;\nimport org.activiti.engine.impl.cfg.IdGenerator;\nimport org.apache.shiro.session.Session;\nimport org.apache.shiro.session.mgt.eis.SessionIdGenerator;\nimport org.springframework.context.annotation.Lazy;\nimport org.springframework.stereotype.Service;\n\n/**\n * 封装各种生成唯一性ID算法的工具类.\n * @author Tony Wong\n * @version 2013-01-15\n */\n@Service\n@Lazy(false)\npublic class IdGen implements IdGenerator, SessionIdGenerator {\n\n private static SecureRandom random = new SecureRandom();\n\n /**\n * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.\n */\n public static String uuid() {\n return UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n }\n\n /**\n * 使用SecureRandom随机生成Long.\n */\n public static long randomLong() {\n return Math.abs(random.nextLong());\n }\n\n /**\n * 基于Base62编码的SecureRandom随机生成bytes.\n */\n public static String randomBase62(int length) {\n byte[] randomBytes = new byte[length];\n random.nextBytes(randomBytes);\n return Encodes.encodeBase62(randomBytes);\n }\n\n /**\n * Activiti ID 生成\n */\n @Override\n public String getNextId() {\n return IdGen.uuid();\n }\n\n @Override\n public Serializable generateId(Session session) {\n return IdGen.uuid();\n }\n\n public static void main(String[] args) {\n System.out.println(IdGen.uuid());\n ", "post_mask_code": "\n for (int i = 0; i < 1000; i++) {\n System.out.println(IdGen.randomLong() + \" \" + IdGen.randomBase62(5));\n }\n }\n}\n"} {"task_id": "Java_1362", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/EleTeam/Shop-for-JavaWeb/src/main/java/com/iwc/shop/common/utils/IdGen.java", "mask_start_position": 1572, "mask_end_position": 1703, "canonical_solution": "for (int i = 0; i < 1000; i++) {\n System.out.println(IdGen.randomLong() + \" \" + IdGen.randomBase62(5));\n }\n }", "pre_mask_code": "package com.iwc.shop.common.utils;\n\nimport java.io.Serializable;\nimport java.security.SecureRandom;\nimport java.util.UUID;\nimport org.activiti.engine.impl.cfg.IdGenerator;\nimport org.apache.shiro.session.Session;\nimport org.apache.shiro.session.mgt.eis.SessionIdGenerator;\nimport org.springframework.context.annotation.Lazy;\nimport org.springframework.stereotype.Service;\n\n/**\n * 封装各种生成唯一性ID算法的工具类.\n * @author Tony Wong\n * @version 2013-01-15\n */\n@Service\n@Lazy(false)\npublic class IdGen implements IdGenerator, SessionIdGenerator {\n\n private static SecureRandom random = new SecureRandom();\n\n /**\n * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.\n */\n public static String uuid() {\n return UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n }\n\n /**\n * 使用SecureRandom随机生成Long.\n */\n public static long randomLong() {\n return Math.abs(random.nextLong());\n }\n\n /**\n * 基于Base62编码的SecureRandom随机生成bytes.\n */\n public static String randomBase62(int length) {\n byte[] randomBytes = new byte[length];\n random.nextBytes(randomBytes);\n return Encodes.encodeBase62(randomBytes);\n }\n\n /**\n * Activiti ID 生成\n */\n @Override\n public String getNextId() {\n return IdGen.uuid();\n }\n\n @Override\n public Serializable generateId(Session session) {\n return IdGen.uuid();\n }\n\n public static void main(String[] args) {\n System.out.println(IdGen.uuid());\n System.out.println(IdGen.uuid().length());\n System.out.println(new IdGen().getNextId());\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1363", "language": "Java", "task_type": "single_line", "source_file": "java/github/EleTeam/Shop-for-JavaWeb/src/main/java/com/iwc/shop/common/utils/IdGen.java", "mask_start_position": 881, "mask_end_position": 889, "canonical_solution": "Long());", "pre_mask_code": "package com.iwc.shop.common.utils;\n\nimport java.io.Serializable;\nimport java.security.SecureRandom;\nimport java.util.UUID;\nimport org.activiti.engine.impl.cfg.IdGenerator;\nimport org.apache.shiro.session.Session;\nimport org.apache.shiro.session.mgt.eis.SessionIdGenerator;\nimport org.springframework.context.annotation.Lazy;\nimport org.springframework.stereotype.Service;\n\n/**\n * 封装各种生成唯一性ID算法的工具类.\n * @author Tony Wong\n * @version 2013-01-15\n */\n@Service\n@Lazy(false)\npublic class IdGen implements IdGenerator, SessionIdGenerator {\n\n private static SecureRandom random = new SecureRandom();\n\n /**\n * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.\n */\n public static String uuid() {\n return UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n }\n\n /**\n * 使用SecureRandom随机生成Long.\n */\n public static long randomLong() {\n return Math.abs(random.next", "post_mask_code": "\n }\n\n /**\n * 基于Base62编码的SecureRandom随机生成bytes.\n */\n public static String randomBase62(int length) {\n byte[] randomBytes = new byte[length];\n random.nextBytes(randomBytes);\n return Encodes.encodeBase62(randomBytes);\n }\n\n /**\n * Activiti ID 生成\n */\n @Override\n public String getNextId() {\n return IdGen.uuid();\n }\n\n @Override\n public Serializable generateId(Session session) {\n return IdGen.uuid();\n }\n\n public static void main(String[] args) {\n System.out.println(IdGen.uuid());\n System.out.println(IdGen.uuid().length());\n System.out.println(new IdGen().getNextId());\n for (int i = 0; i < 1000; i++) {\n System.out.println(IdGen.randomLong() + \" \" + IdGen.randomBase62(5));\n }\n }\n}\n"} {"task_id": "Java_1364", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/EleTeam/Shop-for-JavaWeb/src/main/java/com/iwc/shop/common/utils/IdGen.java", "mask_start_position": 812, "mask_end_position": 895, "canonical_solution": "public static long randomLong() {\n return Math.abs(random.nextLong());\n }", "pre_mask_code": "package com.iwc.shop.common.utils;\n\nimport java.io.Serializable;\nimport java.security.SecureRandom;\nimport java.util.UUID;\nimport org.activiti.engine.impl.cfg.IdGenerator;\nimport org.apache.shiro.session.Session;\nimport org.apache.shiro.session.mgt.eis.SessionIdGenerator;\nimport org.springframework.context.annotation.Lazy;\nimport org.springframework.stereotype.Service;\n\n/**\n * 封装各种生成唯一性ID算法的工具类.\n * @author Tony Wong\n * @version 2013-01-15\n */\n@Service\n@Lazy(false)\npublic class IdGen implements IdGenerator, SessionIdGenerator {\n\n private static SecureRandom random = new SecureRandom();\n\n /**\n * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.\n */\n public static String uuid() {\n return UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n }\n\n /**\n * 使用SecureRandom随机生成Long.\n */\n ", "post_mask_code": "\n\n /**\n * 基于Base62编码的SecureRandom随机生成bytes.\n */\n public static String randomBase62(int length) {\n byte[] randomBytes = new byte[length];\n random.nextBytes(randomBytes);\n return Encodes.encodeBase62(randomBytes);\n }\n\n /**\n * Activiti ID 生成\n */\n @Override\n public String getNextId() {\n return IdGen.uuid();\n }\n\n @Override\n public Serializable generateId(Session session) {\n return IdGen.uuid();\n }\n\n public static void main(String[] args) {\n System.out.println(IdGen.uuid());\n System.out.println(IdGen.uuid().length());\n System.out.println(new IdGen().getNextId());\n for (int i = 0; i < 1000; i++) {\n System.out.println(IdGen.randomLong() + \" \" + IdGen.randomBase62(5));\n }\n }\n}\n"} {"task_id": "Java_1365", "language": "Java", "task_type": "for_statement", "source_file": "java/github/EleTeam/Shop-for-JavaWeb/src/main/java/com/iwc/shop/common/utils/IdGen.java", "mask_start_position": 1572, "mask_end_position": 1697, "canonical_solution": "for (int i = 0; i < 1000; i++) {\n System.out.println(IdGen.randomLong() + \" \" + IdGen.randomBase62(5));\n }", "pre_mask_code": "package com.iwc.shop.common.utils;\n\nimport java.io.Serializable;\nimport java.security.SecureRandom;\nimport java.util.UUID;\nimport org.activiti.engine.impl.cfg.IdGenerator;\nimport org.apache.shiro.session.Session;\nimport org.apache.shiro.session.mgt.eis.SessionIdGenerator;\nimport org.springframework.context.annotation.Lazy;\nimport org.springframework.stereotype.Service;\n\n/**\n * 封装各种生成唯一性ID算法的工具类.\n * @author Tony Wong\n * @version 2013-01-15\n */\n@Service\n@Lazy(false)\npublic class IdGen implements IdGenerator, SessionIdGenerator {\n\n private static SecureRandom random = new SecureRandom();\n\n /**\n * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.\n */\n public static String uuid() {\n return UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n }\n\n /**\n * 使用SecureRandom随机生成Long.\n */\n public static long randomLong() {\n return Math.abs(random.nextLong());\n }\n\n /**\n * 基于Base62编码的SecureRandom随机生成bytes.\n */\n public static String randomBase62(int length) {\n byte[] randomBytes = new byte[length];\n random.nextBytes(randomBytes);\n return Encodes.encodeBase62(randomBytes);\n }\n\n /**\n * Activiti ID 生成\n */\n @Override\n public String getNextId() {\n return IdGen.uuid();\n }\n\n @Override\n public Serializable generateId(Session session) {\n return IdGen.uuid();\n }\n\n public static void main(String[] args) {\n System.out.println(IdGen.uuid());\n System.out.println(IdGen.uuid().length());\n System.out.println(new IdGen().getNextId());\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1366", "language": "Java", "task_type": "method_signature", "source_file": "java/github/grzegorznittner/chanu/app/src/main/java/com/chanapps/four/data/SerializableCookie.java", "mask_start_position": 916, "mask_end_position": 984, "canonical_solution": "private void writeObject(ObjectOutputStream out) throws IOException ", "pre_mask_code": "package com.chanapps.four.data;\n\nimport java.io.Serializable;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.IOException;\nimport java.util.Date;\nimport org.apache.http.cookie.Cookie;\nimport org.apache.http.impl.cookie.BasicClientCookie;\n\n/**\n * A wrapper class around {@link Cookie} and/or {@link BasicClientCookie}\n * designed for use in {@link PersistentCookieStore}.\n */\npublic class SerializableCookie implements Serializable {\n\n private static final long serialVersionUID = 6374381828722046732L;\n\n private transient final Cookie cookie;\n\n private transient BasicClientCookie clientCookie;\n\n public SerializableCookie(Cookie cookie) {\n this.cookie = cookie;\n }\n\n public Cookie getCookie() {\n Cookie bestCookie = cookie;\n if (clientCookie != null) {\n bestCookie = clientCookie;\n }\n return bestCookie;\n }\n\n ", "post_mask_code": "{\n out.writeObject(cookie.getName());\n out.writeObject(cookie.getValue());\n out.writeObject(cookie.getComment());\n out.writeObject(cookie.getDomain());\n out.writeObject(cookie.getExpiryDate());\n out.writeObject(cookie.getPath());\n out.writeInt(cookie.getVersion());\n out.writeBoolean(cookie.isSecure());\n }\n\n private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {\n String name = (String) in.readObject();\n String value = (String) in.readObject();\n clientCookie = new BasicClientCookie(name, value);\n clientCookie.setComment((String) in.readObject());\n clientCookie.setDomain((String) in.readObject());\n clientCookie.setExpiryDate((Date) in.readObject());\n clientCookie.setPath((String) in.readObject());\n clientCookie.setVersion(in.readInt());\n clientCookie.setSecure(in.readBoolean());\n }\n}\n"} {"task_id": "Java_1367", "language": "Java", "task_type": "method_body", "source_file": "java/github/grzegorznittner/chanu/app/src/main/java/com/chanapps/four/data/SerializableCookie.java", "mask_start_position": 984, "mask_end_position": 1349, "canonical_solution": "{\n out.writeObject(cookie.getName());\n out.writeObject(cookie.getValue());\n out.writeObject(cookie.getComment());\n out.writeObject(cookie.getDomain());\n out.writeObject(cookie.getExpiryDate());\n out.writeObject(cookie.getPath());\n out.writeInt(cookie.getVersion());\n out.writeBoolean(cookie.isSecure());\n }", "pre_mask_code": "package com.chanapps.four.data;\n\nimport java.io.Serializable;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.IOException;\nimport java.util.Date;\nimport org.apache.http.cookie.Cookie;\nimport org.apache.http.impl.cookie.BasicClientCookie;\n\n/**\n * A wrapper class around {@link Cookie} and/or {@link BasicClientCookie}\n * designed for use in {@link PersistentCookieStore}.\n */\npublic class SerializableCookie implements Serializable {\n\n private static final long serialVersionUID = 6374381828722046732L;\n\n private transient final Cookie cookie;\n\n private transient BasicClientCookie clientCookie;\n\n public SerializableCookie(Cookie cookie) {\n this.cookie = cookie;\n }\n\n public Cookie getCookie() {\n Cookie bestCookie = cookie;\n if (clientCookie != null) {\n bestCookie = clientCookie;\n }\n return bestCookie;\n }\n\n private void writeObject(ObjectOutputStream out) throws IOException ", "post_mask_code": "\n\n private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {\n String name = (String) in.readObject();\n String value = (String) in.readObject();\n clientCookie = new BasicClientCookie(name, value);\n clientCookie.setComment((String) in.readObject());\n clientCookie.setDomain((String) in.readObject());\n clientCookie.setExpiryDate((Date) in.readObject());\n clientCookie.setPath((String) in.readObject());\n clientCookie.setVersion(in.readInt());\n clientCookie.setSecure(in.readBoolean());\n }\n}\n"} {"task_id": "Java_1368", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/grzegorznittner/chanu/app/src/main/java/com/chanapps/four/data/SerializableCookie.java", "mask_start_position": 1445, "mask_end_position": 1601, "canonical_solution": "\n String name = (String) in.readObject();\n String value = (String) in.readObject();\n clientCookie = new BasicClientCookie(name, value);", "pre_mask_code": "package com.chanapps.four.data;\n\nimport java.io.Serializable;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.IOException;\nimport java.util.Date;\nimport org.apache.http.cookie.Cookie;\nimport org.apache.http.impl.cookie.BasicClientCookie;\n\n/**\n * A wrapper class around {@link Cookie} and/or {@link BasicClientCookie}\n * designed for use in {@link PersistentCookieStore}.\n */\npublic class SerializableCookie implements Serializable {\n\n private static final long serialVersionUID = 6374381828722046732L;\n\n private transient final Cookie cookie;\n\n private transient BasicClientCookie clientCookie;\n\n public SerializableCookie(Cookie cookie) {\n this.cookie = cookie;\n }\n\n public Cookie getCookie() {\n Cookie bestCookie = cookie;\n if (clientCookie != null) {\n bestCookie = clientCookie;\n }\n return bestCookie;\n }\n\n private void writeObject(ObjectOutputStream out) throws IOException {\n out.writeObject(cookie.getName());\n out.writeObject(cookie.getValue());\n out.writeObject(cookie.getComment());\n out.writeObject(cookie.getDomain());\n out.writeObject(cookie.getExpiryDate());\n out.writeObject(cookie.getPath());\n out.writeInt(cookie.getVersion());\n out.writeBoolean(cookie.isSecure());\n }\n\n private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {", "post_mask_code": "\n clientCookie.setComment((String) in.readObject());\n clientCookie.setDomain((String) in.readObject());\n clientCookie.setExpiryDate((Date) in.readObject());\n clientCookie.setPath((String) in.readObject());\n clientCookie.setVersion(in.readInt());\n clientCookie.setSecure(in.readBoolean());\n }\n}\n"} {"task_id": "Java_1369", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/grzegorznittner/chanu/app/src/main/java/com/chanapps/four/data/SerializableCookie.java", "mask_start_position": 1610, "mask_end_position": 1778, "canonical_solution": "clientCookie.setComment((String) in.readObject());\n clientCookie.setDomain((String) in.readObject());\n clientCookie.setExpiryDate((Date) in.readObject());", "pre_mask_code": "package com.chanapps.four.data;\n\nimport java.io.Serializable;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.IOException;\nimport java.util.Date;\nimport org.apache.http.cookie.Cookie;\nimport org.apache.http.impl.cookie.BasicClientCookie;\n\n/**\n * A wrapper class around {@link Cookie} and/or {@link BasicClientCookie}\n * designed for use in {@link PersistentCookieStore}.\n */\npublic class SerializableCookie implements Serializable {\n\n private static final long serialVersionUID = 6374381828722046732L;\n\n private transient final Cookie cookie;\n\n private transient BasicClientCookie clientCookie;\n\n public SerializableCookie(Cookie cookie) {\n this.cookie = cookie;\n }\n\n public Cookie getCookie() {\n Cookie bestCookie = cookie;\n if (clientCookie != null) {\n bestCookie = clientCookie;\n }\n return bestCookie;\n }\n\n private void writeObject(ObjectOutputStream out) throws IOException {\n out.writeObject(cookie.getName());\n out.writeObject(cookie.getValue());\n out.writeObject(cookie.getComment());\n out.writeObject(cookie.getDomain());\n out.writeObject(cookie.getExpiryDate());\n out.writeObject(cookie.getPath());\n out.writeInt(cookie.getVersion());\n out.writeBoolean(cookie.isSecure());\n }\n\n private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {\n String name = (String) in.readObject();\n String value = (String) in.readObject();\n clientCookie = new BasicClientCookie(name, value);\n ", "post_mask_code": "\n clientCookie.setPath((String) in.readObject());\n clientCookie.setVersion(in.readInt());\n clientCookie.setSecure(in.readBoolean());\n }\n}\n"} {"task_id": "Java_1370", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/grzegorznittner/chanu/app/src/main/java/com/chanapps/four/data/SerializableCookie.java", "mask_start_position": 1787, "mask_end_position": 1937, "canonical_solution": "clientCookie.setPath((String) in.readObject());\n clientCookie.setVersion(in.readInt());\n clientCookie.setSecure(in.readBoolean());\n }", "pre_mask_code": "package com.chanapps.four.data;\n\nimport java.io.Serializable;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.IOException;\nimport java.util.Date;\nimport org.apache.http.cookie.Cookie;\nimport org.apache.http.impl.cookie.BasicClientCookie;\n\n/**\n * A wrapper class around {@link Cookie} and/or {@link BasicClientCookie}\n * designed for use in {@link PersistentCookieStore}.\n */\npublic class SerializableCookie implements Serializable {\n\n private static final long serialVersionUID = 6374381828722046732L;\n\n private transient final Cookie cookie;\n\n private transient BasicClientCookie clientCookie;\n\n public SerializableCookie(Cookie cookie) {\n this.cookie = cookie;\n }\n\n public Cookie getCookie() {\n Cookie bestCookie = cookie;\n if (clientCookie != null) {\n bestCookie = clientCookie;\n }\n return bestCookie;\n }\n\n private void writeObject(ObjectOutputStream out) throws IOException {\n out.writeObject(cookie.getName());\n out.writeObject(cookie.getValue());\n out.writeObject(cookie.getComment());\n out.writeObject(cookie.getDomain());\n out.writeObject(cookie.getExpiryDate());\n out.writeObject(cookie.getPath());\n out.writeInt(cookie.getVersion());\n out.writeBoolean(cookie.isSecure());\n }\n\n private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {\n String name = (String) in.readObject();\n String value = (String) in.readObject();\n clientCookie = new BasicClientCookie(name, value);\n clientCookie.setComment((String) in.readObject());\n clientCookie.setDomain((String) in.readObject());\n clientCookie.setExpiryDate((Date) in.readObject());\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1371", "language": "Java", "task_type": "single_line", "source_file": "java/github/grzegorznittner/chanu/app/src/main/java/com/chanapps/four/data/SerializableCookie.java", "mask_start_position": 1742, "mask_end_position": 1778, "canonical_solution": "tExpiryDate((Date) in.readObject());", "pre_mask_code": "package com.chanapps.four.data;\n\nimport java.io.Serializable;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.IOException;\nimport java.util.Date;\nimport org.apache.http.cookie.Cookie;\nimport org.apache.http.impl.cookie.BasicClientCookie;\n\n/**\n * A wrapper class around {@link Cookie} and/or {@link BasicClientCookie}\n * designed for use in {@link PersistentCookieStore}.\n */\npublic class SerializableCookie implements Serializable {\n\n private static final long serialVersionUID = 6374381828722046732L;\n\n private transient final Cookie cookie;\n\n private transient BasicClientCookie clientCookie;\n\n public SerializableCookie(Cookie cookie) {\n this.cookie = cookie;\n }\n\n public Cookie getCookie() {\n Cookie bestCookie = cookie;\n if (clientCookie != null) {\n bestCookie = clientCookie;\n }\n return bestCookie;\n }\n\n private void writeObject(ObjectOutputStream out) throws IOException {\n out.writeObject(cookie.getName());\n out.writeObject(cookie.getValue());\n out.writeObject(cookie.getComment());\n out.writeObject(cookie.getDomain());\n out.writeObject(cookie.getExpiryDate());\n out.writeObject(cookie.getPath());\n out.writeInt(cookie.getVersion());\n out.writeBoolean(cookie.isSecure());\n }\n\n private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {\n String name = (String) in.readObject();\n String value = (String) in.readObject();\n clientCookie = new BasicClientCookie(name, value);\n clientCookie.setComment((String) in.readObject());\n clientCookie.setDomain((String) in.readObject());\n clientCookie.se", "post_mask_code": "\n clientCookie.setPath((String) in.readObject());\n clientCookie.setVersion(in.readInt());\n clientCookie.setSecure(in.readBoolean());\n }\n}\n"} {"task_id": "Java_1372", "language": "Java", "task_type": "if_statement", "source_file": "java/github/grzegorznittner/chanu/app/src/main/java/com/chanapps/four/data/SerializableCookie.java", "mask_start_position": 801, "mask_end_position": 877, "canonical_solution": "if (clientCookie != null) {\n bestCookie = clientCookie;\n }", "pre_mask_code": "package com.chanapps.four.data;\n\nimport java.io.Serializable;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.IOException;\nimport java.util.Date;\nimport org.apache.http.cookie.Cookie;\nimport org.apache.http.impl.cookie.BasicClientCookie;\n\n/**\n * A wrapper class around {@link Cookie} and/or {@link BasicClientCookie}\n * designed for use in {@link PersistentCookieStore}.\n */\npublic class SerializableCookie implements Serializable {\n\n private static final long serialVersionUID = 6374381828722046732L;\n\n private transient final Cookie cookie;\n\n private transient BasicClientCookie clientCookie;\n\n public SerializableCookie(Cookie cookie) {\n this.cookie = cookie;\n }\n\n public Cookie getCookie() {\n Cookie bestCookie = cookie;\n ", "post_mask_code": "\n return bestCookie;\n }\n\n private void writeObject(ObjectOutputStream out) throws IOException {\n out.writeObject(cookie.getName());\n out.writeObject(cookie.getValue());\n out.writeObject(cookie.getComment());\n out.writeObject(cookie.getDomain());\n out.writeObject(cookie.getExpiryDate());\n out.writeObject(cookie.getPath());\n out.writeInt(cookie.getVersion());\n out.writeBoolean(cookie.isSecure());\n }\n\n private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {\n String name = (String) in.readObject();\n String value = (String) in.readObject();\n clientCookie = new BasicClientCookie(name, value);\n clientCookie.setComment((String) in.readObject());\n clientCookie.setDomain((String) in.readObject());\n clientCookie.setExpiryDate((Date) in.readObject());\n clientCookie.setPath((String) in.readObject());\n clientCookie.setVersion(in.readInt());\n clientCookie.setSecure(in.readBoolean());\n }\n}\n"} {"task_id": "Java_1373", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cnzx219/QingTingCheat/src/com/alibaba/fastjson/util/ParameterizedTypeImpl.java", "mask_start_position": 617, "mask_end_position": 644, "canonical_solution": "public Type getOwnerType() ", "pre_mask_code": "package com.alibaba.fastjson.util;\n\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\n\npublic class ParameterizedTypeImpl implements ParameterizedType {\n\n private final Type[] actualTypeArguments;\n\n private final Type ownerType;\n\n private final Type rawType;\n\n public ParameterizedTypeImpl(Type[] paramArrayOfType, Type paramType1, Type paramType2) {\n this.actualTypeArguments = paramArrayOfType;\n this.ownerType = paramType1;\n this.rawType = paramType2;\n }\n\n public Type[] getActualTypeArguments() {\n return this.actualTypeArguments;\n }\n\n ", "post_mask_code": "{\n return this.ownerType;\n }\n\n public Type getRawType() {\n return this.rawType;\n }\n}\n"} {"task_id": "Java_1374", "language": "Java", "task_type": "method_body", "source_file": "java/github/cnzx219/QingTingCheat/src/com/alibaba/fastjson/util/ParameterizedTypeImpl.java", "mask_start_position": 563, "mask_end_position": 611, "canonical_solution": "{\n return this.actualTypeArguments;\n }", "pre_mask_code": "package com.alibaba.fastjson.util;\n\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\n\npublic class ParameterizedTypeImpl implements ParameterizedType {\n\n private final Type[] actualTypeArguments;\n\n private final Type ownerType;\n\n private final Type rawType;\n\n public ParameterizedTypeImpl(Type[] paramArrayOfType, Type paramType1, Type paramType2) {\n this.actualTypeArguments = paramArrayOfType;\n this.ownerType = paramType1;\n this.rawType = paramType2;\n }\n\n public Type[] getActualTypeArguments() ", "post_mask_code": "\n\n public Type getOwnerType() {\n return this.ownerType;\n }\n\n public Type getRawType() {\n return this.rawType;\n }\n}\n"} {"task_id": "Java_1375", "language": "Java", "task_type": "single_line", "source_file": "java/github/cnzx219/QingTingCheat/src/com/alibaba/fastjson/util/ParameterizedTypeImpl.java", "mask_start_position": 727, "mask_end_position": 743, "canonical_solution": "rn this.rawType;", "pre_mask_code": "package com.alibaba.fastjson.util;\n\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\n\npublic class ParameterizedTypeImpl implements ParameterizedType {\n\n private final Type[] actualTypeArguments;\n\n private final Type ownerType;\n\n private final Type rawType;\n\n public ParameterizedTypeImpl(Type[] paramArrayOfType, Type paramType1, Type paramType2) {\n this.actualTypeArguments = paramArrayOfType;\n this.ownerType = paramType1;\n this.rawType = paramType2;\n }\n\n public Type[] getActualTypeArguments() {\n return this.actualTypeArguments;\n }\n\n public Type getOwnerType() {\n return this.ownerType;\n }\n\n public Type getRawType() {\n retu", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1376", "language": "Java", "task_type": "method_signature", "source_file": "java/github/kieker-monitoring/kieker/kieker-common/src-gen/kieker/common/record/misc/HostApplicationMetaData.java", "mask_start_position": 2977, "mask_end_position": 3079, "canonical_solution": "@Override\n public void serialize(final IValueSerializer serializer) throws BufferOverflowException ", "pre_mask_code": "package kieker.common.record.misc;\n\nimport java.nio.BufferOverflowException;\nimport kieker.common.exception.RecordInstantiationException;\nimport kieker.common.record.AbstractMonitoringRecord;\nimport kieker.common.record.io.IValueDeserializer;\nimport kieker.common.record.io.IValueSerializer;\n\n/**\n * @author Christian Wulf\n * API compatibility: Kieker 1.15.0\n *\n * @since 1.13\n */\npublic class HostApplicationMetaData extends AbstractMonitoringRecord {\n\n /**\n * Descriptive definition of the serialization size of the record.\n */\n public static final int SIZE = // HostApplicationMetaData.systemName\n TYPE_SIZE_STRING + // HostApplicationMetaData.ipAddress\n TYPE_SIZE_STRING + // HostApplicationMetaData.hostname\n TYPE_SIZE_STRING + // HostApplicationMetaData.applicationName\n TYPE_SIZE_STRING;\n\n public static final Class[] TYPES = { // HostApplicationMetaData.systemName\n String.class, // HostApplicationMetaData.ipAddress\n String.class, // HostApplicationMetaData.hostname\n String.class, // HostApplicationMetaData.applicationName\n String.class };\n\n /**\n * property name array.\n */\n public static final String[] VALUE_NAMES = { \"systemName\", \"ipAddress\", \"hostname\", \"applicationName\" };\n\n public static final String SYSTEM_NAME = \"\";\n\n public static final String IP_ADDRESS = \"\";\n\n public static final String HOSTNAME = \"\";\n\n public static final String APPLICATION_NAME = \"\";\n\n private static final long serialVersionUID = 5425789809172379297L;\n\n /**\n * property declarations.\n */\n private final String systemName;\n\n private final String ipAddress;\n\n private final String hostname;\n\n private final String applicationName;\n\n /**\n * Creates a new instance of this class using the given parameters.\n *\n * @param systemName\n * systemName\n * @param ipAddress\n * ipAddress\n * @param hostname\n * hostname\n * @param applicationName\n * applicationName\n */\n public HostApplicationMetaData(final String systemName, final String ipAddress, final String hostname, final String applicationName) {\n this.systemName = systemName == null ? \"\" : systemName;\n this.ipAddress = ipAddress == null ? \"\" : ipAddress;\n this.hostname = hostname == null ? \"\" : hostname;\n this.applicationName = applicationName == null ? \"\" : applicationName;\n }\n\n /**\n * @param deserializer\n * The deserializer to use\n * @throws RecordInstantiationException\n * when the record could not be deserialized\n */\n public HostApplicationMetaData(final IValueDeserializer deserializer) throws RecordInstantiationException {\n this.systemName = deserializer.getString();\n this.ipAddress = deserializer.getString();\n this.hostname = deserializer.getString();\n this.applicationName = deserializer.getString();\n }\n\n ", "post_mask_code": "{\n serializer.putString(this.getSystemName());\n serializer.putString(this.getIpAddress());\n serializer.putString(this.getHostname());\n serializer.putString(this.getApplicationName());\n }\n\n @Override\n public Class[] getValueTypes() {\n // NOPMD\n return TYPES;\n }\n\n @Override\n public String[] getValueNames() {\n // NOPMD\n return VALUE_NAMES;\n }\n\n @Override\n public int getSize() {\n return SIZE;\n }\n\n @Override\n public boolean equals(final Object obj) {\n if (obj == null) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n if (obj.getClass() != this.getClass()) {\n return false;\n }\n final HostApplicationMetaData castedRecord = (HostApplicationMetaData) obj;\n if (this.getLoggingTimestamp() != castedRecord.getLoggingTimestamp()) {\n return false;\n }\n if (!this.getSystemName().equals(castedRecord.getSystemName())) {\n return false;\n }\n if (!this.getIpAddress().equals(castedRecord.getIpAddress())) {\n return false;\n }\n if (!this.getHostname().equals(castedRecord.getHostname())) {\n return false;\n }\n if (!this.getApplicationName().equals(castedRecord.getApplicationName())) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int code = 0;\n code += this.getSystemName().hashCode();\n code += this.getIpAddress().hashCode();\n code += this.getHostname().hashCode();\n code += this.getApplicationName().hashCode();\n return code;\n }\n\n public final String getSystemName() {\n return this.systemName;\n }\n\n public final String getIpAddress() {\n return this.ipAddress;\n }\n\n public final String getHostname() {\n return this.hostname;\n }\n\n public final String getApplicationName() {\n return this.applicationName;\n }\n\n @Override\n public String toString() {\n String result = \"HostApplicationMetaData: \";\n result += \"systemName = \";\n result += this.getSystemName() + \", \";\n result += \"ipAddress = \";\n result += this.getIpAddress() + \", \";\n result += \"hostname = \";\n result += this.getHostname() + \", \";\n result += \"applicationName = \";\n result += this.getApplicationName() + \", \";\n return result;\n }\n}\n"} {"task_id": "Java_1377", "language": "Java", "task_type": "method_body", "source_file": "java/github/kieker-monitoring/kieker/kieker-common/src-gen/kieker/common/record/misc/HostApplicationMetaData.java", "mask_start_position": 3541, "mask_end_position": 3569, "canonical_solution": "{\n return SIZE;\n }", "pre_mask_code": "package kieker.common.record.misc;\n\nimport java.nio.BufferOverflowException;\nimport kieker.common.exception.RecordInstantiationException;\nimport kieker.common.record.AbstractMonitoringRecord;\nimport kieker.common.record.io.IValueDeserializer;\nimport kieker.common.record.io.IValueSerializer;\n\n/**\n * @author Christian Wulf\n * API compatibility: Kieker 1.15.0\n *\n * @since 1.13\n */\npublic class HostApplicationMetaData extends AbstractMonitoringRecord {\n\n /**\n * Descriptive definition of the serialization size of the record.\n */\n public static final int SIZE = // HostApplicationMetaData.systemName\n TYPE_SIZE_STRING + // HostApplicationMetaData.ipAddress\n TYPE_SIZE_STRING + // HostApplicationMetaData.hostname\n TYPE_SIZE_STRING + // HostApplicationMetaData.applicationName\n TYPE_SIZE_STRING;\n\n public static final Class[] TYPES = { // HostApplicationMetaData.systemName\n String.class, // HostApplicationMetaData.ipAddress\n String.class, // HostApplicationMetaData.hostname\n String.class, // HostApplicationMetaData.applicationName\n String.class };\n\n /**\n * property name array.\n */\n public static final String[] VALUE_NAMES = { \"systemName\", \"ipAddress\", \"hostname\", \"applicationName\" };\n\n public static final String SYSTEM_NAME = \"\";\n\n public static final String IP_ADDRESS = \"\";\n\n public static final String HOSTNAME = \"\";\n\n public static final String APPLICATION_NAME = \"\";\n\n private static final long serialVersionUID = 5425789809172379297L;\n\n /**\n * property declarations.\n */\n private final String systemName;\n\n private final String ipAddress;\n\n private final String hostname;\n\n private final String applicationName;\n\n /**\n * Creates a new instance of this class using the given parameters.\n *\n * @param systemName\n * systemName\n * @param ipAddress\n * ipAddress\n * @param hostname\n * hostname\n * @param applicationName\n * applicationName\n */\n public HostApplicationMetaData(final String systemName, final String ipAddress, final String hostname, final String applicationName) {\n this.systemName = systemName == null ? \"\" : systemName;\n this.ipAddress = ipAddress == null ? \"\" : ipAddress;\n this.hostname = hostname == null ? \"\" : hostname;\n this.applicationName = applicationName == null ? \"\" : applicationName;\n }\n\n /**\n * @param deserializer\n * The deserializer to use\n * @throws RecordInstantiationException\n * when the record could not be deserialized\n */\n public HostApplicationMetaData(final IValueDeserializer deserializer) throws RecordInstantiationException {\n this.systemName = deserializer.getString();\n this.ipAddress = deserializer.getString();\n this.hostname = deserializer.getString();\n this.applicationName = deserializer.getString();\n }\n\n @Override\n public void serialize(final IValueSerializer serializer) throws BufferOverflowException {\n serializer.putString(this.getSystemName());\n serializer.putString(this.getIpAddress());\n serializer.putString(this.getHostname());\n serializer.putString(this.getApplicationName());\n }\n\n @Override\n public Class[] getValueTypes() {\n // NOPMD\n return TYPES;\n }\n\n @Override\n public String[] getValueNames() {\n // NOPMD\n return VALUE_NAMES;\n }\n\n @Override\n public int getSize() ", "post_mask_code": "\n\n @Override\n public boolean equals(final Object obj) {\n if (obj == null) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n if (obj.getClass() != this.getClass()) {\n return false;\n }\n final HostApplicationMetaData castedRecord = (HostApplicationMetaData) obj;\n if (this.getLoggingTimestamp() != castedRecord.getLoggingTimestamp()) {\n return false;\n }\n if (!this.getSystemName().equals(castedRecord.getSystemName())) {\n return false;\n }\n if (!this.getIpAddress().equals(castedRecord.getIpAddress())) {\n return false;\n }\n if (!this.getHostname().equals(castedRecord.getHostname())) {\n return false;\n }\n if (!this.getApplicationName().equals(castedRecord.getApplicationName())) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int code = 0;\n code += this.getSystemName().hashCode();\n code += this.getIpAddress().hashCode();\n code += this.getHostname().hashCode();\n code += this.getApplicationName().hashCode();\n return code;\n }\n\n public final String getSystemName() {\n return this.systemName;\n }\n\n public final String getIpAddress() {\n return this.ipAddress;\n }\n\n public final String getHostname() {\n return this.hostname;\n }\n\n public final String getApplicationName() {\n return this.applicationName;\n }\n\n @Override\n public String toString() {\n String result = \"HostApplicationMetaData: \";\n result += \"systemName = \";\n result += this.getSystemName() + \", \";\n result += \"ipAddress = \";\n result += this.getIpAddress() + \", \";\n result += \"hostname = \";\n result += this.getHostname() + \", \";\n result += \"applicationName = \";\n result += this.getApplicationName() + \", \";\n return result;\n }\n}\n"} {"task_id": "Java_1378", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/kieker-monitoring/kieker/kieker-common/src-gen/kieker/common/record/misc/HostApplicationMetaData.java", "mask_start_position": 4554, "mask_end_position": 4625, "canonical_solution": "\n int code = 0;\n code += this.getSystemName().hashCode();", "pre_mask_code": "package kieker.common.record.misc;\n\nimport java.nio.BufferOverflowException;\nimport kieker.common.exception.RecordInstantiationException;\nimport kieker.common.record.AbstractMonitoringRecord;\nimport kieker.common.record.io.IValueDeserializer;\nimport kieker.common.record.io.IValueSerializer;\n\n/**\n * @author Christian Wulf\n * API compatibility: Kieker 1.15.0\n *\n * @since 1.13\n */\npublic class HostApplicationMetaData extends AbstractMonitoringRecord {\n\n /**\n * Descriptive definition of the serialization size of the record.\n */\n public static final int SIZE = // HostApplicationMetaData.systemName\n TYPE_SIZE_STRING + // HostApplicationMetaData.ipAddress\n TYPE_SIZE_STRING + // HostApplicationMetaData.hostname\n TYPE_SIZE_STRING + // HostApplicationMetaData.applicationName\n TYPE_SIZE_STRING;\n\n public static final Class[] TYPES = { // HostApplicationMetaData.systemName\n String.class, // HostApplicationMetaData.ipAddress\n String.class, // HostApplicationMetaData.hostname\n String.class, // HostApplicationMetaData.applicationName\n String.class };\n\n /**\n * property name array.\n */\n public static final String[] VALUE_NAMES = { \"systemName\", \"ipAddress\", \"hostname\", \"applicationName\" };\n\n public static final String SYSTEM_NAME = \"\";\n\n public static final String IP_ADDRESS = \"\";\n\n public static final String HOSTNAME = \"\";\n\n public static final String APPLICATION_NAME = \"\";\n\n private static final long serialVersionUID = 5425789809172379297L;\n\n /**\n * property declarations.\n */\n private final String systemName;\n\n private final String ipAddress;\n\n private final String hostname;\n\n private final String applicationName;\n\n /**\n * Creates a new instance of this class using the given parameters.\n *\n * @param systemName\n * systemName\n * @param ipAddress\n * ipAddress\n * @param hostname\n * hostname\n * @param applicationName\n * applicationName\n */\n public HostApplicationMetaData(final String systemName, final String ipAddress, final String hostname, final String applicationName) {\n this.systemName = systemName == null ? \"\" : systemName;\n this.ipAddress = ipAddress == null ? \"\" : ipAddress;\n this.hostname = hostname == null ? \"\" : hostname;\n this.applicationName = applicationName == null ? \"\" : applicationName;\n }\n\n /**\n * @param deserializer\n * The deserializer to use\n * @throws RecordInstantiationException\n * when the record could not be deserialized\n */\n public HostApplicationMetaData(final IValueDeserializer deserializer) throws RecordInstantiationException {\n this.systemName = deserializer.getString();\n this.ipAddress = deserializer.getString();\n this.hostname = deserializer.getString();\n this.applicationName = deserializer.getString();\n }\n\n @Override\n public void serialize(final IValueSerializer serializer) throws BufferOverflowException {\n serializer.putString(this.getSystemName());\n serializer.putString(this.getIpAddress());\n serializer.putString(this.getHostname());\n serializer.putString(this.getApplicationName());\n }\n\n @Override\n public Class[] getValueTypes() {\n // NOPMD\n return TYPES;\n }\n\n @Override\n public String[] getValueNames() {\n // NOPMD\n return VALUE_NAMES;\n }\n\n @Override\n public int getSize() {\n return SIZE;\n }\n\n @Override\n public boolean equals(final Object obj) {\n if (obj == null) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n if (obj.getClass() != this.getClass()) {\n return false;\n }\n final HostApplicationMetaData castedRecord = (HostApplicationMetaData) obj;\n if (this.getLoggingTimestamp() != castedRecord.getLoggingTimestamp()) {\n return false;\n }\n if (!this.getSystemName().equals(castedRecord.getSystemName())) {\n return false;\n }\n if (!this.getIpAddress().equals(castedRecord.getIpAddress())) {\n return false;\n }\n if (!this.getHostname().equals(castedRecord.getHostname())) {\n return false;\n }\n if (!this.getApplicationName().equals(castedRecord.getApplicationName())) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {", "post_mask_code": "\n code += this.getIpAddress().hashCode();\n code += this.getHostname().hashCode();\n code += this.getApplicationName().hashCode();\n return code;\n }\n\n public final String getSystemName() {\n return this.systemName;\n }\n\n public final String getIpAddress() {\n return this.ipAddress;\n }\n\n public final String getHostname() {\n return this.hostname;\n }\n\n public final String getApplicationName() {\n return this.applicationName;\n }\n\n @Override\n public String toString() {\n String result = \"HostApplicationMetaData: \";\n result += \"systemName = \";\n result += this.getSystemName() + \", \";\n result += \"ipAddress = \";\n result += this.getIpAddress() + \", \";\n result += \"hostname = \";\n result += this.getHostname() + \", \";\n result += \"applicationName = \";\n result += this.getApplicationName() + \", \";\n return result;\n }\n}\n"} {"task_id": "Java_1379", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/kieker-monitoring/kieker/kieker-common/src-gen/kieker/common/record/misc/HostApplicationMetaData.java", "mask_start_position": 4634, "mask_end_position": 4720, "canonical_solution": "code += this.getIpAddress().hashCode();\n code += this.getHostname().hashCode();", "pre_mask_code": "package kieker.common.record.misc;\n\nimport java.nio.BufferOverflowException;\nimport kieker.common.exception.RecordInstantiationException;\nimport kieker.common.record.AbstractMonitoringRecord;\nimport kieker.common.record.io.IValueDeserializer;\nimport kieker.common.record.io.IValueSerializer;\n\n/**\n * @author Christian Wulf\n * API compatibility: Kieker 1.15.0\n *\n * @since 1.13\n */\npublic class HostApplicationMetaData extends AbstractMonitoringRecord {\n\n /**\n * Descriptive definition of the serialization size of the record.\n */\n public static final int SIZE = // HostApplicationMetaData.systemName\n TYPE_SIZE_STRING + // HostApplicationMetaData.ipAddress\n TYPE_SIZE_STRING + // HostApplicationMetaData.hostname\n TYPE_SIZE_STRING + // HostApplicationMetaData.applicationName\n TYPE_SIZE_STRING;\n\n public static final Class[] TYPES = { // HostApplicationMetaData.systemName\n String.class, // HostApplicationMetaData.ipAddress\n String.class, // HostApplicationMetaData.hostname\n String.class, // HostApplicationMetaData.applicationName\n String.class };\n\n /**\n * property name array.\n */\n public static final String[] VALUE_NAMES = { \"systemName\", \"ipAddress\", \"hostname\", \"applicationName\" };\n\n public static final String SYSTEM_NAME = \"\";\n\n public static final String IP_ADDRESS = \"\";\n\n public static final String HOSTNAME = \"\";\n\n public static final String APPLICATION_NAME = \"\";\n\n private static final long serialVersionUID = 5425789809172379297L;\n\n /**\n * property declarations.\n */\n private final String systemName;\n\n private final String ipAddress;\n\n private final String hostname;\n\n private final String applicationName;\n\n /**\n * Creates a new instance of this class using the given parameters.\n *\n * @param systemName\n * systemName\n * @param ipAddress\n * ipAddress\n * @param hostname\n * hostname\n * @param applicationName\n * applicationName\n */\n public HostApplicationMetaData(final String systemName, final String ipAddress, final String hostname, final String applicationName) {\n this.systemName = systemName == null ? \"\" : systemName;\n this.ipAddress = ipAddress == null ? \"\" : ipAddress;\n this.hostname = hostname == null ? \"\" : hostname;\n this.applicationName = applicationName == null ? \"\" : applicationName;\n }\n\n /**\n * @param deserializer\n * The deserializer to use\n * @throws RecordInstantiationException\n * when the record could not be deserialized\n */\n public HostApplicationMetaData(final IValueDeserializer deserializer) throws RecordInstantiationException {\n this.systemName = deserializer.getString();\n this.ipAddress = deserializer.getString();\n this.hostname = deserializer.getString();\n this.applicationName = deserializer.getString();\n }\n\n @Override\n public void serialize(final IValueSerializer serializer) throws BufferOverflowException {\n serializer.putString(this.getSystemName());\n serializer.putString(this.getIpAddress());\n serializer.putString(this.getHostname());\n serializer.putString(this.getApplicationName());\n }\n\n @Override\n public Class[] getValueTypes() {\n // NOPMD\n return TYPES;\n }\n\n @Override\n public String[] getValueNames() {\n // NOPMD\n return VALUE_NAMES;\n }\n\n @Override\n public int getSize() {\n return SIZE;\n }\n\n @Override\n public boolean equals(final Object obj) {\n if (obj == null) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n if (obj.getClass() != this.getClass()) {\n return false;\n }\n final HostApplicationMetaData castedRecord = (HostApplicationMetaData) obj;\n if (this.getLoggingTimestamp() != castedRecord.getLoggingTimestamp()) {\n return false;\n }\n if (!this.getSystemName().equals(castedRecord.getSystemName())) {\n return false;\n }\n if (!this.getIpAddress().equals(castedRecord.getIpAddress())) {\n return false;\n }\n if (!this.getHostname().equals(castedRecord.getHostname())) {\n return false;\n }\n if (!this.getApplicationName().equals(castedRecord.getApplicationName())) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int code = 0;\n code += this.getSystemName().hashCode();\n ", "post_mask_code": "\n code += this.getApplicationName().hashCode();\n return code;\n }\n\n public final String getSystemName() {\n return this.systemName;\n }\n\n public final String getIpAddress() {\n return this.ipAddress;\n }\n\n public final String getHostname() {\n return this.hostname;\n }\n\n public final String getApplicationName() {\n return this.applicationName;\n }\n\n @Override\n public String toString() {\n String result = \"HostApplicationMetaData: \";\n result += \"systemName = \";\n result += this.getSystemName() + \", \";\n result += \"ipAddress = \";\n result += this.getIpAddress() + \", \";\n result += \"hostname = \";\n result += this.getHostname() + \", \";\n result += \"applicationName = \";\n result += this.getApplicationName() + \", \";\n return result;\n }\n}\n"} {"task_id": "Java_1380", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/kieker-monitoring/kieker/kieker-common/src-gen/kieker/common/record/misc/HostApplicationMetaData.java", "mask_start_position": 4729, "mask_end_position": 4801, "canonical_solution": "code += this.getApplicationName().hashCode();\n return code;\n }", "pre_mask_code": "package kieker.common.record.misc;\n\nimport java.nio.BufferOverflowException;\nimport kieker.common.exception.RecordInstantiationException;\nimport kieker.common.record.AbstractMonitoringRecord;\nimport kieker.common.record.io.IValueDeserializer;\nimport kieker.common.record.io.IValueSerializer;\n\n/**\n * @author Christian Wulf\n * API compatibility: Kieker 1.15.0\n *\n * @since 1.13\n */\npublic class HostApplicationMetaData extends AbstractMonitoringRecord {\n\n /**\n * Descriptive definition of the serialization size of the record.\n */\n public static final int SIZE = // HostApplicationMetaData.systemName\n TYPE_SIZE_STRING + // HostApplicationMetaData.ipAddress\n TYPE_SIZE_STRING + // HostApplicationMetaData.hostname\n TYPE_SIZE_STRING + // HostApplicationMetaData.applicationName\n TYPE_SIZE_STRING;\n\n public static final Class[] TYPES = { // HostApplicationMetaData.systemName\n String.class, // HostApplicationMetaData.ipAddress\n String.class, // HostApplicationMetaData.hostname\n String.class, // HostApplicationMetaData.applicationName\n String.class };\n\n /**\n * property name array.\n */\n public static final String[] VALUE_NAMES = { \"systemName\", \"ipAddress\", \"hostname\", \"applicationName\" };\n\n public static final String SYSTEM_NAME = \"\";\n\n public static final String IP_ADDRESS = \"\";\n\n public static final String HOSTNAME = \"\";\n\n public static final String APPLICATION_NAME = \"\";\n\n private static final long serialVersionUID = 5425789809172379297L;\n\n /**\n * property declarations.\n */\n private final String systemName;\n\n private final String ipAddress;\n\n private final String hostname;\n\n private final String applicationName;\n\n /**\n * Creates a new instance of this class using the given parameters.\n *\n * @param systemName\n * systemName\n * @param ipAddress\n * ipAddress\n * @param hostname\n * hostname\n * @param applicationName\n * applicationName\n */\n public HostApplicationMetaData(final String systemName, final String ipAddress, final String hostname, final String applicationName) {\n this.systemName = systemName == null ? \"\" : systemName;\n this.ipAddress = ipAddress == null ? \"\" : ipAddress;\n this.hostname = hostname == null ? \"\" : hostname;\n this.applicationName = applicationName == null ? \"\" : applicationName;\n }\n\n /**\n * @param deserializer\n * The deserializer to use\n * @throws RecordInstantiationException\n * when the record could not be deserialized\n */\n public HostApplicationMetaData(final IValueDeserializer deserializer) throws RecordInstantiationException {\n this.systemName = deserializer.getString();\n this.ipAddress = deserializer.getString();\n this.hostname = deserializer.getString();\n this.applicationName = deserializer.getString();\n }\n\n @Override\n public void serialize(final IValueSerializer serializer) throws BufferOverflowException {\n serializer.putString(this.getSystemName());\n serializer.putString(this.getIpAddress());\n serializer.putString(this.getHostname());\n serializer.putString(this.getApplicationName());\n }\n\n @Override\n public Class[] getValueTypes() {\n // NOPMD\n return TYPES;\n }\n\n @Override\n public String[] getValueNames() {\n // NOPMD\n return VALUE_NAMES;\n }\n\n @Override\n public int getSize() {\n return SIZE;\n }\n\n @Override\n public boolean equals(final Object obj) {\n if (obj == null) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n if (obj.getClass() != this.getClass()) {\n return false;\n }\n final HostApplicationMetaData castedRecord = (HostApplicationMetaData) obj;\n if (this.getLoggingTimestamp() != castedRecord.getLoggingTimestamp()) {\n return false;\n }\n if (!this.getSystemName().equals(castedRecord.getSystemName())) {\n return false;\n }\n if (!this.getIpAddress().equals(castedRecord.getIpAddress())) {\n return false;\n }\n if (!this.getHostname().equals(castedRecord.getHostname())) {\n return false;\n }\n if (!this.getApplicationName().equals(castedRecord.getApplicationName())) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int code = 0;\n code += this.getSystemName().hashCode();\n code += this.getIpAddress().hashCode();\n code += this.getHostname().hashCode();\n ", "post_mask_code": "\n\n public final String getSystemName() {\n return this.systemName;\n }\n\n public final String getIpAddress() {\n return this.ipAddress;\n }\n\n public final String getHostname() {\n return this.hostname;\n }\n\n public final String getApplicationName() {\n return this.applicationName;\n }\n\n @Override\n public String toString() {\n String result = \"HostApplicationMetaData: \";\n result += \"systemName = \";\n result += this.getSystemName() + \", \";\n result += \"ipAddress = \";\n result += this.getIpAddress() + \", \";\n result += \"hostname = \";\n result += this.getHostname() + \", \";\n result += \"applicationName = \";\n result += this.getApplicationName() + \", \";\n return result;\n }\n}\n"} {"task_id": "Java_1381", "language": "Java", "task_type": "single_line", "source_file": "java/github/kieker-monitoring/kieker/kieker-common/src-gen/kieker/common/record/misc/HostApplicationMetaData.java", "mask_start_position": 5240, "mask_end_position": 5263, "canonical_solution": "ult += \"systemName = \";", "pre_mask_code": "package kieker.common.record.misc;\n\nimport java.nio.BufferOverflowException;\nimport kieker.common.exception.RecordInstantiationException;\nimport kieker.common.record.AbstractMonitoringRecord;\nimport kieker.common.record.io.IValueDeserializer;\nimport kieker.common.record.io.IValueSerializer;\n\n/**\n * @author Christian Wulf\n * API compatibility: Kieker 1.15.0\n *\n * @since 1.13\n */\npublic class HostApplicationMetaData extends AbstractMonitoringRecord {\n\n /**\n * Descriptive definition of the serialization size of the record.\n */\n public static final int SIZE = // HostApplicationMetaData.systemName\n TYPE_SIZE_STRING + // HostApplicationMetaData.ipAddress\n TYPE_SIZE_STRING + // HostApplicationMetaData.hostname\n TYPE_SIZE_STRING + // HostApplicationMetaData.applicationName\n TYPE_SIZE_STRING;\n\n public static final Class[] TYPES = { // HostApplicationMetaData.systemName\n String.class, // HostApplicationMetaData.ipAddress\n String.class, // HostApplicationMetaData.hostname\n String.class, // HostApplicationMetaData.applicationName\n String.class };\n\n /**\n * property name array.\n */\n public static final String[] VALUE_NAMES = { \"systemName\", \"ipAddress\", \"hostname\", \"applicationName\" };\n\n public static final String SYSTEM_NAME = \"\";\n\n public static final String IP_ADDRESS = \"\";\n\n public static final String HOSTNAME = \"\";\n\n public static final String APPLICATION_NAME = \"\";\n\n private static final long serialVersionUID = 5425789809172379297L;\n\n /**\n * property declarations.\n */\n private final String systemName;\n\n private final String ipAddress;\n\n private final String hostname;\n\n private final String applicationName;\n\n /**\n * Creates a new instance of this class using the given parameters.\n *\n * @param systemName\n * systemName\n * @param ipAddress\n * ipAddress\n * @param hostname\n * hostname\n * @param applicationName\n * applicationName\n */\n public HostApplicationMetaData(final String systemName, final String ipAddress, final String hostname, final String applicationName) {\n this.systemName = systemName == null ? \"\" : systemName;\n this.ipAddress = ipAddress == null ? \"\" : ipAddress;\n this.hostname = hostname == null ? \"\" : hostname;\n this.applicationName = applicationName == null ? \"\" : applicationName;\n }\n\n /**\n * @param deserializer\n * The deserializer to use\n * @throws RecordInstantiationException\n * when the record could not be deserialized\n */\n public HostApplicationMetaData(final IValueDeserializer deserializer) throws RecordInstantiationException {\n this.systemName = deserializer.getString();\n this.ipAddress = deserializer.getString();\n this.hostname = deserializer.getString();\n this.applicationName = deserializer.getString();\n }\n\n @Override\n public void serialize(final IValueSerializer serializer) throws BufferOverflowException {\n serializer.putString(this.getSystemName());\n serializer.putString(this.getIpAddress());\n serializer.putString(this.getHostname());\n serializer.putString(this.getApplicationName());\n }\n\n @Override\n public Class[] getValueTypes() {\n // NOPMD\n return TYPES;\n }\n\n @Override\n public String[] getValueNames() {\n // NOPMD\n return VALUE_NAMES;\n }\n\n @Override\n public int getSize() {\n return SIZE;\n }\n\n @Override\n public boolean equals(final Object obj) {\n if (obj == null) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n if (obj.getClass() != this.getClass()) {\n return false;\n }\n final HostApplicationMetaData castedRecord = (HostApplicationMetaData) obj;\n if (this.getLoggingTimestamp() != castedRecord.getLoggingTimestamp()) {\n return false;\n }\n if (!this.getSystemName().equals(castedRecord.getSystemName())) {\n return false;\n }\n if (!this.getIpAddress().equals(castedRecord.getIpAddress())) {\n return false;\n }\n if (!this.getHostname().equals(castedRecord.getHostname())) {\n return false;\n }\n if (!this.getApplicationName().equals(castedRecord.getApplicationName())) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int code = 0;\n code += this.getSystemName().hashCode();\n code += this.getIpAddress().hashCode();\n code += this.getHostname().hashCode();\n code += this.getApplicationName().hashCode();\n return code;\n }\n\n public final String getSystemName() {\n return this.systemName;\n }\n\n public final String getIpAddress() {\n return this.ipAddress;\n }\n\n public final String getHostname() {\n return this.hostname;\n }\n\n public final String getApplicationName() {\n return this.applicationName;\n }\n\n @Override\n public String toString() {\n String result = \"HostApplicationMetaData: \";\n res", "post_mask_code": "\n result += this.getSystemName() + \", \";\n result += \"ipAddress = \";\n result += this.getIpAddress() + \", \";\n result += \"hostname = \";\n result += this.getHostname() + \", \";\n result += \"applicationName = \";\n result += this.getApplicationName() + \", \";\n return result;\n }\n}\n"} {"task_id": "Java_1382", "language": "Java", "task_type": "if_statement", "source_file": "java/github/kieker-monitoring/kieker/kieker-common/src-gen/kieker/common/record/misc/HostApplicationMetaData.java", "mask_start_position": 3764, "mask_end_position": 3840, "canonical_solution": "if (obj.getClass() != this.getClass()) {\n return false;\n }", "pre_mask_code": "package kieker.common.record.misc;\n\nimport java.nio.BufferOverflowException;\nimport kieker.common.exception.RecordInstantiationException;\nimport kieker.common.record.AbstractMonitoringRecord;\nimport kieker.common.record.io.IValueDeserializer;\nimport kieker.common.record.io.IValueSerializer;\n\n/**\n * @author Christian Wulf\n * API compatibility: Kieker 1.15.0\n *\n * @since 1.13\n */\npublic class HostApplicationMetaData extends AbstractMonitoringRecord {\n\n /**\n * Descriptive definition of the serialization size of the record.\n */\n public static final int SIZE = // HostApplicationMetaData.systemName\n TYPE_SIZE_STRING + // HostApplicationMetaData.ipAddress\n TYPE_SIZE_STRING + // HostApplicationMetaData.hostname\n TYPE_SIZE_STRING + // HostApplicationMetaData.applicationName\n TYPE_SIZE_STRING;\n\n public static final Class[] TYPES = { // HostApplicationMetaData.systemName\n String.class, // HostApplicationMetaData.ipAddress\n String.class, // HostApplicationMetaData.hostname\n String.class, // HostApplicationMetaData.applicationName\n String.class };\n\n /**\n * property name array.\n */\n public static final String[] VALUE_NAMES = { \"systemName\", \"ipAddress\", \"hostname\", \"applicationName\" };\n\n public static final String SYSTEM_NAME = \"\";\n\n public static final String IP_ADDRESS = \"\";\n\n public static final String HOSTNAME = \"\";\n\n public static final String APPLICATION_NAME = \"\";\n\n private static final long serialVersionUID = 5425789809172379297L;\n\n /**\n * property declarations.\n */\n private final String systemName;\n\n private final String ipAddress;\n\n private final String hostname;\n\n private final String applicationName;\n\n /**\n * Creates a new instance of this class using the given parameters.\n *\n * @param systemName\n * systemName\n * @param ipAddress\n * ipAddress\n * @param hostname\n * hostname\n * @param applicationName\n * applicationName\n */\n public HostApplicationMetaData(final String systemName, final String ipAddress, final String hostname, final String applicationName) {\n this.systemName = systemName == null ? \"\" : systemName;\n this.ipAddress = ipAddress == null ? \"\" : ipAddress;\n this.hostname = hostname == null ? \"\" : hostname;\n this.applicationName = applicationName == null ? \"\" : applicationName;\n }\n\n /**\n * @param deserializer\n * The deserializer to use\n * @throws RecordInstantiationException\n * when the record could not be deserialized\n */\n public HostApplicationMetaData(final IValueDeserializer deserializer) throws RecordInstantiationException {\n this.systemName = deserializer.getString();\n this.ipAddress = deserializer.getString();\n this.hostname = deserializer.getString();\n this.applicationName = deserializer.getString();\n }\n\n @Override\n public void serialize(final IValueSerializer serializer) throws BufferOverflowException {\n serializer.putString(this.getSystemName());\n serializer.putString(this.getIpAddress());\n serializer.putString(this.getHostname());\n serializer.putString(this.getApplicationName());\n }\n\n @Override\n public Class[] getValueTypes() {\n // NOPMD\n return TYPES;\n }\n\n @Override\n public String[] getValueNames() {\n // NOPMD\n return VALUE_NAMES;\n }\n\n @Override\n public int getSize() {\n return SIZE;\n }\n\n @Override\n public boolean equals(final Object obj) {\n if (obj == null) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n ", "post_mask_code": "\n final HostApplicationMetaData castedRecord = (HostApplicationMetaData) obj;\n if (this.getLoggingTimestamp() != castedRecord.getLoggingTimestamp()) {\n return false;\n }\n if (!this.getSystemName().equals(castedRecord.getSystemName())) {\n return false;\n }\n if (!this.getIpAddress().equals(castedRecord.getIpAddress())) {\n return false;\n }\n if (!this.getHostname().equals(castedRecord.getHostname())) {\n return false;\n }\n if (!this.getApplicationName().equals(castedRecord.getApplicationName())) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int code = 0;\n code += this.getSystemName().hashCode();\n code += this.getIpAddress().hashCode();\n code += this.getHostname().hashCode();\n code += this.getApplicationName().hashCode();\n return code;\n }\n\n public final String getSystemName() {\n return this.systemName;\n }\n\n public final String getIpAddress() {\n return this.ipAddress;\n }\n\n public final String getHostname() {\n return this.hostname;\n }\n\n public final String getApplicationName() {\n return this.applicationName;\n }\n\n @Override\n public String toString() {\n String result = \"HostApplicationMetaData: \";\n result += \"systemName = \";\n result += this.getSystemName() + \", \";\n result += \"ipAddress = \";\n result += this.getIpAddress() + \", \";\n result += \"hostname = \";\n result += this.getHostname() + \", \";\n result += \"applicationName = \";\n result += this.getApplicationName() + \", \";\n return result;\n }\n}\n"} {"task_id": "Java_1383", "language": "Java", "task_type": "method_signature", "source_file": "java/github/google/binnavi/src/main/java/com/google/security/zynamics/binnavi/Gui/CriteriaDialog/CAddConditionButtonListener.java", "mask_start_position": 1380, "mask_end_position": 1447, "canonical_solution": "@Override\n public void actionPerformed(final ActionEvent event) ", "pre_mask_code": "package com.google.security.zynamics.binnavi.Gui.CriteriaDialog;\n\nimport java.awt.event.ActionEvent;\nimport javax.swing.AbstractAction;\nimport com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionModel.CCriteriumTree;\nimport com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.JCriteriumTree;\nimport com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Implementations.CCriteriumFunctions;\n\n/**\n * Listener class that handles clicks on the Add Condition button.\n */\npublic final class CAddConditionButtonListener extends AbstractAction {\n\n private static final long serialVersionUID = 502859633998619670L;\n\n /**\n * Visible criteria tree.\n */\n private final JCriteriumTree m_jtree;\n\n /**\n * Backs the visible criteria tree.\n */\n private final CCriteriumTree m_ctree;\n\n /**\n * Provides the criterium to add.\n */\n private final CConditionBox m_selectionBox;\n\n /**\n * Creates a new action object.\n *\n * @param jtree Visible criteria tree.\n * @param ctree Backs the visible criteria tree.\n * @param conditionBox Provides the criterium to add.\n */\n public CAddConditionButtonListener(final JCriteriumTree jtree, final CCriteriumTree ctree, final CConditionBox conditionBox) {\n m_jtree = jtree;\n m_ctree = ctree;\n m_selectionBox = conditionBox;\n }\n\n ", "post_mask_code": "{\n CCriteriumFunctions.appendCriterium(m_jtree, m_ctree, m_selectionBox);\n }\n}\n"} {"task_id": "Java_1384", "language": "Java", "task_type": "method_body", "source_file": "java/github/google/binnavi/src/main/java/com/google/security/zynamics/binnavi/Gui/CriteriaDialog/CAddConditionButtonListener.java", "mask_start_position": 1447, "mask_end_position": 1533, "canonical_solution": "{\n CCriteriumFunctions.appendCriterium(m_jtree, m_ctree, m_selectionBox);\n }", "pre_mask_code": "package com.google.security.zynamics.binnavi.Gui.CriteriaDialog;\n\nimport java.awt.event.ActionEvent;\nimport javax.swing.AbstractAction;\nimport com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionModel.CCriteriumTree;\nimport com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.JCriteriumTree;\nimport com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Implementations.CCriteriumFunctions;\n\n/**\n * Listener class that handles clicks on the Add Condition button.\n */\npublic final class CAddConditionButtonListener extends AbstractAction {\n\n private static final long serialVersionUID = 502859633998619670L;\n\n /**\n * Visible criteria tree.\n */\n private final JCriteriumTree m_jtree;\n\n /**\n * Backs the visible criteria tree.\n */\n private final CCriteriumTree m_ctree;\n\n /**\n * Provides the criterium to add.\n */\n private final CConditionBox m_selectionBox;\n\n /**\n * Creates a new action object.\n *\n * @param jtree Visible criteria tree.\n * @param ctree Backs the visible criteria tree.\n * @param conditionBox Provides the criterium to add.\n */\n public CAddConditionButtonListener(final JCriteriumTree jtree, final CCriteriumTree ctree, final CConditionBox conditionBox) {\n m_jtree = jtree;\n m_ctree = ctree;\n m_selectionBox = conditionBox;\n }\n\n @Override\n public void actionPerformed(final ActionEvent event) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1385", "language": "Java", "task_type": "single_line", "source_file": "java/github/google/binnavi/src/main/java/com/google/security/zynamics/binnavi/Gui/CriteriaDialog/CAddConditionButtonListener.java", "mask_start_position": 1480, "mask_end_position": 1527, "canonical_solution": "endCriterium(m_jtree, m_ctree, m_selectionBox);", "pre_mask_code": "package com.google.security.zynamics.binnavi.Gui.CriteriaDialog;\n\nimport java.awt.event.ActionEvent;\nimport javax.swing.AbstractAction;\nimport com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionModel.CCriteriumTree;\nimport com.google.security.zynamics.binnavi.Gui.CriteriaDialog.ExpressionTree.JCriteriumTree;\nimport com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Implementations.CCriteriumFunctions;\n\n/**\n * Listener class that handles clicks on the Add Condition button.\n */\npublic final class CAddConditionButtonListener extends AbstractAction {\n\n private static final long serialVersionUID = 502859633998619670L;\n\n /**\n * Visible criteria tree.\n */\n private final JCriteriumTree m_jtree;\n\n /**\n * Backs the visible criteria tree.\n */\n private final CCriteriumTree m_ctree;\n\n /**\n * Provides the criterium to add.\n */\n private final CConditionBox m_selectionBox;\n\n /**\n * Creates a new action object.\n *\n * @param jtree Visible criteria tree.\n * @param ctree Backs the visible criteria tree.\n * @param conditionBox Provides the criterium to add.\n */\n public CAddConditionButtonListener(final JCriteriumTree jtree, final CCriteriumTree ctree, final CConditionBox conditionBox) {\n m_jtree = jtree;\n m_ctree = ctree;\n m_selectionBox = conditionBox;\n }\n\n @Override\n public void actionPerformed(final ActionEvent event) {\n CCriteriumFunctions.app", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1386", "language": "Java", "task_type": "method_signature", "source_file": "java/github/helyho/Voovan/Web/src/main/java/org/voovan/http/message/packet/Cookie.java", "mask_start_position": 1693, "mask_end_position": 1718, "canonical_solution": "public String getValue() ", "pre_mask_code": "package org.voovan.http.message.packet;\n\nimport org.voovan.http.message.Request;\nimport org.voovan.http.server.context.WebContext;\nimport org.voovan.tools.log.Logger;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.net.URLEncoder;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * HTTP 的 cookie 对象\n * @author helyho\n *\n * Voovan Framework.\n * WebSite: http://example.com\n */\npublic class Cookie {\n\n private String domain;\n\n private String path;\n\n private int maxAge = -999999;\n\n private String expires;\n\n private boolean secure;\n\n private boolean httpOnly;\n\n private String name;\n\n private String value;\n\n private Cookie() {\n }\n\n public String getDomain() {\n return domain;\n }\n\n public void setDomain(String domain) {\n this.domain = domain;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public int getMaxAge() {\n return maxAge;\n }\n\n public void setMaxAge(int maxAge) {\n this.maxAge = maxAge;\n }\n\n public String getExpires() {\n return expires;\n }\n\n public void setExpires(String expires) {\n this.expires = expires;\n }\n\n public boolean isSecure() {\n return secure;\n }\n\n public void setSecure(boolean secure) {\n this.secure = secure;\n }\n\n public boolean isHttpOnly() {\n return httpOnly;\n }\n\n public void setHttpOnly(boolean httpOnly) {\n this.httpOnly = httpOnly;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n ", "post_mask_code": "{\n try {\n return URLDecoder.decode(this.value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n return this.value;\n }\n\n public void setValue(String value) {\n try {\n this.value = URLEncoder.encode(value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n }\n\n @Override\n public String toString() {\n return (this.name != null || this.value != null ? (this.name + \"=\" + this.value) : \"\") + (this.domain != null ? (\"; domain=\" + this.domain) : \"\") + (this.maxAge != -999999 ? (\"; max-age=\" + this.maxAge) : \"\") + (this.path != null ? (\"; path=\" + this.path) : \"\") + (this.httpOnly ? \"; httponly; \" : \"\") + (this.secure ? \"; secure\" : \"\");\n }\n\n /**\n * 通过 Map 构建一个 Cookie 对象\n * @param cookieMap Cookie 属性 Map\n * @return Cookie 对象\n */\n public static Cookie buildCookie(Map cookieMap) {\n Cookie cookie = new Cookie();\n for (Entry cookieMapItem : cookieMap.entrySet()) {\n switch(cookieMapItem.getKey().toLowerCase()) {\n case \"domain\":\n cookie.setDomain(cookieMapItem.getValue());\n break;\n case \"path\":\n cookie.setPath(cookieMapItem.getValue());\n break;\n case \"max-age\":\n cookie.setMaxAge(Integer.parseInt(cookieMapItem.getValue()));\n break;\n case \"secure\":\n cookie.setSecure(true);\n break;\n case \"httponly\":\n cookie.setHttpOnly(true);\n break;\n case \"expires\":\n cookie.setExpires(cookieMapItem.getValue());\n break;\n default:\n cookie.setName(cookieMapItem.getKey());\n cookie.setValue(cookieMapItem.getValue());\n break;\n }\n }\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param domain\tcookie的受控域\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(String domain, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n Cookie cookie = new Cookie();\n cookie.setName(name);\n cookie.setValue(value);\n cookie.setPath(path);\n cookie.setDomain(domain);\n cookie.setMaxAge(maxAge);\n cookie.setHttpOnly(isHttpOnly);\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n String Host = request.header().get(\"Host\");\n String domain = Host.split(\":\")[0];\n return newInstance(domain, path, name, value, maxAge, isHttpOnly);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value) {\n return newInstance(request, path, name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String name, String value) {\n return newInstance(request, \"/\", name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n}\n"} {"task_id": "Java_1387", "language": "Java", "task_type": "method_body", "source_file": "java/github/helyho/Voovan/Web/src/main/java/org/voovan/http/message/packet/Cookie.java", "mask_start_position": 1654, "mask_end_position": 1687, "canonical_solution": "{\n this.name = name;\n }", "pre_mask_code": "package org.voovan.http.message.packet;\n\nimport org.voovan.http.message.Request;\nimport org.voovan.http.server.context.WebContext;\nimport org.voovan.tools.log.Logger;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.net.URLEncoder;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * HTTP 的 cookie 对象\n * @author helyho\n *\n * Voovan Framework.\n * WebSite: http://example.com\n */\npublic class Cookie {\n\n private String domain;\n\n private String path;\n\n private int maxAge = -999999;\n\n private String expires;\n\n private boolean secure;\n\n private boolean httpOnly;\n\n private String name;\n\n private String value;\n\n private Cookie() {\n }\n\n public String getDomain() {\n return domain;\n }\n\n public void setDomain(String domain) {\n this.domain = domain;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public int getMaxAge() {\n return maxAge;\n }\n\n public void setMaxAge(int maxAge) {\n this.maxAge = maxAge;\n }\n\n public String getExpires() {\n return expires;\n }\n\n public void setExpires(String expires) {\n this.expires = expires;\n }\n\n public boolean isSecure() {\n return secure;\n }\n\n public void setSecure(boolean secure) {\n this.secure = secure;\n }\n\n public boolean isHttpOnly() {\n return httpOnly;\n }\n\n public void setHttpOnly(boolean httpOnly) {\n this.httpOnly = httpOnly;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) ", "post_mask_code": "\n\n public String getValue() {\n try {\n return URLDecoder.decode(this.value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n return this.value;\n }\n\n public void setValue(String value) {\n try {\n this.value = URLEncoder.encode(value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n }\n\n @Override\n public String toString() {\n return (this.name != null || this.value != null ? (this.name + \"=\" + this.value) : \"\") + (this.domain != null ? (\"; domain=\" + this.domain) : \"\") + (this.maxAge != -999999 ? (\"; max-age=\" + this.maxAge) : \"\") + (this.path != null ? (\"; path=\" + this.path) : \"\") + (this.httpOnly ? \"; httponly; \" : \"\") + (this.secure ? \"; secure\" : \"\");\n }\n\n /**\n * 通过 Map 构建一个 Cookie 对象\n * @param cookieMap Cookie 属性 Map\n * @return Cookie 对象\n */\n public static Cookie buildCookie(Map cookieMap) {\n Cookie cookie = new Cookie();\n for (Entry cookieMapItem : cookieMap.entrySet()) {\n switch(cookieMapItem.getKey().toLowerCase()) {\n case \"domain\":\n cookie.setDomain(cookieMapItem.getValue());\n break;\n case \"path\":\n cookie.setPath(cookieMapItem.getValue());\n break;\n case \"max-age\":\n cookie.setMaxAge(Integer.parseInt(cookieMapItem.getValue()));\n break;\n case \"secure\":\n cookie.setSecure(true);\n break;\n case \"httponly\":\n cookie.setHttpOnly(true);\n break;\n case \"expires\":\n cookie.setExpires(cookieMapItem.getValue());\n break;\n default:\n cookie.setName(cookieMapItem.getKey());\n cookie.setValue(cookieMapItem.getValue());\n break;\n }\n }\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param domain\tcookie的受控域\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(String domain, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n Cookie cookie = new Cookie();\n cookie.setName(name);\n cookie.setValue(value);\n cookie.setPath(path);\n cookie.setDomain(domain);\n cookie.setMaxAge(maxAge);\n cookie.setHttpOnly(isHttpOnly);\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n String Host = request.header().get(\"Host\");\n String domain = Host.split(\":\")[0];\n return newInstance(domain, path, name, value, maxAge, isHttpOnly);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value) {\n return newInstance(request, path, name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String name, String value) {\n return newInstance(request, \"/\", name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n}\n"} {"task_id": "Java_1388", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/helyho/Voovan/Web/src/main/java/org/voovan/http/message/packet/Cookie.java", "mask_start_position": 1719, "mask_end_position": 1882, "canonical_solution": "\n try {\n return URLDecoder.decode(this.value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }", "pre_mask_code": "package org.voovan.http.message.packet;\n\nimport org.voovan.http.message.Request;\nimport org.voovan.http.server.context.WebContext;\nimport org.voovan.tools.log.Logger;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.net.URLEncoder;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * HTTP 的 cookie 对象\n * @author helyho\n *\n * Voovan Framework.\n * WebSite: http://example.com\n */\npublic class Cookie {\n\n private String domain;\n\n private String path;\n\n private int maxAge = -999999;\n\n private String expires;\n\n private boolean secure;\n\n private boolean httpOnly;\n\n private String name;\n\n private String value;\n\n private Cookie() {\n }\n\n public String getDomain() {\n return domain;\n }\n\n public void setDomain(String domain) {\n this.domain = domain;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public int getMaxAge() {\n return maxAge;\n }\n\n public void setMaxAge(int maxAge) {\n this.maxAge = maxAge;\n }\n\n public String getExpires() {\n return expires;\n }\n\n public void setExpires(String expires) {\n this.expires = expires;\n }\n\n public boolean isSecure() {\n return secure;\n }\n\n public void setSecure(boolean secure) {\n this.secure = secure;\n }\n\n public boolean isHttpOnly() {\n return httpOnly;\n }\n\n public void setHttpOnly(boolean httpOnly) {\n this.httpOnly = httpOnly;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getValue() {", "post_mask_code": "\n return this.value;\n }\n\n public void setValue(String value) {\n try {\n this.value = URLEncoder.encode(value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n }\n\n @Override\n public String toString() {\n return (this.name != null || this.value != null ? (this.name + \"=\" + this.value) : \"\") + (this.domain != null ? (\"; domain=\" + this.domain) : \"\") + (this.maxAge != -999999 ? (\"; max-age=\" + this.maxAge) : \"\") + (this.path != null ? (\"; path=\" + this.path) : \"\") + (this.httpOnly ? \"; httponly; \" : \"\") + (this.secure ? \"; secure\" : \"\");\n }\n\n /**\n * 通过 Map 构建一个 Cookie 对象\n * @param cookieMap Cookie 属性 Map\n * @return Cookie 对象\n */\n public static Cookie buildCookie(Map cookieMap) {\n Cookie cookie = new Cookie();\n for (Entry cookieMapItem : cookieMap.entrySet()) {\n switch(cookieMapItem.getKey().toLowerCase()) {\n case \"domain\":\n cookie.setDomain(cookieMapItem.getValue());\n break;\n case \"path\":\n cookie.setPath(cookieMapItem.getValue());\n break;\n case \"max-age\":\n cookie.setMaxAge(Integer.parseInt(cookieMapItem.getValue()));\n break;\n case \"secure\":\n cookie.setSecure(true);\n break;\n case \"httponly\":\n cookie.setHttpOnly(true);\n break;\n case \"expires\":\n cookie.setExpires(cookieMapItem.getValue());\n break;\n default:\n cookie.setName(cookieMapItem.getKey());\n cookie.setValue(cookieMapItem.getValue());\n break;\n }\n }\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param domain\tcookie的受控域\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(String domain, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n Cookie cookie = new Cookie();\n cookie.setName(name);\n cookie.setValue(value);\n cookie.setPath(path);\n cookie.setDomain(domain);\n cookie.setMaxAge(maxAge);\n cookie.setHttpOnly(isHttpOnly);\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n String Host = request.header().get(\"Host\");\n String domain = Host.split(\":\")[0];\n return newInstance(domain, path, name, value, maxAge, isHttpOnly);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value) {\n return newInstance(request, path, name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String name, String value) {\n return newInstance(request, \"/\", name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n}\n"} {"task_id": "Java_1389", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/helyho/Voovan/Web/src/main/java/org/voovan/http/message/packet/Cookie.java", "mask_start_position": 1891, "mask_end_position": 1909, "canonical_solution": "return this.value;", "pre_mask_code": "package org.voovan.http.message.packet;\n\nimport org.voovan.http.message.Request;\nimport org.voovan.http.server.context.WebContext;\nimport org.voovan.tools.log.Logger;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.net.URLEncoder;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * HTTP 的 cookie 对象\n * @author helyho\n *\n * Voovan Framework.\n * WebSite: http://example.com\n */\npublic class Cookie {\n\n private String domain;\n\n private String path;\n\n private int maxAge = -999999;\n\n private String expires;\n\n private boolean secure;\n\n private boolean httpOnly;\n\n private String name;\n\n private String value;\n\n private Cookie() {\n }\n\n public String getDomain() {\n return domain;\n }\n\n public void setDomain(String domain) {\n this.domain = domain;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public int getMaxAge() {\n return maxAge;\n }\n\n public void setMaxAge(int maxAge) {\n this.maxAge = maxAge;\n }\n\n public String getExpires() {\n return expires;\n }\n\n public void setExpires(String expires) {\n this.expires = expires;\n }\n\n public boolean isSecure() {\n return secure;\n }\n\n public void setSecure(boolean secure) {\n this.secure = secure;\n }\n\n public boolean isHttpOnly() {\n return httpOnly;\n }\n\n public void setHttpOnly(boolean httpOnly) {\n this.httpOnly = httpOnly;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getValue() {\n try {\n return URLDecoder.decode(this.value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n ", "post_mask_code": "\n }\n\n public void setValue(String value) {\n try {\n this.value = URLEncoder.encode(value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n }\n\n @Override\n public String toString() {\n return (this.name != null || this.value != null ? (this.name + \"=\" + this.value) : \"\") + (this.domain != null ? (\"; domain=\" + this.domain) : \"\") + (this.maxAge != -999999 ? (\"; max-age=\" + this.maxAge) : \"\") + (this.path != null ? (\"; path=\" + this.path) : \"\") + (this.httpOnly ? \"; httponly; \" : \"\") + (this.secure ? \"; secure\" : \"\");\n }\n\n /**\n * 通过 Map 构建一个 Cookie 对象\n * @param cookieMap Cookie 属性 Map\n * @return Cookie 对象\n */\n public static Cookie buildCookie(Map cookieMap) {\n Cookie cookie = new Cookie();\n for (Entry cookieMapItem : cookieMap.entrySet()) {\n switch(cookieMapItem.getKey().toLowerCase()) {\n case \"domain\":\n cookie.setDomain(cookieMapItem.getValue());\n break;\n case \"path\":\n cookie.setPath(cookieMapItem.getValue());\n break;\n case \"max-age\":\n cookie.setMaxAge(Integer.parseInt(cookieMapItem.getValue()));\n break;\n case \"secure\":\n cookie.setSecure(true);\n break;\n case \"httponly\":\n cookie.setHttpOnly(true);\n break;\n case \"expires\":\n cookie.setExpires(cookieMapItem.getValue());\n break;\n default:\n cookie.setName(cookieMapItem.getKey());\n cookie.setValue(cookieMapItem.getValue());\n break;\n }\n }\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param domain\tcookie的受控域\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(String domain, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n Cookie cookie = new Cookie();\n cookie.setName(name);\n cookie.setValue(value);\n cookie.setPath(path);\n cookie.setDomain(domain);\n cookie.setMaxAge(maxAge);\n cookie.setHttpOnly(isHttpOnly);\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n String Host = request.header().get(\"Host\");\n String domain = Host.split(\":\")[0];\n return newInstance(domain, path, name, value, maxAge, isHttpOnly);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value) {\n return newInstance(request, path, name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String name, String value) {\n return newInstance(request, \"/\", name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n}\n"} {"task_id": "Java_1390", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/helyho/Voovan/Web/src/main/java/org/voovan/http/message/packet/Cookie.java", "mask_start_position": 1914, "mask_end_position": 1915, "canonical_solution": "}", "pre_mask_code": "package org.voovan.http.message.packet;\n\nimport org.voovan.http.message.Request;\nimport org.voovan.http.server.context.WebContext;\nimport org.voovan.tools.log.Logger;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.net.URLEncoder;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * HTTP 的 cookie 对象\n * @author helyho\n *\n * Voovan Framework.\n * WebSite: http://example.com\n */\npublic class Cookie {\n\n private String domain;\n\n private String path;\n\n private int maxAge = -999999;\n\n private String expires;\n\n private boolean secure;\n\n private boolean httpOnly;\n\n private String name;\n\n private String value;\n\n private Cookie() {\n }\n\n public String getDomain() {\n return domain;\n }\n\n public void setDomain(String domain) {\n this.domain = domain;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public int getMaxAge() {\n return maxAge;\n }\n\n public void setMaxAge(int maxAge) {\n this.maxAge = maxAge;\n }\n\n public String getExpires() {\n return expires;\n }\n\n public void setExpires(String expires) {\n this.expires = expires;\n }\n\n public boolean isSecure() {\n return secure;\n }\n\n public void setSecure(boolean secure) {\n this.secure = secure;\n }\n\n public boolean isHttpOnly() {\n return httpOnly;\n }\n\n public void setHttpOnly(boolean httpOnly) {\n this.httpOnly = httpOnly;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getValue() {\n try {\n return URLDecoder.decode(this.value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n return this.value;\n ", "post_mask_code": "\n\n public void setValue(String value) {\n try {\n this.value = URLEncoder.encode(value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n }\n\n @Override\n public String toString() {\n return (this.name != null || this.value != null ? (this.name + \"=\" + this.value) : \"\") + (this.domain != null ? (\"; domain=\" + this.domain) : \"\") + (this.maxAge != -999999 ? (\"; max-age=\" + this.maxAge) : \"\") + (this.path != null ? (\"; path=\" + this.path) : \"\") + (this.httpOnly ? \"; httponly; \" : \"\") + (this.secure ? \"; secure\" : \"\");\n }\n\n /**\n * 通过 Map 构建一个 Cookie 对象\n * @param cookieMap Cookie 属性 Map\n * @return Cookie 对象\n */\n public static Cookie buildCookie(Map cookieMap) {\n Cookie cookie = new Cookie();\n for (Entry cookieMapItem : cookieMap.entrySet()) {\n switch(cookieMapItem.getKey().toLowerCase()) {\n case \"domain\":\n cookie.setDomain(cookieMapItem.getValue());\n break;\n case \"path\":\n cookie.setPath(cookieMapItem.getValue());\n break;\n case \"max-age\":\n cookie.setMaxAge(Integer.parseInt(cookieMapItem.getValue()));\n break;\n case \"secure\":\n cookie.setSecure(true);\n break;\n case \"httponly\":\n cookie.setHttpOnly(true);\n break;\n case \"expires\":\n cookie.setExpires(cookieMapItem.getValue());\n break;\n default:\n cookie.setName(cookieMapItem.getKey());\n cookie.setValue(cookieMapItem.getValue());\n break;\n }\n }\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param domain\tcookie的受控域\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(String domain, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n Cookie cookie = new Cookie();\n cookie.setName(name);\n cookie.setValue(value);\n cookie.setPath(path);\n cookie.setDomain(domain);\n cookie.setMaxAge(maxAge);\n cookie.setHttpOnly(isHttpOnly);\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n String Host = request.header().get(\"Host\");\n String domain = Host.split(\":\")[0];\n return newInstance(domain, path, name, value, maxAge, isHttpOnly);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value) {\n return newInstance(request, path, name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String name, String value) {\n return newInstance(request, \"/\", name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n}\n"} {"task_id": "Java_1391", "language": "Java", "task_type": "single_line", "source_file": "java/github/helyho/Voovan/Web/src/main/java/org/voovan/http/message/packet/Cookie.java", "mask_start_position": 4227, "mask_end_position": 4248, "canonical_solution": "cookie.setName(name);", "pre_mask_code": "package org.voovan.http.message.packet;\n\nimport org.voovan.http.message.Request;\nimport org.voovan.http.server.context.WebContext;\nimport org.voovan.tools.log.Logger;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.net.URLEncoder;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * HTTP 的 cookie 对象\n * @author helyho\n *\n * Voovan Framework.\n * WebSite: http://example.com\n */\npublic class Cookie {\n\n private String domain;\n\n private String path;\n\n private int maxAge = -999999;\n\n private String expires;\n\n private boolean secure;\n\n private boolean httpOnly;\n\n private String name;\n\n private String value;\n\n private Cookie() {\n }\n\n public String getDomain() {\n return domain;\n }\n\n public void setDomain(String domain) {\n this.domain = domain;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public int getMaxAge() {\n return maxAge;\n }\n\n public void setMaxAge(int maxAge) {\n this.maxAge = maxAge;\n }\n\n public String getExpires() {\n return expires;\n }\n\n public void setExpires(String expires) {\n this.expires = expires;\n }\n\n public boolean isSecure() {\n return secure;\n }\n\n public void setSecure(boolean secure) {\n this.secure = secure;\n }\n\n public boolean isHttpOnly() {\n return httpOnly;\n }\n\n public void setHttpOnly(boolean httpOnly) {\n this.httpOnly = httpOnly;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getValue() {\n try {\n return URLDecoder.decode(this.value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n return this.value;\n }\n\n public void setValue(String value) {\n try {\n this.value = URLEncoder.encode(value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n }\n\n @Override\n public String toString() {\n return (this.name != null || this.value != null ? (this.name + \"=\" + this.value) : \"\") + (this.domain != null ? (\"; domain=\" + this.domain) : \"\") + (this.maxAge != -999999 ? (\"; max-age=\" + this.maxAge) : \"\") + (this.path != null ? (\"; path=\" + this.path) : \"\") + (this.httpOnly ? \"; httponly; \" : \"\") + (this.secure ? \"; secure\" : \"\");\n }\n\n /**\n * 通过 Map 构建一个 Cookie 对象\n * @param cookieMap Cookie 属性 Map\n * @return Cookie 对象\n */\n public static Cookie buildCookie(Map cookieMap) {\n Cookie cookie = new Cookie();\n for (Entry cookieMapItem : cookieMap.entrySet()) {\n switch(cookieMapItem.getKey().toLowerCase()) {\n case \"domain\":\n cookie.setDomain(cookieMapItem.getValue());\n break;\n case \"path\":\n cookie.setPath(cookieMapItem.getValue());\n break;\n case \"max-age\":\n cookie.setMaxAge(Integer.parseInt(cookieMapItem.getValue()));\n break;\n case \"secure\":\n cookie.setSecure(true);\n break;\n case \"httponly\":\n cookie.setHttpOnly(true);\n break;\n case \"expires\":\n cookie.setExpires(cookieMapItem.getValue());\n break;\n default:\n cookie.setName(cookieMapItem.getKey());\n cookie.setValue(cookieMapItem.getValue());\n break;\n }\n }\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param domain\tcookie的受控域\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(String domain, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n Cookie cookie = new Cookie();\n ", "post_mask_code": "\n cookie.setValue(value);\n cookie.setPath(path);\n cookie.setDomain(domain);\n cookie.setMaxAge(maxAge);\n cookie.setHttpOnly(isHttpOnly);\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n String Host = request.header().get(\"Host\");\n String domain = Host.split(\":\")[0];\n return newInstance(domain, path, name, value, maxAge, isHttpOnly);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value) {\n return newInstance(request, path, name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String name, String value) {\n return newInstance(request, \"/\", name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n}\n"} {"task_id": "Java_1392", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/helyho/Voovan/Web/src/main/java/org/voovan/http/message/packet/Cookie.java", "mask_start_position": 5514, "mask_end_position": 5718, "canonical_solution": "public static Cookie newInstance(Request request, String name, String value) {\n return newInstance(request, \"/\", name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }", "pre_mask_code": "package org.voovan.http.message.packet;\n\nimport org.voovan.http.message.Request;\nimport org.voovan.http.server.context.WebContext;\nimport org.voovan.tools.log.Logger;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.net.URLEncoder;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * HTTP 的 cookie 对象\n * @author helyho\n *\n * Voovan Framework.\n * WebSite: http://example.com\n */\npublic class Cookie {\n\n private String domain;\n\n private String path;\n\n private int maxAge = -999999;\n\n private String expires;\n\n private boolean secure;\n\n private boolean httpOnly;\n\n private String name;\n\n private String value;\n\n private Cookie() {\n }\n\n public String getDomain() {\n return domain;\n }\n\n public void setDomain(String domain) {\n this.domain = domain;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public int getMaxAge() {\n return maxAge;\n }\n\n public void setMaxAge(int maxAge) {\n this.maxAge = maxAge;\n }\n\n public String getExpires() {\n return expires;\n }\n\n public void setExpires(String expires) {\n this.expires = expires;\n }\n\n public boolean isSecure() {\n return secure;\n }\n\n public void setSecure(boolean secure) {\n this.secure = secure;\n }\n\n public boolean isHttpOnly() {\n return httpOnly;\n }\n\n public void setHttpOnly(boolean httpOnly) {\n this.httpOnly = httpOnly;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getValue() {\n try {\n return URLDecoder.decode(this.value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n return this.value;\n }\n\n public void setValue(String value) {\n try {\n this.value = URLEncoder.encode(value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n }\n\n @Override\n public String toString() {\n return (this.name != null || this.value != null ? (this.name + \"=\" + this.value) : \"\") + (this.domain != null ? (\"; domain=\" + this.domain) : \"\") + (this.maxAge != -999999 ? (\"; max-age=\" + this.maxAge) : \"\") + (this.path != null ? (\"; path=\" + this.path) : \"\") + (this.httpOnly ? \"; httponly; \" : \"\") + (this.secure ? \"; secure\" : \"\");\n }\n\n /**\n * 通过 Map 构建一个 Cookie 对象\n * @param cookieMap Cookie 属性 Map\n * @return Cookie 对象\n */\n public static Cookie buildCookie(Map cookieMap) {\n Cookie cookie = new Cookie();\n for (Entry cookieMapItem : cookieMap.entrySet()) {\n switch(cookieMapItem.getKey().toLowerCase()) {\n case \"domain\":\n cookie.setDomain(cookieMapItem.getValue());\n break;\n case \"path\":\n cookie.setPath(cookieMapItem.getValue());\n break;\n case \"max-age\":\n cookie.setMaxAge(Integer.parseInt(cookieMapItem.getValue()));\n break;\n case \"secure\":\n cookie.setSecure(true);\n break;\n case \"httponly\":\n cookie.setHttpOnly(true);\n break;\n case \"expires\":\n cookie.setExpires(cookieMapItem.getValue());\n break;\n default:\n cookie.setName(cookieMapItem.getKey());\n cookie.setValue(cookieMapItem.getValue());\n break;\n }\n }\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param domain\tcookie的受控域\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(String domain, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n Cookie cookie = new Cookie();\n cookie.setName(name);\n cookie.setValue(value);\n cookie.setPath(path);\n cookie.setDomain(domain);\n cookie.setMaxAge(maxAge);\n cookie.setHttpOnly(isHttpOnly);\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n String Host = request.header().get(\"Host\");\n String domain = Host.split(\":\")[0];\n return newInstance(domain, path, name, value, maxAge, isHttpOnly);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value) {\n return newInstance(request, path, name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1393", "language": "Java", "task_type": "try_statement", "source_file": "java/github/helyho/Voovan/Web/src/main/java/org/voovan/http/message/packet/Cookie.java", "mask_start_position": 1966, "mask_end_position": 2121, "canonical_solution": "try {\n this.value = URLEncoder.encode(value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }", "pre_mask_code": "package org.voovan.http.message.packet;\n\nimport org.voovan.http.message.Request;\nimport org.voovan.http.server.context.WebContext;\nimport org.voovan.tools.log.Logger;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.net.URLEncoder;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * HTTP 的 cookie 对象\n * @author helyho\n *\n * Voovan Framework.\n * WebSite: http://example.com\n */\npublic class Cookie {\n\n private String domain;\n\n private String path;\n\n private int maxAge = -999999;\n\n private String expires;\n\n private boolean secure;\n\n private boolean httpOnly;\n\n private String name;\n\n private String value;\n\n private Cookie() {\n }\n\n public String getDomain() {\n return domain;\n }\n\n public void setDomain(String domain) {\n this.domain = domain;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public int getMaxAge() {\n return maxAge;\n }\n\n public void setMaxAge(int maxAge) {\n this.maxAge = maxAge;\n }\n\n public String getExpires() {\n return expires;\n }\n\n public void setExpires(String expires) {\n this.expires = expires;\n }\n\n public boolean isSecure() {\n return secure;\n }\n\n public void setSecure(boolean secure) {\n this.secure = secure;\n }\n\n public boolean isHttpOnly() {\n return httpOnly;\n }\n\n public void setHttpOnly(boolean httpOnly) {\n this.httpOnly = httpOnly;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getValue() {\n try {\n return URLDecoder.decode(this.value, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n Logger.error(e);\n }\n return this.value;\n }\n\n public void setValue(String value) {\n ", "post_mask_code": "\n }\n\n @Override\n public String toString() {\n return (this.name != null || this.value != null ? (this.name + \"=\" + this.value) : \"\") + (this.domain != null ? (\"; domain=\" + this.domain) : \"\") + (this.maxAge != -999999 ? (\"; max-age=\" + this.maxAge) : \"\") + (this.path != null ? (\"; path=\" + this.path) : \"\") + (this.httpOnly ? \"; httponly; \" : \"\") + (this.secure ? \"; secure\" : \"\");\n }\n\n /**\n * 通过 Map 构建一个 Cookie 对象\n * @param cookieMap Cookie 属性 Map\n * @return Cookie 对象\n */\n public static Cookie buildCookie(Map cookieMap) {\n Cookie cookie = new Cookie();\n for (Entry cookieMapItem : cookieMap.entrySet()) {\n switch(cookieMapItem.getKey().toLowerCase()) {\n case \"domain\":\n cookie.setDomain(cookieMapItem.getValue());\n break;\n case \"path\":\n cookie.setPath(cookieMapItem.getValue());\n break;\n case \"max-age\":\n cookie.setMaxAge(Integer.parseInt(cookieMapItem.getValue()));\n break;\n case \"secure\":\n cookie.setSecure(true);\n break;\n case \"httponly\":\n cookie.setHttpOnly(true);\n break;\n case \"expires\":\n cookie.setExpires(cookieMapItem.getValue());\n break;\n default:\n cookie.setName(cookieMapItem.getKey());\n cookie.setValue(cookieMapItem.getValue());\n break;\n }\n }\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param domain\tcookie的受控域\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(String domain, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n Cookie cookie = new Cookie();\n cookie.setName(name);\n cookie.setValue(value);\n cookie.setPath(path);\n cookie.setDomain(domain);\n cookie.setMaxAge(maxAge);\n cookie.setHttpOnly(isHttpOnly);\n return cookie;\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @param maxAge\t失效时间,单位秒\n * @param isHttpOnly httpOnly属性\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value, int maxAge, boolean isHttpOnly) {\n String Host = request.header().get(\"Host\");\n String domain = Host.split(\":\")[0];\n return newInstance(domain, path, name, value, maxAge, isHttpOnly);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param path cookie路径\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String path, String name, String value) {\n return newInstance(request, path, name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n\n /**\n * 创建一个 Cookie\n * @param request\t请求对象\n * @param name\t\t名称\n * @param value\t\t值\n * @return Cookie 对象\n */\n public static Cookie newInstance(Request request, String name, String value) {\n return newInstance(request, \"/\", name, value, WebContext.getWebServerConfig().getSessionTimeout() * 60, false);\n }\n}\n"} {"task_id": "Java_1394", "language": "Java", "task_type": "method_signature", "source_file": "java/github/NashLegend/SourceWall/app/src/main/java/net/nashlegend/sourcewall/request/parsers/ArticleListParser.java", "mask_start_position": 415, "mask_end_position": 545, "canonical_solution": "@Override\n public ArrayList
parse(String jString, ResponseObject> responseObject) throws Exception ", "pre_mask_code": "package net.nashlegend.sourcewall.request.parsers;\n\nimport net.nashlegend.sourcewall.model.Article;\nimport net.nashlegend.sourcewall.request.JsonHandler;\nimport net.nashlegend.sourcewall.request.ResponseObject;\nimport org.json.JSONArray;\nimport org.json.JSONObject;\nimport java.util.ArrayList;\n\n/**\n * Created by NashLegend on 16/5/2.\n */\npublic class ArticleListParser implements Parser> {\n\n ", "post_mask_code": "{\n ArrayList
articleList = new ArrayList<>();\n JSONArray articles = JsonHandler.getUniversalJsonArray(jString, responseObject);\n assert articles != null;\n for (int i = 0; i < articles.length(); i++) {\n JSONObject jo = articles.getJSONObject(i);\n articleList.add(Article.fromJsonSimple(jo));\n }\n return articleList;\n }\n}\n"} {"task_id": "Java_1395", "language": "Java", "task_type": "method_body", "source_file": "java/github/NashLegend/SourceWall/app/src/main/java/net/nashlegend/sourcewall/request/parsers/ArticleListParser.java", "mask_start_position": 545, "mask_end_position": 938, "canonical_solution": "{\n ArrayList
articleList = new ArrayList<>();\n JSONArray articles = JsonHandler.getUniversalJsonArray(jString, responseObject);\n assert articles != null;\n for (int i = 0; i < articles.length(); i++) {\n JSONObject jo = articles.getJSONObject(i);\n articleList.add(Article.fromJsonSimple(jo));\n }\n return articleList;\n }", "pre_mask_code": "package net.nashlegend.sourcewall.request.parsers;\n\nimport net.nashlegend.sourcewall.model.Article;\nimport net.nashlegend.sourcewall.request.JsonHandler;\nimport net.nashlegend.sourcewall.request.ResponseObject;\nimport org.json.JSONArray;\nimport org.json.JSONObject;\nimport java.util.ArrayList;\n\n/**\n * Created by NashLegend on 16/5/2.\n */\npublic class ArticleListParser implements Parser> {\n\n @Override\n public ArrayList
parse(String jString, ResponseObject> responseObject) throws Exception ", "post_mask_code": "\n}\n"} {"task_id": "Java_1396", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/NashLegend/SourceWall/app/src/main/java/net/nashlegend/sourcewall/request/parsers/ArticleListParser.java", "mask_start_position": 546, "mask_end_position": 695, "canonical_solution": "\n ArrayList
articleList = new ArrayList<>();\n JSONArray articles = JsonHandler.getUniversalJsonArray(jString, responseObject);", "pre_mask_code": "package net.nashlegend.sourcewall.request.parsers;\n\nimport net.nashlegend.sourcewall.model.Article;\nimport net.nashlegend.sourcewall.request.JsonHandler;\nimport net.nashlegend.sourcewall.request.ResponseObject;\nimport org.json.JSONArray;\nimport org.json.JSONObject;\nimport java.util.ArrayList;\n\n/**\n * Created by NashLegend on 16/5/2.\n */\npublic class ArticleListParser implements Parser> {\n\n @Override\n public ArrayList
parse(String jString, ResponseObject> responseObject) throws Exception {", "post_mask_code": "\n assert articles != null;\n for (int i = 0; i < articles.length(); i++) {\n JSONObject jo = articles.getJSONObject(i);\n articleList.add(Article.fromJsonSimple(jo));\n }\n return articleList;\n }\n}\n"} {"task_id": "Java_1397", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/NashLegend/SourceWall/app/src/main/java/net/nashlegend/sourcewall/request/parsers/ArticleListParser.java", "mask_start_position": 704, "mask_end_position": 904, "canonical_solution": "assert articles != null;\n for (int i = 0; i < articles.length(); i++) {\n JSONObject jo = articles.getJSONObject(i);\n articleList.add(Article.fromJsonSimple(jo));\n }", "pre_mask_code": "package net.nashlegend.sourcewall.request.parsers;\n\nimport net.nashlegend.sourcewall.model.Article;\nimport net.nashlegend.sourcewall.request.JsonHandler;\nimport net.nashlegend.sourcewall.request.ResponseObject;\nimport org.json.JSONArray;\nimport org.json.JSONObject;\nimport java.util.ArrayList;\n\n/**\n * Created by NashLegend on 16/5/2.\n */\npublic class ArticleListParser implements Parser> {\n\n @Override\n public ArrayList
parse(String jString, ResponseObject> responseObject) throws Exception {\n ArrayList
articleList = new ArrayList<>();\n JSONArray articles = JsonHandler.getUniversalJsonArray(jString, responseObject);\n ", "post_mask_code": "\n return articleList;\n }\n}\n"} {"task_id": "Java_1398", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/NashLegend/SourceWall/app/src/main/java/net/nashlegend/sourcewall/request/parsers/ArticleListParser.java", "mask_start_position": 913, "mask_end_position": 938, "canonical_solution": "return articleList;\n }", "pre_mask_code": "package net.nashlegend.sourcewall.request.parsers;\n\nimport net.nashlegend.sourcewall.model.Article;\nimport net.nashlegend.sourcewall.request.JsonHandler;\nimport net.nashlegend.sourcewall.request.ResponseObject;\nimport org.json.JSONArray;\nimport org.json.JSONObject;\nimport java.util.ArrayList;\n\n/**\n * Created by NashLegend on 16/5/2.\n */\npublic class ArticleListParser implements Parser> {\n\n @Override\n public ArrayList
parse(String jString, ResponseObject> responseObject) throws Exception {\n ArrayList
articleList = new ArrayList<>();\n JSONArray articles = JsonHandler.getUniversalJsonArray(jString, responseObject);\n assert articles != null;\n for (int i = 0; i < articles.length(); i++) {\n JSONObject jo = articles.getJSONObject(i);\n articleList.add(Article.fromJsonSimple(jo));\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1399", "language": "Java", "task_type": "single_line", "source_file": "java/github/NashLegend/SourceWall/app/src/main/java/net/nashlegend/sourcewall/request/parsers/ArticleListParser.java", "mask_start_position": 646, "mask_end_position": 695, "canonical_solution": "r.getUniversalJsonArray(jString, responseObject);", "pre_mask_code": "package net.nashlegend.sourcewall.request.parsers;\n\nimport net.nashlegend.sourcewall.model.Article;\nimport net.nashlegend.sourcewall.request.JsonHandler;\nimport net.nashlegend.sourcewall.request.ResponseObject;\nimport org.json.JSONArray;\nimport org.json.JSONObject;\nimport java.util.ArrayList;\n\n/**\n * Created by NashLegend on 16/5/2.\n */\npublic class ArticleListParser implements Parser> {\n\n @Override\n public ArrayList
parse(String jString, ResponseObject> responseObject) throws Exception {\n ArrayList
articleList = new ArrayList<>();\n JSONArray articles = JsonHandle", "post_mask_code": "\n assert articles != null;\n for (int i = 0; i < articles.length(); i++) {\n JSONObject jo = articles.getJSONObject(i);\n articleList.add(Article.fromJsonSimple(jo));\n }\n return articleList;\n }\n}\n"} {"task_id": "Java_1400", "language": "Java", "task_type": "for_statement", "source_file": "java/github/NashLegend/SourceWall/app/src/main/java/net/nashlegend/sourcewall/request/parsers/ArticleListParser.java", "mask_start_position": 737, "mask_end_position": 904, "canonical_solution": "for (int i = 0; i < articles.length(); i++) {\n JSONObject jo = articles.getJSONObject(i);\n articleList.add(Article.fromJsonSimple(jo));\n }", "pre_mask_code": "package net.nashlegend.sourcewall.request.parsers;\n\nimport net.nashlegend.sourcewall.model.Article;\nimport net.nashlegend.sourcewall.request.JsonHandler;\nimport net.nashlegend.sourcewall.request.ResponseObject;\nimport org.json.JSONArray;\nimport org.json.JSONObject;\nimport java.util.ArrayList;\n\n/**\n * Created by NashLegend on 16/5/2.\n */\npublic class ArticleListParser implements Parser> {\n\n @Override\n public ArrayList
parse(String jString, ResponseObject> responseObject) throws Exception {\n ArrayList
articleList = new ArrayList<>();\n JSONArray articles = JsonHandler.getUniversalJsonArray(jString, responseObject);\n assert articles != null;\n ", "post_mask_code": "\n return articleList;\n }\n}\n"} {"task_id": "Java_1401", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/incubator-sedona/core/src/main/java/org/apache/sedona/core/formatMapper/WkbReader.java", "mask_start_position": 787, "mask_end_position": 970, "canonical_solution": "public static SpatialRDD readToGeometryRDD(JavaSparkContext sc, String inputPath, int wkbColumn, boolean allowInvalidGeometries, boolean skipSyntacticallyInvalidGeometries) ", "pre_mask_code": "package org.apache.sedona.core.formatMapper;\n\nimport org.apache.sedona.core.enums.FileDataSplitter;\nimport org.apache.sedona.core.spatialRDD.SpatialRDD;\nimport org.apache.spark.api.java.JavaRDD;\nimport org.apache.spark.api.java.JavaSparkContext;\nimport org.locationtech.jts.geom.Geometry;\n\npublic class WkbReader extends RddReader {\n\n /**\n * Read a SpatialRDD from a file.\n *\n * @param sc\n * @param inputPath\n * @param wkbColumn The column which contains the wkt string. Start from 0.\n * @param allowInvalidGeometries whether allows topology-invalid geometries exist in the generated RDD\n * @param skipSyntacticallyInvalidGeometries whether allows Sedona to automatically skip syntax-invalid geometries, rather than throw errors\n * @return\n */\n ", "post_mask_code": "{\n JavaRDD rawTextRDD = sc.textFile(inputPath);\n FormatMapper formatMapper = new FormatMapper(wkbColumn, -1, FileDataSplitter.WKB, true, null);\n formatMapper.allowTopologicallyInvalidGeometries = allowInvalidGeometries;\n formatMapper.skipSyntacticallyInvalidGeometries = skipSyntacticallyInvalidGeometries;\n return createSpatialRDD(rawTextRDD, formatMapper);\n }\n\n /**\n * Read a SpatialRDD from a string type rdd.\n *\n * @param rawTextRDD a string type RDD\n * @param wkbColumn The column which contains the wkt string. Start from 0.\n * @param allowInvalidGeometries whether allows topology-invalid geometries exist in the generated RDD\n * @param skipSyntacticallyInvalidGeometries whether allows Sedona to automatically skip syntax-invalid geometries, rather than throw errors\n * @return\n */\n public static SpatialRDD readToGeometryRDD(JavaRDD rawTextRDD, int wkbColumn, boolean allowInvalidGeometries, boolean skipSyntacticallyInvalidGeometries) {\n FormatMapper formatMapper = new FormatMapper(wkbColumn, -1, FileDataSplitter.WKB, true, null);\n formatMapper.allowTopologicallyInvalidGeometries = allowInvalidGeometries;\n formatMapper.skipSyntacticallyInvalidGeometries = skipSyntacticallyInvalidGeometries;\n return createSpatialRDD(rawTextRDD, formatMapper);\n }\n}\n"} {"task_id": "Java_1402", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/incubator-sedona/core/src/main/java/org/apache/sedona/core/formatMapper/WkbReader.java", "mask_start_position": 2021, "mask_end_position": 2387, "canonical_solution": "{\n FormatMapper formatMapper = new FormatMapper(wkbColumn, -1, FileDataSplitter.WKB, true, null);\n formatMapper.allowTopologicallyInvalidGeometries = allowInvalidGeometries;\n formatMapper.skipSyntacticallyInvalidGeometries = skipSyntacticallyInvalidGeometries;\n return createSpatialRDD(rawTextRDD, formatMapper);\n }", "pre_mask_code": "package org.apache.sedona.core.formatMapper;\n\nimport org.apache.sedona.core.enums.FileDataSplitter;\nimport org.apache.sedona.core.spatialRDD.SpatialRDD;\nimport org.apache.spark.api.java.JavaRDD;\nimport org.apache.spark.api.java.JavaSparkContext;\nimport org.locationtech.jts.geom.Geometry;\n\npublic class WkbReader extends RddReader {\n\n /**\n * Read a SpatialRDD from a file.\n *\n * @param sc\n * @param inputPath\n * @param wkbColumn The column which contains the wkt string. Start from 0.\n * @param allowInvalidGeometries whether allows topology-invalid geometries exist in the generated RDD\n * @param skipSyntacticallyInvalidGeometries whether allows Sedona to automatically skip syntax-invalid geometries, rather than throw errors\n * @return\n */\n public static SpatialRDD readToGeometryRDD(JavaSparkContext sc, String inputPath, int wkbColumn, boolean allowInvalidGeometries, boolean skipSyntacticallyInvalidGeometries) {\n JavaRDD rawTextRDD = sc.textFile(inputPath);\n FormatMapper formatMapper = new FormatMapper(wkbColumn, -1, FileDataSplitter.WKB, true, null);\n formatMapper.allowTopologicallyInvalidGeometries = allowInvalidGeometries;\n formatMapper.skipSyntacticallyInvalidGeometries = skipSyntacticallyInvalidGeometries;\n return createSpatialRDD(rawTextRDD, formatMapper);\n }\n\n /**\n * Read a SpatialRDD from a string type rdd.\n *\n * @param rawTextRDD a string type RDD\n * @param wkbColumn The column which contains the wkt string. Start from 0.\n * @param allowInvalidGeometries whether allows topology-invalid geometries exist in the generated RDD\n * @param skipSyntacticallyInvalidGeometries whether allows Sedona to automatically skip syntax-invalid geometries, rather than throw errors\n * @return\n */\n public static SpatialRDD readToGeometryRDD(JavaRDD rawTextRDD, int wkbColumn, boolean allowInvalidGeometries, boolean skipSyntacticallyInvalidGeometries) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1403", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/incubator-sedona/core/src/main/java/org/apache/sedona/core/formatMapper/WkbReader.java", "mask_start_position": 971, "mask_end_position": 1147, "canonical_solution": "\n JavaRDD rawTextRDD = sc.textFile(inputPath);\n FormatMapper formatMapper = new FormatMapper(wkbColumn, -1, FileDataSplitter.WKB, true, null);", "pre_mask_code": "package org.apache.sedona.core.formatMapper;\n\nimport org.apache.sedona.core.enums.FileDataSplitter;\nimport org.apache.sedona.core.spatialRDD.SpatialRDD;\nimport org.apache.spark.api.java.JavaRDD;\nimport org.apache.spark.api.java.JavaSparkContext;\nimport org.locationtech.jts.geom.Geometry;\n\npublic class WkbReader extends RddReader {\n\n /**\n * Read a SpatialRDD from a file.\n *\n * @param sc\n * @param inputPath\n * @param wkbColumn The column which contains the wkt string. Start from 0.\n * @param allowInvalidGeometries whether allows topology-invalid geometries exist in the generated RDD\n * @param skipSyntacticallyInvalidGeometries whether allows Sedona to automatically skip syntax-invalid geometries, rather than throw errors\n * @return\n */\n public static SpatialRDD readToGeometryRDD(JavaSparkContext sc, String inputPath, int wkbColumn, boolean allowInvalidGeometries, boolean skipSyntacticallyInvalidGeometries) {", "post_mask_code": "\n formatMapper.allowTopologicallyInvalidGeometries = allowInvalidGeometries;\n formatMapper.skipSyntacticallyInvalidGeometries = skipSyntacticallyInvalidGeometries;\n return createSpatialRDD(rawTextRDD, formatMapper);\n }\n\n /**\n * Read a SpatialRDD from a string type rdd.\n *\n * @param rawTextRDD a string type RDD\n * @param wkbColumn The column which contains the wkt string. Start from 0.\n * @param allowInvalidGeometries whether allows topology-invalid geometries exist in the generated RDD\n * @param skipSyntacticallyInvalidGeometries whether allows Sedona to automatically skip syntax-invalid geometries, rather than throw errors\n * @return\n */\n public static SpatialRDD readToGeometryRDD(JavaRDD rawTextRDD, int wkbColumn, boolean allowInvalidGeometries, boolean skipSyntacticallyInvalidGeometries) {\n FormatMapper formatMapper = new FormatMapper(wkbColumn, -1, FileDataSplitter.WKB, true, null);\n formatMapper.allowTopologicallyInvalidGeometries = allowInvalidGeometries;\n formatMapper.skipSyntacticallyInvalidGeometries = skipSyntacticallyInvalidGeometries;\n return createSpatialRDD(rawTextRDD, formatMapper);\n }\n}\n"} {"task_id": "Java_1404", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/incubator-sedona/core/src/main/java/org/apache/sedona/core/formatMapper/WkbReader.java", "mask_start_position": 1156, "mask_end_position": 1324, "canonical_solution": "formatMapper.allowTopologicallyInvalidGeometries = allowInvalidGeometries;\n formatMapper.skipSyntacticallyInvalidGeometries = skipSyntacticallyInvalidGeometries;", "pre_mask_code": "package org.apache.sedona.core.formatMapper;\n\nimport org.apache.sedona.core.enums.FileDataSplitter;\nimport org.apache.sedona.core.spatialRDD.SpatialRDD;\nimport org.apache.spark.api.java.JavaRDD;\nimport org.apache.spark.api.java.JavaSparkContext;\nimport org.locationtech.jts.geom.Geometry;\n\npublic class WkbReader extends RddReader {\n\n /**\n * Read a SpatialRDD from a file.\n *\n * @param sc\n * @param inputPath\n * @param wkbColumn The column which contains the wkt string. Start from 0.\n * @param allowInvalidGeometries whether allows topology-invalid geometries exist in the generated RDD\n * @param skipSyntacticallyInvalidGeometries whether allows Sedona to automatically skip syntax-invalid geometries, rather than throw errors\n * @return\n */\n public static SpatialRDD readToGeometryRDD(JavaSparkContext sc, String inputPath, int wkbColumn, boolean allowInvalidGeometries, boolean skipSyntacticallyInvalidGeometries) {\n JavaRDD rawTextRDD = sc.textFile(inputPath);\n FormatMapper formatMapper = new FormatMapper(wkbColumn, -1, FileDataSplitter.WKB, true, null);\n ", "post_mask_code": "\n return createSpatialRDD(rawTextRDD, formatMapper);\n }\n\n /**\n * Read a SpatialRDD from a string type rdd.\n *\n * @param rawTextRDD a string type RDD\n * @param wkbColumn The column which contains the wkt string. Start from 0.\n * @param allowInvalidGeometries whether allows topology-invalid geometries exist in the generated RDD\n * @param skipSyntacticallyInvalidGeometries whether allows Sedona to automatically skip syntax-invalid geometries, rather than throw errors\n * @return\n */\n public static SpatialRDD readToGeometryRDD(JavaRDD rawTextRDD, int wkbColumn, boolean allowInvalidGeometries, boolean skipSyntacticallyInvalidGeometries) {\n FormatMapper formatMapper = new FormatMapper(wkbColumn, -1, FileDataSplitter.WKB, true, null);\n formatMapper.allowTopologicallyInvalidGeometries = allowInvalidGeometries;\n formatMapper.skipSyntacticallyInvalidGeometries = skipSyntacticallyInvalidGeometries;\n return createSpatialRDD(rawTextRDD, formatMapper);\n }\n}\n"} {"task_id": "Java_1405", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/incubator-sedona/core/src/main/java/org/apache/sedona/core/formatMapper/WkbReader.java", "mask_start_position": 1333, "mask_end_position": 1389, "canonical_solution": "return createSpatialRDD(rawTextRDD, formatMapper);\n }", "pre_mask_code": "package org.apache.sedona.core.formatMapper;\n\nimport org.apache.sedona.core.enums.FileDataSplitter;\nimport org.apache.sedona.core.spatialRDD.SpatialRDD;\nimport org.apache.spark.api.java.JavaRDD;\nimport org.apache.spark.api.java.JavaSparkContext;\nimport org.locationtech.jts.geom.Geometry;\n\npublic class WkbReader extends RddReader {\n\n /**\n * Read a SpatialRDD from a file.\n *\n * @param sc\n * @param inputPath\n * @param wkbColumn The column which contains the wkt string. Start from 0.\n * @param allowInvalidGeometries whether allows topology-invalid geometries exist in the generated RDD\n * @param skipSyntacticallyInvalidGeometries whether allows Sedona to automatically skip syntax-invalid geometries, rather than throw errors\n * @return\n */\n public static SpatialRDD readToGeometryRDD(JavaSparkContext sc, String inputPath, int wkbColumn, boolean allowInvalidGeometries, boolean skipSyntacticallyInvalidGeometries) {\n JavaRDD rawTextRDD = sc.textFile(inputPath);\n FormatMapper formatMapper = new FormatMapper(wkbColumn, -1, FileDataSplitter.WKB, true, null);\n formatMapper.allowTopologicallyInvalidGeometries = allowInvalidGeometries;\n formatMapper.skipSyntacticallyInvalidGeometries = skipSyntacticallyInvalidGeometries;\n ", "post_mask_code": "\n\n /**\n * Read a SpatialRDD from a string type rdd.\n *\n * @param rawTextRDD a string type RDD\n * @param wkbColumn The column which contains the wkt string. Start from 0.\n * @param allowInvalidGeometries whether allows topology-invalid geometries exist in the generated RDD\n * @param skipSyntacticallyInvalidGeometries whether allows Sedona to automatically skip syntax-invalid geometries, rather than throw errors\n * @return\n */\n public static SpatialRDD readToGeometryRDD(JavaRDD rawTextRDD, int wkbColumn, boolean allowInvalidGeometries, boolean skipSyntacticallyInvalidGeometries) {\n FormatMapper formatMapper = new FormatMapper(wkbColumn, -1, FileDataSplitter.WKB, true, null);\n formatMapper.allowTopologicallyInvalidGeometries = allowInvalidGeometries;\n formatMapper.skipSyntacticallyInvalidGeometries = skipSyntacticallyInvalidGeometries;\n return createSpatialRDD(rawTextRDD, formatMapper);\n }\n}\n"} {"task_id": "Java_1406", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/incubator-sedona/core/src/main/java/org/apache/sedona/core/formatMapper/WkbReader.java", "mask_start_position": 2058, "mask_end_position": 2145, "canonical_solution": "atMapper = new FormatMapper(wkbColumn, -1, FileDataSplitter.WKB, true, null);", "pre_mask_code": "package org.apache.sedona.core.formatMapper;\n\nimport org.apache.sedona.core.enums.FileDataSplitter;\nimport org.apache.sedona.core.spatialRDD.SpatialRDD;\nimport org.apache.spark.api.java.JavaRDD;\nimport org.apache.spark.api.java.JavaSparkContext;\nimport org.locationtech.jts.geom.Geometry;\n\npublic class WkbReader extends RddReader {\n\n /**\n * Read a SpatialRDD from a file.\n *\n * @param sc\n * @param inputPath\n * @param wkbColumn The column which contains the wkt string. Start from 0.\n * @param allowInvalidGeometries whether allows topology-invalid geometries exist in the generated RDD\n * @param skipSyntacticallyInvalidGeometries whether allows Sedona to automatically skip syntax-invalid geometries, rather than throw errors\n * @return\n */\n public static SpatialRDD readToGeometryRDD(JavaSparkContext sc, String inputPath, int wkbColumn, boolean allowInvalidGeometries, boolean skipSyntacticallyInvalidGeometries) {\n JavaRDD rawTextRDD = sc.textFile(inputPath);\n FormatMapper formatMapper = new FormatMapper(wkbColumn, -1, FileDataSplitter.WKB, true, null);\n formatMapper.allowTopologicallyInvalidGeometries = allowInvalidGeometries;\n formatMapper.skipSyntacticallyInvalidGeometries = skipSyntacticallyInvalidGeometries;\n return createSpatialRDD(rawTextRDD, formatMapper);\n }\n\n /**\n * Read a SpatialRDD from a string type rdd.\n *\n * @param rawTextRDD a string type RDD\n * @param wkbColumn The column which contains the wkt string. Start from 0.\n * @param allowInvalidGeometries whether allows topology-invalid geometries exist in the generated RDD\n * @param skipSyntacticallyInvalidGeometries whether allows Sedona to automatically skip syntax-invalid geometries, rather than throw errors\n * @return\n */\n public static SpatialRDD readToGeometryRDD(JavaRDD rawTextRDD, int wkbColumn, boolean allowInvalidGeometries, boolean skipSyntacticallyInvalidGeometries) {\n FormatMapper form", "post_mask_code": "\n formatMapper.allowTopologicallyInvalidGeometries = allowInvalidGeometries;\n formatMapper.skipSyntacticallyInvalidGeometries = skipSyntacticallyInvalidGeometries;\n return createSpatialRDD(rawTextRDD, formatMapper);\n }\n}\n"} {"task_id": "Java_1407", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Haehnchen/idea-php-symfony2-plugin/src/main/java/fr/adrienbrault/idea/symfony2plugin/templating/util/PhpMethodVariableResolveUtil.java", "mask_start_position": 12360, "mask_end_position": 12423, "canonical_solution": "@Override\n public void visitElement(PsiElement element) ", "pre_mask_code": "package fr.adrienbrault.idea.symfony2plugin.templating.util;\n\nimport com.intellij.openapi.util.Pair;\nimport com.intellij.psi.PsiElement;\nimport com.intellij.psi.PsiRecursiveElementWalkingVisitor;\nimport com.intellij.psi.util.PsiTreeUtil;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;\nimport com.jetbrains.php.lang.parser.PhpElementTypes;\nimport com.jetbrains.php.lang.psi.elements.*;\nimport de.espend.idea.php.annotation.util.AnnotationUtil;\nimport fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtension;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtensionParameter;\nimport fr.adrienbrault.idea.symfony2plugin.templating.variable.dict.PsiVariable;\nimport fr.adrienbrault.idea.symfony2plugin.util.AnnotationBackportUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;\nimport kotlin.Triple;\nimport org.apache.commons.lang.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\nimport java.util.*;\nimport java.util.function.Consumer;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport static fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore;\n\n/**\n * @author Daniel Espendiller \n */\npublic class PhpMethodVariableResolveUtil {\n\n private static Set RENDER_METHODS = new HashSet() {\n\n {\n add(\"render\");\n add(\"renderView\");\n add(\"renderResponse\");\n }\n };\n\n /**\n * search for twig template variable on common use cases\n *\n * $this->render('foobar.html.twig', $foobar)\n * $this->render('foobar.html.twig', ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge_recursive($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_push($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_replace($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', $foobar + ['foobar' => $var])\n * $this->render('foobar.html.twig', $foobar += ['foobar' => $var])\n */\n public static Map collectMethodVariables(@NotNull Function method) {\n Map collectedTypes = new HashMap<>();\n for (PsiElement var : collectPossibleTemplateArrays(method)) {\n if (var instanceof ArrayCreationExpression) {\n // \"return array(...)\" we dont need any parsing\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) var));\n } else if (var instanceof Variable) {\n // we need variable declaration line so resolve it and search for references which attach other values to array\n // find definition and search for references on it\n PsiElement resolvedVariable = ((Variable) var).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n } else if (var instanceof FunctionReference && \"array_merge\".equalsIgnoreCase(((FunctionReference) var).getName())) {\n String name = ((FunctionReference) var).getName();\n if (\"array_merge\".equalsIgnoreCase(name) || \"array_merge_recursive\".equalsIgnoreCase(name) || \"array_push\".equalsIgnoreCase(name) || \"array_replace\".equalsIgnoreCase(name)) {\n for (PsiElement psiElement : ((FunctionReference) var).getParameters()) {\n collectVariablesForPsiElement(method, collectedTypes, psiElement);\n }\n }\n } else if (var instanceof BinaryExpression && var.getNode().getElementType() == PhpElementTypes.ADDITIVE_EXPRESSION) {\n PsiElement leftOperand = ((BinaryExpression) var).getLeftOperand();\n if (leftOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, leftOperand);\n }\n PsiElement rightOperand = ((BinaryExpression) var).getRightOperand();\n if (rightOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, rightOperand);\n }\n } else if (var instanceof SelfAssignmentExpression) {\n PhpPsiElement variable = ((SelfAssignmentExpression) var).getVariable();\n if (variable != null) {\n collectVariablesForPsiElement(method, collectedTypes, variable);\n }\n PhpPsiElement value = ((SelfAssignmentExpression) var).getValue();\n if (value != null) {\n collectVariablesForPsiElement(method, collectedTypes, value);\n }\n }\n }\n return collectedTypes;\n }\n\n private static void collectVariablesForPsiElement(@NotNull Function method, @NotNull Map collectedTypes, @NotNull PsiElement psiElement) {\n if (psiElement instanceof ArrayCreationExpression) {\n // reuse array collector: ['foobar' => $var]\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) psiElement));\n } else if (psiElement instanceof Variable) {\n // reuse variable collector: [$var]\n PsiElement resolvedVariable = ((Variable) psiElement).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n }\n }\n\n /**\n * search for variables which are possible accessible inside rendered twig template\n */\n @NotNull\n private static List collectPossibleTemplateArrays(@NotNull Function method) {\n List collectedTemplateVariables = new ArrayList<>();\n // Annotation controller\n // @TODO: check for phpdoc tag\n for (PhpReturn phpReturn : PsiTreeUtil.findChildrenOfType(method, PhpReturn.class)) {\n PhpPsiElement returnPsiElement = phpReturn.getFirstPsiChild();\n // @TODO: think of support all types here\n if (returnPsiElement instanceof Variable || returnPsiElement instanceof ArrayCreationExpression) {\n collectedTemplateVariables.add(returnPsiElement);\n }\n }\n // twig render calls:\n Set references = new HashSet<>();\n visitRenderTemplateFunctions(method, triple -> {\n FunctionReference functionScope = triple.getThird();\n if (functionScope != null) {\n references.add(functionScope);\n }\n });\n for (FunctionReference methodReference : references) {\n PsiElement templateParameter = PsiElementUtils.getMethodParameterPsiElementAt((methodReference).getParameterList(), 1);\n if (templateParameter != null) {\n collectedTemplateVariables.add(templateParameter);\n }\n }\n return collectedTemplateVariables;\n }\n\n /**\n * search for references of variable declaration and collect the types\n *\n * @param function should be function / method scope\n * @param variable the variable declaration psi $var = array();\n */\n @NotNull\n private static Map collectOnVariableReferences(@NotNull Function function, @NotNull Variable variable) {\n Map collectedTypes = new HashMap<>();\n for (Variable scopeVar : PhpElementsUtil.getVariablesInScope(function, variable)) {\n PsiElement parent = scopeVar.getParent();\n if (parent instanceof ArrayAccessExpression) {\n Pair pair = getTypesOnArrayIndex((ArrayAccessExpression) parent);\n if (pair != null) {\n collectedTypes.put(pair.getFirst(), pair.getSecond());\n }\n } else if (parent instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parent).getValue();\n if (value instanceof ArrayCreationExpression) {\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) value));\n }\n }\n }\n return collectedTypes;\n }\n\n @Nullable\n private static Pair getTypesOnArrayIndex(@NotNull ArrayAccessExpression arrayAccessExpression) {\n ArrayIndex arrayIndex = arrayAccessExpression.getIndex();\n if (arrayIndex != null && arrayIndex.getValue() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayIndex.getValue()).getContents();\n Set variableTypes = new HashSet<>();\n PsiElement parent = arrayAccessExpression.getParent();\n if (parent instanceof AssignmentExpression) {\n PsiElement arrayValue = ((AssignmentExpression) parent).getValue();\n if (arrayValue instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayValue).getType().getTypes());\n }\n return Pair.create(variableName, new PsiVariable(variableTypes, ((AssignmentExpression) parent).getValue()));\n } else {\n return Pair.create(variableName, new PsiVariable(variableTypes));\n }\n }\n return null;\n }\n\n public static Map getTypesOnArrayHash(@NotNull ArrayCreationExpression arrayCreationExpression) {\n Map collectedTypes = new HashMap<>();\n for (ArrayHashElement arrayHashElement : arrayCreationExpression.getHashElements()) {\n if (arrayHashElement.getKey() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayHashElement.getKey()).getContents();\n Set variableTypes = new HashSet<>();\n if (arrayHashElement.getValue() instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayHashElement.getValue()).getType().getTypes());\n }\n collectedTypes.put(variableName, new PsiVariable(variableTypes, arrayHashElement.getValue()));\n }\n }\n return collectedTypes;\n }\n\n /**\n * Visit method scope for template renders, also via annotation of the method itself\n *\n * As annotations are not in scope of the method itself\n */\n public static void visitRenderTemplateFunctions(@NotNull Method method, @NotNull Consumer> consumer) {\n TemplateRenderPsiRecursiveElementWalkingVisitor psiElementVisitor = new TemplateRenderPsiRecursiveElementWalkingVisitor(method, consumer);\n PhpDocComment docComment = method.getDocComment();\n for (PhpDocTag phpDocTag : PsiTreeUtil.getChildrenOfTypeAsList(docComment, PhpDocTag.class)) {\n psiElementVisitor.visitPhpDocTag(phpDocTag);\n }\n method.accept(psiElementVisitor);\n }\n\n /**\n * Visit all possible elements for render clements, scope shop be the class or a file itself\n */\n public static void visitRenderTemplateFunctions(@NotNull PsiElement context, @NotNull Consumer> consumer) {\n context.accept(new TemplateRenderPsiRecursiveElementWalkingVisitor(context, consumer));\n }\n\n private static class TemplateRenderPsiRecursiveElementWalkingVisitor extends PsiRecursiveElementWalkingVisitor {\n\n private final PsiElement context;\n\n private final Consumer> consumer;\n\n private Set methods;\n\n TemplateRenderPsiRecursiveElementWalkingVisitor(PsiElement context, Consumer> consumer) {\n this.context = context;\n this.consumer = consumer;\n methods = null;\n }\n\n ", "post_mask_code": "{\n if (element instanceof MethodReference) {\n visitMethodReference((MethodReference) element);\n } else if (element instanceof PhpDocTag) {\n visitPhpDocTag((PhpDocTag) element);\n }\n super.visitElement(element);\n }\n\n private void visitMethodReference(@NotNull MethodReference methodReference) {\n String methodName = methodReference.getName();\n // init methods once per file\n if (methods == null) {\n methods = new HashSet<>();\n methods.addAll(RENDER_METHODS);\n PluginConfigurationExtension[] extensions = Symfony2ProjectComponent.PLUGIN_CONFIGURATION_EXTENSION.getExtensions();\n if (extensions.length > 0) {\n PluginConfigurationExtensionParameter pluginConfiguration = new PluginConfigurationExtensionParameter(context.getProject());\n for (PluginConfigurationExtension extension : extensions) {\n extension.invokePluginConfiguration(pluginConfiguration);\n }\n methods.addAll(pluginConfiguration.getTemplateUsageMethod());\n }\n }\n if (!methods.contains(methodName)) {\n return;\n }\n PsiElement[] parameters = methodReference.getParameters();\n if (parameters.length == 0) {\n return;\n }\n if (parameters[0] instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) parameters[0]);\n } else if (parameters[0] instanceof TernaryExpression) {\n for (PhpPsiElement phpPsiElement : new PhpPsiElement[] { ((TernaryExpression) parameters[0]).getTrueVariant(), ((TernaryExpression) parameters[0]).getFalseVariant() }) {\n if (phpPsiElement == null) {\n continue;\n }\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n } else if (parameters[0] instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parameters[0]).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n } else if (parameters[0] instanceof PhpReference) {\n resolvePhpReference(methodReference, parameters[0]);\n } else if (parameters[0] instanceof BinaryExpression) {\n PsiElement phpPsiElement = ((BinaryExpression) parameters[0]).getRightOperand();\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n }\n\n private void resolvePhpReference(@NotNull MethodReference methodReference, PsiElement parameter) {\n for (PhpNamedElement phpNamedElement : ((PhpReference) parameter).resolveLocal()) {\n if (phpNamedElement instanceof Field) {\n PsiElement defaultValue = ((Field) phpNamedElement).getDefaultValue();\n if (defaultValue instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) defaultValue);\n }\n } else if (phpNamedElement instanceof Variable) {\n PsiElement assignmentExpression = phpNamedElement.getParent();\n if (assignmentExpression instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) assignmentExpression).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n } else if (phpNamedElement instanceof Parameter) {\n PsiElement value = ((Parameter) phpNamedElement).getDefaultValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n }\n }\n\n private void addStringLiteralScope(@NotNull MethodReference methodReference, @NotNull StringLiteralExpression defaultValue) {\n String contents = defaultValue.getContents();\n if (StringUtils.isBlank(contents) || !contents.endsWith(\".twig\")) {\n return;\n }\n Function parentOfType = PsiTreeUtil.getParentOfType(methodReference, Function.class);\n if (parentOfType == null) {\n return;\n }\n addTemplateWithScope(contents, parentOfType, methodReference);\n }\n\n private void visitPhpDocTag(@NotNull PhpDocTag phpDocTag) {\n // \"@var\" and user non related tags dont need an action\n if (AnnotationBackportUtil.NON_ANNOTATION_TAGS.contains(phpDocTag.getName())) {\n return;\n }\n // init scope imports\n Map fileImports = AnnotationBackportUtil.getUseImportMap(phpDocTag);\n if (fileImports.size() == 0) {\n return;\n }\n String annotationFqnName = AnnotationBackportUtil.getClassNameReference(phpDocTag, fileImports);\n if (!StringUtils.stripStart(TwigUtil.TEMPLATE_ANNOTATION_CLASS, \"\\\\\").equals(StringUtils.stripStart(annotationFqnName, \"\\\\\"))) {\n return;\n }\n String template = AnnotationUtil.getPropertyValueOrDefault(phpDocTag, \"template\");\n if (template == null) {\n // see \\Sensio\\Bundle\\FrameworkExtraBundle\\Templating\\TemplateGuesser\n // App\\Controller\\MyNiceController::myAction => my_nice/my.html.twig\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n PhpClass phpClass = methodScope.getContainingClass();\n if (phpClass != null) {\n // App\\Controller\\ \"MyNice\" Controller\n Matcher matcher = Pattern.compile(\"Controller\\\\\\\\(.+)Controller$\", Pattern.MULTILINE).matcher(StringUtils.stripStart(phpClass.getFQN(), \"\\\\\"));\n if (matcher.find()) {\n String group = underscore(matcher.group(1).replace(\"\\\\\", \"/\"));\n String name = methodScope.getName();\n // __invoke is using controller as template name\n if (name.equals(\"__invoke\")) {\n addTemplateWithScope(group + \".html.twig\", methodScope, null);\n } else {\n String action = name.endsWith(\"Action\") ? name.substring(0, name.length() - \"Action\".length()) : name;\n addTemplateWithScope(group + \"/\" + underscore(action) + \".html.twig\", methodScope, null);\n }\n }\n }\n }\n } else if (template.endsWith(\".twig\")) {\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n addTemplateWithScope(template, methodScope, null);\n }\n }\n }\n\n private void addTemplateWithScope(@NotNull String contents, @NotNull PhpNamedElement scope, @Nullable FunctionReference functionReference) {\n String s = TwigUtil.normalizeTemplateName(contents);\n consumer.accept(new Triple<>(s, scope, functionReference));\n }\n }\n}\n"} {"task_id": "Java_1408", "language": "Java", "task_type": "method_body", "source_file": "java/github/Haehnchen/idea-php-symfony2-plugin/src/main/java/fr/adrienbrault/idea/symfony2plugin/templating/util/PhpMethodVariableResolveUtil.java", "mask_start_position": 12423, "mask_end_position": 12716, "canonical_solution": "{\n if (element instanceof MethodReference) {\n visitMethodReference((MethodReference) element);\n } else if (element instanceof PhpDocTag) {\n visitPhpDocTag((PhpDocTag) element);\n }\n super.visitElement(element);\n }", "pre_mask_code": "package fr.adrienbrault.idea.symfony2plugin.templating.util;\n\nimport com.intellij.openapi.util.Pair;\nimport com.intellij.psi.PsiElement;\nimport com.intellij.psi.PsiRecursiveElementWalkingVisitor;\nimport com.intellij.psi.util.PsiTreeUtil;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;\nimport com.jetbrains.php.lang.parser.PhpElementTypes;\nimport com.jetbrains.php.lang.psi.elements.*;\nimport de.espend.idea.php.annotation.util.AnnotationUtil;\nimport fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtension;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtensionParameter;\nimport fr.adrienbrault.idea.symfony2plugin.templating.variable.dict.PsiVariable;\nimport fr.adrienbrault.idea.symfony2plugin.util.AnnotationBackportUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;\nimport kotlin.Triple;\nimport org.apache.commons.lang.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\nimport java.util.*;\nimport java.util.function.Consumer;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport static fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore;\n\n/**\n * @author Daniel Espendiller \n */\npublic class PhpMethodVariableResolveUtil {\n\n private static Set RENDER_METHODS = new HashSet() {\n\n {\n add(\"render\");\n add(\"renderView\");\n add(\"renderResponse\");\n }\n };\n\n /**\n * search for twig template variable on common use cases\n *\n * $this->render('foobar.html.twig', $foobar)\n * $this->render('foobar.html.twig', ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge_recursive($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_push($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_replace($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', $foobar + ['foobar' => $var])\n * $this->render('foobar.html.twig', $foobar += ['foobar' => $var])\n */\n public static Map collectMethodVariables(@NotNull Function method) {\n Map collectedTypes = new HashMap<>();\n for (PsiElement var : collectPossibleTemplateArrays(method)) {\n if (var instanceof ArrayCreationExpression) {\n // \"return array(...)\" we dont need any parsing\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) var));\n } else if (var instanceof Variable) {\n // we need variable declaration line so resolve it and search for references which attach other values to array\n // find definition and search for references on it\n PsiElement resolvedVariable = ((Variable) var).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n } else if (var instanceof FunctionReference && \"array_merge\".equalsIgnoreCase(((FunctionReference) var).getName())) {\n String name = ((FunctionReference) var).getName();\n if (\"array_merge\".equalsIgnoreCase(name) || \"array_merge_recursive\".equalsIgnoreCase(name) || \"array_push\".equalsIgnoreCase(name) || \"array_replace\".equalsIgnoreCase(name)) {\n for (PsiElement psiElement : ((FunctionReference) var).getParameters()) {\n collectVariablesForPsiElement(method, collectedTypes, psiElement);\n }\n }\n } else if (var instanceof BinaryExpression && var.getNode().getElementType() == PhpElementTypes.ADDITIVE_EXPRESSION) {\n PsiElement leftOperand = ((BinaryExpression) var).getLeftOperand();\n if (leftOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, leftOperand);\n }\n PsiElement rightOperand = ((BinaryExpression) var).getRightOperand();\n if (rightOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, rightOperand);\n }\n } else if (var instanceof SelfAssignmentExpression) {\n PhpPsiElement variable = ((SelfAssignmentExpression) var).getVariable();\n if (variable != null) {\n collectVariablesForPsiElement(method, collectedTypes, variable);\n }\n PhpPsiElement value = ((SelfAssignmentExpression) var).getValue();\n if (value != null) {\n collectVariablesForPsiElement(method, collectedTypes, value);\n }\n }\n }\n return collectedTypes;\n }\n\n private static void collectVariablesForPsiElement(@NotNull Function method, @NotNull Map collectedTypes, @NotNull PsiElement psiElement) {\n if (psiElement instanceof ArrayCreationExpression) {\n // reuse array collector: ['foobar' => $var]\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) psiElement));\n } else if (psiElement instanceof Variable) {\n // reuse variable collector: [$var]\n PsiElement resolvedVariable = ((Variable) psiElement).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n }\n }\n\n /**\n * search for variables which are possible accessible inside rendered twig template\n */\n @NotNull\n private static List collectPossibleTemplateArrays(@NotNull Function method) {\n List collectedTemplateVariables = new ArrayList<>();\n // Annotation controller\n // @TODO: check for phpdoc tag\n for (PhpReturn phpReturn : PsiTreeUtil.findChildrenOfType(method, PhpReturn.class)) {\n PhpPsiElement returnPsiElement = phpReturn.getFirstPsiChild();\n // @TODO: think of support all types here\n if (returnPsiElement instanceof Variable || returnPsiElement instanceof ArrayCreationExpression) {\n collectedTemplateVariables.add(returnPsiElement);\n }\n }\n // twig render calls:\n Set references = new HashSet<>();\n visitRenderTemplateFunctions(method, triple -> {\n FunctionReference functionScope = triple.getThird();\n if (functionScope != null) {\n references.add(functionScope);\n }\n });\n for (FunctionReference methodReference : references) {\n PsiElement templateParameter = PsiElementUtils.getMethodParameterPsiElementAt((methodReference).getParameterList(), 1);\n if (templateParameter != null) {\n collectedTemplateVariables.add(templateParameter);\n }\n }\n return collectedTemplateVariables;\n }\n\n /**\n * search for references of variable declaration and collect the types\n *\n * @param function should be function / method scope\n * @param variable the variable declaration psi $var = array();\n */\n @NotNull\n private static Map collectOnVariableReferences(@NotNull Function function, @NotNull Variable variable) {\n Map collectedTypes = new HashMap<>();\n for (Variable scopeVar : PhpElementsUtil.getVariablesInScope(function, variable)) {\n PsiElement parent = scopeVar.getParent();\n if (parent instanceof ArrayAccessExpression) {\n Pair pair = getTypesOnArrayIndex((ArrayAccessExpression) parent);\n if (pair != null) {\n collectedTypes.put(pair.getFirst(), pair.getSecond());\n }\n } else if (parent instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parent).getValue();\n if (value instanceof ArrayCreationExpression) {\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) value));\n }\n }\n }\n return collectedTypes;\n }\n\n @Nullable\n private static Pair getTypesOnArrayIndex(@NotNull ArrayAccessExpression arrayAccessExpression) {\n ArrayIndex arrayIndex = arrayAccessExpression.getIndex();\n if (arrayIndex != null && arrayIndex.getValue() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayIndex.getValue()).getContents();\n Set variableTypes = new HashSet<>();\n PsiElement parent = arrayAccessExpression.getParent();\n if (parent instanceof AssignmentExpression) {\n PsiElement arrayValue = ((AssignmentExpression) parent).getValue();\n if (arrayValue instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayValue).getType().getTypes());\n }\n return Pair.create(variableName, new PsiVariable(variableTypes, ((AssignmentExpression) parent).getValue()));\n } else {\n return Pair.create(variableName, new PsiVariable(variableTypes));\n }\n }\n return null;\n }\n\n public static Map getTypesOnArrayHash(@NotNull ArrayCreationExpression arrayCreationExpression) {\n Map collectedTypes = new HashMap<>();\n for (ArrayHashElement arrayHashElement : arrayCreationExpression.getHashElements()) {\n if (arrayHashElement.getKey() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayHashElement.getKey()).getContents();\n Set variableTypes = new HashSet<>();\n if (arrayHashElement.getValue() instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayHashElement.getValue()).getType().getTypes());\n }\n collectedTypes.put(variableName, new PsiVariable(variableTypes, arrayHashElement.getValue()));\n }\n }\n return collectedTypes;\n }\n\n /**\n * Visit method scope for template renders, also via annotation of the method itself\n *\n * As annotations are not in scope of the method itself\n */\n public static void visitRenderTemplateFunctions(@NotNull Method method, @NotNull Consumer> consumer) {\n TemplateRenderPsiRecursiveElementWalkingVisitor psiElementVisitor = new TemplateRenderPsiRecursiveElementWalkingVisitor(method, consumer);\n PhpDocComment docComment = method.getDocComment();\n for (PhpDocTag phpDocTag : PsiTreeUtil.getChildrenOfTypeAsList(docComment, PhpDocTag.class)) {\n psiElementVisitor.visitPhpDocTag(phpDocTag);\n }\n method.accept(psiElementVisitor);\n }\n\n /**\n * Visit all possible elements for render clements, scope shop be the class or a file itself\n */\n public static void visitRenderTemplateFunctions(@NotNull PsiElement context, @NotNull Consumer> consumer) {\n context.accept(new TemplateRenderPsiRecursiveElementWalkingVisitor(context, consumer));\n }\n\n private static class TemplateRenderPsiRecursiveElementWalkingVisitor extends PsiRecursiveElementWalkingVisitor {\n\n private final PsiElement context;\n\n private final Consumer> consumer;\n\n private Set methods;\n\n TemplateRenderPsiRecursiveElementWalkingVisitor(PsiElement context, Consumer> consumer) {\n this.context = context;\n this.consumer = consumer;\n methods = null;\n }\n\n @Override\n public void visitElement(PsiElement element) ", "post_mask_code": "\n\n private void visitMethodReference(@NotNull MethodReference methodReference) {\n String methodName = methodReference.getName();\n // init methods once per file\n if (methods == null) {\n methods = new HashSet<>();\n methods.addAll(RENDER_METHODS);\n PluginConfigurationExtension[] extensions = Symfony2ProjectComponent.PLUGIN_CONFIGURATION_EXTENSION.getExtensions();\n if (extensions.length > 0) {\n PluginConfigurationExtensionParameter pluginConfiguration = new PluginConfigurationExtensionParameter(context.getProject());\n for (PluginConfigurationExtension extension : extensions) {\n extension.invokePluginConfiguration(pluginConfiguration);\n }\n methods.addAll(pluginConfiguration.getTemplateUsageMethod());\n }\n }\n if (!methods.contains(methodName)) {\n return;\n }\n PsiElement[] parameters = methodReference.getParameters();\n if (parameters.length == 0) {\n return;\n }\n if (parameters[0] instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) parameters[0]);\n } else if (parameters[0] instanceof TernaryExpression) {\n for (PhpPsiElement phpPsiElement : new PhpPsiElement[] { ((TernaryExpression) parameters[0]).getTrueVariant(), ((TernaryExpression) parameters[0]).getFalseVariant() }) {\n if (phpPsiElement == null) {\n continue;\n }\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n } else if (parameters[0] instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parameters[0]).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n } else if (parameters[0] instanceof PhpReference) {\n resolvePhpReference(methodReference, parameters[0]);\n } else if (parameters[0] instanceof BinaryExpression) {\n PsiElement phpPsiElement = ((BinaryExpression) parameters[0]).getRightOperand();\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n }\n\n private void resolvePhpReference(@NotNull MethodReference methodReference, PsiElement parameter) {\n for (PhpNamedElement phpNamedElement : ((PhpReference) parameter).resolveLocal()) {\n if (phpNamedElement instanceof Field) {\n PsiElement defaultValue = ((Field) phpNamedElement).getDefaultValue();\n if (defaultValue instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) defaultValue);\n }\n } else if (phpNamedElement instanceof Variable) {\n PsiElement assignmentExpression = phpNamedElement.getParent();\n if (assignmentExpression instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) assignmentExpression).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n } else if (phpNamedElement instanceof Parameter) {\n PsiElement value = ((Parameter) phpNamedElement).getDefaultValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n }\n }\n\n private void addStringLiteralScope(@NotNull MethodReference methodReference, @NotNull StringLiteralExpression defaultValue) {\n String contents = defaultValue.getContents();\n if (StringUtils.isBlank(contents) || !contents.endsWith(\".twig\")) {\n return;\n }\n Function parentOfType = PsiTreeUtil.getParentOfType(methodReference, Function.class);\n if (parentOfType == null) {\n return;\n }\n addTemplateWithScope(contents, parentOfType, methodReference);\n }\n\n private void visitPhpDocTag(@NotNull PhpDocTag phpDocTag) {\n // \"@var\" and user non related tags dont need an action\n if (AnnotationBackportUtil.NON_ANNOTATION_TAGS.contains(phpDocTag.getName())) {\n return;\n }\n // init scope imports\n Map fileImports = AnnotationBackportUtil.getUseImportMap(phpDocTag);\n if (fileImports.size() == 0) {\n return;\n }\n String annotationFqnName = AnnotationBackportUtil.getClassNameReference(phpDocTag, fileImports);\n if (!StringUtils.stripStart(TwigUtil.TEMPLATE_ANNOTATION_CLASS, \"\\\\\").equals(StringUtils.stripStart(annotationFqnName, \"\\\\\"))) {\n return;\n }\n String template = AnnotationUtil.getPropertyValueOrDefault(phpDocTag, \"template\");\n if (template == null) {\n // see \\Sensio\\Bundle\\FrameworkExtraBundle\\Templating\\TemplateGuesser\n // App\\Controller\\MyNiceController::myAction => my_nice/my.html.twig\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n PhpClass phpClass = methodScope.getContainingClass();\n if (phpClass != null) {\n // App\\Controller\\ \"MyNice\" Controller\n Matcher matcher = Pattern.compile(\"Controller\\\\\\\\(.+)Controller$\", Pattern.MULTILINE).matcher(StringUtils.stripStart(phpClass.getFQN(), \"\\\\\"));\n if (matcher.find()) {\n String group = underscore(matcher.group(1).replace(\"\\\\\", \"/\"));\n String name = methodScope.getName();\n // __invoke is using controller as template name\n if (name.equals(\"__invoke\")) {\n addTemplateWithScope(group + \".html.twig\", methodScope, null);\n } else {\n String action = name.endsWith(\"Action\") ? name.substring(0, name.length() - \"Action\".length()) : name;\n addTemplateWithScope(group + \"/\" + underscore(action) + \".html.twig\", methodScope, null);\n }\n }\n }\n }\n } else if (template.endsWith(\".twig\")) {\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n addTemplateWithScope(template, methodScope, null);\n }\n }\n }\n\n private void addTemplateWithScope(@NotNull String contents, @NotNull PhpNamedElement scope, @Nullable FunctionReference functionReference) {\n String s = TwigUtil.normalizeTemplateName(contents);\n consumer.accept(new Triple<>(s, scope, functionReference));\n }\n }\n}\n"} {"task_id": "Java_1409", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Haehnchen/idea-php-symfony2-plugin/src/main/java/fr/adrienbrault/idea/symfony2plugin/templating/util/PhpMethodVariableResolveUtil.java", "mask_start_position": 17905, "mask_end_position": 18137, "canonical_solution": "\n // \"@var\" and user non related tags dont need an action\n if (AnnotationBackportUtil.NON_ANNOTATION_TAGS.contains(phpDocTag.getName())) {\n return;\n }\n // init scope imports", "pre_mask_code": "package fr.adrienbrault.idea.symfony2plugin.templating.util;\n\nimport com.intellij.openapi.util.Pair;\nimport com.intellij.psi.PsiElement;\nimport com.intellij.psi.PsiRecursiveElementWalkingVisitor;\nimport com.intellij.psi.util.PsiTreeUtil;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;\nimport com.jetbrains.php.lang.parser.PhpElementTypes;\nimport com.jetbrains.php.lang.psi.elements.*;\nimport de.espend.idea.php.annotation.util.AnnotationUtil;\nimport fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtension;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtensionParameter;\nimport fr.adrienbrault.idea.symfony2plugin.templating.variable.dict.PsiVariable;\nimport fr.adrienbrault.idea.symfony2plugin.util.AnnotationBackportUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;\nimport kotlin.Triple;\nimport org.apache.commons.lang.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\nimport java.util.*;\nimport java.util.function.Consumer;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport static fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore;\n\n/**\n * @author Daniel Espendiller \n */\npublic class PhpMethodVariableResolveUtil {\n\n private static Set RENDER_METHODS = new HashSet() {\n\n {\n add(\"render\");\n add(\"renderView\");\n add(\"renderResponse\");\n }\n };\n\n /**\n * search for twig template variable on common use cases\n *\n * $this->render('foobar.html.twig', $foobar)\n * $this->render('foobar.html.twig', ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge_recursive($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_push($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_replace($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', $foobar + ['foobar' => $var])\n * $this->render('foobar.html.twig', $foobar += ['foobar' => $var])\n */\n public static Map collectMethodVariables(@NotNull Function method) {\n Map collectedTypes = new HashMap<>();\n for (PsiElement var : collectPossibleTemplateArrays(method)) {\n if (var instanceof ArrayCreationExpression) {\n // \"return array(...)\" we dont need any parsing\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) var));\n } else if (var instanceof Variable) {\n // we need variable declaration line so resolve it and search for references which attach other values to array\n // find definition and search for references on it\n PsiElement resolvedVariable = ((Variable) var).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n } else if (var instanceof FunctionReference && \"array_merge\".equalsIgnoreCase(((FunctionReference) var).getName())) {\n String name = ((FunctionReference) var).getName();\n if (\"array_merge\".equalsIgnoreCase(name) || \"array_merge_recursive\".equalsIgnoreCase(name) || \"array_push\".equalsIgnoreCase(name) || \"array_replace\".equalsIgnoreCase(name)) {\n for (PsiElement psiElement : ((FunctionReference) var).getParameters()) {\n collectVariablesForPsiElement(method, collectedTypes, psiElement);\n }\n }\n } else if (var instanceof BinaryExpression && var.getNode().getElementType() == PhpElementTypes.ADDITIVE_EXPRESSION) {\n PsiElement leftOperand = ((BinaryExpression) var).getLeftOperand();\n if (leftOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, leftOperand);\n }\n PsiElement rightOperand = ((BinaryExpression) var).getRightOperand();\n if (rightOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, rightOperand);\n }\n } else if (var instanceof SelfAssignmentExpression) {\n PhpPsiElement variable = ((SelfAssignmentExpression) var).getVariable();\n if (variable != null) {\n collectVariablesForPsiElement(method, collectedTypes, variable);\n }\n PhpPsiElement value = ((SelfAssignmentExpression) var).getValue();\n if (value != null) {\n collectVariablesForPsiElement(method, collectedTypes, value);\n }\n }\n }\n return collectedTypes;\n }\n\n private static void collectVariablesForPsiElement(@NotNull Function method, @NotNull Map collectedTypes, @NotNull PsiElement psiElement) {\n if (psiElement instanceof ArrayCreationExpression) {\n // reuse array collector: ['foobar' => $var]\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) psiElement));\n } else if (psiElement instanceof Variable) {\n // reuse variable collector: [$var]\n PsiElement resolvedVariable = ((Variable) psiElement).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n }\n }\n\n /**\n * search for variables which are possible accessible inside rendered twig template\n */\n @NotNull\n private static List collectPossibleTemplateArrays(@NotNull Function method) {\n List collectedTemplateVariables = new ArrayList<>();\n // Annotation controller\n // @TODO: check for phpdoc tag\n for (PhpReturn phpReturn : PsiTreeUtil.findChildrenOfType(method, PhpReturn.class)) {\n PhpPsiElement returnPsiElement = phpReturn.getFirstPsiChild();\n // @TODO: think of support all types here\n if (returnPsiElement instanceof Variable || returnPsiElement instanceof ArrayCreationExpression) {\n collectedTemplateVariables.add(returnPsiElement);\n }\n }\n // twig render calls:\n Set references = new HashSet<>();\n visitRenderTemplateFunctions(method, triple -> {\n FunctionReference functionScope = triple.getThird();\n if (functionScope != null) {\n references.add(functionScope);\n }\n });\n for (FunctionReference methodReference : references) {\n PsiElement templateParameter = PsiElementUtils.getMethodParameterPsiElementAt((methodReference).getParameterList(), 1);\n if (templateParameter != null) {\n collectedTemplateVariables.add(templateParameter);\n }\n }\n return collectedTemplateVariables;\n }\n\n /**\n * search for references of variable declaration and collect the types\n *\n * @param function should be function / method scope\n * @param variable the variable declaration psi $var = array();\n */\n @NotNull\n private static Map collectOnVariableReferences(@NotNull Function function, @NotNull Variable variable) {\n Map collectedTypes = new HashMap<>();\n for (Variable scopeVar : PhpElementsUtil.getVariablesInScope(function, variable)) {\n PsiElement parent = scopeVar.getParent();\n if (parent instanceof ArrayAccessExpression) {\n Pair pair = getTypesOnArrayIndex((ArrayAccessExpression) parent);\n if (pair != null) {\n collectedTypes.put(pair.getFirst(), pair.getSecond());\n }\n } else if (parent instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parent).getValue();\n if (value instanceof ArrayCreationExpression) {\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) value));\n }\n }\n }\n return collectedTypes;\n }\n\n @Nullable\n private static Pair getTypesOnArrayIndex(@NotNull ArrayAccessExpression arrayAccessExpression) {\n ArrayIndex arrayIndex = arrayAccessExpression.getIndex();\n if (arrayIndex != null && arrayIndex.getValue() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayIndex.getValue()).getContents();\n Set variableTypes = new HashSet<>();\n PsiElement parent = arrayAccessExpression.getParent();\n if (parent instanceof AssignmentExpression) {\n PsiElement arrayValue = ((AssignmentExpression) parent).getValue();\n if (arrayValue instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayValue).getType().getTypes());\n }\n return Pair.create(variableName, new PsiVariable(variableTypes, ((AssignmentExpression) parent).getValue()));\n } else {\n return Pair.create(variableName, new PsiVariable(variableTypes));\n }\n }\n return null;\n }\n\n public static Map getTypesOnArrayHash(@NotNull ArrayCreationExpression arrayCreationExpression) {\n Map collectedTypes = new HashMap<>();\n for (ArrayHashElement arrayHashElement : arrayCreationExpression.getHashElements()) {\n if (arrayHashElement.getKey() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayHashElement.getKey()).getContents();\n Set variableTypes = new HashSet<>();\n if (arrayHashElement.getValue() instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayHashElement.getValue()).getType().getTypes());\n }\n collectedTypes.put(variableName, new PsiVariable(variableTypes, arrayHashElement.getValue()));\n }\n }\n return collectedTypes;\n }\n\n /**\n * Visit method scope for template renders, also via annotation of the method itself\n *\n * As annotations are not in scope of the method itself\n */\n public static void visitRenderTemplateFunctions(@NotNull Method method, @NotNull Consumer> consumer) {\n TemplateRenderPsiRecursiveElementWalkingVisitor psiElementVisitor = new TemplateRenderPsiRecursiveElementWalkingVisitor(method, consumer);\n PhpDocComment docComment = method.getDocComment();\n for (PhpDocTag phpDocTag : PsiTreeUtil.getChildrenOfTypeAsList(docComment, PhpDocTag.class)) {\n psiElementVisitor.visitPhpDocTag(phpDocTag);\n }\n method.accept(psiElementVisitor);\n }\n\n /**\n * Visit all possible elements for render clements, scope shop be the class or a file itself\n */\n public static void visitRenderTemplateFunctions(@NotNull PsiElement context, @NotNull Consumer> consumer) {\n context.accept(new TemplateRenderPsiRecursiveElementWalkingVisitor(context, consumer));\n }\n\n private static class TemplateRenderPsiRecursiveElementWalkingVisitor extends PsiRecursiveElementWalkingVisitor {\n\n private final PsiElement context;\n\n private final Consumer> consumer;\n\n private Set methods;\n\n TemplateRenderPsiRecursiveElementWalkingVisitor(PsiElement context, Consumer> consumer) {\n this.context = context;\n this.consumer = consumer;\n methods = null;\n }\n\n @Override\n public void visitElement(PsiElement element) {\n if (element instanceof MethodReference) {\n visitMethodReference((MethodReference) element);\n } else if (element instanceof PhpDocTag) {\n visitPhpDocTag((PhpDocTag) element);\n }\n super.visitElement(element);\n }\n\n private void visitMethodReference(@NotNull MethodReference methodReference) {\n String methodName = methodReference.getName();\n // init methods once per file\n if (methods == null) {\n methods = new HashSet<>();\n methods.addAll(RENDER_METHODS);\n PluginConfigurationExtension[] extensions = Symfony2ProjectComponent.PLUGIN_CONFIGURATION_EXTENSION.getExtensions();\n if (extensions.length > 0) {\n PluginConfigurationExtensionParameter pluginConfiguration = new PluginConfigurationExtensionParameter(context.getProject());\n for (PluginConfigurationExtension extension : extensions) {\n extension.invokePluginConfiguration(pluginConfiguration);\n }\n methods.addAll(pluginConfiguration.getTemplateUsageMethod());\n }\n }\n if (!methods.contains(methodName)) {\n return;\n }\n PsiElement[] parameters = methodReference.getParameters();\n if (parameters.length == 0) {\n return;\n }\n if (parameters[0] instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) parameters[0]);\n } else if (parameters[0] instanceof TernaryExpression) {\n for (PhpPsiElement phpPsiElement : new PhpPsiElement[] { ((TernaryExpression) parameters[0]).getTrueVariant(), ((TernaryExpression) parameters[0]).getFalseVariant() }) {\n if (phpPsiElement == null) {\n continue;\n }\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n } else if (parameters[0] instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parameters[0]).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n } else if (parameters[0] instanceof PhpReference) {\n resolvePhpReference(methodReference, parameters[0]);\n } else if (parameters[0] instanceof BinaryExpression) {\n PsiElement phpPsiElement = ((BinaryExpression) parameters[0]).getRightOperand();\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n }\n\n private void resolvePhpReference(@NotNull MethodReference methodReference, PsiElement parameter) {\n for (PhpNamedElement phpNamedElement : ((PhpReference) parameter).resolveLocal()) {\n if (phpNamedElement instanceof Field) {\n PsiElement defaultValue = ((Field) phpNamedElement).getDefaultValue();\n if (defaultValue instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) defaultValue);\n }\n } else if (phpNamedElement instanceof Variable) {\n PsiElement assignmentExpression = phpNamedElement.getParent();\n if (assignmentExpression instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) assignmentExpression).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n } else if (phpNamedElement instanceof Parameter) {\n PsiElement value = ((Parameter) phpNamedElement).getDefaultValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n }\n }\n\n private void addStringLiteralScope(@NotNull MethodReference methodReference, @NotNull StringLiteralExpression defaultValue) {\n String contents = defaultValue.getContents();\n if (StringUtils.isBlank(contents) || !contents.endsWith(\".twig\")) {\n return;\n }\n Function parentOfType = PsiTreeUtil.getParentOfType(methodReference, Function.class);\n if (parentOfType == null) {\n return;\n }\n addTemplateWithScope(contents, parentOfType, methodReference);\n }\n\n private void visitPhpDocTag(@NotNull PhpDocTag phpDocTag) {", "post_mask_code": "\n Map fileImports = AnnotationBackportUtil.getUseImportMap(phpDocTag);\n if (fileImports.size() == 0) {\n return;\n }\n String annotationFqnName = AnnotationBackportUtil.getClassNameReference(phpDocTag, fileImports);\n if (!StringUtils.stripStart(TwigUtil.TEMPLATE_ANNOTATION_CLASS, \"\\\\\").equals(StringUtils.stripStart(annotationFqnName, \"\\\\\"))) {\n return;\n }\n String template = AnnotationUtil.getPropertyValueOrDefault(phpDocTag, \"template\");\n if (template == null) {\n // see \\Sensio\\Bundle\\FrameworkExtraBundle\\Templating\\TemplateGuesser\n // App\\Controller\\MyNiceController::myAction => my_nice/my.html.twig\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n PhpClass phpClass = methodScope.getContainingClass();\n if (phpClass != null) {\n // App\\Controller\\ \"MyNice\" Controller\n Matcher matcher = Pattern.compile(\"Controller\\\\\\\\(.+)Controller$\", Pattern.MULTILINE).matcher(StringUtils.stripStart(phpClass.getFQN(), \"\\\\\"));\n if (matcher.find()) {\n String group = underscore(matcher.group(1).replace(\"\\\\\", \"/\"));\n String name = methodScope.getName();\n // __invoke is using controller as template name\n if (name.equals(\"__invoke\")) {\n addTemplateWithScope(group + \".html.twig\", methodScope, null);\n } else {\n String action = name.endsWith(\"Action\") ? name.substring(0, name.length() - \"Action\".length()) : name;\n addTemplateWithScope(group + \"/\" + underscore(action) + \".html.twig\", methodScope, null);\n }\n }\n }\n }\n } else if (template.endsWith(\".twig\")) {\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n addTemplateWithScope(template, methodScope, null);\n }\n }\n }\n\n private void addTemplateWithScope(@NotNull String contents, @NotNull PhpNamedElement scope, @Nullable FunctionReference functionReference) {\n String s = TwigUtil.normalizeTemplateName(contents);\n consumer.accept(new Triple<>(s, scope, functionReference));\n }\n }\n}\n"} {"task_id": "Java_1410", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Haehnchen/idea-php-symfony2-plugin/src/main/java/fr/adrienbrault/idea/symfony2plugin/templating/util/PhpMethodVariableResolveUtil.java", "mask_start_position": 18150, "mask_end_position": 18424, "canonical_solution": "Map fileImports = AnnotationBackportUtil.getUseImportMap(phpDocTag);\n if (fileImports.size() == 0) {\n return;\n }\n String annotationFqnName = AnnotationBackportUtil.getClassNameReference(phpDocTag, fileImports);", "pre_mask_code": "package fr.adrienbrault.idea.symfony2plugin.templating.util;\n\nimport com.intellij.openapi.util.Pair;\nimport com.intellij.psi.PsiElement;\nimport com.intellij.psi.PsiRecursiveElementWalkingVisitor;\nimport com.intellij.psi.util.PsiTreeUtil;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;\nimport com.jetbrains.php.lang.parser.PhpElementTypes;\nimport com.jetbrains.php.lang.psi.elements.*;\nimport de.espend.idea.php.annotation.util.AnnotationUtil;\nimport fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtension;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtensionParameter;\nimport fr.adrienbrault.idea.symfony2plugin.templating.variable.dict.PsiVariable;\nimport fr.adrienbrault.idea.symfony2plugin.util.AnnotationBackportUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;\nimport kotlin.Triple;\nimport org.apache.commons.lang.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\nimport java.util.*;\nimport java.util.function.Consumer;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport static fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore;\n\n/**\n * @author Daniel Espendiller \n */\npublic class PhpMethodVariableResolveUtil {\n\n private static Set RENDER_METHODS = new HashSet() {\n\n {\n add(\"render\");\n add(\"renderView\");\n add(\"renderResponse\");\n }\n };\n\n /**\n * search for twig template variable on common use cases\n *\n * $this->render('foobar.html.twig', $foobar)\n * $this->render('foobar.html.twig', ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge_recursive($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_push($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_replace($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', $foobar + ['foobar' => $var])\n * $this->render('foobar.html.twig', $foobar += ['foobar' => $var])\n */\n public static Map collectMethodVariables(@NotNull Function method) {\n Map collectedTypes = new HashMap<>();\n for (PsiElement var : collectPossibleTemplateArrays(method)) {\n if (var instanceof ArrayCreationExpression) {\n // \"return array(...)\" we dont need any parsing\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) var));\n } else if (var instanceof Variable) {\n // we need variable declaration line so resolve it and search for references which attach other values to array\n // find definition and search for references on it\n PsiElement resolvedVariable = ((Variable) var).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n } else if (var instanceof FunctionReference && \"array_merge\".equalsIgnoreCase(((FunctionReference) var).getName())) {\n String name = ((FunctionReference) var).getName();\n if (\"array_merge\".equalsIgnoreCase(name) || \"array_merge_recursive\".equalsIgnoreCase(name) || \"array_push\".equalsIgnoreCase(name) || \"array_replace\".equalsIgnoreCase(name)) {\n for (PsiElement psiElement : ((FunctionReference) var).getParameters()) {\n collectVariablesForPsiElement(method, collectedTypes, psiElement);\n }\n }\n } else if (var instanceof BinaryExpression && var.getNode().getElementType() == PhpElementTypes.ADDITIVE_EXPRESSION) {\n PsiElement leftOperand = ((BinaryExpression) var).getLeftOperand();\n if (leftOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, leftOperand);\n }\n PsiElement rightOperand = ((BinaryExpression) var).getRightOperand();\n if (rightOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, rightOperand);\n }\n } else if (var instanceof SelfAssignmentExpression) {\n PhpPsiElement variable = ((SelfAssignmentExpression) var).getVariable();\n if (variable != null) {\n collectVariablesForPsiElement(method, collectedTypes, variable);\n }\n PhpPsiElement value = ((SelfAssignmentExpression) var).getValue();\n if (value != null) {\n collectVariablesForPsiElement(method, collectedTypes, value);\n }\n }\n }\n return collectedTypes;\n }\n\n private static void collectVariablesForPsiElement(@NotNull Function method, @NotNull Map collectedTypes, @NotNull PsiElement psiElement) {\n if (psiElement instanceof ArrayCreationExpression) {\n // reuse array collector: ['foobar' => $var]\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) psiElement));\n } else if (psiElement instanceof Variable) {\n // reuse variable collector: [$var]\n PsiElement resolvedVariable = ((Variable) psiElement).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n }\n }\n\n /**\n * search for variables which are possible accessible inside rendered twig template\n */\n @NotNull\n private static List collectPossibleTemplateArrays(@NotNull Function method) {\n List collectedTemplateVariables = new ArrayList<>();\n // Annotation controller\n // @TODO: check for phpdoc tag\n for (PhpReturn phpReturn : PsiTreeUtil.findChildrenOfType(method, PhpReturn.class)) {\n PhpPsiElement returnPsiElement = phpReturn.getFirstPsiChild();\n // @TODO: think of support all types here\n if (returnPsiElement instanceof Variable || returnPsiElement instanceof ArrayCreationExpression) {\n collectedTemplateVariables.add(returnPsiElement);\n }\n }\n // twig render calls:\n Set references = new HashSet<>();\n visitRenderTemplateFunctions(method, triple -> {\n FunctionReference functionScope = triple.getThird();\n if (functionScope != null) {\n references.add(functionScope);\n }\n });\n for (FunctionReference methodReference : references) {\n PsiElement templateParameter = PsiElementUtils.getMethodParameterPsiElementAt((methodReference).getParameterList(), 1);\n if (templateParameter != null) {\n collectedTemplateVariables.add(templateParameter);\n }\n }\n return collectedTemplateVariables;\n }\n\n /**\n * search for references of variable declaration and collect the types\n *\n * @param function should be function / method scope\n * @param variable the variable declaration psi $var = array();\n */\n @NotNull\n private static Map collectOnVariableReferences(@NotNull Function function, @NotNull Variable variable) {\n Map collectedTypes = new HashMap<>();\n for (Variable scopeVar : PhpElementsUtil.getVariablesInScope(function, variable)) {\n PsiElement parent = scopeVar.getParent();\n if (parent instanceof ArrayAccessExpression) {\n Pair pair = getTypesOnArrayIndex((ArrayAccessExpression) parent);\n if (pair != null) {\n collectedTypes.put(pair.getFirst(), pair.getSecond());\n }\n } else if (parent instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parent).getValue();\n if (value instanceof ArrayCreationExpression) {\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) value));\n }\n }\n }\n return collectedTypes;\n }\n\n @Nullable\n private static Pair getTypesOnArrayIndex(@NotNull ArrayAccessExpression arrayAccessExpression) {\n ArrayIndex arrayIndex = arrayAccessExpression.getIndex();\n if (arrayIndex != null && arrayIndex.getValue() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayIndex.getValue()).getContents();\n Set variableTypes = new HashSet<>();\n PsiElement parent = arrayAccessExpression.getParent();\n if (parent instanceof AssignmentExpression) {\n PsiElement arrayValue = ((AssignmentExpression) parent).getValue();\n if (arrayValue instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayValue).getType().getTypes());\n }\n return Pair.create(variableName, new PsiVariable(variableTypes, ((AssignmentExpression) parent).getValue()));\n } else {\n return Pair.create(variableName, new PsiVariable(variableTypes));\n }\n }\n return null;\n }\n\n public static Map getTypesOnArrayHash(@NotNull ArrayCreationExpression arrayCreationExpression) {\n Map collectedTypes = new HashMap<>();\n for (ArrayHashElement arrayHashElement : arrayCreationExpression.getHashElements()) {\n if (arrayHashElement.getKey() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayHashElement.getKey()).getContents();\n Set variableTypes = new HashSet<>();\n if (arrayHashElement.getValue() instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayHashElement.getValue()).getType().getTypes());\n }\n collectedTypes.put(variableName, new PsiVariable(variableTypes, arrayHashElement.getValue()));\n }\n }\n return collectedTypes;\n }\n\n /**\n * Visit method scope for template renders, also via annotation of the method itself\n *\n * As annotations are not in scope of the method itself\n */\n public static void visitRenderTemplateFunctions(@NotNull Method method, @NotNull Consumer> consumer) {\n TemplateRenderPsiRecursiveElementWalkingVisitor psiElementVisitor = new TemplateRenderPsiRecursiveElementWalkingVisitor(method, consumer);\n PhpDocComment docComment = method.getDocComment();\n for (PhpDocTag phpDocTag : PsiTreeUtil.getChildrenOfTypeAsList(docComment, PhpDocTag.class)) {\n psiElementVisitor.visitPhpDocTag(phpDocTag);\n }\n method.accept(psiElementVisitor);\n }\n\n /**\n * Visit all possible elements for render clements, scope shop be the class or a file itself\n */\n public static void visitRenderTemplateFunctions(@NotNull PsiElement context, @NotNull Consumer> consumer) {\n context.accept(new TemplateRenderPsiRecursiveElementWalkingVisitor(context, consumer));\n }\n\n private static class TemplateRenderPsiRecursiveElementWalkingVisitor extends PsiRecursiveElementWalkingVisitor {\n\n private final PsiElement context;\n\n private final Consumer> consumer;\n\n private Set methods;\n\n TemplateRenderPsiRecursiveElementWalkingVisitor(PsiElement context, Consumer> consumer) {\n this.context = context;\n this.consumer = consumer;\n methods = null;\n }\n\n @Override\n public void visitElement(PsiElement element) {\n if (element instanceof MethodReference) {\n visitMethodReference((MethodReference) element);\n } else if (element instanceof PhpDocTag) {\n visitPhpDocTag((PhpDocTag) element);\n }\n super.visitElement(element);\n }\n\n private void visitMethodReference(@NotNull MethodReference methodReference) {\n String methodName = methodReference.getName();\n // init methods once per file\n if (methods == null) {\n methods = new HashSet<>();\n methods.addAll(RENDER_METHODS);\n PluginConfigurationExtension[] extensions = Symfony2ProjectComponent.PLUGIN_CONFIGURATION_EXTENSION.getExtensions();\n if (extensions.length > 0) {\n PluginConfigurationExtensionParameter pluginConfiguration = new PluginConfigurationExtensionParameter(context.getProject());\n for (PluginConfigurationExtension extension : extensions) {\n extension.invokePluginConfiguration(pluginConfiguration);\n }\n methods.addAll(pluginConfiguration.getTemplateUsageMethod());\n }\n }\n if (!methods.contains(methodName)) {\n return;\n }\n PsiElement[] parameters = methodReference.getParameters();\n if (parameters.length == 0) {\n return;\n }\n if (parameters[0] instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) parameters[0]);\n } else if (parameters[0] instanceof TernaryExpression) {\n for (PhpPsiElement phpPsiElement : new PhpPsiElement[] { ((TernaryExpression) parameters[0]).getTrueVariant(), ((TernaryExpression) parameters[0]).getFalseVariant() }) {\n if (phpPsiElement == null) {\n continue;\n }\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n } else if (parameters[0] instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parameters[0]).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n } else if (parameters[0] instanceof PhpReference) {\n resolvePhpReference(methodReference, parameters[0]);\n } else if (parameters[0] instanceof BinaryExpression) {\n PsiElement phpPsiElement = ((BinaryExpression) parameters[0]).getRightOperand();\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n }\n\n private void resolvePhpReference(@NotNull MethodReference methodReference, PsiElement parameter) {\n for (PhpNamedElement phpNamedElement : ((PhpReference) parameter).resolveLocal()) {\n if (phpNamedElement instanceof Field) {\n PsiElement defaultValue = ((Field) phpNamedElement).getDefaultValue();\n if (defaultValue instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) defaultValue);\n }\n } else if (phpNamedElement instanceof Variable) {\n PsiElement assignmentExpression = phpNamedElement.getParent();\n if (assignmentExpression instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) assignmentExpression).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n } else if (phpNamedElement instanceof Parameter) {\n PsiElement value = ((Parameter) phpNamedElement).getDefaultValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n }\n }\n\n private void addStringLiteralScope(@NotNull MethodReference methodReference, @NotNull StringLiteralExpression defaultValue) {\n String contents = defaultValue.getContents();\n if (StringUtils.isBlank(contents) || !contents.endsWith(\".twig\")) {\n return;\n }\n Function parentOfType = PsiTreeUtil.getParentOfType(methodReference, Function.class);\n if (parentOfType == null) {\n return;\n }\n addTemplateWithScope(contents, parentOfType, methodReference);\n }\n\n private void visitPhpDocTag(@NotNull PhpDocTag phpDocTag) {\n // \"@var\" and user non related tags dont need an action\n if (AnnotationBackportUtil.NON_ANNOTATION_TAGS.contains(phpDocTag.getName())) {\n return;\n }\n // init scope imports\n ", "post_mask_code": "\n if (!StringUtils.stripStart(TwigUtil.TEMPLATE_ANNOTATION_CLASS, \"\\\\\").equals(StringUtils.stripStart(annotationFqnName, \"\\\\\"))) {\n return;\n }\n String template = AnnotationUtil.getPropertyValueOrDefault(phpDocTag, \"template\");\n if (template == null) {\n // see \\Sensio\\Bundle\\FrameworkExtraBundle\\Templating\\TemplateGuesser\n // App\\Controller\\MyNiceController::myAction => my_nice/my.html.twig\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n PhpClass phpClass = methodScope.getContainingClass();\n if (phpClass != null) {\n // App\\Controller\\ \"MyNice\" Controller\n Matcher matcher = Pattern.compile(\"Controller\\\\\\\\(.+)Controller$\", Pattern.MULTILINE).matcher(StringUtils.stripStart(phpClass.getFQN(), \"\\\\\"));\n if (matcher.find()) {\n String group = underscore(matcher.group(1).replace(\"\\\\\", \"/\"));\n String name = methodScope.getName();\n // __invoke is using controller as template name\n if (name.equals(\"__invoke\")) {\n addTemplateWithScope(group + \".html.twig\", methodScope, null);\n } else {\n String action = name.endsWith(\"Action\") ? name.substring(0, name.length() - \"Action\".length()) : name;\n addTemplateWithScope(group + \"/\" + underscore(action) + \".html.twig\", methodScope, null);\n }\n }\n }\n }\n } else if (template.endsWith(\".twig\")) {\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n addTemplateWithScope(template, methodScope, null);\n }\n }\n }\n\n private void addTemplateWithScope(@NotNull String contents, @NotNull PhpNamedElement scope, @Nullable FunctionReference functionReference) {\n String s = TwigUtil.normalizeTemplateName(contents);\n consumer.accept(new Triple<>(s, scope, functionReference));\n }\n }\n}\n"} {"task_id": "Java_1411", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Haehnchen/idea-php-symfony2-plugin/src/main/java/fr/adrienbrault/idea/symfony2plugin/templating/util/PhpMethodVariableResolveUtil.java", "mask_start_position": 18437, "mask_end_position": 20506, "canonical_solution": "if (!StringUtils.stripStart(TwigUtil.TEMPLATE_ANNOTATION_CLASS, \"\\\\\").equals(StringUtils.stripStart(annotationFqnName, \"\\\\\"))) {\n return;\n }\n String template = AnnotationUtil.getPropertyValueOrDefault(phpDocTag, \"template\");\n if (template == null) {\n // see \\Sensio\\Bundle\\FrameworkExtraBundle\\Templating\\TemplateGuesser\n // App\\Controller\\MyNiceController::myAction => my_nice/my.html.twig\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n PhpClass phpClass = methodScope.getContainingClass();\n if (phpClass != null) {\n // App\\Controller\\ \"MyNice\" Controller\n Matcher matcher = Pattern.compile(\"Controller\\\\\\\\(.+)Controller$\", Pattern.MULTILINE).matcher(StringUtils.stripStart(phpClass.getFQN(), \"\\\\\"));\n if (matcher.find()) {\n String group = underscore(matcher.group(1).replace(\"\\\\\", \"/\"));\n String name = methodScope.getName();\n // __invoke is using controller as template name\n if (name.equals(\"__invoke\")) {\n addTemplateWithScope(group + \".html.twig\", methodScope, null);\n } else {\n String action = name.endsWith(\"Action\") ? name.substring(0, name.length() - \"Action\".length()) : name;\n addTemplateWithScope(group + \"/\" + underscore(action) + \".html.twig\", methodScope, null);\n }\n }\n }\n }\n } else if (template.endsWith(\".twig\")) {\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n addTemplateWithScope(template, methodScope, null);\n }\n }\n }", "pre_mask_code": "package fr.adrienbrault.idea.symfony2plugin.templating.util;\n\nimport com.intellij.openapi.util.Pair;\nimport com.intellij.psi.PsiElement;\nimport com.intellij.psi.PsiRecursiveElementWalkingVisitor;\nimport com.intellij.psi.util.PsiTreeUtil;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;\nimport com.jetbrains.php.lang.parser.PhpElementTypes;\nimport com.jetbrains.php.lang.psi.elements.*;\nimport de.espend.idea.php.annotation.util.AnnotationUtil;\nimport fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtension;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtensionParameter;\nimport fr.adrienbrault.idea.symfony2plugin.templating.variable.dict.PsiVariable;\nimport fr.adrienbrault.idea.symfony2plugin.util.AnnotationBackportUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;\nimport kotlin.Triple;\nimport org.apache.commons.lang.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\nimport java.util.*;\nimport java.util.function.Consumer;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport static fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore;\n\n/**\n * @author Daniel Espendiller \n */\npublic class PhpMethodVariableResolveUtil {\n\n private static Set RENDER_METHODS = new HashSet() {\n\n {\n add(\"render\");\n add(\"renderView\");\n add(\"renderResponse\");\n }\n };\n\n /**\n * search for twig template variable on common use cases\n *\n * $this->render('foobar.html.twig', $foobar)\n * $this->render('foobar.html.twig', ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge_recursive($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_push($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_replace($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', $foobar + ['foobar' => $var])\n * $this->render('foobar.html.twig', $foobar += ['foobar' => $var])\n */\n public static Map collectMethodVariables(@NotNull Function method) {\n Map collectedTypes = new HashMap<>();\n for (PsiElement var : collectPossibleTemplateArrays(method)) {\n if (var instanceof ArrayCreationExpression) {\n // \"return array(...)\" we dont need any parsing\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) var));\n } else if (var instanceof Variable) {\n // we need variable declaration line so resolve it and search for references which attach other values to array\n // find definition and search for references on it\n PsiElement resolvedVariable = ((Variable) var).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n } else if (var instanceof FunctionReference && \"array_merge\".equalsIgnoreCase(((FunctionReference) var).getName())) {\n String name = ((FunctionReference) var).getName();\n if (\"array_merge\".equalsIgnoreCase(name) || \"array_merge_recursive\".equalsIgnoreCase(name) || \"array_push\".equalsIgnoreCase(name) || \"array_replace\".equalsIgnoreCase(name)) {\n for (PsiElement psiElement : ((FunctionReference) var).getParameters()) {\n collectVariablesForPsiElement(method, collectedTypes, psiElement);\n }\n }\n } else if (var instanceof BinaryExpression && var.getNode().getElementType() == PhpElementTypes.ADDITIVE_EXPRESSION) {\n PsiElement leftOperand = ((BinaryExpression) var).getLeftOperand();\n if (leftOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, leftOperand);\n }\n PsiElement rightOperand = ((BinaryExpression) var).getRightOperand();\n if (rightOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, rightOperand);\n }\n } else if (var instanceof SelfAssignmentExpression) {\n PhpPsiElement variable = ((SelfAssignmentExpression) var).getVariable();\n if (variable != null) {\n collectVariablesForPsiElement(method, collectedTypes, variable);\n }\n PhpPsiElement value = ((SelfAssignmentExpression) var).getValue();\n if (value != null) {\n collectVariablesForPsiElement(method, collectedTypes, value);\n }\n }\n }\n return collectedTypes;\n }\n\n private static void collectVariablesForPsiElement(@NotNull Function method, @NotNull Map collectedTypes, @NotNull PsiElement psiElement) {\n if (psiElement instanceof ArrayCreationExpression) {\n // reuse array collector: ['foobar' => $var]\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) psiElement));\n } else if (psiElement instanceof Variable) {\n // reuse variable collector: [$var]\n PsiElement resolvedVariable = ((Variable) psiElement).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n }\n }\n\n /**\n * search for variables which are possible accessible inside rendered twig template\n */\n @NotNull\n private static List collectPossibleTemplateArrays(@NotNull Function method) {\n List collectedTemplateVariables = new ArrayList<>();\n // Annotation controller\n // @TODO: check for phpdoc tag\n for (PhpReturn phpReturn : PsiTreeUtil.findChildrenOfType(method, PhpReturn.class)) {\n PhpPsiElement returnPsiElement = phpReturn.getFirstPsiChild();\n // @TODO: think of support all types here\n if (returnPsiElement instanceof Variable || returnPsiElement instanceof ArrayCreationExpression) {\n collectedTemplateVariables.add(returnPsiElement);\n }\n }\n // twig render calls:\n Set references = new HashSet<>();\n visitRenderTemplateFunctions(method, triple -> {\n FunctionReference functionScope = triple.getThird();\n if (functionScope != null) {\n references.add(functionScope);\n }\n });\n for (FunctionReference methodReference : references) {\n PsiElement templateParameter = PsiElementUtils.getMethodParameterPsiElementAt((methodReference).getParameterList(), 1);\n if (templateParameter != null) {\n collectedTemplateVariables.add(templateParameter);\n }\n }\n return collectedTemplateVariables;\n }\n\n /**\n * search for references of variable declaration and collect the types\n *\n * @param function should be function / method scope\n * @param variable the variable declaration psi $var = array();\n */\n @NotNull\n private static Map collectOnVariableReferences(@NotNull Function function, @NotNull Variable variable) {\n Map collectedTypes = new HashMap<>();\n for (Variable scopeVar : PhpElementsUtil.getVariablesInScope(function, variable)) {\n PsiElement parent = scopeVar.getParent();\n if (parent instanceof ArrayAccessExpression) {\n Pair pair = getTypesOnArrayIndex((ArrayAccessExpression) parent);\n if (pair != null) {\n collectedTypes.put(pair.getFirst(), pair.getSecond());\n }\n } else if (parent instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parent).getValue();\n if (value instanceof ArrayCreationExpression) {\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) value));\n }\n }\n }\n return collectedTypes;\n }\n\n @Nullable\n private static Pair getTypesOnArrayIndex(@NotNull ArrayAccessExpression arrayAccessExpression) {\n ArrayIndex arrayIndex = arrayAccessExpression.getIndex();\n if (arrayIndex != null && arrayIndex.getValue() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayIndex.getValue()).getContents();\n Set variableTypes = new HashSet<>();\n PsiElement parent = arrayAccessExpression.getParent();\n if (parent instanceof AssignmentExpression) {\n PsiElement arrayValue = ((AssignmentExpression) parent).getValue();\n if (arrayValue instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayValue).getType().getTypes());\n }\n return Pair.create(variableName, new PsiVariable(variableTypes, ((AssignmentExpression) parent).getValue()));\n } else {\n return Pair.create(variableName, new PsiVariable(variableTypes));\n }\n }\n return null;\n }\n\n public static Map getTypesOnArrayHash(@NotNull ArrayCreationExpression arrayCreationExpression) {\n Map collectedTypes = new HashMap<>();\n for (ArrayHashElement arrayHashElement : arrayCreationExpression.getHashElements()) {\n if (arrayHashElement.getKey() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayHashElement.getKey()).getContents();\n Set variableTypes = new HashSet<>();\n if (arrayHashElement.getValue() instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayHashElement.getValue()).getType().getTypes());\n }\n collectedTypes.put(variableName, new PsiVariable(variableTypes, arrayHashElement.getValue()));\n }\n }\n return collectedTypes;\n }\n\n /**\n * Visit method scope for template renders, also via annotation of the method itself\n *\n * As annotations are not in scope of the method itself\n */\n public static void visitRenderTemplateFunctions(@NotNull Method method, @NotNull Consumer> consumer) {\n TemplateRenderPsiRecursiveElementWalkingVisitor psiElementVisitor = new TemplateRenderPsiRecursiveElementWalkingVisitor(method, consumer);\n PhpDocComment docComment = method.getDocComment();\n for (PhpDocTag phpDocTag : PsiTreeUtil.getChildrenOfTypeAsList(docComment, PhpDocTag.class)) {\n psiElementVisitor.visitPhpDocTag(phpDocTag);\n }\n method.accept(psiElementVisitor);\n }\n\n /**\n * Visit all possible elements for render clements, scope shop be the class or a file itself\n */\n public static void visitRenderTemplateFunctions(@NotNull PsiElement context, @NotNull Consumer> consumer) {\n context.accept(new TemplateRenderPsiRecursiveElementWalkingVisitor(context, consumer));\n }\n\n private static class TemplateRenderPsiRecursiveElementWalkingVisitor extends PsiRecursiveElementWalkingVisitor {\n\n private final PsiElement context;\n\n private final Consumer> consumer;\n\n private Set methods;\n\n TemplateRenderPsiRecursiveElementWalkingVisitor(PsiElement context, Consumer> consumer) {\n this.context = context;\n this.consumer = consumer;\n methods = null;\n }\n\n @Override\n public void visitElement(PsiElement element) {\n if (element instanceof MethodReference) {\n visitMethodReference((MethodReference) element);\n } else if (element instanceof PhpDocTag) {\n visitPhpDocTag((PhpDocTag) element);\n }\n super.visitElement(element);\n }\n\n private void visitMethodReference(@NotNull MethodReference methodReference) {\n String methodName = methodReference.getName();\n // init methods once per file\n if (methods == null) {\n methods = new HashSet<>();\n methods.addAll(RENDER_METHODS);\n PluginConfigurationExtension[] extensions = Symfony2ProjectComponent.PLUGIN_CONFIGURATION_EXTENSION.getExtensions();\n if (extensions.length > 0) {\n PluginConfigurationExtensionParameter pluginConfiguration = new PluginConfigurationExtensionParameter(context.getProject());\n for (PluginConfigurationExtension extension : extensions) {\n extension.invokePluginConfiguration(pluginConfiguration);\n }\n methods.addAll(pluginConfiguration.getTemplateUsageMethod());\n }\n }\n if (!methods.contains(methodName)) {\n return;\n }\n PsiElement[] parameters = methodReference.getParameters();\n if (parameters.length == 0) {\n return;\n }\n if (parameters[0] instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) parameters[0]);\n } else if (parameters[0] instanceof TernaryExpression) {\n for (PhpPsiElement phpPsiElement : new PhpPsiElement[] { ((TernaryExpression) parameters[0]).getTrueVariant(), ((TernaryExpression) parameters[0]).getFalseVariant() }) {\n if (phpPsiElement == null) {\n continue;\n }\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n } else if (parameters[0] instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parameters[0]).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n } else if (parameters[0] instanceof PhpReference) {\n resolvePhpReference(methodReference, parameters[0]);\n } else if (parameters[0] instanceof BinaryExpression) {\n PsiElement phpPsiElement = ((BinaryExpression) parameters[0]).getRightOperand();\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n }\n\n private void resolvePhpReference(@NotNull MethodReference methodReference, PsiElement parameter) {\n for (PhpNamedElement phpNamedElement : ((PhpReference) parameter).resolveLocal()) {\n if (phpNamedElement instanceof Field) {\n PsiElement defaultValue = ((Field) phpNamedElement).getDefaultValue();\n if (defaultValue instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) defaultValue);\n }\n } else if (phpNamedElement instanceof Variable) {\n PsiElement assignmentExpression = phpNamedElement.getParent();\n if (assignmentExpression instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) assignmentExpression).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n } else if (phpNamedElement instanceof Parameter) {\n PsiElement value = ((Parameter) phpNamedElement).getDefaultValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n }\n }\n\n private void addStringLiteralScope(@NotNull MethodReference methodReference, @NotNull StringLiteralExpression defaultValue) {\n String contents = defaultValue.getContents();\n if (StringUtils.isBlank(contents) || !contents.endsWith(\".twig\")) {\n return;\n }\n Function parentOfType = PsiTreeUtil.getParentOfType(methodReference, Function.class);\n if (parentOfType == null) {\n return;\n }\n addTemplateWithScope(contents, parentOfType, methodReference);\n }\n\n private void visitPhpDocTag(@NotNull PhpDocTag phpDocTag) {\n // \"@var\" and user non related tags dont need an action\n if (AnnotationBackportUtil.NON_ANNOTATION_TAGS.contains(phpDocTag.getName())) {\n return;\n }\n // init scope imports\n Map fileImports = AnnotationBackportUtil.getUseImportMap(phpDocTag);\n if (fileImports.size() == 0) {\n return;\n }\n String annotationFqnName = AnnotationBackportUtil.getClassNameReference(phpDocTag, fileImports);\n ", "post_mask_code": "\n\n private void addTemplateWithScope(@NotNull String contents, @NotNull PhpNamedElement scope, @Nullable FunctionReference functionReference) {\n String s = TwigUtil.normalizeTemplateName(contents);\n consumer.accept(new Triple<>(s, scope, functionReference));\n }\n }\n}\n"} {"task_id": "Java_1412", "language": "Java", "task_type": "single_line", "source_file": "java/github/Haehnchen/idea-php-symfony2-plugin/src/main/java/fr/adrienbrault/idea/symfony2plugin/templating/util/PhpMethodVariableResolveUtil.java", "mask_start_position": 11734, "mask_end_position": 11789, "canonical_solution": "rPsiRecursiveElementWalkingVisitor(context, consumer));", "pre_mask_code": "package fr.adrienbrault.idea.symfony2plugin.templating.util;\n\nimport com.intellij.openapi.util.Pair;\nimport com.intellij.psi.PsiElement;\nimport com.intellij.psi.PsiRecursiveElementWalkingVisitor;\nimport com.intellij.psi.util.PsiTreeUtil;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;\nimport com.jetbrains.php.lang.parser.PhpElementTypes;\nimport com.jetbrains.php.lang.psi.elements.*;\nimport de.espend.idea.php.annotation.util.AnnotationUtil;\nimport fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtension;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtensionParameter;\nimport fr.adrienbrault.idea.symfony2plugin.templating.variable.dict.PsiVariable;\nimport fr.adrienbrault.idea.symfony2plugin.util.AnnotationBackportUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;\nimport kotlin.Triple;\nimport org.apache.commons.lang.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\nimport java.util.*;\nimport java.util.function.Consumer;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport static fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore;\n\n/**\n * @author Daniel Espendiller \n */\npublic class PhpMethodVariableResolveUtil {\n\n private static Set RENDER_METHODS = new HashSet() {\n\n {\n add(\"render\");\n add(\"renderView\");\n add(\"renderResponse\");\n }\n };\n\n /**\n * search for twig template variable on common use cases\n *\n * $this->render('foobar.html.twig', $foobar)\n * $this->render('foobar.html.twig', ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge_recursive($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_push($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_replace($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', $foobar + ['foobar' => $var])\n * $this->render('foobar.html.twig', $foobar += ['foobar' => $var])\n */\n public static Map collectMethodVariables(@NotNull Function method) {\n Map collectedTypes = new HashMap<>();\n for (PsiElement var : collectPossibleTemplateArrays(method)) {\n if (var instanceof ArrayCreationExpression) {\n // \"return array(...)\" we dont need any parsing\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) var));\n } else if (var instanceof Variable) {\n // we need variable declaration line so resolve it and search for references which attach other values to array\n // find definition and search for references on it\n PsiElement resolvedVariable = ((Variable) var).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n } else if (var instanceof FunctionReference && \"array_merge\".equalsIgnoreCase(((FunctionReference) var).getName())) {\n String name = ((FunctionReference) var).getName();\n if (\"array_merge\".equalsIgnoreCase(name) || \"array_merge_recursive\".equalsIgnoreCase(name) || \"array_push\".equalsIgnoreCase(name) || \"array_replace\".equalsIgnoreCase(name)) {\n for (PsiElement psiElement : ((FunctionReference) var).getParameters()) {\n collectVariablesForPsiElement(method, collectedTypes, psiElement);\n }\n }\n } else if (var instanceof BinaryExpression && var.getNode().getElementType() == PhpElementTypes.ADDITIVE_EXPRESSION) {\n PsiElement leftOperand = ((BinaryExpression) var).getLeftOperand();\n if (leftOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, leftOperand);\n }\n PsiElement rightOperand = ((BinaryExpression) var).getRightOperand();\n if (rightOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, rightOperand);\n }\n } else if (var instanceof SelfAssignmentExpression) {\n PhpPsiElement variable = ((SelfAssignmentExpression) var).getVariable();\n if (variable != null) {\n collectVariablesForPsiElement(method, collectedTypes, variable);\n }\n PhpPsiElement value = ((SelfAssignmentExpression) var).getValue();\n if (value != null) {\n collectVariablesForPsiElement(method, collectedTypes, value);\n }\n }\n }\n return collectedTypes;\n }\n\n private static void collectVariablesForPsiElement(@NotNull Function method, @NotNull Map collectedTypes, @NotNull PsiElement psiElement) {\n if (psiElement instanceof ArrayCreationExpression) {\n // reuse array collector: ['foobar' => $var]\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) psiElement));\n } else if (psiElement instanceof Variable) {\n // reuse variable collector: [$var]\n PsiElement resolvedVariable = ((Variable) psiElement).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n }\n }\n\n /**\n * search for variables which are possible accessible inside rendered twig template\n */\n @NotNull\n private static List collectPossibleTemplateArrays(@NotNull Function method) {\n List collectedTemplateVariables = new ArrayList<>();\n // Annotation controller\n // @TODO: check for phpdoc tag\n for (PhpReturn phpReturn : PsiTreeUtil.findChildrenOfType(method, PhpReturn.class)) {\n PhpPsiElement returnPsiElement = phpReturn.getFirstPsiChild();\n // @TODO: think of support all types here\n if (returnPsiElement instanceof Variable || returnPsiElement instanceof ArrayCreationExpression) {\n collectedTemplateVariables.add(returnPsiElement);\n }\n }\n // twig render calls:\n Set references = new HashSet<>();\n visitRenderTemplateFunctions(method, triple -> {\n FunctionReference functionScope = triple.getThird();\n if (functionScope != null) {\n references.add(functionScope);\n }\n });\n for (FunctionReference methodReference : references) {\n PsiElement templateParameter = PsiElementUtils.getMethodParameterPsiElementAt((methodReference).getParameterList(), 1);\n if (templateParameter != null) {\n collectedTemplateVariables.add(templateParameter);\n }\n }\n return collectedTemplateVariables;\n }\n\n /**\n * search for references of variable declaration and collect the types\n *\n * @param function should be function / method scope\n * @param variable the variable declaration psi $var = array();\n */\n @NotNull\n private static Map collectOnVariableReferences(@NotNull Function function, @NotNull Variable variable) {\n Map collectedTypes = new HashMap<>();\n for (Variable scopeVar : PhpElementsUtil.getVariablesInScope(function, variable)) {\n PsiElement parent = scopeVar.getParent();\n if (parent instanceof ArrayAccessExpression) {\n Pair pair = getTypesOnArrayIndex((ArrayAccessExpression) parent);\n if (pair != null) {\n collectedTypes.put(pair.getFirst(), pair.getSecond());\n }\n } else if (parent instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parent).getValue();\n if (value instanceof ArrayCreationExpression) {\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) value));\n }\n }\n }\n return collectedTypes;\n }\n\n @Nullable\n private static Pair getTypesOnArrayIndex(@NotNull ArrayAccessExpression arrayAccessExpression) {\n ArrayIndex arrayIndex = arrayAccessExpression.getIndex();\n if (arrayIndex != null && arrayIndex.getValue() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayIndex.getValue()).getContents();\n Set variableTypes = new HashSet<>();\n PsiElement parent = arrayAccessExpression.getParent();\n if (parent instanceof AssignmentExpression) {\n PsiElement arrayValue = ((AssignmentExpression) parent).getValue();\n if (arrayValue instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayValue).getType().getTypes());\n }\n return Pair.create(variableName, new PsiVariable(variableTypes, ((AssignmentExpression) parent).getValue()));\n } else {\n return Pair.create(variableName, new PsiVariable(variableTypes));\n }\n }\n return null;\n }\n\n public static Map getTypesOnArrayHash(@NotNull ArrayCreationExpression arrayCreationExpression) {\n Map collectedTypes = new HashMap<>();\n for (ArrayHashElement arrayHashElement : arrayCreationExpression.getHashElements()) {\n if (arrayHashElement.getKey() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayHashElement.getKey()).getContents();\n Set variableTypes = new HashSet<>();\n if (arrayHashElement.getValue() instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayHashElement.getValue()).getType().getTypes());\n }\n collectedTypes.put(variableName, new PsiVariable(variableTypes, arrayHashElement.getValue()));\n }\n }\n return collectedTypes;\n }\n\n /**\n * Visit method scope for template renders, also via annotation of the method itself\n *\n * As annotations are not in scope of the method itself\n */\n public static void visitRenderTemplateFunctions(@NotNull Method method, @NotNull Consumer> consumer) {\n TemplateRenderPsiRecursiveElementWalkingVisitor psiElementVisitor = new TemplateRenderPsiRecursiveElementWalkingVisitor(method, consumer);\n PhpDocComment docComment = method.getDocComment();\n for (PhpDocTag phpDocTag : PsiTreeUtil.getChildrenOfTypeAsList(docComment, PhpDocTag.class)) {\n psiElementVisitor.visitPhpDocTag(phpDocTag);\n }\n method.accept(psiElementVisitor);\n }\n\n /**\n * Visit all possible elements for render clements, scope shop be the class or a file itself\n */\n public static void visitRenderTemplateFunctions(@NotNull PsiElement context, @NotNull Consumer> consumer) {\n context.accept(new TemplateRende", "post_mask_code": "\n }\n\n private static class TemplateRenderPsiRecursiveElementWalkingVisitor extends PsiRecursiveElementWalkingVisitor {\n\n private final PsiElement context;\n\n private final Consumer> consumer;\n\n private Set methods;\n\n TemplateRenderPsiRecursiveElementWalkingVisitor(PsiElement context, Consumer> consumer) {\n this.context = context;\n this.consumer = consumer;\n methods = null;\n }\n\n @Override\n public void visitElement(PsiElement element) {\n if (element instanceof MethodReference) {\n visitMethodReference((MethodReference) element);\n } else if (element instanceof PhpDocTag) {\n visitPhpDocTag((PhpDocTag) element);\n }\n super.visitElement(element);\n }\n\n private void visitMethodReference(@NotNull MethodReference methodReference) {\n String methodName = methodReference.getName();\n // init methods once per file\n if (methods == null) {\n methods = new HashSet<>();\n methods.addAll(RENDER_METHODS);\n PluginConfigurationExtension[] extensions = Symfony2ProjectComponent.PLUGIN_CONFIGURATION_EXTENSION.getExtensions();\n if (extensions.length > 0) {\n PluginConfigurationExtensionParameter pluginConfiguration = new PluginConfigurationExtensionParameter(context.getProject());\n for (PluginConfigurationExtension extension : extensions) {\n extension.invokePluginConfiguration(pluginConfiguration);\n }\n methods.addAll(pluginConfiguration.getTemplateUsageMethod());\n }\n }\n if (!methods.contains(methodName)) {\n return;\n }\n PsiElement[] parameters = methodReference.getParameters();\n if (parameters.length == 0) {\n return;\n }\n if (parameters[0] instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) parameters[0]);\n } else if (parameters[0] instanceof TernaryExpression) {\n for (PhpPsiElement phpPsiElement : new PhpPsiElement[] { ((TernaryExpression) parameters[0]).getTrueVariant(), ((TernaryExpression) parameters[0]).getFalseVariant() }) {\n if (phpPsiElement == null) {\n continue;\n }\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n } else if (parameters[0] instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parameters[0]).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n } else if (parameters[0] instanceof PhpReference) {\n resolvePhpReference(methodReference, parameters[0]);\n } else if (parameters[0] instanceof BinaryExpression) {\n PsiElement phpPsiElement = ((BinaryExpression) parameters[0]).getRightOperand();\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n }\n\n private void resolvePhpReference(@NotNull MethodReference methodReference, PsiElement parameter) {\n for (PhpNamedElement phpNamedElement : ((PhpReference) parameter).resolveLocal()) {\n if (phpNamedElement instanceof Field) {\n PsiElement defaultValue = ((Field) phpNamedElement).getDefaultValue();\n if (defaultValue instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) defaultValue);\n }\n } else if (phpNamedElement instanceof Variable) {\n PsiElement assignmentExpression = phpNamedElement.getParent();\n if (assignmentExpression instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) assignmentExpression).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n } else if (phpNamedElement instanceof Parameter) {\n PsiElement value = ((Parameter) phpNamedElement).getDefaultValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n }\n }\n\n private void addStringLiteralScope(@NotNull MethodReference methodReference, @NotNull StringLiteralExpression defaultValue) {\n String contents = defaultValue.getContents();\n if (StringUtils.isBlank(contents) || !contents.endsWith(\".twig\")) {\n return;\n }\n Function parentOfType = PsiTreeUtil.getParentOfType(methodReference, Function.class);\n if (parentOfType == null) {\n return;\n }\n addTemplateWithScope(contents, parentOfType, methodReference);\n }\n\n private void visitPhpDocTag(@NotNull PhpDocTag phpDocTag) {\n // \"@var\" and user non related tags dont need an action\n if (AnnotationBackportUtil.NON_ANNOTATION_TAGS.contains(phpDocTag.getName())) {\n return;\n }\n // init scope imports\n Map fileImports = AnnotationBackportUtil.getUseImportMap(phpDocTag);\n if (fileImports.size() == 0) {\n return;\n }\n String annotationFqnName = AnnotationBackportUtil.getClassNameReference(phpDocTag, fileImports);\n if (!StringUtils.stripStart(TwigUtil.TEMPLATE_ANNOTATION_CLASS, \"\\\\\").equals(StringUtils.stripStart(annotationFqnName, \"\\\\\"))) {\n return;\n }\n String template = AnnotationUtil.getPropertyValueOrDefault(phpDocTag, \"template\");\n if (template == null) {\n // see \\Sensio\\Bundle\\FrameworkExtraBundle\\Templating\\TemplateGuesser\n // App\\Controller\\MyNiceController::myAction => my_nice/my.html.twig\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n PhpClass phpClass = methodScope.getContainingClass();\n if (phpClass != null) {\n // App\\Controller\\ \"MyNice\" Controller\n Matcher matcher = Pattern.compile(\"Controller\\\\\\\\(.+)Controller$\", Pattern.MULTILINE).matcher(StringUtils.stripStart(phpClass.getFQN(), \"\\\\\"));\n if (matcher.find()) {\n String group = underscore(matcher.group(1).replace(\"\\\\\", \"/\"));\n String name = methodScope.getName();\n // __invoke is using controller as template name\n if (name.equals(\"__invoke\")) {\n addTemplateWithScope(group + \".html.twig\", methodScope, null);\n } else {\n String action = name.endsWith(\"Action\") ? name.substring(0, name.length() - \"Action\".length()) : name;\n addTemplateWithScope(group + \"/\" + underscore(action) + \".html.twig\", methodScope, null);\n }\n }\n }\n }\n } else if (template.endsWith(\".twig\")) {\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n addTemplateWithScope(template, methodScope, null);\n }\n }\n }\n\n private void addTemplateWithScope(@NotNull String contents, @NotNull PhpNamedElement scope, @Nullable FunctionReference functionReference) {\n String s = TwigUtil.normalizeTemplateName(contents);\n consumer.accept(new Triple<>(s, scope, functionReference));\n }\n }\n}\n"} {"task_id": "Java_1413", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Haehnchen/idea-php-symfony2-plugin/src/main/java/fr/adrienbrault/idea/symfony2plugin/templating/util/PhpMethodVariableResolveUtil.java", "mask_start_position": 11535, "mask_end_position": 11795, "canonical_solution": "public static void visitRenderTemplateFunctions(@NotNull PsiElement context, @NotNull Consumer> consumer) {\n context.accept(new TemplateRenderPsiRecursiveElementWalkingVisitor(context, consumer));\n }", "pre_mask_code": "package fr.adrienbrault.idea.symfony2plugin.templating.util;\n\nimport com.intellij.openapi.util.Pair;\nimport com.intellij.psi.PsiElement;\nimport com.intellij.psi.PsiRecursiveElementWalkingVisitor;\nimport com.intellij.psi.util.PsiTreeUtil;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;\nimport com.jetbrains.php.lang.parser.PhpElementTypes;\nimport com.jetbrains.php.lang.psi.elements.*;\nimport de.espend.idea.php.annotation.util.AnnotationUtil;\nimport fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtension;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtensionParameter;\nimport fr.adrienbrault.idea.symfony2plugin.templating.variable.dict.PsiVariable;\nimport fr.adrienbrault.idea.symfony2plugin.util.AnnotationBackportUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;\nimport kotlin.Triple;\nimport org.apache.commons.lang.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\nimport java.util.*;\nimport java.util.function.Consumer;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport static fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore;\n\n/**\n * @author Daniel Espendiller \n */\npublic class PhpMethodVariableResolveUtil {\n\n private static Set RENDER_METHODS = new HashSet() {\n\n {\n add(\"render\");\n add(\"renderView\");\n add(\"renderResponse\");\n }\n };\n\n /**\n * search for twig template variable on common use cases\n *\n * $this->render('foobar.html.twig', $foobar)\n * $this->render('foobar.html.twig', ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge_recursive($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_push($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_replace($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', $foobar + ['foobar' => $var])\n * $this->render('foobar.html.twig', $foobar += ['foobar' => $var])\n */\n public static Map collectMethodVariables(@NotNull Function method) {\n Map collectedTypes = new HashMap<>();\n for (PsiElement var : collectPossibleTemplateArrays(method)) {\n if (var instanceof ArrayCreationExpression) {\n // \"return array(...)\" we dont need any parsing\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) var));\n } else if (var instanceof Variable) {\n // we need variable declaration line so resolve it and search for references which attach other values to array\n // find definition and search for references on it\n PsiElement resolvedVariable = ((Variable) var).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n } else if (var instanceof FunctionReference && \"array_merge\".equalsIgnoreCase(((FunctionReference) var).getName())) {\n String name = ((FunctionReference) var).getName();\n if (\"array_merge\".equalsIgnoreCase(name) || \"array_merge_recursive\".equalsIgnoreCase(name) || \"array_push\".equalsIgnoreCase(name) || \"array_replace\".equalsIgnoreCase(name)) {\n for (PsiElement psiElement : ((FunctionReference) var).getParameters()) {\n collectVariablesForPsiElement(method, collectedTypes, psiElement);\n }\n }\n } else if (var instanceof BinaryExpression && var.getNode().getElementType() == PhpElementTypes.ADDITIVE_EXPRESSION) {\n PsiElement leftOperand = ((BinaryExpression) var).getLeftOperand();\n if (leftOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, leftOperand);\n }\n PsiElement rightOperand = ((BinaryExpression) var).getRightOperand();\n if (rightOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, rightOperand);\n }\n } else if (var instanceof SelfAssignmentExpression) {\n PhpPsiElement variable = ((SelfAssignmentExpression) var).getVariable();\n if (variable != null) {\n collectVariablesForPsiElement(method, collectedTypes, variable);\n }\n PhpPsiElement value = ((SelfAssignmentExpression) var).getValue();\n if (value != null) {\n collectVariablesForPsiElement(method, collectedTypes, value);\n }\n }\n }\n return collectedTypes;\n }\n\n private static void collectVariablesForPsiElement(@NotNull Function method, @NotNull Map collectedTypes, @NotNull PsiElement psiElement) {\n if (psiElement instanceof ArrayCreationExpression) {\n // reuse array collector: ['foobar' => $var]\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) psiElement));\n } else if (psiElement instanceof Variable) {\n // reuse variable collector: [$var]\n PsiElement resolvedVariable = ((Variable) psiElement).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n }\n }\n\n /**\n * search for variables which are possible accessible inside rendered twig template\n */\n @NotNull\n private static List collectPossibleTemplateArrays(@NotNull Function method) {\n List collectedTemplateVariables = new ArrayList<>();\n // Annotation controller\n // @TODO: check for phpdoc tag\n for (PhpReturn phpReturn : PsiTreeUtil.findChildrenOfType(method, PhpReturn.class)) {\n PhpPsiElement returnPsiElement = phpReturn.getFirstPsiChild();\n // @TODO: think of support all types here\n if (returnPsiElement instanceof Variable || returnPsiElement instanceof ArrayCreationExpression) {\n collectedTemplateVariables.add(returnPsiElement);\n }\n }\n // twig render calls:\n Set references = new HashSet<>();\n visitRenderTemplateFunctions(method, triple -> {\n FunctionReference functionScope = triple.getThird();\n if (functionScope != null) {\n references.add(functionScope);\n }\n });\n for (FunctionReference methodReference : references) {\n PsiElement templateParameter = PsiElementUtils.getMethodParameterPsiElementAt((methodReference).getParameterList(), 1);\n if (templateParameter != null) {\n collectedTemplateVariables.add(templateParameter);\n }\n }\n return collectedTemplateVariables;\n }\n\n /**\n * search for references of variable declaration and collect the types\n *\n * @param function should be function / method scope\n * @param variable the variable declaration psi $var = array();\n */\n @NotNull\n private static Map collectOnVariableReferences(@NotNull Function function, @NotNull Variable variable) {\n Map collectedTypes = new HashMap<>();\n for (Variable scopeVar : PhpElementsUtil.getVariablesInScope(function, variable)) {\n PsiElement parent = scopeVar.getParent();\n if (parent instanceof ArrayAccessExpression) {\n Pair pair = getTypesOnArrayIndex((ArrayAccessExpression) parent);\n if (pair != null) {\n collectedTypes.put(pair.getFirst(), pair.getSecond());\n }\n } else if (parent instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parent).getValue();\n if (value instanceof ArrayCreationExpression) {\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) value));\n }\n }\n }\n return collectedTypes;\n }\n\n @Nullable\n private static Pair getTypesOnArrayIndex(@NotNull ArrayAccessExpression arrayAccessExpression) {\n ArrayIndex arrayIndex = arrayAccessExpression.getIndex();\n if (arrayIndex != null && arrayIndex.getValue() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayIndex.getValue()).getContents();\n Set variableTypes = new HashSet<>();\n PsiElement parent = arrayAccessExpression.getParent();\n if (parent instanceof AssignmentExpression) {\n PsiElement arrayValue = ((AssignmentExpression) parent).getValue();\n if (arrayValue instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayValue).getType().getTypes());\n }\n return Pair.create(variableName, new PsiVariable(variableTypes, ((AssignmentExpression) parent).getValue()));\n } else {\n return Pair.create(variableName, new PsiVariable(variableTypes));\n }\n }\n return null;\n }\n\n public static Map getTypesOnArrayHash(@NotNull ArrayCreationExpression arrayCreationExpression) {\n Map collectedTypes = new HashMap<>();\n for (ArrayHashElement arrayHashElement : arrayCreationExpression.getHashElements()) {\n if (arrayHashElement.getKey() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayHashElement.getKey()).getContents();\n Set variableTypes = new HashSet<>();\n if (arrayHashElement.getValue() instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayHashElement.getValue()).getType().getTypes());\n }\n collectedTypes.put(variableName, new PsiVariable(variableTypes, arrayHashElement.getValue()));\n }\n }\n return collectedTypes;\n }\n\n /**\n * Visit method scope for template renders, also via annotation of the method itself\n *\n * As annotations are not in scope of the method itself\n */\n public static void visitRenderTemplateFunctions(@NotNull Method method, @NotNull Consumer> consumer) {\n TemplateRenderPsiRecursiveElementWalkingVisitor psiElementVisitor = new TemplateRenderPsiRecursiveElementWalkingVisitor(method, consumer);\n PhpDocComment docComment = method.getDocComment();\n for (PhpDocTag phpDocTag : PsiTreeUtil.getChildrenOfTypeAsList(docComment, PhpDocTag.class)) {\n psiElementVisitor.visitPhpDocTag(phpDocTag);\n }\n method.accept(psiElementVisitor);\n }\n\n /**\n * Visit all possible elements for render clements, scope shop be the class or a file itself\n */\n ", "post_mask_code": "\n\n private static class TemplateRenderPsiRecursiveElementWalkingVisitor extends PsiRecursiveElementWalkingVisitor {\n\n private final PsiElement context;\n\n private final Consumer> consumer;\n\n private Set methods;\n\n TemplateRenderPsiRecursiveElementWalkingVisitor(PsiElement context, Consumer> consumer) {\n this.context = context;\n this.consumer = consumer;\n methods = null;\n }\n\n @Override\n public void visitElement(PsiElement element) {\n if (element instanceof MethodReference) {\n visitMethodReference((MethodReference) element);\n } else if (element instanceof PhpDocTag) {\n visitPhpDocTag((PhpDocTag) element);\n }\n super.visitElement(element);\n }\n\n private void visitMethodReference(@NotNull MethodReference methodReference) {\n String methodName = methodReference.getName();\n // init methods once per file\n if (methods == null) {\n methods = new HashSet<>();\n methods.addAll(RENDER_METHODS);\n PluginConfigurationExtension[] extensions = Symfony2ProjectComponent.PLUGIN_CONFIGURATION_EXTENSION.getExtensions();\n if (extensions.length > 0) {\n PluginConfigurationExtensionParameter pluginConfiguration = new PluginConfigurationExtensionParameter(context.getProject());\n for (PluginConfigurationExtension extension : extensions) {\n extension.invokePluginConfiguration(pluginConfiguration);\n }\n methods.addAll(pluginConfiguration.getTemplateUsageMethod());\n }\n }\n if (!methods.contains(methodName)) {\n return;\n }\n PsiElement[] parameters = methodReference.getParameters();\n if (parameters.length == 0) {\n return;\n }\n if (parameters[0] instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) parameters[0]);\n } else if (parameters[0] instanceof TernaryExpression) {\n for (PhpPsiElement phpPsiElement : new PhpPsiElement[] { ((TernaryExpression) parameters[0]).getTrueVariant(), ((TernaryExpression) parameters[0]).getFalseVariant() }) {\n if (phpPsiElement == null) {\n continue;\n }\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n } else if (parameters[0] instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parameters[0]).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n } else if (parameters[0] instanceof PhpReference) {\n resolvePhpReference(methodReference, parameters[0]);\n } else if (parameters[0] instanceof BinaryExpression) {\n PsiElement phpPsiElement = ((BinaryExpression) parameters[0]).getRightOperand();\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n }\n\n private void resolvePhpReference(@NotNull MethodReference methodReference, PsiElement parameter) {\n for (PhpNamedElement phpNamedElement : ((PhpReference) parameter).resolveLocal()) {\n if (phpNamedElement instanceof Field) {\n PsiElement defaultValue = ((Field) phpNamedElement).getDefaultValue();\n if (defaultValue instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) defaultValue);\n }\n } else if (phpNamedElement instanceof Variable) {\n PsiElement assignmentExpression = phpNamedElement.getParent();\n if (assignmentExpression instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) assignmentExpression).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n } else if (phpNamedElement instanceof Parameter) {\n PsiElement value = ((Parameter) phpNamedElement).getDefaultValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n }\n }\n\n private void addStringLiteralScope(@NotNull MethodReference methodReference, @NotNull StringLiteralExpression defaultValue) {\n String contents = defaultValue.getContents();\n if (StringUtils.isBlank(contents) || !contents.endsWith(\".twig\")) {\n return;\n }\n Function parentOfType = PsiTreeUtil.getParentOfType(methodReference, Function.class);\n if (parentOfType == null) {\n return;\n }\n addTemplateWithScope(contents, parentOfType, methodReference);\n }\n\n private void visitPhpDocTag(@NotNull PhpDocTag phpDocTag) {\n // \"@var\" and user non related tags dont need an action\n if (AnnotationBackportUtil.NON_ANNOTATION_TAGS.contains(phpDocTag.getName())) {\n return;\n }\n // init scope imports\n Map fileImports = AnnotationBackportUtil.getUseImportMap(phpDocTag);\n if (fileImports.size() == 0) {\n return;\n }\n String annotationFqnName = AnnotationBackportUtil.getClassNameReference(phpDocTag, fileImports);\n if (!StringUtils.stripStart(TwigUtil.TEMPLATE_ANNOTATION_CLASS, \"\\\\\").equals(StringUtils.stripStart(annotationFqnName, \"\\\\\"))) {\n return;\n }\n String template = AnnotationUtil.getPropertyValueOrDefault(phpDocTag, \"template\");\n if (template == null) {\n // see \\Sensio\\Bundle\\FrameworkExtraBundle\\Templating\\TemplateGuesser\n // App\\Controller\\MyNiceController::myAction => my_nice/my.html.twig\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n PhpClass phpClass = methodScope.getContainingClass();\n if (phpClass != null) {\n // App\\Controller\\ \"MyNice\" Controller\n Matcher matcher = Pattern.compile(\"Controller\\\\\\\\(.+)Controller$\", Pattern.MULTILINE).matcher(StringUtils.stripStart(phpClass.getFQN(), \"\\\\\"));\n if (matcher.find()) {\n String group = underscore(matcher.group(1).replace(\"\\\\\", \"/\"));\n String name = methodScope.getName();\n // __invoke is using controller as template name\n if (name.equals(\"__invoke\")) {\n addTemplateWithScope(group + \".html.twig\", methodScope, null);\n } else {\n String action = name.endsWith(\"Action\") ? name.substring(0, name.length() - \"Action\".length()) : name;\n addTemplateWithScope(group + \"/\" + underscore(action) + \".html.twig\", methodScope, null);\n }\n }\n }\n }\n } else if (template.endsWith(\".twig\")) {\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n addTemplateWithScope(template, methodScope, null);\n }\n }\n }\n\n private void addTemplateWithScope(@NotNull String contents, @NotNull PhpNamedElement scope, @Nullable FunctionReference functionReference) {\n String s = TwigUtil.normalizeTemplateName(contents);\n consumer.accept(new Triple<>(s, scope, functionReference));\n }\n }\n}\n"} {"task_id": "Java_1414", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Haehnchen/idea-php-symfony2-plugin/src/main/java/fr/adrienbrault/idea/symfony2plugin/templating/util/PhpMethodVariableResolveUtil.java", "mask_start_position": 12563, "mask_end_position": 12665, "canonical_solution": "if (element instanceof PhpDocTag) {\n visitPhpDocTag((PhpDocTag) element);\n }", "pre_mask_code": "package fr.adrienbrault.idea.symfony2plugin.templating.util;\n\nimport com.intellij.openapi.util.Pair;\nimport com.intellij.psi.PsiElement;\nimport com.intellij.psi.PsiRecursiveElementWalkingVisitor;\nimport com.intellij.psi.util.PsiTreeUtil;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;\nimport com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;\nimport com.jetbrains.php.lang.parser.PhpElementTypes;\nimport com.jetbrains.php.lang.psi.elements.*;\nimport de.espend.idea.php.annotation.util.AnnotationUtil;\nimport fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtension;\nimport fr.adrienbrault.idea.symfony2plugin.extension.PluginConfigurationExtensionParameter;\nimport fr.adrienbrault.idea.symfony2plugin.templating.variable.dict.PsiVariable;\nimport fr.adrienbrault.idea.symfony2plugin.util.AnnotationBackportUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;\nimport fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;\nimport kotlin.Triple;\nimport org.apache.commons.lang.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\nimport java.util.*;\nimport java.util.function.Consumer;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport static fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore;\n\n/**\n * @author Daniel Espendiller \n */\npublic class PhpMethodVariableResolveUtil {\n\n private static Set RENDER_METHODS = new HashSet() {\n\n {\n add(\"render\");\n add(\"renderView\");\n add(\"renderResponse\");\n }\n };\n\n /**\n * search for twig template variable on common use cases\n *\n * $this->render('foobar.html.twig', $foobar)\n * $this->render('foobar.html.twig', ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_merge_recursive($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_push($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', array_replace($foobar, ['foobar' => $var]))\n * $this->render('foobar.html.twig', $foobar + ['foobar' => $var])\n * $this->render('foobar.html.twig', $foobar += ['foobar' => $var])\n */\n public static Map collectMethodVariables(@NotNull Function method) {\n Map collectedTypes = new HashMap<>();\n for (PsiElement var : collectPossibleTemplateArrays(method)) {\n if (var instanceof ArrayCreationExpression) {\n // \"return array(...)\" we dont need any parsing\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) var));\n } else if (var instanceof Variable) {\n // we need variable declaration line so resolve it and search for references which attach other values to array\n // find definition and search for references on it\n PsiElement resolvedVariable = ((Variable) var).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n } else if (var instanceof FunctionReference && \"array_merge\".equalsIgnoreCase(((FunctionReference) var).getName())) {\n String name = ((FunctionReference) var).getName();\n if (\"array_merge\".equalsIgnoreCase(name) || \"array_merge_recursive\".equalsIgnoreCase(name) || \"array_push\".equalsIgnoreCase(name) || \"array_replace\".equalsIgnoreCase(name)) {\n for (PsiElement psiElement : ((FunctionReference) var).getParameters()) {\n collectVariablesForPsiElement(method, collectedTypes, psiElement);\n }\n }\n } else if (var instanceof BinaryExpression && var.getNode().getElementType() == PhpElementTypes.ADDITIVE_EXPRESSION) {\n PsiElement leftOperand = ((BinaryExpression) var).getLeftOperand();\n if (leftOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, leftOperand);\n }\n PsiElement rightOperand = ((BinaryExpression) var).getRightOperand();\n if (rightOperand != null) {\n collectVariablesForPsiElement(method, collectedTypes, rightOperand);\n }\n } else if (var instanceof SelfAssignmentExpression) {\n PhpPsiElement variable = ((SelfAssignmentExpression) var).getVariable();\n if (variable != null) {\n collectVariablesForPsiElement(method, collectedTypes, variable);\n }\n PhpPsiElement value = ((SelfAssignmentExpression) var).getValue();\n if (value != null) {\n collectVariablesForPsiElement(method, collectedTypes, value);\n }\n }\n }\n return collectedTypes;\n }\n\n private static void collectVariablesForPsiElement(@NotNull Function method, @NotNull Map collectedTypes, @NotNull PsiElement psiElement) {\n if (psiElement instanceof ArrayCreationExpression) {\n // reuse array collector: ['foobar' => $var]\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) psiElement));\n } else if (psiElement instanceof Variable) {\n // reuse variable collector: [$var]\n PsiElement resolvedVariable = ((Variable) psiElement).resolve();\n if (resolvedVariable instanceof Variable) {\n collectedTypes.putAll(collectOnVariableReferences(method, (Variable) resolvedVariable));\n }\n }\n }\n\n /**\n * search for variables which are possible accessible inside rendered twig template\n */\n @NotNull\n private static List collectPossibleTemplateArrays(@NotNull Function method) {\n List collectedTemplateVariables = new ArrayList<>();\n // Annotation controller\n // @TODO: check for phpdoc tag\n for (PhpReturn phpReturn : PsiTreeUtil.findChildrenOfType(method, PhpReturn.class)) {\n PhpPsiElement returnPsiElement = phpReturn.getFirstPsiChild();\n // @TODO: think of support all types here\n if (returnPsiElement instanceof Variable || returnPsiElement instanceof ArrayCreationExpression) {\n collectedTemplateVariables.add(returnPsiElement);\n }\n }\n // twig render calls:\n Set references = new HashSet<>();\n visitRenderTemplateFunctions(method, triple -> {\n FunctionReference functionScope = triple.getThird();\n if (functionScope != null) {\n references.add(functionScope);\n }\n });\n for (FunctionReference methodReference : references) {\n PsiElement templateParameter = PsiElementUtils.getMethodParameterPsiElementAt((methodReference).getParameterList(), 1);\n if (templateParameter != null) {\n collectedTemplateVariables.add(templateParameter);\n }\n }\n return collectedTemplateVariables;\n }\n\n /**\n * search for references of variable declaration and collect the types\n *\n * @param function should be function / method scope\n * @param variable the variable declaration psi $var = array();\n */\n @NotNull\n private static Map collectOnVariableReferences(@NotNull Function function, @NotNull Variable variable) {\n Map collectedTypes = new HashMap<>();\n for (Variable scopeVar : PhpElementsUtil.getVariablesInScope(function, variable)) {\n PsiElement parent = scopeVar.getParent();\n if (parent instanceof ArrayAccessExpression) {\n Pair pair = getTypesOnArrayIndex((ArrayAccessExpression) parent);\n if (pair != null) {\n collectedTypes.put(pair.getFirst(), pair.getSecond());\n }\n } else if (parent instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parent).getValue();\n if (value instanceof ArrayCreationExpression) {\n collectedTypes.putAll(getTypesOnArrayHash((ArrayCreationExpression) value));\n }\n }\n }\n return collectedTypes;\n }\n\n @Nullable\n private static Pair getTypesOnArrayIndex(@NotNull ArrayAccessExpression arrayAccessExpression) {\n ArrayIndex arrayIndex = arrayAccessExpression.getIndex();\n if (arrayIndex != null && arrayIndex.getValue() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayIndex.getValue()).getContents();\n Set variableTypes = new HashSet<>();\n PsiElement parent = arrayAccessExpression.getParent();\n if (parent instanceof AssignmentExpression) {\n PsiElement arrayValue = ((AssignmentExpression) parent).getValue();\n if (arrayValue instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayValue).getType().getTypes());\n }\n return Pair.create(variableName, new PsiVariable(variableTypes, ((AssignmentExpression) parent).getValue()));\n } else {\n return Pair.create(variableName, new PsiVariable(variableTypes));\n }\n }\n return null;\n }\n\n public static Map getTypesOnArrayHash(@NotNull ArrayCreationExpression arrayCreationExpression) {\n Map collectedTypes = new HashMap<>();\n for (ArrayHashElement arrayHashElement : arrayCreationExpression.getHashElements()) {\n if (arrayHashElement.getKey() instanceof StringLiteralExpression) {\n String variableName = ((StringLiteralExpression) arrayHashElement.getKey()).getContents();\n Set variableTypes = new HashSet<>();\n if (arrayHashElement.getValue() instanceof PhpTypedElement) {\n variableTypes.addAll(((PhpTypedElement) arrayHashElement.getValue()).getType().getTypes());\n }\n collectedTypes.put(variableName, new PsiVariable(variableTypes, arrayHashElement.getValue()));\n }\n }\n return collectedTypes;\n }\n\n /**\n * Visit method scope for template renders, also via annotation of the method itself\n *\n * As annotations are not in scope of the method itself\n */\n public static void visitRenderTemplateFunctions(@NotNull Method method, @NotNull Consumer> consumer) {\n TemplateRenderPsiRecursiveElementWalkingVisitor psiElementVisitor = new TemplateRenderPsiRecursiveElementWalkingVisitor(method, consumer);\n PhpDocComment docComment = method.getDocComment();\n for (PhpDocTag phpDocTag : PsiTreeUtil.getChildrenOfTypeAsList(docComment, PhpDocTag.class)) {\n psiElementVisitor.visitPhpDocTag(phpDocTag);\n }\n method.accept(psiElementVisitor);\n }\n\n /**\n * Visit all possible elements for render clements, scope shop be the class or a file itself\n */\n public static void visitRenderTemplateFunctions(@NotNull PsiElement context, @NotNull Consumer> consumer) {\n context.accept(new TemplateRenderPsiRecursiveElementWalkingVisitor(context, consumer));\n }\n\n private static class TemplateRenderPsiRecursiveElementWalkingVisitor extends PsiRecursiveElementWalkingVisitor {\n\n private final PsiElement context;\n\n private final Consumer> consumer;\n\n private Set methods;\n\n TemplateRenderPsiRecursiveElementWalkingVisitor(PsiElement context, Consumer> consumer) {\n this.context = context;\n this.consumer = consumer;\n methods = null;\n }\n\n @Override\n public void visitElement(PsiElement element) {\n if (element instanceof MethodReference) {\n visitMethodReference((MethodReference) element);\n } else ", "post_mask_code": "\n super.visitElement(element);\n }\n\n private void visitMethodReference(@NotNull MethodReference methodReference) {\n String methodName = methodReference.getName();\n // init methods once per file\n if (methods == null) {\n methods = new HashSet<>();\n methods.addAll(RENDER_METHODS);\n PluginConfigurationExtension[] extensions = Symfony2ProjectComponent.PLUGIN_CONFIGURATION_EXTENSION.getExtensions();\n if (extensions.length > 0) {\n PluginConfigurationExtensionParameter pluginConfiguration = new PluginConfigurationExtensionParameter(context.getProject());\n for (PluginConfigurationExtension extension : extensions) {\n extension.invokePluginConfiguration(pluginConfiguration);\n }\n methods.addAll(pluginConfiguration.getTemplateUsageMethod());\n }\n }\n if (!methods.contains(methodName)) {\n return;\n }\n PsiElement[] parameters = methodReference.getParameters();\n if (parameters.length == 0) {\n return;\n }\n if (parameters[0] instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) parameters[0]);\n } else if (parameters[0] instanceof TernaryExpression) {\n for (PhpPsiElement phpPsiElement : new PhpPsiElement[] { ((TernaryExpression) parameters[0]).getTrueVariant(), ((TernaryExpression) parameters[0]).getFalseVariant() }) {\n if (phpPsiElement == null) {\n continue;\n }\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n } else if (parameters[0] instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) parameters[0]).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n } else if (parameters[0] instanceof PhpReference) {\n resolvePhpReference(methodReference, parameters[0]);\n } else if (parameters[0] instanceof BinaryExpression) {\n PsiElement phpPsiElement = ((BinaryExpression) parameters[0]).getRightOperand();\n if (phpPsiElement instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) phpPsiElement);\n } else if (phpPsiElement instanceof PhpReference) {\n resolvePhpReference(methodReference, phpPsiElement);\n }\n }\n }\n\n private void resolvePhpReference(@NotNull MethodReference methodReference, PsiElement parameter) {\n for (PhpNamedElement phpNamedElement : ((PhpReference) parameter).resolveLocal()) {\n if (phpNamedElement instanceof Field) {\n PsiElement defaultValue = ((Field) phpNamedElement).getDefaultValue();\n if (defaultValue instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) defaultValue);\n }\n } else if (phpNamedElement instanceof Variable) {\n PsiElement assignmentExpression = phpNamedElement.getParent();\n if (assignmentExpression instanceof AssignmentExpression) {\n PhpPsiElement value = ((AssignmentExpression) assignmentExpression).getValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n } else if (phpNamedElement instanceof Parameter) {\n PsiElement value = ((Parameter) phpNamedElement).getDefaultValue();\n if (value instanceof StringLiteralExpression) {\n addStringLiteralScope(methodReference, (StringLiteralExpression) value);\n }\n }\n }\n }\n\n private void addStringLiteralScope(@NotNull MethodReference methodReference, @NotNull StringLiteralExpression defaultValue) {\n String contents = defaultValue.getContents();\n if (StringUtils.isBlank(contents) || !contents.endsWith(\".twig\")) {\n return;\n }\n Function parentOfType = PsiTreeUtil.getParentOfType(methodReference, Function.class);\n if (parentOfType == null) {\n return;\n }\n addTemplateWithScope(contents, parentOfType, methodReference);\n }\n\n private void visitPhpDocTag(@NotNull PhpDocTag phpDocTag) {\n // \"@var\" and user non related tags dont need an action\n if (AnnotationBackportUtil.NON_ANNOTATION_TAGS.contains(phpDocTag.getName())) {\n return;\n }\n // init scope imports\n Map fileImports = AnnotationBackportUtil.getUseImportMap(phpDocTag);\n if (fileImports.size() == 0) {\n return;\n }\n String annotationFqnName = AnnotationBackportUtil.getClassNameReference(phpDocTag, fileImports);\n if (!StringUtils.stripStart(TwigUtil.TEMPLATE_ANNOTATION_CLASS, \"\\\\\").equals(StringUtils.stripStart(annotationFqnName, \"\\\\\"))) {\n return;\n }\n String template = AnnotationUtil.getPropertyValueOrDefault(phpDocTag, \"template\");\n if (template == null) {\n // see \\Sensio\\Bundle\\FrameworkExtraBundle\\Templating\\TemplateGuesser\n // App\\Controller\\MyNiceController::myAction => my_nice/my.html.twig\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n PhpClass phpClass = methodScope.getContainingClass();\n if (phpClass != null) {\n // App\\Controller\\ \"MyNice\" Controller\n Matcher matcher = Pattern.compile(\"Controller\\\\\\\\(.+)Controller$\", Pattern.MULTILINE).matcher(StringUtils.stripStart(phpClass.getFQN(), \"\\\\\"));\n if (matcher.find()) {\n String group = underscore(matcher.group(1).replace(\"\\\\\", \"/\"));\n String name = methodScope.getName();\n // __invoke is using controller as template name\n if (name.equals(\"__invoke\")) {\n addTemplateWithScope(group + \".html.twig\", methodScope, null);\n } else {\n String action = name.endsWith(\"Action\") ? name.substring(0, name.length() - \"Action\".length()) : name;\n addTemplateWithScope(group + \"/\" + underscore(action) + \".html.twig\", methodScope, null);\n }\n }\n }\n }\n } else if (template.endsWith(\".twig\")) {\n Method methodScope = AnnotationBackportUtil.getMethodScope(phpDocTag);\n if (methodScope != null) {\n addTemplateWithScope(template, methodScope, null);\n }\n }\n }\n\n private void addTemplateWithScope(@NotNull String contents, @NotNull PhpNamedElement scope, @Nullable FunctionReference functionReference) {\n String s = TwigUtil.normalizeTemplateName(contents);\n consumer.accept(new Triple<>(s, scope, functionReference));\n }\n }\n}\n"} {"task_id": "Java_1415", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/metron/metron-interface/metron-rest/src/main/java/org/apache/metron/rest/controller/StellarController.java", "mask_start_position": 1600, "mask_end_position": 2096, "canonical_solution": "@ApiOperation(value = \"Executes transformations against a sample message\")\n @ApiResponse(message = \"Returns transformation results\", code = 200)\n @RequestMapping(value = \"/apply/transformations\", method = RequestMethod.POST)\n ResponseEntity> applyTransformations(@ApiParam(name = \"transformationValidation\", value = \"Object containing SensorParserConfig and sample message\", required = true) @RequestBody SensorParserContext sensorParserContext) throws RestException ", "pre_mask_code": "package org.apache.metron.rest.controller;\n\nimport io.swagger.annotations.ApiOperation;\nimport io.swagger.annotations.ApiParam;\nimport io.swagger.annotations.ApiResponse;\nimport org.apache.metron.common.field.transformation.FieldTransformations;\nimport org.apache.metron.rest.RestException;\nimport org.apache.metron.rest.model.StellarFunctionDescription;\nimport org.apache.metron.rest.model.SensorParserContext;\nimport org.apache.metron.rest.service.StellarService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\nimport java.util.List;\nimport java.util.Map;\n\n@RestController\n@RequestMapping(\"/api/v1/stellar\")\npublic class StellarController {\n\n @Autowired\n private StellarService stellarService;\n\n @ApiOperation(value = \"Tests Stellar statements to ensure they are well-formed\")\n @ApiResponse(message = \"Returns validation results\", code = 200)\n @RequestMapping(value = \"/validate/rules\", method = RequestMethod.POST)\n ResponseEntity> validateRules(@ApiParam(name = \"statements\", value = \"List of statements to validate\", required = true) @RequestBody List statements) throws RestException {\n return new ResponseEntity<>(stellarService.validateRules(statements), HttpStatus.OK);\n }\n\n ", "post_mask_code": "{\n return new ResponseEntity<>(stellarService.applyTransformations(sensorParserContext), HttpStatus.OK);\n }\n\n @ApiOperation(value = \"Retrieves field transformations\")\n @ApiResponse(message = \"Returns a list field transformations\", code = 200)\n @RequestMapping(value = \"/list\", method = RequestMethod.GET)\n ResponseEntity list() throws RestException {\n return new ResponseEntity<>(stellarService.getTransformations(), HttpStatus.OK);\n }\n\n @ApiOperation(value = \"Lists the Stellar functions that can be found on the classpath\")\n @ApiResponse(message = \"Returns a list of Stellar functions\", code = 200)\n @RequestMapping(value = \"/list/functions\", method = RequestMethod.GET)\n ResponseEntity> listFunctions() throws RestException {\n return new ResponseEntity<>(stellarService.getStellarFunctions(), HttpStatus.OK);\n }\n\n @ApiOperation(value = \"Lists the simple Stellar functions (functions with only 1 input) that can be found on the classpath\")\n @ApiResponse(message = \"Returns a list of simple Stellar functions\", code = 200)\n @RequestMapping(value = \"/list/simple/functions\", method = RequestMethod.GET)\n ResponseEntity> listSimpleFunctions() throws RestException {\n return new ResponseEntity<>(stellarService.getSimpleStellarFunctions(), HttpStatus.OK);\n }\n}\n"} {"task_id": "Java_1416", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/metron/metron-interface/metron-rest/src/main/java/org/apache/metron/rest/controller/StellarController.java", "mask_start_position": 2924, "mask_end_position": 3021, "canonical_solution": "{\n return new ResponseEntity<>(stellarService.getStellarFunctions(), HttpStatus.OK);\n }", "pre_mask_code": "package org.apache.metron.rest.controller;\n\nimport io.swagger.annotations.ApiOperation;\nimport io.swagger.annotations.ApiParam;\nimport io.swagger.annotations.ApiResponse;\nimport org.apache.metron.common.field.transformation.FieldTransformations;\nimport org.apache.metron.rest.RestException;\nimport org.apache.metron.rest.model.StellarFunctionDescription;\nimport org.apache.metron.rest.model.SensorParserContext;\nimport org.apache.metron.rest.service.StellarService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\nimport java.util.List;\nimport java.util.Map;\n\n@RestController\n@RequestMapping(\"/api/v1/stellar\")\npublic class StellarController {\n\n @Autowired\n private StellarService stellarService;\n\n @ApiOperation(value = \"Tests Stellar statements to ensure they are well-formed\")\n @ApiResponse(message = \"Returns validation results\", code = 200)\n @RequestMapping(value = \"/validate/rules\", method = RequestMethod.POST)\n ResponseEntity> validateRules(@ApiParam(name = \"statements\", value = \"List of statements to validate\", required = true) @RequestBody List statements) throws RestException {\n return new ResponseEntity<>(stellarService.validateRules(statements), HttpStatus.OK);\n }\n\n @ApiOperation(value = \"Executes transformations against a sample message\")\n @ApiResponse(message = \"Returns transformation results\", code = 200)\n @RequestMapping(value = \"/apply/transformations\", method = RequestMethod.POST)\n ResponseEntity> applyTransformations(@ApiParam(name = \"transformationValidation\", value = \"Object containing SensorParserConfig and sample message\", required = true) @RequestBody SensorParserContext sensorParserContext) throws RestException {\n return new ResponseEntity<>(stellarService.applyTransformations(sensorParserContext), HttpStatus.OK);\n }\n\n @ApiOperation(value = \"Retrieves field transformations\")\n @ApiResponse(message = \"Returns a list field transformations\", code = 200)\n @RequestMapping(value = \"/list\", method = RequestMethod.GET)\n ResponseEntity list() throws RestException {\n return new ResponseEntity<>(stellarService.getTransformations(), HttpStatus.OK);\n }\n\n @ApiOperation(value = \"Lists the Stellar functions that can be found on the classpath\")\n @ApiResponse(message = \"Returns a list of Stellar functions\", code = 200)\n @RequestMapping(value = \"/list/functions\", method = RequestMethod.GET)\n ResponseEntity> listFunctions() throws RestException ", "post_mask_code": "\n\n @ApiOperation(value = \"Lists the simple Stellar functions (functions with only 1 input) that can be found on the classpath\")\n @ApiResponse(message = \"Returns a list of simple Stellar functions\", code = 200)\n @RequestMapping(value = \"/list/simple/functions\", method = RequestMethod.GET)\n ResponseEntity> listSimpleFunctions() throws RestException {\n return new ResponseEntity<>(stellarService.getSimpleStellarFunctions(), HttpStatus.OK);\n }\n}\n"} {"task_id": "Java_1417", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/metron/metron-interface/metron-rest/src/main/java/org/apache/metron/rest/controller/StellarController.java", "mask_start_position": 3433, "mask_end_position": 3512, "canonical_solution": "ew ResponseEntity<>(stellarService.getSimpleStellarFunctions(), HttpStatus.OK);", "pre_mask_code": "package org.apache.metron.rest.controller;\n\nimport io.swagger.annotations.ApiOperation;\nimport io.swagger.annotations.ApiParam;\nimport io.swagger.annotations.ApiResponse;\nimport org.apache.metron.common.field.transformation.FieldTransformations;\nimport org.apache.metron.rest.RestException;\nimport org.apache.metron.rest.model.StellarFunctionDescription;\nimport org.apache.metron.rest.model.SensorParserContext;\nimport org.apache.metron.rest.service.StellarService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\nimport java.util.List;\nimport java.util.Map;\n\n@RestController\n@RequestMapping(\"/api/v1/stellar\")\npublic class StellarController {\n\n @Autowired\n private StellarService stellarService;\n\n @ApiOperation(value = \"Tests Stellar statements to ensure they are well-formed\")\n @ApiResponse(message = \"Returns validation results\", code = 200)\n @RequestMapping(value = \"/validate/rules\", method = RequestMethod.POST)\n ResponseEntity> validateRules(@ApiParam(name = \"statements\", value = \"List of statements to validate\", required = true) @RequestBody List statements) throws RestException {\n return new ResponseEntity<>(stellarService.validateRules(statements), HttpStatus.OK);\n }\n\n @ApiOperation(value = \"Executes transformations against a sample message\")\n @ApiResponse(message = \"Returns transformation results\", code = 200)\n @RequestMapping(value = \"/apply/transformations\", method = RequestMethod.POST)\n ResponseEntity> applyTransformations(@ApiParam(name = \"transformationValidation\", value = \"Object containing SensorParserConfig and sample message\", required = true) @RequestBody SensorParserContext sensorParserContext) throws RestException {\n return new ResponseEntity<>(stellarService.applyTransformations(sensorParserContext), HttpStatus.OK);\n }\n\n @ApiOperation(value = \"Retrieves field transformations\")\n @ApiResponse(message = \"Returns a list field transformations\", code = 200)\n @RequestMapping(value = \"/list\", method = RequestMethod.GET)\n ResponseEntity list() throws RestException {\n return new ResponseEntity<>(stellarService.getTransformations(), HttpStatus.OK);\n }\n\n @ApiOperation(value = \"Lists the Stellar functions that can be found on the classpath\")\n @ApiResponse(message = \"Returns a list of Stellar functions\", code = 200)\n @RequestMapping(value = \"/list/functions\", method = RequestMethod.GET)\n ResponseEntity> listFunctions() throws RestException {\n return new ResponseEntity<>(stellarService.getStellarFunctions(), HttpStatus.OK);\n }\n\n @ApiOperation(value = \"Lists the simple Stellar functions (functions with only 1 input) that can be found on the classpath\")\n @ApiResponse(message = \"Returns a list of simple Stellar functions\", code = 200)\n @RequestMapping(value = \"/list/simple/functions\", method = RequestMethod.GET)\n ResponseEntity> listSimpleFunctions() throws RestException {\n return n", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1418", "language": "Java", "task_type": "method_signature", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/io/CharToByteCp942.java", "mask_start_position": 386, "mask_end_position": 423, "canonical_solution": "public String getCharacterEncoding() ", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.io;\n\nimport sun.nio.cs.ext.IBM942;\n\n/**\n * Tables and data to convert Unicode to Cp942\n *\n * @author Malcolm Ayres, assisted by UniMap program\n */\npublic class CharToByteCp942 extends CharToByteDBCS_ASCII {\n\n private static IBM942 nioCoder = new IBM942();\n\n // Return the character set id\n ", "post_mask_code": "{\n return \"Cp942\";\n }\n\n public CharToByteCp942() {\n super();\n super.mask1 = 0xFFE0;\n super.mask2 = 0x001F;\n super.shift = 5;\n super.index1 = nioCoder.getEncoderIndex1();\n super.index2 = nioCoder.getEncoderIndex2();\n super.index2a = nioCoder.getEncoderIndex2a();\n }\n}\n"} {"task_id": "Java_1419", "language": "Java", "task_type": "method_body", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/io/CharToByteCp942.java", "mask_start_position": 423, "mask_end_position": 454, "canonical_solution": "{\n return \"Cp942\";\n }", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.io;\n\nimport sun.nio.cs.ext.IBM942;\n\n/**\n * Tables and data to convert Unicode to Cp942\n *\n * @author Malcolm Ayres, assisted by UniMap program\n */\npublic class CharToByteCp942 extends CharToByteDBCS_ASCII {\n\n private static IBM942 nioCoder = new IBM942();\n\n // Return the character set id\n public String getCharacterEncoding() ", "post_mask_code": "\n\n public CharToByteCp942() {\n super();\n super.mask1 = 0xFFE0;\n super.mask2 = 0x001F;\n super.shift = 5;\n super.index1 = nioCoder.getEncoderIndex1();\n super.index2 = nioCoder.getEncoderIndex2();\n super.index2a = nioCoder.getEncoderIndex2a();\n }\n}\n"} {"task_id": "Java_1420", "language": "Java", "task_type": "single_line", "source_file": "java/github/GregBowyer/ManagedRuntimeInitiative/MRI-J/jdk/src/share/classes/sun/io/CharToByteCp942.java", "mask_start_position": 447, "mask_end_position": 448, "canonical_solution": ";", "pre_mask_code": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n */\npackage sun.io;\n\nimport sun.nio.cs.ext.IBM942;\n\n/**\n * Tables and data to convert Unicode to Cp942\n *\n * @author Malcolm Ayres, assisted by UniMap program\n */\npublic class CharToByteCp942 extends CharToByteDBCS_ASCII {\n\n private static IBM942 nioCoder = new IBM942();\n\n // Return the character set id\n public String getCharacterEncoding() {\n return \"Cp942\"", "post_mask_code": "\n }\n\n public CharToByteCp942() {\n super();\n super.mask1 = 0xFFE0;\n super.mask2 = 0x001F;\n super.shift = 5;\n super.index1 = nioCoder.getEncoderIndex1();\n super.index2 = nioCoder.getEncoderIndex2();\n super.index2a = nioCoder.getEncoderIndex2a();\n }\n}\n"} {"task_id": "Java_1421", "language": "Java", "task_type": "method_signature", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/apigateway/v20180808/ApigatewayClient.java", "mask_start_position": 72264, "mask_end_position": 72374, "canonical_solution": "public UnReleaseServiceResponse UnReleaseService(UnReleaseServiceRequest req) throws TencentCloudSDKException ", "pre_mask_code": "package com.tencentcloudapi.apigateway.v20180808;\n\nimport java.lang.reflect.Type;\nimport com.google.gson.JsonSyntaxException;\nimport com.google.gson.reflect.TypeToken;\nimport com.tencentcloudapi.common.exception.TencentCloudSDKException;\nimport com.tencentcloudapi.common.AbstractClient;\nimport com.tencentcloudapi.common.profile.ClientProfile;\nimport com.tencentcloudapi.common.JsonResponseModel;\nimport com.tencentcloudapi.common.Credential;\nimport com.tencentcloudapi.apigateway.v20180808.models.*;\n\npublic class ApigatewayClient extends AbstractClient {\n\n private static String endpoint = \"apigateway.tencentcloudapi.com\";\n\n private static String service = \"apigateway\";\n\n private static String version = \"2018-08-08\";\n\n public ApigatewayClient(Credential credential, String region) {\n this(credential, region, new ClientProfile());\n }\n\n public ApigatewayClient(Credential credential, String region, ClientProfile profile) {\n super(ApigatewayClient.endpoint, ApigatewayClient.version, credential, region, profile);\n }\n\n /**\n * 绑定插件到API上。\n * @param req AttachPluginRequest\n * @return AttachPluginResponse\n * @throws TencentCloudSDKException\n */\n public AttachPluginResponse AttachPlugin(AttachPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"AttachPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindApiApp)用于绑定应用到API。\n * @param req BindApiAppRequest\n * @return BindApiAppResponse\n * @throws TencentCloudSDKException\n */\n public BindApiAppResponse BindApiApp(BindApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindEnvironment)用于绑定使用计划到服务或API。\n * 用户在发布服务到某个环境中后,如果 API 需要鉴权,还需要绑定使用计划才能进行调用,此接口用户将使用计划绑定到特定环境。\n * 目前支持绑定使用计划到API,但是同一个服务不能同时存在绑定到服务的使用计划和绑定到API的使用计划,所以对已经绑定过服务级别使用计划的环境,请先使用 服务级别使用计划降级 接口进行降级操作。\n * @param req BindEnvironmentRequest\n * @return BindEnvironmentResponse\n * @throws TencentCloudSDKException\n */\n public BindEnvironmentResponse BindEnvironment(BindEnvironmentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindEnvironment\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindIPStrategy)用于API绑定IP策略。\n * @param req BindIPStrategyRequest\n * @return BindIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public BindIPStrategyResponse BindIPStrategy(BindIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindSecretIds)用于为使用计划绑定密钥。\n * 将密钥绑定到某个使用计划,并将此使用计划绑定到某个服务发布的环境上,调用者方可使用此密钥调用这个服务中的 API,可使用本接口为使用计划绑定密钥。\n * @param req BindSecretIdsRequest\n * @return BindSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public BindSecretIdsResponse BindSecretIds(BindSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindSubDomain)用于绑定自定义域名到服务。\n * API 网关中每个服务都会提供一个默认的域名供用户调用,但当用户想使用自己的已有域名时,也可以将自定义域名绑定到此服务,在做好备案、与默认域名的 CNAME 后,可直接调用自定义域名。\n * @param req BindSubDomainRequest\n * @return BindSubDomainResponse\n * @throws TencentCloudSDKException\n */\n public BindSubDomainResponse BindSubDomain(BindSubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindSubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 构建 API 文档\n * @param req BuildAPIDocRequest\n * @return BuildAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public BuildAPIDocResponse BuildAPIDoc(BuildAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BuildAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 创建 API 文档\n * @param req CreateAPIDocRequest\n * @return CreateAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public CreateAPIDocResponse CreateAPIDoc(CreateAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApi)用于创建 API 接口,创建 API 前,用户需要先创建服务,每个 API 都有自己归属的服务。\n * @param req CreateApiRequest\n * @return CreateApiResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiResponse CreateApi(CreateApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApiApp)用于创建应用。\n * @param req CreateApiAppRequest\n * @return CreateApiAppResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiAppResponse CreateApiApp(CreateApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApiKey)用于创建一对新的 API 密钥。\n * @param req CreateApiKeyRequest\n * @return CreateApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiKeyResponse CreateApiKey(CreateApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateIPStrategy)用于创建服务IP策略。\n * @param req CreateIPStrategyRequest\n * @return CreateIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public CreateIPStrategyResponse CreateIPStrategy(CreateIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 创建API网关插件。\n * @param req CreatePluginRequest\n * @return CreatePluginResponse\n * @throws TencentCloudSDKException\n */\n public CreatePluginResponse CreatePlugin(CreatePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreatePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateService)用于创建服务。\n * API 网关使用的最大单元为服务,每个服务中可创建多个 API 接口。每个服务有一个默认域名供客户调用,用户也可绑定自定义域名到此服务中。\n * @param req CreateServiceRequest\n * @return CreateServiceResponse\n * @throws TencentCloudSDKException\n */\n public CreateServiceResponse CreateService(CreateServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateUsagePlan)用于创建使用计划。\n * 用户在使用 API 网关时,需要创建使用计划并将其绑定到服务的环境中使用。\n * @param req CreateUsagePlanRequest\n * @return CreateUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public CreateUsagePlanResponse CreateUsagePlan(CreateUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 删除 API 文档\n * @param req DeleteAPIDocRequest\n * @return DeleteAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public DeleteAPIDocResponse DeleteAPIDoc(DeleteAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApi)用于删除已经创建的API。\n * @param req DeleteApiRequest\n * @return DeleteApiResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiResponse DeleteApi(DeleteApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApiApp)用于删除已经创建的应用。\n * @param req DeleteApiAppRequest\n * @return DeleteApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiAppResponse DeleteApiApp(DeleteApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApiKey)用于删除一对 API 密钥。\n * @param req DeleteApiKeyRequest\n * @return DeleteApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiKeyResponse DeleteApiKey(DeleteApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteIPStrategy)用于删除服务IP策略。\n * @param req DeleteIPStrategyRequest\n * @return DeleteIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DeleteIPStrategyResponse DeleteIPStrategy(DeleteIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 删除API网关插件\n * @param req DeletePluginRequest\n * @return DeletePluginResponse\n * @throws TencentCloudSDKException\n */\n public DeletePluginResponse DeletePlugin(DeletePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeletePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteService)用于删除 API 网关中某个服务。\n * @param req DeleteServiceRequest\n * @return DeleteServiceResponse\n * @throws TencentCloudSDKException\n */\n public DeleteServiceResponse DeleteService(DeleteServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteServiceSubDomainMapping)用于删除服务中某个环境的自定义域名映射。\n * 当用户使用自定义域名,并使用了自定义映射时,可使用此接口。但需注意,若删除了所有环境的映射时,调用此 API 均会返回失败。\n * @param req DeleteServiceSubDomainMappingRequest\n * @return DeleteServiceSubDomainMappingResponse\n * @throws TencentCloudSDKException\n */\n public DeleteServiceSubDomainMappingResponse DeleteServiceSubDomainMapping(DeleteServiceSubDomainMappingRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteServiceSubDomainMapping\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteUsagePlan)用于删除使用计划。\n * @param req DeleteUsagePlanRequest\n * @return DeleteUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DeleteUsagePlanResponse DeleteUsagePlan(DeleteUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DemoteServiceUsagePlan)用于将某个服务在某个环境的使用计划,降级到API上。\n * 如果服务内没有API不允许进行此操作。\n * 如果当前环境没有发布,不允许进行此操作。\n * @param req DemoteServiceUsagePlanRequest\n * @return DemoteServiceUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DemoteServiceUsagePlanResponse DemoteServiceUsagePlan(DemoteServiceUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DemoteServiceUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询 API 文档详情\n * @param req DescribeAPIDocDetailRequest\n * @return DescribeAPIDocDetailResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAPIDocDetailResponse DescribeAPIDocDetail(DescribeAPIDocDetailRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAPIDocDetail\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询 API 文档列表\n * @param req DescribeAPIDocsRequest\n * @return DescribeAPIDocsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAPIDocsResponse DescribeAPIDocs(DescribeAPIDocsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAPIDocs\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件相关的API列表,包括已绑定的和未绑定的API信息。\n * @param req DescribeAllPluginApisRequest\n * @return DescribeAllPluginApisResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAllPluginApisResponse DescribeAllPluginApis(DescribeAllPluginApisRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAllPluginApis\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApi)用于查询用户 API 网关的 API 接口的详细信息。​\n * @param req DescribeApiRequest\n * @return DescribeApiResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiResponse DescribeApi(DescribeApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiApp)用于根据应用ID搜索应用。\n * @param req DescribeApiAppRequest\n * @return DescribeApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppResponse DescribeApiApp(DescribeApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiAppBindApisStatus)查询应用绑定的Api列表。\n * @param req DescribeApiAppBindApisStatusRequest\n * @return DescribeApiAppBindApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppBindApisStatusResponse DescribeApiAppBindApisStatus(DescribeApiAppBindApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiAppBindApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiAppsStatus)查询应用列表。\n * @param req DescribeApiAppsStatusRequest\n * @return DescribeApiAppsStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppsStatusResponse DescribeApiAppsStatus(DescribeApiAppsStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiAppsStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiBindApiAppsStatus)查询Api绑定的应用列表。\n * @param req DescribeApiBindApiAppsStatusRequest\n * @return DescribeApiBindApiAppsStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiBindApiAppsStatusResponse DescribeApiBindApiAppsStatus(DescribeApiBindApiAppsStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiBindApiAppsStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiEnvironmentStrategy)用于展示API绑定的限流策略。\n * @param req DescribeApiEnvironmentStrategyRequest\n * @return DescribeApiEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiEnvironmentStrategyResponse DescribeApiEnvironmentStrategy(DescribeApiEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiForApiApp)用于应用使用者查询部署于 API 网关的 API 接口的详细信息。​\n * @param req DescribeApiForApiAppRequest\n * @return DescribeApiForApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiForApiAppResponse DescribeApiForApiApp(DescribeApiForApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiForApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiKey)用于查询密钥详情。\n * 用户在创建密钥后,可用此接口查询一个 API 密钥的详情,该接口会显示密钥 Key。\n * @param req DescribeApiKeyRequest\n * @return DescribeApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiKeyResponse DescribeApiKey(DescribeApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiKeysStatus)用于查询密钥列表。\n * 当用户创建了多个密钥对时,可使用本接口查询一个或多个 API 密钥信息,本接口不会显示密钥 Key。\n * @param req DescribeApiKeysStatusRequest\n * @return DescribeApiKeysStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiKeysStatusResponse DescribeApiKeysStatus(DescribeApiKeysStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiKeysStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiUsagePlan)用于查询服务中 API 使用计划详情。\n * 服务若需要鉴权限流生效,则需要绑定使用计划到此服务中,本接口用于查询绑定到一个服务及其中 API 的所有使用计划。\n * @param req DescribeApiUsagePlanRequest\n * @return DescribeApiUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiUsagePlanResponse DescribeApiUsagePlan(DescribeApiUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApisStatus)用于查看一个服务下的某个 API 或所有 API 列表及其相关信息。\n * @param req DescribeApisStatusRequest\n * @return DescribeApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApisStatusResponse DescribeApisStatus(DescribeApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategy)用于查询IP策略详情。\n * @param req DescribeIPStrategyRequest\n * @return DescribeIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategyResponse DescribeIPStrategy(DescribeIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategyApisStatus)用于查询IP策略可以绑定的API列表。即服务下所有API和该策略已绑定API的差集。\n * @param req DescribeIPStrategyApisStatusRequest\n * @return DescribeIPStrategyApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategyApisStatusResponse DescribeIPStrategyApisStatus(DescribeIPStrategyApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategyApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategysStatus)用于查询服务IP策略列表。\n * @param req DescribeIPStrategysStatusRequest\n * @return DescribeIPStrategysStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategysStatusResponse DescribeIPStrategysStatus(DescribeIPStrategysStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategysStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口DescribeLogSearch用于搜索日志\n * @param req DescribeLogSearchRequest\n * @return DescribeLogSearchResponse\n * @throws TencentCloudSDKException\n */\n public DescribeLogSearchResponse DescribeLogSearch(DescribeLogSearchRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeLogSearch\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件详情,支持按照插件ID进行。\n * @param req DescribePluginRequest\n * @return DescribePluginResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginResponse DescribePlugin(DescribePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询指定插件下绑定的API信息\n * @param req DescribePluginApisRequest\n * @return DescribePluginApisResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginApisResponse DescribePluginApis(DescribePluginApisRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePluginApis\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件列表和详情,支持分页,支持按照插件类型查询,支持按照插件ID批量查询,支持按照插件名称查询。\n * @param req DescribePluginsRequest\n * @return DescribePluginsResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginsResponse DescribePlugins(DescribePluginsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePlugins\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeService)用于查询一个服务的详细信息、包括服务的描述、域名、协议、创建时间、发布情况等信息。\n * @param req DescribeServiceRequest\n * @return DescribeServiceResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceResponse DescribeService(DescribeServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentList)用于查询一个服务的环境列表,可查询到此服务下所有环境及其状态。\n * @param req DescribeServiceEnvironmentListRequest\n * @return DescribeServiceEnvironmentListResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentListResponse DescribeServiceEnvironmentList(DescribeServiceEnvironmentListRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentList\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentReleaseHistory)用于查询服务环境的发布历史。\n * 用户在创建好服务后需要发布到某个环境中才能进行使用,本接口用于查询一个服务某个环境的发布记录。\n * @param req DescribeServiceEnvironmentReleaseHistoryRequest\n * @return DescribeServiceEnvironmentReleaseHistoryResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentReleaseHistoryResponse DescribeServiceEnvironmentReleaseHistory(DescribeServiceEnvironmentReleaseHistoryRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentReleaseHistory\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentStrategy)用于展示服务限流策略。\n * @param req DescribeServiceEnvironmentStrategyRequest\n * @return DescribeServiceEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentStrategyResponse DescribeServiceEnvironmentStrategy(DescribeServiceEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceForApiApp)用于应用使用者查询一个服务的详细信息、包括服务的描述、域名、协议等信息。\n * @param req DescribeServiceForApiAppRequest\n * @return DescribeServiceForApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceForApiAppResponse DescribeServiceForApiApp(DescribeServiceForApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceForApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceReleaseVersion)查询一个服务下面所有已经发布的版本列表。\n * 用户在发布服务时,常有多个版本发布,可使用本接口查询已发布的版本。\n * @param req DescribeServiceReleaseVersionRequest\n * @return DescribeServiceReleaseVersionResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceReleaseVersionResponse DescribeServiceReleaseVersion(DescribeServiceReleaseVersionRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceReleaseVersion\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceSubDomainMappings)用于查询自定义域名的路径映射。\n * API 网关可绑定自定义域名到服务,并且可以对自定义域名的路径进行映射,可自定义不同的路径映射到服务中的三个环境,本接口用于查询绑定服务的自定义域名的路径映射列表。\n * @param req DescribeServiceSubDomainMappingsRequest\n * @return DescribeServiceSubDomainMappingsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceSubDomainMappingsResponse DescribeServiceSubDomainMappings(DescribeServiceSubDomainMappingsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceSubDomainMappings\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceSubDomains)用于查询自定义域名列表。\n * API 网关可绑定自定义域名到服务,用于服务调用。此接口用于查询用户绑定在服务的自定义域名列表。\n * @param req DescribeServiceSubDomainsRequest\n * @return DescribeServiceSubDomainsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceSubDomainsResponse DescribeServiceSubDomains(DescribeServiceSubDomainsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceSubDomains\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceUsagePlan)用于查询服务使用计划详情。\n * 服务若需要鉴权限流生效,则需要绑定使用计划到此服务中,本接口用于查询绑定到一个服务的所有使用计划。\n * @param req DescribeServiceUsagePlanRequest\n * @return DescribeServiceUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceUsagePlanResponse DescribeServiceUsagePlan(DescribeServiceUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServicesStatus)用于搜索查询某一个服务或多个服务的列表,并返回服务相关的域名、时间等信息。\n * @param req DescribeServicesStatusRequest\n * @return DescribeServicesStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServicesStatusResponse DescribeServicesStatus(DescribeServicesStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServicesStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlan)用于查询一个使用计划的详细信息,包括名称、QPS、创建时间绑定的环境等。\n * @param req DescribeUsagePlanRequest\n * @return DescribeUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanResponse DescribeUsagePlan(DescribeUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanEnvironments)用于查询使用计划绑定的环境列表。\n * 用户在绑定了某个使用计划到环境后,可使用本接口查询这个使用计划绑定的所有服务的环境。\n * @param req DescribeUsagePlanEnvironmentsRequest\n * @return DescribeUsagePlanEnvironmentsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanEnvironmentsResponse DescribeUsagePlanEnvironments(DescribeUsagePlanEnvironmentsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlanEnvironments\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanSecretIds)用于查询使用计划绑定的密钥列表。\n * 在 API 网关中,一个使用计划可绑定多个密钥对,可使用本接口查询使用计划绑定的密钥列表。\n * @param req DescribeUsagePlanSecretIdsRequest\n * @return DescribeUsagePlanSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanSecretIdsResponse DescribeUsagePlanSecretIds(DescribeUsagePlanSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlanSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanStatus)用于查询使用计划的列表。\n * @param req DescribeUsagePlansStatusRequest\n * @return DescribeUsagePlansStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlansStatusResponse DescribeUsagePlansStatus(DescribeUsagePlansStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlansStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 解除插件与API绑定\n * @param req DetachPluginRequest\n * @return DetachPluginResponse\n * @throws TencentCloudSDKException\n */\n public DetachPluginResponse DetachPlugin(DetachPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DetachPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DisableApiKey)用于禁用一对 API 密钥。\n * @param req DisableApiKeyRequest\n * @return DisableApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DisableApiKeyResponse DisableApiKey(DisableApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DisableApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(EnableApiKey)用于启动一对被禁用的 API 密钥。\n * @param req EnableApiKeyRequest\n * @return EnableApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public EnableApiKeyResponse EnableApiKey(EnableApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"EnableApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(GenerateApiDocument)用于自动生成 API 文档和 SDK,一个服务的一个环境生成一份文档和 SDK。\n * @param req GenerateApiDocumentRequest\n * @return GenerateApiDocumentResponse\n * @throws TencentCloudSDKException\n */\n public GenerateApiDocumentResponse GenerateApiDocument(GenerateApiDocumentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"GenerateApiDocument\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 修改 API 文档\n * @param req ModifyAPIDocRequest\n * @return ModifyAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public ModifyAPIDocResponse ModifyAPIDoc(ModifyAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApi)用于修改 API 接口,可调用此接口对已经配置的 API 接口进行编辑修改。修改后的 API 需要重新发布 API 所在的服务到对应环境方能生效。\n * @param req ModifyApiRequest\n * @return ModifyApiResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiResponse ModifyApi(ModifyApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApiApp)用于修改已经创建的应用。\n * @param req ModifyApiAppRequest\n * @return ModifyApiAppResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiAppResponse ModifyApiApp(ModifyApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApiEnvironmentStrategy)用于修改API限流策略\n * @param req ModifyApiEnvironmentStrategyRequest\n * @return ModifyApiEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiEnvironmentStrategyResponse ModifyApiEnvironmentStrategy(ModifyApiEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 提供增量更新API能力,主要是给程序调用(区别于ModifyApi,该接口是需要传入API的全量参数,对console使用较友好)\n * @param req ModifyApiIncrementRequest\n * @return ModifyApiIncrementResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiIncrementResponse ModifyApiIncrement(ModifyApiIncrementRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiIncrement\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyIPStrategy)用于修改服务IP策略。\n * @param req ModifyIPStrategyRequest\n * @return ModifyIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyIPStrategyResponse ModifyIPStrategy(ModifyIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 修改API网关插件。\n * @param req ModifyPluginRequest\n * @return ModifyPluginResponse\n * @throws TencentCloudSDKException\n */\n public ModifyPluginResponse ModifyPlugin(ModifyPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyService)用于修改服务的相关信息。当服务创建后,服务的名称、描述和服务类型均可被修改。\n * @param req ModifyServiceRequest\n * @return ModifyServiceResponse\n * @throws TencentCloudSDKException\n */\n public ModifyServiceResponse ModifyService(ModifyServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyServiceEnvironmentStrategy)用于修改服务限流策略\n * @param req ModifyServiceEnvironmentStrategyRequest\n * @return ModifyServiceEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyServiceEnvironmentStrategyResponse ModifyServiceEnvironmentStrategy(ModifyServiceEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyServiceEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifySubDomain)用于修改服务的自定义域名设置中的路径映射,可以修改绑定自定义域名之前的路径映射规则。\n * @param req ModifySubDomainRequest\n * @return ModifySubDomainResponse\n * @throws TencentCloudSDKException\n */\n public ModifySubDomainResponse ModifySubDomain(ModifySubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifySubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyUsagePlan)用于修改使用计划的名称,描述及 QPS。\n * @param req ModifyUsagePlanRequest\n * @return ModifyUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public ModifyUsagePlanResponse ModifyUsagePlan(ModifyUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ReleaseService)用于发布服务。\n * API 网关的服务创建后,需要发布到某个环境方生效后,使用者才能进行调用,此接口用于发布服务到环境,如 release 环境。\n * @param req ReleaseServiceRequest\n * @return ReleaseServiceResponse\n * @throws TencentCloudSDKException\n */\n public ReleaseServiceResponse ReleaseService(ReleaseServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ReleaseService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 重置API文档密码\n * @param req ResetAPIDocPasswordRequest\n * @return ResetAPIDocPasswordResponse\n * @throws TencentCloudSDKException\n */\n public ResetAPIDocPasswordResponse ResetAPIDocPassword(ResetAPIDocPasswordRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ResetAPIDocPassword\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindEnvironment)用于将使用计划从特定环境解绑。\n * @param req UnBindEnvironmentRequest\n * @return UnBindEnvironmentResponse\n * @throws TencentCloudSDKException\n */\n public UnBindEnvironmentResponse UnBindEnvironment(UnBindEnvironmentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindEnvironment\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindIPStrategy)用于服务解绑IP策略。\n * @param req UnBindIPStrategyRequest\n * @return UnBindIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public UnBindIPStrategyResponse UnBindIPStrategy(UnBindIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindSecretIds)用于为使用计划解绑密钥。\n * @param req UnBindSecretIdsRequest\n * @return UnBindSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public UnBindSecretIdsResponse UnBindSecretIds(UnBindSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindSubDomain)用于解绑自定义域名。\n * 用户使用 API 网关绑定了自定义域名到服务中后,若想要解绑此自定义域名,可使用此接口。\n * @param req UnBindSubDomainRequest\n * @return UnBindSubDomainResponse\n * @throws TencentCloudSDKException\n */\n public UnBindSubDomainResponse UnBindSubDomain(UnBindSubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindSubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnReleaseService)用于下线服务。\n * 用户发布服务到某个环境后,此服务中的 API 方可被调用者进行调用,当用户需要将此服务从发布环境中下线时,可调用此 API。下线后的服务不可被调用。\n * @param req UnReleaseServiceRequest\n * @return UnReleaseServiceResponse\n * @throws TencentCloudSDKException\n */\n ", "post_mask_code": "{\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnReleaseService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnbindApiApp)用于解除应用和API绑定。\n * @param req UnbindApiAppRequest\n * @return UnbindApiAppResponse\n * @throws TencentCloudSDKException\n */\n public UnbindApiAppResponse UnbindApiApp(UnbindApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnbindApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateApiAppKey)用于更新应用秘钥。\n * @param req UpdateApiAppKeyRequest\n * @return UpdateApiAppKeyResponse\n * @throws TencentCloudSDKException\n */\n public UpdateApiAppKeyResponse UpdateApiAppKey(UpdateApiAppKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateApiAppKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateApiKey)用于更换用户已创建的一对 API 密钥。\n * @param req UpdateApiKeyRequest\n * @return UpdateApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public UpdateApiKeyResponse UpdateApiKey(UpdateApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateService)用于从服务发布的环境中运行版本切换到特定版本。用户在使用 API 网关创建服务并发布服务到某个环境后,多因为开发过程会产生多个版本,此时可调用本接口。\n * @param req UpdateServiceRequest\n * @return UpdateServiceResponse\n * @throws TencentCloudSDKException\n */\n public UpdateServiceResponse UpdateService(UpdateServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n}\n"} {"task_id": "Java_1422", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/apigateway/v20180808/ApigatewayClient.java", "mask_start_position": 72375, "mask_end_position": 72439, "canonical_solution": "\n JsonResponseModel rsp = null;", "pre_mask_code": "package com.tencentcloudapi.apigateway.v20180808;\n\nimport java.lang.reflect.Type;\nimport com.google.gson.JsonSyntaxException;\nimport com.google.gson.reflect.TypeToken;\nimport com.tencentcloudapi.common.exception.TencentCloudSDKException;\nimport com.tencentcloudapi.common.AbstractClient;\nimport com.tencentcloudapi.common.profile.ClientProfile;\nimport com.tencentcloudapi.common.JsonResponseModel;\nimport com.tencentcloudapi.common.Credential;\nimport com.tencentcloudapi.apigateway.v20180808.models.*;\n\npublic class ApigatewayClient extends AbstractClient {\n\n private static String endpoint = \"apigateway.tencentcloudapi.com\";\n\n private static String service = \"apigateway\";\n\n private static String version = \"2018-08-08\";\n\n public ApigatewayClient(Credential credential, String region) {\n this(credential, region, new ClientProfile());\n }\n\n public ApigatewayClient(Credential credential, String region, ClientProfile profile) {\n super(ApigatewayClient.endpoint, ApigatewayClient.version, credential, region, profile);\n }\n\n /**\n * 绑定插件到API上。\n * @param req AttachPluginRequest\n * @return AttachPluginResponse\n * @throws TencentCloudSDKException\n */\n public AttachPluginResponse AttachPlugin(AttachPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"AttachPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindApiApp)用于绑定应用到API。\n * @param req BindApiAppRequest\n * @return BindApiAppResponse\n * @throws TencentCloudSDKException\n */\n public BindApiAppResponse BindApiApp(BindApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindEnvironment)用于绑定使用计划到服务或API。\n * 用户在发布服务到某个环境中后,如果 API 需要鉴权,还需要绑定使用计划才能进行调用,此接口用户将使用计划绑定到特定环境。\n * 目前支持绑定使用计划到API,但是同一个服务不能同时存在绑定到服务的使用计划和绑定到API的使用计划,所以对已经绑定过服务级别使用计划的环境,请先使用 服务级别使用计划降级 接口进行降级操作。\n * @param req BindEnvironmentRequest\n * @return BindEnvironmentResponse\n * @throws TencentCloudSDKException\n */\n public BindEnvironmentResponse BindEnvironment(BindEnvironmentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindEnvironment\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindIPStrategy)用于API绑定IP策略。\n * @param req BindIPStrategyRequest\n * @return BindIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public BindIPStrategyResponse BindIPStrategy(BindIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindSecretIds)用于为使用计划绑定密钥。\n * 将密钥绑定到某个使用计划,并将此使用计划绑定到某个服务发布的环境上,调用者方可使用此密钥调用这个服务中的 API,可使用本接口为使用计划绑定密钥。\n * @param req BindSecretIdsRequest\n * @return BindSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public BindSecretIdsResponse BindSecretIds(BindSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindSubDomain)用于绑定自定义域名到服务。\n * API 网关中每个服务都会提供一个默认的域名供用户调用,但当用户想使用自己的已有域名时,也可以将自定义域名绑定到此服务,在做好备案、与默认域名的 CNAME 后,可直接调用自定义域名。\n * @param req BindSubDomainRequest\n * @return BindSubDomainResponse\n * @throws TencentCloudSDKException\n */\n public BindSubDomainResponse BindSubDomain(BindSubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindSubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 构建 API 文档\n * @param req BuildAPIDocRequest\n * @return BuildAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public BuildAPIDocResponse BuildAPIDoc(BuildAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BuildAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 创建 API 文档\n * @param req CreateAPIDocRequest\n * @return CreateAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public CreateAPIDocResponse CreateAPIDoc(CreateAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApi)用于创建 API 接口,创建 API 前,用户需要先创建服务,每个 API 都有自己归属的服务。\n * @param req CreateApiRequest\n * @return CreateApiResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiResponse CreateApi(CreateApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApiApp)用于创建应用。\n * @param req CreateApiAppRequest\n * @return CreateApiAppResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiAppResponse CreateApiApp(CreateApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApiKey)用于创建一对新的 API 密钥。\n * @param req CreateApiKeyRequest\n * @return CreateApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiKeyResponse CreateApiKey(CreateApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateIPStrategy)用于创建服务IP策略。\n * @param req CreateIPStrategyRequest\n * @return CreateIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public CreateIPStrategyResponse CreateIPStrategy(CreateIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 创建API网关插件。\n * @param req CreatePluginRequest\n * @return CreatePluginResponse\n * @throws TencentCloudSDKException\n */\n public CreatePluginResponse CreatePlugin(CreatePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreatePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateService)用于创建服务。\n * API 网关使用的最大单元为服务,每个服务中可创建多个 API 接口。每个服务有一个默认域名供客户调用,用户也可绑定自定义域名到此服务中。\n * @param req CreateServiceRequest\n * @return CreateServiceResponse\n * @throws TencentCloudSDKException\n */\n public CreateServiceResponse CreateService(CreateServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateUsagePlan)用于创建使用计划。\n * 用户在使用 API 网关时,需要创建使用计划并将其绑定到服务的环境中使用。\n * @param req CreateUsagePlanRequest\n * @return CreateUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public CreateUsagePlanResponse CreateUsagePlan(CreateUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 删除 API 文档\n * @param req DeleteAPIDocRequest\n * @return DeleteAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public DeleteAPIDocResponse DeleteAPIDoc(DeleteAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApi)用于删除已经创建的API。\n * @param req DeleteApiRequest\n * @return DeleteApiResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiResponse DeleteApi(DeleteApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApiApp)用于删除已经创建的应用。\n * @param req DeleteApiAppRequest\n * @return DeleteApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiAppResponse DeleteApiApp(DeleteApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApiKey)用于删除一对 API 密钥。\n * @param req DeleteApiKeyRequest\n * @return DeleteApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiKeyResponse DeleteApiKey(DeleteApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteIPStrategy)用于删除服务IP策略。\n * @param req DeleteIPStrategyRequest\n * @return DeleteIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DeleteIPStrategyResponse DeleteIPStrategy(DeleteIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 删除API网关插件\n * @param req DeletePluginRequest\n * @return DeletePluginResponse\n * @throws TencentCloudSDKException\n */\n public DeletePluginResponse DeletePlugin(DeletePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeletePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteService)用于删除 API 网关中某个服务。\n * @param req DeleteServiceRequest\n * @return DeleteServiceResponse\n * @throws TencentCloudSDKException\n */\n public DeleteServiceResponse DeleteService(DeleteServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteServiceSubDomainMapping)用于删除服务中某个环境的自定义域名映射。\n * 当用户使用自定义域名,并使用了自定义映射时,可使用此接口。但需注意,若删除了所有环境的映射时,调用此 API 均会返回失败。\n * @param req DeleteServiceSubDomainMappingRequest\n * @return DeleteServiceSubDomainMappingResponse\n * @throws TencentCloudSDKException\n */\n public DeleteServiceSubDomainMappingResponse DeleteServiceSubDomainMapping(DeleteServiceSubDomainMappingRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteServiceSubDomainMapping\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteUsagePlan)用于删除使用计划。\n * @param req DeleteUsagePlanRequest\n * @return DeleteUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DeleteUsagePlanResponse DeleteUsagePlan(DeleteUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DemoteServiceUsagePlan)用于将某个服务在某个环境的使用计划,降级到API上。\n * 如果服务内没有API不允许进行此操作。\n * 如果当前环境没有发布,不允许进行此操作。\n * @param req DemoteServiceUsagePlanRequest\n * @return DemoteServiceUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DemoteServiceUsagePlanResponse DemoteServiceUsagePlan(DemoteServiceUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DemoteServiceUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询 API 文档详情\n * @param req DescribeAPIDocDetailRequest\n * @return DescribeAPIDocDetailResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAPIDocDetailResponse DescribeAPIDocDetail(DescribeAPIDocDetailRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAPIDocDetail\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询 API 文档列表\n * @param req DescribeAPIDocsRequest\n * @return DescribeAPIDocsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAPIDocsResponse DescribeAPIDocs(DescribeAPIDocsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAPIDocs\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件相关的API列表,包括已绑定的和未绑定的API信息。\n * @param req DescribeAllPluginApisRequest\n * @return DescribeAllPluginApisResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAllPluginApisResponse DescribeAllPluginApis(DescribeAllPluginApisRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAllPluginApis\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApi)用于查询用户 API 网关的 API 接口的详细信息。​\n * @param req DescribeApiRequest\n * @return DescribeApiResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiResponse DescribeApi(DescribeApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiApp)用于根据应用ID搜索应用。\n * @param req DescribeApiAppRequest\n * @return DescribeApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppResponse DescribeApiApp(DescribeApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiAppBindApisStatus)查询应用绑定的Api列表。\n * @param req DescribeApiAppBindApisStatusRequest\n * @return DescribeApiAppBindApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppBindApisStatusResponse DescribeApiAppBindApisStatus(DescribeApiAppBindApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiAppBindApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiAppsStatus)查询应用列表。\n * @param req DescribeApiAppsStatusRequest\n * @return DescribeApiAppsStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppsStatusResponse DescribeApiAppsStatus(DescribeApiAppsStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiAppsStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiBindApiAppsStatus)查询Api绑定的应用列表。\n * @param req DescribeApiBindApiAppsStatusRequest\n * @return DescribeApiBindApiAppsStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiBindApiAppsStatusResponse DescribeApiBindApiAppsStatus(DescribeApiBindApiAppsStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiBindApiAppsStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiEnvironmentStrategy)用于展示API绑定的限流策略。\n * @param req DescribeApiEnvironmentStrategyRequest\n * @return DescribeApiEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiEnvironmentStrategyResponse DescribeApiEnvironmentStrategy(DescribeApiEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiForApiApp)用于应用使用者查询部署于 API 网关的 API 接口的详细信息。​\n * @param req DescribeApiForApiAppRequest\n * @return DescribeApiForApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiForApiAppResponse DescribeApiForApiApp(DescribeApiForApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiForApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiKey)用于查询密钥详情。\n * 用户在创建密钥后,可用此接口查询一个 API 密钥的详情,该接口会显示密钥 Key。\n * @param req DescribeApiKeyRequest\n * @return DescribeApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiKeyResponse DescribeApiKey(DescribeApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiKeysStatus)用于查询密钥列表。\n * 当用户创建了多个密钥对时,可使用本接口查询一个或多个 API 密钥信息,本接口不会显示密钥 Key。\n * @param req DescribeApiKeysStatusRequest\n * @return DescribeApiKeysStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiKeysStatusResponse DescribeApiKeysStatus(DescribeApiKeysStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiKeysStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiUsagePlan)用于查询服务中 API 使用计划详情。\n * 服务若需要鉴权限流生效,则需要绑定使用计划到此服务中,本接口用于查询绑定到一个服务及其中 API 的所有使用计划。\n * @param req DescribeApiUsagePlanRequest\n * @return DescribeApiUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiUsagePlanResponse DescribeApiUsagePlan(DescribeApiUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApisStatus)用于查看一个服务下的某个 API 或所有 API 列表及其相关信息。\n * @param req DescribeApisStatusRequest\n * @return DescribeApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApisStatusResponse DescribeApisStatus(DescribeApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategy)用于查询IP策略详情。\n * @param req DescribeIPStrategyRequest\n * @return DescribeIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategyResponse DescribeIPStrategy(DescribeIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategyApisStatus)用于查询IP策略可以绑定的API列表。即服务下所有API和该策略已绑定API的差集。\n * @param req DescribeIPStrategyApisStatusRequest\n * @return DescribeIPStrategyApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategyApisStatusResponse DescribeIPStrategyApisStatus(DescribeIPStrategyApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategyApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategysStatus)用于查询服务IP策略列表。\n * @param req DescribeIPStrategysStatusRequest\n * @return DescribeIPStrategysStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategysStatusResponse DescribeIPStrategysStatus(DescribeIPStrategysStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategysStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口DescribeLogSearch用于搜索日志\n * @param req DescribeLogSearchRequest\n * @return DescribeLogSearchResponse\n * @throws TencentCloudSDKException\n */\n public DescribeLogSearchResponse DescribeLogSearch(DescribeLogSearchRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeLogSearch\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件详情,支持按照插件ID进行。\n * @param req DescribePluginRequest\n * @return DescribePluginResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginResponse DescribePlugin(DescribePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询指定插件下绑定的API信息\n * @param req DescribePluginApisRequest\n * @return DescribePluginApisResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginApisResponse DescribePluginApis(DescribePluginApisRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePluginApis\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件列表和详情,支持分页,支持按照插件类型查询,支持按照插件ID批量查询,支持按照插件名称查询。\n * @param req DescribePluginsRequest\n * @return DescribePluginsResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginsResponse DescribePlugins(DescribePluginsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePlugins\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeService)用于查询一个服务的详细信息、包括服务的描述、域名、协议、创建时间、发布情况等信息。\n * @param req DescribeServiceRequest\n * @return DescribeServiceResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceResponse DescribeService(DescribeServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentList)用于查询一个服务的环境列表,可查询到此服务下所有环境及其状态。\n * @param req DescribeServiceEnvironmentListRequest\n * @return DescribeServiceEnvironmentListResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentListResponse DescribeServiceEnvironmentList(DescribeServiceEnvironmentListRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentList\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentReleaseHistory)用于查询服务环境的发布历史。\n * 用户在创建好服务后需要发布到某个环境中才能进行使用,本接口用于查询一个服务某个环境的发布记录。\n * @param req DescribeServiceEnvironmentReleaseHistoryRequest\n * @return DescribeServiceEnvironmentReleaseHistoryResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentReleaseHistoryResponse DescribeServiceEnvironmentReleaseHistory(DescribeServiceEnvironmentReleaseHistoryRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentReleaseHistory\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentStrategy)用于展示服务限流策略。\n * @param req DescribeServiceEnvironmentStrategyRequest\n * @return DescribeServiceEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentStrategyResponse DescribeServiceEnvironmentStrategy(DescribeServiceEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceForApiApp)用于应用使用者查询一个服务的详细信息、包括服务的描述、域名、协议等信息。\n * @param req DescribeServiceForApiAppRequest\n * @return DescribeServiceForApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceForApiAppResponse DescribeServiceForApiApp(DescribeServiceForApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceForApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceReleaseVersion)查询一个服务下面所有已经发布的版本列表。\n * 用户在发布服务时,常有多个版本发布,可使用本接口查询已发布的版本。\n * @param req DescribeServiceReleaseVersionRequest\n * @return DescribeServiceReleaseVersionResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceReleaseVersionResponse DescribeServiceReleaseVersion(DescribeServiceReleaseVersionRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceReleaseVersion\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceSubDomainMappings)用于查询自定义域名的路径映射。\n * API 网关可绑定自定义域名到服务,并且可以对自定义域名的路径进行映射,可自定义不同的路径映射到服务中的三个环境,本接口用于查询绑定服务的自定义域名的路径映射列表。\n * @param req DescribeServiceSubDomainMappingsRequest\n * @return DescribeServiceSubDomainMappingsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceSubDomainMappingsResponse DescribeServiceSubDomainMappings(DescribeServiceSubDomainMappingsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceSubDomainMappings\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceSubDomains)用于查询自定义域名列表。\n * API 网关可绑定自定义域名到服务,用于服务调用。此接口用于查询用户绑定在服务的自定义域名列表。\n * @param req DescribeServiceSubDomainsRequest\n * @return DescribeServiceSubDomainsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceSubDomainsResponse DescribeServiceSubDomains(DescribeServiceSubDomainsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceSubDomains\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceUsagePlan)用于查询服务使用计划详情。\n * 服务若需要鉴权限流生效,则需要绑定使用计划到此服务中,本接口用于查询绑定到一个服务的所有使用计划。\n * @param req DescribeServiceUsagePlanRequest\n * @return DescribeServiceUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceUsagePlanResponse DescribeServiceUsagePlan(DescribeServiceUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServicesStatus)用于搜索查询某一个服务或多个服务的列表,并返回服务相关的域名、时间等信息。\n * @param req DescribeServicesStatusRequest\n * @return DescribeServicesStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServicesStatusResponse DescribeServicesStatus(DescribeServicesStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServicesStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlan)用于查询一个使用计划的详细信息,包括名称、QPS、创建时间绑定的环境等。\n * @param req DescribeUsagePlanRequest\n * @return DescribeUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanResponse DescribeUsagePlan(DescribeUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanEnvironments)用于查询使用计划绑定的环境列表。\n * 用户在绑定了某个使用计划到环境后,可使用本接口查询这个使用计划绑定的所有服务的环境。\n * @param req DescribeUsagePlanEnvironmentsRequest\n * @return DescribeUsagePlanEnvironmentsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanEnvironmentsResponse DescribeUsagePlanEnvironments(DescribeUsagePlanEnvironmentsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlanEnvironments\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanSecretIds)用于查询使用计划绑定的密钥列表。\n * 在 API 网关中,一个使用计划可绑定多个密钥对,可使用本接口查询使用计划绑定的密钥列表。\n * @param req DescribeUsagePlanSecretIdsRequest\n * @return DescribeUsagePlanSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanSecretIdsResponse DescribeUsagePlanSecretIds(DescribeUsagePlanSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlanSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanStatus)用于查询使用计划的列表。\n * @param req DescribeUsagePlansStatusRequest\n * @return DescribeUsagePlansStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlansStatusResponse DescribeUsagePlansStatus(DescribeUsagePlansStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlansStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 解除插件与API绑定\n * @param req DetachPluginRequest\n * @return DetachPluginResponse\n * @throws TencentCloudSDKException\n */\n public DetachPluginResponse DetachPlugin(DetachPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DetachPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DisableApiKey)用于禁用一对 API 密钥。\n * @param req DisableApiKeyRequest\n * @return DisableApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DisableApiKeyResponse DisableApiKey(DisableApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DisableApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(EnableApiKey)用于启动一对被禁用的 API 密钥。\n * @param req EnableApiKeyRequest\n * @return EnableApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public EnableApiKeyResponse EnableApiKey(EnableApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"EnableApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(GenerateApiDocument)用于自动生成 API 文档和 SDK,一个服务的一个环境生成一份文档和 SDK。\n * @param req GenerateApiDocumentRequest\n * @return GenerateApiDocumentResponse\n * @throws TencentCloudSDKException\n */\n public GenerateApiDocumentResponse GenerateApiDocument(GenerateApiDocumentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"GenerateApiDocument\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 修改 API 文档\n * @param req ModifyAPIDocRequest\n * @return ModifyAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public ModifyAPIDocResponse ModifyAPIDoc(ModifyAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApi)用于修改 API 接口,可调用此接口对已经配置的 API 接口进行编辑修改。修改后的 API 需要重新发布 API 所在的服务到对应环境方能生效。\n * @param req ModifyApiRequest\n * @return ModifyApiResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiResponse ModifyApi(ModifyApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApiApp)用于修改已经创建的应用。\n * @param req ModifyApiAppRequest\n * @return ModifyApiAppResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiAppResponse ModifyApiApp(ModifyApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApiEnvironmentStrategy)用于修改API限流策略\n * @param req ModifyApiEnvironmentStrategyRequest\n * @return ModifyApiEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiEnvironmentStrategyResponse ModifyApiEnvironmentStrategy(ModifyApiEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 提供增量更新API能力,主要是给程序调用(区别于ModifyApi,该接口是需要传入API的全量参数,对console使用较友好)\n * @param req ModifyApiIncrementRequest\n * @return ModifyApiIncrementResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiIncrementResponse ModifyApiIncrement(ModifyApiIncrementRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiIncrement\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyIPStrategy)用于修改服务IP策略。\n * @param req ModifyIPStrategyRequest\n * @return ModifyIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyIPStrategyResponse ModifyIPStrategy(ModifyIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 修改API网关插件。\n * @param req ModifyPluginRequest\n * @return ModifyPluginResponse\n * @throws TencentCloudSDKException\n */\n public ModifyPluginResponse ModifyPlugin(ModifyPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyService)用于修改服务的相关信息。当服务创建后,服务的名称、描述和服务类型均可被修改。\n * @param req ModifyServiceRequest\n * @return ModifyServiceResponse\n * @throws TencentCloudSDKException\n */\n public ModifyServiceResponse ModifyService(ModifyServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyServiceEnvironmentStrategy)用于修改服务限流策略\n * @param req ModifyServiceEnvironmentStrategyRequest\n * @return ModifyServiceEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyServiceEnvironmentStrategyResponse ModifyServiceEnvironmentStrategy(ModifyServiceEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyServiceEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifySubDomain)用于修改服务的自定义域名设置中的路径映射,可以修改绑定自定义域名之前的路径映射规则。\n * @param req ModifySubDomainRequest\n * @return ModifySubDomainResponse\n * @throws TencentCloudSDKException\n */\n public ModifySubDomainResponse ModifySubDomain(ModifySubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifySubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyUsagePlan)用于修改使用计划的名称,描述及 QPS。\n * @param req ModifyUsagePlanRequest\n * @return ModifyUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public ModifyUsagePlanResponse ModifyUsagePlan(ModifyUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ReleaseService)用于发布服务。\n * API 网关的服务创建后,需要发布到某个环境方生效后,使用者才能进行调用,此接口用于发布服务到环境,如 release 环境。\n * @param req ReleaseServiceRequest\n * @return ReleaseServiceResponse\n * @throws TencentCloudSDKException\n */\n public ReleaseServiceResponse ReleaseService(ReleaseServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ReleaseService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 重置API文档密码\n * @param req ResetAPIDocPasswordRequest\n * @return ResetAPIDocPasswordResponse\n * @throws TencentCloudSDKException\n */\n public ResetAPIDocPasswordResponse ResetAPIDocPassword(ResetAPIDocPasswordRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ResetAPIDocPassword\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindEnvironment)用于将使用计划从特定环境解绑。\n * @param req UnBindEnvironmentRequest\n * @return UnBindEnvironmentResponse\n * @throws TencentCloudSDKException\n */\n public UnBindEnvironmentResponse UnBindEnvironment(UnBindEnvironmentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindEnvironment\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindIPStrategy)用于服务解绑IP策略。\n * @param req UnBindIPStrategyRequest\n * @return UnBindIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public UnBindIPStrategyResponse UnBindIPStrategy(UnBindIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindSecretIds)用于为使用计划解绑密钥。\n * @param req UnBindSecretIdsRequest\n * @return UnBindSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public UnBindSecretIdsResponse UnBindSecretIds(UnBindSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindSubDomain)用于解绑自定义域名。\n * 用户使用 API 网关绑定了自定义域名到服务中后,若想要解绑此自定义域名,可使用此接口。\n * @param req UnBindSubDomainRequest\n * @return UnBindSubDomainResponse\n * @throws TencentCloudSDKException\n */\n public UnBindSubDomainResponse UnBindSubDomain(UnBindSubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindSubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnReleaseService)用于下线服务。\n * 用户发布服务到某个环境后,此服务中的 API 方可被调用者进行调用,当用户需要将此服务从发布环境中下线时,可调用此 API。下线后的服务不可被调用。\n * @param req UnReleaseServiceRequest\n * @return UnReleaseServiceResponse\n * @throws TencentCloudSDKException\n */\n public UnReleaseServiceResponse UnReleaseService(UnReleaseServiceRequest req) throws TencentCloudSDKException {", "post_mask_code": "\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnReleaseService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnbindApiApp)用于解除应用和API绑定。\n * @param req UnbindApiAppRequest\n * @return UnbindApiAppResponse\n * @throws TencentCloudSDKException\n */\n public UnbindApiAppResponse UnbindApiApp(UnbindApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnbindApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateApiAppKey)用于更新应用秘钥。\n * @param req UpdateApiAppKeyRequest\n * @return UpdateApiAppKeyResponse\n * @throws TencentCloudSDKException\n */\n public UpdateApiAppKeyResponse UpdateApiAppKey(UpdateApiAppKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateApiAppKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateApiKey)用于更换用户已创建的一对 API 密钥。\n * @param req UpdateApiKeyRequest\n * @return UpdateApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public UpdateApiKeyResponse UpdateApiKey(UpdateApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateService)用于从服务发布的环境中运行版本切换到特定版本。用户在使用 API 网关创建服务并发布服务到某个环境后,多因为开发过程会产生多个版本,此时可调用本接口。\n * @param req UpdateServiceRequest\n * @return UpdateServiceResponse\n * @throws TencentCloudSDKException\n */\n public UpdateServiceResponse UpdateService(UpdateServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n}\n"} {"task_id": "Java_1423", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/apigateway/v20180808/ApigatewayClient.java", "mask_start_position": 72448, "mask_end_position": 72880, "canonical_solution": "String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnReleaseService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }", "pre_mask_code": "package com.tencentcloudapi.apigateway.v20180808;\n\nimport java.lang.reflect.Type;\nimport com.google.gson.JsonSyntaxException;\nimport com.google.gson.reflect.TypeToken;\nimport com.tencentcloudapi.common.exception.TencentCloudSDKException;\nimport com.tencentcloudapi.common.AbstractClient;\nimport com.tencentcloudapi.common.profile.ClientProfile;\nimport com.tencentcloudapi.common.JsonResponseModel;\nimport com.tencentcloudapi.common.Credential;\nimport com.tencentcloudapi.apigateway.v20180808.models.*;\n\npublic class ApigatewayClient extends AbstractClient {\n\n private static String endpoint = \"apigateway.tencentcloudapi.com\";\n\n private static String service = \"apigateway\";\n\n private static String version = \"2018-08-08\";\n\n public ApigatewayClient(Credential credential, String region) {\n this(credential, region, new ClientProfile());\n }\n\n public ApigatewayClient(Credential credential, String region, ClientProfile profile) {\n super(ApigatewayClient.endpoint, ApigatewayClient.version, credential, region, profile);\n }\n\n /**\n * 绑定插件到API上。\n * @param req AttachPluginRequest\n * @return AttachPluginResponse\n * @throws TencentCloudSDKException\n */\n public AttachPluginResponse AttachPlugin(AttachPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"AttachPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindApiApp)用于绑定应用到API。\n * @param req BindApiAppRequest\n * @return BindApiAppResponse\n * @throws TencentCloudSDKException\n */\n public BindApiAppResponse BindApiApp(BindApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindEnvironment)用于绑定使用计划到服务或API。\n * 用户在发布服务到某个环境中后,如果 API 需要鉴权,还需要绑定使用计划才能进行调用,此接口用户将使用计划绑定到特定环境。\n * 目前支持绑定使用计划到API,但是同一个服务不能同时存在绑定到服务的使用计划和绑定到API的使用计划,所以对已经绑定过服务级别使用计划的环境,请先使用 服务级别使用计划降级 接口进行降级操作。\n * @param req BindEnvironmentRequest\n * @return BindEnvironmentResponse\n * @throws TencentCloudSDKException\n */\n public BindEnvironmentResponse BindEnvironment(BindEnvironmentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindEnvironment\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindIPStrategy)用于API绑定IP策略。\n * @param req BindIPStrategyRequest\n * @return BindIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public BindIPStrategyResponse BindIPStrategy(BindIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindSecretIds)用于为使用计划绑定密钥。\n * 将密钥绑定到某个使用计划,并将此使用计划绑定到某个服务发布的环境上,调用者方可使用此密钥调用这个服务中的 API,可使用本接口为使用计划绑定密钥。\n * @param req BindSecretIdsRequest\n * @return BindSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public BindSecretIdsResponse BindSecretIds(BindSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindSubDomain)用于绑定自定义域名到服务。\n * API 网关中每个服务都会提供一个默认的域名供用户调用,但当用户想使用自己的已有域名时,也可以将自定义域名绑定到此服务,在做好备案、与默认域名的 CNAME 后,可直接调用自定义域名。\n * @param req BindSubDomainRequest\n * @return BindSubDomainResponse\n * @throws TencentCloudSDKException\n */\n public BindSubDomainResponse BindSubDomain(BindSubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindSubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 构建 API 文档\n * @param req BuildAPIDocRequest\n * @return BuildAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public BuildAPIDocResponse BuildAPIDoc(BuildAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BuildAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 创建 API 文档\n * @param req CreateAPIDocRequest\n * @return CreateAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public CreateAPIDocResponse CreateAPIDoc(CreateAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApi)用于创建 API 接口,创建 API 前,用户需要先创建服务,每个 API 都有自己归属的服务。\n * @param req CreateApiRequest\n * @return CreateApiResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiResponse CreateApi(CreateApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApiApp)用于创建应用。\n * @param req CreateApiAppRequest\n * @return CreateApiAppResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiAppResponse CreateApiApp(CreateApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApiKey)用于创建一对新的 API 密钥。\n * @param req CreateApiKeyRequest\n * @return CreateApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiKeyResponse CreateApiKey(CreateApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateIPStrategy)用于创建服务IP策略。\n * @param req CreateIPStrategyRequest\n * @return CreateIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public CreateIPStrategyResponse CreateIPStrategy(CreateIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 创建API网关插件。\n * @param req CreatePluginRequest\n * @return CreatePluginResponse\n * @throws TencentCloudSDKException\n */\n public CreatePluginResponse CreatePlugin(CreatePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreatePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateService)用于创建服务。\n * API 网关使用的最大单元为服务,每个服务中可创建多个 API 接口。每个服务有一个默认域名供客户调用,用户也可绑定自定义域名到此服务中。\n * @param req CreateServiceRequest\n * @return CreateServiceResponse\n * @throws TencentCloudSDKException\n */\n public CreateServiceResponse CreateService(CreateServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateUsagePlan)用于创建使用计划。\n * 用户在使用 API 网关时,需要创建使用计划并将其绑定到服务的环境中使用。\n * @param req CreateUsagePlanRequest\n * @return CreateUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public CreateUsagePlanResponse CreateUsagePlan(CreateUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 删除 API 文档\n * @param req DeleteAPIDocRequest\n * @return DeleteAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public DeleteAPIDocResponse DeleteAPIDoc(DeleteAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApi)用于删除已经创建的API。\n * @param req DeleteApiRequest\n * @return DeleteApiResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiResponse DeleteApi(DeleteApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApiApp)用于删除已经创建的应用。\n * @param req DeleteApiAppRequest\n * @return DeleteApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiAppResponse DeleteApiApp(DeleteApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApiKey)用于删除一对 API 密钥。\n * @param req DeleteApiKeyRequest\n * @return DeleteApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiKeyResponse DeleteApiKey(DeleteApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteIPStrategy)用于删除服务IP策略。\n * @param req DeleteIPStrategyRequest\n * @return DeleteIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DeleteIPStrategyResponse DeleteIPStrategy(DeleteIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 删除API网关插件\n * @param req DeletePluginRequest\n * @return DeletePluginResponse\n * @throws TencentCloudSDKException\n */\n public DeletePluginResponse DeletePlugin(DeletePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeletePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteService)用于删除 API 网关中某个服务。\n * @param req DeleteServiceRequest\n * @return DeleteServiceResponse\n * @throws TencentCloudSDKException\n */\n public DeleteServiceResponse DeleteService(DeleteServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteServiceSubDomainMapping)用于删除服务中某个环境的自定义域名映射。\n * 当用户使用自定义域名,并使用了自定义映射时,可使用此接口。但需注意,若删除了所有环境的映射时,调用此 API 均会返回失败。\n * @param req DeleteServiceSubDomainMappingRequest\n * @return DeleteServiceSubDomainMappingResponse\n * @throws TencentCloudSDKException\n */\n public DeleteServiceSubDomainMappingResponse DeleteServiceSubDomainMapping(DeleteServiceSubDomainMappingRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteServiceSubDomainMapping\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteUsagePlan)用于删除使用计划。\n * @param req DeleteUsagePlanRequest\n * @return DeleteUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DeleteUsagePlanResponse DeleteUsagePlan(DeleteUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DemoteServiceUsagePlan)用于将某个服务在某个环境的使用计划,降级到API上。\n * 如果服务内没有API不允许进行此操作。\n * 如果当前环境没有发布,不允许进行此操作。\n * @param req DemoteServiceUsagePlanRequest\n * @return DemoteServiceUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DemoteServiceUsagePlanResponse DemoteServiceUsagePlan(DemoteServiceUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DemoteServiceUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询 API 文档详情\n * @param req DescribeAPIDocDetailRequest\n * @return DescribeAPIDocDetailResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAPIDocDetailResponse DescribeAPIDocDetail(DescribeAPIDocDetailRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAPIDocDetail\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询 API 文档列表\n * @param req DescribeAPIDocsRequest\n * @return DescribeAPIDocsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAPIDocsResponse DescribeAPIDocs(DescribeAPIDocsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAPIDocs\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件相关的API列表,包括已绑定的和未绑定的API信息。\n * @param req DescribeAllPluginApisRequest\n * @return DescribeAllPluginApisResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAllPluginApisResponse DescribeAllPluginApis(DescribeAllPluginApisRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAllPluginApis\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApi)用于查询用户 API 网关的 API 接口的详细信息。​\n * @param req DescribeApiRequest\n * @return DescribeApiResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiResponse DescribeApi(DescribeApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiApp)用于根据应用ID搜索应用。\n * @param req DescribeApiAppRequest\n * @return DescribeApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppResponse DescribeApiApp(DescribeApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiAppBindApisStatus)查询应用绑定的Api列表。\n * @param req DescribeApiAppBindApisStatusRequest\n * @return DescribeApiAppBindApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppBindApisStatusResponse DescribeApiAppBindApisStatus(DescribeApiAppBindApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiAppBindApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiAppsStatus)查询应用列表。\n * @param req DescribeApiAppsStatusRequest\n * @return DescribeApiAppsStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppsStatusResponse DescribeApiAppsStatus(DescribeApiAppsStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiAppsStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiBindApiAppsStatus)查询Api绑定的应用列表。\n * @param req DescribeApiBindApiAppsStatusRequest\n * @return DescribeApiBindApiAppsStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiBindApiAppsStatusResponse DescribeApiBindApiAppsStatus(DescribeApiBindApiAppsStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiBindApiAppsStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiEnvironmentStrategy)用于展示API绑定的限流策略。\n * @param req DescribeApiEnvironmentStrategyRequest\n * @return DescribeApiEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiEnvironmentStrategyResponse DescribeApiEnvironmentStrategy(DescribeApiEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiForApiApp)用于应用使用者查询部署于 API 网关的 API 接口的详细信息。​\n * @param req DescribeApiForApiAppRequest\n * @return DescribeApiForApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiForApiAppResponse DescribeApiForApiApp(DescribeApiForApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiForApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiKey)用于查询密钥详情。\n * 用户在创建密钥后,可用此接口查询一个 API 密钥的详情,该接口会显示密钥 Key。\n * @param req DescribeApiKeyRequest\n * @return DescribeApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiKeyResponse DescribeApiKey(DescribeApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiKeysStatus)用于查询密钥列表。\n * 当用户创建了多个密钥对时,可使用本接口查询一个或多个 API 密钥信息,本接口不会显示密钥 Key。\n * @param req DescribeApiKeysStatusRequest\n * @return DescribeApiKeysStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiKeysStatusResponse DescribeApiKeysStatus(DescribeApiKeysStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiKeysStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiUsagePlan)用于查询服务中 API 使用计划详情。\n * 服务若需要鉴权限流生效,则需要绑定使用计划到此服务中,本接口用于查询绑定到一个服务及其中 API 的所有使用计划。\n * @param req DescribeApiUsagePlanRequest\n * @return DescribeApiUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiUsagePlanResponse DescribeApiUsagePlan(DescribeApiUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApisStatus)用于查看一个服务下的某个 API 或所有 API 列表及其相关信息。\n * @param req DescribeApisStatusRequest\n * @return DescribeApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApisStatusResponse DescribeApisStatus(DescribeApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategy)用于查询IP策略详情。\n * @param req DescribeIPStrategyRequest\n * @return DescribeIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategyResponse DescribeIPStrategy(DescribeIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategyApisStatus)用于查询IP策略可以绑定的API列表。即服务下所有API和该策略已绑定API的差集。\n * @param req DescribeIPStrategyApisStatusRequest\n * @return DescribeIPStrategyApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategyApisStatusResponse DescribeIPStrategyApisStatus(DescribeIPStrategyApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategyApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategysStatus)用于查询服务IP策略列表。\n * @param req DescribeIPStrategysStatusRequest\n * @return DescribeIPStrategysStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategysStatusResponse DescribeIPStrategysStatus(DescribeIPStrategysStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategysStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口DescribeLogSearch用于搜索日志\n * @param req DescribeLogSearchRequest\n * @return DescribeLogSearchResponse\n * @throws TencentCloudSDKException\n */\n public DescribeLogSearchResponse DescribeLogSearch(DescribeLogSearchRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeLogSearch\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件详情,支持按照插件ID进行。\n * @param req DescribePluginRequest\n * @return DescribePluginResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginResponse DescribePlugin(DescribePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询指定插件下绑定的API信息\n * @param req DescribePluginApisRequest\n * @return DescribePluginApisResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginApisResponse DescribePluginApis(DescribePluginApisRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePluginApis\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件列表和详情,支持分页,支持按照插件类型查询,支持按照插件ID批量查询,支持按照插件名称查询。\n * @param req DescribePluginsRequest\n * @return DescribePluginsResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginsResponse DescribePlugins(DescribePluginsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePlugins\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeService)用于查询一个服务的详细信息、包括服务的描述、域名、协议、创建时间、发布情况等信息。\n * @param req DescribeServiceRequest\n * @return DescribeServiceResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceResponse DescribeService(DescribeServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentList)用于查询一个服务的环境列表,可查询到此服务下所有环境及其状态。\n * @param req DescribeServiceEnvironmentListRequest\n * @return DescribeServiceEnvironmentListResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentListResponse DescribeServiceEnvironmentList(DescribeServiceEnvironmentListRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentList\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentReleaseHistory)用于查询服务环境的发布历史。\n * 用户在创建好服务后需要发布到某个环境中才能进行使用,本接口用于查询一个服务某个环境的发布记录。\n * @param req DescribeServiceEnvironmentReleaseHistoryRequest\n * @return DescribeServiceEnvironmentReleaseHistoryResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentReleaseHistoryResponse DescribeServiceEnvironmentReleaseHistory(DescribeServiceEnvironmentReleaseHistoryRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentReleaseHistory\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentStrategy)用于展示服务限流策略。\n * @param req DescribeServiceEnvironmentStrategyRequest\n * @return DescribeServiceEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentStrategyResponse DescribeServiceEnvironmentStrategy(DescribeServiceEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceForApiApp)用于应用使用者查询一个服务的详细信息、包括服务的描述、域名、协议等信息。\n * @param req DescribeServiceForApiAppRequest\n * @return DescribeServiceForApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceForApiAppResponse DescribeServiceForApiApp(DescribeServiceForApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceForApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceReleaseVersion)查询一个服务下面所有已经发布的版本列表。\n * 用户在发布服务时,常有多个版本发布,可使用本接口查询已发布的版本。\n * @param req DescribeServiceReleaseVersionRequest\n * @return DescribeServiceReleaseVersionResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceReleaseVersionResponse DescribeServiceReleaseVersion(DescribeServiceReleaseVersionRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceReleaseVersion\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceSubDomainMappings)用于查询自定义域名的路径映射。\n * API 网关可绑定自定义域名到服务,并且可以对自定义域名的路径进行映射,可自定义不同的路径映射到服务中的三个环境,本接口用于查询绑定服务的自定义域名的路径映射列表。\n * @param req DescribeServiceSubDomainMappingsRequest\n * @return DescribeServiceSubDomainMappingsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceSubDomainMappingsResponse DescribeServiceSubDomainMappings(DescribeServiceSubDomainMappingsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceSubDomainMappings\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceSubDomains)用于查询自定义域名列表。\n * API 网关可绑定自定义域名到服务,用于服务调用。此接口用于查询用户绑定在服务的自定义域名列表。\n * @param req DescribeServiceSubDomainsRequest\n * @return DescribeServiceSubDomainsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceSubDomainsResponse DescribeServiceSubDomains(DescribeServiceSubDomainsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceSubDomains\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceUsagePlan)用于查询服务使用计划详情。\n * 服务若需要鉴权限流生效,则需要绑定使用计划到此服务中,本接口用于查询绑定到一个服务的所有使用计划。\n * @param req DescribeServiceUsagePlanRequest\n * @return DescribeServiceUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceUsagePlanResponse DescribeServiceUsagePlan(DescribeServiceUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServicesStatus)用于搜索查询某一个服务或多个服务的列表,并返回服务相关的域名、时间等信息。\n * @param req DescribeServicesStatusRequest\n * @return DescribeServicesStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServicesStatusResponse DescribeServicesStatus(DescribeServicesStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServicesStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlan)用于查询一个使用计划的详细信息,包括名称、QPS、创建时间绑定的环境等。\n * @param req DescribeUsagePlanRequest\n * @return DescribeUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanResponse DescribeUsagePlan(DescribeUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanEnvironments)用于查询使用计划绑定的环境列表。\n * 用户在绑定了某个使用计划到环境后,可使用本接口查询这个使用计划绑定的所有服务的环境。\n * @param req DescribeUsagePlanEnvironmentsRequest\n * @return DescribeUsagePlanEnvironmentsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanEnvironmentsResponse DescribeUsagePlanEnvironments(DescribeUsagePlanEnvironmentsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlanEnvironments\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanSecretIds)用于查询使用计划绑定的密钥列表。\n * 在 API 网关中,一个使用计划可绑定多个密钥对,可使用本接口查询使用计划绑定的密钥列表。\n * @param req DescribeUsagePlanSecretIdsRequest\n * @return DescribeUsagePlanSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanSecretIdsResponse DescribeUsagePlanSecretIds(DescribeUsagePlanSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlanSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanStatus)用于查询使用计划的列表。\n * @param req DescribeUsagePlansStatusRequest\n * @return DescribeUsagePlansStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlansStatusResponse DescribeUsagePlansStatus(DescribeUsagePlansStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlansStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 解除插件与API绑定\n * @param req DetachPluginRequest\n * @return DetachPluginResponse\n * @throws TencentCloudSDKException\n */\n public DetachPluginResponse DetachPlugin(DetachPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DetachPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DisableApiKey)用于禁用一对 API 密钥。\n * @param req DisableApiKeyRequest\n * @return DisableApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DisableApiKeyResponse DisableApiKey(DisableApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DisableApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(EnableApiKey)用于启动一对被禁用的 API 密钥。\n * @param req EnableApiKeyRequest\n * @return EnableApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public EnableApiKeyResponse EnableApiKey(EnableApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"EnableApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(GenerateApiDocument)用于自动生成 API 文档和 SDK,一个服务的一个环境生成一份文档和 SDK。\n * @param req GenerateApiDocumentRequest\n * @return GenerateApiDocumentResponse\n * @throws TencentCloudSDKException\n */\n public GenerateApiDocumentResponse GenerateApiDocument(GenerateApiDocumentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"GenerateApiDocument\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 修改 API 文档\n * @param req ModifyAPIDocRequest\n * @return ModifyAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public ModifyAPIDocResponse ModifyAPIDoc(ModifyAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApi)用于修改 API 接口,可调用此接口对已经配置的 API 接口进行编辑修改。修改后的 API 需要重新发布 API 所在的服务到对应环境方能生效。\n * @param req ModifyApiRequest\n * @return ModifyApiResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiResponse ModifyApi(ModifyApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApiApp)用于修改已经创建的应用。\n * @param req ModifyApiAppRequest\n * @return ModifyApiAppResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiAppResponse ModifyApiApp(ModifyApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApiEnvironmentStrategy)用于修改API限流策略\n * @param req ModifyApiEnvironmentStrategyRequest\n * @return ModifyApiEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiEnvironmentStrategyResponse ModifyApiEnvironmentStrategy(ModifyApiEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 提供增量更新API能力,主要是给程序调用(区别于ModifyApi,该接口是需要传入API的全量参数,对console使用较友好)\n * @param req ModifyApiIncrementRequest\n * @return ModifyApiIncrementResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiIncrementResponse ModifyApiIncrement(ModifyApiIncrementRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiIncrement\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyIPStrategy)用于修改服务IP策略。\n * @param req ModifyIPStrategyRequest\n * @return ModifyIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyIPStrategyResponse ModifyIPStrategy(ModifyIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 修改API网关插件。\n * @param req ModifyPluginRequest\n * @return ModifyPluginResponse\n * @throws TencentCloudSDKException\n */\n public ModifyPluginResponse ModifyPlugin(ModifyPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyService)用于修改服务的相关信息。当服务创建后,服务的名称、描述和服务类型均可被修改。\n * @param req ModifyServiceRequest\n * @return ModifyServiceResponse\n * @throws TencentCloudSDKException\n */\n public ModifyServiceResponse ModifyService(ModifyServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyServiceEnvironmentStrategy)用于修改服务限流策略\n * @param req ModifyServiceEnvironmentStrategyRequest\n * @return ModifyServiceEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyServiceEnvironmentStrategyResponse ModifyServiceEnvironmentStrategy(ModifyServiceEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyServiceEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifySubDomain)用于修改服务的自定义域名设置中的路径映射,可以修改绑定自定义域名之前的路径映射规则。\n * @param req ModifySubDomainRequest\n * @return ModifySubDomainResponse\n * @throws TencentCloudSDKException\n */\n public ModifySubDomainResponse ModifySubDomain(ModifySubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifySubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyUsagePlan)用于修改使用计划的名称,描述及 QPS。\n * @param req ModifyUsagePlanRequest\n * @return ModifyUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public ModifyUsagePlanResponse ModifyUsagePlan(ModifyUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ReleaseService)用于发布服务。\n * API 网关的服务创建后,需要发布到某个环境方生效后,使用者才能进行调用,此接口用于发布服务到环境,如 release 环境。\n * @param req ReleaseServiceRequest\n * @return ReleaseServiceResponse\n * @throws TencentCloudSDKException\n */\n public ReleaseServiceResponse ReleaseService(ReleaseServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ReleaseService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 重置API文档密码\n * @param req ResetAPIDocPasswordRequest\n * @return ResetAPIDocPasswordResponse\n * @throws TencentCloudSDKException\n */\n public ResetAPIDocPasswordResponse ResetAPIDocPassword(ResetAPIDocPasswordRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ResetAPIDocPassword\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindEnvironment)用于将使用计划从特定环境解绑。\n * @param req UnBindEnvironmentRequest\n * @return UnBindEnvironmentResponse\n * @throws TencentCloudSDKException\n */\n public UnBindEnvironmentResponse UnBindEnvironment(UnBindEnvironmentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindEnvironment\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindIPStrategy)用于服务解绑IP策略。\n * @param req UnBindIPStrategyRequest\n * @return UnBindIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public UnBindIPStrategyResponse UnBindIPStrategy(UnBindIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindSecretIds)用于为使用计划解绑密钥。\n * @param req UnBindSecretIdsRequest\n * @return UnBindSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public UnBindSecretIdsResponse UnBindSecretIds(UnBindSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindSubDomain)用于解绑自定义域名。\n * 用户使用 API 网关绑定了自定义域名到服务中后,若想要解绑此自定义域名,可使用此接口。\n * @param req UnBindSubDomainRequest\n * @return UnBindSubDomainResponse\n * @throws TencentCloudSDKException\n */\n public UnBindSubDomainResponse UnBindSubDomain(UnBindSubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindSubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnReleaseService)用于下线服务。\n * 用户发布服务到某个环境后,此服务中的 API 方可被调用者进行调用,当用户需要将此服务从发布环境中下线时,可调用此 API。下线后的服务不可被调用。\n * @param req UnReleaseServiceRequest\n * @return UnReleaseServiceResponse\n * @throws TencentCloudSDKException\n */\n public UnReleaseServiceResponse UnReleaseService(UnReleaseServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n ", "post_mask_code": "\n return rsp.response;\n }\n\n /**\n * 本接口(UnbindApiApp)用于解除应用和API绑定。\n * @param req UnbindApiAppRequest\n * @return UnbindApiAppResponse\n * @throws TencentCloudSDKException\n */\n public UnbindApiAppResponse UnbindApiApp(UnbindApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnbindApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateApiAppKey)用于更新应用秘钥。\n * @param req UpdateApiAppKeyRequest\n * @return UpdateApiAppKeyResponse\n * @throws TencentCloudSDKException\n */\n public UpdateApiAppKeyResponse UpdateApiAppKey(UpdateApiAppKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateApiAppKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateApiKey)用于更换用户已创建的一对 API 密钥。\n * @param req UpdateApiKeyRequest\n * @return UpdateApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public UpdateApiKeyResponse UpdateApiKey(UpdateApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateService)用于从服务发布的环境中运行版本切换到特定版本。用户在使用 API 网关创建服务并发布服务到某个环境后,多因为开发过程会产生多个版本,此时可调用本接口。\n * @param req UpdateServiceRequest\n * @return UpdateServiceResponse\n * @throws TencentCloudSDKException\n */\n public UpdateServiceResponse UpdateService(UpdateServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n}\n"} {"task_id": "Java_1424", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/apigateway/v20180808/ApigatewayClient.java", "mask_start_position": 72889, "mask_end_position": 72915, "canonical_solution": "return rsp.response;\n }", "pre_mask_code": "package com.tencentcloudapi.apigateway.v20180808;\n\nimport java.lang.reflect.Type;\nimport com.google.gson.JsonSyntaxException;\nimport com.google.gson.reflect.TypeToken;\nimport com.tencentcloudapi.common.exception.TencentCloudSDKException;\nimport com.tencentcloudapi.common.AbstractClient;\nimport com.tencentcloudapi.common.profile.ClientProfile;\nimport com.tencentcloudapi.common.JsonResponseModel;\nimport com.tencentcloudapi.common.Credential;\nimport com.tencentcloudapi.apigateway.v20180808.models.*;\n\npublic class ApigatewayClient extends AbstractClient {\n\n private static String endpoint = \"apigateway.tencentcloudapi.com\";\n\n private static String service = \"apigateway\";\n\n private static String version = \"2018-08-08\";\n\n public ApigatewayClient(Credential credential, String region) {\n this(credential, region, new ClientProfile());\n }\n\n public ApigatewayClient(Credential credential, String region, ClientProfile profile) {\n super(ApigatewayClient.endpoint, ApigatewayClient.version, credential, region, profile);\n }\n\n /**\n * 绑定插件到API上。\n * @param req AttachPluginRequest\n * @return AttachPluginResponse\n * @throws TencentCloudSDKException\n */\n public AttachPluginResponse AttachPlugin(AttachPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"AttachPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindApiApp)用于绑定应用到API。\n * @param req BindApiAppRequest\n * @return BindApiAppResponse\n * @throws TencentCloudSDKException\n */\n public BindApiAppResponse BindApiApp(BindApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindEnvironment)用于绑定使用计划到服务或API。\n * 用户在发布服务到某个环境中后,如果 API 需要鉴权,还需要绑定使用计划才能进行调用,此接口用户将使用计划绑定到特定环境。\n * 目前支持绑定使用计划到API,但是同一个服务不能同时存在绑定到服务的使用计划和绑定到API的使用计划,所以对已经绑定过服务级别使用计划的环境,请先使用 服务级别使用计划降级 接口进行降级操作。\n * @param req BindEnvironmentRequest\n * @return BindEnvironmentResponse\n * @throws TencentCloudSDKException\n */\n public BindEnvironmentResponse BindEnvironment(BindEnvironmentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindEnvironment\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindIPStrategy)用于API绑定IP策略。\n * @param req BindIPStrategyRequest\n * @return BindIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public BindIPStrategyResponse BindIPStrategy(BindIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindSecretIds)用于为使用计划绑定密钥。\n * 将密钥绑定到某个使用计划,并将此使用计划绑定到某个服务发布的环境上,调用者方可使用此密钥调用这个服务中的 API,可使用本接口为使用计划绑定密钥。\n * @param req BindSecretIdsRequest\n * @return BindSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public BindSecretIdsResponse BindSecretIds(BindSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindSubDomain)用于绑定自定义域名到服务。\n * API 网关中每个服务都会提供一个默认的域名供用户调用,但当用户想使用自己的已有域名时,也可以将自定义域名绑定到此服务,在做好备案、与默认域名的 CNAME 后,可直接调用自定义域名。\n * @param req BindSubDomainRequest\n * @return BindSubDomainResponse\n * @throws TencentCloudSDKException\n */\n public BindSubDomainResponse BindSubDomain(BindSubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindSubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 构建 API 文档\n * @param req BuildAPIDocRequest\n * @return BuildAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public BuildAPIDocResponse BuildAPIDoc(BuildAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BuildAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 创建 API 文档\n * @param req CreateAPIDocRequest\n * @return CreateAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public CreateAPIDocResponse CreateAPIDoc(CreateAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApi)用于创建 API 接口,创建 API 前,用户需要先创建服务,每个 API 都有自己归属的服务。\n * @param req CreateApiRequest\n * @return CreateApiResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiResponse CreateApi(CreateApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApiApp)用于创建应用。\n * @param req CreateApiAppRequest\n * @return CreateApiAppResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiAppResponse CreateApiApp(CreateApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApiKey)用于创建一对新的 API 密钥。\n * @param req CreateApiKeyRequest\n * @return CreateApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiKeyResponse CreateApiKey(CreateApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateIPStrategy)用于创建服务IP策略。\n * @param req CreateIPStrategyRequest\n * @return CreateIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public CreateIPStrategyResponse CreateIPStrategy(CreateIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 创建API网关插件。\n * @param req CreatePluginRequest\n * @return CreatePluginResponse\n * @throws TencentCloudSDKException\n */\n public CreatePluginResponse CreatePlugin(CreatePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreatePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateService)用于创建服务。\n * API 网关使用的最大单元为服务,每个服务中可创建多个 API 接口。每个服务有一个默认域名供客户调用,用户也可绑定自定义域名到此服务中。\n * @param req CreateServiceRequest\n * @return CreateServiceResponse\n * @throws TencentCloudSDKException\n */\n public CreateServiceResponse CreateService(CreateServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateUsagePlan)用于创建使用计划。\n * 用户在使用 API 网关时,需要创建使用计划并将其绑定到服务的环境中使用。\n * @param req CreateUsagePlanRequest\n * @return CreateUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public CreateUsagePlanResponse CreateUsagePlan(CreateUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 删除 API 文档\n * @param req DeleteAPIDocRequest\n * @return DeleteAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public DeleteAPIDocResponse DeleteAPIDoc(DeleteAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApi)用于删除已经创建的API。\n * @param req DeleteApiRequest\n * @return DeleteApiResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiResponse DeleteApi(DeleteApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApiApp)用于删除已经创建的应用。\n * @param req DeleteApiAppRequest\n * @return DeleteApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiAppResponse DeleteApiApp(DeleteApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApiKey)用于删除一对 API 密钥。\n * @param req DeleteApiKeyRequest\n * @return DeleteApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiKeyResponse DeleteApiKey(DeleteApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteIPStrategy)用于删除服务IP策略。\n * @param req DeleteIPStrategyRequest\n * @return DeleteIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DeleteIPStrategyResponse DeleteIPStrategy(DeleteIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 删除API网关插件\n * @param req DeletePluginRequest\n * @return DeletePluginResponse\n * @throws TencentCloudSDKException\n */\n public DeletePluginResponse DeletePlugin(DeletePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeletePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteService)用于删除 API 网关中某个服务。\n * @param req DeleteServiceRequest\n * @return DeleteServiceResponse\n * @throws TencentCloudSDKException\n */\n public DeleteServiceResponse DeleteService(DeleteServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteServiceSubDomainMapping)用于删除服务中某个环境的自定义域名映射。\n * 当用户使用自定义域名,并使用了自定义映射时,可使用此接口。但需注意,若删除了所有环境的映射时,调用此 API 均会返回失败。\n * @param req DeleteServiceSubDomainMappingRequest\n * @return DeleteServiceSubDomainMappingResponse\n * @throws TencentCloudSDKException\n */\n public DeleteServiceSubDomainMappingResponse DeleteServiceSubDomainMapping(DeleteServiceSubDomainMappingRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteServiceSubDomainMapping\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteUsagePlan)用于删除使用计划。\n * @param req DeleteUsagePlanRequest\n * @return DeleteUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DeleteUsagePlanResponse DeleteUsagePlan(DeleteUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DemoteServiceUsagePlan)用于将某个服务在某个环境的使用计划,降级到API上。\n * 如果服务内没有API不允许进行此操作。\n * 如果当前环境没有发布,不允许进行此操作。\n * @param req DemoteServiceUsagePlanRequest\n * @return DemoteServiceUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DemoteServiceUsagePlanResponse DemoteServiceUsagePlan(DemoteServiceUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DemoteServiceUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询 API 文档详情\n * @param req DescribeAPIDocDetailRequest\n * @return DescribeAPIDocDetailResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAPIDocDetailResponse DescribeAPIDocDetail(DescribeAPIDocDetailRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAPIDocDetail\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询 API 文档列表\n * @param req DescribeAPIDocsRequest\n * @return DescribeAPIDocsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAPIDocsResponse DescribeAPIDocs(DescribeAPIDocsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAPIDocs\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件相关的API列表,包括已绑定的和未绑定的API信息。\n * @param req DescribeAllPluginApisRequest\n * @return DescribeAllPluginApisResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAllPluginApisResponse DescribeAllPluginApis(DescribeAllPluginApisRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAllPluginApis\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApi)用于查询用户 API 网关的 API 接口的详细信息。​\n * @param req DescribeApiRequest\n * @return DescribeApiResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiResponse DescribeApi(DescribeApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiApp)用于根据应用ID搜索应用。\n * @param req DescribeApiAppRequest\n * @return DescribeApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppResponse DescribeApiApp(DescribeApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiAppBindApisStatus)查询应用绑定的Api列表。\n * @param req DescribeApiAppBindApisStatusRequest\n * @return DescribeApiAppBindApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppBindApisStatusResponse DescribeApiAppBindApisStatus(DescribeApiAppBindApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiAppBindApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiAppsStatus)查询应用列表。\n * @param req DescribeApiAppsStatusRequest\n * @return DescribeApiAppsStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppsStatusResponse DescribeApiAppsStatus(DescribeApiAppsStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiAppsStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiBindApiAppsStatus)查询Api绑定的应用列表。\n * @param req DescribeApiBindApiAppsStatusRequest\n * @return DescribeApiBindApiAppsStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiBindApiAppsStatusResponse DescribeApiBindApiAppsStatus(DescribeApiBindApiAppsStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiBindApiAppsStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiEnvironmentStrategy)用于展示API绑定的限流策略。\n * @param req DescribeApiEnvironmentStrategyRequest\n * @return DescribeApiEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiEnvironmentStrategyResponse DescribeApiEnvironmentStrategy(DescribeApiEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiForApiApp)用于应用使用者查询部署于 API 网关的 API 接口的详细信息。​\n * @param req DescribeApiForApiAppRequest\n * @return DescribeApiForApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiForApiAppResponse DescribeApiForApiApp(DescribeApiForApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiForApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiKey)用于查询密钥详情。\n * 用户在创建密钥后,可用此接口查询一个 API 密钥的详情,该接口会显示密钥 Key。\n * @param req DescribeApiKeyRequest\n * @return DescribeApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiKeyResponse DescribeApiKey(DescribeApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiKeysStatus)用于查询密钥列表。\n * 当用户创建了多个密钥对时,可使用本接口查询一个或多个 API 密钥信息,本接口不会显示密钥 Key。\n * @param req DescribeApiKeysStatusRequest\n * @return DescribeApiKeysStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiKeysStatusResponse DescribeApiKeysStatus(DescribeApiKeysStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiKeysStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiUsagePlan)用于查询服务中 API 使用计划详情。\n * 服务若需要鉴权限流生效,则需要绑定使用计划到此服务中,本接口用于查询绑定到一个服务及其中 API 的所有使用计划。\n * @param req DescribeApiUsagePlanRequest\n * @return DescribeApiUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiUsagePlanResponse DescribeApiUsagePlan(DescribeApiUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApisStatus)用于查看一个服务下的某个 API 或所有 API 列表及其相关信息。\n * @param req DescribeApisStatusRequest\n * @return DescribeApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApisStatusResponse DescribeApisStatus(DescribeApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategy)用于查询IP策略详情。\n * @param req DescribeIPStrategyRequest\n * @return DescribeIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategyResponse DescribeIPStrategy(DescribeIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategyApisStatus)用于查询IP策略可以绑定的API列表。即服务下所有API和该策略已绑定API的差集。\n * @param req DescribeIPStrategyApisStatusRequest\n * @return DescribeIPStrategyApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategyApisStatusResponse DescribeIPStrategyApisStatus(DescribeIPStrategyApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategyApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategysStatus)用于查询服务IP策略列表。\n * @param req DescribeIPStrategysStatusRequest\n * @return DescribeIPStrategysStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategysStatusResponse DescribeIPStrategysStatus(DescribeIPStrategysStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategysStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口DescribeLogSearch用于搜索日志\n * @param req DescribeLogSearchRequest\n * @return DescribeLogSearchResponse\n * @throws TencentCloudSDKException\n */\n public DescribeLogSearchResponse DescribeLogSearch(DescribeLogSearchRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeLogSearch\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件详情,支持按照插件ID进行。\n * @param req DescribePluginRequest\n * @return DescribePluginResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginResponse DescribePlugin(DescribePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询指定插件下绑定的API信息\n * @param req DescribePluginApisRequest\n * @return DescribePluginApisResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginApisResponse DescribePluginApis(DescribePluginApisRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePluginApis\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件列表和详情,支持分页,支持按照插件类型查询,支持按照插件ID批量查询,支持按照插件名称查询。\n * @param req DescribePluginsRequest\n * @return DescribePluginsResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginsResponse DescribePlugins(DescribePluginsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePlugins\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeService)用于查询一个服务的详细信息、包括服务的描述、域名、协议、创建时间、发布情况等信息。\n * @param req DescribeServiceRequest\n * @return DescribeServiceResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceResponse DescribeService(DescribeServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentList)用于查询一个服务的环境列表,可查询到此服务下所有环境及其状态。\n * @param req DescribeServiceEnvironmentListRequest\n * @return DescribeServiceEnvironmentListResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentListResponse DescribeServiceEnvironmentList(DescribeServiceEnvironmentListRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentList\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentReleaseHistory)用于查询服务环境的发布历史。\n * 用户在创建好服务后需要发布到某个环境中才能进行使用,本接口用于查询一个服务某个环境的发布记录。\n * @param req DescribeServiceEnvironmentReleaseHistoryRequest\n * @return DescribeServiceEnvironmentReleaseHistoryResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentReleaseHistoryResponse DescribeServiceEnvironmentReleaseHistory(DescribeServiceEnvironmentReleaseHistoryRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentReleaseHistory\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentStrategy)用于展示服务限流策略。\n * @param req DescribeServiceEnvironmentStrategyRequest\n * @return DescribeServiceEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentStrategyResponse DescribeServiceEnvironmentStrategy(DescribeServiceEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceForApiApp)用于应用使用者查询一个服务的详细信息、包括服务的描述、域名、协议等信息。\n * @param req DescribeServiceForApiAppRequest\n * @return DescribeServiceForApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceForApiAppResponse DescribeServiceForApiApp(DescribeServiceForApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceForApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceReleaseVersion)查询一个服务下面所有已经发布的版本列表。\n * 用户在发布服务时,常有多个版本发布,可使用本接口查询已发布的版本。\n * @param req DescribeServiceReleaseVersionRequest\n * @return DescribeServiceReleaseVersionResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceReleaseVersionResponse DescribeServiceReleaseVersion(DescribeServiceReleaseVersionRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceReleaseVersion\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceSubDomainMappings)用于查询自定义域名的路径映射。\n * API 网关可绑定自定义域名到服务,并且可以对自定义域名的路径进行映射,可自定义不同的路径映射到服务中的三个环境,本接口用于查询绑定服务的自定义域名的路径映射列表。\n * @param req DescribeServiceSubDomainMappingsRequest\n * @return DescribeServiceSubDomainMappingsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceSubDomainMappingsResponse DescribeServiceSubDomainMappings(DescribeServiceSubDomainMappingsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceSubDomainMappings\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceSubDomains)用于查询自定义域名列表。\n * API 网关可绑定自定义域名到服务,用于服务调用。此接口用于查询用户绑定在服务的自定义域名列表。\n * @param req DescribeServiceSubDomainsRequest\n * @return DescribeServiceSubDomainsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceSubDomainsResponse DescribeServiceSubDomains(DescribeServiceSubDomainsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceSubDomains\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceUsagePlan)用于查询服务使用计划详情。\n * 服务若需要鉴权限流生效,则需要绑定使用计划到此服务中,本接口用于查询绑定到一个服务的所有使用计划。\n * @param req DescribeServiceUsagePlanRequest\n * @return DescribeServiceUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceUsagePlanResponse DescribeServiceUsagePlan(DescribeServiceUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServicesStatus)用于搜索查询某一个服务或多个服务的列表,并返回服务相关的域名、时间等信息。\n * @param req DescribeServicesStatusRequest\n * @return DescribeServicesStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServicesStatusResponse DescribeServicesStatus(DescribeServicesStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServicesStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlan)用于查询一个使用计划的详细信息,包括名称、QPS、创建时间绑定的环境等。\n * @param req DescribeUsagePlanRequest\n * @return DescribeUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanResponse DescribeUsagePlan(DescribeUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanEnvironments)用于查询使用计划绑定的环境列表。\n * 用户在绑定了某个使用计划到环境后,可使用本接口查询这个使用计划绑定的所有服务的环境。\n * @param req DescribeUsagePlanEnvironmentsRequest\n * @return DescribeUsagePlanEnvironmentsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanEnvironmentsResponse DescribeUsagePlanEnvironments(DescribeUsagePlanEnvironmentsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlanEnvironments\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanSecretIds)用于查询使用计划绑定的密钥列表。\n * 在 API 网关中,一个使用计划可绑定多个密钥对,可使用本接口查询使用计划绑定的密钥列表。\n * @param req DescribeUsagePlanSecretIdsRequest\n * @return DescribeUsagePlanSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanSecretIdsResponse DescribeUsagePlanSecretIds(DescribeUsagePlanSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlanSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanStatus)用于查询使用计划的列表。\n * @param req DescribeUsagePlansStatusRequest\n * @return DescribeUsagePlansStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlansStatusResponse DescribeUsagePlansStatus(DescribeUsagePlansStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlansStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 解除插件与API绑定\n * @param req DetachPluginRequest\n * @return DetachPluginResponse\n * @throws TencentCloudSDKException\n */\n public DetachPluginResponse DetachPlugin(DetachPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DetachPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DisableApiKey)用于禁用一对 API 密钥。\n * @param req DisableApiKeyRequest\n * @return DisableApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DisableApiKeyResponse DisableApiKey(DisableApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DisableApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(EnableApiKey)用于启动一对被禁用的 API 密钥。\n * @param req EnableApiKeyRequest\n * @return EnableApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public EnableApiKeyResponse EnableApiKey(EnableApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"EnableApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(GenerateApiDocument)用于自动生成 API 文档和 SDK,一个服务的一个环境生成一份文档和 SDK。\n * @param req GenerateApiDocumentRequest\n * @return GenerateApiDocumentResponse\n * @throws TencentCloudSDKException\n */\n public GenerateApiDocumentResponse GenerateApiDocument(GenerateApiDocumentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"GenerateApiDocument\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 修改 API 文档\n * @param req ModifyAPIDocRequest\n * @return ModifyAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public ModifyAPIDocResponse ModifyAPIDoc(ModifyAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApi)用于修改 API 接口,可调用此接口对已经配置的 API 接口进行编辑修改。修改后的 API 需要重新发布 API 所在的服务到对应环境方能生效。\n * @param req ModifyApiRequest\n * @return ModifyApiResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiResponse ModifyApi(ModifyApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApiApp)用于修改已经创建的应用。\n * @param req ModifyApiAppRequest\n * @return ModifyApiAppResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiAppResponse ModifyApiApp(ModifyApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApiEnvironmentStrategy)用于修改API限流策略\n * @param req ModifyApiEnvironmentStrategyRequest\n * @return ModifyApiEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiEnvironmentStrategyResponse ModifyApiEnvironmentStrategy(ModifyApiEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 提供增量更新API能力,主要是给程序调用(区别于ModifyApi,该接口是需要传入API的全量参数,对console使用较友好)\n * @param req ModifyApiIncrementRequest\n * @return ModifyApiIncrementResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiIncrementResponse ModifyApiIncrement(ModifyApiIncrementRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiIncrement\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyIPStrategy)用于修改服务IP策略。\n * @param req ModifyIPStrategyRequest\n * @return ModifyIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyIPStrategyResponse ModifyIPStrategy(ModifyIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 修改API网关插件。\n * @param req ModifyPluginRequest\n * @return ModifyPluginResponse\n * @throws TencentCloudSDKException\n */\n public ModifyPluginResponse ModifyPlugin(ModifyPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyService)用于修改服务的相关信息。当服务创建后,服务的名称、描述和服务类型均可被修改。\n * @param req ModifyServiceRequest\n * @return ModifyServiceResponse\n * @throws TencentCloudSDKException\n */\n public ModifyServiceResponse ModifyService(ModifyServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyServiceEnvironmentStrategy)用于修改服务限流策略\n * @param req ModifyServiceEnvironmentStrategyRequest\n * @return ModifyServiceEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyServiceEnvironmentStrategyResponse ModifyServiceEnvironmentStrategy(ModifyServiceEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyServiceEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifySubDomain)用于修改服务的自定义域名设置中的路径映射,可以修改绑定自定义域名之前的路径映射规则。\n * @param req ModifySubDomainRequest\n * @return ModifySubDomainResponse\n * @throws TencentCloudSDKException\n */\n public ModifySubDomainResponse ModifySubDomain(ModifySubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifySubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyUsagePlan)用于修改使用计划的名称,描述及 QPS。\n * @param req ModifyUsagePlanRequest\n * @return ModifyUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public ModifyUsagePlanResponse ModifyUsagePlan(ModifyUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ReleaseService)用于发布服务。\n * API 网关的服务创建后,需要发布到某个环境方生效后,使用者才能进行调用,此接口用于发布服务到环境,如 release 环境。\n * @param req ReleaseServiceRequest\n * @return ReleaseServiceResponse\n * @throws TencentCloudSDKException\n */\n public ReleaseServiceResponse ReleaseService(ReleaseServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ReleaseService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 重置API文档密码\n * @param req ResetAPIDocPasswordRequest\n * @return ResetAPIDocPasswordResponse\n * @throws TencentCloudSDKException\n */\n public ResetAPIDocPasswordResponse ResetAPIDocPassword(ResetAPIDocPasswordRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ResetAPIDocPassword\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindEnvironment)用于将使用计划从特定环境解绑。\n * @param req UnBindEnvironmentRequest\n * @return UnBindEnvironmentResponse\n * @throws TencentCloudSDKException\n */\n public UnBindEnvironmentResponse UnBindEnvironment(UnBindEnvironmentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindEnvironment\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindIPStrategy)用于服务解绑IP策略。\n * @param req UnBindIPStrategyRequest\n * @return UnBindIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public UnBindIPStrategyResponse UnBindIPStrategy(UnBindIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindSecretIds)用于为使用计划解绑密钥。\n * @param req UnBindSecretIdsRequest\n * @return UnBindSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public UnBindSecretIdsResponse UnBindSecretIds(UnBindSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindSubDomain)用于解绑自定义域名。\n * 用户使用 API 网关绑定了自定义域名到服务中后,若想要解绑此自定义域名,可使用此接口。\n * @param req UnBindSubDomainRequest\n * @return UnBindSubDomainResponse\n * @throws TencentCloudSDKException\n */\n public UnBindSubDomainResponse UnBindSubDomain(UnBindSubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindSubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnReleaseService)用于下线服务。\n * 用户发布服务到某个环境后,此服务中的 API 方可被调用者进行调用,当用户需要将此服务从发布环境中下线时,可调用此 API。下线后的服务不可被调用。\n * @param req UnReleaseServiceRequest\n * @return UnReleaseServiceResponse\n * @throws TencentCloudSDKException\n */\n public UnReleaseServiceResponse UnReleaseService(UnReleaseServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnReleaseService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n ", "post_mask_code": "\n\n /**\n * 本接口(UnbindApiApp)用于解除应用和API绑定。\n * @param req UnbindApiAppRequest\n * @return UnbindApiAppResponse\n * @throws TencentCloudSDKException\n */\n public UnbindApiAppResponse UnbindApiApp(UnbindApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnbindApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateApiAppKey)用于更新应用秘钥。\n * @param req UpdateApiAppKeyRequest\n * @return UpdateApiAppKeyResponse\n * @throws TencentCloudSDKException\n */\n public UpdateApiAppKeyResponse UpdateApiAppKey(UpdateApiAppKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateApiAppKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateApiKey)用于更换用户已创建的一对 API 密钥。\n * @param req UpdateApiKeyRequest\n * @return UpdateApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public UpdateApiKeyResponse UpdateApiKey(UpdateApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateService)用于从服务发布的环境中运行版本切换到特定版本。用户在使用 API 网关创建服务并发布服务到某个环境后,多因为开发过程会产生多个版本,此时可调用本接口。\n * @param req UpdateServiceRequest\n * @return UpdateServiceResponse\n * @throws TencentCloudSDKException\n */\n public UpdateServiceResponse UpdateService(UpdateServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n}\n"} {"task_id": "Java_1425", "language": "Java", "task_type": "single_line", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/apigateway/v20180808/ApigatewayClient.java", "mask_start_position": 48015, "mask_end_position": 48019, "canonical_solution": "ull;", "pre_mask_code": "package com.tencentcloudapi.apigateway.v20180808;\n\nimport java.lang.reflect.Type;\nimport com.google.gson.JsonSyntaxException;\nimport com.google.gson.reflect.TypeToken;\nimport com.tencentcloudapi.common.exception.TencentCloudSDKException;\nimport com.tencentcloudapi.common.AbstractClient;\nimport com.tencentcloudapi.common.profile.ClientProfile;\nimport com.tencentcloudapi.common.JsonResponseModel;\nimport com.tencentcloudapi.common.Credential;\nimport com.tencentcloudapi.apigateway.v20180808.models.*;\n\npublic class ApigatewayClient extends AbstractClient {\n\n private static String endpoint = \"apigateway.tencentcloudapi.com\";\n\n private static String service = \"apigateway\";\n\n private static String version = \"2018-08-08\";\n\n public ApigatewayClient(Credential credential, String region) {\n this(credential, region, new ClientProfile());\n }\n\n public ApigatewayClient(Credential credential, String region, ClientProfile profile) {\n super(ApigatewayClient.endpoint, ApigatewayClient.version, credential, region, profile);\n }\n\n /**\n * 绑定插件到API上。\n * @param req AttachPluginRequest\n * @return AttachPluginResponse\n * @throws TencentCloudSDKException\n */\n public AttachPluginResponse AttachPlugin(AttachPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"AttachPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindApiApp)用于绑定应用到API。\n * @param req BindApiAppRequest\n * @return BindApiAppResponse\n * @throws TencentCloudSDKException\n */\n public BindApiAppResponse BindApiApp(BindApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindEnvironment)用于绑定使用计划到服务或API。\n * 用户在发布服务到某个环境中后,如果 API 需要鉴权,还需要绑定使用计划才能进行调用,此接口用户将使用计划绑定到特定环境。\n * 目前支持绑定使用计划到API,但是同一个服务不能同时存在绑定到服务的使用计划和绑定到API的使用计划,所以对已经绑定过服务级别使用计划的环境,请先使用 服务级别使用计划降级 接口进行降级操作。\n * @param req BindEnvironmentRequest\n * @return BindEnvironmentResponse\n * @throws TencentCloudSDKException\n */\n public BindEnvironmentResponse BindEnvironment(BindEnvironmentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindEnvironment\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindIPStrategy)用于API绑定IP策略。\n * @param req BindIPStrategyRequest\n * @return BindIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public BindIPStrategyResponse BindIPStrategy(BindIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindSecretIds)用于为使用计划绑定密钥。\n * 将密钥绑定到某个使用计划,并将此使用计划绑定到某个服务发布的环境上,调用者方可使用此密钥调用这个服务中的 API,可使用本接口为使用计划绑定密钥。\n * @param req BindSecretIdsRequest\n * @return BindSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public BindSecretIdsResponse BindSecretIds(BindSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindSubDomain)用于绑定自定义域名到服务。\n * API 网关中每个服务都会提供一个默认的域名供用户调用,但当用户想使用自己的已有域名时,也可以将自定义域名绑定到此服务,在做好备案、与默认域名的 CNAME 后,可直接调用自定义域名。\n * @param req BindSubDomainRequest\n * @return BindSubDomainResponse\n * @throws TencentCloudSDKException\n */\n public BindSubDomainResponse BindSubDomain(BindSubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindSubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 构建 API 文档\n * @param req BuildAPIDocRequest\n * @return BuildAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public BuildAPIDocResponse BuildAPIDoc(BuildAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BuildAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 创建 API 文档\n * @param req CreateAPIDocRequest\n * @return CreateAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public CreateAPIDocResponse CreateAPIDoc(CreateAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApi)用于创建 API 接口,创建 API 前,用户需要先创建服务,每个 API 都有自己归属的服务。\n * @param req CreateApiRequest\n * @return CreateApiResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiResponse CreateApi(CreateApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApiApp)用于创建应用。\n * @param req CreateApiAppRequest\n * @return CreateApiAppResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiAppResponse CreateApiApp(CreateApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApiKey)用于创建一对新的 API 密钥。\n * @param req CreateApiKeyRequest\n * @return CreateApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiKeyResponse CreateApiKey(CreateApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateIPStrategy)用于创建服务IP策略。\n * @param req CreateIPStrategyRequest\n * @return CreateIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public CreateIPStrategyResponse CreateIPStrategy(CreateIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 创建API网关插件。\n * @param req CreatePluginRequest\n * @return CreatePluginResponse\n * @throws TencentCloudSDKException\n */\n public CreatePluginResponse CreatePlugin(CreatePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreatePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateService)用于创建服务。\n * API 网关使用的最大单元为服务,每个服务中可创建多个 API 接口。每个服务有一个默认域名供客户调用,用户也可绑定自定义域名到此服务中。\n * @param req CreateServiceRequest\n * @return CreateServiceResponse\n * @throws TencentCloudSDKException\n */\n public CreateServiceResponse CreateService(CreateServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateUsagePlan)用于创建使用计划。\n * 用户在使用 API 网关时,需要创建使用计划并将其绑定到服务的环境中使用。\n * @param req CreateUsagePlanRequest\n * @return CreateUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public CreateUsagePlanResponse CreateUsagePlan(CreateUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 删除 API 文档\n * @param req DeleteAPIDocRequest\n * @return DeleteAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public DeleteAPIDocResponse DeleteAPIDoc(DeleteAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApi)用于删除已经创建的API。\n * @param req DeleteApiRequest\n * @return DeleteApiResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiResponse DeleteApi(DeleteApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApiApp)用于删除已经创建的应用。\n * @param req DeleteApiAppRequest\n * @return DeleteApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiAppResponse DeleteApiApp(DeleteApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApiKey)用于删除一对 API 密钥。\n * @param req DeleteApiKeyRequest\n * @return DeleteApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiKeyResponse DeleteApiKey(DeleteApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteIPStrategy)用于删除服务IP策略。\n * @param req DeleteIPStrategyRequest\n * @return DeleteIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DeleteIPStrategyResponse DeleteIPStrategy(DeleteIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 删除API网关插件\n * @param req DeletePluginRequest\n * @return DeletePluginResponse\n * @throws TencentCloudSDKException\n */\n public DeletePluginResponse DeletePlugin(DeletePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeletePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteService)用于删除 API 网关中某个服务。\n * @param req DeleteServiceRequest\n * @return DeleteServiceResponse\n * @throws TencentCloudSDKException\n */\n public DeleteServiceResponse DeleteService(DeleteServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteServiceSubDomainMapping)用于删除服务中某个环境的自定义域名映射。\n * 当用户使用自定义域名,并使用了自定义映射时,可使用此接口。但需注意,若删除了所有环境的映射时,调用此 API 均会返回失败。\n * @param req DeleteServiceSubDomainMappingRequest\n * @return DeleteServiceSubDomainMappingResponse\n * @throws TencentCloudSDKException\n */\n public DeleteServiceSubDomainMappingResponse DeleteServiceSubDomainMapping(DeleteServiceSubDomainMappingRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteServiceSubDomainMapping\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteUsagePlan)用于删除使用计划。\n * @param req DeleteUsagePlanRequest\n * @return DeleteUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DeleteUsagePlanResponse DeleteUsagePlan(DeleteUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DemoteServiceUsagePlan)用于将某个服务在某个环境的使用计划,降级到API上。\n * 如果服务内没有API不允许进行此操作。\n * 如果当前环境没有发布,不允许进行此操作。\n * @param req DemoteServiceUsagePlanRequest\n * @return DemoteServiceUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DemoteServiceUsagePlanResponse DemoteServiceUsagePlan(DemoteServiceUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DemoteServiceUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询 API 文档详情\n * @param req DescribeAPIDocDetailRequest\n * @return DescribeAPIDocDetailResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAPIDocDetailResponse DescribeAPIDocDetail(DescribeAPIDocDetailRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAPIDocDetail\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询 API 文档列表\n * @param req DescribeAPIDocsRequest\n * @return DescribeAPIDocsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAPIDocsResponse DescribeAPIDocs(DescribeAPIDocsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAPIDocs\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件相关的API列表,包括已绑定的和未绑定的API信息。\n * @param req DescribeAllPluginApisRequest\n * @return DescribeAllPluginApisResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAllPluginApisResponse DescribeAllPluginApis(DescribeAllPluginApisRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAllPluginApis\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApi)用于查询用户 API 网关的 API 接口的详细信息。​\n * @param req DescribeApiRequest\n * @return DescribeApiResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiResponse DescribeApi(DescribeApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiApp)用于根据应用ID搜索应用。\n * @param req DescribeApiAppRequest\n * @return DescribeApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppResponse DescribeApiApp(DescribeApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiAppBindApisStatus)查询应用绑定的Api列表。\n * @param req DescribeApiAppBindApisStatusRequest\n * @return DescribeApiAppBindApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppBindApisStatusResponse DescribeApiAppBindApisStatus(DescribeApiAppBindApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiAppBindApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiAppsStatus)查询应用列表。\n * @param req DescribeApiAppsStatusRequest\n * @return DescribeApiAppsStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppsStatusResponse DescribeApiAppsStatus(DescribeApiAppsStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiAppsStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiBindApiAppsStatus)查询Api绑定的应用列表。\n * @param req DescribeApiBindApiAppsStatusRequest\n * @return DescribeApiBindApiAppsStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiBindApiAppsStatusResponse DescribeApiBindApiAppsStatus(DescribeApiBindApiAppsStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiBindApiAppsStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiEnvironmentStrategy)用于展示API绑定的限流策略。\n * @param req DescribeApiEnvironmentStrategyRequest\n * @return DescribeApiEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiEnvironmentStrategyResponse DescribeApiEnvironmentStrategy(DescribeApiEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiForApiApp)用于应用使用者查询部署于 API 网关的 API 接口的详细信息。​\n * @param req DescribeApiForApiAppRequest\n * @return DescribeApiForApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiForApiAppResponse DescribeApiForApiApp(DescribeApiForApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiForApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiKey)用于查询密钥详情。\n * 用户在创建密钥后,可用此接口查询一个 API 密钥的详情,该接口会显示密钥 Key。\n * @param req DescribeApiKeyRequest\n * @return DescribeApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiKeyResponse DescribeApiKey(DescribeApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiKeysStatus)用于查询密钥列表。\n * 当用户创建了多个密钥对时,可使用本接口查询一个或多个 API 密钥信息,本接口不会显示密钥 Key。\n * @param req DescribeApiKeysStatusRequest\n * @return DescribeApiKeysStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiKeysStatusResponse DescribeApiKeysStatus(DescribeApiKeysStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiKeysStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiUsagePlan)用于查询服务中 API 使用计划详情。\n * 服务若需要鉴权限流生效,则需要绑定使用计划到此服务中,本接口用于查询绑定到一个服务及其中 API 的所有使用计划。\n * @param req DescribeApiUsagePlanRequest\n * @return DescribeApiUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiUsagePlanResponse DescribeApiUsagePlan(DescribeApiUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApisStatus)用于查看一个服务下的某个 API 或所有 API 列表及其相关信息。\n * @param req DescribeApisStatusRequest\n * @return DescribeApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApisStatusResponse DescribeApisStatus(DescribeApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategy)用于查询IP策略详情。\n * @param req DescribeIPStrategyRequest\n * @return DescribeIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategyResponse DescribeIPStrategy(DescribeIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategyApisStatus)用于查询IP策略可以绑定的API列表。即服务下所有API和该策略已绑定API的差集。\n * @param req DescribeIPStrategyApisStatusRequest\n * @return DescribeIPStrategyApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategyApisStatusResponse DescribeIPStrategyApisStatus(DescribeIPStrategyApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategyApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategysStatus)用于查询服务IP策略列表。\n * @param req DescribeIPStrategysStatusRequest\n * @return DescribeIPStrategysStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategysStatusResponse DescribeIPStrategysStatus(DescribeIPStrategysStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategysStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口DescribeLogSearch用于搜索日志\n * @param req DescribeLogSearchRequest\n * @return DescribeLogSearchResponse\n * @throws TencentCloudSDKException\n */\n public DescribeLogSearchResponse DescribeLogSearch(DescribeLogSearchRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeLogSearch\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件详情,支持按照插件ID进行。\n * @param req DescribePluginRequest\n * @return DescribePluginResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginResponse DescribePlugin(DescribePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询指定插件下绑定的API信息\n * @param req DescribePluginApisRequest\n * @return DescribePluginApisResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginApisResponse DescribePluginApis(DescribePluginApisRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePluginApis\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件列表和详情,支持分页,支持按照插件类型查询,支持按照插件ID批量查询,支持按照插件名称查询。\n * @param req DescribePluginsRequest\n * @return DescribePluginsResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginsResponse DescribePlugins(DescribePluginsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePlugins\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeService)用于查询一个服务的详细信息、包括服务的描述、域名、协议、创建时间、发布情况等信息。\n * @param req DescribeServiceRequest\n * @return DescribeServiceResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceResponse DescribeService(DescribeServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentList)用于查询一个服务的环境列表,可查询到此服务下所有环境及其状态。\n * @param req DescribeServiceEnvironmentListRequest\n * @return DescribeServiceEnvironmentListResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentListResponse DescribeServiceEnvironmentList(DescribeServiceEnvironmentListRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentList\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentReleaseHistory)用于查询服务环境的发布历史。\n * 用户在创建好服务后需要发布到某个环境中才能进行使用,本接口用于查询一个服务某个环境的发布记录。\n * @param req DescribeServiceEnvironmentReleaseHistoryRequest\n * @return DescribeServiceEnvironmentReleaseHistoryResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentReleaseHistoryResponse DescribeServiceEnvironmentReleaseHistory(DescribeServiceEnvironmentReleaseHistoryRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentReleaseHistory\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentStrategy)用于展示服务限流策略。\n * @param req DescribeServiceEnvironmentStrategyRequest\n * @return DescribeServiceEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentStrategyResponse DescribeServiceEnvironmentStrategy(DescribeServiceEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceForApiApp)用于应用使用者查询一个服务的详细信息、包括服务的描述、域名、协议等信息。\n * @param req DescribeServiceForApiAppRequest\n * @return DescribeServiceForApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceForApiAppResponse DescribeServiceForApiApp(DescribeServiceForApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceForApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceReleaseVersion)查询一个服务下面所有已经发布的版本列表。\n * 用户在发布服务时,常有多个版本发布,可使用本接口查询已发布的版本。\n * @param req DescribeServiceReleaseVersionRequest\n * @return DescribeServiceReleaseVersionResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceReleaseVersionResponse DescribeServiceReleaseVersion(DescribeServiceReleaseVersionRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceReleaseVersion\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceSubDomainMappings)用于查询自定义域名的路径映射。\n * API 网关可绑定自定义域名到服务,并且可以对自定义域名的路径进行映射,可自定义不同的路径映射到服务中的三个环境,本接口用于查询绑定服务的自定义域名的路径映射列表。\n * @param req DescribeServiceSubDomainMappingsRequest\n * @return DescribeServiceSubDomainMappingsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceSubDomainMappingsResponse DescribeServiceSubDomainMappings(DescribeServiceSubDomainMappingsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceSubDomainMappings\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceSubDomains)用于查询自定义域名列表。\n * API 网关可绑定自定义域名到服务,用于服务调用。此接口用于查询用户绑定在服务的自定义域名列表。\n * @param req DescribeServiceSubDomainsRequest\n * @return DescribeServiceSubDomainsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceSubDomainsResponse DescribeServiceSubDomains(DescribeServiceSubDomainsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = n", "post_mask_code": "\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceSubDomains\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceUsagePlan)用于查询服务使用计划详情。\n * 服务若需要鉴权限流生效,则需要绑定使用计划到此服务中,本接口用于查询绑定到一个服务的所有使用计划。\n * @param req DescribeServiceUsagePlanRequest\n * @return DescribeServiceUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceUsagePlanResponse DescribeServiceUsagePlan(DescribeServiceUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServicesStatus)用于搜索查询某一个服务或多个服务的列表,并返回服务相关的域名、时间等信息。\n * @param req DescribeServicesStatusRequest\n * @return DescribeServicesStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServicesStatusResponse DescribeServicesStatus(DescribeServicesStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServicesStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlan)用于查询一个使用计划的详细信息,包括名称、QPS、创建时间绑定的环境等。\n * @param req DescribeUsagePlanRequest\n * @return DescribeUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanResponse DescribeUsagePlan(DescribeUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanEnvironments)用于查询使用计划绑定的环境列表。\n * 用户在绑定了某个使用计划到环境后,可使用本接口查询这个使用计划绑定的所有服务的环境。\n * @param req DescribeUsagePlanEnvironmentsRequest\n * @return DescribeUsagePlanEnvironmentsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanEnvironmentsResponse DescribeUsagePlanEnvironments(DescribeUsagePlanEnvironmentsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlanEnvironments\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanSecretIds)用于查询使用计划绑定的密钥列表。\n * 在 API 网关中,一个使用计划可绑定多个密钥对,可使用本接口查询使用计划绑定的密钥列表。\n * @param req DescribeUsagePlanSecretIdsRequest\n * @return DescribeUsagePlanSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanSecretIdsResponse DescribeUsagePlanSecretIds(DescribeUsagePlanSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlanSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanStatus)用于查询使用计划的列表。\n * @param req DescribeUsagePlansStatusRequest\n * @return DescribeUsagePlansStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlansStatusResponse DescribeUsagePlansStatus(DescribeUsagePlansStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlansStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 解除插件与API绑定\n * @param req DetachPluginRequest\n * @return DetachPluginResponse\n * @throws TencentCloudSDKException\n */\n public DetachPluginResponse DetachPlugin(DetachPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DetachPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DisableApiKey)用于禁用一对 API 密钥。\n * @param req DisableApiKeyRequest\n * @return DisableApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DisableApiKeyResponse DisableApiKey(DisableApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DisableApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(EnableApiKey)用于启动一对被禁用的 API 密钥。\n * @param req EnableApiKeyRequest\n * @return EnableApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public EnableApiKeyResponse EnableApiKey(EnableApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"EnableApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(GenerateApiDocument)用于自动生成 API 文档和 SDK,一个服务的一个环境生成一份文档和 SDK。\n * @param req GenerateApiDocumentRequest\n * @return GenerateApiDocumentResponse\n * @throws TencentCloudSDKException\n */\n public GenerateApiDocumentResponse GenerateApiDocument(GenerateApiDocumentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"GenerateApiDocument\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 修改 API 文档\n * @param req ModifyAPIDocRequest\n * @return ModifyAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public ModifyAPIDocResponse ModifyAPIDoc(ModifyAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApi)用于修改 API 接口,可调用此接口对已经配置的 API 接口进行编辑修改。修改后的 API 需要重新发布 API 所在的服务到对应环境方能生效。\n * @param req ModifyApiRequest\n * @return ModifyApiResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiResponse ModifyApi(ModifyApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApiApp)用于修改已经创建的应用。\n * @param req ModifyApiAppRequest\n * @return ModifyApiAppResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiAppResponse ModifyApiApp(ModifyApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApiEnvironmentStrategy)用于修改API限流策略\n * @param req ModifyApiEnvironmentStrategyRequest\n * @return ModifyApiEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiEnvironmentStrategyResponse ModifyApiEnvironmentStrategy(ModifyApiEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 提供增量更新API能力,主要是给程序调用(区别于ModifyApi,该接口是需要传入API的全量参数,对console使用较友好)\n * @param req ModifyApiIncrementRequest\n * @return ModifyApiIncrementResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiIncrementResponse ModifyApiIncrement(ModifyApiIncrementRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiIncrement\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyIPStrategy)用于修改服务IP策略。\n * @param req ModifyIPStrategyRequest\n * @return ModifyIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyIPStrategyResponse ModifyIPStrategy(ModifyIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 修改API网关插件。\n * @param req ModifyPluginRequest\n * @return ModifyPluginResponse\n * @throws TencentCloudSDKException\n */\n public ModifyPluginResponse ModifyPlugin(ModifyPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyService)用于修改服务的相关信息。当服务创建后,服务的名称、描述和服务类型均可被修改。\n * @param req ModifyServiceRequest\n * @return ModifyServiceResponse\n * @throws TencentCloudSDKException\n */\n public ModifyServiceResponse ModifyService(ModifyServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyServiceEnvironmentStrategy)用于修改服务限流策略\n * @param req ModifyServiceEnvironmentStrategyRequest\n * @return ModifyServiceEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyServiceEnvironmentStrategyResponse ModifyServiceEnvironmentStrategy(ModifyServiceEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyServiceEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifySubDomain)用于修改服务的自定义域名设置中的路径映射,可以修改绑定自定义域名之前的路径映射规则。\n * @param req ModifySubDomainRequest\n * @return ModifySubDomainResponse\n * @throws TencentCloudSDKException\n */\n public ModifySubDomainResponse ModifySubDomain(ModifySubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifySubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyUsagePlan)用于修改使用计划的名称,描述及 QPS。\n * @param req ModifyUsagePlanRequest\n * @return ModifyUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public ModifyUsagePlanResponse ModifyUsagePlan(ModifyUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ReleaseService)用于发布服务。\n * API 网关的服务创建后,需要发布到某个环境方生效后,使用者才能进行调用,此接口用于发布服务到环境,如 release 环境。\n * @param req ReleaseServiceRequest\n * @return ReleaseServiceResponse\n * @throws TencentCloudSDKException\n */\n public ReleaseServiceResponse ReleaseService(ReleaseServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ReleaseService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 重置API文档密码\n * @param req ResetAPIDocPasswordRequest\n * @return ResetAPIDocPasswordResponse\n * @throws TencentCloudSDKException\n */\n public ResetAPIDocPasswordResponse ResetAPIDocPassword(ResetAPIDocPasswordRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ResetAPIDocPassword\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindEnvironment)用于将使用计划从特定环境解绑。\n * @param req UnBindEnvironmentRequest\n * @return UnBindEnvironmentResponse\n * @throws TencentCloudSDKException\n */\n public UnBindEnvironmentResponse UnBindEnvironment(UnBindEnvironmentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindEnvironment\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindIPStrategy)用于服务解绑IP策略。\n * @param req UnBindIPStrategyRequest\n * @return UnBindIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public UnBindIPStrategyResponse UnBindIPStrategy(UnBindIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindSecretIds)用于为使用计划解绑密钥。\n * @param req UnBindSecretIdsRequest\n * @return UnBindSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public UnBindSecretIdsResponse UnBindSecretIds(UnBindSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindSubDomain)用于解绑自定义域名。\n * 用户使用 API 网关绑定了自定义域名到服务中后,若想要解绑此自定义域名,可使用此接口。\n * @param req UnBindSubDomainRequest\n * @return UnBindSubDomainResponse\n * @throws TencentCloudSDKException\n */\n public UnBindSubDomainResponse UnBindSubDomain(UnBindSubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindSubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnReleaseService)用于下线服务。\n * 用户发布服务到某个环境后,此服务中的 API 方可被调用者进行调用,当用户需要将此服务从发布环境中下线时,可调用此 API。下线后的服务不可被调用。\n * @param req UnReleaseServiceRequest\n * @return UnReleaseServiceResponse\n * @throws TencentCloudSDKException\n */\n public UnReleaseServiceResponse UnReleaseService(UnReleaseServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnReleaseService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnbindApiApp)用于解除应用和API绑定。\n * @param req UnbindApiAppRequest\n * @return UnbindApiAppResponse\n * @throws TencentCloudSDKException\n */\n public UnbindApiAppResponse UnbindApiApp(UnbindApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnbindApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateApiAppKey)用于更新应用秘钥。\n * @param req UpdateApiAppKeyRequest\n * @return UpdateApiAppKeyResponse\n * @throws TencentCloudSDKException\n */\n public UpdateApiAppKeyResponse UpdateApiAppKey(UpdateApiAppKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateApiAppKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateApiKey)用于更换用户已创建的一对 API 密钥。\n * @param req UpdateApiKeyRequest\n * @return UpdateApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public UpdateApiKeyResponse UpdateApiKey(UpdateApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateService)用于从服务发布的环境中运行版本切换到特定版本。用户在使用 API 网关创建服务并发布服务到某个环境后,多因为开发过程会产生多个版本,此时可调用本接口。\n * @param req UpdateServiceRequest\n * @return UpdateServiceResponse\n * @throws TencentCloudSDKException\n */\n public UpdateServiceResponse UpdateService(UpdateServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n}\n"} {"task_id": "Java_1426", "language": "Java", "task_type": "try_statement", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/apigateway/v20180808/ApigatewayClient.java", "mask_start_position": 52809, "mask_end_position": 53233, "canonical_solution": "try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlanSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }", "pre_mask_code": "package com.tencentcloudapi.apigateway.v20180808;\n\nimport java.lang.reflect.Type;\nimport com.google.gson.JsonSyntaxException;\nimport com.google.gson.reflect.TypeToken;\nimport com.tencentcloudapi.common.exception.TencentCloudSDKException;\nimport com.tencentcloudapi.common.AbstractClient;\nimport com.tencentcloudapi.common.profile.ClientProfile;\nimport com.tencentcloudapi.common.JsonResponseModel;\nimport com.tencentcloudapi.common.Credential;\nimport com.tencentcloudapi.apigateway.v20180808.models.*;\n\npublic class ApigatewayClient extends AbstractClient {\n\n private static String endpoint = \"apigateway.tencentcloudapi.com\";\n\n private static String service = \"apigateway\";\n\n private static String version = \"2018-08-08\";\n\n public ApigatewayClient(Credential credential, String region) {\n this(credential, region, new ClientProfile());\n }\n\n public ApigatewayClient(Credential credential, String region, ClientProfile profile) {\n super(ApigatewayClient.endpoint, ApigatewayClient.version, credential, region, profile);\n }\n\n /**\n * 绑定插件到API上。\n * @param req AttachPluginRequest\n * @return AttachPluginResponse\n * @throws TencentCloudSDKException\n */\n public AttachPluginResponse AttachPlugin(AttachPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"AttachPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindApiApp)用于绑定应用到API。\n * @param req BindApiAppRequest\n * @return BindApiAppResponse\n * @throws TencentCloudSDKException\n */\n public BindApiAppResponse BindApiApp(BindApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindEnvironment)用于绑定使用计划到服务或API。\n * 用户在发布服务到某个环境中后,如果 API 需要鉴权,还需要绑定使用计划才能进行调用,此接口用户将使用计划绑定到特定环境。\n * 目前支持绑定使用计划到API,但是同一个服务不能同时存在绑定到服务的使用计划和绑定到API的使用计划,所以对已经绑定过服务级别使用计划的环境,请先使用 服务级别使用计划降级 接口进行降级操作。\n * @param req BindEnvironmentRequest\n * @return BindEnvironmentResponse\n * @throws TencentCloudSDKException\n */\n public BindEnvironmentResponse BindEnvironment(BindEnvironmentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindEnvironment\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindIPStrategy)用于API绑定IP策略。\n * @param req BindIPStrategyRequest\n * @return BindIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public BindIPStrategyResponse BindIPStrategy(BindIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindSecretIds)用于为使用计划绑定密钥。\n * 将密钥绑定到某个使用计划,并将此使用计划绑定到某个服务发布的环境上,调用者方可使用此密钥调用这个服务中的 API,可使用本接口为使用计划绑定密钥。\n * @param req BindSecretIdsRequest\n * @return BindSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public BindSecretIdsResponse BindSecretIds(BindSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(BindSubDomain)用于绑定自定义域名到服务。\n * API 网关中每个服务都会提供一个默认的域名供用户调用,但当用户想使用自己的已有域名时,也可以将自定义域名绑定到此服务,在做好备案、与默认域名的 CNAME 后,可直接调用自定义域名。\n * @param req BindSubDomainRequest\n * @return BindSubDomainResponse\n * @throws TencentCloudSDKException\n */\n public BindSubDomainResponse BindSubDomain(BindSubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BindSubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 构建 API 文档\n * @param req BuildAPIDocRequest\n * @return BuildAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public BuildAPIDocResponse BuildAPIDoc(BuildAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"BuildAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 创建 API 文档\n * @param req CreateAPIDocRequest\n * @return CreateAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public CreateAPIDocResponse CreateAPIDoc(CreateAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApi)用于创建 API 接口,创建 API 前,用户需要先创建服务,每个 API 都有自己归属的服务。\n * @param req CreateApiRequest\n * @return CreateApiResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiResponse CreateApi(CreateApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApiApp)用于创建应用。\n * @param req CreateApiAppRequest\n * @return CreateApiAppResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiAppResponse CreateApiApp(CreateApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateApiKey)用于创建一对新的 API 密钥。\n * @param req CreateApiKeyRequest\n * @return CreateApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public CreateApiKeyResponse CreateApiKey(CreateApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateIPStrategy)用于创建服务IP策略。\n * @param req CreateIPStrategyRequest\n * @return CreateIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public CreateIPStrategyResponse CreateIPStrategy(CreateIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 创建API网关插件。\n * @param req CreatePluginRequest\n * @return CreatePluginResponse\n * @throws TencentCloudSDKException\n */\n public CreatePluginResponse CreatePlugin(CreatePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreatePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateService)用于创建服务。\n * API 网关使用的最大单元为服务,每个服务中可创建多个 API 接口。每个服务有一个默认域名供客户调用,用户也可绑定自定义域名到此服务中。\n * @param req CreateServiceRequest\n * @return CreateServiceResponse\n * @throws TencentCloudSDKException\n */\n public CreateServiceResponse CreateService(CreateServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(CreateUsagePlan)用于创建使用计划。\n * 用户在使用 API 网关时,需要创建使用计划并将其绑定到服务的环境中使用。\n * @param req CreateUsagePlanRequest\n * @return CreateUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public CreateUsagePlanResponse CreateUsagePlan(CreateUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"CreateUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 删除 API 文档\n * @param req DeleteAPIDocRequest\n * @return DeleteAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public DeleteAPIDocResponse DeleteAPIDoc(DeleteAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApi)用于删除已经创建的API。\n * @param req DeleteApiRequest\n * @return DeleteApiResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiResponse DeleteApi(DeleteApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApiApp)用于删除已经创建的应用。\n * @param req DeleteApiAppRequest\n * @return DeleteApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiAppResponse DeleteApiApp(DeleteApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteApiKey)用于删除一对 API 密钥。\n * @param req DeleteApiKeyRequest\n * @return DeleteApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DeleteApiKeyResponse DeleteApiKey(DeleteApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteIPStrategy)用于删除服务IP策略。\n * @param req DeleteIPStrategyRequest\n * @return DeleteIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DeleteIPStrategyResponse DeleteIPStrategy(DeleteIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 删除API网关插件\n * @param req DeletePluginRequest\n * @return DeletePluginResponse\n * @throws TencentCloudSDKException\n */\n public DeletePluginResponse DeletePlugin(DeletePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeletePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteService)用于删除 API 网关中某个服务。\n * @param req DeleteServiceRequest\n * @return DeleteServiceResponse\n * @throws TencentCloudSDKException\n */\n public DeleteServiceResponse DeleteService(DeleteServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteServiceSubDomainMapping)用于删除服务中某个环境的自定义域名映射。\n * 当用户使用自定义域名,并使用了自定义映射时,可使用此接口。但需注意,若删除了所有环境的映射时,调用此 API 均会返回失败。\n * @param req DeleteServiceSubDomainMappingRequest\n * @return DeleteServiceSubDomainMappingResponse\n * @throws TencentCloudSDKException\n */\n public DeleteServiceSubDomainMappingResponse DeleteServiceSubDomainMapping(DeleteServiceSubDomainMappingRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteServiceSubDomainMapping\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DeleteUsagePlan)用于删除使用计划。\n * @param req DeleteUsagePlanRequest\n * @return DeleteUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DeleteUsagePlanResponse DeleteUsagePlan(DeleteUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DeleteUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DemoteServiceUsagePlan)用于将某个服务在某个环境的使用计划,降级到API上。\n * 如果服务内没有API不允许进行此操作。\n * 如果当前环境没有发布,不允许进行此操作。\n * @param req DemoteServiceUsagePlanRequest\n * @return DemoteServiceUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DemoteServiceUsagePlanResponse DemoteServiceUsagePlan(DemoteServiceUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DemoteServiceUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询 API 文档详情\n * @param req DescribeAPIDocDetailRequest\n * @return DescribeAPIDocDetailResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAPIDocDetailResponse DescribeAPIDocDetail(DescribeAPIDocDetailRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAPIDocDetail\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询 API 文档列表\n * @param req DescribeAPIDocsRequest\n * @return DescribeAPIDocsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAPIDocsResponse DescribeAPIDocs(DescribeAPIDocsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAPIDocs\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件相关的API列表,包括已绑定的和未绑定的API信息。\n * @param req DescribeAllPluginApisRequest\n * @return DescribeAllPluginApisResponse\n * @throws TencentCloudSDKException\n */\n public DescribeAllPluginApisResponse DescribeAllPluginApis(DescribeAllPluginApisRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeAllPluginApis\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApi)用于查询用户 API 网关的 API 接口的详细信息。​\n * @param req DescribeApiRequest\n * @return DescribeApiResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiResponse DescribeApi(DescribeApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiApp)用于根据应用ID搜索应用。\n * @param req DescribeApiAppRequest\n * @return DescribeApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppResponse DescribeApiApp(DescribeApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiAppBindApisStatus)查询应用绑定的Api列表。\n * @param req DescribeApiAppBindApisStatusRequest\n * @return DescribeApiAppBindApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppBindApisStatusResponse DescribeApiAppBindApisStatus(DescribeApiAppBindApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiAppBindApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiAppsStatus)查询应用列表。\n * @param req DescribeApiAppsStatusRequest\n * @return DescribeApiAppsStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiAppsStatusResponse DescribeApiAppsStatus(DescribeApiAppsStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiAppsStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiBindApiAppsStatus)查询Api绑定的应用列表。\n * @param req DescribeApiBindApiAppsStatusRequest\n * @return DescribeApiBindApiAppsStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiBindApiAppsStatusResponse DescribeApiBindApiAppsStatus(DescribeApiBindApiAppsStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiBindApiAppsStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiEnvironmentStrategy)用于展示API绑定的限流策略。\n * @param req DescribeApiEnvironmentStrategyRequest\n * @return DescribeApiEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiEnvironmentStrategyResponse DescribeApiEnvironmentStrategy(DescribeApiEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiForApiApp)用于应用使用者查询部署于 API 网关的 API 接口的详细信息。​\n * @param req DescribeApiForApiAppRequest\n * @return DescribeApiForApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiForApiAppResponse DescribeApiForApiApp(DescribeApiForApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiForApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiKey)用于查询密钥详情。\n * 用户在创建密钥后,可用此接口查询一个 API 密钥的详情,该接口会显示密钥 Key。\n * @param req DescribeApiKeyRequest\n * @return DescribeApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiKeyResponse DescribeApiKey(DescribeApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiKeysStatus)用于查询密钥列表。\n * 当用户创建了多个密钥对时,可使用本接口查询一个或多个 API 密钥信息,本接口不会显示密钥 Key。\n * @param req DescribeApiKeysStatusRequest\n * @return DescribeApiKeysStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiKeysStatusResponse DescribeApiKeysStatus(DescribeApiKeysStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiKeysStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApiUsagePlan)用于查询服务中 API 使用计划详情。\n * 服务若需要鉴权限流生效,则需要绑定使用计划到此服务中,本接口用于查询绑定到一个服务及其中 API 的所有使用计划。\n * @param req DescribeApiUsagePlanRequest\n * @return DescribeApiUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApiUsagePlanResponse DescribeApiUsagePlan(DescribeApiUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApiUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeApisStatus)用于查看一个服务下的某个 API 或所有 API 列表及其相关信息。\n * @param req DescribeApisStatusRequest\n * @return DescribeApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeApisStatusResponse DescribeApisStatus(DescribeApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategy)用于查询IP策略详情。\n * @param req DescribeIPStrategyRequest\n * @return DescribeIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategyResponse DescribeIPStrategy(DescribeIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategyApisStatus)用于查询IP策略可以绑定的API列表。即服务下所有API和该策略已绑定API的差集。\n * @param req DescribeIPStrategyApisStatusRequest\n * @return DescribeIPStrategyApisStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategyApisStatusResponse DescribeIPStrategyApisStatus(DescribeIPStrategyApisStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategyApisStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeIPStrategysStatus)用于查询服务IP策略列表。\n * @param req DescribeIPStrategysStatusRequest\n * @return DescribeIPStrategysStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeIPStrategysStatusResponse DescribeIPStrategysStatus(DescribeIPStrategysStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeIPStrategysStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口DescribeLogSearch用于搜索日志\n * @param req DescribeLogSearchRequest\n * @return DescribeLogSearchResponse\n * @throws TencentCloudSDKException\n */\n public DescribeLogSearchResponse DescribeLogSearch(DescribeLogSearchRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeLogSearch\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件详情,支持按照插件ID进行。\n * @param req DescribePluginRequest\n * @return DescribePluginResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginResponse DescribePlugin(DescribePluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 查询指定插件下绑定的API信息\n * @param req DescribePluginApisRequest\n * @return DescribePluginApisResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginApisResponse DescribePluginApis(DescribePluginApisRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePluginApis\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 展示插件列表和详情,支持分页,支持按照插件类型查询,支持按照插件ID批量查询,支持按照插件名称查询。\n * @param req DescribePluginsRequest\n * @return DescribePluginsResponse\n * @throws TencentCloudSDKException\n */\n public DescribePluginsResponse DescribePlugins(DescribePluginsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribePlugins\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeService)用于查询一个服务的详细信息、包括服务的描述、域名、协议、创建时间、发布情况等信息。\n * @param req DescribeServiceRequest\n * @return DescribeServiceResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceResponse DescribeService(DescribeServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentList)用于查询一个服务的环境列表,可查询到此服务下所有环境及其状态。\n * @param req DescribeServiceEnvironmentListRequest\n * @return DescribeServiceEnvironmentListResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentListResponse DescribeServiceEnvironmentList(DescribeServiceEnvironmentListRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentList\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentReleaseHistory)用于查询服务环境的发布历史。\n * 用户在创建好服务后需要发布到某个环境中才能进行使用,本接口用于查询一个服务某个环境的发布记录。\n * @param req DescribeServiceEnvironmentReleaseHistoryRequest\n * @return DescribeServiceEnvironmentReleaseHistoryResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentReleaseHistoryResponse DescribeServiceEnvironmentReleaseHistory(DescribeServiceEnvironmentReleaseHistoryRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentReleaseHistory\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceEnvironmentStrategy)用于展示服务限流策略。\n * @param req DescribeServiceEnvironmentStrategyRequest\n * @return DescribeServiceEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceEnvironmentStrategyResponse DescribeServiceEnvironmentStrategy(DescribeServiceEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceForApiApp)用于应用使用者查询一个服务的详细信息、包括服务的描述、域名、协议等信息。\n * @param req DescribeServiceForApiAppRequest\n * @return DescribeServiceForApiAppResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceForApiAppResponse DescribeServiceForApiApp(DescribeServiceForApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceForApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceReleaseVersion)查询一个服务下面所有已经发布的版本列表。\n * 用户在发布服务时,常有多个版本发布,可使用本接口查询已发布的版本。\n * @param req DescribeServiceReleaseVersionRequest\n * @return DescribeServiceReleaseVersionResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceReleaseVersionResponse DescribeServiceReleaseVersion(DescribeServiceReleaseVersionRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceReleaseVersion\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceSubDomainMappings)用于查询自定义域名的路径映射。\n * API 网关可绑定自定义域名到服务,并且可以对自定义域名的路径进行映射,可自定义不同的路径映射到服务中的三个环境,本接口用于查询绑定服务的自定义域名的路径映射列表。\n * @param req DescribeServiceSubDomainMappingsRequest\n * @return DescribeServiceSubDomainMappingsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceSubDomainMappingsResponse DescribeServiceSubDomainMappings(DescribeServiceSubDomainMappingsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceSubDomainMappings\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceSubDomains)用于查询自定义域名列表。\n * API 网关可绑定自定义域名到服务,用于服务调用。此接口用于查询用户绑定在服务的自定义域名列表。\n * @param req DescribeServiceSubDomainsRequest\n * @return DescribeServiceSubDomainsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceSubDomainsResponse DescribeServiceSubDomains(DescribeServiceSubDomainsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceSubDomains\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServiceUsagePlan)用于查询服务使用计划详情。\n * 服务若需要鉴权限流生效,则需要绑定使用计划到此服务中,本接口用于查询绑定到一个服务的所有使用计划。\n * @param req DescribeServiceUsagePlanRequest\n * @return DescribeServiceUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServiceUsagePlanResponse DescribeServiceUsagePlan(DescribeServiceUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServiceUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeServicesStatus)用于搜索查询某一个服务或多个服务的列表,并返回服务相关的域名、时间等信息。\n * @param req DescribeServicesStatusRequest\n * @return DescribeServicesStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeServicesStatusResponse DescribeServicesStatus(DescribeServicesStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeServicesStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlan)用于查询一个使用计划的详细信息,包括名称、QPS、创建时间绑定的环境等。\n * @param req DescribeUsagePlanRequest\n * @return DescribeUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanResponse DescribeUsagePlan(DescribeUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanEnvironments)用于查询使用计划绑定的环境列表。\n * 用户在绑定了某个使用计划到环境后,可使用本接口查询这个使用计划绑定的所有服务的环境。\n * @param req DescribeUsagePlanEnvironmentsRequest\n * @return DescribeUsagePlanEnvironmentsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanEnvironmentsResponse DescribeUsagePlanEnvironments(DescribeUsagePlanEnvironmentsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlanEnvironments\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanSecretIds)用于查询使用计划绑定的密钥列表。\n * 在 API 网关中,一个使用计划可绑定多个密钥对,可使用本接口查询使用计划绑定的密钥列表。\n * @param req DescribeUsagePlanSecretIdsRequest\n * @return DescribeUsagePlanSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlanSecretIdsResponse DescribeUsagePlanSecretIds(DescribeUsagePlanSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n ", "post_mask_code": "\n return rsp.response;\n }\n\n /**\n * 本接口(DescribeUsagePlanStatus)用于查询使用计划的列表。\n * @param req DescribeUsagePlansStatusRequest\n * @return DescribeUsagePlansStatusResponse\n * @throws TencentCloudSDKException\n */\n public DescribeUsagePlansStatusResponse DescribeUsagePlansStatus(DescribeUsagePlansStatusRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DescribeUsagePlansStatus\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 解除插件与API绑定\n * @param req DetachPluginRequest\n * @return DetachPluginResponse\n * @throws TencentCloudSDKException\n */\n public DetachPluginResponse DetachPlugin(DetachPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DetachPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(DisableApiKey)用于禁用一对 API 密钥。\n * @param req DisableApiKeyRequest\n * @return DisableApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public DisableApiKeyResponse DisableApiKey(DisableApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"DisableApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(EnableApiKey)用于启动一对被禁用的 API 密钥。\n * @param req EnableApiKeyRequest\n * @return EnableApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public EnableApiKeyResponse EnableApiKey(EnableApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"EnableApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(GenerateApiDocument)用于自动生成 API 文档和 SDK,一个服务的一个环境生成一份文档和 SDK。\n * @param req GenerateApiDocumentRequest\n * @return GenerateApiDocumentResponse\n * @throws TencentCloudSDKException\n */\n public GenerateApiDocumentResponse GenerateApiDocument(GenerateApiDocumentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"GenerateApiDocument\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 修改 API 文档\n * @param req ModifyAPIDocRequest\n * @return ModifyAPIDocResponse\n * @throws TencentCloudSDKException\n */\n public ModifyAPIDocResponse ModifyAPIDoc(ModifyAPIDocRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyAPIDoc\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApi)用于修改 API 接口,可调用此接口对已经配置的 API 接口进行编辑修改。修改后的 API 需要重新发布 API 所在的服务到对应环境方能生效。\n * @param req ModifyApiRequest\n * @return ModifyApiResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiResponse ModifyApi(ModifyApiRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApi\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApiApp)用于修改已经创建的应用。\n * @param req ModifyApiAppRequest\n * @return ModifyApiAppResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiAppResponse ModifyApiApp(ModifyApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyApiEnvironmentStrategy)用于修改API限流策略\n * @param req ModifyApiEnvironmentStrategyRequest\n * @return ModifyApiEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiEnvironmentStrategyResponse ModifyApiEnvironmentStrategy(ModifyApiEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 提供增量更新API能力,主要是给程序调用(区别于ModifyApi,该接口是需要传入API的全量参数,对console使用较友好)\n * @param req ModifyApiIncrementRequest\n * @return ModifyApiIncrementResponse\n * @throws TencentCloudSDKException\n */\n public ModifyApiIncrementResponse ModifyApiIncrement(ModifyApiIncrementRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyApiIncrement\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyIPStrategy)用于修改服务IP策略。\n * @param req ModifyIPStrategyRequest\n * @return ModifyIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyIPStrategyResponse ModifyIPStrategy(ModifyIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 修改API网关插件。\n * @param req ModifyPluginRequest\n * @return ModifyPluginResponse\n * @throws TencentCloudSDKException\n */\n public ModifyPluginResponse ModifyPlugin(ModifyPluginRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyPlugin\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyService)用于修改服务的相关信息。当服务创建后,服务的名称、描述和服务类型均可被修改。\n * @param req ModifyServiceRequest\n * @return ModifyServiceResponse\n * @throws TencentCloudSDKException\n */\n public ModifyServiceResponse ModifyService(ModifyServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyServiceEnvironmentStrategy)用于修改服务限流策略\n * @param req ModifyServiceEnvironmentStrategyRequest\n * @return ModifyServiceEnvironmentStrategyResponse\n * @throws TencentCloudSDKException\n */\n public ModifyServiceEnvironmentStrategyResponse ModifyServiceEnvironmentStrategy(ModifyServiceEnvironmentStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyServiceEnvironmentStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifySubDomain)用于修改服务的自定义域名设置中的路径映射,可以修改绑定自定义域名之前的路径映射规则。\n * @param req ModifySubDomainRequest\n * @return ModifySubDomainResponse\n * @throws TencentCloudSDKException\n */\n public ModifySubDomainResponse ModifySubDomain(ModifySubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifySubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ModifyUsagePlan)用于修改使用计划的名称,描述及 QPS。\n * @param req ModifyUsagePlanRequest\n * @return ModifyUsagePlanResponse\n * @throws TencentCloudSDKException\n */\n public ModifyUsagePlanResponse ModifyUsagePlan(ModifyUsagePlanRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ModifyUsagePlan\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(ReleaseService)用于发布服务。\n * API 网关的服务创建后,需要发布到某个环境方生效后,使用者才能进行调用,此接口用于发布服务到环境,如 release 环境。\n * @param req ReleaseServiceRequest\n * @return ReleaseServiceResponse\n * @throws TencentCloudSDKException\n */\n public ReleaseServiceResponse ReleaseService(ReleaseServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ReleaseService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 重置API文档密码\n * @param req ResetAPIDocPasswordRequest\n * @return ResetAPIDocPasswordResponse\n * @throws TencentCloudSDKException\n */\n public ResetAPIDocPasswordResponse ResetAPIDocPassword(ResetAPIDocPasswordRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"ResetAPIDocPassword\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindEnvironment)用于将使用计划从特定环境解绑。\n * @param req UnBindEnvironmentRequest\n * @return UnBindEnvironmentResponse\n * @throws TencentCloudSDKException\n */\n public UnBindEnvironmentResponse UnBindEnvironment(UnBindEnvironmentRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindEnvironment\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindIPStrategy)用于服务解绑IP策略。\n * @param req UnBindIPStrategyRequest\n * @return UnBindIPStrategyResponse\n * @throws TencentCloudSDKException\n */\n public UnBindIPStrategyResponse UnBindIPStrategy(UnBindIPStrategyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindIPStrategy\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindSecretIds)用于为使用计划解绑密钥。\n * @param req UnBindSecretIdsRequest\n * @return UnBindSecretIdsResponse\n * @throws TencentCloudSDKException\n */\n public UnBindSecretIdsResponse UnBindSecretIds(UnBindSecretIdsRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindSecretIds\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnBindSubDomain)用于解绑自定义域名。\n * 用户使用 API 网关绑定了自定义域名到服务中后,若想要解绑此自定义域名,可使用此接口。\n * @param req UnBindSubDomainRequest\n * @return UnBindSubDomainResponse\n * @throws TencentCloudSDKException\n */\n public UnBindSubDomainResponse UnBindSubDomain(UnBindSubDomainRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnBindSubDomain\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnReleaseService)用于下线服务。\n * 用户发布服务到某个环境后,此服务中的 API 方可被调用者进行调用,当用户需要将此服务从发布环境中下线时,可调用此 API。下线后的服务不可被调用。\n * @param req UnReleaseServiceRequest\n * @return UnReleaseServiceResponse\n * @throws TencentCloudSDKException\n */\n public UnReleaseServiceResponse UnReleaseService(UnReleaseServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnReleaseService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UnbindApiApp)用于解除应用和API绑定。\n * @param req UnbindApiAppRequest\n * @return UnbindApiAppResponse\n * @throws TencentCloudSDKException\n */\n public UnbindApiAppResponse UnbindApiApp(UnbindApiAppRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UnbindApiApp\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateApiAppKey)用于更新应用秘钥。\n * @param req UpdateApiAppKeyRequest\n * @return UpdateApiAppKeyResponse\n * @throws TencentCloudSDKException\n */\n public UpdateApiAppKeyResponse UpdateApiAppKey(UpdateApiAppKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateApiAppKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateApiKey)用于更换用户已创建的一对 API 密钥。\n * @param req UpdateApiKeyRequest\n * @return UpdateApiKeyResponse\n * @throws TencentCloudSDKException\n */\n public UpdateApiKeyResponse UpdateApiKey(UpdateApiKeyRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateApiKey\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n\n /**\n * 本接口(UpdateService)用于从服务发布的环境中运行版本切换到特定版本。用户在使用 API 网关创建服务并发布服务到某个环境后,多因为开发过程会产生多个版本,此时可调用本接口。\n * @param req UpdateServiceRequest\n * @return UpdateServiceResponse\n * @throws TencentCloudSDKException\n */\n public UpdateServiceResponse UpdateService(UpdateServiceRequest req) throws TencentCloudSDKException {\n JsonResponseModel rsp = null;\n String rspStr = \"\";\n try {\n Type type = new TypeToken>() {\n }.getType();\n rspStr = this.internalRequest(req, \"UpdateService\");\n rsp = gson.fromJson(rspStr, type);\n } catch (JsonSyntaxException e) {\n throw new TencentCloudSDKException(\"response message: \" + rspStr + \".\\n Error message: \" + e.getMessage());\n }\n return rsp.response;\n }\n}\n"} {"task_id": "Java_1427", "language": "Java", "task_type": "method_signature", "source_file": "java/github/thiagokimo/TMDb/presentation/src/main/java/io/kimo/tmdb/presentation/mvp/presenter/GalleryPresenter.java", "mask_start_position": 891, "mask_end_position": 919, "canonical_solution": "private void hideAllViews() ", "pre_mask_code": "package io.kimo.tmdb.presentation.mvp.presenter;\n\nimport java.util.List;\nimport io.kimo.tmdb.presentation.mvp.BasePresenter;\nimport io.kimo.tmdb.presentation.mvp.model.ImageModel;\nimport io.kimo.tmdb.presentation.mvp.view.GalleryView;\n\npublic class GalleryPresenter implements BasePresenter {\n\n private GalleryView view;\n\n private List urls;\n\n public GalleryPresenter(GalleryView view, List urls) {\n this.urls = urls;\n this.view = view;\n }\n\n @Override\n public void createView() {\n hideAllViews();\n view.showLoading();\n if (urls.isEmpty()) {\n view.showEmpty(\"There are no images.\");\n view.hideLoading();\n } else {\n view.renderImages(urls);\n view.hideLoading();\n view.showView();\n }\n }\n\n @Override\n public void destroyView() {\n }\n\n ", "post_mask_code": "{\n view.hideView();\n view.hideLoading();\n view.hideRetry();\n view.hideEmpty();\n }\n}\n"} {"task_id": "Java_1428", "language": "Java", "task_type": "method_body", "source_file": "java/github/thiagokimo/TMDb/presentation/src/main/java/io/kimo/tmdb/presentation/mvp/presenter/GalleryPresenter.java", "mask_start_position": 919, "mask_end_position": 1031, "canonical_solution": "{\n view.hideView();\n view.hideLoading();\n view.hideRetry();\n view.hideEmpty();\n }", "pre_mask_code": "package io.kimo.tmdb.presentation.mvp.presenter;\n\nimport java.util.List;\nimport io.kimo.tmdb.presentation.mvp.BasePresenter;\nimport io.kimo.tmdb.presentation.mvp.model.ImageModel;\nimport io.kimo.tmdb.presentation.mvp.view.GalleryView;\n\npublic class GalleryPresenter implements BasePresenter {\n\n private GalleryView view;\n\n private List urls;\n\n public GalleryPresenter(GalleryView view, List urls) {\n this.urls = urls;\n this.view = view;\n }\n\n @Override\n public void createView() {\n hideAllViews();\n view.showLoading();\n if (urls.isEmpty()) {\n view.showEmpty(\"There are no images.\");\n view.hideLoading();\n } else {\n view.renderImages(urls);\n view.hideLoading();\n view.showView();\n }\n }\n\n @Override\n public void destroyView() {\n }\n\n private void hideAllViews() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1429", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/thiagokimo/TMDb/presentation/src/main/java/io/kimo/tmdb/presentation/mvp/presenter/GalleryPresenter.java", "mask_start_position": 535, "mask_end_position": 559, "canonical_solution": "\n hideAllViews();", "pre_mask_code": "package io.kimo.tmdb.presentation.mvp.presenter;\n\nimport java.util.List;\nimport io.kimo.tmdb.presentation.mvp.BasePresenter;\nimport io.kimo.tmdb.presentation.mvp.model.ImageModel;\nimport io.kimo.tmdb.presentation.mvp.view.GalleryView;\n\npublic class GalleryPresenter implements BasePresenter {\n\n private GalleryView view;\n\n private List urls;\n\n public GalleryPresenter(GalleryView view, List urls) {\n this.urls = urls;\n this.view = view;\n }\n\n @Override\n public void createView() {", "post_mask_code": "\n view.showLoading();\n if (urls.isEmpty()) {\n view.showEmpty(\"There are no images.\");\n view.hideLoading();\n } else {\n view.renderImages(urls);\n view.hideLoading();\n view.showView();\n }\n }\n\n @Override\n public void destroyView() {\n }\n\n private void hideAllViews() {\n view.hideView();\n view.hideLoading();\n view.hideRetry();\n view.hideEmpty();\n }\n}\n"} {"task_id": "Java_1430", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/thiagokimo/TMDb/presentation/src/main/java/io/kimo/tmdb/presentation/mvp/presenter/GalleryPresenter.java", "mask_start_position": 568, "mask_end_position": 587, "canonical_solution": "view.showLoading();", "pre_mask_code": "package io.kimo.tmdb.presentation.mvp.presenter;\n\nimport java.util.List;\nimport io.kimo.tmdb.presentation.mvp.BasePresenter;\nimport io.kimo.tmdb.presentation.mvp.model.ImageModel;\nimport io.kimo.tmdb.presentation.mvp.view.GalleryView;\n\npublic class GalleryPresenter implements BasePresenter {\n\n private GalleryView view;\n\n private List urls;\n\n public GalleryPresenter(GalleryView view, List urls) {\n this.urls = urls;\n this.view = view;\n }\n\n @Override\n public void createView() {\n hideAllViews();\n ", "post_mask_code": "\n if (urls.isEmpty()) {\n view.showEmpty(\"There are no images.\");\n view.hideLoading();\n } else {\n view.renderImages(urls);\n view.hideLoading();\n view.showView();\n }\n }\n\n @Override\n public void destroyView() {\n }\n\n private void hideAllViews() {\n view.hideView();\n view.hideLoading();\n view.hideRetry();\n view.hideEmpty();\n }\n}\n"} {"task_id": "Java_1431", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/thiagokimo/TMDb/presentation/src/main/java/io/kimo/tmdb/presentation/mvp/presenter/GalleryPresenter.java", "mask_start_position": 596, "mask_end_position": 832, "canonical_solution": "if (urls.isEmpty()) {\n view.showEmpty(\"There are no images.\");\n view.hideLoading();\n } else {\n view.renderImages(urls);\n view.hideLoading();\n view.showView();\n }\n }", "pre_mask_code": "package io.kimo.tmdb.presentation.mvp.presenter;\n\nimport java.util.List;\nimport io.kimo.tmdb.presentation.mvp.BasePresenter;\nimport io.kimo.tmdb.presentation.mvp.model.ImageModel;\nimport io.kimo.tmdb.presentation.mvp.view.GalleryView;\n\npublic class GalleryPresenter implements BasePresenter {\n\n private GalleryView view;\n\n private List urls;\n\n public GalleryPresenter(GalleryView view, List urls) {\n this.urls = urls;\n this.view = view;\n }\n\n @Override\n public void createView() {\n hideAllViews();\n view.showLoading();\n ", "post_mask_code": "\n\n @Override\n public void destroyView() {\n }\n\n private void hideAllViews() {\n view.hideView();\n view.hideLoading();\n view.hideRetry();\n view.hideEmpty();\n }\n}\n"} {"task_id": "Java_1432", "language": "Java", "task_type": "single_line", "source_file": "java/github/thiagokimo/TMDb/presentation/src/main/java/io/kimo/tmdb/presentation/mvp/presenter/GalleryPresenter.java", "mask_start_position": 982, "mask_end_position": 999, "canonical_solution": "view.hideRetry();", "pre_mask_code": "package io.kimo.tmdb.presentation.mvp.presenter;\n\nimport java.util.List;\nimport io.kimo.tmdb.presentation.mvp.BasePresenter;\nimport io.kimo.tmdb.presentation.mvp.model.ImageModel;\nimport io.kimo.tmdb.presentation.mvp.view.GalleryView;\n\npublic class GalleryPresenter implements BasePresenter {\n\n private GalleryView view;\n\n private List urls;\n\n public GalleryPresenter(GalleryView view, List urls) {\n this.urls = urls;\n this.view = view;\n }\n\n @Override\n public void createView() {\n hideAllViews();\n view.showLoading();\n if (urls.isEmpty()) {\n view.showEmpty(\"There are no images.\");\n view.hideLoading();\n } else {\n view.renderImages(urls);\n view.hideLoading();\n view.showView();\n }\n }\n\n @Override\n public void destroyView() {\n }\n\n private void hideAllViews() {\n view.hideView();\n view.hideLoading();\n ", "post_mask_code": "\n view.hideEmpty();\n }\n}\n"} {"task_id": "Java_1433", "language": "Java", "task_type": "if_statement", "source_file": "java/github/thiagokimo/TMDb/presentation/src/main/java/io/kimo/tmdb/presentation/mvp/presenter/GalleryPresenter.java", "mask_start_position": 596, "mask_end_position": 826, "canonical_solution": "if (urls.isEmpty()) {\n view.showEmpty(\"There are no images.\");\n view.hideLoading();\n } else {\n view.renderImages(urls);\n view.hideLoading();\n view.showView();\n }", "pre_mask_code": "package io.kimo.tmdb.presentation.mvp.presenter;\n\nimport java.util.List;\nimport io.kimo.tmdb.presentation.mvp.BasePresenter;\nimport io.kimo.tmdb.presentation.mvp.model.ImageModel;\nimport io.kimo.tmdb.presentation.mvp.view.GalleryView;\n\npublic class GalleryPresenter implements BasePresenter {\n\n private GalleryView view;\n\n private List urls;\n\n public GalleryPresenter(GalleryView view, List urls) {\n this.urls = urls;\n this.view = view;\n }\n\n @Override\n public void createView() {\n hideAllViews();\n view.showLoading();\n ", "post_mask_code": "\n }\n\n @Override\n public void destroyView() {\n }\n\n private void hideAllViews() {\n view.hideView();\n view.hideLoading();\n view.hideRetry();\n view.hideEmpty();\n }\n}\n"} {"task_id": "Java_1434", "language": "Java", "task_type": "method_signature", "source_file": "java/github/haridaniel/PayrollCaseStudy/PayrollDBAdapterJPA/src/main/java/hu/daniel/hari/exercises/cleanarchitecture/payrollcasestudy/adapters/secondary/database/jpa/proxy/paymentclassification/hourly/TimeCardProxy.java", "mask_start_position": 1321, "mask_end_position": 1369, "canonical_solution": "@Override\n public JPATimeCard getJPAObject() ", "pre_mask_code": "package hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.adapters.secondary.database.jpa.proxy.paymentclassification.hourly;\n\nimport java.time.LocalDate;\nimport hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.adapters.secondary.database.jpa.model.paymentclassification.hourly.JPATimeCard;\nimport hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.adapters.secondary.database.jpa.proxy.AutoBindedProxy;\nimport hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.adapters.secondary.database.jpa.proxy.Proxy;\nimport hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.app.entity.paymenttype.TimeCard;\n\n@AutoBindedProxy(JPATimeCard.class)\npublic class TimeCardProxy extends TimeCard implements Proxy {\n\n private JPATimeCard jpaTimeCard;\n\n public TimeCardProxy(JPATimeCard jpaTimeCard) {\n this.jpaTimeCard = jpaTimeCard;\n }\n\n @Override\n public LocalDate getDate() {\n return jpaTimeCard.id.date;\n }\n\n @Override\n public int getWorkingHourQty() {\n return jpaTimeCard.workingHourQty;\n }\n\n @Override\n public void setDate(LocalDate date) {\n jpaTimeCard.id.date = date;\n }\n\n @Override\n public void setWorkingHourQty(int workingHourQty) {\n jpaTimeCard.workingHourQty = workingHourQty;\n }\n\n ", "post_mask_code": "{\n return jpaTimeCard;\n }\n}\n"} {"task_id": "Java_1435", "language": "Java", "task_type": "method_body", "source_file": "java/github/haridaniel/PayrollCaseStudy/PayrollDBAdapterJPA/src/main/java/hu/daniel/hari/exercises/cleanarchitecture/payrollcasestudy/adapters/secondary/database/jpa/proxy/paymentclassification/hourly/TimeCardProxy.java", "mask_start_position": 942, "mask_end_position": 985, "canonical_solution": "{\n return jpaTimeCard.id.date;\n }", "pre_mask_code": "package hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.adapters.secondary.database.jpa.proxy.paymentclassification.hourly;\n\nimport java.time.LocalDate;\nimport hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.adapters.secondary.database.jpa.model.paymentclassification.hourly.JPATimeCard;\nimport hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.adapters.secondary.database.jpa.proxy.AutoBindedProxy;\nimport hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.adapters.secondary.database.jpa.proxy.Proxy;\nimport hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.app.entity.paymenttype.TimeCard;\n\n@AutoBindedProxy(JPATimeCard.class)\npublic class TimeCardProxy extends TimeCard implements Proxy {\n\n private JPATimeCard jpaTimeCard;\n\n public TimeCardProxy(JPATimeCard jpaTimeCard) {\n this.jpaTimeCard = jpaTimeCard;\n }\n\n @Override\n public LocalDate getDate() ", "post_mask_code": "\n\n @Override\n public int getWorkingHourQty() {\n return jpaTimeCard.workingHourQty;\n }\n\n @Override\n public void setDate(LocalDate date) {\n jpaTimeCard.id.date = date;\n }\n\n @Override\n public void setWorkingHourQty(int workingHourQty) {\n jpaTimeCard.workingHourQty = workingHourQty;\n }\n\n @Override\n public JPATimeCard getJPAObject() {\n return jpaTimeCard;\n }\n}\n"} {"task_id": "Java_1436", "language": "Java", "task_type": "single_line", "source_file": "java/github/haridaniel/PayrollCaseStudy/PayrollDBAdapterJPA/src/main/java/hu/daniel/hari/exercises/cleanarchitecture/payrollcasestudy/adapters/secondary/database/jpa/proxy/paymentclassification/hourly/TimeCardProxy.java", "mask_start_position": 1164, "mask_end_position": 1179, "canonical_solution": "id.date = date;", "pre_mask_code": "package hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.adapters.secondary.database.jpa.proxy.paymentclassification.hourly;\n\nimport java.time.LocalDate;\nimport hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.adapters.secondary.database.jpa.model.paymentclassification.hourly.JPATimeCard;\nimport hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.adapters.secondary.database.jpa.proxy.AutoBindedProxy;\nimport hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.adapters.secondary.database.jpa.proxy.Proxy;\nimport hu.daniel.hari.exercises.cleanarchitecture.payrollcasestudy.app.entity.paymenttype.TimeCard;\n\n@AutoBindedProxy(JPATimeCard.class)\npublic class TimeCardProxy extends TimeCard implements Proxy {\n\n private JPATimeCard jpaTimeCard;\n\n public TimeCardProxy(JPATimeCard jpaTimeCard) {\n this.jpaTimeCard = jpaTimeCard;\n }\n\n @Override\n public LocalDate getDate() {\n return jpaTimeCard.id.date;\n }\n\n @Override\n public int getWorkingHourQty() {\n return jpaTimeCard.workingHourQty;\n }\n\n @Override\n public void setDate(LocalDate date) {\n jpaTimeCard.", "post_mask_code": "\n }\n\n @Override\n public void setWorkingHourQty(int workingHourQty) {\n jpaTimeCard.workingHourQty = workingHourQty;\n }\n\n @Override\n public JPATimeCard getJPAObject() {\n return jpaTimeCard;\n }\n}\n"} {"task_id": "Java_1437", "language": "Java", "task_type": "method_signature", "source_file": "java/github/vicinityh2020/vicinity-agent/testing-adapter/src/main/java/sk/intersoft/vicinity/adapter/testing/service/resource/DiscoResource.java", "mask_start_position": 1805, "mask_end_position": 1859, "canonical_solution": "@Get()\n public String disco(Representation entity) ", "pre_mask_code": "package sk.intersoft.vicinity.adapter.testing.service.resource;\n\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.util.EntityUtils;\nimport org.json.JSONObject;\nimport org.restlet.representation.Representation;\nimport org.restlet.resource.Get;\nimport org.restlet.resource.Post;\nimport org.restlet.resource.ServerResource;\n\npublic class DiscoResource extends ServerResource {\n\n public static String post() {\n try {\n HttpClient client = HttpClientBuilder.create().build();\n String callEndpoint = System.getProperty(\"agent.endpoint\") + \"/objects\";\n String objects = ObjectsResource.file2string(System.getProperty(\"active.objects.file\"));\n System.out.println(\"DISCO POST:\");\n System.out.println(\"endpoint: \" + callEndpoint);\n System.out.println(\"payload: \" + objects);\n HttpPost request = new HttpPost(callEndpoint);\n request.addHeader(\"Content-Type\", \"application/json\");\n if (objects != null) {\n StringEntity data = new StringEntity(objects, \"utf-8\");\n request.setEntity(data);\n }\n HttpResponse response = client.execute(request);\n int status = response.getStatusLine().getStatusCode();\n System.out.println(\"POST status: \" + status);\n String responseContent = EntityUtils.toString(response.getEntity());\n System.out.println(\"response: \" + responseContent);\n return responseContent;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"failed\";\n }\n\n ", "post_mask_code": "{\n try {\n System.out.println(\"active disco\");\n String response = post();\n JSONObject out = new JSONObject();\n out.put(\"disco\", \"executed\");\n try {\n out.put(\"response\", new JSONObject(response));\n } catch (Exception e) {\n out.put(\"response\", response);\n }\n return out.toString(2);\n } catch (Exception e) {\n return \"{}\";\n }\n }\n}\n"} {"task_id": "Java_1438", "language": "Java", "task_type": "method_body", "source_file": "java/github/vicinityh2020/vicinity-agent/testing-adapter/src/main/java/sk/intersoft/vicinity/adapter/testing/service/resource/DiscoResource.java", "mask_start_position": 1859, "mask_end_position": 2336, "canonical_solution": "{\n try {\n System.out.println(\"active disco\");\n String response = post();\n JSONObject out = new JSONObject();\n out.put(\"disco\", \"executed\");\n try {\n out.put(\"response\", new JSONObject(response));\n } catch (Exception e) {\n out.put(\"response\", response);\n }\n return out.toString(2);\n } catch (Exception e) {\n return \"{}\";\n }\n }", "pre_mask_code": "package sk.intersoft.vicinity.adapter.testing.service.resource;\n\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.util.EntityUtils;\nimport org.json.JSONObject;\nimport org.restlet.representation.Representation;\nimport org.restlet.resource.Get;\nimport org.restlet.resource.Post;\nimport org.restlet.resource.ServerResource;\n\npublic class DiscoResource extends ServerResource {\n\n public static String post() {\n try {\n HttpClient client = HttpClientBuilder.create().build();\n String callEndpoint = System.getProperty(\"agent.endpoint\") + \"/objects\";\n String objects = ObjectsResource.file2string(System.getProperty(\"active.objects.file\"));\n System.out.println(\"DISCO POST:\");\n System.out.println(\"endpoint: \" + callEndpoint);\n System.out.println(\"payload: \" + objects);\n HttpPost request = new HttpPost(callEndpoint);\n request.addHeader(\"Content-Type\", \"application/json\");\n if (objects != null) {\n StringEntity data = new StringEntity(objects, \"utf-8\");\n request.setEntity(data);\n }\n HttpResponse response = client.execute(request);\n int status = response.getStatusLine().getStatusCode();\n System.out.println(\"POST status: \" + status);\n String responseContent = EntityUtils.toString(response.getEntity());\n System.out.println(\"response: \" + responseContent);\n return responseContent;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"failed\";\n }\n\n @Get()\n public String disco(Representation entity) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1439", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/vicinityh2020/vicinity-agent/testing-adapter/src/main/java/sk/intersoft/vicinity/adapter/testing/service/resource/DiscoResource.java", "mask_start_position": 1860, "mask_end_position": 1860, "canonical_solution": "", "pre_mask_code": "package sk.intersoft.vicinity.adapter.testing.service.resource;\n\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.util.EntityUtils;\nimport org.json.JSONObject;\nimport org.restlet.representation.Representation;\nimport org.restlet.resource.Get;\nimport org.restlet.resource.Post;\nimport org.restlet.resource.ServerResource;\n\npublic class DiscoResource extends ServerResource {\n\n public static String post() {\n try {\n HttpClient client = HttpClientBuilder.create().build();\n String callEndpoint = System.getProperty(\"agent.endpoint\") + \"/objects\";\n String objects = ObjectsResource.file2string(System.getProperty(\"active.objects.file\"));\n System.out.println(\"DISCO POST:\");\n System.out.println(\"endpoint: \" + callEndpoint);\n System.out.println(\"payload: \" + objects);\n HttpPost request = new HttpPost(callEndpoint);\n request.addHeader(\"Content-Type\", \"application/json\");\n if (objects != null) {\n StringEntity data = new StringEntity(objects, \"utf-8\");\n request.setEntity(data);\n }\n HttpResponse response = client.execute(request);\n int status = response.getStatusLine().getStatusCode();\n System.out.println(\"POST status: \" + status);\n String responseContent = EntityUtils.toString(response.getEntity());\n System.out.println(\"response: \" + responseContent);\n return responseContent;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"failed\";\n }\n\n @Get()\n public String disco(Representation entity) {", "post_mask_code": "\n try {\n System.out.println(\"active disco\");\n String response = post();\n JSONObject out = new JSONObject();\n out.put(\"disco\", \"executed\");\n try {\n out.put(\"response\", new JSONObject(response));\n } catch (Exception e) {\n out.put(\"response\", response);\n }\n return out.toString(2);\n } catch (Exception e) {\n return \"{}\";\n }\n }\n}\n"} {"task_id": "Java_1440", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/vicinityh2020/vicinity-agent/testing-adapter/src/main/java/sk/intersoft/vicinity/adapter/testing/service/resource/DiscoResource.java", "mask_start_position": 1869, "mask_end_position": 2330, "canonical_solution": "try {\n System.out.println(\"active disco\");\n String response = post();\n JSONObject out = new JSONObject();\n out.put(\"disco\", \"executed\");\n try {\n out.put(\"response\", new JSONObject(response));\n } catch (Exception e) {\n out.put(\"response\", response);\n }\n return out.toString(2);\n } catch (Exception e) {\n return \"{}\";\n }", "pre_mask_code": "package sk.intersoft.vicinity.adapter.testing.service.resource;\n\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.util.EntityUtils;\nimport org.json.JSONObject;\nimport org.restlet.representation.Representation;\nimport org.restlet.resource.Get;\nimport org.restlet.resource.Post;\nimport org.restlet.resource.ServerResource;\n\npublic class DiscoResource extends ServerResource {\n\n public static String post() {\n try {\n HttpClient client = HttpClientBuilder.create().build();\n String callEndpoint = System.getProperty(\"agent.endpoint\") + \"/objects\";\n String objects = ObjectsResource.file2string(System.getProperty(\"active.objects.file\"));\n System.out.println(\"DISCO POST:\");\n System.out.println(\"endpoint: \" + callEndpoint);\n System.out.println(\"payload: \" + objects);\n HttpPost request = new HttpPost(callEndpoint);\n request.addHeader(\"Content-Type\", \"application/json\");\n if (objects != null) {\n StringEntity data = new StringEntity(objects, \"utf-8\");\n request.setEntity(data);\n }\n HttpResponse response = client.execute(request);\n int status = response.getStatusLine().getStatusCode();\n System.out.println(\"POST status: \" + status);\n String responseContent = EntityUtils.toString(response.getEntity());\n System.out.println(\"response: \" + responseContent);\n return responseContent;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"failed\";\n }\n\n @Get()\n public String disco(Representation entity) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1441", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/vicinityh2020/vicinity-agent/testing-adapter/src/main/java/sk/intersoft/vicinity/adapter/testing/service/resource/DiscoResource.java", "mask_start_position": 2335, "mask_end_position": 2336, "canonical_solution": "}", "pre_mask_code": "package sk.intersoft.vicinity.adapter.testing.service.resource;\n\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.util.EntityUtils;\nimport org.json.JSONObject;\nimport org.restlet.representation.Representation;\nimport org.restlet.resource.Get;\nimport org.restlet.resource.Post;\nimport org.restlet.resource.ServerResource;\n\npublic class DiscoResource extends ServerResource {\n\n public static String post() {\n try {\n HttpClient client = HttpClientBuilder.create().build();\n String callEndpoint = System.getProperty(\"agent.endpoint\") + \"/objects\";\n String objects = ObjectsResource.file2string(System.getProperty(\"active.objects.file\"));\n System.out.println(\"DISCO POST:\");\n System.out.println(\"endpoint: \" + callEndpoint);\n System.out.println(\"payload: \" + objects);\n HttpPost request = new HttpPost(callEndpoint);\n request.addHeader(\"Content-Type\", \"application/json\");\n if (objects != null) {\n StringEntity data = new StringEntity(objects, \"utf-8\");\n request.setEntity(data);\n }\n HttpResponse response = client.execute(request);\n int status = response.getStatusLine().getStatusCode();\n System.out.println(\"POST status: \" + status);\n String responseContent = EntityUtils.toString(response.getEntity());\n System.out.println(\"response: \" + responseContent);\n return responseContent;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"failed\";\n }\n\n @Get()\n public String disco(Representation entity) {\n try {\n System.out.println(\"active disco\");\n String response = post();\n JSONObject out = new JSONObject();\n out.put(\"disco\", \"executed\");\n try {\n out.put(\"response\", new JSONObject(response));\n } catch (Exception e) {\n out.put(\"response\", response);\n }\n return out.toString(2);\n } catch (Exception e) {\n return \"{}\";\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1442", "language": "Java", "task_type": "single_line", "source_file": "java/github/vicinityh2020/vicinity-agent/testing-adapter/src/main/java/sk/intersoft/vicinity/adapter/testing/service/resource/DiscoResource.java", "mask_start_position": 1791, "mask_end_position": 1793, "canonical_solution": "\";", "pre_mask_code": "package sk.intersoft.vicinity.adapter.testing.service.resource;\n\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.util.EntityUtils;\nimport org.json.JSONObject;\nimport org.restlet.representation.Representation;\nimport org.restlet.resource.Get;\nimport org.restlet.resource.Post;\nimport org.restlet.resource.ServerResource;\n\npublic class DiscoResource extends ServerResource {\n\n public static String post() {\n try {\n HttpClient client = HttpClientBuilder.create().build();\n String callEndpoint = System.getProperty(\"agent.endpoint\") + \"/objects\";\n String objects = ObjectsResource.file2string(System.getProperty(\"active.objects.file\"));\n System.out.println(\"DISCO POST:\");\n System.out.println(\"endpoint: \" + callEndpoint);\n System.out.println(\"payload: \" + objects);\n HttpPost request = new HttpPost(callEndpoint);\n request.addHeader(\"Content-Type\", \"application/json\");\n if (objects != null) {\n StringEntity data = new StringEntity(objects, \"utf-8\");\n request.setEntity(data);\n }\n HttpResponse response = client.execute(request);\n int status = response.getStatusLine().getStatusCode();\n System.out.println(\"POST status: \" + status);\n String responseContent = EntityUtils.toString(response.getEntity());\n System.out.println(\"response: \" + responseContent);\n return responseContent;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"failed", "post_mask_code": "\n }\n\n @Get()\n public String disco(Representation entity) {\n try {\n System.out.println(\"active disco\");\n String response = post();\n JSONObject out = new JSONObject();\n out.put(\"disco\", \"executed\");\n try {\n out.put(\"response\", new JSONObject(response));\n } catch (Exception e) {\n out.put(\"response\", response);\n }\n return out.toString(2);\n } catch (Exception e) {\n return \"{}\";\n }\n }\n}\n"} {"task_id": "Java_1443", "language": "Java", "task_type": "if_statement", "source_file": "java/github/vicinityh2020/vicinity-agent/testing-adapter/src/main/java/sk/intersoft/vicinity/adapter/testing/service/resource/DiscoResource.java", "mask_start_position": 1177, "mask_end_position": 1326, "canonical_solution": "if (objects != null) {\n StringEntity data = new StringEntity(objects, \"utf-8\");\n request.setEntity(data);\n }", "pre_mask_code": "package sk.intersoft.vicinity.adapter.testing.service.resource;\n\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.util.EntityUtils;\nimport org.json.JSONObject;\nimport org.restlet.representation.Representation;\nimport org.restlet.resource.Get;\nimport org.restlet.resource.Post;\nimport org.restlet.resource.ServerResource;\n\npublic class DiscoResource extends ServerResource {\n\n public static String post() {\n try {\n HttpClient client = HttpClientBuilder.create().build();\n String callEndpoint = System.getProperty(\"agent.endpoint\") + \"/objects\";\n String objects = ObjectsResource.file2string(System.getProperty(\"active.objects.file\"));\n System.out.println(\"DISCO POST:\");\n System.out.println(\"endpoint: \" + callEndpoint);\n System.out.println(\"payload: \" + objects);\n HttpPost request = new HttpPost(callEndpoint);\n request.addHeader(\"Content-Type\", \"application/json\");\n ", "post_mask_code": "\n HttpResponse response = client.execute(request);\n int status = response.getStatusLine().getStatusCode();\n System.out.println(\"POST status: \" + status);\n String responseContent = EntityUtils.toString(response.getEntity());\n System.out.println(\"response: \" + responseContent);\n return responseContent;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"failed\";\n }\n\n @Get()\n public String disco(Representation entity) {\n try {\n System.out.println(\"active disco\");\n String response = post();\n JSONObject out = new JSONObject();\n out.put(\"disco\", \"executed\");\n try {\n out.put(\"response\", new JSONObject(response));\n } catch (Exception e) {\n out.put(\"response\", response);\n }\n return out.toString(2);\n } catch (Exception e) {\n return \"{}\";\n }\n }\n}\n"} {"task_id": "Java_1444", "language": "Java", "task_type": "try_statement", "source_file": "java/github/vicinityh2020/vicinity-agent/testing-adapter/src/main/java/sk/intersoft/vicinity/adapter/testing/service/resource/DiscoResource.java", "mask_start_position": 1869, "mask_end_position": 2330, "canonical_solution": "try {\n System.out.println(\"active disco\");\n String response = post();\n JSONObject out = new JSONObject();\n out.put(\"disco\", \"executed\");\n try {\n out.put(\"response\", new JSONObject(response));\n } catch (Exception e) {\n out.put(\"response\", response);\n }\n return out.toString(2);\n } catch (Exception e) {\n return \"{}\";\n }", "pre_mask_code": "package sk.intersoft.vicinity.adapter.testing.service.resource;\n\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.util.EntityUtils;\nimport org.json.JSONObject;\nimport org.restlet.representation.Representation;\nimport org.restlet.resource.Get;\nimport org.restlet.resource.Post;\nimport org.restlet.resource.ServerResource;\n\npublic class DiscoResource extends ServerResource {\n\n public static String post() {\n try {\n HttpClient client = HttpClientBuilder.create().build();\n String callEndpoint = System.getProperty(\"agent.endpoint\") + \"/objects\";\n String objects = ObjectsResource.file2string(System.getProperty(\"active.objects.file\"));\n System.out.println(\"DISCO POST:\");\n System.out.println(\"endpoint: \" + callEndpoint);\n System.out.println(\"payload: \" + objects);\n HttpPost request = new HttpPost(callEndpoint);\n request.addHeader(\"Content-Type\", \"application/json\");\n if (objects != null) {\n StringEntity data = new StringEntity(objects, \"utf-8\");\n request.setEntity(data);\n }\n HttpResponse response = client.execute(request);\n int status = response.getStatusLine().getStatusCode();\n System.out.println(\"POST status: \" + status);\n String responseContent = EntityUtils.toString(response.getEntity());\n System.out.println(\"response: \" + responseContent);\n return responseContent;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"failed\";\n }\n\n @Get()\n public String disco(Representation entity) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1445", "language": "Java", "task_type": "method_signature", "source_file": "java/github/software-jessies-org/jessies/salma-hayek/src/e/util/Range.java", "mask_start_position": 836, "mask_end_position": 856, "canonical_solution": "public int getEnd() ", "pre_mask_code": "package e.util;\n\npublic final class Range {\n\n /**\n * A unique empty range. If you use this, you might save space, but you\n * also get extra checking: it's illegal to invoke getStart or getEnd\n * on NULL_RANGE (though not on a Range that just happens to be empty).\n */\n public static final Range NULL_RANGE = new Range(-1, -1);\n\n private final int start;\n\n private final int end;\n\n public Range(int start, int end) {\n this.start = start;\n this.end = end;\n }\n\n public boolean isEmpty() {\n // This operation is allowed on NULL_RANGE.\n return (start == end);\n }\n\n public boolean isNonEmpty() {\n // This operation is allowed on NULL_RANGE.\n return (start != end);\n }\n\n public int getStart() {\n checkNotNull();\n return start;\n }\n\n ", "post_mask_code": "{\n checkNotNull();\n return end;\n }\n\n public int length() {\n checkNotNull();\n return (end - start);\n }\n\n private void checkNotNull() {\n if (this == NULL_RANGE) {\n throw new IllegalStateException(\"can't use NULL_RANGE\");\n }\n }\n\n public String toString() {\n if (this == NULL_RANGE) {\n return \"Range[NULL_RANGE]\";\n }\n return \"Range[start=\" + start + \",end=\" + end + \"]\";\n }\n}\n"} {"task_id": "Java_1446", "language": "Java", "task_type": "method_body", "source_file": "java/github/software-jessies-org/jessies/salma-hayek/src/e/util/Range.java", "mask_start_position": 933, "mask_end_position": 994, "canonical_solution": "{\n checkNotNull();\n return (end - start);\n }", "pre_mask_code": "package e.util;\n\npublic final class Range {\n\n /**\n * A unique empty range. If you use this, you might save space, but you\n * also get extra checking: it's illegal to invoke getStart or getEnd\n * on NULL_RANGE (though not on a Range that just happens to be empty).\n */\n public static final Range NULL_RANGE = new Range(-1, -1);\n\n private final int start;\n\n private final int end;\n\n public Range(int start, int end) {\n this.start = start;\n this.end = end;\n }\n\n public boolean isEmpty() {\n // This operation is allowed on NULL_RANGE.\n return (start == end);\n }\n\n public boolean isNonEmpty() {\n // This operation is allowed on NULL_RANGE.\n return (start != end);\n }\n\n public int getStart() {\n checkNotNull();\n return start;\n }\n\n public int getEnd() {\n checkNotNull();\n return end;\n }\n\n public int length() ", "post_mask_code": "\n\n private void checkNotNull() {\n if (this == NULL_RANGE) {\n throw new IllegalStateException(\"can't use NULL_RANGE\");\n }\n }\n\n public String toString() {\n if (this == NULL_RANGE) {\n return \"Range[NULL_RANGE]\";\n }\n return \"Range[start=\" + start + \",end=\" + end + \"]\";\n }\n}\n"} {"task_id": "Java_1447", "language": "Java", "task_type": "single_line", "source_file": "java/github/software-jessies-org/jessies/salma-hayek/src/e/util/Range.java", "mask_start_position": 600, "mask_end_position": 619, "canonical_solution": "urn (start == end);", "pre_mask_code": "package e.util;\n\npublic final class Range {\n\n /**\n * A unique empty range. If you use this, you might save space, but you\n * also get extra checking: it's illegal to invoke getStart or getEnd\n * on NULL_RANGE (though not on a Range that just happens to be empty).\n */\n public static final Range NULL_RANGE = new Range(-1, -1);\n\n private final int start;\n\n private final int end;\n\n public Range(int start, int end) {\n this.start = start;\n this.end = end;\n }\n\n public boolean isEmpty() {\n // This operation is allowed on NULL_RANGE.\n ret", "post_mask_code": "\n }\n\n public boolean isNonEmpty() {\n // This operation is allowed on NULL_RANGE.\n return (start != end);\n }\n\n public int getStart() {\n checkNotNull();\n return start;\n }\n\n public int getEnd() {\n checkNotNull();\n return end;\n }\n\n public int length() {\n checkNotNull();\n return (end - start);\n }\n\n private void checkNotNull() {\n if (this == NULL_RANGE) {\n throw new IllegalStateException(\"can't use NULL_RANGE\");\n }\n }\n\n public String toString() {\n if (this == NULL_RANGE) {\n return \"Range[NULL_RANGE]\";\n }\n return \"Range[start=\" + start + \",end=\" + end + \"]\";\n }\n}\n"} {"task_id": "Java_1448", "language": "Java", "task_type": "if_statement", "source_file": "java/github/software-jessies-org/jessies/salma-hayek/src/e/util/Range.java", "mask_start_position": 1038, "mask_end_position": 1142, "canonical_solution": "if (this == NULL_RANGE) {\n throw new IllegalStateException(\"can't use NULL_RANGE\");\n }", "pre_mask_code": "package e.util;\n\npublic final class Range {\n\n /**\n * A unique empty range. If you use this, you might save space, but you\n * also get extra checking: it's illegal to invoke getStart or getEnd\n * on NULL_RANGE (though not on a Range that just happens to be empty).\n */\n public static final Range NULL_RANGE = new Range(-1, -1);\n\n private final int start;\n\n private final int end;\n\n public Range(int start, int end) {\n this.start = start;\n this.end = end;\n }\n\n public boolean isEmpty() {\n // This operation is allowed on NULL_RANGE.\n return (start == end);\n }\n\n public boolean isNonEmpty() {\n // This operation is allowed on NULL_RANGE.\n return (start != end);\n }\n\n public int getStart() {\n checkNotNull();\n return start;\n }\n\n public int getEnd() {\n checkNotNull();\n return end;\n }\n\n public int length() {\n checkNotNull();\n return (end - start);\n }\n\n private void checkNotNull() {\n ", "post_mask_code": "\n }\n\n public String toString() {\n if (this == NULL_RANGE) {\n return \"Range[NULL_RANGE]\";\n }\n return \"Range[start=\" + start + \",end=\" + end + \"]\";\n }\n}\n"} {"task_id": "Java_1449", "language": "Java", "task_type": "method_signature", "source_file": "java/github/luontola/jumi/jumi-core/src/main/java/fi/jumi/core/discovery/PathMatcherTestFileFinder.java", "mask_start_position": 1333, "mask_end_position": 1372, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "package fi.jumi.core.discovery;\n\nimport fi.jumi.actors.ActorRef;\nimport fi.jumi.core.api.TestFile;\nimport fi.jumi.core.util.Boilerplate;\nimport javax.annotation.concurrent.NotThreadSafe;\nimport java.io.IOException;\nimport java.nio.file.*;\n\n@NotThreadSafe\npublic class PathMatcherTestFileFinder implements TestFileFinder {\n\n private final PathMatcher matcher;\n\n private final Path baseDir;\n\n public PathMatcherTestFileFinder(PathMatcher matcher, Path baseDir) {\n this.matcher = matcher;\n this.baseDir = baseDir;\n }\n\n @Override\n public void findTestFiles(ActorRef listener) {\n try {\n // TODO: Java 8, use Files.walk\n Files.walkFileTree(baseDir, new RelativePathMatchingFileVisitor(matcher, baseDir) {\n\n @Override\n protected void fileFound(Path relativePath) {\n // XXX: This class must not call onAllTestFilesFound, but only CompositeTestFileFinder does, to avoid duplicate calls\n listener.tell().onTestFileFound(TestFile.fromPath(relativePath));\n }\n });\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to traverse \" + baseDir, e);\n } finally {\n listener.tell().onAllTestFilesFound();\n }\n }\n\n ", "post_mask_code": "{\n return Boilerplate.toString(getClass(), matcher, baseDir);\n }\n}\n"} {"task_id": "Java_1450", "language": "Java", "task_type": "method_body", "source_file": "java/github/luontola/jumi/jumi-core/src/main/java/fi/jumi/core/discovery/PathMatcherTestFileFinder.java", "mask_start_position": 1372, "mask_end_position": 1446, "canonical_solution": "{\n return Boilerplate.toString(getClass(), matcher, baseDir);\n }", "pre_mask_code": "package fi.jumi.core.discovery;\n\nimport fi.jumi.actors.ActorRef;\nimport fi.jumi.core.api.TestFile;\nimport fi.jumi.core.util.Boilerplate;\nimport javax.annotation.concurrent.NotThreadSafe;\nimport java.io.IOException;\nimport java.nio.file.*;\n\n@NotThreadSafe\npublic class PathMatcherTestFileFinder implements TestFileFinder {\n\n private final PathMatcher matcher;\n\n private final Path baseDir;\n\n public PathMatcherTestFileFinder(PathMatcher matcher, Path baseDir) {\n this.matcher = matcher;\n this.baseDir = baseDir;\n }\n\n @Override\n public void findTestFiles(ActorRef listener) {\n try {\n // TODO: Java 8, use Files.walk\n Files.walkFileTree(baseDir, new RelativePathMatchingFileVisitor(matcher, baseDir) {\n\n @Override\n protected void fileFound(Path relativePath) {\n // XXX: This class must not call onAllTestFilesFound, but only CompositeTestFileFinder does, to avoid duplicate calls\n listener.tell().onTestFileFound(TestFile.fromPath(relativePath));\n }\n });\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to traverse \" + baseDir, e);\n } finally {\n listener.tell().onAllTestFilesFound();\n }\n }\n\n @Override\n public String toString() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1451", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/luontola/jumi/jumi-core/src/main/java/fi/jumi/core/discovery/PathMatcherTestFileFinder.java", "mask_start_position": 629, "mask_end_position": 629, "canonical_solution": "", "pre_mask_code": "package fi.jumi.core.discovery;\n\nimport fi.jumi.actors.ActorRef;\nimport fi.jumi.core.api.TestFile;\nimport fi.jumi.core.util.Boilerplate;\nimport javax.annotation.concurrent.NotThreadSafe;\nimport java.io.IOException;\nimport java.nio.file.*;\n\n@NotThreadSafe\npublic class PathMatcherTestFileFinder implements TestFileFinder {\n\n private final PathMatcher matcher;\n\n private final Path baseDir;\n\n public PathMatcherTestFileFinder(PathMatcher matcher, Path baseDir) {\n this.matcher = matcher;\n this.baseDir = baseDir;\n }\n\n @Override\n public void findTestFiles(ActorRef listener) {", "post_mask_code": "\n try {\n // TODO: Java 8, use Files.walk\n Files.walkFileTree(baseDir, new RelativePathMatchingFileVisitor(matcher, baseDir) {\n\n @Override\n protected void fileFound(Path relativePath) {\n // XXX: This class must not call onAllTestFilesFound, but only CompositeTestFileFinder does, to avoid duplicate calls\n listener.tell().onTestFileFound(TestFile.fromPath(relativePath));\n }\n });\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to traverse \" + baseDir, e);\n } finally {\n listener.tell().onAllTestFilesFound();\n }\n }\n\n @Override\n public String toString() {\n return Boilerplate.toString(getClass(), matcher, baseDir);\n }\n}\n"} {"task_id": "Java_1452", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/luontola/jumi/jumi-core/src/main/java/fi/jumi/core/discovery/PathMatcherTestFileFinder.java", "mask_start_position": 638, "mask_end_position": 1321, "canonical_solution": "try {\n // TODO: Java 8, use Files.walk\n Files.walkFileTree(baseDir, new RelativePathMatchingFileVisitor(matcher, baseDir) {\n\n @Override\n protected void fileFound(Path relativePath) {\n // XXX: This class must not call onAllTestFilesFound, but only CompositeTestFileFinder does, to avoid duplicate calls\n listener.tell().onTestFileFound(TestFile.fromPath(relativePath));\n }\n });\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to traverse \" + baseDir, e);\n } finally {\n listener.tell().onAllTestFilesFound();\n }", "pre_mask_code": "package fi.jumi.core.discovery;\n\nimport fi.jumi.actors.ActorRef;\nimport fi.jumi.core.api.TestFile;\nimport fi.jumi.core.util.Boilerplate;\nimport javax.annotation.concurrent.NotThreadSafe;\nimport java.io.IOException;\nimport java.nio.file.*;\n\n@NotThreadSafe\npublic class PathMatcherTestFileFinder implements TestFileFinder {\n\n private final PathMatcher matcher;\n\n private final Path baseDir;\n\n public PathMatcherTestFileFinder(PathMatcher matcher, Path baseDir) {\n this.matcher = matcher;\n this.baseDir = baseDir;\n }\n\n @Override\n public void findTestFiles(ActorRef listener) {\n ", "post_mask_code": "\n }\n\n @Override\n public String toString() {\n return Boilerplate.toString(getClass(), matcher, baseDir);\n }\n}\n"} {"task_id": "Java_1453", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/luontola/jumi/jumi-core/src/main/java/fi/jumi/core/discovery/PathMatcherTestFileFinder.java", "mask_start_position": 1326, "mask_end_position": 1327, "canonical_solution": "}", "pre_mask_code": "package fi.jumi.core.discovery;\n\nimport fi.jumi.actors.ActorRef;\nimport fi.jumi.core.api.TestFile;\nimport fi.jumi.core.util.Boilerplate;\nimport javax.annotation.concurrent.NotThreadSafe;\nimport java.io.IOException;\nimport java.nio.file.*;\n\n@NotThreadSafe\npublic class PathMatcherTestFileFinder implements TestFileFinder {\n\n private final PathMatcher matcher;\n\n private final Path baseDir;\n\n public PathMatcherTestFileFinder(PathMatcher matcher, Path baseDir) {\n this.matcher = matcher;\n this.baseDir = baseDir;\n }\n\n @Override\n public void findTestFiles(ActorRef listener) {\n try {\n // TODO: Java 8, use Files.walk\n Files.walkFileTree(baseDir, new RelativePathMatchingFileVisitor(matcher, baseDir) {\n\n @Override\n protected void fileFound(Path relativePath) {\n // XXX: This class must not call onAllTestFilesFound, but only CompositeTestFileFinder does, to avoid duplicate calls\n listener.tell().onTestFileFound(TestFile.fromPath(relativePath));\n }\n });\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to traverse \" + baseDir, e);\n } finally {\n listener.tell().onAllTestFilesFound();\n }\n ", "post_mask_code": "\n\n @Override\n public String toString() {\n return Boilerplate.toString(getClass(), matcher, baseDir);\n }\n}\n"} {"task_id": "Java_1454", "language": "Java", "task_type": "single_line", "source_file": "java/github/luontola/jumi/jumi-core/src/main/java/fi/jumi/core/discovery/PathMatcherTestFileFinder.java", "mask_start_position": 1434, "mask_end_position": 1440, "canonical_solution": "eDir);", "pre_mask_code": "package fi.jumi.core.discovery;\n\nimport fi.jumi.actors.ActorRef;\nimport fi.jumi.core.api.TestFile;\nimport fi.jumi.core.util.Boilerplate;\nimport javax.annotation.concurrent.NotThreadSafe;\nimport java.io.IOException;\nimport java.nio.file.*;\n\n@NotThreadSafe\npublic class PathMatcherTestFileFinder implements TestFileFinder {\n\n private final PathMatcher matcher;\n\n private final Path baseDir;\n\n public PathMatcherTestFileFinder(PathMatcher matcher, Path baseDir) {\n this.matcher = matcher;\n this.baseDir = baseDir;\n }\n\n @Override\n public void findTestFiles(ActorRef listener) {\n try {\n // TODO: Java 8, use Files.walk\n Files.walkFileTree(baseDir, new RelativePathMatchingFileVisitor(matcher, baseDir) {\n\n @Override\n protected void fileFound(Path relativePath) {\n // XXX: This class must not call onAllTestFilesFound, but only CompositeTestFileFinder does, to avoid duplicate calls\n listener.tell().onTestFileFound(TestFile.fromPath(relativePath));\n }\n });\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to traverse \" + baseDir, e);\n } finally {\n listener.tell().onAllTestFilesFound();\n }\n }\n\n @Override\n public String toString() {\n return Boilerplate.toString(getClass(), matcher, bas", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1455", "language": "Java", "task_type": "method_signature", "source_file": "java/github/keycloak/keycloak/services/src/main/java/org/keycloak/theme/TemplatingUtil.java", "mask_start_position": 169, "mask_end_position": 238, "canonical_solution": "public static String resolveVariables(String text, Properties props) ", "pre_mask_code": "package org.keycloak.theme;\n\nimport java.util.Properties;\n\n/**\n * @author Marko Strukelj\n */\npublic class TemplatingUtil {\n\n ", "post_mask_code": "{\n return resolveVariables(text, props, \"${\", \"}\");\n }\n\n public static String resolveVariables(String text, Properties props, String startMarker, String endMarker) {\n int e = 0;\n int s = text.indexOf(startMarker);\n if (s == -1) {\n return text;\n } else {\n StringBuilder sb = new StringBuilder();\n do {\n if (e < s) {\n sb.append(text.substring(e, s));\n }\n e = text.indexOf(endMarker, s + startMarker.length());\n if (e != -1) {\n String key = text.substring(s + startMarker.length(), e);\n sb.append(props.getProperty(key, key));\n e += endMarker.length();\n s = text.indexOf(startMarker, e);\n } else {\n e = s;\n break;\n }\n } while (s != -1);\n if (e < text.length()) {\n sb.append(text.substring(e));\n }\n return sb.toString();\n }\n }\n}\n"} {"task_id": "Java_1456", "language": "Java", "task_type": "method_body", "source_file": "java/github/keycloak/keycloak/services/src/main/java/org/keycloak/theme/TemplatingUtil.java", "mask_start_position": 238, "mask_end_position": 302, "canonical_solution": "{\n return resolveVariables(text, props, \"${\", \"}\");\n }", "pre_mask_code": "package org.keycloak.theme;\n\nimport java.util.Properties;\n\n/**\n * @author Marko Strukelj\n */\npublic class TemplatingUtil {\n\n public static String resolveVariables(String text, Properties props) ", "post_mask_code": "\n\n public static String resolveVariables(String text, Properties props, String startMarker, String endMarker) {\n int e = 0;\n int s = text.indexOf(startMarker);\n if (s == -1) {\n return text;\n } else {\n StringBuilder sb = new StringBuilder();\n do {\n if (e < s) {\n sb.append(text.substring(e, s));\n }\n e = text.indexOf(endMarker, s + startMarker.length());\n if (e != -1) {\n String key = text.substring(s + startMarker.length(), e);\n sb.append(props.getProperty(key, key));\n e += endMarker.length();\n s = text.indexOf(startMarker, e);\n } else {\n e = s;\n break;\n }\n } while (s != -1);\n if (e < text.length()) {\n sb.append(text.substring(e));\n }\n return sb.toString();\n }\n }\n}\n"} {"task_id": "Java_1457", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/keycloak/keycloak/services/src/main/java/org/keycloak/theme/TemplatingUtil.java", "mask_start_position": 416, "mask_end_position": 435, "canonical_solution": "\n int e = 0;", "pre_mask_code": "package org.keycloak.theme;\n\nimport java.util.Properties;\n\n/**\n * @author Marko Strukelj\n */\npublic class TemplatingUtil {\n\n public static String resolveVariables(String text, Properties props) {\n return resolveVariables(text, props, \"${\", \"}\");\n }\n\n public static String resolveVariables(String text, Properties props, String startMarker, String endMarker) {", "post_mask_code": "\n int s = text.indexOf(startMarker);\n if (s == -1) {\n return text;\n } else {\n StringBuilder sb = new StringBuilder();\n do {\n if (e < s) {\n sb.append(text.substring(e, s));\n }\n e = text.indexOf(endMarker, s + startMarker.length());\n if (e != -1) {\n String key = text.substring(s + startMarker.length(), e);\n sb.append(props.getProperty(key, key));\n e += endMarker.length();\n s = text.indexOf(startMarker, e);\n } else {\n e = s;\n break;\n }\n } while (s != -1);\n if (e < text.length()) {\n sb.append(text.substring(e));\n }\n return sb.toString();\n }\n }\n}\n"} {"task_id": "Java_1458", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/keycloak/keycloak/services/src/main/java/org/keycloak/theme/TemplatingUtil.java", "mask_start_position": 444, "mask_end_position": 478, "canonical_solution": "int s = text.indexOf(startMarker);", "pre_mask_code": "package org.keycloak.theme;\n\nimport java.util.Properties;\n\n/**\n * @author Marko Strukelj\n */\npublic class TemplatingUtil {\n\n public static String resolveVariables(String text, Properties props) {\n return resolveVariables(text, props, \"${\", \"}\");\n }\n\n public static String resolveVariables(String text, Properties props, String startMarker, String endMarker) {\n int e = 0;\n ", "post_mask_code": "\n if (s == -1) {\n return text;\n } else {\n StringBuilder sb = new StringBuilder();\n do {\n if (e < s) {\n sb.append(text.substring(e, s));\n }\n e = text.indexOf(endMarker, s + startMarker.length());\n if (e != -1) {\n String key = text.substring(s + startMarker.length(), e);\n sb.append(props.getProperty(key, key));\n e += endMarker.length();\n s = text.indexOf(startMarker, e);\n } else {\n e = s;\n break;\n }\n } while (s != -1);\n if (e < text.length()) {\n sb.append(text.substring(e));\n }\n return sb.toString();\n }\n }\n}\n"} {"task_id": "Java_1459", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/keycloak/keycloak/services/src/main/java/org/keycloak/theme/TemplatingUtil.java", "mask_start_position": 487, "mask_end_position": 1326, "canonical_solution": "if (s == -1) {\n return text;\n } else {\n StringBuilder sb = new StringBuilder();\n do {\n if (e < s) {\n sb.append(text.substring(e, s));\n }\n e = text.indexOf(endMarker, s + startMarker.length());\n if (e != -1) {\n String key = text.substring(s + startMarker.length(), e);\n sb.append(props.getProperty(key, key));\n e += endMarker.length();\n s = text.indexOf(startMarker, e);\n } else {\n e = s;\n break;\n }\n } while (s != -1);\n if (e < text.length()) {\n sb.append(text.substring(e));\n }\n return sb.toString();\n }\n }", "pre_mask_code": "package org.keycloak.theme;\n\nimport java.util.Properties;\n\n/**\n * @author Marko Strukelj\n */\npublic class TemplatingUtil {\n\n public static String resolveVariables(String text, Properties props) {\n return resolveVariables(text, props, \"${\", \"}\");\n }\n\n public static String resolveVariables(String text, Properties props, String startMarker, String endMarker) {\n int e = 0;\n int s = text.indexOf(startMarker);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1460", "language": "Java", "task_type": "single_line", "source_file": "java/github/keycloak/keycloak/services/src/main/java/org/keycloak/theme/TemplatingUtil.java", "mask_start_position": 269, "mask_end_position": 296, "canonical_solution": "es(text, props, \"${\", \"}\");", "pre_mask_code": "package org.keycloak.theme;\n\nimport java.util.Properties;\n\n/**\n * @author Marko Strukelj\n */\npublic class TemplatingUtil {\n\n public static String resolveVariables(String text, Properties props) {\n return resolveVariabl", "post_mask_code": "\n }\n\n public static String resolveVariables(String text, Properties props, String startMarker, String endMarker) {\n int e = 0;\n int s = text.indexOf(startMarker);\n if (s == -1) {\n return text;\n } else {\n StringBuilder sb = new StringBuilder();\n do {\n if (e < s) {\n sb.append(text.substring(e, s));\n }\n e = text.indexOf(endMarker, s + startMarker.length());\n if (e != -1) {\n String key = text.substring(s + startMarker.length(), e);\n sb.append(props.getProperty(key, key));\n e += endMarker.length();\n s = text.indexOf(startMarker, e);\n } else {\n e = s;\n break;\n }\n } while (s != -1);\n if (e < text.length()) {\n sb.append(text.substring(e));\n }\n return sb.toString();\n }\n }\n}\n"} {"task_id": "Java_1461", "language": "Java", "task_type": "if_statement", "source_file": "java/github/keycloak/keycloak/services/src/main/java/org/keycloak/theme/TemplatingUtil.java", "mask_start_position": 800, "mask_end_position": 1148, "canonical_solution": "if (e != -1) {\n String key = text.substring(s + startMarker.length(), e);\n sb.append(props.getProperty(key, key));\n e += endMarker.length();\n s = text.indexOf(startMarker, e);\n } else {\n e = s;\n break;\n }", "pre_mask_code": "package org.keycloak.theme;\n\nimport java.util.Properties;\n\n/**\n * @author Marko Strukelj\n */\npublic class TemplatingUtil {\n\n public static String resolveVariables(String text, Properties props) {\n return resolveVariables(text, props, \"${\", \"}\");\n }\n\n public static String resolveVariables(String text, Properties props, String startMarker, String endMarker) {\n int e = 0;\n int s = text.indexOf(startMarker);\n if (s == -1) {\n return text;\n } else {\n StringBuilder sb = new StringBuilder();\n do {\n if (e < s) {\n sb.append(text.substring(e, s));\n }\n e = text.indexOf(endMarker, s + startMarker.length());\n ", "post_mask_code": "\n } while (s != -1);\n if (e < text.length()) {\n sb.append(text.substring(e));\n }\n return sb.toString();\n }\n }\n}\n"} {"task_id": "Java_1462", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/eclipse-ee4j/cdi/api/src/main/java/jakarta/enterprise/inject/spi/ProcessInjectionTarget.java", "mask_start_position": 2379, "mask_end_position": 2422, "canonical_solution": "public AnnotatedType getAnnotatedType();", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source\n * full listing of individual contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://example.com\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage jakarta.enterprise.inject.spi;\n\n/**\n *

\n * The container fires an event of this type for every Java EE component class supporting injection that may be instantiated by\n * the container at runtime, including every managed bean declared using {@code jakarta.annotation.ManagedBean}, EJB session or\n * message-driven bean, enabled bean, enabled interceptor or enabled decorator.\n *

\n *

\n * Any observer of this event is permitted to wrap and/or replace the {@link InjectionTarget}. The\n * container must use the final value of this property, after all observers have been called, whenever it performs injection\n * upon the managed bean, session bean or other Java EE component class supporting injection.\n *

\n *

\n * For example, this observer decorates the {@code InjectionTarget} for all servlets.\n *

\n *\n *
\n * public <T extends Servlet> void decorateServlet(@Observes ProcessInjectionTarget<T> pit) {\n *     pit.setInjectionTarget(decorate(pit.getInjectionTarget()));\n * }\n * 
\n *

\n * If any observer method of a {@code ProcessInjectionTarget} event throws an exception, the exception is treated as a\n * definition error by the container.\n *

\n *\n * @see InjectionTarget\n * @author David Allen\n * @param The managed bean class, session bean class or Java EE component class supporting injection\n */\npublic interface ProcessInjectionTarget {\n\n /**\n * Returns the {@link AnnotatedType} representing the managed bean class, session bean class or\n * other Java EE component class supporting injection.\n *\n * @return the {@link AnnotatedType} of the bean with an injection target\n * @throws IllegalStateException if called outside of the observer method invocation\n */\n ", "post_mask_code": "\n\n /**\n * Returns the {@link InjectionTarget} object that will be used by the container to perform\n * injection.\n *\n * @return the {@link InjectionTarget} object which performs the injection\n * @throws IllegalStateException if called outside of the observer method invocation\n */\n public InjectionTarget getInjectionTarget();\n\n /**\n * Replaces the {@link InjectionTarget} which performs injection for this target.\n *\n * @param injectionTarget The new {@link InjectionTarget} to use\n * @throws IllegalStateException if called outside of the observer method invocation\n */\n public void setInjectionTarget(InjectionTarget injectionTarget);\n\n /**\n * Registers a definition error with the container, causing the container to abort deployment after bean discovery is\n * complete.\n *\n * @param t A {@link java.lang.Throwable} representing the definition error\n * @throws IllegalStateException if called outside of the observer method invocation\n */\n public void addDefinitionError(Throwable t);\n}\n"} {"task_id": "Java_1463", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Tencent/TubeMQ/tubemq-server/src/main/java/com/tencent/tubemq/server/common/utils/IdWorker.java", "mask_start_position": 1611, "mask_end_position": 1665, "canonical_solution": "private long tillNextMillis(final long lastTimestamp) ", "pre_mask_code": "/**\n * Tencent is pleased to support the open source community by making TubeMQ available.\n *

\n *

\n */\npackage com.tencent.tubemq.server.common.utils;\n\n/**\n * 来自于twitter项目snowflake的id产生方案,全局唯一,时间有序\n * http://example.com\n */\npublic class IdWorker {\n\n private static final long twepoch = 1350282310830L;\n\n private static final long workerIdBits = 10L;\n\n private static final long maxWorkerId = -1L ^ -1L << workerIdBits;\n\n private static final long sequenceBits = 12L;\n\n private static final long workerIdShift = sequenceBits;\n\n private static final long timestampLeftShift = sequenceBits + workerIdBits;\n\n private static final long sequenceMask = -1L ^ -1L << sequenceBits;\n\n private final long workerId;\n\n private long sequence = 0L;\n\n private long lastTimestamp = -1L;\n\n public IdWorker(final long workerId) {\n if (workerId > maxWorkerId || workerId < 0) {\n throw new IllegalArgumentException(String.format(\"worker Id required in range [%d , 0]\", maxWorkerId));\n }\n this.workerId = workerId;\n }\n\n public synchronized long nextId() {\n long timestamp = System.nanoTime();\n if (this.lastTimestamp == timestamp) {\n this.sequence = this.sequence + 1 & sequenceMask;\n if (this.sequence == 0) {\n timestamp = this.tillNextMillis(this.lastTimestamp);\n }\n } else {\n this.sequence = 0;\n }\n this.lastTimestamp = timestamp;\n return Math.abs(timestamp - twepoch << timestampLeftShift | this.workerId << workerIdShift | this.sequence);\n }\n\n ", "post_mask_code": "{\n long timestamp = System.nanoTime();\n while (timestamp <= lastTimestamp) {\n timestamp = System.nanoTime();\n }\n return timestamp;\n }\n}\n"} {"task_id": "Java_1464", "language": "Java", "task_type": "method_body", "source_file": "java/github/Tencent/TubeMQ/tubemq-server/src/main/java/com/tencent/tubemq/server/common/utils/IdWorker.java", "mask_start_position": 1665, "mask_end_position": 1840, "canonical_solution": "{\n long timestamp = System.nanoTime();\n while (timestamp <= lastTimestamp) {\n timestamp = System.nanoTime();\n }\n return timestamp;\n }", "pre_mask_code": "/**\n * Tencent is pleased to support the open source community by making TubeMQ available.\n *

\n *

\n */\npackage com.tencent.tubemq.server.common.utils;\n\n/**\n * 来自于twitter项目snowflake的id产生方案,全局唯一,时间有序\n * http://example.com\n */\npublic class IdWorker {\n\n private static final long twepoch = 1350282310830L;\n\n private static final long workerIdBits = 10L;\n\n private static final long maxWorkerId = -1L ^ -1L << workerIdBits;\n\n private static final long sequenceBits = 12L;\n\n private static final long workerIdShift = sequenceBits;\n\n private static final long timestampLeftShift = sequenceBits + workerIdBits;\n\n private static final long sequenceMask = -1L ^ -1L << sequenceBits;\n\n private final long workerId;\n\n private long sequence = 0L;\n\n private long lastTimestamp = -1L;\n\n public IdWorker(final long workerId) {\n if (workerId > maxWorkerId || workerId < 0) {\n throw new IllegalArgumentException(String.format(\"worker Id required in range [%d , 0]\", maxWorkerId));\n }\n this.workerId = workerId;\n }\n\n public synchronized long nextId() {\n long timestamp = System.nanoTime();\n if (this.lastTimestamp == timestamp) {\n this.sequence = this.sequence + 1 & sequenceMask;\n if (this.sequence == 0) {\n timestamp = this.tillNextMillis(this.lastTimestamp);\n }\n } else {\n this.sequence = 0;\n }\n this.lastTimestamp = timestamp;\n return Math.abs(timestamp - twepoch << timestampLeftShift | this.workerId << workerIdShift | this.sequence);\n }\n\n private long tillNextMillis(final long lastTimestamp) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1465", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Tencent/TubeMQ/tubemq-server/src/main/java/com/tencent/tubemq/server/common/utils/IdWorker.java", "mask_start_position": 1666, "mask_end_position": 1710, "canonical_solution": "\n long timestamp = System.nanoTime();", "pre_mask_code": "/**\n * Tencent is pleased to support the open source community by making TubeMQ available.\n *

\n *

\n */\npackage com.tencent.tubemq.server.common.utils;\n\n/**\n * 来自于twitter项目snowflake的id产生方案,全局唯一,时间有序\n * http://example.com\n */\npublic class IdWorker {\n\n private static final long twepoch = 1350282310830L;\n\n private static final long workerIdBits = 10L;\n\n private static final long maxWorkerId = -1L ^ -1L << workerIdBits;\n\n private static final long sequenceBits = 12L;\n\n private static final long workerIdShift = sequenceBits;\n\n private static final long timestampLeftShift = sequenceBits + workerIdBits;\n\n private static final long sequenceMask = -1L ^ -1L << sequenceBits;\n\n private final long workerId;\n\n private long sequence = 0L;\n\n private long lastTimestamp = -1L;\n\n public IdWorker(final long workerId) {\n if (workerId > maxWorkerId || workerId < 0) {\n throw new IllegalArgumentException(String.format(\"worker Id required in range [%d , 0]\", maxWorkerId));\n }\n this.workerId = workerId;\n }\n\n public synchronized long nextId() {\n long timestamp = System.nanoTime();\n if (this.lastTimestamp == timestamp) {\n this.sequence = this.sequence + 1 & sequenceMask;\n if (this.sequence == 0) {\n timestamp = this.tillNextMillis(this.lastTimestamp);\n }\n } else {\n this.sequence = 0;\n }\n this.lastTimestamp = timestamp;\n return Math.abs(timestamp - twepoch << timestampLeftShift | this.workerId << workerIdShift | this.sequence);\n }\n\n private long tillNextMillis(final long lastTimestamp) {", "post_mask_code": "\n while (timestamp <= lastTimestamp) {\n timestamp = System.nanoTime();\n }\n return timestamp;\n }\n}\n"} {"task_id": "Java_1466", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Tencent/TubeMQ/tubemq-server/src/main/java/com/tencent/tubemq/server/common/utils/IdWorker.java", "mask_start_position": 1719, "mask_end_position": 1808, "canonical_solution": "while (timestamp <= lastTimestamp) {\n timestamp = System.nanoTime();\n }", "pre_mask_code": "/**\n * Tencent is pleased to support the open source community by making TubeMQ available.\n *

\n *

\n */\npackage com.tencent.tubemq.server.common.utils;\n\n/**\n * 来自于twitter项目snowflake的id产生方案,全局唯一,时间有序\n * http://example.com\n */\npublic class IdWorker {\n\n private static final long twepoch = 1350282310830L;\n\n private static final long workerIdBits = 10L;\n\n private static final long maxWorkerId = -1L ^ -1L << workerIdBits;\n\n private static final long sequenceBits = 12L;\n\n private static final long workerIdShift = sequenceBits;\n\n private static final long timestampLeftShift = sequenceBits + workerIdBits;\n\n private static final long sequenceMask = -1L ^ -1L << sequenceBits;\n\n private final long workerId;\n\n private long sequence = 0L;\n\n private long lastTimestamp = -1L;\n\n public IdWorker(final long workerId) {\n if (workerId > maxWorkerId || workerId < 0) {\n throw new IllegalArgumentException(String.format(\"worker Id required in range [%d , 0]\", maxWorkerId));\n }\n this.workerId = workerId;\n }\n\n public synchronized long nextId() {\n long timestamp = System.nanoTime();\n if (this.lastTimestamp == timestamp) {\n this.sequence = this.sequence + 1 & sequenceMask;\n if (this.sequence == 0) {\n timestamp = this.tillNextMillis(this.lastTimestamp);\n }\n } else {\n this.sequence = 0;\n }\n this.lastTimestamp = timestamp;\n return Math.abs(timestamp - twepoch << timestampLeftShift | this.workerId << workerIdShift | this.sequence);\n }\n\n private long tillNextMillis(final long lastTimestamp) {\n long timestamp = System.nanoTime();\n ", "post_mask_code": "\n return timestamp;\n }\n}\n"} {"task_id": "Java_1467", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Tencent/TubeMQ/tubemq-server/src/main/java/com/tencent/tubemq/server/common/utils/IdWorker.java", "mask_start_position": 1817, "mask_end_position": 1840, "canonical_solution": "return timestamp;\n }", "pre_mask_code": "/**\n * Tencent is pleased to support the open source community by making TubeMQ available.\n *

\n *

\n */\npackage com.tencent.tubemq.server.common.utils;\n\n/**\n * 来自于twitter项目snowflake的id产生方案,全局唯一,时间有序\n * http://example.com\n */\npublic class IdWorker {\n\n private static final long twepoch = 1350282310830L;\n\n private static final long workerIdBits = 10L;\n\n private static final long maxWorkerId = -1L ^ -1L << workerIdBits;\n\n private static final long sequenceBits = 12L;\n\n private static final long workerIdShift = sequenceBits;\n\n private static final long timestampLeftShift = sequenceBits + workerIdBits;\n\n private static final long sequenceMask = -1L ^ -1L << sequenceBits;\n\n private final long workerId;\n\n private long sequence = 0L;\n\n private long lastTimestamp = -1L;\n\n public IdWorker(final long workerId) {\n if (workerId > maxWorkerId || workerId < 0) {\n throw new IllegalArgumentException(String.format(\"worker Id required in range [%d , 0]\", maxWorkerId));\n }\n this.workerId = workerId;\n }\n\n public synchronized long nextId() {\n long timestamp = System.nanoTime();\n if (this.lastTimestamp == timestamp) {\n this.sequence = this.sequence + 1 & sequenceMask;\n if (this.sequence == 0) {\n timestamp = this.tillNextMillis(this.lastTimestamp);\n }\n } else {\n this.sequence = 0;\n }\n this.lastTimestamp = timestamp;\n return Math.abs(timestamp - twepoch << timestampLeftShift | this.workerId << workerIdShift | this.sequence);\n }\n\n private long tillNextMillis(final long lastTimestamp) {\n long timestamp = System.nanoTime();\n while (timestamp <= lastTimestamp) {\n timestamp = System.nanoTime();\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1468", "language": "Java", "task_type": "single_line", "source_file": "java/github/Tencent/TubeMQ/tubemq-server/src/main/java/com/tencent/tubemq/server/common/utils/IdWorker.java", "mask_start_position": 1125, "mask_end_position": 1154, "canonical_solution": "imestamp = System.nanoTime();", "pre_mask_code": "/**\n * Tencent is pleased to support the open source community by making TubeMQ available.\n *

\n *

\n */\npackage com.tencent.tubemq.server.common.utils;\n\n/**\n * 来自于twitter项目snowflake的id产生方案,全局唯一,时间有序\n * http://example.com\n */\npublic class IdWorker {\n\n private static final long twepoch = 1350282310830L;\n\n private static final long workerIdBits = 10L;\n\n private static final long maxWorkerId = -1L ^ -1L << workerIdBits;\n\n private static final long sequenceBits = 12L;\n\n private static final long workerIdShift = sequenceBits;\n\n private static final long timestampLeftShift = sequenceBits + workerIdBits;\n\n private static final long sequenceMask = -1L ^ -1L << sequenceBits;\n\n private final long workerId;\n\n private long sequence = 0L;\n\n private long lastTimestamp = -1L;\n\n public IdWorker(final long workerId) {\n if (workerId > maxWorkerId || workerId < 0) {\n throw new IllegalArgumentException(String.format(\"worker Id required in range [%d , 0]\", maxWorkerId));\n }\n this.workerId = workerId;\n }\n\n public synchronized long nextId() {\n long t", "post_mask_code": "\n if (this.lastTimestamp == timestamp) {\n this.sequence = this.sequence + 1 & sequenceMask;\n if (this.sequence == 0) {\n timestamp = this.tillNextMillis(this.lastTimestamp);\n }\n } else {\n this.sequence = 0;\n }\n this.lastTimestamp = timestamp;\n return Math.abs(timestamp - twepoch << timestampLeftShift | this.workerId << workerIdShift | this.sequence);\n }\n\n private long tillNextMillis(final long lastTimestamp) {\n long timestamp = System.nanoTime();\n while (timestamp <= lastTimestamp) {\n timestamp = System.nanoTime();\n }\n return timestamp;\n }\n}\n"} {"task_id": "Java_1469", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Tencent/TubeMQ/tubemq-server/src/main/java/com/tencent/tubemq/server/common/utils/IdWorker.java", "mask_start_position": 858, "mask_end_position": 1029, "canonical_solution": "if (workerId > maxWorkerId || workerId < 0) {\n throw new IllegalArgumentException(String.format(\"worker Id required in range [%d , 0]\", maxWorkerId));\n }", "pre_mask_code": "/**\n * Tencent is pleased to support the open source community by making TubeMQ available.\n *

\n *

\n */\npackage com.tencent.tubemq.server.common.utils;\n\n/**\n * 来自于twitter项目snowflake的id产生方案,全局唯一,时间有序\n * http://example.com\n */\npublic class IdWorker {\n\n private static final long twepoch = 1350282310830L;\n\n private static final long workerIdBits = 10L;\n\n private static final long maxWorkerId = -1L ^ -1L << workerIdBits;\n\n private static final long sequenceBits = 12L;\n\n private static final long workerIdShift = sequenceBits;\n\n private static final long timestampLeftShift = sequenceBits + workerIdBits;\n\n private static final long sequenceMask = -1L ^ -1L << sequenceBits;\n\n private final long workerId;\n\n private long sequence = 0L;\n\n private long lastTimestamp = -1L;\n\n public IdWorker(final long workerId) {\n ", "post_mask_code": "\n this.workerId = workerId;\n }\n\n public synchronized long nextId() {\n long timestamp = System.nanoTime();\n if (this.lastTimestamp == timestamp) {\n this.sequence = this.sequence + 1 & sequenceMask;\n if (this.sequence == 0) {\n timestamp = this.tillNextMillis(this.lastTimestamp);\n }\n } else {\n this.sequence = 0;\n }\n this.lastTimestamp = timestamp;\n return Math.abs(timestamp - twepoch << timestampLeftShift | this.workerId << workerIdShift | this.sequence);\n }\n\n private long tillNextMillis(final long lastTimestamp) {\n long timestamp = System.nanoTime();\n while (timestamp <= lastTimestamp) {\n timestamp = System.nanoTime();\n }\n return timestamp;\n }\n}\n"} {"task_id": "Java_1470", "language": "Java", "task_type": "while_statement", "source_file": "java/github/Tencent/TubeMQ/tubemq-server/src/main/java/com/tencent/tubemq/server/common/utils/IdWorker.java", "mask_start_position": 1719, "mask_end_position": 1808, "canonical_solution": "while (timestamp <= lastTimestamp) {\n timestamp = System.nanoTime();\n }", "pre_mask_code": "/**\n * Tencent is pleased to support the open source community by making TubeMQ available.\n *

\n *

\n */\npackage com.tencent.tubemq.server.common.utils;\n\n/**\n * 来自于twitter项目snowflake的id产生方案,全局唯一,时间有序\n * http://example.com\n */\npublic class IdWorker {\n\n private static final long twepoch = 1350282310830L;\n\n private static final long workerIdBits = 10L;\n\n private static final long maxWorkerId = -1L ^ -1L << workerIdBits;\n\n private static final long sequenceBits = 12L;\n\n private static final long workerIdShift = sequenceBits;\n\n private static final long timestampLeftShift = sequenceBits + workerIdBits;\n\n private static final long sequenceMask = -1L ^ -1L << sequenceBits;\n\n private final long workerId;\n\n private long sequence = 0L;\n\n private long lastTimestamp = -1L;\n\n public IdWorker(final long workerId) {\n if (workerId > maxWorkerId || workerId < 0) {\n throw new IllegalArgumentException(String.format(\"worker Id required in range [%d , 0]\", maxWorkerId));\n }\n this.workerId = workerId;\n }\n\n public synchronized long nextId() {\n long timestamp = System.nanoTime();\n if (this.lastTimestamp == timestamp) {\n this.sequence = this.sequence + 1 & sequenceMask;\n if (this.sequence == 0) {\n timestamp = this.tillNextMillis(this.lastTimestamp);\n }\n } else {\n this.sequence = 0;\n }\n this.lastTimestamp = timestamp;\n return Math.abs(timestamp - twepoch << timestampLeftShift | this.workerId << workerIdShift | this.sequence);\n }\n\n private long tillNextMillis(final long lastTimestamp) {\n long timestamp = System.nanoTime();\n ", "post_mask_code": "\n return timestamp;\n }\n}\n"} {"task_id": "Java_1471", "language": "Java", "task_type": "method_signature", "source_file": "java/github/gnosygnu/xowa/140_dbs/src/gplx/dbs/stmts/Db_stmt_arg_list.java", "mask_start_position": 601, "mask_end_position": 664, "canonical_solution": "public Db_stmt_arg_list Crt_str_by_bry(String key, byte[] val) ", "pre_mask_code": "/*\nXOWA: the XOWA Offline Wiki Application\n\n\nThe terms of each license can be found in the source code repository:\n\n*/\npackage gplx.dbs.stmts;\n\nimport gplx.*;\nimport gplx.dbs.*;\n\npublic class Db_stmt_arg_list {\n\n private final List_adp list = List_adp_.New();\n\n public void Clear() {\n list.Clear();\n }\n\n public int Len() {\n return list.Len();\n }\n\n public Db_stmt_arg Get_at(int i) {\n return (Db_stmt_arg) list.Get_at(i);\n }\n\n public Db_stmt_arg_list Crt_int(String key, int val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__int, key, val);\n }\n\n ", "post_mask_code": "{\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, String_.new_u8(val));\n }\n\n public Db_stmt_arg_list Crt_str(String key, String val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, val);\n }\n\n public Db_stmt_arg_list Add(boolean crt, int tid, String key, Object val) {\n list.Add(new Db_stmt_arg(crt, tid, key, val));\n return this;\n }\n\n public void Fill(Db_stmt stmt) {\n int len = list.Len();\n for (int i = 0; i < len; ++i) {\n Db_stmt_arg arg = (Db_stmt_arg) list.Get_at(i);\n if (arg.Crt)\n Fill_crt(stmt, arg.Tid, arg.Key, arg.Val);\n else\n Fill_val(stmt, arg.Tid, arg.Key, arg.Val);\n }\n list.Clear();\n }\n\n public static void Fill_crt(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Crt_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Crt_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Crt_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Crt_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Crt_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Crt_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Crt_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Crt_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Crt_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n\n public static void Fill_val(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Val_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Val_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Val_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Val_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Val_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Val_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Val_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Val_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Val_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n}\n"} {"task_id": "Java_1472", "language": "Java", "task_type": "method_body", "source_file": "java/github/gnosygnu/xowa/140_dbs/src/gplx/dbs/stmts/Db_stmt_arg_list.java", "mask_start_position": 413, "mask_end_position": 465, "canonical_solution": "{\n return (Db_stmt_arg) list.Get_at(i);\n }", "pre_mask_code": "/*\nXOWA: the XOWA Offline Wiki Application\n\n\nThe terms of each license can be found in the source code repository:\n\n*/\npackage gplx.dbs.stmts;\n\nimport gplx.*;\nimport gplx.dbs.*;\n\npublic class Db_stmt_arg_list {\n\n private final List_adp list = List_adp_.New();\n\n public void Clear() {\n list.Clear();\n }\n\n public int Len() {\n return list.Len();\n }\n\n public Db_stmt_arg Get_at(int i) ", "post_mask_code": "\n\n public Db_stmt_arg_list Crt_int(String key, int val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__int, key, val);\n }\n\n public Db_stmt_arg_list Crt_str_by_bry(String key, byte[] val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, String_.new_u8(val));\n }\n\n public Db_stmt_arg_list Crt_str(String key, String val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, val);\n }\n\n public Db_stmt_arg_list Add(boolean crt, int tid, String key, Object val) {\n list.Add(new Db_stmt_arg(crt, tid, key, val));\n return this;\n }\n\n public void Fill(Db_stmt stmt) {\n int len = list.Len();\n for (int i = 0; i < len; ++i) {\n Db_stmt_arg arg = (Db_stmt_arg) list.Get_at(i);\n if (arg.Crt)\n Fill_crt(stmt, arg.Tid, arg.Key, arg.Val);\n else\n Fill_val(stmt, arg.Tid, arg.Key, arg.Val);\n }\n list.Clear();\n }\n\n public static void Fill_crt(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Crt_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Crt_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Crt_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Crt_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Crt_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Crt_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Crt_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Crt_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Crt_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n\n public static void Fill_val(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Val_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Val_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Val_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Val_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Val_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Val_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Val_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Val_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Val_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n}\n"} {"task_id": "Java_1473", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/gnosygnu/xowa/140_dbs/src/gplx/dbs/stmts/Db_stmt_arg_list.java", "mask_start_position": 2775, "mask_end_position": 2775, "canonical_solution": "", "pre_mask_code": "/*\nXOWA: the XOWA Offline Wiki Application\n\n\nThe terms of each license can be found in the source code repository:\n\n*/\npackage gplx.dbs.stmts;\n\nimport gplx.*;\nimport gplx.dbs.*;\n\npublic class Db_stmt_arg_list {\n\n private final List_adp list = List_adp_.New();\n\n public void Clear() {\n list.Clear();\n }\n\n public int Len() {\n return list.Len();\n }\n\n public Db_stmt_arg Get_at(int i) {\n return (Db_stmt_arg) list.Get_at(i);\n }\n\n public Db_stmt_arg_list Crt_int(String key, int val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__int, key, val);\n }\n\n public Db_stmt_arg_list Crt_str_by_bry(String key, byte[] val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, String_.new_u8(val));\n }\n\n public Db_stmt_arg_list Crt_str(String key, String val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, val);\n }\n\n public Db_stmt_arg_list Add(boolean crt, int tid, String key, Object val) {\n list.Add(new Db_stmt_arg(crt, tid, key, val));\n return this;\n }\n\n public void Fill(Db_stmt stmt) {\n int len = list.Len();\n for (int i = 0; i < len; ++i) {\n Db_stmt_arg arg = (Db_stmt_arg) list.Get_at(i);\n if (arg.Crt)\n Fill_crt(stmt, arg.Tid, arg.Key, arg.Val);\n else\n Fill_val(stmt, arg.Tid, arg.Key, arg.Val);\n }\n list.Clear();\n }\n\n public static void Fill_crt(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Crt_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Crt_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Crt_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Crt_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Crt_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Crt_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Crt_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Crt_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Crt_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n\n public static void Fill_val(Db_stmt stmt, int tid, String key, Object val) {", "post_mask_code": "\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Val_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Val_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Val_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Val_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Val_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Val_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Val_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Val_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Val_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n}\n"} {"task_id": "Java_1474", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/gnosygnu/xowa/140_dbs/src/gplx/dbs/stmts/Db_stmt_arg_list.java", "mask_start_position": 2784, "mask_end_position": 3967, "canonical_solution": "switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Val_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Val_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Val_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Val_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Val_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Val_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Val_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Val_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Val_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }", "pre_mask_code": "/*\nXOWA: the XOWA Offline Wiki Application\n\n\nThe terms of each license can be found in the source code repository:\n\n*/\npackage gplx.dbs.stmts;\n\nimport gplx.*;\nimport gplx.dbs.*;\n\npublic class Db_stmt_arg_list {\n\n private final List_adp list = List_adp_.New();\n\n public void Clear() {\n list.Clear();\n }\n\n public int Len() {\n return list.Len();\n }\n\n public Db_stmt_arg Get_at(int i) {\n return (Db_stmt_arg) list.Get_at(i);\n }\n\n public Db_stmt_arg_list Crt_int(String key, int val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__int, key, val);\n }\n\n public Db_stmt_arg_list Crt_str_by_bry(String key, byte[] val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, String_.new_u8(val));\n }\n\n public Db_stmt_arg_list Crt_str(String key, String val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, val);\n }\n\n public Db_stmt_arg_list Add(boolean crt, int tid, String key, Object val) {\n list.Add(new Db_stmt_arg(crt, tid, key, val));\n return this;\n }\n\n public void Fill(Db_stmt stmt) {\n int len = list.Len();\n for (int i = 0; i < len; ++i) {\n Db_stmt_arg arg = (Db_stmt_arg) list.Get_at(i);\n if (arg.Crt)\n Fill_crt(stmt, arg.Tid, arg.Key, arg.Val);\n else\n Fill_val(stmt, arg.Tid, arg.Key, arg.Val);\n }\n list.Clear();\n }\n\n public static void Fill_crt(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Crt_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Crt_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Crt_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Crt_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Crt_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Crt_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Crt_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Crt_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Crt_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n\n public static void Fill_val(Db_stmt stmt, int tid, String key, Object val) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1475", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/gnosygnu/xowa/140_dbs/src/gplx/dbs/stmts/Db_stmt_arg_list.java", "mask_start_position": 3972, "mask_end_position": 3973, "canonical_solution": "}", "pre_mask_code": "/*\nXOWA: the XOWA Offline Wiki Application\n\n\nThe terms of each license can be found in the source code repository:\n\n*/\npackage gplx.dbs.stmts;\n\nimport gplx.*;\nimport gplx.dbs.*;\n\npublic class Db_stmt_arg_list {\n\n private final List_adp list = List_adp_.New();\n\n public void Clear() {\n list.Clear();\n }\n\n public int Len() {\n return list.Len();\n }\n\n public Db_stmt_arg Get_at(int i) {\n return (Db_stmt_arg) list.Get_at(i);\n }\n\n public Db_stmt_arg_list Crt_int(String key, int val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__int, key, val);\n }\n\n public Db_stmt_arg_list Crt_str_by_bry(String key, byte[] val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, String_.new_u8(val));\n }\n\n public Db_stmt_arg_list Crt_str(String key, String val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, val);\n }\n\n public Db_stmt_arg_list Add(boolean crt, int tid, String key, Object val) {\n list.Add(new Db_stmt_arg(crt, tid, key, val));\n return this;\n }\n\n public void Fill(Db_stmt stmt) {\n int len = list.Len();\n for (int i = 0; i < len; ++i) {\n Db_stmt_arg arg = (Db_stmt_arg) list.Get_at(i);\n if (arg.Crt)\n Fill_crt(stmt, arg.Tid, arg.Key, arg.Val);\n else\n Fill_val(stmt, arg.Tid, arg.Key, arg.Val);\n }\n list.Clear();\n }\n\n public static void Fill_crt(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Crt_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Crt_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Crt_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Crt_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Crt_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Crt_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Crt_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Crt_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Crt_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n\n public static void Fill_val(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Val_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Val_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Val_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Val_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Val_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Val_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Val_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Val_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Val_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1476", "language": "Java", "task_type": "single_line", "source_file": "java/github/gnosygnu/xowa/140_dbs/src/gplx/dbs/stmts/Db_stmt_arg_list.java", "mask_start_position": 1040, "mask_end_position": 1041, "canonical_solution": ";", "pre_mask_code": "/*\nXOWA: the XOWA Offline Wiki Application\n\n\nThe terms of each license can be found in the source code repository:\n\n*/\npackage gplx.dbs.stmts;\n\nimport gplx.*;\nimport gplx.dbs.*;\n\npublic class Db_stmt_arg_list {\n\n private final List_adp list = List_adp_.New();\n\n public void Clear() {\n list.Clear();\n }\n\n public int Len() {\n return list.Len();\n }\n\n public Db_stmt_arg Get_at(int i) {\n return (Db_stmt_arg) list.Get_at(i);\n }\n\n public Db_stmt_arg_list Crt_int(String key, int val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__int, key, val);\n }\n\n public Db_stmt_arg_list Crt_str_by_bry(String key, byte[] val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, String_.new_u8(val));\n }\n\n public Db_stmt_arg_list Crt_str(String key, String val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, val);\n }\n\n public Db_stmt_arg_list Add(boolean crt, int tid, String key, Object val) {\n list.Add(new Db_stmt_arg(crt, tid, key, val));\n return this", "post_mask_code": "\n }\n\n public void Fill(Db_stmt stmt) {\n int len = list.Len();\n for (int i = 0; i < len; ++i) {\n Db_stmt_arg arg = (Db_stmt_arg) list.Get_at(i);\n if (arg.Crt)\n Fill_crt(stmt, arg.Tid, arg.Key, arg.Val);\n else\n Fill_val(stmt, arg.Tid, arg.Key, arg.Val);\n }\n list.Clear();\n }\n\n public static void Fill_crt(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Crt_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Crt_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Crt_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Crt_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Crt_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Crt_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Crt_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Crt_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Crt_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n\n public static void Fill_val(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Val_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Val_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Val_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Val_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Val_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Val_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Val_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Val_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Val_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n}\n"} {"task_id": "Java_1477", "language": "Java", "task_type": "if_statement", "source_file": "java/github/gnosygnu/xowa/140_dbs/src/gplx/dbs/stmts/Db_stmt_arg_list.java", "mask_start_position": 1228, "mask_end_position": 1375, "canonical_solution": "if (arg.Crt)\n Fill_crt(stmt, arg.Tid, arg.Key, arg.Val);\n else\n Fill_val(stmt, arg.Tid, arg.Key, arg.Val);", "pre_mask_code": "/*\nXOWA: the XOWA Offline Wiki Application\n\n\nThe terms of each license can be found in the source code repository:\n\n*/\npackage gplx.dbs.stmts;\n\nimport gplx.*;\nimport gplx.dbs.*;\n\npublic class Db_stmt_arg_list {\n\n private final List_adp list = List_adp_.New();\n\n public void Clear() {\n list.Clear();\n }\n\n public int Len() {\n return list.Len();\n }\n\n public Db_stmt_arg Get_at(int i) {\n return (Db_stmt_arg) list.Get_at(i);\n }\n\n public Db_stmt_arg_list Crt_int(String key, int val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__int, key, val);\n }\n\n public Db_stmt_arg_list Crt_str_by_bry(String key, byte[] val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, String_.new_u8(val));\n }\n\n public Db_stmt_arg_list Crt_str(String key, String val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, val);\n }\n\n public Db_stmt_arg_list Add(boolean crt, int tid, String key, Object val) {\n list.Add(new Db_stmt_arg(crt, tid, key, val));\n return this;\n }\n\n public void Fill(Db_stmt stmt) {\n int len = list.Len();\n for (int i = 0; i < len; ++i) {\n Db_stmt_arg arg = (Db_stmt_arg) list.Get_at(i);\n ", "post_mask_code": "\n }\n list.Clear();\n }\n\n public static void Fill_crt(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Crt_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Crt_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Crt_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Crt_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Crt_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Crt_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Crt_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Crt_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Crt_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n\n public static void Fill_val(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Val_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Val_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Val_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Val_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Val_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Val_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Val_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Val_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Val_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n}\n"} {"task_id": "Java_1478", "language": "Java", "task_type": "for_statement", "source_file": "java/github/gnosygnu/xowa/140_dbs/src/gplx/dbs/stmts/Db_stmt_arg_list.java", "mask_start_position": 1124, "mask_end_position": 1385, "canonical_solution": "for (int i = 0; i < len; ++i) {\n Db_stmt_arg arg = (Db_stmt_arg) list.Get_at(i);\n if (arg.Crt)\n Fill_crt(stmt, arg.Tid, arg.Key, arg.Val);\n else\n Fill_val(stmt, arg.Tid, arg.Key, arg.Val);\n }", "pre_mask_code": "/*\nXOWA: the XOWA Offline Wiki Application\n\n\nThe terms of each license can be found in the source code repository:\n\n*/\npackage gplx.dbs.stmts;\n\nimport gplx.*;\nimport gplx.dbs.*;\n\npublic class Db_stmt_arg_list {\n\n private final List_adp list = List_adp_.New();\n\n public void Clear() {\n list.Clear();\n }\n\n public int Len() {\n return list.Len();\n }\n\n public Db_stmt_arg Get_at(int i) {\n return (Db_stmt_arg) list.Get_at(i);\n }\n\n public Db_stmt_arg_list Crt_int(String key, int val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__int, key, val);\n }\n\n public Db_stmt_arg_list Crt_str_by_bry(String key, byte[] val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, String_.new_u8(val));\n }\n\n public Db_stmt_arg_list Crt_str(String key, String val) {\n return Add(Bool_.Y, Dbmeta_fld_tid.Tid__str, key, val);\n }\n\n public Db_stmt_arg_list Add(boolean crt, int tid, String key, Object val) {\n list.Add(new Db_stmt_arg(crt, tid, key, val));\n return this;\n }\n\n public void Fill(Db_stmt stmt) {\n int len = list.Len();\n ", "post_mask_code": "\n list.Clear();\n }\n\n public static void Fill_crt(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Crt_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Crt_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Crt_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Crt_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Crt_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Crt_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Crt_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Crt_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Crt_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n\n public static void Fill_val(Db_stmt stmt, int tid, String key, Object val) {\n switch(tid) {\n case Dbmeta_fld_tid.Tid__bool:\n stmt.Val_bool_as_byte(key, Bool_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__byte:\n stmt.Val_byte(key, Byte_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__int:\n stmt.Val_int(key, Int_.Cast(val));\n break;\n case Dbmeta_fld_tid.Tid__long:\n stmt.Val_long(key, Long_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__float:\n stmt.Val_float(key, Float_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__double:\n stmt.Val_double(key, Double_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__str:\n stmt.Val_str(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__text:\n stmt.Val_text(key, String_.cast(val));\n break;\n case Dbmeta_fld_tid.Tid__bry:\n stmt.Val_bry(key, Bry_.cast(val));\n break;\n default:\n throw Err_.new_unhandled_default(tid);\n }\n }\n}\n"} {"task_id": "Java_1479", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Ms0x0/Dayu/src/org/secbug/model/UrlCheckType.java", "mask_start_position": 213, "mask_end_position": 300, "canonical_solution": "@Override\n public boolean check(String url, String recogninfo, String responseInfo) ", "pre_mask_code": "package org.secbug.model;\n\nimport org.apache.log4j.Logger;\nimport org.secbug.conf.Context;\n\npublic class UrlCheckType implements CheckType {\n\n private Logger logger = Logger.getLogger(UrlCheckType.class);\n\n ", "post_mask_code": "{\n boolean falg = false;\n if (responseInfo.equals(\"true\")) {\n falg = true;\n return falg;\n }\n logger.info(\"当前jobid:\" + Context.jobid + \" 检验状态:\" + falg + \" 识别内容:\" + recogninfo + \" URL:\" + url);\n return falg;\n }\n}\n"} {"task_id": "Java_1480", "language": "Java", "task_type": "method_body", "source_file": "java/github/Ms0x0/Dayu/src/org/secbug/model/UrlCheckType.java", "mask_start_position": 300, "mask_end_position": 568, "canonical_solution": "{\n boolean falg = false;\n if (responseInfo.equals(\"true\")) {\n falg = true;\n return falg;\n }\n logger.info(\"当前jobid:\" + Context.jobid + \" 检验状态:\" + falg + \" 识别内容:\" + recogninfo + \" URL:\" + url);\n return falg;\n }", "pre_mask_code": "package org.secbug.model;\n\nimport org.apache.log4j.Logger;\nimport org.secbug.conf.Context;\n\npublic class UrlCheckType implements CheckType {\n\n private Logger logger = Logger.getLogger(UrlCheckType.class);\n\n @Override\n public boolean check(String url, String recogninfo, String responseInfo) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1481", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Ms0x0/Dayu/src/org/secbug/model/UrlCheckType.java", "mask_start_position": 301, "mask_end_position": 331, "canonical_solution": "\n boolean falg = false;", "pre_mask_code": "package org.secbug.model;\n\nimport org.apache.log4j.Logger;\nimport org.secbug.conf.Context;\n\npublic class UrlCheckType implements CheckType {\n\n private Logger logger = Logger.getLogger(UrlCheckType.class);\n\n @Override\n public boolean check(String url, String recogninfo, String responseInfo) {", "post_mask_code": "\n if (responseInfo.equals(\"true\")) {\n falg = true;\n return falg;\n }\n logger.info(\"当前jobid:\" + Context.jobid + \" 检验状态:\" + falg + \" 识别内容:\" + recogninfo + \" URL:\" + url);\n return falg;\n }\n}\n"} {"task_id": "Java_1482", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Ms0x0/Dayu/src/org/secbug/model/UrlCheckType.java", "mask_start_position": 340, "mask_end_position": 541, "canonical_solution": "if (responseInfo.equals(\"true\")) {\n falg = true;\n return falg;\n }\n logger.info(\"当前jobid:\" + Context.jobid + \" 检验状态:\" + falg + \" 识别内容:\" + recogninfo + \" URL:\" + url);", "pre_mask_code": "package org.secbug.model;\n\nimport org.apache.log4j.Logger;\nimport org.secbug.conf.Context;\n\npublic class UrlCheckType implements CheckType {\n\n private Logger logger = Logger.getLogger(UrlCheckType.class);\n\n @Override\n public boolean check(String url, String recogninfo, String responseInfo) {\n boolean falg = false;\n ", "post_mask_code": "\n return falg;\n }\n}\n"} {"task_id": "Java_1483", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Ms0x0/Dayu/src/org/secbug/model/UrlCheckType.java", "mask_start_position": 550, "mask_end_position": 568, "canonical_solution": "return falg;\n }", "pre_mask_code": "package org.secbug.model;\n\nimport org.apache.log4j.Logger;\nimport org.secbug.conf.Context;\n\npublic class UrlCheckType implements CheckType {\n\n private Logger logger = Logger.getLogger(UrlCheckType.class);\n\n @Override\n public boolean check(String url, String recogninfo, String responseInfo) {\n boolean falg = false;\n if (responseInfo.equals(\"true\")) {\n falg = true;\n return falg;\n }\n logger.info(\"当前jobid:\" + Context.jobid + \" 检验状态:\" + falg + \" 识别内容:\" + recogninfo + \" URL:\" + url);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1484", "language": "Java", "task_type": "single_line", "source_file": "java/github/Ms0x0/Dayu/src/org/secbug/model/UrlCheckType.java", "mask_start_position": 554, "mask_end_position": 562, "canonical_solution": "rn falg;", "pre_mask_code": "package org.secbug.model;\n\nimport org.apache.log4j.Logger;\nimport org.secbug.conf.Context;\n\npublic class UrlCheckType implements CheckType {\n\n private Logger logger = Logger.getLogger(UrlCheckType.class);\n\n @Override\n public boolean check(String url, String recogninfo, String responseInfo) {\n boolean falg = false;\n if (responseInfo.equals(\"true\")) {\n falg = true;\n return falg;\n }\n logger.info(\"当前jobid:\" + Context.jobid + \" 检验状态:\" + falg + \" 识别内容:\" + recogninfo + \" URL:\" + url);\n retu", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1485", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Ms0x0/Dayu/src/org/secbug/model/UrlCheckType.java", "mask_start_position": 340, "mask_end_position": 434, "canonical_solution": "if (responseInfo.equals(\"true\")) {\n falg = true;\n return falg;\n }", "pre_mask_code": "package org.secbug.model;\n\nimport org.apache.log4j.Logger;\nimport org.secbug.conf.Context;\n\npublic class UrlCheckType implements CheckType {\n\n private Logger logger = Logger.getLogger(UrlCheckType.class);\n\n @Override\n public boolean check(String url, String recogninfo, String responseInfo) {\n boolean falg = false;\n ", "post_mask_code": "\n logger.info(\"当前jobid:\" + Context.jobid + \" 检验状态:\" + falg + \" 识别内容:\" + recogninfo + \" URL:\" + url);\n return falg;\n }\n}\n"} {"task_id": "Java_1486", "language": "Java", "task_type": "method_signature", "source_file": "java/github/WeTheInternet/xapi/collect/src/main/java/xapi/collect/impl/StringToAbstract.java", "mask_start_position": 1628, "mask_end_position": 1662, "canonical_solution": "@Override\n public void clear() ", "pre_mask_code": "package xapi.collect.impl;\n\nimport xapi.annotation.inject.InstanceDefault;\nimport xapi.collect.api.StringTo;\nimport xapi.fu.itr.MappedIterable;\nimport xapi.fu.Out2;\nimport xapi.fu.itr.SizedIterable;\nimport xapi.fu.itr.SizedIterator;\nimport xapi.platform.GwtDevPlatform;\nimport xapi.platform.JrePlatform;\nimport xapi.util.X_Runtime;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.ConcurrentHashMap;\n\n@JrePlatform\n@GwtDevPlatform\n@InstanceDefault(implFor = StringTo.class)\npublic class StringToAbstract implements StringTo {\n\n private static final long serialVersionUID = 7743120861632536635L;\n\n private final java.util.Map map;\n\n private final Class valueType;\n\n public StringToAbstract(Class valueType) {\n this.valueType = valueType;\n if (isMultithreaded()) {\n map = new ConcurrentHashMap<>();\n } else {\n map = new HashMap<>();\n }\n }\n\n public StringToAbstract(Class valueType, final Map map) {\n this.valueType = Class.class.cast(valueType);\n this.map = map;\n }\n\n protected boolean isMultithreaded() {\n return X_Runtime.isMultithreaded();\n }\n\n @Override\n public SizedIterator> iterator() {\n final MappedIterable> entries = MappedIterable.mapped(entries());\n return SizedIterator.of(this::size, entries.map(Out2::fromEntry).iterator());\n }\n\n @Override\n public boolean isEmpty() {\n return map.isEmpty();\n }\n\n ", "post_mask_code": "{\n map.clear();\n }\n\n @Override\n public final boolean containsKey(final Object key) {\n return has((String) key);\n }\n\n public boolean has(String key) {\n return map.containsKey(key);\n }\n\n @Override\n public boolean containsValue(final Object key) {\n return map.containsValue(key);\n }\n\n @Override\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public void putEntries(final Iterable> items) {\n if (items instanceof java.util.Map) {\n map.putAll((java.util.Map) items);\n } else {\n for (final java.util.Map.Entry item : items) {\n map.put(item.getKey(), item.getValue());\n }\n }\n }\n\n @Override\n public void addAll(Iterable> items) {\n for (final Out2 item : items) {\n map.put(item.out1(), item.out2());\n }\n }\n\n @Override\n public void removeAll(final Iterable items) {\n for (final String item : items) {\n map.remove(item);\n }\n }\n\n @Override\n public SizedIterable keys() {\n return SizedIterable.of(this::size, map.keySet());\n }\n\n @Override\n public String[] keyArray() {\n return map.keySet().toArray(new String[0]);\n }\n\n @Override\n public Iterable values() {\n return map.values();\n }\n\n @Override\n public Class keyType() {\n return String.class;\n }\n\n @Override\n public Class valueType() {\n return valueType;\n }\n\n @Override\n public Iterable> entries() {\n return map.entrySet();\n }\n\n @Override\n public V get(final String key) {\n return map.get(key);\n }\n\n @Override\n public V put(final String key, final V value) {\n if (value == null) {\n return map.remove(key);\n } else {\n return map.put(key, value);\n }\n }\n\n @Override\n public V remove(final String key) {\n return map.remove(key);\n }\n\n @Override\n public int size() {\n return map.size();\n }\n\n @Override\n public String toString() {\n return forEachItem().join(o -> o.join(\" = \"), \"\\n\");\n }\n\n protected Collection valueSet() {\n return map.values();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n final StringToAbstract that = (StringToAbstract) o;\n if (!map.equals(that.map))\n return false;\n return valueType != null ? valueType.equals(that.valueType) : that.valueType == null;\n }\n\n @Override\n public int hashCode() {\n int result = map.hashCode();\n result = 31 * result + (valueType != null ? valueType.hashCode() : 0);\n return result;\n }\n}\n"} {"task_id": "Java_1487", "language": "Java", "task_type": "method_body", "source_file": "java/github/WeTheInternet/xapi/collect/src/main/java/xapi/collect/impl/StringToAbstract.java", "mask_start_position": 2671, "mask_end_position": 2760, "canonical_solution": "{\n for (final String item : items) {\n map.remove(item);\n }\n }", "pre_mask_code": "package xapi.collect.impl;\n\nimport xapi.annotation.inject.InstanceDefault;\nimport xapi.collect.api.StringTo;\nimport xapi.fu.itr.MappedIterable;\nimport xapi.fu.Out2;\nimport xapi.fu.itr.SizedIterable;\nimport xapi.fu.itr.SizedIterator;\nimport xapi.platform.GwtDevPlatform;\nimport xapi.platform.JrePlatform;\nimport xapi.util.X_Runtime;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.ConcurrentHashMap;\n\n@JrePlatform\n@GwtDevPlatform\n@InstanceDefault(implFor = StringTo.class)\npublic class StringToAbstract implements StringTo {\n\n private static final long serialVersionUID = 7743120861632536635L;\n\n private final java.util.Map map;\n\n private final Class valueType;\n\n public StringToAbstract(Class valueType) {\n this.valueType = valueType;\n if (isMultithreaded()) {\n map = new ConcurrentHashMap<>();\n } else {\n map = new HashMap<>();\n }\n }\n\n public StringToAbstract(Class valueType, final Map map) {\n this.valueType = Class.class.cast(valueType);\n this.map = map;\n }\n\n protected boolean isMultithreaded() {\n return X_Runtime.isMultithreaded();\n }\n\n @Override\n public SizedIterator> iterator() {\n final MappedIterable> entries = MappedIterable.mapped(entries());\n return SizedIterator.of(this::size, entries.map(Out2::fromEntry).iterator());\n }\n\n @Override\n public boolean isEmpty() {\n return map.isEmpty();\n }\n\n @Override\n public void clear() {\n map.clear();\n }\n\n @Override\n public final boolean containsKey(final Object key) {\n return has((String) key);\n }\n\n public boolean has(String key) {\n return map.containsKey(key);\n }\n\n @Override\n public boolean containsValue(final Object key) {\n return map.containsValue(key);\n }\n\n @Override\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public void putEntries(final Iterable> items) {\n if (items instanceof java.util.Map) {\n map.putAll((java.util.Map) items);\n } else {\n for (final java.util.Map.Entry item : items) {\n map.put(item.getKey(), item.getValue());\n }\n }\n }\n\n @Override\n public void addAll(Iterable> items) {\n for (final Out2 item : items) {\n map.put(item.out1(), item.out2());\n }\n }\n\n @Override\n public void removeAll(final Iterable items) ", "post_mask_code": "\n\n @Override\n public SizedIterable keys() {\n return SizedIterable.of(this::size, map.keySet());\n }\n\n @Override\n public String[] keyArray() {\n return map.keySet().toArray(new String[0]);\n }\n\n @Override\n public Iterable values() {\n return map.values();\n }\n\n @Override\n public Class keyType() {\n return String.class;\n }\n\n @Override\n public Class valueType() {\n return valueType;\n }\n\n @Override\n public Iterable> entries() {\n return map.entrySet();\n }\n\n @Override\n public V get(final String key) {\n return map.get(key);\n }\n\n @Override\n public V put(final String key, final V value) {\n if (value == null) {\n return map.remove(key);\n } else {\n return map.put(key, value);\n }\n }\n\n @Override\n public V remove(final String key) {\n return map.remove(key);\n }\n\n @Override\n public int size() {\n return map.size();\n }\n\n @Override\n public String toString() {\n return forEachItem().join(o -> o.join(\" = \"), \"\\n\");\n }\n\n protected Collection valueSet() {\n return map.values();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n final StringToAbstract that = (StringToAbstract) o;\n if (!map.equals(that.map))\n return false;\n return valueType != null ? valueType.equals(that.valueType) : that.valueType == null;\n }\n\n @Override\n public int hashCode() {\n int result = map.hashCode();\n result = 31 * result + (valueType != null ? valueType.hashCode() : 0);\n return result;\n }\n}\n"} {"task_id": "Java_1488", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/WeTheInternet/xapi/collect/src/main/java/xapi/collect/impl/StringToAbstract.java", "mask_start_position": 2145, "mask_end_position": 2145, "canonical_solution": "", "pre_mask_code": "package xapi.collect.impl;\n\nimport xapi.annotation.inject.InstanceDefault;\nimport xapi.collect.api.StringTo;\nimport xapi.fu.itr.MappedIterable;\nimport xapi.fu.Out2;\nimport xapi.fu.itr.SizedIterable;\nimport xapi.fu.itr.SizedIterator;\nimport xapi.platform.GwtDevPlatform;\nimport xapi.platform.JrePlatform;\nimport xapi.util.X_Runtime;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.ConcurrentHashMap;\n\n@JrePlatform\n@GwtDevPlatform\n@InstanceDefault(implFor = StringTo.class)\npublic class StringToAbstract implements StringTo {\n\n private static final long serialVersionUID = 7743120861632536635L;\n\n private final java.util.Map map;\n\n private final Class valueType;\n\n public StringToAbstract(Class valueType) {\n this.valueType = valueType;\n if (isMultithreaded()) {\n map = new ConcurrentHashMap<>();\n } else {\n map = new HashMap<>();\n }\n }\n\n public StringToAbstract(Class valueType, final Map map) {\n this.valueType = Class.class.cast(valueType);\n this.map = map;\n }\n\n protected boolean isMultithreaded() {\n return X_Runtime.isMultithreaded();\n }\n\n @Override\n public SizedIterator> iterator() {\n final MappedIterable> entries = MappedIterable.mapped(entries());\n return SizedIterator.of(this::size, entries.map(Out2::fromEntry).iterator());\n }\n\n @Override\n public boolean isEmpty() {\n return map.isEmpty();\n }\n\n @Override\n public void clear() {\n map.clear();\n }\n\n @Override\n public final boolean containsKey(final Object key) {\n return has((String) key);\n }\n\n public boolean has(String key) {\n return map.containsKey(key);\n }\n\n @Override\n public boolean containsValue(final Object key) {\n return map.containsValue(key);\n }\n\n @Override\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public void putEntries(final Iterable> items) {", "post_mask_code": "\n if (items instanceof java.util.Map) {\n map.putAll((java.util.Map) items);\n } else {\n for (final java.util.Map.Entry item : items) {\n map.put(item.getKey(), item.getValue());\n }\n }\n }\n\n @Override\n public void addAll(Iterable> items) {\n for (final Out2 item : items) {\n map.put(item.out1(), item.out2());\n }\n }\n\n @Override\n public void removeAll(final Iterable items) {\n for (final String item : items) {\n map.remove(item);\n }\n }\n\n @Override\n public SizedIterable keys() {\n return SizedIterable.of(this::size, map.keySet());\n }\n\n @Override\n public String[] keyArray() {\n return map.keySet().toArray(new String[0]);\n }\n\n @Override\n public Iterable values() {\n return map.values();\n }\n\n @Override\n public Class keyType() {\n return String.class;\n }\n\n @Override\n public Class valueType() {\n return valueType;\n }\n\n @Override\n public Iterable> entries() {\n return map.entrySet();\n }\n\n @Override\n public V get(final String key) {\n return map.get(key);\n }\n\n @Override\n public V put(final String key, final V value) {\n if (value == null) {\n return map.remove(key);\n } else {\n return map.put(key, value);\n }\n }\n\n @Override\n public V remove(final String key) {\n return map.remove(key);\n }\n\n @Override\n public int size() {\n return map.size();\n }\n\n @Override\n public String toString() {\n return forEachItem().join(o -> o.join(\" = \"), \"\\n\");\n }\n\n protected Collection valueSet() {\n return map.values();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n final StringToAbstract that = (StringToAbstract) o;\n if (!map.equals(that.map))\n return false;\n return valueType != null ? valueType.equals(that.valueType) : that.valueType == null;\n }\n\n @Override\n public int hashCode() {\n int result = map.hashCode();\n result = 31 * result + (valueType != null ? valueType.hashCode() : 0);\n return result;\n }\n}\n"} {"task_id": "Java_1489", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/WeTheInternet/xapi/collect/src/main/java/xapi/collect/impl/StringToAbstract.java", "mask_start_position": 2154, "mask_end_position": 2406, "canonical_solution": "if (items instanceof java.util.Map) {\n map.putAll((java.util.Map) items);\n } else {\n for (final java.util.Map.Entry item : items) {\n map.put(item.getKey(), item.getValue());\n }\n }", "pre_mask_code": "package xapi.collect.impl;\n\nimport xapi.annotation.inject.InstanceDefault;\nimport xapi.collect.api.StringTo;\nimport xapi.fu.itr.MappedIterable;\nimport xapi.fu.Out2;\nimport xapi.fu.itr.SizedIterable;\nimport xapi.fu.itr.SizedIterator;\nimport xapi.platform.GwtDevPlatform;\nimport xapi.platform.JrePlatform;\nimport xapi.util.X_Runtime;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.ConcurrentHashMap;\n\n@JrePlatform\n@GwtDevPlatform\n@InstanceDefault(implFor = StringTo.class)\npublic class StringToAbstract implements StringTo {\n\n private static final long serialVersionUID = 7743120861632536635L;\n\n private final java.util.Map map;\n\n private final Class valueType;\n\n public StringToAbstract(Class valueType) {\n this.valueType = valueType;\n if (isMultithreaded()) {\n map = new ConcurrentHashMap<>();\n } else {\n map = new HashMap<>();\n }\n }\n\n public StringToAbstract(Class valueType, final Map map) {\n this.valueType = Class.class.cast(valueType);\n this.map = map;\n }\n\n protected boolean isMultithreaded() {\n return X_Runtime.isMultithreaded();\n }\n\n @Override\n public SizedIterator> iterator() {\n final MappedIterable> entries = MappedIterable.mapped(entries());\n return SizedIterator.of(this::size, entries.map(Out2::fromEntry).iterator());\n }\n\n @Override\n public boolean isEmpty() {\n return map.isEmpty();\n }\n\n @Override\n public void clear() {\n map.clear();\n }\n\n @Override\n public final boolean containsKey(final Object key) {\n return has((String) key);\n }\n\n public boolean has(String key) {\n return map.containsKey(key);\n }\n\n @Override\n public boolean containsValue(final Object key) {\n return map.containsValue(key);\n }\n\n @Override\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public void putEntries(final Iterable> items) {\n ", "post_mask_code": "\n }\n\n @Override\n public void addAll(Iterable> items) {\n for (final Out2 item : items) {\n map.put(item.out1(), item.out2());\n }\n }\n\n @Override\n public void removeAll(final Iterable items) {\n for (final String item : items) {\n map.remove(item);\n }\n }\n\n @Override\n public SizedIterable keys() {\n return SizedIterable.of(this::size, map.keySet());\n }\n\n @Override\n public String[] keyArray() {\n return map.keySet().toArray(new String[0]);\n }\n\n @Override\n public Iterable values() {\n return map.values();\n }\n\n @Override\n public Class keyType() {\n return String.class;\n }\n\n @Override\n public Class valueType() {\n return valueType;\n }\n\n @Override\n public Iterable> entries() {\n return map.entrySet();\n }\n\n @Override\n public V get(final String key) {\n return map.get(key);\n }\n\n @Override\n public V put(final String key, final V value) {\n if (value == null) {\n return map.remove(key);\n } else {\n return map.put(key, value);\n }\n }\n\n @Override\n public V remove(final String key) {\n return map.remove(key);\n }\n\n @Override\n public int size() {\n return map.size();\n }\n\n @Override\n public String toString() {\n return forEachItem().join(o -> o.join(\" = \"), \"\\n\");\n }\n\n protected Collection valueSet() {\n return map.values();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n final StringToAbstract that = (StringToAbstract) o;\n if (!map.equals(that.map))\n return false;\n return valueType != null ? valueType.equals(that.valueType) : that.valueType == null;\n }\n\n @Override\n public int hashCode() {\n int result = map.hashCode();\n result = 31 * result + (valueType != null ? valueType.hashCode() : 0);\n return result;\n }\n}\n"} {"task_id": "Java_1490", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/WeTheInternet/xapi/collect/src/main/java/xapi/collect/impl/StringToAbstract.java", "mask_start_position": 2411, "mask_end_position": 2412, "canonical_solution": "}", "pre_mask_code": "package xapi.collect.impl;\n\nimport xapi.annotation.inject.InstanceDefault;\nimport xapi.collect.api.StringTo;\nimport xapi.fu.itr.MappedIterable;\nimport xapi.fu.Out2;\nimport xapi.fu.itr.SizedIterable;\nimport xapi.fu.itr.SizedIterator;\nimport xapi.platform.GwtDevPlatform;\nimport xapi.platform.JrePlatform;\nimport xapi.util.X_Runtime;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.ConcurrentHashMap;\n\n@JrePlatform\n@GwtDevPlatform\n@InstanceDefault(implFor = StringTo.class)\npublic class StringToAbstract implements StringTo {\n\n private static final long serialVersionUID = 7743120861632536635L;\n\n private final java.util.Map map;\n\n private final Class valueType;\n\n public StringToAbstract(Class valueType) {\n this.valueType = valueType;\n if (isMultithreaded()) {\n map = new ConcurrentHashMap<>();\n } else {\n map = new HashMap<>();\n }\n }\n\n public StringToAbstract(Class valueType, final Map map) {\n this.valueType = Class.class.cast(valueType);\n this.map = map;\n }\n\n protected boolean isMultithreaded() {\n return X_Runtime.isMultithreaded();\n }\n\n @Override\n public SizedIterator> iterator() {\n final MappedIterable> entries = MappedIterable.mapped(entries());\n return SizedIterator.of(this::size, entries.map(Out2::fromEntry).iterator());\n }\n\n @Override\n public boolean isEmpty() {\n return map.isEmpty();\n }\n\n @Override\n public void clear() {\n map.clear();\n }\n\n @Override\n public final boolean containsKey(final Object key) {\n return has((String) key);\n }\n\n public boolean has(String key) {\n return map.containsKey(key);\n }\n\n @Override\n public boolean containsValue(final Object key) {\n return map.containsValue(key);\n }\n\n @Override\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public void putEntries(final Iterable> items) {\n if (items instanceof java.util.Map) {\n map.putAll((java.util.Map) items);\n } else {\n for (final java.util.Map.Entry item : items) {\n map.put(item.getKey(), item.getValue());\n }\n }\n ", "post_mask_code": "\n\n @Override\n public void addAll(Iterable> items) {\n for (final Out2 item : items) {\n map.put(item.out1(), item.out2());\n }\n }\n\n @Override\n public void removeAll(final Iterable items) {\n for (final String item : items) {\n map.remove(item);\n }\n }\n\n @Override\n public SizedIterable keys() {\n return SizedIterable.of(this::size, map.keySet());\n }\n\n @Override\n public String[] keyArray() {\n return map.keySet().toArray(new String[0]);\n }\n\n @Override\n public Iterable values() {\n return map.values();\n }\n\n @Override\n public Class keyType() {\n return String.class;\n }\n\n @Override\n public Class valueType() {\n return valueType;\n }\n\n @Override\n public Iterable> entries() {\n return map.entrySet();\n }\n\n @Override\n public V get(final String key) {\n return map.get(key);\n }\n\n @Override\n public V put(final String key, final V value) {\n if (value == null) {\n return map.remove(key);\n } else {\n return map.put(key, value);\n }\n }\n\n @Override\n public V remove(final String key) {\n return map.remove(key);\n }\n\n @Override\n public int size() {\n return map.size();\n }\n\n @Override\n public String toString() {\n return forEachItem().join(o -> o.join(\" = \"), \"\\n\");\n }\n\n protected Collection valueSet() {\n return map.values();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n final StringToAbstract that = (StringToAbstract) o;\n if (!map.equals(that.map))\n return false;\n return valueType != null ? valueType.equals(that.valueType) : that.valueType == null;\n }\n\n @Override\n public int hashCode() {\n int result = map.hashCode();\n result = 31 * result + (valueType != null ? valueType.hashCode() : 0);\n return result;\n }\n}\n"} {"task_id": "Java_1491", "language": "Java", "task_type": "single_line", "source_file": "java/github/WeTheInternet/xapi/collect/src/main/java/xapi/collect/impl/StringToAbstract.java", "mask_start_position": 3221, "mask_end_position": 3234, "canonical_solution": "rn valueType;", "pre_mask_code": "package xapi.collect.impl;\n\nimport xapi.annotation.inject.InstanceDefault;\nimport xapi.collect.api.StringTo;\nimport xapi.fu.itr.MappedIterable;\nimport xapi.fu.Out2;\nimport xapi.fu.itr.SizedIterable;\nimport xapi.fu.itr.SizedIterator;\nimport xapi.platform.GwtDevPlatform;\nimport xapi.platform.JrePlatform;\nimport xapi.util.X_Runtime;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.ConcurrentHashMap;\n\n@JrePlatform\n@GwtDevPlatform\n@InstanceDefault(implFor = StringTo.class)\npublic class StringToAbstract implements StringTo {\n\n private static final long serialVersionUID = 7743120861632536635L;\n\n private final java.util.Map map;\n\n private final Class valueType;\n\n public StringToAbstract(Class valueType) {\n this.valueType = valueType;\n if (isMultithreaded()) {\n map = new ConcurrentHashMap<>();\n } else {\n map = new HashMap<>();\n }\n }\n\n public StringToAbstract(Class valueType, final Map map) {\n this.valueType = Class.class.cast(valueType);\n this.map = map;\n }\n\n protected boolean isMultithreaded() {\n return X_Runtime.isMultithreaded();\n }\n\n @Override\n public SizedIterator> iterator() {\n final MappedIterable> entries = MappedIterable.mapped(entries());\n return SizedIterator.of(this::size, entries.map(Out2::fromEntry).iterator());\n }\n\n @Override\n public boolean isEmpty() {\n return map.isEmpty();\n }\n\n @Override\n public void clear() {\n map.clear();\n }\n\n @Override\n public final boolean containsKey(final Object key) {\n return has((String) key);\n }\n\n public boolean has(String key) {\n return map.containsKey(key);\n }\n\n @Override\n public boolean containsValue(final Object key) {\n return map.containsValue(key);\n }\n\n @Override\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public void putEntries(final Iterable> items) {\n if (items instanceof java.util.Map) {\n map.putAll((java.util.Map) items);\n } else {\n for (final java.util.Map.Entry item : items) {\n map.put(item.getKey(), item.getValue());\n }\n }\n }\n\n @Override\n public void addAll(Iterable> items) {\n for (final Out2 item : items) {\n map.put(item.out1(), item.out2());\n }\n }\n\n @Override\n public void removeAll(final Iterable items) {\n for (final String item : items) {\n map.remove(item);\n }\n }\n\n @Override\n public SizedIterable keys() {\n return SizedIterable.of(this::size, map.keySet());\n }\n\n @Override\n public String[] keyArray() {\n return map.keySet().toArray(new String[0]);\n }\n\n @Override\n public Iterable values() {\n return map.values();\n }\n\n @Override\n public Class keyType() {\n return String.class;\n }\n\n @Override\n public Class valueType() {\n retu", "post_mask_code": "\n }\n\n @Override\n public Iterable> entries() {\n return map.entrySet();\n }\n\n @Override\n public V get(final String key) {\n return map.get(key);\n }\n\n @Override\n public V put(final String key, final V value) {\n if (value == null) {\n return map.remove(key);\n } else {\n return map.put(key, value);\n }\n }\n\n @Override\n public V remove(final String key) {\n return map.remove(key);\n }\n\n @Override\n public int size() {\n return map.size();\n }\n\n @Override\n public String toString() {\n return forEachItem().join(o -> o.join(\" = \"), \"\\n\");\n }\n\n protected Collection valueSet() {\n return map.values();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n final StringToAbstract that = (StringToAbstract) o;\n if (!map.equals(that.map))\n return false;\n return valueType != null ? valueType.equals(that.valueType) : that.valueType == null;\n }\n\n @Override\n public int hashCode() {\n int result = map.hashCode();\n result = 31 * result + (valueType != null ? valueType.hashCode() : 0);\n return result;\n }\n}\n"} {"task_id": "Java_1492", "language": "Java", "task_type": "if_statement", "source_file": "java/github/WeTheInternet/xapi/collect/src/main/java/xapi/collect/impl/StringToAbstract.java", "mask_start_position": 2154, "mask_end_position": 2406, "canonical_solution": "if (items instanceof java.util.Map) {\n map.putAll((java.util.Map) items);\n } else {\n for (final java.util.Map.Entry item : items) {\n map.put(item.getKey(), item.getValue());\n }\n }", "pre_mask_code": "package xapi.collect.impl;\n\nimport xapi.annotation.inject.InstanceDefault;\nimport xapi.collect.api.StringTo;\nimport xapi.fu.itr.MappedIterable;\nimport xapi.fu.Out2;\nimport xapi.fu.itr.SizedIterable;\nimport xapi.fu.itr.SizedIterator;\nimport xapi.platform.GwtDevPlatform;\nimport xapi.platform.JrePlatform;\nimport xapi.util.X_Runtime;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.ConcurrentHashMap;\n\n@JrePlatform\n@GwtDevPlatform\n@InstanceDefault(implFor = StringTo.class)\npublic class StringToAbstract implements StringTo {\n\n private static final long serialVersionUID = 7743120861632536635L;\n\n private final java.util.Map map;\n\n private final Class valueType;\n\n public StringToAbstract(Class valueType) {\n this.valueType = valueType;\n if (isMultithreaded()) {\n map = new ConcurrentHashMap<>();\n } else {\n map = new HashMap<>();\n }\n }\n\n public StringToAbstract(Class valueType, final Map map) {\n this.valueType = Class.class.cast(valueType);\n this.map = map;\n }\n\n protected boolean isMultithreaded() {\n return X_Runtime.isMultithreaded();\n }\n\n @Override\n public SizedIterator> iterator() {\n final MappedIterable> entries = MappedIterable.mapped(entries());\n return SizedIterator.of(this::size, entries.map(Out2::fromEntry).iterator());\n }\n\n @Override\n public boolean isEmpty() {\n return map.isEmpty();\n }\n\n @Override\n public void clear() {\n map.clear();\n }\n\n @Override\n public final boolean containsKey(final Object key) {\n return has((String) key);\n }\n\n public boolean has(String key) {\n return map.containsKey(key);\n }\n\n @Override\n public boolean containsValue(final Object key) {\n return map.containsValue(key);\n }\n\n @Override\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public void putEntries(final Iterable> items) {\n ", "post_mask_code": "\n }\n\n @Override\n public void addAll(Iterable> items) {\n for (final Out2 item : items) {\n map.put(item.out1(), item.out2());\n }\n }\n\n @Override\n public void removeAll(final Iterable items) {\n for (final String item : items) {\n map.remove(item);\n }\n }\n\n @Override\n public SizedIterable keys() {\n return SizedIterable.of(this::size, map.keySet());\n }\n\n @Override\n public String[] keyArray() {\n return map.keySet().toArray(new String[0]);\n }\n\n @Override\n public Iterable values() {\n return map.values();\n }\n\n @Override\n public Class keyType() {\n return String.class;\n }\n\n @Override\n public Class valueType() {\n return valueType;\n }\n\n @Override\n public Iterable> entries() {\n return map.entrySet();\n }\n\n @Override\n public V get(final String key) {\n return map.get(key);\n }\n\n @Override\n public V put(final String key, final V value) {\n if (value == null) {\n return map.remove(key);\n } else {\n return map.put(key, value);\n }\n }\n\n @Override\n public V remove(final String key) {\n return map.remove(key);\n }\n\n @Override\n public int size() {\n return map.size();\n }\n\n @Override\n public String toString() {\n return forEachItem().join(o -> o.join(\" = \"), \"\\n\");\n }\n\n protected Collection valueSet() {\n return map.values();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n final StringToAbstract that = (StringToAbstract) o;\n if (!map.equals(that.map))\n return false;\n return valueType != null ? valueType.equals(that.valueType) : that.valueType == null;\n }\n\n @Override\n public int hashCode() {\n int result = map.hashCode();\n result = 31 * result + (valueType != null ? valueType.hashCode() : 0);\n return result;\n }\n}\n"} {"task_id": "Java_1493", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/vzw/nfc/AidFilter.java", "mask_start_position": 4376, "mask_end_position": 4421, "canonical_solution": "private static INfcVzw getServiceInterface() ", "pre_mask_code": "package com.vzw.nfc;\n\nimport android.nfc.INfcAdapter.Stub;\nimport android.os.IBinder;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.util.Log;\nimport com.nxp.nfc.INfcVzw;\nimport com.nxp.nfc.INxpNfcAdapter;\nimport com.vzw.nfc.dos.AidMaskDo;\nimport com.vzw.nfc.dos.AidRangeDo;\nimport com.vzw.nfc.dos.ClfFilterDo;\nimport com.vzw.nfc.dos.ClfFilterDoList;\nimport com.vzw.nfc.dos.DoParserException;\nimport com.vzw.nfc.dos.FilterConditionTagDo;\nimport com.vzw.nfc.dos.FilterEntryDo;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n\npublic final class AidFilter {\n\n private static INfcVzw sVzwNfcAdapter;\n\n public final int DEFAULT_ROUTE_LOCATION = 2;\n\n public boolean setFilterList(byte[] filterList) {\n boolean status = true;\n ClfFilterDoList allClfFilterDo = new ClfFilterDoList(filterList, 0, filterList.length);\n try {\n allClfFilterDo.translate();\n ArrayList entries = new ArrayList();\n prepareRouteInfo(allClfFilterDo, entries);\n if (getServiceInterface() != null) {\n try {\n status = getServiceInterface().setVzwAidList((RouteEntry[]) entries.toArray(new RouteEntry[entries.size()]));\n } catch (RemoteException e) {\n status = false;\n }\n }\n return status;\n } catch (DoParserException e2) {\n e2.printStackTrace();\n return false;\n }\n }\n\n public boolean enableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(true);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n public boolean disableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(false);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n private void prepareRouteInfo(ClfFilterDoList allClfFilterDo, ArrayList entries) {\n Iterator it = allClfFilterDo.getClfFilterDos().iterator();\n while (it.hasNext()) {\n ClfFilterDo clfDoFilter = (ClfFilterDo) it.next();\n byte[] aid = getAid(clfDoFilter.getFilterEntryDo().getAidRangeDo(), clfDoFilter.getFilterEntryDo().getAidMaskDo());\n int powerState = getPowerState(clfDoFilter.getFilterEntryDo());\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"prepareRouteInfo powerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n entries.add(new RouteEntry(aid, powerState, 2, clfDoFilter.getFilterEntryDo().getVzwArDo().isVzwAllowed()));\n }\n }\n\n private byte[] getAid(AidRangeDo aid_range, AidMaskDo aid_mask) {\n byte[] barr_aid_mask = aid_mask.getAidMask();\n int count = 0;\n while (count < barr_aid_mask.length && barr_aid_mask[count] == (byte) -1) {\n count++;\n }\n if (count == 0) {\n return null;\n }\n byte[] aid = new byte[count];\n System.arraycopy(aid_range.getAidRange(), 0, aid, 0, count);\n return aid;\n }\n\n private int getPowerState(FilterEntryDo filter_entry_do) {\n int powerState = 0;\n int routeInfo = filter_entry_do.getRoutingModeDo().getRoutingInfo();\n FilterConditionTagDo conditionTagDo = filter_entry_do.getFilterConditionTagDo();\n if (conditionTagDo != null && conditionTagDo.getFilterConditionTag() == FilterConditionTagDo.SCREEN_OFF_TAG) {\n powerState = 1;\n } else if (routeInfo != 0) {\n powerState = ((((routeInfo & 1) << 2) | (routeInfo & 2)) | ((routeInfo & 4) >> 2)) | 128;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"getPowerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n return powerState;\n }\n\n ", "post_mask_code": "{\n if (sVzwNfcAdapter != null) {\n return sVzwNfcAdapter;\n }\n IBinder b = ServiceManager.getService(\"nfc\");\n if (b == null) {\n return null;\n }\n try {\n IBinder b2 = Stub.asInterface(b).getNfcAdapterVendorInterface(\"nxp\");\n if (b2 == null) {\n return null;\n }\n sVzwNfcAdapter = INxpNfcAdapter.Stub.asInterface(b2).getNfcVzwInterface();\n return sVzwNfcAdapter;\n } catch (Exception e) {\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_1494", "language": "Java", "task_type": "method_body", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/vzw/nfc/AidFilter.java", "mask_start_position": 3194, "mask_end_position": 3581, "canonical_solution": "{\n byte[] barr_aid_mask = aid_mask.getAidMask();\n int count = 0;\n while (count < barr_aid_mask.length && barr_aid_mask[count] == (byte) -1) {\n count++;\n }\n if (count == 0) {\n return null;\n }\n byte[] aid = new byte[count];\n System.arraycopy(aid_range.getAidRange(), 0, aid, 0, count);\n return aid;\n }", "pre_mask_code": "package com.vzw.nfc;\n\nimport android.nfc.INfcAdapter.Stub;\nimport android.os.IBinder;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.util.Log;\nimport com.nxp.nfc.INfcVzw;\nimport com.nxp.nfc.INxpNfcAdapter;\nimport com.vzw.nfc.dos.AidMaskDo;\nimport com.vzw.nfc.dos.AidRangeDo;\nimport com.vzw.nfc.dos.ClfFilterDo;\nimport com.vzw.nfc.dos.ClfFilterDoList;\nimport com.vzw.nfc.dos.DoParserException;\nimport com.vzw.nfc.dos.FilterConditionTagDo;\nimport com.vzw.nfc.dos.FilterEntryDo;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n\npublic final class AidFilter {\n\n private static INfcVzw sVzwNfcAdapter;\n\n public final int DEFAULT_ROUTE_LOCATION = 2;\n\n public boolean setFilterList(byte[] filterList) {\n boolean status = true;\n ClfFilterDoList allClfFilterDo = new ClfFilterDoList(filterList, 0, filterList.length);\n try {\n allClfFilterDo.translate();\n ArrayList entries = new ArrayList();\n prepareRouteInfo(allClfFilterDo, entries);\n if (getServiceInterface() != null) {\n try {\n status = getServiceInterface().setVzwAidList((RouteEntry[]) entries.toArray(new RouteEntry[entries.size()]));\n } catch (RemoteException e) {\n status = false;\n }\n }\n return status;\n } catch (DoParserException e2) {\n e2.printStackTrace();\n return false;\n }\n }\n\n public boolean enableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(true);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n public boolean disableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(false);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n private void prepareRouteInfo(ClfFilterDoList allClfFilterDo, ArrayList entries) {\n Iterator it = allClfFilterDo.getClfFilterDos().iterator();\n while (it.hasNext()) {\n ClfFilterDo clfDoFilter = (ClfFilterDo) it.next();\n byte[] aid = getAid(clfDoFilter.getFilterEntryDo().getAidRangeDo(), clfDoFilter.getFilterEntryDo().getAidMaskDo());\n int powerState = getPowerState(clfDoFilter.getFilterEntryDo());\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"prepareRouteInfo powerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n entries.add(new RouteEntry(aid, powerState, 2, clfDoFilter.getFilterEntryDo().getVzwArDo().isVzwAllowed()));\n }\n }\n\n private byte[] getAid(AidRangeDo aid_range, AidMaskDo aid_mask) ", "post_mask_code": "\n\n private int getPowerState(FilterEntryDo filter_entry_do) {\n int powerState = 0;\n int routeInfo = filter_entry_do.getRoutingModeDo().getRoutingInfo();\n FilterConditionTagDo conditionTagDo = filter_entry_do.getFilterConditionTagDo();\n if (conditionTagDo != null && conditionTagDo.getFilterConditionTag() == FilterConditionTagDo.SCREEN_OFF_TAG) {\n powerState = 1;\n } else if (routeInfo != 0) {\n powerState = ((((routeInfo & 1) << 2) | (routeInfo & 2)) | ((routeInfo & 4) >> 2)) | 128;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"getPowerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n return powerState;\n }\n\n private static INfcVzw getServiceInterface() {\n if (sVzwNfcAdapter != null) {\n return sVzwNfcAdapter;\n }\n IBinder b = ServiceManager.getService(\"nfc\");\n if (b == null) {\n return null;\n }\n try {\n IBinder b2 = Stub.asInterface(b).getNfcAdapterVendorInterface(\"nxp\");\n if (b2 == null) {\n return null;\n }\n sVzwNfcAdapter = INxpNfcAdapter.Stub.asInterface(b2).getNfcVzwInterface();\n return sVzwNfcAdapter;\n } catch (Exception e) {\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_1495", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/vzw/nfc/AidFilter.java", "mask_start_position": 2390, "mask_end_position": 2457, "canonical_solution": "\n Iterator it = allClfFilterDo.getClfFilterDos().iterator();", "pre_mask_code": "package com.vzw.nfc;\n\nimport android.nfc.INfcAdapter.Stub;\nimport android.os.IBinder;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.util.Log;\nimport com.nxp.nfc.INfcVzw;\nimport com.nxp.nfc.INxpNfcAdapter;\nimport com.vzw.nfc.dos.AidMaskDo;\nimport com.vzw.nfc.dos.AidRangeDo;\nimport com.vzw.nfc.dos.ClfFilterDo;\nimport com.vzw.nfc.dos.ClfFilterDoList;\nimport com.vzw.nfc.dos.DoParserException;\nimport com.vzw.nfc.dos.FilterConditionTagDo;\nimport com.vzw.nfc.dos.FilterEntryDo;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n\npublic final class AidFilter {\n\n private static INfcVzw sVzwNfcAdapter;\n\n public final int DEFAULT_ROUTE_LOCATION = 2;\n\n public boolean setFilterList(byte[] filterList) {\n boolean status = true;\n ClfFilterDoList allClfFilterDo = new ClfFilterDoList(filterList, 0, filterList.length);\n try {\n allClfFilterDo.translate();\n ArrayList entries = new ArrayList();\n prepareRouteInfo(allClfFilterDo, entries);\n if (getServiceInterface() != null) {\n try {\n status = getServiceInterface().setVzwAidList((RouteEntry[]) entries.toArray(new RouteEntry[entries.size()]));\n } catch (RemoteException e) {\n status = false;\n }\n }\n return status;\n } catch (DoParserException e2) {\n e2.printStackTrace();\n return false;\n }\n }\n\n public boolean enableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(true);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n public boolean disableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(false);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n private void prepareRouteInfo(ClfFilterDoList allClfFilterDo, ArrayList entries) {", "post_mask_code": "\n while (it.hasNext()) {\n ClfFilterDo clfDoFilter = (ClfFilterDo) it.next();\n byte[] aid = getAid(clfDoFilter.getFilterEntryDo().getAidRangeDo(), clfDoFilter.getFilterEntryDo().getAidMaskDo());\n int powerState = getPowerState(clfDoFilter.getFilterEntryDo());\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"prepareRouteInfo powerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n entries.add(new RouteEntry(aid, powerState, 2, clfDoFilter.getFilterEntryDo().getVzwArDo().isVzwAllowed()));\n }\n }\n\n private byte[] getAid(AidRangeDo aid_range, AidMaskDo aid_mask) {\n byte[] barr_aid_mask = aid_mask.getAidMask();\n int count = 0;\n while (count < barr_aid_mask.length && barr_aid_mask[count] == (byte) -1) {\n count++;\n }\n if (count == 0) {\n return null;\n }\n byte[] aid = new byte[count];\n System.arraycopy(aid_range.getAidRange(), 0, aid, 0, count);\n return aid;\n }\n\n private int getPowerState(FilterEntryDo filter_entry_do) {\n int powerState = 0;\n int routeInfo = filter_entry_do.getRoutingModeDo().getRoutingInfo();\n FilterConditionTagDo conditionTagDo = filter_entry_do.getFilterConditionTagDo();\n if (conditionTagDo != null && conditionTagDo.getFilterConditionTag() == FilterConditionTagDo.SCREEN_OFF_TAG) {\n powerState = 1;\n } else if (routeInfo != 0) {\n powerState = ((((routeInfo & 1) << 2) | (routeInfo & 2)) | ((routeInfo & 4) >> 2)) | 128;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"getPowerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n return powerState;\n }\n\n private static INfcVzw getServiceInterface() {\n if (sVzwNfcAdapter != null) {\n return sVzwNfcAdapter;\n }\n IBinder b = ServiceManager.getService(\"nfc\");\n if (b == null) {\n return null;\n }\n try {\n IBinder b2 = Stub.asInterface(b).getNfcAdapterVendorInterface(\"nxp\");\n if (b2 == null) {\n return null;\n }\n sVzwNfcAdapter = INxpNfcAdapter.Stub.asInterface(b2).getNfcVzwInterface();\n return sVzwNfcAdapter;\n } catch (Exception e) {\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_1496", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/vzw/nfc/AidFilter.java", "mask_start_position": 2466, "mask_end_position": 3118, "canonical_solution": "while (it.hasNext()) {\n ClfFilterDo clfDoFilter = (ClfFilterDo) it.next();\n byte[] aid = getAid(clfDoFilter.getFilterEntryDo().getAidRangeDo(), clfDoFilter.getFilterEntryDo().getAidMaskDo());\n int powerState = getPowerState(clfDoFilter.getFilterEntryDo());\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"prepareRouteInfo powerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n entries.add(new RouteEntry(aid, powerState, 2, clfDoFilter.getFilterEntryDo().getVzwArDo().isVzwAllowed()));\n }", "pre_mask_code": "package com.vzw.nfc;\n\nimport android.nfc.INfcAdapter.Stub;\nimport android.os.IBinder;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.util.Log;\nimport com.nxp.nfc.INfcVzw;\nimport com.nxp.nfc.INxpNfcAdapter;\nimport com.vzw.nfc.dos.AidMaskDo;\nimport com.vzw.nfc.dos.AidRangeDo;\nimport com.vzw.nfc.dos.ClfFilterDo;\nimport com.vzw.nfc.dos.ClfFilterDoList;\nimport com.vzw.nfc.dos.DoParserException;\nimport com.vzw.nfc.dos.FilterConditionTagDo;\nimport com.vzw.nfc.dos.FilterEntryDo;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n\npublic final class AidFilter {\n\n private static INfcVzw sVzwNfcAdapter;\n\n public final int DEFAULT_ROUTE_LOCATION = 2;\n\n public boolean setFilterList(byte[] filterList) {\n boolean status = true;\n ClfFilterDoList allClfFilterDo = new ClfFilterDoList(filterList, 0, filterList.length);\n try {\n allClfFilterDo.translate();\n ArrayList entries = new ArrayList();\n prepareRouteInfo(allClfFilterDo, entries);\n if (getServiceInterface() != null) {\n try {\n status = getServiceInterface().setVzwAidList((RouteEntry[]) entries.toArray(new RouteEntry[entries.size()]));\n } catch (RemoteException e) {\n status = false;\n }\n }\n return status;\n } catch (DoParserException e2) {\n e2.printStackTrace();\n return false;\n }\n }\n\n public boolean enableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(true);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n public boolean disableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(false);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n private void prepareRouteInfo(ClfFilterDoList allClfFilterDo, ArrayList entries) {\n Iterator it = allClfFilterDo.getClfFilterDos().iterator();\n ", "post_mask_code": "\n }\n\n private byte[] getAid(AidRangeDo aid_range, AidMaskDo aid_mask) {\n byte[] barr_aid_mask = aid_mask.getAidMask();\n int count = 0;\n while (count < barr_aid_mask.length && barr_aid_mask[count] == (byte) -1) {\n count++;\n }\n if (count == 0) {\n return null;\n }\n byte[] aid = new byte[count];\n System.arraycopy(aid_range.getAidRange(), 0, aid, 0, count);\n return aid;\n }\n\n private int getPowerState(FilterEntryDo filter_entry_do) {\n int powerState = 0;\n int routeInfo = filter_entry_do.getRoutingModeDo().getRoutingInfo();\n FilterConditionTagDo conditionTagDo = filter_entry_do.getFilterConditionTagDo();\n if (conditionTagDo != null && conditionTagDo.getFilterConditionTag() == FilterConditionTagDo.SCREEN_OFF_TAG) {\n powerState = 1;\n } else if (routeInfo != 0) {\n powerState = ((((routeInfo & 1) << 2) | (routeInfo & 2)) | ((routeInfo & 4) >> 2)) | 128;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"getPowerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n return powerState;\n }\n\n private static INfcVzw getServiceInterface() {\n if (sVzwNfcAdapter != null) {\n return sVzwNfcAdapter;\n }\n IBinder b = ServiceManager.getService(\"nfc\");\n if (b == null) {\n return null;\n }\n try {\n IBinder b2 = Stub.asInterface(b).getNfcAdapterVendorInterface(\"nxp\");\n if (b2 == null) {\n return null;\n }\n sVzwNfcAdapter = INxpNfcAdapter.Stub.asInterface(b2).getNfcVzwInterface();\n return sVzwNfcAdapter;\n } catch (Exception e) {\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_1497", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/vzw/nfc/AidFilter.java", "mask_start_position": 3123, "mask_end_position": 3124, "canonical_solution": "}", "pre_mask_code": "package com.vzw.nfc;\n\nimport android.nfc.INfcAdapter.Stub;\nimport android.os.IBinder;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.util.Log;\nimport com.nxp.nfc.INfcVzw;\nimport com.nxp.nfc.INxpNfcAdapter;\nimport com.vzw.nfc.dos.AidMaskDo;\nimport com.vzw.nfc.dos.AidRangeDo;\nimport com.vzw.nfc.dos.ClfFilterDo;\nimport com.vzw.nfc.dos.ClfFilterDoList;\nimport com.vzw.nfc.dos.DoParserException;\nimport com.vzw.nfc.dos.FilterConditionTagDo;\nimport com.vzw.nfc.dos.FilterEntryDo;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n\npublic final class AidFilter {\n\n private static INfcVzw sVzwNfcAdapter;\n\n public final int DEFAULT_ROUTE_LOCATION = 2;\n\n public boolean setFilterList(byte[] filterList) {\n boolean status = true;\n ClfFilterDoList allClfFilterDo = new ClfFilterDoList(filterList, 0, filterList.length);\n try {\n allClfFilterDo.translate();\n ArrayList entries = new ArrayList();\n prepareRouteInfo(allClfFilterDo, entries);\n if (getServiceInterface() != null) {\n try {\n status = getServiceInterface().setVzwAidList((RouteEntry[]) entries.toArray(new RouteEntry[entries.size()]));\n } catch (RemoteException e) {\n status = false;\n }\n }\n return status;\n } catch (DoParserException e2) {\n e2.printStackTrace();\n return false;\n }\n }\n\n public boolean enableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(true);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n public boolean disableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(false);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n private void prepareRouteInfo(ClfFilterDoList allClfFilterDo, ArrayList entries) {\n Iterator it = allClfFilterDo.getClfFilterDos().iterator();\n while (it.hasNext()) {\n ClfFilterDo clfDoFilter = (ClfFilterDo) it.next();\n byte[] aid = getAid(clfDoFilter.getFilterEntryDo().getAidRangeDo(), clfDoFilter.getFilterEntryDo().getAidMaskDo());\n int powerState = getPowerState(clfDoFilter.getFilterEntryDo());\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"prepareRouteInfo powerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n entries.add(new RouteEntry(aid, powerState, 2, clfDoFilter.getFilterEntryDo().getVzwArDo().isVzwAllowed()));\n }\n ", "post_mask_code": "\n\n private byte[] getAid(AidRangeDo aid_range, AidMaskDo aid_mask) {\n byte[] barr_aid_mask = aid_mask.getAidMask();\n int count = 0;\n while (count < barr_aid_mask.length && barr_aid_mask[count] == (byte) -1) {\n count++;\n }\n if (count == 0) {\n return null;\n }\n byte[] aid = new byte[count];\n System.arraycopy(aid_range.getAidRange(), 0, aid, 0, count);\n return aid;\n }\n\n private int getPowerState(FilterEntryDo filter_entry_do) {\n int powerState = 0;\n int routeInfo = filter_entry_do.getRoutingModeDo().getRoutingInfo();\n FilterConditionTagDo conditionTagDo = filter_entry_do.getFilterConditionTagDo();\n if (conditionTagDo != null && conditionTagDo.getFilterConditionTag() == FilterConditionTagDo.SCREEN_OFF_TAG) {\n powerState = 1;\n } else if (routeInfo != 0) {\n powerState = ((((routeInfo & 1) << 2) | (routeInfo & 2)) | ((routeInfo & 4) >> 2)) | 128;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"getPowerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n return powerState;\n }\n\n private static INfcVzw getServiceInterface() {\n if (sVzwNfcAdapter != null) {\n return sVzwNfcAdapter;\n }\n IBinder b = ServiceManager.getService(\"nfc\");\n if (b == null) {\n return null;\n }\n try {\n IBinder b2 = Stub.asInterface(b).getNfcAdapterVendorInterface(\"nxp\");\n if (b2 == null) {\n return null;\n }\n sVzwNfcAdapter = INxpNfcAdapter.Stub.asInterface(b2).getNfcVzwInterface();\n return sVzwNfcAdapter;\n } catch (Exception e) {\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_1498", "language": "Java", "task_type": "single_line", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/vzw/nfc/AidFilter.java", "mask_start_position": 4307, "mask_end_position": 4337, "canonical_solution": "r\", stringBuilder.toString());", "pre_mask_code": "package com.vzw.nfc;\n\nimport android.nfc.INfcAdapter.Stub;\nimport android.os.IBinder;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.util.Log;\nimport com.nxp.nfc.INfcVzw;\nimport com.nxp.nfc.INxpNfcAdapter;\nimport com.vzw.nfc.dos.AidMaskDo;\nimport com.vzw.nfc.dos.AidRangeDo;\nimport com.vzw.nfc.dos.ClfFilterDo;\nimport com.vzw.nfc.dos.ClfFilterDoList;\nimport com.vzw.nfc.dos.DoParserException;\nimport com.vzw.nfc.dos.FilterConditionTagDo;\nimport com.vzw.nfc.dos.FilterEntryDo;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n\npublic final class AidFilter {\n\n private static INfcVzw sVzwNfcAdapter;\n\n public final int DEFAULT_ROUTE_LOCATION = 2;\n\n public boolean setFilterList(byte[] filterList) {\n boolean status = true;\n ClfFilterDoList allClfFilterDo = new ClfFilterDoList(filterList, 0, filterList.length);\n try {\n allClfFilterDo.translate();\n ArrayList entries = new ArrayList();\n prepareRouteInfo(allClfFilterDo, entries);\n if (getServiceInterface() != null) {\n try {\n status = getServiceInterface().setVzwAidList((RouteEntry[]) entries.toArray(new RouteEntry[entries.size()]));\n } catch (RemoteException e) {\n status = false;\n }\n }\n return status;\n } catch (DoParserException e2) {\n e2.printStackTrace();\n return false;\n }\n }\n\n public boolean enableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(true);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n public boolean disableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(false);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n private void prepareRouteInfo(ClfFilterDoList allClfFilterDo, ArrayList entries) {\n Iterator it = allClfFilterDo.getClfFilterDos().iterator();\n while (it.hasNext()) {\n ClfFilterDo clfDoFilter = (ClfFilterDo) it.next();\n byte[] aid = getAid(clfDoFilter.getFilterEntryDo().getAidRangeDo(), clfDoFilter.getFilterEntryDo().getAidMaskDo());\n int powerState = getPowerState(clfDoFilter.getFilterEntryDo());\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"prepareRouteInfo powerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n entries.add(new RouteEntry(aid, powerState, 2, clfDoFilter.getFilterEntryDo().getVzwArDo().isVzwAllowed()));\n }\n }\n\n private byte[] getAid(AidRangeDo aid_range, AidMaskDo aid_mask) {\n byte[] barr_aid_mask = aid_mask.getAidMask();\n int count = 0;\n while (count < barr_aid_mask.length && barr_aid_mask[count] == (byte) -1) {\n count++;\n }\n if (count == 0) {\n return null;\n }\n byte[] aid = new byte[count];\n System.arraycopy(aid_range.getAidRange(), 0, aid, 0, count);\n return aid;\n }\n\n private int getPowerState(FilterEntryDo filter_entry_do) {\n int powerState = 0;\n int routeInfo = filter_entry_do.getRoutingModeDo().getRoutingInfo();\n FilterConditionTagDo conditionTagDo = filter_entry_do.getFilterConditionTagDo();\n if (conditionTagDo != null && conditionTagDo.getFilterConditionTag() == FilterConditionTagDo.SCREEN_OFF_TAG) {\n powerState = 1;\n } else if (routeInfo != 0) {\n powerState = ((((routeInfo & 1) << 2) | (routeInfo & 2)) | ((routeInfo & 4) >> 2)) | 128;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"getPowerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilte", "post_mask_code": "\n return powerState;\n }\n\n private static INfcVzw getServiceInterface() {\n if (sVzwNfcAdapter != null) {\n return sVzwNfcAdapter;\n }\n IBinder b = ServiceManager.getService(\"nfc\");\n if (b == null) {\n return null;\n }\n try {\n IBinder b2 = Stub.asInterface(b).getNfcAdapterVendorInterface(\"nxp\");\n if (b2 == null) {\n return null;\n }\n sVzwNfcAdapter = INxpNfcAdapter.Stub.asInterface(b2).getNfcVzwInterface();\n return sVzwNfcAdapter;\n } catch (Exception e) {\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_1499", "language": "Java", "task_type": "if_statement", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/vzw/nfc/AidFilter.java", "mask_start_position": 4002, "mask_end_position": 4135, "canonical_solution": "if (routeInfo != 0) {\n powerState = ((((routeInfo & 1) << 2) | (routeInfo & 2)) | ((routeInfo & 4) >> 2)) | 128;\n }", "pre_mask_code": "package com.vzw.nfc;\n\nimport android.nfc.INfcAdapter.Stub;\nimport android.os.IBinder;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.util.Log;\nimport com.nxp.nfc.INfcVzw;\nimport com.nxp.nfc.INxpNfcAdapter;\nimport com.vzw.nfc.dos.AidMaskDo;\nimport com.vzw.nfc.dos.AidRangeDo;\nimport com.vzw.nfc.dos.ClfFilterDo;\nimport com.vzw.nfc.dos.ClfFilterDoList;\nimport com.vzw.nfc.dos.DoParserException;\nimport com.vzw.nfc.dos.FilterConditionTagDo;\nimport com.vzw.nfc.dos.FilterEntryDo;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n\npublic final class AidFilter {\n\n private static INfcVzw sVzwNfcAdapter;\n\n public final int DEFAULT_ROUTE_LOCATION = 2;\n\n public boolean setFilterList(byte[] filterList) {\n boolean status = true;\n ClfFilterDoList allClfFilterDo = new ClfFilterDoList(filterList, 0, filterList.length);\n try {\n allClfFilterDo.translate();\n ArrayList entries = new ArrayList();\n prepareRouteInfo(allClfFilterDo, entries);\n if (getServiceInterface() != null) {\n try {\n status = getServiceInterface().setVzwAidList((RouteEntry[]) entries.toArray(new RouteEntry[entries.size()]));\n } catch (RemoteException e) {\n status = false;\n }\n }\n return status;\n } catch (DoParserException e2) {\n e2.printStackTrace();\n return false;\n }\n }\n\n public boolean enableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(true);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n public boolean disableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(false);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n private void prepareRouteInfo(ClfFilterDoList allClfFilterDo, ArrayList entries) {\n Iterator it = allClfFilterDo.getClfFilterDos().iterator();\n while (it.hasNext()) {\n ClfFilterDo clfDoFilter = (ClfFilterDo) it.next();\n byte[] aid = getAid(clfDoFilter.getFilterEntryDo().getAidRangeDo(), clfDoFilter.getFilterEntryDo().getAidMaskDo());\n int powerState = getPowerState(clfDoFilter.getFilterEntryDo());\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"prepareRouteInfo powerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n entries.add(new RouteEntry(aid, powerState, 2, clfDoFilter.getFilterEntryDo().getVzwArDo().isVzwAllowed()));\n }\n }\n\n private byte[] getAid(AidRangeDo aid_range, AidMaskDo aid_mask) {\n byte[] barr_aid_mask = aid_mask.getAidMask();\n int count = 0;\n while (count < barr_aid_mask.length && barr_aid_mask[count] == (byte) -1) {\n count++;\n }\n if (count == 0) {\n return null;\n }\n byte[] aid = new byte[count];\n System.arraycopy(aid_range.getAidRange(), 0, aid, 0, count);\n return aid;\n }\n\n private int getPowerState(FilterEntryDo filter_entry_do) {\n int powerState = 0;\n int routeInfo = filter_entry_do.getRoutingModeDo().getRoutingInfo();\n FilterConditionTagDo conditionTagDo = filter_entry_do.getFilterConditionTagDo();\n if (conditionTagDo != null && conditionTagDo.getFilterConditionTag() == FilterConditionTagDo.SCREEN_OFF_TAG) {\n powerState = 1;\n } else ", "post_mask_code": "\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"getPowerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n return powerState;\n }\n\n private static INfcVzw getServiceInterface() {\n if (sVzwNfcAdapter != null) {\n return sVzwNfcAdapter;\n }\n IBinder b = ServiceManager.getService(\"nfc\");\n if (b == null) {\n return null;\n }\n try {\n IBinder b2 = Stub.asInterface(b).getNfcAdapterVendorInterface(\"nxp\");\n if (b2 == null) {\n return null;\n }\n sVzwNfcAdapter = INxpNfcAdapter.Stub.asInterface(b2).getNfcVzwInterface();\n return sVzwNfcAdapter;\n } catch (Exception e) {\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_1500", "language": "Java", "task_type": "while_statement", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/vzw/nfc/AidFilter.java", "mask_start_position": 3281, "mask_end_position": 3387, "canonical_solution": "while (count < barr_aid_mask.length && barr_aid_mask[count] == (byte) -1) {\n count++;\n }", "pre_mask_code": "package com.vzw.nfc;\n\nimport android.nfc.INfcAdapter.Stub;\nimport android.os.IBinder;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.util.Log;\nimport com.nxp.nfc.INfcVzw;\nimport com.nxp.nfc.INxpNfcAdapter;\nimport com.vzw.nfc.dos.AidMaskDo;\nimport com.vzw.nfc.dos.AidRangeDo;\nimport com.vzw.nfc.dos.ClfFilterDo;\nimport com.vzw.nfc.dos.ClfFilterDoList;\nimport com.vzw.nfc.dos.DoParserException;\nimport com.vzw.nfc.dos.FilterConditionTagDo;\nimport com.vzw.nfc.dos.FilterEntryDo;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n\npublic final class AidFilter {\n\n private static INfcVzw sVzwNfcAdapter;\n\n public final int DEFAULT_ROUTE_LOCATION = 2;\n\n public boolean setFilterList(byte[] filterList) {\n boolean status = true;\n ClfFilterDoList allClfFilterDo = new ClfFilterDoList(filterList, 0, filterList.length);\n try {\n allClfFilterDo.translate();\n ArrayList entries = new ArrayList();\n prepareRouteInfo(allClfFilterDo, entries);\n if (getServiceInterface() != null) {\n try {\n status = getServiceInterface().setVzwAidList((RouteEntry[]) entries.toArray(new RouteEntry[entries.size()]));\n } catch (RemoteException e) {\n status = false;\n }\n }\n return status;\n } catch (DoParserException e2) {\n e2.printStackTrace();\n return false;\n }\n }\n\n public boolean enableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(true);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n public boolean disableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(false);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n private void prepareRouteInfo(ClfFilterDoList allClfFilterDo, ArrayList entries) {\n Iterator it = allClfFilterDo.getClfFilterDos().iterator();\n while (it.hasNext()) {\n ClfFilterDo clfDoFilter = (ClfFilterDo) it.next();\n byte[] aid = getAid(clfDoFilter.getFilterEntryDo().getAidRangeDo(), clfDoFilter.getFilterEntryDo().getAidMaskDo());\n int powerState = getPowerState(clfDoFilter.getFilterEntryDo());\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"prepareRouteInfo powerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n entries.add(new RouteEntry(aid, powerState, 2, clfDoFilter.getFilterEntryDo().getVzwArDo().isVzwAllowed()));\n }\n }\n\n private byte[] getAid(AidRangeDo aid_range, AidMaskDo aid_mask) {\n byte[] barr_aid_mask = aid_mask.getAidMask();\n int count = 0;\n ", "post_mask_code": "\n if (count == 0) {\n return null;\n }\n byte[] aid = new byte[count];\n System.arraycopy(aid_range.getAidRange(), 0, aid, 0, count);\n return aid;\n }\n\n private int getPowerState(FilterEntryDo filter_entry_do) {\n int powerState = 0;\n int routeInfo = filter_entry_do.getRoutingModeDo().getRoutingInfo();\n FilterConditionTagDo conditionTagDo = filter_entry_do.getFilterConditionTagDo();\n if (conditionTagDo != null && conditionTagDo.getFilterConditionTag() == FilterConditionTagDo.SCREEN_OFF_TAG) {\n powerState = 1;\n } else if (routeInfo != 0) {\n powerState = ((((routeInfo & 1) << 2) | (routeInfo & 2)) | ((routeInfo & 4) >> 2)) | 128;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"getPowerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n return powerState;\n }\n\n private static INfcVzw getServiceInterface() {\n if (sVzwNfcAdapter != null) {\n return sVzwNfcAdapter;\n }\n IBinder b = ServiceManager.getService(\"nfc\");\n if (b == null) {\n return null;\n }\n try {\n IBinder b2 = Stub.asInterface(b).getNfcAdapterVendorInterface(\"nxp\");\n if (b2 == null) {\n return null;\n }\n sVzwNfcAdapter = INxpNfcAdapter.Stub.asInterface(b2).getNfcVzwInterface();\n return sVzwNfcAdapter;\n } catch (Exception e) {\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_1501", "language": "Java", "task_type": "try_statement", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/vzw/nfc/AidFilter.java", "mask_start_position": 2116, "mask_end_position": 2284, "canonical_solution": "try {\n getServiceInterface().setScreenOffCondition(false);\n return true;\n } catch (RemoteException e) {\n return false;\n }", "pre_mask_code": "package com.vzw.nfc;\n\nimport android.nfc.INfcAdapter.Stub;\nimport android.os.IBinder;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.util.Log;\nimport com.nxp.nfc.INfcVzw;\nimport com.nxp.nfc.INxpNfcAdapter;\nimport com.vzw.nfc.dos.AidMaskDo;\nimport com.vzw.nfc.dos.AidRangeDo;\nimport com.vzw.nfc.dos.ClfFilterDo;\nimport com.vzw.nfc.dos.ClfFilterDoList;\nimport com.vzw.nfc.dos.DoParserException;\nimport com.vzw.nfc.dos.FilterConditionTagDo;\nimport com.vzw.nfc.dos.FilterEntryDo;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n\npublic final class AidFilter {\n\n private static INfcVzw sVzwNfcAdapter;\n\n public final int DEFAULT_ROUTE_LOCATION = 2;\n\n public boolean setFilterList(byte[] filterList) {\n boolean status = true;\n ClfFilterDoList allClfFilterDo = new ClfFilterDoList(filterList, 0, filterList.length);\n try {\n allClfFilterDo.translate();\n ArrayList entries = new ArrayList();\n prepareRouteInfo(allClfFilterDo, entries);\n if (getServiceInterface() != null) {\n try {\n status = getServiceInterface().setVzwAidList((RouteEntry[]) entries.toArray(new RouteEntry[entries.size()]));\n } catch (RemoteException e) {\n status = false;\n }\n }\n return status;\n } catch (DoParserException e2) {\n e2.printStackTrace();\n return false;\n }\n }\n\n public boolean enableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n try {\n getServiceInterface().setScreenOffCondition(true);\n return true;\n } catch (RemoteException e) {\n return false;\n }\n }\n\n public boolean disableFilterCondition(byte filterConditionTag) {\n if (getServiceInterface() == null || FilterConditionTagDo.SCREEN_OFF_TAG != filterConditionTag) {\n return true;\n }\n ", "post_mask_code": "\n }\n\n private void prepareRouteInfo(ClfFilterDoList allClfFilterDo, ArrayList entries) {\n Iterator it = allClfFilterDo.getClfFilterDos().iterator();\n while (it.hasNext()) {\n ClfFilterDo clfDoFilter = (ClfFilterDo) it.next();\n byte[] aid = getAid(clfDoFilter.getFilterEntryDo().getAidRangeDo(), clfDoFilter.getFilterEntryDo().getAidMaskDo());\n int powerState = getPowerState(clfDoFilter.getFilterEntryDo());\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"prepareRouteInfo powerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n entries.add(new RouteEntry(aid, powerState, 2, clfDoFilter.getFilterEntryDo().getVzwArDo().isVzwAllowed()));\n }\n }\n\n private byte[] getAid(AidRangeDo aid_range, AidMaskDo aid_mask) {\n byte[] barr_aid_mask = aid_mask.getAidMask();\n int count = 0;\n while (count < barr_aid_mask.length && barr_aid_mask[count] == (byte) -1) {\n count++;\n }\n if (count == 0) {\n return null;\n }\n byte[] aid = new byte[count];\n System.arraycopy(aid_range.getAidRange(), 0, aid, 0, count);\n return aid;\n }\n\n private int getPowerState(FilterEntryDo filter_entry_do) {\n int powerState = 0;\n int routeInfo = filter_entry_do.getRoutingModeDo().getRoutingInfo();\n FilterConditionTagDo conditionTagDo = filter_entry_do.getFilterConditionTagDo();\n if (conditionTagDo != null && conditionTagDo.getFilterConditionTag() == FilterConditionTagDo.SCREEN_OFF_TAG) {\n powerState = 1;\n } else if (routeInfo != 0) {\n powerState = ((((routeInfo & 1) << 2) | (routeInfo & 2)) | ((routeInfo & 4) >> 2)) | 128;\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"getPowerState\");\n stringBuilder.append(powerState);\n Log.d(\"AidFilter\", stringBuilder.toString());\n return powerState;\n }\n\n private static INfcVzw getServiceInterface() {\n if (sVzwNfcAdapter != null) {\n return sVzwNfcAdapter;\n }\n IBinder b = ServiceManager.getService(\"nfc\");\n if (b == null) {\n return null;\n }\n try {\n IBinder b2 = Stub.asInterface(b).getNfcAdapterVendorInterface(\"nxp\");\n if (b2 == null) {\n return null;\n }\n sVzwNfcAdapter = INxpNfcAdapter.Stub.asInterface(b2).getNfcVzwInterface();\n return sVzwNfcAdapter;\n } catch (Exception e) {\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_1502", "language": "Java", "task_type": "method_signature", "source_file": "java/github/radioegor146/native-obfuscator/test_data/tests/lang/Character/TestIsJavaIdentifierMethods.java/TestIsJavaIdentifierMethods.java", "mask_start_position": 775, "mask_end_position": 814, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "/**\n * @test\n * @summary Test behavior of isJavaIdentifierXX, testIsJavaLetter, and\n * testIsJavaLetterOrDigit methods for all code points.\n * @bug 8218915\n */\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class TestIsJavaIdentifierMethods {\n\n // List of new code points are not present in Unicode 6.2.\n private static final List UNASSIGNED_CODEPOINTS_IN_6_2 = new ArrayList() {\n\n {\n // NORDIC MARK SIGN\n add(0x20BB);\n // MANAT SIGN\n add(0x20BC);\n // RUBLE SIGN\n add(0x20BD);\n // LARI SIGN\n add(0x20BE);\n // BITCOIN SIGN\n add(0x20BF);\n // SQUARE ERA NAME NEWERA\n add(0x32FF);\n }\n };\n\n ", "post_mask_code": "{\n testIsJavaIdentifierPart_int();\n testIsJavaIdentifierPart_char();\n testIsJavaIdentifierStart_int();\n testIsJavaIdentifierStart_char();\n testIsJavaLetter();\n testIsJavaLetterOrDigit();\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(int\n * codePoint), A character may be part of a Java identifier if any of the\n * following are true:\n *

    \n *
  • it is a letter
  • \n *
  • it is a currency symbol (such as '$')
  • \n *
  • it is a connecting punctuation character (such as '_')\n *
  • \n *
  • it is a digit
  • \n *
  • it is a numeric letter (such as a Roman numeral character)
  • \n *
  • it is a combining mark
  • \n *
  • it is a non-spacing mark
  • \n *
  • isIdentifierIgnorable returns true for the\n * character
  • \n *
\n * All code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_int() {\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(cp) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(cp);\n }\n if (Character.isJavaIdentifierPart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(char\n * ch), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter;\n *
  • it is a currency symbol (such as \"$\");\n *
  • it is a connecting punctuation character (such as \"_\");\n *
  • it is a digit;\n *
  • it is a numeric letter (such as a Roman numeral character);\n *
  • it is a combining mark;\n *
  • it is a non-spacing mark;\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaIdentifierPart((char) i) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(int\n * codePoint), A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_int() {\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(char),\n * A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; i++) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetter(char ch), A\n * character may start a Java identifier if and only if one of the\n * following is true:\n *
    \n *
  • isLetter(ch) returns true\n *
  • getType(ch) returns LETTER_NUMBER\n *
  • ch is a currency symbol (such as \"$\")\n *
  • ch is a connecting punctuation character (such as \"_\").\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetter() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetter(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaLetter(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetter(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetterOrDigit(char\n * ch), A character may be part of a Java identifier if and only if any\n * of the following are true:\n *
    \n *
  • it is a letter\n *
  • it is a currency symbol (such as '$')\n *
  • it is a connecting punctuation character (such as '_')\n *
  • it is a digit\n *
  • it is a numeric letter (such as a Roman numeral character)\n *
  • it is a combining mark\n *
  • it is a non-spacing mark\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetterOrDigit() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetterOrDigit(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaLetterOrDigit(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetterOrDigit(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n}\n"} {"task_id": "Java_1503", "language": "Java", "task_type": "method_body", "source_file": "java/github/radioegor146/native-obfuscator/test_data/tests/lang/Character/TestIsJavaIdentifierMethods.java/TestIsJavaIdentifierMethods.java", "mask_start_position": 814, "mask_end_position": 1048, "canonical_solution": "{\n testIsJavaIdentifierPart_int();\n testIsJavaIdentifierPart_char();\n testIsJavaIdentifierStart_int();\n testIsJavaIdentifierStart_char();\n testIsJavaLetter();\n testIsJavaLetterOrDigit();\n }", "pre_mask_code": "/**\n * @test\n * @summary Test behavior of isJavaIdentifierXX, testIsJavaLetter, and\n * testIsJavaLetterOrDigit methods for all code points.\n * @bug 8218915\n */\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class TestIsJavaIdentifierMethods {\n\n // List of new code points are not present in Unicode 6.2.\n private static final List UNASSIGNED_CODEPOINTS_IN_6_2 = new ArrayList() {\n\n {\n // NORDIC MARK SIGN\n add(0x20BB);\n // MANAT SIGN\n add(0x20BC);\n // RUBLE SIGN\n add(0x20BD);\n // LARI SIGN\n add(0x20BE);\n // BITCOIN SIGN\n add(0x20BF);\n // SQUARE ERA NAME NEWERA\n add(0x32FF);\n }\n };\n\n public static void main(String[] args) ", "post_mask_code": "\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(int\n * codePoint), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter
  • \n *
  • it is a currency symbol (such as '$')
  • \n *
  • it is a connecting punctuation character (such as '_')\n *
  • \n *
  • it is a digit
  • \n *
  • it is a numeric letter (such as a Roman numeral character)
  • \n *
  • it is a combining mark
  • \n *
  • it is a non-spacing mark
  • \n *
  • isIdentifierIgnorable returns true for the\n * character
  • \n *
\n * All code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_int() {\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(cp) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(cp);\n }\n if (Character.isJavaIdentifierPart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(char\n * ch), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter;\n *
  • it is a currency symbol (such as \"$\");\n *
  • it is a connecting punctuation character (such as \"_\");\n *
  • it is a digit;\n *
  • it is a numeric letter (such as a Roman numeral character);\n *
  • it is a combining mark;\n *
  • it is a non-spacing mark;\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaIdentifierPart((char) i) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(int\n * codePoint), A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_int() {\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(char),\n * A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; i++) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetter(char ch), A\n * character may start a Java identifier if and only if one of the\n * following is true:\n *
    \n *
  • isLetter(ch) returns true\n *
  • getType(ch) returns LETTER_NUMBER\n *
  • ch is a currency symbol (such as \"$\")\n *
  • ch is a connecting punctuation character (such as \"_\").\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetter() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetter(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaLetter(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetter(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetterOrDigit(char\n * ch), A character may be part of a Java identifier if and only if any\n * of the following are true:\n *
    \n *
  • it is a letter\n *
  • it is a currency symbol (such as '$')\n *
  • it is a connecting punctuation character (such as '_')\n *
  • it is a digit\n *
  • it is a numeric letter (such as a Roman numeral character)\n *
  • it is a combining mark\n *
  • it is a non-spacing mark\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetterOrDigit() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetterOrDigit(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaLetterOrDigit(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetterOrDigit(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n}\n"} {"task_id": "Java_1504", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/radioegor146/native-obfuscator/test_data/tests/lang/Character/TestIsJavaIdentifierMethods.java/TestIsJavaIdentifierMethods.java", "mask_start_position": 1863, "mask_end_position": 1863, "canonical_solution": "", "pre_mask_code": "/**\n * @test\n * @summary Test behavior of isJavaIdentifierXX, testIsJavaLetter, and\n * testIsJavaLetterOrDigit methods for all code points.\n * @bug 8218915\n */\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class TestIsJavaIdentifierMethods {\n\n // List of new code points are not present in Unicode 6.2.\n private static final List UNASSIGNED_CODEPOINTS_IN_6_2 = new ArrayList() {\n\n {\n // NORDIC MARK SIGN\n add(0x20BB);\n // MANAT SIGN\n add(0x20BC);\n // RUBLE SIGN\n add(0x20BD);\n // LARI SIGN\n add(0x20BE);\n // BITCOIN SIGN\n add(0x20BF);\n // SQUARE ERA NAME NEWERA\n add(0x32FF);\n }\n };\n\n public static void main(String[] args) {\n testIsJavaIdentifierPart_int();\n testIsJavaIdentifierPart_char();\n testIsJavaIdentifierStart_int();\n testIsJavaIdentifierStart_char();\n testIsJavaLetter();\n testIsJavaLetterOrDigit();\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(int\n * codePoint), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter
  • \n *
  • it is a currency symbol (such as '$')
  • \n *
  • it is a connecting punctuation character (such as '_')\n *
  • \n *
  • it is a digit
  • \n *
  • it is a numeric letter (such as a Roman numeral character)
  • \n *
  • it is a combining mark
  • \n *
  • it is a non-spacing mark
  • \n *
  • isIdentifierIgnorable returns true for the\n * character
  • \n *
\n * All code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_int() {", "post_mask_code": "\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(cp) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(cp);\n }\n if (Character.isJavaIdentifierPart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(char\n * ch), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter;\n *
  • it is a currency symbol (such as \"$\");\n *
  • it is a connecting punctuation character (such as \"_\");\n *
  • it is a digit;\n *
  • it is a numeric letter (such as a Roman numeral character);\n *
  • it is a combining mark;\n *
  • it is a non-spacing mark;\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaIdentifierPart((char) i) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(int\n * codePoint), A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_int() {\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(char),\n * A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; i++) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetter(char ch), A\n * character may start a Java identifier if and only if one of the\n * following is true:\n *
    \n *
  • isLetter(ch) returns true\n *
  • getType(ch) returns LETTER_NUMBER\n *
  • ch is a currency symbol (such as \"$\")\n *
  • ch is a connecting punctuation character (such as \"_\").\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetter() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetter(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaLetter(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetter(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetterOrDigit(char\n * ch), A character may be part of a Java identifier if and only if any\n * of the following are true:\n *
    \n *
  • it is a letter\n *
  • it is a currency symbol (such as '$')\n *
  • it is a connecting punctuation character (such as '_')\n *
  • it is a digit\n *
  • it is a numeric letter (such as a Roman numeral character)\n *
  • it is a combining mark\n *
  • it is a non-spacing mark\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetterOrDigit() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetterOrDigit(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaLetterOrDigit(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetterOrDigit(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n}\n"} {"task_id": "Java_1505", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/radioegor146/native-obfuscator/test_data/tests/lang/Character/TestIsJavaIdentifierMethods.java/TestIsJavaIdentifierMethods.java", "mask_start_position": 1872, "mask_end_position": 2983, "canonical_solution": "for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(cp) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(cp);\n }\n if (Character.isJavaIdentifierPart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }", "pre_mask_code": "/**\n * @test\n * @summary Test behavior of isJavaIdentifierXX, testIsJavaLetter, and\n * testIsJavaLetterOrDigit methods for all code points.\n * @bug 8218915\n */\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class TestIsJavaIdentifierMethods {\n\n // List of new code points are not present in Unicode 6.2.\n private static final List UNASSIGNED_CODEPOINTS_IN_6_2 = new ArrayList() {\n\n {\n // NORDIC MARK SIGN\n add(0x20BB);\n // MANAT SIGN\n add(0x20BC);\n // RUBLE SIGN\n add(0x20BD);\n // LARI SIGN\n add(0x20BE);\n // BITCOIN SIGN\n add(0x20BF);\n // SQUARE ERA NAME NEWERA\n add(0x32FF);\n }\n };\n\n public static void main(String[] args) {\n testIsJavaIdentifierPart_int();\n testIsJavaIdentifierPart_char();\n testIsJavaIdentifierStart_int();\n testIsJavaIdentifierStart_char();\n testIsJavaLetter();\n testIsJavaLetterOrDigit();\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(int\n * codePoint), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter
  • \n *
  • it is a currency symbol (such as '$')
  • \n *
  • it is a connecting punctuation character (such as '_')\n *
  • \n *
  • it is a digit
  • \n *
  • it is a numeric letter (such as a Roman numeral character)
  • \n *
  • it is a combining mark
  • \n *
  • it is a non-spacing mark
  • \n *
  • isIdentifierIgnorable returns true for the\n * character
  • \n *
\n * All code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_int() {\n ", "post_mask_code": "\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(char\n * ch), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter;\n *
  • it is a currency symbol (such as \"$\");\n *
  • it is a connecting punctuation character (such as \"_\");\n *
  • it is a digit;\n *
  • it is a numeric letter (such as a Roman numeral character);\n *
  • it is a combining mark;\n *
  • it is a non-spacing mark;\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaIdentifierPart((char) i) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(int\n * codePoint), A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_int() {\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(char),\n * A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; i++) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetter(char ch), A\n * character may start a Java identifier if and only if one of the\n * following is true:\n *
    \n *
  • isLetter(ch) returns true\n *
  • getType(ch) returns LETTER_NUMBER\n *
  • ch is a currency symbol (such as \"$\")\n *
  • ch is a connecting punctuation character (such as \"_\").\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetter() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetter(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaLetter(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetter(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetterOrDigit(char\n * ch), A character may be part of a Java identifier if and only if any\n * of the following are true:\n *
    \n *
  • it is a letter\n *
  • it is a currency symbol (such as '$')\n *
  • it is a connecting punctuation character (such as '_')\n *
  • it is a digit\n *
  • it is a numeric letter (such as a Roman numeral character)\n *
  • it is a combining mark\n *
  • it is a non-spacing mark\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetterOrDigit() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetterOrDigit(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaLetterOrDigit(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetterOrDigit(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n}\n"} {"task_id": "Java_1506", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/radioegor146/native-obfuscator/test_data/tests/lang/Character/TestIsJavaIdentifierMethods.java/TestIsJavaIdentifierMethods.java", "mask_start_position": 2988, "mask_end_position": 2989, "canonical_solution": "}", "pre_mask_code": "/**\n * @test\n * @summary Test behavior of isJavaIdentifierXX, testIsJavaLetter, and\n * testIsJavaLetterOrDigit methods for all code points.\n * @bug 8218915\n */\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class TestIsJavaIdentifierMethods {\n\n // List of new code points are not present in Unicode 6.2.\n private static final List UNASSIGNED_CODEPOINTS_IN_6_2 = new ArrayList() {\n\n {\n // NORDIC MARK SIGN\n add(0x20BB);\n // MANAT SIGN\n add(0x20BC);\n // RUBLE SIGN\n add(0x20BD);\n // LARI SIGN\n add(0x20BE);\n // BITCOIN SIGN\n add(0x20BF);\n // SQUARE ERA NAME NEWERA\n add(0x32FF);\n }\n };\n\n public static void main(String[] args) {\n testIsJavaIdentifierPart_int();\n testIsJavaIdentifierPart_char();\n testIsJavaIdentifierStart_int();\n testIsJavaIdentifierStart_char();\n testIsJavaLetter();\n testIsJavaLetterOrDigit();\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(int\n * codePoint), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter
  • \n *
  • it is a currency symbol (such as '$')
  • \n *
  • it is a connecting punctuation character (such as '_')\n *
  • \n *
  • it is a digit
  • \n *
  • it is a numeric letter (such as a Roman numeral character)
  • \n *
  • it is a combining mark
  • \n *
  • it is a non-spacing mark
  • \n *
  • isIdentifierIgnorable returns true for the\n * character
  • \n *
\n * All code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_int() {\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(cp) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(cp);\n }\n if (Character.isJavaIdentifierPart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n ", "post_mask_code": "\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(char\n * ch), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter;\n *
  • it is a currency symbol (such as \"$\");\n *
  • it is a connecting punctuation character (such as \"_\");\n *
  • it is a digit;\n *
  • it is a numeric letter (such as a Roman numeral character);\n *
  • it is a combining mark;\n *
  • it is a non-spacing mark;\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaIdentifierPart((char) i) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(int\n * codePoint), A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_int() {\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(char),\n * A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; i++) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetter(char ch), A\n * character may start a Java identifier if and only if one of the\n * following is true:\n *
    \n *
  • isLetter(ch) returns true\n *
  • getType(ch) returns LETTER_NUMBER\n *
  • ch is a currency symbol (such as \"$\")\n *
  • ch is a connecting punctuation character (such as \"_\").\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetter() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetter(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaLetter(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetter(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetterOrDigit(char\n * ch), A character may be part of a Java identifier if and only if any\n * of the following are true:\n *
    \n *
  • it is a letter\n *
  • it is a currency symbol (such as '$')\n *
  • it is a connecting punctuation character (such as '_')\n *
  • it is a digit\n *
  • it is a numeric letter (such as a Roman numeral character)\n *
  • it is a combining mark\n *
  • it is a non-spacing mark\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetterOrDigit() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetterOrDigit(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaLetterOrDigit(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetterOrDigit(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n}\n"} {"task_id": "Java_1507", "language": "Java", "task_type": "single_line", "source_file": "java/github/radioegor146/native-obfuscator/test_data/tests/lang/Character/TestIsJavaIdentifierMethods.java/TestIsJavaIdentifierMethods.java", "mask_start_position": 830, "mask_end_position": 855, "canonical_solution": "JavaIdentifierPart_int();", "pre_mask_code": "/**\n * @test\n * @summary Test behavior of isJavaIdentifierXX, testIsJavaLetter, and\n * testIsJavaLetterOrDigit methods for all code points.\n * @bug 8218915\n */\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class TestIsJavaIdentifierMethods {\n\n // List of new code points are not present in Unicode 6.2.\n private static final List UNASSIGNED_CODEPOINTS_IN_6_2 = new ArrayList() {\n\n {\n // NORDIC MARK SIGN\n add(0x20BB);\n // MANAT SIGN\n add(0x20BC);\n // RUBLE SIGN\n add(0x20BD);\n // LARI SIGN\n add(0x20BE);\n // BITCOIN SIGN\n add(0x20BF);\n // SQUARE ERA NAME NEWERA\n add(0x32FF);\n }\n };\n\n public static void main(String[] args) {\n testIs", "post_mask_code": "\n testIsJavaIdentifierPart_char();\n testIsJavaIdentifierStart_int();\n testIsJavaIdentifierStart_char();\n testIsJavaLetter();\n testIsJavaLetterOrDigit();\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(int\n * codePoint), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter
  • \n *
  • it is a currency symbol (such as '$')
  • \n *
  • it is a connecting punctuation character (such as '_')\n *
  • \n *
  • it is a digit
  • \n *
  • it is a numeric letter (such as a Roman numeral character)
  • \n *
  • it is a combining mark
  • \n *
  • it is a non-spacing mark
  • \n *
  • isIdentifierIgnorable returns true for the\n * character
  • \n *
\n * All code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_int() {\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(cp) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(cp);\n }\n if (Character.isJavaIdentifierPart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(char\n * ch), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter;\n *
  • it is a currency symbol (such as \"$\");\n *
  • it is a connecting punctuation character (such as \"_\");\n *
  • it is a digit;\n *
  • it is a numeric letter (such as a Roman numeral character);\n *
  • it is a combining mark;\n *
  • it is a non-spacing mark;\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaIdentifierPart((char) i) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(int\n * codePoint), A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_int() {\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(char),\n * A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; i++) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetter(char ch), A\n * character may start a Java identifier if and only if one of the\n * following is true:\n *
    \n *
  • isLetter(ch) returns true\n *
  • getType(ch) returns LETTER_NUMBER\n *
  • ch is a currency symbol (such as \"$\")\n *
  • ch is a connecting punctuation character (such as \"_\").\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetter() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetter(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaLetter(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetter(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetterOrDigit(char\n * ch), A character may be part of a Java identifier if and only if any\n * of the following are true:\n *
    \n *
  • it is a letter\n *
  • it is a currency symbol (such as '$')\n *
  • it is a connecting punctuation character (such as '_')\n *
  • it is a digit\n *
  • it is a numeric letter (such as a Roman numeral character)\n *
  • it is a combining mark\n *
  • it is a non-spacing mark\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetterOrDigit() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetterOrDigit(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaLetterOrDigit(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetterOrDigit(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n}\n"} {"task_id": "Java_1508", "language": "Java", "task_type": "if_statement", "source_file": "java/github/radioegor146/native-obfuscator/test_data/tests/lang/Character/TestIsJavaIdentifierMethods.java/TestIsJavaIdentifierMethods.java", "mask_start_position": 11133, "mask_end_position": 11327, "canonical_solution": "if (Character.isJavaLetterOrDigit(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetterOrDigit(ch) failed for codepoint \" + Integer.toHexString(i));\n }", "pre_mask_code": "/**\n * @test\n * @summary Test behavior of isJavaIdentifierXX, testIsJavaLetter, and\n * testIsJavaLetterOrDigit methods for all code points.\n * @bug 8218915\n */\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class TestIsJavaIdentifierMethods {\n\n // List of new code points are not present in Unicode 6.2.\n private static final List UNASSIGNED_CODEPOINTS_IN_6_2 = new ArrayList() {\n\n {\n // NORDIC MARK SIGN\n add(0x20BB);\n // MANAT SIGN\n add(0x20BC);\n // RUBLE SIGN\n add(0x20BD);\n // LARI SIGN\n add(0x20BE);\n // BITCOIN SIGN\n add(0x20BF);\n // SQUARE ERA NAME NEWERA\n add(0x32FF);\n }\n };\n\n public static void main(String[] args) {\n testIsJavaIdentifierPart_int();\n testIsJavaIdentifierPart_char();\n testIsJavaIdentifierStart_int();\n testIsJavaIdentifierStart_char();\n testIsJavaLetter();\n testIsJavaLetterOrDigit();\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(int\n * codePoint), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter
  • \n *
  • it is a currency symbol (such as '$')
  • \n *
  • it is a connecting punctuation character (such as '_')\n *
  • \n *
  • it is a digit
  • \n *
  • it is a numeric letter (such as a Roman numeral character)
  • \n *
  • it is a combining mark
  • \n *
  • it is a non-spacing mark
  • \n *
  • isIdentifierIgnorable returns true for the\n * character
  • \n *
\n * All code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_int() {\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(cp) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(cp);\n }\n if (Character.isJavaIdentifierPart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierPart(char\n * ch), A character may be part of a Java identifier if any of the\n * following are true:\n *
    \n *
  • it is a letter;\n *
  • it is a currency symbol (such as \"$\");\n *
  • it is a connecting punctuation character (such as \"_\");\n *
  • it is a digit;\n *
  • it is a numeric letter (such as a Roman numeral character);\n *
  • it is a combining mark;\n *
  • it is a non-spacing mark;\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierPart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierPart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n if (Character.isJavaIdentifierPart((char) i) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierPart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(int\n * codePoint), A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Code points from (0x0000..0x10FFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_int() {\n for (int cp = 0; cp <= Character.MAX_CODE_POINT; cp++) {\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(int) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(cp)) {\n byte type = (byte) Character.getType(cp);\n expected = Character.isLetter(cp) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(cp) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(int) failed for codepoint \" + Integer.toHexString(cp));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaIdentifierStart(char),\n * A character may start a Java identifier if and only if it is\n * one of the following:\n *
    \n *
  • it is a letter;
  • \n *
  • getType(ch) returns LETTER_NUMBER;
  • \n *
  • it is a currency symbol (such as \"$\");
  • \n *
  • it is a connecting punctuation character (such as \"_\");
  • \n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaIdentifierStart_char() {\n for (int i = 0; i <= Character.MAX_VALUE; i++) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaIdentifierStart(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaIdentifierStart(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaIdentifierStart(char) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetter(char ch), A\n * character may start a Java identifier if and only if one of the\n * following is true:\n *
    \n *
  • isLetter(ch) returns true\n *
  • getType(ch) returns LETTER_NUMBER\n *
  • ch is a currency symbol (such as \"$\")\n *
  • ch is a connecting punctuation character (such as \"_\").\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetter() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetter(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.LETTER_NUMBER || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION;\n }\n if (Character.isJavaLetter(ch) != expected) {\n throw new RuntimeException(\"Character.isJavaLetter(ch) failed for codepoint \" + Integer.toHexString(i));\n }\n }\n }\n\n /**\n * Assertion testing for public static boolean isJavaLetterOrDigit(char\n * ch), A character may be part of a Java identifier if and only if any\n * of the following are true:\n *
    \n *
  • it is a letter\n *
  • it is a currency symbol (such as '$')\n *
  • it is a connecting punctuation character (such as '_')\n *
  • it is a digit\n *
  • it is a numeric letter (such as a Roman numeral character)\n *
  • it is a combining mark\n *
  • it is a non-spacing mark\n *
  • isIdentifierIgnorable returns true for the character.\n *
\n * All Unicode code points in the BMP (0x0000..0xFFFF) are tested.\n */\n public static void testIsJavaLetterOrDigit() {\n for (int i = 0; i <= Character.MAX_VALUE; ++i) {\n char ch = (char) i;\n boolean expected = false;\n // Since Character.isJavaLetterOrDigit(char) strictly conforms to\n // character information from version 6.2 of the Unicode Standard,\n // check if code point is in \"UNASSIGNED_CODEPOINTS_IN_6_2\"\n // list. If the code point is found in list\n // \"UNASSIGNED_CODEPOINTS_IN_6_2\", value of variable\n if (!UNASSIGNED_CODEPOINTS_IN_6_2.contains(i)) {\n byte type = (byte) Character.getType(ch);\n expected = Character.isLetter(ch) || type == Character.CURRENCY_SYMBOL || type == Character.CONNECTOR_PUNCTUATION || Character.isDigit(ch) || type == Character.LETTER_NUMBER || type == Character.COMBINING_SPACING_MARK || type == Character.NON_SPACING_MARK || Character.isIdentifierIgnorable(ch);\n }\n ", "post_mask_code": "\n }\n }\n}\n"} {"task_id": "Java_1509", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/server/data/DecimalDataObjectFieldFlatFileLoaderColumn.java", "mask_start_position": 5091, "mask_end_position": 5153, "canonical_solution": "public static int parseMultiplierForImport(String multiplier) ", "pre_mask_code": "package org.openlowcode.server.data;\n\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.text.ParseException;\nimport java.util.Locale;\nimport java.util.logging.Logger;\nimport org.apache.poi.ss.usermodel.Cell;\nimport org.apache.poi.ss.usermodel.CellStyle;\nimport org.openlowcode.module.system.data.choice.ApplocaleChoiceDefinition;\nimport org.openlowcode.server.data.loader.FlatFileExtractor;\nimport org.openlowcode.server.data.loader.FlatFileLoader;\nimport org.openlowcode.server.data.loader.FlatFileLoaderColumn;\nimport org.openlowcode.server.data.loader.PostUpdateProcessingStore;\n\npublic class DecimalDataObjectFieldFlatFileLoaderColumn> extends FlatFileLoaderColumn {\n\n private static Logger logger = Logger.getLogger(DecimalDataObjectFieldFlatFileLoaderColumn.class.getName());\n\n private String name;\n\n private int scale;\n\n private int precision;\n\n @SuppressWarnings(\"unused\")\n private ChoiceValue locale;\n\n public BigDecimal multiplyatexport = new BigDecimal(1);\n\n public static class DecimalParser {\n\n private int scale;\n\n private int precision;\n\n private ChoiceValue locale;\n\n private DecimalFormat decimalformat;\n\n private int specialtreatment;\n\n public static int SPECIAL_TREATMENT_NONE = 0;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_1000 = 1;\n\n public static int SPECIAL_TREATMENT_DIVIDE_BY_1000 = 2;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_100 = 3;\n\n public int getSpecialTreatment() {\n return this.specialtreatment;\n }\n\n /**\n * creates a decimal parser\n *\n * @param scale digits to the right of decimal point (e.g. 533.33 has\n * precision on 2)\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale if CSV import\n */\n public DecimalParser(int scale, int precision, ChoiceValue locale, int specialtreatment) {\n this.scale = scale;\n this.precision = precision;\n this.locale = locale;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.US);\n if (this.locale != null)\n if (this.locale.getStorageCode().equals(ApplocaleChoiceDefinition.get().FR))\n ;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);\n decimalformat.setParseBigDecimal(true);\n this.specialtreatment = specialtreatment;\n }\n\n public DecimalParser(int scale, int precision, ChoiceValue locale) {\n this(scale, precision, locale, SPECIAL_TREATMENT_NONE);\n }\n\n public BigDecimal parse(String value) {\n try {\n BigDecimal decimal = null;\n if (value != null)\n if (value.length() > 0) {\n Number number = decimalformat.parse(value);\n decimal = (BigDecimal) number;\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_1000)\n decimal = decimal.multiply(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_DIVIDE_BY_1000)\n decimal = decimal.divide(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_100)\n decimal = decimal.multiply(new BigDecimal(100));\n }\n if (decimal != null)\n if (decimal.scale() > scale) {\n decimal = decimal.setScale(scale, RoundingMode.HALF_DOWN);\n }\n if (decimal != null)\n if (decimal.precision() > precision)\n throw new RuntimeException(\"bad format for big decimal, precision is longer than limit \" + precision + \" for value \" + decimal);\n return decimal;\n } catch (ParseException e) {\n throw new RuntimeException(\"data is supposed to be big decimal but received the following error when parsing '\" + value + \"'. Exception \" + e.getMessage());\n }\n }\n }\n\n private DecimalParser decimalparser;\n\n public static BigDecimal parsemultiplierForExport(String multiplier) {\n if (multiplier == null)\n return new BigDecimal(1);\n if (multiplier.length() == 0)\n return new BigDecimal(1);\n if (multiplier.trim().equals(\"M1000\"))\n return new BigDecimal(\"0.001\");\n if (multiplier.trim().equals(\"M100\"))\n return new BigDecimal(\"0.01\");\n if (multiplier.trim().equals(\"D1000\"))\n return new BigDecimal(\"1000\");\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n ", "post_mask_code": "{\n if (multiplier == null)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.length() == 0)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.trim().equals(\"M1000\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n if (multiplier.trim().equals(\"M100\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n if (multiplier.trim().equals(\"D1000\"))\n return DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public DecimalDataObjectFieldFlatFileLoaderColumn(DataObjectDefinition definition, String[] arguments, String name, int scale, int precision, ChoiceValue locale) {\n this.scale = scale;\n this.precision = precision;\n this.name = name;\n this.locale = locale;\n int modifier = DecimalParser.SPECIAL_TREATMENT_NONE;\n if (arguments != null)\n if (arguments.length == 1) {\n String multiplier = arguments[0];\n if (multiplier.trim().equals(\"M1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n multiplyatexport = new BigDecimal(\"0.001\");\n }\n if (multiplier.trim().equals(\"M100\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M100\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n multiplyatexport = new BigDecimal(\"0.01\");\n }\n if (multiplier.trim().equals(\"D1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of D1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n multiplyatexport = new BigDecimal(\"1000\");\n }\n if (modifier == DecimalParser.SPECIAL_TREATMENT_NONE)\n throw new RuntimeException(\"Decimal DataObjectFieldFlatFileLoader invalid modifier \" + multiplier);\n }\n if (arguments != null)\n if (arguments.length > 1)\n throw new RuntimeException(\"Decimal DataObjetFieldFlatFileLoader only supports 1 modifier ( M100, M1000 or D1000)\");\n decimalparser = new DecimalParser(scale, precision, locale, modifier);\n }\n\n @Override\n public boolean load(E object, Object value, PostUpdateProcessingStore postupdateprocessingstore) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = object.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + object.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) object.payload.lookupSimpleFieldOnName(name);\n BigDecimal oldbigdecimal = decimalfield.getValue();\n BigDecimal newbigdecimal = FlatFileLoader.parseDecimal(value, precision, scale, \"Flat file loader for column \" + decimalfield.getName(), decimalparser);\n if (FlatFileLoader.isTheSame(oldbigdecimal, newbigdecimal)) {\n return false;\n } else {\n decimalfield.setValue(newbigdecimal);\n return true;\n }\n }\n\n @Override\n protected boolean putContentInCell(E currentobject, Cell cell, String context) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = currentobject.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + currentobject.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) currentobject.payload.lookupSimpleFieldOnName(name);\n BigDecimal decimal = decimalfield.getValue();\n if (decimal != null) {\n decimal = decimal.multiply(this.multiplyatexport);\n cell.setCellValue(decimal.doubleValue());\n }\n if (this.decimalparser.getSpecialTreatment() == DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100) {\n logger.finest(\"special treatment for cell percentage\");\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * puts a big decimal in cell, formatting as percentage if needed\n *\n * @param cell cell\n * @param value value\n * @param multiplier multiplier in the sense of DecimalFlatFileLoader\n * @return true if formatting was done, false if formatting was not done\n */\n public static > boolean putContentInCell(Cell cell, BigDecimal value, String multiplier) {\n BigDecimal multiplierforexport = parsemultiplierForExport(multiplier);\n if (value != null)\n cell.setCellValue(value.multiply(multiplierforexport).doubleValue());\n if (multiplierforexport.equals(new BigDecimal(\"0.01\"))) {\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * gets a BigDecimal from cell\n *\n * @param value value to parse\n * @param scale number of digits right of the decimal point (e.g.\n * 533.33 is 2 digits\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale for import from text (comma or dot as decimal)\n * @param modifier String modifier in the sense of\n * DecimalDataObjectFieldFlatFileLoader\n * @param contextforerror context used in exceptions\n * @return\n */\n public static > BigDecimal getContentFromCell(Object value, int scale, int precision, ChoiceValue locale, int modifier, String contextforerror) {\n return FlatFileLoader.parseDecimal(value, precision, scale, contextforerror, new DecimalParser(scale, precision, locale, modifier));\n }\n}\n"} {"task_id": "Java_1510", "language": "Java", "task_type": "method_body", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/server/data/DecimalDataObjectFieldFlatFileLoaderColumn.java", "mask_start_position": 12174, "mask_end_position": 12322, "canonical_solution": "{\n return FlatFileLoader.parseDecimal(value, precision, scale, contextforerror, new DecimalParser(scale, precision, locale, modifier));\n }", "pre_mask_code": "package org.openlowcode.server.data;\n\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.text.ParseException;\nimport java.util.Locale;\nimport java.util.logging.Logger;\nimport org.apache.poi.ss.usermodel.Cell;\nimport org.apache.poi.ss.usermodel.CellStyle;\nimport org.openlowcode.module.system.data.choice.ApplocaleChoiceDefinition;\nimport org.openlowcode.server.data.loader.FlatFileExtractor;\nimport org.openlowcode.server.data.loader.FlatFileLoader;\nimport org.openlowcode.server.data.loader.FlatFileLoaderColumn;\nimport org.openlowcode.server.data.loader.PostUpdateProcessingStore;\n\npublic class DecimalDataObjectFieldFlatFileLoaderColumn> extends FlatFileLoaderColumn {\n\n private static Logger logger = Logger.getLogger(DecimalDataObjectFieldFlatFileLoaderColumn.class.getName());\n\n private String name;\n\n private int scale;\n\n private int precision;\n\n @SuppressWarnings(\"unused\")\n private ChoiceValue locale;\n\n public BigDecimal multiplyatexport = new BigDecimal(1);\n\n public static class DecimalParser {\n\n private int scale;\n\n private int precision;\n\n private ChoiceValue locale;\n\n private DecimalFormat decimalformat;\n\n private int specialtreatment;\n\n public static int SPECIAL_TREATMENT_NONE = 0;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_1000 = 1;\n\n public static int SPECIAL_TREATMENT_DIVIDE_BY_1000 = 2;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_100 = 3;\n\n public int getSpecialTreatment() {\n return this.specialtreatment;\n }\n\n /**\n * creates a decimal parser\n *\n * @param scale digits to the right of decimal point (e.g. 533.33 has\n * precision on 2)\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale if CSV import\n */\n public DecimalParser(int scale, int precision, ChoiceValue locale, int specialtreatment) {\n this.scale = scale;\n this.precision = precision;\n this.locale = locale;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.US);\n if (this.locale != null)\n if (this.locale.getStorageCode().equals(ApplocaleChoiceDefinition.get().FR))\n ;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);\n decimalformat.setParseBigDecimal(true);\n this.specialtreatment = specialtreatment;\n }\n\n public DecimalParser(int scale, int precision, ChoiceValue locale) {\n this(scale, precision, locale, SPECIAL_TREATMENT_NONE);\n }\n\n public BigDecimal parse(String value) {\n try {\n BigDecimal decimal = null;\n if (value != null)\n if (value.length() > 0) {\n Number number = decimalformat.parse(value);\n decimal = (BigDecimal) number;\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_1000)\n decimal = decimal.multiply(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_DIVIDE_BY_1000)\n decimal = decimal.divide(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_100)\n decimal = decimal.multiply(new BigDecimal(100));\n }\n if (decimal != null)\n if (decimal.scale() > scale) {\n decimal = decimal.setScale(scale, RoundingMode.HALF_DOWN);\n }\n if (decimal != null)\n if (decimal.precision() > precision)\n throw new RuntimeException(\"bad format for big decimal, precision is longer than limit \" + precision + \" for value \" + decimal);\n return decimal;\n } catch (ParseException e) {\n throw new RuntimeException(\"data is supposed to be big decimal but received the following error when parsing '\" + value + \"'. Exception \" + e.getMessage());\n }\n }\n }\n\n private DecimalParser decimalparser;\n\n public static BigDecimal parsemultiplierForExport(String multiplier) {\n if (multiplier == null)\n return new BigDecimal(1);\n if (multiplier.length() == 0)\n return new BigDecimal(1);\n if (multiplier.trim().equals(\"M1000\"))\n return new BigDecimal(\"0.001\");\n if (multiplier.trim().equals(\"M100\"))\n return new BigDecimal(\"0.01\");\n if (multiplier.trim().equals(\"D1000\"))\n return new BigDecimal(\"1000\");\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public static int parseMultiplierForImport(String multiplier) {\n if (multiplier == null)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.length() == 0)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.trim().equals(\"M1000\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n if (multiplier.trim().equals(\"M100\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n if (multiplier.trim().equals(\"D1000\"))\n return DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public DecimalDataObjectFieldFlatFileLoaderColumn(DataObjectDefinition definition, String[] arguments, String name, int scale, int precision, ChoiceValue locale) {\n this.scale = scale;\n this.precision = precision;\n this.name = name;\n this.locale = locale;\n int modifier = DecimalParser.SPECIAL_TREATMENT_NONE;\n if (arguments != null)\n if (arguments.length == 1) {\n String multiplier = arguments[0];\n if (multiplier.trim().equals(\"M1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n multiplyatexport = new BigDecimal(\"0.001\");\n }\n if (multiplier.trim().equals(\"M100\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M100\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n multiplyatexport = new BigDecimal(\"0.01\");\n }\n if (multiplier.trim().equals(\"D1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of D1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n multiplyatexport = new BigDecimal(\"1000\");\n }\n if (modifier == DecimalParser.SPECIAL_TREATMENT_NONE)\n throw new RuntimeException(\"Decimal DataObjectFieldFlatFileLoader invalid modifier \" + multiplier);\n }\n if (arguments != null)\n if (arguments.length > 1)\n throw new RuntimeException(\"Decimal DataObjetFieldFlatFileLoader only supports 1 modifier ( M100, M1000 or D1000)\");\n decimalparser = new DecimalParser(scale, precision, locale, modifier);\n }\n\n @Override\n public boolean load(E object, Object value, PostUpdateProcessingStore postupdateprocessingstore) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = object.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + object.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) object.payload.lookupSimpleFieldOnName(name);\n BigDecimal oldbigdecimal = decimalfield.getValue();\n BigDecimal newbigdecimal = FlatFileLoader.parseDecimal(value, precision, scale, \"Flat file loader for column \" + decimalfield.getName(), decimalparser);\n if (FlatFileLoader.isTheSame(oldbigdecimal, newbigdecimal)) {\n return false;\n } else {\n decimalfield.setValue(newbigdecimal);\n return true;\n }\n }\n\n @Override\n protected boolean putContentInCell(E currentobject, Cell cell, String context) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = currentobject.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + currentobject.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) currentobject.payload.lookupSimpleFieldOnName(name);\n BigDecimal decimal = decimalfield.getValue();\n if (decimal != null) {\n decimal = decimal.multiply(this.multiplyatexport);\n cell.setCellValue(decimal.doubleValue());\n }\n if (this.decimalparser.getSpecialTreatment() == DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100) {\n logger.finest(\"special treatment for cell percentage\");\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * puts a big decimal in cell, formatting as percentage if needed\n *\n * @param cell cell\n * @param value value\n * @param multiplier multiplier in the sense of DecimalFlatFileLoader\n * @return true if formatting was done, false if formatting was not done\n */\n public static > boolean putContentInCell(Cell cell, BigDecimal value, String multiplier) {\n BigDecimal multiplierforexport = parsemultiplierForExport(multiplier);\n if (value != null)\n cell.setCellValue(value.multiply(multiplierforexport).doubleValue());\n if (multiplierforexport.equals(new BigDecimal(\"0.01\"))) {\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * gets a BigDecimal from cell\n *\n * @param value value to parse\n * @param scale number of digits right of the decimal point (e.g.\n * 533.33 is 2 digits\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale for import from text (comma or dot as decimal)\n * @param modifier String modifier in the sense of\n * DecimalDataObjectFieldFlatFileLoader\n * @param contextforerror context used in exceptions\n * @return\n */\n public static > BigDecimal getContentFromCell(Object value, int scale, int precision, ChoiceValue locale, int modifier, String contextforerror) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1511", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/server/data/DecimalDataObjectFieldFlatFileLoaderColumn.java", "mask_start_position": 7809, "mask_end_position": 8067, "canonical_solution": "\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = object.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + object.getName());", "pre_mask_code": "package org.openlowcode.server.data;\n\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.text.ParseException;\nimport java.util.Locale;\nimport java.util.logging.Logger;\nimport org.apache.poi.ss.usermodel.Cell;\nimport org.apache.poi.ss.usermodel.CellStyle;\nimport org.openlowcode.module.system.data.choice.ApplocaleChoiceDefinition;\nimport org.openlowcode.server.data.loader.FlatFileExtractor;\nimport org.openlowcode.server.data.loader.FlatFileLoader;\nimport org.openlowcode.server.data.loader.FlatFileLoaderColumn;\nimport org.openlowcode.server.data.loader.PostUpdateProcessingStore;\n\npublic class DecimalDataObjectFieldFlatFileLoaderColumn> extends FlatFileLoaderColumn {\n\n private static Logger logger = Logger.getLogger(DecimalDataObjectFieldFlatFileLoaderColumn.class.getName());\n\n private String name;\n\n private int scale;\n\n private int precision;\n\n @SuppressWarnings(\"unused\")\n private ChoiceValue locale;\n\n public BigDecimal multiplyatexport = new BigDecimal(1);\n\n public static class DecimalParser {\n\n private int scale;\n\n private int precision;\n\n private ChoiceValue locale;\n\n private DecimalFormat decimalformat;\n\n private int specialtreatment;\n\n public static int SPECIAL_TREATMENT_NONE = 0;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_1000 = 1;\n\n public static int SPECIAL_TREATMENT_DIVIDE_BY_1000 = 2;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_100 = 3;\n\n public int getSpecialTreatment() {\n return this.specialtreatment;\n }\n\n /**\n * creates a decimal parser\n *\n * @param scale digits to the right of decimal point (e.g. 533.33 has\n * precision on 2)\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale if CSV import\n */\n public DecimalParser(int scale, int precision, ChoiceValue locale, int specialtreatment) {\n this.scale = scale;\n this.precision = precision;\n this.locale = locale;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.US);\n if (this.locale != null)\n if (this.locale.getStorageCode().equals(ApplocaleChoiceDefinition.get().FR))\n ;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);\n decimalformat.setParseBigDecimal(true);\n this.specialtreatment = specialtreatment;\n }\n\n public DecimalParser(int scale, int precision, ChoiceValue locale) {\n this(scale, precision, locale, SPECIAL_TREATMENT_NONE);\n }\n\n public BigDecimal parse(String value) {\n try {\n BigDecimal decimal = null;\n if (value != null)\n if (value.length() > 0) {\n Number number = decimalformat.parse(value);\n decimal = (BigDecimal) number;\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_1000)\n decimal = decimal.multiply(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_DIVIDE_BY_1000)\n decimal = decimal.divide(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_100)\n decimal = decimal.multiply(new BigDecimal(100));\n }\n if (decimal != null)\n if (decimal.scale() > scale) {\n decimal = decimal.setScale(scale, RoundingMode.HALF_DOWN);\n }\n if (decimal != null)\n if (decimal.precision() > precision)\n throw new RuntimeException(\"bad format for big decimal, precision is longer than limit \" + precision + \" for value \" + decimal);\n return decimal;\n } catch (ParseException e) {\n throw new RuntimeException(\"data is supposed to be big decimal but received the following error when parsing '\" + value + \"'. Exception \" + e.getMessage());\n }\n }\n }\n\n private DecimalParser decimalparser;\n\n public static BigDecimal parsemultiplierForExport(String multiplier) {\n if (multiplier == null)\n return new BigDecimal(1);\n if (multiplier.length() == 0)\n return new BigDecimal(1);\n if (multiplier.trim().equals(\"M1000\"))\n return new BigDecimal(\"0.001\");\n if (multiplier.trim().equals(\"M100\"))\n return new BigDecimal(\"0.01\");\n if (multiplier.trim().equals(\"D1000\"))\n return new BigDecimal(\"1000\");\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public static int parseMultiplierForImport(String multiplier) {\n if (multiplier == null)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.length() == 0)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.trim().equals(\"M1000\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n if (multiplier.trim().equals(\"M100\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n if (multiplier.trim().equals(\"D1000\"))\n return DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public DecimalDataObjectFieldFlatFileLoaderColumn(DataObjectDefinition definition, String[] arguments, String name, int scale, int precision, ChoiceValue locale) {\n this.scale = scale;\n this.precision = precision;\n this.name = name;\n this.locale = locale;\n int modifier = DecimalParser.SPECIAL_TREATMENT_NONE;\n if (arguments != null)\n if (arguments.length == 1) {\n String multiplier = arguments[0];\n if (multiplier.trim().equals(\"M1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n multiplyatexport = new BigDecimal(\"0.001\");\n }\n if (multiplier.trim().equals(\"M100\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M100\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n multiplyatexport = new BigDecimal(\"0.01\");\n }\n if (multiplier.trim().equals(\"D1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of D1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n multiplyatexport = new BigDecimal(\"1000\");\n }\n if (modifier == DecimalParser.SPECIAL_TREATMENT_NONE)\n throw new RuntimeException(\"Decimal DataObjectFieldFlatFileLoader invalid modifier \" + multiplier);\n }\n if (arguments != null)\n if (arguments.length > 1)\n throw new RuntimeException(\"Decimal DataObjetFieldFlatFileLoader only supports 1 modifier ( M100, M1000 or D1000)\");\n decimalparser = new DecimalParser(scale, precision, locale, modifier);\n }\n\n @Override\n public boolean load(E object, Object value, PostUpdateProcessingStore postupdateprocessingstore) {", "post_mask_code": "\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) object.payload.lookupSimpleFieldOnName(name);\n BigDecimal oldbigdecimal = decimalfield.getValue();\n BigDecimal newbigdecimal = FlatFileLoader.parseDecimal(value, precision, scale, \"Flat file loader for column \" + decimalfield.getName(), decimalparser);\n if (FlatFileLoader.isTheSame(oldbigdecimal, newbigdecimal)) {\n return false;\n } else {\n decimalfield.setValue(newbigdecimal);\n return true;\n }\n }\n\n @Override\n protected boolean putContentInCell(E currentobject, Cell cell, String context) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = currentobject.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + currentobject.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) currentobject.payload.lookupSimpleFieldOnName(name);\n BigDecimal decimal = decimalfield.getValue();\n if (decimal != null) {\n decimal = decimal.multiply(this.multiplyatexport);\n cell.setCellValue(decimal.doubleValue());\n }\n if (this.decimalparser.getSpecialTreatment() == DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100) {\n logger.finest(\"special treatment for cell percentage\");\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * puts a big decimal in cell, formatting as percentage if needed\n *\n * @param cell cell\n * @param value value\n * @param multiplier multiplier in the sense of DecimalFlatFileLoader\n * @return true if formatting was done, false if formatting was not done\n */\n public static > boolean putContentInCell(Cell cell, BigDecimal value, String multiplier) {\n BigDecimal multiplierforexport = parsemultiplierForExport(multiplier);\n if (value != null)\n cell.setCellValue(value.multiply(multiplierforexport).doubleValue());\n if (multiplierforexport.equals(new BigDecimal(\"0.01\"))) {\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * gets a BigDecimal from cell\n *\n * @param value value to parse\n * @param scale number of digits right of the decimal point (e.g.\n * 533.33 is 2 digits\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale for import from text (comma or dot as decimal)\n * @param modifier String modifier in the sense of\n * DecimalDataObjectFieldFlatFileLoader\n * @param contextforerror context used in exceptions\n * @return\n */\n public static > BigDecimal getContentFromCell(Object value, int scale, int precision, ChoiceValue locale, int modifier, String contextforerror) {\n return FlatFileLoader.parseDecimal(value, precision, scale, contextforerror, new DecimalParser(scale, precision, locale, modifier));\n }\n}\n"} {"task_id": "Java_1512", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/server/data/DecimalDataObjectFieldFlatFileLoaderColumn.java", "mask_start_position": 8076, "mask_end_position": 8470, "canonical_solution": "if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) object.payload.lookupSimpleFieldOnName(name);\n BigDecimal oldbigdecimal = decimalfield.getValue();", "pre_mask_code": "package org.openlowcode.server.data;\n\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.text.ParseException;\nimport java.util.Locale;\nimport java.util.logging.Logger;\nimport org.apache.poi.ss.usermodel.Cell;\nimport org.apache.poi.ss.usermodel.CellStyle;\nimport org.openlowcode.module.system.data.choice.ApplocaleChoiceDefinition;\nimport org.openlowcode.server.data.loader.FlatFileExtractor;\nimport org.openlowcode.server.data.loader.FlatFileLoader;\nimport org.openlowcode.server.data.loader.FlatFileLoaderColumn;\nimport org.openlowcode.server.data.loader.PostUpdateProcessingStore;\n\npublic class DecimalDataObjectFieldFlatFileLoaderColumn> extends FlatFileLoaderColumn {\n\n private static Logger logger = Logger.getLogger(DecimalDataObjectFieldFlatFileLoaderColumn.class.getName());\n\n private String name;\n\n private int scale;\n\n private int precision;\n\n @SuppressWarnings(\"unused\")\n private ChoiceValue locale;\n\n public BigDecimal multiplyatexport = new BigDecimal(1);\n\n public static class DecimalParser {\n\n private int scale;\n\n private int precision;\n\n private ChoiceValue locale;\n\n private DecimalFormat decimalformat;\n\n private int specialtreatment;\n\n public static int SPECIAL_TREATMENT_NONE = 0;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_1000 = 1;\n\n public static int SPECIAL_TREATMENT_DIVIDE_BY_1000 = 2;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_100 = 3;\n\n public int getSpecialTreatment() {\n return this.specialtreatment;\n }\n\n /**\n * creates a decimal parser\n *\n * @param scale digits to the right of decimal point (e.g. 533.33 has\n * precision on 2)\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale if CSV import\n */\n public DecimalParser(int scale, int precision, ChoiceValue locale, int specialtreatment) {\n this.scale = scale;\n this.precision = precision;\n this.locale = locale;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.US);\n if (this.locale != null)\n if (this.locale.getStorageCode().equals(ApplocaleChoiceDefinition.get().FR))\n ;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);\n decimalformat.setParseBigDecimal(true);\n this.specialtreatment = specialtreatment;\n }\n\n public DecimalParser(int scale, int precision, ChoiceValue locale) {\n this(scale, precision, locale, SPECIAL_TREATMENT_NONE);\n }\n\n public BigDecimal parse(String value) {\n try {\n BigDecimal decimal = null;\n if (value != null)\n if (value.length() > 0) {\n Number number = decimalformat.parse(value);\n decimal = (BigDecimal) number;\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_1000)\n decimal = decimal.multiply(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_DIVIDE_BY_1000)\n decimal = decimal.divide(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_100)\n decimal = decimal.multiply(new BigDecimal(100));\n }\n if (decimal != null)\n if (decimal.scale() > scale) {\n decimal = decimal.setScale(scale, RoundingMode.HALF_DOWN);\n }\n if (decimal != null)\n if (decimal.precision() > precision)\n throw new RuntimeException(\"bad format for big decimal, precision is longer than limit \" + precision + \" for value \" + decimal);\n return decimal;\n } catch (ParseException e) {\n throw new RuntimeException(\"data is supposed to be big decimal but received the following error when parsing '\" + value + \"'. Exception \" + e.getMessage());\n }\n }\n }\n\n private DecimalParser decimalparser;\n\n public static BigDecimal parsemultiplierForExport(String multiplier) {\n if (multiplier == null)\n return new BigDecimal(1);\n if (multiplier.length() == 0)\n return new BigDecimal(1);\n if (multiplier.trim().equals(\"M1000\"))\n return new BigDecimal(\"0.001\");\n if (multiplier.trim().equals(\"M100\"))\n return new BigDecimal(\"0.01\");\n if (multiplier.trim().equals(\"D1000\"))\n return new BigDecimal(\"1000\");\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public static int parseMultiplierForImport(String multiplier) {\n if (multiplier == null)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.length() == 0)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.trim().equals(\"M1000\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n if (multiplier.trim().equals(\"M100\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n if (multiplier.trim().equals(\"D1000\"))\n return DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public DecimalDataObjectFieldFlatFileLoaderColumn(DataObjectDefinition definition, String[] arguments, String name, int scale, int precision, ChoiceValue locale) {\n this.scale = scale;\n this.precision = precision;\n this.name = name;\n this.locale = locale;\n int modifier = DecimalParser.SPECIAL_TREATMENT_NONE;\n if (arguments != null)\n if (arguments.length == 1) {\n String multiplier = arguments[0];\n if (multiplier.trim().equals(\"M1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n multiplyatexport = new BigDecimal(\"0.001\");\n }\n if (multiplier.trim().equals(\"M100\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M100\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n multiplyatexport = new BigDecimal(\"0.01\");\n }\n if (multiplier.trim().equals(\"D1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of D1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n multiplyatexport = new BigDecimal(\"1000\");\n }\n if (modifier == DecimalParser.SPECIAL_TREATMENT_NONE)\n throw new RuntimeException(\"Decimal DataObjectFieldFlatFileLoader invalid modifier \" + multiplier);\n }\n if (arguments != null)\n if (arguments.length > 1)\n throw new RuntimeException(\"Decimal DataObjetFieldFlatFileLoader only supports 1 modifier ( M100, M1000 or D1000)\");\n decimalparser = new DecimalParser(scale, precision, locale, modifier);\n }\n\n @Override\n public boolean load(E object, Object value, PostUpdateProcessingStore postupdateprocessingstore) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = object.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + object.getName());\n ", "post_mask_code": "\n BigDecimal newbigdecimal = FlatFileLoader.parseDecimal(value, precision, scale, \"Flat file loader for column \" + decimalfield.getName(), decimalparser);\n if (FlatFileLoader.isTheSame(oldbigdecimal, newbigdecimal)) {\n return false;\n } else {\n decimalfield.setValue(newbigdecimal);\n return true;\n }\n }\n\n @Override\n protected boolean putContentInCell(E currentobject, Cell cell, String context) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = currentobject.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + currentobject.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) currentobject.payload.lookupSimpleFieldOnName(name);\n BigDecimal decimal = decimalfield.getValue();\n if (decimal != null) {\n decimal = decimal.multiply(this.multiplyatexport);\n cell.setCellValue(decimal.doubleValue());\n }\n if (this.decimalparser.getSpecialTreatment() == DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100) {\n logger.finest(\"special treatment for cell percentage\");\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * puts a big decimal in cell, formatting as percentage if needed\n *\n * @param cell cell\n * @param value value\n * @param multiplier multiplier in the sense of DecimalFlatFileLoader\n * @return true if formatting was done, false if formatting was not done\n */\n public static > boolean putContentInCell(Cell cell, BigDecimal value, String multiplier) {\n BigDecimal multiplierforexport = parsemultiplierForExport(multiplier);\n if (value != null)\n cell.setCellValue(value.multiply(multiplierforexport).doubleValue());\n if (multiplierforexport.equals(new BigDecimal(\"0.01\"))) {\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * gets a BigDecimal from cell\n *\n * @param value value to parse\n * @param scale number of digits right of the decimal point (e.g.\n * 533.33 is 2 digits\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale for import from text (comma or dot as decimal)\n * @param modifier String modifier in the sense of\n * DecimalDataObjectFieldFlatFileLoader\n * @param contextforerror context used in exceptions\n * @return\n */\n public static > BigDecimal getContentFromCell(Object value, int scale, int precision, ChoiceValue locale, int modifier, String contextforerror) {\n return FlatFileLoader.parseDecimal(value, precision, scale, contextforerror, new DecimalParser(scale, precision, locale, modifier));\n }\n}\n"} {"task_id": "Java_1513", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/server/data/DecimalDataObjectFieldFlatFileLoaderColumn.java", "mask_start_position": 8479, "mask_end_position": 8835, "canonical_solution": "BigDecimal newbigdecimal = FlatFileLoader.parseDecimal(value, precision, scale, \"Flat file loader for column \" + decimalfield.getName(), decimalparser);\n if (FlatFileLoader.isTheSame(oldbigdecimal, newbigdecimal)) {\n return false;\n } else {\n decimalfield.setValue(newbigdecimal);\n return true;\n }\n }", "pre_mask_code": "package org.openlowcode.server.data;\n\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.text.ParseException;\nimport java.util.Locale;\nimport java.util.logging.Logger;\nimport org.apache.poi.ss.usermodel.Cell;\nimport org.apache.poi.ss.usermodel.CellStyle;\nimport org.openlowcode.module.system.data.choice.ApplocaleChoiceDefinition;\nimport org.openlowcode.server.data.loader.FlatFileExtractor;\nimport org.openlowcode.server.data.loader.FlatFileLoader;\nimport org.openlowcode.server.data.loader.FlatFileLoaderColumn;\nimport org.openlowcode.server.data.loader.PostUpdateProcessingStore;\n\npublic class DecimalDataObjectFieldFlatFileLoaderColumn> extends FlatFileLoaderColumn {\n\n private static Logger logger = Logger.getLogger(DecimalDataObjectFieldFlatFileLoaderColumn.class.getName());\n\n private String name;\n\n private int scale;\n\n private int precision;\n\n @SuppressWarnings(\"unused\")\n private ChoiceValue locale;\n\n public BigDecimal multiplyatexport = new BigDecimal(1);\n\n public static class DecimalParser {\n\n private int scale;\n\n private int precision;\n\n private ChoiceValue locale;\n\n private DecimalFormat decimalformat;\n\n private int specialtreatment;\n\n public static int SPECIAL_TREATMENT_NONE = 0;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_1000 = 1;\n\n public static int SPECIAL_TREATMENT_DIVIDE_BY_1000 = 2;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_100 = 3;\n\n public int getSpecialTreatment() {\n return this.specialtreatment;\n }\n\n /**\n * creates a decimal parser\n *\n * @param scale digits to the right of decimal point (e.g. 533.33 has\n * precision on 2)\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale if CSV import\n */\n public DecimalParser(int scale, int precision, ChoiceValue locale, int specialtreatment) {\n this.scale = scale;\n this.precision = precision;\n this.locale = locale;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.US);\n if (this.locale != null)\n if (this.locale.getStorageCode().equals(ApplocaleChoiceDefinition.get().FR))\n ;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);\n decimalformat.setParseBigDecimal(true);\n this.specialtreatment = specialtreatment;\n }\n\n public DecimalParser(int scale, int precision, ChoiceValue locale) {\n this(scale, precision, locale, SPECIAL_TREATMENT_NONE);\n }\n\n public BigDecimal parse(String value) {\n try {\n BigDecimal decimal = null;\n if (value != null)\n if (value.length() > 0) {\n Number number = decimalformat.parse(value);\n decimal = (BigDecimal) number;\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_1000)\n decimal = decimal.multiply(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_DIVIDE_BY_1000)\n decimal = decimal.divide(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_100)\n decimal = decimal.multiply(new BigDecimal(100));\n }\n if (decimal != null)\n if (decimal.scale() > scale) {\n decimal = decimal.setScale(scale, RoundingMode.HALF_DOWN);\n }\n if (decimal != null)\n if (decimal.precision() > precision)\n throw new RuntimeException(\"bad format for big decimal, precision is longer than limit \" + precision + \" for value \" + decimal);\n return decimal;\n } catch (ParseException e) {\n throw new RuntimeException(\"data is supposed to be big decimal but received the following error when parsing '\" + value + \"'. Exception \" + e.getMessage());\n }\n }\n }\n\n private DecimalParser decimalparser;\n\n public static BigDecimal parsemultiplierForExport(String multiplier) {\n if (multiplier == null)\n return new BigDecimal(1);\n if (multiplier.length() == 0)\n return new BigDecimal(1);\n if (multiplier.trim().equals(\"M1000\"))\n return new BigDecimal(\"0.001\");\n if (multiplier.trim().equals(\"M100\"))\n return new BigDecimal(\"0.01\");\n if (multiplier.trim().equals(\"D1000\"))\n return new BigDecimal(\"1000\");\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public static int parseMultiplierForImport(String multiplier) {\n if (multiplier == null)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.length() == 0)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.trim().equals(\"M1000\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n if (multiplier.trim().equals(\"M100\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n if (multiplier.trim().equals(\"D1000\"))\n return DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public DecimalDataObjectFieldFlatFileLoaderColumn(DataObjectDefinition definition, String[] arguments, String name, int scale, int precision, ChoiceValue locale) {\n this.scale = scale;\n this.precision = precision;\n this.name = name;\n this.locale = locale;\n int modifier = DecimalParser.SPECIAL_TREATMENT_NONE;\n if (arguments != null)\n if (arguments.length == 1) {\n String multiplier = arguments[0];\n if (multiplier.trim().equals(\"M1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n multiplyatexport = new BigDecimal(\"0.001\");\n }\n if (multiplier.trim().equals(\"M100\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M100\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n multiplyatexport = new BigDecimal(\"0.01\");\n }\n if (multiplier.trim().equals(\"D1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of D1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n multiplyatexport = new BigDecimal(\"1000\");\n }\n if (modifier == DecimalParser.SPECIAL_TREATMENT_NONE)\n throw new RuntimeException(\"Decimal DataObjectFieldFlatFileLoader invalid modifier \" + multiplier);\n }\n if (arguments != null)\n if (arguments.length > 1)\n throw new RuntimeException(\"Decimal DataObjetFieldFlatFileLoader only supports 1 modifier ( M100, M1000 or D1000)\");\n decimalparser = new DecimalParser(scale, precision, locale, modifier);\n }\n\n @Override\n public boolean load(E object, Object value, PostUpdateProcessingStore postupdateprocessingstore) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = object.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + object.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) object.payload.lookupSimpleFieldOnName(name);\n BigDecimal oldbigdecimal = decimalfield.getValue();\n ", "post_mask_code": "\n\n @Override\n protected boolean putContentInCell(E currentobject, Cell cell, String context) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = currentobject.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + currentobject.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) currentobject.payload.lookupSimpleFieldOnName(name);\n BigDecimal decimal = decimalfield.getValue();\n if (decimal != null) {\n decimal = decimal.multiply(this.multiplyatexport);\n cell.setCellValue(decimal.doubleValue());\n }\n if (this.decimalparser.getSpecialTreatment() == DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100) {\n logger.finest(\"special treatment for cell percentage\");\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * puts a big decimal in cell, formatting as percentage if needed\n *\n * @param cell cell\n * @param value value\n * @param multiplier multiplier in the sense of DecimalFlatFileLoader\n * @return true if formatting was done, false if formatting was not done\n */\n public static > boolean putContentInCell(Cell cell, BigDecimal value, String multiplier) {\n BigDecimal multiplierforexport = parsemultiplierForExport(multiplier);\n if (value != null)\n cell.setCellValue(value.multiply(multiplierforexport).doubleValue());\n if (multiplierforexport.equals(new BigDecimal(\"0.01\"))) {\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * gets a BigDecimal from cell\n *\n * @param value value to parse\n * @param scale number of digits right of the decimal point (e.g.\n * 533.33 is 2 digits\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale for import from text (comma or dot as decimal)\n * @param modifier String modifier in the sense of\n * DecimalDataObjectFieldFlatFileLoader\n * @param contextforerror context used in exceptions\n * @return\n */\n public static > BigDecimal getContentFromCell(Object value, int scale, int precision, ChoiceValue locale, int modifier, String contextforerror) {\n return FlatFileLoader.parseDecimal(value, precision, scale, contextforerror, new DecimalParser(scale, precision, locale, modifier));\n }\n}\n"} {"task_id": "Java_1514", "language": "Java", "task_type": "single_line", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/server/data/DecimalDataObjectFieldFlatFileLoaderColumn.java", "mask_start_position": 5020, "mask_end_position": 5079, "canonical_solution": "w new RuntimeException(\"Invalid multiplier \" + multiplier);", "pre_mask_code": "package org.openlowcode.server.data;\n\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.text.ParseException;\nimport java.util.Locale;\nimport java.util.logging.Logger;\nimport org.apache.poi.ss.usermodel.Cell;\nimport org.apache.poi.ss.usermodel.CellStyle;\nimport org.openlowcode.module.system.data.choice.ApplocaleChoiceDefinition;\nimport org.openlowcode.server.data.loader.FlatFileExtractor;\nimport org.openlowcode.server.data.loader.FlatFileLoader;\nimport org.openlowcode.server.data.loader.FlatFileLoaderColumn;\nimport org.openlowcode.server.data.loader.PostUpdateProcessingStore;\n\npublic class DecimalDataObjectFieldFlatFileLoaderColumn> extends FlatFileLoaderColumn {\n\n private static Logger logger = Logger.getLogger(DecimalDataObjectFieldFlatFileLoaderColumn.class.getName());\n\n private String name;\n\n private int scale;\n\n private int precision;\n\n @SuppressWarnings(\"unused\")\n private ChoiceValue locale;\n\n public BigDecimal multiplyatexport = new BigDecimal(1);\n\n public static class DecimalParser {\n\n private int scale;\n\n private int precision;\n\n private ChoiceValue locale;\n\n private DecimalFormat decimalformat;\n\n private int specialtreatment;\n\n public static int SPECIAL_TREATMENT_NONE = 0;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_1000 = 1;\n\n public static int SPECIAL_TREATMENT_DIVIDE_BY_1000 = 2;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_100 = 3;\n\n public int getSpecialTreatment() {\n return this.specialtreatment;\n }\n\n /**\n * creates a decimal parser\n *\n * @param scale digits to the right of decimal point (e.g. 533.33 has\n * precision on 2)\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale if CSV import\n */\n public DecimalParser(int scale, int precision, ChoiceValue locale, int specialtreatment) {\n this.scale = scale;\n this.precision = precision;\n this.locale = locale;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.US);\n if (this.locale != null)\n if (this.locale.getStorageCode().equals(ApplocaleChoiceDefinition.get().FR))\n ;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);\n decimalformat.setParseBigDecimal(true);\n this.specialtreatment = specialtreatment;\n }\n\n public DecimalParser(int scale, int precision, ChoiceValue locale) {\n this(scale, precision, locale, SPECIAL_TREATMENT_NONE);\n }\n\n public BigDecimal parse(String value) {\n try {\n BigDecimal decimal = null;\n if (value != null)\n if (value.length() > 0) {\n Number number = decimalformat.parse(value);\n decimal = (BigDecimal) number;\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_1000)\n decimal = decimal.multiply(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_DIVIDE_BY_1000)\n decimal = decimal.divide(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_100)\n decimal = decimal.multiply(new BigDecimal(100));\n }\n if (decimal != null)\n if (decimal.scale() > scale) {\n decimal = decimal.setScale(scale, RoundingMode.HALF_DOWN);\n }\n if (decimal != null)\n if (decimal.precision() > precision)\n throw new RuntimeException(\"bad format for big decimal, precision is longer than limit \" + precision + \" for value \" + decimal);\n return decimal;\n } catch (ParseException e) {\n throw new RuntimeException(\"data is supposed to be big decimal but received the following error when parsing '\" + value + \"'. Exception \" + e.getMessage());\n }\n }\n }\n\n private DecimalParser decimalparser;\n\n public static BigDecimal parsemultiplierForExport(String multiplier) {\n if (multiplier == null)\n return new BigDecimal(1);\n if (multiplier.length() == 0)\n return new BigDecimal(1);\n if (multiplier.trim().equals(\"M1000\"))\n return new BigDecimal(\"0.001\");\n if (multiplier.trim().equals(\"M100\"))\n return new BigDecimal(\"0.01\");\n if (multiplier.trim().equals(\"D1000\"))\n return new BigDecimal(\"1000\");\n thro", "post_mask_code": "\n }\n\n public static int parseMultiplierForImport(String multiplier) {\n if (multiplier == null)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.length() == 0)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.trim().equals(\"M1000\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n if (multiplier.trim().equals(\"M100\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n if (multiplier.trim().equals(\"D1000\"))\n return DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public DecimalDataObjectFieldFlatFileLoaderColumn(DataObjectDefinition definition, String[] arguments, String name, int scale, int precision, ChoiceValue locale) {\n this.scale = scale;\n this.precision = precision;\n this.name = name;\n this.locale = locale;\n int modifier = DecimalParser.SPECIAL_TREATMENT_NONE;\n if (arguments != null)\n if (arguments.length == 1) {\n String multiplier = arguments[0];\n if (multiplier.trim().equals(\"M1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n multiplyatexport = new BigDecimal(\"0.001\");\n }\n if (multiplier.trim().equals(\"M100\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M100\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n multiplyatexport = new BigDecimal(\"0.01\");\n }\n if (multiplier.trim().equals(\"D1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of D1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n multiplyatexport = new BigDecimal(\"1000\");\n }\n if (modifier == DecimalParser.SPECIAL_TREATMENT_NONE)\n throw new RuntimeException(\"Decimal DataObjectFieldFlatFileLoader invalid modifier \" + multiplier);\n }\n if (arguments != null)\n if (arguments.length > 1)\n throw new RuntimeException(\"Decimal DataObjetFieldFlatFileLoader only supports 1 modifier ( M100, M1000 or D1000)\");\n decimalparser = new DecimalParser(scale, precision, locale, modifier);\n }\n\n @Override\n public boolean load(E object, Object value, PostUpdateProcessingStore postupdateprocessingstore) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = object.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + object.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) object.payload.lookupSimpleFieldOnName(name);\n BigDecimal oldbigdecimal = decimalfield.getValue();\n BigDecimal newbigdecimal = FlatFileLoader.parseDecimal(value, precision, scale, \"Flat file loader for column \" + decimalfield.getName(), decimalparser);\n if (FlatFileLoader.isTheSame(oldbigdecimal, newbigdecimal)) {\n return false;\n } else {\n decimalfield.setValue(newbigdecimal);\n return true;\n }\n }\n\n @Override\n protected boolean putContentInCell(E currentobject, Cell cell, String context) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = currentobject.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + currentobject.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) currentobject.payload.lookupSimpleFieldOnName(name);\n BigDecimal decimal = decimalfield.getValue();\n if (decimal != null) {\n decimal = decimal.multiply(this.multiplyatexport);\n cell.setCellValue(decimal.doubleValue());\n }\n if (this.decimalparser.getSpecialTreatment() == DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100) {\n logger.finest(\"special treatment for cell percentage\");\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * puts a big decimal in cell, formatting as percentage if needed\n *\n * @param cell cell\n * @param value value\n * @param multiplier multiplier in the sense of DecimalFlatFileLoader\n * @return true if formatting was done, false if formatting was not done\n */\n public static > boolean putContentInCell(Cell cell, BigDecimal value, String multiplier) {\n BigDecimal multiplierforexport = parsemultiplierForExport(multiplier);\n if (value != null)\n cell.setCellValue(value.multiply(multiplierforexport).doubleValue());\n if (multiplierforexport.equals(new BigDecimal(\"0.01\"))) {\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * gets a BigDecimal from cell\n *\n * @param value value to parse\n * @param scale number of digits right of the decimal point (e.g.\n * 533.33 is 2 digits\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale for import from text (comma or dot as decimal)\n * @param modifier String modifier in the sense of\n * DecimalDataObjectFieldFlatFileLoader\n * @param contextforerror context used in exceptions\n * @return\n */\n public static > BigDecimal getContentFromCell(Object value, int scale, int precision, ChoiceValue locale, int modifier, String contextforerror) {\n return FlatFileLoader.parseDecimal(value, precision, scale, contextforerror, new DecimalParser(scale, precision, locale, modifier));\n }\n}\n"} {"task_id": "Java_1515", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/server/data/DecimalDataObjectFieldFlatFileLoaderColumn.java", "mask_start_position": 11968, "mask_end_position": 12322, "canonical_solution": "public static > BigDecimal getContentFromCell(Object value, int scale, int precision, ChoiceValue locale, int modifier, String contextforerror) {\n return FlatFileLoader.parseDecimal(value, precision, scale, contextforerror, new DecimalParser(scale, precision, locale, modifier));\n }", "pre_mask_code": "package org.openlowcode.server.data;\n\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.text.ParseException;\nimport java.util.Locale;\nimport java.util.logging.Logger;\nimport org.apache.poi.ss.usermodel.Cell;\nimport org.apache.poi.ss.usermodel.CellStyle;\nimport org.openlowcode.module.system.data.choice.ApplocaleChoiceDefinition;\nimport org.openlowcode.server.data.loader.FlatFileExtractor;\nimport org.openlowcode.server.data.loader.FlatFileLoader;\nimport org.openlowcode.server.data.loader.FlatFileLoaderColumn;\nimport org.openlowcode.server.data.loader.PostUpdateProcessingStore;\n\npublic class DecimalDataObjectFieldFlatFileLoaderColumn> extends FlatFileLoaderColumn {\n\n private static Logger logger = Logger.getLogger(DecimalDataObjectFieldFlatFileLoaderColumn.class.getName());\n\n private String name;\n\n private int scale;\n\n private int precision;\n\n @SuppressWarnings(\"unused\")\n private ChoiceValue locale;\n\n public BigDecimal multiplyatexport = new BigDecimal(1);\n\n public static class DecimalParser {\n\n private int scale;\n\n private int precision;\n\n private ChoiceValue locale;\n\n private DecimalFormat decimalformat;\n\n private int specialtreatment;\n\n public static int SPECIAL_TREATMENT_NONE = 0;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_1000 = 1;\n\n public static int SPECIAL_TREATMENT_DIVIDE_BY_1000 = 2;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_100 = 3;\n\n public int getSpecialTreatment() {\n return this.specialtreatment;\n }\n\n /**\n * creates a decimal parser\n *\n * @param scale digits to the right of decimal point (e.g. 533.33 has\n * precision on 2)\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale if CSV import\n */\n public DecimalParser(int scale, int precision, ChoiceValue locale, int specialtreatment) {\n this.scale = scale;\n this.precision = precision;\n this.locale = locale;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.US);\n if (this.locale != null)\n if (this.locale.getStorageCode().equals(ApplocaleChoiceDefinition.get().FR))\n ;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);\n decimalformat.setParseBigDecimal(true);\n this.specialtreatment = specialtreatment;\n }\n\n public DecimalParser(int scale, int precision, ChoiceValue locale) {\n this(scale, precision, locale, SPECIAL_TREATMENT_NONE);\n }\n\n public BigDecimal parse(String value) {\n try {\n BigDecimal decimal = null;\n if (value != null)\n if (value.length() > 0) {\n Number number = decimalformat.parse(value);\n decimal = (BigDecimal) number;\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_1000)\n decimal = decimal.multiply(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_DIVIDE_BY_1000)\n decimal = decimal.divide(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_100)\n decimal = decimal.multiply(new BigDecimal(100));\n }\n if (decimal != null)\n if (decimal.scale() > scale) {\n decimal = decimal.setScale(scale, RoundingMode.HALF_DOWN);\n }\n if (decimal != null)\n if (decimal.precision() > precision)\n throw new RuntimeException(\"bad format for big decimal, precision is longer than limit \" + precision + \" for value \" + decimal);\n return decimal;\n } catch (ParseException e) {\n throw new RuntimeException(\"data is supposed to be big decimal but received the following error when parsing '\" + value + \"'. Exception \" + e.getMessage());\n }\n }\n }\n\n private DecimalParser decimalparser;\n\n public static BigDecimal parsemultiplierForExport(String multiplier) {\n if (multiplier == null)\n return new BigDecimal(1);\n if (multiplier.length() == 0)\n return new BigDecimal(1);\n if (multiplier.trim().equals(\"M1000\"))\n return new BigDecimal(\"0.001\");\n if (multiplier.trim().equals(\"M100\"))\n return new BigDecimal(\"0.01\");\n if (multiplier.trim().equals(\"D1000\"))\n return new BigDecimal(\"1000\");\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public static int parseMultiplierForImport(String multiplier) {\n if (multiplier == null)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.length() == 0)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.trim().equals(\"M1000\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n if (multiplier.trim().equals(\"M100\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n if (multiplier.trim().equals(\"D1000\"))\n return DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public DecimalDataObjectFieldFlatFileLoaderColumn(DataObjectDefinition definition, String[] arguments, String name, int scale, int precision, ChoiceValue locale) {\n this.scale = scale;\n this.precision = precision;\n this.name = name;\n this.locale = locale;\n int modifier = DecimalParser.SPECIAL_TREATMENT_NONE;\n if (arguments != null)\n if (arguments.length == 1) {\n String multiplier = arguments[0];\n if (multiplier.trim().equals(\"M1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n multiplyatexport = new BigDecimal(\"0.001\");\n }\n if (multiplier.trim().equals(\"M100\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M100\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n multiplyatexport = new BigDecimal(\"0.01\");\n }\n if (multiplier.trim().equals(\"D1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of D1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n multiplyatexport = new BigDecimal(\"1000\");\n }\n if (modifier == DecimalParser.SPECIAL_TREATMENT_NONE)\n throw new RuntimeException(\"Decimal DataObjectFieldFlatFileLoader invalid modifier \" + multiplier);\n }\n if (arguments != null)\n if (arguments.length > 1)\n throw new RuntimeException(\"Decimal DataObjetFieldFlatFileLoader only supports 1 modifier ( M100, M1000 or D1000)\");\n decimalparser = new DecimalParser(scale, precision, locale, modifier);\n }\n\n @Override\n public boolean load(E object, Object value, PostUpdateProcessingStore postupdateprocessingstore) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = object.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + object.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) object.payload.lookupSimpleFieldOnName(name);\n BigDecimal oldbigdecimal = decimalfield.getValue();\n BigDecimal newbigdecimal = FlatFileLoader.parseDecimal(value, precision, scale, \"Flat file loader for column \" + decimalfield.getName(), decimalparser);\n if (FlatFileLoader.isTheSame(oldbigdecimal, newbigdecimal)) {\n return false;\n } else {\n decimalfield.setValue(newbigdecimal);\n return true;\n }\n }\n\n @Override\n protected boolean putContentInCell(E currentobject, Cell cell, String context) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = currentobject.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + currentobject.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) currentobject.payload.lookupSimpleFieldOnName(name);\n BigDecimal decimal = decimalfield.getValue();\n if (decimal != null) {\n decimal = decimal.multiply(this.multiplyatexport);\n cell.setCellValue(decimal.doubleValue());\n }\n if (this.decimalparser.getSpecialTreatment() == DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100) {\n logger.finest(\"special treatment for cell percentage\");\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * puts a big decimal in cell, formatting as percentage if needed\n *\n * @param cell cell\n * @param value value\n * @param multiplier multiplier in the sense of DecimalFlatFileLoader\n * @return true if formatting was done, false if formatting was not done\n */\n public static > boolean putContentInCell(Cell cell, BigDecimal value, String multiplier) {\n BigDecimal multiplierforexport = parsemultiplierForExport(multiplier);\n if (value != null)\n cell.setCellValue(value.multiply(multiplierforexport).doubleValue());\n if (multiplierforexport.equals(new BigDecimal(\"0.01\"))) {\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * gets a BigDecimal from cell\n *\n * @param value value to parse\n * @param scale number of digits right of the decimal point (e.g.\n * 533.33 is 2 digits\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale for import from text (comma or dot as decimal)\n * @param modifier String modifier in the sense of\n * DecimalDataObjectFieldFlatFileLoader\n * @param contextforerror context used in exceptions\n * @return\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1516", "language": "Java", "task_type": "if_statement", "source_file": "java/github/openlowcode/Open-Lowcode/src/org/openlowcode/server/data/DecimalDataObjectFieldFlatFileLoaderColumn.java", "mask_start_position": 4926, "mask_end_position": 5007, "canonical_solution": "if (multiplier.trim().equals(\"D1000\"))\n return new BigDecimal(\"1000\");", "pre_mask_code": "package org.openlowcode.server.data;\n\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.text.ParseException;\nimport java.util.Locale;\nimport java.util.logging.Logger;\nimport org.apache.poi.ss.usermodel.Cell;\nimport org.apache.poi.ss.usermodel.CellStyle;\nimport org.openlowcode.module.system.data.choice.ApplocaleChoiceDefinition;\nimport org.openlowcode.server.data.loader.FlatFileExtractor;\nimport org.openlowcode.server.data.loader.FlatFileLoader;\nimport org.openlowcode.server.data.loader.FlatFileLoaderColumn;\nimport org.openlowcode.server.data.loader.PostUpdateProcessingStore;\n\npublic class DecimalDataObjectFieldFlatFileLoaderColumn> extends FlatFileLoaderColumn {\n\n private static Logger logger = Logger.getLogger(DecimalDataObjectFieldFlatFileLoaderColumn.class.getName());\n\n private String name;\n\n private int scale;\n\n private int precision;\n\n @SuppressWarnings(\"unused\")\n private ChoiceValue locale;\n\n public BigDecimal multiplyatexport = new BigDecimal(1);\n\n public static class DecimalParser {\n\n private int scale;\n\n private int precision;\n\n private ChoiceValue locale;\n\n private DecimalFormat decimalformat;\n\n private int specialtreatment;\n\n public static int SPECIAL_TREATMENT_NONE = 0;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_1000 = 1;\n\n public static int SPECIAL_TREATMENT_DIVIDE_BY_1000 = 2;\n\n public static int SPECIAL_TREATMENT_MULTIPLY_BY_100 = 3;\n\n public int getSpecialTreatment() {\n return this.specialtreatment;\n }\n\n /**\n * creates a decimal parser\n *\n * @param scale digits to the right of decimal point (e.g. 533.33 has\n * precision on 2)\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale if CSV import\n */\n public DecimalParser(int scale, int precision, ChoiceValue locale, int specialtreatment) {\n this.scale = scale;\n this.precision = precision;\n this.locale = locale;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.US);\n if (this.locale != null)\n if (this.locale.getStorageCode().equals(ApplocaleChoiceDefinition.get().FR))\n ;\n decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);\n decimalformat.setParseBigDecimal(true);\n this.specialtreatment = specialtreatment;\n }\n\n public DecimalParser(int scale, int precision, ChoiceValue locale) {\n this(scale, precision, locale, SPECIAL_TREATMENT_NONE);\n }\n\n public BigDecimal parse(String value) {\n try {\n BigDecimal decimal = null;\n if (value != null)\n if (value.length() > 0) {\n Number number = decimalformat.parse(value);\n decimal = (BigDecimal) number;\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_1000)\n decimal = decimal.multiply(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_DIVIDE_BY_1000)\n decimal = decimal.divide(new BigDecimal(1000));\n if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_100)\n decimal = decimal.multiply(new BigDecimal(100));\n }\n if (decimal != null)\n if (decimal.scale() > scale) {\n decimal = decimal.setScale(scale, RoundingMode.HALF_DOWN);\n }\n if (decimal != null)\n if (decimal.precision() > precision)\n throw new RuntimeException(\"bad format for big decimal, precision is longer than limit \" + precision + \" for value \" + decimal);\n return decimal;\n } catch (ParseException e) {\n throw new RuntimeException(\"data is supposed to be big decimal but received the following error when parsing '\" + value + \"'. Exception \" + e.getMessage());\n }\n }\n }\n\n private DecimalParser decimalparser;\n\n public static BigDecimal parsemultiplierForExport(String multiplier) {\n if (multiplier == null)\n return new BigDecimal(1);\n if (multiplier.length() == 0)\n return new BigDecimal(1);\n if (multiplier.trim().equals(\"M1000\"))\n return new BigDecimal(\"0.001\");\n if (multiplier.trim().equals(\"M100\"))\n return new BigDecimal(\"0.01\");\n ", "post_mask_code": "\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public static int parseMultiplierForImport(String multiplier) {\n if (multiplier == null)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.length() == 0)\n return DecimalParser.SPECIAL_TREATMENT_NONE;\n if (multiplier.trim().equals(\"M1000\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n if (multiplier.trim().equals(\"M100\"))\n return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n if (multiplier.trim().equals(\"D1000\"))\n return DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n throw new RuntimeException(\"Invalid multiplier \" + multiplier);\n }\n\n public DecimalDataObjectFieldFlatFileLoaderColumn(DataObjectDefinition definition, String[] arguments, String name, int scale, int precision, ChoiceValue locale) {\n this.scale = scale;\n this.precision = precision;\n this.name = name;\n this.locale = locale;\n int modifier = DecimalParser.SPECIAL_TREATMENT_NONE;\n if (arguments != null)\n if (arguments.length == 1) {\n String multiplier = arguments[0];\n if (multiplier.trim().equals(\"M1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;\n multiplyatexport = new BigDecimal(\"0.001\");\n }\n if (multiplier.trim().equals(\"M100\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of M100\");\n modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;\n multiplyatexport = new BigDecimal(\"0.01\");\n }\n if (multiplier.trim().equals(\"D1000\")) {\n logger.finer(\" ---> For field \" + name + \", special treatment of D1000\");\n modifier = DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;\n multiplyatexport = new BigDecimal(\"1000\");\n }\n if (modifier == DecimalParser.SPECIAL_TREATMENT_NONE)\n throw new RuntimeException(\"Decimal DataObjectFieldFlatFileLoader invalid modifier \" + multiplier);\n }\n if (arguments != null)\n if (arguments.length > 1)\n throw new RuntimeException(\"Decimal DataObjetFieldFlatFileLoader only supports 1 modifier ( M100, M1000 or D1000)\");\n decimalparser = new DecimalParser(scale, precision, locale, modifier);\n }\n\n @Override\n public boolean load(E object, Object value, PostUpdateProcessingStore postupdateprocessingstore) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = object.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + object.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) object.payload.lookupSimpleFieldOnName(name);\n BigDecimal oldbigdecimal = decimalfield.getValue();\n BigDecimal newbigdecimal = FlatFileLoader.parseDecimal(value, precision, scale, \"Flat file loader for column \" + decimalfield.getName(), decimalparser);\n if (FlatFileLoader.isTheSame(oldbigdecimal, newbigdecimal)) {\n return false;\n } else {\n decimalfield.setValue(newbigdecimal);\n return true;\n }\n }\n\n @Override\n protected boolean putContentInCell(E currentobject, Cell cell, String context) {\n @SuppressWarnings(\"unchecked\")\n DataObjectField field = currentobject.payload.lookupSimpleFieldOnName(name);\n if (field == null)\n throw new RuntimeException(\"field \" + name + \" could not be looked-up on \" + currentobject.getName());\n if (!(field instanceof DecimalDataObjectField))\n throw new RuntimeException(\"Expected field \" + name + \" would be of type DecimalDataObjectField but in reality, it is \" + field.getClass().toString());\n DecimalDataObjectField decimalfield = (DecimalDataObjectField) currentobject.payload.lookupSimpleFieldOnName(name);\n BigDecimal decimal = decimalfield.getValue();\n if (decimal != null) {\n decimal = decimal.multiply(this.multiplyatexport);\n cell.setCellValue(decimal.doubleValue());\n }\n if (this.decimalparser.getSpecialTreatment() == DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100) {\n logger.finest(\"special treatment for cell percentage\");\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * puts a big decimal in cell, formatting as percentage if needed\n *\n * @param cell cell\n * @param value value\n * @param multiplier multiplier in the sense of DecimalFlatFileLoader\n * @return true if formatting was done, false if formatting was not done\n */\n public static > boolean putContentInCell(Cell cell, BigDecimal value, String multiplier) {\n BigDecimal multiplierforexport = parsemultiplierForExport(multiplier);\n if (value != null)\n cell.setCellValue(value.multiply(multiplierforexport).doubleValue());\n if (multiplierforexport.equals(new BigDecimal(\"0.01\"))) {\n CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());\n percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat(\"0.0%\"));\n cell.setCellStyle(percentagecellstyle);\n return true;\n }\n return false;\n }\n\n /**\n * gets a BigDecimal from cell\n *\n * @param value value to parse\n * @param scale number of digits right of the decimal point (e.g.\n * 533.33 is 2 digits\n * @param precision total number of digits of the number (e.g. 533.33 is 5\n * digits)\n * @param locale locale for import from text (comma or dot as decimal)\n * @param modifier String modifier in the sense of\n * DecimalDataObjectFieldFlatFileLoader\n * @param contextforerror context used in exceptions\n * @return\n */\n public static > BigDecimal getContentFromCell(Object value, int scale, int precision, ChoiceValue locale, int modifier, String contextforerror) {\n return FlatFileLoader.parseDecimal(value, precision, scale, contextforerror, new DecimalParser(scale, precision, locale, modifier));\n }\n}\n"} {"task_id": "Java_1517", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse-ee4j/glassfish/appserver/tests/appserv-tests/devtests/deployment/ejb30/ear/session3/persistence/Person.java", "mask_start_position": 315, "mask_end_position": 354, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "package com.sun.s1asdev.ejb.ejb30.hello.session3;\n\nimport jakarta.persistence.*;\n\n@Entity\n@Table(name = \"EJB30_HELLO_SESSION3_PERSON\")\npublic class Person implements java.io.Serializable {\n\n @Id\n String name;\n\n public Person() {\n }\n\n public Person(String name) {\n this.name = name;\n }\n\n ", "post_mask_code": "{\n return \"Person: {\" + \"(name = \" + name + \")}\";\n }\n}\n"} {"task_id": "Java_1518", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse-ee4j/glassfish/appserver/tests/appserv-tests/devtests/deployment/ejb30/ear/session3/persistence/Person.java", "mask_start_position": 354, "mask_end_position": 416, "canonical_solution": "{\n return \"Person: {\" + \"(name = \" + name + \")}\";\n }", "pre_mask_code": "package com.sun.s1asdev.ejb.ejb30.hello.session3;\n\nimport jakarta.persistence.*;\n\n@Entity\n@Table(name = \"EJB30_HELLO_SESSION3_PERSON\")\npublic class Person implements java.io.Serializable {\n\n @Id\n String name;\n\n public Person() {\n }\n\n public Person(String name) {\n this.name = name;\n }\n\n @Override\n public String toString() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1519", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse-ee4j/glassfish/appserver/tests/appserv-tests/devtests/deployment/ejb30/ear/session3/persistence/Person.java", "mask_start_position": 390, "mask_end_position": 410, "canonical_solution": "e = \" + name + \")}\";", "pre_mask_code": "package com.sun.s1asdev.ejb.ejb30.hello.session3;\n\nimport jakarta.persistence.*;\n\n@Entity\n@Table(name = \"EJB30_HELLO_SESSION3_PERSON\")\npublic class Person implements java.io.Serializable {\n\n @Id\n String name;\n\n public Person() {\n }\n\n public Person(String name) {\n this.name = name;\n }\n\n @Override\n public String toString() {\n return \"Person: {\" + \"(nam", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1520", "language": "Java", "task_type": "method_signature", "source_file": "java/github/glowroot/glowroot/agent/core/src/main/java/org/glowroot/agent/util/Reflections.java", "mask_start_position": 1674, "mask_end_position": 1791, "canonical_solution": "private static Method getAnyDeclaredMethod(Class clazz, String name, Class... parameterTypes) throws Exception ", "pre_mask_code": "package org.glowroot.agent.util;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class Reflections {\n\n private static final Logger logger = LoggerFactory.getLogger(Reflections.class);\n\n private Reflections() {\n }\n\n public static Method getAnyMethod(Class clazz, String name, Class... parameterTypes) throws Exception {\n try {\n Method method = clazz.getMethod(name, parameterTypes);\n // even though getMethod() above only returns public method, still need to\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n }\n }\n\n public static Field getAnyField(Class clazz, String fieldName) throws Exception {\n try {\n Field field = clazz.getField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredField(clazz, fieldName);\n }\n }\n\n ", "post_mask_code": "{\n try {\n Method method = clazz.getDeclaredMethod(name, parameterTypes);\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw new NoSuchMethodException();\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n }\n }\n\n private static Field getAnyDeclaredField(Class clazz, String fieldName) throws Exception {\n try {\n Field field = clazz.getDeclaredField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredField(superClass, fieldName);\n }\n }\n}\n"} {"task_id": "Java_1521", "language": "Java", "task_type": "method_body", "source_file": "java/github/glowroot/glowroot/agent/core/src/main/java/org/glowroot/agent/util/Reflections.java", "mask_start_position": 2936, "mask_end_position": 3422, "canonical_solution": "{\n try {\n Field field = clazz.getDeclaredField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredField(superClass, fieldName);\n }\n }", "pre_mask_code": "package org.glowroot.agent.util;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class Reflections {\n\n private static final Logger logger = LoggerFactory.getLogger(Reflections.class);\n\n private Reflections() {\n }\n\n public static Method getAnyMethod(Class clazz, String name, Class... parameterTypes) throws Exception {\n try {\n Method method = clazz.getMethod(name, parameterTypes);\n // even though getMethod() above only returns public method, still need to\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n }\n }\n\n public static Field getAnyField(Class clazz, String fieldName) throws Exception {\n try {\n Field field = clazz.getField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredField(clazz, fieldName);\n }\n }\n\n private static Method getAnyDeclaredMethod(Class clazz, String name, Class... parameterTypes) throws Exception {\n try {\n Method method = clazz.getDeclaredMethod(name, parameterTypes);\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw new NoSuchMethodException();\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n }\n }\n\n private static Field getAnyDeclaredField(Class clazz, String fieldName) throws Exception ", "post_mask_code": "\n}\n"} {"task_id": "Java_1522", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/glowroot/glowroot/agent/core/src/main/java/org/glowroot/agent/util/Reflections.java", "mask_start_position": 1792, "mask_end_position": 1792, "canonical_solution": "", "pre_mask_code": "package org.glowroot.agent.util;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class Reflections {\n\n private static final Logger logger = LoggerFactory.getLogger(Reflections.class);\n\n private Reflections() {\n }\n\n public static Method getAnyMethod(Class clazz, String name, Class... parameterTypes) throws Exception {\n try {\n Method method = clazz.getMethod(name, parameterTypes);\n // even though getMethod() above only returns public method, still need to\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n }\n }\n\n public static Field getAnyField(Class clazz, String fieldName) throws Exception {\n try {\n Field field = clazz.getField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredField(clazz, fieldName);\n }\n }\n\n private static Method getAnyDeclaredMethod(Class clazz, String name, Class... parameterTypes) throws Exception {", "post_mask_code": "\n try {\n Method method = clazz.getDeclaredMethod(name, parameterTypes);\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw new NoSuchMethodException();\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n }\n }\n\n private static Field getAnyDeclaredField(Class clazz, String fieldName) throws Exception {\n try {\n Field field = clazz.getDeclaredField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredField(superClass, fieldName);\n }\n }\n}\n"} {"task_id": "Java_1523", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/glowroot/glowroot/agent/core/src/main/java/org/glowroot/agent/util/Reflections.java", "mask_start_position": 1801, "mask_end_position": 2832, "canonical_solution": "try {\n Method method = clazz.getDeclaredMethod(name, parameterTypes);\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw new NoSuchMethodException();\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n }", "pre_mask_code": "package org.glowroot.agent.util;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class Reflections {\n\n private static final Logger logger = LoggerFactory.getLogger(Reflections.class);\n\n private Reflections() {\n }\n\n public static Method getAnyMethod(Class clazz, String name, Class... parameterTypes) throws Exception {\n try {\n Method method = clazz.getMethod(name, parameterTypes);\n // even though getMethod() above only returns public method, still need to\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n }\n }\n\n public static Field getAnyField(Class clazz, String fieldName) throws Exception {\n try {\n Field field = clazz.getField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredField(clazz, fieldName);\n }\n }\n\n private static Method getAnyDeclaredMethod(Class clazz, String name, Class... parameterTypes) throws Exception {\n ", "post_mask_code": "\n }\n\n private static Field getAnyDeclaredField(Class clazz, String fieldName) throws Exception {\n try {\n Field field = clazz.getDeclaredField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredField(superClass, fieldName);\n }\n }\n}\n"} {"task_id": "Java_1524", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/glowroot/glowroot/agent/core/src/main/java/org/glowroot/agent/util/Reflections.java", "mask_start_position": 2837, "mask_end_position": 2838, "canonical_solution": "}", "pre_mask_code": "package org.glowroot.agent.util;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class Reflections {\n\n private static final Logger logger = LoggerFactory.getLogger(Reflections.class);\n\n private Reflections() {\n }\n\n public static Method getAnyMethod(Class clazz, String name, Class... parameterTypes) throws Exception {\n try {\n Method method = clazz.getMethod(name, parameterTypes);\n // even though getMethod() above only returns public method, still need to\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n }\n }\n\n public static Field getAnyField(Class clazz, String fieldName) throws Exception {\n try {\n Field field = clazz.getField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredField(clazz, fieldName);\n }\n }\n\n private static Method getAnyDeclaredMethod(Class clazz, String name, Class... parameterTypes) throws Exception {\n try {\n Method method = clazz.getDeclaredMethod(name, parameterTypes);\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw new NoSuchMethodException();\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n }\n ", "post_mask_code": "\n\n private static Field getAnyDeclaredField(Class clazz, String fieldName) throws Exception {\n try {\n Field field = clazz.getDeclaredField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredField(superClass, fieldName);\n }\n }\n}\n"} {"task_id": "Java_1525", "language": "Java", "task_type": "if_statement", "source_file": "java/github/glowroot/glowroot/agent/core/src/main/java/org/glowroot/agent/util/Reflections.java", "mask_start_position": 2151, "mask_end_position": 2215, "canonical_solution": "if (superClass == null) {\n throw e;\n }", "pre_mask_code": "package org.glowroot.agent.util;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class Reflections {\n\n private static final Logger logger = LoggerFactory.getLogger(Reflections.class);\n\n private Reflections() {\n }\n\n public static Method getAnyMethod(Class clazz, String name, Class... parameterTypes) throws Exception {\n try {\n Method method = clazz.getMethod(name, parameterTypes);\n // even though getMethod() above only returns public method, still need to\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n }\n }\n\n public static Field getAnyField(Class clazz, String fieldName) throws Exception {\n try {\n Field field = clazz.getField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredField(clazz, fieldName);\n }\n }\n\n private static Method getAnyDeclaredMethod(Class clazz, String name, Class... parameterTypes) throws Exception {\n try {\n Method method = clazz.getDeclaredMethod(name, parameterTypes);\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n ", "post_mask_code": "\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw new NoSuchMethodException();\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n }\n }\n\n private static Field getAnyDeclaredField(Class clazz, String fieldName) throws Exception {\n try {\n Field field = clazz.getDeclaredField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredField(superClass, fieldName);\n }\n }\n}\n"} {"task_id": "Java_1526", "language": "Java", "task_type": "try_statement", "source_file": "java/github/glowroot/glowroot/agent/core/src/main/java/org/glowroot/agent/util/Reflections.java", "mask_start_position": 2946, "mask_end_position": 3416, "canonical_solution": "try {\n Field field = clazz.getDeclaredField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredField(superClass, fieldName);\n }", "pre_mask_code": "package org.glowroot.agent.util;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class Reflections {\n\n private static final Logger logger = LoggerFactory.getLogger(Reflections.class);\n\n private Reflections() {\n }\n\n public static Method getAnyMethod(Class clazz, String name, Class... parameterTypes) throws Exception {\n try {\n Method method = clazz.getMethod(name, parameterTypes);\n // even though getMethod() above only returns public method, still need to\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredMethod(clazz, name, parameterTypes);\n }\n }\n\n public static Field getAnyField(Class clazz, String fieldName) throws Exception {\n try {\n Field field = clazz.getField(fieldName);\n field.setAccessible(true);\n return field;\n } catch (NoSuchFieldException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n return getAnyDeclaredField(clazz, fieldName);\n }\n }\n\n private static Method getAnyDeclaredMethod(Class clazz, String name, Class... parameterTypes) throws Exception {\n try {\n Method method = clazz.getDeclaredMethod(name, parameterTypes);\n method.setAccessible(true);\n return method;\n } catch (NoSuchMethodException e) {\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw e;\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n } catch (NoClassDefFoundError e) {\n // NoClassDefFoundError is thrown if any method signature in clazz references a missing\n // seems best to treat same as NoSuchMethodException\n // log exception at trace level\n logger.trace(e.getMessage(), e);\n Class superClass = clazz.getSuperclass();\n if (superClass == null) {\n throw new NoSuchMethodException();\n }\n return getAnyDeclaredMethod(superClass, name, parameterTypes);\n }\n }\n\n private static Field getAnyDeclaredField(Class clazz, String fieldName) throws Exception {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1527", "language": "Java", "task_type": "method_signature", "source_file": "java/github/spring-projects/spring-webflow/spring-faces/src/main/java/org/springframework/faces/webflow/JsfUtils.java", "mask_start_position": 2386, "mask_end_position": 2436, "canonical_solution": "public static boolean isAsynchronousFlowRequest() ", "pre_mask_code": "package org.springframework.faces.webflow;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.faces.FactoryFinder;\nimport javax.faces.application.ApplicationFactory;\nimport javax.faces.component.visit.VisitContextFactory;\nimport javax.faces.context.ExceptionHandlerFactory;\nimport javax.faces.context.ExternalContextFactory;\nimport javax.faces.context.FacesContext;\nimport javax.faces.context.FacesContextFactory;\nimport javax.faces.context.PartialViewContextFactory;\nimport javax.faces.event.PhaseEvent;\nimport javax.faces.event.PhaseId;\nimport javax.faces.event.PhaseListener;\nimport javax.faces.lifecycle.Lifecycle;\nimport javax.faces.lifecycle.LifecycleFactory;\nimport javax.faces.render.RenderKitFactory;\nimport javax.faces.view.ViewDeclarationLanguageFactory;\nimport javax.faces.view.facelets.FaceletCacheFactory;\nimport javax.faces.view.facelets.TagHandlerDelegateFactory;\nimport org.springframework.util.Assert;\nimport org.springframework.webflow.execution.RequestContextHolder;\n\n/**\n * Common support for the JSF integration with Spring Web Flow.\n *\n * @author Jeremy Grelle\n * @author Phillip Webb\n */\npublic class JsfUtils {\n\n public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.afterPhase(afterPhaseEvent);\n }\n }\n }\n\n public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.beforePhase(beforePhaseEvent);\n }\n }\n }\n\n public static boolean isFlowRequest() {\n if (RequestContextHolder.getRequestContext() != null) {\n return true;\n } else {\n return false;\n }\n }\n\n ", "post_mask_code": "{\n if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Find a factory of the specified class using JSFs {@link FactoryFinder} class.\n * @param factoryClass the factory class to find\n * @return the factory instance\n */\n @SuppressWarnings(\"unchecked\")\n public static T findFactory(Class factoryClass) {\n Assert.notNull(factoryClass, \"FactoryClass must not be null\");\n String name = FACTORY_NAMES.get(factoryClass);\n Assert.state(name != null, \"Unknown factory class \" + factoryClass.getName());\n return (T) FactoryFinder.getFactory(name);\n }\n\n private static final Map, String> FACTORY_NAMES;\n\n static {\n FACTORY_NAMES = new HashMap<>();\n FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);\n FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);\n FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);\n FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);\n FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);\n FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);\n FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);\n FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);\n FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);\n FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);\n FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);\n }\n}\n"} {"task_id": "Java_1528", "language": "Java", "task_type": "method_body", "source_file": "java/github/spring-projects/spring-webflow/spring-faces/src/main/java/org/springframework/faces/webflow/JsfUtils.java", "mask_start_position": 2231, "mask_end_position": 2380, "canonical_solution": "{\n if (RequestContextHolder.getRequestContext() != null) {\n return true;\n } else {\n return false;\n }\n }", "pre_mask_code": "package org.springframework.faces.webflow;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.faces.FactoryFinder;\nimport javax.faces.application.ApplicationFactory;\nimport javax.faces.component.visit.VisitContextFactory;\nimport javax.faces.context.ExceptionHandlerFactory;\nimport javax.faces.context.ExternalContextFactory;\nimport javax.faces.context.FacesContext;\nimport javax.faces.context.FacesContextFactory;\nimport javax.faces.context.PartialViewContextFactory;\nimport javax.faces.event.PhaseEvent;\nimport javax.faces.event.PhaseId;\nimport javax.faces.event.PhaseListener;\nimport javax.faces.lifecycle.Lifecycle;\nimport javax.faces.lifecycle.LifecycleFactory;\nimport javax.faces.render.RenderKitFactory;\nimport javax.faces.view.ViewDeclarationLanguageFactory;\nimport javax.faces.view.facelets.FaceletCacheFactory;\nimport javax.faces.view.facelets.TagHandlerDelegateFactory;\nimport org.springframework.util.Assert;\nimport org.springframework.webflow.execution.RequestContextHolder;\n\n/**\n * Common support for the JSF integration with Spring Web Flow.\n *\n * @author Jeremy Grelle\n * @author Phillip Webb\n */\npublic class JsfUtils {\n\n public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.afterPhase(afterPhaseEvent);\n }\n }\n }\n\n public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.beforePhase(beforePhaseEvent);\n }\n }\n }\n\n public static boolean isFlowRequest() ", "post_mask_code": "\n\n public static boolean isAsynchronousFlowRequest() {\n if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Find a factory of the specified class using JSFs {@link FactoryFinder} class.\n * @param factoryClass the factory class to find\n * @return the factory instance\n */\n @SuppressWarnings(\"unchecked\")\n public static T findFactory(Class factoryClass) {\n Assert.notNull(factoryClass, \"FactoryClass must not be null\");\n String name = FACTORY_NAMES.get(factoryClass);\n Assert.state(name != null, \"Unknown factory class \" + factoryClass.getName());\n return (T) FactoryFinder.getFactory(name);\n }\n\n private static final Map, String> FACTORY_NAMES;\n\n static {\n FACTORY_NAMES = new HashMap<>();\n FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);\n FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);\n FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);\n FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);\n FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);\n FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);\n FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);\n FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);\n FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);\n FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);\n FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);\n }\n}\n"} {"task_id": "Java_1529", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/spring-projects/spring-webflow/spring-faces/src/main/java/org/springframework/faces/webflow/JsfUtils.java", "mask_start_position": 1776, "mask_end_position": 1859, "canonical_solution": "\n PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);", "pre_mask_code": "package org.springframework.faces.webflow;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.faces.FactoryFinder;\nimport javax.faces.application.ApplicationFactory;\nimport javax.faces.component.visit.VisitContextFactory;\nimport javax.faces.context.ExceptionHandlerFactory;\nimport javax.faces.context.ExternalContextFactory;\nimport javax.faces.context.FacesContext;\nimport javax.faces.context.FacesContextFactory;\nimport javax.faces.context.PartialViewContextFactory;\nimport javax.faces.event.PhaseEvent;\nimport javax.faces.event.PhaseId;\nimport javax.faces.event.PhaseListener;\nimport javax.faces.lifecycle.Lifecycle;\nimport javax.faces.lifecycle.LifecycleFactory;\nimport javax.faces.render.RenderKitFactory;\nimport javax.faces.view.ViewDeclarationLanguageFactory;\nimport javax.faces.view.facelets.FaceletCacheFactory;\nimport javax.faces.view.facelets.TagHandlerDelegateFactory;\nimport org.springframework.util.Assert;\nimport org.springframework.webflow.execution.RequestContextHolder;\n\n/**\n * Common support for the JSF integration with Spring Web Flow.\n *\n * @author Jeremy Grelle\n * @author Phillip Webb\n */\npublic class JsfUtils {\n\n public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.afterPhase(afterPhaseEvent);\n }\n }\n }\n\n public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {", "post_mask_code": "\n for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.beforePhase(beforePhaseEvent);\n }\n }\n }\n\n public static boolean isFlowRequest() {\n if (RequestContextHolder.getRequestContext() != null) {\n return true;\n } else {\n return false;\n }\n }\n\n public static boolean isAsynchronousFlowRequest() {\n if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Find a factory of the specified class using JSFs {@link FactoryFinder} class.\n * @param factoryClass the factory class to find\n * @return the factory instance\n */\n @SuppressWarnings(\"unchecked\")\n public static T findFactory(Class factoryClass) {\n Assert.notNull(factoryClass, \"FactoryClass must not be null\");\n String name = FACTORY_NAMES.get(factoryClass);\n Assert.state(name != null, \"Unknown factory class \" + factoryClass.getName());\n return (T) FactoryFinder.getFactory(name);\n }\n\n private static final Map, String> FACTORY_NAMES;\n\n static {\n FACTORY_NAMES = new HashMap<>();\n FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);\n FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);\n FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);\n FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);\n FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);\n FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);\n FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);\n FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);\n FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);\n FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);\n FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);\n }\n}\n"} {"task_id": "Java_1530", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/spring-projects/spring-webflow/spring-faces/src/main/java/org/springframework/faces/webflow/JsfUtils.java", "mask_start_position": 1868, "mask_end_position": 2181, "canonical_solution": "for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.beforePhase(beforePhaseEvent);\n }\n }", "pre_mask_code": "package org.springframework.faces.webflow;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.faces.FactoryFinder;\nimport javax.faces.application.ApplicationFactory;\nimport javax.faces.component.visit.VisitContextFactory;\nimport javax.faces.context.ExceptionHandlerFactory;\nimport javax.faces.context.ExternalContextFactory;\nimport javax.faces.context.FacesContext;\nimport javax.faces.context.FacesContextFactory;\nimport javax.faces.context.PartialViewContextFactory;\nimport javax.faces.event.PhaseEvent;\nimport javax.faces.event.PhaseId;\nimport javax.faces.event.PhaseListener;\nimport javax.faces.lifecycle.Lifecycle;\nimport javax.faces.lifecycle.LifecycleFactory;\nimport javax.faces.render.RenderKitFactory;\nimport javax.faces.view.ViewDeclarationLanguageFactory;\nimport javax.faces.view.facelets.FaceletCacheFactory;\nimport javax.faces.view.facelets.TagHandlerDelegateFactory;\nimport org.springframework.util.Assert;\nimport org.springframework.webflow.execution.RequestContextHolder;\n\n/**\n * Common support for the JSF integration with Spring Web Flow.\n *\n * @author Jeremy Grelle\n * @author Phillip Webb\n */\npublic class JsfUtils {\n\n public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.afterPhase(afterPhaseEvent);\n }\n }\n }\n\n public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n ", "post_mask_code": "\n }\n\n public static boolean isFlowRequest() {\n if (RequestContextHolder.getRequestContext() != null) {\n return true;\n } else {\n return false;\n }\n }\n\n public static boolean isAsynchronousFlowRequest() {\n if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Find a factory of the specified class using JSFs {@link FactoryFinder} class.\n * @param factoryClass the factory class to find\n * @return the factory instance\n */\n @SuppressWarnings(\"unchecked\")\n public static T findFactory(Class factoryClass) {\n Assert.notNull(factoryClass, \"FactoryClass must not be null\");\n String name = FACTORY_NAMES.get(factoryClass);\n Assert.state(name != null, \"Unknown factory class \" + factoryClass.getName());\n return (T) FactoryFinder.getFactory(name);\n }\n\n private static final Map, String> FACTORY_NAMES;\n\n static {\n FACTORY_NAMES = new HashMap<>();\n FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);\n FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);\n FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);\n FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);\n FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);\n FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);\n FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);\n FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);\n FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);\n FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);\n FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);\n }\n}\n"} {"task_id": "Java_1531", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/spring-projects/spring-webflow/spring-faces/src/main/java/org/springframework/faces/webflow/JsfUtils.java", "mask_start_position": 2186, "mask_end_position": 2187, "canonical_solution": "}", "pre_mask_code": "package org.springframework.faces.webflow;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.faces.FactoryFinder;\nimport javax.faces.application.ApplicationFactory;\nimport javax.faces.component.visit.VisitContextFactory;\nimport javax.faces.context.ExceptionHandlerFactory;\nimport javax.faces.context.ExternalContextFactory;\nimport javax.faces.context.FacesContext;\nimport javax.faces.context.FacesContextFactory;\nimport javax.faces.context.PartialViewContextFactory;\nimport javax.faces.event.PhaseEvent;\nimport javax.faces.event.PhaseId;\nimport javax.faces.event.PhaseListener;\nimport javax.faces.lifecycle.Lifecycle;\nimport javax.faces.lifecycle.LifecycleFactory;\nimport javax.faces.render.RenderKitFactory;\nimport javax.faces.view.ViewDeclarationLanguageFactory;\nimport javax.faces.view.facelets.FaceletCacheFactory;\nimport javax.faces.view.facelets.TagHandlerDelegateFactory;\nimport org.springframework.util.Assert;\nimport org.springframework.webflow.execution.RequestContextHolder;\n\n/**\n * Common support for the JSF integration with Spring Web Flow.\n *\n * @author Jeremy Grelle\n * @author Phillip Webb\n */\npublic class JsfUtils {\n\n public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.afterPhase(afterPhaseEvent);\n }\n }\n }\n\n public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.beforePhase(beforePhaseEvent);\n }\n }\n ", "post_mask_code": "\n\n public static boolean isFlowRequest() {\n if (RequestContextHolder.getRequestContext() != null) {\n return true;\n } else {\n return false;\n }\n }\n\n public static boolean isAsynchronousFlowRequest() {\n if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Find a factory of the specified class using JSFs {@link FactoryFinder} class.\n * @param factoryClass the factory class to find\n * @return the factory instance\n */\n @SuppressWarnings(\"unchecked\")\n public static T findFactory(Class factoryClass) {\n Assert.notNull(factoryClass, \"FactoryClass must not be null\");\n String name = FACTORY_NAMES.get(factoryClass);\n Assert.state(name != null, \"Unknown factory class \" + factoryClass.getName());\n return (T) FactoryFinder.getFactory(name);\n }\n\n private static final Map, String> FACTORY_NAMES;\n\n static {\n FACTORY_NAMES = new HashMap<>();\n FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);\n FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);\n FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);\n FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);\n FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);\n FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);\n FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);\n FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);\n FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);\n FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);\n FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);\n }\n}\n"} {"task_id": "Java_1532", "language": "Java", "task_type": "single_line", "source_file": "java/github/spring-projects/spring-webflow/spring-faces/src/main/java/org/springframework/faces/webflow/JsfUtils.java", "mask_start_position": 1818, "mask_end_position": 1859, "canonical_solution": " PhaseEvent(context, phaseId, lifecycle);", "pre_mask_code": "package org.springframework.faces.webflow;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.faces.FactoryFinder;\nimport javax.faces.application.ApplicationFactory;\nimport javax.faces.component.visit.VisitContextFactory;\nimport javax.faces.context.ExceptionHandlerFactory;\nimport javax.faces.context.ExternalContextFactory;\nimport javax.faces.context.FacesContext;\nimport javax.faces.context.FacesContextFactory;\nimport javax.faces.context.PartialViewContextFactory;\nimport javax.faces.event.PhaseEvent;\nimport javax.faces.event.PhaseId;\nimport javax.faces.event.PhaseListener;\nimport javax.faces.lifecycle.Lifecycle;\nimport javax.faces.lifecycle.LifecycleFactory;\nimport javax.faces.render.RenderKitFactory;\nimport javax.faces.view.ViewDeclarationLanguageFactory;\nimport javax.faces.view.facelets.FaceletCacheFactory;\nimport javax.faces.view.facelets.TagHandlerDelegateFactory;\nimport org.springframework.util.Assert;\nimport org.springframework.webflow.execution.RequestContextHolder;\n\n/**\n * Common support for the JSF integration with Spring Web Flow.\n *\n * @author Jeremy Grelle\n * @author Phillip Webb\n */\npublic class JsfUtils {\n\n public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.afterPhase(afterPhaseEvent);\n }\n }\n }\n\n public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent beforePhaseEvent = new", "post_mask_code": "\n for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.beforePhase(beforePhaseEvent);\n }\n }\n }\n\n public static boolean isFlowRequest() {\n if (RequestContextHolder.getRequestContext() != null) {\n return true;\n } else {\n return false;\n }\n }\n\n public static boolean isAsynchronousFlowRequest() {\n if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Find a factory of the specified class using JSFs {@link FactoryFinder} class.\n * @param factoryClass the factory class to find\n * @return the factory instance\n */\n @SuppressWarnings(\"unchecked\")\n public static T findFactory(Class factoryClass) {\n Assert.notNull(factoryClass, \"FactoryClass must not be null\");\n String name = FACTORY_NAMES.get(factoryClass);\n Assert.state(name != null, \"Unknown factory class \" + factoryClass.getName());\n return (T) FactoryFinder.getFactory(name);\n }\n\n private static final Map, String> FACTORY_NAMES;\n\n static {\n FACTORY_NAMES = new HashMap<>();\n FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);\n FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);\n FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);\n FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);\n FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);\n FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);\n FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);\n FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);\n FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);\n FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);\n FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);\n }\n}\n"} {"task_id": "Java_1533", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/spring-projects/spring-webflow/spring-faces/src/main/java/org/springframework/faces/webflow/JsfUtils.java", "mask_start_position": 2829, "mask_end_position": 3190, "canonical_solution": "@SuppressWarnings(\"unchecked\")\n public static T findFactory(Class factoryClass) {\n Assert.notNull(factoryClass, \"FactoryClass must not be null\");\n String name = FACTORY_NAMES.get(factoryClass);\n Assert.state(name != null, \"Unknown factory class \" + factoryClass.getName());\n return (T) FactoryFinder.getFactory(name);\n }", "pre_mask_code": "package org.springframework.faces.webflow;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.faces.FactoryFinder;\nimport javax.faces.application.ApplicationFactory;\nimport javax.faces.component.visit.VisitContextFactory;\nimport javax.faces.context.ExceptionHandlerFactory;\nimport javax.faces.context.ExternalContextFactory;\nimport javax.faces.context.FacesContext;\nimport javax.faces.context.FacesContextFactory;\nimport javax.faces.context.PartialViewContextFactory;\nimport javax.faces.event.PhaseEvent;\nimport javax.faces.event.PhaseId;\nimport javax.faces.event.PhaseListener;\nimport javax.faces.lifecycle.Lifecycle;\nimport javax.faces.lifecycle.LifecycleFactory;\nimport javax.faces.render.RenderKitFactory;\nimport javax.faces.view.ViewDeclarationLanguageFactory;\nimport javax.faces.view.facelets.FaceletCacheFactory;\nimport javax.faces.view.facelets.TagHandlerDelegateFactory;\nimport org.springframework.util.Assert;\nimport org.springframework.webflow.execution.RequestContextHolder;\n\n/**\n * Common support for the JSF integration with Spring Web Flow.\n *\n * @author Jeremy Grelle\n * @author Phillip Webb\n */\npublic class JsfUtils {\n\n public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.afterPhase(afterPhaseEvent);\n }\n }\n }\n\n public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.beforePhase(beforePhaseEvent);\n }\n }\n }\n\n public static boolean isFlowRequest() {\n if (RequestContextHolder.getRequestContext() != null) {\n return true;\n } else {\n return false;\n }\n }\n\n public static boolean isAsynchronousFlowRequest() {\n if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Find a factory of the specified class using JSFs {@link FactoryFinder} class.\n * @param factoryClass the factory class to find\n * @return the factory instance\n */\n ", "post_mask_code": "\n\n private static final Map, String> FACTORY_NAMES;\n\n static {\n FACTORY_NAMES = new HashMap<>();\n FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);\n FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);\n FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);\n FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);\n FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);\n FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);\n FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);\n FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);\n FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);\n FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);\n FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);\n }\n}\n"} {"task_id": "Java_1534", "language": "Java", "task_type": "if_statement", "source_file": "java/github/spring-projects/spring-webflow/spring-faces/src/main/java/org/springframework/faces/webflow/JsfUtils.java", "mask_start_position": 1499, "mask_end_position": 1652, "canonical_solution": "if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.afterPhase(afterPhaseEvent);\n }", "pre_mask_code": "package org.springframework.faces.webflow;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.faces.FactoryFinder;\nimport javax.faces.application.ApplicationFactory;\nimport javax.faces.component.visit.VisitContextFactory;\nimport javax.faces.context.ExceptionHandlerFactory;\nimport javax.faces.context.ExternalContextFactory;\nimport javax.faces.context.FacesContext;\nimport javax.faces.context.FacesContextFactory;\nimport javax.faces.context.PartialViewContextFactory;\nimport javax.faces.event.PhaseEvent;\nimport javax.faces.event.PhaseId;\nimport javax.faces.event.PhaseListener;\nimport javax.faces.lifecycle.Lifecycle;\nimport javax.faces.lifecycle.LifecycleFactory;\nimport javax.faces.render.RenderKitFactory;\nimport javax.faces.view.ViewDeclarationLanguageFactory;\nimport javax.faces.view.facelets.FaceletCacheFactory;\nimport javax.faces.view.facelets.TagHandlerDelegateFactory;\nimport org.springframework.util.Assert;\nimport org.springframework.webflow.execution.RequestContextHolder;\n\n/**\n * Common support for the JSF integration with Spring Web Flow.\n *\n * @author Jeremy Grelle\n * @author Phillip Webb\n */\npublic class JsfUtils {\n\n public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n ", "post_mask_code": "\n }\n }\n\n public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.beforePhase(beforePhaseEvent);\n }\n }\n }\n\n public static boolean isFlowRequest() {\n if (RequestContextHolder.getRequestContext() != null) {\n return true;\n } else {\n return false;\n }\n }\n\n public static boolean isAsynchronousFlowRequest() {\n if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Find a factory of the specified class using JSFs {@link FactoryFinder} class.\n * @param factoryClass the factory class to find\n * @return the factory instance\n */\n @SuppressWarnings(\"unchecked\")\n public static T findFactory(Class factoryClass) {\n Assert.notNull(factoryClass, \"FactoryClass must not be null\");\n String name = FACTORY_NAMES.get(factoryClass);\n Assert.state(name != null, \"Unknown factory class \" + factoryClass.getName());\n return (T) FactoryFinder.getFactory(name);\n }\n\n private static final Map, String> FACTORY_NAMES;\n\n static {\n FACTORY_NAMES = new HashMap<>();\n FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);\n FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);\n FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);\n FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);\n FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);\n FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);\n FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);\n FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);\n FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);\n FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);\n FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);\n }\n}\n"} {"task_id": "Java_1535", "language": "Java", "task_type": "for_statement", "source_file": "java/github/spring-projects/spring-webflow/spring-faces/src/main/java/org/springframework/faces/webflow/JsfUtils.java", "mask_start_position": 1868, "mask_end_position": 2181, "canonical_solution": "for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.beforePhase(beforePhaseEvent);\n }\n }", "pre_mask_code": "package org.springframework.faces.webflow;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.faces.FactoryFinder;\nimport javax.faces.application.ApplicationFactory;\nimport javax.faces.component.visit.VisitContextFactory;\nimport javax.faces.context.ExceptionHandlerFactory;\nimport javax.faces.context.ExternalContextFactory;\nimport javax.faces.context.FacesContext;\nimport javax.faces.context.FacesContextFactory;\nimport javax.faces.context.PartialViewContextFactory;\nimport javax.faces.event.PhaseEvent;\nimport javax.faces.event.PhaseId;\nimport javax.faces.event.PhaseListener;\nimport javax.faces.lifecycle.Lifecycle;\nimport javax.faces.lifecycle.LifecycleFactory;\nimport javax.faces.render.RenderKitFactory;\nimport javax.faces.view.ViewDeclarationLanguageFactory;\nimport javax.faces.view.facelets.FaceletCacheFactory;\nimport javax.faces.view.facelets.TagHandlerDelegateFactory;\nimport org.springframework.util.Assert;\nimport org.springframework.webflow.execution.RequestContextHolder;\n\n/**\n * Common support for the JSF integration with Spring Web Flow.\n *\n * @author Jeremy Grelle\n * @author Phillip Webb\n */\npublic class JsfUtils {\n\n public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {\n PhaseListener listener = lifecycle.getPhaseListeners()[i];\n if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {\n listener.afterPhase(afterPhaseEvent);\n }\n }\n }\n\n public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {\n PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);\n ", "post_mask_code": "\n }\n\n public static boolean isFlowRequest() {\n if (RequestContextHolder.getRequestContext() != null) {\n return true;\n } else {\n return false;\n }\n }\n\n public static boolean isAsynchronousFlowRequest() {\n if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Find a factory of the specified class using JSFs {@link FactoryFinder} class.\n * @param factoryClass the factory class to find\n * @return the factory instance\n */\n @SuppressWarnings(\"unchecked\")\n public static T findFactory(Class factoryClass) {\n Assert.notNull(factoryClass, \"FactoryClass must not be null\");\n String name = FACTORY_NAMES.get(factoryClass);\n Assert.state(name != null, \"Unknown factory class \" + factoryClass.getName());\n return (T) FactoryFinder.getFactory(name);\n }\n\n private static final Map, String> FACTORY_NAMES;\n\n static {\n FACTORY_NAMES = new HashMap<>();\n FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);\n FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);\n FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);\n FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);\n FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);\n FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);\n FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);\n FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);\n FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);\n FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);\n FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);\n }\n}\n"} {"task_id": "Java_1536", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cping/LGame/Java/old/OpenGL-1.0(old_ver)/Loon-backend-JavaSE/src/loon/action/map/heuristics/DiagonalShort.java", "mask_start_position": 264, "mask_end_position": 326, "canonical_solution": "public float getScore(float sx, float sy, float tx, float ty) ", "pre_mask_code": "/**\n * @project loon\n * @author cping\n * @email:example@nnthink.com\n * @version 0.3.3\n */\npackage loon.action.map.heuristics;\n\nimport loon.action.map.AStarFindHeuristic;\nimport loon.utils.MathUtils;\n\npublic class DiagonalShort implements AStarFindHeuristic {\n\n ", "post_mask_code": "{\n float diagonal = MathUtils.min(MathUtils.abs(sx - tx), MathUtils.abs(sy - ty));\n float straight = (MathUtils.abs(sx - tx) + MathUtils.abs(sy - ty));\n return 2 * diagonal + (straight - 2 * diagonal);\n }\n\n public int getType() {\n return DIAGONAL_SHORT;\n }\n}\n"} {"task_id": "Java_1537", "language": "Java", "task_type": "method_body", "source_file": "java/github/cping/LGame/Java/old/OpenGL-1.0(old_ver)/Loon-backend-JavaSE/src/loon/action/map/heuristics/DiagonalShort.java", "mask_start_position": 581, "mask_end_position": 619, "canonical_solution": "{\n return DIAGONAL_SHORT;\n }", "pre_mask_code": "/**\n * @project loon\n * @author cping\n * @email:example@nnthink.com\n * @version 0.3.3\n */\npackage loon.action.map.heuristics;\n\nimport loon.action.map.AStarFindHeuristic;\nimport loon.utils.MathUtils;\n\npublic class DiagonalShort implements AStarFindHeuristic {\n\n public float getScore(float sx, float sy, float tx, float ty) {\n float diagonal = MathUtils.min(MathUtils.abs(sx - tx), MathUtils.abs(sy - ty));\n float straight = (MathUtils.abs(sx - tx) + MathUtils.abs(sy - ty));\n return 2 * diagonal + (straight - 2 * diagonal);\n }\n\n public int getType() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1538", "language": "Java", "task_type": "single_line", "source_file": "java/github/cping/LGame/Java/old/OpenGL-1.0(old_ver)/Loon-backend-JavaSE/src/loon/action/map/heuristics/DiagonalShort.java", "mask_start_position": 452, "mask_end_position": 491, "canonical_solution": "abs(sx - tx) + MathUtils.abs(sy - ty));", "pre_mask_code": "/**\n * @project loon\n * @author cping\n * @email:example@nnthink.com\n * @version 0.3.3\n */\npackage loon.action.map.heuristics;\n\nimport loon.action.map.AStarFindHeuristic;\nimport loon.utils.MathUtils;\n\npublic class DiagonalShort implements AStarFindHeuristic {\n\n public float getScore(float sx, float sy, float tx, float ty) {\n float diagonal = MathUtils.min(MathUtils.abs(sx - tx), MathUtils.abs(sy - ty));\n float straight = (MathUtils.", "post_mask_code": "\n return 2 * diagonal + (straight - 2 * diagonal);\n }\n\n public int getType() {\n return DIAGONAL_SHORT;\n }\n}\n"} {"task_id": "Java_1539", "language": "Java", "task_type": "method_signature", "source_file": "java/github/BotLibre/BotLibre/sdk/android/BotLibre/app/src/main/java/org/botlibre/sdk/config/AvatarConfig.java", "mask_start_position": 249, "mask_end_position": 286, "canonical_solution": "public WebMediumConfig credentials() ", "pre_mask_code": "package org.botlibre.sdk.config;\n\nimport java.io.StringWriter;\nimport org.w3c.dom.Element;\n\n/**\n * DTO for XML avatar config.\n */\npublic class AvatarConfig extends WebMediumConfig {\n\n public String getType() {\n return \"avatar\";\n }\n\n ", "post_mask_code": "{\n AvatarConfig config = new AvatarConfig();\n config.id = this.id;\n return config;\n }\n\n public String toXML() {\n StringWriter writer = new StringWriter();\n writer.write(\"\");\n return writer.toString();\n }\n\n public void parseXML(Element element) {\n super.parseXML(element);\n }\n}\n"} {"task_id": "Java_1540", "language": "Java", "task_type": "method_body", "source_file": "java/github/BotLibre/BotLibre/sdk/android/BotLibre/app/src/main/java/org/botlibre/sdk/config/AvatarConfig.java", "mask_start_position": 652, "mask_end_position": 692, "canonical_solution": "{\n super.parseXML(element);\n }", "pre_mask_code": "package org.botlibre.sdk.config;\n\nimport java.io.StringWriter;\nimport org.w3c.dom.Element;\n\n/**\n * DTO for XML avatar config.\n */\npublic class AvatarConfig extends WebMediumConfig {\n\n public String getType() {\n return \"avatar\";\n }\n\n public WebMediumConfig credentials() {\n AvatarConfig config = new AvatarConfig();\n config.id = this.id;\n return config;\n }\n\n public String toXML() {\n StringWriter writer = new StringWriter();\n writer.write(\"\");\n return writer.toString();\n }\n\n public void parseXML(Element element) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1541", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/BotLibre/BotLibre/sdk/android/BotLibre/app/src/main/java/org/botlibre/sdk/config/AvatarConfig.java", "mask_start_position": 424, "mask_end_position": 507, "canonical_solution": "\n StringWriter writer = new StringWriter();\n writer.write(\"\");\n return writer.toString();\n }\n\n public void parseXML(Element element) {\n super.parseXML(element);\n }\n}\n"} {"task_id": "Java_1542", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/BotLibre/BotLibre/sdk/android/BotLibre/app/src/main/java/org/botlibre/sdk/config/AvatarConfig.java", "mask_start_position": 516, "mask_end_position": 568, "canonical_solution": "writeXML(writer);\n writer.write(\"\");", "pre_mask_code": "package org.botlibre.sdk.config;\n\nimport java.io.StringWriter;\nimport org.w3c.dom.Element;\n\n/**\n * DTO for XML avatar config.\n */\npublic class AvatarConfig extends WebMediumConfig {\n\n public String getType() {\n return \"avatar\";\n }\n\n public WebMediumConfig credentials() {\n AvatarConfig config = new AvatarConfig();\n config.id = this.id;\n return config;\n }\n\n public String toXML() {\n StringWriter writer = new StringWriter();\n writer.write(\"\");\n ", "post_mask_code": "\n\n public void parseXML(Element element) {\n super.parseXML(element);\n }\n}\n"} {"task_id": "Java_1544", "language": "Java", "task_type": "single_line", "source_file": "java/github/BotLibre/BotLibre/sdk/android/BotLibre/app/src/main/java/org/botlibre/sdk/config/AvatarConfig.java", "mask_start_position": 378, "mask_end_position": 389, "canonical_solution": "urn config;", "pre_mask_code": "package org.botlibre.sdk.config;\n\nimport java.io.StringWriter;\nimport org.w3c.dom.Element;\n\n/**\n * DTO for XML avatar config.\n */\npublic class AvatarConfig extends WebMediumConfig {\n\n public String getType() {\n return \"avatar\";\n }\n\n public WebMediumConfig credentials() {\n AvatarConfig config = new AvatarConfig();\n config.id = this.id;\n ret", "post_mask_code": "\n }\n\n public String toXML() {\n StringWriter writer = new StringWriter();\n writer.write(\"\");\n return writer.toString();\n }\n\n public void parseXML(Element element) {\n super.parseXML(element);\n }\n}\n"} {"task_id": "Java_1545", "language": "Java", "task_type": "method_signature", "source_file": "java/github/wuba/Oceanus/oceanus-all/oceanus-core/src/main/java/com/bj58/oceanus/core/timetracker/Tracker.java", "mask_start_position": 778, "mask_end_position": 843, "canonical_solution": "static synchronized void addTracker(TrackerHodler trackerHodler) ", "pre_mask_code": "/*\n * Copyright Beijing 58 Information Technology Co.,Ltd.\n *\n */\npackage com.bj58.oceanus.core.timetracker;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.bj58.oceanus.core.exception.ConfigurationException;\nimport com.bj58.oceanus.core.timetracker.handler.TrackResult;\nimport com.google.common.collect.Maps;\n\n/**\n * 耗时监控点以及处理器的持有者,也是监控器的基类\n * 子类实现 {@link #doTrack()} 方法并加入配置,即可实现自定义监控\n *\n * @author Service Platform Architecture Team (example@nnthink.com)\n */\npublic abstract class Tracker {\n\n private static final Map generalTrackerMap = Maps.newHashMap();\n\n private static final Map> tableTrackerMap = Maps.newHashMap();\n\n /**\n * 添加全局Tracker\n * @param trackerHodler\n */\n ", "post_mask_code": "{\n if (generalTrackerMap.containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] already exsit!\");\n generalTrackerMap.put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 为指定table添加Tracker\n * @param tableName\n * @param trackerHodler\n */\n static synchronized void addTracker(String tableName, TrackerHodler trackerHodler) {\n if (!tableTrackerMap.containsKey(tableName))\n tableTrackerMap.put(tableName, new HashMap());\n if (tableTrackerMap.get(tableName).containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] for table [\" + tableName + \"] already exsit!\");\n tableTrackerMap.get(tableName).put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 获取全局指定类型的 tracker\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTracker(TrackPoint trackPoint) {\n return generalTrackerMap.get(trackPoint);\n }\n\n /**\n * 获取指定表、指定类型的 tracker\n * @param tableName\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTableTracker(String tableName, TrackPoint trackPoint) {\n if (!tableTrackerMap.containsKey(tableName))\n return null;\n return tableTrackerMap.get(tableName).get(trackPoint);\n }\n\n /**\n * 当对应的 TrackPoint 执行时间大于 getThreshold() 时的回调方法\n * @param TrackResult\n * \t- tableName 对应的表\n * \t- sql 对应的sql\n * \t- costTime 执行耗时\n */\n public abstract void doTrack(TrackResult trackResult);\n}\n"} {"task_id": "Java_1546", "language": "Java", "task_type": "method_body", "source_file": "java/github/wuba/Oceanus/oceanus-all/oceanus-core/src/main/java/com/bj58/oceanus/core/timetracker/Tracker.java", "mask_start_position": 1908, "mask_end_position": 1965, "canonical_solution": "{\n return generalTrackerMap.get(trackPoint);\n }", "pre_mask_code": "/*\n * Copyright Beijing 58 Information Technology Co.,Ltd.\n *\n */\npackage com.bj58.oceanus.core.timetracker;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.bj58.oceanus.core.exception.ConfigurationException;\nimport com.bj58.oceanus.core.timetracker.handler.TrackResult;\nimport com.google.common.collect.Maps;\n\n/**\n * 耗时监控点以及处理器的持有者,也是监控器的基类\n * 子类实现 {@link #doTrack()} 方法并加入配置,即可实现自定义监控\n *\n * @author Service Platform Architecture Team (example@nnthink.com)\n */\npublic abstract class Tracker {\n\n private static final Map generalTrackerMap = Maps.newHashMap();\n\n private static final Map> tableTrackerMap = Maps.newHashMap();\n\n /**\n * 添加全局Tracker\n * @param trackerHodler\n */\n static synchronized void addTracker(TrackerHodler trackerHodler) {\n if (generalTrackerMap.containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] already exsit!\");\n generalTrackerMap.put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 为指定table添加Tracker\n * @param tableName\n * @param trackerHodler\n */\n static synchronized void addTracker(String tableName, TrackerHodler trackerHodler) {\n if (!tableTrackerMap.containsKey(tableName))\n tableTrackerMap.put(tableName, new HashMap());\n if (tableTrackerMap.get(tableName).containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] for table [\" + tableName + \"] already exsit!\");\n tableTrackerMap.get(tableName).put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 获取全局指定类型的 tracker\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTracker(TrackPoint trackPoint) ", "post_mask_code": "\n\n /**\n * 获取指定表、指定类型的 tracker\n * @param tableName\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTableTracker(String tableName, TrackPoint trackPoint) {\n if (!tableTrackerMap.containsKey(tableName))\n return null;\n return tableTrackerMap.get(tableName).get(trackPoint);\n }\n\n /**\n * 当对应的 TrackPoint 执行时间大于 getThreshold() 时的回调方法\n * @param TrackResult\n * \t- tableName 对应的表\n * \t- sql 对应的sql\n * \t- costTime 执行耗时\n */\n public abstract void doTrack(TrackResult trackResult);\n}\n"} {"task_id": "Java_1547", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/wuba/Oceanus/oceanus-all/oceanus-core/src/main/java/com/bj58/oceanus/core/timetracker/Tracker.java", "mask_start_position": 1299, "mask_end_position": 1438, "canonical_solution": "\n if (!tableTrackerMap.containsKey(tableName))\n tableTrackerMap.put(tableName, new HashMap());", "pre_mask_code": "/*\n * Copyright Beijing 58 Information Technology Co.,Ltd.\n *\n */\npackage com.bj58.oceanus.core.timetracker;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.bj58.oceanus.core.exception.ConfigurationException;\nimport com.bj58.oceanus.core.timetracker.handler.TrackResult;\nimport com.google.common.collect.Maps;\n\n/**\n * 耗时监控点以及处理器的持有者,也是监控器的基类\n * 子类实现 {@link #doTrack()} 方法并加入配置,即可实现自定义监控\n *\n * @author Service Platform Architecture Team (example@nnthink.com)\n */\npublic abstract class Tracker {\n\n private static final Map generalTrackerMap = Maps.newHashMap();\n\n private static final Map> tableTrackerMap = Maps.newHashMap();\n\n /**\n * 添加全局Tracker\n * @param trackerHodler\n */\n static synchronized void addTracker(TrackerHodler trackerHodler) {\n if (generalTrackerMap.containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] already exsit!\");\n generalTrackerMap.put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 为指定table添加Tracker\n * @param tableName\n * @param trackerHodler\n */\n static synchronized void addTracker(String tableName, TrackerHodler trackerHodler) {", "post_mask_code": "\n if (tableTrackerMap.get(tableName).containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] for table [\" + tableName + \"] already exsit!\");\n tableTrackerMap.get(tableName).put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 获取全局指定类型的 tracker\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTracker(TrackPoint trackPoint) {\n return generalTrackerMap.get(trackPoint);\n }\n\n /**\n * 获取指定表、指定类型的 tracker\n * @param tableName\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTableTracker(String tableName, TrackPoint trackPoint) {\n if (!tableTrackerMap.containsKey(tableName))\n return null;\n return tableTrackerMap.get(tableName).get(trackPoint);\n }\n\n /**\n * 当对应的 TrackPoint 执行时间大于 getThreshold() 时的回调方法\n * @param TrackResult\n * \t- tableName 对应的表\n * \t- sql 对应的sql\n * \t- costTime 执行耗时\n */\n public abstract void doTrack(TrackResult trackResult);\n}\n"} {"task_id": "Java_1548", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/wuba/Oceanus/oceanus-all/oceanus-core/src/main/java/com/bj58/oceanus/core/timetracker/Tracker.java", "mask_start_position": 1447, "mask_end_position": 1670, "canonical_solution": "if (tableTrackerMap.get(tableName).containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] for table [\" + tableName + \"] already exsit!\");", "pre_mask_code": "/*\n * Copyright Beijing 58 Information Technology Co.,Ltd.\n *\n */\npackage com.bj58.oceanus.core.timetracker;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.bj58.oceanus.core.exception.ConfigurationException;\nimport com.bj58.oceanus.core.timetracker.handler.TrackResult;\nimport com.google.common.collect.Maps;\n\n/**\n * 耗时监控点以及处理器的持有者,也是监控器的基类\n * 子类实现 {@link #doTrack()} 方法并加入配置,即可实现自定义监控\n *\n * @author Service Platform Architecture Team (example@nnthink.com)\n */\npublic abstract class Tracker {\n\n private static final Map generalTrackerMap = Maps.newHashMap();\n\n private static final Map> tableTrackerMap = Maps.newHashMap();\n\n /**\n * 添加全局Tracker\n * @param trackerHodler\n */\n static synchronized void addTracker(TrackerHodler trackerHodler) {\n if (generalTrackerMap.containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] already exsit!\");\n generalTrackerMap.put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 为指定table添加Tracker\n * @param tableName\n * @param trackerHodler\n */\n static synchronized void addTracker(String tableName, TrackerHodler trackerHodler) {\n if (!tableTrackerMap.containsKey(tableName))\n tableTrackerMap.put(tableName, new HashMap());\n ", "post_mask_code": "\n tableTrackerMap.get(tableName).put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 获取全局指定类型的 tracker\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTracker(TrackPoint trackPoint) {\n return generalTrackerMap.get(trackPoint);\n }\n\n /**\n * 获取指定表、指定类型的 tracker\n * @param tableName\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTableTracker(String tableName, TrackPoint trackPoint) {\n if (!tableTrackerMap.containsKey(tableName))\n return null;\n return tableTrackerMap.get(tableName).get(trackPoint);\n }\n\n /**\n * 当对应的 TrackPoint 执行时间大于 getThreshold() 时的回调方法\n * @param TrackResult\n * \t- tableName 对应的表\n * \t- sql 对应的sql\n * \t- costTime 执行耗时\n */\n public abstract void doTrack(TrackResult trackResult);\n}\n"} {"task_id": "Java_1549", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/wuba/Oceanus/oceanus-all/oceanus-core/src/main/java/com/bj58/oceanus/core/timetracker/Tracker.java", "mask_start_position": 1679, "mask_end_position": 1766, "canonical_solution": "tableTrackerMap.get(tableName).put(trackerHodler.getTrackPoint(), trackerHodler);\n }", "pre_mask_code": "/*\n * Copyright Beijing 58 Information Technology Co.,Ltd.\n *\n */\npackage com.bj58.oceanus.core.timetracker;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.bj58.oceanus.core.exception.ConfigurationException;\nimport com.bj58.oceanus.core.timetracker.handler.TrackResult;\nimport com.google.common.collect.Maps;\n\n/**\n * 耗时监控点以及处理器的持有者,也是监控器的基类\n * 子类实现 {@link #doTrack()} 方法并加入配置,即可实现自定义监控\n *\n * @author Service Platform Architecture Team (example@nnthink.com)\n */\npublic abstract class Tracker {\n\n private static final Map generalTrackerMap = Maps.newHashMap();\n\n private static final Map> tableTrackerMap = Maps.newHashMap();\n\n /**\n * 添加全局Tracker\n * @param trackerHodler\n */\n static synchronized void addTracker(TrackerHodler trackerHodler) {\n if (generalTrackerMap.containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] already exsit!\");\n generalTrackerMap.put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 为指定table添加Tracker\n * @param tableName\n * @param trackerHodler\n */\n static synchronized void addTracker(String tableName, TrackerHodler trackerHodler) {\n if (!tableTrackerMap.containsKey(tableName))\n tableTrackerMap.put(tableName, new HashMap());\n if (tableTrackerMap.get(tableName).containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] for table [\" + tableName + \"] already exsit!\");\n ", "post_mask_code": "\n\n /**\n * 获取全局指定类型的 tracker\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTracker(TrackPoint trackPoint) {\n return generalTrackerMap.get(trackPoint);\n }\n\n /**\n * 获取指定表、指定类型的 tracker\n * @param tableName\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTableTracker(String tableName, TrackPoint trackPoint) {\n if (!tableTrackerMap.containsKey(tableName))\n return null;\n return tableTrackerMap.get(tableName).get(trackPoint);\n }\n\n /**\n * 当对应的 TrackPoint 执行时间大于 getThreshold() 时的回调方法\n * @param TrackResult\n * \t- tableName 对应的表\n * \t- sql 对应的sql\n * \t- costTime 执行耗时\n */\n public abstract void doTrack(TrackResult trackResult);\n}\n"} {"task_id": "Java_1550", "language": "Java", "task_type": "single_line", "source_file": "java/github/wuba/Oceanus/oceanus-all/oceanus-core/src/main/java/com/bj58/oceanus/core/timetracker/Tracker.java", "mask_start_position": 2273, "mask_end_position": 2298, "canonical_solution": "bleName).get(trackPoint);", "pre_mask_code": "/*\n * Copyright Beijing 58 Information Technology Co.,Ltd.\n *\n */\npackage com.bj58.oceanus.core.timetracker;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.bj58.oceanus.core.exception.ConfigurationException;\nimport com.bj58.oceanus.core.timetracker.handler.TrackResult;\nimport com.google.common.collect.Maps;\n\n/**\n * 耗时监控点以及处理器的持有者,也是监控器的基类\n * 子类实现 {@link #doTrack()} 方法并加入配置,即可实现自定义监控\n *\n * @author Service Platform Architecture Team (example@nnthink.com)\n */\npublic abstract class Tracker {\n\n private static final Map generalTrackerMap = Maps.newHashMap();\n\n private static final Map> tableTrackerMap = Maps.newHashMap();\n\n /**\n * 添加全局Tracker\n * @param trackerHodler\n */\n static synchronized void addTracker(TrackerHodler trackerHodler) {\n if (generalTrackerMap.containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] already exsit!\");\n generalTrackerMap.put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 为指定table添加Tracker\n * @param tableName\n * @param trackerHodler\n */\n static synchronized void addTracker(String tableName, TrackerHodler trackerHodler) {\n if (!tableTrackerMap.containsKey(tableName))\n tableTrackerMap.put(tableName, new HashMap());\n if (tableTrackerMap.get(tableName).containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] for table [\" + tableName + \"] already exsit!\");\n tableTrackerMap.get(tableName).put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 获取全局指定类型的 tracker\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTracker(TrackPoint trackPoint) {\n return generalTrackerMap.get(trackPoint);\n }\n\n /**\n * 获取指定表、指定类型的 tracker\n * @param tableName\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTableTracker(String tableName, TrackPoint trackPoint) {\n if (!tableTrackerMap.containsKey(tableName))\n return null;\n return tableTrackerMap.get(ta", "post_mask_code": "\n }\n\n /**\n * 当对应的 TrackPoint 执行时间大于 getThreshold() 时的回调方法\n * @param TrackResult\n * \t- tableName 对应的表\n * \t- sql 对应的sql\n * \t- costTime 执行耗时\n */\n public abstract void doTrack(TrackResult trackResult);\n}\n"} {"task_id": "Java_1551", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/wuba/Oceanus/oceanus-all/oceanus-core/src/main/java/com/bj58/oceanus/core/timetracker/Tracker.java", "mask_start_position": 2078, "mask_end_position": 2304, "canonical_solution": "static TrackerHodler getTableTracker(String tableName, TrackPoint trackPoint) {\n if (!tableTrackerMap.containsKey(tableName))\n return null;\n return tableTrackerMap.get(tableName).get(trackPoint);\n }", "pre_mask_code": "/*\n * Copyright Beijing 58 Information Technology Co.,Ltd.\n *\n */\npackage com.bj58.oceanus.core.timetracker;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.bj58.oceanus.core.exception.ConfigurationException;\nimport com.bj58.oceanus.core.timetracker.handler.TrackResult;\nimport com.google.common.collect.Maps;\n\n/**\n * 耗时监控点以及处理器的持有者,也是监控器的基类\n * 子类实现 {@link #doTrack()} 方法并加入配置,即可实现自定义监控\n *\n * @author Service Platform Architecture Team (example@nnthink.com)\n */\npublic abstract class Tracker {\n\n private static final Map generalTrackerMap = Maps.newHashMap();\n\n private static final Map> tableTrackerMap = Maps.newHashMap();\n\n /**\n * 添加全局Tracker\n * @param trackerHodler\n */\n static synchronized void addTracker(TrackerHodler trackerHodler) {\n if (generalTrackerMap.containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] already exsit!\");\n generalTrackerMap.put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 为指定table添加Tracker\n * @param tableName\n * @param trackerHodler\n */\n static synchronized void addTracker(String tableName, TrackerHodler trackerHodler) {\n if (!tableTrackerMap.containsKey(tableName))\n tableTrackerMap.put(tableName, new HashMap());\n if (tableTrackerMap.get(tableName).containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] for table [\" + tableName + \"] already exsit!\");\n tableTrackerMap.get(tableName).put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 获取全局指定类型的 tracker\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTracker(TrackPoint trackPoint) {\n return generalTrackerMap.get(trackPoint);\n }\n\n /**\n * 获取指定表、指定类型的 tracker\n * @param tableName\n * @param trackPoint\n * @return\n */\n ", "post_mask_code": "\n\n /**\n * 当对应的 TrackPoint 执行时间大于 getThreshold() 时的回调方法\n * @param TrackResult\n * \t- tableName 对应的表\n * \t- sql 对应的sql\n * \t- costTime 执行耗时\n */\n public abstract void doTrack(TrackResult trackResult);\n}\n"} {"task_id": "Java_1552", "language": "Java", "task_type": "if_statement", "source_file": "java/github/wuba/Oceanus/oceanus-all/oceanus-core/src/main/java/com/bj58/oceanus/core/timetracker/Tracker.java", "mask_start_position": 1308, "mask_end_position": 1438, "canonical_solution": "if (!tableTrackerMap.containsKey(tableName))\n tableTrackerMap.put(tableName, new HashMap());", "pre_mask_code": "/*\n * Copyright Beijing 58 Information Technology Co.,Ltd.\n *\n */\npackage com.bj58.oceanus.core.timetracker;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.bj58.oceanus.core.exception.ConfigurationException;\nimport com.bj58.oceanus.core.timetracker.handler.TrackResult;\nimport com.google.common.collect.Maps;\n\n/**\n * 耗时监控点以及处理器的持有者,也是监控器的基类\n * 子类实现 {@link #doTrack()} 方法并加入配置,即可实现自定义监控\n *\n * @author Service Platform Architecture Team (example@nnthink.com)\n */\npublic abstract class Tracker {\n\n private static final Map generalTrackerMap = Maps.newHashMap();\n\n private static final Map> tableTrackerMap = Maps.newHashMap();\n\n /**\n * 添加全局Tracker\n * @param trackerHodler\n */\n static synchronized void addTracker(TrackerHodler trackerHodler) {\n if (generalTrackerMap.containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] already exsit!\");\n generalTrackerMap.put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 为指定table添加Tracker\n * @param tableName\n * @param trackerHodler\n */\n static synchronized void addTracker(String tableName, TrackerHodler trackerHodler) {\n ", "post_mask_code": "\n if (tableTrackerMap.get(tableName).containsKey(trackerHodler.getTrackPoint()))\n throw new ConfigurationException(\"TrackPoint [\" + trackerHodler.getTrackPoint() + \"] for table [\" + tableName + \"] already exsit!\");\n tableTrackerMap.get(tableName).put(trackerHodler.getTrackPoint(), trackerHodler);\n }\n\n /**\n * 获取全局指定类型的 tracker\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTracker(TrackPoint trackPoint) {\n return generalTrackerMap.get(trackPoint);\n }\n\n /**\n * 获取指定表、指定类型的 tracker\n * @param tableName\n * @param trackPoint\n * @return\n */\n static TrackerHodler getTableTracker(String tableName, TrackPoint trackPoint) {\n if (!tableTrackerMap.containsKey(tableName))\n return null;\n return tableTrackerMap.get(tableName).get(trackPoint);\n }\n\n /**\n * 当对应的 TrackPoint 执行时间大于 getThreshold() 时的回调方法\n * @param TrackResult\n * \t- tableName 对应的表\n * \t- sql 对应的sql\n * \t- costTime 执行耗时\n */\n public abstract void doTrack(TrackResult trackResult);\n}\n"} {"task_id": "Java_1553", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Stericson/busybox-free/src/stericson/busybox/jobs/InitialChecksJob.java", "mask_start_position": 533, "mask_end_position": 566, "canonical_solution": "@Override\n JobResult handle() ", "pre_mask_code": "package stericson.busybox.jobs;\n\nimport android.app.Activity;\nimport stericson.busybox.R;\nimport stericson.busybox.interfaces.JobCallback;\nimport stericson.busybox.jobs.containers.JobResult;\nimport stericson.busybox.jobs.tasks.InitialChecksTask;\n\npublic class InitialChecksJob extends AsyncJob {\n\n public final static int Checks = 456214;\n\n private JobCallback cb;\n\n public InitialChecksJob(Activity activity, JobCallback cb) {\n super(activity, R.string.initialChecks, false, false);\n this.cb = cb;\n }\n\n ", "post_mask_code": "{\n return InitialChecksTask.execute(this);\n }\n\n @Override\n protected void onProgressUpdate(Object... values) {\n super.onProgressUpdate(values);\n }\n\n @Override\n void callback(JobResult result) {\n cb.jobFinished(result, Checks);\n }\n}\n"} {"task_id": "Java_1554", "language": "Java", "task_type": "method_body", "source_file": "java/github/Stericson/busybox-free/src/stericson/busybox/jobs/InitialChecksJob.java", "mask_start_position": 566, "mask_end_position": 621, "canonical_solution": "{\n return InitialChecksTask.execute(this);\n }", "pre_mask_code": "package stericson.busybox.jobs;\n\nimport android.app.Activity;\nimport stericson.busybox.R;\nimport stericson.busybox.interfaces.JobCallback;\nimport stericson.busybox.jobs.containers.JobResult;\nimport stericson.busybox.jobs.tasks.InitialChecksTask;\n\npublic class InitialChecksJob extends AsyncJob {\n\n public final static int Checks = 456214;\n\n private JobCallback cb;\n\n public InitialChecksJob(Activity activity, JobCallback cb) {\n super(activity, R.string.initialChecks, false, false);\n this.cb = cb;\n }\n\n @Override\n JobResult handle() ", "post_mask_code": "\n\n @Override\n protected void onProgressUpdate(Object... values) {\n super.onProgressUpdate(values);\n }\n\n @Override\n void callback(JobResult result) {\n cb.jobFinished(result, Checks);\n }\n}\n"} {"task_id": "Java_1555", "language": "Java", "task_type": "single_line", "source_file": "java/github/Stericson/busybox-free/src/stericson/busybox/jobs/InitialChecksJob.java", "mask_start_position": 587, "mask_end_position": 615, "canonical_solution": "ialChecksTask.execute(this);", "pre_mask_code": "package stericson.busybox.jobs;\n\nimport android.app.Activity;\nimport stericson.busybox.R;\nimport stericson.busybox.interfaces.JobCallback;\nimport stericson.busybox.jobs.containers.JobResult;\nimport stericson.busybox.jobs.tasks.InitialChecksTask;\n\npublic class InitialChecksJob extends AsyncJob {\n\n public final static int Checks = 456214;\n\n private JobCallback cb;\n\n public InitialChecksJob(Activity activity, JobCallback cb) {\n super(activity, R.string.initialChecks, false, false);\n this.cb = cb;\n }\n\n @Override\n JobResult handle() {\n return Init", "post_mask_code": "\n }\n\n @Override\n protected void onProgressUpdate(Object... values) {\n super.onProgressUpdate(values);\n }\n\n @Override\n void callback(JobResult result) {\n cb.jobFinished(result, Checks);\n }\n}\n"} {"task_id": "Java_1556", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ProgrammeVitam/vitam/sources/logbook/logbook-common/src/main/java/fr/gouv/vitam/logbook/common/model/LogbookLifeCycleObjectGroupModel.java", "mask_start_position": 2353, "mask_end_position": 2375, "canonical_solution": "public String getId() ", "pre_mask_code": "/*\n *\n * example@nnthink.com\n *\n * This software is a computer program whose purpose is to implement a digital archiving back-office system managing\n * high volumetry securely and efficiently.\n *\n * circulated by CEA, CNRS and INRIA at the following URL \"https://cecill.info\".\n *\n * As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license,\n * users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the\n * successive licensors have only limited liability.\n *\n * In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or\n * developing or reproducing the software by the user in light of its specific status of free software, that may mean\n * that it is complicated to manipulate, and that also therefore means that it is reserved for developers and\n * experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the\n * software's suitability as regards their requirements in conditions enabling the security of their systems and/or data\n * to be ensured and, more generally, to use and operate it in the same conditions as regards security.\n *\n * accept its terms.\n */\npackage fr.gouv.vitam.logbook.common.model;\n\nimport java.util.Collection;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport fr.gouv.vitam.logbook.common.parameters.LogbookLifeCycleObjectGroupParameters;\n\npublic class LogbookLifeCycleObjectGroupModel implements LogbookLifeCycleModel {\n\n private String id;\n\n private Collection logbookLifeCycleParameters;\n\n /**\n * Constructor\n *\n * @param id lfc id\n * @param logbookLifeCycleParameters lfc parameters\n */\n @JsonCreator\n public LogbookLifeCycleObjectGroupModel(@JsonProperty(\"id\") String id, @JsonProperty(\"logbookLifeCycleParameters\") Collection logbookLifeCycleParameters) {\n this.id = id;\n this.logbookLifeCycleParameters = logbookLifeCycleParameters;\n }\n\n @Override\n public Collection getLogbookLifeCycleParameters() {\n return logbookLifeCycleParameters;\n }\n\n ", "post_mask_code": "{\n return id;\n }\n}\n"} {"task_id": "Java_1557", "language": "Java", "task_type": "method_body", "source_file": "java/github/ProgrammeVitam/vitam/sources/logbook/logbook-common/src/main/java/fr/gouv/vitam/logbook/common/model/LogbookLifeCycleObjectGroupModel.java", "mask_start_position": 2297, "mask_end_position": 2347, "canonical_solution": "{\n return logbookLifeCycleParameters;\n }", "pre_mask_code": "/*\n *\n * example@nnthink.com\n *\n * This software is a computer program whose purpose is to implement a digital archiving back-office system managing\n * high volumetry securely and efficiently.\n *\n * circulated by CEA, CNRS and INRIA at the following URL \"https://cecill.info\".\n *\n * As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license,\n * users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the\n * successive licensors have only limited liability.\n *\n * In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or\n * developing or reproducing the software by the user in light of its specific status of free software, that may mean\n * that it is complicated to manipulate, and that also therefore means that it is reserved for developers and\n * experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the\n * software's suitability as regards their requirements in conditions enabling the security of their systems and/or data\n * to be ensured and, more generally, to use and operate it in the same conditions as regards security.\n *\n * accept its terms.\n */\npackage fr.gouv.vitam.logbook.common.model;\n\nimport java.util.Collection;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport fr.gouv.vitam.logbook.common.parameters.LogbookLifeCycleObjectGroupParameters;\n\npublic class LogbookLifeCycleObjectGroupModel implements LogbookLifeCycleModel {\n\n private String id;\n\n private Collection logbookLifeCycleParameters;\n\n /**\n * Constructor\n *\n * @param id lfc id\n * @param logbookLifeCycleParameters lfc parameters\n */\n @JsonCreator\n public LogbookLifeCycleObjectGroupModel(@JsonProperty(\"id\") String id, @JsonProperty(\"logbookLifeCycleParameters\") Collection logbookLifeCycleParameters) {\n this.id = id;\n this.logbookLifeCycleParameters = logbookLifeCycleParameters;\n }\n\n @Override\n public Collection getLogbookLifeCycleParameters() ", "post_mask_code": "\n\n public String getId() {\n return id;\n }\n}\n"} {"task_id": "Java_1558", "language": "Java", "task_type": "single_line", "source_file": "java/github/ProgrammeVitam/vitam/sources/logbook/logbook-common/src/main/java/fr/gouv/vitam/logbook/common/model/LogbookLifeCycleObjectGroupModel.java", "mask_start_position": 2307, "mask_end_position": 2341, "canonical_solution": "return logbookLifeCycleParameters;", "pre_mask_code": "/*\n *\n * example@nnthink.com\n *\n * This software is a computer program whose purpose is to implement a digital archiving back-office system managing\n * high volumetry securely and efficiently.\n *\n * circulated by CEA, CNRS and INRIA at the following URL \"https://cecill.info\".\n *\n * As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license,\n * users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the\n * successive licensors have only limited liability.\n *\n * In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or\n * developing or reproducing the software by the user in light of its specific status of free software, that may mean\n * that it is complicated to manipulate, and that also therefore means that it is reserved for developers and\n * experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the\n * software's suitability as regards their requirements in conditions enabling the security of their systems and/or data\n * to be ensured and, more generally, to use and operate it in the same conditions as regards security.\n *\n * accept its terms.\n */\npackage fr.gouv.vitam.logbook.common.model;\n\nimport java.util.Collection;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport fr.gouv.vitam.logbook.common.parameters.LogbookLifeCycleObjectGroupParameters;\n\npublic class LogbookLifeCycleObjectGroupModel implements LogbookLifeCycleModel {\n\n private String id;\n\n private Collection logbookLifeCycleParameters;\n\n /**\n * Constructor\n *\n * @param id lfc id\n * @param logbookLifeCycleParameters lfc parameters\n */\n @JsonCreator\n public LogbookLifeCycleObjectGroupModel(@JsonProperty(\"id\") String id, @JsonProperty(\"logbookLifeCycleParameters\") Collection logbookLifeCycleParameters) {\n this.id = id;\n this.logbookLifeCycleParameters = logbookLifeCycleParameters;\n }\n\n @Override\n public Collection getLogbookLifeCycleParameters() {\n ", "post_mask_code": "\n }\n\n public String getId() {\n return id;\n }\n}\n"} {"task_id": "Java_1559", "language": "Java", "task_type": "method_signature", "source_file": "java/github/JetBrains/intellij-plugins/gauge/src/com/thoughtworks/gauge/highlight/SpecSyntaxHighlighter.java", "mask_start_position": 661, "mask_end_position": 724, "canonical_solution": "@NotNull\n @Override\n public Lexer getHighlightingLexer() ", "pre_mask_code": "package com.thoughtworks.gauge.highlight;\n\nimport com.intellij.lexer.Lexer;\nimport com.intellij.openapi.editor.colors.TextAttributesKey;\nimport com.intellij.openapi.fileTypes.SyntaxHighlighterBase;\nimport com.intellij.psi.TokenType;\nimport com.intellij.psi.tree.IElementType;\nimport com.thoughtworks.gauge.language.token.SpecTokenTypes;\nimport com.thoughtworks.gauge.lexer.SpecLexer;\nimport org.jetbrains.annotations.NotNull;\n\n/**\n * A class that describes what highlighting styles should be applied to various tokens (headings, comments, etc) in a\n * Gauge specification (.spec) file.\n */\nfinal class SpecSyntaxHighlighter extends SyntaxHighlighterBase {\n\n ", "post_mask_code": "{\n return new SpecLexer();\n }\n\n @Override\n public TextAttributesKey @NotNull [] getTokenHighlights(IElementType tokenType) {\n if (tokenType.equals(SpecTokenTypes.SPEC_HEADING)) {\n return HighlighterTokens.SPEC_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.SCENARIO_HEADING)) {\n return HighlighterTokens.SCENARIO_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.STEP)) {\n return HighlighterTokens.STEP_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.COMMENT)) {\n return HighlighterTokens.COMMENT_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_HEADER)) {\n return HighlighterTokens.TABLE_HEADER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_ROW_VALUE)) {\n return HighlighterTokens.TABLE_ROW_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TAGS)) {\n return HighlighterTokens.TAGS_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_BORDER)) {\n return HighlighterTokens.TABLE_BORDER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.ARG_START) || tokenType.equals(SpecTokenTypes.ARG) || tokenType.equals(SpecTokenTypes.ARG_END)) {\n return HighlighterTokens.ARG_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_START) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_END)) {\n return HighlighterTokens.DYNAMIC_ARG_ATTRIBUTE;\n } else if (tokenType.equals(TokenType.BAD_CHARACTER)) {\n return HighlighterTokens.BAD_CHAR_KEYS;\n } else if (tokenType.equals((SpecTokenTypes.KEYWORD))) {\n return HighlighterTokens.KEYWORD_ATTRIBUTE;\n } else {\n return HighlighterTokens.EMPTY_KEYS;\n }\n }\n}\n"} {"task_id": "Java_1560", "language": "Java", "task_type": "method_body", "source_file": "java/github/JetBrains/intellij-plugins/gauge/src/com/thoughtworks/gauge/highlight/SpecSyntaxHighlighter.java", "mask_start_position": 724, "mask_end_position": 763, "canonical_solution": "{\n return new SpecLexer();\n }", "pre_mask_code": "package com.thoughtworks.gauge.highlight;\n\nimport com.intellij.lexer.Lexer;\nimport com.intellij.openapi.editor.colors.TextAttributesKey;\nimport com.intellij.openapi.fileTypes.SyntaxHighlighterBase;\nimport com.intellij.psi.TokenType;\nimport com.intellij.psi.tree.IElementType;\nimport com.thoughtworks.gauge.language.token.SpecTokenTypes;\nimport com.thoughtworks.gauge.lexer.SpecLexer;\nimport org.jetbrains.annotations.NotNull;\n\n/**\n * A class that describes what highlighting styles should be applied to various tokens (headings, comments, etc) in a\n * Gauge specification (.spec) file.\n */\nfinal class SpecSyntaxHighlighter extends SyntaxHighlighterBase {\n\n @NotNull\n @Override\n public Lexer getHighlightingLexer() ", "post_mask_code": "\n\n @Override\n public TextAttributesKey @NotNull [] getTokenHighlights(IElementType tokenType) {\n if (tokenType.equals(SpecTokenTypes.SPEC_HEADING)) {\n return HighlighterTokens.SPEC_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.SCENARIO_HEADING)) {\n return HighlighterTokens.SCENARIO_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.STEP)) {\n return HighlighterTokens.STEP_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.COMMENT)) {\n return HighlighterTokens.COMMENT_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_HEADER)) {\n return HighlighterTokens.TABLE_HEADER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_ROW_VALUE)) {\n return HighlighterTokens.TABLE_ROW_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TAGS)) {\n return HighlighterTokens.TAGS_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_BORDER)) {\n return HighlighterTokens.TABLE_BORDER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.ARG_START) || tokenType.equals(SpecTokenTypes.ARG) || tokenType.equals(SpecTokenTypes.ARG_END)) {\n return HighlighterTokens.ARG_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_START) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_END)) {\n return HighlighterTokens.DYNAMIC_ARG_ATTRIBUTE;\n } else if (tokenType.equals(TokenType.BAD_CHARACTER)) {\n return HighlighterTokens.BAD_CHAR_KEYS;\n } else if (tokenType.equals((SpecTokenTypes.KEYWORD))) {\n return HighlighterTokens.KEYWORD_ATTRIBUTE;\n } else {\n return HighlighterTokens.EMPTY_KEYS;\n }\n }\n}\n"} {"task_id": "Java_1561", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/JetBrains/intellij-plugins/gauge/src/com/thoughtworks/gauge/highlight/SpecSyntaxHighlighter.java", "mask_start_position": 864, "mask_end_position": 864, "canonical_solution": "", "pre_mask_code": "package com.thoughtworks.gauge.highlight;\n\nimport com.intellij.lexer.Lexer;\nimport com.intellij.openapi.editor.colors.TextAttributesKey;\nimport com.intellij.openapi.fileTypes.SyntaxHighlighterBase;\nimport com.intellij.psi.TokenType;\nimport com.intellij.psi.tree.IElementType;\nimport com.thoughtworks.gauge.language.token.SpecTokenTypes;\nimport com.thoughtworks.gauge.lexer.SpecLexer;\nimport org.jetbrains.annotations.NotNull;\n\n/**\n * A class that describes what highlighting styles should be applied to various tokens (headings, comments, etc) in a\n * Gauge specification (.spec) file.\n */\nfinal class SpecSyntaxHighlighter extends SyntaxHighlighterBase {\n\n @NotNull\n @Override\n public Lexer getHighlightingLexer() {\n return new SpecLexer();\n }\n\n @Override\n public TextAttributesKey @NotNull [] getTokenHighlights(IElementType tokenType) {", "post_mask_code": "\n if (tokenType.equals(SpecTokenTypes.SPEC_HEADING)) {\n return HighlighterTokens.SPEC_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.SCENARIO_HEADING)) {\n return HighlighterTokens.SCENARIO_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.STEP)) {\n return HighlighterTokens.STEP_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.COMMENT)) {\n return HighlighterTokens.COMMENT_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_HEADER)) {\n return HighlighterTokens.TABLE_HEADER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_ROW_VALUE)) {\n return HighlighterTokens.TABLE_ROW_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TAGS)) {\n return HighlighterTokens.TAGS_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_BORDER)) {\n return HighlighterTokens.TABLE_BORDER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.ARG_START) || tokenType.equals(SpecTokenTypes.ARG) || tokenType.equals(SpecTokenTypes.ARG_END)) {\n return HighlighterTokens.ARG_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_START) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_END)) {\n return HighlighterTokens.DYNAMIC_ARG_ATTRIBUTE;\n } else if (tokenType.equals(TokenType.BAD_CHARACTER)) {\n return HighlighterTokens.BAD_CHAR_KEYS;\n } else if (tokenType.equals((SpecTokenTypes.KEYWORD))) {\n return HighlighterTokens.KEYWORD_ATTRIBUTE;\n } else {\n return HighlighterTokens.EMPTY_KEYS;\n }\n }\n}\n"} {"task_id": "Java_1562", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/JetBrains/intellij-plugins/gauge/src/com/thoughtworks/gauge/highlight/SpecSyntaxHighlighter.java", "mask_start_position": 873, "mask_end_position": 2602, "canonical_solution": "if (tokenType.equals(SpecTokenTypes.SPEC_HEADING)) {\n return HighlighterTokens.SPEC_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.SCENARIO_HEADING)) {\n return HighlighterTokens.SCENARIO_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.STEP)) {\n return HighlighterTokens.STEP_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.COMMENT)) {\n return HighlighterTokens.COMMENT_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_HEADER)) {\n return HighlighterTokens.TABLE_HEADER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_ROW_VALUE)) {\n return HighlighterTokens.TABLE_ROW_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TAGS)) {\n return HighlighterTokens.TAGS_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_BORDER)) {\n return HighlighterTokens.TABLE_BORDER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.ARG_START) || tokenType.equals(SpecTokenTypes.ARG) || tokenType.equals(SpecTokenTypes.ARG_END)) {\n return HighlighterTokens.ARG_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_START) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_END)) {\n return HighlighterTokens.DYNAMIC_ARG_ATTRIBUTE;\n } else if (tokenType.equals(TokenType.BAD_CHARACTER)) {\n return HighlighterTokens.BAD_CHAR_KEYS;\n } else if (tokenType.equals((SpecTokenTypes.KEYWORD))) {\n return HighlighterTokens.KEYWORD_ATTRIBUTE;\n } else {\n return HighlighterTokens.EMPTY_KEYS;\n }", "pre_mask_code": "package com.thoughtworks.gauge.highlight;\n\nimport com.intellij.lexer.Lexer;\nimport com.intellij.openapi.editor.colors.TextAttributesKey;\nimport com.intellij.openapi.fileTypes.SyntaxHighlighterBase;\nimport com.intellij.psi.TokenType;\nimport com.intellij.psi.tree.IElementType;\nimport com.thoughtworks.gauge.language.token.SpecTokenTypes;\nimport com.thoughtworks.gauge.lexer.SpecLexer;\nimport org.jetbrains.annotations.NotNull;\n\n/**\n * A class that describes what highlighting styles should be applied to various tokens (headings, comments, etc) in a\n * Gauge specification (.spec) file.\n */\nfinal class SpecSyntaxHighlighter extends SyntaxHighlighterBase {\n\n @NotNull\n @Override\n public Lexer getHighlightingLexer() {\n return new SpecLexer();\n }\n\n @Override\n public TextAttributesKey @NotNull [] getTokenHighlights(IElementType tokenType) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1563", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/JetBrains/intellij-plugins/gauge/src/com/thoughtworks/gauge/highlight/SpecSyntaxHighlighter.java", "mask_start_position": 2607, "mask_end_position": 2608, "canonical_solution": "}", "pre_mask_code": "package com.thoughtworks.gauge.highlight;\n\nimport com.intellij.lexer.Lexer;\nimport com.intellij.openapi.editor.colors.TextAttributesKey;\nimport com.intellij.openapi.fileTypes.SyntaxHighlighterBase;\nimport com.intellij.psi.TokenType;\nimport com.intellij.psi.tree.IElementType;\nimport com.thoughtworks.gauge.language.token.SpecTokenTypes;\nimport com.thoughtworks.gauge.lexer.SpecLexer;\nimport org.jetbrains.annotations.NotNull;\n\n/**\n * A class that describes what highlighting styles should be applied to various tokens (headings, comments, etc) in a\n * Gauge specification (.spec) file.\n */\nfinal class SpecSyntaxHighlighter extends SyntaxHighlighterBase {\n\n @NotNull\n @Override\n public Lexer getHighlightingLexer() {\n return new SpecLexer();\n }\n\n @Override\n public TextAttributesKey @NotNull [] getTokenHighlights(IElementType tokenType) {\n if (tokenType.equals(SpecTokenTypes.SPEC_HEADING)) {\n return HighlighterTokens.SPEC_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.SCENARIO_HEADING)) {\n return HighlighterTokens.SCENARIO_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.STEP)) {\n return HighlighterTokens.STEP_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.COMMENT)) {\n return HighlighterTokens.COMMENT_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_HEADER)) {\n return HighlighterTokens.TABLE_HEADER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_ROW_VALUE)) {\n return HighlighterTokens.TABLE_ROW_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TAGS)) {\n return HighlighterTokens.TAGS_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_BORDER)) {\n return HighlighterTokens.TABLE_BORDER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.ARG_START) || tokenType.equals(SpecTokenTypes.ARG) || tokenType.equals(SpecTokenTypes.ARG_END)) {\n return HighlighterTokens.ARG_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_START) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_END)) {\n return HighlighterTokens.DYNAMIC_ARG_ATTRIBUTE;\n } else if (tokenType.equals(TokenType.BAD_CHARACTER)) {\n return HighlighterTokens.BAD_CHAR_KEYS;\n } else if (tokenType.equals((SpecTokenTypes.KEYWORD))) {\n return HighlighterTokens.KEYWORD_ATTRIBUTE;\n } else {\n return HighlighterTokens.EMPTY_KEYS;\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1564", "language": "Java", "task_type": "single_line", "source_file": "java/github/JetBrains/intellij-plugins/gauge/src/com/thoughtworks/gauge/highlight/SpecSyntaxHighlighter.java", "mask_start_position": 734, "mask_end_position": 757, "canonical_solution": "return new SpecLexer();", "pre_mask_code": "package com.thoughtworks.gauge.highlight;\n\nimport com.intellij.lexer.Lexer;\nimport com.intellij.openapi.editor.colors.TextAttributesKey;\nimport com.intellij.openapi.fileTypes.SyntaxHighlighterBase;\nimport com.intellij.psi.TokenType;\nimport com.intellij.psi.tree.IElementType;\nimport com.thoughtworks.gauge.language.token.SpecTokenTypes;\nimport com.thoughtworks.gauge.lexer.SpecLexer;\nimport org.jetbrains.annotations.NotNull;\n\n/**\n * A class that describes what highlighting styles should be applied to various tokens (headings, comments, etc) in a\n * Gauge specification (.spec) file.\n */\nfinal class SpecSyntaxHighlighter extends SyntaxHighlighterBase {\n\n @NotNull\n @Override\n public Lexer getHighlightingLexer() {\n ", "post_mask_code": "\n }\n\n @Override\n public TextAttributesKey @NotNull [] getTokenHighlights(IElementType tokenType) {\n if (tokenType.equals(SpecTokenTypes.SPEC_HEADING)) {\n return HighlighterTokens.SPEC_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.SCENARIO_HEADING)) {\n return HighlighterTokens.SCENARIO_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.STEP)) {\n return HighlighterTokens.STEP_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.COMMENT)) {\n return HighlighterTokens.COMMENT_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_HEADER)) {\n return HighlighterTokens.TABLE_HEADER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_ROW_VALUE)) {\n return HighlighterTokens.TABLE_ROW_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TAGS)) {\n return HighlighterTokens.TAGS_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_BORDER)) {\n return HighlighterTokens.TABLE_BORDER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.ARG_START) || tokenType.equals(SpecTokenTypes.ARG) || tokenType.equals(SpecTokenTypes.ARG_END)) {\n return HighlighterTokens.ARG_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_START) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_END)) {\n return HighlighterTokens.DYNAMIC_ARG_ATTRIBUTE;\n } else if (tokenType.equals(TokenType.BAD_CHARACTER)) {\n return HighlighterTokens.BAD_CHAR_KEYS;\n } else if (tokenType.equals((SpecTokenTypes.KEYWORD))) {\n return HighlighterTokens.KEYWORD_ATTRIBUTE;\n } else {\n return HighlighterTokens.EMPTY_KEYS;\n }\n }\n}\n"} {"task_id": "Java_1565", "language": "Java", "task_type": "if_statement", "source_file": "java/github/JetBrains/intellij-plugins/gauge/src/com/thoughtworks/gauge/highlight/SpecSyntaxHighlighter.java", "mask_start_position": 2305, "mask_end_position": 2602, "canonical_solution": "if (tokenType.equals(TokenType.BAD_CHARACTER)) {\n return HighlighterTokens.BAD_CHAR_KEYS;\n } else if (tokenType.equals((SpecTokenTypes.KEYWORD))) {\n return HighlighterTokens.KEYWORD_ATTRIBUTE;\n } else {\n return HighlighterTokens.EMPTY_KEYS;\n }", "pre_mask_code": "package com.thoughtworks.gauge.highlight;\n\nimport com.intellij.lexer.Lexer;\nimport com.intellij.openapi.editor.colors.TextAttributesKey;\nimport com.intellij.openapi.fileTypes.SyntaxHighlighterBase;\nimport com.intellij.psi.TokenType;\nimport com.intellij.psi.tree.IElementType;\nimport com.thoughtworks.gauge.language.token.SpecTokenTypes;\nimport com.thoughtworks.gauge.lexer.SpecLexer;\nimport org.jetbrains.annotations.NotNull;\n\n/**\n * A class that describes what highlighting styles should be applied to various tokens (headings, comments, etc) in a\n * Gauge specification (.spec) file.\n */\nfinal class SpecSyntaxHighlighter extends SyntaxHighlighterBase {\n\n @NotNull\n @Override\n public Lexer getHighlightingLexer() {\n return new SpecLexer();\n }\n\n @Override\n public TextAttributesKey @NotNull [] getTokenHighlights(IElementType tokenType) {\n if (tokenType.equals(SpecTokenTypes.SPEC_HEADING)) {\n return HighlighterTokens.SPEC_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.SCENARIO_HEADING)) {\n return HighlighterTokens.SCENARIO_HEADING_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.STEP)) {\n return HighlighterTokens.STEP_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.COMMENT)) {\n return HighlighterTokens.COMMENT_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_HEADER)) {\n return HighlighterTokens.TABLE_HEADER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_ROW_VALUE)) {\n return HighlighterTokens.TABLE_ROW_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TAGS)) {\n return HighlighterTokens.TAGS_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.TABLE_BORDER)) {\n return HighlighterTokens.TABLE_BORDER_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.ARG_START) || tokenType.equals(SpecTokenTypes.ARG) || tokenType.equals(SpecTokenTypes.ARG_END)) {\n return HighlighterTokens.ARG_ATTRIBUTE;\n } else if (tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_START) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG) || tokenType.equals(SpecTokenTypes.DYNAMIC_ARG_END)) {\n return HighlighterTokens.DYNAMIC_ARG_ATTRIBUTE;\n } else ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1566", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/phoenix/phoenix-core/src/main/java/org/apache/phoenix/schema/types/PUnsignedTinyint.java", "mask_start_position": 1879, "mask_end_position": 1953, "canonical_solution": "@Override\n public Object toObject(Object object, PDataType actualType) ", "pre_mask_code": "package org.apache.phoenix.schema.types;\n\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.apache.phoenix.schema.SortOrder;\nimport org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;\n\npublic class PUnsignedTinyint extends PWholeNumber {\n\n public static final PUnsignedTinyint INSTANCE = new PUnsignedTinyint();\n\n private PUnsignedTinyint() {\n super(\"UNSIGNED_TINYINT\", 11, Byte.class, new UnsignedByteCodec(), 18);\n }\n\n @Override\n public Integer getScale(Object o) {\n return ZERO;\n }\n\n @Override\n public int compareTo(Object lhs, Object rhs, PDataType rhsType) {\n return PLong.INSTANCE.compareTo(lhs, rhs, rhsType);\n }\n\n @Override\n public boolean isFixedWidth() {\n return true;\n }\n\n @Override\n public Integer getByteSize() {\n return Bytes.SIZEOF_BYTE;\n }\n\n @Override\n public Integer getMaxLength(Object o) {\n return BYTE_PRECISION;\n }\n\n @Override\n public byte[] toBytes(Object object) {\n byte[] b = new byte[Bytes.SIZEOF_BYTE];\n toBytes(object, b, 0);\n return b;\n }\n\n @Override\n public int toBytes(Object object, byte[] bytes, int offset) {\n if (object == null) {\n throw newIllegalDataException(this + \" may not be null\");\n }\n return this.getCodec().encodeByte(((Number) object).byteValue(), bytes, offset);\n }\n\n @Override\n public Object toObject(String value) {\n if (value == null || value.length() == 0) {\n return null;\n }\n try {\n Byte b = Byte.parseByte(value);\n if (b.byteValue() < 0) {\n throw newIllegalDataException(\"Value may not be negative(\" + b + \")\");\n }\n return b;\n } catch (NumberFormatException e) {\n throw newIllegalDataException(e);\n }\n }\n\n ", "post_mask_code": "{\n Byte v = (Byte) PTinyint.INSTANCE.toObject(object, actualType);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public Object toObject(byte[] b, int o, int l, PDataType actualType, SortOrder sortOrder, Integer maxLength, Integer scale) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(b, o, l, actualType, sortOrder);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType) {\n return targetType.equals(this) || PUnsignedSmallint.INSTANCE.isCoercibleTo(targetType) || PTinyint.INSTANCE.isCoercibleTo(targetType);\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType, Object value) {\n return super.isCoercibleTo(targetType, value) || PTinyint.INSTANCE.isCoercibleTo(targetType, value);\n }\n\n @Override\n public boolean isComparableTo(PDataType targetType) {\n return PDecimal.INSTANCE.isComparableTo(targetType);\n }\n\n @Override\n public int getResultSetSqlType() {\n return PTinyint.INSTANCE.getResultSetSqlType();\n }\n\n @Override\n public Object getSampleValue(Integer maxLength, Integer arrayLength) {\n return ((Integer) RANDOM.get().nextInt(Byte.MAX_VALUE)).byteValue();\n }\n\n static class UnsignedByteCodec extends PTinyint.ByteCodec {\n\n @Override\n public byte decodeByte(byte[] b, int o, SortOrder sortOrder) {\n Preconditions.checkNotNull(sortOrder);\n checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE);\n byte v = b[o];\n if (sortOrder == SortOrder.DESC) {\n v = SortOrder.invert(v);\n }\n if (v < 0) {\n throw newIllegalDataException();\n }\n return v;\n }\n\n @Override\n public int encodeByte(byte v, byte[] b, int o) {\n if (v < 0) {\n throw newIllegalDataException();\n }\n Bytes.putByte(b, o, v);\n return Bytes.SIZEOF_BYTE;\n }\n }\n}\n"} {"task_id": "Java_1567", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/phoenix/phoenix-core/src/main/java/org/apache/phoenix/schema/types/PUnsignedTinyint.java", "mask_start_position": 3382, "mask_end_position": 3746, "canonical_solution": "{\n Preconditions.checkNotNull(sortOrder);\n checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE);\n byte v = b[o];\n if (sortOrder == SortOrder.DESC) {\n v = SortOrder.invert(v);\n }\n if (v < 0) {\n throw newIllegalDataException();\n }\n return v;\n }", "pre_mask_code": "package org.apache.phoenix.schema.types;\n\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.apache.phoenix.schema.SortOrder;\nimport org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;\n\npublic class PUnsignedTinyint extends PWholeNumber {\n\n public static final PUnsignedTinyint INSTANCE = new PUnsignedTinyint();\n\n private PUnsignedTinyint() {\n super(\"UNSIGNED_TINYINT\", 11, Byte.class, new UnsignedByteCodec(), 18);\n }\n\n @Override\n public Integer getScale(Object o) {\n return ZERO;\n }\n\n @Override\n public int compareTo(Object lhs, Object rhs, PDataType rhsType) {\n return PLong.INSTANCE.compareTo(lhs, rhs, rhsType);\n }\n\n @Override\n public boolean isFixedWidth() {\n return true;\n }\n\n @Override\n public Integer getByteSize() {\n return Bytes.SIZEOF_BYTE;\n }\n\n @Override\n public Integer getMaxLength(Object o) {\n return BYTE_PRECISION;\n }\n\n @Override\n public byte[] toBytes(Object object) {\n byte[] b = new byte[Bytes.SIZEOF_BYTE];\n toBytes(object, b, 0);\n return b;\n }\n\n @Override\n public int toBytes(Object object, byte[] bytes, int offset) {\n if (object == null) {\n throw newIllegalDataException(this + \" may not be null\");\n }\n return this.getCodec().encodeByte(((Number) object).byteValue(), bytes, offset);\n }\n\n @Override\n public Object toObject(String value) {\n if (value == null || value.length() == 0) {\n return null;\n }\n try {\n Byte b = Byte.parseByte(value);\n if (b.byteValue() < 0) {\n throw newIllegalDataException(\"Value may not be negative(\" + b + \")\");\n }\n return b;\n } catch (NumberFormatException e) {\n throw newIllegalDataException(e);\n }\n }\n\n @Override\n public Object toObject(Object object, PDataType actualType) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(object, actualType);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public Object toObject(byte[] b, int o, int l, PDataType actualType, SortOrder sortOrder, Integer maxLength, Integer scale) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(b, o, l, actualType, sortOrder);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType) {\n return targetType.equals(this) || PUnsignedSmallint.INSTANCE.isCoercibleTo(targetType) || PTinyint.INSTANCE.isCoercibleTo(targetType);\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType, Object value) {\n return super.isCoercibleTo(targetType, value) || PTinyint.INSTANCE.isCoercibleTo(targetType, value);\n }\n\n @Override\n public boolean isComparableTo(PDataType targetType) {\n return PDecimal.INSTANCE.isComparableTo(targetType);\n }\n\n @Override\n public int getResultSetSqlType() {\n return PTinyint.INSTANCE.getResultSetSqlType();\n }\n\n @Override\n public Object getSampleValue(Integer maxLength, Integer arrayLength) {\n return ((Integer) RANDOM.get().nextInt(Byte.MAX_VALUE)).byteValue();\n }\n\n static class UnsignedByteCodec extends PTinyint.ByteCodec {\n\n @Override\n public byte decodeByte(byte[] b, int o, SortOrder sortOrder) ", "post_mask_code": "\n\n @Override\n public int encodeByte(byte v, byte[] b, int o) {\n if (v < 0) {\n throw newIllegalDataException();\n }\n Bytes.putByte(b, o, v);\n return Bytes.SIZEOF_BYTE;\n }\n }\n}\n"} {"task_id": "Java_1568", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/phoenix/phoenix-core/src/main/java/org/apache/phoenix/schema/types/PUnsignedTinyint.java", "mask_start_position": 1462, "mask_end_position": 1549, "canonical_solution": "\n if (value == null || value.length() == 0) {\n return null;\n }", "pre_mask_code": "package org.apache.phoenix.schema.types;\n\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.apache.phoenix.schema.SortOrder;\nimport org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;\n\npublic class PUnsignedTinyint extends PWholeNumber {\n\n public static final PUnsignedTinyint INSTANCE = new PUnsignedTinyint();\n\n private PUnsignedTinyint() {\n super(\"UNSIGNED_TINYINT\", 11, Byte.class, new UnsignedByteCodec(), 18);\n }\n\n @Override\n public Integer getScale(Object o) {\n return ZERO;\n }\n\n @Override\n public int compareTo(Object lhs, Object rhs, PDataType rhsType) {\n return PLong.INSTANCE.compareTo(lhs, rhs, rhsType);\n }\n\n @Override\n public boolean isFixedWidth() {\n return true;\n }\n\n @Override\n public Integer getByteSize() {\n return Bytes.SIZEOF_BYTE;\n }\n\n @Override\n public Integer getMaxLength(Object o) {\n return BYTE_PRECISION;\n }\n\n @Override\n public byte[] toBytes(Object object) {\n byte[] b = new byte[Bytes.SIZEOF_BYTE];\n toBytes(object, b, 0);\n return b;\n }\n\n @Override\n public int toBytes(Object object, byte[] bytes, int offset) {\n if (object == null) {\n throw newIllegalDataException(this + \" may not be null\");\n }\n return this.getCodec().encodeByte(((Number) object).byteValue(), bytes, offset);\n }\n\n @Override\n public Object toObject(String value) {", "post_mask_code": "\n try {\n Byte b = Byte.parseByte(value);\n if (b.byteValue() < 0) {\n throw newIllegalDataException(\"Value may not be negative(\" + b + \")\");\n }\n return b;\n } catch (NumberFormatException e) {\n throw newIllegalDataException(e);\n }\n }\n\n @Override\n public Object toObject(Object object, PDataType actualType) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(object, actualType);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public Object toObject(byte[] b, int o, int l, PDataType actualType, SortOrder sortOrder, Integer maxLength, Integer scale) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(b, o, l, actualType, sortOrder);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType) {\n return targetType.equals(this) || PUnsignedSmallint.INSTANCE.isCoercibleTo(targetType) || PTinyint.INSTANCE.isCoercibleTo(targetType);\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType, Object value) {\n return super.isCoercibleTo(targetType, value) || PTinyint.INSTANCE.isCoercibleTo(targetType, value);\n }\n\n @Override\n public boolean isComparableTo(PDataType targetType) {\n return PDecimal.INSTANCE.isComparableTo(targetType);\n }\n\n @Override\n public int getResultSetSqlType() {\n return PTinyint.INSTANCE.getResultSetSqlType();\n }\n\n @Override\n public Object getSampleValue(Integer maxLength, Integer arrayLength) {\n return ((Integer) RANDOM.get().nextInt(Byte.MAX_VALUE)).byteValue();\n }\n\n static class UnsignedByteCodec extends PTinyint.ByteCodec {\n\n @Override\n public byte decodeByte(byte[] b, int o, SortOrder sortOrder) {\n Preconditions.checkNotNull(sortOrder);\n checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE);\n byte v = b[o];\n if (sortOrder == SortOrder.DESC) {\n v = SortOrder.invert(v);\n }\n if (v < 0) {\n throw newIllegalDataException();\n }\n return v;\n }\n\n @Override\n public int encodeByte(byte v, byte[] b, int o) {\n if (v < 0) {\n throw newIllegalDataException();\n }\n Bytes.putByte(b, o, v);\n return Bytes.SIZEOF_BYTE;\n }\n }\n}\n"} {"task_id": "Java_1569", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/phoenix/phoenix-core/src/main/java/org/apache/phoenix/schema/types/PUnsignedTinyint.java", "mask_start_position": 1558, "mask_end_position": 1867, "canonical_solution": "try {\n Byte b = Byte.parseByte(value);\n if (b.byteValue() < 0) {\n throw newIllegalDataException(\"Value may not be negative(\" + b + \")\");\n }\n return b;\n } catch (NumberFormatException e) {\n throw newIllegalDataException(e);\n }", "pre_mask_code": "package org.apache.phoenix.schema.types;\n\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.apache.phoenix.schema.SortOrder;\nimport org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;\n\npublic class PUnsignedTinyint extends PWholeNumber {\n\n public static final PUnsignedTinyint INSTANCE = new PUnsignedTinyint();\n\n private PUnsignedTinyint() {\n super(\"UNSIGNED_TINYINT\", 11, Byte.class, new UnsignedByteCodec(), 18);\n }\n\n @Override\n public Integer getScale(Object o) {\n return ZERO;\n }\n\n @Override\n public int compareTo(Object lhs, Object rhs, PDataType rhsType) {\n return PLong.INSTANCE.compareTo(lhs, rhs, rhsType);\n }\n\n @Override\n public boolean isFixedWidth() {\n return true;\n }\n\n @Override\n public Integer getByteSize() {\n return Bytes.SIZEOF_BYTE;\n }\n\n @Override\n public Integer getMaxLength(Object o) {\n return BYTE_PRECISION;\n }\n\n @Override\n public byte[] toBytes(Object object) {\n byte[] b = new byte[Bytes.SIZEOF_BYTE];\n toBytes(object, b, 0);\n return b;\n }\n\n @Override\n public int toBytes(Object object, byte[] bytes, int offset) {\n if (object == null) {\n throw newIllegalDataException(this + \" may not be null\");\n }\n return this.getCodec().encodeByte(((Number) object).byteValue(), bytes, offset);\n }\n\n @Override\n public Object toObject(String value) {\n if (value == null || value.length() == 0) {\n return null;\n }\n ", "post_mask_code": "\n }\n\n @Override\n public Object toObject(Object object, PDataType actualType) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(object, actualType);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public Object toObject(byte[] b, int o, int l, PDataType actualType, SortOrder sortOrder, Integer maxLength, Integer scale) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(b, o, l, actualType, sortOrder);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType) {\n return targetType.equals(this) || PUnsignedSmallint.INSTANCE.isCoercibleTo(targetType) || PTinyint.INSTANCE.isCoercibleTo(targetType);\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType, Object value) {\n return super.isCoercibleTo(targetType, value) || PTinyint.INSTANCE.isCoercibleTo(targetType, value);\n }\n\n @Override\n public boolean isComparableTo(PDataType targetType) {\n return PDecimal.INSTANCE.isComparableTo(targetType);\n }\n\n @Override\n public int getResultSetSqlType() {\n return PTinyint.INSTANCE.getResultSetSqlType();\n }\n\n @Override\n public Object getSampleValue(Integer maxLength, Integer arrayLength) {\n return ((Integer) RANDOM.get().nextInt(Byte.MAX_VALUE)).byteValue();\n }\n\n static class UnsignedByteCodec extends PTinyint.ByteCodec {\n\n @Override\n public byte decodeByte(byte[] b, int o, SortOrder sortOrder) {\n Preconditions.checkNotNull(sortOrder);\n checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE);\n byte v = b[o];\n if (sortOrder == SortOrder.DESC) {\n v = SortOrder.invert(v);\n }\n if (v < 0) {\n throw newIllegalDataException();\n }\n return v;\n }\n\n @Override\n public int encodeByte(byte v, byte[] b, int o) {\n if (v < 0) {\n throw newIllegalDataException();\n }\n Bytes.putByte(b, o, v);\n return Bytes.SIZEOF_BYTE;\n }\n }\n}\n"} {"task_id": "Java_1570", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/phoenix/phoenix-core/src/main/java/org/apache/phoenix/schema/types/PUnsignedTinyint.java", "mask_start_position": 1872, "mask_end_position": 1873, "canonical_solution": "}", "pre_mask_code": "package org.apache.phoenix.schema.types;\n\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.apache.phoenix.schema.SortOrder;\nimport org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;\n\npublic class PUnsignedTinyint extends PWholeNumber {\n\n public static final PUnsignedTinyint INSTANCE = new PUnsignedTinyint();\n\n private PUnsignedTinyint() {\n super(\"UNSIGNED_TINYINT\", 11, Byte.class, new UnsignedByteCodec(), 18);\n }\n\n @Override\n public Integer getScale(Object o) {\n return ZERO;\n }\n\n @Override\n public int compareTo(Object lhs, Object rhs, PDataType rhsType) {\n return PLong.INSTANCE.compareTo(lhs, rhs, rhsType);\n }\n\n @Override\n public boolean isFixedWidth() {\n return true;\n }\n\n @Override\n public Integer getByteSize() {\n return Bytes.SIZEOF_BYTE;\n }\n\n @Override\n public Integer getMaxLength(Object o) {\n return BYTE_PRECISION;\n }\n\n @Override\n public byte[] toBytes(Object object) {\n byte[] b = new byte[Bytes.SIZEOF_BYTE];\n toBytes(object, b, 0);\n return b;\n }\n\n @Override\n public int toBytes(Object object, byte[] bytes, int offset) {\n if (object == null) {\n throw newIllegalDataException(this + \" may not be null\");\n }\n return this.getCodec().encodeByte(((Number) object).byteValue(), bytes, offset);\n }\n\n @Override\n public Object toObject(String value) {\n if (value == null || value.length() == 0) {\n return null;\n }\n try {\n Byte b = Byte.parseByte(value);\n if (b.byteValue() < 0) {\n throw newIllegalDataException(\"Value may not be negative(\" + b + \")\");\n }\n return b;\n } catch (NumberFormatException e) {\n throw newIllegalDataException(e);\n }\n ", "post_mask_code": "\n\n @Override\n public Object toObject(Object object, PDataType actualType) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(object, actualType);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public Object toObject(byte[] b, int o, int l, PDataType actualType, SortOrder sortOrder, Integer maxLength, Integer scale) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(b, o, l, actualType, sortOrder);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType) {\n return targetType.equals(this) || PUnsignedSmallint.INSTANCE.isCoercibleTo(targetType) || PTinyint.INSTANCE.isCoercibleTo(targetType);\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType, Object value) {\n return super.isCoercibleTo(targetType, value) || PTinyint.INSTANCE.isCoercibleTo(targetType, value);\n }\n\n @Override\n public boolean isComparableTo(PDataType targetType) {\n return PDecimal.INSTANCE.isComparableTo(targetType);\n }\n\n @Override\n public int getResultSetSqlType() {\n return PTinyint.INSTANCE.getResultSetSqlType();\n }\n\n @Override\n public Object getSampleValue(Integer maxLength, Integer arrayLength) {\n return ((Integer) RANDOM.get().nextInt(Byte.MAX_VALUE)).byteValue();\n }\n\n static class UnsignedByteCodec extends PTinyint.ByteCodec {\n\n @Override\n public byte decodeByte(byte[] b, int o, SortOrder sortOrder) {\n Preconditions.checkNotNull(sortOrder);\n checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE);\n byte v = b[o];\n if (sortOrder == SortOrder.DESC) {\n v = SortOrder.invert(v);\n }\n if (v < 0) {\n throw newIllegalDataException();\n }\n return v;\n }\n\n @Override\n public int encodeByte(byte v, byte[] b, int o) {\n if (v < 0) {\n throw newIllegalDataException();\n }\n Bytes.putByte(b, o, v);\n return Bytes.SIZEOF_BYTE;\n }\n }\n}\n"} {"task_id": "Java_1571", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/phoenix/phoenix-core/src/main/java/org/apache/phoenix/schema/types/PUnsignedTinyint.java", "mask_start_position": 3983, "mask_end_position": 3984, "canonical_solution": ";", "pre_mask_code": "package org.apache.phoenix.schema.types;\n\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.apache.phoenix.schema.SortOrder;\nimport org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;\n\npublic class PUnsignedTinyint extends PWholeNumber {\n\n public static final PUnsignedTinyint INSTANCE = new PUnsignedTinyint();\n\n private PUnsignedTinyint() {\n super(\"UNSIGNED_TINYINT\", 11, Byte.class, new UnsignedByteCodec(), 18);\n }\n\n @Override\n public Integer getScale(Object o) {\n return ZERO;\n }\n\n @Override\n public int compareTo(Object lhs, Object rhs, PDataType rhsType) {\n return PLong.INSTANCE.compareTo(lhs, rhs, rhsType);\n }\n\n @Override\n public boolean isFixedWidth() {\n return true;\n }\n\n @Override\n public Integer getByteSize() {\n return Bytes.SIZEOF_BYTE;\n }\n\n @Override\n public Integer getMaxLength(Object o) {\n return BYTE_PRECISION;\n }\n\n @Override\n public byte[] toBytes(Object object) {\n byte[] b = new byte[Bytes.SIZEOF_BYTE];\n toBytes(object, b, 0);\n return b;\n }\n\n @Override\n public int toBytes(Object object, byte[] bytes, int offset) {\n if (object == null) {\n throw newIllegalDataException(this + \" may not be null\");\n }\n return this.getCodec().encodeByte(((Number) object).byteValue(), bytes, offset);\n }\n\n @Override\n public Object toObject(String value) {\n if (value == null || value.length() == 0) {\n return null;\n }\n try {\n Byte b = Byte.parseByte(value);\n if (b.byteValue() < 0) {\n throw newIllegalDataException(\"Value may not be negative(\" + b + \")\");\n }\n return b;\n } catch (NumberFormatException e) {\n throw newIllegalDataException(e);\n }\n }\n\n @Override\n public Object toObject(Object object, PDataType actualType) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(object, actualType);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public Object toObject(byte[] b, int o, int l, PDataType actualType, SortOrder sortOrder, Integer maxLength, Integer scale) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(b, o, l, actualType, sortOrder);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType) {\n return targetType.equals(this) || PUnsignedSmallint.INSTANCE.isCoercibleTo(targetType) || PTinyint.INSTANCE.isCoercibleTo(targetType);\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType, Object value) {\n return super.isCoercibleTo(targetType, value) || PTinyint.INSTANCE.isCoercibleTo(targetType, value);\n }\n\n @Override\n public boolean isComparableTo(PDataType targetType) {\n return PDecimal.INSTANCE.isComparableTo(targetType);\n }\n\n @Override\n public int getResultSetSqlType() {\n return PTinyint.INSTANCE.getResultSetSqlType();\n }\n\n @Override\n public Object getSampleValue(Integer maxLength, Integer arrayLength) {\n return ((Integer) RANDOM.get().nextInt(Byte.MAX_VALUE)).byteValue();\n }\n\n static class UnsignedByteCodec extends PTinyint.ByteCodec {\n\n @Override\n public byte decodeByte(byte[] b, int o, SortOrder sortOrder) {\n Preconditions.checkNotNull(sortOrder);\n checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE);\n byte v = b[o];\n if (sortOrder == SortOrder.DESC) {\n v = SortOrder.invert(v);\n }\n if (v < 0) {\n throw newIllegalDataException();\n }\n return v;\n }\n\n @Override\n public int encodeByte(byte v, byte[] b, int o) {\n if (v < 0) {\n throw newIllegalDataException();\n }\n Bytes.putByte(b, o, v);\n return Bytes.SIZEOF_BYTE", "post_mask_code": "\n }\n }\n}\n"} {"task_id": "Java_1572", "language": "Java", "task_type": "if_statement", "source_file": "java/github/apache/phoenix/phoenix-core/src/main/java/org/apache/phoenix/schema/types/PUnsignedTinyint.java", "mask_start_position": 1208, "mask_end_position": 1309, "canonical_solution": "if (object == null) {\n throw newIllegalDataException(this + \" may not be null\");\n }", "pre_mask_code": "package org.apache.phoenix.schema.types;\n\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.apache.phoenix.schema.SortOrder;\nimport org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;\n\npublic class PUnsignedTinyint extends PWholeNumber {\n\n public static final PUnsignedTinyint INSTANCE = new PUnsignedTinyint();\n\n private PUnsignedTinyint() {\n super(\"UNSIGNED_TINYINT\", 11, Byte.class, new UnsignedByteCodec(), 18);\n }\n\n @Override\n public Integer getScale(Object o) {\n return ZERO;\n }\n\n @Override\n public int compareTo(Object lhs, Object rhs, PDataType rhsType) {\n return PLong.INSTANCE.compareTo(lhs, rhs, rhsType);\n }\n\n @Override\n public boolean isFixedWidth() {\n return true;\n }\n\n @Override\n public Integer getByteSize() {\n return Bytes.SIZEOF_BYTE;\n }\n\n @Override\n public Integer getMaxLength(Object o) {\n return BYTE_PRECISION;\n }\n\n @Override\n public byte[] toBytes(Object object) {\n byte[] b = new byte[Bytes.SIZEOF_BYTE];\n toBytes(object, b, 0);\n return b;\n }\n\n @Override\n public int toBytes(Object object, byte[] bytes, int offset) {\n ", "post_mask_code": "\n return this.getCodec().encodeByte(((Number) object).byteValue(), bytes, offset);\n }\n\n @Override\n public Object toObject(String value) {\n if (value == null || value.length() == 0) {\n return null;\n }\n try {\n Byte b = Byte.parseByte(value);\n if (b.byteValue() < 0) {\n throw newIllegalDataException(\"Value may not be negative(\" + b + \")\");\n }\n return b;\n } catch (NumberFormatException e) {\n throw newIllegalDataException(e);\n }\n }\n\n @Override\n public Object toObject(Object object, PDataType actualType) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(object, actualType);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public Object toObject(byte[] b, int o, int l, PDataType actualType, SortOrder sortOrder, Integer maxLength, Integer scale) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(b, o, l, actualType, sortOrder);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType) {\n return targetType.equals(this) || PUnsignedSmallint.INSTANCE.isCoercibleTo(targetType) || PTinyint.INSTANCE.isCoercibleTo(targetType);\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType, Object value) {\n return super.isCoercibleTo(targetType, value) || PTinyint.INSTANCE.isCoercibleTo(targetType, value);\n }\n\n @Override\n public boolean isComparableTo(PDataType targetType) {\n return PDecimal.INSTANCE.isComparableTo(targetType);\n }\n\n @Override\n public int getResultSetSqlType() {\n return PTinyint.INSTANCE.getResultSetSqlType();\n }\n\n @Override\n public Object getSampleValue(Integer maxLength, Integer arrayLength) {\n return ((Integer) RANDOM.get().nextInt(Byte.MAX_VALUE)).byteValue();\n }\n\n static class UnsignedByteCodec extends PTinyint.ByteCodec {\n\n @Override\n public byte decodeByte(byte[] b, int o, SortOrder sortOrder) {\n Preconditions.checkNotNull(sortOrder);\n checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE);\n byte v = b[o];\n if (sortOrder == SortOrder.DESC) {\n v = SortOrder.invert(v);\n }\n if (v < 0) {\n throw newIllegalDataException();\n }\n return v;\n }\n\n @Override\n public int encodeByte(byte v, byte[] b, int o) {\n if (v < 0) {\n throw newIllegalDataException();\n }\n Bytes.putByte(b, o, v);\n return Bytes.SIZEOF_BYTE;\n }\n }\n}\n"} {"task_id": "Java_1573", "language": "Java", "task_type": "try_statement", "source_file": "java/github/apache/phoenix/phoenix-core/src/main/java/org/apache/phoenix/schema/types/PUnsignedTinyint.java", "mask_start_position": 1558, "mask_end_position": 1867, "canonical_solution": "try {\n Byte b = Byte.parseByte(value);\n if (b.byteValue() < 0) {\n throw newIllegalDataException(\"Value may not be negative(\" + b + \")\");\n }\n return b;\n } catch (NumberFormatException e) {\n throw newIllegalDataException(e);\n }", "pre_mask_code": "package org.apache.phoenix.schema.types;\n\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.apache.phoenix.schema.SortOrder;\nimport org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;\n\npublic class PUnsignedTinyint extends PWholeNumber {\n\n public static final PUnsignedTinyint INSTANCE = new PUnsignedTinyint();\n\n private PUnsignedTinyint() {\n super(\"UNSIGNED_TINYINT\", 11, Byte.class, new UnsignedByteCodec(), 18);\n }\n\n @Override\n public Integer getScale(Object o) {\n return ZERO;\n }\n\n @Override\n public int compareTo(Object lhs, Object rhs, PDataType rhsType) {\n return PLong.INSTANCE.compareTo(lhs, rhs, rhsType);\n }\n\n @Override\n public boolean isFixedWidth() {\n return true;\n }\n\n @Override\n public Integer getByteSize() {\n return Bytes.SIZEOF_BYTE;\n }\n\n @Override\n public Integer getMaxLength(Object o) {\n return BYTE_PRECISION;\n }\n\n @Override\n public byte[] toBytes(Object object) {\n byte[] b = new byte[Bytes.SIZEOF_BYTE];\n toBytes(object, b, 0);\n return b;\n }\n\n @Override\n public int toBytes(Object object, byte[] bytes, int offset) {\n if (object == null) {\n throw newIllegalDataException(this + \" may not be null\");\n }\n return this.getCodec().encodeByte(((Number) object).byteValue(), bytes, offset);\n }\n\n @Override\n public Object toObject(String value) {\n if (value == null || value.length() == 0) {\n return null;\n }\n ", "post_mask_code": "\n }\n\n @Override\n public Object toObject(Object object, PDataType actualType) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(object, actualType);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public Object toObject(byte[] b, int o, int l, PDataType actualType, SortOrder sortOrder, Integer maxLength, Integer scale) {\n Byte v = (Byte) PTinyint.INSTANCE.toObject(b, o, l, actualType, sortOrder);\n throwIfNonNegativeNumber(v);\n return v;\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType) {\n return targetType.equals(this) || PUnsignedSmallint.INSTANCE.isCoercibleTo(targetType) || PTinyint.INSTANCE.isCoercibleTo(targetType);\n }\n\n @Override\n public boolean isCoercibleTo(PDataType targetType, Object value) {\n return super.isCoercibleTo(targetType, value) || PTinyint.INSTANCE.isCoercibleTo(targetType, value);\n }\n\n @Override\n public boolean isComparableTo(PDataType targetType) {\n return PDecimal.INSTANCE.isComparableTo(targetType);\n }\n\n @Override\n public int getResultSetSqlType() {\n return PTinyint.INSTANCE.getResultSetSqlType();\n }\n\n @Override\n public Object getSampleValue(Integer maxLength, Integer arrayLength) {\n return ((Integer) RANDOM.get().nextInt(Byte.MAX_VALUE)).byteValue();\n }\n\n static class UnsignedByteCodec extends PTinyint.ByteCodec {\n\n @Override\n public byte decodeByte(byte[] b, int o, SortOrder sortOrder) {\n Preconditions.checkNotNull(sortOrder);\n checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE);\n byte v = b[o];\n if (sortOrder == SortOrder.DESC) {\n v = SortOrder.invert(v);\n }\n if (v < 0) {\n throw newIllegalDataException();\n }\n return v;\n }\n\n @Override\n public int encodeByte(byte v, byte[] b, int o) {\n if (v < 0) {\n throw newIllegalDataException();\n }\n Bytes.putByte(b, o, v);\n return Bytes.SIZEOF_BYTE;\n }\n }\n}\n"} {"task_id": "Java_1574", "language": "Java", "task_type": "method_signature", "source_file": "java/github/weld/core/impl/src/main/java/org/jboss/weld/contexts/AbstractUnboundContext.java", "mask_start_position": 1212, "mask_end_position": 1247, "canonical_solution": "protected BeanStore getBeanStore() ", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source\n * full listing of individual contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://example.com\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jboss.weld.contexts;\n\nimport org.jboss.weld.contexts.beanstore.BeanStore;\n\n/**\n * Base class for contexts using a thread local to store a bound bean context\n *\n * @author Pete Muir\n */\npublic abstract class AbstractUnboundContext extends AbstractManagedContext {\n\n private final ThreadLocal beanStore;\n\n public AbstractUnboundContext(String contextId, boolean multithreaded) {\n super(contextId, multithreaded);\n this.beanStore = new ThreadLocal();\n }\n\n /**\n * Gets the bean store\n *\n * @returns The bean store\n */\n ", "post_mask_code": "{\n return beanStore.get();\n }\n\n /**\n * Sets the bean store\n *\n * @param beanStore The bean store\n */\n protected void setBeanStore(BeanStore beanStore) {\n this.beanStore.set(beanStore);\n }\n\n @Override\n protected void destroy() {\n super.destroy();\n this.beanStore.remove();\n }\n\n @Override\n public void cleanup() {\n super.cleanup();\n beanStore.remove();\n }\n}\n"} {"task_id": "Java_1575", "language": "Java", "task_type": "method_body", "source_file": "java/github/weld/core/impl/src/main/java/org/jboss/weld/contexts/AbstractUnboundContext.java", "mask_start_position": 1430, "mask_end_position": 1476, "canonical_solution": "{\n this.beanStore.set(beanStore);\n }", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source\n * full listing of individual contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://example.com\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jboss.weld.contexts;\n\nimport org.jboss.weld.contexts.beanstore.BeanStore;\n\n/**\n * Base class for contexts using a thread local to store a bound bean context\n *\n * @author Pete Muir\n */\npublic abstract class AbstractUnboundContext extends AbstractManagedContext {\n\n private final ThreadLocal beanStore;\n\n public AbstractUnboundContext(String contextId, boolean multithreaded) {\n super(contextId, multithreaded);\n this.beanStore = new ThreadLocal();\n }\n\n /**\n * Gets the bean store\n *\n * @returns The bean store\n */\n protected BeanStore getBeanStore() {\n return beanStore.get();\n }\n\n /**\n * Sets the bean store\n *\n * @param beanStore The bean store\n */\n protected void setBeanStore(BeanStore beanStore) ", "post_mask_code": "\n\n @Override\n protected void destroy() {\n super.destroy();\n this.beanStore.remove();\n }\n\n @Override\n public void cleanup() {\n super.cleanup();\n beanStore.remove();\n }\n}\n"} {"task_id": "Java_1576", "language": "Java", "task_type": "single_line", "source_file": "java/github/weld/core/impl/src/main/java/org/jboss/weld/contexts/AbstractUnboundContext.java", "mask_start_position": 1645, "mask_end_position": 1654, "canonical_solution": "leanup();", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source\n * full listing of individual contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://example.com\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jboss.weld.contexts;\n\nimport org.jboss.weld.contexts.beanstore.BeanStore;\n\n/**\n * Base class for contexts using a thread local to store a bound bean context\n *\n * @author Pete Muir\n */\npublic abstract class AbstractUnboundContext extends AbstractManagedContext {\n\n private final ThreadLocal beanStore;\n\n public AbstractUnboundContext(String contextId, boolean multithreaded) {\n super(contextId, multithreaded);\n this.beanStore = new ThreadLocal();\n }\n\n /**\n * Gets the bean store\n *\n * @returns The bean store\n */\n protected BeanStore getBeanStore() {\n return beanStore.get();\n }\n\n /**\n * Sets the bean store\n *\n * @param beanStore The bean store\n */\n protected void setBeanStore(BeanStore beanStore) {\n this.beanStore.set(beanStore);\n }\n\n @Override\n protected void destroy() {\n super.destroy();\n this.beanStore.remove();\n }\n\n @Override\n public void cleanup() {\n super.c", "post_mask_code": "\n beanStore.remove();\n }\n}\n"} {"task_id": "Java_1577", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/weld/core/impl/src/main/java/org/jboss/weld/contexts/AbstractUnboundContext.java", "mask_start_position": 1381, "mask_end_position": 1476, "canonical_solution": "protected void setBeanStore(BeanStore beanStore) {\n this.beanStore.set(beanStore);\n }", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source\n * full listing of individual contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://example.com\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jboss.weld.contexts;\n\nimport org.jboss.weld.contexts.beanstore.BeanStore;\n\n/**\n * Base class for contexts using a thread local to store a bound bean context\n *\n * @author Pete Muir\n */\npublic abstract class AbstractUnboundContext extends AbstractManagedContext {\n\n private final ThreadLocal beanStore;\n\n public AbstractUnboundContext(String contextId, boolean multithreaded) {\n super(contextId, multithreaded);\n this.beanStore = new ThreadLocal();\n }\n\n /**\n * Gets the bean store\n *\n * @returns The bean store\n */\n protected BeanStore getBeanStore() {\n return beanStore.get();\n }\n\n /**\n * Sets the bean store\n *\n * @param beanStore The bean store\n */\n ", "post_mask_code": "\n\n @Override\n protected void destroy() {\n super.destroy();\n this.beanStore.remove();\n }\n\n @Override\n public void cleanup() {\n super.cleanup();\n beanStore.remove();\n }\n}\n"} {"task_id": "Java_1578", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ops4j/org.ops4j.pax.web/pax-web-spi/src/main/java/org/ops4j/pax/web/service/spi/servlet/OsgiScopedServletContext.java", "mask_start_position": 8879, "mask_end_position": 8923, "canonical_solution": "@Override\n public String getServerInfo() ", "pre_mask_code": "package org.ops4j.pax.web.service.spi.servlet;\n\nimport java.io.InputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.Enumeration;\nimport java.util.EventListener;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.Filter;\nimport javax.servlet.FilterRegistration;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.Servlet;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRegistration;\nimport javax.servlet.SessionCookieConfig;\nimport javax.servlet.SessionTrackingMode;\nimport javax.servlet.descriptor.JspConfigDescriptor;\nimport org.ops4j.pax.web.service.WebContainerContext;\nimport org.ops4j.pax.web.service.spi.model.OsgiContextModel;\nimport org.osgi.framework.Bundle;\nimport org.osgi.framework.wiring.BundleWiring;\n\n/**\n *

This class provides special {@link ServletContext#getClassLoader()} method for Whiteboard elements.\n * All Whiteboard services should use a {@link ServletContext} which uses single\n * {@link org.osgi.service.http.HttpContext} or {@link org.osgi.service.http.context.ServletContextHelper}, but\n * additionally, class loader should come from the bundle which registered the Whiteboard service (e.g., a servlet)\n * itself, not from the bundle that has registered the {@link org.osgi.service.http.context.ServletContextHelper}.

\n */\npublic class OsgiScopedServletContext implements ServletContext {\n\n /**\n * {@link org.ops4j.pax.web.service.spi.servlet.OsgiServletContext} to which the target servlet is registered.\n * Servlet itself can be registered in the scope of different {@link Bundle}, so actual\n * {@link org.ops4j.pax.web.service.WebContainerContext} has to be obtained/resolved within the scope of proper\n * {@link Bundle}.\n */\n private final OsgiServletContext osgiContext;\n\n /**\n * {@link Bundle} which was used to register target {@link javax.servlet.Servlet}\n */\n private final Bundle bundle;\n\n private final WebContainerContext webContainerContext;\n\n public OsgiScopedServletContext(OsgiServletContext osgiContext, Bundle bundle) {\n this.osgiContext = osgiContext;\n this.bundle = bundle;\n this.webContainerContext = osgiContext.getOsgiContextModel().resolveHttpContext(bundle);\n }\n\n public OsgiServletContext getOsgiContext() {\n return osgiContext;\n }\n\n public OsgiContextModel getOsgiContextModel() {\n return osgiContext.getOsgiContextModel();\n }\n\n public ServletContext getContainerServletContext() {\n return osgiContext.getContainerServletContext();\n }\n\n public ClassLoader getOsgiContextClassLoader() {\n return osgiContext.getClassLoader();\n }\n\n public String[] getWelcomeFiles() {\n return osgiContext.getWelcomeFiles();\n }\n\n public boolean isWelcomeFilesRedirect() {\n return osgiContext.isWelcomeFilesRedirect();\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, String className) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Class filterClass) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public void addListener(String className) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(T t) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(Class listenerClass) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, String className) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Class servletClass) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public T createFilter(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createFilter() is not supported.\");\n }\n\n @Override\n public T createListener(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createListener() is not supported.\");\n }\n\n @Override\n public T createServlet(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createServlet() is not supported.\");\n }\n\n @Override\n public void declareRoles(String... roleNames) {\n throw new UnsupportedOperationException(\"declareRoles() is not supported.\");\n }\n\n @Override\n public boolean setInitParameter(String name, String value) {\n throw new UnsupportedOperationException(\"setInitParameter() is not supported.\");\n }\n\n @Override\n public void setSessionTrackingModes(Set sessionTrackingModes) {\n throw new UnsupportedOperationException(\"setSessionTrackingModes() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addJspFile(String servletName, String jspFile) {\n throw new UnsupportedOperationException(\"addJspFile() is not supported.\");\n }\n\n // --- methods that are scoped to HttpContext/ServletContextHelper\n @Override\n public Object getAttribute(String name) {\n return osgiContext.getAttribute(name);\n }\n\n @Override\n public Enumeration getAttributeNames() {\n return osgiContext.getAttributeNames();\n }\n\n @Override\n public void setAttribute(String name, Object object) {\n osgiContext.setAttribute(name, object);\n }\n\n @Override\n public void removeAttribute(String name) {\n osgiContext.removeAttribute(name);\n }\n\n // --- methods simply delegating to server-specific ServletContext. Backed by the Servlet Container.\n @Override\n public String getContextPath() {\n return osgiContext.getContextPath();\n }\n\n @Override\n public ServletContext getContext(String uripath) {\n return osgiContext.getContext(uripath);\n }\n\n @Override\n public Set getDefaultSessionTrackingModes() {\n return osgiContext.getDefaultSessionTrackingModes();\n }\n\n @Override\n public int getEffectiveMajorVersion() {\n return osgiContext.getEffectiveMajorVersion();\n }\n\n @Override\n public int getEffectiveMinorVersion() {\n return osgiContext.getEffectiveMinorVersion();\n }\n\n @Override\n public Set getEffectiveSessionTrackingModes() {\n return osgiContext.getEffectiveSessionTrackingModes();\n }\n\n @Override\n public FilterRegistration getFilterRegistration(String filterName) {\n return osgiContext.getFilterRegistration(filterName);\n }\n\n @Override\n public Map getFilterRegistrations() {\n return osgiContext.getFilterRegistrations();\n }\n\n @Override\n public int getMajorVersion() {\n return osgiContext.getMajorVersion();\n }\n\n @Override\n public int getMinorVersion() {\n return osgiContext.getMinorVersion();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Servlet getServlet(String name) throws ServletException {\n return osgiContext.getServlet(name);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServletNames() {\n return osgiContext.getServletNames();\n }\n\n @Override\n public ServletRegistration getServletRegistration(String servletName) {\n return osgiContext.getServletRegistration(servletName);\n }\n\n @Override\n public Map getServletRegistrations() {\n return osgiContext.getServletRegistrations();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServlets() {\n return osgiContext.getServlets();\n }\n\n @Override\n public String getVirtualServerName() {\n return osgiContext.getVirtualServerName();\n }\n\n ", "post_mask_code": "{\n return osgiContext.getServerInfo();\n }\n\n @Override\n public void log(String msg) {\n osgiContext.log(msg);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public void log(Exception exception, String msg) {\n osgiContext.log(exception, msg);\n }\n\n @Override\n public void log(String message, Throwable throwable) {\n osgiContext.log(message, throwable);\n }\n\n @Override\n public SessionCookieConfig getSessionCookieConfig() {\n return osgiContext.getSessionCookieConfig();\n }\n\n @Override\n public JspConfigDescriptor getJspConfigDescriptor() {\n return osgiContext.getJspConfigDescriptor();\n }\n\n // --- methods also delegating to server-specific ServletContext, but added in Servlet spec 4.0\n @Override\n public int getSessionTimeout() {\n return osgiContext.getSessionTimeout();\n }\n\n @Override\n public void setSessionTimeout(int sessionTimeout) {\n osgiContext.setSessionTimeout(sessionTimeout);\n }\n\n @Override\n public String getRequestCharacterEncoding() {\n return osgiContext.getRequestCharacterEncoding();\n }\n\n @Override\n public void setRequestCharacterEncoding(String encoding) {\n osgiContext.setRequestCharacterEncoding(encoding);\n }\n\n @Override\n public String getResponseCharacterEncoding() {\n return osgiContext.getResponseCharacterEncoding();\n }\n\n @Override\n public void setResponseCharacterEncoding(String encoding) {\n osgiContext.setResponseCharacterEncoding(encoding);\n }\n\n // --- methods backed by the ServletContextHelper.\n // some of them, that delegate to WebContainerContext have to use proper WebContainerContext - from\n // the bundle that was used to register the servlet, not from the bundle that registered target\n // HttpContext/ServletContextHelper\n @Override\n public String getMimeType(String file) {\n return osgiContext.getMimeType(webContainerContext, file);\n }\n\n @Override\n public String getRealPath(String path) {\n return osgiContext.getRealPath(webContainerContext, path);\n }\n\n @Override\n public URL getResource(String path) throws MalformedURLException {\n return osgiContext.getResource(webContainerContext, path);\n }\n\n @Override\n public InputStream getResourceAsStream(String path) {\n return osgiContext.getResourceAsStream(webContainerContext, path);\n }\n\n @Override\n public Set getResourcePaths(String path) {\n return osgiContext.getResourcePaths(webContainerContext, path);\n }\n\n // --- methods backed by the OsgiContextModel (object \"customized\" by trackers from ServletContextHelper)\n @Override\n public String getInitParameter(String name) {\n return osgiContext.getInitParameter(name);\n }\n\n @Override\n public Enumeration getInitParameterNames() {\n return osgiContext.getInitParameterNames();\n }\n\n @Override\n public RequestDispatcher getRequestDispatcher(String path) {\n return osgiContext.getRequestDispatcher(path);\n }\n\n @Override\n public RequestDispatcher getNamedDispatcher(String name) {\n return osgiContext.getNamedDispatcher(name);\n }\n\n @Override\n public String getServletContextName() {\n return osgiContext.getServletContextName();\n }\n\n // --- methods dependent on which actual servlet/filter uses the context\n @Override\n public ClassLoader getClassLoader() {\n // according to Whiteboard specification - this should be strictly a classloader of a bundle registering\n // the servlet/filter, but in case of WAB, we'll return the WAB's classloader (delegating to\n // all reachable bundles)\n if (getOsgiContextModel().isWab()) {\n return getOsgiContextModel().getClassLoader();\n }\n return bundle.adapt(BundleWiring.class).getClassLoader();\n }\n}\n"} {"task_id": "Java_1579", "language": "Java", "task_type": "method_body", "source_file": "java/github/ops4j/org.ops4j.pax.web/pax-web-spi/src/main/java/org/ops4j/pax/web/service/spi/servlet/OsgiScopedServletContext.java", "mask_start_position": 7148, "mask_end_position": 7210, "canonical_solution": "{\n return osgiContext.getEffectiveMinorVersion();\n }", "pre_mask_code": "package org.ops4j.pax.web.service.spi.servlet;\n\nimport java.io.InputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.Enumeration;\nimport java.util.EventListener;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.Filter;\nimport javax.servlet.FilterRegistration;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.Servlet;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRegistration;\nimport javax.servlet.SessionCookieConfig;\nimport javax.servlet.SessionTrackingMode;\nimport javax.servlet.descriptor.JspConfigDescriptor;\nimport org.ops4j.pax.web.service.WebContainerContext;\nimport org.ops4j.pax.web.service.spi.model.OsgiContextModel;\nimport org.osgi.framework.Bundle;\nimport org.osgi.framework.wiring.BundleWiring;\n\n/**\n *

This class provides special {@link ServletContext#getClassLoader()} method for Whiteboard elements.\n * All Whiteboard services should use a {@link ServletContext} which uses single\n * {@link org.osgi.service.http.HttpContext} or {@link org.osgi.service.http.context.ServletContextHelper}, but\n * additionally, class loader should come from the bundle which registered the Whiteboard service (e.g., a servlet)\n * itself, not from the bundle that has registered the {@link org.osgi.service.http.context.ServletContextHelper}.

\n */\npublic class OsgiScopedServletContext implements ServletContext {\n\n /**\n * {@link org.ops4j.pax.web.service.spi.servlet.OsgiServletContext} to which the target servlet is registered.\n * Servlet itself can be registered in the scope of different {@link Bundle}, so actual\n * {@link org.ops4j.pax.web.service.WebContainerContext} has to be obtained/resolved within the scope of proper\n * {@link Bundle}.\n */\n private final OsgiServletContext osgiContext;\n\n /**\n * {@link Bundle} which was used to register target {@link javax.servlet.Servlet}\n */\n private final Bundle bundle;\n\n private final WebContainerContext webContainerContext;\n\n public OsgiScopedServletContext(OsgiServletContext osgiContext, Bundle bundle) {\n this.osgiContext = osgiContext;\n this.bundle = bundle;\n this.webContainerContext = osgiContext.getOsgiContextModel().resolveHttpContext(bundle);\n }\n\n public OsgiServletContext getOsgiContext() {\n return osgiContext;\n }\n\n public OsgiContextModel getOsgiContextModel() {\n return osgiContext.getOsgiContextModel();\n }\n\n public ServletContext getContainerServletContext() {\n return osgiContext.getContainerServletContext();\n }\n\n public ClassLoader getOsgiContextClassLoader() {\n return osgiContext.getClassLoader();\n }\n\n public String[] getWelcomeFiles() {\n return osgiContext.getWelcomeFiles();\n }\n\n public boolean isWelcomeFilesRedirect() {\n return osgiContext.isWelcomeFilesRedirect();\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, String className) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Class filterClass) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public void addListener(String className) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(T t) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(Class listenerClass) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, String className) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Class servletClass) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public T createFilter(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createFilter() is not supported.\");\n }\n\n @Override\n public T createListener(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createListener() is not supported.\");\n }\n\n @Override\n public T createServlet(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createServlet() is not supported.\");\n }\n\n @Override\n public void declareRoles(String... roleNames) {\n throw new UnsupportedOperationException(\"declareRoles() is not supported.\");\n }\n\n @Override\n public boolean setInitParameter(String name, String value) {\n throw new UnsupportedOperationException(\"setInitParameter() is not supported.\");\n }\n\n @Override\n public void setSessionTrackingModes(Set sessionTrackingModes) {\n throw new UnsupportedOperationException(\"setSessionTrackingModes() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addJspFile(String servletName, String jspFile) {\n throw new UnsupportedOperationException(\"addJspFile() is not supported.\");\n }\n\n // --- methods that are scoped to HttpContext/ServletContextHelper\n @Override\n public Object getAttribute(String name) {\n return osgiContext.getAttribute(name);\n }\n\n @Override\n public Enumeration getAttributeNames() {\n return osgiContext.getAttributeNames();\n }\n\n @Override\n public void setAttribute(String name, Object object) {\n osgiContext.setAttribute(name, object);\n }\n\n @Override\n public void removeAttribute(String name) {\n osgiContext.removeAttribute(name);\n }\n\n // --- methods simply delegating to server-specific ServletContext. Backed by the Servlet Container.\n @Override\n public String getContextPath() {\n return osgiContext.getContextPath();\n }\n\n @Override\n public ServletContext getContext(String uripath) {\n return osgiContext.getContext(uripath);\n }\n\n @Override\n public Set getDefaultSessionTrackingModes() {\n return osgiContext.getDefaultSessionTrackingModes();\n }\n\n @Override\n public int getEffectiveMajorVersion() {\n return osgiContext.getEffectiveMajorVersion();\n }\n\n @Override\n public int getEffectiveMinorVersion() ", "post_mask_code": "\n\n @Override\n public Set getEffectiveSessionTrackingModes() {\n return osgiContext.getEffectiveSessionTrackingModes();\n }\n\n @Override\n public FilterRegistration getFilterRegistration(String filterName) {\n return osgiContext.getFilterRegistration(filterName);\n }\n\n @Override\n public Map getFilterRegistrations() {\n return osgiContext.getFilterRegistrations();\n }\n\n @Override\n public int getMajorVersion() {\n return osgiContext.getMajorVersion();\n }\n\n @Override\n public int getMinorVersion() {\n return osgiContext.getMinorVersion();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Servlet getServlet(String name) throws ServletException {\n return osgiContext.getServlet(name);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServletNames() {\n return osgiContext.getServletNames();\n }\n\n @Override\n public ServletRegistration getServletRegistration(String servletName) {\n return osgiContext.getServletRegistration(servletName);\n }\n\n @Override\n public Map getServletRegistrations() {\n return osgiContext.getServletRegistrations();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServlets() {\n return osgiContext.getServlets();\n }\n\n @Override\n public String getVirtualServerName() {\n return osgiContext.getVirtualServerName();\n }\n\n @Override\n public String getServerInfo() {\n return osgiContext.getServerInfo();\n }\n\n @Override\n public void log(String msg) {\n osgiContext.log(msg);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public void log(Exception exception, String msg) {\n osgiContext.log(exception, msg);\n }\n\n @Override\n public void log(String message, Throwable throwable) {\n osgiContext.log(message, throwable);\n }\n\n @Override\n public SessionCookieConfig getSessionCookieConfig() {\n return osgiContext.getSessionCookieConfig();\n }\n\n @Override\n public JspConfigDescriptor getJspConfigDescriptor() {\n return osgiContext.getJspConfigDescriptor();\n }\n\n // --- methods also delegating to server-specific ServletContext, but added in Servlet spec 4.0\n @Override\n public int getSessionTimeout() {\n return osgiContext.getSessionTimeout();\n }\n\n @Override\n public void setSessionTimeout(int sessionTimeout) {\n osgiContext.setSessionTimeout(sessionTimeout);\n }\n\n @Override\n public String getRequestCharacterEncoding() {\n return osgiContext.getRequestCharacterEncoding();\n }\n\n @Override\n public void setRequestCharacterEncoding(String encoding) {\n osgiContext.setRequestCharacterEncoding(encoding);\n }\n\n @Override\n public String getResponseCharacterEncoding() {\n return osgiContext.getResponseCharacterEncoding();\n }\n\n @Override\n public void setResponseCharacterEncoding(String encoding) {\n osgiContext.setResponseCharacterEncoding(encoding);\n }\n\n // --- methods backed by the ServletContextHelper.\n // some of them, that delegate to WebContainerContext have to use proper WebContainerContext - from\n // the bundle that was used to register the servlet, not from the bundle that registered target\n // HttpContext/ServletContextHelper\n @Override\n public String getMimeType(String file) {\n return osgiContext.getMimeType(webContainerContext, file);\n }\n\n @Override\n public String getRealPath(String path) {\n return osgiContext.getRealPath(webContainerContext, path);\n }\n\n @Override\n public URL getResource(String path) throws MalformedURLException {\n return osgiContext.getResource(webContainerContext, path);\n }\n\n @Override\n public InputStream getResourceAsStream(String path) {\n return osgiContext.getResourceAsStream(webContainerContext, path);\n }\n\n @Override\n public Set getResourcePaths(String path) {\n return osgiContext.getResourcePaths(webContainerContext, path);\n }\n\n // --- methods backed by the OsgiContextModel (object \"customized\" by trackers from ServletContextHelper)\n @Override\n public String getInitParameter(String name) {\n return osgiContext.getInitParameter(name);\n }\n\n @Override\n public Enumeration getInitParameterNames() {\n return osgiContext.getInitParameterNames();\n }\n\n @Override\n public RequestDispatcher getRequestDispatcher(String path) {\n return osgiContext.getRequestDispatcher(path);\n }\n\n @Override\n public RequestDispatcher getNamedDispatcher(String name) {\n return osgiContext.getNamedDispatcher(name);\n }\n\n @Override\n public String getServletContextName() {\n return osgiContext.getServletContextName();\n }\n\n // --- methods dependent on which actual servlet/filter uses the context\n @Override\n public ClassLoader getClassLoader() {\n // according to Whiteboard specification - this should be strictly a classloader of a bundle registering\n // the servlet/filter, but in case of WAB, we'll return the WAB's classloader (delegating to\n // all reachable bundles)\n if (getOsgiContextModel().isWab()) {\n return getOsgiContextModel().getClassLoader();\n }\n return bundle.adapt(BundleWiring.class).getClassLoader();\n }\n}\n"} {"task_id": "Java_1580", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/ops4j/org.ops4j.pax.web/pax-web-spi/src/main/java/org/ops4j/pax/web/service/spi/servlet/OsgiScopedServletContext.java", "mask_start_position": 12433, "mask_end_position": 12647, "canonical_solution": "\n // according to Whiteboard specification - this should be strictly a classloader of a bundle registering\n // the servlet/filter, but in case of WAB, we'll return the WAB's classloader (delegating to", "pre_mask_code": "package org.ops4j.pax.web.service.spi.servlet;\n\nimport java.io.InputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.Enumeration;\nimport java.util.EventListener;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.Filter;\nimport javax.servlet.FilterRegistration;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.Servlet;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRegistration;\nimport javax.servlet.SessionCookieConfig;\nimport javax.servlet.SessionTrackingMode;\nimport javax.servlet.descriptor.JspConfigDescriptor;\nimport org.ops4j.pax.web.service.WebContainerContext;\nimport org.ops4j.pax.web.service.spi.model.OsgiContextModel;\nimport org.osgi.framework.Bundle;\nimport org.osgi.framework.wiring.BundleWiring;\n\n/**\n *

This class provides special {@link ServletContext#getClassLoader()} method for Whiteboard elements.\n * All Whiteboard services should use a {@link ServletContext} which uses single\n * {@link org.osgi.service.http.HttpContext} or {@link org.osgi.service.http.context.ServletContextHelper}, but\n * additionally, class loader should come from the bundle which registered the Whiteboard service (e.g., a servlet)\n * itself, not from the bundle that has registered the {@link org.osgi.service.http.context.ServletContextHelper}.

\n */\npublic class OsgiScopedServletContext implements ServletContext {\n\n /**\n * {@link org.ops4j.pax.web.service.spi.servlet.OsgiServletContext} to which the target servlet is registered.\n * Servlet itself can be registered in the scope of different {@link Bundle}, so actual\n * {@link org.ops4j.pax.web.service.WebContainerContext} has to be obtained/resolved within the scope of proper\n * {@link Bundle}.\n */\n private final OsgiServletContext osgiContext;\n\n /**\n * {@link Bundle} which was used to register target {@link javax.servlet.Servlet}\n */\n private final Bundle bundle;\n\n private final WebContainerContext webContainerContext;\n\n public OsgiScopedServletContext(OsgiServletContext osgiContext, Bundle bundle) {\n this.osgiContext = osgiContext;\n this.bundle = bundle;\n this.webContainerContext = osgiContext.getOsgiContextModel().resolveHttpContext(bundle);\n }\n\n public OsgiServletContext getOsgiContext() {\n return osgiContext;\n }\n\n public OsgiContextModel getOsgiContextModel() {\n return osgiContext.getOsgiContextModel();\n }\n\n public ServletContext getContainerServletContext() {\n return osgiContext.getContainerServletContext();\n }\n\n public ClassLoader getOsgiContextClassLoader() {\n return osgiContext.getClassLoader();\n }\n\n public String[] getWelcomeFiles() {\n return osgiContext.getWelcomeFiles();\n }\n\n public boolean isWelcomeFilesRedirect() {\n return osgiContext.isWelcomeFilesRedirect();\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, String className) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Class filterClass) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public void addListener(String className) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(T t) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(Class listenerClass) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, String className) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Class servletClass) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public T createFilter(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createFilter() is not supported.\");\n }\n\n @Override\n public T createListener(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createListener() is not supported.\");\n }\n\n @Override\n public T createServlet(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createServlet() is not supported.\");\n }\n\n @Override\n public void declareRoles(String... roleNames) {\n throw new UnsupportedOperationException(\"declareRoles() is not supported.\");\n }\n\n @Override\n public boolean setInitParameter(String name, String value) {\n throw new UnsupportedOperationException(\"setInitParameter() is not supported.\");\n }\n\n @Override\n public void setSessionTrackingModes(Set sessionTrackingModes) {\n throw new UnsupportedOperationException(\"setSessionTrackingModes() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addJspFile(String servletName, String jspFile) {\n throw new UnsupportedOperationException(\"addJspFile() is not supported.\");\n }\n\n // --- methods that are scoped to HttpContext/ServletContextHelper\n @Override\n public Object getAttribute(String name) {\n return osgiContext.getAttribute(name);\n }\n\n @Override\n public Enumeration getAttributeNames() {\n return osgiContext.getAttributeNames();\n }\n\n @Override\n public void setAttribute(String name, Object object) {\n osgiContext.setAttribute(name, object);\n }\n\n @Override\n public void removeAttribute(String name) {\n osgiContext.removeAttribute(name);\n }\n\n // --- methods simply delegating to server-specific ServletContext. Backed by the Servlet Container.\n @Override\n public String getContextPath() {\n return osgiContext.getContextPath();\n }\n\n @Override\n public ServletContext getContext(String uripath) {\n return osgiContext.getContext(uripath);\n }\n\n @Override\n public Set getDefaultSessionTrackingModes() {\n return osgiContext.getDefaultSessionTrackingModes();\n }\n\n @Override\n public int getEffectiveMajorVersion() {\n return osgiContext.getEffectiveMajorVersion();\n }\n\n @Override\n public int getEffectiveMinorVersion() {\n return osgiContext.getEffectiveMinorVersion();\n }\n\n @Override\n public Set getEffectiveSessionTrackingModes() {\n return osgiContext.getEffectiveSessionTrackingModes();\n }\n\n @Override\n public FilterRegistration getFilterRegistration(String filterName) {\n return osgiContext.getFilterRegistration(filterName);\n }\n\n @Override\n public Map getFilterRegistrations() {\n return osgiContext.getFilterRegistrations();\n }\n\n @Override\n public int getMajorVersion() {\n return osgiContext.getMajorVersion();\n }\n\n @Override\n public int getMinorVersion() {\n return osgiContext.getMinorVersion();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Servlet getServlet(String name) throws ServletException {\n return osgiContext.getServlet(name);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServletNames() {\n return osgiContext.getServletNames();\n }\n\n @Override\n public ServletRegistration getServletRegistration(String servletName) {\n return osgiContext.getServletRegistration(servletName);\n }\n\n @Override\n public Map getServletRegistrations() {\n return osgiContext.getServletRegistrations();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServlets() {\n return osgiContext.getServlets();\n }\n\n @Override\n public String getVirtualServerName() {\n return osgiContext.getVirtualServerName();\n }\n\n @Override\n public String getServerInfo() {\n return osgiContext.getServerInfo();\n }\n\n @Override\n public void log(String msg) {\n osgiContext.log(msg);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public void log(Exception exception, String msg) {\n osgiContext.log(exception, msg);\n }\n\n @Override\n public void log(String message, Throwable throwable) {\n osgiContext.log(message, throwable);\n }\n\n @Override\n public SessionCookieConfig getSessionCookieConfig() {\n return osgiContext.getSessionCookieConfig();\n }\n\n @Override\n public JspConfigDescriptor getJspConfigDescriptor() {\n return osgiContext.getJspConfigDescriptor();\n }\n\n // --- methods also delegating to server-specific ServletContext, but added in Servlet spec 4.0\n @Override\n public int getSessionTimeout() {\n return osgiContext.getSessionTimeout();\n }\n\n @Override\n public void setSessionTimeout(int sessionTimeout) {\n osgiContext.setSessionTimeout(sessionTimeout);\n }\n\n @Override\n public String getRequestCharacterEncoding() {\n return osgiContext.getRequestCharacterEncoding();\n }\n\n @Override\n public void setRequestCharacterEncoding(String encoding) {\n osgiContext.setRequestCharacterEncoding(encoding);\n }\n\n @Override\n public String getResponseCharacterEncoding() {\n return osgiContext.getResponseCharacterEncoding();\n }\n\n @Override\n public void setResponseCharacterEncoding(String encoding) {\n osgiContext.setResponseCharacterEncoding(encoding);\n }\n\n // --- methods backed by the ServletContextHelper.\n // some of them, that delegate to WebContainerContext have to use proper WebContainerContext - from\n // the bundle that was used to register the servlet, not from the bundle that registered target\n // HttpContext/ServletContextHelper\n @Override\n public String getMimeType(String file) {\n return osgiContext.getMimeType(webContainerContext, file);\n }\n\n @Override\n public String getRealPath(String path) {\n return osgiContext.getRealPath(webContainerContext, path);\n }\n\n @Override\n public URL getResource(String path) throws MalformedURLException {\n return osgiContext.getResource(webContainerContext, path);\n }\n\n @Override\n public InputStream getResourceAsStream(String path) {\n return osgiContext.getResourceAsStream(webContainerContext, path);\n }\n\n @Override\n public Set getResourcePaths(String path) {\n return osgiContext.getResourcePaths(webContainerContext, path);\n }\n\n // --- methods backed by the OsgiContextModel (object \"customized\" by trackers from ServletContextHelper)\n @Override\n public String getInitParameter(String name) {\n return osgiContext.getInitParameter(name);\n }\n\n @Override\n public Enumeration getInitParameterNames() {\n return osgiContext.getInitParameterNames();\n }\n\n @Override\n public RequestDispatcher getRequestDispatcher(String path) {\n return osgiContext.getRequestDispatcher(path);\n }\n\n @Override\n public RequestDispatcher getNamedDispatcher(String name) {\n return osgiContext.getNamedDispatcher(name);\n }\n\n @Override\n public String getServletContextName() {\n return osgiContext.getServletContextName();\n }\n\n // --- methods dependent on which actual servlet/filter uses the context\n @Override\n public ClassLoader getClassLoader() {", "post_mask_code": "\n // all reachable bundles)\n if (getOsgiContextModel().isWab()) {\n return getOsgiContextModel().getClassLoader();\n }\n return bundle.adapt(BundleWiring.class).getClassLoader();\n }\n}\n"} {"task_id": "Java_1581", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/ops4j/org.ops4j.pax.web/pax-web-spi/src/main/java/org/ops4j/pax/web/service/spi/servlet/OsgiScopedServletContext.java", "mask_start_position": 12656, "mask_end_position": 12795, "canonical_solution": "// all reachable bundles)\n if (getOsgiContextModel().isWab()) {\n return getOsgiContextModel().getClassLoader();\n }", "pre_mask_code": "package org.ops4j.pax.web.service.spi.servlet;\n\nimport java.io.InputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.Enumeration;\nimport java.util.EventListener;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.Filter;\nimport javax.servlet.FilterRegistration;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.Servlet;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRegistration;\nimport javax.servlet.SessionCookieConfig;\nimport javax.servlet.SessionTrackingMode;\nimport javax.servlet.descriptor.JspConfigDescriptor;\nimport org.ops4j.pax.web.service.WebContainerContext;\nimport org.ops4j.pax.web.service.spi.model.OsgiContextModel;\nimport org.osgi.framework.Bundle;\nimport org.osgi.framework.wiring.BundleWiring;\n\n/**\n *

This class provides special {@link ServletContext#getClassLoader()} method for Whiteboard elements.\n * All Whiteboard services should use a {@link ServletContext} which uses single\n * {@link org.osgi.service.http.HttpContext} or {@link org.osgi.service.http.context.ServletContextHelper}, but\n * additionally, class loader should come from the bundle which registered the Whiteboard service (e.g., a servlet)\n * itself, not from the bundle that has registered the {@link org.osgi.service.http.context.ServletContextHelper}.

\n */\npublic class OsgiScopedServletContext implements ServletContext {\n\n /**\n * {@link org.ops4j.pax.web.service.spi.servlet.OsgiServletContext} to which the target servlet is registered.\n * Servlet itself can be registered in the scope of different {@link Bundle}, so actual\n * {@link org.ops4j.pax.web.service.WebContainerContext} has to be obtained/resolved within the scope of proper\n * {@link Bundle}.\n */\n private final OsgiServletContext osgiContext;\n\n /**\n * {@link Bundle} which was used to register target {@link javax.servlet.Servlet}\n */\n private final Bundle bundle;\n\n private final WebContainerContext webContainerContext;\n\n public OsgiScopedServletContext(OsgiServletContext osgiContext, Bundle bundle) {\n this.osgiContext = osgiContext;\n this.bundle = bundle;\n this.webContainerContext = osgiContext.getOsgiContextModel().resolveHttpContext(bundle);\n }\n\n public OsgiServletContext getOsgiContext() {\n return osgiContext;\n }\n\n public OsgiContextModel getOsgiContextModel() {\n return osgiContext.getOsgiContextModel();\n }\n\n public ServletContext getContainerServletContext() {\n return osgiContext.getContainerServletContext();\n }\n\n public ClassLoader getOsgiContextClassLoader() {\n return osgiContext.getClassLoader();\n }\n\n public String[] getWelcomeFiles() {\n return osgiContext.getWelcomeFiles();\n }\n\n public boolean isWelcomeFilesRedirect() {\n return osgiContext.isWelcomeFilesRedirect();\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, String className) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Class filterClass) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public void addListener(String className) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(T t) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(Class listenerClass) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, String className) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Class servletClass) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public T createFilter(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createFilter() is not supported.\");\n }\n\n @Override\n public T createListener(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createListener() is not supported.\");\n }\n\n @Override\n public T createServlet(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createServlet() is not supported.\");\n }\n\n @Override\n public void declareRoles(String... roleNames) {\n throw new UnsupportedOperationException(\"declareRoles() is not supported.\");\n }\n\n @Override\n public boolean setInitParameter(String name, String value) {\n throw new UnsupportedOperationException(\"setInitParameter() is not supported.\");\n }\n\n @Override\n public void setSessionTrackingModes(Set sessionTrackingModes) {\n throw new UnsupportedOperationException(\"setSessionTrackingModes() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addJspFile(String servletName, String jspFile) {\n throw new UnsupportedOperationException(\"addJspFile() is not supported.\");\n }\n\n // --- methods that are scoped to HttpContext/ServletContextHelper\n @Override\n public Object getAttribute(String name) {\n return osgiContext.getAttribute(name);\n }\n\n @Override\n public Enumeration getAttributeNames() {\n return osgiContext.getAttributeNames();\n }\n\n @Override\n public void setAttribute(String name, Object object) {\n osgiContext.setAttribute(name, object);\n }\n\n @Override\n public void removeAttribute(String name) {\n osgiContext.removeAttribute(name);\n }\n\n // --- methods simply delegating to server-specific ServletContext. Backed by the Servlet Container.\n @Override\n public String getContextPath() {\n return osgiContext.getContextPath();\n }\n\n @Override\n public ServletContext getContext(String uripath) {\n return osgiContext.getContext(uripath);\n }\n\n @Override\n public Set getDefaultSessionTrackingModes() {\n return osgiContext.getDefaultSessionTrackingModes();\n }\n\n @Override\n public int getEffectiveMajorVersion() {\n return osgiContext.getEffectiveMajorVersion();\n }\n\n @Override\n public int getEffectiveMinorVersion() {\n return osgiContext.getEffectiveMinorVersion();\n }\n\n @Override\n public Set getEffectiveSessionTrackingModes() {\n return osgiContext.getEffectiveSessionTrackingModes();\n }\n\n @Override\n public FilterRegistration getFilterRegistration(String filterName) {\n return osgiContext.getFilterRegistration(filterName);\n }\n\n @Override\n public Map getFilterRegistrations() {\n return osgiContext.getFilterRegistrations();\n }\n\n @Override\n public int getMajorVersion() {\n return osgiContext.getMajorVersion();\n }\n\n @Override\n public int getMinorVersion() {\n return osgiContext.getMinorVersion();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Servlet getServlet(String name) throws ServletException {\n return osgiContext.getServlet(name);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServletNames() {\n return osgiContext.getServletNames();\n }\n\n @Override\n public ServletRegistration getServletRegistration(String servletName) {\n return osgiContext.getServletRegistration(servletName);\n }\n\n @Override\n public Map getServletRegistrations() {\n return osgiContext.getServletRegistrations();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServlets() {\n return osgiContext.getServlets();\n }\n\n @Override\n public String getVirtualServerName() {\n return osgiContext.getVirtualServerName();\n }\n\n @Override\n public String getServerInfo() {\n return osgiContext.getServerInfo();\n }\n\n @Override\n public void log(String msg) {\n osgiContext.log(msg);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public void log(Exception exception, String msg) {\n osgiContext.log(exception, msg);\n }\n\n @Override\n public void log(String message, Throwable throwable) {\n osgiContext.log(message, throwable);\n }\n\n @Override\n public SessionCookieConfig getSessionCookieConfig() {\n return osgiContext.getSessionCookieConfig();\n }\n\n @Override\n public JspConfigDescriptor getJspConfigDescriptor() {\n return osgiContext.getJspConfigDescriptor();\n }\n\n // --- methods also delegating to server-specific ServletContext, but added in Servlet spec 4.0\n @Override\n public int getSessionTimeout() {\n return osgiContext.getSessionTimeout();\n }\n\n @Override\n public void setSessionTimeout(int sessionTimeout) {\n osgiContext.setSessionTimeout(sessionTimeout);\n }\n\n @Override\n public String getRequestCharacterEncoding() {\n return osgiContext.getRequestCharacterEncoding();\n }\n\n @Override\n public void setRequestCharacterEncoding(String encoding) {\n osgiContext.setRequestCharacterEncoding(encoding);\n }\n\n @Override\n public String getResponseCharacterEncoding() {\n return osgiContext.getResponseCharacterEncoding();\n }\n\n @Override\n public void setResponseCharacterEncoding(String encoding) {\n osgiContext.setResponseCharacterEncoding(encoding);\n }\n\n // --- methods backed by the ServletContextHelper.\n // some of them, that delegate to WebContainerContext have to use proper WebContainerContext - from\n // the bundle that was used to register the servlet, not from the bundle that registered target\n // HttpContext/ServletContextHelper\n @Override\n public String getMimeType(String file) {\n return osgiContext.getMimeType(webContainerContext, file);\n }\n\n @Override\n public String getRealPath(String path) {\n return osgiContext.getRealPath(webContainerContext, path);\n }\n\n @Override\n public URL getResource(String path) throws MalformedURLException {\n return osgiContext.getResource(webContainerContext, path);\n }\n\n @Override\n public InputStream getResourceAsStream(String path) {\n return osgiContext.getResourceAsStream(webContainerContext, path);\n }\n\n @Override\n public Set getResourcePaths(String path) {\n return osgiContext.getResourcePaths(webContainerContext, path);\n }\n\n // --- methods backed by the OsgiContextModel (object \"customized\" by trackers from ServletContextHelper)\n @Override\n public String getInitParameter(String name) {\n return osgiContext.getInitParameter(name);\n }\n\n @Override\n public Enumeration getInitParameterNames() {\n return osgiContext.getInitParameterNames();\n }\n\n @Override\n public RequestDispatcher getRequestDispatcher(String path) {\n return osgiContext.getRequestDispatcher(path);\n }\n\n @Override\n public RequestDispatcher getNamedDispatcher(String name) {\n return osgiContext.getNamedDispatcher(name);\n }\n\n @Override\n public String getServletContextName() {\n return osgiContext.getServletContextName();\n }\n\n // --- methods dependent on which actual servlet/filter uses the context\n @Override\n public ClassLoader getClassLoader() {\n // according to Whiteboard specification - this should be strictly a classloader of a bundle registering\n // the servlet/filter, but in case of WAB, we'll return the WAB's classloader (delegating to\n ", "post_mask_code": "\n return bundle.adapt(BundleWiring.class).getClassLoader();\n }\n}\n"} {"task_id": "Java_1582", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/ops4j/org.ops4j.pax.web/pax-web-spi/src/main/java/org/ops4j/pax/web/service/spi/servlet/OsgiScopedServletContext.java", "mask_start_position": 12804, "mask_end_position": 12867, "canonical_solution": "return bundle.adapt(BundleWiring.class).getClassLoader();\n }", "pre_mask_code": "package org.ops4j.pax.web.service.spi.servlet;\n\nimport java.io.InputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.Enumeration;\nimport java.util.EventListener;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.Filter;\nimport javax.servlet.FilterRegistration;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.Servlet;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRegistration;\nimport javax.servlet.SessionCookieConfig;\nimport javax.servlet.SessionTrackingMode;\nimport javax.servlet.descriptor.JspConfigDescriptor;\nimport org.ops4j.pax.web.service.WebContainerContext;\nimport org.ops4j.pax.web.service.spi.model.OsgiContextModel;\nimport org.osgi.framework.Bundle;\nimport org.osgi.framework.wiring.BundleWiring;\n\n/**\n *

This class provides special {@link ServletContext#getClassLoader()} method for Whiteboard elements.\n * All Whiteboard services should use a {@link ServletContext} which uses single\n * {@link org.osgi.service.http.HttpContext} or {@link org.osgi.service.http.context.ServletContextHelper}, but\n * additionally, class loader should come from the bundle which registered the Whiteboard service (e.g., a servlet)\n * itself, not from the bundle that has registered the {@link org.osgi.service.http.context.ServletContextHelper}.

\n */\npublic class OsgiScopedServletContext implements ServletContext {\n\n /**\n * {@link org.ops4j.pax.web.service.spi.servlet.OsgiServletContext} to which the target servlet is registered.\n * Servlet itself can be registered in the scope of different {@link Bundle}, so actual\n * {@link org.ops4j.pax.web.service.WebContainerContext} has to be obtained/resolved within the scope of proper\n * {@link Bundle}.\n */\n private final OsgiServletContext osgiContext;\n\n /**\n * {@link Bundle} which was used to register target {@link javax.servlet.Servlet}\n */\n private final Bundle bundle;\n\n private final WebContainerContext webContainerContext;\n\n public OsgiScopedServletContext(OsgiServletContext osgiContext, Bundle bundle) {\n this.osgiContext = osgiContext;\n this.bundle = bundle;\n this.webContainerContext = osgiContext.getOsgiContextModel().resolveHttpContext(bundle);\n }\n\n public OsgiServletContext getOsgiContext() {\n return osgiContext;\n }\n\n public OsgiContextModel getOsgiContextModel() {\n return osgiContext.getOsgiContextModel();\n }\n\n public ServletContext getContainerServletContext() {\n return osgiContext.getContainerServletContext();\n }\n\n public ClassLoader getOsgiContextClassLoader() {\n return osgiContext.getClassLoader();\n }\n\n public String[] getWelcomeFiles() {\n return osgiContext.getWelcomeFiles();\n }\n\n public boolean isWelcomeFilesRedirect() {\n return osgiContext.isWelcomeFilesRedirect();\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, String className) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Class filterClass) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public void addListener(String className) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(T t) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(Class listenerClass) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, String className) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Class servletClass) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public T createFilter(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createFilter() is not supported.\");\n }\n\n @Override\n public T createListener(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createListener() is not supported.\");\n }\n\n @Override\n public T createServlet(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createServlet() is not supported.\");\n }\n\n @Override\n public void declareRoles(String... roleNames) {\n throw new UnsupportedOperationException(\"declareRoles() is not supported.\");\n }\n\n @Override\n public boolean setInitParameter(String name, String value) {\n throw new UnsupportedOperationException(\"setInitParameter() is not supported.\");\n }\n\n @Override\n public void setSessionTrackingModes(Set sessionTrackingModes) {\n throw new UnsupportedOperationException(\"setSessionTrackingModes() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addJspFile(String servletName, String jspFile) {\n throw new UnsupportedOperationException(\"addJspFile() is not supported.\");\n }\n\n // --- methods that are scoped to HttpContext/ServletContextHelper\n @Override\n public Object getAttribute(String name) {\n return osgiContext.getAttribute(name);\n }\n\n @Override\n public Enumeration getAttributeNames() {\n return osgiContext.getAttributeNames();\n }\n\n @Override\n public void setAttribute(String name, Object object) {\n osgiContext.setAttribute(name, object);\n }\n\n @Override\n public void removeAttribute(String name) {\n osgiContext.removeAttribute(name);\n }\n\n // --- methods simply delegating to server-specific ServletContext. Backed by the Servlet Container.\n @Override\n public String getContextPath() {\n return osgiContext.getContextPath();\n }\n\n @Override\n public ServletContext getContext(String uripath) {\n return osgiContext.getContext(uripath);\n }\n\n @Override\n public Set getDefaultSessionTrackingModes() {\n return osgiContext.getDefaultSessionTrackingModes();\n }\n\n @Override\n public int getEffectiveMajorVersion() {\n return osgiContext.getEffectiveMajorVersion();\n }\n\n @Override\n public int getEffectiveMinorVersion() {\n return osgiContext.getEffectiveMinorVersion();\n }\n\n @Override\n public Set getEffectiveSessionTrackingModes() {\n return osgiContext.getEffectiveSessionTrackingModes();\n }\n\n @Override\n public FilterRegistration getFilterRegistration(String filterName) {\n return osgiContext.getFilterRegistration(filterName);\n }\n\n @Override\n public Map getFilterRegistrations() {\n return osgiContext.getFilterRegistrations();\n }\n\n @Override\n public int getMajorVersion() {\n return osgiContext.getMajorVersion();\n }\n\n @Override\n public int getMinorVersion() {\n return osgiContext.getMinorVersion();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Servlet getServlet(String name) throws ServletException {\n return osgiContext.getServlet(name);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServletNames() {\n return osgiContext.getServletNames();\n }\n\n @Override\n public ServletRegistration getServletRegistration(String servletName) {\n return osgiContext.getServletRegistration(servletName);\n }\n\n @Override\n public Map getServletRegistrations() {\n return osgiContext.getServletRegistrations();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServlets() {\n return osgiContext.getServlets();\n }\n\n @Override\n public String getVirtualServerName() {\n return osgiContext.getVirtualServerName();\n }\n\n @Override\n public String getServerInfo() {\n return osgiContext.getServerInfo();\n }\n\n @Override\n public void log(String msg) {\n osgiContext.log(msg);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public void log(Exception exception, String msg) {\n osgiContext.log(exception, msg);\n }\n\n @Override\n public void log(String message, Throwable throwable) {\n osgiContext.log(message, throwable);\n }\n\n @Override\n public SessionCookieConfig getSessionCookieConfig() {\n return osgiContext.getSessionCookieConfig();\n }\n\n @Override\n public JspConfigDescriptor getJspConfigDescriptor() {\n return osgiContext.getJspConfigDescriptor();\n }\n\n // --- methods also delegating to server-specific ServletContext, but added in Servlet spec 4.0\n @Override\n public int getSessionTimeout() {\n return osgiContext.getSessionTimeout();\n }\n\n @Override\n public void setSessionTimeout(int sessionTimeout) {\n osgiContext.setSessionTimeout(sessionTimeout);\n }\n\n @Override\n public String getRequestCharacterEncoding() {\n return osgiContext.getRequestCharacterEncoding();\n }\n\n @Override\n public void setRequestCharacterEncoding(String encoding) {\n osgiContext.setRequestCharacterEncoding(encoding);\n }\n\n @Override\n public String getResponseCharacterEncoding() {\n return osgiContext.getResponseCharacterEncoding();\n }\n\n @Override\n public void setResponseCharacterEncoding(String encoding) {\n osgiContext.setResponseCharacterEncoding(encoding);\n }\n\n // --- methods backed by the ServletContextHelper.\n // some of them, that delegate to WebContainerContext have to use proper WebContainerContext - from\n // the bundle that was used to register the servlet, not from the bundle that registered target\n // HttpContext/ServletContextHelper\n @Override\n public String getMimeType(String file) {\n return osgiContext.getMimeType(webContainerContext, file);\n }\n\n @Override\n public String getRealPath(String path) {\n return osgiContext.getRealPath(webContainerContext, path);\n }\n\n @Override\n public URL getResource(String path) throws MalformedURLException {\n return osgiContext.getResource(webContainerContext, path);\n }\n\n @Override\n public InputStream getResourceAsStream(String path) {\n return osgiContext.getResourceAsStream(webContainerContext, path);\n }\n\n @Override\n public Set getResourcePaths(String path) {\n return osgiContext.getResourcePaths(webContainerContext, path);\n }\n\n // --- methods backed by the OsgiContextModel (object \"customized\" by trackers from ServletContextHelper)\n @Override\n public String getInitParameter(String name) {\n return osgiContext.getInitParameter(name);\n }\n\n @Override\n public Enumeration getInitParameterNames() {\n return osgiContext.getInitParameterNames();\n }\n\n @Override\n public RequestDispatcher getRequestDispatcher(String path) {\n return osgiContext.getRequestDispatcher(path);\n }\n\n @Override\n public RequestDispatcher getNamedDispatcher(String name) {\n return osgiContext.getNamedDispatcher(name);\n }\n\n @Override\n public String getServletContextName() {\n return osgiContext.getServletContextName();\n }\n\n // --- methods dependent on which actual servlet/filter uses the context\n @Override\n public ClassLoader getClassLoader() {\n // according to Whiteboard specification - this should be strictly a classloader of a bundle registering\n // the servlet/filter, but in case of WAB, we'll return the WAB's classloader (delegating to\n // all reachable bundles)\n if (getOsgiContextModel().isWab()) {\n return getOsgiContextModel().getClassLoader();\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1583", "language": "Java", "task_type": "single_line", "source_file": "java/github/ops4j/org.ops4j.pax.web/pax-web-spi/src/main/java/org/ops4j/pax/web/service/spi/servlet/OsgiScopedServletContext.java", "mask_start_position": 7359, "mask_end_position": 7361, "canonical_solution": ");", "pre_mask_code": "package org.ops4j.pax.web.service.spi.servlet;\n\nimport java.io.InputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.Enumeration;\nimport java.util.EventListener;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.Filter;\nimport javax.servlet.FilterRegistration;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.Servlet;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRegistration;\nimport javax.servlet.SessionCookieConfig;\nimport javax.servlet.SessionTrackingMode;\nimport javax.servlet.descriptor.JspConfigDescriptor;\nimport org.ops4j.pax.web.service.WebContainerContext;\nimport org.ops4j.pax.web.service.spi.model.OsgiContextModel;\nimport org.osgi.framework.Bundle;\nimport org.osgi.framework.wiring.BundleWiring;\n\n/**\n *

This class provides special {@link ServletContext#getClassLoader()} method for Whiteboard elements.\n * All Whiteboard services should use a {@link ServletContext} which uses single\n * {@link org.osgi.service.http.HttpContext} or {@link org.osgi.service.http.context.ServletContextHelper}, but\n * additionally, class loader should come from the bundle which registered the Whiteboard service (e.g., a servlet)\n * itself, not from the bundle that has registered the {@link org.osgi.service.http.context.ServletContextHelper}.

\n */\npublic class OsgiScopedServletContext implements ServletContext {\n\n /**\n * {@link org.ops4j.pax.web.service.spi.servlet.OsgiServletContext} to which the target servlet is registered.\n * Servlet itself can be registered in the scope of different {@link Bundle}, so actual\n * {@link org.ops4j.pax.web.service.WebContainerContext} has to be obtained/resolved within the scope of proper\n * {@link Bundle}.\n */\n private final OsgiServletContext osgiContext;\n\n /**\n * {@link Bundle} which was used to register target {@link javax.servlet.Servlet}\n */\n private final Bundle bundle;\n\n private final WebContainerContext webContainerContext;\n\n public OsgiScopedServletContext(OsgiServletContext osgiContext, Bundle bundle) {\n this.osgiContext = osgiContext;\n this.bundle = bundle;\n this.webContainerContext = osgiContext.getOsgiContextModel().resolveHttpContext(bundle);\n }\n\n public OsgiServletContext getOsgiContext() {\n return osgiContext;\n }\n\n public OsgiContextModel getOsgiContextModel() {\n return osgiContext.getOsgiContextModel();\n }\n\n public ServletContext getContainerServletContext() {\n return osgiContext.getContainerServletContext();\n }\n\n public ClassLoader getOsgiContextClassLoader() {\n return osgiContext.getClassLoader();\n }\n\n public String[] getWelcomeFiles() {\n return osgiContext.getWelcomeFiles();\n }\n\n public boolean isWelcomeFilesRedirect() {\n return osgiContext.isWelcomeFilesRedirect();\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, String className) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Class filterClass) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public void addListener(String className) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(T t) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(Class listenerClass) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, String className) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Class servletClass) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public T createFilter(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createFilter() is not supported.\");\n }\n\n @Override\n public T createListener(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createListener() is not supported.\");\n }\n\n @Override\n public T createServlet(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createServlet() is not supported.\");\n }\n\n @Override\n public void declareRoles(String... roleNames) {\n throw new UnsupportedOperationException(\"declareRoles() is not supported.\");\n }\n\n @Override\n public boolean setInitParameter(String name, String value) {\n throw new UnsupportedOperationException(\"setInitParameter() is not supported.\");\n }\n\n @Override\n public void setSessionTrackingModes(Set sessionTrackingModes) {\n throw new UnsupportedOperationException(\"setSessionTrackingModes() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addJspFile(String servletName, String jspFile) {\n throw new UnsupportedOperationException(\"addJspFile() is not supported.\");\n }\n\n // --- methods that are scoped to HttpContext/ServletContextHelper\n @Override\n public Object getAttribute(String name) {\n return osgiContext.getAttribute(name);\n }\n\n @Override\n public Enumeration getAttributeNames() {\n return osgiContext.getAttributeNames();\n }\n\n @Override\n public void setAttribute(String name, Object object) {\n osgiContext.setAttribute(name, object);\n }\n\n @Override\n public void removeAttribute(String name) {\n osgiContext.removeAttribute(name);\n }\n\n // --- methods simply delegating to server-specific ServletContext. Backed by the Servlet Container.\n @Override\n public String getContextPath() {\n return osgiContext.getContextPath();\n }\n\n @Override\n public ServletContext getContext(String uripath) {\n return osgiContext.getContext(uripath);\n }\n\n @Override\n public Set getDefaultSessionTrackingModes() {\n return osgiContext.getDefaultSessionTrackingModes();\n }\n\n @Override\n public int getEffectiveMajorVersion() {\n return osgiContext.getEffectiveMajorVersion();\n }\n\n @Override\n public int getEffectiveMinorVersion() {\n return osgiContext.getEffectiveMinorVersion();\n }\n\n @Override\n public Set getEffectiveSessionTrackingModes() {\n return osgiContext.getEffectiveSessionTrackingModes(", "post_mask_code": "\n }\n\n @Override\n public FilterRegistration getFilterRegistration(String filterName) {\n return osgiContext.getFilterRegistration(filterName);\n }\n\n @Override\n public Map getFilterRegistrations() {\n return osgiContext.getFilterRegistrations();\n }\n\n @Override\n public int getMajorVersion() {\n return osgiContext.getMajorVersion();\n }\n\n @Override\n public int getMinorVersion() {\n return osgiContext.getMinorVersion();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Servlet getServlet(String name) throws ServletException {\n return osgiContext.getServlet(name);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServletNames() {\n return osgiContext.getServletNames();\n }\n\n @Override\n public ServletRegistration getServletRegistration(String servletName) {\n return osgiContext.getServletRegistration(servletName);\n }\n\n @Override\n public Map getServletRegistrations() {\n return osgiContext.getServletRegistrations();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServlets() {\n return osgiContext.getServlets();\n }\n\n @Override\n public String getVirtualServerName() {\n return osgiContext.getVirtualServerName();\n }\n\n @Override\n public String getServerInfo() {\n return osgiContext.getServerInfo();\n }\n\n @Override\n public void log(String msg) {\n osgiContext.log(msg);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public void log(Exception exception, String msg) {\n osgiContext.log(exception, msg);\n }\n\n @Override\n public void log(String message, Throwable throwable) {\n osgiContext.log(message, throwable);\n }\n\n @Override\n public SessionCookieConfig getSessionCookieConfig() {\n return osgiContext.getSessionCookieConfig();\n }\n\n @Override\n public JspConfigDescriptor getJspConfigDescriptor() {\n return osgiContext.getJspConfigDescriptor();\n }\n\n // --- methods also delegating to server-specific ServletContext, but added in Servlet spec 4.0\n @Override\n public int getSessionTimeout() {\n return osgiContext.getSessionTimeout();\n }\n\n @Override\n public void setSessionTimeout(int sessionTimeout) {\n osgiContext.setSessionTimeout(sessionTimeout);\n }\n\n @Override\n public String getRequestCharacterEncoding() {\n return osgiContext.getRequestCharacterEncoding();\n }\n\n @Override\n public void setRequestCharacterEncoding(String encoding) {\n osgiContext.setRequestCharacterEncoding(encoding);\n }\n\n @Override\n public String getResponseCharacterEncoding() {\n return osgiContext.getResponseCharacterEncoding();\n }\n\n @Override\n public void setResponseCharacterEncoding(String encoding) {\n osgiContext.setResponseCharacterEncoding(encoding);\n }\n\n // --- methods backed by the ServletContextHelper.\n // some of them, that delegate to WebContainerContext have to use proper WebContainerContext - from\n // the bundle that was used to register the servlet, not from the bundle that registered target\n // HttpContext/ServletContextHelper\n @Override\n public String getMimeType(String file) {\n return osgiContext.getMimeType(webContainerContext, file);\n }\n\n @Override\n public String getRealPath(String path) {\n return osgiContext.getRealPath(webContainerContext, path);\n }\n\n @Override\n public URL getResource(String path) throws MalformedURLException {\n return osgiContext.getResource(webContainerContext, path);\n }\n\n @Override\n public InputStream getResourceAsStream(String path) {\n return osgiContext.getResourceAsStream(webContainerContext, path);\n }\n\n @Override\n public Set getResourcePaths(String path) {\n return osgiContext.getResourcePaths(webContainerContext, path);\n }\n\n // --- methods backed by the OsgiContextModel (object \"customized\" by trackers from ServletContextHelper)\n @Override\n public String getInitParameter(String name) {\n return osgiContext.getInitParameter(name);\n }\n\n @Override\n public Enumeration getInitParameterNames() {\n return osgiContext.getInitParameterNames();\n }\n\n @Override\n public RequestDispatcher getRequestDispatcher(String path) {\n return osgiContext.getRequestDispatcher(path);\n }\n\n @Override\n public RequestDispatcher getNamedDispatcher(String name) {\n return osgiContext.getNamedDispatcher(name);\n }\n\n @Override\n public String getServletContextName() {\n return osgiContext.getServletContextName();\n }\n\n // --- methods dependent on which actual servlet/filter uses the context\n @Override\n public ClassLoader getClassLoader() {\n // according to Whiteboard specification - this should be strictly a classloader of a bundle registering\n // the servlet/filter, but in case of WAB, we'll return the WAB's classloader (delegating to\n // all reachable bundles)\n if (getOsgiContextModel().isWab()) {\n return getOsgiContextModel().getClassLoader();\n }\n return bundle.adapt(BundleWiring.class).getClassLoader();\n }\n}\n"} {"task_id": "Java_1584", "language": "Java", "task_type": "if_statement", "source_file": "java/github/ops4j/org.ops4j.pax.web/pax-web-spi/src/main/java/org/ops4j/pax/web/service/spi/servlet/OsgiScopedServletContext.java", "mask_start_position": 12690, "mask_end_position": 12795, "canonical_solution": "if (getOsgiContextModel().isWab()) {\n return getOsgiContextModel().getClassLoader();\n }", "pre_mask_code": "package org.ops4j.pax.web.service.spi.servlet;\n\nimport java.io.InputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.Enumeration;\nimport java.util.EventListener;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.servlet.Filter;\nimport javax.servlet.FilterRegistration;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.Servlet;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRegistration;\nimport javax.servlet.SessionCookieConfig;\nimport javax.servlet.SessionTrackingMode;\nimport javax.servlet.descriptor.JspConfigDescriptor;\nimport org.ops4j.pax.web.service.WebContainerContext;\nimport org.ops4j.pax.web.service.spi.model.OsgiContextModel;\nimport org.osgi.framework.Bundle;\nimport org.osgi.framework.wiring.BundleWiring;\n\n/**\n *

This class provides special {@link ServletContext#getClassLoader()} method for Whiteboard elements.\n * All Whiteboard services should use a {@link ServletContext} which uses single\n * {@link org.osgi.service.http.HttpContext} or {@link org.osgi.service.http.context.ServletContextHelper}, but\n * additionally, class loader should come from the bundle which registered the Whiteboard service (e.g., a servlet)\n * itself, not from the bundle that has registered the {@link org.osgi.service.http.context.ServletContextHelper}.

\n */\npublic class OsgiScopedServletContext implements ServletContext {\n\n /**\n * {@link org.ops4j.pax.web.service.spi.servlet.OsgiServletContext} to which the target servlet is registered.\n * Servlet itself can be registered in the scope of different {@link Bundle}, so actual\n * {@link org.ops4j.pax.web.service.WebContainerContext} has to be obtained/resolved within the scope of proper\n * {@link Bundle}.\n */\n private final OsgiServletContext osgiContext;\n\n /**\n * {@link Bundle} which was used to register target {@link javax.servlet.Servlet}\n */\n private final Bundle bundle;\n\n private final WebContainerContext webContainerContext;\n\n public OsgiScopedServletContext(OsgiServletContext osgiContext, Bundle bundle) {\n this.osgiContext = osgiContext;\n this.bundle = bundle;\n this.webContainerContext = osgiContext.getOsgiContextModel().resolveHttpContext(bundle);\n }\n\n public OsgiServletContext getOsgiContext() {\n return osgiContext;\n }\n\n public OsgiContextModel getOsgiContextModel() {\n return osgiContext.getOsgiContextModel();\n }\n\n public ServletContext getContainerServletContext() {\n return osgiContext.getContainerServletContext();\n }\n\n public ClassLoader getOsgiContextClassLoader() {\n return osgiContext.getClassLoader();\n }\n\n public String[] getWelcomeFiles() {\n return osgiContext.getWelcomeFiles();\n }\n\n public boolean isWelcomeFilesRedirect() {\n return osgiContext.isWelcomeFilesRedirect();\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, String className) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public FilterRegistration.Dynamic addFilter(String filterName, Class filterClass) {\n throw new UnsupportedOperationException(\"addFilter() is not supported.\");\n }\n\n @Override\n public void addListener(String className) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(T t) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public void addListener(Class listenerClass) {\n throw new UnsupportedOperationException(\"addListener() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, String className) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addServlet(String servletName, Class servletClass) {\n throw new UnsupportedOperationException(\"addServlet() is not supported.\");\n }\n\n @Override\n public T createFilter(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createFilter() is not supported.\");\n }\n\n @Override\n public T createListener(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createListener() is not supported.\");\n }\n\n @Override\n public T createServlet(Class clazz) throws ServletException {\n throw new UnsupportedOperationException(\"createServlet() is not supported.\");\n }\n\n @Override\n public void declareRoles(String... roleNames) {\n throw new UnsupportedOperationException(\"declareRoles() is not supported.\");\n }\n\n @Override\n public boolean setInitParameter(String name, String value) {\n throw new UnsupportedOperationException(\"setInitParameter() is not supported.\");\n }\n\n @Override\n public void setSessionTrackingModes(Set sessionTrackingModes) {\n throw new UnsupportedOperationException(\"setSessionTrackingModes() is not supported.\");\n }\n\n @Override\n public ServletRegistration.Dynamic addJspFile(String servletName, String jspFile) {\n throw new UnsupportedOperationException(\"addJspFile() is not supported.\");\n }\n\n // --- methods that are scoped to HttpContext/ServletContextHelper\n @Override\n public Object getAttribute(String name) {\n return osgiContext.getAttribute(name);\n }\n\n @Override\n public Enumeration getAttributeNames() {\n return osgiContext.getAttributeNames();\n }\n\n @Override\n public void setAttribute(String name, Object object) {\n osgiContext.setAttribute(name, object);\n }\n\n @Override\n public void removeAttribute(String name) {\n osgiContext.removeAttribute(name);\n }\n\n // --- methods simply delegating to server-specific ServletContext. Backed by the Servlet Container.\n @Override\n public String getContextPath() {\n return osgiContext.getContextPath();\n }\n\n @Override\n public ServletContext getContext(String uripath) {\n return osgiContext.getContext(uripath);\n }\n\n @Override\n public Set getDefaultSessionTrackingModes() {\n return osgiContext.getDefaultSessionTrackingModes();\n }\n\n @Override\n public int getEffectiveMajorVersion() {\n return osgiContext.getEffectiveMajorVersion();\n }\n\n @Override\n public int getEffectiveMinorVersion() {\n return osgiContext.getEffectiveMinorVersion();\n }\n\n @Override\n public Set getEffectiveSessionTrackingModes() {\n return osgiContext.getEffectiveSessionTrackingModes();\n }\n\n @Override\n public FilterRegistration getFilterRegistration(String filterName) {\n return osgiContext.getFilterRegistration(filterName);\n }\n\n @Override\n public Map getFilterRegistrations() {\n return osgiContext.getFilterRegistrations();\n }\n\n @Override\n public int getMajorVersion() {\n return osgiContext.getMajorVersion();\n }\n\n @Override\n public int getMinorVersion() {\n return osgiContext.getMinorVersion();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Servlet getServlet(String name) throws ServletException {\n return osgiContext.getServlet(name);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServletNames() {\n return osgiContext.getServletNames();\n }\n\n @Override\n public ServletRegistration getServletRegistration(String servletName) {\n return osgiContext.getServletRegistration(servletName);\n }\n\n @Override\n public Map getServletRegistrations() {\n return osgiContext.getServletRegistrations();\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public Enumeration getServlets() {\n return osgiContext.getServlets();\n }\n\n @Override\n public String getVirtualServerName() {\n return osgiContext.getVirtualServerName();\n }\n\n @Override\n public String getServerInfo() {\n return osgiContext.getServerInfo();\n }\n\n @Override\n public void log(String msg) {\n osgiContext.log(msg);\n }\n\n @Override\n @SuppressWarnings({ \"deprecation\", \"RedundantSuppression\" })\n public void log(Exception exception, String msg) {\n osgiContext.log(exception, msg);\n }\n\n @Override\n public void log(String message, Throwable throwable) {\n osgiContext.log(message, throwable);\n }\n\n @Override\n public SessionCookieConfig getSessionCookieConfig() {\n return osgiContext.getSessionCookieConfig();\n }\n\n @Override\n public JspConfigDescriptor getJspConfigDescriptor() {\n return osgiContext.getJspConfigDescriptor();\n }\n\n // --- methods also delegating to server-specific ServletContext, but added in Servlet spec 4.0\n @Override\n public int getSessionTimeout() {\n return osgiContext.getSessionTimeout();\n }\n\n @Override\n public void setSessionTimeout(int sessionTimeout) {\n osgiContext.setSessionTimeout(sessionTimeout);\n }\n\n @Override\n public String getRequestCharacterEncoding() {\n return osgiContext.getRequestCharacterEncoding();\n }\n\n @Override\n public void setRequestCharacterEncoding(String encoding) {\n osgiContext.setRequestCharacterEncoding(encoding);\n }\n\n @Override\n public String getResponseCharacterEncoding() {\n return osgiContext.getResponseCharacterEncoding();\n }\n\n @Override\n public void setResponseCharacterEncoding(String encoding) {\n osgiContext.setResponseCharacterEncoding(encoding);\n }\n\n // --- methods backed by the ServletContextHelper.\n // some of them, that delegate to WebContainerContext have to use proper WebContainerContext - from\n // the bundle that was used to register the servlet, not from the bundle that registered target\n // HttpContext/ServletContextHelper\n @Override\n public String getMimeType(String file) {\n return osgiContext.getMimeType(webContainerContext, file);\n }\n\n @Override\n public String getRealPath(String path) {\n return osgiContext.getRealPath(webContainerContext, path);\n }\n\n @Override\n public URL getResource(String path) throws MalformedURLException {\n return osgiContext.getResource(webContainerContext, path);\n }\n\n @Override\n public InputStream getResourceAsStream(String path) {\n return osgiContext.getResourceAsStream(webContainerContext, path);\n }\n\n @Override\n public Set getResourcePaths(String path) {\n return osgiContext.getResourcePaths(webContainerContext, path);\n }\n\n // --- methods backed by the OsgiContextModel (object \"customized\" by trackers from ServletContextHelper)\n @Override\n public String getInitParameter(String name) {\n return osgiContext.getInitParameter(name);\n }\n\n @Override\n public Enumeration getInitParameterNames() {\n return osgiContext.getInitParameterNames();\n }\n\n @Override\n public RequestDispatcher getRequestDispatcher(String path) {\n return osgiContext.getRequestDispatcher(path);\n }\n\n @Override\n public RequestDispatcher getNamedDispatcher(String name) {\n return osgiContext.getNamedDispatcher(name);\n }\n\n @Override\n public String getServletContextName() {\n return osgiContext.getServletContextName();\n }\n\n // --- methods dependent on which actual servlet/filter uses the context\n @Override\n public ClassLoader getClassLoader() {\n // according to Whiteboard specification - this should be strictly a classloader of a bundle registering\n // the servlet/filter, but in case of WAB, we'll return the WAB's classloader (delegating to\n // all reachable bundles)\n ", "post_mask_code": "\n return bundle.adapt(BundleWiring.class).getClassLoader();\n }\n}\n"} {"task_id": "Java_1585", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openhab/openhab-addons/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/fields/ByteField.java", "mask_start_position": 601, "mask_end_position": 665, "canonical_solution": "@Override\n public ByteBuffer bytesInternal(ByteBuffer value) ", "pre_mask_code": "package org.openhab.binding.lifx.internal.fields;\n\nimport java.nio.ByteBuffer;\nimport org.eclipse.jdt.annotation.NonNullByDefault;\n\n/**\n * @author Tim Buckley - Initial contribution\n */\n@NonNullByDefault\npublic class ByteField extends Field {\n\n public ByteField() {\n }\n\n public ByteField(int length) {\n super(length);\n }\n\n @Override\n public int defaultLength() {\n return 2;\n }\n\n @Override\n public ByteBuffer value(ByteBuffer bytes) {\n byte[] data = new byte[length];\n bytes.get(data);\n return ByteBuffer.wrap(data);\n }\n\n ", "post_mask_code": "{\n return value;\n }\n}\n"} {"task_id": "Java_1586", "language": "Java", "task_type": "method_body", "source_file": "java/github/openhab/openhab-addons/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/fields/ByteField.java", "mask_start_position": 665, "mask_end_position": 694, "canonical_solution": "{\n return value;\n }", "pre_mask_code": "package org.openhab.binding.lifx.internal.fields;\n\nimport java.nio.ByteBuffer;\nimport org.eclipse.jdt.annotation.NonNullByDefault;\n\n/**\n * @author Tim Buckley - Initial contribution\n */\n@NonNullByDefault\npublic class ByteField extends Field {\n\n public ByteField() {\n }\n\n public ByteField(int length) {\n super(length);\n }\n\n @Override\n public int defaultLength() {\n return 2;\n }\n\n @Override\n public ByteBuffer value(ByteBuffer bytes) {\n byte[] data = new byte[length];\n bytes.get(data);\n return ByteBuffer.wrap(data);\n }\n\n @Override\n public ByteBuffer bytesInternal(ByteBuffer value) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1587", "language": "Java", "task_type": "single_line", "source_file": "java/github/openhab/openhab-addons/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/fields/ByteField.java", "mask_start_position": 679, "mask_end_position": 688, "canonical_solution": "rn value;", "pre_mask_code": "package org.openhab.binding.lifx.internal.fields;\n\nimport java.nio.ByteBuffer;\nimport org.eclipse.jdt.annotation.NonNullByDefault;\n\n/**\n * @author Tim Buckley - Initial contribution\n */\n@NonNullByDefault\npublic class ByteField extends Field {\n\n public ByteField() {\n }\n\n public ByteField(int length) {\n super(length);\n }\n\n @Override\n public int defaultLength() {\n return 2;\n }\n\n @Override\n public ByteBuffer value(ByteBuffer bytes) {\n byte[] data = new byte[length];\n bytes.get(data);\n return ByteBuffer.wrap(data);\n }\n\n @Override\n public ByteBuffer bytesInternal(ByteBuffer value) {\n retu", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1588", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Mighty16/JSONToKotlinClass/src/com/mighty16/json/IDEFileSaver.java", "mask_start_position": 644, "mask_end_position": 716, "canonical_solution": "@Override\n public void saveFile(String fileName, String fileContent) ", "pre_mask_code": "package com.mighty16.json;\n\nimport com.intellij.openapi.command.WriteCommandAction;\nimport com.intellij.openapi.fileTypes.FileType;\nimport com.intellij.psi.PsiDirectory;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.psi.PsiFileFactory;\nimport com.mighty16.json.core.FileSaver;\n\npublic class IDEFileSaver extends FileSaver {\n\n private PsiDirectory directory;\n\n private PsiFileFactory factory;\n\n private FileType fileType;\n\n public IDEFileSaver(PsiFileFactory factory, PsiDirectory directory, FileType fileType) {\n this.directory = directory;\n this.factory = factory;\n this.fileType = fileType;\n }\n\n ", "post_mask_code": "{\n PsiFile classFile = factory.createFileFromText(fileName, fileType, fileContent);\n PsiFile oldFile = directory.findFile(fileName);\n if (oldFile != null) {\n if (listener != null && listener.shouldOverwriteFile(fileName)) {\n WriteCommandAction.runWriteCommandAction(directory.getProject(), () -> {\n oldFile.delete();\n directory.add(classFile);\n });\n }\n } else {\n WriteCommandAction.runWriteCommandAction(directory.getProject(), () -> {\n directory.add(classFile);\n });\n }\n }\n}\n"} {"task_id": "Java_1589", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Mighty16/JSONToKotlinClass/src/com/mighty16/json/IDEFileSaver.java", "mask_start_position": 717, "mask_end_position": 806, "canonical_solution": "\n PsiFile classFile = factory.createFileFromText(fileName, fileType, fileContent);", "pre_mask_code": "package com.mighty16.json;\n\nimport com.intellij.openapi.command.WriteCommandAction;\nimport com.intellij.openapi.fileTypes.FileType;\nimport com.intellij.psi.PsiDirectory;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.psi.PsiFileFactory;\nimport com.mighty16.json.core.FileSaver;\n\npublic class IDEFileSaver extends FileSaver {\n\n private PsiDirectory directory;\n\n private PsiFileFactory factory;\n\n private FileType fileType;\n\n public IDEFileSaver(PsiFileFactory factory, PsiDirectory directory, FileType fileType) {\n this.directory = directory;\n this.factory = factory;\n this.fileType = fileType;\n }\n\n @Override\n public void saveFile(String fileName, String fileContent) {", "post_mask_code": "\n PsiFile oldFile = directory.findFile(fileName);\n if (oldFile != null) {\n if (listener != null && listener.shouldOverwriteFile(fileName)) {\n WriteCommandAction.runWriteCommandAction(directory.getProject(), () -> {\n oldFile.delete();\n directory.add(classFile);\n });\n }\n } else {\n WriteCommandAction.runWriteCommandAction(directory.getProject(), () -> {\n directory.add(classFile);\n });\n }\n }\n}\n"} {"task_id": "Java_1590", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Mighty16/JSONToKotlinClass/src/com/mighty16/json/IDEFileSaver.java", "mask_start_position": 815, "mask_end_position": 862, "canonical_solution": "PsiFile oldFile = directory.findFile(fileName);", "pre_mask_code": "package com.mighty16.json;\n\nimport com.intellij.openapi.command.WriteCommandAction;\nimport com.intellij.openapi.fileTypes.FileType;\nimport com.intellij.psi.PsiDirectory;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.psi.PsiFileFactory;\nimport com.mighty16.json.core.FileSaver;\n\npublic class IDEFileSaver extends FileSaver {\n\n private PsiDirectory directory;\n\n private PsiFileFactory factory;\n\n private FileType fileType;\n\n public IDEFileSaver(PsiFileFactory factory, PsiDirectory directory, FileType fileType) {\n this.directory = directory;\n this.factory = factory;\n this.fileType = fileType;\n }\n\n @Override\n public void saveFile(String fileName, String fileContent) {\n PsiFile classFile = factory.createFileFromText(fileName, fileType, fileContent);\n ", "post_mask_code": "\n if (oldFile != null) {\n if (listener != null && listener.shouldOverwriteFile(fileName)) {\n WriteCommandAction.runWriteCommandAction(directory.getProject(), () -> {\n oldFile.delete();\n directory.add(classFile);\n });\n }\n } else {\n WriteCommandAction.runWriteCommandAction(directory.getProject(), () -> {\n directory.add(classFile);\n });\n }\n }\n}\n"} {"task_id": "Java_1591", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Mighty16/JSONToKotlinClass/src/com/mighty16/json/IDEFileSaver.java", "mask_start_position": 871, "mask_end_position": 1354, "canonical_solution": "if (oldFile != null) {\n if (listener != null && listener.shouldOverwriteFile(fileName)) {\n WriteCommandAction.runWriteCommandAction(directory.getProject(), () -> {\n oldFile.delete();\n directory.add(classFile);\n });\n }\n } else {\n WriteCommandAction.runWriteCommandAction(directory.getProject(), () -> {\n directory.add(classFile);\n });\n }\n }", "pre_mask_code": "package com.mighty16.json;\n\nimport com.intellij.openapi.command.WriteCommandAction;\nimport com.intellij.openapi.fileTypes.FileType;\nimport com.intellij.psi.PsiDirectory;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.psi.PsiFileFactory;\nimport com.mighty16.json.core.FileSaver;\n\npublic class IDEFileSaver extends FileSaver {\n\n private PsiDirectory directory;\n\n private PsiFileFactory factory;\n\n private FileType fileType;\n\n public IDEFileSaver(PsiFileFactory factory, PsiDirectory directory, FileType fileType) {\n this.directory = directory;\n this.factory = factory;\n this.fileType = fileType;\n }\n\n @Override\n public void saveFile(String fileName, String fileContent) {\n PsiFile classFile = factory.createFileFromText(fileName, fileType, fileContent);\n PsiFile oldFile = directory.findFile(fileName);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1592", "language": "Java", "task_type": "single_line", "source_file": "java/github/Mighty16/JSONToKotlinClass/src/com/mighty16/json/IDEFileSaver.java", "mask_start_position": 800, "mask_end_position": 806, "canonical_solution": "tent);", "pre_mask_code": "package com.mighty16.json;\n\nimport com.intellij.openapi.command.WriteCommandAction;\nimport com.intellij.openapi.fileTypes.FileType;\nimport com.intellij.psi.PsiDirectory;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.psi.PsiFileFactory;\nimport com.mighty16.json.core.FileSaver;\n\npublic class IDEFileSaver extends FileSaver {\n\n private PsiDirectory directory;\n\n private PsiFileFactory factory;\n\n private FileType fileType;\n\n public IDEFileSaver(PsiFileFactory factory, PsiDirectory directory, FileType fileType) {\n this.directory = directory;\n this.factory = factory;\n this.fileType = fileType;\n }\n\n @Override\n public void saveFile(String fileName, String fileContent) {\n PsiFile classFile = factory.createFileFromText(fileName, fileType, fileCon", "post_mask_code": "\n PsiFile oldFile = directory.findFile(fileName);\n if (oldFile != null) {\n if (listener != null && listener.shouldOverwriteFile(fileName)) {\n WriteCommandAction.runWriteCommandAction(directory.getProject(), () -> {\n oldFile.delete();\n directory.add(classFile);\n });\n }\n } else {\n WriteCommandAction.runWriteCommandAction(directory.getProject(), () -> {\n directory.add(classFile);\n });\n }\n }\n}\n"} {"task_id": "Java_1593", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Mighty16/JSONToKotlinClass/src/com/mighty16/json/IDEFileSaver.java", "mask_start_position": 871, "mask_end_position": 1348, "canonical_solution": "if (oldFile != null) {\n if (listener != null && listener.shouldOverwriteFile(fileName)) {\n WriteCommandAction.runWriteCommandAction(directory.getProject(), () -> {\n oldFile.delete();\n directory.add(classFile);\n });\n }\n } else {\n WriteCommandAction.runWriteCommandAction(directory.getProject(), () -> {\n directory.add(classFile);\n });\n }", "pre_mask_code": "package com.mighty16.json;\n\nimport com.intellij.openapi.command.WriteCommandAction;\nimport com.intellij.openapi.fileTypes.FileType;\nimport com.intellij.psi.PsiDirectory;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.psi.PsiFileFactory;\nimport com.mighty16.json.core.FileSaver;\n\npublic class IDEFileSaver extends FileSaver {\n\n private PsiDirectory directory;\n\n private PsiFileFactory factory;\n\n private FileType fileType;\n\n public IDEFileSaver(PsiFileFactory factory, PsiDirectory directory, FileType fileType) {\n this.directory = directory;\n this.factory = factory;\n this.fileType = fileType;\n }\n\n @Override\n public void saveFile(String fileName, String fileContent) {\n PsiFile classFile = factory.createFileFromText(fileName, fileType, fileContent);\n PsiFile oldFile = directory.findFile(fileName);\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1594", "language": "Java", "task_type": "method_signature", "source_file": "java/github/onlyliuxin/coding2017/students/1058267830/newMail/src/com/coderising/ood/srp/Product.java", "mask_start_position": 516, "mask_end_position": 563, "canonical_solution": "public void setProductDesc(String productDesc) ", "pre_mask_code": "package com.coderising.ood.srp;\n\npublic class Product {\n\n private String productId;\n\n private String productDesc;\n\n public Product(String productId, String productDesc) {\n super();\n this.productId = productId;\n this.productDesc = productDesc;\n }\n\n public String getProductId() {\n return productId;\n }\n\n public void setProductId(String productId) {\n this.productId = productId;\n }\n\n public String getProductDesc() {\n return productDesc;\n }\n\n ", "post_mask_code": "{\n this.productDesc = productDesc;\n }\n}\n"} {"task_id": "Java_1595", "language": "Java", "task_type": "method_body", "source_file": "java/github/onlyliuxin/coding2017/students/1058267830/newMail/src/com/coderising/ood/srp/Product.java", "mask_start_position": 313, "mask_end_position": 346, "canonical_solution": "{\n return productId;\n }", "pre_mask_code": "package com.coderising.ood.srp;\n\npublic class Product {\n\n private String productId;\n\n private String productDesc;\n\n public Product(String productId, String productDesc) {\n super();\n this.productId = productId;\n this.productDesc = productDesc;\n }\n\n public String getProductId() ", "post_mask_code": "\n\n public void setProductId(String productId) {\n this.productId = productId;\n }\n\n public String getProductDesc() {\n return productDesc;\n }\n\n public void setProductDesc(String productDesc) {\n this.productDesc = productDesc;\n }\n}\n"} {"task_id": "Java_1596", "language": "Java", "task_type": "single_line", "source_file": "java/github/onlyliuxin/coding2017/students/1058267830/newMail/src/com/coderising/ood/srp/Product.java", "mask_start_position": 587, "mask_end_position": 604, "canonical_solution": "sc = productDesc;", "pre_mask_code": "package com.coderising.ood.srp;\n\npublic class Product {\n\n private String productId;\n\n private String productDesc;\n\n public Product(String productId, String productDesc) {\n super();\n this.productId = productId;\n this.productDesc = productDesc;\n }\n\n public String getProductId() {\n return productId;\n }\n\n public void setProductId(String productId) {\n this.productId = productId;\n }\n\n public String getProductDesc() {\n return productDesc;\n }\n\n public void setProductDesc(String productDesc) {\n this.productDe", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1597", "language": "Java", "task_type": "method_signature", "source_file": "java/github/JetBrains/android/android/testData/refactoring/migrateToAndroidx/MainActivity_after.java", "mask_start_position": 211, "mask_end_position": 276, "canonical_solution": "@Override\n protected void onCreate(Bundle savedInstanceState) ", "pre_mask_code": "package p1.p2;\n\nimport androidx.app.AppCompatActivity;\nimport androidx.widget.CoordinatorLayout;\nimport android.os.Bundle;\n\npublic class MainActivity extends AppCompatActivity {\n\n CoordinatorLayout lay;\n\n ", "post_mask_code": "{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n CoordinatorLayout layout = findViewById(R.id.layout);\n }\n}\n"} {"task_id": "Java_1598", "language": "Java", "task_type": "method_body", "source_file": "java/github/JetBrains/android/android/testData/refactoring/migrateToAndroidx/MainActivity_after.java", "mask_start_position": 276, "mask_end_position": 437, "canonical_solution": "{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n CoordinatorLayout layout = findViewById(R.id.layout);\n }", "pre_mask_code": "package p1.p2;\n\nimport androidx.app.AppCompatActivity;\nimport androidx.widget.CoordinatorLayout;\nimport android.os.Bundle;\n\npublic class MainActivity extends AppCompatActivity {\n\n CoordinatorLayout lay;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1599", "language": "Java", "task_type": "single_line", "source_file": "java/github/JetBrains/android/android/testData/refactoring/migrateToAndroidx/MainActivity_after.java", "mask_start_position": 351, "mask_end_position": 369, "canonical_solution": "ut.activity_main);", "pre_mask_code": "package p1.p2;\n\nimport androidx.app.AppCompatActivity;\nimport androidx.widget.CoordinatorLayout;\nimport android.os.Bundle;\n\npublic class MainActivity extends AppCompatActivity {\n\n CoordinatorLayout lay;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layo", "post_mask_code": "\n CoordinatorLayout layout = findViewById(R.id.layout);\n }\n}\n"} {"task_id": "Java_1600", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/solr/solr/core/src/java/org/apache/solr/search/FunctionQParserPlugin.java", "mask_start_position": 375, "mask_end_position": 495, "canonical_solution": "@Override\n public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) ", "pre_mask_code": "package org.apache.solr.search;\n\nimport org.apache.solr.common.params.SolrParams;\nimport org.apache.solr.request.SolrQueryRequest;\n\n/**\n * Create a function query from the input value.\n *
Other parameters: none\n *
Example: {!func}log(foo)\n */\npublic class FunctionQParserPlugin extends QParserPlugin {\n\n public static final String NAME = \"func\";\n\n ", "post_mask_code": "{\n return new FunctionQParser(qstr, localParams, params, req);\n }\n}\n"} {"task_id": "Java_1601", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/solr/solr/core/src/java/org/apache/solr/search/FunctionQParserPlugin.java", "mask_start_position": 495, "mask_end_position": 570, "canonical_solution": "{\n return new FunctionQParser(qstr, localParams, params, req);\n }", "pre_mask_code": "package org.apache.solr.search;\n\nimport org.apache.solr.common.params.SolrParams;\nimport org.apache.solr.request.SolrQueryRequest;\n\n/**\n * Create a function query from the input value.\n *
Other parameters: none\n *
Example: {!func}log(foo)\n */\npublic class FunctionQParserPlugin extends QParserPlugin {\n\n public static final String NAME = \"func\";\n\n @Override\n public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1602", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/solr/solr/core/src/java/org/apache/solr/search/FunctionQParserPlugin.java", "mask_start_position": 556, "mask_end_position": 564, "canonical_solution": "s, req);", "pre_mask_code": "package org.apache.solr.search;\n\nimport org.apache.solr.common.params.SolrParams;\nimport org.apache.solr.request.SolrQueryRequest;\n\n/**\n * Create a function query from the input value.\n *
Other parameters: none\n *
Example: {!func}log(foo)\n */\npublic class FunctionQParserPlugin extends QParserPlugin {\n\n public static final String NAME = \"func\";\n\n @Override\n public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {\n return new FunctionQParser(qstr, localParams, param", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1603", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/karaf/obr/src/main/java/org/apache/karaf/obr/command/SourceCommand.java", "mask_start_position": 1184, "mask_end_position": 1249, "canonical_solution": "protected void doExecute(RepositoryAdmin admin) throws Exception ", "pre_mask_code": "package org.apache.karaf.obr.command;\n\nimport java.net.URI;\nimport java.util.List;\nimport org.apache.felix.bundlerepository.RepositoryAdmin;\nimport org.apache.felix.bundlerepository.Resource;\nimport org.apache.karaf.obr.command.util.FileUtil;\nimport org.apache.karaf.shell.api.action.Argument;\nimport org.apache.karaf.shell.api.action.Command;\nimport org.apache.karaf.shell.api.action.Option;\nimport org.apache.karaf.shell.api.action.lifecycle.Service;\n\n@Command(scope = \"obr\", name = \"source\", description = \"Downloads the sources for an OBR bundle.\")\n@Service\npublic class SourceCommand extends ObrCommandSupport {\n\n @Option(name = \"-x\", aliases = {}, description = \"Extract the archive\", required = false, multiValued = false)\n boolean extract;\n\n @Argument(index = 0, name = \"folder\", description = \"Local folder for storing sources\", required = true, multiValued = false)\n String localDir;\n\n @Argument(index = 1, name = \"bundles\", description = \"List of bundles to download the sources for. The bundles are identified using the following syntax: symbolic_name,version where version is optional.\", required = true, multiValued = true)\n List bundles;\n\n ", "post_mask_code": "{\n for (String bundle : bundles) {\n String[] target = getTarget(bundle);\n Resource resource = selectNewestVersion(searchRepository(admin, target[0], target[1]));\n if (resource == null) {\n System.err.println(\"Unknown bundle and/or version: \" + target[0]);\n } else {\n URI srcURL = (URI) resource.getProperties().get(Resource.SOURCE_URI);\n if (srcURL != null) {\n FileUtil.downloadSource(System.out, System.err, srcURL.toURL(), localDir, extract);\n } else {\n System.err.println(\"Missing source URL: \" + target[0]);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_1604", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/karaf/obr/src/main/java/org/apache/karaf/obr/command/SourceCommand.java", "mask_start_position": 1250, "mask_end_position": 1250, "canonical_solution": "", "pre_mask_code": "package org.apache.karaf.obr.command;\n\nimport java.net.URI;\nimport java.util.List;\nimport org.apache.felix.bundlerepository.RepositoryAdmin;\nimport org.apache.felix.bundlerepository.Resource;\nimport org.apache.karaf.obr.command.util.FileUtil;\nimport org.apache.karaf.shell.api.action.Argument;\nimport org.apache.karaf.shell.api.action.Command;\nimport org.apache.karaf.shell.api.action.Option;\nimport org.apache.karaf.shell.api.action.lifecycle.Service;\n\n@Command(scope = \"obr\", name = \"source\", description = \"Downloads the sources for an OBR bundle.\")\n@Service\npublic class SourceCommand extends ObrCommandSupport {\n\n @Option(name = \"-x\", aliases = {}, description = \"Extract the archive\", required = false, multiValued = false)\n boolean extract;\n\n @Argument(index = 0, name = \"folder\", description = \"Local folder for storing sources\", required = true, multiValued = false)\n String localDir;\n\n @Argument(index = 1, name = \"bundles\", description = \"List of bundles to download the sources for. The bundles are identified using the following syntax: symbolic_name,version where version is optional.\", required = true, multiValued = true)\n List bundles;\n\n protected void doExecute(RepositoryAdmin admin) throws Exception {", "post_mask_code": "\n for (String bundle : bundles) {\n String[] target = getTarget(bundle);\n Resource resource = selectNewestVersion(searchRepository(admin, target[0], target[1]));\n if (resource == null) {\n System.err.println(\"Unknown bundle and/or version: \" + target[0]);\n } else {\n URI srcURL = (URI) resource.getProperties().get(Resource.SOURCE_URI);\n if (srcURL != null) {\n FileUtil.downloadSource(System.out, System.err, srcURL.toURL(), localDir, extract);\n } else {\n System.err.println(\"Missing source URL: \" + target[0]);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_1605", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/karaf/obr/src/main/java/org/apache/karaf/obr/command/SourceCommand.java", "mask_start_position": 1259, "mask_end_position": 1950, "canonical_solution": "for (String bundle : bundles) {\n String[] target = getTarget(bundle);\n Resource resource = selectNewestVersion(searchRepository(admin, target[0], target[1]));\n if (resource == null) {\n System.err.println(\"Unknown bundle and/or version: \" + target[0]);\n } else {\n URI srcURL = (URI) resource.getProperties().get(Resource.SOURCE_URI);\n if (srcURL != null) {\n FileUtil.downloadSource(System.out, System.err, srcURL.toURL(), localDir, extract);\n } else {\n System.err.println(\"Missing source URL: \" + target[0]);\n }\n }\n }", "pre_mask_code": "package org.apache.karaf.obr.command;\n\nimport java.net.URI;\nimport java.util.List;\nimport org.apache.felix.bundlerepository.RepositoryAdmin;\nimport org.apache.felix.bundlerepository.Resource;\nimport org.apache.karaf.obr.command.util.FileUtil;\nimport org.apache.karaf.shell.api.action.Argument;\nimport org.apache.karaf.shell.api.action.Command;\nimport org.apache.karaf.shell.api.action.Option;\nimport org.apache.karaf.shell.api.action.lifecycle.Service;\n\n@Command(scope = \"obr\", name = \"source\", description = \"Downloads the sources for an OBR bundle.\")\n@Service\npublic class SourceCommand extends ObrCommandSupport {\n\n @Option(name = \"-x\", aliases = {}, description = \"Extract the archive\", required = false, multiValued = false)\n boolean extract;\n\n @Argument(index = 0, name = \"folder\", description = \"Local folder for storing sources\", required = true, multiValued = false)\n String localDir;\n\n @Argument(index = 1, name = \"bundles\", description = \"List of bundles to download the sources for. The bundles are identified using the following syntax: symbolic_name,version where version is optional.\", required = true, multiValued = true)\n List bundles;\n\n protected void doExecute(RepositoryAdmin admin) throws Exception {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1606", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/karaf/obr/src/main/java/org/apache/karaf/obr/command/SourceCommand.java", "mask_start_position": 1955, "mask_end_position": 1956, "canonical_solution": "}", "pre_mask_code": "package org.apache.karaf.obr.command;\n\nimport java.net.URI;\nimport java.util.List;\nimport org.apache.felix.bundlerepository.RepositoryAdmin;\nimport org.apache.felix.bundlerepository.Resource;\nimport org.apache.karaf.obr.command.util.FileUtil;\nimport org.apache.karaf.shell.api.action.Argument;\nimport org.apache.karaf.shell.api.action.Command;\nimport org.apache.karaf.shell.api.action.Option;\nimport org.apache.karaf.shell.api.action.lifecycle.Service;\n\n@Command(scope = \"obr\", name = \"source\", description = \"Downloads the sources for an OBR bundle.\")\n@Service\npublic class SourceCommand extends ObrCommandSupport {\n\n @Option(name = \"-x\", aliases = {}, description = \"Extract the archive\", required = false, multiValued = false)\n boolean extract;\n\n @Argument(index = 0, name = \"folder\", description = \"Local folder for storing sources\", required = true, multiValued = false)\n String localDir;\n\n @Argument(index = 1, name = \"bundles\", description = \"List of bundles to download the sources for. The bundles are identified using the following syntax: symbolic_name,version where version is optional.\", required = true, multiValued = true)\n List bundles;\n\n protected void doExecute(RepositoryAdmin admin) throws Exception {\n for (String bundle : bundles) {\n String[] target = getTarget(bundle);\n Resource resource = selectNewestVersion(searchRepository(admin, target[0], target[1]));\n if (resource == null) {\n System.err.println(\"Unknown bundle and/or version: \" + target[0]);\n } else {\n URI srcURL = (URI) resource.getProperties().get(Resource.SOURCE_URI);\n if (srcURL != null) {\n FileUtil.downloadSource(System.out, System.err, srcURL.toURL(), localDir, extract);\n } else {\n System.err.println(\"Missing source URL: \" + target[0]);\n }\n }\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1607", "language": "Java", "task_type": "if_statement", "source_file": "java/github/apache/karaf/obr/src/main/java/org/apache/karaf/obr/command/SourceCommand.java", "mask_start_position": 1452, "mask_end_position": 1940, "canonical_solution": "if (resource == null) {\n System.err.println(\"Unknown bundle and/or version: \" + target[0]);\n } else {\n URI srcURL = (URI) resource.getProperties().get(Resource.SOURCE_URI);\n if (srcURL != null) {\n FileUtil.downloadSource(System.out, System.err, srcURL.toURL(), localDir, extract);\n } else {\n System.err.println(\"Missing source URL: \" + target[0]);\n }\n }", "pre_mask_code": "package org.apache.karaf.obr.command;\n\nimport java.net.URI;\nimport java.util.List;\nimport org.apache.felix.bundlerepository.RepositoryAdmin;\nimport org.apache.felix.bundlerepository.Resource;\nimport org.apache.karaf.obr.command.util.FileUtil;\nimport org.apache.karaf.shell.api.action.Argument;\nimport org.apache.karaf.shell.api.action.Command;\nimport org.apache.karaf.shell.api.action.Option;\nimport org.apache.karaf.shell.api.action.lifecycle.Service;\n\n@Command(scope = \"obr\", name = \"source\", description = \"Downloads the sources for an OBR bundle.\")\n@Service\npublic class SourceCommand extends ObrCommandSupport {\n\n @Option(name = \"-x\", aliases = {}, description = \"Extract the archive\", required = false, multiValued = false)\n boolean extract;\n\n @Argument(index = 0, name = \"folder\", description = \"Local folder for storing sources\", required = true, multiValued = false)\n String localDir;\n\n @Argument(index = 1, name = \"bundles\", description = \"List of bundles to download the sources for. The bundles are identified using the following syntax: symbolic_name,version where version is optional.\", required = true, multiValued = true)\n List bundles;\n\n protected void doExecute(RepositoryAdmin admin) throws Exception {\n for (String bundle : bundles) {\n String[] target = getTarget(bundle);\n Resource resource = selectNewestVersion(searchRepository(admin, target[0], target[1]));\n ", "post_mask_code": "\n }\n }\n}\n"} {"task_id": "Java_1608", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Taskana/taskana/lib/taskana-core/src/main/java/pro/taskana/task/internal/TaskCommentQueryImpl.java", "mask_start_position": 6661, "mask_end_position": 6687, "canonical_solution": "public String[] getIdIn() ", "pre_mask_code": "package pro.taskana.task.internal;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.apache.ibatis.session.RowBounds;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport pro.taskana.common.api.TaskanaRole;\nimport pro.taskana.common.api.TimeInterval;\nimport pro.taskana.common.api.exceptions.NotAuthorizedException;\nimport pro.taskana.common.internal.InternalTaskanaEngine;\nimport pro.taskana.task.api.TaskCommentQuery;\nimport pro.taskana.task.api.TaskCommentQueryColumnName;\nimport pro.taskana.task.api.exceptions.TaskNotFoundException;\nimport pro.taskana.task.api.models.TaskComment;\nimport pro.taskana.workbasket.api.exceptions.NotAuthorizedToQueryWorkbasketException;\nimport pro.taskana.workbasket.internal.WorkbasketQueryImpl;\n\n/**\n * TaskCommentQuery for generating dynamic sql.\n */\npublic class TaskCommentQueryImpl implements TaskCommentQuery {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(TaskCommentQueryImpl.class);\n\n private static final String LINK_TO_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskComments\";\n\n private static final String LINK_TO_VALUE_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskCommentColumnValues\";\n\n private static final String LINK_TO_COUNTER = \"pro.taskana.task.internal.TaskCommentQueryMapper.countQueryTaskComments\";\n\n private final InternalTaskanaEngine taskanaEngine;\n\n private final TaskServiceImpl taskService;\n\n private final List orderBy;\n\n private final List orderColumns;\n\n private TaskCommentQueryColumnName queryColumnName;\n\n private String[] idIn;\n\n private String[] idNotIn;\n\n private String[] idLike;\n\n private String[] idNotLike;\n\n private String[] taskIdIn;\n\n private String[] creatorIn;\n\n private String[] creatorNotIn;\n\n private String[] creatorLike;\n\n private String[] creatorNotLike;\n\n private String[] textFieldLike;\n\n private String[] textFieldNotLike;\n\n private TimeInterval[] modifiedIn;\n\n private TimeInterval[] modifiedNotIn;\n\n private TimeInterval[] createdIn;\n\n private TimeInterval[] createdNotIn;\n\n private String[] accessIdIn;\n\n private boolean joinWithUserInfo;\n\n TaskCommentQueryImpl(InternalTaskanaEngine taskanaEngine) {\n this.taskanaEngine = taskanaEngine;\n this.taskService = (TaskServiceImpl) taskanaEngine.getEngine().getTaskService();\n this.orderBy = new ArrayList<>();\n this.orderColumns = new ArrayList<>();\n this.joinWithUserInfo = taskanaEngine.getEngine().getConfiguration().getAddAdditionalUserInfo();\n }\n\n @Override\n public TaskCommentQuery idIn(String... taskCommentIds) {\n this.idIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotIn(String... taskCommentIds) {\n this.idNotIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idLike(String... taskCommentIds) {\n this.idLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotLike(String... taskCommentIds) {\n this.idNotLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery taskIdIn(String... taskIds) {\n this.taskIdIn = taskIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldLike(String... texts) {\n this.textFieldLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldNotLike(String... texts) {\n this.textFieldNotLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorIn(String... creators) {\n this.creatorIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotIn(String... creators) {\n this.creatorNotIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorLike(String... creators) {\n this.creatorLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotLike(String... creators) {\n this.creatorNotLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery createdWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.createdIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery createdNotWithin(TimeInterval... intervals) {\n this.createdNotIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.modifiedIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedNotWithin(TimeInterval... intervals) {\n this.modifiedNotIn = intervals;\n return this;\n }\n\n @Override\n public List list() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this));\n }\n\n @Override\n public List list(int offset, int limit) {\n checkTaskPermission();\n setupAccessIds();\n RowBounds rowBounds = new RowBounds(offset, limit);\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds));\n }\n\n @Override\n public List listValues(TaskCommentQueryColumnName columnName, SortDirection sortDirection) {\n checkTaskPermission();\n setupAccessIds();\n queryColumnName = columnName;\n if (columnName == TaskCommentQueryColumnName.CREATOR_FULL_NAME) {\n joinWithUserInfo = true;\n }\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_VALUE_MAPPER, this));\n }\n\n @Override\n public TaskComment single() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this));\n }\n\n @Override\n public long count() {\n checkTaskPermission();\n setupAccessIds();\n Long rowCount = taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this));\n return (rowCount == null) ? 0L : rowCount;\n }\n\n public TaskCommentQueryColumnName getQueryColumnName() {\n return queryColumnName;\n }\n\n ", "post_mask_code": "{\n return idIn;\n }\n\n public String[] getIdNotIn() {\n return idNotIn;\n }\n\n public String[] getIdLike() {\n return idLike;\n }\n\n public String[] getIdNotLike() {\n return idNotLike;\n }\n\n public String[] getTaskIdIn() {\n return taskIdIn;\n }\n\n public String[] getCreatorIn() {\n return creatorIn;\n }\n\n public String[] getCreatorNotIn() {\n return creatorNotIn;\n }\n\n public String[] getCreatorLike() {\n return creatorLike;\n }\n\n public String[] getCreatorNotLike() {\n return creatorNotLike;\n }\n\n public String[] getTextFieldLike() {\n return textFieldLike;\n }\n\n public String[] getTextFieldNotLike() {\n return textFieldNotLike;\n }\n\n public TimeInterval[] getModifiedIn() {\n return modifiedIn;\n }\n\n public TimeInterval[] getModifiedNotIn() {\n return modifiedNotIn;\n }\n\n public TimeInterval[] getCreatedIn() {\n return createdIn;\n }\n\n public TimeInterval[] getCreatedNotIn() {\n return createdNotIn;\n }\n\n public String[] getAccessIdIn() {\n return accessIdIn;\n }\n\n public boolean isIncludeLongName() {\n return joinWithUserInfo;\n }\n\n public void setIncludeLongName(boolean joinWithUserInfo) {\n this.joinWithUserInfo = joinWithUserInfo;\n }\n\n @Override\n public TaskCommentQuery orderByCreated(SortDirection sortDirection) {\n return addOrderCriteria(\"CREATED\", sortDirection);\n }\n\n @Override\n public TaskCommentQuery orderByModified(SortDirection sortDirection) {\n return addOrderCriteria(\"MODIFIED\", sortDirection);\n }\n\n private void checkTaskPermission() {\n if (taskIdIn != null) {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Skipping permissions check since user is in role ADMIN or TASK_ADMIN.\");\n }\n return;\n }\n Arrays.stream(taskIdIn).forEach(taskId -> {\n try {\n taskService.getTask(taskId);\n } catch (NotAuthorizedException e) {\n throw new NotAuthorizedToQueryWorkbasketException(e.getMessage(), e.getErrorCode(), e);\n } catch (TaskNotFoundException e) {\n LOGGER.warn(String.format(\"The Task with the ID ' %s ' does not exist.\", taskId), e);\n }\n });\n }\n }\n\n private TaskCommentQuery addOrderCriteria(String columnName, SortDirection sortDirection) {\n String orderByDirection = \" \" + (sortDirection == null ? SortDirection.ASCENDING : sortDirection);\n orderBy.add(columnName + orderByDirection);\n orderColumns.add(columnName);\n return this;\n }\n\n private void setupAccessIds() {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n this.accessIdIn = null;\n } else if (this.accessIdIn == null) {\n String[] accessIds = new String[0];\n List ucAccessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();\n if (!ucAccessIds.isEmpty()) {\n accessIds = new String[ucAccessIds.size()];\n accessIds = ucAccessIds.toArray(accessIds);\n }\n this.accessIdIn = accessIds;\n WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn);\n }\n }\n\n private void validateAllIntervals(TimeInterval[] intervals) {\n for (TimeInterval ti : intervals) {\n if (!ti.isValid()) {\n throw new IllegalArgumentException(\"TimeInterval \" + ti + \" is invalid.\");\n }\n }\n }\n\n @Override\n public String toString() {\n return \"TaskCommentQueryImpl [taskanaEngine=\" + taskanaEngine + \", taskService=\" + taskService + \", queryColumnName=\" + queryColumnName + \", idIn=\" + Arrays.toString(idIn) + \", idNotIn=\" + Arrays.toString(idNotIn) + \", idLike=\" + Arrays.toString(idLike) + \", idNotLike=\" + Arrays.toString(idNotLike) + \", taskIdIn=\" + Arrays.toString(taskIdIn) + \", creatorIn=\" + Arrays.toString(creatorIn) + \", creatorNotIn=\" + Arrays.toString(creatorNotIn) + \", creatorLike=\" + Arrays.toString(creatorLike) + \", creatorNotLike=\" + Arrays.toString(creatorNotLike) + \", textFieldLike=\" + Arrays.toString(textFieldLike) + \", textFieldNotLike=\" + Arrays.toString(textFieldNotLike) + \", modifiedIn=\" + Arrays.toString(modifiedIn) + \", modifiedNotIn=\" + Arrays.toString(modifiedNotIn) + \", createdIn=\" + Arrays.toString(createdIn) + \", createdNotIn=\" + Arrays.toString(createdNotIn) + \", accessIdIn=\" + Arrays.toString(accessIdIn) + \", joinWithUserInfo=\" + joinWithUserInfo + \"]\";\n }\n}\n"} {"task_id": "Java_1609", "language": "Java", "task_type": "method_body", "source_file": "java/github/Taskana/taskana/lib/taskana-core/src/main/java/pro/taskana/task/internal/TaskCommentQueryImpl.java", "mask_start_position": 4705, "mask_end_position": 4811, "canonical_solution": "{\n validateAllIntervals(intervals);\n this.modifiedIn = intervals;\n return this;\n }", "pre_mask_code": "package pro.taskana.task.internal;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.apache.ibatis.session.RowBounds;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport pro.taskana.common.api.TaskanaRole;\nimport pro.taskana.common.api.TimeInterval;\nimport pro.taskana.common.api.exceptions.NotAuthorizedException;\nimport pro.taskana.common.internal.InternalTaskanaEngine;\nimport pro.taskana.task.api.TaskCommentQuery;\nimport pro.taskana.task.api.TaskCommentQueryColumnName;\nimport pro.taskana.task.api.exceptions.TaskNotFoundException;\nimport pro.taskana.task.api.models.TaskComment;\nimport pro.taskana.workbasket.api.exceptions.NotAuthorizedToQueryWorkbasketException;\nimport pro.taskana.workbasket.internal.WorkbasketQueryImpl;\n\n/**\n * TaskCommentQuery for generating dynamic sql.\n */\npublic class TaskCommentQueryImpl implements TaskCommentQuery {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(TaskCommentQueryImpl.class);\n\n private static final String LINK_TO_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskComments\";\n\n private static final String LINK_TO_VALUE_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskCommentColumnValues\";\n\n private static final String LINK_TO_COUNTER = \"pro.taskana.task.internal.TaskCommentQueryMapper.countQueryTaskComments\";\n\n private final InternalTaskanaEngine taskanaEngine;\n\n private final TaskServiceImpl taskService;\n\n private final List orderBy;\n\n private final List orderColumns;\n\n private TaskCommentQueryColumnName queryColumnName;\n\n private String[] idIn;\n\n private String[] idNotIn;\n\n private String[] idLike;\n\n private String[] idNotLike;\n\n private String[] taskIdIn;\n\n private String[] creatorIn;\n\n private String[] creatorNotIn;\n\n private String[] creatorLike;\n\n private String[] creatorNotLike;\n\n private String[] textFieldLike;\n\n private String[] textFieldNotLike;\n\n private TimeInterval[] modifiedIn;\n\n private TimeInterval[] modifiedNotIn;\n\n private TimeInterval[] createdIn;\n\n private TimeInterval[] createdNotIn;\n\n private String[] accessIdIn;\n\n private boolean joinWithUserInfo;\n\n TaskCommentQueryImpl(InternalTaskanaEngine taskanaEngine) {\n this.taskanaEngine = taskanaEngine;\n this.taskService = (TaskServiceImpl) taskanaEngine.getEngine().getTaskService();\n this.orderBy = new ArrayList<>();\n this.orderColumns = new ArrayList<>();\n this.joinWithUserInfo = taskanaEngine.getEngine().getConfiguration().getAddAdditionalUserInfo();\n }\n\n @Override\n public TaskCommentQuery idIn(String... taskCommentIds) {\n this.idIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotIn(String... taskCommentIds) {\n this.idNotIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idLike(String... taskCommentIds) {\n this.idLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotLike(String... taskCommentIds) {\n this.idNotLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery taskIdIn(String... taskIds) {\n this.taskIdIn = taskIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldLike(String... texts) {\n this.textFieldLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldNotLike(String... texts) {\n this.textFieldNotLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorIn(String... creators) {\n this.creatorIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotIn(String... creators) {\n this.creatorNotIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorLike(String... creators) {\n this.creatorLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotLike(String... creators) {\n this.creatorNotLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery createdWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.createdIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery createdNotWithin(TimeInterval... intervals) {\n this.createdNotIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedWithin(TimeInterval... intervals) ", "post_mask_code": "\n\n @Override\n public TaskCommentQuery modifiedNotWithin(TimeInterval... intervals) {\n this.modifiedNotIn = intervals;\n return this;\n }\n\n @Override\n public List list() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this));\n }\n\n @Override\n public List list(int offset, int limit) {\n checkTaskPermission();\n setupAccessIds();\n RowBounds rowBounds = new RowBounds(offset, limit);\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds));\n }\n\n @Override\n public List listValues(TaskCommentQueryColumnName columnName, SortDirection sortDirection) {\n checkTaskPermission();\n setupAccessIds();\n queryColumnName = columnName;\n if (columnName == TaskCommentQueryColumnName.CREATOR_FULL_NAME) {\n joinWithUserInfo = true;\n }\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_VALUE_MAPPER, this));\n }\n\n @Override\n public TaskComment single() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this));\n }\n\n @Override\n public long count() {\n checkTaskPermission();\n setupAccessIds();\n Long rowCount = taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this));\n return (rowCount == null) ? 0L : rowCount;\n }\n\n public TaskCommentQueryColumnName getQueryColumnName() {\n return queryColumnName;\n }\n\n public String[] getIdIn() {\n return idIn;\n }\n\n public String[] getIdNotIn() {\n return idNotIn;\n }\n\n public String[] getIdLike() {\n return idLike;\n }\n\n public String[] getIdNotLike() {\n return idNotLike;\n }\n\n public String[] getTaskIdIn() {\n return taskIdIn;\n }\n\n public String[] getCreatorIn() {\n return creatorIn;\n }\n\n public String[] getCreatorNotIn() {\n return creatorNotIn;\n }\n\n public String[] getCreatorLike() {\n return creatorLike;\n }\n\n public String[] getCreatorNotLike() {\n return creatorNotLike;\n }\n\n public String[] getTextFieldLike() {\n return textFieldLike;\n }\n\n public String[] getTextFieldNotLike() {\n return textFieldNotLike;\n }\n\n public TimeInterval[] getModifiedIn() {\n return modifiedIn;\n }\n\n public TimeInterval[] getModifiedNotIn() {\n return modifiedNotIn;\n }\n\n public TimeInterval[] getCreatedIn() {\n return createdIn;\n }\n\n public TimeInterval[] getCreatedNotIn() {\n return createdNotIn;\n }\n\n public String[] getAccessIdIn() {\n return accessIdIn;\n }\n\n public boolean isIncludeLongName() {\n return joinWithUserInfo;\n }\n\n public void setIncludeLongName(boolean joinWithUserInfo) {\n this.joinWithUserInfo = joinWithUserInfo;\n }\n\n @Override\n public TaskCommentQuery orderByCreated(SortDirection sortDirection) {\n return addOrderCriteria(\"CREATED\", sortDirection);\n }\n\n @Override\n public TaskCommentQuery orderByModified(SortDirection sortDirection) {\n return addOrderCriteria(\"MODIFIED\", sortDirection);\n }\n\n private void checkTaskPermission() {\n if (taskIdIn != null) {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Skipping permissions check since user is in role ADMIN or TASK_ADMIN.\");\n }\n return;\n }\n Arrays.stream(taskIdIn).forEach(taskId -> {\n try {\n taskService.getTask(taskId);\n } catch (NotAuthorizedException e) {\n throw new NotAuthorizedToQueryWorkbasketException(e.getMessage(), e.getErrorCode(), e);\n } catch (TaskNotFoundException e) {\n LOGGER.warn(String.format(\"The Task with the ID ' %s ' does not exist.\", taskId), e);\n }\n });\n }\n }\n\n private TaskCommentQuery addOrderCriteria(String columnName, SortDirection sortDirection) {\n String orderByDirection = \" \" + (sortDirection == null ? SortDirection.ASCENDING : sortDirection);\n orderBy.add(columnName + orderByDirection);\n orderColumns.add(columnName);\n return this;\n }\n\n private void setupAccessIds() {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n this.accessIdIn = null;\n } else if (this.accessIdIn == null) {\n String[] accessIds = new String[0];\n List ucAccessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();\n if (!ucAccessIds.isEmpty()) {\n accessIds = new String[ucAccessIds.size()];\n accessIds = ucAccessIds.toArray(accessIds);\n }\n this.accessIdIn = accessIds;\n WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn);\n }\n }\n\n private void validateAllIntervals(TimeInterval[] intervals) {\n for (TimeInterval ti : intervals) {\n if (!ti.isValid()) {\n throw new IllegalArgumentException(\"TimeInterval \" + ti + \" is invalid.\");\n }\n }\n }\n\n @Override\n public String toString() {\n return \"TaskCommentQueryImpl [taskanaEngine=\" + taskanaEngine + \", taskService=\" + taskService + \", queryColumnName=\" + queryColumnName + \", idIn=\" + Arrays.toString(idIn) + \", idNotIn=\" + Arrays.toString(idNotIn) + \", idLike=\" + Arrays.toString(idLike) + \", idNotLike=\" + Arrays.toString(idNotLike) + \", taskIdIn=\" + Arrays.toString(taskIdIn) + \", creatorIn=\" + Arrays.toString(creatorIn) + \", creatorNotIn=\" + Arrays.toString(creatorNotIn) + \", creatorLike=\" + Arrays.toString(creatorLike) + \", creatorNotLike=\" + Arrays.toString(creatorNotLike) + \", textFieldLike=\" + Arrays.toString(textFieldLike) + \", textFieldNotLike=\" + Arrays.toString(textFieldNotLike) + \", modifiedIn=\" + Arrays.toString(modifiedIn) + \", modifiedNotIn=\" + Arrays.toString(modifiedNotIn) + \", createdIn=\" + Arrays.toString(createdIn) + \", createdNotIn=\" + Arrays.toString(createdNotIn) + \", accessIdIn=\" + Arrays.toString(accessIdIn) + \", joinWithUserInfo=\" + joinWithUserInfo + \"]\";\n }\n}\n"} {"task_id": "Java_1610", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Taskana/taskana/lib/taskana-core/src/main/java/pro/taskana/task/internal/TaskCommentQueryImpl.java", "mask_start_position": 10288, "mask_end_position": 10288, "canonical_solution": "", "pre_mask_code": "package pro.taskana.task.internal;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.apache.ibatis.session.RowBounds;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport pro.taskana.common.api.TaskanaRole;\nimport pro.taskana.common.api.TimeInterval;\nimport pro.taskana.common.api.exceptions.NotAuthorizedException;\nimport pro.taskana.common.internal.InternalTaskanaEngine;\nimport pro.taskana.task.api.TaskCommentQuery;\nimport pro.taskana.task.api.TaskCommentQueryColumnName;\nimport pro.taskana.task.api.exceptions.TaskNotFoundException;\nimport pro.taskana.task.api.models.TaskComment;\nimport pro.taskana.workbasket.api.exceptions.NotAuthorizedToQueryWorkbasketException;\nimport pro.taskana.workbasket.internal.WorkbasketQueryImpl;\n\n/**\n * TaskCommentQuery for generating dynamic sql.\n */\npublic class TaskCommentQueryImpl implements TaskCommentQuery {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(TaskCommentQueryImpl.class);\n\n private static final String LINK_TO_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskComments\";\n\n private static final String LINK_TO_VALUE_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskCommentColumnValues\";\n\n private static final String LINK_TO_COUNTER = \"pro.taskana.task.internal.TaskCommentQueryMapper.countQueryTaskComments\";\n\n private final InternalTaskanaEngine taskanaEngine;\n\n private final TaskServiceImpl taskService;\n\n private final List orderBy;\n\n private final List orderColumns;\n\n private TaskCommentQueryColumnName queryColumnName;\n\n private String[] idIn;\n\n private String[] idNotIn;\n\n private String[] idLike;\n\n private String[] idNotLike;\n\n private String[] taskIdIn;\n\n private String[] creatorIn;\n\n private String[] creatorNotIn;\n\n private String[] creatorLike;\n\n private String[] creatorNotLike;\n\n private String[] textFieldLike;\n\n private String[] textFieldNotLike;\n\n private TimeInterval[] modifiedIn;\n\n private TimeInterval[] modifiedNotIn;\n\n private TimeInterval[] createdIn;\n\n private TimeInterval[] createdNotIn;\n\n private String[] accessIdIn;\n\n private boolean joinWithUserInfo;\n\n TaskCommentQueryImpl(InternalTaskanaEngine taskanaEngine) {\n this.taskanaEngine = taskanaEngine;\n this.taskService = (TaskServiceImpl) taskanaEngine.getEngine().getTaskService();\n this.orderBy = new ArrayList<>();\n this.orderColumns = new ArrayList<>();\n this.joinWithUserInfo = taskanaEngine.getEngine().getConfiguration().getAddAdditionalUserInfo();\n }\n\n @Override\n public TaskCommentQuery idIn(String... taskCommentIds) {\n this.idIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotIn(String... taskCommentIds) {\n this.idNotIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idLike(String... taskCommentIds) {\n this.idLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotLike(String... taskCommentIds) {\n this.idNotLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery taskIdIn(String... taskIds) {\n this.taskIdIn = taskIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldLike(String... texts) {\n this.textFieldLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldNotLike(String... texts) {\n this.textFieldNotLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorIn(String... creators) {\n this.creatorIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotIn(String... creators) {\n this.creatorNotIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorLike(String... creators) {\n this.creatorLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotLike(String... creators) {\n this.creatorNotLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery createdWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.createdIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery createdNotWithin(TimeInterval... intervals) {\n this.createdNotIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.modifiedIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedNotWithin(TimeInterval... intervals) {\n this.modifiedNotIn = intervals;\n return this;\n }\n\n @Override\n public List list() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this));\n }\n\n @Override\n public List list(int offset, int limit) {\n checkTaskPermission();\n setupAccessIds();\n RowBounds rowBounds = new RowBounds(offset, limit);\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds));\n }\n\n @Override\n public List listValues(TaskCommentQueryColumnName columnName, SortDirection sortDirection) {\n checkTaskPermission();\n setupAccessIds();\n queryColumnName = columnName;\n if (columnName == TaskCommentQueryColumnName.CREATOR_FULL_NAME) {\n joinWithUserInfo = true;\n }\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_VALUE_MAPPER, this));\n }\n\n @Override\n public TaskComment single() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this));\n }\n\n @Override\n public long count() {\n checkTaskPermission();\n setupAccessIds();\n Long rowCount = taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this));\n return (rowCount == null) ? 0L : rowCount;\n }\n\n public TaskCommentQueryColumnName getQueryColumnName() {\n return queryColumnName;\n }\n\n public String[] getIdIn() {\n return idIn;\n }\n\n public String[] getIdNotIn() {\n return idNotIn;\n }\n\n public String[] getIdLike() {\n return idLike;\n }\n\n public String[] getIdNotLike() {\n return idNotLike;\n }\n\n public String[] getTaskIdIn() {\n return taskIdIn;\n }\n\n public String[] getCreatorIn() {\n return creatorIn;\n }\n\n public String[] getCreatorNotIn() {\n return creatorNotIn;\n }\n\n public String[] getCreatorLike() {\n return creatorLike;\n }\n\n public String[] getCreatorNotLike() {\n return creatorNotLike;\n }\n\n public String[] getTextFieldLike() {\n return textFieldLike;\n }\n\n public String[] getTextFieldNotLike() {\n return textFieldNotLike;\n }\n\n public TimeInterval[] getModifiedIn() {\n return modifiedIn;\n }\n\n public TimeInterval[] getModifiedNotIn() {\n return modifiedNotIn;\n }\n\n public TimeInterval[] getCreatedIn() {\n return createdIn;\n }\n\n public TimeInterval[] getCreatedNotIn() {\n return createdNotIn;\n }\n\n public String[] getAccessIdIn() {\n return accessIdIn;\n }\n\n public boolean isIncludeLongName() {\n return joinWithUserInfo;\n }\n\n public void setIncludeLongName(boolean joinWithUserInfo) {\n this.joinWithUserInfo = joinWithUserInfo;\n }\n\n @Override\n public TaskCommentQuery orderByCreated(SortDirection sortDirection) {\n return addOrderCriteria(\"CREATED\", sortDirection);\n }\n\n @Override\n public TaskCommentQuery orderByModified(SortDirection sortDirection) {\n return addOrderCriteria(\"MODIFIED\", sortDirection);\n }\n\n private void checkTaskPermission() {\n if (taskIdIn != null) {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Skipping permissions check since user is in role ADMIN or TASK_ADMIN.\");\n }\n return;\n }\n Arrays.stream(taskIdIn).forEach(taskId -> {\n try {\n taskService.getTask(taskId);\n } catch (NotAuthorizedException e) {\n throw new NotAuthorizedToQueryWorkbasketException(e.getMessage(), e.getErrorCode(), e);\n } catch (TaskNotFoundException e) {\n LOGGER.warn(String.format(\"The Task with the ID ' %s ' does not exist.\", taskId), e);\n }\n });\n }\n }\n\n private TaskCommentQuery addOrderCriteria(String columnName, SortDirection sortDirection) {\n String orderByDirection = \" \" + (sortDirection == null ? SortDirection.ASCENDING : sortDirection);\n orderBy.add(columnName + orderByDirection);\n orderColumns.add(columnName);\n return this;\n }\n\n private void setupAccessIds() {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n this.accessIdIn = null;\n } else if (this.accessIdIn == null) {\n String[] accessIds = new String[0];\n List ucAccessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();\n if (!ucAccessIds.isEmpty()) {\n accessIds = new String[ucAccessIds.size()];\n accessIds = ucAccessIds.toArray(accessIds);\n }\n this.accessIdIn = accessIds;\n WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn);\n }\n }\n\n private void validateAllIntervals(TimeInterval[] intervals) {", "post_mask_code": "\n for (TimeInterval ti : intervals) {\n if (!ti.isValid()) {\n throw new IllegalArgumentException(\"TimeInterval \" + ti + \" is invalid.\");\n }\n }\n }\n\n @Override\n public String toString() {\n return \"TaskCommentQueryImpl [taskanaEngine=\" + taskanaEngine + \", taskService=\" + taskService + \", queryColumnName=\" + queryColumnName + \", idIn=\" + Arrays.toString(idIn) + \", idNotIn=\" + Arrays.toString(idNotIn) + \", idLike=\" + Arrays.toString(idLike) + \", idNotLike=\" + Arrays.toString(idNotLike) + \", taskIdIn=\" + Arrays.toString(taskIdIn) + \", creatorIn=\" + Arrays.toString(creatorIn) + \", creatorNotIn=\" + Arrays.toString(creatorNotIn) + \", creatorLike=\" + Arrays.toString(creatorLike) + \", creatorNotLike=\" + Arrays.toString(creatorNotLike) + \", textFieldLike=\" + Arrays.toString(textFieldLike) + \", textFieldNotLike=\" + Arrays.toString(textFieldNotLike) + \", modifiedIn=\" + Arrays.toString(modifiedIn) + \", modifiedNotIn=\" + Arrays.toString(modifiedNotIn) + \", createdIn=\" + Arrays.toString(createdIn) + \", createdNotIn=\" + Arrays.toString(createdNotIn) + \", accessIdIn=\" + Arrays.toString(accessIdIn) + \", joinWithUserInfo=\" + joinWithUserInfo + \"]\";\n }\n}\n"} {"task_id": "Java_1611", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Taskana/taskana/lib/taskana-core/src/main/java/pro/taskana/task/internal/TaskCommentQueryImpl.java", "mask_start_position": 10297, "mask_end_position": 10480, "canonical_solution": "for (TimeInterval ti : intervals) {\n if (!ti.isValid()) {\n throw new IllegalArgumentException(\"TimeInterval \" + ti + \" is invalid.\");\n }\n }", "pre_mask_code": "package pro.taskana.task.internal;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.apache.ibatis.session.RowBounds;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport pro.taskana.common.api.TaskanaRole;\nimport pro.taskana.common.api.TimeInterval;\nimport pro.taskana.common.api.exceptions.NotAuthorizedException;\nimport pro.taskana.common.internal.InternalTaskanaEngine;\nimport pro.taskana.task.api.TaskCommentQuery;\nimport pro.taskana.task.api.TaskCommentQueryColumnName;\nimport pro.taskana.task.api.exceptions.TaskNotFoundException;\nimport pro.taskana.task.api.models.TaskComment;\nimport pro.taskana.workbasket.api.exceptions.NotAuthorizedToQueryWorkbasketException;\nimport pro.taskana.workbasket.internal.WorkbasketQueryImpl;\n\n/**\n * TaskCommentQuery for generating dynamic sql.\n */\npublic class TaskCommentQueryImpl implements TaskCommentQuery {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(TaskCommentQueryImpl.class);\n\n private static final String LINK_TO_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskComments\";\n\n private static final String LINK_TO_VALUE_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskCommentColumnValues\";\n\n private static final String LINK_TO_COUNTER = \"pro.taskana.task.internal.TaskCommentQueryMapper.countQueryTaskComments\";\n\n private final InternalTaskanaEngine taskanaEngine;\n\n private final TaskServiceImpl taskService;\n\n private final List orderBy;\n\n private final List orderColumns;\n\n private TaskCommentQueryColumnName queryColumnName;\n\n private String[] idIn;\n\n private String[] idNotIn;\n\n private String[] idLike;\n\n private String[] idNotLike;\n\n private String[] taskIdIn;\n\n private String[] creatorIn;\n\n private String[] creatorNotIn;\n\n private String[] creatorLike;\n\n private String[] creatorNotLike;\n\n private String[] textFieldLike;\n\n private String[] textFieldNotLike;\n\n private TimeInterval[] modifiedIn;\n\n private TimeInterval[] modifiedNotIn;\n\n private TimeInterval[] createdIn;\n\n private TimeInterval[] createdNotIn;\n\n private String[] accessIdIn;\n\n private boolean joinWithUserInfo;\n\n TaskCommentQueryImpl(InternalTaskanaEngine taskanaEngine) {\n this.taskanaEngine = taskanaEngine;\n this.taskService = (TaskServiceImpl) taskanaEngine.getEngine().getTaskService();\n this.orderBy = new ArrayList<>();\n this.orderColumns = new ArrayList<>();\n this.joinWithUserInfo = taskanaEngine.getEngine().getConfiguration().getAddAdditionalUserInfo();\n }\n\n @Override\n public TaskCommentQuery idIn(String... taskCommentIds) {\n this.idIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotIn(String... taskCommentIds) {\n this.idNotIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idLike(String... taskCommentIds) {\n this.idLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotLike(String... taskCommentIds) {\n this.idNotLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery taskIdIn(String... taskIds) {\n this.taskIdIn = taskIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldLike(String... texts) {\n this.textFieldLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldNotLike(String... texts) {\n this.textFieldNotLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorIn(String... creators) {\n this.creatorIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotIn(String... creators) {\n this.creatorNotIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorLike(String... creators) {\n this.creatorLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotLike(String... creators) {\n this.creatorNotLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery createdWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.createdIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery createdNotWithin(TimeInterval... intervals) {\n this.createdNotIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.modifiedIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedNotWithin(TimeInterval... intervals) {\n this.modifiedNotIn = intervals;\n return this;\n }\n\n @Override\n public List list() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this));\n }\n\n @Override\n public List list(int offset, int limit) {\n checkTaskPermission();\n setupAccessIds();\n RowBounds rowBounds = new RowBounds(offset, limit);\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds));\n }\n\n @Override\n public List listValues(TaskCommentQueryColumnName columnName, SortDirection sortDirection) {\n checkTaskPermission();\n setupAccessIds();\n queryColumnName = columnName;\n if (columnName == TaskCommentQueryColumnName.CREATOR_FULL_NAME) {\n joinWithUserInfo = true;\n }\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_VALUE_MAPPER, this));\n }\n\n @Override\n public TaskComment single() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this));\n }\n\n @Override\n public long count() {\n checkTaskPermission();\n setupAccessIds();\n Long rowCount = taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this));\n return (rowCount == null) ? 0L : rowCount;\n }\n\n public TaskCommentQueryColumnName getQueryColumnName() {\n return queryColumnName;\n }\n\n public String[] getIdIn() {\n return idIn;\n }\n\n public String[] getIdNotIn() {\n return idNotIn;\n }\n\n public String[] getIdLike() {\n return idLike;\n }\n\n public String[] getIdNotLike() {\n return idNotLike;\n }\n\n public String[] getTaskIdIn() {\n return taskIdIn;\n }\n\n public String[] getCreatorIn() {\n return creatorIn;\n }\n\n public String[] getCreatorNotIn() {\n return creatorNotIn;\n }\n\n public String[] getCreatorLike() {\n return creatorLike;\n }\n\n public String[] getCreatorNotLike() {\n return creatorNotLike;\n }\n\n public String[] getTextFieldLike() {\n return textFieldLike;\n }\n\n public String[] getTextFieldNotLike() {\n return textFieldNotLike;\n }\n\n public TimeInterval[] getModifiedIn() {\n return modifiedIn;\n }\n\n public TimeInterval[] getModifiedNotIn() {\n return modifiedNotIn;\n }\n\n public TimeInterval[] getCreatedIn() {\n return createdIn;\n }\n\n public TimeInterval[] getCreatedNotIn() {\n return createdNotIn;\n }\n\n public String[] getAccessIdIn() {\n return accessIdIn;\n }\n\n public boolean isIncludeLongName() {\n return joinWithUserInfo;\n }\n\n public void setIncludeLongName(boolean joinWithUserInfo) {\n this.joinWithUserInfo = joinWithUserInfo;\n }\n\n @Override\n public TaskCommentQuery orderByCreated(SortDirection sortDirection) {\n return addOrderCriteria(\"CREATED\", sortDirection);\n }\n\n @Override\n public TaskCommentQuery orderByModified(SortDirection sortDirection) {\n return addOrderCriteria(\"MODIFIED\", sortDirection);\n }\n\n private void checkTaskPermission() {\n if (taskIdIn != null) {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Skipping permissions check since user is in role ADMIN or TASK_ADMIN.\");\n }\n return;\n }\n Arrays.stream(taskIdIn).forEach(taskId -> {\n try {\n taskService.getTask(taskId);\n } catch (NotAuthorizedException e) {\n throw new NotAuthorizedToQueryWorkbasketException(e.getMessage(), e.getErrorCode(), e);\n } catch (TaskNotFoundException e) {\n LOGGER.warn(String.format(\"The Task with the ID ' %s ' does not exist.\", taskId), e);\n }\n });\n }\n }\n\n private TaskCommentQuery addOrderCriteria(String columnName, SortDirection sortDirection) {\n String orderByDirection = \" \" + (sortDirection == null ? SortDirection.ASCENDING : sortDirection);\n orderBy.add(columnName + orderByDirection);\n orderColumns.add(columnName);\n return this;\n }\n\n private void setupAccessIds() {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n this.accessIdIn = null;\n } else if (this.accessIdIn == null) {\n String[] accessIds = new String[0];\n List ucAccessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();\n if (!ucAccessIds.isEmpty()) {\n accessIds = new String[ucAccessIds.size()];\n accessIds = ucAccessIds.toArray(accessIds);\n }\n this.accessIdIn = accessIds;\n WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn);\n }\n }\n\n private void validateAllIntervals(TimeInterval[] intervals) {\n ", "post_mask_code": "\n }\n\n @Override\n public String toString() {\n return \"TaskCommentQueryImpl [taskanaEngine=\" + taskanaEngine + \", taskService=\" + taskService + \", queryColumnName=\" + queryColumnName + \", idIn=\" + Arrays.toString(idIn) + \", idNotIn=\" + Arrays.toString(idNotIn) + \", idLike=\" + Arrays.toString(idLike) + \", idNotLike=\" + Arrays.toString(idNotLike) + \", taskIdIn=\" + Arrays.toString(taskIdIn) + \", creatorIn=\" + Arrays.toString(creatorIn) + \", creatorNotIn=\" + Arrays.toString(creatorNotIn) + \", creatorLike=\" + Arrays.toString(creatorLike) + \", creatorNotLike=\" + Arrays.toString(creatorNotLike) + \", textFieldLike=\" + Arrays.toString(textFieldLike) + \", textFieldNotLike=\" + Arrays.toString(textFieldNotLike) + \", modifiedIn=\" + Arrays.toString(modifiedIn) + \", modifiedNotIn=\" + Arrays.toString(modifiedNotIn) + \", createdIn=\" + Arrays.toString(createdIn) + \", createdNotIn=\" + Arrays.toString(createdNotIn) + \", accessIdIn=\" + Arrays.toString(accessIdIn) + \", joinWithUserInfo=\" + joinWithUserInfo + \"]\";\n }\n}\n"} {"task_id": "Java_1612", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Taskana/taskana/lib/taskana-core/src/main/java/pro/taskana/task/internal/TaskCommentQueryImpl.java", "mask_start_position": 10485, "mask_end_position": 10486, "canonical_solution": "}", "pre_mask_code": "package pro.taskana.task.internal;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.apache.ibatis.session.RowBounds;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport pro.taskana.common.api.TaskanaRole;\nimport pro.taskana.common.api.TimeInterval;\nimport pro.taskana.common.api.exceptions.NotAuthorizedException;\nimport pro.taskana.common.internal.InternalTaskanaEngine;\nimport pro.taskana.task.api.TaskCommentQuery;\nimport pro.taskana.task.api.TaskCommentQueryColumnName;\nimport pro.taskana.task.api.exceptions.TaskNotFoundException;\nimport pro.taskana.task.api.models.TaskComment;\nimport pro.taskana.workbasket.api.exceptions.NotAuthorizedToQueryWorkbasketException;\nimport pro.taskana.workbasket.internal.WorkbasketQueryImpl;\n\n/**\n * TaskCommentQuery for generating dynamic sql.\n */\npublic class TaskCommentQueryImpl implements TaskCommentQuery {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(TaskCommentQueryImpl.class);\n\n private static final String LINK_TO_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskComments\";\n\n private static final String LINK_TO_VALUE_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskCommentColumnValues\";\n\n private static final String LINK_TO_COUNTER = \"pro.taskana.task.internal.TaskCommentQueryMapper.countQueryTaskComments\";\n\n private final InternalTaskanaEngine taskanaEngine;\n\n private final TaskServiceImpl taskService;\n\n private final List orderBy;\n\n private final List orderColumns;\n\n private TaskCommentQueryColumnName queryColumnName;\n\n private String[] idIn;\n\n private String[] idNotIn;\n\n private String[] idLike;\n\n private String[] idNotLike;\n\n private String[] taskIdIn;\n\n private String[] creatorIn;\n\n private String[] creatorNotIn;\n\n private String[] creatorLike;\n\n private String[] creatorNotLike;\n\n private String[] textFieldLike;\n\n private String[] textFieldNotLike;\n\n private TimeInterval[] modifiedIn;\n\n private TimeInterval[] modifiedNotIn;\n\n private TimeInterval[] createdIn;\n\n private TimeInterval[] createdNotIn;\n\n private String[] accessIdIn;\n\n private boolean joinWithUserInfo;\n\n TaskCommentQueryImpl(InternalTaskanaEngine taskanaEngine) {\n this.taskanaEngine = taskanaEngine;\n this.taskService = (TaskServiceImpl) taskanaEngine.getEngine().getTaskService();\n this.orderBy = new ArrayList<>();\n this.orderColumns = new ArrayList<>();\n this.joinWithUserInfo = taskanaEngine.getEngine().getConfiguration().getAddAdditionalUserInfo();\n }\n\n @Override\n public TaskCommentQuery idIn(String... taskCommentIds) {\n this.idIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotIn(String... taskCommentIds) {\n this.idNotIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idLike(String... taskCommentIds) {\n this.idLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotLike(String... taskCommentIds) {\n this.idNotLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery taskIdIn(String... taskIds) {\n this.taskIdIn = taskIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldLike(String... texts) {\n this.textFieldLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldNotLike(String... texts) {\n this.textFieldNotLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorIn(String... creators) {\n this.creatorIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotIn(String... creators) {\n this.creatorNotIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorLike(String... creators) {\n this.creatorLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotLike(String... creators) {\n this.creatorNotLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery createdWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.createdIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery createdNotWithin(TimeInterval... intervals) {\n this.createdNotIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.modifiedIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedNotWithin(TimeInterval... intervals) {\n this.modifiedNotIn = intervals;\n return this;\n }\n\n @Override\n public List list() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this));\n }\n\n @Override\n public List list(int offset, int limit) {\n checkTaskPermission();\n setupAccessIds();\n RowBounds rowBounds = new RowBounds(offset, limit);\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds));\n }\n\n @Override\n public List listValues(TaskCommentQueryColumnName columnName, SortDirection sortDirection) {\n checkTaskPermission();\n setupAccessIds();\n queryColumnName = columnName;\n if (columnName == TaskCommentQueryColumnName.CREATOR_FULL_NAME) {\n joinWithUserInfo = true;\n }\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_VALUE_MAPPER, this));\n }\n\n @Override\n public TaskComment single() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this));\n }\n\n @Override\n public long count() {\n checkTaskPermission();\n setupAccessIds();\n Long rowCount = taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this));\n return (rowCount == null) ? 0L : rowCount;\n }\n\n public TaskCommentQueryColumnName getQueryColumnName() {\n return queryColumnName;\n }\n\n public String[] getIdIn() {\n return idIn;\n }\n\n public String[] getIdNotIn() {\n return idNotIn;\n }\n\n public String[] getIdLike() {\n return idLike;\n }\n\n public String[] getIdNotLike() {\n return idNotLike;\n }\n\n public String[] getTaskIdIn() {\n return taskIdIn;\n }\n\n public String[] getCreatorIn() {\n return creatorIn;\n }\n\n public String[] getCreatorNotIn() {\n return creatorNotIn;\n }\n\n public String[] getCreatorLike() {\n return creatorLike;\n }\n\n public String[] getCreatorNotLike() {\n return creatorNotLike;\n }\n\n public String[] getTextFieldLike() {\n return textFieldLike;\n }\n\n public String[] getTextFieldNotLike() {\n return textFieldNotLike;\n }\n\n public TimeInterval[] getModifiedIn() {\n return modifiedIn;\n }\n\n public TimeInterval[] getModifiedNotIn() {\n return modifiedNotIn;\n }\n\n public TimeInterval[] getCreatedIn() {\n return createdIn;\n }\n\n public TimeInterval[] getCreatedNotIn() {\n return createdNotIn;\n }\n\n public String[] getAccessIdIn() {\n return accessIdIn;\n }\n\n public boolean isIncludeLongName() {\n return joinWithUserInfo;\n }\n\n public void setIncludeLongName(boolean joinWithUserInfo) {\n this.joinWithUserInfo = joinWithUserInfo;\n }\n\n @Override\n public TaskCommentQuery orderByCreated(SortDirection sortDirection) {\n return addOrderCriteria(\"CREATED\", sortDirection);\n }\n\n @Override\n public TaskCommentQuery orderByModified(SortDirection sortDirection) {\n return addOrderCriteria(\"MODIFIED\", sortDirection);\n }\n\n private void checkTaskPermission() {\n if (taskIdIn != null) {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Skipping permissions check since user is in role ADMIN or TASK_ADMIN.\");\n }\n return;\n }\n Arrays.stream(taskIdIn).forEach(taskId -> {\n try {\n taskService.getTask(taskId);\n } catch (NotAuthorizedException e) {\n throw new NotAuthorizedToQueryWorkbasketException(e.getMessage(), e.getErrorCode(), e);\n } catch (TaskNotFoundException e) {\n LOGGER.warn(String.format(\"The Task with the ID ' %s ' does not exist.\", taskId), e);\n }\n });\n }\n }\n\n private TaskCommentQuery addOrderCriteria(String columnName, SortDirection sortDirection) {\n String orderByDirection = \" \" + (sortDirection == null ? SortDirection.ASCENDING : sortDirection);\n orderBy.add(columnName + orderByDirection);\n orderColumns.add(columnName);\n return this;\n }\n\n private void setupAccessIds() {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n this.accessIdIn = null;\n } else if (this.accessIdIn == null) {\n String[] accessIds = new String[0];\n List ucAccessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();\n if (!ucAccessIds.isEmpty()) {\n accessIds = new String[ucAccessIds.size()];\n accessIds = ucAccessIds.toArray(accessIds);\n }\n this.accessIdIn = accessIds;\n WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn);\n }\n }\n\n private void validateAllIntervals(TimeInterval[] intervals) {\n for (TimeInterval ti : intervals) {\n if (!ti.isValid()) {\n throw new IllegalArgumentException(\"TimeInterval \" + ti + \" is invalid.\");\n }\n }\n ", "post_mask_code": "\n\n @Override\n public String toString() {\n return \"TaskCommentQueryImpl [taskanaEngine=\" + taskanaEngine + \", taskService=\" + taskService + \", queryColumnName=\" + queryColumnName + \", idIn=\" + Arrays.toString(idIn) + \", idNotIn=\" + Arrays.toString(idNotIn) + \", idLike=\" + Arrays.toString(idLike) + \", idNotLike=\" + Arrays.toString(idNotLike) + \", taskIdIn=\" + Arrays.toString(taskIdIn) + \", creatorIn=\" + Arrays.toString(creatorIn) + \", creatorNotIn=\" + Arrays.toString(creatorNotIn) + \", creatorLike=\" + Arrays.toString(creatorLike) + \", creatorNotLike=\" + Arrays.toString(creatorNotLike) + \", textFieldLike=\" + Arrays.toString(textFieldLike) + \", textFieldNotLike=\" + Arrays.toString(textFieldNotLike) + \", modifiedIn=\" + Arrays.toString(modifiedIn) + \", modifiedNotIn=\" + Arrays.toString(modifiedNotIn) + \", createdIn=\" + Arrays.toString(createdIn) + \", createdNotIn=\" + Arrays.toString(createdNotIn) + \", accessIdIn=\" + Arrays.toString(accessIdIn) + \", joinWithUserInfo=\" + joinWithUserInfo + \"]\";\n }\n}\n"} {"task_id": "Java_1613", "language": "Java", "task_type": "single_line", "source_file": "java/github/Taskana/taskana/lib/taskana-core/src/main/java/pro/taskana/task/internal/TaskCommentQueryImpl.java", "mask_start_position": 6120, "mask_end_position": 6130, "canonical_solution": "cessIds();", "pre_mask_code": "package pro.taskana.task.internal;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.apache.ibatis.session.RowBounds;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport pro.taskana.common.api.TaskanaRole;\nimport pro.taskana.common.api.TimeInterval;\nimport pro.taskana.common.api.exceptions.NotAuthorizedException;\nimport pro.taskana.common.internal.InternalTaskanaEngine;\nimport pro.taskana.task.api.TaskCommentQuery;\nimport pro.taskana.task.api.TaskCommentQueryColumnName;\nimport pro.taskana.task.api.exceptions.TaskNotFoundException;\nimport pro.taskana.task.api.models.TaskComment;\nimport pro.taskana.workbasket.api.exceptions.NotAuthorizedToQueryWorkbasketException;\nimport pro.taskana.workbasket.internal.WorkbasketQueryImpl;\n\n/**\n * TaskCommentQuery for generating dynamic sql.\n */\npublic class TaskCommentQueryImpl implements TaskCommentQuery {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(TaskCommentQueryImpl.class);\n\n private static final String LINK_TO_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskComments\";\n\n private static final String LINK_TO_VALUE_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskCommentColumnValues\";\n\n private static final String LINK_TO_COUNTER = \"pro.taskana.task.internal.TaskCommentQueryMapper.countQueryTaskComments\";\n\n private final InternalTaskanaEngine taskanaEngine;\n\n private final TaskServiceImpl taskService;\n\n private final List orderBy;\n\n private final List orderColumns;\n\n private TaskCommentQueryColumnName queryColumnName;\n\n private String[] idIn;\n\n private String[] idNotIn;\n\n private String[] idLike;\n\n private String[] idNotLike;\n\n private String[] taskIdIn;\n\n private String[] creatorIn;\n\n private String[] creatorNotIn;\n\n private String[] creatorLike;\n\n private String[] creatorNotLike;\n\n private String[] textFieldLike;\n\n private String[] textFieldNotLike;\n\n private TimeInterval[] modifiedIn;\n\n private TimeInterval[] modifiedNotIn;\n\n private TimeInterval[] createdIn;\n\n private TimeInterval[] createdNotIn;\n\n private String[] accessIdIn;\n\n private boolean joinWithUserInfo;\n\n TaskCommentQueryImpl(InternalTaskanaEngine taskanaEngine) {\n this.taskanaEngine = taskanaEngine;\n this.taskService = (TaskServiceImpl) taskanaEngine.getEngine().getTaskService();\n this.orderBy = new ArrayList<>();\n this.orderColumns = new ArrayList<>();\n this.joinWithUserInfo = taskanaEngine.getEngine().getConfiguration().getAddAdditionalUserInfo();\n }\n\n @Override\n public TaskCommentQuery idIn(String... taskCommentIds) {\n this.idIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotIn(String... taskCommentIds) {\n this.idNotIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idLike(String... taskCommentIds) {\n this.idLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotLike(String... taskCommentIds) {\n this.idNotLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery taskIdIn(String... taskIds) {\n this.taskIdIn = taskIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldLike(String... texts) {\n this.textFieldLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldNotLike(String... texts) {\n this.textFieldNotLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorIn(String... creators) {\n this.creatorIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotIn(String... creators) {\n this.creatorNotIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorLike(String... creators) {\n this.creatorLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotLike(String... creators) {\n this.creatorNotLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery createdWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.createdIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery createdNotWithin(TimeInterval... intervals) {\n this.createdNotIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.modifiedIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedNotWithin(TimeInterval... intervals) {\n this.modifiedNotIn = intervals;\n return this;\n }\n\n @Override\n public List list() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this));\n }\n\n @Override\n public List list(int offset, int limit) {\n checkTaskPermission();\n setupAccessIds();\n RowBounds rowBounds = new RowBounds(offset, limit);\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds));\n }\n\n @Override\n public List listValues(TaskCommentQueryColumnName columnName, SortDirection sortDirection) {\n checkTaskPermission();\n setupAccessIds();\n queryColumnName = columnName;\n if (columnName == TaskCommentQueryColumnName.CREATOR_FULL_NAME) {\n joinWithUserInfo = true;\n }\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_VALUE_MAPPER, this));\n }\n\n @Override\n public TaskComment single() {\n checkTaskPermission();\n setupAc", "post_mask_code": "\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this));\n }\n\n @Override\n public long count() {\n checkTaskPermission();\n setupAccessIds();\n Long rowCount = taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this));\n return (rowCount == null) ? 0L : rowCount;\n }\n\n public TaskCommentQueryColumnName getQueryColumnName() {\n return queryColumnName;\n }\n\n public String[] getIdIn() {\n return idIn;\n }\n\n public String[] getIdNotIn() {\n return idNotIn;\n }\n\n public String[] getIdLike() {\n return idLike;\n }\n\n public String[] getIdNotLike() {\n return idNotLike;\n }\n\n public String[] getTaskIdIn() {\n return taskIdIn;\n }\n\n public String[] getCreatorIn() {\n return creatorIn;\n }\n\n public String[] getCreatorNotIn() {\n return creatorNotIn;\n }\n\n public String[] getCreatorLike() {\n return creatorLike;\n }\n\n public String[] getCreatorNotLike() {\n return creatorNotLike;\n }\n\n public String[] getTextFieldLike() {\n return textFieldLike;\n }\n\n public String[] getTextFieldNotLike() {\n return textFieldNotLike;\n }\n\n public TimeInterval[] getModifiedIn() {\n return modifiedIn;\n }\n\n public TimeInterval[] getModifiedNotIn() {\n return modifiedNotIn;\n }\n\n public TimeInterval[] getCreatedIn() {\n return createdIn;\n }\n\n public TimeInterval[] getCreatedNotIn() {\n return createdNotIn;\n }\n\n public String[] getAccessIdIn() {\n return accessIdIn;\n }\n\n public boolean isIncludeLongName() {\n return joinWithUserInfo;\n }\n\n public void setIncludeLongName(boolean joinWithUserInfo) {\n this.joinWithUserInfo = joinWithUserInfo;\n }\n\n @Override\n public TaskCommentQuery orderByCreated(SortDirection sortDirection) {\n return addOrderCriteria(\"CREATED\", sortDirection);\n }\n\n @Override\n public TaskCommentQuery orderByModified(SortDirection sortDirection) {\n return addOrderCriteria(\"MODIFIED\", sortDirection);\n }\n\n private void checkTaskPermission() {\n if (taskIdIn != null) {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Skipping permissions check since user is in role ADMIN or TASK_ADMIN.\");\n }\n return;\n }\n Arrays.stream(taskIdIn).forEach(taskId -> {\n try {\n taskService.getTask(taskId);\n } catch (NotAuthorizedException e) {\n throw new NotAuthorizedToQueryWorkbasketException(e.getMessage(), e.getErrorCode(), e);\n } catch (TaskNotFoundException e) {\n LOGGER.warn(String.format(\"The Task with the ID ' %s ' does not exist.\", taskId), e);\n }\n });\n }\n }\n\n private TaskCommentQuery addOrderCriteria(String columnName, SortDirection sortDirection) {\n String orderByDirection = \" \" + (sortDirection == null ? SortDirection.ASCENDING : sortDirection);\n orderBy.add(columnName + orderByDirection);\n orderColumns.add(columnName);\n return this;\n }\n\n private void setupAccessIds() {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n this.accessIdIn = null;\n } else if (this.accessIdIn == null) {\n String[] accessIds = new String[0];\n List ucAccessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();\n if (!ucAccessIds.isEmpty()) {\n accessIds = new String[ucAccessIds.size()];\n accessIds = ucAccessIds.toArray(accessIds);\n }\n this.accessIdIn = accessIds;\n WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn);\n }\n }\n\n private void validateAllIntervals(TimeInterval[] intervals) {\n for (TimeInterval ti : intervals) {\n if (!ti.isValid()) {\n throw new IllegalArgumentException(\"TimeInterval \" + ti + \" is invalid.\");\n }\n }\n }\n\n @Override\n public String toString() {\n return \"TaskCommentQueryImpl [taskanaEngine=\" + taskanaEngine + \", taskService=\" + taskService + \", queryColumnName=\" + queryColumnName + \", idIn=\" + Arrays.toString(idIn) + \", idNotIn=\" + Arrays.toString(idNotIn) + \", idLike=\" + Arrays.toString(idLike) + \", idNotLike=\" + Arrays.toString(idNotLike) + \", taskIdIn=\" + Arrays.toString(taskIdIn) + \", creatorIn=\" + Arrays.toString(creatorIn) + \", creatorNotIn=\" + Arrays.toString(creatorNotIn) + \", creatorLike=\" + Arrays.toString(creatorLike) + \", creatorNotLike=\" + Arrays.toString(creatorNotLike) + \", textFieldLike=\" + Arrays.toString(textFieldLike) + \", textFieldNotLike=\" + Arrays.toString(textFieldNotLike) + \", modifiedIn=\" + Arrays.toString(modifiedIn) + \", modifiedNotIn=\" + Arrays.toString(modifiedNotIn) + \", createdIn=\" + Arrays.toString(createdIn) + \", createdNotIn=\" + Arrays.toString(createdNotIn) + \", accessIdIn=\" + Arrays.toString(accessIdIn) + \", joinWithUserInfo=\" + joinWithUserInfo + \"]\";\n }\n}\n"} {"task_id": "Java_1614", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Taskana/taskana/lib/taskana-core/src/main/java/pro/taskana/task/internal/TaskCommentQueryImpl.java", "mask_start_position": 10345, "mask_end_position": 10470, "canonical_solution": "if (!ti.isValid()) {\n throw new IllegalArgumentException(\"TimeInterval \" + ti + \" is invalid.\");\n }", "pre_mask_code": "package pro.taskana.task.internal;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.apache.ibatis.session.RowBounds;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport pro.taskana.common.api.TaskanaRole;\nimport pro.taskana.common.api.TimeInterval;\nimport pro.taskana.common.api.exceptions.NotAuthorizedException;\nimport pro.taskana.common.internal.InternalTaskanaEngine;\nimport pro.taskana.task.api.TaskCommentQuery;\nimport pro.taskana.task.api.TaskCommentQueryColumnName;\nimport pro.taskana.task.api.exceptions.TaskNotFoundException;\nimport pro.taskana.task.api.models.TaskComment;\nimport pro.taskana.workbasket.api.exceptions.NotAuthorizedToQueryWorkbasketException;\nimport pro.taskana.workbasket.internal.WorkbasketQueryImpl;\n\n/**\n * TaskCommentQuery for generating dynamic sql.\n */\npublic class TaskCommentQueryImpl implements TaskCommentQuery {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(TaskCommentQueryImpl.class);\n\n private static final String LINK_TO_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskComments\";\n\n private static final String LINK_TO_VALUE_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskCommentColumnValues\";\n\n private static final String LINK_TO_COUNTER = \"pro.taskana.task.internal.TaskCommentQueryMapper.countQueryTaskComments\";\n\n private final InternalTaskanaEngine taskanaEngine;\n\n private final TaskServiceImpl taskService;\n\n private final List orderBy;\n\n private final List orderColumns;\n\n private TaskCommentQueryColumnName queryColumnName;\n\n private String[] idIn;\n\n private String[] idNotIn;\n\n private String[] idLike;\n\n private String[] idNotLike;\n\n private String[] taskIdIn;\n\n private String[] creatorIn;\n\n private String[] creatorNotIn;\n\n private String[] creatorLike;\n\n private String[] creatorNotLike;\n\n private String[] textFieldLike;\n\n private String[] textFieldNotLike;\n\n private TimeInterval[] modifiedIn;\n\n private TimeInterval[] modifiedNotIn;\n\n private TimeInterval[] createdIn;\n\n private TimeInterval[] createdNotIn;\n\n private String[] accessIdIn;\n\n private boolean joinWithUserInfo;\n\n TaskCommentQueryImpl(InternalTaskanaEngine taskanaEngine) {\n this.taskanaEngine = taskanaEngine;\n this.taskService = (TaskServiceImpl) taskanaEngine.getEngine().getTaskService();\n this.orderBy = new ArrayList<>();\n this.orderColumns = new ArrayList<>();\n this.joinWithUserInfo = taskanaEngine.getEngine().getConfiguration().getAddAdditionalUserInfo();\n }\n\n @Override\n public TaskCommentQuery idIn(String... taskCommentIds) {\n this.idIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotIn(String... taskCommentIds) {\n this.idNotIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idLike(String... taskCommentIds) {\n this.idLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotLike(String... taskCommentIds) {\n this.idNotLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery taskIdIn(String... taskIds) {\n this.taskIdIn = taskIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldLike(String... texts) {\n this.textFieldLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldNotLike(String... texts) {\n this.textFieldNotLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorIn(String... creators) {\n this.creatorIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotIn(String... creators) {\n this.creatorNotIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorLike(String... creators) {\n this.creatorLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotLike(String... creators) {\n this.creatorNotLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery createdWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.createdIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery createdNotWithin(TimeInterval... intervals) {\n this.createdNotIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.modifiedIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedNotWithin(TimeInterval... intervals) {\n this.modifiedNotIn = intervals;\n return this;\n }\n\n @Override\n public List list() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this));\n }\n\n @Override\n public List list(int offset, int limit) {\n checkTaskPermission();\n setupAccessIds();\n RowBounds rowBounds = new RowBounds(offset, limit);\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds));\n }\n\n @Override\n public List listValues(TaskCommentQueryColumnName columnName, SortDirection sortDirection) {\n checkTaskPermission();\n setupAccessIds();\n queryColumnName = columnName;\n if (columnName == TaskCommentQueryColumnName.CREATOR_FULL_NAME) {\n joinWithUserInfo = true;\n }\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_VALUE_MAPPER, this));\n }\n\n @Override\n public TaskComment single() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this));\n }\n\n @Override\n public long count() {\n checkTaskPermission();\n setupAccessIds();\n Long rowCount = taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this));\n return (rowCount == null) ? 0L : rowCount;\n }\n\n public TaskCommentQueryColumnName getQueryColumnName() {\n return queryColumnName;\n }\n\n public String[] getIdIn() {\n return idIn;\n }\n\n public String[] getIdNotIn() {\n return idNotIn;\n }\n\n public String[] getIdLike() {\n return idLike;\n }\n\n public String[] getIdNotLike() {\n return idNotLike;\n }\n\n public String[] getTaskIdIn() {\n return taskIdIn;\n }\n\n public String[] getCreatorIn() {\n return creatorIn;\n }\n\n public String[] getCreatorNotIn() {\n return creatorNotIn;\n }\n\n public String[] getCreatorLike() {\n return creatorLike;\n }\n\n public String[] getCreatorNotLike() {\n return creatorNotLike;\n }\n\n public String[] getTextFieldLike() {\n return textFieldLike;\n }\n\n public String[] getTextFieldNotLike() {\n return textFieldNotLike;\n }\n\n public TimeInterval[] getModifiedIn() {\n return modifiedIn;\n }\n\n public TimeInterval[] getModifiedNotIn() {\n return modifiedNotIn;\n }\n\n public TimeInterval[] getCreatedIn() {\n return createdIn;\n }\n\n public TimeInterval[] getCreatedNotIn() {\n return createdNotIn;\n }\n\n public String[] getAccessIdIn() {\n return accessIdIn;\n }\n\n public boolean isIncludeLongName() {\n return joinWithUserInfo;\n }\n\n public void setIncludeLongName(boolean joinWithUserInfo) {\n this.joinWithUserInfo = joinWithUserInfo;\n }\n\n @Override\n public TaskCommentQuery orderByCreated(SortDirection sortDirection) {\n return addOrderCriteria(\"CREATED\", sortDirection);\n }\n\n @Override\n public TaskCommentQuery orderByModified(SortDirection sortDirection) {\n return addOrderCriteria(\"MODIFIED\", sortDirection);\n }\n\n private void checkTaskPermission() {\n if (taskIdIn != null) {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Skipping permissions check since user is in role ADMIN or TASK_ADMIN.\");\n }\n return;\n }\n Arrays.stream(taskIdIn).forEach(taskId -> {\n try {\n taskService.getTask(taskId);\n } catch (NotAuthorizedException e) {\n throw new NotAuthorizedToQueryWorkbasketException(e.getMessage(), e.getErrorCode(), e);\n } catch (TaskNotFoundException e) {\n LOGGER.warn(String.format(\"The Task with the ID ' %s ' does not exist.\", taskId), e);\n }\n });\n }\n }\n\n private TaskCommentQuery addOrderCriteria(String columnName, SortDirection sortDirection) {\n String orderByDirection = \" \" + (sortDirection == null ? SortDirection.ASCENDING : sortDirection);\n orderBy.add(columnName + orderByDirection);\n orderColumns.add(columnName);\n return this;\n }\n\n private void setupAccessIds() {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n this.accessIdIn = null;\n } else if (this.accessIdIn == null) {\n String[] accessIds = new String[0];\n List ucAccessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();\n if (!ucAccessIds.isEmpty()) {\n accessIds = new String[ucAccessIds.size()];\n accessIds = ucAccessIds.toArray(accessIds);\n }\n this.accessIdIn = accessIds;\n WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn);\n }\n }\n\n private void validateAllIntervals(TimeInterval[] intervals) {\n for (TimeInterval ti : intervals) {\n ", "post_mask_code": "\n }\n }\n\n @Override\n public String toString() {\n return \"TaskCommentQueryImpl [taskanaEngine=\" + taskanaEngine + \", taskService=\" + taskService + \", queryColumnName=\" + queryColumnName + \", idIn=\" + Arrays.toString(idIn) + \", idNotIn=\" + Arrays.toString(idNotIn) + \", idLike=\" + Arrays.toString(idLike) + \", idNotLike=\" + Arrays.toString(idNotLike) + \", taskIdIn=\" + Arrays.toString(taskIdIn) + \", creatorIn=\" + Arrays.toString(creatorIn) + \", creatorNotIn=\" + Arrays.toString(creatorNotIn) + \", creatorLike=\" + Arrays.toString(creatorLike) + \", creatorNotLike=\" + Arrays.toString(creatorNotLike) + \", textFieldLike=\" + Arrays.toString(textFieldLike) + \", textFieldNotLike=\" + Arrays.toString(textFieldNotLike) + \", modifiedIn=\" + Arrays.toString(modifiedIn) + \", modifiedNotIn=\" + Arrays.toString(modifiedNotIn) + \", createdIn=\" + Arrays.toString(createdIn) + \", createdNotIn=\" + Arrays.toString(createdNotIn) + \", accessIdIn=\" + Arrays.toString(accessIdIn) + \", joinWithUserInfo=\" + joinWithUserInfo + \"]\";\n }\n}\n"} {"task_id": "Java_1615", "language": "Java", "task_type": "try_statement", "source_file": "java/github/Taskana/taskana/lib/taskana-core/src/main/java/pro/taskana/task/internal/TaskCommentQueryImpl.java", "mask_start_position": 8806, "mask_end_position": 9197, "canonical_solution": "try {\n taskService.getTask(taskId);\n } catch (NotAuthorizedException e) {\n throw new NotAuthorizedToQueryWorkbasketException(e.getMessage(), e.getErrorCode(), e);\n } catch (TaskNotFoundException e) {\n LOGGER.warn(String.format(\"The Task with the ID ' %s ' does not exist.\", taskId), e);\n }", "pre_mask_code": "package pro.taskana.task.internal;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.apache.ibatis.session.RowBounds;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport pro.taskana.common.api.TaskanaRole;\nimport pro.taskana.common.api.TimeInterval;\nimport pro.taskana.common.api.exceptions.NotAuthorizedException;\nimport pro.taskana.common.internal.InternalTaskanaEngine;\nimport pro.taskana.task.api.TaskCommentQuery;\nimport pro.taskana.task.api.TaskCommentQueryColumnName;\nimport pro.taskana.task.api.exceptions.TaskNotFoundException;\nimport pro.taskana.task.api.models.TaskComment;\nimport pro.taskana.workbasket.api.exceptions.NotAuthorizedToQueryWorkbasketException;\nimport pro.taskana.workbasket.internal.WorkbasketQueryImpl;\n\n/**\n * TaskCommentQuery for generating dynamic sql.\n */\npublic class TaskCommentQueryImpl implements TaskCommentQuery {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(TaskCommentQueryImpl.class);\n\n private static final String LINK_TO_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskComments\";\n\n private static final String LINK_TO_VALUE_MAPPER = \"pro.taskana.task.internal.TaskCommentQueryMapper.queryTaskCommentColumnValues\";\n\n private static final String LINK_TO_COUNTER = \"pro.taskana.task.internal.TaskCommentQueryMapper.countQueryTaskComments\";\n\n private final InternalTaskanaEngine taskanaEngine;\n\n private final TaskServiceImpl taskService;\n\n private final List orderBy;\n\n private final List orderColumns;\n\n private TaskCommentQueryColumnName queryColumnName;\n\n private String[] idIn;\n\n private String[] idNotIn;\n\n private String[] idLike;\n\n private String[] idNotLike;\n\n private String[] taskIdIn;\n\n private String[] creatorIn;\n\n private String[] creatorNotIn;\n\n private String[] creatorLike;\n\n private String[] creatorNotLike;\n\n private String[] textFieldLike;\n\n private String[] textFieldNotLike;\n\n private TimeInterval[] modifiedIn;\n\n private TimeInterval[] modifiedNotIn;\n\n private TimeInterval[] createdIn;\n\n private TimeInterval[] createdNotIn;\n\n private String[] accessIdIn;\n\n private boolean joinWithUserInfo;\n\n TaskCommentQueryImpl(InternalTaskanaEngine taskanaEngine) {\n this.taskanaEngine = taskanaEngine;\n this.taskService = (TaskServiceImpl) taskanaEngine.getEngine().getTaskService();\n this.orderBy = new ArrayList<>();\n this.orderColumns = new ArrayList<>();\n this.joinWithUserInfo = taskanaEngine.getEngine().getConfiguration().getAddAdditionalUserInfo();\n }\n\n @Override\n public TaskCommentQuery idIn(String... taskCommentIds) {\n this.idIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotIn(String... taskCommentIds) {\n this.idNotIn = taskCommentIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery idLike(String... taskCommentIds) {\n this.idLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery idNotLike(String... taskCommentIds) {\n this.idNotLike = toUpperCopy(taskCommentIds);\n return this;\n }\n\n @Override\n public TaskCommentQuery taskIdIn(String... taskIds) {\n this.taskIdIn = taskIds;\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldLike(String... texts) {\n this.textFieldLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery textFieldNotLike(String... texts) {\n this.textFieldNotLike = toUpperCopy(texts);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorIn(String... creators) {\n this.creatorIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotIn(String... creators) {\n this.creatorNotIn = creators;\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorLike(String... creators) {\n this.creatorLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery creatorNotLike(String... creators) {\n this.creatorNotLike = toUpperCopy(creators);\n return this;\n }\n\n @Override\n public TaskCommentQuery createdWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.createdIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery createdNotWithin(TimeInterval... intervals) {\n this.createdNotIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedWithin(TimeInterval... intervals) {\n validateAllIntervals(intervals);\n this.modifiedIn = intervals;\n return this;\n }\n\n @Override\n public TaskCommentQuery modifiedNotWithin(TimeInterval... intervals) {\n this.modifiedNotIn = intervals;\n return this;\n }\n\n @Override\n public List list() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this));\n }\n\n @Override\n public List list(int offset, int limit) {\n checkTaskPermission();\n setupAccessIds();\n RowBounds rowBounds = new RowBounds(offset, limit);\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds));\n }\n\n @Override\n public List listValues(TaskCommentQueryColumnName columnName, SortDirection sortDirection) {\n checkTaskPermission();\n setupAccessIds();\n queryColumnName = columnName;\n if (columnName == TaskCommentQueryColumnName.CREATOR_FULL_NAME) {\n joinWithUserInfo = true;\n }\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectList(LINK_TO_VALUE_MAPPER, this));\n }\n\n @Override\n public TaskComment single() {\n checkTaskPermission();\n setupAccessIds();\n return taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this));\n }\n\n @Override\n public long count() {\n checkTaskPermission();\n setupAccessIds();\n Long rowCount = taskanaEngine.executeInDatabaseConnection(() -> taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this));\n return (rowCount == null) ? 0L : rowCount;\n }\n\n public TaskCommentQueryColumnName getQueryColumnName() {\n return queryColumnName;\n }\n\n public String[] getIdIn() {\n return idIn;\n }\n\n public String[] getIdNotIn() {\n return idNotIn;\n }\n\n public String[] getIdLike() {\n return idLike;\n }\n\n public String[] getIdNotLike() {\n return idNotLike;\n }\n\n public String[] getTaskIdIn() {\n return taskIdIn;\n }\n\n public String[] getCreatorIn() {\n return creatorIn;\n }\n\n public String[] getCreatorNotIn() {\n return creatorNotIn;\n }\n\n public String[] getCreatorLike() {\n return creatorLike;\n }\n\n public String[] getCreatorNotLike() {\n return creatorNotLike;\n }\n\n public String[] getTextFieldLike() {\n return textFieldLike;\n }\n\n public String[] getTextFieldNotLike() {\n return textFieldNotLike;\n }\n\n public TimeInterval[] getModifiedIn() {\n return modifiedIn;\n }\n\n public TimeInterval[] getModifiedNotIn() {\n return modifiedNotIn;\n }\n\n public TimeInterval[] getCreatedIn() {\n return createdIn;\n }\n\n public TimeInterval[] getCreatedNotIn() {\n return createdNotIn;\n }\n\n public String[] getAccessIdIn() {\n return accessIdIn;\n }\n\n public boolean isIncludeLongName() {\n return joinWithUserInfo;\n }\n\n public void setIncludeLongName(boolean joinWithUserInfo) {\n this.joinWithUserInfo = joinWithUserInfo;\n }\n\n @Override\n public TaskCommentQuery orderByCreated(SortDirection sortDirection) {\n return addOrderCriteria(\"CREATED\", sortDirection);\n }\n\n @Override\n public TaskCommentQuery orderByModified(SortDirection sortDirection) {\n return addOrderCriteria(\"MODIFIED\", sortDirection);\n }\n\n private void checkTaskPermission() {\n if (taskIdIn != null) {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Skipping permissions check since user is in role ADMIN or TASK_ADMIN.\");\n }\n return;\n }\n Arrays.stream(taskIdIn).forEach(taskId -> {\n ", "post_mask_code": "\n });\n }\n }\n\n private TaskCommentQuery addOrderCriteria(String columnName, SortDirection sortDirection) {\n String orderByDirection = \" \" + (sortDirection == null ? SortDirection.ASCENDING : sortDirection);\n orderBy.add(columnName + orderByDirection);\n orderColumns.add(columnName);\n return this;\n }\n\n private void setupAccessIds() {\n if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.TASK_ADMIN)) {\n this.accessIdIn = null;\n } else if (this.accessIdIn == null) {\n String[] accessIds = new String[0];\n List ucAccessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();\n if (!ucAccessIds.isEmpty()) {\n accessIds = new String[ucAccessIds.size()];\n accessIds = ucAccessIds.toArray(accessIds);\n }\n this.accessIdIn = accessIds;\n WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn);\n }\n }\n\n private void validateAllIntervals(TimeInterval[] intervals) {\n for (TimeInterval ti : intervals) {\n if (!ti.isValid()) {\n throw new IllegalArgumentException(\"TimeInterval \" + ti + \" is invalid.\");\n }\n }\n }\n\n @Override\n public String toString() {\n return \"TaskCommentQueryImpl [taskanaEngine=\" + taskanaEngine + \", taskService=\" + taskService + \", queryColumnName=\" + queryColumnName + \", idIn=\" + Arrays.toString(idIn) + \", idNotIn=\" + Arrays.toString(idNotIn) + \", idLike=\" + Arrays.toString(idLike) + \", idNotLike=\" + Arrays.toString(idNotLike) + \", taskIdIn=\" + Arrays.toString(taskIdIn) + \", creatorIn=\" + Arrays.toString(creatorIn) + \", creatorNotIn=\" + Arrays.toString(creatorNotIn) + \", creatorLike=\" + Arrays.toString(creatorLike) + \", creatorNotLike=\" + Arrays.toString(creatorNotLike) + \", textFieldLike=\" + Arrays.toString(textFieldLike) + \", textFieldNotLike=\" + Arrays.toString(textFieldNotLike) + \", modifiedIn=\" + Arrays.toString(modifiedIn) + \", modifiedNotIn=\" + Arrays.toString(modifiedNotIn) + \", createdIn=\" + Arrays.toString(createdIn) + \", createdNotIn=\" + Arrays.toString(createdNotIn) + \", accessIdIn=\" + Arrays.toString(accessIdIn) + \", joinWithUserInfo=\" + joinWithUserInfo + \"]\";\n }\n}\n"} {"task_id": "Java_1616", "language": "Java", "task_type": "method_signature", "source_file": "java/github/spring-projects/spring-xd/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/server/admin/deployment/RuntimeModuleDeploymentPropertiesProvider.java", "mask_start_position": 1816, "mask_end_position": 1930, "canonical_solution": "@Override\n public RuntimeModuleDeploymentProperties propertiesForDescriptor(ModuleDescriptor moduleDescriptor) ", "pre_mask_code": "package org.springframework.xd.dirt.server.admin.deployment;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.springframework.xd.module.ModuleDeploymentProperties;\nimport org.springframework.xd.module.ModuleDescriptor;\nimport org.springframework.xd.module.RuntimeModuleDeploymentProperties;\n\n/**\n * Default implementation of {@link ModuleDeploymentPropertiesProvider}\n * for type {@link RuntimeModuleDeploymentProperties}.\n *\n * @author Ilayaperumal Gopinathan\n */\npublic class RuntimeModuleDeploymentPropertiesProvider implements ModuleDeploymentPropertiesProvider {\n\n /**\n * Map to keep track of how many instances of a module this provider\n * has generated properties for. This is used to generate a unique\n * id for each module deployment per container for stream partitioning.\n */\n private final Map mapModuleCount = new HashMap();\n\n /**\n * The {@link ModuleDeploymentProperties} provider for a {@link ModuleDescriptor}\n */\n protected final ModuleDeploymentPropertiesProvider deploymentPropertiesProvider;\n\n /**\n * Construct a {@code DefaultRuntimeModuleDeploymentPropertiesProvider}.\n *\n * @param propertiesProvider the module deployment properties provider\n */\n public RuntimeModuleDeploymentPropertiesProvider(ModuleDeploymentPropertiesProvider propertiesProvider) {\n this.deploymentPropertiesProvider = propertiesProvider;\n }\n\n /**\n * Return the runtime deployment properties for the given module descriptor.\n * Currently, this implementation assigns the module sequence for the given descriptor and add it to\n * the runtime deployment properties.\n */\n ", "post_mask_code": "{\n RuntimeModuleDeploymentProperties properties = new RuntimeModuleDeploymentProperties();\n properties.putAll(deploymentPropertiesProvider.propertiesForDescriptor(moduleDescriptor));\n ModuleDescriptor.Key moduleKey = moduleDescriptor.createKey();\n Integer index = mapModuleCount.get(moduleKey);\n if (index == null) {\n index = 0;\n }\n mapModuleCount.put(moduleKey, index + 1);\n // sequence number only applies if count > 0\n properties.setSequence((properties.getCount() == 0) ? 0 : mapModuleCount.get(moduleKey));\n return properties;\n }\n}\n"} {"task_id": "Java_1617", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/spring-projects/spring-xd/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/server/admin/deployment/RuntimeModuleDeploymentPropertiesProvider.java", "mask_start_position": 1931, "mask_end_position": 2197, "canonical_solution": "\n RuntimeModuleDeploymentProperties properties = new RuntimeModuleDeploymentProperties();\n properties.putAll(deploymentPropertiesProvider.propertiesForDescriptor(moduleDescriptor));\n ModuleDescriptor.Key moduleKey = moduleDescriptor.createKey();", "pre_mask_code": "package org.springframework.xd.dirt.server.admin.deployment;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.springframework.xd.module.ModuleDeploymentProperties;\nimport org.springframework.xd.module.ModuleDescriptor;\nimport org.springframework.xd.module.RuntimeModuleDeploymentProperties;\n\n/**\n * Default implementation of {@link ModuleDeploymentPropertiesProvider}\n * for type {@link RuntimeModuleDeploymentProperties}.\n *\n * @author Ilayaperumal Gopinathan\n */\npublic class RuntimeModuleDeploymentPropertiesProvider implements ModuleDeploymentPropertiesProvider {\n\n /**\n * Map to keep track of how many instances of a module this provider\n * has generated properties for. This is used to generate a unique\n * id for each module deployment per container for stream partitioning.\n */\n private final Map mapModuleCount = new HashMap();\n\n /**\n * The {@link ModuleDeploymentProperties} provider for a {@link ModuleDescriptor}\n */\n protected final ModuleDeploymentPropertiesProvider deploymentPropertiesProvider;\n\n /**\n * Construct a {@code DefaultRuntimeModuleDeploymentPropertiesProvider}.\n *\n * @param propertiesProvider the module deployment properties provider\n */\n public RuntimeModuleDeploymentPropertiesProvider(ModuleDeploymentPropertiesProvider propertiesProvider) {\n this.deploymentPropertiesProvider = propertiesProvider;\n }\n\n /**\n * Return the runtime deployment properties for the given module descriptor.\n * Currently, this implementation assigns the module sequence for the given descriptor and add it to\n * the runtime deployment properties.\n */\n @Override\n public RuntimeModuleDeploymentProperties propertiesForDescriptor(ModuleDescriptor moduleDescriptor) {", "post_mask_code": "\n Integer index = mapModuleCount.get(moduleKey);\n if (index == null) {\n index = 0;\n }\n mapModuleCount.put(moduleKey, index + 1);\n // sequence number only applies if count > 0\n properties.setSequence((properties.getCount() == 0) ? 0 : mapModuleCount.get(moduleKey));\n return properties;\n }\n}\n"} {"task_id": "Java_1618", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/spring-projects/spring-xd/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/server/admin/deployment/RuntimeModuleDeploymentPropertiesProvider.java", "mask_start_position": 2206, "mask_end_position": 2364, "canonical_solution": "Integer index = mapModuleCount.get(moduleKey);\n if (index == null) {\n index = 0;\n }\n mapModuleCount.put(moduleKey, index + 1);", "pre_mask_code": "package org.springframework.xd.dirt.server.admin.deployment;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.springframework.xd.module.ModuleDeploymentProperties;\nimport org.springframework.xd.module.ModuleDescriptor;\nimport org.springframework.xd.module.RuntimeModuleDeploymentProperties;\n\n/**\n * Default implementation of {@link ModuleDeploymentPropertiesProvider}\n * for type {@link RuntimeModuleDeploymentProperties}.\n *\n * @author Ilayaperumal Gopinathan\n */\npublic class RuntimeModuleDeploymentPropertiesProvider implements ModuleDeploymentPropertiesProvider {\n\n /**\n * Map to keep track of how many instances of a module this provider\n * has generated properties for. This is used to generate a unique\n * id for each module deployment per container for stream partitioning.\n */\n private final Map mapModuleCount = new HashMap();\n\n /**\n * The {@link ModuleDeploymentProperties} provider for a {@link ModuleDescriptor}\n */\n protected final ModuleDeploymentPropertiesProvider deploymentPropertiesProvider;\n\n /**\n * Construct a {@code DefaultRuntimeModuleDeploymentPropertiesProvider}.\n *\n * @param propertiesProvider the module deployment properties provider\n */\n public RuntimeModuleDeploymentPropertiesProvider(ModuleDeploymentPropertiesProvider propertiesProvider) {\n this.deploymentPropertiesProvider = propertiesProvider;\n }\n\n /**\n * Return the runtime deployment properties for the given module descriptor.\n * Currently, this implementation assigns the module sequence for the given descriptor and add it to\n * the runtime deployment properties.\n */\n @Override\n public RuntimeModuleDeploymentProperties propertiesForDescriptor(ModuleDescriptor moduleDescriptor) {\n RuntimeModuleDeploymentProperties properties = new RuntimeModuleDeploymentProperties();\n properties.putAll(deploymentPropertiesProvider.propertiesForDescriptor(moduleDescriptor));\n ModuleDescriptor.Key moduleKey = moduleDescriptor.createKey();\n ", "post_mask_code": "\n // sequence number only applies if count > 0\n properties.setSequence((properties.getCount() == 0) ? 0 : mapModuleCount.get(moduleKey));\n return properties;\n }\n}\n"} {"task_id": "Java_1619", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/spring-projects/spring-xd/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/server/admin/deployment/RuntimeModuleDeploymentPropertiesProvider.java", "mask_start_position": 2373, "mask_end_position": 2548, "canonical_solution": "// sequence number only applies if count > 0\n properties.setSequence((properties.getCount() == 0) ? 0 : mapModuleCount.get(moduleKey));\n return properties;\n }", "pre_mask_code": "package org.springframework.xd.dirt.server.admin.deployment;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.springframework.xd.module.ModuleDeploymentProperties;\nimport org.springframework.xd.module.ModuleDescriptor;\nimport org.springframework.xd.module.RuntimeModuleDeploymentProperties;\n\n/**\n * Default implementation of {@link ModuleDeploymentPropertiesProvider}\n * for type {@link RuntimeModuleDeploymentProperties}.\n *\n * @author Ilayaperumal Gopinathan\n */\npublic class RuntimeModuleDeploymentPropertiesProvider implements ModuleDeploymentPropertiesProvider {\n\n /**\n * Map to keep track of how many instances of a module this provider\n * has generated properties for. This is used to generate a unique\n * id for each module deployment per container for stream partitioning.\n */\n private final Map mapModuleCount = new HashMap();\n\n /**\n * The {@link ModuleDeploymentProperties} provider for a {@link ModuleDescriptor}\n */\n protected final ModuleDeploymentPropertiesProvider deploymentPropertiesProvider;\n\n /**\n * Construct a {@code DefaultRuntimeModuleDeploymentPropertiesProvider}.\n *\n * @param propertiesProvider the module deployment properties provider\n */\n public RuntimeModuleDeploymentPropertiesProvider(ModuleDeploymentPropertiesProvider propertiesProvider) {\n this.deploymentPropertiesProvider = propertiesProvider;\n }\n\n /**\n * Return the runtime deployment properties for the given module descriptor.\n * Currently, this implementation assigns the module sequence for the given descriptor and add it to\n * the runtime deployment properties.\n */\n @Override\n public RuntimeModuleDeploymentProperties propertiesForDescriptor(ModuleDescriptor moduleDescriptor) {\n RuntimeModuleDeploymentProperties properties = new RuntimeModuleDeploymentProperties();\n properties.putAll(deploymentPropertiesProvider.propertiesForDescriptor(moduleDescriptor));\n ModuleDescriptor.Key moduleKey = moduleDescriptor.createKey();\n Integer index = mapModuleCount.get(moduleKey);\n if (index == null) {\n index = 0;\n }\n mapModuleCount.put(moduleKey, index + 1);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1620", "language": "Java", "task_type": "single_line", "source_file": "java/github/spring-projects/spring-xd/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/server/admin/deployment/RuntimeModuleDeploymentPropertiesProvider.java", "mask_start_position": 2539, "mask_end_position": 2542, "canonical_solution": "es;", "pre_mask_code": "package org.springframework.xd.dirt.server.admin.deployment;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.springframework.xd.module.ModuleDeploymentProperties;\nimport org.springframework.xd.module.ModuleDescriptor;\nimport org.springframework.xd.module.RuntimeModuleDeploymentProperties;\n\n/**\n * Default implementation of {@link ModuleDeploymentPropertiesProvider}\n * for type {@link RuntimeModuleDeploymentProperties}.\n *\n * @author Ilayaperumal Gopinathan\n */\npublic class RuntimeModuleDeploymentPropertiesProvider implements ModuleDeploymentPropertiesProvider {\n\n /**\n * Map to keep track of how many instances of a module this provider\n * has generated properties for. This is used to generate a unique\n * id for each module deployment per container for stream partitioning.\n */\n private final Map mapModuleCount = new HashMap();\n\n /**\n * The {@link ModuleDeploymentProperties} provider for a {@link ModuleDescriptor}\n */\n protected final ModuleDeploymentPropertiesProvider deploymentPropertiesProvider;\n\n /**\n * Construct a {@code DefaultRuntimeModuleDeploymentPropertiesProvider}.\n *\n * @param propertiesProvider the module deployment properties provider\n */\n public RuntimeModuleDeploymentPropertiesProvider(ModuleDeploymentPropertiesProvider propertiesProvider) {\n this.deploymentPropertiesProvider = propertiesProvider;\n }\n\n /**\n * Return the runtime deployment properties for the given module descriptor.\n * Currently, this implementation assigns the module sequence for the given descriptor and add it to\n * the runtime deployment properties.\n */\n @Override\n public RuntimeModuleDeploymentProperties propertiesForDescriptor(ModuleDescriptor moduleDescriptor) {\n RuntimeModuleDeploymentProperties properties = new RuntimeModuleDeploymentProperties();\n properties.putAll(deploymentPropertiesProvider.propertiesForDescriptor(moduleDescriptor));\n ModuleDescriptor.Key moduleKey = moduleDescriptor.createKey();\n Integer index = mapModuleCount.get(moduleKey);\n if (index == null) {\n index = 0;\n }\n mapModuleCount.put(moduleKey, index + 1);\n // sequence number only applies if count > 0\n properties.setSequence((properties.getCount() == 0) ? 0 : mapModuleCount.get(moduleKey));\n return properti", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1621", "language": "Java", "task_type": "if_statement", "source_file": "java/github/spring-projects/spring-xd/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/server/admin/deployment/RuntimeModuleDeploymentPropertiesProvider.java", "mask_start_position": 2261, "mask_end_position": 2314, "canonical_solution": "if (index == null) {\n index = 0;\n }", "pre_mask_code": "package org.springframework.xd.dirt.server.admin.deployment;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.springframework.xd.module.ModuleDeploymentProperties;\nimport org.springframework.xd.module.ModuleDescriptor;\nimport org.springframework.xd.module.RuntimeModuleDeploymentProperties;\n\n/**\n * Default implementation of {@link ModuleDeploymentPropertiesProvider}\n * for type {@link RuntimeModuleDeploymentProperties}.\n *\n * @author Ilayaperumal Gopinathan\n */\npublic class RuntimeModuleDeploymentPropertiesProvider implements ModuleDeploymentPropertiesProvider {\n\n /**\n * Map to keep track of how many instances of a module this provider\n * has generated properties for. This is used to generate a unique\n * id for each module deployment per container for stream partitioning.\n */\n private final Map mapModuleCount = new HashMap();\n\n /**\n * The {@link ModuleDeploymentProperties} provider for a {@link ModuleDescriptor}\n */\n protected final ModuleDeploymentPropertiesProvider deploymentPropertiesProvider;\n\n /**\n * Construct a {@code DefaultRuntimeModuleDeploymentPropertiesProvider}.\n *\n * @param propertiesProvider the module deployment properties provider\n */\n public RuntimeModuleDeploymentPropertiesProvider(ModuleDeploymentPropertiesProvider propertiesProvider) {\n this.deploymentPropertiesProvider = propertiesProvider;\n }\n\n /**\n * Return the runtime deployment properties for the given module descriptor.\n * Currently, this implementation assigns the module sequence for the given descriptor and add it to\n * the runtime deployment properties.\n */\n @Override\n public RuntimeModuleDeploymentProperties propertiesForDescriptor(ModuleDescriptor moduleDescriptor) {\n RuntimeModuleDeploymentProperties properties = new RuntimeModuleDeploymentProperties();\n properties.putAll(deploymentPropertiesProvider.propertiesForDescriptor(moduleDescriptor));\n ModuleDescriptor.Key moduleKey = moduleDescriptor.createKey();\n Integer index = mapModuleCount.get(moduleKey);\n ", "post_mask_code": "\n mapModuleCount.put(moduleKey, index + 1);\n // sequence number only applies if count > 0\n properties.setSequence((properties.getCount() == 0) ? 0 : mapModuleCount.get(moduleKey));\n return properties;\n }\n}\n"} {"task_id": "Java_1622", "language": "Java", "task_type": "method_signature", "source_file": "java/github/archimatetool/archi-scripting-plugin/com.archimatetool.script/src/com/archimatetool/script/commands/ScriptCommand.java", "mask_start_position": 963, "mask_end_position": 1005, "canonical_solution": "@Override\n public final void execute() ", "pre_mask_code": "package com.archimatetool.script.commands;\n\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.gef.commands.Command;\nimport com.archimatetool.model.IArchimateModel;\n\n/**\n * ScriptCommand\n *\n * @author Phillip Beauvoir\n */\npublic abstract class ScriptCommand extends Command {\n\n private IArchimateModel model;\n\n protected ScriptCommand(String name, IArchimateModel model) {\n super(name);\n this.model = model;\n }\n\n protected ScriptCommand(String name, EObject eObject) {\n super(name);\n setModel(eObject);\n }\n\n protected ScriptCommand(String name) {\n super(name);\n }\n\n protected void setModel(EObject eObject) {\n while (!(eObject instanceof IArchimateModel) && eObject != null) {\n eObject = eObject.eContainer();\n }\n model = (IArchimateModel) eObject;\n }\n\n public IArchimateModel getModel() {\n return model;\n }\n\n public abstract void perform();\n\n ", "post_mask_code": "{\n // Do nothing. Do not use! Use perform() instead.\n }\n\n @Override\n public void redo() {\n perform();\n }\n\n @Override\n public void dispose() {\n model = null;\n }\n}\n"} {"task_id": "Java_1623", "language": "Java", "task_type": "method_body", "source_file": "java/github/archimatetool/archi-scripting-plugin/com.archimatetool.script/src/com/archimatetool/script/commands/ScriptCommand.java", "mask_start_position": 891, "mask_end_position": 920, "canonical_solution": "{\n return model;\n }", "pre_mask_code": "package com.archimatetool.script.commands;\n\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.gef.commands.Command;\nimport com.archimatetool.model.IArchimateModel;\n\n/**\n * ScriptCommand\n *\n * @author Phillip Beauvoir\n */\npublic abstract class ScriptCommand extends Command {\n\n private IArchimateModel model;\n\n protected ScriptCommand(String name, IArchimateModel model) {\n super(name);\n this.model = model;\n }\n\n protected ScriptCommand(String name, EObject eObject) {\n super(name);\n setModel(eObject);\n }\n\n protected ScriptCommand(String name) {\n super(name);\n }\n\n protected void setModel(EObject eObject) {\n while (!(eObject instanceof IArchimateModel) && eObject != null) {\n eObject = eObject.eContainer();\n }\n model = (IArchimateModel) eObject;\n }\n\n public IArchimateModel getModel() ", "post_mask_code": "\n\n public abstract void perform();\n\n @Override\n public final void execute() {\n // Do nothing. Do not use! Use perform() instead.\n }\n\n @Override\n public void redo() {\n perform();\n }\n\n @Override\n public void dispose() {\n model = null;\n }\n}\n"} {"task_id": "Java_1624", "language": "Java", "task_type": "single_line", "source_file": "java/github/archimatetool/archi-scripting-plugin/com.archimatetool.script/src/com/archimatetool/script/commands/ScriptCommand.java", "mask_start_position": 1196, "mask_end_position": 1200, "canonical_solution": "ull;", "pre_mask_code": "package com.archimatetool.script.commands;\n\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.gef.commands.Command;\nimport com.archimatetool.model.IArchimateModel;\n\n/**\n * ScriptCommand\n *\n * @author Phillip Beauvoir\n */\npublic abstract class ScriptCommand extends Command {\n\n private IArchimateModel model;\n\n protected ScriptCommand(String name, IArchimateModel model) {\n super(name);\n this.model = model;\n }\n\n protected ScriptCommand(String name, EObject eObject) {\n super(name);\n setModel(eObject);\n }\n\n protected ScriptCommand(String name) {\n super(name);\n }\n\n protected void setModel(EObject eObject) {\n while (!(eObject instanceof IArchimateModel) && eObject != null) {\n eObject = eObject.eContainer();\n }\n model = (IArchimateModel) eObject;\n }\n\n public IArchimateModel getModel() {\n return model;\n }\n\n public abstract void perform();\n\n @Override\n public final void execute() {\n // Do nothing. Do not use! Use perform() instead.\n }\n\n @Override\n public void redo() {\n perform();\n }\n\n @Override\n public void dispose() {\n model = n", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1625", "language": "Java", "task_type": "while_statement", "source_file": "java/github/archimatetool/archi-scripting-plugin/com.archimatetool.script/src/com/archimatetool/script/commands/ScriptCommand.java", "mask_start_position": 682, "mask_end_position": 802, "canonical_solution": "while (!(eObject instanceof IArchimateModel) && eObject != null) {\n eObject = eObject.eContainer();\n }", "pre_mask_code": "package com.archimatetool.script.commands;\n\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.gef.commands.Command;\nimport com.archimatetool.model.IArchimateModel;\n\n/**\n * ScriptCommand\n *\n * @author Phillip Beauvoir\n */\npublic abstract class ScriptCommand extends Command {\n\n private IArchimateModel model;\n\n protected ScriptCommand(String name, IArchimateModel model) {\n super(name);\n this.model = model;\n }\n\n protected ScriptCommand(String name, EObject eObject) {\n super(name);\n setModel(eObject);\n }\n\n protected ScriptCommand(String name) {\n super(name);\n }\n\n protected void setModel(EObject eObject) {\n ", "post_mask_code": "\n model = (IArchimateModel) eObject;\n }\n\n public IArchimateModel getModel() {\n return model;\n }\n\n public abstract void perform();\n\n @Override\n public final void execute() {\n // Do nothing. Do not use! Use perform() instead.\n }\n\n @Override\n public void redo() {\n perform();\n }\n\n @Override\n public void dispose() {\n model = null;\n }\n}\n"} {"task_id": "Java_1626", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cdapio/cdap/cdap-watchdog/src/main/java/io/cdap/cdap/logging/logbuffer/recover/LogBufferRecoveryService.java", "mask_start_position": 4536, "mask_end_position": 4593, "canonical_solution": "@Override\n protected void shutDown() throws Exception ", "pre_mask_code": "package io.cdap.cdap.logging.logbuffer.recover;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.util.concurrent.AbstractExecutionThreadService;\nimport io.cdap.cdap.common.conf.CConfiguration;\nimport io.cdap.cdap.common.conf.Constants;\nimport io.cdap.cdap.common.logging.LogSamplers;\nimport io.cdap.cdap.common.logging.Loggers;\nimport io.cdap.cdap.logging.logbuffer.LogBufferEvent;\nimport io.cdap.cdap.logging.logbuffer.LogBufferFileOffset;\nimport io.cdap.cdap.logging.meta.CheckpointManager;\nimport io.cdap.cdap.logging.pipeline.logbuffer.LogBufferProcessorPipeline;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\n/**\n * Log buffer recovery service which recovers logs upon log saver restart and sends them to log buffer pipeline for\n * further processing. This service first scans all the files to figure out max file id till which it should recover.\n * This is because while recovery service is running, new files can be created. Recovery service should not recover\n * those logs.\n */\npublic class LogBufferRecoveryService extends AbstractExecutionThreadService {\n\n private static final Logger LOG = LoggerFactory.getLogger(LogBufferRecoveryService.class);\n\n // For outage, only log once per 60 seconds per message.\n private static final Logger OUTAGE_LOG = Loggers.sampling(LOG, LogSamplers.perMessage(() -> LogSamplers.limitRate(60000)));\n\n private static final String SERVICE_NAME = \"log.buffer.recovery\";\n\n private final List pipelines;\n\n private final List> checkpointManagers;\n\n private final String baseLogDir;\n\n private final boolean baseDirExists;\n\n private final int batchSize;\n\n private final CountDownLatch stopLatch;\n\n private final AtomicBoolean startCleanup;\n\n private LogBufferReader reader;\n\n private volatile boolean stopped;\n\n public LogBufferRecoveryService(CConfiguration cConf, List pipelines, List> checkpointManagers, AtomicBoolean startCleanup) {\n this(pipelines, checkpointManagers, cConf.get(Constants.LogBuffer.LOG_BUFFER_BASE_DIR), cConf.getInt(Constants.LogBuffer.LOG_BUFFER_RECOVERY_BATCH_SIZE), startCleanup);\n }\n\n @VisibleForTesting\n LogBufferRecoveryService(List pipelines, List> checkpointManager, String baseLogDir, int batchSize, AtomicBoolean startCleanup) {\n this.pipelines = pipelines;\n this.checkpointManagers = checkpointManager;\n this.baseLogDir = baseLogDir;\n this.baseDirExists = dirExists(baseLogDir);\n this.batchSize = batchSize;\n this.stopLatch = new CountDownLatch(1);\n this.startCleanup = startCleanup;\n }\n\n @Override\n protected void startUp() throws Exception {\n if (baseDirExists) {\n // get the smallest offset of all the log pipelines\n LogBufferFileOffset minOffset = getSmallestOffset(checkpointManagers);\n this.reader = new LogBufferReader(baseLogDir, batchSize, getMaxFileId(baseLogDir), minOffset.getFileId(), minOffset.getFilePos());\n }\n }\n\n @Override\n protected void run() throws Exception {\n if (baseDirExists) {\n List logBufferEvents = new LinkedList<>();\n boolean hasReadEvents = true;\n while (!stopped && hasReadEvents) {\n try {\n hasReadEvents = reader.readEvents(logBufferEvents) > 0;\n recoverLogs(logBufferEvents, pipelines);\n } catch (Exception e) {\n // even though error occurred while reading, whatever logs were read, those should be processed. This is\n // because recovery service should be finished quickly so that the logs are persisted in almost sorted order.\n recoverLogs(logBufferEvents, pipelines);\n OUTAGE_LOG.warn(\"Failed to recover logs from log buffer. Read will be retried.\", e);\n // in case of failure to read, sleep and then retry\n stopLatch.await(500, TimeUnit.MILLISECONDS);\n }\n }\n }\n startCleanup.set(true);\n }\n\n ", "post_mask_code": "{\n if (reader != null) {\n reader.close();\n }\n }\n\n @Override\n protected void triggerShutdown() {\n stopped = true;\n stopLatch.countDown();\n }\n\n @Override\n protected String getServiceName() {\n return SERVICE_NAME;\n }\n\n private LogBufferFileOffset getSmallestOffset(List> checkpointManagers) throws IOException {\n // there will be atleast one log pipeline\n LogBufferFileOffset minOffset = checkpointManagers.get(0).getCheckpoint(0).getOffset();\n for (int i = 1; i < checkpointManagers.size(); i++) {\n LogBufferFileOffset offset = checkpointManagers.get(i).getCheckpoint(0).getOffset();\n // keep track of minimum offset\n minOffset = minOffset.compareTo(offset) > 0 ? offset : minOffset;\n }\n return minOffset;\n }\n\n private void recoverLogs(List logBufferEvents, List pipelines) {\n for (LogBufferProcessorPipeline pipeline : pipelines) {\n pipeline.processLogEvents(logBufferEvents.iterator());\n }\n logBufferEvents.clear();\n }\n\n private long getMaxFileId(String baseDir) {\n long maxFileId = -1;\n File[] files = new File(baseDir).listFiles();\n if (files != null) {\n for (File file : files) {\n String[] splitted = file.getName().split(\"\\\\.\");\n long fileId = Long.parseLong(splitted[0]);\n if (maxFileId < fileId) {\n maxFileId = fileId;\n }\n }\n }\n return maxFileId;\n }\n\n private boolean dirExists(String baseLogDir) {\n File baseDir = new File(baseLogDir);\n return baseDir.exists();\n }\n}\n"} {"task_id": "Java_1627", "language": "Java", "task_type": "method_body", "source_file": "java/github/cdapio/cdap/cdap-watchdog/src/main/java/io/cdap/cdap/logging/logbuffer/recover/LogBufferRecoveryService.java", "mask_start_position": 4721, "mask_end_position": 4783, "canonical_solution": "{\n stopped = true;\n stopLatch.countDown();\n }", "pre_mask_code": "package io.cdap.cdap.logging.logbuffer.recover;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.util.concurrent.AbstractExecutionThreadService;\nimport io.cdap.cdap.common.conf.CConfiguration;\nimport io.cdap.cdap.common.conf.Constants;\nimport io.cdap.cdap.common.logging.LogSamplers;\nimport io.cdap.cdap.common.logging.Loggers;\nimport io.cdap.cdap.logging.logbuffer.LogBufferEvent;\nimport io.cdap.cdap.logging.logbuffer.LogBufferFileOffset;\nimport io.cdap.cdap.logging.meta.CheckpointManager;\nimport io.cdap.cdap.logging.pipeline.logbuffer.LogBufferProcessorPipeline;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\n/**\n * Log buffer recovery service which recovers logs upon log saver restart and sends them to log buffer pipeline for\n * further processing. This service first scans all the files to figure out max file id till which it should recover.\n * This is because while recovery service is running, new files can be created. Recovery service should not recover\n * those logs.\n */\npublic class LogBufferRecoveryService extends AbstractExecutionThreadService {\n\n private static final Logger LOG = LoggerFactory.getLogger(LogBufferRecoveryService.class);\n\n // For outage, only log once per 60 seconds per message.\n private static final Logger OUTAGE_LOG = Loggers.sampling(LOG, LogSamplers.perMessage(() -> LogSamplers.limitRate(60000)));\n\n private static final String SERVICE_NAME = \"log.buffer.recovery\";\n\n private final List pipelines;\n\n private final List> checkpointManagers;\n\n private final String baseLogDir;\n\n private final boolean baseDirExists;\n\n private final int batchSize;\n\n private final CountDownLatch stopLatch;\n\n private final AtomicBoolean startCleanup;\n\n private LogBufferReader reader;\n\n private volatile boolean stopped;\n\n public LogBufferRecoveryService(CConfiguration cConf, List pipelines, List> checkpointManagers, AtomicBoolean startCleanup) {\n this(pipelines, checkpointManagers, cConf.get(Constants.LogBuffer.LOG_BUFFER_BASE_DIR), cConf.getInt(Constants.LogBuffer.LOG_BUFFER_RECOVERY_BATCH_SIZE), startCleanup);\n }\n\n @VisibleForTesting\n LogBufferRecoveryService(List pipelines, List> checkpointManager, String baseLogDir, int batchSize, AtomicBoolean startCleanup) {\n this.pipelines = pipelines;\n this.checkpointManagers = checkpointManager;\n this.baseLogDir = baseLogDir;\n this.baseDirExists = dirExists(baseLogDir);\n this.batchSize = batchSize;\n this.stopLatch = new CountDownLatch(1);\n this.startCleanup = startCleanup;\n }\n\n @Override\n protected void startUp() throws Exception {\n if (baseDirExists) {\n // get the smallest offset of all the log pipelines\n LogBufferFileOffset minOffset = getSmallestOffset(checkpointManagers);\n this.reader = new LogBufferReader(baseLogDir, batchSize, getMaxFileId(baseLogDir), minOffset.getFileId(), minOffset.getFilePos());\n }\n }\n\n @Override\n protected void run() throws Exception {\n if (baseDirExists) {\n List logBufferEvents = new LinkedList<>();\n boolean hasReadEvents = true;\n while (!stopped && hasReadEvents) {\n try {\n hasReadEvents = reader.readEvents(logBufferEvents) > 0;\n recoverLogs(logBufferEvents, pipelines);\n } catch (Exception e) {\n // even though error occurred while reading, whatever logs were read, those should be processed. This is\n // because recovery service should be finished quickly so that the logs are persisted in almost sorted order.\n recoverLogs(logBufferEvents, pipelines);\n OUTAGE_LOG.warn(\"Failed to recover logs from log buffer. Read will be retried.\", e);\n // in case of failure to read, sleep and then retry\n stopLatch.await(500, TimeUnit.MILLISECONDS);\n }\n }\n }\n startCleanup.set(true);\n }\n\n @Override\n protected void shutDown() throws Exception {\n if (reader != null) {\n reader.close();\n }\n }\n\n @Override\n protected void triggerShutdown() ", "post_mask_code": "\n\n @Override\n protected String getServiceName() {\n return SERVICE_NAME;\n }\n\n private LogBufferFileOffset getSmallestOffset(List> checkpointManagers) throws IOException {\n // there will be atleast one log pipeline\n LogBufferFileOffset minOffset = checkpointManagers.get(0).getCheckpoint(0).getOffset();\n for (int i = 1; i < checkpointManagers.size(); i++) {\n LogBufferFileOffset offset = checkpointManagers.get(i).getCheckpoint(0).getOffset();\n // keep track of minimum offset\n minOffset = minOffset.compareTo(offset) > 0 ? offset : minOffset;\n }\n return minOffset;\n }\n\n private void recoverLogs(List logBufferEvents, List pipelines) {\n for (LogBufferProcessorPipeline pipeline : pipelines) {\n pipeline.processLogEvents(logBufferEvents.iterator());\n }\n logBufferEvents.clear();\n }\n\n private long getMaxFileId(String baseDir) {\n long maxFileId = -1;\n File[] files = new File(baseDir).listFiles();\n if (files != null) {\n for (File file : files) {\n String[] splitted = file.getName().split(\"\\\\.\");\n long fileId = Long.parseLong(splitted[0]);\n if (maxFileId < fileId) {\n maxFileId = fileId;\n }\n }\n }\n return maxFileId;\n }\n\n private boolean dirExists(String baseLogDir) {\n File baseDir = new File(baseLogDir);\n return baseDir.exists();\n }\n}\n"} {"task_id": "Java_1628", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/cdapio/cdap/cdap-watchdog/src/main/java/io/cdap/cdap/logging/logbuffer/recover/LogBufferRecoveryService.java", "mask_start_position": 3109, "mask_end_position": 3109, "canonical_solution": "", "pre_mask_code": "package io.cdap.cdap.logging.logbuffer.recover;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.util.concurrent.AbstractExecutionThreadService;\nimport io.cdap.cdap.common.conf.CConfiguration;\nimport io.cdap.cdap.common.conf.Constants;\nimport io.cdap.cdap.common.logging.LogSamplers;\nimport io.cdap.cdap.common.logging.Loggers;\nimport io.cdap.cdap.logging.logbuffer.LogBufferEvent;\nimport io.cdap.cdap.logging.logbuffer.LogBufferFileOffset;\nimport io.cdap.cdap.logging.meta.CheckpointManager;\nimport io.cdap.cdap.logging.pipeline.logbuffer.LogBufferProcessorPipeline;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\n/**\n * Log buffer recovery service which recovers logs upon log saver restart and sends them to log buffer pipeline for\n * further processing. This service first scans all the files to figure out max file id till which it should recover.\n * This is because while recovery service is running, new files can be created. Recovery service should not recover\n * those logs.\n */\npublic class LogBufferRecoveryService extends AbstractExecutionThreadService {\n\n private static final Logger LOG = LoggerFactory.getLogger(LogBufferRecoveryService.class);\n\n // For outage, only log once per 60 seconds per message.\n private static final Logger OUTAGE_LOG = Loggers.sampling(LOG, LogSamplers.perMessage(() -> LogSamplers.limitRate(60000)));\n\n private static final String SERVICE_NAME = \"log.buffer.recovery\";\n\n private final List pipelines;\n\n private final List> checkpointManagers;\n\n private final String baseLogDir;\n\n private final boolean baseDirExists;\n\n private final int batchSize;\n\n private final CountDownLatch stopLatch;\n\n private final AtomicBoolean startCleanup;\n\n private LogBufferReader reader;\n\n private volatile boolean stopped;\n\n public LogBufferRecoveryService(CConfiguration cConf, List pipelines, List> checkpointManagers, AtomicBoolean startCleanup) {\n this(pipelines, checkpointManagers, cConf.get(Constants.LogBuffer.LOG_BUFFER_BASE_DIR), cConf.getInt(Constants.LogBuffer.LOG_BUFFER_RECOVERY_BATCH_SIZE), startCleanup);\n }\n\n @VisibleForTesting\n LogBufferRecoveryService(List pipelines, List> checkpointManager, String baseLogDir, int batchSize, AtomicBoolean startCleanup) {\n this.pipelines = pipelines;\n this.checkpointManagers = checkpointManager;\n this.baseLogDir = baseLogDir;\n this.baseDirExists = dirExists(baseLogDir);\n this.batchSize = batchSize;\n this.stopLatch = new CountDownLatch(1);\n this.startCleanup = startCleanup;\n }\n\n @Override\n protected void startUp() throws Exception {", "post_mask_code": "\n if (baseDirExists) {\n // get the smallest offset of all the log pipelines\n LogBufferFileOffset minOffset = getSmallestOffset(checkpointManagers);\n this.reader = new LogBufferReader(baseLogDir, batchSize, getMaxFileId(baseLogDir), minOffset.getFileId(), minOffset.getFilePos());\n }\n }\n\n @Override\n protected void run() throws Exception {\n if (baseDirExists) {\n List logBufferEvents = new LinkedList<>();\n boolean hasReadEvents = true;\n while (!stopped && hasReadEvents) {\n try {\n hasReadEvents = reader.readEvents(logBufferEvents) > 0;\n recoverLogs(logBufferEvents, pipelines);\n } catch (Exception e) {\n // even though error occurred while reading, whatever logs were read, those should be processed. This is\n // because recovery service should be finished quickly so that the logs are persisted in almost sorted order.\n recoverLogs(logBufferEvents, pipelines);\n OUTAGE_LOG.warn(\"Failed to recover logs from log buffer. Read will be retried.\", e);\n // in case of failure to read, sleep and then retry\n stopLatch.await(500, TimeUnit.MILLISECONDS);\n }\n }\n }\n startCleanup.set(true);\n }\n\n @Override\n protected void shutDown() throws Exception {\n if (reader != null) {\n reader.close();\n }\n }\n\n @Override\n protected void triggerShutdown() {\n stopped = true;\n stopLatch.countDown();\n }\n\n @Override\n protected String getServiceName() {\n return SERVICE_NAME;\n }\n\n private LogBufferFileOffset getSmallestOffset(List> checkpointManagers) throws IOException {\n // there will be atleast one log pipeline\n LogBufferFileOffset minOffset = checkpointManagers.get(0).getCheckpoint(0).getOffset();\n for (int i = 1; i < checkpointManagers.size(); i++) {\n LogBufferFileOffset offset = checkpointManagers.get(i).getCheckpoint(0).getOffset();\n // keep track of minimum offset\n minOffset = minOffset.compareTo(offset) > 0 ? offset : minOffset;\n }\n return minOffset;\n }\n\n private void recoverLogs(List logBufferEvents, List pipelines) {\n for (LogBufferProcessorPipeline pipeline : pipelines) {\n pipeline.processLogEvents(logBufferEvents.iterator());\n }\n logBufferEvents.clear();\n }\n\n private long getMaxFileId(String baseDir) {\n long maxFileId = -1;\n File[] files = new File(baseDir).listFiles();\n if (files != null) {\n for (File file : files) {\n String[] splitted = file.getName().split(\"\\\\.\");\n long fileId = Long.parseLong(splitted[0]);\n if (maxFileId < fileId) {\n maxFileId = fileId;\n }\n }\n }\n return maxFileId;\n }\n\n private boolean dirExists(String baseLogDir) {\n File baseDir = new File(baseLogDir);\n return baseDir.exists();\n }\n}\n"} {"task_id": "Java_1629", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/cdapio/cdap/cdap-watchdog/src/main/java/io/cdap/cdap/logging/logbuffer/recover/LogBufferRecoveryService.java", "mask_start_position": 3118, "mask_end_position": 3438, "canonical_solution": "if (baseDirExists) {\n // get the smallest offset of all the log pipelines\n LogBufferFileOffset minOffset = getSmallestOffset(checkpointManagers);\n this.reader = new LogBufferReader(baseLogDir, batchSize, getMaxFileId(baseLogDir), minOffset.getFileId(), minOffset.getFilePos());\n }", "pre_mask_code": "package io.cdap.cdap.logging.logbuffer.recover;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.util.concurrent.AbstractExecutionThreadService;\nimport io.cdap.cdap.common.conf.CConfiguration;\nimport io.cdap.cdap.common.conf.Constants;\nimport io.cdap.cdap.common.logging.LogSamplers;\nimport io.cdap.cdap.common.logging.Loggers;\nimport io.cdap.cdap.logging.logbuffer.LogBufferEvent;\nimport io.cdap.cdap.logging.logbuffer.LogBufferFileOffset;\nimport io.cdap.cdap.logging.meta.CheckpointManager;\nimport io.cdap.cdap.logging.pipeline.logbuffer.LogBufferProcessorPipeline;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\n/**\n * Log buffer recovery service which recovers logs upon log saver restart and sends them to log buffer pipeline for\n * further processing. This service first scans all the files to figure out max file id till which it should recover.\n * This is because while recovery service is running, new files can be created. Recovery service should not recover\n * those logs.\n */\npublic class LogBufferRecoveryService extends AbstractExecutionThreadService {\n\n private static final Logger LOG = LoggerFactory.getLogger(LogBufferRecoveryService.class);\n\n // For outage, only log once per 60 seconds per message.\n private static final Logger OUTAGE_LOG = Loggers.sampling(LOG, LogSamplers.perMessage(() -> LogSamplers.limitRate(60000)));\n\n private static final String SERVICE_NAME = \"log.buffer.recovery\";\n\n private final List pipelines;\n\n private final List> checkpointManagers;\n\n private final String baseLogDir;\n\n private final boolean baseDirExists;\n\n private final int batchSize;\n\n private final CountDownLatch stopLatch;\n\n private final AtomicBoolean startCleanup;\n\n private LogBufferReader reader;\n\n private volatile boolean stopped;\n\n public LogBufferRecoveryService(CConfiguration cConf, List pipelines, List> checkpointManagers, AtomicBoolean startCleanup) {\n this(pipelines, checkpointManagers, cConf.get(Constants.LogBuffer.LOG_BUFFER_BASE_DIR), cConf.getInt(Constants.LogBuffer.LOG_BUFFER_RECOVERY_BATCH_SIZE), startCleanup);\n }\n\n @VisibleForTesting\n LogBufferRecoveryService(List pipelines, List> checkpointManager, String baseLogDir, int batchSize, AtomicBoolean startCleanup) {\n this.pipelines = pipelines;\n this.checkpointManagers = checkpointManager;\n this.baseLogDir = baseLogDir;\n this.baseDirExists = dirExists(baseLogDir);\n this.batchSize = batchSize;\n this.stopLatch = new CountDownLatch(1);\n this.startCleanup = startCleanup;\n }\n\n @Override\n protected void startUp() throws Exception {\n ", "post_mask_code": "\n }\n\n @Override\n protected void run() throws Exception {\n if (baseDirExists) {\n List logBufferEvents = new LinkedList<>();\n boolean hasReadEvents = true;\n while (!stopped && hasReadEvents) {\n try {\n hasReadEvents = reader.readEvents(logBufferEvents) > 0;\n recoverLogs(logBufferEvents, pipelines);\n } catch (Exception e) {\n // even though error occurred while reading, whatever logs were read, those should be processed. This is\n // because recovery service should be finished quickly so that the logs are persisted in almost sorted order.\n recoverLogs(logBufferEvents, pipelines);\n OUTAGE_LOG.warn(\"Failed to recover logs from log buffer. Read will be retried.\", e);\n // in case of failure to read, sleep and then retry\n stopLatch.await(500, TimeUnit.MILLISECONDS);\n }\n }\n }\n startCleanup.set(true);\n }\n\n @Override\n protected void shutDown() throws Exception {\n if (reader != null) {\n reader.close();\n }\n }\n\n @Override\n protected void triggerShutdown() {\n stopped = true;\n stopLatch.countDown();\n }\n\n @Override\n protected String getServiceName() {\n return SERVICE_NAME;\n }\n\n private LogBufferFileOffset getSmallestOffset(List> checkpointManagers) throws IOException {\n // there will be atleast one log pipeline\n LogBufferFileOffset minOffset = checkpointManagers.get(0).getCheckpoint(0).getOffset();\n for (int i = 1; i < checkpointManagers.size(); i++) {\n LogBufferFileOffset offset = checkpointManagers.get(i).getCheckpoint(0).getOffset();\n // keep track of minimum offset\n minOffset = minOffset.compareTo(offset) > 0 ? offset : minOffset;\n }\n return minOffset;\n }\n\n private void recoverLogs(List logBufferEvents, List pipelines) {\n for (LogBufferProcessorPipeline pipeline : pipelines) {\n pipeline.processLogEvents(logBufferEvents.iterator());\n }\n logBufferEvents.clear();\n }\n\n private long getMaxFileId(String baseDir) {\n long maxFileId = -1;\n File[] files = new File(baseDir).listFiles();\n if (files != null) {\n for (File file : files) {\n String[] splitted = file.getName().split(\"\\\\.\");\n long fileId = Long.parseLong(splitted[0]);\n if (maxFileId < fileId) {\n maxFileId = fileId;\n }\n }\n }\n return maxFileId;\n }\n\n private boolean dirExists(String baseLogDir) {\n File baseDir = new File(baseLogDir);\n return baseDir.exists();\n }\n}\n"} {"task_id": "Java_1630", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/cdapio/cdap/cdap-watchdog/src/main/java/io/cdap/cdap/logging/logbuffer/recover/LogBufferRecoveryService.java", "mask_start_position": 3443, "mask_end_position": 3444, "canonical_solution": "}", "pre_mask_code": "package io.cdap.cdap.logging.logbuffer.recover;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.util.concurrent.AbstractExecutionThreadService;\nimport io.cdap.cdap.common.conf.CConfiguration;\nimport io.cdap.cdap.common.conf.Constants;\nimport io.cdap.cdap.common.logging.LogSamplers;\nimport io.cdap.cdap.common.logging.Loggers;\nimport io.cdap.cdap.logging.logbuffer.LogBufferEvent;\nimport io.cdap.cdap.logging.logbuffer.LogBufferFileOffset;\nimport io.cdap.cdap.logging.meta.CheckpointManager;\nimport io.cdap.cdap.logging.pipeline.logbuffer.LogBufferProcessorPipeline;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\n/**\n * Log buffer recovery service which recovers logs upon log saver restart and sends them to log buffer pipeline for\n * further processing. This service first scans all the files to figure out max file id till which it should recover.\n * This is because while recovery service is running, new files can be created. Recovery service should not recover\n * those logs.\n */\npublic class LogBufferRecoveryService extends AbstractExecutionThreadService {\n\n private static final Logger LOG = LoggerFactory.getLogger(LogBufferRecoveryService.class);\n\n // For outage, only log once per 60 seconds per message.\n private static final Logger OUTAGE_LOG = Loggers.sampling(LOG, LogSamplers.perMessage(() -> LogSamplers.limitRate(60000)));\n\n private static final String SERVICE_NAME = \"log.buffer.recovery\";\n\n private final List pipelines;\n\n private final List> checkpointManagers;\n\n private final String baseLogDir;\n\n private final boolean baseDirExists;\n\n private final int batchSize;\n\n private final CountDownLatch stopLatch;\n\n private final AtomicBoolean startCleanup;\n\n private LogBufferReader reader;\n\n private volatile boolean stopped;\n\n public LogBufferRecoveryService(CConfiguration cConf, List pipelines, List> checkpointManagers, AtomicBoolean startCleanup) {\n this(pipelines, checkpointManagers, cConf.get(Constants.LogBuffer.LOG_BUFFER_BASE_DIR), cConf.getInt(Constants.LogBuffer.LOG_BUFFER_RECOVERY_BATCH_SIZE), startCleanup);\n }\n\n @VisibleForTesting\n LogBufferRecoveryService(List pipelines, List> checkpointManager, String baseLogDir, int batchSize, AtomicBoolean startCleanup) {\n this.pipelines = pipelines;\n this.checkpointManagers = checkpointManager;\n this.baseLogDir = baseLogDir;\n this.baseDirExists = dirExists(baseLogDir);\n this.batchSize = batchSize;\n this.stopLatch = new CountDownLatch(1);\n this.startCleanup = startCleanup;\n }\n\n @Override\n protected void startUp() throws Exception {\n if (baseDirExists) {\n // get the smallest offset of all the log pipelines\n LogBufferFileOffset minOffset = getSmallestOffset(checkpointManagers);\n this.reader = new LogBufferReader(baseLogDir, batchSize, getMaxFileId(baseLogDir), minOffset.getFileId(), minOffset.getFilePos());\n }\n ", "post_mask_code": "\n\n @Override\n protected void run() throws Exception {\n if (baseDirExists) {\n List logBufferEvents = new LinkedList<>();\n boolean hasReadEvents = true;\n while (!stopped && hasReadEvents) {\n try {\n hasReadEvents = reader.readEvents(logBufferEvents) > 0;\n recoverLogs(logBufferEvents, pipelines);\n } catch (Exception e) {\n // even though error occurred while reading, whatever logs were read, those should be processed. This is\n // because recovery service should be finished quickly so that the logs are persisted in almost sorted order.\n recoverLogs(logBufferEvents, pipelines);\n OUTAGE_LOG.warn(\"Failed to recover logs from log buffer. Read will be retried.\", e);\n // in case of failure to read, sleep and then retry\n stopLatch.await(500, TimeUnit.MILLISECONDS);\n }\n }\n }\n startCleanup.set(true);\n }\n\n @Override\n protected void shutDown() throws Exception {\n if (reader != null) {\n reader.close();\n }\n }\n\n @Override\n protected void triggerShutdown() {\n stopped = true;\n stopLatch.countDown();\n }\n\n @Override\n protected String getServiceName() {\n return SERVICE_NAME;\n }\n\n private LogBufferFileOffset getSmallestOffset(List> checkpointManagers) throws IOException {\n // there will be atleast one log pipeline\n LogBufferFileOffset minOffset = checkpointManagers.get(0).getCheckpoint(0).getOffset();\n for (int i = 1; i < checkpointManagers.size(); i++) {\n LogBufferFileOffset offset = checkpointManagers.get(i).getCheckpoint(0).getOffset();\n // keep track of minimum offset\n minOffset = minOffset.compareTo(offset) > 0 ? offset : minOffset;\n }\n return minOffset;\n }\n\n private void recoverLogs(List logBufferEvents, List pipelines) {\n for (LogBufferProcessorPipeline pipeline : pipelines) {\n pipeline.processLogEvents(logBufferEvents.iterator());\n }\n logBufferEvents.clear();\n }\n\n private long getMaxFileId(String baseDir) {\n long maxFileId = -1;\n File[] files = new File(baseDir).listFiles();\n if (files != null) {\n for (File file : files) {\n String[] splitted = file.getName().split(\"\\\\.\");\n long fileId = Long.parseLong(splitted[0]);\n if (maxFileId < fileId) {\n maxFileId = fileId;\n }\n }\n }\n return maxFileId;\n }\n\n private boolean dirExists(String baseLogDir) {\n File baseDir = new File(baseLogDir);\n return baseDir.exists();\n }\n}\n"} {"task_id": "Java_1631", "language": "Java", "task_type": "single_line", "source_file": "java/github/cdapio/cdap/cdap-watchdog/src/main/java/io/cdap/cdap/logging/logbuffer/recover/LogBufferRecoveryService.java", "mask_start_position": 5763, "mask_end_position": 5767, "canonical_solution": "r();", "pre_mask_code": "package io.cdap.cdap.logging.logbuffer.recover;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.util.concurrent.AbstractExecutionThreadService;\nimport io.cdap.cdap.common.conf.CConfiguration;\nimport io.cdap.cdap.common.conf.Constants;\nimport io.cdap.cdap.common.logging.LogSamplers;\nimport io.cdap.cdap.common.logging.Loggers;\nimport io.cdap.cdap.logging.logbuffer.LogBufferEvent;\nimport io.cdap.cdap.logging.logbuffer.LogBufferFileOffset;\nimport io.cdap.cdap.logging.meta.CheckpointManager;\nimport io.cdap.cdap.logging.pipeline.logbuffer.LogBufferProcessorPipeline;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\n/**\n * Log buffer recovery service which recovers logs upon log saver restart and sends them to log buffer pipeline for\n * further processing. This service first scans all the files to figure out max file id till which it should recover.\n * This is because while recovery service is running, new files can be created. Recovery service should not recover\n * those logs.\n */\npublic class LogBufferRecoveryService extends AbstractExecutionThreadService {\n\n private static final Logger LOG = LoggerFactory.getLogger(LogBufferRecoveryService.class);\n\n // For outage, only log once per 60 seconds per message.\n private static final Logger OUTAGE_LOG = Loggers.sampling(LOG, LogSamplers.perMessage(() -> LogSamplers.limitRate(60000)));\n\n private static final String SERVICE_NAME = \"log.buffer.recovery\";\n\n private final List pipelines;\n\n private final List> checkpointManagers;\n\n private final String baseLogDir;\n\n private final boolean baseDirExists;\n\n private final int batchSize;\n\n private final CountDownLatch stopLatch;\n\n private final AtomicBoolean startCleanup;\n\n private LogBufferReader reader;\n\n private volatile boolean stopped;\n\n public LogBufferRecoveryService(CConfiguration cConf, List pipelines, List> checkpointManagers, AtomicBoolean startCleanup) {\n this(pipelines, checkpointManagers, cConf.get(Constants.LogBuffer.LOG_BUFFER_BASE_DIR), cConf.getInt(Constants.LogBuffer.LOG_BUFFER_RECOVERY_BATCH_SIZE), startCleanup);\n }\n\n @VisibleForTesting\n LogBufferRecoveryService(List pipelines, List> checkpointManager, String baseLogDir, int batchSize, AtomicBoolean startCleanup) {\n this.pipelines = pipelines;\n this.checkpointManagers = checkpointManager;\n this.baseLogDir = baseLogDir;\n this.baseDirExists = dirExists(baseLogDir);\n this.batchSize = batchSize;\n this.stopLatch = new CountDownLatch(1);\n this.startCleanup = startCleanup;\n }\n\n @Override\n protected void startUp() throws Exception {\n if (baseDirExists) {\n // get the smallest offset of all the log pipelines\n LogBufferFileOffset minOffset = getSmallestOffset(checkpointManagers);\n this.reader = new LogBufferReader(baseLogDir, batchSize, getMaxFileId(baseLogDir), minOffset.getFileId(), minOffset.getFilePos());\n }\n }\n\n @Override\n protected void run() throws Exception {\n if (baseDirExists) {\n List logBufferEvents = new LinkedList<>();\n boolean hasReadEvents = true;\n while (!stopped && hasReadEvents) {\n try {\n hasReadEvents = reader.readEvents(logBufferEvents) > 0;\n recoverLogs(logBufferEvents, pipelines);\n } catch (Exception e) {\n // even though error occurred while reading, whatever logs were read, those should be processed. This is\n // because recovery service should be finished quickly so that the logs are persisted in almost sorted order.\n recoverLogs(logBufferEvents, pipelines);\n OUTAGE_LOG.warn(\"Failed to recover logs from log buffer. Read will be retried.\", e);\n // in case of failure to read, sleep and then retry\n stopLatch.await(500, TimeUnit.MILLISECONDS);\n }\n }\n }\n startCleanup.set(true);\n }\n\n @Override\n protected void shutDown() throws Exception {\n if (reader != null) {\n reader.close();\n }\n }\n\n @Override\n protected void triggerShutdown() {\n stopped = true;\n stopLatch.countDown();\n }\n\n @Override\n protected String getServiceName() {\n return SERVICE_NAME;\n }\n\n private LogBufferFileOffset getSmallestOffset(List> checkpointManagers) throws IOException {\n // there will be atleast one log pipeline\n LogBufferFileOffset minOffset = checkpointManagers.get(0).getCheckpoint(0).getOffset();\n for (int i = 1; i < checkpointManagers.size(); i++) {\n LogBufferFileOffset offset = checkpointManagers.get(i).getCheckpoint(0).getOffset();\n // keep track of minimum offset\n minOffset = minOffset.compareTo(offset) > 0 ? offset : minOffset;\n }\n return minOffset;\n }\n\n private void recoverLogs(List logBufferEvents, List pipelines) {\n for (LogBufferProcessorPipeline pipeline : pipelines) {\n pipeline.processLogEvents(logBufferEvents.iterator());\n }\n logBufferEvents.clea", "post_mask_code": "\n }\n\n private long getMaxFileId(String baseDir) {\n long maxFileId = -1;\n File[] files = new File(baseDir).listFiles();\n if (files != null) {\n for (File file : files) {\n String[] splitted = file.getName().split(\"\\\\.\");\n long fileId = Long.parseLong(splitted[0]);\n if (maxFileId < fileId) {\n maxFileId = fileId;\n }\n }\n }\n return maxFileId;\n }\n\n private boolean dirExists(String baseLogDir) {\n File baseDir = new File(baseLogDir);\n return baseDir.exists();\n }\n}\n"} {"task_id": "Java_1632", "language": "Java", "task_type": "if_statement", "source_file": "java/github/cdapio/cdap/cdap-watchdog/src/main/java/io/cdap/cdap/logging/logbuffer/recover/LogBufferRecoveryService.java", "mask_start_position": 4603, "mask_end_position": 4662, "canonical_solution": "if (reader != null) {\n reader.close();\n }", "pre_mask_code": "package io.cdap.cdap.logging.logbuffer.recover;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.util.concurrent.AbstractExecutionThreadService;\nimport io.cdap.cdap.common.conf.CConfiguration;\nimport io.cdap.cdap.common.conf.Constants;\nimport io.cdap.cdap.common.logging.LogSamplers;\nimport io.cdap.cdap.common.logging.Loggers;\nimport io.cdap.cdap.logging.logbuffer.LogBufferEvent;\nimport io.cdap.cdap.logging.logbuffer.LogBufferFileOffset;\nimport io.cdap.cdap.logging.meta.CheckpointManager;\nimport io.cdap.cdap.logging.pipeline.logbuffer.LogBufferProcessorPipeline;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\n/**\n * Log buffer recovery service which recovers logs upon log saver restart and sends them to log buffer pipeline for\n * further processing. This service first scans all the files to figure out max file id till which it should recover.\n * This is because while recovery service is running, new files can be created. Recovery service should not recover\n * those logs.\n */\npublic class LogBufferRecoveryService extends AbstractExecutionThreadService {\n\n private static final Logger LOG = LoggerFactory.getLogger(LogBufferRecoveryService.class);\n\n // For outage, only log once per 60 seconds per message.\n private static final Logger OUTAGE_LOG = Loggers.sampling(LOG, LogSamplers.perMessage(() -> LogSamplers.limitRate(60000)));\n\n private static final String SERVICE_NAME = \"log.buffer.recovery\";\n\n private final List pipelines;\n\n private final List> checkpointManagers;\n\n private final String baseLogDir;\n\n private final boolean baseDirExists;\n\n private final int batchSize;\n\n private final CountDownLatch stopLatch;\n\n private final AtomicBoolean startCleanup;\n\n private LogBufferReader reader;\n\n private volatile boolean stopped;\n\n public LogBufferRecoveryService(CConfiguration cConf, List pipelines, List> checkpointManagers, AtomicBoolean startCleanup) {\n this(pipelines, checkpointManagers, cConf.get(Constants.LogBuffer.LOG_BUFFER_BASE_DIR), cConf.getInt(Constants.LogBuffer.LOG_BUFFER_RECOVERY_BATCH_SIZE), startCleanup);\n }\n\n @VisibleForTesting\n LogBufferRecoveryService(List pipelines, List> checkpointManager, String baseLogDir, int batchSize, AtomicBoolean startCleanup) {\n this.pipelines = pipelines;\n this.checkpointManagers = checkpointManager;\n this.baseLogDir = baseLogDir;\n this.baseDirExists = dirExists(baseLogDir);\n this.batchSize = batchSize;\n this.stopLatch = new CountDownLatch(1);\n this.startCleanup = startCleanup;\n }\n\n @Override\n protected void startUp() throws Exception {\n if (baseDirExists) {\n // get the smallest offset of all the log pipelines\n LogBufferFileOffset minOffset = getSmallestOffset(checkpointManagers);\n this.reader = new LogBufferReader(baseLogDir, batchSize, getMaxFileId(baseLogDir), minOffset.getFileId(), minOffset.getFilePos());\n }\n }\n\n @Override\n protected void run() throws Exception {\n if (baseDirExists) {\n List logBufferEvents = new LinkedList<>();\n boolean hasReadEvents = true;\n while (!stopped && hasReadEvents) {\n try {\n hasReadEvents = reader.readEvents(logBufferEvents) > 0;\n recoverLogs(logBufferEvents, pipelines);\n } catch (Exception e) {\n // even though error occurred while reading, whatever logs were read, those should be processed. This is\n // because recovery service should be finished quickly so that the logs are persisted in almost sorted order.\n recoverLogs(logBufferEvents, pipelines);\n OUTAGE_LOG.warn(\"Failed to recover logs from log buffer. Read will be retried.\", e);\n // in case of failure to read, sleep and then retry\n stopLatch.await(500, TimeUnit.MILLISECONDS);\n }\n }\n }\n startCleanup.set(true);\n }\n\n @Override\n protected void shutDown() throws Exception {\n ", "post_mask_code": "\n }\n\n @Override\n protected void triggerShutdown() {\n stopped = true;\n stopLatch.countDown();\n }\n\n @Override\n protected String getServiceName() {\n return SERVICE_NAME;\n }\n\n private LogBufferFileOffset getSmallestOffset(List> checkpointManagers) throws IOException {\n // there will be atleast one log pipeline\n LogBufferFileOffset minOffset = checkpointManagers.get(0).getCheckpoint(0).getOffset();\n for (int i = 1; i < checkpointManagers.size(); i++) {\n LogBufferFileOffset offset = checkpointManagers.get(i).getCheckpoint(0).getOffset();\n // keep track of minimum offset\n minOffset = minOffset.compareTo(offset) > 0 ? offset : minOffset;\n }\n return minOffset;\n }\n\n private void recoverLogs(List logBufferEvents, List pipelines) {\n for (LogBufferProcessorPipeline pipeline : pipelines) {\n pipeline.processLogEvents(logBufferEvents.iterator());\n }\n logBufferEvents.clear();\n }\n\n private long getMaxFileId(String baseDir) {\n long maxFileId = -1;\n File[] files = new File(baseDir).listFiles();\n if (files != null) {\n for (File file : files) {\n String[] splitted = file.getName().split(\"\\\\.\");\n long fileId = Long.parseLong(splitted[0]);\n if (maxFileId < fileId) {\n maxFileId = fileId;\n }\n }\n }\n return maxFileId;\n }\n\n private boolean dirExists(String baseLogDir) {\n File baseDir = new File(baseLogDir);\n return baseDir.exists();\n }\n}\n"} {"task_id": "Java_1633", "language": "Java", "task_type": "for_statement", "source_file": "java/github/cdapio/cdap/cdap-watchdog/src/main/java/io/cdap/cdap/logging/logbuffer/recover/LogBufferRecoveryService.java", "mask_start_position": 5165, "mask_end_position": 5447, "canonical_solution": "for (int i = 1; i < checkpointManagers.size(); i++) {\n LogBufferFileOffset offset = checkpointManagers.get(i).getCheckpoint(0).getOffset();\n // keep track of minimum offset\n minOffset = minOffset.compareTo(offset) > 0 ? offset : minOffset;\n }", "pre_mask_code": "package io.cdap.cdap.logging.logbuffer.recover;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.util.concurrent.AbstractExecutionThreadService;\nimport io.cdap.cdap.common.conf.CConfiguration;\nimport io.cdap.cdap.common.conf.Constants;\nimport io.cdap.cdap.common.logging.LogSamplers;\nimport io.cdap.cdap.common.logging.Loggers;\nimport io.cdap.cdap.logging.logbuffer.LogBufferEvent;\nimport io.cdap.cdap.logging.logbuffer.LogBufferFileOffset;\nimport io.cdap.cdap.logging.meta.CheckpointManager;\nimport io.cdap.cdap.logging.pipeline.logbuffer.LogBufferProcessorPipeline;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\n/**\n * Log buffer recovery service which recovers logs upon log saver restart and sends them to log buffer pipeline for\n * further processing. This service first scans all the files to figure out max file id till which it should recover.\n * This is because while recovery service is running, new files can be created. Recovery service should not recover\n * those logs.\n */\npublic class LogBufferRecoveryService extends AbstractExecutionThreadService {\n\n private static final Logger LOG = LoggerFactory.getLogger(LogBufferRecoveryService.class);\n\n // For outage, only log once per 60 seconds per message.\n private static final Logger OUTAGE_LOG = Loggers.sampling(LOG, LogSamplers.perMessage(() -> LogSamplers.limitRate(60000)));\n\n private static final String SERVICE_NAME = \"log.buffer.recovery\";\n\n private final List pipelines;\n\n private final List> checkpointManagers;\n\n private final String baseLogDir;\n\n private final boolean baseDirExists;\n\n private final int batchSize;\n\n private final CountDownLatch stopLatch;\n\n private final AtomicBoolean startCleanup;\n\n private LogBufferReader reader;\n\n private volatile boolean stopped;\n\n public LogBufferRecoveryService(CConfiguration cConf, List pipelines, List> checkpointManagers, AtomicBoolean startCleanup) {\n this(pipelines, checkpointManagers, cConf.get(Constants.LogBuffer.LOG_BUFFER_BASE_DIR), cConf.getInt(Constants.LogBuffer.LOG_BUFFER_RECOVERY_BATCH_SIZE), startCleanup);\n }\n\n @VisibleForTesting\n LogBufferRecoveryService(List pipelines, List> checkpointManager, String baseLogDir, int batchSize, AtomicBoolean startCleanup) {\n this.pipelines = pipelines;\n this.checkpointManagers = checkpointManager;\n this.baseLogDir = baseLogDir;\n this.baseDirExists = dirExists(baseLogDir);\n this.batchSize = batchSize;\n this.stopLatch = new CountDownLatch(1);\n this.startCleanup = startCleanup;\n }\n\n @Override\n protected void startUp() throws Exception {\n if (baseDirExists) {\n // get the smallest offset of all the log pipelines\n LogBufferFileOffset minOffset = getSmallestOffset(checkpointManagers);\n this.reader = new LogBufferReader(baseLogDir, batchSize, getMaxFileId(baseLogDir), minOffset.getFileId(), minOffset.getFilePos());\n }\n }\n\n @Override\n protected void run() throws Exception {\n if (baseDirExists) {\n List logBufferEvents = new LinkedList<>();\n boolean hasReadEvents = true;\n while (!stopped && hasReadEvents) {\n try {\n hasReadEvents = reader.readEvents(logBufferEvents) > 0;\n recoverLogs(logBufferEvents, pipelines);\n } catch (Exception e) {\n // even though error occurred while reading, whatever logs were read, those should be processed. This is\n // because recovery service should be finished quickly so that the logs are persisted in almost sorted order.\n recoverLogs(logBufferEvents, pipelines);\n OUTAGE_LOG.warn(\"Failed to recover logs from log buffer. Read will be retried.\", e);\n // in case of failure to read, sleep and then retry\n stopLatch.await(500, TimeUnit.MILLISECONDS);\n }\n }\n }\n startCleanup.set(true);\n }\n\n @Override\n protected void shutDown() throws Exception {\n if (reader != null) {\n reader.close();\n }\n }\n\n @Override\n protected void triggerShutdown() {\n stopped = true;\n stopLatch.countDown();\n }\n\n @Override\n protected String getServiceName() {\n return SERVICE_NAME;\n }\n\n private LogBufferFileOffset getSmallestOffset(List> checkpointManagers) throws IOException {\n // there will be atleast one log pipeline\n LogBufferFileOffset minOffset = checkpointManagers.get(0).getCheckpoint(0).getOffset();\n ", "post_mask_code": "\n return minOffset;\n }\n\n private void recoverLogs(List logBufferEvents, List pipelines) {\n for (LogBufferProcessorPipeline pipeline : pipelines) {\n pipeline.processLogEvents(logBufferEvents.iterator());\n }\n logBufferEvents.clear();\n }\n\n private long getMaxFileId(String baseDir) {\n long maxFileId = -1;\n File[] files = new File(baseDir).listFiles();\n if (files != null) {\n for (File file : files) {\n String[] splitted = file.getName().split(\"\\\\.\");\n long fileId = Long.parseLong(splitted[0]);\n if (maxFileId < fileId) {\n maxFileId = fileId;\n }\n }\n }\n return maxFileId;\n }\n\n private boolean dirExists(String baseLogDir) {\n File baseDir = new File(baseLogDir);\n return baseDir.exists();\n }\n}\n"} {"task_id": "Java_1634", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/datastax/java-driver/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousAsyncResultSet.java", "mask_start_position": 880, "mask_end_position": 897, "canonical_solution": "int pageNumber();", "pre_mask_code": "package com.datastax.dse.driver.api.core.cql.continuous;\n\nimport com.datastax.oss.driver.api.core.AsyncPagingIterable;\nimport com.datastax.oss.driver.api.core.cql.ExecutionInfo;\nimport com.datastax.oss.driver.api.core.cql.Row;\nimport com.datastax.oss.driver.api.core.cql.Statement;\nimport edu.umd.cs.findbugs.annotations.NonNull;\nimport java.nio.ByteBuffer;\nimport java.util.concurrent.CancellationException;\n\n/**\n * The result of an {@linkplain ContinuousSession#executeContinuouslyAsync(Statement) asynchronous\n * continuous paging query}.\n *\n *

DSE replies to a continuous query with a stream of response frames. There is one instance of\n * this class for each frame.\n */\npublic interface ContinuousAsyncResultSet extends AsyncPagingIterable {\n\n /**\n * Returns the current page's number. Pages are numbered starting from 1.\n */\n ", "post_mask_code": "\n\n /**\n * Cancels the continuous query.\n *\n *

There might still be rows available in the {@linkplain #currentPage() current page} after\n * the cancellation; these rows can be retrieved normally.\n *\n *

Also, there might be more pages available in the driver's local page cache after the\n * cancellation; these extra pages will be discarded.\n *\n *

Therefore, if you plan to resume the iteration later, the correct procedure is as follows:\n *\n *

    \n *
  1. Cancel the operation by invoking this method, or by cancelling the {@linkplain\n * #fetchNextPage() next page's future};\n *
  2. Keep iterating on the current page until it doesn't return any more rows;\n *
  3. Retrieve the paging state with {@link #getExecutionInfo()\n * getExecutionInfo().getPagingState()};\n *
  4. {@linkplain Statement#setPagingState(ByteBuffer) Re-inject the paging state} in the\n * statement;\n *
  5. Resume the operation by invoking {@link\n * ContinuousSession#executeContinuouslyAsync(Statement) executeContinuouslyAsync} again.\n *
\n *\n * After a cancellation, futures returned by {@link #fetchNextPage()} that are not yet complete\n * will always complete exceptionally by throwing a {@link CancellationException}, even if\n * they were obtained before the cancellation.\n */\n void cancel();\n\n /**\n * {@inheritDoc}\n *\n *

Note: because the driver does not support query traces for continuous queries, {@link\n * ExecutionInfo#getTracingId()} will always be {@code null}.\n */\n @NonNull\n @Override\n ExecutionInfo getExecutionInfo();\n}\n"} {"task_id": "Java_1635", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Alfresco/alfresco-community-repo/remote-api/src/main/java/org/alfresco/rest/api/people/PersonSitesRelation.java", "mask_start_position": 1274, "mask_end_position": 1308, "canonical_solution": "public void setSites(Sites sites) ", "pre_mask_code": "/*\n * #%L\n * Alfresco Remote API\n * %%\n * %%\n * This file is part of the Alfresco software. \n * If the software was purchased under a paid Alfresco license, the terms of \n * \n * #L%\n */\npackage org.alfresco.rest.api.people;\n\nimport org.alfresco.rest.api.Sites;\nimport org.alfresco.rest.api.model.MemberOfSite;\nimport org.alfresco.rest.framework.WebApiDescription;\nimport org.alfresco.rest.framework.resource.RelationshipResource;\nimport org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction;\nimport org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo;\nimport org.alfresco.rest.framework.resource.parameters.Parameters;\nimport org.alfresco.util.ParameterCheck;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.springframework.beans.factory.InitializingBean;\n\n@RelationshipResource(name = \"sites\", entityResource = PeopleEntityResource.class, title = \"Person Sites\")\npublic class PersonSitesRelation implements RelationshipResourceAction.Read, RelationshipResourceAction.ReadById, RelationshipResourceAction.Delete, InitializingBean {\n\n private static final Log logger = LogFactory.getLog(PersonSitesRelation.class);\n\n private Sites sites;\n\n ", "post_mask_code": "{\n this.sites = sites;\n }\n\n @Override\n public void afterPropertiesSet() {\n ParameterCheck.mandatory(\"sites\", this.sites);\n }\n\n /**\n * List all the sites that the specified user has a explicit membership of.\n *\n * THOR-1151: “F312: For a user, get the list of sites they are a member of”\n *\n * If personId does not exist, NotFoundException (status 404).\n *\n * @param personId the id (email) of the person\n *\n * (non-Javadoc)\n * @see org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction.Read#readAll(String, org.alfresco.rest.framework.resource.parameters.Parameters)\n */\n @Override\n @WebApiDescription(title = \"A paged list of the person's site memberships.\")\n public CollectionWithPagingInfo readAll(String personId, Parameters parameters) {\n return sites.getSites(personId, parameters);\n }\n\n /**\n * Returns site membership information for personId in siteId.\n *\n * @see org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction.ReadById#readById(String, String, org.alfresco.rest.framework.resource.parameters.Parameters)\n */\n @Override\n @WebApiDescription(title = \"Site membership information for 'personId' in 'siteId'.\")\n public MemberOfSite readById(String personId, String siteId, Parameters parameters) {\n return sites.getMemberOfSite(personId, siteId);\n }\n\n @Override\n public void delete(String personId, String siteId, Parameters parameters) {\n sites.removeSiteMember(personId, siteId);\n }\n}\n"} {"task_id": "Java_1636", "language": "Java", "task_type": "method_body", "source_file": "java/github/Alfresco/alfresco-community-repo/remote-api/src/main/java/org/alfresco/rest/api/people/PersonSitesRelation.java", "mask_start_position": 2707, "mask_end_position": 2770, "canonical_solution": "{\n return sites.getMemberOfSite(personId, siteId);\n }", "pre_mask_code": "/*\n * #%L\n * Alfresco Remote API\n * %%\n * %%\n * This file is part of the Alfresco software. \n * If the software was purchased under a paid Alfresco license, the terms of \n * \n * #L%\n */\npackage org.alfresco.rest.api.people;\n\nimport org.alfresco.rest.api.Sites;\nimport org.alfresco.rest.api.model.MemberOfSite;\nimport org.alfresco.rest.framework.WebApiDescription;\nimport org.alfresco.rest.framework.resource.RelationshipResource;\nimport org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction;\nimport org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo;\nimport org.alfresco.rest.framework.resource.parameters.Parameters;\nimport org.alfresco.util.ParameterCheck;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.springframework.beans.factory.InitializingBean;\n\n@RelationshipResource(name = \"sites\", entityResource = PeopleEntityResource.class, title = \"Person Sites\")\npublic class PersonSitesRelation implements RelationshipResourceAction.Read, RelationshipResourceAction.ReadById, RelationshipResourceAction.Delete, InitializingBean {\n\n private static final Log logger = LogFactory.getLog(PersonSitesRelation.class);\n\n private Sites sites;\n\n public void setSites(Sites sites) {\n this.sites = sites;\n }\n\n @Override\n public void afterPropertiesSet() {\n ParameterCheck.mandatory(\"sites\", this.sites);\n }\n\n /**\n * List all the sites that the specified user has a explicit membership of.\n *\n * THOR-1151: “F312: For a user, get the list of sites they are a member of”\n *\n * If personId does not exist, NotFoundException (status 404).\n *\n * @param personId the id (email) of the person\n *\n * (non-Javadoc)\n * @see org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction.Read#readAll(String, org.alfresco.rest.framework.resource.parameters.Parameters)\n */\n @Override\n @WebApiDescription(title = \"A paged list of the person's site memberships.\")\n public CollectionWithPagingInfo readAll(String personId, Parameters parameters) {\n return sites.getSites(personId, parameters);\n }\n\n /**\n * Returns site membership information for personId in siteId.\n *\n * @see org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction.ReadById#readById(String, String, org.alfresco.rest.framework.resource.parameters.Parameters)\n */\n @Override\n @WebApiDescription(title = \"Site membership information for 'personId' in 'siteId'.\")\n public MemberOfSite readById(String personId, String siteId, Parameters parameters) ", "post_mask_code": "\n\n @Override\n public void delete(String personId, String siteId, Parameters parameters) {\n sites.removeSiteMember(personId, siteId);\n }\n}\n"} {"task_id": "Java_1637", "language": "Java", "task_type": "single_line", "source_file": "java/github/Alfresco/alfresco-community-repo/remote-api/src/main/java/org/alfresco/rest/api/people/PersonSitesRelation.java", "mask_start_position": 1325, "mask_end_position": 1337, "canonical_solution": "tes = sites;", "pre_mask_code": "/*\n * #%L\n * Alfresco Remote API\n * %%\n * %%\n * This file is part of the Alfresco software. \n * If the software was purchased under a paid Alfresco license, the terms of \n * \n * #L%\n */\npackage org.alfresco.rest.api.people;\n\nimport org.alfresco.rest.api.Sites;\nimport org.alfresco.rest.api.model.MemberOfSite;\nimport org.alfresco.rest.framework.WebApiDescription;\nimport org.alfresco.rest.framework.resource.RelationshipResource;\nimport org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction;\nimport org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo;\nimport org.alfresco.rest.framework.resource.parameters.Parameters;\nimport org.alfresco.util.ParameterCheck;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.springframework.beans.factory.InitializingBean;\n\n@RelationshipResource(name = \"sites\", entityResource = PeopleEntityResource.class, title = \"Person Sites\")\npublic class PersonSitesRelation implements RelationshipResourceAction.Read, RelationshipResourceAction.ReadById, RelationshipResourceAction.Delete, InitializingBean {\n\n private static final Log logger = LogFactory.getLog(PersonSitesRelation.class);\n\n private Sites sites;\n\n public void setSites(Sites sites) {\n this.si", "post_mask_code": "\n }\n\n @Override\n public void afterPropertiesSet() {\n ParameterCheck.mandatory(\"sites\", this.sites);\n }\n\n /**\n * List all the sites that the specified user has a explicit membership of.\n *\n * THOR-1151: “F312: For a user, get the list of sites they are a member of”\n *\n * If personId does not exist, NotFoundException (status 404).\n *\n * @param personId the id (email) of the person\n *\n * (non-Javadoc)\n * @see org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction.Read#readAll(String, org.alfresco.rest.framework.resource.parameters.Parameters)\n */\n @Override\n @WebApiDescription(title = \"A paged list of the person's site memberships.\")\n public CollectionWithPagingInfo readAll(String personId, Parameters parameters) {\n return sites.getSites(personId, parameters);\n }\n\n /**\n * Returns site membership information for personId in siteId.\n *\n * @see org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction.ReadById#readById(String, String, org.alfresco.rest.framework.resource.parameters.Parameters)\n */\n @Override\n @WebApiDescription(title = \"Site membership information for 'personId' in 'siteId'.\")\n public MemberOfSite readById(String personId, String siteId, Parameters parameters) {\n return sites.getMemberOfSite(personId, siteId);\n }\n\n @Override\n public void delete(String personId, String siteId, Parameters parameters) {\n sites.removeSiteMember(personId, siteId);\n }\n}\n"} {"task_id": "Java_1638", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Alfresco/alfresco-community-repo/remote-api/src/main/java/org/alfresco/rest/api/people/PersonSitesRelation.java", "mask_start_position": 2519, "mask_end_position": 2770, "canonical_solution": "@Override\n @WebApiDescription(title = \"Site membership information for 'personId' in 'siteId'.\")\n public MemberOfSite readById(String personId, String siteId, Parameters parameters) {\n return sites.getMemberOfSite(personId, siteId);\n }", "pre_mask_code": "/*\n * #%L\n * Alfresco Remote API\n * %%\n * %%\n * This file is part of the Alfresco software. \n * If the software was purchased under a paid Alfresco license, the terms of \n * \n * #L%\n */\npackage org.alfresco.rest.api.people;\n\nimport org.alfresco.rest.api.Sites;\nimport org.alfresco.rest.api.model.MemberOfSite;\nimport org.alfresco.rest.framework.WebApiDescription;\nimport org.alfresco.rest.framework.resource.RelationshipResource;\nimport org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction;\nimport org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo;\nimport org.alfresco.rest.framework.resource.parameters.Parameters;\nimport org.alfresco.util.ParameterCheck;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.springframework.beans.factory.InitializingBean;\n\n@RelationshipResource(name = \"sites\", entityResource = PeopleEntityResource.class, title = \"Person Sites\")\npublic class PersonSitesRelation implements RelationshipResourceAction.Read, RelationshipResourceAction.ReadById, RelationshipResourceAction.Delete, InitializingBean {\n\n private static final Log logger = LogFactory.getLog(PersonSitesRelation.class);\n\n private Sites sites;\n\n public void setSites(Sites sites) {\n this.sites = sites;\n }\n\n @Override\n public void afterPropertiesSet() {\n ParameterCheck.mandatory(\"sites\", this.sites);\n }\n\n /**\n * List all the sites that the specified user has a explicit membership of.\n *\n * THOR-1151: “F312: For a user, get the list of sites they are a member of”\n *\n * If personId does not exist, NotFoundException (status 404).\n *\n * @param personId the id (email) of the person\n *\n * (non-Javadoc)\n * @see org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction.Read#readAll(String, org.alfresco.rest.framework.resource.parameters.Parameters)\n */\n @Override\n @WebApiDescription(title = \"A paged list of the person's site memberships.\")\n public CollectionWithPagingInfo readAll(String personId, Parameters parameters) {\n return sites.getSites(personId, parameters);\n }\n\n /**\n * Returns site membership information for personId in siteId.\n *\n * @see org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction.ReadById#readById(String, String, org.alfresco.rest.framework.resource.parameters.Parameters)\n */\n ", "post_mask_code": "\n\n @Override\n public void delete(String personId, String siteId, Parameters parameters) {\n sites.removeSiteMember(personId, siteId);\n }\n}\n"} {"task_id": "Java_1639", "language": "Java", "task_type": "method_signature", "source_file": "java/github/uhonliu/open-platform/platform/api-spring-server/src/main/java/com/opencloud/gateway/spring/server/filter/PreRequestFilter.java", "mask_start_position": 643, "mask_end_position": 732, "canonical_solution": "@Override\n public Mono filter(ServerWebExchange exchange, WebFilterChain chain) ", "pre_mask_code": "package com.opencloud.gateway.spring.server.filter;\n\nimport com.opencloud.common.interceptor.FeignRequestInterceptor;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.http.server.reactive.ServerHttpRequest;\nimport org.springframework.http.server.reactive.ServerHttpResponse;\nimport org.springframework.web.server.ServerWebExchange;\nimport org.springframework.web.server.WebFilter;\nimport org.springframework.web.server.WebFilterChain;\nimport reactor.core.publisher.Mono;\nimport java.util.Date;\nimport java.util.UUID;\n\n/**\n * 请求前缀过滤器,增加请求时间\n *\n * @author liuyadu\n */\n@Slf4j\npublic class PreRequestFilter implements WebFilter {\n\n ", "post_mask_code": "{\n // 添加自定义请求头\n String rid = UUID.randomUUID().toString();\n ServerHttpRequest request = exchange.getRequest().mutate().header(FeignRequestInterceptor.X_REQUEST_ID, rid).build();\n ServerHttpResponse response = exchange.getResponse();\n response.getHeaders().set(FeignRequestInterceptor.X_REQUEST_ID, rid);\n // 将现在的request 变成 change对象\n ServerWebExchange build = exchange.mutate().request(request).response(response).build();\n // 添加请求时间\n build.getAttributes().put(\"requestTime\", new Date());\n return chain.filter(build);\n }\n}\n"} {"task_id": "Java_1640", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/uhonliu/open-platform/platform/api-spring-server/src/main/java/com/opencloud/gateway/spring/server/filter/PreRequestFilter.java", "mask_start_position": 733, "mask_end_position": 930, "canonical_solution": "\n // 添加自定义请求头\n String rid = UUID.randomUUID().toString();\n ServerHttpRequest request = exchange.getRequest().mutate().header(FeignRequestInterceptor.X_REQUEST_ID, rid).build();", "pre_mask_code": "package com.opencloud.gateway.spring.server.filter;\n\nimport com.opencloud.common.interceptor.FeignRequestInterceptor;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.http.server.reactive.ServerHttpRequest;\nimport org.springframework.http.server.reactive.ServerHttpResponse;\nimport org.springframework.web.server.ServerWebExchange;\nimport org.springframework.web.server.WebFilter;\nimport org.springframework.web.server.WebFilterChain;\nimport reactor.core.publisher.Mono;\nimport java.util.Date;\nimport java.util.UUID;\n\n/**\n * 请求前缀过滤器,增加请求时间\n *\n * @author liuyadu\n */\n@Slf4j\npublic class PreRequestFilter implements WebFilter {\n\n @Override\n public Mono filter(ServerWebExchange exchange, WebFilterChain chain) {", "post_mask_code": "\n ServerHttpResponse response = exchange.getResponse();\n response.getHeaders().set(FeignRequestInterceptor.X_REQUEST_ID, rid);\n // 将现在的request 变成 change对象\n ServerWebExchange build = exchange.mutate().request(request).response(response).build();\n // 添加请求时间\n build.getAttributes().put(\"requestTime\", new Date());\n return chain.filter(build);\n }\n}\n"} {"task_id": "Java_1641", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/uhonliu/open-platform/platform/api-spring-server/src/main/java/com/opencloud/gateway/spring/server/filter/PreRequestFilter.java", "mask_start_position": 939, "mask_end_position": 1202, "canonical_solution": "ServerHttpResponse response = exchange.getResponse();\n response.getHeaders().set(FeignRequestInterceptor.X_REQUEST_ID, rid);\n // 将现在的request 变成 change对象\n ServerWebExchange build = exchange.mutate().request(request).response(response).build();", "pre_mask_code": "package com.opencloud.gateway.spring.server.filter;\n\nimport com.opencloud.common.interceptor.FeignRequestInterceptor;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.http.server.reactive.ServerHttpRequest;\nimport org.springframework.http.server.reactive.ServerHttpResponse;\nimport org.springframework.web.server.ServerWebExchange;\nimport org.springframework.web.server.WebFilter;\nimport org.springframework.web.server.WebFilterChain;\nimport reactor.core.publisher.Mono;\nimport java.util.Date;\nimport java.util.UUID;\n\n/**\n * 请求前缀过滤器,增加请求时间\n *\n * @author liuyadu\n */\n@Slf4j\npublic class PreRequestFilter implements WebFilter {\n\n @Override\n public Mono filter(ServerWebExchange exchange, WebFilterChain chain) {\n // 添加自定义请求头\n String rid = UUID.randomUUID().toString();\n ServerHttpRequest request = exchange.getRequest().mutate().header(FeignRequestInterceptor.X_REQUEST_ID, rid).build();\n ", "post_mask_code": "\n // 添加请求时间\n build.getAttributes().put(\"requestTime\", new Date());\n return chain.filter(build);\n }\n}\n"} {"task_id": "Java_1642", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/uhonliu/open-platform/platform/api-spring-server/src/main/java/com/opencloud/gateway/spring/server/filter/PreRequestFilter.java", "mask_start_position": 1211, "mask_end_position": 1324, "canonical_solution": "// 添加请求时间\n build.getAttributes().put(\"requestTime\", new Date());\n return chain.filter(build);\n }", "pre_mask_code": "package com.opencloud.gateway.spring.server.filter;\n\nimport com.opencloud.common.interceptor.FeignRequestInterceptor;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.http.server.reactive.ServerHttpRequest;\nimport org.springframework.http.server.reactive.ServerHttpResponse;\nimport org.springframework.web.server.ServerWebExchange;\nimport org.springframework.web.server.WebFilter;\nimport org.springframework.web.server.WebFilterChain;\nimport reactor.core.publisher.Mono;\nimport java.util.Date;\nimport java.util.UUID;\n\n/**\n * 请求前缀过滤器,增加请求时间\n *\n * @author liuyadu\n */\n@Slf4j\npublic class PreRequestFilter implements WebFilter {\n\n @Override\n public Mono filter(ServerWebExchange exchange, WebFilterChain chain) {\n // 添加自定义请求头\n String rid = UUID.randomUUID().toString();\n ServerHttpRequest request = exchange.getRequest().mutate().header(FeignRequestInterceptor.X_REQUEST_ID, rid).build();\n ServerHttpResponse response = exchange.getResponse();\n response.getHeaders().set(FeignRequestInterceptor.X_REQUEST_ID, rid);\n // 将现在的request 变成 change对象\n ServerWebExchange build = exchange.mutate().request(request).response(response).build();\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1643", "language": "Java", "task_type": "single_line", "source_file": "java/github/uhonliu/open-platform/platform/api-spring-server/src/main/java/com/opencloud/gateway/spring/server/filter/PreRequestFilter.java", "mask_start_position": 870, "mask_end_position": 930, "canonical_solution": ").header(FeignRequestInterceptor.X_REQUEST_ID, rid).build();", "pre_mask_code": "package com.opencloud.gateway.spring.server.filter;\n\nimport com.opencloud.common.interceptor.FeignRequestInterceptor;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.http.server.reactive.ServerHttpRequest;\nimport org.springframework.http.server.reactive.ServerHttpResponse;\nimport org.springframework.web.server.ServerWebExchange;\nimport org.springframework.web.server.WebFilter;\nimport org.springframework.web.server.WebFilterChain;\nimport reactor.core.publisher.Mono;\nimport java.util.Date;\nimport java.util.UUID;\n\n/**\n * 请求前缀过滤器,增加请求时间\n *\n * @author liuyadu\n */\n@Slf4j\npublic class PreRequestFilter implements WebFilter {\n\n @Override\n public Mono filter(ServerWebExchange exchange, WebFilterChain chain) {\n // 添加自定义请求头\n String rid = UUID.randomUUID().toString();\n ServerHttpRequest request = exchange.getRequest().mutate(", "post_mask_code": "\n ServerHttpResponse response = exchange.getResponse();\n response.getHeaders().set(FeignRequestInterceptor.X_REQUEST_ID, rid);\n // 将现在的request 变成 change对象\n ServerWebExchange build = exchange.mutate().request(request).response(response).build();\n // 添加请求时间\n build.getAttributes().put(\"requestTime\", new Date());\n return chain.filter(build);\n }\n}\n"} {"task_id": "Java_1644", "language": "Java", "task_type": "method_signature", "source_file": "java/github/sofastack/sofa-lookout/gateway/metrics/exporter/elasticsearch/src/main/java/com/alipay/sofa/lookout/gateway/metrics/exporter/es/ESProperties.java", "mask_start_position": 2066, "mask_end_position": 2100, "canonical_solution": "public void setAuto(boolean auto) ", "pre_mask_code": "package com.alipay.sofa.lookout.gateway.metrics.exporter.es;\n\nimport com.alipay.sofa.lookout.gateway.metrics.exporter.es.common.ESConsts;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n/**\n * @author xiangfeng.xzc\n * @date 2018/11/26\n */\n@ConfigurationProperties(prefix = ESProperties.PREFIX)\npublic class ESProperties {\n\n public static final String PREFIX = \"metrics.exporter.es\";\n\n private String host = ESConsts.DEFAULT_ES_HOST;\n\n private int port = 9200;\n\n private String username = \"lookout\";\n\n private String password = \"dkZpMNJF\";\n\n private int timeout = 5000;\n\n private String index = ESConsts.DEFAULT_ES_INDEX;\n\n private String type = ESConsts.DEFAULT_ES_TYPE;\n\n private Operation operation = new Operation();\n\n public Operation getOperation() {\n return operation;\n }\n\n public void setOperation(Operation operation) {\n this.operation = operation;\n }\n\n public String getHost() {\n return host;\n }\n\n public void setHost(String host) {\n this.host = host;\n }\n\n public int getPort() {\n return port;\n }\n\n public void setPort(int port) {\n this.port = port;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n public void setTimeout(int timeout) {\n this.timeout = timeout;\n }\n\n public String getIndex() {\n return index;\n }\n\n public void setIndex(String index) {\n this.index = index;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public static class Operation {\n\n private boolean auto = true;\n\n public boolean isAuto() {\n return auto;\n }\n\n ", "post_mask_code": "{\n this.auto = auto;\n }\n }\n}\n"} {"task_id": "Java_1645", "language": "Java", "task_type": "method_body", "source_file": "java/github/sofastack/sofa-lookout/gateway/metrics/exporter/elasticsearch/src/main/java/com/alipay/sofa/lookout/gateway/metrics/exporter/es/ESProperties.java", "mask_start_position": 971, "mask_end_position": 999, "canonical_solution": "{\n return host;\n }", "pre_mask_code": "package com.alipay.sofa.lookout.gateway.metrics.exporter.es;\n\nimport com.alipay.sofa.lookout.gateway.metrics.exporter.es.common.ESConsts;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n/**\n * @author xiangfeng.xzc\n * @date 2018/11/26\n */\n@ConfigurationProperties(prefix = ESProperties.PREFIX)\npublic class ESProperties {\n\n public static final String PREFIX = \"metrics.exporter.es\";\n\n private String host = ESConsts.DEFAULT_ES_HOST;\n\n private int port = 9200;\n\n private String username = \"lookout\";\n\n private String password = \"dkZpMNJF\";\n\n private int timeout = 5000;\n\n private String index = ESConsts.DEFAULT_ES_INDEX;\n\n private String type = ESConsts.DEFAULT_ES_TYPE;\n\n private Operation operation = new Operation();\n\n public Operation getOperation() {\n return operation;\n }\n\n public void setOperation(Operation operation) {\n this.operation = operation;\n }\n\n public String getHost() ", "post_mask_code": "\n\n public void setHost(String host) {\n this.host = host;\n }\n\n public int getPort() {\n return port;\n }\n\n public void setPort(int port) {\n this.port = port;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n public void setTimeout(int timeout) {\n this.timeout = timeout;\n }\n\n public String getIndex() {\n return index;\n }\n\n public void setIndex(String index) {\n this.index = index;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public static class Operation {\n\n private boolean auto = true;\n\n public boolean isAuto() {\n return auto;\n }\n\n public void setAuto(boolean auto) {\n this.auto = auto;\n }\n }\n}\n"} {"task_id": "Java_1646", "language": "Java", "task_type": "single_line", "source_file": "java/github/sofastack/sofa-lookout/gateway/metrics/exporter/elasticsearch/src/main/java/com/alipay/sofa/lookout/gateway/metrics/exporter/es/ESProperties.java", "mask_start_position": 1894, "mask_end_position": 1905, "canonical_solution": "ype = type;", "pre_mask_code": "package com.alipay.sofa.lookout.gateway.metrics.exporter.es;\n\nimport com.alipay.sofa.lookout.gateway.metrics.exporter.es.common.ESConsts;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n/**\n * @author xiangfeng.xzc\n * @date 2018/11/26\n */\n@ConfigurationProperties(prefix = ESProperties.PREFIX)\npublic class ESProperties {\n\n public static final String PREFIX = \"metrics.exporter.es\";\n\n private String host = ESConsts.DEFAULT_ES_HOST;\n\n private int port = 9200;\n\n private String username = \"lookout\";\n\n private String password = \"dkZpMNJF\";\n\n private int timeout = 5000;\n\n private String index = ESConsts.DEFAULT_ES_INDEX;\n\n private String type = ESConsts.DEFAULT_ES_TYPE;\n\n private Operation operation = new Operation();\n\n public Operation getOperation() {\n return operation;\n }\n\n public void setOperation(Operation operation) {\n this.operation = operation;\n }\n\n public String getHost() {\n return host;\n }\n\n public void setHost(String host) {\n this.host = host;\n }\n\n public int getPort() {\n return port;\n }\n\n public void setPort(int port) {\n this.port = port;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n public void setTimeout(int timeout) {\n this.timeout = timeout;\n }\n\n public String getIndex() {\n return index;\n }\n\n public void setIndex(String index) {\n this.index = index;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.t", "post_mask_code": "\n }\n\n public static class Operation {\n\n private boolean auto = true;\n\n public boolean isAuto() {\n return auto;\n }\n\n public void setAuto(boolean auto) {\n this.auto = auto;\n }\n }\n}\n"} {"task_id": "Java_1647", "language": "Java", "task_type": "method_signature", "source_file": "java/github/bejayoharen/java-bells/lib-src/libjitsi/src/org/jitsi/impl/neomedia/codec/video/h263p/Packetizer.java", "mask_start_position": 2699, "mask_end_position": 2746, "canonical_solution": "@Override\n public synchronized void close() ", "pre_mask_code": "/*\n * Jitsi, the OpenSource Java VoIP and Instant Messaging client.\n *\n * See terms of license at gnu.org.\n */\npackage org.jitsi.impl.neomedia.codec.video.h263p;\n\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\nimport javax.media.*;\nimport javax.media.format.*;\nimport net.sf.fmj.media.*;\nimport org.jitsi.impl.neomedia.codec.*;\nimport org.jitsi.service.neomedia.codec.*;\n\n/**\n * Packetizes H.263+ encoded data into RTP packets in accord with RFC 4529\n * \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n *\n * @author Sebastien Vincent\n * @author Lyubomir Marinov\n */\npublic class Packetizer extends AbstractPacketizer {\n\n private static final Format[] DEFAULT_OUTPUT_FORMATS = { new VideoFormat(Constants.H263P_RTP) };\n\n /**\n * Maximum payload size without the headers.\n */\n public static final int MAX_PAYLOAD_SIZE = 1024;\n\n /**\n * Name of the plugin.\n */\n private static final String PLUGIN_NAME = \"H263+ Packetizer\";\n\n /**\n * Finds the index in byteStream at which a Picture Start code\n * begins.\n *\n * @param byteStream the H.263+ encoded byte stream\n * @param beginIndex the inclusive index in byteStream at which the\n * search is to begin\n * @param endIndex the exclusive index in byteStream at which the\n * search is to end\n * @return the index in byteStream at which the Picture Start code\n * begins, otherwise, endIndex\n */\n private static int findStartcode(byte[] byteStream, int beginIndex, int endIndex) {\n for (; beginIndex < (endIndex - 3); beginIndex++) {\n if ((byteStream[beginIndex] == 0) && (byteStream[beginIndex + 1] == 0) && ((byteStream[beginIndex + 2] & (byte) 0x80) == -128)) {\n return beginIndex;\n }\n }\n return endIndex;\n }\n\n /**\n * The sequence number of the next RTP packet to be output by this\n * Packetizer.\n */\n private int sequenceNumber = 0;\n\n /**\n * The timeStamp of the RTP packets in which H263+ packets are to be sent.\n */\n private long timeStamp = 0;\n\n /**\n * The list of H263+ \"Start code\" video packets to be sent as payload in RTP\n * packets.\n */\n private final List videoPkts = new LinkedList();\n\n /**\n * Initializes a new Packetizer instance which is to packetize\n * H.263+ encoded data into RTP packets in accord with\n * RFC 4529 \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n */\n public Packetizer() {\n inputFormats = new Format[] { new VideoFormat(Constants.H263P) };\n inputFormat = null;\n outputFormat = null;\n }\n\n ", "post_mask_code": "{\n if (opened) {\n videoPkts.clear();\n opened = false;\n super.close();\n }\n }\n\n /**\n * Get the matching output formats for a specific format.\n *\n * @param inputFormat input format\n * @return array for formats matching input format\n */\n private Format[] getMatchingOutputFormats(Format inputFormat) {\n VideoFormat inputVideoFormat = (VideoFormat) inputFormat;\n return new Format[] { new VideoFormat(Constants.H263P_RTP, inputVideoFormat.getSize(), /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, inputVideoFormat.getFrameRate()) };\n }\n\n /**\n * Get codec name.\n *\n * @return codec name\n */\n @Override\n public String getName() {\n return PLUGIN_NAME;\n }\n\n /**\n * Return the list of formats supported at the output.\n * @param inputFormat input Format to determine corresponding\n * output Format/tt>s\n * @return array of formats supported at output\n */\n public Format[] getSupportedOutputFormats(Format inputFormat) {\n if (inputFormat == null)\n return DEFAULT_OUTPUT_FORMATS;\n // mismatch input format\n if (!(inputFormat instanceof VideoFormat) || (AbstractCodec2.matches(inputFormat, inputFormats) == null)) {\n return new Format[0];\n }\n return getMatchingOutputFormats(inputFormat);\n }\n\n /**\n * Open this Packetizer.\n *\n * @throws ResourceUnavailableException if something goes wrong during\n * initialization of the Packetizer.\n */\n @Override\n public synchronized void open() throws ResourceUnavailableException {\n if (!opened) {\n videoPkts.clear();\n sequenceNumber = 0;\n super.open();\n opened = true;\n }\n }\n\n /**\n * Packetizes H.263+ encoded data so that it becomes ready to be sent as the\n * payload of RTP packets.\n *\n * @param data the bytes which contain the H.263+ encoded data to be\n * packetized\n * @param offset the offset of H.263+ encoded data to be packetized begins\n * @param length the length of the H.263+ encoded data starting at offset\n * @return true if at least one RTP packet payload has been\n * packetized i.e. prepared for sending; otherwise, false\n */\n private boolean packetize(byte[] data, int offset, int length) {\n boolean pktAdded = false;\n while (length > 0) {\n boolean isPsc = false;\n int pos = 0;\n int maxPayloadLength = MAX_PAYLOAD_SIZE;\n byte[] pkt = null;\n int payloadLength = 0;\n /* is we are at synchronization point (PSC, GSBC, EOS, EOSBS) */\n if (data.length > 3 && data[offset] == 0x00 && data[offset + 1] == 0x00) {\n isPsc = true;\n pos = 2;\n } else {\n maxPayloadLength -= 2;\n }\n if (length > maxPayloadLength) {\n payloadLength = maxPayloadLength;\n } else {\n payloadLength = length;\n }\n pkt = new byte[payloadLength + (isPsc ? 0 : 2)];\n /* add H263+ payload header */\n /* no VRC and no extra picture header */\n pkt[0] = (byte) (isPsc ? 0x04 : 0x00);\n pkt[1] = 0x00;\n System.arraycopy(data, offset + pos, pkt, 2, payloadLength - pos);\n pktAdded = videoPkts.add(pkt) || pktAdded;\n offset += payloadLength;\n length -= payloadLength;\n }\n return pktAdded;\n }\n\n /**\n * Processes/packetizes a buffer.\n *\n * @param inBuffer input buffer\n * @param outBuffer output buffer\n * @return BUFFER_PROCESSED_OK if buffer has been successfully\n * processed\n */\n @Override\n public int process(Buffer inBuffer, Buffer outBuffer) {\n int inLength = inBuffer.getLength();\n byte[] inData = (byte[]) inBuffer.getData();\n int inOffset = inBuffer.getOffset();\n boolean pktAdded = false;\n if (videoPkts.size() > 0) {\n byte[] pktData = videoPkts.remove(0);\n // Send the packet.\n outBuffer.setData(pktData);\n outBuffer.setLength(pktData.length);\n outBuffer.setOffset(0);\n outBuffer.setTimeStamp(timeStamp);\n outBuffer.setSequenceNumber(sequenceNumber++);\n // If there are other packets, send them as well.\n if (videoPkts.size() > 0) {\n return (BUFFER_PROCESSED_OK | INPUT_BUFFER_NOT_CONSUMED);\n } else {\n // It's the last packet of the current frame so mark it.\n outBuffer.setFlags(outBuffer.getFlags() | Buffer.FLAG_RTP_MARKER);\n return BUFFER_PROCESSED_OK;\n }\n }\n if (isEOM(inBuffer)) {\n propagateEOM(outBuffer);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n if (inBuffer.isDiscard()) {\n outBuffer.setDiscard(true);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n Format inFormat = inBuffer.getFormat();\n if ((inFormat != inputFormat) && !inFormat.matches(inputFormat))\n setInputFormat(inFormat);\n int endIndex = inOffset + inLength;\n int beginIndex = findStartcode(inData, inOffset, endIndex);\n if (beginIndex < endIndex) {\n for (int nextBeginIndex; beginIndex < endIndex; beginIndex = nextBeginIndex + 3) {\n nextBeginIndex = findStartcode(inData, beginIndex + 3, endIndex);\n int length = nextBeginIndex - beginIndex;\n if (length > 0) {\n pktAdded = packetize(inData, beginIndex, length) || pktAdded;\n beginIndex += length;\n }\n }\n }\n timeStamp = inBuffer.getTimeStamp();\n if (pktAdded) {\n return process(inBuffer, outBuffer);\n } else {\n /* first frame is not a synchronization point, discard ?*/\n return BUFFER_PROCESSED_FAILED;\n }\n }\n\n /**\n * Sets the input format.\n *\n * @param in format to set\n * @return format\n */\n @Override\n public Format setInputFormat(Format in) {\n /*\n * Return null if the specified input Format is incompatible with this\n * Packetizer.\n */\n if (!(in instanceof VideoFormat) || null == AbstractCodec2.matches(in, inputFormats))\n return null;\n inputFormat = in;\n return in;\n }\n\n /**\n * Sets the Format in which this Codec is to output media\n * data.\n *\n * @param format the Format in which this Codec is to\n * output media data\n * @return the Format in which this Codec is currently\n * configured to output media data or null if format was\n * found to be incompatible with this Codec\n */\n @Override\n public Format setOutputFormat(Format format) {\n /*\n * Return null if the specified output Format is incompatible with this\n * Packetizer.\n */\n if (!(format instanceof VideoFormat) || (null == AbstractCodec2.matches(format, getMatchingOutputFormats(inputFormat))))\n return null;\n VideoFormat videoFormat = (VideoFormat) format;\n /*\n * A Packetizer translates raw media data in RTP payloads. Consequently,\n * the size of the output is equal to the size of the input.\n */\n Dimension size = null;\n if (inputFormat != null)\n size = ((VideoFormat) inputFormat).getSize();\n if ((size == null) && format.matches(outputFormat))\n size = ((VideoFormat) outputFormat).getSize();\n outputFormat = new VideoFormat(videoFormat.getEncoding(), size, /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, videoFormat.getFrameRate());\n // Return the outputFormat which is actually set.\n return outputFormat;\n }\n}\n"} {"task_id": "Java_1648", "language": "Java", "task_type": "method_body", "source_file": "java/github/bejayoharen/java-bells/lib-src/libjitsi/src/org/jitsi/impl/neomedia/codec/video/h263p/Packetizer.java", "mask_start_position": 3841, "mask_end_position": 4171, "canonical_solution": "{\n if (inputFormat == null)\n return DEFAULT_OUTPUT_FORMATS;\n // mismatch input format\n if (!(inputFormat instanceof VideoFormat) || (AbstractCodec2.matches(inputFormat, inputFormats) == null)) {\n return new Format[0];\n }\n return getMatchingOutputFormats(inputFormat);\n }", "pre_mask_code": "/*\n * Jitsi, the OpenSource Java VoIP and Instant Messaging client.\n *\n * See terms of license at gnu.org.\n */\npackage org.jitsi.impl.neomedia.codec.video.h263p;\n\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\nimport javax.media.*;\nimport javax.media.format.*;\nimport net.sf.fmj.media.*;\nimport org.jitsi.impl.neomedia.codec.*;\nimport org.jitsi.service.neomedia.codec.*;\n\n/**\n * Packetizes H.263+ encoded data into RTP packets in accord with RFC 4529\n * \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n *\n * @author Sebastien Vincent\n * @author Lyubomir Marinov\n */\npublic class Packetizer extends AbstractPacketizer {\n\n private static final Format[] DEFAULT_OUTPUT_FORMATS = { new VideoFormat(Constants.H263P_RTP) };\n\n /**\n * Maximum payload size without the headers.\n */\n public static final int MAX_PAYLOAD_SIZE = 1024;\n\n /**\n * Name of the plugin.\n */\n private static final String PLUGIN_NAME = \"H263+ Packetizer\";\n\n /**\n * Finds the index in byteStream at which a Picture Start code\n * begins.\n *\n * @param byteStream the H.263+ encoded byte stream\n * @param beginIndex the inclusive index in byteStream at which the\n * search is to begin\n * @param endIndex the exclusive index in byteStream at which the\n * search is to end\n * @return the index in byteStream at which the Picture Start code\n * begins, otherwise, endIndex\n */\n private static int findStartcode(byte[] byteStream, int beginIndex, int endIndex) {\n for (; beginIndex < (endIndex - 3); beginIndex++) {\n if ((byteStream[beginIndex] == 0) && (byteStream[beginIndex + 1] == 0) && ((byteStream[beginIndex + 2] & (byte) 0x80) == -128)) {\n return beginIndex;\n }\n }\n return endIndex;\n }\n\n /**\n * The sequence number of the next RTP packet to be output by this\n * Packetizer.\n */\n private int sequenceNumber = 0;\n\n /**\n * The timeStamp of the RTP packets in which H263+ packets are to be sent.\n */\n private long timeStamp = 0;\n\n /**\n * The list of H263+ \"Start code\" video packets to be sent as payload in RTP\n * packets.\n */\n private final List videoPkts = new LinkedList();\n\n /**\n * Initializes a new Packetizer instance which is to packetize\n * H.263+ encoded data into RTP packets in accord with\n * RFC 4529 \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n */\n public Packetizer() {\n inputFormats = new Format[] { new VideoFormat(Constants.H263P) };\n inputFormat = null;\n outputFormat = null;\n }\n\n @Override\n public synchronized void close() {\n if (opened) {\n videoPkts.clear();\n opened = false;\n super.close();\n }\n }\n\n /**\n * Get the matching output formats for a specific format.\n *\n * @param inputFormat input format\n * @return array for formats matching input format\n */\n private Format[] getMatchingOutputFormats(Format inputFormat) {\n VideoFormat inputVideoFormat = (VideoFormat) inputFormat;\n return new Format[] { new VideoFormat(Constants.H263P_RTP, inputVideoFormat.getSize(), /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, inputVideoFormat.getFrameRate()) };\n }\n\n /**\n * Get codec name.\n *\n * @return codec name\n */\n @Override\n public String getName() {\n return PLUGIN_NAME;\n }\n\n /**\n * Return the list of formats supported at the output.\n * @param inputFormat input Format to determine corresponding\n * output Format/tt>s\n * @return array of formats supported at output\n */\n public Format[] getSupportedOutputFormats(Format inputFormat) ", "post_mask_code": "\n\n /**\n * Open this Packetizer.\n *\n * @throws ResourceUnavailableException if something goes wrong during\n * initialization of the Packetizer.\n */\n @Override\n public synchronized void open() throws ResourceUnavailableException {\n if (!opened) {\n videoPkts.clear();\n sequenceNumber = 0;\n super.open();\n opened = true;\n }\n }\n\n /**\n * Packetizes H.263+ encoded data so that it becomes ready to be sent as the\n * payload of RTP packets.\n *\n * @param data the bytes which contain the H.263+ encoded data to be\n * packetized\n * @param offset the offset of H.263+ encoded data to be packetized begins\n * @param length the length of the H.263+ encoded data starting at offset\n * @return true if at least one RTP packet payload has been\n * packetized i.e. prepared for sending; otherwise, false\n */\n private boolean packetize(byte[] data, int offset, int length) {\n boolean pktAdded = false;\n while (length > 0) {\n boolean isPsc = false;\n int pos = 0;\n int maxPayloadLength = MAX_PAYLOAD_SIZE;\n byte[] pkt = null;\n int payloadLength = 0;\n /* is we are at synchronization point (PSC, GSBC, EOS, EOSBS) */\n if (data.length > 3 && data[offset] == 0x00 && data[offset + 1] == 0x00) {\n isPsc = true;\n pos = 2;\n } else {\n maxPayloadLength -= 2;\n }\n if (length > maxPayloadLength) {\n payloadLength = maxPayloadLength;\n } else {\n payloadLength = length;\n }\n pkt = new byte[payloadLength + (isPsc ? 0 : 2)];\n /* add H263+ payload header */\n /* no VRC and no extra picture header */\n pkt[0] = (byte) (isPsc ? 0x04 : 0x00);\n pkt[1] = 0x00;\n System.arraycopy(data, offset + pos, pkt, 2, payloadLength - pos);\n pktAdded = videoPkts.add(pkt) || pktAdded;\n offset += payloadLength;\n length -= payloadLength;\n }\n return pktAdded;\n }\n\n /**\n * Processes/packetizes a buffer.\n *\n * @param inBuffer input buffer\n * @param outBuffer output buffer\n * @return BUFFER_PROCESSED_OK if buffer has been successfully\n * processed\n */\n @Override\n public int process(Buffer inBuffer, Buffer outBuffer) {\n int inLength = inBuffer.getLength();\n byte[] inData = (byte[]) inBuffer.getData();\n int inOffset = inBuffer.getOffset();\n boolean pktAdded = false;\n if (videoPkts.size() > 0) {\n byte[] pktData = videoPkts.remove(0);\n // Send the packet.\n outBuffer.setData(pktData);\n outBuffer.setLength(pktData.length);\n outBuffer.setOffset(0);\n outBuffer.setTimeStamp(timeStamp);\n outBuffer.setSequenceNumber(sequenceNumber++);\n // If there are other packets, send them as well.\n if (videoPkts.size() > 0) {\n return (BUFFER_PROCESSED_OK | INPUT_BUFFER_NOT_CONSUMED);\n } else {\n // It's the last packet of the current frame so mark it.\n outBuffer.setFlags(outBuffer.getFlags() | Buffer.FLAG_RTP_MARKER);\n return BUFFER_PROCESSED_OK;\n }\n }\n if (isEOM(inBuffer)) {\n propagateEOM(outBuffer);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n if (inBuffer.isDiscard()) {\n outBuffer.setDiscard(true);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n Format inFormat = inBuffer.getFormat();\n if ((inFormat != inputFormat) && !inFormat.matches(inputFormat))\n setInputFormat(inFormat);\n int endIndex = inOffset + inLength;\n int beginIndex = findStartcode(inData, inOffset, endIndex);\n if (beginIndex < endIndex) {\n for (int nextBeginIndex; beginIndex < endIndex; beginIndex = nextBeginIndex + 3) {\n nextBeginIndex = findStartcode(inData, beginIndex + 3, endIndex);\n int length = nextBeginIndex - beginIndex;\n if (length > 0) {\n pktAdded = packetize(inData, beginIndex, length) || pktAdded;\n beginIndex += length;\n }\n }\n }\n timeStamp = inBuffer.getTimeStamp();\n if (pktAdded) {\n return process(inBuffer, outBuffer);\n } else {\n /* first frame is not a synchronization point, discard ?*/\n return BUFFER_PROCESSED_FAILED;\n }\n }\n\n /**\n * Sets the input format.\n *\n * @param in format to set\n * @return format\n */\n @Override\n public Format setInputFormat(Format in) {\n /*\n * Return null if the specified input Format is incompatible with this\n * Packetizer.\n */\n if (!(in instanceof VideoFormat) || null == AbstractCodec2.matches(in, inputFormats))\n return null;\n inputFormat = in;\n return in;\n }\n\n /**\n * Sets the Format in which this Codec is to output media\n * data.\n *\n * @param format the Format in which this Codec is to\n * output media data\n * @return the Format in which this Codec is currently\n * configured to output media data or null if format was\n * found to be incompatible with this Codec\n */\n @Override\n public Format setOutputFormat(Format format) {\n /*\n * Return null if the specified output Format is incompatible with this\n * Packetizer.\n */\n if (!(format instanceof VideoFormat) || (null == AbstractCodec2.matches(format, getMatchingOutputFormats(inputFormat))))\n return null;\n VideoFormat videoFormat = (VideoFormat) format;\n /*\n * A Packetizer translates raw media data in RTP payloads. Consequently,\n * the size of the output is equal to the size of the input.\n */\n Dimension size = null;\n if (inputFormat != null)\n size = ((VideoFormat) inputFormat).getSize();\n if ((size == null) && format.matches(outputFormat))\n size = ((VideoFormat) outputFormat).getSize();\n outputFormat = new VideoFormat(videoFormat.getEncoding(), size, /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, videoFormat.getFrameRate());\n // Return the outputFormat which is actually set.\n return outputFormat;\n }\n}\n"} {"task_id": "Java_1649", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/bejayoharen/java-bells/lib-src/libjitsi/src/org/jitsi/impl/neomedia/codec/video/h263p/Packetizer.java", "mask_start_position": 5190, "mask_end_position": 5224, "canonical_solution": "\n boolean pktAdded = false;", "pre_mask_code": "/*\n * Jitsi, the OpenSource Java VoIP and Instant Messaging client.\n *\n * See terms of license at gnu.org.\n */\npackage org.jitsi.impl.neomedia.codec.video.h263p;\n\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\nimport javax.media.*;\nimport javax.media.format.*;\nimport net.sf.fmj.media.*;\nimport org.jitsi.impl.neomedia.codec.*;\nimport org.jitsi.service.neomedia.codec.*;\n\n/**\n * Packetizes H.263+ encoded data into RTP packets in accord with RFC 4529\n * \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n *\n * @author Sebastien Vincent\n * @author Lyubomir Marinov\n */\npublic class Packetizer extends AbstractPacketizer {\n\n private static final Format[] DEFAULT_OUTPUT_FORMATS = { new VideoFormat(Constants.H263P_RTP) };\n\n /**\n * Maximum payload size without the headers.\n */\n public static final int MAX_PAYLOAD_SIZE = 1024;\n\n /**\n * Name of the plugin.\n */\n private static final String PLUGIN_NAME = \"H263+ Packetizer\";\n\n /**\n * Finds the index in byteStream at which a Picture Start code\n * begins.\n *\n * @param byteStream the H.263+ encoded byte stream\n * @param beginIndex the inclusive index in byteStream at which the\n * search is to begin\n * @param endIndex the exclusive index in byteStream at which the\n * search is to end\n * @return the index in byteStream at which the Picture Start code\n * begins, otherwise, endIndex\n */\n private static int findStartcode(byte[] byteStream, int beginIndex, int endIndex) {\n for (; beginIndex < (endIndex - 3); beginIndex++) {\n if ((byteStream[beginIndex] == 0) && (byteStream[beginIndex + 1] == 0) && ((byteStream[beginIndex + 2] & (byte) 0x80) == -128)) {\n return beginIndex;\n }\n }\n return endIndex;\n }\n\n /**\n * The sequence number of the next RTP packet to be output by this\n * Packetizer.\n */\n private int sequenceNumber = 0;\n\n /**\n * The timeStamp of the RTP packets in which H263+ packets are to be sent.\n */\n private long timeStamp = 0;\n\n /**\n * The list of H263+ \"Start code\" video packets to be sent as payload in RTP\n * packets.\n */\n private final List videoPkts = new LinkedList();\n\n /**\n * Initializes a new Packetizer instance which is to packetize\n * H.263+ encoded data into RTP packets in accord with\n * RFC 4529 \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n */\n public Packetizer() {\n inputFormats = new Format[] { new VideoFormat(Constants.H263P) };\n inputFormat = null;\n outputFormat = null;\n }\n\n @Override\n public synchronized void close() {\n if (opened) {\n videoPkts.clear();\n opened = false;\n super.close();\n }\n }\n\n /**\n * Get the matching output formats for a specific format.\n *\n * @param inputFormat input format\n * @return array for formats matching input format\n */\n private Format[] getMatchingOutputFormats(Format inputFormat) {\n VideoFormat inputVideoFormat = (VideoFormat) inputFormat;\n return new Format[] { new VideoFormat(Constants.H263P_RTP, inputVideoFormat.getSize(), /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, inputVideoFormat.getFrameRate()) };\n }\n\n /**\n * Get codec name.\n *\n * @return codec name\n */\n @Override\n public String getName() {\n return PLUGIN_NAME;\n }\n\n /**\n * Return the list of formats supported at the output.\n * @param inputFormat input Format to determine corresponding\n * output Format/tt>s\n * @return array of formats supported at output\n */\n public Format[] getSupportedOutputFormats(Format inputFormat) {\n if (inputFormat == null)\n return DEFAULT_OUTPUT_FORMATS;\n // mismatch input format\n if (!(inputFormat instanceof VideoFormat) || (AbstractCodec2.matches(inputFormat, inputFormats) == null)) {\n return new Format[0];\n }\n return getMatchingOutputFormats(inputFormat);\n }\n\n /**\n * Open this Packetizer.\n *\n * @throws ResourceUnavailableException if something goes wrong during\n * initialization of the Packetizer.\n */\n @Override\n public synchronized void open() throws ResourceUnavailableException {\n if (!opened) {\n videoPkts.clear();\n sequenceNumber = 0;\n super.open();\n opened = true;\n }\n }\n\n /**\n * Packetizes H.263+ encoded data so that it becomes ready to be sent as the\n * payload of RTP packets.\n *\n * @param data the bytes which contain the H.263+ encoded data to be\n * packetized\n * @param offset the offset of H.263+ encoded data to be packetized begins\n * @param length the length of the H.263+ encoded data starting at offset\n * @return true if at least one RTP packet payload has been\n * packetized i.e. prepared for sending; otherwise, false\n */\n private boolean packetize(byte[] data, int offset, int length) {", "post_mask_code": "\n while (length > 0) {\n boolean isPsc = false;\n int pos = 0;\n int maxPayloadLength = MAX_PAYLOAD_SIZE;\n byte[] pkt = null;\n int payloadLength = 0;\n /* is we are at synchronization point (PSC, GSBC, EOS, EOSBS) */\n if (data.length > 3 && data[offset] == 0x00 && data[offset + 1] == 0x00) {\n isPsc = true;\n pos = 2;\n } else {\n maxPayloadLength -= 2;\n }\n if (length > maxPayloadLength) {\n payloadLength = maxPayloadLength;\n } else {\n payloadLength = length;\n }\n pkt = new byte[payloadLength + (isPsc ? 0 : 2)];\n /* add H263+ payload header */\n /* no VRC and no extra picture header */\n pkt[0] = (byte) (isPsc ? 0x04 : 0x00);\n pkt[1] = 0x00;\n System.arraycopy(data, offset + pos, pkt, 2, payloadLength - pos);\n pktAdded = videoPkts.add(pkt) || pktAdded;\n offset += payloadLength;\n length -= payloadLength;\n }\n return pktAdded;\n }\n\n /**\n * Processes/packetizes a buffer.\n *\n * @param inBuffer input buffer\n * @param outBuffer output buffer\n * @return BUFFER_PROCESSED_OK if buffer has been successfully\n * processed\n */\n @Override\n public int process(Buffer inBuffer, Buffer outBuffer) {\n int inLength = inBuffer.getLength();\n byte[] inData = (byte[]) inBuffer.getData();\n int inOffset = inBuffer.getOffset();\n boolean pktAdded = false;\n if (videoPkts.size() > 0) {\n byte[] pktData = videoPkts.remove(0);\n // Send the packet.\n outBuffer.setData(pktData);\n outBuffer.setLength(pktData.length);\n outBuffer.setOffset(0);\n outBuffer.setTimeStamp(timeStamp);\n outBuffer.setSequenceNumber(sequenceNumber++);\n // If there are other packets, send them as well.\n if (videoPkts.size() > 0) {\n return (BUFFER_PROCESSED_OK | INPUT_BUFFER_NOT_CONSUMED);\n } else {\n // It's the last packet of the current frame so mark it.\n outBuffer.setFlags(outBuffer.getFlags() | Buffer.FLAG_RTP_MARKER);\n return BUFFER_PROCESSED_OK;\n }\n }\n if (isEOM(inBuffer)) {\n propagateEOM(outBuffer);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n if (inBuffer.isDiscard()) {\n outBuffer.setDiscard(true);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n Format inFormat = inBuffer.getFormat();\n if ((inFormat != inputFormat) && !inFormat.matches(inputFormat))\n setInputFormat(inFormat);\n int endIndex = inOffset + inLength;\n int beginIndex = findStartcode(inData, inOffset, endIndex);\n if (beginIndex < endIndex) {\n for (int nextBeginIndex; beginIndex < endIndex; beginIndex = nextBeginIndex + 3) {\n nextBeginIndex = findStartcode(inData, beginIndex + 3, endIndex);\n int length = nextBeginIndex - beginIndex;\n if (length > 0) {\n pktAdded = packetize(inData, beginIndex, length) || pktAdded;\n beginIndex += length;\n }\n }\n }\n timeStamp = inBuffer.getTimeStamp();\n if (pktAdded) {\n return process(inBuffer, outBuffer);\n } else {\n /* first frame is not a synchronization point, discard ?*/\n return BUFFER_PROCESSED_FAILED;\n }\n }\n\n /**\n * Sets the input format.\n *\n * @param in format to set\n * @return format\n */\n @Override\n public Format setInputFormat(Format in) {\n /*\n * Return null if the specified input Format is incompatible with this\n * Packetizer.\n */\n if (!(in instanceof VideoFormat) || null == AbstractCodec2.matches(in, inputFormats))\n return null;\n inputFormat = in;\n return in;\n }\n\n /**\n * Sets the Format in which this Codec is to output media\n * data.\n *\n * @param format the Format in which this Codec is to\n * output media data\n * @return the Format in which this Codec is currently\n * configured to output media data or null if format was\n * found to be incompatible with this Codec\n */\n @Override\n public Format setOutputFormat(Format format) {\n /*\n * Return null if the specified output Format is incompatible with this\n * Packetizer.\n */\n if (!(format instanceof VideoFormat) || (null == AbstractCodec2.matches(format, getMatchingOutputFormats(inputFormat))))\n return null;\n VideoFormat videoFormat = (VideoFormat) format;\n /*\n * A Packetizer translates raw media data in RTP payloads. Consequently,\n * the size of the output is equal to the size of the input.\n */\n Dimension size = null;\n if (inputFormat != null)\n size = ((VideoFormat) inputFormat).getSize();\n if ((size == null) && format.matches(outputFormat))\n size = ((VideoFormat) outputFormat).getSize();\n outputFormat = new VideoFormat(videoFormat.getEncoding(), size, /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, videoFormat.getFrameRate());\n // Return the outputFormat which is actually set.\n return outputFormat;\n }\n}\n"} {"task_id": "Java_1650", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/bejayoharen/java-bells/lib-src/libjitsi/src/org/jitsi/impl/neomedia/codec/video/h263p/Packetizer.java", "mask_start_position": 5233, "mask_end_position": 6348, "canonical_solution": "while (length > 0) {\n boolean isPsc = false;\n int pos = 0;\n int maxPayloadLength = MAX_PAYLOAD_SIZE;\n byte[] pkt = null;\n int payloadLength = 0;\n /* is we are at synchronization point (PSC, GSBC, EOS, EOSBS) */\n if (data.length > 3 && data[offset] == 0x00 && data[offset + 1] == 0x00) {\n isPsc = true;\n pos = 2;\n } else {\n maxPayloadLength -= 2;\n }\n if (length > maxPayloadLength) {\n payloadLength = maxPayloadLength;\n } else {\n payloadLength = length;\n }\n pkt = new byte[payloadLength + (isPsc ? 0 : 2)];\n /* add H263+ payload header */\n /* no VRC and no extra picture header */\n pkt[0] = (byte) (isPsc ? 0x04 : 0x00);\n pkt[1] = 0x00;\n System.arraycopy(data, offset + pos, pkt, 2, payloadLength - pos);\n pktAdded = videoPkts.add(pkt) || pktAdded;\n offset += payloadLength;\n length -= payloadLength;\n }", "pre_mask_code": "/*\n * Jitsi, the OpenSource Java VoIP and Instant Messaging client.\n *\n * See terms of license at gnu.org.\n */\npackage org.jitsi.impl.neomedia.codec.video.h263p;\n\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\nimport javax.media.*;\nimport javax.media.format.*;\nimport net.sf.fmj.media.*;\nimport org.jitsi.impl.neomedia.codec.*;\nimport org.jitsi.service.neomedia.codec.*;\n\n/**\n * Packetizes H.263+ encoded data into RTP packets in accord with RFC 4529\n * \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n *\n * @author Sebastien Vincent\n * @author Lyubomir Marinov\n */\npublic class Packetizer extends AbstractPacketizer {\n\n private static final Format[] DEFAULT_OUTPUT_FORMATS = { new VideoFormat(Constants.H263P_RTP) };\n\n /**\n * Maximum payload size without the headers.\n */\n public static final int MAX_PAYLOAD_SIZE = 1024;\n\n /**\n * Name of the plugin.\n */\n private static final String PLUGIN_NAME = \"H263+ Packetizer\";\n\n /**\n * Finds the index in byteStream at which a Picture Start code\n * begins.\n *\n * @param byteStream the H.263+ encoded byte stream\n * @param beginIndex the inclusive index in byteStream at which the\n * search is to begin\n * @param endIndex the exclusive index in byteStream at which the\n * search is to end\n * @return the index in byteStream at which the Picture Start code\n * begins, otherwise, endIndex\n */\n private static int findStartcode(byte[] byteStream, int beginIndex, int endIndex) {\n for (; beginIndex < (endIndex - 3); beginIndex++) {\n if ((byteStream[beginIndex] == 0) && (byteStream[beginIndex + 1] == 0) && ((byteStream[beginIndex + 2] & (byte) 0x80) == -128)) {\n return beginIndex;\n }\n }\n return endIndex;\n }\n\n /**\n * The sequence number of the next RTP packet to be output by this\n * Packetizer.\n */\n private int sequenceNumber = 0;\n\n /**\n * The timeStamp of the RTP packets in which H263+ packets are to be sent.\n */\n private long timeStamp = 0;\n\n /**\n * The list of H263+ \"Start code\" video packets to be sent as payload in RTP\n * packets.\n */\n private final List videoPkts = new LinkedList();\n\n /**\n * Initializes a new Packetizer instance which is to packetize\n * H.263+ encoded data into RTP packets in accord with\n * RFC 4529 \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n */\n public Packetizer() {\n inputFormats = new Format[] { new VideoFormat(Constants.H263P) };\n inputFormat = null;\n outputFormat = null;\n }\n\n @Override\n public synchronized void close() {\n if (opened) {\n videoPkts.clear();\n opened = false;\n super.close();\n }\n }\n\n /**\n * Get the matching output formats for a specific format.\n *\n * @param inputFormat input format\n * @return array for formats matching input format\n */\n private Format[] getMatchingOutputFormats(Format inputFormat) {\n VideoFormat inputVideoFormat = (VideoFormat) inputFormat;\n return new Format[] { new VideoFormat(Constants.H263P_RTP, inputVideoFormat.getSize(), /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, inputVideoFormat.getFrameRate()) };\n }\n\n /**\n * Get codec name.\n *\n * @return codec name\n */\n @Override\n public String getName() {\n return PLUGIN_NAME;\n }\n\n /**\n * Return the list of formats supported at the output.\n * @param inputFormat input Format to determine corresponding\n * output Format/tt>s\n * @return array of formats supported at output\n */\n public Format[] getSupportedOutputFormats(Format inputFormat) {\n if (inputFormat == null)\n return DEFAULT_OUTPUT_FORMATS;\n // mismatch input format\n if (!(inputFormat instanceof VideoFormat) || (AbstractCodec2.matches(inputFormat, inputFormats) == null)) {\n return new Format[0];\n }\n return getMatchingOutputFormats(inputFormat);\n }\n\n /**\n * Open this Packetizer.\n *\n * @throws ResourceUnavailableException if something goes wrong during\n * initialization of the Packetizer.\n */\n @Override\n public synchronized void open() throws ResourceUnavailableException {\n if (!opened) {\n videoPkts.clear();\n sequenceNumber = 0;\n super.open();\n opened = true;\n }\n }\n\n /**\n * Packetizes H.263+ encoded data so that it becomes ready to be sent as the\n * payload of RTP packets.\n *\n * @param data the bytes which contain the H.263+ encoded data to be\n * packetized\n * @param offset the offset of H.263+ encoded data to be packetized begins\n * @param length the length of the H.263+ encoded data starting at offset\n * @return true if at least one RTP packet payload has been\n * packetized i.e. prepared for sending; otherwise, false\n */\n private boolean packetize(byte[] data, int offset, int length) {\n boolean pktAdded = false;\n ", "post_mask_code": "\n return pktAdded;\n }\n\n /**\n * Processes/packetizes a buffer.\n *\n * @param inBuffer input buffer\n * @param outBuffer output buffer\n * @return BUFFER_PROCESSED_OK if buffer has been successfully\n * processed\n */\n @Override\n public int process(Buffer inBuffer, Buffer outBuffer) {\n int inLength = inBuffer.getLength();\n byte[] inData = (byte[]) inBuffer.getData();\n int inOffset = inBuffer.getOffset();\n boolean pktAdded = false;\n if (videoPkts.size() > 0) {\n byte[] pktData = videoPkts.remove(0);\n // Send the packet.\n outBuffer.setData(pktData);\n outBuffer.setLength(pktData.length);\n outBuffer.setOffset(0);\n outBuffer.setTimeStamp(timeStamp);\n outBuffer.setSequenceNumber(sequenceNumber++);\n // If there are other packets, send them as well.\n if (videoPkts.size() > 0) {\n return (BUFFER_PROCESSED_OK | INPUT_BUFFER_NOT_CONSUMED);\n } else {\n // It's the last packet of the current frame so mark it.\n outBuffer.setFlags(outBuffer.getFlags() | Buffer.FLAG_RTP_MARKER);\n return BUFFER_PROCESSED_OK;\n }\n }\n if (isEOM(inBuffer)) {\n propagateEOM(outBuffer);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n if (inBuffer.isDiscard()) {\n outBuffer.setDiscard(true);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n Format inFormat = inBuffer.getFormat();\n if ((inFormat != inputFormat) && !inFormat.matches(inputFormat))\n setInputFormat(inFormat);\n int endIndex = inOffset + inLength;\n int beginIndex = findStartcode(inData, inOffset, endIndex);\n if (beginIndex < endIndex) {\n for (int nextBeginIndex; beginIndex < endIndex; beginIndex = nextBeginIndex + 3) {\n nextBeginIndex = findStartcode(inData, beginIndex + 3, endIndex);\n int length = nextBeginIndex - beginIndex;\n if (length > 0) {\n pktAdded = packetize(inData, beginIndex, length) || pktAdded;\n beginIndex += length;\n }\n }\n }\n timeStamp = inBuffer.getTimeStamp();\n if (pktAdded) {\n return process(inBuffer, outBuffer);\n } else {\n /* first frame is not a synchronization point, discard ?*/\n return BUFFER_PROCESSED_FAILED;\n }\n }\n\n /**\n * Sets the input format.\n *\n * @param in format to set\n * @return format\n */\n @Override\n public Format setInputFormat(Format in) {\n /*\n * Return null if the specified input Format is incompatible with this\n * Packetizer.\n */\n if (!(in instanceof VideoFormat) || null == AbstractCodec2.matches(in, inputFormats))\n return null;\n inputFormat = in;\n return in;\n }\n\n /**\n * Sets the Format in which this Codec is to output media\n * data.\n *\n * @param format the Format in which this Codec is to\n * output media data\n * @return the Format in which this Codec is currently\n * configured to output media data or null if format was\n * found to be incompatible with this Codec\n */\n @Override\n public Format setOutputFormat(Format format) {\n /*\n * Return null if the specified output Format is incompatible with this\n * Packetizer.\n */\n if (!(format instanceof VideoFormat) || (null == AbstractCodec2.matches(format, getMatchingOutputFormats(inputFormat))))\n return null;\n VideoFormat videoFormat = (VideoFormat) format;\n /*\n * A Packetizer translates raw media data in RTP payloads. Consequently,\n * the size of the output is equal to the size of the input.\n */\n Dimension size = null;\n if (inputFormat != null)\n size = ((VideoFormat) inputFormat).getSize();\n if ((size == null) && format.matches(outputFormat))\n size = ((VideoFormat) outputFormat).getSize();\n outputFormat = new VideoFormat(videoFormat.getEncoding(), size, /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, videoFormat.getFrameRate());\n // Return the outputFormat which is actually set.\n return outputFormat;\n }\n}\n"} {"task_id": "Java_1651", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/bejayoharen/java-bells/lib-src/libjitsi/src/org/jitsi/impl/neomedia/codec/video/h263p/Packetizer.java", "mask_start_position": 6357, "mask_end_position": 6379, "canonical_solution": "return pktAdded;\n }", "pre_mask_code": "/*\n * Jitsi, the OpenSource Java VoIP and Instant Messaging client.\n *\n * See terms of license at gnu.org.\n */\npackage org.jitsi.impl.neomedia.codec.video.h263p;\n\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\nimport javax.media.*;\nimport javax.media.format.*;\nimport net.sf.fmj.media.*;\nimport org.jitsi.impl.neomedia.codec.*;\nimport org.jitsi.service.neomedia.codec.*;\n\n/**\n * Packetizes H.263+ encoded data into RTP packets in accord with RFC 4529\n * \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n *\n * @author Sebastien Vincent\n * @author Lyubomir Marinov\n */\npublic class Packetizer extends AbstractPacketizer {\n\n private static final Format[] DEFAULT_OUTPUT_FORMATS = { new VideoFormat(Constants.H263P_RTP) };\n\n /**\n * Maximum payload size without the headers.\n */\n public static final int MAX_PAYLOAD_SIZE = 1024;\n\n /**\n * Name of the plugin.\n */\n private static final String PLUGIN_NAME = \"H263+ Packetizer\";\n\n /**\n * Finds the index in byteStream at which a Picture Start code\n * begins.\n *\n * @param byteStream the H.263+ encoded byte stream\n * @param beginIndex the inclusive index in byteStream at which the\n * search is to begin\n * @param endIndex the exclusive index in byteStream at which the\n * search is to end\n * @return the index in byteStream at which the Picture Start code\n * begins, otherwise, endIndex\n */\n private static int findStartcode(byte[] byteStream, int beginIndex, int endIndex) {\n for (; beginIndex < (endIndex - 3); beginIndex++) {\n if ((byteStream[beginIndex] == 0) && (byteStream[beginIndex + 1] == 0) && ((byteStream[beginIndex + 2] & (byte) 0x80) == -128)) {\n return beginIndex;\n }\n }\n return endIndex;\n }\n\n /**\n * The sequence number of the next RTP packet to be output by this\n * Packetizer.\n */\n private int sequenceNumber = 0;\n\n /**\n * The timeStamp of the RTP packets in which H263+ packets are to be sent.\n */\n private long timeStamp = 0;\n\n /**\n * The list of H263+ \"Start code\" video packets to be sent as payload in RTP\n * packets.\n */\n private final List videoPkts = new LinkedList();\n\n /**\n * Initializes a new Packetizer instance which is to packetize\n * H.263+ encoded data into RTP packets in accord with\n * RFC 4529 \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n */\n public Packetizer() {\n inputFormats = new Format[] { new VideoFormat(Constants.H263P) };\n inputFormat = null;\n outputFormat = null;\n }\n\n @Override\n public synchronized void close() {\n if (opened) {\n videoPkts.clear();\n opened = false;\n super.close();\n }\n }\n\n /**\n * Get the matching output formats for a specific format.\n *\n * @param inputFormat input format\n * @return array for formats matching input format\n */\n private Format[] getMatchingOutputFormats(Format inputFormat) {\n VideoFormat inputVideoFormat = (VideoFormat) inputFormat;\n return new Format[] { new VideoFormat(Constants.H263P_RTP, inputVideoFormat.getSize(), /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, inputVideoFormat.getFrameRate()) };\n }\n\n /**\n * Get codec name.\n *\n * @return codec name\n */\n @Override\n public String getName() {\n return PLUGIN_NAME;\n }\n\n /**\n * Return the list of formats supported at the output.\n * @param inputFormat input Format to determine corresponding\n * output Format/tt>s\n * @return array of formats supported at output\n */\n public Format[] getSupportedOutputFormats(Format inputFormat) {\n if (inputFormat == null)\n return DEFAULT_OUTPUT_FORMATS;\n // mismatch input format\n if (!(inputFormat instanceof VideoFormat) || (AbstractCodec2.matches(inputFormat, inputFormats) == null)) {\n return new Format[0];\n }\n return getMatchingOutputFormats(inputFormat);\n }\n\n /**\n * Open this Packetizer.\n *\n * @throws ResourceUnavailableException if something goes wrong during\n * initialization of the Packetizer.\n */\n @Override\n public synchronized void open() throws ResourceUnavailableException {\n if (!opened) {\n videoPkts.clear();\n sequenceNumber = 0;\n super.open();\n opened = true;\n }\n }\n\n /**\n * Packetizes H.263+ encoded data so that it becomes ready to be sent as the\n * payload of RTP packets.\n *\n * @param data the bytes which contain the H.263+ encoded data to be\n * packetized\n * @param offset the offset of H.263+ encoded data to be packetized begins\n * @param length the length of the H.263+ encoded data starting at offset\n * @return true if at least one RTP packet payload has been\n * packetized i.e. prepared for sending; otherwise, false\n */\n private boolean packetize(byte[] data, int offset, int length) {\n boolean pktAdded = false;\n while (length > 0) {\n boolean isPsc = false;\n int pos = 0;\n int maxPayloadLength = MAX_PAYLOAD_SIZE;\n byte[] pkt = null;\n int payloadLength = 0;\n /* is we are at synchronization point (PSC, GSBC, EOS, EOSBS) */\n if (data.length > 3 && data[offset] == 0x00 && data[offset + 1] == 0x00) {\n isPsc = true;\n pos = 2;\n } else {\n maxPayloadLength -= 2;\n }\n if (length > maxPayloadLength) {\n payloadLength = maxPayloadLength;\n } else {\n payloadLength = length;\n }\n pkt = new byte[payloadLength + (isPsc ? 0 : 2)];\n /* add H263+ payload header */\n /* no VRC and no extra picture header */\n pkt[0] = (byte) (isPsc ? 0x04 : 0x00);\n pkt[1] = 0x00;\n System.arraycopy(data, offset + pos, pkt, 2, payloadLength - pos);\n pktAdded = videoPkts.add(pkt) || pktAdded;\n offset += payloadLength;\n length -= payloadLength;\n }\n ", "post_mask_code": "\n\n /**\n * Processes/packetizes a buffer.\n *\n * @param inBuffer input buffer\n * @param outBuffer output buffer\n * @return BUFFER_PROCESSED_OK if buffer has been successfully\n * processed\n */\n @Override\n public int process(Buffer inBuffer, Buffer outBuffer) {\n int inLength = inBuffer.getLength();\n byte[] inData = (byte[]) inBuffer.getData();\n int inOffset = inBuffer.getOffset();\n boolean pktAdded = false;\n if (videoPkts.size() > 0) {\n byte[] pktData = videoPkts.remove(0);\n // Send the packet.\n outBuffer.setData(pktData);\n outBuffer.setLength(pktData.length);\n outBuffer.setOffset(0);\n outBuffer.setTimeStamp(timeStamp);\n outBuffer.setSequenceNumber(sequenceNumber++);\n // If there are other packets, send them as well.\n if (videoPkts.size() > 0) {\n return (BUFFER_PROCESSED_OK | INPUT_BUFFER_NOT_CONSUMED);\n } else {\n // It's the last packet of the current frame so mark it.\n outBuffer.setFlags(outBuffer.getFlags() | Buffer.FLAG_RTP_MARKER);\n return BUFFER_PROCESSED_OK;\n }\n }\n if (isEOM(inBuffer)) {\n propagateEOM(outBuffer);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n if (inBuffer.isDiscard()) {\n outBuffer.setDiscard(true);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n Format inFormat = inBuffer.getFormat();\n if ((inFormat != inputFormat) && !inFormat.matches(inputFormat))\n setInputFormat(inFormat);\n int endIndex = inOffset + inLength;\n int beginIndex = findStartcode(inData, inOffset, endIndex);\n if (beginIndex < endIndex) {\n for (int nextBeginIndex; beginIndex < endIndex; beginIndex = nextBeginIndex + 3) {\n nextBeginIndex = findStartcode(inData, beginIndex + 3, endIndex);\n int length = nextBeginIndex - beginIndex;\n if (length > 0) {\n pktAdded = packetize(inData, beginIndex, length) || pktAdded;\n beginIndex += length;\n }\n }\n }\n timeStamp = inBuffer.getTimeStamp();\n if (pktAdded) {\n return process(inBuffer, outBuffer);\n } else {\n /* first frame is not a synchronization point, discard ?*/\n return BUFFER_PROCESSED_FAILED;\n }\n }\n\n /**\n * Sets the input format.\n *\n * @param in format to set\n * @return format\n */\n @Override\n public Format setInputFormat(Format in) {\n /*\n * Return null if the specified input Format is incompatible with this\n * Packetizer.\n */\n if (!(in instanceof VideoFormat) || null == AbstractCodec2.matches(in, inputFormats))\n return null;\n inputFormat = in;\n return in;\n }\n\n /**\n * Sets the Format in which this Codec is to output media\n * data.\n *\n * @param format the Format in which this Codec is to\n * output media data\n * @return the Format in which this Codec is currently\n * configured to output media data or null if format was\n * found to be incompatible with this Codec\n */\n @Override\n public Format setOutputFormat(Format format) {\n /*\n * Return null if the specified output Format is incompatible with this\n * Packetizer.\n */\n if (!(format instanceof VideoFormat) || (null == AbstractCodec2.matches(format, getMatchingOutputFormats(inputFormat))))\n return null;\n VideoFormat videoFormat = (VideoFormat) format;\n /*\n * A Packetizer translates raw media data in RTP payloads. Consequently,\n * the size of the output is equal to the size of the input.\n */\n Dimension size = null;\n if (inputFormat != null)\n size = ((VideoFormat) inputFormat).getSize();\n if ((size == null) && format.matches(outputFormat))\n size = ((VideoFormat) outputFormat).getSize();\n outputFormat = new VideoFormat(videoFormat.getEncoding(), size, /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, videoFormat.getFrameRate());\n // Return the outputFormat which is actually set.\n return outputFormat;\n }\n}\n"} {"task_id": "Java_1652", "language": "Java", "task_type": "single_line", "source_file": "java/github/bejayoharen/java-bells/lib-src/libjitsi/src/org/jitsi/impl/neomedia/codec/video/h263p/Packetizer.java", "mask_start_position": 10420, "mask_end_position": 10422, "canonical_solution": "l;", "pre_mask_code": "/*\n * Jitsi, the OpenSource Java VoIP and Instant Messaging client.\n *\n * See terms of license at gnu.org.\n */\npackage org.jitsi.impl.neomedia.codec.video.h263p;\n\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\nimport javax.media.*;\nimport javax.media.format.*;\nimport net.sf.fmj.media.*;\nimport org.jitsi.impl.neomedia.codec.*;\nimport org.jitsi.service.neomedia.codec.*;\n\n/**\n * Packetizes H.263+ encoded data into RTP packets in accord with RFC 4529\n * \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n *\n * @author Sebastien Vincent\n * @author Lyubomir Marinov\n */\npublic class Packetizer extends AbstractPacketizer {\n\n private static final Format[] DEFAULT_OUTPUT_FORMATS = { new VideoFormat(Constants.H263P_RTP) };\n\n /**\n * Maximum payload size without the headers.\n */\n public static final int MAX_PAYLOAD_SIZE = 1024;\n\n /**\n * Name of the plugin.\n */\n private static final String PLUGIN_NAME = \"H263+ Packetizer\";\n\n /**\n * Finds the index in byteStream at which a Picture Start code\n * begins.\n *\n * @param byteStream the H.263+ encoded byte stream\n * @param beginIndex the inclusive index in byteStream at which the\n * search is to begin\n * @param endIndex the exclusive index in byteStream at which the\n * search is to end\n * @return the index in byteStream at which the Picture Start code\n * begins, otherwise, endIndex\n */\n private static int findStartcode(byte[] byteStream, int beginIndex, int endIndex) {\n for (; beginIndex < (endIndex - 3); beginIndex++) {\n if ((byteStream[beginIndex] == 0) && (byteStream[beginIndex + 1] == 0) && ((byteStream[beginIndex + 2] & (byte) 0x80) == -128)) {\n return beginIndex;\n }\n }\n return endIndex;\n }\n\n /**\n * The sequence number of the next RTP packet to be output by this\n * Packetizer.\n */\n private int sequenceNumber = 0;\n\n /**\n * The timeStamp of the RTP packets in which H263+ packets are to be sent.\n */\n private long timeStamp = 0;\n\n /**\n * The list of H263+ \"Start code\" video packets to be sent as payload in RTP\n * packets.\n */\n private final List videoPkts = new LinkedList();\n\n /**\n * Initializes a new Packetizer instance which is to packetize\n * H.263+ encoded data into RTP packets in accord with\n * RFC 4529 \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n */\n public Packetizer() {\n inputFormats = new Format[] { new VideoFormat(Constants.H263P) };\n inputFormat = null;\n outputFormat = null;\n }\n\n @Override\n public synchronized void close() {\n if (opened) {\n videoPkts.clear();\n opened = false;\n super.close();\n }\n }\n\n /**\n * Get the matching output formats for a specific format.\n *\n * @param inputFormat input format\n * @return array for formats matching input format\n */\n private Format[] getMatchingOutputFormats(Format inputFormat) {\n VideoFormat inputVideoFormat = (VideoFormat) inputFormat;\n return new Format[] { new VideoFormat(Constants.H263P_RTP, inputVideoFormat.getSize(), /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, inputVideoFormat.getFrameRate()) };\n }\n\n /**\n * Get codec name.\n *\n * @return codec name\n */\n @Override\n public String getName() {\n return PLUGIN_NAME;\n }\n\n /**\n * Return the list of formats supported at the output.\n * @param inputFormat input Format to determine corresponding\n * output Format/tt>s\n * @return array of formats supported at output\n */\n public Format[] getSupportedOutputFormats(Format inputFormat) {\n if (inputFormat == null)\n return DEFAULT_OUTPUT_FORMATS;\n // mismatch input format\n if (!(inputFormat instanceof VideoFormat) || (AbstractCodec2.matches(inputFormat, inputFormats) == null)) {\n return new Format[0];\n }\n return getMatchingOutputFormats(inputFormat);\n }\n\n /**\n * Open this Packetizer.\n *\n * @throws ResourceUnavailableException if something goes wrong during\n * initialization of the Packetizer.\n */\n @Override\n public synchronized void open() throws ResourceUnavailableException {\n if (!opened) {\n videoPkts.clear();\n sequenceNumber = 0;\n super.open();\n opened = true;\n }\n }\n\n /**\n * Packetizes H.263+ encoded data so that it becomes ready to be sent as the\n * payload of RTP packets.\n *\n * @param data the bytes which contain the H.263+ encoded data to be\n * packetized\n * @param offset the offset of H.263+ encoded data to be packetized begins\n * @param length the length of the H.263+ encoded data starting at offset\n * @return true if at least one RTP packet payload has been\n * packetized i.e. prepared for sending; otherwise, false\n */\n private boolean packetize(byte[] data, int offset, int length) {\n boolean pktAdded = false;\n while (length > 0) {\n boolean isPsc = false;\n int pos = 0;\n int maxPayloadLength = MAX_PAYLOAD_SIZE;\n byte[] pkt = null;\n int payloadLength = 0;\n /* is we are at synchronization point (PSC, GSBC, EOS, EOSBS) */\n if (data.length > 3 && data[offset] == 0x00 && data[offset + 1] == 0x00) {\n isPsc = true;\n pos = 2;\n } else {\n maxPayloadLength -= 2;\n }\n if (length > maxPayloadLength) {\n payloadLength = maxPayloadLength;\n } else {\n payloadLength = length;\n }\n pkt = new byte[payloadLength + (isPsc ? 0 : 2)];\n /* add H263+ payload header */\n /* no VRC and no extra picture header */\n pkt[0] = (byte) (isPsc ? 0x04 : 0x00);\n pkt[1] = 0x00;\n System.arraycopy(data, offset + pos, pkt, 2, payloadLength - pos);\n pktAdded = videoPkts.add(pkt) || pktAdded;\n offset += payloadLength;\n length -= payloadLength;\n }\n return pktAdded;\n }\n\n /**\n * Processes/packetizes a buffer.\n *\n * @param inBuffer input buffer\n * @param outBuffer output buffer\n * @return BUFFER_PROCESSED_OK if buffer has been successfully\n * processed\n */\n @Override\n public int process(Buffer inBuffer, Buffer outBuffer) {\n int inLength = inBuffer.getLength();\n byte[] inData = (byte[]) inBuffer.getData();\n int inOffset = inBuffer.getOffset();\n boolean pktAdded = false;\n if (videoPkts.size() > 0) {\n byte[] pktData = videoPkts.remove(0);\n // Send the packet.\n outBuffer.setData(pktData);\n outBuffer.setLength(pktData.length);\n outBuffer.setOffset(0);\n outBuffer.setTimeStamp(timeStamp);\n outBuffer.setSequenceNumber(sequenceNumber++);\n // If there are other packets, send them as well.\n if (videoPkts.size() > 0) {\n return (BUFFER_PROCESSED_OK | INPUT_BUFFER_NOT_CONSUMED);\n } else {\n // It's the last packet of the current frame so mark it.\n outBuffer.setFlags(outBuffer.getFlags() | Buffer.FLAG_RTP_MARKER);\n return BUFFER_PROCESSED_OK;\n }\n }\n if (isEOM(inBuffer)) {\n propagateEOM(outBuffer);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n if (inBuffer.isDiscard()) {\n outBuffer.setDiscard(true);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n Format inFormat = inBuffer.getFormat();\n if ((inFormat != inputFormat) && !inFormat.matches(inputFormat))\n setInputFormat(inFormat);\n int endIndex = inOffset + inLength;\n int beginIndex = findStartcode(inData, inOffset, endIndex);\n if (beginIndex < endIndex) {\n for (int nextBeginIndex; beginIndex < endIndex; beginIndex = nextBeginIndex + 3) {\n nextBeginIndex = findStartcode(inData, beginIndex + 3, endIndex);\n int length = nextBeginIndex - beginIndex;\n if (length > 0) {\n pktAdded = packetize(inData, beginIndex, length) || pktAdded;\n beginIndex += length;\n }\n }\n }\n timeStamp = inBuffer.getTimeStamp();\n if (pktAdded) {\n return process(inBuffer, outBuffer);\n } else {\n /* first frame is not a synchronization point, discard ?*/\n return BUFFER_PROCESSED_FAILED;\n }\n }\n\n /**\n * Sets the input format.\n *\n * @param in format to set\n * @return format\n */\n @Override\n public Format setInputFormat(Format in) {\n /*\n * Return null if the specified input Format is incompatible with this\n * Packetizer.\n */\n if (!(in instanceof VideoFormat) || null == AbstractCodec2.matches(in, inputFormats))\n return null;\n inputFormat = in;\n return in;\n }\n\n /**\n * Sets the Format in which this Codec is to output media\n * data.\n *\n * @param format the Format in which this Codec is to\n * output media data\n * @return the Format in which this Codec is currently\n * configured to output media data or null if format was\n * found to be incompatible with this Codec\n */\n @Override\n public Format setOutputFormat(Format format) {\n /*\n * Return null if the specified output Format is incompatible with this\n * Packetizer.\n */\n if (!(format instanceof VideoFormat) || (null == AbstractCodec2.matches(format, getMatchingOutputFormats(inputFormat))))\n return null;\n VideoFormat videoFormat = (VideoFormat) format;\n /*\n * A Packetizer translates raw media data in RTP payloads. Consequently,\n * the size of the output is equal to the size of the input.\n */\n Dimension size = nul", "post_mask_code": "\n if (inputFormat != null)\n size = ((VideoFormat) inputFormat).getSize();\n if ((size == null) && format.matches(outputFormat))\n size = ((VideoFormat) outputFormat).getSize();\n outputFormat = new VideoFormat(videoFormat.getEncoding(), size, /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, videoFormat.getFrameRate());\n // Return the outputFormat which is actually set.\n return outputFormat;\n }\n}\n"} {"task_id": "Java_1653", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/bejayoharen/java-bells/lib-src/libjitsi/src/org/jitsi/impl/neomedia/codec/video/h263p/Packetizer.java", "mask_start_position": 3468, "mask_end_position": 3541, "canonical_solution": "@Override\n public String getName() {\n return PLUGIN_NAME;\n }", "pre_mask_code": "/*\n * Jitsi, the OpenSource Java VoIP and Instant Messaging client.\n *\n * See terms of license at gnu.org.\n */\npackage org.jitsi.impl.neomedia.codec.video.h263p;\n\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\nimport javax.media.*;\nimport javax.media.format.*;\nimport net.sf.fmj.media.*;\nimport org.jitsi.impl.neomedia.codec.*;\nimport org.jitsi.service.neomedia.codec.*;\n\n/**\n * Packetizes H.263+ encoded data into RTP packets in accord with RFC 4529\n * \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n *\n * @author Sebastien Vincent\n * @author Lyubomir Marinov\n */\npublic class Packetizer extends AbstractPacketizer {\n\n private static final Format[] DEFAULT_OUTPUT_FORMATS = { new VideoFormat(Constants.H263P_RTP) };\n\n /**\n * Maximum payload size without the headers.\n */\n public static final int MAX_PAYLOAD_SIZE = 1024;\n\n /**\n * Name of the plugin.\n */\n private static final String PLUGIN_NAME = \"H263+ Packetizer\";\n\n /**\n * Finds the index in byteStream at which a Picture Start code\n * begins.\n *\n * @param byteStream the H.263+ encoded byte stream\n * @param beginIndex the inclusive index in byteStream at which the\n * search is to begin\n * @param endIndex the exclusive index in byteStream at which the\n * search is to end\n * @return the index in byteStream at which the Picture Start code\n * begins, otherwise, endIndex\n */\n private static int findStartcode(byte[] byteStream, int beginIndex, int endIndex) {\n for (; beginIndex < (endIndex - 3); beginIndex++) {\n if ((byteStream[beginIndex] == 0) && (byteStream[beginIndex + 1] == 0) && ((byteStream[beginIndex + 2] & (byte) 0x80) == -128)) {\n return beginIndex;\n }\n }\n return endIndex;\n }\n\n /**\n * The sequence number of the next RTP packet to be output by this\n * Packetizer.\n */\n private int sequenceNumber = 0;\n\n /**\n * The timeStamp of the RTP packets in which H263+ packets are to be sent.\n */\n private long timeStamp = 0;\n\n /**\n * The list of H263+ \"Start code\" video packets to be sent as payload in RTP\n * packets.\n */\n private final List videoPkts = new LinkedList();\n\n /**\n * Initializes a new Packetizer instance which is to packetize\n * H.263+ encoded data into RTP packets in accord with\n * RFC 4529 \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n */\n public Packetizer() {\n inputFormats = new Format[] { new VideoFormat(Constants.H263P) };\n inputFormat = null;\n outputFormat = null;\n }\n\n @Override\n public synchronized void close() {\n if (opened) {\n videoPkts.clear();\n opened = false;\n super.close();\n }\n }\n\n /**\n * Get the matching output formats for a specific format.\n *\n * @param inputFormat input format\n * @return array for formats matching input format\n */\n private Format[] getMatchingOutputFormats(Format inputFormat) {\n VideoFormat inputVideoFormat = (VideoFormat) inputFormat;\n return new Format[] { new VideoFormat(Constants.H263P_RTP, inputVideoFormat.getSize(), /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, inputVideoFormat.getFrameRate()) };\n }\n\n /**\n * Get codec name.\n *\n * @return codec name\n */\n ", "post_mask_code": "\n\n /**\n * Return the list of formats supported at the output.\n * @param inputFormat input Format to determine corresponding\n * output Format/tt>s\n * @return array of formats supported at output\n */\n public Format[] getSupportedOutputFormats(Format inputFormat) {\n if (inputFormat == null)\n return DEFAULT_OUTPUT_FORMATS;\n // mismatch input format\n if (!(inputFormat instanceof VideoFormat) || (AbstractCodec2.matches(inputFormat, inputFormats) == null)) {\n return new Format[0];\n }\n return getMatchingOutputFormats(inputFormat);\n }\n\n /**\n * Open this Packetizer.\n *\n * @throws ResourceUnavailableException if something goes wrong during\n * initialization of the Packetizer.\n */\n @Override\n public synchronized void open() throws ResourceUnavailableException {\n if (!opened) {\n videoPkts.clear();\n sequenceNumber = 0;\n super.open();\n opened = true;\n }\n }\n\n /**\n * Packetizes H.263+ encoded data so that it becomes ready to be sent as the\n * payload of RTP packets.\n *\n * @param data the bytes which contain the H.263+ encoded data to be\n * packetized\n * @param offset the offset of H.263+ encoded data to be packetized begins\n * @param length the length of the H.263+ encoded data starting at offset\n * @return true if at least one RTP packet payload has been\n * packetized i.e. prepared for sending; otherwise, false\n */\n private boolean packetize(byte[] data, int offset, int length) {\n boolean pktAdded = false;\n while (length > 0) {\n boolean isPsc = false;\n int pos = 0;\n int maxPayloadLength = MAX_PAYLOAD_SIZE;\n byte[] pkt = null;\n int payloadLength = 0;\n /* is we are at synchronization point (PSC, GSBC, EOS, EOSBS) */\n if (data.length > 3 && data[offset] == 0x00 && data[offset + 1] == 0x00) {\n isPsc = true;\n pos = 2;\n } else {\n maxPayloadLength -= 2;\n }\n if (length > maxPayloadLength) {\n payloadLength = maxPayloadLength;\n } else {\n payloadLength = length;\n }\n pkt = new byte[payloadLength + (isPsc ? 0 : 2)];\n /* add H263+ payload header */\n /* no VRC and no extra picture header */\n pkt[0] = (byte) (isPsc ? 0x04 : 0x00);\n pkt[1] = 0x00;\n System.arraycopy(data, offset + pos, pkt, 2, payloadLength - pos);\n pktAdded = videoPkts.add(pkt) || pktAdded;\n offset += payloadLength;\n length -= payloadLength;\n }\n return pktAdded;\n }\n\n /**\n * Processes/packetizes a buffer.\n *\n * @param inBuffer input buffer\n * @param outBuffer output buffer\n * @return BUFFER_PROCESSED_OK if buffer has been successfully\n * processed\n */\n @Override\n public int process(Buffer inBuffer, Buffer outBuffer) {\n int inLength = inBuffer.getLength();\n byte[] inData = (byte[]) inBuffer.getData();\n int inOffset = inBuffer.getOffset();\n boolean pktAdded = false;\n if (videoPkts.size() > 0) {\n byte[] pktData = videoPkts.remove(0);\n // Send the packet.\n outBuffer.setData(pktData);\n outBuffer.setLength(pktData.length);\n outBuffer.setOffset(0);\n outBuffer.setTimeStamp(timeStamp);\n outBuffer.setSequenceNumber(sequenceNumber++);\n // If there are other packets, send them as well.\n if (videoPkts.size() > 0) {\n return (BUFFER_PROCESSED_OK | INPUT_BUFFER_NOT_CONSUMED);\n } else {\n // It's the last packet of the current frame so mark it.\n outBuffer.setFlags(outBuffer.getFlags() | Buffer.FLAG_RTP_MARKER);\n return BUFFER_PROCESSED_OK;\n }\n }\n if (isEOM(inBuffer)) {\n propagateEOM(outBuffer);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n if (inBuffer.isDiscard()) {\n outBuffer.setDiscard(true);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n Format inFormat = inBuffer.getFormat();\n if ((inFormat != inputFormat) && !inFormat.matches(inputFormat))\n setInputFormat(inFormat);\n int endIndex = inOffset + inLength;\n int beginIndex = findStartcode(inData, inOffset, endIndex);\n if (beginIndex < endIndex) {\n for (int nextBeginIndex; beginIndex < endIndex; beginIndex = nextBeginIndex + 3) {\n nextBeginIndex = findStartcode(inData, beginIndex + 3, endIndex);\n int length = nextBeginIndex - beginIndex;\n if (length > 0) {\n pktAdded = packetize(inData, beginIndex, length) || pktAdded;\n beginIndex += length;\n }\n }\n }\n timeStamp = inBuffer.getTimeStamp();\n if (pktAdded) {\n return process(inBuffer, outBuffer);\n } else {\n /* first frame is not a synchronization point, discard ?*/\n return BUFFER_PROCESSED_FAILED;\n }\n }\n\n /**\n * Sets the input format.\n *\n * @param in format to set\n * @return format\n */\n @Override\n public Format setInputFormat(Format in) {\n /*\n * Return null if the specified input Format is incompatible with this\n * Packetizer.\n */\n if (!(in instanceof VideoFormat) || null == AbstractCodec2.matches(in, inputFormats))\n return null;\n inputFormat = in;\n return in;\n }\n\n /**\n * Sets the Format in which this Codec is to output media\n * data.\n *\n * @param format the Format in which this Codec is to\n * output media data\n * @return the Format in which this Codec is currently\n * configured to output media data or null if format was\n * found to be incompatible with this Codec\n */\n @Override\n public Format setOutputFormat(Format format) {\n /*\n * Return null if the specified output Format is incompatible with this\n * Packetizer.\n */\n if (!(format instanceof VideoFormat) || (null == AbstractCodec2.matches(format, getMatchingOutputFormats(inputFormat))))\n return null;\n VideoFormat videoFormat = (VideoFormat) format;\n /*\n * A Packetizer translates raw media data in RTP payloads. Consequently,\n * the size of the output is equal to the size of the input.\n */\n Dimension size = null;\n if (inputFormat != null)\n size = ((VideoFormat) inputFormat).getSize();\n if ((size == null) && format.matches(outputFormat))\n size = ((VideoFormat) outputFormat).getSize();\n outputFormat = new VideoFormat(videoFormat.getEncoding(), size, /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, videoFormat.getFrameRate());\n // Return the outputFormat which is actually set.\n return outputFormat;\n }\n}\n"} {"task_id": "Java_1654", "language": "Java", "task_type": "if_statement", "source_file": "java/github/bejayoharen/java-bells/lib-src/libjitsi/src/org/jitsi/impl/neomedia/codec/video/h263p/Packetizer.java", "mask_start_position": 7777, "mask_end_position": 7915, "canonical_solution": "if (inBuffer.isDiscard()) {\n outBuffer.setDiscard(true);\n reset();\n return BUFFER_PROCESSED_OK;\n }", "pre_mask_code": "/*\n * Jitsi, the OpenSource Java VoIP and Instant Messaging client.\n *\n * See terms of license at gnu.org.\n */\npackage org.jitsi.impl.neomedia.codec.video.h263p;\n\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\nimport javax.media.*;\nimport javax.media.format.*;\nimport net.sf.fmj.media.*;\nimport org.jitsi.impl.neomedia.codec.*;\nimport org.jitsi.service.neomedia.codec.*;\n\n/**\n * Packetizes H.263+ encoded data into RTP packets in accord with RFC 4529\n * \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n *\n * @author Sebastien Vincent\n * @author Lyubomir Marinov\n */\npublic class Packetizer extends AbstractPacketizer {\n\n private static final Format[] DEFAULT_OUTPUT_FORMATS = { new VideoFormat(Constants.H263P_RTP) };\n\n /**\n * Maximum payload size without the headers.\n */\n public static final int MAX_PAYLOAD_SIZE = 1024;\n\n /**\n * Name of the plugin.\n */\n private static final String PLUGIN_NAME = \"H263+ Packetizer\";\n\n /**\n * Finds the index in byteStream at which a Picture Start code\n * begins.\n *\n * @param byteStream the H.263+ encoded byte stream\n * @param beginIndex the inclusive index in byteStream at which the\n * search is to begin\n * @param endIndex the exclusive index in byteStream at which the\n * search is to end\n * @return the index in byteStream at which the Picture Start code\n * begins, otherwise, endIndex\n */\n private static int findStartcode(byte[] byteStream, int beginIndex, int endIndex) {\n for (; beginIndex < (endIndex - 3); beginIndex++) {\n if ((byteStream[beginIndex] == 0) && (byteStream[beginIndex + 1] == 0) && ((byteStream[beginIndex + 2] & (byte) 0x80) == -128)) {\n return beginIndex;\n }\n }\n return endIndex;\n }\n\n /**\n * The sequence number of the next RTP packet to be output by this\n * Packetizer.\n */\n private int sequenceNumber = 0;\n\n /**\n * The timeStamp of the RTP packets in which H263+ packets are to be sent.\n */\n private long timeStamp = 0;\n\n /**\n * The list of H263+ \"Start code\" video packets to be sent as payload in RTP\n * packets.\n */\n private final List videoPkts = new LinkedList();\n\n /**\n * Initializes a new Packetizer instance which is to packetize\n * H.263+ encoded data into RTP packets in accord with\n * RFC 4529 \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n */\n public Packetizer() {\n inputFormats = new Format[] { new VideoFormat(Constants.H263P) };\n inputFormat = null;\n outputFormat = null;\n }\n\n @Override\n public synchronized void close() {\n if (opened) {\n videoPkts.clear();\n opened = false;\n super.close();\n }\n }\n\n /**\n * Get the matching output formats for a specific format.\n *\n * @param inputFormat input format\n * @return array for formats matching input format\n */\n private Format[] getMatchingOutputFormats(Format inputFormat) {\n VideoFormat inputVideoFormat = (VideoFormat) inputFormat;\n return new Format[] { new VideoFormat(Constants.H263P_RTP, inputVideoFormat.getSize(), /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, inputVideoFormat.getFrameRate()) };\n }\n\n /**\n * Get codec name.\n *\n * @return codec name\n */\n @Override\n public String getName() {\n return PLUGIN_NAME;\n }\n\n /**\n * Return the list of formats supported at the output.\n * @param inputFormat input Format to determine corresponding\n * output Format/tt>s\n * @return array of formats supported at output\n */\n public Format[] getSupportedOutputFormats(Format inputFormat) {\n if (inputFormat == null)\n return DEFAULT_OUTPUT_FORMATS;\n // mismatch input format\n if (!(inputFormat instanceof VideoFormat) || (AbstractCodec2.matches(inputFormat, inputFormats) == null)) {\n return new Format[0];\n }\n return getMatchingOutputFormats(inputFormat);\n }\n\n /**\n * Open this Packetizer.\n *\n * @throws ResourceUnavailableException if something goes wrong during\n * initialization of the Packetizer.\n */\n @Override\n public synchronized void open() throws ResourceUnavailableException {\n if (!opened) {\n videoPkts.clear();\n sequenceNumber = 0;\n super.open();\n opened = true;\n }\n }\n\n /**\n * Packetizes H.263+ encoded data so that it becomes ready to be sent as the\n * payload of RTP packets.\n *\n * @param data the bytes which contain the H.263+ encoded data to be\n * packetized\n * @param offset the offset of H.263+ encoded data to be packetized begins\n * @param length the length of the H.263+ encoded data starting at offset\n * @return true if at least one RTP packet payload has been\n * packetized i.e. prepared for sending; otherwise, false\n */\n private boolean packetize(byte[] data, int offset, int length) {\n boolean pktAdded = false;\n while (length > 0) {\n boolean isPsc = false;\n int pos = 0;\n int maxPayloadLength = MAX_PAYLOAD_SIZE;\n byte[] pkt = null;\n int payloadLength = 0;\n /* is we are at synchronization point (PSC, GSBC, EOS, EOSBS) */\n if (data.length > 3 && data[offset] == 0x00 && data[offset + 1] == 0x00) {\n isPsc = true;\n pos = 2;\n } else {\n maxPayloadLength -= 2;\n }\n if (length > maxPayloadLength) {\n payloadLength = maxPayloadLength;\n } else {\n payloadLength = length;\n }\n pkt = new byte[payloadLength + (isPsc ? 0 : 2)];\n /* add H263+ payload header */\n /* no VRC and no extra picture header */\n pkt[0] = (byte) (isPsc ? 0x04 : 0x00);\n pkt[1] = 0x00;\n System.arraycopy(data, offset + pos, pkt, 2, payloadLength - pos);\n pktAdded = videoPkts.add(pkt) || pktAdded;\n offset += payloadLength;\n length -= payloadLength;\n }\n return pktAdded;\n }\n\n /**\n * Processes/packetizes a buffer.\n *\n * @param inBuffer input buffer\n * @param outBuffer output buffer\n * @return BUFFER_PROCESSED_OK if buffer has been successfully\n * processed\n */\n @Override\n public int process(Buffer inBuffer, Buffer outBuffer) {\n int inLength = inBuffer.getLength();\n byte[] inData = (byte[]) inBuffer.getData();\n int inOffset = inBuffer.getOffset();\n boolean pktAdded = false;\n if (videoPkts.size() > 0) {\n byte[] pktData = videoPkts.remove(0);\n // Send the packet.\n outBuffer.setData(pktData);\n outBuffer.setLength(pktData.length);\n outBuffer.setOffset(0);\n outBuffer.setTimeStamp(timeStamp);\n outBuffer.setSequenceNumber(sequenceNumber++);\n // If there are other packets, send them as well.\n if (videoPkts.size() > 0) {\n return (BUFFER_PROCESSED_OK | INPUT_BUFFER_NOT_CONSUMED);\n } else {\n // It's the last packet of the current frame so mark it.\n outBuffer.setFlags(outBuffer.getFlags() | Buffer.FLAG_RTP_MARKER);\n return BUFFER_PROCESSED_OK;\n }\n }\n if (isEOM(inBuffer)) {\n propagateEOM(outBuffer);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n ", "post_mask_code": "\n Format inFormat = inBuffer.getFormat();\n if ((inFormat != inputFormat) && !inFormat.matches(inputFormat))\n setInputFormat(inFormat);\n int endIndex = inOffset + inLength;\n int beginIndex = findStartcode(inData, inOffset, endIndex);\n if (beginIndex < endIndex) {\n for (int nextBeginIndex; beginIndex < endIndex; beginIndex = nextBeginIndex + 3) {\n nextBeginIndex = findStartcode(inData, beginIndex + 3, endIndex);\n int length = nextBeginIndex - beginIndex;\n if (length > 0) {\n pktAdded = packetize(inData, beginIndex, length) || pktAdded;\n beginIndex += length;\n }\n }\n }\n timeStamp = inBuffer.getTimeStamp();\n if (pktAdded) {\n return process(inBuffer, outBuffer);\n } else {\n /* first frame is not a synchronization point, discard ?*/\n return BUFFER_PROCESSED_FAILED;\n }\n }\n\n /**\n * Sets the input format.\n *\n * @param in format to set\n * @return format\n */\n @Override\n public Format setInputFormat(Format in) {\n /*\n * Return null if the specified input Format is incompatible with this\n * Packetizer.\n */\n if (!(in instanceof VideoFormat) || null == AbstractCodec2.matches(in, inputFormats))\n return null;\n inputFormat = in;\n return in;\n }\n\n /**\n * Sets the Format in which this Codec is to output media\n * data.\n *\n * @param format the Format in which this Codec is to\n * output media data\n * @return the Format in which this Codec is currently\n * configured to output media data or null if format was\n * found to be incompatible with this Codec\n */\n @Override\n public Format setOutputFormat(Format format) {\n /*\n * Return null if the specified output Format is incompatible with this\n * Packetizer.\n */\n if (!(format instanceof VideoFormat) || (null == AbstractCodec2.matches(format, getMatchingOutputFormats(inputFormat))))\n return null;\n VideoFormat videoFormat = (VideoFormat) format;\n /*\n * A Packetizer translates raw media data in RTP payloads. Consequently,\n * the size of the output is equal to the size of the input.\n */\n Dimension size = null;\n if (inputFormat != null)\n size = ((VideoFormat) inputFormat).getSize();\n if ((size == null) && format.matches(outputFormat))\n size = ((VideoFormat) outputFormat).getSize();\n outputFormat = new VideoFormat(videoFormat.getEncoding(), size, /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, videoFormat.getFrameRate());\n // Return the outputFormat which is actually set.\n return outputFormat;\n }\n}\n"} {"task_id": "Java_1655", "language": "Java", "task_type": "for_statement", "source_file": "java/github/bejayoharen/java-bells/lib-src/libjitsi/src/org/jitsi/impl/neomedia/codec/video/h263p/Packetizer.java", "mask_start_position": 8236, "mask_end_position": 8648, "canonical_solution": "for (int nextBeginIndex; beginIndex < endIndex; beginIndex = nextBeginIndex + 3) {\n nextBeginIndex = findStartcode(inData, beginIndex + 3, endIndex);\n int length = nextBeginIndex - beginIndex;\n if (length > 0) {\n pktAdded = packetize(inData, beginIndex, length) || pktAdded;\n beginIndex += length;\n }\n }", "pre_mask_code": "/*\n * Jitsi, the OpenSource Java VoIP and Instant Messaging client.\n *\n * See terms of license at gnu.org.\n */\npackage org.jitsi.impl.neomedia.codec.video.h263p;\n\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\nimport javax.media.*;\nimport javax.media.format.*;\nimport net.sf.fmj.media.*;\nimport org.jitsi.impl.neomedia.codec.*;\nimport org.jitsi.service.neomedia.codec.*;\n\n/**\n * Packetizes H.263+ encoded data into RTP packets in accord with RFC 4529\n * \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n *\n * @author Sebastien Vincent\n * @author Lyubomir Marinov\n */\npublic class Packetizer extends AbstractPacketizer {\n\n private static final Format[] DEFAULT_OUTPUT_FORMATS = { new VideoFormat(Constants.H263P_RTP) };\n\n /**\n * Maximum payload size without the headers.\n */\n public static final int MAX_PAYLOAD_SIZE = 1024;\n\n /**\n * Name of the plugin.\n */\n private static final String PLUGIN_NAME = \"H263+ Packetizer\";\n\n /**\n * Finds the index in byteStream at which a Picture Start code\n * begins.\n *\n * @param byteStream the H.263+ encoded byte stream\n * @param beginIndex the inclusive index in byteStream at which the\n * search is to begin\n * @param endIndex the exclusive index in byteStream at which the\n * search is to end\n * @return the index in byteStream at which the Picture Start code\n * begins, otherwise, endIndex\n */\n private static int findStartcode(byte[] byteStream, int beginIndex, int endIndex) {\n for (; beginIndex < (endIndex - 3); beginIndex++) {\n if ((byteStream[beginIndex] == 0) && (byteStream[beginIndex + 1] == 0) && ((byteStream[beginIndex + 2] & (byte) 0x80) == -128)) {\n return beginIndex;\n }\n }\n return endIndex;\n }\n\n /**\n * The sequence number of the next RTP packet to be output by this\n * Packetizer.\n */\n private int sequenceNumber = 0;\n\n /**\n * The timeStamp of the RTP packets in which H263+ packets are to be sent.\n */\n private long timeStamp = 0;\n\n /**\n * The list of H263+ \"Start code\" video packets to be sent as payload in RTP\n * packets.\n */\n private final List videoPkts = new LinkedList();\n\n /**\n * Initializes a new Packetizer instance which is to packetize\n * H.263+ encoded data into RTP packets in accord with\n * RFC 4529 \"RTP Payload Format for ITU-T Rec. H.263 Video\".\n */\n public Packetizer() {\n inputFormats = new Format[] { new VideoFormat(Constants.H263P) };\n inputFormat = null;\n outputFormat = null;\n }\n\n @Override\n public synchronized void close() {\n if (opened) {\n videoPkts.clear();\n opened = false;\n super.close();\n }\n }\n\n /**\n * Get the matching output formats for a specific format.\n *\n * @param inputFormat input format\n * @return array for formats matching input format\n */\n private Format[] getMatchingOutputFormats(Format inputFormat) {\n VideoFormat inputVideoFormat = (VideoFormat) inputFormat;\n return new Format[] { new VideoFormat(Constants.H263P_RTP, inputVideoFormat.getSize(), /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, inputVideoFormat.getFrameRate()) };\n }\n\n /**\n * Get codec name.\n *\n * @return codec name\n */\n @Override\n public String getName() {\n return PLUGIN_NAME;\n }\n\n /**\n * Return the list of formats supported at the output.\n * @param inputFormat input Format to determine corresponding\n * output Format/tt>s\n * @return array of formats supported at output\n */\n public Format[] getSupportedOutputFormats(Format inputFormat) {\n if (inputFormat == null)\n return DEFAULT_OUTPUT_FORMATS;\n // mismatch input format\n if (!(inputFormat instanceof VideoFormat) || (AbstractCodec2.matches(inputFormat, inputFormats) == null)) {\n return new Format[0];\n }\n return getMatchingOutputFormats(inputFormat);\n }\n\n /**\n * Open this Packetizer.\n *\n * @throws ResourceUnavailableException if something goes wrong during\n * initialization of the Packetizer.\n */\n @Override\n public synchronized void open() throws ResourceUnavailableException {\n if (!opened) {\n videoPkts.clear();\n sequenceNumber = 0;\n super.open();\n opened = true;\n }\n }\n\n /**\n * Packetizes H.263+ encoded data so that it becomes ready to be sent as the\n * payload of RTP packets.\n *\n * @param data the bytes which contain the H.263+ encoded data to be\n * packetized\n * @param offset the offset of H.263+ encoded data to be packetized begins\n * @param length the length of the H.263+ encoded data starting at offset\n * @return true if at least one RTP packet payload has been\n * packetized i.e. prepared for sending; otherwise, false\n */\n private boolean packetize(byte[] data, int offset, int length) {\n boolean pktAdded = false;\n while (length > 0) {\n boolean isPsc = false;\n int pos = 0;\n int maxPayloadLength = MAX_PAYLOAD_SIZE;\n byte[] pkt = null;\n int payloadLength = 0;\n /* is we are at synchronization point (PSC, GSBC, EOS, EOSBS) */\n if (data.length > 3 && data[offset] == 0x00 && data[offset + 1] == 0x00) {\n isPsc = true;\n pos = 2;\n } else {\n maxPayloadLength -= 2;\n }\n if (length > maxPayloadLength) {\n payloadLength = maxPayloadLength;\n } else {\n payloadLength = length;\n }\n pkt = new byte[payloadLength + (isPsc ? 0 : 2)];\n /* add H263+ payload header */\n /* no VRC and no extra picture header */\n pkt[0] = (byte) (isPsc ? 0x04 : 0x00);\n pkt[1] = 0x00;\n System.arraycopy(data, offset + pos, pkt, 2, payloadLength - pos);\n pktAdded = videoPkts.add(pkt) || pktAdded;\n offset += payloadLength;\n length -= payloadLength;\n }\n return pktAdded;\n }\n\n /**\n * Processes/packetizes a buffer.\n *\n * @param inBuffer input buffer\n * @param outBuffer output buffer\n * @return BUFFER_PROCESSED_OK if buffer has been successfully\n * processed\n */\n @Override\n public int process(Buffer inBuffer, Buffer outBuffer) {\n int inLength = inBuffer.getLength();\n byte[] inData = (byte[]) inBuffer.getData();\n int inOffset = inBuffer.getOffset();\n boolean pktAdded = false;\n if (videoPkts.size() > 0) {\n byte[] pktData = videoPkts.remove(0);\n // Send the packet.\n outBuffer.setData(pktData);\n outBuffer.setLength(pktData.length);\n outBuffer.setOffset(0);\n outBuffer.setTimeStamp(timeStamp);\n outBuffer.setSequenceNumber(sequenceNumber++);\n // If there are other packets, send them as well.\n if (videoPkts.size() > 0) {\n return (BUFFER_PROCESSED_OK | INPUT_BUFFER_NOT_CONSUMED);\n } else {\n // It's the last packet of the current frame so mark it.\n outBuffer.setFlags(outBuffer.getFlags() | Buffer.FLAG_RTP_MARKER);\n return BUFFER_PROCESSED_OK;\n }\n }\n if (isEOM(inBuffer)) {\n propagateEOM(outBuffer);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n if (inBuffer.isDiscard()) {\n outBuffer.setDiscard(true);\n reset();\n return BUFFER_PROCESSED_OK;\n }\n Format inFormat = inBuffer.getFormat();\n if ((inFormat != inputFormat) && !inFormat.matches(inputFormat))\n setInputFormat(inFormat);\n int endIndex = inOffset + inLength;\n int beginIndex = findStartcode(inData, inOffset, endIndex);\n if (beginIndex < endIndex) {\n ", "post_mask_code": "\n }\n timeStamp = inBuffer.getTimeStamp();\n if (pktAdded) {\n return process(inBuffer, outBuffer);\n } else {\n /* first frame is not a synchronization point, discard ?*/\n return BUFFER_PROCESSED_FAILED;\n }\n }\n\n /**\n * Sets the input format.\n *\n * @param in format to set\n * @return format\n */\n @Override\n public Format setInputFormat(Format in) {\n /*\n * Return null if the specified input Format is incompatible with this\n * Packetizer.\n */\n if (!(in instanceof VideoFormat) || null == AbstractCodec2.matches(in, inputFormats))\n return null;\n inputFormat = in;\n return in;\n }\n\n /**\n * Sets the Format in which this Codec is to output media\n * data.\n *\n * @param format the Format in which this Codec is to\n * output media data\n * @return the Format in which this Codec is currently\n * configured to output media data or null if format was\n * found to be incompatible with this Codec\n */\n @Override\n public Format setOutputFormat(Format format) {\n /*\n * Return null if the specified output Format is incompatible with this\n * Packetizer.\n */\n if (!(format instanceof VideoFormat) || (null == AbstractCodec2.matches(format, getMatchingOutputFormats(inputFormat))))\n return null;\n VideoFormat videoFormat = (VideoFormat) format;\n /*\n * A Packetizer translates raw media data in RTP payloads. Consequently,\n * the size of the output is equal to the size of the input.\n */\n Dimension size = null;\n if (inputFormat != null)\n size = ((VideoFormat) inputFormat).getSize();\n if ((size == null) && format.matches(outputFormat))\n size = ((VideoFormat) outputFormat).getSize();\n outputFormat = new VideoFormat(videoFormat.getEncoding(), size, /* maxDataLength */\n Format.NOT_SPECIFIED, Format.byteArray, videoFormat.getFrameRate());\n // Return the outputFormat which is actually set.\n return outputFormat;\n }\n}\n"} {"task_id": "Java_1656", "language": "Java", "task_type": "method_signature", "source_file": "java/github/opennetworkinglab/onos/core/api/src/main/java/org/onosproject/net/behaviour/protection/ProtectionConfig.java", "mask_start_position": 2834, "mask_end_position": 2890, "canonical_solution": "public ProtectionConfig fingerprint(String fingerprint) ", "pre_mask_code": "package org.onosproject.net.behaviour.protection;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.onosproject.net.behaviour.protection.ProtectedTransportEndpointDescription.buildDescription;\nimport java.util.List;\nimport org.onosproject.net.DeviceId;\nimport org.onosproject.net.config.BaseConfig;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\n// FIXME Move this to Protection handling Intent related package?\n/**\n * Config object for protection end-point.\n *

\n * Contains equivalent of {@link ProtectedTransportEndpointDescription}.\n */\npublic class ProtectionConfig extends BaseConfig {\n\n /**\n * {@value #CONFIG_KEY} : a netcfg ConfigKey for {@link ProtectionConfig}.\n */\n public static final String CONFIG_KEY = \"protection\";\n\n /**\n * JSON key for paths.\n *

\n * Value is list of {@link TransportEndpointDescription} in JSON.\n */\n private static final String PATHS = \"paths\";\n\n /**\n * JSON key for Peer {@link DeviceId}.\n */\n private static final String PEER = \"peer\";\n\n private static final String FINGERPRINT = \"fingerprint\";\n\n @Override\n public boolean isValid() {\n return isString(PEER, FieldPresence.MANDATORY) && isString(FINGERPRINT, FieldPresence.MANDATORY) && hasField(PATHS);\n }\n\n /**\n * Returns List of underlying transport entity endpoints in priority order.\n *\n * @return the transport entity endpoint descriptions\n */\n public List paths() {\n return getList(PATHS, jsonStr -> decode(jsonStr, TransportEndpointDescription.class));\n }\n\n /**\n * Sets the List of underlying transport entity endpoints in priority order.\n *\n * @param paths the transport entity endpoint descriptions\n * @return self\n */\n public ProtectionConfig paths(List paths) {\n setList(PATHS, elm -> encode(elm, TransportEndpointDescription.class).toString(), paths);\n return this;\n }\n\n /**\n * Returns DeviceId of remote peer of this endpoint.\n *\n * @return the peer\n */\n public DeviceId peer() {\n return DeviceId.deviceId(get(PEER, \"\"));\n }\n\n /**\n * Sets the DeviceId of remote peer of this endpoint.\n *\n * @param peer DeviceId\n * @return self\n */\n public ProtectionConfig peer(DeviceId peer) {\n setOrClear(PEER, peer.toString());\n return this;\n }\n\n /**\n * Returns fingerprint to identify this protected transport entity.\n *\n * @return the fingerprint\n */\n public String fingerprint() {\n return get(FINGERPRINT, \"\");\n }\n\n /**\n * Sets the fingerprint to identify this protected transport entity.\n *\n * @param fingerprint the fingerprint\n * @return self\n */\n ", "post_mask_code": "{\n setOrClear(FINGERPRINT, checkNotNull(fingerprint));\n return this;\n }\n\n /**\n * Returns equivalent of this Config as {@link ProtectedTransportEndpointDescription}.\n *\n * @return {@link ProtectedTransportEndpointDescription}\n */\n public ProtectedTransportEndpointDescription asDescription() {\n return buildDescription(paths(), peer(), fingerprint());\n }\n\n @Override\n public String toString() {\n return object.toString();\n }\n\n /**\n * Create a {@link ProtectionConfig}.\n *

\n * Note: created instance needs to be initialized by #init(..) before using.\n */\n public ProtectionConfig() {\n super();\n }\n\n /**\n * Create a {@link ProtectionConfig} for specified Device.\n *

\n * Note: created instance is not bound to NetworkConfigService,\n * cannot use {@link #apply()}. Must be passed to the service\n * using NetworkConfigService#applyConfig\n *\n * @param did DeviceId\n */\n public ProtectionConfig(DeviceId did) {\n ObjectMapper mapper = new ObjectMapper();\n init(did, CONFIG_KEY, mapper.createObjectNode(), mapper, null);\n }\n}\n"} {"task_id": "Java_1657", "language": "Java", "task_type": "method_body", "source_file": "java/github/opennetworkinglab/onos/core/api/src/main/java/org/onosproject/net/behaviour/protection/ProtectionConfig.java", "mask_start_position": 2626, "mask_end_position": 2670, "canonical_solution": "{\n return get(FINGERPRINT, \"\");\n }", "pre_mask_code": "package org.onosproject.net.behaviour.protection;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.onosproject.net.behaviour.protection.ProtectedTransportEndpointDescription.buildDescription;\nimport java.util.List;\nimport org.onosproject.net.DeviceId;\nimport org.onosproject.net.config.BaseConfig;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\n// FIXME Move this to Protection handling Intent related package?\n/**\n * Config object for protection end-point.\n *

\n * Contains equivalent of {@link ProtectedTransportEndpointDescription}.\n */\npublic class ProtectionConfig extends BaseConfig {\n\n /**\n * {@value #CONFIG_KEY} : a netcfg ConfigKey for {@link ProtectionConfig}.\n */\n public static final String CONFIG_KEY = \"protection\";\n\n /**\n * JSON key for paths.\n *

\n * Value is list of {@link TransportEndpointDescription} in JSON.\n */\n private static final String PATHS = \"paths\";\n\n /**\n * JSON key for Peer {@link DeviceId}.\n */\n private static final String PEER = \"peer\";\n\n private static final String FINGERPRINT = \"fingerprint\";\n\n @Override\n public boolean isValid() {\n return isString(PEER, FieldPresence.MANDATORY) && isString(FINGERPRINT, FieldPresence.MANDATORY) && hasField(PATHS);\n }\n\n /**\n * Returns List of underlying transport entity endpoints in priority order.\n *\n * @return the transport entity endpoint descriptions\n */\n public List paths() {\n return getList(PATHS, jsonStr -> decode(jsonStr, TransportEndpointDescription.class));\n }\n\n /**\n * Sets the List of underlying transport entity endpoints in priority order.\n *\n * @param paths the transport entity endpoint descriptions\n * @return self\n */\n public ProtectionConfig paths(List paths) {\n setList(PATHS, elm -> encode(elm, TransportEndpointDescription.class).toString(), paths);\n return this;\n }\n\n /**\n * Returns DeviceId of remote peer of this endpoint.\n *\n * @return the peer\n */\n public DeviceId peer() {\n return DeviceId.deviceId(get(PEER, \"\"));\n }\n\n /**\n * Sets the DeviceId of remote peer of this endpoint.\n *\n * @param peer DeviceId\n * @return self\n */\n public ProtectionConfig peer(DeviceId peer) {\n setOrClear(PEER, peer.toString());\n return this;\n }\n\n /**\n * Returns fingerprint to identify this protected transport entity.\n *\n * @return the fingerprint\n */\n public String fingerprint() ", "post_mask_code": "\n\n /**\n * Sets the fingerprint to identify this protected transport entity.\n *\n * @param fingerprint the fingerprint\n * @return self\n */\n public ProtectionConfig fingerprint(String fingerprint) {\n setOrClear(FINGERPRINT, checkNotNull(fingerprint));\n return this;\n }\n\n /**\n * Returns equivalent of this Config as {@link ProtectedTransportEndpointDescription}.\n *\n * @return {@link ProtectedTransportEndpointDescription}\n */\n public ProtectedTransportEndpointDescription asDescription() {\n return buildDescription(paths(), peer(), fingerprint());\n }\n\n @Override\n public String toString() {\n return object.toString();\n }\n\n /**\n * Create a {@link ProtectionConfig}.\n *

\n * Note: created instance needs to be initialized by #init(..) before using.\n */\n public ProtectionConfig() {\n super();\n }\n\n /**\n * Create a {@link ProtectionConfig} for specified Device.\n *

\n * Note: created instance is not bound to NetworkConfigService,\n * cannot use {@link #apply()}. Must be passed to the service\n * using NetworkConfigService#applyConfig\n *\n * @param did DeviceId\n */\n public ProtectionConfig(DeviceId did) {\n ObjectMapper mapper = new ObjectMapper();\n init(did, CONFIG_KEY, mapper.createObjectNode(), mapper, null);\n }\n}\n"} {"task_id": "Java_1658", "language": "Java", "task_type": "single_line", "source_file": "java/github/opennetworkinglab/onos/core/api/src/main/java/org/onosproject/net/behaviour/protection/ProtectionConfig.java", "mask_start_position": 1966, "mask_end_position": 2000, "canonical_solution": "ription.class).toString(), paths);", "pre_mask_code": "package org.onosproject.net.behaviour.protection;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.onosproject.net.behaviour.protection.ProtectedTransportEndpointDescription.buildDescription;\nimport java.util.List;\nimport org.onosproject.net.DeviceId;\nimport org.onosproject.net.config.BaseConfig;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\n// FIXME Move this to Protection handling Intent related package?\n/**\n * Config object for protection end-point.\n *

\n * Contains equivalent of {@link ProtectedTransportEndpointDescription}.\n */\npublic class ProtectionConfig extends BaseConfig {\n\n /**\n * {@value #CONFIG_KEY} : a netcfg ConfigKey for {@link ProtectionConfig}.\n */\n public static final String CONFIG_KEY = \"protection\";\n\n /**\n * JSON key for paths.\n *

\n * Value is list of {@link TransportEndpointDescription} in JSON.\n */\n private static final String PATHS = \"paths\";\n\n /**\n * JSON key for Peer {@link DeviceId}.\n */\n private static final String PEER = \"peer\";\n\n private static final String FINGERPRINT = \"fingerprint\";\n\n @Override\n public boolean isValid() {\n return isString(PEER, FieldPresence.MANDATORY) && isString(FINGERPRINT, FieldPresence.MANDATORY) && hasField(PATHS);\n }\n\n /**\n * Returns List of underlying transport entity endpoints in priority order.\n *\n * @return the transport entity endpoint descriptions\n */\n public List paths() {\n return getList(PATHS, jsonStr -> decode(jsonStr, TransportEndpointDescription.class));\n }\n\n /**\n * Sets the List of underlying transport entity endpoints in priority order.\n *\n * @param paths the transport entity endpoint descriptions\n * @return self\n */\n public ProtectionConfig paths(List paths) {\n setList(PATHS, elm -> encode(elm, TransportEndpointDesc", "post_mask_code": "\n return this;\n }\n\n /**\n * Returns DeviceId of remote peer of this endpoint.\n *\n * @return the peer\n */\n public DeviceId peer() {\n return DeviceId.deviceId(get(PEER, \"\"));\n }\n\n /**\n * Sets the DeviceId of remote peer of this endpoint.\n *\n * @param peer DeviceId\n * @return self\n */\n public ProtectionConfig peer(DeviceId peer) {\n setOrClear(PEER, peer.toString());\n return this;\n }\n\n /**\n * Returns fingerprint to identify this protected transport entity.\n *\n * @return the fingerprint\n */\n public String fingerprint() {\n return get(FINGERPRINT, \"\");\n }\n\n /**\n * Sets the fingerprint to identify this protected transport entity.\n *\n * @param fingerprint the fingerprint\n * @return self\n */\n public ProtectionConfig fingerprint(String fingerprint) {\n setOrClear(FINGERPRINT, checkNotNull(fingerprint));\n return this;\n }\n\n /**\n * Returns equivalent of this Config as {@link ProtectedTransportEndpointDescription}.\n *\n * @return {@link ProtectedTransportEndpointDescription}\n */\n public ProtectedTransportEndpointDescription asDescription() {\n return buildDescription(paths(), peer(), fingerprint());\n }\n\n @Override\n public String toString() {\n return object.toString();\n }\n\n /**\n * Create a {@link ProtectionConfig}.\n *

\n * Note: created instance needs to be initialized by #init(..) before using.\n */\n public ProtectionConfig() {\n super();\n }\n\n /**\n * Create a {@link ProtectionConfig} for specified Device.\n *

\n * Note: created instance is not bound to NetworkConfigService,\n * cannot use {@link #apply()}. Must be passed to the service\n * using NetworkConfigService#applyConfig\n *\n * @param did DeviceId\n */\n public ProtectionConfig(DeviceId did) {\n ObjectMapper mapper = new ObjectMapper();\n init(did, CONFIG_KEY, mapper.createObjectNode(), mapper, null);\n }\n}\n"} {"task_id": "Java_1659", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/opennetworkinglab/onos/core/api/src/main/java/org/onosproject/net/behaviour/protection/ProtectionConfig.java", "mask_start_position": 2598, "mask_end_position": 2670, "canonical_solution": "public String fingerprint() {\n return get(FINGERPRINT, \"\");\n }", "pre_mask_code": "package org.onosproject.net.behaviour.protection;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.onosproject.net.behaviour.protection.ProtectedTransportEndpointDescription.buildDescription;\nimport java.util.List;\nimport org.onosproject.net.DeviceId;\nimport org.onosproject.net.config.BaseConfig;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\n// FIXME Move this to Protection handling Intent related package?\n/**\n * Config object for protection end-point.\n *

\n * Contains equivalent of {@link ProtectedTransportEndpointDescription}.\n */\npublic class ProtectionConfig extends BaseConfig {\n\n /**\n * {@value #CONFIG_KEY} : a netcfg ConfigKey for {@link ProtectionConfig}.\n */\n public static final String CONFIG_KEY = \"protection\";\n\n /**\n * JSON key for paths.\n *

\n * Value is list of {@link TransportEndpointDescription} in JSON.\n */\n private static final String PATHS = \"paths\";\n\n /**\n * JSON key for Peer {@link DeviceId}.\n */\n private static final String PEER = \"peer\";\n\n private static final String FINGERPRINT = \"fingerprint\";\n\n @Override\n public boolean isValid() {\n return isString(PEER, FieldPresence.MANDATORY) && isString(FINGERPRINT, FieldPresence.MANDATORY) && hasField(PATHS);\n }\n\n /**\n * Returns List of underlying transport entity endpoints in priority order.\n *\n * @return the transport entity endpoint descriptions\n */\n public List paths() {\n return getList(PATHS, jsonStr -> decode(jsonStr, TransportEndpointDescription.class));\n }\n\n /**\n * Sets the List of underlying transport entity endpoints in priority order.\n *\n * @param paths the transport entity endpoint descriptions\n * @return self\n */\n public ProtectionConfig paths(List paths) {\n setList(PATHS, elm -> encode(elm, TransportEndpointDescription.class).toString(), paths);\n return this;\n }\n\n /**\n * Returns DeviceId of remote peer of this endpoint.\n *\n * @return the peer\n */\n public DeviceId peer() {\n return DeviceId.deviceId(get(PEER, \"\"));\n }\n\n /**\n * Sets the DeviceId of remote peer of this endpoint.\n *\n * @param peer DeviceId\n * @return self\n */\n public ProtectionConfig peer(DeviceId peer) {\n setOrClear(PEER, peer.toString());\n return this;\n }\n\n /**\n * Returns fingerprint to identify this protected transport entity.\n *\n * @return the fingerprint\n */\n ", "post_mask_code": "\n\n /**\n * Sets the fingerprint to identify this protected transport entity.\n *\n * @param fingerprint the fingerprint\n * @return self\n */\n public ProtectionConfig fingerprint(String fingerprint) {\n setOrClear(FINGERPRINT, checkNotNull(fingerprint));\n return this;\n }\n\n /**\n * Returns equivalent of this Config as {@link ProtectedTransportEndpointDescription}.\n *\n * @return {@link ProtectedTransportEndpointDescription}\n */\n public ProtectedTransportEndpointDescription asDescription() {\n return buildDescription(paths(), peer(), fingerprint());\n }\n\n @Override\n public String toString() {\n return object.toString();\n }\n\n /**\n * Create a {@link ProtectionConfig}.\n *

\n * Note: created instance needs to be initialized by #init(..) before using.\n */\n public ProtectionConfig() {\n super();\n }\n\n /**\n * Create a {@link ProtectionConfig} for specified Device.\n *

\n * Note: created instance is not bound to NetworkConfigService,\n * cannot use {@link #apply()}. Must be passed to the service\n * using NetworkConfigService#applyConfig\n *\n * @param did DeviceId\n */\n public ProtectionConfig(DeviceId did) {\n ObjectMapper mapper = new ObjectMapper();\n init(did, CONFIG_KEY, mapper.createObjectNode(), mapper, null);\n }\n}\n"} {"task_id": "Java_1660", "language": "Java", "task_type": "method_signature", "source_file": "java/github/bonitasoft/bonita-studio/bundles/plugins/org.bonitasoft.studio.contract/src/org/bonitasoft/studio/contract/ui/property/input/ContractInputController.java", "mask_start_position": 8546, "mask_end_position": 8679, "canonical_solution": "private Collection constraintsReferencingSingleInput(final Contract contract, final ContractInput contractInput) ", "pre_mask_code": "package org.bonitasoft.studio.contract.ui.property.input;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.bonitasoft.studio.common.emf.tools.ModelHelper.getAllElementOfTypeIn;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.Collection;\nimport java.util.List;\nimport org.bonitasoft.studio.common.NamingUtils;\nimport org.bonitasoft.studio.common.emf.tools.ModelHelper;\nimport org.bonitasoft.studio.common.jface.BonitaErrorDialog;\nimport org.bonitasoft.studio.common.jface.FileActionDialog;\nimport org.bonitasoft.studio.common.jface.databinding.CustomEMFEditObservables;\nimport org.bonitasoft.studio.common.log.BonitaStudioLog;\nimport org.bonitasoft.studio.contract.core.refactoring.RefactorContractInputOperation;\nimport org.bonitasoft.studio.contract.i18n.Messages;\nimport org.bonitasoft.studio.contract.ui.property.IViewerController;\nimport org.bonitasoft.studio.model.process.Contract;\nimport org.bonitasoft.studio.model.process.ContractConstraint;\nimport org.bonitasoft.studio.model.process.ContractContainer;\nimport org.bonitasoft.studio.model.process.ContractInput;\nimport org.bonitasoft.studio.model.process.ContractInputType;\nimport org.bonitasoft.studio.model.process.ProcessFactory;\nimport org.bonitasoft.studio.model.process.ProcessPackage;\nimport org.bonitasoft.studio.refactoring.core.RefactoringOperationType;\nimport org.bonitasoft.studio.refactoring.core.script.GroovyScriptRefactoringOperationFactory;\nimport org.bonitasoft.studio.refactoring.core.script.IScriptRefactoringOperationFactory;\nimport org.eclipse.core.databinding.observable.value.IObservableValue;\nimport org.eclipse.emf.common.command.CompoundCommand;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.EReference;\nimport org.eclipse.emf.edit.command.DeleteCommand;\nimport org.eclipse.emf.transaction.TransactionalEditingDomain;\nimport org.eclipse.emf.transaction.util.TransactionUtil;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.ColumnViewer;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Widget;\nimport org.eclipse.ui.progress.IProgressService;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n\n/**\n * @author Romain Bioteau\n */\npublic class ContractInputController implements IViewerController {\n\n private static final int NAME_COLUMN_INDEX = 0;\n\n private final IProgressService progressService;\n\n class EditNameRunnable implements Runnable {\n\n private final ColumnViewer viewer;\n\n private final ContractInput input;\n\n public EditNameRunnable(final ColumnViewer viewer, final ContractInput input) {\n this.viewer = viewer;\n this.input = input;\n }\n\n /*\n * (non-Javadoc)\n * @see java.lang.Runnable#run()\n */\n @Override\n public void run() {\n if (viewer != null && viewer.getControl() != null && !viewer.getControl().isDisposed()) {\n viewer.setSelection(new StructuredSelection(input), false);\n final Widget item = viewer.testFindItem(input);\n if (item != null && !item.isDisposed()) {\n viewer.reveal(input);\n viewer.editElement(input, NAME_COLUMN_INDEX);\n }\n }\n }\n }\n\n public ContractInputController(final IProgressService progressService) {\n this.progressService = progressService;\n }\n\n @Override\n public ContractInput add(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final Contract contract = (Contract) contractObservable.getValue();\n final ContractInput defaultInput = createDefaultInput(contract);\n final EObject targetContainer = targetContainer(parentInput, contract);\n CustomEMFEditObservables.observeList(targetContainer, inputContainerFeature(targetContainer)).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private EObject targetContainer(final ContractInput parentInput, final Contract contract) {\n return parentInput != null ? parentInput.eContainer() : contract;\n }\n\n public ContractInput addChildInput(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n if (selection.isEmpty()) {\n return null;\n }\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final ContractInput defaultInput = createDefaultInput(ModelHelper.getFirstContainerOfType(parentInput, Contract.class));\n CustomEMFEditObservables.observeList(parentInput, ProcessPackage.Literals.CONTRACT_INPUT__INPUTS).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private ContractInput createDefaultInput(final Contract contract) {\n final ContractInput contractInput = ProcessFactory.eINSTANCE.createContractInput();\n contractInput.setName(defaultContractInputName(contract));\n contractInput.setType(ContractInputType.TEXT);\n contractInput.setMapping(ProcessFactory.eINSTANCE.createContractInputMapping());\n return contractInput;\n }\n\n private String defaultContractInputName(final Contract contract) {\n return NamingUtils.generateNewName(newHashSet(transform(getAllElementOfTypeIn(contract, ContractInput.class), toInputName())), \"input\", 1);\n }\n\n private Function toInputName() {\n return new Function() {\n\n @Override\n public String apply(final ContractInput input) {\n return input.getName();\n }\n };\n }\n\n @Override\n public void remove(final ColumnViewer viewer) {\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final List selectedInput = selection.toList();\n Contract contract = (Contract) contractObservable.getValue();\n if (openConfirmation(selectedInput)) {\n final RefactorContractInputOperation refactorOperation = newRefactorOperation(contract);\n final TransactionalEditingDomain editingDomain = editingDomain(contract);\n refactorOperation.setEditingDomain(editingDomain);\n refactorOperation.setAskConfirmation(shouldAskConfirmation());\n final CompoundCommand compoundCommand = refactorOperation.getCompoundCommand();\n for (final Object input : selectedInput) {\n final ContractInput contractInput = (ContractInput) input;\n contract = ModelHelper.getFirstContainerOfType(contractInput, Contract.class);\n // Parent input has been removed in current selection\n if (contract == null) {\n continue;\n }\n refactorOperation.addItemToRefactor(null, contractInput);\n compoundCommand.append(DeleteCommand.create(editingDomain, contractInput));\n final Collection constraintsReferencingInput = constraintsReferencingSingleInput(contract, contractInput);\n if (!constraintsReferencingInput.isEmpty()) {\n compoundCommand.append(DeleteCommand.create(editingDomain, constraintsReferencingInput));\n }\n }\n try {\n if (refactorOperation.canExecute()) {\n progressService.run(true, true, refactorOperation);\n }\n } catch (final InvocationTargetException | InterruptedException e) {\n BonitaStudioLog.error(\"Failed to remove contract input.\", e);\n openErrorDialog(e);\n }\n }\n }\n\n protected boolean shouldAskConfirmation() {\n return true;\n }\n\n ", "post_mask_code": "{\n return newHashSet(filter(contract.getConstraints(), havingInputReference(contractInput.getName())));\n }\n\n private Predicate havingInputReference(final String inputName) {\n return new Predicate() {\n\n @Override\n public boolean apply(final ContractConstraint constraint) {\n return constraint.getInputNames().contains(inputName) && constraint.getInputNames().size() == 1;\n }\n };\n }\n\n protected TransactionalEditingDomain editingDomain(final Contract contract) {\n return TransactionUtil.getEditingDomain(contract);\n }\n\n protected RefactorContractInputOperation newRefactorOperation(final Contract contract) {\n return new RefactorContractInputOperation(ModelHelper.getFirstContainerOfType(contract, ContractContainer.class), scriptRefactoringOperationFactory(), RefactoringOperationType.REMOVE);\n }\n\n protected IScriptRefactoringOperationFactory scriptRefactoringOperationFactory() {\n return new GroovyScriptRefactoringOperationFactory();\n }\n\n private EReference inputContainerFeature(final EObject eContainer) {\n return eContainer instanceof ContractInput ? ProcessPackage.Literals.CONTRACT_INPUT__INPUTS : ProcessPackage.Literals.CONTRACT__INPUTS;\n }\n\n protected void openErrorDialog(final Throwable e) {\n if (!FileActionDialog.getDisablePopup()) {\n new BonitaErrorDialog(Display.getDefault().getActiveShell(), Messages.removeInputErrorTitle, Messages.removeInputErrorMsg, e).open();\n }\n }\n\n protected boolean openConfirmation(final List selectedInput) {\n final StringBuilder message = new StringBuilder(Messages.removeInputConfirmationMessagePart1);\n for (final Object input : selectedInput) {\n message.append(SWT.CR);\n message.append(\"- \" + ((ContractInput) input).getName());\n message.append(SWT.CR);\n message.append(Messages.removeInputConfirmationMessagesPart2);\n }\n return FileActionDialog.getDisablePopup() ? true : MessageDialog.openConfirm(Display.getDefault().getActiveShell(), Messages.removeInputConfirmationTitle, message.toString());\n }\n\n @Override\n public void moveUp(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n\n @Override\n public void moveDown(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n}\n"} {"task_id": "Java_1661", "language": "Java", "task_type": "method_body", "source_file": "java/github/bonitasoft/bonita-studio/bundles/plugins/org.bonitasoft.studio.contract/src/org/bonitasoft/studio/contract/ui/property/input/ContractInputController.java", "mask_start_position": 10054, "mask_end_position": 10268, "canonical_solution": "{\n if (!FileActionDialog.getDisablePopup()) {\n new BonitaErrorDialog(Display.getDefault().getActiveShell(), Messages.removeInputErrorTitle, Messages.removeInputErrorMsg, e).open();\n }\n }", "pre_mask_code": "package org.bonitasoft.studio.contract.ui.property.input;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.bonitasoft.studio.common.emf.tools.ModelHelper.getAllElementOfTypeIn;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.Collection;\nimport java.util.List;\nimport org.bonitasoft.studio.common.NamingUtils;\nimport org.bonitasoft.studio.common.emf.tools.ModelHelper;\nimport org.bonitasoft.studio.common.jface.BonitaErrorDialog;\nimport org.bonitasoft.studio.common.jface.FileActionDialog;\nimport org.bonitasoft.studio.common.jface.databinding.CustomEMFEditObservables;\nimport org.bonitasoft.studio.common.log.BonitaStudioLog;\nimport org.bonitasoft.studio.contract.core.refactoring.RefactorContractInputOperation;\nimport org.bonitasoft.studio.contract.i18n.Messages;\nimport org.bonitasoft.studio.contract.ui.property.IViewerController;\nimport org.bonitasoft.studio.model.process.Contract;\nimport org.bonitasoft.studio.model.process.ContractConstraint;\nimport org.bonitasoft.studio.model.process.ContractContainer;\nimport org.bonitasoft.studio.model.process.ContractInput;\nimport org.bonitasoft.studio.model.process.ContractInputType;\nimport org.bonitasoft.studio.model.process.ProcessFactory;\nimport org.bonitasoft.studio.model.process.ProcessPackage;\nimport org.bonitasoft.studio.refactoring.core.RefactoringOperationType;\nimport org.bonitasoft.studio.refactoring.core.script.GroovyScriptRefactoringOperationFactory;\nimport org.bonitasoft.studio.refactoring.core.script.IScriptRefactoringOperationFactory;\nimport org.eclipse.core.databinding.observable.value.IObservableValue;\nimport org.eclipse.emf.common.command.CompoundCommand;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.EReference;\nimport org.eclipse.emf.edit.command.DeleteCommand;\nimport org.eclipse.emf.transaction.TransactionalEditingDomain;\nimport org.eclipse.emf.transaction.util.TransactionUtil;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.ColumnViewer;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Widget;\nimport org.eclipse.ui.progress.IProgressService;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n\n/**\n * @author Romain Bioteau\n */\npublic class ContractInputController implements IViewerController {\n\n private static final int NAME_COLUMN_INDEX = 0;\n\n private final IProgressService progressService;\n\n class EditNameRunnable implements Runnable {\n\n private final ColumnViewer viewer;\n\n private final ContractInput input;\n\n public EditNameRunnable(final ColumnViewer viewer, final ContractInput input) {\n this.viewer = viewer;\n this.input = input;\n }\n\n /*\n * (non-Javadoc)\n * @see java.lang.Runnable#run()\n */\n @Override\n public void run() {\n if (viewer != null && viewer.getControl() != null && !viewer.getControl().isDisposed()) {\n viewer.setSelection(new StructuredSelection(input), false);\n final Widget item = viewer.testFindItem(input);\n if (item != null && !item.isDisposed()) {\n viewer.reveal(input);\n viewer.editElement(input, NAME_COLUMN_INDEX);\n }\n }\n }\n }\n\n public ContractInputController(final IProgressService progressService) {\n this.progressService = progressService;\n }\n\n @Override\n public ContractInput add(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final Contract contract = (Contract) contractObservable.getValue();\n final ContractInput defaultInput = createDefaultInput(contract);\n final EObject targetContainer = targetContainer(parentInput, contract);\n CustomEMFEditObservables.observeList(targetContainer, inputContainerFeature(targetContainer)).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private EObject targetContainer(final ContractInput parentInput, final Contract contract) {\n return parentInput != null ? parentInput.eContainer() : contract;\n }\n\n public ContractInput addChildInput(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n if (selection.isEmpty()) {\n return null;\n }\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final ContractInput defaultInput = createDefaultInput(ModelHelper.getFirstContainerOfType(parentInput, Contract.class));\n CustomEMFEditObservables.observeList(parentInput, ProcessPackage.Literals.CONTRACT_INPUT__INPUTS).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private ContractInput createDefaultInput(final Contract contract) {\n final ContractInput contractInput = ProcessFactory.eINSTANCE.createContractInput();\n contractInput.setName(defaultContractInputName(contract));\n contractInput.setType(ContractInputType.TEXT);\n contractInput.setMapping(ProcessFactory.eINSTANCE.createContractInputMapping());\n return contractInput;\n }\n\n private String defaultContractInputName(final Contract contract) {\n return NamingUtils.generateNewName(newHashSet(transform(getAllElementOfTypeIn(contract, ContractInput.class), toInputName())), \"input\", 1);\n }\n\n private Function toInputName() {\n return new Function() {\n\n @Override\n public String apply(final ContractInput input) {\n return input.getName();\n }\n };\n }\n\n @Override\n public void remove(final ColumnViewer viewer) {\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final List selectedInput = selection.toList();\n Contract contract = (Contract) contractObservable.getValue();\n if (openConfirmation(selectedInput)) {\n final RefactorContractInputOperation refactorOperation = newRefactorOperation(contract);\n final TransactionalEditingDomain editingDomain = editingDomain(contract);\n refactorOperation.setEditingDomain(editingDomain);\n refactorOperation.setAskConfirmation(shouldAskConfirmation());\n final CompoundCommand compoundCommand = refactorOperation.getCompoundCommand();\n for (final Object input : selectedInput) {\n final ContractInput contractInput = (ContractInput) input;\n contract = ModelHelper.getFirstContainerOfType(contractInput, Contract.class);\n // Parent input has been removed in current selection\n if (contract == null) {\n continue;\n }\n refactorOperation.addItemToRefactor(null, contractInput);\n compoundCommand.append(DeleteCommand.create(editingDomain, contractInput));\n final Collection constraintsReferencingInput = constraintsReferencingSingleInput(contract, contractInput);\n if (!constraintsReferencingInput.isEmpty()) {\n compoundCommand.append(DeleteCommand.create(editingDomain, constraintsReferencingInput));\n }\n }\n try {\n if (refactorOperation.canExecute()) {\n progressService.run(true, true, refactorOperation);\n }\n } catch (final InvocationTargetException | InterruptedException e) {\n BonitaStudioLog.error(\"Failed to remove contract input.\", e);\n openErrorDialog(e);\n }\n }\n }\n\n protected boolean shouldAskConfirmation() {\n return true;\n }\n\n private Collection constraintsReferencingSingleInput(final Contract contract, final ContractInput contractInput) {\n return newHashSet(filter(contract.getConstraints(), havingInputReference(contractInput.getName())));\n }\n\n private Predicate havingInputReference(final String inputName) {\n return new Predicate() {\n\n @Override\n public boolean apply(final ContractConstraint constraint) {\n return constraint.getInputNames().contains(inputName) && constraint.getInputNames().size() == 1;\n }\n };\n }\n\n protected TransactionalEditingDomain editingDomain(final Contract contract) {\n return TransactionUtil.getEditingDomain(contract);\n }\n\n protected RefactorContractInputOperation newRefactorOperation(final Contract contract) {\n return new RefactorContractInputOperation(ModelHelper.getFirstContainerOfType(contract, ContractContainer.class), scriptRefactoringOperationFactory(), RefactoringOperationType.REMOVE);\n }\n\n protected IScriptRefactoringOperationFactory scriptRefactoringOperationFactory() {\n return new GroovyScriptRefactoringOperationFactory();\n }\n\n private EReference inputContainerFeature(final EObject eContainer) {\n return eContainer instanceof ContractInput ? ProcessPackage.Literals.CONTRACT_INPUT__INPUTS : ProcessPackage.Literals.CONTRACT__INPUTS;\n }\n\n protected void openErrorDialog(final Throwable e) ", "post_mask_code": "\n\n protected boolean openConfirmation(final List selectedInput) {\n final StringBuilder message = new StringBuilder(Messages.removeInputConfirmationMessagePart1);\n for (final Object input : selectedInput) {\n message.append(SWT.CR);\n message.append(\"- \" + ((ContractInput) input).getName());\n message.append(SWT.CR);\n message.append(Messages.removeInputConfirmationMessagesPart2);\n }\n return FileActionDialog.getDisablePopup() ? true : MessageDialog.openConfirm(Display.getDefault().getActiveShell(), Messages.removeInputConfirmationTitle, message.toString());\n }\n\n @Override\n public void moveUp(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n\n @Override\n public void moveDown(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n}\n"} {"task_id": "Java_1662", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/bonitasoft/bonita-studio/bundles/plugins/org.bonitasoft.studio.contract/src/org/bonitasoft/studio/contract/ui/property/input/ContractInputController.java", "mask_start_position": 5503, "mask_end_position": 5662, "canonical_solution": "\n final ContractInput contractInput = ProcessFactory.eINSTANCE.createContractInput();\n contractInput.setName(defaultContractInputName(contract));", "pre_mask_code": "package org.bonitasoft.studio.contract.ui.property.input;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.bonitasoft.studio.common.emf.tools.ModelHelper.getAllElementOfTypeIn;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.Collection;\nimport java.util.List;\nimport org.bonitasoft.studio.common.NamingUtils;\nimport org.bonitasoft.studio.common.emf.tools.ModelHelper;\nimport org.bonitasoft.studio.common.jface.BonitaErrorDialog;\nimport org.bonitasoft.studio.common.jface.FileActionDialog;\nimport org.bonitasoft.studio.common.jface.databinding.CustomEMFEditObservables;\nimport org.bonitasoft.studio.common.log.BonitaStudioLog;\nimport org.bonitasoft.studio.contract.core.refactoring.RefactorContractInputOperation;\nimport org.bonitasoft.studio.contract.i18n.Messages;\nimport org.bonitasoft.studio.contract.ui.property.IViewerController;\nimport org.bonitasoft.studio.model.process.Contract;\nimport org.bonitasoft.studio.model.process.ContractConstraint;\nimport org.bonitasoft.studio.model.process.ContractContainer;\nimport org.bonitasoft.studio.model.process.ContractInput;\nimport org.bonitasoft.studio.model.process.ContractInputType;\nimport org.bonitasoft.studio.model.process.ProcessFactory;\nimport org.bonitasoft.studio.model.process.ProcessPackage;\nimport org.bonitasoft.studio.refactoring.core.RefactoringOperationType;\nimport org.bonitasoft.studio.refactoring.core.script.GroovyScriptRefactoringOperationFactory;\nimport org.bonitasoft.studio.refactoring.core.script.IScriptRefactoringOperationFactory;\nimport org.eclipse.core.databinding.observable.value.IObservableValue;\nimport org.eclipse.emf.common.command.CompoundCommand;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.EReference;\nimport org.eclipse.emf.edit.command.DeleteCommand;\nimport org.eclipse.emf.transaction.TransactionalEditingDomain;\nimport org.eclipse.emf.transaction.util.TransactionUtil;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.ColumnViewer;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Widget;\nimport org.eclipse.ui.progress.IProgressService;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n\n/**\n * @author Romain Bioteau\n */\npublic class ContractInputController implements IViewerController {\n\n private static final int NAME_COLUMN_INDEX = 0;\n\n private final IProgressService progressService;\n\n class EditNameRunnable implements Runnable {\n\n private final ColumnViewer viewer;\n\n private final ContractInput input;\n\n public EditNameRunnable(final ColumnViewer viewer, final ContractInput input) {\n this.viewer = viewer;\n this.input = input;\n }\n\n /*\n * (non-Javadoc)\n * @see java.lang.Runnable#run()\n */\n @Override\n public void run() {\n if (viewer != null && viewer.getControl() != null && !viewer.getControl().isDisposed()) {\n viewer.setSelection(new StructuredSelection(input), false);\n final Widget item = viewer.testFindItem(input);\n if (item != null && !item.isDisposed()) {\n viewer.reveal(input);\n viewer.editElement(input, NAME_COLUMN_INDEX);\n }\n }\n }\n }\n\n public ContractInputController(final IProgressService progressService) {\n this.progressService = progressService;\n }\n\n @Override\n public ContractInput add(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final Contract contract = (Contract) contractObservable.getValue();\n final ContractInput defaultInput = createDefaultInput(contract);\n final EObject targetContainer = targetContainer(parentInput, contract);\n CustomEMFEditObservables.observeList(targetContainer, inputContainerFeature(targetContainer)).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private EObject targetContainer(final ContractInput parentInput, final Contract contract) {\n return parentInput != null ? parentInput.eContainer() : contract;\n }\n\n public ContractInput addChildInput(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n if (selection.isEmpty()) {\n return null;\n }\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final ContractInput defaultInput = createDefaultInput(ModelHelper.getFirstContainerOfType(parentInput, Contract.class));\n CustomEMFEditObservables.observeList(parentInput, ProcessPackage.Literals.CONTRACT_INPUT__INPUTS).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private ContractInput createDefaultInput(final Contract contract) {", "post_mask_code": "\n contractInput.setType(ContractInputType.TEXT);\n contractInput.setMapping(ProcessFactory.eINSTANCE.createContractInputMapping());\n return contractInput;\n }\n\n private String defaultContractInputName(final Contract contract) {\n return NamingUtils.generateNewName(newHashSet(transform(getAllElementOfTypeIn(contract, ContractInput.class), toInputName())), \"input\", 1);\n }\n\n private Function toInputName() {\n return new Function() {\n\n @Override\n public String apply(final ContractInput input) {\n return input.getName();\n }\n };\n }\n\n @Override\n public void remove(final ColumnViewer viewer) {\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final List selectedInput = selection.toList();\n Contract contract = (Contract) contractObservable.getValue();\n if (openConfirmation(selectedInput)) {\n final RefactorContractInputOperation refactorOperation = newRefactorOperation(contract);\n final TransactionalEditingDomain editingDomain = editingDomain(contract);\n refactorOperation.setEditingDomain(editingDomain);\n refactorOperation.setAskConfirmation(shouldAskConfirmation());\n final CompoundCommand compoundCommand = refactorOperation.getCompoundCommand();\n for (final Object input : selectedInput) {\n final ContractInput contractInput = (ContractInput) input;\n contract = ModelHelper.getFirstContainerOfType(contractInput, Contract.class);\n // Parent input has been removed in current selection\n if (contract == null) {\n continue;\n }\n refactorOperation.addItemToRefactor(null, contractInput);\n compoundCommand.append(DeleteCommand.create(editingDomain, contractInput));\n final Collection constraintsReferencingInput = constraintsReferencingSingleInput(contract, contractInput);\n if (!constraintsReferencingInput.isEmpty()) {\n compoundCommand.append(DeleteCommand.create(editingDomain, constraintsReferencingInput));\n }\n }\n try {\n if (refactorOperation.canExecute()) {\n progressService.run(true, true, refactorOperation);\n }\n } catch (final InvocationTargetException | InterruptedException e) {\n BonitaStudioLog.error(\"Failed to remove contract input.\", e);\n openErrorDialog(e);\n }\n }\n }\n\n protected boolean shouldAskConfirmation() {\n return true;\n }\n\n private Collection constraintsReferencingSingleInput(final Contract contract, final ContractInput contractInput) {\n return newHashSet(filter(contract.getConstraints(), havingInputReference(contractInput.getName())));\n }\n\n private Predicate havingInputReference(final String inputName) {\n return new Predicate() {\n\n @Override\n public boolean apply(final ContractConstraint constraint) {\n return constraint.getInputNames().contains(inputName) && constraint.getInputNames().size() == 1;\n }\n };\n }\n\n protected TransactionalEditingDomain editingDomain(final Contract contract) {\n return TransactionUtil.getEditingDomain(contract);\n }\n\n protected RefactorContractInputOperation newRefactorOperation(final Contract contract) {\n return new RefactorContractInputOperation(ModelHelper.getFirstContainerOfType(contract, ContractContainer.class), scriptRefactoringOperationFactory(), RefactoringOperationType.REMOVE);\n }\n\n protected IScriptRefactoringOperationFactory scriptRefactoringOperationFactory() {\n return new GroovyScriptRefactoringOperationFactory();\n }\n\n private EReference inputContainerFeature(final EObject eContainer) {\n return eContainer instanceof ContractInput ? ProcessPackage.Literals.CONTRACT_INPUT__INPUTS : ProcessPackage.Literals.CONTRACT__INPUTS;\n }\n\n protected void openErrorDialog(final Throwable e) {\n if (!FileActionDialog.getDisablePopup()) {\n new BonitaErrorDialog(Display.getDefault().getActiveShell(), Messages.removeInputErrorTitle, Messages.removeInputErrorMsg, e).open();\n }\n }\n\n protected boolean openConfirmation(final List selectedInput) {\n final StringBuilder message = new StringBuilder(Messages.removeInputConfirmationMessagePart1);\n for (final Object input : selectedInput) {\n message.append(SWT.CR);\n message.append(\"- \" + ((ContractInput) input).getName());\n message.append(SWT.CR);\n message.append(Messages.removeInputConfirmationMessagesPart2);\n }\n return FileActionDialog.getDisablePopup() ? true : MessageDialog.openConfirm(Display.getDefault().getActiveShell(), Messages.removeInputConfirmationTitle, message.toString());\n }\n\n @Override\n public void moveUp(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n\n @Override\n public void moveDown(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n}\n"} {"task_id": "Java_1663", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/bonitasoft/bonita-studio/bundles/plugins/org.bonitasoft.studio.contract/src/org/bonitasoft/studio/contract/ui/property/input/ContractInputController.java", "mask_start_position": 5671, "mask_end_position": 5806, "canonical_solution": "contractInput.setType(ContractInputType.TEXT);\n contractInput.setMapping(ProcessFactory.eINSTANCE.createContractInputMapping());", "pre_mask_code": "package org.bonitasoft.studio.contract.ui.property.input;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.bonitasoft.studio.common.emf.tools.ModelHelper.getAllElementOfTypeIn;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.Collection;\nimport java.util.List;\nimport org.bonitasoft.studio.common.NamingUtils;\nimport org.bonitasoft.studio.common.emf.tools.ModelHelper;\nimport org.bonitasoft.studio.common.jface.BonitaErrorDialog;\nimport org.bonitasoft.studio.common.jface.FileActionDialog;\nimport org.bonitasoft.studio.common.jface.databinding.CustomEMFEditObservables;\nimport org.bonitasoft.studio.common.log.BonitaStudioLog;\nimport org.bonitasoft.studio.contract.core.refactoring.RefactorContractInputOperation;\nimport org.bonitasoft.studio.contract.i18n.Messages;\nimport org.bonitasoft.studio.contract.ui.property.IViewerController;\nimport org.bonitasoft.studio.model.process.Contract;\nimport org.bonitasoft.studio.model.process.ContractConstraint;\nimport org.bonitasoft.studio.model.process.ContractContainer;\nimport org.bonitasoft.studio.model.process.ContractInput;\nimport org.bonitasoft.studio.model.process.ContractInputType;\nimport org.bonitasoft.studio.model.process.ProcessFactory;\nimport org.bonitasoft.studio.model.process.ProcessPackage;\nimport org.bonitasoft.studio.refactoring.core.RefactoringOperationType;\nimport org.bonitasoft.studio.refactoring.core.script.GroovyScriptRefactoringOperationFactory;\nimport org.bonitasoft.studio.refactoring.core.script.IScriptRefactoringOperationFactory;\nimport org.eclipse.core.databinding.observable.value.IObservableValue;\nimport org.eclipse.emf.common.command.CompoundCommand;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.EReference;\nimport org.eclipse.emf.edit.command.DeleteCommand;\nimport org.eclipse.emf.transaction.TransactionalEditingDomain;\nimport org.eclipse.emf.transaction.util.TransactionUtil;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.ColumnViewer;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Widget;\nimport org.eclipse.ui.progress.IProgressService;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n\n/**\n * @author Romain Bioteau\n */\npublic class ContractInputController implements IViewerController {\n\n private static final int NAME_COLUMN_INDEX = 0;\n\n private final IProgressService progressService;\n\n class EditNameRunnable implements Runnable {\n\n private final ColumnViewer viewer;\n\n private final ContractInput input;\n\n public EditNameRunnable(final ColumnViewer viewer, final ContractInput input) {\n this.viewer = viewer;\n this.input = input;\n }\n\n /*\n * (non-Javadoc)\n * @see java.lang.Runnable#run()\n */\n @Override\n public void run() {\n if (viewer != null && viewer.getControl() != null && !viewer.getControl().isDisposed()) {\n viewer.setSelection(new StructuredSelection(input), false);\n final Widget item = viewer.testFindItem(input);\n if (item != null && !item.isDisposed()) {\n viewer.reveal(input);\n viewer.editElement(input, NAME_COLUMN_INDEX);\n }\n }\n }\n }\n\n public ContractInputController(final IProgressService progressService) {\n this.progressService = progressService;\n }\n\n @Override\n public ContractInput add(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final Contract contract = (Contract) contractObservable.getValue();\n final ContractInput defaultInput = createDefaultInput(contract);\n final EObject targetContainer = targetContainer(parentInput, contract);\n CustomEMFEditObservables.observeList(targetContainer, inputContainerFeature(targetContainer)).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private EObject targetContainer(final ContractInput parentInput, final Contract contract) {\n return parentInput != null ? parentInput.eContainer() : contract;\n }\n\n public ContractInput addChildInput(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n if (selection.isEmpty()) {\n return null;\n }\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final ContractInput defaultInput = createDefaultInput(ModelHelper.getFirstContainerOfType(parentInput, Contract.class));\n CustomEMFEditObservables.observeList(parentInput, ProcessPackage.Literals.CONTRACT_INPUT__INPUTS).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private ContractInput createDefaultInput(final Contract contract) {\n final ContractInput contractInput = ProcessFactory.eINSTANCE.createContractInput();\n contractInput.setName(defaultContractInputName(contract));\n ", "post_mask_code": "\n return contractInput;\n }\n\n private String defaultContractInputName(final Contract contract) {\n return NamingUtils.generateNewName(newHashSet(transform(getAllElementOfTypeIn(contract, ContractInput.class), toInputName())), \"input\", 1);\n }\n\n private Function toInputName() {\n return new Function() {\n\n @Override\n public String apply(final ContractInput input) {\n return input.getName();\n }\n };\n }\n\n @Override\n public void remove(final ColumnViewer viewer) {\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final List selectedInput = selection.toList();\n Contract contract = (Contract) contractObservable.getValue();\n if (openConfirmation(selectedInput)) {\n final RefactorContractInputOperation refactorOperation = newRefactorOperation(contract);\n final TransactionalEditingDomain editingDomain = editingDomain(contract);\n refactorOperation.setEditingDomain(editingDomain);\n refactorOperation.setAskConfirmation(shouldAskConfirmation());\n final CompoundCommand compoundCommand = refactorOperation.getCompoundCommand();\n for (final Object input : selectedInput) {\n final ContractInput contractInput = (ContractInput) input;\n contract = ModelHelper.getFirstContainerOfType(contractInput, Contract.class);\n // Parent input has been removed in current selection\n if (contract == null) {\n continue;\n }\n refactorOperation.addItemToRefactor(null, contractInput);\n compoundCommand.append(DeleteCommand.create(editingDomain, contractInput));\n final Collection constraintsReferencingInput = constraintsReferencingSingleInput(contract, contractInput);\n if (!constraintsReferencingInput.isEmpty()) {\n compoundCommand.append(DeleteCommand.create(editingDomain, constraintsReferencingInput));\n }\n }\n try {\n if (refactorOperation.canExecute()) {\n progressService.run(true, true, refactorOperation);\n }\n } catch (final InvocationTargetException | InterruptedException e) {\n BonitaStudioLog.error(\"Failed to remove contract input.\", e);\n openErrorDialog(e);\n }\n }\n }\n\n protected boolean shouldAskConfirmation() {\n return true;\n }\n\n private Collection constraintsReferencingSingleInput(final Contract contract, final ContractInput contractInput) {\n return newHashSet(filter(contract.getConstraints(), havingInputReference(contractInput.getName())));\n }\n\n private Predicate havingInputReference(final String inputName) {\n return new Predicate() {\n\n @Override\n public boolean apply(final ContractConstraint constraint) {\n return constraint.getInputNames().contains(inputName) && constraint.getInputNames().size() == 1;\n }\n };\n }\n\n protected TransactionalEditingDomain editingDomain(final Contract contract) {\n return TransactionUtil.getEditingDomain(contract);\n }\n\n protected RefactorContractInputOperation newRefactorOperation(final Contract contract) {\n return new RefactorContractInputOperation(ModelHelper.getFirstContainerOfType(contract, ContractContainer.class), scriptRefactoringOperationFactory(), RefactoringOperationType.REMOVE);\n }\n\n protected IScriptRefactoringOperationFactory scriptRefactoringOperationFactory() {\n return new GroovyScriptRefactoringOperationFactory();\n }\n\n private EReference inputContainerFeature(final EObject eContainer) {\n return eContainer instanceof ContractInput ? ProcessPackage.Literals.CONTRACT_INPUT__INPUTS : ProcessPackage.Literals.CONTRACT__INPUTS;\n }\n\n protected void openErrorDialog(final Throwable e) {\n if (!FileActionDialog.getDisablePopup()) {\n new BonitaErrorDialog(Display.getDefault().getActiveShell(), Messages.removeInputErrorTitle, Messages.removeInputErrorMsg, e).open();\n }\n }\n\n protected boolean openConfirmation(final List selectedInput) {\n final StringBuilder message = new StringBuilder(Messages.removeInputConfirmationMessagePart1);\n for (final Object input : selectedInput) {\n message.append(SWT.CR);\n message.append(\"- \" + ((ContractInput) input).getName());\n message.append(SWT.CR);\n message.append(Messages.removeInputConfirmationMessagesPart2);\n }\n return FileActionDialog.getDisablePopup() ? true : MessageDialog.openConfirm(Display.getDefault().getActiveShell(), Messages.removeInputConfirmationTitle, message.toString());\n }\n\n @Override\n public void moveUp(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n\n @Override\n public void moveDown(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n}\n"} {"task_id": "Java_1664", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/bonitasoft/bonita-studio/bundles/plugins/org.bonitasoft.studio.contract/src/org/bonitasoft/studio/contract/ui/property/input/ContractInputController.java", "mask_start_position": 5815, "mask_end_position": 5842, "canonical_solution": "return contractInput;\n }", "pre_mask_code": "package org.bonitasoft.studio.contract.ui.property.input;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.bonitasoft.studio.common.emf.tools.ModelHelper.getAllElementOfTypeIn;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.Collection;\nimport java.util.List;\nimport org.bonitasoft.studio.common.NamingUtils;\nimport org.bonitasoft.studio.common.emf.tools.ModelHelper;\nimport org.bonitasoft.studio.common.jface.BonitaErrorDialog;\nimport org.bonitasoft.studio.common.jface.FileActionDialog;\nimport org.bonitasoft.studio.common.jface.databinding.CustomEMFEditObservables;\nimport org.bonitasoft.studio.common.log.BonitaStudioLog;\nimport org.bonitasoft.studio.contract.core.refactoring.RefactorContractInputOperation;\nimport org.bonitasoft.studio.contract.i18n.Messages;\nimport org.bonitasoft.studio.contract.ui.property.IViewerController;\nimport org.bonitasoft.studio.model.process.Contract;\nimport org.bonitasoft.studio.model.process.ContractConstraint;\nimport org.bonitasoft.studio.model.process.ContractContainer;\nimport org.bonitasoft.studio.model.process.ContractInput;\nimport org.bonitasoft.studio.model.process.ContractInputType;\nimport org.bonitasoft.studio.model.process.ProcessFactory;\nimport org.bonitasoft.studio.model.process.ProcessPackage;\nimport org.bonitasoft.studio.refactoring.core.RefactoringOperationType;\nimport org.bonitasoft.studio.refactoring.core.script.GroovyScriptRefactoringOperationFactory;\nimport org.bonitasoft.studio.refactoring.core.script.IScriptRefactoringOperationFactory;\nimport org.eclipse.core.databinding.observable.value.IObservableValue;\nimport org.eclipse.emf.common.command.CompoundCommand;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.EReference;\nimport org.eclipse.emf.edit.command.DeleteCommand;\nimport org.eclipse.emf.transaction.TransactionalEditingDomain;\nimport org.eclipse.emf.transaction.util.TransactionUtil;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.ColumnViewer;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Widget;\nimport org.eclipse.ui.progress.IProgressService;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n\n/**\n * @author Romain Bioteau\n */\npublic class ContractInputController implements IViewerController {\n\n private static final int NAME_COLUMN_INDEX = 0;\n\n private final IProgressService progressService;\n\n class EditNameRunnable implements Runnable {\n\n private final ColumnViewer viewer;\n\n private final ContractInput input;\n\n public EditNameRunnable(final ColumnViewer viewer, final ContractInput input) {\n this.viewer = viewer;\n this.input = input;\n }\n\n /*\n * (non-Javadoc)\n * @see java.lang.Runnable#run()\n */\n @Override\n public void run() {\n if (viewer != null && viewer.getControl() != null && !viewer.getControl().isDisposed()) {\n viewer.setSelection(new StructuredSelection(input), false);\n final Widget item = viewer.testFindItem(input);\n if (item != null && !item.isDisposed()) {\n viewer.reveal(input);\n viewer.editElement(input, NAME_COLUMN_INDEX);\n }\n }\n }\n }\n\n public ContractInputController(final IProgressService progressService) {\n this.progressService = progressService;\n }\n\n @Override\n public ContractInput add(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final Contract contract = (Contract) contractObservable.getValue();\n final ContractInput defaultInput = createDefaultInput(contract);\n final EObject targetContainer = targetContainer(parentInput, contract);\n CustomEMFEditObservables.observeList(targetContainer, inputContainerFeature(targetContainer)).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private EObject targetContainer(final ContractInput parentInput, final Contract contract) {\n return parentInput != null ? parentInput.eContainer() : contract;\n }\n\n public ContractInput addChildInput(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n if (selection.isEmpty()) {\n return null;\n }\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final ContractInput defaultInput = createDefaultInput(ModelHelper.getFirstContainerOfType(parentInput, Contract.class));\n CustomEMFEditObservables.observeList(parentInput, ProcessPackage.Literals.CONTRACT_INPUT__INPUTS).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private ContractInput createDefaultInput(final Contract contract) {\n final ContractInput contractInput = ProcessFactory.eINSTANCE.createContractInput();\n contractInput.setName(defaultContractInputName(contract));\n contractInput.setType(ContractInputType.TEXT);\n contractInput.setMapping(ProcessFactory.eINSTANCE.createContractInputMapping());\n ", "post_mask_code": "\n\n private String defaultContractInputName(final Contract contract) {\n return NamingUtils.generateNewName(newHashSet(transform(getAllElementOfTypeIn(contract, ContractInput.class), toInputName())), \"input\", 1);\n }\n\n private Function toInputName() {\n return new Function() {\n\n @Override\n public String apply(final ContractInput input) {\n return input.getName();\n }\n };\n }\n\n @Override\n public void remove(final ColumnViewer viewer) {\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final List selectedInput = selection.toList();\n Contract contract = (Contract) contractObservable.getValue();\n if (openConfirmation(selectedInput)) {\n final RefactorContractInputOperation refactorOperation = newRefactorOperation(contract);\n final TransactionalEditingDomain editingDomain = editingDomain(contract);\n refactorOperation.setEditingDomain(editingDomain);\n refactorOperation.setAskConfirmation(shouldAskConfirmation());\n final CompoundCommand compoundCommand = refactorOperation.getCompoundCommand();\n for (final Object input : selectedInput) {\n final ContractInput contractInput = (ContractInput) input;\n contract = ModelHelper.getFirstContainerOfType(contractInput, Contract.class);\n // Parent input has been removed in current selection\n if (contract == null) {\n continue;\n }\n refactorOperation.addItemToRefactor(null, contractInput);\n compoundCommand.append(DeleteCommand.create(editingDomain, contractInput));\n final Collection constraintsReferencingInput = constraintsReferencingSingleInput(contract, contractInput);\n if (!constraintsReferencingInput.isEmpty()) {\n compoundCommand.append(DeleteCommand.create(editingDomain, constraintsReferencingInput));\n }\n }\n try {\n if (refactorOperation.canExecute()) {\n progressService.run(true, true, refactorOperation);\n }\n } catch (final InvocationTargetException | InterruptedException e) {\n BonitaStudioLog.error(\"Failed to remove contract input.\", e);\n openErrorDialog(e);\n }\n }\n }\n\n protected boolean shouldAskConfirmation() {\n return true;\n }\n\n private Collection constraintsReferencingSingleInput(final Contract contract, final ContractInput contractInput) {\n return newHashSet(filter(contract.getConstraints(), havingInputReference(contractInput.getName())));\n }\n\n private Predicate havingInputReference(final String inputName) {\n return new Predicate() {\n\n @Override\n public boolean apply(final ContractConstraint constraint) {\n return constraint.getInputNames().contains(inputName) && constraint.getInputNames().size() == 1;\n }\n };\n }\n\n protected TransactionalEditingDomain editingDomain(final Contract contract) {\n return TransactionUtil.getEditingDomain(contract);\n }\n\n protected RefactorContractInputOperation newRefactorOperation(final Contract contract) {\n return new RefactorContractInputOperation(ModelHelper.getFirstContainerOfType(contract, ContractContainer.class), scriptRefactoringOperationFactory(), RefactoringOperationType.REMOVE);\n }\n\n protected IScriptRefactoringOperationFactory scriptRefactoringOperationFactory() {\n return new GroovyScriptRefactoringOperationFactory();\n }\n\n private EReference inputContainerFeature(final EObject eContainer) {\n return eContainer instanceof ContractInput ? ProcessPackage.Literals.CONTRACT_INPUT__INPUTS : ProcessPackage.Literals.CONTRACT__INPUTS;\n }\n\n protected void openErrorDialog(final Throwable e) {\n if (!FileActionDialog.getDisablePopup()) {\n new BonitaErrorDialog(Display.getDefault().getActiveShell(), Messages.removeInputErrorTitle, Messages.removeInputErrorMsg, e).open();\n }\n }\n\n protected boolean openConfirmation(final List selectedInput) {\n final StringBuilder message = new StringBuilder(Messages.removeInputConfirmationMessagePart1);\n for (final Object input : selectedInput) {\n message.append(SWT.CR);\n message.append(\"- \" + ((ContractInput) input).getName());\n message.append(SWT.CR);\n message.append(Messages.removeInputConfirmationMessagesPart2);\n }\n return FileActionDialog.getDisablePopup() ? true : MessageDialog.openConfirm(Display.getDefault().getActiveShell(), Messages.removeInputConfirmationTitle, message.toString());\n }\n\n @Override\n public void moveUp(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n\n @Override\n public void moveDown(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n}\n"} {"task_id": "Java_1665", "language": "Java", "task_type": "single_line", "source_file": "java/github/bonitasoft/bonita-studio/bundles/plugins/org.bonitasoft.studio.contract/src/org/bonitasoft/studio/contract/ui/property/input/ContractInputController.java", "mask_start_position": 6674, "mask_end_position": 6717, "canonical_solution": "= (Contract) contractObservable.getValue();", "pre_mask_code": "package org.bonitasoft.studio.contract.ui.property.input;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.bonitasoft.studio.common.emf.tools.ModelHelper.getAllElementOfTypeIn;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.Collection;\nimport java.util.List;\nimport org.bonitasoft.studio.common.NamingUtils;\nimport org.bonitasoft.studio.common.emf.tools.ModelHelper;\nimport org.bonitasoft.studio.common.jface.BonitaErrorDialog;\nimport org.bonitasoft.studio.common.jface.FileActionDialog;\nimport org.bonitasoft.studio.common.jface.databinding.CustomEMFEditObservables;\nimport org.bonitasoft.studio.common.log.BonitaStudioLog;\nimport org.bonitasoft.studio.contract.core.refactoring.RefactorContractInputOperation;\nimport org.bonitasoft.studio.contract.i18n.Messages;\nimport org.bonitasoft.studio.contract.ui.property.IViewerController;\nimport org.bonitasoft.studio.model.process.Contract;\nimport org.bonitasoft.studio.model.process.ContractConstraint;\nimport org.bonitasoft.studio.model.process.ContractContainer;\nimport org.bonitasoft.studio.model.process.ContractInput;\nimport org.bonitasoft.studio.model.process.ContractInputType;\nimport org.bonitasoft.studio.model.process.ProcessFactory;\nimport org.bonitasoft.studio.model.process.ProcessPackage;\nimport org.bonitasoft.studio.refactoring.core.RefactoringOperationType;\nimport org.bonitasoft.studio.refactoring.core.script.GroovyScriptRefactoringOperationFactory;\nimport org.bonitasoft.studio.refactoring.core.script.IScriptRefactoringOperationFactory;\nimport org.eclipse.core.databinding.observable.value.IObservableValue;\nimport org.eclipse.emf.common.command.CompoundCommand;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.EReference;\nimport org.eclipse.emf.edit.command.DeleteCommand;\nimport org.eclipse.emf.transaction.TransactionalEditingDomain;\nimport org.eclipse.emf.transaction.util.TransactionUtil;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.ColumnViewer;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Widget;\nimport org.eclipse.ui.progress.IProgressService;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n\n/**\n * @author Romain Bioteau\n */\npublic class ContractInputController implements IViewerController {\n\n private static final int NAME_COLUMN_INDEX = 0;\n\n private final IProgressService progressService;\n\n class EditNameRunnable implements Runnable {\n\n private final ColumnViewer viewer;\n\n private final ContractInput input;\n\n public EditNameRunnable(final ColumnViewer viewer, final ContractInput input) {\n this.viewer = viewer;\n this.input = input;\n }\n\n /*\n * (non-Javadoc)\n * @see java.lang.Runnable#run()\n */\n @Override\n public void run() {\n if (viewer != null && viewer.getControl() != null && !viewer.getControl().isDisposed()) {\n viewer.setSelection(new StructuredSelection(input), false);\n final Widget item = viewer.testFindItem(input);\n if (item != null && !item.isDisposed()) {\n viewer.reveal(input);\n viewer.editElement(input, NAME_COLUMN_INDEX);\n }\n }\n }\n }\n\n public ContractInputController(final IProgressService progressService) {\n this.progressService = progressService;\n }\n\n @Override\n public ContractInput add(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final Contract contract = (Contract) contractObservable.getValue();\n final ContractInput defaultInput = createDefaultInput(contract);\n final EObject targetContainer = targetContainer(parentInput, contract);\n CustomEMFEditObservables.observeList(targetContainer, inputContainerFeature(targetContainer)).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private EObject targetContainer(final ContractInput parentInput, final Contract contract) {\n return parentInput != null ? parentInput.eContainer() : contract;\n }\n\n public ContractInput addChildInput(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n if (selection.isEmpty()) {\n return null;\n }\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final ContractInput defaultInput = createDefaultInput(ModelHelper.getFirstContainerOfType(parentInput, Contract.class));\n CustomEMFEditObservables.observeList(parentInput, ProcessPackage.Literals.CONTRACT_INPUT__INPUTS).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private ContractInput createDefaultInput(final Contract contract) {\n final ContractInput contractInput = ProcessFactory.eINSTANCE.createContractInput();\n contractInput.setName(defaultContractInputName(contract));\n contractInput.setType(ContractInputType.TEXT);\n contractInput.setMapping(ProcessFactory.eINSTANCE.createContractInputMapping());\n return contractInput;\n }\n\n private String defaultContractInputName(final Contract contract) {\n return NamingUtils.generateNewName(newHashSet(transform(getAllElementOfTypeIn(contract, ContractInput.class), toInputName())), \"input\", 1);\n }\n\n private Function toInputName() {\n return new Function() {\n\n @Override\n public String apply(final ContractInput input) {\n return input.getName();\n }\n };\n }\n\n @Override\n public void remove(final ColumnViewer viewer) {\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final List selectedInput = selection.toList();\n Contract contract ", "post_mask_code": "\n if (openConfirmation(selectedInput)) {\n final RefactorContractInputOperation refactorOperation = newRefactorOperation(contract);\n final TransactionalEditingDomain editingDomain = editingDomain(contract);\n refactorOperation.setEditingDomain(editingDomain);\n refactorOperation.setAskConfirmation(shouldAskConfirmation());\n final CompoundCommand compoundCommand = refactorOperation.getCompoundCommand();\n for (final Object input : selectedInput) {\n final ContractInput contractInput = (ContractInput) input;\n contract = ModelHelper.getFirstContainerOfType(contractInput, Contract.class);\n // Parent input has been removed in current selection\n if (contract == null) {\n continue;\n }\n refactorOperation.addItemToRefactor(null, contractInput);\n compoundCommand.append(DeleteCommand.create(editingDomain, contractInput));\n final Collection constraintsReferencingInput = constraintsReferencingSingleInput(contract, contractInput);\n if (!constraintsReferencingInput.isEmpty()) {\n compoundCommand.append(DeleteCommand.create(editingDomain, constraintsReferencingInput));\n }\n }\n try {\n if (refactorOperation.canExecute()) {\n progressService.run(true, true, refactorOperation);\n }\n } catch (final InvocationTargetException | InterruptedException e) {\n BonitaStudioLog.error(\"Failed to remove contract input.\", e);\n openErrorDialog(e);\n }\n }\n }\n\n protected boolean shouldAskConfirmation() {\n return true;\n }\n\n private Collection constraintsReferencingSingleInput(final Contract contract, final ContractInput contractInput) {\n return newHashSet(filter(contract.getConstraints(), havingInputReference(contractInput.getName())));\n }\n\n private Predicate havingInputReference(final String inputName) {\n return new Predicate() {\n\n @Override\n public boolean apply(final ContractConstraint constraint) {\n return constraint.getInputNames().contains(inputName) && constraint.getInputNames().size() == 1;\n }\n };\n }\n\n protected TransactionalEditingDomain editingDomain(final Contract contract) {\n return TransactionUtil.getEditingDomain(contract);\n }\n\n protected RefactorContractInputOperation newRefactorOperation(final Contract contract) {\n return new RefactorContractInputOperation(ModelHelper.getFirstContainerOfType(contract, ContractContainer.class), scriptRefactoringOperationFactory(), RefactoringOperationType.REMOVE);\n }\n\n protected IScriptRefactoringOperationFactory scriptRefactoringOperationFactory() {\n return new GroovyScriptRefactoringOperationFactory();\n }\n\n private EReference inputContainerFeature(final EObject eContainer) {\n return eContainer instanceof ContractInput ? ProcessPackage.Literals.CONTRACT_INPUT__INPUTS : ProcessPackage.Literals.CONTRACT__INPUTS;\n }\n\n protected void openErrorDialog(final Throwable e) {\n if (!FileActionDialog.getDisablePopup()) {\n new BonitaErrorDialog(Display.getDefault().getActiveShell(), Messages.removeInputErrorTitle, Messages.removeInputErrorMsg, e).open();\n }\n }\n\n protected boolean openConfirmation(final List selectedInput) {\n final StringBuilder message = new StringBuilder(Messages.removeInputConfirmationMessagePart1);\n for (final Object input : selectedInput) {\n message.append(SWT.CR);\n message.append(\"- \" + ((ContractInput) input).getName());\n message.append(SWT.CR);\n message.append(Messages.removeInputConfirmationMessagesPart2);\n }\n return FileActionDialog.getDisablePopup() ? true : MessageDialog.openConfirm(Display.getDefault().getActiveShell(), Messages.removeInputConfirmationTitle, message.toString());\n }\n\n @Override\n public void moveUp(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n\n @Override\n public void moveDown(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n}\n"} {"task_id": "Java_1666", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/bonitasoft/bonita-studio/bundles/plugins/org.bonitasoft.studio.contract/src/org/bonitasoft/studio/contract/ui/property/input/ContractInputController.java", "mask_start_position": 3100, "mask_end_position": 3587, "canonical_solution": "@Override\n public void run() {\n if (viewer != null && viewer.getControl() != null && !viewer.getControl().isDisposed()) {\n viewer.setSelection(new StructuredSelection(input), false);\n final Widget item = viewer.testFindItem(input);\n if (item != null && !item.isDisposed()) {\n viewer.reveal(input);\n viewer.editElement(input, NAME_COLUMN_INDEX);\n }\n }\n }", "pre_mask_code": "package org.bonitasoft.studio.contract.ui.property.input;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.bonitasoft.studio.common.emf.tools.ModelHelper.getAllElementOfTypeIn;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.Collection;\nimport java.util.List;\nimport org.bonitasoft.studio.common.NamingUtils;\nimport org.bonitasoft.studio.common.emf.tools.ModelHelper;\nimport org.bonitasoft.studio.common.jface.BonitaErrorDialog;\nimport org.bonitasoft.studio.common.jface.FileActionDialog;\nimport org.bonitasoft.studio.common.jface.databinding.CustomEMFEditObservables;\nimport org.bonitasoft.studio.common.log.BonitaStudioLog;\nimport org.bonitasoft.studio.contract.core.refactoring.RefactorContractInputOperation;\nimport org.bonitasoft.studio.contract.i18n.Messages;\nimport org.bonitasoft.studio.contract.ui.property.IViewerController;\nimport org.bonitasoft.studio.model.process.Contract;\nimport org.bonitasoft.studio.model.process.ContractConstraint;\nimport org.bonitasoft.studio.model.process.ContractContainer;\nimport org.bonitasoft.studio.model.process.ContractInput;\nimport org.bonitasoft.studio.model.process.ContractInputType;\nimport org.bonitasoft.studio.model.process.ProcessFactory;\nimport org.bonitasoft.studio.model.process.ProcessPackage;\nimport org.bonitasoft.studio.refactoring.core.RefactoringOperationType;\nimport org.bonitasoft.studio.refactoring.core.script.GroovyScriptRefactoringOperationFactory;\nimport org.bonitasoft.studio.refactoring.core.script.IScriptRefactoringOperationFactory;\nimport org.eclipse.core.databinding.observable.value.IObservableValue;\nimport org.eclipse.emf.common.command.CompoundCommand;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.EReference;\nimport org.eclipse.emf.edit.command.DeleteCommand;\nimport org.eclipse.emf.transaction.TransactionalEditingDomain;\nimport org.eclipse.emf.transaction.util.TransactionUtil;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.ColumnViewer;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Widget;\nimport org.eclipse.ui.progress.IProgressService;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n\n/**\n * @author Romain Bioteau\n */\npublic class ContractInputController implements IViewerController {\n\n private static final int NAME_COLUMN_INDEX = 0;\n\n private final IProgressService progressService;\n\n class EditNameRunnable implements Runnable {\n\n private final ColumnViewer viewer;\n\n private final ContractInput input;\n\n public EditNameRunnable(final ColumnViewer viewer, final ContractInput input) {\n this.viewer = viewer;\n this.input = input;\n }\n\n /*\n * (non-Javadoc)\n * @see java.lang.Runnable#run()\n */\n ", "post_mask_code": "\n }\n\n public ContractInputController(final IProgressService progressService) {\n this.progressService = progressService;\n }\n\n @Override\n public ContractInput add(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final Contract contract = (Contract) contractObservable.getValue();\n final ContractInput defaultInput = createDefaultInput(contract);\n final EObject targetContainer = targetContainer(parentInput, contract);\n CustomEMFEditObservables.observeList(targetContainer, inputContainerFeature(targetContainer)).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private EObject targetContainer(final ContractInput parentInput, final Contract contract) {\n return parentInput != null ? parentInput.eContainer() : contract;\n }\n\n public ContractInput addChildInput(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n if (selection.isEmpty()) {\n return null;\n }\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final ContractInput defaultInput = createDefaultInput(ModelHelper.getFirstContainerOfType(parentInput, Contract.class));\n CustomEMFEditObservables.observeList(parentInput, ProcessPackage.Literals.CONTRACT_INPUT__INPUTS).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private ContractInput createDefaultInput(final Contract contract) {\n final ContractInput contractInput = ProcessFactory.eINSTANCE.createContractInput();\n contractInput.setName(defaultContractInputName(contract));\n contractInput.setType(ContractInputType.TEXT);\n contractInput.setMapping(ProcessFactory.eINSTANCE.createContractInputMapping());\n return contractInput;\n }\n\n private String defaultContractInputName(final Contract contract) {\n return NamingUtils.generateNewName(newHashSet(transform(getAllElementOfTypeIn(contract, ContractInput.class), toInputName())), \"input\", 1);\n }\n\n private Function toInputName() {\n return new Function() {\n\n @Override\n public String apply(final ContractInput input) {\n return input.getName();\n }\n };\n }\n\n @Override\n public void remove(final ColumnViewer viewer) {\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final List selectedInput = selection.toList();\n Contract contract = (Contract) contractObservable.getValue();\n if (openConfirmation(selectedInput)) {\n final RefactorContractInputOperation refactorOperation = newRefactorOperation(contract);\n final TransactionalEditingDomain editingDomain = editingDomain(contract);\n refactorOperation.setEditingDomain(editingDomain);\n refactorOperation.setAskConfirmation(shouldAskConfirmation());\n final CompoundCommand compoundCommand = refactorOperation.getCompoundCommand();\n for (final Object input : selectedInput) {\n final ContractInput contractInput = (ContractInput) input;\n contract = ModelHelper.getFirstContainerOfType(contractInput, Contract.class);\n // Parent input has been removed in current selection\n if (contract == null) {\n continue;\n }\n refactorOperation.addItemToRefactor(null, contractInput);\n compoundCommand.append(DeleteCommand.create(editingDomain, contractInput));\n final Collection constraintsReferencingInput = constraintsReferencingSingleInput(contract, contractInput);\n if (!constraintsReferencingInput.isEmpty()) {\n compoundCommand.append(DeleteCommand.create(editingDomain, constraintsReferencingInput));\n }\n }\n try {\n if (refactorOperation.canExecute()) {\n progressService.run(true, true, refactorOperation);\n }\n } catch (final InvocationTargetException | InterruptedException e) {\n BonitaStudioLog.error(\"Failed to remove contract input.\", e);\n openErrorDialog(e);\n }\n }\n }\n\n protected boolean shouldAskConfirmation() {\n return true;\n }\n\n private Collection constraintsReferencingSingleInput(final Contract contract, final ContractInput contractInput) {\n return newHashSet(filter(contract.getConstraints(), havingInputReference(contractInput.getName())));\n }\n\n private Predicate havingInputReference(final String inputName) {\n return new Predicate() {\n\n @Override\n public boolean apply(final ContractConstraint constraint) {\n return constraint.getInputNames().contains(inputName) && constraint.getInputNames().size() == 1;\n }\n };\n }\n\n protected TransactionalEditingDomain editingDomain(final Contract contract) {\n return TransactionUtil.getEditingDomain(contract);\n }\n\n protected RefactorContractInputOperation newRefactorOperation(final Contract contract) {\n return new RefactorContractInputOperation(ModelHelper.getFirstContainerOfType(contract, ContractContainer.class), scriptRefactoringOperationFactory(), RefactoringOperationType.REMOVE);\n }\n\n protected IScriptRefactoringOperationFactory scriptRefactoringOperationFactory() {\n return new GroovyScriptRefactoringOperationFactory();\n }\n\n private EReference inputContainerFeature(final EObject eContainer) {\n return eContainer instanceof ContractInput ? ProcessPackage.Literals.CONTRACT_INPUT__INPUTS : ProcessPackage.Literals.CONTRACT__INPUTS;\n }\n\n protected void openErrorDialog(final Throwable e) {\n if (!FileActionDialog.getDisablePopup()) {\n new BonitaErrorDialog(Display.getDefault().getActiveShell(), Messages.removeInputErrorTitle, Messages.removeInputErrorMsg, e).open();\n }\n }\n\n protected boolean openConfirmation(final List selectedInput) {\n final StringBuilder message = new StringBuilder(Messages.removeInputConfirmationMessagePart1);\n for (final Object input : selectedInput) {\n message.append(SWT.CR);\n message.append(\"- \" + ((ContractInput) input).getName());\n message.append(SWT.CR);\n message.append(Messages.removeInputConfirmationMessagesPart2);\n }\n return FileActionDialog.getDisablePopup() ? true : MessageDialog.openConfirm(Display.getDefault().getActiveShell(), Messages.removeInputConfirmationTitle, message.toString());\n }\n\n @Override\n public void moveUp(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n\n @Override\n public void moveDown(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n}\n"} {"task_id": "Java_1667", "language": "Java", "task_type": "if_statement", "source_file": "java/github/bonitasoft/bonita-studio/bundles/plugins/org.bonitasoft.studio.contract/src/org/bonitasoft/studio/contract/ui/property/input/ContractInputController.java", "mask_start_position": 8112, "mask_end_position": 8239, "canonical_solution": "if (refactorOperation.canExecute()) {\n progressService.run(true, true, refactorOperation);\n }", "pre_mask_code": "package org.bonitasoft.studio.contract.ui.property.input;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.bonitasoft.studio.common.emf.tools.ModelHelper.getAllElementOfTypeIn;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.Collection;\nimport java.util.List;\nimport org.bonitasoft.studio.common.NamingUtils;\nimport org.bonitasoft.studio.common.emf.tools.ModelHelper;\nimport org.bonitasoft.studio.common.jface.BonitaErrorDialog;\nimport org.bonitasoft.studio.common.jface.FileActionDialog;\nimport org.bonitasoft.studio.common.jface.databinding.CustomEMFEditObservables;\nimport org.bonitasoft.studio.common.log.BonitaStudioLog;\nimport org.bonitasoft.studio.contract.core.refactoring.RefactorContractInputOperation;\nimport org.bonitasoft.studio.contract.i18n.Messages;\nimport org.bonitasoft.studio.contract.ui.property.IViewerController;\nimport org.bonitasoft.studio.model.process.Contract;\nimport org.bonitasoft.studio.model.process.ContractConstraint;\nimport org.bonitasoft.studio.model.process.ContractContainer;\nimport org.bonitasoft.studio.model.process.ContractInput;\nimport org.bonitasoft.studio.model.process.ContractInputType;\nimport org.bonitasoft.studio.model.process.ProcessFactory;\nimport org.bonitasoft.studio.model.process.ProcessPackage;\nimport org.bonitasoft.studio.refactoring.core.RefactoringOperationType;\nimport org.bonitasoft.studio.refactoring.core.script.GroovyScriptRefactoringOperationFactory;\nimport org.bonitasoft.studio.refactoring.core.script.IScriptRefactoringOperationFactory;\nimport org.eclipse.core.databinding.observable.value.IObservableValue;\nimport org.eclipse.emf.common.command.CompoundCommand;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.EReference;\nimport org.eclipse.emf.edit.command.DeleteCommand;\nimport org.eclipse.emf.transaction.TransactionalEditingDomain;\nimport org.eclipse.emf.transaction.util.TransactionUtil;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.ColumnViewer;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Widget;\nimport org.eclipse.ui.progress.IProgressService;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n\n/**\n * @author Romain Bioteau\n */\npublic class ContractInputController implements IViewerController {\n\n private static final int NAME_COLUMN_INDEX = 0;\n\n private final IProgressService progressService;\n\n class EditNameRunnable implements Runnable {\n\n private final ColumnViewer viewer;\n\n private final ContractInput input;\n\n public EditNameRunnable(final ColumnViewer viewer, final ContractInput input) {\n this.viewer = viewer;\n this.input = input;\n }\n\n /*\n * (non-Javadoc)\n * @see java.lang.Runnable#run()\n */\n @Override\n public void run() {\n if (viewer != null && viewer.getControl() != null && !viewer.getControl().isDisposed()) {\n viewer.setSelection(new StructuredSelection(input), false);\n final Widget item = viewer.testFindItem(input);\n if (item != null && !item.isDisposed()) {\n viewer.reveal(input);\n viewer.editElement(input, NAME_COLUMN_INDEX);\n }\n }\n }\n }\n\n public ContractInputController(final IProgressService progressService) {\n this.progressService = progressService;\n }\n\n @Override\n public ContractInput add(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final Contract contract = (Contract) contractObservable.getValue();\n final ContractInput defaultInput = createDefaultInput(contract);\n final EObject targetContainer = targetContainer(parentInput, contract);\n CustomEMFEditObservables.observeList(targetContainer, inputContainerFeature(targetContainer)).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private EObject targetContainer(final ContractInput parentInput, final Contract contract) {\n return parentInput != null ? parentInput.eContainer() : contract;\n }\n\n public ContractInput addChildInput(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n if (selection.isEmpty()) {\n return null;\n }\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final ContractInput defaultInput = createDefaultInput(ModelHelper.getFirstContainerOfType(parentInput, Contract.class));\n CustomEMFEditObservables.observeList(parentInput, ProcessPackage.Literals.CONTRACT_INPUT__INPUTS).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private ContractInput createDefaultInput(final Contract contract) {\n final ContractInput contractInput = ProcessFactory.eINSTANCE.createContractInput();\n contractInput.setName(defaultContractInputName(contract));\n contractInput.setType(ContractInputType.TEXT);\n contractInput.setMapping(ProcessFactory.eINSTANCE.createContractInputMapping());\n return contractInput;\n }\n\n private String defaultContractInputName(final Contract contract) {\n return NamingUtils.generateNewName(newHashSet(transform(getAllElementOfTypeIn(contract, ContractInput.class), toInputName())), \"input\", 1);\n }\n\n private Function toInputName() {\n return new Function() {\n\n @Override\n public String apply(final ContractInput input) {\n return input.getName();\n }\n };\n }\n\n @Override\n public void remove(final ColumnViewer viewer) {\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final List selectedInput = selection.toList();\n Contract contract = (Contract) contractObservable.getValue();\n if (openConfirmation(selectedInput)) {\n final RefactorContractInputOperation refactorOperation = newRefactorOperation(contract);\n final TransactionalEditingDomain editingDomain = editingDomain(contract);\n refactorOperation.setEditingDomain(editingDomain);\n refactorOperation.setAskConfirmation(shouldAskConfirmation());\n final CompoundCommand compoundCommand = refactorOperation.getCompoundCommand();\n for (final Object input : selectedInput) {\n final ContractInput contractInput = (ContractInput) input;\n contract = ModelHelper.getFirstContainerOfType(contractInput, Contract.class);\n // Parent input has been removed in current selection\n if (contract == null) {\n continue;\n }\n refactorOperation.addItemToRefactor(null, contractInput);\n compoundCommand.append(DeleteCommand.create(editingDomain, contractInput));\n final Collection constraintsReferencingInput = constraintsReferencingSingleInput(contract, contractInput);\n if (!constraintsReferencingInput.isEmpty()) {\n compoundCommand.append(DeleteCommand.create(editingDomain, constraintsReferencingInput));\n }\n }\n try {\n ", "post_mask_code": "\n } catch (final InvocationTargetException | InterruptedException e) {\n BonitaStudioLog.error(\"Failed to remove contract input.\", e);\n openErrorDialog(e);\n }\n }\n }\n\n protected boolean shouldAskConfirmation() {\n return true;\n }\n\n private Collection constraintsReferencingSingleInput(final Contract contract, final ContractInput contractInput) {\n return newHashSet(filter(contract.getConstraints(), havingInputReference(contractInput.getName())));\n }\n\n private Predicate havingInputReference(final String inputName) {\n return new Predicate() {\n\n @Override\n public boolean apply(final ContractConstraint constraint) {\n return constraint.getInputNames().contains(inputName) && constraint.getInputNames().size() == 1;\n }\n };\n }\n\n protected TransactionalEditingDomain editingDomain(final Contract contract) {\n return TransactionUtil.getEditingDomain(contract);\n }\n\n protected RefactorContractInputOperation newRefactorOperation(final Contract contract) {\n return new RefactorContractInputOperation(ModelHelper.getFirstContainerOfType(contract, ContractContainer.class), scriptRefactoringOperationFactory(), RefactoringOperationType.REMOVE);\n }\n\n protected IScriptRefactoringOperationFactory scriptRefactoringOperationFactory() {\n return new GroovyScriptRefactoringOperationFactory();\n }\n\n private EReference inputContainerFeature(final EObject eContainer) {\n return eContainer instanceof ContractInput ? ProcessPackage.Literals.CONTRACT_INPUT__INPUTS : ProcessPackage.Literals.CONTRACT__INPUTS;\n }\n\n protected void openErrorDialog(final Throwable e) {\n if (!FileActionDialog.getDisablePopup()) {\n new BonitaErrorDialog(Display.getDefault().getActiveShell(), Messages.removeInputErrorTitle, Messages.removeInputErrorMsg, e).open();\n }\n }\n\n protected boolean openConfirmation(final List selectedInput) {\n final StringBuilder message = new StringBuilder(Messages.removeInputConfirmationMessagePart1);\n for (final Object input : selectedInput) {\n message.append(SWT.CR);\n message.append(\"- \" + ((ContractInput) input).getName());\n message.append(SWT.CR);\n message.append(Messages.removeInputConfirmationMessagesPart2);\n }\n return FileActionDialog.getDisablePopup() ? true : MessageDialog.openConfirm(Display.getDefault().getActiveShell(), Messages.removeInputConfirmationTitle, message.toString());\n }\n\n @Override\n public void moveUp(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n\n @Override\n public void moveDown(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n}\n"} {"task_id": "Java_1668", "language": "Java", "task_type": "try_statement", "source_file": "java/github/bonitasoft/bonita-studio/bundles/plugins/org.bonitasoft.studio.contract/src/org/bonitasoft/studio/contract/ui/property/input/ContractInputController.java", "mask_start_position": 8090, "mask_end_position": 8448, "canonical_solution": "try {\n if (refactorOperation.canExecute()) {\n progressService.run(true, true, refactorOperation);\n }\n } catch (final InvocationTargetException | InterruptedException e) {\n BonitaStudioLog.error(\"Failed to remove contract input.\", e);\n openErrorDialog(e);\n }", "pre_mask_code": "package org.bonitasoft.studio.contract.ui.property.input;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.bonitasoft.studio.common.emf.tools.ModelHelper.getAllElementOfTypeIn;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.Collection;\nimport java.util.List;\nimport org.bonitasoft.studio.common.NamingUtils;\nimport org.bonitasoft.studio.common.emf.tools.ModelHelper;\nimport org.bonitasoft.studio.common.jface.BonitaErrorDialog;\nimport org.bonitasoft.studio.common.jface.FileActionDialog;\nimport org.bonitasoft.studio.common.jface.databinding.CustomEMFEditObservables;\nimport org.bonitasoft.studio.common.log.BonitaStudioLog;\nimport org.bonitasoft.studio.contract.core.refactoring.RefactorContractInputOperation;\nimport org.bonitasoft.studio.contract.i18n.Messages;\nimport org.bonitasoft.studio.contract.ui.property.IViewerController;\nimport org.bonitasoft.studio.model.process.Contract;\nimport org.bonitasoft.studio.model.process.ContractConstraint;\nimport org.bonitasoft.studio.model.process.ContractContainer;\nimport org.bonitasoft.studio.model.process.ContractInput;\nimport org.bonitasoft.studio.model.process.ContractInputType;\nimport org.bonitasoft.studio.model.process.ProcessFactory;\nimport org.bonitasoft.studio.model.process.ProcessPackage;\nimport org.bonitasoft.studio.refactoring.core.RefactoringOperationType;\nimport org.bonitasoft.studio.refactoring.core.script.GroovyScriptRefactoringOperationFactory;\nimport org.bonitasoft.studio.refactoring.core.script.IScriptRefactoringOperationFactory;\nimport org.eclipse.core.databinding.observable.value.IObservableValue;\nimport org.eclipse.emf.common.command.CompoundCommand;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.EReference;\nimport org.eclipse.emf.edit.command.DeleteCommand;\nimport org.eclipse.emf.transaction.TransactionalEditingDomain;\nimport org.eclipse.emf.transaction.util.TransactionUtil;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.ColumnViewer;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Widget;\nimport org.eclipse.ui.progress.IProgressService;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n\n/**\n * @author Romain Bioteau\n */\npublic class ContractInputController implements IViewerController {\n\n private static final int NAME_COLUMN_INDEX = 0;\n\n private final IProgressService progressService;\n\n class EditNameRunnable implements Runnable {\n\n private final ColumnViewer viewer;\n\n private final ContractInput input;\n\n public EditNameRunnable(final ColumnViewer viewer, final ContractInput input) {\n this.viewer = viewer;\n this.input = input;\n }\n\n /*\n * (non-Javadoc)\n * @see java.lang.Runnable#run()\n */\n @Override\n public void run() {\n if (viewer != null && viewer.getControl() != null && !viewer.getControl().isDisposed()) {\n viewer.setSelection(new StructuredSelection(input), false);\n final Widget item = viewer.testFindItem(input);\n if (item != null && !item.isDisposed()) {\n viewer.reveal(input);\n viewer.editElement(input, NAME_COLUMN_INDEX);\n }\n }\n }\n }\n\n public ContractInputController(final IProgressService progressService) {\n this.progressService = progressService;\n }\n\n @Override\n public ContractInput add(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final Contract contract = (Contract) contractObservable.getValue();\n final ContractInput defaultInput = createDefaultInput(contract);\n final EObject targetContainer = targetContainer(parentInput, contract);\n CustomEMFEditObservables.observeList(targetContainer, inputContainerFeature(targetContainer)).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private EObject targetContainer(final ContractInput parentInput, final Contract contract) {\n return parentInput != null ? parentInput.eContainer() : contract;\n }\n\n public ContractInput addChildInput(final ColumnViewer viewer) {\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n if (selection.isEmpty()) {\n return null;\n }\n final ContractInput parentInput = (ContractInput) selection.getFirstElement();\n final ContractInput defaultInput = createDefaultInput(ModelHelper.getFirstContainerOfType(parentInput, Contract.class));\n CustomEMFEditObservables.observeList(parentInput, ProcessPackage.Literals.CONTRACT_INPUT__INPUTS).add(defaultInput);\n viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));\n return defaultInput;\n }\n\n private ContractInput createDefaultInput(final Contract contract) {\n final ContractInput contractInput = ProcessFactory.eINSTANCE.createContractInput();\n contractInput.setName(defaultContractInputName(contract));\n contractInput.setType(ContractInputType.TEXT);\n contractInput.setMapping(ProcessFactory.eINSTANCE.createContractInputMapping());\n return contractInput;\n }\n\n private String defaultContractInputName(final Contract contract) {\n return NamingUtils.generateNewName(newHashSet(transform(getAllElementOfTypeIn(contract, ContractInput.class), toInputName())), \"input\", 1);\n }\n\n private Function toInputName() {\n return new Function() {\n\n @Override\n public String apply(final ContractInput input) {\n return input.getName();\n }\n };\n }\n\n @Override\n public void remove(final ColumnViewer viewer) {\n final IObservableValue contractObservable = (IObservableValue) viewer.getInput();\n final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();\n final List selectedInput = selection.toList();\n Contract contract = (Contract) contractObservable.getValue();\n if (openConfirmation(selectedInput)) {\n final RefactorContractInputOperation refactorOperation = newRefactorOperation(contract);\n final TransactionalEditingDomain editingDomain = editingDomain(contract);\n refactorOperation.setEditingDomain(editingDomain);\n refactorOperation.setAskConfirmation(shouldAskConfirmation());\n final CompoundCommand compoundCommand = refactorOperation.getCompoundCommand();\n for (final Object input : selectedInput) {\n final ContractInput contractInput = (ContractInput) input;\n contract = ModelHelper.getFirstContainerOfType(contractInput, Contract.class);\n // Parent input has been removed in current selection\n if (contract == null) {\n continue;\n }\n refactorOperation.addItemToRefactor(null, contractInput);\n compoundCommand.append(DeleteCommand.create(editingDomain, contractInput));\n final Collection constraintsReferencingInput = constraintsReferencingSingleInput(contract, contractInput);\n if (!constraintsReferencingInput.isEmpty()) {\n compoundCommand.append(DeleteCommand.create(editingDomain, constraintsReferencingInput));\n }\n }\n ", "post_mask_code": "\n }\n }\n\n protected boolean shouldAskConfirmation() {\n return true;\n }\n\n private Collection constraintsReferencingSingleInput(final Contract contract, final ContractInput contractInput) {\n return newHashSet(filter(contract.getConstraints(), havingInputReference(contractInput.getName())));\n }\n\n private Predicate havingInputReference(final String inputName) {\n return new Predicate() {\n\n @Override\n public boolean apply(final ContractConstraint constraint) {\n return constraint.getInputNames().contains(inputName) && constraint.getInputNames().size() == 1;\n }\n };\n }\n\n protected TransactionalEditingDomain editingDomain(final Contract contract) {\n return TransactionUtil.getEditingDomain(contract);\n }\n\n protected RefactorContractInputOperation newRefactorOperation(final Contract contract) {\n return new RefactorContractInputOperation(ModelHelper.getFirstContainerOfType(contract, ContractContainer.class), scriptRefactoringOperationFactory(), RefactoringOperationType.REMOVE);\n }\n\n protected IScriptRefactoringOperationFactory scriptRefactoringOperationFactory() {\n return new GroovyScriptRefactoringOperationFactory();\n }\n\n private EReference inputContainerFeature(final EObject eContainer) {\n return eContainer instanceof ContractInput ? ProcessPackage.Literals.CONTRACT_INPUT__INPUTS : ProcessPackage.Literals.CONTRACT__INPUTS;\n }\n\n protected void openErrorDialog(final Throwable e) {\n if (!FileActionDialog.getDisablePopup()) {\n new BonitaErrorDialog(Display.getDefault().getActiveShell(), Messages.removeInputErrorTitle, Messages.removeInputErrorMsg, e).open();\n }\n }\n\n protected boolean openConfirmation(final List selectedInput) {\n final StringBuilder message = new StringBuilder(Messages.removeInputConfirmationMessagePart1);\n for (final Object input : selectedInput) {\n message.append(SWT.CR);\n message.append(\"- \" + ((ContractInput) input).getName());\n message.append(SWT.CR);\n message.append(Messages.removeInputConfirmationMessagesPart2);\n }\n return FileActionDialog.getDisablePopup() ? true : MessageDialog.openConfirm(Display.getDefault().getActiveShell(), Messages.removeInputConfirmationTitle, message.toString());\n }\n\n @Override\n public void moveUp(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n\n @Override\n public void moveDown(final ColumnViewer viewer) {\n throw new UnsupportedOperationException(\"Not implemented yet.\");\n }\n}\n"} {"task_id": "Java_1669", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Zimbra/zm-mailbox/store/src/java-test/com/zimbra/cs/store/external/StoreManagerNegativeTest.java", "mask_start_position": 1638, "mask_end_position": 1689, "canonical_solution": "@After\n public void tearDown() throws Exception ", "pre_mask_code": "/*\n * ***** BEGIN LICENSE BLOCK *****\n * Zimbra Collaboration Suite Server\n *\n * ***** END LICENSE BLOCK *****\n */\npackage com.zimbra.cs.store.external;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Random;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport com.zimbra.common.service.ServiceException;\nimport com.zimbra.common.util.ZimbraLog;\nimport com.zimbra.cs.account.MockProvisioning;\nimport com.zimbra.cs.account.Provisioning;\nimport com.zimbra.cs.mailbox.Mailbox;\nimport com.zimbra.cs.mailbox.MailboxManager;\nimport com.zimbra.cs.mailbox.MailboxTestUtil;\nimport com.zimbra.cs.store.Blob;\nimport com.zimbra.cs.store.BlobBuilder;\nimport com.zimbra.cs.store.IncomingBlob;\nimport com.zimbra.cs.store.MailboxBlob;\nimport com.zimbra.cs.store.StagedBlob;\nimport com.zimbra.cs.store.StoreManager;\nimport com.zimbra.qa.unittest.TestUtil;\n\npublic class StoreManagerNegativeTest {\n\n static StoreManager originalStoreManager;\n\n @BeforeClass\n public static void init() throws Exception {\n MailboxTestUtil.initServer();\n MailboxTestUtil.initProvisioning();\n Provisioning.getInstance().createAccount(\"example@nnthink.com\", \"secret\", new HashMap());\n }\n\n @Before\n public void setUp() throws Exception {\n originalStoreManager = StoreManager.getInstance();\n StoreManager.setInstance(getStoreManager());\n StoreManager.getInstance().startup();\n }\n\n ", "post_mask_code": "{\n StoreManager.getInstance().shutdown();\n StoreManager.setInstance(originalStoreManager);\n }\n\n protected StoreManager getStoreManager() {\n return new BrokenStreamingStoreManager();\n }\n\n @Test\n public void nullLocator() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n Blob blob = incoming.getBlob();\n Assert.assertEquals(\"blob size = incoming written\", bytes.length, blob.getRawSize());\n Assert.assertTrue(\"blob content = mime content\", TestUtil.bytesEqual(bytes, blob.getInputStream()));\n StagedBlob staged = sm.stage(blob, mbox);\n Assert.assertEquals(\"staged size = blob size\", blob.getRawSize(), staged.getSize());\n MailboxBlob mblob = sm.link(staged, mbox, 0, 0);\n Assert.assertEquals(\"link size = staged size\", staged.getSize(), mblob.getSize());\n try {\n mblob.getLocalBlob().getInputStream();\n Assert.fail(\"Expected IOException since locator is not handled correctly\");\n } catch (IOException io) {\n // expected\n } finally {\n sm.delete(mblob);\n }\n }\n\n @Test\n public void incorrectRemoteSize() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n try {\n incoming.getCurrentSize();\n Assert.fail(\"Expected exception since remote size is incorrect\");\n } catch (IOException ioe) {\n // expected\n }\n }\n\n private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {\n\n @Override\n public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {\n return null;\n }\n\n @Override\n public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {\n super.writeStreamToStore(in, actualSize, mbox);\n return null;\n }\n\n @Override\n public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {\n return null;\n }\n\n @Override\n public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {\n return false;\n }\n\n @Override\n public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {\n return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);\n }\n\n private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {\n\n private final File file;\n\n public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {\n super(id, blobBuilder, ctx);\n String baseName = uploadDirectory + \"/upload-\" + id;\n String name = baseName;\n synchronized (this) {\n int count = 1;\n File upFile = new File(name + \".upl\");\n while (upFile.exists()) {\n name = baseName + \"_\" + count++;\n upFile = new File(name + \".upl\");\n }\n if (upFile.createNewFile()) {\n ZimbraLog.store.debug(\"writing to new file %s\", upFile.getName());\n file = upFile;\n } else {\n throw new IOException(\"unable to create new file\");\n }\n }\n }\n\n @Override\n protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {\n return new SimpleStreamingOutputStream(blobBuilder, file);\n }\n\n @Override\n protected long getRemoteSize() throws IOException {\n // size returned wrong to test getCurrentSize() mismatches\n return file.length() - 1;\n }\n\n @Override\n public Blob getBlob() throws IOException, ServiceException {\n return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());\n }\n }\n\n private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {\n\n private final FileOutputStream fos;\n\n public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {\n super(blobBuilder);\n this.fos = new FileOutputStream(file);\n }\n\n @Override\n protected void writeToExternal(byte[] b, int off, int len) throws IOException {\n fos.write(b, off, len);\n }\n }\n }\n}\n"} {"task_id": "Java_1670", "language": "Java", "task_type": "method_body", "source_file": "java/github/Zimbra/zm-mailbox/store/src/java-test/com/zimbra/cs/store/external/StoreManagerNegativeTest.java", "mask_start_position": 4408, "mask_end_position": 4444, "canonical_solution": "{\n return null;\n }", "pre_mask_code": "/*\n * ***** BEGIN LICENSE BLOCK *****\n * Zimbra Collaboration Suite Server\n *\n * ***** END LICENSE BLOCK *****\n */\npackage com.zimbra.cs.store.external;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Random;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport com.zimbra.common.service.ServiceException;\nimport com.zimbra.common.util.ZimbraLog;\nimport com.zimbra.cs.account.MockProvisioning;\nimport com.zimbra.cs.account.Provisioning;\nimport com.zimbra.cs.mailbox.Mailbox;\nimport com.zimbra.cs.mailbox.MailboxManager;\nimport com.zimbra.cs.mailbox.MailboxTestUtil;\nimport com.zimbra.cs.store.Blob;\nimport com.zimbra.cs.store.BlobBuilder;\nimport com.zimbra.cs.store.IncomingBlob;\nimport com.zimbra.cs.store.MailboxBlob;\nimport com.zimbra.cs.store.StagedBlob;\nimport com.zimbra.cs.store.StoreManager;\nimport com.zimbra.qa.unittest.TestUtil;\n\npublic class StoreManagerNegativeTest {\n\n static StoreManager originalStoreManager;\n\n @BeforeClass\n public static void init() throws Exception {\n MailboxTestUtil.initServer();\n MailboxTestUtil.initProvisioning();\n Provisioning.getInstance().createAccount(\"example@nnthink.com\", \"secret\", new HashMap());\n }\n\n @Before\n public void setUp() throws Exception {\n originalStoreManager = StoreManager.getInstance();\n StoreManager.setInstance(getStoreManager());\n StoreManager.getInstance().startup();\n }\n\n @After\n public void tearDown() throws Exception {\n StoreManager.getInstance().shutdown();\n StoreManager.setInstance(originalStoreManager);\n }\n\n protected StoreManager getStoreManager() {\n return new BrokenStreamingStoreManager();\n }\n\n @Test\n public void nullLocator() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n Blob blob = incoming.getBlob();\n Assert.assertEquals(\"blob size = incoming written\", bytes.length, blob.getRawSize());\n Assert.assertTrue(\"blob content = mime content\", TestUtil.bytesEqual(bytes, blob.getInputStream()));\n StagedBlob staged = sm.stage(blob, mbox);\n Assert.assertEquals(\"staged size = blob size\", blob.getRawSize(), staged.getSize());\n MailboxBlob mblob = sm.link(staged, mbox, 0, 0);\n Assert.assertEquals(\"link size = staged size\", staged.getSize(), mblob.getSize());\n try {\n mblob.getLocalBlob().getInputStream();\n Assert.fail(\"Expected IOException since locator is not handled correctly\");\n } catch (IOException io) {\n // expected\n } finally {\n sm.delete(mblob);\n }\n }\n\n @Test\n public void incorrectRemoteSize() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n try {\n incoming.getCurrentSize();\n Assert.fail(\"Expected exception since remote size is incorrect\");\n } catch (IOException ioe) {\n // expected\n }\n }\n\n private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {\n\n @Override\n public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {\n return null;\n }\n\n @Override\n public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {\n super.writeStreamToStore(in, actualSize, mbox);\n return null;\n }\n\n @Override\n public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException ", "post_mask_code": "\n\n @Override\n public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {\n return false;\n }\n\n @Override\n public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {\n return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);\n }\n\n private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {\n\n private final File file;\n\n public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {\n super(id, blobBuilder, ctx);\n String baseName = uploadDirectory + \"/upload-\" + id;\n String name = baseName;\n synchronized (this) {\n int count = 1;\n File upFile = new File(name + \".upl\");\n while (upFile.exists()) {\n name = baseName + \"_\" + count++;\n upFile = new File(name + \".upl\");\n }\n if (upFile.createNewFile()) {\n ZimbraLog.store.debug(\"writing to new file %s\", upFile.getName());\n file = upFile;\n } else {\n throw new IOException(\"unable to create new file\");\n }\n }\n }\n\n @Override\n protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {\n return new SimpleStreamingOutputStream(blobBuilder, file);\n }\n\n @Override\n protected long getRemoteSize() throws IOException {\n // size returned wrong to test getCurrentSize() mismatches\n return file.length() - 1;\n }\n\n @Override\n public Blob getBlob() throws IOException, ServiceException {\n return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());\n }\n }\n\n private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {\n\n private final FileOutputStream fos;\n\n public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {\n super(blobBuilder);\n this.fos = new FileOutputStream(file);\n }\n\n @Override\n protected void writeToExternal(byte[] b, int off, int len) throws IOException {\n fos.write(b, off, len);\n }\n }\n }\n}\n"} {"task_id": "Java_1671", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Zimbra/zm-mailbox/store/src/java-test/com/zimbra/cs/store/external/StoreManagerNegativeTest.java", "mask_start_position": 1963, "mask_end_position": 2236, "canonical_solution": "\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);", "pre_mask_code": "/*\n * ***** BEGIN LICENSE BLOCK *****\n * Zimbra Collaboration Suite Server\n *\n * ***** END LICENSE BLOCK *****\n */\npackage com.zimbra.cs.store.external;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Random;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport com.zimbra.common.service.ServiceException;\nimport com.zimbra.common.util.ZimbraLog;\nimport com.zimbra.cs.account.MockProvisioning;\nimport com.zimbra.cs.account.Provisioning;\nimport com.zimbra.cs.mailbox.Mailbox;\nimport com.zimbra.cs.mailbox.MailboxManager;\nimport com.zimbra.cs.mailbox.MailboxTestUtil;\nimport com.zimbra.cs.store.Blob;\nimport com.zimbra.cs.store.BlobBuilder;\nimport com.zimbra.cs.store.IncomingBlob;\nimport com.zimbra.cs.store.MailboxBlob;\nimport com.zimbra.cs.store.StagedBlob;\nimport com.zimbra.cs.store.StoreManager;\nimport com.zimbra.qa.unittest.TestUtil;\n\npublic class StoreManagerNegativeTest {\n\n static StoreManager originalStoreManager;\n\n @BeforeClass\n public static void init() throws Exception {\n MailboxTestUtil.initServer();\n MailboxTestUtil.initProvisioning();\n Provisioning.getInstance().createAccount(\"example@nnthink.com\", \"secret\", new HashMap());\n }\n\n @Before\n public void setUp() throws Exception {\n originalStoreManager = StoreManager.getInstance();\n StoreManager.setInstance(getStoreManager());\n StoreManager.getInstance().startup();\n }\n\n @After\n public void tearDown() throws Exception {\n StoreManager.getInstance().shutdown();\n StoreManager.setInstance(originalStoreManager);\n }\n\n protected StoreManager getStoreManager() {\n return new BrokenStreamingStoreManager();\n }\n\n @Test\n public void nullLocator() throws Exception {", "post_mask_code": "\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n Blob blob = incoming.getBlob();\n Assert.assertEquals(\"blob size = incoming written\", bytes.length, blob.getRawSize());\n Assert.assertTrue(\"blob content = mime content\", TestUtil.bytesEqual(bytes, blob.getInputStream()));\n StagedBlob staged = sm.stage(blob, mbox);\n Assert.assertEquals(\"staged size = blob size\", blob.getRawSize(), staged.getSize());\n MailboxBlob mblob = sm.link(staged, mbox, 0, 0);\n Assert.assertEquals(\"link size = staged size\", staged.getSize(), mblob.getSize());\n try {\n mblob.getLocalBlob().getInputStream();\n Assert.fail(\"Expected IOException since locator is not handled correctly\");\n } catch (IOException io) {\n // expected\n } finally {\n sm.delete(mblob);\n }\n }\n\n @Test\n public void incorrectRemoteSize() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n try {\n incoming.getCurrentSize();\n Assert.fail(\"Expected exception since remote size is incorrect\");\n } catch (IOException ioe) {\n // expected\n }\n }\n\n private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {\n\n @Override\n public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {\n return null;\n }\n\n @Override\n public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {\n super.writeStreamToStore(in, actualSize, mbox);\n return null;\n }\n\n @Override\n public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {\n return null;\n }\n\n @Override\n public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {\n return false;\n }\n\n @Override\n public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {\n return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);\n }\n\n private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {\n\n private final File file;\n\n public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {\n super(id, blobBuilder, ctx);\n String baseName = uploadDirectory + \"/upload-\" + id;\n String name = baseName;\n synchronized (this) {\n int count = 1;\n File upFile = new File(name + \".upl\");\n while (upFile.exists()) {\n name = baseName + \"_\" + count++;\n upFile = new File(name + \".upl\");\n }\n if (upFile.createNewFile()) {\n ZimbraLog.store.debug(\"writing to new file %s\", upFile.getName());\n file = upFile;\n } else {\n throw new IOException(\"unable to create new file\");\n }\n }\n }\n\n @Override\n protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {\n return new SimpleStreamingOutputStream(blobBuilder, file);\n }\n\n @Override\n protected long getRemoteSize() throws IOException {\n // size returned wrong to test getCurrentSize() mismatches\n return file.length() - 1;\n }\n\n @Override\n public Blob getBlob() throws IOException, ServiceException {\n return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());\n }\n }\n\n private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {\n\n private final FileOutputStream fos;\n\n public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {\n super(blobBuilder);\n this.fos = new FileOutputStream(file);\n }\n\n @Override\n protected void writeToExternal(byte[] b, int off, int len) throws IOException {\n fos.write(b, off, len);\n }\n }\n }\n}\n"} {"task_id": "Java_1672", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Zimbra/zm-mailbox/store/src/java-test/com/zimbra/cs/store/external/StoreManagerNegativeTest.java", "mask_start_position": 2245, "mask_end_position": 2634, "canonical_solution": "IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n Blob blob = incoming.getBlob();\n Assert.assertEquals(\"blob size = incoming written\", bytes.length, blob.getRawSize());\n Assert.assertTrue(\"blob content = mime content\", TestUtil.bytesEqual(bytes, blob.getInputStream()));", "pre_mask_code": "/*\n * ***** BEGIN LICENSE BLOCK *****\n * Zimbra Collaboration Suite Server\n *\n * ***** END LICENSE BLOCK *****\n */\npackage com.zimbra.cs.store.external;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Random;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport com.zimbra.common.service.ServiceException;\nimport com.zimbra.common.util.ZimbraLog;\nimport com.zimbra.cs.account.MockProvisioning;\nimport com.zimbra.cs.account.Provisioning;\nimport com.zimbra.cs.mailbox.Mailbox;\nimport com.zimbra.cs.mailbox.MailboxManager;\nimport com.zimbra.cs.mailbox.MailboxTestUtil;\nimport com.zimbra.cs.store.Blob;\nimport com.zimbra.cs.store.BlobBuilder;\nimport com.zimbra.cs.store.IncomingBlob;\nimport com.zimbra.cs.store.MailboxBlob;\nimport com.zimbra.cs.store.StagedBlob;\nimport com.zimbra.cs.store.StoreManager;\nimport com.zimbra.qa.unittest.TestUtil;\n\npublic class StoreManagerNegativeTest {\n\n static StoreManager originalStoreManager;\n\n @BeforeClass\n public static void init() throws Exception {\n MailboxTestUtil.initServer();\n MailboxTestUtil.initProvisioning();\n Provisioning.getInstance().createAccount(\"example@nnthink.com\", \"secret\", new HashMap());\n }\n\n @Before\n public void setUp() throws Exception {\n originalStoreManager = StoreManager.getInstance();\n StoreManager.setInstance(getStoreManager());\n StoreManager.getInstance().startup();\n }\n\n @After\n public void tearDown() throws Exception {\n StoreManager.getInstance().shutdown();\n StoreManager.setInstance(originalStoreManager);\n }\n\n protected StoreManager getStoreManager() {\n return new BrokenStreamingStoreManager();\n }\n\n @Test\n public void nullLocator() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);\n ", "post_mask_code": "\n StagedBlob staged = sm.stage(blob, mbox);\n Assert.assertEquals(\"staged size = blob size\", blob.getRawSize(), staged.getSize());\n MailboxBlob mblob = sm.link(staged, mbox, 0, 0);\n Assert.assertEquals(\"link size = staged size\", staged.getSize(), mblob.getSize());\n try {\n mblob.getLocalBlob().getInputStream();\n Assert.fail(\"Expected IOException since locator is not handled correctly\");\n } catch (IOException io) {\n // expected\n } finally {\n sm.delete(mblob);\n }\n }\n\n @Test\n public void incorrectRemoteSize() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n try {\n incoming.getCurrentSize();\n Assert.fail(\"Expected exception since remote size is incorrect\");\n } catch (IOException ioe) {\n // expected\n }\n }\n\n private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {\n\n @Override\n public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {\n return null;\n }\n\n @Override\n public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {\n super.writeStreamToStore(in, actualSize, mbox);\n return null;\n }\n\n @Override\n public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {\n return null;\n }\n\n @Override\n public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {\n return false;\n }\n\n @Override\n public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {\n return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);\n }\n\n private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {\n\n private final File file;\n\n public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {\n super(id, blobBuilder, ctx);\n String baseName = uploadDirectory + \"/upload-\" + id;\n String name = baseName;\n synchronized (this) {\n int count = 1;\n File upFile = new File(name + \".upl\");\n while (upFile.exists()) {\n name = baseName + \"_\" + count++;\n upFile = new File(name + \".upl\");\n }\n if (upFile.createNewFile()) {\n ZimbraLog.store.debug(\"writing to new file %s\", upFile.getName());\n file = upFile;\n } else {\n throw new IOException(\"unable to create new file\");\n }\n }\n }\n\n @Override\n protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {\n return new SimpleStreamingOutputStream(blobBuilder, file);\n }\n\n @Override\n protected long getRemoteSize() throws IOException {\n // size returned wrong to test getCurrentSize() mismatches\n return file.length() - 1;\n }\n\n @Override\n public Blob getBlob() throws IOException, ServiceException {\n return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());\n }\n }\n\n private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {\n\n private final FileOutputStream fos;\n\n public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {\n super(blobBuilder);\n this.fos = new FileOutputStream(file);\n }\n\n @Override\n protected void writeToExternal(byte[] b, int off, int len) throws IOException {\n fos.write(b, off, len);\n }\n }\n }\n}\n"} {"task_id": "Java_1673", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Zimbra/zm-mailbox/store/src/java-test/com/zimbra/cs/store/external/StoreManagerNegativeTest.java", "mask_start_position": 2643, "mask_end_position": 3203, "canonical_solution": "StagedBlob staged = sm.stage(blob, mbox);\n Assert.assertEquals(\"staged size = blob size\", blob.getRawSize(), staged.getSize());\n MailboxBlob mblob = sm.link(staged, mbox, 0, 0);\n Assert.assertEquals(\"link size = staged size\", staged.getSize(), mblob.getSize());\n try {\n mblob.getLocalBlob().getInputStream();\n Assert.fail(\"Expected IOException since locator is not handled correctly\");\n } catch (IOException io) {\n // expected\n } finally {\n sm.delete(mblob);\n }\n }", "pre_mask_code": "/*\n * ***** BEGIN LICENSE BLOCK *****\n * Zimbra Collaboration Suite Server\n *\n * ***** END LICENSE BLOCK *****\n */\npackage com.zimbra.cs.store.external;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Random;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport com.zimbra.common.service.ServiceException;\nimport com.zimbra.common.util.ZimbraLog;\nimport com.zimbra.cs.account.MockProvisioning;\nimport com.zimbra.cs.account.Provisioning;\nimport com.zimbra.cs.mailbox.Mailbox;\nimport com.zimbra.cs.mailbox.MailboxManager;\nimport com.zimbra.cs.mailbox.MailboxTestUtil;\nimport com.zimbra.cs.store.Blob;\nimport com.zimbra.cs.store.BlobBuilder;\nimport com.zimbra.cs.store.IncomingBlob;\nimport com.zimbra.cs.store.MailboxBlob;\nimport com.zimbra.cs.store.StagedBlob;\nimport com.zimbra.cs.store.StoreManager;\nimport com.zimbra.qa.unittest.TestUtil;\n\npublic class StoreManagerNegativeTest {\n\n static StoreManager originalStoreManager;\n\n @BeforeClass\n public static void init() throws Exception {\n MailboxTestUtil.initServer();\n MailboxTestUtil.initProvisioning();\n Provisioning.getInstance().createAccount(\"example@nnthink.com\", \"secret\", new HashMap());\n }\n\n @Before\n public void setUp() throws Exception {\n originalStoreManager = StoreManager.getInstance();\n StoreManager.setInstance(getStoreManager());\n StoreManager.getInstance().startup();\n }\n\n @After\n public void tearDown() throws Exception {\n StoreManager.getInstance().shutdown();\n StoreManager.setInstance(originalStoreManager);\n }\n\n protected StoreManager getStoreManager() {\n return new BrokenStreamingStoreManager();\n }\n\n @Test\n public void nullLocator() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n Blob blob = incoming.getBlob();\n Assert.assertEquals(\"blob size = incoming written\", bytes.length, blob.getRawSize());\n Assert.assertTrue(\"blob content = mime content\", TestUtil.bytesEqual(bytes, blob.getInputStream()));\n ", "post_mask_code": "\n\n @Test\n public void incorrectRemoteSize() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n try {\n incoming.getCurrentSize();\n Assert.fail(\"Expected exception since remote size is incorrect\");\n } catch (IOException ioe) {\n // expected\n }\n }\n\n private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {\n\n @Override\n public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {\n return null;\n }\n\n @Override\n public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {\n super.writeStreamToStore(in, actualSize, mbox);\n return null;\n }\n\n @Override\n public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {\n return null;\n }\n\n @Override\n public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {\n return false;\n }\n\n @Override\n public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {\n return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);\n }\n\n private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {\n\n private final File file;\n\n public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {\n super(id, blobBuilder, ctx);\n String baseName = uploadDirectory + \"/upload-\" + id;\n String name = baseName;\n synchronized (this) {\n int count = 1;\n File upFile = new File(name + \".upl\");\n while (upFile.exists()) {\n name = baseName + \"_\" + count++;\n upFile = new File(name + \".upl\");\n }\n if (upFile.createNewFile()) {\n ZimbraLog.store.debug(\"writing to new file %s\", upFile.getName());\n file = upFile;\n } else {\n throw new IOException(\"unable to create new file\");\n }\n }\n }\n\n @Override\n protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {\n return new SimpleStreamingOutputStream(blobBuilder, file);\n }\n\n @Override\n protected long getRemoteSize() throws IOException {\n // size returned wrong to test getCurrentSize() mismatches\n return file.length() - 1;\n }\n\n @Override\n public Blob getBlob() throws IOException, ServiceException {\n return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());\n }\n }\n\n private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {\n\n private final FileOutputStream fos;\n\n public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {\n super(blobBuilder);\n this.fos = new FileOutputStream(file);\n }\n\n @Override\n protected void writeToExternal(byte[] b, int off, int len) throws IOException {\n fos.write(b, off, len);\n }\n }\n }\n}\n"} {"task_id": "Java_1674", "language": "Java", "task_type": "single_line", "source_file": "java/github/Zimbra/zm-mailbox/store/src/java-test/com/zimbra/cs/store/external/StoreManagerNegativeTest.java", "mask_start_position": 2847, "mask_end_position": 2925, "canonical_solution": "rt.assertEquals(\"link size = staged size\", staged.getSize(), mblob.getSize());", "pre_mask_code": "/*\n * ***** BEGIN LICENSE BLOCK *****\n * Zimbra Collaboration Suite Server\n *\n * ***** END LICENSE BLOCK *****\n */\npackage com.zimbra.cs.store.external;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Random;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport com.zimbra.common.service.ServiceException;\nimport com.zimbra.common.util.ZimbraLog;\nimport com.zimbra.cs.account.MockProvisioning;\nimport com.zimbra.cs.account.Provisioning;\nimport com.zimbra.cs.mailbox.Mailbox;\nimport com.zimbra.cs.mailbox.MailboxManager;\nimport com.zimbra.cs.mailbox.MailboxTestUtil;\nimport com.zimbra.cs.store.Blob;\nimport com.zimbra.cs.store.BlobBuilder;\nimport com.zimbra.cs.store.IncomingBlob;\nimport com.zimbra.cs.store.MailboxBlob;\nimport com.zimbra.cs.store.StagedBlob;\nimport com.zimbra.cs.store.StoreManager;\nimport com.zimbra.qa.unittest.TestUtil;\n\npublic class StoreManagerNegativeTest {\n\n static StoreManager originalStoreManager;\n\n @BeforeClass\n public static void init() throws Exception {\n MailboxTestUtil.initServer();\n MailboxTestUtil.initProvisioning();\n Provisioning.getInstance().createAccount(\"example@nnthink.com\", \"secret\", new HashMap());\n }\n\n @Before\n public void setUp() throws Exception {\n originalStoreManager = StoreManager.getInstance();\n StoreManager.setInstance(getStoreManager());\n StoreManager.getInstance().startup();\n }\n\n @After\n public void tearDown() throws Exception {\n StoreManager.getInstance().shutdown();\n StoreManager.setInstance(originalStoreManager);\n }\n\n protected StoreManager getStoreManager() {\n return new BrokenStreamingStoreManager();\n }\n\n @Test\n public void nullLocator() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n Blob blob = incoming.getBlob();\n Assert.assertEquals(\"blob size = incoming written\", bytes.length, blob.getRawSize());\n Assert.assertTrue(\"blob content = mime content\", TestUtil.bytesEqual(bytes, blob.getInputStream()));\n StagedBlob staged = sm.stage(blob, mbox);\n Assert.assertEquals(\"staged size = blob size\", blob.getRawSize(), staged.getSize());\n MailboxBlob mblob = sm.link(staged, mbox, 0, 0);\n Asse", "post_mask_code": "\n try {\n mblob.getLocalBlob().getInputStream();\n Assert.fail(\"Expected IOException since locator is not handled correctly\");\n } catch (IOException io) {\n // expected\n } finally {\n sm.delete(mblob);\n }\n }\n\n @Test\n public void incorrectRemoteSize() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n try {\n incoming.getCurrentSize();\n Assert.fail(\"Expected exception since remote size is incorrect\");\n } catch (IOException ioe) {\n // expected\n }\n }\n\n private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {\n\n @Override\n public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {\n return null;\n }\n\n @Override\n public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {\n super.writeStreamToStore(in, actualSize, mbox);\n return null;\n }\n\n @Override\n public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {\n return null;\n }\n\n @Override\n public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {\n return false;\n }\n\n @Override\n public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {\n return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);\n }\n\n private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {\n\n private final File file;\n\n public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {\n super(id, blobBuilder, ctx);\n String baseName = uploadDirectory + \"/upload-\" + id;\n String name = baseName;\n synchronized (this) {\n int count = 1;\n File upFile = new File(name + \".upl\");\n while (upFile.exists()) {\n name = baseName + \"_\" + count++;\n upFile = new File(name + \".upl\");\n }\n if (upFile.createNewFile()) {\n ZimbraLog.store.debug(\"writing to new file %s\", upFile.getName());\n file = upFile;\n } else {\n throw new IOException(\"unable to create new file\");\n }\n }\n }\n\n @Override\n protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {\n return new SimpleStreamingOutputStream(blobBuilder, file);\n }\n\n @Override\n protected long getRemoteSize() throws IOException {\n // size returned wrong to test getCurrentSize() mismatches\n return file.length() - 1;\n }\n\n @Override\n public Blob getBlob() throws IOException, ServiceException {\n return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());\n }\n }\n\n private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {\n\n private final FileOutputStream fos;\n\n public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {\n super(blobBuilder);\n this.fos = new FileOutputStream(file);\n }\n\n @Override\n protected void writeToExternal(byte[] b, int off, int len) throws IOException {\n fos.write(b, off, len);\n }\n }\n }\n}\n"} {"task_id": "Java_1675", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Zimbra/zm-mailbox/store/src/java-test/com/zimbra/cs/store/external/StoreManagerNegativeTest.java", "mask_start_position": 5576, "mask_end_position": 5862, "canonical_solution": "if (upFile.createNewFile()) {\n ZimbraLog.store.debug(\"writing to new file %s\", upFile.getName());\n file = upFile;\n } else {\n throw new IOException(\"unable to create new file\");\n }", "pre_mask_code": "/*\n * ***** BEGIN LICENSE BLOCK *****\n * Zimbra Collaboration Suite Server\n *\n * ***** END LICENSE BLOCK *****\n */\npackage com.zimbra.cs.store.external;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Random;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport com.zimbra.common.service.ServiceException;\nimport com.zimbra.common.util.ZimbraLog;\nimport com.zimbra.cs.account.MockProvisioning;\nimport com.zimbra.cs.account.Provisioning;\nimport com.zimbra.cs.mailbox.Mailbox;\nimport com.zimbra.cs.mailbox.MailboxManager;\nimport com.zimbra.cs.mailbox.MailboxTestUtil;\nimport com.zimbra.cs.store.Blob;\nimport com.zimbra.cs.store.BlobBuilder;\nimport com.zimbra.cs.store.IncomingBlob;\nimport com.zimbra.cs.store.MailboxBlob;\nimport com.zimbra.cs.store.StagedBlob;\nimport com.zimbra.cs.store.StoreManager;\nimport com.zimbra.qa.unittest.TestUtil;\n\npublic class StoreManagerNegativeTest {\n\n static StoreManager originalStoreManager;\n\n @BeforeClass\n public static void init() throws Exception {\n MailboxTestUtil.initServer();\n MailboxTestUtil.initProvisioning();\n Provisioning.getInstance().createAccount(\"example@nnthink.com\", \"secret\", new HashMap());\n }\n\n @Before\n public void setUp() throws Exception {\n originalStoreManager = StoreManager.getInstance();\n StoreManager.setInstance(getStoreManager());\n StoreManager.getInstance().startup();\n }\n\n @After\n public void tearDown() throws Exception {\n StoreManager.getInstance().shutdown();\n StoreManager.setInstance(originalStoreManager);\n }\n\n protected StoreManager getStoreManager() {\n return new BrokenStreamingStoreManager();\n }\n\n @Test\n public void nullLocator() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n Blob blob = incoming.getBlob();\n Assert.assertEquals(\"blob size = incoming written\", bytes.length, blob.getRawSize());\n Assert.assertTrue(\"blob content = mime content\", TestUtil.bytesEqual(bytes, blob.getInputStream()));\n StagedBlob staged = sm.stage(blob, mbox);\n Assert.assertEquals(\"staged size = blob size\", blob.getRawSize(), staged.getSize());\n MailboxBlob mblob = sm.link(staged, mbox, 0, 0);\n Assert.assertEquals(\"link size = staged size\", staged.getSize(), mblob.getSize());\n try {\n mblob.getLocalBlob().getInputStream();\n Assert.fail(\"Expected IOException since locator is not handled correctly\");\n } catch (IOException io) {\n // expected\n } finally {\n sm.delete(mblob);\n }\n }\n\n @Test\n public void incorrectRemoteSize() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n try {\n incoming.getCurrentSize();\n Assert.fail(\"Expected exception since remote size is incorrect\");\n } catch (IOException ioe) {\n // expected\n }\n }\n\n private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {\n\n @Override\n public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {\n return null;\n }\n\n @Override\n public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {\n super.writeStreamToStore(in, actualSize, mbox);\n return null;\n }\n\n @Override\n public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {\n return null;\n }\n\n @Override\n public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {\n return false;\n }\n\n @Override\n public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {\n return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);\n }\n\n private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {\n\n private final File file;\n\n public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {\n super(id, blobBuilder, ctx);\n String baseName = uploadDirectory + \"/upload-\" + id;\n String name = baseName;\n synchronized (this) {\n int count = 1;\n File upFile = new File(name + \".upl\");\n while (upFile.exists()) {\n name = baseName + \"_\" + count++;\n upFile = new File(name + \".upl\");\n }\n ", "post_mask_code": "\n }\n }\n\n @Override\n protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {\n return new SimpleStreamingOutputStream(blobBuilder, file);\n }\n\n @Override\n protected long getRemoteSize() throws IOException {\n // size returned wrong to test getCurrentSize() mismatches\n return file.length() - 1;\n }\n\n @Override\n public Blob getBlob() throws IOException, ServiceException {\n return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());\n }\n }\n\n private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {\n\n private final FileOutputStream fos;\n\n public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {\n super(blobBuilder);\n this.fos = new FileOutputStream(file);\n }\n\n @Override\n protected void writeToExternal(byte[] b, int off, int len) throws IOException {\n fos.write(b, off, len);\n }\n }\n }\n}\n"} {"task_id": "Java_1676", "language": "Java", "task_type": "while_statement", "source_file": "java/github/Zimbra/zm-mailbox/store/src/java-test/com/zimbra/cs/store/external/StoreManagerNegativeTest.java", "mask_start_position": 5393, "mask_end_position": 5555, "canonical_solution": "while (upFile.exists()) {\n name = baseName + \"_\" + count++;\n upFile = new File(name + \".upl\");\n }", "pre_mask_code": "/*\n * ***** BEGIN LICENSE BLOCK *****\n * Zimbra Collaboration Suite Server\n *\n * ***** END LICENSE BLOCK *****\n */\npackage com.zimbra.cs.store.external;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Random;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport com.zimbra.common.service.ServiceException;\nimport com.zimbra.common.util.ZimbraLog;\nimport com.zimbra.cs.account.MockProvisioning;\nimport com.zimbra.cs.account.Provisioning;\nimport com.zimbra.cs.mailbox.Mailbox;\nimport com.zimbra.cs.mailbox.MailboxManager;\nimport com.zimbra.cs.mailbox.MailboxTestUtil;\nimport com.zimbra.cs.store.Blob;\nimport com.zimbra.cs.store.BlobBuilder;\nimport com.zimbra.cs.store.IncomingBlob;\nimport com.zimbra.cs.store.MailboxBlob;\nimport com.zimbra.cs.store.StagedBlob;\nimport com.zimbra.cs.store.StoreManager;\nimport com.zimbra.qa.unittest.TestUtil;\n\npublic class StoreManagerNegativeTest {\n\n static StoreManager originalStoreManager;\n\n @BeforeClass\n public static void init() throws Exception {\n MailboxTestUtil.initServer();\n MailboxTestUtil.initProvisioning();\n Provisioning.getInstance().createAccount(\"example@nnthink.com\", \"secret\", new HashMap());\n }\n\n @Before\n public void setUp() throws Exception {\n originalStoreManager = StoreManager.getInstance();\n StoreManager.setInstance(getStoreManager());\n StoreManager.getInstance().startup();\n }\n\n @After\n public void tearDown() throws Exception {\n StoreManager.getInstance().shutdown();\n StoreManager.setInstance(originalStoreManager);\n }\n\n protected StoreManager getStoreManager() {\n return new BrokenStreamingStoreManager();\n }\n\n @Test\n public void nullLocator() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n Blob blob = incoming.getBlob();\n Assert.assertEquals(\"blob size = incoming written\", bytes.length, blob.getRawSize());\n Assert.assertTrue(\"blob content = mime content\", TestUtil.bytesEqual(bytes, blob.getInputStream()));\n StagedBlob staged = sm.stage(blob, mbox);\n Assert.assertEquals(\"staged size = blob size\", blob.getRawSize(), staged.getSize());\n MailboxBlob mblob = sm.link(staged, mbox, 0, 0);\n Assert.assertEquals(\"link size = staged size\", staged.getSize(), mblob.getSize());\n try {\n mblob.getLocalBlob().getInputStream();\n Assert.fail(\"Expected IOException since locator is not handled correctly\");\n } catch (IOException io) {\n // expected\n } finally {\n sm.delete(mblob);\n }\n }\n\n @Test\n public void incorrectRemoteSize() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n try {\n incoming.getCurrentSize();\n Assert.fail(\"Expected exception since remote size is incorrect\");\n } catch (IOException ioe) {\n // expected\n }\n }\n\n private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {\n\n @Override\n public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {\n return null;\n }\n\n @Override\n public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {\n super.writeStreamToStore(in, actualSize, mbox);\n return null;\n }\n\n @Override\n public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {\n return null;\n }\n\n @Override\n public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {\n return false;\n }\n\n @Override\n public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {\n return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);\n }\n\n private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {\n\n private final File file;\n\n public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {\n super(id, blobBuilder, ctx);\n String baseName = uploadDirectory + \"/upload-\" + id;\n String name = baseName;\n synchronized (this) {\n int count = 1;\n File upFile = new File(name + \".upl\");\n ", "post_mask_code": "\n if (upFile.createNewFile()) {\n ZimbraLog.store.debug(\"writing to new file %s\", upFile.getName());\n file = upFile;\n } else {\n throw new IOException(\"unable to create new file\");\n }\n }\n }\n\n @Override\n protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {\n return new SimpleStreamingOutputStream(blobBuilder, file);\n }\n\n @Override\n protected long getRemoteSize() throws IOException {\n // size returned wrong to test getCurrentSize() mismatches\n return file.length() - 1;\n }\n\n @Override\n public Blob getBlob() throws IOException, ServiceException {\n return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());\n }\n }\n\n private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {\n\n private final FileOutputStream fos;\n\n public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {\n super(blobBuilder);\n this.fos = new FileOutputStream(file);\n }\n\n @Override\n protected void writeToExternal(byte[] b, int off, int len) throws IOException {\n fos.write(b, off, len);\n }\n }\n }\n}\n"} {"task_id": "Java_1677", "language": "Java", "task_type": "try_statement", "source_file": "java/github/Zimbra/zm-mailbox/store/src/java-test/com/zimbra/cs/store/external/StoreManagerNegativeTest.java", "mask_start_position": 2934, "mask_end_position": 3197, "canonical_solution": "try {\n mblob.getLocalBlob().getInputStream();\n Assert.fail(\"Expected IOException since locator is not handled correctly\");\n } catch (IOException io) {\n // expected\n } finally {\n sm.delete(mblob);\n }", "pre_mask_code": "/*\n * ***** BEGIN LICENSE BLOCK *****\n * Zimbra Collaboration Suite Server\n *\n * ***** END LICENSE BLOCK *****\n */\npackage com.zimbra.cs.store.external;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.HashMap;\nimport java.util.Random;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport com.zimbra.common.service.ServiceException;\nimport com.zimbra.common.util.ZimbraLog;\nimport com.zimbra.cs.account.MockProvisioning;\nimport com.zimbra.cs.account.Provisioning;\nimport com.zimbra.cs.mailbox.Mailbox;\nimport com.zimbra.cs.mailbox.MailboxManager;\nimport com.zimbra.cs.mailbox.MailboxTestUtil;\nimport com.zimbra.cs.store.Blob;\nimport com.zimbra.cs.store.BlobBuilder;\nimport com.zimbra.cs.store.IncomingBlob;\nimport com.zimbra.cs.store.MailboxBlob;\nimport com.zimbra.cs.store.StagedBlob;\nimport com.zimbra.cs.store.StoreManager;\nimport com.zimbra.qa.unittest.TestUtil;\n\npublic class StoreManagerNegativeTest {\n\n static StoreManager originalStoreManager;\n\n @BeforeClass\n public static void init() throws Exception {\n MailboxTestUtil.initServer();\n MailboxTestUtil.initProvisioning();\n Provisioning.getInstance().createAccount(\"example@nnthink.com\", \"secret\", new HashMap());\n }\n\n @Before\n public void setUp() throws Exception {\n originalStoreManager = StoreManager.getInstance();\n StoreManager.setInstance(getStoreManager());\n StoreManager.getInstance().startup();\n }\n\n @After\n public void tearDown() throws Exception {\n StoreManager.getInstance().shutdown();\n StoreManager.setInstance(originalStoreManager);\n }\n\n protected StoreManager getStoreManager() {\n return new BrokenStreamingStoreManager();\n }\n\n @Test\n public void nullLocator() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n Blob blob = incoming.getBlob();\n Assert.assertEquals(\"blob size = incoming written\", bytes.length, blob.getRawSize());\n Assert.assertTrue(\"blob content = mime content\", TestUtil.bytesEqual(bytes, blob.getInputStream()));\n StagedBlob staged = sm.stage(blob, mbox);\n Assert.assertEquals(\"staged size = blob size\", blob.getRawSize(), staged.getSize());\n MailboxBlob mblob = sm.link(staged, mbox, 0, 0);\n Assert.assertEquals(\"link size = staged size\", staged.getSize(), mblob.getSize());\n ", "post_mask_code": "\n }\n\n @Test\n public void incorrectRemoteSize() throws Exception {\n Random rand = new Random();\n byte[] bytes = new byte[10000];\n rand.nextBytes(bytes);\n StoreManager sm = StoreManager.getInstance();\n IncomingBlob incoming = sm.newIncomingBlob(\"foo\", null);\n OutputStream out = incoming.getAppendingOutputStream();\n out.write(bytes);\n try {\n incoming.getCurrentSize();\n Assert.fail(\"Expected exception since remote size is incorrect\");\n } catch (IOException ioe) {\n // expected\n }\n }\n\n private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {\n\n @Override\n public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {\n return null;\n }\n\n @Override\n public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {\n super.writeStreamToStore(in, actualSize, mbox);\n return null;\n }\n\n @Override\n public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {\n return null;\n }\n\n @Override\n public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {\n return false;\n }\n\n @Override\n public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {\n return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);\n }\n\n private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {\n\n private final File file;\n\n public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {\n super(id, blobBuilder, ctx);\n String baseName = uploadDirectory + \"/upload-\" + id;\n String name = baseName;\n synchronized (this) {\n int count = 1;\n File upFile = new File(name + \".upl\");\n while (upFile.exists()) {\n name = baseName + \"_\" + count++;\n upFile = new File(name + \".upl\");\n }\n if (upFile.createNewFile()) {\n ZimbraLog.store.debug(\"writing to new file %s\", upFile.getName());\n file = upFile;\n } else {\n throw new IOException(\"unable to create new file\");\n }\n }\n }\n\n @Override\n protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {\n return new SimpleStreamingOutputStream(blobBuilder, file);\n }\n\n @Override\n protected long getRemoteSize() throws IOException {\n // size returned wrong to test getCurrentSize() mismatches\n return file.length() - 1;\n }\n\n @Override\n public Blob getBlob() throws IOException, ServiceException {\n return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());\n }\n }\n\n private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {\n\n private final FileOutputStream fos;\n\n public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {\n super(blobBuilder);\n this.fos = new FileOutputStream(file);\n }\n\n @Override\n protected void writeToExternal(byte[] b, int off, int len) throws IOException {\n fos.write(b, off, len);\n }\n }\n }\n}\n"} {"task_id": "Java_1678", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jbosstm/narayana/qa/tests/src/org/jboss/jbossts/qa/RawResources02Clients2/Client095.java", "mask_start_position": 1045, "mask_end_position": 1084, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source\n * as indicated by the @author tags.\n * See the copyright.txt in the distribution for a\n * full listing of individual contributors.\n *\n * @author JBoss Inc.\n */\n// Newcastle upon Tyne,\n// Tyne and Wear,\npackage org.jboss.jbossts.qa.RawResources02Clients2;\n\n/*\n *\n * HP Arjuna Labs,\n * Newcastle upon Tyne,\n * Tyne and Wear,\n * UK.\n *\n * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $\n */\n/*\n * Try to get around the differences between Ansi CPP and\n * K&R cpp with concatenation.\n */\n/*\n *\n * HP Arjuna Labs,\n * Newcastle upon Tyne,\n * Tyne and Wear,\n * UK.\n *\n * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $\n */\nimport org.jboss.jbossts.qa.RawResources02.*;\nimport org.jboss.jbossts.qa.Utils.OAInterface;\nimport org.jboss.jbossts.qa.Utils.ORBInterface;\nimport org.jboss.jbossts.qa.Utils.OTS;\nimport org.jboss.jbossts.qa.Utils.ServerIORStore;\nimport org.omg.CosTransactions.HeuristicHazard;\nimport org.omg.CosTransactions.HeuristicMixed;\n\npublic class Client095 {\n\n ", "post_mask_code": "{\n try {\n ORBInterface.initORB(args, null);\n OAInterface.initOA();\n String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]);\n Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1));\n String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]);\n Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2));\n ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1];\n resourceBehaviors1[0] = new ResourceBehavior();\n resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorRaiseHeuristicMixed;\n resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;\n resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;\n resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;\n ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1];\n resourceBehaviors2[0] = new ResourceBehavior();\n resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteCommit;\n resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorRaiseHeuristicMixed;\n resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;\n resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;\n boolean correct = true;\n OTS.current().begin();\n service1.oper(resourceBehaviors1, OTS.current().get_control());\n service2.oper(resourceBehaviors2, OTS.current().get_control());\n try {\n OTS.current().commit(true);\n System.err.println(\"Commit succeeded when it shouldn't\");\n correct = false;\n } catch (HeuristicMixed heuristicMixed) {\n } catch (HeuristicHazard heuristicHazard) {\n }\n correct = correct && service1.is_correct() && service2.is_correct();\n if (!correct) {\n System.err.println(\"service1.is_correct() or service2.is_correct() returned false\");\n }\n ResourceTrace resourceTrace1 = service1.get_resource_trace(0);\n ResourceTrace resourceTrace2 = service2.get_resource_trace(0);\n correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareForget);\n correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepareRollbackForget) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback));\n if (correct) {\n System.out.println(\"Passed\");\n } else {\n System.out.println(\"Failed\");\n }\n } catch (Exception exception) {\n System.err.println(\"Client095.main: \" + exception);\n exception.printStackTrace(System.err);\n System.out.println(\"Failed\");\n }\n try {\n OAInterface.shutdownOA();\n ORBInterface.shutdownORB();\n } catch (Exception exception) {\n System.err.println(\"Client095.main: \" + exception);\n exception.printStackTrace(System.err);\n }\n }\n}\n"} {"task_id": "Java_1679", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/jbosstm/narayana/qa/tests/src/org/jboss/jbossts/qa/RawResources02Clients2/Client095.java", "mask_start_position": 1085, "mask_end_position": 4143, "canonical_solution": "\n try {\n ORBInterface.initORB(args, null);\n OAInterface.initOA();\n String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]);\n Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1));\n String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]);\n Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2));\n ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1];\n resourceBehaviors1[0] = new ResourceBehavior();\n resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorRaiseHeuristicMixed;\n resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;\n resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;\n resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;\n ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1];\n resourceBehaviors2[0] = new ResourceBehavior();\n resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteCommit;\n resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorRaiseHeuristicMixed;\n resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;\n resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;\n boolean correct = true;\n OTS.current().begin();\n service1.oper(resourceBehaviors1, OTS.current().get_control());\n service2.oper(resourceBehaviors2, OTS.current().get_control());\n try {\n OTS.current().commit(true);\n System.err.println(\"Commit succeeded when it shouldn't\");\n correct = false;\n } catch (HeuristicMixed heuristicMixed) {\n } catch (HeuristicHazard heuristicHazard) {\n }\n correct = correct && service1.is_correct() && service2.is_correct();\n if (!correct) {\n System.err.println(\"service1.is_correct() or service2.is_correct() returned false\");\n }\n ResourceTrace resourceTrace1 = service1.get_resource_trace(0);\n ResourceTrace resourceTrace2 = service2.get_resource_trace(0);\n correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareForget);\n correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepareRollbackForget) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback));\n if (correct) {\n System.out.println(\"Passed\");\n } else {\n System.out.println(\"Failed\");\n }\n } catch (Exception exception) {\n System.err.println(\"Client095.main: \" + exception);\n exception.printStackTrace(System.err);\n System.out.println(\"Failed\");\n }", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source\n * as indicated by the @author tags.\n * See the copyright.txt in the distribution for a\n * full listing of individual contributors.\n *\n * @author JBoss Inc.\n */\n// Newcastle upon Tyne,\n// Tyne and Wear,\npackage org.jboss.jbossts.qa.RawResources02Clients2;\n\n/*\n *\n * HP Arjuna Labs,\n * Newcastle upon Tyne,\n * Tyne and Wear,\n * UK.\n *\n * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $\n */\n/*\n * Try to get around the differences between Ansi CPP and\n * K&R cpp with concatenation.\n */\n/*\n *\n * HP Arjuna Labs,\n * Newcastle upon Tyne,\n * Tyne and Wear,\n * UK.\n *\n * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $\n */\nimport org.jboss.jbossts.qa.RawResources02.*;\nimport org.jboss.jbossts.qa.Utils.OAInterface;\nimport org.jboss.jbossts.qa.Utils.ORBInterface;\nimport org.jboss.jbossts.qa.Utils.OTS;\nimport org.jboss.jbossts.qa.Utils.ServerIORStore;\nimport org.omg.CosTransactions.HeuristicHazard;\nimport org.omg.CosTransactions.HeuristicMixed;\n\npublic class Client095 {\n\n public static void main(String[] args) {", "post_mask_code": "\n try {\n OAInterface.shutdownOA();\n ORBInterface.shutdownORB();\n } catch (Exception exception) {\n System.err.println(\"Client095.main: \" + exception);\n exception.printStackTrace(System.err);\n }\n }\n}\n"} {"task_id": "Java_1680", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/jbosstm/narayana/qa/tests/src/org/jboss/jbossts/qa/RawResources02Clients2/Client095.java", "mask_start_position": 4152, "mask_end_position": 4400, "canonical_solution": "try {\n OAInterface.shutdownOA();\n ORBInterface.shutdownORB();\n } catch (Exception exception) {\n System.err.println(\"Client095.main: \" + exception);\n exception.printStackTrace(System.err);\n }", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source\n * as indicated by the @author tags.\n * See the copyright.txt in the distribution for a\n * full listing of individual contributors.\n *\n * @author JBoss Inc.\n */\n// Newcastle upon Tyne,\n// Tyne and Wear,\npackage org.jboss.jbossts.qa.RawResources02Clients2;\n\n/*\n *\n * HP Arjuna Labs,\n * Newcastle upon Tyne,\n * Tyne and Wear,\n * UK.\n *\n * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $\n */\n/*\n * Try to get around the differences between Ansi CPP and\n * K&R cpp with concatenation.\n */\n/*\n *\n * HP Arjuna Labs,\n * Newcastle upon Tyne,\n * Tyne and Wear,\n * UK.\n *\n * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $\n */\nimport org.jboss.jbossts.qa.RawResources02.*;\nimport org.jboss.jbossts.qa.Utils.OAInterface;\nimport org.jboss.jbossts.qa.Utils.ORBInterface;\nimport org.jboss.jbossts.qa.Utils.OTS;\nimport org.jboss.jbossts.qa.Utils.ServerIORStore;\nimport org.omg.CosTransactions.HeuristicHazard;\nimport org.omg.CosTransactions.HeuristicMixed;\n\npublic class Client095 {\n\n public static void main(String[] args) {\n try {\n ORBInterface.initORB(args, null);\n OAInterface.initOA();\n String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]);\n Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1));\n String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]);\n Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2));\n ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1];\n resourceBehaviors1[0] = new ResourceBehavior();\n resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorRaiseHeuristicMixed;\n resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;\n resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;\n resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;\n ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1];\n resourceBehaviors2[0] = new ResourceBehavior();\n resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteCommit;\n resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorRaiseHeuristicMixed;\n resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;\n resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;\n boolean correct = true;\n OTS.current().begin();\n service1.oper(resourceBehaviors1, OTS.current().get_control());\n service2.oper(resourceBehaviors2, OTS.current().get_control());\n try {\n OTS.current().commit(true);\n System.err.println(\"Commit succeeded when it shouldn't\");\n correct = false;\n } catch (HeuristicMixed heuristicMixed) {\n } catch (HeuristicHazard heuristicHazard) {\n }\n correct = correct && service1.is_correct() && service2.is_correct();\n if (!correct) {\n System.err.println(\"service1.is_correct() or service2.is_correct() returned false\");\n }\n ResourceTrace resourceTrace1 = service1.get_resource_trace(0);\n ResourceTrace resourceTrace2 = service2.get_resource_trace(0);\n correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareForget);\n correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepareRollbackForget) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback));\n if (correct) {\n System.out.println(\"Passed\");\n } else {\n System.out.println(\"Failed\");\n }\n } catch (Exception exception) {\n System.err.println(\"Client095.main: \" + exception);\n exception.printStackTrace(System.err);\n System.out.println(\"Failed\");\n }\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1681", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/jbosstm/narayana/qa/tests/src/org/jboss/jbossts/qa/RawResources02Clients2/Client095.java", "mask_start_position": 4405, "mask_end_position": 4406, "canonical_solution": "}", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source\n * as indicated by the @author tags.\n * See the copyright.txt in the distribution for a\n * full listing of individual contributors.\n *\n * @author JBoss Inc.\n */\n// Newcastle upon Tyne,\n// Tyne and Wear,\npackage org.jboss.jbossts.qa.RawResources02Clients2;\n\n/*\n *\n * HP Arjuna Labs,\n * Newcastle upon Tyne,\n * Tyne and Wear,\n * UK.\n *\n * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $\n */\n/*\n * Try to get around the differences between Ansi CPP and\n * K&R cpp with concatenation.\n */\n/*\n *\n * HP Arjuna Labs,\n * Newcastle upon Tyne,\n * Tyne and Wear,\n * UK.\n *\n * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $\n */\nimport org.jboss.jbossts.qa.RawResources02.*;\nimport org.jboss.jbossts.qa.Utils.OAInterface;\nimport org.jboss.jbossts.qa.Utils.ORBInterface;\nimport org.jboss.jbossts.qa.Utils.OTS;\nimport org.jboss.jbossts.qa.Utils.ServerIORStore;\nimport org.omg.CosTransactions.HeuristicHazard;\nimport org.omg.CosTransactions.HeuristicMixed;\n\npublic class Client095 {\n\n public static void main(String[] args) {\n try {\n ORBInterface.initORB(args, null);\n OAInterface.initOA();\n String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]);\n Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1));\n String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]);\n Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2));\n ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1];\n resourceBehaviors1[0] = new ResourceBehavior();\n resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorRaiseHeuristicMixed;\n resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;\n resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;\n resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;\n ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1];\n resourceBehaviors2[0] = new ResourceBehavior();\n resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteCommit;\n resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorRaiseHeuristicMixed;\n resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;\n resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;\n boolean correct = true;\n OTS.current().begin();\n service1.oper(resourceBehaviors1, OTS.current().get_control());\n service2.oper(resourceBehaviors2, OTS.current().get_control());\n try {\n OTS.current().commit(true);\n System.err.println(\"Commit succeeded when it shouldn't\");\n correct = false;\n } catch (HeuristicMixed heuristicMixed) {\n } catch (HeuristicHazard heuristicHazard) {\n }\n correct = correct && service1.is_correct() && service2.is_correct();\n if (!correct) {\n System.err.println(\"service1.is_correct() or service2.is_correct() returned false\");\n }\n ResourceTrace resourceTrace1 = service1.get_resource_trace(0);\n ResourceTrace resourceTrace2 = service2.get_resource_trace(0);\n correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareForget);\n correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepareRollbackForget) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback));\n if (correct) {\n System.out.println(\"Passed\");\n } else {\n System.out.println(\"Failed\");\n }\n } catch (Exception exception) {\n System.err.println(\"Client095.main: \" + exception);\n exception.printStackTrace(System.err);\n System.out.println(\"Failed\");\n }\n try {\n OAInterface.shutdownOA();\n ORBInterface.shutdownORB();\n } catch (Exception exception) {\n System.err.println(\"Client095.main: \" + exception);\n exception.printStackTrace(System.err);\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1682", "language": "Java", "task_type": "if_statement", "source_file": "java/github/jbosstm/narayana/qa/tests/src/org/jboss/jbossts/qa/RawResources02Clients2/Client095.java", "mask_start_position": 3795, "mask_end_position": 3936, "canonical_solution": "if (correct) {\n System.out.println(\"Passed\");\n } else {\n System.out.println(\"Failed\");\n }", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source\n * as indicated by the @author tags.\n * See the copyright.txt in the distribution for a\n * full listing of individual contributors.\n *\n * @author JBoss Inc.\n */\n// Newcastle upon Tyne,\n// Tyne and Wear,\npackage org.jboss.jbossts.qa.RawResources02Clients2;\n\n/*\n *\n * HP Arjuna Labs,\n * Newcastle upon Tyne,\n * Tyne and Wear,\n * UK.\n *\n * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $\n */\n/*\n * Try to get around the differences between Ansi CPP and\n * K&R cpp with concatenation.\n */\n/*\n *\n * HP Arjuna Labs,\n * Newcastle upon Tyne,\n * Tyne and Wear,\n * UK.\n *\n * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $\n */\nimport org.jboss.jbossts.qa.RawResources02.*;\nimport org.jboss.jbossts.qa.Utils.OAInterface;\nimport org.jboss.jbossts.qa.Utils.ORBInterface;\nimport org.jboss.jbossts.qa.Utils.OTS;\nimport org.jboss.jbossts.qa.Utils.ServerIORStore;\nimport org.omg.CosTransactions.HeuristicHazard;\nimport org.omg.CosTransactions.HeuristicMixed;\n\npublic class Client095 {\n\n public static void main(String[] args) {\n try {\n ORBInterface.initORB(args, null);\n OAInterface.initOA();\n String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]);\n Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1));\n String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]);\n Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2));\n ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1];\n resourceBehaviors1[0] = new ResourceBehavior();\n resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorRaiseHeuristicMixed;\n resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;\n resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;\n resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;\n ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1];\n resourceBehaviors2[0] = new ResourceBehavior();\n resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteCommit;\n resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorRaiseHeuristicMixed;\n resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;\n resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;\n boolean correct = true;\n OTS.current().begin();\n service1.oper(resourceBehaviors1, OTS.current().get_control());\n service2.oper(resourceBehaviors2, OTS.current().get_control());\n try {\n OTS.current().commit(true);\n System.err.println(\"Commit succeeded when it shouldn't\");\n correct = false;\n } catch (HeuristicMixed heuristicMixed) {\n } catch (HeuristicHazard heuristicHazard) {\n }\n correct = correct && service1.is_correct() && service2.is_correct();\n if (!correct) {\n System.err.println(\"service1.is_correct() or service2.is_correct() returned false\");\n }\n ResourceTrace resourceTrace1 = service1.get_resource_trace(0);\n ResourceTrace resourceTrace2 = service2.get_resource_trace(0);\n correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareForget);\n correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepareRollbackForget) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback));\n ", "post_mask_code": "\n } catch (Exception exception) {\n System.err.println(\"Client095.main: \" + exception);\n exception.printStackTrace(System.err);\n System.out.println(\"Failed\");\n }\n try {\n OAInterface.shutdownOA();\n ORBInterface.shutdownORB();\n } catch (Exception exception) {\n System.err.println(\"Client095.main: \" + exception);\n exception.printStackTrace(System.err);\n }\n }\n}\n"} {"task_id": "Java_1683", "language": "Java", "task_type": "try_statement", "source_file": "java/github/jbosstm/narayana/qa/tests/src/org/jboss/jbossts/qa/RawResources02Clients2/Client095.java", "mask_start_position": 4152, "mask_end_position": 4400, "canonical_solution": "try {\n OAInterface.shutdownOA();\n ORBInterface.shutdownORB();\n } catch (Exception exception) {\n System.err.println(\"Client095.main: \" + exception);\n exception.printStackTrace(System.err);\n }", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source\n * as indicated by the @author tags.\n * See the copyright.txt in the distribution for a\n * full listing of individual contributors.\n *\n * @author JBoss Inc.\n */\n// Newcastle upon Tyne,\n// Tyne and Wear,\npackage org.jboss.jbossts.qa.RawResources02Clients2;\n\n/*\n *\n * HP Arjuna Labs,\n * Newcastle upon Tyne,\n * Tyne and Wear,\n * UK.\n *\n * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $\n */\n/*\n * Try to get around the differences between Ansi CPP and\n * K&R cpp with concatenation.\n */\n/*\n *\n * HP Arjuna Labs,\n * Newcastle upon Tyne,\n * Tyne and Wear,\n * UK.\n *\n * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $\n */\nimport org.jboss.jbossts.qa.RawResources02.*;\nimport org.jboss.jbossts.qa.Utils.OAInterface;\nimport org.jboss.jbossts.qa.Utils.ORBInterface;\nimport org.jboss.jbossts.qa.Utils.OTS;\nimport org.jboss.jbossts.qa.Utils.ServerIORStore;\nimport org.omg.CosTransactions.HeuristicHazard;\nimport org.omg.CosTransactions.HeuristicMixed;\n\npublic class Client095 {\n\n public static void main(String[] args) {\n try {\n ORBInterface.initORB(args, null);\n OAInterface.initOA();\n String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]);\n Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1));\n String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]);\n Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2));\n ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1];\n resourceBehaviors1[0] = new ResourceBehavior();\n resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorRaiseHeuristicMixed;\n resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;\n resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;\n resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;\n ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1];\n resourceBehaviors2[0] = new ResourceBehavior();\n resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteCommit;\n resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorRaiseHeuristicMixed;\n resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;\n resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;\n boolean correct = true;\n OTS.current().begin();\n service1.oper(resourceBehaviors1, OTS.current().get_control());\n service2.oper(resourceBehaviors2, OTS.current().get_control());\n try {\n OTS.current().commit(true);\n System.err.println(\"Commit succeeded when it shouldn't\");\n correct = false;\n } catch (HeuristicMixed heuristicMixed) {\n } catch (HeuristicHazard heuristicHazard) {\n }\n correct = correct && service1.is_correct() && service2.is_correct();\n if (!correct) {\n System.err.println(\"service1.is_correct() or service2.is_correct() returned false\");\n }\n ResourceTrace resourceTrace1 = service1.get_resource_trace(0);\n ResourceTrace resourceTrace2 = service2.get_resource_trace(0);\n correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareForget);\n correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepareRollbackForget) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback));\n if (correct) {\n System.out.println(\"Passed\");\n } else {\n System.out.println(\"Failed\");\n }\n } catch (Exception exception) {\n System.err.println(\"Client095.main: \" + exception);\n exception.printStackTrace(System.err);\n System.out.println(\"Failed\");\n }\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1684", "language": "Java", "task_type": "method_signature", "source_file": "java/github/wangzhijun1124/MyTomcat/src/User.java", "mask_start_position": 231, "mask_end_position": 325, "canonical_solution": "@Override\n protected void doPost(HttpServletRequest request, HttpServletResponse response) ", "pre_mask_code": "import servlet.HttpServlet;\nimport servlet.HttpServletRequest;\nimport servlet.HttpServletResponse;\nimport servlet.HttpSession;\nimport java.io.PrintWriter;\n\n/**\n * @author WangZhiJun\n */\npublic class User extends HttpServlet {\n\n ", "post_mask_code": "{\n HttpSession session = request.getSession();\n String username = (String) session.getAttribute(\"username\");\n PrintWriter out = response.getWriter();\n String jsession = request.getJsessionid();\n if (jsession != null) {\n out.print(\"HTTP/1.1 200 OK\\r\\nSet-Cookie: JSESSIONID=\" + jsession + \"\\r\\n\\r\\n\");\n } else {\n out.print(\"HTTP/1.1 200 OK\\r\\n\\r\\n\");\n }\n out.print(\"\");\n out.print(\"\");\n out.print(\"welcome! \" + username + \"\\r\\n\\r\\n\");\n out.print(\"sessionId:\" + jsession);\n out.print(\"\");\n out.print(\"\");\n out.flush();\n out.close();\n }\n\n @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) {\n doPost(request, response);\n }\n}\n"} {"task_id": "Java_1685", "language": "Java", "task_type": "method_body", "source_file": "java/github/wangzhijun1124/MyTomcat/src/User.java", "mask_start_position": 1113, "mask_end_position": 1155, "canonical_solution": "{\n doPost(request, response);\n }", "pre_mask_code": "import servlet.HttpServlet;\nimport servlet.HttpServletRequest;\nimport servlet.HttpServletResponse;\nimport servlet.HttpSession;\nimport java.io.PrintWriter;\n\n/**\n * @author WangZhiJun\n */\npublic class User extends HttpServlet {\n\n @Override\n protected void doPost(HttpServletRequest request, HttpServletResponse response) {\n HttpSession session = request.getSession();\n String username = (String) session.getAttribute(\"username\");\n PrintWriter out = response.getWriter();\n String jsession = request.getJsessionid();\n if (jsession != null) {\n out.print(\"HTTP/1.1 200 OK\\r\\nSet-Cookie: JSESSIONID=\" + jsession + \"\\r\\n\\r\\n\");\n } else {\n out.print(\"HTTP/1.1 200 OK\\r\\n\\r\\n\");\n }\n out.print(\"\");\n out.print(\"\");\n out.print(\"welcome! \" + username + \"\\r\\n\\r\\n\");\n out.print(\"sessionId:\" + jsession);\n out.print(\"\");\n out.print(\"\");\n out.flush();\n out.close();\n }\n\n @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1686", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/wangzhijun1124/MyTomcat/src/User.java", "mask_start_position": 326, "mask_end_position": 546, "canonical_solution": "\n HttpSession session = request.getSession();\n String username = (String) session.getAttribute(\"username\");\n PrintWriter out = response.getWriter();\n String jsession = request.getJsessionid();", "pre_mask_code": "import servlet.HttpServlet;\nimport servlet.HttpServletRequest;\nimport servlet.HttpServletResponse;\nimport servlet.HttpSession;\nimport java.io.PrintWriter;\n\n/**\n * @author WangZhiJun\n */\npublic class User extends HttpServlet {\n\n @Override\n protected void doPost(HttpServletRequest request, HttpServletResponse response) {", "post_mask_code": "\n if (jsession != null) {\n out.print(\"HTTP/1.1 200 OK\\r\\nSet-Cookie: JSESSIONID=\" + jsession + \"\\r\\n\\r\\n\");\n } else {\n out.print(\"HTTP/1.1 200 OK\\r\\n\\r\\n\");\n }\n out.print(\"\");\n out.print(\"\");\n out.print(\"welcome! \" + username + \"\\r\\n\\r\\n\");\n out.print(\"sessionId:\" + jsession);\n out.print(\"\");\n out.print(\"\");\n out.flush();\n out.close();\n }\n\n @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) {\n doPost(request, response);\n }\n}\n"} {"task_id": "Java_1687", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/wangzhijun1124/MyTomcat/src/User.java", "mask_start_position": 555, "mask_end_position": 906, "canonical_solution": "if (jsession != null) {\n out.print(\"HTTP/1.1 200 OK\\r\\nSet-Cookie: JSESSIONID=\" + jsession + \"\\r\\n\\r\\n\");\n } else {\n out.print(\"HTTP/1.1 200 OK\\r\\n\\r\\n\");\n }\n out.print(\"\");\n out.print(\"\");\n out.print(\"welcome! \" + username + \"\\r\\n\\r\\n\");\n out.print(\"sessionId:\" + jsession);", "pre_mask_code": "import servlet.HttpServlet;\nimport servlet.HttpServletRequest;\nimport servlet.HttpServletResponse;\nimport servlet.HttpSession;\nimport java.io.PrintWriter;\n\n/**\n * @author WangZhiJun\n */\npublic class User extends HttpServlet {\n\n @Override\n protected void doPost(HttpServletRequest request, HttpServletResponse response) {\n HttpSession session = request.getSession();\n String username = (String) session.getAttribute(\"username\");\n PrintWriter out = response.getWriter();\n String jsession = request.getJsessionid();\n ", "post_mask_code": "\n out.print(\"\");\n out.print(\"\");\n out.flush();\n out.close();\n }\n\n @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) {\n doPost(request, response);\n }\n}\n"} {"task_id": "Java_1688", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/wangzhijun1124/MyTomcat/src/User.java", "mask_start_position": 915, "mask_end_position": 1014, "canonical_solution": "out.print(\"\");\n out.print(\"\");\n out.flush();\n out.close();\n }", "pre_mask_code": "import servlet.HttpServlet;\nimport servlet.HttpServletRequest;\nimport servlet.HttpServletResponse;\nimport servlet.HttpSession;\nimport java.io.PrintWriter;\n\n/**\n * @author WangZhiJun\n */\npublic class User extends HttpServlet {\n\n @Override\n protected void doPost(HttpServletRequest request, HttpServletResponse response) {\n HttpSession session = request.getSession();\n String username = (String) session.getAttribute(\"username\");\n PrintWriter out = response.getWriter();\n String jsession = request.getJsessionid();\n if (jsession != null) {\n out.print(\"HTTP/1.1 200 OK\\r\\nSet-Cookie: JSESSIONID=\" + jsession + \"\\r\\n\\r\\n\");\n } else {\n out.print(\"HTTP/1.1 200 OK\\r\\n\\r\\n\");\n }\n out.print(\"\");\n out.print(\"\");\n out.print(\"welcome! \" + username + \"\\r\\n\\r\\n\");\n out.print(\"sessionId:\" + jsession);\n ", "post_mask_code": "\n\n @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) {\n doPost(request, response);\n }\n}\n"} {"task_id": "Java_1689", "language": "Java", "task_type": "single_line", "source_file": "java/github/wangzhijun1124/MyTomcat/src/User.java", "mask_start_position": 982, "mask_end_position": 987, "canonical_solution": "sh();", "pre_mask_code": "import servlet.HttpServlet;\nimport servlet.HttpServletRequest;\nimport servlet.HttpServletResponse;\nimport servlet.HttpSession;\nimport java.io.PrintWriter;\n\n/**\n * @author WangZhiJun\n */\npublic class User extends HttpServlet {\n\n @Override\n protected void doPost(HttpServletRequest request, HttpServletResponse response) {\n HttpSession session = request.getSession();\n String username = (String) session.getAttribute(\"username\");\n PrintWriter out = response.getWriter();\n String jsession = request.getJsessionid();\n if (jsession != null) {\n out.print(\"HTTP/1.1 200 OK\\r\\nSet-Cookie: JSESSIONID=\" + jsession + \"\\r\\n\\r\\n\");\n } else {\n out.print(\"HTTP/1.1 200 OK\\r\\n\\r\\n\");\n }\n out.print(\"\");\n out.print(\"\");\n out.print(\"welcome! \" + username + \"\\r\\n\\r\\n\");\n out.print(\"sessionId:\" + jsession);\n out.print(\"\");\n out.print(\"\");\n out.flu", "post_mask_code": "\n out.close();\n }\n\n @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) {\n doPost(request, response);\n }\n}\n"} {"task_id": "Java_1690", "language": "Java", "task_type": "if_statement", "source_file": "java/github/wangzhijun1124/MyTomcat/src/User.java", "mask_start_position": 555, "mask_end_position": 748, "canonical_solution": "if (jsession != null) {\n out.print(\"HTTP/1.1 200 OK\\r\\nSet-Cookie: JSESSIONID=\" + jsession + \"\\r\\n\\r\\n\");\n } else {\n out.print(\"HTTP/1.1 200 OK\\r\\n\\r\\n\");\n }", "pre_mask_code": "import servlet.HttpServlet;\nimport servlet.HttpServletRequest;\nimport servlet.HttpServletResponse;\nimport servlet.HttpSession;\nimport java.io.PrintWriter;\n\n/**\n * @author WangZhiJun\n */\npublic class User extends HttpServlet {\n\n @Override\n protected void doPost(HttpServletRequest request, HttpServletResponse response) {\n HttpSession session = request.getSession();\n String username = (String) session.getAttribute(\"username\");\n PrintWriter out = response.getWriter();\n String jsession = request.getJsessionid();\n ", "post_mask_code": "\n out.print(\"\");\n out.print(\"\");\n out.print(\"welcome! \" + username + \"\\r\\n\\r\\n\");\n out.print(\"sessionId:\" + jsession);\n out.print(\"\");\n out.print(\"\");\n out.flush();\n out.close();\n }\n\n @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) {\n doPost(request, response);\n }\n}\n"} {"task_id": "Java_1691", "language": "Java", "task_type": "method_signature", "source_file": "java/github/subutai-io/peer-os/management/server/subutai-common/src/main/java/io/subutai/common/peer/FitCheckResult.java", "mask_start_position": 1093, "mask_end_position": 1164, "canonical_solution": "public Map getAvailableResources() ", "pre_mask_code": "package io.subutai.common.peer;\n\nimport java.util.Collections;\nimport java.util.Map;\nimport com.google.common.base.Preconditions;\nimport io.subutai.common.settings.Common;\nimport io.subutai.common.util.CollectionUtil;\nimport io.subutai.common.util.UnitUtil;\n\npublic class FitCheckResult {\n\n public static final double ACCOMMODATION_OVERHEAD_FACTOR = 1.01;\n\n private final Map availableResources;\n\n private final Map requestedResources;\n\n private boolean canFit = true;\n\n private String description;\n\n public FitCheckResult(final Map availableResources, final Map requestedResources) {\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(availableResources));\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(requestedResources));\n this.availableResources = availableResources;\n this.requestedResources = requestedResources;\n parse();\n }\n\n // returns capacity available on RH\n ", "post_mask_code": "{\n return Collections.unmodifiableMap(availableResources);\n }\n\n // returns resources requested on RH\n public Map getRequestedResources() {\n return Collections.unmodifiableMap(requestedResources);\n }\n\n public boolean canFit() {\n if (!Common.CHECK_RH_LIMITS) {\n return true;\n }\n return canFit;\n }\n\n public String getDescription() {\n return description;\n }\n\n private void parse() {\n StringBuilder humanResult = new StringBuilder();\n for (Map.Entry resourceEntry : requestedResources.entrySet()) {\n ResourceHost resourceHost = resourceEntry.getKey();\n ResourceHostCapacity requestedCapacity = resourceEntry.getValue();\n ResourceHostCapacity availableCapacity = availableResources.get(resourceHost);\n if (requestedCapacity.getRam() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getRam()) {\n humanResult.append(String.format(\"Requested RAM volume %.2fMB can not be provided on RH %s: available RAM volume is %\" + \".2fMB%n\", UnitUtil.convert(requestedCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB)));\n canFit = false;\n }\n if (requestedCapacity.getDisk() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getDisk()) {\n humanResult.append(String.format(\"Requested DISK volume %.2fGB can not be provided on RH %s: available DISK volume is \" + \"%.2fGB%n\", UnitUtil.convert(requestedCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB)));\n canFit = false;\n }\n if (requestedCapacity.getCpu() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getCpu()) {\n humanResult.append(String.format(\"Requested CPU %.2f can not be provided on RH %s: available CPU is %.2f%n\", requestedCapacity.getCpu(), resourceHost.getHostname(), availableCapacity.getCpu()));\n canFit = false;\n }\n }\n description = humanResult.length() > 0 ? humanResult.toString() : \"The requested resources can be allocated\";\n }\n}\n"} {"task_id": "Java_1692", "language": "Java", "task_type": "method_body", "source_file": "java/github/subutai-io/peer-os/management/server/subutai-common/src/main/java/io/subutai/common/peer/FitCheckResult.java", "mask_start_position": 1164, "mask_end_position": 1235, "canonical_solution": "{\n return Collections.unmodifiableMap(availableResources);\n }", "pre_mask_code": "package io.subutai.common.peer;\n\nimport java.util.Collections;\nimport java.util.Map;\nimport com.google.common.base.Preconditions;\nimport io.subutai.common.settings.Common;\nimport io.subutai.common.util.CollectionUtil;\nimport io.subutai.common.util.UnitUtil;\n\npublic class FitCheckResult {\n\n public static final double ACCOMMODATION_OVERHEAD_FACTOR = 1.01;\n\n private final Map availableResources;\n\n private final Map requestedResources;\n\n private boolean canFit = true;\n\n private String description;\n\n public FitCheckResult(final Map availableResources, final Map requestedResources) {\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(availableResources));\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(requestedResources));\n this.availableResources = availableResources;\n this.requestedResources = requestedResources;\n parse();\n }\n\n // returns capacity available on RH\n public Map getAvailableResources() ", "post_mask_code": "\n\n // returns resources requested on RH\n public Map getRequestedResources() {\n return Collections.unmodifiableMap(requestedResources);\n }\n\n public boolean canFit() {\n if (!Common.CHECK_RH_LIMITS) {\n return true;\n }\n return canFit;\n }\n\n public String getDescription() {\n return description;\n }\n\n private void parse() {\n StringBuilder humanResult = new StringBuilder();\n for (Map.Entry resourceEntry : requestedResources.entrySet()) {\n ResourceHost resourceHost = resourceEntry.getKey();\n ResourceHostCapacity requestedCapacity = resourceEntry.getValue();\n ResourceHostCapacity availableCapacity = availableResources.get(resourceHost);\n if (requestedCapacity.getRam() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getRam()) {\n humanResult.append(String.format(\"Requested RAM volume %.2fMB can not be provided on RH %s: available RAM volume is %\" + \".2fMB%n\", UnitUtil.convert(requestedCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB)));\n canFit = false;\n }\n if (requestedCapacity.getDisk() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getDisk()) {\n humanResult.append(String.format(\"Requested DISK volume %.2fGB can not be provided on RH %s: available DISK volume is \" + \"%.2fGB%n\", UnitUtil.convert(requestedCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB)));\n canFit = false;\n }\n if (requestedCapacity.getCpu() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getCpu()) {\n humanResult.append(String.format(\"Requested CPU %.2f can not be provided on RH %s: available CPU is %.2f%n\", requestedCapacity.getCpu(), resourceHost.getHostname(), availableCapacity.getCpu()));\n canFit = false;\n }\n }\n description = humanResult.length() > 0 ? humanResult.toString() : \"The requested resources can be allocated\";\n }\n}\n"} {"task_id": "Java_1693", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/subutai-io/peer-os/management/server/subutai-common/src/main/java/io/subutai/common/peer/FitCheckResult.java", "mask_start_position": 1658, "mask_end_position": 1715, "canonical_solution": "\n StringBuilder humanResult = new StringBuilder();", "pre_mask_code": "package io.subutai.common.peer;\n\nimport java.util.Collections;\nimport java.util.Map;\nimport com.google.common.base.Preconditions;\nimport io.subutai.common.settings.Common;\nimport io.subutai.common.util.CollectionUtil;\nimport io.subutai.common.util.UnitUtil;\n\npublic class FitCheckResult {\n\n public static final double ACCOMMODATION_OVERHEAD_FACTOR = 1.01;\n\n private final Map availableResources;\n\n private final Map requestedResources;\n\n private boolean canFit = true;\n\n private String description;\n\n public FitCheckResult(final Map availableResources, final Map requestedResources) {\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(availableResources));\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(requestedResources));\n this.availableResources = availableResources;\n this.requestedResources = requestedResources;\n parse();\n }\n\n // returns capacity available on RH\n public Map getAvailableResources() {\n return Collections.unmodifiableMap(availableResources);\n }\n\n // returns resources requested on RH\n public Map getRequestedResources() {\n return Collections.unmodifiableMap(requestedResources);\n }\n\n public boolean canFit() {\n if (!Common.CHECK_RH_LIMITS) {\n return true;\n }\n return canFit;\n }\n\n public String getDescription() {\n return description;\n }\n\n private void parse() {", "post_mask_code": "\n for (Map.Entry resourceEntry : requestedResources.entrySet()) {\n ResourceHost resourceHost = resourceEntry.getKey();\n ResourceHostCapacity requestedCapacity = resourceEntry.getValue();\n ResourceHostCapacity availableCapacity = availableResources.get(resourceHost);\n if (requestedCapacity.getRam() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getRam()) {\n humanResult.append(String.format(\"Requested RAM volume %.2fMB can not be provided on RH %s: available RAM volume is %\" + \".2fMB%n\", UnitUtil.convert(requestedCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB)));\n canFit = false;\n }\n if (requestedCapacity.getDisk() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getDisk()) {\n humanResult.append(String.format(\"Requested DISK volume %.2fGB can not be provided on RH %s: available DISK volume is \" + \"%.2fGB%n\", UnitUtil.convert(requestedCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB)));\n canFit = false;\n }\n if (requestedCapacity.getCpu() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getCpu()) {\n humanResult.append(String.format(\"Requested CPU %.2f can not be provided on RH %s: available CPU is %.2f%n\", requestedCapacity.getCpu(), resourceHost.getHostname(), availableCapacity.getCpu()));\n canFit = false;\n }\n }\n description = humanResult.length() > 0 ? humanResult.toString() : \"The requested resources can be allocated\";\n }\n}\n"} {"task_id": "Java_1694", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/subutai-io/peer-os/management/server/subutai-common/src/main/java/io/subutai/common/peer/FitCheckResult.java", "mask_start_position": 1724, "mask_end_position": 3468, "canonical_solution": "for (Map.Entry resourceEntry : requestedResources.entrySet()) {\n ResourceHost resourceHost = resourceEntry.getKey();\n ResourceHostCapacity requestedCapacity = resourceEntry.getValue();\n ResourceHostCapacity availableCapacity = availableResources.get(resourceHost);\n if (requestedCapacity.getRam() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getRam()) {\n humanResult.append(String.format(\"Requested RAM volume %.2fMB can not be provided on RH %s: available RAM volume is %\" + \".2fMB%n\", UnitUtil.convert(requestedCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB)));\n canFit = false;\n }\n if (requestedCapacity.getDisk() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getDisk()) {\n humanResult.append(String.format(\"Requested DISK volume %.2fGB can not be provided on RH %s: available DISK volume is \" + \"%.2fGB%n\", UnitUtil.convert(requestedCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB)));\n canFit = false;\n }\n if (requestedCapacity.getCpu() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getCpu()) {\n humanResult.append(String.format(\"Requested CPU %.2f can not be provided on RH %s: available CPU is %.2f%n\", requestedCapacity.getCpu(), resourceHost.getHostname(), availableCapacity.getCpu()));\n canFit = false;\n }\n }", "pre_mask_code": "package io.subutai.common.peer;\n\nimport java.util.Collections;\nimport java.util.Map;\nimport com.google.common.base.Preconditions;\nimport io.subutai.common.settings.Common;\nimport io.subutai.common.util.CollectionUtil;\nimport io.subutai.common.util.UnitUtil;\n\npublic class FitCheckResult {\n\n public static final double ACCOMMODATION_OVERHEAD_FACTOR = 1.01;\n\n private final Map availableResources;\n\n private final Map requestedResources;\n\n private boolean canFit = true;\n\n private String description;\n\n public FitCheckResult(final Map availableResources, final Map requestedResources) {\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(availableResources));\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(requestedResources));\n this.availableResources = availableResources;\n this.requestedResources = requestedResources;\n parse();\n }\n\n // returns capacity available on RH\n public Map getAvailableResources() {\n return Collections.unmodifiableMap(availableResources);\n }\n\n // returns resources requested on RH\n public Map getRequestedResources() {\n return Collections.unmodifiableMap(requestedResources);\n }\n\n public boolean canFit() {\n if (!Common.CHECK_RH_LIMITS) {\n return true;\n }\n return canFit;\n }\n\n public String getDescription() {\n return description;\n }\n\n private void parse() {\n StringBuilder humanResult = new StringBuilder();\n ", "post_mask_code": "\n description = humanResult.length() > 0 ? humanResult.toString() : \"The requested resources can be allocated\";\n }\n}\n"} {"task_id": "Java_1695", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/subutai-io/peer-os/management/server/subutai-common/src/main/java/io/subutai/common/peer/FitCheckResult.java", "mask_start_position": 3477, "mask_end_position": 3592, "canonical_solution": "description = humanResult.length() > 0 ? humanResult.toString() : \"The requested resources can be allocated\";\n }", "pre_mask_code": "package io.subutai.common.peer;\n\nimport java.util.Collections;\nimport java.util.Map;\nimport com.google.common.base.Preconditions;\nimport io.subutai.common.settings.Common;\nimport io.subutai.common.util.CollectionUtil;\nimport io.subutai.common.util.UnitUtil;\n\npublic class FitCheckResult {\n\n public static final double ACCOMMODATION_OVERHEAD_FACTOR = 1.01;\n\n private final Map availableResources;\n\n private final Map requestedResources;\n\n private boolean canFit = true;\n\n private String description;\n\n public FitCheckResult(final Map availableResources, final Map requestedResources) {\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(availableResources));\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(requestedResources));\n this.availableResources = availableResources;\n this.requestedResources = requestedResources;\n parse();\n }\n\n // returns capacity available on RH\n public Map getAvailableResources() {\n return Collections.unmodifiableMap(availableResources);\n }\n\n // returns resources requested on RH\n public Map getRequestedResources() {\n return Collections.unmodifiableMap(requestedResources);\n }\n\n public boolean canFit() {\n if (!Common.CHECK_RH_LIMITS) {\n return true;\n }\n return canFit;\n }\n\n public String getDescription() {\n return description;\n }\n\n private void parse() {\n StringBuilder humanResult = new StringBuilder();\n for (Map.Entry resourceEntry : requestedResources.entrySet()) {\n ResourceHost resourceHost = resourceEntry.getKey();\n ResourceHostCapacity requestedCapacity = resourceEntry.getValue();\n ResourceHostCapacity availableCapacity = availableResources.get(resourceHost);\n if (requestedCapacity.getRam() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getRam()) {\n humanResult.append(String.format(\"Requested RAM volume %.2fMB can not be provided on RH %s: available RAM volume is %\" + \".2fMB%n\", UnitUtil.convert(requestedCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB)));\n canFit = false;\n }\n if (requestedCapacity.getDisk() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getDisk()) {\n humanResult.append(String.format(\"Requested DISK volume %.2fGB can not be provided on RH %s: available DISK volume is \" + \"%.2fGB%n\", UnitUtil.convert(requestedCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB)));\n canFit = false;\n }\n if (requestedCapacity.getCpu() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getCpu()) {\n humanResult.append(String.format(\"Requested CPU %.2f can not be provided on RH %s: available CPU is %.2f%n\", requestedCapacity.getCpu(), resourceHost.getHostname(), availableCapacity.getCpu()));\n canFit = false;\n }\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1696", "language": "Java", "task_type": "single_line", "source_file": "java/github/subutai-io/peer-os/management/server/subutai-common/src/main/java/io/subutai/common/peer/FitCheckResult.java", "mask_start_position": 1611, "mask_end_position": 1624, "canonical_solution": " description;", "pre_mask_code": "package io.subutai.common.peer;\n\nimport java.util.Collections;\nimport java.util.Map;\nimport com.google.common.base.Preconditions;\nimport io.subutai.common.settings.Common;\nimport io.subutai.common.util.CollectionUtil;\nimport io.subutai.common.util.UnitUtil;\n\npublic class FitCheckResult {\n\n public static final double ACCOMMODATION_OVERHEAD_FACTOR = 1.01;\n\n private final Map availableResources;\n\n private final Map requestedResources;\n\n private boolean canFit = true;\n\n private String description;\n\n public FitCheckResult(final Map availableResources, final Map requestedResources) {\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(availableResources));\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(requestedResources));\n this.availableResources = availableResources;\n this.requestedResources = requestedResources;\n parse();\n }\n\n // returns capacity available on RH\n public Map getAvailableResources() {\n return Collections.unmodifiableMap(availableResources);\n }\n\n // returns resources requested on RH\n public Map getRequestedResources() {\n return Collections.unmodifiableMap(requestedResources);\n }\n\n public boolean canFit() {\n if (!Common.CHECK_RH_LIMITS) {\n return true;\n }\n return canFit;\n }\n\n public String getDescription() {\n return", "post_mask_code": "\n }\n\n private void parse() {\n StringBuilder humanResult = new StringBuilder();\n for (Map.Entry resourceEntry : requestedResources.entrySet()) {\n ResourceHost resourceHost = resourceEntry.getKey();\n ResourceHostCapacity requestedCapacity = resourceEntry.getValue();\n ResourceHostCapacity availableCapacity = availableResources.get(resourceHost);\n if (requestedCapacity.getRam() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getRam()) {\n humanResult.append(String.format(\"Requested RAM volume %.2fMB can not be provided on RH %s: available RAM volume is %\" + \".2fMB%n\", UnitUtil.convert(requestedCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB)));\n canFit = false;\n }\n if (requestedCapacity.getDisk() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getDisk()) {\n humanResult.append(String.format(\"Requested DISK volume %.2fGB can not be provided on RH %s: available DISK volume is \" + \"%.2fGB%n\", UnitUtil.convert(requestedCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB)));\n canFit = false;\n }\n if (requestedCapacity.getCpu() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getCpu()) {\n humanResult.append(String.format(\"Requested CPU %.2f can not be provided on RH %s: available CPU is %.2f%n\", requestedCapacity.getCpu(), resourceHost.getHostname(), availableCapacity.getCpu()));\n canFit = false;\n }\n }\n description = humanResult.length() > 0 ? humanResult.toString() : \"The requested resources can be allocated\";\n }\n}\n"} {"task_id": "Java_1697", "language": "Java", "task_type": "if_statement", "source_file": "java/github/subutai-io/peer-os/management/server/subutai-common/src/main/java/io/subutai/common/peer/FitCheckResult.java", "mask_start_position": 3092, "mask_end_position": 3458, "canonical_solution": "if (requestedCapacity.getCpu() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getCpu()) {\n humanResult.append(String.format(\"Requested CPU %.2f can not be provided on RH %s: available CPU is %.2f%n\", requestedCapacity.getCpu(), resourceHost.getHostname(), availableCapacity.getCpu()));\n canFit = false;\n }", "pre_mask_code": "package io.subutai.common.peer;\n\nimport java.util.Collections;\nimport java.util.Map;\nimport com.google.common.base.Preconditions;\nimport io.subutai.common.settings.Common;\nimport io.subutai.common.util.CollectionUtil;\nimport io.subutai.common.util.UnitUtil;\n\npublic class FitCheckResult {\n\n public static final double ACCOMMODATION_OVERHEAD_FACTOR = 1.01;\n\n private final Map availableResources;\n\n private final Map requestedResources;\n\n private boolean canFit = true;\n\n private String description;\n\n public FitCheckResult(final Map availableResources, final Map requestedResources) {\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(availableResources));\n Preconditions.checkArgument(!CollectionUtil.isMapEmpty(requestedResources));\n this.availableResources = availableResources;\n this.requestedResources = requestedResources;\n parse();\n }\n\n // returns capacity available on RH\n public Map getAvailableResources() {\n return Collections.unmodifiableMap(availableResources);\n }\n\n // returns resources requested on RH\n public Map getRequestedResources() {\n return Collections.unmodifiableMap(requestedResources);\n }\n\n public boolean canFit() {\n if (!Common.CHECK_RH_LIMITS) {\n return true;\n }\n return canFit;\n }\n\n public String getDescription() {\n return description;\n }\n\n private void parse() {\n StringBuilder humanResult = new StringBuilder();\n for (Map.Entry resourceEntry : requestedResources.entrySet()) {\n ResourceHost resourceHost = resourceEntry.getKey();\n ResourceHostCapacity requestedCapacity = resourceEntry.getValue();\n ResourceHostCapacity availableCapacity = availableResources.get(resourceHost);\n if (requestedCapacity.getRam() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getRam()) {\n humanResult.append(String.format(\"Requested RAM volume %.2fMB can not be provided on RH %s: available RAM volume is %\" + \".2fMB%n\", UnitUtil.convert(requestedCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getRam(), UnitUtil.Unit.B, UnitUtil.Unit.MB)));\n canFit = false;\n }\n if (requestedCapacity.getDisk() * FitCheckResult.ACCOMMODATION_OVERHEAD_FACTOR > availableCapacity.getDisk()) {\n humanResult.append(String.format(\"Requested DISK volume %.2fGB can not be provided on RH %s: available DISK volume is \" + \"%.2fGB%n\", UnitUtil.convert(requestedCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB), resourceHost.getHostname(), UnitUtil.convert(availableCapacity.getDisk(), UnitUtil.Unit.B, UnitUtil.Unit.GB)));\n canFit = false;\n }\n ", "post_mask_code": "\n }\n description = humanResult.length() > 0 ? humanResult.toString() : \"The requested resources can be allocated\";\n }\n}\n"} {"task_id": "Java_1698", "language": "Java", "task_type": "method_signature", "source_file": "java/github/geotools/geotools/modules/library/opengis/src/main/java/org/opengis/metadata/identification/TopicCategory.java", "mask_start_position": 9123, "mask_end_position": 9162, "canonical_solution": "public static TopicCategory[] values() ", "pre_mask_code": "/*\n * GeoTools - The Open Source Java GIS Toolkit\n * http://geotools.org\n *\n *\n * All Rights Reserved. http://example.com\n */\npackage org.opengis.metadata.identification;\n\nimport static org.opengis.annotation.Obligation.CONDITIONAL;\nimport static org.opengis.annotation.Specification.ISO_19115;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.opengis.annotation.UML;\nimport org.opengis.util.CodeList;\n\n/**\n * High-level geographic data thematic classification to assist in the grouping and search of\n * available geographic data sets. Can be used to group keywords as well. Listed examples are not\n * exhaustive.\n *\n *

NOTE: It is understood there are overlaps between general categories and the user is\n * encouraged to select the one most appropriate.\n *\n * @version ISO 19115\n * @author Martin Desruisseaux (IRD)\n * @since GeoAPI 2.0\n */\n@UML(identifier = \"MD_TopicCategoryCode\", specification = ISO_19115)\npublic final class TopicCategory extends CodeList {\n\n /**\n * Serial number for compatibility with different versions.\n */\n private static final long serialVersionUID = -4987523565852255081L;\n\n /**\n * List of all enumerations of this type. Must be declared before any enum declaration.\n */\n private static final List VALUES = new ArrayList<>(19);\n\n /**\n * Rearing of animals and/or cultivation of plants.\n *\n *

Examples: agriculture, irrigation, aquaculture, plantations, herding, pests and diseases\n * affecting crops and livestock.\n */\n @UML(identifier = \"farming\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory FARMING = new TopicCategory(\"FARMING\");\n\n /**\n * Flora and/or fauna in natural environment.\n *\n *

Examples: wildlife, vegetation, biological sciences, ecology, wilderness, sealife,\n * wetlands, habitat\n */\n @UML(identifier = \"biota\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory BIOTA = new TopicCategory(\"BIOTA\");\n\n /**\n * Legal land descriptions.\n *\n *

Examples: political and administrative boundaries.\n */\n @UML(identifier = \"boundaries\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory BOUNDARIES = new TopicCategory(\"BOUNDARIES\");\n\n /**\n * Processes and phenomena of the atmosphere.\n *\n *

Examples: cloud cover, weather, climate, atmospheric conditions, climate change,\n * precipitation.\n */\n @UML(identifier = \"climatologyMeteorologyAtmosphere\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory CLIMATOLOGY_METEOROLOGY_ATMOSPHERE = new TopicCategory(\"CLIMATOLOGY_METEOROLOGY_ATMOSPHERE\");\n\n /**\n * Economic activities, conditions and employment.\n *\n *

Examples: production, labour, revenue, commerce, industry, tourism and ecotourism,\n * forestry, fisheries, commercial or subsistence hunting, exploration and exploitation of\n * resources such as minerals, oil and gas.\n */\n @UML(identifier = \"economy\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory ECONOMY = new TopicCategory(\"ECONOMY\");\n\n /**\n * Height above or below sea level.\n *\n *

Examples: altitude, bathymetry, digital elevation models, slope, derived products.\n */\n @UML(identifier = \"elevation\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory ELEVATION = new TopicCategory(\"ELEVATION\");\n\n /**\n * Environmental resources, protection and conservation.\n *\n *

Examples: environmental pollution, waste storage and treatment, environmental impact\n * assessment, monitoring environmental risk, nature reserves, landscape.\n */\n @UML(identifier = \"environment\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory ENVIRONMENT = new TopicCategory(\"ENVIRONMENT\");\n\n /**\n * Information pertaining to earth sciences.\n *\n *

Examples: geophysical features and processes, geology, minerals, sciences dealing with the\n * composition, structure and origin of the earth's rocks, risks of earthquakes, volcanic\n * activity, landslides, gravity information, soils, permafrost, hydrogeology, erosion.\n */\n @UML(identifier = \"geoscientificInformation\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory GEOSCIENTIFIC_INFORMATION = new TopicCategory(\"GEOSCIENTIFIC_INFORMATION\");\n\n /**\n * Health, health services, human ecology, and safety.\n *\n *

Examples: disease and illness, factors affecting health, hygiene, substance abuse, mental\n * and physical health, health services.\n *\n * @since GeoAPI 2.1\n */\n @UML(identifier = \"health\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory HEALTH = new TopicCategory(\"HEALTH\");\n\n @UML(identifier = \"imageryBaseMapsEarthCover\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory IMAGERY_BASE_MAPS_EARTH_COVER = new TopicCategory(\"IMAGERY_BASE_MAPS_EARTH_COVER\");\n\n @UML(identifier = \"intelligenceMilitary\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory INTELLIGENCE_MILITARY = new TopicCategory(\"INTELLIGENCE_MILITARY\");\n\n /**\n * Inland water features, drainage systems and their characteristics.\n *\n *

Examples: rivers and glaciers, salt lakes, water utilization plans, dams, currents,\n * floods, water quality, hydrographic charts.\n */\n @UML(identifier = \"inlandWaters\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory INLAND_WATERS = new TopicCategory(\"INLAND_WATERS\");\n\n /**\n * Positional information and services.\n *\n *

Examples: addresses, geodetic networks, control points, postal zones and services, place\n * names.\n */\n @UML(identifier = \"location\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory LOCATION = new TopicCategory(\"LOCATION\");\n\n /**\n * Features and characteristics of salt water bodies (excluding inland waters).\n *\n *

Examples: tides, tidal waves, coastal information, reefs.\n */\n @UML(identifier = \"oceans\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory OCEANS = new TopicCategory(\"OCEANS\");\n\n /**\n * Information used for appropriate actions for future use of the land.\n *\n *

Examples: land use maps, zoning maps, cadastral surveys, land ownership.\n */\n @UML(identifier = \"planningCadastre\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory PLANNING_CADASTRE = new TopicCategory(\"PLANNING_CADASTRE\");\n\n /**\n * Characteristics of society and cultures.\n *\n *

Examples: settlements, anthropology, archaeology, education, traditional beliefs, manners\n * and customs, demographic data, recreational areas and activities, social impact assessments,\n * crime and justice, census information\n */\n @UML(identifier = \"society\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory SOCIETY = new TopicCategory(\"SOCIETY\");\n\n @UML(identifier = \"structure\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory STRUCTURE = new TopicCategory(\"STRUCTURE\");\n\n /**\n * Means and aids for conveying persons and/or goods.\n *\n *

Examples: roads, airports/airstrips, shipping routes, tunnels, nautical charts, vehicle or\n * vessel location, aeronautical charts, railways.\n */\n @UML(identifier = \"transportation\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory TRANSPORTATION = new TopicCategory(\"TRANSPORTATION\");\n\n /**\n * Energy, water and waste systems and communications infrastructure and services.\n *\n *

Examples: hydroelectricity, geothermal, solar and nuclear sources of energy, water\n * purification and distribution, sewage collection and disposal, electricity and gas\n * distribution, data communication, telecommunication, radio, communication networks.\n */\n @UML(identifier = \"utilitiesCommunication\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory UTILITIES_COMMUNICATION = new TopicCategory(\"UTILITIES_COMMUNICATION\");\n\n /**\n * Constructs an enum with the given name. The new enum is automatically added to the list\n * returned by {@link #values}.\n *\n * @param name The enum name. This name must not be in use by an other enum of this type.\n */\n private TopicCategory(final String name) {\n super(name, VALUES);\n }\n\n /**\n * Returns the list of {@code TopicCategory}s.\n *\n * @return The list of codes declared in the current JVM.\n */\n ", "post_mask_code": "{\n synchronized (VALUES) {\n return VALUES.toArray(new TopicCategory[VALUES.size()]);\n }\n }\n\n /**\n * Returns the list of enumerations of the same kind than this enum.\n */\n @Override\n public TopicCategory[] family() {\n return values();\n }\n\n /**\n * Returns the topic category that matches the given string, or returns a new one if none match\n * it.\n *\n * @param code The name of the code to fetch or to create.\n * @return A code matching the given name.\n */\n public static TopicCategory valueOf(String code) {\n return valueOf(TopicCategory.class, code);\n }\n}\n"} {"task_id": "Java_1699", "language": "Java", "task_type": "method_body", "source_file": "java/github/geotools/geotools/modules/library/opengis/src/main/java/org/opengis/metadata/identification/TopicCategory.java", "mask_start_position": 9162, "mask_end_position": 9280, "canonical_solution": "{\n synchronized (VALUES) {\n return VALUES.toArray(new TopicCategory[VALUES.size()]);\n }\n }", "pre_mask_code": "/*\n * GeoTools - The Open Source Java GIS Toolkit\n * http://geotools.org\n *\n *\n * All Rights Reserved. http://example.com\n */\npackage org.opengis.metadata.identification;\n\nimport static org.opengis.annotation.Obligation.CONDITIONAL;\nimport static org.opengis.annotation.Specification.ISO_19115;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.opengis.annotation.UML;\nimport org.opengis.util.CodeList;\n\n/**\n * High-level geographic data thematic classification to assist in the grouping and search of\n * available geographic data sets. Can be used to group keywords as well. Listed examples are not\n * exhaustive.\n *\n *

NOTE: It is understood there are overlaps between general categories and the user is\n * encouraged to select the one most appropriate.\n *\n * @version ISO 19115\n * @author Martin Desruisseaux (IRD)\n * @since GeoAPI 2.0\n */\n@UML(identifier = \"MD_TopicCategoryCode\", specification = ISO_19115)\npublic final class TopicCategory extends CodeList {\n\n /**\n * Serial number for compatibility with different versions.\n */\n private static final long serialVersionUID = -4987523565852255081L;\n\n /**\n * List of all enumerations of this type. Must be declared before any enum declaration.\n */\n private static final List VALUES = new ArrayList<>(19);\n\n /**\n * Rearing of animals and/or cultivation of plants.\n *\n *

Examples: agriculture, irrigation, aquaculture, plantations, herding, pests and diseases\n * affecting crops and livestock.\n */\n @UML(identifier = \"farming\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory FARMING = new TopicCategory(\"FARMING\");\n\n /**\n * Flora and/or fauna in natural environment.\n *\n *

Examples: wildlife, vegetation, biological sciences, ecology, wilderness, sealife,\n * wetlands, habitat\n */\n @UML(identifier = \"biota\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory BIOTA = new TopicCategory(\"BIOTA\");\n\n /**\n * Legal land descriptions.\n *\n *

Examples: political and administrative boundaries.\n */\n @UML(identifier = \"boundaries\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory BOUNDARIES = new TopicCategory(\"BOUNDARIES\");\n\n /**\n * Processes and phenomena of the atmosphere.\n *\n *

Examples: cloud cover, weather, climate, atmospheric conditions, climate change,\n * precipitation.\n */\n @UML(identifier = \"climatologyMeteorologyAtmosphere\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory CLIMATOLOGY_METEOROLOGY_ATMOSPHERE = new TopicCategory(\"CLIMATOLOGY_METEOROLOGY_ATMOSPHERE\");\n\n /**\n * Economic activities, conditions and employment.\n *\n *

Examples: production, labour, revenue, commerce, industry, tourism and ecotourism,\n * forestry, fisheries, commercial or subsistence hunting, exploration and exploitation of\n * resources such as minerals, oil and gas.\n */\n @UML(identifier = \"economy\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory ECONOMY = new TopicCategory(\"ECONOMY\");\n\n /**\n * Height above or below sea level.\n *\n *

Examples: altitude, bathymetry, digital elevation models, slope, derived products.\n */\n @UML(identifier = \"elevation\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory ELEVATION = new TopicCategory(\"ELEVATION\");\n\n /**\n * Environmental resources, protection and conservation.\n *\n *

Examples: environmental pollution, waste storage and treatment, environmental impact\n * assessment, monitoring environmental risk, nature reserves, landscape.\n */\n @UML(identifier = \"environment\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory ENVIRONMENT = new TopicCategory(\"ENVIRONMENT\");\n\n /**\n * Information pertaining to earth sciences.\n *\n *

Examples: geophysical features and processes, geology, minerals, sciences dealing with the\n * composition, structure and origin of the earth's rocks, risks of earthquakes, volcanic\n * activity, landslides, gravity information, soils, permafrost, hydrogeology, erosion.\n */\n @UML(identifier = \"geoscientificInformation\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory GEOSCIENTIFIC_INFORMATION = new TopicCategory(\"GEOSCIENTIFIC_INFORMATION\");\n\n /**\n * Health, health services, human ecology, and safety.\n *\n *

Examples: disease and illness, factors affecting health, hygiene, substance abuse, mental\n * and physical health, health services.\n *\n * @since GeoAPI 2.1\n */\n @UML(identifier = \"health\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory HEALTH = new TopicCategory(\"HEALTH\");\n\n @UML(identifier = \"imageryBaseMapsEarthCover\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory IMAGERY_BASE_MAPS_EARTH_COVER = new TopicCategory(\"IMAGERY_BASE_MAPS_EARTH_COVER\");\n\n @UML(identifier = \"intelligenceMilitary\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory INTELLIGENCE_MILITARY = new TopicCategory(\"INTELLIGENCE_MILITARY\");\n\n /**\n * Inland water features, drainage systems and their characteristics.\n *\n *

Examples: rivers and glaciers, salt lakes, water utilization plans, dams, currents,\n * floods, water quality, hydrographic charts.\n */\n @UML(identifier = \"inlandWaters\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory INLAND_WATERS = new TopicCategory(\"INLAND_WATERS\");\n\n /**\n * Positional information and services.\n *\n *

Examples: addresses, geodetic networks, control points, postal zones and services, place\n * names.\n */\n @UML(identifier = \"location\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory LOCATION = new TopicCategory(\"LOCATION\");\n\n /**\n * Features and characteristics of salt water bodies (excluding inland waters).\n *\n *

Examples: tides, tidal waves, coastal information, reefs.\n */\n @UML(identifier = \"oceans\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory OCEANS = new TopicCategory(\"OCEANS\");\n\n /**\n * Information used for appropriate actions for future use of the land.\n *\n *

Examples: land use maps, zoning maps, cadastral surveys, land ownership.\n */\n @UML(identifier = \"planningCadastre\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory PLANNING_CADASTRE = new TopicCategory(\"PLANNING_CADASTRE\");\n\n /**\n * Characteristics of society and cultures.\n *\n *

Examples: settlements, anthropology, archaeology, education, traditional beliefs, manners\n * and customs, demographic data, recreational areas and activities, social impact assessments,\n * crime and justice, census information\n */\n @UML(identifier = \"society\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory SOCIETY = new TopicCategory(\"SOCIETY\");\n\n @UML(identifier = \"structure\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory STRUCTURE = new TopicCategory(\"STRUCTURE\");\n\n /**\n * Means and aids for conveying persons and/or goods.\n *\n *

Examples: roads, airports/airstrips, shipping routes, tunnels, nautical charts, vehicle or\n * vessel location, aeronautical charts, railways.\n */\n @UML(identifier = \"transportation\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory TRANSPORTATION = new TopicCategory(\"TRANSPORTATION\");\n\n /**\n * Energy, water and waste systems and communications infrastructure and services.\n *\n *

Examples: hydroelectricity, geothermal, solar and nuclear sources of energy, water\n * purification and distribution, sewage collection and disposal, electricity and gas\n * distribution, data communication, telecommunication, radio, communication networks.\n */\n @UML(identifier = \"utilitiesCommunication\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory UTILITIES_COMMUNICATION = new TopicCategory(\"UTILITIES_COMMUNICATION\");\n\n /**\n * Constructs an enum with the given name. The new enum is automatically added to the list\n * returned by {@link #values}.\n *\n * @param name The enum name. This name must not be in use by an other enum of this type.\n */\n private TopicCategory(final String name) {\n super(name, VALUES);\n }\n\n /**\n * Returns the list of {@code TopicCategory}s.\n *\n * @return The list of codes declared in the current JVM.\n */\n public static TopicCategory[] values() ", "post_mask_code": "\n\n /**\n * Returns the list of enumerations of the same kind than this enum.\n */\n @Override\n public TopicCategory[] family() {\n return values();\n }\n\n /**\n * Returns the topic category that matches the given string, or returns a new one if none match\n * it.\n *\n * @param code The name of the code to fetch or to create.\n * @return A code matching the given name.\n */\n public static TopicCategory valueOf(String code) {\n return valueOf(TopicCategory.class, code);\n }\n}\n"} {"task_id": "Java_1700", "language": "Java", "task_type": "single_line", "source_file": "java/github/geotools/geotools/modules/library/opengis/src/main/java/org/opengis/metadata/identification/TopicCategory.java", "mask_start_position": 9435, "mask_end_position": 9447, "canonical_solution": "rn values();", "pre_mask_code": "/*\n * GeoTools - The Open Source Java GIS Toolkit\n * http://geotools.org\n *\n *\n * All Rights Reserved. http://example.com\n */\npackage org.opengis.metadata.identification;\n\nimport static org.opengis.annotation.Obligation.CONDITIONAL;\nimport static org.opengis.annotation.Specification.ISO_19115;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.opengis.annotation.UML;\nimport org.opengis.util.CodeList;\n\n/**\n * High-level geographic data thematic classification to assist in the grouping and search of\n * available geographic data sets. Can be used to group keywords as well. Listed examples are not\n * exhaustive.\n *\n *

NOTE: It is understood there are overlaps between general categories and the user is\n * encouraged to select the one most appropriate.\n *\n * @version ISO 19115\n * @author Martin Desruisseaux (IRD)\n * @since GeoAPI 2.0\n */\n@UML(identifier = \"MD_TopicCategoryCode\", specification = ISO_19115)\npublic final class TopicCategory extends CodeList {\n\n /**\n * Serial number for compatibility with different versions.\n */\n private static final long serialVersionUID = -4987523565852255081L;\n\n /**\n * List of all enumerations of this type. Must be declared before any enum declaration.\n */\n private static final List VALUES = new ArrayList<>(19);\n\n /**\n * Rearing of animals and/or cultivation of plants.\n *\n *

Examples: agriculture, irrigation, aquaculture, plantations, herding, pests and diseases\n * affecting crops and livestock.\n */\n @UML(identifier = \"farming\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory FARMING = new TopicCategory(\"FARMING\");\n\n /**\n * Flora and/or fauna in natural environment.\n *\n *

Examples: wildlife, vegetation, biological sciences, ecology, wilderness, sealife,\n * wetlands, habitat\n */\n @UML(identifier = \"biota\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory BIOTA = new TopicCategory(\"BIOTA\");\n\n /**\n * Legal land descriptions.\n *\n *

Examples: political and administrative boundaries.\n */\n @UML(identifier = \"boundaries\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory BOUNDARIES = new TopicCategory(\"BOUNDARIES\");\n\n /**\n * Processes and phenomena of the atmosphere.\n *\n *

Examples: cloud cover, weather, climate, atmospheric conditions, climate change,\n * precipitation.\n */\n @UML(identifier = \"climatologyMeteorologyAtmosphere\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory CLIMATOLOGY_METEOROLOGY_ATMOSPHERE = new TopicCategory(\"CLIMATOLOGY_METEOROLOGY_ATMOSPHERE\");\n\n /**\n * Economic activities, conditions and employment.\n *\n *

Examples: production, labour, revenue, commerce, industry, tourism and ecotourism,\n * forestry, fisheries, commercial or subsistence hunting, exploration and exploitation of\n * resources such as minerals, oil and gas.\n */\n @UML(identifier = \"economy\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory ECONOMY = new TopicCategory(\"ECONOMY\");\n\n /**\n * Height above or below sea level.\n *\n *

Examples: altitude, bathymetry, digital elevation models, slope, derived products.\n */\n @UML(identifier = \"elevation\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory ELEVATION = new TopicCategory(\"ELEVATION\");\n\n /**\n * Environmental resources, protection and conservation.\n *\n *

Examples: environmental pollution, waste storage and treatment, environmental impact\n * assessment, monitoring environmental risk, nature reserves, landscape.\n */\n @UML(identifier = \"environment\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory ENVIRONMENT = new TopicCategory(\"ENVIRONMENT\");\n\n /**\n * Information pertaining to earth sciences.\n *\n *

Examples: geophysical features and processes, geology, minerals, sciences dealing with the\n * composition, structure and origin of the earth's rocks, risks of earthquakes, volcanic\n * activity, landslides, gravity information, soils, permafrost, hydrogeology, erosion.\n */\n @UML(identifier = \"geoscientificInformation\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory GEOSCIENTIFIC_INFORMATION = new TopicCategory(\"GEOSCIENTIFIC_INFORMATION\");\n\n /**\n * Health, health services, human ecology, and safety.\n *\n *

Examples: disease and illness, factors affecting health, hygiene, substance abuse, mental\n * and physical health, health services.\n *\n * @since GeoAPI 2.1\n */\n @UML(identifier = \"health\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory HEALTH = new TopicCategory(\"HEALTH\");\n\n @UML(identifier = \"imageryBaseMapsEarthCover\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory IMAGERY_BASE_MAPS_EARTH_COVER = new TopicCategory(\"IMAGERY_BASE_MAPS_EARTH_COVER\");\n\n @UML(identifier = \"intelligenceMilitary\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory INTELLIGENCE_MILITARY = new TopicCategory(\"INTELLIGENCE_MILITARY\");\n\n /**\n * Inland water features, drainage systems and their characteristics.\n *\n *

Examples: rivers and glaciers, salt lakes, water utilization plans, dams, currents,\n * floods, water quality, hydrographic charts.\n */\n @UML(identifier = \"inlandWaters\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory INLAND_WATERS = new TopicCategory(\"INLAND_WATERS\");\n\n /**\n * Positional information and services.\n *\n *

Examples: addresses, geodetic networks, control points, postal zones and services, place\n * names.\n */\n @UML(identifier = \"location\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory LOCATION = new TopicCategory(\"LOCATION\");\n\n /**\n * Features and characteristics of salt water bodies (excluding inland waters).\n *\n *

Examples: tides, tidal waves, coastal information, reefs.\n */\n @UML(identifier = \"oceans\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory OCEANS = new TopicCategory(\"OCEANS\");\n\n /**\n * Information used for appropriate actions for future use of the land.\n *\n *

Examples: land use maps, zoning maps, cadastral surveys, land ownership.\n */\n @UML(identifier = \"planningCadastre\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory PLANNING_CADASTRE = new TopicCategory(\"PLANNING_CADASTRE\");\n\n /**\n * Characteristics of society and cultures.\n *\n *

Examples: settlements, anthropology, archaeology, education, traditional beliefs, manners\n * and customs, demographic data, recreational areas and activities, social impact assessments,\n * crime and justice, census information\n */\n @UML(identifier = \"society\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory SOCIETY = new TopicCategory(\"SOCIETY\");\n\n @UML(identifier = \"structure\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory STRUCTURE = new TopicCategory(\"STRUCTURE\");\n\n /**\n * Means and aids for conveying persons and/or goods.\n *\n *

Examples: roads, airports/airstrips, shipping routes, tunnels, nautical charts, vehicle or\n * vessel location, aeronautical charts, railways.\n */\n @UML(identifier = \"transportation\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory TRANSPORTATION = new TopicCategory(\"TRANSPORTATION\");\n\n /**\n * Energy, water and waste systems and communications infrastructure and services.\n *\n *

Examples: hydroelectricity, geothermal, solar and nuclear sources of energy, water\n * purification and distribution, sewage collection and disposal, electricity and gas\n * distribution, data communication, telecommunication, radio, communication networks.\n */\n @UML(identifier = \"utilitiesCommunication\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory UTILITIES_COMMUNICATION = new TopicCategory(\"UTILITIES_COMMUNICATION\");\n\n /**\n * Constructs an enum with the given name. The new enum is automatically added to the list\n * returned by {@link #values}.\n *\n * @param name The enum name. This name must not be in use by an other enum of this type.\n */\n private TopicCategory(final String name) {\n super(name, VALUES);\n }\n\n /**\n * Returns the list of {@code TopicCategory}s.\n *\n * @return The list of codes declared in the current JVM.\n */\n public static TopicCategory[] values() {\n synchronized (VALUES) {\n return VALUES.toArray(new TopicCategory[VALUES.size()]);\n }\n }\n\n /**\n * Returns the list of enumerations of the same kind than this enum.\n */\n @Override\n public TopicCategory[] family() {\n retu", "post_mask_code": "\n }\n\n /**\n * Returns the topic category that matches the given string, or returns a new one if none match\n * it.\n *\n * @param code The name of the code to fetch or to create.\n * @return A code matching the given name.\n */\n public static TopicCategory valueOf(String code) {\n return valueOf(TopicCategory.class, code);\n }\n}\n"} {"task_id": "Java_1701", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/geotools/geotools/modules/library/opengis/src/main/java/org/opengis/metadata/identification/TopicCategory.java", "mask_start_position": 9123, "mask_end_position": 9280, "canonical_solution": "public static TopicCategory[] values() {\n synchronized (VALUES) {\n return VALUES.toArray(new TopicCategory[VALUES.size()]);\n }\n }", "pre_mask_code": "/*\n * GeoTools - The Open Source Java GIS Toolkit\n * http://geotools.org\n *\n *\n * All Rights Reserved. http://example.com\n */\npackage org.opengis.metadata.identification;\n\nimport static org.opengis.annotation.Obligation.CONDITIONAL;\nimport static org.opengis.annotation.Specification.ISO_19115;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.opengis.annotation.UML;\nimport org.opengis.util.CodeList;\n\n/**\n * High-level geographic data thematic classification to assist in the grouping and search of\n * available geographic data sets. Can be used to group keywords as well. Listed examples are not\n * exhaustive.\n *\n *

NOTE: It is understood there are overlaps between general categories and the user is\n * encouraged to select the one most appropriate.\n *\n * @version ISO 19115\n * @author Martin Desruisseaux (IRD)\n * @since GeoAPI 2.0\n */\n@UML(identifier = \"MD_TopicCategoryCode\", specification = ISO_19115)\npublic final class TopicCategory extends CodeList {\n\n /**\n * Serial number for compatibility with different versions.\n */\n private static final long serialVersionUID = -4987523565852255081L;\n\n /**\n * List of all enumerations of this type. Must be declared before any enum declaration.\n */\n private static final List VALUES = new ArrayList<>(19);\n\n /**\n * Rearing of animals and/or cultivation of plants.\n *\n *

Examples: agriculture, irrigation, aquaculture, plantations, herding, pests and diseases\n * affecting crops and livestock.\n */\n @UML(identifier = \"farming\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory FARMING = new TopicCategory(\"FARMING\");\n\n /**\n * Flora and/or fauna in natural environment.\n *\n *

Examples: wildlife, vegetation, biological sciences, ecology, wilderness, sealife,\n * wetlands, habitat\n */\n @UML(identifier = \"biota\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory BIOTA = new TopicCategory(\"BIOTA\");\n\n /**\n * Legal land descriptions.\n *\n *

Examples: political and administrative boundaries.\n */\n @UML(identifier = \"boundaries\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory BOUNDARIES = new TopicCategory(\"BOUNDARIES\");\n\n /**\n * Processes and phenomena of the atmosphere.\n *\n *

Examples: cloud cover, weather, climate, atmospheric conditions, climate change,\n * precipitation.\n */\n @UML(identifier = \"climatologyMeteorologyAtmosphere\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory CLIMATOLOGY_METEOROLOGY_ATMOSPHERE = new TopicCategory(\"CLIMATOLOGY_METEOROLOGY_ATMOSPHERE\");\n\n /**\n * Economic activities, conditions and employment.\n *\n *

Examples: production, labour, revenue, commerce, industry, tourism and ecotourism,\n * forestry, fisheries, commercial or subsistence hunting, exploration and exploitation of\n * resources such as minerals, oil and gas.\n */\n @UML(identifier = \"economy\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory ECONOMY = new TopicCategory(\"ECONOMY\");\n\n /**\n * Height above or below sea level.\n *\n *

Examples: altitude, bathymetry, digital elevation models, slope, derived products.\n */\n @UML(identifier = \"elevation\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory ELEVATION = new TopicCategory(\"ELEVATION\");\n\n /**\n * Environmental resources, protection and conservation.\n *\n *

Examples: environmental pollution, waste storage and treatment, environmental impact\n * assessment, monitoring environmental risk, nature reserves, landscape.\n */\n @UML(identifier = \"environment\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory ENVIRONMENT = new TopicCategory(\"ENVIRONMENT\");\n\n /**\n * Information pertaining to earth sciences.\n *\n *

Examples: geophysical features and processes, geology, minerals, sciences dealing with the\n * composition, structure and origin of the earth's rocks, risks of earthquakes, volcanic\n * activity, landslides, gravity information, soils, permafrost, hydrogeology, erosion.\n */\n @UML(identifier = \"geoscientificInformation\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory GEOSCIENTIFIC_INFORMATION = new TopicCategory(\"GEOSCIENTIFIC_INFORMATION\");\n\n /**\n * Health, health services, human ecology, and safety.\n *\n *

Examples: disease and illness, factors affecting health, hygiene, substance abuse, mental\n * and physical health, health services.\n *\n * @since GeoAPI 2.1\n */\n @UML(identifier = \"health\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory HEALTH = new TopicCategory(\"HEALTH\");\n\n @UML(identifier = \"imageryBaseMapsEarthCover\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory IMAGERY_BASE_MAPS_EARTH_COVER = new TopicCategory(\"IMAGERY_BASE_MAPS_EARTH_COVER\");\n\n @UML(identifier = \"intelligenceMilitary\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory INTELLIGENCE_MILITARY = new TopicCategory(\"INTELLIGENCE_MILITARY\");\n\n /**\n * Inland water features, drainage systems and their characteristics.\n *\n *

Examples: rivers and glaciers, salt lakes, water utilization plans, dams, currents,\n * floods, water quality, hydrographic charts.\n */\n @UML(identifier = \"inlandWaters\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory INLAND_WATERS = new TopicCategory(\"INLAND_WATERS\");\n\n /**\n * Positional information and services.\n *\n *

Examples: addresses, geodetic networks, control points, postal zones and services, place\n * names.\n */\n @UML(identifier = \"location\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory LOCATION = new TopicCategory(\"LOCATION\");\n\n /**\n * Features and characteristics of salt water bodies (excluding inland waters).\n *\n *

Examples: tides, tidal waves, coastal information, reefs.\n */\n @UML(identifier = \"oceans\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory OCEANS = new TopicCategory(\"OCEANS\");\n\n /**\n * Information used for appropriate actions for future use of the land.\n *\n *

Examples: land use maps, zoning maps, cadastral surveys, land ownership.\n */\n @UML(identifier = \"planningCadastre\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory PLANNING_CADASTRE = new TopicCategory(\"PLANNING_CADASTRE\");\n\n /**\n * Characteristics of society and cultures.\n *\n *

Examples: settlements, anthropology, archaeology, education, traditional beliefs, manners\n * and customs, demographic data, recreational areas and activities, social impact assessments,\n * crime and justice, census information\n */\n @UML(identifier = \"society\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory SOCIETY = new TopicCategory(\"SOCIETY\");\n\n @UML(identifier = \"structure\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory STRUCTURE = new TopicCategory(\"STRUCTURE\");\n\n /**\n * Means and aids for conveying persons and/or goods.\n *\n *

Examples: roads, airports/airstrips, shipping routes, tunnels, nautical charts, vehicle or\n * vessel location, aeronautical charts, railways.\n */\n @UML(identifier = \"transportation\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory TRANSPORTATION = new TopicCategory(\"TRANSPORTATION\");\n\n /**\n * Energy, water and waste systems and communications infrastructure and services.\n *\n *

Examples: hydroelectricity, geothermal, solar and nuclear sources of energy, water\n * purification and distribution, sewage collection and disposal, electricity and gas\n * distribution, data communication, telecommunication, radio, communication networks.\n */\n @UML(identifier = \"utilitiesCommunication\", obligation = CONDITIONAL, specification = ISO_19115)\n public static final TopicCategory UTILITIES_COMMUNICATION = new TopicCategory(\"UTILITIES_COMMUNICATION\");\n\n /**\n * Constructs an enum with the given name. The new enum is automatically added to the list\n * returned by {@link #values}.\n *\n * @param name The enum name. This name must not be in use by an other enum of this type.\n */\n private TopicCategory(final String name) {\n super(name, VALUES);\n }\n\n /**\n * Returns the list of {@code TopicCategory}s.\n *\n * @return The list of codes declared in the current JVM.\n */\n ", "post_mask_code": "\n\n /**\n * Returns the list of enumerations of the same kind than this enum.\n */\n @Override\n public TopicCategory[] family() {\n return values();\n }\n\n /**\n * Returns the topic category that matches the given string, or returns a new one if none match\n * it.\n *\n * @param code The name of the code to fetch or to create.\n * @return A code matching the given name.\n */\n public static TopicCategory valueOf(String code) {\n return valueOf(TopicCategory.class, code);\n }\n}\n"} {"task_id": "Java_1702", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/javaee/jersey/connectors/jdk-connector/src/main/java/org/glassfish/jersey/jdk/connector/internal/WriteListener.java", "mask_start_position": 752, "mask_end_position": 794, "canonical_solution": "void onWritePossible() throws IOException;", "pre_mask_code": "package org.glassfish.jersey.jdk.connector.internal;\n\nimport java.io.IOException;\n\n/**\n * Callback notification mechanism that signals to the developer it's possible\n * to write content without blocking.\n *

\n * Based on Servlet 3.1\n */\ninterface WriteListener {\n\n /**\n * When an instance of the WriteListener is registered with a {@link BodyOutputStream},\n * this method will be invoked by the container the first time when it is possible\n * to write data. Subsequently the container will invoke this method if and only\n * if {@link BodyOutputStream#isReady()} method\n * has been called and has returned false.\n *\n * @throws IOException if an I/O related error has occurred during processing\n */\n ", "post_mask_code": "\n\n /**\n * Invoked when an error occurs writing data using the non-blocking APIs.\n */\n void onError(final Throwable t);\n}\n"} {"task_id": "Java_1703", "language": "Java", "task_type": "method_signature", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/elb/src/main/java/com/huaweicloud/sdk/elb/v2/model/UpdateL7policiesRequestBody.java", "mask_start_position": 2004, "mask_end_position": 2056, "canonical_solution": "private String toIndentedString(java.lang.Object o) ", "pre_mask_code": "package com.huaweicloud.sdk.elb.v2.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * This is a auto create Body Object\n */\npublic class UpdateL7policiesRequestBody {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"l7policy\")\n private UpdateL7policyReq l7policy;\n\n public UpdateL7policiesRequestBody withL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n return this;\n }\n\n public UpdateL7policiesRequestBody withL7policy(Consumer l7policySetter) {\n if (this.l7policy == null) {\n this.l7policy = new UpdateL7policyReq();\n l7policySetter.accept(this.l7policy);\n }\n return this;\n }\n\n /**\n * Get l7policy\n *\n * @return l7policy\n */\n public UpdateL7policyReq getL7policy() {\n return l7policy;\n }\n\n public void setL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n UpdateL7policiesRequestBody updateL7policiesRequestBody = (UpdateL7policiesRequestBody) o;\n return Objects.equals(this.l7policy, updateL7policiesRequestBody.l7policy);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(l7policy);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class UpdateL7policiesRequestBody {\\n\");\n sb.append(\" l7policy: \").append(toIndentedString(l7policy)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n ", "post_mask_code": "{\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_1704", "language": "Java", "task_type": "method_body", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/elb/src/main/java/com/huaweicloud/sdk/elb/v2/model/UpdateL7policiesRequestBody.java", "mask_start_position": 1625, "mask_end_position": 1879, "canonical_solution": "{\n StringBuilder sb = new StringBuilder();\n sb.append(\"class UpdateL7policiesRequestBody {\\n\");\n sb.append(\" l7policy: \").append(toIndentedString(l7policy)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }", "pre_mask_code": "package com.huaweicloud.sdk.elb.v2.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * This is a auto create Body Object\n */\npublic class UpdateL7policiesRequestBody {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"l7policy\")\n private UpdateL7policyReq l7policy;\n\n public UpdateL7policiesRequestBody withL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n return this;\n }\n\n public UpdateL7policiesRequestBody withL7policy(Consumer l7policySetter) {\n if (this.l7policy == null) {\n this.l7policy = new UpdateL7policyReq();\n l7policySetter.accept(this.l7policy);\n }\n return this;\n }\n\n /**\n * Get l7policy\n *\n * @return l7policy\n */\n public UpdateL7policyReq getL7policy() {\n return l7policy;\n }\n\n public void setL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n UpdateL7policiesRequestBody updateL7policiesRequestBody = (UpdateL7policiesRequestBody) o;\n return Objects.equals(this.l7policy, updateL7policiesRequestBody.l7policy);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(l7policy);\n }\n\n @Override\n public String toString() ", "post_mask_code": "\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_1705", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/elb/src/main/java/com/huaweicloud/sdk/elb/v2/model/UpdateL7policiesRequestBody.java", "mask_start_position": 1152, "mask_end_position": 1212, "canonical_solution": "\n if (this == o) {\n return true;\n }", "pre_mask_code": "package com.huaweicloud.sdk.elb.v2.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * This is a auto create Body Object\n */\npublic class UpdateL7policiesRequestBody {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"l7policy\")\n private UpdateL7policyReq l7policy;\n\n public UpdateL7policiesRequestBody withL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n return this;\n }\n\n public UpdateL7policiesRequestBody withL7policy(Consumer l7policySetter) {\n if (this.l7policy == null) {\n this.l7policy = new UpdateL7policyReq();\n l7policySetter.accept(this.l7policy);\n }\n return this;\n }\n\n /**\n * Get l7policy\n *\n * @return l7policy\n */\n public UpdateL7policyReq getL7policy() {\n return l7policy;\n }\n\n public void setL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {", "post_mask_code": "\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n UpdateL7policiesRequestBody updateL7policiesRequestBody = (UpdateL7policiesRequestBody) o;\n return Objects.equals(this.l7policy, updateL7policiesRequestBody.l7policy);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(l7policy);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class UpdateL7policiesRequestBody {\\n\");\n sb.append(\" l7policy: \").append(toIndentedString(l7policy)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_1706", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/elb/src/main/java/com/huaweicloud/sdk/elb/v2/model/UpdateL7policiesRequestBody.java", "mask_start_position": 1221, "mask_end_position": 1402, "canonical_solution": "if (o == null || getClass() != o.getClass()) {\n return false;\n }\n UpdateL7policiesRequestBody updateL7policiesRequestBody = (UpdateL7policiesRequestBody) o;", "pre_mask_code": "package com.huaweicloud.sdk.elb.v2.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * This is a auto create Body Object\n */\npublic class UpdateL7policiesRequestBody {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"l7policy\")\n private UpdateL7policyReq l7policy;\n\n public UpdateL7policiesRequestBody withL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n return this;\n }\n\n public UpdateL7policiesRequestBody withL7policy(Consumer l7policySetter) {\n if (this.l7policy == null) {\n this.l7policy = new UpdateL7policyReq();\n l7policySetter.accept(this.l7policy);\n }\n return this;\n }\n\n /**\n * Get l7policy\n *\n * @return l7policy\n */\n public UpdateL7policyReq getL7policy() {\n return l7policy;\n }\n\n public void setL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n ", "post_mask_code": "\n return Objects.equals(this.l7policy, updateL7policiesRequestBody.l7policy);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(l7policy);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class UpdateL7policiesRequestBody {\\n\");\n sb.append(\" l7policy: \").append(toIndentedString(l7policy)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_1707", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/elb/src/main/java/com/huaweicloud/sdk/elb/v2/model/UpdateL7policiesRequestBody.java", "mask_start_position": 1411, "mask_end_position": 1492, "canonical_solution": "return Objects.equals(this.l7policy, updateL7policiesRequestBody.l7policy);\n }", "pre_mask_code": "package com.huaweicloud.sdk.elb.v2.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * This is a auto create Body Object\n */\npublic class UpdateL7policiesRequestBody {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"l7policy\")\n private UpdateL7policyReq l7policy;\n\n public UpdateL7policiesRequestBody withL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n return this;\n }\n\n public UpdateL7policiesRequestBody withL7policy(Consumer l7policySetter) {\n if (this.l7policy == null) {\n this.l7policy = new UpdateL7policyReq();\n l7policySetter.accept(this.l7policy);\n }\n return this;\n }\n\n /**\n * Get l7policy\n *\n * @return l7policy\n */\n public UpdateL7policyReq getL7policy() {\n return l7policy;\n }\n\n public void setL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n UpdateL7policiesRequestBody updateL7policiesRequestBody = (UpdateL7policiesRequestBody) o;\n ", "post_mask_code": "\n\n @Override\n public int hashCode() {\n return Objects.hash(l7policy);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class UpdateL7policiesRequestBody {\\n\");\n sb.append(\" l7policy: \").append(toIndentedString(l7policy)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_1708", "language": "Java", "task_type": "single_line", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/elb/src/main/java/com/huaweicloud/sdk/elb/v2/model/UpdateL7policiesRequestBody.java", "mask_start_position": 536, "mask_end_position": 543, "canonical_solution": "policy;", "pre_mask_code": "package com.huaweicloud.sdk.elb.v2.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * This is a auto create Body Object\n */\npublic class UpdateL7policiesRequestBody {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"l7policy\")\n private UpdateL7policyReq l7policy;\n\n public UpdateL7policiesRequestBody withL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7", "post_mask_code": "\n return this;\n }\n\n public UpdateL7policiesRequestBody withL7policy(Consumer l7policySetter) {\n if (this.l7policy == null) {\n this.l7policy = new UpdateL7policyReq();\n l7policySetter.accept(this.l7policy);\n }\n return this;\n }\n\n /**\n * Get l7policy\n *\n * @return l7policy\n */\n public UpdateL7policyReq getL7policy() {\n return l7policy;\n }\n\n public void setL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n UpdateL7policiesRequestBody updateL7policiesRequestBody = (UpdateL7policiesRequestBody) o;\n return Objects.equals(this.l7policy, updateL7policiesRequestBody.l7policy);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(l7policy);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class UpdateL7policiesRequestBody {\\n\");\n sb.append(\" l7policy: \").append(toIndentedString(l7policy)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_1709", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/elb/src/main/java/com/huaweicloud/sdk/elb/v2/model/UpdateL7policiesRequestBody.java", "mask_start_position": 919, "mask_end_position": 990, "canonical_solution": "public UpdateL7policyReq getL7policy() {\n return l7policy;\n }", "pre_mask_code": "package com.huaweicloud.sdk.elb.v2.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * This is a auto create Body Object\n */\npublic class UpdateL7policiesRequestBody {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"l7policy\")\n private UpdateL7policyReq l7policy;\n\n public UpdateL7policiesRequestBody withL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n return this;\n }\n\n public UpdateL7policiesRequestBody withL7policy(Consumer l7policySetter) {\n if (this.l7policy == null) {\n this.l7policy = new UpdateL7policyReq();\n l7policySetter.accept(this.l7policy);\n }\n return this;\n }\n\n /**\n * Get l7policy\n *\n * @return l7policy\n */\n ", "post_mask_code": "\n\n public void setL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n UpdateL7policiesRequestBody updateL7policiesRequestBody = (UpdateL7policiesRequestBody) o;\n return Objects.equals(this.l7policy, updateL7policiesRequestBody.l7policy);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(l7policy);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class UpdateL7policiesRequestBody {\\n\");\n sb.append(\" l7policy: \").append(toIndentedString(l7policy)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_1710", "language": "Java", "task_type": "if_statement", "source_file": "java/github/huaweicloud/huaweicloud-sdk-java-v3/services/elb/src/main/java/com/huaweicloud/sdk/elb/v2/model/UpdateL7policiesRequestBody.java", "mask_start_position": 1221, "mask_end_position": 1303, "canonical_solution": "if (o == null || getClass() != o.getClass()) {\n return false;\n }", "pre_mask_code": "package com.huaweicloud.sdk.elb.v2.model;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport java.util.Objects;\nimport java.util.function.Consumer;\n\n/**\n * This is a auto create Body Object\n */\npublic class UpdateL7policiesRequestBody {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(value = \"l7policy\")\n private UpdateL7policyReq l7policy;\n\n public UpdateL7policiesRequestBody withL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n return this;\n }\n\n public UpdateL7policiesRequestBody withL7policy(Consumer l7policySetter) {\n if (this.l7policy == null) {\n this.l7policy = new UpdateL7policyReq();\n l7policySetter.accept(this.l7policy);\n }\n return this;\n }\n\n /**\n * Get l7policy\n *\n * @return l7policy\n */\n public UpdateL7policyReq getL7policy() {\n return l7policy;\n }\n\n public void setL7policy(UpdateL7policyReq l7policy) {\n this.l7policy = l7policy;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n ", "post_mask_code": "\n UpdateL7policiesRequestBody updateL7policiesRequestBody = (UpdateL7policiesRequestBody) o;\n return Objects.equals(this.l7policy, updateL7policiesRequestBody.l7policy);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(l7policy);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class UpdateL7policiesRequestBody {\\n\");\n sb.append(\" l7policy: \").append(toIndentedString(l7policy)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_1711", "language": "Java", "task_type": "method_signature", "source_file": "java/github/binance-chain/java-sdk/src/main/java/com/binance/dex/api/client/domain/stake/sidechain/EditSideChainValidator.java", "mask_start_position": 872, "mask_end_position": 923, "canonical_solution": "public void setCommissionRate(long commissionRate) ", "pre_mask_code": "package com.binance.dex.api.client.domain.stake.sidechain;\n\nimport com.binance.dex.api.client.domain.stake.Description;\n\n/**\n * @author Fitz.Lu\n */\npublic class EditSideChainValidator {\n\n private Description description;\n\n private String validatorAddress;\n\n private long commissionRate;\n\n private String sideChainId;\n\n private String sideFeeAddr;\n\n public EditSideChainValidator() {\n }\n\n public Description getDescription() {\n return description;\n }\n\n public void setDescription(Description description) {\n this.description = description;\n }\n\n public String getValidatorAddress() {\n return validatorAddress;\n }\n\n public void setValidatorAddress(String validatorAddress) {\n this.validatorAddress = validatorAddress;\n }\n\n public long getCommissionRate() {\n return commissionRate;\n }\n\n ", "post_mask_code": "{\n this.commissionRate = commissionRate;\n }\n\n public String getSideChainId() {\n return sideChainId;\n }\n\n public void setSideChainId(String sideChainId) {\n this.sideChainId = sideChainId;\n }\n\n public String getSideFeeAddr() {\n return sideFeeAddr;\n }\n\n public void setSideFeeAddr(String sideFeeAddr) {\n this.sideFeeAddr = sideFeeAddr;\n }\n\n @Override\n public String toString() {\n return \"EditSideChainValidator{\" + \"description=\" + description + \"\\n\" + \", validatorAddress='\" + validatorAddress + '\\'' + \"\\n\" + \", commissionRate=\" + commissionRate + \"\\n\" + \", sideChainId='\" + sideChainId + '\\'' + \"\\n\" + \", sideFeeAddr='\" + sideFeeAddr + '\\'' + \"\\n\" + '}';\n }\n}\n"} {"task_id": "Java_1712", "language": "Java", "task_type": "method_body", "source_file": "java/github/binance-chain/java-sdk/src/main/java/com/binance/dex/api/client/domain/stake/sidechain/EditSideChainValidator.java", "mask_start_position": 1365, "mask_end_position": 1658, "canonical_solution": "{\n return \"EditSideChainValidator{\" + \"description=\" + description + \"\\n\" + \", validatorAddress='\" + validatorAddress + '\\'' + \"\\n\" + \", commissionRate=\" + commissionRate + \"\\n\" + \", sideChainId='\" + sideChainId + '\\'' + \"\\n\" + \", sideFeeAddr='\" + sideFeeAddr + '\\'' + \"\\n\" + '}';\n }", "pre_mask_code": "package com.binance.dex.api.client.domain.stake.sidechain;\n\nimport com.binance.dex.api.client.domain.stake.Description;\n\n/**\n * @author Fitz.Lu\n */\npublic class EditSideChainValidator {\n\n private Description description;\n\n private String validatorAddress;\n\n private long commissionRate;\n\n private String sideChainId;\n\n private String sideFeeAddr;\n\n public EditSideChainValidator() {\n }\n\n public Description getDescription() {\n return description;\n }\n\n public void setDescription(Description description) {\n this.description = description;\n }\n\n public String getValidatorAddress() {\n return validatorAddress;\n }\n\n public void setValidatorAddress(String validatorAddress) {\n this.validatorAddress = validatorAddress;\n }\n\n public long getCommissionRate() {\n return commissionRate;\n }\n\n public void setCommissionRate(long commissionRate) {\n this.commissionRate = commissionRate;\n }\n\n public String getSideChainId() {\n return sideChainId;\n }\n\n public void setSideChainId(String sideChainId) {\n this.sideChainId = sideChainId;\n }\n\n public String getSideFeeAddr() {\n return sideFeeAddr;\n }\n\n public void setSideFeeAddr(String sideFeeAddr) {\n this.sideFeeAddr = sideFeeAddr;\n }\n\n @Override\n public String toString() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1713", "language": "Java", "task_type": "single_line", "source_file": "java/github/binance-chain/java-sdk/src/main/java/com/binance/dex/api/client/domain/stake/sidechain/EditSideChainValidator.java", "mask_start_position": 1304, "mask_end_position": 1314, "canonical_solution": "deFeeAddr;", "pre_mask_code": "package com.binance.dex.api.client.domain.stake.sidechain;\n\nimport com.binance.dex.api.client.domain.stake.Description;\n\n/**\n * @author Fitz.Lu\n */\npublic class EditSideChainValidator {\n\n private Description description;\n\n private String validatorAddress;\n\n private long commissionRate;\n\n private String sideChainId;\n\n private String sideFeeAddr;\n\n public EditSideChainValidator() {\n }\n\n public Description getDescription() {\n return description;\n }\n\n public void setDescription(Description description) {\n this.description = description;\n }\n\n public String getValidatorAddress() {\n return validatorAddress;\n }\n\n public void setValidatorAddress(String validatorAddress) {\n this.validatorAddress = validatorAddress;\n }\n\n public long getCommissionRate() {\n return commissionRate;\n }\n\n public void setCommissionRate(long commissionRate) {\n this.commissionRate = commissionRate;\n }\n\n public String getSideChainId() {\n return sideChainId;\n }\n\n public void setSideChainId(String sideChainId) {\n this.sideChainId = sideChainId;\n }\n\n public String getSideFeeAddr() {\n return sideFeeAddr;\n }\n\n public void setSideFeeAddr(String sideFeeAddr) {\n this.sideFeeAddr = si", "post_mask_code": "\n }\n\n @Override\n public String toString() {\n return \"EditSideChainValidator{\" + \"description=\" + description + \"\\n\" + \", validatorAddress='\" + validatorAddress + '\\'' + \"\\n\" + \", commissionRate=\" + commissionRate + \"\\n\" + \", sideChainId='\" + sideChainId + '\\'' + \"\\n\" + \", sideFeeAddr='\" + sideFeeAddr + '\\'' + \"\\n\" + '}';\n }\n}\n"} {"task_id": "Java_1714", "language": "Java", "task_type": "method_signature", "source_file": "java/github/sanyouyugan/Mas/core/src/main/java/com/qiudaoyu/monitor/df/MMonitor.java", "mask_start_position": 3716, "mask_end_position": 3752, "canonical_solution": "public void onTrimMemory(int level) ", "pre_mask_code": "package com.qiudaoyu.monitor.df;\n\nimport android.content.Context;\nimport com.qiudaoyu.monitor.Monitor;\nimport com.qiudaoyu.monitor.analysis.MasData;\nimport com.qiudaoyu.monitor.df.config.DFConfigManager;\nimport com.qiudaoyu.monitor.df.upload.MUploadService;\nimport com.qiudaoyu.monitor.log.MLog;\nimport com.qiudaoyu.monitor.log.mlog.MethodValueAopHandler;\nimport com.qiudaoyu.monitor.utils.AppUtils;\nimport com.qiudaoyu.monitor.utils.EmptyUtils;\nimport com.qiudaoyu.monitor.BuildConfig;\nimport org.json.JSONObject;\nimport java.util.Map;\n\npublic class MMonitor {\n\n public final static String TEST_URL = \"10.1.27.50\";\n\n public final static int TEST_PROT = 10000;\n\n private static MMonitor msInstance;\n\n private MUploadService.Info info;\n\n private MasData masData;\n\n private boolean debug;\n\n private MMonitor(MUploadService.Info info, boolean isDebug) {\n this.info = info;\n debug = isDebug;\n masData = MasData.getInstance();\n masData.setAppKey(info.appkey);\n }\n\n public static MMonitor getInstance() {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should build MMonitor fisrt!!!\");\n }\n return msInstance;\n }\n\n public MUploadService.Info getInfo() {\n return info;\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety);\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety, String parId) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety, parId);\n }\n\n /**\n * 获取当前线程前置操作的Id\n */\n public String getParentId() {\n return masData.getParentId();\n }\n\n /**\n * @param cusParentId\n */\n public void setParentId(String cusParentId) {\n masData.setParentId(cusParentId);\n }\n\n /**\n * 传递entityId和userId\n *\n * @param entityId\n * @param userId\n */\n public void setUserId(final String entityId, final String userId) {\n masData.setUserId(entityId, userId);\n }\n\n /**\n * 设置每个时间都携带的业务数据\n *\n * @param properties\n */\n public void setDynamicProperties(Map properties) {\n masData.setDynamicProperties(properties);\n }\n\n public void start() {\n MUploadService.getInstance().initialize(info);\n if (AppUtils.isMainProcess(info.context, info.pkgName)) {\n Monitor.start();\n }\n }\n\n public String getAppKey() {\n return info.appkey;\n }\n\n public void destroy() {\n if (masData != null) {\n masData.shutDown();\n }\n Monitor.shutDown();\n MUploadService.getInstance().shutDown();\n DFConfigManager.getInstance().shutDown();\n }\n\n public boolean isDebug() {\n return debug;\n }\n\n public void onLowMemory() {\n }\n\n ", "post_mask_code": "{\n }\n\n public static class Builder {\n\n private Context context;\n\n private String appkey;\n\n private String appSecret;\n\n private String pkgName;\n\n private String appVer;\n\n private String path;\n\n private short heartBeatInterval;\n\n private boolean isDebug;\n\n private MethodValueAopHandler handler;\n\n private boolean level;\n\n private String prefix;\n\n private MLog.LogInterface logInterface;\n\n private String url;\n\n private int port = -1;\n\n private int[] types;\n\n public static Builder newBuilder() {\n return new Builder();\n }\n\n public Builder isDebugEnalbe(boolean isDebug) {\n this.isDebug = isDebug;\n return this;\n }\n\n public Builder context(Context context) {\n this.context = context;\n return this;\n }\n\n public Builder appKey(String appkey, String appSecret) {\n this.appkey = appkey;\n this.appSecret = appSecret;\n return this;\n }\n\n public Builder appInfo(String pkgName, String appVer) {\n this.pkgName = pkgName;\n this.appVer = appVer;\n return this;\n }\n\n public Builder uploadService(String url, int port, String cachePath, short heartBeatInterval) {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < 0 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n this.url = url;\n this.port = port;\n this.path = cachePath;\n this.heartBeatInterval = heartBeatInterval;\n return this;\n }\n\n public Builder mAopHandler(MethodValueAopHandler handler) {\n this.handler = handler;\n return this;\n }\n\n public Builder MLog(boolean level, String prefix, MLog.LogInterface logInterface) {\n this.level = level;\n this.logInterface = logInterface;\n this.prefix = prefix;\n return this;\n }\n\n public Builder install(int[] types) {\n this.types = types;\n return this;\n }\n\n public MMonitor build() {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < -1 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n Monitor.Builder.newBuilder().context(context).isDebugEnalbe(isDebug).uploadService(MUploadService.getInstance()).configManager(DFConfigManager.getInstance()).MLog(level, prefix, logInterface).mAopHandler(handler).install(types).build();\n // 生成初始化数据\n MUploadService.Info info = new MUploadService.Info(context, MasData.getDeviceId(context), pkgName, appkey, appSecret, appVer, BuildConfig.SDK_VER, path, heartBeatInterval, url, port);\n msInstance = new MMonitor(info, isDebug);\n return msInstance;\n }\n }\n}\n"} {"task_id": "Java_1715", "language": "Java", "task_type": "method_body", "source_file": "java/github/sanyouyugan/Mas/core/src/main/java/com/qiudaoyu/monitor/df/MMonitor.java", "mask_start_position": 5634, "mask_end_position": 5706, "canonical_solution": "{\n this.handler = handler;\n return this;\n }", "pre_mask_code": "package com.qiudaoyu.monitor.df;\n\nimport android.content.Context;\nimport com.qiudaoyu.monitor.Monitor;\nimport com.qiudaoyu.monitor.analysis.MasData;\nimport com.qiudaoyu.monitor.df.config.DFConfigManager;\nimport com.qiudaoyu.monitor.df.upload.MUploadService;\nimport com.qiudaoyu.monitor.log.MLog;\nimport com.qiudaoyu.monitor.log.mlog.MethodValueAopHandler;\nimport com.qiudaoyu.monitor.utils.AppUtils;\nimport com.qiudaoyu.monitor.utils.EmptyUtils;\nimport com.qiudaoyu.monitor.BuildConfig;\nimport org.json.JSONObject;\nimport java.util.Map;\n\npublic class MMonitor {\n\n public final static String TEST_URL = \"10.1.27.50\";\n\n public final static int TEST_PROT = 10000;\n\n private static MMonitor msInstance;\n\n private MUploadService.Info info;\n\n private MasData masData;\n\n private boolean debug;\n\n private MMonitor(MUploadService.Info info, boolean isDebug) {\n this.info = info;\n debug = isDebug;\n masData = MasData.getInstance();\n masData.setAppKey(info.appkey);\n }\n\n public static MMonitor getInstance() {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should build MMonitor fisrt!!!\");\n }\n return msInstance;\n }\n\n public MUploadService.Info getInfo() {\n return info;\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety);\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety, String parId) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety, parId);\n }\n\n /**\n * 获取当前线程前置操作的Id\n */\n public String getParentId() {\n return masData.getParentId();\n }\n\n /**\n * @param cusParentId\n */\n public void setParentId(String cusParentId) {\n masData.setParentId(cusParentId);\n }\n\n /**\n * 传递entityId和userId\n *\n * @param entityId\n * @param userId\n */\n public void setUserId(final String entityId, final String userId) {\n masData.setUserId(entityId, userId);\n }\n\n /**\n * 设置每个时间都携带的业务数据\n *\n * @param properties\n */\n public void setDynamicProperties(Map properties) {\n masData.setDynamicProperties(properties);\n }\n\n public void start() {\n MUploadService.getInstance().initialize(info);\n if (AppUtils.isMainProcess(info.context, info.pkgName)) {\n Monitor.start();\n }\n }\n\n public String getAppKey() {\n return info.appkey;\n }\n\n public void destroy() {\n if (masData != null) {\n masData.shutDown();\n }\n Monitor.shutDown();\n MUploadService.getInstance().shutDown();\n DFConfigManager.getInstance().shutDown();\n }\n\n public boolean isDebug() {\n return debug;\n }\n\n public void onLowMemory() {\n }\n\n public void onTrimMemory(int level) {\n }\n\n public static class Builder {\n\n private Context context;\n\n private String appkey;\n\n private String appSecret;\n\n private String pkgName;\n\n private String appVer;\n\n private String path;\n\n private short heartBeatInterval;\n\n private boolean isDebug;\n\n private MethodValueAopHandler handler;\n\n private boolean level;\n\n private String prefix;\n\n private MLog.LogInterface logInterface;\n\n private String url;\n\n private int port = -1;\n\n private int[] types;\n\n public static Builder newBuilder() {\n return new Builder();\n }\n\n public Builder isDebugEnalbe(boolean isDebug) {\n this.isDebug = isDebug;\n return this;\n }\n\n public Builder context(Context context) {\n this.context = context;\n return this;\n }\n\n public Builder appKey(String appkey, String appSecret) {\n this.appkey = appkey;\n this.appSecret = appSecret;\n return this;\n }\n\n public Builder appInfo(String pkgName, String appVer) {\n this.pkgName = pkgName;\n this.appVer = appVer;\n return this;\n }\n\n public Builder uploadService(String url, int port, String cachePath, short heartBeatInterval) {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < 0 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n this.url = url;\n this.port = port;\n this.path = cachePath;\n this.heartBeatInterval = heartBeatInterval;\n return this;\n }\n\n public Builder mAopHandler(MethodValueAopHandler handler) ", "post_mask_code": "\n\n public Builder MLog(boolean level, String prefix, MLog.LogInterface logInterface) {\n this.level = level;\n this.logInterface = logInterface;\n this.prefix = prefix;\n return this;\n }\n\n public Builder install(int[] types) {\n this.types = types;\n return this;\n }\n\n public MMonitor build() {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < -1 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n Monitor.Builder.newBuilder().context(context).isDebugEnalbe(isDebug).uploadService(MUploadService.getInstance()).configManager(DFConfigManager.getInstance()).MLog(level, prefix, logInterface).mAopHandler(handler).install(types).build();\n // 生成初始化数据\n MUploadService.Info info = new MUploadService.Info(context, MasData.getDeviceId(context), pkgName, appkey, appSecret, appVer, BuildConfig.SDK_VER, path, heartBeatInterval, url, port);\n msInstance = new MMonitor(info, isDebug);\n return msInstance;\n }\n }\n}\n"} {"task_id": "Java_1716", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/sanyouyugan/Mas/core/src/main/java/com/qiudaoyu/monitor/df/MMonitor.java", "mask_start_position": 6095, "mask_end_position": 6370, "canonical_solution": "\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < -1 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }", "pre_mask_code": "package com.qiudaoyu.monitor.df;\n\nimport android.content.Context;\nimport com.qiudaoyu.monitor.Monitor;\nimport com.qiudaoyu.monitor.analysis.MasData;\nimport com.qiudaoyu.monitor.df.config.DFConfigManager;\nimport com.qiudaoyu.monitor.df.upload.MUploadService;\nimport com.qiudaoyu.monitor.log.MLog;\nimport com.qiudaoyu.monitor.log.mlog.MethodValueAopHandler;\nimport com.qiudaoyu.monitor.utils.AppUtils;\nimport com.qiudaoyu.monitor.utils.EmptyUtils;\nimport com.qiudaoyu.monitor.BuildConfig;\nimport org.json.JSONObject;\nimport java.util.Map;\n\npublic class MMonitor {\n\n public final static String TEST_URL = \"10.1.27.50\";\n\n public final static int TEST_PROT = 10000;\n\n private static MMonitor msInstance;\n\n private MUploadService.Info info;\n\n private MasData masData;\n\n private boolean debug;\n\n private MMonitor(MUploadService.Info info, boolean isDebug) {\n this.info = info;\n debug = isDebug;\n masData = MasData.getInstance();\n masData.setAppKey(info.appkey);\n }\n\n public static MMonitor getInstance() {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should build MMonitor fisrt!!!\");\n }\n return msInstance;\n }\n\n public MUploadService.Info getInfo() {\n return info;\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety);\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety, String parId) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety, parId);\n }\n\n /**\n * 获取当前线程前置操作的Id\n */\n public String getParentId() {\n return masData.getParentId();\n }\n\n /**\n * @param cusParentId\n */\n public void setParentId(String cusParentId) {\n masData.setParentId(cusParentId);\n }\n\n /**\n * 传递entityId和userId\n *\n * @param entityId\n * @param userId\n */\n public void setUserId(final String entityId, final String userId) {\n masData.setUserId(entityId, userId);\n }\n\n /**\n * 设置每个时间都携带的业务数据\n *\n * @param properties\n */\n public void setDynamicProperties(Map properties) {\n masData.setDynamicProperties(properties);\n }\n\n public void start() {\n MUploadService.getInstance().initialize(info);\n if (AppUtils.isMainProcess(info.context, info.pkgName)) {\n Monitor.start();\n }\n }\n\n public String getAppKey() {\n return info.appkey;\n }\n\n public void destroy() {\n if (masData != null) {\n masData.shutDown();\n }\n Monitor.shutDown();\n MUploadService.getInstance().shutDown();\n DFConfigManager.getInstance().shutDown();\n }\n\n public boolean isDebug() {\n return debug;\n }\n\n public void onLowMemory() {\n }\n\n public void onTrimMemory(int level) {\n }\n\n public static class Builder {\n\n private Context context;\n\n private String appkey;\n\n private String appSecret;\n\n private String pkgName;\n\n private String appVer;\n\n private String path;\n\n private short heartBeatInterval;\n\n private boolean isDebug;\n\n private MethodValueAopHandler handler;\n\n private boolean level;\n\n private String prefix;\n\n private MLog.LogInterface logInterface;\n\n private String url;\n\n private int port = -1;\n\n private int[] types;\n\n public static Builder newBuilder() {\n return new Builder();\n }\n\n public Builder isDebugEnalbe(boolean isDebug) {\n this.isDebug = isDebug;\n return this;\n }\n\n public Builder context(Context context) {\n this.context = context;\n return this;\n }\n\n public Builder appKey(String appkey, String appSecret) {\n this.appkey = appkey;\n this.appSecret = appSecret;\n return this;\n }\n\n public Builder appInfo(String pkgName, String appVer) {\n this.pkgName = pkgName;\n this.appVer = appVer;\n return this;\n }\n\n public Builder uploadService(String url, int port, String cachePath, short heartBeatInterval) {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < 0 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n this.url = url;\n this.port = port;\n this.path = cachePath;\n this.heartBeatInterval = heartBeatInterval;\n return this;\n }\n\n public Builder mAopHandler(MethodValueAopHandler handler) {\n this.handler = handler;\n return this;\n }\n\n public Builder MLog(boolean level, String prefix, MLog.LogInterface logInterface) {\n this.level = level;\n this.logInterface = logInterface;\n this.prefix = prefix;\n return this;\n }\n\n public Builder install(int[] types) {\n this.types = types;\n return this;\n }\n\n public MMonitor build() {", "post_mask_code": "\n Monitor.Builder.newBuilder().context(context).isDebugEnalbe(isDebug).uploadService(MUploadService.getInstance()).configManager(DFConfigManager.getInstance()).MLog(level, prefix, logInterface).mAopHandler(handler).install(types).build();\n // 生成初始化数据\n MUploadService.Info info = new MUploadService.Info(context, MasData.getDeviceId(context), pkgName, appkey, appSecret, appVer, BuildConfig.SDK_VER, path, heartBeatInterval, url, port);\n msInstance = new MMonitor(info, isDebug);\n return msInstance;\n }\n }\n}\n"} {"task_id": "Java_1717", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/sanyouyugan/Mas/core/src/main/java/com/qiudaoyu/monitor/df/MMonitor.java", "mask_start_position": 6383, "mask_end_position": 6838, "canonical_solution": "Monitor.Builder.newBuilder().context(context).isDebugEnalbe(isDebug).uploadService(MUploadService.getInstance()).configManager(DFConfigManager.getInstance()).MLog(level, prefix, logInterface).mAopHandler(handler).install(types).build();\n // 生成初始化数据\n MUploadService.Info info = new MUploadService.Info(context, MasData.getDeviceId(context), pkgName, appkey, appSecret, appVer, BuildConfig.SDK_VER, path, heartBeatInterval, url, port);", "pre_mask_code": "package com.qiudaoyu.monitor.df;\n\nimport android.content.Context;\nimport com.qiudaoyu.monitor.Monitor;\nimport com.qiudaoyu.monitor.analysis.MasData;\nimport com.qiudaoyu.monitor.df.config.DFConfigManager;\nimport com.qiudaoyu.monitor.df.upload.MUploadService;\nimport com.qiudaoyu.monitor.log.MLog;\nimport com.qiudaoyu.monitor.log.mlog.MethodValueAopHandler;\nimport com.qiudaoyu.monitor.utils.AppUtils;\nimport com.qiudaoyu.monitor.utils.EmptyUtils;\nimport com.qiudaoyu.monitor.BuildConfig;\nimport org.json.JSONObject;\nimport java.util.Map;\n\npublic class MMonitor {\n\n public final static String TEST_URL = \"10.1.27.50\";\n\n public final static int TEST_PROT = 10000;\n\n private static MMonitor msInstance;\n\n private MUploadService.Info info;\n\n private MasData masData;\n\n private boolean debug;\n\n private MMonitor(MUploadService.Info info, boolean isDebug) {\n this.info = info;\n debug = isDebug;\n masData = MasData.getInstance();\n masData.setAppKey(info.appkey);\n }\n\n public static MMonitor getInstance() {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should build MMonitor fisrt!!!\");\n }\n return msInstance;\n }\n\n public MUploadService.Info getInfo() {\n return info;\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety);\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety, String parId) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety, parId);\n }\n\n /**\n * 获取当前线程前置操作的Id\n */\n public String getParentId() {\n return masData.getParentId();\n }\n\n /**\n * @param cusParentId\n */\n public void setParentId(String cusParentId) {\n masData.setParentId(cusParentId);\n }\n\n /**\n * 传递entityId和userId\n *\n * @param entityId\n * @param userId\n */\n public void setUserId(final String entityId, final String userId) {\n masData.setUserId(entityId, userId);\n }\n\n /**\n * 设置每个时间都携带的业务数据\n *\n * @param properties\n */\n public void setDynamicProperties(Map properties) {\n masData.setDynamicProperties(properties);\n }\n\n public void start() {\n MUploadService.getInstance().initialize(info);\n if (AppUtils.isMainProcess(info.context, info.pkgName)) {\n Monitor.start();\n }\n }\n\n public String getAppKey() {\n return info.appkey;\n }\n\n public void destroy() {\n if (masData != null) {\n masData.shutDown();\n }\n Monitor.shutDown();\n MUploadService.getInstance().shutDown();\n DFConfigManager.getInstance().shutDown();\n }\n\n public boolean isDebug() {\n return debug;\n }\n\n public void onLowMemory() {\n }\n\n public void onTrimMemory(int level) {\n }\n\n public static class Builder {\n\n private Context context;\n\n private String appkey;\n\n private String appSecret;\n\n private String pkgName;\n\n private String appVer;\n\n private String path;\n\n private short heartBeatInterval;\n\n private boolean isDebug;\n\n private MethodValueAopHandler handler;\n\n private boolean level;\n\n private String prefix;\n\n private MLog.LogInterface logInterface;\n\n private String url;\n\n private int port = -1;\n\n private int[] types;\n\n public static Builder newBuilder() {\n return new Builder();\n }\n\n public Builder isDebugEnalbe(boolean isDebug) {\n this.isDebug = isDebug;\n return this;\n }\n\n public Builder context(Context context) {\n this.context = context;\n return this;\n }\n\n public Builder appKey(String appkey, String appSecret) {\n this.appkey = appkey;\n this.appSecret = appSecret;\n return this;\n }\n\n public Builder appInfo(String pkgName, String appVer) {\n this.pkgName = pkgName;\n this.appVer = appVer;\n return this;\n }\n\n public Builder uploadService(String url, int port, String cachePath, short heartBeatInterval) {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < 0 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n this.url = url;\n this.port = port;\n this.path = cachePath;\n this.heartBeatInterval = heartBeatInterval;\n return this;\n }\n\n public Builder mAopHandler(MethodValueAopHandler handler) {\n this.handler = handler;\n return this;\n }\n\n public Builder MLog(boolean level, String prefix, MLog.LogInterface logInterface) {\n this.level = level;\n this.logInterface = logInterface;\n this.prefix = prefix;\n return this;\n }\n\n public Builder install(int[] types) {\n this.types = types;\n return this;\n }\n\n public MMonitor build() {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < -1 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n ", "post_mask_code": "\n msInstance = new MMonitor(info, isDebug);\n return msInstance;\n }\n }\n}\n"} {"task_id": "Java_1718", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/sanyouyugan/Mas/core/src/main/java/com/qiudaoyu/monitor/df/MMonitor.java", "mask_start_position": 6851, "mask_end_position": 6933, "canonical_solution": "msInstance = new MMonitor(info, isDebug);\n return msInstance;\n }", "pre_mask_code": "package com.qiudaoyu.monitor.df;\n\nimport android.content.Context;\nimport com.qiudaoyu.monitor.Monitor;\nimport com.qiudaoyu.monitor.analysis.MasData;\nimport com.qiudaoyu.monitor.df.config.DFConfigManager;\nimport com.qiudaoyu.monitor.df.upload.MUploadService;\nimport com.qiudaoyu.monitor.log.MLog;\nimport com.qiudaoyu.monitor.log.mlog.MethodValueAopHandler;\nimport com.qiudaoyu.monitor.utils.AppUtils;\nimport com.qiudaoyu.monitor.utils.EmptyUtils;\nimport com.qiudaoyu.monitor.BuildConfig;\nimport org.json.JSONObject;\nimport java.util.Map;\n\npublic class MMonitor {\n\n public final static String TEST_URL = \"10.1.27.50\";\n\n public final static int TEST_PROT = 10000;\n\n private static MMonitor msInstance;\n\n private MUploadService.Info info;\n\n private MasData masData;\n\n private boolean debug;\n\n private MMonitor(MUploadService.Info info, boolean isDebug) {\n this.info = info;\n debug = isDebug;\n masData = MasData.getInstance();\n masData.setAppKey(info.appkey);\n }\n\n public static MMonitor getInstance() {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should build MMonitor fisrt!!!\");\n }\n return msInstance;\n }\n\n public MUploadService.Info getInfo() {\n return info;\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety);\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety, String parId) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety, parId);\n }\n\n /**\n * 获取当前线程前置操作的Id\n */\n public String getParentId() {\n return masData.getParentId();\n }\n\n /**\n * @param cusParentId\n */\n public void setParentId(String cusParentId) {\n masData.setParentId(cusParentId);\n }\n\n /**\n * 传递entityId和userId\n *\n * @param entityId\n * @param userId\n */\n public void setUserId(final String entityId, final String userId) {\n masData.setUserId(entityId, userId);\n }\n\n /**\n * 设置每个时间都携带的业务数据\n *\n * @param properties\n */\n public void setDynamicProperties(Map properties) {\n masData.setDynamicProperties(properties);\n }\n\n public void start() {\n MUploadService.getInstance().initialize(info);\n if (AppUtils.isMainProcess(info.context, info.pkgName)) {\n Monitor.start();\n }\n }\n\n public String getAppKey() {\n return info.appkey;\n }\n\n public void destroy() {\n if (masData != null) {\n masData.shutDown();\n }\n Monitor.shutDown();\n MUploadService.getInstance().shutDown();\n DFConfigManager.getInstance().shutDown();\n }\n\n public boolean isDebug() {\n return debug;\n }\n\n public void onLowMemory() {\n }\n\n public void onTrimMemory(int level) {\n }\n\n public static class Builder {\n\n private Context context;\n\n private String appkey;\n\n private String appSecret;\n\n private String pkgName;\n\n private String appVer;\n\n private String path;\n\n private short heartBeatInterval;\n\n private boolean isDebug;\n\n private MethodValueAopHandler handler;\n\n private boolean level;\n\n private String prefix;\n\n private MLog.LogInterface logInterface;\n\n private String url;\n\n private int port = -1;\n\n private int[] types;\n\n public static Builder newBuilder() {\n return new Builder();\n }\n\n public Builder isDebugEnalbe(boolean isDebug) {\n this.isDebug = isDebug;\n return this;\n }\n\n public Builder context(Context context) {\n this.context = context;\n return this;\n }\n\n public Builder appKey(String appkey, String appSecret) {\n this.appkey = appkey;\n this.appSecret = appSecret;\n return this;\n }\n\n public Builder appInfo(String pkgName, String appVer) {\n this.pkgName = pkgName;\n this.appVer = appVer;\n return this;\n }\n\n public Builder uploadService(String url, int port, String cachePath, short heartBeatInterval) {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < 0 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n this.url = url;\n this.port = port;\n this.path = cachePath;\n this.heartBeatInterval = heartBeatInterval;\n return this;\n }\n\n public Builder mAopHandler(MethodValueAopHandler handler) {\n this.handler = handler;\n return this;\n }\n\n public Builder MLog(boolean level, String prefix, MLog.LogInterface logInterface) {\n this.level = level;\n this.logInterface = logInterface;\n this.prefix = prefix;\n return this;\n }\n\n public Builder install(int[] types) {\n this.types = types;\n return this;\n }\n\n public MMonitor build() {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < -1 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n Monitor.Builder.newBuilder().context(context).isDebugEnalbe(isDebug).uploadService(MUploadService.getInstance()).configManager(DFConfigManager.getInstance()).MLog(level, prefix, logInterface).mAopHandler(handler).install(types).build();\n // 生成初始化数据\n MUploadService.Info info = new MUploadService.Info(context, MasData.getDeviceId(context), pkgName, appkey, appSecret, appVer, BuildConfig.SDK_VER, path, heartBeatInterval, url, port);\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1719", "language": "Java", "task_type": "single_line", "source_file": "java/github/sanyouyugan/Mas/core/src/main/java/com/qiudaoyu/monitor/df/MMonitor.java", "mask_start_position": 4918, "mask_end_position": 4934, "canonical_solution": "gName = pkgName;", "pre_mask_code": "package com.qiudaoyu.monitor.df;\n\nimport android.content.Context;\nimport com.qiudaoyu.monitor.Monitor;\nimport com.qiudaoyu.monitor.analysis.MasData;\nimport com.qiudaoyu.monitor.df.config.DFConfigManager;\nimport com.qiudaoyu.monitor.df.upload.MUploadService;\nimport com.qiudaoyu.monitor.log.MLog;\nimport com.qiudaoyu.monitor.log.mlog.MethodValueAopHandler;\nimport com.qiudaoyu.monitor.utils.AppUtils;\nimport com.qiudaoyu.monitor.utils.EmptyUtils;\nimport com.qiudaoyu.monitor.BuildConfig;\nimport org.json.JSONObject;\nimport java.util.Map;\n\npublic class MMonitor {\n\n public final static String TEST_URL = \"10.1.27.50\";\n\n public final static int TEST_PROT = 10000;\n\n private static MMonitor msInstance;\n\n private MUploadService.Info info;\n\n private MasData masData;\n\n private boolean debug;\n\n private MMonitor(MUploadService.Info info, boolean isDebug) {\n this.info = info;\n debug = isDebug;\n masData = MasData.getInstance();\n masData.setAppKey(info.appkey);\n }\n\n public static MMonitor getInstance() {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should build MMonitor fisrt!!!\");\n }\n return msInstance;\n }\n\n public MUploadService.Info getInfo() {\n return info;\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety);\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety, String parId) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety, parId);\n }\n\n /**\n * 获取当前线程前置操作的Id\n */\n public String getParentId() {\n return masData.getParentId();\n }\n\n /**\n * @param cusParentId\n */\n public void setParentId(String cusParentId) {\n masData.setParentId(cusParentId);\n }\n\n /**\n * 传递entityId和userId\n *\n * @param entityId\n * @param userId\n */\n public void setUserId(final String entityId, final String userId) {\n masData.setUserId(entityId, userId);\n }\n\n /**\n * 设置每个时间都携带的业务数据\n *\n * @param properties\n */\n public void setDynamicProperties(Map properties) {\n masData.setDynamicProperties(properties);\n }\n\n public void start() {\n MUploadService.getInstance().initialize(info);\n if (AppUtils.isMainProcess(info.context, info.pkgName)) {\n Monitor.start();\n }\n }\n\n public String getAppKey() {\n return info.appkey;\n }\n\n public void destroy() {\n if (masData != null) {\n masData.shutDown();\n }\n Monitor.shutDown();\n MUploadService.getInstance().shutDown();\n DFConfigManager.getInstance().shutDown();\n }\n\n public boolean isDebug() {\n return debug;\n }\n\n public void onLowMemory() {\n }\n\n public void onTrimMemory(int level) {\n }\n\n public static class Builder {\n\n private Context context;\n\n private String appkey;\n\n private String appSecret;\n\n private String pkgName;\n\n private String appVer;\n\n private String path;\n\n private short heartBeatInterval;\n\n private boolean isDebug;\n\n private MethodValueAopHandler handler;\n\n private boolean level;\n\n private String prefix;\n\n private MLog.LogInterface logInterface;\n\n private String url;\n\n private int port = -1;\n\n private int[] types;\n\n public static Builder newBuilder() {\n return new Builder();\n }\n\n public Builder isDebugEnalbe(boolean isDebug) {\n this.isDebug = isDebug;\n return this;\n }\n\n public Builder context(Context context) {\n this.context = context;\n return this;\n }\n\n public Builder appKey(String appkey, String appSecret) {\n this.appkey = appkey;\n this.appSecret = appSecret;\n return this;\n }\n\n public Builder appInfo(String pkgName, String appVer) {\n this.pk", "post_mask_code": "\n this.appVer = appVer;\n return this;\n }\n\n public Builder uploadService(String url, int port, String cachePath, short heartBeatInterval) {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < 0 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n this.url = url;\n this.port = port;\n this.path = cachePath;\n this.heartBeatInterval = heartBeatInterval;\n return this;\n }\n\n public Builder mAopHandler(MethodValueAopHandler handler) {\n this.handler = handler;\n return this;\n }\n\n public Builder MLog(boolean level, String prefix, MLog.LogInterface logInterface) {\n this.level = level;\n this.logInterface = logInterface;\n this.prefix = prefix;\n return this;\n }\n\n public Builder install(int[] types) {\n this.types = types;\n return this;\n }\n\n public MMonitor build() {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < -1 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n Monitor.Builder.newBuilder().context(context).isDebugEnalbe(isDebug).uploadService(MUploadService.getInstance()).configManager(DFConfigManager.getInstance()).MLog(level, prefix, logInterface).mAopHandler(handler).install(types).build();\n // 生成初始化数据\n MUploadService.Info info = new MUploadService.Info(context, MasData.getDeviceId(context), pkgName, appkey, appSecret, appVer, BuildConfig.SDK_VER, path, heartBeatInterval, url, port);\n msInstance = new MMonitor(info, isDebug);\n return msInstance;\n }\n }\n}\n"} {"task_id": "Java_1720", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/sanyouyugan/Mas/core/src/main/java/com/qiudaoyu/monitor/df/MMonitor.java", "mask_start_position": 2488, "mask_end_position": 2561, "canonical_solution": "public String getParentId() {\n return masData.getParentId();\n }", "pre_mask_code": "package com.qiudaoyu.monitor.df;\n\nimport android.content.Context;\nimport com.qiudaoyu.monitor.Monitor;\nimport com.qiudaoyu.monitor.analysis.MasData;\nimport com.qiudaoyu.monitor.df.config.DFConfigManager;\nimport com.qiudaoyu.monitor.df.upload.MUploadService;\nimport com.qiudaoyu.monitor.log.MLog;\nimport com.qiudaoyu.monitor.log.mlog.MethodValueAopHandler;\nimport com.qiudaoyu.monitor.utils.AppUtils;\nimport com.qiudaoyu.monitor.utils.EmptyUtils;\nimport com.qiudaoyu.monitor.BuildConfig;\nimport org.json.JSONObject;\nimport java.util.Map;\n\npublic class MMonitor {\n\n public final static String TEST_URL = \"10.1.27.50\";\n\n public final static int TEST_PROT = 10000;\n\n private static MMonitor msInstance;\n\n private MUploadService.Info info;\n\n private MasData masData;\n\n private boolean debug;\n\n private MMonitor(MUploadService.Info info, boolean isDebug) {\n this.info = info;\n debug = isDebug;\n masData = MasData.getInstance();\n masData.setAppKey(info.appkey);\n }\n\n public static MMonitor getInstance() {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should build MMonitor fisrt!!!\");\n }\n return msInstance;\n }\n\n public MUploadService.Info getInfo() {\n return info;\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety);\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety, String parId) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety, parId);\n }\n\n /**\n * 获取当前线程前置操作的Id\n */\n ", "post_mask_code": "\n\n /**\n * @param cusParentId\n */\n public void setParentId(String cusParentId) {\n masData.setParentId(cusParentId);\n }\n\n /**\n * 传递entityId和userId\n *\n * @param entityId\n * @param userId\n */\n public void setUserId(final String entityId, final String userId) {\n masData.setUserId(entityId, userId);\n }\n\n /**\n * 设置每个时间都携带的业务数据\n *\n * @param properties\n */\n public void setDynamicProperties(Map properties) {\n masData.setDynamicProperties(properties);\n }\n\n public void start() {\n MUploadService.getInstance().initialize(info);\n if (AppUtils.isMainProcess(info.context, info.pkgName)) {\n Monitor.start();\n }\n }\n\n public String getAppKey() {\n return info.appkey;\n }\n\n public void destroy() {\n if (masData != null) {\n masData.shutDown();\n }\n Monitor.shutDown();\n MUploadService.getInstance().shutDown();\n DFConfigManager.getInstance().shutDown();\n }\n\n public boolean isDebug() {\n return debug;\n }\n\n public void onLowMemory() {\n }\n\n public void onTrimMemory(int level) {\n }\n\n public static class Builder {\n\n private Context context;\n\n private String appkey;\n\n private String appSecret;\n\n private String pkgName;\n\n private String appVer;\n\n private String path;\n\n private short heartBeatInterval;\n\n private boolean isDebug;\n\n private MethodValueAopHandler handler;\n\n private boolean level;\n\n private String prefix;\n\n private MLog.LogInterface logInterface;\n\n private String url;\n\n private int port = -1;\n\n private int[] types;\n\n public static Builder newBuilder() {\n return new Builder();\n }\n\n public Builder isDebugEnalbe(boolean isDebug) {\n this.isDebug = isDebug;\n return this;\n }\n\n public Builder context(Context context) {\n this.context = context;\n return this;\n }\n\n public Builder appKey(String appkey, String appSecret) {\n this.appkey = appkey;\n this.appSecret = appSecret;\n return this;\n }\n\n public Builder appInfo(String pkgName, String appVer) {\n this.pkgName = pkgName;\n this.appVer = appVer;\n return this;\n }\n\n public Builder uploadService(String url, int port, String cachePath, short heartBeatInterval) {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < 0 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n this.url = url;\n this.port = port;\n this.path = cachePath;\n this.heartBeatInterval = heartBeatInterval;\n return this;\n }\n\n public Builder mAopHandler(MethodValueAopHandler handler) {\n this.handler = handler;\n return this;\n }\n\n public Builder MLog(boolean level, String prefix, MLog.LogInterface logInterface) {\n this.level = level;\n this.logInterface = logInterface;\n this.prefix = prefix;\n return this;\n }\n\n public Builder install(int[] types) {\n this.types = types;\n return this;\n }\n\n public MMonitor build() {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < -1 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n Monitor.Builder.newBuilder().context(context).isDebugEnalbe(isDebug).uploadService(MUploadService.getInstance()).configManager(DFConfigManager.getInstance()).MLog(level, prefix, logInterface).mAopHandler(handler).install(types).build();\n // 生成初始化数据\n MUploadService.Info info = new MUploadService.Info(context, MasData.getDeviceId(context), pkgName, appkey, appSecret, appVer, BuildConfig.SDK_VER, path, heartBeatInterval, url, port);\n msInstance = new MMonitor(info, isDebug);\n return msInstance;\n }\n }\n}\n"} {"task_id": "Java_1721", "language": "Java", "task_type": "if_statement", "source_file": "java/github/sanyouyugan/Mas/core/src/main/java/com/qiudaoyu/monitor/df/MMonitor.java", "mask_start_position": 6247, "mask_end_position": 6370, "canonical_solution": "if (port < -1 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }", "pre_mask_code": "package com.qiudaoyu.monitor.df;\n\nimport android.content.Context;\nimport com.qiudaoyu.monitor.Monitor;\nimport com.qiudaoyu.monitor.analysis.MasData;\nimport com.qiudaoyu.monitor.df.config.DFConfigManager;\nimport com.qiudaoyu.monitor.df.upload.MUploadService;\nimport com.qiudaoyu.monitor.log.MLog;\nimport com.qiudaoyu.monitor.log.mlog.MethodValueAopHandler;\nimport com.qiudaoyu.monitor.utils.AppUtils;\nimport com.qiudaoyu.monitor.utils.EmptyUtils;\nimport com.qiudaoyu.monitor.BuildConfig;\nimport org.json.JSONObject;\nimport java.util.Map;\n\npublic class MMonitor {\n\n public final static String TEST_URL = \"10.1.27.50\";\n\n public final static int TEST_PROT = 10000;\n\n private static MMonitor msInstance;\n\n private MUploadService.Info info;\n\n private MasData masData;\n\n private boolean debug;\n\n private MMonitor(MUploadService.Info info, boolean isDebug) {\n this.info = info;\n debug = isDebug;\n masData = MasData.getInstance();\n masData.setAppKey(info.appkey);\n }\n\n public static MMonitor getInstance() {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should build MMonitor fisrt!!!\");\n }\n return msInstance;\n }\n\n public MUploadService.Info getInfo() {\n return info;\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety);\n }\n\n /**\n * 发送自定义数据\n *\n * @param eventType\n * @param propety\n */\n public void trackBusUserEvent(String eventType, JSONObject propety, String parId) {\n if (msInstance == null) {\n throw new IllegalStateException(\"you should init monitor fisrt!!!\");\n }\n if (EmptyUtils.isEmpty(eventType)) {\n throw new IllegalArgumentException(\"eventType can not be null or empty!!!\");\n }\n if (propety == null) {\n propety = new JSONObject();\n }\n masData.trackBusUserEvent(eventType, propety, parId);\n }\n\n /**\n * 获取当前线程前置操作的Id\n */\n public String getParentId() {\n return masData.getParentId();\n }\n\n /**\n * @param cusParentId\n */\n public void setParentId(String cusParentId) {\n masData.setParentId(cusParentId);\n }\n\n /**\n * 传递entityId和userId\n *\n * @param entityId\n * @param userId\n */\n public void setUserId(final String entityId, final String userId) {\n masData.setUserId(entityId, userId);\n }\n\n /**\n * 设置每个时间都携带的业务数据\n *\n * @param properties\n */\n public void setDynamicProperties(Map properties) {\n masData.setDynamicProperties(properties);\n }\n\n public void start() {\n MUploadService.getInstance().initialize(info);\n if (AppUtils.isMainProcess(info.context, info.pkgName)) {\n Monitor.start();\n }\n }\n\n public String getAppKey() {\n return info.appkey;\n }\n\n public void destroy() {\n if (masData != null) {\n masData.shutDown();\n }\n Monitor.shutDown();\n MUploadService.getInstance().shutDown();\n DFConfigManager.getInstance().shutDown();\n }\n\n public boolean isDebug() {\n return debug;\n }\n\n public void onLowMemory() {\n }\n\n public void onTrimMemory(int level) {\n }\n\n public static class Builder {\n\n private Context context;\n\n private String appkey;\n\n private String appSecret;\n\n private String pkgName;\n\n private String appVer;\n\n private String path;\n\n private short heartBeatInterval;\n\n private boolean isDebug;\n\n private MethodValueAopHandler handler;\n\n private boolean level;\n\n private String prefix;\n\n private MLog.LogInterface logInterface;\n\n private String url;\n\n private int port = -1;\n\n private int[] types;\n\n public static Builder newBuilder() {\n return new Builder();\n }\n\n public Builder isDebugEnalbe(boolean isDebug) {\n this.isDebug = isDebug;\n return this;\n }\n\n public Builder context(Context context) {\n this.context = context;\n return this;\n }\n\n public Builder appKey(String appkey, String appSecret) {\n this.appkey = appkey;\n this.appSecret = appSecret;\n return this;\n }\n\n public Builder appInfo(String pkgName, String appVer) {\n this.pkgName = pkgName;\n this.appVer = appVer;\n return this;\n }\n\n public Builder uploadService(String url, int port, String cachePath, short heartBeatInterval) {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n if (port < 0 || port > 66000) {\n throw new IllegalArgumentException(\"port can't be \" + port);\n }\n this.url = url;\n this.port = port;\n this.path = cachePath;\n this.heartBeatInterval = heartBeatInterval;\n return this;\n }\n\n public Builder mAopHandler(MethodValueAopHandler handler) {\n this.handler = handler;\n return this;\n }\n\n public Builder MLog(boolean level, String prefix, MLog.LogInterface logInterface) {\n this.level = level;\n this.logInterface = logInterface;\n this.prefix = prefix;\n return this;\n }\n\n public Builder install(int[] types) {\n this.types = types;\n return this;\n }\n\n public MMonitor build() {\n if (EmptyUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"url can't be null or empty\");\n }\n ", "post_mask_code": "\n Monitor.Builder.newBuilder().context(context).isDebugEnalbe(isDebug).uploadService(MUploadService.getInstance()).configManager(DFConfigManager.getInstance()).MLog(level, prefix, logInterface).mAopHandler(handler).install(types).build();\n // 生成初始化数据\n MUploadService.Info info = new MUploadService.Info(context, MasData.getDeviceId(context), pkgName, appkey, appSecret, appVer, BuildConfig.SDK_VER, path, heartBeatInterval, url, port);\n msInstance = new MMonitor(info, isDebug);\n return msInstance;\n }\n }\n}\n"} {"task_id": "Java_1722", "language": "Java", "task_type": "method_signature", "source_file": "java/github/hortonworks/ratis/ratis-common/src/main/java/org/apache/ratis/util/DataBlockingQueue.java", "mask_start_position": 3309, "mask_end_position": 3373, "canonical_solution": "public E poll(TimeDuration timeout) throws InterruptedException ", "pre_mask_code": "package org.apache.ratis.util;\n\nimport org.apache.ratis.util.function.CheckedFunctionWithTimeout;\nimport org.apache.ratis.util.function.TriConsumer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.ToIntFunction;\n\n/**\n * A queue for data elements\n * such that the queue imposes limits on both number of elements and the data size in bytes.\n *\n * Null element is NOT supported.\n *\n * This class is threadsafe.\n */\npublic class DataBlockingQueue extends DataQueue {\n\n public static final Logger LOG = LoggerFactory.getLogger(DataBlockingQueue.class);\n\n private final Lock lock = new ReentrantLock();\n\n private final Condition notFull = lock.newCondition();\n\n private final Condition notEmpty = lock.newCondition();\n\n public DataBlockingQueue(Object name, SizeInBytes byteLimit, int elementLimit, ToIntFunction getNumBytes) {\n super(name, byteLimit, elementLimit, getNumBytes);\n }\n\n @Override\n public int getNumBytes() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumBytes();\n }\n }\n\n @Override\n public int getNumElements() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumElements();\n }\n }\n\n @Override\n public void clear() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n super.clear();\n notFull.signal();\n }\n }\n\n @Override\n public boolean offer(E element) {\n Objects.requireNonNull(element, \"element == null\");\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n return false;\n }\n }\n\n /**\n * Adds an element to this queue, waiting up to the given timeout.\n *\n * @return true if the element is added successfully;\n * otherwise, the element is not added, return false.\n */\n public boolean offer(E element, TimeDuration timeout) throws InterruptedException {\n Objects.requireNonNull(element, \"element == null\");\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n if (nanos <= 0) {\n return false;\n }\n nanos = notFull.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public E poll() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n }\n return polled;\n }\n }\n\n /**\n * Poll out the head element from this queue, waiting up to the given timeout.\n */\n ", "post_mask_code": "{\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n return polled;\n }\n if (nanos <= 0) {\n return null;\n }\n nanos = notEmpty.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public List pollList(long timeoutMs, CheckedFunctionWithTimeout getResult, TriConsumer timeoutHandler) throws THROWABLE {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final List results = super.pollList(timeoutMs, getResult, timeoutHandler);\n if (!results.isEmpty()) {\n notFull.signal();\n }\n return results;\n }\n }\n}\n"} {"task_id": "Java_1723", "language": "Java", "task_type": "method_body", "source_file": "java/github/hortonworks/ratis/ratis-common/src/main/java/org/apache/ratis/util/DataBlockingQueue.java", "mask_start_position": 1608, "mask_end_position": 1755, "canonical_solution": "{\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n super.clear();\n notFull.signal();\n }\n }", "pre_mask_code": "package org.apache.ratis.util;\n\nimport org.apache.ratis.util.function.CheckedFunctionWithTimeout;\nimport org.apache.ratis.util.function.TriConsumer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.ToIntFunction;\n\n/**\n * A queue for data elements\n * such that the queue imposes limits on both number of elements and the data size in bytes.\n *\n * Null element is NOT supported.\n *\n * This class is threadsafe.\n */\npublic class DataBlockingQueue extends DataQueue {\n\n public static final Logger LOG = LoggerFactory.getLogger(DataBlockingQueue.class);\n\n private final Lock lock = new ReentrantLock();\n\n private final Condition notFull = lock.newCondition();\n\n private final Condition notEmpty = lock.newCondition();\n\n public DataBlockingQueue(Object name, SizeInBytes byteLimit, int elementLimit, ToIntFunction getNumBytes) {\n super(name, byteLimit, elementLimit, getNumBytes);\n }\n\n @Override\n public int getNumBytes() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumBytes();\n }\n }\n\n @Override\n public int getNumElements() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumElements();\n }\n }\n\n @Override\n public void clear() ", "post_mask_code": "\n\n @Override\n public boolean offer(E element) {\n Objects.requireNonNull(element, \"element == null\");\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n return false;\n }\n }\n\n /**\n * Adds an element to this queue, waiting up to the given timeout.\n *\n * @return true if the element is added successfully;\n * otherwise, the element is not added, return false.\n */\n public boolean offer(E element, TimeDuration timeout) throws InterruptedException {\n Objects.requireNonNull(element, \"element == null\");\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n if (nanos <= 0) {\n return false;\n }\n nanos = notFull.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public E poll() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n }\n return polled;\n }\n }\n\n /**\n * Poll out the head element from this queue, waiting up to the given timeout.\n */\n public E poll(TimeDuration timeout) throws InterruptedException {\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n return polled;\n }\n if (nanos <= 0) {\n return null;\n }\n nanos = notEmpty.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public List pollList(long timeoutMs, CheckedFunctionWithTimeout getResult, TriConsumer timeoutHandler) throws THROWABLE {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final List results = super.pollList(timeoutMs, getResult, timeoutHandler);\n if (!results.isEmpty()) {\n notFull.signal();\n }\n return results;\n }\n }\n}\n"} {"task_id": "Java_1724", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/hortonworks/ratis/ratis-common/src/main/java/org/apache/ratis/util/DataBlockingQueue.java", "mask_start_position": 1808, "mask_end_position": 1868, "canonical_solution": "\n Objects.requireNonNull(element, \"element == null\");", "pre_mask_code": "package org.apache.ratis.util;\n\nimport org.apache.ratis.util.function.CheckedFunctionWithTimeout;\nimport org.apache.ratis.util.function.TriConsumer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.ToIntFunction;\n\n/**\n * A queue for data elements\n * such that the queue imposes limits on both number of elements and the data size in bytes.\n *\n * Null element is NOT supported.\n *\n * This class is threadsafe.\n */\npublic class DataBlockingQueue extends DataQueue {\n\n public static final Logger LOG = LoggerFactory.getLogger(DataBlockingQueue.class);\n\n private final Lock lock = new ReentrantLock();\n\n private final Condition notFull = lock.newCondition();\n\n private final Condition notEmpty = lock.newCondition();\n\n public DataBlockingQueue(Object name, SizeInBytes byteLimit, int elementLimit, ToIntFunction getNumBytes) {\n super(name, byteLimit, elementLimit, getNumBytes);\n }\n\n @Override\n public int getNumBytes() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumBytes();\n }\n }\n\n @Override\n public int getNumElements() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumElements();\n }\n }\n\n @Override\n public void clear() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n super.clear();\n notFull.signal();\n }\n }\n\n @Override\n public boolean offer(E element) {", "post_mask_code": "\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n return false;\n }\n }\n\n /**\n * Adds an element to this queue, waiting up to the given timeout.\n *\n * @return true if the element is added successfully;\n * otherwise, the element is not added, return false.\n */\n public boolean offer(E element, TimeDuration timeout) throws InterruptedException {\n Objects.requireNonNull(element, \"element == null\");\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n if (nanos <= 0) {\n return false;\n }\n nanos = notFull.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public E poll() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n }\n return polled;\n }\n }\n\n /**\n * Poll out the head element from this queue, waiting up to the given timeout.\n */\n public E poll(TimeDuration timeout) throws InterruptedException {\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n return polled;\n }\n if (nanos <= 0) {\n return null;\n }\n nanos = notEmpty.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public List pollList(long timeoutMs, CheckedFunctionWithTimeout getResult, TriConsumer timeoutHandler) throws THROWABLE {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final List results = super.pollList(timeoutMs, getResult, timeoutHandler);\n if (!results.isEmpty()) {\n notFull.signal();\n }\n return results;\n }\n }\n}\n"} {"task_id": "Java_1725", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/hortonworks/ratis/ratis-common/src/main/java/org/apache/ratis/util/DataBlockingQueue.java", "mask_start_position": 1877, "mask_end_position": 2095, "canonical_solution": "try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n return false;\n }", "pre_mask_code": "package org.apache.ratis.util;\n\nimport org.apache.ratis.util.function.CheckedFunctionWithTimeout;\nimport org.apache.ratis.util.function.TriConsumer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.ToIntFunction;\n\n/**\n * A queue for data elements\n * such that the queue imposes limits on both number of elements and the data size in bytes.\n *\n * Null element is NOT supported.\n *\n * This class is threadsafe.\n */\npublic class DataBlockingQueue extends DataQueue {\n\n public static final Logger LOG = LoggerFactory.getLogger(DataBlockingQueue.class);\n\n private final Lock lock = new ReentrantLock();\n\n private final Condition notFull = lock.newCondition();\n\n private final Condition notEmpty = lock.newCondition();\n\n public DataBlockingQueue(Object name, SizeInBytes byteLimit, int elementLimit, ToIntFunction getNumBytes) {\n super(name, byteLimit, elementLimit, getNumBytes);\n }\n\n @Override\n public int getNumBytes() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumBytes();\n }\n }\n\n @Override\n public int getNumElements() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumElements();\n }\n }\n\n @Override\n public void clear() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n super.clear();\n notFull.signal();\n }\n }\n\n @Override\n public boolean offer(E element) {\n Objects.requireNonNull(element, \"element == null\");\n ", "post_mask_code": "\n }\n\n /**\n * Adds an element to this queue, waiting up to the given timeout.\n *\n * @return true if the element is added successfully;\n * otherwise, the element is not added, return false.\n */\n public boolean offer(E element, TimeDuration timeout) throws InterruptedException {\n Objects.requireNonNull(element, \"element == null\");\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n if (nanos <= 0) {\n return false;\n }\n nanos = notFull.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public E poll() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n }\n return polled;\n }\n }\n\n /**\n * Poll out the head element from this queue, waiting up to the given timeout.\n */\n public E poll(TimeDuration timeout) throws InterruptedException {\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n return polled;\n }\n if (nanos <= 0) {\n return null;\n }\n nanos = notEmpty.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public List pollList(long timeoutMs, CheckedFunctionWithTimeout getResult, TriConsumer timeoutHandler) throws THROWABLE {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final List results = super.pollList(timeoutMs, getResult, timeoutHandler);\n if (!results.isEmpty()) {\n notFull.signal();\n }\n return results;\n }\n }\n}\n"} {"task_id": "Java_1726", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/hortonworks/ratis/ratis-common/src/main/java/org/apache/ratis/util/DataBlockingQueue.java", "mask_start_position": 2100, "mask_end_position": 2101, "canonical_solution": "}", "pre_mask_code": "package org.apache.ratis.util;\n\nimport org.apache.ratis.util.function.CheckedFunctionWithTimeout;\nimport org.apache.ratis.util.function.TriConsumer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.ToIntFunction;\n\n/**\n * A queue for data elements\n * such that the queue imposes limits on both number of elements and the data size in bytes.\n *\n * Null element is NOT supported.\n *\n * This class is threadsafe.\n */\npublic class DataBlockingQueue extends DataQueue {\n\n public static final Logger LOG = LoggerFactory.getLogger(DataBlockingQueue.class);\n\n private final Lock lock = new ReentrantLock();\n\n private final Condition notFull = lock.newCondition();\n\n private final Condition notEmpty = lock.newCondition();\n\n public DataBlockingQueue(Object name, SizeInBytes byteLimit, int elementLimit, ToIntFunction getNumBytes) {\n super(name, byteLimit, elementLimit, getNumBytes);\n }\n\n @Override\n public int getNumBytes() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumBytes();\n }\n }\n\n @Override\n public int getNumElements() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumElements();\n }\n }\n\n @Override\n public void clear() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n super.clear();\n notFull.signal();\n }\n }\n\n @Override\n public boolean offer(E element) {\n Objects.requireNonNull(element, \"element == null\");\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n return false;\n }\n ", "post_mask_code": "\n\n /**\n * Adds an element to this queue, waiting up to the given timeout.\n *\n * @return true if the element is added successfully;\n * otherwise, the element is not added, return false.\n */\n public boolean offer(E element, TimeDuration timeout) throws InterruptedException {\n Objects.requireNonNull(element, \"element == null\");\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n if (nanos <= 0) {\n return false;\n }\n nanos = notFull.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public E poll() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n }\n return polled;\n }\n }\n\n /**\n * Poll out the head element from this queue, waiting up to the given timeout.\n */\n public E poll(TimeDuration timeout) throws InterruptedException {\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n return polled;\n }\n if (nanos <= 0) {\n return null;\n }\n nanos = notEmpty.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public List pollList(long timeoutMs, CheckedFunctionWithTimeout getResult, TriConsumer timeoutHandler) throws THROWABLE {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final List results = super.pollList(timeoutMs, getResult, timeoutHandler);\n if (!results.isEmpty()) {\n notFull.signal();\n }\n return results;\n }\n }\n}\n"} {"task_id": "Java_1727", "language": "Java", "task_type": "single_line", "source_file": "java/github/hortonworks/ratis/ratis-common/src/main/java/org/apache/ratis/util/DataBlockingQueue.java", "mask_start_position": 2463, "mask_end_position": 2468, "canonical_solution": "ll\");", "pre_mask_code": "package org.apache.ratis.util;\n\nimport org.apache.ratis.util.function.CheckedFunctionWithTimeout;\nimport org.apache.ratis.util.function.TriConsumer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.ToIntFunction;\n\n/**\n * A queue for data elements\n * such that the queue imposes limits on both number of elements and the data size in bytes.\n *\n * Null element is NOT supported.\n *\n * This class is threadsafe.\n */\npublic class DataBlockingQueue extends DataQueue {\n\n public static final Logger LOG = LoggerFactory.getLogger(DataBlockingQueue.class);\n\n private final Lock lock = new ReentrantLock();\n\n private final Condition notFull = lock.newCondition();\n\n private final Condition notEmpty = lock.newCondition();\n\n public DataBlockingQueue(Object name, SizeInBytes byteLimit, int elementLimit, ToIntFunction getNumBytes) {\n super(name, byteLimit, elementLimit, getNumBytes);\n }\n\n @Override\n public int getNumBytes() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumBytes();\n }\n }\n\n @Override\n public int getNumElements() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumElements();\n }\n }\n\n @Override\n public void clear() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n super.clear();\n notFull.signal();\n }\n }\n\n @Override\n public boolean offer(E element) {\n Objects.requireNonNull(element, \"element == null\");\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n return false;\n }\n }\n\n /**\n * Adds an element to this queue, waiting up to the given timeout.\n *\n * @return true if the element is added successfully;\n * otherwise, the element is not added, return false.\n */\n public boolean offer(E element, TimeDuration timeout) throws InterruptedException {\n Objects.requireNonNull(element, \"element == nu", "post_mask_code": "\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n if (nanos <= 0) {\n return false;\n }\n nanos = notFull.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public E poll() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n }\n return polled;\n }\n }\n\n /**\n * Poll out the head element from this queue, waiting up to the given timeout.\n */\n public E poll(TimeDuration timeout) throws InterruptedException {\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n return polled;\n }\n if (nanos <= 0) {\n return null;\n }\n nanos = notEmpty.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public List pollList(long timeoutMs, CheckedFunctionWithTimeout getResult, TriConsumer timeoutHandler) throws THROWABLE {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final List results = super.pollList(timeoutMs, getResult, timeoutHandler);\n if (!results.isEmpty()) {\n notFull.signal();\n }\n return results;\n }\n }\n}\n"} {"task_id": "Java_1728", "language": "Java", "task_type": "if_statement", "source_file": "java/github/hortonworks/ratis/ratis-common/src/main/java/org/apache/ratis/util/DataBlockingQueue.java", "mask_start_position": 4299, "mask_end_position": 4372, "canonical_solution": "if (!results.isEmpty()) {\n notFull.signal();\n }", "pre_mask_code": "package org.apache.ratis.util;\n\nimport org.apache.ratis.util.function.CheckedFunctionWithTimeout;\nimport org.apache.ratis.util.function.TriConsumer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.ToIntFunction;\n\n/**\n * A queue for data elements\n * such that the queue imposes limits on both number of elements and the data size in bytes.\n *\n * Null element is NOT supported.\n *\n * This class is threadsafe.\n */\npublic class DataBlockingQueue extends DataQueue {\n\n public static final Logger LOG = LoggerFactory.getLogger(DataBlockingQueue.class);\n\n private final Lock lock = new ReentrantLock();\n\n private final Condition notFull = lock.newCondition();\n\n private final Condition notEmpty = lock.newCondition();\n\n public DataBlockingQueue(Object name, SizeInBytes byteLimit, int elementLimit, ToIntFunction getNumBytes) {\n super(name, byteLimit, elementLimit, getNumBytes);\n }\n\n @Override\n public int getNumBytes() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumBytes();\n }\n }\n\n @Override\n public int getNumElements() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumElements();\n }\n }\n\n @Override\n public void clear() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n super.clear();\n notFull.signal();\n }\n }\n\n @Override\n public boolean offer(E element) {\n Objects.requireNonNull(element, \"element == null\");\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n return false;\n }\n }\n\n /**\n * Adds an element to this queue, waiting up to the given timeout.\n *\n * @return true if the element is added successfully;\n * otherwise, the element is not added, return false.\n */\n public boolean offer(E element, TimeDuration timeout) throws InterruptedException {\n Objects.requireNonNull(element, \"element == null\");\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n if (nanos <= 0) {\n return false;\n }\n nanos = notFull.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public E poll() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n }\n return polled;\n }\n }\n\n /**\n * Poll out the head element from this queue, waiting up to the given timeout.\n */\n public E poll(TimeDuration timeout) throws InterruptedException {\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n return polled;\n }\n if (nanos <= 0) {\n return null;\n }\n nanos = notEmpty.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public List pollList(long timeoutMs, CheckedFunctionWithTimeout getResult, TriConsumer timeoutHandler) throws THROWABLE {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final List results = super.pollList(timeoutMs, getResult, timeoutHandler);\n ", "post_mask_code": "\n return results;\n }\n }\n}\n"} {"task_id": "Java_1729", "language": "Java", "task_type": "for_statement", "source_file": "java/github/hortonworks/ratis/ratis-common/src/main/java/org/apache/ratis/util/DataBlockingQueue.java", "mask_start_position": 2613, "mask_end_position": 2910, "canonical_solution": "for (; ; ) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n if (nanos <= 0) {\n return false;\n }\n nanos = notFull.awaitNanos(nanos);\n }", "pre_mask_code": "package org.apache.ratis.util;\n\nimport org.apache.ratis.util.function.CheckedFunctionWithTimeout;\nimport org.apache.ratis.util.function.TriConsumer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.ToIntFunction;\n\n/**\n * A queue for data elements\n * such that the queue imposes limits on both number of elements and the data size in bytes.\n *\n * Null element is NOT supported.\n *\n * This class is threadsafe.\n */\npublic class DataBlockingQueue extends DataQueue {\n\n public static final Logger LOG = LoggerFactory.getLogger(DataBlockingQueue.class);\n\n private final Lock lock = new ReentrantLock();\n\n private final Condition notFull = lock.newCondition();\n\n private final Condition notEmpty = lock.newCondition();\n\n public DataBlockingQueue(Object name, SizeInBytes byteLimit, int elementLimit, ToIntFunction getNumBytes) {\n super(name, byteLimit, elementLimit, getNumBytes);\n }\n\n @Override\n public int getNumBytes() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumBytes();\n }\n }\n\n @Override\n public int getNumElements() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n return super.getNumElements();\n }\n }\n\n @Override\n public void clear() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n super.clear();\n notFull.signal();\n }\n }\n\n @Override\n public boolean offer(E element) {\n Objects.requireNonNull(element, \"element == null\");\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n if (super.offer(element)) {\n notEmpty.signal();\n return true;\n }\n return false;\n }\n }\n\n /**\n * Adds an element to this queue, waiting up to the given timeout.\n *\n * @return true if the element is added successfully;\n * otherwise, the element is not added, return false.\n */\n public boolean offer(E element, TimeDuration timeout) throws InterruptedException {\n Objects.requireNonNull(element, \"element == null\");\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n ", "post_mask_code": "\n }\n }\n\n @Override\n public E poll() {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n }\n return polled;\n }\n }\n\n /**\n * Poll out the head element from this queue, waiting up to the given timeout.\n */\n public E poll(TimeDuration timeout) throws InterruptedException {\n long nanos = timeout.toLong(TimeUnit.NANOSECONDS);\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n for (; ; ) {\n final E polled = super.poll();\n if (polled != null) {\n notFull.signal();\n return polled;\n }\n if (nanos <= 0) {\n return null;\n }\n nanos = notEmpty.awaitNanos(nanos);\n }\n }\n }\n\n @Override\n public List pollList(long timeoutMs, CheckedFunctionWithTimeout getResult, TriConsumer timeoutHandler) throws THROWABLE {\n try (AutoCloseableLock auto = AutoCloseableLock.acquire(lock)) {\n final List results = super.pollList(timeoutMs, getResult, timeoutHandler);\n if (!results.isEmpty()) {\n notFull.signal();\n }\n return results;\n }\n }\n}\n"} {"task_id": "Java_1730", "language": "Java", "task_type": "method_signature", "source_file": "java/github/negusoft/holoaccent/HoloAccent/src/com/negusoft/holoaccent/interceptor/ContactBadgeInterceptor.java", "mask_start_position": 643, "mask_end_position": 734, "canonical_solution": "@Override\n public Drawable getDrawable(Resources res, AccentPalette palette, int resId) ", "pre_mask_code": "package com.negusoft.holoaccent.interceptor;\n\nimport android.content.res.Resources;\nimport android.graphics.drawable.Drawable;\nimport com.negusoft.holoaccent.AccentPalette;\nimport com.negusoft.holoaccent.AccentResources;\nimport com.negusoft.holoaccent.R;\nimport com.negusoft.holoaccent.drawable.ContactBadgeDrawable;\n\npublic class ContactBadgeInterceptor implements AccentResources.Interceptor {\n\n private static final int FILL_COLOR_DARK = 0xccaaaaaa;\n\n private static final int LINE_COLOR_DARK = 0xcc090909;\n\n private static final int FILL_COLOR_LIGHT = 0x96333333;\n\n private static final int LINE_COLOR_LIGHT = 0xccffffff;\n\n ", "post_mask_code": "{\n if (resId == R.drawable.ha__contact_badge_normal_reference)\n return new ContactBadgeDrawable(res, 0, 0f, 0, FILL_COLOR_DARK, LINE_COLOR_DARK);\n if (resId == R.drawable.ha__contact_badge_focused_reference) {\n int backColor = palette.getActionBarAccentColor(0x55);\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, backColor, 2f, borderColor, palette.accentColor, LINE_COLOR_DARK);\n }\n if (resId == R.drawable.ha__contact_badge_pressed_reference) {\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, borderColor, 0f, 0, palette.accentColor, LINE_COLOR_DARK);\n }\n if (resId == R.drawable.ha__contact_badge_normal_light_reference)\n return new ContactBadgeDrawable(res, 0, 0f, 0, FILL_COLOR_LIGHT, LINE_COLOR_LIGHT);\n if (resId == R.drawable.ha__contact_badge_focused_light_reference) {\n int backColor = palette.getActionBarAccentColor(0x55);\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, backColor, 2f, borderColor, palette.accentColor, LINE_COLOR_LIGHT);\n }\n if (resId == R.drawable.ha__contact_badge_pressed_light_reference) {\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, borderColor, 0f, 0, palette.accentColor, LINE_COLOR_LIGHT);\n }\n return null;\n }\n}\n"} {"task_id": "Java_1731", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/negusoft/holoaccent/HoloAccent/src/com/negusoft/holoaccent/interceptor/ContactBadgeInterceptor.java", "mask_start_position": 735, "mask_end_position": 1230, "canonical_solution": "\n if (resId == R.drawable.ha__contact_badge_normal_reference)\n return new ContactBadgeDrawable(res, 0, 0f, 0, FILL_COLOR_DARK, LINE_COLOR_DARK);\n if (resId == R.drawable.ha__contact_badge_focused_reference) {\n int backColor = palette.getActionBarAccentColor(0x55);\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, backColor, 2f, borderColor, palette.accentColor, LINE_COLOR_DARK);\n }", "pre_mask_code": "package com.negusoft.holoaccent.interceptor;\n\nimport android.content.res.Resources;\nimport android.graphics.drawable.Drawable;\nimport com.negusoft.holoaccent.AccentPalette;\nimport com.negusoft.holoaccent.AccentResources;\nimport com.negusoft.holoaccent.R;\nimport com.negusoft.holoaccent.drawable.ContactBadgeDrawable;\n\npublic class ContactBadgeInterceptor implements AccentResources.Interceptor {\n\n private static final int FILL_COLOR_DARK = 0xccaaaaaa;\n\n private static final int LINE_COLOR_DARK = 0xcc090909;\n\n private static final int FILL_COLOR_LIGHT = 0x96333333;\n\n private static final int LINE_COLOR_LIGHT = 0xccffffff;\n\n @Override\n public Drawable getDrawable(Resources res, AccentPalette palette, int resId) {", "post_mask_code": "\n if (resId == R.drawable.ha__contact_badge_pressed_reference) {\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, borderColor, 0f, 0, palette.accentColor, LINE_COLOR_DARK);\n }\n if (resId == R.drawable.ha__contact_badge_normal_light_reference)\n return new ContactBadgeDrawable(res, 0, 0f, 0, FILL_COLOR_LIGHT, LINE_COLOR_LIGHT);\n if (resId == R.drawable.ha__contact_badge_focused_light_reference) {\n int backColor = palette.getActionBarAccentColor(0x55);\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, backColor, 2f, borderColor, palette.accentColor, LINE_COLOR_LIGHT);\n }\n if (resId == R.drawable.ha__contact_badge_pressed_light_reference) {\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, borderColor, 0f, 0, palette.accentColor, LINE_COLOR_LIGHT);\n }\n return null;\n }\n}\n"} {"task_id": "Java_1732", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/negusoft/holoaccent/HoloAccent/src/com/negusoft/holoaccent/interceptor/ContactBadgeInterceptor.java", "mask_start_position": 1239, "mask_end_position": 1998, "canonical_solution": "if (resId == R.drawable.ha__contact_badge_pressed_reference) {\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, borderColor, 0f, 0, palette.accentColor, LINE_COLOR_DARK);\n }\n if (resId == R.drawable.ha__contact_badge_normal_light_reference)\n return new ContactBadgeDrawable(res, 0, 0f, 0, FILL_COLOR_LIGHT, LINE_COLOR_LIGHT);\n if (resId == R.drawable.ha__contact_badge_focused_light_reference) {\n int backColor = palette.getActionBarAccentColor(0x55);\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, backColor, 2f, borderColor, palette.accentColor, LINE_COLOR_LIGHT);\n }", "pre_mask_code": "package com.negusoft.holoaccent.interceptor;\n\nimport android.content.res.Resources;\nimport android.graphics.drawable.Drawable;\nimport com.negusoft.holoaccent.AccentPalette;\nimport com.negusoft.holoaccent.AccentResources;\nimport com.negusoft.holoaccent.R;\nimport com.negusoft.holoaccent.drawable.ContactBadgeDrawable;\n\npublic class ContactBadgeInterceptor implements AccentResources.Interceptor {\n\n private static final int FILL_COLOR_DARK = 0xccaaaaaa;\n\n private static final int LINE_COLOR_DARK = 0xcc090909;\n\n private static final int FILL_COLOR_LIGHT = 0x96333333;\n\n private static final int LINE_COLOR_LIGHT = 0xccffffff;\n\n @Override\n public Drawable getDrawable(Resources res, AccentPalette palette, int resId) {\n if (resId == R.drawable.ha__contact_badge_normal_reference)\n return new ContactBadgeDrawable(res, 0, 0f, 0, FILL_COLOR_DARK, LINE_COLOR_DARK);\n if (resId == R.drawable.ha__contact_badge_focused_reference) {\n int backColor = palette.getActionBarAccentColor(0x55);\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, backColor, 2f, borderColor, palette.accentColor, LINE_COLOR_DARK);\n }\n ", "post_mask_code": "\n if (resId == R.drawable.ha__contact_badge_pressed_light_reference) {\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, borderColor, 0f, 0, palette.accentColor, LINE_COLOR_LIGHT);\n }\n return null;\n }\n}\n"} {"task_id": "Java_1733", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/negusoft/holoaccent/HoloAccent/src/com/negusoft/holoaccent/interceptor/ContactBadgeInterceptor.java", "mask_start_position": 2007, "mask_end_position": 2290, "canonical_solution": "if (resId == R.drawable.ha__contact_badge_pressed_light_reference) {\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, borderColor, 0f, 0, palette.accentColor, LINE_COLOR_LIGHT);\n }\n return null;\n }", "pre_mask_code": "package com.negusoft.holoaccent.interceptor;\n\nimport android.content.res.Resources;\nimport android.graphics.drawable.Drawable;\nimport com.negusoft.holoaccent.AccentPalette;\nimport com.negusoft.holoaccent.AccentResources;\nimport com.negusoft.holoaccent.R;\nimport com.negusoft.holoaccent.drawable.ContactBadgeDrawable;\n\npublic class ContactBadgeInterceptor implements AccentResources.Interceptor {\n\n private static final int FILL_COLOR_DARK = 0xccaaaaaa;\n\n private static final int LINE_COLOR_DARK = 0xcc090909;\n\n private static final int FILL_COLOR_LIGHT = 0x96333333;\n\n private static final int LINE_COLOR_LIGHT = 0xccffffff;\n\n @Override\n public Drawable getDrawable(Resources res, AccentPalette palette, int resId) {\n if (resId == R.drawable.ha__contact_badge_normal_reference)\n return new ContactBadgeDrawable(res, 0, 0f, 0, FILL_COLOR_DARK, LINE_COLOR_DARK);\n if (resId == R.drawable.ha__contact_badge_focused_reference) {\n int backColor = palette.getActionBarAccentColor(0x55);\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, backColor, 2f, borderColor, palette.accentColor, LINE_COLOR_DARK);\n }\n if (resId == R.drawable.ha__contact_badge_pressed_reference) {\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, borderColor, 0f, 0, palette.accentColor, LINE_COLOR_DARK);\n }\n if (resId == R.drawable.ha__contact_badge_normal_light_reference)\n return new ContactBadgeDrawable(res, 0, 0f, 0, FILL_COLOR_LIGHT, LINE_COLOR_LIGHT);\n if (resId == R.drawable.ha__contact_badge_focused_light_reference) {\n int backColor = palette.getActionBarAccentColor(0x55);\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, backColor, 2f, borderColor, palette.accentColor, LINE_COLOR_LIGHT);\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1734", "language": "Java", "task_type": "single_line", "source_file": "java/github/negusoft/holoaccent/HoloAccent/src/com/negusoft/holoaccent/interceptor/ContactBadgeInterceptor.java", "mask_start_position": 2275, "mask_end_position": 2284, "canonical_solution": "urn null;", "pre_mask_code": "package com.negusoft.holoaccent.interceptor;\n\nimport android.content.res.Resources;\nimport android.graphics.drawable.Drawable;\nimport com.negusoft.holoaccent.AccentPalette;\nimport com.negusoft.holoaccent.AccentResources;\nimport com.negusoft.holoaccent.R;\nimport com.negusoft.holoaccent.drawable.ContactBadgeDrawable;\n\npublic class ContactBadgeInterceptor implements AccentResources.Interceptor {\n\n private static final int FILL_COLOR_DARK = 0xccaaaaaa;\n\n private static final int LINE_COLOR_DARK = 0xcc090909;\n\n private static final int FILL_COLOR_LIGHT = 0x96333333;\n\n private static final int LINE_COLOR_LIGHT = 0xccffffff;\n\n @Override\n public Drawable getDrawable(Resources res, AccentPalette palette, int resId) {\n if (resId == R.drawable.ha__contact_badge_normal_reference)\n return new ContactBadgeDrawable(res, 0, 0f, 0, FILL_COLOR_DARK, LINE_COLOR_DARK);\n if (resId == R.drawable.ha__contact_badge_focused_reference) {\n int backColor = palette.getActionBarAccentColor(0x55);\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, backColor, 2f, borderColor, palette.accentColor, LINE_COLOR_DARK);\n }\n if (resId == R.drawable.ha__contact_badge_pressed_reference) {\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, borderColor, 0f, 0, palette.accentColor, LINE_COLOR_DARK);\n }\n if (resId == R.drawable.ha__contact_badge_normal_light_reference)\n return new ContactBadgeDrawable(res, 0, 0f, 0, FILL_COLOR_LIGHT, LINE_COLOR_LIGHT);\n if (resId == R.drawable.ha__contact_badge_focused_light_reference) {\n int backColor = palette.getActionBarAccentColor(0x55);\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, backColor, 2f, borderColor, palette.accentColor, LINE_COLOR_LIGHT);\n }\n if (resId == R.drawable.ha__contact_badge_pressed_light_reference) {\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, borderColor, 0f, 0, palette.accentColor, LINE_COLOR_LIGHT);\n }\n ret", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1735", "language": "Java", "task_type": "if_statement", "source_file": "java/github/negusoft/holoaccent/HoloAccent/src/com/negusoft/holoaccent/interceptor/ContactBadgeInterceptor.java", "mask_start_position": 744, "mask_end_position": 897, "canonical_solution": "if (resId == R.drawable.ha__contact_badge_normal_reference)\n return new ContactBadgeDrawable(res, 0, 0f, 0, FILL_COLOR_DARK, LINE_COLOR_DARK);", "pre_mask_code": "package com.negusoft.holoaccent.interceptor;\n\nimport android.content.res.Resources;\nimport android.graphics.drawable.Drawable;\nimport com.negusoft.holoaccent.AccentPalette;\nimport com.negusoft.holoaccent.AccentResources;\nimport com.negusoft.holoaccent.R;\nimport com.negusoft.holoaccent.drawable.ContactBadgeDrawable;\n\npublic class ContactBadgeInterceptor implements AccentResources.Interceptor {\n\n private static final int FILL_COLOR_DARK = 0xccaaaaaa;\n\n private static final int LINE_COLOR_DARK = 0xcc090909;\n\n private static final int FILL_COLOR_LIGHT = 0x96333333;\n\n private static final int LINE_COLOR_LIGHT = 0xccffffff;\n\n @Override\n public Drawable getDrawable(Resources res, AccentPalette palette, int resId) {\n ", "post_mask_code": "\n if (resId == R.drawable.ha__contact_badge_focused_reference) {\n int backColor = palette.getActionBarAccentColor(0x55);\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, backColor, 2f, borderColor, palette.accentColor, LINE_COLOR_DARK);\n }\n if (resId == R.drawable.ha__contact_badge_pressed_reference) {\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, borderColor, 0f, 0, palette.accentColor, LINE_COLOR_DARK);\n }\n if (resId == R.drawable.ha__contact_badge_normal_light_reference)\n return new ContactBadgeDrawable(res, 0, 0f, 0, FILL_COLOR_LIGHT, LINE_COLOR_LIGHT);\n if (resId == R.drawable.ha__contact_badge_focused_light_reference) {\n int backColor = palette.getActionBarAccentColor(0x55);\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, backColor, 2f, borderColor, palette.accentColor, LINE_COLOR_LIGHT);\n }\n if (resId == R.drawable.ha__contact_badge_pressed_light_reference) {\n int borderColor = palette.getActionBarAccentColor(0xAA);\n return new ContactBadgeDrawable(res, borderColor, 0f, 0, palette.accentColor, LINE_COLOR_LIGHT);\n }\n return null;\n }\n}\n"} {"task_id": "Java_1736", "language": "Java", "task_type": "method_signature", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/development/FileEncryptionPreferenceController.java", "mask_start_position": 994, "mask_end_position": 1037, "canonical_solution": "@Override\n public boolean isAvailable() ", "pre_mask_code": "package com.android.settings.development;\n\nimport android.content.Context;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.os.storage.IStorageManager;\nimport android.text.TextUtils;\nimport android.sysprop.CryptoProperties;\nimport androidx.annotation.VisibleForTesting;\nimport androidx.preference.Preference;\nimport com.android.settings.R;\nimport com.android.settings.core.PreferenceControllerMixin;\nimport com.android.settingslib.development.DeveloperOptionsPreferenceController;\n\npublic class FileEncryptionPreferenceController extends DeveloperOptionsPreferenceController implements PreferenceControllerMixin {\n\n private static final String KEY_CONVERT_FBE = \"convert_to_file_encryption\";\n\n private static final String KEY_STORAGE_MANAGER = \"mount\";\n\n private final IStorageManager mStorageManager;\n\n public FileEncryptionPreferenceController(Context context) {\n super(context);\n mStorageManager = getStorageManager();\n }\n\n ", "post_mask_code": "{\n if (mStorageManager == null) {\n return false;\n }\n try {\n return mStorageManager.isConvertibleToFBE();\n } catch (RemoteException e) {\n return false;\n }\n }\n\n @Override\n public String getPreferenceKey() {\n return KEY_CONVERT_FBE;\n }\n\n @Override\n public void updateState(Preference preference) {\n if (CryptoProperties.type().orElse(CryptoProperties.type_values.NONE) != CryptoProperties.type_values.FILE) {\n return;\n }\n mPreference.setEnabled(false);\n mPreference.setSummary(mContext.getResources().getString(R.string.convert_to_file_encryption_done));\n }\n\n private IStorageManager getStorageManager() {\n try {\n return IStorageManager.Stub.asInterface(ServiceManager.getService(KEY_STORAGE_MANAGER));\n } catch (VerifyError e) {\n // Used for tests since Robolectric cannot initialize this class.\n return null;\n }\n }\n}\n"} {"task_id": "Java_1737", "language": "Java", "task_type": "method_body", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/development/FileEncryptionPreferenceController.java", "mask_start_position": 1776, "mask_end_position": 2045, "canonical_solution": "{\n try {\n return IStorageManager.Stub.asInterface(ServiceManager.getService(KEY_STORAGE_MANAGER));\n } catch (VerifyError e) {\n // Used for tests since Robolectric cannot initialize this class.\n return null;\n }\n }", "pre_mask_code": "package com.android.settings.development;\n\nimport android.content.Context;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.os.storage.IStorageManager;\nimport android.text.TextUtils;\nimport android.sysprop.CryptoProperties;\nimport androidx.annotation.VisibleForTesting;\nimport androidx.preference.Preference;\nimport com.android.settings.R;\nimport com.android.settings.core.PreferenceControllerMixin;\nimport com.android.settingslib.development.DeveloperOptionsPreferenceController;\n\npublic class FileEncryptionPreferenceController extends DeveloperOptionsPreferenceController implements PreferenceControllerMixin {\n\n private static final String KEY_CONVERT_FBE = \"convert_to_file_encryption\";\n\n private static final String KEY_STORAGE_MANAGER = \"mount\";\n\n private final IStorageManager mStorageManager;\n\n public FileEncryptionPreferenceController(Context context) {\n super(context);\n mStorageManager = getStorageManager();\n }\n\n @Override\n public boolean isAvailable() {\n if (mStorageManager == null) {\n return false;\n }\n try {\n return mStorageManager.isConvertibleToFBE();\n } catch (RemoteException e) {\n return false;\n }\n }\n\n @Override\n public String getPreferenceKey() {\n return KEY_CONVERT_FBE;\n }\n\n @Override\n public void updateState(Preference preference) {\n if (CryptoProperties.type().orElse(CryptoProperties.type_values.NONE) != CryptoProperties.type_values.FILE) {\n return;\n }\n mPreference.setEnabled(false);\n mPreference.setSummary(mContext.getResources().getString(R.string.convert_to_file_encryption_done));\n }\n\n private IStorageManager getStorageManager() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1738", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/development/FileEncryptionPreferenceController.java", "mask_start_position": 1777, "mask_end_position": 1777, "canonical_solution": "", "pre_mask_code": "package com.android.settings.development;\n\nimport android.content.Context;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.os.storage.IStorageManager;\nimport android.text.TextUtils;\nimport android.sysprop.CryptoProperties;\nimport androidx.annotation.VisibleForTesting;\nimport androidx.preference.Preference;\nimport com.android.settings.R;\nimport com.android.settings.core.PreferenceControllerMixin;\nimport com.android.settingslib.development.DeveloperOptionsPreferenceController;\n\npublic class FileEncryptionPreferenceController extends DeveloperOptionsPreferenceController implements PreferenceControllerMixin {\n\n private static final String KEY_CONVERT_FBE = \"convert_to_file_encryption\";\n\n private static final String KEY_STORAGE_MANAGER = \"mount\";\n\n private final IStorageManager mStorageManager;\n\n public FileEncryptionPreferenceController(Context context) {\n super(context);\n mStorageManager = getStorageManager();\n }\n\n @Override\n public boolean isAvailable() {\n if (mStorageManager == null) {\n return false;\n }\n try {\n return mStorageManager.isConvertibleToFBE();\n } catch (RemoteException e) {\n return false;\n }\n }\n\n @Override\n public String getPreferenceKey() {\n return KEY_CONVERT_FBE;\n }\n\n @Override\n public void updateState(Preference preference) {\n if (CryptoProperties.type().orElse(CryptoProperties.type_values.NONE) != CryptoProperties.type_values.FILE) {\n return;\n }\n mPreference.setEnabled(false);\n mPreference.setSummary(mContext.getResources().getString(R.string.convert_to_file_encryption_done));\n }\n\n private IStorageManager getStorageManager() {", "post_mask_code": "\n try {\n return IStorageManager.Stub.asInterface(ServiceManager.getService(KEY_STORAGE_MANAGER));\n } catch (VerifyError e) {\n // Used for tests since Robolectric cannot initialize this class.\n return null;\n }\n }\n}\n"} {"task_id": "Java_1739", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/development/FileEncryptionPreferenceController.java", "mask_start_position": 1786, "mask_end_position": 2039, "canonical_solution": "try {\n return IStorageManager.Stub.asInterface(ServiceManager.getService(KEY_STORAGE_MANAGER));\n } catch (VerifyError e) {\n // Used for tests since Robolectric cannot initialize this class.\n return null;\n }", "pre_mask_code": "package com.android.settings.development;\n\nimport android.content.Context;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.os.storage.IStorageManager;\nimport android.text.TextUtils;\nimport android.sysprop.CryptoProperties;\nimport androidx.annotation.VisibleForTesting;\nimport androidx.preference.Preference;\nimport com.android.settings.R;\nimport com.android.settings.core.PreferenceControllerMixin;\nimport com.android.settingslib.development.DeveloperOptionsPreferenceController;\n\npublic class FileEncryptionPreferenceController extends DeveloperOptionsPreferenceController implements PreferenceControllerMixin {\n\n private static final String KEY_CONVERT_FBE = \"convert_to_file_encryption\";\n\n private static final String KEY_STORAGE_MANAGER = \"mount\";\n\n private final IStorageManager mStorageManager;\n\n public FileEncryptionPreferenceController(Context context) {\n super(context);\n mStorageManager = getStorageManager();\n }\n\n @Override\n public boolean isAvailable() {\n if (mStorageManager == null) {\n return false;\n }\n try {\n return mStorageManager.isConvertibleToFBE();\n } catch (RemoteException e) {\n return false;\n }\n }\n\n @Override\n public String getPreferenceKey() {\n return KEY_CONVERT_FBE;\n }\n\n @Override\n public void updateState(Preference preference) {\n if (CryptoProperties.type().orElse(CryptoProperties.type_values.NONE) != CryptoProperties.type_values.FILE) {\n return;\n }\n mPreference.setEnabled(false);\n mPreference.setSummary(mContext.getResources().getString(R.string.convert_to_file_encryption_done));\n }\n\n private IStorageManager getStorageManager() {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1740", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/development/FileEncryptionPreferenceController.java", "mask_start_position": 2044, "mask_end_position": 2045, "canonical_solution": "}", "pre_mask_code": "package com.android.settings.development;\n\nimport android.content.Context;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.os.storage.IStorageManager;\nimport android.text.TextUtils;\nimport android.sysprop.CryptoProperties;\nimport androidx.annotation.VisibleForTesting;\nimport androidx.preference.Preference;\nimport com.android.settings.R;\nimport com.android.settings.core.PreferenceControllerMixin;\nimport com.android.settingslib.development.DeveloperOptionsPreferenceController;\n\npublic class FileEncryptionPreferenceController extends DeveloperOptionsPreferenceController implements PreferenceControllerMixin {\n\n private static final String KEY_CONVERT_FBE = \"convert_to_file_encryption\";\n\n private static final String KEY_STORAGE_MANAGER = \"mount\";\n\n private final IStorageManager mStorageManager;\n\n public FileEncryptionPreferenceController(Context context) {\n super(context);\n mStorageManager = getStorageManager();\n }\n\n @Override\n public boolean isAvailable() {\n if (mStorageManager == null) {\n return false;\n }\n try {\n return mStorageManager.isConvertibleToFBE();\n } catch (RemoteException e) {\n return false;\n }\n }\n\n @Override\n public String getPreferenceKey() {\n return KEY_CONVERT_FBE;\n }\n\n @Override\n public void updateState(Preference preference) {\n if (CryptoProperties.type().orElse(CryptoProperties.type_values.NONE) != CryptoProperties.type_values.FILE) {\n return;\n }\n mPreference.setEnabled(false);\n mPreference.setSummary(mContext.getResources().getString(R.string.convert_to_file_encryption_done));\n }\n\n private IStorageManager getStorageManager() {\n try {\n return IStorageManager.Stub.asInterface(ServiceManager.getService(KEY_STORAGE_MANAGER));\n } catch (VerifyError e) {\n // Used for tests since Robolectric cannot initialize this class.\n return null;\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1741", "language": "Java", "task_type": "single_line", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/development/FileEncryptionPreferenceController.java", "mask_start_position": 1327, "mask_end_position": 1350, "canonical_solution": "return KEY_CONVERT_FBE;", "pre_mask_code": "package com.android.settings.development;\n\nimport android.content.Context;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.os.storage.IStorageManager;\nimport android.text.TextUtils;\nimport android.sysprop.CryptoProperties;\nimport androidx.annotation.VisibleForTesting;\nimport androidx.preference.Preference;\nimport com.android.settings.R;\nimport com.android.settings.core.PreferenceControllerMixin;\nimport com.android.settingslib.development.DeveloperOptionsPreferenceController;\n\npublic class FileEncryptionPreferenceController extends DeveloperOptionsPreferenceController implements PreferenceControllerMixin {\n\n private static final String KEY_CONVERT_FBE = \"convert_to_file_encryption\";\n\n private static final String KEY_STORAGE_MANAGER = \"mount\";\n\n private final IStorageManager mStorageManager;\n\n public FileEncryptionPreferenceController(Context context) {\n super(context);\n mStorageManager = getStorageManager();\n }\n\n @Override\n public boolean isAvailable() {\n if (mStorageManager == null) {\n return false;\n }\n try {\n return mStorageManager.isConvertibleToFBE();\n } catch (RemoteException e) {\n return false;\n }\n }\n\n @Override\n public String getPreferenceKey() {\n ", "post_mask_code": "\n }\n\n @Override\n public void updateState(Preference preference) {\n if (CryptoProperties.type().orElse(CryptoProperties.type_values.NONE) != CryptoProperties.type_values.FILE) {\n return;\n }\n mPreference.setEnabled(false);\n mPreference.setSummary(mContext.getResources().getString(R.string.convert_to_file_encryption_done));\n }\n\n private IStorageManager getStorageManager() {\n try {\n return IStorageManager.Stub.asInterface(ServiceManager.getService(KEY_STORAGE_MANAGER));\n } catch (VerifyError e) {\n // Used for tests since Robolectric cannot initialize this class.\n return null;\n }\n }\n}\n"} {"task_id": "Java_1742", "language": "Java", "task_type": "if_statement", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/development/FileEncryptionPreferenceController.java", "mask_start_position": 1433, "mask_end_position": 1572, "canonical_solution": "if (CryptoProperties.type().orElse(CryptoProperties.type_values.NONE) != CryptoProperties.type_values.FILE) {\n return;\n }", "pre_mask_code": "package com.android.settings.development;\n\nimport android.content.Context;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.os.storage.IStorageManager;\nimport android.text.TextUtils;\nimport android.sysprop.CryptoProperties;\nimport androidx.annotation.VisibleForTesting;\nimport androidx.preference.Preference;\nimport com.android.settings.R;\nimport com.android.settings.core.PreferenceControllerMixin;\nimport com.android.settingslib.development.DeveloperOptionsPreferenceController;\n\npublic class FileEncryptionPreferenceController extends DeveloperOptionsPreferenceController implements PreferenceControllerMixin {\n\n private static final String KEY_CONVERT_FBE = \"convert_to_file_encryption\";\n\n private static final String KEY_STORAGE_MANAGER = \"mount\";\n\n private final IStorageManager mStorageManager;\n\n public FileEncryptionPreferenceController(Context context) {\n super(context);\n mStorageManager = getStorageManager();\n }\n\n @Override\n public boolean isAvailable() {\n if (mStorageManager == null) {\n return false;\n }\n try {\n return mStorageManager.isConvertibleToFBE();\n } catch (RemoteException e) {\n return false;\n }\n }\n\n @Override\n public String getPreferenceKey() {\n return KEY_CONVERT_FBE;\n }\n\n @Override\n public void updateState(Preference preference) {\n ", "post_mask_code": "\n mPreference.setEnabled(false);\n mPreference.setSummary(mContext.getResources().getString(R.string.convert_to_file_encryption_done));\n }\n\n private IStorageManager getStorageManager() {\n try {\n return IStorageManager.Stub.asInterface(ServiceManager.getService(KEY_STORAGE_MANAGER));\n } catch (VerifyError e) {\n // Used for tests since Robolectric cannot initialize this class.\n return null;\n }\n }\n}\n"} {"task_id": "Java_1743", "language": "Java", "task_type": "try_statement", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/development/FileEncryptionPreferenceController.java", "mask_start_position": 1122, "mask_end_position": 1258, "canonical_solution": "try {\n return mStorageManager.isConvertibleToFBE();\n } catch (RemoteException e) {\n return false;\n }", "pre_mask_code": "package com.android.settings.development;\n\nimport android.content.Context;\nimport android.os.RemoteException;\nimport android.os.ServiceManager;\nimport android.os.storage.IStorageManager;\nimport android.text.TextUtils;\nimport android.sysprop.CryptoProperties;\nimport androidx.annotation.VisibleForTesting;\nimport androidx.preference.Preference;\nimport com.android.settings.R;\nimport com.android.settings.core.PreferenceControllerMixin;\nimport com.android.settingslib.development.DeveloperOptionsPreferenceController;\n\npublic class FileEncryptionPreferenceController extends DeveloperOptionsPreferenceController implements PreferenceControllerMixin {\n\n private static final String KEY_CONVERT_FBE = \"convert_to_file_encryption\";\n\n private static final String KEY_STORAGE_MANAGER = \"mount\";\n\n private final IStorageManager mStorageManager;\n\n public FileEncryptionPreferenceController(Context context) {\n super(context);\n mStorageManager = getStorageManager();\n }\n\n @Override\n public boolean isAvailable() {\n if (mStorageManager == null) {\n return false;\n }\n ", "post_mask_code": "\n }\n\n @Override\n public String getPreferenceKey() {\n return KEY_CONVERT_FBE;\n }\n\n @Override\n public void updateState(Preference preference) {\n if (CryptoProperties.type().orElse(CryptoProperties.type_values.NONE) != CryptoProperties.type_values.FILE) {\n return;\n }\n mPreference.setEnabled(false);\n mPreference.setSummary(mContext.getResources().getString(R.string.convert_to_file_encryption_done));\n }\n\n private IStorageManager getStorageManager() {\n try {\n return IStorageManager.Stub.asInterface(ServiceManager.getService(KEY_STORAGE_MANAGER));\n } catch (VerifyError e) {\n // Used for tests since Robolectric cannot initialize this class.\n return null;\n }\n }\n}\n"} {"task_id": "Java_1744", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ardovic/Open-Source-Android-Weather-App/app/src/androidTest/java/com/ardovic/weatherappprototype/network/FetchThreadDataTest.java", "mask_start_position": 524, "mask_end_position": 573, "canonical_solution": "@Before\n public void setUp() throws Exception ", "pre_mask_code": "package com.ardovic.weatherappprototype.network;\n\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport org.junit.Before;\nimport org.junit.Test;\nimport java.util.concurrent.Callable;\nimport static org.junit.Assert.*;\nimport static org.mockito.Mockito.calls;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.verify;\n\n/**\n * Created by user on 01.04.2018.\n */\npublic class FetchThreadDataTest {\n\n FetchThreadData fetchThreadData;\n\n public FetchThreadDataTest() {\n }\n\n ", "post_mask_code": "{\n Handler handler = mock(Handler.class);\n fetchThreadData = new FetchThreadData<>(handler);\n fetchThreadData.start();\n fetchThreadData.getLooper();\n }\n\n @Test\n public void queueResponce() throws Exception {\n fetchThreadData.queueResponce(\"f\", \"a\");\n fetchThreadData.queueResponce(\"c\", \"a\");\n fetchThreadData.queueResponce(\"a\", \"a\");\n fetchThreadData.queueResponce(\"d\", \"a\");\n }\n}\n"} {"task_id": "Java_1745", "language": "Java", "task_type": "method_body", "source_file": "java/github/ardovic/Open-Source-Android-Weather-App/app/src/androidTest/java/com/ardovic/weatherappprototype/network/FetchThreadDataTest.java", "mask_start_position": 816, "mask_end_position": 1019, "canonical_solution": "{\n fetchThreadData.queueResponce(\"f\", \"a\");\n fetchThreadData.queueResponce(\"c\", \"a\");\n fetchThreadData.queueResponce(\"a\", \"a\");\n fetchThreadData.queueResponce(\"d\", \"a\");\n }", "pre_mask_code": "package com.ardovic.weatherappprototype.network;\n\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport org.junit.Before;\nimport org.junit.Test;\nimport java.util.concurrent.Callable;\nimport static org.junit.Assert.*;\nimport static org.mockito.Mockito.calls;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.verify;\n\n/**\n * Created by user on 01.04.2018.\n */\npublic class FetchThreadDataTest {\n\n FetchThreadData fetchThreadData;\n\n public FetchThreadDataTest() {\n }\n\n @Before\n public void setUp() throws Exception {\n Handler handler = mock(Handler.class);\n fetchThreadData = new FetchThreadData<>(handler);\n fetchThreadData.start();\n fetchThreadData.getLooper();\n }\n\n @Test\n public void queueResponce() throws Exception ", "post_mask_code": "\n}\n"} {"task_id": "Java_1746", "language": "Java", "task_type": "single_line", "source_file": "java/github/ardovic/Open-Source-Android-Weather-App/app/src/androidTest/java/com/ardovic/weatherappprototype/network/FetchThreadDataTest.java", "mask_start_position": 615, "mask_end_position": 621, "canonical_solution": "lass);", "pre_mask_code": "package com.ardovic.weatherappprototype.network;\n\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport org.junit.Before;\nimport org.junit.Test;\nimport java.util.concurrent.Callable;\nimport static org.junit.Assert.*;\nimport static org.mockito.Mockito.calls;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.verify;\n\n/**\n * Created by user on 01.04.2018.\n */\npublic class FetchThreadDataTest {\n\n FetchThreadData fetchThreadData;\n\n public FetchThreadDataTest() {\n }\n\n @Before\n public void setUp() throws Exception {\n Handler handler = mock(Handler.c", "post_mask_code": "\n fetchThreadData = new FetchThreadData<>(handler);\n fetchThreadData.start();\n fetchThreadData.getLooper();\n }\n\n @Test\n public void queueResponce() throws Exception {\n fetchThreadData.queueResponce(\"f\", \"a\");\n fetchThreadData.queueResponce(\"c\", \"a\");\n fetchThreadData.queueResponce(\"a\", \"a\");\n fetchThreadData.queueResponce(\"d\", \"a\");\n }\n}\n"} {"task_id": "Java_1747", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jclouds/jclouds/apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/options/CreateVolumeOptions.java", "mask_start_position": 4579, "mask_end_position": 4638, "canonical_solution": "public CreateVolumeOptions description(String description) ", "pre_mask_code": "package org.jclouds.openstack.cinder.v1.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport javax.inject.Inject;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateVolumeOptions implements MapBinder {\n\n public static final CreateVolumeOptions NONE = new CreateVolumeOptions();\n\n @Inject\n private BindToJsonPayload jsonBinder;\n\n protected String name;\n\n protected String description;\n\n protected String volumeType;\n\n protected String availabilityZone;\n\n protected String snapshotId;\n\n protected Map metadata = ImmutableMap.of();\n\n @Override\n public R bindToRequest(R request, Map postParams) {\n Map image = Maps.newHashMap();\n image.putAll(postParams);\n if (name != null)\n image.put(\"display_name\", name);\n if (description != null)\n image.put(\"display_description\", description);\n if (volumeType != null)\n image.put(\"volume_type\", volumeType);\n if (availabilityZone != null)\n image.put(\"availability_zone\", availabilityZone);\n if (snapshotId != null)\n image.put(\"snapshot_id\", snapshotId);\n if (!metadata.isEmpty())\n image.put(\"metadata\", metadata);\n return jsonBinder.bindToRequest(request, ImmutableMap.of(\"volume\", image));\n }\n\n @Override\n public R bindToRequest(R request, Object toBind) {\n throw new IllegalStateException(\"CreateVolume is a POST operation\");\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) {\n return true;\n }\n if (!(object instanceof CreateVolumeOptions))\n return false;\n final CreateVolumeOptions other = CreateVolumeOptions.class.cast(object);\n return equal(volumeType, other.volumeType) && equal(availabilityZone, other.availabilityZone) && equal(snapshotId, other.snapshotId) && equal(name, other.name) && equal(description, other.description) && equal(metadata, other.metadata);\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(volumeType, availabilityZone, snapshotId, name, description, metadata);\n }\n\n protected ToStringHelper string() {\n return toStringHelper(\"\").add(\"volumeType\", volumeType).add(\"availabilityZone\", availabilityZone).add(\"snapshotId\", snapshotId).add(\"name\", name).add(\"description\", description).add(\"metadata\", metadata);\n }\n\n @Override\n public String toString() {\n return string().toString();\n }\n\n /**\n * Custom cloud server metadata can also be supplied at launch time. This\n * metadata is stored in the API system where it is retrievable by querying\n * the API for server status. The maximum size of the metadata key and value\n * is each 255 bytes and the maximum number of key-value pairs that can be\n * supplied per volume is 5.\n */\n public CreateVolumeOptions metadata(Map metadata) {\n checkNotNull(metadata, \"metadata\");\n checkArgument(metadata.size() <= 5, \"you cannot have more then 5 metadata values. You specified: \" + metadata.size());\n for (Entry entry : metadata.entrySet()) {\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes\", entry.getKey(), entry.getKey().getBytes().length));\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes\", entry.getKey(), entry.getValue(), entry.getValue().getBytes().length));\n }\n this.metadata = ImmutableMap.copyOf(metadata);\n return this;\n }\n\n /**\n * @param name The name of the Volume\n */\n public CreateVolumeOptions name(String name) {\n this.name = name;\n return this;\n }\n\n /**\n * @param description A description of the Volume\n */\n ", "post_mask_code": "{\n this.description = description;\n return this;\n }\n\n /**\n * @see VolumeTypeApi#list()\n *\n * @param volumeType The type of Volume to create\n */\n public CreateVolumeOptions volumeType(String volumeType) {\n this.volumeType = volumeType;\n return this;\n }\n\n /**\n * @param availabilityZone The optional availability zone in which to create a Volume\n */\n public CreateVolumeOptions availabilityZone(String availabilityZone) {\n this.availabilityZone = availabilityZone;\n return this;\n }\n\n /**\n * @param snapshotId The optional snapshot from which to create a Volume\n */\n public CreateVolumeOptions snapshotId(String snapshotId) {\n this.snapshotId = snapshotId;\n return this;\n }\n\n public String getVolumeType() {\n return volumeType;\n }\n\n public String getAvailabilityZone() {\n return availabilityZone;\n }\n\n public String getSnapshotId() {\n return snapshotId;\n }\n\n public String getName() {\n return name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public Map getMetadata() {\n return metadata;\n }\n\n public static class Builder {\n\n /**\n * @see CreateVolumeOptions#getName()\n */\n public static CreateVolumeOptions name(String name) {\n return new CreateVolumeOptions().name(name);\n }\n\n /**\n * @see CreateVolumeOptions#getDescription()\n */\n public static CreateVolumeOptions description(String description) {\n return new CreateVolumeOptions().description(description);\n }\n\n /**\n * @see CreateVolumeOptions#getVolumeType()\n */\n public static CreateVolumeOptions volumeType(String volumeType) {\n return new CreateVolumeOptions().volumeType(volumeType);\n }\n\n /**\n * @see CreateVolumeOptions#getAvailabilityZone()\n */\n public static CreateVolumeOptions availabilityZone(String availabilityZone) {\n return new CreateVolumeOptions().availabilityZone(availabilityZone);\n }\n\n /**\n * @see CreateVolumeOptions#getSnapshotId()\n */\n public static CreateVolumeOptions snapshotId(String snapshotId) {\n return new CreateVolumeOptions().snapshotId(snapshotId);\n }\n\n /**\n * @see CreateVolumeOptions#getMetadata()\n */\n public static CreateVolumeOptions metadata(Map metadata) {\n return new CreateVolumeOptions().metadata(metadata);\n }\n }\n}\n"} {"task_id": "Java_1748", "language": "Java", "task_type": "method_body", "source_file": "java/github/jclouds/jclouds/apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/options/CreateVolumeOptions.java", "mask_start_position": 5538, "mask_end_position": 5578, "canonical_solution": "{\n return availabilityZone;\n }", "pre_mask_code": "package org.jclouds.openstack.cinder.v1.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport javax.inject.Inject;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateVolumeOptions implements MapBinder {\n\n public static final CreateVolumeOptions NONE = new CreateVolumeOptions();\n\n @Inject\n private BindToJsonPayload jsonBinder;\n\n protected String name;\n\n protected String description;\n\n protected String volumeType;\n\n protected String availabilityZone;\n\n protected String snapshotId;\n\n protected Map metadata = ImmutableMap.of();\n\n @Override\n public R bindToRequest(R request, Map postParams) {\n Map image = Maps.newHashMap();\n image.putAll(postParams);\n if (name != null)\n image.put(\"display_name\", name);\n if (description != null)\n image.put(\"display_description\", description);\n if (volumeType != null)\n image.put(\"volume_type\", volumeType);\n if (availabilityZone != null)\n image.put(\"availability_zone\", availabilityZone);\n if (snapshotId != null)\n image.put(\"snapshot_id\", snapshotId);\n if (!metadata.isEmpty())\n image.put(\"metadata\", metadata);\n return jsonBinder.bindToRequest(request, ImmutableMap.of(\"volume\", image));\n }\n\n @Override\n public R bindToRequest(R request, Object toBind) {\n throw new IllegalStateException(\"CreateVolume is a POST operation\");\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) {\n return true;\n }\n if (!(object instanceof CreateVolumeOptions))\n return false;\n final CreateVolumeOptions other = CreateVolumeOptions.class.cast(object);\n return equal(volumeType, other.volumeType) && equal(availabilityZone, other.availabilityZone) && equal(snapshotId, other.snapshotId) && equal(name, other.name) && equal(description, other.description) && equal(metadata, other.metadata);\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(volumeType, availabilityZone, snapshotId, name, description, metadata);\n }\n\n protected ToStringHelper string() {\n return toStringHelper(\"\").add(\"volumeType\", volumeType).add(\"availabilityZone\", availabilityZone).add(\"snapshotId\", snapshotId).add(\"name\", name).add(\"description\", description).add(\"metadata\", metadata);\n }\n\n @Override\n public String toString() {\n return string().toString();\n }\n\n /**\n * Custom cloud server metadata can also be supplied at launch time. This\n * metadata is stored in the API system where it is retrievable by querying\n * the API for server status. The maximum size of the metadata key and value\n * is each 255 bytes and the maximum number of key-value pairs that can be\n * supplied per volume is 5.\n */\n public CreateVolumeOptions metadata(Map metadata) {\n checkNotNull(metadata, \"metadata\");\n checkArgument(metadata.size() <= 5, \"you cannot have more then 5 metadata values. You specified: \" + metadata.size());\n for (Entry entry : metadata.entrySet()) {\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes\", entry.getKey(), entry.getKey().getBytes().length));\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes\", entry.getKey(), entry.getValue(), entry.getValue().getBytes().length));\n }\n this.metadata = ImmutableMap.copyOf(metadata);\n return this;\n }\n\n /**\n * @param name The name of the Volume\n */\n public CreateVolumeOptions name(String name) {\n this.name = name;\n return this;\n }\n\n /**\n * @param description A description of the Volume\n */\n public CreateVolumeOptions description(String description) {\n this.description = description;\n return this;\n }\n\n /**\n * @see VolumeTypeApi#list()\n *\n * @param volumeType The type of Volume to create\n */\n public CreateVolumeOptions volumeType(String volumeType) {\n this.volumeType = volumeType;\n return this;\n }\n\n /**\n * @param availabilityZone The optional availability zone in which to create a Volume\n */\n public CreateVolumeOptions availabilityZone(String availabilityZone) {\n this.availabilityZone = availabilityZone;\n return this;\n }\n\n /**\n * @param snapshotId The optional snapshot from which to create a Volume\n */\n public CreateVolumeOptions snapshotId(String snapshotId) {\n this.snapshotId = snapshotId;\n return this;\n }\n\n public String getVolumeType() {\n return volumeType;\n }\n\n public String getAvailabilityZone() ", "post_mask_code": "\n\n public String getSnapshotId() {\n return snapshotId;\n }\n\n public String getName() {\n return name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public Map getMetadata() {\n return metadata;\n }\n\n public static class Builder {\n\n /**\n * @see CreateVolumeOptions#getName()\n */\n public static CreateVolumeOptions name(String name) {\n return new CreateVolumeOptions().name(name);\n }\n\n /**\n * @see CreateVolumeOptions#getDescription()\n */\n public static CreateVolumeOptions description(String description) {\n return new CreateVolumeOptions().description(description);\n }\n\n /**\n * @see CreateVolumeOptions#getVolumeType()\n */\n public static CreateVolumeOptions volumeType(String volumeType) {\n return new CreateVolumeOptions().volumeType(volumeType);\n }\n\n /**\n * @see CreateVolumeOptions#getAvailabilityZone()\n */\n public static CreateVolumeOptions availabilityZone(String availabilityZone) {\n return new CreateVolumeOptions().availabilityZone(availabilityZone);\n }\n\n /**\n * @see CreateVolumeOptions#getSnapshotId()\n */\n public static CreateVolumeOptions snapshotId(String snapshotId) {\n return new CreateVolumeOptions().snapshotId(snapshotId);\n }\n\n /**\n * @see CreateVolumeOptions#getMetadata()\n */\n public static CreateVolumeOptions metadata(Map metadata) {\n return new CreateVolumeOptions().metadata(metadata);\n }\n }\n}\n"} {"task_id": "Java_1749", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/jclouds/jclouds/apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/options/CreateVolumeOptions.java", "mask_start_position": 2138, "mask_end_position": 2203, "canonical_solution": "\n if (this == object) {\n return true;\n }", "pre_mask_code": "package org.jclouds.openstack.cinder.v1.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport javax.inject.Inject;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateVolumeOptions implements MapBinder {\n\n public static final CreateVolumeOptions NONE = new CreateVolumeOptions();\n\n @Inject\n private BindToJsonPayload jsonBinder;\n\n protected String name;\n\n protected String description;\n\n protected String volumeType;\n\n protected String availabilityZone;\n\n protected String snapshotId;\n\n protected Map metadata = ImmutableMap.of();\n\n @Override\n public R bindToRequest(R request, Map postParams) {\n Map image = Maps.newHashMap();\n image.putAll(postParams);\n if (name != null)\n image.put(\"display_name\", name);\n if (description != null)\n image.put(\"display_description\", description);\n if (volumeType != null)\n image.put(\"volume_type\", volumeType);\n if (availabilityZone != null)\n image.put(\"availability_zone\", availabilityZone);\n if (snapshotId != null)\n image.put(\"snapshot_id\", snapshotId);\n if (!metadata.isEmpty())\n image.put(\"metadata\", metadata);\n return jsonBinder.bindToRequest(request, ImmutableMap.of(\"volume\", image));\n }\n\n @Override\n public R bindToRequest(R request, Object toBind) {\n throw new IllegalStateException(\"CreateVolume is a POST operation\");\n }\n\n @Override\n public boolean equals(Object object) {", "post_mask_code": "\n if (!(object instanceof CreateVolumeOptions))\n return false;\n final CreateVolumeOptions other = CreateVolumeOptions.class.cast(object);\n return equal(volumeType, other.volumeType) && equal(availabilityZone, other.availabilityZone) && equal(snapshotId, other.snapshotId) && equal(name, other.name) && equal(description, other.description) && equal(metadata, other.metadata);\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(volumeType, availabilityZone, snapshotId, name, description, metadata);\n }\n\n protected ToStringHelper string() {\n return toStringHelper(\"\").add(\"volumeType\", volumeType).add(\"availabilityZone\", availabilityZone).add(\"snapshotId\", snapshotId).add(\"name\", name).add(\"description\", description).add(\"metadata\", metadata);\n }\n\n @Override\n public String toString() {\n return string().toString();\n }\n\n /**\n * Custom cloud server metadata can also be supplied at launch time. This\n * metadata is stored in the API system where it is retrievable by querying\n * the API for server status. The maximum size of the metadata key and value\n * is each 255 bytes and the maximum number of key-value pairs that can be\n * supplied per volume is 5.\n */\n public CreateVolumeOptions metadata(Map metadata) {\n checkNotNull(metadata, \"metadata\");\n checkArgument(metadata.size() <= 5, \"you cannot have more then 5 metadata values. You specified: \" + metadata.size());\n for (Entry entry : metadata.entrySet()) {\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes\", entry.getKey(), entry.getKey().getBytes().length));\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes\", entry.getKey(), entry.getValue(), entry.getValue().getBytes().length));\n }\n this.metadata = ImmutableMap.copyOf(metadata);\n return this;\n }\n\n /**\n * @param name The name of the Volume\n */\n public CreateVolumeOptions name(String name) {\n this.name = name;\n return this;\n }\n\n /**\n * @param description A description of the Volume\n */\n public CreateVolumeOptions description(String description) {\n this.description = description;\n return this;\n }\n\n /**\n * @see VolumeTypeApi#list()\n *\n * @param volumeType The type of Volume to create\n */\n public CreateVolumeOptions volumeType(String volumeType) {\n this.volumeType = volumeType;\n return this;\n }\n\n /**\n * @param availabilityZone The optional availability zone in which to create a Volume\n */\n public CreateVolumeOptions availabilityZone(String availabilityZone) {\n this.availabilityZone = availabilityZone;\n return this;\n }\n\n /**\n * @param snapshotId The optional snapshot from which to create a Volume\n */\n public CreateVolumeOptions snapshotId(String snapshotId) {\n this.snapshotId = snapshotId;\n return this;\n }\n\n public String getVolumeType() {\n return volumeType;\n }\n\n public String getAvailabilityZone() {\n return availabilityZone;\n }\n\n public String getSnapshotId() {\n return snapshotId;\n }\n\n public String getName() {\n return name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public Map getMetadata() {\n return metadata;\n }\n\n public static class Builder {\n\n /**\n * @see CreateVolumeOptions#getName()\n */\n public static CreateVolumeOptions name(String name) {\n return new CreateVolumeOptions().name(name);\n }\n\n /**\n * @see CreateVolumeOptions#getDescription()\n */\n public static CreateVolumeOptions description(String description) {\n return new CreateVolumeOptions().description(description);\n }\n\n /**\n * @see CreateVolumeOptions#getVolumeType()\n */\n public static CreateVolumeOptions volumeType(String volumeType) {\n return new CreateVolumeOptions().volumeType(volumeType);\n }\n\n /**\n * @see CreateVolumeOptions#getAvailabilityZone()\n */\n public static CreateVolumeOptions availabilityZone(String availabilityZone) {\n return new CreateVolumeOptions().availabilityZone(availabilityZone);\n }\n\n /**\n * @see CreateVolumeOptions#getSnapshotId()\n */\n public static CreateVolumeOptions snapshotId(String snapshotId) {\n return new CreateVolumeOptions().snapshotId(snapshotId);\n }\n\n /**\n * @see CreateVolumeOptions#getMetadata()\n */\n public static CreateVolumeOptions metadata(Map metadata) {\n return new CreateVolumeOptions().metadata(metadata);\n }\n }\n}\n"} {"task_id": "Java_1750", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/jclouds/jclouds/apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/options/CreateVolumeOptions.java", "mask_start_position": 2212, "mask_end_position": 2365, "canonical_solution": "if (!(object instanceof CreateVolumeOptions))\n return false;\n final CreateVolumeOptions other = CreateVolumeOptions.class.cast(object);", "pre_mask_code": "package org.jclouds.openstack.cinder.v1.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport javax.inject.Inject;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateVolumeOptions implements MapBinder {\n\n public static final CreateVolumeOptions NONE = new CreateVolumeOptions();\n\n @Inject\n private BindToJsonPayload jsonBinder;\n\n protected String name;\n\n protected String description;\n\n protected String volumeType;\n\n protected String availabilityZone;\n\n protected String snapshotId;\n\n protected Map metadata = ImmutableMap.of();\n\n @Override\n public R bindToRequest(R request, Map postParams) {\n Map image = Maps.newHashMap();\n image.putAll(postParams);\n if (name != null)\n image.put(\"display_name\", name);\n if (description != null)\n image.put(\"display_description\", description);\n if (volumeType != null)\n image.put(\"volume_type\", volumeType);\n if (availabilityZone != null)\n image.put(\"availability_zone\", availabilityZone);\n if (snapshotId != null)\n image.put(\"snapshot_id\", snapshotId);\n if (!metadata.isEmpty())\n image.put(\"metadata\", metadata);\n return jsonBinder.bindToRequest(request, ImmutableMap.of(\"volume\", image));\n }\n\n @Override\n public R bindToRequest(R request, Object toBind) {\n throw new IllegalStateException(\"CreateVolume is a POST operation\");\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) {\n return true;\n }\n ", "post_mask_code": "\n return equal(volumeType, other.volumeType) && equal(availabilityZone, other.availabilityZone) && equal(snapshotId, other.snapshotId) && equal(name, other.name) && equal(description, other.description) && equal(metadata, other.metadata);\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(volumeType, availabilityZone, snapshotId, name, description, metadata);\n }\n\n protected ToStringHelper string() {\n return toStringHelper(\"\").add(\"volumeType\", volumeType).add(\"availabilityZone\", availabilityZone).add(\"snapshotId\", snapshotId).add(\"name\", name).add(\"description\", description).add(\"metadata\", metadata);\n }\n\n @Override\n public String toString() {\n return string().toString();\n }\n\n /**\n * Custom cloud server metadata can also be supplied at launch time. This\n * metadata is stored in the API system where it is retrievable by querying\n * the API for server status. The maximum size of the metadata key and value\n * is each 255 bytes and the maximum number of key-value pairs that can be\n * supplied per volume is 5.\n */\n public CreateVolumeOptions metadata(Map metadata) {\n checkNotNull(metadata, \"metadata\");\n checkArgument(metadata.size() <= 5, \"you cannot have more then 5 metadata values. You specified: \" + metadata.size());\n for (Entry entry : metadata.entrySet()) {\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes\", entry.getKey(), entry.getKey().getBytes().length));\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes\", entry.getKey(), entry.getValue(), entry.getValue().getBytes().length));\n }\n this.metadata = ImmutableMap.copyOf(metadata);\n return this;\n }\n\n /**\n * @param name The name of the Volume\n */\n public CreateVolumeOptions name(String name) {\n this.name = name;\n return this;\n }\n\n /**\n * @param description A description of the Volume\n */\n public CreateVolumeOptions description(String description) {\n this.description = description;\n return this;\n }\n\n /**\n * @see VolumeTypeApi#list()\n *\n * @param volumeType The type of Volume to create\n */\n public CreateVolumeOptions volumeType(String volumeType) {\n this.volumeType = volumeType;\n return this;\n }\n\n /**\n * @param availabilityZone The optional availability zone in which to create a Volume\n */\n public CreateVolumeOptions availabilityZone(String availabilityZone) {\n this.availabilityZone = availabilityZone;\n return this;\n }\n\n /**\n * @param snapshotId The optional snapshot from which to create a Volume\n */\n public CreateVolumeOptions snapshotId(String snapshotId) {\n this.snapshotId = snapshotId;\n return this;\n }\n\n public String getVolumeType() {\n return volumeType;\n }\n\n public String getAvailabilityZone() {\n return availabilityZone;\n }\n\n public String getSnapshotId() {\n return snapshotId;\n }\n\n public String getName() {\n return name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public Map getMetadata() {\n return metadata;\n }\n\n public static class Builder {\n\n /**\n * @see CreateVolumeOptions#getName()\n */\n public static CreateVolumeOptions name(String name) {\n return new CreateVolumeOptions().name(name);\n }\n\n /**\n * @see CreateVolumeOptions#getDescription()\n */\n public static CreateVolumeOptions description(String description) {\n return new CreateVolumeOptions().description(description);\n }\n\n /**\n * @see CreateVolumeOptions#getVolumeType()\n */\n public static CreateVolumeOptions volumeType(String volumeType) {\n return new CreateVolumeOptions().volumeType(volumeType);\n }\n\n /**\n * @see CreateVolumeOptions#getAvailabilityZone()\n */\n public static CreateVolumeOptions availabilityZone(String availabilityZone) {\n return new CreateVolumeOptions().availabilityZone(availabilityZone);\n }\n\n /**\n * @see CreateVolumeOptions#getSnapshotId()\n */\n public static CreateVolumeOptions snapshotId(String snapshotId) {\n return new CreateVolumeOptions().snapshotId(snapshotId);\n }\n\n /**\n * @see CreateVolumeOptions#getMetadata()\n */\n public static CreateVolumeOptions metadata(Map metadata) {\n return new CreateVolumeOptions().metadata(metadata);\n }\n }\n}\n"} {"task_id": "Java_1751", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/jclouds/jclouds/apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/options/CreateVolumeOptions.java", "mask_start_position": 2374, "mask_end_position": 2616, "canonical_solution": "return equal(volumeType, other.volumeType) && equal(availabilityZone, other.availabilityZone) && equal(snapshotId, other.snapshotId) && equal(name, other.name) && equal(description, other.description) && equal(metadata, other.metadata);\n }", "pre_mask_code": "package org.jclouds.openstack.cinder.v1.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport javax.inject.Inject;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateVolumeOptions implements MapBinder {\n\n public static final CreateVolumeOptions NONE = new CreateVolumeOptions();\n\n @Inject\n private BindToJsonPayload jsonBinder;\n\n protected String name;\n\n protected String description;\n\n protected String volumeType;\n\n protected String availabilityZone;\n\n protected String snapshotId;\n\n protected Map metadata = ImmutableMap.of();\n\n @Override\n public R bindToRequest(R request, Map postParams) {\n Map image = Maps.newHashMap();\n image.putAll(postParams);\n if (name != null)\n image.put(\"display_name\", name);\n if (description != null)\n image.put(\"display_description\", description);\n if (volumeType != null)\n image.put(\"volume_type\", volumeType);\n if (availabilityZone != null)\n image.put(\"availability_zone\", availabilityZone);\n if (snapshotId != null)\n image.put(\"snapshot_id\", snapshotId);\n if (!metadata.isEmpty())\n image.put(\"metadata\", metadata);\n return jsonBinder.bindToRequest(request, ImmutableMap.of(\"volume\", image));\n }\n\n @Override\n public R bindToRequest(R request, Object toBind) {\n throw new IllegalStateException(\"CreateVolume is a POST operation\");\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) {\n return true;\n }\n if (!(object instanceof CreateVolumeOptions))\n return false;\n final CreateVolumeOptions other = CreateVolumeOptions.class.cast(object);\n ", "post_mask_code": "\n\n @Override\n public int hashCode() {\n return Objects.hashCode(volumeType, availabilityZone, snapshotId, name, description, metadata);\n }\n\n protected ToStringHelper string() {\n return toStringHelper(\"\").add(\"volumeType\", volumeType).add(\"availabilityZone\", availabilityZone).add(\"snapshotId\", snapshotId).add(\"name\", name).add(\"description\", description).add(\"metadata\", metadata);\n }\n\n @Override\n public String toString() {\n return string().toString();\n }\n\n /**\n * Custom cloud server metadata can also be supplied at launch time. This\n * metadata is stored in the API system where it is retrievable by querying\n * the API for server status. The maximum size of the metadata key and value\n * is each 255 bytes and the maximum number of key-value pairs that can be\n * supplied per volume is 5.\n */\n public CreateVolumeOptions metadata(Map metadata) {\n checkNotNull(metadata, \"metadata\");\n checkArgument(metadata.size() <= 5, \"you cannot have more then 5 metadata values. You specified: \" + metadata.size());\n for (Entry entry : metadata.entrySet()) {\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes\", entry.getKey(), entry.getKey().getBytes().length));\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes\", entry.getKey(), entry.getValue(), entry.getValue().getBytes().length));\n }\n this.metadata = ImmutableMap.copyOf(metadata);\n return this;\n }\n\n /**\n * @param name The name of the Volume\n */\n public CreateVolumeOptions name(String name) {\n this.name = name;\n return this;\n }\n\n /**\n * @param description A description of the Volume\n */\n public CreateVolumeOptions description(String description) {\n this.description = description;\n return this;\n }\n\n /**\n * @see VolumeTypeApi#list()\n *\n * @param volumeType The type of Volume to create\n */\n public CreateVolumeOptions volumeType(String volumeType) {\n this.volumeType = volumeType;\n return this;\n }\n\n /**\n * @param availabilityZone The optional availability zone in which to create a Volume\n */\n public CreateVolumeOptions availabilityZone(String availabilityZone) {\n this.availabilityZone = availabilityZone;\n return this;\n }\n\n /**\n * @param snapshotId The optional snapshot from which to create a Volume\n */\n public CreateVolumeOptions snapshotId(String snapshotId) {\n this.snapshotId = snapshotId;\n return this;\n }\n\n public String getVolumeType() {\n return volumeType;\n }\n\n public String getAvailabilityZone() {\n return availabilityZone;\n }\n\n public String getSnapshotId() {\n return snapshotId;\n }\n\n public String getName() {\n return name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public Map getMetadata() {\n return metadata;\n }\n\n public static class Builder {\n\n /**\n * @see CreateVolumeOptions#getName()\n */\n public static CreateVolumeOptions name(String name) {\n return new CreateVolumeOptions().name(name);\n }\n\n /**\n * @see CreateVolumeOptions#getDescription()\n */\n public static CreateVolumeOptions description(String description) {\n return new CreateVolumeOptions().description(description);\n }\n\n /**\n * @see CreateVolumeOptions#getVolumeType()\n */\n public static CreateVolumeOptions volumeType(String volumeType) {\n return new CreateVolumeOptions().volumeType(volumeType);\n }\n\n /**\n * @see CreateVolumeOptions#getAvailabilityZone()\n */\n public static CreateVolumeOptions availabilityZone(String availabilityZone) {\n return new CreateVolumeOptions().availabilityZone(availabilityZone);\n }\n\n /**\n * @see CreateVolumeOptions#getSnapshotId()\n */\n public static CreateVolumeOptions snapshotId(String snapshotId) {\n return new CreateVolumeOptions().snapshotId(snapshotId);\n }\n\n /**\n * @see CreateVolumeOptions#getMetadata()\n */\n public static CreateVolumeOptions metadata(Map metadata) {\n return new CreateVolumeOptions().metadata(metadata);\n }\n }\n}\n"} {"task_id": "Java_1752", "language": "Java", "task_type": "single_line", "source_file": "java/github/jclouds/jclouds/apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/options/CreateVolumeOptions.java", "mask_start_position": 6075, "mask_end_position": 6082, "canonical_solution": "(name);", "pre_mask_code": "package org.jclouds.openstack.cinder.v1.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport javax.inject.Inject;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateVolumeOptions implements MapBinder {\n\n public static final CreateVolumeOptions NONE = new CreateVolumeOptions();\n\n @Inject\n private BindToJsonPayload jsonBinder;\n\n protected String name;\n\n protected String description;\n\n protected String volumeType;\n\n protected String availabilityZone;\n\n protected String snapshotId;\n\n protected Map metadata = ImmutableMap.of();\n\n @Override\n public R bindToRequest(R request, Map postParams) {\n Map image = Maps.newHashMap();\n image.putAll(postParams);\n if (name != null)\n image.put(\"display_name\", name);\n if (description != null)\n image.put(\"display_description\", description);\n if (volumeType != null)\n image.put(\"volume_type\", volumeType);\n if (availabilityZone != null)\n image.put(\"availability_zone\", availabilityZone);\n if (snapshotId != null)\n image.put(\"snapshot_id\", snapshotId);\n if (!metadata.isEmpty())\n image.put(\"metadata\", metadata);\n return jsonBinder.bindToRequest(request, ImmutableMap.of(\"volume\", image));\n }\n\n @Override\n public R bindToRequest(R request, Object toBind) {\n throw new IllegalStateException(\"CreateVolume is a POST operation\");\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) {\n return true;\n }\n if (!(object instanceof CreateVolumeOptions))\n return false;\n final CreateVolumeOptions other = CreateVolumeOptions.class.cast(object);\n return equal(volumeType, other.volumeType) && equal(availabilityZone, other.availabilityZone) && equal(snapshotId, other.snapshotId) && equal(name, other.name) && equal(description, other.description) && equal(metadata, other.metadata);\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(volumeType, availabilityZone, snapshotId, name, description, metadata);\n }\n\n protected ToStringHelper string() {\n return toStringHelper(\"\").add(\"volumeType\", volumeType).add(\"availabilityZone\", availabilityZone).add(\"snapshotId\", snapshotId).add(\"name\", name).add(\"description\", description).add(\"metadata\", metadata);\n }\n\n @Override\n public String toString() {\n return string().toString();\n }\n\n /**\n * Custom cloud server metadata can also be supplied at launch time. This\n * metadata is stored in the API system where it is retrievable by querying\n * the API for server status. The maximum size of the metadata key and value\n * is each 255 bytes and the maximum number of key-value pairs that can be\n * supplied per volume is 5.\n */\n public CreateVolumeOptions metadata(Map metadata) {\n checkNotNull(metadata, \"metadata\");\n checkArgument(metadata.size() <= 5, \"you cannot have more then 5 metadata values. You specified: \" + metadata.size());\n for (Entry entry : metadata.entrySet()) {\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes\", entry.getKey(), entry.getKey().getBytes().length));\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes\", entry.getKey(), entry.getValue(), entry.getValue().getBytes().length));\n }\n this.metadata = ImmutableMap.copyOf(metadata);\n return this;\n }\n\n /**\n * @param name The name of the Volume\n */\n public CreateVolumeOptions name(String name) {\n this.name = name;\n return this;\n }\n\n /**\n * @param description A description of the Volume\n */\n public CreateVolumeOptions description(String description) {\n this.description = description;\n return this;\n }\n\n /**\n * @see VolumeTypeApi#list()\n *\n * @param volumeType The type of Volume to create\n */\n public CreateVolumeOptions volumeType(String volumeType) {\n this.volumeType = volumeType;\n return this;\n }\n\n /**\n * @param availabilityZone The optional availability zone in which to create a Volume\n */\n public CreateVolumeOptions availabilityZone(String availabilityZone) {\n this.availabilityZone = availabilityZone;\n return this;\n }\n\n /**\n * @param snapshotId The optional snapshot from which to create a Volume\n */\n public CreateVolumeOptions snapshotId(String snapshotId) {\n this.snapshotId = snapshotId;\n return this;\n }\n\n public String getVolumeType() {\n return volumeType;\n }\n\n public String getAvailabilityZone() {\n return availabilityZone;\n }\n\n public String getSnapshotId() {\n return snapshotId;\n }\n\n public String getName() {\n return name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public Map getMetadata() {\n return metadata;\n }\n\n public static class Builder {\n\n /**\n * @see CreateVolumeOptions#getName()\n */\n public static CreateVolumeOptions name(String name) {\n return new CreateVolumeOptions().name", "post_mask_code": "\n }\n\n /**\n * @see CreateVolumeOptions#getDescription()\n */\n public static CreateVolumeOptions description(String description) {\n return new CreateVolumeOptions().description(description);\n }\n\n /**\n * @see CreateVolumeOptions#getVolumeType()\n */\n public static CreateVolumeOptions volumeType(String volumeType) {\n return new CreateVolumeOptions().volumeType(volumeType);\n }\n\n /**\n * @see CreateVolumeOptions#getAvailabilityZone()\n */\n public static CreateVolumeOptions availabilityZone(String availabilityZone) {\n return new CreateVolumeOptions().availabilityZone(availabilityZone);\n }\n\n /**\n * @see CreateVolumeOptions#getSnapshotId()\n */\n public static CreateVolumeOptions snapshotId(String snapshotId) {\n return new CreateVolumeOptions().snapshotId(snapshotId);\n }\n\n /**\n * @see CreateVolumeOptions#getMetadata()\n */\n public static CreateVolumeOptions metadata(Map metadata) {\n return new CreateVolumeOptions().metadata(metadata);\n }\n }\n}\n"} {"task_id": "Java_1753", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/jclouds/jclouds/apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/options/CreateVolumeOptions.java", "mask_start_position": 4404, "mask_end_position": 4503, "canonical_solution": "public CreateVolumeOptions name(String name) {\n this.name = name;\n return this;\n }", "pre_mask_code": "package org.jclouds.openstack.cinder.v1.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport javax.inject.Inject;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateVolumeOptions implements MapBinder {\n\n public static final CreateVolumeOptions NONE = new CreateVolumeOptions();\n\n @Inject\n private BindToJsonPayload jsonBinder;\n\n protected String name;\n\n protected String description;\n\n protected String volumeType;\n\n protected String availabilityZone;\n\n protected String snapshotId;\n\n protected Map metadata = ImmutableMap.of();\n\n @Override\n public R bindToRequest(R request, Map postParams) {\n Map image = Maps.newHashMap();\n image.putAll(postParams);\n if (name != null)\n image.put(\"display_name\", name);\n if (description != null)\n image.put(\"display_description\", description);\n if (volumeType != null)\n image.put(\"volume_type\", volumeType);\n if (availabilityZone != null)\n image.put(\"availability_zone\", availabilityZone);\n if (snapshotId != null)\n image.put(\"snapshot_id\", snapshotId);\n if (!metadata.isEmpty())\n image.put(\"metadata\", metadata);\n return jsonBinder.bindToRequest(request, ImmutableMap.of(\"volume\", image));\n }\n\n @Override\n public R bindToRequest(R request, Object toBind) {\n throw new IllegalStateException(\"CreateVolume is a POST operation\");\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) {\n return true;\n }\n if (!(object instanceof CreateVolumeOptions))\n return false;\n final CreateVolumeOptions other = CreateVolumeOptions.class.cast(object);\n return equal(volumeType, other.volumeType) && equal(availabilityZone, other.availabilityZone) && equal(snapshotId, other.snapshotId) && equal(name, other.name) && equal(description, other.description) && equal(metadata, other.metadata);\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(volumeType, availabilityZone, snapshotId, name, description, metadata);\n }\n\n protected ToStringHelper string() {\n return toStringHelper(\"\").add(\"volumeType\", volumeType).add(\"availabilityZone\", availabilityZone).add(\"snapshotId\", snapshotId).add(\"name\", name).add(\"description\", description).add(\"metadata\", metadata);\n }\n\n @Override\n public String toString() {\n return string().toString();\n }\n\n /**\n * Custom cloud server metadata can also be supplied at launch time. This\n * metadata is stored in the API system where it is retrievable by querying\n * the API for server status. The maximum size of the metadata key and value\n * is each 255 bytes and the maximum number of key-value pairs that can be\n * supplied per volume is 5.\n */\n public CreateVolumeOptions metadata(Map metadata) {\n checkNotNull(metadata, \"metadata\");\n checkArgument(metadata.size() <= 5, \"you cannot have more then 5 metadata values. You specified: \" + metadata.size());\n for (Entry entry : metadata.entrySet()) {\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes\", entry.getKey(), entry.getKey().getBytes().length));\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes\", entry.getKey(), entry.getValue(), entry.getValue().getBytes().length));\n }\n this.metadata = ImmutableMap.copyOf(metadata);\n return this;\n }\n\n /**\n * @param name The name of the Volume\n */\n ", "post_mask_code": "\n\n /**\n * @param description A description of the Volume\n */\n public CreateVolumeOptions description(String description) {\n this.description = description;\n return this;\n }\n\n /**\n * @see VolumeTypeApi#list()\n *\n * @param volumeType The type of Volume to create\n */\n public CreateVolumeOptions volumeType(String volumeType) {\n this.volumeType = volumeType;\n return this;\n }\n\n /**\n * @param availabilityZone The optional availability zone in which to create a Volume\n */\n public CreateVolumeOptions availabilityZone(String availabilityZone) {\n this.availabilityZone = availabilityZone;\n return this;\n }\n\n /**\n * @param snapshotId The optional snapshot from which to create a Volume\n */\n public CreateVolumeOptions snapshotId(String snapshotId) {\n this.snapshotId = snapshotId;\n return this;\n }\n\n public String getVolumeType() {\n return volumeType;\n }\n\n public String getAvailabilityZone() {\n return availabilityZone;\n }\n\n public String getSnapshotId() {\n return snapshotId;\n }\n\n public String getName() {\n return name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public Map getMetadata() {\n return metadata;\n }\n\n public static class Builder {\n\n /**\n * @see CreateVolumeOptions#getName()\n */\n public static CreateVolumeOptions name(String name) {\n return new CreateVolumeOptions().name(name);\n }\n\n /**\n * @see CreateVolumeOptions#getDescription()\n */\n public static CreateVolumeOptions description(String description) {\n return new CreateVolumeOptions().description(description);\n }\n\n /**\n * @see CreateVolumeOptions#getVolumeType()\n */\n public static CreateVolumeOptions volumeType(String volumeType) {\n return new CreateVolumeOptions().volumeType(volumeType);\n }\n\n /**\n * @see CreateVolumeOptions#getAvailabilityZone()\n */\n public static CreateVolumeOptions availabilityZone(String availabilityZone) {\n return new CreateVolumeOptions().availabilityZone(availabilityZone);\n }\n\n /**\n * @see CreateVolumeOptions#getSnapshotId()\n */\n public static CreateVolumeOptions snapshotId(String snapshotId) {\n return new CreateVolumeOptions().snapshotId(snapshotId);\n }\n\n /**\n * @see CreateVolumeOptions#getMetadata()\n */\n public static CreateVolumeOptions metadata(Map metadata) {\n return new CreateVolumeOptions().metadata(metadata);\n }\n }\n}\n"} {"task_id": "Java_1754", "language": "Java", "task_type": "if_statement", "source_file": "java/github/jclouds/jclouds/apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/options/CreateVolumeOptions.java", "mask_start_position": 1388, "mask_end_position": 1471, "canonical_solution": "if (description != null)\n image.put(\"display_description\", description);", "pre_mask_code": "package org.jclouds.openstack.cinder.v1.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport javax.inject.Inject;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateVolumeOptions implements MapBinder {\n\n public static final CreateVolumeOptions NONE = new CreateVolumeOptions();\n\n @Inject\n private BindToJsonPayload jsonBinder;\n\n protected String name;\n\n protected String description;\n\n protected String volumeType;\n\n protected String availabilityZone;\n\n protected String snapshotId;\n\n protected Map metadata = ImmutableMap.of();\n\n @Override\n public R bindToRequest(R request, Map postParams) {\n Map image = Maps.newHashMap();\n image.putAll(postParams);\n if (name != null)\n image.put(\"display_name\", name);\n ", "post_mask_code": "\n if (volumeType != null)\n image.put(\"volume_type\", volumeType);\n if (availabilityZone != null)\n image.put(\"availability_zone\", availabilityZone);\n if (snapshotId != null)\n image.put(\"snapshot_id\", snapshotId);\n if (!metadata.isEmpty())\n image.put(\"metadata\", metadata);\n return jsonBinder.bindToRequest(request, ImmutableMap.of(\"volume\", image));\n }\n\n @Override\n public R bindToRequest(R request, Object toBind) {\n throw new IllegalStateException(\"CreateVolume is a POST operation\");\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) {\n return true;\n }\n if (!(object instanceof CreateVolumeOptions))\n return false;\n final CreateVolumeOptions other = CreateVolumeOptions.class.cast(object);\n return equal(volumeType, other.volumeType) && equal(availabilityZone, other.availabilityZone) && equal(snapshotId, other.snapshotId) && equal(name, other.name) && equal(description, other.description) && equal(metadata, other.metadata);\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(volumeType, availabilityZone, snapshotId, name, description, metadata);\n }\n\n protected ToStringHelper string() {\n return toStringHelper(\"\").add(\"volumeType\", volumeType).add(\"availabilityZone\", availabilityZone).add(\"snapshotId\", snapshotId).add(\"name\", name).add(\"description\", description).add(\"metadata\", metadata);\n }\n\n @Override\n public String toString() {\n return string().toString();\n }\n\n /**\n * Custom cloud server metadata can also be supplied at launch time. This\n * metadata is stored in the API system where it is retrievable by querying\n * the API for server status. The maximum size of the metadata key and value\n * is each 255 bytes and the maximum number of key-value pairs that can be\n * supplied per volume is 5.\n */\n public CreateVolumeOptions metadata(Map metadata) {\n checkNotNull(metadata, \"metadata\");\n checkArgument(metadata.size() <= 5, \"you cannot have more then 5 metadata values. You specified: \" + metadata.size());\n for (Entry entry : metadata.entrySet()) {\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata key is 255 bytes. Key specified %s is %d bytes\", entry.getKey(), entry.getKey().getBytes().length));\n checkArgument(entry.getKey().getBytes().length < 255, String.format(\"maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes\", entry.getKey(), entry.getValue(), entry.getValue().getBytes().length));\n }\n this.metadata = ImmutableMap.copyOf(metadata);\n return this;\n }\n\n /**\n * @param name The name of the Volume\n */\n public CreateVolumeOptions name(String name) {\n this.name = name;\n return this;\n }\n\n /**\n * @param description A description of the Volume\n */\n public CreateVolumeOptions description(String description) {\n this.description = description;\n return this;\n }\n\n /**\n * @see VolumeTypeApi#list()\n *\n * @param volumeType The type of Volume to create\n */\n public CreateVolumeOptions volumeType(String volumeType) {\n this.volumeType = volumeType;\n return this;\n }\n\n /**\n * @param availabilityZone The optional availability zone in which to create a Volume\n */\n public CreateVolumeOptions availabilityZone(String availabilityZone) {\n this.availabilityZone = availabilityZone;\n return this;\n }\n\n /**\n * @param snapshotId The optional snapshot from which to create a Volume\n */\n public CreateVolumeOptions snapshotId(String snapshotId) {\n this.snapshotId = snapshotId;\n return this;\n }\n\n public String getVolumeType() {\n return volumeType;\n }\n\n public String getAvailabilityZone() {\n return availabilityZone;\n }\n\n public String getSnapshotId() {\n return snapshotId;\n }\n\n public String getName() {\n return name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public Map getMetadata() {\n return metadata;\n }\n\n public static class Builder {\n\n /**\n * @see CreateVolumeOptions#getName()\n */\n public static CreateVolumeOptions name(String name) {\n return new CreateVolumeOptions().name(name);\n }\n\n /**\n * @see CreateVolumeOptions#getDescription()\n */\n public static CreateVolumeOptions description(String description) {\n return new CreateVolumeOptions().description(description);\n }\n\n /**\n * @see CreateVolumeOptions#getVolumeType()\n */\n public static CreateVolumeOptions volumeType(String volumeType) {\n return new CreateVolumeOptions().volumeType(volumeType);\n }\n\n /**\n * @see CreateVolumeOptions#getAvailabilityZone()\n */\n public static CreateVolumeOptions availabilityZone(String availabilityZone) {\n return new CreateVolumeOptions().availabilityZone(availabilityZone);\n }\n\n /**\n * @see CreateVolumeOptions#getSnapshotId()\n */\n public static CreateVolumeOptions snapshotId(String snapshotId) {\n return new CreateVolumeOptions().snapshotId(snapshotId);\n }\n\n /**\n * @see CreateVolumeOptions#getMetadata()\n */\n public static CreateVolumeOptions metadata(Map metadata) {\n return new CreateVolumeOptions().metadata(metadata);\n }\n }\n}\n"} {"task_id": "Java_1755", "language": "Java", "task_type": "method_signature", "source_file": "java/github/netty/netty/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java", "mask_start_position": 5956, "mask_end_position": 6019, "canonical_solution": "@Override\n protected void _setLongLE(int index, long value) ", "pre_mask_code": "package io.netty.buffer;\n\nimport io.netty.util.internal.ObjectPool;\nimport io.netty.util.internal.ObjectPool.Handle;\nimport io.netty.util.internal.ObjectPool.ObjectCreator;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.nio.ByteBuffer;\n\nfinal class PooledDirectByteBuf extends PooledByteBuf {\n\n private static final ObjectPool RECYCLER = ObjectPool.newPool(new ObjectCreator() {\n\n @Override\n public PooledDirectByteBuf newObject(Handle handle) {\n return new PooledDirectByteBuf(handle, 0);\n }\n });\n\n static PooledDirectByteBuf newInstance(int maxCapacity) {\n PooledDirectByteBuf buf = RECYCLER.get();\n buf.reuse(maxCapacity);\n return buf;\n }\n\n private PooledDirectByteBuf(Handle recyclerHandle, int maxCapacity) {\n super(recyclerHandle, maxCapacity);\n }\n\n @Override\n protected ByteBuffer newInternalNioBuffer(ByteBuffer memory) {\n return memory.duplicate();\n }\n\n @Override\n public boolean isDirect() {\n return true;\n }\n\n @Override\n protected byte _getByte(int index) {\n return memory.get(idx(index));\n }\n\n @Override\n protected short _getShort(int index) {\n return memory.getShort(idx(index));\n }\n\n @Override\n protected short _getShortLE(int index) {\n return ByteBufUtil.swapShort(_getShort(index));\n }\n\n @Override\n protected int _getUnsignedMedium(int index) {\n index = idx(index);\n return (memory.get(index) & 0xff) << 16 | (memory.get(index + 1) & 0xff) << 8 | memory.get(index + 2) & 0xff;\n }\n\n @Override\n protected int _getUnsignedMediumLE(int index) {\n index = idx(index);\n return memory.get(index) & 0xff | (memory.get(index + 1) & 0xff) << 8 | (memory.get(index + 2) & 0xff) << 16;\n }\n\n @Override\n protected int _getInt(int index) {\n return memory.getInt(idx(index));\n }\n\n @Override\n protected int _getIntLE(int index) {\n return ByteBufUtil.swapInt(_getInt(index));\n }\n\n @Override\n protected long _getLong(int index) {\n return memory.getLong(idx(index));\n }\n\n @Override\n protected long _getLongLE(int index) {\n return ByteBufUtil.swapLong(_getLong(index));\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.capacity());\n if (dst.hasArray()) {\n getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length);\n } else if (dst.nioBufferCount() > 0) {\n for (ByteBuffer bb : dst.nioBuffers(dstIndex, length)) {\n int bbLen = bb.remaining();\n getBytes(index, bb);\n index += bbLen;\n }\n } else {\n dst.setBytes(dstIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.length);\n _internalNioBuffer(index, length, true).get(dst, dstIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf readBytes(byte[] dst, int dstIndex, int length) {\n checkDstIndex(length, dstIndex, dst.length);\n _internalNioBuffer(readerIndex, length, false).get(dst, dstIndex, length);\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuffer dst) {\n dst.put(duplicateInternalNioBuffer(index, dst.remaining()));\n return this;\n }\n\n @Override\n public ByteBuf readBytes(ByteBuffer dst) {\n int length = dst.remaining();\n checkReadableBytes(length);\n dst.put(_internalNioBuffer(readerIndex, length, false));\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException {\n getBytes(index, out, length, false);\n return this;\n }\n\n private void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException {\n checkIndex(index, length);\n if (length == 0) {\n return;\n }\n ByteBufUtil.readBytes(alloc(), internal ? internalNioBuffer() : memory.duplicate(), idx(index), length, out);\n }\n\n @Override\n public ByteBuf readBytes(OutputStream out, int length) throws IOException {\n checkReadableBytes(length);\n getBytes(readerIndex, out, length, true);\n readerIndex += length;\n return this;\n }\n\n @Override\n protected void _setByte(int index, int value) {\n memory.put(idx(index), (byte) value);\n }\n\n @Override\n protected void _setShort(int index, int value) {\n memory.putShort(idx(index), (short) value);\n }\n\n @Override\n protected void _setShortLE(int index, int value) {\n _setShort(index, ByteBufUtil.swapShort((short) value));\n }\n\n @Override\n protected void _setMedium(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) (value >>> 16));\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) value);\n }\n\n @Override\n protected void _setMediumLE(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) value);\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) (value >>> 16));\n }\n\n @Override\n protected void _setInt(int index, int value) {\n memory.putInt(idx(index), value);\n }\n\n @Override\n protected void _setIntLE(int index, int value) {\n _setInt(index, ByteBufUtil.swapInt(value));\n }\n\n @Override\n protected void _setLong(int index, long value) {\n memory.putLong(idx(index), value);\n }\n\n ", "post_mask_code": "{\n _setLong(index, ByteBufUtil.swapLong(value));\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.capacity());\n if (src.hasArray()) {\n setBytes(index, src.array(), src.arrayOffset() + srcIndex, length);\n } else if (src.nioBufferCount() > 0) {\n for (ByteBuffer bb : src.nioBuffers(srcIndex, length)) {\n int bbLen = bb.remaining();\n setBytes(index, bb);\n index += bbLen;\n }\n } else {\n src.getBytes(srcIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.length);\n _internalNioBuffer(index, length, false).put(src, srcIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuffer src) {\n int length = src.remaining();\n checkIndex(index, length);\n ByteBuffer tmpBuf = internalNioBuffer();\n if (src == tmpBuf) {\n src = src.duplicate();\n }\n index = idx(index);\n tmpBuf.limit(index + length).position(index);\n tmpBuf.put(src);\n return this;\n }\n\n @Override\n public int setBytes(int index, InputStream in, int length) throws IOException {\n checkIndex(index, length);\n byte[] tmp = ByteBufUtil.threadLocalTempArray(length);\n int readBytes = in.read(tmp, 0, length);\n if (readBytes <= 0) {\n return readBytes;\n }\n ByteBuffer tmpBuf = internalNioBuffer();\n tmpBuf.position(idx(index));\n tmpBuf.put(tmp, 0, readBytes);\n return readBytes;\n }\n\n @Override\n public ByteBuf copy(int index, int length) {\n checkIndex(index, length);\n ByteBuf copy = alloc().directBuffer(length, maxCapacity());\n return copy.writeBytes(this, index, length);\n }\n\n @Override\n public boolean hasArray() {\n return false;\n }\n\n @Override\n public byte[] array() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public int arrayOffset() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public boolean hasMemoryAddress() {\n return false;\n }\n\n @Override\n public long memoryAddress() {\n throw new UnsupportedOperationException();\n }\n}\n"} {"task_id": "Java_1756", "language": "Java", "task_type": "method_body", "source_file": "java/github/netty/netty/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java", "mask_start_position": 1332, "mask_end_position": 1383, "canonical_solution": "{\n return memory.getShort(idx(index));\n }", "pre_mask_code": "package io.netty.buffer;\n\nimport io.netty.util.internal.ObjectPool;\nimport io.netty.util.internal.ObjectPool.Handle;\nimport io.netty.util.internal.ObjectPool.ObjectCreator;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.nio.ByteBuffer;\n\nfinal class PooledDirectByteBuf extends PooledByteBuf {\n\n private static final ObjectPool RECYCLER = ObjectPool.newPool(new ObjectCreator() {\n\n @Override\n public PooledDirectByteBuf newObject(Handle handle) {\n return new PooledDirectByteBuf(handle, 0);\n }\n });\n\n static PooledDirectByteBuf newInstance(int maxCapacity) {\n PooledDirectByteBuf buf = RECYCLER.get();\n buf.reuse(maxCapacity);\n return buf;\n }\n\n private PooledDirectByteBuf(Handle recyclerHandle, int maxCapacity) {\n super(recyclerHandle, maxCapacity);\n }\n\n @Override\n protected ByteBuffer newInternalNioBuffer(ByteBuffer memory) {\n return memory.duplicate();\n }\n\n @Override\n public boolean isDirect() {\n return true;\n }\n\n @Override\n protected byte _getByte(int index) {\n return memory.get(idx(index));\n }\n\n @Override\n protected short _getShort(int index) ", "post_mask_code": "\n\n @Override\n protected short _getShortLE(int index) {\n return ByteBufUtil.swapShort(_getShort(index));\n }\n\n @Override\n protected int _getUnsignedMedium(int index) {\n index = idx(index);\n return (memory.get(index) & 0xff) << 16 | (memory.get(index + 1) & 0xff) << 8 | memory.get(index + 2) & 0xff;\n }\n\n @Override\n protected int _getUnsignedMediumLE(int index) {\n index = idx(index);\n return memory.get(index) & 0xff | (memory.get(index + 1) & 0xff) << 8 | (memory.get(index + 2) & 0xff) << 16;\n }\n\n @Override\n protected int _getInt(int index) {\n return memory.getInt(idx(index));\n }\n\n @Override\n protected int _getIntLE(int index) {\n return ByteBufUtil.swapInt(_getInt(index));\n }\n\n @Override\n protected long _getLong(int index) {\n return memory.getLong(idx(index));\n }\n\n @Override\n protected long _getLongLE(int index) {\n return ByteBufUtil.swapLong(_getLong(index));\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.capacity());\n if (dst.hasArray()) {\n getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length);\n } else if (dst.nioBufferCount() > 0) {\n for (ByteBuffer bb : dst.nioBuffers(dstIndex, length)) {\n int bbLen = bb.remaining();\n getBytes(index, bb);\n index += bbLen;\n }\n } else {\n dst.setBytes(dstIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.length);\n _internalNioBuffer(index, length, true).get(dst, dstIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf readBytes(byte[] dst, int dstIndex, int length) {\n checkDstIndex(length, dstIndex, dst.length);\n _internalNioBuffer(readerIndex, length, false).get(dst, dstIndex, length);\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuffer dst) {\n dst.put(duplicateInternalNioBuffer(index, dst.remaining()));\n return this;\n }\n\n @Override\n public ByteBuf readBytes(ByteBuffer dst) {\n int length = dst.remaining();\n checkReadableBytes(length);\n dst.put(_internalNioBuffer(readerIndex, length, false));\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException {\n getBytes(index, out, length, false);\n return this;\n }\n\n private void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException {\n checkIndex(index, length);\n if (length == 0) {\n return;\n }\n ByteBufUtil.readBytes(alloc(), internal ? internalNioBuffer() : memory.duplicate(), idx(index), length, out);\n }\n\n @Override\n public ByteBuf readBytes(OutputStream out, int length) throws IOException {\n checkReadableBytes(length);\n getBytes(readerIndex, out, length, true);\n readerIndex += length;\n return this;\n }\n\n @Override\n protected void _setByte(int index, int value) {\n memory.put(idx(index), (byte) value);\n }\n\n @Override\n protected void _setShort(int index, int value) {\n memory.putShort(idx(index), (short) value);\n }\n\n @Override\n protected void _setShortLE(int index, int value) {\n _setShort(index, ByteBufUtil.swapShort((short) value));\n }\n\n @Override\n protected void _setMedium(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) (value >>> 16));\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) value);\n }\n\n @Override\n protected void _setMediumLE(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) value);\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) (value >>> 16));\n }\n\n @Override\n protected void _setInt(int index, int value) {\n memory.putInt(idx(index), value);\n }\n\n @Override\n protected void _setIntLE(int index, int value) {\n _setInt(index, ByteBufUtil.swapInt(value));\n }\n\n @Override\n protected void _setLong(int index, long value) {\n memory.putLong(idx(index), value);\n }\n\n @Override\n protected void _setLongLE(int index, long value) {\n _setLong(index, ByteBufUtil.swapLong(value));\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.capacity());\n if (src.hasArray()) {\n setBytes(index, src.array(), src.arrayOffset() + srcIndex, length);\n } else if (src.nioBufferCount() > 0) {\n for (ByteBuffer bb : src.nioBuffers(srcIndex, length)) {\n int bbLen = bb.remaining();\n setBytes(index, bb);\n index += bbLen;\n }\n } else {\n src.getBytes(srcIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.length);\n _internalNioBuffer(index, length, false).put(src, srcIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuffer src) {\n int length = src.remaining();\n checkIndex(index, length);\n ByteBuffer tmpBuf = internalNioBuffer();\n if (src == tmpBuf) {\n src = src.duplicate();\n }\n index = idx(index);\n tmpBuf.limit(index + length).position(index);\n tmpBuf.put(src);\n return this;\n }\n\n @Override\n public int setBytes(int index, InputStream in, int length) throws IOException {\n checkIndex(index, length);\n byte[] tmp = ByteBufUtil.threadLocalTempArray(length);\n int readBytes = in.read(tmp, 0, length);\n if (readBytes <= 0) {\n return readBytes;\n }\n ByteBuffer tmpBuf = internalNioBuffer();\n tmpBuf.position(idx(index));\n tmpBuf.put(tmp, 0, readBytes);\n return readBytes;\n }\n\n @Override\n public ByteBuf copy(int index, int length) {\n checkIndex(index, length);\n ByteBuf copy = alloc().directBuffer(length, maxCapacity());\n return copy.writeBytes(this, index, length);\n }\n\n @Override\n public boolean hasArray() {\n return false;\n }\n\n @Override\n public byte[] array() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public int arrayOffset() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public boolean hasMemoryAddress() {\n return false;\n }\n\n @Override\n public long memoryAddress() {\n throw new UnsupportedOperationException();\n }\n}\n"} {"task_id": "Java_1757", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/netty/netty/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java", "mask_start_position": 7462, "mask_end_position": 7609, "canonical_solution": "\n checkIndex(index, length);\n byte[] tmp = ByteBufUtil.threadLocalTempArray(length);\n int readBytes = in.read(tmp, 0, length);", "pre_mask_code": "package io.netty.buffer;\n\nimport io.netty.util.internal.ObjectPool;\nimport io.netty.util.internal.ObjectPool.Handle;\nimport io.netty.util.internal.ObjectPool.ObjectCreator;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.nio.ByteBuffer;\n\nfinal class PooledDirectByteBuf extends PooledByteBuf {\n\n private static final ObjectPool RECYCLER = ObjectPool.newPool(new ObjectCreator() {\n\n @Override\n public PooledDirectByteBuf newObject(Handle handle) {\n return new PooledDirectByteBuf(handle, 0);\n }\n });\n\n static PooledDirectByteBuf newInstance(int maxCapacity) {\n PooledDirectByteBuf buf = RECYCLER.get();\n buf.reuse(maxCapacity);\n return buf;\n }\n\n private PooledDirectByteBuf(Handle recyclerHandle, int maxCapacity) {\n super(recyclerHandle, maxCapacity);\n }\n\n @Override\n protected ByteBuffer newInternalNioBuffer(ByteBuffer memory) {\n return memory.duplicate();\n }\n\n @Override\n public boolean isDirect() {\n return true;\n }\n\n @Override\n protected byte _getByte(int index) {\n return memory.get(idx(index));\n }\n\n @Override\n protected short _getShort(int index) {\n return memory.getShort(idx(index));\n }\n\n @Override\n protected short _getShortLE(int index) {\n return ByteBufUtil.swapShort(_getShort(index));\n }\n\n @Override\n protected int _getUnsignedMedium(int index) {\n index = idx(index);\n return (memory.get(index) & 0xff) << 16 | (memory.get(index + 1) & 0xff) << 8 | memory.get(index + 2) & 0xff;\n }\n\n @Override\n protected int _getUnsignedMediumLE(int index) {\n index = idx(index);\n return memory.get(index) & 0xff | (memory.get(index + 1) & 0xff) << 8 | (memory.get(index + 2) & 0xff) << 16;\n }\n\n @Override\n protected int _getInt(int index) {\n return memory.getInt(idx(index));\n }\n\n @Override\n protected int _getIntLE(int index) {\n return ByteBufUtil.swapInt(_getInt(index));\n }\n\n @Override\n protected long _getLong(int index) {\n return memory.getLong(idx(index));\n }\n\n @Override\n protected long _getLongLE(int index) {\n return ByteBufUtil.swapLong(_getLong(index));\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.capacity());\n if (dst.hasArray()) {\n getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length);\n } else if (dst.nioBufferCount() > 0) {\n for (ByteBuffer bb : dst.nioBuffers(dstIndex, length)) {\n int bbLen = bb.remaining();\n getBytes(index, bb);\n index += bbLen;\n }\n } else {\n dst.setBytes(dstIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.length);\n _internalNioBuffer(index, length, true).get(dst, dstIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf readBytes(byte[] dst, int dstIndex, int length) {\n checkDstIndex(length, dstIndex, dst.length);\n _internalNioBuffer(readerIndex, length, false).get(dst, dstIndex, length);\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuffer dst) {\n dst.put(duplicateInternalNioBuffer(index, dst.remaining()));\n return this;\n }\n\n @Override\n public ByteBuf readBytes(ByteBuffer dst) {\n int length = dst.remaining();\n checkReadableBytes(length);\n dst.put(_internalNioBuffer(readerIndex, length, false));\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException {\n getBytes(index, out, length, false);\n return this;\n }\n\n private void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException {\n checkIndex(index, length);\n if (length == 0) {\n return;\n }\n ByteBufUtil.readBytes(alloc(), internal ? internalNioBuffer() : memory.duplicate(), idx(index), length, out);\n }\n\n @Override\n public ByteBuf readBytes(OutputStream out, int length) throws IOException {\n checkReadableBytes(length);\n getBytes(readerIndex, out, length, true);\n readerIndex += length;\n return this;\n }\n\n @Override\n protected void _setByte(int index, int value) {\n memory.put(idx(index), (byte) value);\n }\n\n @Override\n protected void _setShort(int index, int value) {\n memory.putShort(idx(index), (short) value);\n }\n\n @Override\n protected void _setShortLE(int index, int value) {\n _setShort(index, ByteBufUtil.swapShort((short) value));\n }\n\n @Override\n protected void _setMedium(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) (value >>> 16));\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) value);\n }\n\n @Override\n protected void _setMediumLE(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) value);\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) (value >>> 16));\n }\n\n @Override\n protected void _setInt(int index, int value) {\n memory.putInt(idx(index), value);\n }\n\n @Override\n protected void _setIntLE(int index, int value) {\n _setInt(index, ByteBufUtil.swapInt(value));\n }\n\n @Override\n protected void _setLong(int index, long value) {\n memory.putLong(idx(index), value);\n }\n\n @Override\n protected void _setLongLE(int index, long value) {\n _setLong(index, ByteBufUtil.swapLong(value));\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.capacity());\n if (src.hasArray()) {\n setBytes(index, src.array(), src.arrayOffset() + srcIndex, length);\n } else if (src.nioBufferCount() > 0) {\n for (ByteBuffer bb : src.nioBuffers(srcIndex, length)) {\n int bbLen = bb.remaining();\n setBytes(index, bb);\n index += bbLen;\n }\n } else {\n src.getBytes(srcIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.length);\n _internalNioBuffer(index, length, false).put(src, srcIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuffer src) {\n int length = src.remaining();\n checkIndex(index, length);\n ByteBuffer tmpBuf = internalNioBuffer();\n if (src == tmpBuf) {\n src = src.duplicate();\n }\n index = idx(index);\n tmpBuf.limit(index + length).position(index);\n tmpBuf.put(src);\n return this;\n }\n\n @Override\n public int setBytes(int index, InputStream in, int length) throws IOException {", "post_mask_code": "\n if (readBytes <= 0) {\n return readBytes;\n }\n ByteBuffer tmpBuf = internalNioBuffer();\n tmpBuf.position(idx(index));\n tmpBuf.put(tmp, 0, readBytes);\n return readBytes;\n }\n\n @Override\n public ByteBuf copy(int index, int length) {\n checkIndex(index, length);\n ByteBuf copy = alloc().directBuffer(length, maxCapacity());\n return copy.writeBytes(this, index, length);\n }\n\n @Override\n public boolean hasArray() {\n return false;\n }\n\n @Override\n public byte[] array() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public int arrayOffset() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public boolean hasMemoryAddress() {\n return false;\n }\n\n @Override\n public long memoryAddress() {\n throw new UnsupportedOperationException();\n }\n}\n"} {"task_id": "Java_1758", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/netty/netty/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java", "mask_start_position": 7618, "mask_end_position": 7765, "canonical_solution": "if (readBytes <= 0) {\n return readBytes;\n }\n ByteBuffer tmpBuf = internalNioBuffer();\n tmpBuf.position(idx(index));", "pre_mask_code": "package io.netty.buffer;\n\nimport io.netty.util.internal.ObjectPool;\nimport io.netty.util.internal.ObjectPool.Handle;\nimport io.netty.util.internal.ObjectPool.ObjectCreator;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.nio.ByteBuffer;\n\nfinal class PooledDirectByteBuf extends PooledByteBuf {\n\n private static final ObjectPool RECYCLER = ObjectPool.newPool(new ObjectCreator() {\n\n @Override\n public PooledDirectByteBuf newObject(Handle handle) {\n return new PooledDirectByteBuf(handle, 0);\n }\n });\n\n static PooledDirectByteBuf newInstance(int maxCapacity) {\n PooledDirectByteBuf buf = RECYCLER.get();\n buf.reuse(maxCapacity);\n return buf;\n }\n\n private PooledDirectByteBuf(Handle recyclerHandle, int maxCapacity) {\n super(recyclerHandle, maxCapacity);\n }\n\n @Override\n protected ByteBuffer newInternalNioBuffer(ByteBuffer memory) {\n return memory.duplicate();\n }\n\n @Override\n public boolean isDirect() {\n return true;\n }\n\n @Override\n protected byte _getByte(int index) {\n return memory.get(idx(index));\n }\n\n @Override\n protected short _getShort(int index) {\n return memory.getShort(idx(index));\n }\n\n @Override\n protected short _getShortLE(int index) {\n return ByteBufUtil.swapShort(_getShort(index));\n }\n\n @Override\n protected int _getUnsignedMedium(int index) {\n index = idx(index);\n return (memory.get(index) & 0xff) << 16 | (memory.get(index + 1) & 0xff) << 8 | memory.get(index + 2) & 0xff;\n }\n\n @Override\n protected int _getUnsignedMediumLE(int index) {\n index = idx(index);\n return memory.get(index) & 0xff | (memory.get(index + 1) & 0xff) << 8 | (memory.get(index + 2) & 0xff) << 16;\n }\n\n @Override\n protected int _getInt(int index) {\n return memory.getInt(idx(index));\n }\n\n @Override\n protected int _getIntLE(int index) {\n return ByteBufUtil.swapInt(_getInt(index));\n }\n\n @Override\n protected long _getLong(int index) {\n return memory.getLong(idx(index));\n }\n\n @Override\n protected long _getLongLE(int index) {\n return ByteBufUtil.swapLong(_getLong(index));\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.capacity());\n if (dst.hasArray()) {\n getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length);\n } else if (dst.nioBufferCount() > 0) {\n for (ByteBuffer bb : dst.nioBuffers(dstIndex, length)) {\n int bbLen = bb.remaining();\n getBytes(index, bb);\n index += bbLen;\n }\n } else {\n dst.setBytes(dstIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.length);\n _internalNioBuffer(index, length, true).get(dst, dstIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf readBytes(byte[] dst, int dstIndex, int length) {\n checkDstIndex(length, dstIndex, dst.length);\n _internalNioBuffer(readerIndex, length, false).get(dst, dstIndex, length);\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuffer dst) {\n dst.put(duplicateInternalNioBuffer(index, dst.remaining()));\n return this;\n }\n\n @Override\n public ByteBuf readBytes(ByteBuffer dst) {\n int length = dst.remaining();\n checkReadableBytes(length);\n dst.put(_internalNioBuffer(readerIndex, length, false));\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException {\n getBytes(index, out, length, false);\n return this;\n }\n\n private void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException {\n checkIndex(index, length);\n if (length == 0) {\n return;\n }\n ByteBufUtil.readBytes(alloc(), internal ? internalNioBuffer() : memory.duplicate(), idx(index), length, out);\n }\n\n @Override\n public ByteBuf readBytes(OutputStream out, int length) throws IOException {\n checkReadableBytes(length);\n getBytes(readerIndex, out, length, true);\n readerIndex += length;\n return this;\n }\n\n @Override\n protected void _setByte(int index, int value) {\n memory.put(idx(index), (byte) value);\n }\n\n @Override\n protected void _setShort(int index, int value) {\n memory.putShort(idx(index), (short) value);\n }\n\n @Override\n protected void _setShortLE(int index, int value) {\n _setShort(index, ByteBufUtil.swapShort((short) value));\n }\n\n @Override\n protected void _setMedium(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) (value >>> 16));\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) value);\n }\n\n @Override\n protected void _setMediumLE(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) value);\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) (value >>> 16));\n }\n\n @Override\n protected void _setInt(int index, int value) {\n memory.putInt(idx(index), value);\n }\n\n @Override\n protected void _setIntLE(int index, int value) {\n _setInt(index, ByteBufUtil.swapInt(value));\n }\n\n @Override\n protected void _setLong(int index, long value) {\n memory.putLong(idx(index), value);\n }\n\n @Override\n protected void _setLongLE(int index, long value) {\n _setLong(index, ByteBufUtil.swapLong(value));\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.capacity());\n if (src.hasArray()) {\n setBytes(index, src.array(), src.arrayOffset() + srcIndex, length);\n } else if (src.nioBufferCount() > 0) {\n for (ByteBuffer bb : src.nioBuffers(srcIndex, length)) {\n int bbLen = bb.remaining();\n setBytes(index, bb);\n index += bbLen;\n }\n } else {\n src.getBytes(srcIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.length);\n _internalNioBuffer(index, length, false).put(src, srcIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuffer src) {\n int length = src.remaining();\n checkIndex(index, length);\n ByteBuffer tmpBuf = internalNioBuffer();\n if (src == tmpBuf) {\n src = src.duplicate();\n }\n index = idx(index);\n tmpBuf.limit(index + length).position(index);\n tmpBuf.put(src);\n return this;\n }\n\n @Override\n public int setBytes(int index, InputStream in, int length) throws IOException {\n checkIndex(index, length);\n byte[] tmp = ByteBufUtil.threadLocalTempArray(length);\n int readBytes = in.read(tmp, 0, length);\n ", "post_mask_code": "\n tmpBuf.put(tmp, 0, readBytes);\n return readBytes;\n }\n\n @Override\n public ByteBuf copy(int index, int length) {\n checkIndex(index, length);\n ByteBuf copy = alloc().directBuffer(length, maxCapacity());\n return copy.writeBytes(this, index, length);\n }\n\n @Override\n public boolean hasArray() {\n return false;\n }\n\n @Override\n public byte[] array() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public int arrayOffset() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public boolean hasMemoryAddress() {\n return false;\n }\n\n @Override\n public long memoryAddress() {\n throw new UnsupportedOperationException();\n }\n}\n"} {"task_id": "Java_1759", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/netty/netty/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java", "mask_start_position": 7774, "mask_end_position": 7836, "canonical_solution": "tmpBuf.put(tmp, 0, readBytes);\n return readBytes;\n }", "pre_mask_code": "package io.netty.buffer;\n\nimport io.netty.util.internal.ObjectPool;\nimport io.netty.util.internal.ObjectPool.Handle;\nimport io.netty.util.internal.ObjectPool.ObjectCreator;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.nio.ByteBuffer;\n\nfinal class PooledDirectByteBuf extends PooledByteBuf {\n\n private static final ObjectPool RECYCLER = ObjectPool.newPool(new ObjectCreator() {\n\n @Override\n public PooledDirectByteBuf newObject(Handle handle) {\n return new PooledDirectByteBuf(handle, 0);\n }\n });\n\n static PooledDirectByteBuf newInstance(int maxCapacity) {\n PooledDirectByteBuf buf = RECYCLER.get();\n buf.reuse(maxCapacity);\n return buf;\n }\n\n private PooledDirectByteBuf(Handle recyclerHandle, int maxCapacity) {\n super(recyclerHandle, maxCapacity);\n }\n\n @Override\n protected ByteBuffer newInternalNioBuffer(ByteBuffer memory) {\n return memory.duplicate();\n }\n\n @Override\n public boolean isDirect() {\n return true;\n }\n\n @Override\n protected byte _getByte(int index) {\n return memory.get(idx(index));\n }\n\n @Override\n protected short _getShort(int index) {\n return memory.getShort(idx(index));\n }\n\n @Override\n protected short _getShortLE(int index) {\n return ByteBufUtil.swapShort(_getShort(index));\n }\n\n @Override\n protected int _getUnsignedMedium(int index) {\n index = idx(index);\n return (memory.get(index) & 0xff) << 16 | (memory.get(index + 1) & 0xff) << 8 | memory.get(index + 2) & 0xff;\n }\n\n @Override\n protected int _getUnsignedMediumLE(int index) {\n index = idx(index);\n return memory.get(index) & 0xff | (memory.get(index + 1) & 0xff) << 8 | (memory.get(index + 2) & 0xff) << 16;\n }\n\n @Override\n protected int _getInt(int index) {\n return memory.getInt(idx(index));\n }\n\n @Override\n protected int _getIntLE(int index) {\n return ByteBufUtil.swapInt(_getInt(index));\n }\n\n @Override\n protected long _getLong(int index) {\n return memory.getLong(idx(index));\n }\n\n @Override\n protected long _getLongLE(int index) {\n return ByteBufUtil.swapLong(_getLong(index));\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.capacity());\n if (dst.hasArray()) {\n getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length);\n } else if (dst.nioBufferCount() > 0) {\n for (ByteBuffer bb : dst.nioBuffers(dstIndex, length)) {\n int bbLen = bb.remaining();\n getBytes(index, bb);\n index += bbLen;\n }\n } else {\n dst.setBytes(dstIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.length);\n _internalNioBuffer(index, length, true).get(dst, dstIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf readBytes(byte[] dst, int dstIndex, int length) {\n checkDstIndex(length, dstIndex, dst.length);\n _internalNioBuffer(readerIndex, length, false).get(dst, dstIndex, length);\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuffer dst) {\n dst.put(duplicateInternalNioBuffer(index, dst.remaining()));\n return this;\n }\n\n @Override\n public ByteBuf readBytes(ByteBuffer dst) {\n int length = dst.remaining();\n checkReadableBytes(length);\n dst.put(_internalNioBuffer(readerIndex, length, false));\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException {\n getBytes(index, out, length, false);\n return this;\n }\n\n private void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException {\n checkIndex(index, length);\n if (length == 0) {\n return;\n }\n ByteBufUtil.readBytes(alloc(), internal ? internalNioBuffer() : memory.duplicate(), idx(index), length, out);\n }\n\n @Override\n public ByteBuf readBytes(OutputStream out, int length) throws IOException {\n checkReadableBytes(length);\n getBytes(readerIndex, out, length, true);\n readerIndex += length;\n return this;\n }\n\n @Override\n protected void _setByte(int index, int value) {\n memory.put(idx(index), (byte) value);\n }\n\n @Override\n protected void _setShort(int index, int value) {\n memory.putShort(idx(index), (short) value);\n }\n\n @Override\n protected void _setShortLE(int index, int value) {\n _setShort(index, ByteBufUtil.swapShort((short) value));\n }\n\n @Override\n protected void _setMedium(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) (value >>> 16));\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) value);\n }\n\n @Override\n protected void _setMediumLE(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) value);\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) (value >>> 16));\n }\n\n @Override\n protected void _setInt(int index, int value) {\n memory.putInt(idx(index), value);\n }\n\n @Override\n protected void _setIntLE(int index, int value) {\n _setInt(index, ByteBufUtil.swapInt(value));\n }\n\n @Override\n protected void _setLong(int index, long value) {\n memory.putLong(idx(index), value);\n }\n\n @Override\n protected void _setLongLE(int index, long value) {\n _setLong(index, ByteBufUtil.swapLong(value));\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.capacity());\n if (src.hasArray()) {\n setBytes(index, src.array(), src.arrayOffset() + srcIndex, length);\n } else if (src.nioBufferCount() > 0) {\n for (ByteBuffer bb : src.nioBuffers(srcIndex, length)) {\n int bbLen = bb.remaining();\n setBytes(index, bb);\n index += bbLen;\n }\n } else {\n src.getBytes(srcIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.length);\n _internalNioBuffer(index, length, false).put(src, srcIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuffer src) {\n int length = src.remaining();\n checkIndex(index, length);\n ByteBuffer tmpBuf = internalNioBuffer();\n if (src == tmpBuf) {\n src = src.duplicate();\n }\n index = idx(index);\n tmpBuf.limit(index + length).position(index);\n tmpBuf.put(src);\n return this;\n }\n\n @Override\n public int setBytes(int index, InputStream in, int length) throws IOException {\n checkIndex(index, length);\n byte[] tmp = ByteBufUtil.threadLocalTempArray(length);\n int readBytes = in.read(tmp, 0, length);\n if (readBytes <= 0) {\n return readBytes;\n }\n ByteBuffer tmpBuf = internalNioBuffer();\n tmpBuf.position(idx(index));\n ", "post_mask_code": "\n\n @Override\n public ByteBuf copy(int index, int length) {\n checkIndex(index, length);\n ByteBuf copy = alloc().directBuffer(length, maxCapacity());\n return copy.writeBytes(this, index, length);\n }\n\n @Override\n public boolean hasArray() {\n return false;\n }\n\n @Override\n public byte[] array() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public int arrayOffset() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public boolean hasMemoryAddress() {\n return false;\n }\n\n @Override\n public long memoryAddress() {\n throw new UnsupportedOperationException();\n }\n}\n"} {"task_id": "Java_1760", "language": "Java", "task_type": "single_line", "source_file": "java/github/netty/netty/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java", "mask_start_position": 5269, "mask_end_position": 5289, "canonical_solution": "yte) (value >>> 8));", "pre_mask_code": "package io.netty.buffer;\n\nimport io.netty.util.internal.ObjectPool;\nimport io.netty.util.internal.ObjectPool.Handle;\nimport io.netty.util.internal.ObjectPool.ObjectCreator;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.nio.ByteBuffer;\n\nfinal class PooledDirectByteBuf extends PooledByteBuf {\n\n private static final ObjectPool RECYCLER = ObjectPool.newPool(new ObjectCreator() {\n\n @Override\n public PooledDirectByteBuf newObject(Handle handle) {\n return new PooledDirectByteBuf(handle, 0);\n }\n });\n\n static PooledDirectByteBuf newInstance(int maxCapacity) {\n PooledDirectByteBuf buf = RECYCLER.get();\n buf.reuse(maxCapacity);\n return buf;\n }\n\n private PooledDirectByteBuf(Handle recyclerHandle, int maxCapacity) {\n super(recyclerHandle, maxCapacity);\n }\n\n @Override\n protected ByteBuffer newInternalNioBuffer(ByteBuffer memory) {\n return memory.duplicate();\n }\n\n @Override\n public boolean isDirect() {\n return true;\n }\n\n @Override\n protected byte _getByte(int index) {\n return memory.get(idx(index));\n }\n\n @Override\n protected short _getShort(int index) {\n return memory.getShort(idx(index));\n }\n\n @Override\n protected short _getShortLE(int index) {\n return ByteBufUtil.swapShort(_getShort(index));\n }\n\n @Override\n protected int _getUnsignedMedium(int index) {\n index = idx(index);\n return (memory.get(index) & 0xff) << 16 | (memory.get(index + 1) & 0xff) << 8 | memory.get(index + 2) & 0xff;\n }\n\n @Override\n protected int _getUnsignedMediumLE(int index) {\n index = idx(index);\n return memory.get(index) & 0xff | (memory.get(index + 1) & 0xff) << 8 | (memory.get(index + 2) & 0xff) << 16;\n }\n\n @Override\n protected int _getInt(int index) {\n return memory.getInt(idx(index));\n }\n\n @Override\n protected int _getIntLE(int index) {\n return ByteBufUtil.swapInt(_getInt(index));\n }\n\n @Override\n protected long _getLong(int index) {\n return memory.getLong(idx(index));\n }\n\n @Override\n protected long _getLongLE(int index) {\n return ByteBufUtil.swapLong(_getLong(index));\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.capacity());\n if (dst.hasArray()) {\n getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length);\n } else if (dst.nioBufferCount() > 0) {\n for (ByteBuffer bb : dst.nioBuffers(dstIndex, length)) {\n int bbLen = bb.remaining();\n getBytes(index, bb);\n index += bbLen;\n }\n } else {\n dst.setBytes(dstIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.length);\n _internalNioBuffer(index, length, true).get(dst, dstIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf readBytes(byte[] dst, int dstIndex, int length) {\n checkDstIndex(length, dstIndex, dst.length);\n _internalNioBuffer(readerIndex, length, false).get(dst, dstIndex, length);\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuffer dst) {\n dst.put(duplicateInternalNioBuffer(index, dst.remaining()));\n return this;\n }\n\n @Override\n public ByteBuf readBytes(ByteBuffer dst) {\n int length = dst.remaining();\n checkReadableBytes(length);\n dst.put(_internalNioBuffer(readerIndex, length, false));\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException {\n getBytes(index, out, length, false);\n return this;\n }\n\n private void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException {\n checkIndex(index, length);\n if (length == 0) {\n return;\n }\n ByteBufUtil.readBytes(alloc(), internal ? internalNioBuffer() : memory.duplicate(), idx(index), length, out);\n }\n\n @Override\n public ByteBuf readBytes(OutputStream out, int length) throws IOException {\n checkReadableBytes(length);\n getBytes(readerIndex, out, length, true);\n readerIndex += length;\n return this;\n }\n\n @Override\n protected void _setByte(int index, int value) {\n memory.put(idx(index), (byte) value);\n }\n\n @Override\n protected void _setShort(int index, int value) {\n memory.putShort(idx(index), (short) value);\n }\n\n @Override\n protected void _setShortLE(int index, int value) {\n _setShort(index, ByteBufUtil.swapShort((short) value));\n }\n\n @Override\n protected void _setMedium(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) (value >>> 16));\n memory.put(index + 1, (b", "post_mask_code": "\n memory.put(index + 2, (byte) value);\n }\n\n @Override\n protected void _setMediumLE(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) value);\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) (value >>> 16));\n }\n\n @Override\n protected void _setInt(int index, int value) {\n memory.putInt(idx(index), value);\n }\n\n @Override\n protected void _setIntLE(int index, int value) {\n _setInt(index, ByteBufUtil.swapInt(value));\n }\n\n @Override\n protected void _setLong(int index, long value) {\n memory.putLong(idx(index), value);\n }\n\n @Override\n protected void _setLongLE(int index, long value) {\n _setLong(index, ByteBufUtil.swapLong(value));\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.capacity());\n if (src.hasArray()) {\n setBytes(index, src.array(), src.arrayOffset() + srcIndex, length);\n } else if (src.nioBufferCount() > 0) {\n for (ByteBuffer bb : src.nioBuffers(srcIndex, length)) {\n int bbLen = bb.remaining();\n setBytes(index, bb);\n index += bbLen;\n }\n } else {\n src.getBytes(srcIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.length);\n _internalNioBuffer(index, length, false).put(src, srcIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuffer src) {\n int length = src.remaining();\n checkIndex(index, length);\n ByteBuffer tmpBuf = internalNioBuffer();\n if (src == tmpBuf) {\n src = src.duplicate();\n }\n index = idx(index);\n tmpBuf.limit(index + length).position(index);\n tmpBuf.put(src);\n return this;\n }\n\n @Override\n public int setBytes(int index, InputStream in, int length) throws IOException {\n checkIndex(index, length);\n byte[] tmp = ByteBufUtil.threadLocalTempArray(length);\n int readBytes = in.read(tmp, 0, length);\n if (readBytes <= 0) {\n return readBytes;\n }\n ByteBuffer tmpBuf = internalNioBuffer();\n tmpBuf.position(idx(index));\n tmpBuf.put(tmp, 0, readBytes);\n return readBytes;\n }\n\n @Override\n public ByteBuf copy(int index, int length) {\n checkIndex(index, length);\n ByteBuf copy = alloc().directBuffer(length, maxCapacity());\n return copy.writeBytes(this, index, length);\n }\n\n @Override\n public boolean hasArray() {\n return false;\n }\n\n @Override\n public byte[] array() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public int arrayOffset() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public boolean hasMemoryAddress() {\n return false;\n }\n\n @Override\n public long memoryAddress() {\n throw new UnsupportedOperationException();\n }\n}\n"} {"task_id": "Java_1761", "language": "Java", "task_type": "if_statement", "source_file": "java/github/netty/netty/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java", "mask_start_position": 2665, "mask_end_position": 2976, "canonical_solution": "if (dst.nioBufferCount() > 0) {\n for (ByteBuffer bb : dst.nioBuffers(dstIndex, length)) {\n int bbLen = bb.remaining();\n getBytes(index, bb);\n index += bbLen;\n }\n } else {\n dst.setBytes(dstIndex, this, index, length);\n }", "pre_mask_code": "package io.netty.buffer;\n\nimport io.netty.util.internal.ObjectPool;\nimport io.netty.util.internal.ObjectPool.Handle;\nimport io.netty.util.internal.ObjectPool.ObjectCreator;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.nio.ByteBuffer;\n\nfinal class PooledDirectByteBuf extends PooledByteBuf {\n\n private static final ObjectPool RECYCLER = ObjectPool.newPool(new ObjectCreator() {\n\n @Override\n public PooledDirectByteBuf newObject(Handle handle) {\n return new PooledDirectByteBuf(handle, 0);\n }\n });\n\n static PooledDirectByteBuf newInstance(int maxCapacity) {\n PooledDirectByteBuf buf = RECYCLER.get();\n buf.reuse(maxCapacity);\n return buf;\n }\n\n private PooledDirectByteBuf(Handle recyclerHandle, int maxCapacity) {\n super(recyclerHandle, maxCapacity);\n }\n\n @Override\n protected ByteBuffer newInternalNioBuffer(ByteBuffer memory) {\n return memory.duplicate();\n }\n\n @Override\n public boolean isDirect() {\n return true;\n }\n\n @Override\n protected byte _getByte(int index) {\n return memory.get(idx(index));\n }\n\n @Override\n protected short _getShort(int index) {\n return memory.getShort(idx(index));\n }\n\n @Override\n protected short _getShortLE(int index) {\n return ByteBufUtil.swapShort(_getShort(index));\n }\n\n @Override\n protected int _getUnsignedMedium(int index) {\n index = idx(index);\n return (memory.get(index) & 0xff) << 16 | (memory.get(index + 1) & 0xff) << 8 | memory.get(index + 2) & 0xff;\n }\n\n @Override\n protected int _getUnsignedMediumLE(int index) {\n index = idx(index);\n return memory.get(index) & 0xff | (memory.get(index + 1) & 0xff) << 8 | (memory.get(index + 2) & 0xff) << 16;\n }\n\n @Override\n protected int _getInt(int index) {\n return memory.getInt(idx(index));\n }\n\n @Override\n protected int _getIntLE(int index) {\n return ByteBufUtil.swapInt(_getInt(index));\n }\n\n @Override\n protected long _getLong(int index) {\n return memory.getLong(idx(index));\n }\n\n @Override\n protected long _getLongLE(int index) {\n return ByteBufUtil.swapLong(_getLong(index));\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.capacity());\n if (dst.hasArray()) {\n getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length);\n } else ", "post_mask_code": "\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) {\n checkDstIndex(index, length, dstIndex, dst.length);\n _internalNioBuffer(index, length, true).get(dst, dstIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf readBytes(byte[] dst, int dstIndex, int length) {\n checkDstIndex(length, dstIndex, dst.length);\n _internalNioBuffer(readerIndex, length, false).get(dst, dstIndex, length);\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, ByteBuffer dst) {\n dst.put(duplicateInternalNioBuffer(index, dst.remaining()));\n return this;\n }\n\n @Override\n public ByteBuf readBytes(ByteBuffer dst) {\n int length = dst.remaining();\n checkReadableBytes(length);\n dst.put(_internalNioBuffer(readerIndex, length, false));\n readerIndex += length;\n return this;\n }\n\n @Override\n public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException {\n getBytes(index, out, length, false);\n return this;\n }\n\n private void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException {\n checkIndex(index, length);\n if (length == 0) {\n return;\n }\n ByteBufUtil.readBytes(alloc(), internal ? internalNioBuffer() : memory.duplicate(), idx(index), length, out);\n }\n\n @Override\n public ByteBuf readBytes(OutputStream out, int length) throws IOException {\n checkReadableBytes(length);\n getBytes(readerIndex, out, length, true);\n readerIndex += length;\n return this;\n }\n\n @Override\n protected void _setByte(int index, int value) {\n memory.put(idx(index), (byte) value);\n }\n\n @Override\n protected void _setShort(int index, int value) {\n memory.putShort(idx(index), (short) value);\n }\n\n @Override\n protected void _setShortLE(int index, int value) {\n _setShort(index, ByteBufUtil.swapShort((short) value));\n }\n\n @Override\n protected void _setMedium(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) (value >>> 16));\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) value);\n }\n\n @Override\n protected void _setMediumLE(int index, int value) {\n index = idx(index);\n memory.put(index, (byte) value);\n memory.put(index + 1, (byte) (value >>> 8));\n memory.put(index + 2, (byte) (value >>> 16));\n }\n\n @Override\n protected void _setInt(int index, int value) {\n memory.putInt(idx(index), value);\n }\n\n @Override\n protected void _setIntLE(int index, int value) {\n _setInt(index, ByteBufUtil.swapInt(value));\n }\n\n @Override\n protected void _setLong(int index, long value) {\n memory.putLong(idx(index), value);\n }\n\n @Override\n protected void _setLongLE(int index, long value) {\n _setLong(index, ByteBufUtil.swapLong(value));\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.capacity());\n if (src.hasArray()) {\n setBytes(index, src.array(), src.arrayOffset() + srcIndex, length);\n } else if (src.nioBufferCount() > 0) {\n for (ByteBuffer bb : src.nioBuffers(srcIndex, length)) {\n int bbLen = bb.remaining();\n setBytes(index, bb);\n index += bbLen;\n }\n } else {\n src.getBytes(srcIndex, this, index, length);\n }\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) {\n checkSrcIndex(index, length, srcIndex, src.length);\n _internalNioBuffer(index, length, false).put(src, srcIndex, length);\n return this;\n }\n\n @Override\n public ByteBuf setBytes(int index, ByteBuffer src) {\n int length = src.remaining();\n checkIndex(index, length);\n ByteBuffer tmpBuf = internalNioBuffer();\n if (src == tmpBuf) {\n src = src.duplicate();\n }\n index = idx(index);\n tmpBuf.limit(index + length).position(index);\n tmpBuf.put(src);\n return this;\n }\n\n @Override\n public int setBytes(int index, InputStream in, int length) throws IOException {\n checkIndex(index, length);\n byte[] tmp = ByteBufUtil.threadLocalTempArray(length);\n int readBytes = in.read(tmp, 0, length);\n if (readBytes <= 0) {\n return readBytes;\n }\n ByteBuffer tmpBuf = internalNioBuffer();\n tmpBuf.position(idx(index));\n tmpBuf.put(tmp, 0, readBytes);\n return readBytes;\n }\n\n @Override\n public ByteBuf copy(int index, int length) {\n checkIndex(index, length);\n ByteBuf copy = alloc().directBuffer(length, maxCapacity());\n return copy.writeBytes(this, index, length);\n }\n\n @Override\n public boolean hasArray() {\n return false;\n }\n\n @Override\n public byte[] array() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public int arrayOffset() {\n throw new UnsupportedOperationException(\"direct buffer\");\n }\n\n @Override\n public boolean hasMemoryAddress() {\n return false;\n }\n\n @Override\n public long memoryAddress() {\n throw new UnsupportedOperationException();\n }\n}\n"} {"task_id": "Java_1762", "language": "Java", "task_type": "method_signature", "source_file": "java/github/beihu-stack/beihu-boot/beihu-boot-project/beihu-boot-core/tools-beihu-boot/src/main/java/ltd/beihu/core/tools/spi/ServiceLoader.java", "mask_start_position": 6842, "mask_end_position": 6943, "canonical_solution": "private static Set collectExtensionUrls(String resourceName, ClassLoader classLoader) ", "pre_mask_code": "package ltd.beihu.core.tools.spi;\n\nimport ltd.beihu.core.tools.utils.Assert;\nimport ltd.beihu.core.tools.utils.IDUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class ServiceLoader {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ServiceLoader.class);\n\n private static final String LTS_DIRECTORY = \"META-INF/ceres/\";\n\n private static final String LTS_INTERNAL = \"internal\";\n\n private static final String LTS_INTERNAL_DIRECTORY = LTS_DIRECTORY + LTS_INTERNAL + \"/\";\n\n private static final String DEFAULT_IDENTITY = IDUtils.UUID();\n\n private static final ConcurrentMap, ServiceProvider> serviceMap = new ConcurrentHashMap, ServiceProvider>();\n\n private static final ConcurrentMap cachedObjectMap = new ConcurrentHashMap();\n\n public static T loadDefault(Class clazz) {\n return load(clazz, \"\");\n }\n\n public static T load(Class clazz, String name) {\n return load(clazz, name, DEFAULT_IDENTITY);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T load(Class clazz, String name, String identity) {\n try {\n ServiceProvider serviceProvider = getServiceProvider(clazz);\n if (StringUtils.isEmpty(name)) {\n // 加载默认的\n name = serviceProvider.defaultName;\n }\n ServiceDefinition definition = serviceProvider.nameMaps.get(name);\n if (definition == null) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n // 用来保证每个节点都是一个各自的对象\n IdentityUniqueKey uniqueKey = new IdentityUniqueKey(identity, definition);\n Object obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n synchronized (definition) {\n obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n String className = definition.clazz;\n ClassLoader classLoader = definition.classLoader;\n T srv = clazz.cast(ClassLoaderUtil.newInstance(classLoader, className));\n cachedObjectMap.putIfAbsent(uniqueKey, srv);\n return srv;\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n }\n\n private static ServiceProvider getServiceProvider(Class clazz) {\n ServiceProvider serviceProvider = serviceMap.get(clazz);\n if (serviceProvider == null) {\n getServiceProviders(clazz);\n serviceProvider = serviceMap.get(clazz);\n }\n return serviceProvider;\n }\n\n public static Set getServiceProviders(final Class clazz) {\n if (clazz == null)\n throw new IllegalArgumentException(\"type == null\");\n if (!clazz.isInterface()) {\n throw new IllegalArgumentException(\" type(\" + clazz + \") is not interface!\");\n }\n if (!clazz.isAnnotationPresent(SPI.class)) {\n throw new IllegalArgumentException(\"type(\" + clazz + \") is not extension, because WITHOUT @\" + SPI.class.getSimpleName() + \" Annotation!\");\n }\n SPI spi = clazz.getAnnotation(SPI.class);\n String defaultName = spi.dftValue();\n String dynamicConfigKey = spi.key();\n final Set urlDefinitions = new HashSet();\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n urlDefinitions.addAll(collectExtensionUrls(LTS_DIRECTORY + clazz.getName(), classLoader));\n urlDefinitions.addAll(collectExtensionUrls(LTS_INTERNAL_DIRECTORY + clazz.getName(), classLoader));\n final ConcurrentMap serviceDefinitions = new ConcurrentHashMap();\n for (URLDefinition urlDefinition : urlDefinitions) {\n serviceDefinitions.putAll(parse(urlDefinition));\n }\n if (serviceDefinitions.isEmpty()) {\n throw new IllegalStateException(\"Service loader could not load \" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n ServiceProvider serviceProvider = new ServiceProvider(clazz, dynamicConfigKey, defaultName, serviceDefinitions);\n // 先移除\n serviceMap.remove(clazz);\n serviceMap.put(clazz, serviceProvider);\n return serviceDefinitions.keySet();\n }\n\n private static Map parse(URLDefinition urlDefinition) {\n final Map nameClassMap = new HashMap();\n try {\n BufferedReader r = null;\n try {\n URL url = urlDefinition.uri.toURL();\n r = new BufferedReader(new InputStreamReader(url.openStream(), \"UTF-8\"));\n while (true) {\n String line = r.readLine();\n if (line == null) {\n break;\n }\n int comment = line.indexOf('#');\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (line.length() == 0) {\n continue;\n }\n int i = line.indexOf('=');\n if (i > 0) {\n String name = line.substring(0, i).trim();\n String clazz = line.substring(i + 1).trim();\n nameClassMap.put(name, new ServiceDefinition(name, clazz, urlDefinition.classLoader));\n }\n }\n } finally {\n if (r != null) {\n r.close();\n }\n }\n } catch (Exception e) {\n LOGGER.error(\"parse \" + urlDefinition.uri + \" error:\" + e.getMessage(), e);\n }\n return nameClassMap;\n }\n\n ", "post_mask_code": "{\n try {\n final Enumeration configs;\n if (classLoader != null) {\n configs = classLoader.getResources(resourceName);\n } else {\n configs = ClassLoader.getSystemResources(resourceName);\n }\n Set urlDefinitions = new HashSet();\n while (configs.hasMoreElements()) {\n URL url = configs.nextElement();\n final URI uri = url.toURI();\n ClassLoader highestClassLoader = findHighestReachableClassLoader(url, classLoader, resourceName);\n urlDefinitions.add(new URLDefinition(uri, highestClassLoader));\n }\n return urlDefinitions;\n } catch (Exception e) {\n LOGGER.error(e.getMessage(), e);\n }\n return Collections.emptySet();\n }\n\n private static ClassLoader findHighestReachableClassLoader(URL url, ClassLoader classLoader, String resourceName) {\n if (classLoader.getParent() == null) {\n return classLoader;\n }\n ClassLoader highestClassLoader = classLoader;\n ClassLoader current = classLoader;\n while (current.getParent() != null) {\n ClassLoader parent = current.getParent();\n try {\n Enumeration resources = parent.getResources(resourceName);\n if (resources != null) {\n while (resources.hasMoreElements()) {\n URL resourceURL = resources.nextElement();\n if (url.toURI().equals(resourceURL.toURI())) {\n highestClassLoader = parent;\n }\n }\n }\n } catch (IOException ignore) {\n } catch (URISyntaxException ignore) {\n }\n current = current.getParent();\n }\n return highestClassLoader;\n }\n\n private static final class URLDefinition {\n\n private final URI uri;\n\n private final ClassLoader classLoader;\n\n private URLDefinition(URI url, ClassLoader classLoader) {\n this.uri = url;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n URLDefinition that = (URLDefinition) o;\n return uri != null ? uri.equals(that.uri) : that.uri == null;\n }\n\n @Override\n public int hashCode() {\n return uri != null ? uri.hashCode() : 0;\n }\n }\n\n private static final class ServiceDefinition {\n\n private final String name;\n\n private final String clazz;\n\n private final ClassLoader classLoader;\n\n private ServiceDefinition(String name, String clazz, ClassLoader classLoader) {\n Assert.notNull(name, \"name\");\n Assert.notNull(clazz, \"clazz\");\n Assert.notNull(classLoader, \"classLoader\");\n this.name = name;\n this.clazz = clazz;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ServiceDefinition that = (ServiceDefinition) o;\n if (name != null ? !name.equals(that.name) : that.name != null)\n return false;\n if (clazz != null ? !clazz.equals(that.clazz) : that.clazz != null)\n return false;\n return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;\n }\n\n @Override\n public int hashCode() {\n int result = name != null ? name.hashCode() : 0;\n result = 31 * result + (clazz != null ? clazz.hashCode() : 0);\n result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);\n return result;\n }\n }\n\n private static class IdentityUniqueKey {\n\n private String identity;\n\n private ServiceDefinition definition;\n\n public IdentityUniqueKey(String identity, ServiceDefinition definition) {\n this.identity = identity;\n this.definition = definition;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n IdentityUniqueKey that = (IdentityUniqueKey) o;\n if (identity != null ? !identity.equals(that.identity) : that.identity != null)\n return false;\n return definition != null ? definition.equals(that.definition) : that.definition == null;\n }\n\n @Override\n public int hashCode() {\n int result = identity != null ? identity.hashCode() : 0;\n result = 31 * result + (definition != null ? definition.hashCode() : 0);\n return result;\n }\n }\n\n private static final class ServiceProvider {\n\n private final Class clazz;\n\n private final String defaultName;\n\n private final String dynamicConfigKey;\n\n private final ConcurrentMap nameMaps;\n\n public ServiceProvider(Class clazz, String dynamicConfigKey, String defaultName, ConcurrentMap nameMaps) {\n this.clazz = clazz;\n this.dynamicConfigKey = dynamicConfigKey;\n this.defaultName = defaultName;\n this.nameMaps = nameMaps;\n }\n }\n}\n"} {"task_id": "Java_1763", "language": "Java", "task_type": "method_body", "source_file": "java/github/beihu-stack/beihu-boot/beihu-boot-project/beihu-boot-core/tools-beihu-boot/src/main/java/ltd/beihu/core/tools/spi/ServiceLoader.java", "mask_start_position": 1233, "mask_end_position": 1272, "canonical_solution": "{\n return load(clazz, \"\");\n }", "pre_mask_code": "package ltd.beihu.core.tools.spi;\n\nimport ltd.beihu.core.tools.utils.Assert;\nimport ltd.beihu.core.tools.utils.IDUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class ServiceLoader {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ServiceLoader.class);\n\n private static final String LTS_DIRECTORY = \"META-INF/ceres/\";\n\n private static final String LTS_INTERNAL = \"internal\";\n\n private static final String LTS_INTERNAL_DIRECTORY = LTS_DIRECTORY + LTS_INTERNAL + \"/\";\n\n private static final String DEFAULT_IDENTITY = IDUtils.UUID();\n\n private static final ConcurrentMap, ServiceProvider> serviceMap = new ConcurrentHashMap, ServiceProvider>();\n\n private static final ConcurrentMap cachedObjectMap = new ConcurrentHashMap();\n\n public static T loadDefault(Class clazz) ", "post_mask_code": "\n\n public static T load(Class clazz, String name) {\n return load(clazz, name, DEFAULT_IDENTITY);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T load(Class clazz, String name, String identity) {\n try {\n ServiceProvider serviceProvider = getServiceProvider(clazz);\n if (StringUtils.isEmpty(name)) {\n // 加载默认的\n name = serviceProvider.defaultName;\n }\n ServiceDefinition definition = serviceProvider.nameMaps.get(name);\n if (definition == null) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n // 用来保证每个节点都是一个各自的对象\n IdentityUniqueKey uniqueKey = new IdentityUniqueKey(identity, definition);\n Object obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n synchronized (definition) {\n obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n String className = definition.clazz;\n ClassLoader classLoader = definition.classLoader;\n T srv = clazz.cast(ClassLoaderUtil.newInstance(classLoader, className));\n cachedObjectMap.putIfAbsent(uniqueKey, srv);\n return srv;\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n }\n\n private static ServiceProvider getServiceProvider(Class clazz) {\n ServiceProvider serviceProvider = serviceMap.get(clazz);\n if (serviceProvider == null) {\n getServiceProviders(clazz);\n serviceProvider = serviceMap.get(clazz);\n }\n return serviceProvider;\n }\n\n public static Set getServiceProviders(final Class clazz) {\n if (clazz == null)\n throw new IllegalArgumentException(\"type == null\");\n if (!clazz.isInterface()) {\n throw new IllegalArgumentException(\" type(\" + clazz + \") is not interface!\");\n }\n if (!clazz.isAnnotationPresent(SPI.class)) {\n throw new IllegalArgumentException(\"type(\" + clazz + \") is not extension, because WITHOUT @\" + SPI.class.getSimpleName() + \" Annotation!\");\n }\n SPI spi = clazz.getAnnotation(SPI.class);\n String defaultName = spi.dftValue();\n String dynamicConfigKey = spi.key();\n final Set urlDefinitions = new HashSet();\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n urlDefinitions.addAll(collectExtensionUrls(LTS_DIRECTORY + clazz.getName(), classLoader));\n urlDefinitions.addAll(collectExtensionUrls(LTS_INTERNAL_DIRECTORY + clazz.getName(), classLoader));\n final ConcurrentMap serviceDefinitions = new ConcurrentHashMap();\n for (URLDefinition urlDefinition : urlDefinitions) {\n serviceDefinitions.putAll(parse(urlDefinition));\n }\n if (serviceDefinitions.isEmpty()) {\n throw new IllegalStateException(\"Service loader could not load \" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n ServiceProvider serviceProvider = new ServiceProvider(clazz, dynamicConfigKey, defaultName, serviceDefinitions);\n // 先移除\n serviceMap.remove(clazz);\n serviceMap.put(clazz, serviceProvider);\n return serviceDefinitions.keySet();\n }\n\n private static Map parse(URLDefinition urlDefinition) {\n final Map nameClassMap = new HashMap();\n try {\n BufferedReader r = null;\n try {\n URL url = urlDefinition.uri.toURL();\n r = new BufferedReader(new InputStreamReader(url.openStream(), \"UTF-8\"));\n while (true) {\n String line = r.readLine();\n if (line == null) {\n break;\n }\n int comment = line.indexOf('#');\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (line.length() == 0) {\n continue;\n }\n int i = line.indexOf('=');\n if (i > 0) {\n String name = line.substring(0, i).trim();\n String clazz = line.substring(i + 1).trim();\n nameClassMap.put(name, new ServiceDefinition(name, clazz, urlDefinition.classLoader));\n }\n }\n } finally {\n if (r != null) {\n r.close();\n }\n }\n } catch (Exception e) {\n LOGGER.error(\"parse \" + urlDefinition.uri + \" error:\" + e.getMessage(), e);\n }\n return nameClassMap;\n }\n\n private static Set collectExtensionUrls(String resourceName, ClassLoader classLoader) {\n try {\n final Enumeration configs;\n if (classLoader != null) {\n configs = classLoader.getResources(resourceName);\n } else {\n configs = ClassLoader.getSystemResources(resourceName);\n }\n Set urlDefinitions = new HashSet();\n while (configs.hasMoreElements()) {\n URL url = configs.nextElement();\n final URI uri = url.toURI();\n ClassLoader highestClassLoader = findHighestReachableClassLoader(url, classLoader, resourceName);\n urlDefinitions.add(new URLDefinition(uri, highestClassLoader));\n }\n return urlDefinitions;\n } catch (Exception e) {\n LOGGER.error(e.getMessage(), e);\n }\n return Collections.emptySet();\n }\n\n private static ClassLoader findHighestReachableClassLoader(URL url, ClassLoader classLoader, String resourceName) {\n if (classLoader.getParent() == null) {\n return classLoader;\n }\n ClassLoader highestClassLoader = classLoader;\n ClassLoader current = classLoader;\n while (current.getParent() != null) {\n ClassLoader parent = current.getParent();\n try {\n Enumeration resources = parent.getResources(resourceName);\n if (resources != null) {\n while (resources.hasMoreElements()) {\n URL resourceURL = resources.nextElement();\n if (url.toURI().equals(resourceURL.toURI())) {\n highestClassLoader = parent;\n }\n }\n }\n } catch (IOException ignore) {\n } catch (URISyntaxException ignore) {\n }\n current = current.getParent();\n }\n return highestClassLoader;\n }\n\n private static final class URLDefinition {\n\n private final URI uri;\n\n private final ClassLoader classLoader;\n\n private URLDefinition(URI url, ClassLoader classLoader) {\n this.uri = url;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n URLDefinition that = (URLDefinition) o;\n return uri != null ? uri.equals(that.uri) : that.uri == null;\n }\n\n @Override\n public int hashCode() {\n return uri != null ? uri.hashCode() : 0;\n }\n }\n\n private static final class ServiceDefinition {\n\n private final String name;\n\n private final String clazz;\n\n private final ClassLoader classLoader;\n\n private ServiceDefinition(String name, String clazz, ClassLoader classLoader) {\n Assert.notNull(name, \"name\");\n Assert.notNull(clazz, \"clazz\");\n Assert.notNull(classLoader, \"classLoader\");\n this.name = name;\n this.clazz = clazz;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ServiceDefinition that = (ServiceDefinition) o;\n if (name != null ? !name.equals(that.name) : that.name != null)\n return false;\n if (clazz != null ? !clazz.equals(that.clazz) : that.clazz != null)\n return false;\n return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;\n }\n\n @Override\n public int hashCode() {\n int result = name != null ? name.hashCode() : 0;\n result = 31 * result + (clazz != null ? clazz.hashCode() : 0);\n result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);\n return result;\n }\n }\n\n private static class IdentityUniqueKey {\n\n private String identity;\n\n private ServiceDefinition definition;\n\n public IdentityUniqueKey(String identity, ServiceDefinition definition) {\n this.identity = identity;\n this.definition = definition;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n IdentityUniqueKey that = (IdentityUniqueKey) o;\n if (identity != null ? !identity.equals(that.identity) : that.identity != null)\n return false;\n return definition != null ? definition.equals(that.definition) : that.definition == null;\n }\n\n @Override\n public int hashCode() {\n int result = identity != null ? identity.hashCode() : 0;\n result = 31 * result + (definition != null ? definition.hashCode() : 0);\n return result;\n }\n }\n\n private static final class ServiceProvider {\n\n private final Class clazz;\n\n private final String defaultName;\n\n private final String dynamicConfigKey;\n\n private final ConcurrentMap nameMaps;\n\n public ServiceProvider(Class clazz, String dynamicConfigKey, String defaultName, ConcurrentMap nameMaps) {\n this.clazz = clazz;\n this.dynamicConfigKey = dynamicConfigKey;\n this.defaultName = defaultName;\n this.nameMaps = nameMaps;\n }\n }\n}\n"} {"task_id": "Java_1764", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/beihu-stack/beihu-boot/beihu-boot-project/beihu-boot-core/tools-beihu-boot/src/main/java/ltd/beihu/core/tools/spi/ServiceLoader.java", "mask_start_position": 3541, "mask_end_position": 4123, "canonical_solution": "\n if (clazz == null)\n throw new IllegalArgumentException(\"type == null\");\n if (!clazz.isInterface()) {\n throw new IllegalArgumentException(\" type(\" + clazz + \") is not interface!\");\n }\n if (!clazz.isAnnotationPresent(SPI.class)) {\n throw new IllegalArgumentException(\"type(\" + clazz + \") is not extension, because WITHOUT @\" + SPI.class.getSimpleName() + \" Annotation!\");\n }\n SPI spi = clazz.getAnnotation(SPI.class);\n String defaultName = spi.dftValue();\n String dynamicConfigKey = spi.key();", "pre_mask_code": "package ltd.beihu.core.tools.spi;\n\nimport ltd.beihu.core.tools.utils.Assert;\nimport ltd.beihu.core.tools.utils.IDUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class ServiceLoader {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ServiceLoader.class);\n\n private static final String LTS_DIRECTORY = \"META-INF/ceres/\";\n\n private static final String LTS_INTERNAL = \"internal\";\n\n private static final String LTS_INTERNAL_DIRECTORY = LTS_DIRECTORY + LTS_INTERNAL + \"/\";\n\n private static final String DEFAULT_IDENTITY = IDUtils.UUID();\n\n private static final ConcurrentMap, ServiceProvider> serviceMap = new ConcurrentHashMap, ServiceProvider>();\n\n private static final ConcurrentMap cachedObjectMap = new ConcurrentHashMap();\n\n public static T loadDefault(Class clazz) {\n return load(clazz, \"\");\n }\n\n public static T load(Class clazz, String name) {\n return load(clazz, name, DEFAULT_IDENTITY);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T load(Class clazz, String name, String identity) {\n try {\n ServiceProvider serviceProvider = getServiceProvider(clazz);\n if (StringUtils.isEmpty(name)) {\n // 加载默认的\n name = serviceProvider.defaultName;\n }\n ServiceDefinition definition = serviceProvider.nameMaps.get(name);\n if (definition == null) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n // 用来保证每个节点都是一个各自的对象\n IdentityUniqueKey uniqueKey = new IdentityUniqueKey(identity, definition);\n Object obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n synchronized (definition) {\n obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n String className = definition.clazz;\n ClassLoader classLoader = definition.classLoader;\n T srv = clazz.cast(ClassLoaderUtil.newInstance(classLoader, className));\n cachedObjectMap.putIfAbsent(uniqueKey, srv);\n return srv;\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n }\n\n private static ServiceProvider getServiceProvider(Class clazz) {\n ServiceProvider serviceProvider = serviceMap.get(clazz);\n if (serviceProvider == null) {\n getServiceProviders(clazz);\n serviceProvider = serviceMap.get(clazz);\n }\n return serviceProvider;\n }\n\n public static Set getServiceProviders(final Class clazz) {", "post_mask_code": "\n final Set urlDefinitions = new HashSet();\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n urlDefinitions.addAll(collectExtensionUrls(LTS_DIRECTORY + clazz.getName(), classLoader));\n urlDefinitions.addAll(collectExtensionUrls(LTS_INTERNAL_DIRECTORY + clazz.getName(), classLoader));\n final ConcurrentMap serviceDefinitions = new ConcurrentHashMap();\n for (URLDefinition urlDefinition : urlDefinitions) {\n serviceDefinitions.putAll(parse(urlDefinition));\n }\n if (serviceDefinitions.isEmpty()) {\n throw new IllegalStateException(\"Service loader could not load \" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n ServiceProvider serviceProvider = new ServiceProvider(clazz, dynamicConfigKey, defaultName, serviceDefinitions);\n // 先移除\n serviceMap.remove(clazz);\n serviceMap.put(clazz, serviceProvider);\n return serviceDefinitions.keySet();\n }\n\n private static Map parse(URLDefinition urlDefinition) {\n final Map nameClassMap = new HashMap();\n try {\n BufferedReader r = null;\n try {\n URL url = urlDefinition.uri.toURL();\n r = new BufferedReader(new InputStreamReader(url.openStream(), \"UTF-8\"));\n while (true) {\n String line = r.readLine();\n if (line == null) {\n break;\n }\n int comment = line.indexOf('#');\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (line.length() == 0) {\n continue;\n }\n int i = line.indexOf('=');\n if (i > 0) {\n String name = line.substring(0, i).trim();\n String clazz = line.substring(i + 1).trim();\n nameClassMap.put(name, new ServiceDefinition(name, clazz, urlDefinition.classLoader));\n }\n }\n } finally {\n if (r != null) {\n r.close();\n }\n }\n } catch (Exception e) {\n LOGGER.error(\"parse \" + urlDefinition.uri + \" error:\" + e.getMessage(), e);\n }\n return nameClassMap;\n }\n\n private static Set collectExtensionUrls(String resourceName, ClassLoader classLoader) {\n try {\n final Enumeration configs;\n if (classLoader != null) {\n configs = classLoader.getResources(resourceName);\n } else {\n configs = ClassLoader.getSystemResources(resourceName);\n }\n Set urlDefinitions = new HashSet();\n while (configs.hasMoreElements()) {\n URL url = configs.nextElement();\n final URI uri = url.toURI();\n ClassLoader highestClassLoader = findHighestReachableClassLoader(url, classLoader, resourceName);\n urlDefinitions.add(new URLDefinition(uri, highestClassLoader));\n }\n return urlDefinitions;\n } catch (Exception e) {\n LOGGER.error(e.getMessage(), e);\n }\n return Collections.emptySet();\n }\n\n private static ClassLoader findHighestReachableClassLoader(URL url, ClassLoader classLoader, String resourceName) {\n if (classLoader.getParent() == null) {\n return classLoader;\n }\n ClassLoader highestClassLoader = classLoader;\n ClassLoader current = classLoader;\n while (current.getParent() != null) {\n ClassLoader parent = current.getParent();\n try {\n Enumeration resources = parent.getResources(resourceName);\n if (resources != null) {\n while (resources.hasMoreElements()) {\n URL resourceURL = resources.nextElement();\n if (url.toURI().equals(resourceURL.toURI())) {\n highestClassLoader = parent;\n }\n }\n }\n } catch (IOException ignore) {\n } catch (URISyntaxException ignore) {\n }\n current = current.getParent();\n }\n return highestClassLoader;\n }\n\n private static final class URLDefinition {\n\n private final URI uri;\n\n private final ClassLoader classLoader;\n\n private URLDefinition(URI url, ClassLoader classLoader) {\n this.uri = url;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n URLDefinition that = (URLDefinition) o;\n return uri != null ? uri.equals(that.uri) : that.uri == null;\n }\n\n @Override\n public int hashCode() {\n return uri != null ? uri.hashCode() : 0;\n }\n }\n\n private static final class ServiceDefinition {\n\n private final String name;\n\n private final String clazz;\n\n private final ClassLoader classLoader;\n\n private ServiceDefinition(String name, String clazz, ClassLoader classLoader) {\n Assert.notNull(name, \"name\");\n Assert.notNull(clazz, \"clazz\");\n Assert.notNull(classLoader, \"classLoader\");\n this.name = name;\n this.clazz = clazz;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ServiceDefinition that = (ServiceDefinition) o;\n if (name != null ? !name.equals(that.name) : that.name != null)\n return false;\n if (clazz != null ? !clazz.equals(that.clazz) : that.clazz != null)\n return false;\n return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;\n }\n\n @Override\n public int hashCode() {\n int result = name != null ? name.hashCode() : 0;\n result = 31 * result + (clazz != null ? clazz.hashCode() : 0);\n result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);\n return result;\n }\n }\n\n private static class IdentityUniqueKey {\n\n private String identity;\n\n private ServiceDefinition definition;\n\n public IdentityUniqueKey(String identity, ServiceDefinition definition) {\n this.identity = identity;\n this.definition = definition;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n IdentityUniqueKey that = (IdentityUniqueKey) o;\n if (identity != null ? !identity.equals(that.identity) : that.identity != null)\n return false;\n return definition != null ? definition.equals(that.definition) : that.definition == null;\n }\n\n @Override\n public int hashCode() {\n int result = identity != null ? identity.hashCode() : 0;\n result = 31 * result + (definition != null ? definition.hashCode() : 0);\n return result;\n }\n }\n\n private static final class ServiceProvider {\n\n private final Class clazz;\n\n private final String defaultName;\n\n private final String dynamicConfigKey;\n\n private final ConcurrentMap nameMaps;\n\n public ServiceProvider(Class clazz, String dynamicConfigKey, String defaultName, ConcurrentMap nameMaps) {\n this.clazz = clazz;\n this.dynamicConfigKey = dynamicConfigKey;\n this.defaultName = defaultName;\n this.nameMaps = nameMaps;\n }\n }\n}\n"} {"task_id": "Java_1765", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/beihu-stack/beihu-boot/beihu-boot-project/beihu-boot-core/tools-beihu-boot/src/main/java/ltd/beihu/core/tools/spi/ServiceLoader.java", "mask_start_position": 4132, "mask_end_position": 4752, "canonical_solution": "final Set urlDefinitions = new HashSet();\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n urlDefinitions.addAll(collectExtensionUrls(LTS_DIRECTORY + clazz.getName(), classLoader));\n urlDefinitions.addAll(collectExtensionUrls(LTS_INTERNAL_DIRECTORY + clazz.getName(), classLoader));\n final ConcurrentMap serviceDefinitions = new ConcurrentHashMap();\n for (URLDefinition urlDefinition : urlDefinitions) {\n serviceDefinitions.putAll(parse(urlDefinition));\n }", "pre_mask_code": "package ltd.beihu.core.tools.spi;\n\nimport ltd.beihu.core.tools.utils.Assert;\nimport ltd.beihu.core.tools.utils.IDUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class ServiceLoader {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ServiceLoader.class);\n\n private static final String LTS_DIRECTORY = \"META-INF/ceres/\";\n\n private static final String LTS_INTERNAL = \"internal\";\n\n private static final String LTS_INTERNAL_DIRECTORY = LTS_DIRECTORY + LTS_INTERNAL + \"/\";\n\n private static final String DEFAULT_IDENTITY = IDUtils.UUID();\n\n private static final ConcurrentMap, ServiceProvider> serviceMap = new ConcurrentHashMap, ServiceProvider>();\n\n private static final ConcurrentMap cachedObjectMap = new ConcurrentHashMap();\n\n public static T loadDefault(Class clazz) {\n return load(clazz, \"\");\n }\n\n public static T load(Class clazz, String name) {\n return load(clazz, name, DEFAULT_IDENTITY);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T load(Class clazz, String name, String identity) {\n try {\n ServiceProvider serviceProvider = getServiceProvider(clazz);\n if (StringUtils.isEmpty(name)) {\n // 加载默认的\n name = serviceProvider.defaultName;\n }\n ServiceDefinition definition = serviceProvider.nameMaps.get(name);\n if (definition == null) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n // 用来保证每个节点都是一个各自的对象\n IdentityUniqueKey uniqueKey = new IdentityUniqueKey(identity, definition);\n Object obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n synchronized (definition) {\n obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n String className = definition.clazz;\n ClassLoader classLoader = definition.classLoader;\n T srv = clazz.cast(ClassLoaderUtil.newInstance(classLoader, className));\n cachedObjectMap.putIfAbsent(uniqueKey, srv);\n return srv;\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n }\n\n private static ServiceProvider getServiceProvider(Class clazz) {\n ServiceProvider serviceProvider = serviceMap.get(clazz);\n if (serviceProvider == null) {\n getServiceProviders(clazz);\n serviceProvider = serviceMap.get(clazz);\n }\n return serviceProvider;\n }\n\n public static Set getServiceProviders(final Class clazz) {\n if (clazz == null)\n throw new IllegalArgumentException(\"type == null\");\n if (!clazz.isInterface()) {\n throw new IllegalArgumentException(\" type(\" + clazz + \") is not interface!\");\n }\n if (!clazz.isAnnotationPresent(SPI.class)) {\n throw new IllegalArgumentException(\"type(\" + clazz + \") is not extension, because WITHOUT @\" + SPI.class.getSimpleName() + \" Annotation!\");\n }\n SPI spi = clazz.getAnnotation(SPI.class);\n String defaultName = spi.dftValue();\n String dynamicConfigKey = spi.key();\n ", "post_mask_code": "\n if (serviceDefinitions.isEmpty()) {\n throw new IllegalStateException(\"Service loader could not load \" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n ServiceProvider serviceProvider = new ServiceProvider(clazz, dynamicConfigKey, defaultName, serviceDefinitions);\n // 先移除\n serviceMap.remove(clazz);\n serviceMap.put(clazz, serviceProvider);\n return serviceDefinitions.keySet();\n }\n\n private static Map parse(URLDefinition urlDefinition) {\n final Map nameClassMap = new HashMap();\n try {\n BufferedReader r = null;\n try {\n URL url = urlDefinition.uri.toURL();\n r = new BufferedReader(new InputStreamReader(url.openStream(), \"UTF-8\"));\n while (true) {\n String line = r.readLine();\n if (line == null) {\n break;\n }\n int comment = line.indexOf('#');\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (line.length() == 0) {\n continue;\n }\n int i = line.indexOf('=');\n if (i > 0) {\n String name = line.substring(0, i).trim();\n String clazz = line.substring(i + 1).trim();\n nameClassMap.put(name, new ServiceDefinition(name, clazz, urlDefinition.classLoader));\n }\n }\n } finally {\n if (r != null) {\n r.close();\n }\n }\n } catch (Exception e) {\n LOGGER.error(\"parse \" + urlDefinition.uri + \" error:\" + e.getMessage(), e);\n }\n return nameClassMap;\n }\n\n private static Set collectExtensionUrls(String resourceName, ClassLoader classLoader) {\n try {\n final Enumeration configs;\n if (classLoader != null) {\n configs = classLoader.getResources(resourceName);\n } else {\n configs = ClassLoader.getSystemResources(resourceName);\n }\n Set urlDefinitions = new HashSet();\n while (configs.hasMoreElements()) {\n URL url = configs.nextElement();\n final URI uri = url.toURI();\n ClassLoader highestClassLoader = findHighestReachableClassLoader(url, classLoader, resourceName);\n urlDefinitions.add(new URLDefinition(uri, highestClassLoader));\n }\n return urlDefinitions;\n } catch (Exception e) {\n LOGGER.error(e.getMessage(), e);\n }\n return Collections.emptySet();\n }\n\n private static ClassLoader findHighestReachableClassLoader(URL url, ClassLoader classLoader, String resourceName) {\n if (classLoader.getParent() == null) {\n return classLoader;\n }\n ClassLoader highestClassLoader = classLoader;\n ClassLoader current = classLoader;\n while (current.getParent() != null) {\n ClassLoader parent = current.getParent();\n try {\n Enumeration resources = parent.getResources(resourceName);\n if (resources != null) {\n while (resources.hasMoreElements()) {\n URL resourceURL = resources.nextElement();\n if (url.toURI().equals(resourceURL.toURI())) {\n highestClassLoader = parent;\n }\n }\n }\n } catch (IOException ignore) {\n } catch (URISyntaxException ignore) {\n }\n current = current.getParent();\n }\n return highestClassLoader;\n }\n\n private static final class URLDefinition {\n\n private final URI uri;\n\n private final ClassLoader classLoader;\n\n private URLDefinition(URI url, ClassLoader classLoader) {\n this.uri = url;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n URLDefinition that = (URLDefinition) o;\n return uri != null ? uri.equals(that.uri) : that.uri == null;\n }\n\n @Override\n public int hashCode() {\n return uri != null ? uri.hashCode() : 0;\n }\n }\n\n private static final class ServiceDefinition {\n\n private final String name;\n\n private final String clazz;\n\n private final ClassLoader classLoader;\n\n private ServiceDefinition(String name, String clazz, ClassLoader classLoader) {\n Assert.notNull(name, \"name\");\n Assert.notNull(clazz, \"clazz\");\n Assert.notNull(classLoader, \"classLoader\");\n this.name = name;\n this.clazz = clazz;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ServiceDefinition that = (ServiceDefinition) o;\n if (name != null ? !name.equals(that.name) : that.name != null)\n return false;\n if (clazz != null ? !clazz.equals(that.clazz) : that.clazz != null)\n return false;\n return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;\n }\n\n @Override\n public int hashCode() {\n int result = name != null ? name.hashCode() : 0;\n result = 31 * result + (clazz != null ? clazz.hashCode() : 0);\n result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);\n return result;\n }\n }\n\n private static class IdentityUniqueKey {\n\n private String identity;\n\n private ServiceDefinition definition;\n\n public IdentityUniqueKey(String identity, ServiceDefinition definition) {\n this.identity = identity;\n this.definition = definition;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n IdentityUniqueKey that = (IdentityUniqueKey) o;\n if (identity != null ? !identity.equals(that.identity) : that.identity != null)\n return false;\n return definition != null ? definition.equals(that.definition) : that.definition == null;\n }\n\n @Override\n public int hashCode() {\n int result = identity != null ? identity.hashCode() : 0;\n result = 31 * result + (definition != null ? definition.hashCode() : 0);\n return result;\n }\n }\n\n private static final class ServiceProvider {\n\n private final Class clazz;\n\n private final String defaultName;\n\n private final String dynamicConfigKey;\n\n private final ConcurrentMap nameMaps;\n\n public ServiceProvider(Class clazz, String dynamicConfigKey, String defaultName, ConcurrentMap nameMaps) {\n this.clazz = clazz;\n this.dynamicConfigKey = dynamicConfigKey;\n this.defaultName = defaultName;\n this.nameMaps = nameMaps;\n }\n }\n}\n"} {"task_id": "Java_1766", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/beihu-stack/beihu-boot/beihu-boot-project/beihu-boot-core/tools-beihu-boot/src/main/java/ltd/beihu/core/tools/spi/ServiceLoader.java", "mask_start_position": 4761, "mask_end_position": 5294, "canonical_solution": "if (serviceDefinitions.isEmpty()) {\n throw new IllegalStateException(\"Service loader could not load \" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n ServiceProvider serviceProvider = new ServiceProvider(clazz, dynamicConfigKey, defaultName, serviceDefinitions);\n // 先移除\n serviceMap.remove(clazz);\n serviceMap.put(clazz, serviceProvider);\n return serviceDefinitions.keySet();\n }", "pre_mask_code": "package ltd.beihu.core.tools.spi;\n\nimport ltd.beihu.core.tools.utils.Assert;\nimport ltd.beihu.core.tools.utils.IDUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class ServiceLoader {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ServiceLoader.class);\n\n private static final String LTS_DIRECTORY = \"META-INF/ceres/\";\n\n private static final String LTS_INTERNAL = \"internal\";\n\n private static final String LTS_INTERNAL_DIRECTORY = LTS_DIRECTORY + LTS_INTERNAL + \"/\";\n\n private static final String DEFAULT_IDENTITY = IDUtils.UUID();\n\n private static final ConcurrentMap, ServiceProvider> serviceMap = new ConcurrentHashMap, ServiceProvider>();\n\n private static final ConcurrentMap cachedObjectMap = new ConcurrentHashMap();\n\n public static T loadDefault(Class clazz) {\n return load(clazz, \"\");\n }\n\n public static T load(Class clazz, String name) {\n return load(clazz, name, DEFAULT_IDENTITY);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T load(Class clazz, String name, String identity) {\n try {\n ServiceProvider serviceProvider = getServiceProvider(clazz);\n if (StringUtils.isEmpty(name)) {\n // 加载默认的\n name = serviceProvider.defaultName;\n }\n ServiceDefinition definition = serviceProvider.nameMaps.get(name);\n if (definition == null) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n // 用来保证每个节点都是一个各自的对象\n IdentityUniqueKey uniqueKey = new IdentityUniqueKey(identity, definition);\n Object obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n synchronized (definition) {\n obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n String className = definition.clazz;\n ClassLoader classLoader = definition.classLoader;\n T srv = clazz.cast(ClassLoaderUtil.newInstance(classLoader, className));\n cachedObjectMap.putIfAbsent(uniqueKey, srv);\n return srv;\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n }\n\n private static ServiceProvider getServiceProvider(Class clazz) {\n ServiceProvider serviceProvider = serviceMap.get(clazz);\n if (serviceProvider == null) {\n getServiceProviders(clazz);\n serviceProvider = serviceMap.get(clazz);\n }\n return serviceProvider;\n }\n\n public static Set getServiceProviders(final Class clazz) {\n if (clazz == null)\n throw new IllegalArgumentException(\"type == null\");\n if (!clazz.isInterface()) {\n throw new IllegalArgumentException(\" type(\" + clazz + \") is not interface!\");\n }\n if (!clazz.isAnnotationPresent(SPI.class)) {\n throw new IllegalArgumentException(\"type(\" + clazz + \") is not extension, because WITHOUT @\" + SPI.class.getSimpleName() + \" Annotation!\");\n }\n SPI spi = clazz.getAnnotation(SPI.class);\n String defaultName = spi.dftValue();\n String dynamicConfigKey = spi.key();\n final Set urlDefinitions = new HashSet();\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n urlDefinitions.addAll(collectExtensionUrls(LTS_DIRECTORY + clazz.getName(), classLoader));\n urlDefinitions.addAll(collectExtensionUrls(LTS_INTERNAL_DIRECTORY + clazz.getName(), classLoader));\n final ConcurrentMap serviceDefinitions = new ConcurrentHashMap();\n for (URLDefinition urlDefinition : urlDefinitions) {\n serviceDefinitions.putAll(parse(urlDefinition));\n }\n ", "post_mask_code": "\n\n private static Map parse(URLDefinition urlDefinition) {\n final Map nameClassMap = new HashMap();\n try {\n BufferedReader r = null;\n try {\n URL url = urlDefinition.uri.toURL();\n r = new BufferedReader(new InputStreamReader(url.openStream(), \"UTF-8\"));\n while (true) {\n String line = r.readLine();\n if (line == null) {\n break;\n }\n int comment = line.indexOf('#');\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (line.length() == 0) {\n continue;\n }\n int i = line.indexOf('=');\n if (i > 0) {\n String name = line.substring(0, i).trim();\n String clazz = line.substring(i + 1).trim();\n nameClassMap.put(name, new ServiceDefinition(name, clazz, urlDefinition.classLoader));\n }\n }\n } finally {\n if (r != null) {\n r.close();\n }\n }\n } catch (Exception e) {\n LOGGER.error(\"parse \" + urlDefinition.uri + \" error:\" + e.getMessage(), e);\n }\n return nameClassMap;\n }\n\n private static Set collectExtensionUrls(String resourceName, ClassLoader classLoader) {\n try {\n final Enumeration configs;\n if (classLoader != null) {\n configs = classLoader.getResources(resourceName);\n } else {\n configs = ClassLoader.getSystemResources(resourceName);\n }\n Set urlDefinitions = new HashSet();\n while (configs.hasMoreElements()) {\n URL url = configs.nextElement();\n final URI uri = url.toURI();\n ClassLoader highestClassLoader = findHighestReachableClassLoader(url, classLoader, resourceName);\n urlDefinitions.add(new URLDefinition(uri, highestClassLoader));\n }\n return urlDefinitions;\n } catch (Exception e) {\n LOGGER.error(e.getMessage(), e);\n }\n return Collections.emptySet();\n }\n\n private static ClassLoader findHighestReachableClassLoader(URL url, ClassLoader classLoader, String resourceName) {\n if (classLoader.getParent() == null) {\n return classLoader;\n }\n ClassLoader highestClassLoader = classLoader;\n ClassLoader current = classLoader;\n while (current.getParent() != null) {\n ClassLoader parent = current.getParent();\n try {\n Enumeration resources = parent.getResources(resourceName);\n if (resources != null) {\n while (resources.hasMoreElements()) {\n URL resourceURL = resources.nextElement();\n if (url.toURI().equals(resourceURL.toURI())) {\n highestClassLoader = parent;\n }\n }\n }\n } catch (IOException ignore) {\n } catch (URISyntaxException ignore) {\n }\n current = current.getParent();\n }\n return highestClassLoader;\n }\n\n private static final class URLDefinition {\n\n private final URI uri;\n\n private final ClassLoader classLoader;\n\n private URLDefinition(URI url, ClassLoader classLoader) {\n this.uri = url;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n URLDefinition that = (URLDefinition) o;\n return uri != null ? uri.equals(that.uri) : that.uri == null;\n }\n\n @Override\n public int hashCode() {\n return uri != null ? uri.hashCode() : 0;\n }\n }\n\n private static final class ServiceDefinition {\n\n private final String name;\n\n private final String clazz;\n\n private final ClassLoader classLoader;\n\n private ServiceDefinition(String name, String clazz, ClassLoader classLoader) {\n Assert.notNull(name, \"name\");\n Assert.notNull(clazz, \"clazz\");\n Assert.notNull(classLoader, \"classLoader\");\n this.name = name;\n this.clazz = clazz;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ServiceDefinition that = (ServiceDefinition) o;\n if (name != null ? !name.equals(that.name) : that.name != null)\n return false;\n if (clazz != null ? !clazz.equals(that.clazz) : that.clazz != null)\n return false;\n return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;\n }\n\n @Override\n public int hashCode() {\n int result = name != null ? name.hashCode() : 0;\n result = 31 * result + (clazz != null ? clazz.hashCode() : 0);\n result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);\n return result;\n }\n }\n\n private static class IdentityUniqueKey {\n\n private String identity;\n\n private ServiceDefinition definition;\n\n public IdentityUniqueKey(String identity, ServiceDefinition definition) {\n this.identity = identity;\n this.definition = definition;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n IdentityUniqueKey that = (IdentityUniqueKey) o;\n if (identity != null ? !identity.equals(that.identity) : that.identity != null)\n return false;\n return definition != null ? definition.equals(that.definition) : that.definition == null;\n }\n\n @Override\n public int hashCode() {\n int result = identity != null ? identity.hashCode() : 0;\n result = 31 * result + (definition != null ? definition.hashCode() : 0);\n return result;\n }\n }\n\n private static final class ServiceProvider {\n\n private final Class clazz;\n\n private final String defaultName;\n\n private final String dynamicConfigKey;\n\n private final ConcurrentMap nameMaps;\n\n public ServiceProvider(Class clazz, String dynamicConfigKey, String defaultName, ConcurrentMap nameMaps) {\n this.clazz = clazz;\n this.dynamicConfigKey = dynamicConfigKey;\n this.defaultName = defaultName;\n this.nameMaps = nameMaps;\n }\n }\n}\n"} {"task_id": "Java_1767", "language": "Java", "task_type": "single_line", "source_file": "java/github/beihu-stack/beihu-boot/beihu-boot-project/beihu-boot-core/tools-beihu-boot/src/main/java/ltd/beihu/core/tools/spi/ServiceLoader.java", "mask_start_position": 10658, "mask_end_position": 10750, "canonical_solution": "eturn classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;", "pre_mask_code": "package ltd.beihu.core.tools.spi;\n\nimport ltd.beihu.core.tools.utils.Assert;\nimport ltd.beihu.core.tools.utils.IDUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class ServiceLoader {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ServiceLoader.class);\n\n private static final String LTS_DIRECTORY = \"META-INF/ceres/\";\n\n private static final String LTS_INTERNAL = \"internal\";\n\n private static final String LTS_INTERNAL_DIRECTORY = LTS_DIRECTORY + LTS_INTERNAL + \"/\";\n\n private static final String DEFAULT_IDENTITY = IDUtils.UUID();\n\n private static final ConcurrentMap, ServiceProvider> serviceMap = new ConcurrentHashMap, ServiceProvider>();\n\n private static final ConcurrentMap cachedObjectMap = new ConcurrentHashMap();\n\n public static T loadDefault(Class clazz) {\n return load(clazz, \"\");\n }\n\n public static T load(Class clazz, String name) {\n return load(clazz, name, DEFAULT_IDENTITY);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T load(Class clazz, String name, String identity) {\n try {\n ServiceProvider serviceProvider = getServiceProvider(clazz);\n if (StringUtils.isEmpty(name)) {\n // 加载默认的\n name = serviceProvider.defaultName;\n }\n ServiceDefinition definition = serviceProvider.nameMaps.get(name);\n if (definition == null) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n // 用来保证每个节点都是一个各自的对象\n IdentityUniqueKey uniqueKey = new IdentityUniqueKey(identity, definition);\n Object obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n synchronized (definition) {\n obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n String className = definition.clazz;\n ClassLoader classLoader = definition.classLoader;\n T srv = clazz.cast(ClassLoaderUtil.newInstance(classLoader, className));\n cachedObjectMap.putIfAbsent(uniqueKey, srv);\n return srv;\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n }\n\n private static ServiceProvider getServiceProvider(Class clazz) {\n ServiceProvider serviceProvider = serviceMap.get(clazz);\n if (serviceProvider == null) {\n getServiceProviders(clazz);\n serviceProvider = serviceMap.get(clazz);\n }\n return serviceProvider;\n }\n\n public static Set getServiceProviders(final Class clazz) {\n if (clazz == null)\n throw new IllegalArgumentException(\"type == null\");\n if (!clazz.isInterface()) {\n throw new IllegalArgumentException(\" type(\" + clazz + \") is not interface!\");\n }\n if (!clazz.isAnnotationPresent(SPI.class)) {\n throw new IllegalArgumentException(\"type(\" + clazz + \") is not extension, because WITHOUT @\" + SPI.class.getSimpleName() + \" Annotation!\");\n }\n SPI spi = clazz.getAnnotation(SPI.class);\n String defaultName = spi.dftValue();\n String dynamicConfigKey = spi.key();\n final Set urlDefinitions = new HashSet();\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n urlDefinitions.addAll(collectExtensionUrls(LTS_DIRECTORY + clazz.getName(), classLoader));\n urlDefinitions.addAll(collectExtensionUrls(LTS_INTERNAL_DIRECTORY + clazz.getName(), classLoader));\n final ConcurrentMap serviceDefinitions = new ConcurrentHashMap();\n for (URLDefinition urlDefinition : urlDefinitions) {\n serviceDefinitions.putAll(parse(urlDefinition));\n }\n if (serviceDefinitions.isEmpty()) {\n throw new IllegalStateException(\"Service loader could not load \" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n ServiceProvider serviceProvider = new ServiceProvider(clazz, dynamicConfigKey, defaultName, serviceDefinitions);\n // 先移除\n serviceMap.remove(clazz);\n serviceMap.put(clazz, serviceProvider);\n return serviceDefinitions.keySet();\n }\n\n private static Map parse(URLDefinition urlDefinition) {\n final Map nameClassMap = new HashMap();\n try {\n BufferedReader r = null;\n try {\n URL url = urlDefinition.uri.toURL();\n r = new BufferedReader(new InputStreamReader(url.openStream(), \"UTF-8\"));\n while (true) {\n String line = r.readLine();\n if (line == null) {\n break;\n }\n int comment = line.indexOf('#');\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (line.length() == 0) {\n continue;\n }\n int i = line.indexOf('=');\n if (i > 0) {\n String name = line.substring(0, i).trim();\n String clazz = line.substring(i + 1).trim();\n nameClassMap.put(name, new ServiceDefinition(name, clazz, urlDefinition.classLoader));\n }\n }\n } finally {\n if (r != null) {\n r.close();\n }\n }\n } catch (Exception e) {\n LOGGER.error(\"parse \" + urlDefinition.uri + \" error:\" + e.getMessage(), e);\n }\n return nameClassMap;\n }\n\n private static Set collectExtensionUrls(String resourceName, ClassLoader classLoader) {\n try {\n final Enumeration configs;\n if (classLoader != null) {\n configs = classLoader.getResources(resourceName);\n } else {\n configs = ClassLoader.getSystemResources(resourceName);\n }\n Set urlDefinitions = new HashSet();\n while (configs.hasMoreElements()) {\n URL url = configs.nextElement();\n final URI uri = url.toURI();\n ClassLoader highestClassLoader = findHighestReachableClassLoader(url, classLoader, resourceName);\n urlDefinitions.add(new URLDefinition(uri, highestClassLoader));\n }\n return urlDefinitions;\n } catch (Exception e) {\n LOGGER.error(e.getMessage(), e);\n }\n return Collections.emptySet();\n }\n\n private static ClassLoader findHighestReachableClassLoader(URL url, ClassLoader classLoader, String resourceName) {\n if (classLoader.getParent() == null) {\n return classLoader;\n }\n ClassLoader highestClassLoader = classLoader;\n ClassLoader current = classLoader;\n while (current.getParent() != null) {\n ClassLoader parent = current.getParent();\n try {\n Enumeration resources = parent.getResources(resourceName);\n if (resources != null) {\n while (resources.hasMoreElements()) {\n URL resourceURL = resources.nextElement();\n if (url.toURI().equals(resourceURL.toURI())) {\n highestClassLoader = parent;\n }\n }\n }\n } catch (IOException ignore) {\n } catch (URISyntaxException ignore) {\n }\n current = current.getParent();\n }\n return highestClassLoader;\n }\n\n private static final class URLDefinition {\n\n private final URI uri;\n\n private final ClassLoader classLoader;\n\n private URLDefinition(URI url, ClassLoader classLoader) {\n this.uri = url;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n URLDefinition that = (URLDefinition) o;\n return uri != null ? uri.equals(that.uri) : that.uri == null;\n }\n\n @Override\n public int hashCode() {\n return uri != null ? uri.hashCode() : 0;\n }\n }\n\n private static final class ServiceDefinition {\n\n private final String name;\n\n private final String clazz;\n\n private final ClassLoader classLoader;\n\n private ServiceDefinition(String name, String clazz, ClassLoader classLoader) {\n Assert.notNull(name, \"name\");\n Assert.notNull(clazz, \"clazz\");\n Assert.notNull(classLoader, \"classLoader\");\n this.name = name;\n this.clazz = clazz;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ServiceDefinition that = (ServiceDefinition) o;\n if (name != null ? !name.equals(that.name) : that.name != null)\n return false;\n if (clazz != null ? !clazz.equals(that.clazz) : that.clazz != null)\n return false;\n r", "post_mask_code": "\n }\n\n @Override\n public int hashCode() {\n int result = name != null ? name.hashCode() : 0;\n result = 31 * result + (clazz != null ? clazz.hashCode() : 0);\n result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);\n return result;\n }\n }\n\n private static class IdentityUniqueKey {\n\n private String identity;\n\n private ServiceDefinition definition;\n\n public IdentityUniqueKey(String identity, ServiceDefinition definition) {\n this.identity = identity;\n this.definition = definition;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n IdentityUniqueKey that = (IdentityUniqueKey) o;\n if (identity != null ? !identity.equals(that.identity) : that.identity != null)\n return false;\n return definition != null ? definition.equals(that.definition) : that.definition == null;\n }\n\n @Override\n public int hashCode() {\n int result = identity != null ? identity.hashCode() : 0;\n result = 31 * result + (definition != null ? definition.hashCode() : 0);\n return result;\n }\n }\n\n private static final class ServiceProvider {\n\n private final Class clazz;\n\n private final String defaultName;\n\n private final String dynamicConfigKey;\n\n private final ConcurrentMap nameMaps;\n\n public ServiceProvider(Class clazz, String dynamicConfigKey, String defaultName, ConcurrentMap nameMaps) {\n this.clazz = clazz;\n this.dynamicConfigKey = dynamicConfigKey;\n this.defaultName = defaultName;\n this.nameMaps = nameMaps;\n }\n }\n}\n"} {"task_id": "Java_1768", "language": "Java", "task_type": "if_statement", "source_file": "java/github/beihu-stack/beihu-boot/beihu-boot-project/beihu-boot-core/tools-beihu-boot/src/main/java/ltd/beihu/core/tools/spi/ServiceLoader.java", "mask_start_position": 1604, "mask_end_position": 1727, "canonical_solution": "if (StringUtils.isEmpty(name)) {\n // 加载默认的\n name = serviceProvider.defaultName;\n }", "pre_mask_code": "package ltd.beihu.core.tools.spi;\n\nimport ltd.beihu.core.tools.utils.Assert;\nimport ltd.beihu.core.tools.utils.IDUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class ServiceLoader {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ServiceLoader.class);\n\n private static final String LTS_DIRECTORY = \"META-INF/ceres/\";\n\n private static final String LTS_INTERNAL = \"internal\";\n\n private static final String LTS_INTERNAL_DIRECTORY = LTS_DIRECTORY + LTS_INTERNAL + \"/\";\n\n private static final String DEFAULT_IDENTITY = IDUtils.UUID();\n\n private static final ConcurrentMap, ServiceProvider> serviceMap = new ConcurrentHashMap, ServiceProvider>();\n\n private static final ConcurrentMap cachedObjectMap = new ConcurrentHashMap();\n\n public static T loadDefault(Class clazz) {\n return load(clazz, \"\");\n }\n\n public static T load(Class clazz, String name) {\n return load(clazz, name, DEFAULT_IDENTITY);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T load(Class clazz, String name, String identity) {\n try {\n ServiceProvider serviceProvider = getServiceProvider(clazz);\n ", "post_mask_code": "\n ServiceDefinition definition = serviceProvider.nameMaps.get(name);\n if (definition == null) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n // 用来保证每个节点都是一个各自的对象\n IdentityUniqueKey uniqueKey = new IdentityUniqueKey(identity, definition);\n Object obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n synchronized (definition) {\n obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n String className = definition.clazz;\n ClassLoader classLoader = definition.classLoader;\n T srv = clazz.cast(ClassLoaderUtil.newInstance(classLoader, className));\n cachedObjectMap.putIfAbsent(uniqueKey, srv);\n return srv;\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n }\n\n private static ServiceProvider getServiceProvider(Class clazz) {\n ServiceProvider serviceProvider = serviceMap.get(clazz);\n if (serviceProvider == null) {\n getServiceProviders(clazz);\n serviceProvider = serviceMap.get(clazz);\n }\n return serviceProvider;\n }\n\n public static Set getServiceProviders(final Class clazz) {\n if (clazz == null)\n throw new IllegalArgumentException(\"type == null\");\n if (!clazz.isInterface()) {\n throw new IllegalArgumentException(\" type(\" + clazz + \") is not interface!\");\n }\n if (!clazz.isAnnotationPresent(SPI.class)) {\n throw new IllegalArgumentException(\"type(\" + clazz + \") is not extension, because WITHOUT @\" + SPI.class.getSimpleName() + \" Annotation!\");\n }\n SPI spi = clazz.getAnnotation(SPI.class);\n String defaultName = spi.dftValue();\n String dynamicConfigKey = spi.key();\n final Set urlDefinitions = new HashSet();\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n urlDefinitions.addAll(collectExtensionUrls(LTS_DIRECTORY + clazz.getName(), classLoader));\n urlDefinitions.addAll(collectExtensionUrls(LTS_INTERNAL_DIRECTORY + clazz.getName(), classLoader));\n final ConcurrentMap serviceDefinitions = new ConcurrentHashMap();\n for (URLDefinition urlDefinition : urlDefinitions) {\n serviceDefinitions.putAll(parse(urlDefinition));\n }\n if (serviceDefinitions.isEmpty()) {\n throw new IllegalStateException(\"Service loader could not load \" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n ServiceProvider serviceProvider = new ServiceProvider(clazz, dynamicConfigKey, defaultName, serviceDefinitions);\n // 先移除\n serviceMap.remove(clazz);\n serviceMap.put(clazz, serviceProvider);\n return serviceDefinitions.keySet();\n }\n\n private static Map parse(URLDefinition urlDefinition) {\n final Map nameClassMap = new HashMap();\n try {\n BufferedReader r = null;\n try {\n URL url = urlDefinition.uri.toURL();\n r = new BufferedReader(new InputStreamReader(url.openStream(), \"UTF-8\"));\n while (true) {\n String line = r.readLine();\n if (line == null) {\n break;\n }\n int comment = line.indexOf('#');\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (line.length() == 0) {\n continue;\n }\n int i = line.indexOf('=');\n if (i > 0) {\n String name = line.substring(0, i).trim();\n String clazz = line.substring(i + 1).trim();\n nameClassMap.put(name, new ServiceDefinition(name, clazz, urlDefinition.classLoader));\n }\n }\n } finally {\n if (r != null) {\n r.close();\n }\n }\n } catch (Exception e) {\n LOGGER.error(\"parse \" + urlDefinition.uri + \" error:\" + e.getMessage(), e);\n }\n return nameClassMap;\n }\n\n private static Set collectExtensionUrls(String resourceName, ClassLoader classLoader) {\n try {\n final Enumeration configs;\n if (classLoader != null) {\n configs = classLoader.getResources(resourceName);\n } else {\n configs = ClassLoader.getSystemResources(resourceName);\n }\n Set urlDefinitions = new HashSet();\n while (configs.hasMoreElements()) {\n URL url = configs.nextElement();\n final URI uri = url.toURI();\n ClassLoader highestClassLoader = findHighestReachableClassLoader(url, classLoader, resourceName);\n urlDefinitions.add(new URLDefinition(uri, highestClassLoader));\n }\n return urlDefinitions;\n } catch (Exception e) {\n LOGGER.error(e.getMessage(), e);\n }\n return Collections.emptySet();\n }\n\n private static ClassLoader findHighestReachableClassLoader(URL url, ClassLoader classLoader, String resourceName) {\n if (classLoader.getParent() == null) {\n return classLoader;\n }\n ClassLoader highestClassLoader = classLoader;\n ClassLoader current = classLoader;\n while (current.getParent() != null) {\n ClassLoader parent = current.getParent();\n try {\n Enumeration resources = parent.getResources(resourceName);\n if (resources != null) {\n while (resources.hasMoreElements()) {\n URL resourceURL = resources.nextElement();\n if (url.toURI().equals(resourceURL.toURI())) {\n highestClassLoader = parent;\n }\n }\n }\n } catch (IOException ignore) {\n } catch (URISyntaxException ignore) {\n }\n current = current.getParent();\n }\n return highestClassLoader;\n }\n\n private static final class URLDefinition {\n\n private final URI uri;\n\n private final ClassLoader classLoader;\n\n private URLDefinition(URI url, ClassLoader classLoader) {\n this.uri = url;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n URLDefinition that = (URLDefinition) o;\n return uri != null ? uri.equals(that.uri) : that.uri == null;\n }\n\n @Override\n public int hashCode() {\n return uri != null ? uri.hashCode() : 0;\n }\n }\n\n private static final class ServiceDefinition {\n\n private final String name;\n\n private final String clazz;\n\n private final ClassLoader classLoader;\n\n private ServiceDefinition(String name, String clazz, ClassLoader classLoader) {\n Assert.notNull(name, \"name\");\n Assert.notNull(clazz, \"clazz\");\n Assert.notNull(classLoader, \"classLoader\");\n this.name = name;\n this.clazz = clazz;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ServiceDefinition that = (ServiceDefinition) o;\n if (name != null ? !name.equals(that.name) : that.name != null)\n return false;\n if (clazz != null ? !clazz.equals(that.clazz) : that.clazz != null)\n return false;\n return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;\n }\n\n @Override\n public int hashCode() {\n int result = name != null ? name.hashCode() : 0;\n result = 31 * result + (clazz != null ? clazz.hashCode() : 0);\n result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);\n return result;\n }\n }\n\n private static class IdentityUniqueKey {\n\n private String identity;\n\n private ServiceDefinition definition;\n\n public IdentityUniqueKey(String identity, ServiceDefinition definition) {\n this.identity = identity;\n this.definition = definition;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n IdentityUniqueKey that = (IdentityUniqueKey) o;\n if (identity != null ? !identity.equals(that.identity) : that.identity != null)\n return false;\n return definition != null ? definition.equals(that.definition) : that.definition == null;\n }\n\n @Override\n public int hashCode() {\n int result = identity != null ? identity.hashCode() : 0;\n result = 31 * result + (definition != null ? definition.hashCode() : 0);\n return result;\n }\n }\n\n private static final class ServiceProvider {\n\n private final Class clazz;\n\n private final String defaultName;\n\n private final String dynamicConfigKey;\n\n private final ConcurrentMap nameMaps;\n\n public ServiceProvider(Class clazz, String dynamicConfigKey, String defaultName, ConcurrentMap nameMaps) {\n this.clazz = clazz;\n this.dynamicConfigKey = dynamicConfigKey;\n this.defaultName = defaultName;\n this.nameMaps = nameMaps;\n }\n }\n}\n"} {"task_id": "Java_1769", "language": "Java", "task_type": "while_statement", "source_file": "java/github/beihu-stack/beihu-boot/beihu-boot-project/beihu-boot-core/tools-beihu-boot/src/main/java/ltd/beihu/core/tools/spi/ServiceLoader.java", "mask_start_position": 8376, "mask_end_position": 8656, "canonical_solution": "while (resources.hasMoreElements()) {\n URL resourceURL = resources.nextElement();\n if (url.toURI().equals(resourceURL.toURI())) {\n highestClassLoader = parent;\n }\n }", "pre_mask_code": "package ltd.beihu.core.tools.spi;\n\nimport ltd.beihu.core.tools.utils.Assert;\nimport ltd.beihu.core.tools.utils.IDUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class ServiceLoader {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ServiceLoader.class);\n\n private static final String LTS_DIRECTORY = \"META-INF/ceres/\";\n\n private static final String LTS_INTERNAL = \"internal\";\n\n private static final String LTS_INTERNAL_DIRECTORY = LTS_DIRECTORY + LTS_INTERNAL + \"/\";\n\n private static final String DEFAULT_IDENTITY = IDUtils.UUID();\n\n private static final ConcurrentMap, ServiceProvider> serviceMap = new ConcurrentHashMap, ServiceProvider>();\n\n private static final ConcurrentMap cachedObjectMap = new ConcurrentHashMap();\n\n public static T loadDefault(Class clazz) {\n return load(clazz, \"\");\n }\n\n public static T load(Class clazz, String name) {\n return load(clazz, name, DEFAULT_IDENTITY);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T load(Class clazz, String name, String identity) {\n try {\n ServiceProvider serviceProvider = getServiceProvider(clazz);\n if (StringUtils.isEmpty(name)) {\n // 加载默认的\n name = serviceProvider.defaultName;\n }\n ServiceDefinition definition = serviceProvider.nameMaps.get(name);\n if (definition == null) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n // 用来保证每个节点都是一个各自的对象\n IdentityUniqueKey uniqueKey = new IdentityUniqueKey(identity, definition);\n Object obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n synchronized (definition) {\n obj = cachedObjectMap.get(uniqueKey);\n if (obj != null) {\n return (T) obj;\n }\n String className = definition.clazz;\n ClassLoader classLoader = definition.classLoader;\n T srv = clazz.cast(ClassLoaderUtil.newInstance(classLoader, className));\n cachedObjectMap.putIfAbsent(uniqueKey, srv);\n return srv;\n }\n } catch (Exception e) {\n throw new IllegalStateException(\"Service loader could not load name:\" + name + \" class:\" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n }\n\n private static ServiceProvider getServiceProvider(Class clazz) {\n ServiceProvider serviceProvider = serviceMap.get(clazz);\n if (serviceProvider == null) {\n getServiceProviders(clazz);\n serviceProvider = serviceMap.get(clazz);\n }\n return serviceProvider;\n }\n\n public static Set getServiceProviders(final Class clazz) {\n if (clazz == null)\n throw new IllegalArgumentException(\"type == null\");\n if (!clazz.isInterface()) {\n throw new IllegalArgumentException(\" type(\" + clazz + \") is not interface!\");\n }\n if (!clazz.isAnnotationPresent(SPI.class)) {\n throw new IllegalArgumentException(\"type(\" + clazz + \") is not extension, because WITHOUT @\" + SPI.class.getSimpleName() + \" Annotation!\");\n }\n SPI spi = clazz.getAnnotation(SPI.class);\n String defaultName = spi.dftValue();\n String dynamicConfigKey = spi.key();\n final Set urlDefinitions = new HashSet();\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n urlDefinitions.addAll(collectExtensionUrls(LTS_DIRECTORY + clazz.getName(), classLoader));\n urlDefinitions.addAll(collectExtensionUrls(LTS_INTERNAL_DIRECTORY + clazz.getName(), classLoader));\n final ConcurrentMap serviceDefinitions = new ConcurrentHashMap();\n for (URLDefinition urlDefinition : urlDefinitions) {\n serviceDefinitions.putAll(parse(urlDefinition));\n }\n if (serviceDefinitions.isEmpty()) {\n throw new IllegalStateException(\"Service loader could not load \" + clazz.getName() + \"'s ServiceProvider from '\" + LTS_DIRECTORY + \"' or '\" + LTS_INTERNAL_DIRECTORY + \"' It may be empty or does not exist.\");\n }\n ServiceProvider serviceProvider = new ServiceProvider(clazz, dynamicConfigKey, defaultName, serviceDefinitions);\n // 先移除\n serviceMap.remove(clazz);\n serviceMap.put(clazz, serviceProvider);\n return serviceDefinitions.keySet();\n }\n\n private static Map parse(URLDefinition urlDefinition) {\n final Map nameClassMap = new HashMap();\n try {\n BufferedReader r = null;\n try {\n URL url = urlDefinition.uri.toURL();\n r = new BufferedReader(new InputStreamReader(url.openStream(), \"UTF-8\"));\n while (true) {\n String line = r.readLine();\n if (line == null) {\n break;\n }\n int comment = line.indexOf('#');\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (line.length() == 0) {\n continue;\n }\n int i = line.indexOf('=');\n if (i > 0) {\n String name = line.substring(0, i).trim();\n String clazz = line.substring(i + 1).trim();\n nameClassMap.put(name, new ServiceDefinition(name, clazz, urlDefinition.classLoader));\n }\n }\n } finally {\n if (r != null) {\n r.close();\n }\n }\n } catch (Exception e) {\n LOGGER.error(\"parse \" + urlDefinition.uri + \" error:\" + e.getMessage(), e);\n }\n return nameClassMap;\n }\n\n private static Set collectExtensionUrls(String resourceName, ClassLoader classLoader) {\n try {\n final Enumeration configs;\n if (classLoader != null) {\n configs = classLoader.getResources(resourceName);\n } else {\n configs = ClassLoader.getSystemResources(resourceName);\n }\n Set urlDefinitions = new HashSet();\n while (configs.hasMoreElements()) {\n URL url = configs.nextElement();\n final URI uri = url.toURI();\n ClassLoader highestClassLoader = findHighestReachableClassLoader(url, classLoader, resourceName);\n urlDefinitions.add(new URLDefinition(uri, highestClassLoader));\n }\n return urlDefinitions;\n } catch (Exception e) {\n LOGGER.error(e.getMessage(), e);\n }\n return Collections.emptySet();\n }\n\n private static ClassLoader findHighestReachableClassLoader(URL url, ClassLoader classLoader, String resourceName) {\n if (classLoader.getParent() == null) {\n return classLoader;\n }\n ClassLoader highestClassLoader = classLoader;\n ClassLoader current = classLoader;\n while (current.getParent() != null) {\n ClassLoader parent = current.getParent();\n try {\n Enumeration resources = parent.getResources(resourceName);\n if (resources != null) {\n ", "post_mask_code": "\n }\n } catch (IOException ignore) {\n } catch (URISyntaxException ignore) {\n }\n current = current.getParent();\n }\n return highestClassLoader;\n }\n\n private static final class URLDefinition {\n\n private final URI uri;\n\n private final ClassLoader classLoader;\n\n private URLDefinition(URI url, ClassLoader classLoader) {\n this.uri = url;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n URLDefinition that = (URLDefinition) o;\n return uri != null ? uri.equals(that.uri) : that.uri == null;\n }\n\n @Override\n public int hashCode() {\n return uri != null ? uri.hashCode() : 0;\n }\n }\n\n private static final class ServiceDefinition {\n\n private final String name;\n\n private final String clazz;\n\n private final ClassLoader classLoader;\n\n private ServiceDefinition(String name, String clazz, ClassLoader classLoader) {\n Assert.notNull(name, \"name\");\n Assert.notNull(clazz, \"clazz\");\n Assert.notNull(classLoader, \"classLoader\");\n this.name = name;\n this.clazz = clazz;\n this.classLoader = classLoader;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ServiceDefinition that = (ServiceDefinition) o;\n if (name != null ? !name.equals(that.name) : that.name != null)\n return false;\n if (clazz != null ? !clazz.equals(that.clazz) : that.clazz != null)\n return false;\n return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;\n }\n\n @Override\n public int hashCode() {\n int result = name != null ? name.hashCode() : 0;\n result = 31 * result + (clazz != null ? clazz.hashCode() : 0);\n result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);\n return result;\n }\n }\n\n private static class IdentityUniqueKey {\n\n private String identity;\n\n private ServiceDefinition definition;\n\n public IdentityUniqueKey(String identity, ServiceDefinition definition) {\n this.identity = identity;\n this.definition = definition;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n IdentityUniqueKey that = (IdentityUniqueKey) o;\n if (identity != null ? !identity.equals(that.identity) : that.identity != null)\n return false;\n return definition != null ? definition.equals(that.definition) : that.definition == null;\n }\n\n @Override\n public int hashCode() {\n int result = identity != null ? identity.hashCode() : 0;\n result = 31 * result + (definition != null ? definition.hashCode() : 0);\n return result;\n }\n }\n\n private static final class ServiceProvider {\n\n private final Class clazz;\n\n private final String defaultName;\n\n private final String dynamicConfigKey;\n\n private final ConcurrentMap nameMaps;\n\n public ServiceProvider(Class clazz, String dynamicConfigKey, String defaultName, ConcurrentMap nameMaps) {\n this.clazz = clazz;\n this.dynamicConfigKey = dynamicConfigKey;\n this.defaultName = defaultName;\n this.nameMaps = nameMaps;\n }\n }\n}\n"} {"task_id": "Java_1770", "language": "Java", "task_type": "method_signature", "source_file": "java/github/magefree/mage/Mage.Sets/src/mage/cards/g/GenerousPatron.java", "mask_start_position": 1710, "mask_end_position": 1782, "canonical_solution": "@Override\n public boolean checkEventType(GameEvent event, Game game) ", "pre_mask_code": "package mage.cards.g;\n\nimport mage.MageInt;\nimport mage.abilities.TriggeredAbilityImpl;\nimport mage.abilities.effects.common.DrawCardSourceControllerEffect;\nimport mage.abilities.keyword.SupportAbility;\nimport mage.cards.CardImpl;\nimport mage.cards.CardSetInfo;\nimport mage.constants.CardType;\nimport mage.constants.SubType;\nimport mage.constants.Zone;\nimport mage.game.Game;\nimport mage.game.events.GameEvent;\nimport mage.game.permanent.Permanent;\nimport java.util.UUID;\n\n/**\n * @author TheElk801\n */\npublic final class GenerousPatron extends CardImpl {\n\n public GenerousPatron(UUID ownerId, CardSetInfo setInfo) {\n super(ownerId, setInfo, new CardType[] { CardType.CREATURE }, \"{2}{G}\");\n this.subtype.add(SubType.ELF);\n this.subtype.add(SubType.ADVISOR);\n this.power = new MageInt(1);\n this.toughness = new MageInt(4);\n // When Generous Patron enters the battlefield, support 2. (Put a +1/+1 counter on each of up to two other target creatures.)\n this.addAbility(new SupportAbility(this, 2));\n // Whenever you put one or more counters on a creature you don't control, draw a card.\n this.addAbility(new GenerousPatronTriggeredAbility());\n }\n\n private GenerousPatron(final GenerousPatron card) {\n super(card);\n }\n\n @Override\n public GenerousPatron copy() {\n return new GenerousPatron(this);\n }\n}\n\nclass GenerousPatronTriggeredAbility extends TriggeredAbilityImpl {\n\n GenerousPatronTriggeredAbility() {\n super(Zone.BATTLEFIELD, new DrawCardSourceControllerEffect(1), false);\n }\n\n private GenerousPatronTriggeredAbility(GenerousPatronTriggeredAbility ability) {\n super(ability);\n }\n\n ", "post_mask_code": "{\n return event.getType() == GameEvent.EventType.COUNTERS_ADDED;\n }\n\n @Override\n public boolean checkTrigger(GameEvent event, Game game) {\n if (!isControlledBy(event.getPlayerId())) {\n return false;\n }\n Permanent permanent = game.getPermanentOrLKIBattlefield(event.getTargetId());\n if (permanent == null) {\n permanent = game.getPermanentEntering(event.getTargetId());\n }\n return permanent != null && permanent.isCreature(game) && !permanent.isControlledBy(getControllerId());\n }\n\n @Override\n public GenerousPatronTriggeredAbility copy() {\n return new GenerousPatronTriggeredAbility(this);\n }\n\n @Override\n public String getTriggerPhrase() {\n return \"Whenever you put one or more counters on a creature you don't control, \";\n }\n}\n"} {"task_id": "Java_1771", "language": "Java", "task_type": "method_body", "source_file": "java/github/magefree/mage/Mage.Sets/src/mage/cards/g/GenerousPatron.java", "mask_start_position": 1782, "mask_end_position": 1859, "canonical_solution": "{\n return event.getType() == GameEvent.EventType.COUNTERS_ADDED;\n }", "pre_mask_code": "package mage.cards.g;\n\nimport mage.MageInt;\nimport mage.abilities.TriggeredAbilityImpl;\nimport mage.abilities.effects.common.DrawCardSourceControllerEffect;\nimport mage.abilities.keyword.SupportAbility;\nimport mage.cards.CardImpl;\nimport mage.cards.CardSetInfo;\nimport mage.constants.CardType;\nimport mage.constants.SubType;\nimport mage.constants.Zone;\nimport mage.game.Game;\nimport mage.game.events.GameEvent;\nimport mage.game.permanent.Permanent;\nimport java.util.UUID;\n\n/**\n * @author TheElk801\n */\npublic final class GenerousPatron extends CardImpl {\n\n public GenerousPatron(UUID ownerId, CardSetInfo setInfo) {\n super(ownerId, setInfo, new CardType[] { CardType.CREATURE }, \"{2}{G}\");\n this.subtype.add(SubType.ELF);\n this.subtype.add(SubType.ADVISOR);\n this.power = new MageInt(1);\n this.toughness = new MageInt(4);\n // When Generous Patron enters the battlefield, support 2. (Put a +1/+1 counter on each of up to two other target creatures.)\n this.addAbility(new SupportAbility(this, 2));\n // Whenever you put one or more counters on a creature you don't control, draw a card.\n this.addAbility(new GenerousPatronTriggeredAbility());\n }\n\n private GenerousPatron(final GenerousPatron card) {\n super(card);\n }\n\n @Override\n public GenerousPatron copy() {\n return new GenerousPatron(this);\n }\n}\n\nclass GenerousPatronTriggeredAbility extends TriggeredAbilityImpl {\n\n GenerousPatronTriggeredAbility() {\n super(Zone.BATTLEFIELD, new DrawCardSourceControllerEffect(1), false);\n }\n\n private GenerousPatronTriggeredAbility(GenerousPatronTriggeredAbility ability) {\n super(ability);\n }\n\n @Override\n public boolean checkEventType(GameEvent event, Game game) ", "post_mask_code": "\n\n @Override\n public boolean checkTrigger(GameEvent event, Game game) {\n if (!isControlledBy(event.getPlayerId())) {\n return false;\n }\n Permanent permanent = game.getPermanentOrLKIBattlefield(event.getTargetId());\n if (permanent == null) {\n permanent = game.getPermanentEntering(event.getTargetId());\n }\n return permanent != null && permanent.isCreature(game) && !permanent.isControlledBy(getControllerId());\n }\n\n @Override\n public GenerousPatronTriggeredAbility copy() {\n return new GenerousPatronTriggeredAbility(this);\n }\n\n @Override\n public String getTriggerPhrase() {\n return \"Whenever you put one or more counters on a creature you don't control, \";\n }\n}\n"} {"task_id": "Java_1772", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/magefree/mage/Mage.Sets/src/mage/cards/g/GenerousPatron.java", "mask_start_position": 1936, "mask_end_position": 2024, "canonical_solution": "\n if (!isControlledBy(event.getPlayerId())) {\n return false;\n }", "pre_mask_code": "package mage.cards.g;\n\nimport mage.MageInt;\nimport mage.abilities.TriggeredAbilityImpl;\nimport mage.abilities.effects.common.DrawCardSourceControllerEffect;\nimport mage.abilities.keyword.SupportAbility;\nimport mage.cards.CardImpl;\nimport mage.cards.CardSetInfo;\nimport mage.constants.CardType;\nimport mage.constants.SubType;\nimport mage.constants.Zone;\nimport mage.game.Game;\nimport mage.game.events.GameEvent;\nimport mage.game.permanent.Permanent;\nimport java.util.UUID;\n\n/**\n * @author TheElk801\n */\npublic final class GenerousPatron extends CardImpl {\n\n public GenerousPatron(UUID ownerId, CardSetInfo setInfo) {\n super(ownerId, setInfo, new CardType[] { CardType.CREATURE }, \"{2}{G}\");\n this.subtype.add(SubType.ELF);\n this.subtype.add(SubType.ADVISOR);\n this.power = new MageInt(1);\n this.toughness = new MageInt(4);\n // When Generous Patron enters the battlefield, support 2. (Put a +1/+1 counter on each of up to two other target creatures.)\n this.addAbility(new SupportAbility(this, 2));\n // Whenever you put one or more counters on a creature you don't control, draw a card.\n this.addAbility(new GenerousPatronTriggeredAbility());\n }\n\n private GenerousPatron(final GenerousPatron card) {\n super(card);\n }\n\n @Override\n public GenerousPatron copy() {\n return new GenerousPatron(this);\n }\n}\n\nclass GenerousPatronTriggeredAbility extends TriggeredAbilityImpl {\n\n GenerousPatronTriggeredAbility() {\n super(Zone.BATTLEFIELD, new DrawCardSourceControllerEffect(1), false);\n }\n\n private GenerousPatronTriggeredAbility(GenerousPatronTriggeredAbility ability) {\n super(ability);\n }\n\n @Override\n public boolean checkEventType(GameEvent event, Game game) {\n return event.getType() == GameEvent.EventType.COUNTERS_ADDED;\n }\n\n @Override\n public boolean checkTrigger(GameEvent event, Game game) {", "post_mask_code": "\n Permanent permanent = game.getPermanentOrLKIBattlefield(event.getTargetId());\n if (permanent == null) {\n permanent = game.getPermanentEntering(event.getTargetId());\n }\n return permanent != null && permanent.isCreature(game) && !permanent.isControlledBy(getControllerId());\n }\n\n @Override\n public GenerousPatronTriggeredAbility copy() {\n return new GenerousPatronTriggeredAbility(this);\n }\n\n @Override\n public String getTriggerPhrase() {\n return \"Whenever you put one or more counters on a creature you don't control, \";\n }\n}\n"} {"task_id": "Java_1773", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/magefree/mage/Mage.Sets/src/mage/cards/g/GenerousPatron.java", "mask_start_position": 2033, "mask_end_position": 2225, "canonical_solution": "Permanent permanent = game.getPermanentOrLKIBattlefield(event.getTargetId());\n if (permanent == null) {\n permanent = game.getPermanentEntering(event.getTargetId());\n }", "pre_mask_code": "package mage.cards.g;\n\nimport mage.MageInt;\nimport mage.abilities.TriggeredAbilityImpl;\nimport mage.abilities.effects.common.DrawCardSourceControllerEffect;\nimport mage.abilities.keyword.SupportAbility;\nimport mage.cards.CardImpl;\nimport mage.cards.CardSetInfo;\nimport mage.constants.CardType;\nimport mage.constants.SubType;\nimport mage.constants.Zone;\nimport mage.game.Game;\nimport mage.game.events.GameEvent;\nimport mage.game.permanent.Permanent;\nimport java.util.UUID;\n\n/**\n * @author TheElk801\n */\npublic final class GenerousPatron extends CardImpl {\n\n public GenerousPatron(UUID ownerId, CardSetInfo setInfo) {\n super(ownerId, setInfo, new CardType[] { CardType.CREATURE }, \"{2}{G}\");\n this.subtype.add(SubType.ELF);\n this.subtype.add(SubType.ADVISOR);\n this.power = new MageInt(1);\n this.toughness = new MageInt(4);\n // When Generous Patron enters the battlefield, support 2. (Put a +1/+1 counter on each of up to two other target creatures.)\n this.addAbility(new SupportAbility(this, 2));\n // Whenever you put one or more counters on a creature you don't control, draw a card.\n this.addAbility(new GenerousPatronTriggeredAbility());\n }\n\n private GenerousPatron(final GenerousPatron card) {\n super(card);\n }\n\n @Override\n public GenerousPatron copy() {\n return new GenerousPatron(this);\n }\n}\n\nclass GenerousPatronTriggeredAbility extends TriggeredAbilityImpl {\n\n GenerousPatronTriggeredAbility() {\n super(Zone.BATTLEFIELD, new DrawCardSourceControllerEffect(1), false);\n }\n\n private GenerousPatronTriggeredAbility(GenerousPatronTriggeredAbility ability) {\n super(ability);\n }\n\n @Override\n public boolean checkEventType(GameEvent event, Game game) {\n return event.getType() == GameEvent.EventType.COUNTERS_ADDED;\n }\n\n @Override\n public boolean checkTrigger(GameEvent event, Game game) {\n if (!isControlledBy(event.getPlayerId())) {\n return false;\n }\n ", "post_mask_code": "\n return permanent != null && permanent.isCreature(game) && !permanent.isControlledBy(getControllerId());\n }\n\n @Override\n public GenerousPatronTriggeredAbility copy() {\n return new GenerousPatronTriggeredAbility(this);\n }\n\n @Override\n public String getTriggerPhrase() {\n return \"Whenever you put one or more counters on a creature you don't control, \";\n }\n}\n"} {"task_id": "Java_1774", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/magefree/mage/Mage.Sets/src/mage/cards/g/GenerousPatron.java", "mask_start_position": 2234, "mask_end_position": 2343, "canonical_solution": "return permanent != null && permanent.isCreature(game) && !permanent.isControlledBy(getControllerId());\n }", "pre_mask_code": "package mage.cards.g;\n\nimport mage.MageInt;\nimport mage.abilities.TriggeredAbilityImpl;\nimport mage.abilities.effects.common.DrawCardSourceControllerEffect;\nimport mage.abilities.keyword.SupportAbility;\nimport mage.cards.CardImpl;\nimport mage.cards.CardSetInfo;\nimport mage.constants.CardType;\nimport mage.constants.SubType;\nimport mage.constants.Zone;\nimport mage.game.Game;\nimport mage.game.events.GameEvent;\nimport mage.game.permanent.Permanent;\nimport java.util.UUID;\n\n/**\n * @author TheElk801\n */\npublic final class GenerousPatron extends CardImpl {\n\n public GenerousPatron(UUID ownerId, CardSetInfo setInfo) {\n super(ownerId, setInfo, new CardType[] { CardType.CREATURE }, \"{2}{G}\");\n this.subtype.add(SubType.ELF);\n this.subtype.add(SubType.ADVISOR);\n this.power = new MageInt(1);\n this.toughness = new MageInt(4);\n // When Generous Patron enters the battlefield, support 2. (Put a +1/+1 counter on each of up to two other target creatures.)\n this.addAbility(new SupportAbility(this, 2));\n // Whenever you put one or more counters on a creature you don't control, draw a card.\n this.addAbility(new GenerousPatronTriggeredAbility());\n }\n\n private GenerousPatron(final GenerousPatron card) {\n super(card);\n }\n\n @Override\n public GenerousPatron copy() {\n return new GenerousPatron(this);\n }\n}\n\nclass GenerousPatronTriggeredAbility extends TriggeredAbilityImpl {\n\n GenerousPatronTriggeredAbility() {\n super(Zone.BATTLEFIELD, new DrawCardSourceControllerEffect(1), false);\n }\n\n private GenerousPatronTriggeredAbility(GenerousPatronTriggeredAbility ability) {\n super(ability);\n }\n\n @Override\n public boolean checkEventType(GameEvent event, Game game) {\n return event.getType() == GameEvent.EventType.COUNTERS_ADDED;\n }\n\n @Override\n public boolean checkTrigger(GameEvent event, Game game) {\n if (!isControlledBy(event.getPlayerId())) {\n return false;\n }\n Permanent permanent = game.getPermanentOrLKIBattlefield(event.getTargetId());\n if (permanent == null) {\n permanent = game.getPermanentEntering(event.getTargetId());\n }\n ", "post_mask_code": "\n\n @Override\n public GenerousPatronTriggeredAbility copy() {\n return new GenerousPatronTriggeredAbility(this);\n }\n\n @Override\n public String getTriggerPhrase() {\n return \"Whenever you put one or more counters on a creature you don't control, \";\n }\n}\n"} {"task_id": "Java_1775", "language": "Java", "task_type": "single_line", "source_file": "java/github/magefree/mage/Mage.Sets/src/mage/cards/g/GenerousPatron.java", "mask_start_position": 2458, "mask_end_position": 2466, "canonical_solution": "y(this);", "pre_mask_code": "package mage.cards.g;\n\nimport mage.MageInt;\nimport mage.abilities.TriggeredAbilityImpl;\nimport mage.abilities.effects.common.DrawCardSourceControllerEffect;\nimport mage.abilities.keyword.SupportAbility;\nimport mage.cards.CardImpl;\nimport mage.cards.CardSetInfo;\nimport mage.constants.CardType;\nimport mage.constants.SubType;\nimport mage.constants.Zone;\nimport mage.game.Game;\nimport mage.game.events.GameEvent;\nimport mage.game.permanent.Permanent;\nimport java.util.UUID;\n\n/**\n * @author TheElk801\n */\npublic final class GenerousPatron extends CardImpl {\n\n public GenerousPatron(UUID ownerId, CardSetInfo setInfo) {\n super(ownerId, setInfo, new CardType[] { CardType.CREATURE }, \"{2}{G}\");\n this.subtype.add(SubType.ELF);\n this.subtype.add(SubType.ADVISOR);\n this.power = new MageInt(1);\n this.toughness = new MageInt(4);\n // When Generous Patron enters the battlefield, support 2. (Put a +1/+1 counter on each of up to two other target creatures.)\n this.addAbility(new SupportAbility(this, 2));\n // Whenever you put one or more counters on a creature you don't control, draw a card.\n this.addAbility(new GenerousPatronTriggeredAbility());\n }\n\n private GenerousPatron(final GenerousPatron card) {\n super(card);\n }\n\n @Override\n public GenerousPatron copy() {\n return new GenerousPatron(this);\n }\n}\n\nclass GenerousPatronTriggeredAbility extends TriggeredAbilityImpl {\n\n GenerousPatronTriggeredAbility() {\n super(Zone.BATTLEFIELD, new DrawCardSourceControllerEffect(1), false);\n }\n\n private GenerousPatronTriggeredAbility(GenerousPatronTriggeredAbility ability) {\n super(ability);\n }\n\n @Override\n public boolean checkEventType(GameEvent event, Game game) {\n return event.getType() == GameEvent.EventType.COUNTERS_ADDED;\n }\n\n @Override\n public boolean checkTrigger(GameEvent event, Game game) {\n if (!isControlledBy(event.getPlayerId())) {\n return false;\n }\n Permanent permanent = game.getPermanentOrLKIBattlefield(event.getTargetId());\n if (permanent == null) {\n permanent = game.getPermanentEntering(event.getTargetId());\n }\n return permanent != null && permanent.isCreature(game) && !permanent.isControlledBy(getControllerId());\n }\n\n @Override\n public GenerousPatronTriggeredAbility copy() {\n return new GenerousPatronTriggeredAbilit", "post_mask_code": "\n }\n\n @Override\n public String getTriggerPhrase() {\n return \"Whenever you put one or more counters on a creature you don't control, \";\n }\n}\n"} {"task_id": "Java_1776", "language": "Java", "task_type": "if_statement", "source_file": "java/github/magefree/mage/Mage.Sets/src/mage/cards/g/GenerousPatron.java", "mask_start_position": 2119, "mask_end_position": 2225, "canonical_solution": "if (permanent == null) {\n permanent = game.getPermanentEntering(event.getTargetId());\n }", "pre_mask_code": "package mage.cards.g;\n\nimport mage.MageInt;\nimport mage.abilities.TriggeredAbilityImpl;\nimport mage.abilities.effects.common.DrawCardSourceControllerEffect;\nimport mage.abilities.keyword.SupportAbility;\nimport mage.cards.CardImpl;\nimport mage.cards.CardSetInfo;\nimport mage.constants.CardType;\nimport mage.constants.SubType;\nimport mage.constants.Zone;\nimport mage.game.Game;\nimport mage.game.events.GameEvent;\nimport mage.game.permanent.Permanent;\nimport java.util.UUID;\n\n/**\n * @author TheElk801\n */\npublic final class GenerousPatron extends CardImpl {\n\n public GenerousPatron(UUID ownerId, CardSetInfo setInfo) {\n super(ownerId, setInfo, new CardType[] { CardType.CREATURE }, \"{2}{G}\");\n this.subtype.add(SubType.ELF);\n this.subtype.add(SubType.ADVISOR);\n this.power = new MageInt(1);\n this.toughness = new MageInt(4);\n // When Generous Patron enters the battlefield, support 2. (Put a +1/+1 counter on each of up to two other target creatures.)\n this.addAbility(new SupportAbility(this, 2));\n // Whenever you put one or more counters on a creature you don't control, draw a card.\n this.addAbility(new GenerousPatronTriggeredAbility());\n }\n\n private GenerousPatron(final GenerousPatron card) {\n super(card);\n }\n\n @Override\n public GenerousPatron copy() {\n return new GenerousPatron(this);\n }\n}\n\nclass GenerousPatronTriggeredAbility extends TriggeredAbilityImpl {\n\n GenerousPatronTriggeredAbility() {\n super(Zone.BATTLEFIELD, new DrawCardSourceControllerEffect(1), false);\n }\n\n private GenerousPatronTriggeredAbility(GenerousPatronTriggeredAbility ability) {\n super(ability);\n }\n\n @Override\n public boolean checkEventType(GameEvent event, Game game) {\n return event.getType() == GameEvent.EventType.COUNTERS_ADDED;\n }\n\n @Override\n public boolean checkTrigger(GameEvent event, Game game) {\n if (!isControlledBy(event.getPlayerId())) {\n return false;\n }\n Permanent permanent = game.getPermanentOrLKIBattlefield(event.getTargetId());\n ", "post_mask_code": "\n return permanent != null && permanent.isCreature(game) && !permanent.isControlledBy(getControllerId());\n }\n\n @Override\n public GenerousPatronTriggeredAbility copy() {\n return new GenerousPatronTriggeredAbility(this);\n }\n\n @Override\n public String getTriggerPhrase() {\n return \"Whenever you put one or more counters on a creature you don't control, \";\n }\n}\n"} {"task_id": "Java_1777", "language": "Java", "task_type": "method_signature", "source_file": "java/github/microg/android_external_GmsApi/play-services-basement/src/main/java/com/google/android/gms/common/internal/GetServiceRequest.java", "mask_start_position": 1175, "mask_end_position": 1214, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "package com.google.android.gms.common.internal;\n\nimport android.accounts.Account;\nimport android.os.Bundle;\nimport android.os.IBinder;\nimport com.google.android.gms.common.api.Scope;\nimport org.microg.gms.common.Constants;\nimport org.microg.gms.common.GmsService;\nimport org.microg.safeparcel.AutoSafeParcelable;\nimport org.microg.safeparcel.SafeParceled;\nimport java.util.Arrays;\n\npublic class GetServiceRequest extends AutoSafeParcelable {\n\n @SafeParceled(1)\n private int versionCode = 3;\n\n @SafeParceled(2)\n public final int serviceId;\n\n @SafeParceled(3)\n public int gmsVersion;\n\n @SafeParceled(4)\n public String packageName;\n\n @SafeParceled(5)\n public IBinder accountAccessor;\n\n @SafeParceled(6)\n public Scope[] scopes;\n\n @SafeParceled(7)\n public Bundle extras;\n\n @SafeParceled(8)\n public Account account;\n\n @SafeParceled(9)\n public long long1;\n\n private GetServiceRequest() {\n serviceId = -1;\n gmsVersion = Constants.MAX_REFERENCE_VERSION;\n }\n\n public GetServiceRequest(int serviceId) {\n this.serviceId = serviceId;\n this.gmsVersion = Constants.MAX_REFERENCE_VERSION;\n }\n\n ", "post_mask_code": "{\n return \"GetServiceRequest{\" + \"serviceId=\" + GmsService.nameFromServiceId(serviceId) + \", gmsVersion=\" + gmsVersion + \", packageName='\" + packageName + '\\'' + (scopes == null || scopes.length == 0 ? \"\" : (\", scopes=\" + Arrays.toString(scopes))) + (extras == null ? \"\" : (\", extras=\" + extras)) + (account == null ? \"\" : (\", account=\" + account)) + '}';\n }\n\n public static Creator CREATOR = new AutoCreator(GetServiceRequest.class);\n}\n"} {"task_id": "Java_1778", "language": "Java", "task_type": "method_body", "source_file": "java/github/microg/android_external_GmsApi/play-services-basement/src/main/java/com/google/android/gms/common/internal/GetServiceRequest.java", "mask_start_position": 1214, "mask_end_position": 1582, "canonical_solution": "{\n return \"GetServiceRequest{\" + \"serviceId=\" + GmsService.nameFromServiceId(serviceId) + \", gmsVersion=\" + gmsVersion + \", packageName='\" + packageName + '\\'' + (scopes == null || scopes.length == 0 ? \"\" : (\", scopes=\" + Arrays.toString(scopes))) + (extras == null ? \"\" : (\", extras=\" + extras)) + (account == null ? \"\" : (\", account=\" + account)) + '}';\n }", "pre_mask_code": "package com.google.android.gms.common.internal;\n\nimport android.accounts.Account;\nimport android.os.Bundle;\nimport android.os.IBinder;\nimport com.google.android.gms.common.api.Scope;\nimport org.microg.gms.common.Constants;\nimport org.microg.gms.common.GmsService;\nimport org.microg.safeparcel.AutoSafeParcelable;\nimport org.microg.safeparcel.SafeParceled;\nimport java.util.Arrays;\n\npublic class GetServiceRequest extends AutoSafeParcelable {\n\n @SafeParceled(1)\n private int versionCode = 3;\n\n @SafeParceled(2)\n public final int serviceId;\n\n @SafeParceled(3)\n public int gmsVersion;\n\n @SafeParceled(4)\n public String packageName;\n\n @SafeParceled(5)\n public IBinder accountAccessor;\n\n @SafeParceled(6)\n public Scope[] scopes;\n\n @SafeParceled(7)\n public Bundle extras;\n\n @SafeParceled(8)\n public Account account;\n\n @SafeParceled(9)\n public long long1;\n\n private GetServiceRequest() {\n serviceId = -1;\n gmsVersion = Constants.MAX_REFERENCE_VERSION;\n }\n\n public GetServiceRequest(int serviceId) {\n this.serviceId = serviceId;\n this.gmsVersion = Constants.MAX_REFERENCE_VERSION;\n }\n\n @Override\n public String toString() ", "post_mask_code": "\n\n public static Creator CREATOR = new AutoCreator(GetServiceRequest.class);\n}\n"} {"task_id": "Java_1779", "language": "Java", "task_type": "single_line", "source_file": "java/github/microg/android_external_GmsApi/play-services-basement/src/main/java/com/google/android/gms/common/internal/GetServiceRequest.java", "mask_start_position": 1332, "mask_end_position": 1576, "canonical_solution": "Version + \", packageName='\" + packageName + '\\'' + (scopes == null || scopes.length == 0 ? \"\" : (\", scopes=\" + Arrays.toString(scopes))) + (extras == null ? \"\" : (\", extras=\" + extras)) + (account == null ? \"\" : (\", account=\" + account)) + '}';", "pre_mask_code": "package com.google.android.gms.common.internal;\n\nimport android.accounts.Account;\nimport android.os.Bundle;\nimport android.os.IBinder;\nimport com.google.android.gms.common.api.Scope;\nimport org.microg.gms.common.Constants;\nimport org.microg.gms.common.GmsService;\nimport org.microg.safeparcel.AutoSafeParcelable;\nimport org.microg.safeparcel.SafeParceled;\nimport java.util.Arrays;\n\npublic class GetServiceRequest extends AutoSafeParcelable {\n\n @SafeParceled(1)\n private int versionCode = 3;\n\n @SafeParceled(2)\n public final int serviceId;\n\n @SafeParceled(3)\n public int gmsVersion;\n\n @SafeParceled(4)\n public String packageName;\n\n @SafeParceled(5)\n public IBinder accountAccessor;\n\n @SafeParceled(6)\n public Scope[] scopes;\n\n @SafeParceled(7)\n public Bundle extras;\n\n @SafeParceled(8)\n public Account account;\n\n @SafeParceled(9)\n public long long1;\n\n private GetServiceRequest() {\n serviceId = -1;\n gmsVersion = Constants.MAX_REFERENCE_VERSION;\n }\n\n public GetServiceRequest(int serviceId) {\n this.serviceId = serviceId;\n this.gmsVersion = Constants.MAX_REFERENCE_VERSION;\n }\n\n @Override\n public String toString() {\n return \"GetServiceRequest{\" + \"serviceId=\" + GmsService.nameFromServiceId(serviceId) + \", gmsVersion=\" + gms", "post_mask_code": "\n }\n\n public static Creator CREATOR = new AutoCreator(GetServiceRequest.class);\n}\n"} {"task_id": "Java_1780", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/mem/UnsafeChunk.java", "mask_start_position": 931, "mask_end_position": 970, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "package org.apache.ignite.internal.mem;\n\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\n\npublic class UnsafeChunk implements DirectMemoryRegion {\n\n private long ptr;\n\n private long len;\n\n /**\n * @param ptr Pointer to the memory start.\n * @param len Memory length.\n */\n public UnsafeChunk(long ptr, long len) {\n this.ptr = ptr;\n this.len = len;\n }\n\n @Override\n public long address() {\n return ptr;\n }\n\n @Override\n public long size() {\n return len;\n }\n\n @Override\n public DirectMemoryRegion slice(long offset) {\n if (offset < 0 || offset >= len)\n throw new IllegalArgumentException(\"Failed to create a memory region slice [ptr=\" + U.hexLong(ptr) + \", len=\" + len + \", offset=\" + offset + ']');\n return new UnsafeChunk(ptr + offset, len - offset);\n }\n\n ", "post_mask_code": "{\n return S.toString(UnsafeChunk.class, this);\n }\n}\n"} {"task_id": "Java_1781", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/mem/UnsafeChunk.java", "mask_start_position": 658, "mask_end_position": 925, "canonical_solution": "{\n if (offset < 0 || offset >= len)\n throw new IllegalArgumentException(\"Failed to create a memory region slice [ptr=\" + U.hexLong(ptr) + \", len=\" + len + \", offset=\" + offset + ']');\n return new UnsafeChunk(ptr + offset, len - offset);\n }", "pre_mask_code": "package org.apache.ignite.internal.mem;\n\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\n\npublic class UnsafeChunk implements DirectMemoryRegion {\n\n private long ptr;\n\n private long len;\n\n /**\n * @param ptr Pointer to the memory start.\n * @param len Memory length.\n */\n public UnsafeChunk(long ptr, long len) {\n this.ptr = ptr;\n this.len = len;\n }\n\n @Override\n public long address() {\n return ptr;\n }\n\n @Override\n public long size() {\n return len;\n }\n\n @Override\n public DirectMemoryRegion slice(long offset) ", "post_mask_code": "\n\n @Override\n public String toString() {\n return S.toString(UnsafeChunk.class, this);\n }\n}\n"} {"task_id": "Java_1782", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/mem/UnsafeChunk.java", "mask_start_position": 900, "mask_end_position": 919, "canonical_solution": "set, len - offset);", "pre_mask_code": "package org.apache.ignite.internal.mem;\n\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\n\npublic class UnsafeChunk implements DirectMemoryRegion {\n\n private long ptr;\n\n private long len;\n\n /**\n * @param ptr Pointer to the memory start.\n * @param len Memory length.\n */\n public UnsafeChunk(long ptr, long len) {\n this.ptr = ptr;\n this.len = len;\n }\n\n @Override\n public long address() {\n return ptr;\n }\n\n @Override\n public long size() {\n return len;\n }\n\n @Override\n public DirectMemoryRegion slice(long offset) {\n if (offset < 0 || offset >= len)\n throw new IllegalArgumentException(\"Failed to create a memory region slice [ptr=\" + U.hexLong(ptr) + \", len=\" + len + \", offset=\" + offset + ']');\n return new UnsafeChunk(ptr + off", "post_mask_code": "\n }\n\n @Override\n public String toString() {\n return S.toString(UnsafeChunk.class, this);\n }\n}\n"} {"task_id": "Java_1783", "language": "Java", "task_type": "if_statement", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/mem/UnsafeChunk.java", "mask_start_position": 668, "mask_end_position": 859, "canonical_solution": "if (offset < 0 || offset >= len)\n throw new IllegalArgumentException(\"Failed to create a memory region slice [ptr=\" + U.hexLong(ptr) + \", len=\" + len + \", offset=\" + offset + ']');", "pre_mask_code": "package org.apache.ignite.internal.mem;\n\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\n\npublic class UnsafeChunk implements DirectMemoryRegion {\n\n private long ptr;\n\n private long len;\n\n /**\n * @param ptr Pointer to the memory start.\n * @param len Memory length.\n */\n public UnsafeChunk(long ptr, long len) {\n this.ptr = ptr;\n this.len = len;\n }\n\n @Override\n public long address() {\n return ptr;\n }\n\n @Override\n public long size() {\n return len;\n }\n\n @Override\n public DirectMemoryRegion slice(long offset) {\n ", "post_mask_code": "\n return new UnsafeChunk(ptr + offset, len - offset);\n }\n\n @Override\n public String toString() {\n return S.toString(UnsafeChunk.class, this);\n }\n}\n"} {"task_id": "Java_1784", "language": "Java", "task_type": "method_signature", "source_file": "java/github/alexcheng1982/happyride/happyride-passenger-service/src/main/java/io/vividcode/happyride/passengerservice/messagehandlers/PassengerServiceMessageHandlersConfiguration.java", "mask_start_position": 1098, "mask_end_position": 1301, "canonical_solution": "@Bean\n public DomainEventDispatcher passengerServiceEventDispatcher(final PassengerServiceEventConsumer passengerServiceEventConsumer, final DomainEventDispatcherFactory domainEventDispatcherFactory) ", "pre_mask_code": "package io.vividcode.happyride.passengerservice.messagehandlers;\n\nimport io.eventuate.tram.consumer.common.DuplicateMessageDetector;\nimport io.eventuate.tram.consumer.common.NoopDuplicateMessageDetector;\nimport io.eventuate.tram.events.subscriber.DomainEventDispatcher;\nimport io.eventuate.tram.events.subscriber.DomainEventDispatcherFactory;\nimport io.eventuate.tram.spring.events.publisher.TramEventsPublisherConfiguration;\nimport io.eventuate.tram.spring.events.subscriber.TramEventSubscriberConfiguration;\nimport io.eventuate.tram.spring.jdbckafka.TramJdbcKafkaConfiguration;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Import;\n\n@Configuration\n@Import({ TramJdbcKafkaConfiguration.class, TramEventsPublisherConfiguration.class, TramEventSubscriberConfiguration.class })\npublic class PassengerServiceMessageHandlersConfiguration {\n\n @Bean\n public PassengerServiceEventConsumer passengerServiceEventConsumer() {\n return new PassengerServiceEventConsumer();\n }\n\n ", "post_mask_code": "{\n return domainEventDispatcherFactory.make(\"passengerServiceEvents\", passengerServiceEventConsumer.domainEventHandlers());\n }\n\n @Bean\n public DuplicateMessageDetector duplicateMessageDetector() {\n return new NoopDuplicateMessageDetector();\n }\n}\n"} {"task_id": "Java_1785", "language": "Java", "task_type": "method_body", "source_file": "java/github/alexcheng1982/happyride/happyride-passenger-service/src/main/java/io/vividcode/happyride/passengerservice/messagehandlers/PassengerServiceMessageHandlersConfiguration.java", "mask_start_position": 1301, "mask_end_position": 1437, "canonical_solution": "{\n return domainEventDispatcherFactory.make(\"passengerServiceEvents\", passengerServiceEventConsumer.domainEventHandlers());\n }", "pre_mask_code": "package io.vividcode.happyride.passengerservice.messagehandlers;\n\nimport io.eventuate.tram.consumer.common.DuplicateMessageDetector;\nimport io.eventuate.tram.consumer.common.NoopDuplicateMessageDetector;\nimport io.eventuate.tram.events.subscriber.DomainEventDispatcher;\nimport io.eventuate.tram.events.subscriber.DomainEventDispatcherFactory;\nimport io.eventuate.tram.spring.events.publisher.TramEventsPublisherConfiguration;\nimport io.eventuate.tram.spring.events.subscriber.TramEventSubscriberConfiguration;\nimport io.eventuate.tram.spring.jdbckafka.TramJdbcKafkaConfiguration;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Import;\n\n@Configuration\n@Import({ TramJdbcKafkaConfiguration.class, TramEventsPublisherConfiguration.class, TramEventSubscriberConfiguration.class })\npublic class PassengerServiceMessageHandlersConfiguration {\n\n @Bean\n public PassengerServiceEventConsumer passengerServiceEventConsumer() {\n return new PassengerServiceEventConsumer();\n }\n\n @Bean\n public DomainEventDispatcher passengerServiceEventDispatcher(final PassengerServiceEventConsumer passengerServiceEventConsumer, final DomainEventDispatcherFactory domainEventDispatcherFactory) ", "post_mask_code": "\n\n @Bean\n public DuplicateMessageDetector duplicateMessageDetector() {\n return new NoopDuplicateMessageDetector();\n }\n}\n"} {"task_id": "Java_1786", "language": "Java", "task_type": "single_line", "source_file": "java/github/alexcheng1982/happyride/happyride-passenger-service/src/main/java/io/vividcode/happyride/passengerservice/messagehandlers/PassengerServiceMessageHandlersConfiguration.java", "mask_start_position": 1535, "mask_end_position": 1564, "canonical_solution": "opDuplicateMessageDetector();", "pre_mask_code": "package io.vividcode.happyride.passengerservice.messagehandlers;\n\nimport io.eventuate.tram.consumer.common.DuplicateMessageDetector;\nimport io.eventuate.tram.consumer.common.NoopDuplicateMessageDetector;\nimport io.eventuate.tram.events.subscriber.DomainEventDispatcher;\nimport io.eventuate.tram.events.subscriber.DomainEventDispatcherFactory;\nimport io.eventuate.tram.spring.events.publisher.TramEventsPublisherConfiguration;\nimport io.eventuate.tram.spring.events.subscriber.TramEventSubscriberConfiguration;\nimport io.eventuate.tram.spring.jdbckafka.TramJdbcKafkaConfiguration;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Import;\n\n@Configuration\n@Import({ TramJdbcKafkaConfiguration.class, TramEventsPublisherConfiguration.class, TramEventSubscriberConfiguration.class })\npublic class PassengerServiceMessageHandlersConfiguration {\n\n @Bean\n public PassengerServiceEventConsumer passengerServiceEventConsumer() {\n return new PassengerServiceEventConsumer();\n }\n\n @Bean\n public DomainEventDispatcher passengerServiceEventDispatcher(final PassengerServiceEventConsumer passengerServiceEventConsumer, final DomainEventDispatcherFactory domainEventDispatcherFactory) {\n return domainEventDispatcherFactory.make(\"passengerServiceEvents\", passengerServiceEventConsumer.domainEventHandlers());\n }\n\n @Bean\n public DuplicateMessageDetector duplicateMessageDetector() {\n return new No", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1787", "language": "Java", "task_type": "method_signature", "source_file": "java/github/PacktPublishing/The-Complete-Coding-Interview-Guide-in-Java/Chapter13/BinaryTreeIsBST/src/main/java/coding/challenge/Main.java", "mask_start_position": 52, "mask_end_position": 91, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "package coding.challenge;\n\npublic class Main {\n\n ", "post_mask_code": "{\n /* This tree is BST \n 40\n / \\\n 35 45\n / \\ / \\ \n 30 37 44 48 \n /\n 20 \n */\n BinaryTree bt = new BinaryTree<>();\n bt.insert(40);\n bt.insert(35);\n bt.insert(45);\n bt.insert(30);\n bt.insert(37);\n bt.insert(44);\n bt.insert(48);\n bt.insert(20);\n System.out.println(\"\\n\\nTraversal LEVEL: \");\n bt.print();\n System.out.println(\"\\n\\nIs this binary tree BST: \" + bt.isBinarySearchTree());\n }\n}\n"} {"task_id": "Java_1788", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/PacktPublishing/The-Complete-Coding-Interview-Guide-in-Java/Chapter13/BinaryTreeIsBST/src/main/java/coding/challenge/Main.java", "mask_start_position": 92, "mask_end_position": 362, "canonical_solution": "\n /* This tree is BST \n 40\n / \\\n 35 45\n / \\ / \\ \n 30 37 44 48 \n /\n 20 \n */\n BinaryTree bt = new BinaryTree<>();\n bt.insert(40);\n bt.insert(35);", "pre_mask_code": "package coding.challenge;\n\npublic class Main {\n\n public static void main(String[] args) {", "post_mask_code": "\n bt.insert(45);\n bt.insert(30);\n bt.insert(37);\n bt.insert(44);\n bt.insert(48);\n bt.insert(20);\n System.out.println(\"\\n\\nTraversal LEVEL: \");\n bt.print();\n System.out.println(\"\\n\\nIs this binary tree BST: \" + bt.isBinarySearchTree());\n }\n}\n"} {"task_id": "Java_1789", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/PacktPublishing/The-Complete-Coding-Interview-Guide-in-Java/Chapter13/BinaryTreeIsBST/src/main/java/coding/challenge/Main.java", "mask_start_position": 371, "mask_end_position": 477, "canonical_solution": "bt.insert(45);\n bt.insert(30);\n bt.insert(37);\n bt.insert(44);\n bt.insert(48);", "pre_mask_code": "package coding.challenge;\n\npublic class Main {\n\n public static void main(String[] args) {\n /* This tree is BST \n 40\n / \\\n 35 45\n / \\ / \\ \n 30 37 44 48 \n /\n 20 \n */\n BinaryTree bt = new BinaryTree<>();\n bt.insert(40);\n bt.insert(35);\n ", "post_mask_code": "\n bt.insert(20);\n System.out.println(\"\\n\\nTraversal LEVEL: \");\n bt.print();\n System.out.println(\"\\n\\nIs this binary tree BST: \" + bt.isBinarySearchTree());\n }\n}\n"} {"task_id": "Java_1790", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/PacktPublishing/The-Complete-Coding-Interview-Guide-in-Java/Chapter13/BinaryTreeIsBST/src/main/java/coding/challenge/Main.java", "mask_start_position": 486, "mask_end_position": 666, "canonical_solution": "bt.insert(20);\n System.out.println(\"\\n\\nTraversal LEVEL: \");\n bt.print();\n System.out.println(\"\\n\\nIs this binary tree BST: \" + bt.isBinarySearchTree());\n }", "pre_mask_code": "package coding.challenge;\n\npublic class Main {\n\n public static void main(String[] args) {\n /* This tree is BST \n 40\n / \\\n 35 45\n / \\ / \\ \n 30 37 44 48 \n /\n 20 \n */\n BinaryTree bt = new BinaryTree<>();\n bt.insert(40);\n bt.insert(35);\n bt.insert(45);\n bt.insert(30);\n bt.insert(37);\n bt.insert(44);\n bt.insert(48);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1791", "language": "Java", "task_type": "single_line", "source_file": "java/github/PacktPublishing/The-Complete-Coding-Interview-Guide-in-Java/Chapter13/BinaryTreeIsBST/src/main/java/coding/challenge/Main.java", "mask_start_position": 377, "mask_end_position": 385, "canonical_solution": "ert(45);", "pre_mask_code": "package coding.challenge;\n\npublic class Main {\n\n public static void main(String[] args) {\n /* This tree is BST \n 40\n / \\\n 35 45\n / \\ / \\ \n 30 37 44 48 \n /\n 20 \n */\n BinaryTree bt = new BinaryTree<>();\n bt.insert(40);\n bt.insert(35);\n bt.ins", "post_mask_code": "\n bt.insert(30);\n bt.insert(37);\n bt.insert(44);\n bt.insert(48);\n bt.insert(20);\n System.out.println(\"\\n\\nTraversal LEVEL: \");\n bt.print();\n System.out.println(\"\\n\\nIs this binary tree BST: \" + bt.isBinarySearchTree());\n }\n}\n"} {"task_id": "Java_1792", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/visor/query/VisorQueryTaskArg.java", "mask_start_position": 5029, "mask_end_position": 5113, "canonical_solution": "@Override\n protected void writeExternalData(ObjectOutput out) throws IOException ", "pre_mask_code": "package org.apache.ignite.internal.visor.query;\n\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\nimport org.apache.ignite.internal.visor.VisorDataTransferObject;\n\n/**\n * Arguments for {@link VisorQueryTask}.\n */\npublic class VisorQueryTaskArg extends VisorDataTransferObject {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Cache name for query.\n */\n private String cacheName;\n\n /**\n * Query text.\n */\n private String qryTxt;\n\n /**\n * Distributed joins enabled flag.\n */\n private boolean distributedJoins;\n\n /**\n * Enforce join order flag.\n */\n private boolean enforceJoinOrder;\n\n /**\n * Query contains only replicated tables flag.\n */\n private boolean replicatedOnly;\n\n /**\n * Flag whether to execute query locally.\n */\n private boolean loc;\n\n /**\n * Result batch size.\n */\n private int pageSize;\n\n /**\n * Lazy query execution flag\n */\n private boolean lazy;\n\n /**\n * Collocation flag.\n */\n private boolean collocated;\n\n public VisorQueryTaskArg() {\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, false, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, lazy, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n * @param collocated Collocation flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy, boolean collocated) {\n this.cacheName = cacheName;\n this.qryTxt = qryTxt;\n this.distributedJoins = distributedJoins;\n this.enforceJoinOrder = enforceJoinOrder;\n this.replicatedOnly = replicatedOnly;\n this.loc = loc;\n this.pageSize = pageSize;\n this.lazy = lazy;\n this.collocated = collocated;\n }\n\n public String getCacheName() {\n return cacheName;\n }\n\n public String getQueryText() {\n return qryTxt;\n }\n\n /**\n * @return Distributed joins enabled flag.\n */\n public boolean isDistributedJoins() {\n return distributedJoins;\n }\n\n /**\n * @return Enforce join order flag.\n */\n public boolean isEnforceJoinOrder() {\n return enforceJoinOrder;\n }\n\n /**\n * @return {@code true} If the query contains only replicated tables.\n */\n public boolean isReplicatedOnly() {\n return replicatedOnly;\n }\n\n /**\n * @return {@code true} If query should be executed locally.\n */\n public boolean isLocal() {\n return loc;\n }\n\n public int getPageSize() {\n return pageSize;\n }\n\n /**\n * Lazy query execution flag.\n *\n * @return Lazy flag.\n */\n public boolean getLazy() {\n return lazy;\n }\n\n /**\n * Flag indicating if this query is collocated.\n *\n * @return {@code true} If the query is collocated.\n */\n public boolean isCollocated() {\n return collocated;\n }\n\n @Override\n public byte getProtocolVersion() {\n return V3;\n }\n\n ", "post_mask_code": "{\n U.writeString(out, cacheName);\n U.writeString(out, qryTxt);\n out.writeBoolean(distributedJoins);\n out.writeBoolean(enforceJoinOrder);\n out.writeBoolean(loc);\n out.writeInt(pageSize);\n out.writeBoolean(lazy);\n out.writeBoolean(collocated);\n }\n\n @Override\n protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {\n cacheName = U.readString(in);\n qryTxt = U.readString(in);\n distributedJoins = in.readBoolean();\n enforceJoinOrder = in.readBoolean();\n loc = in.readBoolean();\n pageSize = in.readInt();\n if (protoVer > V1)\n lazy = in.readBoolean();\n if (protoVer > V2)\n collocated = in.readBoolean();\n }\n\n @Override\n public String toString() {\n return S.toString(VisorQueryTaskArg.class, this);\n }\n}\n"} {"task_id": "Java_1793", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/visor/query/VisorQueryTaskArg.java", "mask_start_position": 4715, "mask_end_position": 4743, "canonical_solution": "{\n return lazy;\n }", "pre_mask_code": "package org.apache.ignite.internal.visor.query;\n\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\nimport org.apache.ignite.internal.visor.VisorDataTransferObject;\n\n/**\n * Arguments for {@link VisorQueryTask}.\n */\npublic class VisorQueryTaskArg extends VisorDataTransferObject {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Cache name for query.\n */\n private String cacheName;\n\n /**\n * Query text.\n */\n private String qryTxt;\n\n /**\n * Distributed joins enabled flag.\n */\n private boolean distributedJoins;\n\n /**\n * Enforce join order flag.\n */\n private boolean enforceJoinOrder;\n\n /**\n * Query contains only replicated tables flag.\n */\n private boolean replicatedOnly;\n\n /**\n * Flag whether to execute query locally.\n */\n private boolean loc;\n\n /**\n * Result batch size.\n */\n private int pageSize;\n\n /**\n * Lazy query execution flag\n */\n private boolean lazy;\n\n /**\n * Collocation flag.\n */\n private boolean collocated;\n\n public VisorQueryTaskArg() {\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, false, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, lazy, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n * @param collocated Collocation flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy, boolean collocated) {\n this.cacheName = cacheName;\n this.qryTxt = qryTxt;\n this.distributedJoins = distributedJoins;\n this.enforceJoinOrder = enforceJoinOrder;\n this.replicatedOnly = replicatedOnly;\n this.loc = loc;\n this.pageSize = pageSize;\n this.lazy = lazy;\n this.collocated = collocated;\n }\n\n public String getCacheName() {\n return cacheName;\n }\n\n public String getQueryText() {\n return qryTxt;\n }\n\n /**\n * @return Distributed joins enabled flag.\n */\n public boolean isDistributedJoins() {\n return distributedJoins;\n }\n\n /**\n * @return Enforce join order flag.\n */\n public boolean isEnforceJoinOrder() {\n return enforceJoinOrder;\n }\n\n /**\n * @return {@code true} If the query contains only replicated tables.\n */\n public boolean isReplicatedOnly() {\n return replicatedOnly;\n }\n\n /**\n * @return {@code true} If query should be executed locally.\n */\n public boolean isLocal() {\n return loc;\n }\n\n public int getPageSize() {\n return pageSize;\n }\n\n /**\n * Lazy query execution flag.\n *\n * @return Lazy flag.\n */\n public boolean getLazy() ", "post_mask_code": "\n\n /**\n * Flag indicating if this query is collocated.\n *\n * @return {@code true} If the query is collocated.\n */\n public boolean isCollocated() {\n return collocated;\n }\n\n @Override\n public byte getProtocolVersion() {\n return V3;\n }\n\n @Override\n protected void writeExternalData(ObjectOutput out) throws IOException {\n U.writeString(out, cacheName);\n U.writeString(out, qryTxt);\n out.writeBoolean(distributedJoins);\n out.writeBoolean(enforceJoinOrder);\n out.writeBoolean(loc);\n out.writeInt(pageSize);\n out.writeBoolean(lazy);\n out.writeBoolean(collocated);\n }\n\n @Override\n protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {\n cacheName = U.readString(in);\n qryTxt = U.readString(in);\n distributedJoins = in.readBoolean();\n enforceJoinOrder = in.readBoolean();\n loc = in.readBoolean();\n pageSize = in.readInt();\n if (protoVer > V1)\n lazy = in.readBoolean();\n if (protoVer > V2)\n collocated = in.readBoolean();\n }\n\n @Override\n public String toString() {\n return S.toString(VisorQueryTaskArg.class, this);\n }\n}\n"} {"task_id": "Java_1794", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/visor/query/VisorQueryTaskArg.java", "mask_start_position": 5114, "mask_end_position": 5233, "canonical_solution": "\n U.writeString(out, cacheName);\n U.writeString(out, qryTxt);\n out.writeBoolean(distributedJoins);", "pre_mask_code": "package org.apache.ignite.internal.visor.query;\n\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\nimport org.apache.ignite.internal.visor.VisorDataTransferObject;\n\n/**\n * Arguments for {@link VisorQueryTask}.\n */\npublic class VisorQueryTaskArg extends VisorDataTransferObject {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Cache name for query.\n */\n private String cacheName;\n\n /**\n * Query text.\n */\n private String qryTxt;\n\n /**\n * Distributed joins enabled flag.\n */\n private boolean distributedJoins;\n\n /**\n * Enforce join order flag.\n */\n private boolean enforceJoinOrder;\n\n /**\n * Query contains only replicated tables flag.\n */\n private boolean replicatedOnly;\n\n /**\n * Flag whether to execute query locally.\n */\n private boolean loc;\n\n /**\n * Result batch size.\n */\n private int pageSize;\n\n /**\n * Lazy query execution flag\n */\n private boolean lazy;\n\n /**\n * Collocation flag.\n */\n private boolean collocated;\n\n public VisorQueryTaskArg() {\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, false, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, lazy, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n * @param collocated Collocation flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy, boolean collocated) {\n this.cacheName = cacheName;\n this.qryTxt = qryTxt;\n this.distributedJoins = distributedJoins;\n this.enforceJoinOrder = enforceJoinOrder;\n this.replicatedOnly = replicatedOnly;\n this.loc = loc;\n this.pageSize = pageSize;\n this.lazy = lazy;\n this.collocated = collocated;\n }\n\n public String getCacheName() {\n return cacheName;\n }\n\n public String getQueryText() {\n return qryTxt;\n }\n\n /**\n * @return Distributed joins enabled flag.\n */\n public boolean isDistributedJoins() {\n return distributedJoins;\n }\n\n /**\n * @return Enforce join order flag.\n */\n public boolean isEnforceJoinOrder() {\n return enforceJoinOrder;\n }\n\n /**\n * @return {@code true} If the query contains only replicated tables.\n */\n public boolean isReplicatedOnly() {\n return replicatedOnly;\n }\n\n /**\n * @return {@code true} If query should be executed locally.\n */\n public boolean isLocal() {\n return loc;\n }\n\n public int getPageSize() {\n return pageSize;\n }\n\n /**\n * Lazy query execution flag.\n *\n * @return Lazy flag.\n */\n public boolean getLazy() {\n return lazy;\n }\n\n /**\n * Flag indicating if this query is collocated.\n *\n * @return {@code true} If the query is collocated.\n */\n public boolean isCollocated() {\n return collocated;\n }\n\n @Override\n public byte getProtocolVersion() {\n return V3;\n }\n\n @Override\n protected void writeExternalData(ObjectOutput out) throws IOException {", "post_mask_code": "\n out.writeBoolean(enforceJoinOrder);\n out.writeBoolean(loc);\n out.writeInt(pageSize);\n out.writeBoolean(lazy);\n out.writeBoolean(collocated);\n }\n\n @Override\n protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {\n cacheName = U.readString(in);\n qryTxt = U.readString(in);\n distributedJoins = in.readBoolean();\n enforceJoinOrder = in.readBoolean();\n loc = in.readBoolean();\n pageSize = in.readInt();\n if (protoVer > V1)\n lazy = in.readBoolean();\n if (protoVer > V2)\n collocated = in.readBoolean();\n }\n\n @Override\n public String toString() {\n return S.toString(VisorQueryTaskArg.class, this);\n }\n}\n"} {"task_id": "Java_1795", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/visor/query/VisorQueryTaskArg.java", "mask_start_position": 5242, "mask_end_position": 5340, "canonical_solution": "out.writeBoolean(enforceJoinOrder);\n out.writeBoolean(loc);\n out.writeInt(pageSize);", "pre_mask_code": "package org.apache.ignite.internal.visor.query;\n\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\nimport org.apache.ignite.internal.visor.VisorDataTransferObject;\n\n/**\n * Arguments for {@link VisorQueryTask}.\n */\npublic class VisorQueryTaskArg extends VisorDataTransferObject {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Cache name for query.\n */\n private String cacheName;\n\n /**\n * Query text.\n */\n private String qryTxt;\n\n /**\n * Distributed joins enabled flag.\n */\n private boolean distributedJoins;\n\n /**\n * Enforce join order flag.\n */\n private boolean enforceJoinOrder;\n\n /**\n * Query contains only replicated tables flag.\n */\n private boolean replicatedOnly;\n\n /**\n * Flag whether to execute query locally.\n */\n private boolean loc;\n\n /**\n * Result batch size.\n */\n private int pageSize;\n\n /**\n * Lazy query execution flag\n */\n private boolean lazy;\n\n /**\n * Collocation flag.\n */\n private boolean collocated;\n\n public VisorQueryTaskArg() {\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, false, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, lazy, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n * @param collocated Collocation flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy, boolean collocated) {\n this.cacheName = cacheName;\n this.qryTxt = qryTxt;\n this.distributedJoins = distributedJoins;\n this.enforceJoinOrder = enforceJoinOrder;\n this.replicatedOnly = replicatedOnly;\n this.loc = loc;\n this.pageSize = pageSize;\n this.lazy = lazy;\n this.collocated = collocated;\n }\n\n public String getCacheName() {\n return cacheName;\n }\n\n public String getQueryText() {\n return qryTxt;\n }\n\n /**\n * @return Distributed joins enabled flag.\n */\n public boolean isDistributedJoins() {\n return distributedJoins;\n }\n\n /**\n * @return Enforce join order flag.\n */\n public boolean isEnforceJoinOrder() {\n return enforceJoinOrder;\n }\n\n /**\n * @return {@code true} If the query contains only replicated tables.\n */\n public boolean isReplicatedOnly() {\n return replicatedOnly;\n }\n\n /**\n * @return {@code true} If query should be executed locally.\n */\n public boolean isLocal() {\n return loc;\n }\n\n public int getPageSize() {\n return pageSize;\n }\n\n /**\n * Lazy query execution flag.\n *\n * @return Lazy flag.\n */\n public boolean getLazy() {\n return lazy;\n }\n\n /**\n * Flag indicating if this query is collocated.\n *\n * @return {@code true} If the query is collocated.\n */\n public boolean isCollocated() {\n return collocated;\n }\n\n @Override\n public byte getProtocolVersion() {\n return V3;\n }\n\n @Override\n protected void writeExternalData(ObjectOutput out) throws IOException {\n U.writeString(out, cacheName);\n U.writeString(out, qryTxt);\n out.writeBoolean(distributedJoins);\n ", "post_mask_code": "\n out.writeBoolean(lazy);\n out.writeBoolean(collocated);\n }\n\n @Override\n protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {\n cacheName = U.readString(in);\n qryTxt = U.readString(in);\n distributedJoins = in.readBoolean();\n enforceJoinOrder = in.readBoolean();\n loc = in.readBoolean();\n pageSize = in.readInt();\n if (protoVer > V1)\n lazy = in.readBoolean();\n if (protoVer > V2)\n collocated = in.readBoolean();\n }\n\n @Override\n public String toString() {\n return S.toString(VisorQueryTaskArg.class, this);\n }\n}\n"} {"task_id": "Java_1796", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/visor/query/VisorQueryTaskArg.java", "mask_start_position": 5349, "mask_end_position": 5416, "canonical_solution": "out.writeBoolean(lazy);\n out.writeBoolean(collocated);\n }", "pre_mask_code": "package org.apache.ignite.internal.visor.query;\n\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\nimport org.apache.ignite.internal.visor.VisorDataTransferObject;\n\n/**\n * Arguments for {@link VisorQueryTask}.\n */\npublic class VisorQueryTaskArg extends VisorDataTransferObject {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Cache name for query.\n */\n private String cacheName;\n\n /**\n * Query text.\n */\n private String qryTxt;\n\n /**\n * Distributed joins enabled flag.\n */\n private boolean distributedJoins;\n\n /**\n * Enforce join order flag.\n */\n private boolean enforceJoinOrder;\n\n /**\n * Query contains only replicated tables flag.\n */\n private boolean replicatedOnly;\n\n /**\n * Flag whether to execute query locally.\n */\n private boolean loc;\n\n /**\n * Result batch size.\n */\n private int pageSize;\n\n /**\n * Lazy query execution flag\n */\n private boolean lazy;\n\n /**\n * Collocation flag.\n */\n private boolean collocated;\n\n public VisorQueryTaskArg() {\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, false, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, lazy, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n * @param collocated Collocation flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy, boolean collocated) {\n this.cacheName = cacheName;\n this.qryTxt = qryTxt;\n this.distributedJoins = distributedJoins;\n this.enforceJoinOrder = enforceJoinOrder;\n this.replicatedOnly = replicatedOnly;\n this.loc = loc;\n this.pageSize = pageSize;\n this.lazy = lazy;\n this.collocated = collocated;\n }\n\n public String getCacheName() {\n return cacheName;\n }\n\n public String getQueryText() {\n return qryTxt;\n }\n\n /**\n * @return Distributed joins enabled flag.\n */\n public boolean isDistributedJoins() {\n return distributedJoins;\n }\n\n /**\n * @return Enforce join order flag.\n */\n public boolean isEnforceJoinOrder() {\n return enforceJoinOrder;\n }\n\n /**\n * @return {@code true} If the query contains only replicated tables.\n */\n public boolean isReplicatedOnly() {\n return replicatedOnly;\n }\n\n /**\n * @return {@code true} If query should be executed locally.\n */\n public boolean isLocal() {\n return loc;\n }\n\n public int getPageSize() {\n return pageSize;\n }\n\n /**\n * Lazy query execution flag.\n *\n * @return Lazy flag.\n */\n public boolean getLazy() {\n return lazy;\n }\n\n /**\n * Flag indicating if this query is collocated.\n *\n * @return {@code true} If the query is collocated.\n */\n public boolean isCollocated() {\n return collocated;\n }\n\n @Override\n public byte getProtocolVersion() {\n return V3;\n }\n\n @Override\n protected void writeExternalData(ObjectOutput out) throws IOException {\n U.writeString(out, cacheName);\n U.writeString(out, qryTxt);\n out.writeBoolean(distributedJoins);\n out.writeBoolean(enforceJoinOrder);\n out.writeBoolean(loc);\n out.writeInt(pageSize);\n ", "post_mask_code": "\n\n @Override\n protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {\n cacheName = U.readString(in);\n qryTxt = U.readString(in);\n distributedJoins = in.readBoolean();\n enforceJoinOrder = in.readBoolean();\n loc = in.readBoolean();\n pageSize = in.readInt();\n if (protoVer > V1)\n lazy = in.readBoolean();\n if (protoVer > V2)\n collocated = in.readBoolean();\n }\n\n @Override\n public String toString() {\n return S.toString(VisorQueryTaskArg.class, this);\n }\n}\n"} {"task_id": "Java_1797", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/visor/query/VisorQueryTaskArg.java", "mask_start_position": 5993, "mask_end_position": 6015, "canonical_solution": "yTaskArg.class, this);", "pre_mask_code": "package org.apache.ignite.internal.visor.query;\n\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\nimport org.apache.ignite.internal.visor.VisorDataTransferObject;\n\n/**\n * Arguments for {@link VisorQueryTask}.\n */\npublic class VisorQueryTaskArg extends VisorDataTransferObject {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Cache name for query.\n */\n private String cacheName;\n\n /**\n * Query text.\n */\n private String qryTxt;\n\n /**\n * Distributed joins enabled flag.\n */\n private boolean distributedJoins;\n\n /**\n * Enforce join order flag.\n */\n private boolean enforceJoinOrder;\n\n /**\n * Query contains only replicated tables flag.\n */\n private boolean replicatedOnly;\n\n /**\n * Flag whether to execute query locally.\n */\n private boolean loc;\n\n /**\n * Result batch size.\n */\n private int pageSize;\n\n /**\n * Lazy query execution flag\n */\n private boolean lazy;\n\n /**\n * Collocation flag.\n */\n private boolean collocated;\n\n public VisorQueryTaskArg() {\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, false, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, lazy, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n * @param collocated Collocation flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy, boolean collocated) {\n this.cacheName = cacheName;\n this.qryTxt = qryTxt;\n this.distributedJoins = distributedJoins;\n this.enforceJoinOrder = enforceJoinOrder;\n this.replicatedOnly = replicatedOnly;\n this.loc = loc;\n this.pageSize = pageSize;\n this.lazy = lazy;\n this.collocated = collocated;\n }\n\n public String getCacheName() {\n return cacheName;\n }\n\n public String getQueryText() {\n return qryTxt;\n }\n\n /**\n * @return Distributed joins enabled flag.\n */\n public boolean isDistributedJoins() {\n return distributedJoins;\n }\n\n /**\n * @return Enforce join order flag.\n */\n public boolean isEnforceJoinOrder() {\n return enforceJoinOrder;\n }\n\n /**\n * @return {@code true} If the query contains only replicated tables.\n */\n public boolean isReplicatedOnly() {\n return replicatedOnly;\n }\n\n /**\n * @return {@code true} If query should be executed locally.\n */\n public boolean isLocal() {\n return loc;\n }\n\n public int getPageSize() {\n return pageSize;\n }\n\n /**\n * Lazy query execution flag.\n *\n * @return Lazy flag.\n */\n public boolean getLazy() {\n return lazy;\n }\n\n /**\n * Flag indicating if this query is collocated.\n *\n * @return {@code true} If the query is collocated.\n */\n public boolean isCollocated() {\n return collocated;\n }\n\n @Override\n public byte getProtocolVersion() {\n return V3;\n }\n\n @Override\n protected void writeExternalData(ObjectOutput out) throws IOException {\n U.writeString(out, cacheName);\n U.writeString(out, qryTxt);\n out.writeBoolean(distributedJoins);\n out.writeBoolean(enforceJoinOrder);\n out.writeBoolean(loc);\n out.writeInt(pageSize);\n out.writeBoolean(lazy);\n out.writeBoolean(collocated);\n }\n\n @Override\n protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {\n cacheName = U.readString(in);\n qryTxt = U.readString(in);\n distributedJoins = in.readBoolean();\n enforceJoinOrder = in.readBoolean();\n loc = in.readBoolean();\n pageSize = in.readInt();\n if (protoVer > V1)\n lazy = in.readBoolean();\n if (protoVer > V2)\n collocated = in.readBoolean();\n }\n\n @Override\n public String toString() {\n return S.toString(VisorQuer", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1798", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/visor/query/VisorQueryTaskArg.java", "mask_start_position": 4327, "mask_end_position": 4399, "canonical_solution": "public boolean isReplicatedOnly() {\n return replicatedOnly;\n }", "pre_mask_code": "package org.apache.ignite.internal.visor.query;\n\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\nimport org.apache.ignite.internal.visor.VisorDataTransferObject;\n\n/**\n * Arguments for {@link VisorQueryTask}.\n */\npublic class VisorQueryTaskArg extends VisorDataTransferObject {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Cache name for query.\n */\n private String cacheName;\n\n /**\n * Query text.\n */\n private String qryTxt;\n\n /**\n * Distributed joins enabled flag.\n */\n private boolean distributedJoins;\n\n /**\n * Enforce join order flag.\n */\n private boolean enforceJoinOrder;\n\n /**\n * Query contains only replicated tables flag.\n */\n private boolean replicatedOnly;\n\n /**\n * Flag whether to execute query locally.\n */\n private boolean loc;\n\n /**\n * Result batch size.\n */\n private int pageSize;\n\n /**\n * Lazy query execution flag\n */\n private boolean lazy;\n\n /**\n * Collocation flag.\n */\n private boolean collocated;\n\n public VisorQueryTaskArg() {\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, false, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, lazy, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n * @param collocated Collocation flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy, boolean collocated) {\n this.cacheName = cacheName;\n this.qryTxt = qryTxt;\n this.distributedJoins = distributedJoins;\n this.enforceJoinOrder = enforceJoinOrder;\n this.replicatedOnly = replicatedOnly;\n this.loc = loc;\n this.pageSize = pageSize;\n this.lazy = lazy;\n this.collocated = collocated;\n }\n\n public String getCacheName() {\n return cacheName;\n }\n\n public String getQueryText() {\n return qryTxt;\n }\n\n /**\n * @return Distributed joins enabled flag.\n */\n public boolean isDistributedJoins() {\n return distributedJoins;\n }\n\n /**\n * @return Enforce join order flag.\n */\n public boolean isEnforceJoinOrder() {\n return enforceJoinOrder;\n }\n\n /**\n * @return {@code true} If the query contains only replicated tables.\n */\n ", "post_mask_code": "\n\n /**\n * @return {@code true} If query should be executed locally.\n */\n public boolean isLocal() {\n return loc;\n }\n\n public int getPageSize() {\n return pageSize;\n }\n\n /**\n * Lazy query execution flag.\n *\n * @return Lazy flag.\n */\n public boolean getLazy() {\n return lazy;\n }\n\n /**\n * Flag indicating if this query is collocated.\n *\n * @return {@code true} If the query is collocated.\n */\n public boolean isCollocated() {\n return collocated;\n }\n\n @Override\n public byte getProtocolVersion() {\n return V3;\n }\n\n @Override\n protected void writeExternalData(ObjectOutput out) throws IOException {\n U.writeString(out, cacheName);\n U.writeString(out, qryTxt);\n out.writeBoolean(distributedJoins);\n out.writeBoolean(enforceJoinOrder);\n out.writeBoolean(loc);\n out.writeInt(pageSize);\n out.writeBoolean(lazy);\n out.writeBoolean(collocated);\n }\n\n @Override\n protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {\n cacheName = U.readString(in);\n qryTxt = U.readString(in);\n distributedJoins = in.readBoolean();\n enforceJoinOrder = in.readBoolean();\n loc = in.readBoolean();\n pageSize = in.readInt();\n if (protoVer > V1)\n lazy = in.readBoolean();\n if (protoVer > V2)\n collocated = in.readBoolean();\n }\n\n @Override\n public String toString() {\n return S.toString(VisorQueryTaskArg.class, this);\n }\n}\n"} {"task_id": "Java_1799", "language": "Java", "task_type": "if_statement", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/visor/query/VisorQueryTaskArg.java", "mask_start_position": 5844, "mask_end_position": 5905, "canonical_solution": "if (protoVer > V2)\n collocated = in.readBoolean();", "pre_mask_code": "package org.apache.ignite.internal.visor.query;\n\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\nimport org.apache.ignite.internal.visor.VisorDataTransferObject;\n\n/**\n * Arguments for {@link VisorQueryTask}.\n */\npublic class VisorQueryTaskArg extends VisorDataTransferObject {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Cache name for query.\n */\n private String cacheName;\n\n /**\n * Query text.\n */\n private String qryTxt;\n\n /**\n * Distributed joins enabled flag.\n */\n private boolean distributedJoins;\n\n /**\n * Enforce join order flag.\n */\n private boolean enforceJoinOrder;\n\n /**\n * Query contains only replicated tables flag.\n */\n private boolean replicatedOnly;\n\n /**\n * Flag whether to execute query locally.\n */\n private boolean loc;\n\n /**\n * Result batch size.\n */\n private int pageSize;\n\n /**\n * Lazy query execution flag\n */\n private boolean lazy;\n\n /**\n * Collocation flag.\n */\n private boolean collocated;\n\n public VisorQueryTaskArg() {\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, false, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy) {\n this(cacheName, qryTxt, distributedJoins, enforceJoinOrder, replicatedOnly, loc, pageSize, lazy, false);\n }\n\n /**\n * @param cacheName Cache name for query.\n * @param qryTxt Query text.\n * @param distributedJoins If {@code true} then distributed joins enabled.\n * @param enforceJoinOrder If {@code true} then enforce join order.\n * @param replicatedOnly {@code true} then query contains only replicated tables.\n * @param loc Flag whether to execute query locally.\n * @param pageSize Result batch size.\n * @param lazy Lazy query execution flag.\n * @param collocated Collocation flag.\n */\n public VisorQueryTaskArg(String cacheName, String qryTxt, boolean distributedJoins, boolean enforceJoinOrder, boolean replicatedOnly, boolean loc, int pageSize, boolean lazy, boolean collocated) {\n this.cacheName = cacheName;\n this.qryTxt = qryTxt;\n this.distributedJoins = distributedJoins;\n this.enforceJoinOrder = enforceJoinOrder;\n this.replicatedOnly = replicatedOnly;\n this.loc = loc;\n this.pageSize = pageSize;\n this.lazy = lazy;\n this.collocated = collocated;\n }\n\n public String getCacheName() {\n return cacheName;\n }\n\n public String getQueryText() {\n return qryTxt;\n }\n\n /**\n * @return Distributed joins enabled flag.\n */\n public boolean isDistributedJoins() {\n return distributedJoins;\n }\n\n /**\n * @return Enforce join order flag.\n */\n public boolean isEnforceJoinOrder() {\n return enforceJoinOrder;\n }\n\n /**\n * @return {@code true} If the query contains only replicated tables.\n */\n public boolean isReplicatedOnly() {\n return replicatedOnly;\n }\n\n /**\n * @return {@code true} If query should be executed locally.\n */\n public boolean isLocal() {\n return loc;\n }\n\n public int getPageSize() {\n return pageSize;\n }\n\n /**\n * Lazy query execution flag.\n *\n * @return Lazy flag.\n */\n public boolean getLazy() {\n return lazy;\n }\n\n /**\n * Flag indicating if this query is collocated.\n *\n * @return {@code true} If the query is collocated.\n */\n public boolean isCollocated() {\n return collocated;\n }\n\n @Override\n public byte getProtocolVersion() {\n return V3;\n }\n\n @Override\n protected void writeExternalData(ObjectOutput out) throws IOException {\n U.writeString(out, cacheName);\n U.writeString(out, qryTxt);\n out.writeBoolean(distributedJoins);\n out.writeBoolean(enforceJoinOrder);\n out.writeBoolean(loc);\n out.writeInt(pageSize);\n out.writeBoolean(lazy);\n out.writeBoolean(collocated);\n }\n\n @Override\n protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {\n cacheName = U.readString(in);\n qryTxt = U.readString(in);\n distributedJoins = in.readBoolean();\n enforceJoinOrder = in.readBoolean();\n loc = in.readBoolean();\n pageSize = in.readInt();\n if (protoVer > V1)\n lazy = in.readBoolean();\n ", "post_mask_code": "\n }\n\n @Override\n public String toString() {\n return S.toString(VisorQueryTaskArg.class, this);\n }\n}\n"} {"task_id": "Java_1800", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/asterixdb/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/file/DelimitedDataTupleParserFactory.java", "mask_start_position": 1616, "mask_end_position": 1699, "canonical_solution": "@Override\n public ITupleParser createTupleParser(final IHyracksTaskContext ctx) ", "pre_mask_code": "package org.apache.hyracks.dataflow.std.file;\n\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport org.apache.hyracks.api.comm.IFrame;\nimport org.apache.hyracks.api.comm.IFrameWriter;\nimport org.apache.hyracks.api.comm.VSizeFrame;\nimport org.apache.hyracks.api.context.IHyracksTaskContext;\nimport org.apache.hyracks.api.exceptions.HyracksDataException;\nimport org.apache.hyracks.api.exceptions.IWarningCollector;\nimport org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder;\nimport org.apache.hyracks.dataflow.common.comm.io.FrameTupleAppender;\nimport org.apache.hyracks.dataflow.common.comm.util.FrameUtils;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParser;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParserFactory;\n\n/**\n * Currently used by tests only. Reconsider the code when it will be used otherwise.\n */\npublic class DelimitedDataTupleParserFactory implements ITupleParserFactory {\n\n private static final long serialVersionUID = 1L;\n\n private IValueParserFactory[] valueParserFactories;\n\n private char fieldDelimiter;\n\n private char quote;\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter) {\n this(fieldParserFactories, fieldDelimiter, '\\\"');\n }\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter, char quote) {\n this.valueParserFactories = fieldParserFactories;\n this.fieldDelimiter = fieldDelimiter;\n this.quote = quote;\n }\n\n ", "post_mask_code": "{\n return new ITupleParser() {\n\n final IWarningCollector warningCollector = ctx.getWarningCollector();\n\n @Override\n public void parse(InputStream in, IFrameWriter writer) throws HyracksDataException {\n try {\n IValueParser[] valueParsers = new IValueParser[valueParserFactories.length];\n for (int i = 0; i < valueParserFactories.length; ++i) {\n valueParsers[i] = valueParserFactories[i].createValueParser();\n }\n IFrame frame = new VSizeFrame(ctx);\n FrameTupleAppender appender = new FrameTupleAppender();\n appender.reset(frame, true);\n ArrayTupleBuilder tb = new ArrayTupleBuilder(valueParsers.length);\n DataOutput dos = tb.getDataOutput();\n FieldCursorForDelimitedDataParser cursor = new FieldCursorForDelimitedDataParser(new InputStreamReader(in), fieldDelimiter, quote, warningCollector, () -> \"\");\n while (cursor.nextRecord()) {\n tb.reset();\n for (int i = 0; i < valueParsers.length; ++i) {\n FieldCursorForDelimitedDataParser.Result result = cursor.nextField();\n switch(result) {\n case OK:\n break;\n case END:\n case ERROR:\n throw new HyracksDataException(\"Failed to parse record\");\n default:\n throw new IllegalStateException();\n }\n // Eliminate double quotes in the field that we are going to parse\n if (cursor.fieldHasDoubleQuote()) {\n cursor.eliminateDoubleQuote();\n }\n if (!valueParsers[i].parse(cursor.getBuffer(), cursor.getFieldStart(), cursor.getFieldLength(), dos)) {\n throw new HyracksDataException(\"Failed to parse field\");\n }\n tb.addFieldEndOffset();\n }\n FrameUtils.appendToWriter(writer, appender, tb.getFieldEndOffsets(), tb.getByteArray(), 0, tb.getSize());\n }\n appender.write(writer, true);\n } catch (IOException e) {\n throw HyracksDataException.create(e);\n }\n }\n };\n }\n}\n"} {"task_id": "Java_1801", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/asterixdb/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/file/DelimitedDataTupleParserFactory.java", "mask_start_position": 1700, "mask_end_position": 1700, "canonical_solution": "", "pre_mask_code": "package org.apache.hyracks.dataflow.std.file;\n\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport org.apache.hyracks.api.comm.IFrame;\nimport org.apache.hyracks.api.comm.IFrameWriter;\nimport org.apache.hyracks.api.comm.VSizeFrame;\nimport org.apache.hyracks.api.context.IHyracksTaskContext;\nimport org.apache.hyracks.api.exceptions.HyracksDataException;\nimport org.apache.hyracks.api.exceptions.IWarningCollector;\nimport org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder;\nimport org.apache.hyracks.dataflow.common.comm.io.FrameTupleAppender;\nimport org.apache.hyracks.dataflow.common.comm.util.FrameUtils;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParser;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParserFactory;\n\n/**\n * Currently used by tests only. Reconsider the code when it will be used otherwise.\n */\npublic class DelimitedDataTupleParserFactory implements ITupleParserFactory {\n\n private static final long serialVersionUID = 1L;\n\n private IValueParserFactory[] valueParserFactories;\n\n private char fieldDelimiter;\n\n private char quote;\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter) {\n this(fieldParserFactories, fieldDelimiter, '\\\"');\n }\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter, char quote) {\n this.valueParserFactories = fieldParserFactories;\n this.fieldDelimiter = fieldDelimiter;\n this.quote = quote;\n }\n\n @Override\n public ITupleParser createTupleParser(final IHyracksTaskContext ctx) {", "post_mask_code": "\n return new ITupleParser() {\n\n final IWarningCollector warningCollector = ctx.getWarningCollector();\n\n @Override\n public void parse(InputStream in, IFrameWriter writer) throws HyracksDataException {\n try {\n IValueParser[] valueParsers = new IValueParser[valueParserFactories.length];\n for (int i = 0; i < valueParserFactories.length; ++i) {\n valueParsers[i] = valueParserFactories[i].createValueParser();\n }\n IFrame frame = new VSizeFrame(ctx);\n FrameTupleAppender appender = new FrameTupleAppender();\n appender.reset(frame, true);\n ArrayTupleBuilder tb = new ArrayTupleBuilder(valueParsers.length);\n DataOutput dos = tb.getDataOutput();\n FieldCursorForDelimitedDataParser cursor = new FieldCursorForDelimitedDataParser(new InputStreamReader(in), fieldDelimiter, quote, warningCollector, () -> \"\");\n while (cursor.nextRecord()) {\n tb.reset();\n for (int i = 0; i < valueParsers.length; ++i) {\n FieldCursorForDelimitedDataParser.Result result = cursor.nextField();\n switch(result) {\n case OK:\n break;\n case END:\n case ERROR:\n throw new HyracksDataException(\"Failed to parse record\");\n default:\n throw new IllegalStateException();\n }\n // Eliminate double quotes in the field that we are going to parse\n if (cursor.fieldHasDoubleQuote()) {\n cursor.eliminateDoubleQuote();\n }\n if (!valueParsers[i].parse(cursor.getBuffer(), cursor.getFieldStart(), cursor.getFieldLength(), dos)) {\n throw new HyracksDataException(\"Failed to parse field\");\n }\n tb.addFieldEndOffset();\n }\n FrameUtils.appendToWriter(writer, appender, tb.getFieldEndOffsets(), tb.getByteArray(), 0, tb.getSize());\n }\n appender.write(writer, true);\n } catch (IOException e) {\n throw HyracksDataException.create(e);\n }\n }\n };\n }\n}\n"} {"task_id": "Java_1802", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/asterixdb/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/file/DelimitedDataTupleParserFactory.java", "mask_start_position": 1709, "mask_end_position": 4381, "canonical_solution": "return new ITupleParser() {\n\n final IWarningCollector warningCollector = ctx.getWarningCollector();\n\n @Override\n public void parse(InputStream in, IFrameWriter writer) throws HyracksDataException {\n try {\n IValueParser[] valueParsers = new IValueParser[valueParserFactories.length];\n for (int i = 0; i < valueParserFactories.length; ++i) {\n valueParsers[i] = valueParserFactories[i].createValueParser();\n }\n IFrame frame = new VSizeFrame(ctx);\n FrameTupleAppender appender = new FrameTupleAppender();\n appender.reset(frame, true);\n ArrayTupleBuilder tb = new ArrayTupleBuilder(valueParsers.length);\n DataOutput dos = tb.getDataOutput();\n FieldCursorForDelimitedDataParser cursor = new FieldCursorForDelimitedDataParser(new InputStreamReader(in), fieldDelimiter, quote, warningCollector, () -> \"\");\n while (cursor.nextRecord()) {\n tb.reset();\n for (int i = 0; i < valueParsers.length; ++i) {\n FieldCursorForDelimitedDataParser.Result result = cursor.nextField();\n switch(result) {\n case OK:\n break;\n case END:\n case ERROR:\n throw new HyracksDataException(\"Failed to parse record\");\n default:\n throw new IllegalStateException();\n }\n // Eliminate double quotes in the field that we are going to parse\n if (cursor.fieldHasDoubleQuote()) {\n cursor.eliminateDoubleQuote();\n }\n if (!valueParsers[i].parse(cursor.getBuffer(), cursor.getFieldStart(), cursor.getFieldLength(), dos)) {\n throw new HyracksDataException(\"Failed to parse field\");\n }\n tb.addFieldEndOffset();\n }\n FrameUtils.appendToWriter(writer, appender, tb.getFieldEndOffsets(), tb.getByteArray(), 0, tb.getSize());\n }\n appender.write(writer, true);\n } catch (IOException e) {\n throw HyracksDataException.create(e);\n }\n }\n };", "pre_mask_code": "package org.apache.hyracks.dataflow.std.file;\n\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport org.apache.hyracks.api.comm.IFrame;\nimport org.apache.hyracks.api.comm.IFrameWriter;\nimport org.apache.hyracks.api.comm.VSizeFrame;\nimport org.apache.hyracks.api.context.IHyracksTaskContext;\nimport org.apache.hyracks.api.exceptions.HyracksDataException;\nimport org.apache.hyracks.api.exceptions.IWarningCollector;\nimport org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder;\nimport org.apache.hyracks.dataflow.common.comm.io.FrameTupleAppender;\nimport org.apache.hyracks.dataflow.common.comm.util.FrameUtils;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParser;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParserFactory;\n\n/**\n * Currently used by tests only. Reconsider the code when it will be used otherwise.\n */\npublic class DelimitedDataTupleParserFactory implements ITupleParserFactory {\n\n private static final long serialVersionUID = 1L;\n\n private IValueParserFactory[] valueParserFactories;\n\n private char fieldDelimiter;\n\n private char quote;\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter) {\n this(fieldParserFactories, fieldDelimiter, '\\\"');\n }\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter, char quote) {\n this.valueParserFactories = fieldParserFactories;\n this.fieldDelimiter = fieldDelimiter;\n this.quote = quote;\n }\n\n @Override\n public ITupleParser createTupleParser(final IHyracksTaskContext ctx) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1803", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/asterixdb/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/file/DelimitedDataTupleParserFactory.java", "mask_start_position": 4386, "mask_end_position": 4387, "canonical_solution": "}", "pre_mask_code": "package org.apache.hyracks.dataflow.std.file;\n\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport org.apache.hyracks.api.comm.IFrame;\nimport org.apache.hyracks.api.comm.IFrameWriter;\nimport org.apache.hyracks.api.comm.VSizeFrame;\nimport org.apache.hyracks.api.context.IHyracksTaskContext;\nimport org.apache.hyracks.api.exceptions.HyracksDataException;\nimport org.apache.hyracks.api.exceptions.IWarningCollector;\nimport org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder;\nimport org.apache.hyracks.dataflow.common.comm.io.FrameTupleAppender;\nimport org.apache.hyracks.dataflow.common.comm.util.FrameUtils;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParser;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParserFactory;\n\n/**\n * Currently used by tests only. Reconsider the code when it will be used otherwise.\n */\npublic class DelimitedDataTupleParserFactory implements ITupleParserFactory {\n\n private static final long serialVersionUID = 1L;\n\n private IValueParserFactory[] valueParserFactories;\n\n private char fieldDelimiter;\n\n private char quote;\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter) {\n this(fieldParserFactories, fieldDelimiter, '\\\"');\n }\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter, char quote) {\n this.valueParserFactories = fieldParserFactories;\n this.fieldDelimiter = fieldDelimiter;\n this.quote = quote;\n }\n\n @Override\n public ITupleParser createTupleParser(final IHyracksTaskContext ctx) {\n return new ITupleParser() {\n\n final IWarningCollector warningCollector = ctx.getWarningCollector();\n\n @Override\n public void parse(InputStream in, IFrameWriter writer) throws HyracksDataException {\n try {\n IValueParser[] valueParsers = new IValueParser[valueParserFactories.length];\n for (int i = 0; i < valueParserFactories.length; ++i) {\n valueParsers[i] = valueParserFactories[i].createValueParser();\n }\n IFrame frame = new VSizeFrame(ctx);\n FrameTupleAppender appender = new FrameTupleAppender();\n appender.reset(frame, true);\n ArrayTupleBuilder tb = new ArrayTupleBuilder(valueParsers.length);\n DataOutput dos = tb.getDataOutput();\n FieldCursorForDelimitedDataParser cursor = new FieldCursorForDelimitedDataParser(new InputStreamReader(in), fieldDelimiter, quote, warningCollector, () -> \"\");\n while (cursor.nextRecord()) {\n tb.reset();\n for (int i = 0; i < valueParsers.length; ++i) {\n FieldCursorForDelimitedDataParser.Result result = cursor.nextField();\n switch(result) {\n case OK:\n break;\n case END:\n case ERROR:\n throw new HyracksDataException(\"Failed to parse record\");\n default:\n throw new IllegalStateException();\n }\n // Eliminate double quotes in the field that we are going to parse\n if (cursor.fieldHasDoubleQuote()) {\n cursor.eliminateDoubleQuote();\n }\n if (!valueParsers[i].parse(cursor.getBuffer(), cursor.getFieldStart(), cursor.getFieldLength(), dos)) {\n throw new HyracksDataException(\"Failed to parse field\");\n }\n tb.addFieldEndOffset();\n }\n FrameUtils.appendToWriter(writer, appender, tb.getFieldEndOffsets(), tb.getByteArray(), 0, tb.getSize());\n }\n appender.write(writer, true);\n } catch (IOException e) {\n throw HyracksDataException.create(e);\n }\n }\n };\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1804", "language": "Java", "task_type": "if_statement", "source_file": "java/github/apache/asterixdb/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/file/DelimitedDataTupleParserFactory.java", "mask_start_position": 3736, "mask_end_position": 3958, "canonical_solution": "if (!valueParsers[i].parse(cursor.getBuffer(), cursor.getFieldStart(), cursor.getFieldLength(), dos)) {\n throw new HyracksDataException(\"Failed to parse field\");\n }", "pre_mask_code": "package org.apache.hyracks.dataflow.std.file;\n\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport org.apache.hyracks.api.comm.IFrame;\nimport org.apache.hyracks.api.comm.IFrameWriter;\nimport org.apache.hyracks.api.comm.VSizeFrame;\nimport org.apache.hyracks.api.context.IHyracksTaskContext;\nimport org.apache.hyracks.api.exceptions.HyracksDataException;\nimport org.apache.hyracks.api.exceptions.IWarningCollector;\nimport org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder;\nimport org.apache.hyracks.dataflow.common.comm.io.FrameTupleAppender;\nimport org.apache.hyracks.dataflow.common.comm.util.FrameUtils;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParser;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParserFactory;\n\n/**\n * Currently used by tests only. Reconsider the code when it will be used otherwise.\n */\npublic class DelimitedDataTupleParserFactory implements ITupleParserFactory {\n\n private static final long serialVersionUID = 1L;\n\n private IValueParserFactory[] valueParserFactories;\n\n private char fieldDelimiter;\n\n private char quote;\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter) {\n this(fieldParserFactories, fieldDelimiter, '\\\"');\n }\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter, char quote) {\n this.valueParserFactories = fieldParserFactories;\n this.fieldDelimiter = fieldDelimiter;\n this.quote = quote;\n }\n\n @Override\n public ITupleParser createTupleParser(final IHyracksTaskContext ctx) {\n return new ITupleParser() {\n\n final IWarningCollector warningCollector = ctx.getWarningCollector();\n\n @Override\n public void parse(InputStream in, IFrameWriter writer) throws HyracksDataException {\n try {\n IValueParser[] valueParsers = new IValueParser[valueParserFactories.length];\n for (int i = 0; i < valueParserFactories.length; ++i) {\n valueParsers[i] = valueParserFactories[i].createValueParser();\n }\n IFrame frame = new VSizeFrame(ctx);\n FrameTupleAppender appender = new FrameTupleAppender();\n appender.reset(frame, true);\n ArrayTupleBuilder tb = new ArrayTupleBuilder(valueParsers.length);\n DataOutput dos = tb.getDataOutput();\n FieldCursorForDelimitedDataParser cursor = new FieldCursorForDelimitedDataParser(new InputStreamReader(in), fieldDelimiter, quote, warningCollector, () -> \"\");\n while (cursor.nextRecord()) {\n tb.reset();\n for (int i = 0; i < valueParsers.length; ++i) {\n FieldCursorForDelimitedDataParser.Result result = cursor.nextField();\n switch(result) {\n case OK:\n break;\n case END:\n case ERROR:\n throw new HyracksDataException(\"Failed to parse record\");\n default:\n throw new IllegalStateException();\n }\n // Eliminate double quotes in the field that we are going to parse\n if (cursor.fieldHasDoubleQuote()) {\n cursor.eliminateDoubleQuote();\n }\n ", "post_mask_code": "\n tb.addFieldEndOffset();\n }\n FrameUtils.appendToWriter(writer, appender, tb.getFieldEndOffsets(), tb.getByteArray(), 0, tb.getSize());\n }\n appender.write(writer, true);\n } catch (IOException e) {\n throw HyracksDataException.create(e);\n }\n }\n };\n }\n}\n"} {"task_id": "Java_1805", "language": "Java", "task_type": "switch_case", "source_file": "java/github/apache/asterixdb/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/file/DelimitedDataTupleParserFactory.java", "mask_start_position": 3033, "mask_end_position": 3455, "canonical_solution": "switch(result) {\n case OK:\n break;\n case END:\n case ERROR:\n throw new HyracksDataException(\"Failed to parse record\");\n default:\n throw new IllegalStateException();\n }", "pre_mask_code": "package org.apache.hyracks.dataflow.std.file;\n\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport org.apache.hyracks.api.comm.IFrame;\nimport org.apache.hyracks.api.comm.IFrameWriter;\nimport org.apache.hyracks.api.comm.VSizeFrame;\nimport org.apache.hyracks.api.context.IHyracksTaskContext;\nimport org.apache.hyracks.api.exceptions.HyracksDataException;\nimport org.apache.hyracks.api.exceptions.IWarningCollector;\nimport org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder;\nimport org.apache.hyracks.dataflow.common.comm.io.FrameTupleAppender;\nimport org.apache.hyracks.dataflow.common.comm.util.FrameUtils;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParser;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParserFactory;\n\n/**\n * Currently used by tests only. Reconsider the code when it will be used otherwise.\n */\npublic class DelimitedDataTupleParserFactory implements ITupleParserFactory {\n\n private static final long serialVersionUID = 1L;\n\n private IValueParserFactory[] valueParserFactories;\n\n private char fieldDelimiter;\n\n private char quote;\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter) {\n this(fieldParserFactories, fieldDelimiter, '\\\"');\n }\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter, char quote) {\n this.valueParserFactories = fieldParserFactories;\n this.fieldDelimiter = fieldDelimiter;\n this.quote = quote;\n }\n\n @Override\n public ITupleParser createTupleParser(final IHyracksTaskContext ctx) {\n return new ITupleParser() {\n\n final IWarningCollector warningCollector = ctx.getWarningCollector();\n\n @Override\n public void parse(InputStream in, IFrameWriter writer) throws HyracksDataException {\n try {\n IValueParser[] valueParsers = new IValueParser[valueParserFactories.length];\n for (int i = 0; i < valueParserFactories.length; ++i) {\n valueParsers[i] = valueParserFactories[i].createValueParser();\n }\n IFrame frame = new VSizeFrame(ctx);\n FrameTupleAppender appender = new FrameTupleAppender();\n appender.reset(frame, true);\n ArrayTupleBuilder tb = new ArrayTupleBuilder(valueParsers.length);\n DataOutput dos = tb.getDataOutput();\n FieldCursorForDelimitedDataParser cursor = new FieldCursorForDelimitedDataParser(new InputStreamReader(in), fieldDelimiter, quote, warningCollector, () -> \"\");\n while (cursor.nextRecord()) {\n tb.reset();\n for (int i = 0; i < valueParsers.length; ++i) {\n FieldCursorForDelimitedDataParser.Result result = cursor.nextField();\n ", "post_mask_code": "\n // Eliminate double quotes in the field that we are going to parse\n if (cursor.fieldHasDoubleQuote()) {\n cursor.eliminateDoubleQuote();\n }\n if (!valueParsers[i].parse(cursor.getBuffer(), cursor.getFieldStart(), cursor.getFieldLength(), dos)) {\n throw new HyracksDataException(\"Failed to parse field\");\n }\n tb.addFieldEndOffset();\n }\n FrameUtils.appendToWriter(writer, appender, tb.getFieldEndOffsets(), tb.getByteArray(), 0, tb.getSize());\n }\n appender.write(writer, true);\n } catch (IOException e) {\n throw HyracksDataException.create(e);\n }\n }\n };\n }\n}\n"} {"task_id": "Java_1806", "language": "Java", "task_type": "for_statement", "source_file": "java/github/apache/asterixdb/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/file/DelimitedDataTupleParserFactory.java", "mask_start_position": 2079, "mask_end_position": 2243, "canonical_solution": "for (int i = 0; i < valueParserFactories.length; ++i) {\n valueParsers[i] = valueParserFactories[i].createValueParser();\n }", "pre_mask_code": "package org.apache.hyracks.dataflow.std.file;\n\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport org.apache.hyracks.api.comm.IFrame;\nimport org.apache.hyracks.api.comm.IFrameWriter;\nimport org.apache.hyracks.api.comm.VSizeFrame;\nimport org.apache.hyracks.api.context.IHyracksTaskContext;\nimport org.apache.hyracks.api.exceptions.HyracksDataException;\nimport org.apache.hyracks.api.exceptions.IWarningCollector;\nimport org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder;\nimport org.apache.hyracks.dataflow.common.comm.io.FrameTupleAppender;\nimport org.apache.hyracks.dataflow.common.comm.util.FrameUtils;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParser;\nimport org.apache.hyracks.dataflow.common.data.parsers.IValueParserFactory;\n\n/**\n * Currently used by tests only. Reconsider the code when it will be used otherwise.\n */\npublic class DelimitedDataTupleParserFactory implements ITupleParserFactory {\n\n private static final long serialVersionUID = 1L;\n\n private IValueParserFactory[] valueParserFactories;\n\n private char fieldDelimiter;\n\n private char quote;\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter) {\n this(fieldParserFactories, fieldDelimiter, '\\\"');\n }\n\n public DelimitedDataTupleParserFactory(IValueParserFactory[] fieldParserFactories, char fieldDelimiter, char quote) {\n this.valueParserFactories = fieldParserFactories;\n this.fieldDelimiter = fieldDelimiter;\n this.quote = quote;\n }\n\n @Override\n public ITupleParser createTupleParser(final IHyracksTaskContext ctx) {\n return new ITupleParser() {\n\n final IWarningCollector warningCollector = ctx.getWarningCollector();\n\n @Override\n public void parse(InputStream in, IFrameWriter writer) throws HyracksDataException {\n try {\n IValueParser[] valueParsers = new IValueParser[valueParserFactories.length];\n ", "post_mask_code": "\n IFrame frame = new VSizeFrame(ctx);\n FrameTupleAppender appender = new FrameTupleAppender();\n appender.reset(frame, true);\n ArrayTupleBuilder tb = new ArrayTupleBuilder(valueParsers.length);\n DataOutput dos = tb.getDataOutput();\n FieldCursorForDelimitedDataParser cursor = new FieldCursorForDelimitedDataParser(new InputStreamReader(in), fieldDelimiter, quote, warningCollector, () -> \"\");\n while (cursor.nextRecord()) {\n tb.reset();\n for (int i = 0; i < valueParsers.length; ++i) {\n FieldCursorForDelimitedDataParser.Result result = cursor.nextField();\n switch(result) {\n case OK:\n break;\n case END:\n case ERROR:\n throw new HyracksDataException(\"Failed to parse record\");\n default:\n throw new IllegalStateException();\n }\n // Eliminate double quotes in the field that we are going to parse\n if (cursor.fieldHasDoubleQuote()) {\n cursor.eliminateDoubleQuote();\n }\n if (!valueParsers[i].parse(cursor.getBuffer(), cursor.getFieldStart(), cursor.getFieldLength(), dos)) {\n throw new HyracksDataException(\"Failed to parse field\");\n }\n tb.addFieldEndOffset();\n }\n FrameUtils.appendToWriter(writer, appender, tb.getFieldEndOffsets(), tb.getByteArray(), 0, tb.getSize());\n }\n appender.write(writer, true);\n } catch (IOException e) {\n throw HyracksDataException.create(e);\n }\n }\n };\n }\n}\n"} {"task_id": "Java_1807", "language": "Java", "task_type": "method_signature", "source_file": "java/github/trinodb/trino/plugin/trino-postgresql/src/main/java/io/trino/plugin/postgresql/PostgreSqlClientModule.java", "mask_start_position": 1303, "mask_end_position": 1457, "canonical_solution": "@Provides\n @Singleton\n @ForBaseJdbc\n public ConnectionFactory getConnectionFactory(BaseJdbcConfig config, CredentialProvider credentialProvider) ", "pre_mask_code": "package io.trino.plugin.postgresql;\n\nimport com.google.inject.Binder;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.Singleton;\nimport io.airlift.configuration.AbstractConfigurationAwareModule;\nimport io.trino.plugin.jdbc.BaseJdbcConfig;\nimport io.trino.plugin.jdbc.ConnectionFactory;\nimport io.trino.plugin.jdbc.DecimalModule;\nimport io.trino.plugin.jdbc.DriverConnectionFactory;\nimport io.trino.plugin.jdbc.ForBaseJdbc;\nimport io.trino.plugin.jdbc.JdbcClient;\nimport io.trino.plugin.jdbc.RemoteQueryCancellationModule;\nimport io.trino.plugin.jdbc.credential.CredentialProvider;\nimport org.postgresql.Driver;\nimport static io.airlift.configuration.ConfigBinder.configBinder;\nimport static io.trino.plugin.jdbc.JdbcModule.bindSessionPropertiesProvider;\n\npublic class PostgreSqlClientModule extends AbstractConfigurationAwareModule {\n\n @Override\n public void setup(Binder binder) {\n binder.bind(JdbcClient.class).annotatedWith(ForBaseJdbc.class).to(PostgreSqlClient.class).in(Scopes.SINGLETON);\n configBinder(binder).bindConfig(PostgreSqlConfig.class);\n bindSessionPropertiesProvider(binder, PostgreSqlSessionProperties.class);\n install(new DecimalModule());\n install(new RemoteQueryCancellationModule());\n }\n\n ", "post_mask_code": "{\n return new DriverConnectionFactory(new Driver(), config, credentialProvider);\n }\n}\n"} {"task_id": "Java_1808", "language": "Java", "task_type": "method_body", "source_file": "java/github/trinodb/trino/plugin/trino-postgresql/src/main/java/io/trino/plugin/postgresql/PostgreSqlClientModule.java", "mask_start_position": 931, "mask_end_position": 1297, "canonical_solution": "{\n binder.bind(JdbcClient.class).annotatedWith(ForBaseJdbc.class).to(PostgreSqlClient.class).in(Scopes.SINGLETON);\n configBinder(binder).bindConfig(PostgreSqlConfig.class);\n bindSessionPropertiesProvider(binder, PostgreSqlSessionProperties.class);\n install(new DecimalModule());\n install(new RemoteQueryCancellationModule());\n }", "pre_mask_code": "package io.trino.plugin.postgresql;\n\nimport com.google.inject.Binder;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.Singleton;\nimport io.airlift.configuration.AbstractConfigurationAwareModule;\nimport io.trino.plugin.jdbc.BaseJdbcConfig;\nimport io.trino.plugin.jdbc.ConnectionFactory;\nimport io.trino.plugin.jdbc.DecimalModule;\nimport io.trino.plugin.jdbc.DriverConnectionFactory;\nimport io.trino.plugin.jdbc.ForBaseJdbc;\nimport io.trino.plugin.jdbc.JdbcClient;\nimport io.trino.plugin.jdbc.RemoteQueryCancellationModule;\nimport io.trino.plugin.jdbc.credential.CredentialProvider;\nimport org.postgresql.Driver;\nimport static io.airlift.configuration.ConfigBinder.configBinder;\nimport static io.trino.plugin.jdbc.JdbcModule.bindSessionPropertiesProvider;\n\npublic class PostgreSqlClientModule extends AbstractConfigurationAwareModule {\n\n @Override\n public void setup(Binder binder) ", "post_mask_code": "\n\n @Provides\n @Singleton\n @ForBaseJdbc\n public ConnectionFactory getConnectionFactory(BaseJdbcConfig config, CredentialProvider credentialProvider) {\n return new DriverConnectionFactory(new Driver(), config, credentialProvider);\n }\n}\n"} {"task_id": "Java_1809", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/trinodb/trino/plugin/trino-postgresql/src/main/java/io/trino/plugin/postgresql/PostgreSqlClientModule.java", "mask_start_position": 932, "mask_end_position": 1117, "canonical_solution": "\n binder.bind(JdbcClient.class).annotatedWith(ForBaseJdbc.class).to(PostgreSqlClient.class).in(Scopes.SINGLETON);\n configBinder(binder).bindConfig(PostgreSqlConfig.class);", "pre_mask_code": "package io.trino.plugin.postgresql;\n\nimport com.google.inject.Binder;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.Singleton;\nimport io.airlift.configuration.AbstractConfigurationAwareModule;\nimport io.trino.plugin.jdbc.BaseJdbcConfig;\nimport io.trino.plugin.jdbc.ConnectionFactory;\nimport io.trino.plugin.jdbc.DecimalModule;\nimport io.trino.plugin.jdbc.DriverConnectionFactory;\nimport io.trino.plugin.jdbc.ForBaseJdbc;\nimport io.trino.plugin.jdbc.JdbcClient;\nimport io.trino.plugin.jdbc.RemoteQueryCancellationModule;\nimport io.trino.plugin.jdbc.credential.CredentialProvider;\nimport org.postgresql.Driver;\nimport static io.airlift.configuration.ConfigBinder.configBinder;\nimport static io.trino.plugin.jdbc.JdbcModule.bindSessionPropertiesProvider;\n\npublic class PostgreSqlClientModule extends AbstractConfigurationAwareModule {\n\n @Override\n public void setup(Binder binder) {", "post_mask_code": "\n bindSessionPropertiesProvider(binder, PostgreSqlSessionProperties.class);\n install(new DecimalModule());\n install(new RemoteQueryCancellationModule());\n }\n\n @Provides\n @Singleton\n @ForBaseJdbc\n public ConnectionFactory getConnectionFactory(BaseJdbcConfig config, CredentialProvider credentialProvider) {\n return new DriverConnectionFactory(new Driver(), config, credentialProvider);\n }\n}\n"} {"task_id": "Java_1810", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/trinodb/trino/plugin/trino-postgresql/src/main/java/io/trino/plugin/postgresql/PostgreSqlClientModule.java", "mask_start_position": 1126, "mask_end_position": 1237, "canonical_solution": "bindSessionPropertiesProvider(binder, PostgreSqlSessionProperties.class);\n install(new DecimalModule());", "pre_mask_code": "package io.trino.plugin.postgresql;\n\nimport com.google.inject.Binder;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.Singleton;\nimport io.airlift.configuration.AbstractConfigurationAwareModule;\nimport io.trino.plugin.jdbc.BaseJdbcConfig;\nimport io.trino.plugin.jdbc.ConnectionFactory;\nimport io.trino.plugin.jdbc.DecimalModule;\nimport io.trino.plugin.jdbc.DriverConnectionFactory;\nimport io.trino.plugin.jdbc.ForBaseJdbc;\nimport io.trino.plugin.jdbc.JdbcClient;\nimport io.trino.plugin.jdbc.RemoteQueryCancellationModule;\nimport io.trino.plugin.jdbc.credential.CredentialProvider;\nimport org.postgresql.Driver;\nimport static io.airlift.configuration.ConfigBinder.configBinder;\nimport static io.trino.plugin.jdbc.JdbcModule.bindSessionPropertiesProvider;\n\npublic class PostgreSqlClientModule extends AbstractConfigurationAwareModule {\n\n @Override\n public void setup(Binder binder) {\n binder.bind(JdbcClient.class).annotatedWith(ForBaseJdbc.class).to(PostgreSqlClient.class).in(Scopes.SINGLETON);\n configBinder(binder).bindConfig(PostgreSqlConfig.class);\n ", "post_mask_code": "\n install(new RemoteQueryCancellationModule());\n }\n\n @Provides\n @Singleton\n @ForBaseJdbc\n public ConnectionFactory getConnectionFactory(BaseJdbcConfig config, CredentialProvider credentialProvider) {\n return new DriverConnectionFactory(new Driver(), config, credentialProvider);\n }\n}\n"} {"task_id": "Java_1811", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/trinodb/trino/plugin/trino-postgresql/src/main/java/io/trino/plugin/postgresql/PostgreSqlClientModule.java", "mask_start_position": 1246, "mask_end_position": 1297, "canonical_solution": "install(new RemoteQueryCancellationModule());\n }", "pre_mask_code": "package io.trino.plugin.postgresql;\n\nimport com.google.inject.Binder;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.Singleton;\nimport io.airlift.configuration.AbstractConfigurationAwareModule;\nimport io.trino.plugin.jdbc.BaseJdbcConfig;\nimport io.trino.plugin.jdbc.ConnectionFactory;\nimport io.trino.plugin.jdbc.DecimalModule;\nimport io.trino.plugin.jdbc.DriverConnectionFactory;\nimport io.trino.plugin.jdbc.ForBaseJdbc;\nimport io.trino.plugin.jdbc.JdbcClient;\nimport io.trino.plugin.jdbc.RemoteQueryCancellationModule;\nimport io.trino.plugin.jdbc.credential.CredentialProvider;\nimport org.postgresql.Driver;\nimport static io.airlift.configuration.ConfigBinder.configBinder;\nimport static io.trino.plugin.jdbc.JdbcModule.bindSessionPropertiesProvider;\n\npublic class PostgreSqlClientModule extends AbstractConfigurationAwareModule {\n\n @Override\n public void setup(Binder binder) {\n binder.bind(JdbcClient.class).annotatedWith(ForBaseJdbc.class).to(PostgreSqlClient.class).in(Scopes.SINGLETON);\n configBinder(binder).bindConfig(PostgreSqlConfig.class);\n bindSessionPropertiesProvider(binder, PostgreSqlSessionProperties.class);\n install(new DecimalModule());\n ", "post_mask_code": "\n\n @Provides\n @Singleton\n @ForBaseJdbc\n public ConnectionFactory getConnectionFactory(BaseJdbcConfig config, CredentialProvider credentialProvider) {\n return new DriverConnectionFactory(new Driver(), config, credentialProvider);\n }\n}\n"} {"task_id": "Java_1812", "language": "Java", "task_type": "single_line", "source_file": "java/github/trinodb/trino/plugin/trino-postgresql/src/main/java/io/trino/plugin/postgresql/PostgreSqlClientModule.java", "mask_start_position": 1114, "mask_end_position": 1117, "canonical_solution": "s);", "pre_mask_code": "package io.trino.plugin.postgresql;\n\nimport com.google.inject.Binder;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.Singleton;\nimport io.airlift.configuration.AbstractConfigurationAwareModule;\nimport io.trino.plugin.jdbc.BaseJdbcConfig;\nimport io.trino.plugin.jdbc.ConnectionFactory;\nimport io.trino.plugin.jdbc.DecimalModule;\nimport io.trino.plugin.jdbc.DriverConnectionFactory;\nimport io.trino.plugin.jdbc.ForBaseJdbc;\nimport io.trino.plugin.jdbc.JdbcClient;\nimport io.trino.plugin.jdbc.RemoteQueryCancellationModule;\nimport io.trino.plugin.jdbc.credential.CredentialProvider;\nimport org.postgresql.Driver;\nimport static io.airlift.configuration.ConfigBinder.configBinder;\nimport static io.trino.plugin.jdbc.JdbcModule.bindSessionPropertiesProvider;\n\npublic class PostgreSqlClientModule extends AbstractConfigurationAwareModule {\n\n @Override\n public void setup(Binder binder) {\n binder.bind(JdbcClient.class).annotatedWith(ForBaseJdbc.class).to(PostgreSqlClient.class).in(Scopes.SINGLETON);\n configBinder(binder).bindConfig(PostgreSqlConfig.clas", "post_mask_code": "\n bindSessionPropertiesProvider(binder, PostgreSqlSessionProperties.class);\n install(new DecimalModule());\n install(new RemoteQueryCancellationModule());\n }\n\n @Provides\n @Singleton\n @ForBaseJdbc\n public ConnectionFactory getConnectionFactory(BaseJdbcConfig config, CredentialProvider credentialProvider) {\n return new DriverConnectionFactory(new Driver(), config, credentialProvider);\n }\n}\n"} {"task_id": "Java_1813", "language": "Java", "task_type": "method_signature", "source_file": "java/github/amitshekhariitbhu/Fast-Android-Networking/android-networking/src/main/java/com/androidnetworking/internal/UploadProgressHandler.java", "mask_start_position": 638, "mask_end_position": 691, "canonical_solution": "@Override\n public void handleMessage(Message msg) ", "pre_mask_code": "package com.androidnetworking.internal;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport com.androidnetworking.common.ANConstants;\nimport com.androidnetworking.interfaces.UploadProgressListener;\nimport com.androidnetworking.model.Progress;\n\n/**\n * Created by amitshekhar on 24/05/16.\n */\npublic class UploadProgressHandler extends Handler {\n\n private final UploadProgressListener mUploadProgressListener;\n\n public UploadProgressHandler(UploadProgressListener uploadProgressListener) {\n super(Looper.getMainLooper());\n mUploadProgressListener = uploadProgressListener;\n }\n\n ", "post_mask_code": "{\n switch(msg.what) {\n case ANConstants.UPDATE:\n if (mUploadProgressListener != null) {\n final Progress progress = (Progress) msg.obj;\n mUploadProgressListener.onProgress(progress.currentBytes, progress.totalBytes);\n }\n break;\n default:\n super.handleMessage(msg);\n break;\n }\n }\n}\n"} {"task_id": "Java_1814", "language": "Java", "task_type": "method_body", "source_file": "java/github/amitshekhariitbhu/Fast-Android-Networking/android-networking/src/main/java/com/androidnetworking/internal/UploadProgressHandler.java", "mask_start_position": 691, "mask_end_position": 1120, "canonical_solution": "{\n switch(msg.what) {\n case ANConstants.UPDATE:\n if (mUploadProgressListener != null) {\n final Progress progress = (Progress) msg.obj;\n mUploadProgressListener.onProgress(progress.currentBytes, progress.totalBytes);\n }\n break;\n default:\n super.handleMessage(msg);\n break;\n }\n }", "pre_mask_code": "package com.androidnetworking.internal;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport com.androidnetworking.common.ANConstants;\nimport com.androidnetworking.interfaces.UploadProgressListener;\nimport com.androidnetworking.model.Progress;\n\n/**\n * Created by amitshekhar on 24/05/16.\n */\npublic class UploadProgressHandler extends Handler {\n\n private final UploadProgressListener mUploadProgressListener;\n\n public UploadProgressHandler(UploadProgressListener uploadProgressListener) {\n super(Looper.getMainLooper());\n mUploadProgressListener = uploadProgressListener;\n }\n\n @Override\n public void handleMessage(Message msg) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1815", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/amitshekhariitbhu/Fast-Android-Networking/android-networking/src/main/java/com/androidnetworking/internal/UploadProgressHandler.java", "mask_start_position": 692, "mask_end_position": 692, "canonical_solution": "", "pre_mask_code": "package com.androidnetworking.internal;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport com.androidnetworking.common.ANConstants;\nimport com.androidnetworking.interfaces.UploadProgressListener;\nimport com.androidnetworking.model.Progress;\n\n/**\n * Created by amitshekhar on 24/05/16.\n */\npublic class UploadProgressHandler extends Handler {\n\n private final UploadProgressListener mUploadProgressListener;\n\n public UploadProgressHandler(UploadProgressListener uploadProgressListener) {\n super(Looper.getMainLooper());\n mUploadProgressListener = uploadProgressListener;\n }\n\n @Override\n public void handleMessage(Message msg) {", "post_mask_code": "\n switch(msg.what) {\n case ANConstants.UPDATE:\n if (mUploadProgressListener != null) {\n final Progress progress = (Progress) msg.obj;\n mUploadProgressListener.onProgress(progress.currentBytes, progress.totalBytes);\n }\n break;\n default:\n super.handleMessage(msg);\n break;\n }\n }\n}\n"} {"task_id": "Java_1816", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/amitshekhariitbhu/Fast-Android-Networking/android-networking/src/main/java/com/androidnetworking/internal/UploadProgressHandler.java", "mask_start_position": 701, "mask_end_position": 1114, "canonical_solution": "switch(msg.what) {\n case ANConstants.UPDATE:\n if (mUploadProgressListener != null) {\n final Progress progress = (Progress) msg.obj;\n mUploadProgressListener.onProgress(progress.currentBytes, progress.totalBytes);\n }\n break;\n default:\n super.handleMessage(msg);\n break;\n }", "pre_mask_code": "package com.androidnetworking.internal;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport com.androidnetworking.common.ANConstants;\nimport com.androidnetworking.interfaces.UploadProgressListener;\nimport com.androidnetworking.model.Progress;\n\n/**\n * Created by amitshekhar on 24/05/16.\n */\npublic class UploadProgressHandler extends Handler {\n\n private final UploadProgressListener mUploadProgressListener;\n\n public UploadProgressHandler(UploadProgressListener uploadProgressListener) {\n super(Looper.getMainLooper());\n mUploadProgressListener = uploadProgressListener;\n }\n\n @Override\n public void handleMessage(Message msg) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1817", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/amitshekhariitbhu/Fast-Android-Networking/android-networking/src/main/java/com/androidnetworking/internal/UploadProgressHandler.java", "mask_start_position": 1119, "mask_end_position": 1120, "canonical_solution": "}", "pre_mask_code": "package com.androidnetworking.internal;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport com.androidnetworking.common.ANConstants;\nimport com.androidnetworking.interfaces.UploadProgressListener;\nimport com.androidnetworking.model.Progress;\n\n/**\n * Created by amitshekhar on 24/05/16.\n */\npublic class UploadProgressHandler extends Handler {\n\n private final UploadProgressListener mUploadProgressListener;\n\n public UploadProgressHandler(UploadProgressListener uploadProgressListener) {\n super(Looper.getMainLooper());\n mUploadProgressListener = uploadProgressListener;\n }\n\n @Override\n public void handleMessage(Message msg) {\n switch(msg.what) {\n case ANConstants.UPDATE:\n if (mUploadProgressListener != null) {\n final Progress progress = (Progress) msg.obj;\n mUploadProgressListener.onProgress(progress.currentBytes, progress.totalBytes);\n }\n break;\n default:\n super.handleMessage(msg);\n break;\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1818", "language": "Java", "task_type": "if_statement", "source_file": "java/github/amitshekhariitbhu/Fast-Android-Networking/android-networking/src/main/java/com/androidnetworking/internal/UploadProgressHandler.java", "mask_start_position": 773, "mask_end_position": 995, "canonical_solution": "if (mUploadProgressListener != null) {\n final Progress progress = (Progress) msg.obj;\n mUploadProgressListener.onProgress(progress.currentBytes, progress.totalBytes);\n }", "pre_mask_code": "package com.androidnetworking.internal;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport com.androidnetworking.common.ANConstants;\nimport com.androidnetworking.interfaces.UploadProgressListener;\nimport com.androidnetworking.model.Progress;\n\n/**\n * Created by amitshekhar on 24/05/16.\n */\npublic class UploadProgressHandler extends Handler {\n\n private final UploadProgressListener mUploadProgressListener;\n\n public UploadProgressHandler(UploadProgressListener uploadProgressListener) {\n super(Looper.getMainLooper());\n mUploadProgressListener = uploadProgressListener;\n }\n\n @Override\n public void handleMessage(Message msg) {\n switch(msg.what) {\n case ANConstants.UPDATE:\n ", "post_mask_code": "\n break;\n default:\n super.handleMessage(msg);\n break;\n }\n }\n}\n"} {"task_id": "Java_1819", "language": "Java", "task_type": "switch_case", "source_file": "java/github/amitshekhariitbhu/Fast-Android-Networking/android-networking/src/main/java/com/androidnetworking/internal/UploadProgressHandler.java", "mask_start_position": 701, "mask_end_position": 1114, "canonical_solution": "switch(msg.what) {\n case ANConstants.UPDATE:\n if (mUploadProgressListener != null) {\n final Progress progress = (Progress) msg.obj;\n mUploadProgressListener.onProgress(progress.currentBytes, progress.totalBytes);\n }\n break;\n default:\n super.handleMessage(msg);\n break;\n }", "pre_mask_code": "package com.androidnetworking.internal;\n\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport com.androidnetworking.common.ANConstants;\nimport com.androidnetworking.interfaces.UploadProgressListener;\nimport com.androidnetworking.model.Progress;\n\n/**\n * Created by amitshekhar on 24/05/16.\n */\npublic class UploadProgressHandler extends Handler {\n\n private final UploadProgressListener mUploadProgressListener;\n\n public UploadProgressHandler(UploadProgressListener uploadProgressListener) {\n super(Looper.getMainLooper());\n mUploadProgressListener = uploadProgressListener;\n }\n\n @Override\n public void handleMessage(Message msg) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1820", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/lyb-geek/springboot-learning/springboot-transation-after-commit/src/main/java/com/github/lybgeek/user/service/UserService.java", "mask_start_position": 350, "mask_end_position": 393, "canonical_solution": "void saveAndMockNotityWithEvent(User user);", "pre_mask_code": "package com.github.lybgeek.user.service;\n\nimport com.github.lybgeek.user.entity.User;\nimport com.baomidou.mybatisplus.extension.service.IService;\n\npublic interface UserService extends IService {\n\n void saveAndMockLongTimeNotity(User user);\n\n void saveAndMockExceptionCall(User user);\n\n /**\n * 基于事件驱动\n * @param user\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1821", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Team254/FRC-2018-Public/src/main/java/com/team254/lib/util/CrashTracker.java", "mask_start_position": 865, "mask_end_position": 923, "canonical_solution": "public static void logThrowableCrash(Throwable throwable) ", "pre_mask_code": "package com.team254.lib.util;\n\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.Date;\nimport java.util.UUID;\n\n/**\n * Tracks start-up and caught crash events, logging them to a file which dosn't roll over\n */\npublic class CrashTracker {\n\n private static final UUID RUN_INSTANCE_UUID = UUID.randomUUID();\n\n public static void logRobotStartup() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotConstruction() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotInit() {\n logMarker(\"robot init\");\n }\n\n public static void logTeleopInit() {\n logMarker(\"teleop init\");\n }\n\n public static void logAutoInit() {\n logMarker(\"auto init\");\n }\n\n public static void logDisabledInit() {\n logMarker(\"disabled init\");\n }\n\n ", "post_mask_code": "{\n logMarker(\"Exception\", throwable);\n }\n\n private static void logMarker(String mark) {\n logMarker(mark, null);\n }\n\n private static void logMarker(String mark, Throwable nullableException) {\n try (PrintWriter writer = new PrintWriter(new FileWriter(\"/home/lvuser/crash_tracking.txt\", true))) {\n writer.print(RUN_INSTANCE_UUID.toString());\n writer.print(\", \");\n writer.print(mark);\n writer.print(\", \");\n writer.print(new Date().toString());\n if (nullableException != null) {\n writer.print(\", \");\n nullableException.printStackTrace(writer);\n }\n writer.println();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n"} {"task_id": "Java_1822", "language": "Java", "task_type": "method_body", "source_file": "java/github/Team254/FRC-2018-Public/src/main/java/com/team254/lib/util/CrashTracker.java", "mask_start_position": 816, "mask_end_position": 859, "canonical_solution": "{\n logMarker(\"disabled init\");\n }", "pre_mask_code": "package com.team254.lib.util;\n\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.Date;\nimport java.util.UUID;\n\n/**\n * Tracks start-up and caught crash events, logging them to a file which dosn't roll over\n */\npublic class CrashTracker {\n\n private static final UUID RUN_INSTANCE_UUID = UUID.randomUUID();\n\n public static void logRobotStartup() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotConstruction() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotInit() {\n logMarker(\"robot init\");\n }\n\n public static void logTeleopInit() {\n logMarker(\"teleop init\");\n }\n\n public static void logAutoInit() {\n logMarker(\"auto init\");\n }\n\n public static void logDisabledInit() ", "post_mask_code": "\n\n public static void logThrowableCrash(Throwable throwable) {\n logMarker(\"Exception\", throwable);\n }\n\n private static void logMarker(String mark) {\n logMarker(mark, null);\n }\n\n private static void logMarker(String mark, Throwable nullableException) {\n try (PrintWriter writer = new PrintWriter(new FileWriter(\"/home/lvuser/crash_tracking.txt\", true))) {\n writer.print(RUN_INSTANCE_UUID.toString());\n writer.print(\", \");\n writer.print(mark);\n writer.print(\", \");\n writer.print(new Date().toString());\n if (nullableException != null) {\n writer.print(\", \");\n nullableException.printStackTrace(writer);\n }\n writer.println();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n"} {"task_id": "Java_1823", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Team254/FRC-2018-Public/src/main/java/com/team254/lib/util/CrashTracker.java", "mask_start_position": 1139, "mask_end_position": 1139, "canonical_solution": "", "pre_mask_code": "package com.team254.lib.util;\n\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.Date;\nimport java.util.UUID;\n\n/**\n * Tracks start-up and caught crash events, logging them to a file which dosn't roll over\n */\npublic class CrashTracker {\n\n private static final UUID RUN_INSTANCE_UUID = UUID.randomUUID();\n\n public static void logRobotStartup() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotConstruction() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotInit() {\n logMarker(\"robot init\");\n }\n\n public static void logTeleopInit() {\n logMarker(\"teleop init\");\n }\n\n public static void logAutoInit() {\n logMarker(\"auto init\");\n }\n\n public static void logDisabledInit() {\n logMarker(\"disabled init\");\n }\n\n public static void logThrowableCrash(Throwable throwable) {\n logMarker(\"Exception\", throwable);\n }\n\n private static void logMarker(String mark) {\n logMarker(mark, null);\n }\n\n private static void logMarker(String mark, Throwable nullableException) {", "post_mask_code": "\n try (PrintWriter writer = new PrintWriter(new FileWriter(\"/home/lvuser/crash_tracking.txt\", true))) {\n writer.print(RUN_INSTANCE_UUID.toString());\n writer.print(\", \");\n writer.print(mark);\n writer.print(\", \");\n writer.print(new Date().toString());\n if (nullableException != null) {\n writer.print(\", \");\n nullableException.printStackTrace(writer);\n }\n writer.println();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n"} {"task_id": "Java_1824", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Team254/FRC-2018-Public/src/main/java/com/team254/lib/util/CrashTracker.java", "mask_start_position": 1148, "mask_end_position": 1711, "canonical_solution": "try (PrintWriter writer = new PrintWriter(new FileWriter(\"/home/lvuser/crash_tracking.txt\", true))) {\n writer.print(RUN_INSTANCE_UUID.toString());\n writer.print(\", \");\n writer.print(mark);\n writer.print(\", \");\n writer.print(new Date().toString());\n if (nullableException != null) {\n writer.print(\", \");\n nullableException.printStackTrace(writer);\n }\n writer.println();\n } catch (IOException e) {\n e.printStackTrace();\n }", "pre_mask_code": "package com.team254.lib.util;\n\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.Date;\nimport java.util.UUID;\n\n/**\n * Tracks start-up and caught crash events, logging them to a file which dosn't roll over\n */\npublic class CrashTracker {\n\n private static final UUID RUN_INSTANCE_UUID = UUID.randomUUID();\n\n public static void logRobotStartup() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotConstruction() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotInit() {\n logMarker(\"robot init\");\n }\n\n public static void logTeleopInit() {\n logMarker(\"teleop init\");\n }\n\n public static void logAutoInit() {\n logMarker(\"auto init\");\n }\n\n public static void logDisabledInit() {\n logMarker(\"disabled init\");\n }\n\n public static void logThrowableCrash(Throwable throwable) {\n logMarker(\"Exception\", throwable);\n }\n\n private static void logMarker(String mark) {\n logMarker(mark, null);\n }\n\n private static void logMarker(String mark, Throwable nullableException) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1825", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Team254/FRC-2018-Public/src/main/java/com/team254/lib/util/CrashTracker.java", "mask_start_position": 1716, "mask_end_position": 1717, "canonical_solution": "}", "pre_mask_code": "package com.team254.lib.util;\n\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.Date;\nimport java.util.UUID;\n\n/**\n * Tracks start-up and caught crash events, logging them to a file which dosn't roll over\n */\npublic class CrashTracker {\n\n private static final UUID RUN_INSTANCE_UUID = UUID.randomUUID();\n\n public static void logRobotStartup() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotConstruction() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotInit() {\n logMarker(\"robot init\");\n }\n\n public static void logTeleopInit() {\n logMarker(\"teleop init\");\n }\n\n public static void logAutoInit() {\n logMarker(\"auto init\");\n }\n\n public static void logDisabledInit() {\n logMarker(\"disabled init\");\n }\n\n public static void logThrowableCrash(Throwable throwable) {\n logMarker(\"Exception\", throwable);\n }\n\n private static void logMarker(String mark) {\n logMarker(mark, null);\n }\n\n private static void logMarker(String mark, Throwable nullableException) {\n try (PrintWriter writer = new PrintWriter(new FileWriter(\"/home/lvuser/crash_tracking.txt\", true))) {\n writer.print(RUN_INSTANCE_UUID.toString());\n writer.print(\", \");\n writer.print(mark);\n writer.print(\", \");\n writer.print(new Date().toString());\n if (nullableException != null) {\n writer.print(\", \");\n nullableException.printStackTrace(writer);\n }\n writer.println();\n } catch (IOException e) {\n e.printStackTrace();\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1826", "language": "Java", "task_type": "single_line", "source_file": "java/github/Team254/FRC-2018-Public/src/main/java/com/team254/lib/util/CrashTracker.java", "mask_start_position": 826, "mask_end_position": 853, "canonical_solution": "logMarker(\"disabled init\");", "pre_mask_code": "package com.team254.lib.util;\n\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.Date;\nimport java.util.UUID;\n\n/**\n * Tracks start-up and caught crash events, logging them to a file which dosn't roll over\n */\npublic class CrashTracker {\n\n private static final UUID RUN_INSTANCE_UUID = UUID.randomUUID();\n\n public static void logRobotStartup() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotConstruction() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotInit() {\n logMarker(\"robot init\");\n }\n\n public static void logTeleopInit() {\n logMarker(\"teleop init\");\n }\n\n public static void logAutoInit() {\n logMarker(\"auto init\");\n }\n\n public static void logDisabledInit() {\n ", "post_mask_code": "\n }\n\n public static void logThrowableCrash(Throwable throwable) {\n logMarker(\"Exception\", throwable);\n }\n\n private static void logMarker(String mark) {\n logMarker(mark, null);\n }\n\n private static void logMarker(String mark, Throwable nullableException) {\n try (PrintWriter writer = new PrintWriter(new FileWriter(\"/home/lvuser/crash_tracking.txt\", true))) {\n writer.print(RUN_INSTANCE_UUID.toString());\n writer.print(\", \");\n writer.print(mark);\n writer.print(\", \");\n writer.print(new Date().toString());\n if (nullableException != null) {\n writer.print(\", \");\n nullableException.printStackTrace(writer);\n }\n writer.println();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n"} {"task_id": "Java_1827", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Team254/FRC-2018-Public/src/main/java/com/team254/lib/util/CrashTracker.java", "mask_start_position": 1463, "mask_end_position": 1604, "canonical_solution": "if (nullableException != null) {\n writer.print(\", \");\n nullableException.printStackTrace(writer);\n }", "pre_mask_code": "package com.team254.lib.util;\n\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.Date;\nimport java.util.UUID;\n\n/**\n * Tracks start-up and caught crash events, logging them to a file which dosn't roll over\n */\npublic class CrashTracker {\n\n private static final UUID RUN_INSTANCE_UUID = UUID.randomUUID();\n\n public static void logRobotStartup() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotConstruction() {\n logMarker(\"robot startup\");\n }\n\n public static void logRobotInit() {\n logMarker(\"robot init\");\n }\n\n public static void logTeleopInit() {\n logMarker(\"teleop init\");\n }\n\n public static void logAutoInit() {\n logMarker(\"auto init\");\n }\n\n public static void logDisabledInit() {\n logMarker(\"disabled init\");\n }\n\n public static void logThrowableCrash(Throwable throwable) {\n logMarker(\"Exception\", throwable);\n }\n\n private static void logMarker(String mark) {\n logMarker(mark, null);\n }\n\n private static void logMarker(String mark, Throwable nullableException) {\n try (PrintWriter writer = new PrintWriter(new FileWriter(\"/home/lvuser/crash_tracking.txt\", true))) {\n writer.print(RUN_INSTANCE_UUID.toString());\n writer.print(\", \");\n writer.print(mark);\n writer.print(\", \");\n writer.print(new Date().toString());\n ", "post_mask_code": "\n writer.println();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n"} {"task_id": "Java_1828", "language": "Java", "task_type": "method_signature", "source_file": "java/github/java-port/clank/modules/org.clang.frontend/src/org/clang/frontend/impl/ModuleDependencyListener.java", "mask_start_position": 5767, "mask_end_position": 5806, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "/**\n * This file was converted to Java from the original LLVM source file. The original\n * source file follows the LLVM Release License, outlined below.\n *\n * ==============================================================================\n *\n * All rights reserved.\n *\n * Developed by:\n *\n * LLVM Team\n *\n * University of Illinois at Urbana-Champaign\n *\n * http://llvm.org\n *\n * ==============================================================================\n * Copyrights and Licenses for Third Party Software Distributed with LLVM:\n * ==============================================================================\n *\n * The following pieces of software have additional or alternate copyrights,\n * licenses, and/or restrictions:\n *\n * Program Directory\n * ------- ---------\n * Autoconf llvm/autoconf\n * llvm/projects/ModuleMaker/autoconf\n * Google Test llvm/utils/unittest/googletest\n * OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex}\n * pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT}\n * ARM contributions llvm/lib/Target/ARM/LICENSE.TXT\n * md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h\n */\npackage org.clang.frontend.impl;\n\nimport org.clank.support.*;\nimport org.llvm.adt.*;\nimport org.clang.serialization.*;\nimport org.clang.frontend.*;\n\n// / Private implementations for ModuleDependencyCollector\n@Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 28, old_source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", old_line = 26, FQN = \"(anonymous namespace)::ModuleDependencyListener\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListenerE\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListenerE\")\npublic class ModuleDependencyListener extends ASTReaderListener implements Destructors.ClassWithDestructor {\n\n private ModuleDependencyCollector Collector;\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 31, FQN = \"(anonymous namespace)::ModuleDependencyListener::ModuleDependencyListener\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListenerC1ERN5clang25ModuleDependencyCollectorE\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListenerC1ERN5clang25ModuleDependencyCollectorE\")\n public ModuleDependencyListener(ModuleDependencyCollector Collector) {\n // START JInit\n super();\n this.Collector = Collector;\n // END JInit\n }\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 33, FQN = \"(anonymous namespace)::ModuleDependencyListener::needsInputFileVisitation\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListener24needsInputFileVisitationEv\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListener24needsInputFileVisitationEv\")\n @Override\n public boolean needsInputFileVisitation() /* override*/\n {\n return true;\n }\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 34, FQN = \"(anonymous namespace)::ModuleDependencyListener::needsSystemInputFileVisitation\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListener30needsSystemInputFileVisitationEv\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListener30needsSystemInputFileVisitationEv\")\n @Override\n public boolean needsSystemInputFileVisitation() /* override*/\n {\n return true;\n }\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 35, old_source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", old_line = 87, FQN = \"(anonymous namespace)::ModuleDependencyListener::visitInputFile\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListener14visitInputFileEN4llvm9StringRefEbbb\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListener14visitInputFileEN4llvm9StringRefEbbb\")\n @Override\n public boolean visitInputFile(StringRef Filename, boolean IsSystem, boolean IsOverridden, boolean IsExplicitModule) /* override*/\n {\n Collector.addFile(new StringRef(Filename));\n return true;\n }\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 28, old_source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", old_line = 26, FQN = \"(anonymous namespace)::ModuleDependencyListener::~ModuleDependencyListener\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListenerD0Ev\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListenerD0Ev\")\n @Override\n public /*inline*/\n void $destroy() {\n super.$destroy();\n }\n\n ", "post_mask_code": "{\n return // NOI18N\n \"\" + \"Collector=\" + Collector + // NOI18N\n super.toString();\n }\n}\n"} {"task_id": "Java_1829", "language": "Java", "task_type": "method_body", "source_file": "java/github/java-port/clank/modules/org.clang.frontend/src/org/clang/frontend/impl/ModuleDependencyListener.java", "mask_start_position": 5806, "mask_end_position": 5914, "canonical_solution": "{\n return // NOI18N\n \"\" + \"Collector=\" + Collector + // NOI18N\n super.toString();\n }", "pre_mask_code": "/**\n * This file was converted to Java from the original LLVM source file. The original\n * source file follows the LLVM Release License, outlined below.\n *\n * ==============================================================================\n *\n * All rights reserved.\n *\n * Developed by:\n *\n * LLVM Team\n *\n * University of Illinois at Urbana-Champaign\n *\n * http://llvm.org\n *\n * ==============================================================================\n * Copyrights and Licenses for Third Party Software Distributed with LLVM:\n * ==============================================================================\n *\n * The following pieces of software have additional or alternate copyrights,\n * licenses, and/or restrictions:\n *\n * Program Directory\n * ------- ---------\n * Autoconf llvm/autoconf\n * llvm/projects/ModuleMaker/autoconf\n * Google Test llvm/utils/unittest/googletest\n * OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex}\n * pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT}\n * ARM contributions llvm/lib/Target/ARM/LICENSE.TXT\n * md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h\n */\npackage org.clang.frontend.impl;\n\nimport org.clank.support.*;\nimport org.llvm.adt.*;\nimport org.clang.serialization.*;\nimport org.clang.frontend.*;\n\n// / Private implementations for ModuleDependencyCollector\n@Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 28, old_source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", old_line = 26, FQN = \"(anonymous namespace)::ModuleDependencyListener\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListenerE\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListenerE\")\npublic class ModuleDependencyListener extends ASTReaderListener implements Destructors.ClassWithDestructor {\n\n private ModuleDependencyCollector Collector;\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 31, FQN = \"(anonymous namespace)::ModuleDependencyListener::ModuleDependencyListener\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListenerC1ERN5clang25ModuleDependencyCollectorE\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListenerC1ERN5clang25ModuleDependencyCollectorE\")\n public ModuleDependencyListener(ModuleDependencyCollector Collector) {\n // START JInit\n super();\n this.Collector = Collector;\n // END JInit\n }\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 33, FQN = \"(anonymous namespace)::ModuleDependencyListener::needsInputFileVisitation\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListener24needsInputFileVisitationEv\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListener24needsInputFileVisitationEv\")\n @Override\n public boolean needsInputFileVisitation() /* override*/\n {\n return true;\n }\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 34, FQN = \"(anonymous namespace)::ModuleDependencyListener::needsSystemInputFileVisitation\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListener30needsSystemInputFileVisitationEv\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListener30needsSystemInputFileVisitationEv\")\n @Override\n public boolean needsSystemInputFileVisitation() /* override*/\n {\n return true;\n }\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 35, old_source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", old_line = 87, FQN = \"(anonymous namespace)::ModuleDependencyListener::visitInputFile\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListener14visitInputFileEN4llvm9StringRefEbbb\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListener14visitInputFileEN4llvm9StringRefEbbb\")\n @Override\n public boolean visitInputFile(StringRef Filename, boolean IsSystem, boolean IsOverridden, boolean IsExplicitModule) /* override*/\n {\n Collector.addFile(new StringRef(Filename));\n return true;\n }\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 28, old_source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", old_line = 26, FQN = \"(anonymous namespace)::ModuleDependencyListener::~ModuleDependencyListener\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListenerD0Ev\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListenerD0Ev\")\n @Override\n public /*inline*/\n void $destroy() {\n super.$destroy();\n }\n\n @Override\n public String toString() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1830", "language": "Java", "task_type": "single_line", "source_file": "java/github/java-port/clank/modules/org.clang.frontend/src/org/clang/frontend/impl/ModuleDependencyListener.java", "mask_start_position": 3520, "mask_end_position": 3523, "canonical_solution": "ue;", "pre_mask_code": "/**\n * This file was converted to Java from the original LLVM source file. The original\n * source file follows the LLVM Release License, outlined below.\n *\n * ==============================================================================\n *\n * All rights reserved.\n *\n * Developed by:\n *\n * LLVM Team\n *\n * University of Illinois at Urbana-Champaign\n *\n * http://llvm.org\n *\n * ==============================================================================\n * Copyrights and Licenses for Third Party Software Distributed with LLVM:\n * ==============================================================================\n *\n * The following pieces of software have additional or alternate copyrights,\n * licenses, and/or restrictions:\n *\n * Program Directory\n * ------- ---------\n * Autoconf llvm/autoconf\n * llvm/projects/ModuleMaker/autoconf\n * Google Test llvm/utils/unittest/googletest\n * OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex}\n * pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT}\n * ARM contributions llvm/lib/Target/ARM/LICENSE.TXT\n * md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h\n */\npackage org.clang.frontend.impl;\n\nimport org.clank.support.*;\nimport org.llvm.adt.*;\nimport org.clang.serialization.*;\nimport org.clang.frontend.*;\n\n// / Private implementations for ModuleDependencyCollector\n@Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 28, old_source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", old_line = 26, FQN = \"(anonymous namespace)::ModuleDependencyListener\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListenerE\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListenerE\")\npublic class ModuleDependencyListener extends ASTReaderListener implements Destructors.ClassWithDestructor {\n\n private ModuleDependencyCollector Collector;\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 31, FQN = \"(anonymous namespace)::ModuleDependencyListener::ModuleDependencyListener\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListenerC1ERN5clang25ModuleDependencyCollectorE\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListenerC1ERN5clang25ModuleDependencyCollectorE\")\n public ModuleDependencyListener(ModuleDependencyCollector Collector) {\n // START JInit\n super();\n this.Collector = Collector;\n // END JInit\n }\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 33, FQN = \"(anonymous namespace)::ModuleDependencyListener::needsInputFileVisitation\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListener24needsInputFileVisitationEv\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListener24needsInputFileVisitationEv\")\n @Override\n public boolean needsInputFileVisitation() /* override*/\n {\n return tr", "post_mask_code": "\n }\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 34, FQN = \"(anonymous namespace)::ModuleDependencyListener::needsSystemInputFileVisitation\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListener30needsSystemInputFileVisitationEv\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListener30needsSystemInputFileVisitationEv\")\n @Override\n public boolean needsSystemInputFileVisitation() /* override*/\n {\n return true;\n }\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 35, old_source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", old_line = 87, FQN = \"(anonymous namespace)::ModuleDependencyListener::visitInputFile\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListener14visitInputFileEN4llvm9StringRefEbbb\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListener14visitInputFileEN4llvm9StringRefEbbb\")\n @Override\n public boolean visitInputFile(StringRef Filename, boolean IsSystem, boolean IsOverridden, boolean IsExplicitModule) /* override*/\n {\n Collector.addFile(new StringRef(Filename));\n return true;\n }\n\n @Converted(kind = Converted.Kind.AUTO, source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", line = 28, old_source = \"${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp\", old_line = 26, FQN = \"(anonymous namespace)::ModuleDependencyListener::~ModuleDependencyListener\", NM = \"_ZN12_GLOBAL__N_124ModuleDependencyListenerD0Ev\", cmd = \"jclank.sh -java-options=${SPUTNIK}/modules/org.clang.frontend/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp -nm=_ZN12_GLOBAL__N_124ModuleDependencyListenerD0Ev\")\n @Override\n public /*inline*/\n void $destroy() {\n super.$destroy();\n }\n\n @Override\n public String toString() {\n return // NOI18N\n \"\" + \"Collector=\" + Collector + // NOI18N\n super.toString();\n }\n}\n"} {"task_id": "Java_1831", "language": "Java", "task_type": "method_signature", "source_file": "java/github/alibaba/nacos/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckProcessorV2Delegate.java", "mask_start_position": 1731, "mask_end_position": 1769, "canonical_solution": "@Override\n public String getType() ", "pre_mask_code": "package com.alibaba.nacos.naming.healthcheck.v2.processor;\n\nimport com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;\nimport com.alibaba.nacos.naming.core.v2.pojo.Service;\nimport com.alibaba.nacos.naming.healthcheck.NoneHealthCheckProcessor;\nimport com.alibaba.nacos.naming.healthcheck.extend.HealthCheckExtendProvider;\nimport com.alibaba.nacos.naming.healthcheck.v2.HealthCheckTaskV2;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\n/**\n * Delegate of health check v2.x.\n *\n * @author nacos\n */\n@Component(\"healthCheckDelegateV2\")\npublic class HealthCheckProcessorV2Delegate implements HealthCheckProcessorV2 {\n\n private final Map healthCheckProcessorMap = new HashMap<>();\n\n public HealthCheckProcessorV2Delegate(HealthCheckExtendProvider provider) {\n provider.init();\n }\n\n @Autowired\n public void addProcessor(Collection processors) {\n healthCheckProcessorMap.putAll(processors.stream().filter(processor -> processor.getType() != null).collect(Collectors.toMap(HealthCheckProcessorV2::getType, processor -> processor)));\n }\n\n @Override\n public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata) {\n String type = metadata.getHealthyCheckType();\n HealthCheckProcessorV2 processor = healthCheckProcessorMap.get(type);\n if (processor == null) {\n processor = healthCheckProcessorMap.get(NoneHealthCheckProcessor.TYPE);\n }\n processor.process(task, service, metadata);\n }\n\n ", "post_mask_code": "{\n return null;\n }\n}\n"} {"task_id": "Java_1832", "language": "Java", "task_type": "method_body", "source_file": "java/github/alibaba/nacos/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckProcessorV2Delegate.java", "mask_start_position": 1100, "mask_end_position": 1300, "canonical_solution": "{\n healthCheckProcessorMap.putAll(processors.stream().filter(processor -> processor.getType() != null).collect(Collectors.toMap(HealthCheckProcessorV2::getType, processor -> processor)));\n }", "pre_mask_code": "package com.alibaba.nacos.naming.healthcheck.v2.processor;\n\nimport com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;\nimport com.alibaba.nacos.naming.core.v2.pojo.Service;\nimport com.alibaba.nacos.naming.healthcheck.NoneHealthCheckProcessor;\nimport com.alibaba.nacos.naming.healthcheck.extend.HealthCheckExtendProvider;\nimport com.alibaba.nacos.naming.healthcheck.v2.HealthCheckTaskV2;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\n/**\n * Delegate of health check v2.x.\n *\n * @author nacos\n */\n@Component(\"healthCheckDelegateV2\")\npublic class HealthCheckProcessorV2Delegate implements HealthCheckProcessorV2 {\n\n private final Map healthCheckProcessorMap = new HashMap<>();\n\n public HealthCheckProcessorV2Delegate(HealthCheckExtendProvider provider) {\n provider.init();\n }\n\n @Autowired\n public void addProcessor(Collection processors) ", "post_mask_code": "\n\n @Override\n public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata) {\n String type = metadata.getHealthyCheckType();\n HealthCheckProcessorV2 processor = healthCheckProcessorMap.get(type);\n if (processor == null) {\n processor = healthCheckProcessorMap.get(NoneHealthCheckProcessor.TYPE);\n }\n processor.process(task, service, metadata);\n }\n\n @Override\n public String getType() {\n return null;\n }\n}\n"} {"task_id": "Java_1833", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/alibaba/nacos/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckProcessorV2Delegate.java", "mask_start_position": 1408, "mask_end_position": 1462, "canonical_solution": "\n String type = metadata.getHealthyCheckType();", "pre_mask_code": "package com.alibaba.nacos.naming.healthcheck.v2.processor;\n\nimport com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;\nimport com.alibaba.nacos.naming.core.v2.pojo.Service;\nimport com.alibaba.nacos.naming.healthcheck.NoneHealthCheckProcessor;\nimport com.alibaba.nacos.naming.healthcheck.extend.HealthCheckExtendProvider;\nimport com.alibaba.nacos.naming.healthcheck.v2.HealthCheckTaskV2;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\n/**\n * Delegate of health check v2.x.\n *\n * @author nacos\n */\n@Component(\"healthCheckDelegateV2\")\npublic class HealthCheckProcessorV2Delegate implements HealthCheckProcessorV2 {\n\n private final Map healthCheckProcessorMap = new HashMap<>();\n\n public HealthCheckProcessorV2Delegate(HealthCheckExtendProvider provider) {\n provider.init();\n }\n\n @Autowired\n public void addProcessor(Collection processors) {\n healthCheckProcessorMap.putAll(processors.stream().filter(processor -> processor.getType() != null).collect(Collectors.toMap(HealthCheckProcessorV2::getType, processor -> processor)));\n }\n\n @Override\n public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata) {", "post_mask_code": "\n HealthCheckProcessorV2 processor = healthCheckProcessorMap.get(type);\n if (processor == null) {\n processor = healthCheckProcessorMap.get(NoneHealthCheckProcessor.TYPE);\n }\n processor.process(task, service, metadata);\n }\n\n @Override\n public String getType() {\n return null;\n }\n}\n"} {"task_id": "Java_1834", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/alibaba/nacos/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckProcessorV2Delegate.java", "mask_start_position": 1471, "mask_end_position": 1667, "canonical_solution": "HealthCheckProcessorV2 processor = healthCheckProcessorMap.get(type);\n if (processor == null) {\n processor = healthCheckProcessorMap.get(NoneHealthCheckProcessor.TYPE);\n }", "pre_mask_code": "package com.alibaba.nacos.naming.healthcheck.v2.processor;\n\nimport com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;\nimport com.alibaba.nacos.naming.core.v2.pojo.Service;\nimport com.alibaba.nacos.naming.healthcheck.NoneHealthCheckProcessor;\nimport com.alibaba.nacos.naming.healthcheck.extend.HealthCheckExtendProvider;\nimport com.alibaba.nacos.naming.healthcheck.v2.HealthCheckTaskV2;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\n/**\n * Delegate of health check v2.x.\n *\n * @author nacos\n */\n@Component(\"healthCheckDelegateV2\")\npublic class HealthCheckProcessorV2Delegate implements HealthCheckProcessorV2 {\n\n private final Map healthCheckProcessorMap = new HashMap<>();\n\n public HealthCheckProcessorV2Delegate(HealthCheckExtendProvider provider) {\n provider.init();\n }\n\n @Autowired\n public void addProcessor(Collection processors) {\n healthCheckProcessorMap.putAll(processors.stream().filter(processor -> processor.getType() != null).collect(Collectors.toMap(HealthCheckProcessorV2::getType, processor -> processor)));\n }\n\n @Override\n public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata) {\n String type = metadata.getHealthyCheckType();\n ", "post_mask_code": "\n processor.process(task, service, metadata);\n }\n\n @Override\n public String getType() {\n return null;\n }\n}\n"} {"task_id": "Java_1835", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/alibaba/nacos/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckProcessorV2Delegate.java", "mask_start_position": 1676, "mask_end_position": 1725, "canonical_solution": "processor.process(task, service, metadata);\n }", "pre_mask_code": "package com.alibaba.nacos.naming.healthcheck.v2.processor;\n\nimport com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;\nimport com.alibaba.nacos.naming.core.v2.pojo.Service;\nimport com.alibaba.nacos.naming.healthcheck.NoneHealthCheckProcessor;\nimport com.alibaba.nacos.naming.healthcheck.extend.HealthCheckExtendProvider;\nimport com.alibaba.nacos.naming.healthcheck.v2.HealthCheckTaskV2;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\n/**\n * Delegate of health check v2.x.\n *\n * @author nacos\n */\n@Component(\"healthCheckDelegateV2\")\npublic class HealthCheckProcessorV2Delegate implements HealthCheckProcessorV2 {\n\n private final Map healthCheckProcessorMap = new HashMap<>();\n\n public HealthCheckProcessorV2Delegate(HealthCheckExtendProvider provider) {\n provider.init();\n }\n\n @Autowired\n public void addProcessor(Collection processors) {\n healthCheckProcessorMap.putAll(processors.stream().filter(processor -> processor.getType() != null).collect(Collectors.toMap(HealthCheckProcessorV2::getType, processor -> processor)));\n }\n\n @Override\n public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata) {\n String type = metadata.getHealthyCheckType();\n HealthCheckProcessorV2 processor = healthCheckProcessorMap.get(type);\n if (processor == null) {\n processor = healthCheckProcessorMap.get(NoneHealthCheckProcessor.TYPE);\n }\n ", "post_mask_code": "\n\n @Override\n public String getType() {\n return null;\n }\n}\n"} {"task_id": "Java_1836", "language": "Java", "task_type": "single_line", "source_file": "java/github/alibaba/nacos/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckProcessorV2Delegate.java", "mask_start_position": 1530, "mask_end_position": 1540, "canonical_solution": "get(type);", "pre_mask_code": "package com.alibaba.nacos.naming.healthcheck.v2.processor;\n\nimport com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;\nimport com.alibaba.nacos.naming.core.v2.pojo.Service;\nimport com.alibaba.nacos.naming.healthcheck.NoneHealthCheckProcessor;\nimport com.alibaba.nacos.naming.healthcheck.extend.HealthCheckExtendProvider;\nimport com.alibaba.nacos.naming.healthcheck.v2.HealthCheckTaskV2;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\n/**\n * Delegate of health check v2.x.\n *\n * @author nacos\n */\n@Component(\"healthCheckDelegateV2\")\npublic class HealthCheckProcessorV2Delegate implements HealthCheckProcessorV2 {\n\n private final Map healthCheckProcessorMap = new HashMap<>();\n\n public HealthCheckProcessorV2Delegate(HealthCheckExtendProvider provider) {\n provider.init();\n }\n\n @Autowired\n public void addProcessor(Collection processors) {\n healthCheckProcessorMap.putAll(processors.stream().filter(processor -> processor.getType() != null).collect(Collectors.toMap(HealthCheckProcessorV2::getType, processor -> processor)));\n }\n\n @Override\n public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata) {\n String type = metadata.getHealthyCheckType();\n HealthCheckProcessorV2 processor = healthCheckProcessorMap.", "post_mask_code": "\n if (processor == null) {\n processor = healthCheckProcessorMap.get(NoneHealthCheckProcessor.TYPE);\n }\n processor.process(task, service, metadata);\n }\n\n @Override\n public String getType() {\n return null;\n }\n}\n"} {"task_id": "Java_1837", "language": "Java", "task_type": "if_statement", "source_file": "java/github/alibaba/nacos/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckProcessorV2Delegate.java", "mask_start_position": 1549, "mask_end_position": 1667, "canonical_solution": "if (processor == null) {\n processor = healthCheckProcessorMap.get(NoneHealthCheckProcessor.TYPE);\n }", "pre_mask_code": "package com.alibaba.nacos.naming.healthcheck.v2.processor;\n\nimport com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;\nimport com.alibaba.nacos.naming.core.v2.pojo.Service;\nimport com.alibaba.nacos.naming.healthcheck.NoneHealthCheckProcessor;\nimport com.alibaba.nacos.naming.healthcheck.extend.HealthCheckExtendProvider;\nimport com.alibaba.nacos.naming.healthcheck.v2.HealthCheckTaskV2;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\n/**\n * Delegate of health check v2.x.\n *\n * @author nacos\n */\n@Component(\"healthCheckDelegateV2\")\npublic class HealthCheckProcessorV2Delegate implements HealthCheckProcessorV2 {\n\n private final Map healthCheckProcessorMap = new HashMap<>();\n\n public HealthCheckProcessorV2Delegate(HealthCheckExtendProvider provider) {\n provider.init();\n }\n\n @Autowired\n public void addProcessor(Collection processors) {\n healthCheckProcessorMap.putAll(processors.stream().filter(processor -> processor.getType() != null).collect(Collectors.toMap(HealthCheckProcessorV2::getType, processor -> processor)));\n }\n\n @Override\n public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata) {\n String type = metadata.getHealthyCheckType();\n HealthCheckProcessorV2 processor = healthCheckProcessorMap.get(type);\n ", "post_mask_code": "\n processor.process(task, service, metadata);\n }\n\n @Override\n public String getType() {\n return null;\n }\n}\n"} {"task_id": "Java_1838", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/apex-core/engine/src/main/java/com/datatorrent/stram/util/StableWrapper.java", "mask_start_position": 1232, "mask_end_position": 1311, "canonical_solution": "@Override\n public int compare(StableWrapper o1, StableWrapper o2) ", "pre_mask_code": "package com.datatorrent.stram.util;\n\nimport java.util.Comparator;\n\n/**\n * Used to wrap around long int values safely

\n *
\n * Needed to ensure that windowId wrap around safely
\n * {@see StablePriorityQueue}
\n *
\n *\n * @since 0.3.2\n */\nclass StableWrapper {\n\n public final int id;\n\n public final E object;\n\n public StableWrapper(E o, int id) {\n this.id = id;\n this.object = o;\n }\n\n static class NaturalComparator implements Comparator> {\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) {\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n int ret = ((Comparable) o1.object).compareTo(o2.object);\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }\n return ret;\n }\n }\n\n static class ProvidedComparator implements Comparator> {\n\n public final Comparator comparator;\n\n public ProvidedComparator(Comparator comparator) {\n this.comparator = comparator;\n }\n\n ", "post_mask_code": "{\n int ret = comparator.compare(o1.object, o2.object);\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }\n return ret;\n }\n }\n}\n"} {"task_id": "Java_1839", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/apex-core/engine/src/main/java/com/datatorrent/stram/util/StableWrapper.java", "mask_start_position": 592, "mask_end_position": 955, "canonical_solution": "{\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n int ret = ((Comparable) o1.object).compareTo(o2.object);\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }\n return ret;\n }", "pre_mask_code": "package com.datatorrent.stram.util;\n\nimport java.util.Comparator;\n\n/**\n * Used to wrap around long int values safely

\n *
\n * Needed to ensure that windowId wrap around safely
\n * {@see StablePriorityQueue}
\n *
\n *\n * @since 0.3.2\n */\nclass StableWrapper {\n\n public final int id;\n\n public final E object;\n\n public StableWrapper(E o, int id) {\n this.id = id;\n this.object = o;\n }\n\n static class NaturalComparator implements Comparator> {\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) ", "post_mask_code": "\n }\n\n static class ProvidedComparator implements Comparator> {\n\n public final Comparator comparator;\n\n public ProvidedComparator(Comparator comparator) {\n this.comparator = comparator;\n }\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) {\n int ret = comparator.compare(o1.object, o2.object);\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }\n return ret;\n }\n }\n}\n"} {"task_id": "Java_1840", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/apex-core/engine/src/main/java/com/datatorrent/stram/util/StableWrapper.java", "mask_start_position": 593, "mask_end_position": 721, "canonical_solution": "\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n int ret = ((Comparable) o1.object).compareTo(o2.object);", "pre_mask_code": "package com.datatorrent.stram.util;\n\nimport java.util.Comparator;\n\n/**\n * Used to wrap around long int values safely

\n *
\n * Needed to ensure that windowId wrap around safely
\n * {@see StablePriorityQueue}
\n *
\n *\n * @since 0.3.2\n */\nclass StableWrapper {\n\n public final int id;\n\n public final E object;\n\n public StableWrapper(E o, int id) {\n this.id = id;\n this.object = o;\n }\n\n static class NaturalComparator implements Comparator> {\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) {", "post_mask_code": "\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }\n return ret;\n }\n }\n\n static class ProvidedComparator implements Comparator> {\n\n public final Comparator comparator;\n\n public ProvidedComparator(Comparator comparator) {\n this.comparator = comparator;\n }\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) {\n int ret = comparator.compare(o1.object, o2.object);\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }\n return ret;\n }\n }\n}\n"} {"task_id": "Java_1841", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/apex-core/engine/src/main/java/com/datatorrent/stram/util/StableWrapper.java", "mask_start_position": 734, "mask_end_position": 921, "canonical_solution": "if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }", "pre_mask_code": "package com.datatorrent.stram.util;\n\nimport java.util.Comparator;\n\n/**\n * Used to wrap around long int values safely

\n *
\n * Needed to ensure that windowId wrap around safely
\n * {@see StablePriorityQueue}
\n *
\n *\n * @since 0.3.2\n */\nclass StableWrapper {\n\n public final int id;\n\n public final E object;\n\n public StableWrapper(E o, int id) {\n this.id = id;\n this.object = o;\n }\n\n static class NaturalComparator implements Comparator> {\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) {\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n int ret = ((Comparable) o1.object).compareTo(o2.object);\n ", "post_mask_code": "\n return ret;\n }\n }\n\n static class ProvidedComparator implements Comparator> {\n\n public final Comparator comparator;\n\n public ProvidedComparator(Comparator comparator) {\n this.comparator = comparator;\n }\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) {\n int ret = comparator.compare(o1.object, o2.object);\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }\n return ret;\n }\n }\n}\n"} {"task_id": "Java_1842", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/apex-core/engine/src/main/java/com/datatorrent/stram/util/StableWrapper.java", "mask_start_position": 934, "mask_end_position": 955, "canonical_solution": "return ret;\n }", "pre_mask_code": "package com.datatorrent.stram.util;\n\nimport java.util.Comparator;\n\n/**\n * Used to wrap around long int values safely

\n *
\n * Needed to ensure that windowId wrap around safely
\n * {@see StablePriorityQueue}
\n *
\n *\n * @since 0.3.2\n */\nclass StableWrapper {\n\n public final int id;\n\n public final E object;\n\n public StableWrapper(E o, int id) {\n this.id = id;\n this.object = o;\n }\n\n static class NaturalComparator implements Comparator> {\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) {\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n int ret = ((Comparable) o1.object).compareTo(o2.object);\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }\n ", "post_mask_code": "\n }\n\n static class ProvidedComparator implements Comparator> {\n\n public final Comparator comparator;\n\n public ProvidedComparator(Comparator comparator) {\n this.comparator = comparator;\n }\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) {\n int ret = comparator.compare(o1.object, o2.object);\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }\n return ret;\n }\n }\n}\n"} {"task_id": "Java_1843", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/apex-core/engine/src/main/java/com/datatorrent/stram/util/StableWrapper.java", "mask_start_position": 942, "mask_end_position": 945, "canonical_solution": "et;", "pre_mask_code": "package com.datatorrent.stram.util;\n\nimport java.util.Comparator;\n\n/**\n * Used to wrap around long int values safely

\n *
\n * Needed to ensure that windowId wrap around safely
\n * {@see StablePriorityQueue}
\n *
\n *\n * @since 0.3.2\n */\nclass StableWrapper {\n\n public final int id;\n\n public final E object;\n\n public StableWrapper(E o, int id) {\n this.id = id;\n this.object = o;\n }\n\n static class NaturalComparator implements Comparator> {\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) {\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n int ret = ((Comparable) o1.object).compareTo(o2.object);\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }\n return r", "post_mask_code": "\n }\n }\n\n static class ProvidedComparator implements Comparator> {\n\n public final Comparator comparator;\n\n public ProvidedComparator(Comparator comparator) {\n this.comparator = comparator;\n }\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) {\n int ret = comparator.compare(o1.object, o2.object);\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }\n return ret;\n }\n }\n}\n"} {"task_id": "Java_1844", "language": "Java", "task_type": "if_statement", "source_file": "java/github/apache/apex-core/engine/src/main/java/com/datatorrent/stram/util/StableWrapper.java", "mask_start_position": 1494, "mask_end_position": 1562, "canonical_solution": "if (o1.id < o2.id) {\n ret = -1;\n }", "pre_mask_code": "package com.datatorrent.stram.util;\n\nimport java.util.Comparator;\n\n/**\n * Used to wrap around long int values safely

\n *
\n * Needed to ensure that windowId wrap around safely
\n * {@see StablePriorityQueue}
\n *
\n *\n * @since 0.3.2\n */\nclass StableWrapper {\n\n public final int id;\n\n public final E object;\n\n public StableWrapper(E o, int id) {\n this.id = id;\n this.object = o;\n }\n\n static class NaturalComparator implements Comparator> {\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) {\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n int ret = ((Comparable) o1.object).compareTo(o2.object);\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else if (o1.id < o2.id) {\n ret = -1;\n }\n }\n return ret;\n }\n }\n\n static class ProvidedComparator implements Comparator> {\n\n public final Comparator comparator;\n\n public ProvidedComparator(Comparator comparator) {\n this.comparator = comparator;\n }\n\n @Override\n public int compare(StableWrapper o1, StableWrapper o2) {\n int ret = comparator.compare(o1.object, o2.object);\n if (ret == 0) {\n if (o1.id > o2.id) {\n ret = 1;\n } else ", "post_mask_code": "\n }\n return ret;\n }\n }\n}\n"} {"task_id": "Java_1845", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openjdk/jmc/core/org.openjdk.jmc.flightrecorder.rules/src/main/java/org/openjdk/jmc/flightrecorder/rules/util/SlidingWindowToolkit.java", "mask_start_position": 9877, "mask_end_position": 9942, "canonical_solution": "@Override\n public int compare(IQuantity o1, IQuantity o2) ", "pre_mask_code": "/*\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n *\n */\npackage org.openjdk.jmc.flightrecorder.rules.util;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.concurrent.FutureTask;\nimport org.openjdk.jmc.common.item.IItem;\nimport org.openjdk.jmc.common.item.IItemCollection;\nimport org.openjdk.jmc.common.item.IItemFilter;\nimport org.openjdk.jmc.common.item.IMemberAccessor;\nimport org.openjdk.jmc.common.item.ItemFilters;\nimport org.openjdk.jmc.common.unit.IQuantity;\nimport org.openjdk.jmc.common.unit.IRange;\nimport org.openjdk.jmc.common.unit.QuantityRange;\nimport org.openjdk.jmc.common.util.Pair;\nimport org.openjdk.jmc.flightrecorder.JfrAttributes;\nimport org.openjdk.jmc.flightrecorder.rules.IResult;\n\n/**\n * Utility functions and interfaces for doing sliding window calculations.\n */\npublic class SlidingWindowToolkit {\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowOrdered}\n */\n public interface IOrderedWindowVisitor {\n\n void visitWindow(Iterator items);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, looping through items once, removing from the start\n * and adding and the end of a windowItem set to match the current time window. items.\n *

\n * Suitable if the items are guaranteed to be ordered.\n *\n * @param callback\n * method that can do calculations on the items in the window\n * @param items\n * input items\n * @param posAccessor\n * an accessor that should give a position value that is used with windowsSize and\n * slideSize\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be, if slideSize is {@code null}, it will slide one item\n * at a time\n */\n public static void slidingWindowOrdered(IOrderedWindowVisitor callback, Iterator items, IMemberAccessor posAccessor, IQuantity windowSize, IQuantity slideSize) {\n IQuantity windowStart = null;\n List windowItems = new ArrayList<>();\n for (Iterator iterator = items; iterator.hasNext() && callback.shouldContinue(); ) {\n IItem item = iterator.next();\n if (windowItems.isEmpty()) {\n windowStart = posAccessor.getMember(item);\n } else {\n windowStart = posAccessor.getMember(windowItems.get(0));\n }\n windowItems.add(item);\n IQuantity windowEnd = posAccessor.getMember(item);\n while (iterator.hasNext() && windowEnd.subtract(windowSize).compareTo(windowStart) < 0 && callback.shouldContinue()) {\n IItem next = iterator.next();\n windowEnd = posAccessor.getMember(next);\n windowItems.add(next);\n }\n callback.visitWindow(windowItems.iterator());\n // FIXME: What should we do about empty time intervals?\n if (slideSize == null) {\n if (windowItems.size() > 1) {\n windowItems.remove(0);\n }\n } else {\n IQuantity newStart = windowStart.add(slideSize);\n for (Iterator it = windowItems.iterator(); it.hasNext() && callback.shouldContinue(); ) {\n IItem wi = it.next();\n if (posAccessor.getMember(wi).compareTo(newStart) < 0) {\n it.remove();\n } else {\n break;\n }\n }\n }\n }\n }\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowUnordered}\n */\n public interface IUnorderedWindowVisitor {\n\n void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize) {\n slidingWindowUnordered(callback, items, windowSize, slideSize, false);\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n * @param includeIntersecting\n * if the window filter should include events intersecting the window, or just those\n * with end time in the window. It's up to the caller to take this into account and\n * for example cap event duration to the window timespan.\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize, boolean includeIntersecting) {\n IQuantity first = includeIntersecting ? RulesToolkit.getEarliestStartTime(items) : RulesToolkit.getEarliestEndTime(items);\n IQuantity last = RulesToolkit.getLatestEndTime(items);\n if (first == null) {\n return;\n }\n IQuantity windowStart = first;\n IQuantity windowEnd = windowStart.add(windowSize);\n do {\n IItemFilter window = includeIntersecting ? ItemFilters.rangeIntersects(JfrAttributes.LIFETIME, QuantityRange.createWithEnd(windowStart, windowEnd)) : ItemFilters.interval(JfrAttributes.END_TIME, windowStart, true, windowEnd, true);\n IItemCollection windowItems = items.apply(window);\n callback.visitWindow(windowItems, windowStart, windowEnd);\n windowStart = windowStart.add(slideSize);\n windowEnd = windowEnd.add(slideSize);\n } while (windowStart.compareTo(last) < 0 && callback.shouldContinue());\n }\n\n /**\n * Value function used when calling\n * {@link SlidingWindowToolkit#slidingWindowUnorderedMinMaxValue}\n */\n public interface IUnorderedWindowValueFunction {\n\n V getValue(IItemCollection items, IQuantity startTime, IQuantity endTime);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, QUANTITY_COMPARATOR, max, includeIntersecting);\n }\n\n private static final Comparator QUANTITY_COMPARATOR = new Comparator() {\n\n ", "post_mask_code": "{\n return o1.compareTo(o2);\n }\n };\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, valueComparator, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n final List>> valueList = new ArrayList<>();\n slidingWindowUnordered(new IUnorderedWindowVisitor() {\n\n @Override\n public void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime) {\n V value = valueFunction.getValue(items, startTime, endTime);\n if (value != null) {\n valueList.add(new Pair<>(value, QuantityRange.createWithEnd(startTime, endTime)));\n }\n }\n\n @Override\n public boolean shouldContinue() {\n return !cancellationSupplier.isCancelled();\n }\n }, items, windowSize, slideSize, includeIntersecting);\n Comparator>> comparator = new Comparator>>() {\n\n @Override\n public int compare(Pair> o1, Pair> o2) {\n return valueComparator.compare(o1.left, o2.left);\n }\n };\n if (valueList.isEmpty()) {\n return null;\n }\n Pair> minMaxWindow = max ? Collections.max(valueList, comparator) : Collections.min(valueList, comparator);\n return minMaxWindow;\n }\n}\n"} {"task_id": "Java_1846", "language": "Java", "task_type": "method_body", "source_file": "java/github/openjdk/jmc/core/org.openjdk.jmc.flightrecorder.rules/src/main/java/org/openjdk/jmc/flightrecorder/rules/util/SlidingWindowToolkit.java", "mask_start_position": 11156, "mask_end_position": 11438, "canonical_solution": "{\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, valueComparator, max, includeIntersecting);\n }", "pre_mask_code": "/*\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n *\n */\npackage org.openjdk.jmc.flightrecorder.rules.util;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.concurrent.FutureTask;\nimport org.openjdk.jmc.common.item.IItem;\nimport org.openjdk.jmc.common.item.IItemCollection;\nimport org.openjdk.jmc.common.item.IItemFilter;\nimport org.openjdk.jmc.common.item.IMemberAccessor;\nimport org.openjdk.jmc.common.item.ItemFilters;\nimport org.openjdk.jmc.common.unit.IQuantity;\nimport org.openjdk.jmc.common.unit.IRange;\nimport org.openjdk.jmc.common.unit.QuantityRange;\nimport org.openjdk.jmc.common.util.Pair;\nimport org.openjdk.jmc.flightrecorder.JfrAttributes;\nimport org.openjdk.jmc.flightrecorder.rules.IResult;\n\n/**\n * Utility functions and interfaces for doing sliding window calculations.\n */\npublic class SlidingWindowToolkit {\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowOrdered}\n */\n public interface IOrderedWindowVisitor {\n\n void visitWindow(Iterator items);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, looping through items once, removing from the start\n * and adding and the end of a windowItem set to match the current time window. items.\n *

\n * Suitable if the items are guaranteed to be ordered.\n *\n * @param callback\n * method that can do calculations on the items in the window\n * @param items\n * input items\n * @param posAccessor\n * an accessor that should give a position value that is used with windowsSize and\n * slideSize\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be, if slideSize is {@code null}, it will slide one item\n * at a time\n */\n public static void slidingWindowOrdered(IOrderedWindowVisitor callback, Iterator items, IMemberAccessor posAccessor, IQuantity windowSize, IQuantity slideSize) {\n IQuantity windowStart = null;\n List windowItems = new ArrayList<>();\n for (Iterator iterator = items; iterator.hasNext() && callback.shouldContinue(); ) {\n IItem item = iterator.next();\n if (windowItems.isEmpty()) {\n windowStart = posAccessor.getMember(item);\n } else {\n windowStart = posAccessor.getMember(windowItems.get(0));\n }\n windowItems.add(item);\n IQuantity windowEnd = posAccessor.getMember(item);\n while (iterator.hasNext() && windowEnd.subtract(windowSize).compareTo(windowStart) < 0 && callback.shouldContinue()) {\n IItem next = iterator.next();\n windowEnd = posAccessor.getMember(next);\n windowItems.add(next);\n }\n callback.visitWindow(windowItems.iterator());\n // FIXME: What should we do about empty time intervals?\n if (slideSize == null) {\n if (windowItems.size() > 1) {\n windowItems.remove(0);\n }\n } else {\n IQuantity newStart = windowStart.add(slideSize);\n for (Iterator it = windowItems.iterator(); it.hasNext() && callback.shouldContinue(); ) {\n IItem wi = it.next();\n if (posAccessor.getMember(wi).compareTo(newStart) < 0) {\n it.remove();\n } else {\n break;\n }\n }\n }\n }\n }\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowUnordered}\n */\n public interface IUnorderedWindowVisitor {\n\n void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize) {\n slidingWindowUnordered(callback, items, windowSize, slideSize, false);\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n * @param includeIntersecting\n * if the window filter should include events intersecting the window, or just those\n * with end time in the window. It's up to the caller to take this into account and\n * for example cap event duration to the window timespan.\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize, boolean includeIntersecting) {\n IQuantity first = includeIntersecting ? RulesToolkit.getEarliestStartTime(items) : RulesToolkit.getEarliestEndTime(items);\n IQuantity last = RulesToolkit.getLatestEndTime(items);\n if (first == null) {\n return;\n }\n IQuantity windowStart = first;\n IQuantity windowEnd = windowStart.add(windowSize);\n do {\n IItemFilter window = includeIntersecting ? ItemFilters.rangeIntersects(JfrAttributes.LIFETIME, QuantityRange.createWithEnd(windowStart, windowEnd)) : ItemFilters.interval(JfrAttributes.END_TIME, windowStart, true, windowEnd, true);\n IItemCollection windowItems = items.apply(window);\n callback.visitWindow(windowItems, windowStart, windowEnd);\n windowStart = windowStart.add(slideSize);\n windowEnd = windowEnd.add(slideSize);\n } while (windowStart.compareTo(last) < 0 && callback.shouldContinue());\n }\n\n /**\n * Value function used when calling\n * {@link SlidingWindowToolkit#slidingWindowUnorderedMinMaxValue}\n */\n public interface IUnorderedWindowValueFunction {\n\n V getValue(IItemCollection items, IQuantity startTime, IQuantity endTime);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, QUANTITY_COMPARATOR, max, includeIntersecting);\n }\n\n private static final Comparator QUANTITY_COMPARATOR = new Comparator() {\n\n @Override\n public int compare(IQuantity o1, IQuantity o2) {\n return o1.compareTo(o2);\n }\n };\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) ", "post_mask_code": "\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n final List>> valueList = new ArrayList<>();\n slidingWindowUnordered(new IUnorderedWindowVisitor() {\n\n @Override\n public void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime) {\n V value = valueFunction.getValue(items, startTime, endTime);\n if (value != null) {\n valueList.add(new Pair<>(value, QuantityRange.createWithEnd(startTime, endTime)));\n }\n }\n\n @Override\n public boolean shouldContinue() {\n return !cancellationSupplier.isCancelled();\n }\n }, items, windowSize, slideSize, includeIntersecting);\n Comparator>> comparator = new Comparator>>() {\n\n @Override\n public int compare(Pair> o1, Pair> o2) {\n return valueComparator.compare(o1.left, o2.left);\n }\n };\n if (valueList.isEmpty()) {\n return null;\n }\n Pair> minMaxWindow = max ? Collections.max(valueList, comparator) : Collections.min(valueList, comparator);\n return minMaxWindow;\n }\n}\n"} {"task_id": "Java_1847", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/openjdk/jmc/core/org.openjdk.jmc.flightrecorder.rules/src/main/java/org/openjdk/jmc/flightrecorder/rules/util/SlidingWindowToolkit.java", "mask_start_position": 2204, "mask_end_position": 2242, "canonical_solution": "\n IQuantity windowStart = null;", "pre_mask_code": "/*\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n *\n */\npackage org.openjdk.jmc.flightrecorder.rules.util;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.concurrent.FutureTask;\nimport org.openjdk.jmc.common.item.IItem;\nimport org.openjdk.jmc.common.item.IItemCollection;\nimport org.openjdk.jmc.common.item.IItemFilter;\nimport org.openjdk.jmc.common.item.IMemberAccessor;\nimport org.openjdk.jmc.common.item.ItemFilters;\nimport org.openjdk.jmc.common.unit.IQuantity;\nimport org.openjdk.jmc.common.unit.IRange;\nimport org.openjdk.jmc.common.unit.QuantityRange;\nimport org.openjdk.jmc.common.util.Pair;\nimport org.openjdk.jmc.flightrecorder.JfrAttributes;\nimport org.openjdk.jmc.flightrecorder.rules.IResult;\n\n/**\n * Utility functions and interfaces for doing sliding window calculations.\n */\npublic class SlidingWindowToolkit {\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowOrdered}\n */\n public interface IOrderedWindowVisitor {\n\n void visitWindow(Iterator items);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, looping through items once, removing from the start\n * and adding and the end of a windowItem set to match the current time window. items.\n *

\n * Suitable if the items are guaranteed to be ordered.\n *\n * @param callback\n * method that can do calculations on the items in the window\n * @param items\n * input items\n * @param posAccessor\n * an accessor that should give a position value that is used with windowsSize and\n * slideSize\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be, if slideSize is {@code null}, it will slide one item\n * at a time\n */\n public static void slidingWindowOrdered(IOrderedWindowVisitor callback, Iterator items, IMemberAccessor posAccessor, IQuantity windowSize, IQuantity slideSize) {", "post_mask_code": "\n List windowItems = new ArrayList<>();\n for (Iterator iterator = items; iterator.hasNext() && callback.shouldContinue(); ) {\n IItem item = iterator.next();\n if (windowItems.isEmpty()) {\n windowStart = posAccessor.getMember(item);\n } else {\n windowStart = posAccessor.getMember(windowItems.get(0));\n }\n windowItems.add(item);\n IQuantity windowEnd = posAccessor.getMember(item);\n while (iterator.hasNext() && windowEnd.subtract(windowSize).compareTo(windowStart) < 0 && callback.shouldContinue()) {\n IItem next = iterator.next();\n windowEnd = posAccessor.getMember(next);\n windowItems.add(next);\n }\n callback.visitWindow(windowItems.iterator());\n // FIXME: What should we do about empty time intervals?\n if (slideSize == null) {\n if (windowItems.size() > 1) {\n windowItems.remove(0);\n }\n } else {\n IQuantity newStart = windowStart.add(slideSize);\n for (Iterator it = windowItems.iterator(); it.hasNext() && callback.shouldContinue(); ) {\n IItem wi = it.next();\n if (posAccessor.getMember(wi).compareTo(newStart) < 0) {\n it.remove();\n } else {\n break;\n }\n }\n }\n }\n }\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowUnordered}\n */\n public interface IUnorderedWindowVisitor {\n\n void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize) {\n slidingWindowUnordered(callback, items, windowSize, slideSize, false);\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n * @param includeIntersecting\n * if the window filter should include events intersecting the window, or just those\n * with end time in the window. It's up to the caller to take this into account and\n * for example cap event duration to the window timespan.\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize, boolean includeIntersecting) {\n IQuantity first = includeIntersecting ? RulesToolkit.getEarliestStartTime(items) : RulesToolkit.getEarliestEndTime(items);\n IQuantity last = RulesToolkit.getLatestEndTime(items);\n if (first == null) {\n return;\n }\n IQuantity windowStart = first;\n IQuantity windowEnd = windowStart.add(windowSize);\n do {\n IItemFilter window = includeIntersecting ? ItemFilters.rangeIntersects(JfrAttributes.LIFETIME, QuantityRange.createWithEnd(windowStart, windowEnd)) : ItemFilters.interval(JfrAttributes.END_TIME, windowStart, true, windowEnd, true);\n IItemCollection windowItems = items.apply(window);\n callback.visitWindow(windowItems, windowStart, windowEnd);\n windowStart = windowStart.add(slideSize);\n windowEnd = windowEnd.add(slideSize);\n } while (windowStart.compareTo(last) < 0 && callback.shouldContinue());\n }\n\n /**\n * Value function used when calling\n * {@link SlidingWindowToolkit#slidingWindowUnorderedMinMaxValue}\n */\n public interface IUnorderedWindowValueFunction {\n\n V getValue(IItemCollection items, IQuantity startTime, IQuantity endTime);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, QUANTITY_COMPARATOR, max, includeIntersecting);\n }\n\n private static final Comparator QUANTITY_COMPARATOR = new Comparator() {\n\n @Override\n public int compare(IQuantity o1, IQuantity o2) {\n return o1.compareTo(o2);\n }\n };\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, valueComparator, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n final List>> valueList = new ArrayList<>();\n slidingWindowUnordered(new IUnorderedWindowVisitor() {\n\n @Override\n public void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime) {\n V value = valueFunction.getValue(items, startTime, endTime);\n if (value != null) {\n valueList.add(new Pair<>(value, QuantityRange.createWithEnd(startTime, endTime)));\n }\n }\n\n @Override\n public boolean shouldContinue() {\n return !cancellationSupplier.isCancelled();\n }\n }, items, windowSize, slideSize, includeIntersecting);\n Comparator>> comparator = new Comparator>>() {\n\n @Override\n public int compare(Pair> o1, Pair> o2) {\n return valueComparator.compare(o1.left, o2.left);\n }\n };\n if (valueList.isEmpty()) {\n return null;\n }\n Pair> minMaxWindow = max ? Collections.max(valueList, comparator) : Collections.min(valueList, comparator);\n return minMaxWindow;\n }\n}\n"} {"task_id": "Java_1848", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/openjdk/jmc/core/org.openjdk.jmc.flightrecorder.rules/src/main/java/org/openjdk/jmc/flightrecorder/rules/util/SlidingWindowToolkit.java", "mask_start_position": 2251, "mask_end_position": 2295, "canonical_solution": "List windowItems = new ArrayList<>();", "pre_mask_code": "/*\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n *\n */\npackage org.openjdk.jmc.flightrecorder.rules.util;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.concurrent.FutureTask;\nimport org.openjdk.jmc.common.item.IItem;\nimport org.openjdk.jmc.common.item.IItemCollection;\nimport org.openjdk.jmc.common.item.IItemFilter;\nimport org.openjdk.jmc.common.item.IMemberAccessor;\nimport org.openjdk.jmc.common.item.ItemFilters;\nimport org.openjdk.jmc.common.unit.IQuantity;\nimport org.openjdk.jmc.common.unit.IRange;\nimport org.openjdk.jmc.common.unit.QuantityRange;\nimport org.openjdk.jmc.common.util.Pair;\nimport org.openjdk.jmc.flightrecorder.JfrAttributes;\nimport org.openjdk.jmc.flightrecorder.rules.IResult;\n\n/**\n * Utility functions and interfaces for doing sliding window calculations.\n */\npublic class SlidingWindowToolkit {\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowOrdered}\n */\n public interface IOrderedWindowVisitor {\n\n void visitWindow(Iterator items);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, looping through items once, removing from the start\n * and adding and the end of a windowItem set to match the current time window. items.\n *

\n * Suitable if the items are guaranteed to be ordered.\n *\n * @param callback\n * method that can do calculations on the items in the window\n * @param items\n * input items\n * @param posAccessor\n * an accessor that should give a position value that is used with windowsSize and\n * slideSize\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be, if slideSize is {@code null}, it will slide one item\n * at a time\n */\n public static void slidingWindowOrdered(IOrderedWindowVisitor callback, Iterator items, IMemberAccessor posAccessor, IQuantity windowSize, IQuantity slideSize) {\n IQuantity windowStart = null;\n ", "post_mask_code": "\n for (Iterator iterator = items; iterator.hasNext() && callback.shouldContinue(); ) {\n IItem item = iterator.next();\n if (windowItems.isEmpty()) {\n windowStart = posAccessor.getMember(item);\n } else {\n windowStart = posAccessor.getMember(windowItems.get(0));\n }\n windowItems.add(item);\n IQuantity windowEnd = posAccessor.getMember(item);\n while (iterator.hasNext() && windowEnd.subtract(windowSize).compareTo(windowStart) < 0 && callback.shouldContinue()) {\n IItem next = iterator.next();\n windowEnd = posAccessor.getMember(next);\n windowItems.add(next);\n }\n callback.visitWindow(windowItems.iterator());\n // FIXME: What should we do about empty time intervals?\n if (slideSize == null) {\n if (windowItems.size() > 1) {\n windowItems.remove(0);\n }\n } else {\n IQuantity newStart = windowStart.add(slideSize);\n for (Iterator it = windowItems.iterator(); it.hasNext() && callback.shouldContinue(); ) {\n IItem wi = it.next();\n if (posAccessor.getMember(wi).compareTo(newStart) < 0) {\n it.remove();\n } else {\n break;\n }\n }\n }\n }\n }\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowUnordered}\n */\n public interface IUnorderedWindowVisitor {\n\n void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize) {\n slidingWindowUnordered(callback, items, windowSize, slideSize, false);\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n * @param includeIntersecting\n * if the window filter should include events intersecting the window, or just those\n * with end time in the window. It's up to the caller to take this into account and\n * for example cap event duration to the window timespan.\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize, boolean includeIntersecting) {\n IQuantity first = includeIntersecting ? RulesToolkit.getEarliestStartTime(items) : RulesToolkit.getEarliestEndTime(items);\n IQuantity last = RulesToolkit.getLatestEndTime(items);\n if (first == null) {\n return;\n }\n IQuantity windowStart = first;\n IQuantity windowEnd = windowStart.add(windowSize);\n do {\n IItemFilter window = includeIntersecting ? ItemFilters.rangeIntersects(JfrAttributes.LIFETIME, QuantityRange.createWithEnd(windowStart, windowEnd)) : ItemFilters.interval(JfrAttributes.END_TIME, windowStart, true, windowEnd, true);\n IItemCollection windowItems = items.apply(window);\n callback.visitWindow(windowItems, windowStart, windowEnd);\n windowStart = windowStart.add(slideSize);\n windowEnd = windowEnd.add(slideSize);\n } while (windowStart.compareTo(last) < 0 && callback.shouldContinue());\n }\n\n /**\n * Value function used when calling\n * {@link SlidingWindowToolkit#slidingWindowUnorderedMinMaxValue}\n */\n public interface IUnorderedWindowValueFunction {\n\n V getValue(IItemCollection items, IQuantity startTime, IQuantity endTime);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, QUANTITY_COMPARATOR, max, includeIntersecting);\n }\n\n private static final Comparator QUANTITY_COMPARATOR = new Comparator() {\n\n @Override\n public int compare(IQuantity o1, IQuantity o2) {\n return o1.compareTo(o2);\n }\n };\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, valueComparator, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n final List>> valueList = new ArrayList<>();\n slidingWindowUnordered(new IUnorderedWindowVisitor() {\n\n @Override\n public void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime) {\n V value = valueFunction.getValue(items, startTime, endTime);\n if (value != null) {\n valueList.add(new Pair<>(value, QuantityRange.createWithEnd(startTime, endTime)));\n }\n }\n\n @Override\n public boolean shouldContinue() {\n return !cancellationSupplier.isCancelled();\n }\n }, items, windowSize, slideSize, includeIntersecting);\n Comparator>> comparator = new Comparator>>() {\n\n @Override\n public int compare(Pair> o1, Pair> o2) {\n return valueComparator.compare(o1.left, o2.left);\n }\n };\n if (valueList.isEmpty()) {\n return null;\n }\n Pair> minMaxWindow = max ? Collections.max(valueList, comparator) : Collections.min(valueList, comparator);\n return minMaxWindow;\n }\n}\n"} {"task_id": "Java_1849", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/openjdk/jmc/core/org.openjdk.jmc.flightrecorder.rules/src/main/java/org/openjdk/jmc/flightrecorder/rules/util/SlidingWindowToolkit.java", "mask_start_position": 2304, "mask_end_position": 3785, "canonical_solution": "for (Iterator iterator = items; iterator.hasNext() && callback.shouldContinue(); ) {\n IItem item = iterator.next();\n if (windowItems.isEmpty()) {\n windowStart = posAccessor.getMember(item);\n } else {\n windowStart = posAccessor.getMember(windowItems.get(0));\n }\n windowItems.add(item);\n IQuantity windowEnd = posAccessor.getMember(item);\n while (iterator.hasNext() && windowEnd.subtract(windowSize).compareTo(windowStart) < 0 && callback.shouldContinue()) {\n IItem next = iterator.next();\n windowEnd = posAccessor.getMember(next);\n windowItems.add(next);\n }\n callback.visitWindow(windowItems.iterator());\n // FIXME: What should we do about empty time intervals?\n if (slideSize == null) {\n if (windowItems.size() > 1) {\n windowItems.remove(0);\n }\n } else {\n IQuantity newStart = windowStart.add(slideSize);\n for (Iterator it = windowItems.iterator(); it.hasNext() && callback.shouldContinue(); ) {\n IItem wi = it.next();\n if (posAccessor.getMember(wi).compareTo(newStart) < 0) {\n it.remove();\n } else {\n break;\n }\n }\n }\n }\n }", "pre_mask_code": "/*\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n *\n */\npackage org.openjdk.jmc.flightrecorder.rules.util;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.concurrent.FutureTask;\nimport org.openjdk.jmc.common.item.IItem;\nimport org.openjdk.jmc.common.item.IItemCollection;\nimport org.openjdk.jmc.common.item.IItemFilter;\nimport org.openjdk.jmc.common.item.IMemberAccessor;\nimport org.openjdk.jmc.common.item.ItemFilters;\nimport org.openjdk.jmc.common.unit.IQuantity;\nimport org.openjdk.jmc.common.unit.IRange;\nimport org.openjdk.jmc.common.unit.QuantityRange;\nimport org.openjdk.jmc.common.util.Pair;\nimport org.openjdk.jmc.flightrecorder.JfrAttributes;\nimport org.openjdk.jmc.flightrecorder.rules.IResult;\n\n/**\n * Utility functions and interfaces for doing sliding window calculations.\n */\npublic class SlidingWindowToolkit {\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowOrdered}\n */\n public interface IOrderedWindowVisitor {\n\n void visitWindow(Iterator items);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, looping through items once, removing from the start\n * and adding and the end of a windowItem set to match the current time window. items.\n *

\n * Suitable if the items are guaranteed to be ordered.\n *\n * @param callback\n * method that can do calculations on the items in the window\n * @param items\n * input items\n * @param posAccessor\n * an accessor that should give a position value that is used with windowsSize and\n * slideSize\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be, if slideSize is {@code null}, it will slide one item\n * at a time\n */\n public static void slidingWindowOrdered(IOrderedWindowVisitor callback, Iterator items, IMemberAccessor posAccessor, IQuantity windowSize, IQuantity slideSize) {\n IQuantity windowStart = null;\n List windowItems = new ArrayList<>();\n ", "post_mask_code": "\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowUnordered}\n */\n public interface IUnorderedWindowVisitor {\n\n void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize) {\n slidingWindowUnordered(callback, items, windowSize, slideSize, false);\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n * @param includeIntersecting\n * if the window filter should include events intersecting the window, or just those\n * with end time in the window. It's up to the caller to take this into account and\n * for example cap event duration to the window timespan.\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize, boolean includeIntersecting) {\n IQuantity first = includeIntersecting ? RulesToolkit.getEarliestStartTime(items) : RulesToolkit.getEarliestEndTime(items);\n IQuantity last = RulesToolkit.getLatestEndTime(items);\n if (first == null) {\n return;\n }\n IQuantity windowStart = first;\n IQuantity windowEnd = windowStart.add(windowSize);\n do {\n IItemFilter window = includeIntersecting ? ItemFilters.rangeIntersects(JfrAttributes.LIFETIME, QuantityRange.createWithEnd(windowStart, windowEnd)) : ItemFilters.interval(JfrAttributes.END_TIME, windowStart, true, windowEnd, true);\n IItemCollection windowItems = items.apply(window);\n callback.visitWindow(windowItems, windowStart, windowEnd);\n windowStart = windowStart.add(slideSize);\n windowEnd = windowEnd.add(slideSize);\n } while (windowStart.compareTo(last) < 0 && callback.shouldContinue());\n }\n\n /**\n * Value function used when calling\n * {@link SlidingWindowToolkit#slidingWindowUnorderedMinMaxValue}\n */\n public interface IUnorderedWindowValueFunction {\n\n V getValue(IItemCollection items, IQuantity startTime, IQuantity endTime);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, QUANTITY_COMPARATOR, max, includeIntersecting);\n }\n\n private static final Comparator QUANTITY_COMPARATOR = new Comparator() {\n\n @Override\n public int compare(IQuantity o1, IQuantity o2) {\n return o1.compareTo(o2);\n }\n };\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, valueComparator, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n final List>> valueList = new ArrayList<>();\n slidingWindowUnordered(new IUnorderedWindowVisitor() {\n\n @Override\n public void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime) {\n V value = valueFunction.getValue(items, startTime, endTime);\n if (value != null) {\n valueList.add(new Pair<>(value, QuantityRange.createWithEnd(startTime, endTime)));\n }\n }\n\n @Override\n public boolean shouldContinue() {\n return !cancellationSupplier.isCancelled();\n }\n }, items, windowSize, slideSize, includeIntersecting);\n Comparator>> comparator = new Comparator>>() {\n\n @Override\n public int compare(Pair> o1, Pair> o2) {\n return valueComparator.compare(o1.left, o2.left);\n }\n };\n if (valueList.isEmpty()) {\n return null;\n }\n Pair> minMaxWindow = max ? Collections.max(valueList, comparator) : Collections.min(valueList, comparator);\n return minMaxWindow;\n }\n}\n"} {"task_id": "Java_1850", "language": "Java", "task_type": "single_line", "source_file": "java/github/openjdk/jmc/core/org.openjdk.jmc.flightrecorder.rules/src/main/java/org/openjdk/jmc/flightrecorder/rules/util/SlidingWindowToolkit.java", "mask_start_position": 13933, "mask_end_position": 13951, "canonical_solution": "turn minMaxWindow;", "pre_mask_code": "/*\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n *\n */\npackage org.openjdk.jmc.flightrecorder.rules.util;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.concurrent.FutureTask;\nimport org.openjdk.jmc.common.item.IItem;\nimport org.openjdk.jmc.common.item.IItemCollection;\nimport org.openjdk.jmc.common.item.IItemFilter;\nimport org.openjdk.jmc.common.item.IMemberAccessor;\nimport org.openjdk.jmc.common.item.ItemFilters;\nimport org.openjdk.jmc.common.unit.IQuantity;\nimport org.openjdk.jmc.common.unit.IRange;\nimport org.openjdk.jmc.common.unit.QuantityRange;\nimport org.openjdk.jmc.common.util.Pair;\nimport org.openjdk.jmc.flightrecorder.JfrAttributes;\nimport org.openjdk.jmc.flightrecorder.rules.IResult;\n\n/**\n * Utility functions and interfaces for doing sliding window calculations.\n */\npublic class SlidingWindowToolkit {\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowOrdered}\n */\n public interface IOrderedWindowVisitor {\n\n void visitWindow(Iterator items);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, looping through items once, removing from the start\n * and adding and the end of a windowItem set to match the current time window. items.\n *

\n * Suitable if the items are guaranteed to be ordered.\n *\n * @param callback\n * method that can do calculations on the items in the window\n * @param items\n * input items\n * @param posAccessor\n * an accessor that should give a position value that is used with windowsSize and\n * slideSize\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be, if slideSize is {@code null}, it will slide one item\n * at a time\n */\n public static void slidingWindowOrdered(IOrderedWindowVisitor callback, Iterator items, IMemberAccessor posAccessor, IQuantity windowSize, IQuantity slideSize) {\n IQuantity windowStart = null;\n List windowItems = new ArrayList<>();\n for (Iterator iterator = items; iterator.hasNext() && callback.shouldContinue(); ) {\n IItem item = iterator.next();\n if (windowItems.isEmpty()) {\n windowStart = posAccessor.getMember(item);\n } else {\n windowStart = posAccessor.getMember(windowItems.get(0));\n }\n windowItems.add(item);\n IQuantity windowEnd = posAccessor.getMember(item);\n while (iterator.hasNext() && windowEnd.subtract(windowSize).compareTo(windowStart) < 0 && callback.shouldContinue()) {\n IItem next = iterator.next();\n windowEnd = posAccessor.getMember(next);\n windowItems.add(next);\n }\n callback.visitWindow(windowItems.iterator());\n // FIXME: What should we do about empty time intervals?\n if (slideSize == null) {\n if (windowItems.size() > 1) {\n windowItems.remove(0);\n }\n } else {\n IQuantity newStart = windowStart.add(slideSize);\n for (Iterator it = windowItems.iterator(); it.hasNext() && callback.shouldContinue(); ) {\n IItem wi = it.next();\n if (posAccessor.getMember(wi).compareTo(newStart) < 0) {\n it.remove();\n } else {\n break;\n }\n }\n }\n }\n }\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowUnordered}\n */\n public interface IUnorderedWindowVisitor {\n\n void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize) {\n slidingWindowUnordered(callback, items, windowSize, slideSize, false);\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n * @param includeIntersecting\n * if the window filter should include events intersecting the window, or just those\n * with end time in the window. It's up to the caller to take this into account and\n * for example cap event duration to the window timespan.\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize, boolean includeIntersecting) {\n IQuantity first = includeIntersecting ? RulesToolkit.getEarliestStartTime(items) : RulesToolkit.getEarliestEndTime(items);\n IQuantity last = RulesToolkit.getLatestEndTime(items);\n if (first == null) {\n return;\n }\n IQuantity windowStart = first;\n IQuantity windowEnd = windowStart.add(windowSize);\n do {\n IItemFilter window = includeIntersecting ? ItemFilters.rangeIntersects(JfrAttributes.LIFETIME, QuantityRange.createWithEnd(windowStart, windowEnd)) : ItemFilters.interval(JfrAttributes.END_TIME, windowStart, true, windowEnd, true);\n IItemCollection windowItems = items.apply(window);\n callback.visitWindow(windowItems, windowStart, windowEnd);\n windowStart = windowStart.add(slideSize);\n windowEnd = windowEnd.add(slideSize);\n } while (windowStart.compareTo(last) < 0 && callback.shouldContinue());\n }\n\n /**\n * Value function used when calling\n * {@link SlidingWindowToolkit#slidingWindowUnorderedMinMaxValue}\n */\n public interface IUnorderedWindowValueFunction {\n\n V getValue(IItemCollection items, IQuantity startTime, IQuantity endTime);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, QUANTITY_COMPARATOR, max, includeIntersecting);\n }\n\n private static final Comparator QUANTITY_COMPARATOR = new Comparator() {\n\n @Override\n public int compare(IQuantity o1, IQuantity o2) {\n return o1.compareTo(o2);\n }\n };\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, valueComparator, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n final List>> valueList = new ArrayList<>();\n slidingWindowUnordered(new IUnorderedWindowVisitor() {\n\n @Override\n public void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime) {\n V value = valueFunction.getValue(items, startTime, endTime);\n if (value != null) {\n valueList.add(new Pair<>(value, QuantityRange.createWithEnd(startTime, endTime)));\n }\n }\n\n @Override\n public boolean shouldContinue() {\n return !cancellationSupplier.isCancelled();\n }\n }, items, windowSize, slideSize, includeIntersecting);\n Comparator>> comparator = new Comparator>>() {\n\n @Override\n public int compare(Pair> o1, Pair> o2) {\n return valueComparator.compare(o1.left, o2.left);\n }\n };\n if (valueList.isEmpty()) {\n return null;\n }\n Pair> minMaxWindow = max ? Collections.max(valueList, comparator) : Collections.min(valueList, comparator);\n re", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1851", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/openjdk/jmc/core/org.openjdk.jmc.flightrecorder.rules/src/main/java/org/openjdk/jmc/flightrecorder/rules/util/SlidingWindowToolkit.java", "mask_start_position": 4628, "mask_end_position": 4856, "canonical_solution": "public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize) {\n slidingWindowUnordered(callback, items, windowSize, slideSize, false);\n }", "pre_mask_code": "/*\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n *\n */\npackage org.openjdk.jmc.flightrecorder.rules.util;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.concurrent.FutureTask;\nimport org.openjdk.jmc.common.item.IItem;\nimport org.openjdk.jmc.common.item.IItemCollection;\nimport org.openjdk.jmc.common.item.IItemFilter;\nimport org.openjdk.jmc.common.item.IMemberAccessor;\nimport org.openjdk.jmc.common.item.ItemFilters;\nimport org.openjdk.jmc.common.unit.IQuantity;\nimport org.openjdk.jmc.common.unit.IRange;\nimport org.openjdk.jmc.common.unit.QuantityRange;\nimport org.openjdk.jmc.common.util.Pair;\nimport org.openjdk.jmc.flightrecorder.JfrAttributes;\nimport org.openjdk.jmc.flightrecorder.rules.IResult;\n\n/**\n * Utility functions and interfaces for doing sliding window calculations.\n */\npublic class SlidingWindowToolkit {\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowOrdered}\n */\n public interface IOrderedWindowVisitor {\n\n void visitWindow(Iterator items);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, looping through items once, removing from the start\n * and adding and the end of a windowItem set to match the current time window. items.\n *

\n * Suitable if the items are guaranteed to be ordered.\n *\n * @param callback\n * method that can do calculations on the items in the window\n * @param items\n * input items\n * @param posAccessor\n * an accessor that should give a position value that is used with windowsSize and\n * slideSize\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be, if slideSize is {@code null}, it will slide one item\n * at a time\n */\n public static void slidingWindowOrdered(IOrderedWindowVisitor callback, Iterator items, IMemberAccessor posAccessor, IQuantity windowSize, IQuantity slideSize) {\n IQuantity windowStart = null;\n List windowItems = new ArrayList<>();\n for (Iterator iterator = items; iterator.hasNext() && callback.shouldContinue(); ) {\n IItem item = iterator.next();\n if (windowItems.isEmpty()) {\n windowStart = posAccessor.getMember(item);\n } else {\n windowStart = posAccessor.getMember(windowItems.get(0));\n }\n windowItems.add(item);\n IQuantity windowEnd = posAccessor.getMember(item);\n while (iterator.hasNext() && windowEnd.subtract(windowSize).compareTo(windowStart) < 0 && callback.shouldContinue()) {\n IItem next = iterator.next();\n windowEnd = posAccessor.getMember(next);\n windowItems.add(next);\n }\n callback.visitWindow(windowItems.iterator());\n // FIXME: What should we do about empty time intervals?\n if (slideSize == null) {\n if (windowItems.size() > 1) {\n windowItems.remove(0);\n }\n } else {\n IQuantity newStart = windowStart.add(slideSize);\n for (Iterator it = windowItems.iterator(); it.hasNext() && callback.shouldContinue(); ) {\n IItem wi = it.next();\n if (posAccessor.getMember(wi).compareTo(newStart) < 0) {\n it.remove();\n } else {\n break;\n }\n }\n }\n }\n }\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowUnordered}\n */\n public interface IUnorderedWindowVisitor {\n\n void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n */\n ", "post_mask_code": "\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n * @param includeIntersecting\n * if the window filter should include events intersecting the window, or just those\n * with end time in the window. It's up to the caller to take this into account and\n * for example cap event duration to the window timespan.\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize, boolean includeIntersecting) {\n IQuantity first = includeIntersecting ? RulesToolkit.getEarliestStartTime(items) : RulesToolkit.getEarliestEndTime(items);\n IQuantity last = RulesToolkit.getLatestEndTime(items);\n if (first == null) {\n return;\n }\n IQuantity windowStart = first;\n IQuantity windowEnd = windowStart.add(windowSize);\n do {\n IItemFilter window = includeIntersecting ? ItemFilters.rangeIntersects(JfrAttributes.LIFETIME, QuantityRange.createWithEnd(windowStart, windowEnd)) : ItemFilters.interval(JfrAttributes.END_TIME, windowStart, true, windowEnd, true);\n IItemCollection windowItems = items.apply(window);\n callback.visitWindow(windowItems, windowStart, windowEnd);\n windowStart = windowStart.add(slideSize);\n windowEnd = windowEnd.add(slideSize);\n } while (windowStart.compareTo(last) < 0 && callback.shouldContinue());\n }\n\n /**\n * Value function used when calling\n * {@link SlidingWindowToolkit#slidingWindowUnorderedMinMaxValue}\n */\n public interface IUnorderedWindowValueFunction {\n\n V getValue(IItemCollection items, IQuantity startTime, IQuantity endTime);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, QUANTITY_COMPARATOR, max, includeIntersecting);\n }\n\n private static final Comparator QUANTITY_COMPARATOR = new Comparator() {\n\n @Override\n public int compare(IQuantity o1, IQuantity o2) {\n return o1.compareTo(o2);\n }\n };\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, valueComparator, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n final List>> valueList = new ArrayList<>();\n slidingWindowUnordered(new IUnorderedWindowVisitor() {\n\n @Override\n public void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime) {\n V value = valueFunction.getValue(items, startTime, endTime);\n if (value != null) {\n valueList.add(new Pair<>(value, QuantityRange.createWithEnd(startTime, endTime)));\n }\n }\n\n @Override\n public boolean shouldContinue() {\n return !cancellationSupplier.isCancelled();\n }\n }, items, windowSize, slideSize, includeIntersecting);\n Comparator>> comparator = new Comparator>>() {\n\n @Override\n public int compare(Pair> o1, Pair> o2) {\n return valueComparator.compare(o1.left, o2.left);\n }\n };\n if (valueList.isEmpty()) {\n return null;\n }\n Pair> minMaxWindow = max ? Collections.max(valueList, comparator) : Collections.min(valueList, comparator);\n return minMaxWindow;\n }\n}\n"} {"task_id": "Java_1852", "language": "Java", "task_type": "if_statement", "source_file": "java/github/openjdk/jmc/core/org.openjdk.jmc.flightrecorder.rules/src/main/java/org/openjdk/jmc/flightrecorder/rules/util/SlidingWindowToolkit.java", "mask_start_position": 2450, "mask_end_position": 2645, "canonical_solution": "if (windowItems.isEmpty()) {\n windowStart = posAccessor.getMember(item);\n } else {\n windowStart = posAccessor.getMember(windowItems.get(0));\n }", "pre_mask_code": "/*\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n *\n */\npackage org.openjdk.jmc.flightrecorder.rules.util;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.concurrent.FutureTask;\nimport org.openjdk.jmc.common.item.IItem;\nimport org.openjdk.jmc.common.item.IItemCollection;\nimport org.openjdk.jmc.common.item.IItemFilter;\nimport org.openjdk.jmc.common.item.IMemberAccessor;\nimport org.openjdk.jmc.common.item.ItemFilters;\nimport org.openjdk.jmc.common.unit.IQuantity;\nimport org.openjdk.jmc.common.unit.IRange;\nimport org.openjdk.jmc.common.unit.QuantityRange;\nimport org.openjdk.jmc.common.util.Pair;\nimport org.openjdk.jmc.flightrecorder.JfrAttributes;\nimport org.openjdk.jmc.flightrecorder.rules.IResult;\n\n/**\n * Utility functions and interfaces for doing sliding window calculations.\n */\npublic class SlidingWindowToolkit {\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowOrdered}\n */\n public interface IOrderedWindowVisitor {\n\n void visitWindow(Iterator items);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, looping through items once, removing from the start\n * and adding and the end of a windowItem set to match the current time window. items.\n *

\n * Suitable if the items are guaranteed to be ordered.\n *\n * @param callback\n * method that can do calculations on the items in the window\n * @param items\n * input items\n * @param posAccessor\n * an accessor that should give a position value that is used with windowsSize and\n * slideSize\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be, if slideSize is {@code null}, it will slide one item\n * at a time\n */\n public static void slidingWindowOrdered(IOrderedWindowVisitor callback, Iterator items, IMemberAccessor posAccessor, IQuantity windowSize, IQuantity slideSize) {\n IQuantity windowStart = null;\n List windowItems = new ArrayList<>();\n for (Iterator iterator = items; iterator.hasNext() && callback.shouldContinue(); ) {\n IItem item = iterator.next();\n ", "post_mask_code": "\n windowItems.add(item);\n IQuantity windowEnd = posAccessor.getMember(item);\n while (iterator.hasNext() && windowEnd.subtract(windowSize).compareTo(windowStart) < 0 && callback.shouldContinue()) {\n IItem next = iterator.next();\n windowEnd = posAccessor.getMember(next);\n windowItems.add(next);\n }\n callback.visitWindow(windowItems.iterator());\n // FIXME: What should we do about empty time intervals?\n if (slideSize == null) {\n if (windowItems.size() > 1) {\n windowItems.remove(0);\n }\n } else {\n IQuantity newStart = windowStart.add(slideSize);\n for (Iterator it = windowItems.iterator(); it.hasNext() && callback.shouldContinue(); ) {\n IItem wi = it.next();\n if (posAccessor.getMember(wi).compareTo(newStart) < 0) {\n it.remove();\n } else {\n break;\n }\n }\n }\n }\n }\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowUnordered}\n */\n public interface IUnorderedWindowVisitor {\n\n void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize) {\n slidingWindowUnordered(callback, items, windowSize, slideSize, false);\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n * @param includeIntersecting\n * if the window filter should include events intersecting the window, or just those\n * with end time in the window. It's up to the caller to take this into account and\n * for example cap event duration to the window timespan.\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize, boolean includeIntersecting) {\n IQuantity first = includeIntersecting ? RulesToolkit.getEarliestStartTime(items) : RulesToolkit.getEarliestEndTime(items);\n IQuantity last = RulesToolkit.getLatestEndTime(items);\n if (first == null) {\n return;\n }\n IQuantity windowStart = first;\n IQuantity windowEnd = windowStart.add(windowSize);\n do {\n IItemFilter window = includeIntersecting ? ItemFilters.rangeIntersects(JfrAttributes.LIFETIME, QuantityRange.createWithEnd(windowStart, windowEnd)) : ItemFilters.interval(JfrAttributes.END_TIME, windowStart, true, windowEnd, true);\n IItemCollection windowItems = items.apply(window);\n callback.visitWindow(windowItems, windowStart, windowEnd);\n windowStart = windowStart.add(slideSize);\n windowEnd = windowEnd.add(slideSize);\n } while (windowStart.compareTo(last) < 0 && callback.shouldContinue());\n }\n\n /**\n * Value function used when calling\n * {@link SlidingWindowToolkit#slidingWindowUnorderedMinMaxValue}\n */\n public interface IUnorderedWindowValueFunction {\n\n V getValue(IItemCollection items, IQuantity startTime, IQuantity endTime);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, QUANTITY_COMPARATOR, max, includeIntersecting);\n }\n\n private static final Comparator QUANTITY_COMPARATOR = new Comparator() {\n\n @Override\n public int compare(IQuantity o1, IQuantity o2) {\n return o1.compareTo(o2);\n }\n };\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, valueComparator, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n final List>> valueList = new ArrayList<>();\n slidingWindowUnordered(new IUnorderedWindowVisitor() {\n\n @Override\n public void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime) {\n V value = valueFunction.getValue(items, startTime, endTime);\n if (value != null) {\n valueList.add(new Pair<>(value, QuantityRange.createWithEnd(startTime, endTime)));\n }\n }\n\n @Override\n public boolean shouldContinue() {\n return !cancellationSupplier.isCancelled();\n }\n }, items, windowSize, slideSize, includeIntersecting);\n Comparator>> comparator = new Comparator>>() {\n\n @Override\n public int compare(Pair> o1, Pair> o2) {\n return valueComparator.compare(o1.left, o2.left);\n }\n };\n if (valueList.isEmpty()) {\n return null;\n }\n Pair> minMaxWindow = max ? Collections.max(valueList, comparator) : Collections.min(valueList, comparator);\n return minMaxWindow;\n }\n}\n"} {"task_id": "Java_1853", "language": "Java", "task_type": "for_statement", "source_file": "java/github/openjdk/jmc/core/org.openjdk.jmc.flightrecorder.rules/src/main/java/org/openjdk/jmc/flightrecorder/rules/util/SlidingWindowToolkit.java", "mask_start_position": 3403, "mask_end_position": 3755, "canonical_solution": "for (Iterator it = windowItems.iterator(); it.hasNext() && callback.shouldContinue(); ) {\n IItem wi = it.next();\n if (posAccessor.getMember(wi).compareTo(newStart) < 0) {\n it.remove();\n } else {\n break;\n }\n }", "pre_mask_code": "/*\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n *\n */\npackage org.openjdk.jmc.flightrecorder.rules.util;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.concurrent.FutureTask;\nimport org.openjdk.jmc.common.item.IItem;\nimport org.openjdk.jmc.common.item.IItemCollection;\nimport org.openjdk.jmc.common.item.IItemFilter;\nimport org.openjdk.jmc.common.item.IMemberAccessor;\nimport org.openjdk.jmc.common.item.ItemFilters;\nimport org.openjdk.jmc.common.unit.IQuantity;\nimport org.openjdk.jmc.common.unit.IRange;\nimport org.openjdk.jmc.common.unit.QuantityRange;\nimport org.openjdk.jmc.common.util.Pair;\nimport org.openjdk.jmc.flightrecorder.JfrAttributes;\nimport org.openjdk.jmc.flightrecorder.rules.IResult;\n\n/**\n * Utility functions and interfaces for doing sliding window calculations.\n */\npublic class SlidingWindowToolkit {\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowOrdered}\n */\n public interface IOrderedWindowVisitor {\n\n void visitWindow(Iterator items);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, looping through items once, removing from the start\n * and adding and the end of a windowItem set to match the current time window. items.\n *

\n * Suitable if the items are guaranteed to be ordered.\n *\n * @param callback\n * method that can do calculations on the items in the window\n * @param items\n * input items\n * @param posAccessor\n * an accessor that should give a position value that is used with windowsSize and\n * slideSize\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be, if slideSize is {@code null}, it will slide one item\n * at a time\n */\n public static void slidingWindowOrdered(IOrderedWindowVisitor callback, Iterator items, IMemberAccessor posAccessor, IQuantity windowSize, IQuantity slideSize) {\n IQuantity windowStart = null;\n List windowItems = new ArrayList<>();\n for (Iterator iterator = items; iterator.hasNext() && callback.shouldContinue(); ) {\n IItem item = iterator.next();\n if (windowItems.isEmpty()) {\n windowStart = posAccessor.getMember(item);\n } else {\n windowStart = posAccessor.getMember(windowItems.get(0));\n }\n windowItems.add(item);\n IQuantity windowEnd = posAccessor.getMember(item);\n while (iterator.hasNext() && windowEnd.subtract(windowSize).compareTo(windowStart) < 0 && callback.shouldContinue()) {\n IItem next = iterator.next();\n windowEnd = posAccessor.getMember(next);\n windowItems.add(next);\n }\n callback.visitWindow(windowItems.iterator());\n // FIXME: What should we do about empty time intervals?\n if (slideSize == null) {\n if (windowItems.size() > 1) {\n windowItems.remove(0);\n }\n } else {\n IQuantity newStart = windowStart.add(slideSize);\n ", "post_mask_code": "\n }\n }\n }\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowUnordered}\n */\n public interface IUnorderedWindowVisitor {\n\n void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize) {\n slidingWindowUnordered(callback, items, windowSize, slideSize, false);\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n * @param includeIntersecting\n * if the window filter should include events intersecting the window, or just those\n * with end time in the window. It's up to the caller to take this into account and\n * for example cap event duration to the window timespan.\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize, boolean includeIntersecting) {\n IQuantity first = includeIntersecting ? RulesToolkit.getEarliestStartTime(items) : RulesToolkit.getEarliestEndTime(items);\n IQuantity last = RulesToolkit.getLatestEndTime(items);\n if (first == null) {\n return;\n }\n IQuantity windowStart = first;\n IQuantity windowEnd = windowStart.add(windowSize);\n do {\n IItemFilter window = includeIntersecting ? ItemFilters.rangeIntersects(JfrAttributes.LIFETIME, QuantityRange.createWithEnd(windowStart, windowEnd)) : ItemFilters.interval(JfrAttributes.END_TIME, windowStart, true, windowEnd, true);\n IItemCollection windowItems = items.apply(window);\n callback.visitWindow(windowItems, windowStart, windowEnd);\n windowStart = windowStart.add(slideSize);\n windowEnd = windowEnd.add(slideSize);\n } while (windowStart.compareTo(last) < 0 && callback.shouldContinue());\n }\n\n /**\n * Value function used when calling\n * {@link SlidingWindowToolkit#slidingWindowUnorderedMinMaxValue}\n */\n public interface IUnorderedWindowValueFunction {\n\n V getValue(IItemCollection items, IQuantity startTime, IQuantity endTime);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, QUANTITY_COMPARATOR, max, includeIntersecting);\n }\n\n private static final Comparator QUANTITY_COMPARATOR = new Comparator() {\n\n @Override\n public int compare(IQuantity o1, IQuantity o2) {\n return o1.compareTo(o2);\n }\n };\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, valueComparator, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n final List>> valueList = new ArrayList<>();\n slidingWindowUnordered(new IUnorderedWindowVisitor() {\n\n @Override\n public void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime) {\n V value = valueFunction.getValue(items, startTime, endTime);\n if (value != null) {\n valueList.add(new Pair<>(value, QuantityRange.createWithEnd(startTime, endTime)));\n }\n }\n\n @Override\n public boolean shouldContinue() {\n return !cancellationSupplier.isCancelled();\n }\n }, items, windowSize, slideSize, includeIntersecting);\n Comparator>> comparator = new Comparator>>() {\n\n @Override\n public int compare(Pair> o1, Pair> o2) {\n return valueComparator.compare(o1.left, o2.left);\n }\n };\n if (valueList.isEmpty()) {\n return null;\n }\n Pair> minMaxWindow = max ? Collections.max(valueList, comparator) : Collections.min(valueList, comparator);\n return minMaxWindow;\n }\n}\n"} {"task_id": "Java_1854", "language": "Java", "task_type": "while_statement", "source_file": "java/github/openjdk/jmc/core/org.openjdk.jmc.flightrecorder.rules/src/main/java/org/openjdk/jmc/flightrecorder/rules/util/SlidingWindowToolkit.java", "mask_start_position": 2756, "mask_end_position": 3030, "canonical_solution": "while (iterator.hasNext() && windowEnd.subtract(windowSize).compareTo(windowStart) < 0 && callback.shouldContinue()) {\n IItem next = iterator.next();\n windowEnd = posAccessor.getMember(next);\n windowItems.add(next);\n }", "pre_mask_code": "/*\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n *\n */\npackage org.openjdk.jmc.flightrecorder.rules.util;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.concurrent.FutureTask;\nimport org.openjdk.jmc.common.item.IItem;\nimport org.openjdk.jmc.common.item.IItemCollection;\nimport org.openjdk.jmc.common.item.IItemFilter;\nimport org.openjdk.jmc.common.item.IMemberAccessor;\nimport org.openjdk.jmc.common.item.ItemFilters;\nimport org.openjdk.jmc.common.unit.IQuantity;\nimport org.openjdk.jmc.common.unit.IRange;\nimport org.openjdk.jmc.common.unit.QuantityRange;\nimport org.openjdk.jmc.common.util.Pair;\nimport org.openjdk.jmc.flightrecorder.JfrAttributes;\nimport org.openjdk.jmc.flightrecorder.rules.IResult;\n\n/**\n * Utility functions and interfaces for doing sliding window calculations.\n */\npublic class SlidingWindowToolkit {\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowOrdered}\n */\n public interface IOrderedWindowVisitor {\n\n void visitWindow(Iterator items);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, looping through items once, removing from the start\n * and adding and the end of a windowItem set to match the current time window. items.\n *

\n * Suitable if the items are guaranteed to be ordered.\n *\n * @param callback\n * method that can do calculations on the items in the window\n * @param items\n * input items\n * @param posAccessor\n * an accessor that should give a position value that is used with windowsSize and\n * slideSize\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be, if slideSize is {@code null}, it will slide one item\n * at a time\n */\n public static void slidingWindowOrdered(IOrderedWindowVisitor callback, Iterator items, IMemberAccessor posAccessor, IQuantity windowSize, IQuantity slideSize) {\n IQuantity windowStart = null;\n List windowItems = new ArrayList<>();\n for (Iterator iterator = items; iterator.hasNext() && callback.shouldContinue(); ) {\n IItem item = iterator.next();\n if (windowItems.isEmpty()) {\n windowStart = posAccessor.getMember(item);\n } else {\n windowStart = posAccessor.getMember(windowItems.get(0));\n }\n windowItems.add(item);\n IQuantity windowEnd = posAccessor.getMember(item);\n ", "post_mask_code": "\n callback.visitWindow(windowItems.iterator());\n // FIXME: What should we do about empty time intervals?\n if (slideSize == null) {\n if (windowItems.size() > 1) {\n windowItems.remove(0);\n }\n } else {\n IQuantity newStart = windowStart.add(slideSize);\n for (Iterator it = windowItems.iterator(); it.hasNext() && callback.shouldContinue(); ) {\n IItem wi = it.next();\n if (posAccessor.getMember(wi).compareTo(newStart) < 0) {\n it.remove();\n } else {\n break;\n }\n }\n }\n }\n }\n\n /**\n * Visitor interface used when calling {@link SlidingWindowToolkit#slidingWindowUnordered}\n */\n public interface IUnorderedWindowVisitor {\n\n void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime);\n\n boolean shouldContinue();\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize) {\n slidingWindowUnordered(callback, items, windowSize, slideSize, false);\n }\n\n /**\n * Runs a sliding window through all items, by calculating the window start and end and filter\n * through all the items. Suitable if the items are not guaranteed to be ordered, but is slower\n * than the ordered version.\n *\n * @param callback\n * method that can do calculations on the items in the window.\n * @param items\n * input items\n * @param windowSize\n * size for the sliding window\n * @param slideSize\n * how big the slide should be\n * @param includeIntersecting\n * if the window filter should include events intersecting the window, or just those\n * with end time in the window. It's up to the caller to take this into account and\n * for example cap event duration to the window timespan.\n */\n public static void slidingWindowUnordered(IUnorderedWindowVisitor callback, IItemCollection items, IQuantity windowSize, IQuantity slideSize, boolean includeIntersecting) {\n IQuantity first = includeIntersecting ? RulesToolkit.getEarliestStartTime(items) : RulesToolkit.getEarliestEndTime(items);\n IQuantity last = RulesToolkit.getLatestEndTime(items);\n if (first == null) {\n return;\n }\n IQuantity windowStart = first;\n IQuantity windowEnd = windowStart.add(windowSize);\n do {\n IItemFilter window = includeIntersecting ? ItemFilters.rangeIntersects(JfrAttributes.LIFETIME, QuantityRange.createWithEnd(windowStart, windowEnd)) : ItemFilters.interval(JfrAttributes.END_TIME, windowStart, true, windowEnd, true);\n IItemCollection windowItems = items.apply(window);\n callback.visitWindow(windowItems, windowStart, windowEnd);\n windowStart = windowStart.add(slideSize);\n windowEnd = windowEnd.add(slideSize);\n } while (windowStart.compareTo(last) < 0 && callback.shouldContinue());\n }\n\n /**\n * Value function used when calling\n * {@link SlidingWindowToolkit#slidingWindowUnorderedMinMaxValue}\n */\n public interface IUnorderedWindowValueFunction {\n\n V getValue(IItemCollection items, IQuantity startTime, IQuantity endTime);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window quantity value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, boolean max, boolean includeIntersecting) {\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, QUANTITY_COMPARATOR, max, includeIntersecting);\n }\n\n private static final Comparator QUANTITY_COMPARATOR = new Comparator() {\n\n @Override\n public int compare(IQuantity o1, IQuantity o2) {\n return o1.compareTo(o2);\n }\n };\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n IQuantity slideSize = windowSize.getUnit().quantity(windowSize.ratioTo(windowSize.getUnit().quantity(2)));\n return slidingWindowUnorderedMinMaxValue(items, windowSize, slideSize, cancellationSupplier, valueFunction, valueComparator, max, includeIntersecting);\n }\n\n /**\n * Calculates max/min window value of items.\n *\n * @param items\n * items to use for evaluation\n * @param windowSize\n * window size\n * @param slideSize\n * window slide size\n * @param cancellationSupplier\n * if the evaluation should be cancelled\n * @param valueFunction\n * provides the window value for items\n * @param valueComparator\n * compares values\n * @param max\n * true to get the max value, false to get min value\n * @param includeIntersecting\n * true to include also intersecting items, false to only include contained items. If\n * set to true, it's up to the valueFunction to only use the duration events that is\n * actually included in the window.\n * @return min/max window value and range\n */\n public static Pair> slidingWindowUnorderedMinMaxValue(IItemCollection items, IQuantity windowSize, IQuantity slideSize, final FutureTask cancellationSupplier, final IUnorderedWindowValueFunction valueFunction, final Comparator valueComparator, boolean max, boolean includeIntersecting) {\n final List>> valueList = new ArrayList<>();\n slidingWindowUnordered(new IUnorderedWindowVisitor() {\n\n @Override\n public void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime) {\n V value = valueFunction.getValue(items, startTime, endTime);\n if (value != null) {\n valueList.add(new Pair<>(value, QuantityRange.createWithEnd(startTime, endTime)));\n }\n }\n\n @Override\n public boolean shouldContinue() {\n return !cancellationSupplier.isCancelled();\n }\n }, items, windowSize, slideSize, includeIntersecting);\n Comparator>> comparator = new Comparator>>() {\n\n @Override\n public int compare(Pair> o1, Pair> o2) {\n return valueComparator.compare(o1.left, o2.left);\n }\n };\n if (valueList.isEmpty()) {\n return null;\n }\n Pair> minMaxWindow = max ? Collections.max(valueList, comparator) : Collections.min(valueList, comparator);\n return minMaxWindow;\n }\n}\n"} {"task_id": "Java_1855", "language": "Java", "task_type": "method_signature", "source_file": "java/github/JoeAlisson/L2jOrg/Datapack/gameserver/data/scripts/org.l2j.scripts/handlers/itemhandlers/AbstractShot.java", "mask_start_position": 830, "mask_end_position": 915, "canonical_solution": "@Override\n public boolean useItem(Playable playable, Item item, boolean forceUse) ", "pre_mask_code": "/*\n *\n * This file is part of the L2JOrg project.\n *\n */\npackage handlers.itemhandlers;\n\nimport org.l2j.gameserver.enums.ItemSkillType;\nimport org.l2j.gameserver.enums.ShotType;\nimport org.l2j.gameserver.handler.IItemHandler;\nimport org.l2j.gameserver.model.actor.Playable;\nimport org.l2j.gameserver.model.actor.instance.Player;\nimport org.l2j.gameserver.model.events.EventDispatcher;\nimport org.l2j.gameserver.model.events.impl.character.player.OnPlayeableChargeShots;\nimport org.l2j.gameserver.model.item.instance.Item;\nimport org.l2j.gameserver.network.SystemMessageId;\nimport org.l2j.gameserver.network.serverpackets.MagicSkillUse;\nimport org.l2j.gameserver.util.Broadcast;\nimport static org.l2j.commons.util.Util.isNullOrEmpty;\n\n/**\n * @author JoeAlisson\n */\npublic abstract class AbstractShot implements IItemHandler {\n\n ", "post_mask_code": "{\n var player = playable.getActingPlayer();\n var skills = item.getSkills(ItemSkillType.NORMAL);\n if (isNullOrEmpty(skills)) {\n LOGGER.warn(\"item {} is missing skills!\", item);\n return false;\n }\n // Check if Soul shot can be used\n if (!canUse(player)) {\n return false;\n }\n player.chargeShot(getShotType(), getBonus(player));\n player.sendPacket(getEnabledShotsMessage());\n EventDispatcher.getInstance().notifyEventAsync(new OnPlayeableChargeShots(player, getShotType(), isBlessed()), player);\n skills.forEach(holder -> Broadcast.toSelfAndKnownPlayersInRadius(player, new MagicSkillUse(player, player, holder.getSkillId(), holder.getLevel(), 0, 0), 600));\n return true;\n }\n\n protected abstract boolean isBlessed();\n\n protected abstract double getBonus(Player player);\n\n protected abstract boolean canUse(Player player);\n\n protected abstract ShotType getShotType();\n\n protected abstract SystemMessageId getEnabledShotsMessage();\n}\n"} {"task_id": "Java_1856", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/JoeAlisson/L2jOrg/Datapack/gameserver/data/scripts/org.l2j.scripts/handlers/itemhandlers/AbstractShot.java", "mask_start_position": 916, "mask_end_position": 1158, "canonical_solution": "\n var player = playable.getActingPlayer();\n var skills = item.getSkills(ItemSkillType.NORMAL);\n if (isNullOrEmpty(skills)) {\n LOGGER.warn(\"item {} is missing skills!\", item);\n return false;\n }", "pre_mask_code": "/*\n *\n * This file is part of the L2JOrg project.\n *\n */\npackage handlers.itemhandlers;\n\nimport org.l2j.gameserver.enums.ItemSkillType;\nimport org.l2j.gameserver.enums.ShotType;\nimport org.l2j.gameserver.handler.IItemHandler;\nimport org.l2j.gameserver.model.actor.Playable;\nimport org.l2j.gameserver.model.actor.instance.Player;\nimport org.l2j.gameserver.model.events.EventDispatcher;\nimport org.l2j.gameserver.model.events.impl.character.player.OnPlayeableChargeShots;\nimport org.l2j.gameserver.model.item.instance.Item;\nimport org.l2j.gameserver.network.SystemMessageId;\nimport org.l2j.gameserver.network.serverpackets.MagicSkillUse;\nimport org.l2j.gameserver.util.Broadcast;\nimport static org.l2j.commons.util.Util.isNullOrEmpty;\n\n/**\n * @author JoeAlisson\n */\npublic abstract class AbstractShot implements IItemHandler {\n\n @Override\n public boolean useItem(Playable playable, Item item, boolean forceUse) {", "post_mask_code": "\n // Check if Soul shot can be used\n if (!canUse(player)) {\n return false;\n }\n player.chargeShot(getShotType(), getBonus(player));\n player.sendPacket(getEnabledShotsMessage());\n EventDispatcher.getInstance().notifyEventAsync(new OnPlayeableChargeShots(player, getShotType(), isBlessed()), player);\n skills.forEach(holder -> Broadcast.toSelfAndKnownPlayersInRadius(player, new MagicSkillUse(player, player, holder.getSkillId(), holder.getLevel(), 0, 0), 600));\n return true;\n }\n\n protected abstract boolean isBlessed();\n\n protected abstract double getBonus(Player player);\n\n protected abstract boolean canUse(Player player);\n\n protected abstract ShotType getShotType();\n\n protected abstract SystemMessageId getEnabledShotsMessage();\n}\n"} {"task_id": "Java_1857", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/JoeAlisson/L2jOrg/Datapack/gameserver/data/scripts/org.l2j.scripts/handlers/itemhandlers/AbstractShot.java", "mask_start_position": 1167, "mask_end_position": 1380, "canonical_solution": "// Check if Soul shot can be used\n if (!canUse(player)) {\n return false;\n }\n player.chargeShot(getShotType(), getBonus(player));\n player.sendPacket(getEnabledShotsMessage());", "pre_mask_code": "/*\n *\n * This file is part of the L2JOrg project.\n *\n */\npackage handlers.itemhandlers;\n\nimport org.l2j.gameserver.enums.ItemSkillType;\nimport org.l2j.gameserver.enums.ShotType;\nimport org.l2j.gameserver.handler.IItemHandler;\nimport org.l2j.gameserver.model.actor.Playable;\nimport org.l2j.gameserver.model.actor.instance.Player;\nimport org.l2j.gameserver.model.events.EventDispatcher;\nimport org.l2j.gameserver.model.events.impl.character.player.OnPlayeableChargeShots;\nimport org.l2j.gameserver.model.item.instance.Item;\nimport org.l2j.gameserver.network.SystemMessageId;\nimport org.l2j.gameserver.network.serverpackets.MagicSkillUse;\nimport org.l2j.gameserver.util.Broadcast;\nimport static org.l2j.commons.util.Util.isNullOrEmpty;\n\n/**\n * @author JoeAlisson\n */\npublic abstract class AbstractShot implements IItemHandler {\n\n @Override\n public boolean useItem(Playable playable, Item item, boolean forceUse) {\n var player = playable.getActingPlayer();\n var skills = item.getSkills(ItemSkillType.NORMAL);\n if (isNullOrEmpty(skills)) {\n LOGGER.warn(\"item {} is missing skills!\", item);\n return false;\n }\n ", "post_mask_code": "\n EventDispatcher.getInstance().notifyEventAsync(new OnPlayeableChargeShots(player, getShotType(), isBlessed()), player);\n skills.forEach(holder -> Broadcast.toSelfAndKnownPlayersInRadius(player, new MagicSkillUse(player, player, holder.getSkillId(), holder.getLevel(), 0, 0), 600));\n return true;\n }\n\n protected abstract boolean isBlessed();\n\n protected abstract double getBonus(Player player);\n\n protected abstract boolean canUse(Player player);\n\n protected abstract ShotType getShotType();\n\n protected abstract SystemMessageId getEnabledShotsMessage();\n}\n"} {"task_id": "Java_1858", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/JoeAlisson/L2jOrg/Datapack/gameserver/data/scripts/org.l2j.scripts/handlers/itemhandlers/AbstractShot.java", "mask_start_position": 1389, "mask_end_position": 1704, "canonical_solution": "EventDispatcher.getInstance().notifyEventAsync(new OnPlayeableChargeShots(player, getShotType(), isBlessed()), player);\n skills.forEach(holder -> Broadcast.toSelfAndKnownPlayersInRadius(player, new MagicSkillUse(player, player, holder.getSkillId(), holder.getLevel(), 0, 0), 600));\n return true;\n }", "pre_mask_code": "/*\n *\n * This file is part of the L2JOrg project.\n *\n */\npackage handlers.itemhandlers;\n\nimport org.l2j.gameserver.enums.ItemSkillType;\nimport org.l2j.gameserver.enums.ShotType;\nimport org.l2j.gameserver.handler.IItemHandler;\nimport org.l2j.gameserver.model.actor.Playable;\nimport org.l2j.gameserver.model.actor.instance.Player;\nimport org.l2j.gameserver.model.events.EventDispatcher;\nimport org.l2j.gameserver.model.events.impl.character.player.OnPlayeableChargeShots;\nimport org.l2j.gameserver.model.item.instance.Item;\nimport org.l2j.gameserver.network.SystemMessageId;\nimport org.l2j.gameserver.network.serverpackets.MagicSkillUse;\nimport org.l2j.gameserver.util.Broadcast;\nimport static org.l2j.commons.util.Util.isNullOrEmpty;\n\n/**\n * @author JoeAlisson\n */\npublic abstract class AbstractShot implements IItemHandler {\n\n @Override\n public boolean useItem(Playable playable, Item item, boolean forceUse) {\n var player = playable.getActingPlayer();\n var skills = item.getSkills(ItemSkillType.NORMAL);\n if (isNullOrEmpty(skills)) {\n LOGGER.warn(\"item {} is missing skills!\", item);\n return false;\n }\n // Check if Soul shot can be used\n if (!canUse(player)) {\n return false;\n }\n player.chargeShot(getShotType(), getBonus(player));\n player.sendPacket(getEnabledShotsMessage());\n ", "post_mask_code": "\n\n protected abstract boolean isBlessed();\n\n protected abstract double getBonus(Player player);\n\n protected abstract boolean canUse(Player player);\n\n protected abstract ShotType getShotType();\n\n protected abstract SystemMessageId getEnabledShotsMessage();\n}\n"} {"task_id": "Java_1859", "language": "Java", "task_type": "single_line", "source_file": "java/github/JoeAlisson/L2jOrg/Datapack/gameserver/data/scripts/org.l2j.scripts/handlers/itemhandlers/AbstractShot.java", "mask_start_position": 990, "mask_end_position": 1024, "canonical_solution": "m.getSkills(ItemSkillType.NORMAL);", "pre_mask_code": "/*\n *\n * This file is part of the L2JOrg project.\n *\n */\npackage handlers.itemhandlers;\n\nimport org.l2j.gameserver.enums.ItemSkillType;\nimport org.l2j.gameserver.enums.ShotType;\nimport org.l2j.gameserver.handler.IItemHandler;\nimport org.l2j.gameserver.model.actor.Playable;\nimport org.l2j.gameserver.model.actor.instance.Player;\nimport org.l2j.gameserver.model.events.EventDispatcher;\nimport org.l2j.gameserver.model.events.impl.character.player.OnPlayeableChargeShots;\nimport org.l2j.gameserver.model.item.instance.Item;\nimport org.l2j.gameserver.network.SystemMessageId;\nimport org.l2j.gameserver.network.serverpackets.MagicSkillUse;\nimport org.l2j.gameserver.util.Broadcast;\nimport static org.l2j.commons.util.Util.isNullOrEmpty;\n\n/**\n * @author JoeAlisson\n */\npublic abstract class AbstractShot implements IItemHandler {\n\n @Override\n public boolean useItem(Playable playable, Item item, boolean forceUse) {\n var player = playable.getActingPlayer();\n var skills = ite", "post_mask_code": "\n if (isNullOrEmpty(skills)) {\n LOGGER.warn(\"item {} is missing skills!\", item);\n return false;\n }\n // Check if Soul shot can be used\n if (!canUse(player)) {\n return false;\n }\n player.chargeShot(getShotType(), getBonus(player));\n player.sendPacket(getEnabledShotsMessage());\n EventDispatcher.getInstance().notifyEventAsync(new OnPlayeableChargeShots(player, getShotType(), isBlessed()), player);\n skills.forEach(holder -> Broadcast.toSelfAndKnownPlayersInRadius(player, new MagicSkillUse(player, player, holder.getSkillId(), holder.getLevel(), 0, 0), 600));\n return true;\n }\n\n protected abstract boolean isBlessed();\n\n protected abstract double getBonus(Player player);\n\n protected abstract boolean canUse(Player player);\n\n protected abstract ShotType getShotType();\n\n protected abstract SystemMessageId getEnabledShotsMessage();\n}\n"} {"task_id": "Java_1860", "language": "Java", "task_type": "if_statement", "source_file": "java/github/JoeAlisson/L2jOrg/Datapack/gameserver/data/scripts/org.l2j.scripts/handlers/itemhandlers/AbstractShot.java", "mask_start_position": 1033, "mask_end_position": 1158, "canonical_solution": "if (isNullOrEmpty(skills)) {\n LOGGER.warn(\"item {} is missing skills!\", item);\n return false;\n }", "pre_mask_code": "/*\n *\n * This file is part of the L2JOrg project.\n *\n */\npackage handlers.itemhandlers;\n\nimport org.l2j.gameserver.enums.ItemSkillType;\nimport org.l2j.gameserver.enums.ShotType;\nimport org.l2j.gameserver.handler.IItemHandler;\nimport org.l2j.gameserver.model.actor.Playable;\nimport org.l2j.gameserver.model.actor.instance.Player;\nimport org.l2j.gameserver.model.events.EventDispatcher;\nimport org.l2j.gameserver.model.events.impl.character.player.OnPlayeableChargeShots;\nimport org.l2j.gameserver.model.item.instance.Item;\nimport org.l2j.gameserver.network.SystemMessageId;\nimport org.l2j.gameserver.network.serverpackets.MagicSkillUse;\nimport org.l2j.gameserver.util.Broadcast;\nimport static org.l2j.commons.util.Util.isNullOrEmpty;\n\n/**\n * @author JoeAlisson\n */\npublic abstract class AbstractShot implements IItemHandler {\n\n @Override\n public boolean useItem(Playable playable, Item item, boolean forceUse) {\n var player = playable.getActingPlayer();\n var skills = item.getSkills(ItemSkillType.NORMAL);\n ", "post_mask_code": "\n // Check if Soul shot can be used\n if (!canUse(player)) {\n return false;\n }\n player.chargeShot(getShotType(), getBonus(player));\n player.sendPacket(getEnabledShotsMessage());\n EventDispatcher.getInstance().notifyEventAsync(new OnPlayeableChargeShots(player, getShotType(), isBlessed()), player);\n skills.forEach(holder -> Broadcast.toSelfAndKnownPlayersInRadius(player, new MagicSkillUse(player, player, holder.getSkillId(), holder.getLevel(), 0, 0), 600));\n return true;\n }\n\n protected abstract boolean isBlessed();\n\n protected abstract double getBonus(Player player);\n\n protected abstract boolean canUse(Player player);\n\n protected abstract ShotType getShotType();\n\n protected abstract SystemMessageId getEnabledShotsMessage();\n}\n"} {"task_id": "Java_1861", "language": "Java", "task_type": "method_signature", "source_file": "java/github/quartz-scheduler/quartz/distribution/examples/src/main/java/org/quartz/examples/example4/JobStateExample.java", "mask_start_position": 3792, "mask_end_position": 3848, "canonical_solution": "public static void main(String[] args) throws Exception ", "pre_mask_code": "package org.quartz.examples.example4;\n\nimport static org.quartz.DateBuilder.nextGivenSecondDate;\nimport static org.quartz.JobBuilder.newJob;\nimport static org.quartz.SimpleScheduleBuilder.simpleSchedule;\nimport static org.quartz.TriggerBuilder.newTrigger;\nimport org.quartz.JobDetail;\nimport org.quartz.Scheduler;\nimport org.quartz.SchedulerFactory;\nimport org.quartz.SchedulerMetaData;\nimport org.quartz.SimpleTrigger;\nimport org.quartz.impl.StdSchedulerFactory;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.Date;\n\n/**\n * This Example will demonstrate how job parameters can be passed into jobs and how state can be maintained\n *\n * @author Bill Kratzer\n */\npublic class JobStateExample {\n\n public void run() throws Exception {\n Logger log = LoggerFactory.getLogger(JobStateExample.class);\n log.info(\"------- Initializing -------------------\");\n // First we must get a reference to a scheduler\n SchedulerFactory sf = new StdSchedulerFactory();\n Scheduler sched = sf.getScheduler();\n log.info(\"------- Initialization Complete --------\");\n log.info(\"------- Scheduling Jobs ----------------\");\n // get a \"nice round\" time a few seconds in the future....\n Date startTime = nextGivenSecondDate(null, 10);\n // job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds\n JobDetail job1 = newJob(ColorJob.class).withIdentity(\"job1\", \"group1\").build();\n SimpleTrigger trigger1 = newTrigger().withIdentity(\"trigger1\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Green\");\n job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime1 = sched.scheduleJob(job1, trigger1);\n log.info(job1.getKey() + \" will run at: \" + scheduleTime1 + \" and repeat: \" + trigger1.getRepeatCount() + \" times, every \" + trigger1.getRepeatInterval() / 1000 + \" seconds\");\n // job2 will also run 5 times, every 10 seconds\n JobDetail job2 = newJob(ColorJob.class).withIdentity(\"job2\", \"group1\").build();\n SimpleTrigger trigger2 = newTrigger().withIdentity(\"trigger2\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n // this job has a different favorite color!\n job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Red\");\n job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime2 = sched.scheduleJob(job2, trigger2);\n log.info(job2.getKey().toString() + \" will run at: \" + scheduleTime2 + \" and repeat: \" + trigger2.getRepeatCount() + \" times, every \" + trigger2.getRepeatInterval() / 1000 + \" seconds\");\n log.info(\"------- Starting Scheduler ----------------\");\n // All of the jobs have been added to the scheduler, but none of the jobs\n // will run until the scheduler has been started\n sched.start();\n log.info(\"------- Started Scheduler -----------------\");\n log.info(\"------- Waiting 60 seconds... -------------\");\n try {\n // wait five minutes to show jobs\n Thread.sleep(60L * 1000L);\n } catch (Exception e) {\n }\n log.info(\"------- Shutting Down ---------------------\");\n sched.shutdown(true);\n log.info(\"------- Shutdown Complete -----------------\");\n SchedulerMetaData metaData = sched.getMetaData();\n log.info(\"Executed \" + metaData.getNumberOfJobsExecuted() + \" jobs.\");\n }\n\n ", "post_mask_code": "{\n JobStateExample example = new JobStateExample();\n example.run();\n }\n}\n"} {"task_id": "Java_1862", "language": "Java", "task_type": "method_body", "source_file": "java/github/quartz-scheduler/quartz/distribution/examples/src/main/java/org/quartz/examples/example4/JobStateExample.java", "mask_start_position": 3848, "mask_end_position": 3935, "canonical_solution": "{\n JobStateExample example = new JobStateExample();\n example.run();\n }", "pre_mask_code": "package org.quartz.examples.example4;\n\nimport static org.quartz.DateBuilder.nextGivenSecondDate;\nimport static org.quartz.JobBuilder.newJob;\nimport static org.quartz.SimpleScheduleBuilder.simpleSchedule;\nimport static org.quartz.TriggerBuilder.newTrigger;\nimport org.quartz.JobDetail;\nimport org.quartz.Scheduler;\nimport org.quartz.SchedulerFactory;\nimport org.quartz.SchedulerMetaData;\nimport org.quartz.SimpleTrigger;\nimport org.quartz.impl.StdSchedulerFactory;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.Date;\n\n/**\n * This Example will demonstrate how job parameters can be passed into jobs and how state can be maintained\n *\n * @author Bill Kratzer\n */\npublic class JobStateExample {\n\n public void run() throws Exception {\n Logger log = LoggerFactory.getLogger(JobStateExample.class);\n log.info(\"------- Initializing -------------------\");\n // First we must get a reference to a scheduler\n SchedulerFactory sf = new StdSchedulerFactory();\n Scheduler sched = sf.getScheduler();\n log.info(\"------- Initialization Complete --------\");\n log.info(\"------- Scheduling Jobs ----------------\");\n // get a \"nice round\" time a few seconds in the future....\n Date startTime = nextGivenSecondDate(null, 10);\n // job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds\n JobDetail job1 = newJob(ColorJob.class).withIdentity(\"job1\", \"group1\").build();\n SimpleTrigger trigger1 = newTrigger().withIdentity(\"trigger1\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Green\");\n job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime1 = sched.scheduleJob(job1, trigger1);\n log.info(job1.getKey() + \" will run at: \" + scheduleTime1 + \" and repeat: \" + trigger1.getRepeatCount() + \" times, every \" + trigger1.getRepeatInterval() / 1000 + \" seconds\");\n // job2 will also run 5 times, every 10 seconds\n JobDetail job2 = newJob(ColorJob.class).withIdentity(\"job2\", \"group1\").build();\n SimpleTrigger trigger2 = newTrigger().withIdentity(\"trigger2\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n // this job has a different favorite color!\n job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Red\");\n job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime2 = sched.scheduleJob(job2, trigger2);\n log.info(job2.getKey().toString() + \" will run at: \" + scheduleTime2 + \" and repeat: \" + trigger2.getRepeatCount() + \" times, every \" + trigger2.getRepeatInterval() / 1000 + \" seconds\");\n log.info(\"------- Starting Scheduler ----------------\");\n // All of the jobs have been added to the scheduler, but none of the jobs\n // will run until the scheduler has been started\n sched.start();\n log.info(\"------- Started Scheduler -----------------\");\n log.info(\"------- Waiting 60 seconds... -------------\");\n try {\n // wait five minutes to show jobs\n Thread.sleep(60L * 1000L);\n } catch (Exception e) {\n }\n log.info(\"------- Shutting Down ---------------------\");\n sched.shutdown(true);\n log.info(\"------- Shutdown Complete -----------------\");\n SchedulerMetaData metaData = sched.getMetaData();\n log.info(\"Executed \" + metaData.getNumberOfJobsExecuted() + \" jobs.\");\n }\n\n public static void main(String[] args) throws Exception ", "post_mask_code": "\n}\n"} {"task_id": "Java_1863", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/quartz-scheduler/quartz/distribution/examples/src/main/java/org/quartz/examples/example4/JobStateExample.java", "mask_start_position": 760, "mask_end_position": 1712, "canonical_solution": "\n Logger log = LoggerFactory.getLogger(JobStateExample.class);\n log.info(\"------- Initializing -------------------\");\n // First we must get a reference to a scheduler\n SchedulerFactory sf = new StdSchedulerFactory();\n Scheduler sched = sf.getScheduler();\n log.info(\"------- Initialization Complete --------\");\n log.info(\"------- Scheduling Jobs ----------------\");\n // get a \"nice round\" time a few seconds in the future....\n Date startTime = nextGivenSecondDate(null, 10);\n // job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds\n JobDetail job1 = newJob(ColorJob.class).withIdentity(\"job1\", \"group1\").build();\n SimpleTrigger trigger1 = newTrigger().withIdentity(\"trigger1\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job", "pre_mask_code": "package org.quartz.examples.example4;\n\nimport static org.quartz.DateBuilder.nextGivenSecondDate;\nimport static org.quartz.JobBuilder.newJob;\nimport static org.quartz.SimpleScheduleBuilder.simpleSchedule;\nimport static org.quartz.TriggerBuilder.newTrigger;\nimport org.quartz.JobDetail;\nimport org.quartz.Scheduler;\nimport org.quartz.SchedulerFactory;\nimport org.quartz.SchedulerMetaData;\nimport org.quartz.SimpleTrigger;\nimport org.quartz.impl.StdSchedulerFactory;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.Date;\n\n/**\n * This Example will demonstrate how job parameters can be passed into jobs and how state can be maintained\n *\n * @author Bill Kratzer\n */\npublic class JobStateExample {\n\n public void run() throws Exception {", "post_mask_code": "\n job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Green\");\n job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime1 = sched.scheduleJob(job1, trigger1);\n log.info(job1.getKey() + \" will run at: \" + scheduleTime1 + \" and repeat: \" + trigger1.getRepeatCount() + \" times, every \" + trigger1.getRepeatInterval() / 1000 + \" seconds\");\n // job2 will also run 5 times, every 10 seconds\n JobDetail job2 = newJob(ColorJob.class).withIdentity(\"job2\", \"group1\").build();\n SimpleTrigger trigger2 = newTrigger().withIdentity(\"trigger2\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n // this job has a different favorite color!\n job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Red\");\n job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime2 = sched.scheduleJob(job2, trigger2);\n log.info(job2.getKey().toString() + \" will run at: \" + scheduleTime2 + \" and repeat: \" + trigger2.getRepeatCount() + \" times, every \" + trigger2.getRepeatInterval() / 1000 + \" seconds\");\n log.info(\"------- Starting Scheduler ----------------\");\n // All of the jobs have been added to the scheduler, but none of the jobs\n // will run until the scheduler has been started\n sched.start();\n log.info(\"------- Started Scheduler -----------------\");\n log.info(\"------- Waiting 60 seconds... -------------\");\n try {\n // wait five minutes to show jobs\n Thread.sleep(60L * 1000L);\n } catch (Exception e) {\n }\n log.info(\"------- Shutting Down ---------------------\");\n sched.shutdown(true);\n log.info(\"------- Shutdown Complete -----------------\");\n SchedulerMetaData metaData = sched.getMetaData();\n log.info(\"Executed \" + metaData.getNumberOfJobsExecuted() + \" jobs.\");\n }\n\n public static void main(String[] args) throws Exception {\n JobStateExample example = new JobStateExample();\n example.run();\n }\n}\n"} {"task_id": "Java_1864", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/quartz-scheduler/quartz/distribution/examples/src/main/java/org/quartz/examples/example4/JobStateExample.java", "mask_start_position": 1721, "mask_end_position": 2790, "canonical_solution": "job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Green\");\n job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime1 = sched.scheduleJob(job1, trigger1);\n log.info(job1.getKey() + \" will run at: \" + scheduleTime1 + \" and repeat: \" + trigger1.getRepeatCount() + \" times, every \" + trigger1.getRepeatInterval() / 1000 + \" seconds\");\n // job2 will also run 5 times, every 10 seconds\n JobDetail job2 = newJob(ColorJob.class).withIdentity(\"job2\", \"group1\").build();\n SimpleTrigger trigger2 = newTrigger().withIdentity(\"trigger2\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n // this job has a different favorite color!\n job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Red\");\n job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime2 = sched.scheduleJob(job2, trigger2);", "pre_mask_code": "package org.quartz.examples.example4;\n\nimport static org.quartz.DateBuilder.nextGivenSecondDate;\nimport static org.quartz.JobBuilder.newJob;\nimport static org.quartz.SimpleScheduleBuilder.simpleSchedule;\nimport static org.quartz.TriggerBuilder.newTrigger;\nimport org.quartz.JobDetail;\nimport org.quartz.Scheduler;\nimport org.quartz.SchedulerFactory;\nimport org.quartz.SchedulerMetaData;\nimport org.quartz.SimpleTrigger;\nimport org.quartz.impl.StdSchedulerFactory;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.Date;\n\n/**\n * This Example will demonstrate how job parameters can be passed into jobs and how state can be maintained\n *\n * @author Bill Kratzer\n */\npublic class JobStateExample {\n\n public void run() throws Exception {\n Logger log = LoggerFactory.getLogger(JobStateExample.class);\n log.info(\"------- Initializing -------------------\");\n // First we must get a reference to a scheduler\n SchedulerFactory sf = new StdSchedulerFactory();\n Scheduler sched = sf.getScheduler();\n log.info(\"------- Initialization Complete --------\");\n log.info(\"------- Scheduling Jobs ----------------\");\n // get a \"nice round\" time a few seconds in the future....\n Date startTime = nextGivenSecondDate(null, 10);\n // job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds\n JobDetail job1 = newJob(ColorJob.class).withIdentity(\"job1\", \"group1\").build();\n SimpleTrigger trigger1 = newTrigger().withIdentity(\"trigger1\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n ", "post_mask_code": "\n log.info(job2.getKey().toString() + \" will run at: \" + scheduleTime2 + \" and repeat: \" + trigger2.getRepeatCount() + \" times, every \" + trigger2.getRepeatInterval() / 1000 + \" seconds\");\n log.info(\"------- Starting Scheduler ----------------\");\n // All of the jobs have been added to the scheduler, but none of the jobs\n // will run until the scheduler has been started\n sched.start();\n log.info(\"------- Started Scheduler -----------------\");\n log.info(\"------- Waiting 60 seconds... -------------\");\n try {\n // wait five minutes to show jobs\n Thread.sleep(60L * 1000L);\n } catch (Exception e) {\n }\n log.info(\"------- Shutting Down ---------------------\");\n sched.shutdown(true);\n log.info(\"------- Shutdown Complete -----------------\");\n SchedulerMetaData metaData = sched.getMetaData();\n log.info(\"Executed \" + metaData.getNumberOfJobsExecuted() + \" jobs.\");\n }\n\n public static void main(String[] args) throws Exception {\n JobStateExample example = new JobStateExample();\n example.run();\n }\n}\n"} {"task_id": "Java_1865", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/quartz-scheduler/quartz/distribution/examples/src/main/java/org/quartz/examples/example4/JobStateExample.java", "mask_start_position": 2799, "mask_end_position": 3786, "canonical_solution": "log.info(job2.getKey().toString() + \" will run at: \" + scheduleTime2 + \" and repeat: \" + trigger2.getRepeatCount() + \" times, every \" + trigger2.getRepeatInterval() / 1000 + \" seconds\");\n log.info(\"------- Starting Scheduler ----------------\");\n // All of the jobs have been added to the scheduler, but none of the jobs\n // will run until the scheduler has been started\n sched.start();\n log.info(\"------- Started Scheduler -----------------\");\n log.info(\"------- Waiting 60 seconds... -------------\");\n try {\n // wait five minutes to show jobs\n Thread.sleep(60L * 1000L);\n } catch (Exception e) {\n }\n log.info(\"------- Shutting Down ---------------------\");\n sched.shutdown(true);\n log.info(\"------- Shutdown Complete -----------------\");\n SchedulerMetaData metaData = sched.getMetaData();\n log.info(\"Executed \" + metaData.getNumberOfJobsExecuted() + \" jobs.\");\n }", "pre_mask_code": "package org.quartz.examples.example4;\n\nimport static org.quartz.DateBuilder.nextGivenSecondDate;\nimport static org.quartz.JobBuilder.newJob;\nimport static org.quartz.SimpleScheduleBuilder.simpleSchedule;\nimport static org.quartz.TriggerBuilder.newTrigger;\nimport org.quartz.JobDetail;\nimport org.quartz.Scheduler;\nimport org.quartz.SchedulerFactory;\nimport org.quartz.SchedulerMetaData;\nimport org.quartz.SimpleTrigger;\nimport org.quartz.impl.StdSchedulerFactory;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.Date;\n\n/**\n * This Example will demonstrate how job parameters can be passed into jobs and how state can be maintained\n *\n * @author Bill Kratzer\n */\npublic class JobStateExample {\n\n public void run() throws Exception {\n Logger log = LoggerFactory.getLogger(JobStateExample.class);\n log.info(\"------- Initializing -------------------\");\n // First we must get a reference to a scheduler\n SchedulerFactory sf = new StdSchedulerFactory();\n Scheduler sched = sf.getScheduler();\n log.info(\"------- Initialization Complete --------\");\n log.info(\"------- Scheduling Jobs ----------------\");\n // get a \"nice round\" time a few seconds in the future....\n Date startTime = nextGivenSecondDate(null, 10);\n // job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds\n JobDetail job1 = newJob(ColorJob.class).withIdentity(\"job1\", \"group1\").build();\n SimpleTrigger trigger1 = newTrigger().withIdentity(\"trigger1\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Green\");\n job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime1 = sched.scheduleJob(job1, trigger1);\n log.info(job1.getKey() + \" will run at: \" + scheduleTime1 + \" and repeat: \" + trigger1.getRepeatCount() + \" times, every \" + trigger1.getRepeatInterval() / 1000 + \" seconds\");\n // job2 will also run 5 times, every 10 seconds\n JobDetail job2 = newJob(ColorJob.class).withIdentity(\"job2\", \"group1\").build();\n SimpleTrigger trigger2 = newTrigger().withIdentity(\"trigger2\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n // this job has a different favorite color!\n job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Red\");\n job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime2 = sched.scheduleJob(job2, trigger2);\n ", "post_mask_code": "\n\n public static void main(String[] args) throws Exception {\n JobStateExample example = new JobStateExample();\n example.run();\n }\n}\n"} {"task_id": "Java_1866", "language": "Java", "task_type": "single_line", "source_file": "java/github/quartz-scheduler/quartz/distribution/examples/src/main/java/org/quartz/examples/example4/JobStateExample.java", "mask_start_position": 1286, "mask_end_position": 1296, "canonical_solution": "null, 10);", "pre_mask_code": "package org.quartz.examples.example4;\n\nimport static org.quartz.DateBuilder.nextGivenSecondDate;\nimport static org.quartz.JobBuilder.newJob;\nimport static org.quartz.SimpleScheduleBuilder.simpleSchedule;\nimport static org.quartz.TriggerBuilder.newTrigger;\nimport org.quartz.JobDetail;\nimport org.quartz.Scheduler;\nimport org.quartz.SchedulerFactory;\nimport org.quartz.SchedulerMetaData;\nimport org.quartz.SimpleTrigger;\nimport org.quartz.impl.StdSchedulerFactory;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.Date;\n\n/**\n * This Example will demonstrate how job parameters can be passed into jobs and how state can be maintained\n *\n * @author Bill Kratzer\n */\npublic class JobStateExample {\n\n public void run() throws Exception {\n Logger log = LoggerFactory.getLogger(JobStateExample.class);\n log.info(\"------- Initializing -------------------\");\n // First we must get a reference to a scheduler\n SchedulerFactory sf = new StdSchedulerFactory();\n Scheduler sched = sf.getScheduler();\n log.info(\"------- Initialization Complete --------\");\n log.info(\"------- Scheduling Jobs ----------------\");\n // get a \"nice round\" time a few seconds in the future....\n Date startTime = nextGivenSecondDate(", "post_mask_code": "\n // job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds\n JobDetail job1 = newJob(ColorJob.class).withIdentity(\"job1\", \"group1\").build();\n SimpleTrigger trigger1 = newTrigger().withIdentity(\"trigger1\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Green\");\n job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime1 = sched.scheduleJob(job1, trigger1);\n log.info(job1.getKey() + \" will run at: \" + scheduleTime1 + \" and repeat: \" + trigger1.getRepeatCount() + \" times, every \" + trigger1.getRepeatInterval() / 1000 + \" seconds\");\n // job2 will also run 5 times, every 10 seconds\n JobDetail job2 = newJob(ColorJob.class).withIdentity(\"job2\", \"group1\").build();\n SimpleTrigger trigger2 = newTrigger().withIdentity(\"trigger2\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n // this job has a different favorite color!\n job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Red\");\n job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime2 = sched.scheduleJob(job2, trigger2);\n log.info(job2.getKey().toString() + \" will run at: \" + scheduleTime2 + \" and repeat: \" + trigger2.getRepeatCount() + \" times, every \" + trigger2.getRepeatInterval() / 1000 + \" seconds\");\n log.info(\"------- Starting Scheduler ----------------\");\n // All of the jobs have been added to the scheduler, but none of the jobs\n // will run until the scheduler has been started\n sched.start();\n log.info(\"------- Started Scheduler -----------------\");\n log.info(\"------- Waiting 60 seconds... -------------\");\n try {\n // wait five minutes to show jobs\n Thread.sleep(60L * 1000L);\n } catch (Exception e) {\n }\n log.info(\"------- Shutting Down ---------------------\");\n sched.shutdown(true);\n log.info(\"------- Shutdown Complete -----------------\");\n SchedulerMetaData metaData = sched.getMetaData();\n log.info(\"Executed \" + metaData.getNumberOfJobsExecuted() + \" jobs.\");\n }\n\n public static void main(String[] args) throws Exception {\n JobStateExample example = new JobStateExample();\n example.run();\n }\n}\n"} {"task_id": "Java_1867", "language": "Java", "task_type": "try_statement", "source_file": "java/github/quartz-scheduler/quartz/distribution/examples/src/main/java/org/quartz/examples/example4/JobStateExample.java", "mask_start_position": 3351, "mask_end_position": 3483, "canonical_solution": "try {\n // wait five minutes to show jobs\n Thread.sleep(60L * 1000L);\n } catch (Exception e) {\n }", "pre_mask_code": "package org.quartz.examples.example4;\n\nimport static org.quartz.DateBuilder.nextGivenSecondDate;\nimport static org.quartz.JobBuilder.newJob;\nimport static org.quartz.SimpleScheduleBuilder.simpleSchedule;\nimport static org.quartz.TriggerBuilder.newTrigger;\nimport org.quartz.JobDetail;\nimport org.quartz.Scheduler;\nimport org.quartz.SchedulerFactory;\nimport org.quartz.SchedulerMetaData;\nimport org.quartz.SimpleTrigger;\nimport org.quartz.impl.StdSchedulerFactory;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.util.Date;\n\n/**\n * This Example will demonstrate how job parameters can be passed into jobs and how state can be maintained\n *\n * @author Bill Kratzer\n */\npublic class JobStateExample {\n\n public void run() throws Exception {\n Logger log = LoggerFactory.getLogger(JobStateExample.class);\n log.info(\"------- Initializing -------------------\");\n // First we must get a reference to a scheduler\n SchedulerFactory sf = new StdSchedulerFactory();\n Scheduler sched = sf.getScheduler();\n log.info(\"------- Initialization Complete --------\");\n log.info(\"------- Scheduling Jobs ----------------\");\n // get a \"nice round\" time a few seconds in the future....\n Date startTime = nextGivenSecondDate(null, 10);\n // job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds\n JobDetail job1 = newJob(ColorJob.class).withIdentity(\"job1\", \"group1\").build();\n SimpleTrigger trigger1 = newTrigger().withIdentity(\"trigger1\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Green\");\n job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime1 = sched.scheduleJob(job1, trigger1);\n log.info(job1.getKey() + \" will run at: \" + scheduleTime1 + \" and repeat: \" + trigger1.getRepeatCount() + \" times, every \" + trigger1.getRepeatInterval() / 1000 + \" seconds\");\n // job2 will also run 5 times, every 10 seconds\n JobDetail job2 = newJob(ColorJob.class).withIdentity(\"job2\", \"group1\").build();\n SimpleTrigger trigger2 = newTrigger().withIdentity(\"trigger2\", \"group1\").startAt(startTime).withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();\n // pass initialization parameters into the job\n // this job has a different favorite color!\n job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, \"Red\");\n job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);\n // schedule the job to run\n Date scheduleTime2 = sched.scheduleJob(job2, trigger2);\n log.info(job2.getKey().toString() + \" will run at: \" + scheduleTime2 + \" and repeat: \" + trigger2.getRepeatCount() + \" times, every \" + trigger2.getRepeatInterval() / 1000 + \" seconds\");\n log.info(\"------- Starting Scheduler ----------------\");\n // All of the jobs have been added to the scheduler, but none of the jobs\n // will run until the scheduler has been started\n sched.start();\n log.info(\"------- Started Scheduler -----------------\");\n log.info(\"------- Waiting 60 seconds... -------------\");\n ", "post_mask_code": "\n log.info(\"------- Shutting Down ---------------------\");\n sched.shutdown(true);\n log.info(\"------- Shutdown Complete -----------------\");\n SchedulerMetaData metaData = sched.getMetaData();\n log.info(\"Executed \" + metaData.getNumberOfJobsExecuted() + \" jobs.\");\n }\n\n public static void main(String[] args) throws Exception {\n JobStateExample example = new JobStateExample();\n example.run();\n }\n}\n"} {"task_id": "Java_1868", "language": "Java", "task_type": "method_signature", "source_file": "java/github/laomengzhu/NsRefreshLayout/nrl/src/main/java/com/xlf/nrl/CircleProgressBar.java", "mask_start_position": 4776, "mask_end_position": 4812, "canonical_solution": "public void setTextColor(int color) ", "pre_mask_code": "package com.xlf.nrl;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.RadialGradient;\nimport android.graphics.Shader;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.ShapeDrawable;\nimport android.graphics.drawable.shapes.OvalShape;\nimport android.net.Uri;\nimport android.support.v4.view.ViewCompat;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.animation.Animation;\nimport android.widget.ImageView;\n\n/**\n * The author is lsjwzh(MaterialLoadingProgressBar) link{http://example.com},\n * I did some slight modifications\n */\npublic class CircleProgressBar extends ImageView {\n\n private static final int KEY_SHADOW_COLOR = 0x1E000000;\n\n private static final int FILL_SHADOW_COLOR = 0x3D000000;\n\n // PX\n private static final float X_OFFSET = 0f;\n\n private static final float Y_OFFSET = 1.75f;\n\n private static final float SHADOW_RADIUS = 3.5f;\n\n private static final int SHADOW_ELEVATION = 4;\n\n public static final int DEFAULT_CIRCLE_BG_LIGHT = 0xFFFAFAFA;\n\n public static final int DEFAULT_CIRCLE_COLOR = 0xFFF00000;\n\n private static final int DEFAULT_CIRCLE_DIAMETER = 40;\n\n private static final int STROKE_WIDTH_LARGE = 3;\n\n public static final int DEFAULT_TEXT_SIZE = 9;\n\n private Animation.AnimationListener mListener;\n\n private int mShadowRadius;\n\n private int mBackGroundColor;\n\n private int mProgressColor;\n\n private int mProgressStokeWidth;\n\n private int mArrowWidth;\n\n private int mArrowHeight;\n\n private int mProgress;\n\n private int mMax;\n\n private int mDiameter;\n\n private int mInnerRadius;\n\n private Paint mTextPaint;\n\n private int mTextColor;\n\n private int mTextSize;\n\n private boolean mIfDrawText;\n\n private boolean mShowArrow;\n\n public MaterialProgressDrawable mProgressDrawable;\n\n private ShapeDrawable mBgCircle;\n\n private boolean mCircleBackgroundEnabled;\n\n private int[] mColors = new int[] { Color.BLACK };\n\n public CircleProgressBar(Context context) {\n super(context);\n init(context, null, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context, attrs, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr) {\n final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar, defStyleAttr, 0);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mBackGroundColor = a.getColor(R.styleable.CircleProgressBar_background_color, DEFAULT_CIRCLE_BG_LIGHT);\n mProgressColor = a.getColor(R.styleable.CircleProgressBar_progress_color, DEFAULT_CIRCLE_COLOR);\n mColors = new int[] { mProgressColor };\n mInnerRadius = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_inner_radius, -1);\n mProgressStokeWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_stoke_width, (int) (STROKE_WIDTH_LARGE * density));\n mArrowWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_width, -1);\n mArrowHeight = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_height, -1);\n mTextSize = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_text_size, (int) (DEFAULT_TEXT_SIZE * density));\n mTextColor = a.getColor(R.styleable.CircleProgressBar_progress_text_color, Color.BLACK);\n mShowArrow = a.getBoolean(R.styleable.CircleProgressBar_show_arrow, true);\n mCircleBackgroundEnabled = a.getBoolean(R.styleable.CircleProgressBar_enable_circle_background, true);\n mProgress = a.getInt(R.styleable.CircleProgressBar_progress, 0);\n mMax = a.getInt(R.styleable.CircleProgressBar_max, 100);\n int textVisible = a.getInt(R.styleable.CircleProgressBar_progress_text_visibility, 1);\n if (textVisible != 1) {\n mIfDrawText = true;\n }\n mTextPaint = new Paint();\n mTextPaint.setStyle(Paint.Style.FILL);\n mTextPaint.setColor(mTextColor);\n mTextPaint.setTextSize(mTextSize);\n mTextPaint.setAntiAlias(true);\n a.recycle();\n mProgressDrawable = new MaterialProgressDrawable(getContext(), this);\n super.setImageDrawable(mProgressDrawable);\n }\n\n public void setProgressBackGroundColor(int color) {\n this.mBackGroundColor = color;\n }\n\n ", "post_mask_code": "{\n this.mTextColor = color;\n }\n\n private boolean elevationSupported() {\n return android.os.Build.VERSION.SDK_INT >= 21;\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n if (!elevationSupported()) {\n setMeasuredDimension(getMeasuredWidth() + mShadowRadius * 2, getMeasuredHeight() + mShadowRadius * 2);\n }\n }\n\n public int getProgressStokeWidth() {\n return mProgressStokeWidth;\n }\n\n public void setProgressStokeWidth(int mProgressStokeWidth) {\n final float density = getContext().getResources().getDisplayMetrics().density;\n this.mProgressStokeWidth = (int) (mProgressStokeWidth * density);\n }\n\n @Override\n protected void onLayout(boolean changed, int left, int top, int right, int bottom) {\n super.onLayout(changed, left, top, right, bottom);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mDiameter = Math.min(getMeasuredWidth(), getMeasuredHeight());\n if (mDiameter <= 0) {\n mDiameter = (int) density * DEFAULT_CIRCLE_DIAMETER;\n }\n if (getBackground() == null && mCircleBackgroundEnabled) {\n final int shadowYOffset = (int) (density * Y_OFFSET);\n final int shadowXOffset = (int) (density * X_OFFSET);\n mShadowRadius = (int) (density * SHADOW_RADIUS);\n if (elevationSupported()) {\n mBgCircle = new ShapeDrawable(new OvalShape());\n ViewCompat.setElevation(this, SHADOW_ELEVATION * density);\n } else {\n OvalShape oval = new OvalShadow(mShadowRadius, mDiameter - mShadowRadius * 2);\n mBgCircle = new ShapeDrawable(oval);\n ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, mBgCircle.getPaint());\n mBgCircle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset, KEY_SHADOW_COLOR);\n final int padding = (int) mShadowRadius;\n // set padding so the inner image sits correctly within the shadow.\n setPadding(padding, padding, padding, padding);\n }\n mBgCircle.getPaint().setColor(mBackGroundColor);\n setBackgroundDrawable(mBgCircle);\n }\n mProgressDrawable.setBackgroundColor(mBackGroundColor);\n mProgressDrawable.setColorSchemeColors(mColors);\n mProgressDrawable.setSizeParameters(mDiameter, mDiameter, mInnerRadius <= 0 ? (mDiameter - mProgressStokeWidth * 2) / 4 : mInnerRadius, mProgressStokeWidth, mArrowWidth < 0 ? mProgressStokeWidth * 4 : mArrowWidth, mArrowHeight < 0 ? mProgressStokeWidth * 2 : mArrowHeight);\n if (isShowArrow()) {\n mProgressDrawable.showArrowOnFirstStart(true);\n mProgressDrawable.setArrowScale(1f);\n mProgressDrawable.showArrow(true);\n }\n super.setImageDrawable(null);\n super.setImageDrawable(mProgressDrawable);\n mProgressDrawable.setAlpha(255);\n if (getVisibility() == VISIBLE) {\n mProgressDrawable.setStartEndTrim(0, (float) 0.8);\n }\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n if (mIfDrawText) {\n String text = String.format(\"%s%%\", mProgress);\n int x = getWidth() / 2 - text.length() * mTextSize / 4;\n int y = getHeight() / 2 + mTextSize / 4;\n canvas.drawText(text, x, y, mTextPaint);\n }\n }\n\n @Override\n final public void setImageResource(int resId) {\n }\n\n public boolean isShowArrow() {\n return mShowArrow;\n }\n\n public void setShowArrow(boolean showArrow) {\n this.mShowArrow = showArrow;\n }\n\n @Override\n final public void setImageURI(Uri uri) {\n super.setImageURI(uri);\n }\n\n @Override\n final public void setImageDrawable(Drawable drawable) {\n }\n\n public void setAnimationListener(Animation.AnimationListener listener) {\n mListener = listener;\n }\n\n @Override\n public void onAnimationStart() {\n super.onAnimationStart();\n if (mListener != null) {\n mListener.onAnimationStart(getAnimation());\n }\n }\n\n @Override\n public void onAnimationEnd() {\n super.onAnimationEnd();\n if (mListener != null) {\n mListener.onAnimationEnd(getAnimation());\n }\n }\n\n /**\n * Set the color resources used in the progress animation from color resources.\n * The first color will also be the color of the bar that grows in response\n * to a user swipe gesture.\n *\n * @param colorResIds\n */\n public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }\n\n /**\n * Set the colors used in the progress animation. The first\n * color will also be the color of the bar that grows in response to a user\n * swipe gesture.\n *\n * @param colors\n */\n public void setColorSchemeColors(int... colors) {\n mColors = colors;\n if (mProgressDrawable != null) {\n mProgressDrawable.setColorSchemeColors(colors);\n }\n }\n\n /**\n * Update the background color of the mBgCircle image view.\n */\n public void setBackgroundColorResource(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }\n\n public void setBackgroundColor(int color) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(color);\n }\n }\n\n public boolean isShowProgressText() {\n return mIfDrawText;\n }\n\n public void setShowProgressText(boolean mIfDrawText) {\n this.mIfDrawText = mIfDrawText;\n }\n\n public int getMax() {\n return mMax;\n }\n\n public void setMax(int max) {\n mMax = max;\n }\n\n public int getProgress() {\n return mProgress;\n }\n\n public void setProgress(int progress) {\n if (getMax() > 0) {\n mProgress = progress;\n }\n invalidate();\n Log.i(\"cjj_log\", \"progress------->>>>\" + progress);\n }\n\n public boolean circleBackgroundEnabled() {\n return mCircleBackgroundEnabled;\n }\n\n public void setCircleBackgroundEnabled(boolean enableCircleBackground) {\n this.mCircleBackgroundEnabled = enableCircleBackground;\n }\n\n @Override\n public int getVisibility() {\n return super.getVisibility();\n }\n\n @Override\n public void setVisibility(int visibility) {\n super.setVisibility(visibility);\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(getVisibility() == VISIBLE, false);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(false, false);\n }\n }\n\n private class OvalShadow extends OvalShape {\n\n private RadialGradient mRadialGradient;\n\n private int mShadowRadius;\n\n private Paint mShadowPaint;\n\n private int mCircleDiameter;\n\n public OvalShadow(int shadowRadius, int circleDiameter) {\n super();\n mShadowPaint = new Paint();\n mShadowRadius = shadowRadius;\n mCircleDiameter = circleDiameter;\n mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2, mShadowRadius, new int[] { FILL_SHADOW_COLOR, Color.TRANSPARENT }, null, Shader.TileMode.CLAMP);\n mShadowPaint.setShader(mRadialGradient);\n }\n\n @Override\n public void draw(Canvas canvas, Paint paint) {\n final int viewWidth = CircleProgressBar.this.getWidth();\n final int viewHeight = CircleProgressBar.this.getHeight();\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius), mShadowPaint);\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);\n }\n }\n\n public void start() {\n mProgressDrawable.start();\n }\n\n public void setStartEndTrim(float startAngle, float endAngle) {\n mProgressDrawable.setStartEndTrim(startAngle, endAngle);\n }\n\n public void stop() {\n mProgressDrawable.stop();\n }\n\n public void setProgressRotation(float rotation) {\n mProgressDrawable.setProgressRotation(rotation);\n }\n}\n"} {"task_id": "Java_1869", "language": "Java", "task_type": "method_body", "source_file": "java/github/laomengzhu/NsRefreshLayout/nrl/src/main/java/com/xlf/nrl/CircleProgressBar.java", "mask_start_position": 10422, "mask_end_position": 10636, "canonical_solution": "{\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }", "pre_mask_code": "package com.xlf.nrl;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.RadialGradient;\nimport android.graphics.Shader;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.ShapeDrawable;\nimport android.graphics.drawable.shapes.OvalShape;\nimport android.net.Uri;\nimport android.support.v4.view.ViewCompat;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.animation.Animation;\nimport android.widget.ImageView;\n\n/**\n * The author is lsjwzh(MaterialLoadingProgressBar) link{http://example.com},\n * I did some slight modifications\n */\npublic class CircleProgressBar extends ImageView {\n\n private static final int KEY_SHADOW_COLOR = 0x1E000000;\n\n private static final int FILL_SHADOW_COLOR = 0x3D000000;\n\n // PX\n private static final float X_OFFSET = 0f;\n\n private static final float Y_OFFSET = 1.75f;\n\n private static final float SHADOW_RADIUS = 3.5f;\n\n private static final int SHADOW_ELEVATION = 4;\n\n public static final int DEFAULT_CIRCLE_BG_LIGHT = 0xFFFAFAFA;\n\n public static final int DEFAULT_CIRCLE_COLOR = 0xFFF00000;\n\n private static final int DEFAULT_CIRCLE_DIAMETER = 40;\n\n private static final int STROKE_WIDTH_LARGE = 3;\n\n public static final int DEFAULT_TEXT_SIZE = 9;\n\n private Animation.AnimationListener mListener;\n\n private int mShadowRadius;\n\n private int mBackGroundColor;\n\n private int mProgressColor;\n\n private int mProgressStokeWidth;\n\n private int mArrowWidth;\n\n private int mArrowHeight;\n\n private int mProgress;\n\n private int mMax;\n\n private int mDiameter;\n\n private int mInnerRadius;\n\n private Paint mTextPaint;\n\n private int mTextColor;\n\n private int mTextSize;\n\n private boolean mIfDrawText;\n\n private boolean mShowArrow;\n\n public MaterialProgressDrawable mProgressDrawable;\n\n private ShapeDrawable mBgCircle;\n\n private boolean mCircleBackgroundEnabled;\n\n private int[] mColors = new int[] { Color.BLACK };\n\n public CircleProgressBar(Context context) {\n super(context);\n init(context, null, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context, attrs, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr) {\n final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar, defStyleAttr, 0);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mBackGroundColor = a.getColor(R.styleable.CircleProgressBar_background_color, DEFAULT_CIRCLE_BG_LIGHT);\n mProgressColor = a.getColor(R.styleable.CircleProgressBar_progress_color, DEFAULT_CIRCLE_COLOR);\n mColors = new int[] { mProgressColor };\n mInnerRadius = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_inner_radius, -1);\n mProgressStokeWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_stoke_width, (int) (STROKE_WIDTH_LARGE * density));\n mArrowWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_width, -1);\n mArrowHeight = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_height, -1);\n mTextSize = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_text_size, (int) (DEFAULT_TEXT_SIZE * density));\n mTextColor = a.getColor(R.styleable.CircleProgressBar_progress_text_color, Color.BLACK);\n mShowArrow = a.getBoolean(R.styleable.CircleProgressBar_show_arrow, true);\n mCircleBackgroundEnabled = a.getBoolean(R.styleable.CircleProgressBar_enable_circle_background, true);\n mProgress = a.getInt(R.styleable.CircleProgressBar_progress, 0);\n mMax = a.getInt(R.styleable.CircleProgressBar_max, 100);\n int textVisible = a.getInt(R.styleable.CircleProgressBar_progress_text_visibility, 1);\n if (textVisible != 1) {\n mIfDrawText = true;\n }\n mTextPaint = new Paint();\n mTextPaint.setStyle(Paint.Style.FILL);\n mTextPaint.setColor(mTextColor);\n mTextPaint.setTextSize(mTextSize);\n mTextPaint.setAntiAlias(true);\n a.recycle();\n mProgressDrawable = new MaterialProgressDrawable(getContext(), this);\n super.setImageDrawable(mProgressDrawable);\n }\n\n public void setProgressBackGroundColor(int color) {\n this.mBackGroundColor = color;\n }\n\n public void setTextColor(int color) {\n this.mTextColor = color;\n }\n\n private boolean elevationSupported() {\n return android.os.Build.VERSION.SDK_INT >= 21;\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n if (!elevationSupported()) {\n setMeasuredDimension(getMeasuredWidth() + mShadowRadius * 2, getMeasuredHeight() + mShadowRadius * 2);\n }\n }\n\n public int getProgressStokeWidth() {\n return mProgressStokeWidth;\n }\n\n public void setProgressStokeWidth(int mProgressStokeWidth) {\n final float density = getContext().getResources().getDisplayMetrics().density;\n this.mProgressStokeWidth = (int) (mProgressStokeWidth * density);\n }\n\n @Override\n protected void onLayout(boolean changed, int left, int top, int right, int bottom) {\n super.onLayout(changed, left, top, right, bottom);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mDiameter = Math.min(getMeasuredWidth(), getMeasuredHeight());\n if (mDiameter <= 0) {\n mDiameter = (int) density * DEFAULT_CIRCLE_DIAMETER;\n }\n if (getBackground() == null && mCircleBackgroundEnabled) {\n final int shadowYOffset = (int) (density * Y_OFFSET);\n final int shadowXOffset = (int) (density * X_OFFSET);\n mShadowRadius = (int) (density * SHADOW_RADIUS);\n if (elevationSupported()) {\n mBgCircle = new ShapeDrawable(new OvalShape());\n ViewCompat.setElevation(this, SHADOW_ELEVATION * density);\n } else {\n OvalShape oval = new OvalShadow(mShadowRadius, mDiameter - mShadowRadius * 2);\n mBgCircle = new ShapeDrawable(oval);\n ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, mBgCircle.getPaint());\n mBgCircle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset, KEY_SHADOW_COLOR);\n final int padding = (int) mShadowRadius;\n // set padding so the inner image sits correctly within the shadow.\n setPadding(padding, padding, padding, padding);\n }\n mBgCircle.getPaint().setColor(mBackGroundColor);\n setBackgroundDrawable(mBgCircle);\n }\n mProgressDrawable.setBackgroundColor(mBackGroundColor);\n mProgressDrawable.setColorSchemeColors(mColors);\n mProgressDrawable.setSizeParameters(mDiameter, mDiameter, mInnerRadius <= 0 ? (mDiameter - mProgressStokeWidth * 2) / 4 : mInnerRadius, mProgressStokeWidth, mArrowWidth < 0 ? mProgressStokeWidth * 4 : mArrowWidth, mArrowHeight < 0 ? mProgressStokeWidth * 2 : mArrowHeight);\n if (isShowArrow()) {\n mProgressDrawable.showArrowOnFirstStart(true);\n mProgressDrawable.setArrowScale(1f);\n mProgressDrawable.showArrow(true);\n }\n super.setImageDrawable(null);\n super.setImageDrawable(mProgressDrawable);\n mProgressDrawable.setAlpha(255);\n if (getVisibility() == VISIBLE) {\n mProgressDrawable.setStartEndTrim(0, (float) 0.8);\n }\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n if (mIfDrawText) {\n String text = String.format(\"%s%%\", mProgress);\n int x = getWidth() / 2 - text.length() * mTextSize / 4;\n int y = getHeight() / 2 + mTextSize / 4;\n canvas.drawText(text, x, y, mTextPaint);\n }\n }\n\n @Override\n final public void setImageResource(int resId) {\n }\n\n public boolean isShowArrow() {\n return mShowArrow;\n }\n\n public void setShowArrow(boolean showArrow) {\n this.mShowArrow = showArrow;\n }\n\n @Override\n final public void setImageURI(Uri uri) {\n super.setImageURI(uri);\n }\n\n @Override\n final public void setImageDrawable(Drawable drawable) {\n }\n\n public void setAnimationListener(Animation.AnimationListener listener) {\n mListener = listener;\n }\n\n @Override\n public void onAnimationStart() {\n super.onAnimationStart();\n if (mListener != null) {\n mListener.onAnimationStart(getAnimation());\n }\n }\n\n @Override\n public void onAnimationEnd() {\n super.onAnimationEnd();\n if (mListener != null) {\n mListener.onAnimationEnd(getAnimation());\n }\n }\n\n /**\n * Set the color resources used in the progress animation from color resources.\n * The first color will also be the color of the bar that grows in response\n * to a user swipe gesture.\n *\n * @param colorResIds\n */\n public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }\n\n /**\n * Set the colors used in the progress animation. The first\n * color will also be the color of the bar that grows in response to a user\n * swipe gesture.\n *\n * @param colors\n */\n public void setColorSchemeColors(int... colors) {\n mColors = colors;\n if (mProgressDrawable != null) {\n mProgressDrawable.setColorSchemeColors(colors);\n }\n }\n\n /**\n * Update the background color of the mBgCircle image view.\n */\n public void setBackgroundColorResource(int colorRes) ", "post_mask_code": "\n\n public void setBackgroundColor(int color) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(color);\n }\n }\n\n public boolean isShowProgressText() {\n return mIfDrawText;\n }\n\n public void setShowProgressText(boolean mIfDrawText) {\n this.mIfDrawText = mIfDrawText;\n }\n\n public int getMax() {\n return mMax;\n }\n\n public void setMax(int max) {\n mMax = max;\n }\n\n public int getProgress() {\n return mProgress;\n }\n\n public void setProgress(int progress) {\n if (getMax() > 0) {\n mProgress = progress;\n }\n invalidate();\n Log.i(\"cjj_log\", \"progress------->>>>\" + progress);\n }\n\n public boolean circleBackgroundEnabled() {\n return mCircleBackgroundEnabled;\n }\n\n public void setCircleBackgroundEnabled(boolean enableCircleBackground) {\n this.mCircleBackgroundEnabled = enableCircleBackground;\n }\n\n @Override\n public int getVisibility() {\n return super.getVisibility();\n }\n\n @Override\n public void setVisibility(int visibility) {\n super.setVisibility(visibility);\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(getVisibility() == VISIBLE, false);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(false, false);\n }\n }\n\n private class OvalShadow extends OvalShape {\n\n private RadialGradient mRadialGradient;\n\n private int mShadowRadius;\n\n private Paint mShadowPaint;\n\n private int mCircleDiameter;\n\n public OvalShadow(int shadowRadius, int circleDiameter) {\n super();\n mShadowPaint = new Paint();\n mShadowRadius = shadowRadius;\n mCircleDiameter = circleDiameter;\n mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2, mShadowRadius, new int[] { FILL_SHADOW_COLOR, Color.TRANSPARENT }, null, Shader.TileMode.CLAMP);\n mShadowPaint.setShader(mRadialGradient);\n }\n\n @Override\n public void draw(Canvas canvas, Paint paint) {\n final int viewWidth = CircleProgressBar.this.getWidth();\n final int viewHeight = CircleProgressBar.this.getHeight();\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius), mShadowPaint);\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);\n }\n }\n\n public void start() {\n mProgressDrawable.start();\n }\n\n public void setStartEndTrim(float startAngle, float endAngle) {\n mProgressDrawable.setStartEndTrim(startAngle, endAngle);\n }\n\n public void stop() {\n mProgressDrawable.stop();\n }\n\n public void setProgressRotation(float rotation) {\n mProgressDrawable.setProgressRotation(rotation);\n }\n}\n"} {"task_id": "Java_1870", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/laomengzhu/NsRefreshLayout/nrl/src/main/java/com/xlf/nrl/CircleProgressBar.java", "mask_start_position": 12217, "mask_end_position": 12255, "canonical_solution": "\n super.onDetachedFromWindow();", "pre_mask_code": "package com.xlf.nrl;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.RadialGradient;\nimport android.graphics.Shader;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.ShapeDrawable;\nimport android.graphics.drawable.shapes.OvalShape;\nimport android.net.Uri;\nimport android.support.v4.view.ViewCompat;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.animation.Animation;\nimport android.widget.ImageView;\n\n/**\n * The author is lsjwzh(MaterialLoadingProgressBar) link{http://example.com},\n * I did some slight modifications\n */\npublic class CircleProgressBar extends ImageView {\n\n private static final int KEY_SHADOW_COLOR = 0x1E000000;\n\n private static final int FILL_SHADOW_COLOR = 0x3D000000;\n\n // PX\n private static final float X_OFFSET = 0f;\n\n private static final float Y_OFFSET = 1.75f;\n\n private static final float SHADOW_RADIUS = 3.5f;\n\n private static final int SHADOW_ELEVATION = 4;\n\n public static final int DEFAULT_CIRCLE_BG_LIGHT = 0xFFFAFAFA;\n\n public static final int DEFAULT_CIRCLE_COLOR = 0xFFF00000;\n\n private static final int DEFAULT_CIRCLE_DIAMETER = 40;\n\n private static final int STROKE_WIDTH_LARGE = 3;\n\n public static final int DEFAULT_TEXT_SIZE = 9;\n\n private Animation.AnimationListener mListener;\n\n private int mShadowRadius;\n\n private int mBackGroundColor;\n\n private int mProgressColor;\n\n private int mProgressStokeWidth;\n\n private int mArrowWidth;\n\n private int mArrowHeight;\n\n private int mProgress;\n\n private int mMax;\n\n private int mDiameter;\n\n private int mInnerRadius;\n\n private Paint mTextPaint;\n\n private int mTextColor;\n\n private int mTextSize;\n\n private boolean mIfDrawText;\n\n private boolean mShowArrow;\n\n public MaterialProgressDrawable mProgressDrawable;\n\n private ShapeDrawable mBgCircle;\n\n private boolean mCircleBackgroundEnabled;\n\n private int[] mColors = new int[] { Color.BLACK };\n\n public CircleProgressBar(Context context) {\n super(context);\n init(context, null, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context, attrs, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr) {\n final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar, defStyleAttr, 0);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mBackGroundColor = a.getColor(R.styleable.CircleProgressBar_background_color, DEFAULT_CIRCLE_BG_LIGHT);\n mProgressColor = a.getColor(R.styleable.CircleProgressBar_progress_color, DEFAULT_CIRCLE_COLOR);\n mColors = new int[] { mProgressColor };\n mInnerRadius = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_inner_radius, -1);\n mProgressStokeWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_stoke_width, (int) (STROKE_WIDTH_LARGE * density));\n mArrowWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_width, -1);\n mArrowHeight = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_height, -1);\n mTextSize = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_text_size, (int) (DEFAULT_TEXT_SIZE * density));\n mTextColor = a.getColor(R.styleable.CircleProgressBar_progress_text_color, Color.BLACK);\n mShowArrow = a.getBoolean(R.styleable.CircleProgressBar_show_arrow, true);\n mCircleBackgroundEnabled = a.getBoolean(R.styleable.CircleProgressBar_enable_circle_background, true);\n mProgress = a.getInt(R.styleable.CircleProgressBar_progress, 0);\n mMax = a.getInt(R.styleable.CircleProgressBar_max, 100);\n int textVisible = a.getInt(R.styleable.CircleProgressBar_progress_text_visibility, 1);\n if (textVisible != 1) {\n mIfDrawText = true;\n }\n mTextPaint = new Paint();\n mTextPaint.setStyle(Paint.Style.FILL);\n mTextPaint.setColor(mTextColor);\n mTextPaint.setTextSize(mTextSize);\n mTextPaint.setAntiAlias(true);\n a.recycle();\n mProgressDrawable = new MaterialProgressDrawable(getContext(), this);\n super.setImageDrawable(mProgressDrawable);\n }\n\n public void setProgressBackGroundColor(int color) {\n this.mBackGroundColor = color;\n }\n\n public void setTextColor(int color) {\n this.mTextColor = color;\n }\n\n private boolean elevationSupported() {\n return android.os.Build.VERSION.SDK_INT >= 21;\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n if (!elevationSupported()) {\n setMeasuredDimension(getMeasuredWidth() + mShadowRadius * 2, getMeasuredHeight() + mShadowRadius * 2);\n }\n }\n\n public int getProgressStokeWidth() {\n return mProgressStokeWidth;\n }\n\n public void setProgressStokeWidth(int mProgressStokeWidth) {\n final float density = getContext().getResources().getDisplayMetrics().density;\n this.mProgressStokeWidth = (int) (mProgressStokeWidth * density);\n }\n\n @Override\n protected void onLayout(boolean changed, int left, int top, int right, int bottom) {\n super.onLayout(changed, left, top, right, bottom);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mDiameter = Math.min(getMeasuredWidth(), getMeasuredHeight());\n if (mDiameter <= 0) {\n mDiameter = (int) density * DEFAULT_CIRCLE_DIAMETER;\n }\n if (getBackground() == null && mCircleBackgroundEnabled) {\n final int shadowYOffset = (int) (density * Y_OFFSET);\n final int shadowXOffset = (int) (density * X_OFFSET);\n mShadowRadius = (int) (density * SHADOW_RADIUS);\n if (elevationSupported()) {\n mBgCircle = new ShapeDrawable(new OvalShape());\n ViewCompat.setElevation(this, SHADOW_ELEVATION * density);\n } else {\n OvalShape oval = new OvalShadow(mShadowRadius, mDiameter - mShadowRadius * 2);\n mBgCircle = new ShapeDrawable(oval);\n ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, mBgCircle.getPaint());\n mBgCircle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset, KEY_SHADOW_COLOR);\n final int padding = (int) mShadowRadius;\n // set padding so the inner image sits correctly within the shadow.\n setPadding(padding, padding, padding, padding);\n }\n mBgCircle.getPaint().setColor(mBackGroundColor);\n setBackgroundDrawable(mBgCircle);\n }\n mProgressDrawable.setBackgroundColor(mBackGroundColor);\n mProgressDrawable.setColorSchemeColors(mColors);\n mProgressDrawable.setSizeParameters(mDiameter, mDiameter, mInnerRadius <= 0 ? (mDiameter - mProgressStokeWidth * 2) / 4 : mInnerRadius, mProgressStokeWidth, mArrowWidth < 0 ? mProgressStokeWidth * 4 : mArrowWidth, mArrowHeight < 0 ? mProgressStokeWidth * 2 : mArrowHeight);\n if (isShowArrow()) {\n mProgressDrawable.showArrowOnFirstStart(true);\n mProgressDrawable.setArrowScale(1f);\n mProgressDrawable.showArrow(true);\n }\n super.setImageDrawable(null);\n super.setImageDrawable(mProgressDrawable);\n mProgressDrawable.setAlpha(255);\n if (getVisibility() == VISIBLE) {\n mProgressDrawable.setStartEndTrim(0, (float) 0.8);\n }\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n if (mIfDrawText) {\n String text = String.format(\"%s%%\", mProgress);\n int x = getWidth() / 2 - text.length() * mTextSize / 4;\n int y = getHeight() / 2 + mTextSize / 4;\n canvas.drawText(text, x, y, mTextPaint);\n }\n }\n\n @Override\n final public void setImageResource(int resId) {\n }\n\n public boolean isShowArrow() {\n return mShowArrow;\n }\n\n public void setShowArrow(boolean showArrow) {\n this.mShowArrow = showArrow;\n }\n\n @Override\n final public void setImageURI(Uri uri) {\n super.setImageURI(uri);\n }\n\n @Override\n final public void setImageDrawable(Drawable drawable) {\n }\n\n public void setAnimationListener(Animation.AnimationListener listener) {\n mListener = listener;\n }\n\n @Override\n public void onAnimationStart() {\n super.onAnimationStart();\n if (mListener != null) {\n mListener.onAnimationStart(getAnimation());\n }\n }\n\n @Override\n public void onAnimationEnd() {\n super.onAnimationEnd();\n if (mListener != null) {\n mListener.onAnimationEnd(getAnimation());\n }\n }\n\n /**\n * Set the color resources used in the progress animation from color resources.\n * The first color will also be the color of the bar that grows in response\n * to a user swipe gesture.\n *\n * @param colorResIds\n */\n public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }\n\n /**\n * Set the colors used in the progress animation. The first\n * color will also be the color of the bar that grows in response to a user\n * swipe gesture.\n *\n * @param colors\n */\n public void setColorSchemeColors(int... colors) {\n mColors = colors;\n if (mProgressDrawable != null) {\n mProgressDrawable.setColorSchemeColors(colors);\n }\n }\n\n /**\n * Update the background color of the mBgCircle image view.\n */\n public void setBackgroundColorResource(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }\n\n public void setBackgroundColor(int color) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(color);\n }\n }\n\n public boolean isShowProgressText() {\n return mIfDrawText;\n }\n\n public void setShowProgressText(boolean mIfDrawText) {\n this.mIfDrawText = mIfDrawText;\n }\n\n public int getMax() {\n return mMax;\n }\n\n public void setMax(int max) {\n mMax = max;\n }\n\n public int getProgress() {\n return mProgress;\n }\n\n public void setProgress(int progress) {\n if (getMax() > 0) {\n mProgress = progress;\n }\n invalidate();\n Log.i(\"cjj_log\", \"progress------->>>>\" + progress);\n }\n\n public boolean circleBackgroundEnabled() {\n return mCircleBackgroundEnabled;\n }\n\n public void setCircleBackgroundEnabled(boolean enableCircleBackground) {\n this.mCircleBackgroundEnabled = enableCircleBackground;\n }\n\n @Override\n public int getVisibility() {\n return super.getVisibility();\n }\n\n @Override\n public void setVisibility(int visibility) {\n super.setVisibility(visibility);\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(getVisibility() == VISIBLE, false);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {", "post_mask_code": "\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(false, false);\n }\n }\n\n private class OvalShadow extends OvalShape {\n\n private RadialGradient mRadialGradient;\n\n private int mShadowRadius;\n\n private Paint mShadowPaint;\n\n private int mCircleDiameter;\n\n public OvalShadow(int shadowRadius, int circleDiameter) {\n super();\n mShadowPaint = new Paint();\n mShadowRadius = shadowRadius;\n mCircleDiameter = circleDiameter;\n mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2, mShadowRadius, new int[] { FILL_SHADOW_COLOR, Color.TRANSPARENT }, null, Shader.TileMode.CLAMP);\n mShadowPaint.setShader(mRadialGradient);\n }\n\n @Override\n public void draw(Canvas canvas, Paint paint) {\n final int viewWidth = CircleProgressBar.this.getWidth();\n final int viewHeight = CircleProgressBar.this.getHeight();\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius), mShadowPaint);\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);\n }\n }\n\n public void start() {\n mProgressDrawable.start();\n }\n\n public void setStartEndTrim(float startAngle, float endAngle) {\n mProgressDrawable.setStartEndTrim(startAngle, endAngle);\n }\n\n public void stop() {\n mProgressDrawable.stop();\n }\n\n public void setProgressRotation(float rotation) {\n mProgressDrawable.setProgressRotation(rotation);\n }\n}\n"} {"task_id": "Java_1871", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/laomengzhu/NsRefreshLayout/nrl/src/main/java/com/xlf/nrl/CircleProgressBar.java", "mask_start_position": 12264, "mask_end_position": 12400, "canonical_solution": "if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(false, false);\n }", "pre_mask_code": "package com.xlf.nrl;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.RadialGradient;\nimport android.graphics.Shader;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.ShapeDrawable;\nimport android.graphics.drawable.shapes.OvalShape;\nimport android.net.Uri;\nimport android.support.v4.view.ViewCompat;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.animation.Animation;\nimport android.widget.ImageView;\n\n/**\n * The author is lsjwzh(MaterialLoadingProgressBar) link{http://example.com},\n * I did some slight modifications\n */\npublic class CircleProgressBar extends ImageView {\n\n private static final int KEY_SHADOW_COLOR = 0x1E000000;\n\n private static final int FILL_SHADOW_COLOR = 0x3D000000;\n\n // PX\n private static final float X_OFFSET = 0f;\n\n private static final float Y_OFFSET = 1.75f;\n\n private static final float SHADOW_RADIUS = 3.5f;\n\n private static final int SHADOW_ELEVATION = 4;\n\n public static final int DEFAULT_CIRCLE_BG_LIGHT = 0xFFFAFAFA;\n\n public static final int DEFAULT_CIRCLE_COLOR = 0xFFF00000;\n\n private static final int DEFAULT_CIRCLE_DIAMETER = 40;\n\n private static final int STROKE_WIDTH_LARGE = 3;\n\n public static final int DEFAULT_TEXT_SIZE = 9;\n\n private Animation.AnimationListener mListener;\n\n private int mShadowRadius;\n\n private int mBackGroundColor;\n\n private int mProgressColor;\n\n private int mProgressStokeWidth;\n\n private int mArrowWidth;\n\n private int mArrowHeight;\n\n private int mProgress;\n\n private int mMax;\n\n private int mDiameter;\n\n private int mInnerRadius;\n\n private Paint mTextPaint;\n\n private int mTextColor;\n\n private int mTextSize;\n\n private boolean mIfDrawText;\n\n private boolean mShowArrow;\n\n public MaterialProgressDrawable mProgressDrawable;\n\n private ShapeDrawable mBgCircle;\n\n private boolean mCircleBackgroundEnabled;\n\n private int[] mColors = new int[] { Color.BLACK };\n\n public CircleProgressBar(Context context) {\n super(context);\n init(context, null, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context, attrs, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr) {\n final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar, defStyleAttr, 0);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mBackGroundColor = a.getColor(R.styleable.CircleProgressBar_background_color, DEFAULT_CIRCLE_BG_LIGHT);\n mProgressColor = a.getColor(R.styleable.CircleProgressBar_progress_color, DEFAULT_CIRCLE_COLOR);\n mColors = new int[] { mProgressColor };\n mInnerRadius = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_inner_radius, -1);\n mProgressStokeWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_stoke_width, (int) (STROKE_WIDTH_LARGE * density));\n mArrowWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_width, -1);\n mArrowHeight = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_height, -1);\n mTextSize = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_text_size, (int) (DEFAULT_TEXT_SIZE * density));\n mTextColor = a.getColor(R.styleable.CircleProgressBar_progress_text_color, Color.BLACK);\n mShowArrow = a.getBoolean(R.styleable.CircleProgressBar_show_arrow, true);\n mCircleBackgroundEnabled = a.getBoolean(R.styleable.CircleProgressBar_enable_circle_background, true);\n mProgress = a.getInt(R.styleable.CircleProgressBar_progress, 0);\n mMax = a.getInt(R.styleable.CircleProgressBar_max, 100);\n int textVisible = a.getInt(R.styleable.CircleProgressBar_progress_text_visibility, 1);\n if (textVisible != 1) {\n mIfDrawText = true;\n }\n mTextPaint = new Paint();\n mTextPaint.setStyle(Paint.Style.FILL);\n mTextPaint.setColor(mTextColor);\n mTextPaint.setTextSize(mTextSize);\n mTextPaint.setAntiAlias(true);\n a.recycle();\n mProgressDrawable = new MaterialProgressDrawable(getContext(), this);\n super.setImageDrawable(mProgressDrawable);\n }\n\n public void setProgressBackGroundColor(int color) {\n this.mBackGroundColor = color;\n }\n\n public void setTextColor(int color) {\n this.mTextColor = color;\n }\n\n private boolean elevationSupported() {\n return android.os.Build.VERSION.SDK_INT >= 21;\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n if (!elevationSupported()) {\n setMeasuredDimension(getMeasuredWidth() + mShadowRadius * 2, getMeasuredHeight() + mShadowRadius * 2);\n }\n }\n\n public int getProgressStokeWidth() {\n return mProgressStokeWidth;\n }\n\n public void setProgressStokeWidth(int mProgressStokeWidth) {\n final float density = getContext().getResources().getDisplayMetrics().density;\n this.mProgressStokeWidth = (int) (mProgressStokeWidth * density);\n }\n\n @Override\n protected void onLayout(boolean changed, int left, int top, int right, int bottom) {\n super.onLayout(changed, left, top, right, bottom);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mDiameter = Math.min(getMeasuredWidth(), getMeasuredHeight());\n if (mDiameter <= 0) {\n mDiameter = (int) density * DEFAULT_CIRCLE_DIAMETER;\n }\n if (getBackground() == null && mCircleBackgroundEnabled) {\n final int shadowYOffset = (int) (density * Y_OFFSET);\n final int shadowXOffset = (int) (density * X_OFFSET);\n mShadowRadius = (int) (density * SHADOW_RADIUS);\n if (elevationSupported()) {\n mBgCircle = new ShapeDrawable(new OvalShape());\n ViewCompat.setElevation(this, SHADOW_ELEVATION * density);\n } else {\n OvalShape oval = new OvalShadow(mShadowRadius, mDiameter - mShadowRadius * 2);\n mBgCircle = new ShapeDrawable(oval);\n ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, mBgCircle.getPaint());\n mBgCircle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset, KEY_SHADOW_COLOR);\n final int padding = (int) mShadowRadius;\n // set padding so the inner image sits correctly within the shadow.\n setPadding(padding, padding, padding, padding);\n }\n mBgCircle.getPaint().setColor(mBackGroundColor);\n setBackgroundDrawable(mBgCircle);\n }\n mProgressDrawable.setBackgroundColor(mBackGroundColor);\n mProgressDrawable.setColorSchemeColors(mColors);\n mProgressDrawable.setSizeParameters(mDiameter, mDiameter, mInnerRadius <= 0 ? (mDiameter - mProgressStokeWidth * 2) / 4 : mInnerRadius, mProgressStokeWidth, mArrowWidth < 0 ? mProgressStokeWidth * 4 : mArrowWidth, mArrowHeight < 0 ? mProgressStokeWidth * 2 : mArrowHeight);\n if (isShowArrow()) {\n mProgressDrawable.showArrowOnFirstStart(true);\n mProgressDrawable.setArrowScale(1f);\n mProgressDrawable.showArrow(true);\n }\n super.setImageDrawable(null);\n super.setImageDrawable(mProgressDrawable);\n mProgressDrawable.setAlpha(255);\n if (getVisibility() == VISIBLE) {\n mProgressDrawable.setStartEndTrim(0, (float) 0.8);\n }\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n if (mIfDrawText) {\n String text = String.format(\"%s%%\", mProgress);\n int x = getWidth() / 2 - text.length() * mTextSize / 4;\n int y = getHeight() / 2 + mTextSize / 4;\n canvas.drawText(text, x, y, mTextPaint);\n }\n }\n\n @Override\n final public void setImageResource(int resId) {\n }\n\n public boolean isShowArrow() {\n return mShowArrow;\n }\n\n public void setShowArrow(boolean showArrow) {\n this.mShowArrow = showArrow;\n }\n\n @Override\n final public void setImageURI(Uri uri) {\n super.setImageURI(uri);\n }\n\n @Override\n final public void setImageDrawable(Drawable drawable) {\n }\n\n public void setAnimationListener(Animation.AnimationListener listener) {\n mListener = listener;\n }\n\n @Override\n public void onAnimationStart() {\n super.onAnimationStart();\n if (mListener != null) {\n mListener.onAnimationStart(getAnimation());\n }\n }\n\n @Override\n public void onAnimationEnd() {\n super.onAnimationEnd();\n if (mListener != null) {\n mListener.onAnimationEnd(getAnimation());\n }\n }\n\n /**\n * Set the color resources used in the progress animation from color resources.\n * The first color will also be the color of the bar that grows in response\n * to a user swipe gesture.\n *\n * @param colorResIds\n */\n public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }\n\n /**\n * Set the colors used in the progress animation. The first\n * color will also be the color of the bar that grows in response to a user\n * swipe gesture.\n *\n * @param colors\n */\n public void setColorSchemeColors(int... colors) {\n mColors = colors;\n if (mProgressDrawable != null) {\n mProgressDrawable.setColorSchemeColors(colors);\n }\n }\n\n /**\n * Update the background color of the mBgCircle image view.\n */\n public void setBackgroundColorResource(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }\n\n public void setBackgroundColor(int color) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(color);\n }\n }\n\n public boolean isShowProgressText() {\n return mIfDrawText;\n }\n\n public void setShowProgressText(boolean mIfDrawText) {\n this.mIfDrawText = mIfDrawText;\n }\n\n public int getMax() {\n return mMax;\n }\n\n public void setMax(int max) {\n mMax = max;\n }\n\n public int getProgress() {\n return mProgress;\n }\n\n public void setProgress(int progress) {\n if (getMax() > 0) {\n mProgress = progress;\n }\n invalidate();\n Log.i(\"cjj_log\", \"progress------->>>>\" + progress);\n }\n\n public boolean circleBackgroundEnabled() {\n return mCircleBackgroundEnabled;\n }\n\n public void setCircleBackgroundEnabled(boolean enableCircleBackground) {\n this.mCircleBackgroundEnabled = enableCircleBackground;\n }\n\n @Override\n public int getVisibility() {\n return super.getVisibility();\n }\n\n @Override\n public void setVisibility(int visibility) {\n super.setVisibility(visibility);\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(getVisibility() == VISIBLE, false);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n ", "post_mask_code": "\n }\n\n private class OvalShadow extends OvalShape {\n\n private RadialGradient mRadialGradient;\n\n private int mShadowRadius;\n\n private Paint mShadowPaint;\n\n private int mCircleDiameter;\n\n public OvalShadow(int shadowRadius, int circleDiameter) {\n super();\n mShadowPaint = new Paint();\n mShadowRadius = shadowRadius;\n mCircleDiameter = circleDiameter;\n mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2, mShadowRadius, new int[] { FILL_SHADOW_COLOR, Color.TRANSPARENT }, null, Shader.TileMode.CLAMP);\n mShadowPaint.setShader(mRadialGradient);\n }\n\n @Override\n public void draw(Canvas canvas, Paint paint) {\n final int viewWidth = CircleProgressBar.this.getWidth();\n final int viewHeight = CircleProgressBar.this.getHeight();\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius), mShadowPaint);\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);\n }\n }\n\n public void start() {\n mProgressDrawable.start();\n }\n\n public void setStartEndTrim(float startAngle, float endAngle) {\n mProgressDrawable.setStartEndTrim(startAngle, endAngle);\n }\n\n public void stop() {\n mProgressDrawable.stop();\n }\n\n public void setProgressRotation(float rotation) {\n mProgressDrawable.setProgressRotation(rotation);\n }\n}\n"} {"task_id": "Java_1872", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/laomengzhu/NsRefreshLayout/nrl/src/main/java/com/xlf/nrl/CircleProgressBar.java", "mask_start_position": 12405, "mask_end_position": 12406, "canonical_solution": "}", "pre_mask_code": "package com.xlf.nrl;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.RadialGradient;\nimport android.graphics.Shader;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.ShapeDrawable;\nimport android.graphics.drawable.shapes.OvalShape;\nimport android.net.Uri;\nimport android.support.v4.view.ViewCompat;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.animation.Animation;\nimport android.widget.ImageView;\n\n/**\n * The author is lsjwzh(MaterialLoadingProgressBar) link{http://example.com},\n * I did some slight modifications\n */\npublic class CircleProgressBar extends ImageView {\n\n private static final int KEY_SHADOW_COLOR = 0x1E000000;\n\n private static final int FILL_SHADOW_COLOR = 0x3D000000;\n\n // PX\n private static final float X_OFFSET = 0f;\n\n private static final float Y_OFFSET = 1.75f;\n\n private static final float SHADOW_RADIUS = 3.5f;\n\n private static final int SHADOW_ELEVATION = 4;\n\n public static final int DEFAULT_CIRCLE_BG_LIGHT = 0xFFFAFAFA;\n\n public static final int DEFAULT_CIRCLE_COLOR = 0xFFF00000;\n\n private static final int DEFAULT_CIRCLE_DIAMETER = 40;\n\n private static final int STROKE_WIDTH_LARGE = 3;\n\n public static final int DEFAULT_TEXT_SIZE = 9;\n\n private Animation.AnimationListener mListener;\n\n private int mShadowRadius;\n\n private int mBackGroundColor;\n\n private int mProgressColor;\n\n private int mProgressStokeWidth;\n\n private int mArrowWidth;\n\n private int mArrowHeight;\n\n private int mProgress;\n\n private int mMax;\n\n private int mDiameter;\n\n private int mInnerRadius;\n\n private Paint mTextPaint;\n\n private int mTextColor;\n\n private int mTextSize;\n\n private boolean mIfDrawText;\n\n private boolean mShowArrow;\n\n public MaterialProgressDrawable mProgressDrawable;\n\n private ShapeDrawable mBgCircle;\n\n private boolean mCircleBackgroundEnabled;\n\n private int[] mColors = new int[] { Color.BLACK };\n\n public CircleProgressBar(Context context) {\n super(context);\n init(context, null, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context, attrs, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr) {\n final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar, defStyleAttr, 0);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mBackGroundColor = a.getColor(R.styleable.CircleProgressBar_background_color, DEFAULT_CIRCLE_BG_LIGHT);\n mProgressColor = a.getColor(R.styleable.CircleProgressBar_progress_color, DEFAULT_CIRCLE_COLOR);\n mColors = new int[] { mProgressColor };\n mInnerRadius = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_inner_radius, -1);\n mProgressStokeWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_stoke_width, (int) (STROKE_WIDTH_LARGE * density));\n mArrowWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_width, -1);\n mArrowHeight = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_height, -1);\n mTextSize = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_text_size, (int) (DEFAULT_TEXT_SIZE * density));\n mTextColor = a.getColor(R.styleable.CircleProgressBar_progress_text_color, Color.BLACK);\n mShowArrow = a.getBoolean(R.styleable.CircleProgressBar_show_arrow, true);\n mCircleBackgroundEnabled = a.getBoolean(R.styleable.CircleProgressBar_enable_circle_background, true);\n mProgress = a.getInt(R.styleable.CircleProgressBar_progress, 0);\n mMax = a.getInt(R.styleable.CircleProgressBar_max, 100);\n int textVisible = a.getInt(R.styleable.CircleProgressBar_progress_text_visibility, 1);\n if (textVisible != 1) {\n mIfDrawText = true;\n }\n mTextPaint = new Paint();\n mTextPaint.setStyle(Paint.Style.FILL);\n mTextPaint.setColor(mTextColor);\n mTextPaint.setTextSize(mTextSize);\n mTextPaint.setAntiAlias(true);\n a.recycle();\n mProgressDrawable = new MaterialProgressDrawable(getContext(), this);\n super.setImageDrawable(mProgressDrawable);\n }\n\n public void setProgressBackGroundColor(int color) {\n this.mBackGroundColor = color;\n }\n\n public void setTextColor(int color) {\n this.mTextColor = color;\n }\n\n private boolean elevationSupported() {\n return android.os.Build.VERSION.SDK_INT >= 21;\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n if (!elevationSupported()) {\n setMeasuredDimension(getMeasuredWidth() + mShadowRadius * 2, getMeasuredHeight() + mShadowRadius * 2);\n }\n }\n\n public int getProgressStokeWidth() {\n return mProgressStokeWidth;\n }\n\n public void setProgressStokeWidth(int mProgressStokeWidth) {\n final float density = getContext().getResources().getDisplayMetrics().density;\n this.mProgressStokeWidth = (int) (mProgressStokeWidth * density);\n }\n\n @Override\n protected void onLayout(boolean changed, int left, int top, int right, int bottom) {\n super.onLayout(changed, left, top, right, bottom);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mDiameter = Math.min(getMeasuredWidth(), getMeasuredHeight());\n if (mDiameter <= 0) {\n mDiameter = (int) density * DEFAULT_CIRCLE_DIAMETER;\n }\n if (getBackground() == null && mCircleBackgroundEnabled) {\n final int shadowYOffset = (int) (density * Y_OFFSET);\n final int shadowXOffset = (int) (density * X_OFFSET);\n mShadowRadius = (int) (density * SHADOW_RADIUS);\n if (elevationSupported()) {\n mBgCircle = new ShapeDrawable(new OvalShape());\n ViewCompat.setElevation(this, SHADOW_ELEVATION * density);\n } else {\n OvalShape oval = new OvalShadow(mShadowRadius, mDiameter - mShadowRadius * 2);\n mBgCircle = new ShapeDrawable(oval);\n ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, mBgCircle.getPaint());\n mBgCircle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset, KEY_SHADOW_COLOR);\n final int padding = (int) mShadowRadius;\n // set padding so the inner image sits correctly within the shadow.\n setPadding(padding, padding, padding, padding);\n }\n mBgCircle.getPaint().setColor(mBackGroundColor);\n setBackgroundDrawable(mBgCircle);\n }\n mProgressDrawable.setBackgroundColor(mBackGroundColor);\n mProgressDrawable.setColorSchemeColors(mColors);\n mProgressDrawable.setSizeParameters(mDiameter, mDiameter, mInnerRadius <= 0 ? (mDiameter - mProgressStokeWidth * 2) / 4 : mInnerRadius, mProgressStokeWidth, mArrowWidth < 0 ? mProgressStokeWidth * 4 : mArrowWidth, mArrowHeight < 0 ? mProgressStokeWidth * 2 : mArrowHeight);\n if (isShowArrow()) {\n mProgressDrawable.showArrowOnFirstStart(true);\n mProgressDrawable.setArrowScale(1f);\n mProgressDrawable.showArrow(true);\n }\n super.setImageDrawable(null);\n super.setImageDrawable(mProgressDrawable);\n mProgressDrawable.setAlpha(255);\n if (getVisibility() == VISIBLE) {\n mProgressDrawable.setStartEndTrim(0, (float) 0.8);\n }\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n if (mIfDrawText) {\n String text = String.format(\"%s%%\", mProgress);\n int x = getWidth() / 2 - text.length() * mTextSize / 4;\n int y = getHeight() / 2 + mTextSize / 4;\n canvas.drawText(text, x, y, mTextPaint);\n }\n }\n\n @Override\n final public void setImageResource(int resId) {\n }\n\n public boolean isShowArrow() {\n return mShowArrow;\n }\n\n public void setShowArrow(boolean showArrow) {\n this.mShowArrow = showArrow;\n }\n\n @Override\n final public void setImageURI(Uri uri) {\n super.setImageURI(uri);\n }\n\n @Override\n final public void setImageDrawable(Drawable drawable) {\n }\n\n public void setAnimationListener(Animation.AnimationListener listener) {\n mListener = listener;\n }\n\n @Override\n public void onAnimationStart() {\n super.onAnimationStart();\n if (mListener != null) {\n mListener.onAnimationStart(getAnimation());\n }\n }\n\n @Override\n public void onAnimationEnd() {\n super.onAnimationEnd();\n if (mListener != null) {\n mListener.onAnimationEnd(getAnimation());\n }\n }\n\n /**\n * Set the color resources used in the progress animation from color resources.\n * The first color will also be the color of the bar that grows in response\n * to a user swipe gesture.\n *\n * @param colorResIds\n */\n public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }\n\n /**\n * Set the colors used in the progress animation. The first\n * color will also be the color of the bar that grows in response to a user\n * swipe gesture.\n *\n * @param colors\n */\n public void setColorSchemeColors(int... colors) {\n mColors = colors;\n if (mProgressDrawable != null) {\n mProgressDrawable.setColorSchemeColors(colors);\n }\n }\n\n /**\n * Update the background color of the mBgCircle image view.\n */\n public void setBackgroundColorResource(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }\n\n public void setBackgroundColor(int color) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(color);\n }\n }\n\n public boolean isShowProgressText() {\n return mIfDrawText;\n }\n\n public void setShowProgressText(boolean mIfDrawText) {\n this.mIfDrawText = mIfDrawText;\n }\n\n public int getMax() {\n return mMax;\n }\n\n public void setMax(int max) {\n mMax = max;\n }\n\n public int getProgress() {\n return mProgress;\n }\n\n public void setProgress(int progress) {\n if (getMax() > 0) {\n mProgress = progress;\n }\n invalidate();\n Log.i(\"cjj_log\", \"progress------->>>>\" + progress);\n }\n\n public boolean circleBackgroundEnabled() {\n return mCircleBackgroundEnabled;\n }\n\n public void setCircleBackgroundEnabled(boolean enableCircleBackground) {\n this.mCircleBackgroundEnabled = enableCircleBackground;\n }\n\n @Override\n public int getVisibility() {\n return super.getVisibility();\n }\n\n @Override\n public void setVisibility(int visibility) {\n super.setVisibility(visibility);\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(getVisibility() == VISIBLE, false);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(false, false);\n }\n ", "post_mask_code": "\n\n private class OvalShadow extends OvalShape {\n\n private RadialGradient mRadialGradient;\n\n private int mShadowRadius;\n\n private Paint mShadowPaint;\n\n private int mCircleDiameter;\n\n public OvalShadow(int shadowRadius, int circleDiameter) {\n super();\n mShadowPaint = new Paint();\n mShadowRadius = shadowRadius;\n mCircleDiameter = circleDiameter;\n mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2, mShadowRadius, new int[] { FILL_SHADOW_COLOR, Color.TRANSPARENT }, null, Shader.TileMode.CLAMP);\n mShadowPaint.setShader(mRadialGradient);\n }\n\n @Override\n public void draw(Canvas canvas, Paint paint) {\n final int viewWidth = CircleProgressBar.this.getWidth();\n final int viewHeight = CircleProgressBar.this.getHeight();\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius), mShadowPaint);\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);\n }\n }\n\n public void start() {\n mProgressDrawable.start();\n }\n\n public void setStartEndTrim(float startAngle, float endAngle) {\n mProgressDrawable.setStartEndTrim(startAngle, endAngle);\n }\n\n public void stop() {\n mProgressDrawable.stop();\n }\n\n public void setProgressRotation(float rotation) {\n mProgressDrawable.setProgressRotation(rotation);\n }\n}\n"} {"task_id": "Java_1873", "language": "Java", "task_type": "single_line", "source_file": "java/github/laomengzhu/NsRefreshLayout/nrl/src/main/java/com/xlf/nrl/CircleProgressBar.java", "mask_start_position": 5724, "mask_end_position": 5758, "canonical_solution": "hanged, left, top, right, bottom);", "pre_mask_code": "package com.xlf.nrl;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.RadialGradient;\nimport android.graphics.Shader;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.ShapeDrawable;\nimport android.graphics.drawable.shapes.OvalShape;\nimport android.net.Uri;\nimport android.support.v4.view.ViewCompat;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.animation.Animation;\nimport android.widget.ImageView;\n\n/**\n * The author is lsjwzh(MaterialLoadingProgressBar) link{http://example.com},\n * I did some slight modifications\n */\npublic class CircleProgressBar extends ImageView {\n\n private static final int KEY_SHADOW_COLOR = 0x1E000000;\n\n private static final int FILL_SHADOW_COLOR = 0x3D000000;\n\n // PX\n private static final float X_OFFSET = 0f;\n\n private static final float Y_OFFSET = 1.75f;\n\n private static final float SHADOW_RADIUS = 3.5f;\n\n private static final int SHADOW_ELEVATION = 4;\n\n public static final int DEFAULT_CIRCLE_BG_LIGHT = 0xFFFAFAFA;\n\n public static final int DEFAULT_CIRCLE_COLOR = 0xFFF00000;\n\n private static final int DEFAULT_CIRCLE_DIAMETER = 40;\n\n private static final int STROKE_WIDTH_LARGE = 3;\n\n public static final int DEFAULT_TEXT_SIZE = 9;\n\n private Animation.AnimationListener mListener;\n\n private int mShadowRadius;\n\n private int mBackGroundColor;\n\n private int mProgressColor;\n\n private int mProgressStokeWidth;\n\n private int mArrowWidth;\n\n private int mArrowHeight;\n\n private int mProgress;\n\n private int mMax;\n\n private int mDiameter;\n\n private int mInnerRadius;\n\n private Paint mTextPaint;\n\n private int mTextColor;\n\n private int mTextSize;\n\n private boolean mIfDrawText;\n\n private boolean mShowArrow;\n\n public MaterialProgressDrawable mProgressDrawable;\n\n private ShapeDrawable mBgCircle;\n\n private boolean mCircleBackgroundEnabled;\n\n private int[] mColors = new int[] { Color.BLACK };\n\n public CircleProgressBar(Context context) {\n super(context);\n init(context, null, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context, attrs, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr) {\n final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar, defStyleAttr, 0);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mBackGroundColor = a.getColor(R.styleable.CircleProgressBar_background_color, DEFAULT_CIRCLE_BG_LIGHT);\n mProgressColor = a.getColor(R.styleable.CircleProgressBar_progress_color, DEFAULT_CIRCLE_COLOR);\n mColors = new int[] { mProgressColor };\n mInnerRadius = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_inner_radius, -1);\n mProgressStokeWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_stoke_width, (int) (STROKE_WIDTH_LARGE * density));\n mArrowWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_width, -1);\n mArrowHeight = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_height, -1);\n mTextSize = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_text_size, (int) (DEFAULT_TEXT_SIZE * density));\n mTextColor = a.getColor(R.styleable.CircleProgressBar_progress_text_color, Color.BLACK);\n mShowArrow = a.getBoolean(R.styleable.CircleProgressBar_show_arrow, true);\n mCircleBackgroundEnabled = a.getBoolean(R.styleable.CircleProgressBar_enable_circle_background, true);\n mProgress = a.getInt(R.styleable.CircleProgressBar_progress, 0);\n mMax = a.getInt(R.styleable.CircleProgressBar_max, 100);\n int textVisible = a.getInt(R.styleable.CircleProgressBar_progress_text_visibility, 1);\n if (textVisible != 1) {\n mIfDrawText = true;\n }\n mTextPaint = new Paint();\n mTextPaint.setStyle(Paint.Style.FILL);\n mTextPaint.setColor(mTextColor);\n mTextPaint.setTextSize(mTextSize);\n mTextPaint.setAntiAlias(true);\n a.recycle();\n mProgressDrawable = new MaterialProgressDrawable(getContext(), this);\n super.setImageDrawable(mProgressDrawable);\n }\n\n public void setProgressBackGroundColor(int color) {\n this.mBackGroundColor = color;\n }\n\n public void setTextColor(int color) {\n this.mTextColor = color;\n }\n\n private boolean elevationSupported() {\n return android.os.Build.VERSION.SDK_INT >= 21;\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n if (!elevationSupported()) {\n setMeasuredDimension(getMeasuredWidth() + mShadowRadius * 2, getMeasuredHeight() + mShadowRadius * 2);\n }\n }\n\n public int getProgressStokeWidth() {\n return mProgressStokeWidth;\n }\n\n public void setProgressStokeWidth(int mProgressStokeWidth) {\n final float density = getContext().getResources().getDisplayMetrics().density;\n this.mProgressStokeWidth = (int) (mProgressStokeWidth * density);\n }\n\n @Override\n protected void onLayout(boolean changed, int left, int top, int right, int bottom) {\n super.onLayout(c", "post_mask_code": "\n final float density = getContext().getResources().getDisplayMetrics().density;\n mDiameter = Math.min(getMeasuredWidth(), getMeasuredHeight());\n if (mDiameter <= 0) {\n mDiameter = (int) density * DEFAULT_CIRCLE_DIAMETER;\n }\n if (getBackground() == null && mCircleBackgroundEnabled) {\n final int shadowYOffset = (int) (density * Y_OFFSET);\n final int shadowXOffset = (int) (density * X_OFFSET);\n mShadowRadius = (int) (density * SHADOW_RADIUS);\n if (elevationSupported()) {\n mBgCircle = new ShapeDrawable(new OvalShape());\n ViewCompat.setElevation(this, SHADOW_ELEVATION * density);\n } else {\n OvalShape oval = new OvalShadow(mShadowRadius, mDiameter - mShadowRadius * 2);\n mBgCircle = new ShapeDrawable(oval);\n ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, mBgCircle.getPaint());\n mBgCircle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset, KEY_SHADOW_COLOR);\n final int padding = (int) mShadowRadius;\n // set padding so the inner image sits correctly within the shadow.\n setPadding(padding, padding, padding, padding);\n }\n mBgCircle.getPaint().setColor(mBackGroundColor);\n setBackgroundDrawable(mBgCircle);\n }\n mProgressDrawable.setBackgroundColor(mBackGroundColor);\n mProgressDrawable.setColorSchemeColors(mColors);\n mProgressDrawable.setSizeParameters(mDiameter, mDiameter, mInnerRadius <= 0 ? (mDiameter - mProgressStokeWidth * 2) / 4 : mInnerRadius, mProgressStokeWidth, mArrowWidth < 0 ? mProgressStokeWidth * 4 : mArrowWidth, mArrowHeight < 0 ? mProgressStokeWidth * 2 : mArrowHeight);\n if (isShowArrow()) {\n mProgressDrawable.showArrowOnFirstStart(true);\n mProgressDrawable.setArrowScale(1f);\n mProgressDrawable.showArrow(true);\n }\n super.setImageDrawable(null);\n super.setImageDrawable(mProgressDrawable);\n mProgressDrawable.setAlpha(255);\n if (getVisibility() == VISIBLE) {\n mProgressDrawable.setStartEndTrim(0, (float) 0.8);\n }\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n if (mIfDrawText) {\n String text = String.format(\"%s%%\", mProgress);\n int x = getWidth() / 2 - text.length() * mTextSize / 4;\n int y = getHeight() / 2 + mTextSize / 4;\n canvas.drawText(text, x, y, mTextPaint);\n }\n }\n\n @Override\n final public void setImageResource(int resId) {\n }\n\n public boolean isShowArrow() {\n return mShowArrow;\n }\n\n public void setShowArrow(boolean showArrow) {\n this.mShowArrow = showArrow;\n }\n\n @Override\n final public void setImageURI(Uri uri) {\n super.setImageURI(uri);\n }\n\n @Override\n final public void setImageDrawable(Drawable drawable) {\n }\n\n public void setAnimationListener(Animation.AnimationListener listener) {\n mListener = listener;\n }\n\n @Override\n public void onAnimationStart() {\n super.onAnimationStart();\n if (mListener != null) {\n mListener.onAnimationStart(getAnimation());\n }\n }\n\n @Override\n public void onAnimationEnd() {\n super.onAnimationEnd();\n if (mListener != null) {\n mListener.onAnimationEnd(getAnimation());\n }\n }\n\n /**\n * Set the color resources used in the progress animation from color resources.\n * The first color will also be the color of the bar that grows in response\n * to a user swipe gesture.\n *\n * @param colorResIds\n */\n public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }\n\n /**\n * Set the colors used in the progress animation. The first\n * color will also be the color of the bar that grows in response to a user\n * swipe gesture.\n *\n * @param colors\n */\n public void setColorSchemeColors(int... colors) {\n mColors = colors;\n if (mProgressDrawable != null) {\n mProgressDrawable.setColorSchemeColors(colors);\n }\n }\n\n /**\n * Update the background color of the mBgCircle image view.\n */\n public void setBackgroundColorResource(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }\n\n public void setBackgroundColor(int color) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(color);\n }\n }\n\n public boolean isShowProgressText() {\n return mIfDrawText;\n }\n\n public void setShowProgressText(boolean mIfDrawText) {\n this.mIfDrawText = mIfDrawText;\n }\n\n public int getMax() {\n return mMax;\n }\n\n public void setMax(int max) {\n mMax = max;\n }\n\n public int getProgress() {\n return mProgress;\n }\n\n public void setProgress(int progress) {\n if (getMax() > 0) {\n mProgress = progress;\n }\n invalidate();\n Log.i(\"cjj_log\", \"progress------->>>>\" + progress);\n }\n\n public boolean circleBackgroundEnabled() {\n return mCircleBackgroundEnabled;\n }\n\n public void setCircleBackgroundEnabled(boolean enableCircleBackground) {\n this.mCircleBackgroundEnabled = enableCircleBackground;\n }\n\n @Override\n public int getVisibility() {\n return super.getVisibility();\n }\n\n @Override\n public void setVisibility(int visibility) {\n super.setVisibility(visibility);\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(getVisibility() == VISIBLE, false);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(false, false);\n }\n }\n\n private class OvalShadow extends OvalShape {\n\n private RadialGradient mRadialGradient;\n\n private int mShadowRadius;\n\n private Paint mShadowPaint;\n\n private int mCircleDiameter;\n\n public OvalShadow(int shadowRadius, int circleDiameter) {\n super();\n mShadowPaint = new Paint();\n mShadowRadius = shadowRadius;\n mCircleDiameter = circleDiameter;\n mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2, mShadowRadius, new int[] { FILL_SHADOW_COLOR, Color.TRANSPARENT }, null, Shader.TileMode.CLAMP);\n mShadowPaint.setShader(mRadialGradient);\n }\n\n @Override\n public void draw(Canvas canvas, Paint paint) {\n final int viewWidth = CircleProgressBar.this.getWidth();\n final int viewHeight = CircleProgressBar.this.getHeight();\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius), mShadowPaint);\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);\n }\n }\n\n public void start() {\n mProgressDrawable.start();\n }\n\n public void setStartEndTrim(float startAngle, float endAngle) {\n mProgressDrawable.setStartEndTrim(startAngle, endAngle);\n }\n\n public void stop() {\n mProgressDrawable.stop();\n }\n\n public void setProgressRotation(float rotation) {\n mProgressDrawable.setProgressRotation(rotation);\n }\n}\n"} {"task_id": "Java_1874", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/laomengzhu/NsRefreshLayout/nrl/src/main/java/com/xlf/nrl/CircleProgressBar.java", "mask_start_position": 9551, "mask_end_position": 9875, "canonical_solution": "public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }", "pre_mask_code": "package com.xlf.nrl;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.RadialGradient;\nimport android.graphics.Shader;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.ShapeDrawable;\nimport android.graphics.drawable.shapes.OvalShape;\nimport android.net.Uri;\nimport android.support.v4.view.ViewCompat;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.animation.Animation;\nimport android.widget.ImageView;\n\n/**\n * The author is lsjwzh(MaterialLoadingProgressBar) link{http://example.com},\n * I did some slight modifications\n */\npublic class CircleProgressBar extends ImageView {\n\n private static final int KEY_SHADOW_COLOR = 0x1E000000;\n\n private static final int FILL_SHADOW_COLOR = 0x3D000000;\n\n // PX\n private static final float X_OFFSET = 0f;\n\n private static final float Y_OFFSET = 1.75f;\n\n private static final float SHADOW_RADIUS = 3.5f;\n\n private static final int SHADOW_ELEVATION = 4;\n\n public static final int DEFAULT_CIRCLE_BG_LIGHT = 0xFFFAFAFA;\n\n public static final int DEFAULT_CIRCLE_COLOR = 0xFFF00000;\n\n private static final int DEFAULT_CIRCLE_DIAMETER = 40;\n\n private static final int STROKE_WIDTH_LARGE = 3;\n\n public static final int DEFAULT_TEXT_SIZE = 9;\n\n private Animation.AnimationListener mListener;\n\n private int mShadowRadius;\n\n private int mBackGroundColor;\n\n private int mProgressColor;\n\n private int mProgressStokeWidth;\n\n private int mArrowWidth;\n\n private int mArrowHeight;\n\n private int mProgress;\n\n private int mMax;\n\n private int mDiameter;\n\n private int mInnerRadius;\n\n private Paint mTextPaint;\n\n private int mTextColor;\n\n private int mTextSize;\n\n private boolean mIfDrawText;\n\n private boolean mShowArrow;\n\n public MaterialProgressDrawable mProgressDrawable;\n\n private ShapeDrawable mBgCircle;\n\n private boolean mCircleBackgroundEnabled;\n\n private int[] mColors = new int[] { Color.BLACK };\n\n public CircleProgressBar(Context context) {\n super(context);\n init(context, null, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context, attrs, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr) {\n final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar, defStyleAttr, 0);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mBackGroundColor = a.getColor(R.styleable.CircleProgressBar_background_color, DEFAULT_CIRCLE_BG_LIGHT);\n mProgressColor = a.getColor(R.styleable.CircleProgressBar_progress_color, DEFAULT_CIRCLE_COLOR);\n mColors = new int[] { mProgressColor };\n mInnerRadius = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_inner_radius, -1);\n mProgressStokeWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_stoke_width, (int) (STROKE_WIDTH_LARGE * density));\n mArrowWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_width, -1);\n mArrowHeight = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_height, -1);\n mTextSize = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_text_size, (int) (DEFAULT_TEXT_SIZE * density));\n mTextColor = a.getColor(R.styleable.CircleProgressBar_progress_text_color, Color.BLACK);\n mShowArrow = a.getBoolean(R.styleable.CircleProgressBar_show_arrow, true);\n mCircleBackgroundEnabled = a.getBoolean(R.styleable.CircleProgressBar_enable_circle_background, true);\n mProgress = a.getInt(R.styleable.CircleProgressBar_progress, 0);\n mMax = a.getInt(R.styleable.CircleProgressBar_max, 100);\n int textVisible = a.getInt(R.styleable.CircleProgressBar_progress_text_visibility, 1);\n if (textVisible != 1) {\n mIfDrawText = true;\n }\n mTextPaint = new Paint();\n mTextPaint.setStyle(Paint.Style.FILL);\n mTextPaint.setColor(mTextColor);\n mTextPaint.setTextSize(mTextSize);\n mTextPaint.setAntiAlias(true);\n a.recycle();\n mProgressDrawable = new MaterialProgressDrawable(getContext(), this);\n super.setImageDrawable(mProgressDrawable);\n }\n\n public void setProgressBackGroundColor(int color) {\n this.mBackGroundColor = color;\n }\n\n public void setTextColor(int color) {\n this.mTextColor = color;\n }\n\n private boolean elevationSupported() {\n return android.os.Build.VERSION.SDK_INT >= 21;\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n if (!elevationSupported()) {\n setMeasuredDimension(getMeasuredWidth() + mShadowRadius * 2, getMeasuredHeight() + mShadowRadius * 2);\n }\n }\n\n public int getProgressStokeWidth() {\n return mProgressStokeWidth;\n }\n\n public void setProgressStokeWidth(int mProgressStokeWidth) {\n final float density = getContext().getResources().getDisplayMetrics().density;\n this.mProgressStokeWidth = (int) (mProgressStokeWidth * density);\n }\n\n @Override\n protected void onLayout(boolean changed, int left, int top, int right, int bottom) {\n super.onLayout(changed, left, top, right, bottom);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mDiameter = Math.min(getMeasuredWidth(), getMeasuredHeight());\n if (mDiameter <= 0) {\n mDiameter = (int) density * DEFAULT_CIRCLE_DIAMETER;\n }\n if (getBackground() == null && mCircleBackgroundEnabled) {\n final int shadowYOffset = (int) (density * Y_OFFSET);\n final int shadowXOffset = (int) (density * X_OFFSET);\n mShadowRadius = (int) (density * SHADOW_RADIUS);\n if (elevationSupported()) {\n mBgCircle = new ShapeDrawable(new OvalShape());\n ViewCompat.setElevation(this, SHADOW_ELEVATION * density);\n } else {\n OvalShape oval = new OvalShadow(mShadowRadius, mDiameter - mShadowRadius * 2);\n mBgCircle = new ShapeDrawable(oval);\n ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, mBgCircle.getPaint());\n mBgCircle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset, KEY_SHADOW_COLOR);\n final int padding = (int) mShadowRadius;\n // set padding so the inner image sits correctly within the shadow.\n setPadding(padding, padding, padding, padding);\n }\n mBgCircle.getPaint().setColor(mBackGroundColor);\n setBackgroundDrawable(mBgCircle);\n }\n mProgressDrawable.setBackgroundColor(mBackGroundColor);\n mProgressDrawable.setColorSchemeColors(mColors);\n mProgressDrawable.setSizeParameters(mDiameter, mDiameter, mInnerRadius <= 0 ? (mDiameter - mProgressStokeWidth * 2) / 4 : mInnerRadius, mProgressStokeWidth, mArrowWidth < 0 ? mProgressStokeWidth * 4 : mArrowWidth, mArrowHeight < 0 ? mProgressStokeWidth * 2 : mArrowHeight);\n if (isShowArrow()) {\n mProgressDrawable.showArrowOnFirstStart(true);\n mProgressDrawable.setArrowScale(1f);\n mProgressDrawable.showArrow(true);\n }\n super.setImageDrawable(null);\n super.setImageDrawable(mProgressDrawable);\n mProgressDrawable.setAlpha(255);\n if (getVisibility() == VISIBLE) {\n mProgressDrawable.setStartEndTrim(0, (float) 0.8);\n }\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n if (mIfDrawText) {\n String text = String.format(\"%s%%\", mProgress);\n int x = getWidth() / 2 - text.length() * mTextSize / 4;\n int y = getHeight() / 2 + mTextSize / 4;\n canvas.drawText(text, x, y, mTextPaint);\n }\n }\n\n @Override\n final public void setImageResource(int resId) {\n }\n\n public boolean isShowArrow() {\n return mShowArrow;\n }\n\n public void setShowArrow(boolean showArrow) {\n this.mShowArrow = showArrow;\n }\n\n @Override\n final public void setImageURI(Uri uri) {\n super.setImageURI(uri);\n }\n\n @Override\n final public void setImageDrawable(Drawable drawable) {\n }\n\n public void setAnimationListener(Animation.AnimationListener listener) {\n mListener = listener;\n }\n\n @Override\n public void onAnimationStart() {\n super.onAnimationStart();\n if (mListener != null) {\n mListener.onAnimationStart(getAnimation());\n }\n }\n\n @Override\n public void onAnimationEnd() {\n super.onAnimationEnd();\n if (mListener != null) {\n mListener.onAnimationEnd(getAnimation());\n }\n }\n\n /**\n * Set the color resources used in the progress animation from color resources.\n * The first color will also be the color of the bar that grows in response\n * to a user swipe gesture.\n *\n * @param colorResIds\n */\n ", "post_mask_code": "\n\n /**\n * Set the colors used in the progress animation. The first\n * color will also be the color of the bar that grows in response to a user\n * swipe gesture.\n *\n * @param colors\n */\n public void setColorSchemeColors(int... colors) {\n mColors = colors;\n if (mProgressDrawable != null) {\n mProgressDrawable.setColorSchemeColors(colors);\n }\n }\n\n /**\n * Update the background color of the mBgCircle image view.\n */\n public void setBackgroundColorResource(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }\n\n public void setBackgroundColor(int color) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(color);\n }\n }\n\n public boolean isShowProgressText() {\n return mIfDrawText;\n }\n\n public void setShowProgressText(boolean mIfDrawText) {\n this.mIfDrawText = mIfDrawText;\n }\n\n public int getMax() {\n return mMax;\n }\n\n public void setMax(int max) {\n mMax = max;\n }\n\n public int getProgress() {\n return mProgress;\n }\n\n public void setProgress(int progress) {\n if (getMax() > 0) {\n mProgress = progress;\n }\n invalidate();\n Log.i(\"cjj_log\", \"progress------->>>>\" + progress);\n }\n\n public boolean circleBackgroundEnabled() {\n return mCircleBackgroundEnabled;\n }\n\n public void setCircleBackgroundEnabled(boolean enableCircleBackground) {\n this.mCircleBackgroundEnabled = enableCircleBackground;\n }\n\n @Override\n public int getVisibility() {\n return super.getVisibility();\n }\n\n @Override\n public void setVisibility(int visibility) {\n super.setVisibility(visibility);\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(getVisibility() == VISIBLE, false);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(false, false);\n }\n }\n\n private class OvalShadow extends OvalShape {\n\n private RadialGradient mRadialGradient;\n\n private int mShadowRadius;\n\n private Paint mShadowPaint;\n\n private int mCircleDiameter;\n\n public OvalShadow(int shadowRadius, int circleDiameter) {\n super();\n mShadowPaint = new Paint();\n mShadowRadius = shadowRadius;\n mCircleDiameter = circleDiameter;\n mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2, mShadowRadius, new int[] { FILL_SHADOW_COLOR, Color.TRANSPARENT }, null, Shader.TileMode.CLAMP);\n mShadowPaint.setShader(mRadialGradient);\n }\n\n @Override\n public void draw(Canvas canvas, Paint paint) {\n final int viewWidth = CircleProgressBar.this.getWidth();\n final int viewHeight = CircleProgressBar.this.getHeight();\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius), mShadowPaint);\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);\n }\n }\n\n public void start() {\n mProgressDrawable.start();\n }\n\n public void setStartEndTrim(float startAngle, float endAngle) {\n mProgressDrawable.setStartEndTrim(startAngle, endAngle);\n }\n\n public void stop() {\n mProgressDrawable.stop();\n }\n\n public void setProgressRotation(float rotation) {\n mProgressDrawable.setProgressRotation(rotation);\n }\n}\n"} {"task_id": "Java_1875", "language": "Java", "task_type": "if_statement", "source_file": "java/github/laomengzhu/NsRefreshLayout/nrl/src/main/java/com/xlf/nrl/CircleProgressBar.java", "mask_start_position": 9019, "mask_end_position": 9109, "canonical_solution": "if (mListener != null) {\n mListener.onAnimationStart(getAnimation());\n }", "pre_mask_code": "package com.xlf.nrl;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.RadialGradient;\nimport android.graphics.Shader;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.ShapeDrawable;\nimport android.graphics.drawable.shapes.OvalShape;\nimport android.net.Uri;\nimport android.support.v4.view.ViewCompat;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.animation.Animation;\nimport android.widget.ImageView;\n\n/**\n * The author is lsjwzh(MaterialLoadingProgressBar) link{http://example.com},\n * I did some slight modifications\n */\npublic class CircleProgressBar extends ImageView {\n\n private static final int KEY_SHADOW_COLOR = 0x1E000000;\n\n private static final int FILL_SHADOW_COLOR = 0x3D000000;\n\n // PX\n private static final float X_OFFSET = 0f;\n\n private static final float Y_OFFSET = 1.75f;\n\n private static final float SHADOW_RADIUS = 3.5f;\n\n private static final int SHADOW_ELEVATION = 4;\n\n public static final int DEFAULT_CIRCLE_BG_LIGHT = 0xFFFAFAFA;\n\n public static final int DEFAULT_CIRCLE_COLOR = 0xFFF00000;\n\n private static final int DEFAULT_CIRCLE_DIAMETER = 40;\n\n private static final int STROKE_WIDTH_LARGE = 3;\n\n public static final int DEFAULT_TEXT_SIZE = 9;\n\n private Animation.AnimationListener mListener;\n\n private int mShadowRadius;\n\n private int mBackGroundColor;\n\n private int mProgressColor;\n\n private int mProgressStokeWidth;\n\n private int mArrowWidth;\n\n private int mArrowHeight;\n\n private int mProgress;\n\n private int mMax;\n\n private int mDiameter;\n\n private int mInnerRadius;\n\n private Paint mTextPaint;\n\n private int mTextColor;\n\n private int mTextSize;\n\n private boolean mIfDrawText;\n\n private boolean mShowArrow;\n\n public MaterialProgressDrawable mProgressDrawable;\n\n private ShapeDrawable mBgCircle;\n\n private boolean mCircleBackgroundEnabled;\n\n private int[] mColors = new int[] { Color.BLACK };\n\n public CircleProgressBar(Context context) {\n super(context);\n init(context, null, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context, attrs, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr) {\n final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar, defStyleAttr, 0);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mBackGroundColor = a.getColor(R.styleable.CircleProgressBar_background_color, DEFAULT_CIRCLE_BG_LIGHT);\n mProgressColor = a.getColor(R.styleable.CircleProgressBar_progress_color, DEFAULT_CIRCLE_COLOR);\n mColors = new int[] { mProgressColor };\n mInnerRadius = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_inner_radius, -1);\n mProgressStokeWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_stoke_width, (int) (STROKE_WIDTH_LARGE * density));\n mArrowWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_width, -1);\n mArrowHeight = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_height, -1);\n mTextSize = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_text_size, (int) (DEFAULT_TEXT_SIZE * density));\n mTextColor = a.getColor(R.styleable.CircleProgressBar_progress_text_color, Color.BLACK);\n mShowArrow = a.getBoolean(R.styleable.CircleProgressBar_show_arrow, true);\n mCircleBackgroundEnabled = a.getBoolean(R.styleable.CircleProgressBar_enable_circle_background, true);\n mProgress = a.getInt(R.styleable.CircleProgressBar_progress, 0);\n mMax = a.getInt(R.styleable.CircleProgressBar_max, 100);\n int textVisible = a.getInt(R.styleable.CircleProgressBar_progress_text_visibility, 1);\n if (textVisible != 1) {\n mIfDrawText = true;\n }\n mTextPaint = new Paint();\n mTextPaint.setStyle(Paint.Style.FILL);\n mTextPaint.setColor(mTextColor);\n mTextPaint.setTextSize(mTextSize);\n mTextPaint.setAntiAlias(true);\n a.recycle();\n mProgressDrawable = new MaterialProgressDrawable(getContext(), this);\n super.setImageDrawable(mProgressDrawable);\n }\n\n public void setProgressBackGroundColor(int color) {\n this.mBackGroundColor = color;\n }\n\n public void setTextColor(int color) {\n this.mTextColor = color;\n }\n\n private boolean elevationSupported() {\n return android.os.Build.VERSION.SDK_INT >= 21;\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n if (!elevationSupported()) {\n setMeasuredDimension(getMeasuredWidth() + mShadowRadius * 2, getMeasuredHeight() + mShadowRadius * 2);\n }\n }\n\n public int getProgressStokeWidth() {\n return mProgressStokeWidth;\n }\n\n public void setProgressStokeWidth(int mProgressStokeWidth) {\n final float density = getContext().getResources().getDisplayMetrics().density;\n this.mProgressStokeWidth = (int) (mProgressStokeWidth * density);\n }\n\n @Override\n protected void onLayout(boolean changed, int left, int top, int right, int bottom) {\n super.onLayout(changed, left, top, right, bottom);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mDiameter = Math.min(getMeasuredWidth(), getMeasuredHeight());\n if (mDiameter <= 0) {\n mDiameter = (int) density * DEFAULT_CIRCLE_DIAMETER;\n }\n if (getBackground() == null && mCircleBackgroundEnabled) {\n final int shadowYOffset = (int) (density * Y_OFFSET);\n final int shadowXOffset = (int) (density * X_OFFSET);\n mShadowRadius = (int) (density * SHADOW_RADIUS);\n if (elevationSupported()) {\n mBgCircle = new ShapeDrawable(new OvalShape());\n ViewCompat.setElevation(this, SHADOW_ELEVATION * density);\n } else {\n OvalShape oval = new OvalShadow(mShadowRadius, mDiameter - mShadowRadius * 2);\n mBgCircle = new ShapeDrawable(oval);\n ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, mBgCircle.getPaint());\n mBgCircle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset, KEY_SHADOW_COLOR);\n final int padding = (int) mShadowRadius;\n // set padding so the inner image sits correctly within the shadow.\n setPadding(padding, padding, padding, padding);\n }\n mBgCircle.getPaint().setColor(mBackGroundColor);\n setBackgroundDrawable(mBgCircle);\n }\n mProgressDrawable.setBackgroundColor(mBackGroundColor);\n mProgressDrawable.setColorSchemeColors(mColors);\n mProgressDrawable.setSizeParameters(mDiameter, mDiameter, mInnerRadius <= 0 ? (mDiameter - mProgressStokeWidth * 2) / 4 : mInnerRadius, mProgressStokeWidth, mArrowWidth < 0 ? mProgressStokeWidth * 4 : mArrowWidth, mArrowHeight < 0 ? mProgressStokeWidth * 2 : mArrowHeight);\n if (isShowArrow()) {\n mProgressDrawable.showArrowOnFirstStart(true);\n mProgressDrawable.setArrowScale(1f);\n mProgressDrawable.showArrow(true);\n }\n super.setImageDrawable(null);\n super.setImageDrawable(mProgressDrawable);\n mProgressDrawable.setAlpha(255);\n if (getVisibility() == VISIBLE) {\n mProgressDrawable.setStartEndTrim(0, (float) 0.8);\n }\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n if (mIfDrawText) {\n String text = String.format(\"%s%%\", mProgress);\n int x = getWidth() / 2 - text.length() * mTextSize / 4;\n int y = getHeight() / 2 + mTextSize / 4;\n canvas.drawText(text, x, y, mTextPaint);\n }\n }\n\n @Override\n final public void setImageResource(int resId) {\n }\n\n public boolean isShowArrow() {\n return mShowArrow;\n }\n\n public void setShowArrow(boolean showArrow) {\n this.mShowArrow = showArrow;\n }\n\n @Override\n final public void setImageURI(Uri uri) {\n super.setImageURI(uri);\n }\n\n @Override\n final public void setImageDrawable(Drawable drawable) {\n }\n\n public void setAnimationListener(Animation.AnimationListener listener) {\n mListener = listener;\n }\n\n @Override\n public void onAnimationStart() {\n super.onAnimationStart();\n ", "post_mask_code": "\n }\n\n @Override\n public void onAnimationEnd() {\n super.onAnimationEnd();\n if (mListener != null) {\n mListener.onAnimationEnd(getAnimation());\n }\n }\n\n /**\n * Set the color resources used in the progress animation from color resources.\n * The first color will also be the color of the bar that grows in response\n * to a user swipe gesture.\n *\n * @param colorResIds\n */\n public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }\n\n /**\n * Set the colors used in the progress animation. The first\n * color will also be the color of the bar that grows in response to a user\n * swipe gesture.\n *\n * @param colors\n */\n public void setColorSchemeColors(int... colors) {\n mColors = colors;\n if (mProgressDrawable != null) {\n mProgressDrawable.setColorSchemeColors(colors);\n }\n }\n\n /**\n * Update the background color of the mBgCircle image view.\n */\n public void setBackgroundColorResource(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }\n\n public void setBackgroundColor(int color) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(color);\n }\n }\n\n public boolean isShowProgressText() {\n return mIfDrawText;\n }\n\n public void setShowProgressText(boolean mIfDrawText) {\n this.mIfDrawText = mIfDrawText;\n }\n\n public int getMax() {\n return mMax;\n }\n\n public void setMax(int max) {\n mMax = max;\n }\n\n public int getProgress() {\n return mProgress;\n }\n\n public void setProgress(int progress) {\n if (getMax() > 0) {\n mProgress = progress;\n }\n invalidate();\n Log.i(\"cjj_log\", \"progress------->>>>\" + progress);\n }\n\n public boolean circleBackgroundEnabled() {\n return mCircleBackgroundEnabled;\n }\n\n public void setCircleBackgroundEnabled(boolean enableCircleBackground) {\n this.mCircleBackgroundEnabled = enableCircleBackground;\n }\n\n @Override\n public int getVisibility() {\n return super.getVisibility();\n }\n\n @Override\n public void setVisibility(int visibility) {\n super.setVisibility(visibility);\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(getVisibility() == VISIBLE, false);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(false, false);\n }\n }\n\n private class OvalShadow extends OvalShape {\n\n private RadialGradient mRadialGradient;\n\n private int mShadowRadius;\n\n private Paint mShadowPaint;\n\n private int mCircleDiameter;\n\n public OvalShadow(int shadowRadius, int circleDiameter) {\n super();\n mShadowPaint = new Paint();\n mShadowRadius = shadowRadius;\n mCircleDiameter = circleDiameter;\n mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2, mShadowRadius, new int[] { FILL_SHADOW_COLOR, Color.TRANSPARENT }, null, Shader.TileMode.CLAMP);\n mShadowPaint.setShader(mRadialGradient);\n }\n\n @Override\n public void draw(Canvas canvas, Paint paint) {\n final int viewWidth = CircleProgressBar.this.getWidth();\n final int viewHeight = CircleProgressBar.this.getHeight();\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius), mShadowPaint);\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);\n }\n }\n\n public void start() {\n mProgressDrawable.start();\n }\n\n public void setStartEndTrim(float startAngle, float endAngle) {\n mProgressDrawable.setStartEndTrim(startAngle, endAngle);\n }\n\n public void stop() {\n mProgressDrawable.stop();\n }\n\n public void setProgressRotation(float rotation) {\n mProgressDrawable.setProgressRotation(rotation);\n }\n}\n"} {"task_id": "Java_1876", "language": "Java", "task_type": "for_statement", "source_file": "java/github/laomengzhu/NsRefreshLayout/nrl/src/main/java/com/xlf/nrl/CircleProgressBar.java", "mask_start_position": 9717, "mask_end_position": 9829, "canonical_solution": "for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }", "pre_mask_code": "package com.xlf.nrl;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.RadialGradient;\nimport android.graphics.Shader;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.ShapeDrawable;\nimport android.graphics.drawable.shapes.OvalShape;\nimport android.net.Uri;\nimport android.support.v4.view.ViewCompat;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.animation.Animation;\nimport android.widget.ImageView;\n\n/**\n * The author is lsjwzh(MaterialLoadingProgressBar) link{http://example.com},\n * I did some slight modifications\n */\npublic class CircleProgressBar extends ImageView {\n\n private static final int KEY_SHADOW_COLOR = 0x1E000000;\n\n private static final int FILL_SHADOW_COLOR = 0x3D000000;\n\n // PX\n private static final float X_OFFSET = 0f;\n\n private static final float Y_OFFSET = 1.75f;\n\n private static final float SHADOW_RADIUS = 3.5f;\n\n private static final int SHADOW_ELEVATION = 4;\n\n public static final int DEFAULT_CIRCLE_BG_LIGHT = 0xFFFAFAFA;\n\n public static final int DEFAULT_CIRCLE_COLOR = 0xFFF00000;\n\n private static final int DEFAULT_CIRCLE_DIAMETER = 40;\n\n private static final int STROKE_WIDTH_LARGE = 3;\n\n public static final int DEFAULT_TEXT_SIZE = 9;\n\n private Animation.AnimationListener mListener;\n\n private int mShadowRadius;\n\n private int mBackGroundColor;\n\n private int mProgressColor;\n\n private int mProgressStokeWidth;\n\n private int mArrowWidth;\n\n private int mArrowHeight;\n\n private int mProgress;\n\n private int mMax;\n\n private int mDiameter;\n\n private int mInnerRadius;\n\n private Paint mTextPaint;\n\n private int mTextColor;\n\n private int mTextSize;\n\n private boolean mIfDrawText;\n\n private boolean mShowArrow;\n\n public MaterialProgressDrawable mProgressDrawable;\n\n private ShapeDrawable mBgCircle;\n\n private boolean mCircleBackgroundEnabled;\n\n private int[] mColors = new int[] { Color.BLACK };\n\n public CircleProgressBar(Context context) {\n super(context);\n init(context, null, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context, attrs, 0);\n }\n\n public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr) {\n final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar, defStyleAttr, 0);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mBackGroundColor = a.getColor(R.styleable.CircleProgressBar_background_color, DEFAULT_CIRCLE_BG_LIGHT);\n mProgressColor = a.getColor(R.styleable.CircleProgressBar_progress_color, DEFAULT_CIRCLE_COLOR);\n mColors = new int[] { mProgressColor };\n mInnerRadius = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_inner_radius, -1);\n mProgressStokeWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_stoke_width, (int) (STROKE_WIDTH_LARGE * density));\n mArrowWidth = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_width, -1);\n mArrowHeight = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_arrow_height, -1);\n mTextSize = a.getDimensionPixelOffset(R.styleable.CircleProgressBar_progress_text_size, (int) (DEFAULT_TEXT_SIZE * density));\n mTextColor = a.getColor(R.styleable.CircleProgressBar_progress_text_color, Color.BLACK);\n mShowArrow = a.getBoolean(R.styleable.CircleProgressBar_show_arrow, true);\n mCircleBackgroundEnabled = a.getBoolean(R.styleable.CircleProgressBar_enable_circle_background, true);\n mProgress = a.getInt(R.styleable.CircleProgressBar_progress, 0);\n mMax = a.getInt(R.styleable.CircleProgressBar_max, 100);\n int textVisible = a.getInt(R.styleable.CircleProgressBar_progress_text_visibility, 1);\n if (textVisible != 1) {\n mIfDrawText = true;\n }\n mTextPaint = new Paint();\n mTextPaint.setStyle(Paint.Style.FILL);\n mTextPaint.setColor(mTextColor);\n mTextPaint.setTextSize(mTextSize);\n mTextPaint.setAntiAlias(true);\n a.recycle();\n mProgressDrawable = new MaterialProgressDrawable(getContext(), this);\n super.setImageDrawable(mProgressDrawable);\n }\n\n public void setProgressBackGroundColor(int color) {\n this.mBackGroundColor = color;\n }\n\n public void setTextColor(int color) {\n this.mTextColor = color;\n }\n\n private boolean elevationSupported() {\n return android.os.Build.VERSION.SDK_INT >= 21;\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n if (!elevationSupported()) {\n setMeasuredDimension(getMeasuredWidth() + mShadowRadius * 2, getMeasuredHeight() + mShadowRadius * 2);\n }\n }\n\n public int getProgressStokeWidth() {\n return mProgressStokeWidth;\n }\n\n public void setProgressStokeWidth(int mProgressStokeWidth) {\n final float density = getContext().getResources().getDisplayMetrics().density;\n this.mProgressStokeWidth = (int) (mProgressStokeWidth * density);\n }\n\n @Override\n protected void onLayout(boolean changed, int left, int top, int right, int bottom) {\n super.onLayout(changed, left, top, right, bottom);\n final float density = getContext().getResources().getDisplayMetrics().density;\n mDiameter = Math.min(getMeasuredWidth(), getMeasuredHeight());\n if (mDiameter <= 0) {\n mDiameter = (int) density * DEFAULT_CIRCLE_DIAMETER;\n }\n if (getBackground() == null && mCircleBackgroundEnabled) {\n final int shadowYOffset = (int) (density * Y_OFFSET);\n final int shadowXOffset = (int) (density * X_OFFSET);\n mShadowRadius = (int) (density * SHADOW_RADIUS);\n if (elevationSupported()) {\n mBgCircle = new ShapeDrawable(new OvalShape());\n ViewCompat.setElevation(this, SHADOW_ELEVATION * density);\n } else {\n OvalShape oval = new OvalShadow(mShadowRadius, mDiameter - mShadowRadius * 2);\n mBgCircle = new ShapeDrawable(oval);\n ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, mBgCircle.getPaint());\n mBgCircle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset, KEY_SHADOW_COLOR);\n final int padding = (int) mShadowRadius;\n // set padding so the inner image sits correctly within the shadow.\n setPadding(padding, padding, padding, padding);\n }\n mBgCircle.getPaint().setColor(mBackGroundColor);\n setBackgroundDrawable(mBgCircle);\n }\n mProgressDrawable.setBackgroundColor(mBackGroundColor);\n mProgressDrawable.setColorSchemeColors(mColors);\n mProgressDrawable.setSizeParameters(mDiameter, mDiameter, mInnerRadius <= 0 ? (mDiameter - mProgressStokeWidth * 2) / 4 : mInnerRadius, mProgressStokeWidth, mArrowWidth < 0 ? mProgressStokeWidth * 4 : mArrowWidth, mArrowHeight < 0 ? mProgressStokeWidth * 2 : mArrowHeight);\n if (isShowArrow()) {\n mProgressDrawable.showArrowOnFirstStart(true);\n mProgressDrawable.setArrowScale(1f);\n mProgressDrawable.showArrow(true);\n }\n super.setImageDrawable(null);\n super.setImageDrawable(mProgressDrawable);\n mProgressDrawable.setAlpha(255);\n if (getVisibility() == VISIBLE) {\n mProgressDrawable.setStartEndTrim(0, (float) 0.8);\n }\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n if (mIfDrawText) {\n String text = String.format(\"%s%%\", mProgress);\n int x = getWidth() / 2 - text.length() * mTextSize / 4;\n int y = getHeight() / 2 + mTextSize / 4;\n canvas.drawText(text, x, y, mTextPaint);\n }\n }\n\n @Override\n final public void setImageResource(int resId) {\n }\n\n public boolean isShowArrow() {\n return mShowArrow;\n }\n\n public void setShowArrow(boolean showArrow) {\n this.mShowArrow = showArrow;\n }\n\n @Override\n final public void setImageURI(Uri uri) {\n super.setImageURI(uri);\n }\n\n @Override\n final public void setImageDrawable(Drawable drawable) {\n }\n\n public void setAnimationListener(Animation.AnimationListener listener) {\n mListener = listener;\n }\n\n @Override\n public void onAnimationStart() {\n super.onAnimationStart();\n if (mListener != null) {\n mListener.onAnimationStart(getAnimation());\n }\n }\n\n @Override\n public void onAnimationEnd() {\n super.onAnimationEnd();\n if (mListener != null) {\n mListener.onAnimationEnd(getAnimation());\n }\n }\n\n /**\n * Set the color resources used in the progress animation from color resources.\n * The first color will also be the color of the bar that grows in response\n * to a user swipe gesture.\n *\n * @param colorResIds\n */\n public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n ", "post_mask_code": "\n setColorSchemeColors(colorRes);\n }\n\n /**\n * Set the colors used in the progress animation. The first\n * color will also be the color of the bar that grows in response to a user\n * swipe gesture.\n *\n * @param colors\n */\n public void setColorSchemeColors(int... colors) {\n mColors = colors;\n if (mProgressDrawable != null) {\n mProgressDrawable.setColorSchemeColors(colors);\n }\n }\n\n /**\n * Update the background color of the mBgCircle image view.\n */\n public void setBackgroundColorResource(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }\n\n public void setBackgroundColor(int color) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(color);\n }\n }\n\n public boolean isShowProgressText() {\n return mIfDrawText;\n }\n\n public void setShowProgressText(boolean mIfDrawText) {\n this.mIfDrawText = mIfDrawText;\n }\n\n public int getMax() {\n return mMax;\n }\n\n public void setMax(int max) {\n mMax = max;\n }\n\n public int getProgress() {\n return mProgress;\n }\n\n public void setProgress(int progress) {\n if (getMax() > 0) {\n mProgress = progress;\n }\n invalidate();\n Log.i(\"cjj_log\", \"progress------->>>>\" + progress);\n }\n\n public boolean circleBackgroundEnabled() {\n return mCircleBackgroundEnabled;\n }\n\n public void setCircleBackgroundEnabled(boolean enableCircleBackground) {\n this.mCircleBackgroundEnabled = enableCircleBackground;\n }\n\n @Override\n public int getVisibility() {\n return super.getVisibility();\n }\n\n @Override\n public void setVisibility(int visibility) {\n super.setVisibility(visibility);\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(getVisibility() == VISIBLE, false);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n if (mProgressDrawable != null) {\n mProgressDrawable.stop();\n mProgressDrawable.setVisible(false, false);\n }\n }\n\n private class OvalShadow extends OvalShape {\n\n private RadialGradient mRadialGradient;\n\n private int mShadowRadius;\n\n private Paint mShadowPaint;\n\n private int mCircleDiameter;\n\n public OvalShadow(int shadowRadius, int circleDiameter) {\n super();\n mShadowPaint = new Paint();\n mShadowRadius = shadowRadius;\n mCircleDiameter = circleDiameter;\n mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2, mShadowRadius, new int[] { FILL_SHADOW_COLOR, Color.TRANSPARENT }, null, Shader.TileMode.CLAMP);\n mShadowPaint.setShader(mRadialGradient);\n }\n\n @Override\n public void draw(Canvas canvas, Paint paint) {\n final int viewWidth = CircleProgressBar.this.getWidth();\n final int viewHeight = CircleProgressBar.this.getHeight();\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius), mShadowPaint);\n canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);\n }\n }\n\n public void start() {\n mProgressDrawable.start();\n }\n\n public void setStartEndTrim(float startAngle, float endAngle) {\n mProgressDrawable.setStartEndTrim(startAngle, endAngle);\n }\n\n public void stop() {\n mProgressDrawable.stop();\n }\n\n public void setProgressRotation(float rotation) {\n mProgressDrawable.setProgressRotation(rotation);\n }\n}\n"} {"task_id": "Java_1877", "language": "Java", "task_type": "method_signature", "source_file": "java/github/fanhongtao/JDK/src/com/sun/org/apache/xerces/internal/impl/xs/util/XIntPool.java", "mask_start_position": 360, "mask_end_position": 397, "canonical_solution": "public final XInt getXInt(int value) ", "pre_mask_code": "package com.sun.org.apache.xerces.internal.impl.xs.util;\n\n/**\n * @xerces.internal\n *\n * @author Henry Zongaro, IBM\n */\npublic final class XIntPool {\n\n private static final short POOL_SIZE = 10;\n\n private static final XInt[] fXIntPool = new XInt[POOL_SIZE];\n\n static {\n for (int i = 0; i < POOL_SIZE; i++) fXIntPool[i] = new XInt(i);\n }\n\n ", "post_mask_code": "{\n if (value >= 0 && value < fXIntPool.length)\n return fXIntPool[value];\n else\n return new XInt(value);\n }\n}\n"} {"task_id": "Java_1878", "language": "Java", "task_type": "method_body", "source_file": "java/github/fanhongtao/JDK/src/com/sun/org/apache/xerces/internal/impl/xs/util/XIntPool.java", "mask_start_position": 397, "mask_end_position": 542, "canonical_solution": "{\n if (value >= 0 && value < fXIntPool.length)\n return fXIntPool[value];\n else\n return new XInt(value);\n }", "pre_mask_code": "package com.sun.org.apache.xerces.internal.impl.xs.util;\n\n/**\n * @xerces.internal\n *\n * @author Henry Zongaro, IBM\n */\npublic final class XIntPool {\n\n private static final short POOL_SIZE = 10;\n\n private static final XInt[] fXIntPool = new XInt[POOL_SIZE];\n\n static {\n for (int i = 0; i < POOL_SIZE; i++) fXIntPool[i] = new XInt(i);\n }\n\n public final XInt getXInt(int value) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1879", "language": "Java", "task_type": "if_statement", "source_file": "java/github/fanhongtao/JDK/src/com/sun/org/apache/xerces/internal/impl/xs/util/XIntPool.java", "mask_start_position": 407, "mask_end_position": 536, "canonical_solution": "if (value >= 0 && value < fXIntPool.length)\n return fXIntPool[value];\n else\n return new XInt(value);", "pre_mask_code": "package com.sun.org.apache.xerces.internal.impl.xs.util;\n\n/**\n * @xerces.internal\n *\n * @author Henry Zongaro, IBM\n */\npublic final class XIntPool {\n\n private static final short POOL_SIZE = 10;\n\n private static final XInt[] fXIntPool = new XInt[POOL_SIZE];\n\n static {\n for (int i = 0; i < POOL_SIZE; i++) fXIntPool[i] = new XInt(i);\n }\n\n public final XInt getXInt(int value) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1880", "language": "Java", "task_type": "for_statement", "source_file": "java/github/fanhongtao/JDK/src/com/sun/org/apache/xerces/internal/impl/xs/util/XIntPool.java", "mask_start_position": 285, "mask_end_position": 348, "canonical_solution": "for (int i = 0; i < POOL_SIZE; i++) fXIntPool[i] = new XInt(i);", "pre_mask_code": "package com.sun.org.apache.xerces.internal.impl.xs.util;\n\n/**\n * @xerces.internal\n *\n * @author Henry Zongaro, IBM\n */\npublic final class XIntPool {\n\n private static final short POOL_SIZE = 10;\n\n private static final XInt[] fXIntPool = new XInt[POOL_SIZE];\n\n static {\n ", "post_mask_code": "\n }\n\n public final XInt getXInt(int value) {\n if (value >= 0 && value < fXIntPool.length)\n return fXIntPool[value];\n else\n return new XInt(value);\n }\n}\n"} {"task_id": "Java_1881", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ChenJessi/FakeVibrato/app/src/main/java/com/chen/fakevibrato/widget/emojiview/EmojiconTextView.java", "mask_start_position": 2700, "mask_end_position": 2740, "canonical_solution": "public void setEmojiconSize(int pixels) ", "pre_mask_code": "package com.chen.fakevibrato.widget.emojiview;\n\nimport android.content.Context;\nimport android.text.SpannableStringBuilder;\nimport android.text.TextUtils;\nimport android.util.AttributeSet;\nimport android.widget.TextView;\n\n/**\n * emoji 可以显示emoji的textview\n * @author Created by CHEN on 2019/7/5\n * @email example@nnthink.com\n */\npublic class EmojiconTextView extends TextView {\n\n private int mEmojiconSize;\n\n private int mEmojiconTextSize;\n\n private int mTextStart = 0;\n\n private int mTextLength = -1;\n\n private boolean mUseSystemDefault = false;\n\n public EmojiconTextView(Context context) {\n super(context);\n init(null);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n mEmojiconTextSize = (int) getTextSize();\n mEmojiconSize = (int) getTextSize();\n setText(getText());\n }\n\n public void setTextWithWidth(CharSequence text, int limitedWidth) {\n if (TextUtils.isEmpty(text)) {\n super.setText(text);\n return;\n }\n if (limitedWidth < 0) {\n limitedWidth = this.getMeasuredWidth() - getPaddingRight() - getPaddingLeft();\n }\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n CharSequence trucatedText = TextUtils.ellipsize(builder, getPaint(), limitedWidth, getEllipsize());\n super.setText(trucatedText, BufferType.SPANNABLE);\n }\n\n @Override\n public void setText(CharSequence text, BufferType type) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.setText(text, type);\n }\n\n @Override\n public void append(CharSequence text, int start, int end) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.append(text, start, end);\n }\n\n /**\n * Set the size of emojicon in pixels.\n */\n ", "post_mask_code": "{\n mEmojiconSize = pixels;\n super.setText(getText());\n }\n\n /**\n * Set whether to use system default emojicon\n */\n public void setUseSystemDefault(boolean useSystemDefault) {\n mUseSystemDefault = useSystemDefault;\n }\n}\n"} {"task_id": "Java_1882", "language": "Java", "task_type": "method_body", "source_file": "java/github/ChenJessi/FakeVibrato/app/src/main/java/com/chen/fakevibrato/widget/emojiview/EmojiconTextView.java", "mask_start_position": 1874, "mask_end_position": 2213, "canonical_solution": "{\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.setText(text, type);\n }", "pre_mask_code": "package com.chen.fakevibrato.widget.emojiview;\n\nimport android.content.Context;\nimport android.text.SpannableStringBuilder;\nimport android.text.TextUtils;\nimport android.util.AttributeSet;\nimport android.widget.TextView;\n\n/**\n * emoji 可以显示emoji的textview\n * @author Created by CHEN on 2019/7/5\n * @email example@nnthink.com\n */\npublic class EmojiconTextView extends TextView {\n\n private int mEmojiconSize;\n\n private int mEmojiconTextSize;\n\n private int mTextStart = 0;\n\n private int mTextLength = -1;\n\n private boolean mUseSystemDefault = false;\n\n public EmojiconTextView(Context context) {\n super(context);\n init(null);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n mEmojiconTextSize = (int) getTextSize();\n mEmojiconSize = (int) getTextSize();\n setText(getText());\n }\n\n public void setTextWithWidth(CharSequence text, int limitedWidth) {\n if (TextUtils.isEmpty(text)) {\n super.setText(text);\n return;\n }\n if (limitedWidth < 0) {\n limitedWidth = this.getMeasuredWidth() - getPaddingRight() - getPaddingLeft();\n }\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n CharSequence trucatedText = TextUtils.ellipsize(builder, getPaint(), limitedWidth, getEllipsize());\n super.setText(trucatedText, BufferType.SPANNABLE);\n }\n\n @Override\n public void setText(CharSequence text, BufferType type) ", "post_mask_code": "\n\n @Override\n public void append(CharSequence text, int start, int end) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.append(text, start, end);\n }\n\n /**\n * Set the size of emojicon in pixels.\n */\n public void setEmojiconSize(int pixels) {\n mEmojiconSize = pixels;\n super.setText(getText());\n }\n\n /**\n * Set whether to use system default emojicon\n */\n public void setUseSystemDefault(boolean useSystemDefault) {\n mUseSystemDefault = useSystemDefault;\n }\n}\n"} {"task_id": "Java_1883", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/ChenJessi/FakeVibrato/app/src/main/java/com/chen/fakevibrato/widget/emojiview/EmojiconTextView.java", "mask_start_position": 2292, "mask_end_position": 2589, "canonical_solution": "\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }", "pre_mask_code": "package com.chen.fakevibrato.widget.emojiview;\n\nimport android.content.Context;\nimport android.text.SpannableStringBuilder;\nimport android.text.TextUtils;\nimport android.util.AttributeSet;\nimport android.widget.TextView;\n\n/**\n * emoji 可以显示emoji的textview\n * @author Created by CHEN on 2019/7/5\n * @email example@nnthink.com\n */\npublic class EmojiconTextView extends TextView {\n\n private int mEmojiconSize;\n\n private int mEmojiconTextSize;\n\n private int mTextStart = 0;\n\n private int mTextLength = -1;\n\n private boolean mUseSystemDefault = false;\n\n public EmojiconTextView(Context context) {\n super(context);\n init(null);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n mEmojiconTextSize = (int) getTextSize();\n mEmojiconSize = (int) getTextSize();\n setText(getText());\n }\n\n public void setTextWithWidth(CharSequence text, int limitedWidth) {\n if (TextUtils.isEmpty(text)) {\n super.setText(text);\n return;\n }\n if (limitedWidth < 0) {\n limitedWidth = this.getMeasuredWidth() - getPaddingRight() - getPaddingLeft();\n }\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n CharSequence trucatedText = TextUtils.ellipsize(builder, getPaint(), limitedWidth, getEllipsize());\n super.setText(trucatedText, BufferType.SPANNABLE);\n }\n\n @Override\n public void setText(CharSequence text, BufferType type) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.setText(text, type);\n }\n\n @Override\n public void append(CharSequence text, int start, int end) {", "post_mask_code": "\n super.append(text, start, end);\n }\n\n /**\n * Set the size of emojicon in pixels.\n */\n public void setEmojiconSize(int pixels) {\n mEmojiconSize = pixels;\n super.setText(getText());\n }\n\n /**\n * Set whether to use system default emojicon\n */\n public void setUseSystemDefault(boolean useSystemDefault) {\n mUseSystemDefault = useSystemDefault;\n }\n}\n"} {"task_id": "Java_1884", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/ChenJessi/FakeVibrato/app/src/main/java/com/chen/fakevibrato/widget/emojiview/EmojiconTextView.java", "mask_start_position": 2598, "mask_end_position": 2629, "canonical_solution": "super.append(text, start, end);", "pre_mask_code": "package com.chen.fakevibrato.widget.emojiview;\n\nimport android.content.Context;\nimport android.text.SpannableStringBuilder;\nimport android.text.TextUtils;\nimport android.util.AttributeSet;\nimport android.widget.TextView;\n\n/**\n * emoji 可以显示emoji的textview\n * @author Created by CHEN on 2019/7/5\n * @email example@nnthink.com\n */\npublic class EmojiconTextView extends TextView {\n\n private int mEmojiconSize;\n\n private int mEmojiconTextSize;\n\n private int mTextStart = 0;\n\n private int mTextLength = -1;\n\n private boolean mUseSystemDefault = false;\n\n public EmojiconTextView(Context context) {\n super(context);\n init(null);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n mEmojiconTextSize = (int) getTextSize();\n mEmojiconSize = (int) getTextSize();\n setText(getText());\n }\n\n public void setTextWithWidth(CharSequence text, int limitedWidth) {\n if (TextUtils.isEmpty(text)) {\n super.setText(text);\n return;\n }\n if (limitedWidth < 0) {\n limitedWidth = this.getMeasuredWidth() - getPaddingRight() - getPaddingLeft();\n }\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n CharSequence trucatedText = TextUtils.ellipsize(builder, getPaint(), limitedWidth, getEllipsize());\n super.setText(trucatedText, BufferType.SPANNABLE);\n }\n\n @Override\n public void setText(CharSequence text, BufferType type) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.setText(text, type);\n }\n\n @Override\n public void append(CharSequence text, int start, int end) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n ", "post_mask_code": "\n }\n\n /**\n * Set the size of emojicon in pixels.\n */\n public void setEmojiconSize(int pixels) {\n mEmojiconSize = pixels;\n super.setText(getText());\n }\n\n /**\n * Set whether to use system default emojicon\n */\n public void setUseSystemDefault(boolean useSystemDefault) {\n mUseSystemDefault = useSystemDefault;\n }\n}\n"} {"task_id": "Java_1885", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/ChenJessi/FakeVibrato/app/src/main/java/com/chen/fakevibrato/widget/emojiview/EmojiconTextView.java", "mask_start_position": 2634, "mask_end_position": 2635, "canonical_solution": "}", "pre_mask_code": "package com.chen.fakevibrato.widget.emojiview;\n\nimport android.content.Context;\nimport android.text.SpannableStringBuilder;\nimport android.text.TextUtils;\nimport android.util.AttributeSet;\nimport android.widget.TextView;\n\n/**\n * emoji 可以显示emoji的textview\n * @author Created by CHEN on 2019/7/5\n * @email example@nnthink.com\n */\npublic class EmojiconTextView extends TextView {\n\n private int mEmojiconSize;\n\n private int mEmojiconTextSize;\n\n private int mTextStart = 0;\n\n private int mTextLength = -1;\n\n private boolean mUseSystemDefault = false;\n\n public EmojiconTextView(Context context) {\n super(context);\n init(null);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n mEmojiconTextSize = (int) getTextSize();\n mEmojiconSize = (int) getTextSize();\n setText(getText());\n }\n\n public void setTextWithWidth(CharSequence text, int limitedWidth) {\n if (TextUtils.isEmpty(text)) {\n super.setText(text);\n return;\n }\n if (limitedWidth < 0) {\n limitedWidth = this.getMeasuredWidth() - getPaddingRight() - getPaddingLeft();\n }\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n CharSequence trucatedText = TextUtils.ellipsize(builder, getPaint(), limitedWidth, getEllipsize());\n super.setText(trucatedText, BufferType.SPANNABLE);\n }\n\n @Override\n public void setText(CharSequence text, BufferType type) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.setText(text, type);\n }\n\n @Override\n public void append(CharSequence text, int start, int end) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.append(text, start, end);\n ", "post_mask_code": "\n\n /**\n * Set the size of emojicon in pixels.\n */\n public void setEmojiconSize(int pixels) {\n mEmojiconSize = pixels;\n super.setText(getText());\n }\n\n /**\n * Set whether to use system default emojicon\n */\n public void setUseSystemDefault(boolean useSystemDefault) {\n mUseSystemDefault = useSystemDefault;\n }\n}\n"} {"task_id": "Java_1886", "language": "Java", "task_type": "single_line", "source_file": "java/github/ChenJessi/FakeVibrato/app/src/main/java/com/chen/fakevibrato/widget/emojiview/EmojiconTextView.java", "mask_start_position": 2613, "mask_end_position": 2629, "canonical_solution": "xt, start, end);", "pre_mask_code": "package com.chen.fakevibrato.widget.emojiview;\n\nimport android.content.Context;\nimport android.text.SpannableStringBuilder;\nimport android.text.TextUtils;\nimport android.util.AttributeSet;\nimport android.widget.TextView;\n\n/**\n * emoji 可以显示emoji的textview\n * @author Created by CHEN on 2019/7/5\n * @email example@nnthink.com\n */\npublic class EmojiconTextView extends TextView {\n\n private int mEmojiconSize;\n\n private int mEmojiconTextSize;\n\n private int mTextStart = 0;\n\n private int mTextLength = -1;\n\n private boolean mUseSystemDefault = false;\n\n public EmojiconTextView(Context context) {\n super(context);\n init(null);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n mEmojiconTextSize = (int) getTextSize();\n mEmojiconSize = (int) getTextSize();\n setText(getText());\n }\n\n public void setTextWithWidth(CharSequence text, int limitedWidth) {\n if (TextUtils.isEmpty(text)) {\n super.setText(text);\n return;\n }\n if (limitedWidth < 0) {\n limitedWidth = this.getMeasuredWidth() - getPaddingRight() - getPaddingLeft();\n }\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n CharSequence trucatedText = TextUtils.ellipsize(builder, getPaint(), limitedWidth, getEllipsize());\n super.setText(trucatedText, BufferType.SPANNABLE);\n }\n\n @Override\n public void setText(CharSequence text, BufferType type) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.setText(text, type);\n }\n\n @Override\n public void append(CharSequence text, int start, int end) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.append(te", "post_mask_code": "\n }\n\n /**\n * Set the size of emojicon in pixels.\n */\n public void setEmojiconSize(int pixels) {\n mEmojiconSize = pixels;\n super.setText(getText());\n }\n\n /**\n * Set whether to use system default emojicon\n */\n public void setUseSystemDefault(boolean useSystemDefault) {\n mUseSystemDefault = useSystemDefault;\n }\n}\n"} {"task_id": "Java_1887", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/ChenJessi/FakeVibrato/app/src/main/java/com/chen/fakevibrato/widget/emojiview/EmojiconTextView.java", "mask_start_position": 2885, "mask_end_position": 2996, "canonical_solution": "public void setUseSystemDefault(boolean useSystemDefault) {\n mUseSystemDefault = useSystemDefault;\n }", "pre_mask_code": "package com.chen.fakevibrato.widget.emojiview;\n\nimport android.content.Context;\nimport android.text.SpannableStringBuilder;\nimport android.text.TextUtils;\nimport android.util.AttributeSet;\nimport android.widget.TextView;\n\n/**\n * emoji 可以显示emoji的textview\n * @author Created by CHEN on 2019/7/5\n * @email example@nnthink.com\n */\npublic class EmojiconTextView extends TextView {\n\n private int mEmojiconSize;\n\n private int mEmojiconTextSize;\n\n private int mTextStart = 0;\n\n private int mTextLength = -1;\n\n private boolean mUseSystemDefault = false;\n\n public EmojiconTextView(Context context) {\n super(context);\n init(null);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n mEmojiconTextSize = (int) getTextSize();\n mEmojiconSize = (int) getTextSize();\n setText(getText());\n }\n\n public void setTextWithWidth(CharSequence text, int limitedWidth) {\n if (TextUtils.isEmpty(text)) {\n super.setText(text);\n return;\n }\n if (limitedWidth < 0) {\n limitedWidth = this.getMeasuredWidth() - getPaddingRight() - getPaddingLeft();\n }\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n CharSequence trucatedText = TextUtils.ellipsize(builder, getPaint(), limitedWidth, getEllipsize());\n super.setText(trucatedText, BufferType.SPANNABLE);\n }\n\n @Override\n public void setText(CharSequence text, BufferType type) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.setText(text, type);\n }\n\n @Override\n public void append(CharSequence text, int start, int end) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.append(text, start, end);\n }\n\n /**\n * Set the size of emojicon in pixels.\n */\n public void setEmojiconSize(int pixels) {\n mEmojiconSize = pixels;\n super.setText(getText());\n }\n\n /**\n * Set whether to use system default emojicon\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1888", "language": "Java", "task_type": "if_statement", "source_file": "java/github/ChenJessi/FakeVibrato/app/src/main/java/com/chen/fakevibrato/widget/emojiview/EmojiconTextView.java", "mask_start_position": 1188, "mask_end_position": 1281, "canonical_solution": "if (TextUtils.isEmpty(text)) {\n super.setText(text);\n return;\n }", "pre_mask_code": "package com.chen.fakevibrato.widget.emojiview;\n\nimport android.content.Context;\nimport android.text.SpannableStringBuilder;\nimport android.text.TextUtils;\nimport android.util.AttributeSet;\nimport android.widget.TextView;\n\n/**\n * emoji 可以显示emoji的textview\n * @author Created by CHEN on 2019/7/5\n * @email example@nnthink.com\n */\npublic class EmojiconTextView extends TextView {\n\n private int mEmojiconSize;\n\n private int mEmojiconTextSize;\n\n private int mTextStart = 0;\n\n private int mTextLength = -1;\n\n private boolean mUseSystemDefault = false;\n\n public EmojiconTextView(Context context) {\n super(context);\n init(null);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n public EmojiconTextView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n mEmojiconTextSize = (int) getTextSize();\n mEmojiconSize = (int) getTextSize();\n setText(getText());\n }\n\n public void setTextWithWidth(CharSequence text, int limitedWidth) {\n ", "post_mask_code": "\n if (limitedWidth < 0) {\n limitedWidth = this.getMeasuredWidth() - getPaddingRight() - getPaddingLeft();\n }\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n CharSequence trucatedText = TextUtils.ellipsize(builder, getPaint(), limitedWidth, getEllipsize());\n super.setText(trucatedText, BufferType.SPANNABLE);\n }\n\n @Override\n public void setText(CharSequence text, BufferType type) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.setText(text, type);\n }\n\n @Override\n public void append(CharSequence text, int start, int end) {\n if (!TextUtils.isEmpty(text)) {\n SpannableStringBuilder builder = new SpannableStringBuilder(text);\n EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);\n text = builder;\n }\n super.append(text, start, end);\n }\n\n /**\n * Set the size of emojicon in pixels.\n */\n public void setEmojiconSize(int pixels) {\n mEmojiconSize = pixels;\n super.setText(getText());\n }\n\n /**\n * Set whether to use system default emojicon\n */\n public void setUseSystemDefault(boolean useSystemDefault) {\n mUseSystemDefault = useSystemDefault;\n }\n}\n"} {"task_id": "Java_1889", "language": "Java", "task_type": "method_signature", "source_file": "java/github/afs/rdf-delta/rdf-delta-base/src/main/java/org/seaborne/delta/link/DeltaLinkCounter.java", "mask_start_position": 606, "mask_end_position": 633, "canonical_solution": "public long countCreated() ", "pre_mask_code": "package org.seaborne.delta.link;\n\nimport java.util.concurrent.atomic.LongAdder;\nimport org.seaborne.delta.Id;\nimport org.seaborne.delta.Version;\nimport org.seaborne.patch.RDFPatch;\n\n/**\n * {@link DeltaLink} listener that counts operations.\n */\npublic class DeltaLinkCounter implements DeltaLinkListener {\n\n private LongAdder cNew = new LongAdder();\n\n private LongAdder cCopied = new LongAdder();\n\n private LongAdder cRename = new LongAdder();\n\n private LongAdder cRemove = new LongAdder();\n\n private LongAdder cFetch = new LongAdder();\n\n private LongAdder cAppend = new LongAdder();\n\n ", "post_mask_code": "{\n return cNew.longValue();\n }\n\n public long countCopied() {\n return cCopied.longValue();\n }\n\n public long countRenamed() {\n return cRename.longValue();\n }\n\n public long countRemoved() {\n return cRemove.longValue();\n }\n\n public long countFetch() {\n return cFetch.longValue();\n }\n\n public long countAppend() {\n return cAppend.longValue();\n }\n\n @Override\n public void newDataSource(Id dsRef, String name) {\n cNew.increment();\n }\n\n @Override\n public void copyDataSource(Id dsRef, Id dsRef2, String oldName, String newName) {\n cCopied.increment();\n }\n\n @Override\n public void renameDataSource(Id dsRef, Id dsRef2, String oldName, String newName) {\n cRename.increment();\n }\n\n @Override\n public void removeDataSource(Id dsRef) {\n cRemove.increment();\n }\n\n @Override\n public void fetchById(Id dsRef, Id patchId, RDFPatch patch) {\n cFetch.increment();\n }\n\n @Override\n public void fetchByVersion(Id dsRef, Version version, RDFPatch patch) {\n cFetch.increment();\n }\n\n @Override\n public void append(Id dsRef, Version version, RDFPatch patch) {\n cAppend.increment();\n }\n}\n"} {"task_id": "Java_1890", "language": "Java", "task_type": "method_body", "source_file": "java/github/afs/rdf-delta/rdf-delta-base/src/main/java/org/seaborne/delta/link/DeltaLinkCounter.java", "mask_start_position": 1724, "mask_end_position": 1759, "canonical_solution": "{\n cFetch.increment();\n }", "pre_mask_code": "package org.seaborne.delta.link;\n\nimport java.util.concurrent.atomic.LongAdder;\nimport org.seaborne.delta.Id;\nimport org.seaborne.delta.Version;\nimport org.seaborne.patch.RDFPatch;\n\n/**\n * {@link DeltaLink} listener that counts operations.\n */\npublic class DeltaLinkCounter implements DeltaLinkListener {\n\n private LongAdder cNew = new LongAdder();\n\n private LongAdder cCopied = new LongAdder();\n\n private LongAdder cRename = new LongAdder();\n\n private LongAdder cRemove = new LongAdder();\n\n private LongAdder cFetch = new LongAdder();\n\n private LongAdder cAppend = new LongAdder();\n\n public long countCreated() {\n return cNew.longValue();\n }\n\n public long countCopied() {\n return cCopied.longValue();\n }\n\n public long countRenamed() {\n return cRename.longValue();\n }\n\n public long countRemoved() {\n return cRemove.longValue();\n }\n\n public long countFetch() {\n return cFetch.longValue();\n }\n\n public long countAppend() {\n return cAppend.longValue();\n }\n\n @Override\n public void newDataSource(Id dsRef, String name) {\n cNew.increment();\n }\n\n @Override\n public void copyDataSource(Id dsRef, Id dsRef2, String oldName, String newName) {\n cCopied.increment();\n }\n\n @Override\n public void renameDataSource(Id dsRef, Id dsRef2, String oldName, String newName) {\n cRename.increment();\n }\n\n @Override\n public void removeDataSource(Id dsRef) {\n cRemove.increment();\n }\n\n @Override\n public void fetchById(Id dsRef, Id patchId, RDFPatch patch) {\n cFetch.increment();\n }\n\n @Override\n public void fetchByVersion(Id dsRef, Version version, RDFPatch patch) ", "post_mask_code": "\n\n @Override\n public void append(Id dsRef, Version version, RDFPatch patch) {\n cAppend.increment();\n }\n}\n"} {"task_id": "Java_1891", "language": "Java", "task_type": "single_line", "source_file": "java/github/afs/rdf-delta/rdf-delta-base/src/main/java/org/seaborne/delta/link/DeltaLinkCounter.java", "mask_start_position": 1870, "mask_end_position": 1871, "canonical_solution": ";", "pre_mask_code": "package org.seaborne.delta.link;\n\nimport java.util.concurrent.atomic.LongAdder;\nimport org.seaborne.delta.Id;\nimport org.seaborne.delta.Version;\nimport org.seaborne.patch.RDFPatch;\n\n/**\n * {@link DeltaLink} listener that counts operations.\n */\npublic class DeltaLinkCounter implements DeltaLinkListener {\n\n private LongAdder cNew = new LongAdder();\n\n private LongAdder cCopied = new LongAdder();\n\n private LongAdder cRename = new LongAdder();\n\n private LongAdder cRemove = new LongAdder();\n\n private LongAdder cFetch = new LongAdder();\n\n private LongAdder cAppend = new LongAdder();\n\n public long countCreated() {\n return cNew.longValue();\n }\n\n public long countCopied() {\n return cCopied.longValue();\n }\n\n public long countRenamed() {\n return cRename.longValue();\n }\n\n public long countRemoved() {\n return cRemove.longValue();\n }\n\n public long countFetch() {\n return cFetch.longValue();\n }\n\n public long countAppend() {\n return cAppend.longValue();\n }\n\n @Override\n public void newDataSource(Id dsRef, String name) {\n cNew.increment();\n }\n\n @Override\n public void copyDataSource(Id dsRef, Id dsRef2, String oldName, String newName) {\n cCopied.increment();\n }\n\n @Override\n public void renameDataSource(Id dsRef, Id dsRef2, String oldName, String newName) {\n cRename.increment();\n }\n\n @Override\n public void removeDataSource(Id dsRef) {\n cRemove.increment();\n }\n\n @Override\n public void fetchById(Id dsRef, Id patchId, RDFPatch patch) {\n cFetch.increment();\n }\n\n @Override\n public void fetchByVersion(Id dsRef, Version version, RDFPatch patch) {\n cFetch.increment();\n }\n\n @Override\n public void append(Id dsRef, Version version, RDFPatch patch) {\n cAppend.increment()", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1892", "language": "Java", "task_type": "method_signature", "source_file": "java/github/almondtools/stringsearchalgorithms/src/main/java/net/amygdalum/stringsearchalgorithms/search/chars/ShiftOr.java", "mask_start_position": 3292, "mask_end_position": 3339, "canonical_solution": "@Override\n public void skipTo(long pos) ", "pre_mask_code": "package net.amygdalum.stringsearchalgorithms.search.chars;\n\nimport static java.lang.Math.max;\nimport static java.util.Arrays.fill;\nimport net.amygdalum.stringsearchalgorithms.search.AbstractStringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinderOption;\nimport net.amygdalum.stringsearchalgorithms.search.StringMatch;\nimport net.amygdalum.util.io.CharProvider;\nimport net.amygdalum.util.map.CharLongMap;\nimport net.amygdalum.util.map.CharObjectMap;\nimport net.amygdalum.util.text.CharAlphabet;\nimport net.amygdalum.util.text.CharMapping;\n\n/**\n * An implementation of the String Search Algorithm Shift-Or (or Baeza-Yates–Gonnet).\n *\n * This algorithm takes a single pattern as input and generates a finder which can find this pattern in documents\n */\npublic class ShiftOr implements StringSearchAlgorithm {\n\n private int patternLength;\n\n private BitMapStates states;\n\n public ShiftOr(String pattern) {\n this(pattern, CharMapping.IDENTITY);\n }\n\n public ShiftOr(String pattern, CharMapping mapping) {\n this.patternLength = pattern.length();\n this.states = computeStates(pattern.toCharArray(), mapping);\n }\n\n private static BitMapStates computeStates(char[] pattern, CharMapping mapping) {\n CharAlphabet alphabet = CharAlphabet.ranged(pattern, mapping);\n int compactSize = max(256, pattern.length * 2);\n if (alphabet.getRange() < compactSize) {\n if (pattern.length > 64) {\n return new QuickMultiLongStates(pattern, alphabet, mapping);\n } else {\n return new QuickSingleLongStates(pattern, alphabet, mapping);\n }\n } else {\n if (pattern.length > 64) {\n return new SmartMultiLongStates(pattern, mapping);\n } else {\n return new SmartSingleLongStates(pattern, mapping);\n }\n }\n }\n\n @Override\n public int getPatternLength() {\n return patternLength;\n }\n\n @Override\n public StringFinder createFinder(CharProvider chars, StringFinderOption... options) {\n if (states.supportsSingle()) {\n return new LongFinder(chars, options);\n } else {\n return new MultiLongFinder(chars, options);\n }\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n private abstract class Finder extends AbstractStringFinder {\n\n protected final long finalstate;\n\n protected CharProvider chars;\n\n public Finder(CharProvider chars, StringFinderOption... options) {\n super(options);\n this.finalstate = ~(1l << ((patternLength - 1) % 64));\n this.chars = chars;\n }\n\n protected StringMatch createMatch() {\n long end = chars.current();\n long start = end - patternLength;\n String s = chars.slice(start, end);\n return new StringMatch(start, end, s);\n }\n }\n\n private class LongFinder extends Finder {\n\n private long state;\n\n public LongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = BitMapStates.ALLBITS;\n }\n\n ", "post_mask_code": "{\n if (pos > chars.current()) {\n chars.move(pos);\n }\n state = BitMapStates.ALLBITS;\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long bits = states.single(nextChar);\n state = (state << 1) | bits;\n if ((state | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n }\n\n private class MultiLongFinder extends Finder {\n\n private long[] state;\n\n public MultiLongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = new long[((patternLength - 1) / 64) + 1];\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long[] bits = states.all(nextChar);\n state = next(state, bits);\n if ((state[0] | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n\n private long[] next(long[] state, long[] bits) {\n for (int i = 0; i < state.length; i++) {\n int j = i + 1;\n long leastBit = j < state.length ? state[j] >>> 63 : 0l;\n state[i] = (state[i] << 1 | leastBit) | bits[i];\n }\n return state;\n }\n }\n\n public static class Factory implements StringSearchAlgorithmFactory, SupportsCharClasses {\n\n private CharMapping mapping;\n\n @Override\n public void enableCharClasses(CharMapping mapping) {\n this.mapping = mapping;\n }\n\n @Override\n public StringSearchAlgorithm of(String pattern) {\n if (mapping == null) {\n return new ShiftOr(pattern);\n } else {\n return new ShiftOr(pattern, mapping);\n }\n }\n }\n\n public interface BitMapStates {\n\n public static final long ALLBITS = ~0l;\n\n boolean supportsSingle();\n\n long single(char c);\n\n long[] all(char c);\n }\n\n private abstract static class SingleLongBitMapStates implements BitMapStates {\n\n @Override\n public boolean supportsSingle() {\n return true;\n }\n\n @Override\n public long[] all(char c) {\n return new long[] { single(c) };\n }\n }\n\n private static class QuickSingleLongStates extends SingleLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[] characters;\n\n public QuickSingleLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n }\n\n private static long[] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[] characters = new long[max - min + 1];\n fill(characters, ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n characters[c - min] &= ~(1l << i);\n }\n }\n return characters;\n }\n\n @Override\n public long single(char c) {\n if (c < minChar || c > maxChar) {\n return ALLBITS;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartSingleLongStates extends SingleLongBitMapStates {\n\n private CharLongMap states;\n\n public SmartSingleLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharLongMap computeStates(char[] pattern, CharMapping mapping) {\n CharLongMap map = new CharLongMap(ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n long newState = map.get(c) & ~(1l << i);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long single(char c) {\n return states.get(c);\n }\n }\n\n private abstract static class MultiLongBitMapStates implements BitMapStates {\n\n public static long[] computeZero(int length) {\n long[] zero = new long[((length - 1) / 64) + 1];\n fill(zero, ALLBITS);\n return zero;\n }\n\n @Override\n public boolean supportsSingle() {\n return false;\n }\n\n @Override\n public long single(char c) {\n throw new UnsupportedOperationException();\n }\n }\n\n private static class QuickMultiLongStates extends MultiLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[][] characters;\n\n private long[] zero;\n\n public QuickMultiLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n this.zero = computeZero(pattern.length);\n }\n\n private static long[][] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[][] characters = new long[max - min + 1][];\n for (int c = min; c <= max; c++) {\n characters[c - min] = computeZero(pattern.length);\n }\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n characters[c - min][slot] &= ~(1l << offset);\n }\n }\n return characters;\n }\n\n @Override\n public long[] all(char c) {\n if (c < minChar || c > maxChar) {\n return zero;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartMultiLongStates extends MultiLongBitMapStates {\n\n private CharObjectMap states;\n\n public SmartMultiLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharObjectMap computeStates(char[] pattern, CharMapping mapping) {\n long[] zero = computeZero(pattern.length);\n CharObjectMap map = new CharObjectMap<>(zero);\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n long[] newState = map.get(c);\n if (newState == zero) {\n newState = computeZero(pattern.length);\n }\n newState[slot] &= ~(1l << offset);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long[] all(char c) {\n return states.get(c);\n }\n }\n}\n"} {"task_id": "Java_1893", "language": "Java", "task_type": "method_body", "source_file": "java/github/almondtools/stringsearchalgorithms/src/main/java/net/amygdalum/stringsearchalgorithms/search/chars/ShiftOr.java", "mask_start_position": 6134, "mask_end_position": 6190, "canonical_solution": "{\n return new long[] { single(c) };\n }", "pre_mask_code": "package net.amygdalum.stringsearchalgorithms.search.chars;\n\nimport static java.lang.Math.max;\nimport static java.util.Arrays.fill;\nimport net.amygdalum.stringsearchalgorithms.search.AbstractStringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinderOption;\nimport net.amygdalum.stringsearchalgorithms.search.StringMatch;\nimport net.amygdalum.util.io.CharProvider;\nimport net.amygdalum.util.map.CharLongMap;\nimport net.amygdalum.util.map.CharObjectMap;\nimport net.amygdalum.util.text.CharAlphabet;\nimport net.amygdalum.util.text.CharMapping;\n\n/**\n * An implementation of the String Search Algorithm Shift-Or (or Baeza-Yates–Gonnet).\n *\n * This algorithm takes a single pattern as input and generates a finder which can find this pattern in documents\n */\npublic class ShiftOr implements StringSearchAlgorithm {\n\n private int patternLength;\n\n private BitMapStates states;\n\n public ShiftOr(String pattern) {\n this(pattern, CharMapping.IDENTITY);\n }\n\n public ShiftOr(String pattern, CharMapping mapping) {\n this.patternLength = pattern.length();\n this.states = computeStates(pattern.toCharArray(), mapping);\n }\n\n private static BitMapStates computeStates(char[] pattern, CharMapping mapping) {\n CharAlphabet alphabet = CharAlphabet.ranged(pattern, mapping);\n int compactSize = max(256, pattern.length * 2);\n if (alphabet.getRange() < compactSize) {\n if (pattern.length > 64) {\n return new QuickMultiLongStates(pattern, alphabet, mapping);\n } else {\n return new QuickSingleLongStates(pattern, alphabet, mapping);\n }\n } else {\n if (pattern.length > 64) {\n return new SmartMultiLongStates(pattern, mapping);\n } else {\n return new SmartSingleLongStates(pattern, mapping);\n }\n }\n }\n\n @Override\n public int getPatternLength() {\n return patternLength;\n }\n\n @Override\n public StringFinder createFinder(CharProvider chars, StringFinderOption... options) {\n if (states.supportsSingle()) {\n return new LongFinder(chars, options);\n } else {\n return new MultiLongFinder(chars, options);\n }\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n private abstract class Finder extends AbstractStringFinder {\n\n protected final long finalstate;\n\n protected CharProvider chars;\n\n public Finder(CharProvider chars, StringFinderOption... options) {\n super(options);\n this.finalstate = ~(1l << ((patternLength - 1) % 64));\n this.chars = chars;\n }\n\n protected StringMatch createMatch() {\n long end = chars.current();\n long start = end - patternLength;\n String s = chars.slice(start, end);\n return new StringMatch(start, end, s);\n }\n }\n\n private class LongFinder extends Finder {\n\n private long state;\n\n public LongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = BitMapStates.ALLBITS;\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n state = BitMapStates.ALLBITS;\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long bits = states.single(nextChar);\n state = (state << 1) | bits;\n if ((state | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n }\n\n private class MultiLongFinder extends Finder {\n\n private long[] state;\n\n public MultiLongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = new long[((patternLength - 1) / 64) + 1];\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long[] bits = states.all(nextChar);\n state = next(state, bits);\n if ((state[0] | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n\n private long[] next(long[] state, long[] bits) {\n for (int i = 0; i < state.length; i++) {\n int j = i + 1;\n long leastBit = j < state.length ? state[j] >>> 63 : 0l;\n state[i] = (state[i] << 1 | leastBit) | bits[i];\n }\n return state;\n }\n }\n\n public static class Factory implements StringSearchAlgorithmFactory, SupportsCharClasses {\n\n private CharMapping mapping;\n\n @Override\n public void enableCharClasses(CharMapping mapping) {\n this.mapping = mapping;\n }\n\n @Override\n public StringSearchAlgorithm of(String pattern) {\n if (mapping == null) {\n return new ShiftOr(pattern);\n } else {\n return new ShiftOr(pattern, mapping);\n }\n }\n }\n\n public interface BitMapStates {\n\n public static final long ALLBITS = ~0l;\n\n boolean supportsSingle();\n\n long single(char c);\n\n long[] all(char c);\n }\n\n private abstract static class SingleLongBitMapStates implements BitMapStates {\n\n @Override\n public boolean supportsSingle() {\n return true;\n }\n\n @Override\n public long[] all(char c) ", "post_mask_code": "\n }\n\n private static class QuickSingleLongStates extends SingleLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[] characters;\n\n public QuickSingleLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n }\n\n private static long[] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[] characters = new long[max - min + 1];\n fill(characters, ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n characters[c - min] &= ~(1l << i);\n }\n }\n return characters;\n }\n\n @Override\n public long single(char c) {\n if (c < minChar || c > maxChar) {\n return ALLBITS;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartSingleLongStates extends SingleLongBitMapStates {\n\n private CharLongMap states;\n\n public SmartSingleLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharLongMap computeStates(char[] pattern, CharMapping mapping) {\n CharLongMap map = new CharLongMap(ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n long newState = map.get(c) & ~(1l << i);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long single(char c) {\n return states.get(c);\n }\n }\n\n private abstract static class MultiLongBitMapStates implements BitMapStates {\n\n public static long[] computeZero(int length) {\n long[] zero = new long[((length - 1) / 64) + 1];\n fill(zero, ALLBITS);\n return zero;\n }\n\n @Override\n public boolean supportsSingle() {\n return false;\n }\n\n @Override\n public long single(char c) {\n throw new UnsupportedOperationException();\n }\n }\n\n private static class QuickMultiLongStates extends MultiLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[][] characters;\n\n private long[] zero;\n\n public QuickMultiLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n this.zero = computeZero(pattern.length);\n }\n\n private static long[][] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[][] characters = new long[max - min + 1][];\n for (int c = min; c <= max; c++) {\n characters[c - min] = computeZero(pattern.length);\n }\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n characters[c - min][slot] &= ~(1l << offset);\n }\n }\n return characters;\n }\n\n @Override\n public long[] all(char c) {\n if (c < minChar || c > maxChar) {\n return zero;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartMultiLongStates extends MultiLongBitMapStates {\n\n private CharObjectMap states;\n\n public SmartMultiLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharObjectMap computeStates(char[] pattern, CharMapping mapping) {\n long[] zero = computeZero(pattern.length);\n CharObjectMap map = new CharObjectMap<>(zero);\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n long[] newState = map.get(c);\n if (newState == zero) {\n newState = computeZero(pattern.length);\n }\n newState[slot] &= ~(1l << offset);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long[] all(char c) {\n return states.get(c);\n }\n }\n}\n"} {"task_id": "Java_1894", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/almondtools/stringsearchalgorithms/src/main/java/net/amygdalum/stringsearchalgorithms/search/chars/ShiftOr.java", "mask_start_position": 4914, "mask_end_position": 5150, "canonical_solution": "\n for (int i = 0; i < state.length; i++) {\n int j = i + 1;\n long leastBit = j < state.length ? state[j] >>> 63 : 0l;\n state[i] = (state[i] << 1 | leastBit) | bits[i];\n }", "pre_mask_code": "package net.amygdalum.stringsearchalgorithms.search.chars;\n\nimport static java.lang.Math.max;\nimport static java.util.Arrays.fill;\nimport net.amygdalum.stringsearchalgorithms.search.AbstractStringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinderOption;\nimport net.amygdalum.stringsearchalgorithms.search.StringMatch;\nimport net.amygdalum.util.io.CharProvider;\nimport net.amygdalum.util.map.CharLongMap;\nimport net.amygdalum.util.map.CharObjectMap;\nimport net.amygdalum.util.text.CharAlphabet;\nimport net.amygdalum.util.text.CharMapping;\n\n/**\n * An implementation of the String Search Algorithm Shift-Or (or Baeza-Yates–Gonnet).\n *\n * This algorithm takes a single pattern as input and generates a finder which can find this pattern in documents\n */\npublic class ShiftOr implements StringSearchAlgorithm {\n\n private int patternLength;\n\n private BitMapStates states;\n\n public ShiftOr(String pattern) {\n this(pattern, CharMapping.IDENTITY);\n }\n\n public ShiftOr(String pattern, CharMapping mapping) {\n this.patternLength = pattern.length();\n this.states = computeStates(pattern.toCharArray(), mapping);\n }\n\n private static BitMapStates computeStates(char[] pattern, CharMapping mapping) {\n CharAlphabet alphabet = CharAlphabet.ranged(pattern, mapping);\n int compactSize = max(256, pattern.length * 2);\n if (alphabet.getRange() < compactSize) {\n if (pattern.length > 64) {\n return new QuickMultiLongStates(pattern, alphabet, mapping);\n } else {\n return new QuickSingleLongStates(pattern, alphabet, mapping);\n }\n } else {\n if (pattern.length > 64) {\n return new SmartMultiLongStates(pattern, mapping);\n } else {\n return new SmartSingleLongStates(pattern, mapping);\n }\n }\n }\n\n @Override\n public int getPatternLength() {\n return patternLength;\n }\n\n @Override\n public StringFinder createFinder(CharProvider chars, StringFinderOption... options) {\n if (states.supportsSingle()) {\n return new LongFinder(chars, options);\n } else {\n return new MultiLongFinder(chars, options);\n }\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n private abstract class Finder extends AbstractStringFinder {\n\n protected final long finalstate;\n\n protected CharProvider chars;\n\n public Finder(CharProvider chars, StringFinderOption... options) {\n super(options);\n this.finalstate = ~(1l << ((patternLength - 1) % 64));\n this.chars = chars;\n }\n\n protected StringMatch createMatch() {\n long end = chars.current();\n long start = end - patternLength;\n String s = chars.slice(start, end);\n return new StringMatch(start, end, s);\n }\n }\n\n private class LongFinder extends Finder {\n\n private long state;\n\n public LongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = BitMapStates.ALLBITS;\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n state = BitMapStates.ALLBITS;\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long bits = states.single(nextChar);\n state = (state << 1) | bits;\n if ((state | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n }\n\n private class MultiLongFinder extends Finder {\n\n private long[] state;\n\n public MultiLongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = new long[((patternLength - 1) / 64) + 1];\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long[] bits = states.all(nextChar);\n state = next(state, bits);\n if ((state[0] | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n\n private long[] next(long[] state, long[] bits) {", "post_mask_code": "\n return state;\n }\n }\n\n public static class Factory implements StringSearchAlgorithmFactory, SupportsCharClasses {\n\n private CharMapping mapping;\n\n @Override\n public void enableCharClasses(CharMapping mapping) {\n this.mapping = mapping;\n }\n\n @Override\n public StringSearchAlgorithm of(String pattern) {\n if (mapping == null) {\n return new ShiftOr(pattern);\n } else {\n return new ShiftOr(pattern, mapping);\n }\n }\n }\n\n public interface BitMapStates {\n\n public static final long ALLBITS = ~0l;\n\n boolean supportsSingle();\n\n long single(char c);\n\n long[] all(char c);\n }\n\n private abstract static class SingleLongBitMapStates implements BitMapStates {\n\n @Override\n public boolean supportsSingle() {\n return true;\n }\n\n @Override\n public long[] all(char c) {\n return new long[] { single(c) };\n }\n }\n\n private static class QuickSingleLongStates extends SingleLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[] characters;\n\n public QuickSingleLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n }\n\n private static long[] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[] characters = new long[max - min + 1];\n fill(characters, ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n characters[c - min] &= ~(1l << i);\n }\n }\n return characters;\n }\n\n @Override\n public long single(char c) {\n if (c < minChar || c > maxChar) {\n return ALLBITS;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartSingleLongStates extends SingleLongBitMapStates {\n\n private CharLongMap states;\n\n public SmartSingleLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharLongMap computeStates(char[] pattern, CharMapping mapping) {\n CharLongMap map = new CharLongMap(ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n long newState = map.get(c) & ~(1l << i);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long single(char c) {\n return states.get(c);\n }\n }\n\n private abstract static class MultiLongBitMapStates implements BitMapStates {\n\n public static long[] computeZero(int length) {\n long[] zero = new long[((length - 1) / 64) + 1];\n fill(zero, ALLBITS);\n return zero;\n }\n\n @Override\n public boolean supportsSingle() {\n return false;\n }\n\n @Override\n public long single(char c) {\n throw new UnsupportedOperationException();\n }\n }\n\n private static class QuickMultiLongStates extends MultiLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[][] characters;\n\n private long[] zero;\n\n public QuickMultiLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n this.zero = computeZero(pattern.length);\n }\n\n private static long[][] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[][] characters = new long[max - min + 1][];\n for (int c = min; c <= max; c++) {\n characters[c - min] = computeZero(pattern.length);\n }\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n characters[c - min][slot] &= ~(1l << offset);\n }\n }\n return characters;\n }\n\n @Override\n public long[] all(char c) {\n if (c < minChar || c > maxChar) {\n return zero;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartMultiLongStates extends MultiLongBitMapStates {\n\n private CharObjectMap states;\n\n public SmartMultiLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharObjectMap computeStates(char[] pattern, CharMapping mapping) {\n long[] zero = computeZero(pattern.length);\n CharObjectMap map = new CharObjectMap<>(zero);\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n long[] newState = map.get(c);\n if (newState == zero) {\n newState = computeZero(pattern.length);\n }\n newState[slot] &= ~(1l << offset);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long[] all(char c) {\n return states.get(c);\n }\n }\n}\n"} {"task_id": "Java_1895", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/almondtools/stringsearchalgorithms/src/main/java/net/amygdalum/stringsearchalgorithms/search/chars/ShiftOr.java", "mask_start_position": 5163, "mask_end_position": 5176, "canonical_solution": "return state;", "pre_mask_code": "package net.amygdalum.stringsearchalgorithms.search.chars;\n\nimport static java.lang.Math.max;\nimport static java.util.Arrays.fill;\nimport net.amygdalum.stringsearchalgorithms.search.AbstractStringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinderOption;\nimport net.amygdalum.stringsearchalgorithms.search.StringMatch;\nimport net.amygdalum.util.io.CharProvider;\nimport net.amygdalum.util.map.CharLongMap;\nimport net.amygdalum.util.map.CharObjectMap;\nimport net.amygdalum.util.text.CharAlphabet;\nimport net.amygdalum.util.text.CharMapping;\n\n/**\n * An implementation of the String Search Algorithm Shift-Or (or Baeza-Yates–Gonnet).\n *\n * This algorithm takes a single pattern as input and generates a finder which can find this pattern in documents\n */\npublic class ShiftOr implements StringSearchAlgorithm {\n\n private int patternLength;\n\n private BitMapStates states;\n\n public ShiftOr(String pattern) {\n this(pattern, CharMapping.IDENTITY);\n }\n\n public ShiftOr(String pattern, CharMapping mapping) {\n this.patternLength = pattern.length();\n this.states = computeStates(pattern.toCharArray(), mapping);\n }\n\n private static BitMapStates computeStates(char[] pattern, CharMapping mapping) {\n CharAlphabet alphabet = CharAlphabet.ranged(pattern, mapping);\n int compactSize = max(256, pattern.length * 2);\n if (alphabet.getRange() < compactSize) {\n if (pattern.length > 64) {\n return new QuickMultiLongStates(pattern, alphabet, mapping);\n } else {\n return new QuickSingleLongStates(pattern, alphabet, mapping);\n }\n } else {\n if (pattern.length > 64) {\n return new SmartMultiLongStates(pattern, mapping);\n } else {\n return new SmartSingleLongStates(pattern, mapping);\n }\n }\n }\n\n @Override\n public int getPatternLength() {\n return patternLength;\n }\n\n @Override\n public StringFinder createFinder(CharProvider chars, StringFinderOption... options) {\n if (states.supportsSingle()) {\n return new LongFinder(chars, options);\n } else {\n return new MultiLongFinder(chars, options);\n }\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n private abstract class Finder extends AbstractStringFinder {\n\n protected final long finalstate;\n\n protected CharProvider chars;\n\n public Finder(CharProvider chars, StringFinderOption... options) {\n super(options);\n this.finalstate = ~(1l << ((patternLength - 1) % 64));\n this.chars = chars;\n }\n\n protected StringMatch createMatch() {\n long end = chars.current();\n long start = end - patternLength;\n String s = chars.slice(start, end);\n return new StringMatch(start, end, s);\n }\n }\n\n private class LongFinder extends Finder {\n\n private long state;\n\n public LongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = BitMapStates.ALLBITS;\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n state = BitMapStates.ALLBITS;\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long bits = states.single(nextChar);\n state = (state << 1) | bits;\n if ((state | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n }\n\n private class MultiLongFinder extends Finder {\n\n private long[] state;\n\n public MultiLongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = new long[((patternLength - 1) / 64) + 1];\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long[] bits = states.all(nextChar);\n state = next(state, bits);\n if ((state[0] | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n\n private long[] next(long[] state, long[] bits) {\n for (int i = 0; i < state.length; i++) {\n int j = i + 1;\n long leastBit = j < state.length ? state[j] >>> 63 : 0l;\n state[i] = (state[i] << 1 | leastBit) | bits[i];\n }\n ", "post_mask_code": "\n }\n }\n\n public static class Factory implements StringSearchAlgorithmFactory, SupportsCharClasses {\n\n private CharMapping mapping;\n\n @Override\n public void enableCharClasses(CharMapping mapping) {\n this.mapping = mapping;\n }\n\n @Override\n public StringSearchAlgorithm of(String pattern) {\n if (mapping == null) {\n return new ShiftOr(pattern);\n } else {\n return new ShiftOr(pattern, mapping);\n }\n }\n }\n\n public interface BitMapStates {\n\n public static final long ALLBITS = ~0l;\n\n boolean supportsSingle();\n\n long single(char c);\n\n long[] all(char c);\n }\n\n private abstract static class SingleLongBitMapStates implements BitMapStates {\n\n @Override\n public boolean supportsSingle() {\n return true;\n }\n\n @Override\n public long[] all(char c) {\n return new long[] { single(c) };\n }\n }\n\n private static class QuickSingleLongStates extends SingleLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[] characters;\n\n public QuickSingleLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n }\n\n private static long[] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[] characters = new long[max - min + 1];\n fill(characters, ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n characters[c - min] &= ~(1l << i);\n }\n }\n return characters;\n }\n\n @Override\n public long single(char c) {\n if (c < minChar || c > maxChar) {\n return ALLBITS;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartSingleLongStates extends SingleLongBitMapStates {\n\n private CharLongMap states;\n\n public SmartSingleLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharLongMap computeStates(char[] pattern, CharMapping mapping) {\n CharLongMap map = new CharLongMap(ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n long newState = map.get(c) & ~(1l << i);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long single(char c) {\n return states.get(c);\n }\n }\n\n private abstract static class MultiLongBitMapStates implements BitMapStates {\n\n public static long[] computeZero(int length) {\n long[] zero = new long[((length - 1) / 64) + 1];\n fill(zero, ALLBITS);\n return zero;\n }\n\n @Override\n public boolean supportsSingle() {\n return false;\n }\n\n @Override\n public long single(char c) {\n throw new UnsupportedOperationException();\n }\n }\n\n private static class QuickMultiLongStates extends MultiLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[][] characters;\n\n private long[] zero;\n\n public QuickMultiLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n this.zero = computeZero(pattern.length);\n }\n\n private static long[][] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[][] characters = new long[max - min + 1][];\n for (int c = min; c <= max; c++) {\n characters[c - min] = computeZero(pattern.length);\n }\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n characters[c - min][slot] &= ~(1l << offset);\n }\n }\n return characters;\n }\n\n @Override\n public long[] all(char c) {\n if (c < minChar || c > maxChar) {\n return zero;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartMultiLongStates extends MultiLongBitMapStates {\n\n private CharObjectMap states;\n\n public SmartMultiLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharObjectMap computeStates(char[] pattern, CharMapping mapping) {\n long[] zero = computeZero(pattern.length);\n CharObjectMap map = new CharObjectMap<>(zero);\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n long[] newState = map.get(c);\n if (newState == zero) {\n newState = computeZero(pattern.length);\n }\n newState[slot] &= ~(1l << offset);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long[] all(char c) {\n return states.get(c);\n }\n }\n}\n"} {"task_id": "Java_1896", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/almondtools/stringsearchalgorithms/src/main/java/net/amygdalum/stringsearchalgorithms/search/chars/ShiftOr.java", "mask_start_position": 5185, "mask_end_position": 5186, "canonical_solution": "}", "pre_mask_code": "package net.amygdalum.stringsearchalgorithms.search.chars;\n\nimport static java.lang.Math.max;\nimport static java.util.Arrays.fill;\nimport net.amygdalum.stringsearchalgorithms.search.AbstractStringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinderOption;\nimport net.amygdalum.stringsearchalgorithms.search.StringMatch;\nimport net.amygdalum.util.io.CharProvider;\nimport net.amygdalum.util.map.CharLongMap;\nimport net.amygdalum.util.map.CharObjectMap;\nimport net.amygdalum.util.text.CharAlphabet;\nimport net.amygdalum.util.text.CharMapping;\n\n/**\n * An implementation of the String Search Algorithm Shift-Or (or Baeza-Yates–Gonnet).\n *\n * This algorithm takes a single pattern as input and generates a finder which can find this pattern in documents\n */\npublic class ShiftOr implements StringSearchAlgorithm {\n\n private int patternLength;\n\n private BitMapStates states;\n\n public ShiftOr(String pattern) {\n this(pattern, CharMapping.IDENTITY);\n }\n\n public ShiftOr(String pattern, CharMapping mapping) {\n this.patternLength = pattern.length();\n this.states = computeStates(pattern.toCharArray(), mapping);\n }\n\n private static BitMapStates computeStates(char[] pattern, CharMapping mapping) {\n CharAlphabet alphabet = CharAlphabet.ranged(pattern, mapping);\n int compactSize = max(256, pattern.length * 2);\n if (alphabet.getRange() < compactSize) {\n if (pattern.length > 64) {\n return new QuickMultiLongStates(pattern, alphabet, mapping);\n } else {\n return new QuickSingleLongStates(pattern, alphabet, mapping);\n }\n } else {\n if (pattern.length > 64) {\n return new SmartMultiLongStates(pattern, mapping);\n } else {\n return new SmartSingleLongStates(pattern, mapping);\n }\n }\n }\n\n @Override\n public int getPatternLength() {\n return patternLength;\n }\n\n @Override\n public StringFinder createFinder(CharProvider chars, StringFinderOption... options) {\n if (states.supportsSingle()) {\n return new LongFinder(chars, options);\n } else {\n return new MultiLongFinder(chars, options);\n }\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n private abstract class Finder extends AbstractStringFinder {\n\n protected final long finalstate;\n\n protected CharProvider chars;\n\n public Finder(CharProvider chars, StringFinderOption... options) {\n super(options);\n this.finalstate = ~(1l << ((patternLength - 1) % 64));\n this.chars = chars;\n }\n\n protected StringMatch createMatch() {\n long end = chars.current();\n long start = end - patternLength;\n String s = chars.slice(start, end);\n return new StringMatch(start, end, s);\n }\n }\n\n private class LongFinder extends Finder {\n\n private long state;\n\n public LongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = BitMapStates.ALLBITS;\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n state = BitMapStates.ALLBITS;\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long bits = states.single(nextChar);\n state = (state << 1) | bits;\n if ((state | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n }\n\n private class MultiLongFinder extends Finder {\n\n private long[] state;\n\n public MultiLongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = new long[((patternLength - 1) / 64) + 1];\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long[] bits = states.all(nextChar);\n state = next(state, bits);\n if ((state[0] | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n\n private long[] next(long[] state, long[] bits) {\n for (int i = 0; i < state.length; i++) {\n int j = i + 1;\n long leastBit = j < state.length ? state[j] >>> 63 : 0l;\n state[i] = (state[i] << 1 | leastBit) | bits[i];\n }\n return state;\n ", "post_mask_code": "\n }\n\n public static class Factory implements StringSearchAlgorithmFactory, SupportsCharClasses {\n\n private CharMapping mapping;\n\n @Override\n public void enableCharClasses(CharMapping mapping) {\n this.mapping = mapping;\n }\n\n @Override\n public StringSearchAlgorithm of(String pattern) {\n if (mapping == null) {\n return new ShiftOr(pattern);\n } else {\n return new ShiftOr(pattern, mapping);\n }\n }\n }\n\n public interface BitMapStates {\n\n public static final long ALLBITS = ~0l;\n\n boolean supportsSingle();\n\n long single(char c);\n\n long[] all(char c);\n }\n\n private abstract static class SingleLongBitMapStates implements BitMapStates {\n\n @Override\n public boolean supportsSingle() {\n return true;\n }\n\n @Override\n public long[] all(char c) {\n return new long[] { single(c) };\n }\n }\n\n private static class QuickSingleLongStates extends SingleLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[] characters;\n\n public QuickSingleLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n }\n\n private static long[] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[] characters = new long[max - min + 1];\n fill(characters, ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n characters[c - min] &= ~(1l << i);\n }\n }\n return characters;\n }\n\n @Override\n public long single(char c) {\n if (c < minChar || c > maxChar) {\n return ALLBITS;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartSingleLongStates extends SingleLongBitMapStates {\n\n private CharLongMap states;\n\n public SmartSingleLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharLongMap computeStates(char[] pattern, CharMapping mapping) {\n CharLongMap map = new CharLongMap(ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n long newState = map.get(c) & ~(1l << i);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long single(char c) {\n return states.get(c);\n }\n }\n\n private abstract static class MultiLongBitMapStates implements BitMapStates {\n\n public static long[] computeZero(int length) {\n long[] zero = new long[((length - 1) / 64) + 1];\n fill(zero, ALLBITS);\n return zero;\n }\n\n @Override\n public boolean supportsSingle() {\n return false;\n }\n\n @Override\n public long single(char c) {\n throw new UnsupportedOperationException();\n }\n }\n\n private static class QuickMultiLongStates extends MultiLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[][] characters;\n\n private long[] zero;\n\n public QuickMultiLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n this.zero = computeZero(pattern.length);\n }\n\n private static long[][] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[][] characters = new long[max - min + 1][];\n for (int c = min; c <= max; c++) {\n characters[c - min] = computeZero(pattern.length);\n }\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n characters[c - min][slot] &= ~(1l << offset);\n }\n }\n return characters;\n }\n\n @Override\n public long[] all(char c) {\n if (c < minChar || c > maxChar) {\n return zero;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartMultiLongStates extends MultiLongBitMapStates {\n\n private CharObjectMap states;\n\n public SmartMultiLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharObjectMap computeStates(char[] pattern, CharMapping mapping) {\n long[] zero = computeZero(pattern.length);\n CharObjectMap map = new CharObjectMap<>(zero);\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n long[] newState = map.get(c);\n if (newState == zero) {\n newState = computeZero(pattern.length);\n }\n newState[slot] &= ~(1l << offset);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long[] all(char c) {\n return states.get(c);\n }\n }\n}\n"} {"task_id": "Java_1897", "language": "Java", "task_type": "single_line", "source_file": "java/github/almondtools/stringsearchalgorithms/src/main/java/net/amygdalum/stringsearchalgorithms/search/chars/ShiftOr.java", "mask_start_position": 2989, "mask_end_position": 3018, "canonical_solution": "w StringMatch(start, end, s);", "pre_mask_code": "package net.amygdalum.stringsearchalgorithms.search.chars;\n\nimport static java.lang.Math.max;\nimport static java.util.Arrays.fill;\nimport net.amygdalum.stringsearchalgorithms.search.AbstractStringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinderOption;\nimport net.amygdalum.stringsearchalgorithms.search.StringMatch;\nimport net.amygdalum.util.io.CharProvider;\nimport net.amygdalum.util.map.CharLongMap;\nimport net.amygdalum.util.map.CharObjectMap;\nimport net.amygdalum.util.text.CharAlphabet;\nimport net.amygdalum.util.text.CharMapping;\n\n/**\n * An implementation of the String Search Algorithm Shift-Or (or Baeza-Yates–Gonnet).\n *\n * This algorithm takes a single pattern as input and generates a finder which can find this pattern in documents\n */\npublic class ShiftOr implements StringSearchAlgorithm {\n\n private int patternLength;\n\n private BitMapStates states;\n\n public ShiftOr(String pattern) {\n this(pattern, CharMapping.IDENTITY);\n }\n\n public ShiftOr(String pattern, CharMapping mapping) {\n this.patternLength = pattern.length();\n this.states = computeStates(pattern.toCharArray(), mapping);\n }\n\n private static BitMapStates computeStates(char[] pattern, CharMapping mapping) {\n CharAlphabet alphabet = CharAlphabet.ranged(pattern, mapping);\n int compactSize = max(256, pattern.length * 2);\n if (alphabet.getRange() < compactSize) {\n if (pattern.length > 64) {\n return new QuickMultiLongStates(pattern, alphabet, mapping);\n } else {\n return new QuickSingleLongStates(pattern, alphabet, mapping);\n }\n } else {\n if (pattern.length > 64) {\n return new SmartMultiLongStates(pattern, mapping);\n } else {\n return new SmartSingleLongStates(pattern, mapping);\n }\n }\n }\n\n @Override\n public int getPatternLength() {\n return patternLength;\n }\n\n @Override\n public StringFinder createFinder(CharProvider chars, StringFinderOption... options) {\n if (states.supportsSingle()) {\n return new LongFinder(chars, options);\n } else {\n return new MultiLongFinder(chars, options);\n }\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n private abstract class Finder extends AbstractStringFinder {\n\n protected final long finalstate;\n\n protected CharProvider chars;\n\n public Finder(CharProvider chars, StringFinderOption... options) {\n super(options);\n this.finalstate = ~(1l << ((patternLength - 1) % 64));\n this.chars = chars;\n }\n\n protected StringMatch createMatch() {\n long end = chars.current();\n long start = end - patternLength;\n String s = chars.slice(start, end);\n return ne", "post_mask_code": "\n }\n }\n\n private class LongFinder extends Finder {\n\n private long state;\n\n public LongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = BitMapStates.ALLBITS;\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n state = BitMapStates.ALLBITS;\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long bits = states.single(nextChar);\n state = (state << 1) | bits;\n if ((state | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n }\n\n private class MultiLongFinder extends Finder {\n\n private long[] state;\n\n public MultiLongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = new long[((patternLength - 1) / 64) + 1];\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long[] bits = states.all(nextChar);\n state = next(state, bits);\n if ((state[0] | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n\n private long[] next(long[] state, long[] bits) {\n for (int i = 0; i < state.length; i++) {\n int j = i + 1;\n long leastBit = j < state.length ? state[j] >>> 63 : 0l;\n state[i] = (state[i] << 1 | leastBit) | bits[i];\n }\n return state;\n }\n }\n\n public static class Factory implements StringSearchAlgorithmFactory, SupportsCharClasses {\n\n private CharMapping mapping;\n\n @Override\n public void enableCharClasses(CharMapping mapping) {\n this.mapping = mapping;\n }\n\n @Override\n public StringSearchAlgorithm of(String pattern) {\n if (mapping == null) {\n return new ShiftOr(pattern);\n } else {\n return new ShiftOr(pattern, mapping);\n }\n }\n }\n\n public interface BitMapStates {\n\n public static final long ALLBITS = ~0l;\n\n boolean supportsSingle();\n\n long single(char c);\n\n long[] all(char c);\n }\n\n private abstract static class SingleLongBitMapStates implements BitMapStates {\n\n @Override\n public boolean supportsSingle() {\n return true;\n }\n\n @Override\n public long[] all(char c) {\n return new long[] { single(c) };\n }\n }\n\n private static class QuickSingleLongStates extends SingleLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[] characters;\n\n public QuickSingleLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n }\n\n private static long[] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[] characters = new long[max - min + 1];\n fill(characters, ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n characters[c - min] &= ~(1l << i);\n }\n }\n return characters;\n }\n\n @Override\n public long single(char c) {\n if (c < minChar || c > maxChar) {\n return ALLBITS;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartSingleLongStates extends SingleLongBitMapStates {\n\n private CharLongMap states;\n\n public SmartSingleLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharLongMap computeStates(char[] pattern, CharMapping mapping) {\n CharLongMap map = new CharLongMap(ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n long newState = map.get(c) & ~(1l << i);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long single(char c) {\n return states.get(c);\n }\n }\n\n private abstract static class MultiLongBitMapStates implements BitMapStates {\n\n public static long[] computeZero(int length) {\n long[] zero = new long[((length - 1) / 64) + 1];\n fill(zero, ALLBITS);\n return zero;\n }\n\n @Override\n public boolean supportsSingle() {\n return false;\n }\n\n @Override\n public long single(char c) {\n throw new UnsupportedOperationException();\n }\n }\n\n private static class QuickMultiLongStates extends MultiLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[][] characters;\n\n private long[] zero;\n\n public QuickMultiLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n this.zero = computeZero(pattern.length);\n }\n\n private static long[][] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[][] characters = new long[max - min + 1][];\n for (int c = min; c <= max; c++) {\n characters[c - min] = computeZero(pattern.length);\n }\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n characters[c - min][slot] &= ~(1l << offset);\n }\n }\n return characters;\n }\n\n @Override\n public long[] all(char c) {\n if (c < minChar || c > maxChar) {\n return zero;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartMultiLongStates extends MultiLongBitMapStates {\n\n private CharObjectMap states;\n\n public SmartMultiLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharObjectMap computeStates(char[] pattern, CharMapping mapping) {\n long[] zero = computeZero(pattern.length);\n CharObjectMap map = new CharObjectMap<>(zero);\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n long[] newState = map.get(c);\n if (newState == zero) {\n newState = computeZero(pattern.length);\n }\n newState[slot] &= ~(1l << offset);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long[] all(char c) {\n return states.get(c);\n }\n }\n}\n"} {"task_id": "Java_1898", "language": "Java", "task_type": "if_statement", "source_file": "java/github/almondtools/stringsearchalgorithms/src/main/java/net/amygdalum/stringsearchalgorithms/search/chars/ShiftOr.java", "mask_start_position": 3353, "mask_end_position": 3428, "canonical_solution": "if (pos > chars.current()) {\n chars.move(pos);\n }", "pre_mask_code": "package net.amygdalum.stringsearchalgorithms.search.chars;\n\nimport static java.lang.Math.max;\nimport static java.util.Arrays.fill;\nimport net.amygdalum.stringsearchalgorithms.search.AbstractStringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinderOption;\nimport net.amygdalum.stringsearchalgorithms.search.StringMatch;\nimport net.amygdalum.util.io.CharProvider;\nimport net.amygdalum.util.map.CharLongMap;\nimport net.amygdalum.util.map.CharObjectMap;\nimport net.amygdalum.util.text.CharAlphabet;\nimport net.amygdalum.util.text.CharMapping;\n\n/**\n * An implementation of the String Search Algorithm Shift-Or (or Baeza-Yates–Gonnet).\n *\n * This algorithm takes a single pattern as input and generates a finder which can find this pattern in documents\n */\npublic class ShiftOr implements StringSearchAlgorithm {\n\n private int patternLength;\n\n private BitMapStates states;\n\n public ShiftOr(String pattern) {\n this(pattern, CharMapping.IDENTITY);\n }\n\n public ShiftOr(String pattern, CharMapping mapping) {\n this.patternLength = pattern.length();\n this.states = computeStates(pattern.toCharArray(), mapping);\n }\n\n private static BitMapStates computeStates(char[] pattern, CharMapping mapping) {\n CharAlphabet alphabet = CharAlphabet.ranged(pattern, mapping);\n int compactSize = max(256, pattern.length * 2);\n if (alphabet.getRange() < compactSize) {\n if (pattern.length > 64) {\n return new QuickMultiLongStates(pattern, alphabet, mapping);\n } else {\n return new QuickSingleLongStates(pattern, alphabet, mapping);\n }\n } else {\n if (pattern.length > 64) {\n return new SmartMultiLongStates(pattern, mapping);\n } else {\n return new SmartSingleLongStates(pattern, mapping);\n }\n }\n }\n\n @Override\n public int getPatternLength() {\n return patternLength;\n }\n\n @Override\n public StringFinder createFinder(CharProvider chars, StringFinderOption... options) {\n if (states.supportsSingle()) {\n return new LongFinder(chars, options);\n } else {\n return new MultiLongFinder(chars, options);\n }\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n private abstract class Finder extends AbstractStringFinder {\n\n protected final long finalstate;\n\n protected CharProvider chars;\n\n public Finder(CharProvider chars, StringFinderOption... options) {\n super(options);\n this.finalstate = ~(1l << ((patternLength - 1) % 64));\n this.chars = chars;\n }\n\n protected StringMatch createMatch() {\n long end = chars.current();\n long start = end - patternLength;\n String s = chars.slice(start, end);\n return new StringMatch(start, end, s);\n }\n }\n\n private class LongFinder extends Finder {\n\n private long state;\n\n public LongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = BitMapStates.ALLBITS;\n }\n\n @Override\n public void skipTo(long pos) {\n ", "post_mask_code": "\n state = BitMapStates.ALLBITS;\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long bits = states.single(nextChar);\n state = (state << 1) | bits;\n if ((state | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n }\n\n private class MultiLongFinder extends Finder {\n\n private long[] state;\n\n public MultiLongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = new long[((patternLength - 1) / 64) + 1];\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long[] bits = states.all(nextChar);\n state = next(state, bits);\n if ((state[0] | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n\n private long[] next(long[] state, long[] bits) {\n for (int i = 0; i < state.length; i++) {\n int j = i + 1;\n long leastBit = j < state.length ? state[j] >>> 63 : 0l;\n state[i] = (state[i] << 1 | leastBit) | bits[i];\n }\n return state;\n }\n }\n\n public static class Factory implements StringSearchAlgorithmFactory, SupportsCharClasses {\n\n private CharMapping mapping;\n\n @Override\n public void enableCharClasses(CharMapping mapping) {\n this.mapping = mapping;\n }\n\n @Override\n public StringSearchAlgorithm of(String pattern) {\n if (mapping == null) {\n return new ShiftOr(pattern);\n } else {\n return new ShiftOr(pattern, mapping);\n }\n }\n }\n\n public interface BitMapStates {\n\n public static final long ALLBITS = ~0l;\n\n boolean supportsSingle();\n\n long single(char c);\n\n long[] all(char c);\n }\n\n private abstract static class SingleLongBitMapStates implements BitMapStates {\n\n @Override\n public boolean supportsSingle() {\n return true;\n }\n\n @Override\n public long[] all(char c) {\n return new long[] { single(c) };\n }\n }\n\n private static class QuickSingleLongStates extends SingleLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[] characters;\n\n public QuickSingleLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n }\n\n private static long[] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[] characters = new long[max - min + 1];\n fill(characters, ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n characters[c - min] &= ~(1l << i);\n }\n }\n return characters;\n }\n\n @Override\n public long single(char c) {\n if (c < minChar || c > maxChar) {\n return ALLBITS;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartSingleLongStates extends SingleLongBitMapStates {\n\n private CharLongMap states;\n\n public SmartSingleLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharLongMap computeStates(char[] pattern, CharMapping mapping) {\n CharLongMap map = new CharLongMap(ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n long newState = map.get(c) & ~(1l << i);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long single(char c) {\n return states.get(c);\n }\n }\n\n private abstract static class MultiLongBitMapStates implements BitMapStates {\n\n public static long[] computeZero(int length) {\n long[] zero = new long[((length - 1) / 64) + 1];\n fill(zero, ALLBITS);\n return zero;\n }\n\n @Override\n public boolean supportsSingle() {\n return false;\n }\n\n @Override\n public long single(char c) {\n throw new UnsupportedOperationException();\n }\n }\n\n private static class QuickMultiLongStates extends MultiLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[][] characters;\n\n private long[] zero;\n\n public QuickMultiLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n this.zero = computeZero(pattern.length);\n }\n\n private static long[][] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[][] characters = new long[max - min + 1][];\n for (int c = min; c <= max; c++) {\n characters[c - min] = computeZero(pattern.length);\n }\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n characters[c - min][slot] &= ~(1l << offset);\n }\n }\n return characters;\n }\n\n @Override\n public long[] all(char c) {\n if (c < minChar || c > maxChar) {\n return zero;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartMultiLongStates extends MultiLongBitMapStates {\n\n private CharObjectMap states;\n\n public SmartMultiLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharObjectMap computeStates(char[] pattern, CharMapping mapping) {\n long[] zero = computeZero(pattern.length);\n CharObjectMap map = new CharObjectMap<>(zero);\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n long[] newState = map.get(c);\n if (newState == zero) {\n newState = computeZero(pattern.length);\n }\n newState[slot] &= ~(1l << offset);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long[] all(char c) {\n return states.get(c);\n }\n }\n}\n"} {"task_id": "Java_1899", "language": "Java", "task_type": "for_statement", "source_file": "java/github/almondtools/stringsearchalgorithms/src/main/java/net/amygdalum/stringsearchalgorithms/search/chars/ShiftOr.java", "mask_start_position": 7740, "mask_end_position": 7974, "canonical_solution": "for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n long newState = map.get(c) & ~(1l << i);\n map.put(c, newState);\n }\n }", "pre_mask_code": "package net.amygdalum.stringsearchalgorithms.search.chars;\n\nimport static java.lang.Math.max;\nimport static java.util.Arrays.fill;\nimport net.amygdalum.stringsearchalgorithms.search.AbstractStringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinderOption;\nimport net.amygdalum.stringsearchalgorithms.search.StringMatch;\nimport net.amygdalum.util.io.CharProvider;\nimport net.amygdalum.util.map.CharLongMap;\nimport net.amygdalum.util.map.CharObjectMap;\nimport net.amygdalum.util.text.CharAlphabet;\nimport net.amygdalum.util.text.CharMapping;\n\n/**\n * An implementation of the String Search Algorithm Shift-Or (or Baeza-Yates–Gonnet).\n *\n * This algorithm takes a single pattern as input and generates a finder which can find this pattern in documents\n */\npublic class ShiftOr implements StringSearchAlgorithm {\n\n private int patternLength;\n\n private BitMapStates states;\n\n public ShiftOr(String pattern) {\n this(pattern, CharMapping.IDENTITY);\n }\n\n public ShiftOr(String pattern, CharMapping mapping) {\n this.patternLength = pattern.length();\n this.states = computeStates(pattern.toCharArray(), mapping);\n }\n\n private static BitMapStates computeStates(char[] pattern, CharMapping mapping) {\n CharAlphabet alphabet = CharAlphabet.ranged(pattern, mapping);\n int compactSize = max(256, pattern.length * 2);\n if (alphabet.getRange() < compactSize) {\n if (pattern.length > 64) {\n return new QuickMultiLongStates(pattern, alphabet, mapping);\n } else {\n return new QuickSingleLongStates(pattern, alphabet, mapping);\n }\n } else {\n if (pattern.length > 64) {\n return new SmartMultiLongStates(pattern, mapping);\n } else {\n return new SmartSingleLongStates(pattern, mapping);\n }\n }\n }\n\n @Override\n public int getPatternLength() {\n return patternLength;\n }\n\n @Override\n public StringFinder createFinder(CharProvider chars, StringFinderOption... options) {\n if (states.supportsSingle()) {\n return new LongFinder(chars, options);\n } else {\n return new MultiLongFinder(chars, options);\n }\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n private abstract class Finder extends AbstractStringFinder {\n\n protected final long finalstate;\n\n protected CharProvider chars;\n\n public Finder(CharProvider chars, StringFinderOption... options) {\n super(options);\n this.finalstate = ~(1l << ((patternLength - 1) % 64));\n this.chars = chars;\n }\n\n protected StringMatch createMatch() {\n long end = chars.current();\n long start = end - patternLength;\n String s = chars.slice(start, end);\n return new StringMatch(start, end, s);\n }\n }\n\n private class LongFinder extends Finder {\n\n private long state;\n\n public LongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = BitMapStates.ALLBITS;\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n state = BitMapStates.ALLBITS;\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long bits = states.single(nextChar);\n state = (state << 1) | bits;\n if ((state | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n }\n\n private class MultiLongFinder extends Finder {\n\n private long[] state;\n\n public MultiLongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = new long[((patternLength - 1) / 64) + 1];\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long[] bits = states.all(nextChar);\n state = next(state, bits);\n if ((state[0] | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n\n private long[] next(long[] state, long[] bits) {\n for (int i = 0; i < state.length; i++) {\n int j = i + 1;\n long leastBit = j < state.length ? state[j] >>> 63 : 0l;\n state[i] = (state[i] << 1 | leastBit) | bits[i];\n }\n return state;\n }\n }\n\n public static class Factory implements StringSearchAlgorithmFactory, SupportsCharClasses {\n\n private CharMapping mapping;\n\n @Override\n public void enableCharClasses(CharMapping mapping) {\n this.mapping = mapping;\n }\n\n @Override\n public StringSearchAlgorithm of(String pattern) {\n if (mapping == null) {\n return new ShiftOr(pattern);\n } else {\n return new ShiftOr(pattern, mapping);\n }\n }\n }\n\n public interface BitMapStates {\n\n public static final long ALLBITS = ~0l;\n\n boolean supportsSingle();\n\n long single(char c);\n\n long[] all(char c);\n }\n\n private abstract static class SingleLongBitMapStates implements BitMapStates {\n\n @Override\n public boolean supportsSingle() {\n return true;\n }\n\n @Override\n public long[] all(char c) {\n return new long[] { single(c) };\n }\n }\n\n private static class QuickSingleLongStates extends SingleLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[] characters;\n\n public QuickSingleLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n }\n\n private static long[] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[] characters = new long[max - min + 1];\n fill(characters, ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n characters[c - min] &= ~(1l << i);\n }\n }\n return characters;\n }\n\n @Override\n public long single(char c) {\n if (c < minChar || c > maxChar) {\n return ALLBITS;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartSingleLongStates extends SingleLongBitMapStates {\n\n private CharLongMap states;\n\n public SmartSingleLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharLongMap computeStates(char[] pattern, CharMapping mapping) {\n CharLongMap map = new CharLongMap(ALLBITS);\n ", "post_mask_code": "\n return map;\n }\n\n @Override\n public long single(char c) {\n return states.get(c);\n }\n }\n\n private abstract static class MultiLongBitMapStates implements BitMapStates {\n\n public static long[] computeZero(int length) {\n long[] zero = new long[((length - 1) / 64) + 1];\n fill(zero, ALLBITS);\n return zero;\n }\n\n @Override\n public boolean supportsSingle() {\n return false;\n }\n\n @Override\n public long single(char c) {\n throw new UnsupportedOperationException();\n }\n }\n\n private static class QuickMultiLongStates extends MultiLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[][] characters;\n\n private long[] zero;\n\n public QuickMultiLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n this.zero = computeZero(pattern.length);\n }\n\n private static long[][] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[][] characters = new long[max - min + 1][];\n for (int c = min; c <= max; c++) {\n characters[c - min] = computeZero(pattern.length);\n }\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n characters[c - min][slot] &= ~(1l << offset);\n }\n }\n return characters;\n }\n\n @Override\n public long[] all(char c) {\n if (c < minChar || c > maxChar) {\n return zero;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartMultiLongStates extends MultiLongBitMapStates {\n\n private CharObjectMap states;\n\n public SmartMultiLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharObjectMap computeStates(char[] pattern, CharMapping mapping) {\n long[] zero = computeZero(pattern.length);\n CharObjectMap map = new CharObjectMap<>(zero);\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n long[] newState = map.get(c);\n if (newState == zero) {\n newState = computeZero(pattern.length);\n }\n newState[slot] &= ~(1l << offset);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long[] all(char c) {\n return states.get(c);\n }\n }\n}\n"} {"task_id": "Java_1900", "language": "Java", "task_type": "while_statement", "source_file": "java/github/almondtools/stringsearchalgorithms/src/main/java/net/amygdalum/stringsearchalgorithms/search/chars/ShiftOr.java", "mask_start_position": 4508, "mask_end_position": 4821, "canonical_solution": "while (!chars.finished()) {\n char nextChar = chars.next();\n long[] bits = states.all(nextChar);\n state = next(state, bits);\n if ((state[0] | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }", "pre_mask_code": "package net.amygdalum.stringsearchalgorithms.search.chars;\n\nimport static java.lang.Math.max;\nimport static java.util.Arrays.fill;\nimport net.amygdalum.stringsearchalgorithms.search.AbstractStringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinder;\nimport net.amygdalum.stringsearchalgorithms.search.StringFinderOption;\nimport net.amygdalum.stringsearchalgorithms.search.StringMatch;\nimport net.amygdalum.util.io.CharProvider;\nimport net.amygdalum.util.map.CharLongMap;\nimport net.amygdalum.util.map.CharObjectMap;\nimport net.amygdalum.util.text.CharAlphabet;\nimport net.amygdalum.util.text.CharMapping;\n\n/**\n * An implementation of the String Search Algorithm Shift-Or (or Baeza-Yates–Gonnet).\n *\n * This algorithm takes a single pattern as input and generates a finder which can find this pattern in documents\n */\npublic class ShiftOr implements StringSearchAlgorithm {\n\n private int patternLength;\n\n private BitMapStates states;\n\n public ShiftOr(String pattern) {\n this(pattern, CharMapping.IDENTITY);\n }\n\n public ShiftOr(String pattern, CharMapping mapping) {\n this.patternLength = pattern.length();\n this.states = computeStates(pattern.toCharArray(), mapping);\n }\n\n private static BitMapStates computeStates(char[] pattern, CharMapping mapping) {\n CharAlphabet alphabet = CharAlphabet.ranged(pattern, mapping);\n int compactSize = max(256, pattern.length * 2);\n if (alphabet.getRange() < compactSize) {\n if (pattern.length > 64) {\n return new QuickMultiLongStates(pattern, alphabet, mapping);\n } else {\n return new QuickSingleLongStates(pattern, alphabet, mapping);\n }\n } else {\n if (pattern.length > 64) {\n return new SmartMultiLongStates(pattern, mapping);\n } else {\n return new SmartSingleLongStates(pattern, mapping);\n }\n }\n }\n\n @Override\n public int getPatternLength() {\n return patternLength;\n }\n\n @Override\n public StringFinder createFinder(CharProvider chars, StringFinderOption... options) {\n if (states.supportsSingle()) {\n return new LongFinder(chars, options);\n } else {\n return new MultiLongFinder(chars, options);\n }\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n private abstract class Finder extends AbstractStringFinder {\n\n protected final long finalstate;\n\n protected CharProvider chars;\n\n public Finder(CharProvider chars, StringFinderOption... options) {\n super(options);\n this.finalstate = ~(1l << ((patternLength - 1) % 64));\n this.chars = chars;\n }\n\n protected StringMatch createMatch() {\n long end = chars.current();\n long start = end - patternLength;\n String s = chars.slice(start, end);\n return new StringMatch(start, end, s);\n }\n }\n\n private class LongFinder extends Finder {\n\n private long state;\n\n public LongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = BitMapStates.ALLBITS;\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n state = BitMapStates.ALLBITS;\n }\n\n @Override\n public StringMatch findNext() {\n while (!chars.finished()) {\n char nextChar = chars.next();\n long bits = states.single(nextChar);\n state = (state << 1) | bits;\n if ((state | finalstate) != BitMapStates.ALLBITS) {\n return createMatch();\n }\n }\n return null;\n }\n }\n\n private class MultiLongFinder extends Finder {\n\n private long[] state;\n\n public MultiLongFinder(CharProvider chars, StringFinderOption... options) {\n super(chars, options);\n this.state = new long[((patternLength - 1) / 64) + 1];\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public void skipTo(long pos) {\n if (pos > chars.current()) {\n chars.move(pos);\n }\n fill(state, BitMapStates.ALLBITS);\n }\n\n @Override\n public StringMatch findNext() {\n ", "post_mask_code": "\n return null;\n }\n\n private long[] next(long[] state, long[] bits) {\n for (int i = 0; i < state.length; i++) {\n int j = i + 1;\n long leastBit = j < state.length ? state[j] >>> 63 : 0l;\n state[i] = (state[i] << 1 | leastBit) | bits[i];\n }\n return state;\n }\n }\n\n public static class Factory implements StringSearchAlgorithmFactory, SupportsCharClasses {\n\n private CharMapping mapping;\n\n @Override\n public void enableCharClasses(CharMapping mapping) {\n this.mapping = mapping;\n }\n\n @Override\n public StringSearchAlgorithm of(String pattern) {\n if (mapping == null) {\n return new ShiftOr(pattern);\n } else {\n return new ShiftOr(pattern, mapping);\n }\n }\n }\n\n public interface BitMapStates {\n\n public static final long ALLBITS = ~0l;\n\n boolean supportsSingle();\n\n long single(char c);\n\n long[] all(char c);\n }\n\n private abstract static class SingleLongBitMapStates implements BitMapStates {\n\n @Override\n public boolean supportsSingle() {\n return true;\n }\n\n @Override\n public long[] all(char c) {\n return new long[] { single(c) };\n }\n }\n\n private static class QuickSingleLongStates extends SingleLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[] characters;\n\n public QuickSingleLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n }\n\n private static long[] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[] characters = new long[max - min + 1];\n fill(characters, ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n characters[c - min] &= ~(1l << i);\n }\n }\n return characters;\n }\n\n @Override\n public long single(char c) {\n if (c < minChar || c > maxChar) {\n return ALLBITS;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartSingleLongStates extends SingleLongBitMapStates {\n\n private CharLongMap states;\n\n public SmartSingleLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharLongMap computeStates(char[] pattern, CharMapping mapping) {\n CharLongMap map = new CharLongMap(ALLBITS);\n for (int i = 0; i < pattern.length; i++) {\n for (char c : mapping.map(pattern[i])) {\n long newState = map.get(c) & ~(1l << i);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long single(char c) {\n return states.get(c);\n }\n }\n\n private abstract static class MultiLongBitMapStates implements BitMapStates {\n\n public static long[] computeZero(int length) {\n long[] zero = new long[((length - 1) / 64) + 1];\n fill(zero, ALLBITS);\n return zero;\n }\n\n @Override\n public boolean supportsSingle() {\n return false;\n }\n\n @Override\n public long single(char c) {\n throw new UnsupportedOperationException();\n }\n }\n\n private static class QuickMultiLongStates extends MultiLongBitMapStates {\n\n private char minChar;\n\n private char maxChar;\n\n private long[][] characters;\n\n private long[] zero;\n\n public QuickMultiLongStates(char[] pattern, CharAlphabet alphabet, CharMapping mapping) {\n this.minChar = alphabet.minChar();\n this.maxChar = alphabet.maxChar();\n this.characters = computeStates(pattern, mapping, this.minChar, this.maxChar);\n this.zero = computeZero(pattern.length);\n }\n\n private static long[][] computeStates(char[] pattern, CharMapping mapping, char min, char max) {\n long[][] characters = new long[max - min + 1][];\n for (int c = min; c <= max; c++) {\n characters[c - min] = computeZero(pattern.length);\n }\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n characters[c - min][slot] &= ~(1l << offset);\n }\n }\n return characters;\n }\n\n @Override\n public long[] all(char c) {\n if (c < minChar || c > maxChar) {\n return zero;\n }\n return characters[c - minChar];\n }\n }\n\n private static class SmartMultiLongStates extends MultiLongBitMapStates {\n\n private CharObjectMap states;\n\n public SmartMultiLongStates(char[] pattern, CharMapping mapping) {\n this.states = computeStates(pattern, mapping);\n }\n\n private static CharObjectMap computeStates(char[] pattern, CharMapping mapping) {\n long[] zero = computeZero(pattern.length);\n CharObjectMap map = new CharObjectMap<>(zero);\n for (int i = 0; i < pattern.length; i++) {\n int slot = ((pattern.length - 1) / 64) - i / 64;\n int offset = i % 64;\n for (char c : mapping.map(pattern[i])) {\n long[] newState = map.get(c);\n if (newState == zero) {\n newState = computeZero(pattern.length);\n }\n newState[slot] &= ~(1l << offset);\n map.put(c, newState);\n }\n }\n return map;\n }\n\n @Override\n public long[] all(char c) {\n return states.get(c);\n }\n }\n}\n"} {"task_id": "Java_1901", "language": "Java", "task_type": "method_signature", "source_file": "java/github/liuweiran900217/CloudCrypto/src/main/java/cn/edu/buaa/crypto/encryption/hibbe/llw16a/serparams/HIBBELLW16aSecretKeySerParameter.java", "mask_start_position": 1736, "mask_end_position": 1769, "canonical_solution": "public String getIdAt(int index) ", "pre_mask_code": "package cn.edu.buaa.crypto.encryption.hibbe.llw16a.serparams;\n\nimport cn.edu.buaa.crypto.algebra.serparams.PairingKeySerParameter;\nimport cn.edu.buaa.crypto.utils.PairingUtils;\nimport it.unisa.dia.gas.jpbc.Element;\nimport it.unisa.dia.gas.jpbc.Pairing;\nimport it.unisa.dia.gas.jpbc.PairingParameters;\nimport it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;\nimport it.unisa.dia.gas.plaf.jpbc.util.ElementUtils;\nimport java.util.Arrays;\n\n/**\n * Created by Weiran Liu on 2016/5/17.\n *\n * Liu-Liu-Wu prime-order HIBBE secret key parameter.\n */\npublic class HIBBELLW16aSecretKeySerParameter extends PairingKeySerParameter {\n\n private final String[] ids;\n\n private transient Element[] elementIds;\n\n private final byte[][] byteArraysElementIds;\n\n private transient Element a0;\n\n private final byte[] byteArrayA0;\n\n private transient Element a1;\n\n private final byte[] byteArrayA1;\n\n private transient Element[] bs;\n\n private final byte[][] byteArraysBs;\n\n public HIBBELLW16aSecretKeySerParameter(PairingParameters pairingParameters, String[] ids, Element[] elementIds, Element a0, Element a1, Element[] bs) {\n super(true, pairingParameters);\n this.a0 = a0.getImmutable();\n this.byteArrayA0 = this.a0.toBytes();\n this.a1 = a1.getImmutable();\n this.byteArrayA1 = this.a1.toBytes();\n this.bs = ElementUtils.cloneImmutable(bs);\n this.byteArraysBs = PairingUtils.GetElementArrayBytes(this.bs);\n this.ids = new String[ids.length];\n System.arraycopy(ids, 0, this.ids, 0, this.ids.length);\n this.elementIds = ElementUtils.cloneImmutable(elementIds);\n this.byteArraysElementIds = PairingUtils.GetElementArrayBytes(this.elementIds);\n }\n\n ", "post_mask_code": "{\n return this.ids[index];\n }\n\n public String[] getIds() {\n return this.ids;\n }\n\n public Element getElementIdAt(int index) {\n return this.elementIds[index].duplicate();\n }\n\n public Element[] getElementIds() {\n return this.elementIds;\n }\n\n public Element getA0() {\n return this.a0.duplicate();\n }\n\n public Element getA1() {\n return this.a1.duplicate();\n }\n\n public Element getBsAt(int index) {\n return this.bs[index].duplicate();\n }\n\n public Element[] getBs() {\n return this.bs;\n }\n\n @Override\n public boolean equals(Object anOjbect) {\n if (this == anOjbect) {\n return true;\n }\n if (anOjbect instanceof HIBBELLW16aSecretKeySerParameter) {\n HIBBELLW16aSecretKeySerParameter that = (HIBBELLW16aSecretKeySerParameter) anOjbect;\n // Compare ids\n if (!Arrays.equals(this.ids, that.getIds())) {\n return false;\n }\n // Compare elementIds\n if (!PairingUtils.isEqualElementArray(this.elementIds, that.getElementIds())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysElementIds, that.byteArraysElementIds)) {\n return false;\n }\n // Compare a0\n if (!PairingUtils.isEqualElement(this.a0, that.getA0())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA0, that.byteArrayA0)) {\n return false;\n }\n // Compare a1\n if (!PairingUtils.isEqualElement(this.a1, that.getA1())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA1, that.byteArrayA1)) {\n return false;\n }\n // Compare bs\n if (!PairingUtils.isEqualElementArray(this.bs, that.getBs())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysBs, that.byteArraysBs)) {\n return false;\n }\n // Compare Pairing Parameters\n return this.getParameters().toString().equals(that.getParameters().toString());\n }\n return false;\n }\n\n private void readObject(java.io.ObjectInputStream objectInputStream) throws java.io.IOException, ClassNotFoundException {\n objectInputStream.defaultReadObject();\n Pairing pairing = PairingFactory.getPairing(this.getParameters());\n this.elementIds = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysElementIds, PairingUtils.PairingGroupType.Zr);\n this.a0 = pairing.getG1().newElementFromBytes(this.byteArrayA0).getImmutable();\n this.a1 = pairing.getG1().newElementFromBytes(this.byteArrayA1).getImmutable();\n this.bs = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysBs, PairingUtils.PairingGroupType.G1);\n }\n}\n"} {"task_id": "Java_1902", "language": "Java", "task_type": "method_body", "source_file": "java/github/liuweiran900217/CloudCrypto/src/main/java/cn/edu/buaa/crypto/encryption/hibbe/llw16a/serparams/HIBBELLW16aSecretKeySerParameter.java", "mask_start_position": 2319, "mask_end_position": 2350, "canonical_solution": "{\n return this.bs;\n }", "pre_mask_code": "package cn.edu.buaa.crypto.encryption.hibbe.llw16a.serparams;\n\nimport cn.edu.buaa.crypto.algebra.serparams.PairingKeySerParameter;\nimport cn.edu.buaa.crypto.utils.PairingUtils;\nimport it.unisa.dia.gas.jpbc.Element;\nimport it.unisa.dia.gas.jpbc.Pairing;\nimport it.unisa.dia.gas.jpbc.PairingParameters;\nimport it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;\nimport it.unisa.dia.gas.plaf.jpbc.util.ElementUtils;\nimport java.util.Arrays;\n\n/**\n * Created by Weiran Liu on 2016/5/17.\n *\n * Liu-Liu-Wu prime-order HIBBE secret key parameter.\n */\npublic class HIBBELLW16aSecretKeySerParameter extends PairingKeySerParameter {\n\n private final String[] ids;\n\n private transient Element[] elementIds;\n\n private final byte[][] byteArraysElementIds;\n\n private transient Element a0;\n\n private final byte[] byteArrayA0;\n\n private transient Element a1;\n\n private final byte[] byteArrayA1;\n\n private transient Element[] bs;\n\n private final byte[][] byteArraysBs;\n\n public HIBBELLW16aSecretKeySerParameter(PairingParameters pairingParameters, String[] ids, Element[] elementIds, Element a0, Element a1, Element[] bs) {\n super(true, pairingParameters);\n this.a0 = a0.getImmutable();\n this.byteArrayA0 = this.a0.toBytes();\n this.a1 = a1.getImmutable();\n this.byteArrayA1 = this.a1.toBytes();\n this.bs = ElementUtils.cloneImmutable(bs);\n this.byteArraysBs = PairingUtils.GetElementArrayBytes(this.bs);\n this.ids = new String[ids.length];\n System.arraycopy(ids, 0, this.ids, 0, this.ids.length);\n this.elementIds = ElementUtils.cloneImmutable(elementIds);\n this.byteArraysElementIds = PairingUtils.GetElementArrayBytes(this.elementIds);\n }\n\n public String getIdAt(int index) {\n return this.ids[index];\n }\n\n public String[] getIds() {\n return this.ids;\n }\n\n public Element getElementIdAt(int index) {\n return this.elementIds[index].duplicate();\n }\n\n public Element[] getElementIds() {\n return this.elementIds;\n }\n\n public Element getA0() {\n return this.a0.duplicate();\n }\n\n public Element getA1() {\n return this.a1.duplicate();\n }\n\n public Element getBsAt(int index) {\n return this.bs[index].duplicate();\n }\n\n public Element[] getBs() ", "post_mask_code": "\n\n @Override\n public boolean equals(Object anOjbect) {\n if (this == anOjbect) {\n return true;\n }\n if (anOjbect instanceof HIBBELLW16aSecretKeySerParameter) {\n HIBBELLW16aSecretKeySerParameter that = (HIBBELLW16aSecretKeySerParameter) anOjbect;\n // Compare ids\n if (!Arrays.equals(this.ids, that.getIds())) {\n return false;\n }\n // Compare elementIds\n if (!PairingUtils.isEqualElementArray(this.elementIds, that.getElementIds())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysElementIds, that.byteArraysElementIds)) {\n return false;\n }\n // Compare a0\n if (!PairingUtils.isEqualElement(this.a0, that.getA0())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA0, that.byteArrayA0)) {\n return false;\n }\n // Compare a1\n if (!PairingUtils.isEqualElement(this.a1, that.getA1())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA1, that.byteArrayA1)) {\n return false;\n }\n // Compare bs\n if (!PairingUtils.isEqualElementArray(this.bs, that.getBs())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysBs, that.byteArraysBs)) {\n return false;\n }\n // Compare Pairing Parameters\n return this.getParameters().toString().equals(that.getParameters().toString());\n }\n return false;\n }\n\n private void readObject(java.io.ObjectInputStream objectInputStream) throws java.io.IOException, ClassNotFoundException {\n objectInputStream.defaultReadObject();\n Pairing pairing = PairingFactory.getPairing(this.getParameters());\n this.elementIds = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysElementIds, PairingUtils.PairingGroupType.Zr);\n this.a0 = pairing.getG1().newElementFromBytes(this.byteArrayA0).getImmutable();\n this.a1 = pairing.getG1().newElementFromBytes(this.byteArrayA1).getImmutable();\n this.bs = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysBs, PairingUtils.PairingGroupType.G1);\n }\n}\n"} {"task_id": "Java_1903", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/liuweiran900217/CloudCrypto/src/main/java/cn/edu/buaa/crypto/encryption/hibbe/llw16a/serparams/HIBBELLW16aSecretKeySerParameter.java", "mask_start_position": 4179, "mask_end_position": 4301, "canonical_solution": "\n objectInputStream.defaultReadObject();\n Pairing pairing = PairingFactory.getPairing(this.getParameters());", "pre_mask_code": "package cn.edu.buaa.crypto.encryption.hibbe.llw16a.serparams;\n\nimport cn.edu.buaa.crypto.algebra.serparams.PairingKeySerParameter;\nimport cn.edu.buaa.crypto.utils.PairingUtils;\nimport it.unisa.dia.gas.jpbc.Element;\nimport it.unisa.dia.gas.jpbc.Pairing;\nimport it.unisa.dia.gas.jpbc.PairingParameters;\nimport it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;\nimport it.unisa.dia.gas.plaf.jpbc.util.ElementUtils;\nimport java.util.Arrays;\n\n/**\n * Created by Weiran Liu on 2016/5/17.\n *\n * Liu-Liu-Wu prime-order HIBBE secret key parameter.\n */\npublic class HIBBELLW16aSecretKeySerParameter extends PairingKeySerParameter {\n\n private final String[] ids;\n\n private transient Element[] elementIds;\n\n private final byte[][] byteArraysElementIds;\n\n private transient Element a0;\n\n private final byte[] byteArrayA0;\n\n private transient Element a1;\n\n private final byte[] byteArrayA1;\n\n private transient Element[] bs;\n\n private final byte[][] byteArraysBs;\n\n public HIBBELLW16aSecretKeySerParameter(PairingParameters pairingParameters, String[] ids, Element[] elementIds, Element a0, Element a1, Element[] bs) {\n super(true, pairingParameters);\n this.a0 = a0.getImmutable();\n this.byteArrayA0 = this.a0.toBytes();\n this.a1 = a1.getImmutable();\n this.byteArrayA1 = this.a1.toBytes();\n this.bs = ElementUtils.cloneImmutable(bs);\n this.byteArraysBs = PairingUtils.GetElementArrayBytes(this.bs);\n this.ids = new String[ids.length];\n System.arraycopy(ids, 0, this.ids, 0, this.ids.length);\n this.elementIds = ElementUtils.cloneImmutable(elementIds);\n this.byteArraysElementIds = PairingUtils.GetElementArrayBytes(this.elementIds);\n }\n\n public String getIdAt(int index) {\n return this.ids[index];\n }\n\n public String[] getIds() {\n return this.ids;\n }\n\n public Element getElementIdAt(int index) {\n return this.elementIds[index].duplicate();\n }\n\n public Element[] getElementIds() {\n return this.elementIds;\n }\n\n public Element getA0() {\n return this.a0.duplicate();\n }\n\n public Element getA1() {\n return this.a1.duplicate();\n }\n\n public Element getBsAt(int index) {\n return this.bs[index].duplicate();\n }\n\n public Element[] getBs() {\n return this.bs;\n }\n\n @Override\n public boolean equals(Object anOjbect) {\n if (this == anOjbect) {\n return true;\n }\n if (anOjbect instanceof HIBBELLW16aSecretKeySerParameter) {\n HIBBELLW16aSecretKeySerParameter that = (HIBBELLW16aSecretKeySerParameter) anOjbect;\n // Compare ids\n if (!Arrays.equals(this.ids, that.getIds())) {\n return false;\n }\n // Compare elementIds\n if (!PairingUtils.isEqualElementArray(this.elementIds, that.getElementIds())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysElementIds, that.byteArraysElementIds)) {\n return false;\n }\n // Compare a0\n if (!PairingUtils.isEqualElement(this.a0, that.getA0())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA0, that.byteArrayA0)) {\n return false;\n }\n // Compare a1\n if (!PairingUtils.isEqualElement(this.a1, that.getA1())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA1, that.byteArrayA1)) {\n return false;\n }\n // Compare bs\n if (!PairingUtils.isEqualElementArray(this.bs, that.getBs())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysBs, that.byteArraysBs)) {\n return false;\n }\n // Compare Pairing Parameters\n return this.getParameters().toString().equals(that.getParameters().toString());\n }\n return false;\n }\n\n private void readObject(java.io.ObjectInputStream objectInputStream) throws java.io.IOException, ClassNotFoundException {", "post_mask_code": "\n this.elementIds = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysElementIds, PairingUtils.PairingGroupType.Zr);\n this.a0 = pairing.getG1().newElementFromBytes(this.byteArrayA0).getImmutable();\n this.a1 = pairing.getG1().newElementFromBytes(this.byteArrayA1).getImmutable();\n this.bs = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysBs, PairingUtils.PairingGroupType.G1);\n }\n}\n"} {"task_id": "Java_1904", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/liuweiran900217/CloudCrypto/src/main/java/cn/edu/buaa/crypto/encryption/hibbe/llw16a/serparams/HIBBELLW16aSecretKeySerParameter.java", "mask_start_position": 4310, "mask_end_position": 4524, "canonical_solution": "this.elementIds = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysElementIds, PairingUtils.PairingGroupType.Zr);\n this.a0 = pairing.getG1().newElementFromBytes(this.byteArrayA0).getImmutable();", "pre_mask_code": "package cn.edu.buaa.crypto.encryption.hibbe.llw16a.serparams;\n\nimport cn.edu.buaa.crypto.algebra.serparams.PairingKeySerParameter;\nimport cn.edu.buaa.crypto.utils.PairingUtils;\nimport it.unisa.dia.gas.jpbc.Element;\nimport it.unisa.dia.gas.jpbc.Pairing;\nimport it.unisa.dia.gas.jpbc.PairingParameters;\nimport it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;\nimport it.unisa.dia.gas.plaf.jpbc.util.ElementUtils;\nimport java.util.Arrays;\n\n/**\n * Created by Weiran Liu on 2016/5/17.\n *\n * Liu-Liu-Wu prime-order HIBBE secret key parameter.\n */\npublic class HIBBELLW16aSecretKeySerParameter extends PairingKeySerParameter {\n\n private final String[] ids;\n\n private transient Element[] elementIds;\n\n private final byte[][] byteArraysElementIds;\n\n private transient Element a0;\n\n private final byte[] byteArrayA0;\n\n private transient Element a1;\n\n private final byte[] byteArrayA1;\n\n private transient Element[] bs;\n\n private final byte[][] byteArraysBs;\n\n public HIBBELLW16aSecretKeySerParameter(PairingParameters pairingParameters, String[] ids, Element[] elementIds, Element a0, Element a1, Element[] bs) {\n super(true, pairingParameters);\n this.a0 = a0.getImmutable();\n this.byteArrayA0 = this.a0.toBytes();\n this.a1 = a1.getImmutable();\n this.byteArrayA1 = this.a1.toBytes();\n this.bs = ElementUtils.cloneImmutable(bs);\n this.byteArraysBs = PairingUtils.GetElementArrayBytes(this.bs);\n this.ids = new String[ids.length];\n System.arraycopy(ids, 0, this.ids, 0, this.ids.length);\n this.elementIds = ElementUtils.cloneImmutable(elementIds);\n this.byteArraysElementIds = PairingUtils.GetElementArrayBytes(this.elementIds);\n }\n\n public String getIdAt(int index) {\n return this.ids[index];\n }\n\n public String[] getIds() {\n return this.ids;\n }\n\n public Element getElementIdAt(int index) {\n return this.elementIds[index].duplicate();\n }\n\n public Element[] getElementIds() {\n return this.elementIds;\n }\n\n public Element getA0() {\n return this.a0.duplicate();\n }\n\n public Element getA1() {\n return this.a1.duplicate();\n }\n\n public Element getBsAt(int index) {\n return this.bs[index].duplicate();\n }\n\n public Element[] getBs() {\n return this.bs;\n }\n\n @Override\n public boolean equals(Object anOjbect) {\n if (this == anOjbect) {\n return true;\n }\n if (anOjbect instanceof HIBBELLW16aSecretKeySerParameter) {\n HIBBELLW16aSecretKeySerParameter that = (HIBBELLW16aSecretKeySerParameter) anOjbect;\n // Compare ids\n if (!Arrays.equals(this.ids, that.getIds())) {\n return false;\n }\n // Compare elementIds\n if (!PairingUtils.isEqualElementArray(this.elementIds, that.getElementIds())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysElementIds, that.byteArraysElementIds)) {\n return false;\n }\n // Compare a0\n if (!PairingUtils.isEqualElement(this.a0, that.getA0())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA0, that.byteArrayA0)) {\n return false;\n }\n // Compare a1\n if (!PairingUtils.isEqualElement(this.a1, that.getA1())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA1, that.byteArrayA1)) {\n return false;\n }\n // Compare bs\n if (!PairingUtils.isEqualElementArray(this.bs, that.getBs())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysBs, that.byteArraysBs)) {\n return false;\n }\n // Compare Pairing Parameters\n return this.getParameters().toString().equals(that.getParameters().toString());\n }\n return false;\n }\n\n private void readObject(java.io.ObjectInputStream objectInputStream) throws java.io.IOException, ClassNotFoundException {\n objectInputStream.defaultReadObject();\n Pairing pairing = PairingFactory.getPairing(this.getParameters());\n ", "post_mask_code": "\n this.a1 = pairing.getG1().newElementFromBytes(this.byteArrayA1).getImmutable();\n this.bs = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysBs, PairingUtils.PairingGroupType.G1);\n }\n}\n"} {"task_id": "Java_1905", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/liuweiran900217/CloudCrypto/src/main/java/cn/edu/buaa/crypto/encryption/hibbe/llw16a/serparams/HIBBELLW16aSecretKeySerParameter.java", "mask_start_position": 4533, "mask_end_position": 4737, "canonical_solution": "this.a1 = pairing.getG1().newElementFromBytes(this.byteArrayA1).getImmutable();\n this.bs = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysBs, PairingUtils.PairingGroupType.G1);\n }", "pre_mask_code": "package cn.edu.buaa.crypto.encryption.hibbe.llw16a.serparams;\n\nimport cn.edu.buaa.crypto.algebra.serparams.PairingKeySerParameter;\nimport cn.edu.buaa.crypto.utils.PairingUtils;\nimport it.unisa.dia.gas.jpbc.Element;\nimport it.unisa.dia.gas.jpbc.Pairing;\nimport it.unisa.dia.gas.jpbc.PairingParameters;\nimport it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;\nimport it.unisa.dia.gas.plaf.jpbc.util.ElementUtils;\nimport java.util.Arrays;\n\n/**\n * Created by Weiran Liu on 2016/5/17.\n *\n * Liu-Liu-Wu prime-order HIBBE secret key parameter.\n */\npublic class HIBBELLW16aSecretKeySerParameter extends PairingKeySerParameter {\n\n private final String[] ids;\n\n private transient Element[] elementIds;\n\n private final byte[][] byteArraysElementIds;\n\n private transient Element a0;\n\n private final byte[] byteArrayA0;\n\n private transient Element a1;\n\n private final byte[] byteArrayA1;\n\n private transient Element[] bs;\n\n private final byte[][] byteArraysBs;\n\n public HIBBELLW16aSecretKeySerParameter(PairingParameters pairingParameters, String[] ids, Element[] elementIds, Element a0, Element a1, Element[] bs) {\n super(true, pairingParameters);\n this.a0 = a0.getImmutable();\n this.byteArrayA0 = this.a0.toBytes();\n this.a1 = a1.getImmutable();\n this.byteArrayA1 = this.a1.toBytes();\n this.bs = ElementUtils.cloneImmutable(bs);\n this.byteArraysBs = PairingUtils.GetElementArrayBytes(this.bs);\n this.ids = new String[ids.length];\n System.arraycopy(ids, 0, this.ids, 0, this.ids.length);\n this.elementIds = ElementUtils.cloneImmutable(elementIds);\n this.byteArraysElementIds = PairingUtils.GetElementArrayBytes(this.elementIds);\n }\n\n public String getIdAt(int index) {\n return this.ids[index];\n }\n\n public String[] getIds() {\n return this.ids;\n }\n\n public Element getElementIdAt(int index) {\n return this.elementIds[index].duplicate();\n }\n\n public Element[] getElementIds() {\n return this.elementIds;\n }\n\n public Element getA0() {\n return this.a0.duplicate();\n }\n\n public Element getA1() {\n return this.a1.duplicate();\n }\n\n public Element getBsAt(int index) {\n return this.bs[index].duplicate();\n }\n\n public Element[] getBs() {\n return this.bs;\n }\n\n @Override\n public boolean equals(Object anOjbect) {\n if (this == anOjbect) {\n return true;\n }\n if (anOjbect instanceof HIBBELLW16aSecretKeySerParameter) {\n HIBBELLW16aSecretKeySerParameter that = (HIBBELLW16aSecretKeySerParameter) anOjbect;\n // Compare ids\n if (!Arrays.equals(this.ids, that.getIds())) {\n return false;\n }\n // Compare elementIds\n if (!PairingUtils.isEqualElementArray(this.elementIds, that.getElementIds())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysElementIds, that.byteArraysElementIds)) {\n return false;\n }\n // Compare a0\n if (!PairingUtils.isEqualElement(this.a0, that.getA0())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA0, that.byteArrayA0)) {\n return false;\n }\n // Compare a1\n if (!PairingUtils.isEqualElement(this.a1, that.getA1())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA1, that.byteArrayA1)) {\n return false;\n }\n // Compare bs\n if (!PairingUtils.isEqualElementArray(this.bs, that.getBs())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysBs, that.byteArraysBs)) {\n return false;\n }\n // Compare Pairing Parameters\n return this.getParameters().toString().equals(that.getParameters().toString());\n }\n return false;\n }\n\n private void readObject(java.io.ObjectInputStream objectInputStream) throws java.io.IOException, ClassNotFoundException {\n objectInputStream.defaultReadObject();\n Pairing pairing = PairingFactory.getPairing(this.getParameters());\n this.elementIds = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysElementIds, PairingUtils.PairingGroupType.Zr);\n this.a0 = pairing.getG1().newElementFromBytes(this.byteArrayA0).getImmutable();\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1906", "language": "Java", "task_type": "single_line", "source_file": "java/github/liuweiran900217/CloudCrypto/src/main/java/cn/edu/buaa/crypto/encryption/hibbe/llw16a/serparams/HIBBELLW16aSecretKeySerParameter.java", "mask_start_position": 2274, "mask_end_position": 2282, "canonical_solution": "icate();", "pre_mask_code": "package cn.edu.buaa.crypto.encryption.hibbe.llw16a.serparams;\n\nimport cn.edu.buaa.crypto.algebra.serparams.PairingKeySerParameter;\nimport cn.edu.buaa.crypto.utils.PairingUtils;\nimport it.unisa.dia.gas.jpbc.Element;\nimport it.unisa.dia.gas.jpbc.Pairing;\nimport it.unisa.dia.gas.jpbc.PairingParameters;\nimport it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;\nimport it.unisa.dia.gas.plaf.jpbc.util.ElementUtils;\nimport java.util.Arrays;\n\n/**\n * Created by Weiran Liu on 2016/5/17.\n *\n * Liu-Liu-Wu prime-order HIBBE secret key parameter.\n */\npublic class HIBBELLW16aSecretKeySerParameter extends PairingKeySerParameter {\n\n private final String[] ids;\n\n private transient Element[] elementIds;\n\n private final byte[][] byteArraysElementIds;\n\n private transient Element a0;\n\n private final byte[] byteArrayA0;\n\n private transient Element a1;\n\n private final byte[] byteArrayA1;\n\n private transient Element[] bs;\n\n private final byte[][] byteArraysBs;\n\n public HIBBELLW16aSecretKeySerParameter(PairingParameters pairingParameters, String[] ids, Element[] elementIds, Element a0, Element a1, Element[] bs) {\n super(true, pairingParameters);\n this.a0 = a0.getImmutable();\n this.byteArrayA0 = this.a0.toBytes();\n this.a1 = a1.getImmutable();\n this.byteArrayA1 = this.a1.toBytes();\n this.bs = ElementUtils.cloneImmutable(bs);\n this.byteArraysBs = PairingUtils.GetElementArrayBytes(this.bs);\n this.ids = new String[ids.length];\n System.arraycopy(ids, 0, this.ids, 0, this.ids.length);\n this.elementIds = ElementUtils.cloneImmutable(elementIds);\n this.byteArraysElementIds = PairingUtils.GetElementArrayBytes(this.elementIds);\n }\n\n public String getIdAt(int index) {\n return this.ids[index];\n }\n\n public String[] getIds() {\n return this.ids;\n }\n\n public Element getElementIdAt(int index) {\n return this.elementIds[index].duplicate();\n }\n\n public Element[] getElementIds() {\n return this.elementIds;\n }\n\n public Element getA0() {\n return this.a0.duplicate();\n }\n\n public Element getA1() {\n return this.a1.duplicate();\n }\n\n public Element getBsAt(int index) {\n return this.bs[index].dupl", "post_mask_code": "\n }\n\n public Element[] getBs() {\n return this.bs;\n }\n\n @Override\n public boolean equals(Object anOjbect) {\n if (this == anOjbect) {\n return true;\n }\n if (anOjbect instanceof HIBBELLW16aSecretKeySerParameter) {\n HIBBELLW16aSecretKeySerParameter that = (HIBBELLW16aSecretKeySerParameter) anOjbect;\n // Compare ids\n if (!Arrays.equals(this.ids, that.getIds())) {\n return false;\n }\n // Compare elementIds\n if (!PairingUtils.isEqualElementArray(this.elementIds, that.getElementIds())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysElementIds, that.byteArraysElementIds)) {\n return false;\n }\n // Compare a0\n if (!PairingUtils.isEqualElement(this.a0, that.getA0())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA0, that.byteArrayA0)) {\n return false;\n }\n // Compare a1\n if (!PairingUtils.isEqualElement(this.a1, that.getA1())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA1, that.byteArrayA1)) {\n return false;\n }\n // Compare bs\n if (!PairingUtils.isEqualElementArray(this.bs, that.getBs())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysBs, that.byteArraysBs)) {\n return false;\n }\n // Compare Pairing Parameters\n return this.getParameters().toString().equals(that.getParameters().toString());\n }\n return false;\n }\n\n private void readObject(java.io.ObjectInputStream objectInputStream) throws java.io.IOException, ClassNotFoundException {\n objectInputStream.defaultReadObject();\n Pairing pairing = PairingFactory.getPairing(this.getParameters());\n this.elementIds = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysElementIds, PairingUtils.PairingGroupType.Zr);\n this.a0 = pairing.getG1().newElementFromBytes(this.byteArrayA0).getImmutable();\n this.a1 = pairing.getG1().newElementFromBytes(this.byteArrayA1).getImmutable();\n this.bs = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysBs, PairingUtils.PairingGroupType.G1);\n }\n}\n"} {"task_id": "Java_1907", "language": "Java", "task_type": "if_statement", "source_file": "java/github/liuweiran900217/CloudCrypto/src/main/java/cn/edu/buaa/crypto/encryption/hibbe/llw16a/serparams/HIBBELLW16aSecretKeySerParameter.java", "mask_start_position": 3500, "mask_end_position": 3601, "canonical_solution": "if (!Arrays.equals(this.byteArrayA1, that.byteArrayA1)) {\n return false;\n }", "pre_mask_code": "package cn.edu.buaa.crypto.encryption.hibbe.llw16a.serparams;\n\nimport cn.edu.buaa.crypto.algebra.serparams.PairingKeySerParameter;\nimport cn.edu.buaa.crypto.utils.PairingUtils;\nimport it.unisa.dia.gas.jpbc.Element;\nimport it.unisa.dia.gas.jpbc.Pairing;\nimport it.unisa.dia.gas.jpbc.PairingParameters;\nimport it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory;\nimport it.unisa.dia.gas.plaf.jpbc.util.ElementUtils;\nimport java.util.Arrays;\n\n/**\n * Created by Weiran Liu on 2016/5/17.\n *\n * Liu-Liu-Wu prime-order HIBBE secret key parameter.\n */\npublic class HIBBELLW16aSecretKeySerParameter extends PairingKeySerParameter {\n\n private final String[] ids;\n\n private transient Element[] elementIds;\n\n private final byte[][] byteArraysElementIds;\n\n private transient Element a0;\n\n private final byte[] byteArrayA0;\n\n private transient Element a1;\n\n private final byte[] byteArrayA1;\n\n private transient Element[] bs;\n\n private final byte[][] byteArraysBs;\n\n public HIBBELLW16aSecretKeySerParameter(PairingParameters pairingParameters, String[] ids, Element[] elementIds, Element a0, Element a1, Element[] bs) {\n super(true, pairingParameters);\n this.a0 = a0.getImmutable();\n this.byteArrayA0 = this.a0.toBytes();\n this.a1 = a1.getImmutable();\n this.byteArrayA1 = this.a1.toBytes();\n this.bs = ElementUtils.cloneImmutable(bs);\n this.byteArraysBs = PairingUtils.GetElementArrayBytes(this.bs);\n this.ids = new String[ids.length];\n System.arraycopy(ids, 0, this.ids, 0, this.ids.length);\n this.elementIds = ElementUtils.cloneImmutable(elementIds);\n this.byteArraysElementIds = PairingUtils.GetElementArrayBytes(this.elementIds);\n }\n\n public String getIdAt(int index) {\n return this.ids[index];\n }\n\n public String[] getIds() {\n return this.ids;\n }\n\n public Element getElementIdAt(int index) {\n return this.elementIds[index].duplicate();\n }\n\n public Element[] getElementIds() {\n return this.elementIds;\n }\n\n public Element getA0() {\n return this.a0.duplicate();\n }\n\n public Element getA1() {\n return this.a1.duplicate();\n }\n\n public Element getBsAt(int index) {\n return this.bs[index].duplicate();\n }\n\n public Element[] getBs() {\n return this.bs;\n }\n\n @Override\n public boolean equals(Object anOjbect) {\n if (this == anOjbect) {\n return true;\n }\n if (anOjbect instanceof HIBBELLW16aSecretKeySerParameter) {\n HIBBELLW16aSecretKeySerParameter that = (HIBBELLW16aSecretKeySerParameter) anOjbect;\n // Compare ids\n if (!Arrays.equals(this.ids, that.getIds())) {\n return false;\n }\n // Compare elementIds\n if (!PairingUtils.isEqualElementArray(this.elementIds, that.getElementIds())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysElementIds, that.byteArraysElementIds)) {\n return false;\n }\n // Compare a0\n if (!PairingUtils.isEqualElement(this.a0, that.getA0())) {\n return false;\n }\n if (!Arrays.equals(this.byteArrayA0, that.byteArrayA0)) {\n return false;\n }\n // Compare a1\n if (!PairingUtils.isEqualElement(this.a1, that.getA1())) {\n return false;\n }\n ", "post_mask_code": "\n // Compare bs\n if (!PairingUtils.isEqualElementArray(this.bs, that.getBs())) {\n return false;\n }\n if (!PairingUtils.isEqualByteArrays(this.byteArraysBs, that.byteArraysBs)) {\n return false;\n }\n // Compare Pairing Parameters\n return this.getParameters().toString().equals(that.getParameters().toString());\n }\n return false;\n }\n\n private void readObject(java.io.ObjectInputStream objectInputStream) throws java.io.IOException, ClassNotFoundException {\n objectInputStream.defaultReadObject();\n Pairing pairing = PairingFactory.getPairing(this.getParameters());\n this.elementIds = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysElementIds, PairingUtils.PairingGroupType.Zr);\n this.a0 = pairing.getG1().newElementFromBytes(this.byteArrayA0).getImmutable();\n this.a1 = pairing.getG1().newElementFromBytes(this.byteArrayA1).getImmutable();\n this.bs = PairingUtils.GetElementArrayFromBytes(pairing, this.byteArraysBs, PairingUtils.PairingGroupType.G1);\n }\n}\n"} {"task_id": "Java_1908", "language": "Java", "task_type": "method_signature", "source_file": "java/github/TeamAmaze/AmazeFileManager/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadModelProvider.java", "mask_start_position": 1652, "mask_end_position": 1766, "canonical_solution": "@Override\n @Nullable\n public RequestBuilder getPreloadRequestBuilder(IconDataParcelable iconData) ", "pre_mask_code": "/*\n *\n * This file is part of Amaze File Manager.\n *\n */\npackage com.amaze.filemanager.adapters.glide;\n\nimport java.util.Collections;\nimport java.util.List;\nimport com.amaze.filemanager.GlideApp;\nimport com.amaze.filemanager.GlideRequest;\nimport com.amaze.filemanager.adapters.data.IconDataParcelable;\nimport com.bumptech.glide.ListPreloader;\nimport com.bumptech.glide.RequestBuilder;\nimport com.bumptech.glide.load.engine.DiskCacheStrategy;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;\n\n/**\n * @author Emmanuel Messulam on 6/12/2017, at 15:15.\n */\npublic class RecyclerPreloadModelProvider implements ListPreloader.PreloadModelProvider {\n\n private final List urisToLoad;\n\n private final GlideRequest request;\n\n public RecyclerPreloadModelProvider(@NonNull Fragment fragment, @NonNull List uris, boolean isCircled) {\n urisToLoad = uris;\n GlideRequest incompleteRequest = GlideApp.with(fragment).asDrawable();\n if (isCircled) {\n request = incompleteRequest.circleCrop();\n } else {\n request = incompleteRequest.centerCrop();\n }\n }\n\n @Override\n @NonNull\n public List getPreloadItems(int position) {\n IconDataParcelable iconData = position < urisToLoad.size() ? urisToLoad.get(position) : null;\n if (iconData == null)\n return Collections.emptyList();\n return Collections.singletonList(iconData);\n }\n\n ", "post_mask_code": "{\n RequestBuilder requestBuilder;\n if (iconData.type == IconDataParcelable.IMAGE_FROMFILE) {\n requestBuilder = request.load(iconData.path);\n } else if (iconData.type == IconDataParcelable.IMAGE_FROMCLOUD) {\n requestBuilder = request.load(iconData.path).diskCacheStrategy(DiskCacheStrategy.NONE);\n } else {\n requestBuilder = request.load(iconData.image);\n }\n return requestBuilder;\n }\n}\n"} {"task_id": "Java_1909", "language": "Java", "task_type": "method_body", "source_file": "java/github/TeamAmaze/AmazeFileManager/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadModelProvider.java", "mask_start_position": 1411, "mask_end_position": 1646, "canonical_solution": "{\n IconDataParcelable iconData = position < urisToLoad.size() ? urisToLoad.get(position) : null;\n if (iconData == null)\n return Collections.emptyList();\n return Collections.singletonList(iconData);\n }", "pre_mask_code": "/*\n *\n * This file is part of Amaze File Manager.\n *\n */\npackage com.amaze.filemanager.adapters.glide;\n\nimport java.util.Collections;\nimport java.util.List;\nimport com.amaze.filemanager.GlideApp;\nimport com.amaze.filemanager.GlideRequest;\nimport com.amaze.filemanager.adapters.data.IconDataParcelable;\nimport com.bumptech.glide.ListPreloader;\nimport com.bumptech.glide.RequestBuilder;\nimport com.bumptech.glide.load.engine.DiskCacheStrategy;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;\n\n/**\n * @author Emmanuel Messulam on 6/12/2017, at 15:15.\n */\npublic class RecyclerPreloadModelProvider implements ListPreloader.PreloadModelProvider {\n\n private final List urisToLoad;\n\n private final GlideRequest request;\n\n public RecyclerPreloadModelProvider(@NonNull Fragment fragment, @NonNull List uris, boolean isCircled) {\n urisToLoad = uris;\n GlideRequest incompleteRequest = GlideApp.with(fragment).asDrawable();\n if (isCircled) {\n request = incompleteRequest.circleCrop();\n } else {\n request = incompleteRequest.centerCrop();\n }\n }\n\n @Override\n @NonNull\n public List getPreloadItems(int position) ", "post_mask_code": "\n\n @Override\n @Nullable\n public RequestBuilder getPreloadRequestBuilder(IconDataParcelable iconData) {\n RequestBuilder requestBuilder;\n if (iconData.type == IconDataParcelable.IMAGE_FROMFILE) {\n requestBuilder = request.load(iconData.path);\n } else if (iconData.type == IconDataParcelable.IMAGE_FROMCLOUD) {\n requestBuilder = request.load(iconData.path).diskCacheStrategy(DiskCacheStrategy.NONE);\n } else {\n requestBuilder = request.load(iconData.image);\n }\n return requestBuilder;\n }\n}\n"} {"task_id": "Java_1910", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/TeamAmaze/AmazeFileManager/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadModelProvider.java", "mask_start_position": 1767, "mask_end_position": 1816, "canonical_solution": "\n RequestBuilder requestBuilder;", "pre_mask_code": "/*\n *\n * This file is part of Amaze File Manager.\n *\n */\npackage com.amaze.filemanager.adapters.glide;\n\nimport java.util.Collections;\nimport java.util.List;\nimport com.amaze.filemanager.GlideApp;\nimport com.amaze.filemanager.GlideRequest;\nimport com.amaze.filemanager.adapters.data.IconDataParcelable;\nimport com.bumptech.glide.ListPreloader;\nimport com.bumptech.glide.RequestBuilder;\nimport com.bumptech.glide.load.engine.DiskCacheStrategy;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;\n\n/**\n * @author Emmanuel Messulam on 6/12/2017, at 15:15.\n */\npublic class RecyclerPreloadModelProvider implements ListPreloader.PreloadModelProvider {\n\n private final List urisToLoad;\n\n private final GlideRequest request;\n\n public RecyclerPreloadModelProvider(@NonNull Fragment fragment, @NonNull List uris, boolean isCircled) {\n urisToLoad = uris;\n GlideRequest incompleteRequest = GlideApp.with(fragment).asDrawable();\n if (isCircled) {\n request = incompleteRequest.circleCrop();\n } else {\n request = incompleteRequest.centerCrop();\n }\n }\n\n @Override\n @NonNull\n public List getPreloadItems(int position) {\n IconDataParcelable iconData = position < urisToLoad.size() ? urisToLoad.get(position) : null;\n if (iconData == null)\n return Collections.emptyList();\n return Collections.singletonList(iconData);\n }\n\n @Override\n @Nullable\n public RequestBuilder getPreloadRequestBuilder(IconDataParcelable iconData) {", "post_mask_code": "\n if (iconData.type == IconDataParcelable.IMAGE_FROMFILE) {\n requestBuilder = request.load(iconData.path);\n } else if (iconData.type == IconDataParcelable.IMAGE_FROMCLOUD) {\n requestBuilder = request.load(iconData.path).diskCacheStrategy(DiskCacheStrategy.NONE);\n } else {\n requestBuilder = request.load(iconData.image);\n }\n return requestBuilder;\n }\n}\n"} {"task_id": "Java_1911", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/TeamAmaze/AmazeFileManager/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadModelProvider.java", "mask_start_position": 1825, "mask_end_position": 2200, "canonical_solution": "if (iconData.type == IconDataParcelable.IMAGE_FROMFILE) {\n requestBuilder = request.load(iconData.path);\n } else if (iconData.type == IconDataParcelable.IMAGE_FROMCLOUD) {\n requestBuilder = request.load(iconData.path).diskCacheStrategy(DiskCacheStrategy.NONE);\n } else {\n requestBuilder = request.load(iconData.image);\n }", "pre_mask_code": "/*\n *\n * This file is part of Amaze File Manager.\n *\n */\npackage com.amaze.filemanager.adapters.glide;\n\nimport java.util.Collections;\nimport java.util.List;\nimport com.amaze.filemanager.GlideApp;\nimport com.amaze.filemanager.GlideRequest;\nimport com.amaze.filemanager.adapters.data.IconDataParcelable;\nimport com.bumptech.glide.ListPreloader;\nimport com.bumptech.glide.RequestBuilder;\nimport com.bumptech.glide.load.engine.DiskCacheStrategy;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;\n\n/**\n * @author Emmanuel Messulam on 6/12/2017, at 15:15.\n */\npublic class RecyclerPreloadModelProvider implements ListPreloader.PreloadModelProvider {\n\n private final List urisToLoad;\n\n private final GlideRequest request;\n\n public RecyclerPreloadModelProvider(@NonNull Fragment fragment, @NonNull List uris, boolean isCircled) {\n urisToLoad = uris;\n GlideRequest incompleteRequest = GlideApp.with(fragment).asDrawable();\n if (isCircled) {\n request = incompleteRequest.circleCrop();\n } else {\n request = incompleteRequest.centerCrop();\n }\n }\n\n @Override\n @NonNull\n public List getPreloadItems(int position) {\n IconDataParcelable iconData = position < urisToLoad.size() ? urisToLoad.get(position) : null;\n if (iconData == null)\n return Collections.emptyList();\n return Collections.singletonList(iconData);\n }\n\n @Override\n @Nullable\n public RequestBuilder getPreloadRequestBuilder(IconDataParcelable iconData) {\n RequestBuilder requestBuilder;\n ", "post_mask_code": "\n return requestBuilder;\n }\n}\n"} {"task_id": "Java_1912", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/TeamAmaze/AmazeFileManager/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadModelProvider.java", "mask_start_position": 2209, "mask_end_position": 2237, "canonical_solution": "return requestBuilder;\n }", "pre_mask_code": "/*\n *\n * This file is part of Amaze File Manager.\n *\n */\npackage com.amaze.filemanager.adapters.glide;\n\nimport java.util.Collections;\nimport java.util.List;\nimport com.amaze.filemanager.GlideApp;\nimport com.amaze.filemanager.GlideRequest;\nimport com.amaze.filemanager.adapters.data.IconDataParcelable;\nimport com.bumptech.glide.ListPreloader;\nimport com.bumptech.glide.RequestBuilder;\nimport com.bumptech.glide.load.engine.DiskCacheStrategy;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;\n\n/**\n * @author Emmanuel Messulam on 6/12/2017, at 15:15.\n */\npublic class RecyclerPreloadModelProvider implements ListPreloader.PreloadModelProvider {\n\n private final List urisToLoad;\n\n private final GlideRequest request;\n\n public RecyclerPreloadModelProvider(@NonNull Fragment fragment, @NonNull List uris, boolean isCircled) {\n urisToLoad = uris;\n GlideRequest incompleteRequest = GlideApp.with(fragment).asDrawable();\n if (isCircled) {\n request = incompleteRequest.circleCrop();\n } else {\n request = incompleteRequest.centerCrop();\n }\n }\n\n @Override\n @NonNull\n public List getPreloadItems(int position) {\n IconDataParcelable iconData = position < urisToLoad.size() ? urisToLoad.get(position) : null;\n if (iconData == null)\n return Collections.emptyList();\n return Collections.singletonList(iconData);\n }\n\n @Override\n @Nullable\n public RequestBuilder getPreloadRequestBuilder(IconDataParcelable iconData) {\n RequestBuilder requestBuilder;\n if (iconData.type == IconDataParcelable.IMAGE_FROMFILE) {\n requestBuilder = request.load(iconData.path);\n } else if (iconData.type == IconDataParcelable.IMAGE_FROMCLOUD) {\n requestBuilder = request.load(iconData.path).diskCacheStrategy(DiskCacheStrategy.NONE);\n } else {\n requestBuilder = request.load(iconData.image);\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1913", "language": "Java", "task_type": "single_line", "source_file": "java/github/TeamAmaze/AmazeFileManager/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadModelProvider.java", "mask_start_position": 1804, "mask_end_position": 1816, "canonical_solution": "uestBuilder;", "pre_mask_code": "/*\n *\n * This file is part of Amaze File Manager.\n *\n */\npackage com.amaze.filemanager.adapters.glide;\n\nimport java.util.Collections;\nimport java.util.List;\nimport com.amaze.filemanager.GlideApp;\nimport com.amaze.filemanager.GlideRequest;\nimport com.amaze.filemanager.adapters.data.IconDataParcelable;\nimport com.bumptech.glide.ListPreloader;\nimport com.bumptech.glide.RequestBuilder;\nimport com.bumptech.glide.load.engine.DiskCacheStrategy;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;\n\n/**\n * @author Emmanuel Messulam on 6/12/2017, at 15:15.\n */\npublic class RecyclerPreloadModelProvider implements ListPreloader.PreloadModelProvider {\n\n private final List urisToLoad;\n\n private final GlideRequest request;\n\n public RecyclerPreloadModelProvider(@NonNull Fragment fragment, @NonNull List uris, boolean isCircled) {\n urisToLoad = uris;\n GlideRequest incompleteRequest = GlideApp.with(fragment).asDrawable();\n if (isCircled) {\n request = incompleteRequest.circleCrop();\n } else {\n request = incompleteRequest.centerCrop();\n }\n }\n\n @Override\n @NonNull\n public List getPreloadItems(int position) {\n IconDataParcelable iconData = position < urisToLoad.size() ? urisToLoad.get(position) : null;\n if (iconData == null)\n return Collections.emptyList();\n return Collections.singletonList(iconData);\n }\n\n @Override\n @Nullable\n public RequestBuilder getPreloadRequestBuilder(IconDataParcelable iconData) {\n RequestBuilder req", "post_mask_code": "\n if (iconData.type == IconDataParcelable.IMAGE_FROMFILE) {\n requestBuilder = request.load(iconData.path);\n } else if (iconData.type == IconDataParcelable.IMAGE_FROMCLOUD) {\n requestBuilder = request.load(iconData.path).diskCacheStrategy(DiskCacheStrategy.NONE);\n } else {\n requestBuilder = request.load(iconData.image);\n }\n return requestBuilder;\n }\n}\n"} {"task_id": "Java_1914", "language": "Java", "task_type": "if_statement", "source_file": "java/github/TeamAmaze/AmazeFileManager/app/src/main/java/com/amaze/filemanager/adapters/glide/RecyclerPreloadModelProvider.java", "mask_start_position": 1159, "mask_end_position": 1310, "canonical_solution": "if (isCircled) {\n request = incompleteRequest.circleCrop();\n } else {\n request = incompleteRequest.centerCrop();\n }", "pre_mask_code": "/*\n *\n * This file is part of Amaze File Manager.\n *\n */\npackage com.amaze.filemanager.adapters.glide;\n\nimport java.util.Collections;\nimport java.util.List;\nimport com.amaze.filemanager.GlideApp;\nimport com.amaze.filemanager.GlideRequest;\nimport com.amaze.filemanager.adapters.data.IconDataParcelable;\nimport com.bumptech.glide.ListPreloader;\nimport com.bumptech.glide.RequestBuilder;\nimport com.bumptech.glide.load.engine.DiskCacheStrategy;\nimport android.graphics.drawable.Drawable;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;\n\n/**\n * @author Emmanuel Messulam on 6/12/2017, at 15:15.\n */\npublic class RecyclerPreloadModelProvider implements ListPreloader.PreloadModelProvider {\n\n private final List urisToLoad;\n\n private final GlideRequest request;\n\n public RecyclerPreloadModelProvider(@NonNull Fragment fragment, @NonNull List uris, boolean isCircled) {\n urisToLoad = uris;\n GlideRequest incompleteRequest = GlideApp.with(fragment).asDrawable();\n ", "post_mask_code": "\n }\n\n @Override\n @NonNull\n public List getPreloadItems(int position) {\n IconDataParcelable iconData = position < urisToLoad.size() ? urisToLoad.get(position) : null;\n if (iconData == null)\n return Collections.emptyList();\n return Collections.singletonList(iconData);\n }\n\n @Override\n @Nullable\n public RequestBuilder getPreloadRequestBuilder(IconDataParcelable iconData) {\n RequestBuilder requestBuilder;\n if (iconData.type == IconDataParcelable.IMAGE_FROMFILE) {\n requestBuilder = request.load(iconData.path);\n } else if (iconData.type == IconDataParcelable.IMAGE_FROMCLOUD) {\n requestBuilder = request.load(iconData.path).diskCacheStrategy(DiskCacheStrategy.NONE);\n } else {\n requestBuilder = request.load(iconData.image);\n }\n return requestBuilder;\n }\n}\n"} {"task_id": "Java_1915", "language": "Java", "task_type": "method_signature", "source_file": "java/github/BasLeijdekkers/MetricsReloaded/stockmetrics/src/com/sixrr/stockmetrics/classCalculators/LinesOfCodeClassCalculator.java", "mask_start_position": 586, "mask_end_position": 644, "canonical_solution": "@Override\n public void visitClass(PsiClass aClass) ", "pre_mask_code": "package com.sixrr.stockmetrics.classCalculators;\n\nimport com.intellij.psi.JavaRecursiveElementVisitor;\nimport com.intellij.psi.PsiClass;\nimport com.intellij.psi.PsiElementVisitor;\nimport com.sixrr.metrics.Metric;\nimport com.sixrr.stockmetrics.utils.LineUtil;\n\npublic class LinesOfCodeClassCalculator extends ClassCalculator {\n\n public LinesOfCodeClassCalculator(Metric metric) {\n super(metric);\n }\n\n @Override\n protected PsiElementVisitor createVisitor() {\n return new Visitor();\n }\n\n private class Visitor extends JavaRecursiveElementVisitor {\n\n ", "post_mask_code": "{\n super.visitClass(aClass);\n if (isConcreteClass(aClass)) {\n int linesOfCode = LineUtil.countLines(aClass);\n final PsiClass[] innerClasses = aClass.getInnerClasses();\n for (PsiClass innerClass : innerClasses) {\n linesOfCode -= LineUtil.countLines(innerClass);\n }\n postMetric(aClass, (double) linesOfCode);\n }\n }\n }\n}\n"} {"task_id": "Java_1916", "language": "Java", "task_type": "method_body", "source_file": "java/github/BasLeijdekkers/MetricsReloaded/stockmetrics/src/com/sixrr/stockmetrics/classCalculators/LinesOfCodeClassCalculator.java", "mask_start_position": 644, "mask_end_position": 1090, "canonical_solution": "{\n super.visitClass(aClass);\n if (isConcreteClass(aClass)) {\n int linesOfCode = LineUtil.countLines(aClass);\n final PsiClass[] innerClasses = aClass.getInnerClasses();\n for (PsiClass innerClass : innerClasses) {\n linesOfCode -= LineUtil.countLines(innerClass);\n }\n postMetric(aClass, (double) linesOfCode);\n }\n }", "pre_mask_code": "package com.sixrr.stockmetrics.classCalculators;\n\nimport com.intellij.psi.JavaRecursiveElementVisitor;\nimport com.intellij.psi.PsiClass;\nimport com.intellij.psi.PsiElementVisitor;\nimport com.sixrr.metrics.Metric;\nimport com.sixrr.stockmetrics.utils.LineUtil;\n\npublic class LinesOfCodeClassCalculator extends ClassCalculator {\n\n public LinesOfCodeClassCalculator(Metric metric) {\n super(metric);\n }\n\n @Override\n protected PsiElementVisitor createVisitor() {\n return new Visitor();\n }\n\n private class Visitor extends JavaRecursiveElementVisitor {\n\n @Override\n public void visitClass(PsiClass aClass) ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1917", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/BasLeijdekkers/MetricsReloaded/stockmetrics/src/com/sixrr/stockmetrics/classCalculators/LinesOfCodeClassCalculator.java", "mask_start_position": 645, "mask_end_position": 683, "canonical_solution": "\n super.visitClass(aClass);", "pre_mask_code": "package com.sixrr.stockmetrics.classCalculators;\n\nimport com.intellij.psi.JavaRecursiveElementVisitor;\nimport com.intellij.psi.PsiClass;\nimport com.intellij.psi.PsiElementVisitor;\nimport com.sixrr.metrics.Metric;\nimport com.sixrr.stockmetrics.utils.LineUtil;\n\npublic class LinesOfCodeClassCalculator extends ClassCalculator {\n\n public LinesOfCodeClassCalculator(Metric metric) {\n super(metric);\n }\n\n @Override\n protected PsiElementVisitor createVisitor() {\n return new Visitor();\n }\n\n private class Visitor extends JavaRecursiveElementVisitor {\n\n @Override\n public void visitClass(PsiClass aClass) {", "post_mask_code": "\n if (isConcreteClass(aClass)) {\n int linesOfCode = LineUtil.countLines(aClass);\n final PsiClass[] innerClasses = aClass.getInnerClasses();\n for (PsiClass innerClass : innerClasses) {\n linesOfCode -= LineUtil.countLines(innerClass);\n }\n postMetric(aClass, (double) linesOfCode);\n }\n }\n }\n}\n"} {"task_id": "Java_1918", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/BasLeijdekkers/MetricsReloaded/stockmetrics/src/com/sixrr/stockmetrics/classCalculators/LinesOfCodeClassCalculator.java", "mask_start_position": 696, "mask_end_position": 1080, "canonical_solution": "if (isConcreteClass(aClass)) {\n int linesOfCode = LineUtil.countLines(aClass);\n final PsiClass[] innerClasses = aClass.getInnerClasses();\n for (PsiClass innerClass : innerClasses) {\n linesOfCode -= LineUtil.countLines(innerClass);\n }\n postMetric(aClass, (double) linesOfCode);\n }", "pre_mask_code": "package com.sixrr.stockmetrics.classCalculators;\n\nimport com.intellij.psi.JavaRecursiveElementVisitor;\nimport com.intellij.psi.PsiClass;\nimport com.intellij.psi.PsiElementVisitor;\nimport com.sixrr.metrics.Metric;\nimport com.sixrr.stockmetrics.utils.LineUtil;\n\npublic class LinesOfCodeClassCalculator extends ClassCalculator {\n\n public LinesOfCodeClassCalculator(Metric metric) {\n super(metric);\n }\n\n @Override\n protected PsiElementVisitor createVisitor() {\n return new Visitor();\n }\n\n private class Visitor extends JavaRecursiveElementVisitor {\n\n @Override\n public void visitClass(PsiClass aClass) {\n super.visitClass(aClass);\n ", "post_mask_code": "\n }\n }\n}\n"} {"task_id": "Java_1919", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/BasLeijdekkers/MetricsReloaded/stockmetrics/src/com/sixrr/stockmetrics/classCalculators/LinesOfCodeClassCalculator.java", "mask_start_position": 1089, "mask_end_position": 1090, "canonical_solution": "}", "pre_mask_code": "package com.sixrr.stockmetrics.classCalculators;\n\nimport com.intellij.psi.JavaRecursiveElementVisitor;\nimport com.intellij.psi.PsiClass;\nimport com.intellij.psi.PsiElementVisitor;\nimport com.sixrr.metrics.Metric;\nimport com.sixrr.stockmetrics.utils.LineUtil;\n\npublic class LinesOfCodeClassCalculator extends ClassCalculator {\n\n public LinesOfCodeClassCalculator(Metric metric) {\n super(metric);\n }\n\n @Override\n protected PsiElementVisitor createVisitor() {\n return new Visitor();\n }\n\n private class Visitor extends JavaRecursiveElementVisitor {\n\n @Override\n public void visitClass(PsiClass aClass) {\n super.visitClass(aClass);\n if (isConcreteClass(aClass)) {\n int linesOfCode = LineUtil.countLines(aClass);\n final PsiClass[] innerClasses = aClass.getInnerClasses();\n for (PsiClass innerClass : innerClasses) {\n linesOfCode -= LineUtil.countLines(innerClass);\n }\n postMetric(aClass, (double) linesOfCode);\n }\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1920", "language": "Java", "task_type": "single_line", "source_file": "java/github/BasLeijdekkers/MetricsReloaded/stockmetrics/src/com/sixrr/stockmetrics/classCalculators/LinesOfCodeClassCalculator.java", "mask_start_position": 676, "mask_end_position": 683, "canonical_solution": "Class);", "pre_mask_code": "package com.sixrr.stockmetrics.classCalculators;\n\nimport com.intellij.psi.JavaRecursiveElementVisitor;\nimport com.intellij.psi.PsiClass;\nimport com.intellij.psi.PsiElementVisitor;\nimport com.sixrr.metrics.Metric;\nimport com.sixrr.stockmetrics.utils.LineUtil;\n\npublic class LinesOfCodeClassCalculator extends ClassCalculator {\n\n public LinesOfCodeClassCalculator(Metric metric) {\n super(metric);\n }\n\n @Override\n protected PsiElementVisitor createVisitor() {\n return new Visitor();\n }\n\n private class Visitor extends JavaRecursiveElementVisitor {\n\n @Override\n public void visitClass(PsiClass aClass) {\n super.visitClass(a", "post_mask_code": "\n if (isConcreteClass(aClass)) {\n int linesOfCode = LineUtil.countLines(aClass);\n final PsiClass[] innerClasses = aClass.getInnerClasses();\n for (PsiClass innerClass : innerClasses) {\n linesOfCode -= LineUtil.countLines(innerClass);\n }\n postMetric(aClass, (double) linesOfCode);\n }\n }\n }\n}\n"} {"task_id": "Java_1921", "language": "Java", "task_type": "if_statement", "source_file": "java/github/BasLeijdekkers/MetricsReloaded/stockmetrics/src/com/sixrr/stockmetrics/classCalculators/LinesOfCodeClassCalculator.java", "mask_start_position": 696, "mask_end_position": 1080, "canonical_solution": "if (isConcreteClass(aClass)) {\n int linesOfCode = LineUtil.countLines(aClass);\n final PsiClass[] innerClasses = aClass.getInnerClasses();\n for (PsiClass innerClass : innerClasses) {\n linesOfCode -= LineUtil.countLines(innerClass);\n }\n postMetric(aClass, (double) linesOfCode);\n }", "pre_mask_code": "package com.sixrr.stockmetrics.classCalculators;\n\nimport com.intellij.psi.JavaRecursiveElementVisitor;\nimport com.intellij.psi.PsiClass;\nimport com.intellij.psi.PsiElementVisitor;\nimport com.sixrr.metrics.Metric;\nimport com.sixrr.stockmetrics.utils.LineUtil;\n\npublic class LinesOfCodeClassCalculator extends ClassCalculator {\n\n public LinesOfCodeClassCalculator(Metric metric) {\n super(metric);\n }\n\n @Override\n protected PsiElementVisitor createVisitor() {\n return new Visitor();\n }\n\n private class Visitor extends JavaRecursiveElementVisitor {\n\n @Override\n public void visitClass(PsiClass aClass) {\n super.visitClass(aClass);\n ", "post_mask_code": "\n }\n }\n}\n"} {"task_id": "Java_1922", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ForgeRock/opendj-community-edition/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java", "mask_start_position": 10521, "mask_end_position": 10550, "canonical_solution": "private void findFreePorts() ", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport java.net.UnknownHostException;\nimport static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;\nimport static org.opends.server.loggers.ErrorLogger.logError;\nimport static org.opends.server.loggers.debug.DebugLogger.debugEnabled;\nimport static org.opends.server.loggers.debug.DebugLogger.getTracer;\nimport static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\nimport org.opends.messages.Category;\nimport org.opends.messages.Message;\nimport org.opends.messages.Severity;\nimport org.opends.server.TestCaseUtils;\nimport org.opends.server.admin.std.meta.ReplicationDomainCfgDefn.AssuredType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.loggers.debug.DebugTracer;\nimport org.opends.server.replication.ReplicationTestCase;\nimport org.opends.server.replication.common.AssuredMode;\nimport org.opends.server.replication.common.DSInfo;\nimport org.opends.server.replication.common.RSInfo;\nimport org.opends.server.replication.common.ServerStatus;\nimport org.opends.server.replication.protocol.ProtocolVersion;\nimport org.opends.server.replication.server.ReplServerFakeConfiguration;\nimport org.opends.server.replication.server.ReplicationServer;\nimport org.opends.server.types.DN;\nimport org.opends.server.types.DirectoryException;\nimport org.opends.server.util.StaticUtils;\nimport org.testng.annotations.Test;\n\n/**\n * Some tests to know if at any time the view DSs and RSs have of the current\n * topology is accurate, even after some connections, disconnections and\n * re-connections events.\n */\npublic class TopologyViewTest extends ReplicationTestCase {\n\n // Server id definitions\n private static final int DS1_ID = 1;\n\n private static final int DS2_ID = 2;\n\n private static final int DS3_ID = 3;\n\n private static final int DS4_ID = 4;\n\n private static final int DS5_ID = 5;\n\n private static final int DS6_ID = 6;\n\n private static final int RS1_ID = 51;\n\n private static final int RS2_ID = 52;\n\n private static final int RS3_ID = 53;\n\n // Group id definitions\n private static final int DS1_GID = 1;\n\n private static final int DS2_GID = 1;\n\n private static final int DS3_GID = 2;\n\n private static final int DS4_GID = 2;\n\n private static final int DS5_GID = 3;\n\n private static final int DS6_GID = 3;\n\n private static final int RS1_GID = 1;\n\n private static final int RS2_GID = 2;\n\n private static final int RS3_GID = 3;\n\n // Assured conf definitions\n private static final AssuredType DS1_AT = AssuredType.NOT_ASSURED;\n\n private static final int DS1_SDL = -1;\n\n private static SortedSet DS1_RU = new TreeSet();\n\n private static final AssuredType DS2_AT = AssuredType.SAFE_READ;\n\n private static final int DS2_SDL = -1;\n\n private static SortedSet DS2_RU = new TreeSet();\n\n private static final AssuredType DS3_AT = AssuredType.SAFE_DATA;\n\n private static final int DS3_SDL = 1;\n\n private static SortedSet DS3_RU = new TreeSet();\n\n private static final AssuredType DS4_AT = AssuredType.SAFE_READ;\n\n private static final int DS4_SDL = -1;\n\n private static SortedSet DS4_RU = new TreeSet();\n\n private static final AssuredType DS5_AT = AssuredType.SAFE_DATA;\n\n private static final int DS5_SDL = 2;\n\n private static SortedSet DS5_RU = new TreeSet();\n\n private static final AssuredType DS6_AT = AssuredType.SAFE_READ;\n\n private static final int DS6_SDL = -1;\n\n private static SortedSet DS6_RU = new TreeSet();\n\n private static String LOCAL_HOST_NAME;\n\n static {\n DS2_RU.add(\"ldap://fake_url_for_ds2\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_A\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_B\");\n try {\n LOCAL_HOST_NAME = InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n fail(\"Unable to resolve local host name\", e);\n }\n }\n\n private int rs1Port = -1;\n\n private int rs2Port = -1;\n\n private int rs3Port = -1;\n\n private LDAPReplicationDomain rd1 = null;\n\n private LDAPReplicationDomain rd2 = null;\n\n private LDAPReplicationDomain rd3 = null;\n\n private LDAPReplicationDomain rd4 = null;\n\n private LDAPReplicationDomain rd5 = null;\n\n private LDAPReplicationDomain rd6 = null;\n\n private ReplicationServer rs1 = null;\n\n private ReplicationServer rs2 = null;\n\n private ReplicationServer rs3 = null;\n\n // The tracer object for the debug logger\n private static final DebugTracer TRACER = getTracer();\n\n private void debugInfo(String s) {\n logError(Message.raw(Category.SYNC, Severity.NOTICE, s));\n if (debugEnabled()) {\n TRACER.debugInfo(\"** TEST **\" + s);\n }\n }\n\n private void initTest() {\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n rd1 = null;\n rd2 = null;\n rd3 = null;\n rd4 = null;\n rd5 = null;\n rd6 = null;\n rs1 = null;\n rs2 = null;\n rs3 = null;\n findFreePorts();\n }\n\n private void endTest() {\n if (rd1 != null) {\n rd1.shutdown();\n rd1 = null;\n }\n if (rd2 != null) {\n rd2.shutdown();\n rd2 = null;\n }\n if (rd3 != null) {\n rd3.shutdown();\n rd3 = null;\n }\n if (rd4 != null) {\n rd4.shutdown();\n rd4 = null;\n }\n if (rd5 != null) {\n rd5.shutdown();\n rd5 = null;\n }\n if (rd6 != null) {\n rd6.shutdown();\n rd6 = null;\n }\n try {\n // Clear any reference to a domain in synchro plugin\n MultimasterReplication.deleteDomain(DN.decode(TEST_ROOT_DN_STRING));\n } catch (DirectoryException ex) {\n fail(\"Error deleting reference to domain: \" + TEST_ROOT_DN_STRING);\n }\n if (rs1 != null) {\n rs1.clearDb();\n rs1.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs1.getDbDirName()));\n rs1 = null;\n }\n if (rs2 != null) {\n rs2.clearDb();\n rs2.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs2.getDbDirName()));\n rs2 = null;\n }\n if (rs3 != null) {\n rs3.clearDb();\n rs3.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs3.getDbDirName()));\n rs3 = null;\n }\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n }\n\n private void sleep(long time) {\n try {\n Thread.sleep(time);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n }\n\n /**\n * Check connection of the provided replication domain to the provided\n * replication server. Waits for connection to be ok up to secTimeout seconds\n * before failing.\n */\n private void checkConnection(int secTimeout, int dsId, int rsId) {\n int rsPort = -1;\n LDAPReplicationDomain rd = null;\n switch(dsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n int nSec = 0;\n // Go out of the loop only if connection is verified or if timeout occurs\n while (true) {\n // Test connection\n boolean connected = rd.isConnected();\n int rdPort = -1;\n boolean rightPort = false;\n if (connected) {\n String serverStr = rd.getReplicationServer();\n int index = serverStr.lastIndexOf(':');\n if ((index == -1) || (index >= serverStr.length()))\n fail(\"Enable to find port number in: \" + serverStr);\n String rdPortStr = serverStr.substring(index + 1);\n try {\n rdPort = (new Integer(rdPortStr)).intValue();\n } catch (Exception e) {\n fail(\"Enable to get an int from: \" + rdPortStr);\n }\n if (rdPort == rsPort)\n rightPort = true;\n }\n if (connected && rightPort) {\n // Connection verified\n debugInfo(\"checkConnection: connection from domain \" + dsId + \" to\" + \" replication server \" + rsId + \" obtained after \" + nSec + \" seconds.\");\n return;\n }\n // Sleep 1 second\n try {\n Thread.sleep(1000);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n nSec++;\n if (nSec > secTimeout) {\n // Timeout reached, end with error\n fail(\"checkConnection: could not verify connection from domain \" + dsId + \" to replication server \" + rsId + \" after \" + secTimeout + \" seconds.\" + \" Domain connected: \" + connected + \", connection port: \" + rdPort + \" (should be: \" + rsPort + \")\");\n }\n }\n }\n\n /**\n * Find needed free TCP ports.\n */\n ", "post_mask_code": "{\n try {\n ServerSocket socket1 = TestCaseUtils.bindFreePort();\n ServerSocket socket2 = TestCaseUtils.bindFreePort();\n ServerSocket socket3 = TestCaseUtils.bindFreePort();\n rs1Port = socket1.getLocalPort();\n rs2Port = socket2.getLocalPort();\n rs3Port = socket3.getLocalPort();\n socket1.close();\n socket2.close();\n socket3.close();\n } catch (IOException e) {\n fail(\"Unable to determinate some free ports \" + stackTraceToSingleLineString(e));\n }\n }\n\n /**\n * Creates the list of servers to represent the RS topology excluding the\n * RS whose id is passed.\n */\n private SortedSet createRSListExceptOne(int rsIdToExclude) {\n SortedSet replServers = new TreeSet();\n if (rsIdToExclude != RS1_ID) {\n replServers.add(getHostPort(rs1Port));\n }\n if (rsIdToExclude != RS2_ID) {\n replServers.add(getHostPort(rs2Port));\n }\n if (rsIdToExclude != RS3_ID) {\n replServers.add(getHostPort(rs3Port));\n }\n return replServers;\n }\n\n private ReplicationServer createReplicationServer(int rsId, String testCase) {\n try {\n SortedSet replServers = createRSListExceptOne(rsId);\n int rsPort = -1;\n int groupId = -1;\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n groupId = RS1_GID;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n groupId = RS2_GID;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n groupId = RS3_GID;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n String dir = \"topologyViewTest\" + rsId + testCase + \"Db\";\n ReplServerFakeConfiguration conf = new ReplServerFakeConfiguration(rsPort, dir, 0, rsId, 0, 100, replServers, groupId, 1000, 5000);\n ReplicationServer replicationServer = new ReplicationServer(conf);\n return replicationServer;\n } catch (Exception e) {\n fail(\"createReplicationServer \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n /**\n * Creates and starts a new ReplicationDomain with the correct list of\n * know RSs according to DS id\n */\n private LDAPReplicationDomain createReplicationDomain(int dsId) {\n try {\n SortedSet replServers = new TreeSet();\n int groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n // Fill rs list according to defined scenario (see testTopologyChanges\n switch(dsId) {\n case DS1_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n DN baseDn = DN.decode(TEST_ROOT_DN_STRING);\n DomainFakeCfg domainConf = new DomainFakeCfg(baseDn, dsId, replServers, assuredType, assuredSdLevel, groupId, 0, refUrls);\n LDAPReplicationDomain replicationDomain = MultimasterReplication.createNewDomain(domainConf);\n replicationDomain.start();\n return replicationDomain;\n } catch (Exception e) {\n fail(\"createReplicationDomain \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n // Definitions of steps for the test case\n private static final int STEP_1 = 1;\n\n private static final int STEP_2 = 2;\n\n private static final int STEP_3 = 3;\n\n private static final int STEP_4 = 4;\n\n private static final int STEP_5 = 5;\n\n private static final int STEP_6 = 6;\n\n private static final int STEP_7 = 7;\n\n private static final int STEP_8 = 8;\n\n private static final int STEP_9 = 9;\n\n private static final int STEP_10 = 10;\n\n private static final int STEP_11 = 11;\n\n private static final int STEP_12 = 12;\n\n private static final int STEP_13 = 13;\n\n /**\n * Perform connections/disconnections of DS/RS. Uses various config parameters\n * that are embedded in topo info to check if they are well transported.\n * This tests:\n * - if topo msgs are exchanged when needed and reflect topo reality (who is\n * connected to who)\n * - if topo msgs transport config params in terms of assured replication,\n * group id... that reflect what is configured in the DSs.\n *\n * Full topo is:\n * (GID=group id, A=assured, NA=not assured, SR=safe read, SD=safe data,\n * SDL=safe data level, RUF=ref urls filled, RUE=ref urls empty)\n * Except if otherwise stated, RSs and DSs are aware of every others existence\n * - RS1 with GID=1\n * - RS2 with GID=2\n * - RS3 with GID=3\n * - DS1 with GID=1, NA\n * - DS2 with GID=1, A, SR, RUF\n * - DS3 with GID=2, A, SD, SDL=1 (DS3 does not know RS1 and RS3)\n * - DS4 with GID=2, A, SR, RUE (DS4 does not know RS1 and RS3)\n * - DS5 with GID=3, A, SD, SDL=2 (DS5 does not know RS1)\n * - DS6 with GID=3, A, SR, RUF (DS6 does not know RS1)\n * Scenario is:\n * - RS1 starts\n * - DS1 starts and connects to RS1 (check topo view in DS1)\n * - DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n * - RS2 starts (check topo view in DS1,DS2)\n * - DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n * - DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n * - DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - RS3 starts (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n * - RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo view\n * in DS1,DS2,DS5,DS6)\n * @throws Exception If a problem occurred\n */\n @Test(enabled = true, groups = \"slow\")\n public void testTopologyChanges() throws Exception {\n String testCase = \"testTopologyChanges\";\n debugInfo(\"Starting \" + testCase);\n initTest();\n TopoView theoricalTopoView = null;\n try {\n /**\n * RS1 starts\n */\n debugInfo(\"*** STEP 0 ***\");\n rs1 = createReplicationServer(RS1_ID, testCase);\n /**\n * DS1 starts and connects to RS1 (check topo view in DS1)\n */\n debugInfo(\"*** STEP 1 ***\");\n rd1 = createReplicationDomain(DS1_ID);\n checkConnection(30, DS1_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_1);\n checkTopoView(new int[] { DS1_ID }, theoricalTopoView);\n /**\n * DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 2 ***\");\n rd2 = createReplicationDomain(DS2_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_2);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * RS2 starts (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 3 ***\");\n rs2 = createReplicationServer(RS2_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(1000);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_3);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n */\n debugInfo(\"*** STEP 4 ***\");\n rd3 = createReplicationDomain(DS3_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_4);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID }, theoricalTopoView);\n /**\n * DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n */\n debugInfo(\"*** STEP 5 ***\");\n rd4 = createReplicationDomain(DS4_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_5);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID }, theoricalTopoView);\n /**\n * DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 6 ***\");\n rd5 = createReplicationDomain(DS5_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_6);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 7 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_7);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 8 ***\");\n rd6 = createReplicationDomain(DS6_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_8);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 9 ***\");\n rd6.disable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n assertFalse(rd6.isConnected());\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_9);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 10 ***\");\n rd6.enable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_10);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 11 ***\");\n rs3.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n checkConnection(30, DS6_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_11);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 12 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_12);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo\n * view in DS1,DS2,DS5,DS6)\n */\n debugInfo(\"*** STEP 13 ***\");\n rs2.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_13);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n } finally {\n endTest();\n }\n }\n\n /**\n * Creates RSInfo for the passed RS\n */\n private RSInfo createRSInfo(int rsId) {\n int groupId = -1;\n String serverUrl = null;\n switch(rsId) {\n case RS1_ID:\n groupId = RS1_GID;\n serverUrl = getHostPort(rs1Port);\n break;\n case RS2_ID:\n groupId = RS2_GID;\n serverUrl = getHostPort(rs2Port);\n break;\n case RS3_ID:\n groupId = RS3_GID;\n serverUrl = getHostPort(rs3Port);\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n return new RSInfo(rsId, serverUrl, TEST_DN_WITH_ROOT_ENTRY_GENID, (byte) groupId, 1);\n }\n\n /**\n * Creates DSInfo for the passed DS, connected to the passed RS\n */\n private DSInfo createDSInfo(int dsId, int rsId) {\n ServerStatus status = ServerStatus.NORMAL_STATUS;\n byte groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n Set eclIncludes = new HashSet();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n switch(dsId) {\n case DS1_ID:\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n // Perform necessary conversions\n boolean assuredFlag = (assuredType != AssuredType.NOT_ASSURED);\n AssuredMode assMode = ((assuredType == AssuredType.SAFE_READ) ? AssuredMode.SAFE_READ_MODE : AssuredMode.SAFE_DATA_MODE);\n List urls = new ArrayList();\n for (String str : refUrls) {\n urls.add(str);\n }\n return new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assMode, (byte) assuredSdLevel, groupId, urls, eclIncludes, eclIncludes, protocolVersion);\n }\n\n /**\n * Creates the topo view to be checked at each step of the test (view that\n * every concerned DS should have)\n */\n private TopoView createTheoreticalTopoViewForStep(int step) {\n List dsList = new ArrayList();\n List rsList = new ArrayList();\n switch(step) {\n case STEP_1:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n break;\n case STEP_2:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_3:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_4:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n break;\n case STEP_5:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n break;\n case STEP_6:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n break;\n case STEP_7:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_8:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_9:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_10:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_11:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n dsList.add(createDSInfo(DS6_ID, RS2_ID));\n break;\n case STEP_12:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_13:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n default:\n fail(\"Unknown test step: \" + step);\n }\n return new TopoView(dsList, rsList);\n }\n\n /**\n * Get the topo view each DS in the provided ds list has and compares it\n * with the theoretical topology view that every body should have at the time\n * this method is called.\n */\n private void checkTopoView(int[] dsIdList, TopoView theoricalTopoView) {\n sleep(500);\n for (int currentDsId : dsIdList) {\n LDAPReplicationDomain rd = null;\n switch(currentDsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n /**\n * Get the topo view of the current analyzed DS\n */\n List internalDsList = rd.getReplicasList();\n // Add info for DS itself:\n // we need to clone the list as we don't want to modify the list kept\n // inside the DS.\n List dsList = new ArrayList();\n for (DSInfo aDsInfo : internalDsList) {\n dsList.add(aDsInfo);\n }\n int dsId = rd.getServerId();\n int rsId = rd.getRsServerId();\n ServerStatus status = rd.getStatus();\n boolean assuredFlag = rd.isAssured();\n AssuredMode assuredMode = rd.getAssuredMode();\n byte safeDataLevel = rd.getAssuredSdLevel();\n byte groupId = rd.getGroupId();\n List refUrls = rd.getRefUrls();\n Set eclInclude = rd.getEclIncludes();\n Set eclIncludeForDeletes = rd.getEclIncludesForDeletes();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n DSInfo dsInfo = new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assuredMode, safeDataLevel, groupId, refUrls, eclInclude, eclIncludeForDeletes, protocolVersion);\n dsList.add(dsInfo);\n TopoView dsTopoView = new TopoView(dsList, rd.getRsList());\n /**\n * Compare to what is the expected view\n */\n assertEquals(dsTopoView, theoricalTopoView, \" in DSid=\" + currentDsId);\n }\n }\n\n /**\n * Bag class representing a view of the topology at a given time\n * (who is connected to who, what are the config parameters...)\n */\n private class TopoView {\n\n private List dsList = null;\n\n private List rsList = null;\n\n public TopoView(List dsList, List rsList) {\n assertNotNull(dsList);\n assertNotNull(rsList);\n this.dsList = dsList;\n this.rsList = rsList;\n }\n\n public boolean equals(Object obj) {\n assertNotNull(obj);\n assertFalse(obj.getClass() != this.getClass());\n TopoView topoView = (TopoView) obj;\n // Check dsList\n if (topoView.dsList.size() != dsList.size())\n return false;\n for (DSInfo dsInfo : topoView.dsList) {\n int found = 0;\n for (DSInfo thisDsInfo : dsList) {\n if (thisDsInfo.equals(dsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as dsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n // Check rsList\n if (topoView.rsList.size() != rsList.size())\n return false;\n for (RSInfo rsInfo : topoView.rsList) {\n int found = 0;\n for (RSInfo thisRsInfo : rsList) {\n if (thisRsInfo.equals(rsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as rsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n return true;\n }\n\n public String toString() {\n String dsStr = \"\";\n for (DSInfo dsInfo : dsList) {\n dsStr += dsInfo.toString() + \"\\n----------------------------\\n\";\n }\n String rsStr = \"\";\n for (RSInfo rsInfo : rsList) {\n rsStr += rsInfo.toString() + \"\\n----------------------------\\n\";\n }\n return (\"TopoView:\" + \"\\n----------------------------\\n\" + \"CONNECTED DS SERVERS:\\n\" + dsStr + \"CONNECTED RS SERVERS:\\n\" + rsStr);\n }\n }\n\n private String getHostPort(int port) {\n return LOCAL_HOST_NAME + \":\" + port;\n }\n}\n"} {"task_id": "Java_1923", "language": "Java", "task_type": "method_body", "source_file": "java/github/ForgeRock/opendj-community-edition/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java", "mask_start_position": 11326, "mask_end_position": 11724, "canonical_solution": "{\n SortedSet replServers = new TreeSet();\n if (rsIdToExclude != RS1_ID) {\n replServers.add(getHostPort(rs1Port));\n }\n if (rsIdToExclude != RS2_ID) {\n replServers.add(getHostPort(rs2Port));\n }\n if (rsIdToExclude != RS3_ID) {\n replServers.add(getHostPort(rs3Port));\n }\n return replServers;\n }", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport java.net.UnknownHostException;\nimport static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;\nimport static org.opends.server.loggers.ErrorLogger.logError;\nimport static org.opends.server.loggers.debug.DebugLogger.debugEnabled;\nimport static org.opends.server.loggers.debug.DebugLogger.getTracer;\nimport static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\nimport org.opends.messages.Category;\nimport org.opends.messages.Message;\nimport org.opends.messages.Severity;\nimport org.opends.server.TestCaseUtils;\nimport org.opends.server.admin.std.meta.ReplicationDomainCfgDefn.AssuredType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.loggers.debug.DebugTracer;\nimport org.opends.server.replication.ReplicationTestCase;\nimport org.opends.server.replication.common.AssuredMode;\nimport org.opends.server.replication.common.DSInfo;\nimport org.opends.server.replication.common.RSInfo;\nimport org.opends.server.replication.common.ServerStatus;\nimport org.opends.server.replication.protocol.ProtocolVersion;\nimport org.opends.server.replication.server.ReplServerFakeConfiguration;\nimport org.opends.server.replication.server.ReplicationServer;\nimport org.opends.server.types.DN;\nimport org.opends.server.types.DirectoryException;\nimport org.opends.server.util.StaticUtils;\nimport org.testng.annotations.Test;\n\n/**\n * Some tests to know if at any time the view DSs and RSs have of the current\n * topology is accurate, even after some connections, disconnections and\n * re-connections events.\n */\npublic class TopologyViewTest extends ReplicationTestCase {\n\n // Server id definitions\n private static final int DS1_ID = 1;\n\n private static final int DS2_ID = 2;\n\n private static final int DS3_ID = 3;\n\n private static final int DS4_ID = 4;\n\n private static final int DS5_ID = 5;\n\n private static final int DS6_ID = 6;\n\n private static final int RS1_ID = 51;\n\n private static final int RS2_ID = 52;\n\n private static final int RS3_ID = 53;\n\n // Group id definitions\n private static final int DS1_GID = 1;\n\n private static final int DS2_GID = 1;\n\n private static final int DS3_GID = 2;\n\n private static final int DS4_GID = 2;\n\n private static final int DS5_GID = 3;\n\n private static final int DS6_GID = 3;\n\n private static final int RS1_GID = 1;\n\n private static final int RS2_GID = 2;\n\n private static final int RS3_GID = 3;\n\n // Assured conf definitions\n private static final AssuredType DS1_AT = AssuredType.NOT_ASSURED;\n\n private static final int DS1_SDL = -1;\n\n private static SortedSet DS1_RU = new TreeSet();\n\n private static final AssuredType DS2_AT = AssuredType.SAFE_READ;\n\n private static final int DS2_SDL = -1;\n\n private static SortedSet DS2_RU = new TreeSet();\n\n private static final AssuredType DS3_AT = AssuredType.SAFE_DATA;\n\n private static final int DS3_SDL = 1;\n\n private static SortedSet DS3_RU = new TreeSet();\n\n private static final AssuredType DS4_AT = AssuredType.SAFE_READ;\n\n private static final int DS4_SDL = -1;\n\n private static SortedSet DS4_RU = new TreeSet();\n\n private static final AssuredType DS5_AT = AssuredType.SAFE_DATA;\n\n private static final int DS5_SDL = 2;\n\n private static SortedSet DS5_RU = new TreeSet();\n\n private static final AssuredType DS6_AT = AssuredType.SAFE_READ;\n\n private static final int DS6_SDL = -1;\n\n private static SortedSet DS6_RU = new TreeSet();\n\n private static String LOCAL_HOST_NAME;\n\n static {\n DS2_RU.add(\"ldap://fake_url_for_ds2\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_A\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_B\");\n try {\n LOCAL_HOST_NAME = InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n fail(\"Unable to resolve local host name\", e);\n }\n }\n\n private int rs1Port = -1;\n\n private int rs2Port = -1;\n\n private int rs3Port = -1;\n\n private LDAPReplicationDomain rd1 = null;\n\n private LDAPReplicationDomain rd2 = null;\n\n private LDAPReplicationDomain rd3 = null;\n\n private LDAPReplicationDomain rd4 = null;\n\n private LDAPReplicationDomain rd5 = null;\n\n private LDAPReplicationDomain rd6 = null;\n\n private ReplicationServer rs1 = null;\n\n private ReplicationServer rs2 = null;\n\n private ReplicationServer rs3 = null;\n\n // The tracer object for the debug logger\n private static final DebugTracer TRACER = getTracer();\n\n private void debugInfo(String s) {\n logError(Message.raw(Category.SYNC, Severity.NOTICE, s));\n if (debugEnabled()) {\n TRACER.debugInfo(\"** TEST **\" + s);\n }\n }\n\n private void initTest() {\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n rd1 = null;\n rd2 = null;\n rd3 = null;\n rd4 = null;\n rd5 = null;\n rd6 = null;\n rs1 = null;\n rs2 = null;\n rs3 = null;\n findFreePorts();\n }\n\n private void endTest() {\n if (rd1 != null) {\n rd1.shutdown();\n rd1 = null;\n }\n if (rd2 != null) {\n rd2.shutdown();\n rd2 = null;\n }\n if (rd3 != null) {\n rd3.shutdown();\n rd3 = null;\n }\n if (rd4 != null) {\n rd4.shutdown();\n rd4 = null;\n }\n if (rd5 != null) {\n rd5.shutdown();\n rd5 = null;\n }\n if (rd6 != null) {\n rd6.shutdown();\n rd6 = null;\n }\n try {\n // Clear any reference to a domain in synchro plugin\n MultimasterReplication.deleteDomain(DN.decode(TEST_ROOT_DN_STRING));\n } catch (DirectoryException ex) {\n fail(\"Error deleting reference to domain: \" + TEST_ROOT_DN_STRING);\n }\n if (rs1 != null) {\n rs1.clearDb();\n rs1.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs1.getDbDirName()));\n rs1 = null;\n }\n if (rs2 != null) {\n rs2.clearDb();\n rs2.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs2.getDbDirName()));\n rs2 = null;\n }\n if (rs3 != null) {\n rs3.clearDb();\n rs3.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs3.getDbDirName()));\n rs3 = null;\n }\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n }\n\n private void sleep(long time) {\n try {\n Thread.sleep(time);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n }\n\n /**\n * Check connection of the provided replication domain to the provided\n * replication server. Waits for connection to be ok up to secTimeout seconds\n * before failing.\n */\n private void checkConnection(int secTimeout, int dsId, int rsId) {\n int rsPort = -1;\n LDAPReplicationDomain rd = null;\n switch(dsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n int nSec = 0;\n // Go out of the loop only if connection is verified or if timeout occurs\n while (true) {\n // Test connection\n boolean connected = rd.isConnected();\n int rdPort = -1;\n boolean rightPort = false;\n if (connected) {\n String serverStr = rd.getReplicationServer();\n int index = serverStr.lastIndexOf(':');\n if ((index == -1) || (index >= serverStr.length()))\n fail(\"Enable to find port number in: \" + serverStr);\n String rdPortStr = serverStr.substring(index + 1);\n try {\n rdPort = (new Integer(rdPortStr)).intValue();\n } catch (Exception e) {\n fail(\"Enable to get an int from: \" + rdPortStr);\n }\n if (rdPort == rsPort)\n rightPort = true;\n }\n if (connected && rightPort) {\n // Connection verified\n debugInfo(\"checkConnection: connection from domain \" + dsId + \" to\" + \" replication server \" + rsId + \" obtained after \" + nSec + \" seconds.\");\n return;\n }\n // Sleep 1 second\n try {\n Thread.sleep(1000);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n nSec++;\n if (nSec > secTimeout) {\n // Timeout reached, end with error\n fail(\"checkConnection: could not verify connection from domain \" + dsId + \" to replication server \" + rsId + \" after \" + secTimeout + \" seconds.\" + \" Domain connected: \" + connected + \", connection port: \" + rdPort + \" (should be: \" + rsPort + \")\");\n }\n }\n }\n\n /**\n * Find needed free TCP ports.\n */\n private void findFreePorts() {\n try {\n ServerSocket socket1 = TestCaseUtils.bindFreePort();\n ServerSocket socket2 = TestCaseUtils.bindFreePort();\n ServerSocket socket3 = TestCaseUtils.bindFreePort();\n rs1Port = socket1.getLocalPort();\n rs2Port = socket2.getLocalPort();\n rs3Port = socket3.getLocalPort();\n socket1.close();\n socket2.close();\n socket3.close();\n } catch (IOException e) {\n fail(\"Unable to determinate some free ports \" + stackTraceToSingleLineString(e));\n }\n }\n\n /**\n * Creates the list of servers to represent the RS topology excluding the\n * RS whose id is passed.\n */\n private SortedSet createRSListExceptOne(int rsIdToExclude) ", "post_mask_code": "\n\n private ReplicationServer createReplicationServer(int rsId, String testCase) {\n try {\n SortedSet replServers = createRSListExceptOne(rsId);\n int rsPort = -1;\n int groupId = -1;\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n groupId = RS1_GID;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n groupId = RS2_GID;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n groupId = RS3_GID;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n String dir = \"topologyViewTest\" + rsId + testCase + \"Db\";\n ReplServerFakeConfiguration conf = new ReplServerFakeConfiguration(rsPort, dir, 0, rsId, 0, 100, replServers, groupId, 1000, 5000);\n ReplicationServer replicationServer = new ReplicationServer(conf);\n return replicationServer;\n } catch (Exception e) {\n fail(\"createReplicationServer \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n /**\n * Creates and starts a new ReplicationDomain with the correct list of\n * know RSs according to DS id\n */\n private LDAPReplicationDomain createReplicationDomain(int dsId) {\n try {\n SortedSet replServers = new TreeSet();\n int groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n // Fill rs list according to defined scenario (see testTopologyChanges\n switch(dsId) {\n case DS1_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n DN baseDn = DN.decode(TEST_ROOT_DN_STRING);\n DomainFakeCfg domainConf = new DomainFakeCfg(baseDn, dsId, replServers, assuredType, assuredSdLevel, groupId, 0, refUrls);\n LDAPReplicationDomain replicationDomain = MultimasterReplication.createNewDomain(domainConf);\n replicationDomain.start();\n return replicationDomain;\n } catch (Exception e) {\n fail(\"createReplicationDomain \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n // Definitions of steps for the test case\n private static final int STEP_1 = 1;\n\n private static final int STEP_2 = 2;\n\n private static final int STEP_3 = 3;\n\n private static final int STEP_4 = 4;\n\n private static final int STEP_5 = 5;\n\n private static final int STEP_6 = 6;\n\n private static final int STEP_7 = 7;\n\n private static final int STEP_8 = 8;\n\n private static final int STEP_9 = 9;\n\n private static final int STEP_10 = 10;\n\n private static final int STEP_11 = 11;\n\n private static final int STEP_12 = 12;\n\n private static final int STEP_13 = 13;\n\n /**\n * Perform connections/disconnections of DS/RS. Uses various config parameters\n * that are embedded in topo info to check if they are well transported.\n * This tests:\n * - if topo msgs are exchanged when needed and reflect topo reality (who is\n * connected to who)\n * - if topo msgs transport config params in terms of assured replication,\n * group id... that reflect what is configured in the DSs.\n *\n * Full topo is:\n * (GID=group id, A=assured, NA=not assured, SR=safe read, SD=safe data,\n * SDL=safe data level, RUF=ref urls filled, RUE=ref urls empty)\n * Except if otherwise stated, RSs and DSs are aware of every others existence\n * - RS1 with GID=1\n * - RS2 with GID=2\n * - RS3 with GID=3\n * - DS1 with GID=1, NA\n * - DS2 with GID=1, A, SR, RUF\n * - DS3 with GID=2, A, SD, SDL=1 (DS3 does not know RS1 and RS3)\n * - DS4 with GID=2, A, SR, RUE (DS4 does not know RS1 and RS3)\n * - DS5 with GID=3, A, SD, SDL=2 (DS5 does not know RS1)\n * - DS6 with GID=3, A, SR, RUF (DS6 does not know RS1)\n * Scenario is:\n * - RS1 starts\n * - DS1 starts and connects to RS1 (check topo view in DS1)\n * - DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n * - RS2 starts (check topo view in DS1,DS2)\n * - DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n * - DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n * - DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - RS3 starts (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n * - RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo view\n * in DS1,DS2,DS5,DS6)\n * @throws Exception If a problem occurred\n */\n @Test(enabled = true, groups = \"slow\")\n public void testTopologyChanges() throws Exception {\n String testCase = \"testTopologyChanges\";\n debugInfo(\"Starting \" + testCase);\n initTest();\n TopoView theoricalTopoView = null;\n try {\n /**\n * RS1 starts\n */\n debugInfo(\"*** STEP 0 ***\");\n rs1 = createReplicationServer(RS1_ID, testCase);\n /**\n * DS1 starts and connects to RS1 (check topo view in DS1)\n */\n debugInfo(\"*** STEP 1 ***\");\n rd1 = createReplicationDomain(DS1_ID);\n checkConnection(30, DS1_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_1);\n checkTopoView(new int[] { DS1_ID }, theoricalTopoView);\n /**\n * DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 2 ***\");\n rd2 = createReplicationDomain(DS2_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_2);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * RS2 starts (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 3 ***\");\n rs2 = createReplicationServer(RS2_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(1000);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_3);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n */\n debugInfo(\"*** STEP 4 ***\");\n rd3 = createReplicationDomain(DS3_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_4);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID }, theoricalTopoView);\n /**\n * DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n */\n debugInfo(\"*** STEP 5 ***\");\n rd4 = createReplicationDomain(DS4_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_5);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID }, theoricalTopoView);\n /**\n * DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 6 ***\");\n rd5 = createReplicationDomain(DS5_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_6);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 7 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_7);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 8 ***\");\n rd6 = createReplicationDomain(DS6_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_8);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 9 ***\");\n rd6.disable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n assertFalse(rd6.isConnected());\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_9);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 10 ***\");\n rd6.enable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_10);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 11 ***\");\n rs3.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n checkConnection(30, DS6_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_11);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 12 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_12);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo\n * view in DS1,DS2,DS5,DS6)\n */\n debugInfo(\"*** STEP 13 ***\");\n rs2.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_13);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n } finally {\n endTest();\n }\n }\n\n /**\n * Creates RSInfo for the passed RS\n */\n private RSInfo createRSInfo(int rsId) {\n int groupId = -1;\n String serverUrl = null;\n switch(rsId) {\n case RS1_ID:\n groupId = RS1_GID;\n serverUrl = getHostPort(rs1Port);\n break;\n case RS2_ID:\n groupId = RS2_GID;\n serverUrl = getHostPort(rs2Port);\n break;\n case RS3_ID:\n groupId = RS3_GID;\n serverUrl = getHostPort(rs3Port);\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n return new RSInfo(rsId, serverUrl, TEST_DN_WITH_ROOT_ENTRY_GENID, (byte) groupId, 1);\n }\n\n /**\n * Creates DSInfo for the passed DS, connected to the passed RS\n */\n private DSInfo createDSInfo(int dsId, int rsId) {\n ServerStatus status = ServerStatus.NORMAL_STATUS;\n byte groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n Set eclIncludes = new HashSet();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n switch(dsId) {\n case DS1_ID:\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n // Perform necessary conversions\n boolean assuredFlag = (assuredType != AssuredType.NOT_ASSURED);\n AssuredMode assMode = ((assuredType == AssuredType.SAFE_READ) ? AssuredMode.SAFE_READ_MODE : AssuredMode.SAFE_DATA_MODE);\n List urls = new ArrayList();\n for (String str : refUrls) {\n urls.add(str);\n }\n return new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assMode, (byte) assuredSdLevel, groupId, urls, eclIncludes, eclIncludes, protocolVersion);\n }\n\n /**\n * Creates the topo view to be checked at each step of the test (view that\n * every concerned DS should have)\n */\n private TopoView createTheoreticalTopoViewForStep(int step) {\n List dsList = new ArrayList();\n List rsList = new ArrayList();\n switch(step) {\n case STEP_1:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n break;\n case STEP_2:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_3:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_4:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n break;\n case STEP_5:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n break;\n case STEP_6:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n break;\n case STEP_7:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_8:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_9:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_10:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_11:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n dsList.add(createDSInfo(DS6_ID, RS2_ID));\n break;\n case STEP_12:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_13:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n default:\n fail(\"Unknown test step: \" + step);\n }\n return new TopoView(dsList, rsList);\n }\n\n /**\n * Get the topo view each DS in the provided ds list has and compares it\n * with the theoretical topology view that every body should have at the time\n * this method is called.\n */\n private void checkTopoView(int[] dsIdList, TopoView theoricalTopoView) {\n sleep(500);\n for (int currentDsId : dsIdList) {\n LDAPReplicationDomain rd = null;\n switch(currentDsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n /**\n * Get the topo view of the current analyzed DS\n */\n List internalDsList = rd.getReplicasList();\n // Add info for DS itself:\n // we need to clone the list as we don't want to modify the list kept\n // inside the DS.\n List dsList = new ArrayList();\n for (DSInfo aDsInfo : internalDsList) {\n dsList.add(aDsInfo);\n }\n int dsId = rd.getServerId();\n int rsId = rd.getRsServerId();\n ServerStatus status = rd.getStatus();\n boolean assuredFlag = rd.isAssured();\n AssuredMode assuredMode = rd.getAssuredMode();\n byte safeDataLevel = rd.getAssuredSdLevel();\n byte groupId = rd.getGroupId();\n List refUrls = rd.getRefUrls();\n Set eclInclude = rd.getEclIncludes();\n Set eclIncludeForDeletes = rd.getEclIncludesForDeletes();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n DSInfo dsInfo = new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assuredMode, safeDataLevel, groupId, refUrls, eclInclude, eclIncludeForDeletes, protocolVersion);\n dsList.add(dsInfo);\n TopoView dsTopoView = new TopoView(dsList, rd.getRsList());\n /**\n * Compare to what is the expected view\n */\n assertEquals(dsTopoView, theoricalTopoView, \" in DSid=\" + currentDsId);\n }\n }\n\n /**\n * Bag class representing a view of the topology at a given time\n * (who is connected to who, what are the config parameters...)\n */\n private class TopoView {\n\n private List dsList = null;\n\n private List rsList = null;\n\n public TopoView(List dsList, List rsList) {\n assertNotNull(dsList);\n assertNotNull(rsList);\n this.dsList = dsList;\n this.rsList = rsList;\n }\n\n public boolean equals(Object obj) {\n assertNotNull(obj);\n assertFalse(obj.getClass() != this.getClass());\n TopoView topoView = (TopoView) obj;\n // Check dsList\n if (topoView.dsList.size() != dsList.size())\n return false;\n for (DSInfo dsInfo : topoView.dsList) {\n int found = 0;\n for (DSInfo thisDsInfo : dsList) {\n if (thisDsInfo.equals(dsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as dsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n // Check rsList\n if (topoView.rsList.size() != rsList.size())\n return false;\n for (RSInfo rsInfo : topoView.rsList) {\n int found = 0;\n for (RSInfo thisRsInfo : rsList) {\n if (thisRsInfo.equals(rsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as rsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n return true;\n }\n\n public String toString() {\n String dsStr = \"\";\n for (DSInfo dsInfo : dsList) {\n dsStr += dsInfo.toString() + \"\\n----------------------------\\n\";\n }\n String rsStr = \"\";\n for (RSInfo rsInfo : rsList) {\n rsStr += rsInfo.toString() + \"\\n----------------------------\\n\";\n }\n return (\"TopoView:\" + \"\\n----------------------------\\n\" + \"CONNECTED DS SERVERS:\\n\" + dsStr + \"CONNECTED RS SERVERS:\\n\" + rsStr);\n }\n }\n\n private String getHostPort(int port) {\n return LOCAL_HOST_NAME + \":\" + port;\n }\n}\n"} {"task_id": "Java_1924", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/ForgeRock/opendj-community-edition/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java", "mask_start_position": 11808, "mask_end_position": 12932, "canonical_solution": "\n try {\n SortedSet replServers = createRSListExceptOne(rsId);\n int rsPort = -1;\n int groupId = -1;\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n groupId = RS1_GID;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n groupId = RS2_GID;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n groupId = RS3_GID;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n String dir = \"topologyViewTest\" + rsId + testCase + \"Db\";\n ReplServerFakeConfiguration conf = new ReplServerFakeConfiguration(rsPort, dir, 0, rsId, 0, 100, replServers, groupId, 1000, 5000);\n ReplicationServer replicationServer = new ReplicationServer(conf);\n return replicationServer;\n } catch (Exception e) {\n fail(\"createReplicationServer \" + stackTraceToSingleLineString(e));\n }", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport java.net.UnknownHostException;\nimport static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;\nimport static org.opends.server.loggers.ErrorLogger.logError;\nimport static org.opends.server.loggers.debug.DebugLogger.debugEnabled;\nimport static org.opends.server.loggers.debug.DebugLogger.getTracer;\nimport static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\nimport org.opends.messages.Category;\nimport org.opends.messages.Message;\nimport org.opends.messages.Severity;\nimport org.opends.server.TestCaseUtils;\nimport org.opends.server.admin.std.meta.ReplicationDomainCfgDefn.AssuredType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.loggers.debug.DebugTracer;\nimport org.opends.server.replication.ReplicationTestCase;\nimport org.opends.server.replication.common.AssuredMode;\nimport org.opends.server.replication.common.DSInfo;\nimport org.opends.server.replication.common.RSInfo;\nimport org.opends.server.replication.common.ServerStatus;\nimport org.opends.server.replication.protocol.ProtocolVersion;\nimport org.opends.server.replication.server.ReplServerFakeConfiguration;\nimport org.opends.server.replication.server.ReplicationServer;\nimport org.opends.server.types.DN;\nimport org.opends.server.types.DirectoryException;\nimport org.opends.server.util.StaticUtils;\nimport org.testng.annotations.Test;\n\n/**\n * Some tests to know if at any time the view DSs and RSs have of the current\n * topology is accurate, even after some connections, disconnections and\n * re-connections events.\n */\npublic class TopologyViewTest extends ReplicationTestCase {\n\n // Server id definitions\n private static final int DS1_ID = 1;\n\n private static final int DS2_ID = 2;\n\n private static final int DS3_ID = 3;\n\n private static final int DS4_ID = 4;\n\n private static final int DS5_ID = 5;\n\n private static final int DS6_ID = 6;\n\n private static final int RS1_ID = 51;\n\n private static final int RS2_ID = 52;\n\n private static final int RS3_ID = 53;\n\n // Group id definitions\n private static final int DS1_GID = 1;\n\n private static final int DS2_GID = 1;\n\n private static final int DS3_GID = 2;\n\n private static final int DS4_GID = 2;\n\n private static final int DS5_GID = 3;\n\n private static final int DS6_GID = 3;\n\n private static final int RS1_GID = 1;\n\n private static final int RS2_GID = 2;\n\n private static final int RS3_GID = 3;\n\n // Assured conf definitions\n private static final AssuredType DS1_AT = AssuredType.NOT_ASSURED;\n\n private static final int DS1_SDL = -1;\n\n private static SortedSet DS1_RU = new TreeSet();\n\n private static final AssuredType DS2_AT = AssuredType.SAFE_READ;\n\n private static final int DS2_SDL = -1;\n\n private static SortedSet DS2_RU = new TreeSet();\n\n private static final AssuredType DS3_AT = AssuredType.SAFE_DATA;\n\n private static final int DS3_SDL = 1;\n\n private static SortedSet DS3_RU = new TreeSet();\n\n private static final AssuredType DS4_AT = AssuredType.SAFE_READ;\n\n private static final int DS4_SDL = -1;\n\n private static SortedSet DS4_RU = new TreeSet();\n\n private static final AssuredType DS5_AT = AssuredType.SAFE_DATA;\n\n private static final int DS5_SDL = 2;\n\n private static SortedSet DS5_RU = new TreeSet();\n\n private static final AssuredType DS6_AT = AssuredType.SAFE_READ;\n\n private static final int DS6_SDL = -1;\n\n private static SortedSet DS6_RU = new TreeSet();\n\n private static String LOCAL_HOST_NAME;\n\n static {\n DS2_RU.add(\"ldap://fake_url_for_ds2\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_A\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_B\");\n try {\n LOCAL_HOST_NAME = InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n fail(\"Unable to resolve local host name\", e);\n }\n }\n\n private int rs1Port = -1;\n\n private int rs2Port = -1;\n\n private int rs3Port = -1;\n\n private LDAPReplicationDomain rd1 = null;\n\n private LDAPReplicationDomain rd2 = null;\n\n private LDAPReplicationDomain rd3 = null;\n\n private LDAPReplicationDomain rd4 = null;\n\n private LDAPReplicationDomain rd5 = null;\n\n private LDAPReplicationDomain rd6 = null;\n\n private ReplicationServer rs1 = null;\n\n private ReplicationServer rs2 = null;\n\n private ReplicationServer rs3 = null;\n\n // The tracer object for the debug logger\n private static final DebugTracer TRACER = getTracer();\n\n private void debugInfo(String s) {\n logError(Message.raw(Category.SYNC, Severity.NOTICE, s));\n if (debugEnabled()) {\n TRACER.debugInfo(\"** TEST **\" + s);\n }\n }\n\n private void initTest() {\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n rd1 = null;\n rd2 = null;\n rd3 = null;\n rd4 = null;\n rd5 = null;\n rd6 = null;\n rs1 = null;\n rs2 = null;\n rs3 = null;\n findFreePorts();\n }\n\n private void endTest() {\n if (rd1 != null) {\n rd1.shutdown();\n rd1 = null;\n }\n if (rd2 != null) {\n rd2.shutdown();\n rd2 = null;\n }\n if (rd3 != null) {\n rd3.shutdown();\n rd3 = null;\n }\n if (rd4 != null) {\n rd4.shutdown();\n rd4 = null;\n }\n if (rd5 != null) {\n rd5.shutdown();\n rd5 = null;\n }\n if (rd6 != null) {\n rd6.shutdown();\n rd6 = null;\n }\n try {\n // Clear any reference to a domain in synchro plugin\n MultimasterReplication.deleteDomain(DN.decode(TEST_ROOT_DN_STRING));\n } catch (DirectoryException ex) {\n fail(\"Error deleting reference to domain: \" + TEST_ROOT_DN_STRING);\n }\n if (rs1 != null) {\n rs1.clearDb();\n rs1.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs1.getDbDirName()));\n rs1 = null;\n }\n if (rs2 != null) {\n rs2.clearDb();\n rs2.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs2.getDbDirName()));\n rs2 = null;\n }\n if (rs3 != null) {\n rs3.clearDb();\n rs3.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs3.getDbDirName()));\n rs3 = null;\n }\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n }\n\n private void sleep(long time) {\n try {\n Thread.sleep(time);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n }\n\n /**\n * Check connection of the provided replication domain to the provided\n * replication server. Waits for connection to be ok up to secTimeout seconds\n * before failing.\n */\n private void checkConnection(int secTimeout, int dsId, int rsId) {\n int rsPort = -1;\n LDAPReplicationDomain rd = null;\n switch(dsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n int nSec = 0;\n // Go out of the loop only if connection is verified or if timeout occurs\n while (true) {\n // Test connection\n boolean connected = rd.isConnected();\n int rdPort = -1;\n boolean rightPort = false;\n if (connected) {\n String serverStr = rd.getReplicationServer();\n int index = serverStr.lastIndexOf(':');\n if ((index == -1) || (index >= serverStr.length()))\n fail(\"Enable to find port number in: \" + serverStr);\n String rdPortStr = serverStr.substring(index + 1);\n try {\n rdPort = (new Integer(rdPortStr)).intValue();\n } catch (Exception e) {\n fail(\"Enable to get an int from: \" + rdPortStr);\n }\n if (rdPort == rsPort)\n rightPort = true;\n }\n if (connected && rightPort) {\n // Connection verified\n debugInfo(\"checkConnection: connection from domain \" + dsId + \" to\" + \" replication server \" + rsId + \" obtained after \" + nSec + \" seconds.\");\n return;\n }\n // Sleep 1 second\n try {\n Thread.sleep(1000);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n nSec++;\n if (nSec > secTimeout) {\n // Timeout reached, end with error\n fail(\"checkConnection: could not verify connection from domain \" + dsId + \" to replication server \" + rsId + \" after \" + secTimeout + \" seconds.\" + \" Domain connected: \" + connected + \", connection port: \" + rdPort + \" (should be: \" + rsPort + \")\");\n }\n }\n }\n\n /**\n * Find needed free TCP ports.\n */\n private void findFreePorts() {\n try {\n ServerSocket socket1 = TestCaseUtils.bindFreePort();\n ServerSocket socket2 = TestCaseUtils.bindFreePort();\n ServerSocket socket3 = TestCaseUtils.bindFreePort();\n rs1Port = socket1.getLocalPort();\n rs2Port = socket2.getLocalPort();\n rs3Port = socket3.getLocalPort();\n socket1.close();\n socket2.close();\n socket3.close();\n } catch (IOException e) {\n fail(\"Unable to determinate some free ports \" + stackTraceToSingleLineString(e));\n }\n }\n\n /**\n * Creates the list of servers to represent the RS topology excluding the\n * RS whose id is passed.\n */\n private SortedSet createRSListExceptOne(int rsIdToExclude) {\n SortedSet replServers = new TreeSet();\n if (rsIdToExclude != RS1_ID) {\n replServers.add(getHostPort(rs1Port));\n }\n if (rsIdToExclude != RS2_ID) {\n replServers.add(getHostPort(rs2Port));\n }\n if (rsIdToExclude != RS3_ID) {\n replServers.add(getHostPort(rs3Port));\n }\n return replServers;\n }\n\n private ReplicationServer createReplicationServer(int rsId, String testCase) {", "post_mask_code": "\n return null;\n }\n\n /**\n * Creates and starts a new ReplicationDomain with the correct list of\n * know RSs according to DS id\n */\n private LDAPReplicationDomain createReplicationDomain(int dsId) {\n try {\n SortedSet replServers = new TreeSet();\n int groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n // Fill rs list according to defined scenario (see testTopologyChanges\n switch(dsId) {\n case DS1_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n DN baseDn = DN.decode(TEST_ROOT_DN_STRING);\n DomainFakeCfg domainConf = new DomainFakeCfg(baseDn, dsId, replServers, assuredType, assuredSdLevel, groupId, 0, refUrls);\n LDAPReplicationDomain replicationDomain = MultimasterReplication.createNewDomain(domainConf);\n replicationDomain.start();\n return replicationDomain;\n } catch (Exception e) {\n fail(\"createReplicationDomain \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n // Definitions of steps for the test case\n private static final int STEP_1 = 1;\n\n private static final int STEP_2 = 2;\n\n private static final int STEP_3 = 3;\n\n private static final int STEP_4 = 4;\n\n private static final int STEP_5 = 5;\n\n private static final int STEP_6 = 6;\n\n private static final int STEP_7 = 7;\n\n private static final int STEP_8 = 8;\n\n private static final int STEP_9 = 9;\n\n private static final int STEP_10 = 10;\n\n private static final int STEP_11 = 11;\n\n private static final int STEP_12 = 12;\n\n private static final int STEP_13 = 13;\n\n /**\n * Perform connections/disconnections of DS/RS. Uses various config parameters\n * that are embedded in topo info to check if they are well transported.\n * This tests:\n * - if topo msgs are exchanged when needed and reflect topo reality (who is\n * connected to who)\n * - if topo msgs transport config params in terms of assured replication,\n * group id... that reflect what is configured in the DSs.\n *\n * Full topo is:\n * (GID=group id, A=assured, NA=not assured, SR=safe read, SD=safe data,\n * SDL=safe data level, RUF=ref urls filled, RUE=ref urls empty)\n * Except if otherwise stated, RSs and DSs are aware of every others existence\n * - RS1 with GID=1\n * - RS2 with GID=2\n * - RS3 with GID=3\n * - DS1 with GID=1, NA\n * - DS2 with GID=1, A, SR, RUF\n * - DS3 with GID=2, A, SD, SDL=1 (DS3 does not know RS1 and RS3)\n * - DS4 with GID=2, A, SR, RUE (DS4 does not know RS1 and RS3)\n * - DS5 with GID=3, A, SD, SDL=2 (DS5 does not know RS1)\n * - DS6 with GID=3, A, SR, RUF (DS6 does not know RS1)\n * Scenario is:\n * - RS1 starts\n * - DS1 starts and connects to RS1 (check topo view in DS1)\n * - DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n * - RS2 starts (check topo view in DS1,DS2)\n * - DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n * - DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n * - DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - RS3 starts (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n * - RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo view\n * in DS1,DS2,DS5,DS6)\n * @throws Exception If a problem occurred\n */\n @Test(enabled = true, groups = \"slow\")\n public void testTopologyChanges() throws Exception {\n String testCase = \"testTopologyChanges\";\n debugInfo(\"Starting \" + testCase);\n initTest();\n TopoView theoricalTopoView = null;\n try {\n /**\n * RS1 starts\n */\n debugInfo(\"*** STEP 0 ***\");\n rs1 = createReplicationServer(RS1_ID, testCase);\n /**\n * DS1 starts and connects to RS1 (check topo view in DS1)\n */\n debugInfo(\"*** STEP 1 ***\");\n rd1 = createReplicationDomain(DS1_ID);\n checkConnection(30, DS1_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_1);\n checkTopoView(new int[] { DS1_ID }, theoricalTopoView);\n /**\n * DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 2 ***\");\n rd2 = createReplicationDomain(DS2_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_2);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * RS2 starts (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 3 ***\");\n rs2 = createReplicationServer(RS2_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(1000);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_3);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n */\n debugInfo(\"*** STEP 4 ***\");\n rd3 = createReplicationDomain(DS3_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_4);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID }, theoricalTopoView);\n /**\n * DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n */\n debugInfo(\"*** STEP 5 ***\");\n rd4 = createReplicationDomain(DS4_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_5);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID }, theoricalTopoView);\n /**\n * DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 6 ***\");\n rd5 = createReplicationDomain(DS5_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_6);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 7 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_7);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 8 ***\");\n rd6 = createReplicationDomain(DS6_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_8);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 9 ***\");\n rd6.disable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n assertFalse(rd6.isConnected());\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_9);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 10 ***\");\n rd6.enable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_10);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 11 ***\");\n rs3.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n checkConnection(30, DS6_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_11);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 12 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_12);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo\n * view in DS1,DS2,DS5,DS6)\n */\n debugInfo(\"*** STEP 13 ***\");\n rs2.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_13);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n } finally {\n endTest();\n }\n }\n\n /**\n * Creates RSInfo for the passed RS\n */\n private RSInfo createRSInfo(int rsId) {\n int groupId = -1;\n String serverUrl = null;\n switch(rsId) {\n case RS1_ID:\n groupId = RS1_GID;\n serverUrl = getHostPort(rs1Port);\n break;\n case RS2_ID:\n groupId = RS2_GID;\n serverUrl = getHostPort(rs2Port);\n break;\n case RS3_ID:\n groupId = RS3_GID;\n serverUrl = getHostPort(rs3Port);\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n return new RSInfo(rsId, serverUrl, TEST_DN_WITH_ROOT_ENTRY_GENID, (byte) groupId, 1);\n }\n\n /**\n * Creates DSInfo for the passed DS, connected to the passed RS\n */\n private DSInfo createDSInfo(int dsId, int rsId) {\n ServerStatus status = ServerStatus.NORMAL_STATUS;\n byte groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n Set eclIncludes = new HashSet();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n switch(dsId) {\n case DS1_ID:\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n // Perform necessary conversions\n boolean assuredFlag = (assuredType != AssuredType.NOT_ASSURED);\n AssuredMode assMode = ((assuredType == AssuredType.SAFE_READ) ? AssuredMode.SAFE_READ_MODE : AssuredMode.SAFE_DATA_MODE);\n List urls = new ArrayList();\n for (String str : refUrls) {\n urls.add(str);\n }\n return new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assMode, (byte) assuredSdLevel, groupId, urls, eclIncludes, eclIncludes, protocolVersion);\n }\n\n /**\n * Creates the topo view to be checked at each step of the test (view that\n * every concerned DS should have)\n */\n private TopoView createTheoreticalTopoViewForStep(int step) {\n List dsList = new ArrayList();\n List rsList = new ArrayList();\n switch(step) {\n case STEP_1:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n break;\n case STEP_2:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_3:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_4:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n break;\n case STEP_5:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n break;\n case STEP_6:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n break;\n case STEP_7:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_8:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_9:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_10:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_11:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n dsList.add(createDSInfo(DS6_ID, RS2_ID));\n break;\n case STEP_12:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_13:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n default:\n fail(\"Unknown test step: \" + step);\n }\n return new TopoView(dsList, rsList);\n }\n\n /**\n * Get the topo view each DS in the provided ds list has and compares it\n * with the theoretical topology view that every body should have at the time\n * this method is called.\n */\n private void checkTopoView(int[] dsIdList, TopoView theoricalTopoView) {\n sleep(500);\n for (int currentDsId : dsIdList) {\n LDAPReplicationDomain rd = null;\n switch(currentDsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n /**\n * Get the topo view of the current analyzed DS\n */\n List internalDsList = rd.getReplicasList();\n // Add info for DS itself:\n // we need to clone the list as we don't want to modify the list kept\n // inside the DS.\n List dsList = new ArrayList();\n for (DSInfo aDsInfo : internalDsList) {\n dsList.add(aDsInfo);\n }\n int dsId = rd.getServerId();\n int rsId = rd.getRsServerId();\n ServerStatus status = rd.getStatus();\n boolean assuredFlag = rd.isAssured();\n AssuredMode assuredMode = rd.getAssuredMode();\n byte safeDataLevel = rd.getAssuredSdLevel();\n byte groupId = rd.getGroupId();\n List refUrls = rd.getRefUrls();\n Set eclInclude = rd.getEclIncludes();\n Set eclIncludeForDeletes = rd.getEclIncludesForDeletes();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n DSInfo dsInfo = new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assuredMode, safeDataLevel, groupId, refUrls, eclInclude, eclIncludeForDeletes, protocolVersion);\n dsList.add(dsInfo);\n TopoView dsTopoView = new TopoView(dsList, rd.getRsList());\n /**\n * Compare to what is the expected view\n */\n assertEquals(dsTopoView, theoricalTopoView, \" in DSid=\" + currentDsId);\n }\n }\n\n /**\n * Bag class representing a view of the topology at a given time\n * (who is connected to who, what are the config parameters...)\n */\n private class TopoView {\n\n private List dsList = null;\n\n private List rsList = null;\n\n public TopoView(List dsList, List rsList) {\n assertNotNull(dsList);\n assertNotNull(rsList);\n this.dsList = dsList;\n this.rsList = rsList;\n }\n\n public boolean equals(Object obj) {\n assertNotNull(obj);\n assertFalse(obj.getClass() != this.getClass());\n TopoView topoView = (TopoView) obj;\n // Check dsList\n if (topoView.dsList.size() != dsList.size())\n return false;\n for (DSInfo dsInfo : topoView.dsList) {\n int found = 0;\n for (DSInfo thisDsInfo : dsList) {\n if (thisDsInfo.equals(dsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as dsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n // Check rsList\n if (topoView.rsList.size() != rsList.size())\n return false;\n for (RSInfo rsInfo : topoView.rsList) {\n int found = 0;\n for (RSInfo thisRsInfo : rsList) {\n if (thisRsInfo.equals(rsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as rsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n return true;\n }\n\n public String toString() {\n String dsStr = \"\";\n for (DSInfo dsInfo : dsList) {\n dsStr += dsInfo.toString() + \"\\n----------------------------\\n\";\n }\n String rsStr = \"\";\n for (RSInfo rsInfo : rsList) {\n rsStr += rsInfo.toString() + \"\\n----------------------------\\n\";\n }\n return (\"TopoView:\" + \"\\n----------------------------\\n\" + \"CONNECTED DS SERVERS:\\n\" + dsStr + \"CONNECTED RS SERVERS:\\n\" + rsStr);\n }\n }\n\n private String getHostPort(int port) {\n return LOCAL_HOST_NAME + \":\" + port;\n }\n}\n"} {"task_id": "Java_1925", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/ForgeRock/opendj-community-edition/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java", "mask_start_position": 12941, "mask_end_position": 12953, "canonical_solution": "return null;", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport java.net.UnknownHostException;\nimport static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;\nimport static org.opends.server.loggers.ErrorLogger.logError;\nimport static org.opends.server.loggers.debug.DebugLogger.debugEnabled;\nimport static org.opends.server.loggers.debug.DebugLogger.getTracer;\nimport static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\nimport org.opends.messages.Category;\nimport org.opends.messages.Message;\nimport org.opends.messages.Severity;\nimport org.opends.server.TestCaseUtils;\nimport org.opends.server.admin.std.meta.ReplicationDomainCfgDefn.AssuredType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.loggers.debug.DebugTracer;\nimport org.opends.server.replication.ReplicationTestCase;\nimport org.opends.server.replication.common.AssuredMode;\nimport org.opends.server.replication.common.DSInfo;\nimport org.opends.server.replication.common.RSInfo;\nimport org.opends.server.replication.common.ServerStatus;\nimport org.opends.server.replication.protocol.ProtocolVersion;\nimport org.opends.server.replication.server.ReplServerFakeConfiguration;\nimport org.opends.server.replication.server.ReplicationServer;\nimport org.opends.server.types.DN;\nimport org.opends.server.types.DirectoryException;\nimport org.opends.server.util.StaticUtils;\nimport org.testng.annotations.Test;\n\n/**\n * Some tests to know if at any time the view DSs and RSs have of the current\n * topology is accurate, even after some connections, disconnections and\n * re-connections events.\n */\npublic class TopologyViewTest extends ReplicationTestCase {\n\n // Server id definitions\n private static final int DS1_ID = 1;\n\n private static final int DS2_ID = 2;\n\n private static final int DS3_ID = 3;\n\n private static final int DS4_ID = 4;\n\n private static final int DS5_ID = 5;\n\n private static final int DS6_ID = 6;\n\n private static final int RS1_ID = 51;\n\n private static final int RS2_ID = 52;\n\n private static final int RS3_ID = 53;\n\n // Group id definitions\n private static final int DS1_GID = 1;\n\n private static final int DS2_GID = 1;\n\n private static final int DS3_GID = 2;\n\n private static final int DS4_GID = 2;\n\n private static final int DS5_GID = 3;\n\n private static final int DS6_GID = 3;\n\n private static final int RS1_GID = 1;\n\n private static final int RS2_GID = 2;\n\n private static final int RS3_GID = 3;\n\n // Assured conf definitions\n private static final AssuredType DS1_AT = AssuredType.NOT_ASSURED;\n\n private static final int DS1_SDL = -1;\n\n private static SortedSet DS1_RU = new TreeSet();\n\n private static final AssuredType DS2_AT = AssuredType.SAFE_READ;\n\n private static final int DS2_SDL = -1;\n\n private static SortedSet DS2_RU = new TreeSet();\n\n private static final AssuredType DS3_AT = AssuredType.SAFE_DATA;\n\n private static final int DS3_SDL = 1;\n\n private static SortedSet DS3_RU = new TreeSet();\n\n private static final AssuredType DS4_AT = AssuredType.SAFE_READ;\n\n private static final int DS4_SDL = -1;\n\n private static SortedSet DS4_RU = new TreeSet();\n\n private static final AssuredType DS5_AT = AssuredType.SAFE_DATA;\n\n private static final int DS5_SDL = 2;\n\n private static SortedSet DS5_RU = new TreeSet();\n\n private static final AssuredType DS6_AT = AssuredType.SAFE_READ;\n\n private static final int DS6_SDL = -1;\n\n private static SortedSet DS6_RU = new TreeSet();\n\n private static String LOCAL_HOST_NAME;\n\n static {\n DS2_RU.add(\"ldap://fake_url_for_ds2\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_A\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_B\");\n try {\n LOCAL_HOST_NAME = InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n fail(\"Unable to resolve local host name\", e);\n }\n }\n\n private int rs1Port = -1;\n\n private int rs2Port = -1;\n\n private int rs3Port = -1;\n\n private LDAPReplicationDomain rd1 = null;\n\n private LDAPReplicationDomain rd2 = null;\n\n private LDAPReplicationDomain rd3 = null;\n\n private LDAPReplicationDomain rd4 = null;\n\n private LDAPReplicationDomain rd5 = null;\n\n private LDAPReplicationDomain rd6 = null;\n\n private ReplicationServer rs1 = null;\n\n private ReplicationServer rs2 = null;\n\n private ReplicationServer rs3 = null;\n\n // The tracer object for the debug logger\n private static final DebugTracer TRACER = getTracer();\n\n private void debugInfo(String s) {\n logError(Message.raw(Category.SYNC, Severity.NOTICE, s));\n if (debugEnabled()) {\n TRACER.debugInfo(\"** TEST **\" + s);\n }\n }\n\n private void initTest() {\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n rd1 = null;\n rd2 = null;\n rd3 = null;\n rd4 = null;\n rd5 = null;\n rd6 = null;\n rs1 = null;\n rs2 = null;\n rs3 = null;\n findFreePorts();\n }\n\n private void endTest() {\n if (rd1 != null) {\n rd1.shutdown();\n rd1 = null;\n }\n if (rd2 != null) {\n rd2.shutdown();\n rd2 = null;\n }\n if (rd3 != null) {\n rd3.shutdown();\n rd3 = null;\n }\n if (rd4 != null) {\n rd4.shutdown();\n rd4 = null;\n }\n if (rd5 != null) {\n rd5.shutdown();\n rd5 = null;\n }\n if (rd6 != null) {\n rd6.shutdown();\n rd6 = null;\n }\n try {\n // Clear any reference to a domain in synchro plugin\n MultimasterReplication.deleteDomain(DN.decode(TEST_ROOT_DN_STRING));\n } catch (DirectoryException ex) {\n fail(\"Error deleting reference to domain: \" + TEST_ROOT_DN_STRING);\n }\n if (rs1 != null) {\n rs1.clearDb();\n rs1.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs1.getDbDirName()));\n rs1 = null;\n }\n if (rs2 != null) {\n rs2.clearDb();\n rs2.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs2.getDbDirName()));\n rs2 = null;\n }\n if (rs3 != null) {\n rs3.clearDb();\n rs3.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs3.getDbDirName()));\n rs3 = null;\n }\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n }\n\n private void sleep(long time) {\n try {\n Thread.sleep(time);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n }\n\n /**\n * Check connection of the provided replication domain to the provided\n * replication server. Waits for connection to be ok up to secTimeout seconds\n * before failing.\n */\n private void checkConnection(int secTimeout, int dsId, int rsId) {\n int rsPort = -1;\n LDAPReplicationDomain rd = null;\n switch(dsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n int nSec = 0;\n // Go out of the loop only if connection is verified or if timeout occurs\n while (true) {\n // Test connection\n boolean connected = rd.isConnected();\n int rdPort = -1;\n boolean rightPort = false;\n if (connected) {\n String serverStr = rd.getReplicationServer();\n int index = serverStr.lastIndexOf(':');\n if ((index == -1) || (index >= serverStr.length()))\n fail(\"Enable to find port number in: \" + serverStr);\n String rdPortStr = serverStr.substring(index + 1);\n try {\n rdPort = (new Integer(rdPortStr)).intValue();\n } catch (Exception e) {\n fail(\"Enable to get an int from: \" + rdPortStr);\n }\n if (rdPort == rsPort)\n rightPort = true;\n }\n if (connected && rightPort) {\n // Connection verified\n debugInfo(\"checkConnection: connection from domain \" + dsId + \" to\" + \" replication server \" + rsId + \" obtained after \" + nSec + \" seconds.\");\n return;\n }\n // Sleep 1 second\n try {\n Thread.sleep(1000);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n nSec++;\n if (nSec > secTimeout) {\n // Timeout reached, end with error\n fail(\"checkConnection: could not verify connection from domain \" + dsId + \" to replication server \" + rsId + \" after \" + secTimeout + \" seconds.\" + \" Domain connected: \" + connected + \", connection port: \" + rdPort + \" (should be: \" + rsPort + \")\");\n }\n }\n }\n\n /**\n * Find needed free TCP ports.\n */\n private void findFreePorts() {\n try {\n ServerSocket socket1 = TestCaseUtils.bindFreePort();\n ServerSocket socket2 = TestCaseUtils.bindFreePort();\n ServerSocket socket3 = TestCaseUtils.bindFreePort();\n rs1Port = socket1.getLocalPort();\n rs2Port = socket2.getLocalPort();\n rs3Port = socket3.getLocalPort();\n socket1.close();\n socket2.close();\n socket3.close();\n } catch (IOException e) {\n fail(\"Unable to determinate some free ports \" + stackTraceToSingleLineString(e));\n }\n }\n\n /**\n * Creates the list of servers to represent the RS topology excluding the\n * RS whose id is passed.\n */\n private SortedSet createRSListExceptOne(int rsIdToExclude) {\n SortedSet replServers = new TreeSet();\n if (rsIdToExclude != RS1_ID) {\n replServers.add(getHostPort(rs1Port));\n }\n if (rsIdToExclude != RS2_ID) {\n replServers.add(getHostPort(rs2Port));\n }\n if (rsIdToExclude != RS3_ID) {\n replServers.add(getHostPort(rs3Port));\n }\n return replServers;\n }\n\n private ReplicationServer createReplicationServer(int rsId, String testCase) {\n try {\n SortedSet replServers = createRSListExceptOne(rsId);\n int rsPort = -1;\n int groupId = -1;\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n groupId = RS1_GID;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n groupId = RS2_GID;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n groupId = RS3_GID;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n String dir = \"topologyViewTest\" + rsId + testCase + \"Db\";\n ReplServerFakeConfiguration conf = new ReplServerFakeConfiguration(rsPort, dir, 0, rsId, 0, 100, replServers, groupId, 1000, 5000);\n ReplicationServer replicationServer = new ReplicationServer(conf);\n return replicationServer;\n } catch (Exception e) {\n fail(\"createReplicationServer \" + stackTraceToSingleLineString(e));\n }\n ", "post_mask_code": "\n }\n\n /**\n * Creates and starts a new ReplicationDomain with the correct list of\n * know RSs according to DS id\n */\n private LDAPReplicationDomain createReplicationDomain(int dsId) {\n try {\n SortedSet replServers = new TreeSet();\n int groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n // Fill rs list according to defined scenario (see testTopologyChanges\n switch(dsId) {\n case DS1_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n DN baseDn = DN.decode(TEST_ROOT_DN_STRING);\n DomainFakeCfg domainConf = new DomainFakeCfg(baseDn, dsId, replServers, assuredType, assuredSdLevel, groupId, 0, refUrls);\n LDAPReplicationDomain replicationDomain = MultimasterReplication.createNewDomain(domainConf);\n replicationDomain.start();\n return replicationDomain;\n } catch (Exception e) {\n fail(\"createReplicationDomain \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n // Definitions of steps for the test case\n private static final int STEP_1 = 1;\n\n private static final int STEP_2 = 2;\n\n private static final int STEP_3 = 3;\n\n private static final int STEP_4 = 4;\n\n private static final int STEP_5 = 5;\n\n private static final int STEP_6 = 6;\n\n private static final int STEP_7 = 7;\n\n private static final int STEP_8 = 8;\n\n private static final int STEP_9 = 9;\n\n private static final int STEP_10 = 10;\n\n private static final int STEP_11 = 11;\n\n private static final int STEP_12 = 12;\n\n private static final int STEP_13 = 13;\n\n /**\n * Perform connections/disconnections of DS/RS. Uses various config parameters\n * that are embedded in topo info to check if they are well transported.\n * This tests:\n * - if topo msgs are exchanged when needed and reflect topo reality (who is\n * connected to who)\n * - if topo msgs transport config params in terms of assured replication,\n * group id... that reflect what is configured in the DSs.\n *\n * Full topo is:\n * (GID=group id, A=assured, NA=not assured, SR=safe read, SD=safe data,\n * SDL=safe data level, RUF=ref urls filled, RUE=ref urls empty)\n * Except if otherwise stated, RSs and DSs are aware of every others existence\n * - RS1 with GID=1\n * - RS2 with GID=2\n * - RS3 with GID=3\n * - DS1 with GID=1, NA\n * - DS2 with GID=1, A, SR, RUF\n * - DS3 with GID=2, A, SD, SDL=1 (DS3 does not know RS1 and RS3)\n * - DS4 with GID=2, A, SR, RUE (DS4 does not know RS1 and RS3)\n * - DS5 with GID=3, A, SD, SDL=2 (DS5 does not know RS1)\n * - DS6 with GID=3, A, SR, RUF (DS6 does not know RS1)\n * Scenario is:\n * - RS1 starts\n * - DS1 starts and connects to RS1 (check topo view in DS1)\n * - DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n * - RS2 starts (check topo view in DS1,DS2)\n * - DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n * - DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n * - DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - RS3 starts (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n * - RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo view\n * in DS1,DS2,DS5,DS6)\n * @throws Exception If a problem occurred\n */\n @Test(enabled = true, groups = \"slow\")\n public void testTopologyChanges() throws Exception {\n String testCase = \"testTopologyChanges\";\n debugInfo(\"Starting \" + testCase);\n initTest();\n TopoView theoricalTopoView = null;\n try {\n /**\n * RS1 starts\n */\n debugInfo(\"*** STEP 0 ***\");\n rs1 = createReplicationServer(RS1_ID, testCase);\n /**\n * DS1 starts and connects to RS1 (check topo view in DS1)\n */\n debugInfo(\"*** STEP 1 ***\");\n rd1 = createReplicationDomain(DS1_ID);\n checkConnection(30, DS1_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_1);\n checkTopoView(new int[] { DS1_ID }, theoricalTopoView);\n /**\n * DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 2 ***\");\n rd2 = createReplicationDomain(DS2_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_2);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * RS2 starts (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 3 ***\");\n rs2 = createReplicationServer(RS2_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(1000);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_3);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n */\n debugInfo(\"*** STEP 4 ***\");\n rd3 = createReplicationDomain(DS3_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_4);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID }, theoricalTopoView);\n /**\n * DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n */\n debugInfo(\"*** STEP 5 ***\");\n rd4 = createReplicationDomain(DS4_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_5);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID }, theoricalTopoView);\n /**\n * DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 6 ***\");\n rd5 = createReplicationDomain(DS5_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_6);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 7 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_7);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 8 ***\");\n rd6 = createReplicationDomain(DS6_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_8);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 9 ***\");\n rd6.disable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n assertFalse(rd6.isConnected());\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_9);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 10 ***\");\n rd6.enable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_10);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 11 ***\");\n rs3.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n checkConnection(30, DS6_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_11);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 12 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_12);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo\n * view in DS1,DS2,DS5,DS6)\n */\n debugInfo(\"*** STEP 13 ***\");\n rs2.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_13);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n } finally {\n endTest();\n }\n }\n\n /**\n * Creates RSInfo for the passed RS\n */\n private RSInfo createRSInfo(int rsId) {\n int groupId = -1;\n String serverUrl = null;\n switch(rsId) {\n case RS1_ID:\n groupId = RS1_GID;\n serverUrl = getHostPort(rs1Port);\n break;\n case RS2_ID:\n groupId = RS2_GID;\n serverUrl = getHostPort(rs2Port);\n break;\n case RS3_ID:\n groupId = RS3_GID;\n serverUrl = getHostPort(rs3Port);\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n return new RSInfo(rsId, serverUrl, TEST_DN_WITH_ROOT_ENTRY_GENID, (byte) groupId, 1);\n }\n\n /**\n * Creates DSInfo for the passed DS, connected to the passed RS\n */\n private DSInfo createDSInfo(int dsId, int rsId) {\n ServerStatus status = ServerStatus.NORMAL_STATUS;\n byte groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n Set eclIncludes = new HashSet();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n switch(dsId) {\n case DS1_ID:\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n // Perform necessary conversions\n boolean assuredFlag = (assuredType != AssuredType.NOT_ASSURED);\n AssuredMode assMode = ((assuredType == AssuredType.SAFE_READ) ? AssuredMode.SAFE_READ_MODE : AssuredMode.SAFE_DATA_MODE);\n List urls = new ArrayList();\n for (String str : refUrls) {\n urls.add(str);\n }\n return new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assMode, (byte) assuredSdLevel, groupId, urls, eclIncludes, eclIncludes, protocolVersion);\n }\n\n /**\n * Creates the topo view to be checked at each step of the test (view that\n * every concerned DS should have)\n */\n private TopoView createTheoreticalTopoViewForStep(int step) {\n List dsList = new ArrayList();\n List rsList = new ArrayList();\n switch(step) {\n case STEP_1:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n break;\n case STEP_2:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_3:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_4:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n break;\n case STEP_5:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n break;\n case STEP_6:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n break;\n case STEP_7:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_8:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_9:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_10:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_11:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n dsList.add(createDSInfo(DS6_ID, RS2_ID));\n break;\n case STEP_12:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_13:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n default:\n fail(\"Unknown test step: \" + step);\n }\n return new TopoView(dsList, rsList);\n }\n\n /**\n * Get the topo view each DS in the provided ds list has and compares it\n * with the theoretical topology view that every body should have at the time\n * this method is called.\n */\n private void checkTopoView(int[] dsIdList, TopoView theoricalTopoView) {\n sleep(500);\n for (int currentDsId : dsIdList) {\n LDAPReplicationDomain rd = null;\n switch(currentDsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n /**\n * Get the topo view of the current analyzed DS\n */\n List internalDsList = rd.getReplicasList();\n // Add info for DS itself:\n // we need to clone the list as we don't want to modify the list kept\n // inside the DS.\n List dsList = new ArrayList();\n for (DSInfo aDsInfo : internalDsList) {\n dsList.add(aDsInfo);\n }\n int dsId = rd.getServerId();\n int rsId = rd.getRsServerId();\n ServerStatus status = rd.getStatus();\n boolean assuredFlag = rd.isAssured();\n AssuredMode assuredMode = rd.getAssuredMode();\n byte safeDataLevel = rd.getAssuredSdLevel();\n byte groupId = rd.getGroupId();\n List refUrls = rd.getRefUrls();\n Set eclInclude = rd.getEclIncludes();\n Set eclIncludeForDeletes = rd.getEclIncludesForDeletes();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n DSInfo dsInfo = new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assuredMode, safeDataLevel, groupId, refUrls, eclInclude, eclIncludeForDeletes, protocolVersion);\n dsList.add(dsInfo);\n TopoView dsTopoView = new TopoView(dsList, rd.getRsList());\n /**\n * Compare to what is the expected view\n */\n assertEquals(dsTopoView, theoricalTopoView, \" in DSid=\" + currentDsId);\n }\n }\n\n /**\n * Bag class representing a view of the topology at a given time\n * (who is connected to who, what are the config parameters...)\n */\n private class TopoView {\n\n private List dsList = null;\n\n private List rsList = null;\n\n public TopoView(List dsList, List rsList) {\n assertNotNull(dsList);\n assertNotNull(rsList);\n this.dsList = dsList;\n this.rsList = rsList;\n }\n\n public boolean equals(Object obj) {\n assertNotNull(obj);\n assertFalse(obj.getClass() != this.getClass());\n TopoView topoView = (TopoView) obj;\n // Check dsList\n if (topoView.dsList.size() != dsList.size())\n return false;\n for (DSInfo dsInfo : topoView.dsList) {\n int found = 0;\n for (DSInfo thisDsInfo : dsList) {\n if (thisDsInfo.equals(dsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as dsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n // Check rsList\n if (topoView.rsList.size() != rsList.size())\n return false;\n for (RSInfo rsInfo : topoView.rsList) {\n int found = 0;\n for (RSInfo thisRsInfo : rsList) {\n if (thisRsInfo.equals(rsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as rsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n return true;\n }\n\n public String toString() {\n String dsStr = \"\";\n for (DSInfo dsInfo : dsList) {\n dsStr += dsInfo.toString() + \"\\n----------------------------\\n\";\n }\n String rsStr = \"\";\n for (RSInfo rsInfo : rsList) {\n rsStr += rsInfo.toString() + \"\\n----------------------------\\n\";\n }\n return (\"TopoView:\" + \"\\n----------------------------\\n\" + \"CONNECTED DS SERVERS:\\n\" + dsStr + \"CONNECTED RS SERVERS:\\n\" + rsStr);\n }\n }\n\n private String getHostPort(int port) {\n return LOCAL_HOST_NAME + \":\" + port;\n }\n}\n"} {"task_id": "Java_1926", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/ForgeRock/opendj-community-edition/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java", "mask_start_position": 12958, "mask_end_position": 12959, "canonical_solution": "}", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport java.net.UnknownHostException;\nimport static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;\nimport static org.opends.server.loggers.ErrorLogger.logError;\nimport static org.opends.server.loggers.debug.DebugLogger.debugEnabled;\nimport static org.opends.server.loggers.debug.DebugLogger.getTracer;\nimport static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\nimport org.opends.messages.Category;\nimport org.opends.messages.Message;\nimport org.opends.messages.Severity;\nimport org.opends.server.TestCaseUtils;\nimport org.opends.server.admin.std.meta.ReplicationDomainCfgDefn.AssuredType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.loggers.debug.DebugTracer;\nimport org.opends.server.replication.ReplicationTestCase;\nimport org.opends.server.replication.common.AssuredMode;\nimport org.opends.server.replication.common.DSInfo;\nimport org.opends.server.replication.common.RSInfo;\nimport org.opends.server.replication.common.ServerStatus;\nimport org.opends.server.replication.protocol.ProtocolVersion;\nimport org.opends.server.replication.server.ReplServerFakeConfiguration;\nimport org.opends.server.replication.server.ReplicationServer;\nimport org.opends.server.types.DN;\nimport org.opends.server.types.DirectoryException;\nimport org.opends.server.util.StaticUtils;\nimport org.testng.annotations.Test;\n\n/**\n * Some tests to know if at any time the view DSs and RSs have of the current\n * topology is accurate, even after some connections, disconnections and\n * re-connections events.\n */\npublic class TopologyViewTest extends ReplicationTestCase {\n\n // Server id definitions\n private static final int DS1_ID = 1;\n\n private static final int DS2_ID = 2;\n\n private static final int DS3_ID = 3;\n\n private static final int DS4_ID = 4;\n\n private static final int DS5_ID = 5;\n\n private static final int DS6_ID = 6;\n\n private static final int RS1_ID = 51;\n\n private static final int RS2_ID = 52;\n\n private static final int RS3_ID = 53;\n\n // Group id definitions\n private static final int DS1_GID = 1;\n\n private static final int DS2_GID = 1;\n\n private static final int DS3_GID = 2;\n\n private static final int DS4_GID = 2;\n\n private static final int DS5_GID = 3;\n\n private static final int DS6_GID = 3;\n\n private static final int RS1_GID = 1;\n\n private static final int RS2_GID = 2;\n\n private static final int RS3_GID = 3;\n\n // Assured conf definitions\n private static final AssuredType DS1_AT = AssuredType.NOT_ASSURED;\n\n private static final int DS1_SDL = -1;\n\n private static SortedSet DS1_RU = new TreeSet();\n\n private static final AssuredType DS2_AT = AssuredType.SAFE_READ;\n\n private static final int DS2_SDL = -1;\n\n private static SortedSet DS2_RU = new TreeSet();\n\n private static final AssuredType DS3_AT = AssuredType.SAFE_DATA;\n\n private static final int DS3_SDL = 1;\n\n private static SortedSet DS3_RU = new TreeSet();\n\n private static final AssuredType DS4_AT = AssuredType.SAFE_READ;\n\n private static final int DS4_SDL = -1;\n\n private static SortedSet DS4_RU = new TreeSet();\n\n private static final AssuredType DS5_AT = AssuredType.SAFE_DATA;\n\n private static final int DS5_SDL = 2;\n\n private static SortedSet DS5_RU = new TreeSet();\n\n private static final AssuredType DS6_AT = AssuredType.SAFE_READ;\n\n private static final int DS6_SDL = -1;\n\n private static SortedSet DS6_RU = new TreeSet();\n\n private static String LOCAL_HOST_NAME;\n\n static {\n DS2_RU.add(\"ldap://fake_url_for_ds2\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_A\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_B\");\n try {\n LOCAL_HOST_NAME = InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n fail(\"Unable to resolve local host name\", e);\n }\n }\n\n private int rs1Port = -1;\n\n private int rs2Port = -1;\n\n private int rs3Port = -1;\n\n private LDAPReplicationDomain rd1 = null;\n\n private LDAPReplicationDomain rd2 = null;\n\n private LDAPReplicationDomain rd3 = null;\n\n private LDAPReplicationDomain rd4 = null;\n\n private LDAPReplicationDomain rd5 = null;\n\n private LDAPReplicationDomain rd6 = null;\n\n private ReplicationServer rs1 = null;\n\n private ReplicationServer rs2 = null;\n\n private ReplicationServer rs3 = null;\n\n // The tracer object for the debug logger\n private static final DebugTracer TRACER = getTracer();\n\n private void debugInfo(String s) {\n logError(Message.raw(Category.SYNC, Severity.NOTICE, s));\n if (debugEnabled()) {\n TRACER.debugInfo(\"** TEST **\" + s);\n }\n }\n\n private void initTest() {\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n rd1 = null;\n rd2 = null;\n rd3 = null;\n rd4 = null;\n rd5 = null;\n rd6 = null;\n rs1 = null;\n rs2 = null;\n rs3 = null;\n findFreePorts();\n }\n\n private void endTest() {\n if (rd1 != null) {\n rd1.shutdown();\n rd1 = null;\n }\n if (rd2 != null) {\n rd2.shutdown();\n rd2 = null;\n }\n if (rd3 != null) {\n rd3.shutdown();\n rd3 = null;\n }\n if (rd4 != null) {\n rd4.shutdown();\n rd4 = null;\n }\n if (rd5 != null) {\n rd5.shutdown();\n rd5 = null;\n }\n if (rd6 != null) {\n rd6.shutdown();\n rd6 = null;\n }\n try {\n // Clear any reference to a domain in synchro plugin\n MultimasterReplication.deleteDomain(DN.decode(TEST_ROOT_DN_STRING));\n } catch (DirectoryException ex) {\n fail(\"Error deleting reference to domain: \" + TEST_ROOT_DN_STRING);\n }\n if (rs1 != null) {\n rs1.clearDb();\n rs1.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs1.getDbDirName()));\n rs1 = null;\n }\n if (rs2 != null) {\n rs2.clearDb();\n rs2.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs2.getDbDirName()));\n rs2 = null;\n }\n if (rs3 != null) {\n rs3.clearDb();\n rs3.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs3.getDbDirName()));\n rs3 = null;\n }\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n }\n\n private void sleep(long time) {\n try {\n Thread.sleep(time);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n }\n\n /**\n * Check connection of the provided replication domain to the provided\n * replication server. Waits for connection to be ok up to secTimeout seconds\n * before failing.\n */\n private void checkConnection(int secTimeout, int dsId, int rsId) {\n int rsPort = -1;\n LDAPReplicationDomain rd = null;\n switch(dsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n int nSec = 0;\n // Go out of the loop only if connection is verified or if timeout occurs\n while (true) {\n // Test connection\n boolean connected = rd.isConnected();\n int rdPort = -1;\n boolean rightPort = false;\n if (connected) {\n String serverStr = rd.getReplicationServer();\n int index = serverStr.lastIndexOf(':');\n if ((index == -1) || (index >= serverStr.length()))\n fail(\"Enable to find port number in: \" + serverStr);\n String rdPortStr = serverStr.substring(index + 1);\n try {\n rdPort = (new Integer(rdPortStr)).intValue();\n } catch (Exception e) {\n fail(\"Enable to get an int from: \" + rdPortStr);\n }\n if (rdPort == rsPort)\n rightPort = true;\n }\n if (connected && rightPort) {\n // Connection verified\n debugInfo(\"checkConnection: connection from domain \" + dsId + \" to\" + \" replication server \" + rsId + \" obtained after \" + nSec + \" seconds.\");\n return;\n }\n // Sleep 1 second\n try {\n Thread.sleep(1000);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n nSec++;\n if (nSec > secTimeout) {\n // Timeout reached, end with error\n fail(\"checkConnection: could not verify connection from domain \" + dsId + \" to replication server \" + rsId + \" after \" + secTimeout + \" seconds.\" + \" Domain connected: \" + connected + \", connection port: \" + rdPort + \" (should be: \" + rsPort + \")\");\n }\n }\n }\n\n /**\n * Find needed free TCP ports.\n */\n private void findFreePorts() {\n try {\n ServerSocket socket1 = TestCaseUtils.bindFreePort();\n ServerSocket socket2 = TestCaseUtils.bindFreePort();\n ServerSocket socket3 = TestCaseUtils.bindFreePort();\n rs1Port = socket1.getLocalPort();\n rs2Port = socket2.getLocalPort();\n rs3Port = socket3.getLocalPort();\n socket1.close();\n socket2.close();\n socket3.close();\n } catch (IOException e) {\n fail(\"Unable to determinate some free ports \" + stackTraceToSingleLineString(e));\n }\n }\n\n /**\n * Creates the list of servers to represent the RS topology excluding the\n * RS whose id is passed.\n */\n private SortedSet createRSListExceptOne(int rsIdToExclude) {\n SortedSet replServers = new TreeSet();\n if (rsIdToExclude != RS1_ID) {\n replServers.add(getHostPort(rs1Port));\n }\n if (rsIdToExclude != RS2_ID) {\n replServers.add(getHostPort(rs2Port));\n }\n if (rsIdToExclude != RS3_ID) {\n replServers.add(getHostPort(rs3Port));\n }\n return replServers;\n }\n\n private ReplicationServer createReplicationServer(int rsId, String testCase) {\n try {\n SortedSet replServers = createRSListExceptOne(rsId);\n int rsPort = -1;\n int groupId = -1;\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n groupId = RS1_GID;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n groupId = RS2_GID;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n groupId = RS3_GID;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n String dir = \"topologyViewTest\" + rsId + testCase + \"Db\";\n ReplServerFakeConfiguration conf = new ReplServerFakeConfiguration(rsPort, dir, 0, rsId, 0, 100, replServers, groupId, 1000, 5000);\n ReplicationServer replicationServer = new ReplicationServer(conf);\n return replicationServer;\n } catch (Exception e) {\n fail(\"createReplicationServer \" + stackTraceToSingleLineString(e));\n }\n return null;\n ", "post_mask_code": "\n\n /**\n * Creates and starts a new ReplicationDomain with the correct list of\n * know RSs according to DS id\n */\n private LDAPReplicationDomain createReplicationDomain(int dsId) {\n try {\n SortedSet replServers = new TreeSet();\n int groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n // Fill rs list according to defined scenario (see testTopologyChanges\n switch(dsId) {\n case DS1_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n DN baseDn = DN.decode(TEST_ROOT_DN_STRING);\n DomainFakeCfg domainConf = new DomainFakeCfg(baseDn, dsId, replServers, assuredType, assuredSdLevel, groupId, 0, refUrls);\n LDAPReplicationDomain replicationDomain = MultimasterReplication.createNewDomain(domainConf);\n replicationDomain.start();\n return replicationDomain;\n } catch (Exception e) {\n fail(\"createReplicationDomain \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n // Definitions of steps for the test case\n private static final int STEP_1 = 1;\n\n private static final int STEP_2 = 2;\n\n private static final int STEP_3 = 3;\n\n private static final int STEP_4 = 4;\n\n private static final int STEP_5 = 5;\n\n private static final int STEP_6 = 6;\n\n private static final int STEP_7 = 7;\n\n private static final int STEP_8 = 8;\n\n private static final int STEP_9 = 9;\n\n private static final int STEP_10 = 10;\n\n private static final int STEP_11 = 11;\n\n private static final int STEP_12 = 12;\n\n private static final int STEP_13 = 13;\n\n /**\n * Perform connections/disconnections of DS/RS. Uses various config parameters\n * that are embedded in topo info to check if they are well transported.\n * This tests:\n * - if topo msgs are exchanged when needed and reflect topo reality (who is\n * connected to who)\n * - if topo msgs transport config params in terms of assured replication,\n * group id... that reflect what is configured in the DSs.\n *\n * Full topo is:\n * (GID=group id, A=assured, NA=not assured, SR=safe read, SD=safe data,\n * SDL=safe data level, RUF=ref urls filled, RUE=ref urls empty)\n * Except if otherwise stated, RSs and DSs are aware of every others existence\n * - RS1 with GID=1\n * - RS2 with GID=2\n * - RS3 with GID=3\n * - DS1 with GID=1, NA\n * - DS2 with GID=1, A, SR, RUF\n * - DS3 with GID=2, A, SD, SDL=1 (DS3 does not know RS1 and RS3)\n * - DS4 with GID=2, A, SR, RUE (DS4 does not know RS1 and RS3)\n * - DS5 with GID=3, A, SD, SDL=2 (DS5 does not know RS1)\n * - DS6 with GID=3, A, SR, RUF (DS6 does not know RS1)\n * Scenario is:\n * - RS1 starts\n * - DS1 starts and connects to RS1 (check topo view in DS1)\n * - DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n * - RS2 starts (check topo view in DS1,DS2)\n * - DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n * - DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n * - DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - RS3 starts (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n * - RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo view\n * in DS1,DS2,DS5,DS6)\n * @throws Exception If a problem occurred\n */\n @Test(enabled = true, groups = \"slow\")\n public void testTopologyChanges() throws Exception {\n String testCase = \"testTopologyChanges\";\n debugInfo(\"Starting \" + testCase);\n initTest();\n TopoView theoricalTopoView = null;\n try {\n /**\n * RS1 starts\n */\n debugInfo(\"*** STEP 0 ***\");\n rs1 = createReplicationServer(RS1_ID, testCase);\n /**\n * DS1 starts and connects to RS1 (check topo view in DS1)\n */\n debugInfo(\"*** STEP 1 ***\");\n rd1 = createReplicationDomain(DS1_ID);\n checkConnection(30, DS1_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_1);\n checkTopoView(new int[] { DS1_ID }, theoricalTopoView);\n /**\n * DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 2 ***\");\n rd2 = createReplicationDomain(DS2_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_2);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * RS2 starts (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 3 ***\");\n rs2 = createReplicationServer(RS2_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(1000);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_3);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n */\n debugInfo(\"*** STEP 4 ***\");\n rd3 = createReplicationDomain(DS3_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_4);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID }, theoricalTopoView);\n /**\n * DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n */\n debugInfo(\"*** STEP 5 ***\");\n rd4 = createReplicationDomain(DS4_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_5);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID }, theoricalTopoView);\n /**\n * DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 6 ***\");\n rd5 = createReplicationDomain(DS5_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_6);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 7 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_7);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 8 ***\");\n rd6 = createReplicationDomain(DS6_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_8);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 9 ***\");\n rd6.disable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n assertFalse(rd6.isConnected());\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_9);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 10 ***\");\n rd6.enable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_10);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 11 ***\");\n rs3.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n checkConnection(30, DS6_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_11);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 12 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_12);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo\n * view in DS1,DS2,DS5,DS6)\n */\n debugInfo(\"*** STEP 13 ***\");\n rs2.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_13);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n } finally {\n endTest();\n }\n }\n\n /**\n * Creates RSInfo for the passed RS\n */\n private RSInfo createRSInfo(int rsId) {\n int groupId = -1;\n String serverUrl = null;\n switch(rsId) {\n case RS1_ID:\n groupId = RS1_GID;\n serverUrl = getHostPort(rs1Port);\n break;\n case RS2_ID:\n groupId = RS2_GID;\n serverUrl = getHostPort(rs2Port);\n break;\n case RS3_ID:\n groupId = RS3_GID;\n serverUrl = getHostPort(rs3Port);\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n return new RSInfo(rsId, serverUrl, TEST_DN_WITH_ROOT_ENTRY_GENID, (byte) groupId, 1);\n }\n\n /**\n * Creates DSInfo for the passed DS, connected to the passed RS\n */\n private DSInfo createDSInfo(int dsId, int rsId) {\n ServerStatus status = ServerStatus.NORMAL_STATUS;\n byte groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n Set eclIncludes = new HashSet();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n switch(dsId) {\n case DS1_ID:\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n // Perform necessary conversions\n boolean assuredFlag = (assuredType != AssuredType.NOT_ASSURED);\n AssuredMode assMode = ((assuredType == AssuredType.SAFE_READ) ? AssuredMode.SAFE_READ_MODE : AssuredMode.SAFE_DATA_MODE);\n List urls = new ArrayList();\n for (String str : refUrls) {\n urls.add(str);\n }\n return new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assMode, (byte) assuredSdLevel, groupId, urls, eclIncludes, eclIncludes, protocolVersion);\n }\n\n /**\n * Creates the topo view to be checked at each step of the test (view that\n * every concerned DS should have)\n */\n private TopoView createTheoreticalTopoViewForStep(int step) {\n List dsList = new ArrayList();\n List rsList = new ArrayList();\n switch(step) {\n case STEP_1:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n break;\n case STEP_2:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_3:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_4:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n break;\n case STEP_5:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n break;\n case STEP_6:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n break;\n case STEP_7:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_8:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_9:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_10:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_11:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n dsList.add(createDSInfo(DS6_ID, RS2_ID));\n break;\n case STEP_12:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_13:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n default:\n fail(\"Unknown test step: \" + step);\n }\n return new TopoView(dsList, rsList);\n }\n\n /**\n * Get the topo view each DS in the provided ds list has and compares it\n * with the theoretical topology view that every body should have at the time\n * this method is called.\n */\n private void checkTopoView(int[] dsIdList, TopoView theoricalTopoView) {\n sleep(500);\n for (int currentDsId : dsIdList) {\n LDAPReplicationDomain rd = null;\n switch(currentDsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n /**\n * Get the topo view of the current analyzed DS\n */\n List internalDsList = rd.getReplicasList();\n // Add info for DS itself:\n // we need to clone the list as we don't want to modify the list kept\n // inside the DS.\n List dsList = new ArrayList();\n for (DSInfo aDsInfo : internalDsList) {\n dsList.add(aDsInfo);\n }\n int dsId = rd.getServerId();\n int rsId = rd.getRsServerId();\n ServerStatus status = rd.getStatus();\n boolean assuredFlag = rd.isAssured();\n AssuredMode assuredMode = rd.getAssuredMode();\n byte safeDataLevel = rd.getAssuredSdLevel();\n byte groupId = rd.getGroupId();\n List refUrls = rd.getRefUrls();\n Set eclInclude = rd.getEclIncludes();\n Set eclIncludeForDeletes = rd.getEclIncludesForDeletes();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n DSInfo dsInfo = new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assuredMode, safeDataLevel, groupId, refUrls, eclInclude, eclIncludeForDeletes, protocolVersion);\n dsList.add(dsInfo);\n TopoView dsTopoView = new TopoView(dsList, rd.getRsList());\n /**\n * Compare to what is the expected view\n */\n assertEquals(dsTopoView, theoricalTopoView, \" in DSid=\" + currentDsId);\n }\n }\n\n /**\n * Bag class representing a view of the topology at a given time\n * (who is connected to who, what are the config parameters...)\n */\n private class TopoView {\n\n private List dsList = null;\n\n private List rsList = null;\n\n public TopoView(List dsList, List rsList) {\n assertNotNull(dsList);\n assertNotNull(rsList);\n this.dsList = dsList;\n this.rsList = rsList;\n }\n\n public boolean equals(Object obj) {\n assertNotNull(obj);\n assertFalse(obj.getClass() != this.getClass());\n TopoView topoView = (TopoView) obj;\n // Check dsList\n if (topoView.dsList.size() != dsList.size())\n return false;\n for (DSInfo dsInfo : topoView.dsList) {\n int found = 0;\n for (DSInfo thisDsInfo : dsList) {\n if (thisDsInfo.equals(dsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as dsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n // Check rsList\n if (topoView.rsList.size() != rsList.size())\n return false;\n for (RSInfo rsInfo : topoView.rsList) {\n int found = 0;\n for (RSInfo thisRsInfo : rsList) {\n if (thisRsInfo.equals(rsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as rsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n return true;\n }\n\n public String toString() {\n String dsStr = \"\";\n for (DSInfo dsInfo : dsList) {\n dsStr += dsInfo.toString() + \"\\n----------------------------\\n\";\n }\n String rsStr = \"\";\n for (RSInfo rsInfo : rsList) {\n rsStr += rsInfo.toString() + \"\\n----------------------------\\n\";\n }\n return (\"TopoView:\" + \"\\n----------------------------\\n\" + \"CONNECTED DS SERVERS:\\n\" + dsStr + \"CONNECTED RS SERVERS:\\n\" + rsStr);\n }\n }\n\n private String getHostPort(int port) {\n return LOCAL_HOST_NAME + \":\" + port;\n }\n}\n"} {"task_id": "Java_1927", "language": "Java", "task_type": "single_line", "source_file": "java/github/ForgeRock/opendj-community-edition/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java", "mask_start_position": 5323, "mask_end_position": 5336, "canonical_solution": "rs2Port = -1;", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport java.net.UnknownHostException;\nimport static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;\nimport static org.opends.server.loggers.ErrorLogger.logError;\nimport static org.opends.server.loggers.debug.DebugLogger.debugEnabled;\nimport static org.opends.server.loggers.debug.DebugLogger.getTracer;\nimport static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\nimport org.opends.messages.Category;\nimport org.opends.messages.Message;\nimport org.opends.messages.Severity;\nimport org.opends.server.TestCaseUtils;\nimport org.opends.server.admin.std.meta.ReplicationDomainCfgDefn.AssuredType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.loggers.debug.DebugTracer;\nimport org.opends.server.replication.ReplicationTestCase;\nimport org.opends.server.replication.common.AssuredMode;\nimport org.opends.server.replication.common.DSInfo;\nimport org.opends.server.replication.common.RSInfo;\nimport org.opends.server.replication.common.ServerStatus;\nimport org.opends.server.replication.protocol.ProtocolVersion;\nimport org.opends.server.replication.server.ReplServerFakeConfiguration;\nimport org.opends.server.replication.server.ReplicationServer;\nimport org.opends.server.types.DN;\nimport org.opends.server.types.DirectoryException;\nimport org.opends.server.util.StaticUtils;\nimport org.testng.annotations.Test;\n\n/**\n * Some tests to know if at any time the view DSs and RSs have of the current\n * topology is accurate, even after some connections, disconnections and\n * re-connections events.\n */\npublic class TopologyViewTest extends ReplicationTestCase {\n\n // Server id definitions\n private static final int DS1_ID = 1;\n\n private static final int DS2_ID = 2;\n\n private static final int DS3_ID = 3;\n\n private static final int DS4_ID = 4;\n\n private static final int DS5_ID = 5;\n\n private static final int DS6_ID = 6;\n\n private static final int RS1_ID = 51;\n\n private static final int RS2_ID = 52;\n\n private static final int RS3_ID = 53;\n\n // Group id definitions\n private static final int DS1_GID = 1;\n\n private static final int DS2_GID = 1;\n\n private static final int DS3_GID = 2;\n\n private static final int DS4_GID = 2;\n\n private static final int DS5_GID = 3;\n\n private static final int DS6_GID = 3;\n\n private static final int RS1_GID = 1;\n\n private static final int RS2_GID = 2;\n\n private static final int RS3_GID = 3;\n\n // Assured conf definitions\n private static final AssuredType DS1_AT = AssuredType.NOT_ASSURED;\n\n private static final int DS1_SDL = -1;\n\n private static SortedSet DS1_RU = new TreeSet();\n\n private static final AssuredType DS2_AT = AssuredType.SAFE_READ;\n\n private static final int DS2_SDL = -1;\n\n private static SortedSet DS2_RU = new TreeSet();\n\n private static final AssuredType DS3_AT = AssuredType.SAFE_DATA;\n\n private static final int DS3_SDL = 1;\n\n private static SortedSet DS3_RU = new TreeSet();\n\n private static final AssuredType DS4_AT = AssuredType.SAFE_READ;\n\n private static final int DS4_SDL = -1;\n\n private static SortedSet DS4_RU = new TreeSet();\n\n private static final AssuredType DS5_AT = AssuredType.SAFE_DATA;\n\n private static final int DS5_SDL = 2;\n\n private static SortedSet DS5_RU = new TreeSet();\n\n private static final AssuredType DS6_AT = AssuredType.SAFE_READ;\n\n private static final int DS6_SDL = -1;\n\n private static SortedSet DS6_RU = new TreeSet();\n\n private static String LOCAL_HOST_NAME;\n\n static {\n DS2_RU.add(\"ldap://fake_url_for_ds2\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_A\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_B\");\n try {\n LOCAL_HOST_NAME = InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n fail(\"Unable to resolve local host name\", e);\n }\n }\n\n private int rs1Port = -1;\n\n private int rs2Port = -1;\n\n private int rs3Port = -1;\n\n private LDAPReplicationDomain rd1 = null;\n\n private LDAPReplicationDomain rd2 = null;\n\n private LDAPReplicationDomain rd3 = null;\n\n private LDAPReplicationDomain rd4 = null;\n\n private LDAPReplicationDomain rd5 = null;\n\n private LDAPReplicationDomain rd6 = null;\n\n private ReplicationServer rs1 = null;\n\n private ReplicationServer rs2 = null;\n\n private ReplicationServer rs3 = null;\n\n // The tracer object for the debug logger\n private static final DebugTracer TRACER = getTracer();\n\n private void debugInfo(String s) {\n logError(Message.raw(Category.SYNC, Severity.NOTICE, s));\n if (debugEnabled()) {\n TRACER.debugInfo(\"** TEST **\" + s);\n }\n }\n\n private void initTest() {\n rs1Port = -1;\n ", "post_mask_code": "\n rs3Port = -1;\n rd1 = null;\n rd2 = null;\n rd3 = null;\n rd4 = null;\n rd5 = null;\n rd6 = null;\n rs1 = null;\n rs2 = null;\n rs3 = null;\n findFreePorts();\n }\n\n private void endTest() {\n if (rd1 != null) {\n rd1.shutdown();\n rd1 = null;\n }\n if (rd2 != null) {\n rd2.shutdown();\n rd2 = null;\n }\n if (rd3 != null) {\n rd3.shutdown();\n rd3 = null;\n }\n if (rd4 != null) {\n rd4.shutdown();\n rd4 = null;\n }\n if (rd5 != null) {\n rd5.shutdown();\n rd5 = null;\n }\n if (rd6 != null) {\n rd6.shutdown();\n rd6 = null;\n }\n try {\n // Clear any reference to a domain in synchro plugin\n MultimasterReplication.deleteDomain(DN.decode(TEST_ROOT_DN_STRING));\n } catch (DirectoryException ex) {\n fail(\"Error deleting reference to domain: \" + TEST_ROOT_DN_STRING);\n }\n if (rs1 != null) {\n rs1.clearDb();\n rs1.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs1.getDbDirName()));\n rs1 = null;\n }\n if (rs2 != null) {\n rs2.clearDb();\n rs2.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs2.getDbDirName()));\n rs2 = null;\n }\n if (rs3 != null) {\n rs3.clearDb();\n rs3.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs3.getDbDirName()));\n rs3 = null;\n }\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n }\n\n private void sleep(long time) {\n try {\n Thread.sleep(time);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n }\n\n /**\n * Check connection of the provided replication domain to the provided\n * replication server. Waits for connection to be ok up to secTimeout seconds\n * before failing.\n */\n private void checkConnection(int secTimeout, int dsId, int rsId) {\n int rsPort = -1;\n LDAPReplicationDomain rd = null;\n switch(dsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n int nSec = 0;\n // Go out of the loop only if connection is verified or if timeout occurs\n while (true) {\n // Test connection\n boolean connected = rd.isConnected();\n int rdPort = -1;\n boolean rightPort = false;\n if (connected) {\n String serverStr = rd.getReplicationServer();\n int index = serverStr.lastIndexOf(':');\n if ((index == -1) || (index >= serverStr.length()))\n fail(\"Enable to find port number in: \" + serverStr);\n String rdPortStr = serverStr.substring(index + 1);\n try {\n rdPort = (new Integer(rdPortStr)).intValue();\n } catch (Exception e) {\n fail(\"Enable to get an int from: \" + rdPortStr);\n }\n if (rdPort == rsPort)\n rightPort = true;\n }\n if (connected && rightPort) {\n // Connection verified\n debugInfo(\"checkConnection: connection from domain \" + dsId + \" to\" + \" replication server \" + rsId + \" obtained after \" + nSec + \" seconds.\");\n return;\n }\n // Sleep 1 second\n try {\n Thread.sleep(1000);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n nSec++;\n if (nSec > secTimeout) {\n // Timeout reached, end with error\n fail(\"checkConnection: could not verify connection from domain \" + dsId + \" to replication server \" + rsId + \" after \" + secTimeout + \" seconds.\" + \" Domain connected: \" + connected + \", connection port: \" + rdPort + \" (should be: \" + rsPort + \")\");\n }\n }\n }\n\n /**\n * Find needed free TCP ports.\n */\n private void findFreePorts() {\n try {\n ServerSocket socket1 = TestCaseUtils.bindFreePort();\n ServerSocket socket2 = TestCaseUtils.bindFreePort();\n ServerSocket socket3 = TestCaseUtils.bindFreePort();\n rs1Port = socket1.getLocalPort();\n rs2Port = socket2.getLocalPort();\n rs3Port = socket3.getLocalPort();\n socket1.close();\n socket2.close();\n socket3.close();\n } catch (IOException e) {\n fail(\"Unable to determinate some free ports \" + stackTraceToSingleLineString(e));\n }\n }\n\n /**\n * Creates the list of servers to represent the RS topology excluding the\n * RS whose id is passed.\n */\n private SortedSet createRSListExceptOne(int rsIdToExclude) {\n SortedSet replServers = new TreeSet();\n if (rsIdToExclude != RS1_ID) {\n replServers.add(getHostPort(rs1Port));\n }\n if (rsIdToExclude != RS2_ID) {\n replServers.add(getHostPort(rs2Port));\n }\n if (rsIdToExclude != RS3_ID) {\n replServers.add(getHostPort(rs3Port));\n }\n return replServers;\n }\n\n private ReplicationServer createReplicationServer(int rsId, String testCase) {\n try {\n SortedSet replServers = createRSListExceptOne(rsId);\n int rsPort = -1;\n int groupId = -1;\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n groupId = RS1_GID;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n groupId = RS2_GID;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n groupId = RS3_GID;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n String dir = \"topologyViewTest\" + rsId + testCase + \"Db\";\n ReplServerFakeConfiguration conf = new ReplServerFakeConfiguration(rsPort, dir, 0, rsId, 0, 100, replServers, groupId, 1000, 5000);\n ReplicationServer replicationServer = new ReplicationServer(conf);\n return replicationServer;\n } catch (Exception e) {\n fail(\"createReplicationServer \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n /**\n * Creates and starts a new ReplicationDomain with the correct list of\n * know RSs according to DS id\n */\n private LDAPReplicationDomain createReplicationDomain(int dsId) {\n try {\n SortedSet replServers = new TreeSet();\n int groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n // Fill rs list according to defined scenario (see testTopologyChanges\n switch(dsId) {\n case DS1_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n DN baseDn = DN.decode(TEST_ROOT_DN_STRING);\n DomainFakeCfg domainConf = new DomainFakeCfg(baseDn, dsId, replServers, assuredType, assuredSdLevel, groupId, 0, refUrls);\n LDAPReplicationDomain replicationDomain = MultimasterReplication.createNewDomain(domainConf);\n replicationDomain.start();\n return replicationDomain;\n } catch (Exception e) {\n fail(\"createReplicationDomain \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n // Definitions of steps for the test case\n private static final int STEP_1 = 1;\n\n private static final int STEP_2 = 2;\n\n private static final int STEP_3 = 3;\n\n private static final int STEP_4 = 4;\n\n private static final int STEP_5 = 5;\n\n private static final int STEP_6 = 6;\n\n private static final int STEP_7 = 7;\n\n private static final int STEP_8 = 8;\n\n private static final int STEP_9 = 9;\n\n private static final int STEP_10 = 10;\n\n private static final int STEP_11 = 11;\n\n private static final int STEP_12 = 12;\n\n private static final int STEP_13 = 13;\n\n /**\n * Perform connections/disconnections of DS/RS. Uses various config parameters\n * that are embedded in topo info to check if they are well transported.\n * This tests:\n * - if topo msgs are exchanged when needed and reflect topo reality (who is\n * connected to who)\n * - if topo msgs transport config params in terms of assured replication,\n * group id... that reflect what is configured in the DSs.\n *\n * Full topo is:\n * (GID=group id, A=assured, NA=not assured, SR=safe read, SD=safe data,\n * SDL=safe data level, RUF=ref urls filled, RUE=ref urls empty)\n * Except if otherwise stated, RSs and DSs are aware of every others existence\n * - RS1 with GID=1\n * - RS2 with GID=2\n * - RS3 with GID=3\n * - DS1 with GID=1, NA\n * - DS2 with GID=1, A, SR, RUF\n * - DS3 with GID=2, A, SD, SDL=1 (DS3 does not know RS1 and RS3)\n * - DS4 with GID=2, A, SR, RUE (DS4 does not know RS1 and RS3)\n * - DS5 with GID=3, A, SD, SDL=2 (DS5 does not know RS1)\n * - DS6 with GID=3, A, SR, RUF (DS6 does not know RS1)\n * Scenario is:\n * - RS1 starts\n * - DS1 starts and connects to RS1 (check topo view in DS1)\n * - DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n * - RS2 starts (check topo view in DS1,DS2)\n * - DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n * - DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n * - DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - RS3 starts (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n * - RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo view\n * in DS1,DS2,DS5,DS6)\n * @throws Exception If a problem occurred\n */\n @Test(enabled = true, groups = \"slow\")\n public void testTopologyChanges() throws Exception {\n String testCase = \"testTopologyChanges\";\n debugInfo(\"Starting \" + testCase);\n initTest();\n TopoView theoricalTopoView = null;\n try {\n /**\n * RS1 starts\n */\n debugInfo(\"*** STEP 0 ***\");\n rs1 = createReplicationServer(RS1_ID, testCase);\n /**\n * DS1 starts and connects to RS1 (check topo view in DS1)\n */\n debugInfo(\"*** STEP 1 ***\");\n rd1 = createReplicationDomain(DS1_ID);\n checkConnection(30, DS1_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_1);\n checkTopoView(new int[] { DS1_ID }, theoricalTopoView);\n /**\n * DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 2 ***\");\n rd2 = createReplicationDomain(DS2_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_2);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * RS2 starts (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 3 ***\");\n rs2 = createReplicationServer(RS2_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(1000);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_3);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n */\n debugInfo(\"*** STEP 4 ***\");\n rd3 = createReplicationDomain(DS3_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_4);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID }, theoricalTopoView);\n /**\n * DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n */\n debugInfo(\"*** STEP 5 ***\");\n rd4 = createReplicationDomain(DS4_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_5);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID }, theoricalTopoView);\n /**\n * DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 6 ***\");\n rd5 = createReplicationDomain(DS5_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_6);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 7 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_7);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 8 ***\");\n rd6 = createReplicationDomain(DS6_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_8);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 9 ***\");\n rd6.disable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n assertFalse(rd6.isConnected());\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_9);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 10 ***\");\n rd6.enable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_10);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 11 ***\");\n rs3.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n checkConnection(30, DS6_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_11);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 12 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_12);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo\n * view in DS1,DS2,DS5,DS6)\n */\n debugInfo(\"*** STEP 13 ***\");\n rs2.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_13);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n } finally {\n endTest();\n }\n }\n\n /**\n * Creates RSInfo for the passed RS\n */\n private RSInfo createRSInfo(int rsId) {\n int groupId = -1;\n String serverUrl = null;\n switch(rsId) {\n case RS1_ID:\n groupId = RS1_GID;\n serverUrl = getHostPort(rs1Port);\n break;\n case RS2_ID:\n groupId = RS2_GID;\n serverUrl = getHostPort(rs2Port);\n break;\n case RS3_ID:\n groupId = RS3_GID;\n serverUrl = getHostPort(rs3Port);\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n return new RSInfo(rsId, serverUrl, TEST_DN_WITH_ROOT_ENTRY_GENID, (byte) groupId, 1);\n }\n\n /**\n * Creates DSInfo for the passed DS, connected to the passed RS\n */\n private DSInfo createDSInfo(int dsId, int rsId) {\n ServerStatus status = ServerStatus.NORMAL_STATUS;\n byte groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n Set eclIncludes = new HashSet();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n switch(dsId) {\n case DS1_ID:\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n // Perform necessary conversions\n boolean assuredFlag = (assuredType != AssuredType.NOT_ASSURED);\n AssuredMode assMode = ((assuredType == AssuredType.SAFE_READ) ? AssuredMode.SAFE_READ_MODE : AssuredMode.SAFE_DATA_MODE);\n List urls = new ArrayList();\n for (String str : refUrls) {\n urls.add(str);\n }\n return new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assMode, (byte) assuredSdLevel, groupId, urls, eclIncludes, eclIncludes, protocolVersion);\n }\n\n /**\n * Creates the topo view to be checked at each step of the test (view that\n * every concerned DS should have)\n */\n private TopoView createTheoreticalTopoViewForStep(int step) {\n List dsList = new ArrayList();\n List rsList = new ArrayList();\n switch(step) {\n case STEP_1:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n break;\n case STEP_2:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_3:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_4:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n break;\n case STEP_5:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n break;\n case STEP_6:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n break;\n case STEP_7:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_8:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_9:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_10:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_11:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n dsList.add(createDSInfo(DS6_ID, RS2_ID));\n break;\n case STEP_12:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_13:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n default:\n fail(\"Unknown test step: \" + step);\n }\n return new TopoView(dsList, rsList);\n }\n\n /**\n * Get the topo view each DS in the provided ds list has and compares it\n * with the theoretical topology view that every body should have at the time\n * this method is called.\n */\n private void checkTopoView(int[] dsIdList, TopoView theoricalTopoView) {\n sleep(500);\n for (int currentDsId : dsIdList) {\n LDAPReplicationDomain rd = null;\n switch(currentDsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n /**\n * Get the topo view of the current analyzed DS\n */\n List internalDsList = rd.getReplicasList();\n // Add info for DS itself:\n // we need to clone the list as we don't want to modify the list kept\n // inside the DS.\n List dsList = new ArrayList();\n for (DSInfo aDsInfo : internalDsList) {\n dsList.add(aDsInfo);\n }\n int dsId = rd.getServerId();\n int rsId = rd.getRsServerId();\n ServerStatus status = rd.getStatus();\n boolean assuredFlag = rd.isAssured();\n AssuredMode assuredMode = rd.getAssuredMode();\n byte safeDataLevel = rd.getAssuredSdLevel();\n byte groupId = rd.getGroupId();\n List refUrls = rd.getRefUrls();\n Set eclInclude = rd.getEclIncludes();\n Set eclIncludeForDeletes = rd.getEclIncludesForDeletes();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n DSInfo dsInfo = new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assuredMode, safeDataLevel, groupId, refUrls, eclInclude, eclIncludeForDeletes, protocolVersion);\n dsList.add(dsInfo);\n TopoView dsTopoView = new TopoView(dsList, rd.getRsList());\n /**\n * Compare to what is the expected view\n */\n assertEquals(dsTopoView, theoricalTopoView, \" in DSid=\" + currentDsId);\n }\n }\n\n /**\n * Bag class representing a view of the topology at a given time\n * (who is connected to who, what are the config parameters...)\n */\n private class TopoView {\n\n private List dsList = null;\n\n private List rsList = null;\n\n public TopoView(List dsList, List rsList) {\n assertNotNull(dsList);\n assertNotNull(rsList);\n this.dsList = dsList;\n this.rsList = rsList;\n }\n\n public boolean equals(Object obj) {\n assertNotNull(obj);\n assertFalse(obj.getClass() != this.getClass());\n TopoView topoView = (TopoView) obj;\n // Check dsList\n if (topoView.dsList.size() != dsList.size())\n return false;\n for (DSInfo dsInfo : topoView.dsList) {\n int found = 0;\n for (DSInfo thisDsInfo : dsList) {\n if (thisDsInfo.equals(dsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as dsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n // Check rsList\n if (topoView.rsList.size() != rsList.size())\n return false;\n for (RSInfo rsInfo : topoView.rsList) {\n int found = 0;\n for (RSInfo thisRsInfo : rsList) {\n if (thisRsInfo.equals(rsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as rsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n return true;\n }\n\n public String toString() {\n String dsStr = \"\";\n for (DSInfo dsInfo : dsList) {\n dsStr += dsInfo.toString() + \"\\n----------------------------\\n\";\n }\n String rsStr = \"\";\n for (RSInfo rsInfo : rsList) {\n rsStr += rsInfo.toString() + \"\\n----------------------------\\n\";\n }\n return (\"TopoView:\" + \"\\n----------------------------\\n\" + \"CONNECTED DS SERVERS:\\n\" + dsStr + \"CONNECTED RS SERVERS:\\n\" + rsStr);\n }\n }\n\n private String getHostPort(int port) {\n return LOCAL_HOST_NAME + \":\" + port;\n }\n}\n"} {"task_id": "Java_1928", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/ForgeRock/opendj-community-edition/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java", "mask_start_position": 11259, "mask_end_position": 11724, "canonical_solution": "private SortedSet createRSListExceptOne(int rsIdToExclude) {\n SortedSet replServers = new TreeSet();\n if (rsIdToExclude != RS1_ID) {\n replServers.add(getHostPort(rs1Port));\n }\n if (rsIdToExclude != RS2_ID) {\n replServers.add(getHostPort(rs2Port));\n }\n if (rsIdToExclude != RS3_ID) {\n replServers.add(getHostPort(rs3Port));\n }\n return replServers;\n }", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport java.net.UnknownHostException;\nimport static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;\nimport static org.opends.server.loggers.ErrorLogger.logError;\nimport static org.opends.server.loggers.debug.DebugLogger.debugEnabled;\nimport static org.opends.server.loggers.debug.DebugLogger.getTracer;\nimport static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\nimport org.opends.messages.Category;\nimport org.opends.messages.Message;\nimport org.opends.messages.Severity;\nimport org.opends.server.TestCaseUtils;\nimport org.opends.server.admin.std.meta.ReplicationDomainCfgDefn.AssuredType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.loggers.debug.DebugTracer;\nimport org.opends.server.replication.ReplicationTestCase;\nimport org.opends.server.replication.common.AssuredMode;\nimport org.opends.server.replication.common.DSInfo;\nimport org.opends.server.replication.common.RSInfo;\nimport org.opends.server.replication.common.ServerStatus;\nimport org.opends.server.replication.protocol.ProtocolVersion;\nimport org.opends.server.replication.server.ReplServerFakeConfiguration;\nimport org.opends.server.replication.server.ReplicationServer;\nimport org.opends.server.types.DN;\nimport org.opends.server.types.DirectoryException;\nimport org.opends.server.util.StaticUtils;\nimport org.testng.annotations.Test;\n\n/**\n * Some tests to know if at any time the view DSs and RSs have of the current\n * topology is accurate, even after some connections, disconnections and\n * re-connections events.\n */\npublic class TopologyViewTest extends ReplicationTestCase {\n\n // Server id definitions\n private static final int DS1_ID = 1;\n\n private static final int DS2_ID = 2;\n\n private static final int DS3_ID = 3;\n\n private static final int DS4_ID = 4;\n\n private static final int DS5_ID = 5;\n\n private static final int DS6_ID = 6;\n\n private static final int RS1_ID = 51;\n\n private static final int RS2_ID = 52;\n\n private static final int RS3_ID = 53;\n\n // Group id definitions\n private static final int DS1_GID = 1;\n\n private static final int DS2_GID = 1;\n\n private static final int DS3_GID = 2;\n\n private static final int DS4_GID = 2;\n\n private static final int DS5_GID = 3;\n\n private static final int DS6_GID = 3;\n\n private static final int RS1_GID = 1;\n\n private static final int RS2_GID = 2;\n\n private static final int RS3_GID = 3;\n\n // Assured conf definitions\n private static final AssuredType DS1_AT = AssuredType.NOT_ASSURED;\n\n private static final int DS1_SDL = -1;\n\n private static SortedSet DS1_RU = new TreeSet();\n\n private static final AssuredType DS2_AT = AssuredType.SAFE_READ;\n\n private static final int DS2_SDL = -1;\n\n private static SortedSet DS2_RU = new TreeSet();\n\n private static final AssuredType DS3_AT = AssuredType.SAFE_DATA;\n\n private static final int DS3_SDL = 1;\n\n private static SortedSet DS3_RU = new TreeSet();\n\n private static final AssuredType DS4_AT = AssuredType.SAFE_READ;\n\n private static final int DS4_SDL = -1;\n\n private static SortedSet DS4_RU = new TreeSet();\n\n private static final AssuredType DS5_AT = AssuredType.SAFE_DATA;\n\n private static final int DS5_SDL = 2;\n\n private static SortedSet DS5_RU = new TreeSet();\n\n private static final AssuredType DS6_AT = AssuredType.SAFE_READ;\n\n private static final int DS6_SDL = -1;\n\n private static SortedSet DS6_RU = new TreeSet();\n\n private static String LOCAL_HOST_NAME;\n\n static {\n DS2_RU.add(\"ldap://fake_url_for_ds2\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_A\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_B\");\n try {\n LOCAL_HOST_NAME = InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n fail(\"Unable to resolve local host name\", e);\n }\n }\n\n private int rs1Port = -1;\n\n private int rs2Port = -1;\n\n private int rs3Port = -1;\n\n private LDAPReplicationDomain rd1 = null;\n\n private LDAPReplicationDomain rd2 = null;\n\n private LDAPReplicationDomain rd3 = null;\n\n private LDAPReplicationDomain rd4 = null;\n\n private LDAPReplicationDomain rd5 = null;\n\n private LDAPReplicationDomain rd6 = null;\n\n private ReplicationServer rs1 = null;\n\n private ReplicationServer rs2 = null;\n\n private ReplicationServer rs3 = null;\n\n // The tracer object for the debug logger\n private static final DebugTracer TRACER = getTracer();\n\n private void debugInfo(String s) {\n logError(Message.raw(Category.SYNC, Severity.NOTICE, s));\n if (debugEnabled()) {\n TRACER.debugInfo(\"** TEST **\" + s);\n }\n }\n\n private void initTest() {\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n rd1 = null;\n rd2 = null;\n rd3 = null;\n rd4 = null;\n rd5 = null;\n rd6 = null;\n rs1 = null;\n rs2 = null;\n rs3 = null;\n findFreePorts();\n }\n\n private void endTest() {\n if (rd1 != null) {\n rd1.shutdown();\n rd1 = null;\n }\n if (rd2 != null) {\n rd2.shutdown();\n rd2 = null;\n }\n if (rd3 != null) {\n rd3.shutdown();\n rd3 = null;\n }\n if (rd4 != null) {\n rd4.shutdown();\n rd4 = null;\n }\n if (rd5 != null) {\n rd5.shutdown();\n rd5 = null;\n }\n if (rd6 != null) {\n rd6.shutdown();\n rd6 = null;\n }\n try {\n // Clear any reference to a domain in synchro plugin\n MultimasterReplication.deleteDomain(DN.decode(TEST_ROOT_DN_STRING));\n } catch (DirectoryException ex) {\n fail(\"Error deleting reference to domain: \" + TEST_ROOT_DN_STRING);\n }\n if (rs1 != null) {\n rs1.clearDb();\n rs1.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs1.getDbDirName()));\n rs1 = null;\n }\n if (rs2 != null) {\n rs2.clearDb();\n rs2.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs2.getDbDirName()));\n rs2 = null;\n }\n if (rs3 != null) {\n rs3.clearDb();\n rs3.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs3.getDbDirName()));\n rs3 = null;\n }\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n }\n\n private void sleep(long time) {\n try {\n Thread.sleep(time);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n }\n\n /**\n * Check connection of the provided replication domain to the provided\n * replication server. Waits for connection to be ok up to secTimeout seconds\n * before failing.\n */\n private void checkConnection(int secTimeout, int dsId, int rsId) {\n int rsPort = -1;\n LDAPReplicationDomain rd = null;\n switch(dsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n int nSec = 0;\n // Go out of the loop only if connection is verified or if timeout occurs\n while (true) {\n // Test connection\n boolean connected = rd.isConnected();\n int rdPort = -1;\n boolean rightPort = false;\n if (connected) {\n String serverStr = rd.getReplicationServer();\n int index = serverStr.lastIndexOf(':');\n if ((index == -1) || (index >= serverStr.length()))\n fail(\"Enable to find port number in: \" + serverStr);\n String rdPortStr = serverStr.substring(index + 1);\n try {\n rdPort = (new Integer(rdPortStr)).intValue();\n } catch (Exception e) {\n fail(\"Enable to get an int from: \" + rdPortStr);\n }\n if (rdPort == rsPort)\n rightPort = true;\n }\n if (connected && rightPort) {\n // Connection verified\n debugInfo(\"checkConnection: connection from domain \" + dsId + \" to\" + \" replication server \" + rsId + \" obtained after \" + nSec + \" seconds.\");\n return;\n }\n // Sleep 1 second\n try {\n Thread.sleep(1000);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n nSec++;\n if (nSec > secTimeout) {\n // Timeout reached, end with error\n fail(\"checkConnection: could not verify connection from domain \" + dsId + \" to replication server \" + rsId + \" after \" + secTimeout + \" seconds.\" + \" Domain connected: \" + connected + \", connection port: \" + rdPort + \" (should be: \" + rsPort + \")\");\n }\n }\n }\n\n /**\n * Find needed free TCP ports.\n */\n private void findFreePorts() {\n try {\n ServerSocket socket1 = TestCaseUtils.bindFreePort();\n ServerSocket socket2 = TestCaseUtils.bindFreePort();\n ServerSocket socket3 = TestCaseUtils.bindFreePort();\n rs1Port = socket1.getLocalPort();\n rs2Port = socket2.getLocalPort();\n rs3Port = socket3.getLocalPort();\n socket1.close();\n socket2.close();\n socket3.close();\n } catch (IOException e) {\n fail(\"Unable to determinate some free ports \" + stackTraceToSingleLineString(e));\n }\n }\n\n /**\n * Creates the list of servers to represent the RS topology excluding the\n * RS whose id is passed.\n */\n ", "post_mask_code": "\n\n private ReplicationServer createReplicationServer(int rsId, String testCase) {\n try {\n SortedSet replServers = createRSListExceptOne(rsId);\n int rsPort = -1;\n int groupId = -1;\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n groupId = RS1_GID;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n groupId = RS2_GID;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n groupId = RS3_GID;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n String dir = \"topologyViewTest\" + rsId + testCase + \"Db\";\n ReplServerFakeConfiguration conf = new ReplServerFakeConfiguration(rsPort, dir, 0, rsId, 0, 100, replServers, groupId, 1000, 5000);\n ReplicationServer replicationServer = new ReplicationServer(conf);\n return replicationServer;\n } catch (Exception e) {\n fail(\"createReplicationServer \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n /**\n * Creates and starts a new ReplicationDomain with the correct list of\n * know RSs according to DS id\n */\n private LDAPReplicationDomain createReplicationDomain(int dsId) {\n try {\n SortedSet replServers = new TreeSet();\n int groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n // Fill rs list according to defined scenario (see testTopologyChanges\n switch(dsId) {\n case DS1_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n DN baseDn = DN.decode(TEST_ROOT_DN_STRING);\n DomainFakeCfg domainConf = new DomainFakeCfg(baseDn, dsId, replServers, assuredType, assuredSdLevel, groupId, 0, refUrls);\n LDAPReplicationDomain replicationDomain = MultimasterReplication.createNewDomain(domainConf);\n replicationDomain.start();\n return replicationDomain;\n } catch (Exception e) {\n fail(\"createReplicationDomain \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n // Definitions of steps for the test case\n private static final int STEP_1 = 1;\n\n private static final int STEP_2 = 2;\n\n private static final int STEP_3 = 3;\n\n private static final int STEP_4 = 4;\n\n private static final int STEP_5 = 5;\n\n private static final int STEP_6 = 6;\n\n private static final int STEP_7 = 7;\n\n private static final int STEP_8 = 8;\n\n private static final int STEP_9 = 9;\n\n private static final int STEP_10 = 10;\n\n private static final int STEP_11 = 11;\n\n private static final int STEP_12 = 12;\n\n private static final int STEP_13 = 13;\n\n /**\n * Perform connections/disconnections of DS/RS. Uses various config parameters\n * that are embedded in topo info to check if they are well transported.\n * This tests:\n * - if topo msgs are exchanged when needed and reflect topo reality (who is\n * connected to who)\n * - if topo msgs transport config params in terms of assured replication,\n * group id... that reflect what is configured in the DSs.\n *\n * Full topo is:\n * (GID=group id, A=assured, NA=not assured, SR=safe read, SD=safe data,\n * SDL=safe data level, RUF=ref urls filled, RUE=ref urls empty)\n * Except if otherwise stated, RSs and DSs are aware of every others existence\n * - RS1 with GID=1\n * - RS2 with GID=2\n * - RS3 with GID=3\n * - DS1 with GID=1, NA\n * - DS2 with GID=1, A, SR, RUF\n * - DS3 with GID=2, A, SD, SDL=1 (DS3 does not know RS1 and RS3)\n * - DS4 with GID=2, A, SR, RUE (DS4 does not know RS1 and RS3)\n * - DS5 with GID=3, A, SD, SDL=2 (DS5 does not know RS1)\n * - DS6 with GID=3, A, SR, RUF (DS6 does not know RS1)\n * Scenario is:\n * - RS1 starts\n * - DS1 starts and connects to RS1 (check topo view in DS1)\n * - DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n * - RS2 starts (check topo view in DS1,DS2)\n * - DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n * - DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n * - DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - RS3 starts (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n * - RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo view\n * in DS1,DS2,DS5,DS6)\n * @throws Exception If a problem occurred\n */\n @Test(enabled = true, groups = \"slow\")\n public void testTopologyChanges() throws Exception {\n String testCase = \"testTopologyChanges\";\n debugInfo(\"Starting \" + testCase);\n initTest();\n TopoView theoricalTopoView = null;\n try {\n /**\n * RS1 starts\n */\n debugInfo(\"*** STEP 0 ***\");\n rs1 = createReplicationServer(RS1_ID, testCase);\n /**\n * DS1 starts and connects to RS1 (check topo view in DS1)\n */\n debugInfo(\"*** STEP 1 ***\");\n rd1 = createReplicationDomain(DS1_ID);\n checkConnection(30, DS1_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_1);\n checkTopoView(new int[] { DS1_ID }, theoricalTopoView);\n /**\n * DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 2 ***\");\n rd2 = createReplicationDomain(DS2_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_2);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * RS2 starts (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 3 ***\");\n rs2 = createReplicationServer(RS2_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(1000);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_3);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n */\n debugInfo(\"*** STEP 4 ***\");\n rd3 = createReplicationDomain(DS3_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_4);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID }, theoricalTopoView);\n /**\n * DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n */\n debugInfo(\"*** STEP 5 ***\");\n rd4 = createReplicationDomain(DS4_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_5);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID }, theoricalTopoView);\n /**\n * DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 6 ***\");\n rd5 = createReplicationDomain(DS5_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_6);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 7 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_7);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 8 ***\");\n rd6 = createReplicationDomain(DS6_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_8);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 9 ***\");\n rd6.disable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n assertFalse(rd6.isConnected());\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_9);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 10 ***\");\n rd6.enable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_10);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 11 ***\");\n rs3.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n checkConnection(30, DS6_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_11);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 12 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_12);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo\n * view in DS1,DS2,DS5,DS6)\n */\n debugInfo(\"*** STEP 13 ***\");\n rs2.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_13);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n } finally {\n endTest();\n }\n }\n\n /**\n * Creates RSInfo for the passed RS\n */\n private RSInfo createRSInfo(int rsId) {\n int groupId = -1;\n String serverUrl = null;\n switch(rsId) {\n case RS1_ID:\n groupId = RS1_GID;\n serverUrl = getHostPort(rs1Port);\n break;\n case RS2_ID:\n groupId = RS2_GID;\n serverUrl = getHostPort(rs2Port);\n break;\n case RS3_ID:\n groupId = RS3_GID;\n serverUrl = getHostPort(rs3Port);\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n return new RSInfo(rsId, serverUrl, TEST_DN_WITH_ROOT_ENTRY_GENID, (byte) groupId, 1);\n }\n\n /**\n * Creates DSInfo for the passed DS, connected to the passed RS\n */\n private DSInfo createDSInfo(int dsId, int rsId) {\n ServerStatus status = ServerStatus.NORMAL_STATUS;\n byte groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n Set eclIncludes = new HashSet();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n switch(dsId) {\n case DS1_ID:\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n // Perform necessary conversions\n boolean assuredFlag = (assuredType != AssuredType.NOT_ASSURED);\n AssuredMode assMode = ((assuredType == AssuredType.SAFE_READ) ? AssuredMode.SAFE_READ_MODE : AssuredMode.SAFE_DATA_MODE);\n List urls = new ArrayList();\n for (String str : refUrls) {\n urls.add(str);\n }\n return new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assMode, (byte) assuredSdLevel, groupId, urls, eclIncludes, eclIncludes, protocolVersion);\n }\n\n /**\n * Creates the topo view to be checked at each step of the test (view that\n * every concerned DS should have)\n */\n private TopoView createTheoreticalTopoViewForStep(int step) {\n List dsList = new ArrayList();\n List rsList = new ArrayList();\n switch(step) {\n case STEP_1:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n break;\n case STEP_2:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_3:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_4:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n break;\n case STEP_5:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n break;\n case STEP_6:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n break;\n case STEP_7:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_8:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_9:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_10:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_11:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n dsList.add(createDSInfo(DS6_ID, RS2_ID));\n break;\n case STEP_12:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_13:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n default:\n fail(\"Unknown test step: \" + step);\n }\n return new TopoView(dsList, rsList);\n }\n\n /**\n * Get the topo view each DS in the provided ds list has and compares it\n * with the theoretical topology view that every body should have at the time\n * this method is called.\n */\n private void checkTopoView(int[] dsIdList, TopoView theoricalTopoView) {\n sleep(500);\n for (int currentDsId : dsIdList) {\n LDAPReplicationDomain rd = null;\n switch(currentDsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n /**\n * Get the topo view of the current analyzed DS\n */\n List internalDsList = rd.getReplicasList();\n // Add info for DS itself:\n // we need to clone the list as we don't want to modify the list kept\n // inside the DS.\n List dsList = new ArrayList();\n for (DSInfo aDsInfo : internalDsList) {\n dsList.add(aDsInfo);\n }\n int dsId = rd.getServerId();\n int rsId = rd.getRsServerId();\n ServerStatus status = rd.getStatus();\n boolean assuredFlag = rd.isAssured();\n AssuredMode assuredMode = rd.getAssuredMode();\n byte safeDataLevel = rd.getAssuredSdLevel();\n byte groupId = rd.getGroupId();\n List refUrls = rd.getRefUrls();\n Set eclInclude = rd.getEclIncludes();\n Set eclIncludeForDeletes = rd.getEclIncludesForDeletes();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n DSInfo dsInfo = new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assuredMode, safeDataLevel, groupId, refUrls, eclInclude, eclIncludeForDeletes, protocolVersion);\n dsList.add(dsInfo);\n TopoView dsTopoView = new TopoView(dsList, rd.getRsList());\n /**\n * Compare to what is the expected view\n */\n assertEquals(dsTopoView, theoricalTopoView, \" in DSid=\" + currentDsId);\n }\n }\n\n /**\n * Bag class representing a view of the topology at a given time\n * (who is connected to who, what are the config parameters...)\n */\n private class TopoView {\n\n private List dsList = null;\n\n private List rsList = null;\n\n public TopoView(List dsList, List rsList) {\n assertNotNull(dsList);\n assertNotNull(rsList);\n this.dsList = dsList;\n this.rsList = rsList;\n }\n\n public boolean equals(Object obj) {\n assertNotNull(obj);\n assertFalse(obj.getClass() != this.getClass());\n TopoView topoView = (TopoView) obj;\n // Check dsList\n if (topoView.dsList.size() != dsList.size())\n return false;\n for (DSInfo dsInfo : topoView.dsList) {\n int found = 0;\n for (DSInfo thisDsInfo : dsList) {\n if (thisDsInfo.equals(dsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as dsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n // Check rsList\n if (topoView.rsList.size() != rsList.size())\n return false;\n for (RSInfo rsInfo : topoView.rsList) {\n int found = 0;\n for (RSInfo thisRsInfo : rsList) {\n if (thisRsInfo.equals(rsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as rsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n return true;\n }\n\n public String toString() {\n String dsStr = \"\";\n for (DSInfo dsInfo : dsList) {\n dsStr += dsInfo.toString() + \"\\n----------------------------\\n\";\n }\n String rsStr = \"\";\n for (RSInfo rsInfo : rsList) {\n rsStr += rsInfo.toString() + \"\\n----------------------------\\n\";\n }\n return (\"TopoView:\" + \"\\n----------------------------\\n\" + \"CONNECTED DS SERVERS:\\n\" + dsStr + \"CONNECTED RS SERVERS:\\n\" + rsStr);\n }\n }\n\n private String getHostPort(int port) {\n return LOCAL_HOST_NAME + \":\" + port;\n }\n}\n"} {"task_id": "Java_1929", "language": "Java", "task_type": "if_statement", "source_file": "java/github/ForgeRock/opendj-community-edition/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java", "mask_start_position": 9572, "mask_end_position": 9838, "canonical_solution": "if (connected && rightPort) {\n // Connection verified\n debugInfo(\"checkConnection: connection from domain \" + dsId + \" to\" + \" replication server \" + rsId + \" obtained after \" + nSec + \" seconds.\");\n return;\n }", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport java.net.UnknownHostException;\nimport static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;\nimport static org.opends.server.loggers.ErrorLogger.logError;\nimport static org.opends.server.loggers.debug.DebugLogger.debugEnabled;\nimport static org.opends.server.loggers.debug.DebugLogger.getTracer;\nimport static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\nimport org.opends.messages.Category;\nimport org.opends.messages.Message;\nimport org.opends.messages.Severity;\nimport org.opends.server.TestCaseUtils;\nimport org.opends.server.admin.std.meta.ReplicationDomainCfgDefn.AssuredType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.loggers.debug.DebugTracer;\nimport org.opends.server.replication.ReplicationTestCase;\nimport org.opends.server.replication.common.AssuredMode;\nimport org.opends.server.replication.common.DSInfo;\nimport org.opends.server.replication.common.RSInfo;\nimport org.opends.server.replication.common.ServerStatus;\nimport org.opends.server.replication.protocol.ProtocolVersion;\nimport org.opends.server.replication.server.ReplServerFakeConfiguration;\nimport org.opends.server.replication.server.ReplicationServer;\nimport org.opends.server.types.DN;\nimport org.opends.server.types.DirectoryException;\nimport org.opends.server.util.StaticUtils;\nimport org.testng.annotations.Test;\n\n/**\n * Some tests to know if at any time the view DSs and RSs have of the current\n * topology is accurate, even after some connections, disconnections and\n * re-connections events.\n */\npublic class TopologyViewTest extends ReplicationTestCase {\n\n // Server id definitions\n private static final int DS1_ID = 1;\n\n private static final int DS2_ID = 2;\n\n private static final int DS3_ID = 3;\n\n private static final int DS4_ID = 4;\n\n private static final int DS5_ID = 5;\n\n private static final int DS6_ID = 6;\n\n private static final int RS1_ID = 51;\n\n private static final int RS2_ID = 52;\n\n private static final int RS3_ID = 53;\n\n // Group id definitions\n private static final int DS1_GID = 1;\n\n private static final int DS2_GID = 1;\n\n private static final int DS3_GID = 2;\n\n private static final int DS4_GID = 2;\n\n private static final int DS5_GID = 3;\n\n private static final int DS6_GID = 3;\n\n private static final int RS1_GID = 1;\n\n private static final int RS2_GID = 2;\n\n private static final int RS3_GID = 3;\n\n // Assured conf definitions\n private static final AssuredType DS1_AT = AssuredType.NOT_ASSURED;\n\n private static final int DS1_SDL = -1;\n\n private static SortedSet DS1_RU = new TreeSet();\n\n private static final AssuredType DS2_AT = AssuredType.SAFE_READ;\n\n private static final int DS2_SDL = -1;\n\n private static SortedSet DS2_RU = new TreeSet();\n\n private static final AssuredType DS3_AT = AssuredType.SAFE_DATA;\n\n private static final int DS3_SDL = 1;\n\n private static SortedSet DS3_RU = new TreeSet();\n\n private static final AssuredType DS4_AT = AssuredType.SAFE_READ;\n\n private static final int DS4_SDL = -1;\n\n private static SortedSet DS4_RU = new TreeSet();\n\n private static final AssuredType DS5_AT = AssuredType.SAFE_DATA;\n\n private static final int DS5_SDL = 2;\n\n private static SortedSet DS5_RU = new TreeSet();\n\n private static final AssuredType DS6_AT = AssuredType.SAFE_READ;\n\n private static final int DS6_SDL = -1;\n\n private static SortedSet DS6_RU = new TreeSet();\n\n private static String LOCAL_HOST_NAME;\n\n static {\n DS2_RU.add(\"ldap://fake_url_for_ds2\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_A\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_B\");\n try {\n LOCAL_HOST_NAME = InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n fail(\"Unable to resolve local host name\", e);\n }\n }\n\n private int rs1Port = -1;\n\n private int rs2Port = -1;\n\n private int rs3Port = -1;\n\n private LDAPReplicationDomain rd1 = null;\n\n private LDAPReplicationDomain rd2 = null;\n\n private LDAPReplicationDomain rd3 = null;\n\n private LDAPReplicationDomain rd4 = null;\n\n private LDAPReplicationDomain rd5 = null;\n\n private LDAPReplicationDomain rd6 = null;\n\n private ReplicationServer rs1 = null;\n\n private ReplicationServer rs2 = null;\n\n private ReplicationServer rs3 = null;\n\n // The tracer object for the debug logger\n private static final DebugTracer TRACER = getTracer();\n\n private void debugInfo(String s) {\n logError(Message.raw(Category.SYNC, Severity.NOTICE, s));\n if (debugEnabled()) {\n TRACER.debugInfo(\"** TEST **\" + s);\n }\n }\n\n private void initTest() {\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n rd1 = null;\n rd2 = null;\n rd3 = null;\n rd4 = null;\n rd5 = null;\n rd6 = null;\n rs1 = null;\n rs2 = null;\n rs3 = null;\n findFreePorts();\n }\n\n private void endTest() {\n if (rd1 != null) {\n rd1.shutdown();\n rd1 = null;\n }\n if (rd2 != null) {\n rd2.shutdown();\n rd2 = null;\n }\n if (rd3 != null) {\n rd3.shutdown();\n rd3 = null;\n }\n if (rd4 != null) {\n rd4.shutdown();\n rd4 = null;\n }\n if (rd5 != null) {\n rd5.shutdown();\n rd5 = null;\n }\n if (rd6 != null) {\n rd6.shutdown();\n rd6 = null;\n }\n try {\n // Clear any reference to a domain in synchro plugin\n MultimasterReplication.deleteDomain(DN.decode(TEST_ROOT_DN_STRING));\n } catch (DirectoryException ex) {\n fail(\"Error deleting reference to domain: \" + TEST_ROOT_DN_STRING);\n }\n if (rs1 != null) {\n rs1.clearDb();\n rs1.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs1.getDbDirName()));\n rs1 = null;\n }\n if (rs2 != null) {\n rs2.clearDb();\n rs2.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs2.getDbDirName()));\n rs2 = null;\n }\n if (rs3 != null) {\n rs3.clearDb();\n rs3.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs3.getDbDirName()));\n rs3 = null;\n }\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n }\n\n private void sleep(long time) {\n try {\n Thread.sleep(time);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n }\n\n /**\n * Check connection of the provided replication domain to the provided\n * replication server. Waits for connection to be ok up to secTimeout seconds\n * before failing.\n */\n private void checkConnection(int secTimeout, int dsId, int rsId) {\n int rsPort = -1;\n LDAPReplicationDomain rd = null;\n switch(dsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n int nSec = 0;\n // Go out of the loop only if connection is verified or if timeout occurs\n while (true) {\n // Test connection\n boolean connected = rd.isConnected();\n int rdPort = -1;\n boolean rightPort = false;\n if (connected) {\n String serverStr = rd.getReplicationServer();\n int index = serverStr.lastIndexOf(':');\n if ((index == -1) || (index >= serverStr.length()))\n fail(\"Enable to find port number in: \" + serverStr);\n String rdPortStr = serverStr.substring(index + 1);\n try {\n rdPort = (new Integer(rdPortStr)).intValue();\n } catch (Exception e) {\n fail(\"Enable to get an int from: \" + rdPortStr);\n }\n if (rdPort == rsPort)\n rightPort = true;\n }\n ", "post_mask_code": "\n // Sleep 1 second\n try {\n Thread.sleep(1000);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n nSec++;\n if (nSec > secTimeout) {\n // Timeout reached, end with error\n fail(\"checkConnection: could not verify connection from domain \" + dsId + \" to replication server \" + rsId + \" after \" + secTimeout + \" seconds.\" + \" Domain connected: \" + connected + \", connection port: \" + rdPort + \" (should be: \" + rsPort + \")\");\n }\n }\n }\n\n /**\n * Find needed free TCP ports.\n */\n private void findFreePorts() {\n try {\n ServerSocket socket1 = TestCaseUtils.bindFreePort();\n ServerSocket socket2 = TestCaseUtils.bindFreePort();\n ServerSocket socket3 = TestCaseUtils.bindFreePort();\n rs1Port = socket1.getLocalPort();\n rs2Port = socket2.getLocalPort();\n rs3Port = socket3.getLocalPort();\n socket1.close();\n socket2.close();\n socket3.close();\n } catch (IOException e) {\n fail(\"Unable to determinate some free ports \" + stackTraceToSingleLineString(e));\n }\n }\n\n /**\n * Creates the list of servers to represent the RS topology excluding the\n * RS whose id is passed.\n */\n private SortedSet createRSListExceptOne(int rsIdToExclude) {\n SortedSet replServers = new TreeSet();\n if (rsIdToExclude != RS1_ID) {\n replServers.add(getHostPort(rs1Port));\n }\n if (rsIdToExclude != RS2_ID) {\n replServers.add(getHostPort(rs2Port));\n }\n if (rsIdToExclude != RS3_ID) {\n replServers.add(getHostPort(rs3Port));\n }\n return replServers;\n }\n\n private ReplicationServer createReplicationServer(int rsId, String testCase) {\n try {\n SortedSet replServers = createRSListExceptOne(rsId);\n int rsPort = -1;\n int groupId = -1;\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n groupId = RS1_GID;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n groupId = RS2_GID;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n groupId = RS3_GID;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n String dir = \"topologyViewTest\" + rsId + testCase + \"Db\";\n ReplServerFakeConfiguration conf = new ReplServerFakeConfiguration(rsPort, dir, 0, rsId, 0, 100, replServers, groupId, 1000, 5000);\n ReplicationServer replicationServer = new ReplicationServer(conf);\n return replicationServer;\n } catch (Exception e) {\n fail(\"createReplicationServer \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n /**\n * Creates and starts a new ReplicationDomain with the correct list of\n * know RSs according to DS id\n */\n private LDAPReplicationDomain createReplicationDomain(int dsId) {\n try {\n SortedSet replServers = new TreeSet();\n int groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n // Fill rs list according to defined scenario (see testTopologyChanges\n switch(dsId) {\n case DS1_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n DN baseDn = DN.decode(TEST_ROOT_DN_STRING);\n DomainFakeCfg domainConf = new DomainFakeCfg(baseDn, dsId, replServers, assuredType, assuredSdLevel, groupId, 0, refUrls);\n LDAPReplicationDomain replicationDomain = MultimasterReplication.createNewDomain(domainConf);\n replicationDomain.start();\n return replicationDomain;\n } catch (Exception e) {\n fail(\"createReplicationDomain \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n // Definitions of steps for the test case\n private static final int STEP_1 = 1;\n\n private static final int STEP_2 = 2;\n\n private static final int STEP_3 = 3;\n\n private static final int STEP_4 = 4;\n\n private static final int STEP_5 = 5;\n\n private static final int STEP_6 = 6;\n\n private static final int STEP_7 = 7;\n\n private static final int STEP_8 = 8;\n\n private static final int STEP_9 = 9;\n\n private static final int STEP_10 = 10;\n\n private static final int STEP_11 = 11;\n\n private static final int STEP_12 = 12;\n\n private static final int STEP_13 = 13;\n\n /**\n * Perform connections/disconnections of DS/RS. Uses various config parameters\n * that are embedded in topo info to check if they are well transported.\n * This tests:\n * - if topo msgs are exchanged when needed and reflect topo reality (who is\n * connected to who)\n * - if topo msgs transport config params in terms of assured replication,\n * group id... that reflect what is configured in the DSs.\n *\n * Full topo is:\n * (GID=group id, A=assured, NA=not assured, SR=safe read, SD=safe data,\n * SDL=safe data level, RUF=ref urls filled, RUE=ref urls empty)\n * Except if otherwise stated, RSs and DSs are aware of every others existence\n * - RS1 with GID=1\n * - RS2 with GID=2\n * - RS3 with GID=3\n * - DS1 with GID=1, NA\n * - DS2 with GID=1, A, SR, RUF\n * - DS3 with GID=2, A, SD, SDL=1 (DS3 does not know RS1 and RS3)\n * - DS4 with GID=2, A, SR, RUE (DS4 does not know RS1 and RS3)\n * - DS5 with GID=3, A, SD, SDL=2 (DS5 does not know RS1)\n * - DS6 with GID=3, A, SR, RUF (DS6 does not know RS1)\n * Scenario is:\n * - RS1 starts\n * - DS1 starts and connects to RS1 (check topo view in DS1)\n * - DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n * - RS2 starts (check topo view in DS1,DS2)\n * - DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n * - DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n * - DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - RS3 starts (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n * - RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo view\n * in DS1,DS2,DS5,DS6)\n * @throws Exception If a problem occurred\n */\n @Test(enabled = true, groups = \"slow\")\n public void testTopologyChanges() throws Exception {\n String testCase = \"testTopologyChanges\";\n debugInfo(\"Starting \" + testCase);\n initTest();\n TopoView theoricalTopoView = null;\n try {\n /**\n * RS1 starts\n */\n debugInfo(\"*** STEP 0 ***\");\n rs1 = createReplicationServer(RS1_ID, testCase);\n /**\n * DS1 starts and connects to RS1 (check topo view in DS1)\n */\n debugInfo(\"*** STEP 1 ***\");\n rd1 = createReplicationDomain(DS1_ID);\n checkConnection(30, DS1_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_1);\n checkTopoView(new int[] { DS1_ID }, theoricalTopoView);\n /**\n * DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 2 ***\");\n rd2 = createReplicationDomain(DS2_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_2);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * RS2 starts (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 3 ***\");\n rs2 = createReplicationServer(RS2_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(1000);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_3);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n */\n debugInfo(\"*** STEP 4 ***\");\n rd3 = createReplicationDomain(DS3_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_4);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID }, theoricalTopoView);\n /**\n * DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n */\n debugInfo(\"*** STEP 5 ***\");\n rd4 = createReplicationDomain(DS4_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_5);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID }, theoricalTopoView);\n /**\n * DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 6 ***\");\n rd5 = createReplicationDomain(DS5_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_6);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 7 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_7);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 8 ***\");\n rd6 = createReplicationDomain(DS6_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_8);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 9 ***\");\n rd6.disable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n assertFalse(rd6.isConnected());\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_9);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 10 ***\");\n rd6.enable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_10);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 11 ***\");\n rs3.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n checkConnection(30, DS6_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_11);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 12 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_12);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo\n * view in DS1,DS2,DS5,DS6)\n */\n debugInfo(\"*** STEP 13 ***\");\n rs2.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_13);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n } finally {\n endTest();\n }\n }\n\n /**\n * Creates RSInfo for the passed RS\n */\n private RSInfo createRSInfo(int rsId) {\n int groupId = -1;\n String serverUrl = null;\n switch(rsId) {\n case RS1_ID:\n groupId = RS1_GID;\n serverUrl = getHostPort(rs1Port);\n break;\n case RS2_ID:\n groupId = RS2_GID;\n serverUrl = getHostPort(rs2Port);\n break;\n case RS3_ID:\n groupId = RS3_GID;\n serverUrl = getHostPort(rs3Port);\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n return new RSInfo(rsId, serverUrl, TEST_DN_WITH_ROOT_ENTRY_GENID, (byte) groupId, 1);\n }\n\n /**\n * Creates DSInfo for the passed DS, connected to the passed RS\n */\n private DSInfo createDSInfo(int dsId, int rsId) {\n ServerStatus status = ServerStatus.NORMAL_STATUS;\n byte groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n Set eclIncludes = new HashSet();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n switch(dsId) {\n case DS1_ID:\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n // Perform necessary conversions\n boolean assuredFlag = (assuredType != AssuredType.NOT_ASSURED);\n AssuredMode assMode = ((assuredType == AssuredType.SAFE_READ) ? AssuredMode.SAFE_READ_MODE : AssuredMode.SAFE_DATA_MODE);\n List urls = new ArrayList();\n for (String str : refUrls) {\n urls.add(str);\n }\n return new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assMode, (byte) assuredSdLevel, groupId, urls, eclIncludes, eclIncludes, protocolVersion);\n }\n\n /**\n * Creates the topo view to be checked at each step of the test (view that\n * every concerned DS should have)\n */\n private TopoView createTheoreticalTopoViewForStep(int step) {\n List dsList = new ArrayList();\n List rsList = new ArrayList();\n switch(step) {\n case STEP_1:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n break;\n case STEP_2:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_3:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_4:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n break;\n case STEP_5:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n break;\n case STEP_6:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n break;\n case STEP_7:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_8:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_9:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_10:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_11:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n dsList.add(createDSInfo(DS6_ID, RS2_ID));\n break;\n case STEP_12:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_13:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n default:\n fail(\"Unknown test step: \" + step);\n }\n return new TopoView(dsList, rsList);\n }\n\n /**\n * Get the topo view each DS in the provided ds list has and compares it\n * with the theoretical topology view that every body should have at the time\n * this method is called.\n */\n private void checkTopoView(int[] dsIdList, TopoView theoricalTopoView) {\n sleep(500);\n for (int currentDsId : dsIdList) {\n LDAPReplicationDomain rd = null;\n switch(currentDsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n /**\n * Get the topo view of the current analyzed DS\n */\n List internalDsList = rd.getReplicasList();\n // Add info for DS itself:\n // we need to clone the list as we don't want to modify the list kept\n // inside the DS.\n List dsList = new ArrayList();\n for (DSInfo aDsInfo : internalDsList) {\n dsList.add(aDsInfo);\n }\n int dsId = rd.getServerId();\n int rsId = rd.getRsServerId();\n ServerStatus status = rd.getStatus();\n boolean assuredFlag = rd.isAssured();\n AssuredMode assuredMode = rd.getAssuredMode();\n byte safeDataLevel = rd.getAssuredSdLevel();\n byte groupId = rd.getGroupId();\n List refUrls = rd.getRefUrls();\n Set eclInclude = rd.getEclIncludes();\n Set eclIncludeForDeletes = rd.getEclIncludesForDeletes();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n DSInfo dsInfo = new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assuredMode, safeDataLevel, groupId, refUrls, eclInclude, eclIncludeForDeletes, protocolVersion);\n dsList.add(dsInfo);\n TopoView dsTopoView = new TopoView(dsList, rd.getRsList());\n /**\n * Compare to what is the expected view\n */\n assertEquals(dsTopoView, theoricalTopoView, \" in DSid=\" + currentDsId);\n }\n }\n\n /**\n * Bag class representing a view of the topology at a given time\n * (who is connected to who, what are the config parameters...)\n */\n private class TopoView {\n\n private List dsList = null;\n\n private List rsList = null;\n\n public TopoView(List dsList, List rsList) {\n assertNotNull(dsList);\n assertNotNull(rsList);\n this.dsList = dsList;\n this.rsList = rsList;\n }\n\n public boolean equals(Object obj) {\n assertNotNull(obj);\n assertFalse(obj.getClass() != this.getClass());\n TopoView topoView = (TopoView) obj;\n // Check dsList\n if (topoView.dsList.size() != dsList.size())\n return false;\n for (DSInfo dsInfo : topoView.dsList) {\n int found = 0;\n for (DSInfo thisDsInfo : dsList) {\n if (thisDsInfo.equals(dsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as dsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n // Check rsList\n if (topoView.rsList.size() != rsList.size())\n return false;\n for (RSInfo rsInfo : topoView.rsList) {\n int found = 0;\n for (RSInfo thisRsInfo : rsList) {\n if (thisRsInfo.equals(rsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as rsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n return true;\n }\n\n public String toString() {\n String dsStr = \"\";\n for (DSInfo dsInfo : dsList) {\n dsStr += dsInfo.toString() + \"\\n----------------------------\\n\";\n }\n String rsStr = \"\";\n for (RSInfo rsInfo : rsList) {\n rsStr += rsInfo.toString() + \"\\n----------------------------\\n\";\n }\n return (\"TopoView:\" + \"\\n----------------------------\\n\" + \"CONNECTED DS SERVERS:\\n\" + dsStr + \"CONNECTED RS SERVERS:\\n\" + rsStr);\n }\n }\n\n private String getHostPort(int port) {\n return LOCAL_HOST_NAME + \":\" + port;\n }\n}\n"} {"task_id": "Java_1930", "language": "Java", "task_type": "switch_case", "source_file": "java/github/ForgeRock/opendj-community-edition/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java", "mask_start_position": 8276, "mask_end_position": 8623, "canonical_solution": "switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport java.net.UnknownHostException;\nimport static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;\nimport static org.opends.server.loggers.ErrorLogger.logError;\nimport static org.opends.server.loggers.debug.DebugLogger.debugEnabled;\nimport static org.opends.server.loggers.debug.DebugLogger.getTracer;\nimport static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\nimport org.opends.messages.Category;\nimport org.opends.messages.Message;\nimport org.opends.messages.Severity;\nimport org.opends.server.TestCaseUtils;\nimport org.opends.server.admin.std.meta.ReplicationDomainCfgDefn.AssuredType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.loggers.debug.DebugTracer;\nimport org.opends.server.replication.ReplicationTestCase;\nimport org.opends.server.replication.common.AssuredMode;\nimport org.opends.server.replication.common.DSInfo;\nimport org.opends.server.replication.common.RSInfo;\nimport org.opends.server.replication.common.ServerStatus;\nimport org.opends.server.replication.protocol.ProtocolVersion;\nimport org.opends.server.replication.server.ReplServerFakeConfiguration;\nimport org.opends.server.replication.server.ReplicationServer;\nimport org.opends.server.types.DN;\nimport org.opends.server.types.DirectoryException;\nimport org.opends.server.util.StaticUtils;\nimport org.testng.annotations.Test;\n\n/**\n * Some tests to know if at any time the view DSs and RSs have of the current\n * topology is accurate, even after some connections, disconnections and\n * re-connections events.\n */\npublic class TopologyViewTest extends ReplicationTestCase {\n\n // Server id definitions\n private static final int DS1_ID = 1;\n\n private static final int DS2_ID = 2;\n\n private static final int DS3_ID = 3;\n\n private static final int DS4_ID = 4;\n\n private static final int DS5_ID = 5;\n\n private static final int DS6_ID = 6;\n\n private static final int RS1_ID = 51;\n\n private static final int RS2_ID = 52;\n\n private static final int RS3_ID = 53;\n\n // Group id definitions\n private static final int DS1_GID = 1;\n\n private static final int DS2_GID = 1;\n\n private static final int DS3_GID = 2;\n\n private static final int DS4_GID = 2;\n\n private static final int DS5_GID = 3;\n\n private static final int DS6_GID = 3;\n\n private static final int RS1_GID = 1;\n\n private static final int RS2_GID = 2;\n\n private static final int RS3_GID = 3;\n\n // Assured conf definitions\n private static final AssuredType DS1_AT = AssuredType.NOT_ASSURED;\n\n private static final int DS1_SDL = -1;\n\n private static SortedSet DS1_RU = new TreeSet();\n\n private static final AssuredType DS2_AT = AssuredType.SAFE_READ;\n\n private static final int DS2_SDL = -1;\n\n private static SortedSet DS2_RU = new TreeSet();\n\n private static final AssuredType DS3_AT = AssuredType.SAFE_DATA;\n\n private static final int DS3_SDL = 1;\n\n private static SortedSet DS3_RU = new TreeSet();\n\n private static final AssuredType DS4_AT = AssuredType.SAFE_READ;\n\n private static final int DS4_SDL = -1;\n\n private static SortedSet DS4_RU = new TreeSet();\n\n private static final AssuredType DS5_AT = AssuredType.SAFE_DATA;\n\n private static final int DS5_SDL = 2;\n\n private static SortedSet DS5_RU = new TreeSet();\n\n private static final AssuredType DS6_AT = AssuredType.SAFE_READ;\n\n private static final int DS6_SDL = -1;\n\n private static SortedSet DS6_RU = new TreeSet();\n\n private static String LOCAL_HOST_NAME;\n\n static {\n DS2_RU.add(\"ldap://fake_url_for_ds2\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_A\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_B\");\n try {\n LOCAL_HOST_NAME = InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n fail(\"Unable to resolve local host name\", e);\n }\n }\n\n private int rs1Port = -1;\n\n private int rs2Port = -1;\n\n private int rs3Port = -1;\n\n private LDAPReplicationDomain rd1 = null;\n\n private LDAPReplicationDomain rd2 = null;\n\n private LDAPReplicationDomain rd3 = null;\n\n private LDAPReplicationDomain rd4 = null;\n\n private LDAPReplicationDomain rd5 = null;\n\n private LDAPReplicationDomain rd6 = null;\n\n private ReplicationServer rs1 = null;\n\n private ReplicationServer rs2 = null;\n\n private ReplicationServer rs3 = null;\n\n // The tracer object for the debug logger\n private static final DebugTracer TRACER = getTracer();\n\n private void debugInfo(String s) {\n logError(Message.raw(Category.SYNC, Severity.NOTICE, s));\n if (debugEnabled()) {\n TRACER.debugInfo(\"** TEST **\" + s);\n }\n }\n\n private void initTest() {\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n rd1 = null;\n rd2 = null;\n rd3 = null;\n rd4 = null;\n rd5 = null;\n rd6 = null;\n rs1 = null;\n rs2 = null;\n rs3 = null;\n findFreePorts();\n }\n\n private void endTest() {\n if (rd1 != null) {\n rd1.shutdown();\n rd1 = null;\n }\n if (rd2 != null) {\n rd2.shutdown();\n rd2 = null;\n }\n if (rd3 != null) {\n rd3.shutdown();\n rd3 = null;\n }\n if (rd4 != null) {\n rd4.shutdown();\n rd4 = null;\n }\n if (rd5 != null) {\n rd5.shutdown();\n rd5 = null;\n }\n if (rd6 != null) {\n rd6.shutdown();\n rd6 = null;\n }\n try {\n // Clear any reference to a domain in synchro plugin\n MultimasterReplication.deleteDomain(DN.decode(TEST_ROOT_DN_STRING));\n } catch (DirectoryException ex) {\n fail(\"Error deleting reference to domain: \" + TEST_ROOT_DN_STRING);\n }\n if (rs1 != null) {\n rs1.clearDb();\n rs1.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs1.getDbDirName()));\n rs1 = null;\n }\n if (rs2 != null) {\n rs2.clearDb();\n rs2.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs2.getDbDirName()));\n rs2 = null;\n }\n if (rs3 != null) {\n rs3.clearDb();\n rs3.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs3.getDbDirName()));\n rs3 = null;\n }\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n }\n\n private void sleep(long time) {\n try {\n Thread.sleep(time);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n }\n\n /**\n * Check connection of the provided replication domain to the provided\n * replication server. Waits for connection to be ok up to secTimeout seconds\n * before failing.\n */\n private void checkConnection(int secTimeout, int dsId, int rsId) {\n int rsPort = -1;\n LDAPReplicationDomain rd = null;\n switch(dsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n ", "post_mask_code": "\n int nSec = 0;\n // Go out of the loop only if connection is verified or if timeout occurs\n while (true) {\n // Test connection\n boolean connected = rd.isConnected();\n int rdPort = -1;\n boolean rightPort = false;\n if (connected) {\n String serverStr = rd.getReplicationServer();\n int index = serverStr.lastIndexOf(':');\n if ((index == -1) || (index >= serverStr.length()))\n fail(\"Enable to find port number in: \" + serverStr);\n String rdPortStr = serverStr.substring(index + 1);\n try {\n rdPort = (new Integer(rdPortStr)).intValue();\n } catch (Exception e) {\n fail(\"Enable to get an int from: \" + rdPortStr);\n }\n if (rdPort == rsPort)\n rightPort = true;\n }\n if (connected && rightPort) {\n // Connection verified\n debugInfo(\"checkConnection: connection from domain \" + dsId + \" to\" + \" replication server \" + rsId + \" obtained after \" + nSec + \" seconds.\");\n return;\n }\n // Sleep 1 second\n try {\n Thread.sleep(1000);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n nSec++;\n if (nSec > secTimeout) {\n // Timeout reached, end with error\n fail(\"checkConnection: could not verify connection from domain \" + dsId + \" to replication server \" + rsId + \" after \" + secTimeout + \" seconds.\" + \" Domain connected: \" + connected + \", connection port: \" + rdPort + \" (should be: \" + rsPort + \")\");\n }\n }\n }\n\n /**\n * Find needed free TCP ports.\n */\n private void findFreePorts() {\n try {\n ServerSocket socket1 = TestCaseUtils.bindFreePort();\n ServerSocket socket2 = TestCaseUtils.bindFreePort();\n ServerSocket socket3 = TestCaseUtils.bindFreePort();\n rs1Port = socket1.getLocalPort();\n rs2Port = socket2.getLocalPort();\n rs3Port = socket3.getLocalPort();\n socket1.close();\n socket2.close();\n socket3.close();\n } catch (IOException e) {\n fail(\"Unable to determinate some free ports \" + stackTraceToSingleLineString(e));\n }\n }\n\n /**\n * Creates the list of servers to represent the RS topology excluding the\n * RS whose id is passed.\n */\n private SortedSet createRSListExceptOne(int rsIdToExclude) {\n SortedSet replServers = new TreeSet();\n if (rsIdToExclude != RS1_ID) {\n replServers.add(getHostPort(rs1Port));\n }\n if (rsIdToExclude != RS2_ID) {\n replServers.add(getHostPort(rs2Port));\n }\n if (rsIdToExclude != RS3_ID) {\n replServers.add(getHostPort(rs3Port));\n }\n return replServers;\n }\n\n private ReplicationServer createReplicationServer(int rsId, String testCase) {\n try {\n SortedSet replServers = createRSListExceptOne(rsId);\n int rsPort = -1;\n int groupId = -1;\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n groupId = RS1_GID;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n groupId = RS2_GID;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n groupId = RS3_GID;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n String dir = \"topologyViewTest\" + rsId + testCase + \"Db\";\n ReplServerFakeConfiguration conf = new ReplServerFakeConfiguration(rsPort, dir, 0, rsId, 0, 100, replServers, groupId, 1000, 5000);\n ReplicationServer replicationServer = new ReplicationServer(conf);\n return replicationServer;\n } catch (Exception e) {\n fail(\"createReplicationServer \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n /**\n * Creates and starts a new ReplicationDomain with the correct list of\n * know RSs according to DS id\n */\n private LDAPReplicationDomain createReplicationDomain(int dsId) {\n try {\n SortedSet replServers = new TreeSet();\n int groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n // Fill rs list according to defined scenario (see testTopologyChanges\n switch(dsId) {\n case DS1_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n DN baseDn = DN.decode(TEST_ROOT_DN_STRING);\n DomainFakeCfg domainConf = new DomainFakeCfg(baseDn, dsId, replServers, assuredType, assuredSdLevel, groupId, 0, refUrls);\n LDAPReplicationDomain replicationDomain = MultimasterReplication.createNewDomain(domainConf);\n replicationDomain.start();\n return replicationDomain;\n } catch (Exception e) {\n fail(\"createReplicationDomain \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n // Definitions of steps for the test case\n private static final int STEP_1 = 1;\n\n private static final int STEP_2 = 2;\n\n private static final int STEP_3 = 3;\n\n private static final int STEP_4 = 4;\n\n private static final int STEP_5 = 5;\n\n private static final int STEP_6 = 6;\n\n private static final int STEP_7 = 7;\n\n private static final int STEP_8 = 8;\n\n private static final int STEP_9 = 9;\n\n private static final int STEP_10 = 10;\n\n private static final int STEP_11 = 11;\n\n private static final int STEP_12 = 12;\n\n private static final int STEP_13 = 13;\n\n /**\n * Perform connections/disconnections of DS/RS. Uses various config parameters\n * that are embedded in topo info to check if they are well transported.\n * This tests:\n * - if topo msgs are exchanged when needed and reflect topo reality (who is\n * connected to who)\n * - if topo msgs transport config params in terms of assured replication,\n * group id... that reflect what is configured in the DSs.\n *\n * Full topo is:\n * (GID=group id, A=assured, NA=not assured, SR=safe read, SD=safe data,\n * SDL=safe data level, RUF=ref urls filled, RUE=ref urls empty)\n * Except if otherwise stated, RSs and DSs are aware of every others existence\n * - RS1 with GID=1\n * - RS2 with GID=2\n * - RS3 with GID=3\n * - DS1 with GID=1, NA\n * - DS2 with GID=1, A, SR, RUF\n * - DS3 with GID=2, A, SD, SDL=1 (DS3 does not know RS1 and RS3)\n * - DS4 with GID=2, A, SR, RUE (DS4 does not know RS1 and RS3)\n * - DS5 with GID=3, A, SD, SDL=2 (DS5 does not know RS1)\n * - DS6 with GID=3, A, SR, RUF (DS6 does not know RS1)\n * Scenario is:\n * - RS1 starts\n * - DS1 starts and connects to RS1 (check topo view in DS1)\n * - DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n * - RS2 starts (check topo view in DS1,DS2)\n * - DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n * - DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n * - DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - RS3 starts (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n * - RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo view\n * in DS1,DS2,DS5,DS6)\n * @throws Exception If a problem occurred\n */\n @Test(enabled = true, groups = \"slow\")\n public void testTopologyChanges() throws Exception {\n String testCase = \"testTopologyChanges\";\n debugInfo(\"Starting \" + testCase);\n initTest();\n TopoView theoricalTopoView = null;\n try {\n /**\n * RS1 starts\n */\n debugInfo(\"*** STEP 0 ***\");\n rs1 = createReplicationServer(RS1_ID, testCase);\n /**\n * DS1 starts and connects to RS1 (check topo view in DS1)\n */\n debugInfo(\"*** STEP 1 ***\");\n rd1 = createReplicationDomain(DS1_ID);\n checkConnection(30, DS1_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_1);\n checkTopoView(new int[] { DS1_ID }, theoricalTopoView);\n /**\n * DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 2 ***\");\n rd2 = createReplicationDomain(DS2_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_2);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * RS2 starts (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 3 ***\");\n rs2 = createReplicationServer(RS2_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(1000);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_3);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n */\n debugInfo(\"*** STEP 4 ***\");\n rd3 = createReplicationDomain(DS3_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_4);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID }, theoricalTopoView);\n /**\n * DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n */\n debugInfo(\"*** STEP 5 ***\");\n rd4 = createReplicationDomain(DS4_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_5);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID }, theoricalTopoView);\n /**\n * DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 6 ***\");\n rd5 = createReplicationDomain(DS5_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_6);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 7 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_7);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 8 ***\");\n rd6 = createReplicationDomain(DS6_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_8);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 9 ***\");\n rd6.disable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n assertFalse(rd6.isConnected());\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_9);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 10 ***\");\n rd6.enable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_10);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 11 ***\");\n rs3.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n checkConnection(30, DS6_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_11);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 12 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_12);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo\n * view in DS1,DS2,DS5,DS6)\n */\n debugInfo(\"*** STEP 13 ***\");\n rs2.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_13);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n } finally {\n endTest();\n }\n }\n\n /**\n * Creates RSInfo for the passed RS\n */\n private RSInfo createRSInfo(int rsId) {\n int groupId = -1;\n String serverUrl = null;\n switch(rsId) {\n case RS1_ID:\n groupId = RS1_GID;\n serverUrl = getHostPort(rs1Port);\n break;\n case RS2_ID:\n groupId = RS2_GID;\n serverUrl = getHostPort(rs2Port);\n break;\n case RS3_ID:\n groupId = RS3_GID;\n serverUrl = getHostPort(rs3Port);\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n return new RSInfo(rsId, serverUrl, TEST_DN_WITH_ROOT_ENTRY_GENID, (byte) groupId, 1);\n }\n\n /**\n * Creates DSInfo for the passed DS, connected to the passed RS\n */\n private DSInfo createDSInfo(int dsId, int rsId) {\n ServerStatus status = ServerStatus.NORMAL_STATUS;\n byte groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n Set eclIncludes = new HashSet();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n switch(dsId) {\n case DS1_ID:\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n // Perform necessary conversions\n boolean assuredFlag = (assuredType != AssuredType.NOT_ASSURED);\n AssuredMode assMode = ((assuredType == AssuredType.SAFE_READ) ? AssuredMode.SAFE_READ_MODE : AssuredMode.SAFE_DATA_MODE);\n List urls = new ArrayList();\n for (String str : refUrls) {\n urls.add(str);\n }\n return new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assMode, (byte) assuredSdLevel, groupId, urls, eclIncludes, eclIncludes, protocolVersion);\n }\n\n /**\n * Creates the topo view to be checked at each step of the test (view that\n * every concerned DS should have)\n */\n private TopoView createTheoreticalTopoViewForStep(int step) {\n List dsList = new ArrayList();\n List rsList = new ArrayList();\n switch(step) {\n case STEP_1:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n break;\n case STEP_2:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_3:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_4:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n break;\n case STEP_5:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n break;\n case STEP_6:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n break;\n case STEP_7:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_8:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_9:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_10:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_11:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n dsList.add(createDSInfo(DS6_ID, RS2_ID));\n break;\n case STEP_12:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_13:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n default:\n fail(\"Unknown test step: \" + step);\n }\n return new TopoView(dsList, rsList);\n }\n\n /**\n * Get the topo view each DS in the provided ds list has and compares it\n * with the theoretical topology view that every body should have at the time\n * this method is called.\n */\n private void checkTopoView(int[] dsIdList, TopoView theoricalTopoView) {\n sleep(500);\n for (int currentDsId : dsIdList) {\n LDAPReplicationDomain rd = null;\n switch(currentDsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n /**\n * Get the topo view of the current analyzed DS\n */\n List internalDsList = rd.getReplicasList();\n // Add info for DS itself:\n // we need to clone the list as we don't want to modify the list kept\n // inside the DS.\n List dsList = new ArrayList();\n for (DSInfo aDsInfo : internalDsList) {\n dsList.add(aDsInfo);\n }\n int dsId = rd.getServerId();\n int rsId = rd.getRsServerId();\n ServerStatus status = rd.getStatus();\n boolean assuredFlag = rd.isAssured();\n AssuredMode assuredMode = rd.getAssuredMode();\n byte safeDataLevel = rd.getAssuredSdLevel();\n byte groupId = rd.getGroupId();\n List refUrls = rd.getRefUrls();\n Set eclInclude = rd.getEclIncludes();\n Set eclIncludeForDeletes = rd.getEclIncludesForDeletes();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n DSInfo dsInfo = new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assuredMode, safeDataLevel, groupId, refUrls, eclInclude, eclIncludeForDeletes, protocolVersion);\n dsList.add(dsInfo);\n TopoView dsTopoView = new TopoView(dsList, rd.getRsList());\n /**\n * Compare to what is the expected view\n */\n assertEquals(dsTopoView, theoricalTopoView, \" in DSid=\" + currentDsId);\n }\n }\n\n /**\n * Bag class representing a view of the topology at a given time\n * (who is connected to who, what are the config parameters...)\n */\n private class TopoView {\n\n private List dsList = null;\n\n private List rsList = null;\n\n public TopoView(List dsList, List rsList) {\n assertNotNull(dsList);\n assertNotNull(rsList);\n this.dsList = dsList;\n this.rsList = rsList;\n }\n\n public boolean equals(Object obj) {\n assertNotNull(obj);\n assertFalse(obj.getClass() != this.getClass());\n TopoView topoView = (TopoView) obj;\n // Check dsList\n if (topoView.dsList.size() != dsList.size())\n return false;\n for (DSInfo dsInfo : topoView.dsList) {\n int found = 0;\n for (DSInfo thisDsInfo : dsList) {\n if (thisDsInfo.equals(dsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as dsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n // Check rsList\n if (topoView.rsList.size() != rsList.size())\n return false;\n for (RSInfo rsInfo : topoView.rsList) {\n int found = 0;\n for (RSInfo thisRsInfo : rsList) {\n if (thisRsInfo.equals(rsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as rsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n return true;\n }\n\n public String toString() {\n String dsStr = \"\";\n for (DSInfo dsInfo : dsList) {\n dsStr += dsInfo.toString() + \"\\n----------------------------\\n\";\n }\n String rsStr = \"\";\n for (RSInfo rsInfo : rsList) {\n rsStr += rsInfo.toString() + \"\\n----------------------------\\n\";\n }\n return (\"TopoView:\" + \"\\n----------------------------\\n\" + \"CONNECTED DS SERVERS:\\n\" + dsStr + \"CONNECTED RS SERVERS:\\n\" + rsStr);\n }\n }\n\n private String getHostPort(int port) {\n return LOCAL_HOST_NAME + \":\" + port;\n }\n}\n"} {"task_id": "Java_1931", "language": "Java", "task_type": "try_statement", "source_file": "java/github/ForgeRock/opendj-community-edition/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java", "mask_start_position": 4257, "mask_end_position": 4445, "canonical_solution": "try {\n LOCAL_HOST_NAME = InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n fail(\"Unable to resolve local host name\", e);\n }", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport java.net.UnknownHostException;\nimport static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;\nimport static org.opends.server.loggers.ErrorLogger.logError;\nimport static org.opends.server.loggers.debug.DebugLogger.debugEnabled;\nimport static org.opends.server.loggers.debug.DebugLogger.getTracer;\nimport static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\nimport org.opends.messages.Category;\nimport org.opends.messages.Message;\nimport org.opends.messages.Severity;\nimport org.opends.server.TestCaseUtils;\nimport org.opends.server.admin.std.meta.ReplicationDomainCfgDefn.AssuredType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.loggers.debug.DebugTracer;\nimport org.opends.server.replication.ReplicationTestCase;\nimport org.opends.server.replication.common.AssuredMode;\nimport org.opends.server.replication.common.DSInfo;\nimport org.opends.server.replication.common.RSInfo;\nimport org.opends.server.replication.common.ServerStatus;\nimport org.opends.server.replication.protocol.ProtocolVersion;\nimport org.opends.server.replication.server.ReplServerFakeConfiguration;\nimport org.opends.server.replication.server.ReplicationServer;\nimport org.opends.server.types.DN;\nimport org.opends.server.types.DirectoryException;\nimport org.opends.server.util.StaticUtils;\nimport org.testng.annotations.Test;\n\n/**\n * Some tests to know if at any time the view DSs and RSs have of the current\n * topology is accurate, even after some connections, disconnections and\n * re-connections events.\n */\npublic class TopologyViewTest extends ReplicationTestCase {\n\n // Server id definitions\n private static final int DS1_ID = 1;\n\n private static final int DS2_ID = 2;\n\n private static final int DS3_ID = 3;\n\n private static final int DS4_ID = 4;\n\n private static final int DS5_ID = 5;\n\n private static final int DS6_ID = 6;\n\n private static final int RS1_ID = 51;\n\n private static final int RS2_ID = 52;\n\n private static final int RS3_ID = 53;\n\n // Group id definitions\n private static final int DS1_GID = 1;\n\n private static final int DS2_GID = 1;\n\n private static final int DS3_GID = 2;\n\n private static final int DS4_GID = 2;\n\n private static final int DS5_GID = 3;\n\n private static final int DS6_GID = 3;\n\n private static final int RS1_GID = 1;\n\n private static final int RS2_GID = 2;\n\n private static final int RS3_GID = 3;\n\n // Assured conf definitions\n private static final AssuredType DS1_AT = AssuredType.NOT_ASSURED;\n\n private static final int DS1_SDL = -1;\n\n private static SortedSet DS1_RU = new TreeSet();\n\n private static final AssuredType DS2_AT = AssuredType.SAFE_READ;\n\n private static final int DS2_SDL = -1;\n\n private static SortedSet DS2_RU = new TreeSet();\n\n private static final AssuredType DS3_AT = AssuredType.SAFE_DATA;\n\n private static final int DS3_SDL = 1;\n\n private static SortedSet DS3_RU = new TreeSet();\n\n private static final AssuredType DS4_AT = AssuredType.SAFE_READ;\n\n private static final int DS4_SDL = -1;\n\n private static SortedSet DS4_RU = new TreeSet();\n\n private static final AssuredType DS5_AT = AssuredType.SAFE_DATA;\n\n private static final int DS5_SDL = 2;\n\n private static SortedSet DS5_RU = new TreeSet();\n\n private static final AssuredType DS6_AT = AssuredType.SAFE_READ;\n\n private static final int DS6_SDL = -1;\n\n private static SortedSet DS6_RU = new TreeSet();\n\n private static String LOCAL_HOST_NAME;\n\n static {\n DS2_RU.add(\"ldap://fake_url_for_ds2\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_A\");\n DS6_RU.add(\"ldap://fake_url_for_ds6_B\");\n ", "post_mask_code": "\n }\n\n private int rs1Port = -1;\n\n private int rs2Port = -1;\n\n private int rs3Port = -1;\n\n private LDAPReplicationDomain rd1 = null;\n\n private LDAPReplicationDomain rd2 = null;\n\n private LDAPReplicationDomain rd3 = null;\n\n private LDAPReplicationDomain rd4 = null;\n\n private LDAPReplicationDomain rd5 = null;\n\n private LDAPReplicationDomain rd6 = null;\n\n private ReplicationServer rs1 = null;\n\n private ReplicationServer rs2 = null;\n\n private ReplicationServer rs3 = null;\n\n // The tracer object for the debug logger\n private static final DebugTracer TRACER = getTracer();\n\n private void debugInfo(String s) {\n logError(Message.raw(Category.SYNC, Severity.NOTICE, s));\n if (debugEnabled()) {\n TRACER.debugInfo(\"** TEST **\" + s);\n }\n }\n\n private void initTest() {\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n rd1 = null;\n rd2 = null;\n rd3 = null;\n rd4 = null;\n rd5 = null;\n rd6 = null;\n rs1 = null;\n rs2 = null;\n rs3 = null;\n findFreePorts();\n }\n\n private void endTest() {\n if (rd1 != null) {\n rd1.shutdown();\n rd1 = null;\n }\n if (rd2 != null) {\n rd2.shutdown();\n rd2 = null;\n }\n if (rd3 != null) {\n rd3.shutdown();\n rd3 = null;\n }\n if (rd4 != null) {\n rd4.shutdown();\n rd4 = null;\n }\n if (rd5 != null) {\n rd5.shutdown();\n rd5 = null;\n }\n if (rd6 != null) {\n rd6.shutdown();\n rd6 = null;\n }\n try {\n // Clear any reference to a domain in synchro plugin\n MultimasterReplication.deleteDomain(DN.decode(TEST_ROOT_DN_STRING));\n } catch (DirectoryException ex) {\n fail(\"Error deleting reference to domain: \" + TEST_ROOT_DN_STRING);\n }\n if (rs1 != null) {\n rs1.clearDb();\n rs1.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs1.getDbDirName()));\n rs1 = null;\n }\n if (rs2 != null) {\n rs2.clearDb();\n rs2.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs2.getDbDirName()));\n rs2 = null;\n }\n if (rs3 != null) {\n rs3.clearDb();\n rs3.remove();\n StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(), rs3.getDbDirName()));\n rs3 = null;\n }\n rs1Port = -1;\n rs2Port = -1;\n rs3Port = -1;\n }\n\n private void sleep(long time) {\n try {\n Thread.sleep(time);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n }\n\n /**\n * Check connection of the provided replication domain to the provided\n * replication server. Waits for connection to be ok up to secTimeout seconds\n * before failing.\n */\n private void checkConnection(int secTimeout, int dsId, int rsId) {\n int rsPort = -1;\n LDAPReplicationDomain rd = null;\n switch(dsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n int nSec = 0;\n // Go out of the loop only if connection is verified or if timeout occurs\n while (true) {\n // Test connection\n boolean connected = rd.isConnected();\n int rdPort = -1;\n boolean rightPort = false;\n if (connected) {\n String serverStr = rd.getReplicationServer();\n int index = serverStr.lastIndexOf(':');\n if ((index == -1) || (index >= serverStr.length()))\n fail(\"Enable to find port number in: \" + serverStr);\n String rdPortStr = serverStr.substring(index + 1);\n try {\n rdPort = (new Integer(rdPortStr)).intValue();\n } catch (Exception e) {\n fail(\"Enable to get an int from: \" + rdPortStr);\n }\n if (rdPort == rsPort)\n rightPort = true;\n }\n if (connected && rightPort) {\n // Connection verified\n debugInfo(\"checkConnection: connection from domain \" + dsId + \" to\" + \" replication server \" + rsId + \" obtained after \" + nSec + \" seconds.\");\n return;\n }\n // Sleep 1 second\n try {\n Thread.sleep(1000);\n } catch (InterruptedException ex) {\n fail(\"Error sleeping \" + stackTraceToSingleLineString(ex));\n }\n nSec++;\n if (nSec > secTimeout) {\n // Timeout reached, end with error\n fail(\"checkConnection: could not verify connection from domain \" + dsId + \" to replication server \" + rsId + \" after \" + secTimeout + \" seconds.\" + \" Domain connected: \" + connected + \", connection port: \" + rdPort + \" (should be: \" + rsPort + \")\");\n }\n }\n }\n\n /**\n * Find needed free TCP ports.\n */\n private void findFreePorts() {\n try {\n ServerSocket socket1 = TestCaseUtils.bindFreePort();\n ServerSocket socket2 = TestCaseUtils.bindFreePort();\n ServerSocket socket3 = TestCaseUtils.bindFreePort();\n rs1Port = socket1.getLocalPort();\n rs2Port = socket2.getLocalPort();\n rs3Port = socket3.getLocalPort();\n socket1.close();\n socket2.close();\n socket3.close();\n } catch (IOException e) {\n fail(\"Unable to determinate some free ports \" + stackTraceToSingleLineString(e));\n }\n }\n\n /**\n * Creates the list of servers to represent the RS topology excluding the\n * RS whose id is passed.\n */\n private SortedSet createRSListExceptOne(int rsIdToExclude) {\n SortedSet replServers = new TreeSet();\n if (rsIdToExclude != RS1_ID) {\n replServers.add(getHostPort(rs1Port));\n }\n if (rsIdToExclude != RS2_ID) {\n replServers.add(getHostPort(rs2Port));\n }\n if (rsIdToExclude != RS3_ID) {\n replServers.add(getHostPort(rs3Port));\n }\n return replServers;\n }\n\n private ReplicationServer createReplicationServer(int rsId, String testCase) {\n try {\n SortedSet replServers = createRSListExceptOne(rsId);\n int rsPort = -1;\n int groupId = -1;\n switch(rsId) {\n case RS1_ID:\n rsPort = rs1Port;\n groupId = RS1_GID;\n break;\n case RS2_ID:\n rsPort = rs2Port;\n groupId = RS2_GID;\n break;\n case RS3_ID:\n rsPort = rs3Port;\n groupId = RS3_GID;\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n String dir = \"topologyViewTest\" + rsId + testCase + \"Db\";\n ReplServerFakeConfiguration conf = new ReplServerFakeConfiguration(rsPort, dir, 0, rsId, 0, 100, replServers, groupId, 1000, 5000);\n ReplicationServer replicationServer = new ReplicationServer(conf);\n return replicationServer;\n } catch (Exception e) {\n fail(\"createReplicationServer \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n /**\n * Creates and starts a new ReplicationDomain with the correct list of\n * know RSs according to DS id\n */\n private LDAPReplicationDomain createReplicationDomain(int dsId) {\n try {\n SortedSet replServers = new TreeSet();\n int groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n // Fill rs list according to defined scenario (see testTopologyChanges\n switch(dsId) {\n case DS1_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n replServers.add(getHostPort(rs1Port));\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n replServers.add(getHostPort(rs2Port));\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n replServers.add(getHostPort(rs2Port));\n replServers.add(getHostPort(rs3Port));\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n DN baseDn = DN.decode(TEST_ROOT_DN_STRING);\n DomainFakeCfg domainConf = new DomainFakeCfg(baseDn, dsId, replServers, assuredType, assuredSdLevel, groupId, 0, refUrls);\n LDAPReplicationDomain replicationDomain = MultimasterReplication.createNewDomain(domainConf);\n replicationDomain.start();\n return replicationDomain;\n } catch (Exception e) {\n fail(\"createReplicationDomain \" + stackTraceToSingleLineString(e));\n }\n return null;\n }\n\n // Definitions of steps for the test case\n private static final int STEP_1 = 1;\n\n private static final int STEP_2 = 2;\n\n private static final int STEP_3 = 3;\n\n private static final int STEP_4 = 4;\n\n private static final int STEP_5 = 5;\n\n private static final int STEP_6 = 6;\n\n private static final int STEP_7 = 7;\n\n private static final int STEP_8 = 8;\n\n private static final int STEP_9 = 9;\n\n private static final int STEP_10 = 10;\n\n private static final int STEP_11 = 11;\n\n private static final int STEP_12 = 12;\n\n private static final int STEP_13 = 13;\n\n /**\n * Perform connections/disconnections of DS/RS. Uses various config parameters\n * that are embedded in topo info to check if they are well transported.\n * This tests:\n * - if topo msgs are exchanged when needed and reflect topo reality (who is\n * connected to who)\n * - if topo msgs transport config params in terms of assured replication,\n * group id... that reflect what is configured in the DSs.\n *\n * Full topo is:\n * (GID=group id, A=assured, NA=not assured, SR=safe read, SD=safe data,\n * SDL=safe data level, RUF=ref urls filled, RUE=ref urls empty)\n * Except if otherwise stated, RSs and DSs are aware of every others existence\n * - RS1 with GID=1\n * - RS2 with GID=2\n * - RS3 with GID=3\n * - DS1 with GID=1, NA\n * - DS2 with GID=1, A, SR, RUF\n * - DS3 with GID=2, A, SD, SDL=1 (DS3 does not know RS1 and RS3)\n * - DS4 with GID=2, A, SR, RUE (DS4 does not know RS1 and RS3)\n * - DS5 with GID=3, A, SD, SDL=2 (DS5 does not know RS1)\n * - DS6 with GID=3, A, SR, RUF (DS6 does not know RS1)\n * Scenario is:\n * - RS1 starts\n * - DS1 starts and connects to RS1 (check topo view in DS1)\n * - DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n * - RS2 starts (check topo view in DS1,DS2)\n * - DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n * - DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n * - DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - RS3 starts (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n * - DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n * - RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n * - RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo view\n * in DS1,DS2,DS5,DS6)\n * @throws Exception If a problem occurred\n */\n @Test(enabled = true, groups = \"slow\")\n public void testTopologyChanges() throws Exception {\n String testCase = \"testTopologyChanges\";\n debugInfo(\"Starting \" + testCase);\n initTest();\n TopoView theoricalTopoView = null;\n try {\n /**\n * RS1 starts\n */\n debugInfo(\"*** STEP 0 ***\");\n rs1 = createReplicationServer(RS1_ID, testCase);\n /**\n * DS1 starts and connects to RS1 (check topo view in DS1)\n */\n debugInfo(\"*** STEP 1 ***\");\n rd1 = createReplicationDomain(DS1_ID);\n checkConnection(30, DS1_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_1);\n checkTopoView(new int[] { DS1_ID }, theoricalTopoView);\n /**\n * DS2 starts and connects to RS1 (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 2 ***\");\n rd2 = createReplicationDomain(DS2_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_2);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * RS2 starts (check topo view in DS1,DS2)\n */\n debugInfo(\"*** STEP 3 ***\");\n rs2 = createReplicationServer(RS2_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(1000);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_3);\n checkTopoView(new int[] { DS1_ID, DS2_ID }, theoricalTopoView);\n /**\n * DS3 starts and connects to RS2 (check topo view in DS1,DS2,DS3)\n */\n debugInfo(\"*** STEP 4 ***\");\n rd3 = createReplicationDomain(DS3_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_4);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID }, theoricalTopoView);\n /**\n * DS4 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4)\n */\n debugInfo(\"*** STEP 5 ***\");\n rd4 = createReplicationDomain(DS4_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_5);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID }, theoricalTopoView);\n /**\n * DS5 starts and connects to RS2 (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 6 ***\");\n rd5 = createReplicationDomain(DS5_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_6);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 should reconnect to RS3 (as RS with\n * same GID becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 7 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_7);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 8 ***\");\n rd6 = createReplicationDomain(DS6_ID);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_8);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * DS6 stops (check topo view in DS1,DS2,DS3,DS4,DS5)\n */\n debugInfo(\"*** STEP 9 ***\");\n rd6.disable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n assertFalse(rd6.isConnected());\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_9);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID }, theoricalTopoView);\n /**\n * DS6 starts and connects to RS3 (check topo view in DS1,DS2,DS3,DS4,DS5,\n * DS6)\n */\n debugInfo(\"*** STEP 10 ***\");\n rd6.enable();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_10);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 stops. DS5 and DS6 should failover to RS2 as do not know RS1 (check\n * topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 11 ***\");\n rs3.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS2_ID);\n checkConnection(30, DS6_ID, RS2_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_11);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS3 starts. DS5 and DS6 should reconnect to RS3 (as RS with same GID\n * becomes available) (check topo view in DS1,DS2,DS3,DS4,DS5,DS6)\n */\n debugInfo(\"*** STEP 12 ***\");\n rs3 = createReplicationServer(RS3_ID, testCase);\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS3_ID, RS2_ID);\n checkConnection(30, DS4_ID, RS2_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_12);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS3_ID, DS4_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n /**\n * RS2 stops. DS3 and DS4 do not reconnect to any RS as do not know RS1 and\n * RS3. This emulates a full RS with his connected DSs crash. (check topo\n * view in DS1,DS2,DS5,DS6)\n */\n debugInfo(\"*** STEP 13 ***\");\n rs2.remove();\n // Let time to topo msgs being propagated through the network\n sleep(500);\n checkConnection(30, DS1_ID, RS1_ID);\n checkConnection(30, DS2_ID, RS1_ID);\n checkConnection(30, DS5_ID, RS3_ID);\n checkConnection(30, DS6_ID, RS3_ID);\n theoricalTopoView = createTheoreticalTopoViewForStep(STEP_13);\n checkTopoView(new int[] { DS1_ID, DS2_ID, DS5_ID, DS6_ID }, theoricalTopoView);\n } finally {\n endTest();\n }\n }\n\n /**\n * Creates RSInfo for the passed RS\n */\n private RSInfo createRSInfo(int rsId) {\n int groupId = -1;\n String serverUrl = null;\n switch(rsId) {\n case RS1_ID:\n groupId = RS1_GID;\n serverUrl = getHostPort(rs1Port);\n break;\n case RS2_ID:\n groupId = RS2_GID;\n serverUrl = getHostPort(rs2Port);\n break;\n case RS3_ID:\n groupId = RS3_GID;\n serverUrl = getHostPort(rs3Port);\n break;\n default:\n fail(\"Unknown replication server id.\");\n }\n return new RSInfo(rsId, serverUrl, TEST_DN_WITH_ROOT_ENTRY_GENID, (byte) groupId, 1);\n }\n\n /**\n * Creates DSInfo for the passed DS, connected to the passed RS\n */\n private DSInfo createDSInfo(int dsId, int rsId) {\n ServerStatus status = ServerStatus.NORMAL_STATUS;\n byte groupId = -1;\n AssuredType assuredType = null;\n int assuredSdLevel = -100;\n SortedSet refUrls = null;\n Set eclIncludes = new HashSet();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n switch(dsId) {\n case DS1_ID:\n groupId = DS1_GID;\n assuredType = DS1_AT;\n assuredSdLevel = DS1_SDL;\n refUrls = DS1_RU;\n break;\n case DS2_ID:\n groupId = DS2_GID;\n assuredType = DS2_AT;\n assuredSdLevel = DS2_SDL;\n refUrls = DS2_RU;\n break;\n case DS3_ID:\n groupId = DS3_GID;\n assuredType = DS3_AT;\n assuredSdLevel = DS3_SDL;\n refUrls = DS3_RU;\n break;\n case DS4_ID:\n groupId = DS4_GID;\n assuredType = DS4_AT;\n assuredSdLevel = DS4_SDL;\n refUrls = DS4_RU;\n break;\n case DS5_ID:\n groupId = DS5_GID;\n assuredType = DS5_AT;\n assuredSdLevel = DS5_SDL;\n refUrls = DS5_RU;\n break;\n case DS6_ID:\n groupId = DS6_GID;\n assuredType = DS6_AT;\n assuredSdLevel = DS6_SDL;\n refUrls = DS6_RU;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n // Perform necessary conversions\n boolean assuredFlag = (assuredType != AssuredType.NOT_ASSURED);\n AssuredMode assMode = ((assuredType == AssuredType.SAFE_READ) ? AssuredMode.SAFE_READ_MODE : AssuredMode.SAFE_DATA_MODE);\n List urls = new ArrayList();\n for (String str : refUrls) {\n urls.add(str);\n }\n return new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assMode, (byte) assuredSdLevel, groupId, urls, eclIncludes, eclIncludes, protocolVersion);\n }\n\n /**\n * Creates the topo view to be checked at each step of the test (view that\n * every concerned DS should have)\n */\n private TopoView createTheoreticalTopoViewForStep(int step) {\n List dsList = new ArrayList();\n List rsList = new ArrayList();\n switch(step) {\n case STEP_1:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n break;\n case STEP_2:\n rsList.add(createRSInfo(RS1_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_3:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n break;\n case STEP_4:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n break;\n case STEP_5:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n break;\n case STEP_6:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n break;\n case STEP_7:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_8:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_9:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n break;\n case STEP_10:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_11:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS2_ID));\n dsList.add(createDSInfo(DS6_ID, RS2_ID));\n break;\n case STEP_12:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS2_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS3_ID, RS2_ID));\n dsList.add(createDSInfo(DS4_ID, RS2_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n case STEP_13:\n rsList.add(createRSInfo(RS1_ID));\n rsList.add(createRSInfo(RS3_ID));\n dsList.add(createDSInfo(DS1_ID, RS1_ID));\n dsList.add(createDSInfo(DS2_ID, RS1_ID));\n dsList.add(createDSInfo(DS5_ID, RS3_ID));\n dsList.add(createDSInfo(DS6_ID, RS3_ID));\n break;\n default:\n fail(\"Unknown test step: \" + step);\n }\n return new TopoView(dsList, rsList);\n }\n\n /**\n * Get the topo view each DS in the provided ds list has and compares it\n * with the theoretical topology view that every body should have at the time\n * this method is called.\n */\n private void checkTopoView(int[] dsIdList, TopoView theoricalTopoView) {\n sleep(500);\n for (int currentDsId : dsIdList) {\n LDAPReplicationDomain rd = null;\n switch(currentDsId) {\n case DS1_ID:\n rd = rd1;\n break;\n case DS2_ID:\n rd = rd2;\n break;\n case DS3_ID:\n rd = rd3;\n break;\n case DS4_ID:\n rd = rd4;\n break;\n case DS5_ID:\n rd = rd5;\n break;\n case DS6_ID:\n rd = rd6;\n break;\n default:\n fail(\"Unknown replication domain server id.\");\n }\n /**\n * Get the topo view of the current analyzed DS\n */\n List internalDsList = rd.getReplicasList();\n // Add info for DS itself:\n // we need to clone the list as we don't want to modify the list kept\n // inside the DS.\n List dsList = new ArrayList();\n for (DSInfo aDsInfo : internalDsList) {\n dsList.add(aDsInfo);\n }\n int dsId = rd.getServerId();\n int rsId = rd.getRsServerId();\n ServerStatus status = rd.getStatus();\n boolean assuredFlag = rd.isAssured();\n AssuredMode assuredMode = rd.getAssuredMode();\n byte safeDataLevel = rd.getAssuredSdLevel();\n byte groupId = rd.getGroupId();\n List refUrls = rd.getRefUrls();\n Set eclInclude = rd.getEclIncludes();\n Set eclIncludeForDeletes = rd.getEclIncludesForDeletes();\n short protocolVersion = ProtocolVersion.getCurrentVersion();\n DSInfo dsInfo = new DSInfo(dsId, \"dummy:1234\", rsId, TEST_DN_WITH_ROOT_ENTRY_GENID, status, assuredFlag, assuredMode, safeDataLevel, groupId, refUrls, eclInclude, eclIncludeForDeletes, protocolVersion);\n dsList.add(dsInfo);\n TopoView dsTopoView = new TopoView(dsList, rd.getRsList());\n /**\n * Compare to what is the expected view\n */\n assertEquals(dsTopoView, theoricalTopoView, \" in DSid=\" + currentDsId);\n }\n }\n\n /**\n * Bag class representing a view of the topology at a given time\n * (who is connected to who, what are the config parameters...)\n */\n private class TopoView {\n\n private List dsList = null;\n\n private List rsList = null;\n\n public TopoView(List dsList, List rsList) {\n assertNotNull(dsList);\n assertNotNull(rsList);\n this.dsList = dsList;\n this.rsList = rsList;\n }\n\n public boolean equals(Object obj) {\n assertNotNull(obj);\n assertFalse(obj.getClass() != this.getClass());\n TopoView topoView = (TopoView) obj;\n // Check dsList\n if (topoView.dsList.size() != dsList.size())\n return false;\n for (DSInfo dsInfo : topoView.dsList) {\n int found = 0;\n for (DSInfo thisDsInfo : dsList) {\n if (thisDsInfo.equals(dsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as dsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n // Check rsList\n if (topoView.rsList.size() != rsList.size())\n return false;\n for (RSInfo rsInfo : topoView.rsList) {\n int found = 0;\n for (RSInfo thisRsInfo : rsList) {\n if (thisRsInfo.equals(rsInfo))\n found++;\n }\n // Not found\n if (found == 0)\n return false;\n // Should never see twice as rsInfo structure in a dsList\n assertFalse(found > 1);\n // Ok, found exactly once in the list, examine next structure\n }\n return true;\n }\n\n public String toString() {\n String dsStr = \"\";\n for (DSInfo dsInfo : dsList) {\n dsStr += dsInfo.toString() + \"\\n----------------------------\\n\";\n }\n String rsStr = \"\";\n for (RSInfo rsInfo : rsList) {\n rsStr += rsInfo.toString() + \"\\n----------------------------\\n\";\n }\n return (\"TopoView:\" + \"\\n----------------------------\\n\" + \"CONNECTED DS SERVERS:\\n\" + dsStr + \"CONNECTED RS SERVERS:\\n\" + rsStr);\n }\n }\n\n private String getHostPort(int port) {\n return LOCAL_HOST_NAME + \":\" + port;\n }\n}\n"} {"task_id": "Java_1932", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jdemetra/jdemetra-app/nbdemetra-ui/src/main/java/ec/nbdemetra/ui/actions/ReloadAction.java", "mask_start_position": 645, "mask_end_position": 717, "canonical_solution": "@Override\n protected void performAction(Iterable items) ", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage ec.nbdemetra.ui.actions;\n\nimport ec.nbdemetra.ui.IReloadable;\nimport org.openide.awt.ActionID;\nimport org.openide.awt.ActionRegistration;\nimport org.openide.util.NbBundle;\n\n/**\n * @author Philippe Charles\n */\n@ActionID(category = \"File\", id = \"ec.nbdemetra.ui.actions.ReloadAction\")\n@ActionRegistration(displayName = \"#ReloadAction\", lazy = false)\n@NbBundle.Messages({ \"ReloadAction=Reload\" })\npublic final class ReloadAction extends AbilityAction {\n\n public ReloadAction() {\n super(IReloadable.class);\n }\n\n ", "post_mask_code": "{\n for (IReloadable o : items) {\n o.reload();\n }\n }\n\n @Override\n public String getName() {\n return Bundle.ReloadAction();\n }\n}\n"} {"task_id": "Java_1933", "language": "Java", "task_type": "method_body", "source_file": "java/github/jdemetra/jdemetra-app/nbdemetra-ui/src/main/java/ec/nbdemetra/ui/actions/ReloadAction.java", "mask_start_position": 717, "mask_end_position": 796, "canonical_solution": "{\n for (IReloadable o : items) {\n o.reload();\n }\n }", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage ec.nbdemetra.ui.actions;\n\nimport ec.nbdemetra.ui.IReloadable;\nimport org.openide.awt.ActionID;\nimport org.openide.awt.ActionRegistration;\nimport org.openide.util.NbBundle;\n\n/**\n * @author Philippe Charles\n */\n@ActionID(category = \"File\", id = \"ec.nbdemetra.ui.actions.ReloadAction\")\n@ActionRegistration(displayName = \"#ReloadAction\", lazy = false)\n@NbBundle.Messages({ \"ReloadAction=Reload\" })\npublic final class ReloadAction extends AbilityAction {\n\n public ReloadAction() {\n super(IReloadable.class);\n }\n\n @Override\n protected void performAction(Iterable items) ", "post_mask_code": "\n\n @Override\n public String getName() {\n return Bundle.ReloadAction();\n }\n}\n"} {"task_id": "Java_1934", "language": "Java", "task_type": "single_line", "source_file": "java/github/jdemetra/jdemetra-app/nbdemetra-ui/src/main/java/ec/nbdemetra/ui/actions/ReloadAction.java", "mask_start_position": 866, "mask_end_position": 879, "canonical_solution": "loadAction();", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage ec.nbdemetra.ui.actions;\n\nimport ec.nbdemetra.ui.IReloadable;\nimport org.openide.awt.ActionID;\nimport org.openide.awt.ActionRegistration;\nimport org.openide.util.NbBundle;\n\n/**\n * @author Philippe Charles\n */\n@ActionID(category = \"File\", id = \"ec.nbdemetra.ui.actions.ReloadAction\")\n@ActionRegistration(displayName = \"#ReloadAction\", lazy = false)\n@NbBundle.Messages({ \"ReloadAction=Reload\" })\npublic final class ReloadAction extends AbilityAction {\n\n public ReloadAction() {\n super(IReloadable.class);\n }\n\n @Override\n protected void performAction(Iterable items) {\n for (IReloadable o : items) {\n o.reload();\n }\n }\n\n @Override\n public String getName() {\n return Bundle.Re", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1935", "language": "Java", "task_type": "method_signature", "source_file": "java/github/mitchtabian/Google-Maps-2018/app/src/main/java/com/codingwithmitch/googlemaps2018/adapters/ChatroomRecyclerAdapter.java", "mask_start_position": 896, "mask_end_position": 1001, "canonical_solution": "@NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) ", "pre_mask_code": "package com.codingwithmitch.googlemaps2018.adapters;\n\nimport android.support.annotation.NonNull;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport com.codingwithmitch.googlemaps2018.R;\nimport com.codingwithmitch.googlemaps2018.models.Chatroom;\nimport java.util.ArrayList;\n\npublic class ChatroomRecyclerAdapter extends RecyclerView.Adapter {\n\n private ArrayList mChatrooms = new ArrayList<>();\n\n private ChatroomRecyclerClickListener mChatroomRecyclerClickListener;\n\n public ChatroomRecyclerAdapter(ArrayList chatrooms, ChatroomRecyclerClickListener chatroomRecyclerClickListener) {\n this.mChatrooms = chatrooms;\n mChatroomRecyclerClickListener = chatroomRecyclerClickListener;\n }\n\n ", "post_mask_code": "{\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_chatroom_list_item, parent, false);\n final ViewHolder holder = new ViewHolder(view, mChatroomRecyclerClickListener);\n return holder;\n }\n\n @Override\n public void onBindViewHolder(@NonNull ViewHolder holder, int position) {\n ((ViewHolder) holder).chatroomTitle.setText(mChatrooms.get(position).getTitle());\n }\n\n @Override\n public int getItemCount() {\n return mChatrooms.size();\n }\n\n public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {\n\n TextView chatroomTitle;\n\n ChatroomRecyclerClickListener clickListener;\n\n public ViewHolder(View itemView, ChatroomRecyclerClickListener clickListener) {\n super(itemView);\n chatroomTitle = itemView.findViewById(R.id.chatroom_title);\n this.clickListener = clickListener;\n itemView.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View v) {\n clickListener.onChatroomSelected(getAdapterPosition());\n }\n }\n\n public interface ChatroomRecyclerClickListener {\n\n public void onChatroomSelected(int position);\n }\n}\n"} {"task_id": "Java_1936", "language": "Java", "task_type": "method_body", "source_file": "java/github/mitchtabian/Google-Maps-2018/app/src/main/java/com/codingwithmitch/googlemaps2018/adapters/ChatroomRecyclerAdapter.java", "mask_start_position": 2048, "mask_end_position": 2127, "canonical_solution": "{\n clickListener.onChatroomSelected(getAdapterPosition());\n }", "pre_mask_code": "package com.codingwithmitch.googlemaps2018.adapters;\n\nimport android.support.annotation.NonNull;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport com.codingwithmitch.googlemaps2018.R;\nimport com.codingwithmitch.googlemaps2018.models.Chatroom;\nimport java.util.ArrayList;\n\npublic class ChatroomRecyclerAdapter extends RecyclerView.Adapter {\n\n private ArrayList mChatrooms = new ArrayList<>();\n\n private ChatroomRecyclerClickListener mChatroomRecyclerClickListener;\n\n public ChatroomRecyclerAdapter(ArrayList chatrooms, ChatroomRecyclerClickListener chatroomRecyclerClickListener) {\n this.mChatrooms = chatrooms;\n mChatroomRecyclerClickListener = chatroomRecyclerClickListener;\n }\n\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_chatroom_list_item, parent, false);\n final ViewHolder holder = new ViewHolder(view, mChatroomRecyclerClickListener);\n return holder;\n }\n\n @Override\n public void onBindViewHolder(@NonNull ViewHolder holder, int position) {\n ((ViewHolder) holder).chatroomTitle.setText(mChatrooms.get(position).getTitle());\n }\n\n @Override\n public int getItemCount() {\n return mChatrooms.size();\n }\n\n public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {\n\n TextView chatroomTitle;\n\n ChatroomRecyclerClickListener clickListener;\n\n public ViewHolder(View itemView, ChatroomRecyclerClickListener clickListener) {\n super(itemView);\n chatroomTitle = itemView.findViewById(R.id.chatroom_title);\n this.clickListener = clickListener;\n itemView.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View v) ", "post_mask_code": "\n }\n\n public interface ChatroomRecyclerClickListener {\n\n public void onChatroomSelected(int position);\n }\n}\n"} {"task_id": "Java_1937", "language": "Java", "task_type": "single_line", "source_file": "java/github/mitchtabian/Google-Maps-2018/app/src/main/java/com/codingwithmitch/googlemaps2018/adapters/ChatroomRecyclerAdapter.java", "mask_start_position": 1196, "mask_end_position": 1211, "canonical_solution": "ClickListener);", "pre_mask_code": "package com.codingwithmitch.googlemaps2018.adapters;\n\nimport android.support.annotation.NonNull;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport com.codingwithmitch.googlemaps2018.R;\nimport com.codingwithmitch.googlemaps2018.models.Chatroom;\nimport java.util.ArrayList;\n\npublic class ChatroomRecyclerAdapter extends RecyclerView.Adapter {\n\n private ArrayList mChatrooms = new ArrayList<>();\n\n private ChatroomRecyclerClickListener mChatroomRecyclerClickListener;\n\n public ChatroomRecyclerAdapter(ArrayList chatrooms, ChatroomRecyclerClickListener chatroomRecyclerClickListener) {\n this.mChatrooms = chatrooms;\n mChatroomRecyclerClickListener = chatroomRecyclerClickListener;\n }\n\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_chatroom_list_item, parent, false);\n final ViewHolder holder = new ViewHolder(view, mChatroomRecycler", "post_mask_code": "\n return holder;\n }\n\n @Override\n public void onBindViewHolder(@NonNull ViewHolder holder, int position) {\n ((ViewHolder) holder).chatroomTitle.setText(mChatrooms.get(position).getTitle());\n }\n\n @Override\n public int getItemCount() {\n return mChatrooms.size();\n }\n\n public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {\n\n TextView chatroomTitle;\n\n ChatroomRecyclerClickListener clickListener;\n\n public ViewHolder(View itemView, ChatroomRecyclerClickListener clickListener) {\n super(itemView);\n chatroomTitle = itemView.findViewById(R.id.chatroom_title);\n this.clickListener = clickListener;\n itemView.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View v) {\n clickListener.onChatroomSelected(getAdapterPosition());\n }\n }\n\n public interface ChatroomRecyclerClickListener {\n\n public void onChatroomSelected(int position);\n }\n}\n"} {"task_id": "Java_1938", "language": "Java", "task_type": "method_signature", "source_file": "java/github/dennisjzh/GwtMobile/kitchensink/com/gwtmobile/ui/kitchensink/client/widget/FlipSwitchPage.java", "mask_start_position": 855, "mask_end_position": 936, "canonical_solution": "@UiHandler(\"android\")\n void onValueChangeAndroid(ValueChangeEvent e) ", "pre_mask_code": "package com.gwtmobile.ui.kitchensink.client.widget;\n\nimport com.google.gwt.core.client.GWT;\nimport com.google.gwt.event.logical.shared.ValueChangeEvent;\nimport com.google.gwt.uibinder.client.UiBinder;\nimport com.google.gwt.uibinder.client.UiHandler;\nimport com.google.gwt.user.client.ui.Widget;\nimport com.gwtmobile.ui.client.page.Page;\nimport com.gwtmobile.ui.client.utils.Utils;\n\npublic class FlipSwitchPage extends Page {\n\n private static FlipSwitchPageUiBinder uiBinder = GWT.create(FlipSwitchPageUiBinder.class);\n\n interface FlipSwitchPageUiBinder extends UiBinder {\n }\n\n public FlipSwitchPage() {\n initWidget(uiBinder.createAndBindUi(this));\n }\n\n @UiHandler(\"iphone\")\n void onValueChangeIPhone(ValueChangeEvent e) {\n Utils.Console(\"Flip switch iPhone \" + e.getValue());\n }\n\n ", "post_mask_code": "{\n Utils.Console(\"Flip switch android \" + e.getValue());\n }\n\n @UiHandler(\"blackberry\")\n void onValueChangeBlackBerry(ValueChangeEvent e) {\n Utils.Console(\"Flip switch blackberry \" + e.getValue());\n }\n\n @UiHandler(\"webos\")\n void onValueChangeWebOS(ValueChangeEvent e) {\n Utils.Console(\"Flip switch webos \" + e.getValue());\n }\n\n @UiHandler(\"wp7\")\n void onValueChangeWP7(ValueChangeEvent e) {\n Utils.Console(\"Flip switch wp7 \" + e.getValue());\n }\n}\n"} {"task_id": "Java_1939", "language": "Java", "task_type": "method_body", "source_file": "java/github/dennisjzh/GwtMobile/kitchensink/com/gwtmobile/ui/kitchensink/client/widget/FlipSwitchPage.java", "mask_start_position": 1399, "mask_end_position": 1464, "canonical_solution": "{\n Utils.Console(\"Flip switch wp7 \" + e.getValue());\n }", "pre_mask_code": "package com.gwtmobile.ui.kitchensink.client.widget;\n\nimport com.google.gwt.core.client.GWT;\nimport com.google.gwt.event.logical.shared.ValueChangeEvent;\nimport com.google.gwt.uibinder.client.UiBinder;\nimport com.google.gwt.uibinder.client.UiHandler;\nimport com.google.gwt.user.client.ui.Widget;\nimport com.gwtmobile.ui.client.page.Page;\nimport com.gwtmobile.ui.client.utils.Utils;\n\npublic class FlipSwitchPage extends Page {\n\n private static FlipSwitchPageUiBinder uiBinder = GWT.create(FlipSwitchPageUiBinder.class);\n\n interface FlipSwitchPageUiBinder extends UiBinder {\n }\n\n public FlipSwitchPage() {\n initWidget(uiBinder.createAndBindUi(this));\n }\n\n @UiHandler(\"iphone\")\n void onValueChangeIPhone(ValueChangeEvent e) {\n Utils.Console(\"Flip switch iPhone \" + e.getValue());\n }\n\n @UiHandler(\"android\")\n void onValueChangeAndroid(ValueChangeEvent e) {\n Utils.Console(\"Flip switch android \" + e.getValue());\n }\n\n @UiHandler(\"blackberry\")\n void onValueChangeBlackBerry(ValueChangeEvent e) {\n Utils.Console(\"Flip switch blackberry \" + e.getValue());\n }\n\n @UiHandler(\"webos\")\n void onValueChangeWebOS(ValueChangeEvent e) {\n Utils.Console(\"Flip switch webos \" + e.getValue());\n }\n\n @UiHandler(\"wp7\")\n void onValueChangeWP7(ValueChangeEvent e) ", "post_mask_code": "\n}\n"} {"task_id": "Java_1940", "language": "Java", "task_type": "single_line", "source_file": "java/github/dennisjzh/GwtMobile/kitchensink/com/gwtmobile/ui/kitchensink/client/widget/FlipSwitchPage.java", "mask_start_position": 946, "mask_end_position": 999, "canonical_solution": "Utils.Console(\"Flip switch android \" + e.getValue());", "pre_mask_code": "package com.gwtmobile.ui.kitchensink.client.widget;\n\nimport com.google.gwt.core.client.GWT;\nimport com.google.gwt.event.logical.shared.ValueChangeEvent;\nimport com.google.gwt.uibinder.client.UiBinder;\nimport com.google.gwt.uibinder.client.UiHandler;\nimport com.google.gwt.user.client.ui.Widget;\nimport com.gwtmobile.ui.client.page.Page;\nimport com.gwtmobile.ui.client.utils.Utils;\n\npublic class FlipSwitchPage extends Page {\n\n private static FlipSwitchPageUiBinder uiBinder = GWT.create(FlipSwitchPageUiBinder.class);\n\n interface FlipSwitchPageUiBinder extends UiBinder {\n }\n\n public FlipSwitchPage() {\n initWidget(uiBinder.createAndBindUi(this));\n }\n\n @UiHandler(\"iphone\")\n void onValueChangeIPhone(ValueChangeEvent e) {\n Utils.Console(\"Flip switch iPhone \" + e.getValue());\n }\n\n @UiHandler(\"android\")\n void onValueChangeAndroid(ValueChangeEvent e) {\n ", "post_mask_code": "\n }\n\n @UiHandler(\"blackberry\")\n void onValueChangeBlackBerry(ValueChangeEvent e) {\n Utils.Console(\"Flip switch blackberry \" + e.getValue());\n }\n\n @UiHandler(\"webos\")\n void onValueChangeWebOS(ValueChangeEvent e) {\n Utils.Console(\"Flip switch webos \" + e.getValue());\n }\n\n @UiHandler(\"wp7\")\n void onValueChangeWP7(ValueChangeEvent e) {\n Utils.Console(\"Flip switch wp7 \" + e.getValue());\n }\n}\n"} {"task_id": "Java_1941", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jMonkeyEngine/sdk/jme3-assetpack-support/src/com/jme3/gde/assetpack/browser/AssetPackLibrary.java", "mask_start_position": 5121, "mask_end_position": 5173, "canonical_solution": "public ProjectAssetManager getProjectAssetManager() ", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage com.jme3.gde.assetpack.browser;\n\nimport com.jme3.gde.assetpack.browser.nodes.AssetPackBrowserFolder;\nimport com.jme3.gde.assetpack.Installer;\nimport com.jme3.gde.assetpack.XmlHelper;\nimport com.jme3.gde.core.assets.ProjectAssetManager;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport org.netbeans.api.project.Project;\nimport org.openide.filesystems.FileObject;\nimport org.openide.filesystems.FileUtil;\nimport org.openide.nodes.Node;\nimport org.openide.util.Exceptions;\nimport org.openide.util.Lookup;\nimport org.openide.util.NbPreferences;\nimport org.openide.util.lookup.AbstractLookup;\nimport org.openide.util.lookup.InstanceContent;\nimport org.openide.xml.XMLUtil;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.xml.sax.InputSource;\n\n/**\n * @author normenhansen\n */\npublic class AssetPackLibrary implements Project {\n\n FileObject library;\n\n Element[] assetElements = new Element[0];\n\n InstanceContent content = new InstanceContent();\n\n Lookup lookup = new AbstractLookup(content);\n\n private ProjectAssetManager projectAssetManager;\n\n private List categories = new LinkedList();\n\n public AssetPackLibrary() {\n content.add(this);\n }\n\n private void initLibrary() {\n String path = NbPreferences.forModule(Installer.class).get(\"assetpack_path\", null);\n library = FileUtil.toFileObject(new File(path));\n }\n\n public Node getRootNode() {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this);\n return multi;\n }\n\n public Node getRootNode(String[] categories, String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, categories, tags);\n return multi;\n }\n\n public Node getRootNode(String category) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, new String[] { category }, null);\n return multi;\n }\n\n public Node getRootNode(String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, null, tags);\n return multi;\n }\n\n private void parseLibrary() {\n initLibrary();\n categories.clear();\n FileObject[] object = library.getChildren();\n List assetElements = new LinkedList();\n for (int i = 0; i < object.length; i++) {\n FileObject fileObject = object[i];\n if (fileObject.isFolder()) {\n FileObject config = fileObject.getFileObject(\"assetpack.xml\");\n if (config != null) {\n InputStream in;\n try {\n in = config.getInputStream();\n Document doc = XMLUtil.parse(new InputSource(in), false, false, null, null);\n in.close();\n Element assets = XmlHelper.findChildElement(doc.getDocumentElement(), \"assets\");\n if (assets != null) {\n assetElements.add(assets);\n }\n } catch (Exception ex) {\n Exceptions.printStackTrace(ex);\n }\n if (projectAssetManager == null) {\n projectAssetManager = new ProjectAssetManager(this, fileObject.getNameExt() + \"/assets/\");\n content.add(projectAssetManager);\n } else {\n projectAssetManager.addFolderLocator(fileObject.getNameExt() + \"/assets/\");\n }\n } else {\n Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, \"Error in assetpack, could not load assetpack.xml!\");\n }\n }\n }\n this.assetElements = new Element[assetElements.size()];\n for (int i = 0; i < assetElements.size(); i++) {\n Element element = assetElements.get(i);\n this.assetElements[i] = element;\n Element child = XmlHelper.findChildElement(element, \"asset\");\n while (child != null) {\n String cats = child.getAttribute(\"categories\");\n String[] categs = cats.split(\",\");\n for (int j = 0; j < categs.length; j++) {\n String string = categs[j];\n string = string.trim();\n if (!categories.contains(string)) {\n categories.add(string);\n }\n }\n child = XmlHelper.findNextElement(child, \"asset\");\n }\n }\n }\n\n public FileObject getProjectDirectory() {\n return library;\n }\n\n public Lookup getLookup() {\n return lookup;\n }\n\n /**\n * @return the projectAssetManager\n */\n ", "post_mask_code": "{\n return projectAssetManager;\n }\n\n /**\n * @return the categories\n */\n public List getCategories() {\n return categories;\n }\n}\n"} {"task_id": "Java_1942", "language": "Java", "task_type": "method_body", "source_file": "java/github/jMonkeyEngine/sdk/jme3-assetpack-support/src/com/jme3/gde/assetpack/browser/AssetPackLibrary.java", "mask_start_position": 1466, "mask_end_position": 1622, "canonical_solution": "{\n String path = NbPreferences.forModule(Installer.class).get(\"assetpack_path\", null);\n library = FileUtil.toFileObject(new File(path));\n }", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage com.jme3.gde.assetpack.browser;\n\nimport com.jme3.gde.assetpack.browser.nodes.AssetPackBrowserFolder;\nimport com.jme3.gde.assetpack.Installer;\nimport com.jme3.gde.assetpack.XmlHelper;\nimport com.jme3.gde.core.assets.ProjectAssetManager;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport org.netbeans.api.project.Project;\nimport org.openide.filesystems.FileObject;\nimport org.openide.filesystems.FileUtil;\nimport org.openide.nodes.Node;\nimport org.openide.util.Exceptions;\nimport org.openide.util.Lookup;\nimport org.openide.util.NbPreferences;\nimport org.openide.util.lookup.AbstractLookup;\nimport org.openide.util.lookup.InstanceContent;\nimport org.openide.xml.XMLUtil;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.xml.sax.InputSource;\n\n/**\n * @author normenhansen\n */\npublic class AssetPackLibrary implements Project {\n\n FileObject library;\n\n Element[] assetElements = new Element[0];\n\n InstanceContent content = new InstanceContent();\n\n Lookup lookup = new AbstractLookup(content);\n\n private ProjectAssetManager projectAssetManager;\n\n private List categories = new LinkedList();\n\n public AssetPackLibrary() {\n content.add(this);\n }\n\n private void initLibrary() ", "post_mask_code": "\n\n public Node getRootNode() {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this);\n return multi;\n }\n\n public Node getRootNode(String[] categories, String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, categories, tags);\n return multi;\n }\n\n public Node getRootNode(String category) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, new String[] { category }, null);\n return multi;\n }\n\n public Node getRootNode(String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, null, tags);\n return multi;\n }\n\n private void parseLibrary() {\n initLibrary();\n categories.clear();\n FileObject[] object = library.getChildren();\n List assetElements = new LinkedList();\n for (int i = 0; i < object.length; i++) {\n FileObject fileObject = object[i];\n if (fileObject.isFolder()) {\n FileObject config = fileObject.getFileObject(\"assetpack.xml\");\n if (config != null) {\n InputStream in;\n try {\n in = config.getInputStream();\n Document doc = XMLUtil.parse(new InputSource(in), false, false, null, null);\n in.close();\n Element assets = XmlHelper.findChildElement(doc.getDocumentElement(), \"assets\");\n if (assets != null) {\n assetElements.add(assets);\n }\n } catch (Exception ex) {\n Exceptions.printStackTrace(ex);\n }\n if (projectAssetManager == null) {\n projectAssetManager = new ProjectAssetManager(this, fileObject.getNameExt() + \"/assets/\");\n content.add(projectAssetManager);\n } else {\n projectAssetManager.addFolderLocator(fileObject.getNameExt() + \"/assets/\");\n }\n } else {\n Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, \"Error in assetpack, could not load assetpack.xml!\");\n }\n }\n }\n this.assetElements = new Element[assetElements.size()];\n for (int i = 0; i < assetElements.size(); i++) {\n Element element = assetElements.get(i);\n this.assetElements[i] = element;\n Element child = XmlHelper.findChildElement(element, \"asset\");\n while (child != null) {\n String cats = child.getAttribute(\"categories\");\n String[] categs = cats.split(\",\");\n for (int j = 0; j < categs.length; j++) {\n String string = categs[j];\n string = string.trim();\n if (!categories.contains(string)) {\n categories.add(string);\n }\n }\n child = XmlHelper.findNextElement(child, \"asset\");\n }\n }\n }\n\n public FileObject getProjectDirectory() {\n return library;\n }\n\n public Lookup getLookup() {\n return lookup;\n }\n\n /**\n * @return the projectAssetManager\n */\n public ProjectAssetManager getProjectAssetManager() {\n return projectAssetManager;\n }\n\n /**\n * @return the categories\n */\n public List getCategories() {\n return categories;\n }\n}\n"} {"task_id": "Java_1943", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/jMonkeyEngine/sdk/jme3-assetpack-support/src/com/jme3/gde/assetpack/browser/AssetPackLibrary.java", "mask_start_position": 2474, "mask_end_position": 2525, "canonical_solution": "\n initLibrary();\n categories.clear();", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage com.jme3.gde.assetpack.browser;\n\nimport com.jme3.gde.assetpack.browser.nodes.AssetPackBrowserFolder;\nimport com.jme3.gde.assetpack.Installer;\nimport com.jme3.gde.assetpack.XmlHelper;\nimport com.jme3.gde.core.assets.ProjectAssetManager;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport org.netbeans.api.project.Project;\nimport org.openide.filesystems.FileObject;\nimport org.openide.filesystems.FileUtil;\nimport org.openide.nodes.Node;\nimport org.openide.util.Exceptions;\nimport org.openide.util.Lookup;\nimport org.openide.util.NbPreferences;\nimport org.openide.util.lookup.AbstractLookup;\nimport org.openide.util.lookup.InstanceContent;\nimport org.openide.xml.XMLUtil;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.xml.sax.InputSource;\n\n/**\n * @author normenhansen\n */\npublic class AssetPackLibrary implements Project {\n\n FileObject library;\n\n Element[] assetElements = new Element[0];\n\n InstanceContent content = new InstanceContent();\n\n Lookup lookup = new AbstractLookup(content);\n\n private ProjectAssetManager projectAssetManager;\n\n private List categories = new LinkedList();\n\n public AssetPackLibrary() {\n content.add(this);\n }\n\n private void initLibrary() {\n String path = NbPreferences.forModule(Installer.class).get(\"assetpack_path\", null);\n library = FileUtil.toFileObject(new File(path));\n }\n\n public Node getRootNode() {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this);\n return multi;\n }\n\n public Node getRootNode(String[] categories, String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, categories, tags);\n return multi;\n }\n\n public Node getRootNode(String category) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, new String[] { category }, null);\n return multi;\n }\n\n public Node getRootNode(String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, null, tags);\n return multi;\n }\n\n private void parseLibrary() {", "post_mask_code": "\n FileObject[] object = library.getChildren();\n List assetElements = new LinkedList();\n for (int i = 0; i < object.length; i++) {\n FileObject fileObject = object[i];\n if (fileObject.isFolder()) {\n FileObject config = fileObject.getFileObject(\"assetpack.xml\");\n if (config != null) {\n InputStream in;\n try {\n in = config.getInputStream();\n Document doc = XMLUtil.parse(new InputSource(in), false, false, null, null);\n in.close();\n Element assets = XmlHelper.findChildElement(doc.getDocumentElement(), \"assets\");\n if (assets != null) {\n assetElements.add(assets);\n }\n } catch (Exception ex) {\n Exceptions.printStackTrace(ex);\n }\n if (projectAssetManager == null) {\n projectAssetManager = new ProjectAssetManager(this, fileObject.getNameExt() + \"/assets/\");\n content.add(projectAssetManager);\n } else {\n projectAssetManager.addFolderLocator(fileObject.getNameExt() + \"/assets/\");\n }\n } else {\n Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, \"Error in assetpack, could not load assetpack.xml!\");\n }\n }\n }\n this.assetElements = new Element[assetElements.size()];\n for (int i = 0; i < assetElements.size(); i++) {\n Element element = assetElements.get(i);\n this.assetElements[i] = element;\n Element child = XmlHelper.findChildElement(element, \"asset\");\n while (child != null) {\n String cats = child.getAttribute(\"categories\");\n String[] categs = cats.split(\",\");\n for (int j = 0; j < categs.length; j++) {\n String string = categs[j];\n string = string.trim();\n if (!categories.contains(string)) {\n categories.add(string);\n }\n }\n child = XmlHelper.findNextElement(child, \"asset\");\n }\n }\n }\n\n public FileObject getProjectDirectory() {\n return library;\n }\n\n public Lookup getLookup() {\n return lookup;\n }\n\n /**\n * @return the projectAssetManager\n */\n public ProjectAssetManager getProjectAssetManager() {\n return projectAssetManager;\n }\n\n /**\n * @return the categories\n */\n public List getCategories() {\n return categories;\n }\n}\n"} {"task_id": "Java_1944", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/jMonkeyEngine/sdk/jme3-assetpack-support/src/com/jme3/gde/assetpack/browser/AssetPackLibrary.java", "mask_start_position": 2534, "mask_end_position": 4088, "canonical_solution": "FileObject[] object = library.getChildren();\n List assetElements = new LinkedList();\n for (int i = 0; i < object.length; i++) {\n FileObject fileObject = object[i];\n if (fileObject.isFolder()) {\n FileObject config = fileObject.getFileObject(\"assetpack.xml\");\n if (config != null) {\n InputStream in;\n try {\n in = config.getInputStream();\n Document doc = XMLUtil.parse(new InputSource(in), false, false, null, null);\n in.close();\n Element assets = XmlHelper.findChildElement(doc.getDocumentElement(), \"assets\");\n if (assets != null) {\n assetElements.add(assets);\n }\n } catch (Exception ex) {\n Exceptions.printStackTrace(ex);\n }\n if (projectAssetManager == null) {\n projectAssetManager = new ProjectAssetManager(this, fileObject.getNameExt() + \"/assets/\");\n content.add(projectAssetManager);\n } else {\n projectAssetManager.addFolderLocator(fileObject.getNameExt() + \"/assets/\");\n }\n } else {\n Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, \"Error in assetpack, could not load assetpack.xml!\");\n }\n }\n }", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage com.jme3.gde.assetpack.browser;\n\nimport com.jme3.gde.assetpack.browser.nodes.AssetPackBrowserFolder;\nimport com.jme3.gde.assetpack.Installer;\nimport com.jme3.gde.assetpack.XmlHelper;\nimport com.jme3.gde.core.assets.ProjectAssetManager;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport org.netbeans.api.project.Project;\nimport org.openide.filesystems.FileObject;\nimport org.openide.filesystems.FileUtil;\nimport org.openide.nodes.Node;\nimport org.openide.util.Exceptions;\nimport org.openide.util.Lookup;\nimport org.openide.util.NbPreferences;\nimport org.openide.util.lookup.AbstractLookup;\nimport org.openide.util.lookup.InstanceContent;\nimport org.openide.xml.XMLUtil;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.xml.sax.InputSource;\n\n/**\n * @author normenhansen\n */\npublic class AssetPackLibrary implements Project {\n\n FileObject library;\n\n Element[] assetElements = new Element[0];\n\n InstanceContent content = new InstanceContent();\n\n Lookup lookup = new AbstractLookup(content);\n\n private ProjectAssetManager projectAssetManager;\n\n private List categories = new LinkedList();\n\n public AssetPackLibrary() {\n content.add(this);\n }\n\n private void initLibrary() {\n String path = NbPreferences.forModule(Installer.class).get(\"assetpack_path\", null);\n library = FileUtil.toFileObject(new File(path));\n }\n\n public Node getRootNode() {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this);\n return multi;\n }\n\n public Node getRootNode(String[] categories, String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, categories, tags);\n return multi;\n }\n\n public Node getRootNode(String category) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, new String[] { category }, null);\n return multi;\n }\n\n public Node getRootNode(String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, null, tags);\n return multi;\n }\n\n private void parseLibrary() {\n initLibrary();\n categories.clear();\n ", "post_mask_code": "\n this.assetElements = new Element[assetElements.size()];\n for (int i = 0; i < assetElements.size(); i++) {\n Element element = assetElements.get(i);\n this.assetElements[i] = element;\n Element child = XmlHelper.findChildElement(element, \"asset\");\n while (child != null) {\n String cats = child.getAttribute(\"categories\");\n String[] categs = cats.split(\",\");\n for (int j = 0; j < categs.length; j++) {\n String string = categs[j];\n string = string.trim();\n if (!categories.contains(string)) {\n categories.add(string);\n }\n }\n child = XmlHelper.findNextElement(child, \"asset\");\n }\n }\n }\n\n public FileObject getProjectDirectory() {\n return library;\n }\n\n public Lookup getLookup() {\n return lookup;\n }\n\n /**\n * @return the projectAssetManager\n */\n public ProjectAssetManager getProjectAssetManager() {\n return projectAssetManager;\n }\n\n /**\n * @return the categories\n */\n public List getCategories() {\n return categories;\n }\n}\n"} {"task_id": "Java_1945", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/jMonkeyEngine/sdk/jme3-assetpack-support/src/com/jme3/gde/assetpack/browser/AssetPackLibrary.java", "mask_start_position": 4097, "mask_end_position": 4921, "canonical_solution": "this.assetElements = new Element[assetElements.size()];\n for (int i = 0; i < assetElements.size(); i++) {\n Element element = assetElements.get(i);\n this.assetElements[i] = element;\n Element child = XmlHelper.findChildElement(element, \"asset\");\n while (child != null) {\n String cats = child.getAttribute(\"categories\");\n String[] categs = cats.split(\",\");\n for (int j = 0; j < categs.length; j++) {\n String string = categs[j];\n string = string.trim();\n if (!categories.contains(string)) {\n categories.add(string);\n }\n }\n child = XmlHelper.findNextElement(child, \"asset\");\n }\n }\n }", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage com.jme3.gde.assetpack.browser;\n\nimport com.jme3.gde.assetpack.browser.nodes.AssetPackBrowserFolder;\nimport com.jme3.gde.assetpack.Installer;\nimport com.jme3.gde.assetpack.XmlHelper;\nimport com.jme3.gde.core.assets.ProjectAssetManager;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport org.netbeans.api.project.Project;\nimport org.openide.filesystems.FileObject;\nimport org.openide.filesystems.FileUtil;\nimport org.openide.nodes.Node;\nimport org.openide.util.Exceptions;\nimport org.openide.util.Lookup;\nimport org.openide.util.NbPreferences;\nimport org.openide.util.lookup.AbstractLookup;\nimport org.openide.util.lookup.InstanceContent;\nimport org.openide.xml.XMLUtil;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.xml.sax.InputSource;\n\n/**\n * @author normenhansen\n */\npublic class AssetPackLibrary implements Project {\n\n FileObject library;\n\n Element[] assetElements = new Element[0];\n\n InstanceContent content = new InstanceContent();\n\n Lookup lookup = new AbstractLookup(content);\n\n private ProjectAssetManager projectAssetManager;\n\n private List categories = new LinkedList();\n\n public AssetPackLibrary() {\n content.add(this);\n }\n\n private void initLibrary() {\n String path = NbPreferences.forModule(Installer.class).get(\"assetpack_path\", null);\n library = FileUtil.toFileObject(new File(path));\n }\n\n public Node getRootNode() {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this);\n return multi;\n }\n\n public Node getRootNode(String[] categories, String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, categories, tags);\n return multi;\n }\n\n public Node getRootNode(String category) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, new String[] { category }, null);\n return multi;\n }\n\n public Node getRootNode(String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, null, tags);\n return multi;\n }\n\n private void parseLibrary() {\n initLibrary();\n categories.clear();\n FileObject[] object = library.getChildren();\n List assetElements = new LinkedList();\n for (int i = 0; i < object.length; i++) {\n FileObject fileObject = object[i];\n if (fileObject.isFolder()) {\n FileObject config = fileObject.getFileObject(\"assetpack.xml\");\n if (config != null) {\n InputStream in;\n try {\n in = config.getInputStream();\n Document doc = XMLUtil.parse(new InputSource(in), false, false, null, null);\n in.close();\n Element assets = XmlHelper.findChildElement(doc.getDocumentElement(), \"assets\");\n if (assets != null) {\n assetElements.add(assets);\n }\n } catch (Exception ex) {\n Exceptions.printStackTrace(ex);\n }\n if (projectAssetManager == null) {\n projectAssetManager = new ProjectAssetManager(this, fileObject.getNameExt() + \"/assets/\");\n content.add(projectAssetManager);\n } else {\n projectAssetManager.addFolderLocator(fileObject.getNameExt() + \"/assets/\");\n }\n } else {\n Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, \"Error in assetpack, could not load assetpack.xml!\");\n }\n }\n }\n ", "post_mask_code": "\n\n public FileObject getProjectDirectory() {\n return library;\n }\n\n public Lookup getLookup() {\n return lookup;\n }\n\n /**\n * @return the projectAssetManager\n */\n public ProjectAssetManager getProjectAssetManager() {\n return projectAssetManager;\n }\n\n /**\n * @return the categories\n */\n public List getCategories() {\n return categories;\n }\n}\n"} {"task_id": "Java_1946", "language": "Java", "task_type": "single_line", "source_file": "java/github/jMonkeyEngine/sdk/jme3-assetpack-support/src/com/jme3/gde/assetpack/browser/AssetPackLibrary.java", "mask_start_position": 4100, "mask_end_position": 4152, "canonical_solution": "s.assetElements = new Element[assetElements.size()];", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage com.jme3.gde.assetpack.browser;\n\nimport com.jme3.gde.assetpack.browser.nodes.AssetPackBrowserFolder;\nimport com.jme3.gde.assetpack.Installer;\nimport com.jme3.gde.assetpack.XmlHelper;\nimport com.jme3.gde.core.assets.ProjectAssetManager;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport org.netbeans.api.project.Project;\nimport org.openide.filesystems.FileObject;\nimport org.openide.filesystems.FileUtil;\nimport org.openide.nodes.Node;\nimport org.openide.util.Exceptions;\nimport org.openide.util.Lookup;\nimport org.openide.util.NbPreferences;\nimport org.openide.util.lookup.AbstractLookup;\nimport org.openide.util.lookup.InstanceContent;\nimport org.openide.xml.XMLUtil;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.xml.sax.InputSource;\n\n/**\n * @author normenhansen\n */\npublic class AssetPackLibrary implements Project {\n\n FileObject library;\n\n Element[] assetElements = new Element[0];\n\n InstanceContent content = new InstanceContent();\n\n Lookup lookup = new AbstractLookup(content);\n\n private ProjectAssetManager projectAssetManager;\n\n private List categories = new LinkedList();\n\n public AssetPackLibrary() {\n content.add(this);\n }\n\n private void initLibrary() {\n String path = NbPreferences.forModule(Installer.class).get(\"assetpack_path\", null);\n library = FileUtil.toFileObject(new File(path));\n }\n\n public Node getRootNode() {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this);\n return multi;\n }\n\n public Node getRootNode(String[] categories, String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, categories, tags);\n return multi;\n }\n\n public Node getRootNode(String category) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, new String[] { category }, null);\n return multi;\n }\n\n public Node getRootNode(String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, null, tags);\n return multi;\n }\n\n private void parseLibrary() {\n initLibrary();\n categories.clear();\n FileObject[] object = library.getChildren();\n List assetElements = new LinkedList();\n for (int i = 0; i < object.length; i++) {\n FileObject fileObject = object[i];\n if (fileObject.isFolder()) {\n FileObject config = fileObject.getFileObject(\"assetpack.xml\");\n if (config != null) {\n InputStream in;\n try {\n in = config.getInputStream();\n Document doc = XMLUtil.parse(new InputSource(in), false, false, null, null);\n in.close();\n Element assets = XmlHelper.findChildElement(doc.getDocumentElement(), \"assets\");\n if (assets != null) {\n assetElements.add(assets);\n }\n } catch (Exception ex) {\n Exceptions.printStackTrace(ex);\n }\n if (projectAssetManager == null) {\n projectAssetManager = new ProjectAssetManager(this, fileObject.getNameExt() + \"/assets/\");\n content.add(projectAssetManager);\n } else {\n projectAssetManager.addFolderLocator(fileObject.getNameExt() + \"/assets/\");\n }\n } else {\n Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, \"Error in assetpack, could not load assetpack.xml!\");\n }\n }\n }\n thi", "post_mask_code": "\n for (int i = 0; i < assetElements.size(); i++) {\n Element element = assetElements.get(i);\n this.assetElements[i] = element;\n Element child = XmlHelper.findChildElement(element, \"asset\");\n while (child != null) {\n String cats = child.getAttribute(\"categories\");\n String[] categs = cats.split(\",\");\n for (int j = 0; j < categs.length; j++) {\n String string = categs[j];\n string = string.trim();\n if (!categories.contains(string)) {\n categories.add(string);\n }\n }\n child = XmlHelper.findNextElement(child, \"asset\");\n }\n }\n }\n\n public FileObject getProjectDirectory() {\n return library;\n }\n\n public Lookup getLookup() {\n return lookup;\n }\n\n /**\n * @return the projectAssetManager\n */\n public ProjectAssetManager getProjectAssetManager() {\n return projectAssetManager;\n }\n\n /**\n * @return the categories\n */\n public List getCategories() {\n return categories;\n }\n}\n"} {"task_id": "Java_1947", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/jMonkeyEngine/sdk/jme3-assetpack-support/src/com/jme3/gde/assetpack/browser/AssetPackLibrary.java", "mask_start_position": 5268, "mask_end_position": 5338, "canonical_solution": "public List getCategories() {\n return categories;\n }", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage com.jme3.gde.assetpack.browser;\n\nimport com.jme3.gde.assetpack.browser.nodes.AssetPackBrowserFolder;\nimport com.jme3.gde.assetpack.Installer;\nimport com.jme3.gde.assetpack.XmlHelper;\nimport com.jme3.gde.core.assets.ProjectAssetManager;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport org.netbeans.api.project.Project;\nimport org.openide.filesystems.FileObject;\nimport org.openide.filesystems.FileUtil;\nimport org.openide.nodes.Node;\nimport org.openide.util.Exceptions;\nimport org.openide.util.Lookup;\nimport org.openide.util.NbPreferences;\nimport org.openide.util.lookup.AbstractLookup;\nimport org.openide.util.lookup.InstanceContent;\nimport org.openide.xml.XMLUtil;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.xml.sax.InputSource;\n\n/**\n * @author normenhansen\n */\npublic class AssetPackLibrary implements Project {\n\n FileObject library;\n\n Element[] assetElements = new Element[0];\n\n InstanceContent content = new InstanceContent();\n\n Lookup lookup = new AbstractLookup(content);\n\n private ProjectAssetManager projectAssetManager;\n\n private List categories = new LinkedList();\n\n public AssetPackLibrary() {\n content.add(this);\n }\n\n private void initLibrary() {\n String path = NbPreferences.forModule(Installer.class).get(\"assetpack_path\", null);\n library = FileUtil.toFileObject(new File(path));\n }\n\n public Node getRootNode() {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this);\n return multi;\n }\n\n public Node getRootNode(String[] categories, String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, categories, tags);\n return multi;\n }\n\n public Node getRootNode(String category) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, new String[] { category }, null);\n return multi;\n }\n\n public Node getRootNode(String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, null, tags);\n return multi;\n }\n\n private void parseLibrary() {\n initLibrary();\n categories.clear();\n FileObject[] object = library.getChildren();\n List assetElements = new LinkedList();\n for (int i = 0; i < object.length; i++) {\n FileObject fileObject = object[i];\n if (fileObject.isFolder()) {\n FileObject config = fileObject.getFileObject(\"assetpack.xml\");\n if (config != null) {\n InputStream in;\n try {\n in = config.getInputStream();\n Document doc = XMLUtil.parse(new InputSource(in), false, false, null, null);\n in.close();\n Element assets = XmlHelper.findChildElement(doc.getDocumentElement(), \"assets\");\n if (assets != null) {\n assetElements.add(assets);\n }\n } catch (Exception ex) {\n Exceptions.printStackTrace(ex);\n }\n if (projectAssetManager == null) {\n projectAssetManager = new ProjectAssetManager(this, fileObject.getNameExt() + \"/assets/\");\n content.add(projectAssetManager);\n } else {\n projectAssetManager.addFolderLocator(fileObject.getNameExt() + \"/assets/\");\n }\n } else {\n Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, \"Error in assetpack, could not load assetpack.xml!\");\n }\n }\n }\n this.assetElements = new Element[assetElements.size()];\n for (int i = 0; i < assetElements.size(); i++) {\n Element element = assetElements.get(i);\n this.assetElements[i] = element;\n Element child = XmlHelper.findChildElement(element, \"asset\");\n while (child != null) {\n String cats = child.getAttribute(\"categories\");\n String[] categs = cats.split(\",\");\n for (int j = 0; j < categs.length; j++) {\n String string = categs[j];\n string = string.trim();\n if (!categories.contains(string)) {\n categories.add(string);\n }\n }\n child = XmlHelper.findNextElement(child, \"asset\");\n }\n }\n }\n\n public FileObject getProjectDirectory() {\n return library;\n }\n\n public Lookup getLookup() {\n return lookup;\n }\n\n /**\n * @return the projectAssetManager\n */\n public ProjectAssetManager getProjectAssetManager() {\n return projectAssetManager;\n }\n\n /**\n * @return the categories\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1948", "language": "Java", "task_type": "if_statement", "source_file": "java/github/jMonkeyEngine/sdk/jme3-assetpack-support/src/com/jme3/gde/assetpack/browser/AssetPackLibrary.java", "mask_start_position": 3281, "mask_end_position": 3383, "canonical_solution": "if (assets != null) {\n assetElements.add(assets);\n }", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage com.jme3.gde.assetpack.browser;\n\nimport com.jme3.gde.assetpack.browser.nodes.AssetPackBrowserFolder;\nimport com.jme3.gde.assetpack.Installer;\nimport com.jme3.gde.assetpack.XmlHelper;\nimport com.jme3.gde.core.assets.ProjectAssetManager;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport org.netbeans.api.project.Project;\nimport org.openide.filesystems.FileObject;\nimport org.openide.filesystems.FileUtil;\nimport org.openide.nodes.Node;\nimport org.openide.util.Exceptions;\nimport org.openide.util.Lookup;\nimport org.openide.util.NbPreferences;\nimport org.openide.util.lookup.AbstractLookup;\nimport org.openide.util.lookup.InstanceContent;\nimport org.openide.xml.XMLUtil;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.xml.sax.InputSource;\n\n/**\n * @author normenhansen\n */\npublic class AssetPackLibrary implements Project {\n\n FileObject library;\n\n Element[] assetElements = new Element[0];\n\n InstanceContent content = new InstanceContent();\n\n Lookup lookup = new AbstractLookup(content);\n\n private ProjectAssetManager projectAssetManager;\n\n private List categories = new LinkedList();\n\n public AssetPackLibrary() {\n content.add(this);\n }\n\n private void initLibrary() {\n String path = NbPreferences.forModule(Installer.class).get(\"assetpack_path\", null);\n library = FileUtil.toFileObject(new File(path));\n }\n\n public Node getRootNode() {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this);\n return multi;\n }\n\n public Node getRootNode(String[] categories, String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, categories, tags);\n return multi;\n }\n\n public Node getRootNode(String category) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, new String[] { category }, null);\n return multi;\n }\n\n public Node getRootNode(String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, null, tags);\n return multi;\n }\n\n private void parseLibrary() {\n initLibrary();\n categories.clear();\n FileObject[] object = library.getChildren();\n List assetElements = new LinkedList();\n for (int i = 0; i < object.length; i++) {\n FileObject fileObject = object[i];\n if (fileObject.isFolder()) {\n FileObject config = fileObject.getFileObject(\"assetpack.xml\");\n if (config != null) {\n InputStream in;\n try {\n in = config.getInputStream();\n Document doc = XMLUtil.parse(new InputSource(in), false, false, null, null);\n in.close();\n Element assets = XmlHelper.findChildElement(doc.getDocumentElement(), \"assets\");\n ", "post_mask_code": "\n } catch (Exception ex) {\n Exceptions.printStackTrace(ex);\n }\n if (projectAssetManager == null) {\n projectAssetManager = new ProjectAssetManager(this, fileObject.getNameExt() + \"/assets/\");\n content.add(projectAssetManager);\n } else {\n projectAssetManager.addFolderLocator(fileObject.getNameExt() + \"/assets/\");\n }\n } else {\n Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, \"Error in assetpack, could not load assetpack.xml!\");\n }\n }\n }\n this.assetElements = new Element[assetElements.size()];\n for (int i = 0; i < assetElements.size(); i++) {\n Element element = assetElements.get(i);\n this.assetElements[i] = element;\n Element child = XmlHelper.findChildElement(element, \"asset\");\n while (child != null) {\n String cats = child.getAttribute(\"categories\");\n String[] categs = cats.split(\",\");\n for (int j = 0; j < categs.length; j++) {\n String string = categs[j];\n string = string.trim();\n if (!categories.contains(string)) {\n categories.add(string);\n }\n }\n child = XmlHelper.findNextElement(child, \"asset\");\n }\n }\n }\n\n public FileObject getProjectDirectory() {\n return library;\n }\n\n public Lookup getLookup() {\n return lookup;\n }\n\n /**\n * @return the projectAssetManager\n */\n public ProjectAssetManager getProjectAssetManager() {\n return projectAssetManager;\n }\n\n /**\n * @return the categories\n */\n public List getCategories() {\n return categories;\n }\n}\n"} {"task_id": "Java_1949", "language": "Java", "task_type": "for_statement", "source_file": "java/github/jMonkeyEngine/sdk/jme3-assetpack-support/src/com/jme3/gde/assetpack/browser/AssetPackLibrary.java", "mask_start_position": 4548, "mask_end_position": 4824, "canonical_solution": "for (int j = 0; j < categs.length; j++) {\n String string = categs[j];\n string = string.trim();\n if (!categories.contains(string)) {\n categories.add(string);\n }\n }", "pre_mask_code": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage com.jme3.gde.assetpack.browser;\n\nimport com.jme3.gde.assetpack.browser.nodes.AssetPackBrowserFolder;\nimport com.jme3.gde.assetpack.Installer;\nimport com.jme3.gde.assetpack.XmlHelper;\nimport com.jme3.gde.core.assets.ProjectAssetManager;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport org.netbeans.api.project.Project;\nimport org.openide.filesystems.FileObject;\nimport org.openide.filesystems.FileUtil;\nimport org.openide.nodes.Node;\nimport org.openide.util.Exceptions;\nimport org.openide.util.Lookup;\nimport org.openide.util.NbPreferences;\nimport org.openide.util.lookup.AbstractLookup;\nimport org.openide.util.lookup.InstanceContent;\nimport org.openide.xml.XMLUtil;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.xml.sax.InputSource;\n\n/**\n * @author normenhansen\n */\npublic class AssetPackLibrary implements Project {\n\n FileObject library;\n\n Element[] assetElements = new Element[0];\n\n InstanceContent content = new InstanceContent();\n\n Lookup lookup = new AbstractLookup(content);\n\n private ProjectAssetManager projectAssetManager;\n\n private List categories = new LinkedList();\n\n public AssetPackLibrary() {\n content.add(this);\n }\n\n private void initLibrary() {\n String path = NbPreferences.forModule(Installer.class).get(\"assetpack_path\", null);\n library = FileUtil.toFileObject(new File(path));\n }\n\n public Node getRootNode() {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this);\n return multi;\n }\n\n public Node getRootNode(String[] categories, String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, categories, tags);\n return multi;\n }\n\n public Node getRootNode(String category) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, new String[] { category }, null);\n return multi;\n }\n\n public Node getRootNode(String[] tags) {\n parseLibrary();\n AssetPackBrowserFolder multi = new AssetPackBrowserFolder(assetElements, this, null, tags);\n return multi;\n }\n\n private void parseLibrary() {\n initLibrary();\n categories.clear();\n FileObject[] object = library.getChildren();\n List assetElements = new LinkedList();\n for (int i = 0; i < object.length; i++) {\n FileObject fileObject = object[i];\n if (fileObject.isFolder()) {\n FileObject config = fileObject.getFileObject(\"assetpack.xml\");\n if (config != null) {\n InputStream in;\n try {\n in = config.getInputStream();\n Document doc = XMLUtil.parse(new InputSource(in), false, false, null, null);\n in.close();\n Element assets = XmlHelper.findChildElement(doc.getDocumentElement(), \"assets\");\n if (assets != null) {\n assetElements.add(assets);\n }\n } catch (Exception ex) {\n Exceptions.printStackTrace(ex);\n }\n if (projectAssetManager == null) {\n projectAssetManager = new ProjectAssetManager(this, fileObject.getNameExt() + \"/assets/\");\n content.add(projectAssetManager);\n } else {\n projectAssetManager.addFolderLocator(fileObject.getNameExt() + \"/assets/\");\n }\n } else {\n Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, \"Error in assetpack, could not load assetpack.xml!\");\n }\n }\n }\n this.assetElements = new Element[assetElements.size()];\n for (int i = 0; i < assetElements.size(); i++) {\n Element element = assetElements.get(i);\n this.assetElements[i] = element;\n Element child = XmlHelper.findChildElement(element, \"asset\");\n while (child != null) {\n String cats = child.getAttribute(\"categories\");\n String[] categs = cats.split(\",\");\n ", "post_mask_code": "\n child = XmlHelper.findNextElement(child, \"asset\");\n }\n }\n }\n\n public FileObject getProjectDirectory() {\n return library;\n }\n\n public Lookup getLookup() {\n return lookup;\n }\n\n /**\n * @return the projectAssetManager\n */\n public ProjectAssetManager getProjectAssetManager() {\n return projectAssetManager;\n }\n\n /**\n * @return the categories\n */\n public List getCategories() {\n return categories;\n }\n}\n"} {"task_id": "Java_1950", "language": "Java", "task_type": "method_signature", "source_file": "java/github/owlcollab/owltools/OWLTools-Core/src/main/java/owltools/graph/OWLGraphUtil.java", "mask_start_position": 655, "mask_end_position": 764, "canonical_solution": "public static Set findLeastCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) ", "pre_mask_code": "package owltools.graph;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.semanticweb.owlapi.model.OWLObject;\nimport org.semanticweb.owlapi.model.OWLPropertyExpression;\n\n/**\n * general static methods for additional graph operations\n */\npublic class OWLGraphUtil {\n\n /**\n * @param g\n * @param x\n * @param y\n * @return set of edges\n */\n public static Set findCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set xs = g.getOutgoingEdgesClosure(x);\n Set ys = g.getOutgoingEdgesClosure(y);\n xs.retainAll(ys);\n return xs;\n }\n\n ", "post_mask_code": "{\n Set cses = findCommonSubsumersAsEdges(g, x, y);\n Set lcses = new HashSet();\n lcses.addAll(cses);\n for (OWLGraphEdge cse : cses) {\n Set zs = g.getAncestors(cse.getSource());\n for (OWLObject z : zs) {\n for (OWLGraphEdge lcse : lcses) {\n if (lcse.getSource().equals(z))\n lcses.remove(lcse);\n }\n }\n }\n return lcses;\n }\n\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findCommonAncestors(g, x, y, null);\n }\n\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findLeastCommonAncestors(g, x, y, null);\n }\n\n /**\n * Find common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n *\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set xs = g.getAncestors(x, overProps);\n Set ys = g.getAncestors(y, overProps);\n xs.retainAll(ys);\n return xs;\n }\n\n /**\n * Find lest common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set cas = findCommonAncestors(g, x, y, overProps);\n Set lcas = new HashSet();\n lcas.addAll(cas);\n for (OWLObject z : cas) {\n lcas.removeAll(g.getAncestors(z, overProps));\n }\n return lcas;\n }\n}\n"} {"task_id": "Java_1951", "language": "Java", "task_type": "method_body", "source_file": "java/github/owlcollab/owltools/OWLTools-Core/src/main/java/owltools/graph/OWLGraphUtil.java", "mask_start_position": 1978, "mask_end_position": 2146, "canonical_solution": "{\n Set xs = g.getAncestors(x, overProps);\n Set ys = g.getAncestors(y, overProps);\n xs.retainAll(ys);\n return xs;\n }", "pre_mask_code": "package owltools.graph;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.semanticweb.owlapi.model.OWLObject;\nimport org.semanticweb.owlapi.model.OWLPropertyExpression;\n\n/**\n * general static methods for additional graph operations\n */\npublic class OWLGraphUtil {\n\n /**\n * @param g\n * @param x\n * @param y\n * @return set of edges\n */\n public static Set findCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set xs = g.getOutgoingEdgesClosure(x);\n Set ys = g.getOutgoingEdgesClosure(y);\n xs.retainAll(ys);\n return xs;\n }\n\n public static Set findLeastCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set cses = findCommonSubsumersAsEdges(g, x, y);\n Set lcses = new HashSet();\n lcses.addAll(cses);\n for (OWLGraphEdge cse : cses) {\n Set zs = g.getAncestors(cse.getSource());\n for (OWLObject z : zs) {\n for (OWLGraphEdge lcse : lcses) {\n if (lcse.getSource().equals(z))\n lcses.remove(lcse);\n }\n }\n }\n return lcses;\n }\n\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findCommonAncestors(g, x, y, null);\n }\n\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findLeastCommonAncestors(g, x, y, null);\n }\n\n /**\n * Find common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n *\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) ", "post_mask_code": "\n\n /**\n * Find lest common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set cas = findCommonAncestors(g, x, y, overProps);\n Set lcas = new HashSet();\n lcas.addAll(cas);\n for (OWLObject z : cas) {\n lcas.removeAll(g.getAncestors(z, overProps));\n }\n return lcas;\n }\n}\n"} {"task_id": "Java_1952", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/owlcollab/owltools/OWLTools-Core/src/main/java/owltools/graph/OWLGraphUtil.java", "mask_start_position": 2518, "mask_end_position": 2644, "canonical_solution": "\n Set cas = findCommonAncestors(g, x, y, overProps);\n Set lcas = new HashSet();", "pre_mask_code": "package owltools.graph;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.semanticweb.owlapi.model.OWLObject;\nimport org.semanticweb.owlapi.model.OWLPropertyExpression;\n\n/**\n * general static methods for additional graph operations\n */\npublic class OWLGraphUtil {\n\n /**\n * @param g\n * @param x\n * @param y\n * @return set of edges\n */\n public static Set findCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set xs = g.getOutgoingEdgesClosure(x);\n Set ys = g.getOutgoingEdgesClosure(y);\n xs.retainAll(ys);\n return xs;\n }\n\n public static Set findLeastCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set cses = findCommonSubsumersAsEdges(g, x, y);\n Set lcses = new HashSet();\n lcses.addAll(cses);\n for (OWLGraphEdge cse : cses) {\n Set zs = g.getAncestors(cse.getSource());\n for (OWLObject z : zs) {\n for (OWLGraphEdge lcse : lcses) {\n if (lcse.getSource().equals(z))\n lcses.remove(lcse);\n }\n }\n }\n return lcses;\n }\n\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findCommonAncestors(g, x, y, null);\n }\n\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findLeastCommonAncestors(g, x, y, null);\n }\n\n /**\n * Find common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n *\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set xs = g.getAncestors(x, overProps);\n Set ys = g.getAncestors(y, overProps);\n xs.retainAll(ys);\n return xs;\n }\n\n /**\n * Find lest common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {", "post_mask_code": "\n lcas.addAll(cas);\n for (OWLObject z : cas) {\n lcas.removeAll(g.getAncestors(z, overProps));\n }\n return lcas;\n }\n}\n"} {"task_id": "Java_1953", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/owlcollab/owltools/OWLTools-Core/src/main/java/owltools/graph/OWLGraphUtil.java", "mask_start_position": 2653, "mask_end_position": 2772, "canonical_solution": "lcas.addAll(cas);\n for (OWLObject z : cas) {\n lcas.removeAll(g.getAncestors(z, overProps));\n }", "pre_mask_code": "package owltools.graph;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.semanticweb.owlapi.model.OWLObject;\nimport org.semanticweb.owlapi.model.OWLPropertyExpression;\n\n/**\n * general static methods for additional graph operations\n */\npublic class OWLGraphUtil {\n\n /**\n * @param g\n * @param x\n * @param y\n * @return set of edges\n */\n public static Set findCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set xs = g.getOutgoingEdgesClosure(x);\n Set ys = g.getOutgoingEdgesClosure(y);\n xs.retainAll(ys);\n return xs;\n }\n\n public static Set findLeastCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set cses = findCommonSubsumersAsEdges(g, x, y);\n Set lcses = new HashSet();\n lcses.addAll(cses);\n for (OWLGraphEdge cse : cses) {\n Set zs = g.getAncestors(cse.getSource());\n for (OWLObject z : zs) {\n for (OWLGraphEdge lcse : lcses) {\n if (lcse.getSource().equals(z))\n lcses.remove(lcse);\n }\n }\n }\n return lcses;\n }\n\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findCommonAncestors(g, x, y, null);\n }\n\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findLeastCommonAncestors(g, x, y, null);\n }\n\n /**\n * Find common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n *\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set xs = g.getAncestors(x, overProps);\n Set ys = g.getAncestors(y, overProps);\n xs.retainAll(ys);\n return xs;\n }\n\n /**\n * Find lest common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set cas = findCommonAncestors(g, x, y, overProps);\n Set lcas = new HashSet();\n ", "post_mask_code": "\n return lcas;\n }\n}\n"} {"task_id": "Java_1954", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/owlcollab/owltools/OWLTools-Core/src/main/java/owltools/graph/OWLGraphUtil.java", "mask_start_position": 2781, "mask_end_position": 2799, "canonical_solution": "return lcas;\n }", "pre_mask_code": "package owltools.graph;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.semanticweb.owlapi.model.OWLObject;\nimport org.semanticweb.owlapi.model.OWLPropertyExpression;\n\n/**\n * general static methods for additional graph operations\n */\npublic class OWLGraphUtil {\n\n /**\n * @param g\n * @param x\n * @param y\n * @return set of edges\n */\n public static Set findCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set xs = g.getOutgoingEdgesClosure(x);\n Set ys = g.getOutgoingEdgesClosure(y);\n xs.retainAll(ys);\n return xs;\n }\n\n public static Set findLeastCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set cses = findCommonSubsumersAsEdges(g, x, y);\n Set lcses = new HashSet();\n lcses.addAll(cses);\n for (OWLGraphEdge cse : cses) {\n Set zs = g.getAncestors(cse.getSource());\n for (OWLObject z : zs) {\n for (OWLGraphEdge lcse : lcses) {\n if (lcse.getSource().equals(z))\n lcses.remove(lcse);\n }\n }\n }\n return lcses;\n }\n\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findCommonAncestors(g, x, y, null);\n }\n\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findLeastCommonAncestors(g, x, y, null);\n }\n\n /**\n * Find common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n *\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set xs = g.getAncestors(x, overProps);\n Set ys = g.getAncestors(y, overProps);\n xs.retainAll(ys);\n return xs;\n }\n\n /**\n * Find lest common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set cas = findCommonAncestors(g, x, y, overProps);\n Set lcas = new HashSet();\n lcas.addAll(cas);\n for (OWLObject z : cas) {\n lcas.removeAll(g.getAncestors(z, overProps));\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1955", "language": "Java", "task_type": "single_line", "source_file": "java/github/owlcollab/owltools/OWLTools-Core/src/main/java/owltools/graph/OWLGraphUtil.java", "mask_start_position": 910, "mask_end_position": 926, "canonical_solution": "es.addAll(cses);", "pre_mask_code": "package owltools.graph;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.semanticweb.owlapi.model.OWLObject;\nimport org.semanticweb.owlapi.model.OWLPropertyExpression;\n\n/**\n * general static methods for additional graph operations\n */\npublic class OWLGraphUtil {\n\n /**\n * @param g\n * @param x\n * @param y\n * @return set of edges\n */\n public static Set findCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set xs = g.getOutgoingEdgesClosure(x);\n Set ys = g.getOutgoingEdgesClosure(y);\n xs.retainAll(ys);\n return xs;\n }\n\n public static Set findLeastCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set cses = findCommonSubsumersAsEdges(g, x, y);\n Set lcses = new HashSet();\n lcs", "post_mask_code": "\n for (OWLGraphEdge cse : cses) {\n Set zs = g.getAncestors(cse.getSource());\n for (OWLObject z : zs) {\n for (OWLGraphEdge lcse : lcses) {\n if (lcse.getSource().equals(z))\n lcses.remove(lcse);\n }\n }\n }\n return lcses;\n }\n\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findCommonAncestors(g, x, y, null);\n }\n\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findLeastCommonAncestors(g, x, y, null);\n }\n\n /**\n * Find common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n *\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set xs = g.getAncestors(x, overProps);\n Set ys = g.getAncestors(y, overProps);\n xs.retainAll(ys);\n return xs;\n }\n\n /**\n * Find lest common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set cas = findCommonAncestors(g, x, y, overProps);\n Set lcas = new HashSet();\n lcas.addAll(cas);\n for (OWLObject z : cas) {\n lcas.removeAll(g.getAncestors(z, overProps));\n }\n return lcas;\n }\n}\n"} {"task_id": "Java_1956", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/owlcollab/owltools/OWLTools-Core/src/main/java/owltools/graph/OWLGraphUtil.java", "mask_start_position": 2380, "mask_end_position": 2799, "canonical_solution": "public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set cas = findCommonAncestors(g, x, y, overProps);\n Set lcas = new HashSet();\n lcas.addAll(cas);\n for (OWLObject z : cas) {\n lcas.removeAll(g.getAncestors(z, overProps));\n }\n return lcas;\n }", "pre_mask_code": "package owltools.graph;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.semanticweb.owlapi.model.OWLObject;\nimport org.semanticweb.owlapi.model.OWLPropertyExpression;\n\n/**\n * general static methods for additional graph operations\n */\npublic class OWLGraphUtil {\n\n /**\n * @param g\n * @param x\n * @param y\n * @return set of edges\n */\n public static Set findCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set xs = g.getOutgoingEdgesClosure(x);\n Set ys = g.getOutgoingEdgesClosure(y);\n xs.retainAll(ys);\n return xs;\n }\n\n public static Set findLeastCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set cses = findCommonSubsumersAsEdges(g, x, y);\n Set lcses = new HashSet();\n lcses.addAll(cses);\n for (OWLGraphEdge cse : cses) {\n Set zs = g.getAncestors(cse.getSource());\n for (OWLObject z : zs) {\n for (OWLGraphEdge lcse : lcses) {\n if (lcse.getSource().equals(z))\n lcses.remove(lcse);\n }\n }\n }\n return lcses;\n }\n\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findCommonAncestors(g, x, y, null);\n }\n\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findLeastCommonAncestors(g, x, y, null);\n }\n\n /**\n * Find common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n *\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set xs = g.getAncestors(x, overProps);\n Set ys = g.getAncestors(y, overProps);\n xs.retainAll(ys);\n return xs;\n }\n\n /**\n * Find lest common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1957", "language": "Java", "task_type": "if_statement", "source_file": "java/github/owlcollab/owltools/OWLTools-Core/src/main/java/owltools/graph/OWLGraphUtil.java", "mask_start_position": 1139, "mask_end_position": 1214, "canonical_solution": "if (lcse.getSource().equals(z))\n lcses.remove(lcse);", "pre_mask_code": "package owltools.graph;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.semanticweb.owlapi.model.OWLObject;\nimport org.semanticweb.owlapi.model.OWLPropertyExpression;\n\n/**\n * general static methods for additional graph operations\n */\npublic class OWLGraphUtil {\n\n /**\n * @param g\n * @param x\n * @param y\n * @return set of edges\n */\n public static Set findCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set xs = g.getOutgoingEdgesClosure(x);\n Set ys = g.getOutgoingEdgesClosure(y);\n xs.retainAll(ys);\n return xs;\n }\n\n public static Set findLeastCommonSubsumersAsEdges(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n Set cses = findCommonSubsumersAsEdges(g, x, y);\n Set lcses = new HashSet();\n lcses.addAll(cses);\n for (OWLGraphEdge cse : cses) {\n Set zs = g.getAncestors(cse.getSource());\n for (OWLObject z : zs) {\n for (OWLGraphEdge lcse : lcses) {\n ", "post_mask_code": "\n }\n }\n }\n return lcses;\n }\n\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findCommonAncestors(g, x, y, null);\n }\n\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y) {\n return findLeastCommonAncestors(g, x, y, null);\n }\n\n /**\n * Find common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n *\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set xs = g.getAncestors(x, overProps);\n Set ys = g.getAncestors(y, overProps);\n xs.retainAll(ys);\n return xs;\n }\n\n /**\n * Find lest common ancestors to {@code x} and {@code y} that can be reached\n * over the specified set of relations.\n * @param g\n * @param x\n * @param y\n * @param overProps\n * @return\n */\n public static Set findLeastCommonAncestors(OWLGraphWrapper g, OWLObject x, OWLObject y, Set overProps) {\n Set cas = findCommonAncestors(g, x, y, overProps);\n Set lcas = new HashSet();\n lcas.addAll(cas);\n for (OWLObject z : cas) {\n lcas.removeAll(g.getAncestors(z, overProps));\n }\n return lcas;\n }\n}\n"} {"task_id": "Java_1958", "language": "Java", "task_type": "method_signature", "source_file": "java/github/nuxeo/nuxeo/nuxeo-core/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/utils/BlobsExtractor.java", "mask_start_position": 4230, "mask_end_position": 4290, "canonical_solution": "public List getBlobsProperties(DocumentModel doc) ", "pre_mask_code": "package org.nuxeo.ecm.core.utils;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport org.nuxeo.ecm.core.api.Blob;\nimport org.nuxeo.ecm.core.api.DocumentModel;\nimport org.nuxeo.ecm.core.api.model.Property;\nimport org.nuxeo.ecm.core.schema.DocumentType;\nimport org.nuxeo.ecm.core.schema.SchemaManager;\nimport org.nuxeo.ecm.core.schema.TypeConstants;\nimport org.nuxeo.ecm.core.schema.types.ComplexType;\nimport org.nuxeo.ecm.core.schema.types.Field;\nimport org.nuxeo.ecm.core.schema.types.ListType;\nimport org.nuxeo.ecm.core.schema.types.Schema;\nimport org.nuxeo.ecm.core.schema.types.Type;\nimport org.nuxeo.runtime.api.Framework;\n\n/**\n * Extractor for all the blobs of a document.\n */\npublic class BlobsExtractor {\n\n protected final Map> docBlobPaths = new ConcurrentHashMap<>();\n\n private Set includedPaths;\n\n private Set excludedPaths;\n\n private boolean allBlobs;\n\n private boolean isDefaultConfiguration = true;\n\n /**\n * Sets extractor properties, controlling what properties or values are returned by {@link #getBlobsProperties} or\n * {@link #getBlobs}.\n *

\n * The properties have to be defined without prefix if there is no prefix in the schema definition. For blob\n * properties, the path must include the {@code /data} part.\n */\n public void setExtractorProperties(Set includedPaths, Set excludedPaths, boolean allBlobs) {\n this.includedPaths = normalizePaths(includedPaths);\n this.excludedPaths = normalizePaths(excludedPaths);\n this.allBlobs = allBlobs;\n isDefaultConfiguration = includedPaths == null && excludedPaths == null && allBlobs;\n }\n\n protected boolean isInterestingPath(String path) {\n if (isDefaultConfiguration) {\n return true;\n } else if (excludedPaths != null && excludedPaths.contains(path)) {\n return false;\n } else if (includedPaths != null && includedPaths.contains(path)) {\n return true;\n } else if (allBlobs) {\n return true;\n }\n return false;\n }\n\n /**\n * Removes the \"/data\" suffix used by FulltextConfiguration.\n *

\n * Adds missing schema name as prefix if no prefix (\"content\" -> \"file:content\").\n */\n protected Set normalizePaths(Set paths) {\n if (paths == null) {\n return null;\n }\n SchemaManager schemaManager = Framework.getService(SchemaManager.class);\n Set normPaths = new HashSet<>();\n for (String path : paths) {\n if (path.endsWith(\"/data\")) {\n path = path.substring(0, path.length() - \"/data\".length());\n }\n // add schema if no schema prefix\n if (schemaManager.getField(path) == null && !path.contains(\":\")) {\n // check without prefix\n // TODO precompute this in SchemaManagerImpl\n int slash = path.indexOf('/');\n String first = slash == -1 ? path : path.substring(0, slash);\n for (Schema schema : schemaManager.getSchemas()) {\n if (!schema.getNamespace().hasPrefix()) {\n // schema without prefix, try it\n if (schema.getField(first) != null) {\n path = schema.getName() + \":\" + path;\n break;\n }\n }\n }\n }\n normPaths.add(path);\n }\n return normPaths;\n }\n\n /**\n * Gets the blobs of the document.\n *\n * @param doc the document\n * @return the list of blobs\n */\n public List getBlobs(DocumentModel doc) {\n List blobs = new ArrayList<>();\n for (Property property : getBlobsProperties(doc)) {\n blobs.add((Blob) property.getValue());\n }\n return blobs;\n }\n\n /**\n * Gets the blob properties of the document.\n *\n * @param doc the document\n * @return the list of blob properties\n */\n ", "post_mask_code": "{\n List properties = new ArrayList<>();\n for (String path : getBlobPaths(doc.getDocumentType())) {\n if (!isInterestingPath(path)) {\n continue;\n }\n // split on:\n List split = Arrays.asList(path.split(\"/[*]/|/\"));\n if (split.isEmpty()) {\n throw new IllegalStateException(\"Path detected not well-formed: \" + path);\n }\n Property property = doc.getProperty(split.get(0));\n List subPath = split.subList(1, split.size());\n findBlobsProperties(property, subPath, properties);\n }\n return properties;\n }\n\n /**\n * Gets the blob paths of the document type. Extractor properties are ignored.\n *\n * @param documentType the document type\n * @return the list of blob paths\n *\n * @since 8.3\n */\n public List getBlobPaths(DocumentType documentType) {\n String docType = documentType.getName();\n List paths = docBlobPaths.get(docType);\n if (paths == null) {\n paths = new ArrayList<>();\n for (Schema schema : documentType.getSchemas()) {\n findBlobPaths(schema, null, schema, paths);\n }\n docBlobPaths.put(docType, paths);\n }\n return paths;\n }\n\n protected void findBlobsProperties(Property property, List split, List properties) {\n if (split.isEmpty()) {\n if (property.getValue() != null) {\n properties.add(property);\n }\n } else {\n String name = split.get(0);\n List subPath = split.subList(1, split.size());\n if (property.isList()) {\n for (Property childProperty : property.getChildren()) {\n Property childSubProp = childProperty.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n } else {\n // complex type\n Property childSubProp = property.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n }\n }\n\n protected void findBlobPaths(ComplexType complexType, String path, Schema schema, List paths) {\n for (Field field : complexType.getFields()) {\n String fieldPath = field.getName().getPrefixedName();\n if (path == null) {\n // add schema name as prefix if the schema doesn't have a prefix\n if (!schema.getNamespace().hasPrefix()) {\n fieldPath = schema.getName() + \":\" + fieldPath;\n }\n } else {\n fieldPath = path + \"/\" + fieldPath;\n }\n Type type = field.getType();\n if (type.isSimpleType()) {\n // not binary text\n continue;\n } else if (type.isListType()) {\n Type fieldType = ((ListType) type).getFieldType();\n if (fieldType.isComplexType()) {\n findBlobPaths((ComplexType) fieldType, fieldPath + \"/*\", schema, paths);\n } else {\n // not binary text\n continue;\n }\n } else {\n // complex type\n ComplexType ctype = (ComplexType) type;\n if (TypeConstants.isContentType(type)) {\n // note this path\n paths.add(fieldPath);\n } else {\n findBlobPaths(ctype, fieldPath, schema, paths);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_1959", "language": "Java", "task_type": "method_body", "source_file": "java/github/nuxeo/nuxeo/nuxeo-core/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/utils/BlobsExtractor.java", "mask_start_position": 1576, "mask_end_position": 1830, "canonical_solution": "{\n this.includedPaths = normalizePaths(includedPaths);\n this.excludedPaths = normalizePaths(excludedPaths);\n this.allBlobs = allBlobs;\n isDefaultConfiguration = includedPaths == null && excludedPaths == null && allBlobs;\n }", "pre_mask_code": "package org.nuxeo.ecm.core.utils;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport org.nuxeo.ecm.core.api.Blob;\nimport org.nuxeo.ecm.core.api.DocumentModel;\nimport org.nuxeo.ecm.core.api.model.Property;\nimport org.nuxeo.ecm.core.schema.DocumentType;\nimport org.nuxeo.ecm.core.schema.SchemaManager;\nimport org.nuxeo.ecm.core.schema.TypeConstants;\nimport org.nuxeo.ecm.core.schema.types.ComplexType;\nimport org.nuxeo.ecm.core.schema.types.Field;\nimport org.nuxeo.ecm.core.schema.types.ListType;\nimport org.nuxeo.ecm.core.schema.types.Schema;\nimport org.nuxeo.ecm.core.schema.types.Type;\nimport org.nuxeo.runtime.api.Framework;\n\n/**\n * Extractor for all the blobs of a document.\n */\npublic class BlobsExtractor {\n\n protected final Map> docBlobPaths = new ConcurrentHashMap<>();\n\n private Set includedPaths;\n\n private Set excludedPaths;\n\n private boolean allBlobs;\n\n private boolean isDefaultConfiguration = true;\n\n /**\n * Sets extractor properties, controlling what properties or values are returned by {@link #getBlobsProperties} or\n * {@link #getBlobs}.\n *

\n * The properties have to be defined without prefix if there is no prefix in the schema definition. For blob\n * properties, the path must include the {@code /data} part.\n */\n public void setExtractorProperties(Set includedPaths, Set excludedPaths, boolean allBlobs) ", "post_mask_code": "\n\n protected boolean isInterestingPath(String path) {\n if (isDefaultConfiguration) {\n return true;\n } else if (excludedPaths != null && excludedPaths.contains(path)) {\n return false;\n } else if (includedPaths != null && includedPaths.contains(path)) {\n return true;\n } else if (allBlobs) {\n return true;\n }\n return false;\n }\n\n /**\n * Removes the \"/data\" suffix used by FulltextConfiguration.\n *

\n * Adds missing schema name as prefix if no prefix (\"content\" -> \"file:content\").\n */\n protected Set normalizePaths(Set paths) {\n if (paths == null) {\n return null;\n }\n SchemaManager schemaManager = Framework.getService(SchemaManager.class);\n Set normPaths = new HashSet<>();\n for (String path : paths) {\n if (path.endsWith(\"/data\")) {\n path = path.substring(0, path.length() - \"/data\".length());\n }\n // add schema if no schema prefix\n if (schemaManager.getField(path) == null && !path.contains(\":\")) {\n // check without prefix\n // TODO precompute this in SchemaManagerImpl\n int slash = path.indexOf('/');\n String first = slash == -1 ? path : path.substring(0, slash);\n for (Schema schema : schemaManager.getSchemas()) {\n if (!schema.getNamespace().hasPrefix()) {\n // schema without prefix, try it\n if (schema.getField(first) != null) {\n path = schema.getName() + \":\" + path;\n break;\n }\n }\n }\n }\n normPaths.add(path);\n }\n return normPaths;\n }\n\n /**\n * Gets the blobs of the document.\n *\n * @param doc the document\n * @return the list of blobs\n */\n public List getBlobs(DocumentModel doc) {\n List blobs = new ArrayList<>();\n for (Property property : getBlobsProperties(doc)) {\n blobs.add((Blob) property.getValue());\n }\n return blobs;\n }\n\n /**\n * Gets the blob properties of the document.\n *\n * @param doc the document\n * @return the list of blob properties\n */\n public List getBlobsProperties(DocumentModel doc) {\n List properties = new ArrayList<>();\n for (String path : getBlobPaths(doc.getDocumentType())) {\n if (!isInterestingPath(path)) {\n continue;\n }\n // split on:\n List split = Arrays.asList(path.split(\"/[*]/|/\"));\n if (split.isEmpty()) {\n throw new IllegalStateException(\"Path detected not well-formed: \" + path);\n }\n Property property = doc.getProperty(split.get(0));\n List subPath = split.subList(1, split.size());\n findBlobsProperties(property, subPath, properties);\n }\n return properties;\n }\n\n /**\n * Gets the blob paths of the document type. Extractor properties are ignored.\n *\n * @param documentType the document type\n * @return the list of blob paths\n *\n * @since 8.3\n */\n public List getBlobPaths(DocumentType documentType) {\n String docType = documentType.getName();\n List paths = docBlobPaths.get(docType);\n if (paths == null) {\n paths = new ArrayList<>();\n for (Schema schema : documentType.getSchemas()) {\n findBlobPaths(schema, null, schema, paths);\n }\n docBlobPaths.put(docType, paths);\n }\n return paths;\n }\n\n protected void findBlobsProperties(Property property, List split, List properties) {\n if (split.isEmpty()) {\n if (property.getValue() != null) {\n properties.add(property);\n }\n } else {\n String name = split.get(0);\n List subPath = split.subList(1, split.size());\n if (property.isList()) {\n for (Property childProperty : property.getChildren()) {\n Property childSubProp = childProperty.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n } else {\n // complex type\n Property childSubProp = property.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n }\n }\n\n protected void findBlobPaths(ComplexType complexType, String path, Schema schema, List paths) {\n for (Field field : complexType.getFields()) {\n String fieldPath = field.getName().getPrefixedName();\n if (path == null) {\n // add schema name as prefix if the schema doesn't have a prefix\n if (!schema.getNamespace().hasPrefix()) {\n fieldPath = schema.getName() + \":\" + fieldPath;\n }\n } else {\n fieldPath = path + \"/\" + fieldPath;\n }\n Type type = field.getType();\n if (type.isSimpleType()) {\n // not binary text\n continue;\n } else if (type.isListType()) {\n Type fieldType = ((ListType) type).getFieldType();\n if (fieldType.isComplexType()) {\n findBlobPaths((ComplexType) fieldType, fieldPath + \"/*\", schema, paths);\n } else {\n // not binary text\n continue;\n }\n } else {\n // complex type\n ComplexType ctype = (ComplexType) type;\n if (TypeConstants.isContentType(type)) {\n // note this path\n paths.add(fieldPath);\n } else {\n findBlobPaths(ctype, fieldPath, schema, paths);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_1960", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/nuxeo/nuxeo/nuxeo-core/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/utils/BlobsExtractor.java", "mask_start_position": 6605, "mask_end_position": 6605, "canonical_solution": "", "pre_mask_code": "package org.nuxeo.ecm.core.utils;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport org.nuxeo.ecm.core.api.Blob;\nimport org.nuxeo.ecm.core.api.DocumentModel;\nimport org.nuxeo.ecm.core.api.model.Property;\nimport org.nuxeo.ecm.core.schema.DocumentType;\nimport org.nuxeo.ecm.core.schema.SchemaManager;\nimport org.nuxeo.ecm.core.schema.TypeConstants;\nimport org.nuxeo.ecm.core.schema.types.ComplexType;\nimport org.nuxeo.ecm.core.schema.types.Field;\nimport org.nuxeo.ecm.core.schema.types.ListType;\nimport org.nuxeo.ecm.core.schema.types.Schema;\nimport org.nuxeo.ecm.core.schema.types.Type;\nimport org.nuxeo.runtime.api.Framework;\n\n/**\n * Extractor for all the blobs of a document.\n */\npublic class BlobsExtractor {\n\n protected final Map> docBlobPaths = new ConcurrentHashMap<>();\n\n private Set includedPaths;\n\n private Set excludedPaths;\n\n private boolean allBlobs;\n\n private boolean isDefaultConfiguration = true;\n\n /**\n * Sets extractor properties, controlling what properties or values are returned by {@link #getBlobsProperties} or\n * {@link #getBlobs}.\n *

\n * The properties have to be defined without prefix if there is no prefix in the schema definition. For blob\n * properties, the path must include the {@code /data} part.\n */\n public void setExtractorProperties(Set includedPaths, Set excludedPaths, boolean allBlobs) {\n this.includedPaths = normalizePaths(includedPaths);\n this.excludedPaths = normalizePaths(excludedPaths);\n this.allBlobs = allBlobs;\n isDefaultConfiguration = includedPaths == null && excludedPaths == null && allBlobs;\n }\n\n protected boolean isInterestingPath(String path) {\n if (isDefaultConfiguration) {\n return true;\n } else if (excludedPaths != null && excludedPaths.contains(path)) {\n return false;\n } else if (includedPaths != null && includedPaths.contains(path)) {\n return true;\n } else if (allBlobs) {\n return true;\n }\n return false;\n }\n\n /**\n * Removes the \"/data\" suffix used by FulltextConfiguration.\n *

\n * Adds missing schema name as prefix if no prefix (\"content\" -> \"file:content\").\n */\n protected Set normalizePaths(Set paths) {\n if (paths == null) {\n return null;\n }\n SchemaManager schemaManager = Framework.getService(SchemaManager.class);\n Set normPaths = new HashSet<>();\n for (String path : paths) {\n if (path.endsWith(\"/data\")) {\n path = path.substring(0, path.length() - \"/data\".length());\n }\n // add schema if no schema prefix\n if (schemaManager.getField(path) == null && !path.contains(\":\")) {\n // check without prefix\n // TODO precompute this in SchemaManagerImpl\n int slash = path.indexOf('/');\n String first = slash == -1 ? path : path.substring(0, slash);\n for (Schema schema : schemaManager.getSchemas()) {\n if (!schema.getNamespace().hasPrefix()) {\n // schema without prefix, try it\n if (schema.getField(first) != null) {\n path = schema.getName() + \":\" + path;\n break;\n }\n }\n }\n }\n normPaths.add(path);\n }\n return normPaths;\n }\n\n /**\n * Gets the blobs of the document.\n *\n * @param doc the document\n * @return the list of blobs\n */\n public List getBlobs(DocumentModel doc) {\n List blobs = new ArrayList<>();\n for (Property property : getBlobsProperties(doc)) {\n blobs.add((Blob) property.getValue());\n }\n return blobs;\n }\n\n /**\n * Gets the blob properties of the document.\n *\n * @param doc the document\n * @return the list of blob properties\n */\n public List getBlobsProperties(DocumentModel doc) {\n List properties = new ArrayList<>();\n for (String path : getBlobPaths(doc.getDocumentType())) {\n if (!isInterestingPath(path)) {\n continue;\n }\n // split on:\n List split = Arrays.asList(path.split(\"/[*]/|/\"));\n if (split.isEmpty()) {\n throw new IllegalStateException(\"Path detected not well-formed: \" + path);\n }\n Property property = doc.getProperty(split.get(0));\n List subPath = split.subList(1, split.size());\n findBlobsProperties(property, subPath, properties);\n }\n return properties;\n }\n\n /**\n * Gets the blob paths of the document type. Extractor properties are ignored.\n *\n * @param documentType the document type\n * @return the list of blob paths\n *\n * @since 8.3\n */\n public List getBlobPaths(DocumentType documentType) {\n String docType = documentType.getName();\n List paths = docBlobPaths.get(docType);\n if (paths == null) {\n paths = new ArrayList<>();\n for (Schema schema : documentType.getSchemas()) {\n findBlobPaths(schema, null, schema, paths);\n }\n docBlobPaths.put(docType, paths);\n }\n return paths;\n }\n\n protected void findBlobsProperties(Property property, List split, List properties) {\n if (split.isEmpty()) {\n if (property.getValue() != null) {\n properties.add(property);\n }\n } else {\n String name = split.get(0);\n List subPath = split.subList(1, split.size());\n if (property.isList()) {\n for (Property childProperty : property.getChildren()) {\n Property childSubProp = childProperty.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n } else {\n // complex type\n Property childSubProp = property.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n }\n }\n\n protected void findBlobPaths(ComplexType complexType, String path, Schema schema, List paths) {", "post_mask_code": "\n for (Field field : complexType.getFields()) {\n String fieldPath = field.getName().getPrefixedName();\n if (path == null) {\n // add schema name as prefix if the schema doesn't have a prefix\n if (!schema.getNamespace().hasPrefix()) {\n fieldPath = schema.getName() + \":\" + fieldPath;\n }\n } else {\n fieldPath = path + \"/\" + fieldPath;\n }\n Type type = field.getType();\n if (type.isSimpleType()) {\n // not binary text\n continue;\n } else if (type.isListType()) {\n Type fieldType = ((ListType) type).getFieldType();\n if (fieldType.isComplexType()) {\n findBlobPaths((ComplexType) fieldType, fieldPath + \"/*\", schema, paths);\n } else {\n // not binary text\n continue;\n }\n } else {\n // complex type\n ComplexType ctype = (ComplexType) type;\n if (TypeConstants.isContentType(type)) {\n // note this path\n paths.add(fieldPath);\n } else {\n findBlobPaths(ctype, fieldPath, schema, paths);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_1961", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/nuxeo/nuxeo/nuxeo-core/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/utils/BlobsExtractor.java", "mask_start_position": 6614, "mask_end_position": 7956, "canonical_solution": "for (Field field : complexType.getFields()) {\n String fieldPath = field.getName().getPrefixedName();\n if (path == null) {\n // add schema name as prefix if the schema doesn't have a prefix\n if (!schema.getNamespace().hasPrefix()) {\n fieldPath = schema.getName() + \":\" + fieldPath;\n }\n } else {\n fieldPath = path + \"/\" + fieldPath;\n }\n Type type = field.getType();\n if (type.isSimpleType()) {\n // not binary text\n continue;\n } else if (type.isListType()) {\n Type fieldType = ((ListType) type).getFieldType();\n if (fieldType.isComplexType()) {\n findBlobPaths((ComplexType) fieldType, fieldPath + \"/*\", schema, paths);\n } else {\n // not binary text\n continue;\n }\n } else {\n // complex type\n ComplexType ctype = (ComplexType) type;\n if (TypeConstants.isContentType(type)) {\n // note this path\n paths.add(fieldPath);\n } else {\n findBlobPaths(ctype, fieldPath, schema, paths);\n }\n }\n }", "pre_mask_code": "package org.nuxeo.ecm.core.utils;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport org.nuxeo.ecm.core.api.Blob;\nimport org.nuxeo.ecm.core.api.DocumentModel;\nimport org.nuxeo.ecm.core.api.model.Property;\nimport org.nuxeo.ecm.core.schema.DocumentType;\nimport org.nuxeo.ecm.core.schema.SchemaManager;\nimport org.nuxeo.ecm.core.schema.TypeConstants;\nimport org.nuxeo.ecm.core.schema.types.ComplexType;\nimport org.nuxeo.ecm.core.schema.types.Field;\nimport org.nuxeo.ecm.core.schema.types.ListType;\nimport org.nuxeo.ecm.core.schema.types.Schema;\nimport org.nuxeo.ecm.core.schema.types.Type;\nimport org.nuxeo.runtime.api.Framework;\n\n/**\n * Extractor for all the blobs of a document.\n */\npublic class BlobsExtractor {\n\n protected final Map> docBlobPaths = new ConcurrentHashMap<>();\n\n private Set includedPaths;\n\n private Set excludedPaths;\n\n private boolean allBlobs;\n\n private boolean isDefaultConfiguration = true;\n\n /**\n * Sets extractor properties, controlling what properties or values are returned by {@link #getBlobsProperties} or\n * {@link #getBlobs}.\n *

\n * The properties have to be defined without prefix if there is no prefix in the schema definition. For blob\n * properties, the path must include the {@code /data} part.\n */\n public void setExtractorProperties(Set includedPaths, Set excludedPaths, boolean allBlobs) {\n this.includedPaths = normalizePaths(includedPaths);\n this.excludedPaths = normalizePaths(excludedPaths);\n this.allBlobs = allBlobs;\n isDefaultConfiguration = includedPaths == null && excludedPaths == null && allBlobs;\n }\n\n protected boolean isInterestingPath(String path) {\n if (isDefaultConfiguration) {\n return true;\n } else if (excludedPaths != null && excludedPaths.contains(path)) {\n return false;\n } else if (includedPaths != null && includedPaths.contains(path)) {\n return true;\n } else if (allBlobs) {\n return true;\n }\n return false;\n }\n\n /**\n * Removes the \"/data\" suffix used by FulltextConfiguration.\n *

\n * Adds missing schema name as prefix if no prefix (\"content\" -> \"file:content\").\n */\n protected Set normalizePaths(Set paths) {\n if (paths == null) {\n return null;\n }\n SchemaManager schemaManager = Framework.getService(SchemaManager.class);\n Set normPaths = new HashSet<>();\n for (String path : paths) {\n if (path.endsWith(\"/data\")) {\n path = path.substring(0, path.length() - \"/data\".length());\n }\n // add schema if no schema prefix\n if (schemaManager.getField(path) == null && !path.contains(\":\")) {\n // check without prefix\n // TODO precompute this in SchemaManagerImpl\n int slash = path.indexOf('/');\n String first = slash == -1 ? path : path.substring(0, slash);\n for (Schema schema : schemaManager.getSchemas()) {\n if (!schema.getNamespace().hasPrefix()) {\n // schema without prefix, try it\n if (schema.getField(first) != null) {\n path = schema.getName() + \":\" + path;\n break;\n }\n }\n }\n }\n normPaths.add(path);\n }\n return normPaths;\n }\n\n /**\n * Gets the blobs of the document.\n *\n * @param doc the document\n * @return the list of blobs\n */\n public List getBlobs(DocumentModel doc) {\n List blobs = new ArrayList<>();\n for (Property property : getBlobsProperties(doc)) {\n blobs.add((Blob) property.getValue());\n }\n return blobs;\n }\n\n /**\n * Gets the blob properties of the document.\n *\n * @param doc the document\n * @return the list of blob properties\n */\n public List getBlobsProperties(DocumentModel doc) {\n List properties = new ArrayList<>();\n for (String path : getBlobPaths(doc.getDocumentType())) {\n if (!isInterestingPath(path)) {\n continue;\n }\n // split on:\n List split = Arrays.asList(path.split(\"/[*]/|/\"));\n if (split.isEmpty()) {\n throw new IllegalStateException(\"Path detected not well-formed: \" + path);\n }\n Property property = doc.getProperty(split.get(0));\n List subPath = split.subList(1, split.size());\n findBlobsProperties(property, subPath, properties);\n }\n return properties;\n }\n\n /**\n * Gets the blob paths of the document type. Extractor properties are ignored.\n *\n * @param documentType the document type\n * @return the list of blob paths\n *\n * @since 8.3\n */\n public List getBlobPaths(DocumentType documentType) {\n String docType = documentType.getName();\n List paths = docBlobPaths.get(docType);\n if (paths == null) {\n paths = new ArrayList<>();\n for (Schema schema : documentType.getSchemas()) {\n findBlobPaths(schema, null, schema, paths);\n }\n docBlobPaths.put(docType, paths);\n }\n return paths;\n }\n\n protected void findBlobsProperties(Property property, List split, List properties) {\n if (split.isEmpty()) {\n if (property.getValue() != null) {\n properties.add(property);\n }\n } else {\n String name = split.get(0);\n List subPath = split.subList(1, split.size());\n if (property.isList()) {\n for (Property childProperty : property.getChildren()) {\n Property childSubProp = childProperty.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n } else {\n // complex type\n Property childSubProp = property.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n }\n }\n\n protected void findBlobPaths(ComplexType complexType, String path, Schema schema, List paths) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1962", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/nuxeo/nuxeo/nuxeo-core/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/utils/BlobsExtractor.java", "mask_start_position": 7961, "mask_end_position": 7962, "canonical_solution": "}", "pre_mask_code": "package org.nuxeo.ecm.core.utils;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport org.nuxeo.ecm.core.api.Blob;\nimport org.nuxeo.ecm.core.api.DocumentModel;\nimport org.nuxeo.ecm.core.api.model.Property;\nimport org.nuxeo.ecm.core.schema.DocumentType;\nimport org.nuxeo.ecm.core.schema.SchemaManager;\nimport org.nuxeo.ecm.core.schema.TypeConstants;\nimport org.nuxeo.ecm.core.schema.types.ComplexType;\nimport org.nuxeo.ecm.core.schema.types.Field;\nimport org.nuxeo.ecm.core.schema.types.ListType;\nimport org.nuxeo.ecm.core.schema.types.Schema;\nimport org.nuxeo.ecm.core.schema.types.Type;\nimport org.nuxeo.runtime.api.Framework;\n\n/**\n * Extractor for all the blobs of a document.\n */\npublic class BlobsExtractor {\n\n protected final Map> docBlobPaths = new ConcurrentHashMap<>();\n\n private Set includedPaths;\n\n private Set excludedPaths;\n\n private boolean allBlobs;\n\n private boolean isDefaultConfiguration = true;\n\n /**\n * Sets extractor properties, controlling what properties or values are returned by {@link #getBlobsProperties} or\n * {@link #getBlobs}.\n *

\n * The properties have to be defined without prefix if there is no prefix in the schema definition. For blob\n * properties, the path must include the {@code /data} part.\n */\n public void setExtractorProperties(Set includedPaths, Set excludedPaths, boolean allBlobs) {\n this.includedPaths = normalizePaths(includedPaths);\n this.excludedPaths = normalizePaths(excludedPaths);\n this.allBlobs = allBlobs;\n isDefaultConfiguration = includedPaths == null && excludedPaths == null && allBlobs;\n }\n\n protected boolean isInterestingPath(String path) {\n if (isDefaultConfiguration) {\n return true;\n } else if (excludedPaths != null && excludedPaths.contains(path)) {\n return false;\n } else if (includedPaths != null && includedPaths.contains(path)) {\n return true;\n } else if (allBlobs) {\n return true;\n }\n return false;\n }\n\n /**\n * Removes the \"/data\" suffix used by FulltextConfiguration.\n *

\n * Adds missing schema name as prefix if no prefix (\"content\" -> \"file:content\").\n */\n protected Set normalizePaths(Set paths) {\n if (paths == null) {\n return null;\n }\n SchemaManager schemaManager = Framework.getService(SchemaManager.class);\n Set normPaths = new HashSet<>();\n for (String path : paths) {\n if (path.endsWith(\"/data\")) {\n path = path.substring(0, path.length() - \"/data\".length());\n }\n // add schema if no schema prefix\n if (schemaManager.getField(path) == null && !path.contains(\":\")) {\n // check without prefix\n // TODO precompute this in SchemaManagerImpl\n int slash = path.indexOf('/');\n String first = slash == -1 ? path : path.substring(0, slash);\n for (Schema schema : schemaManager.getSchemas()) {\n if (!schema.getNamespace().hasPrefix()) {\n // schema without prefix, try it\n if (schema.getField(first) != null) {\n path = schema.getName() + \":\" + path;\n break;\n }\n }\n }\n }\n normPaths.add(path);\n }\n return normPaths;\n }\n\n /**\n * Gets the blobs of the document.\n *\n * @param doc the document\n * @return the list of blobs\n */\n public List getBlobs(DocumentModel doc) {\n List blobs = new ArrayList<>();\n for (Property property : getBlobsProperties(doc)) {\n blobs.add((Blob) property.getValue());\n }\n return blobs;\n }\n\n /**\n * Gets the blob properties of the document.\n *\n * @param doc the document\n * @return the list of blob properties\n */\n public List getBlobsProperties(DocumentModel doc) {\n List properties = new ArrayList<>();\n for (String path : getBlobPaths(doc.getDocumentType())) {\n if (!isInterestingPath(path)) {\n continue;\n }\n // split on:\n List split = Arrays.asList(path.split(\"/[*]/|/\"));\n if (split.isEmpty()) {\n throw new IllegalStateException(\"Path detected not well-formed: \" + path);\n }\n Property property = doc.getProperty(split.get(0));\n List subPath = split.subList(1, split.size());\n findBlobsProperties(property, subPath, properties);\n }\n return properties;\n }\n\n /**\n * Gets the blob paths of the document type. Extractor properties are ignored.\n *\n * @param documentType the document type\n * @return the list of blob paths\n *\n * @since 8.3\n */\n public List getBlobPaths(DocumentType documentType) {\n String docType = documentType.getName();\n List paths = docBlobPaths.get(docType);\n if (paths == null) {\n paths = new ArrayList<>();\n for (Schema schema : documentType.getSchemas()) {\n findBlobPaths(schema, null, schema, paths);\n }\n docBlobPaths.put(docType, paths);\n }\n return paths;\n }\n\n protected void findBlobsProperties(Property property, List split, List properties) {\n if (split.isEmpty()) {\n if (property.getValue() != null) {\n properties.add(property);\n }\n } else {\n String name = split.get(0);\n List subPath = split.subList(1, split.size());\n if (property.isList()) {\n for (Property childProperty : property.getChildren()) {\n Property childSubProp = childProperty.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n } else {\n // complex type\n Property childSubProp = property.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n }\n }\n\n protected void findBlobPaths(ComplexType complexType, String path, Schema schema, List paths) {\n for (Field field : complexType.getFields()) {\n String fieldPath = field.getName().getPrefixedName();\n if (path == null) {\n // add schema name as prefix if the schema doesn't have a prefix\n if (!schema.getNamespace().hasPrefix()) {\n fieldPath = schema.getName() + \":\" + fieldPath;\n }\n } else {\n fieldPath = path + \"/\" + fieldPath;\n }\n Type type = field.getType();\n if (type.isSimpleType()) {\n // not binary text\n continue;\n } else if (type.isListType()) {\n Type fieldType = ((ListType) type).getFieldType();\n if (fieldType.isComplexType()) {\n findBlobPaths((ComplexType) fieldType, fieldPath + \"/*\", schema, paths);\n } else {\n // not binary text\n continue;\n }\n } else {\n // complex type\n ComplexType ctype = (ComplexType) type;\n if (TypeConstants.isContentType(type)) {\n // note this path\n paths.add(fieldPath);\n } else {\n findBlobPaths(ctype, fieldPath, schema, paths);\n }\n }\n }\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1963", "language": "Java", "task_type": "single_line", "source_file": "java/github/nuxeo/nuxeo/nuxeo-core/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/utils/BlobsExtractor.java", "mask_start_position": 3681, "mask_end_position": 3698, "canonical_solution": "return normPaths;", "pre_mask_code": "package org.nuxeo.ecm.core.utils;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport org.nuxeo.ecm.core.api.Blob;\nimport org.nuxeo.ecm.core.api.DocumentModel;\nimport org.nuxeo.ecm.core.api.model.Property;\nimport org.nuxeo.ecm.core.schema.DocumentType;\nimport org.nuxeo.ecm.core.schema.SchemaManager;\nimport org.nuxeo.ecm.core.schema.TypeConstants;\nimport org.nuxeo.ecm.core.schema.types.ComplexType;\nimport org.nuxeo.ecm.core.schema.types.Field;\nimport org.nuxeo.ecm.core.schema.types.ListType;\nimport org.nuxeo.ecm.core.schema.types.Schema;\nimport org.nuxeo.ecm.core.schema.types.Type;\nimport org.nuxeo.runtime.api.Framework;\n\n/**\n * Extractor for all the blobs of a document.\n */\npublic class BlobsExtractor {\n\n protected final Map> docBlobPaths = new ConcurrentHashMap<>();\n\n private Set includedPaths;\n\n private Set excludedPaths;\n\n private boolean allBlobs;\n\n private boolean isDefaultConfiguration = true;\n\n /**\n * Sets extractor properties, controlling what properties or values are returned by {@link #getBlobsProperties} or\n * {@link #getBlobs}.\n *

\n * The properties have to be defined without prefix if there is no prefix in the schema definition. For blob\n * properties, the path must include the {@code /data} part.\n */\n public void setExtractorProperties(Set includedPaths, Set excludedPaths, boolean allBlobs) {\n this.includedPaths = normalizePaths(includedPaths);\n this.excludedPaths = normalizePaths(excludedPaths);\n this.allBlobs = allBlobs;\n isDefaultConfiguration = includedPaths == null && excludedPaths == null && allBlobs;\n }\n\n protected boolean isInterestingPath(String path) {\n if (isDefaultConfiguration) {\n return true;\n } else if (excludedPaths != null && excludedPaths.contains(path)) {\n return false;\n } else if (includedPaths != null && includedPaths.contains(path)) {\n return true;\n } else if (allBlobs) {\n return true;\n }\n return false;\n }\n\n /**\n * Removes the \"/data\" suffix used by FulltextConfiguration.\n *

\n * Adds missing schema name as prefix if no prefix (\"content\" -> \"file:content\").\n */\n protected Set normalizePaths(Set paths) {\n if (paths == null) {\n return null;\n }\n SchemaManager schemaManager = Framework.getService(SchemaManager.class);\n Set normPaths = new HashSet<>();\n for (String path : paths) {\n if (path.endsWith(\"/data\")) {\n path = path.substring(0, path.length() - \"/data\".length());\n }\n // add schema if no schema prefix\n if (schemaManager.getField(path) == null && !path.contains(\":\")) {\n // check without prefix\n // TODO precompute this in SchemaManagerImpl\n int slash = path.indexOf('/');\n String first = slash == -1 ? path : path.substring(0, slash);\n for (Schema schema : schemaManager.getSchemas()) {\n if (!schema.getNamespace().hasPrefix()) {\n // schema without prefix, try it\n if (schema.getField(first) != null) {\n path = schema.getName() + \":\" + path;\n break;\n }\n }\n }\n }\n normPaths.add(path);\n }\n ", "post_mask_code": "\n }\n\n /**\n * Gets the blobs of the document.\n *\n * @param doc the document\n * @return the list of blobs\n */\n public List getBlobs(DocumentModel doc) {\n List blobs = new ArrayList<>();\n for (Property property : getBlobsProperties(doc)) {\n blobs.add((Blob) property.getValue());\n }\n return blobs;\n }\n\n /**\n * Gets the blob properties of the document.\n *\n * @param doc the document\n * @return the list of blob properties\n */\n public List getBlobsProperties(DocumentModel doc) {\n List properties = new ArrayList<>();\n for (String path : getBlobPaths(doc.getDocumentType())) {\n if (!isInterestingPath(path)) {\n continue;\n }\n // split on:\n List split = Arrays.asList(path.split(\"/[*]/|/\"));\n if (split.isEmpty()) {\n throw new IllegalStateException(\"Path detected not well-formed: \" + path);\n }\n Property property = doc.getProperty(split.get(0));\n List subPath = split.subList(1, split.size());\n findBlobsProperties(property, subPath, properties);\n }\n return properties;\n }\n\n /**\n * Gets the blob paths of the document type. Extractor properties are ignored.\n *\n * @param documentType the document type\n * @return the list of blob paths\n *\n * @since 8.3\n */\n public List getBlobPaths(DocumentType documentType) {\n String docType = documentType.getName();\n List paths = docBlobPaths.get(docType);\n if (paths == null) {\n paths = new ArrayList<>();\n for (Schema schema : documentType.getSchemas()) {\n findBlobPaths(schema, null, schema, paths);\n }\n docBlobPaths.put(docType, paths);\n }\n return paths;\n }\n\n protected void findBlobsProperties(Property property, List split, List properties) {\n if (split.isEmpty()) {\n if (property.getValue() != null) {\n properties.add(property);\n }\n } else {\n String name = split.get(0);\n List subPath = split.subList(1, split.size());\n if (property.isList()) {\n for (Property childProperty : property.getChildren()) {\n Property childSubProp = childProperty.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n } else {\n // complex type\n Property childSubProp = property.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n }\n }\n\n protected void findBlobPaths(ComplexType complexType, String path, Schema schema, List paths) {\n for (Field field : complexType.getFields()) {\n String fieldPath = field.getName().getPrefixedName();\n if (path == null) {\n // add schema name as prefix if the schema doesn't have a prefix\n if (!schema.getNamespace().hasPrefix()) {\n fieldPath = schema.getName() + \":\" + fieldPath;\n }\n } else {\n fieldPath = path + \"/\" + fieldPath;\n }\n Type type = field.getType();\n if (type.isSimpleType()) {\n // not binary text\n continue;\n } else if (type.isListType()) {\n Type fieldType = ((ListType) type).getFieldType();\n if (fieldType.isComplexType()) {\n findBlobPaths((ComplexType) fieldType, fieldPath + \"/*\", schema, paths);\n } else {\n // not binary text\n continue;\n }\n } else {\n // complex type\n ComplexType ctype = (ComplexType) type;\n if (TypeConstants.isContentType(type)) {\n // note this path\n paths.add(fieldPath);\n } else {\n findBlobPaths(ctype, fieldPath, schema, paths);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_1964", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/nuxeo/nuxeo/nuxeo-core/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/utils/BlobsExtractor.java", "mask_start_position": 1469, "mask_end_position": 1830, "canonical_solution": "public void setExtractorProperties(Set includedPaths, Set excludedPaths, boolean allBlobs) {\n this.includedPaths = normalizePaths(includedPaths);\n this.excludedPaths = normalizePaths(excludedPaths);\n this.allBlobs = allBlobs;\n isDefaultConfiguration = includedPaths == null && excludedPaths == null && allBlobs;\n }", "pre_mask_code": "package org.nuxeo.ecm.core.utils;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport org.nuxeo.ecm.core.api.Blob;\nimport org.nuxeo.ecm.core.api.DocumentModel;\nimport org.nuxeo.ecm.core.api.model.Property;\nimport org.nuxeo.ecm.core.schema.DocumentType;\nimport org.nuxeo.ecm.core.schema.SchemaManager;\nimport org.nuxeo.ecm.core.schema.TypeConstants;\nimport org.nuxeo.ecm.core.schema.types.ComplexType;\nimport org.nuxeo.ecm.core.schema.types.Field;\nimport org.nuxeo.ecm.core.schema.types.ListType;\nimport org.nuxeo.ecm.core.schema.types.Schema;\nimport org.nuxeo.ecm.core.schema.types.Type;\nimport org.nuxeo.runtime.api.Framework;\n\n/**\n * Extractor for all the blobs of a document.\n */\npublic class BlobsExtractor {\n\n protected final Map> docBlobPaths = new ConcurrentHashMap<>();\n\n private Set includedPaths;\n\n private Set excludedPaths;\n\n private boolean allBlobs;\n\n private boolean isDefaultConfiguration = true;\n\n /**\n * Sets extractor properties, controlling what properties or values are returned by {@link #getBlobsProperties} or\n * {@link #getBlobs}.\n *

\n * The properties have to be defined without prefix if there is no prefix in the schema definition. For blob\n * properties, the path must include the {@code /data} part.\n */\n ", "post_mask_code": "\n\n protected boolean isInterestingPath(String path) {\n if (isDefaultConfiguration) {\n return true;\n } else if (excludedPaths != null && excludedPaths.contains(path)) {\n return false;\n } else if (includedPaths != null && includedPaths.contains(path)) {\n return true;\n } else if (allBlobs) {\n return true;\n }\n return false;\n }\n\n /**\n * Removes the \"/data\" suffix used by FulltextConfiguration.\n *

\n * Adds missing schema name as prefix if no prefix (\"content\" -> \"file:content\").\n */\n protected Set normalizePaths(Set paths) {\n if (paths == null) {\n return null;\n }\n SchemaManager schemaManager = Framework.getService(SchemaManager.class);\n Set normPaths = new HashSet<>();\n for (String path : paths) {\n if (path.endsWith(\"/data\")) {\n path = path.substring(0, path.length() - \"/data\".length());\n }\n // add schema if no schema prefix\n if (schemaManager.getField(path) == null && !path.contains(\":\")) {\n // check without prefix\n // TODO precompute this in SchemaManagerImpl\n int slash = path.indexOf('/');\n String first = slash == -1 ? path : path.substring(0, slash);\n for (Schema schema : schemaManager.getSchemas()) {\n if (!schema.getNamespace().hasPrefix()) {\n // schema without prefix, try it\n if (schema.getField(first) != null) {\n path = schema.getName() + \":\" + path;\n break;\n }\n }\n }\n }\n normPaths.add(path);\n }\n return normPaths;\n }\n\n /**\n * Gets the blobs of the document.\n *\n * @param doc the document\n * @return the list of blobs\n */\n public List getBlobs(DocumentModel doc) {\n List blobs = new ArrayList<>();\n for (Property property : getBlobsProperties(doc)) {\n blobs.add((Blob) property.getValue());\n }\n return blobs;\n }\n\n /**\n * Gets the blob properties of the document.\n *\n * @param doc the document\n * @return the list of blob properties\n */\n public List getBlobsProperties(DocumentModel doc) {\n List properties = new ArrayList<>();\n for (String path : getBlobPaths(doc.getDocumentType())) {\n if (!isInterestingPath(path)) {\n continue;\n }\n // split on:\n List split = Arrays.asList(path.split(\"/[*]/|/\"));\n if (split.isEmpty()) {\n throw new IllegalStateException(\"Path detected not well-formed: \" + path);\n }\n Property property = doc.getProperty(split.get(0));\n List subPath = split.subList(1, split.size());\n findBlobsProperties(property, subPath, properties);\n }\n return properties;\n }\n\n /**\n * Gets the blob paths of the document type. Extractor properties are ignored.\n *\n * @param documentType the document type\n * @return the list of blob paths\n *\n * @since 8.3\n */\n public List getBlobPaths(DocumentType documentType) {\n String docType = documentType.getName();\n List paths = docBlobPaths.get(docType);\n if (paths == null) {\n paths = new ArrayList<>();\n for (Schema schema : documentType.getSchemas()) {\n findBlobPaths(schema, null, schema, paths);\n }\n docBlobPaths.put(docType, paths);\n }\n return paths;\n }\n\n protected void findBlobsProperties(Property property, List split, List properties) {\n if (split.isEmpty()) {\n if (property.getValue() != null) {\n properties.add(property);\n }\n } else {\n String name = split.get(0);\n List subPath = split.subList(1, split.size());\n if (property.isList()) {\n for (Property childProperty : property.getChildren()) {\n Property childSubProp = childProperty.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n } else {\n // complex type\n Property childSubProp = property.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n }\n }\n\n protected void findBlobPaths(ComplexType complexType, String path, Schema schema, List paths) {\n for (Field field : complexType.getFields()) {\n String fieldPath = field.getName().getPrefixedName();\n if (path == null) {\n // add schema name as prefix if the schema doesn't have a prefix\n if (!schema.getNamespace().hasPrefix()) {\n fieldPath = schema.getName() + \":\" + fieldPath;\n }\n } else {\n fieldPath = path + \"/\" + fieldPath;\n }\n Type type = field.getType();\n if (type.isSimpleType()) {\n // not binary text\n continue;\n } else if (type.isListType()) {\n Type fieldType = ((ListType) type).getFieldType();\n if (fieldType.isComplexType()) {\n findBlobPaths((ComplexType) fieldType, fieldPath + \"/*\", schema, paths);\n } else {\n // not binary text\n continue;\n }\n } else {\n // complex type\n ComplexType ctype = (ComplexType) type;\n if (TypeConstants.isContentType(type)) {\n // note this path\n paths.add(fieldPath);\n } else {\n findBlobPaths(ctype, fieldPath, schema, paths);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_1965", "language": "Java", "task_type": "if_statement", "source_file": "java/github/nuxeo/nuxeo/nuxeo-core/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/utils/BlobsExtractor.java", "mask_start_position": 1965, "mask_end_position": 2218, "canonical_solution": "if (excludedPaths != null && excludedPaths.contains(path)) {\n return false;\n } else if (includedPaths != null && includedPaths.contains(path)) {\n return true;\n } else if (allBlobs) {\n return true;\n }", "pre_mask_code": "package org.nuxeo.ecm.core.utils;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport org.nuxeo.ecm.core.api.Blob;\nimport org.nuxeo.ecm.core.api.DocumentModel;\nimport org.nuxeo.ecm.core.api.model.Property;\nimport org.nuxeo.ecm.core.schema.DocumentType;\nimport org.nuxeo.ecm.core.schema.SchemaManager;\nimport org.nuxeo.ecm.core.schema.TypeConstants;\nimport org.nuxeo.ecm.core.schema.types.ComplexType;\nimport org.nuxeo.ecm.core.schema.types.Field;\nimport org.nuxeo.ecm.core.schema.types.ListType;\nimport org.nuxeo.ecm.core.schema.types.Schema;\nimport org.nuxeo.ecm.core.schema.types.Type;\nimport org.nuxeo.runtime.api.Framework;\n\n/**\n * Extractor for all the blobs of a document.\n */\npublic class BlobsExtractor {\n\n protected final Map> docBlobPaths = new ConcurrentHashMap<>();\n\n private Set includedPaths;\n\n private Set excludedPaths;\n\n private boolean allBlobs;\n\n private boolean isDefaultConfiguration = true;\n\n /**\n * Sets extractor properties, controlling what properties or values are returned by {@link #getBlobsProperties} or\n * {@link #getBlobs}.\n *

\n * The properties have to be defined without prefix if there is no prefix in the schema definition. For blob\n * properties, the path must include the {@code /data} part.\n */\n public void setExtractorProperties(Set includedPaths, Set excludedPaths, boolean allBlobs) {\n this.includedPaths = normalizePaths(includedPaths);\n this.excludedPaths = normalizePaths(excludedPaths);\n this.allBlobs = allBlobs;\n isDefaultConfiguration = includedPaths == null && excludedPaths == null && allBlobs;\n }\n\n protected boolean isInterestingPath(String path) {\n if (isDefaultConfiguration) {\n return true;\n } else ", "post_mask_code": "\n return false;\n }\n\n /**\n * Removes the \"/data\" suffix used by FulltextConfiguration.\n *

\n * Adds missing schema name as prefix if no prefix (\"content\" -> \"file:content\").\n */\n protected Set normalizePaths(Set paths) {\n if (paths == null) {\n return null;\n }\n SchemaManager schemaManager = Framework.getService(SchemaManager.class);\n Set normPaths = new HashSet<>();\n for (String path : paths) {\n if (path.endsWith(\"/data\")) {\n path = path.substring(0, path.length() - \"/data\".length());\n }\n // add schema if no schema prefix\n if (schemaManager.getField(path) == null && !path.contains(\":\")) {\n // check without prefix\n // TODO precompute this in SchemaManagerImpl\n int slash = path.indexOf('/');\n String first = slash == -1 ? path : path.substring(0, slash);\n for (Schema schema : schemaManager.getSchemas()) {\n if (!schema.getNamespace().hasPrefix()) {\n // schema without prefix, try it\n if (schema.getField(first) != null) {\n path = schema.getName() + \":\" + path;\n break;\n }\n }\n }\n }\n normPaths.add(path);\n }\n return normPaths;\n }\n\n /**\n * Gets the blobs of the document.\n *\n * @param doc the document\n * @return the list of blobs\n */\n public List getBlobs(DocumentModel doc) {\n List blobs = new ArrayList<>();\n for (Property property : getBlobsProperties(doc)) {\n blobs.add((Blob) property.getValue());\n }\n return blobs;\n }\n\n /**\n * Gets the blob properties of the document.\n *\n * @param doc the document\n * @return the list of blob properties\n */\n public List getBlobsProperties(DocumentModel doc) {\n List properties = new ArrayList<>();\n for (String path : getBlobPaths(doc.getDocumentType())) {\n if (!isInterestingPath(path)) {\n continue;\n }\n // split on:\n List split = Arrays.asList(path.split(\"/[*]/|/\"));\n if (split.isEmpty()) {\n throw new IllegalStateException(\"Path detected not well-formed: \" + path);\n }\n Property property = doc.getProperty(split.get(0));\n List subPath = split.subList(1, split.size());\n findBlobsProperties(property, subPath, properties);\n }\n return properties;\n }\n\n /**\n * Gets the blob paths of the document type. Extractor properties are ignored.\n *\n * @param documentType the document type\n * @return the list of blob paths\n *\n * @since 8.3\n */\n public List getBlobPaths(DocumentType documentType) {\n String docType = documentType.getName();\n List paths = docBlobPaths.get(docType);\n if (paths == null) {\n paths = new ArrayList<>();\n for (Schema schema : documentType.getSchemas()) {\n findBlobPaths(schema, null, schema, paths);\n }\n docBlobPaths.put(docType, paths);\n }\n return paths;\n }\n\n protected void findBlobsProperties(Property property, List split, List properties) {\n if (split.isEmpty()) {\n if (property.getValue() != null) {\n properties.add(property);\n }\n } else {\n String name = split.get(0);\n List subPath = split.subList(1, split.size());\n if (property.isList()) {\n for (Property childProperty : property.getChildren()) {\n Property childSubProp = childProperty.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n } else {\n // complex type\n Property childSubProp = property.get(name);\n findBlobsProperties(childSubProp, subPath, properties);\n }\n }\n }\n\n protected void findBlobPaths(ComplexType complexType, String path, Schema schema, List paths) {\n for (Field field : complexType.getFields()) {\n String fieldPath = field.getName().getPrefixedName();\n if (path == null) {\n // add schema name as prefix if the schema doesn't have a prefix\n if (!schema.getNamespace().hasPrefix()) {\n fieldPath = schema.getName() + \":\" + fieldPath;\n }\n } else {\n fieldPath = path + \"/\" + fieldPath;\n }\n Type type = field.getType();\n if (type.isSimpleType()) {\n // not binary text\n continue;\n } else if (type.isListType()) {\n Type fieldType = ((ListType) type).getFieldType();\n if (fieldType.isComplexType()) {\n findBlobPaths((ComplexType) fieldType, fieldPath + \"/*\", schema, paths);\n } else {\n // not binary text\n continue;\n }\n } else {\n // complex type\n ComplexType ctype = (ComplexType) type;\n if (TypeConstants.isContentType(type)) {\n // note this path\n paths.add(fieldPath);\n } else {\n findBlobPaths(ctype, fieldPath, schema, paths);\n }\n }\n }\n }\n}\n"} {"task_id": "Java_1966", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Humsen/highdsa/highdsa-security-cas/highdsa-cas-server/src/main/java/pers/husen/highdsa/service/cas/server/auth/UsernamePasswordAuthenticationHandler.java", "mask_start_position": 1662, "mask_end_position": 1723, "canonical_solution": "@Override\n public boolean supports(Credential credential) ", "pre_mask_code": "package pers.husen.highdsa.service.cas.server.auth;\n\nimport java.security.GeneralSecurityException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.security.auth.login.FailedLoginException;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.apereo.cas.authentication.Credential;\nimport org.apereo.cas.authentication.HandlerResult;\nimport org.apereo.cas.authentication.PreventedException;\nimport org.apereo.cas.authentication.UsernamePasswordCredential;\nimport org.apereo.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;\nimport org.apereo.cas.authentication.principal.PrincipalFactory;\nimport org.apereo.cas.services.ServicesManager;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.datasource.DriverManagerDataSource;\nimport pers.husen.highdsa.common.encrypt.Md5Encrypt;\n\n/**\n * @Desc 登录验证类\n *\n * @Author 何明胜\n *\n * @Created at 2018年4月8日 下午10:33:36\n *\n * @Version 1.0.0\n */\npublic class UsernamePasswordAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {\n\n private final static Logger logger = LogManager.getLogger(UsernamePasswordAuthenticationHandler.class.getName());\n\n /**\n * @param name\n * @param servicesManager\n * @param principalFactory\n * @param order\n */\n public UsernamePasswordAuthenticationHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {\n super(name, servicesManager, principalFactory, order);\n }\n\n /**\n * 用于判断用户的Credential(换而言之,就是登录信息),是否是俺能处理的 就是有可能是,子站点的登录信息中不止有用户名密码等信息,还有部门信息的情况\n */\n ", "post_mask_code": "{\n // 判断传递过来的Credential 是否是自己能处理的类型\n return credential instanceof UsernamePasswordCredential;\n }\n\n @Override\n protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential transformedCredential, String originalPassword) throws GeneralSecurityException, PreventedException {\n DriverManagerDataSource d = new DriverManagerDataSource();\n d.setDriverClassName(\"com.mysql.jdbc.Driver\");\n d.setUrl(\"jdbc:mysql://rm-wz9lp2i9322g0n06zvo.mysql.rds.aliyuncs.com:3306/highdsa?useSSL=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull\");\n d.setUsername(\"webuser\");\n d.setPassword(\"123456\");\n JdbcTemplate template = new JdbcTemplate();\n template.setDataSource(d);\n String username = transformedCredential.getUsername();\n String currentPwd = transformedCredential.getPassword();\n logger.info(\"用户输入的密码:\" + currentPwd);\n // 查询数据库加密的的密码\n Map selectUser = template.queryForMap(\"SELECT user_name, user_password, user_pwd_salt FROM sys_user WHERE user_name = ?\", transformedCredential.getUsername());\n if (selectUser == null) {\n throw new FailedLoginException(\"没有该用户\");\n }\n // 返回多属性(暂时不知道怎么用,没研究)\n Map map = new HashMap<>(5);\n map.put(\"email\", \"example@nnthink.com\");\n // md5加密两次\n String encryptedSelectPwd = Md5Encrypt.getMD5Code(currentPwd, selectUser.get(\"user_name\").toString() + selectUser.get(\"user_pwd_salt\").toString(), 2);\n logger.info(\"md5加密两次后的密码:{}\", encryptedSelectPwd);\n String userPassword = \"user_password\";\n if (encryptedSelectPwd.equals(selectUser.get(userPassword).toString())) {\n logger.info(\"密码对比成功\");\n return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username, map), null);\n }\n throw new FailedLoginException(\"Sorry, login attemp failed.\");\n }\n}\n"} {"task_id": "Java_1967", "language": "Java", "task_type": "method_body", "source_file": "java/github/Humsen/highdsa/highdsa-security-cas/highdsa-cas-server/src/main/java/pers/husen/highdsa/service/cas/server/auth/UsernamePasswordAuthenticationHandler.java", "mask_start_position": 1723, "mask_end_position": 1836, "canonical_solution": "{\n // 判断传递过来的Credential 是否是自己能处理的类型\n return credential instanceof UsernamePasswordCredential;\n }", "pre_mask_code": "package pers.husen.highdsa.service.cas.server.auth;\n\nimport java.security.GeneralSecurityException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.security.auth.login.FailedLoginException;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.apereo.cas.authentication.Credential;\nimport org.apereo.cas.authentication.HandlerResult;\nimport org.apereo.cas.authentication.PreventedException;\nimport org.apereo.cas.authentication.UsernamePasswordCredential;\nimport org.apereo.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;\nimport org.apereo.cas.authentication.principal.PrincipalFactory;\nimport org.apereo.cas.services.ServicesManager;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.datasource.DriverManagerDataSource;\nimport pers.husen.highdsa.common.encrypt.Md5Encrypt;\n\n/**\n * @Desc 登录验证类\n *\n * @Author 何明胜\n *\n * @Created at 2018年4月8日 下午10:33:36\n *\n * @Version 1.0.0\n */\npublic class UsernamePasswordAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {\n\n private final static Logger logger = LogManager.getLogger(UsernamePasswordAuthenticationHandler.class.getName());\n\n /**\n * @param name\n * @param servicesManager\n * @param principalFactory\n * @param order\n */\n public UsernamePasswordAuthenticationHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {\n super(name, servicesManager, principalFactory, order);\n }\n\n /**\n * 用于判断用户的Credential(换而言之,就是登录信息),是否是俺能处理的 就是有可能是,子站点的登录信息中不止有用户名密码等信息,还有部门信息的情况\n */\n @Override\n public boolean supports(Credential credential) ", "post_mask_code": "\n\n @Override\n protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential transformedCredential, String originalPassword) throws GeneralSecurityException, PreventedException {\n DriverManagerDataSource d = new DriverManagerDataSource();\n d.setDriverClassName(\"com.mysql.jdbc.Driver\");\n d.setUrl(\"jdbc:mysql://rm-wz9lp2i9322g0n06zvo.mysql.rds.aliyuncs.com:3306/highdsa?useSSL=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull\");\n d.setUsername(\"webuser\");\n d.setPassword(\"123456\");\n JdbcTemplate template = new JdbcTemplate();\n template.setDataSource(d);\n String username = transformedCredential.getUsername();\n String currentPwd = transformedCredential.getPassword();\n logger.info(\"用户输入的密码:\" + currentPwd);\n // 查询数据库加密的的密码\n Map selectUser = template.queryForMap(\"SELECT user_name, user_password, user_pwd_salt FROM sys_user WHERE user_name = ?\", transformedCredential.getUsername());\n if (selectUser == null) {\n throw new FailedLoginException(\"没有该用户\");\n }\n // 返回多属性(暂时不知道怎么用,没研究)\n Map map = new HashMap<>(5);\n map.put(\"email\", \"example@nnthink.com\");\n // md5加密两次\n String encryptedSelectPwd = Md5Encrypt.getMD5Code(currentPwd, selectUser.get(\"user_name\").toString() + selectUser.get(\"user_pwd_salt\").toString(), 2);\n logger.info(\"md5加密两次后的密码:{}\", encryptedSelectPwd);\n String userPassword = \"user_password\";\n if (encryptedSelectPwd.equals(selectUser.get(userPassword).toString())) {\n logger.info(\"密码对比成功\");\n return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username, map), null);\n }\n throw new FailedLoginException(\"Sorry, login attemp failed.\");\n }\n}\n"} {"task_id": "Java_1968", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/Humsen/highdsa/highdsa-security-cas/highdsa-cas-server/src/main/java/pers/husen/highdsa/service/cas/server/auth/UsernamePasswordAuthenticationHandler.java", "mask_start_position": 2045, "mask_end_position": 2501, "canonical_solution": "\n DriverManagerDataSource d = new DriverManagerDataSource();\n d.setDriverClassName(\"com.mysql.jdbc.Driver\");\n d.setUrl(\"jdbc:mysql://rm-wz9lp2i9322g0n06zvo.mysql.rds.aliyuncs.com:3306/highdsa?useSSL=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull\");\n d.setUsername(\"webuser\");\n d.setPassword(\"123456\");\n JdbcTemplate template = new JdbcTemplate();\n template.setDataSource(d);", "pre_mask_code": "package pers.husen.highdsa.service.cas.server.auth;\n\nimport java.security.GeneralSecurityException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.security.auth.login.FailedLoginException;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.apereo.cas.authentication.Credential;\nimport org.apereo.cas.authentication.HandlerResult;\nimport org.apereo.cas.authentication.PreventedException;\nimport org.apereo.cas.authentication.UsernamePasswordCredential;\nimport org.apereo.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;\nimport org.apereo.cas.authentication.principal.PrincipalFactory;\nimport org.apereo.cas.services.ServicesManager;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.datasource.DriverManagerDataSource;\nimport pers.husen.highdsa.common.encrypt.Md5Encrypt;\n\n/**\n * @Desc 登录验证类\n *\n * @Author 何明胜\n *\n * @Created at 2018年4月8日 下午10:33:36\n *\n * @Version 1.0.0\n */\npublic class UsernamePasswordAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {\n\n private final static Logger logger = LogManager.getLogger(UsernamePasswordAuthenticationHandler.class.getName());\n\n /**\n * @param name\n * @param servicesManager\n * @param principalFactory\n * @param order\n */\n public UsernamePasswordAuthenticationHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {\n super(name, servicesManager, principalFactory, order);\n }\n\n /**\n * 用于判断用户的Credential(换而言之,就是登录信息),是否是俺能处理的 就是有可能是,子站点的登录信息中不止有用户名密码等信息,还有部门信息的情况\n */\n @Override\n public boolean supports(Credential credential) {\n // 判断传递过来的Credential 是否是自己能处理的类型\n return credential instanceof UsernamePasswordCredential;\n }\n\n @Override\n protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential transformedCredential, String originalPassword) throws GeneralSecurityException, PreventedException {", "post_mask_code": "\n String username = transformedCredential.getUsername();\n String currentPwd = transformedCredential.getPassword();\n logger.info(\"用户输入的密码:\" + currentPwd);\n // 查询数据库加密的的密码\n Map selectUser = template.queryForMap(\"SELECT user_name, user_password, user_pwd_salt FROM sys_user WHERE user_name = ?\", transformedCredential.getUsername());\n if (selectUser == null) {\n throw new FailedLoginException(\"没有该用户\");\n }\n // 返回多属性(暂时不知道怎么用,没研究)\n Map map = new HashMap<>(5);\n map.put(\"email\", \"example@nnthink.com\");\n // md5加密两次\n String encryptedSelectPwd = Md5Encrypt.getMD5Code(currentPwd, selectUser.get(\"user_name\").toString() + selectUser.get(\"user_pwd_salt\").toString(), 2);\n logger.info(\"md5加密两次后的密码:{}\", encryptedSelectPwd);\n String userPassword = \"user_password\";\n if (encryptedSelectPwd.equals(selectUser.get(userPassword).toString())) {\n logger.info(\"密码对比成功\");\n return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username, map), null);\n }\n throw new FailedLoginException(\"Sorry, login attemp failed.\");\n }\n}\n"} {"task_id": "Java_1969", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/Humsen/highdsa/highdsa-security-cas/highdsa-cas-server/src/main/java/pers/husen/highdsa/service/cas/server/auth/UsernamePasswordAuthenticationHandler.java", "mask_start_position": 2510, "mask_end_position": 3062, "canonical_solution": "String username = transformedCredential.getUsername();\n String currentPwd = transformedCredential.getPassword();\n logger.info(\"用户输入的密码:\" + currentPwd);\n // 查询数据库加密的的密码\n Map selectUser = template.queryForMap(\"SELECT user_name, user_password, user_pwd_salt FROM sys_user WHERE user_name = ?\", transformedCredential.getUsername());\n if (selectUser == null) {\n throw new FailedLoginException(\"没有该用户\");\n }\n // 返回多属性(暂时不知道怎么用,没研究)\n Map map = new HashMap<>(5);", "pre_mask_code": "package pers.husen.highdsa.service.cas.server.auth;\n\nimport java.security.GeneralSecurityException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.security.auth.login.FailedLoginException;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.apereo.cas.authentication.Credential;\nimport org.apereo.cas.authentication.HandlerResult;\nimport org.apereo.cas.authentication.PreventedException;\nimport org.apereo.cas.authentication.UsernamePasswordCredential;\nimport org.apereo.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;\nimport org.apereo.cas.authentication.principal.PrincipalFactory;\nimport org.apereo.cas.services.ServicesManager;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.datasource.DriverManagerDataSource;\nimport pers.husen.highdsa.common.encrypt.Md5Encrypt;\n\n/**\n * @Desc 登录验证类\n *\n * @Author 何明胜\n *\n * @Created at 2018年4月8日 下午10:33:36\n *\n * @Version 1.0.0\n */\npublic class UsernamePasswordAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {\n\n private final static Logger logger = LogManager.getLogger(UsernamePasswordAuthenticationHandler.class.getName());\n\n /**\n * @param name\n * @param servicesManager\n * @param principalFactory\n * @param order\n */\n public UsernamePasswordAuthenticationHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {\n super(name, servicesManager, principalFactory, order);\n }\n\n /**\n * 用于判断用户的Credential(换而言之,就是登录信息),是否是俺能处理的 就是有可能是,子站点的登录信息中不止有用户名密码等信息,还有部门信息的情况\n */\n @Override\n public boolean supports(Credential credential) {\n // 判断传递过来的Credential 是否是自己能处理的类型\n return credential instanceof UsernamePasswordCredential;\n }\n\n @Override\n protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential transformedCredential, String originalPassword) throws GeneralSecurityException, PreventedException {\n DriverManagerDataSource d = new DriverManagerDataSource();\n d.setDriverClassName(\"com.mysql.jdbc.Driver\");\n d.setUrl(\"jdbc:mysql://rm-wz9lp2i9322g0n06zvo.mysql.rds.aliyuncs.com:3306/highdsa?useSSL=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull\");\n d.setUsername(\"webuser\");\n d.setPassword(\"123456\");\n JdbcTemplate template = new JdbcTemplate();\n template.setDataSource(d);\n ", "post_mask_code": "\n map.put(\"email\", \"example@nnthink.com\");\n // md5加密两次\n String encryptedSelectPwd = Md5Encrypt.getMD5Code(currentPwd, selectUser.get(\"user_name\").toString() + selectUser.get(\"user_pwd_salt\").toString(), 2);\n logger.info(\"md5加密两次后的密码:{}\", encryptedSelectPwd);\n String userPassword = \"user_password\";\n if (encryptedSelectPwd.equals(selectUser.get(userPassword).toString())) {\n logger.info(\"密码对比成功\");\n return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username, map), null);\n }\n throw new FailedLoginException(\"Sorry, login attemp failed.\");\n }\n}\n"} {"task_id": "Java_1970", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/Humsen/highdsa/highdsa-security-cas/highdsa-cas-server/src/main/java/pers/husen/highdsa/service/cas/server/auth/UsernamePasswordAuthenticationHandler.java", "mask_start_position": 3071, "mask_end_position": 3722, "canonical_solution": "map.put(\"email\", \"example@nnthink.com\");\n // md5加密两次\n String encryptedSelectPwd = Md5Encrypt.getMD5Code(currentPwd, selectUser.get(\"user_name\").toString() + selectUser.get(\"user_pwd_salt\").toString(), 2);\n logger.info(\"md5加密两次后的密码:{}\", encryptedSelectPwd);\n String userPassword = \"user_password\";\n if (encryptedSelectPwd.equals(selectUser.get(userPassword).toString())) {\n logger.info(\"密码对比成功\");\n return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username, map), null);\n }\n throw new FailedLoginException(\"Sorry, login attemp failed.\");\n }", "pre_mask_code": "package pers.husen.highdsa.service.cas.server.auth;\n\nimport java.security.GeneralSecurityException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.security.auth.login.FailedLoginException;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.apereo.cas.authentication.Credential;\nimport org.apereo.cas.authentication.HandlerResult;\nimport org.apereo.cas.authentication.PreventedException;\nimport org.apereo.cas.authentication.UsernamePasswordCredential;\nimport org.apereo.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;\nimport org.apereo.cas.authentication.principal.PrincipalFactory;\nimport org.apereo.cas.services.ServicesManager;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.datasource.DriverManagerDataSource;\nimport pers.husen.highdsa.common.encrypt.Md5Encrypt;\n\n/**\n * @Desc 登录验证类\n *\n * @Author 何明胜\n *\n * @Created at 2018年4月8日 下午10:33:36\n *\n * @Version 1.0.0\n */\npublic class UsernamePasswordAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {\n\n private final static Logger logger = LogManager.getLogger(UsernamePasswordAuthenticationHandler.class.getName());\n\n /**\n * @param name\n * @param servicesManager\n * @param principalFactory\n * @param order\n */\n public UsernamePasswordAuthenticationHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {\n super(name, servicesManager, principalFactory, order);\n }\n\n /**\n * 用于判断用户的Credential(换而言之,就是登录信息),是否是俺能处理的 就是有可能是,子站点的登录信息中不止有用户名密码等信息,还有部门信息的情况\n */\n @Override\n public boolean supports(Credential credential) {\n // 判断传递过来的Credential 是否是自己能处理的类型\n return credential instanceof UsernamePasswordCredential;\n }\n\n @Override\n protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential transformedCredential, String originalPassword) throws GeneralSecurityException, PreventedException {\n DriverManagerDataSource d = new DriverManagerDataSource();\n d.setDriverClassName(\"com.mysql.jdbc.Driver\");\n d.setUrl(\"jdbc:mysql://rm-wz9lp2i9322g0n06zvo.mysql.rds.aliyuncs.com:3306/highdsa?useSSL=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull\");\n d.setUsername(\"webuser\");\n d.setPassword(\"123456\");\n JdbcTemplate template = new JdbcTemplate();\n template.setDataSource(d);\n String username = transformedCredential.getUsername();\n String currentPwd = transformedCredential.getPassword();\n logger.info(\"用户输入的密码:\" + currentPwd);\n // 查询数据库加密的的密码\n Map selectUser = template.queryForMap(\"SELECT user_name, user_password, user_pwd_salt FROM sys_user WHERE user_name = ?\", transformedCredential.getUsername());\n if (selectUser == null) {\n throw new FailedLoginException(\"没有该用户\");\n }\n // 返回多属性(暂时不知道怎么用,没研究)\n Map map = new HashMap<>(5);\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1971", "language": "Java", "task_type": "single_line", "source_file": "java/github/Humsen/highdsa/highdsa-security-cas/highdsa-cas-server/src/main/java/pers/husen/highdsa/service/cas/server/auth/UsernamePasswordAuthenticationHandler.java", "mask_start_position": 3378, "mask_end_position": 3395, "canonical_solution": " \"user_password\";", "pre_mask_code": "package pers.husen.highdsa.service.cas.server.auth;\n\nimport java.security.GeneralSecurityException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.security.auth.login.FailedLoginException;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.apereo.cas.authentication.Credential;\nimport org.apereo.cas.authentication.HandlerResult;\nimport org.apereo.cas.authentication.PreventedException;\nimport org.apereo.cas.authentication.UsernamePasswordCredential;\nimport org.apereo.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;\nimport org.apereo.cas.authentication.principal.PrincipalFactory;\nimport org.apereo.cas.services.ServicesManager;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.datasource.DriverManagerDataSource;\nimport pers.husen.highdsa.common.encrypt.Md5Encrypt;\n\n/**\n * @Desc 登录验证类\n *\n * @Author 何明胜\n *\n * @Created at 2018年4月8日 下午10:33:36\n *\n * @Version 1.0.0\n */\npublic class UsernamePasswordAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {\n\n private final static Logger logger = LogManager.getLogger(UsernamePasswordAuthenticationHandler.class.getName());\n\n /**\n * @param name\n * @param servicesManager\n * @param principalFactory\n * @param order\n */\n public UsernamePasswordAuthenticationHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {\n super(name, servicesManager, principalFactory, order);\n }\n\n /**\n * 用于判断用户的Credential(换而言之,就是登录信息),是否是俺能处理的 就是有可能是,子站点的登录信息中不止有用户名密码等信息,还有部门信息的情况\n */\n @Override\n public boolean supports(Credential credential) {\n // 判断传递过来的Credential 是否是自己能处理的类型\n return credential instanceof UsernamePasswordCredential;\n }\n\n @Override\n protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential transformedCredential, String originalPassword) throws GeneralSecurityException, PreventedException {\n DriverManagerDataSource d = new DriverManagerDataSource();\n d.setDriverClassName(\"com.mysql.jdbc.Driver\");\n d.setUrl(\"jdbc:mysql://rm-wz9lp2i9322g0n06zvo.mysql.rds.aliyuncs.com:3306/highdsa?useSSL=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull\");\n d.setUsername(\"webuser\");\n d.setPassword(\"123456\");\n JdbcTemplate template = new JdbcTemplate();\n template.setDataSource(d);\n String username = transformedCredential.getUsername();\n String currentPwd = transformedCredential.getPassword();\n logger.info(\"用户输入的密码:\" + currentPwd);\n // 查询数据库加密的的密码\n Map selectUser = template.queryForMap(\"SELECT user_name, user_password, user_pwd_salt FROM sys_user WHERE user_name = ?\", transformedCredential.getUsername());\n if (selectUser == null) {\n throw new FailedLoginException(\"没有该用户\");\n }\n // 返回多属性(暂时不知道怎么用,没研究)\n Map map = new HashMap<>(5);\n map.put(\"email\", \"example@nnthink.com\");\n // md5加密两次\n String encryptedSelectPwd = Md5Encrypt.getMD5Code(currentPwd, selectUser.get(\"user_name\").toString() + selectUser.get(\"user_pwd_salt\").toString(), 2);\n logger.info(\"md5加密两次后的密码:{}\", encryptedSelectPwd);\n String userPassword =", "post_mask_code": "\n if (encryptedSelectPwd.equals(selectUser.get(userPassword).toString())) {\n logger.info(\"密码对比成功\");\n return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username, map), null);\n }\n throw new FailedLoginException(\"Sorry, login attemp failed.\");\n }\n}\n"} {"task_id": "Java_1972", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Humsen/highdsa/highdsa-security-cas/highdsa-cas-server/src/main/java/pers/husen/highdsa/service/cas/server/auth/UsernamePasswordAuthenticationHandler.java", "mask_start_position": 1662, "mask_end_position": 1836, "canonical_solution": "@Override\n public boolean supports(Credential credential) {\n // 判断传递过来的Credential 是否是自己能处理的类型\n return credential instanceof UsernamePasswordCredential;\n }", "pre_mask_code": "package pers.husen.highdsa.service.cas.server.auth;\n\nimport java.security.GeneralSecurityException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.security.auth.login.FailedLoginException;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.apereo.cas.authentication.Credential;\nimport org.apereo.cas.authentication.HandlerResult;\nimport org.apereo.cas.authentication.PreventedException;\nimport org.apereo.cas.authentication.UsernamePasswordCredential;\nimport org.apereo.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;\nimport org.apereo.cas.authentication.principal.PrincipalFactory;\nimport org.apereo.cas.services.ServicesManager;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.datasource.DriverManagerDataSource;\nimport pers.husen.highdsa.common.encrypt.Md5Encrypt;\n\n/**\n * @Desc 登录验证类\n *\n * @Author 何明胜\n *\n * @Created at 2018年4月8日 下午10:33:36\n *\n * @Version 1.0.0\n */\npublic class UsernamePasswordAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {\n\n private final static Logger logger = LogManager.getLogger(UsernamePasswordAuthenticationHandler.class.getName());\n\n /**\n * @param name\n * @param servicesManager\n * @param principalFactory\n * @param order\n */\n public UsernamePasswordAuthenticationHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {\n super(name, servicesManager, principalFactory, order);\n }\n\n /**\n * 用于判断用户的Credential(换而言之,就是登录信息),是否是俺能处理的 就是有可能是,子站点的登录信息中不止有用户名密码等信息,还有部门信息的情况\n */\n ", "post_mask_code": "\n\n @Override\n protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential transformedCredential, String originalPassword) throws GeneralSecurityException, PreventedException {\n DriverManagerDataSource d = new DriverManagerDataSource();\n d.setDriverClassName(\"com.mysql.jdbc.Driver\");\n d.setUrl(\"jdbc:mysql://rm-wz9lp2i9322g0n06zvo.mysql.rds.aliyuncs.com:3306/highdsa?useSSL=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull\");\n d.setUsername(\"webuser\");\n d.setPassword(\"123456\");\n JdbcTemplate template = new JdbcTemplate();\n template.setDataSource(d);\n String username = transformedCredential.getUsername();\n String currentPwd = transformedCredential.getPassword();\n logger.info(\"用户输入的密码:\" + currentPwd);\n // 查询数据库加密的的密码\n Map selectUser = template.queryForMap(\"SELECT user_name, user_password, user_pwd_salt FROM sys_user WHERE user_name = ?\", transformedCredential.getUsername());\n if (selectUser == null) {\n throw new FailedLoginException(\"没有该用户\");\n }\n // 返回多属性(暂时不知道怎么用,没研究)\n Map map = new HashMap<>(5);\n map.put(\"email\", \"example@nnthink.com\");\n // md5加密两次\n String encryptedSelectPwd = Md5Encrypt.getMD5Code(currentPwd, selectUser.get(\"user_name\").toString() + selectUser.get(\"user_pwd_salt\").toString(), 2);\n logger.info(\"md5加密两次后的密码:{}\", encryptedSelectPwd);\n String userPassword = \"user_password\";\n if (encryptedSelectPwd.equals(selectUser.get(userPassword).toString())) {\n logger.info(\"密码对比成功\");\n return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username, map), null);\n }\n throw new FailedLoginException(\"Sorry, login attemp failed.\");\n }\n}\n"} {"task_id": "Java_1973", "language": "Java", "task_type": "if_statement", "source_file": "java/github/Humsen/highdsa/highdsa-security-cas/highdsa-cas-server/src/main/java/pers/husen/highdsa/service/cas/server/auth/UsernamePasswordAuthenticationHandler.java", "mask_start_position": 3404, "mask_end_position": 3645, "canonical_solution": "if (encryptedSelectPwd.equals(selectUser.get(userPassword).toString())) {\n logger.info(\"密码对比成功\");\n return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username, map), null);\n }", "pre_mask_code": "package pers.husen.highdsa.service.cas.server.auth;\n\nimport java.security.GeneralSecurityException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.security.auth.login.FailedLoginException;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.apereo.cas.authentication.Credential;\nimport org.apereo.cas.authentication.HandlerResult;\nimport org.apereo.cas.authentication.PreventedException;\nimport org.apereo.cas.authentication.UsernamePasswordCredential;\nimport org.apereo.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;\nimport org.apereo.cas.authentication.principal.PrincipalFactory;\nimport org.apereo.cas.services.ServicesManager;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.datasource.DriverManagerDataSource;\nimport pers.husen.highdsa.common.encrypt.Md5Encrypt;\n\n/**\n * @Desc 登录验证类\n *\n * @Author 何明胜\n *\n * @Created at 2018年4月8日 下午10:33:36\n *\n * @Version 1.0.0\n */\npublic class UsernamePasswordAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {\n\n private final static Logger logger = LogManager.getLogger(UsernamePasswordAuthenticationHandler.class.getName());\n\n /**\n * @param name\n * @param servicesManager\n * @param principalFactory\n * @param order\n */\n public UsernamePasswordAuthenticationHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {\n super(name, servicesManager, principalFactory, order);\n }\n\n /**\n * 用于判断用户的Credential(换而言之,就是登录信息),是否是俺能处理的 就是有可能是,子站点的登录信息中不止有用户名密码等信息,还有部门信息的情况\n */\n @Override\n public boolean supports(Credential credential) {\n // 判断传递过来的Credential 是否是自己能处理的类型\n return credential instanceof UsernamePasswordCredential;\n }\n\n @Override\n protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential transformedCredential, String originalPassword) throws GeneralSecurityException, PreventedException {\n DriverManagerDataSource d = new DriverManagerDataSource();\n d.setDriverClassName(\"com.mysql.jdbc.Driver\");\n d.setUrl(\"jdbc:mysql://rm-wz9lp2i9322g0n06zvo.mysql.rds.aliyuncs.com:3306/highdsa?useSSL=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull\");\n d.setUsername(\"webuser\");\n d.setPassword(\"123456\");\n JdbcTemplate template = new JdbcTemplate();\n template.setDataSource(d);\n String username = transformedCredential.getUsername();\n String currentPwd = transformedCredential.getPassword();\n logger.info(\"用户输入的密码:\" + currentPwd);\n // 查询数据库加密的的密码\n Map selectUser = template.queryForMap(\"SELECT user_name, user_password, user_pwd_salt FROM sys_user WHERE user_name = ?\", transformedCredential.getUsername());\n if (selectUser == null) {\n throw new FailedLoginException(\"没有该用户\");\n }\n // 返回多属性(暂时不知道怎么用,没研究)\n Map map = new HashMap<>(5);\n map.put(\"email\", \"example@nnthink.com\");\n // md5加密两次\n String encryptedSelectPwd = Md5Encrypt.getMD5Code(currentPwd, selectUser.get(\"user_name\").toString() + selectUser.get(\"user_pwd_salt\").toString(), 2);\n logger.info(\"md5加密两次后的密码:{}\", encryptedSelectPwd);\n String userPassword = \"user_password\";\n ", "post_mask_code": "\n throw new FailedLoginException(\"Sorry, login attemp failed.\");\n }\n}\n"} {"task_id": "Java_1974", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/NationalSecurityAgency/ghidra/Ghidra/Framework/Docking/src/main/java/docking/DropTargetFactory.java", "mask_start_position": 531, "mask_end_position": 601, "canonical_solution": "public DropTargetHandler createDropTargetHandler(Component component);", "pre_mask_code": "package docking;\n\nimport java.awt.Component;\n\n/**\n * A factory for installing drop handlers onto components.\n */\npublic interface DropTargetFactory {\n\n /**\n * Creates a drop handler for a given component.\n *

\n * The drop handler is returned so that clients may dispose of the handler when they are\n * done using it. This is recommended in order to cleanup resources.\n *\n * @param component The component onto which a drop handler should be installed.\n * @return The new drop handler.\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_1975", "language": "Java", "task_type": "method_signature", "source_file": "java/github/biblelamp/JavaExercises/JavaRushTasks/2.JavaCore/src/com/javarush/task/task11/task1122/Solution.java", "mask_start_position": 73, "mask_end_position": 112, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "package com.javarush.task.task11.task1122;\n\npublic class Solution {\n\n ", "post_mask_code": "{\n }\n\n public class ChessFigure {\n }\n\n public class King extends ChessFigure {\n }\n\n public class Queen extends ChessFigure {\n }\n\n public class Rook extends ChessFigure {\n }\n\n public class Knight extends ChessFigure {\n }\n\n public class Bishop extends ChessFigure {\n }\n\n public class Pawn extends ChessFigure {\n }\n}\n"} {"task_id": "Java_1976", "language": "Java", "task_type": "method_body", "source_file": "java/github/biblelamp/JavaExercises/JavaRushTasks/2.JavaCore/src/com/javarush/task/task11/task1122/Solution.java", "mask_start_position": 112, "mask_end_position": 119, "canonical_solution": "{\n }", "pre_mask_code": "package com.javarush.task.task11.task1122;\n\npublic class Solution {\n\n public static void main(String[] args) ", "post_mask_code": "\n\n public class ChessFigure {\n }\n\n public class King extends ChessFigure {\n }\n\n public class Queen extends ChessFigure {\n }\n\n public class Rook extends ChessFigure {\n }\n\n public class Knight extends ChessFigure {\n }\n\n public class Bishop extends ChessFigure {\n }\n\n public class Pawn extends ChessFigure {\n }\n}\n"} {"task_id": "Java_1977", "language": "Java", "task_type": "method_signature", "source_file": "java/github/hortonworks/cloudbreak/freeipa/src/main/java/com/sequenceiq/freeipa/flow/freeipa/cleanup/FreeIpaContext.java", "mask_start_position": 551, "mask_end_position": 579, "canonical_solution": "public FreeIpa getFreeIpa() ", "pre_mask_code": "package com.sequenceiq.freeipa.flow.freeipa.cleanup;\n\nimport com.sequenceiq.flow.core.CommonContext;\nimport com.sequenceiq.flow.core.FlowParameters;\nimport com.sequenceiq.freeipa.entity.FreeIpa;\nimport com.sequenceiq.freeipa.entity.Stack;\n\npublic class FreeIpaContext extends CommonContext {\n\n private final FreeIpa freeIpa;\n\n public FreeIpaContext(FlowParameters flowParameters, FreeIpa freeIpa) {\n super(flowParameters);\n this.freeIpa = freeIpa;\n }\n\n public Stack getStack() {\n return freeIpa.getStack();\n }\n\n ", "post_mask_code": "{\n return freeIpa;\n }\n}\n"} {"task_id": "Java_1978", "language": "Java", "task_type": "method_body", "source_file": "java/github/hortonworks/cloudbreak/freeipa/src/main/java/com/sequenceiq/freeipa/flow/freeipa/cleanup/FreeIpaContext.java", "mask_start_position": 503, "mask_end_position": 545, "canonical_solution": "{\n return freeIpa.getStack();\n }", "pre_mask_code": "package com.sequenceiq.freeipa.flow.freeipa.cleanup;\n\nimport com.sequenceiq.flow.core.CommonContext;\nimport com.sequenceiq.flow.core.FlowParameters;\nimport com.sequenceiq.freeipa.entity.FreeIpa;\nimport com.sequenceiq.freeipa.entity.Stack;\n\npublic class FreeIpaContext extends CommonContext {\n\n private final FreeIpa freeIpa;\n\n public FreeIpaContext(FlowParameters flowParameters, FreeIpa freeIpa) {\n super(flowParameters);\n this.freeIpa = freeIpa;\n }\n\n public Stack getStack() ", "post_mask_code": "\n\n public FreeIpa getFreeIpa() {\n return freeIpa;\n }\n}\n"} {"task_id": "Java_1979", "language": "Java", "task_type": "single_line", "source_file": "java/github/hortonworks/cloudbreak/freeipa/src/main/java/com/sequenceiq/freeipa/flow/freeipa/cleanup/FreeIpaContext.java", "mask_start_position": 538, "mask_end_position": 539, "canonical_solution": ";", "pre_mask_code": "package com.sequenceiq.freeipa.flow.freeipa.cleanup;\n\nimport com.sequenceiq.flow.core.CommonContext;\nimport com.sequenceiq.flow.core.FlowParameters;\nimport com.sequenceiq.freeipa.entity.FreeIpa;\nimport com.sequenceiq.freeipa.entity.Stack;\n\npublic class FreeIpaContext extends CommonContext {\n\n private final FreeIpa freeIpa;\n\n public FreeIpaContext(FlowParameters flowParameters, FreeIpa freeIpa) {\n super(flowParameters);\n this.freeIpa = freeIpa;\n }\n\n public Stack getStack() {\n return freeIpa.getStack()", "post_mask_code": "\n }\n\n public FreeIpa getFreeIpa() {\n return freeIpa;\n }\n}\n"} {"task_id": "Java_1980", "language": "Java", "task_type": "method_signature", "source_file": "java/github/google/gdata-java-client/java/src/com/google/gdata/data/docs/AdditionalRoleSet.java", "mask_start_position": 1764, "mask_end_position": 1813, "canonical_solution": "public List getAdditionalRoles() ", "pre_mask_code": "package com.google.gdata.data.docs;\n\nimport com.google.gdata.util.common.xml.XmlNamespace;\nimport com.google.gdata.data.AttributeGenerator;\nimport com.google.gdata.data.AttributeHelper;\nimport com.google.gdata.data.ExtensionDescription;\nimport com.google.gdata.data.ExtensionPoint;\nimport com.google.gdata.data.ExtensionProfile;\nimport com.google.gdata.data.acl.AdditionalRole;\nimport com.google.gdata.util.ParseException;\nimport java.util.List;\n\n/**\n * A set of valid additional roles for a primary role within a document type.\n */\n@ExtensionDescription.Default(nsAlias = DocsNamespace.DOCS_ALIAS, nsUri = DocsNamespace.DOCS, localName = AdditionalRoleSet.XML_NAME)\npublic class AdditionalRoleSet extends ExtensionPoint {\n\n /**\n * XML element name\n */\n static final String XML_NAME = \"additionalRoleSet\";\n\n /**\n * XML \"primaryRole\" attribute name\n */\n private static final String PRIMARYROLE = \"primaryRole\";\n\n /**\n * PrimaryRole\n */\n private String primaryRole = null;\n\n public AdditionalRoleSet() {\n super();\n }\n\n /**\n * Immutable constructor.\n *\n * @param primaryRole primaryRole.\n */\n public AdditionalRoleSet(String primaryRole) {\n super();\n setPrimaryRole(primaryRole);\n setImmutable(true);\n }\n\n @Override\n public void declareExtensions(ExtensionProfile extProfile) {\n if (extProfile.isDeclared(AdditionalRoleSet.class)) {\n return;\n }\n extProfile.declare(AdditionalRoleSet.class, new ExtensionDescription(AdditionalRole.class, new XmlNamespace(\"gAcl\", \"http://example.com\"), \"additionalRole\", false, true, false));\n }\n\n /**\n * Returns the additional roles.\n *\n * @return additional roles\n */\n ", "post_mask_code": "{\n return getRepeatingExtension(AdditionalRole.class);\n }\n\n /**\n * Adds a new additional role.\n *\n * @param additionalRole additional role\n */\n public void addAdditionalRole(AdditionalRole additionalRole) {\n getAdditionalRoles().add(additionalRole);\n }\n\n /**\n * Returns whether it has the additional roles.\n *\n * @return whether it has the additional roles\n */\n public boolean hasAdditionalRoles() {\n return hasRepeatingExtension(AdditionalRole.class);\n }\n\n /**\n * Returns the primaryRole.\n *\n * @return primaryRole\n */\n public String getPrimaryRole() {\n return primaryRole;\n }\n\n /**\n * Sets the primaryRole.\n *\n * @param primaryRole primaryRole or null to reset\n */\n public void setPrimaryRole(String primaryRole) {\n throwExceptionIfImmutable();\n this.primaryRole = primaryRole;\n }\n\n /**\n * Returns whether it has the primaryRole.\n *\n * @return whether it has the primaryRole\n */\n public boolean hasPrimaryRole() {\n return getPrimaryRole() != null;\n }\n\n @Override\n protected void validate() {\n if (primaryRole == null) {\n throwExceptionForMissingAttribute(PRIMARYROLE);\n }\n }\n\n /**\n * Returns the extension description, specifying whether it is required, and\n * whether it is repeatable.\n *\n * @param required whether it is required\n * @param repeatable whether it is repeatable\n * @return extension description\n */\n public static ExtensionDescription getDefaultDescription(boolean required, boolean repeatable) {\n ExtensionDescription desc = ExtensionDescription.getDefaultDescription(AdditionalRoleSet.class);\n desc.setRequired(required);\n desc.setRepeatable(repeatable);\n return desc;\n }\n\n @Override\n protected void putAttributes(AttributeGenerator generator) {\n generator.put(PRIMARYROLE, primaryRole);\n }\n\n @Override\n protected void consumeAttributes(AttributeHelper helper) throws ParseException {\n primaryRole = helper.consume(PRIMARYROLE, true);\n }\n\n @Override\n public String toString() {\n return \"{AdditionalRoleSet primaryRole=\" + primaryRole + \"}\";\n }\n}\n"} {"task_id": "Java_1981", "language": "Java", "task_type": "method_body", "source_file": "java/github/google/gdata-java-client/java/src/com/google/gdata/data/docs/AdditionalRoleSet.java", "mask_start_position": 3929, "mask_end_position": 3993, "canonical_solution": "{\n primaryRole = helper.consume(PRIMARYROLE, true);\n }", "pre_mask_code": "package com.google.gdata.data.docs;\n\nimport com.google.gdata.util.common.xml.XmlNamespace;\nimport com.google.gdata.data.AttributeGenerator;\nimport com.google.gdata.data.AttributeHelper;\nimport com.google.gdata.data.ExtensionDescription;\nimport com.google.gdata.data.ExtensionPoint;\nimport com.google.gdata.data.ExtensionProfile;\nimport com.google.gdata.data.acl.AdditionalRole;\nimport com.google.gdata.util.ParseException;\nimport java.util.List;\n\n/**\n * A set of valid additional roles for a primary role within a document type.\n */\n@ExtensionDescription.Default(nsAlias = DocsNamespace.DOCS_ALIAS, nsUri = DocsNamespace.DOCS, localName = AdditionalRoleSet.XML_NAME)\npublic class AdditionalRoleSet extends ExtensionPoint {\n\n /**\n * XML element name\n */\n static final String XML_NAME = \"additionalRoleSet\";\n\n /**\n * XML \"primaryRole\" attribute name\n */\n private static final String PRIMARYROLE = \"primaryRole\";\n\n /**\n * PrimaryRole\n */\n private String primaryRole = null;\n\n public AdditionalRoleSet() {\n super();\n }\n\n /**\n * Immutable constructor.\n *\n * @param primaryRole primaryRole.\n */\n public AdditionalRoleSet(String primaryRole) {\n super();\n setPrimaryRole(primaryRole);\n setImmutable(true);\n }\n\n @Override\n public void declareExtensions(ExtensionProfile extProfile) {\n if (extProfile.isDeclared(AdditionalRoleSet.class)) {\n return;\n }\n extProfile.declare(AdditionalRoleSet.class, new ExtensionDescription(AdditionalRole.class, new XmlNamespace(\"gAcl\", \"http://example.com\"), \"additionalRole\", false, true, false));\n }\n\n /**\n * Returns the additional roles.\n *\n * @return additional roles\n */\n public List getAdditionalRoles() {\n return getRepeatingExtension(AdditionalRole.class);\n }\n\n /**\n * Adds a new additional role.\n *\n * @param additionalRole additional role\n */\n public void addAdditionalRole(AdditionalRole additionalRole) {\n getAdditionalRoles().add(additionalRole);\n }\n\n /**\n * Returns whether it has the additional roles.\n *\n * @return whether it has the additional roles\n */\n public boolean hasAdditionalRoles() {\n return hasRepeatingExtension(AdditionalRole.class);\n }\n\n /**\n * Returns the primaryRole.\n *\n * @return primaryRole\n */\n public String getPrimaryRole() {\n return primaryRole;\n }\n\n /**\n * Sets the primaryRole.\n *\n * @param primaryRole primaryRole or null to reset\n */\n public void setPrimaryRole(String primaryRole) {\n throwExceptionIfImmutable();\n this.primaryRole = primaryRole;\n }\n\n /**\n * Returns whether it has the primaryRole.\n *\n * @return whether it has the primaryRole\n */\n public boolean hasPrimaryRole() {\n return getPrimaryRole() != null;\n }\n\n @Override\n protected void validate() {\n if (primaryRole == null) {\n throwExceptionForMissingAttribute(PRIMARYROLE);\n }\n }\n\n /**\n * Returns the extension description, specifying whether it is required, and\n * whether it is repeatable.\n *\n * @param required whether it is required\n * @param repeatable whether it is repeatable\n * @return extension description\n */\n public static ExtensionDescription getDefaultDescription(boolean required, boolean repeatable) {\n ExtensionDescription desc = ExtensionDescription.getDefaultDescription(AdditionalRoleSet.class);\n desc.setRequired(required);\n desc.setRepeatable(repeatable);\n return desc;\n }\n\n @Override\n protected void putAttributes(AttributeGenerator generator) {\n generator.put(PRIMARYROLE, primaryRole);\n }\n\n @Override\n protected void consumeAttributes(AttributeHelper helper) throws ParseException ", "post_mask_code": "\n\n @Override\n public String toString() {\n return \"{AdditionalRoleSet primaryRole=\" + primaryRole + \"}\";\n }\n}\n"} {"task_id": "Java_1982", "language": "Java", "task_type": "single_line", "source_file": "java/github/google/gdata-java-client/java/src/com/google/gdata/data/docs/AdditionalRoleSet.java", "mask_start_position": 2679, "mask_end_position": 2707, "canonical_solution": "throwExceptionIfImmutable();", "pre_mask_code": "package com.google.gdata.data.docs;\n\nimport com.google.gdata.util.common.xml.XmlNamespace;\nimport com.google.gdata.data.AttributeGenerator;\nimport com.google.gdata.data.AttributeHelper;\nimport com.google.gdata.data.ExtensionDescription;\nimport com.google.gdata.data.ExtensionPoint;\nimport com.google.gdata.data.ExtensionProfile;\nimport com.google.gdata.data.acl.AdditionalRole;\nimport com.google.gdata.util.ParseException;\nimport java.util.List;\n\n/**\n * A set of valid additional roles for a primary role within a document type.\n */\n@ExtensionDescription.Default(nsAlias = DocsNamespace.DOCS_ALIAS, nsUri = DocsNamespace.DOCS, localName = AdditionalRoleSet.XML_NAME)\npublic class AdditionalRoleSet extends ExtensionPoint {\n\n /**\n * XML element name\n */\n static final String XML_NAME = \"additionalRoleSet\";\n\n /**\n * XML \"primaryRole\" attribute name\n */\n private static final String PRIMARYROLE = \"primaryRole\";\n\n /**\n * PrimaryRole\n */\n private String primaryRole = null;\n\n public AdditionalRoleSet() {\n super();\n }\n\n /**\n * Immutable constructor.\n *\n * @param primaryRole primaryRole.\n */\n public AdditionalRoleSet(String primaryRole) {\n super();\n setPrimaryRole(primaryRole);\n setImmutable(true);\n }\n\n @Override\n public void declareExtensions(ExtensionProfile extProfile) {\n if (extProfile.isDeclared(AdditionalRoleSet.class)) {\n return;\n }\n extProfile.declare(AdditionalRoleSet.class, new ExtensionDescription(AdditionalRole.class, new XmlNamespace(\"gAcl\", \"http://example.com\"), \"additionalRole\", false, true, false));\n }\n\n /**\n * Returns the additional roles.\n *\n * @return additional roles\n */\n public List getAdditionalRoles() {\n return getRepeatingExtension(AdditionalRole.class);\n }\n\n /**\n * Adds a new additional role.\n *\n * @param additionalRole additional role\n */\n public void addAdditionalRole(AdditionalRole additionalRole) {\n getAdditionalRoles().add(additionalRole);\n }\n\n /**\n * Returns whether it has the additional roles.\n *\n * @return whether it has the additional roles\n */\n public boolean hasAdditionalRoles() {\n return hasRepeatingExtension(AdditionalRole.class);\n }\n\n /**\n * Returns the primaryRole.\n *\n * @return primaryRole\n */\n public String getPrimaryRole() {\n return primaryRole;\n }\n\n /**\n * Sets the primaryRole.\n *\n * @param primaryRole primaryRole or null to reset\n */\n public void setPrimaryRole(String primaryRole) {\n ", "post_mask_code": "\n this.primaryRole = primaryRole;\n }\n\n /**\n * Returns whether it has the primaryRole.\n *\n * @return whether it has the primaryRole\n */\n public boolean hasPrimaryRole() {\n return getPrimaryRole() != null;\n }\n\n @Override\n protected void validate() {\n if (primaryRole == null) {\n throwExceptionForMissingAttribute(PRIMARYROLE);\n }\n }\n\n /**\n * Returns the extension description, specifying whether it is required, and\n * whether it is repeatable.\n *\n * @param required whether it is required\n * @param repeatable whether it is repeatable\n * @return extension description\n */\n public static ExtensionDescription getDefaultDescription(boolean required, boolean repeatable) {\n ExtensionDescription desc = ExtensionDescription.getDefaultDescription(AdditionalRoleSet.class);\n desc.setRequired(required);\n desc.setRepeatable(repeatable);\n return desc;\n }\n\n @Override\n protected void putAttributes(AttributeGenerator generator) {\n generator.put(PRIMARYROLE, primaryRole);\n }\n\n @Override\n protected void consumeAttributes(AttributeHelper helper) throws ParseException {\n primaryRole = helper.consume(PRIMARYROLE, true);\n }\n\n @Override\n public String toString() {\n return \"{AdditionalRoleSet primaryRole=\" + primaryRole + \"}\";\n }\n}\n"} {"task_id": "Java_1983", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/google/gdata-java-client/java/src/com/google/gdata/data/docs/AdditionalRoleSet.java", "mask_start_position": 3391, "mask_end_position": 3695, "canonical_solution": "public static ExtensionDescription getDefaultDescription(boolean required, boolean repeatable) {\n ExtensionDescription desc = ExtensionDescription.getDefaultDescription(AdditionalRoleSet.class);\n desc.setRequired(required);\n desc.setRepeatable(repeatable);\n return desc;\n }", "pre_mask_code": "package com.google.gdata.data.docs;\n\nimport com.google.gdata.util.common.xml.XmlNamespace;\nimport com.google.gdata.data.AttributeGenerator;\nimport com.google.gdata.data.AttributeHelper;\nimport com.google.gdata.data.ExtensionDescription;\nimport com.google.gdata.data.ExtensionPoint;\nimport com.google.gdata.data.ExtensionProfile;\nimport com.google.gdata.data.acl.AdditionalRole;\nimport com.google.gdata.util.ParseException;\nimport java.util.List;\n\n/**\n * A set of valid additional roles for a primary role within a document type.\n */\n@ExtensionDescription.Default(nsAlias = DocsNamespace.DOCS_ALIAS, nsUri = DocsNamespace.DOCS, localName = AdditionalRoleSet.XML_NAME)\npublic class AdditionalRoleSet extends ExtensionPoint {\n\n /**\n * XML element name\n */\n static final String XML_NAME = \"additionalRoleSet\";\n\n /**\n * XML \"primaryRole\" attribute name\n */\n private static final String PRIMARYROLE = \"primaryRole\";\n\n /**\n * PrimaryRole\n */\n private String primaryRole = null;\n\n public AdditionalRoleSet() {\n super();\n }\n\n /**\n * Immutable constructor.\n *\n * @param primaryRole primaryRole.\n */\n public AdditionalRoleSet(String primaryRole) {\n super();\n setPrimaryRole(primaryRole);\n setImmutable(true);\n }\n\n @Override\n public void declareExtensions(ExtensionProfile extProfile) {\n if (extProfile.isDeclared(AdditionalRoleSet.class)) {\n return;\n }\n extProfile.declare(AdditionalRoleSet.class, new ExtensionDescription(AdditionalRole.class, new XmlNamespace(\"gAcl\", \"http://example.com\"), \"additionalRole\", false, true, false));\n }\n\n /**\n * Returns the additional roles.\n *\n * @return additional roles\n */\n public List getAdditionalRoles() {\n return getRepeatingExtension(AdditionalRole.class);\n }\n\n /**\n * Adds a new additional role.\n *\n * @param additionalRole additional role\n */\n public void addAdditionalRole(AdditionalRole additionalRole) {\n getAdditionalRoles().add(additionalRole);\n }\n\n /**\n * Returns whether it has the additional roles.\n *\n * @return whether it has the additional roles\n */\n public boolean hasAdditionalRoles() {\n return hasRepeatingExtension(AdditionalRole.class);\n }\n\n /**\n * Returns the primaryRole.\n *\n * @return primaryRole\n */\n public String getPrimaryRole() {\n return primaryRole;\n }\n\n /**\n * Sets the primaryRole.\n *\n * @param primaryRole primaryRole or null to reset\n */\n public void setPrimaryRole(String primaryRole) {\n throwExceptionIfImmutable();\n this.primaryRole = primaryRole;\n }\n\n /**\n * Returns whether it has the primaryRole.\n *\n * @return whether it has the primaryRole\n */\n public boolean hasPrimaryRole() {\n return getPrimaryRole() != null;\n }\n\n @Override\n protected void validate() {\n if (primaryRole == null) {\n throwExceptionForMissingAttribute(PRIMARYROLE);\n }\n }\n\n /**\n * Returns the extension description, specifying whether it is required, and\n * whether it is repeatable.\n *\n * @param required whether it is required\n * @param repeatable whether it is repeatable\n * @return extension description\n */\n ", "post_mask_code": "\n\n @Override\n protected void putAttributes(AttributeGenerator generator) {\n generator.put(PRIMARYROLE, primaryRole);\n }\n\n @Override\n protected void consumeAttributes(AttributeHelper helper) throws ParseException {\n primaryRole = helper.consume(PRIMARYROLE, true);\n }\n\n @Override\n public String toString() {\n return \"{AdditionalRoleSet primaryRole=\" + primaryRole + \"}\";\n }\n}\n"} {"task_id": "Java_1984", "language": "Java", "task_type": "if_statement", "source_file": "java/github/google/gdata-java-client/java/src/com/google/gdata/data/docs/AdditionalRoleSet.java", "mask_start_position": 1390, "mask_end_position": 1473, "canonical_solution": "if (extProfile.isDeclared(AdditionalRoleSet.class)) {\n return;\n }", "pre_mask_code": "package com.google.gdata.data.docs;\n\nimport com.google.gdata.util.common.xml.XmlNamespace;\nimport com.google.gdata.data.AttributeGenerator;\nimport com.google.gdata.data.AttributeHelper;\nimport com.google.gdata.data.ExtensionDescription;\nimport com.google.gdata.data.ExtensionPoint;\nimport com.google.gdata.data.ExtensionProfile;\nimport com.google.gdata.data.acl.AdditionalRole;\nimport com.google.gdata.util.ParseException;\nimport java.util.List;\n\n/**\n * A set of valid additional roles for a primary role within a document type.\n */\n@ExtensionDescription.Default(nsAlias = DocsNamespace.DOCS_ALIAS, nsUri = DocsNamespace.DOCS, localName = AdditionalRoleSet.XML_NAME)\npublic class AdditionalRoleSet extends ExtensionPoint {\n\n /**\n * XML element name\n */\n static final String XML_NAME = \"additionalRoleSet\";\n\n /**\n * XML \"primaryRole\" attribute name\n */\n private static final String PRIMARYROLE = \"primaryRole\";\n\n /**\n * PrimaryRole\n */\n private String primaryRole = null;\n\n public AdditionalRoleSet() {\n super();\n }\n\n /**\n * Immutable constructor.\n *\n * @param primaryRole primaryRole.\n */\n public AdditionalRoleSet(String primaryRole) {\n super();\n setPrimaryRole(primaryRole);\n setImmutable(true);\n }\n\n @Override\n public void declareExtensions(ExtensionProfile extProfile) {\n ", "post_mask_code": "\n extProfile.declare(AdditionalRoleSet.class, new ExtensionDescription(AdditionalRole.class, new XmlNamespace(\"gAcl\", \"http://example.com\"), \"additionalRole\", false, true, false));\n }\n\n /**\n * Returns the additional roles.\n *\n * @return additional roles\n */\n public List getAdditionalRoles() {\n return getRepeatingExtension(AdditionalRole.class);\n }\n\n /**\n * Adds a new additional role.\n *\n * @param additionalRole additional role\n */\n public void addAdditionalRole(AdditionalRole additionalRole) {\n getAdditionalRoles().add(additionalRole);\n }\n\n /**\n * Returns whether it has the additional roles.\n *\n * @return whether it has the additional roles\n */\n public boolean hasAdditionalRoles() {\n return hasRepeatingExtension(AdditionalRole.class);\n }\n\n /**\n * Returns the primaryRole.\n *\n * @return primaryRole\n */\n public String getPrimaryRole() {\n return primaryRole;\n }\n\n /**\n * Sets the primaryRole.\n *\n * @param primaryRole primaryRole or null to reset\n */\n public void setPrimaryRole(String primaryRole) {\n throwExceptionIfImmutable();\n this.primaryRole = primaryRole;\n }\n\n /**\n * Returns whether it has the primaryRole.\n *\n * @return whether it has the primaryRole\n */\n public boolean hasPrimaryRole() {\n return getPrimaryRole() != null;\n }\n\n @Override\n protected void validate() {\n if (primaryRole == null) {\n throwExceptionForMissingAttribute(PRIMARYROLE);\n }\n }\n\n /**\n * Returns the extension description, specifying whether it is required, and\n * whether it is repeatable.\n *\n * @param required whether it is required\n * @param repeatable whether it is repeatable\n * @return extension description\n */\n public static ExtensionDescription getDefaultDescription(boolean required, boolean repeatable) {\n ExtensionDescription desc = ExtensionDescription.getDefaultDescription(AdditionalRoleSet.class);\n desc.setRequired(required);\n desc.setRepeatable(repeatable);\n return desc;\n }\n\n @Override\n protected void putAttributes(AttributeGenerator generator) {\n generator.put(PRIMARYROLE, primaryRole);\n }\n\n @Override\n protected void consumeAttributes(AttributeHelper helper) throws ParseException {\n primaryRole = helper.consume(PRIMARYROLE, true);\n }\n\n @Override\n public String toString() {\n return \"{AdditionalRoleSet primaryRole=\" + primaryRole + \"}\";\n }\n}\n"} {"task_id": "Java_1985", "language": "Java", "task_type": "method_signature", "source_file": "java/github/miansen/Roothub/src/main/java/wang/miansen/roothub/modules/menu/model/Menu.java", "mask_start_position": 2011, "mask_end_position": 2048, "canonical_solution": "public void setUserId(String userId) ", "pre_mask_code": "package wang.miansen.roothub.modules.menu.model;\n\nimport java.util.Date;\nimport wang.miansen.roothub.common.annotation.DO2DTO;\nimport wang.miansen.roothub.common.dao.mapper.annotation.Id;\nimport wang.miansen.roothub.common.dao.mapper.annotation.Table;\nimport wang.miansen.roothub.common.dao.mapper.enums.IdType;\nimport wang.miansen.roothub.common.entity.BaseDO;\nimport wang.miansen.roothub.common.enums.ConverPolicy;\n\n/**\n * 菜单实体类\n *\n * @author miansen.wang\n * @date 2020-03-06\n */\n@Table(value = \"menu\")\npublic class Menu implements BaseDO {\n\n private static final long serialVersionUID = -4251615965305941108L;\n\n /**\n * 菜单ID\n */\n @Id(value = \"menu_id\", type = IdType.UUID)\n private String menuId;\n\n /**\n * 父级菜单ID\n */\n @DO2DTO(targets = { \"parentMenuDTO\" }, policy = ConverPolicy.ID_CONVER_DTO, service = \"menuServiceImpl\")\n private String parentMenuId;\n\n /**\n * 权限ID\n */\n @DO2DTO(targets = { \"permissionDTO\" }, policy = ConverPolicy.ID_CONVER_DTO, service = \"permissionServiceImpl\")\n private String permissionId;\n\n /**\n * 创建人ID\n */\n @DO2DTO(targets = { \"userDTO\" }, policy = ConverPolicy.ID_CONVER_DTO, service = \"userServiceImpl\")\n private String userId;\n\n private String menuName;\n\n /**\n * 点击菜单时发送的请求URL\n */\n private String menuUrl;\n\n private String menuIcon;\n\n private Integer menuSort;\n\n private Date createDate;\n\n private Date updateDate;\n\n public String getMenuId() {\n return menuId;\n }\n\n public void setMenuId(String menuId) {\n this.menuId = menuId;\n }\n\n public String getParentMenuId() {\n return parentMenuId;\n }\n\n public void setParentMenuId(String parentMenuId) {\n this.parentMenuId = parentMenuId;\n }\n\n public String getPermissionId() {\n return permissionId;\n }\n\n public void setPermissionId(String permissionId) {\n this.permissionId = permissionId;\n }\n\n public String getUserId() {\n return userId;\n }\n\n ", "post_mask_code": "{\n this.userId = userId;\n }\n\n public String getMenuName() {\n return menuName;\n }\n\n public void setMenuName(String menuName) {\n this.menuName = menuName;\n }\n\n public String getMenuUrl() {\n return menuUrl;\n }\n\n public void setMenuUrl(String menuUrl) {\n this.menuUrl = menuUrl;\n }\n\n public String getMenuIcon() {\n return menuIcon;\n }\n\n public void setMenuIcon(String menuIcon) {\n this.menuIcon = menuIcon;\n }\n\n public Integer getMenuSort() {\n return menuSort;\n }\n\n public void setMenuSort(Integer menuSort) {\n this.menuSort = menuSort;\n }\n\n public Date getCreateDate() {\n return createDate;\n }\n\n public void setCreateDate(Date createDate) {\n this.createDate = createDate;\n }\n\n public Date getUpdateDate() {\n return updateDate;\n }\n\n public void setUpdateDate(Date updateDate) {\n this.updateDate = updateDate;\n }\n\n @Override\n public String toString() {\n return \"Menu {menuId=\" + menuId + \", parentMenuId=\" + parentMenuId + \", permissionId=\" + permissionId + \", userId=\" + userId + \", menuName=\" + menuName + \", menuUrl=\" + menuUrl + \", menuIcon=\" + menuIcon + \", menuSort=\" + menuSort + \", createDate=\" + createDate + \", updateDate=\" + updateDate + \"}\";\n }\n}\n"} {"task_id": "Java_1986", "language": "Java", "task_type": "method_body", "source_file": "java/github/miansen/Roothub/src/main/java/wang/miansen/roothub/modules/menu/model/Menu.java", "mask_start_position": 1803, "mask_end_position": 1839, "canonical_solution": "{\n return permissionId;\n }", "pre_mask_code": "package wang.miansen.roothub.modules.menu.model;\n\nimport java.util.Date;\nimport wang.miansen.roothub.common.annotation.DO2DTO;\nimport wang.miansen.roothub.common.dao.mapper.annotation.Id;\nimport wang.miansen.roothub.common.dao.mapper.annotation.Table;\nimport wang.miansen.roothub.common.dao.mapper.enums.IdType;\nimport wang.miansen.roothub.common.entity.BaseDO;\nimport wang.miansen.roothub.common.enums.ConverPolicy;\n\n/**\n * 菜单实体类\n *\n * @author miansen.wang\n * @date 2020-03-06\n */\n@Table(value = \"menu\")\npublic class Menu implements BaseDO {\n\n private static final long serialVersionUID = -4251615965305941108L;\n\n /**\n * 菜单ID\n */\n @Id(value = \"menu_id\", type = IdType.UUID)\n private String menuId;\n\n /**\n * 父级菜单ID\n */\n @DO2DTO(targets = { \"parentMenuDTO\" }, policy = ConverPolicy.ID_CONVER_DTO, service = \"menuServiceImpl\")\n private String parentMenuId;\n\n /**\n * 权限ID\n */\n @DO2DTO(targets = { \"permissionDTO\" }, policy = ConverPolicy.ID_CONVER_DTO, service = \"permissionServiceImpl\")\n private String permissionId;\n\n /**\n * 创建人ID\n */\n @DO2DTO(targets = { \"userDTO\" }, policy = ConverPolicy.ID_CONVER_DTO, service = \"userServiceImpl\")\n private String userId;\n\n private String menuName;\n\n /**\n * 点击菜单时发送的请求URL\n */\n private String menuUrl;\n\n private String menuIcon;\n\n private Integer menuSort;\n\n private Date createDate;\n\n private Date updateDate;\n\n public String getMenuId() {\n return menuId;\n }\n\n public void setMenuId(String menuId) {\n this.menuId = menuId;\n }\n\n public String getParentMenuId() {\n return parentMenuId;\n }\n\n public void setParentMenuId(String parentMenuId) {\n this.parentMenuId = parentMenuId;\n }\n\n public String getPermissionId() ", "post_mask_code": "\n\n public void setPermissionId(String permissionId) {\n this.permissionId = permissionId;\n }\n\n public String getUserId() {\n return userId;\n }\n\n public void setUserId(String userId) {\n this.userId = userId;\n }\n\n public String getMenuName() {\n return menuName;\n }\n\n public void setMenuName(String menuName) {\n this.menuName = menuName;\n }\n\n public String getMenuUrl() {\n return menuUrl;\n }\n\n public void setMenuUrl(String menuUrl) {\n this.menuUrl = menuUrl;\n }\n\n public String getMenuIcon() {\n return menuIcon;\n }\n\n public void setMenuIcon(String menuIcon) {\n this.menuIcon = menuIcon;\n }\n\n public Integer getMenuSort() {\n return menuSort;\n }\n\n public void setMenuSort(Integer menuSort) {\n this.menuSort = menuSort;\n }\n\n public Date getCreateDate() {\n return createDate;\n }\n\n public void setCreateDate(Date createDate) {\n this.createDate = createDate;\n }\n\n public Date getUpdateDate() {\n return updateDate;\n }\n\n public void setUpdateDate(Date updateDate) {\n this.updateDate = updateDate;\n }\n\n @Override\n public String toString() {\n return \"Menu {menuId=\" + menuId + \", parentMenuId=\" + parentMenuId + \", permissionId=\" + permissionId + \", userId=\" + userId + \", menuName=\" + menuName + \", menuUrl=\" + menuUrl + \", menuIcon=\" + menuIcon + \", menuSort=\" + menuSort + \", createDate=\" + createDate + \", updateDate=\" + updateDate + \"}\";\n }\n}\n"} {"task_id": "Java_1987", "language": "Java", "task_type": "single_line", "source_file": "java/github/miansen/Roothub/src/main/java/wang/miansen/roothub/modules/menu/model/Menu.java", "mask_start_position": 1579, "mask_end_position": 1581, "canonical_solution": "d;", "pre_mask_code": "package wang.miansen.roothub.modules.menu.model;\n\nimport java.util.Date;\nimport wang.miansen.roothub.common.annotation.DO2DTO;\nimport wang.miansen.roothub.common.dao.mapper.annotation.Id;\nimport wang.miansen.roothub.common.dao.mapper.annotation.Table;\nimport wang.miansen.roothub.common.dao.mapper.enums.IdType;\nimport wang.miansen.roothub.common.entity.BaseDO;\nimport wang.miansen.roothub.common.enums.ConverPolicy;\n\n/**\n * 菜单实体类\n *\n * @author miansen.wang\n * @date 2020-03-06\n */\n@Table(value = \"menu\")\npublic class Menu implements BaseDO {\n\n private static final long serialVersionUID = -4251615965305941108L;\n\n /**\n * 菜单ID\n */\n @Id(value = \"menu_id\", type = IdType.UUID)\n private String menuId;\n\n /**\n * 父级菜单ID\n */\n @DO2DTO(targets = { \"parentMenuDTO\" }, policy = ConverPolicy.ID_CONVER_DTO, service = \"menuServiceImpl\")\n private String parentMenuId;\n\n /**\n * 权限ID\n */\n @DO2DTO(targets = { \"permissionDTO\" }, policy = ConverPolicy.ID_CONVER_DTO, service = \"permissionServiceImpl\")\n private String permissionId;\n\n /**\n * 创建人ID\n */\n @DO2DTO(targets = { \"userDTO\" }, policy = ConverPolicy.ID_CONVER_DTO, service = \"userServiceImpl\")\n private String userId;\n\n private String menuName;\n\n /**\n * 点击菜单时发送的请求URL\n */\n private String menuUrl;\n\n private String menuIcon;\n\n private Integer menuSort;\n\n private Date createDate;\n\n private Date updateDate;\n\n public String getMenuId() {\n return menuId;\n }\n\n public void setMenuId(String menuId) {\n this.menuId = menuI", "post_mask_code": "\n }\n\n public String getParentMenuId() {\n return parentMenuId;\n }\n\n public void setParentMenuId(String parentMenuId) {\n this.parentMenuId = parentMenuId;\n }\n\n public String getPermissionId() {\n return permissionId;\n }\n\n public void setPermissionId(String permissionId) {\n this.permissionId = permissionId;\n }\n\n public String getUserId() {\n return userId;\n }\n\n public void setUserId(String userId) {\n this.userId = userId;\n }\n\n public String getMenuName() {\n return menuName;\n }\n\n public void setMenuName(String menuName) {\n this.menuName = menuName;\n }\n\n public String getMenuUrl() {\n return menuUrl;\n }\n\n public void setMenuUrl(String menuUrl) {\n this.menuUrl = menuUrl;\n }\n\n public String getMenuIcon() {\n return menuIcon;\n }\n\n public void setMenuIcon(String menuIcon) {\n this.menuIcon = menuIcon;\n }\n\n public Integer getMenuSort() {\n return menuSort;\n }\n\n public void setMenuSort(Integer menuSort) {\n this.menuSort = menuSort;\n }\n\n public Date getCreateDate() {\n return createDate;\n }\n\n public void setCreateDate(Date createDate) {\n this.createDate = createDate;\n }\n\n public Date getUpdateDate() {\n return updateDate;\n }\n\n public void setUpdateDate(Date updateDate) {\n this.updateDate = updateDate;\n }\n\n @Override\n public String toString() {\n return \"Menu {menuId=\" + menuId + \", parentMenuId=\" + parentMenuId + \", permissionId=\" + permissionId + \", userId=\" + userId + \", menuName=\" + menuName + \", menuUrl=\" + menuUrl + \", menuIcon=\" + menuIcon + \", menuSort=\" + menuSort + \", createDate=\" + createDate + \", updateDate=\" + updateDate + \"}\";\n }\n}\n"} {"task_id": "Java_1988", "language": "Java", "task_type": "method_signature", "source_file": "java/github/mucommander/mucommander/mucommander-core/src/main/java/com/mucommander/ui/action/impl/GoForwardAction.java", "mask_start_position": 1854, "mask_end_position": 1876, "canonical_solution": "public String getId() ", "pre_mask_code": "/*\n * This file is part of muCommander, http://www.mucommander.com\n *\n */\npackage com.mucommander.ui.action.impl;\n\nimport java.awt.event.KeyEvent;\nimport java.util.Map;\nimport javax.swing.KeyStroke;\nimport com.mucommander.ui.action.AbstractActionDescriptor;\nimport com.mucommander.ui.action.ActionCategory;\nimport com.mucommander.ui.action.ActionDescriptor;\nimport com.mucommander.ui.action.ActionFactory;\nimport com.mucommander.ui.action.MuAction;\nimport com.mucommander.ui.main.MainFrame;\n\n/**\n * This action recalls the next folder in the current FolderPanel's history.\n *\n * @author Maxence Bernard\n */\npublic class GoForwardAction extends ActiveTabAction {\n\n public GoForwardAction(MainFrame mainFrame, Map properties) {\n super(mainFrame, properties);\n }\n\n @Override\n public void performAction() {\n mainFrame.getActivePanel().getFolderHistory().goForward();\n }\n\n @Override\n public ActionDescriptor getDescriptor() {\n return new Descriptor();\n }\n\n /**\n * Enables or disables this action based on the history of the currently active FolderPanel: if there is a next\n * folder in the history and the current tab is not locked, this action will be enabled, if not it will be disabled.\n */\n @Override\n protected void toggleEnabledState() {\n setEnabled(mainFrame.getActivePanel().getFolderHistory().hasForwardFolder() && !mainFrame.getActivePanel().getTabs().getCurrentTab().isLocked());\n }\n\n public static class Factory implements ActionFactory {\n\n public MuAction createAction(MainFrame mainFrame, Map properties) {\n return new GoForwardAction(mainFrame, properties);\n }\n }\n\n public static class Descriptor extends AbstractActionDescriptor {\n\n public static final String ACTION_ID = \"GoForward\";\n\n ", "post_mask_code": "{\n return ACTION_ID;\n }\n\n public ActionCategory getCategory() {\n return ActionCategory.NAVIGATION;\n }\n\n public KeyStroke getDefaultAltKeyStroke() {\n return null;\n }\n\n public KeyStroke getDefaultKeyStroke() {\n return KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.ALT_DOWN_MASK);\n }\n }\n}\n"} {"task_id": "Java_1989", "language": "Java", "task_type": "method_body", "source_file": "java/github/mucommander/mucommander/mucommander-core/src/main/java/com/mucommander/ui/action/impl/GoForwardAction.java", "mask_start_position": 2157, "mask_end_position": 2254, "canonical_solution": "{\n return KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.ALT_DOWN_MASK);\n }", "pre_mask_code": "/*\n * This file is part of muCommander, http://www.mucommander.com\n *\n */\npackage com.mucommander.ui.action.impl;\n\nimport java.awt.event.KeyEvent;\nimport java.util.Map;\nimport javax.swing.KeyStroke;\nimport com.mucommander.ui.action.AbstractActionDescriptor;\nimport com.mucommander.ui.action.ActionCategory;\nimport com.mucommander.ui.action.ActionDescriptor;\nimport com.mucommander.ui.action.ActionFactory;\nimport com.mucommander.ui.action.MuAction;\nimport com.mucommander.ui.main.MainFrame;\n\n/**\n * This action recalls the next folder in the current FolderPanel's history.\n *\n * @author Maxence Bernard\n */\npublic class GoForwardAction extends ActiveTabAction {\n\n public GoForwardAction(MainFrame mainFrame, Map properties) {\n super(mainFrame, properties);\n }\n\n @Override\n public void performAction() {\n mainFrame.getActivePanel().getFolderHistory().goForward();\n }\n\n @Override\n public ActionDescriptor getDescriptor() {\n return new Descriptor();\n }\n\n /**\n * Enables or disables this action based on the history of the currently active FolderPanel: if there is a next\n * folder in the history and the current tab is not locked, this action will be enabled, if not it will be disabled.\n */\n @Override\n protected void toggleEnabledState() {\n setEnabled(mainFrame.getActivePanel().getFolderHistory().hasForwardFolder() && !mainFrame.getActivePanel().getTabs().getCurrentTab().isLocked());\n }\n\n public static class Factory implements ActionFactory {\n\n public MuAction createAction(MainFrame mainFrame, Map properties) {\n return new GoForwardAction(mainFrame, properties);\n }\n }\n\n public static class Descriptor extends AbstractActionDescriptor {\n\n public static final String ACTION_ID = \"GoForward\";\n\n public String getId() {\n return ACTION_ID;\n }\n\n public ActionCategory getCategory() {\n return ActionCategory.NAVIGATION;\n }\n\n public KeyStroke getDefaultAltKeyStroke() {\n return null;\n }\n\n public KeyStroke getDefaultKeyStroke() ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_1990", "language": "Java", "task_type": "single_line", "source_file": "java/github/mucommander/mucommander/mucommander-core/src/main/java/com/mucommander/ui/action/impl/GoForwardAction.java", "mask_start_position": 1684, "mask_end_position": 1696, "canonical_solution": "properties);", "pre_mask_code": "/*\n * This file is part of muCommander, http://www.mucommander.com\n *\n */\npackage com.mucommander.ui.action.impl;\n\nimport java.awt.event.KeyEvent;\nimport java.util.Map;\nimport javax.swing.KeyStroke;\nimport com.mucommander.ui.action.AbstractActionDescriptor;\nimport com.mucommander.ui.action.ActionCategory;\nimport com.mucommander.ui.action.ActionDescriptor;\nimport com.mucommander.ui.action.ActionFactory;\nimport com.mucommander.ui.action.MuAction;\nimport com.mucommander.ui.main.MainFrame;\n\n/**\n * This action recalls the next folder in the current FolderPanel's history.\n *\n * @author Maxence Bernard\n */\npublic class GoForwardAction extends ActiveTabAction {\n\n public GoForwardAction(MainFrame mainFrame, Map properties) {\n super(mainFrame, properties);\n }\n\n @Override\n public void performAction() {\n mainFrame.getActivePanel().getFolderHistory().goForward();\n }\n\n @Override\n public ActionDescriptor getDescriptor() {\n return new Descriptor();\n }\n\n /**\n * Enables or disables this action based on the history of the currently active FolderPanel: if there is a next\n * folder in the history and the current tab is not locked, this action will be enabled, if not it will be disabled.\n */\n @Override\n protected void toggleEnabledState() {\n setEnabled(mainFrame.getActivePanel().getFolderHistory().hasForwardFolder() && !mainFrame.getActivePanel().getTabs().getCurrentTab().isLocked());\n }\n\n public static class Factory implements ActionFactory {\n\n public MuAction createAction(MainFrame mainFrame, Map properties) {\n return new GoForwardAction(mainFrame, ", "post_mask_code": "\n }\n }\n\n public static class Descriptor extends AbstractActionDescriptor {\n\n public static final String ACTION_ID = \"GoForward\";\n\n public String getId() {\n return ACTION_ID;\n }\n\n public ActionCategory getCategory() {\n return ActionCategory.NAVIGATION;\n }\n\n public KeyStroke getDefaultAltKeyStroke() {\n return null;\n }\n\n public KeyStroke getDefaultKeyStroke() {\n return KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.ALT_DOWN_MASK);\n }\n }\n}\n"} {"task_id": "Java_1991", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/mucommander/mucommander/mucommander-core/src/main/java/com/mucommander/ui/action/impl/GoForwardAction.java", "mask_start_position": 1269, "mask_end_position": 1480, "canonical_solution": "@Override\n protected void toggleEnabledState() {\n setEnabled(mainFrame.getActivePanel().getFolderHistory().hasForwardFolder() && !mainFrame.getActivePanel().getTabs().getCurrentTab().isLocked());\n }", "pre_mask_code": "/*\n * This file is part of muCommander, http://www.mucommander.com\n *\n */\npackage com.mucommander.ui.action.impl;\n\nimport java.awt.event.KeyEvent;\nimport java.util.Map;\nimport javax.swing.KeyStroke;\nimport com.mucommander.ui.action.AbstractActionDescriptor;\nimport com.mucommander.ui.action.ActionCategory;\nimport com.mucommander.ui.action.ActionDescriptor;\nimport com.mucommander.ui.action.ActionFactory;\nimport com.mucommander.ui.action.MuAction;\nimport com.mucommander.ui.main.MainFrame;\n\n/**\n * This action recalls the next folder in the current FolderPanel's history.\n *\n * @author Maxence Bernard\n */\npublic class GoForwardAction extends ActiveTabAction {\n\n public GoForwardAction(MainFrame mainFrame, Map properties) {\n super(mainFrame, properties);\n }\n\n @Override\n public void performAction() {\n mainFrame.getActivePanel().getFolderHistory().goForward();\n }\n\n @Override\n public ActionDescriptor getDescriptor() {\n return new Descriptor();\n }\n\n /**\n * Enables or disables this action based on the history of the currently active FolderPanel: if there is a next\n * folder in the history and the current tab is not locked, this action will be enabled, if not it will be disabled.\n */\n ", "post_mask_code": "\n\n public static class Factory implements ActionFactory {\n\n public MuAction createAction(MainFrame mainFrame, Map properties) {\n return new GoForwardAction(mainFrame, properties);\n }\n }\n\n public static class Descriptor extends AbstractActionDescriptor {\n\n public static final String ACTION_ID = \"GoForward\";\n\n public String getId() {\n return ACTION_ID;\n }\n\n public ActionCategory getCategory() {\n return ActionCategory.NAVIGATION;\n }\n\n public KeyStroke getDefaultAltKeyStroke() {\n return null;\n }\n\n public KeyStroke getDefaultKeyStroke() {\n return KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.ALT_DOWN_MASK);\n }\n }\n}\n"} {"task_id": "Java_1992", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Mojang/DataFixerUpper/src/main/java/com/mojang/datafixers/util/Function13.java", "mask_start_position": 3096, "mask_end_position": 3194, "canonical_solution": "default Function12> curry12() ", "pre_mask_code": "package com.mojang.datafixers.util;\n\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic interface Function13 {\n\n R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13);\n\n default Function> curry() {\n return t1 -> (t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default BiFunction> curry2() {\n return (t1, t2) -> (t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function3> curry3() {\n return (t1, t2, t3) -> (t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function4> curry4() {\n return (t1, t2, t3, t4) -> (t5, t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function5> curry5() {\n return (t1, t2, t3, t4, t5) -> (t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function6> curry6() {\n return (t1, t2, t3, t4, t5, t6) -> (t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function7> curry7() {\n return (t1, t2, t3, t4, t5, t6, t7) -> (t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function8> curry8() {\n return (t1, t2, t3, t4, t5, t6, t7, t8) -> (t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function9> curry9() {\n return (t1, t2, t3, t4, t5, t6, t7, t8, t9) -> (t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function10> curry10() {\n return (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10) -> (t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function11> curry11() {\n return (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11) -> (t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n ", "post_mask_code": "{\n return (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12) -> t13 -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n}\n"} {"task_id": "Java_1993", "language": "Java", "task_type": "method_body", "source_file": "java/github/Mojang/DataFixerUpper/src/main/java/com/mojang/datafixers/util/Function13.java", "mask_start_position": 3194, "mask_end_position": 3341, "canonical_solution": "{\n return (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12) -> t13 -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }", "pre_mask_code": "package com.mojang.datafixers.util;\n\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic interface Function13 {\n\n R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13);\n\n default Function> curry() {\n return t1 -> (t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default BiFunction> curry2() {\n return (t1, t2) -> (t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function3> curry3() {\n return (t1, t2, t3) -> (t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function4> curry4() {\n return (t1, t2, t3, t4) -> (t5, t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function5> curry5() {\n return (t1, t2, t3, t4, t5) -> (t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function6> curry6() {\n return (t1, t2, t3, t4, t5, t6) -> (t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function7> curry7() {\n return (t1, t2, t3, t4, t5, t6, t7) -> (t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function8> curry8() {\n return (t1, t2, t3, t4, t5, t6, t7, t8) -> (t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function9> curry9() {\n return (t1, t2, t3, t4, t5, t6, t7, t8, t9) -> (t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function10> curry10() {\n return (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10) -> (t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function11> curry11() {\n return (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11) -> (t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function12> curry12() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1994", "language": "Java", "task_type": "single_line", "source_file": "java/github/Mojang/DataFixerUpper/src/main/java/com/mojang/datafixers/util/Function13.java", "mask_start_position": 1297, "mask_end_position": 1315, "canonical_solution": "0, t11, t12, t13);", "pre_mask_code": "package com.mojang.datafixers.util;\n\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic interface Function13 {\n\n R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13);\n\n default Function> curry() {\n return t1 -> (t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default BiFunction> curry2() {\n return (t1, t2) -> (t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function3> curry3() {\n return (t1, t2, t3) -> (t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function4> curry4() {\n return (t1, t2, t3, t4) -> (t5, t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t1", "post_mask_code": "\n }\n\n default Function5> curry5() {\n return (t1, t2, t3, t4, t5) -> (t6, t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function6> curry6() {\n return (t1, t2, t3, t4, t5, t6) -> (t7, t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function7> curry7() {\n return (t1, t2, t3, t4, t5, t6, t7) -> (t8, t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function8> curry8() {\n return (t1, t2, t3, t4, t5, t6, t7, t8) -> (t9, t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function9> curry9() {\n return (t1, t2, t3, t4, t5, t6, t7, t8, t9) -> (t10, t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function10> curry10() {\n return (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10) -> (t11, t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function11> curry11() {\n return (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11) -> (t12, t13) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n\n default Function12> curry12() {\n return (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12) -> t13 -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);\n }\n}\n"} {"task_id": "Java_1995", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/shrinkwrap/resolver/api/src/main/java/org/jboss/shrinkwrap/resolver/api/ConfigurableResolverSystem.java", "mask_start_position": 3051, "mask_end_position": 3184, "canonical_solution": "CONFIGUREDRESOLVERSYSTEMTYPE fromClassloaderResource(String path) throws IllegalArgumentException, InvalidConfigurationFileException;", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source\n * full listing of individual contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://example.com\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jboss.shrinkwrap.resolver.api;\n\nimport java.io.File;\n\n/**\n * Top-level of a configurable resolver system; subtypes may be passed in as an argument to {@link Resolvers#use(Class)}\n * or {@link Resolvers#use(Class, ClassLoader)} to create a new instance.\n *\n * @param \n * View type of the {@link ResolverSystem} which does not support configuration\n * @author Andrew Lee Rubinger\n */\npublic interface ConfigurableResolverSystem> extends ResolverSystem {\n\n /**\n * Configures this {@link ResolverSystem} from the specified file\n *\n * @param file The file the {@link ResolverSystem} should be configured from\n * @return This configured {@link ResolverSystem}\n * @throws IllegalArgumentException\n * If the file is not specified, is a directory, or does not exist\n * @throws InvalidConfigurationFileException\n * If the file is not in correct format\n */\n CONFIGUREDRESOLVERSYSTEMTYPE fromFile(File file) throws IllegalArgumentException, InvalidConfigurationFileException;\n\n /**\n * Configures this {@link ResolverSystem} from the file at the specified path\n *\n * @param pathToFile Path to the file the {@link ResolverSystem} should be configured from\n * @return This configured {@link ResolverSystem}\n * @throws IllegalArgumentException\n * If the file is not specified, is a directory, or does not exist\n * @throws InvalidConfigurationFileException\n * If the file is not in correct format\n */\n CONFIGUREDRESOLVERSYSTEMTYPE fromFile(String pathToFile) throws IllegalArgumentException, InvalidConfigurationFileException;\n\n /**\n * Configures this {@link ResolverSystem} from the result of {@link ClassLoader#getResource(String)} using the\n * current {@link Thread#getContextClassLoader()}\n *\n * @param path Path to the classloader resource\n * @return This configured {@link ResolverSystem}\n * @throws IllegalArgumentException\n * If the path is not specified or can not be found\n * @throws InvalidConfigurationFileException\n * If the file is not in correct format\n */\n ", "post_mask_code": "\n\n /**\n * Configures this {@link ResolverSystem} from the result of {@link ClassLoader#getResource(String)} using the\n * specified {@link ClassLoader}\n *\n * @param path Path to the classloader resource\n * @param loader The classloader\n * @return This configured {@link ResolverSystem}\n * @throws IllegalArgumentException\n * If the either argument is not specified or if the path can not be found\n * @throws InvalidConfigurationFileException\n * If the file is not in correct format\n */\n CONFIGUREDRESOLVERSYSTEMTYPE fromClassloaderResource(String path, ClassLoader loader) throws IllegalArgumentException, InvalidConfigurationFileException;\n}\n"} {"task_id": "Java_1996", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/inchaincodes/inchain/inchain-core/src/main/java/org/inchain/crypto/EncryptableItem.java", "mask_start_position": 489, "mask_end_position": 522, "canonical_solution": "EncryptedData getEncryptedData();", "pre_mask_code": "package org.inchain.crypto;\n\npublic interface EncryptableItem {\n\n /**\n * Returns whether the item is encrypted or not. If it is, then {@link #getSecretBytes()} will return null.\n */\n boolean isEncrypted();\n\n /**\n * Returns the raw bytes of the item, if not encrypted, or null if encrypted or the secret is missing.\n */\n byte[] getSecretBytes();\n\n /**\n * Returns the initialization vector and encrypted secret bytes, or null if not encrypted.\n */\n ", "post_mask_code": "\n\n /**\n * Returns the time in seconds since the UNIX epoch at which this encryptable item was first created/derived.\n */\n long getCreationTimeSeconds();\n}\n"} {"task_id": "Java_1997", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/drill/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java", "mask_start_position": 6527, "mask_end_position": 6641, "canonical_solution": "public GenericFutureListener getHandler(C connection, GenericFutureListener parent) ", "pre_mask_code": "package org.apache.drill.exec.rpc;\n\nimport com.google.protobuf.Internal.EnumLite;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.util.concurrent.GenericFutureListener;\nimport java.io.Closeable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicReference;\nimport org.apache.drill.shaded.guava.com.google.common.base.Preconditions;\nimport org.apache.drill.shaded.guava.com.google.common.util.concurrent.AbstractFuture;\nimport com.google.protobuf.MessageLite;\n\n/**\n * Manager all connections between two particular bits.\n */\npublic abstract class ReconnectingConnection implements Closeable {\n\n static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ReconnectingConnection.class);\n\n private final AtomicReference connectionHolder = new AtomicReference();\n\n private final String host;\n\n private final int port;\n\n private final HS handshake;\n\n public ReconnectingConnection(HS handshake, String host, int port) {\n Preconditions.checkNotNull(host);\n Preconditions.checkArgument(port > 0);\n this.host = host;\n this.port = port;\n this.handshake = handshake;\n }\n\n protected abstract BasicClient getNewClient();\n\n public > void runCommand(R cmd) {\n // if(logger.isDebugEnabled()) logger.debug(String.format(\"Running command %s sending to host %s:%d\", cmd, host, port));\n C connection = connectionHolder.get();\n if (connection != null) {\n if (connection.isActive()) {\n cmd.connectionAvailable(connection);\n // logger.debug(\"Connection available and active, command run inline.\");\n return;\n } else {\n // remove the old connection. (don't worry if we fail since someone else should have done it.\n connectionHolder.compareAndSet(connection, null);\n }\n }\n /**\n * We've arrived here without a connection, let's make sure only one of us makes a connection. (fyi, another\n * endpoint could create a reverse connection\n */\n synchronized (this) {\n connection = connectionHolder.get();\n if (connection != null) {\n cmd.connectionAvailable(connection);\n } else {\n // logger.debug(\"No connection active, opening client connection.\");\n BasicClient client = getNewClient();\n ConnectionListeningFuture future = new ConnectionListeningFuture<>(cmd);\n client.connectAsClient(future, handshake, host, port);\n future.waitAndRun();\n // logger.debug(\"Connection available and active, command now being run inline.\");\n }\n return;\n }\n }\n\n public class ConnectionListeningFuture extends AbstractFuture implements RpcConnectionHandler {\n\n private RpcCommand cmd;\n\n public ConnectionListeningFuture(RpcCommand cmd) {\n super();\n this.cmd = cmd;\n }\n\n /**\n * Called by\n */\n public void waitAndRun() {\n boolean isInterrupted = false;\n // We want to wait for at least 120 secs when interrupts occur. Establishing a connection fails/succeeds quickly,\n // So there is no point propagating the interruption as failure immediately.\n long remainingWaitTimeMills = 120000;\n long startTime = System.currentTimeMillis();\n while (true) {\n try {\n C connection = this.get(remainingWaitTimeMills, TimeUnit.MILLISECONDS);\n if (connection == null) {\n } else {\n cmd.connectionSucceeded(connection);\n // logger.debug(\"Finished connection succeeded activity.\");\n }\n break;\n } catch (final InterruptedException interruptEx) {\n remainingWaitTimeMills -= (System.currentTimeMillis() - startTime);\n startTime = System.currentTimeMillis();\n isInterrupted = true;\n if (remainingWaitTimeMills < 1) {\n cmd.connectionFailed(FailureType.CONNECTION, interruptEx);\n break;\n }\n // Ignore the interrupt and continue to wait until we elapse remainingWaitTimeMills.\n } catch (final ExecutionException | TimeoutException ex) {\n logger.error(\"Failed to establish connection\", ex);\n cmd.connectionFailed(FailureType.CONNECTION, ex);\n break;\n }\n }\n if (isInterrupted) {\n // Preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the\n // interruption and respond to it if it wants to.\n Thread.currentThread().interrupt();\n }\n }\n\n @Override\n public void connectionFailed(FailureType type, Throwable t) {\n set(null);\n cmd.connectionFailed(type, t);\n }\n\n @Override\n public void connectionSucceeded(C incoming) {\n C connection = connectionHolder.get();\n while (true) {\n boolean setted = connectionHolder.compareAndSet(null, incoming);\n if (setted) {\n connection = incoming;\n break;\n }\n connection = connectionHolder.get();\n if (connection != null) {\n break;\n }\n }\n if (connection != incoming) {\n // close the incoming because another channel was created in the mean time (unless this is a self connection).\n logger.debug(\"Closing incoming connection because a connection was already set.\");\n incoming.getChannel().close();\n }\n set(connection);\n }\n }\n\n /**\n * Factory for close handlers *\n */\n public class CloseHandlerCreator {\n\n ", "post_mask_code": "{\n return new CloseHandler(connection, parent);\n }\n }\n\n /**\n * Listens for connection closes and clears connection holder.\n */\n protected class CloseHandler implements GenericFutureListener {\n\n private C connection;\n\n private GenericFutureListener parent;\n\n public CloseHandler(C connection, GenericFutureListener parent) {\n super();\n this.connection = connection;\n this.parent = parent;\n }\n\n @Override\n public void operationComplete(ChannelFuture future) throws Exception {\n connectionHolder.compareAndSet(connection, null);\n parent.operationComplete(future);\n }\n }\n\n public CloseHandlerCreator getCloseHandlerCreator() {\n return new CloseHandlerCreator();\n }\n\n public void addExternalConnection(C connection) {\n // if the connection holder is not set, set it to this incoming connection. We'll simply ignore if already set.\n this.connectionHolder.compareAndSet(null, connection);\n }\n\n @Override\n public void close() {\n C c = connectionHolder.getAndSet(null);\n if (c != null) {\n c.getChannel().close();\n }\n }\n}\n"} {"task_id": "Java_1998", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/drill/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java", "mask_start_position": 7785, "mask_end_position": 7911, "canonical_solution": "{\n C c = connectionHolder.getAndSet(null);\n if (c != null) {\n c.getChannel().close();\n }\n }", "pre_mask_code": "package org.apache.drill.exec.rpc;\n\nimport com.google.protobuf.Internal.EnumLite;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.util.concurrent.GenericFutureListener;\nimport java.io.Closeable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicReference;\nimport org.apache.drill.shaded.guava.com.google.common.base.Preconditions;\nimport org.apache.drill.shaded.guava.com.google.common.util.concurrent.AbstractFuture;\nimport com.google.protobuf.MessageLite;\n\n/**\n * Manager all connections between two particular bits.\n */\npublic abstract class ReconnectingConnection implements Closeable {\n\n static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ReconnectingConnection.class);\n\n private final AtomicReference connectionHolder = new AtomicReference();\n\n private final String host;\n\n private final int port;\n\n private final HS handshake;\n\n public ReconnectingConnection(HS handshake, String host, int port) {\n Preconditions.checkNotNull(host);\n Preconditions.checkArgument(port > 0);\n this.host = host;\n this.port = port;\n this.handshake = handshake;\n }\n\n protected abstract BasicClient getNewClient();\n\n public > void runCommand(R cmd) {\n // if(logger.isDebugEnabled()) logger.debug(String.format(\"Running command %s sending to host %s:%d\", cmd, host, port));\n C connection = connectionHolder.get();\n if (connection != null) {\n if (connection.isActive()) {\n cmd.connectionAvailable(connection);\n // logger.debug(\"Connection available and active, command run inline.\");\n return;\n } else {\n // remove the old connection. (don't worry if we fail since someone else should have done it.\n connectionHolder.compareAndSet(connection, null);\n }\n }\n /**\n * We've arrived here without a connection, let's make sure only one of us makes a connection. (fyi, another\n * endpoint could create a reverse connection\n */\n synchronized (this) {\n connection = connectionHolder.get();\n if (connection != null) {\n cmd.connectionAvailable(connection);\n } else {\n // logger.debug(\"No connection active, opening client connection.\");\n BasicClient client = getNewClient();\n ConnectionListeningFuture future = new ConnectionListeningFuture<>(cmd);\n client.connectAsClient(future, handshake, host, port);\n future.waitAndRun();\n // logger.debug(\"Connection available and active, command now being run inline.\");\n }\n return;\n }\n }\n\n public class ConnectionListeningFuture extends AbstractFuture implements RpcConnectionHandler {\n\n private RpcCommand cmd;\n\n public ConnectionListeningFuture(RpcCommand cmd) {\n super();\n this.cmd = cmd;\n }\n\n /**\n * Called by\n */\n public void waitAndRun() {\n boolean isInterrupted = false;\n // We want to wait for at least 120 secs when interrupts occur. Establishing a connection fails/succeeds quickly,\n // So there is no point propagating the interruption as failure immediately.\n long remainingWaitTimeMills = 120000;\n long startTime = System.currentTimeMillis();\n while (true) {\n try {\n C connection = this.get(remainingWaitTimeMills, TimeUnit.MILLISECONDS);\n if (connection == null) {\n } else {\n cmd.connectionSucceeded(connection);\n // logger.debug(\"Finished connection succeeded activity.\");\n }\n break;\n } catch (final InterruptedException interruptEx) {\n remainingWaitTimeMills -= (System.currentTimeMillis() - startTime);\n startTime = System.currentTimeMillis();\n isInterrupted = true;\n if (remainingWaitTimeMills < 1) {\n cmd.connectionFailed(FailureType.CONNECTION, interruptEx);\n break;\n }\n // Ignore the interrupt and continue to wait until we elapse remainingWaitTimeMills.\n } catch (final ExecutionException | TimeoutException ex) {\n logger.error(\"Failed to establish connection\", ex);\n cmd.connectionFailed(FailureType.CONNECTION, ex);\n break;\n }\n }\n if (isInterrupted) {\n // Preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the\n // interruption and respond to it if it wants to.\n Thread.currentThread().interrupt();\n }\n }\n\n @Override\n public void connectionFailed(FailureType type, Throwable t) {\n set(null);\n cmd.connectionFailed(type, t);\n }\n\n @Override\n public void connectionSucceeded(C incoming) {\n C connection = connectionHolder.get();\n while (true) {\n boolean setted = connectionHolder.compareAndSet(null, incoming);\n if (setted) {\n connection = incoming;\n break;\n }\n connection = connectionHolder.get();\n if (connection != null) {\n break;\n }\n }\n if (connection != incoming) {\n // close the incoming because another channel was created in the mean time (unless this is a self connection).\n logger.debug(\"Closing incoming connection because a connection was already set.\");\n incoming.getChannel().close();\n }\n set(connection);\n }\n }\n\n /**\n * Factory for close handlers *\n */\n public class CloseHandlerCreator {\n\n public GenericFutureListener getHandler(C connection, GenericFutureListener parent) {\n return new CloseHandler(connection, parent);\n }\n }\n\n /**\n * Listens for connection closes and clears connection holder.\n */\n protected class CloseHandler implements GenericFutureListener {\n\n private C connection;\n\n private GenericFutureListener parent;\n\n public CloseHandler(C connection, GenericFutureListener parent) {\n super();\n this.connection = connection;\n this.parent = parent;\n }\n\n @Override\n public void operationComplete(ChannelFuture future) throws Exception {\n connectionHolder.compareAndSet(connection, null);\n parent.operationComplete(future);\n }\n }\n\n public CloseHandlerCreator getCloseHandlerCreator() {\n return new CloseHandlerCreator();\n }\n\n public void addExternalConnection(C connection) {\n // if the connection holder is not set, set it to this incoming connection. We'll simply ignore if already set.\n this.connectionHolder.compareAndSet(null, connection);\n }\n\n @Override\n public void close() ", "post_mask_code": "\n}\n"} {"task_id": "Java_1999", "language": "Java", "task_type": "method_body_top", "source_file": "java/github/apache/drill/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java", "mask_start_position": 3478, "mask_end_position": 3647, "canonical_solution": "\n boolean isInterrupted = false;\n // We want to wait for at least 120 secs when interrupts occur. Establishing a connection fails/succeeds quickly,", "pre_mask_code": "package org.apache.drill.exec.rpc;\n\nimport com.google.protobuf.Internal.EnumLite;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.util.concurrent.GenericFutureListener;\nimport java.io.Closeable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicReference;\nimport org.apache.drill.shaded.guava.com.google.common.base.Preconditions;\nimport org.apache.drill.shaded.guava.com.google.common.util.concurrent.AbstractFuture;\nimport com.google.protobuf.MessageLite;\n\n/**\n * Manager all connections between two particular bits.\n */\npublic abstract class ReconnectingConnection implements Closeable {\n\n static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ReconnectingConnection.class);\n\n private final AtomicReference connectionHolder = new AtomicReference();\n\n private final String host;\n\n private final int port;\n\n private final HS handshake;\n\n public ReconnectingConnection(HS handshake, String host, int port) {\n Preconditions.checkNotNull(host);\n Preconditions.checkArgument(port > 0);\n this.host = host;\n this.port = port;\n this.handshake = handshake;\n }\n\n protected abstract BasicClient getNewClient();\n\n public > void runCommand(R cmd) {\n // if(logger.isDebugEnabled()) logger.debug(String.format(\"Running command %s sending to host %s:%d\", cmd, host, port));\n C connection = connectionHolder.get();\n if (connection != null) {\n if (connection.isActive()) {\n cmd.connectionAvailable(connection);\n // logger.debug(\"Connection available and active, command run inline.\");\n return;\n } else {\n // remove the old connection. (don't worry if we fail since someone else should have done it.\n connectionHolder.compareAndSet(connection, null);\n }\n }\n /**\n * We've arrived here without a connection, let's make sure only one of us makes a connection. (fyi, another\n * endpoint could create a reverse connection\n */\n synchronized (this) {\n connection = connectionHolder.get();\n if (connection != null) {\n cmd.connectionAvailable(connection);\n } else {\n // logger.debug(\"No connection active, opening client connection.\");\n BasicClient client = getNewClient();\n ConnectionListeningFuture future = new ConnectionListeningFuture<>(cmd);\n client.connectAsClient(future, handshake, host, port);\n future.waitAndRun();\n // logger.debug(\"Connection available and active, command now being run inline.\");\n }\n return;\n }\n }\n\n public class ConnectionListeningFuture extends AbstractFuture implements RpcConnectionHandler {\n\n private RpcCommand cmd;\n\n public ConnectionListeningFuture(RpcCommand cmd) {\n super();\n this.cmd = cmd;\n }\n\n /**\n * Called by\n */\n public void waitAndRun() {", "post_mask_code": "\n // So there is no point propagating the interruption as failure immediately.\n long remainingWaitTimeMills = 120000;\n long startTime = System.currentTimeMillis();\n while (true) {\n try {\n C connection = this.get(remainingWaitTimeMills, TimeUnit.MILLISECONDS);\n if (connection == null) {\n } else {\n cmd.connectionSucceeded(connection);\n // logger.debug(\"Finished connection succeeded activity.\");\n }\n break;\n } catch (final InterruptedException interruptEx) {\n remainingWaitTimeMills -= (System.currentTimeMillis() - startTime);\n startTime = System.currentTimeMillis();\n isInterrupted = true;\n if (remainingWaitTimeMills < 1) {\n cmd.connectionFailed(FailureType.CONNECTION, interruptEx);\n break;\n }\n // Ignore the interrupt and continue to wait until we elapse remainingWaitTimeMills.\n } catch (final ExecutionException | TimeoutException ex) {\n logger.error(\"Failed to establish connection\", ex);\n cmd.connectionFailed(FailureType.CONNECTION, ex);\n break;\n }\n }\n if (isInterrupted) {\n // Preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the\n // interruption and respond to it if it wants to.\n Thread.currentThread().interrupt();\n }\n }\n\n @Override\n public void connectionFailed(FailureType type, Throwable t) {\n set(null);\n cmd.connectionFailed(type, t);\n }\n\n @Override\n public void connectionSucceeded(C incoming) {\n C connection = connectionHolder.get();\n while (true) {\n boolean setted = connectionHolder.compareAndSet(null, incoming);\n if (setted) {\n connection = incoming;\n break;\n }\n connection = connectionHolder.get();\n if (connection != null) {\n break;\n }\n }\n if (connection != incoming) {\n // close the incoming because another channel was created in the mean time (unless this is a self connection).\n logger.debug(\"Closing incoming connection because a connection was already set.\");\n incoming.getChannel().close();\n }\n set(connection);\n }\n }\n\n /**\n * Factory for close handlers *\n */\n public class CloseHandlerCreator {\n\n public GenericFutureListener getHandler(C connection, GenericFutureListener parent) {\n return new CloseHandler(connection, parent);\n }\n }\n\n /**\n * Listens for connection closes and clears connection holder.\n */\n protected class CloseHandler implements GenericFutureListener {\n\n private C connection;\n\n private GenericFutureListener parent;\n\n public CloseHandler(C connection, GenericFutureListener parent) {\n super();\n this.connection = connection;\n this.parent = parent;\n }\n\n @Override\n public void operationComplete(ChannelFuture future) throws Exception {\n connectionHolder.compareAndSet(connection, null);\n parent.operationComplete(future);\n }\n }\n\n public CloseHandlerCreator getCloseHandlerCreator() {\n return new CloseHandlerCreator();\n }\n\n public void addExternalConnection(C connection) {\n // if the connection holder is not set, set it to this incoming connection. We'll simply ignore if already set.\n this.connectionHolder.compareAndSet(null, connection);\n }\n\n @Override\n public void close() {\n C c = connectionHolder.getAndSet(null);\n if (c != null) {\n c.getChannel().close();\n }\n }\n}\n"} {"task_id": "Java_2000", "language": "Java", "task_type": "method_body_mid", "source_file": "java/github/apache/drill/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java", "mask_start_position": 3660, "mask_end_position": 3843, "canonical_solution": "// So there is no point propagating the interruption as failure immediately.\n long remainingWaitTimeMills = 120000;\n long startTime = System.currentTimeMillis();", "pre_mask_code": "package org.apache.drill.exec.rpc;\n\nimport com.google.protobuf.Internal.EnumLite;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.util.concurrent.GenericFutureListener;\nimport java.io.Closeable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicReference;\nimport org.apache.drill.shaded.guava.com.google.common.base.Preconditions;\nimport org.apache.drill.shaded.guava.com.google.common.util.concurrent.AbstractFuture;\nimport com.google.protobuf.MessageLite;\n\n/**\n * Manager all connections between two particular bits.\n */\npublic abstract class ReconnectingConnection implements Closeable {\n\n static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ReconnectingConnection.class);\n\n private final AtomicReference connectionHolder = new AtomicReference();\n\n private final String host;\n\n private final int port;\n\n private final HS handshake;\n\n public ReconnectingConnection(HS handshake, String host, int port) {\n Preconditions.checkNotNull(host);\n Preconditions.checkArgument(port > 0);\n this.host = host;\n this.port = port;\n this.handshake = handshake;\n }\n\n protected abstract BasicClient getNewClient();\n\n public > void runCommand(R cmd) {\n // if(logger.isDebugEnabled()) logger.debug(String.format(\"Running command %s sending to host %s:%d\", cmd, host, port));\n C connection = connectionHolder.get();\n if (connection != null) {\n if (connection.isActive()) {\n cmd.connectionAvailable(connection);\n // logger.debug(\"Connection available and active, command run inline.\");\n return;\n } else {\n // remove the old connection. (don't worry if we fail since someone else should have done it.\n connectionHolder.compareAndSet(connection, null);\n }\n }\n /**\n * We've arrived here without a connection, let's make sure only one of us makes a connection. (fyi, another\n * endpoint could create a reverse connection\n */\n synchronized (this) {\n connection = connectionHolder.get();\n if (connection != null) {\n cmd.connectionAvailable(connection);\n } else {\n // logger.debug(\"No connection active, opening client connection.\");\n BasicClient client = getNewClient();\n ConnectionListeningFuture future = new ConnectionListeningFuture<>(cmd);\n client.connectAsClient(future, handshake, host, port);\n future.waitAndRun();\n // logger.debug(\"Connection available and active, command now being run inline.\");\n }\n return;\n }\n }\n\n public class ConnectionListeningFuture extends AbstractFuture implements RpcConnectionHandler {\n\n private RpcCommand cmd;\n\n public ConnectionListeningFuture(RpcCommand cmd) {\n super();\n this.cmd = cmd;\n }\n\n /**\n * Called by\n */\n public void waitAndRun() {\n boolean isInterrupted = false;\n // We want to wait for at least 120 secs when interrupts occur. Establishing a connection fails/succeeds quickly,\n ", "post_mask_code": "\n while (true) {\n try {\n C connection = this.get(remainingWaitTimeMills, TimeUnit.MILLISECONDS);\n if (connection == null) {\n } else {\n cmd.connectionSucceeded(connection);\n // logger.debug(\"Finished connection succeeded activity.\");\n }\n break;\n } catch (final InterruptedException interruptEx) {\n remainingWaitTimeMills -= (System.currentTimeMillis() - startTime);\n startTime = System.currentTimeMillis();\n isInterrupted = true;\n if (remainingWaitTimeMills < 1) {\n cmd.connectionFailed(FailureType.CONNECTION, interruptEx);\n break;\n }\n // Ignore the interrupt and continue to wait until we elapse remainingWaitTimeMills.\n } catch (final ExecutionException | TimeoutException ex) {\n logger.error(\"Failed to establish connection\", ex);\n cmd.connectionFailed(FailureType.CONNECTION, ex);\n break;\n }\n }\n if (isInterrupted) {\n // Preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the\n // interruption and respond to it if it wants to.\n Thread.currentThread().interrupt();\n }\n }\n\n @Override\n public void connectionFailed(FailureType type, Throwable t) {\n set(null);\n cmd.connectionFailed(type, t);\n }\n\n @Override\n public void connectionSucceeded(C incoming) {\n C connection = connectionHolder.get();\n while (true) {\n boolean setted = connectionHolder.compareAndSet(null, incoming);\n if (setted) {\n connection = incoming;\n break;\n }\n connection = connectionHolder.get();\n if (connection != null) {\n break;\n }\n }\n if (connection != incoming) {\n // close the incoming because another channel was created in the mean time (unless this is a self connection).\n logger.debug(\"Closing incoming connection because a connection was already set.\");\n incoming.getChannel().close();\n }\n set(connection);\n }\n }\n\n /**\n * Factory for close handlers *\n */\n public class CloseHandlerCreator {\n\n public GenericFutureListener getHandler(C connection, GenericFutureListener parent) {\n return new CloseHandler(connection, parent);\n }\n }\n\n /**\n * Listens for connection closes and clears connection holder.\n */\n protected class CloseHandler implements GenericFutureListener {\n\n private C connection;\n\n private GenericFutureListener parent;\n\n public CloseHandler(C connection, GenericFutureListener parent) {\n super();\n this.connection = connection;\n this.parent = parent;\n }\n\n @Override\n public void operationComplete(ChannelFuture future) throws Exception {\n connectionHolder.compareAndSet(connection, null);\n parent.operationComplete(future);\n }\n }\n\n public CloseHandlerCreator getCloseHandlerCreator() {\n return new CloseHandlerCreator();\n }\n\n public void addExternalConnection(C connection) {\n // if the connection holder is not set, set it to this incoming connection. We'll simply ignore if already set.\n this.connectionHolder.compareAndSet(null, connection);\n }\n\n @Override\n public void close() {\n C c = connectionHolder.getAndSet(null);\n if (c != null) {\n c.getChannel().close();\n }\n }\n}\n"} {"task_id": "Java_2001", "language": "Java", "task_type": "method_body_bottom", "source_file": "java/github/apache/drill/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java", "mask_start_position": 3856, "mask_end_position": 5382, "canonical_solution": "while (true) {\n try {\n C connection = this.get(remainingWaitTimeMills, TimeUnit.MILLISECONDS);\n if (connection == null) {\n } else {\n cmd.connectionSucceeded(connection);\n // logger.debug(\"Finished connection succeeded activity.\");\n }\n break;\n } catch (final InterruptedException interruptEx) {\n remainingWaitTimeMills -= (System.currentTimeMillis() - startTime);\n startTime = System.currentTimeMillis();\n isInterrupted = true;\n if (remainingWaitTimeMills < 1) {\n cmd.connectionFailed(FailureType.CONNECTION, interruptEx);\n break;\n }\n // Ignore the interrupt and continue to wait until we elapse remainingWaitTimeMills.\n } catch (final ExecutionException | TimeoutException ex) {\n logger.error(\"Failed to establish connection\", ex);\n cmd.connectionFailed(FailureType.CONNECTION, ex);\n break;\n }\n }\n if (isInterrupted) {\n // Preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the\n // interruption and respond to it if it wants to.\n Thread.currentThread().interrupt();\n }\n }", "pre_mask_code": "package org.apache.drill.exec.rpc;\n\nimport com.google.protobuf.Internal.EnumLite;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.util.concurrent.GenericFutureListener;\nimport java.io.Closeable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicReference;\nimport org.apache.drill.shaded.guava.com.google.common.base.Preconditions;\nimport org.apache.drill.shaded.guava.com.google.common.util.concurrent.AbstractFuture;\nimport com.google.protobuf.MessageLite;\n\n/**\n * Manager all connections between two particular bits.\n */\npublic abstract class ReconnectingConnection implements Closeable {\n\n static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ReconnectingConnection.class);\n\n private final AtomicReference connectionHolder = new AtomicReference();\n\n private final String host;\n\n private final int port;\n\n private final HS handshake;\n\n public ReconnectingConnection(HS handshake, String host, int port) {\n Preconditions.checkNotNull(host);\n Preconditions.checkArgument(port > 0);\n this.host = host;\n this.port = port;\n this.handshake = handshake;\n }\n\n protected abstract BasicClient getNewClient();\n\n public > void runCommand(R cmd) {\n // if(logger.isDebugEnabled()) logger.debug(String.format(\"Running command %s sending to host %s:%d\", cmd, host, port));\n C connection = connectionHolder.get();\n if (connection != null) {\n if (connection.isActive()) {\n cmd.connectionAvailable(connection);\n // logger.debug(\"Connection available and active, command run inline.\");\n return;\n } else {\n // remove the old connection. (don't worry if we fail since someone else should have done it.\n connectionHolder.compareAndSet(connection, null);\n }\n }\n /**\n * We've arrived here without a connection, let's make sure only one of us makes a connection. (fyi, another\n * endpoint could create a reverse connection\n */\n synchronized (this) {\n connection = connectionHolder.get();\n if (connection != null) {\n cmd.connectionAvailable(connection);\n } else {\n // logger.debug(\"No connection active, opening client connection.\");\n BasicClient client = getNewClient();\n ConnectionListeningFuture future = new ConnectionListeningFuture<>(cmd);\n client.connectAsClient(future, handshake, host, port);\n future.waitAndRun();\n // logger.debug(\"Connection available and active, command now being run inline.\");\n }\n return;\n }\n }\n\n public class ConnectionListeningFuture extends AbstractFuture implements RpcConnectionHandler {\n\n private RpcCommand cmd;\n\n public ConnectionListeningFuture(RpcCommand cmd) {\n super();\n this.cmd = cmd;\n }\n\n /**\n * Called by\n */\n public void waitAndRun() {\n boolean isInterrupted = false;\n // We want to wait for at least 120 secs when interrupts occur. Establishing a connection fails/succeeds quickly,\n // So there is no point propagating the interruption as failure immediately.\n long remainingWaitTimeMills = 120000;\n long startTime = System.currentTimeMillis();\n ", "post_mask_code": "\n\n @Override\n public void connectionFailed(FailureType type, Throwable t) {\n set(null);\n cmd.connectionFailed(type, t);\n }\n\n @Override\n public void connectionSucceeded(C incoming) {\n C connection = connectionHolder.get();\n while (true) {\n boolean setted = connectionHolder.compareAndSet(null, incoming);\n if (setted) {\n connection = incoming;\n break;\n }\n connection = connectionHolder.get();\n if (connection != null) {\n break;\n }\n }\n if (connection != incoming) {\n // close the incoming because another channel was created in the mean time (unless this is a self connection).\n logger.debug(\"Closing incoming connection because a connection was already set.\");\n incoming.getChannel().close();\n }\n set(connection);\n }\n }\n\n /**\n * Factory for close handlers *\n */\n public class CloseHandlerCreator {\n\n public GenericFutureListener getHandler(C connection, GenericFutureListener parent) {\n return new CloseHandler(connection, parent);\n }\n }\n\n /**\n * Listens for connection closes and clears connection holder.\n */\n protected class CloseHandler implements GenericFutureListener {\n\n private C connection;\n\n private GenericFutureListener parent;\n\n public CloseHandler(C connection, GenericFutureListener parent) {\n super();\n this.connection = connection;\n this.parent = parent;\n }\n\n @Override\n public void operationComplete(ChannelFuture future) throws Exception {\n connectionHolder.compareAndSet(connection, null);\n parent.operationComplete(future);\n }\n }\n\n public CloseHandlerCreator getCloseHandlerCreator() {\n return new CloseHandlerCreator();\n }\n\n public void addExternalConnection(C connection) {\n // if the connection holder is not set, set it to this incoming connection. We'll simply ignore if already set.\n this.connectionHolder.compareAndSet(null, connection);\n }\n\n @Override\n public void close() {\n C c = connectionHolder.getAndSet(null);\n if (c != null) {\n c.getChannel().close();\n }\n }\n}\n"} {"task_id": "Java_2002", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/drill/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java", "mask_start_position": 7818, "mask_end_position": 7834, "canonical_solution": "getAndSet(null);", "pre_mask_code": "package org.apache.drill.exec.rpc;\n\nimport com.google.protobuf.Internal.EnumLite;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.util.concurrent.GenericFutureListener;\nimport java.io.Closeable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicReference;\nimport org.apache.drill.shaded.guava.com.google.common.base.Preconditions;\nimport org.apache.drill.shaded.guava.com.google.common.util.concurrent.AbstractFuture;\nimport com.google.protobuf.MessageLite;\n\n/**\n * Manager all connections between two particular bits.\n */\npublic abstract class ReconnectingConnection implements Closeable {\n\n static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ReconnectingConnection.class);\n\n private final AtomicReference connectionHolder = new AtomicReference();\n\n private final String host;\n\n private final int port;\n\n private final HS handshake;\n\n public ReconnectingConnection(HS handshake, String host, int port) {\n Preconditions.checkNotNull(host);\n Preconditions.checkArgument(port > 0);\n this.host = host;\n this.port = port;\n this.handshake = handshake;\n }\n\n protected abstract BasicClient getNewClient();\n\n public > void runCommand(R cmd) {\n // if(logger.isDebugEnabled()) logger.debug(String.format(\"Running command %s sending to host %s:%d\", cmd, host, port));\n C connection = connectionHolder.get();\n if (connection != null) {\n if (connection.isActive()) {\n cmd.connectionAvailable(connection);\n // logger.debug(\"Connection available and active, command run inline.\");\n return;\n } else {\n // remove the old connection. (don't worry if we fail since someone else should have done it.\n connectionHolder.compareAndSet(connection, null);\n }\n }\n /**\n * We've arrived here without a connection, let's make sure only one of us makes a connection. (fyi, another\n * endpoint could create a reverse connection\n */\n synchronized (this) {\n connection = connectionHolder.get();\n if (connection != null) {\n cmd.connectionAvailable(connection);\n } else {\n // logger.debug(\"No connection active, opening client connection.\");\n BasicClient client = getNewClient();\n ConnectionListeningFuture future = new ConnectionListeningFuture<>(cmd);\n client.connectAsClient(future, handshake, host, port);\n future.waitAndRun();\n // logger.debug(\"Connection available and active, command now being run inline.\");\n }\n return;\n }\n }\n\n public class ConnectionListeningFuture extends AbstractFuture implements RpcConnectionHandler {\n\n private RpcCommand cmd;\n\n public ConnectionListeningFuture(RpcCommand cmd) {\n super();\n this.cmd = cmd;\n }\n\n /**\n * Called by\n */\n public void waitAndRun() {\n boolean isInterrupted = false;\n // We want to wait for at least 120 secs when interrupts occur. Establishing a connection fails/succeeds quickly,\n // So there is no point propagating the interruption as failure immediately.\n long remainingWaitTimeMills = 120000;\n long startTime = System.currentTimeMillis();\n while (true) {\n try {\n C connection = this.get(remainingWaitTimeMills, TimeUnit.MILLISECONDS);\n if (connection == null) {\n } else {\n cmd.connectionSucceeded(connection);\n // logger.debug(\"Finished connection succeeded activity.\");\n }\n break;\n } catch (final InterruptedException interruptEx) {\n remainingWaitTimeMills -= (System.currentTimeMillis() - startTime);\n startTime = System.currentTimeMillis();\n isInterrupted = true;\n if (remainingWaitTimeMills < 1) {\n cmd.connectionFailed(FailureType.CONNECTION, interruptEx);\n break;\n }\n // Ignore the interrupt and continue to wait until we elapse remainingWaitTimeMills.\n } catch (final ExecutionException | TimeoutException ex) {\n logger.error(\"Failed to establish connection\", ex);\n cmd.connectionFailed(FailureType.CONNECTION, ex);\n break;\n }\n }\n if (isInterrupted) {\n // Preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the\n // interruption and respond to it if it wants to.\n Thread.currentThread().interrupt();\n }\n }\n\n @Override\n public void connectionFailed(FailureType type, Throwable t) {\n set(null);\n cmd.connectionFailed(type, t);\n }\n\n @Override\n public void connectionSucceeded(C incoming) {\n C connection = connectionHolder.get();\n while (true) {\n boolean setted = connectionHolder.compareAndSet(null, incoming);\n if (setted) {\n connection = incoming;\n break;\n }\n connection = connectionHolder.get();\n if (connection != null) {\n break;\n }\n }\n if (connection != incoming) {\n // close the incoming because another channel was created in the mean time (unless this is a self connection).\n logger.debug(\"Closing incoming connection because a connection was already set.\");\n incoming.getChannel().close();\n }\n set(connection);\n }\n }\n\n /**\n * Factory for close handlers *\n */\n public class CloseHandlerCreator {\n\n public GenericFutureListener getHandler(C connection, GenericFutureListener parent) {\n return new CloseHandler(connection, parent);\n }\n }\n\n /**\n * Listens for connection closes and clears connection holder.\n */\n protected class CloseHandler implements GenericFutureListener {\n\n private C connection;\n\n private GenericFutureListener parent;\n\n public CloseHandler(C connection, GenericFutureListener parent) {\n super();\n this.connection = connection;\n this.parent = parent;\n }\n\n @Override\n public void operationComplete(ChannelFuture future) throws Exception {\n connectionHolder.compareAndSet(connection, null);\n parent.operationComplete(future);\n }\n }\n\n public CloseHandlerCreator getCloseHandlerCreator() {\n return new CloseHandlerCreator();\n }\n\n public void addExternalConnection(C connection) {\n // if the connection holder is not set, set it to this incoming connection. We'll simply ignore if already set.\n this.connectionHolder.compareAndSet(null, connection);\n }\n\n @Override\n public void close() {\n C c = connectionHolder.", "post_mask_code": "\n if (c != null) {\n c.getChannel().close();\n }\n }\n}\n"} {"task_id": "Java_2003", "language": "Java", "task_type": "if_statement", "source_file": "java/github/apache/drill/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java", "mask_start_position": 6064, "mask_end_position": 6380, "canonical_solution": "if (connection != incoming) {\n // close the incoming because another channel was created in the mean time (unless this is a self connection).\n logger.debug(\"Closing incoming connection because a connection was already set.\");\n incoming.getChannel().close();\n }", "pre_mask_code": "package org.apache.drill.exec.rpc;\n\nimport com.google.protobuf.Internal.EnumLite;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.util.concurrent.GenericFutureListener;\nimport java.io.Closeable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicReference;\nimport org.apache.drill.shaded.guava.com.google.common.base.Preconditions;\nimport org.apache.drill.shaded.guava.com.google.common.util.concurrent.AbstractFuture;\nimport com.google.protobuf.MessageLite;\n\n/**\n * Manager all connections between two particular bits.\n */\npublic abstract class ReconnectingConnection implements Closeable {\n\n static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ReconnectingConnection.class);\n\n private final AtomicReference connectionHolder = new AtomicReference();\n\n private final String host;\n\n private final int port;\n\n private final HS handshake;\n\n public ReconnectingConnection(HS handshake, String host, int port) {\n Preconditions.checkNotNull(host);\n Preconditions.checkArgument(port > 0);\n this.host = host;\n this.port = port;\n this.handshake = handshake;\n }\n\n protected abstract BasicClient getNewClient();\n\n public > void runCommand(R cmd) {\n // if(logger.isDebugEnabled()) logger.debug(String.format(\"Running command %s sending to host %s:%d\", cmd, host, port));\n C connection = connectionHolder.get();\n if (connection != null) {\n if (connection.isActive()) {\n cmd.connectionAvailable(connection);\n // logger.debug(\"Connection available and active, command run inline.\");\n return;\n } else {\n // remove the old connection. (don't worry if we fail since someone else should have done it.\n connectionHolder.compareAndSet(connection, null);\n }\n }\n /**\n * We've arrived here without a connection, let's make sure only one of us makes a connection. (fyi, another\n * endpoint could create a reverse connection\n */\n synchronized (this) {\n connection = connectionHolder.get();\n if (connection != null) {\n cmd.connectionAvailable(connection);\n } else {\n // logger.debug(\"No connection active, opening client connection.\");\n BasicClient client = getNewClient();\n ConnectionListeningFuture future = new ConnectionListeningFuture<>(cmd);\n client.connectAsClient(future, handshake, host, port);\n future.waitAndRun();\n // logger.debug(\"Connection available and active, command now being run inline.\");\n }\n return;\n }\n }\n\n public class ConnectionListeningFuture extends AbstractFuture implements RpcConnectionHandler {\n\n private RpcCommand cmd;\n\n public ConnectionListeningFuture(RpcCommand cmd) {\n super();\n this.cmd = cmd;\n }\n\n /**\n * Called by\n */\n public void waitAndRun() {\n boolean isInterrupted = false;\n // We want to wait for at least 120 secs when interrupts occur. Establishing a connection fails/succeeds quickly,\n // So there is no point propagating the interruption as failure immediately.\n long remainingWaitTimeMills = 120000;\n long startTime = System.currentTimeMillis();\n while (true) {\n try {\n C connection = this.get(remainingWaitTimeMills, TimeUnit.MILLISECONDS);\n if (connection == null) {\n } else {\n cmd.connectionSucceeded(connection);\n // logger.debug(\"Finished connection succeeded activity.\");\n }\n break;\n } catch (final InterruptedException interruptEx) {\n remainingWaitTimeMills -= (System.currentTimeMillis() - startTime);\n startTime = System.currentTimeMillis();\n isInterrupted = true;\n if (remainingWaitTimeMills < 1) {\n cmd.connectionFailed(FailureType.CONNECTION, interruptEx);\n break;\n }\n // Ignore the interrupt and continue to wait until we elapse remainingWaitTimeMills.\n } catch (final ExecutionException | TimeoutException ex) {\n logger.error(\"Failed to establish connection\", ex);\n cmd.connectionFailed(FailureType.CONNECTION, ex);\n break;\n }\n }\n if (isInterrupted) {\n // Preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the\n // interruption and respond to it if it wants to.\n Thread.currentThread().interrupt();\n }\n }\n\n @Override\n public void connectionFailed(FailureType type, Throwable t) {\n set(null);\n cmd.connectionFailed(type, t);\n }\n\n @Override\n public void connectionSucceeded(C incoming) {\n C connection = connectionHolder.get();\n while (true) {\n boolean setted = connectionHolder.compareAndSet(null, incoming);\n if (setted) {\n connection = incoming;\n break;\n }\n connection = connectionHolder.get();\n if (connection != null) {\n break;\n }\n }\n ", "post_mask_code": "\n set(connection);\n }\n }\n\n /**\n * Factory for close handlers *\n */\n public class CloseHandlerCreator {\n\n public GenericFutureListener getHandler(C connection, GenericFutureListener parent) {\n return new CloseHandler(connection, parent);\n }\n }\n\n /**\n * Listens for connection closes and clears connection holder.\n */\n protected class CloseHandler implements GenericFutureListener {\n\n private C connection;\n\n private GenericFutureListener parent;\n\n public CloseHandler(C connection, GenericFutureListener parent) {\n super();\n this.connection = connection;\n this.parent = parent;\n }\n\n @Override\n public void operationComplete(ChannelFuture future) throws Exception {\n connectionHolder.compareAndSet(connection, null);\n parent.operationComplete(future);\n }\n }\n\n public CloseHandlerCreator getCloseHandlerCreator() {\n return new CloseHandlerCreator();\n }\n\n public void addExternalConnection(C connection) {\n // if the connection holder is not set, set it to this incoming connection. We'll simply ignore if already set.\n this.connectionHolder.compareAndSet(null, connection);\n }\n\n @Override\n public void close() {\n C c = connectionHolder.getAndSet(null);\n if (c != null) {\n c.getChannel().close();\n }\n }\n}\n"} {"task_id": "Java_2004", "language": "Java", "task_type": "while_statement", "source_file": "java/github/apache/drill/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java", "mask_start_position": 5684, "mask_end_position": 6051, "canonical_solution": "while (true) {\n boolean setted = connectionHolder.compareAndSet(null, incoming);\n if (setted) {\n connection = incoming;\n break;\n }\n connection = connectionHolder.get();\n if (connection != null) {\n break;\n }\n }", "pre_mask_code": "package org.apache.drill.exec.rpc;\n\nimport com.google.protobuf.Internal.EnumLite;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.util.concurrent.GenericFutureListener;\nimport java.io.Closeable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicReference;\nimport org.apache.drill.shaded.guava.com.google.common.base.Preconditions;\nimport org.apache.drill.shaded.guava.com.google.common.util.concurrent.AbstractFuture;\nimport com.google.protobuf.MessageLite;\n\n/**\n * Manager all connections between two particular bits.\n */\npublic abstract class ReconnectingConnection implements Closeable {\n\n static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ReconnectingConnection.class);\n\n private final AtomicReference connectionHolder = new AtomicReference();\n\n private final String host;\n\n private final int port;\n\n private final HS handshake;\n\n public ReconnectingConnection(HS handshake, String host, int port) {\n Preconditions.checkNotNull(host);\n Preconditions.checkArgument(port > 0);\n this.host = host;\n this.port = port;\n this.handshake = handshake;\n }\n\n protected abstract BasicClient getNewClient();\n\n public > void runCommand(R cmd) {\n // if(logger.isDebugEnabled()) logger.debug(String.format(\"Running command %s sending to host %s:%d\", cmd, host, port));\n C connection = connectionHolder.get();\n if (connection != null) {\n if (connection.isActive()) {\n cmd.connectionAvailable(connection);\n // logger.debug(\"Connection available and active, command run inline.\");\n return;\n } else {\n // remove the old connection. (don't worry if we fail since someone else should have done it.\n connectionHolder.compareAndSet(connection, null);\n }\n }\n /**\n * We've arrived here without a connection, let's make sure only one of us makes a connection. (fyi, another\n * endpoint could create a reverse connection\n */\n synchronized (this) {\n connection = connectionHolder.get();\n if (connection != null) {\n cmd.connectionAvailable(connection);\n } else {\n // logger.debug(\"No connection active, opening client connection.\");\n BasicClient client = getNewClient();\n ConnectionListeningFuture future = new ConnectionListeningFuture<>(cmd);\n client.connectAsClient(future, handshake, host, port);\n future.waitAndRun();\n // logger.debug(\"Connection available and active, command now being run inline.\");\n }\n return;\n }\n }\n\n public class ConnectionListeningFuture extends AbstractFuture implements RpcConnectionHandler {\n\n private RpcCommand cmd;\n\n public ConnectionListeningFuture(RpcCommand cmd) {\n super();\n this.cmd = cmd;\n }\n\n /**\n * Called by\n */\n public void waitAndRun() {\n boolean isInterrupted = false;\n // We want to wait for at least 120 secs when interrupts occur. Establishing a connection fails/succeeds quickly,\n // So there is no point propagating the interruption as failure immediately.\n long remainingWaitTimeMills = 120000;\n long startTime = System.currentTimeMillis();\n while (true) {\n try {\n C connection = this.get(remainingWaitTimeMills, TimeUnit.MILLISECONDS);\n if (connection == null) {\n } else {\n cmd.connectionSucceeded(connection);\n // logger.debug(\"Finished connection succeeded activity.\");\n }\n break;\n } catch (final InterruptedException interruptEx) {\n remainingWaitTimeMills -= (System.currentTimeMillis() - startTime);\n startTime = System.currentTimeMillis();\n isInterrupted = true;\n if (remainingWaitTimeMills < 1) {\n cmd.connectionFailed(FailureType.CONNECTION, interruptEx);\n break;\n }\n // Ignore the interrupt and continue to wait until we elapse remainingWaitTimeMills.\n } catch (final ExecutionException | TimeoutException ex) {\n logger.error(\"Failed to establish connection\", ex);\n cmd.connectionFailed(FailureType.CONNECTION, ex);\n break;\n }\n }\n if (isInterrupted) {\n // Preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the\n // interruption and respond to it if it wants to.\n Thread.currentThread().interrupt();\n }\n }\n\n @Override\n public void connectionFailed(FailureType type, Throwable t) {\n set(null);\n cmd.connectionFailed(type, t);\n }\n\n @Override\n public void connectionSucceeded(C incoming) {\n C connection = connectionHolder.get();\n ", "post_mask_code": "\n if (connection != incoming) {\n // close the incoming because another channel was created in the mean time (unless this is a self connection).\n logger.debug(\"Closing incoming connection because a connection was already set.\");\n incoming.getChannel().close();\n }\n set(connection);\n }\n }\n\n /**\n * Factory for close handlers *\n */\n public class CloseHandlerCreator {\n\n public GenericFutureListener getHandler(C connection, GenericFutureListener parent) {\n return new CloseHandler(connection, parent);\n }\n }\n\n /**\n * Listens for connection closes and clears connection holder.\n */\n protected class CloseHandler implements GenericFutureListener {\n\n private C connection;\n\n private GenericFutureListener parent;\n\n public CloseHandler(C connection, GenericFutureListener parent) {\n super();\n this.connection = connection;\n this.parent = parent;\n }\n\n @Override\n public void operationComplete(ChannelFuture future) throws Exception {\n connectionHolder.compareAndSet(connection, null);\n parent.operationComplete(future);\n }\n }\n\n public CloseHandlerCreator getCloseHandlerCreator() {\n return new CloseHandlerCreator();\n }\n\n public void addExternalConnection(C connection) {\n // if the connection holder is not set, set it to this incoming connection. We'll simply ignore if already set.\n this.connectionHolder.compareAndSet(null, connection);\n }\n\n @Override\n public void close() {\n C c = connectionHolder.getAndSet(null);\n if (c != null) {\n c.getChannel().close();\n }\n }\n}\n"} {"task_id": "Java_2005", "language": "Java", "task_type": "method_signature", "source_file": "java/github/panda-lang/panda/panda/src/main/java/panda/interpreter/syntax/scope/StandaloneExpression.java", "mask_start_position": 700, "mask_end_position": 734, "canonical_solution": "public Expression getExpression() ", "pre_mask_code": "package panda.interpreter.syntax.scope;\n\nimport panda.interpreter.architecture.dynamic.AbstractExecutableStatement;\nimport panda.interpreter.architecture.expression.Expression;\nimport panda.interpreter.source.Localizable;\nimport panda.interpreter.runtime.ProcessStack;\n\npublic class StandaloneExpression extends AbstractExecutableStatement {\n\n private final Expression expression;\n\n public StandaloneExpression(Localizable localizable, Expression expression) {\n super(localizable);\n this.expression = expression;\n }\n\n @Override\n public Object execute(ProcessStack stack, Object instance) throws Exception {\n return expression.evaluate(stack, instance);\n }\n\n ", "post_mask_code": "{\n return expression;\n }\n}\n"} {"task_id": "Java_2006", "language": "Java", "task_type": "method_body", "source_file": "java/github/panda-lang/panda/panda/src/main/java/panda/interpreter/syntax/scope/StandaloneExpression.java", "mask_start_position": 634, "mask_end_position": 694, "canonical_solution": "{\n return expression.evaluate(stack, instance);\n }", "pre_mask_code": "package panda.interpreter.syntax.scope;\n\nimport panda.interpreter.architecture.dynamic.AbstractExecutableStatement;\nimport panda.interpreter.architecture.expression.Expression;\nimport panda.interpreter.source.Localizable;\nimport panda.interpreter.runtime.ProcessStack;\n\npublic class StandaloneExpression extends AbstractExecutableStatement {\n\n private final Expression expression;\n\n public StandaloneExpression(Localizable localizable, Expression expression) {\n super(localizable);\n this.expression = expression;\n }\n\n @Override\n public Object execute(ProcessStack stack, Object instance) throws Exception ", "post_mask_code": "\n\n public Expression getExpression() {\n return expression;\n }\n}\n"} {"task_id": "Java_2007", "language": "Java", "task_type": "single_line", "source_file": "java/github/panda-lang/panda/panda/src/main/java/panda/interpreter/syntax/scope/StandaloneExpression.java", "mask_start_position": 759, "mask_end_position": 762, "canonical_solution": "on;", "pre_mask_code": "package panda.interpreter.syntax.scope;\n\nimport panda.interpreter.architecture.dynamic.AbstractExecutableStatement;\nimport panda.interpreter.architecture.expression.Expression;\nimport panda.interpreter.source.Localizable;\nimport panda.interpreter.runtime.ProcessStack;\n\npublic class StandaloneExpression extends AbstractExecutableStatement {\n\n private final Expression expression;\n\n public StandaloneExpression(Localizable localizable, Expression expression) {\n super(localizable);\n this.expression = expression;\n }\n\n @Override\n public Object execute(ProcessStack stack, Object instance) throws Exception {\n return expression.evaluate(stack, instance);\n }\n\n public Expression getExpression() {\n return expressi", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2008", "language": "Java", "task_type": "method_signature", "source_file": "java/github/udacity/ud405/1.8.02-Solution-AddTheHUD/core/src/com/udacity/gamedev/icicles/Player.java", "mask_start_position": 674, "mask_end_position": 693, "canonical_solution": "public void init() ", "pre_mask_code": "package com.udacity.gamedev.icicles;\n\nimport com.badlogic.gdx.Gdx;\nimport com.badlogic.gdx.Input.Keys;\nimport com.badlogic.gdx.graphics.glutils.ShapeRenderer;\nimport com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;\nimport com.badlogic.gdx.math.Vector2;\nimport com.badlogic.gdx.utils.viewport.Viewport;\n\npublic class Player {\n\n public static final String TAG = Player.class.getName();\n\n Vector2 position;\n\n Viewport viewport;\n\n // TODO: Add counter for number of deaths\n int deaths;\n\n public Player(Viewport viewport) {\n this.viewport = viewport;\n // TODO: Set number of deaths to zero\n deaths = 0;\n init();\n }\n\n ", "post_mask_code": "{\n position = new Vector2(viewport.getWorldWidth() / 2, Constants.PLAYER_HEAD_HEIGHT);\n }\n\n public void update(float delta) {\n if (Gdx.input.isKeyPressed(Keys.LEFT)) {\n position.x -= delta * Constants.PLAYER_MOVEMENT_SPEED;\n } else if (Gdx.input.isKeyPressed(Keys.RIGHT)) {\n position.x += delta * Constants.PLAYER_MOVEMENT_SPEED;\n }\n float accelerometerInput = -Gdx.input.getAccelerometerY() / (Constants.GRAVITATIONAL_ACCELERATION * Constants.ACCELEROMETER_SENSITIVITY);\n position.x += -delta * accelerometerInput * Constants.PLAYER_MOVEMENT_SPEED;\n ensureInBounds();\n }\n\n private void ensureInBounds() {\n if (position.x - Constants.PLAYER_HEAD_RADIUS < 0) {\n position.x = Constants.PLAYER_HEAD_RADIUS;\n }\n if (position.x + Constants.PLAYER_HEAD_RADIUS > viewport.getWorldWidth()) {\n position.x = viewport.getWorldWidth() - Constants.PLAYER_HEAD_RADIUS;\n }\n }\n\n public boolean hitByIcicle(Icicles icicles) {\n boolean isHit = false;\n for (Icicle icicle : icicles.icicleList) {\n if (icicle.position.dst(position) < Constants.PLAYER_HEAD_RADIUS) {\n isHit = true;\n }\n }\n // TODO: If the player was hit, increment death counter\n if (isHit) {\n deaths += 1;\n }\n return isHit;\n }\n\n public void render(ShapeRenderer renderer) {\n renderer.setColor(Constants.PLAYER_COLOR);\n renderer.set(ShapeType.Filled);\n renderer.circle(position.x, position.y, Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_HEAD_SEGMENTS);\n Vector2 torsoTop = new Vector2(position.x, position.y - Constants.PLAYER_HEAD_RADIUS);\n Vector2 torsoBottom = new Vector2(torsoTop.x, torsoTop.y - 2 * Constants.PLAYER_HEAD_RADIUS);\n renderer.rectLine(torsoTop, torsoBottom, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoTop.x, torsoTop.y, torsoTop.x + Constants.PLAYER_HEAD_RADIUS, torsoTop.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoTop.x, torsoTop.y, torsoTop.x - Constants.PLAYER_HEAD_RADIUS, torsoTop.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoBottom.x, torsoBottom.y, torsoBottom.x + Constants.PLAYER_HEAD_RADIUS, torsoBottom.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoBottom.x, torsoBottom.y, torsoBottom.x - Constants.PLAYER_HEAD_RADIUS, torsoBottom.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n }\n}\n"} {"task_id": "Java_2009", "language": "Java", "task_type": "method_body", "source_file": "java/github/udacity/ud405/1.8.02-Solution-AddTheHUD/core/src/com/udacity/gamedev/icicles/Player.java", "mask_start_position": 1380, "mask_end_position": 1689, "canonical_solution": "{\n if (position.x - Constants.PLAYER_HEAD_RADIUS < 0) {\n position.x = Constants.PLAYER_HEAD_RADIUS;\n }\n if (position.x + Constants.PLAYER_HEAD_RADIUS > viewport.getWorldWidth()) {\n position.x = viewport.getWorldWidth() - Constants.PLAYER_HEAD_RADIUS;\n }\n }", "pre_mask_code": "package com.udacity.gamedev.icicles;\n\nimport com.badlogic.gdx.Gdx;\nimport com.badlogic.gdx.Input.Keys;\nimport com.badlogic.gdx.graphics.glutils.ShapeRenderer;\nimport com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;\nimport com.badlogic.gdx.math.Vector2;\nimport com.badlogic.gdx.utils.viewport.Viewport;\n\npublic class Player {\n\n public static final String TAG = Player.class.getName();\n\n Vector2 position;\n\n Viewport viewport;\n\n // TODO: Add counter for number of deaths\n int deaths;\n\n public Player(Viewport viewport) {\n this.viewport = viewport;\n // TODO: Set number of deaths to zero\n deaths = 0;\n init();\n }\n\n public void init() {\n position = new Vector2(viewport.getWorldWidth() / 2, Constants.PLAYER_HEAD_HEIGHT);\n }\n\n public void update(float delta) {\n if (Gdx.input.isKeyPressed(Keys.LEFT)) {\n position.x -= delta * Constants.PLAYER_MOVEMENT_SPEED;\n } else if (Gdx.input.isKeyPressed(Keys.RIGHT)) {\n position.x += delta * Constants.PLAYER_MOVEMENT_SPEED;\n }\n float accelerometerInput = -Gdx.input.getAccelerometerY() / (Constants.GRAVITATIONAL_ACCELERATION * Constants.ACCELEROMETER_SENSITIVITY);\n position.x += -delta * accelerometerInput * Constants.PLAYER_MOVEMENT_SPEED;\n ensureInBounds();\n }\n\n private void ensureInBounds() ", "post_mask_code": "\n\n public boolean hitByIcicle(Icicles icicles) {\n boolean isHit = false;\n for (Icicle icicle : icicles.icicleList) {\n if (icicle.position.dst(position) < Constants.PLAYER_HEAD_RADIUS) {\n isHit = true;\n }\n }\n // TODO: If the player was hit, increment death counter\n if (isHit) {\n deaths += 1;\n }\n return isHit;\n }\n\n public void render(ShapeRenderer renderer) {\n renderer.setColor(Constants.PLAYER_COLOR);\n renderer.set(ShapeType.Filled);\n renderer.circle(position.x, position.y, Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_HEAD_SEGMENTS);\n Vector2 torsoTop = new Vector2(position.x, position.y - Constants.PLAYER_HEAD_RADIUS);\n Vector2 torsoBottom = new Vector2(torsoTop.x, torsoTop.y - 2 * Constants.PLAYER_HEAD_RADIUS);\n renderer.rectLine(torsoTop, torsoBottom, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoTop.x, torsoTop.y, torsoTop.x + Constants.PLAYER_HEAD_RADIUS, torsoTop.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoTop.x, torsoTop.y, torsoTop.x - Constants.PLAYER_HEAD_RADIUS, torsoTop.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoBottom.x, torsoBottom.y, torsoBottom.x + Constants.PLAYER_HEAD_RADIUS, torsoBottom.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoBottom.x, torsoBottom.y, torsoBottom.x - Constants.PLAYER_HEAD_RADIUS, torsoBottom.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n }\n}\n"} {"task_id": "Java_2010", "language": "Java", "task_type": "single_line", "source_file": "java/github/udacity/ud405/1.8.02-Solution-AddTheHUD/core/src/com/udacity/gamedev/icicles/Player.java", "mask_start_position": 2854, "mask_end_position": 2964, "canonical_solution": "Top.x - Constants.PLAYER_HEAD_RADIUS, torsoTop.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);", "pre_mask_code": "package com.udacity.gamedev.icicles;\n\nimport com.badlogic.gdx.Gdx;\nimport com.badlogic.gdx.Input.Keys;\nimport com.badlogic.gdx.graphics.glutils.ShapeRenderer;\nimport com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;\nimport com.badlogic.gdx.math.Vector2;\nimport com.badlogic.gdx.utils.viewport.Viewport;\n\npublic class Player {\n\n public static final String TAG = Player.class.getName();\n\n Vector2 position;\n\n Viewport viewport;\n\n // TODO: Add counter for number of deaths\n int deaths;\n\n public Player(Viewport viewport) {\n this.viewport = viewport;\n // TODO: Set number of deaths to zero\n deaths = 0;\n init();\n }\n\n public void init() {\n position = new Vector2(viewport.getWorldWidth() / 2, Constants.PLAYER_HEAD_HEIGHT);\n }\n\n public void update(float delta) {\n if (Gdx.input.isKeyPressed(Keys.LEFT)) {\n position.x -= delta * Constants.PLAYER_MOVEMENT_SPEED;\n } else if (Gdx.input.isKeyPressed(Keys.RIGHT)) {\n position.x += delta * Constants.PLAYER_MOVEMENT_SPEED;\n }\n float accelerometerInput = -Gdx.input.getAccelerometerY() / (Constants.GRAVITATIONAL_ACCELERATION * Constants.ACCELEROMETER_SENSITIVITY);\n position.x += -delta * accelerometerInput * Constants.PLAYER_MOVEMENT_SPEED;\n ensureInBounds();\n }\n\n private void ensureInBounds() {\n if (position.x - Constants.PLAYER_HEAD_RADIUS < 0) {\n position.x = Constants.PLAYER_HEAD_RADIUS;\n }\n if (position.x + Constants.PLAYER_HEAD_RADIUS > viewport.getWorldWidth()) {\n position.x = viewport.getWorldWidth() - Constants.PLAYER_HEAD_RADIUS;\n }\n }\n\n public boolean hitByIcicle(Icicles icicles) {\n boolean isHit = false;\n for (Icicle icicle : icicles.icicleList) {\n if (icicle.position.dst(position) < Constants.PLAYER_HEAD_RADIUS) {\n isHit = true;\n }\n }\n // TODO: If the player was hit, increment death counter\n if (isHit) {\n deaths += 1;\n }\n return isHit;\n }\n\n public void render(ShapeRenderer renderer) {\n renderer.setColor(Constants.PLAYER_COLOR);\n renderer.set(ShapeType.Filled);\n renderer.circle(position.x, position.y, Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_HEAD_SEGMENTS);\n Vector2 torsoTop = new Vector2(position.x, position.y - Constants.PLAYER_HEAD_RADIUS);\n Vector2 torsoBottom = new Vector2(torsoTop.x, torsoTop.y - 2 * Constants.PLAYER_HEAD_RADIUS);\n renderer.rectLine(torsoTop, torsoBottom, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoTop.x, torsoTop.y, torsoTop.x + Constants.PLAYER_HEAD_RADIUS, torsoTop.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoTop.x, torsoTop.y, torso", "post_mask_code": "\n renderer.rectLine(torsoBottom.x, torsoBottom.y, torsoBottom.x + Constants.PLAYER_HEAD_RADIUS, torsoBottom.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoBottom.x, torsoBottom.y, torsoBottom.x - Constants.PLAYER_HEAD_RADIUS, torsoBottom.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n }\n}\n"} {"task_id": "Java_2011", "language": "Java", "task_type": "if_statement", "source_file": "java/github/udacity/ud405/1.8.02-Solution-AddTheHUD/core/src/com/udacity/gamedev/icicles/Player.java", "mask_start_position": 1516, "mask_end_position": 1683, "canonical_solution": "if (position.x + Constants.PLAYER_HEAD_RADIUS > viewport.getWorldWidth()) {\n position.x = viewport.getWorldWidth() - Constants.PLAYER_HEAD_RADIUS;\n }", "pre_mask_code": "package com.udacity.gamedev.icicles;\n\nimport com.badlogic.gdx.Gdx;\nimport com.badlogic.gdx.Input.Keys;\nimport com.badlogic.gdx.graphics.glutils.ShapeRenderer;\nimport com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;\nimport com.badlogic.gdx.math.Vector2;\nimport com.badlogic.gdx.utils.viewport.Viewport;\n\npublic class Player {\n\n public static final String TAG = Player.class.getName();\n\n Vector2 position;\n\n Viewport viewport;\n\n // TODO: Add counter for number of deaths\n int deaths;\n\n public Player(Viewport viewport) {\n this.viewport = viewport;\n // TODO: Set number of deaths to zero\n deaths = 0;\n init();\n }\n\n public void init() {\n position = new Vector2(viewport.getWorldWidth() / 2, Constants.PLAYER_HEAD_HEIGHT);\n }\n\n public void update(float delta) {\n if (Gdx.input.isKeyPressed(Keys.LEFT)) {\n position.x -= delta * Constants.PLAYER_MOVEMENT_SPEED;\n } else if (Gdx.input.isKeyPressed(Keys.RIGHT)) {\n position.x += delta * Constants.PLAYER_MOVEMENT_SPEED;\n }\n float accelerometerInput = -Gdx.input.getAccelerometerY() / (Constants.GRAVITATIONAL_ACCELERATION * Constants.ACCELEROMETER_SENSITIVITY);\n position.x += -delta * accelerometerInput * Constants.PLAYER_MOVEMENT_SPEED;\n ensureInBounds();\n }\n\n private void ensureInBounds() {\n if (position.x - Constants.PLAYER_HEAD_RADIUS < 0) {\n position.x = Constants.PLAYER_HEAD_RADIUS;\n }\n ", "post_mask_code": "\n }\n\n public boolean hitByIcicle(Icicles icicles) {\n boolean isHit = false;\n for (Icicle icicle : icicles.icicleList) {\n if (icicle.position.dst(position) < Constants.PLAYER_HEAD_RADIUS) {\n isHit = true;\n }\n }\n // TODO: If the player was hit, increment death counter\n if (isHit) {\n deaths += 1;\n }\n return isHit;\n }\n\n public void render(ShapeRenderer renderer) {\n renderer.setColor(Constants.PLAYER_COLOR);\n renderer.set(ShapeType.Filled);\n renderer.circle(position.x, position.y, Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_HEAD_SEGMENTS);\n Vector2 torsoTop = new Vector2(position.x, position.y - Constants.PLAYER_HEAD_RADIUS);\n Vector2 torsoBottom = new Vector2(torsoTop.x, torsoTop.y - 2 * Constants.PLAYER_HEAD_RADIUS);\n renderer.rectLine(torsoTop, torsoBottom, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoTop.x, torsoTop.y, torsoTop.x + Constants.PLAYER_HEAD_RADIUS, torsoTop.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoTop.x, torsoTop.y, torsoTop.x - Constants.PLAYER_HEAD_RADIUS, torsoTop.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoBottom.x, torsoBottom.y, torsoBottom.x + Constants.PLAYER_HEAD_RADIUS, torsoBottom.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n renderer.rectLine(torsoBottom.x, torsoBottom.y, torsoBottom.x - Constants.PLAYER_HEAD_RADIUS, torsoBottom.y - Constants.PLAYER_HEAD_RADIUS, Constants.PLAYER_LIMB_WIDTH);\n }\n}\n"} {"task_id": "Java_2012", "language": "Java", "task_type": "method_signature", "source_file": "java/github/yezheng1981/Java-Geometry-Expert/wprover/JExPanel.java", "mask_start_position": 3753, "mask_end_position": 3798, "canonical_solution": "public void componentShown(ComponentEvent e) ", "pre_mask_code": "package wprover;\n\nimport javax.swing.*;\nimport java.awt.event.*;\nimport java.awt.*;\nimport java.net.URL;\n\nclass JExPanel extends JPanel implements ActionListener, MouseListener, MouseMotionListener, ComponentListener {\n\n drawProcess dp;\n\n static ImageIcon icoa;\n\n static ImageIcon icos;\n\n JToggleButton button;\n\n Timer timer = null;\n\n public void paint(Graphics g) {\n super.paint(g);\n if (dp != null)\n dp.paintPoint(g);\n }\n\n public JExPanel() {\n super();\n this.setLayout(null);\n this.addMouseListener(this);\n this.addMouseMotionListener(this);\n this.addComponentListener(this);\n this.setBackground(new Color(228, 236, 252));\n URL imageURL = GExpert.class.getResource(\"images/animate_start.gif\");\n ImageIcon image = new ImageIcon(imageURL);\n URL imageURL1 = GExpert.class.getResource(\"images/animate_stop.gif\");\n ImageIcon image1 = new ImageIcon(imageURL1);\n button = new JToggleButton(image) {\n\n public Dimension getPreferredSize() {\n return new Dimension(30, 28);\n }\n };\n this.add(button);\n button.addActionListener(this);\n Dimension dm = this.getSize();\n button.setBounds(new Rectangle(0, (int) dm.getHeight() - 28, 32, 28));\n button.setSelectedIcon(image1);\n }\n\n public static void setAinimateIcon(ImageIcon ico1, ImageIcon ico2) {\n icoa = ico1;\n icos = ico2;\n }\n\n public Dimension getPreferredSize() {\n return new Dimension(600, 400);\n }\n\n public void setdrawP(drawProcess dp) {\n this.dp = dp;\n if (timer != null)\n timer.stop();\n if (dp.animate != null) {\n AnimateC ant = dp.animate;\n if (timer == null)\n timer = new Timer(ant.getInitValue(), this);\n else\n timer.setDelay(ant.getInitValue());\n timer.start();\n button.setIcon(icos);\n button.setVisible(true);\n } else\n button.setVisible(false);\n }\n\n public void actionPerformed(ActionEvent e) {\n if (e.getSource() == button) {\n if (!timer.isRunning()) {\n dp.animationStart();\n button.setIcon(icos);\n timer.start();\n } else {\n dp.animationStop();\n button.setIcon(icoa);\n timer.stop();\n }\n } else if (e.getSource() == timer) {\n dp.animationOntime();\n this.repaint();\n }\n }\n\n public void mouseClicked(MouseEvent e) {\n if (e.getClickCount() > 1)\n dp.DWMouseDbClick(e.getX(), e.getY());\n if (e.getButton() == MouseEvent.BUTTON3)\n dp.DWMouseRightClick(e.getX(), e.getY());\n }\n\n public void mousePressed(MouseEvent e) {\n dp.DWButtonDown(e.getX(), e.getY());\n repaint();\n }\n\n public void mouseReleased(MouseEvent e) {\n dp.DWButtonUp(e.getX(), e.getY());\n repaint();\n }\n\n public void mouseEntered(MouseEvent e) {\n }\n\n public void mouseExited(MouseEvent e) {\n }\n\n public void mouseDragged(MouseEvent e) {\n dp.DWMouseDrag(e.getX(), e.getY());\n this.repaint();\n }\n\n public void mouseMoved(MouseEvent e) {\n dp.DWMouseMove(e.getX(), e.getY());\n this.repaint();\n }\n\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n dp.paintPoint(g);\n }\n\n public void componentResized(ComponentEvent e) {\n Dimension dm = this.getSize();\n button.setBounds(new Rectangle(0, (int) dm.getHeight() - 28, 32, 28));\n }\n\n public void componentMoved(ComponentEvent e) {\n }\n\n ", "post_mask_code": "{\n }\n\n public void componentHidden(ComponentEvent e) {\n timer.stop();\n }\n}\n"} {"task_id": "Java_2013", "language": "Java", "task_type": "method_body", "source_file": "java/github/yezheng1981/Java-Geometry-Expert/wprover/JExPanel.java", "mask_start_position": 3564, "mask_end_position": 3689, "canonical_solution": "{\n Dimension dm = this.getSize();\n button.setBounds(new Rectangle(0, (int) dm.getHeight() - 28, 32, 28));\n }", "pre_mask_code": "package wprover;\n\nimport javax.swing.*;\nimport java.awt.event.*;\nimport java.awt.*;\nimport java.net.URL;\n\nclass JExPanel extends JPanel implements ActionListener, MouseListener, MouseMotionListener, ComponentListener {\n\n drawProcess dp;\n\n static ImageIcon icoa;\n\n static ImageIcon icos;\n\n JToggleButton button;\n\n Timer timer = null;\n\n public void paint(Graphics g) {\n super.paint(g);\n if (dp != null)\n dp.paintPoint(g);\n }\n\n public JExPanel() {\n super();\n this.setLayout(null);\n this.addMouseListener(this);\n this.addMouseMotionListener(this);\n this.addComponentListener(this);\n this.setBackground(new Color(228, 236, 252));\n URL imageURL = GExpert.class.getResource(\"images/animate_start.gif\");\n ImageIcon image = new ImageIcon(imageURL);\n URL imageURL1 = GExpert.class.getResource(\"images/animate_stop.gif\");\n ImageIcon image1 = new ImageIcon(imageURL1);\n button = new JToggleButton(image) {\n\n public Dimension getPreferredSize() {\n return new Dimension(30, 28);\n }\n };\n this.add(button);\n button.addActionListener(this);\n Dimension dm = this.getSize();\n button.setBounds(new Rectangle(0, (int) dm.getHeight() - 28, 32, 28));\n button.setSelectedIcon(image1);\n }\n\n public static void setAinimateIcon(ImageIcon ico1, ImageIcon ico2) {\n icoa = ico1;\n icos = ico2;\n }\n\n public Dimension getPreferredSize() {\n return new Dimension(600, 400);\n }\n\n public void setdrawP(drawProcess dp) {\n this.dp = dp;\n if (timer != null)\n timer.stop();\n if (dp.animate != null) {\n AnimateC ant = dp.animate;\n if (timer == null)\n timer = new Timer(ant.getInitValue(), this);\n else\n timer.setDelay(ant.getInitValue());\n timer.start();\n button.setIcon(icos);\n button.setVisible(true);\n } else\n button.setVisible(false);\n }\n\n public void actionPerformed(ActionEvent e) {\n if (e.getSource() == button) {\n if (!timer.isRunning()) {\n dp.animationStart();\n button.setIcon(icos);\n timer.start();\n } else {\n dp.animationStop();\n button.setIcon(icoa);\n timer.stop();\n }\n } else if (e.getSource() == timer) {\n dp.animationOntime();\n this.repaint();\n }\n }\n\n public void mouseClicked(MouseEvent e) {\n if (e.getClickCount() > 1)\n dp.DWMouseDbClick(e.getX(), e.getY());\n if (e.getButton() == MouseEvent.BUTTON3)\n dp.DWMouseRightClick(e.getX(), e.getY());\n }\n\n public void mousePressed(MouseEvent e) {\n dp.DWButtonDown(e.getX(), e.getY());\n repaint();\n }\n\n public void mouseReleased(MouseEvent e) {\n dp.DWButtonUp(e.getX(), e.getY());\n repaint();\n }\n\n public void mouseEntered(MouseEvent e) {\n }\n\n public void mouseExited(MouseEvent e) {\n }\n\n public void mouseDragged(MouseEvent e) {\n dp.DWMouseDrag(e.getX(), e.getY());\n this.repaint();\n }\n\n public void mouseMoved(MouseEvent e) {\n dp.DWMouseMove(e.getX(), e.getY());\n this.repaint();\n }\n\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n dp.paintPoint(g);\n }\n\n public void componentResized(ComponentEvent e) ", "post_mask_code": "\n\n public void componentMoved(ComponentEvent e) {\n }\n\n public void componentShown(ComponentEvent e) {\n }\n\n public void componentHidden(ComponentEvent e) {\n timer.stop();\n }\n}\n"} {"task_id": "Java_2014", "language": "Java", "task_type": "single_line", "source_file": "java/github/yezheng1981/Java-Geometry-Expert/wprover/JExPanel.java", "mask_start_position": 3000, "mask_end_position": 3034, "canonical_solution": "dp.DWButtonUp(e.getX(), e.getY());", "pre_mask_code": "package wprover;\n\nimport javax.swing.*;\nimport java.awt.event.*;\nimport java.awt.*;\nimport java.net.URL;\n\nclass JExPanel extends JPanel implements ActionListener, MouseListener, MouseMotionListener, ComponentListener {\n\n drawProcess dp;\n\n static ImageIcon icoa;\n\n static ImageIcon icos;\n\n JToggleButton button;\n\n Timer timer = null;\n\n public void paint(Graphics g) {\n super.paint(g);\n if (dp != null)\n dp.paintPoint(g);\n }\n\n public JExPanel() {\n super();\n this.setLayout(null);\n this.addMouseListener(this);\n this.addMouseMotionListener(this);\n this.addComponentListener(this);\n this.setBackground(new Color(228, 236, 252));\n URL imageURL = GExpert.class.getResource(\"images/animate_start.gif\");\n ImageIcon image = new ImageIcon(imageURL);\n URL imageURL1 = GExpert.class.getResource(\"images/animate_stop.gif\");\n ImageIcon image1 = new ImageIcon(imageURL1);\n button = new JToggleButton(image) {\n\n public Dimension getPreferredSize() {\n return new Dimension(30, 28);\n }\n };\n this.add(button);\n button.addActionListener(this);\n Dimension dm = this.getSize();\n button.setBounds(new Rectangle(0, (int) dm.getHeight() - 28, 32, 28));\n button.setSelectedIcon(image1);\n }\n\n public static void setAinimateIcon(ImageIcon ico1, ImageIcon ico2) {\n icoa = ico1;\n icos = ico2;\n }\n\n public Dimension getPreferredSize() {\n return new Dimension(600, 400);\n }\n\n public void setdrawP(drawProcess dp) {\n this.dp = dp;\n if (timer != null)\n timer.stop();\n if (dp.animate != null) {\n AnimateC ant = dp.animate;\n if (timer == null)\n timer = new Timer(ant.getInitValue(), this);\n else\n timer.setDelay(ant.getInitValue());\n timer.start();\n button.setIcon(icos);\n button.setVisible(true);\n } else\n button.setVisible(false);\n }\n\n public void actionPerformed(ActionEvent e) {\n if (e.getSource() == button) {\n if (!timer.isRunning()) {\n dp.animationStart();\n button.setIcon(icos);\n timer.start();\n } else {\n dp.animationStop();\n button.setIcon(icoa);\n timer.stop();\n }\n } else if (e.getSource() == timer) {\n dp.animationOntime();\n this.repaint();\n }\n }\n\n public void mouseClicked(MouseEvent e) {\n if (e.getClickCount() > 1)\n dp.DWMouseDbClick(e.getX(), e.getY());\n if (e.getButton() == MouseEvent.BUTTON3)\n dp.DWMouseRightClick(e.getX(), e.getY());\n }\n\n public void mousePressed(MouseEvent e) {\n dp.DWButtonDown(e.getX(), e.getY());\n repaint();\n }\n\n public void mouseReleased(MouseEvent e) {\n ", "post_mask_code": "\n repaint();\n }\n\n public void mouseEntered(MouseEvent e) {\n }\n\n public void mouseExited(MouseEvent e) {\n }\n\n public void mouseDragged(MouseEvent e) {\n dp.DWMouseDrag(e.getX(), e.getY());\n this.repaint();\n }\n\n public void mouseMoved(MouseEvent e) {\n dp.DWMouseMove(e.getX(), e.getY());\n this.repaint();\n }\n\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n dp.paintPoint(g);\n }\n\n public void componentResized(ComponentEvent e) {\n Dimension dm = this.getSize();\n button.setBounds(new Rectangle(0, (int) dm.getHeight() - 28, 32, 28));\n }\n\n public void componentMoved(ComponentEvent e) {\n }\n\n public void componentShown(ComponentEvent e) {\n }\n\n public void componentHidden(ComponentEvent e) {\n timer.stop();\n }\n}\n"} {"task_id": "Java_2015", "language": "Java", "task_type": "if_statement", "source_file": "java/github/yezheng1981/Java-Geometry-Expert/wprover/JExPanel.java", "mask_start_position": 1710, "mask_end_position": 2086, "canonical_solution": "if (dp.animate != null) {\n AnimateC ant = dp.animate;\n if (timer == null)\n timer = new Timer(ant.getInitValue(), this);\n else\n timer.setDelay(ant.getInitValue());\n timer.start();\n button.setIcon(icos);\n button.setVisible(true);\n } else\n button.setVisible(false);", "pre_mask_code": "package wprover;\n\nimport javax.swing.*;\nimport java.awt.event.*;\nimport java.awt.*;\nimport java.net.URL;\n\nclass JExPanel extends JPanel implements ActionListener, MouseListener, MouseMotionListener, ComponentListener {\n\n drawProcess dp;\n\n static ImageIcon icoa;\n\n static ImageIcon icos;\n\n JToggleButton button;\n\n Timer timer = null;\n\n public void paint(Graphics g) {\n super.paint(g);\n if (dp != null)\n dp.paintPoint(g);\n }\n\n public JExPanel() {\n super();\n this.setLayout(null);\n this.addMouseListener(this);\n this.addMouseMotionListener(this);\n this.addComponentListener(this);\n this.setBackground(new Color(228, 236, 252));\n URL imageURL = GExpert.class.getResource(\"images/animate_start.gif\");\n ImageIcon image = new ImageIcon(imageURL);\n URL imageURL1 = GExpert.class.getResource(\"images/animate_stop.gif\");\n ImageIcon image1 = new ImageIcon(imageURL1);\n button = new JToggleButton(image) {\n\n public Dimension getPreferredSize() {\n return new Dimension(30, 28);\n }\n };\n this.add(button);\n button.addActionListener(this);\n Dimension dm = this.getSize();\n button.setBounds(new Rectangle(0, (int) dm.getHeight() - 28, 32, 28));\n button.setSelectedIcon(image1);\n }\n\n public static void setAinimateIcon(ImageIcon ico1, ImageIcon ico2) {\n icoa = ico1;\n icos = ico2;\n }\n\n public Dimension getPreferredSize() {\n return new Dimension(600, 400);\n }\n\n public void setdrawP(drawProcess dp) {\n this.dp = dp;\n if (timer != null)\n timer.stop();\n ", "post_mask_code": "\n }\n\n public void actionPerformed(ActionEvent e) {\n if (e.getSource() == button) {\n if (!timer.isRunning()) {\n dp.animationStart();\n button.setIcon(icos);\n timer.start();\n } else {\n dp.animationStop();\n button.setIcon(icoa);\n timer.stop();\n }\n } else if (e.getSource() == timer) {\n dp.animationOntime();\n this.repaint();\n }\n }\n\n public void mouseClicked(MouseEvent e) {\n if (e.getClickCount() > 1)\n dp.DWMouseDbClick(e.getX(), e.getY());\n if (e.getButton() == MouseEvent.BUTTON3)\n dp.DWMouseRightClick(e.getX(), e.getY());\n }\n\n public void mousePressed(MouseEvent e) {\n dp.DWButtonDown(e.getX(), e.getY());\n repaint();\n }\n\n public void mouseReleased(MouseEvent e) {\n dp.DWButtonUp(e.getX(), e.getY());\n repaint();\n }\n\n public void mouseEntered(MouseEvent e) {\n }\n\n public void mouseExited(MouseEvent e) {\n }\n\n public void mouseDragged(MouseEvent e) {\n dp.DWMouseDrag(e.getX(), e.getY());\n this.repaint();\n }\n\n public void mouseMoved(MouseEvent e) {\n dp.DWMouseMove(e.getX(), e.getY());\n this.repaint();\n }\n\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n dp.paintPoint(g);\n }\n\n public void componentResized(ComponentEvent e) {\n Dimension dm = this.getSize();\n button.setBounds(new Rectangle(0, (int) dm.getHeight() - 28, 32, 28));\n }\n\n public void componentMoved(ComponentEvent e) {\n }\n\n public void componentShown(ComponentEvent e) {\n }\n\n public void componentHidden(ComponentEvent e) {\n timer.stop();\n }\n}\n"} {"task_id": "Java_2016", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ra4king/CircuitSim/src/main/java/com/ra4king/circuitsim/gui/ComponentManager.java", "mask_start_position": 5102, "mask_end_position": 5162, "canonical_solution": "public ComponentLauncherInfo get(Pair name) ", "pre_mask_code": "package com.ra4king.circuitsim.gui;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.function.Consumer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.AdderPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.BitExtenderPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.ComparatorPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.DividerPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.MultiplierPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.NegatorPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.RandomGeneratorPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.ShifterPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.SubtractorPeer;\nimport com.ra4king.circuitsim.gui.peers.gates.AndGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.ControlledBufferPeer;\nimport com.ra4king.circuitsim.gui.peers.gates.NandGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.NorGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.NotGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.OrGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.XnorGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.XorGatePeer;\nimport com.ra4king.circuitsim.gui.peers.io.Button;\nimport com.ra4king.circuitsim.gui.peers.io.HexDisplay;\nimport com.ra4king.circuitsim.gui.peers.io.LED;\nimport com.ra4king.circuitsim.gui.peers.io.LEDMatrix;\nimport com.ra4king.circuitsim.gui.peers.memory.DFlipFlopPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.RAMPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.ROMPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.RegisterPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.SRFlipFlopPeer;\nimport com.ra4king.circuitsim.gui.peers.misc.Text;\nimport com.ra4king.circuitsim.gui.peers.plexers.DecoderPeer;\nimport com.ra4king.circuitsim.gui.peers.plexers.DemultiplexerPeer;\nimport com.ra4king.circuitsim.gui.peers.plexers.MultiplexerPeer;\nimport com.ra4king.circuitsim.gui.peers.plexers.PriorityEncoderPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.ClockPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.ConstantPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.PinPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.Probe;\nimport com.ra4king.circuitsim.gui.peers.wiring.SplitterPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.TransistorPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.Tunnel;\nimport com.ra4king.circuitsim.simulator.SimulationException;\nimport javafx.scene.image.Image;\nimport javafx.util.Pair;\n\n/**\n * @author Roi Atalla\n */\npublic class ComponentManager {\n\n private List components;\n\n public static class ComponentLauncherInfo {\n\n public final Class> clazz;\n\n public final Pair name;\n\n public final Image image;\n\n public final Properties properties;\n\n public final ComponentCreator creator;\n\n ComponentLauncherInfo(Class> clazz, Pair name, Image image, Properties properties, ComponentCreator creator) {\n this.clazz = clazz;\n this.name = name;\n this.image = image;\n this.properties = properties;\n this.creator = creator;\n }\n\n @Override\n public int hashCode() {\n return clazz.hashCode() ^ name.hashCode() ^ (image == null ? 0 : image.hashCode()) ^ properties.hashCode() ^ creator.hashCode();\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof ComponentLauncherInfo)) {\n return false;\n }\n ComponentLauncherInfo info = (ComponentLauncherInfo) other;\n return info.clazz == this.clazz && info.name.equals(this.name);\n }\n }\n\n public interface ComponentManagerInterface {\n\n void addComponent(Pair name, Image image, Properties defaultProperties);\n }\n\n static > ComponentCreator forClass(Class clazz) {\n return (properties, x, y) -> {\n try {\n return clazz.getConstructor(Properties.class, Integer.TYPE, Integer.TYPE).newInstance(properties, x, y);\n } catch (NoSuchMethodException exc) {\n throw new RuntimeException(\"Must have constructor taking (Properties props, int x, int y)\");\n } catch (InvocationTargetException exc) {\n if (exc.getTargetException() instanceof SimulationException) {\n throw (SimulationException) exc.getTargetException();\n }\n throw new RuntimeException(exc.getTargetException());\n } catch (RuntimeException exc) {\n throw exc;\n } catch (Exception exc) {\n throw new RuntimeException(exc);\n }\n };\n }\n\n ComponentManager() {\n components = new ArrayList<>();\n registerDefaultComponents();\n }\n\n ", "post_mask_code": "{\n for (ComponentLauncherInfo component : components) {\n if (component.name.equals(name)) {\n return component;\n }\n }\n throw new IllegalArgumentException(\"Component not registered: \" + name);\n }\n\n // To be able to use getClass(), ComponentPeer cannot be parameterized.\n @SuppressWarnings(\"rawtypes\")\n public ComponentLauncherInfo get(Class clazz, Properties properties) throws SimulationException {\n ComponentLauncherInfo firstComponent = null;\n for (ComponentLauncherInfo component : components) {\n if (component.clazz == clazz) {\n firstComponent = component;\n if (properties.intersect(component.properties).equals(component.properties)) {\n return component;\n }\n }\n }\n if (firstComponent != null) {\n return firstComponent;\n }\n throw new SimulationException(\"Component not registered: \" + clazz);\n }\n\n public void forEach(Consumer consumer) {\n components.forEach(consumer);\n }\n\n public > void register(Class clazz) {\n try {\n ComponentCreator creator = forClass(clazz);\n Method method = clazz.getMethod(\"installComponent\", ComponentManagerInterface.class);\n method.invoke(null, (ComponentManagerInterface) (name, image, defaultProperties) -> {\n if (name == null || defaultProperties == null) {\n throw new NullPointerException(\"Name and Properties cannot be null.\");\n }\n ComponentLauncherInfo info = new ComponentLauncherInfo(clazz, name, image, defaultProperties, creator);\n if (!components.contains(info)) {\n components.add(info);\n }\n });\n } catch (NoSuchMethodException exc) {\n throw new RuntimeException(\"Must implement: public static void installComponent\" + \"(ComponentManagerInterface): \" + clazz);\n } catch (RuntimeException exc) {\n throw exc;\n } catch (Exception exc) {\n throw new RuntimeException(exc);\n }\n }\n\n private void registerDefaultComponents() {\n register(PinPeer.class);\n register(ConstantPeer.class);\n register(Probe.class);\n register(ClockPeer.class);\n register(SplitterPeer.class);\n register(Tunnel.class);\n register(TransistorPeer.class);\n register(AndGatePeer.class);\n register(NandGatePeer.class);\n register(OrGatePeer.class);\n register(NorGatePeer.class);\n register(XorGatePeer.class);\n register(XnorGatePeer.class);\n register(NotGatePeer.class);\n register(ControlledBufferPeer.class);\n register(MultiplexerPeer.class);\n register(DemultiplexerPeer.class);\n register(DecoderPeer.class);\n register(PriorityEncoderPeer.class);\n register(RegisterPeer.class);\n register(SRFlipFlopPeer.class);\n register(DFlipFlopPeer.class);\n register(RAMPeer.class);\n register(ROMPeer.class);\n register(AdderPeer.class);\n register(SubtractorPeer.class);\n register(MultiplierPeer.class);\n register(DividerPeer.class);\n register(NegatorPeer.class);\n register(ComparatorPeer.class);\n register(BitExtenderPeer.class);\n register(ShifterPeer.class);\n register(RandomGeneratorPeer.class);\n register(Button.class);\n register(LED.class);\n register(LEDMatrix.class);\n register(HexDisplay.class);\n register(Text.class);\n }\n\n public interface ComponentCreator> {\n\n T createComponent(Properties properties, int x, int y);\n }\n}\n"} {"task_id": "Java_2017", "language": "Java", "task_type": "method_body", "source_file": "java/github/ra4king/CircuitSim/src/main/java/com/ra4king/circuitsim/gui/ComponentManager.java", "mask_start_position": 5162, "mask_end_position": 5416, "canonical_solution": "{\n for (ComponentLauncherInfo component : components) {\n if (component.name.equals(name)) {\n return component;\n }\n }\n throw new IllegalArgumentException(\"Component not registered: \" + name);\n }", "pre_mask_code": "package com.ra4king.circuitsim.gui;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.function.Consumer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.AdderPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.BitExtenderPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.ComparatorPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.DividerPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.MultiplierPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.NegatorPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.RandomGeneratorPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.ShifterPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.SubtractorPeer;\nimport com.ra4king.circuitsim.gui.peers.gates.AndGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.ControlledBufferPeer;\nimport com.ra4king.circuitsim.gui.peers.gates.NandGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.NorGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.NotGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.OrGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.XnorGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.XorGatePeer;\nimport com.ra4king.circuitsim.gui.peers.io.Button;\nimport com.ra4king.circuitsim.gui.peers.io.HexDisplay;\nimport com.ra4king.circuitsim.gui.peers.io.LED;\nimport com.ra4king.circuitsim.gui.peers.io.LEDMatrix;\nimport com.ra4king.circuitsim.gui.peers.memory.DFlipFlopPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.RAMPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.ROMPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.RegisterPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.SRFlipFlopPeer;\nimport com.ra4king.circuitsim.gui.peers.misc.Text;\nimport com.ra4king.circuitsim.gui.peers.plexers.DecoderPeer;\nimport com.ra4king.circuitsim.gui.peers.plexers.DemultiplexerPeer;\nimport com.ra4king.circuitsim.gui.peers.plexers.MultiplexerPeer;\nimport com.ra4king.circuitsim.gui.peers.plexers.PriorityEncoderPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.ClockPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.ConstantPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.PinPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.Probe;\nimport com.ra4king.circuitsim.gui.peers.wiring.SplitterPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.TransistorPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.Tunnel;\nimport com.ra4king.circuitsim.simulator.SimulationException;\nimport javafx.scene.image.Image;\nimport javafx.util.Pair;\n\n/**\n * @author Roi Atalla\n */\npublic class ComponentManager {\n\n private List components;\n\n public static class ComponentLauncherInfo {\n\n public final Class> clazz;\n\n public final Pair name;\n\n public final Image image;\n\n public final Properties properties;\n\n public final ComponentCreator creator;\n\n ComponentLauncherInfo(Class> clazz, Pair name, Image image, Properties properties, ComponentCreator creator) {\n this.clazz = clazz;\n this.name = name;\n this.image = image;\n this.properties = properties;\n this.creator = creator;\n }\n\n @Override\n public int hashCode() {\n return clazz.hashCode() ^ name.hashCode() ^ (image == null ? 0 : image.hashCode()) ^ properties.hashCode() ^ creator.hashCode();\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof ComponentLauncherInfo)) {\n return false;\n }\n ComponentLauncherInfo info = (ComponentLauncherInfo) other;\n return info.clazz == this.clazz && info.name.equals(this.name);\n }\n }\n\n public interface ComponentManagerInterface {\n\n void addComponent(Pair name, Image image, Properties defaultProperties);\n }\n\n static > ComponentCreator forClass(Class clazz) {\n return (properties, x, y) -> {\n try {\n return clazz.getConstructor(Properties.class, Integer.TYPE, Integer.TYPE).newInstance(properties, x, y);\n } catch (NoSuchMethodException exc) {\n throw new RuntimeException(\"Must have constructor taking (Properties props, int x, int y)\");\n } catch (InvocationTargetException exc) {\n if (exc.getTargetException() instanceof SimulationException) {\n throw (SimulationException) exc.getTargetException();\n }\n throw new RuntimeException(exc.getTargetException());\n } catch (RuntimeException exc) {\n throw exc;\n } catch (Exception exc) {\n throw new RuntimeException(exc);\n }\n };\n }\n\n ComponentManager() {\n components = new ArrayList<>();\n registerDefaultComponents();\n }\n\n public ComponentLauncherInfo get(Pair name) ", "post_mask_code": "\n\n // To be able to use getClass(), ComponentPeer cannot be parameterized.\n @SuppressWarnings(\"rawtypes\")\n public ComponentLauncherInfo get(Class clazz, Properties properties) throws SimulationException {\n ComponentLauncherInfo firstComponent = null;\n for (ComponentLauncherInfo component : components) {\n if (component.clazz == clazz) {\n firstComponent = component;\n if (properties.intersect(component.properties).equals(component.properties)) {\n return component;\n }\n }\n }\n if (firstComponent != null) {\n return firstComponent;\n }\n throw new SimulationException(\"Component not registered: \" + clazz);\n }\n\n public void forEach(Consumer consumer) {\n components.forEach(consumer);\n }\n\n public > void register(Class clazz) {\n try {\n ComponentCreator creator = forClass(clazz);\n Method method = clazz.getMethod(\"installComponent\", ComponentManagerInterface.class);\n method.invoke(null, (ComponentManagerInterface) (name, image, defaultProperties) -> {\n if (name == null || defaultProperties == null) {\n throw new NullPointerException(\"Name and Properties cannot be null.\");\n }\n ComponentLauncherInfo info = new ComponentLauncherInfo(clazz, name, image, defaultProperties, creator);\n if (!components.contains(info)) {\n components.add(info);\n }\n });\n } catch (NoSuchMethodException exc) {\n throw new RuntimeException(\"Must implement: public static void installComponent\" + \"(ComponentManagerInterface): \" + clazz);\n } catch (RuntimeException exc) {\n throw exc;\n } catch (Exception exc) {\n throw new RuntimeException(exc);\n }\n }\n\n private void registerDefaultComponents() {\n register(PinPeer.class);\n register(ConstantPeer.class);\n register(Probe.class);\n register(ClockPeer.class);\n register(SplitterPeer.class);\n register(Tunnel.class);\n register(TransistorPeer.class);\n register(AndGatePeer.class);\n register(NandGatePeer.class);\n register(OrGatePeer.class);\n register(NorGatePeer.class);\n register(XorGatePeer.class);\n register(XnorGatePeer.class);\n register(NotGatePeer.class);\n register(ControlledBufferPeer.class);\n register(MultiplexerPeer.class);\n register(DemultiplexerPeer.class);\n register(DecoderPeer.class);\n register(PriorityEncoderPeer.class);\n register(RegisterPeer.class);\n register(SRFlipFlopPeer.class);\n register(DFlipFlopPeer.class);\n register(RAMPeer.class);\n register(ROMPeer.class);\n register(AdderPeer.class);\n register(SubtractorPeer.class);\n register(MultiplierPeer.class);\n register(DividerPeer.class);\n register(NegatorPeer.class);\n register(ComparatorPeer.class);\n register(BitExtenderPeer.class);\n register(ShifterPeer.class);\n register(RandomGeneratorPeer.class);\n register(Button.class);\n register(LED.class);\n register(LEDMatrix.class);\n register(HexDisplay.class);\n register(Text.class);\n }\n\n public interface ComponentCreator> {\n\n T createComponent(Properties properties, int x, int y);\n }\n}\n"} {"task_id": "Java_2018", "language": "Java", "task_type": "single_line", "source_file": "java/github/ra4king/CircuitSim/src/main/java/com/ra4king/circuitsim/gui/ComponentManager.java", "mask_start_position": 8081, "mask_end_position": 8099, "canonical_solution": "plexerPeer.class);", "pre_mask_code": "package com.ra4king.circuitsim.gui;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.function.Consumer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.AdderPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.BitExtenderPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.ComparatorPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.DividerPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.MultiplierPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.NegatorPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.RandomGeneratorPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.ShifterPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.SubtractorPeer;\nimport com.ra4king.circuitsim.gui.peers.gates.AndGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.ControlledBufferPeer;\nimport com.ra4king.circuitsim.gui.peers.gates.NandGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.NorGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.NotGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.OrGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.XnorGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.XorGatePeer;\nimport com.ra4king.circuitsim.gui.peers.io.Button;\nimport com.ra4king.circuitsim.gui.peers.io.HexDisplay;\nimport com.ra4king.circuitsim.gui.peers.io.LED;\nimport com.ra4king.circuitsim.gui.peers.io.LEDMatrix;\nimport com.ra4king.circuitsim.gui.peers.memory.DFlipFlopPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.RAMPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.ROMPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.RegisterPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.SRFlipFlopPeer;\nimport com.ra4king.circuitsim.gui.peers.misc.Text;\nimport com.ra4king.circuitsim.gui.peers.plexers.DecoderPeer;\nimport com.ra4king.circuitsim.gui.peers.plexers.DemultiplexerPeer;\nimport com.ra4king.circuitsim.gui.peers.plexers.MultiplexerPeer;\nimport com.ra4king.circuitsim.gui.peers.plexers.PriorityEncoderPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.ClockPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.ConstantPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.PinPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.Probe;\nimport com.ra4king.circuitsim.gui.peers.wiring.SplitterPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.TransistorPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.Tunnel;\nimport com.ra4king.circuitsim.simulator.SimulationException;\nimport javafx.scene.image.Image;\nimport javafx.util.Pair;\n\n/**\n * @author Roi Atalla\n */\npublic class ComponentManager {\n\n private List components;\n\n public static class ComponentLauncherInfo {\n\n public final Class> clazz;\n\n public final Pair name;\n\n public final Image image;\n\n public final Properties properties;\n\n public final ComponentCreator creator;\n\n ComponentLauncherInfo(Class> clazz, Pair name, Image image, Properties properties, ComponentCreator creator) {\n this.clazz = clazz;\n this.name = name;\n this.image = image;\n this.properties = properties;\n this.creator = creator;\n }\n\n @Override\n public int hashCode() {\n return clazz.hashCode() ^ name.hashCode() ^ (image == null ? 0 : image.hashCode()) ^ properties.hashCode() ^ creator.hashCode();\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof ComponentLauncherInfo)) {\n return false;\n }\n ComponentLauncherInfo info = (ComponentLauncherInfo) other;\n return info.clazz == this.clazz && info.name.equals(this.name);\n }\n }\n\n public interface ComponentManagerInterface {\n\n void addComponent(Pair name, Image image, Properties defaultProperties);\n }\n\n static > ComponentCreator forClass(Class clazz) {\n return (properties, x, y) -> {\n try {\n return clazz.getConstructor(Properties.class, Integer.TYPE, Integer.TYPE).newInstance(properties, x, y);\n } catch (NoSuchMethodException exc) {\n throw new RuntimeException(\"Must have constructor taking (Properties props, int x, int y)\");\n } catch (InvocationTargetException exc) {\n if (exc.getTargetException() instanceof SimulationException) {\n throw (SimulationException) exc.getTargetException();\n }\n throw new RuntimeException(exc.getTargetException());\n } catch (RuntimeException exc) {\n throw exc;\n } catch (Exception exc) {\n throw new RuntimeException(exc);\n }\n };\n }\n\n ComponentManager() {\n components = new ArrayList<>();\n registerDefaultComponents();\n }\n\n public ComponentLauncherInfo get(Pair name) {\n for (ComponentLauncherInfo component : components) {\n if (component.name.equals(name)) {\n return component;\n }\n }\n throw new IllegalArgumentException(\"Component not registered: \" + name);\n }\n\n // To be able to use getClass(), ComponentPeer cannot be parameterized.\n @SuppressWarnings(\"rawtypes\")\n public ComponentLauncherInfo get(Class clazz, Properties properties) throws SimulationException {\n ComponentLauncherInfo firstComponent = null;\n for (ComponentLauncherInfo component : components) {\n if (component.clazz == clazz) {\n firstComponent = component;\n if (properties.intersect(component.properties).equals(component.properties)) {\n return component;\n }\n }\n }\n if (firstComponent != null) {\n return firstComponent;\n }\n throw new SimulationException(\"Component not registered: \" + clazz);\n }\n\n public void forEach(Consumer consumer) {\n components.forEach(consumer);\n }\n\n public > void register(Class clazz) {\n try {\n ComponentCreator creator = forClass(clazz);\n Method method = clazz.getMethod(\"installComponent\", ComponentManagerInterface.class);\n method.invoke(null, (ComponentManagerInterface) (name, image, defaultProperties) -> {\n if (name == null || defaultProperties == null) {\n throw new NullPointerException(\"Name and Properties cannot be null.\");\n }\n ComponentLauncherInfo info = new ComponentLauncherInfo(clazz, name, image, defaultProperties, creator);\n if (!components.contains(info)) {\n components.add(info);\n }\n });\n } catch (NoSuchMethodException exc) {\n throw new RuntimeException(\"Must implement: public static void installComponent\" + \"(ComponentManagerInterface): \" + clazz);\n } catch (RuntimeException exc) {\n throw exc;\n } catch (Exception exc) {\n throw new RuntimeException(exc);\n }\n }\n\n private void registerDefaultComponents() {\n register(PinPeer.class);\n register(ConstantPeer.class);\n register(Probe.class);\n register(ClockPeer.class);\n register(SplitterPeer.class);\n register(Tunnel.class);\n register(TransistorPeer.class);\n register(AndGatePeer.class);\n register(NandGatePeer.class);\n register(OrGatePeer.class);\n register(NorGatePeer.class);\n register(XorGatePeer.class);\n register(XnorGatePeer.class);\n register(NotGatePeer.class);\n register(ControlledBufferPeer.class);\n register(MultiplexerPeer.class);\n register(Demulti", "post_mask_code": "\n register(DecoderPeer.class);\n register(PriorityEncoderPeer.class);\n register(RegisterPeer.class);\n register(SRFlipFlopPeer.class);\n register(DFlipFlopPeer.class);\n register(RAMPeer.class);\n register(ROMPeer.class);\n register(AdderPeer.class);\n register(SubtractorPeer.class);\n register(MultiplierPeer.class);\n register(DividerPeer.class);\n register(NegatorPeer.class);\n register(ComparatorPeer.class);\n register(BitExtenderPeer.class);\n register(ShifterPeer.class);\n register(RandomGeneratorPeer.class);\n register(Button.class);\n register(LED.class);\n register(LEDMatrix.class);\n register(HexDisplay.class);\n register(Text.class);\n }\n\n public interface ComponentCreator> {\n\n T createComponent(Properties properties, int x, int y);\n }\n}\n"} {"task_id": "Java_2019", "language": "Java", "task_type": "if_statement", "source_file": "java/github/ra4king/CircuitSim/src/main/java/com/ra4king/circuitsim/gui/ComponentManager.java", "mask_start_position": 3667, "mask_end_position": 3759, "canonical_solution": "if (!(other instanceof ComponentLauncherInfo)) {\n return false;\n }", "pre_mask_code": "package com.ra4king.circuitsim.gui;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.function.Consumer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.AdderPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.BitExtenderPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.ComparatorPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.DividerPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.MultiplierPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.NegatorPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.RandomGeneratorPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.ShifterPeer;\nimport com.ra4king.circuitsim.gui.peers.arithmetic.SubtractorPeer;\nimport com.ra4king.circuitsim.gui.peers.gates.AndGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.ControlledBufferPeer;\nimport com.ra4king.circuitsim.gui.peers.gates.NandGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.NorGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.NotGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.OrGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.XnorGatePeer;\nimport com.ra4king.circuitsim.gui.peers.gates.XorGatePeer;\nimport com.ra4king.circuitsim.gui.peers.io.Button;\nimport com.ra4king.circuitsim.gui.peers.io.HexDisplay;\nimport com.ra4king.circuitsim.gui.peers.io.LED;\nimport com.ra4king.circuitsim.gui.peers.io.LEDMatrix;\nimport com.ra4king.circuitsim.gui.peers.memory.DFlipFlopPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.RAMPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.ROMPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.RegisterPeer;\nimport com.ra4king.circuitsim.gui.peers.memory.SRFlipFlopPeer;\nimport com.ra4king.circuitsim.gui.peers.misc.Text;\nimport com.ra4king.circuitsim.gui.peers.plexers.DecoderPeer;\nimport com.ra4king.circuitsim.gui.peers.plexers.DemultiplexerPeer;\nimport com.ra4king.circuitsim.gui.peers.plexers.MultiplexerPeer;\nimport com.ra4king.circuitsim.gui.peers.plexers.PriorityEncoderPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.ClockPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.ConstantPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.PinPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.Probe;\nimport com.ra4king.circuitsim.gui.peers.wiring.SplitterPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.TransistorPeer;\nimport com.ra4king.circuitsim.gui.peers.wiring.Tunnel;\nimport com.ra4king.circuitsim.simulator.SimulationException;\nimport javafx.scene.image.Image;\nimport javafx.util.Pair;\n\n/**\n * @author Roi Atalla\n */\npublic class ComponentManager {\n\n private List components;\n\n public static class ComponentLauncherInfo {\n\n public final Class> clazz;\n\n public final Pair name;\n\n public final Image image;\n\n public final Properties properties;\n\n public final ComponentCreator creator;\n\n ComponentLauncherInfo(Class> clazz, Pair name, Image image, Properties properties, ComponentCreator creator) {\n this.clazz = clazz;\n this.name = name;\n this.image = image;\n this.properties = properties;\n this.creator = creator;\n }\n\n @Override\n public int hashCode() {\n return clazz.hashCode() ^ name.hashCode() ^ (image == null ? 0 : image.hashCode()) ^ properties.hashCode() ^ creator.hashCode();\n }\n\n @Override\n public boolean equals(Object other) {\n ", "post_mask_code": "\n ComponentLauncherInfo info = (ComponentLauncherInfo) other;\n return info.clazz == this.clazz && info.name.equals(this.name);\n }\n }\n\n public interface ComponentManagerInterface {\n\n void addComponent(Pair name, Image image, Properties defaultProperties);\n }\n\n static > ComponentCreator forClass(Class clazz) {\n return (properties, x, y) -> {\n try {\n return clazz.getConstructor(Properties.class, Integer.TYPE, Integer.TYPE).newInstance(properties, x, y);\n } catch (NoSuchMethodException exc) {\n throw new RuntimeException(\"Must have constructor taking (Properties props, int x, int y)\");\n } catch (InvocationTargetException exc) {\n if (exc.getTargetException() instanceof SimulationException) {\n throw (SimulationException) exc.getTargetException();\n }\n throw new RuntimeException(exc.getTargetException());\n } catch (RuntimeException exc) {\n throw exc;\n } catch (Exception exc) {\n throw new RuntimeException(exc);\n }\n };\n }\n\n ComponentManager() {\n components = new ArrayList<>();\n registerDefaultComponents();\n }\n\n public ComponentLauncherInfo get(Pair name) {\n for (ComponentLauncherInfo component : components) {\n if (component.name.equals(name)) {\n return component;\n }\n }\n throw new IllegalArgumentException(\"Component not registered: \" + name);\n }\n\n // To be able to use getClass(), ComponentPeer cannot be parameterized.\n @SuppressWarnings(\"rawtypes\")\n public ComponentLauncherInfo get(Class clazz, Properties properties) throws SimulationException {\n ComponentLauncherInfo firstComponent = null;\n for (ComponentLauncherInfo component : components) {\n if (component.clazz == clazz) {\n firstComponent = component;\n if (properties.intersect(component.properties).equals(component.properties)) {\n return component;\n }\n }\n }\n if (firstComponent != null) {\n return firstComponent;\n }\n throw new SimulationException(\"Component not registered: \" + clazz);\n }\n\n public void forEach(Consumer consumer) {\n components.forEach(consumer);\n }\n\n public > void register(Class clazz) {\n try {\n ComponentCreator creator = forClass(clazz);\n Method method = clazz.getMethod(\"installComponent\", ComponentManagerInterface.class);\n method.invoke(null, (ComponentManagerInterface) (name, image, defaultProperties) -> {\n if (name == null || defaultProperties == null) {\n throw new NullPointerException(\"Name and Properties cannot be null.\");\n }\n ComponentLauncherInfo info = new ComponentLauncherInfo(clazz, name, image, defaultProperties, creator);\n if (!components.contains(info)) {\n components.add(info);\n }\n });\n } catch (NoSuchMethodException exc) {\n throw new RuntimeException(\"Must implement: public static void installComponent\" + \"(ComponentManagerInterface): \" + clazz);\n } catch (RuntimeException exc) {\n throw exc;\n } catch (Exception exc) {\n throw new RuntimeException(exc);\n }\n }\n\n private void registerDefaultComponents() {\n register(PinPeer.class);\n register(ConstantPeer.class);\n register(Probe.class);\n register(ClockPeer.class);\n register(SplitterPeer.class);\n register(Tunnel.class);\n register(TransistorPeer.class);\n register(AndGatePeer.class);\n register(NandGatePeer.class);\n register(OrGatePeer.class);\n register(NorGatePeer.class);\n register(XorGatePeer.class);\n register(XnorGatePeer.class);\n register(NotGatePeer.class);\n register(ControlledBufferPeer.class);\n register(MultiplexerPeer.class);\n register(DemultiplexerPeer.class);\n register(DecoderPeer.class);\n register(PriorityEncoderPeer.class);\n register(RegisterPeer.class);\n register(SRFlipFlopPeer.class);\n register(DFlipFlopPeer.class);\n register(RAMPeer.class);\n register(ROMPeer.class);\n register(AdderPeer.class);\n register(SubtractorPeer.class);\n register(MultiplierPeer.class);\n register(DividerPeer.class);\n register(NegatorPeer.class);\n register(ComparatorPeer.class);\n register(BitExtenderPeer.class);\n register(ShifterPeer.class);\n register(RandomGeneratorPeer.class);\n register(Button.class);\n register(LED.class);\n register(LEDMatrix.class);\n register(HexDisplay.class);\n register(Text.class);\n }\n\n public interface ComponentCreator> {\n\n T createComponent(Properties properties, int x, int y);\n }\n}\n"} {"task_id": "Java_2020", "language": "Java", "task_type": "method_signature", "source_file": "java/github/floodlight/floodlight/src/main/java/org/sdnplatform/sync/internal/version/VectorClockInconsistencyResolver.java", "mask_start_position": 1586, "mask_end_position": 1622, "canonical_solution": "@Override\n public int hashCode() ", "pre_mask_code": "package org.sdnplatform.sync.internal.version;\n\nimport java.util.List;\nimport java.util.ListIterator;\nimport org.sdnplatform.sync.IInconsistencyResolver;\nimport org.sdnplatform.sync.Versioned;\nimport org.sdnplatform.sync.IVersion.Occurred;\nimport com.google.common.collect.Lists;\n\n/**\n * An inconsistency resolver that uses the object VectorClocks leaving only a\n * set of concurrent versions remaining.\n */\npublic class VectorClockInconsistencyResolver implements IInconsistencyResolver> {\n\n public List> resolveConflicts(List> items) {\n int size = items.size();\n if (size <= 1)\n return items;\n List> newItems = Lists.newArrayList();\n for (Versioned v1 : items) {\n boolean found = false;\n for (ListIterator> it2 = newItems.listIterator(); it2.hasNext(); ) {\n Versioned v2 = it2.next();\n Occurred compare = v1.getVersion().compare(v2.getVersion());\n if (compare == Occurred.AFTER) {\n if (found)\n it2.remove();\n else\n it2.set(v1);\n }\n if (compare != Occurred.CONCURRENTLY)\n found = true;\n }\n if (!found)\n newItems.add(v1);\n }\n return newItems;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n return (o != null && getClass() == o.getClass());\n }\n\n ", "post_mask_code": "{\n return getClass().hashCode();\n }\n}\n"} {"task_id": "Java_2021", "language": "Java", "task_type": "method_body", "source_file": "java/github/floodlight/floodlight/src/main/java/org/sdnplatform/sync/internal/version/VectorClockInconsistencyResolver.java", "mask_start_position": 1622, "mask_end_position": 1667, "canonical_solution": "{\n return getClass().hashCode();\n }", "pre_mask_code": "package org.sdnplatform.sync.internal.version;\n\nimport java.util.List;\nimport java.util.ListIterator;\nimport org.sdnplatform.sync.IInconsistencyResolver;\nimport org.sdnplatform.sync.Versioned;\nimport org.sdnplatform.sync.IVersion.Occurred;\nimport com.google.common.collect.Lists;\n\n/**\n * An inconsistency resolver that uses the object VectorClocks leaving only a\n * set of concurrent versions remaining.\n */\npublic class VectorClockInconsistencyResolver implements IInconsistencyResolver> {\n\n public List> resolveConflicts(List> items) {\n int size = items.size();\n if (size <= 1)\n return items;\n List> newItems = Lists.newArrayList();\n for (Versioned v1 : items) {\n boolean found = false;\n for (ListIterator> it2 = newItems.listIterator(); it2.hasNext(); ) {\n Versioned v2 = it2.next();\n Occurred compare = v1.getVersion().compare(v2.getVersion());\n if (compare == Occurred.AFTER) {\n if (found)\n it2.remove();\n else\n it2.set(v1);\n }\n if (compare != Occurred.CONCURRENTLY)\n found = true;\n }\n if (!found)\n newItems.add(v1);\n }\n return newItems;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n return (o != null && getClass() == o.getClass());\n }\n\n @Override\n public int hashCode() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2022", "language": "Java", "task_type": "single_line", "source_file": "java/github/floodlight/floodlight/src/main/java/org/sdnplatform/sync/internal/version/VectorClockInconsistencyResolver.java", "mask_start_position": 1565, "mask_end_position": 1574, "canonical_solution": "Class());", "pre_mask_code": "package org.sdnplatform.sync.internal.version;\n\nimport java.util.List;\nimport java.util.ListIterator;\nimport org.sdnplatform.sync.IInconsistencyResolver;\nimport org.sdnplatform.sync.Versioned;\nimport org.sdnplatform.sync.IVersion.Occurred;\nimport com.google.common.collect.Lists;\n\n/**\n * An inconsistency resolver that uses the object VectorClocks leaving only a\n * set of concurrent versions remaining.\n */\npublic class VectorClockInconsistencyResolver implements IInconsistencyResolver> {\n\n public List> resolveConflicts(List> items) {\n int size = items.size();\n if (size <= 1)\n return items;\n List> newItems = Lists.newArrayList();\n for (Versioned v1 : items) {\n boolean found = false;\n for (ListIterator> it2 = newItems.listIterator(); it2.hasNext(); ) {\n Versioned v2 = it2.next();\n Occurred compare = v1.getVersion().compare(v2.getVersion());\n if (compare == Occurred.AFTER) {\n if (found)\n it2.remove();\n else\n it2.set(v1);\n }\n if (compare != Occurred.CONCURRENTLY)\n found = true;\n }\n if (!found)\n newItems.add(v1);\n }\n return newItems;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n return (o != null && getClass() == o.get", "post_mask_code": "\n }\n\n @Override\n public int hashCode() {\n return getClass().hashCode();\n }\n}\n"} {"task_id": "Java_2023", "language": "Java", "task_type": "if_statement", "source_file": "java/github/floodlight/floodlight/src/main/java/org/sdnplatform/sync/internal/version/VectorClockInconsistencyResolver.java", "mask_start_position": 1086, "mask_end_position": 1196, "canonical_solution": "if (found)\n it2.remove();\n else\n it2.set(v1);", "pre_mask_code": "package org.sdnplatform.sync.internal.version;\n\nimport java.util.List;\nimport java.util.ListIterator;\nimport org.sdnplatform.sync.IInconsistencyResolver;\nimport org.sdnplatform.sync.Versioned;\nimport org.sdnplatform.sync.IVersion.Occurred;\nimport com.google.common.collect.Lists;\n\n/**\n * An inconsistency resolver that uses the object VectorClocks leaving only a\n * set of concurrent versions remaining.\n */\npublic class VectorClockInconsistencyResolver implements IInconsistencyResolver> {\n\n public List> resolveConflicts(List> items) {\n int size = items.size();\n if (size <= 1)\n return items;\n List> newItems = Lists.newArrayList();\n for (Versioned v1 : items) {\n boolean found = false;\n for (ListIterator> it2 = newItems.listIterator(); it2.hasNext(); ) {\n Versioned v2 = it2.next();\n Occurred compare = v1.getVersion().compare(v2.getVersion());\n if (compare == Occurred.AFTER) {\n ", "post_mask_code": "\n }\n if (compare != Occurred.CONCURRENTLY)\n found = true;\n }\n if (!found)\n newItems.add(v1);\n }\n return newItems;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n return (o != null && getClass() == o.getClass());\n }\n\n @Override\n public int hashCode() {\n return getClass().hashCode();\n }\n}\n"} {"task_id": "Java_2024", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ZXZxin/zxorder/order/server/src/main/java/com/zxin/order/controller/HystrixController.java", "mask_start_position": 564, "mask_end_position": 696, "canonical_solution": "@HystrixCommand\n @GetMapping(\"/getProductInfoList\")\n public String getProductInfoList(@RequestParam(\"number\") Integer number) ", "pre_mask_code": "package com.zxin.order.controller;\n\nimport com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;\nimport com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.client.RestTemplate;\nimport java.util.Arrays;\n\n@RestController\n@DefaultProperties(defaultFallback = \"defaultFallback\")\npublic class HystrixController {\n\n // 超时配置\n ", "post_mask_code": "{\n if (number % 2 == 0) {\n return \"success\";\n }\n RestTemplate restTemplate = new RestTemplate();\n return restTemplate.postForObject(\"http://127.0.0.1:8005/product/listForOrder\", Arrays.asList(\"157875196366160022\"), String.class);\n }\n\n private String fallback() {\n return \"太拥挤了, 请稍后再试~~\";\n }\n\n private String defaultFallback() {\n return \"默认提示:太拥挤了, 请稍后再试~~\";\n }\n}\n"} {"task_id": "Java_2025", "language": "Java", "task_type": "method_body", "source_file": "java/github/ZXZxin/zxorder/order/server/src/main/java/com/zxin/order/controller/HystrixController.java", "mask_start_position": 1002, "mask_end_position": 1041, "canonical_solution": "{\n return \"太拥挤了, 请稍后再试~~\";\n }", "pre_mask_code": "package com.zxin.order.controller;\n\nimport com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;\nimport com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.client.RestTemplate;\nimport java.util.Arrays;\n\n@RestController\n@DefaultProperties(defaultFallback = \"defaultFallback\")\npublic class HystrixController {\n\n // 超时配置\n @HystrixCommand\n @GetMapping(\"/getProductInfoList\")\n public String getProductInfoList(@RequestParam(\"number\") Integer number) {\n if (number % 2 == 0) {\n return \"success\";\n }\n RestTemplate restTemplate = new RestTemplate();\n return restTemplate.postForObject(\"http://127.0.0.1:8005/product/listForOrder\", Arrays.asList(\"157875196366160022\"), String.class);\n }\n\n private String fallback() ", "post_mask_code": "\n\n private String defaultFallback() {\n return \"默认提示:太拥挤了, 请稍后再试~~\";\n }\n}\n"} {"task_id": "Java_2026", "language": "Java", "task_type": "single_line", "source_file": "java/github/ZXZxin/zxorder/order/server/src/main/java/com/zxin/order/controller/HystrixController.java", "mask_start_position": 876, "mask_end_position": 964, "canonical_solution": "27.0.0.1:8005/product/listForOrder\", Arrays.asList(\"157875196366160022\"), String.class);", "pre_mask_code": "package com.zxin.order.controller;\n\nimport com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;\nimport com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.client.RestTemplate;\nimport java.util.Arrays;\n\n@RestController\n@DefaultProperties(defaultFallback = \"defaultFallback\")\npublic class HystrixController {\n\n // 超时配置\n @HystrixCommand\n @GetMapping(\"/getProductInfoList\")\n public String getProductInfoList(@RequestParam(\"number\") Integer number) {\n if (number % 2 == 0) {\n return \"success\";\n }\n RestTemplate restTemplate = new RestTemplate();\n return restTemplate.postForObject(\"http://1", "post_mask_code": "\n }\n\n private String fallback() {\n return \"太拥挤了, 请稍后再试~~\";\n }\n\n private String defaultFallback() {\n return \"默认提示:太拥挤了, 请稍后再试~~\";\n }\n}\n"} {"task_id": "Java_2027", "language": "Java", "task_type": "if_statement", "source_file": "java/github/ZXZxin/zxorder/order/server/src/main/java/com/zxin/order/controller/HystrixController.java", "mask_start_position": 706, "mask_end_position": 768, "canonical_solution": "if (number % 2 == 0) {\n return \"success\";\n }", "pre_mask_code": "package com.zxin.order.controller;\n\nimport com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;\nimport com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.client.RestTemplate;\nimport java.util.Arrays;\n\n@RestController\n@DefaultProperties(defaultFallback = \"defaultFallback\")\npublic class HystrixController {\n\n // 超时配置\n @HystrixCommand\n @GetMapping(\"/getProductInfoList\")\n public String getProductInfoList(@RequestParam(\"number\") Integer number) {\n ", "post_mask_code": "\n RestTemplate restTemplate = new RestTemplate();\n return restTemplate.postForObject(\"http://127.0.0.1:8005/product/listForOrder\", Arrays.asList(\"157875196366160022\"), String.class);\n }\n\n private String fallback() {\n return \"太拥挤了, 请稍后再试~~\";\n }\n\n private String defaultFallback() {\n return \"默认提示:太拥挤了, 请稍后再试~~\";\n }\n}\n"} {"task_id": "Java_2028", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/geogebra/geogebra/desktop/src/main/java/org/jfugue/JFugueElement.java", "mask_start_position": 567, "mask_end_position": 598, "canonical_solution": "public String getMusicString();", "pre_mask_code": "package org.jfugue;\n\n/**\n * This is the base class for the JFugue elements, including Voice, Instrument,\n * Note, Controller, and Tempo. It requires that elements be able to return a\n * Music String representation of their settings.\n *\n * @author David Koelle\n * @version 2.0\n * @version 4.0 - Added getVerifyString()\n * @version 4.0.3 - Now extends Serializable\n */\npublic interface JFugueElement {\n\n /**\n * Returns the Music String representing this element and all of its\n * settings.\n *\n * @return the Music String for this element\n */\n ", "post_mask_code": "\n\n /**\n * Returns a verification string, which should contain a String\n * representation of all of the aspects of the given element. This should be\n * in the following form: Thing: key=value, key=value, key=value,... For\n * example: Note: value=60, duration=0.25\n *\n * @version 4.0\n */\n public String getVerifyString();\n}\n"} {"task_id": "Java_2029", "language": "Java", "task_type": "method_signature", "source_file": "java/github/halestudio/hale/ui/plugins/eu.esdihumboldt.hale.ui.views.data/src/eu/esdihumboldt/hale/ui/views/data/internal/explore/MetadataExploreActionProvider.java", "mask_start_position": 1253, "mask_end_position": 1367, "canonical_solution": "@SuppressWarnings(\"unchecked\")\n @Override\n protected Pair retrieveMetadata(ViewerCell cell) ", "pre_mask_code": "/*\n * \n * published by the Free Software Foundation, either version 3 of the License,\n * or (at your option) any later version.\n * \n * You should have received a copy of the GNU Lesser General Public License\n * along with this distribution. If not, see .\n * \n * Contributors:\n * HUMBOLDT EU Integrated Project #030962\n * Data Harmonisation Panel \n */\npackage eu.esdihumboldt.hale.ui.views.data.internal.explore;\n\nimport org.eclipse.jface.viewers.TreeViewer;\nimport org.eclipse.jface.viewers.ViewerCell;\nimport eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider;\nimport eu.esdihumboldt.util.Pair;\n\n/**\n * Provides metadata actions for {@link TreeViewer}s used for data views explore\n * mode\n *\n * @author Sebastian Reinhardt\n */\npublic class MetadataExploreActionProvider extends MetadataActionProvider {\n\n /**\n * Standard Constructor\n *\n * @param treeViewer the TreeViewer to which the action will be applied\n */\n public MetadataExploreActionProvider(TreeViewer treeViewer) {\n super(treeViewer);\n }\n\n /**\n * @see eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider#retrieveMetadata(org.eclipse.jface.viewers.ViewerCell)\n */\n ", "post_mask_code": "{\n return (Pair) cell.getElement();\n }\n}\n"} {"task_id": "Java_2030", "language": "Java", "task_type": "method_body", "source_file": "java/github/halestudio/hale/ui/plugins/eu.esdihumboldt.hale.ui.views.data/src/eu/esdihumboldt/hale/ui/views/data/internal/explore/MetadataExploreActionProvider.java", "mask_start_position": 1367, "mask_end_position": 1431, "canonical_solution": "{\n return (Pair) cell.getElement();\n }", "pre_mask_code": "/*\n * \n * published by the Free Software Foundation, either version 3 of the License,\n * or (at your option) any later version.\n * \n * You should have received a copy of the GNU Lesser General Public License\n * along with this distribution. If not, see .\n * \n * Contributors:\n * HUMBOLDT EU Integrated Project #030962\n * Data Harmonisation Panel \n */\npackage eu.esdihumboldt.hale.ui.views.data.internal.explore;\n\nimport org.eclipse.jface.viewers.TreeViewer;\nimport org.eclipse.jface.viewers.ViewerCell;\nimport eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider;\nimport eu.esdihumboldt.util.Pair;\n\n/**\n * Provides metadata actions for {@link TreeViewer}s used for data views explore\n * mode\n *\n * @author Sebastian Reinhardt\n */\npublic class MetadataExploreActionProvider extends MetadataActionProvider {\n\n /**\n * Standard Constructor\n *\n * @param treeViewer the TreeViewer to which the action will be applied\n */\n public MetadataExploreActionProvider(TreeViewer treeViewer) {\n super(treeViewer);\n }\n\n /**\n * @see eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider#retrieveMetadata(org.eclipse.jface.viewers.ViewerCell)\n */\n @SuppressWarnings(\"unchecked\")\n @Override\n protected Pair retrieveMetadata(ViewerCell cell) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2031", "language": "Java", "task_type": "single_line", "source_file": "java/github/halestudio/hale/ui/plugins/eu.esdihumboldt.hale.ui.views.data/src/eu/esdihumboldt/hale/ui/views/data/internal/explore/MetadataExploreActionProvider.java", "mask_start_position": 1385, "mask_end_position": 1425, "canonical_solution": "Pair) cell.getElement();", "pre_mask_code": "/*\n * \n * published by the Free Software Foundation, either version 3 of the License,\n * or (at your option) any later version.\n * \n * You should have received a copy of the GNU Lesser General Public License\n * along with this distribution. If not, see .\n * \n * Contributors:\n * HUMBOLDT EU Integrated Project #030962\n * Data Harmonisation Panel \n */\npackage eu.esdihumboldt.hale.ui.views.data.internal.explore;\n\nimport org.eclipse.jface.viewers.TreeViewer;\nimport org.eclipse.jface.viewers.ViewerCell;\nimport eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider;\nimport eu.esdihumboldt.util.Pair;\n\n/**\n * Provides metadata actions for {@link TreeViewer}s used for data views explore\n * mode\n *\n * @author Sebastian Reinhardt\n */\npublic class MetadataExploreActionProvider extends MetadataActionProvider {\n\n /**\n * Standard Constructor\n *\n * @param treeViewer the TreeViewer to which the action will be applied\n */\n public MetadataExploreActionProvider(TreeViewer treeViewer) {\n super(treeViewer);\n }\n\n /**\n * @see eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider#retrieveMetadata(org.eclipse.jface.viewers.ViewerCell)\n */\n @SuppressWarnings(\"unchecked\")\n @Override\n protected Pair retrieveMetadata(ViewerCell cell) {\n return (", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2032", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/halestudio/hale/ui/plugins/eu.esdihumboldt.hale.ui.views.data/src/eu/esdihumboldt/hale/ui/views/data/internal/explore/MetadataExploreActionProvider.java", "mask_start_position": 1253, "mask_end_position": 1431, "canonical_solution": "@SuppressWarnings(\"unchecked\")\n @Override\n protected Pair retrieveMetadata(ViewerCell cell) {\n return (Pair) cell.getElement();\n }", "pre_mask_code": "/*\n * \n * published by the Free Software Foundation, either version 3 of the License,\n * or (at your option) any later version.\n * \n * You should have received a copy of the GNU Lesser General Public License\n * along with this distribution. If not, see .\n * \n * Contributors:\n * HUMBOLDT EU Integrated Project #030962\n * Data Harmonisation Panel \n */\npackage eu.esdihumboldt.hale.ui.views.data.internal.explore;\n\nimport org.eclipse.jface.viewers.TreeViewer;\nimport org.eclipse.jface.viewers.ViewerCell;\nimport eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider;\nimport eu.esdihumboldt.util.Pair;\n\n/**\n * Provides metadata actions for {@link TreeViewer}s used for data views explore\n * mode\n *\n * @author Sebastian Reinhardt\n */\npublic class MetadataExploreActionProvider extends MetadataActionProvider {\n\n /**\n * Standard Constructor\n *\n * @param treeViewer the TreeViewer to which the action will be applied\n */\n public MetadataExploreActionProvider(TreeViewer treeViewer) {\n super(treeViewer);\n }\n\n /**\n * @see eu.esdihumboldt.hale.ui.views.data.internal.MetadataActionProvider#retrieveMetadata(org.eclipse.jface.viewers.ViewerCell)\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2033", "language": "Java", "task_type": "method_signature", "source_file": "java/github/spacecowboy/NoNonsense-FilePicker/sample/src/main/java/com/nononsenseapps/filepicker/sample/ftp/FtpPickerActivity.java", "mask_start_position": 455, "mask_end_position": 660, "canonical_solution": "@Override\n protected AbstractFilePickerFragment getFragment(@Nullable String startPath, int mode, boolean allowMultiple, boolean allowCreateDir, boolean allowExistingFile, boolean singleClick) ", "pre_mask_code": "package com.nononsenseapps.filepicker.sample.ftp;\n\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport com.nononsenseapps.filepicker.AbstractFilePickerActivity;\nimport com.nononsenseapps.filepicker.AbstractFilePickerFragment;\nimport org.apache.commons.net.ftp.FTPClient;\n\n/**\n * An example implementation of an FTP file-picker\n */\npublic class FtpPickerActivity extends AbstractFilePickerActivity {\n\n ", "post_mask_code": "{\n return FtpPickerFragment.newInstance(startPath, mode, allowMultiple, allowCreateDir, allowExistingFile, singleClick, \"debian.simnet.is\", FTPClient.DEFAULT_PORT, null, null, \"/\");\n }\n}\n"} {"task_id": "Java_2034", "language": "Java", "task_type": "method_body", "source_file": "java/github/spacecowboy/NoNonsense-FilePicker/sample/src/main/java/com/nononsenseapps/filepicker/sample/ftp/FtpPickerActivity.java", "mask_start_position": 660, "mask_end_position": 854, "canonical_solution": "{\n return FtpPickerFragment.newInstance(startPath, mode, allowMultiple, allowCreateDir, allowExistingFile, singleClick, \"debian.simnet.is\", FTPClient.DEFAULT_PORT, null, null, \"/\");\n }", "pre_mask_code": "package com.nononsenseapps.filepicker.sample.ftp;\n\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport com.nononsenseapps.filepicker.AbstractFilePickerActivity;\nimport com.nononsenseapps.filepicker.AbstractFilePickerFragment;\nimport org.apache.commons.net.ftp.FTPClient;\n\n/**\n * An example implementation of an FTP file-picker\n */\npublic class FtpPickerActivity extends AbstractFilePickerActivity {\n\n @Override\n protected AbstractFilePickerFragment getFragment(@Nullable String startPath, int mode, boolean allowMultiple, boolean allowCreateDir, boolean allowExistingFile, boolean singleClick) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2035", "language": "Java", "task_type": "single_line", "source_file": "java/github/spacecowboy/NoNonsense-FilePicker/sample/src/main/java/com/nononsenseapps/filepicker/sample/ftp/FtpPickerActivity.java", "mask_start_position": 719, "mask_end_position": 848, "canonical_solution": "ode, allowMultiple, allowCreateDir, allowExistingFile, singleClick, \"debian.simnet.is\", FTPClient.DEFAULT_PORT, null, null, \"/\");", "pre_mask_code": "package com.nononsenseapps.filepicker.sample.ftp;\n\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport com.nononsenseapps.filepicker.AbstractFilePickerActivity;\nimport com.nononsenseapps.filepicker.AbstractFilePickerFragment;\nimport org.apache.commons.net.ftp.FTPClient;\n\n/**\n * An example implementation of an FTP file-picker\n */\npublic class FtpPickerActivity extends AbstractFilePickerActivity {\n\n @Override\n protected AbstractFilePickerFragment getFragment(@Nullable String startPath, int mode, boolean allowMultiple, boolean allowCreateDir, boolean allowExistingFile, boolean singleClick) {\n return FtpPickerFragment.newInstance(startPath, m", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2036", "language": "Java", "task_type": "method_signature", "source_file": "java/github/robo-code/robocode/robocode.core/src/main/java/net/sf/robocode/peer/TeamMessage.java", "mask_start_position": 1188, "mask_end_position": 1269, "canonical_solution": "public void serialize(RbSerializer serializer, ByteBuffer buffer, Object object) ", "pre_mask_code": "package net.sf.robocode.peer;\n\nimport net.sf.robocode.serialization.ISerializableHelper;\nimport net.sf.robocode.serialization.RbSerializer;\nimport java.io.Serializable;\nimport java.nio.ByteBuffer;\n\n/**\n * @author Pavel Savara (original)\n */\npublic class TeamMessage implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n public TeamMessage(String sender, String recipient, byte[] message) {\n this.sender = sender;\n this.recipient = recipient;\n this.message = message;\n }\n\n public final String sender;\n\n public final String recipient;\n\n public final byte[] message;\n\n static ISerializableHelper createHiddenSerializer() {\n return new SerializableHelper();\n }\n\n private static class SerializableHelper implements ISerializableHelper {\n\n public int sizeOf(RbSerializer serializer, Object object) {\n TeamMessage obj = (TeamMessage) object;\n final int s = serializer.sizeOf(obj.sender);\n final int r = serializer.sizeOf(obj.recipient);\n final int m = serializer.sizeOf(obj.message);\n return RbSerializer.SIZEOF_TYPEINFO + s + r + m;\n }\n\n ", "post_mask_code": "{\n TeamMessage obj = (TeamMessage) object;\n serializer.serialize(buffer, obj.sender);\n serializer.serialize(buffer, obj.recipient);\n serializer.serialize(buffer, obj.message);\n }\n\n public Object deserialize(RbSerializer serializer, ByteBuffer buffer) {\n String sender = serializer.deserializeString(buffer);\n String recipient = serializer.deserializeString(buffer);\n byte[] message = serializer.deserializeBytes(buffer);\n return new TeamMessage(sender, recipient, message);\n }\n }\n}\n"} {"task_id": "Java_2037", "language": "Java", "task_type": "method_body", "source_file": "java/github/robo-code/robocode/robocode.core/src/main/java/net/sf/robocode/peer/TeamMessage.java", "mask_start_position": 879, "mask_end_position": 1178, "canonical_solution": "{\n TeamMessage obj = (TeamMessage) object;\n final int s = serializer.sizeOf(obj.sender);\n final int r = serializer.sizeOf(obj.recipient);\n final int m = serializer.sizeOf(obj.message);\n return RbSerializer.SIZEOF_TYPEINFO + s + r + m;\n }", "pre_mask_code": "package net.sf.robocode.peer;\n\nimport net.sf.robocode.serialization.ISerializableHelper;\nimport net.sf.robocode.serialization.RbSerializer;\nimport java.io.Serializable;\nimport java.nio.ByteBuffer;\n\n/**\n * @author Pavel Savara (original)\n */\npublic class TeamMessage implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n public TeamMessage(String sender, String recipient, byte[] message) {\n this.sender = sender;\n this.recipient = recipient;\n this.message = message;\n }\n\n public final String sender;\n\n public final String recipient;\n\n public final byte[] message;\n\n static ISerializableHelper createHiddenSerializer() {\n return new SerializableHelper();\n }\n\n private static class SerializableHelper implements ISerializableHelper {\n\n public int sizeOf(RbSerializer serializer, Object object) ", "post_mask_code": "\n\n public void serialize(RbSerializer serializer, ByteBuffer buffer, Object object) {\n TeamMessage obj = (TeamMessage) object;\n serializer.serialize(buffer, obj.sender);\n serializer.serialize(buffer, obj.recipient);\n serializer.serialize(buffer, obj.message);\n }\n\n public Object deserialize(RbSerializer serializer, ByteBuffer buffer) {\n String sender = serializer.deserializeString(buffer);\n String recipient = serializer.deserializeString(buffer);\n byte[] message = serializer.deserializeBytes(buffer);\n return new TeamMessage(sender, recipient, message);\n }\n }\n}\n"} {"task_id": "Java_2038", "language": "Java", "task_type": "single_line", "source_file": "java/github/robo-code/robocode/robocode.core/src/main/java/net/sf/robocode/peer/TeamMessage.java", "mask_start_position": 1472, "mask_end_position": 1488, "canonical_solution": "r, obj.message);", "pre_mask_code": "package net.sf.robocode.peer;\n\nimport net.sf.robocode.serialization.ISerializableHelper;\nimport net.sf.robocode.serialization.RbSerializer;\nimport java.io.Serializable;\nimport java.nio.ByteBuffer;\n\n/**\n * @author Pavel Savara (original)\n */\npublic class TeamMessage implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n public TeamMessage(String sender, String recipient, byte[] message) {\n this.sender = sender;\n this.recipient = recipient;\n this.message = message;\n }\n\n public final String sender;\n\n public final String recipient;\n\n public final byte[] message;\n\n static ISerializableHelper createHiddenSerializer() {\n return new SerializableHelper();\n }\n\n private static class SerializableHelper implements ISerializableHelper {\n\n public int sizeOf(RbSerializer serializer, Object object) {\n TeamMessage obj = (TeamMessage) object;\n final int s = serializer.sizeOf(obj.sender);\n final int r = serializer.sizeOf(obj.recipient);\n final int m = serializer.sizeOf(obj.message);\n return RbSerializer.SIZEOF_TYPEINFO + s + r + m;\n }\n\n public void serialize(RbSerializer serializer, ByteBuffer buffer, Object object) {\n TeamMessage obj = (TeamMessage) object;\n serializer.serialize(buffer, obj.sender);\n serializer.serialize(buffer, obj.recipient);\n serializer.serialize(buffe", "post_mask_code": "\n }\n\n public Object deserialize(RbSerializer serializer, ByteBuffer buffer) {\n String sender = serializer.deserializeString(buffer);\n String recipient = serializer.deserializeString(buffer);\n byte[] message = serializer.deserializeBytes(buffer);\n return new TeamMessage(sender, recipient, message);\n }\n }\n}\n"} {"task_id": "Java_2039", "language": "Java", "task_type": "method_signature", "source_file": "java/github/trylimits/Eclipse-Postfix-Code-Completion/luna/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/ClassPathDetector.java", "mask_start_position": 12149, "mask_end_position": 12203, "canonical_solution": "private boolean hasExtension(String name, String ext) ", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic\n * *****************************************************************************\n */\npackage org.eclipse.jdt.internal.ui.wizards;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport com.ibm.icu.text.Collator;\nimport org.eclipse.core.runtime.CoreException;\nimport org.eclipse.core.runtime.IPath;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.IStatus;\nimport org.eclipse.core.runtime.NullProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\nimport org.eclipse.core.runtime.Path;\nimport org.eclipse.core.runtime.Status;\nimport org.eclipse.core.resources.IFile;\nimport org.eclipse.core.resources.IProject;\nimport org.eclipse.core.resources.IResource;\nimport org.eclipse.core.resources.IResourceProxy;\nimport org.eclipse.core.resources.IResourceProxyVisitor;\nimport org.eclipse.jdt.core.IClasspathEntry;\nimport org.eclipse.jdt.core.ICompilationUnit;\nimport org.eclipse.jdt.core.JavaConventions;\nimport org.eclipse.jdt.core.JavaCore;\nimport org.eclipse.jdt.core.ToolFactory;\nimport org.eclipse.jdt.core.compiler.CharOperation;\nimport org.eclipse.jdt.core.dom.ASTParser;\nimport org.eclipse.jdt.core.dom.CompilationUnit;\nimport org.eclipse.jdt.core.dom.PackageDeclaration;\nimport org.eclipse.jdt.core.util.IClassFileReader;\nimport org.eclipse.jdt.core.util.ISourceAttribute;\nimport org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;\nimport org.eclipse.jdt.internal.corext.util.Messages;\nimport org.eclipse.jdt.ui.PreferenceConstants;\nimport org.eclipse.jdt.internal.ui.JavaPlugin;\nimport org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;\nimport org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;\n\npublic class ClassPathDetector implements IResourceProxyVisitor {\n\n private HashMap> fSourceFolders;\n\n private List fClassFiles;\n\n private HashSet fJARFiles;\n\n private IProject fProject;\n\n private IPath fResultOutputFolder;\n\n private IClasspathEntry[] fResultClasspath;\n\n private IProgressMonitor fMonitor;\n\n private static class CPSorter implements Comparator {\n\n private Collator fCollator = Collator.getInstance();\n\n public int compare(IClasspathEntry e1, IClasspathEntry e2) {\n return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());\n }\n }\n\n public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {\n fSourceFolders = new HashMap>();\n fJARFiles = new HashSet(10);\n fClassFiles = new ArrayList(100);\n fProject = project;\n fResultClasspath = null;\n fResultOutputFolder = null;\n if (monitor == null) {\n monitor = new NullProgressMonitor();\n }\n detectClasspath(monitor);\n }\n\n private boolean isNested(IPath path, Iterator iter) {\n while (iter.hasNext()) {\n IPath other = iter.next();\n if (other.isPrefixOf(path)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Method detectClasspath.\n *\n * @param monitor The progress monitor (not null)\n * @throws CoreException in case of any failure\n */\n private void detectClasspath(IProgressMonitor monitor) throws CoreException {\n try {\n monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);\n fMonitor = monitor;\n fProject.accept(this, IResource.NONE);\n monitor.worked(1);\n ArrayList cpEntries = new ArrayList();\n detectSourceFolders(cpEntries);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n IPath outputLocation = detectOutputFolder();\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n detectLibraries(cpEntries, outputLocation);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {\n return;\n }\n IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();\n for (int i = 0; i < jreEntries.length; i++) {\n cpEntries.add(jreEntries[i]);\n }\n IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);\n if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {\n return;\n }\n fResultClasspath = entries;\n fResultOutputFolder = outputLocation;\n } finally {\n monitor.done();\n }\n }\n\n private IPath findInSourceFolders(IPath path) {\n Iterator iter = fSourceFolders.keySet().iterator();\n while (iter.hasNext()) {\n Object key = iter.next();\n List cus = fSourceFolders.get(key);\n if (cus.contains(path)) {\n return (IPath) key;\n }\n }\n return null;\n }\n\n private IPath detectOutputFolder() throws CoreException {\n HashSet classFolders = new HashSet();\n for (Iterator iter = fClassFiles.iterator(); iter.hasNext(); ) {\n IFile file = (IFile) iter.next();\n IClassFileReader reader = null;\n InputStream content = null;\n try {\n content = file.getContents();\n reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);\n } finally {\n try {\n if (content != null)\n content.close();\n } catch (IOException e) {\n throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));\n }\n }\n if (reader == null) {\n // problematic class file\n continue;\n }\n char[] className = reader.getClassName();\n ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();\n if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {\n IPath packPath = file.getParent().getFullPath();\n int idx = CharOperation.lastIndexOf('/', className) + 1;\n IPath relPath = new Path(new String(className, 0, idx));\n IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));\n IPath resPath = null;\n if (idx == 0) {\n resPath = packPath;\n } else {\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n resPath = folderPath;\n }\n }\n if (resPath != null) {\n IPath path = findInSourceFolders(cuPath);\n if (path != null) {\n return resPath;\n } else {\n classFolders.add(resPath);\n }\n }\n }\n }\n IPath projPath = fProject.getFullPath();\n if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {\n return projPath;\n } else {\n IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));\n while (classFolders.contains(path)) {\n path = new Path(path.toString() + '1');\n }\n return path;\n }\n }\n\n private void detectLibraries(ArrayList cpEntries, IPath outputLocation) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = fJARFiles.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n if (isNested(path, sourceFolderSet.iterator())) {\n continue;\n }\n if (outputLocation != null && outputLocation.isPrefixOf(path)) {\n continue;\n }\n IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n cpEntries.addAll(res);\n }\n\n private void detectSourceFolders(ArrayList resEntries) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = sourceFolderSet.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n ArrayList excluded = new ArrayList();\n for (Iterator inner = sourceFolderSet.iterator(); inner.hasNext(); ) {\n IPath other = inner.next();\n if (!path.equals(other) && path.isPrefixOf(other)) {\n IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();\n excluded.add(pathToExclude);\n }\n }\n IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);\n IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n resEntries.addAll(res);\n }\n\n private void visitCompilationUnit(IFile file) {\n ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);\n if (cu != null) {\n ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);\n parser.setSource(cu);\n parser.setFocalPosition(0);\n CompilationUnit root = (CompilationUnit) parser.createAST(null);\n PackageDeclaration packDecl = root.getPackage();\n IPath packPath = file.getParent().getFullPath();\n String cuName = file.getName();\n if (packDecl == null) {\n addToMap(fSourceFolders, packPath, new Path(cuName));\n } else {\n IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n addToMap(fSourceFolders, folderPath, relPath.append(cuName));\n }\n }\n }\n }\n\n private void addToMap(HashMap> map, IPath folderPath, IPath relPath) {\n List list = map.get(folderPath);\n if (list == null) {\n list = new ArrayList(50);\n map.put(folderPath, list);\n }\n list.add(relPath);\n }\n\n private IPath getFolderPath(IPath packPath, IPath relpath) {\n int remainingSegments = packPath.segmentCount() - relpath.segmentCount();\n if (remainingSegments >= 0) {\n IPath common = packPath.removeFirstSegments(remainingSegments);\n if (common.equals(relpath)) {\n return packPath.uptoSegment(remainingSegments);\n }\n }\n return null;\n }\n\n ", "post_mask_code": "{\n return name.endsWith(ext) && (ext.length() != name.length());\n }\n\n private boolean isValidCUName(String name) {\n return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);\n }\n\n /* (non-Javadoc)\n\t * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)\n\t */\n public boolean visit(IResourceProxy proxy) {\n if (fMonitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n if (proxy.getType() == IResource.FILE) {\n String name = proxy.getName();\n if (isValidCUName(name)) {\n visitCompilationUnit((IFile) proxy.requestResource());\n } else if (hasExtension(name, \".class\")) {\n fClassFiles.add(proxy.requestResource());\n } else if (hasExtension(name, \".jar\")) {\n fJARFiles.add(proxy.requestFullPath());\n }\n return false;\n }\n return true;\n }\n\n public IPath getOutputLocation() {\n return fResultOutputFolder;\n }\n\n public IClasspathEntry[] getClasspath() {\n if (fResultClasspath == null)\n return new IClasspathEntry[0];\n return fResultClasspath;\n }\n}\n"} {"task_id": "Java_2040", "language": "Java", "task_type": "method_body", "source_file": "java/github/trylimits/Eclipse-Postfix-Code-Completion/luna/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/ClassPathDetector.java", "mask_start_position": 11520, "mask_end_position": 11724, "canonical_solution": "{\n List list = map.get(folderPath);\n if (list == null) {\n list = new ArrayList(50);\n map.put(folderPath, list);\n }\n list.add(relPath);\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic\n * *****************************************************************************\n */\npackage org.eclipse.jdt.internal.ui.wizards;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport com.ibm.icu.text.Collator;\nimport org.eclipse.core.runtime.CoreException;\nimport org.eclipse.core.runtime.IPath;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.IStatus;\nimport org.eclipse.core.runtime.NullProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\nimport org.eclipse.core.runtime.Path;\nimport org.eclipse.core.runtime.Status;\nimport org.eclipse.core.resources.IFile;\nimport org.eclipse.core.resources.IProject;\nimport org.eclipse.core.resources.IResource;\nimport org.eclipse.core.resources.IResourceProxy;\nimport org.eclipse.core.resources.IResourceProxyVisitor;\nimport org.eclipse.jdt.core.IClasspathEntry;\nimport org.eclipse.jdt.core.ICompilationUnit;\nimport org.eclipse.jdt.core.JavaConventions;\nimport org.eclipse.jdt.core.JavaCore;\nimport org.eclipse.jdt.core.ToolFactory;\nimport org.eclipse.jdt.core.compiler.CharOperation;\nimport org.eclipse.jdt.core.dom.ASTParser;\nimport org.eclipse.jdt.core.dom.CompilationUnit;\nimport org.eclipse.jdt.core.dom.PackageDeclaration;\nimport org.eclipse.jdt.core.util.IClassFileReader;\nimport org.eclipse.jdt.core.util.ISourceAttribute;\nimport org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;\nimport org.eclipse.jdt.internal.corext.util.Messages;\nimport org.eclipse.jdt.ui.PreferenceConstants;\nimport org.eclipse.jdt.internal.ui.JavaPlugin;\nimport org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;\nimport org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;\n\npublic class ClassPathDetector implements IResourceProxyVisitor {\n\n private HashMap> fSourceFolders;\n\n private List fClassFiles;\n\n private HashSet fJARFiles;\n\n private IProject fProject;\n\n private IPath fResultOutputFolder;\n\n private IClasspathEntry[] fResultClasspath;\n\n private IProgressMonitor fMonitor;\n\n private static class CPSorter implements Comparator {\n\n private Collator fCollator = Collator.getInstance();\n\n public int compare(IClasspathEntry e1, IClasspathEntry e2) {\n return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());\n }\n }\n\n public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {\n fSourceFolders = new HashMap>();\n fJARFiles = new HashSet(10);\n fClassFiles = new ArrayList(100);\n fProject = project;\n fResultClasspath = null;\n fResultOutputFolder = null;\n if (monitor == null) {\n monitor = new NullProgressMonitor();\n }\n detectClasspath(monitor);\n }\n\n private boolean isNested(IPath path, Iterator iter) {\n while (iter.hasNext()) {\n IPath other = iter.next();\n if (other.isPrefixOf(path)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Method detectClasspath.\n *\n * @param monitor The progress monitor (not null)\n * @throws CoreException in case of any failure\n */\n private void detectClasspath(IProgressMonitor monitor) throws CoreException {\n try {\n monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);\n fMonitor = monitor;\n fProject.accept(this, IResource.NONE);\n monitor.worked(1);\n ArrayList cpEntries = new ArrayList();\n detectSourceFolders(cpEntries);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n IPath outputLocation = detectOutputFolder();\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n detectLibraries(cpEntries, outputLocation);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {\n return;\n }\n IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();\n for (int i = 0; i < jreEntries.length; i++) {\n cpEntries.add(jreEntries[i]);\n }\n IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);\n if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {\n return;\n }\n fResultClasspath = entries;\n fResultOutputFolder = outputLocation;\n } finally {\n monitor.done();\n }\n }\n\n private IPath findInSourceFolders(IPath path) {\n Iterator iter = fSourceFolders.keySet().iterator();\n while (iter.hasNext()) {\n Object key = iter.next();\n List cus = fSourceFolders.get(key);\n if (cus.contains(path)) {\n return (IPath) key;\n }\n }\n return null;\n }\n\n private IPath detectOutputFolder() throws CoreException {\n HashSet classFolders = new HashSet();\n for (Iterator iter = fClassFiles.iterator(); iter.hasNext(); ) {\n IFile file = (IFile) iter.next();\n IClassFileReader reader = null;\n InputStream content = null;\n try {\n content = file.getContents();\n reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);\n } finally {\n try {\n if (content != null)\n content.close();\n } catch (IOException e) {\n throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));\n }\n }\n if (reader == null) {\n // problematic class file\n continue;\n }\n char[] className = reader.getClassName();\n ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();\n if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {\n IPath packPath = file.getParent().getFullPath();\n int idx = CharOperation.lastIndexOf('/', className) + 1;\n IPath relPath = new Path(new String(className, 0, idx));\n IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));\n IPath resPath = null;\n if (idx == 0) {\n resPath = packPath;\n } else {\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n resPath = folderPath;\n }\n }\n if (resPath != null) {\n IPath path = findInSourceFolders(cuPath);\n if (path != null) {\n return resPath;\n } else {\n classFolders.add(resPath);\n }\n }\n }\n }\n IPath projPath = fProject.getFullPath();\n if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {\n return projPath;\n } else {\n IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));\n while (classFolders.contains(path)) {\n path = new Path(path.toString() + '1');\n }\n return path;\n }\n }\n\n private void detectLibraries(ArrayList cpEntries, IPath outputLocation) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = fJARFiles.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n if (isNested(path, sourceFolderSet.iterator())) {\n continue;\n }\n if (outputLocation != null && outputLocation.isPrefixOf(path)) {\n continue;\n }\n IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n cpEntries.addAll(res);\n }\n\n private void detectSourceFolders(ArrayList resEntries) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = sourceFolderSet.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n ArrayList excluded = new ArrayList();\n for (Iterator inner = sourceFolderSet.iterator(); inner.hasNext(); ) {\n IPath other = inner.next();\n if (!path.equals(other) && path.isPrefixOf(other)) {\n IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();\n excluded.add(pathToExclude);\n }\n }\n IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);\n IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n resEntries.addAll(res);\n }\n\n private void visitCompilationUnit(IFile file) {\n ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);\n if (cu != null) {\n ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);\n parser.setSource(cu);\n parser.setFocalPosition(0);\n CompilationUnit root = (CompilationUnit) parser.createAST(null);\n PackageDeclaration packDecl = root.getPackage();\n IPath packPath = file.getParent().getFullPath();\n String cuName = file.getName();\n if (packDecl == null) {\n addToMap(fSourceFolders, packPath, new Path(cuName));\n } else {\n IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n addToMap(fSourceFolders, folderPath, relPath.append(cuName));\n }\n }\n }\n }\n\n private void addToMap(HashMap> map, IPath folderPath, IPath relPath) ", "post_mask_code": "\n\n private IPath getFolderPath(IPath packPath, IPath relpath) {\n int remainingSegments = packPath.segmentCount() - relpath.segmentCount();\n if (remainingSegments >= 0) {\n IPath common = packPath.removeFirstSegments(remainingSegments);\n if (common.equals(relpath)) {\n return packPath.uptoSegment(remainingSegments);\n }\n }\n return null;\n }\n\n private boolean hasExtension(String name, String ext) {\n return name.endsWith(ext) && (ext.length() != name.length());\n }\n\n private boolean isValidCUName(String name) {\n return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);\n }\n\n /* (non-Javadoc)\n\t * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)\n\t */\n public boolean visit(IResourceProxy proxy) {\n if (fMonitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n if (proxy.getType() == IResource.FILE) {\n String name = proxy.getName();\n if (isValidCUName(name)) {\n visitCompilationUnit((IFile) proxy.requestResource());\n } else if (hasExtension(name, \".class\")) {\n fClassFiles.add(proxy.requestResource());\n } else if (hasExtension(name, \".jar\")) {\n fJARFiles.add(proxy.requestFullPath());\n }\n return false;\n }\n return true;\n }\n\n public IPath getOutputLocation() {\n return fResultOutputFolder;\n }\n\n public IClasspathEntry[] getClasspath() {\n if (fResultClasspath == null)\n return new IClasspathEntry[0];\n return fResultClasspath;\n }\n}\n"} {"task_id": "Java_2041", "language": "Java", "task_type": "single_line", "source_file": "java/github/trylimits/Eclipse-Postfix-Code-Completion/luna/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/ClassPathDetector.java", "mask_start_position": 13459, "mask_end_position": 13483, "canonical_solution": "return fResultClasspath;", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic\n * *****************************************************************************\n */\npackage org.eclipse.jdt.internal.ui.wizards;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport com.ibm.icu.text.Collator;\nimport org.eclipse.core.runtime.CoreException;\nimport org.eclipse.core.runtime.IPath;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.IStatus;\nimport org.eclipse.core.runtime.NullProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\nimport org.eclipse.core.runtime.Path;\nimport org.eclipse.core.runtime.Status;\nimport org.eclipse.core.resources.IFile;\nimport org.eclipse.core.resources.IProject;\nimport org.eclipse.core.resources.IResource;\nimport org.eclipse.core.resources.IResourceProxy;\nimport org.eclipse.core.resources.IResourceProxyVisitor;\nimport org.eclipse.jdt.core.IClasspathEntry;\nimport org.eclipse.jdt.core.ICompilationUnit;\nimport org.eclipse.jdt.core.JavaConventions;\nimport org.eclipse.jdt.core.JavaCore;\nimport org.eclipse.jdt.core.ToolFactory;\nimport org.eclipse.jdt.core.compiler.CharOperation;\nimport org.eclipse.jdt.core.dom.ASTParser;\nimport org.eclipse.jdt.core.dom.CompilationUnit;\nimport org.eclipse.jdt.core.dom.PackageDeclaration;\nimport org.eclipse.jdt.core.util.IClassFileReader;\nimport org.eclipse.jdt.core.util.ISourceAttribute;\nimport org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;\nimport org.eclipse.jdt.internal.corext.util.Messages;\nimport org.eclipse.jdt.ui.PreferenceConstants;\nimport org.eclipse.jdt.internal.ui.JavaPlugin;\nimport org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;\nimport org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;\n\npublic class ClassPathDetector implements IResourceProxyVisitor {\n\n private HashMap> fSourceFolders;\n\n private List fClassFiles;\n\n private HashSet fJARFiles;\n\n private IProject fProject;\n\n private IPath fResultOutputFolder;\n\n private IClasspathEntry[] fResultClasspath;\n\n private IProgressMonitor fMonitor;\n\n private static class CPSorter implements Comparator {\n\n private Collator fCollator = Collator.getInstance();\n\n public int compare(IClasspathEntry e1, IClasspathEntry e2) {\n return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());\n }\n }\n\n public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {\n fSourceFolders = new HashMap>();\n fJARFiles = new HashSet(10);\n fClassFiles = new ArrayList(100);\n fProject = project;\n fResultClasspath = null;\n fResultOutputFolder = null;\n if (monitor == null) {\n monitor = new NullProgressMonitor();\n }\n detectClasspath(monitor);\n }\n\n private boolean isNested(IPath path, Iterator iter) {\n while (iter.hasNext()) {\n IPath other = iter.next();\n if (other.isPrefixOf(path)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Method detectClasspath.\n *\n * @param monitor The progress monitor (not null)\n * @throws CoreException in case of any failure\n */\n private void detectClasspath(IProgressMonitor monitor) throws CoreException {\n try {\n monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);\n fMonitor = monitor;\n fProject.accept(this, IResource.NONE);\n monitor.worked(1);\n ArrayList cpEntries = new ArrayList();\n detectSourceFolders(cpEntries);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n IPath outputLocation = detectOutputFolder();\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n detectLibraries(cpEntries, outputLocation);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {\n return;\n }\n IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();\n for (int i = 0; i < jreEntries.length; i++) {\n cpEntries.add(jreEntries[i]);\n }\n IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);\n if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {\n return;\n }\n fResultClasspath = entries;\n fResultOutputFolder = outputLocation;\n } finally {\n monitor.done();\n }\n }\n\n private IPath findInSourceFolders(IPath path) {\n Iterator iter = fSourceFolders.keySet().iterator();\n while (iter.hasNext()) {\n Object key = iter.next();\n List cus = fSourceFolders.get(key);\n if (cus.contains(path)) {\n return (IPath) key;\n }\n }\n return null;\n }\n\n private IPath detectOutputFolder() throws CoreException {\n HashSet classFolders = new HashSet();\n for (Iterator iter = fClassFiles.iterator(); iter.hasNext(); ) {\n IFile file = (IFile) iter.next();\n IClassFileReader reader = null;\n InputStream content = null;\n try {\n content = file.getContents();\n reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);\n } finally {\n try {\n if (content != null)\n content.close();\n } catch (IOException e) {\n throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));\n }\n }\n if (reader == null) {\n // problematic class file\n continue;\n }\n char[] className = reader.getClassName();\n ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();\n if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {\n IPath packPath = file.getParent().getFullPath();\n int idx = CharOperation.lastIndexOf('/', className) + 1;\n IPath relPath = new Path(new String(className, 0, idx));\n IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));\n IPath resPath = null;\n if (idx == 0) {\n resPath = packPath;\n } else {\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n resPath = folderPath;\n }\n }\n if (resPath != null) {\n IPath path = findInSourceFolders(cuPath);\n if (path != null) {\n return resPath;\n } else {\n classFolders.add(resPath);\n }\n }\n }\n }\n IPath projPath = fProject.getFullPath();\n if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {\n return projPath;\n } else {\n IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));\n while (classFolders.contains(path)) {\n path = new Path(path.toString() + '1');\n }\n return path;\n }\n }\n\n private void detectLibraries(ArrayList cpEntries, IPath outputLocation) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = fJARFiles.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n if (isNested(path, sourceFolderSet.iterator())) {\n continue;\n }\n if (outputLocation != null && outputLocation.isPrefixOf(path)) {\n continue;\n }\n IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n cpEntries.addAll(res);\n }\n\n private void detectSourceFolders(ArrayList resEntries) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = sourceFolderSet.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n ArrayList excluded = new ArrayList();\n for (Iterator inner = sourceFolderSet.iterator(); inner.hasNext(); ) {\n IPath other = inner.next();\n if (!path.equals(other) && path.isPrefixOf(other)) {\n IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();\n excluded.add(pathToExclude);\n }\n }\n IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);\n IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n resEntries.addAll(res);\n }\n\n private void visitCompilationUnit(IFile file) {\n ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);\n if (cu != null) {\n ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);\n parser.setSource(cu);\n parser.setFocalPosition(0);\n CompilationUnit root = (CompilationUnit) parser.createAST(null);\n PackageDeclaration packDecl = root.getPackage();\n IPath packPath = file.getParent().getFullPath();\n String cuName = file.getName();\n if (packDecl == null) {\n addToMap(fSourceFolders, packPath, new Path(cuName));\n } else {\n IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n addToMap(fSourceFolders, folderPath, relPath.append(cuName));\n }\n }\n }\n }\n\n private void addToMap(HashMap> map, IPath folderPath, IPath relPath) {\n List list = map.get(folderPath);\n if (list == null) {\n list = new ArrayList(50);\n map.put(folderPath, list);\n }\n list.add(relPath);\n }\n\n private IPath getFolderPath(IPath packPath, IPath relpath) {\n int remainingSegments = packPath.segmentCount() - relpath.segmentCount();\n if (remainingSegments >= 0) {\n IPath common = packPath.removeFirstSegments(remainingSegments);\n if (common.equals(relpath)) {\n return packPath.uptoSegment(remainingSegments);\n }\n }\n return null;\n }\n\n private boolean hasExtension(String name, String ext) {\n return name.endsWith(ext) && (ext.length() != name.length());\n }\n\n private boolean isValidCUName(String name) {\n return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);\n }\n\n /* (non-Javadoc)\n\t * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)\n\t */\n public boolean visit(IResourceProxy proxy) {\n if (fMonitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n if (proxy.getType() == IResource.FILE) {\n String name = proxy.getName();\n if (isValidCUName(name)) {\n visitCompilationUnit((IFile) proxy.requestResource());\n } else if (hasExtension(name, \".class\")) {\n fClassFiles.add(proxy.requestResource());\n } else if (hasExtension(name, \".jar\")) {\n fJARFiles.add(proxy.requestFullPath());\n }\n return false;\n }\n return true;\n }\n\n public IPath getOutputLocation() {\n return fResultOutputFolder;\n }\n\n public IClasspathEntry[] getClasspath() {\n if (fResultClasspath == null)\n return new IClasspathEntry[0];\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2042", "language": "Java", "task_type": "if_statement", "source_file": "java/github/trylimits/Eclipse-Postfix-Code-Completion/luna/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/ClassPathDetector.java", "mask_start_position": 10967, "mask_end_position": 11410, "canonical_solution": "if (packDecl == null) {\n addToMap(fSourceFolders, packPath, new Path(cuName));\n } else {\n IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n addToMap(fSourceFolders, folderPath, relPath.append(cuName));\n }\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic\n * *****************************************************************************\n */\npackage org.eclipse.jdt.internal.ui.wizards;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport com.ibm.icu.text.Collator;\nimport org.eclipse.core.runtime.CoreException;\nimport org.eclipse.core.runtime.IPath;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.IStatus;\nimport org.eclipse.core.runtime.NullProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\nimport org.eclipse.core.runtime.Path;\nimport org.eclipse.core.runtime.Status;\nimport org.eclipse.core.resources.IFile;\nimport org.eclipse.core.resources.IProject;\nimport org.eclipse.core.resources.IResource;\nimport org.eclipse.core.resources.IResourceProxy;\nimport org.eclipse.core.resources.IResourceProxyVisitor;\nimport org.eclipse.jdt.core.IClasspathEntry;\nimport org.eclipse.jdt.core.ICompilationUnit;\nimport org.eclipse.jdt.core.JavaConventions;\nimport org.eclipse.jdt.core.JavaCore;\nimport org.eclipse.jdt.core.ToolFactory;\nimport org.eclipse.jdt.core.compiler.CharOperation;\nimport org.eclipse.jdt.core.dom.ASTParser;\nimport org.eclipse.jdt.core.dom.CompilationUnit;\nimport org.eclipse.jdt.core.dom.PackageDeclaration;\nimport org.eclipse.jdt.core.util.IClassFileReader;\nimport org.eclipse.jdt.core.util.ISourceAttribute;\nimport org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;\nimport org.eclipse.jdt.internal.corext.util.Messages;\nimport org.eclipse.jdt.ui.PreferenceConstants;\nimport org.eclipse.jdt.internal.ui.JavaPlugin;\nimport org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;\nimport org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;\n\npublic class ClassPathDetector implements IResourceProxyVisitor {\n\n private HashMap> fSourceFolders;\n\n private List fClassFiles;\n\n private HashSet fJARFiles;\n\n private IProject fProject;\n\n private IPath fResultOutputFolder;\n\n private IClasspathEntry[] fResultClasspath;\n\n private IProgressMonitor fMonitor;\n\n private static class CPSorter implements Comparator {\n\n private Collator fCollator = Collator.getInstance();\n\n public int compare(IClasspathEntry e1, IClasspathEntry e2) {\n return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());\n }\n }\n\n public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {\n fSourceFolders = new HashMap>();\n fJARFiles = new HashSet(10);\n fClassFiles = new ArrayList(100);\n fProject = project;\n fResultClasspath = null;\n fResultOutputFolder = null;\n if (monitor == null) {\n monitor = new NullProgressMonitor();\n }\n detectClasspath(monitor);\n }\n\n private boolean isNested(IPath path, Iterator iter) {\n while (iter.hasNext()) {\n IPath other = iter.next();\n if (other.isPrefixOf(path)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Method detectClasspath.\n *\n * @param monitor The progress monitor (not null)\n * @throws CoreException in case of any failure\n */\n private void detectClasspath(IProgressMonitor monitor) throws CoreException {\n try {\n monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);\n fMonitor = monitor;\n fProject.accept(this, IResource.NONE);\n monitor.worked(1);\n ArrayList cpEntries = new ArrayList();\n detectSourceFolders(cpEntries);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n IPath outputLocation = detectOutputFolder();\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n detectLibraries(cpEntries, outputLocation);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {\n return;\n }\n IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();\n for (int i = 0; i < jreEntries.length; i++) {\n cpEntries.add(jreEntries[i]);\n }\n IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);\n if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {\n return;\n }\n fResultClasspath = entries;\n fResultOutputFolder = outputLocation;\n } finally {\n monitor.done();\n }\n }\n\n private IPath findInSourceFolders(IPath path) {\n Iterator iter = fSourceFolders.keySet().iterator();\n while (iter.hasNext()) {\n Object key = iter.next();\n List cus = fSourceFolders.get(key);\n if (cus.contains(path)) {\n return (IPath) key;\n }\n }\n return null;\n }\n\n private IPath detectOutputFolder() throws CoreException {\n HashSet classFolders = new HashSet();\n for (Iterator iter = fClassFiles.iterator(); iter.hasNext(); ) {\n IFile file = (IFile) iter.next();\n IClassFileReader reader = null;\n InputStream content = null;\n try {\n content = file.getContents();\n reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);\n } finally {\n try {\n if (content != null)\n content.close();\n } catch (IOException e) {\n throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));\n }\n }\n if (reader == null) {\n // problematic class file\n continue;\n }\n char[] className = reader.getClassName();\n ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();\n if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {\n IPath packPath = file.getParent().getFullPath();\n int idx = CharOperation.lastIndexOf('/', className) + 1;\n IPath relPath = new Path(new String(className, 0, idx));\n IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));\n IPath resPath = null;\n if (idx == 0) {\n resPath = packPath;\n } else {\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n resPath = folderPath;\n }\n }\n if (resPath != null) {\n IPath path = findInSourceFolders(cuPath);\n if (path != null) {\n return resPath;\n } else {\n classFolders.add(resPath);\n }\n }\n }\n }\n IPath projPath = fProject.getFullPath();\n if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {\n return projPath;\n } else {\n IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));\n while (classFolders.contains(path)) {\n path = new Path(path.toString() + '1');\n }\n return path;\n }\n }\n\n private void detectLibraries(ArrayList cpEntries, IPath outputLocation) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = fJARFiles.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n if (isNested(path, sourceFolderSet.iterator())) {\n continue;\n }\n if (outputLocation != null && outputLocation.isPrefixOf(path)) {\n continue;\n }\n IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n cpEntries.addAll(res);\n }\n\n private void detectSourceFolders(ArrayList resEntries) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = sourceFolderSet.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n ArrayList excluded = new ArrayList();\n for (Iterator inner = sourceFolderSet.iterator(); inner.hasNext(); ) {\n IPath other = inner.next();\n if (!path.equals(other) && path.isPrefixOf(other)) {\n IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();\n excluded.add(pathToExclude);\n }\n }\n IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);\n IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n resEntries.addAll(res);\n }\n\n private void visitCompilationUnit(IFile file) {\n ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);\n if (cu != null) {\n ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);\n parser.setSource(cu);\n parser.setFocalPosition(0);\n CompilationUnit root = (CompilationUnit) parser.createAST(null);\n PackageDeclaration packDecl = root.getPackage();\n IPath packPath = file.getParent().getFullPath();\n String cuName = file.getName();\n ", "post_mask_code": "\n }\n }\n\n private void addToMap(HashMap> map, IPath folderPath, IPath relPath) {\n List list = map.get(folderPath);\n if (list == null) {\n list = new ArrayList(50);\n map.put(folderPath, list);\n }\n list.add(relPath);\n }\n\n private IPath getFolderPath(IPath packPath, IPath relpath) {\n int remainingSegments = packPath.segmentCount() - relpath.segmentCount();\n if (remainingSegments >= 0) {\n IPath common = packPath.removeFirstSegments(remainingSegments);\n if (common.equals(relpath)) {\n return packPath.uptoSegment(remainingSegments);\n }\n }\n return null;\n }\n\n private boolean hasExtension(String name, String ext) {\n return name.endsWith(ext) && (ext.length() != name.length());\n }\n\n private boolean isValidCUName(String name) {\n return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);\n }\n\n /* (non-Javadoc)\n\t * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)\n\t */\n public boolean visit(IResourceProxy proxy) {\n if (fMonitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n if (proxy.getType() == IResource.FILE) {\n String name = proxy.getName();\n if (isValidCUName(name)) {\n visitCompilationUnit((IFile) proxy.requestResource());\n } else if (hasExtension(name, \".class\")) {\n fClassFiles.add(proxy.requestResource());\n } else if (hasExtension(name, \".jar\")) {\n fJARFiles.add(proxy.requestFullPath());\n }\n return false;\n }\n return true;\n }\n\n public IPath getOutputLocation() {\n return fResultOutputFolder;\n }\n\n public IClasspathEntry[] getClasspath() {\n if (fResultClasspath == null)\n return new IClasspathEntry[0];\n return fResultClasspath;\n }\n}\n"} {"task_id": "Java_2043", "language": "Java", "task_type": "for_statement", "source_file": "java/github/trylimits/Eclipse-Postfix-Code-Completion/luna/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/ClassPathDetector.java", "mask_start_position": 9733, "mask_end_position": 10117, "canonical_solution": "for (Iterator inner = sourceFolderSet.iterator(); inner.hasNext(); ) {\n IPath other = inner.next();\n if (!path.equals(other) && path.isPrefixOf(other)) {\n IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();\n excluded.add(pathToExclude);\n }\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic\n * *****************************************************************************\n */\npackage org.eclipse.jdt.internal.ui.wizards;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport com.ibm.icu.text.Collator;\nimport org.eclipse.core.runtime.CoreException;\nimport org.eclipse.core.runtime.IPath;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.IStatus;\nimport org.eclipse.core.runtime.NullProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\nimport org.eclipse.core.runtime.Path;\nimport org.eclipse.core.runtime.Status;\nimport org.eclipse.core.resources.IFile;\nimport org.eclipse.core.resources.IProject;\nimport org.eclipse.core.resources.IResource;\nimport org.eclipse.core.resources.IResourceProxy;\nimport org.eclipse.core.resources.IResourceProxyVisitor;\nimport org.eclipse.jdt.core.IClasspathEntry;\nimport org.eclipse.jdt.core.ICompilationUnit;\nimport org.eclipse.jdt.core.JavaConventions;\nimport org.eclipse.jdt.core.JavaCore;\nimport org.eclipse.jdt.core.ToolFactory;\nimport org.eclipse.jdt.core.compiler.CharOperation;\nimport org.eclipse.jdt.core.dom.ASTParser;\nimport org.eclipse.jdt.core.dom.CompilationUnit;\nimport org.eclipse.jdt.core.dom.PackageDeclaration;\nimport org.eclipse.jdt.core.util.IClassFileReader;\nimport org.eclipse.jdt.core.util.ISourceAttribute;\nimport org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;\nimport org.eclipse.jdt.internal.corext.util.Messages;\nimport org.eclipse.jdt.ui.PreferenceConstants;\nimport org.eclipse.jdt.internal.ui.JavaPlugin;\nimport org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;\nimport org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;\n\npublic class ClassPathDetector implements IResourceProxyVisitor {\n\n private HashMap> fSourceFolders;\n\n private List fClassFiles;\n\n private HashSet fJARFiles;\n\n private IProject fProject;\n\n private IPath fResultOutputFolder;\n\n private IClasspathEntry[] fResultClasspath;\n\n private IProgressMonitor fMonitor;\n\n private static class CPSorter implements Comparator {\n\n private Collator fCollator = Collator.getInstance();\n\n public int compare(IClasspathEntry e1, IClasspathEntry e2) {\n return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());\n }\n }\n\n public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {\n fSourceFolders = new HashMap>();\n fJARFiles = new HashSet(10);\n fClassFiles = new ArrayList(100);\n fProject = project;\n fResultClasspath = null;\n fResultOutputFolder = null;\n if (monitor == null) {\n monitor = new NullProgressMonitor();\n }\n detectClasspath(monitor);\n }\n\n private boolean isNested(IPath path, Iterator iter) {\n while (iter.hasNext()) {\n IPath other = iter.next();\n if (other.isPrefixOf(path)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Method detectClasspath.\n *\n * @param monitor The progress monitor (not null)\n * @throws CoreException in case of any failure\n */\n private void detectClasspath(IProgressMonitor monitor) throws CoreException {\n try {\n monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);\n fMonitor = monitor;\n fProject.accept(this, IResource.NONE);\n monitor.worked(1);\n ArrayList cpEntries = new ArrayList();\n detectSourceFolders(cpEntries);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n IPath outputLocation = detectOutputFolder();\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n detectLibraries(cpEntries, outputLocation);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {\n return;\n }\n IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();\n for (int i = 0; i < jreEntries.length; i++) {\n cpEntries.add(jreEntries[i]);\n }\n IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);\n if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {\n return;\n }\n fResultClasspath = entries;\n fResultOutputFolder = outputLocation;\n } finally {\n monitor.done();\n }\n }\n\n private IPath findInSourceFolders(IPath path) {\n Iterator iter = fSourceFolders.keySet().iterator();\n while (iter.hasNext()) {\n Object key = iter.next();\n List cus = fSourceFolders.get(key);\n if (cus.contains(path)) {\n return (IPath) key;\n }\n }\n return null;\n }\n\n private IPath detectOutputFolder() throws CoreException {\n HashSet classFolders = new HashSet();\n for (Iterator iter = fClassFiles.iterator(); iter.hasNext(); ) {\n IFile file = (IFile) iter.next();\n IClassFileReader reader = null;\n InputStream content = null;\n try {\n content = file.getContents();\n reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);\n } finally {\n try {\n if (content != null)\n content.close();\n } catch (IOException e) {\n throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));\n }\n }\n if (reader == null) {\n // problematic class file\n continue;\n }\n char[] className = reader.getClassName();\n ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();\n if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {\n IPath packPath = file.getParent().getFullPath();\n int idx = CharOperation.lastIndexOf('/', className) + 1;\n IPath relPath = new Path(new String(className, 0, idx));\n IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));\n IPath resPath = null;\n if (idx == 0) {\n resPath = packPath;\n } else {\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n resPath = folderPath;\n }\n }\n if (resPath != null) {\n IPath path = findInSourceFolders(cuPath);\n if (path != null) {\n return resPath;\n } else {\n classFolders.add(resPath);\n }\n }\n }\n }\n IPath projPath = fProject.getFullPath();\n if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {\n return projPath;\n } else {\n IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));\n while (classFolders.contains(path)) {\n path = new Path(path.toString() + '1');\n }\n return path;\n }\n }\n\n private void detectLibraries(ArrayList cpEntries, IPath outputLocation) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = fJARFiles.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n if (isNested(path, sourceFolderSet.iterator())) {\n continue;\n }\n if (outputLocation != null && outputLocation.isPrefixOf(path)) {\n continue;\n }\n IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n cpEntries.addAll(res);\n }\n\n private void detectSourceFolders(ArrayList resEntries) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = sourceFolderSet.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n ArrayList excluded = new ArrayList();\n ", "post_mask_code": "\n IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);\n IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n resEntries.addAll(res);\n }\n\n private void visitCompilationUnit(IFile file) {\n ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);\n if (cu != null) {\n ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);\n parser.setSource(cu);\n parser.setFocalPosition(0);\n CompilationUnit root = (CompilationUnit) parser.createAST(null);\n PackageDeclaration packDecl = root.getPackage();\n IPath packPath = file.getParent().getFullPath();\n String cuName = file.getName();\n if (packDecl == null) {\n addToMap(fSourceFolders, packPath, new Path(cuName));\n } else {\n IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n addToMap(fSourceFolders, folderPath, relPath.append(cuName));\n }\n }\n }\n }\n\n private void addToMap(HashMap> map, IPath folderPath, IPath relPath) {\n List list = map.get(folderPath);\n if (list == null) {\n list = new ArrayList(50);\n map.put(folderPath, list);\n }\n list.add(relPath);\n }\n\n private IPath getFolderPath(IPath packPath, IPath relpath) {\n int remainingSegments = packPath.segmentCount() - relpath.segmentCount();\n if (remainingSegments >= 0) {\n IPath common = packPath.removeFirstSegments(remainingSegments);\n if (common.equals(relpath)) {\n return packPath.uptoSegment(remainingSegments);\n }\n }\n return null;\n }\n\n private boolean hasExtension(String name, String ext) {\n return name.endsWith(ext) && (ext.length() != name.length());\n }\n\n private boolean isValidCUName(String name) {\n return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);\n }\n\n /* (non-Javadoc)\n\t * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)\n\t */\n public boolean visit(IResourceProxy proxy) {\n if (fMonitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n if (proxy.getType() == IResource.FILE) {\n String name = proxy.getName();\n if (isValidCUName(name)) {\n visitCompilationUnit((IFile) proxy.requestResource());\n } else if (hasExtension(name, \".class\")) {\n fClassFiles.add(proxy.requestResource());\n } else if (hasExtension(name, \".jar\")) {\n fJARFiles.add(proxy.requestFullPath());\n }\n return false;\n }\n return true;\n }\n\n public IPath getOutputLocation() {\n return fResultOutputFolder;\n }\n\n public IClasspathEntry[] getClasspath() {\n if (fResultClasspath == null)\n return new IClasspathEntry[0];\n return fResultClasspath;\n }\n}\n"} {"task_id": "Java_2044", "language": "Java", "task_type": "while_statement", "source_file": "java/github/trylimits/Eclipse-Postfix-Code-Completion/luna/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/ClassPathDetector.java", "mask_start_position": 5512, "mask_end_position": 5727, "canonical_solution": "while (iter.hasNext()) {\n Object key = iter.next();\n List cus = fSourceFolders.get(key);\n if (cus.contains(path)) {\n return (IPath) key;\n }\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic\n * *****************************************************************************\n */\npackage org.eclipse.jdt.internal.ui.wizards;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport com.ibm.icu.text.Collator;\nimport org.eclipse.core.runtime.CoreException;\nimport org.eclipse.core.runtime.IPath;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.IStatus;\nimport org.eclipse.core.runtime.NullProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\nimport org.eclipse.core.runtime.Path;\nimport org.eclipse.core.runtime.Status;\nimport org.eclipse.core.resources.IFile;\nimport org.eclipse.core.resources.IProject;\nimport org.eclipse.core.resources.IResource;\nimport org.eclipse.core.resources.IResourceProxy;\nimport org.eclipse.core.resources.IResourceProxyVisitor;\nimport org.eclipse.jdt.core.IClasspathEntry;\nimport org.eclipse.jdt.core.ICompilationUnit;\nimport org.eclipse.jdt.core.JavaConventions;\nimport org.eclipse.jdt.core.JavaCore;\nimport org.eclipse.jdt.core.ToolFactory;\nimport org.eclipse.jdt.core.compiler.CharOperation;\nimport org.eclipse.jdt.core.dom.ASTParser;\nimport org.eclipse.jdt.core.dom.CompilationUnit;\nimport org.eclipse.jdt.core.dom.PackageDeclaration;\nimport org.eclipse.jdt.core.util.IClassFileReader;\nimport org.eclipse.jdt.core.util.ISourceAttribute;\nimport org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;\nimport org.eclipse.jdt.internal.corext.util.Messages;\nimport org.eclipse.jdt.ui.PreferenceConstants;\nimport org.eclipse.jdt.internal.ui.JavaPlugin;\nimport org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;\nimport org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;\n\npublic class ClassPathDetector implements IResourceProxyVisitor {\n\n private HashMap> fSourceFolders;\n\n private List fClassFiles;\n\n private HashSet fJARFiles;\n\n private IProject fProject;\n\n private IPath fResultOutputFolder;\n\n private IClasspathEntry[] fResultClasspath;\n\n private IProgressMonitor fMonitor;\n\n private static class CPSorter implements Comparator {\n\n private Collator fCollator = Collator.getInstance();\n\n public int compare(IClasspathEntry e1, IClasspathEntry e2) {\n return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());\n }\n }\n\n public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {\n fSourceFolders = new HashMap>();\n fJARFiles = new HashSet(10);\n fClassFiles = new ArrayList(100);\n fProject = project;\n fResultClasspath = null;\n fResultOutputFolder = null;\n if (monitor == null) {\n monitor = new NullProgressMonitor();\n }\n detectClasspath(monitor);\n }\n\n private boolean isNested(IPath path, Iterator iter) {\n while (iter.hasNext()) {\n IPath other = iter.next();\n if (other.isPrefixOf(path)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Method detectClasspath.\n *\n * @param monitor The progress monitor (not null)\n * @throws CoreException in case of any failure\n */\n private void detectClasspath(IProgressMonitor monitor) throws CoreException {\n try {\n monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);\n fMonitor = monitor;\n fProject.accept(this, IResource.NONE);\n monitor.worked(1);\n ArrayList cpEntries = new ArrayList();\n detectSourceFolders(cpEntries);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n IPath outputLocation = detectOutputFolder();\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n detectLibraries(cpEntries, outputLocation);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {\n return;\n }\n IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();\n for (int i = 0; i < jreEntries.length; i++) {\n cpEntries.add(jreEntries[i]);\n }\n IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);\n if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {\n return;\n }\n fResultClasspath = entries;\n fResultOutputFolder = outputLocation;\n } finally {\n monitor.done();\n }\n }\n\n private IPath findInSourceFolders(IPath path) {\n Iterator iter = fSourceFolders.keySet().iterator();\n ", "post_mask_code": "\n return null;\n }\n\n private IPath detectOutputFolder() throws CoreException {\n HashSet classFolders = new HashSet();\n for (Iterator iter = fClassFiles.iterator(); iter.hasNext(); ) {\n IFile file = (IFile) iter.next();\n IClassFileReader reader = null;\n InputStream content = null;\n try {\n content = file.getContents();\n reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);\n } finally {\n try {\n if (content != null)\n content.close();\n } catch (IOException e) {\n throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));\n }\n }\n if (reader == null) {\n // problematic class file\n continue;\n }\n char[] className = reader.getClassName();\n ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();\n if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {\n IPath packPath = file.getParent().getFullPath();\n int idx = CharOperation.lastIndexOf('/', className) + 1;\n IPath relPath = new Path(new String(className, 0, idx));\n IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));\n IPath resPath = null;\n if (idx == 0) {\n resPath = packPath;\n } else {\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n resPath = folderPath;\n }\n }\n if (resPath != null) {\n IPath path = findInSourceFolders(cuPath);\n if (path != null) {\n return resPath;\n } else {\n classFolders.add(resPath);\n }\n }\n }\n }\n IPath projPath = fProject.getFullPath();\n if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {\n return projPath;\n } else {\n IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));\n while (classFolders.contains(path)) {\n path = new Path(path.toString() + '1');\n }\n return path;\n }\n }\n\n private void detectLibraries(ArrayList cpEntries, IPath outputLocation) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = fJARFiles.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n if (isNested(path, sourceFolderSet.iterator())) {\n continue;\n }\n if (outputLocation != null && outputLocation.isPrefixOf(path)) {\n continue;\n }\n IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n cpEntries.addAll(res);\n }\n\n private void detectSourceFolders(ArrayList resEntries) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = sourceFolderSet.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n ArrayList excluded = new ArrayList();\n for (Iterator inner = sourceFolderSet.iterator(); inner.hasNext(); ) {\n IPath other = inner.next();\n if (!path.equals(other) && path.isPrefixOf(other)) {\n IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();\n excluded.add(pathToExclude);\n }\n }\n IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);\n IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n resEntries.addAll(res);\n }\n\n private void visitCompilationUnit(IFile file) {\n ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);\n if (cu != null) {\n ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);\n parser.setSource(cu);\n parser.setFocalPosition(0);\n CompilationUnit root = (CompilationUnit) parser.createAST(null);\n PackageDeclaration packDecl = root.getPackage();\n IPath packPath = file.getParent().getFullPath();\n String cuName = file.getName();\n if (packDecl == null) {\n addToMap(fSourceFolders, packPath, new Path(cuName));\n } else {\n IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n addToMap(fSourceFolders, folderPath, relPath.append(cuName));\n }\n }\n }\n }\n\n private void addToMap(HashMap> map, IPath folderPath, IPath relPath) {\n List list = map.get(folderPath);\n if (list == null) {\n list = new ArrayList(50);\n map.put(folderPath, list);\n }\n list.add(relPath);\n }\n\n private IPath getFolderPath(IPath packPath, IPath relpath) {\n int remainingSegments = packPath.segmentCount() - relpath.segmentCount();\n if (remainingSegments >= 0) {\n IPath common = packPath.removeFirstSegments(remainingSegments);\n if (common.equals(relpath)) {\n return packPath.uptoSegment(remainingSegments);\n }\n }\n return null;\n }\n\n private boolean hasExtension(String name, String ext) {\n return name.endsWith(ext) && (ext.length() != name.length());\n }\n\n private boolean isValidCUName(String name) {\n return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);\n }\n\n /* (non-Javadoc)\n\t * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)\n\t */\n public boolean visit(IResourceProxy proxy) {\n if (fMonitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n if (proxy.getType() == IResource.FILE) {\n String name = proxy.getName();\n if (isValidCUName(name)) {\n visitCompilationUnit((IFile) proxy.requestResource());\n } else if (hasExtension(name, \".class\")) {\n fClassFiles.add(proxy.requestResource());\n } else if (hasExtension(name, \".jar\")) {\n fJARFiles.add(proxy.requestFullPath());\n }\n return false;\n }\n return true;\n }\n\n public IPath getOutputLocation() {\n return fResultOutputFolder;\n }\n\n public IClasspathEntry[] getClasspath() {\n if (fResultClasspath == null)\n return new IClasspathEntry[0];\n return fResultClasspath;\n }\n}\n"} {"task_id": "Java_2045", "language": "Java", "task_type": "try_statement", "source_file": "java/github/trylimits/Eclipse-Postfix-Code-Completion/luna/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/ClassPathDetector.java", "mask_start_position": 6311, "mask_end_position": 6707, "canonical_solution": "try {\n if (content != null)\n content.close();\n } catch (IOException e) {\n throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic\n * *****************************************************************************\n */\npackage org.eclipse.jdt.internal.ui.wizards;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport com.ibm.icu.text.Collator;\nimport org.eclipse.core.runtime.CoreException;\nimport org.eclipse.core.runtime.IPath;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.IStatus;\nimport org.eclipse.core.runtime.NullProgressMonitor;\nimport org.eclipse.core.runtime.OperationCanceledException;\nimport org.eclipse.core.runtime.Path;\nimport org.eclipse.core.runtime.Status;\nimport org.eclipse.core.resources.IFile;\nimport org.eclipse.core.resources.IProject;\nimport org.eclipse.core.resources.IResource;\nimport org.eclipse.core.resources.IResourceProxy;\nimport org.eclipse.core.resources.IResourceProxyVisitor;\nimport org.eclipse.jdt.core.IClasspathEntry;\nimport org.eclipse.jdt.core.ICompilationUnit;\nimport org.eclipse.jdt.core.JavaConventions;\nimport org.eclipse.jdt.core.JavaCore;\nimport org.eclipse.jdt.core.ToolFactory;\nimport org.eclipse.jdt.core.compiler.CharOperation;\nimport org.eclipse.jdt.core.dom.ASTParser;\nimport org.eclipse.jdt.core.dom.CompilationUnit;\nimport org.eclipse.jdt.core.dom.PackageDeclaration;\nimport org.eclipse.jdt.core.util.IClassFileReader;\nimport org.eclipse.jdt.core.util.ISourceAttribute;\nimport org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;\nimport org.eclipse.jdt.internal.corext.util.Messages;\nimport org.eclipse.jdt.ui.PreferenceConstants;\nimport org.eclipse.jdt.internal.ui.JavaPlugin;\nimport org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;\nimport org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;\n\npublic class ClassPathDetector implements IResourceProxyVisitor {\n\n private HashMap> fSourceFolders;\n\n private List fClassFiles;\n\n private HashSet fJARFiles;\n\n private IProject fProject;\n\n private IPath fResultOutputFolder;\n\n private IClasspathEntry[] fResultClasspath;\n\n private IProgressMonitor fMonitor;\n\n private static class CPSorter implements Comparator {\n\n private Collator fCollator = Collator.getInstance();\n\n public int compare(IClasspathEntry e1, IClasspathEntry e2) {\n return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());\n }\n }\n\n public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {\n fSourceFolders = new HashMap>();\n fJARFiles = new HashSet(10);\n fClassFiles = new ArrayList(100);\n fProject = project;\n fResultClasspath = null;\n fResultOutputFolder = null;\n if (monitor == null) {\n monitor = new NullProgressMonitor();\n }\n detectClasspath(monitor);\n }\n\n private boolean isNested(IPath path, Iterator iter) {\n while (iter.hasNext()) {\n IPath other = iter.next();\n if (other.isPrefixOf(path)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Method detectClasspath.\n *\n * @param monitor The progress monitor (not null)\n * @throws CoreException in case of any failure\n */\n private void detectClasspath(IProgressMonitor monitor) throws CoreException {\n try {\n monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);\n fMonitor = monitor;\n fProject.accept(this, IResource.NONE);\n monitor.worked(1);\n ArrayList cpEntries = new ArrayList();\n detectSourceFolders(cpEntries);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n IPath outputLocation = detectOutputFolder();\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n detectLibraries(cpEntries, outputLocation);\n if (monitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n monitor.worked(1);\n if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {\n return;\n }\n IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();\n for (int i = 0; i < jreEntries.length; i++) {\n cpEntries.add(jreEntries[i]);\n }\n IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);\n if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {\n return;\n }\n fResultClasspath = entries;\n fResultOutputFolder = outputLocation;\n } finally {\n monitor.done();\n }\n }\n\n private IPath findInSourceFolders(IPath path) {\n Iterator iter = fSourceFolders.keySet().iterator();\n while (iter.hasNext()) {\n Object key = iter.next();\n List cus = fSourceFolders.get(key);\n if (cus.contains(path)) {\n return (IPath) key;\n }\n }\n return null;\n }\n\n private IPath detectOutputFolder() throws CoreException {\n HashSet classFolders = new HashSet();\n for (Iterator iter = fClassFiles.iterator(); iter.hasNext(); ) {\n IFile file = (IFile) iter.next();\n IClassFileReader reader = null;\n InputStream content = null;\n try {\n content = file.getContents();\n reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);\n } finally {\n ", "post_mask_code": "\n }\n if (reader == null) {\n // problematic class file\n continue;\n }\n char[] className = reader.getClassName();\n ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();\n if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {\n IPath packPath = file.getParent().getFullPath();\n int idx = CharOperation.lastIndexOf('/', className) + 1;\n IPath relPath = new Path(new String(className, 0, idx));\n IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));\n IPath resPath = null;\n if (idx == 0) {\n resPath = packPath;\n } else {\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n resPath = folderPath;\n }\n }\n if (resPath != null) {\n IPath path = findInSourceFolders(cuPath);\n if (path != null) {\n return resPath;\n } else {\n classFolders.add(resPath);\n }\n }\n }\n }\n IPath projPath = fProject.getFullPath();\n if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {\n return projPath;\n } else {\n IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));\n while (classFolders.contains(path)) {\n path = new Path(path.toString() + '1');\n }\n return path;\n }\n }\n\n private void detectLibraries(ArrayList cpEntries, IPath outputLocation) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = fJARFiles.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n if (isNested(path, sourceFolderSet.iterator())) {\n continue;\n }\n if (outputLocation != null && outputLocation.isPrefixOf(path)) {\n continue;\n }\n IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n cpEntries.addAll(res);\n }\n\n private void detectSourceFolders(ArrayList resEntries) {\n ArrayList res = new ArrayList();\n Set sourceFolderSet = fSourceFolders.keySet();\n for (Iterator iter = sourceFolderSet.iterator(); iter.hasNext(); ) {\n IPath path = iter.next();\n ArrayList excluded = new ArrayList();\n for (Iterator inner = sourceFolderSet.iterator(); inner.hasNext(); ) {\n IPath other = inner.next();\n if (!path.equals(other) && path.isPrefixOf(other)) {\n IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();\n excluded.add(pathToExclude);\n }\n }\n IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);\n IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);\n res.add(entry);\n }\n Collections.sort(res, new CPSorter());\n resEntries.addAll(res);\n }\n\n private void visitCompilationUnit(IFile file) {\n ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);\n if (cu != null) {\n ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);\n parser.setSource(cu);\n parser.setFocalPosition(0);\n CompilationUnit root = (CompilationUnit) parser.createAST(null);\n PackageDeclaration packDecl = root.getPackage();\n IPath packPath = file.getParent().getFullPath();\n String cuName = file.getName();\n if (packDecl == null) {\n addToMap(fSourceFolders, packPath, new Path(cuName));\n } else {\n IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));\n IPath folderPath = getFolderPath(packPath, relPath);\n if (folderPath != null) {\n addToMap(fSourceFolders, folderPath, relPath.append(cuName));\n }\n }\n }\n }\n\n private void addToMap(HashMap> map, IPath folderPath, IPath relPath) {\n List list = map.get(folderPath);\n if (list == null) {\n list = new ArrayList(50);\n map.put(folderPath, list);\n }\n list.add(relPath);\n }\n\n private IPath getFolderPath(IPath packPath, IPath relpath) {\n int remainingSegments = packPath.segmentCount() - relpath.segmentCount();\n if (remainingSegments >= 0) {\n IPath common = packPath.removeFirstSegments(remainingSegments);\n if (common.equals(relpath)) {\n return packPath.uptoSegment(remainingSegments);\n }\n }\n return null;\n }\n\n private boolean hasExtension(String name, String ext) {\n return name.endsWith(ext) && (ext.length() != name.length());\n }\n\n private boolean isValidCUName(String name) {\n return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);\n }\n\n /* (non-Javadoc)\n\t * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)\n\t */\n public boolean visit(IResourceProxy proxy) {\n if (fMonitor.isCanceled()) {\n throw new OperationCanceledException();\n }\n if (proxy.getType() == IResource.FILE) {\n String name = proxy.getName();\n if (isValidCUName(name)) {\n visitCompilationUnit((IFile) proxy.requestResource());\n } else if (hasExtension(name, \".class\")) {\n fClassFiles.add(proxy.requestResource());\n } else if (hasExtension(name, \".jar\")) {\n fJARFiles.add(proxy.requestFullPath());\n }\n return false;\n }\n return true;\n }\n\n public IPath getOutputLocation() {\n return fResultOutputFolder;\n }\n\n public IClasspathEntry[] getClasspath() {\n if (fResultClasspath == null)\n return new IClasspathEntry[0];\n return fResultClasspath;\n }\n}\n"} {"task_id": "Java_2046", "language": "Java", "task_type": "method_signature", "source_file": "java/github/vx/connectbot/src/sk/vx/connectbot/PortForwardListActivity.java", "mask_start_position": 4914, "mask_end_position": 4974, "canonical_solution": "@Override\n public boolean onCreateOptionsMenu(Menu menu) ", "pre_mask_code": "/*\n * ConnectBot: simple, powerful, open-source SSH client for Android\n *\n */\npackage sk.vx.connectbot;\n\nimport java.util.List;\nimport sk.vx.connectbot.bean.HostBean;\nimport sk.vx.connectbot.bean.PortForwardBean;\nimport sk.vx.connectbot.service.TerminalBridge;\nimport sk.vx.connectbot.service.TerminalManager;\nimport sk.vx.connectbot.util.HostDatabase;\nimport android.app.AlertDialog;\nimport android.app.ListActivity;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.ServiceConnection;\nimport android.content.res.Resources;\nimport android.database.SQLException;\nimport android.graphics.Paint;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.IBinder;\nimport android.os.Message;\nimport android.util.Log;\nimport android.view.ContextMenu;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.MenuItem.OnMenuItemClickListener;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemClickListener;\nimport android.widget.AdapterView.OnItemSelectedListener;\nimport android.widget.ArrayAdapter;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Spinner;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\n/**\n * List all portForwards for a particular host and provide a way for users to add more portForwards,\n * edit existing portForwards, and delete portForwards.\n *\n * @author Kenny Root\n */\npublic class PortForwardListActivity extends ListActivity {\n\n public final static String TAG = \"ConnectBot.PortForwardListActivity\";\n\n private static final int LISTENER_CYCLE_TIME = 500;\n\n protected HostDatabase hostdb;\n\n private List portForwards;\n\n private ServiceConnection connection = null;\n\n protected TerminalBridge hostBridge = null;\n\n protected LayoutInflater inflater = null;\n\n private HostBean host;\n\n @Override\n public void onStart() {\n super.onStart();\n this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);\n if (this.hostdb == null)\n this.hostdb = new HostDatabase(this);\n }\n\n @Override\n public void onStop() {\n super.onStop();\n this.unbindService(connection);\n if (this.hostdb != null) {\n this.hostdb.close();\n this.hostdb = null;\n }\n }\n\n @Override\n public void onCreate(Bundle icicle) {\n super.onCreate(icicle);\n long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);\n setContentView(R.layout.act_portforwardlist);\n // connect with hosts database and populate list\n this.hostdb = new HostDatabase(this);\n host = hostdb.findHostById(hostId);\n {\n final String nickname = host != null ? host.getNickname() : null;\n final Resources resources = getResources();\n if (nickname != null) {\n this.setTitle(String.format(\"%s: %s (%s)\", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list), nickname));\n } else {\n this.setTitle(String.format(\"%s: %s\", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list)));\n }\n }\n connection = new ServiceConnection() {\n\n public void onServiceConnected(ComponentName className, IBinder service) {\n TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();\n hostBridge = bound.getConnectedBridge(host);\n updateHandler.sendEmptyMessage(-1);\n }\n\n public void onServiceDisconnected(ComponentName name) {\n hostBridge = null;\n }\n };\n this.updateList();\n this.registerForContextMenu(this.getListView());\n this.getListView().setOnItemClickListener(new OnItemClickListener() {\n\n public void onItemClick(AdapterView adapter, View view, int position, long id) {\n ListView lv = PortForwardListActivity.this.getListView();\n PortForwardBean pfb = (PortForwardBean) lv.getItemAtPosition(position);\n if (hostBridge != null) {\n if (pfb.isEnabled())\n hostBridge.disablePortForward(pfb);\n else {\n if (!hostBridge.enablePortForward(pfb))\n Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();\n }\n updateHandler.sendEmptyMessage(-1);\n }\n }\n });\n this.inflater = LayoutInflater.from(this);\n }\n\n ", "post_mask_code": "{\n super.onCreateOptionsMenu(menu);\n MenuItem add = menu.add(R.string.portforward_menu_add);\n add.setIcon(android.R.drawable.ic_menu_add);\n add.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n // build dialog to prompt user about updating\n final View portForwardView = inflater.inflate(R.layout.dia_portforward, null, false);\n final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);\n final Spinner typeSpinner = (Spinner) portForwardView.findViewById(R.id.portforward_type);\n typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n public void onItemSelected(AdapterView value, View view, int position, long id) {\n destEdit.setEnabled(position != 2);\n }\n\n public void onNothingSelected(AdapterView arg0) {\n }\n });\n new AlertDialog.Builder(PortForwardListActivity.this).setView(portForwardView).setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);\n final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);\n String type = HostDatabase.PORTFORWARD_LOCAL;\n switch(typeSpinner.getSelectedItemPosition()) {\n case 0:\n type = HostDatabase.PORTFORWARD_LOCAL;\n break;\n case 1:\n type = HostDatabase.PORTFORWARD_REMOTE;\n break;\n case 2:\n type = HostDatabase.PORTFORWARD_DYNAMIC5;\n break;\n }\n PortForwardBean pfb = new PortForwardBean(host != null ? host.getId() : -1, nicknameEdit.getText().toString(), type, sourcePortEdit.getText().toString(), destEdit.getText().toString());\n if (hostBridge != null) {\n hostBridge.addPortForward(pfb);\n hostBridge.enablePortForward(pfb);\n }\n if (host != null && !hostdb.savePortForward(pfb))\n throw new SQLException(\"Could not save port forward\");\n updateHandler.sendEmptyMessage(-1);\n } catch (Exception e) {\n Log.e(TAG, \"Could not update port forward\", e);\n // TODO Show failure dialog.\n }\n }\n }).setNegativeButton(R.string.delete_neg, null).create().show();\n return true;\n }\n });\n return true;\n }\n\n @Override\n public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {\n // Create menu to handle deleting and editing port forward\n AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;\n final PortForwardBean pfb = (PortForwardBean) this.getListView().getItemAtPosition(info.position);\n menu.setHeaderTitle(pfb.getNickname());\n MenuItem edit = menu.add(R.string.portforward_edit);\n edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n final View editTunnelView = inflater.inflate(R.layout.dia_portforward, null, false);\n final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);\n if (HostDatabase.PORTFORWARD_LOCAL.equals(pfb.getType()))\n typeSpinner.setSelection(0);\n else if (HostDatabase.PORTFORWARD_REMOTE.equals(pfb.getType()))\n typeSpinner.setSelection(1);\n else\n typeSpinner.setSelection(2);\n final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);\n nicknameEdit.setText(pfb.getNickname());\n final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);\n sourcePortEdit.setText(String.valueOf(pfb.getSourcePort()));\n final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);\n if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(pfb.getType())) {\n destEdit.setEnabled(false);\n } else {\n destEdit.setText(String.format(\"%s:%d\", pfb.getDestAddr(), pfb.getDestPort()));\n }\n typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n public void onItemSelected(AdapterView value, View view, int position, long id) {\n destEdit.setEnabled(position != 2);\n }\n\n public void onNothingSelected(AdapterView arg0) {\n }\n });\n new AlertDialog.Builder(PortForwardListActivity.this).setView(editTunnelView).setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n if (hostBridge != null)\n hostBridge.disablePortForward(pfb);\n pfb.setNickname(nicknameEdit.getText().toString());\n switch(typeSpinner.getSelectedItemPosition()) {\n case 0:\n pfb.setType(HostDatabase.PORTFORWARD_LOCAL);\n break;\n case 1:\n pfb.setType(HostDatabase.PORTFORWARD_REMOTE);\n break;\n case 2:\n pfb.setType(HostDatabase.PORTFORWARD_DYNAMIC5);\n break;\n }\n pfb.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));\n pfb.setDest(destEdit.getText().toString());\n // Use the new settings for the existing connection.\n if (hostBridge != null)\n updateHandler.postDelayed(new Runnable() {\n\n public void run() {\n hostBridge.enablePortForward(pfb);\n updateHandler.sendEmptyMessage(-1);\n }\n }, LISTENER_CYCLE_TIME);\n if (!hostdb.savePortForward(pfb))\n throw new SQLException(\"Could not save port forward\");\n updateHandler.sendEmptyMessage(-1);\n } catch (Exception e) {\n Log.e(TAG, \"Could not update port forward\", e);\n // TODO Show failure dialog.\n }\n }\n }).setNegativeButton(android.R.string.cancel, null).create().show();\n return true;\n }\n });\n MenuItem delete = menu.add(R.string.portforward_delete);\n delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n // prompt user to make sure they really want this\n new AlertDialog.Builder(PortForwardListActivity.this).setMessage(getString(R.string.delete_message, pfb.getNickname())).setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n // Delete the port forward from the host if needed.\n if (hostBridge != null)\n hostBridge.removePortForward(pfb);\n hostdb.deletePortForward(pfb);\n } catch (Exception e) {\n Log.e(TAG, \"Could not delete port forward\", e);\n }\n updateHandler.sendEmptyMessage(-1);\n }\n }).setNegativeButton(R.string.delete_neg, null).create().show();\n return true;\n }\n });\n }\n\n protected Handler updateHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n PortForwardListActivity.this.updateList();\n }\n };\n\n protected void updateList() {\n if (hostBridge != null) {\n this.portForwards = hostBridge.getPortForwards();\n } else {\n if (this.hostdb == null)\n return;\n this.portForwards = this.hostdb.getPortForwardsForHost(host);\n }\n PortForwardAdapter adapter = new PortForwardAdapter(this, portForwards);\n this.setListAdapter(adapter);\n }\n\n class PortForwardAdapter extends ArrayAdapter {\n\n class ViewHolder {\n\n public TextView nickname;\n\n public TextView caption;\n }\n\n private List portForwards;\n\n public PortForwardAdapter(Context context, List portForwards) {\n super(context, R.layout.item_portforward, portForwards);\n this.portForwards = portForwards;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n ViewHolder holder;\n if (convertView == null) {\n convertView = inflater.inflate(R.layout.item_portforward, null, false);\n holder = new ViewHolder();\n holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);\n holder.caption = (TextView) convertView.findViewById(android.R.id.text2);\n convertView.setTag(holder);\n } else\n holder = (ViewHolder) convertView.getTag();\n PortForwardBean pfb = portForwards.get(position);\n holder.nickname.setText(pfb.getNickname());\n holder.caption.setText(pfb.getDescription());\n if (hostBridge != null && !pfb.isEnabled()) {\n holder.nickname.setPaintFlags(holder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);\n holder.caption.setPaintFlags(holder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);\n }\n return convertView;\n }\n }\n}\n"} {"task_id": "Java_2047", "language": "Java", "task_type": "method_body", "source_file": "java/github/vx/connectbot/src/sk/vx/connectbot/PortForwardListActivity.java", "mask_start_position": 2361, "mask_end_position": 2542, "canonical_solution": "{\n super.onStop();\n this.unbindService(connection);\n if (this.hostdb != null) {\n this.hostdb.close();\n this.hostdb = null;\n }\n }", "pre_mask_code": "/*\n * ConnectBot: simple, powerful, open-source SSH client for Android\n *\n */\npackage sk.vx.connectbot;\n\nimport java.util.List;\nimport sk.vx.connectbot.bean.HostBean;\nimport sk.vx.connectbot.bean.PortForwardBean;\nimport sk.vx.connectbot.service.TerminalBridge;\nimport sk.vx.connectbot.service.TerminalManager;\nimport sk.vx.connectbot.util.HostDatabase;\nimport android.app.AlertDialog;\nimport android.app.ListActivity;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.ServiceConnection;\nimport android.content.res.Resources;\nimport android.database.SQLException;\nimport android.graphics.Paint;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.IBinder;\nimport android.os.Message;\nimport android.util.Log;\nimport android.view.ContextMenu;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.MenuItem.OnMenuItemClickListener;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemClickListener;\nimport android.widget.AdapterView.OnItemSelectedListener;\nimport android.widget.ArrayAdapter;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Spinner;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\n/**\n * List all portForwards for a particular host and provide a way for users to add more portForwards,\n * edit existing portForwards, and delete portForwards.\n *\n * @author Kenny Root\n */\npublic class PortForwardListActivity extends ListActivity {\n\n public final static String TAG = \"ConnectBot.PortForwardListActivity\";\n\n private static final int LISTENER_CYCLE_TIME = 500;\n\n protected HostDatabase hostdb;\n\n private List portForwards;\n\n private ServiceConnection connection = null;\n\n protected TerminalBridge hostBridge = null;\n\n protected LayoutInflater inflater = null;\n\n private HostBean host;\n\n @Override\n public void onStart() {\n super.onStart();\n this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);\n if (this.hostdb == null)\n this.hostdb = new HostDatabase(this);\n }\n\n @Override\n public void onStop() ", "post_mask_code": "\n\n @Override\n public void onCreate(Bundle icicle) {\n super.onCreate(icicle);\n long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);\n setContentView(R.layout.act_portforwardlist);\n // connect with hosts database and populate list\n this.hostdb = new HostDatabase(this);\n host = hostdb.findHostById(hostId);\n {\n final String nickname = host != null ? host.getNickname() : null;\n final Resources resources = getResources();\n if (nickname != null) {\n this.setTitle(String.format(\"%s: %s (%s)\", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list), nickname));\n } else {\n this.setTitle(String.format(\"%s: %s\", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list)));\n }\n }\n connection = new ServiceConnection() {\n\n public void onServiceConnected(ComponentName className, IBinder service) {\n TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();\n hostBridge = bound.getConnectedBridge(host);\n updateHandler.sendEmptyMessage(-1);\n }\n\n public void onServiceDisconnected(ComponentName name) {\n hostBridge = null;\n }\n };\n this.updateList();\n this.registerForContextMenu(this.getListView());\n this.getListView().setOnItemClickListener(new OnItemClickListener() {\n\n public void onItemClick(AdapterView adapter, View view, int position, long id) {\n ListView lv = PortForwardListActivity.this.getListView();\n PortForwardBean pfb = (PortForwardBean) lv.getItemAtPosition(position);\n if (hostBridge != null) {\n if (pfb.isEnabled())\n hostBridge.disablePortForward(pfb);\n else {\n if (!hostBridge.enablePortForward(pfb))\n Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();\n }\n updateHandler.sendEmptyMessage(-1);\n }\n }\n });\n this.inflater = LayoutInflater.from(this);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n super.onCreateOptionsMenu(menu);\n MenuItem add = menu.add(R.string.portforward_menu_add);\n add.setIcon(android.R.drawable.ic_menu_add);\n add.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n // build dialog to prompt user about updating\n final View portForwardView = inflater.inflate(R.layout.dia_portforward, null, false);\n final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);\n final Spinner typeSpinner = (Spinner) portForwardView.findViewById(R.id.portforward_type);\n typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n public void onItemSelected(AdapterView value, View view, int position, long id) {\n destEdit.setEnabled(position != 2);\n }\n\n public void onNothingSelected(AdapterView arg0) {\n }\n });\n new AlertDialog.Builder(PortForwardListActivity.this).setView(portForwardView).setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);\n final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);\n String type = HostDatabase.PORTFORWARD_LOCAL;\n switch(typeSpinner.getSelectedItemPosition()) {\n case 0:\n type = HostDatabase.PORTFORWARD_LOCAL;\n break;\n case 1:\n type = HostDatabase.PORTFORWARD_REMOTE;\n break;\n case 2:\n type = HostDatabase.PORTFORWARD_DYNAMIC5;\n break;\n }\n PortForwardBean pfb = new PortForwardBean(host != null ? host.getId() : -1, nicknameEdit.getText().toString(), type, sourcePortEdit.getText().toString(), destEdit.getText().toString());\n if (hostBridge != null) {\n hostBridge.addPortForward(pfb);\n hostBridge.enablePortForward(pfb);\n }\n if (host != null && !hostdb.savePortForward(pfb))\n throw new SQLException(\"Could not save port forward\");\n updateHandler.sendEmptyMessage(-1);\n } catch (Exception e) {\n Log.e(TAG, \"Could not update port forward\", e);\n // TODO Show failure dialog.\n }\n }\n }).setNegativeButton(R.string.delete_neg, null).create().show();\n return true;\n }\n });\n return true;\n }\n\n @Override\n public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {\n // Create menu to handle deleting and editing port forward\n AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;\n final PortForwardBean pfb = (PortForwardBean) this.getListView().getItemAtPosition(info.position);\n menu.setHeaderTitle(pfb.getNickname());\n MenuItem edit = menu.add(R.string.portforward_edit);\n edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n final View editTunnelView = inflater.inflate(R.layout.dia_portforward, null, false);\n final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);\n if (HostDatabase.PORTFORWARD_LOCAL.equals(pfb.getType()))\n typeSpinner.setSelection(0);\n else if (HostDatabase.PORTFORWARD_REMOTE.equals(pfb.getType()))\n typeSpinner.setSelection(1);\n else\n typeSpinner.setSelection(2);\n final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);\n nicknameEdit.setText(pfb.getNickname());\n final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);\n sourcePortEdit.setText(String.valueOf(pfb.getSourcePort()));\n final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);\n if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(pfb.getType())) {\n destEdit.setEnabled(false);\n } else {\n destEdit.setText(String.format(\"%s:%d\", pfb.getDestAddr(), pfb.getDestPort()));\n }\n typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n public void onItemSelected(AdapterView value, View view, int position, long id) {\n destEdit.setEnabled(position != 2);\n }\n\n public void onNothingSelected(AdapterView arg0) {\n }\n });\n new AlertDialog.Builder(PortForwardListActivity.this).setView(editTunnelView).setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n if (hostBridge != null)\n hostBridge.disablePortForward(pfb);\n pfb.setNickname(nicknameEdit.getText().toString());\n switch(typeSpinner.getSelectedItemPosition()) {\n case 0:\n pfb.setType(HostDatabase.PORTFORWARD_LOCAL);\n break;\n case 1:\n pfb.setType(HostDatabase.PORTFORWARD_REMOTE);\n break;\n case 2:\n pfb.setType(HostDatabase.PORTFORWARD_DYNAMIC5);\n break;\n }\n pfb.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));\n pfb.setDest(destEdit.getText().toString());\n // Use the new settings for the existing connection.\n if (hostBridge != null)\n updateHandler.postDelayed(new Runnable() {\n\n public void run() {\n hostBridge.enablePortForward(pfb);\n updateHandler.sendEmptyMessage(-1);\n }\n }, LISTENER_CYCLE_TIME);\n if (!hostdb.savePortForward(pfb))\n throw new SQLException(\"Could not save port forward\");\n updateHandler.sendEmptyMessage(-1);\n } catch (Exception e) {\n Log.e(TAG, \"Could not update port forward\", e);\n // TODO Show failure dialog.\n }\n }\n }).setNegativeButton(android.R.string.cancel, null).create().show();\n return true;\n }\n });\n MenuItem delete = menu.add(R.string.portforward_delete);\n delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n // prompt user to make sure they really want this\n new AlertDialog.Builder(PortForwardListActivity.this).setMessage(getString(R.string.delete_message, pfb.getNickname())).setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n // Delete the port forward from the host if needed.\n if (hostBridge != null)\n hostBridge.removePortForward(pfb);\n hostdb.deletePortForward(pfb);\n } catch (Exception e) {\n Log.e(TAG, \"Could not delete port forward\", e);\n }\n updateHandler.sendEmptyMessage(-1);\n }\n }).setNegativeButton(R.string.delete_neg, null).create().show();\n return true;\n }\n });\n }\n\n protected Handler updateHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n PortForwardListActivity.this.updateList();\n }\n };\n\n protected void updateList() {\n if (hostBridge != null) {\n this.portForwards = hostBridge.getPortForwards();\n } else {\n if (this.hostdb == null)\n return;\n this.portForwards = this.hostdb.getPortForwardsForHost(host);\n }\n PortForwardAdapter adapter = new PortForwardAdapter(this, portForwards);\n this.setListAdapter(adapter);\n }\n\n class PortForwardAdapter extends ArrayAdapter {\n\n class ViewHolder {\n\n public TextView nickname;\n\n public TextView caption;\n }\n\n private List portForwards;\n\n public PortForwardAdapter(Context context, List portForwards) {\n super(context, R.layout.item_portforward, portForwards);\n this.portForwards = portForwards;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n ViewHolder holder;\n if (convertView == null) {\n convertView = inflater.inflate(R.layout.item_portforward, null, false);\n holder = new ViewHolder();\n holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);\n holder.caption = (TextView) convertView.findViewById(android.R.id.text2);\n convertView.setTag(holder);\n } else\n holder = (ViewHolder) convertView.getTag();\n PortForwardBean pfb = portForwards.get(position);\n holder.nickname.setText(pfb.getNickname());\n holder.caption.setText(pfb.getDescription());\n if (hostBridge != null && !pfb.isEnabled()) {\n holder.nickname.setPaintFlags(holder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);\n holder.caption.setPaintFlags(holder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);\n }\n return convertView;\n }\n }\n}\n"} {"task_id": "Java_2048", "language": "Java", "task_type": "single_line", "source_file": "java/github/vx/connectbot/src/sk/vx/connectbot/PortForwardListActivity.java", "mask_start_position": 12941, "mask_end_position": 12969, "canonical_solution": ".string.portforward_delete);", "pre_mask_code": "/*\n * ConnectBot: simple, powerful, open-source SSH client for Android\n *\n */\npackage sk.vx.connectbot;\n\nimport java.util.List;\nimport sk.vx.connectbot.bean.HostBean;\nimport sk.vx.connectbot.bean.PortForwardBean;\nimport sk.vx.connectbot.service.TerminalBridge;\nimport sk.vx.connectbot.service.TerminalManager;\nimport sk.vx.connectbot.util.HostDatabase;\nimport android.app.AlertDialog;\nimport android.app.ListActivity;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.ServiceConnection;\nimport android.content.res.Resources;\nimport android.database.SQLException;\nimport android.graphics.Paint;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.IBinder;\nimport android.os.Message;\nimport android.util.Log;\nimport android.view.ContextMenu;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.MenuItem.OnMenuItemClickListener;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemClickListener;\nimport android.widget.AdapterView.OnItemSelectedListener;\nimport android.widget.ArrayAdapter;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Spinner;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\n/**\n * List all portForwards for a particular host and provide a way for users to add more portForwards,\n * edit existing portForwards, and delete portForwards.\n *\n * @author Kenny Root\n */\npublic class PortForwardListActivity extends ListActivity {\n\n public final static String TAG = \"ConnectBot.PortForwardListActivity\";\n\n private static final int LISTENER_CYCLE_TIME = 500;\n\n protected HostDatabase hostdb;\n\n private List portForwards;\n\n private ServiceConnection connection = null;\n\n protected TerminalBridge hostBridge = null;\n\n protected LayoutInflater inflater = null;\n\n private HostBean host;\n\n @Override\n public void onStart() {\n super.onStart();\n this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);\n if (this.hostdb == null)\n this.hostdb = new HostDatabase(this);\n }\n\n @Override\n public void onStop() {\n super.onStop();\n this.unbindService(connection);\n if (this.hostdb != null) {\n this.hostdb.close();\n this.hostdb = null;\n }\n }\n\n @Override\n public void onCreate(Bundle icicle) {\n super.onCreate(icicle);\n long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);\n setContentView(R.layout.act_portforwardlist);\n // connect with hosts database and populate list\n this.hostdb = new HostDatabase(this);\n host = hostdb.findHostById(hostId);\n {\n final String nickname = host != null ? host.getNickname() : null;\n final Resources resources = getResources();\n if (nickname != null) {\n this.setTitle(String.format(\"%s: %s (%s)\", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list), nickname));\n } else {\n this.setTitle(String.format(\"%s: %s\", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list)));\n }\n }\n connection = new ServiceConnection() {\n\n public void onServiceConnected(ComponentName className, IBinder service) {\n TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();\n hostBridge = bound.getConnectedBridge(host);\n updateHandler.sendEmptyMessage(-1);\n }\n\n public void onServiceDisconnected(ComponentName name) {\n hostBridge = null;\n }\n };\n this.updateList();\n this.registerForContextMenu(this.getListView());\n this.getListView().setOnItemClickListener(new OnItemClickListener() {\n\n public void onItemClick(AdapterView adapter, View view, int position, long id) {\n ListView lv = PortForwardListActivity.this.getListView();\n PortForwardBean pfb = (PortForwardBean) lv.getItemAtPosition(position);\n if (hostBridge != null) {\n if (pfb.isEnabled())\n hostBridge.disablePortForward(pfb);\n else {\n if (!hostBridge.enablePortForward(pfb))\n Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();\n }\n updateHandler.sendEmptyMessage(-1);\n }\n }\n });\n this.inflater = LayoutInflater.from(this);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n super.onCreateOptionsMenu(menu);\n MenuItem add = menu.add(R.string.portforward_menu_add);\n add.setIcon(android.R.drawable.ic_menu_add);\n add.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n // build dialog to prompt user about updating\n final View portForwardView = inflater.inflate(R.layout.dia_portforward, null, false);\n final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);\n final Spinner typeSpinner = (Spinner) portForwardView.findViewById(R.id.portforward_type);\n typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n public void onItemSelected(AdapterView value, View view, int position, long id) {\n destEdit.setEnabled(position != 2);\n }\n\n public void onNothingSelected(AdapterView arg0) {\n }\n });\n new AlertDialog.Builder(PortForwardListActivity.this).setView(portForwardView).setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);\n final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);\n String type = HostDatabase.PORTFORWARD_LOCAL;\n switch(typeSpinner.getSelectedItemPosition()) {\n case 0:\n type = HostDatabase.PORTFORWARD_LOCAL;\n break;\n case 1:\n type = HostDatabase.PORTFORWARD_REMOTE;\n break;\n case 2:\n type = HostDatabase.PORTFORWARD_DYNAMIC5;\n break;\n }\n PortForwardBean pfb = new PortForwardBean(host != null ? host.getId() : -1, nicknameEdit.getText().toString(), type, sourcePortEdit.getText().toString(), destEdit.getText().toString());\n if (hostBridge != null) {\n hostBridge.addPortForward(pfb);\n hostBridge.enablePortForward(pfb);\n }\n if (host != null && !hostdb.savePortForward(pfb))\n throw new SQLException(\"Could not save port forward\");\n updateHandler.sendEmptyMessage(-1);\n } catch (Exception e) {\n Log.e(TAG, \"Could not update port forward\", e);\n // TODO Show failure dialog.\n }\n }\n }).setNegativeButton(R.string.delete_neg, null).create().show();\n return true;\n }\n });\n return true;\n }\n\n @Override\n public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {\n // Create menu to handle deleting and editing port forward\n AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;\n final PortForwardBean pfb = (PortForwardBean) this.getListView().getItemAtPosition(info.position);\n menu.setHeaderTitle(pfb.getNickname());\n MenuItem edit = menu.add(R.string.portforward_edit);\n edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n final View editTunnelView = inflater.inflate(R.layout.dia_portforward, null, false);\n final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);\n if (HostDatabase.PORTFORWARD_LOCAL.equals(pfb.getType()))\n typeSpinner.setSelection(0);\n else if (HostDatabase.PORTFORWARD_REMOTE.equals(pfb.getType()))\n typeSpinner.setSelection(1);\n else\n typeSpinner.setSelection(2);\n final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);\n nicknameEdit.setText(pfb.getNickname());\n final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);\n sourcePortEdit.setText(String.valueOf(pfb.getSourcePort()));\n final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);\n if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(pfb.getType())) {\n destEdit.setEnabled(false);\n } else {\n destEdit.setText(String.format(\"%s:%d\", pfb.getDestAddr(), pfb.getDestPort()));\n }\n typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n public void onItemSelected(AdapterView value, View view, int position, long id) {\n destEdit.setEnabled(position != 2);\n }\n\n public void onNothingSelected(AdapterView arg0) {\n }\n });\n new AlertDialog.Builder(PortForwardListActivity.this).setView(editTunnelView).setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n if (hostBridge != null)\n hostBridge.disablePortForward(pfb);\n pfb.setNickname(nicknameEdit.getText().toString());\n switch(typeSpinner.getSelectedItemPosition()) {\n case 0:\n pfb.setType(HostDatabase.PORTFORWARD_LOCAL);\n break;\n case 1:\n pfb.setType(HostDatabase.PORTFORWARD_REMOTE);\n break;\n case 2:\n pfb.setType(HostDatabase.PORTFORWARD_DYNAMIC5);\n break;\n }\n pfb.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));\n pfb.setDest(destEdit.getText().toString());\n // Use the new settings for the existing connection.\n if (hostBridge != null)\n updateHandler.postDelayed(new Runnable() {\n\n public void run() {\n hostBridge.enablePortForward(pfb);\n updateHandler.sendEmptyMessage(-1);\n }\n }, LISTENER_CYCLE_TIME);\n if (!hostdb.savePortForward(pfb))\n throw new SQLException(\"Could not save port forward\");\n updateHandler.sendEmptyMessage(-1);\n } catch (Exception e) {\n Log.e(TAG, \"Could not update port forward\", e);\n // TODO Show failure dialog.\n }\n }\n }).setNegativeButton(android.R.string.cancel, null).create().show();\n return true;\n }\n });\n MenuItem delete = menu.add(R", "post_mask_code": "\n delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n // prompt user to make sure they really want this\n new AlertDialog.Builder(PortForwardListActivity.this).setMessage(getString(R.string.delete_message, pfb.getNickname())).setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n // Delete the port forward from the host if needed.\n if (hostBridge != null)\n hostBridge.removePortForward(pfb);\n hostdb.deletePortForward(pfb);\n } catch (Exception e) {\n Log.e(TAG, \"Could not delete port forward\", e);\n }\n updateHandler.sendEmptyMessage(-1);\n }\n }).setNegativeButton(R.string.delete_neg, null).create().show();\n return true;\n }\n });\n }\n\n protected Handler updateHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n PortForwardListActivity.this.updateList();\n }\n };\n\n protected void updateList() {\n if (hostBridge != null) {\n this.portForwards = hostBridge.getPortForwards();\n } else {\n if (this.hostdb == null)\n return;\n this.portForwards = this.hostdb.getPortForwardsForHost(host);\n }\n PortForwardAdapter adapter = new PortForwardAdapter(this, portForwards);\n this.setListAdapter(adapter);\n }\n\n class PortForwardAdapter extends ArrayAdapter {\n\n class ViewHolder {\n\n public TextView nickname;\n\n public TextView caption;\n }\n\n private List portForwards;\n\n public PortForwardAdapter(Context context, List portForwards) {\n super(context, R.layout.item_portforward, portForwards);\n this.portForwards = portForwards;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n ViewHolder holder;\n if (convertView == null) {\n convertView = inflater.inflate(R.layout.item_portforward, null, false);\n holder = new ViewHolder();\n holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);\n holder.caption = (TextView) convertView.findViewById(android.R.id.text2);\n convertView.setTag(holder);\n } else\n holder = (ViewHolder) convertView.getTag();\n PortForwardBean pfb = portForwards.get(position);\n holder.nickname.setText(pfb.getNickname());\n holder.caption.setText(pfb.getDescription());\n if (hostBridge != null && !pfb.isEnabled()) {\n holder.nickname.setPaintFlags(holder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);\n holder.caption.setPaintFlags(holder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);\n }\n return convertView;\n }\n }\n}\n"} {"task_id": "Java_2049", "language": "Java", "task_type": "if_statement", "source_file": "java/github/vx/connectbot/src/sk/vx/connectbot/PortForwardListActivity.java", "mask_start_position": 4371, "mask_end_position": 4825, "canonical_solution": "if (hostBridge != null) {\n if (pfb.isEnabled())\n hostBridge.disablePortForward(pfb);\n else {\n if (!hostBridge.enablePortForward(pfb))\n Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();\n }\n updateHandler.sendEmptyMessage(-1);\n }", "pre_mask_code": "/*\n * ConnectBot: simple, powerful, open-source SSH client for Android\n *\n */\npackage sk.vx.connectbot;\n\nimport java.util.List;\nimport sk.vx.connectbot.bean.HostBean;\nimport sk.vx.connectbot.bean.PortForwardBean;\nimport sk.vx.connectbot.service.TerminalBridge;\nimport sk.vx.connectbot.service.TerminalManager;\nimport sk.vx.connectbot.util.HostDatabase;\nimport android.app.AlertDialog;\nimport android.app.ListActivity;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.ServiceConnection;\nimport android.content.res.Resources;\nimport android.database.SQLException;\nimport android.graphics.Paint;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.IBinder;\nimport android.os.Message;\nimport android.util.Log;\nimport android.view.ContextMenu;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.MenuItem.OnMenuItemClickListener;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemClickListener;\nimport android.widget.AdapterView.OnItemSelectedListener;\nimport android.widget.ArrayAdapter;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Spinner;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\n/**\n * List all portForwards for a particular host and provide a way for users to add more portForwards,\n * edit existing portForwards, and delete portForwards.\n *\n * @author Kenny Root\n */\npublic class PortForwardListActivity extends ListActivity {\n\n public final static String TAG = \"ConnectBot.PortForwardListActivity\";\n\n private static final int LISTENER_CYCLE_TIME = 500;\n\n protected HostDatabase hostdb;\n\n private List portForwards;\n\n private ServiceConnection connection = null;\n\n protected TerminalBridge hostBridge = null;\n\n protected LayoutInflater inflater = null;\n\n private HostBean host;\n\n @Override\n public void onStart() {\n super.onStart();\n this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);\n if (this.hostdb == null)\n this.hostdb = new HostDatabase(this);\n }\n\n @Override\n public void onStop() {\n super.onStop();\n this.unbindService(connection);\n if (this.hostdb != null) {\n this.hostdb.close();\n this.hostdb = null;\n }\n }\n\n @Override\n public void onCreate(Bundle icicle) {\n super.onCreate(icicle);\n long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);\n setContentView(R.layout.act_portforwardlist);\n // connect with hosts database and populate list\n this.hostdb = new HostDatabase(this);\n host = hostdb.findHostById(hostId);\n {\n final String nickname = host != null ? host.getNickname() : null;\n final Resources resources = getResources();\n if (nickname != null) {\n this.setTitle(String.format(\"%s: %s (%s)\", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list), nickname));\n } else {\n this.setTitle(String.format(\"%s: %s\", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list)));\n }\n }\n connection = new ServiceConnection() {\n\n public void onServiceConnected(ComponentName className, IBinder service) {\n TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();\n hostBridge = bound.getConnectedBridge(host);\n updateHandler.sendEmptyMessage(-1);\n }\n\n public void onServiceDisconnected(ComponentName name) {\n hostBridge = null;\n }\n };\n this.updateList();\n this.registerForContextMenu(this.getListView());\n this.getListView().setOnItemClickListener(new OnItemClickListener() {\n\n public void onItemClick(AdapterView adapter, View view, int position, long id) {\n ListView lv = PortForwardListActivity.this.getListView();\n PortForwardBean pfb = (PortForwardBean) lv.getItemAtPosition(position);\n ", "post_mask_code": "\n }\n });\n this.inflater = LayoutInflater.from(this);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n super.onCreateOptionsMenu(menu);\n MenuItem add = menu.add(R.string.portforward_menu_add);\n add.setIcon(android.R.drawable.ic_menu_add);\n add.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n // build dialog to prompt user about updating\n final View portForwardView = inflater.inflate(R.layout.dia_portforward, null, false);\n final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);\n final Spinner typeSpinner = (Spinner) portForwardView.findViewById(R.id.portforward_type);\n typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n public void onItemSelected(AdapterView value, View view, int position, long id) {\n destEdit.setEnabled(position != 2);\n }\n\n public void onNothingSelected(AdapterView arg0) {\n }\n });\n new AlertDialog.Builder(PortForwardListActivity.this).setView(portForwardView).setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);\n final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);\n String type = HostDatabase.PORTFORWARD_LOCAL;\n switch(typeSpinner.getSelectedItemPosition()) {\n case 0:\n type = HostDatabase.PORTFORWARD_LOCAL;\n break;\n case 1:\n type = HostDatabase.PORTFORWARD_REMOTE;\n break;\n case 2:\n type = HostDatabase.PORTFORWARD_DYNAMIC5;\n break;\n }\n PortForwardBean pfb = new PortForwardBean(host != null ? host.getId() : -1, nicknameEdit.getText().toString(), type, sourcePortEdit.getText().toString(), destEdit.getText().toString());\n if (hostBridge != null) {\n hostBridge.addPortForward(pfb);\n hostBridge.enablePortForward(pfb);\n }\n if (host != null && !hostdb.savePortForward(pfb))\n throw new SQLException(\"Could not save port forward\");\n updateHandler.sendEmptyMessage(-1);\n } catch (Exception e) {\n Log.e(TAG, \"Could not update port forward\", e);\n // TODO Show failure dialog.\n }\n }\n }).setNegativeButton(R.string.delete_neg, null).create().show();\n return true;\n }\n });\n return true;\n }\n\n @Override\n public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {\n // Create menu to handle deleting and editing port forward\n AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;\n final PortForwardBean pfb = (PortForwardBean) this.getListView().getItemAtPosition(info.position);\n menu.setHeaderTitle(pfb.getNickname());\n MenuItem edit = menu.add(R.string.portforward_edit);\n edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n final View editTunnelView = inflater.inflate(R.layout.dia_portforward, null, false);\n final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);\n if (HostDatabase.PORTFORWARD_LOCAL.equals(pfb.getType()))\n typeSpinner.setSelection(0);\n else if (HostDatabase.PORTFORWARD_REMOTE.equals(pfb.getType()))\n typeSpinner.setSelection(1);\n else\n typeSpinner.setSelection(2);\n final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);\n nicknameEdit.setText(pfb.getNickname());\n final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);\n sourcePortEdit.setText(String.valueOf(pfb.getSourcePort()));\n final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);\n if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(pfb.getType())) {\n destEdit.setEnabled(false);\n } else {\n destEdit.setText(String.format(\"%s:%d\", pfb.getDestAddr(), pfb.getDestPort()));\n }\n typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n public void onItemSelected(AdapterView value, View view, int position, long id) {\n destEdit.setEnabled(position != 2);\n }\n\n public void onNothingSelected(AdapterView arg0) {\n }\n });\n new AlertDialog.Builder(PortForwardListActivity.this).setView(editTunnelView).setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n if (hostBridge != null)\n hostBridge.disablePortForward(pfb);\n pfb.setNickname(nicknameEdit.getText().toString());\n switch(typeSpinner.getSelectedItemPosition()) {\n case 0:\n pfb.setType(HostDatabase.PORTFORWARD_LOCAL);\n break;\n case 1:\n pfb.setType(HostDatabase.PORTFORWARD_REMOTE);\n break;\n case 2:\n pfb.setType(HostDatabase.PORTFORWARD_DYNAMIC5);\n break;\n }\n pfb.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));\n pfb.setDest(destEdit.getText().toString());\n // Use the new settings for the existing connection.\n if (hostBridge != null)\n updateHandler.postDelayed(new Runnable() {\n\n public void run() {\n hostBridge.enablePortForward(pfb);\n updateHandler.sendEmptyMessage(-1);\n }\n }, LISTENER_CYCLE_TIME);\n if (!hostdb.savePortForward(pfb))\n throw new SQLException(\"Could not save port forward\");\n updateHandler.sendEmptyMessage(-1);\n } catch (Exception e) {\n Log.e(TAG, \"Could not update port forward\", e);\n // TODO Show failure dialog.\n }\n }\n }).setNegativeButton(android.R.string.cancel, null).create().show();\n return true;\n }\n });\n MenuItem delete = menu.add(R.string.portforward_delete);\n delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n // prompt user to make sure they really want this\n new AlertDialog.Builder(PortForwardListActivity.this).setMessage(getString(R.string.delete_message, pfb.getNickname())).setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n // Delete the port forward from the host if needed.\n if (hostBridge != null)\n hostBridge.removePortForward(pfb);\n hostdb.deletePortForward(pfb);\n } catch (Exception e) {\n Log.e(TAG, \"Could not delete port forward\", e);\n }\n updateHandler.sendEmptyMessage(-1);\n }\n }).setNegativeButton(R.string.delete_neg, null).create().show();\n return true;\n }\n });\n }\n\n protected Handler updateHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n PortForwardListActivity.this.updateList();\n }\n };\n\n protected void updateList() {\n if (hostBridge != null) {\n this.portForwards = hostBridge.getPortForwards();\n } else {\n if (this.hostdb == null)\n return;\n this.portForwards = this.hostdb.getPortForwardsForHost(host);\n }\n PortForwardAdapter adapter = new PortForwardAdapter(this, portForwards);\n this.setListAdapter(adapter);\n }\n\n class PortForwardAdapter extends ArrayAdapter {\n\n class ViewHolder {\n\n public TextView nickname;\n\n public TextView caption;\n }\n\n private List portForwards;\n\n public PortForwardAdapter(Context context, List portForwards) {\n super(context, R.layout.item_portforward, portForwards);\n this.portForwards = portForwards;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n ViewHolder holder;\n if (convertView == null) {\n convertView = inflater.inflate(R.layout.item_portforward, null, false);\n holder = new ViewHolder();\n holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);\n holder.caption = (TextView) convertView.findViewById(android.R.id.text2);\n convertView.setTag(holder);\n } else\n holder = (ViewHolder) convertView.getTag();\n PortForwardBean pfb = portForwards.get(position);\n holder.nickname.setText(pfb.getNickname());\n holder.caption.setText(pfb.getDescription());\n if (hostBridge != null && !pfb.isEnabled()) {\n holder.nickname.setPaintFlags(holder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);\n holder.caption.setPaintFlags(holder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);\n }\n return convertView;\n }\n }\n}\n"} {"task_id": "Java_2050", "language": "Java", "task_type": "try_statement", "source_file": "java/github/vx/connectbot/src/sk/vx/connectbot/PortForwardListActivity.java", "mask_start_position": 13488, "mask_end_position": 13901, "canonical_solution": "try {\n // Delete the port forward from the host if needed.\n if (hostBridge != null)\n hostBridge.removePortForward(pfb);\n hostdb.deletePortForward(pfb);\n } catch (Exception e) {\n Log.e(TAG, \"Could not delete port forward\", e);\n }", "pre_mask_code": "/*\n * ConnectBot: simple, powerful, open-source SSH client for Android\n *\n */\npackage sk.vx.connectbot;\n\nimport java.util.List;\nimport sk.vx.connectbot.bean.HostBean;\nimport sk.vx.connectbot.bean.PortForwardBean;\nimport sk.vx.connectbot.service.TerminalBridge;\nimport sk.vx.connectbot.service.TerminalManager;\nimport sk.vx.connectbot.util.HostDatabase;\nimport android.app.AlertDialog;\nimport android.app.ListActivity;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.ServiceConnection;\nimport android.content.res.Resources;\nimport android.database.SQLException;\nimport android.graphics.Paint;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.IBinder;\nimport android.os.Message;\nimport android.util.Log;\nimport android.view.ContextMenu;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.MenuItem.OnMenuItemClickListener;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemClickListener;\nimport android.widget.AdapterView.OnItemSelectedListener;\nimport android.widget.ArrayAdapter;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Spinner;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\n/**\n * List all portForwards for a particular host and provide a way for users to add more portForwards,\n * edit existing portForwards, and delete portForwards.\n *\n * @author Kenny Root\n */\npublic class PortForwardListActivity extends ListActivity {\n\n public final static String TAG = \"ConnectBot.PortForwardListActivity\";\n\n private static final int LISTENER_CYCLE_TIME = 500;\n\n protected HostDatabase hostdb;\n\n private List portForwards;\n\n private ServiceConnection connection = null;\n\n protected TerminalBridge hostBridge = null;\n\n protected LayoutInflater inflater = null;\n\n private HostBean host;\n\n @Override\n public void onStart() {\n super.onStart();\n this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);\n if (this.hostdb == null)\n this.hostdb = new HostDatabase(this);\n }\n\n @Override\n public void onStop() {\n super.onStop();\n this.unbindService(connection);\n if (this.hostdb != null) {\n this.hostdb.close();\n this.hostdb = null;\n }\n }\n\n @Override\n public void onCreate(Bundle icicle) {\n super.onCreate(icicle);\n long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);\n setContentView(R.layout.act_portforwardlist);\n // connect with hosts database and populate list\n this.hostdb = new HostDatabase(this);\n host = hostdb.findHostById(hostId);\n {\n final String nickname = host != null ? host.getNickname() : null;\n final Resources resources = getResources();\n if (nickname != null) {\n this.setTitle(String.format(\"%s: %s (%s)\", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list), nickname));\n } else {\n this.setTitle(String.format(\"%s: %s\", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list)));\n }\n }\n connection = new ServiceConnection() {\n\n public void onServiceConnected(ComponentName className, IBinder service) {\n TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();\n hostBridge = bound.getConnectedBridge(host);\n updateHandler.sendEmptyMessage(-1);\n }\n\n public void onServiceDisconnected(ComponentName name) {\n hostBridge = null;\n }\n };\n this.updateList();\n this.registerForContextMenu(this.getListView());\n this.getListView().setOnItemClickListener(new OnItemClickListener() {\n\n public void onItemClick(AdapterView adapter, View view, int position, long id) {\n ListView lv = PortForwardListActivity.this.getListView();\n PortForwardBean pfb = (PortForwardBean) lv.getItemAtPosition(position);\n if (hostBridge != null) {\n if (pfb.isEnabled())\n hostBridge.disablePortForward(pfb);\n else {\n if (!hostBridge.enablePortForward(pfb))\n Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();\n }\n updateHandler.sendEmptyMessage(-1);\n }\n }\n });\n this.inflater = LayoutInflater.from(this);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n super.onCreateOptionsMenu(menu);\n MenuItem add = menu.add(R.string.portforward_menu_add);\n add.setIcon(android.R.drawable.ic_menu_add);\n add.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n // build dialog to prompt user about updating\n final View portForwardView = inflater.inflate(R.layout.dia_portforward, null, false);\n final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);\n final Spinner typeSpinner = (Spinner) portForwardView.findViewById(R.id.portforward_type);\n typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n public void onItemSelected(AdapterView value, View view, int position, long id) {\n destEdit.setEnabled(position != 2);\n }\n\n public void onNothingSelected(AdapterView arg0) {\n }\n });\n new AlertDialog.Builder(PortForwardListActivity.this).setView(portForwardView).setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);\n final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);\n String type = HostDatabase.PORTFORWARD_LOCAL;\n switch(typeSpinner.getSelectedItemPosition()) {\n case 0:\n type = HostDatabase.PORTFORWARD_LOCAL;\n break;\n case 1:\n type = HostDatabase.PORTFORWARD_REMOTE;\n break;\n case 2:\n type = HostDatabase.PORTFORWARD_DYNAMIC5;\n break;\n }\n PortForwardBean pfb = new PortForwardBean(host != null ? host.getId() : -1, nicknameEdit.getText().toString(), type, sourcePortEdit.getText().toString(), destEdit.getText().toString());\n if (hostBridge != null) {\n hostBridge.addPortForward(pfb);\n hostBridge.enablePortForward(pfb);\n }\n if (host != null && !hostdb.savePortForward(pfb))\n throw new SQLException(\"Could not save port forward\");\n updateHandler.sendEmptyMessage(-1);\n } catch (Exception e) {\n Log.e(TAG, \"Could not update port forward\", e);\n // TODO Show failure dialog.\n }\n }\n }).setNegativeButton(R.string.delete_neg, null).create().show();\n return true;\n }\n });\n return true;\n }\n\n @Override\n public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {\n // Create menu to handle deleting and editing port forward\n AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;\n final PortForwardBean pfb = (PortForwardBean) this.getListView().getItemAtPosition(info.position);\n menu.setHeaderTitle(pfb.getNickname());\n MenuItem edit = menu.add(R.string.portforward_edit);\n edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n final View editTunnelView = inflater.inflate(R.layout.dia_portforward, null, false);\n final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);\n if (HostDatabase.PORTFORWARD_LOCAL.equals(pfb.getType()))\n typeSpinner.setSelection(0);\n else if (HostDatabase.PORTFORWARD_REMOTE.equals(pfb.getType()))\n typeSpinner.setSelection(1);\n else\n typeSpinner.setSelection(2);\n final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);\n nicknameEdit.setText(pfb.getNickname());\n final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);\n sourcePortEdit.setText(String.valueOf(pfb.getSourcePort()));\n final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);\n if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(pfb.getType())) {\n destEdit.setEnabled(false);\n } else {\n destEdit.setText(String.format(\"%s:%d\", pfb.getDestAddr(), pfb.getDestPort()));\n }\n typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n public void onItemSelected(AdapterView value, View view, int position, long id) {\n destEdit.setEnabled(position != 2);\n }\n\n public void onNothingSelected(AdapterView arg0) {\n }\n });\n new AlertDialog.Builder(PortForwardListActivity.this).setView(editTunnelView).setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n if (hostBridge != null)\n hostBridge.disablePortForward(pfb);\n pfb.setNickname(nicknameEdit.getText().toString());\n switch(typeSpinner.getSelectedItemPosition()) {\n case 0:\n pfb.setType(HostDatabase.PORTFORWARD_LOCAL);\n break;\n case 1:\n pfb.setType(HostDatabase.PORTFORWARD_REMOTE);\n break;\n case 2:\n pfb.setType(HostDatabase.PORTFORWARD_DYNAMIC5);\n break;\n }\n pfb.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));\n pfb.setDest(destEdit.getText().toString());\n // Use the new settings for the existing connection.\n if (hostBridge != null)\n updateHandler.postDelayed(new Runnable() {\n\n public void run() {\n hostBridge.enablePortForward(pfb);\n updateHandler.sendEmptyMessage(-1);\n }\n }, LISTENER_CYCLE_TIME);\n if (!hostdb.savePortForward(pfb))\n throw new SQLException(\"Could not save port forward\");\n updateHandler.sendEmptyMessage(-1);\n } catch (Exception e) {\n Log.e(TAG, \"Could not update port forward\", e);\n // TODO Show failure dialog.\n }\n }\n }).setNegativeButton(android.R.string.cancel, null).create().show();\n return true;\n }\n });\n MenuItem delete = menu.add(R.string.portforward_delete);\n delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n\n public boolean onMenuItemClick(MenuItem item) {\n // prompt user to make sure they really want this\n new AlertDialog.Builder(PortForwardListActivity.this).setMessage(getString(R.string.delete_message, pfb.getNickname())).setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n ", "post_mask_code": "\n updateHandler.sendEmptyMessage(-1);\n }\n }).setNegativeButton(R.string.delete_neg, null).create().show();\n return true;\n }\n });\n }\n\n protected Handler updateHandler = new Handler() {\n\n @Override\n public void handleMessage(Message msg) {\n PortForwardListActivity.this.updateList();\n }\n };\n\n protected void updateList() {\n if (hostBridge != null) {\n this.portForwards = hostBridge.getPortForwards();\n } else {\n if (this.hostdb == null)\n return;\n this.portForwards = this.hostdb.getPortForwardsForHost(host);\n }\n PortForwardAdapter adapter = new PortForwardAdapter(this, portForwards);\n this.setListAdapter(adapter);\n }\n\n class PortForwardAdapter extends ArrayAdapter {\n\n class ViewHolder {\n\n public TextView nickname;\n\n public TextView caption;\n }\n\n private List portForwards;\n\n public PortForwardAdapter(Context context, List portForwards) {\n super(context, R.layout.item_portforward, portForwards);\n this.portForwards = portForwards;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n ViewHolder holder;\n if (convertView == null) {\n convertView = inflater.inflate(R.layout.item_portforward, null, false);\n holder = new ViewHolder();\n holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);\n holder.caption = (TextView) convertView.findViewById(android.R.id.text2);\n convertView.setTag(holder);\n } else\n holder = (ViewHolder) convertView.getTag();\n PortForwardBean pfb = portForwards.get(position);\n holder.nickname.setText(pfb.getNickname());\n holder.caption.setText(pfb.getDescription());\n if (hostBridge != null && !pfb.isEnabled()) {\n holder.nickname.setPaintFlags(holder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);\n holder.caption.setPaintFlags(holder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);\n }\n return convertView;\n }\n }\n}\n"} {"task_id": "Java_2051", "language": "Java", "task_type": "method_signature", "source_file": "java/github/rayfowler/rotp-public/src/rotp/ui/races/RacesDiplomacyUI.java", "mask_start_position": 4280, "mask_end_position": 4299, "canonical_solution": "public void init() ", "pre_mask_code": "/*\n * \n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage rotp.ui.races;\n\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.Image;\nimport java.awt.LinearGradientPaint;\nimport java.awt.Polygon;\nimport java.awt.Rectangle;\nimport java.awt.Shape;\nimport java.awt.Stroke;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseListener;\nimport java.awt.event.MouseMotionListener;\nimport java.awt.event.MouseWheelEvent;\nimport java.awt.event.MouseWheelListener;\nimport java.awt.geom.Point2D;\nimport java.awt.geom.RoundRectangle2D;\nimport java.awt.image.BufferedImage;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport rotp.model.empires.DiplomaticTreaty;\nimport rotp.model.empires.Empire;\nimport rotp.model.empires.EmpireView;\nimport rotp.model.empires.TreatyAlliance;\nimport rotp.model.incidents.DiplomaticIncident;\nimport rotp.ui.BasePanel;\nimport rotp.ui.UserPreferences;\nimport rotp.ui.diplomacy.DialogueManager;\nimport rotp.ui.diplomacy.DiplomaticMessage;\nimport rotp.ui.main.MainUI;\nimport rotp.ui.main.SystemPanel;\nimport static rotp.ui.races.RacesIntelligenceUI.sliderC;\n\npublic final class RacesDiplomacyUI extends BasePanel implements MouseListener, MouseMotionListener, MouseWheelListener {\n\n private static final long serialVersionUID = 1L;\n\n public static final String[] relationIds = new String[] { \"RELATIONS_FEUD\", \"RELATIONS_HATE\", \"RELATIONS_DISCORD\", \"RELATIONS_TROUBLED\", \"RELATIONS_TENSE\", \"RELATIONS_RESTLESS\", \"RELATIONS_WARY\", \"RELATIONS_UNEASE\", \"RELATIONS_NEUTRAL\", \"RELATIONS_RELAXED\", \"RELATIONS_AMIABLE\", \"RELATIONS_CALM\", \"RELATIONS_AFFABLE\", \"RELATIONS_PEACEFUL\", \"RELATIONS_FRIENDLY\", \"RELATIONS_UNITY\", \"RELATIONS_HARMONY\" };\n\n private static final Color unselectedC = new Color(112, 85, 68);\n\n private final Color greenEdgeC = new Color(44, 59, 30);\n\n private final Color greenMidC = new Color(70, 93, 48);\n\n private final Color brownEdgeC = new Color(101, 70, 50);\n\n private final Color brownMidC = new Color(161, 111, 78);\n\n private final Color brownDividerC = new Color(136, 115, 96);\n\n private final Color incidentRedC = new Color(112, 0, 0);\n\n private final Color incidentGreenC = new Color(0, 63, 32);\n\n private final RacesUI parent;\n\n private final ManageDiplomatsUI manageDiplomatsPane;\n\n private final ManageSpiesUI manageSpiesPane;\n\n int incidentY, incidentYMax;\n\n int relationsY, relationsYMax;\n\n int dragY;\n\n private LinearGradientPaint incidentTitleBackground;\n\n private LinearGradientPaint backGradient;\n\n private LinearGradientPaint embassyBackground, embassyDisabledBackground;\n\n private final Rectangle embassyBox = new Rectangle();\n\n private final Rectangle incidentListBox = new Rectangle();\n\n private final Rectangle incidentScroller = new Rectangle();\n\n private final Rectangle relationsListBox = new Rectangle();\n\n private final Rectangle relationsScroller = new Rectangle();\n\n private final Rectangle manageDiplomatsBox = new Rectangle();\n\n private final Rectangle manageSpiesBox = new Rectangle();\n\n Polygon buttonIncr = new Polygon();\n\n Polygon buttonDecr = new Polygon();\n\n Rectangle buttonSlider = new Rectangle();\n\n private float internalSecurityCost = 0;\n\n private float externalSpyingCost = 0;\n\n int[] ptX = new int[3];\n\n int[] ptY = new int[3];\n\n private final HashMap incidentMap = new HashMap<>();\n\n private Shape hoverShape;\n\n public RacesDiplomacyUI(RacesUI p) {\n parent = p;\n manageDiplomatsPane = new ManageDiplomatsUI(p);\n manageSpiesPane = new ManageSpiesUI(p);\n initModel();\n }\n\n @Override\n public void drawTexture(Graphics g) {\n }\n\n @Override\n public String textureName() {\n return TEXTURE_BROWN;\n }\n\n ", "post_mask_code": "{\n setValues();\n }\n\n public void changedEmpire() {\n setValues();\n }\n\n private void setValues() {\n incidentY = 0;\n relationsY = 0;\n if (parent.selectedEmpire().isPlayer()) {\n internalSecurityCost = player().empireInternalSecurityCost();\n externalSpyingCost = player().empireExternalSpyingCost();\n }\n }\n\n @Override\n public void paintComponent(Graphics g0) {\n super.paintComponent(g0);\n Graphics2D g = (Graphics2D) g0;\n int w = getWidth();\n int h = getHeight();\n relationsListBox.setBounds(0, 0, 0, 0);\n relationsScroller.setBounds(0, 0, 0, 0);\n manageDiplomatsBox.setBounds(0, 0, 0, 0);\n manageSpiesBox.setBounds(0, 0, 0, 0);\n buttonIncr.reset();\n buttonDecr.reset();\n if (backGradient == null) {\n Point2D start = new Point2D.Float(0, getHeight() / 2);\n Point2D end = new Point2D.Float(0, getHeight());\n float[] dist = { 0.0f, 1.0f };\n Color[] colors = { RacesUI.darkerBrown, RacesUI.gradientBottom };\n backGradient = new LinearGradientPaint(start, end, dist, colors);\n }\n g.setPaint(backGradient);\n g.fillRect(0, h / 2, w, h / 2);\n if (parent.selectedEmpire().isPlayer())\n paintPlayerData(g);\n else\n paintAIData(g);\n }\n\n private void initModel() {\n setBackground(RacesUI.darkerBrown);\n setBorder(newEmptyBorder(5, 5, 5, 5));\n addMouseMotionListener(this);\n addMouseListener(this);\n addMouseWheelListener(this);\n }\n\n private void paintPlayerData(Graphics2D g) {\n Empire emp = parent.selectedEmpire();\n int w = getWidth();\n int h = getHeight();\n int s200 = scaled(200);\n int s210 = scaled(210);\n int s215 = scaled(215);\n int s245 = scaled(245);\n int s260 = scaled(260);\n int s370 = scaled(370);\n int s435 = scaled(435);\n int x0 = s20;\n int x1 = w - scaled(299);\n int w0 = x1 - x0 - s20;\n int w1 = scaled(279);\n drawRaceIconBase(g, emp, s55, s25, s210, s210);\n drawPlayerBaseInfo(g, emp, s260, s80, s370, scaled(130));\n drawPlayerDiplomaticEvents(g, emp, x0, s245, w0, h - s245 - s10);\n drawPlayerDiplomacyBureau(g, emp, x1, s10, w1, s200);\n drawPlayerCounterIntelligenceBureau(g, emp, x1, s215, w1, s215);\n drawPlayerIntelligenceBureau(g, emp, x1, s435, w1, s200);\n if (UserPreferences.texturesInterface())\n drawTexture(g, 0, 0, w, h);\n drawRaceIcon(g, emp, s60, s30, s200, s200);\n drawEmpireName(g, emp, s260, s30, s370, s50);\n }\n\n private void paintAIData(Graphics2D g) {\n Empire emp = parent.selectedEmpire();\n int w = getWidth();\n int h = getHeight();\n int s200 = scaled(200);\n int s135 = scaled(135);\n int s150 = scaled(150);\n int s175 = scaled(175);\n int s210 = scaled(210);\n int s245 = scaled(245);\n int s260 = scaled(260);\n int s295 = scaled(295);\n int s330 = scaled(330);\n int s370 = scaled(370);\n int x0 = s20;\n int x1 = w - scaled(299);\n int w0 = x1 - x0 - s20;\n int w1 = scaled(279);\n drawRaceIconBase(g, emp, s55, s25, s210, s210);\n drawAIBaseInfo(g, emp, s260, s80, s370, scaled(130));\n drawRelationsMeter(g, emp, x0, s245, w0, s40);\n drawAIDiplomaticEvents(g, emp, x0, s295, w0, h - s295 - s10);\n drawAIDiplomacyBureau(g, emp, x1, s10, w1, s135);\n drawAITradeSummary(g, emp, x1, s150, w1, s175);\n drawAIForeignRelations(g, emp, x1, s330, w1, h - s330 - s10);\n if (UserPreferences.texturesInterface())\n drawTexture(g, 0, 0, w, h);\n drawRaceIcon(g, emp, s60, s30, s200, s200);\n drawEmpireName(g, emp, s260, s30, s370, s50);\n }\n\n private void drawRaceIconBase(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n Shape rect = new RoundRectangle2D.Float(x, y, w, h, w / 8, h / 8);\n g.fill(rect);\n }\n\n private void drawRaceIcon(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(Color.black);\n Shape rect = new RoundRectangle2D.Float(x, y, w, h, w / 8, h / 8);\n g.fill(rect);\n BufferedImage backImg = parent.raceIconBackImg();\n g.drawImage(backImg, x, y, null);\n int x1 = x + w / 10;\n int w1 = w * 8 / 10;\n int y1 = y + h / 10;\n int h1 = h * 8 / 10;\n Image img = emp.isPlayer() ? emp.race().flagPact() : player().viewForEmpire(emp).flag();\n int imgH = img.getHeight(null);\n int imgW = img.getWidth(null);\n g.drawImage(img, x1, y1, x1 + w1, y1 + h1, 0, 0, imgW, imgH, null);\n }\n\n private void drawEmpireName(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(SystemPanel.orangeText);\n g.setFont(narrowFont(32));\n drawString(g, emp.name(), x + s10, y + h - s15);\n }\n\n private void drawPlayerBaseInfo(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n int lineH = s30;\n int y1 = y + lineH - s5;\n int y2 = y1 + lineH;\n int y3 = y2 + lineH;\n int y4 = y3 + lineH;\n int x0 = x + s20;\n g.setFont(narrowFont(22));\n Color textC = SystemPanel.whiteText;\n drawShadowedString(g, text(\"RACES_DIPLOMACY_HOMEWORLD\"), 1, x0, y1, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_LEADER\"), 1, x0, y2, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_CURRENT_TRADE\"), 1, x0, y3, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_TOTAL_TRADE\"), 1, x0, y4, SystemPanel.blackText, textC);\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n String s = emp.sv.name(emp.capitalSysId());\n int sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y1);\n s = text(\"TITLE_LEADERNAME\", emp.labels().text(\"_nameTitle\"), emp.leader().name());\n s = emp.replaceTokens(s, \"alien\");\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n int amt = (int) player().totalTradeIncome();\n s = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y3);\n amt = player().totalTradeTreaties();\n s = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y4);\n }\n\n private void drawAIBaseInfo(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n int lineH = s30;\n int y1 = y + lineH - s5;\n int y2 = y1 + lineH;\n int y3 = y2 + lineH;\n int y4 = y3 + lineH;\n int x0 = x + s20;\n g.setFont(narrowFont(22));\n Color textC = SystemPanel.whiteText;\n drawShadowedString(g, text(\"RACES_DIPLOMACY_HOMEWORLD\"), 1, x0, y1, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_LEADER\"), 1, x0, y2, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_CHARACTER\"), 1, x0, y3, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_STATUS\"), 1, x0, y4, SystemPanel.blackText, textC);\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n String s = emp.sv.name(emp.capitalSysId());\n int sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y1);\n s = text(\"TITLE_LEADERNAME\", emp.race().text(\"_nameTitle\"), emp.leader().name());\n s = emp.replaceTokens(s, \"alien\");\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n s = text(\"LEADER_PERSONALITY_FORMAT\", emp.leader().personality(), emp.leader().objective());\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y3);\n EmpireView view = player().viewForEmpire(emp);\n DiplomaticTreaty treaty = view.embassy().treaty();\n boolean isAlly = treaty.isAlliance();\n int starW = s10;\n int offset = isAlly ? (starW * 5) + s5 : 0;\n s = treaty.status(player());\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - offset - sw, y4);\n if (isAlly) {\n TreatyAlliance alliance = (TreatyAlliance) treaty;\n int x1 = x + w - s20 - offset + s5;\n parent.drawAllianceStars(g, x1, y4 - s3, alliance.standing(player()), starW);\n }\n }\n\n private void drawRelationsMeter(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n EmpireView view = player().viewForEmpire(emp);\n if (view == null)\n return;\n int x0 = x + s10;\n int y0 = y + h - s12;\n g.setFont(narrowFont(24));\n String str = text(\"RACES_DIPLOMACY_RELATIONS_METER\");\n this.drawShadowedString(g, str, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n int leftW = g.getFontMetrics().stringWidth(str);\n if (emp.race().masksDiplomacy) {\n g.setFont(narrowFont(15));\n g.setColor(SystemPanel.blackText);\n String str2 = text(\"RACES_DIPLOMACY_RELATIONS_UNKNOWN\");\n str2 = emp.replaceTokens(str2, \"alien\");\n List lines = this.wrappedLines(g, str2, w - s60 - leftW);\n int x1 = x0 + leftW + s40;\n int y1 = lines.size() == 1 ? y0 : y0 - s10;\n for (String line : lines) {\n drawString(g, line, x1, y1);\n y1 += s15;\n }\n return;\n }\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n float relations = view.otherView().embassy().relations();\n // which relation key display to use\n float pctRel = (relations + 100) / 200.0f;\n float sizeRelId = 1.0f / relationIds.length;\n int i = (int) (pctRel / sizeRelId);\n i = bounds(0, i, relationIds.length - 1);\n String rel = text(relationIds[i]);\n int rightW = g.getFontMetrics().stringWidth(rel);\n int x1 = x + w - rightW - s20;\n drawString(g, rel, x1, y0);\n int x2 = x0 + leftW + s30;\n int w2 = x + w - x2 - rightW - s30;\n int y2 = y + s12;\n int h2 = h - s15;\n parent.drawRelationsBar(g, emp, x2, y2, w2, h2, s16, s8);\n }\n\n private void drawPlayerDiplomaticEvents(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n // title area\n int x0 = x;\n int w0 = w;\n int y0 = y;\n int h0 = s30;\n if (incidentTitleBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x0, 0);\n Point2D ptEnd = new Point2D.Float(x0 + w0, 0);\n Color[] yesColors = { brownEdgeC, brownMidC, brownEdgeC };\n incidentTitleBackground = new LinearGradientPaint(ptStart, ptEnd, dist, yesColors);\n }\n g.setPaint(incidentTitleBackground);\n g.fillRect(x0, y0, w0, h0);\n // year or turn\n g.setFont(narrowFont(20));\n int x1 = x0;\n int w1 = s60;\n String year = UserPreferences.displayYear() ? text(\"RACES_DIPLOMACY_EVENT_YEAR\") : text(\"RACES_DIPLOMACY_EVENT_TURN\");\n int sw = g.getFontMetrics().stringWidth(year);\n drawShadowedString(g, year, 1, x0 + (w1 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // race\n g.setFont(narrowFont(20));\n int x2 = x1 + w1;\n int w2 = s100;\n String race = text(\"RACES_DIPLOMACY_EVENT_RACE\");\n sw = g.getFontMetrics().stringWidth(race);\n drawShadowedString(g, race, 1, x2 + (w2 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // scrollboar\n int w5 = s20;\n int x5 = x0 + w0 - w5;\n // effect\n g.setFont(narrowFont(20));\n String effect = text(\"RACES_DIPLOMACY_EVENT_EFFECT\");\n sw = g.getFontMetrics().stringWidth(effect);\n int w4 = s60;\n int x4 = x5 - w4;\n drawShadowedString(g, effect, 1, x4 + (w4 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(22));\n int x3 = x2 + w2;\n int w3 = x4 - x3;\n String title = text(\"RACES_DIPLOMACY_EVENT_TITLE\");\n sw = g.getFontMetrics().stringWidth(title);\n drawShadowedString(g, title, 1, x3 + (w3 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // data area\n g.setColor(RacesUI.darkBrown);\n int y1 = y0 + h0;\n int listH = h - h0;\n g.fillRect(x0, y1, w0, listH);\n g.setClip(x0, y1 + s1, w0, listH - s2);\n // draw vertical divider lines\n Stroke prev = g.getStroke();\n g.setStroke(stroke1);\n g.setColor(brownDividerC);\n g.drawLine(x2, y1, x2, y1 + listH);\n g.drawLine(x3, y1, x3, y1 + listH);\n g.drawLine(x4, y1, x4, y1 + listH);\n g.drawLine(x5, y1, x5, y1 + listH);\n g.setStroke(prev);\n List incidents = new ArrayList<>();\n incidentMap.clear();\n for (EmpireView view : player().contacts()) {\n for (DiplomaticIncident inc : view.otherView().embassy().allIncidents()) {\n if ((inc.currentSeverity() != 0) && inc.triggeredByAction()) {\n incidents.add(inc);\n incidentMap.put(inc, view.empire());\n }\n }\n }\n Collections.sort(incidents, DiplomaticIncident.DATE);\n int y2 = y1 - incidentY;\n int fullListH = 0;\n for (int i = 0; i < incidents.size(); i++) {\n DiplomaticIncident inc = incidents.get(i);\n int incidentH = drawPlayerIncident(g, inc, x0, y2, w0, w1, w2, w3, w4);\n fullListH += incidentH;\n y2 += incidentH;\n }\n incidentYMax = max(0, fullListH - listH);\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + incidentYMax));\n int scrollX = x + w - scrollW - s4;\n int scrollY = (int) (y1 + (float) listH * incidentY / (incidentYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n incidentScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == incidentScroller) {\n prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n g.setClip(null);\n incidentListBox.setBounds(x0, y1, w0, listH);\n if ((hoverShape == incidentListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(incidentListBox);\n g.setStroke(prev);\n }\n }\n\n private int drawPlayerIncident(Graphics g, DiplomaticIncident inc, int x, int y, int w, int w1, int w2, int w3, int w4) {\n String title = inc.title() + \":\";\n String sev = fmt(inc.currentSeverity(), 1);\n String desc = inc.description();\n g.setFont(narrowFont(18));\n int indent = g.getFontMetrics().stringWidth(title) + s5;\n g.setFont(narrowFont(15));\n List descLines = wrappedLines(g, desc, w3 - s15, indent);\n int h0 = s7 + (s22 * descLines.size());\n // title\n int x1 = x;\n int x2 = x1 + w1;\n int x3 = x2 + w2;\n int x4 = x3 + w3;\n int y1 = y + s8;\n // year or turn\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n String year = UserPreferences.displayYear() ? str(inc.dateOccurred()) : str(inc.turnOccurred());\n int sw = g.getFontMetrics().stringWidth(year);\n int x0 = x1 + (w1 - sw) / 2;\n int y0 = y + s25;\n drawString(g, year, x0, y0);\n // race\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n Empire otherEmpire = incidentMap.get(inc);\n String race = otherEmpire.raceName();\n sw = g.getFontMetrics().stringWidth(race);\n x0 = x2 + (w2 - sw) / 2;\n y0 = y + s25;\n drawString(g, race, x0, y0);\n boolean firstLine = true;\n g.setFont(narrowFont(18));\n for (String line : descLines) {\n y1 += s17;\n g.setColor(Color.black);\n if (firstLine) {\n drawString(g, title, x3 + s10, y1);\n g.setFont(narrowFont(15));\n drawString(g, line, x3 + s10 + indent, y1);\n firstLine = false;\n } else\n drawString(g, line, x3 + s10, y1);\n }\n // severity\n if (!otherEmpire.race().masksDiplomacy) {\n g.setFont(narrowFont(18));\n sw = g.getFontMetrics().stringWidth(sev);\n x0 = x4 + (w4 - sw) / 2;\n if (inc.currentSeverity() < 0)\n g.setColor(incidentRedC);\n else\n g.setColor(incidentGreenC);\n drawString(g, sev, x0, y0);\n }\n g.setColor(brownDividerC);\n g.drawLine(x1, y1 + s12, x + w - s20, y1 + s12);\n return h0;\n }\n\n private void drawPlayerDiplomacyBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n List views = player().contacts();\n int recalls = 0;\n for (EmpireView v : views) {\n if (v.embassy().diplomatGone())\n recalls++;\n }\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_BUREAU\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_DIPLOMACY_BUREAU_DESC1\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_DIPLOMACY_KNOWN_EMPIRES\");\n int y2 = y0 + s85;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String str2 = str(views.size());\n int sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_DIPLOMACY_RECALLED_DIPLOMAT\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) 0;\n g.setFont(narrowFont(16));\n str2 = str(recalls);\n sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n drawManageDiplomatsButton(g, x + s20, y + h - s45, w - s40, s25);\n }\n\n private void drawPlayerCounterIntelligenceBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_COUNTER_BUREAU\");\n int fontSize = scaledFont(g, title, w - s20, 24, 20);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_DIPLOMACY_COUNTER_DESC\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_INTEL_SECURITY_BONUS\");\n int y2 = y0 + s70;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n int amt = (int) (100 * player().totalInternalSecurityPct());\n String s = amt == 0 ? text(\"RACES_INTEL_SECURITY_BONUS_NONE\") : text(\"RACES_INTEL_SECURITY_BONUS_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_INTEL_TOTAL_SPENDING\");\n drawString(g, spending, x + s20, y2);\n g.setFont(narrowFont(16));\n amt = (int) internalSecurityCost;\n s = text(\"RACES_INTEL_SPENDING_ANNUAL\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n g.setFont(narrowFont(15));\n desc = text(\"RACES_DIPLOMACY_COUNTER_DESC2\");\n lines = wrappedLines(g, desc, w - s30);\n int y3 = y + h - s20 - (s16 * 3);\n for (String line : lines) {\n drawString(g, line, x + s20, y3);\n y3 += s16;\n }\n g.setFont(narrowFont(16));\n int y4 = y + h - s20;\n String taxStr = text(\"RACES_INTEL_SECURITY_TAX\");\n drawString(g, taxStr, x + s20, y4);\n int sw4 = g.getFontMetrics().stringWidth(taxStr);\n // draw string on right for pct\n String cost = text(\"RACES_INTEL_PERCENT_AMT\", (int) (player().internalSecurityCostPct() * 100));\n sw = g.getFontMetrics().stringWidth(cost);\n drawString(g, cost, x + w - s20 - sw, y4);\n // need maxwidth so slider doesn't move as cost pct changes\n String maxWidthStr = text(\"RACES_INTEL_PERCENT_AMT\", 10);\n sw = g.getFontMetrics().stringWidth(maxWidthStr);\n int sliderW = w - sw - sw4 - s80;\n int sliderH = s16;\n drawSecuritySliderBar(g, x + s20 + sw4, y4 - sliderH + s3, sliderW, sliderH);\n }\n\n private void drawSecuritySliderBar(Graphics2D g, int x, int y, int w, int h) {\n // draw spending bar\n // height of bar\n int h1 = h;\n // width of bar\n int w1 = w;\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n float pct = view == null ? player().internalSecurityPct() : view.spies().allocationPct();\n // width of spending\n int w1a = (int) (pct * w1);\n int y1 = y + ((h - h1) / 2);\n int x1 = x + s20;\n g.setColor(Color.black);\n g.fillRect(x1, y1, w1, h1);\n g.setColor(sliderC);\n g.fillRect(x1, y1, w1a, h1);\n buttonSlider.setBounds(x1, y1, w1, h1);\n if (hoverShape == buttonSlider) {\n g.setColor(Color.yellow);\n Stroke prev = g.getStroke();\n g.setStroke(stroke2);\n g.drawRect(x1, y1, w1, h1);\n g.setStroke(prev);\n }\n int sz = h1 / 2;\n // draw left/decr button\n ptX[0] = x1 - s3 - sz;\n ptX[1] = ptX[0] + sz;\n ptX[2] = ptX[0] + sz;\n ptY[0] = y + (h / 2);\n ptY[1] = ptY[0] - sz;\n ptY[2] = ptY[0] + sz;\n Color buttonC = hoverShape == buttonDecr ? SystemPanel.yellowText : Color.black;\n buttonDecr.reset();\n for (int i = 0; i < ptX.length; i++) buttonDecr.addPoint(ptX[i], ptY[i]);\n drawShadedPolygon(g, ptX, ptY, buttonC, s1, -s1);\n // draw right/incr button\n ptX[0] = x1 + w1 + sz + s3;\n ptX[1] = ptX[0] - sz;\n ptX[2] = ptX[0] - sz;\n ptY[0] = y + (h / 2);\n ptY[1] = ptY[0] - sz;\n ptY[2] = ptY[0] + sz;\n buttonIncr.reset();\n for (int i = 0; i < ptX.length; i++) buttonIncr.addPoint(ptX[i], ptY[i]);\n buttonC = hoverShape == buttonIncr ? SystemPanel.yellowText : Color.black;\n drawShadedPolygon(g, ptX, ptY, buttonC, s1, -s1);\n if (!parent.selectedEmpire().isPlayer()) {\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(15));\n String spyCost = text(\"RACES_INTEL_SPENDING_ANNUAL\", (int) externalSpyingCost);\n int sw1 = g.getFontMetrics().stringWidth(spyCost);\n int xa = buttonSlider.x + ((buttonSlider.width - sw1) / 2);\n int ya = buttonSlider.y + buttonSlider.height - s4;\n drawString(g, spyCost, xa, ya);\n }\n }\n\n private void drawPlayerIntelligenceBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_INTEL_BUREAU_TITLE\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_INTEL_BUREAU_DESC\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_INTEL_BUREAU_SPIES\");\n int y2 = y + h - s85;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String str2 = str(player().totalActiveSpies());\n int sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_INTEL_BUREAU_SPENDING\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) externalSpyingCost;\n g.setFont(narrowFont(16));\n str2 = amt == 0 ? text(\"RACES_INTEL_SECURITY_BONUS_NONE\") : text(\"RACES_INTEL_SPENDING_ANNUAL\", str(amt));\n sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n drawManageSpiesButton(g, x + s20, y2, w - s40, s25);\n }\n\n private void drawManageDiplomatsButton(Graphics2D g, int x, int y, int w, int h) {\n manageDiplomatsBox.setBounds(x, y, w, h);\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n g.setColor(unselectedC);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if (hoverShape == manageDiplomatsBox)\n c0 = Color.yellow;\n String lbl = text(\"RACES_DIPLOMACY_MANAGE_DIPLOMATS\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n private void drawManageSpiesButton(Graphics2D g, int x, int y, int w, int h) {\n manageSpiesBox.setBounds(x, y, w, h);\n g.setColor(Color.blue);\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n g.setColor(unselectedC);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if (hoverShape == manageSpiesBox)\n c0 = Color.yellow;\n String lbl = text(\"RACES_INTEL_BUREAU_MANAGE\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n private void drawAIDiplomaticEvents(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n // title area\n int x0 = x;\n int w0 = w;\n int y0 = y;\n int h0 = s30;\n if (incidentTitleBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x0, 0);\n Point2D ptEnd = new Point2D.Float(x0 + w0, 0);\n Color[] yesColors = { brownEdgeC, brownMidC, brownEdgeC };\n incidentTitleBackground = new LinearGradientPaint(ptStart, ptEnd, dist, yesColors);\n }\n g.setPaint(incidentTitleBackground);\n g.fillRect(x0, y0, w0, h0);\n // title\n g.setFont(narrowFont(20));\n String year = UserPreferences.displayYear() ? text(\"RACES_DIPLOMACY_EVENT_YEAR\") : text(\"RACES_DIPLOMACY_EVENT_TURN\");\n drawShadowedString(g, year, 1, x0 + s10, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(22));\n String title = text(\"RACES_DIPLOMACY_EVENT_TITLE\");\n int sw = g.getFontMetrics().stringWidth(title);\n drawShadowedString(g, title, 1, x0 + (w0 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(20));\n String effect = text(\"RACES_DIPLOMACY_EVENT_EFFECT\");\n int sw2 = g.getFontMetrics().stringWidth(effect);\n drawShadowedString(g, effect, 1, x0 + w0 - sw2 - s30, y0 + s23, Color.black, SystemPanel.whiteText);\n // data area\n g.setColor(RacesUI.darkBrown);\n int y1 = y0 + h0;\n int x1 = x0;\n int w1 = w0;\n int listH = h - h0;\n g.fillRect(x1, y1, w1, listH);\n g.setClip(x1, y1 + s1, w1, listH - s2);\n // draw vertical divider lines\n int x1a = x1 + s60;\n int x1b = x1 + w1 - s80;\n int x1c = x1 + w1 - s20;\n Stroke prev = g.getStroke();\n g.setStroke(stroke1);\n g.setColor(brownDividerC);\n g.drawLine(x1a, y1, x1a, y1 + listH);\n g.drawLine(x1b, y1, x1b, y1 + listH);\n g.drawLine(x1c, y1, x1c, y1 + listH);\n g.setStroke(prev);\n List incidents = new ArrayList<>();\n for (DiplomaticIncident inc : parent.selectedView().otherView().embassy().allIncidents()) {\n if (inc.currentSeverity() != 0)\n incidents.add(inc);\n }\n Collections.sort(incidents, DiplomaticIncident.DATE);\n int y2 = y1 - incidentY;\n int fullListH = 0;\n for (int i = 0; i < incidents.size(); i++) {\n DiplomaticIncident inc = incidents.get(i);\n int incidentH = drawAIIncident(g, inc, x1, y2, w1, s60, s80);\n fullListH += incidentH;\n y2 += incidentH;\n }\n incidentYMax = max(0, fullListH - listH);\n if (incidentYMax == 0)\n incidentScroller.setBounds(0, 0, 0, 0);\n else {\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + incidentYMax));\n int scrollX = x1 + w1 - scrollW - s2;\n int scrollY = (int) (y1 + (float) listH * incidentY / (incidentYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n incidentScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == incidentScroller) {\n prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n }\n g.setClip(null);\n incidentListBox.setBounds(x1, y1, w1, listH);\n if ((hoverShape == incidentListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(incidentListBox);\n g.setStroke(prev);\n }\n }\n\n private int drawAIIncident(Graphics g, DiplomaticIncident inc, int x, int y, int w, int leftM, int rightM) {\n String title = inc.title() + \":\";\n String sev = fmt(inc.currentSeverity(), 1);\n String desc = inc.description();\n g.setFont(narrowFont(18));\n int indent = g.getFontMetrics().stringWidth(title) + s5;\n g.setFont(narrowFont(15));\n List descLines = wrappedLines(g, desc, w - s20 - leftM - rightM, indent);\n int h0 = s7 + (s22 * descLines.size());\n // title\n int x1 = x + leftM + s10;\n int y1 = y + s8;\n g.setFont(narrowFont(22));\n g.setColor(Color.black);\n // description lines\n boolean firstLine = true;\n g.setFont(narrowFont(18));\n for (String line : descLines) {\n y1 += s17;\n g.setColor(Color.black);\n if (firstLine) {\n drawString(g, title, x1, y1);\n g.setFont(narrowFont(15));\n drawString(g, line, x1 + indent, y1);\n firstLine = false;\n } else\n drawString(g, line, x1, y1);\n }\n // year\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n String year = UserPreferences.displayYear() ? str(inc.dateOccurred()) : str(inc.turnOccurred());\n int sw0 = g.getFontMetrics().stringWidth(year);\n int x0 = x + (leftM - sw0) / 2;\n int y0 = y + s25;\n drawString(g, year, x0, y0);\n // severity\n int x2 = x + w - rightM;\n int w2 = s60;\n if (!parent.selectedEmpire().race().masksDiplomacy) {\n g.setFont(narrowFont(18));\n int sw = g.getFontMetrics().stringWidth(sev);\n int x2a = x2 + (w2 - sw) / 2;\n if (inc.currentSeverity() < 0)\n g.setColor(incidentRedC);\n else\n g.setColor(incidentGreenC);\n drawString(g, sev, x2a, y0);\n }\n g.setColor(brownDividerC);\n g.drawLine(x, y1 + s8, x + w - s20, y1 + s8);\n return h0;\n }\n\n private void drawAIDiplomacyBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_BUREAU\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean finalWar = player().viewForEmpire(emp).embassy().finalWar();\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (finalWar)\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC_FINAL\");\n else if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC_RANGE\");\n else {\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n }\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s7;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n embassyBox.setBounds(0, 0, 0, 0);\n if (!finalWar && !outOfRange)\n drawEmbassyButton(g, x + s20, y + h - s38, w - s40, s28);\n }\n\n private void drawAITradeSummary(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_TRADE_SUMMARY\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean finalWar = player().viewForEmpire(emp).embassy().finalWar();\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (finalWar)\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC_FINAL\");\n else if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC_RANGE\");\n else {\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n }\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s10;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n EmpireView view = player().viewForEmpire(emp);\n if (view == null)\n return;\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_DIPLOMACY_TRADE_TREATY\");\n int y2 = lines.size() <= 5 ? y0 + h - s65 : y0 + h - s55;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String s2 = text(\"RACES_DIPLOMACY_TRADE_AMT\", view.trade().level());\n int sw2 = g.getFontMetrics().stringWidth(s2);\n drawString(g, s2, x + w - s20 - sw2, y2);\n y2 += s22;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_DIPLOMACY_CURRENT_TRADE\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) view.trade().profit();\n g.setFont(narrowFont(16));\n s2 = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw2 = g.getFontMetrics().stringWidth(s2);\n drawString(g, s2, x + w - s20 - sw2, y2);\n }\n\n private void drawAIForeignRelations(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_FOREIGN_RELATIONS\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_FOREIGN_RANGE\");\n else\n desc = text(\"RACES_DIPLOMACY_FOREIGN_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s10;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n if (outOfRange)\n return;\n int x2 = x + s10;\n int y2 = y1 + s10;\n int w2 = w - s20;\n int listH = y + h - y2 - s20;\n g.setColor(RacesUI.brown);\n g.fillRect(x2, y2, w2, listH);\n relationsListBox.setBounds(x2, y2, w2, listH);\n g.setClip(x2, y2 + s1, w2, listH - s2);\n int y3 = y2 - relationsY;\n int x3 = x2 + s10;\n g.setFont(narrowFont(18));\n g.setColor(SystemPanel.blackText);\n List contacts = emp.contacts();\n Collections.sort(contacts, EmpireView.PLAYER_LIST_ORDER);\n int rowH = s18;\n int fullListH = (contacts.size() * rowH) + s5;\n int rightM = fullListH <= listH ? s10 : s20;\n for (EmpireView contact : contacts) {\n if (contact.inEconomicRange()) {\n y3 += rowH;\n g.setFont(narrowFont(18));\n drawString(g, contact.empire().raceName(), x3, y3);\n g.setFont(narrowFont(15));\n String treaty = contact.embassy().treaty().status(player());\n int sw1 = g.getFontMetrics().stringWidth(treaty);\n int x3b = x2 + w2 - sw1 - rightM;\n drawString(g, treaty, x3b, y3);\n }\n }\n relationsYMax = max(0, fullListH - listH);\n if (relationsYMax == 0)\n relationsScroller.setBounds(0, 0, 0, 0);\n else {\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + relationsYMax));\n int scrollX = x2 + w2 - scrollW - s2;\n int scrollY = (int) (y2 + (float) listH * relationsY / (relationsYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n relationsScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == relationsScroller) {\n Stroke prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n }\n g.setClip(null);\n if ((hoverShape == relationsListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n Stroke prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(relationsListBox);\n g.setStroke(prev);\n }\n }\n\n private void drawEmbassyButton(Graphics2D g, int x, int y, int w, int h) {\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n if (view == null)\n return;\n embassyBox.setBounds(x, y, w, h);\n if (embassyBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x, 0);\n Point2D ptEnd = new Point2D.Float(x + w, 0);\n Color[] colors = { greenEdgeC, greenMidC, greenEdgeC };\n embassyBackground = new LinearGradientPaint(ptStart, ptEnd, dist, colors);\n Color[] colors2 = { brownEdgeC, brownMidC, brownEdgeC };\n embassyDisabledBackground = new LinearGradientPaint(ptStart, ptEnd, dist, colors2);\n }\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n if (view.diplomats())\n g.setPaint(embassyBackground);\n else\n g.setPaint(embassyDisabledBackground);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if ((hoverShape == embassyBox) && view.diplomats())\n c0 = Color.yellow;\n String lbl = view.embassy().diplomatGone() ? text(\"RACES_DIPLOMACY_CONTACT\") : text(\"RACES_DIPLOMACY_AUDIENCE\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n public void openEmbassy() {\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n if (view == null)\n return;\n if (view.embassy().diplomatGone()) {\n view.embassy().reopenEmbassy();\n parent.repaint();\n return;\n }\n if (!view.diplomats())\n return;\n DiplomaticMessage.show(parent.selectedEmpire().viewForEmpire(player()), DialogueManager.DIPLOMACY_MAIN_MENU);\n }\n\n public void openManageDiplomatsPane() {\n softClick();\n manageDiplomatsPane.init();\n enableGlassPane(manageDiplomatsPane);\n return;\n }\n\n public void openManageSpiesPane() {\n softClick();\n manageSpiesPane.init();\n enableGlassPane(manageSpiesPane);\n return;\n }\n\n private boolean increaseSliderValue() {\n int oldValue = player().internalSecurity();\n player().increaseInternalSecurity();\n return oldValue != player().internalSecurity();\n }\n\n private boolean decreaseSliderValue() {\n int oldValue = player().internalSecurity();\n player().decreaseInternalSecurity();\n return oldValue != player().internalSecurity();\n }\n\n @Override\n public void mouseWheelMoved(MouseWheelEvent e) {\n int count = e.getUnitsToScroll();\n if ((hoverShape == incidentListBox) || (hoverShape == incidentScroller)) {\n int prevY = incidentY;\n if (count < 0)\n incidentY = max(0, incidentY - s10);\n else\n incidentY = min(incidentYMax, incidentY + s10);\n if (incidentY != prevY)\n repaint(incidentListBox);\n return;\n } else if (hoverShape == buttonSlider) {\n boolean changed = count < 0 ? increaseSliderValue() : decreaseSliderValue();\n if (changed) {\n setValues();\n repaint();\n }\n } else if ((hoverShape == relationsListBox) || (hoverShape == relationsScroller)) {\n int prevY = relationsY;\n if (count < 0)\n relationsY = max(0, relationsY - s10);\n else\n relationsY = min(relationsYMax, relationsY + s10);\n if (relationsY != prevY)\n repaint(relationsListBox);\n return;\n }\n }\n\n @Override\n public void mouseDragged(MouseEvent e) {\n int x = e.getX();\n int y = e.getY();\n int dY = y - dragY;\n dragY = y;\n if (incidentScroller == hoverShape) {\n if ((y >= incidentListBox.y) || (y <= (incidentListBox.y + incidentListBox.height))) {\n int h = (int) incidentListBox.getHeight();\n int dListY = (int) ((float) dY * (h + incidentYMax) / h);\n if (dY < 0)\n incidentY = max(0, incidentY + dListY);\n else\n incidentY = min(incidentYMax, incidentY + dListY);\n }\n repaint(incidentListBox);\n return;\n } else if (incidentListBox == hoverShape) {\n if (incidentListBox.contains(x, y)) {\n int h = (int) incidentListBox.getHeight();\n int dListY = (int) (-(float) dY * (h + incidentYMax) / h);\n if (dListY < 0)\n incidentY = max(0, incidentY + dListY);\n else\n incidentY = min(incidentYMax, incidentY + dListY);\n }\n repaint(incidentListBox);\n return;\n } else if (relationsScroller == hoverShape) {\n if ((y >= relationsListBox.y) || (y <= (relationsListBox.y + relationsListBox.height))) {\n int h = (int) relationsListBox.getHeight();\n int dListY = (int) ((float) dY * (h + relationsYMax) / h);\n if (dY < 0)\n relationsY = max(0, relationsY + dListY);\n else\n relationsY = min(relationsYMax, relationsY + dListY);\n }\n repaint(relationsListBox);\n return;\n } else if (relationsListBox == hoverShape) {\n if (relationsListBox.contains(x, y)) {\n int h = (int) relationsListBox.getHeight();\n int dListY = (int) (-(float) dY * (h + relationsYMax) / h);\n if (dListY < 0)\n relationsY = max(0, relationsY + dListY);\n else\n relationsY = min(relationsYMax, relationsY + dListY);\n }\n repaint(relationsListBox);\n return;\n }\n }\n\n @Override\n public void mouseMoved(MouseEvent e) {\n int x = e.getX();\n int y = e.getY();\n Shape prevHover = hoverShape;\n hoverShape = null;\n if (buttonIncr.contains(x, y))\n hoverShape = buttonIncr;\n else if (buttonDecr.contains(x, y))\n hoverShape = buttonDecr;\n else if (buttonSlider.contains(x, y))\n hoverShape = buttonSlider;\n else if (embassyBox.contains(x, y))\n hoverShape = embassyBox;\n else if (incidentScroller.contains(x, y))\n hoverShape = incidentScroller;\n else if (incidentListBox.contains(x, y))\n hoverShape = incidentListBox;\n else if (relationsScroller.contains(x, y))\n hoverShape = relationsScroller;\n else if (relationsListBox.contains(x, y))\n hoverShape = relationsListBox;\n else if (manageSpiesBox.contains(x, y))\n hoverShape = manageSpiesBox;\n else if (manageDiplomatsBox.contains(x, y))\n hoverShape = manageDiplomatsBox;\n if (hoverShape != prevHover)\n repaint();\n }\n\n @Override\n public void mouseClicked(MouseEvent e) {\n }\n\n @Override\n public void mousePressed(MouseEvent e) {\n dragY = e.getY();\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n dragY = 0;\n if (e.getButton() > 3)\n return;\n if (hoverShape == null)\n return;\n Empire emp = parent.selectedEmpire();\n if (hoverShape == embassyBox) {\n openEmbassy();\n return;\n } else if (hoverShape == manageSpiesBox) {\n openManageSpiesPane();\n return;\n } else if (hoverShape == manageDiplomatsBox) {\n openManageDiplomatsPane();\n return;\n }\n if (hoverShape == buttonIncr) {\n boolean changed = increaseSliderValue();\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n } else if (hoverShape == buttonDecr) {\n boolean changed = decreaseSliderValue();\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n } else if (hoverShape == buttonSlider) {\n float pct = (float) ((e.getX() - buttonSlider.getMinX()) / buttonSlider.getWidth());\n boolean changed = false;\n if (emp.isPlayer()) {\n int oldSec = emp.internalSecurity();\n emp.securityAllocation(pct);\n changed = oldSec != emp.internalSecurity();\n }\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n }\n }\n\n @Override\n public void mouseEntered(MouseEvent e) {\n }\n\n @Override\n public void mouseExited(MouseEvent e) {\n if (hoverShape != null) {\n hoverShape = null;\n repaint();\n }\n }\n}\n"} {"task_id": "Java_2052", "language": "Java", "task_type": "method_body", "source_file": "java/github/rayfowler/rotp-public/src/rotp/ui/races/RacesDiplomacyUI.java", "mask_start_position": 4182, "mask_end_position": 4189, "canonical_solution": "{\n }", "pre_mask_code": "/*\n * \n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage rotp.ui.races;\n\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.Image;\nimport java.awt.LinearGradientPaint;\nimport java.awt.Polygon;\nimport java.awt.Rectangle;\nimport java.awt.Shape;\nimport java.awt.Stroke;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseListener;\nimport java.awt.event.MouseMotionListener;\nimport java.awt.event.MouseWheelEvent;\nimport java.awt.event.MouseWheelListener;\nimport java.awt.geom.Point2D;\nimport java.awt.geom.RoundRectangle2D;\nimport java.awt.image.BufferedImage;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport rotp.model.empires.DiplomaticTreaty;\nimport rotp.model.empires.Empire;\nimport rotp.model.empires.EmpireView;\nimport rotp.model.empires.TreatyAlliance;\nimport rotp.model.incidents.DiplomaticIncident;\nimport rotp.ui.BasePanel;\nimport rotp.ui.UserPreferences;\nimport rotp.ui.diplomacy.DialogueManager;\nimport rotp.ui.diplomacy.DiplomaticMessage;\nimport rotp.ui.main.MainUI;\nimport rotp.ui.main.SystemPanel;\nimport static rotp.ui.races.RacesIntelligenceUI.sliderC;\n\npublic final class RacesDiplomacyUI extends BasePanel implements MouseListener, MouseMotionListener, MouseWheelListener {\n\n private static final long serialVersionUID = 1L;\n\n public static final String[] relationIds = new String[] { \"RELATIONS_FEUD\", \"RELATIONS_HATE\", \"RELATIONS_DISCORD\", \"RELATIONS_TROUBLED\", \"RELATIONS_TENSE\", \"RELATIONS_RESTLESS\", \"RELATIONS_WARY\", \"RELATIONS_UNEASE\", \"RELATIONS_NEUTRAL\", \"RELATIONS_RELAXED\", \"RELATIONS_AMIABLE\", \"RELATIONS_CALM\", \"RELATIONS_AFFABLE\", \"RELATIONS_PEACEFUL\", \"RELATIONS_FRIENDLY\", \"RELATIONS_UNITY\", \"RELATIONS_HARMONY\" };\n\n private static final Color unselectedC = new Color(112, 85, 68);\n\n private final Color greenEdgeC = new Color(44, 59, 30);\n\n private final Color greenMidC = new Color(70, 93, 48);\n\n private final Color brownEdgeC = new Color(101, 70, 50);\n\n private final Color brownMidC = new Color(161, 111, 78);\n\n private final Color brownDividerC = new Color(136, 115, 96);\n\n private final Color incidentRedC = new Color(112, 0, 0);\n\n private final Color incidentGreenC = new Color(0, 63, 32);\n\n private final RacesUI parent;\n\n private final ManageDiplomatsUI manageDiplomatsPane;\n\n private final ManageSpiesUI manageSpiesPane;\n\n int incidentY, incidentYMax;\n\n int relationsY, relationsYMax;\n\n int dragY;\n\n private LinearGradientPaint incidentTitleBackground;\n\n private LinearGradientPaint backGradient;\n\n private LinearGradientPaint embassyBackground, embassyDisabledBackground;\n\n private final Rectangle embassyBox = new Rectangle();\n\n private final Rectangle incidentListBox = new Rectangle();\n\n private final Rectangle incidentScroller = new Rectangle();\n\n private final Rectangle relationsListBox = new Rectangle();\n\n private final Rectangle relationsScroller = new Rectangle();\n\n private final Rectangle manageDiplomatsBox = new Rectangle();\n\n private final Rectangle manageSpiesBox = new Rectangle();\n\n Polygon buttonIncr = new Polygon();\n\n Polygon buttonDecr = new Polygon();\n\n Rectangle buttonSlider = new Rectangle();\n\n private float internalSecurityCost = 0;\n\n private float externalSpyingCost = 0;\n\n int[] ptX = new int[3];\n\n int[] ptY = new int[3];\n\n private final HashMap incidentMap = new HashMap<>();\n\n private Shape hoverShape;\n\n public RacesDiplomacyUI(RacesUI p) {\n parent = p;\n manageDiplomatsPane = new ManageDiplomatsUI(p);\n manageSpiesPane = new ManageSpiesUI(p);\n initModel();\n }\n\n @Override\n public void drawTexture(Graphics g) ", "post_mask_code": "\n\n @Override\n public String textureName() {\n return TEXTURE_BROWN;\n }\n\n public void init() {\n setValues();\n }\n\n public void changedEmpire() {\n setValues();\n }\n\n private void setValues() {\n incidentY = 0;\n relationsY = 0;\n if (parent.selectedEmpire().isPlayer()) {\n internalSecurityCost = player().empireInternalSecurityCost();\n externalSpyingCost = player().empireExternalSpyingCost();\n }\n }\n\n @Override\n public void paintComponent(Graphics g0) {\n super.paintComponent(g0);\n Graphics2D g = (Graphics2D) g0;\n int w = getWidth();\n int h = getHeight();\n relationsListBox.setBounds(0, 0, 0, 0);\n relationsScroller.setBounds(0, 0, 0, 0);\n manageDiplomatsBox.setBounds(0, 0, 0, 0);\n manageSpiesBox.setBounds(0, 0, 0, 0);\n buttonIncr.reset();\n buttonDecr.reset();\n if (backGradient == null) {\n Point2D start = new Point2D.Float(0, getHeight() / 2);\n Point2D end = new Point2D.Float(0, getHeight());\n float[] dist = { 0.0f, 1.0f };\n Color[] colors = { RacesUI.darkerBrown, RacesUI.gradientBottom };\n backGradient = new LinearGradientPaint(start, end, dist, colors);\n }\n g.setPaint(backGradient);\n g.fillRect(0, h / 2, w, h / 2);\n if (parent.selectedEmpire().isPlayer())\n paintPlayerData(g);\n else\n paintAIData(g);\n }\n\n private void initModel() {\n setBackground(RacesUI.darkerBrown);\n setBorder(newEmptyBorder(5, 5, 5, 5));\n addMouseMotionListener(this);\n addMouseListener(this);\n addMouseWheelListener(this);\n }\n\n private void paintPlayerData(Graphics2D g) {\n Empire emp = parent.selectedEmpire();\n int w = getWidth();\n int h = getHeight();\n int s200 = scaled(200);\n int s210 = scaled(210);\n int s215 = scaled(215);\n int s245 = scaled(245);\n int s260 = scaled(260);\n int s370 = scaled(370);\n int s435 = scaled(435);\n int x0 = s20;\n int x1 = w - scaled(299);\n int w0 = x1 - x0 - s20;\n int w1 = scaled(279);\n drawRaceIconBase(g, emp, s55, s25, s210, s210);\n drawPlayerBaseInfo(g, emp, s260, s80, s370, scaled(130));\n drawPlayerDiplomaticEvents(g, emp, x0, s245, w0, h - s245 - s10);\n drawPlayerDiplomacyBureau(g, emp, x1, s10, w1, s200);\n drawPlayerCounterIntelligenceBureau(g, emp, x1, s215, w1, s215);\n drawPlayerIntelligenceBureau(g, emp, x1, s435, w1, s200);\n if (UserPreferences.texturesInterface())\n drawTexture(g, 0, 0, w, h);\n drawRaceIcon(g, emp, s60, s30, s200, s200);\n drawEmpireName(g, emp, s260, s30, s370, s50);\n }\n\n private void paintAIData(Graphics2D g) {\n Empire emp = parent.selectedEmpire();\n int w = getWidth();\n int h = getHeight();\n int s200 = scaled(200);\n int s135 = scaled(135);\n int s150 = scaled(150);\n int s175 = scaled(175);\n int s210 = scaled(210);\n int s245 = scaled(245);\n int s260 = scaled(260);\n int s295 = scaled(295);\n int s330 = scaled(330);\n int s370 = scaled(370);\n int x0 = s20;\n int x1 = w - scaled(299);\n int w0 = x1 - x0 - s20;\n int w1 = scaled(279);\n drawRaceIconBase(g, emp, s55, s25, s210, s210);\n drawAIBaseInfo(g, emp, s260, s80, s370, scaled(130));\n drawRelationsMeter(g, emp, x0, s245, w0, s40);\n drawAIDiplomaticEvents(g, emp, x0, s295, w0, h - s295 - s10);\n drawAIDiplomacyBureau(g, emp, x1, s10, w1, s135);\n drawAITradeSummary(g, emp, x1, s150, w1, s175);\n drawAIForeignRelations(g, emp, x1, s330, w1, h - s330 - s10);\n if (UserPreferences.texturesInterface())\n drawTexture(g, 0, 0, w, h);\n drawRaceIcon(g, emp, s60, s30, s200, s200);\n drawEmpireName(g, emp, s260, s30, s370, s50);\n }\n\n private void drawRaceIconBase(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n Shape rect = new RoundRectangle2D.Float(x, y, w, h, w / 8, h / 8);\n g.fill(rect);\n }\n\n private void drawRaceIcon(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(Color.black);\n Shape rect = new RoundRectangle2D.Float(x, y, w, h, w / 8, h / 8);\n g.fill(rect);\n BufferedImage backImg = parent.raceIconBackImg();\n g.drawImage(backImg, x, y, null);\n int x1 = x + w / 10;\n int w1 = w * 8 / 10;\n int y1 = y + h / 10;\n int h1 = h * 8 / 10;\n Image img = emp.isPlayer() ? emp.race().flagPact() : player().viewForEmpire(emp).flag();\n int imgH = img.getHeight(null);\n int imgW = img.getWidth(null);\n g.drawImage(img, x1, y1, x1 + w1, y1 + h1, 0, 0, imgW, imgH, null);\n }\n\n private void drawEmpireName(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(SystemPanel.orangeText);\n g.setFont(narrowFont(32));\n drawString(g, emp.name(), x + s10, y + h - s15);\n }\n\n private void drawPlayerBaseInfo(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n int lineH = s30;\n int y1 = y + lineH - s5;\n int y2 = y1 + lineH;\n int y3 = y2 + lineH;\n int y4 = y3 + lineH;\n int x0 = x + s20;\n g.setFont(narrowFont(22));\n Color textC = SystemPanel.whiteText;\n drawShadowedString(g, text(\"RACES_DIPLOMACY_HOMEWORLD\"), 1, x0, y1, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_LEADER\"), 1, x0, y2, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_CURRENT_TRADE\"), 1, x0, y3, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_TOTAL_TRADE\"), 1, x0, y4, SystemPanel.blackText, textC);\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n String s = emp.sv.name(emp.capitalSysId());\n int sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y1);\n s = text(\"TITLE_LEADERNAME\", emp.labels().text(\"_nameTitle\"), emp.leader().name());\n s = emp.replaceTokens(s, \"alien\");\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n int amt = (int) player().totalTradeIncome();\n s = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y3);\n amt = player().totalTradeTreaties();\n s = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y4);\n }\n\n private void drawAIBaseInfo(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n int lineH = s30;\n int y1 = y + lineH - s5;\n int y2 = y1 + lineH;\n int y3 = y2 + lineH;\n int y4 = y3 + lineH;\n int x0 = x + s20;\n g.setFont(narrowFont(22));\n Color textC = SystemPanel.whiteText;\n drawShadowedString(g, text(\"RACES_DIPLOMACY_HOMEWORLD\"), 1, x0, y1, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_LEADER\"), 1, x0, y2, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_CHARACTER\"), 1, x0, y3, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_STATUS\"), 1, x0, y4, SystemPanel.blackText, textC);\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n String s = emp.sv.name(emp.capitalSysId());\n int sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y1);\n s = text(\"TITLE_LEADERNAME\", emp.race().text(\"_nameTitle\"), emp.leader().name());\n s = emp.replaceTokens(s, \"alien\");\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n s = text(\"LEADER_PERSONALITY_FORMAT\", emp.leader().personality(), emp.leader().objective());\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y3);\n EmpireView view = player().viewForEmpire(emp);\n DiplomaticTreaty treaty = view.embassy().treaty();\n boolean isAlly = treaty.isAlliance();\n int starW = s10;\n int offset = isAlly ? (starW * 5) + s5 : 0;\n s = treaty.status(player());\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - offset - sw, y4);\n if (isAlly) {\n TreatyAlliance alliance = (TreatyAlliance) treaty;\n int x1 = x + w - s20 - offset + s5;\n parent.drawAllianceStars(g, x1, y4 - s3, alliance.standing(player()), starW);\n }\n }\n\n private void drawRelationsMeter(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n EmpireView view = player().viewForEmpire(emp);\n if (view == null)\n return;\n int x0 = x + s10;\n int y0 = y + h - s12;\n g.setFont(narrowFont(24));\n String str = text(\"RACES_DIPLOMACY_RELATIONS_METER\");\n this.drawShadowedString(g, str, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n int leftW = g.getFontMetrics().stringWidth(str);\n if (emp.race().masksDiplomacy) {\n g.setFont(narrowFont(15));\n g.setColor(SystemPanel.blackText);\n String str2 = text(\"RACES_DIPLOMACY_RELATIONS_UNKNOWN\");\n str2 = emp.replaceTokens(str2, \"alien\");\n List lines = this.wrappedLines(g, str2, w - s60 - leftW);\n int x1 = x0 + leftW + s40;\n int y1 = lines.size() == 1 ? y0 : y0 - s10;\n for (String line : lines) {\n drawString(g, line, x1, y1);\n y1 += s15;\n }\n return;\n }\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n float relations = view.otherView().embassy().relations();\n // which relation key display to use\n float pctRel = (relations + 100) / 200.0f;\n float sizeRelId = 1.0f / relationIds.length;\n int i = (int) (pctRel / sizeRelId);\n i = bounds(0, i, relationIds.length - 1);\n String rel = text(relationIds[i]);\n int rightW = g.getFontMetrics().stringWidth(rel);\n int x1 = x + w - rightW - s20;\n drawString(g, rel, x1, y0);\n int x2 = x0 + leftW + s30;\n int w2 = x + w - x2 - rightW - s30;\n int y2 = y + s12;\n int h2 = h - s15;\n parent.drawRelationsBar(g, emp, x2, y2, w2, h2, s16, s8);\n }\n\n private void drawPlayerDiplomaticEvents(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n // title area\n int x0 = x;\n int w0 = w;\n int y0 = y;\n int h0 = s30;\n if (incidentTitleBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x0, 0);\n Point2D ptEnd = new Point2D.Float(x0 + w0, 0);\n Color[] yesColors = { brownEdgeC, brownMidC, brownEdgeC };\n incidentTitleBackground = new LinearGradientPaint(ptStart, ptEnd, dist, yesColors);\n }\n g.setPaint(incidentTitleBackground);\n g.fillRect(x0, y0, w0, h0);\n // year or turn\n g.setFont(narrowFont(20));\n int x1 = x0;\n int w1 = s60;\n String year = UserPreferences.displayYear() ? text(\"RACES_DIPLOMACY_EVENT_YEAR\") : text(\"RACES_DIPLOMACY_EVENT_TURN\");\n int sw = g.getFontMetrics().stringWidth(year);\n drawShadowedString(g, year, 1, x0 + (w1 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // race\n g.setFont(narrowFont(20));\n int x2 = x1 + w1;\n int w2 = s100;\n String race = text(\"RACES_DIPLOMACY_EVENT_RACE\");\n sw = g.getFontMetrics().stringWidth(race);\n drawShadowedString(g, race, 1, x2 + (w2 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // scrollboar\n int w5 = s20;\n int x5 = x0 + w0 - w5;\n // effect\n g.setFont(narrowFont(20));\n String effect = text(\"RACES_DIPLOMACY_EVENT_EFFECT\");\n sw = g.getFontMetrics().stringWidth(effect);\n int w4 = s60;\n int x4 = x5 - w4;\n drawShadowedString(g, effect, 1, x4 + (w4 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(22));\n int x3 = x2 + w2;\n int w3 = x4 - x3;\n String title = text(\"RACES_DIPLOMACY_EVENT_TITLE\");\n sw = g.getFontMetrics().stringWidth(title);\n drawShadowedString(g, title, 1, x3 + (w3 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // data area\n g.setColor(RacesUI.darkBrown);\n int y1 = y0 + h0;\n int listH = h - h0;\n g.fillRect(x0, y1, w0, listH);\n g.setClip(x0, y1 + s1, w0, listH - s2);\n // draw vertical divider lines\n Stroke prev = g.getStroke();\n g.setStroke(stroke1);\n g.setColor(brownDividerC);\n g.drawLine(x2, y1, x2, y1 + listH);\n g.drawLine(x3, y1, x3, y1 + listH);\n g.drawLine(x4, y1, x4, y1 + listH);\n g.drawLine(x5, y1, x5, y1 + listH);\n g.setStroke(prev);\n List incidents = new ArrayList<>();\n incidentMap.clear();\n for (EmpireView view : player().contacts()) {\n for (DiplomaticIncident inc : view.otherView().embassy().allIncidents()) {\n if ((inc.currentSeverity() != 0) && inc.triggeredByAction()) {\n incidents.add(inc);\n incidentMap.put(inc, view.empire());\n }\n }\n }\n Collections.sort(incidents, DiplomaticIncident.DATE);\n int y2 = y1 - incidentY;\n int fullListH = 0;\n for (int i = 0; i < incidents.size(); i++) {\n DiplomaticIncident inc = incidents.get(i);\n int incidentH = drawPlayerIncident(g, inc, x0, y2, w0, w1, w2, w3, w4);\n fullListH += incidentH;\n y2 += incidentH;\n }\n incidentYMax = max(0, fullListH - listH);\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + incidentYMax));\n int scrollX = x + w - scrollW - s4;\n int scrollY = (int) (y1 + (float) listH * incidentY / (incidentYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n incidentScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == incidentScroller) {\n prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n g.setClip(null);\n incidentListBox.setBounds(x0, y1, w0, listH);\n if ((hoverShape == incidentListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(incidentListBox);\n g.setStroke(prev);\n }\n }\n\n private int drawPlayerIncident(Graphics g, DiplomaticIncident inc, int x, int y, int w, int w1, int w2, int w3, int w4) {\n String title = inc.title() + \":\";\n String sev = fmt(inc.currentSeverity(), 1);\n String desc = inc.description();\n g.setFont(narrowFont(18));\n int indent = g.getFontMetrics().stringWidth(title) + s5;\n g.setFont(narrowFont(15));\n List descLines = wrappedLines(g, desc, w3 - s15, indent);\n int h0 = s7 + (s22 * descLines.size());\n // title\n int x1 = x;\n int x2 = x1 + w1;\n int x3 = x2 + w2;\n int x4 = x3 + w3;\n int y1 = y + s8;\n // year or turn\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n String year = UserPreferences.displayYear() ? str(inc.dateOccurred()) : str(inc.turnOccurred());\n int sw = g.getFontMetrics().stringWidth(year);\n int x0 = x1 + (w1 - sw) / 2;\n int y0 = y + s25;\n drawString(g, year, x0, y0);\n // race\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n Empire otherEmpire = incidentMap.get(inc);\n String race = otherEmpire.raceName();\n sw = g.getFontMetrics().stringWidth(race);\n x0 = x2 + (w2 - sw) / 2;\n y0 = y + s25;\n drawString(g, race, x0, y0);\n boolean firstLine = true;\n g.setFont(narrowFont(18));\n for (String line : descLines) {\n y1 += s17;\n g.setColor(Color.black);\n if (firstLine) {\n drawString(g, title, x3 + s10, y1);\n g.setFont(narrowFont(15));\n drawString(g, line, x3 + s10 + indent, y1);\n firstLine = false;\n } else\n drawString(g, line, x3 + s10, y1);\n }\n // severity\n if (!otherEmpire.race().masksDiplomacy) {\n g.setFont(narrowFont(18));\n sw = g.getFontMetrics().stringWidth(sev);\n x0 = x4 + (w4 - sw) / 2;\n if (inc.currentSeverity() < 0)\n g.setColor(incidentRedC);\n else\n g.setColor(incidentGreenC);\n drawString(g, sev, x0, y0);\n }\n g.setColor(brownDividerC);\n g.drawLine(x1, y1 + s12, x + w - s20, y1 + s12);\n return h0;\n }\n\n private void drawPlayerDiplomacyBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n List views = player().contacts();\n int recalls = 0;\n for (EmpireView v : views) {\n if (v.embassy().diplomatGone())\n recalls++;\n }\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_BUREAU\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_DIPLOMACY_BUREAU_DESC1\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_DIPLOMACY_KNOWN_EMPIRES\");\n int y2 = y0 + s85;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String str2 = str(views.size());\n int sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_DIPLOMACY_RECALLED_DIPLOMAT\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) 0;\n g.setFont(narrowFont(16));\n str2 = str(recalls);\n sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n drawManageDiplomatsButton(g, x + s20, y + h - s45, w - s40, s25);\n }\n\n private void drawPlayerCounterIntelligenceBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_COUNTER_BUREAU\");\n int fontSize = scaledFont(g, title, w - s20, 24, 20);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_DIPLOMACY_COUNTER_DESC\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_INTEL_SECURITY_BONUS\");\n int y2 = y0 + s70;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n int amt = (int) (100 * player().totalInternalSecurityPct());\n String s = amt == 0 ? text(\"RACES_INTEL_SECURITY_BONUS_NONE\") : text(\"RACES_INTEL_SECURITY_BONUS_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_INTEL_TOTAL_SPENDING\");\n drawString(g, spending, x + s20, y2);\n g.setFont(narrowFont(16));\n amt = (int) internalSecurityCost;\n s = text(\"RACES_INTEL_SPENDING_ANNUAL\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n g.setFont(narrowFont(15));\n desc = text(\"RACES_DIPLOMACY_COUNTER_DESC2\");\n lines = wrappedLines(g, desc, w - s30);\n int y3 = y + h - s20 - (s16 * 3);\n for (String line : lines) {\n drawString(g, line, x + s20, y3);\n y3 += s16;\n }\n g.setFont(narrowFont(16));\n int y4 = y + h - s20;\n String taxStr = text(\"RACES_INTEL_SECURITY_TAX\");\n drawString(g, taxStr, x + s20, y4);\n int sw4 = g.getFontMetrics().stringWidth(taxStr);\n // draw string on right for pct\n String cost = text(\"RACES_INTEL_PERCENT_AMT\", (int) (player().internalSecurityCostPct() * 100));\n sw = g.getFontMetrics().stringWidth(cost);\n drawString(g, cost, x + w - s20 - sw, y4);\n // need maxwidth so slider doesn't move as cost pct changes\n String maxWidthStr = text(\"RACES_INTEL_PERCENT_AMT\", 10);\n sw = g.getFontMetrics().stringWidth(maxWidthStr);\n int sliderW = w - sw - sw4 - s80;\n int sliderH = s16;\n drawSecuritySliderBar(g, x + s20 + sw4, y4 - sliderH + s3, sliderW, sliderH);\n }\n\n private void drawSecuritySliderBar(Graphics2D g, int x, int y, int w, int h) {\n // draw spending bar\n // height of bar\n int h1 = h;\n // width of bar\n int w1 = w;\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n float pct = view == null ? player().internalSecurityPct() : view.spies().allocationPct();\n // width of spending\n int w1a = (int) (pct * w1);\n int y1 = y + ((h - h1) / 2);\n int x1 = x + s20;\n g.setColor(Color.black);\n g.fillRect(x1, y1, w1, h1);\n g.setColor(sliderC);\n g.fillRect(x1, y1, w1a, h1);\n buttonSlider.setBounds(x1, y1, w1, h1);\n if (hoverShape == buttonSlider) {\n g.setColor(Color.yellow);\n Stroke prev = g.getStroke();\n g.setStroke(stroke2);\n g.drawRect(x1, y1, w1, h1);\n g.setStroke(prev);\n }\n int sz = h1 / 2;\n // draw left/decr button\n ptX[0] = x1 - s3 - sz;\n ptX[1] = ptX[0] + sz;\n ptX[2] = ptX[0] + sz;\n ptY[0] = y + (h / 2);\n ptY[1] = ptY[0] - sz;\n ptY[2] = ptY[0] + sz;\n Color buttonC = hoverShape == buttonDecr ? SystemPanel.yellowText : Color.black;\n buttonDecr.reset();\n for (int i = 0; i < ptX.length; i++) buttonDecr.addPoint(ptX[i], ptY[i]);\n drawShadedPolygon(g, ptX, ptY, buttonC, s1, -s1);\n // draw right/incr button\n ptX[0] = x1 + w1 + sz + s3;\n ptX[1] = ptX[0] - sz;\n ptX[2] = ptX[0] - sz;\n ptY[0] = y + (h / 2);\n ptY[1] = ptY[0] - sz;\n ptY[2] = ptY[0] + sz;\n buttonIncr.reset();\n for (int i = 0; i < ptX.length; i++) buttonIncr.addPoint(ptX[i], ptY[i]);\n buttonC = hoverShape == buttonIncr ? SystemPanel.yellowText : Color.black;\n drawShadedPolygon(g, ptX, ptY, buttonC, s1, -s1);\n if (!parent.selectedEmpire().isPlayer()) {\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(15));\n String spyCost = text(\"RACES_INTEL_SPENDING_ANNUAL\", (int) externalSpyingCost);\n int sw1 = g.getFontMetrics().stringWidth(spyCost);\n int xa = buttonSlider.x + ((buttonSlider.width - sw1) / 2);\n int ya = buttonSlider.y + buttonSlider.height - s4;\n drawString(g, spyCost, xa, ya);\n }\n }\n\n private void drawPlayerIntelligenceBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_INTEL_BUREAU_TITLE\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_INTEL_BUREAU_DESC\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_INTEL_BUREAU_SPIES\");\n int y2 = y + h - s85;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String str2 = str(player().totalActiveSpies());\n int sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_INTEL_BUREAU_SPENDING\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) externalSpyingCost;\n g.setFont(narrowFont(16));\n str2 = amt == 0 ? text(\"RACES_INTEL_SECURITY_BONUS_NONE\") : text(\"RACES_INTEL_SPENDING_ANNUAL\", str(amt));\n sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n drawManageSpiesButton(g, x + s20, y2, w - s40, s25);\n }\n\n private void drawManageDiplomatsButton(Graphics2D g, int x, int y, int w, int h) {\n manageDiplomatsBox.setBounds(x, y, w, h);\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n g.setColor(unselectedC);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if (hoverShape == manageDiplomatsBox)\n c0 = Color.yellow;\n String lbl = text(\"RACES_DIPLOMACY_MANAGE_DIPLOMATS\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n private void drawManageSpiesButton(Graphics2D g, int x, int y, int w, int h) {\n manageSpiesBox.setBounds(x, y, w, h);\n g.setColor(Color.blue);\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n g.setColor(unselectedC);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if (hoverShape == manageSpiesBox)\n c0 = Color.yellow;\n String lbl = text(\"RACES_INTEL_BUREAU_MANAGE\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n private void drawAIDiplomaticEvents(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n // title area\n int x0 = x;\n int w0 = w;\n int y0 = y;\n int h0 = s30;\n if (incidentTitleBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x0, 0);\n Point2D ptEnd = new Point2D.Float(x0 + w0, 0);\n Color[] yesColors = { brownEdgeC, brownMidC, brownEdgeC };\n incidentTitleBackground = new LinearGradientPaint(ptStart, ptEnd, dist, yesColors);\n }\n g.setPaint(incidentTitleBackground);\n g.fillRect(x0, y0, w0, h0);\n // title\n g.setFont(narrowFont(20));\n String year = UserPreferences.displayYear() ? text(\"RACES_DIPLOMACY_EVENT_YEAR\") : text(\"RACES_DIPLOMACY_EVENT_TURN\");\n drawShadowedString(g, year, 1, x0 + s10, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(22));\n String title = text(\"RACES_DIPLOMACY_EVENT_TITLE\");\n int sw = g.getFontMetrics().stringWidth(title);\n drawShadowedString(g, title, 1, x0 + (w0 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(20));\n String effect = text(\"RACES_DIPLOMACY_EVENT_EFFECT\");\n int sw2 = g.getFontMetrics().stringWidth(effect);\n drawShadowedString(g, effect, 1, x0 + w0 - sw2 - s30, y0 + s23, Color.black, SystemPanel.whiteText);\n // data area\n g.setColor(RacesUI.darkBrown);\n int y1 = y0 + h0;\n int x1 = x0;\n int w1 = w0;\n int listH = h - h0;\n g.fillRect(x1, y1, w1, listH);\n g.setClip(x1, y1 + s1, w1, listH - s2);\n // draw vertical divider lines\n int x1a = x1 + s60;\n int x1b = x1 + w1 - s80;\n int x1c = x1 + w1 - s20;\n Stroke prev = g.getStroke();\n g.setStroke(stroke1);\n g.setColor(brownDividerC);\n g.drawLine(x1a, y1, x1a, y1 + listH);\n g.drawLine(x1b, y1, x1b, y1 + listH);\n g.drawLine(x1c, y1, x1c, y1 + listH);\n g.setStroke(prev);\n List incidents = new ArrayList<>();\n for (DiplomaticIncident inc : parent.selectedView().otherView().embassy().allIncidents()) {\n if (inc.currentSeverity() != 0)\n incidents.add(inc);\n }\n Collections.sort(incidents, DiplomaticIncident.DATE);\n int y2 = y1 - incidentY;\n int fullListH = 0;\n for (int i = 0; i < incidents.size(); i++) {\n DiplomaticIncident inc = incidents.get(i);\n int incidentH = drawAIIncident(g, inc, x1, y2, w1, s60, s80);\n fullListH += incidentH;\n y2 += incidentH;\n }\n incidentYMax = max(0, fullListH - listH);\n if (incidentYMax == 0)\n incidentScroller.setBounds(0, 0, 0, 0);\n else {\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + incidentYMax));\n int scrollX = x1 + w1 - scrollW - s2;\n int scrollY = (int) (y1 + (float) listH * incidentY / (incidentYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n incidentScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == incidentScroller) {\n prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n }\n g.setClip(null);\n incidentListBox.setBounds(x1, y1, w1, listH);\n if ((hoverShape == incidentListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(incidentListBox);\n g.setStroke(prev);\n }\n }\n\n private int drawAIIncident(Graphics g, DiplomaticIncident inc, int x, int y, int w, int leftM, int rightM) {\n String title = inc.title() + \":\";\n String sev = fmt(inc.currentSeverity(), 1);\n String desc = inc.description();\n g.setFont(narrowFont(18));\n int indent = g.getFontMetrics().stringWidth(title) + s5;\n g.setFont(narrowFont(15));\n List descLines = wrappedLines(g, desc, w - s20 - leftM - rightM, indent);\n int h0 = s7 + (s22 * descLines.size());\n // title\n int x1 = x + leftM + s10;\n int y1 = y + s8;\n g.setFont(narrowFont(22));\n g.setColor(Color.black);\n // description lines\n boolean firstLine = true;\n g.setFont(narrowFont(18));\n for (String line : descLines) {\n y1 += s17;\n g.setColor(Color.black);\n if (firstLine) {\n drawString(g, title, x1, y1);\n g.setFont(narrowFont(15));\n drawString(g, line, x1 + indent, y1);\n firstLine = false;\n } else\n drawString(g, line, x1, y1);\n }\n // year\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n String year = UserPreferences.displayYear() ? str(inc.dateOccurred()) : str(inc.turnOccurred());\n int sw0 = g.getFontMetrics().stringWidth(year);\n int x0 = x + (leftM - sw0) / 2;\n int y0 = y + s25;\n drawString(g, year, x0, y0);\n // severity\n int x2 = x + w - rightM;\n int w2 = s60;\n if (!parent.selectedEmpire().race().masksDiplomacy) {\n g.setFont(narrowFont(18));\n int sw = g.getFontMetrics().stringWidth(sev);\n int x2a = x2 + (w2 - sw) / 2;\n if (inc.currentSeverity() < 0)\n g.setColor(incidentRedC);\n else\n g.setColor(incidentGreenC);\n drawString(g, sev, x2a, y0);\n }\n g.setColor(brownDividerC);\n g.drawLine(x, y1 + s8, x + w - s20, y1 + s8);\n return h0;\n }\n\n private void drawAIDiplomacyBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_BUREAU\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean finalWar = player().viewForEmpire(emp).embassy().finalWar();\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (finalWar)\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC_FINAL\");\n else if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC_RANGE\");\n else {\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n }\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s7;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n embassyBox.setBounds(0, 0, 0, 0);\n if (!finalWar && !outOfRange)\n drawEmbassyButton(g, x + s20, y + h - s38, w - s40, s28);\n }\n\n private void drawAITradeSummary(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_TRADE_SUMMARY\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean finalWar = player().viewForEmpire(emp).embassy().finalWar();\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (finalWar)\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC_FINAL\");\n else if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC_RANGE\");\n else {\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n }\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s10;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n EmpireView view = player().viewForEmpire(emp);\n if (view == null)\n return;\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_DIPLOMACY_TRADE_TREATY\");\n int y2 = lines.size() <= 5 ? y0 + h - s65 : y0 + h - s55;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String s2 = text(\"RACES_DIPLOMACY_TRADE_AMT\", view.trade().level());\n int sw2 = g.getFontMetrics().stringWidth(s2);\n drawString(g, s2, x + w - s20 - sw2, y2);\n y2 += s22;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_DIPLOMACY_CURRENT_TRADE\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) view.trade().profit();\n g.setFont(narrowFont(16));\n s2 = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw2 = g.getFontMetrics().stringWidth(s2);\n drawString(g, s2, x + w - s20 - sw2, y2);\n }\n\n private void drawAIForeignRelations(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_FOREIGN_RELATIONS\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_FOREIGN_RANGE\");\n else\n desc = text(\"RACES_DIPLOMACY_FOREIGN_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s10;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n if (outOfRange)\n return;\n int x2 = x + s10;\n int y2 = y1 + s10;\n int w2 = w - s20;\n int listH = y + h - y2 - s20;\n g.setColor(RacesUI.brown);\n g.fillRect(x2, y2, w2, listH);\n relationsListBox.setBounds(x2, y2, w2, listH);\n g.setClip(x2, y2 + s1, w2, listH - s2);\n int y3 = y2 - relationsY;\n int x3 = x2 + s10;\n g.setFont(narrowFont(18));\n g.setColor(SystemPanel.blackText);\n List contacts = emp.contacts();\n Collections.sort(contacts, EmpireView.PLAYER_LIST_ORDER);\n int rowH = s18;\n int fullListH = (contacts.size() * rowH) + s5;\n int rightM = fullListH <= listH ? s10 : s20;\n for (EmpireView contact : contacts) {\n if (contact.inEconomicRange()) {\n y3 += rowH;\n g.setFont(narrowFont(18));\n drawString(g, contact.empire().raceName(), x3, y3);\n g.setFont(narrowFont(15));\n String treaty = contact.embassy().treaty().status(player());\n int sw1 = g.getFontMetrics().stringWidth(treaty);\n int x3b = x2 + w2 - sw1 - rightM;\n drawString(g, treaty, x3b, y3);\n }\n }\n relationsYMax = max(0, fullListH - listH);\n if (relationsYMax == 0)\n relationsScroller.setBounds(0, 0, 0, 0);\n else {\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + relationsYMax));\n int scrollX = x2 + w2 - scrollW - s2;\n int scrollY = (int) (y2 + (float) listH * relationsY / (relationsYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n relationsScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == relationsScroller) {\n Stroke prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n }\n g.setClip(null);\n if ((hoverShape == relationsListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n Stroke prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(relationsListBox);\n g.setStroke(prev);\n }\n }\n\n private void drawEmbassyButton(Graphics2D g, int x, int y, int w, int h) {\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n if (view == null)\n return;\n embassyBox.setBounds(x, y, w, h);\n if (embassyBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x, 0);\n Point2D ptEnd = new Point2D.Float(x + w, 0);\n Color[] colors = { greenEdgeC, greenMidC, greenEdgeC };\n embassyBackground = new LinearGradientPaint(ptStart, ptEnd, dist, colors);\n Color[] colors2 = { brownEdgeC, brownMidC, brownEdgeC };\n embassyDisabledBackground = new LinearGradientPaint(ptStart, ptEnd, dist, colors2);\n }\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n if (view.diplomats())\n g.setPaint(embassyBackground);\n else\n g.setPaint(embassyDisabledBackground);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if ((hoverShape == embassyBox) && view.diplomats())\n c0 = Color.yellow;\n String lbl = view.embassy().diplomatGone() ? text(\"RACES_DIPLOMACY_CONTACT\") : text(\"RACES_DIPLOMACY_AUDIENCE\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n public void openEmbassy() {\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n if (view == null)\n return;\n if (view.embassy().diplomatGone()) {\n view.embassy().reopenEmbassy();\n parent.repaint();\n return;\n }\n if (!view.diplomats())\n return;\n DiplomaticMessage.show(parent.selectedEmpire().viewForEmpire(player()), DialogueManager.DIPLOMACY_MAIN_MENU);\n }\n\n public void openManageDiplomatsPane() {\n softClick();\n manageDiplomatsPane.init();\n enableGlassPane(manageDiplomatsPane);\n return;\n }\n\n public void openManageSpiesPane() {\n softClick();\n manageSpiesPane.init();\n enableGlassPane(manageSpiesPane);\n return;\n }\n\n private boolean increaseSliderValue() {\n int oldValue = player().internalSecurity();\n player().increaseInternalSecurity();\n return oldValue != player().internalSecurity();\n }\n\n private boolean decreaseSliderValue() {\n int oldValue = player().internalSecurity();\n player().decreaseInternalSecurity();\n return oldValue != player().internalSecurity();\n }\n\n @Override\n public void mouseWheelMoved(MouseWheelEvent e) {\n int count = e.getUnitsToScroll();\n if ((hoverShape == incidentListBox) || (hoverShape == incidentScroller)) {\n int prevY = incidentY;\n if (count < 0)\n incidentY = max(0, incidentY - s10);\n else\n incidentY = min(incidentYMax, incidentY + s10);\n if (incidentY != prevY)\n repaint(incidentListBox);\n return;\n } else if (hoverShape == buttonSlider) {\n boolean changed = count < 0 ? increaseSliderValue() : decreaseSliderValue();\n if (changed) {\n setValues();\n repaint();\n }\n } else if ((hoverShape == relationsListBox) || (hoverShape == relationsScroller)) {\n int prevY = relationsY;\n if (count < 0)\n relationsY = max(0, relationsY - s10);\n else\n relationsY = min(relationsYMax, relationsY + s10);\n if (relationsY != prevY)\n repaint(relationsListBox);\n return;\n }\n }\n\n @Override\n public void mouseDragged(MouseEvent e) {\n int x = e.getX();\n int y = e.getY();\n int dY = y - dragY;\n dragY = y;\n if (incidentScroller == hoverShape) {\n if ((y >= incidentListBox.y) || (y <= (incidentListBox.y + incidentListBox.height))) {\n int h = (int) incidentListBox.getHeight();\n int dListY = (int) ((float) dY * (h + incidentYMax) / h);\n if (dY < 0)\n incidentY = max(0, incidentY + dListY);\n else\n incidentY = min(incidentYMax, incidentY + dListY);\n }\n repaint(incidentListBox);\n return;\n } else if (incidentListBox == hoverShape) {\n if (incidentListBox.contains(x, y)) {\n int h = (int) incidentListBox.getHeight();\n int dListY = (int) (-(float) dY * (h + incidentYMax) / h);\n if (dListY < 0)\n incidentY = max(0, incidentY + dListY);\n else\n incidentY = min(incidentYMax, incidentY + dListY);\n }\n repaint(incidentListBox);\n return;\n } else if (relationsScroller == hoverShape) {\n if ((y >= relationsListBox.y) || (y <= (relationsListBox.y + relationsListBox.height))) {\n int h = (int) relationsListBox.getHeight();\n int dListY = (int) ((float) dY * (h + relationsYMax) / h);\n if (dY < 0)\n relationsY = max(0, relationsY + dListY);\n else\n relationsY = min(relationsYMax, relationsY + dListY);\n }\n repaint(relationsListBox);\n return;\n } else if (relationsListBox == hoverShape) {\n if (relationsListBox.contains(x, y)) {\n int h = (int) relationsListBox.getHeight();\n int dListY = (int) (-(float) dY * (h + relationsYMax) / h);\n if (dListY < 0)\n relationsY = max(0, relationsY + dListY);\n else\n relationsY = min(relationsYMax, relationsY + dListY);\n }\n repaint(relationsListBox);\n return;\n }\n }\n\n @Override\n public void mouseMoved(MouseEvent e) {\n int x = e.getX();\n int y = e.getY();\n Shape prevHover = hoverShape;\n hoverShape = null;\n if (buttonIncr.contains(x, y))\n hoverShape = buttonIncr;\n else if (buttonDecr.contains(x, y))\n hoverShape = buttonDecr;\n else if (buttonSlider.contains(x, y))\n hoverShape = buttonSlider;\n else if (embassyBox.contains(x, y))\n hoverShape = embassyBox;\n else if (incidentScroller.contains(x, y))\n hoverShape = incidentScroller;\n else if (incidentListBox.contains(x, y))\n hoverShape = incidentListBox;\n else if (relationsScroller.contains(x, y))\n hoverShape = relationsScroller;\n else if (relationsListBox.contains(x, y))\n hoverShape = relationsListBox;\n else if (manageSpiesBox.contains(x, y))\n hoverShape = manageSpiesBox;\n else if (manageDiplomatsBox.contains(x, y))\n hoverShape = manageDiplomatsBox;\n if (hoverShape != prevHover)\n repaint();\n }\n\n @Override\n public void mouseClicked(MouseEvent e) {\n }\n\n @Override\n public void mousePressed(MouseEvent e) {\n dragY = e.getY();\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n dragY = 0;\n if (e.getButton() > 3)\n return;\n if (hoverShape == null)\n return;\n Empire emp = parent.selectedEmpire();\n if (hoverShape == embassyBox) {\n openEmbassy();\n return;\n } else if (hoverShape == manageSpiesBox) {\n openManageSpiesPane();\n return;\n } else if (hoverShape == manageDiplomatsBox) {\n openManageDiplomatsPane();\n return;\n }\n if (hoverShape == buttonIncr) {\n boolean changed = increaseSliderValue();\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n } else if (hoverShape == buttonDecr) {\n boolean changed = decreaseSliderValue();\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n } else if (hoverShape == buttonSlider) {\n float pct = (float) ((e.getX() - buttonSlider.getMinX()) / buttonSlider.getWidth());\n boolean changed = false;\n if (emp.isPlayer()) {\n int oldSec = emp.internalSecurity();\n emp.securityAllocation(pct);\n changed = oldSec != emp.internalSecurity();\n }\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n }\n }\n\n @Override\n public void mouseEntered(MouseEvent e) {\n }\n\n @Override\n public void mouseExited(MouseEvent e) {\n if (hoverShape != null) {\n hoverShape = null;\n repaint();\n }\n }\n}\n"} {"task_id": "Java_2053", "language": "Java", "task_type": "single_line", "source_file": "java/github/rayfowler/rotp-public/src/rotp/ui/races/RacesDiplomacyUI.java", "mask_start_position": 52740, "mask_end_position": 52750, "canonical_solution": " e.getX();", "pre_mask_code": "/*\n * \n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage rotp.ui.races;\n\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.Image;\nimport java.awt.LinearGradientPaint;\nimport java.awt.Polygon;\nimport java.awt.Rectangle;\nimport java.awt.Shape;\nimport java.awt.Stroke;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseListener;\nimport java.awt.event.MouseMotionListener;\nimport java.awt.event.MouseWheelEvent;\nimport java.awt.event.MouseWheelListener;\nimport java.awt.geom.Point2D;\nimport java.awt.geom.RoundRectangle2D;\nimport java.awt.image.BufferedImage;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport rotp.model.empires.DiplomaticTreaty;\nimport rotp.model.empires.Empire;\nimport rotp.model.empires.EmpireView;\nimport rotp.model.empires.TreatyAlliance;\nimport rotp.model.incidents.DiplomaticIncident;\nimport rotp.ui.BasePanel;\nimport rotp.ui.UserPreferences;\nimport rotp.ui.diplomacy.DialogueManager;\nimport rotp.ui.diplomacy.DiplomaticMessage;\nimport rotp.ui.main.MainUI;\nimport rotp.ui.main.SystemPanel;\nimport static rotp.ui.races.RacesIntelligenceUI.sliderC;\n\npublic final class RacesDiplomacyUI extends BasePanel implements MouseListener, MouseMotionListener, MouseWheelListener {\n\n private static final long serialVersionUID = 1L;\n\n public static final String[] relationIds = new String[] { \"RELATIONS_FEUD\", \"RELATIONS_HATE\", \"RELATIONS_DISCORD\", \"RELATIONS_TROUBLED\", \"RELATIONS_TENSE\", \"RELATIONS_RESTLESS\", \"RELATIONS_WARY\", \"RELATIONS_UNEASE\", \"RELATIONS_NEUTRAL\", \"RELATIONS_RELAXED\", \"RELATIONS_AMIABLE\", \"RELATIONS_CALM\", \"RELATIONS_AFFABLE\", \"RELATIONS_PEACEFUL\", \"RELATIONS_FRIENDLY\", \"RELATIONS_UNITY\", \"RELATIONS_HARMONY\" };\n\n private static final Color unselectedC = new Color(112, 85, 68);\n\n private final Color greenEdgeC = new Color(44, 59, 30);\n\n private final Color greenMidC = new Color(70, 93, 48);\n\n private final Color brownEdgeC = new Color(101, 70, 50);\n\n private final Color brownMidC = new Color(161, 111, 78);\n\n private final Color brownDividerC = new Color(136, 115, 96);\n\n private final Color incidentRedC = new Color(112, 0, 0);\n\n private final Color incidentGreenC = new Color(0, 63, 32);\n\n private final RacesUI parent;\n\n private final ManageDiplomatsUI manageDiplomatsPane;\n\n private final ManageSpiesUI manageSpiesPane;\n\n int incidentY, incidentYMax;\n\n int relationsY, relationsYMax;\n\n int dragY;\n\n private LinearGradientPaint incidentTitleBackground;\n\n private LinearGradientPaint backGradient;\n\n private LinearGradientPaint embassyBackground, embassyDisabledBackground;\n\n private final Rectangle embassyBox = new Rectangle();\n\n private final Rectangle incidentListBox = new Rectangle();\n\n private final Rectangle incidentScroller = new Rectangle();\n\n private final Rectangle relationsListBox = new Rectangle();\n\n private final Rectangle relationsScroller = new Rectangle();\n\n private final Rectangle manageDiplomatsBox = new Rectangle();\n\n private final Rectangle manageSpiesBox = new Rectangle();\n\n Polygon buttonIncr = new Polygon();\n\n Polygon buttonDecr = new Polygon();\n\n Rectangle buttonSlider = new Rectangle();\n\n private float internalSecurityCost = 0;\n\n private float externalSpyingCost = 0;\n\n int[] ptX = new int[3];\n\n int[] ptY = new int[3];\n\n private final HashMap incidentMap = new HashMap<>();\n\n private Shape hoverShape;\n\n public RacesDiplomacyUI(RacesUI p) {\n parent = p;\n manageDiplomatsPane = new ManageDiplomatsUI(p);\n manageSpiesPane = new ManageSpiesUI(p);\n initModel();\n }\n\n @Override\n public void drawTexture(Graphics g) {\n }\n\n @Override\n public String textureName() {\n return TEXTURE_BROWN;\n }\n\n public void init() {\n setValues();\n }\n\n public void changedEmpire() {\n setValues();\n }\n\n private void setValues() {\n incidentY = 0;\n relationsY = 0;\n if (parent.selectedEmpire().isPlayer()) {\n internalSecurityCost = player().empireInternalSecurityCost();\n externalSpyingCost = player().empireExternalSpyingCost();\n }\n }\n\n @Override\n public void paintComponent(Graphics g0) {\n super.paintComponent(g0);\n Graphics2D g = (Graphics2D) g0;\n int w = getWidth();\n int h = getHeight();\n relationsListBox.setBounds(0, 0, 0, 0);\n relationsScroller.setBounds(0, 0, 0, 0);\n manageDiplomatsBox.setBounds(0, 0, 0, 0);\n manageSpiesBox.setBounds(0, 0, 0, 0);\n buttonIncr.reset();\n buttonDecr.reset();\n if (backGradient == null) {\n Point2D start = new Point2D.Float(0, getHeight() / 2);\n Point2D end = new Point2D.Float(0, getHeight());\n float[] dist = { 0.0f, 1.0f };\n Color[] colors = { RacesUI.darkerBrown, RacesUI.gradientBottom };\n backGradient = new LinearGradientPaint(start, end, dist, colors);\n }\n g.setPaint(backGradient);\n g.fillRect(0, h / 2, w, h / 2);\n if (parent.selectedEmpire().isPlayer())\n paintPlayerData(g);\n else\n paintAIData(g);\n }\n\n private void initModel() {\n setBackground(RacesUI.darkerBrown);\n setBorder(newEmptyBorder(5, 5, 5, 5));\n addMouseMotionListener(this);\n addMouseListener(this);\n addMouseWheelListener(this);\n }\n\n private void paintPlayerData(Graphics2D g) {\n Empire emp = parent.selectedEmpire();\n int w = getWidth();\n int h = getHeight();\n int s200 = scaled(200);\n int s210 = scaled(210);\n int s215 = scaled(215);\n int s245 = scaled(245);\n int s260 = scaled(260);\n int s370 = scaled(370);\n int s435 = scaled(435);\n int x0 = s20;\n int x1 = w - scaled(299);\n int w0 = x1 - x0 - s20;\n int w1 = scaled(279);\n drawRaceIconBase(g, emp, s55, s25, s210, s210);\n drawPlayerBaseInfo(g, emp, s260, s80, s370, scaled(130));\n drawPlayerDiplomaticEvents(g, emp, x0, s245, w0, h - s245 - s10);\n drawPlayerDiplomacyBureau(g, emp, x1, s10, w1, s200);\n drawPlayerCounterIntelligenceBureau(g, emp, x1, s215, w1, s215);\n drawPlayerIntelligenceBureau(g, emp, x1, s435, w1, s200);\n if (UserPreferences.texturesInterface())\n drawTexture(g, 0, 0, w, h);\n drawRaceIcon(g, emp, s60, s30, s200, s200);\n drawEmpireName(g, emp, s260, s30, s370, s50);\n }\n\n private void paintAIData(Graphics2D g) {\n Empire emp = parent.selectedEmpire();\n int w = getWidth();\n int h = getHeight();\n int s200 = scaled(200);\n int s135 = scaled(135);\n int s150 = scaled(150);\n int s175 = scaled(175);\n int s210 = scaled(210);\n int s245 = scaled(245);\n int s260 = scaled(260);\n int s295 = scaled(295);\n int s330 = scaled(330);\n int s370 = scaled(370);\n int x0 = s20;\n int x1 = w - scaled(299);\n int w0 = x1 - x0 - s20;\n int w1 = scaled(279);\n drawRaceIconBase(g, emp, s55, s25, s210, s210);\n drawAIBaseInfo(g, emp, s260, s80, s370, scaled(130));\n drawRelationsMeter(g, emp, x0, s245, w0, s40);\n drawAIDiplomaticEvents(g, emp, x0, s295, w0, h - s295 - s10);\n drawAIDiplomacyBureau(g, emp, x1, s10, w1, s135);\n drawAITradeSummary(g, emp, x1, s150, w1, s175);\n drawAIForeignRelations(g, emp, x1, s330, w1, h - s330 - s10);\n if (UserPreferences.texturesInterface())\n drawTexture(g, 0, 0, w, h);\n drawRaceIcon(g, emp, s60, s30, s200, s200);\n drawEmpireName(g, emp, s260, s30, s370, s50);\n }\n\n private void drawRaceIconBase(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n Shape rect = new RoundRectangle2D.Float(x, y, w, h, w / 8, h / 8);\n g.fill(rect);\n }\n\n private void drawRaceIcon(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(Color.black);\n Shape rect = new RoundRectangle2D.Float(x, y, w, h, w / 8, h / 8);\n g.fill(rect);\n BufferedImage backImg = parent.raceIconBackImg();\n g.drawImage(backImg, x, y, null);\n int x1 = x + w / 10;\n int w1 = w * 8 / 10;\n int y1 = y + h / 10;\n int h1 = h * 8 / 10;\n Image img = emp.isPlayer() ? emp.race().flagPact() : player().viewForEmpire(emp).flag();\n int imgH = img.getHeight(null);\n int imgW = img.getWidth(null);\n g.drawImage(img, x1, y1, x1 + w1, y1 + h1, 0, 0, imgW, imgH, null);\n }\n\n private void drawEmpireName(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(SystemPanel.orangeText);\n g.setFont(narrowFont(32));\n drawString(g, emp.name(), x + s10, y + h - s15);\n }\n\n private void drawPlayerBaseInfo(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n int lineH = s30;\n int y1 = y + lineH - s5;\n int y2 = y1 + lineH;\n int y3 = y2 + lineH;\n int y4 = y3 + lineH;\n int x0 = x + s20;\n g.setFont(narrowFont(22));\n Color textC = SystemPanel.whiteText;\n drawShadowedString(g, text(\"RACES_DIPLOMACY_HOMEWORLD\"), 1, x0, y1, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_LEADER\"), 1, x0, y2, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_CURRENT_TRADE\"), 1, x0, y3, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_TOTAL_TRADE\"), 1, x0, y4, SystemPanel.blackText, textC);\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n String s = emp.sv.name(emp.capitalSysId());\n int sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y1);\n s = text(\"TITLE_LEADERNAME\", emp.labels().text(\"_nameTitle\"), emp.leader().name());\n s = emp.replaceTokens(s, \"alien\");\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n int amt = (int) player().totalTradeIncome();\n s = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y3);\n amt = player().totalTradeTreaties();\n s = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y4);\n }\n\n private void drawAIBaseInfo(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n int lineH = s30;\n int y1 = y + lineH - s5;\n int y2 = y1 + lineH;\n int y3 = y2 + lineH;\n int y4 = y3 + lineH;\n int x0 = x + s20;\n g.setFont(narrowFont(22));\n Color textC = SystemPanel.whiteText;\n drawShadowedString(g, text(\"RACES_DIPLOMACY_HOMEWORLD\"), 1, x0, y1, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_LEADER\"), 1, x0, y2, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_CHARACTER\"), 1, x0, y3, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_STATUS\"), 1, x0, y4, SystemPanel.blackText, textC);\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n String s = emp.sv.name(emp.capitalSysId());\n int sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y1);\n s = text(\"TITLE_LEADERNAME\", emp.race().text(\"_nameTitle\"), emp.leader().name());\n s = emp.replaceTokens(s, \"alien\");\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n s = text(\"LEADER_PERSONALITY_FORMAT\", emp.leader().personality(), emp.leader().objective());\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y3);\n EmpireView view = player().viewForEmpire(emp);\n DiplomaticTreaty treaty = view.embassy().treaty();\n boolean isAlly = treaty.isAlliance();\n int starW = s10;\n int offset = isAlly ? (starW * 5) + s5 : 0;\n s = treaty.status(player());\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - offset - sw, y4);\n if (isAlly) {\n TreatyAlliance alliance = (TreatyAlliance) treaty;\n int x1 = x + w - s20 - offset + s5;\n parent.drawAllianceStars(g, x1, y4 - s3, alliance.standing(player()), starW);\n }\n }\n\n private void drawRelationsMeter(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n EmpireView view = player().viewForEmpire(emp);\n if (view == null)\n return;\n int x0 = x + s10;\n int y0 = y + h - s12;\n g.setFont(narrowFont(24));\n String str = text(\"RACES_DIPLOMACY_RELATIONS_METER\");\n this.drawShadowedString(g, str, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n int leftW = g.getFontMetrics().stringWidth(str);\n if (emp.race().masksDiplomacy) {\n g.setFont(narrowFont(15));\n g.setColor(SystemPanel.blackText);\n String str2 = text(\"RACES_DIPLOMACY_RELATIONS_UNKNOWN\");\n str2 = emp.replaceTokens(str2, \"alien\");\n List lines = this.wrappedLines(g, str2, w - s60 - leftW);\n int x1 = x0 + leftW + s40;\n int y1 = lines.size() == 1 ? y0 : y0 - s10;\n for (String line : lines) {\n drawString(g, line, x1, y1);\n y1 += s15;\n }\n return;\n }\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n float relations = view.otherView().embassy().relations();\n // which relation key display to use\n float pctRel = (relations + 100) / 200.0f;\n float sizeRelId = 1.0f / relationIds.length;\n int i = (int) (pctRel / sizeRelId);\n i = bounds(0, i, relationIds.length - 1);\n String rel = text(relationIds[i]);\n int rightW = g.getFontMetrics().stringWidth(rel);\n int x1 = x + w - rightW - s20;\n drawString(g, rel, x1, y0);\n int x2 = x0 + leftW + s30;\n int w2 = x + w - x2 - rightW - s30;\n int y2 = y + s12;\n int h2 = h - s15;\n parent.drawRelationsBar(g, emp, x2, y2, w2, h2, s16, s8);\n }\n\n private void drawPlayerDiplomaticEvents(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n // title area\n int x0 = x;\n int w0 = w;\n int y0 = y;\n int h0 = s30;\n if (incidentTitleBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x0, 0);\n Point2D ptEnd = new Point2D.Float(x0 + w0, 0);\n Color[] yesColors = { brownEdgeC, brownMidC, brownEdgeC };\n incidentTitleBackground = new LinearGradientPaint(ptStart, ptEnd, dist, yesColors);\n }\n g.setPaint(incidentTitleBackground);\n g.fillRect(x0, y0, w0, h0);\n // year or turn\n g.setFont(narrowFont(20));\n int x1 = x0;\n int w1 = s60;\n String year = UserPreferences.displayYear() ? text(\"RACES_DIPLOMACY_EVENT_YEAR\") : text(\"RACES_DIPLOMACY_EVENT_TURN\");\n int sw = g.getFontMetrics().stringWidth(year);\n drawShadowedString(g, year, 1, x0 + (w1 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // race\n g.setFont(narrowFont(20));\n int x2 = x1 + w1;\n int w2 = s100;\n String race = text(\"RACES_DIPLOMACY_EVENT_RACE\");\n sw = g.getFontMetrics().stringWidth(race);\n drawShadowedString(g, race, 1, x2 + (w2 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // scrollboar\n int w5 = s20;\n int x5 = x0 + w0 - w5;\n // effect\n g.setFont(narrowFont(20));\n String effect = text(\"RACES_DIPLOMACY_EVENT_EFFECT\");\n sw = g.getFontMetrics().stringWidth(effect);\n int w4 = s60;\n int x4 = x5 - w4;\n drawShadowedString(g, effect, 1, x4 + (w4 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(22));\n int x3 = x2 + w2;\n int w3 = x4 - x3;\n String title = text(\"RACES_DIPLOMACY_EVENT_TITLE\");\n sw = g.getFontMetrics().stringWidth(title);\n drawShadowedString(g, title, 1, x3 + (w3 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // data area\n g.setColor(RacesUI.darkBrown);\n int y1 = y0 + h0;\n int listH = h - h0;\n g.fillRect(x0, y1, w0, listH);\n g.setClip(x0, y1 + s1, w0, listH - s2);\n // draw vertical divider lines\n Stroke prev = g.getStroke();\n g.setStroke(stroke1);\n g.setColor(brownDividerC);\n g.drawLine(x2, y1, x2, y1 + listH);\n g.drawLine(x3, y1, x3, y1 + listH);\n g.drawLine(x4, y1, x4, y1 + listH);\n g.drawLine(x5, y1, x5, y1 + listH);\n g.setStroke(prev);\n List incidents = new ArrayList<>();\n incidentMap.clear();\n for (EmpireView view : player().contacts()) {\n for (DiplomaticIncident inc : view.otherView().embassy().allIncidents()) {\n if ((inc.currentSeverity() != 0) && inc.triggeredByAction()) {\n incidents.add(inc);\n incidentMap.put(inc, view.empire());\n }\n }\n }\n Collections.sort(incidents, DiplomaticIncident.DATE);\n int y2 = y1 - incidentY;\n int fullListH = 0;\n for (int i = 0; i < incidents.size(); i++) {\n DiplomaticIncident inc = incidents.get(i);\n int incidentH = drawPlayerIncident(g, inc, x0, y2, w0, w1, w2, w3, w4);\n fullListH += incidentH;\n y2 += incidentH;\n }\n incidentYMax = max(0, fullListH - listH);\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + incidentYMax));\n int scrollX = x + w - scrollW - s4;\n int scrollY = (int) (y1 + (float) listH * incidentY / (incidentYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n incidentScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == incidentScroller) {\n prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n g.setClip(null);\n incidentListBox.setBounds(x0, y1, w0, listH);\n if ((hoverShape == incidentListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(incidentListBox);\n g.setStroke(prev);\n }\n }\n\n private int drawPlayerIncident(Graphics g, DiplomaticIncident inc, int x, int y, int w, int w1, int w2, int w3, int w4) {\n String title = inc.title() + \":\";\n String sev = fmt(inc.currentSeverity(), 1);\n String desc = inc.description();\n g.setFont(narrowFont(18));\n int indent = g.getFontMetrics().stringWidth(title) + s5;\n g.setFont(narrowFont(15));\n List descLines = wrappedLines(g, desc, w3 - s15, indent);\n int h0 = s7 + (s22 * descLines.size());\n // title\n int x1 = x;\n int x2 = x1 + w1;\n int x3 = x2 + w2;\n int x4 = x3 + w3;\n int y1 = y + s8;\n // year or turn\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n String year = UserPreferences.displayYear() ? str(inc.dateOccurred()) : str(inc.turnOccurred());\n int sw = g.getFontMetrics().stringWidth(year);\n int x0 = x1 + (w1 - sw) / 2;\n int y0 = y + s25;\n drawString(g, year, x0, y0);\n // race\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n Empire otherEmpire = incidentMap.get(inc);\n String race = otherEmpire.raceName();\n sw = g.getFontMetrics().stringWidth(race);\n x0 = x2 + (w2 - sw) / 2;\n y0 = y + s25;\n drawString(g, race, x0, y0);\n boolean firstLine = true;\n g.setFont(narrowFont(18));\n for (String line : descLines) {\n y1 += s17;\n g.setColor(Color.black);\n if (firstLine) {\n drawString(g, title, x3 + s10, y1);\n g.setFont(narrowFont(15));\n drawString(g, line, x3 + s10 + indent, y1);\n firstLine = false;\n } else\n drawString(g, line, x3 + s10, y1);\n }\n // severity\n if (!otherEmpire.race().masksDiplomacy) {\n g.setFont(narrowFont(18));\n sw = g.getFontMetrics().stringWidth(sev);\n x0 = x4 + (w4 - sw) / 2;\n if (inc.currentSeverity() < 0)\n g.setColor(incidentRedC);\n else\n g.setColor(incidentGreenC);\n drawString(g, sev, x0, y0);\n }\n g.setColor(brownDividerC);\n g.drawLine(x1, y1 + s12, x + w - s20, y1 + s12);\n return h0;\n }\n\n private void drawPlayerDiplomacyBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n List views = player().contacts();\n int recalls = 0;\n for (EmpireView v : views) {\n if (v.embassy().diplomatGone())\n recalls++;\n }\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_BUREAU\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_DIPLOMACY_BUREAU_DESC1\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_DIPLOMACY_KNOWN_EMPIRES\");\n int y2 = y0 + s85;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String str2 = str(views.size());\n int sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_DIPLOMACY_RECALLED_DIPLOMAT\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) 0;\n g.setFont(narrowFont(16));\n str2 = str(recalls);\n sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n drawManageDiplomatsButton(g, x + s20, y + h - s45, w - s40, s25);\n }\n\n private void drawPlayerCounterIntelligenceBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_COUNTER_BUREAU\");\n int fontSize = scaledFont(g, title, w - s20, 24, 20);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_DIPLOMACY_COUNTER_DESC\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_INTEL_SECURITY_BONUS\");\n int y2 = y0 + s70;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n int amt = (int) (100 * player().totalInternalSecurityPct());\n String s = amt == 0 ? text(\"RACES_INTEL_SECURITY_BONUS_NONE\") : text(\"RACES_INTEL_SECURITY_BONUS_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_INTEL_TOTAL_SPENDING\");\n drawString(g, spending, x + s20, y2);\n g.setFont(narrowFont(16));\n amt = (int) internalSecurityCost;\n s = text(\"RACES_INTEL_SPENDING_ANNUAL\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n g.setFont(narrowFont(15));\n desc = text(\"RACES_DIPLOMACY_COUNTER_DESC2\");\n lines = wrappedLines(g, desc, w - s30);\n int y3 = y + h - s20 - (s16 * 3);\n for (String line : lines) {\n drawString(g, line, x + s20, y3);\n y3 += s16;\n }\n g.setFont(narrowFont(16));\n int y4 = y + h - s20;\n String taxStr = text(\"RACES_INTEL_SECURITY_TAX\");\n drawString(g, taxStr, x + s20, y4);\n int sw4 = g.getFontMetrics().stringWidth(taxStr);\n // draw string on right for pct\n String cost = text(\"RACES_INTEL_PERCENT_AMT\", (int) (player().internalSecurityCostPct() * 100));\n sw = g.getFontMetrics().stringWidth(cost);\n drawString(g, cost, x + w - s20 - sw, y4);\n // need maxwidth so slider doesn't move as cost pct changes\n String maxWidthStr = text(\"RACES_INTEL_PERCENT_AMT\", 10);\n sw = g.getFontMetrics().stringWidth(maxWidthStr);\n int sliderW = w - sw - sw4 - s80;\n int sliderH = s16;\n drawSecuritySliderBar(g, x + s20 + sw4, y4 - sliderH + s3, sliderW, sliderH);\n }\n\n private void drawSecuritySliderBar(Graphics2D g, int x, int y, int w, int h) {\n // draw spending bar\n // height of bar\n int h1 = h;\n // width of bar\n int w1 = w;\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n float pct = view == null ? player().internalSecurityPct() : view.spies().allocationPct();\n // width of spending\n int w1a = (int) (pct * w1);\n int y1 = y + ((h - h1) / 2);\n int x1 = x + s20;\n g.setColor(Color.black);\n g.fillRect(x1, y1, w1, h1);\n g.setColor(sliderC);\n g.fillRect(x1, y1, w1a, h1);\n buttonSlider.setBounds(x1, y1, w1, h1);\n if (hoverShape == buttonSlider) {\n g.setColor(Color.yellow);\n Stroke prev = g.getStroke();\n g.setStroke(stroke2);\n g.drawRect(x1, y1, w1, h1);\n g.setStroke(prev);\n }\n int sz = h1 / 2;\n // draw left/decr button\n ptX[0] = x1 - s3 - sz;\n ptX[1] = ptX[0] + sz;\n ptX[2] = ptX[0] + sz;\n ptY[0] = y + (h / 2);\n ptY[1] = ptY[0] - sz;\n ptY[2] = ptY[0] + sz;\n Color buttonC = hoverShape == buttonDecr ? SystemPanel.yellowText : Color.black;\n buttonDecr.reset();\n for (int i = 0; i < ptX.length; i++) buttonDecr.addPoint(ptX[i], ptY[i]);\n drawShadedPolygon(g, ptX, ptY, buttonC, s1, -s1);\n // draw right/incr button\n ptX[0] = x1 + w1 + sz + s3;\n ptX[1] = ptX[0] - sz;\n ptX[2] = ptX[0] - sz;\n ptY[0] = y + (h / 2);\n ptY[1] = ptY[0] - sz;\n ptY[2] = ptY[0] + sz;\n buttonIncr.reset();\n for (int i = 0; i < ptX.length; i++) buttonIncr.addPoint(ptX[i], ptY[i]);\n buttonC = hoverShape == buttonIncr ? SystemPanel.yellowText : Color.black;\n drawShadedPolygon(g, ptX, ptY, buttonC, s1, -s1);\n if (!parent.selectedEmpire().isPlayer()) {\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(15));\n String spyCost = text(\"RACES_INTEL_SPENDING_ANNUAL\", (int) externalSpyingCost);\n int sw1 = g.getFontMetrics().stringWidth(spyCost);\n int xa = buttonSlider.x + ((buttonSlider.width - sw1) / 2);\n int ya = buttonSlider.y + buttonSlider.height - s4;\n drawString(g, spyCost, xa, ya);\n }\n }\n\n private void drawPlayerIntelligenceBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_INTEL_BUREAU_TITLE\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_INTEL_BUREAU_DESC\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_INTEL_BUREAU_SPIES\");\n int y2 = y + h - s85;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String str2 = str(player().totalActiveSpies());\n int sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_INTEL_BUREAU_SPENDING\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) externalSpyingCost;\n g.setFont(narrowFont(16));\n str2 = amt == 0 ? text(\"RACES_INTEL_SECURITY_BONUS_NONE\") : text(\"RACES_INTEL_SPENDING_ANNUAL\", str(amt));\n sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n drawManageSpiesButton(g, x + s20, y2, w - s40, s25);\n }\n\n private void drawManageDiplomatsButton(Graphics2D g, int x, int y, int w, int h) {\n manageDiplomatsBox.setBounds(x, y, w, h);\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n g.setColor(unselectedC);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if (hoverShape == manageDiplomatsBox)\n c0 = Color.yellow;\n String lbl = text(\"RACES_DIPLOMACY_MANAGE_DIPLOMATS\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n private void drawManageSpiesButton(Graphics2D g, int x, int y, int w, int h) {\n manageSpiesBox.setBounds(x, y, w, h);\n g.setColor(Color.blue);\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n g.setColor(unselectedC);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if (hoverShape == manageSpiesBox)\n c0 = Color.yellow;\n String lbl = text(\"RACES_INTEL_BUREAU_MANAGE\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n private void drawAIDiplomaticEvents(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n // title area\n int x0 = x;\n int w0 = w;\n int y0 = y;\n int h0 = s30;\n if (incidentTitleBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x0, 0);\n Point2D ptEnd = new Point2D.Float(x0 + w0, 0);\n Color[] yesColors = { brownEdgeC, brownMidC, brownEdgeC };\n incidentTitleBackground = new LinearGradientPaint(ptStart, ptEnd, dist, yesColors);\n }\n g.setPaint(incidentTitleBackground);\n g.fillRect(x0, y0, w0, h0);\n // title\n g.setFont(narrowFont(20));\n String year = UserPreferences.displayYear() ? text(\"RACES_DIPLOMACY_EVENT_YEAR\") : text(\"RACES_DIPLOMACY_EVENT_TURN\");\n drawShadowedString(g, year, 1, x0 + s10, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(22));\n String title = text(\"RACES_DIPLOMACY_EVENT_TITLE\");\n int sw = g.getFontMetrics().stringWidth(title);\n drawShadowedString(g, title, 1, x0 + (w0 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(20));\n String effect = text(\"RACES_DIPLOMACY_EVENT_EFFECT\");\n int sw2 = g.getFontMetrics().stringWidth(effect);\n drawShadowedString(g, effect, 1, x0 + w0 - sw2 - s30, y0 + s23, Color.black, SystemPanel.whiteText);\n // data area\n g.setColor(RacesUI.darkBrown);\n int y1 = y0 + h0;\n int x1 = x0;\n int w1 = w0;\n int listH = h - h0;\n g.fillRect(x1, y1, w1, listH);\n g.setClip(x1, y1 + s1, w1, listH - s2);\n // draw vertical divider lines\n int x1a = x1 + s60;\n int x1b = x1 + w1 - s80;\n int x1c = x1 + w1 - s20;\n Stroke prev = g.getStroke();\n g.setStroke(stroke1);\n g.setColor(brownDividerC);\n g.drawLine(x1a, y1, x1a, y1 + listH);\n g.drawLine(x1b, y1, x1b, y1 + listH);\n g.drawLine(x1c, y1, x1c, y1 + listH);\n g.setStroke(prev);\n List incidents = new ArrayList<>();\n for (DiplomaticIncident inc : parent.selectedView().otherView().embassy().allIncidents()) {\n if (inc.currentSeverity() != 0)\n incidents.add(inc);\n }\n Collections.sort(incidents, DiplomaticIncident.DATE);\n int y2 = y1 - incidentY;\n int fullListH = 0;\n for (int i = 0; i < incidents.size(); i++) {\n DiplomaticIncident inc = incidents.get(i);\n int incidentH = drawAIIncident(g, inc, x1, y2, w1, s60, s80);\n fullListH += incidentH;\n y2 += incidentH;\n }\n incidentYMax = max(0, fullListH - listH);\n if (incidentYMax == 0)\n incidentScroller.setBounds(0, 0, 0, 0);\n else {\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + incidentYMax));\n int scrollX = x1 + w1 - scrollW - s2;\n int scrollY = (int) (y1 + (float) listH * incidentY / (incidentYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n incidentScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == incidentScroller) {\n prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n }\n g.setClip(null);\n incidentListBox.setBounds(x1, y1, w1, listH);\n if ((hoverShape == incidentListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(incidentListBox);\n g.setStroke(prev);\n }\n }\n\n private int drawAIIncident(Graphics g, DiplomaticIncident inc, int x, int y, int w, int leftM, int rightM) {\n String title = inc.title() + \":\";\n String sev = fmt(inc.currentSeverity(), 1);\n String desc = inc.description();\n g.setFont(narrowFont(18));\n int indent = g.getFontMetrics().stringWidth(title) + s5;\n g.setFont(narrowFont(15));\n List descLines = wrappedLines(g, desc, w - s20 - leftM - rightM, indent);\n int h0 = s7 + (s22 * descLines.size());\n // title\n int x1 = x + leftM + s10;\n int y1 = y + s8;\n g.setFont(narrowFont(22));\n g.setColor(Color.black);\n // description lines\n boolean firstLine = true;\n g.setFont(narrowFont(18));\n for (String line : descLines) {\n y1 += s17;\n g.setColor(Color.black);\n if (firstLine) {\n drawString(g, title, x1, y1);\n g.setFont(narrowFont(15));\n drawString(g, line, x1 + indent, y1);\n firstLine = false;\n } else\n drawString(g, line, x1, y1);\n }\n // year\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n String year = UserPreferences.displayYear() ? str(inc.dateOccurred()) : str(inc.turnOccurred());\n int sw0 = g.getFontMetrics().stringWidth(year);\n int x0 = x + (leftM - sw0) / 2;\n int y0 = y + s25;\n drawString(g, year, x0, y0);\n // severity\n int x2 = x + w - rightM;\n int w2 = s60;\n if (!parent.selectedEmpire().race().masksDiplomacy) {\n g.setFont(narrowFont(18));\n int sw = g.getFontMetrics().stringWidth(sev);\n int x2a = x2 + (w2 - sw) / 2;\n if (inc.currentSeverity() < 0)\n g.setColor(incidentRedC);\n else\n g.setColor(incidentGreenC);\n drawString(g, sev, x2a, y0);\n }\n g.setColor(brownDividerC);\n g.drawLine(x, y1 + s8, x + w - s20, y1 + s8);\n return h0;\n }\n\n private void drawAIDiplomacyBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_BUREAU\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean finalWar = player().viewForEmpire(emp).embassy().finalWar();\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (finalWar)\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC_FINAL\");\n else if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC_RANGE\");\n else {\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n }\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s7;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n embassyBox.setBounds(0, 0, 0, 0);\n if (!finalWar && !outOfRange)\n drawEmbassyButton(g, x + s20, y + h - s38, w - s40, s28);\n }\n\n private void drawAITradeSummary(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_TRADE_SUMMARY\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean finalWar = player().viewForEmpire(emp).embassy().finalWar();\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (finalWar)\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC_FINAL\");\n else if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC_RANGE\");\n else {\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n }\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s10;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n EmpireView view = player().viewForEmpire(emp);\n if (view == null)\n return;\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_DIPLOMACY_TRADE_TREATY\");\n int y2 = lines.size() <= 5 ? y0 + h - s65 : y0 + h - s55;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String s2 = text(\"RACES_DIPLOMACY_TRADE_AMT\", view.trade().level());\n int sw2 = g.getFontMetrics().stringWidth(s2);\n drawString(g, s2, x + w - s20 - sw2, y2);\n y2 += s22;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_DIPLOMACY_CURRENT_TRADE\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) view.trade().profit();\n g.setFont(narrowFont(16));\n s2 = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw2 = g.getFontMetrics().stringWidth(s2);\n drawString(g, s2, x + w - s20 - sw2, y2);\n }\n\n private void drawAIForeignRelations(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_FOREIGN_RELATIONS\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_FOREIGN_RANGE\");\n else\n desc = text(\"RACES_DIPLOMACY_FOREIGN_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s10;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n if (outOfRange)\n return;\n int x2 = x + s10;\n int y2 = y1 + s10;\n int w2 = w - s20;\n int listH = y + h - y2 - s20;\n g.setColor(RacesUI.brown);\n g.fillRect(x2, y2, w2, listH);\n relationsListBox.setBounds(x2, y2, w2, listH);\n g.setClip(x2, y2 + s1, w2, listH - s2);\n int y3 = y2 - relationsY;\n int x3 = x2 + s10;\n g.setFont(narrowFont(18));\n g.setColor(SystemPanel.blackText);\n List contacts = emp.contacts();\n Collections.sort(contacts, EmpireView.PLAYER_LIST_ORDER);\n int rowH = s18;\n int fullListH = (contacts.size() * rowH) + s5;\n int rightM = fullListH <= listH ? s10 : s20;\n for (EmpireView contact : contacts) {\n if (contact.inEconomicRange()) {\n y3 += rowH;\n g.setFont(narrowFont(18));\n drawString(g, contact.empire().raceName(), x3, y3);\n g.setFont(narrowFont(15));\n String treaty = contact.embassy().treaty().status(player());\n int sw1 = g.getFontMetrics().stringWidth(treaty);\n int x3b = x2 + w2 - sw1 - rightM;\n drawString(g, treaty, x3b, y3);\n }\n }\n relationsYMax = max(0, fullListH - listH);\n if (relationsYMax == 0)\n relationsScroller.setBounds(0, 0, 0, 0);\n else {\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + relationsYMax));\n int scrollX = x2 + w2 - scrollW - s2;\n int scrollY = (int) (y2 + (float) listH * relationsY / (relationsYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n relationsScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == relationsScroller) {\n Stroke prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n }\n g.setClip(null);\n if ((hoverShape == relationsListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n Stroke prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(relationsListBox);\n g.setStroke(prev);\n }\n }\n\n private void drawEmbassyButton(Graphics2D g, int x, int y, int w, int h) {\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n if (view == null)\n return;\n embassyBox.setBounds(x, y, w, h);\n if (embassyBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x, 0);\n Point2D ptEnd = new Point2D.Float(x + w, 0);\n Color[] colors = { greenEdgeC, greenMidC, greenEdgeC };\n embassyBackground = new LinearGradientPaint(ptStart, ptEnd, dist, colors);\n Color[] colors2 = { brownEdgeC, brownMidC, brownEdgeC };\n embassyDisabledBackground = new LinearGradientPaint(ptStart, ptEnd, dist, colors2);\n }\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n if (view.diplomats())\n g.setPaint(embassyBackground);\n else\n g.setPaint(embassyDisabledBackground);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if ((hoverShape == embassyBox) && view.diplomats())\n c0 = Color.yellow;\n String lbl = view.embassy().diplomatGone() ? text(\"RACES_DIPLOMACY_CONTACT\") : text(\"RACES_DIPLOMACY_AUDIENCE\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n public void openEmbassy() {\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n if (view == null)\n return;\n if (view.embassy().diplomatGone()) {\n view.embassy().reopenEmbassy();\n parent.repaint();\n return;\n }\n if (!view.diplomats())\n return;\n DiplomaticMessage.show(parent.selectedEmpire().viewForEmpire(player()), DialogueManager.DIPLOMACY_MAIN_MENU);\n }\n\n public void openManageDiplomatsPane() {\n softClick();\n manageDiplomatsPane.init();\n enableGlassPane(manageDiplomatsPane);\n return;\n }\n\n public void openManageSpiesPane() {\n softClick();\n manageSpiesPane.init();\n enableGlassPane(manageSpiesPane);\n return;\n }\n\n private boolean increaseSliderValue() {\n int oldValue = player().internalSecurity();\n player().increaseInternalSecurity();\n return oldValue != player().internalSecurity();\n }\n\n private boolean decreaseSliderValue() {\n int oldValue = player().internalSecurity();\n player().decreaseInternalSecurity();\n return oldValue != player().internalSecurity();\n }\n\n @Override\n public void mouseWheelMoved(MouseWheelEvent e) {\n int count = e.getUnitsToScroll();\n if ((hoverShape == incidentListBox) || (hoverShape == incidentScroller)) {\n int prevY = incidentY;\n if (count < 0)\n incidentY = max(0, incidentY - s10);\n else\n incidentY = min(incidentYMax, incidentY + s10);\n if (incidentY != prevY)\n repaint(incidentListBox);\n return;\n } else if (hoverShape == buttonSlider) {\n boolean changed = count < 0 ? increaseSliderValue() : decreaseSliderValue();\n if (changed) {\n setValues();\n repaint();\n }\n } else if ((hoverShape == relationsListBox) || (hoverShape == relationsScroller)) {\n int prevY = relationsY;\n if (count < 0)\n relationsY = max(0, relationsY - s10);\n else\n relationsY = min(relationsYMax, relationsY + s10);\n if (relationsY != prevY)\n repaint(relationsListBox);\n return;\n }\n }\n\n @Override\n public void mouseDragged(MouseEvent e) {\n int x = e.getX();\n int y = e.getY();\n int dY = y - dragY;\n dragY = y;\n if (incidentScroller == hoverShape) {\n if ((y >= incidentListBox.y) || (y <= (incidentListBox.y + incidentListBox.height))) {\n int h = (int) incidentListBox.getHeight();\n int dListY = (int) ((float) dY * (h + incidentYMax) / h);\n if (dY < 0)\n incidentY = max(0, incidentY + dListY);\n else\n incidentY = min(incidentYMax, incidentY + dListY);\n }\n repaint(incidentListBox);\n return;\n } else if (incidentListBox == hoverShape) {\n if (incidentListBox.contains(x, y)) {\n int h = (int) incidentListBox.getHeight();\n int dListY = (int) (-(float) dY * (h + incidentYMax) / h);\n if (dListY < 0)\n incidentY = max(0, incidentY + dListY);\n else\n incidentY = min(incidentYMax, incidentY + dListY);\n }\n repaint(incidentListBox);\n return;\n } else if (relationsScroller == hoverShape) {\n if ((y >= relationsListBox.y) || (y <= (relationsListBox.y + relationsListBox.height))) {\n int h = (int) relationsListBox.getHeight();\n int dListY = (int) ((float) dY * (h + relationsYMax) / h);\n if (dY < 0)\n relationsY = max(0, relationsY + dListY);\n else\n relationsY = min(relationsYMax, relationsY + dListY);\n }\n repaint(relationsListBox);\n return;\n } else if (relationsListBox == hoverShape) {\n if (relationsListBox.contains(x, y)) {\n int h = (int) relationsListBox.getHeight();\n int dListY = (int) (-(float) dY * (h + relationsYMax) / h);\n if (dListY < 0)\n relationsY = max(0, relationsY + dListY);\n else\n relationsY = min(relationsYMax, relationsY + dListY);\n }\n repaint(relationsListBox);\n return;\n }\n }\n\n @Override\n public void mouseMoved(MouseEvent e) {\n int x =", "post_mask_code": "\n int y = e.getY();\n Shape prevHover = hoverShape;\n hoverShape = null;\n if (buttonIncr.contains(x, y))\n hoverShape = buttonIncr;\n else if (buttonDecr.contains(x, y))\n hoverShape = buttonDecr;\n else if (buttonSlider.contains(x, y))\n hoverShape = buttonSlider;\n else if (embassyBox.contains(x, y))\n hoverShape = embassyBox;\n else if (incidentScroller.contains(x, y))\n hoverShape = incidentScroller;\n else if (incidentListBox.contains(x, y))\n hoverShape = incidentListBox;\n else if (relationsScroller.contains(x, y))\n hoverShape = relationsScroller;\n else if (relationsListBox.contains(x, y))\n hoverShape = relationsListBox;\n else if (manageSpiesBox.contains(x, y))\n hoverShape = manageSpiesBox;\n else if (manageDiplomatsBox.contains(x, y))\n hoverShape = manageDiplomatsBox;\n if (hoverShape != prevHover)\n repaint();\n }\n\n @Override\n public void mouseClicked(MouseEvent e) {\n }\n\n @Override\n public void mousePressed(MouseEvent e) {\n dragY = e.getY();\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n dragY = 0;\n if (e.getButton() > 3)\n return;\n if (hoverShape == null)\n return;\n Empire emp = parent.selectedEmpire();\n if (hoverShape == embassyBox) {\n openEmbassy();\n return;\n } else if (hoverShape == manageSpiesBox) {\n openManageSpiesPane();\n return;\n } else if (hoverShape == manageDiplomatsBox) {\n openManageDiplomatsPane();\n return;\n }\n if (hoverShape == buttonIncr) {\n boolean changed = increaseSliderValue();\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n } else if (hoverShape == buttonDecr) {\n boolean changed = decreaseSliderValue();\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n } else if (hoverShape == buttonSlider) {\n float pct = (float) ((e.getX() - buttonSlider.getMinX()) / buttonSlider.getWidth());\n boolean changed = false;\n if (emp.isPlayer()) {\n int oldSec = emp.internalSecurity();\n emp.securityAllocation(pct);\n changed = oldSec != emp.internalSecurity();\n }\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n }\n }\n\n @Override\n public void mouseEntered(MouseEvent e) {\n }\n\n @Override\n public void mouseExited(MouseEvent e) {\n if (hoverShape != null) {\n hoverShape = null;\n repaint();\n }\n }\n}\n"} {"task_id": "Java_2054", "language": "Java", "task_type": "if_statement", "source_file": "java/github/rayfowler/rotp-public/src/rotp/ui/races/RacesDiplomacyUI.java", "mask_start_position": 43797, "mask_end_position": 43832, "canonical_solution": "if (outOfRange)\n return;", "pre_mask_code": "/*\n * \n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage rotp.ui.races;\n\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.Image;\nimport java.awt.LinearGradientPaint;\nimport java.awt.Polygon;\nimport java.awt.Rectangle;\nimport java.awt.Shape;\nimport java.awt.Stroke;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseListener;\nimport java.awt.event.MouseMotionListener;\nimport java.awt.event.MouseWheelEvent;\nimport java.awt.event.MouseWheelListener;\nimport java.awt.geom.Point2D;\nimport java.awt.geom.RoundRectangle2D;\nimport java.awt.image.BufferedImage;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport rotp.model.empires.DiplomaticTreaty;\nimport rotp.model.empires.Empire;\nimport rotp.model.empires.EmpireView;\nimport rotp.model.empires.TreatyAlliance;\nimport rotp.model.incidents.DiplomaticIncident;\nimport rotp.ui.BasePanel;\nimport rotp.ui.UserPreferences;\nimport rotp.ui.diplomacy.DialogueManager;\nimport rotp.ui.diplomacy.DiplomaticMessage;\nimport rotp.ui.main.MainUI;\nimport rotp.ui.main.SystemPanel;\nimport static rotp.ui.races.RacesIntelligenceUI.sliderC;\n\npublic final class RacesDiplomacyUI extends BasePanel implements MouseListener, MouseMotionListener, MouseWheelListener {\n\n private static final long serialVersionUID = 1L;\n\n public static final String[] relationIds = new String[] { \"RELATIONS_FEUD\", \"RELATIONS_HATE\", \"RELATIONS_DISCORD\", \"RELATIONS_TROUBLED\", \"RELATIONS_TENSE\", \"RELATIONS_RESTLESS\", \"RELATIONS_WARY\", \"RELATIONS_UNEASE\", \"RELATIONS_NEUTRAL\", \"RELATIONS_RELAXED\", \"RELATIONS_AMIABLE\", \"RELATIONS_CALM\", \"RELATIONS_AFFABLE\", \"RELATIONS_PEACEFUL\", \"RELATIONS_FRIENDLY\", \"RELATIONS_UNITY\", \"RELATIONS_HARMONY\" };\n\n private static final Color unselectedC = new Color(112, 85, 68);\n\n private final Color greenEdgeC = new Color(44, 59, 30);\n\n private final Color greenMidC = new Color(70, 93, 48);\n\n private final Color brownEdgeC = new Color(101, 70, 50);\n\n private final Color brownMidC = new Color(161, 111, 78);\n\n private final Color brownDividerC = new Color(136, 115, 96);\n\n private final Color incidentRedC = new Color(112, 0, 0);\n\n private final Color incidentGreenC = new Color(0, 63, 32);\n\n private final RacesUI parent;\n\n private final ManageDiplomatsUI manageDiplomatsPane;\n\n private final ManageSpiesUI manageSpiesPane;\n\n int incidentY, incidentYMax;\n\n int relationsY, relationsYMax;\n\n int dragY;\n\n private LinearGradientPaint incidentTitleBackground;\n\n private LinearGradientPaint backGradient;\n\n private LinearGradientPaint embassyBackground, embassyDisabledBackground;\n\n private final Rectangle embassyBox = new Rectangle();\n\n private final Rectangle incidentListBox = new Rectangle();\n\n private final Rectangle incidentScroller = new Rectangle();\n\n private final Rectangle relationsListBox = new Rectangle();\n\n private final Rectangle relationsScroller = new Rectangle();\n\n private final Rectangle manageDiplomatsBox = new Rectangle();\n\n private final Rectangle manageSpiesBox = new Rectangle();\n\n Polygon buttonIncr = new Polygon();\n\n Polygon buttonDecr = new Polygon();\n\n Rectangle buttonSlider = new Rectangle();\n\n private float internalSecurityCost = 0;\n\n private float externalSpyingCost = 0;\n\n int[] ptX = new int[3];\n\n int[] ptY = new int[3];\n\n private final HashMap incidentMap = new HashMap<>();\n\n private Shape hoverShape;\n\n public RacesDiplomacyUI(RacesUI p) {\n parent = p;\n manageDiplomatsPane = new ManageDiplomatsUI(p);\n manageSpiesPane = new ManageSpiesUI(p);\n initModel();\n }\n\n @Override\n public void drawTexture(Graphics g) {\n }\n\n @Override\n public String textureName() {\n return TEXTURE_BROWN;\n }\n\n public void init() {\n setValues();\n }\n\n public void changedEmpire() {\n setValues();\n }\n\n private void setValues() {\n incidentY = 0;\n relationsY = 0;\n if (parent.selectedEmpire().isPlayer()) {\n internalSecurityCost = player().empireInternalSecurityCost();\n externalSpyingCost = player().empireExternalSpyingCost();\n }\n }\n\n @Override\n public void paintComponent(Graphics g0) {\n super.paintComponent(g0);\n Graphics2D g = (Graphics2D) g0;\n int w = getWidth();\n int h = getHeight();\n relationsListBox.setBounds(0, 0, 0, 0);\n relationsScroller.setBounds(0, 0, 0, 0);\n manageDiplomatsBox.setBounds(0, 0, 0, 0);\n manageSpiesBox.setBounds(0, 0, 0, 0);\n buttonIncr.reset();\n buttonDecr.reset();\n if (backGradient == null) {\n Point2D start = new Point2D.Float(0, getHeight() / 2);\n Point2D end = new Point2D.Float(0, getHeight());\n float[] dist = { 0.0f, 1.0f };\n Color[] colors = { RacesUI.darkerBrown, RacesUI.gradientBottom };\n backGradient = new LinearGradientPaint(start, end, dist, colors);\n }\n g.setPaint(backGradient);\n g.fillRect(0, h / 2, w, h / 2);\n if (parent.selectedEmpire().isPlayer())\n paintPlayerData(g);\n else\n paintAIData(g);\n }\n\n private void initModel() {\n setBackground(RacesUI.darkerBrown);\n setBorder(newEmptyBorder(5, 5, 5, 5));\n addMouseMotionListener(this);\n addMouseListener(this);\n addMouseWheelListener(this);\n }\n\n private void paintPlayerData(Graphics2D g) {\n Empire emp = parent.selectedEmpire();\n int w = getWidth();\n int h = getHeight();\n int s200 = scaled(200);\n int s210 = scaled(210);\n int s215 = scaled(215);\n int s245 = scaled(245);\n int s260 = scaled(260);\n int s370 = scaled(370);\n int s435 = scaled(435);\n int x0 = s20;\n int x1 = w - scaled(299);\n int w0 = x1 - x0 - s20;\n int w1 = scaled(279);\n drawRaceIconBase(g, emp, s55, s25, s210, s210);\n drawPlayerBaseInfo(g, emp, s260, s80, s370, scaled(130));\n drawPlayerDiplomaticEvents(g, emp, x0, s245, w0, h - s245 - s10);\n drawPlayerDiplomacyBureau(g, emp, x1, s10, w1, s200);\n drawPlayerCounterIntelligenceBureau(g, emp, x1, s215, w1, s215);\n drawPlayerIntelligenceBureau(g, emp, x1, s435, w1, s200);\n if (UserPreferences.texturesInterface())\n drawTexture(g, 0, 0, w, h);\n drawRaceIcon(g, emp, s60, s30, s200, s200);\n drawEmpireName(g, emp, s260, s30, s370, s50);\n }\n\n private void paintAIData(Graphics2D g) {\n Empire emp = parent.selectedEmpire();\n int w = getWidth();\n int h = getHeight();\n int s200 = scaled(200);\n int s135 = scaled(135);\n int s150 = scaled(150);\n int s175 = scaled(175);\n int s210 = scaled(210);\n int s245 = scaled(245);\n int s260 = scaled(260);\n int s295 = scaled(295);\n int s330 = scaled(330);\n int s370 = scaled(370);\n int x0 = s20;\n int x1 = w - scaled(299);\n int w0 = x1 - x0 - s20;\n int w1 = scaled(279);\n drawRaceIconBase(g, emp, s55, s25, s210, s210);\n drawAIBaseInfo(g, emp, s260, s80, s370, scaled(130));\n drawRelationsMeter(g, emp, x0, s245, w0, s40);\n drawAIDiplomaticEvents(g, emp, x0, s295, w0, h - s295 - s10);\n drawAIDiplomacyBureau(g, emp, x1, s10, w1, s135);\n drawAITradeSummary(g, emp, x1, s150, w1, s175);\n drawAIForeignRelations(g, emp, x1, s330, w1, h - s330 - s10);\n if (UserPreferences.texturesInterface())\n drawTexture(g, 0, 0, w, h);\n drawRaceIcon(g, emp, s60, s30, s200, s200);\n drawEmpireName(g, emp, s260, s30, s370, s50);\n }\n\n private void drawRaceIconBase(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n Shape rect = new RoundRectangle2D.Float(x, y, w, h, w / 8, h / 8);\n g.fill(rect);\n }\n\n private void drawRaceIcon(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(Color.black);\n Shape rect = new RoundRectangle2D.Float(x, y, w, h, w / 8, h / 8);\n g.fill(rect);\n BufferedImage backImg = parent.raceIconBackImg();\n g.drawImage(backImg, x, y, null);\n int x1 = x + w / 10;\n int w1 = w * 8 / 10;\n int y1 = y + h / 10;\n int h1 = h * 8 / 10;\n Image img = emp.isPlayer() ? emp.race().flagPact() : player().viewForEmpire(emp).flag();\n int imgH = img.getHeight(null);\n int imgW = img.getWidth(null);\n g.drawImage(img, x1, y1, x1 + w1, y1 + h1, 0, 0, imgW, imgH, null);\n }\n\n private void drawEmpireName(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(SystemPanel.orangeText);\n g.setFont(narrowFont(32));\n drawString(g, emp.name(), x + s10, y + h - s15);\n }\n\n private void drawPlayerBaseInfo(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n int lineH = s30;\n int y1 = y + lineH - s5;\n int y2 = y1 + lineH;\n int y3 = y2 + lineH;\n int y4 = y3 + lineH;\n int x0 = x + s20;\n g.setFont(narrowFont(22));\n Color textC = SystemPanel.whiteText;\n drawShadowedString(g, text(\"RACES_DIPLOMACY_HOMEWORLD\"), 1, x0, y1, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_LEADER\"), 1, x0, y2, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_CURRENT_TRADE\"), 1, x0, y3, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_TOTAL_TRADE\"), 1, x0, y4, SystemPanel.blackText, textC);\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n String s = emp.sv.name(emp.capitalSysId());\n int sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y1);\n s = text(\"TITLE_LEADERNAME\", emp.labels().text(\"_nameTitle\"), emp.leader().name());\n s = emp.replaceTokens(s, \"alien\");\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n int amt = (int) player().totalTradeIncome();\n s = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y3);\n amt = player().totalTradeTreaties();\n s = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y4);\n }\n\n private void drawAIBaseInfo(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n int lineH = s30;\n int y1 = y + lineH - s5;\n int y2 = y1 + lineH;\n int y3 = y2 + lineH;\n int y4 = y3 + lineH;\n int x0 = x + s20;\n g.setFont(narrowFont(22));\n Color textC = SystemPanel.whiteText;\n drawShadowedString(g, text(\"RACES_DIPLOMACY_HOMEWORLD\"), 1, x0, y1, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_LEADER\"), 1, x0, y2, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_CHARACTER\"), 1, x0, y3, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_STATUS\"), 1, x0, y4, SystemPanel.blackText, textC);\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n String s = emp.sv.name(emp.capitalSysId());\n int sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y1);\n s = text(\"TITLE_LEADERNAME\", emp.race().text(\"_nameTitle\"), emp.leader().name());\n s = emp.replaceTokens(s, \"alien\");\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n s = text(\"LEADER_PERSONALITY_FORMAT\", emp.leader().personality(), emp.leader().objective());\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y3);\n EmpireView view = player().viewForEmpire(emp);\n DiplomaticTreaty treaty = view.embassy().treaty();\n boolean isAlly = treaty.isAlliance();\n int starW = s10;\n int offset = isAlly ? (starW * 5) + s5 : 0;\n s = treaty.status(player());\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - offset - sw, y4);\n if (isAlly) {\n TreatyAlliance alliance = (TreatyAlliance) treaty;\n int x1 = x + w - s20 - offset + s5;\n parent.drawAllianceStars(g, x1, y4 - s3, alliance.standing(player()), starW);\n }\n }\n\n private void drawRelationsMeter(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n EmpireView view = player().viewForEmpire(emp);\n if (view == null)\n return;\n int x0 = x + s10;\n int y0 = y + h - s12;\n g.setFont(narrowFont(24));\n String str = text(\"RACES_DIPLOMACY_RELATIONS_METER\");\n this.drawShadowedString(g, str, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n int leftW = g.getFontMetrics().stringWidth(str);\n if (emp.race().masksDiplomacy) {\n g.setFont(narrowFont(15));\n g.setColor(SystemPanel.blackText);\n String str2 = text(\"RACES_DIPLOMACY_RELATIONS_UNKNOWN\");\n str2 = emp.replaceTokens(str2, \"alien\");\n List lines = this.wrappedLines(g, str2, w - s60 - leftW);\n int x1 = x0 + leftW + s40;\n int y1 = lines.size() == 1 ? y0 : y0 - s10;\n for (String line : lines) {\n drawString(g, line, x1, y1);\n y1 += s15;\n }\n return;\n }\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n float relations = view.otherView().embassy().relations();\n // which relation key display to use\n float pctRel = (relations + 100) / 200.0f;\n float sizeRelId = 1.0f / relationIds.length;\n int i = (int) (pctRel / sizeRelId);\n i = bounds(0, i, relationIds.length - 1);\n String rel = text(relationIds[i]);\n int rightW = g.getFontMetrics().stringWidth(rel);\n int x1 = x + w - rightW - s20;\n drawString(g, rel, x1, y0);\n int x2 = x0 + leftW + s30;\n int w2 = x + w - x2 - rightW - s30;\n int y2 = y + s12;\n int h2 = h - s15;\n parent.drawRelationsBar(g, emp, x2, y2, w2, h2, s16, s8);\n }\n\n private void drawPlayerDiplomaticEvents(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n // title area\n int x0 = x;\n int w0 = w;\n int y0 = y;\n int h0 = s30;\n if (incidentTitleBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x0, 0);\n Point2D ptEnd = new Point2D.Float(x0 + w0, 0);\n Color[] yesColors = { brownEdgeC, brownMidC, brownEdgeC };\n incidentTitleBackground = new LinearGradientPaint(ptStart, ptEnd, dist, yesColors);\n }\n g.setPaint(incidentTitleBackground);\n g.fillRect(x0, y0, w0, h0);\n // year or turn\n g.setFont(narrowFont(20));\n int x1 = x0;\n int w1 = s60;\n String year = UserPreferences.displayYear() ? text(\"RACES_DIPLOMACY_EVENT_YEAR\") : text(\"RACES_DIPLOMACY_EVENT_TURN\");\n int sw = g.getFontMetrics().stringWidth(year);\n drawShadowedString(g, year, 1, x0 + (w1 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // race\n g.setFont(narrowFont(20));\n int x2 = x1 + w1;\n int w2 = s100;\n String race = text(\"RACES_DIPLOMACY_EVENT_RACE\");\n sw = g.getFontMetrics().stringWidth(race);\n drawShadowedString(g, race, 1, x2 + (w2 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // scrollboar\n int w5 = s20;\n int x5 = x0 + w0 - w5;\n // effect\n g.setFont(narrowFont(20));\n String effect = text(\"RACES_DIPLOMACY_EVENT_EFFECT\");\n sw = g.getFontMetrics().stringWidth(effect);\n int w4 = s60;\n int x4 = x5 - w4;\n drawShadowedString(g, effect, 1, x4 + (w4 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(22));\n int x3 = x2 + w2;\n int w3 = x4 - x3;\n String title = text(\"RACES_DIPLOMACY_EVENT_TITLE\");\n sw = g.getFontMetrics().stringWidth(title);\n drawShadowedString(g, title, 1, x3 + (w3 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // data area\n g.setColor(RacesUI.darkBrown);\n int y1 = y0 + h0;\n int listH = h - h0;\n g.fillRect(x0, y1, w0, listH);\n g.setClip(x0, y1 + s1, w0, listH - s2);\n // draw vertical divider lines\n Stroke prev = g.getStroke();\n g.setStroke(stroke1);\n g.setColor(brownDividerC);\n g.drawLine(x2, y1, x2, y1 + listH);\n g.drawLine(x3, y1, x3, y1 + listH);\n g.drawLine(x4, y1, x4, y1 + listH);\n g.drawLine(x5, y1, x5, y1 + listH);\n g.setStroke(prev);\n List incidents = new ArrayList<>();\n incidentMap.clear();\n for (EmpireView view : player().contacts()) {\n for (DiplomaticIncident inc : view.otherView().embassy().allIncidents()) {\n if ((inc.currentSeverity() != 0) && inc.triggeredByAction()) {\n incidents.add(inc);\n incidentMap.put(inc, view.empire());\n }\n }\n }\n Collections.sort(incidents, DiplomaticIncident.DATE);\n int y2 = y1 - incidentY;\n int fullListH = 0;\n for (int i = 0; i < incidents.size(); i++) {\n DiplomaticIncident inc = incidents.get(i);\n int incidentH = drawPlayerIncident(g, inc, x0, y2, w0, w1, w2, w3, w4);\n fullListH += incidentH;\n y2 += incidentH;\n }\n incidentYMax = max(0, fullListH - listH);\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + incidentYMax));\n int scrollX = x + w - scrollW - s4;\n int scrollY = (int) (y1 + (float) listH * incidentY / (incidentYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n incidentScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == incidentScroller) {\n prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n g.setClip(null);\n incidentListBox.setBounds(x0, y1, w0, listH);\n if ((hoverShape == incidentListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(incidentListBox);\n g.setStroke(prev);\n }\n }\n\n private int drawPlayerIncident(Graphics g, DiplomaticIncident inc, int x, int y, int w, int w1, int w2, int w3, int w4) {\n String title = inc.title() + \":\";\n String sev = fmt(inc.currentSeverity(), 1);\n String desc = inc.description();\n g.setFont(narrowFont(18));\n int indent = g.getFontMetrics().stringWidth(title) + s5;\n g.setFont(narrowFont(15));\n List descLines = wrappedLines(g, desc, w3 - s15, indent);\n int h0 = s7 + (s22 * descLines.size());\n // title\n int x1 = x;\n int x2 = x1 + w1;\n int x3 = x2 + w2;\n int x4 = x3 + w3;\n int y1 = y + s8;\n // year or turn\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n String year = UserPreferences.displayYear() ? str(inc.dateOccurred()) : str(inc.turnOccurred());\n int sw = g.getFontMetrics().stringWidth(year);\n int x0 = x1 + (w1 - sw) / 2;\n int y0 = y + s25;\n drawString(g, year, x0, y0);\n // race\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n Empire otherEmpire = incidentMap.get(inc);\n String race = otherEmpire.raceName();\n sw = g.getFontMetrics().stringWidth(race);\n x0 = x2 + (w2 - sw) / 2;\n y0 = y + s25;\n drawString(g, race, x0, y0);\n boolean firstLine = true;\n g.setFont(narrowFont(18));\n for (String line : descLines) {\n y1 += s17;\n g.setColor(Color.black);\n if (firstLine) {\n drawString(g, title, x3 + s10, y1);\n g.setFont(narrowFont(15));\n drawString(g, line, x3 + s10 + indent, y1);\n firstLine = false;\n } else\n drawString(g, line, x3 + s10, y1);\n }\n // severity\n if (!otherEmpire.race().masksDiplomacy) {\n g.setFont(narrowFont(18));\n sw = g.getFontMetrics().stringWidth(sev);\n x0 = x4 + (w4 - sw) / 2;\n if (inc.currentSeverity() < 0)\n g.setColor(incidentRedC);\n else\n g.setColor(incidentGreenC);\n drawString(g, sev, x0, y0);\n }\n g.setColor(brownDividerC);\n g.drawLine(x1, y1 + s12, x + w - s20, y1 + s12);\n return h0;\n }\n\n private void drawPlayerDiplomacyBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n List views = player().contacts();\n int recalls = 0;\n for (EmpireView v : views) {\n if (v.embassy().diplomatGone())\n recalls++;\n }\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_BUREAU\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_DIPLOMACY_BUREAU_DESC1\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_DIPLOMACY_KNOWN_EMPIRES\");\n int y2 = y0 + s85;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String str2 = str(views.size());\n int sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_DIPLOMACY_RECALLED_DIPLOMAT\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) 0;\n g.setFont(narrowFont(16));\n str2 = str(recalls);\n sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n drawManageDiplomatsButton(g, x + s20, y + h - s45, w - s40, s25);\n }\n\n private void drawPlayerCounterIntelligenceBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_COUNTER_BUREAU\");\n int fontSize = scaledFont(g, title, w - s20, 24, 20);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_DIPLOMACY_COUNTER_DESC\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_INTEL_SECURITY_BONUS\");\n int y2 = y0 + s70;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n int amt = (int) (100 * player().totalInternalSecurityPct());\n String s = amt == 0 ? text(\"RACES_INTEL_SECURITY_BONUS_NONE\") : text(\"RACES_INTEL_SECURITY_BONUS_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_INTEL_TOTAL_SPENDING\");\n drawString(g, spending, x + s20, y2);\n g.setFont(narrowFont(16));\n amt = (int) internalSecurityCost;\n s = text(\"RACES_INTEL_SPENDING_ANNUAL\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n g.setFont(narrowFont(15));\n desc = text(\"RACES_DIPLOMACY_COUNTER_DESC2\");\n lines = wrappedLines(g, desc, w - s30);\n int y3 = y + h - s20 - (s16 * 3);\n for (String line : lines) {\n drawString(g, line, x + s20, y3);\n y3 += s16;\n }\n g.setFont(narrowFont(16));\n int y4 = y + h - s20;\n String taxStr = text(\"RACES_INTEL_SECURITY_TAX\");\n drawString(g, taxStr, x + s20, y4);\n int sw4 = g.getFontMetrics().stringWidth(taxStr);\n // draw string on right for pct\n String cost = text(\"RACES_INTEL_PERCENT_AMT\", (int) (player().internalSecurityCostPct() * 100));\n sw = g.getFontMetrics().stringWidth(cost);\n drawString(g, cost, x + w - s20 - sw, y4);\n // need maxwidth so slider doesn't move as cost pct changes\n String maxWidthStr = text(\"RACES_INTEL_PERCENT_AMT\", 10);\n sw = g.getFontMetrics().stringWidth(maxWidthStr);\n int sliderW = w - sw - sw4 - s80;\n int sliderH = s16;\n drawSecuritySliderBar(g, x + s20 + sw4, y4 - sliderH + s3, sliderW, sliderH);\n }\n\n private void drawSecuritySliderBar(Graphics2D g, int x, int y, int w, int h) {\n // draw spending bar\n // height of bar\n int h1 = h;\n // width of bar\n int w1 = w;\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n float pct = view == null ? player().internalSecurityPct() : view.spies().allocationPct();\n // width of spending\n int w1a = (int) (pct * w1);\n int y1 = y + ((h - h1) / 2);\n int x1 = x + s20;\n g.setColor(Color.black);\n g.fillRect(x1, y1, w1, h1);\n g.setColor(sliderC);\n g.fillRect(x1, y1, w1a, h1);\n buttonSlider.setBounds(x1, y1, w1, h1);\n if (hoverShape == buttonSlider) {\n g.setColor(Color.yellow);\n Stroke prev = g.getStroke();\n g.setStroke(stroke2);\n g.drawRect(x1, y1, w1, h1);\n g.setStroke(prev);\n }\n int sz = h1 / 2;\n // draw left/decr button\n ptX[0] = x1 - s3 - sz;\n ptX[1] = ptX[0] + sz;\n ptX[2] = ptX[0] + sz;\n ptY[0] = y + (h / 2);\n ptY[1] = ptY[0] - sz;\n ptY[2] = ptY[0] + sz;\n Color buttonC = hoverShape == buttonDecr ? SystemPanel.yellowText : Color.black;\n buttonDecr.reset();\n for (int i = 0; i < ptX.length; i++) buttonDecr.addPoint(ptX[i], ptY[i]);\n drawShadedPolygon(g, ptX, ptY, buttonC, s1, -s1);\n // draw right/incr button\n ptX[0] = x1 + w1 + sz + s3;\n ptX[1] = ptX[0] - sz;\n ptX[2] = ptX[0] - sz;\n ptY[0] = y + (h / 2);\n ptY[1] = ptY[0] - sz;\n ptY[2] = ptY[0] + sz;\n buttonIncr.reset();\n for (int i = 0; i < ptX.length; i++) buttonIncr.addPoint(ptX[i], ptY[i]);\n buttonC = hoverShape == buttonIncr ? SystemPanel.yellowText : Color.black;\n drawShadedPolygon(g, ptX, ptY, buttonC, s1, -s1);\n if (!parent.selectedEmpire().isPlayer()) {\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(15));\n String spyCost = text(\"RACES_INTEL_SPENDING_ANNUAL\", (int) externalSpyingCost);\n int sw1 = g.getFontMetrics().stringWidth(spyCost);\n int xa = buttonSlider.x + ((buttonSlider.width - sw1) / 2);\n int ya = buttonSlider.y + buttonSlider.height - s4;\n drawString(g, spyCost, xa, ya);\n }\n }\n\n private void drawPlayerIntelligenceBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_INTEL_BUREAU_TITLE\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_INTEL_BUREAU_DESC\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_INTEL_BUREAU_SPIES\");\n int y2 = y + h - s85;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String str2 = str(player().totalActiveSpies());\n int sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_INTEL_BUREAU_SPENDING\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) externalSpyingCost;\n g.setFont(narrowFont(16));\n str2 = amt == 0 ? text(\"RACES_INTEL_SECURITY_BONUS_NONE\") : text(\"RACES_INTEL_SPENDING_ANNUAL\", str(amt));\n sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n drawManageSpiesButton(g, x + s20, y2, w - s40, s25);\n }\n\n private void drawManageDiplomatsButton(Graphics2D g, int x, int y, int w, int h) {\n manageDiplomatsBox.setBounds(x, y, w, h);\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n g.setColor(unselectedC);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if (hoverShape == manageDiplomatsBox)\n c0 = Color.yellow;\n String lbl = text(\"RACES_DIPLOMACY_MANAGE_DIPLOMATS\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n private void drawManageSpiesButton(Graphics2D g, int x, int y, int w, int h) {\n manageSpiesBox.setBounds(x, y, w, h);\n g.setColor(Color.blue);\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n g.setColor(unselectedC);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if (hoverShape == manageSpiesBox)\n c0 = Color.yellow;\n String lbl = text(\"RACES_INTEL_BUREAU_MANAGE\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n private void drawAIDiplomaticEvents(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n // title area\n int x0 = x;\n int w0 = w;\n int y0 = y;\n int h0 = s30;\n if (incidentTitleBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x0, 0);\n Point2D ptEnd = new Point2D.Float(x0 + w0, 0);\n Color[] yesColors = { brownEdgeC, brownMidC, brownEdgeC };\n incidentTitleBackground = new LinearGradientPaint(ptStart, ptEnd, dist, yesColors);\n }\n g.setPaint(incidentTitleBackground);\n g.fillRect(x0, y0, w0, h0);\n // title\n g.setFont(narrowFont(20));\n String year = UserPreferences.displayYear() ? text(\"RACES_DIPLOMACY_EVENT_YEAR\") : text(\"RACES_DIPLOMACY_EVENT_TURN\");\n drawShadowedString(g, year, 1, x0 + s10, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(22));\n String title = text(\"RACES_DIPLOMACY_EVENT_TITLE\");\n int sw = g.getFontMetrics().stringWidth(title);\n drawShadowedString(g, title, 1, x0 + (w0 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(20));\n String effect = text(\"RACES_DIPLOMACY_EVENT_EFFECT\");\n int sw2 = g.getFontMetrics().stringWidth(effect);\n drawShadowedString(g, effect, 1, x0 + w0 - sw2 - s30, y0 + s23, Color.black, SystemPanel.whiteText);\n // data area\n g.setColor(RacesUI.darkBrown);\n int y1 = y0 + h0;\n int x1 = x0;\n int w1 = w0;\n int listH = h - h0;\n g.fillRect(x1, y1, w1, listH);\n g.setClip(x1, y1 + s1, w1, listH - s2);\n // draw vertical divider lines\n int x1a = x1 + s60;\n int x1b = x1 + w1 - s80;\n int x1c = x1 + w1 - s20;\n Stroke prev = g.getStroke();\n g.setStroke(stroke1);\n g.setColor(brownDividerC);\n g.drawLine(x1a, y1, x1a, y1 + listH);\n g.drawLine(x1b, y1, x1b, y1 + listH);\n g.drawLine(x1c, y1, x1c, y1 + listH);\n g.setStroke(prev);\n List incidents = new ArrayList<>();\n for (DiplomaticIncident inc : parent.selectedView().otherView().embassy().allIncidents()) {\n if (inc.currentSeverity() != 0)\n incidents.add(inc);\n }\n Collections.sort(incidents, DiplomaticIncident.DATE);\n int y2 = y1 - incidentY;\n int fullListH = 0;\n for (int i = 0; i < incidents.size(); i++) {\n DiplomaticIncident inc = incidents.get(i);\n int incidentH = drawAIIncident(g, inc, x1, y2, w1, s60, s80);\n fullListH += incidentH;\n y2 += incidentH;\n }\n incidentYMax = max(0, fullListH - listH);\n if (incidentYMax == 0)\n incidentScroller.setBounds(0, 0, 0, 0);\n else {\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + incidentYMax));\n int scrollX = x1 + w1 - scrollW - s2;\n int scrollY = (int) (y1 + (float) listH * incidentY / (incidentYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n incidentScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == incidentScroller) {\n prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n }\n g.setClip(null);\n incidentListBox.setBounds(x1, y1, w1, listH);\n if ((hoverShape == incidentListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(incidentListBox);\n g.setStroke(prev);\n }\n }\n\n private int drawAIIncident(Graphics g, DiplomaticIncident inc, int x, int y, int w, int leftM, int rightM) {\n String title = inc.title() + \":\";\n String sev = fmt(inc.currentSeverity(), 1);\n String desc = inc.description();\n g.setFont(narrowFont(18));\n int indent = g.getFontMetrics().stringWidth(title) + s5;\n g.setFont(narrowFont(15));\n List descLines = wrappedLines(g, desc, w - s20 - leftM - rightM, indent);\n int h0 = s7 + (s22 * descLines.size());\n // title\n int x1 = x + leftM + s10;\n int y1 = y + s8;\n g.setFont(narrowFont(22));\n g.setColor(Color.black);\n // description lines\n boolean firstLine = true;\n g.setFont(narrowFont(18));\n for (String line : descLines) {\n y1 += s17;\n g.setColor(Color.black);\n if (firstLine) {\n drawString(g, title, x1, y1);\n g.setFont(narrowFont(15));\n drawString(g, line, x1 + indent, y1);\n firstLine = false;\n } else\n drawString(g, line, x1, y1);\n }\n // year\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n String year = UserPreferences.displayYear() ? str(inc.dateOccurred()) : str(inc.turnOccurred());\n int sw0 = g.getFontMetrics().stringWidth(year);\n int x0 = x + (leftM - sw0) / 2;\n int y0 = y + s25;\n drawString(g, year, x0, y0);\n // severity\n int x2 = x + w - rightM;\n int w2 = s60;\n if (!parent.selectedEmpire().race().masksDiplomacy) {\n g.setFont(narrowFont(18));\n int sw = g.getFontMetrics().stringWidth(sev);\n int x2a = x2 + (w2 - sw) / 2;\n if (inc.currentSeverity() < 0)\n g.setColor(incidentRedC);\n else\n g.setColor(incidentGreenC);\n drawString(g, sev, x2a, y0);\n }\n g.setColor(brownDividerC);\n g.drawLine(x, y1 + s8, x + w - s20, y1 + s8);\n return h0;\n }\n\n private void drawAIDiplomacyBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_BUREAU\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean finalWar = player().viewForEmpire(emp).embassy().finalWar();\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (finalWar)\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC_FINAL\");\n else if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC_RANGE\");\n else {\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n }\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s7;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n embassyBox.setBounds(0, 0, 0, 0);\n if (!finalWar && !outOfRange)\n drawEmbassyButton(g, x + s20, y + h - s38, w - s40, s28);\n }\n\n private void drawAITradeSummary(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_TRADE_SUMMARY\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean finalWar = player().viewForEmpire(emp).embassy().finalWar();\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (finalWar)\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC_FINAL\");\n else if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC_RANGE\");\n else {\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n }\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s10;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n EmpireView view = player().viewForEmpire(emp);\n if (view == null)\n return;\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_DIPLOMACY_TRADE_TREATY\");\n int y2 = lines.size() <= 5 ? y0 + h - s65 : y0 + h - s55;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String s2 = text(\"RACES_DIPLOMACY_TRADE_AMT\", view.trade().level());\n int sw2 = g.getFontMetrics().stringWidth(s2);\n drawString(g, s2, x + w - s20 - sw2, y2);\n y2 += s22;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_DIPLOMACY_CURRENT_TRADE\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) view.trade().profit();\n g.setFont(narrowFont(16));\n s2 = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw2 = g.getFontMetrics().stringWidth(s2);\n drawString(g, s2, x + w - s20 - sw2, y2);\n }\n\n private void drawAIForeignRelations(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_FOREIGN_RELATIONS\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_FOREIGN_RANGE\");\n else\n desc = text(\"RACES_DIPLOMACY_FOREIGN_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s10;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n ", "post_mask_code": "\n int x2 = x + s10;\n int y2 = y1 + s10;\n int w2 = w - s20;\n int listH = y + h - y2 - s20;\n g.setColor(RacesUI.brown);\n g.fillRect(x2, y2, w2, listH);\n relationsListBox.setBounds(x2, y2, w2, listH);\n g.setClip(x2, y2 + s1, w2, listH - s2);\n int y3 = y2 - relationsY;\n int x3 = x2 + s10;\n g.setFont(narrowFont(18));\n g.setColor(SystemPanel.blackText);\n List contacts = emp.contacts();\n Collections.sort(contacts, EmpireView.PLAYER_LIST_ORDER);\n int rowH = s18;\n int fullListH = (contacts.size() * rowH) + s5;\n int rightM = fullListH <= listH ? s10 : s20;\n for (EmpireView contact : contacts) {\n if (contact.inEconomicRange()) {\n y3 += rowH;\n g.setFont(narrowFont(18));\n drawString(g, contact.empire().raceName(), x3, y3);\n g.setFont(narrowFont(15));\n String treaty = contact.embassy().treaty().status(player());\n int sw1 = g.getFontMetrics().stringWidth(treaty);\n int x3b = x2 + w2 - sw1 - rightM;\n drawString(g, treaty, x3b, y3);\n }\n }\n relationsYMax = max(0, fullListH - listH);\n if (relationsYMax == 0)\n relationsScroller.setBounds(0, 0, 0, 0);\n else {\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + relationsYMax));\n int scrollX = x2 + w2 - scrollW - s2;\n int scrollY = (int) (y2 + (float) listH * relationsY / (relationsYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n relationsScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == relationsScroller) {\n Stroke prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n }\n g.setClip(null);\n if ((hoverShape == relationsListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n Stroke prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(relationsListBox);\n g.setStroke(prev);\n }\n }\n\n private void drawEmbassyButton(Graphics2D g, int x, int y, int w, int h) {\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n if (view == null)\n return;\n embassyBox.setBounds(x, y, w, h);\n if (embassyBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x, 0);\n Point2D ptEnd = new Point2D.Float(x + w, 0);\n Color[] colors = { greenEdgeC, greenMidC, greenEdgeC };\n embassyBackground = new LinearGradientPaint(ptStart, ptEnd, dist, colors);\n Color[] colors2 = { brownEdgeC, brownMidC, brownEdgeC };\n embassyDisabledBackground = new LinearGradientPaint(ptStart, ptEnd, dist, colors2);\n }\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n if (view.diplomats())\n g.setPaint(embassyBackground);\n else\n g.setPaint(embassyDisabledBackground);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if ((hoverShape == embassyBox) && view.diplomats())\n c0 = Color.yellow;\n String lbl = view.embassy().diplomatGone() ? text(\"RACES_DIPLOMACY_CONTACT\") : text(\"RACES_DIPLOMACY_AUDIENCE\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n public void openEmbassy() {\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n if (view == null)\n return;\n if (view.embassy().diplomatGone()) {\n view.embassy().reopenEmbassy();\n parent.repaint();\n return;\n }\n if (!view.diplomats())\n return;\n DiplomaticMessage.show(parent.selectedEmpire().viewForEmpire(player()), DialogueManager.DIPLOMACY_MAIN_MENU);\n }\n\n public void openManageDiplomatsPane() {\n softClick();\n manageDiplomatsPane.init();\n enableGlassPane(manageDiplomatsPane);\n return;\n }\n\n public void openManageSpiesPane() {\n softClick();\n manageSpiesPane.init();\n enableGlassPane(manageSpiesPane);\n return;\n }\n\n private boolean increaseSliderValue() {\n int oldValue = player().internalSecurity();\n player().increaseInternalSecurity();\n return oldValue != player().internalSecurity();\n }\n\n private boolean decreaseSliderValue() {\n int oldValue = player().internalSecurity();\n player().decreaseInternalSecurity();\n return oldValue != player().internalSecurity();\n }\n\n @Override\n public void mouseWheelMoved(MouseWheelEvent e) {\n int count = e.getUnitsToScroll();\n if ((hoverShape == incidentListBox) || (hoverShape == incidentScroller)) {\n int prevY = incidentY;\n if (count < 0)\n incidentY = max(0, incidentY - s10);\n else\n incidentY = min(incidentYMax, incidentY + s10);\n if (incidentY != prevY)\n repaint(incidentListBox);\n return;\n } else if (hoverShape == buttonSlider) {\n boolean changed = count < 0 ? increaseSliderValue() : decreaseSliderValue();\n if (changed) {\n setValues();\n repaint();\n }\n } else if ((hoverShape == relationsListBox) || (hoverShape == relationsScroller)) {\n int prevY = relationsY;\n if (count < 0)\n relationsY = max(0, relationsY - s10);\n else\n relationsY = min(relationsYMax, relationsY + s10);\n if (relationsY != prevY)\n repaint(relationsListBox);\n return;\n }\n }\n\n @Override\n public void mouseDragged(MouseEvent e) {\n int x = e.getX();\n int y = e.getY();\n int dY = y - dragY;\n dragY = y;\n if (incidentScroller == hoverShape) {\n if ((y >= incidentListBox.y) || (y <= (incidentListBox.y + incidentListBox.height))) {\n int h = (int) incidentListBox.getHeight();\n int dListY = (int) ((float) dY * (h + incidentYMax) / h);\n if (dY < 0)\n incidentY = max(0, incidentY + dListY);\n else\n incidentY = min(incidentYMax, incidentY + dListY);\n }\n repaint(incidentListBox);\n return;\n } else if (incidentListBox == hoverShape) {\n if (incidentListBox.contains(x, y)) {\n int h = (int) incidentListBox.getHeight();\n int dListY = (int) (-(float) dY * (h + incidentYMax) / h);\n if (dListY < 0)\n incidentY = max(0, incidentY + dListY);\n else\n incidentY = min(incidentYMax, incidentY + dListY);\n }\n repaint(incidentListBox);\n return;\n } else if (relationsScroller == hoverShape) {\n if ((y >= relationsListBox.y) || (y <= (relationsListBox.y + relationsListBox.height))) {\n int h = (int) relationsListBox.getHeight();\n int dListY = (int) ((float) dY * (h + relationsYMax) / h);\n if (dY < 0)\n relationsY = max(0, relationsY + dListY);\n else\n relationsY = min(relationsYMax, relationsY + dListY);\n }\n repaint(relationsListBox);\n return;\n } else if (relationsListBox == hoverShape) {\n if (relationsListBox.contains(x, y)) {\n int h = (int) relationsListBox.getHeight();\n int dListY = (int) (-(float) dY * (h + relationsYMax) / h);\n if (dListY < 0)\n relationsY = max(0, relationsY + dListY);\n else\n relationsY = min(relationsYMax, relationsY + dListY);\n }\n repaint(relationsListBox);\n return;\n }\n }\n\n @Override\n public void mouseMoved(MouseEvent e) {\n int x = e.getX();\n int y = e.getY();\n Shape prevHover = hoverShape;\n hoverShape = null;\n if (buttonIncr.contains(x, y))\n hoverShape = buttonIncr;\n else if (buttonDecr.contains(x, y))\n hoverShape = buttonDecr;\n else if (buttonSlider.contains(x, y))\n hoverShape = buttonSlider;\n else if (embassyBox.contains(x, y))\n hoverShape = embassyBox;\n else if (incidentScroller.contains(x, y))\n hoverShape = incidentScroller;\n else if (incidentListBox.contains(x, y))\n hoverShape = incidentListBox;\n else if (relationsScroller.contains(x, y))\n hoverShape = relationsScroller;\n else if (relationsListBox.contains(x, y))\n hoverShape = relationsListBox;\n else if (manageSpiesBox.contains(x, y))\n hoverShape = manageSpiesBox;\n else if (manageDiplomatsBox.contains(x, y))\n hoverShape = manageDiplomatsBox;\n if (hoverShape != prevHover)\n repaint();\n }\n\n @Override\n public void mouseClicked(MouseEvent e) {\n }\n\n @Override\n public void mousePressed(MouseEvent e) {\n dragY = e.getY();\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n dragY = 0;\n if (e.getButton() > 3)\n return;\n if (hoverShape == null)\n return;\n Empire emp = parent.selectedEmpire();\n if (hoverShape == embassyBox) {\n openEmbassy();\n return;\n } else if (hoverShape == manageSpiesBox) {\n openManageSpiesPane();\n return;\n } else if (hoverShape == manageDiplomatsBox) {\n openManageDiplomatsPane();\n return;\n }\n if (hoverShape == buttonIncr) {\n boolean changed = increaseSliderValue();\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n } else if (hoverShape == buttonDecr) {\n boolean changed = decreaseSliderValue();\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n } else if (hoverShape == buttonSlider) {\n float pct = (float) ((e.getX() - buttonSlider.getMinX()) / buttonSlider.getWidth());\n boolean changed = false;\n if (emp.isPlayer()) {\n int oldSec = emp.internalSecurity();\n emp.securityAllocation(pct);\n changed = oldSec != emp.internalSecurity();\n }\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n }\n }\n\n @Override\n public void mouseEntered(MouseEvent e) {\n }\n\n @Override\n public void mouseExited(MouseEvent e) {\n if (hoverShape != null) {\n hoverShape = null;\n repaint();\n }\n }\n}\n"} {"task_id": "Java_2055", "language": "Java", "task_type": "for_statement", "source_file": "java/github/rayfowler/rotp-public/src/rotp/ui/races/RacesDiplomacyUI.java", "mask_start_position": 18345, "mask_end_position": 18603, "canonical_solution": "for (int i = 0; i < incidents.size(); i++) {\n DiplomaticIncident inc = incidents.get(i);\n int incidentH = drawPlayerIncident(g, inc, x0, y2, w0, w1, w2, w3, w4);\n fullListH += incidentH;\n y2 += incidentH;\n }", "pre_mask_code": "/*\n * \n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage rotp.ui.races;\n\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.Image;\nimport java.awt.LinearGradientPaint;\nimport java.awt.Polygon;\nimport java.awt.Rectangle;\nimport java.awt.Shape;\nimport java.awt.Stroke;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseListener;\nimport java.awt.event.MouseMotionListener;\nimport java.awt.event.MouseWheelEvent;\nimport java.awt.event.MouseWheelListener;\nimport java.awt.geom.Point2D;\nimport java.awt.geom.RoundRectangle2D;\nimport java.awt.image.BufferedImage;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport rotp.model.empires.DiplomaticTreaty;\nimport rotp.model.empires.Empire;\nimport rotp.model.empires.EmpireView;\nimport rotp.model.empires.TreatyAlliance;\nimport rotp.model.incidents.DiplomaticIncident;\nimport rotp.ui.BasePanel;\nimport rotp.ui.UserPreferences;\nimport rotp.ui.diplomacy.DialogueManager;\nimport rotp.ui.diplomacy.DiplomaticMessage;\nimport rotp.ui.main.MainUI;\nimport rotp.ui.main.SystemPanel;\nimport static rotp.ui.races.RacesIntelligenceUI.sliderC;\n\npublic final class RacesDiplomacyUI extends BasePanel implements MouseListener, MouseMotionListener, MouseWheelListener {\n\n private static final long serialVersionUID = 1L;\n\n public static final String[] relationIds = new String[] { \"RELATIONS_FEUD\", \"RELATIONS_HATE\", \"RELATIONS_DISCORD\", \"RELATIONS_TROUBLED\", \"RELATIONS_TENSE\", \"RELATIONS_RESTLESS\", \"RELATIONS_WARY\", \"RELATIONS_UNEASE\", \"RELATIONS_NEUTRAL\", \"RELATIONS_RELAXED\", \"RELATIONS_AMIABLE\", \"RELATIONS_CALM\", \"RELATIONS_AFFABLE\", \"RELATIONS_PEACEFUL\", \"RELATIONS_FRIENDLY\", \"RELATIONS_UNITY\", \"RELATIONS_HARMONY\" };\n\n private static final Color unselectedC = new Color(112, 85, 68);\n\n private final Color greenEdgeC = new Color(44, 59, 30);\n\n private final Color greenMidC = new Color(70, 93, 48);\n\n private final Color brownEdgeC = new Color(101, 70, 50);\n\n private final Color brownMidC = new Color(161, 111, 78);\n\n private final Color brownDividerC = new Color(136, 115, 96);\n\n private final Color incidentRedC = new Color(112, 0, 0);\n\n private final Color incidentGreenC = new Color(0, 63, 32);\n\n private final RacesUI parent;\n\n private final ManageDiplomatsUI manageDiplomatsPane;\n\n private final ManageSpiesUI manageSpiesPane;\n\n int incidentY, incidentYMax;\n\n int relationsY, relationsYMax;\n\n int dragY;\n\n private LinearGradientPaint incidentTitleBackground;\n\n private LinearGradientPaint backGradient;\n\n private LinearGradientPaint embassyBackground, embassyDisabledBackground;\n\n private final Rectangle embassyBox = new Rectangle();\n\n private final Rectangle incidentListBox = new Rectangle();\n\n private final Rectangle incidentScroller = new Rectangle();\n\n private final Rectangle relationsListBox = new Rectangle();\n\n private final Rectangle relationsScroller = new Rectangle();\n\n private final Rectangle manageDiplomatsBox = new Rectangle();\n\n private final Rectangle manageSpiesBox = new Rectangle();\n\n Polygon buttonIncr = new Polygon();\n\n Polygon buttonDecr = new Polygon();\n\n Rectangle buttonSlider = new Rectangle();\n\n private float internalSecurityCost = 0;\n\n private float externalSpyingCost = 0;\n\n int[] ptX = new int[3];\n\n int[] ptY = new int[3];\n\n private final HashMap incidentMap = new HashMap<>();\n\n private Shape hoverShape;\n\n public RacesDiplomacyUI(RacesUI p) {\n parent = p;\n manageDiplomatsPane = new ManageDiplomatsUI(p);\n manageSpiesPane = new ManageSpiesUI(p);\n initModel();\n }\n\n @Override\n public void drawTexture(Graphics g) {\n }\n\n @Override\n public String textureName() {\n return TEXTURE_BROWN;\n }\n\n public void init() {\n setValues();\n }\n\n public void changedEmpire() {\n setValues();\n }\n\n private void setValues() {\n incidentY = 0;\n relationsY = 0;\n if (parent.selectedEmpire().isPlayer()) {\n internalSecurityCost = player().empireInternalSecurityCost();\n externalSpyingCost = player().empireExternalSpyingCost();\n }\n }\n\n @Override\n public void paintComponent(Graphics g0) {\n super.paintComponent(g0);\n Graphics2D g = (Graphics2D) g0;\n int w = getWidth();\n int h = getHeight();\n relationsListBox.setBounds(0, 0, 0, 0);\n relationsScroller.setBounds(0, 0, 0, 0);\n manageDiplomatsBox.setBounds(0, 0, 0, 0);\n manageSpiesBox.setBounds(0, 0, 0, 0);\n buttonIncr.reset();\n buttonDecr.reset();\n if (backGradient == null) {\n Point2D start = new Point2D.Float(0, getHeight() / 2);\n Point2D end = new Point2D.Float(0, getHeight());\n float[] dist = { 0.0f, 1.0f };\n Color[] colors = { RacesUI.darkerBrown, RacesUI.gradientBottom };\n backGradient = new LinearGradientPaint(start, end, dist, colors);\n }\n g.setPaint(backGradient);\n g.fillRect(0, h / 2, w, h / 2);\n if (parent.selectedEmpire().isPlayer())\n paintPlayerData(g);\n else\n paintAIData(g);\n }\n\n private void initModel() {\n setBackground(RacesUI.darkerBrown);\n setBorder(newEmptyBorder(5, 5, 5, 5));\n addMouseMotionListener(this);\n addMouseListener(this);\n addMouseWheelListener(this);\n }\n\n private void paintPlayerData(Graphics2D g) {\n Empire emp = parent.selectedEmpire();\n int w = getWidth();\n int h = getHeight();\n int s200 = scaled(200);\n int s210 = scaled(210);\n int s215 = scaled(215);\n int s245 = scaled(245);\n int s260 = scaled(260);\n int s370 = scaled(370);\n int s435 = scaled(435);\n int x0 = s20;\n int x1 = w - scaled(299);\n int w0 = x1 - x0 - s20;\n int w1 = scaled(279);\n drawRaceIconBase(g, emp, s55, s25, s210, s210);\n drawPlayerBaseInfo(g, emp, s260, s80, s370, scaled(130));\n drawPlayerDiplomaticEvents(g, emp, x0, s245, w0, h - s245 - s10);\n drawPlayerDiplomacyBureau(g, emp, x1, s10, w1, s200);\n drawPlayerCounterIntelligenceBureau(g, emp, x1, s215, w1, s215);\n drawPlayerIntelligenceBureau(g, emp, x1, s435, w1, s200);\n if (UserPreferences.texturesInterface())\n drawTexture(g, 0, 0, w, h);\n drawRaceIcon(g, emp, s60, s30, s200, s200);\n drawEmpireName(g, emp, s260, s30, s370, s50);\n }\n\n private void paintAIData(Graphics2D g) {\n Empire emp = parent.selectedEmpire();\n int w = getWidth();\n int h = getHeight();\n int s200 = scaled(200);\n int s135 = scaled(135);\n int s150 = scaled(150);\n int s175 = scaled(175);\n int s210 = scaled(210);\n int s245 = scaled(245);\n int s260 = scaled(260);\n int s295 = scaled(295);\n int s330 = scaled(330);\n int s370 = scaled(370);\n int x0 = s20;\n int x1 = w - scaled(299);\n int w0 = x1 - x0 - s20;\n int w1 = scaled(279);\n drawRaceIconBase(g, emp, s55, s25, s210, s210);\n drawAIBaseInfo(g, emp, s260, s80, s370, scaled(130));\n drawRelationsMeter(g, emp, x0, s245, w0, s40);\n drawAIDiplomaticEvents(g, emp, x0, s295, w0, h - s295 - s10);\n drawAIDiplomacyBureau(g, emp, x1, s10, w1, s135);\n drawAITradeSummary(g, emp, x1, s150, w1, s175);\n drawAIForeignRelations(g, emp, x1, s330, w1, h - s330 - s10);\n if (UserPreferences.texturesInterface())\n drawTexture(g, 0, 0, w, h);\n drawRaceIcon(g, emp, s60, s30, s200, s200);\n drawEmpireName(g, emp, s260, s30, s370, s50);\n }\n\n private void drawRaceIconBase(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n Shape rect = new RoundRectangle2D.Float(x, y, w, h, w / 8, h / 8);\n g.fill(rect);\n }\n\n private void drawRaceIcon(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(Color.black);\n Shape rect = new RoundRectangle2D.Float(x, y, w, h, w / 8, h / 8);\n g.fill(rect);\n BufferedImage backImg = parent.raceIconBackImg();\n g.drawImage(backImg, x, y, null);\n int x1 = x + w / 10;\n int w1 = w * 8 / 10;\n int y1 = y + h / 10;\n int h1 = h * 8 / 10;\n Image img = emp.isPlayer() ? emp.race().flagPact() : player().viewForEmpire(emp).flag();\n int imgH = img.getHeight(null);\n int imgW = img.getWidth(null);\n g.drawImage(img, x1, y1, x1 + w1, y1 + h1, 0, 0, imgW, imgH, null);\n }\n\n private void drawEmpireName(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(SystemPanel.orangeText);\n g.setFont(narrowFont(32));\n drawString(g, emp.name(), x + s10, y + h - s15);\n }\n\n private void drawPlayerBaseInfo(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n int lineH = s30;\n int y1 = y + lineH - s5;\n int y2 = y1 + lineH;\n int y3 = y2 + lineH;\n int y4 = y3 + lineH;\n int x0 = x + s20;\n g.setFont(narrowFont(22));\n Color textC = SystemPanel.whiteText;\n drawShadowedString(g, text(\"RACES_DIPLOMACY_HOMEWORLD\"), 1, x0, y1, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_LEADER\"), 1, x0, y2, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_CURRENT_TRADE\"), 1, x0, y3, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_TOTAL_TRADE\"), 1, x0, y4, SystemPanel.blackText, textC);\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n String s = emp.sv.name(emp.capitalSysId());\n int sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y1);\n s = text(\"TITLE_LEADERNAME\", emp.labels().text(\"_nameTitle\"), emp.leader().name());\n s = emp.replaceTokens(s, \"alien\");\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n int amt = (int) player().totalTradeIncome();\n s = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y3);\n amt = player().totalTradeTreaties();\n s = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y4);\n }\n\n private void drawAIBaseInfo(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n int lineH = s30;\n int y1 = y + lineH - s5;\n int y2 = y1 + lineH;\n int y3 = y2 + lineH;\n int y4 = y3 + lineH;\n int x0 = x + s20;\n g.setFont(narrowFont(22));\n Color textC = SystemPanel.whiteText;\n drawShadowedString(g, text(\"RACES_DIPLOMACY_HOMEWORLD\"), 1, x0, y1, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_LEADER\"), 1, x0, y2, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_CHARACTER\"), 1, x0, y3, SystemPanel.blackText, textC);\n drawShadowedString(g, text(\"RACES_DIPLOMACY_STATUS\"), 1, x0, y4, SystemPanel.blackText, textC);\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n String s = emp.sv.name(emp.capitalSysId());\n int sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y1);\n s = text(\"TITLE_LEADERNAME\", emp.race().text(\"_nameTitle\"), emp.leader().name());\n s = emp.replaceTokens(s, \"alien\");\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n s = text(\"LEADER_PERSONALITY_FORMAT\", emp.leader().personality(), emp.leader().objective());\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y3);\n EmpireView view = player().viewForEmpire(emp);\n DiplomaticTreaty treaty = view.embassy().treaty();\n boolean isAlly = treaty.isAlliance();\n int starW = s10;\n int offset = isAlly ? (starW * 5) + s5 : 0;\n s = treaty.status(player());\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - offset - sw, y4);\n if (isAlly) {\n TreatyAlliance alliance = (TreatyAlliance) treaty;\n int x1 = x + w - s20 - offset + s5;\n parent.drawAllianceStars(g, x1, y4 - s3, alliance.standing(player()), starW);\n }\n }\n\n private void drawRelationsMeter(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n EmpireView view = player().viewForEmpire(emp);\n if (view == null)\n return;\n int x0 = x + s10;\n int y0 = y + h - s12;\n g.setFont(narrowFont(24));\n String str = text(\"RACES_DIPLOMACY_RELATIONS_METER\");\n this.drawShadowedString(g, str, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n int leftW = g.getFontMetrics().stringWidth(str);\n if (emp.race().masksDiplomacy) {\n g.setFont(narrowFont(15));\n g.setColor(SystemPanel.blackText);\n String str2 = text(\"RACES_DIPLOMACY_RELATIONS_UNKNOWN\");\n str2 = emp.replaceTokens(str2, \"alien\");\n List lines = this.wrappedLines(g, str2, w - s60 - leftW);\n int x1 = x0 + leftW + s40;\n int y1 = lines.size() == 1 ? y0 : y0 - s10;\n for (String line : lines) {\n drawString(g, line, x1, y1);\n y1 += s15;\n }\n return;\n }\n g.setFont(narrowFont(20));\n g.setColor(SystemPanel.blackText);\n float relations = view.otherView().embassy().relations();\n // which relation key display to use\n float pctRel = (relations + 100) / 200.0f;\n float sizeRelId = 1.0f / relationIds.length;\n int i = (int) (pctRel / sizeRelId);\n i = bounds(0, i, relationIds.length - 1);\n String rel = text(relationIds[i]);\n int rightW = g.getFontMetrics().stringWidth(rel);\n int x1 = x + w - rightW - s20;\n drawString(g, rel, x1, y0);\n int x2 = x0 + leftW + s30;\n int w2 = x + w - x2 - rightW - s30;\n int y2 = y + s12;\n int h2 = h - s15;\n parent.drawRelationsBar(g, emp, x2, y2, w2, h2, s16, s8);\n }\n\n private void drawPlayerDiplomaticEvents(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n // title area\n int x0 = x;\n int w0 = w;\n int y0 = y;\n int h0 = s30;\n if (incidentTitleBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x0, 0);\n Point2D ptEnd = new Point2D.Float(x0 + w0, 0);\n Color[] yesColors = { brownEdgeC, brownMidC, brownEdgeC };\n incidentTitleBackground = new LinearGradientPaint(ptStart, ptEnd, dist, yesColors);\n }\n g.setPaint(incidentTitleBackground);\n g.fillRect(x0, y0, w0, h0);\n // year or turn\n g.setFont(narrowFont(20));\n int x1 = x0;\n int w1 = s60;\n String year = UserPreferences.displayYear() ? text(\"RACES_DIPLOMACY_EVENT_YEAR\") : text(\"RACES_DIPLOMACY_EVENT_TURN\");\n int sw = g.getFontMetrics().stringWidth(year);\n drawShadowedString(g, year, 1, x0 + (w1 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // race\n g.setFont(narrowFont(20));\n int x2 = x1 + w1;\n int w2 = s100;\n String race = text(\"RACES_DIPLOMACY_EVENT_RACE\");\n sw = g.getFontMetrics().stringWidth(race);\n drawShadowedString(g, race, 1, x2 + (w2 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // scrollboar\n int w5 = s20;\n int x5 = x0 + w0 - w5;\n // effect\n g.setFont(narrowFont(20));\n String effect = text(\"RACES_DIPLOMACY_EVENT_EFFECT\");\n sw = g.getFontMetrics().stringWidth(effect);\n int w4 = s60;\n int x4 = x5 - w4;\n drawShadowedString(g, effect, 1, x4 + (w4 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(22));\n int x3 = x2 + w2;\n int w3 = x4 - x3;\n String title = text(\"RACES_DIPLOMACY_EVENT_TITLE\");\n sw = g.getFontMetrics().stringWidth(title);\n drawShadowedString(g, title, 1, x3 + (w3 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n // data area\n g.setColor(RacesUI.darkBrown);\n int y1 = y0 + h0;\n int listH = h - h0;\n g.fillRect(x0, y1, w0, listH);\n g.setClip(x0, y1 + s1, w0, listH - s2);\n // draw vertical divider lines\n Stroke prev = g.getStroke();\n g.setStroke(stroke1);\n g.setColor(brownDividerC);\n g.drawLine(x2, y1, x2, y1 + listH);\n g.drawLine(x3, y1, x3, y1 + listH);\n g.drawLine(x4, y1, x4, y1 + listH);\n g.drawLine(x5, y1, x5, y1 + listH);\n g.setStroke(prev);\n List incidents = new ArrayList<>();\n incidentMap.clear();\n for (EmpireView view : player().contacts()) {\n for (DiplomaticIncident inc : view.otherView().embassy().allIncidents()) {\n if ((inc.currentSeverity() != 0) && inc.triggeredByAction()) {\n incidents.add(inc);\n incidentMap.put(inc, view.empire());\n }\n }\n }\n Collections.sort(incidents, DiplomaticIncident.DATE);\n int y2 = y1 - incidentY;\n int fullListH = 0;\n ", "post_mask_code": "\n incidentYMax = max(0, fullListH - listH);\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + incidentYMax));\n int scrollX = x + w - scrollW - s4;\n int scrollY = (int) (y1 + (float) listH * incidentY / (incidentYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n incidentScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == incidentScroller) {\n prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n g.setClip(null);\n incidentListBox.setBounds(x0, y1, w0, listH);\n if ((hoverShape == incidentListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(incidentListBox);\n g.setStroke(prev);\n }\n }\n\n private int drawPlayerIncident(Graphics g, DiplomaticIncident inc, int x, int y, int w, int w1, int w2, int w3, int w4) {\n String title = inc.title() + \":\";\n String sev = fmt(inc.currentSeverity(), 1);\n String desc = inc.description();\n g.setFont(narrowFont(18));\n int indent = g.getFontMetrics().stringWidth(title) + s5;\n g.setFont(narrowFont(15));\n List descLines = wrappedLines(g, desc, w3 - s15, indent);\n int h0 = s7 + (s22 * descLines.size());\n // title\n int x1 = x;\n int x2 = x1 + w1;\n int x3 = x2 + w2;\n int x4 = x3 + w3;\n int y1 = y + s8;\n // year or turn\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n String year = UserPreferences.displayYear() ? str(inc.dateOccurred()) : str(inc.turnOccurred());\n int sw = g.getFontMetrics().stringWidth(year);\n int x0 = x1 + (w1 - sw) / 2;\n int y0 = y + s25;\n drawString(g, year, x0, y0);\n // race\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n Empire otherEmpire = incidentMap.get(inc);\n String race = otherEmpire.raceName();\n sw = g.getFontMetrics().stringWidth(race);\n x0 = x2 + (w2 - sw) / 2;\n y0 = y + s25;\n drawString(g, race, x0, y0);\n boolean firstLine = true;\n g.setFont(narrowFont(18));\n for (String line : descLines) {\n y1 += s17;\n g.setColor(Color.black);\n if (firstLine) {\n drawString(g, title, x3 + s10, y1);\n g.setFont(narrowFont(15));\n drawString(g, line, x3 + s10 + indent, y1);\n firstLine = false;\n } else\n drawString(g, line, x3 + s10, y1);\n }\n // severity\n if (!otherEmpire.race().masksDiplomacy) {\n g.setFont(narrowFont(18));\n sw = g.getFontMetrics().stringWidth(sev);\n x0 = x4 + (w4 - sw) / 2;\n if (inc.currentSeverity() < 0)\n g.setColor(incidentRedC);\n else\n g.setColor(incidentGreenC);\n drawString(g, sev, x0, y0);\n }\n g.setColor(brownDividerC);\n g.drawLine(x1, y1 + s12, x + w - s20, y1 + s12);\n return h0;\n }\n\n private void drawPlayerDiplomacyBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n List views = player().contacts();\n int recalls = 0;\n for (EmpireView v : views) {\n if (v.embassy().diplomatGone())\n recalls++;\n }\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_BUREAU\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_DIPLOMACY_BUREAU_DESC1\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_DIPLOMACY_KNOWN_EMPIRES\");\n int y2 = y0 + s85;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String str2 = str(views.size());\n int sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_DIPLOMACY_RECALLED_DIPLOMAT\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) 0;\n g.setFont(narrowFont(16));\n str2 = str(recalls);\n sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n drawManageDiplomatsButton(g, x + s20, y + h - s45, w - s40, s25);\n }\n\n private void drawPlayerCounterIntelligenceBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_COUNTER_BUREAU\");\n int fontSize = scaledFont(g, title, w - s20, 24, 20);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_DIPLOMACY_COUNTER_DESC\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_INTEL_SECURITY_BONUS\");\n int y2 = y0 + s70;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n int amt = (int) (100 * player().totalInternalSecurityPct());\n String s = amt == 0 ? text(\"RACES_INTEL_SECURITY_BONUS_NONE\") : text(\"RACES_INTEL_SECURITY_BONUS_AMT\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_INTEL_TOTAL_SPENDING\");\n drawString(g, spending, x + s20, y2);\n g.setFont(narrowFont(16));\n amt = (int) internalSecurityCost;\n s = text(\"RACES_INTEL_SPENDING_ANNUAL\", str(amt));\n sw = g.getFontMetrics().stringWidth(s);\n drawString(g, s, x + w - s20 - sw, y2);\n g.setFont(narrowFont(15));\n desc = text(\"RACES_DIPLOMACY_COUNTER_DESC2\");\n lines = wrappedLines(g, desc, w - s30);\n int y3 = y + h - s20 - (s16 * 3);\n for (String line : lines) {\n drawString(g, line, x + s20, y3);\n y3 += s16;\n }\n g.setFont(narrowFont(16));\n int y4 = y + h - s20;\n String taxStr = text(\"RACES_INTEL_SECURITY_TAX\");\n drawString(g, taxStr, x + s20, y4);\n int sw4 = g.getFontMetrics().stringWidth(taxStr);\n // draw string on right for pct\n String cost = text(\"RACES_INTEL_PERCENT_AMT\", (int) (player().internalSecurityCostPct() * 100));\n sw = g.getFontMetrics().stringWidth(cost);\n drawString(g, cost, x + w - s20 - sw, y4);\n // need maxwidth so slider doesn't move as cost pct changes\n String maxWidthStr = text(\"RACES_INTEL_PERCENT_AMT\", 10);\n sw = g.getFontMetrics().stringWidth(maxWidthStr);\n int sliderW = w - sw - sw4 - s80;\n int sliderH = s16;\n drawSecuritySliderBar(g, x + s20 + sw4, y4 - sliderH + s3, sliderW, sliderH);\n }\n\n private void drawSecuritySliderBar(Graphics2D g, int x, int y, int w, int h) {\n // draw spending bar\n // height of bar\n int h1 = h;\n // width of bar\n int w1 = w;\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n float pct = view == null ? player().internalSecurityPct() : view.spies().allocationPct();\n // width of spending\n int w1a = (int) (pct * w1);\n int y1 = y + ((h - h1) / 2);\n int x1 = x + s20;\n g.setColor(Color.black);\n g.fillRect(x1, y1, w1, h1);\n g.setColor(sliderC);\n g.fillRect(x1, y1, w1a, h1);\n buttonSlider.setBounds(x1, y1, w1, h1);\n if (hoverShape == buttonSlider) {\n g.setColor(Color.yellow);\n Stroke prev = g.getStroke();\n g.setStroke(stroke2);\n g.drawRect(x1, y1, w1, h1);\n g.setStroke(prev);\n }\n int sz = h1 / 2;\n // draw left/decr button\n ptX[0] = x1 - s3 - sz;\n ptX[1] = ptX[0] + sz;\n ptX[2] = ptX[0] + sz;\n ptY[0] = y + (h / 2);\n ptY[1] = ptY[0] - sz;\n ptY[2] = ptY[0] + sz;\n Color buttonC = hoverShape == buttonDecr ? SystemPanel.yellowText : Color.black;\n buttonDecr.reset();\n for (int i = 0; i < ptX.length; i++) buttonDecr.addPoint(ptX[i], ptY[i]);\n drawShadedPolygon(g, ptX, ptY, buttonC, s1, -s1);\n // draw right/incr button\n ptX[0] = x1 + w1 + sz + s3;\n ptX[1] = ptX[0] - sz;\n ptX[2] = ptX[0] - sz;\n ptY[0] = y + (h / 2);\n ptY[1] = ptY[0] - sz;\n ptY[2] = ptY[0] + sz;\n buttonIncr.reset();\n for (int i = 0; i < ptX.length; i++) buttonIncr.addPoint(ptX[i], ptY[i]);\n buttonC = hoverShape == buttonIncr ? SystemPanel.yellowText : Color.black;\n drawShadedPolygon(g, ptX, ptY, buttonC, s1, -s1);\n if (!parent.selectedEmpire().isPlayer()) {\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(15));\n String spyCost = text(\"RACES_INTEL_SPENDING_ANNUAL\", (int) externalSpyingCost);\n int sw1 = g.getFontMetrics().stringWidth(spyCost);\n int xa = buttonSlider.x + ((buttonSlider.width - sw1) / 2);\n int ya = buttonSlider.y + buttonSlider.height - s4;\n drawString(g, spyCost, xa, ya);\n }\n }\n\n private void drawPlayerIntelligenceBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_INTEL_BUREAU_TITLE\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc = text(\"RACES_INTEL_BUREAU_DESC\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s5;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s20, y1);\n }\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_INTEL_BUREAU_SPIES\");\n int y2 = y + h - s85;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String str2 = str(player().totalActiveSpies());\n int sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_INTEL_BUREAU_SPENDING\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) externalSpyingCost;\n g.setFont(narrowFont(16));\n str2 = amt == 0 ? text(\"RACES_INTEL_SECURITY_BONUS_NONE\") : text(\"RACES_INTEL_SPENDING_ANNUAL\", str(amt));\n sw2 = g.getFontMetrics().stringWidth(str2);\n drawString(g, str2, x + w - s20 - sw2, y2);\n y2 += s20;\n drawManageSpiesButton(g, x + s20, y2, w - s40, s25);\n }\n\n private void drawManageDiplomatsButton(Graphics2D g, int x, int y, int w, int h) {\n manageDiplomatsBox.setBounds(x, y, w, h);\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n g.setColor(unselectedC);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if (hoverShape == manageDiplomatsBox)\n c0 = Color.yellow;\n String lbl = text(\"RACES_DIPLOMACY_MANAGE_DIPLOMATS\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n private void drawManageSpiesButton(Graphics2D g, int x, int y, int w, int h) {\n manageSpiesBox.setBounds(x, y, w, h);\n g.setColor(Color.blue);\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n g.setColor(unselectedC);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if (hoverShape == manageSpiesBox)\n c0 = Color.yellow;\n String lbl = text(\"RACES_INTEL_BUREAU_MANAGE\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n private void drawAIDiplomaticEvents(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n // title area\n int x0 = x;\n int w0 = w;\n int y0 = y;\n int h0 = s30;\n if (incidentTitleBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x0, 0);\n Point2D ptEnd = new Point2D.Float(x0 + w0, 0);\n Color[] yesColors = { brownEdgeC, brownMidC, brownEdgeC };\n incidentTitleBackground = new LinearGradientPaint(ptStart, ptEnd, dist, yesColors);\n }\n g.setPaint(incidentTitleBackground);\n g.fillRect(x0, y0, w0, h0);\n // title\n g.setFont(narrowFont(20));\n String year = UserPreferences.displayYear() ? text(\"RACES_DIPLOMACY_EVENT_YEAR\") : text(\"RACES_DIPLOMACY_EVENT_TURN\");\n drawShadowedString(g, year, 1, x0 + s10, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(22));\n String title = text(\"RACES_DIPLOMACY_EVENT_TITLE\");\n int sw = g.getFontMetrics().stringWidth(title);\n drawShadowedString(g, title, 1, x0 + (w0 - sw) / 2, y0 + s23, Color.black, SystemPanel.whiteText);\n g.setFont(narrowFont(20));\n String effect = text(\"RACES_DIPLOMACY_EVENT_EFFECT\");\n int sw2 = g.getFontMetrics().stringWidth(effect);\n drawShadowedString(g, effect, 1, x0 + w0 - sw2 - s30, y0 + s23, Color.black, SystemPanel.whiteText);\n // data area\n g.setColor(RacesUI.darkBrown);\n int y1 = y0 + h0;\n int x1 = x0;\n int w1 = w0;\n int listH = h - h0;\n g.fillRect(x1, y1, w1, listH);\n g.setClip(x1, y1 + s1, w1, listH - s2);\n // draw vertical divider lines\n int x1a = x1 + s60;\n int x1b = x1 + w1 - s80;\n int x1c = x1 + w1 - s20;\n Stroke prev = g.getStroke();\n g.setStroke(stroke1);\n g.setColor(brownDividerC);\n g.drawLine(x1a, y1, x1a, y1 + listH);\n g.drawLine(x1b, y1, x1b, y1 + listH);\n g.drawLine(x1c, y1, x1c, y1 + listH);\n g.setStroke(prev);\n List incidents = new ArrayList<>();\n for (DiplomaticIncident inc : parent.selectedView().otherView().embassy().allIncidents()) {\n if (inc.currentSeverity() != 0)\n incidents.add(inc);\n }\n Collections.sort(incidents, DiplomaticIncident.DATE);\n int y2 = y1 - incidentY;\n int fullListH = 0;\n for (int i = 0; i < incidents.size(); i++) {\n DiplomaticIncident inc = incidents.get(i);\n int incidentH = drawAIIncident(g, inc, x1, y2, w1, s60, s80);\n fullListH += incidentH;\n y2 += incidentH;\n }\n incidentYMax = max(0, fullListH - listH);\n if (incidentYMax == 0)\n incidentScroller.setBounds(0, 0, 0, 0);\n else {\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + incidentYMax));\n int scrollX = x1 + w1 - scrollW - s2;\n int scrollY = (int) (y1 + (float) listH * incidentY / (incidentYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n incidentScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == incidentScroller) {\n prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n }\n g.setClip(null);\n incidentListBox.setBounds(x1, y1, w1, listH);\n if ((hoverShape == incidentListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(incidentListBox);\n g.setStroke(prev);\n }\n }\n\n private int drawAIIncident(Graphics g, DiplomaticIncident inc, int x, int y, int w, int leftM, int rightM) {\n String title = inc.title() + \":\";\n String sev = fmt(inc.currentSeverity(), 1);\n String desc = inc.description();\n g.setFont(narrowFont(18));\n int indent = g.getFontMetrics().stringWidth(title) + s5;\n g.setFont(narrowFont(15));\n List descLines = wrappedLines(g, desc, w - s20 - leftM - rightM, indent);\n int h0 = s7 + (s22 * descLines.size());\n // title\n int x1 = x + leftM + s10;\n int y1 = y + s8;\n g.setFont(narrowFont(22));\n g.setColor(Color.black);\n // description lines\n boolean firstLine = true;\n g.setFont(narrowFont(18));\n for (String line : descLines) {\n y1 += s17;\n g.setColor(Color.black);\n if (firstLine) {\n drawString(g, title, x1, y1);\n g.setFont(narrowFont(15));\n drawString(g, line, x1 + indent, y1);\n firstLine = false;\n } else\n drawString(g, line, x1, y1);\n }\n // year\n g.setFont(narrowFont(18));\n g.setColor(Color.black);\n String year = UserPreferences.displayYear() ? str(inc.dateOccurred()) : str(inc.turnOccurred());\n int sw0 = g.getFontMetrics().stringWidth(year);\n int x0 = x + (leftM - sw0) / 2;\n int y0 = y + s25;\n drawString(g, year, x0, y0);\n // severity\n int x2 = x + w - rightM;\n int w2 = s60;\n if (!parent.selectedEmpire().race().masksDiplomacy) {\n g.setFont(narrowFont(18));\n int sw = g.getFontMetrics().stringWidth(sev);\n int x2a = x2 + (w2 - sw) / 2;\n if (inc.currentSeverity() < 0)\n g.setColor(incidentRedC);\n else\n g.setColor(incidentGreenC);\n drawString(g, sev, x2a, y0);\n }\n g.setColor(brownDividerC);\n g.drawLine(x, y1 + s8, x + w - s20, y1 + s8);\n return h0;\n }\n\n private void drawAIDiplomacyBureau(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_BUREAU\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean finalWar = player().viewForEmpire(emp).embassy().finalWar();\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (finalWar)\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC_FINAL\");\n else if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC_RANGE\");\n else {\n desc = text(\"RACES_DIPLOMACY_BUREAU_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n }\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s7;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n embassyBox.setBounds(0, 0, 0, 0);\n if (!finalWar && !outOfRange)\n drawEmbassyButton(g, x + s20, y + h - s38, w - s40, s28);\n }\n\n private void drawAITradeSummary(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_TRADE_SUMMARY\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean finalWar = player().viewForEmpire(emp).embassy().finalWar();\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (finalWar)\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC_FINAL\");\n else if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC_RANGE\");\n else {\n desc = text(\"RACES_DIPLOMACY_TRADE_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n }\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s10;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n EmpireView view = player().viewForEmpire(emp);\n if (view == null)\n return;\n g.setFont(narrowFont(18));\n String spies = text(\"RACES_DIPLOMACY_TRADE_TREATY\");\n int y2 = lines.size() <= 5 ? y0 + h - s65 : y0 + h - s55;\n drawString(g, spies, x + s20, y2);\n g.setFont(narrowFont(16));\n String s2 = text(\"RACES_DIPLOMACY_TRADE_AMT\", view.trade().level());\n int sw2 = g.getFontMetrics().stringWidth(s2);\n drawString(g, s2, x + w - s20 - sw2, y2);\n y2 += s22;\n g.setFont(narrowFont(18));\n String spending = text(\"RACES_DIPLOMACY_CURRENT_TRADE\");\n drawString(g, spending, x + s20, y2);\n int amt = (int) view.trade().profit();\n g.setFont(narrowFont(16));\n s2 = text(\"RACES_DIPLOMACY_TRADE_AMT\", str(amt));\n sw2 = g.getFontMetrics().stringWidth(s2);\n drawString(g, s2, x + w - s20 - sw2, y2);\n }\n\n private void drawAIForeignRelations(Graphics2D g, Empire emp, int x, int y, int w, int h) {\n g.setColor(RacesUI.darkBrown);\n g.fillRect(x, y, w, h);\n g.setColor(SystemPanel.whiteText);\n g.setFont(narrowFont(24));\n String title = text(\"RACES_DIPLOMACY_FOREIGN_RELATIONS\");\n int sw = g.getFontMetrics().stringWidth(title);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + s25;\n drawShadowedString(g, title, 1, x0, y0, SystemPanel.blackText, SystemPanel.whiteText);\n boolean outOfRange = !player().viewForEmpire(emp).inEconomicRange();\n g.setColor(SystemPanel.blackText);\n g.setFont(narrowFont(15));\n String desc;\n if (outOfRange)\n desc = text(\"RACES_DIPLOMACY_FOREIGN_RANGE\");\n else\n desc = text(\"RACES_DIPLOMACY_FOREIGN_DESC\");\n desc = emp.replaceTokens(desc, \"alien\");\n List lines = wrappedLines(g, desc, w - s30);\n int y1 = y0 + s10;\n for (String line : lines) {\n y1 += s16;\n drawString(g, line, x + s15, y1);\n }\n if (outOfRange)\n return;\n int x2 = x + s10;\n int y2 = y1 + s10;\n int w2 = w - s20;\n int listH = y + h - y2 - s20;\n g.setColor(RacesUI.brown);\n g.fillRect(x2, y2, w2, listH);\n relationsListBox.setBounds(x2, y2, w2, listH);\n g.setClip(x2, y2 + s1, w2, listH - s2);\n int y3 = y2 - relationsY;\n int x3 = x2 + s10;\n g.setFont(narrowFont(18));\n g.setColor(SystemPanel.blackText);\n List contacts = emp.contacts();\n Collections.sort(contacts, EmpireView.PLAYER_LIST_ORDER);\n int rowH = s18;\n int fullListH = (contacts.size() * rowH) + s5;\n int rightM = fullListH <= listH ? s10 : s20;\n for (EmpireView contact : contacts) {\n if (contact.inEconomicRange()) {\n y3 += rowH;\n g.setFont(narrowFont(18));\n drawString(g, contact.empire().raceName(), x3, y3);\n g.setFont(narrowFont(15));\n String treaty = contact.embassy().treaty().status(player());\n int sw1 = g.getFontMetrics().stringWidth(treaty);\n int x3b = x2 + w2 - sw1 - rightM;\n drawString(g, treaty, x3b, y3);\n }\n }\n relationsYMax = max(0, fullListH - listH);\n if (relationsYMax == 0)\n relationsScroller.setBounds(0, 0, 0, 0);\n else {\n g.setColor(RacesUI.scrollBarC);\n int scrollW = s12;\n int scrollH = (int) ((float) listH * listH / (listH + relationsYMax));\n int scrollX = x2 + w2 - scrollW - s2;\n int scrollY = (int) (y2 + (float) listH * relationsY / (relationsYMax + listH));\n g.fillRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n relationsScroller.setBounds(scrollX, scrollY, scrollW, scrollH);\n if (hoverShape == relationsScroller) {\n Stroke prev = g.getStroke();\n g.setColor(Color.yellow);\n g.setStroke(stroke2);\n g.drawRoundRect(scrollX, scrollY, scrollW, scrollH, s4, s4);\n g.setStroke(prev);\n }\n }\n g.setClip(null);\n if ((hoverShape == relationsListBox) && (fullListH > listH)) {\n g.setColor(Color.yellow);\n Stroke prev = g.getStroke();\n g.setStroke(stroke2);\n g.draw(relationsListBox);\n g.setStroke(prev);\n }\n }\n\n private void drawEmbassyButton(Graphics2D g, int x, int y, int w, int h) {\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n if (view == null)\n return;\n embassyBox.setBounds(x, y, w, h);\n if (embassyBackground == null) {\n float[] dist = { 0.0f, 0.5f, 1.0f };\n Point2D ptStart = new Point2D.Float(x, 0);\n Point2D ptEnd = new Point2D.Float(x + w, 0);\n Color[] colors = { greenEdgeC, greenMidC, greenEdgeC };\n embassyBackground = new LinearGradientPaint(ptStart, ptEnd, dist, colors);\n Color[] colors2 = { brownEdgeC, brownMidC, brownEdgeC };\n embassyDisabledBackground = new LinearGradientPaint(ptStart, ptEnd, dist, colors2);\n }\n Stroke prev = g.getStroke();\n g.setStroke(stroke3);\n g.setColor(Color.black);\n g.drawRect(x + s2, y + s2, w, h);\n g.setStroke(prev);\n if (view.diplomats())\n g.setPaint(embassyBackground);\n else\n g.setPaint(embassyDisabledBackground);\n g.fillRect(x, y, w, h);\n Color c0 = SystemPanel.whiteText;\n if ((hoverShape == embassyBox) && view.diplomats())\n c0 = Color.yellow;\n String lbl = view.embassy().diplomatGone() ? text(\"RACES_DIPLOMACY_CONTACT\") : text(\"RACES_DIPLOMACY_AUDIENCE\");\n int fontSize = scaledFont(g, lbl, w - s10, 18, 14);\n g.setFont(narrowFont(fontSize));\n int sw = g.getFontMetrics().stringWidth(lbl);\n int x0 = x + ((w - sw) / 2);\n int y0 = y + h - s8;\n drawShadowedString(g, lbl, 2, x0, y0, MainUI.shadeBorderC(), c0);\n prev = g.getStroke();\n g.setStroke(stroke2);\n g.setColor(c0);\n g.drawRect(x, y, w, h);\n g.setStroke(prev);\n }\n\n public void openEmbassy() {\n EmpireView view = player().viewForEmpire(parent.selectedEmpire());\n if (view == null)\n return;\n if (view.embassy().diplomatGone()) {\n view.embassy().reopenEmbassy();\n parent.repaint();\n return;\n }\n if (!view.diplomats())\n return;\n DiplomaticMessage.show(parent.selectedEmpire().viewForEmpire(player()), DialogueManager.DIPLOMACY_MAIN_MENU);\n }\n\n public void openManageDiplomatsPane() {\n softClick();\n manageDiplomatsPane.init();\n enableGlassPane(manageDiplomatsPane);\n return;\n }\n\n public void openManageSpiesPane() {\n softClick();\n manageSpiesPane.init();\n enableGlassPane(manageSpiesPane);\n return;\n }\n\n private boolean increaseSliderValue() {\n int oldValue = player().internalSecurity();\n player().increaseInternalSecurity();\n return oldValue != player().internalSecurity();\n }\n\n private boolean decreaseSliderValue() {\n int oldValue = player().internalSecurity();\n player().decreaseInternalSecurity();\n return oldValue != player().internalSecurity();\n }\n\n @Override\n public void mouseWheelMoved(MouseWheelEvent e) {\n int count = e.getUnitsToScroll();\n if ((hoverShape == incidentListBox) || (hoverShape == incidentScroller)) {\n int prevY = incidentY;\n if (count < 0)\n incidentY = max(0, incidentY - s10);\n else\n incidentY = min(incidentYMax, incidentY + s10);\n if (incidentY != prevY)\n repaint(incidentListBox);\n return;\n } else if (hoverShape == buttonSlider) {\n boolean changed = count < 0 ? increaseSliderValue() : decreaseSliderValue();\n if (changed) {\n setValues();\n repaint();\n }\n } else if ((hoverShape == relationsListBox) || (hoverShape == relationsScroller)) {\n int prevY = relationsY;\n if (count < 0)\n relationsY = max(0, relationsY - s10);\n else\n relationsY = min(relationsYMax, relationsY + s10);\n if (relationsY != prevY)\n repaint(relationsListBox);\n return;\n }\n }\n\n @Override\n public void mouseDragged(MouseEvent e) {\n int x = e.getX();\n int y = e.getY();\n int dY = y - dragY;\n dragY = y;\n if (incidentScroller == hoverShape) {\n if ((y >= incidentListBox.y) || (y <= (incidentListBox.y + incidentListBox.height))) {\n int h = (int) incidentListBox.getHeight();\n int dListY = (int) ((float) dY * (h + incidentYMax) / h);\n if (dY < 0)\n incidentY = max(0, incidentY + dListY);\n else\n incidentY = min(incidentYMax, incidentY + dListY);\n }\n repaint(incidentListBox);\n return;\n } else if (incidentListBox == hoverShape) {\n if (incidentListBox.contains(x, y)) {\n int h = (int) incidentListBox.getHeight();\n int dListY = (int) (-(float) dY * (h + incidentYMax) / h);\n if (dListY < 0)\n incidentY = max(0, incidentY + dListY);\n else\n incidentY = min(incidentYMax, incidentY + dListY);\n }\n repaint(incidentListBox);\n return;\n } else if (relationsScroller == hoverShape) {\n if ((y >= relationsListBox.y) || (y <= (relationsListBox.y + relationsListBox.height))) {\n int h = (int) relationsListBox.getHeight();\n int dListY = (int) ((float) dY * (h + relationsYMax) / h);\n if (dY < 0)\n relationsY = max(0, relationsY + dListY);\n else\n relationsY = min(relationsYMax, relationsY + dListY);\n }\n repaint(relationsListBox);\n return;\n } else if (relationsListBox == hoverShape) {\n if (relationsListBox.contains(x, y)) {\n int h = (int) relationsListBox.getHeight();\n int dListY = (int) (-(float) dY * (h + relationsYMax) / h);\n if (dListY < 0)\n relationsY = max(0, relationsY + dListY);\n else\n relationsY = min(relationsYMax, relationsY + dListY);\n }\n repaint(relationsListBox);\n return;\n }\n }\n\n @Override\n public void mouseMoved(MouseEvent e) {\n int x = e.getX();\n int y = e.getY();\n Shape prevHover = hoverShape;\n hoverShape = null;\n if (buttonIncr.contains(x, y))\n hoverShape = buttonIncr;\n else if (buttonDecr.contains(x, y))\n hoverShape = buttonDecr;\n else if (buttonSlider.contains(x, y))\n hoverShape = buttonSlider;\n else if (embassyBox.contains(x, y))\n hoverShape = embassyBox;\n else if (incidentScroller.contains(x, y))\n hoverShape = incidentScroller;\n else if (incidentListBox.contains(x, y))\n hoverShape = incidentListBox;\n else if (relationsScroller.contains(x, y))\n hoverShape = relationsScroller;\n else if (relationsListBox.contains(x, y))\n hoverShape = relationsListBox;\n else if (manageSpiesBox.contains(x, y))\n hoverShape = manageSpiesBox;\n else if (manageDiplomatsBox.contains(x, y))\n hoverShape = manageDiplomatsBox;\n if (hoverShape != prevHover)\n repaint();\n }\n\n @Override\n public void mouseClicked(MouseEvent e) {\n }\n\n @Override\n public void mousePressed(MouseEvent e) {\n dragY = e.getY();\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n dragY = 0;\n if (e.getButton() > 3)\n return;\n if (hoverShape == null)\n return;\n Empire emp = parent.selectedEmpire();\n if (hoverShape == embassyBox) {\n openEmbassy();\n return;\n } else if (hoverShape == manageSpiesBox) {\n openManageSpiesPane();\n return;\n } else if (hoverShape == manageDiplomatsBox) {\n openManageDiplomatsPane();\n return;\n }\n if (hoverShape == buttonIncr) {\n boolean changed = increaseSliderValue();\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n } else if (hoverShape == buttonDecr) {\n boolean changed = decreaseSliderValue();\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n } else if (hoverShape == buttonSlider) {\n float pct = (float) ((e.getX() - buttonSlider.getMinX()) / buttonSlider.getWidth());\n boolean changed = false;\n if (emp.isPlayer()) {\n int oldSec = emp.internalSecurity();\n emp.securityAllocation(pct);\n changed = oldSec != emp.internalSecurity();\n }\n if (changed) {\n setValues();\n softClick();\n repaint();\n } else\n misClick();\n return;\n }\n }\n\n @Override\n public void mouseEntered(MouseEvent e) {\n }\n\n @Override\n public void mouseExited(MouseEvent e) {\n if (hoverShape != null) {\n hoverShape = null;\n repaint();\n }\n }\n}\n"} {"task_id": "Java_2056", "language": "Java", "task_type": "method_signature", "source_file": "java/github/topcoder-platform/topcoder-UML-Tool/src/java/components/diagram_uml_sequence_elements/trunk/src/java/tests/com/topcoder/gui/diagramviewer/uml/sequenceelements/edgelayout/DefaultEdgeLayoutStrategyTests.java", "mask_start_position": 7961, "mask_end_position": 8006, "canonical_solution": "public void testLayout_NullElementMapping2() ", "pre_mask_code": "package com.topcoder.gui.diagramviewer.uml.sequenceelements.edgelayout;\n\nimport java.awt.Point;\nimport java.awt.Rectangle;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.EdgeLayoutException;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.ObjectNode;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.SequenceEdge;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.TestHelper;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.lifeline.LifelineSegment;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.lifeline.TestUtil;\n\n/**\n *

\n * Unit TestCases for DefaultEdgeLayoutStrategy class.\n *

\n *\n * @author TCSDEVELOPER\n * @version 1.1\n * @since 1.1\n */\npublic class DefaultEdgeLayoutStrategyTests extends TestCase {\n\n private DefaultEdgeLayoutStrategy layoutStrategy;\n\n private List edges;\n\n /**\n *

\n * The edge to nodes mapping for testing use.\n *

\n */\n private Map edgeNodeMapping;\n\n /**\n *

\n * Sets up test environment.\n *

\n *\n * @throws Exception to JUnit\n */\n protected void setUp() throws Exception {\n this.layoutStrategy = new DefaultEdgeLayoutStrategy();\n edgeNodeMapping = new HashMap();\n edges = TestUtil.createSimpleSequnceEdgeAndAssociation(edgeNodeMapping);\n }\n\n /**\n *

\n * Tears down test environment.\n *

\n *\n * @throws Exception to JUnit\n */\n protected void tearDown() throws Exception {\n this.layoutStrategy = null;\n }\n\n /**\n *

\n * Returns the test suite of this class.\n *

\n *\n * @return the test suite of this class.\n */\n public static Test suite() {\n return new TestSuite(DefaultEdgeLayoutStrategyTests.class);\n }\n\n /**\n *

\n * Test the default constructor.\n *

\n *\n *

\n * Test when the edgeSpace is loaded from default.\n *

\n */\n public void testCtor_Default() {\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy();\n assertNotNull(\"Fail to call the default constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in default constuctor\", 20, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the default constructor.\n *

\n *\n *

\n * Test when the edgeSpace is loaded from ConfigManager.\n *

\n *\n * @throws Exception to JUnit\n */\n public void testCtor_Config() throws Exception {\n TestHelper.loadXMLConfig(TestHelper.CONFIG_FILE);\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy();\n TestHelper.clearConfig();\n assertNotNull(\"Fail to call the default constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in default constuctor\", 10, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the constructor DefaultEdgeLayoutStrategy(int edgeSpace) for failure.\n *

\n *\n *

\n * It tests when edgeSpace argument is 0 or negative and expects the IllegalArgumentException.\n *

\n */\n public void testCtor_Failure() {\n try {\n new DefaultEdgeLayoutStrategy(0);\n fail(\"Should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n }\n try {\n new DefaultEdgeLayoutStrategy(-8);\n fail(\"Should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n }\n }\n\n public void testCtor_Accuracy() {\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy(40);\n assertNotNull(\"Fail to call the constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in the constuctor\", 40, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the setter method setEdgeSpace for failure.\n *

\n *\n *

\n * It tests when the argument is 0 or negative,and expects the IllegalArgumentException.\n *

\n */\n public void testSetEdgeSpace_Fail() {\n try {\n layoutStrategy.setEdgeSpace(0);\n fail(\"Should throw IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n }\n try {\n layoutStrategy.setEdgeSpace(-1);\n fail(\"Should throw IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n }\n }\n\n /**\n *

\n * Test the setter method setEdgeSpace for accuracy.\n *

\n */\n public void testSetEdgeSpace_Accuracy() {\n layoutStrategy.setEdgeSpace(70);\n assertEquals(\"Fail to set the edgeSpace correctly\", 70, layoutStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the getter method getEdgeSpace for accuracy.\n *

\n */\n public void testGetEdgeSpace() {\n layoutStrategy.setEdgeSpace(25);\n assertEquals(\"Fail to get the edgeSpace correctly\", 25, layoutStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the edges argument is null,and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullEdges() {\n try {\n layoutStrategy.layout(null, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the edgeNodeMapping argument is null,and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullEdgeNodeMapping() {\n try {\n layoutStrategy.layout(edges, null);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the element in the edges argument is null,and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementEdge() {\n try {\n edges.set(2, null);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when no value for edge key in the mapping and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementMapping1() {\n try {\n SequenceEdge edge = edges.get(3);\n edgeNodeMapping.remove(edge);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the value for edge key in the mapping is null and expects the\n * IllegalArgumentException.\n *

\n */\n ", "post_mask_code": "{\n try {\n SequenceEdge edge = edges.get(3);\n edgeNodeMapping.put(edge, null);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the number of the ObjectNode in ObjectNode[] is not equal to 2 , and expects\n * the IllegalArgumentException.\n *

\n */\n public void testLayout_InvalidElementMapping1() {\n try {\n SequenceEdge edge = edges.get(1);\n edgeNodeMapping.put(edge, TestUtil.createObjectNodes(3));\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the element of the ObjectNode in ObjectNode[] is null, and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_InvalidElementMapping2() {\n try {\n SequenceEdge edge = edges.get(1);\n ObjectNode[] nodes = TestUtil.createObjectNodes(2);\n nodes[1] = null;\n edgeNodeMapping.put(edge, nodes);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for accuracy.\n *

\n */\n public void testLayout_Accuracy() {\n List lsList = null;\n try {\n lsList = layoutStrategy.layout(edges, edgeNodeMapping);\n assertEquals(\"fail to generate the LifelineSegments correctly\", 5, lsList.size());\n // check the layout of LifelineSegments\n LifelineSegment llseg = lsList.get(0);\n Rectangle rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(1);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 40, rect.height);\n llseg = lsList.get(2);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(3);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(4);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n // check the layout of the edge\n SequenceEdge edge = edges.get(0);\n com.topcoder.diagraminterchange.Point left = edge.getGraphEdge().getWaypoints().get(0);\n com.topcoder.diagraminterchange.Point right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 235), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 235), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(1);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 255), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 255), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(2);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 275), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(335, 275), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(3);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(335, 295), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 295), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(4);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 315), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 315), new Point((int) right.getX(), (int) right.getY()));\n } catch (EdgeLayoutException e) {\n fail(\"should get no Exception\");\n }\n }\n\n /**\n *

\n * Test the layout method for accuracy.\n *

\n *\n *

\n * Test the cases when a SequenceEdge start and end at the same ObjectNode\n *

\n */\n public void testLayout_AccuracySameObjNode() {\n List lsList = null;\n edgeNodeMapping = new HashMap();\n edges = TestUtil.createSequnceEdgeAndAssociationSameObjNodes(edgeNodeMapping);\n try {\n lsList = layoutStrategy.layout(edges, edgeNodeMapping);\n assertEquals(\"fail to generate the LifelineSegments correctly\", 5, lsList.size());\n // check the layout of LifelineSegments\n LifelineSegment llseg = lsList.get(0);\n Rectangle rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 60, rect.height);\n llseg = lsList.get(1);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(2);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(3);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(4);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n // check the layout of the edge\n SequenceEdge edge = edges.get(0);\n com.topcoder.diagraminterchange.Point left = edge.getGraphEdge().getWaypoints().get(0);\n com.topcoder.diagraminterchange.Point right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 235), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 235), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(1);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 255), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 255), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(2);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 275), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 275), new Point((int) right.getX(), (int) right.getY()));\n // edge starts and ends with the same ObjectNode\n edge = edges.get(3);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 295), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(285, 295), new Point((int) right.getX(), (int) right.getY()));\n // edge starts and ends with the same ObjectNode\n edge = edges.get(4);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 315), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(285, 315), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(5);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 335), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 335), new Point((int) right.getX(), (int) right.getY()));\n } catch (EdgeLayoutException e) {\n fail(\"should get no Exception\");\n }\n }\n}\n"} {"task_id": "Java_2057", "language": "Java", "task_type": "method_body", "source_file": "java/github/topcoder-platform/topcoder-UML-Tool/src/java/components/diagram_uml_sequence_elements/trunk/src/java/tests/com/topcoder/gui/diagramviewer/uml/sequenceelements/edgelayout/DefaultEdgeLayoutStrategyTests.java", "mask_start_position": 3830, "mask_end_position": 4108, "canonical_solution": "{\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy(40);\n assertNotNull(\"Fail to call the constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in the constuctor\", 40, defaultStrategy.getEdgeSpace());\n }", "pre_mask_code": "package com.topcoder.gui.diagramviewer.uml.sequenceelements.edgelayout;\n\nimport java.awt.Point;\nimport java.awt.Rectangle;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.EdgeLayoutException;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.ObjectNode;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.SequenceEdge;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.TestHelper;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.lifeline.LifelineSegment;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.lifeline.TestUtil;\n\n/**\n *

\n * Unit TestCases for DefaultEdgeLayoutStrategy class.\n *

\n *\n * @author TCSDEVELOPER\n * @version 1.1\n * @since 1.1\n */\npublic class DefaultEdgeLayoutStrategyTests extends TestCase {\n\n private DefaultEdgeLayoutStrategy layoutStrategy;\n\n private List edges;\n\n /**\n *

\n * The edge to nodes mapping for testing use.\n *

\n */\n private Map edgeNodeMapping;\n\n /**\n *

\n * Sets up test environment.\n *

\n *\n * @throws Exception to JUnit\n */\n protected void setUp() throws Exception {\n this.layoutStrategy = new DefaultEdgeLayoutStrategy();\n edgeNodeMapping = new HashMap();\n edges = TestUtil.createSimpleSequnceEdgeAndAssociation(edgeNodeMapping);\n }\n\n /**\n *

\n * Tears down test environment.\n *

\n *\n * @throws Exception to JUnit\n */\n protected void tearDown() throws Exception {\n this.layoutStrategy = null;\n }\n\n /**\n *

\n * Returns the test suite of this class.\n *

\n *\n * @return the test suite of this class.\n */\n public static Test suite() {\n return new TestSuite(DefaultEdgeLayoutStrategyTests.class);\n }\n\n /**\n *

\n * Test the default constructor.\n *

\n *\n *

\n * Test when the edgeSpace is loaded from default.\n *

\n */\n public void testCtor_Default() {\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy();\n assertNotNull(\"Fail to call the default constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in default constuctor\", 20, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the default constructor.\n *

\n *\n *

\n * Test when the edgeSpace is loaded from ConfigManager.\n *

\n *\n * @throws Exception to JUnit\n */\n public void testCtor_Config() throws Exception {\n TestHelper.loadXMLConfig(TestHelper.CONFIG_FILE);\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy();\n TestHelper.clearConfig();\n assertNotNull(\"Fail to call the default constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in default constuctor\", 10, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the constructor DefaultEdgeLayoutStrategy(int edgeSpace) for failure.\n *

\n *\n *

\n * It tests when edgeSpace argument is 0 or negative and expects the IllegalArgumentException.\n *

\n */\n public void testCtor_Failure() {\n try {\n new DefaultEdgeLayoutStrategy(0);\n fail(\"Should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n }\n try {\n new DefaultEdgeLayoutStrategy(-8);\n fail(\"Should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n }\n }\n\n public void testCtor_Accuracy() ", "post_mask_code": "\n\n /**\n *

\n * Test the setter method setEdgeSpace for failure.\n *

\n *\n *

\n * It tests when the argument is 0 or negative,and expects the IllegalArgumentException.\n *

\n */\n public void testSetEdgeSpace_Fail() {\n try {\n layoutStrategy.setEdgeSpace(0);\n fail(\"Should throw IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n }\n try {\n layoutStrategy.setEdgeSpace(-1);\n fail(\"Should throw IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n }\n }\n\n /**\n *

\n * Test the setter method setEdgeSpace for accuracy.\n *

\n */\n public void testSetEdgeSpace_Accuracy() {\n layoutStrategy.setEdgeSpace(70);\n assertEquals(\"Fail to set the edgeSpace correctly\", 70, layoutStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the getter method getEdgeSpace for accuracy.\n *

\n */\n public void testGetEdgeSpace() {\n layoutStrategy.setEdgeSpace(25);\n assertEquals(\"Fail to get the edgeSpace correctly\", 25, layoutStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the edges argument is null,and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullEdges() {\n try {\n layoutStrategy.layout(null, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the edgeNodeMapping argument is null,and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullEdgeNodeMapping() {\n try {\n layoutStrategy.layout(edges, null);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the element in the edges argument is null,and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementEdge() {\n try {\n edges.set(2, null);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when no value for edge key in the mapping and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementMapping1() {\n try {\n SequenceEdge edge = edges.get(3);\n edgeNodeMapping.remove(edge);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the value for edge key in the mapping is null and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementMapping2() {\n try {\n SequenceEdge edge = edges.get(3);\n edgeNodeMapping.put(edge, null);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the number of the ObjectNode in ObjectNode[] is not equal to 2 , and expects\n * the IllegalArgumentException.\n *

\n */\n public void testLayout_InvalidElementMapping1() {\n try {\n SequenceEdge edge = edges.get(1);\n edgeNodeMapping.put(edge, TestUtil.createObjectNodes(3));\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the element of the ObjectNode in ObjectNode[] is null, and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_InvalidElementMapping2() {\n try {\n SequenceEdge edge = edges.get(1);\n ObjectNode[] nodes = TestUtil.createObjectNodes(2);\n nodes[1] = null;\n edgeNodeMapping.put(edge, nodes);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for accuracy.\n *

\n */\n public void testLayout_Accuracy() {\n List lsList = null;\n try {\n lsList = layoutStrategy.layout(edges, edgeNodeMapping);\n assertEquals(\"fail to generate the LifelineSegments correctly\", 5, lsList.size());\n // check the layout of LifelineSegments\n LifelineSegment llseg = lsList.get(0);\n Rectangle rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(1);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 40, rect.height);\n llseg = lsList.get(2);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(3);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(4);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n // check the layout of the edge\n SequenceEdge edge = edges.get(0);\n com.topcoder.diagraminterchange.Point left = edge.getGraphEdge().getWaypoints().get(0);\n com.topcoder.diagraminterchange.Point right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 235), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 235), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(1);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 255), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 255), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(2);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 275), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(335, 275), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(3);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(335, 295), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 295), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(4);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 315), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 315), new Point((int) right.getX(), (int) right.getY()));\n } catch (EdgeLayoutException e) {\n fail(\"should get no Exception\");\n }\n }\n\n /**\n *

\n * Test the layout method for accuracy.\n *

\n *\n *

\n * Test the cases when a SequenceEdge start and end at the same ObjectNode\n *

\n */\n public void testLayout_AccuracySameObjNode() {\n List lsList = null;\n edgeNodeMapping = new HashMap();\n edges = TestUtil.createSequnceEdgeAndAssociationSameObjNodes(edgeNodeMapping);\n try {\n lsList = layoutStrategy.layout(edges, edgeNodeMapping);\n assertEquals(\"fail to generate the LifelineSegments correctly\", 5, lsList.size());\n // check the layout of LifelineSegments\n LifelineSegment llseg = lsList.get(0);\n Rectangle rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 60, rect.height);\n llseg = lsList.get(1);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(2);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(3);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(4);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n // check the layout of the edge\n SequenceEdge edge = edges.get(0);\n com.topcoder.diagraminterchange.Point left = edge.getGraphEdge().getWaypoints().get(0);\n com.topcoder.diagraminterchange.Point right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 235), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 235), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(1);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 255), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 255), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(2);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 275), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 275), new Point((int) right.getX(), (int) right.getY()));\n // edge starts and ends with the same ObjectNode\n edge = edges.get(3);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 295), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(285, 295), new Point((int) right.getX(), (int) right.getY()));\n // edge starts and ends with the same ObjectNode\n edge = edges.get(4);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 315), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(285, 315), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(5);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 335), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 335), new Point((int) right.getX(), (int) right.getY()));\n } catch (EdgeLayoutException e) {\n fail(\"should get no Exception\");\n }\n }\n}\n"} {"task_id": "Java_2058", "language": "Java", "task_type": "single_line", "source_file": "java/github/topcoder-platform/topcoder-UML-Tool/src/java/components/diagram_uml_sequence_elements/trunk/src/java/tests/com/topcoder/gui/diagramviewer/uml/sequenceelements/edgelayout/DefaultEdgeLayoutStrategyTests.java", "mask_start_position": 4923, "mask_end_position": 4948, "canonical_solution": "trategy.setEdgeSpace(70);", "pre_mask_code": "package com.topcoder.gui.diagramviewer.uml.sequenceelements.edgelayout;\n\nimport java.awt.Point;\nimport java.awt.Rectangle;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.EdgeLayoutException;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.ObjectNode;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.SequenceEdge;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.TestHelper;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.lifeline.LifelineSegment;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.lifeline.TestUtil;\n\n/**\n *

\n * Unit TestCases for DefaultEdgeLayoutStrategy class.\n *

\n *\n * @author TCSDEVELOPER\n * @version 1.1\n * @since 1.1\n */\npublic class DefaultEdgeLayoutStrategyTests extends TestCase {\n\n private DefaultEdgeLayoutStrategy layoutStrategy;\n\n private List edges;\n\n /**\n *

\n * The edge to nodes mapping for testing use.\n *

\n */\n private Map edgeNodeMapping;\n\n /**\n *

\n * Sets up test environment.\n *

\n *\n * @throws Exception to JUnit\n */\n protected void setUp() throws Exception {\n this.layoutStrategy = new DefaultEdgeLayoutStrategy();\n edgeNodeMapping = new HashMap();\n edges = TestUtil.createSimpleSequnceEdgeAndAssociation(edgeNodeMapping);\n }\n\n /**\n *

\n * Tears down test environment.\n *

\n *\n * @throws Exception to JUnit\n */\n protected void tearDown() throws Exception {\n this.layoutStrategy = null;\n }\n\n /**\n *

\n * Returns the test suite of this class.\n *

\n *\n * @return the test suite of this class.\n */\n public static Test suite() {\n return new TestSuite(DefaultEdgeLayoutStrategyTests.class);\n }\n\n /**\n *

\n * Test the default constructor.\n *

\n *\n *

\n * Test when the edgeSpace is loaded from default.\n *

\n */\n public void testCtor_Default() {\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy();\n assertNotNull(\"Fail to call the default constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in default constuctor\", 20, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the default constructor.\n *

\n *\n *

\n * Test when the edgeSpace is loaded from ConfigManager.\n *

\n *\n * @throws Exception to JUnit\n */\n public void testCtor_Config() throws Exception {\n TestHelper.loadXMLConfig(TestHelper.CONFIG_FILE);\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy();\n TestHelper.clearConfig();\n assertNotNull(\"Fail to call the default constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in default constuctor\", 10, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the constructor DefaultEdgeLayoutStrategy(int edgeSpace) for failure.\n *

\n *\n *

\n * It tests when edgeSpace argument is 0 or negative and expects the IllegalArgumentException.\n *

\n */\n public void testCtor_Failure() {\n try {\n new DefaultEdgeLayoutStrategy(0);\n fail(\"Should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n }\n try {\n new DefaultEdgeLayoutStrategy(-8);\n fail(\"Should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n }\n }\n\n public void testCtor_Accuracy() {\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy(40);\n assertNotNull(\"Fail to call the constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in the constuctor\", 40, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the setter method setEdgeSpace for failure.\n *

\n *\n *

\n * It tests when the argument is 0 or negative,and expects the IllegalArgumentException.\n *

\n */\n public void testSetEdgeSpace_Fail() {\n try {\n layoutStrategy.setEdgeSpace(0);\n fail(\"Should throw IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n }\n try {\n layoutStrategy.setEdgeSpace(-1);\n fail(\"Should throw IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n }\n }\n\n /**\n *

\n * Test the setter method setEdgeSpace for accuracy.\n *

\n */\n public void testSetEdgeSpace_Accuracy() {\n layoutS", "post_mask_code": "\n assertEquals(\"Fail to set the edgeSpace correctly\", 70, layoutStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the getter method getEdgeSpace for accuracy.\n *

\n */\n public void testGetEdgeSpace() {\n layoutStrategy.setEdgeSpace(25);\n assertEquals(\"Fail to get the edgeSpace correctly\", 25, layoutStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the edges argument is null,and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullEdges() {\n try {\n layoutStrategy.layout(null, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the edgeNodeMapping argument is null,and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullEdgeNodeMapping() {\n try {\n layoutStrategy.layout(edges, null);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the element in the edges argument is null,and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementEdge() {\n try {\n edges.set(2, null);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when no value for edge key in the mapping and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementMapping1() {\n try {\n SequenceEdge edge = edges.get(3);\n edgeNodeMapping.remove(edge);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the value for edge key in the mapping is null and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementMapping2() {\n try {\n SequenceEdge edge = edges.get(3);\n edgeNodeMapping.put(edge, null);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the number of the ObjectNode in ObjectNode[] is not equal to 2 , and expects\n * the IllegalArgumentException.\n *

\n */\n public void testLayout_InvalidElementMapping1() {\n try {\n SequenceEdge edge = edges.get(1);\n edgeNodeMapping.put(edge, TestUtil.createObjectNodes(3));\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the element of the ObjectNode in ObjectNode[] is null, and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_InvalidElementMapping2() {\n try {\n SequenceEdge edge = edges.get(1);\n ObjectNode[] nodes = TestUtil.createObjectNodes(2);\n nodes[1] = null;\n edgeNodeMapping.put(edge, nodes);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for accuracy.\n *

\n */\n public void testLayout_Accuracy() {\n List lsList = null;\n try {\n lsList = layoutStrategy.layout(edges, edgeNodeMapping);\n assertEquals(\"fail to generate the LifelineSegments correctly\", 5, lsList.size());\n // check the layout of LifelineSegments\n LifelineSegment llseg = lsList.get(0);\n Rectangle rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(1);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 40, rect.height);\n llseg = lsList.get(2);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(3);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(4);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n // check the layout of the edge\n SequenceEdge edge = edges.get(0);\n com.topcoder.diagraminterchange.Point left = edge.getGraphEdge().getWaypoints().get(0);\n com.topcoder.diagraminterchange.Point right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 235), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 235), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(1);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 255), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 255), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(2);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 275), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(335, 275), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(3);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(335, 295), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 295), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(4);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 315), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 315), new Point((int) right.getX(), (int) right.getY()));\n } catch (EdgeLayoutException e) {\n fail(\"should get no Exception\");\n }\n }\n\n /**\n *

\n * Test the layout method for accuracy.\n *

\n *\n *

\n * Test the cases when a SequenceEdge start and end at the same ObjectNode\n *

\n */\n public void testLayout_AccuracySameObjNode() {\n List lsList = null;\n edgeNodeMapping = new HashMap();\n edges = TestUtil.createSequnceEdgeAndAssociationSameObjNodes(edgeNodeMapping);\n try {\n lsList = layoutStrategy.layout(edges, edgeNodeMapping);\n assertEquals(\"fail to generate the LifelineSegments correctly\", 5, lsList.size());\n // check the layout of LifelineSegments\n LifelineSegment llseg = lsList.get(0);\n Rectangle rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 60, rect.height);\n llseg = lsList.get(1);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(2);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(3);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(4);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n // check the layout of the edge\n SequenceEdge edge = edges.get(0);\n com.topcoder.diagraminterchange.Point left = edge.getGraphEdge().getWaypoints().get(0);\n com.topcoder.diagraminterchange.Point right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 235), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 235), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(1);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 255), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 255), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(2);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 275), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 275), new Point((int) right.getX(), (int) right.getY()));\n // edge starts and ends with the same ObjectNode\n edge = edges.get(3);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 295), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(285, 295), new Point((int) right.getX(), (int) right.getY()));\n // edge starts and ends with the same ObjectNode\n edge = edges.get(4);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 315), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(285, 315), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(5);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 335), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 335), new Point((int) right.getX(), (int) right.getY()));\n } catch (EdgeLayoutException e) {\n fail(\"should get no Exception\");\n }\n }\n}\n"} {"task_id": "Java_2059", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/topcoder-platform/topcoder-UML-Tool/src/java/components/diagram_uml_sequence_elements/trunk/src/java/tests/com/topcoder/gui/diagramviewer/uml/sequenceelements/edgelayout/DefaultEdgeLayoutStrategyTests.java", "mask_start_position": 3405, "mask_end_position": 3792, "canonical_solution": "public void testCtor_Failure() {\n try {\n new DefaultEdgeLayoutStrategy(0);\n fail(\"Should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n }\n try {\n new DefaultEdgeLayoutStrategy(-8);\n fail(\"Should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n }\n }", "pre_mask_code": "package com.topcoder.gui.diagramviewer.uml.sequenceelements.edgelayout;\n\nimport java.awt.Point;\nimport java.awt.Rectangle;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.EdgeLayoutException;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.ObjectNode;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.SequenceEdge;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.TestHelper;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.lifeline.LifelineSegment;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.lifeline.TestUtil;\n\n/**\n *

\n * Unit TestCases for DefaultEdgeLayoutStrategy class.\n *

\n *\n * @author TCSDEVELOPER\n * @version 1.1\n * @since 1.1\n */\npublic class DefaultEdgeLayoutStrategyTests extends TestCase {\n\n private DefaultEdgeLayoutStrategy layoutStrategy;\n\n private List edges;\n\n /**\n *

\n * The edge to nodes mapping for testing use.\n *

\n */\n private Map edgeNodeMapping;\n\n /**\n *

\n * Sets up test environment.\n *

\n *\n * @throws Exception to JUnit\n */\n protected void setUp() throws Exception {\n this.layoutStrategy = new DefaultEdgeLayoutStrategy();\n edgeNodeMapping = new HashMap();\n edges = TestUtil.createSimpleSequnceEdgeAndAssociation(edgeNodeMapping);\n }\n\n /**\n *

\n * Tears down test environment.\n *

\n *\n * @throws Exception to JUnit\n */\n protected void tearDown() throws Exception {\n this.layoutStrategy = null;\n }\n\n /**\n *

\n * Returns the test suite of this class.\n *

\n *\n * @return the test suite of this class.\n */\n public static Test suite() {\n return new TestSuite(DefaultEdgeLayoutStrategyTests.class);\n }\n\n /**\n *

\n * Test the default constructor.\n *

\n *\n *

\n * Test when the edgeSpace is loaded from default.\n *

\n */\n public void testCtor_Default() {\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy();\n assertNotNull(\"Fail to call the default constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in default constuctor\", 20, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the default constructor.\n *

\n *\n *

\n * Test when the edgeSpace is loaded from ConfigManager.\n *

\n *\n * @throws Exception to JUnit\n */\n public void testCtor_Config() throws Exception {\n TestHelper.loadXMLConfig(TestHelper.CONFIG_FILE);\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy();\n TestHelper.clearConfig();\n assertNotNull(\"Fail to call the default constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in default constuctor\", 10, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the constructor DefaultEdgeLayoutStrategy(int edgeSpace) for failure.\n *

\n *\n *

\n * It tests when edgeSpace argument is 0 or negative and expects the IllegalArgumentException.\n *

\n */\n ", "post_mask_code": "\n\n public void testCtor_Accuracy() {\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy(40);\n assertNotNull(\"Fail to call the constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in the constuctor\", 40, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the setter method setEdgeSpace for failure.\n *

\n *\n *

\n * It tests when the argument is 0 or negative,and expects the IllegalArgumentException.\n *

\n */\n public void testSetEdgeSpace_Fail() {\n try {\n layoutStrategy.setEdgeSpace(0);\n fail(\"Should throw IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n }\n try {\n layoutStrategy.setEdgeSpace(-1);\n fail(\"Should throw IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n }\n }\n\n /**\n *

\n * Test the setter method setEdgeSpace for accuracy.\n *

\n */\n public void testSetEdgeSpace_Accuracy() {\n layoutStrategy.setEdgeSpace(70);\n assertEquals(\"Fail to set the edgeSpace correctly\", 70, layoutStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the getter method getEdgeSpace for accuracy.\n *

\n */\n public void testGetEdgeSpace() {\n layoutStrategy.setEdgeSpace(25);\n assertEquals(\"Fail to get the edgeSpace correctly\", 25, layoutStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the edges argument is null,and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullEdges() {\n try {\n layoutStrategy.layout(null, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the edgeNodeMapping argument is null,and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullEdgeNodeMapping() {\n try {\n layoutStrategy.layout(edges, null);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the element in the edges argument is null,and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementEdge() {\n try {\n edges.set(2, null);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when no value for edge key in the mapping and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementMapping1() {\n try {\n SequenceEdge edge = edges.get(3);\n edgeNodeMapping.remove(edge);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the value for edge key in the mapping is null and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementMapping2() {\n try {\n SequenceEdge edge = edges.get(3);\n edgeNodeMapping.put(edge, null);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the number of the ObjectNode in ObjectNode[] is not equal to 2 , and expects\n * the IllegalArgumentException.\n *

\n */\n public void testLayout_InvalidElementMapping1() {\n try {\n SequenceEdge edge = edges.get(1);\n edgeNodeMapping.put(edge, TestUtil.createObjectNodes(3));\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the element of the ObjectNode in ObjectNode[] is null, and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_InvalidElementMapping2() {\n try {\n SequenceEdge edge = edges.get(1);\n ObjectNode[] nodes = TestUtil.createObjectNodes(2);\n nodes[1] = null;\n edgeNodeMapping.put(edge, nodes);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for accuracy.\n *

\n */\n public void testLayout_Accuracy() {\n List lsList = null;\n try {\n lsList = layoutStrategy.layout(edges, edgeNodeMapping);\n assertEquals(\"fail to generate the LifelineSegments correctly\", 5, lsList.size());\n // check the layout of LifelineSegments\n LifelineSegment llseg = lsList.get(0);\n Rectangle rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(1);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 40, rect.height);\n llseg = lsList.get(2);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(3);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(4);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n // check the layout of the edge\n SequenceEdge edge = edges.get(0);\n com.topcoder.diagraminterchange.Point left = edge.getGraphEdge().getWaypoints().get(0);\n com.topcoder.diagraminterchange.Point right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 235), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 235), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(1);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 255), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 255), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(2);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 275), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(335, 275), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(3);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(335, 295), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 295), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(4);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 315), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 315), new Point((int) right.getX(), (int) right.getY()));\n } catch (EdgeLayoutException e) {\n fail(\"should get no Exception\");\n }\n }\n\n /**\n *

\n * Test the layout method for accuracy.\n *

\n *\n *

\n * Test the cases when a SequenceEdge start and end at the same ObjectNode\n *

\n */\n public void testLayout_AccuracySameObjNode() {\n List lsList = null;\n edgeNodeMapping = new HashMap();\n edges = TestUtil.createSequnceEdgeAndAssociationSameObjNodes(edgeNodeMapping);\n try {\n lsList = layoutStrategy.layout(edges, edgeNodeMapping);\n assertEquals(\"fail to generate the LifelineSegments correctly\", 5, lsList.size());\n // check the layout of LifelineSegments\n LifelineSegment llseg = lsList.get(0);\n Rectangle rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 60, rect.height);\n llseg = lsList.get(1);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(2);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(3);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(4);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n // check the layout of the edge\n SequenceEdge edge = edges.get(0);\n com.topcoder.diagraminterchange.Point left = edge.getGraphEdge().getWaypoints().get(0);\n com.topcoder.diagraminterchange.Point right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 235), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 235), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(1);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 255), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 255), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(2);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 275), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 275), new Point((int) right.getX(), (int) right.getY()));\n // edge starts and ends with the same ObjectNode\n edge = edges.get(3);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 295), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(285, 295), new Point((int) right.getX(), (int) right.getY()));\n // edge starts and ends with the same ObjectNode\n edge = edges.get(4);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 315), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(285, 315), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(5);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 335), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 335), new Point((int) right.getX(), (int) right.getY()));\n } catch (EdgeLayoutException e) {\n fail(\"should get no Exception\");\n }\n }\n}\n"} {"task_id": "Java_2060", "language": "Java", "task_type": "try_statement", "source_file": "java/github/topcoder-platform/topcoder-UML-Tool/src/java/components/diagram_uml_sequence_elements/trunk/src/java/tests/com/topcoder/gui/diagramviewer/uml/sequenceelements/edgelayout/DefaultEdgeLayoutStrategyTests.java", "mask_start_position": 7336, "mask_end_position": 7721, "canonical_solution": "try {\n SequenceEdge edge = edges.get(3);\n edgeNodeMapping.remove(edge);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }", "pre_mask_code": "package com.topcoder.gui.diagramviewer.uml.sequenceelements.edgelayout;\n\nimport java.awt.Point;\nimport java.awt.Rectangle;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.EdgeLayoutException;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.ObjectNode;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.SequenceEdge;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.TestHelper;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.lifeline.LifelineSegment;\nimport com.topcoder.gui.diagramviewer.uml.sequenceelements.lifeline.TestUtil;\n\n/**\n *

\n * Unit TestCases for DefaultEdgeLayoutStrategy class.\n *

\n *\n * @author TCSDEVELOPER\n * @version 1.1\n * @since 1.1\n */\npublic class DefaultEdgeLayoutStrategyTests extends TestCase {\n\n private DefaultEdgeLayoutStrategy layoutStrategy;\n\n private List edges;\n\n /**\n *

\n * The edge to nodes mapping for testing use.\n *

\n */\n private Map edgeNodeMapping;\n\n /**\n *

\n * Sets up test environment.\n *

\n *\n * @throws Exception to JUnit\n */\n protected void setUp() throws Exception {\n this.layoutStrategy = new DefaultEdgeLayoutStrategy();\n edgeNodeMapping = new HashMap();\n edges = TestUtil.createSimpleSequnceEdgeAndAssociation(edgeNodeMapping);\n }\n\n /**\n *

\n * Tears down test environment.\n *

\n *\n * @throws Exception to JUnit\n */\n protected void tearDown() throws Exception {\n this.layoutStrategy = null;\n }\n\n /**\n *

\n * Returns the test suite of this class.\n *

\n *\n * @return the test suite of this class.\n */\n public static Test suite() {\n return new TestSuite(DefaultEdgeLayoutStrategyTests.class);\n }\n\n /**\n *

\n * Test the default constructor.\n *

\n *\n *

\n * Test when the edgeSpace is loaded from default.\n *

\n */\n public void testCtor_Default() {\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy();\n assertNotNull(\"Fail to call the default constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in default constuctor\", 20, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the default constructor.\n *

\n *\n *

\n * Test when the edgeSpace is loaded from ConfigManager.\n *

\n *\n * @throws Exception to JUnit\n */\n public void testCtor_Config() throws Exception {\n TestHelper.loadXMLConfig(TestHelper.CONFIG_FILE);\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy();\n TestHelper.clearConfig();\n assertNotNull(\"Fail to call the default constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in default constuctor\", 10, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the constructor DefaultEdgeLayoutStrategy(int edgeSpace) for failure.\n *

\n *\n *

\n * It tests when edgeSpace argument is 0 or negative and expects the IllegalArgumentException.\n *

\n */\n public void testCtor_Failure() {\n try {\n new DefaultEdgeLayoutStrategy(0);\n fail(\"Should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n }\n try {\n new DefaultEdgeLayoutStrategy(-8);\n fail(\"Should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n }\n }\n\n public void testCtor_Accuracy() {\n DefaultEdgeLayoutStrategy defaultStrategy = new DefaultEdgeLayoutStrategy(40);\n assertNotNull(\"Fail to call the constructor\", defaultStrategy);\n assertEquals(\"Fail to set the member variables in the constuctor\", 40, defaultStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the setter method setEdgeSpace for failure.\n *

\n *\n *

\n * It tests when the argument is 0 or negative,and expects the IllegalArgumentException.\n *

\n */\n public void testSetEdgeSpace_Fail() {\n try {\n layoutStrategy.setEdgeSpace(0);\n fail(\"Should throw IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n }\n try {\n layoutStrategy.setEdgeSpace(-1);\n fail(\"Should throw IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n }\n }\n\n /**\n *

\n * Test the setter method setEdgeSpace for accuracy.\n *

\n */\n public void testSetEdgeSpace_Accuracy() {\n layoutStrategy.setEdgeSpace(70);\n assertEquals(\"Fail to set the edgeSpace correctly\", 70, layoutStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the getter method getEdgeSpace for accuracy.\n *

\n */\n public void testGetEdgeSpace() {\n layoutStrategy.setEdgeSpace(25);\n assertEquals(\"Fail to get the edgeSpace correctly\", 25, layoutStrategy.getEdgeSpace());\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the edges argument is null,and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullEdges() {\n try {\n layoutStrategy.layout(null, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the edgeNodeMapping argument is null,and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullEdgeNodeMapping() {\n try {\n layoutStrategy.layout(edges, null);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the element in the edges argument is null,and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementEdge() {\n try {\n edges.set(2, null);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when no value for edge key in the mapping and expects the IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementMapping1() {\n ", "post_mask_code": "\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the value for edge key in the mapping is null and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_NullElementMapping2() {\n try {\n SequenceEdge edge = edges.get(3);\n edgeNodeMapping.put(edge, null);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the number of the ObjectNode in ObjectNode[] is not equal to 2 , and expects\n * the IllegalArgumentException.\n *

\n */\n public void testLayout_InvalidElementMapping1() {\n try {\n SequenceEdge edge = edges.get(1);\n edgeNodeMapping.put(edge, TestUtil.createObjectNodes(3));\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for failure.\n *

\n *\n *

\n * It tests when the element of the ObjectNode in ObjectNode[] is null, and expects the\n * IllegalArgumentException.\n *

\n */\n public void testLayout_InvalidElementMapping2() {\n try {\n SequenceEdge edge = edges.get(1);\n ObjectNode[] nodes = TestUtil.createObjectNodes(2);\n nodes[1] = null;\n edgeNodeMapping.put(edge, nodes);\n layoutStrategy.layout(edges, edgeNodeMapping);\n fail(\"should get IllegalArgumentException\");\n } catch (IllegalArgumentException e) {\n // good\n } catch (EdgeLayoutException e) {\n fail(\"should get IllegalArgumentException\");\n }\n }\n\n /**\n *

\n * Test the layout method for accuracy.\n *

\n */\n public void testLayout_Accuracy() {\n List lsList = null;\n try {\n lsList = layoutStrategy.layout(edges, edgeNodeMapping);\n assertEquals(\"fail to generate the LifelineSegments correctly\", 5, lsList.size());\n // check the layout of LifelineSegments\n LifelineSegment llseg = lsList.get(0);\n Rectangle rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(1);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 40, rect.height);\n llseg = lsList.get(2);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(3);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(4);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n // check the layout of the edge\n SequenceEdge edge = edges.get(0);\n com.topcoder.diagraminterchange.Point left = edge.getGraphEdge().getWaypoints().get(0);\n com.topcoder.diagraminterchange.Point right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 235), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 235), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(1);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 255), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 255), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(2);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 275), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(335, 275), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(3);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(335, 295), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 295), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(4);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 315), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 315), new Point((int) right.getX(), (int) right.getY()));\n } catch (EdgeLayoutException e) {\n fail(\"should get no Exception\");\n }\n }\n\n /**\n *

\n * Test the layout method for accuracy.\n *

\n *\n *

\n * Test the cases when a SequenceEdge start and end at the same ObjectNode\n *

\n */\n public void testLayout_AccuracySameObjNode() {\n List lsList = null;\n edgeNodeMapping = new HashMap();\n edges = TestUtil.createSequnceEdgeAndAssociationSameObjNodes(edgeNodeMapping);\n try {\n lsList = layoutStrategy.layout(edges, edgeNodeMapping);\n assertEquals(\"fail to generate the LifelineSegments correctly\", 5, lsList.size());\n // check the layout of LifelineSegments\n LifelineSegment llseg = lsList.get(0);\n Rectangle rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 60, rect.height);\n llseg = lsList.get(1);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(2);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(3);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n llseg = lsList.get(4);\n rect = llseg.getSelectionBound();\n assertEquals(\"fail to layout the LifelineSegments correctly\", 20, rect.height);\n // check the layout of the edge\n SequenceEdge edge = edges.get(0);\n com.topcoder.diagraminterchange.Point left = edge.getGraphEdge().getWaypoints().get(0);\n com.topcoder.diagraminterchange.Point right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 235), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 235), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(1);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 255), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(215, 255), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(2);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 275), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 275), new Point((int) right.getX(), (int) right.getY()));\n // edge starts and ends with the same ObjectNode\n edge = edges.get(3);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 295), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(285, 295), new Point((int) right.getX(), (int) right.getY()));\n // edge starts and ends with the same ObjectNode\n edge = edges.get(4);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 315), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(285, 315), new Point((int) right.getX(), (int) right.getY()));\n edge = edges.get(5);\n left = edge.getGraphEdge().getWaypoints().get(0);\n right = edge.getGraphEdge().getWaypoints().get(1);\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(275, 335), new Point((int) left.getX(), (int) left.getY()));\n assertEquals(\"fail to layout the SequenceEdge correctly\", new Point(155, 335), new Point((int) right.getX(), (int) right.getY()));\n } catch (EdgeLayoutException e) {\n fail(\"should get no Exception\");\n }\n }\n}\n"} {"task_id": "Java_2061", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/halestudio/hale/common/plugins/eu.esdihumboldt.hale.common.core/src/eu/esdihumboldt/hale/common/core/service/cleanup/TemporaryFiles.java", "mask_start_position": 707, "mask_end_position": 749, "canonical_solution": "public Iterable getTemporaryFiles();", "pre_mask_code": "/*\n * \n * published by the Free Software Foundation, either version 3 of the License,\n * or (at your option) any later version.\n * \n * You should have received a copy of the GNU Lesser General Public License\n * along with this distribution. If not, see .\n * \n * Contributors:\n * Data Harmonisation Panel \n */\npackage eu.esdihumboldt.hale.common.core.service.cleanup;\n\nimport java.io.File;\n\n/**\n * Exposes associated temporary files for external clean up.\n *\n * @author Simon Templer\n */\npublic interface TemporaryFiles {\n\n /**\n * Get the temporary files that should be removed when no longer needed\n *\n * @return the temporary files\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2062", "language": "Java", "task_type": "method_signature", "source_file": "java/github/x-stream/xstream/xstream/src/java/com/thoughtworks/xstream/io/AbstractReader.java", "mask_start_position": 3191, "mask_end_position": 3230, "canonical_solution": "@Override\n public void remove() ", "pre_mask_code": "/*\n * All rights reserved.\n *\n *\n * Created on 16. August 2009 by Joerg Schaible\n */\npackage com.thoughtworks.xstream.io;\n\nimport java.util.Iterator;\nimport com.thoughtworks.xstream.core.util.Cloneables;\nimport com.thoughtworks.xstream.io.naming.NameCoder;\nimport com.thoughtworks.xstream.io.naming.NoNameCoder;\n\n/**\n * Abstract base class for all HierarchicalStreamReader implementations. Implementations of\n * {@link HierarchicalStreamReader} should rather be derived from this class then implementing the interface directly.\n *\n * @author Jörg Schaible\n * @since 1.4\n */\npublic abstract class AbstractReader implements ExtendedHierarchicalStreamReader {\n\n private final NameCoder nameCoder;\n\n /**\n * Creates an AbstractReader with a NameCoder that does nothing.\n *\n * @since 1.4\n */\n protected AbstractReader() {\n this(new NoNameCoder());\n }\n\n /**\n * Creates an AbstractReader with a provided {@link NameCoder}.\n *\n * @param nameCoder the name coder used to read names from the incoming format\n * @since 1.4\n */\n protected AbstractReader(final NameCoder nameCoder) {\n this.nameCoder = Cloneables.cloneIfPossible(nameCoder);\n }\n\n @Override\n public HierarchicalStreamReader underlyingReader() {\n return this;\n }\n\n @Override\n public Iterator getAttributeNames() {\n return new AttributeNameIterator();\n }\n\n /**\n * Decode a node name from the target format.\n *\n * @param name the name in the target format\n * @return the original name\n * @since 1.4\n */\n public String decodeNode(final String name) {\n return nameCoder.decodeNode(name);\n }\n\n /**\n * Decode an attribute name from the target format.\n *\n * @param name the name in the target format\n * @return the original name\n * @since 1.4\n */\n public String decodeAttribute(final String name) {\n return nameCoder.decodeAttribute(name);\n }\n\n /**\n * Encode the node name again into the name of the target format. Internally used.\n *\n * @param name the original name\n * @return the name in the target format\n * @since 1.4\n */\n protected String encodeNode(final String name) {\n return nameCoder.encodeNode(name);\n }\n\n /**\n * Encode the attribute name again into the name of the target format. Internally used.\n *\n * @param name the original name\n * @return the name in the target format\n * @since 1.4\n */\n protected String encodeAttribute(final String name) {\n return nameCoder.encodeAttribute(name);\n }\n\n @Override\n public String peekNextChild() {\n throw new UnsupportedOperationException(\"peekNextChild\");\n }\n\n private class AttributeNameIterator implements Iterator {\n\n private int current;\n\n private final int count;\n\n public AttributeNameIterator() {\n count = getAttributeCount();\n }\n\n @Override\n public boolean hasNext() {\n return current < count;\n }\n\n @Override\n public String next() {\n return getAttributeName(current++);\n }\n\n ", "post_mask_code": "{\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_2063", "language": "Java", "task_type": "method_body", "source_file": "java/github/x-stream/xstream/xstream/src/java/com/thoughtworks/xstream/io/AbstractReader.java", "mask_start_position": 2672, "mask_end_position": 2745, "canonical_solution": "{\n throw new UnsupportedOperationException(\"peekNextChild\");\n }", "pre_mask_code": "/*\n * All rights reserved.\n *\n *\n * Created on 16. August 2009 by Joerg Schaible\n */\npackage com.thoughtworks.xstream.io;\n\nimport java.util.Iterator;\nimport com.thoughtworks.xstream.core.util.Cloneables;\nimport com.thoughtworks.xstream.io.naming.NameCoder;\nimport com.thoughtworks.xstream.io.naming.NoNameCoder;\n\n/**\n * Abstract base class for all HierarchicalStreamReader implementations. Implementations of\n * {@link HierarchicalStreamReader} should rather be derived from this class then implementing the interface directly.\n *\n * @author Jörg Schaible\n * @since 1.4\n */\npublic abstract class AbstractReader implements ExtendedHierarchicalStreamReader {\n\n private final NameCoder nameCoder;\n\n /**\n * Creates an AbstractReader with a NameCoder that does nothing.\n *\n * @since 1.4\n */\n protected AbstractReader() {\n this(new NoNameCoder());\n }\n\n /**\n * Creates an AbstractReader with a provided {@link NameCoder}.\n *\n * @param nameCoder the name coder used to read names from the incoming format\n * @since 1.4\n */\n protected AbstractReader(final NameCoder nameCoder) {\n this.nameCoder = Cloneables.cloneIfPossible(nameCoder);\n }\n\n @Override\n public HierarchicalStreamReader underlyingReader() {\n return this;\n }\n\n @Override\n public Iterator getAttributeNames() {\n return new AttributeNameIterator();\n }\n\n /**\n * Decode a node name from the target format.\n *\n * @param name the name in the target format\n * @return the original name\n * @since 1.4\n */\n public String decodeNode(final String name) {\n return nameCoder.decodeNode(name);\n }\n\n /**\n * Decode an attribute name from the target format.\n *\n * @param name the name in the target format\n * @return the original name\n * @since 1.4\n */\n public String decodeAttribute(final String name) {\n return nameCoder.decodeAttribute(name);\n }\n\n /**\n * Encode the node name again into the name of the target format. Internally used.\n *\n * @param name the original name\n * @return the name in the target format\n * @since 1.4\n */\n protected String encodeNode(final String name) {\n return nameCoder.encodeNode(name);\n }\n\n /**\n * Encode the attribute name again into the name of the target format. Internally used.\n *\n * @param name the original name\n * @return the name in the target format\n * @since 1.4\n */\n protected String encodeAttribute(final String name) {\n return nameCoder.encodeAttribute(name);\n }\n\n @Override\n public String peekNextChild() ", "post_mask_code": "\n\n private class AttributeNameIterator implements Iterator {\n\n private int current;\n\n private final int count;\n\n public AttributeNameIterator() {\n count = getAttributeCount();\n }\n\n @Override\n public boolean hasNext() {\n return current < count;\n }\n\n @Override\n public String next() {\n return getAttributeName(current++);\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_2064", "language": "Java", "task_type": "single_line", "source_file": "java/github/x-stream/xstream/xstream/src/java/com/thoughtworks/xstream/io/AbstractReader.java", "mask_start_position": 3059, "mask_end_position": 3063, "canonical_solution": "unt;", "pre_mask_code": "/*\n * All rights reserved.\n *\n *\n * Created on 16. August 2009 by Joerg Schaible\n */\npackage com.thoughtworks.xstream.io;\n\nimport java.util.Iterator;\nimport com.thoughtworks.xstream.core.util.Cloneables;\nimport com.thoughtworks.xstream.io.naming.NameCoder;\nimport com.thoughtworks.xstream.io.naming.NoNameCoder;\n\n/**\n * Abstract base class for all HierarchicalStreamReader implementations. Implementations of\n * {@link HierarchicalStreamReader} should rather be derived from this class then implementing the interface directly.\n *\n * @author Jörg Schaible\n * @since 1.4\n */\npublic abstract class AbstractReader implements ExtendedHierarchicalStreamReader {\n\n private final NameCoder nameCoder;\n\n /**\n * Creates an AbstractReader with a NameCoder that does nothing.\n *\n * @since 1.4\n */\n protected AbstractReader() {\n this(new NoNameCoder());\n }\n\n /**\n * Creates an AbstractReader with a provided {@link NameCoder}.\n *\n * @param nameCoder the name coder used to read names from the incoming format\n * @since 1.4\n */\n protected AbstractReader(final NameCoder nameCoder) {\n this.nameCoder = Cloneables.cloneIfPossible(nameCoder);\n }\n\n @Override\n public HierarchicalStreamReader underlyingReader() {\n return this;\n }\n\n @Override\n public Iterator getAttributeNames() {\n return new AttributeNameIterator();\n }\n\n /**\n * Decode a node name from the target format.\n *\n * @param name the name in the target format\n * @return the original name\n * @since 1.4\n */\n public String decodeNode(final String name) {\n return nameCoder.decodeNode(name);\n }\n\n /**\n * Decode an attribute name from the target format.\n *\n * @param name the name in the target format\n * @return the original name\n * @since 1.4\n */\n public String decodeAttribute(final String name) {\n return nameCoder.decodeAttribute(name);\n }\n\n /**\n * Encode the node name again into the name of the target format. Internally used.\n *\n * @param name the original name\n * @return the name in the target format\n * @since 1.4\n */\n protected String encodeNode(final String name) {\n return nameCoder.encodeNode(name);\n }\n\n /**\n * Encode the attribute name again into the name of the target format. Internally used.\n *\n * @param name the original name\n * @return the name in the target format\n * @since 1.4\n */\n protected String encodeAttribute(final String name) {\n return nameCoder.encodeAttribute(name);\n }\n\n @Override\n public String peekNextChild() {\n throw new UnsupportedOperationException(\"peekNextChild\");\n }\n\n private class AttributeNameIterator implements Iterator {\n\n private int current;\n\n private final int count;\n\n public AttributeNameIterator() {\n count = getAttributeCount();\n }\n\n @Override\n public boolean hasNext() {\n return current < co", "post_mask_code": "\n }\n\n @Override\n public String next() {\n return getAttributeName(current++);\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_2065", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/x-stream/xstream/xstream/src/java/com/thoughtworks/xstream/io/AbstractReader.java", "mask_start_position": 2515, "mask_end_position": 2622, "canonical_solution": "protected String encodeAttribute(final String name) {\n return nameCoder.encodeAttribute(name);\n }", "pre_mask_code": "/*\n * All rights reserved.\n *\n *\n * Created on 16. August 2009 by Joerg Schaible\n */\npackage com.thoughtworks.xstream.io;\n\nimport java.util.Iterator;\nimport com.thoughtworks.xstream.core.util.Cloneables;\nimport com.thoughtworks.xstream.io.naming.NameCoder;\nimport com.thoughtworks.xstream.io.naming.NoNameCoder;\n\n/**\n * Abstract base class for all HierarchicalStreamReader implementations. Implementations of\n * {@link HierarchicalStreamReader} should rather be derived from this class then implementing the interface directly.\n *\n * @author Jörg Schaible\n * @since 1.4\n */\npublic abstract class AbstractReader implements ExtendedHierarchicalStreamReader {\n\n private final NameCoder nameCoder;\n\n /**\n * Creates an AbstractReader with a NameCoder that does nothing.\n *\n * @since 1.4\n */\n protected AbstractReader() {\n this(new NoNameCoder());\n }\n\n /**\n * Creates an AbstractReader with a provided {@link NameCoder}.\n *\n * @param nameCoder the name coder used to read names from the incoming format\n * @since 1.4\n */\n protected AbstractReader(final NameCoder nameCoder) {\n this.nameCoder = Cloneables.cloneIfPossible(nameCoder);\n }\n\n @Override\n public HierarchicalStreamReader underlyingReader() {\n return this;\n }\n\n @Override\n public Iterator getAttributeNames() {\n return new AttributeNameIterator();\n }\n\n /**\n * Decode a node name from the target format.\n *\n * @param name the name in the target format\n * @return the original name\n * @since 1.4\n */\n public String decodeNode(final String name) {\n return nameCoder.decodeNode(name);\n }\n\n /**\n * Decode an attribute name from the target format.\n *\n * @param name the name in the target format\n * @return the original name\n * @since 1.4\n */\n public String decodeAttribute(final String name) {\n return nameCoder.decodeAttribute(name);\n }\n\n /**\n * Encode the node name again into the name of the target format. Internally used.\n *\n * @param name the original name\n * @return the name in the target format\n * @since 1.4\n */\n protected String encodeNode(final String name) {\n return nameCoder.encodeNode(name);\n }\n\n /**\n * Encode the attribute name again into the name of the target format. Internally used.\n *\n * @param name the original name\n * @return the name in the target format\n * @since 1.4\n */\n ", "post_mask_code": "\n\n @Override\n public String peekNextChild() {\n throw new UnsupportedOperationException(\"peekNextChild\");\n }\n\n private class AttributeNameIterator implements Iterator {\n\n private int current;\n\n private final int count;\n\n public AttributeNameIterator() {\n count = getAttributeCount();\n }\n\n @Override\n public boolean hasNext() {\n return current < count;\n }\n\n @Override\n public String next() {\n return getAttributeName(current++);\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n }\n}\n"} {"task_id": "Java_2066", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Pushjet/Pushjet-Android/gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/core/org/gradle/groovy/scripts/ScriptRunner.java", "mask_start_position": 336, "mask_end_position": 350, "canonical_solution": "T getScript();", "pre_mask_code": "package org.gradle.groovy.scripts;\n\nimport groovy.lang.Script;\nimport org.gradle.api.GradleScriptException;\n\n/**\n * Executes a script of type T.\n */\npublic interface ScriptRunner extends Runnable {\n\n /**\n * Returns the script which will be executed by this runner.\n *\n * @return the script.\n */\n ", "post_mask_code": "\n\n /**\n * Executes the script.\n *\n * @throws GradleScriptException On execution failure.\n */\n void run() throws GradleScriptException;\n}\n"} {"task_id": "Java_2067", "language": "Java", "task_type": "method_signature", "source_file": "java/github/LuXugang/Lucene-7.5.0/solr-7.5.0/lucene/analysis/stempel/src/java/org/egothor/stemmer/Optimizer2.java", "mask_start_position": 2142, "mask_end_position": 2190, "canonical_solution": "@Override\n public Cell merge(Cell m, Cell e) ", "pre_mask_code": "/*\n Egothor Software License version 1.00\n on behalf of the Egothor Project.\n All rights reserved.\n\n This software is copyrighted by the \"Egothor developers\". If this\n license applies to a single file or document, the \"Egothor developers\"\n are the people or entities mentioned as copyright holders in that file\n or document. If this license applies to the Egothor project as a\n whole, the copyright holders are the people or entities mentioned in\n the file CREDITS. This file can be found in the same location as this\n license in the distribution.\n\n written permission, please contact example@nnthink.com\n 4. Products derived from this software may not be called \"Egothor\",\n nor may \"Egothor\" appear in their name, without prior written\n permission from Leo.G@seznam.cz.\n\n In addition, we request that you include in the end-user documentation\n provided with the redistribution and/or in the software itself an\n acknowledgement equivalent to the following:\n \"This product includes software developed by the Egothor Project.\n http://example.com\"\n\n created by Leo Galambos (Leo.G@seznam.cz).\n */\npackage org.egothor.stemmer;\n\n/**\n * The Optimizer class is a Trie that will be reduced (have empty rows removed).\n *

\n * This is the result of allowing a joining of rows when there is no collision\n * between non-null values in the rows. Information loss, resulting in\n * the stemmer not being able to recognize words (as in Optimizer), is\n * curtailed, allowing the stemmer to recognize words for which the original\n * trie was built. Use of this class allows the stemmer to be self-teaching.\n */\npublic class Optimizer2 extends Optimizer {\n\n /**\n * Constructor for the Optimizer2 object.\n */\n public Optimizer2() {\n }\n\n /**\n * Merge the given Cells and return the resulting Cell.\n *\n * @param m the master Cell\n * @param e the existing Cell\n * @return the resulting Cell, or null if the operation cannot be\n * realized\n */\n ", "post_mask_code": "{\n if (m.cmd == e.cmd && m.ref == e.ref && m.skip == e.skip) {\n Cell c = new Cell(m);\n c.cnt += e.cnt;\n return c;\n } else {\n return null;\n }\n }\n}\n"} {"task_id": "Java_2068", "language": "Java", "task_type": "method_body", "source_file": "java/github/LuXugang/Lucene-7.5.0/solr-7.5.0/lucene/analysis/stempel/src/java/org/egothor/stemmer/Optimizer2.java", "mask_start_position": 2190, "mask_end_position": 2401, "canonical_solution": "{\n if (m.cmd == e.cmd && m.ref == e.ref && m.skip == e.skip) {\n Cell c = new Cell(m);\n c.cnt += e.cnt;\n return c;\n } else {\n return null;\n }\n }", "pre_mask_code": "/*\n Egothor Software License version 1.00\n on behalf of the Egothor Project.\n All rights reserved.\n\n This software is copyrighted by the \"Egothor developers\". If this\n license applies to a single file or document, the \"Egothor developers\"\n are the people or entities mentioned as copyright holders in that file\n or document. If this license applies to the Egothor project as a\n whole, the copyright holders are the people or entities mentioned in\n the file CREDITS. This file can be found in the same location as this\n license in the distribution.\n\n written permission, please contact example@nnthink.com\n 4. Products derived from this software may not be called \"Egothor\",\n nor may \"Egothor\" appear in their name, without prior written\n permission from Leo.G@seznam.cz.\n\n In addition, we request that you include in the end-user documentation\n provided with the redistribution and/or in the software itself an\n acknowledgement equivalent to the following:\n \"This product includes software developed by the Egothor Project.\n http://example.com\"\n\n created by Leo Galambos (Leo.G@seznam.cz).\n */\npackage org.egothor.stemmer;\n\n/**\n * The Optimizer class is a Trie that will be reduced (have empty rows removed).\n *

\n * This is the result of allowing a joining of rows when there is no collision\n * between non-null values in the rows. Information loss, resulting in\n * the stemmer not being able to recognize words (as in Optimizer), is\n * curtailed, allowing the stemmer to recognize words for which the original\n * trie was built. Use of this class allows the stemmer to be self-teaching.\n */\npublic class Optimizer2 extends Optimizer {\n\n /**\n * Constructor for the Optimizer2 object.\n */\n public Optimizer2() {\n }\n\n /**\n * Merge the given Cells and return the resulting Cell.\n *\n * @param m the master Cell\n * @param e the existing Cell\n * @return the resulting Cell, or null if the operation cannot be\n * realized\n */\n @Override\n public Cell merge(Cell m, Cell e) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2069", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/LuXugang/Lucene-7.5.0/solr-7.5.0/lucene/analysis/stempel/src/java/org/egothor/stemmer/Optimizer2.java", "mask_start_position": 2142, "mask_end_position": 2401, "canonical_solution": "@Override\n public Cell merge(Cell m, Cell e) {\n if (m.cmd == e.cmd && m.ref == e.ref && m.skip == e.skip) {\n Cell c = new Cell(m);\n c.cnt += e.cnt;\n return c;\n } else {\n return null;\n }\n }", "pre_mask_code": "/*\n Egothor Software License version 1.00\n on behalf of the Egothor Project.\n All rights reserved.\n\n This software is copyrighted by the \"Egothor developers\". If this\n license applies to a single file or document, the \"Egothor developers\"\n are the people or entities mentioned as copyright holders in that file\n or document. If this license applies to the Egothor project as a\n whole, the copyright holders are the people or entities mentioned in\n the file CREDITS. This file can be found in the same location as this\n license in the distribution.\n\n written permission, please contact example@nnthink.com\n 4. Products derived from this software may not be called \"Egothor\",\n nor may \"Egothor\" appear in their name, without prior written\n permission from Leo.G@seznam.cz.\n\n In addition, we request that you include in the end-user documentation\n provided with the redistribution and/or in the software itself an\n acknowledgement equivalent to the following:\n \"This product includes software developed by the Egothor Project.\n http://example.com\"\n\n created by Leo Galambos (Leo.G@seznam.cz).\n */\npackage org.egothor.stemmer;\n\n/**\n * The Optimizer class is a Trie that will be reduced (have empty rows removed).\n *

\n * This is the result of allowing a joining of rows when there is no collision\n * between non-null values in the rows. Information loss, resulting in\n * the stemmer not being able to recognize words (as in Optimizer), is\n * curtailed, allowing the stemmer to recognize words for which the original\n * trie was built. Use of this class allows the stemmer to be self-teaching.\n */\npublic class Optimizer2 extends Optimizer {\n\n /**\n * Constructor for the Optimizer2 object.\n */\n public Optimizer2() {\n }\n\n /**\n * Merge the given Cells and return the resulting Cell.\n *\n * @param m the master Cell\n * @param e the existing Cell\n * @return the resulting Cell, or null if the operation cannot be\n * realized\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2070", "language": "Java", "task_type": "if_statement", "source_file": "java/github/LuXugang/Lucene-7.5.0/solr-7.5.0/lucene/analysis/stempel/src/java/org/egothor/stemmer/Optimizer2.java", "mask_start_position": 2200, "mask_end_position": 2395, "canonical_solution": "if (m.cmd == e.cmd && m.ref == e.ref && m.skip == e.skip) {\n Cell c = new Cell(m);\n c.cnt += e.cnt;\n return c;\n } else {\n return null;\n }", "pre_mask_code": "/*\n Egothor Software License version 1.00\n on behalf of the Egothor Project.\n All rights reserved.\n\n This software is copyrighted by the \"Egothor developers\". If this\n license applies to a single file or document, the \"Egothor developers\"\n are the people or entities mentioned as copyright holders in that file\n or document. If this license applies to the Egothor project as a\n whole, the copyright holders are the people or entities mentioned in\n the file CREDITS. This file can be found in the same location as this\n license in the distribution.\n\n written permission, please contact example@nnthink.com\n 4. Products derived from this software may not be called \"Egothor\",\n nor may \"Egothor\" appear in their name, without prior written\n permission from Leo.G@seznam.cz.\n\n In addition, we request that you include in the end-user documentation\n provided with the redistribution and/or in the software itself an\n acknowledgement equivalent to the following:\n \"This product includes software developed by the Egothor Project.\n http://example.com\"\n\n created by Leo Galambos (Leo.G@seznam.cz).\n */\npackage org.egothor.stemmer;\n\n/**\n * The Optimizer class is a Trie that will be reduced (have empty rows removed).\n *

\n * This is the result of allowing a joining of rows when there is no collision\n * between non-null values in the rows. Information loss, resulting in\n * the stemmer not being able to recognize words (as in Optimizer), is\n * curtailed, allowing the stemmer to recognize words for which the original\n * trie was built. Use of this class allows the stemmer to be self-teaching.\n */\npublic class Optimizer2 extends Optimizer {\n\n /**\n * Constructor for the Optimizer2 object.\n */\n public Optimizer2() {\n }\n\n /**\n * Merge the given Cells and return the resulting Cell.\n *\n * @param m the master Cell\n * @param e the existing Cell\n * @return the resulting Cell, or null if the operation cannot be\n * realized\n */\n @Override\n public Cell merge(Cell m, Cell e) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2071", "language": "Java", "task_type": "method_signature", "source_file": "java/github/marcusklang/wikiforia/src/main/java/se/lth/cs/nlp/wikipedia/lang/IiConfig.java", "mask_start_position": 8649, "mask_end_position": 8693, "canonical_solution": "@Override\n protected String getWikiUrl() ", "pre_mask_code": "/**\n * This file is part of Wikiforia.\n */\npackage se.lth.cs.nlp.wikipedia.lang;\n\n// Autogenerated from Wikimedia sources at 2015-04-16T13:55:11+00:00\npublic class IiConfig extends TemplateConfig {\n\n public IiConfig() {\n addNamespaceAlias(-2, \"媒体文件\", \"媒体\");\n addNamespaceAlias(-1, \"特殊\", \"特殊\");\n addNamespaceAlias(1, \"讨论\", \"对话\", \"讨论\");\n addNamespaceAlias(2, \"用户\", \"用户\");\n addNamespaceAlias(3, \"用户讨论\", \"用户对话\", \"用户讨论\");\n addNamespaceAlias(5, \"Wikipedia讨论\");\n addNamespaceAlias(6, \"文件\", \"图像\", \"档案\", \"文件\", \"Image\");\n addNamespaceAlias(7, \"文件讨论\", \"Image_talk\", \"图像对话\", \"图像讨论\", \"档案对话\", \"档案讨论\", \"文件对话\", \"文件讨论\");\n addNamespaceAlias(8, \"MediaWiki\");\n addNamespaceAlias(9, \"MediaWiki讨论\");\n addNamespaceAlias(10, \"模板\", \"模板\");\n addNamespaceAlias(11, \"模板讨论\", \"模板对话\", \"模板讨论\");\n addNamespaceAlias(12, \"帮助\", \"帮助\");\n addNamespaceAlias(13, \"帮助讨论\", \"帮助对话\", \"帮助讨论\");\n addNamespaceAlias(14, \"分类\", \"分类\");\n addNamespaceAlias(15, \"分类讨论\", \"分类对话\", \"分类讨论\");\n addI18nCIAlias(\"redirect\", \"#重定向\", \"#REDIRECT\");\n addI18nCIAlias(\"notoc\", \"__无目录__\", \"__NOTOC__\");\n addI18nCIAlias(\"nogallery\", \"__无图库__\", \"__NOGALLERY__\");\n addI18nCIAlias(\"forcetoc\", \"__强显目录__\", \"__FORCETOC__\");\n addI18nCIAlias(\"toc\", \"__目录__\", \"__TOC__\");\n addI18nCIAlias(\"noeditsection\", \"__无编辑段落__\", \"__无段落编辑__\", \"__NOEDITSECTION__\");\n addI18nAlias(\"currentmonth\", \"本月\", \"本月2\", \"CURRENTMONTH\", \"CURRENTMONTH2\");\n addI18nAlias(\"currentmonth1\", \"本月1\", \"CURRENTMONTH1\");\n addI18nAlias(\"currentmonthname\", \"本月名\", \"本月名称\", \"CURRENTMONTHNAME\");\n addI18nAlias(\"currentmonthnamegen\", \"本月名属格\", \"本月名称属格\", \"CURRENTMONTHNAMEGEN\");\n addI18nAlias(\"currentmonthabbrev\", \"本月简称\", \"CURRENTMONTHABBREV\");\n addI18nAlias(\"currentday\", \"今天\", \"CURRENTDAY\");\n addI18nAlias(\"currentday2\", \"今天2\", \"CURRENTDAY2\");\n addI18nAlias(\"currentdayname\", \"星期\", \"今天名\", \"今天名称\", \"CURRENTDAYNAME\");\n addI18nAlias(\"currentyear\", \"今年\", \"CURRENTYEAR\");\n addI18nAlias(\"currenttime\", \"当前时间\", \"此时\", \"CURRENTTIME\");\n addI18nAlias(\"currenthour\", \"当前小时\", \"CURRENTHOUR\");\n addI18nAlias(\"localmonth\", \"本地月\", \"LOCALMONTH\", \"LOCALMONTH2\");\n addI18nAlias(\"localmonthname\", \"本地月份名\", \"LOCALMONTHNAME\");\n addI18nAlias(\"localmonthnamegen\", \"本地月历\", \"LOCALMONTHNAMEGEN\");\n addI18nAlias(\"localday\", \"本地日\", \"LOCALDAY\");\n addI18nAlias(\"localdayname\", \"本地日名\", \"LOCALDAYNAME\");\n addI18nAlias(\"localyear\", \"本地年\", \"LOCALYEAR\");\n addI18nAlias(\"localtime\", \"本地时间\", \"LOCALTIME\");\n addI18nAlias(\"localhour\", \"本地小时\", \"LOCALHOUR\");\n addI18nAlias(\"numberofpages\", \"页面数\", \"NUMBEROFPAGES\");\n addI18nAlias(\"numberofarticles\", \"条目数\", \"NUMBEROFARTICLES\");\n addI18nAlias(\"numberoffiles\", \"文件数\", \"NUMBEROFFILES\");\n addI18nAlias(\"numberofusers\", \"用户数\", \"NUMBEROFUSERS\");\n addI18nAlias(\"numberofactiveusers\", \"活跃用户数\", \"NUMBEROFACTIVEUSERS\");\n addI18nAlias(\"numberofedits\", \"编辑数\", \"NUMBEROFEDITS\");\n addI18nAlias(\"numberofviews\", \"访问数\", \"NUMBEROFVIEWS\");\n addI18nAlias(\"pagename\", \"页名\", \"页面名\", \"页面名称\", \"PAGENAME\");\n addI18nAlias(\"pagenamee\", \"页名等同\", \"页面名等同\", \"页面名E\", \"PAGENAMEE\");\n addI18nAlias(\"namespace\", \"名字空间\", \"NAMESPACE\");\n addI18nAlias(\"namespacee\", \"名字空间等同\", \"名字空间E\", \"NAMESPACEE\");\n addI18nAlias(\"namespacenumber\", \"名字空间编号\", \"NAMESPACENUMBER\");\n addI18nAlias(\"talkspace\", \"讨论空间\", \"讨论名字空间\", \"TALKSPACE\");\n addI18nAlias(\"talkspacee\", \"讨论空间等同\", \"讨论名字空间E\", \"TALKSPACEE\");\n addI18nAlias(\"fullpagename\", \"页面全名\", \"完整页面名\", \"FULLPAGENAME\");\n addI18nAlias(\"fullpagenamee\", \"完整页面名E\", \"FULLPAGENAMEE\");\n addI18nAlias(\"subpagename\", \"子页面名\", \"SUBPAGENAME\");\n addI18nAlias(\"subpagenamee\", \"子页面名等同\", \"子页面名E\", \"SUBPAGENAMEE\");\n addI18nAlias(\"talkpagename\", \"讨论页面名\", \"TALKPAGENAME\");\n addI18nAlias(\"talkpagenamee\", \"讨论页面名等同\", \"讨论页面名E\", \"TALKPAGENAMEE\");\n addI18nCIAlias(\"subst\", \"替代:\", \"SUBST:\");\n addI18nCIAlias(\"safesubst\", \"安全替代:\", \"SAFESUBST:\");\n addI18nAlias(\"img_thumbnail\", \"缩略图\", \"thumbnail\", \"thumb\");\n addI18nAlias(\"img_manualthumb\", \"缩略图=$1\", \"thumbnail=$1\", \"thumb=$1\");\n addI18nAlias(\"img_right\", \"右\", \"right\");\n addI18nAlias(\"img_left\", \"左\", \"left\");\n addI18nAlias(\"img_none\", \"无\", \"none\");\n addI18nAlias(\"img_width\", \"$1像素\", \"$1px\");\n addI18nAlias(\"img_center\", \"居中\", \"center\", \"centre\");\n addI18nAlias(\"img_framed\", \"有框\", \"framed\", \"enframed\", \"frame\");\n addI18nAlias(\"img_frameless\", \"无框\", \"frameless\");\n addI18nAlias(\"img_page\", \"页数=$1\", \"$1页\", \"page=$1\", \"page $1\");\n addI18nAlias(\"img_border\", \"边框\", \"border\");\n addI18nAlias(\"img_link\", \"链接=$1\", \"link=$1\");\n addI18nAlias(\"img_alt\", \"替代=$1\", \"替代文本=$1\", \"alt=$1\");\n addI18nAlias(\"img_class\", \"类=$1\", \"class=$1\");\n addI18nCIAlias(\"int\", \"界面:\", \"INT:\");\n addI18nAlias(\"sitename\", \"站点名称\", \"SITENAME\");\n addI18nCIAlias(\"ns\", \"名字空间:\", \"NS:\");\n addI18nCIAlias(\"nse\", \"名字空间E:\", \"NSE:\");\n addI18nCIAlias(\"localurl\", \"本地URL:\", \"LOCALURL:\");\n addI18nCIAlias(\"localurle\", \"本地URLE:\", \"LOCALURLE:\");\n addI18nCIAlias(\"articlepath\", \"条目路径\", \"ARTICLEPATH\");\n addI18nCIAlias(\"pageid\", \"页面ID\", \"PAGEID\");\n addI18nCIAlias(\"server\", \"服务器\", \"SERVER\");\n addI18nCIAlias(\"servername\", \"服务器名\", \"SERVERNAME\");\n addI18nCIAlias(\"scriptpath\", \"脚本路径\", \"SCRIPTPATH\");\n addI18nCIAlias(\"stylepath\", \"样式路径\", \"STYLEPATH\");\n addI18nCIAlias(\"grammar\", \"语法:\", \"GRAMMAR:\");\n addI18nCIAlias(\"gender\", \"性:\", \"性别:\", \"GENDER:\");\n addI18nCIAlias(\"notitleconvert\", \"__不转换标题__\", \"__NOTITLECONVERT__\", \"__NOTC__\");\n addI18nCIAlias(\"nocontentconvert\", \"__不转换内容__\", \"__NOCONTENTCONVERT__\", \"__NOCC__\");\n addI18nAlias(\"currentweek\", \"本周\", \"CURRENTWEEK\");\n addI18nCIAlias(\"plural\", \"复数:\", \"PLURAL:\");\n addI18nCIAlias(\"fullurl\", \"完整URL:\", \"FULLURL:\");\n addI18nCIAlias(\"fullurle\", \"完整URL等同:\", \"完整URLE:\", \"FULLURLE:\");\n addI18nCIAlias(\"lcfirst\", \"小写首字:\", \"LCFIRST:\");\n addI18nCIAlias(\"ucfirst\", \"大写首字:\", \"UCFIRST:\");\n addI18nCIAlias(\"lc\", \"小写:\", \"LC:\");\n addI18nCIAlias(\"uc\", \"大写:\", \"UC:\");\n addI18nAlias(\"displaytitle\", \"显示标题\", \"DISPLAYTITLE\");\n addI18nAlias(\"newsectionlink\", \"__新段落链接__\", \"__NEWSECTIONLINK__\");\n addI18nAlias(\"nonewsectionlink\", \"__无新段落链接__\", \"__NONEWSECTIONLINK__\");\n addI18nAlias(\"currentversion\", \"当前版本\", \"CURRENTVERSION\");\n addI18nCIAlias(\"urlencode\", \"URL编码:\", \"URLENCODE:\");\n addI18nCIAlias(\"anchorencode\", \"锚编码\", \"ANCHORENCODE\");\n addI18nAlias(\"currenttimestamp\", \"当前时间戳\", \"CURRENTTIMESTAMP\");\n addI18nAlias(\"localtimestamp\", \"本地时间戳\", \"LOCALTIMESTAMP\");\n addI18nAlias(\"directionmark\", \"方向标记\", \"DIRECTIONMARK\", \"DIRMARK\");\n addI18nCIAlias(\"language\", \"#语言:\", \"#LANGUAGE:\");\n addI18nAlias(\"contentlanguage\", \"内容语言\", \"CONTENTLANGUAGE\", \"CONTENTLANG\");\n addI18nAlias(\"pagesinnamespace\", \"名字空间中页面数:\", \"PAGESINNAMESPACE:\", \"PAGESINNS:\");\n addI18nAlias(\"numberofadmins\", \"管理员数\", \"NUMBEROFADMINS\");\n addI18nCIAlias(\"formatnum\", \"格式化数字\", \"FORMATNUM\");\n addI18nCIAlias(\"padleft\", \"左填充\", \"PADLEFT\");\n addI18nCIAlias(\"padright\", \"右填充\", \"PADRIGHT\");\n addI18nCIAlias(\"special\", \"特殊\", \"special\");\n addI18nCIAlias(\"speciale\", \"特殊等同\", \"特殊e\", \"speciale\");\n addI18nAlias(\"defaultsort\", \"默认排序:\", \"默认排序关键字:\", \"默认分类排序:\", \"DEFAULTSORT:\", \"DEFAULTSORTKEY:\", \"DEFAULTCATEGORYSORT:\");\n addI18nCIAlias(\"filepath\", \"文件路径:\", \"FILEPATH:\");\n addI18nCIAlias(\"tag\", \"标记\", \"tag\");\n addI18nAlias(\"hiddencat\", \"__隐藏分类__\", \"__HIDDENCAT__\");\n addI18nAlias(\"pagesincategory\", \"分类中页数\", \"分类中页面数\", \"PAGESINCATEGORY\", \"PAGESINCAT\");\n addI18nAlias(\"pagesize\", \"页面大小\", \"PAGESIZE\");\n addI18nAlias(\"index\", \"__索引__\", \"__INDEX__\");\n addI18nAlias(\"noindex\", \"__不索引__\", \"__NOINDEX__\");\n addI18nAlias(\"numberingroup\", \"组中用户数\", \"NUMBERINGROUP\", \"NUMINGROUP\");\n addI18nAlias(\"staticredirect\", \"__静态重定向__\", \"__STATICREDIRECT__\");\n addI18nAlias(\"protectionlevel\", \"保护级别\", \"PROTECTIONLEVEL\");\n addI18nCIAlias(\"formatdate\", \"格式化日期\", \"日期格式化\", \"formatdate\", \"dateformat\");\n addI18nCIAlias(\"defaultsort_noerror\", \"不报错\", \"noerror\");\n addI18nCIAlias(\"defaultsort_noreplace\", \"不替换\", \"noreplace\");\n }\n\n @Override\n protected String getSiteName() {\n return \"Wikipedia\";\n }\n\n ", "post_mask_code": "{\n return \"http://example.com\";\n }\n\n @Override\n public String getIso639() {\n return \"ii\";\n }\n}\n"} {"task_id": "Java_2072", "language": "Java", "task_type": "method_body", "source_file": "java/github/marcusklang/wikiforia/src/main/java/se/lth/cs/nlp/wikipedia/lang/IiConfig.java", "mask_start_position": 8693, "mask_end_position": 8737, "canonical_solution": "{\n return \"http://example.com\";\n }", "pre_mask_code": "/**\n * This file is part of Wikiforia.\n */\npackage se.lth.cs.nlp.wikipedia.lang;\n\n// Autogenerated from Wikimedia sources at 2015-04-16T13:55:11+00:00\npublic class IiConfig extends TemplateConfig {\n\n public IiConfig() {\n addNamespaceAlias(-2, \"媒体文件\", \"媒体\");\n addNamespaceAlias(-1, \"特殊\", \"特殊\");\n addNamespaceAlias(1, \"讨论\", \"对话\", \"讨论\");\n addNamespaceAlias(2, \"用户\", \"用户\");\n addNamespaceAlias(3, \"用户讨论\", \"用户对话\", \"用户讨论\");\n addNamespaceAlias(5, \"Wikipedia讨论\");\n addNamespaceAlias(6, \"文件\", \"图像\", \"档案\", \"文件\", \"Image\");\n addNamespaceAlias(7, \"文件讨论\", \"Image_talk\", \"图像对话\", \"图像讨论\", \"档案对话\", \"档案讨论\", \"文件对话\", \"文件讨论\");\n addNamespaceAlias(8, \"MediaWiki\");\n addNamespaceAlias(9, \"MediaWiki讨论\");\n addNamespaceAlias(10, \"模板\", \"模板\");\n addNamespaceAlias(11, \"模板讨论\", \"模板对话\", \"模板讨论\");\n addNamespaceAlias(12, \"帮助\", \"帮助\");\n addNamespaceAlias(13, \"帮助讨论\", \"帮助对话\", \"帮助讨论\");\n addNamespaceAlias(14, \"分类\", \"分类\");\n addNamespaceAlias(15, \"分类讨论\", \"分类对话\", \"分类讨论\");\n addI18nCIAlias(\"redirect\", \"#重定向\", \"#REDIRECT\");\n addI18nCIAlias(\"notoc\", \"__无目录__\", \"__NOTOC__\");\n addI18nCIAlias(\"nogallery\", \"__无图库__\", \"__NOGALLERY__\");\n addI18nCIAlias(\"forcetoc\", \"__强显目录__\", \"__FORCETOC__\");\n addI18nCIAlias(\"toc\", \"__目录__\", \"__TOC__\");\n addI18nCIAlias(\"noeditsection\", \"__无编辑段落__\", \"__无段落编辑__\", \"__NOEDITSECTION__\");\n addI18nAlias(\"currentmonth\", \"本月\", \"本月2\", \"CURRENTMONTH\", \"CURRENTMONTH2\");\n addI18nAlias(\"currentmonth1\", \"本月1\", \"CURRENTMONTH1\");\n addI18nAlias(\"currentmonthname\", \"本月名\", \"本月名称\", \"CURRENTMONTHNAME\");\n addI18nAlias(\"currentmonthnamegen\", \"本月名属格\", \"本月名称属格\", \"CURRENTMONTHNAMEGEN\");\n addI18nAlias(\"currentmonthabbrev\", \"本月简称\", \"CURRENTMONTHABBREV\");\n addI18nAlias(\"currentday\", \"今天\", \"CURRENTDAY\");\n addI18nAlias(\"currentday2\", \"今天2\", \"CURRENTDAY2\");\n addI18nAlias(\"currentdayname\", \"星期\", \"今天名\", \"今天名称\", \"CURRENTDAYNAME\");\n addI18nAlias(\"currentyear\", \"今年\", \"CURRENTYEAR\");\n addI18nAlias(\"currenttime\", \"当前时间\", \"此时\", \"CURRENTTIME\");\n addI18nAlias(\"currenthour\", \"当前小时\", \"CURRENTHOUR\");\n addI18nAlias(\"localmonth\", \"本地月\", \"LOCALMONTH\", \"LOCALMONTH2\");\n addI18nAlias(\"localmonthname\", \"本地月份名\", \"LOCALMONTHNAME\");\n addI18nAlias(\"localmonthnamegen\", \"本地月历\", \"LOCALMONTHNAMEGEN\");\n addI18nAlias(\"localday\", \"本地日\", \"LOCALDAY\");\n addI18nAlias(\"localdayname\", \"本地日名\", \"LOCALDAYNAME\");\n addI18nAlias(\"localyear\", \"本地年\", \"LOCALYEAR\");\n addI18nAlias(\"localtime\", \"本地时间\", \"LOCALTIME\");\n addI18nAlias(\"localhour\", \"本地小时\", \"LOCALHOUR\");\n addI18nAlias(\"numberofpages\", \"页面数\", \"NUMBEROFPAGES\");\n addI18nAlias(\"numberofarticles\", \"条目数\", \"NUMBEROFARTICLES\");\n addI18nAlias(\"numberoffiles\", \"文件数\", \"NUMBEROFFILES\");\n addI18nAlias(\"numberofusers\", \"用户数\", \"NUMBEROFUSERS\");\n addI18nAlias(\"numberofactiveusers\", \"活跃用户数\", \"NUMBEROFACTIVEUSERS\");\n addI18nAlias(\"numberofedits\", \"编辑数\", \"NUMBEROFEDITS\");\n addI18nAlias(\"numberofviews\", \"访问数\", \"NUMBEROFVIEWS\");\n addI18nAlias(\"pagename\", \"页名\", \"页面名\", \"页面名称\", \"PAGENAME\");\n addI18nAlias(\"pagenamee\", \"页名等同\", \"页面名等同\", \"页面名E\", \"PAGENAMEE\");\n addI18nAlias(\"namespace\", \"名字空间\", \"NAMESPACE\");\n addI18nAlias(\"namespacee\", \"名字空间等同\", \"名字空间E\", \"NAMESPACEE\");\n addI18nAlias(\"namespacenumber\", \"名字空间编号\", \"NAMESPACENUMBER\");\n addI18nAlias(\"talkspace\", \"讨论空间\", \"讨论名字空间\", \"TALKSPACE\");\n addI18nAlias(\"talkspacee\", \"讨论空间等同\", \"讨论名字空间E\", \"TALKSPACEE\");\n addI18nAlias(\"fullpagename\", \"页面全名\", \"完整页面名\", \"FULLPAGENAME\");\n addI18nAlias(\"fullpagenamee\", \"完整页面名E\", \"FULLPAGENAMEE\");\n addI18nAlias(\"subpagename\", \"子页面名\", \"SUBPAGENAME\");\n addI18nAlias(\"subpagenamee\", \"子页面名等同\", \"子页面名E\", \"SUBPAGENAMEE\");\n addI18nAlias(\"talkpagename\", \"讨论页面名\", \"TALKPAGENAME\");\n addI18nAlias(\"talkpagenamee\", \"讨论页面名等同\", \"讨论页面名E\", \"TALKPAGENAMEE\");\n addI18nCIAlias(\"subst\", \"替代:\", \"SUBST:\");\n addI18nCIAlias(\"safesubst\", \"安全替代:\", \"SAFESUBST:\");\n addI18nAlias(\"img_thumbnail\", \"缩略图\", \"thumbnail\", \"thumb\");\n addI18nAlias(\"img_manualthumb\", \"缩略图=$1\", \"thumbnail=$1\", \"thumb=$1\");\n addI18nAlias(\"img_right\", \"右\", \"right\");\n addI18nAlias(\"img_left\", \"左\", \"left\");\n addI18nAlias(\"img_none\", \"无\", \"none\");\n addI18nAlias(\"img_width\", \"$1像素\", \"$1px\");\n addI18nAlias(\"img_center\", \"居中\", \"center\", \"centre\");\n addI18nAlias(\"img_framed\", \"有框\", \"framed\", \"enframed\", \"frame\");\n addI18nAlias(\"img_frameless\", \"无框\", \"frameless\");\n addI18nAlias(\"img_page\", \"页数=$1\", \"$1页\", \"page=$1\", \"page $1\");\n addI18nAlias(\"img_border\", \"边框\", \"border\");\n addI18nAlias(\"img_link\", \"链接=$1\", \"link=$1\");\n addI18nAlias(\"img_alt\", \"替代=$1\", \"替代文本=$1\", \"alt=$1\");\n addI18nAlias(\"img_class\", \"类=$1\", \"class=$1\");\n addI18nCIAlias(\"int\", \"界面:\", \"INT:\");\n addI18nAlias(\"sitename\", \"站点名称\", \"SITENAME\");\n addI18nCIAlias(\"ns\", \"名字空间:\", \"NS:\");\n addI18nCIAlias(\"nse\", \"名字空间E:\", \"NSE:\");\n addI18nCIAlias(\"localurl\", \"本地URL:\", \"LOCALURL:\");\n addI18nCIAlias(\"localurle\", \"本地URLE:\", \"LOCALURLE:\");\n addI18nCIAlias(\"articlepath\", \"条目路径\", \"ARTICLEPATH\");\n addI18nCIAlias(\"pageid\", \"页面ID\", \"PAGEID\");\n addI18nCIAlias(\"server\", \"服务器\", \"SERVER\");\n addI18nCIAlias(\"servername\", \"服务器名\", \"SERVERNAME\");\n addI18nCIAlias(\"scriptpath\", \"脚本路径\", \"SCRIPTPATH\");\n addI18nCIAlias(\"stylepath\", \"样式路径\", \"STYLEPATH\");\n addI18nCIAlias(\"grammar\", \"语法:\", \"GRAMMAR:\");\n addI18nCIAlias(\"gender\", \"性:\", \"性别:\", \"GENDER:\");\n addI18nCIAlias(\"notitleconvert\", \"__不转换标题__\", \"__NOTITLECONVERT__\", \"__NOTC__\");\n addI18nCIAlias(\"nocontentconvert\", \"__不转换内容__\", \"__NOCONTENTCONVERT__\", \"__NOCC__\");\n addI18nAlias(\"currentweek\", \"本周\", \"CURRENTWEEK\");\n addI18nCIAlias(\"plural\", \"复数:\", \"PLURAL:\");\n addI18nCIAlias(\"fullurl\", \"完整URL:\", \"FULLURL:\");\n addI18nCIAlias(\"fullurle\", \"完整URL等同:\", \"完整URLE:\", \"FULLURLE:\");\n addI18nCIAlias(\"lcfirst\", \"小写首字:\", \"LCFIRST:\");\n addI18nCIAlias(\"ucfirst\", \"大写首字:\", \"UCFIRST:\");\n addI18nCIAlias(\"lc\", \"小写:\", \"LC:\");\n addI18nCIAlias(\"uc\", \"大写:\", \"UC:\");\n addI18nAlias(\"displaytitle\", \"显示标题\", \"DISPLAYTITLE\");\n addI18nAlias(\"newsectionlink\", \"__新段落链接__\", \"__NEWSECTIONLINK__\");\n addI18nAlias(\"nonewsectionlink\", \"__无新段落链接__\", \"__NONEWSECTIONLINK__\");\n addI18nAlias(\"currentversion\", \"当前版本\", \"CURRENTVERSION\");\n addI18nCIAlias(\"urlencode\", \"URL编码:\", \"URLENCODE:\");\n addI18nCIAlias(\"anchorencode\", \"锚编码\", \"ANCHORENCODE\");\n addI18nAlias(\"currenttimestamp\", \"当前时间戳\", \"CURRENTTIMESTAMP\");\n addI18nAlias(\"localtimestamp\", \"本地时间戳\", \"LOCALTIMESTAMP\");\n addI18nAlias(\"directionmark\", \"方向标记\", \"DIRECTIONMARK\", \"DIRMARK\");\n addI18nCIAlias(\"language\", \"#语言:\", \"#LANGUAGE:\");\n addI18nAlias(\"contentlanguage\", \"内容语言\", \"CONTENTLANGUAGE\", \"CONTENTLANG\");\n addI18nAlias(\"pagesinnamespace\", \"名字空间中页面数:\", \"PAGESINNAMESPACE:\", \"PAGESINNS:\");\n addI18nAlias(\"numberofadmins\", \"管理员数\", \"NUMBEROFADMINS\");\n addI18nCIAlias(\"formatnum\", \"格式化数字\", \"FORMATNUM\");\n addI18nCIAlias(\"padleft\", \"左填充\", \"PADLEFT\");\n addI18nCIAlias(\"padright\", \"右填充\", \"PADRIGHT\");\n addI18nCIAlias(\"special\", \"特殊\", \"special\");\n addI18nCIAlias(\"speciale\", \"特殊等同\", \"特殊e\", \"speciale\");\n addI18nAlias(\"defaultsort\", \"默认排序:\", \"默认排序关键字:\", \"默认分类排序:\", \"DEFAULTSORT:\", \"DEFAULTSORTKEY:\", \"DEFAULTCATEGORYSORT:\");\n addI18nCIAlias(\"filepath\", \"文件路径:\", \"FILEPATH:\");\n addI18nCIAlias(\"tag\", \"标记\", \"tag\");\n addI18nAlias(\"hiddencat\", \"__隐藏分类__\", \"__HIDDENCAT__\");\n addI18nAlias(\"pagesincategory\", \"分类中页数\", \"分类中页面数\", \"PAGESINCATEGORY\", \"PAGESINCAT\");\n addI18nAlias(\"pagesize\", \"页面大小\", \"PAGESIZE\");\n addI18nAlias(\"index\", \"__索引__\", \"__INDEX__\");\n addI18nAlias(\"noindex\", \"__不索引__\", \"__NOINDEX__\");\n addI18nAlias(\"numberingroup\", \"组中用户数\", \"NUMBERINGROUP\", \"NUMINGROUP\");\n addI18nAlias(\"staticredirect\", \"__静态重定向__\", \"__STATICREDIRECT__\");\n addI18nAlias(\"protectionlevel\", \"保护级别\", \"PROTECTIONLEVEL\");\n addI18nCIAlias(\"formatdate\", \"格式化日期\", \"日期格式化\", \"formatdate\", \"dateformat\");\n addI18nCIAlias(\"defaultsort_noerror\", \"不报错\", \"noerror\");\n addI18nCIAlias(\"defaultsort_noreplace\", \"不替换\", \"noreplace\");\n }\n\n @Override\n protected String getSiteName() {\n return \"Wikipedia\";\n }\n\n @Override\n protected String getWikiUrl() ", "post_mask_code": "\n\n @Override\n public String getIso639() {\n return \"ii\";\n }\n}\n"} {"task_id": "Java_2073", "language": "Java", "task_type": "single_line", "source_file": "java/github/marcusklang/wikiforia/src/main/java/se/lth/cs/nlp/wikipedia/lang/IiConfig.java", "mask_start_position": 8799, "mask_end_position": 8805, "canonical_solution": " \"ii\";", "pre_mask_code": "/**\n * This file is part of Wikiforia.\n */\npackage se.lth.cs.nlp.wikipedia.lang;\n\n// Autogenerated from Wikimedia sources at 2015-04-16T13:55:11+00:00\npublic class IiConfig extends TemplateConfig {\n\n public IiConfig() {\n addNamespaceAlias(-2, \"媒体文件\", \"媒体\");\n addNamespaceAlias(-1, \"特殊\", \"特殊\");\n addNamespaceAlias(1, \"讨论\", \"对话\", \"讨论\");\n addNamespaceAlias(2, \"用户\", \"用户\");\n addNamespaceAlias(3, \"用户讨论\", \"用户对话\", \"用户讨论\");\n addNamespaceAlias(5, \"Wikipedia讨论\");\n addNamespaceAlias(6, \"文件\", \"图像\", \"档案\", \"文件\", \"Image\");\n addNamespaceAlias(7, \"文件讨论\", \"Image_talk\", \"图像对话\", \"图像讨论\", \"档案对话\", \"档案讨论\", \"文件对话\", \"文件讨论\");\n addNamespaceAlias(8, \"MediaWiki\");\n addNamespaceAlias(9, \"MediaWiki讨论\");\n addNamespaceAlias(10, \"模板\", \"模板\");\n addNamespaceAlias(11, \"模板讨论\", \"模板对话\", \"模板讨论\");\n addNamespaceAlias(12, \"帮助\", \"帮助\");\n addNamespaceAlias(13, \"帮助讨论\", \"帮助对话\", \"帮助讨论\");\n addNamespaceAlias(14, \"分类\", \"分类\");\n addNamespaceAlias(15, \"分类讨论\", \"分类对话\", \"分类讨论\");\n addI18nCIAlias(\"redirect\", \"#重定向\", \"#REDIRECT\");\n addI18nCIAlias(\"notoc\", \"__无目录__\", \"__NOTOC__\");\n addI18nCIAlias(\"nogallery\", \"__无图库__\", \"__NOGALLERY__\");\n addI18nCIAlias(\"forcetoc\", \"__强显目录__\", \"__FORCETOC__\");\n addI18nCIAlias(\"toc\", \"__目录__\", \"__TOC__\");\n addI18nCIAlias(\"noeditsection\", \"__无编辑段落__\", \"__无段落编辑__\", \"__NOEDITSECTION__\");\n addI18nAlias(\"currentmonth\", \"本月\", \"本月2\", \"CURRENTMONTH\", \"CURRENTMONTH2\");\n addI18nAlias(\"currentmonth1\", \"本月1\", \"CURRENTMONTH1\");\n addI18nAlias(\"currentmonthname\", \"本月名\", \"本月名称\", \"CURRENTMONTHNAME\");\n addI18nAlias(\"currentmonthnamegen\", \"本月名属格\", \"本月名称属格\", \"CURRENTMONTHNAMEGEN\");\n addI18nAlias(\"currentmonthabbrev\", \"本月简称\", \"CURRENTMONTHABBREV\");\n addI18nAlias(\"currentday\", \"今天\", \"CURRENTDAY\");\n addI18nAlias(\"currentday2\", \"今天2\", \"CURRENTDAY2\");\n addI18nAlias(\"currentdayname\", \"星期\", \"今天名\", \"今天名称\", \"CURRENTDAYNAME\");\n addI18nAlias(\"currentyear\", \"今年\", \"CURRENTYEAR\");\n addI18nAlias(\"currenttime\", \"当前时间\", \"此时\", \"CURRENTTIME\");\n addI18nAlias(\"currenthour\", \"当前小时\", \"CURRENTHOUR\");\n addI18nAlias(\"localmonth\", \"本地月\", \"LOCALMONTH\", \"LOCALMONTH2\");\n addI18nAlias(\"localmonthname\", \"本地月份名\", \"LOCALMONTHNAME\");\n addI18nAlias(\"localmonthnamegen\", \"本地月历\", \"LOCALMONTHNAMEGEN\");\n addI18nAlias(\"localday\", \"本地日\", \"LOCALDAY\");\n addI18nAlias(\"localdayname\", \"本地日名\", \"LOCALDAYNAME\");\n addI18nAlias(\"localyear\", \"本地年\", \"LOCALYEAR\");\n addI18nAlias(\"localtime\", \"本地时间\", \"LOCALTIME\");\n addI18nAlias(\"localhour\", \"本地小时\", \"LOCALHOUR\");\n addI18nAlias(\"numberofpages\", \"页面数\", \"NUMBEROFPAGES\");\n addI18nAlias(\"numberofarticles\", \"条目数\", \"NUMBEROFARTICLES\");\n addI18nAlias(\"numberoffiles\", \"文件数\", \"NUMBEROFFILES\");\n addI18nAlias(\"numberofusers\", \"用户数\", \"NUMBEROFUSERS\");\n addI18nAlias(\"numberofactiveusers\", \"活跃用户数\", \"NUMBEROFACTIVEUSERS\");\n addI18nAlias(\"numberofedits\", \"编辑数\", \"NUMBEROFEDITS\");\n addI18nAlias(\"numberofviews\", \"访问数\", \"NUMBEROFVIEWS\");\n addI18nAlias(\"pagename\", \"页名\", \"页面名\", \"页面名称\", \"PAGENAME\");\n addI18nAlias(\"pagenamee\", \"页名等同\", \"页面名等同\", \"页面名E\", \"PAGENAMEE\");\n addI18nAlias(\"namespace\", \"名字空间\", \"NAMESPACE\");\n addI18nAlias(\"namespacee\", \"名字空间等同\", \"名字空间E\", \"NAMESPACEE\");\n addI18nAlias(\"namespacenumber\", \"名字空间编号\", \"NAMESPACENUMBER\");\n addI18nAlias(\"talkspace\", \"讨论空间\", \"讨论名字空间\", \"TALKSPACE\");\n addI18nAlias(\"talkspacee\", \"讨论空间等同\", \"讨论名字空间E\", \"TALKSPACEE\");\n addI18nAlias(\"fullpagename\", \"页面全名\", \"完整页面名\", \"FULLPAGENAME\");\n addI18nAlias(\"fullpagenamee\", \"完整页面名E\", \"FULLPAGENAMEE\");\n addI18nAlias(\"subpagename\", \"子页面名\", \"SUBPAGENAME\");\n addI18nAlias(\"subpagenamee\", \"子页面名等同\", \"子页面名E\", \"SUBPAGENAMEE\");\n addI18nAlias(\"talkpagename\", \"讨论页面名\", \"TALKPAGENAME\");\n addI18nAlias(\"talkpagenamee\", \"讨论页面名等同\", \"讨论页面名E\", \"TALKPAGENAMEE\");\n addI18nCIAlias(\"subst\", \"替代:\", \"SUBST:\");\n addI18nCIAlias(\"safesubst\", \"安全替代:\", \"SAFESUBST:\");\n addI18nAlias(\"img_thumbnail\", \"缩略图\", \"thumbnail\", \"thumb\");\n addI18nAlias(\"img_manualthumb\", \"缩略图=$1\", \"thumbnail=$1\", \"thumb=$1\");\n addI18nAlias(\"img_right\", \"右\", \"right\");\n addI18nAlias(\"img_left\", \"左\", \"left\");\n addI18nAlias(\"img_none\", \"无\", \"none\");\n addI18nAlias(\"img_width\", \"$1像素\", \"$1px\");\n addI18nAlias(\"img_center\", \"居中\", \"center\", \"centre\");\n addI18nAlias(\"img_framed\", \"有框\", \"framed\", \"enframed\", \"frame\");\n addI18nAlias(\"img_frameless\", \"无框\", \"frameless\");\n addI18nAlias(\"img_page\", \"页数=$1\", \"$1页\", \"page=$1\", \"page $1\");\n addI18nAlias(\"img_border\", \"边框\", \"border\");\n addI18nAlias(\"img_link\", \"链接=$1\", \"link=$1\");\n addI18nAlias(\"img_alt\", \"替代=$1\", \"替代文本=$1\", \"alt=$1\");\n addI18nAlias(\"img_class\", \"类=$1\", \"class=$1\");\n addI18nCIAlias(\"int\", \"界面:\", \"INT:\");\n addI18nAlias(\"sitename\", \"站点名称\", \"SITENAME\");\n addI18nCIAlias(\"ns\", \"名字空间:\", \"NS:\");\n addI18nCIAlias(\"nse\", \"名字空间E:\", \"NSE:\");\n addI18nCIAlias(\"localurl\", \"本地URL:\", \"LOCALURL:\");\n addI18nCIAlias(\"localurle\", \"本地URLE:\", \"LOCALURLE:\");\n addI18nCIAlias(\"articlepath\", \"条目路径\", \"ARTICLEPATH\");\n addI18nCIAlias(\"pageid\", \"页面ID\", \"PAGEID\");\n addI18nCIAlias(\"server\", \"服务器\", \"SERVER\");\n addI18nCIAlias(\"servername\", \"服务器名\", \"SERVERNAME\");\n addI18nCIAlias(\"scriptpath\", \"脚本路径\", \"SCRIPTPATH\");\n addI18nCIAlias(\"stylepath\", \"样式路径\", \"STYLEPATH\");\n addI18nCIAlias(\"grammar\", \"语法:\", \"GRAMMAR:\");\n addI18nCIAlias(\"gender\", \"性:\", \"性别:\", \"GENDER:\");\n addI18nCIAlias(\"notitleconvert\", \"__不转换标题__\", \"__NOTITLECONVERT__\", \"__NOTC__\");\n addI18nCIAlias(\"nocontentconvert\", \"__不转换内容__\", \"__NOCONTENTCONVERT__\", \"__NOCC__\");\n addI18nAlias(\"currentweek\", \"本周\", \"CURRENTWEEK\");\n addI18nCIAlias(\"plural\", \"复数:\", \"PLURAL:\");\n addI18nCIAlias(\"fullurl\", \"完整URL:\", \"FULLURL:\");\n addI18nCIAlias(\"fullurle\", \"完整URL等同:\", \"完整URLE:\", \"FULLURLE:\");\n addI18nCIAlias(\"lcfirst\", \"小写首字:\", \"LCFIRST:\");\n addI18nCIAlias(\"ucfirst\", \"大写首字:\", \"UCFIRST:\");\n addI18nCIAlias(\"lc\", \"小写:\", \"LC:\");\n addI18nCIAlias(\"uc\", \"大写:\", \"UC:\");\n addI18nAlias(\"displaytitle\", \"显示标题\", \"DISPLAYTITLE\");\n addI18nAlias(\"newsectionlink\", \"__新段落链接__\", \"__NEWSECTIONLINK__\");\n addI18nAlias(\"nonewsectionlink\", \"__无新段落链接__\", \"__NONEWSECTIONLINK__\");\n addI18nAlias(\"currentversion\", \"当前版本\", \"CURRENTVERSION\");\n addI18nCIAlias(\"urlencode\", \"URL编码:\", \"URLENCODE:\");\n addI18nCIAlias(\"anchorencode\", \"锚编码\", \"ANCHORENCODE\");\n addI18nAlias(\"currenttimestamp\", \"当前时间戳\", \"CURRENTTIMESTAMP\");\n addI18nAlias(\"localtimestamp\", \"本地时间戳\", \"LOCALTIMESTAMP\");\n addI18nAlias(\"directionmark\", \"方向标记\", \"DIRECTIONMARK\", \"DIRMARK\");\n addI18nCIAlias(\"language\", \"#语言:\", \"#LANGUAGE:\");\n addI18nAlias(\"contentlanguage\", \"内容语言\", \"CONTENTLANGUAGE\", \"CONTENTLANG\");\n addI18nAlias(\"pagesinnamespace\", \"名字空间中页面数:\", \"PAGESINNAMESPACE:\", \"PAGESINNS:\");\n addI18nAlias(\"numberofadmins\", \"管理员数\", \"NUMBEROFADMINS\");\n addI18nCIAlias(\"formatnum\", \"格式化数字\", \"FORMATNUM\");\n addI18nCIAlias(\"padleft\", \"左填充\", \"PADLEFT\");\n addI18nCIAlias(\"padright\", \"右填充\", \"PADRIGHT\");\n addI18nCIAlias(\"special\", \"特殊\", \"special\");\n addI18nCIAlias(\"speciale\", \"特殊等同\", \"特殊e\", \"speciale\");\n addI18nAlias(\"defaultsort\", \"默认排序:\", \"默认排序关键字:\", \"默认分类排序:\", \"DEFAULTSORT:\", \"DEFAULTSORTKEY:\", \"DEFAULTCATEGORYSORT:\");\n addI18nCIAlias(\"filepath\", \"文件路径:\", \"FILEPATH:\");\n addI18nCIAlias(\"tag\", \"标记\", \"tag\");\n addI18nAlias(\"hiddencat\", \"__隐藏分类__\", \"__HIDDENCAT__\");\n addI18nAlias(\"pagesincategory\", \"分类中页数\", \"分类中页面数\", \"PAGESINCATEGORY\", \"PAGESINCAT\");\n addI18nAlias(\"pagesize\", \"页面大小\", \"PAGESIZE\");\n addI18nAlias(\"index\", \"__索引__\", \"__INDEX__\");\n addI18nAlias(\"noindex\", \"__不索引__\", \"__NOINDEX__\");\n addI18nAlias(\"numberingroup\", \"组中用户数\", \"NUMBERINGROUP\", \"NUMINGROUP\");\n addI18nAlias(\"staticredirect\", \"__静态重定向__\", \"__STATICREDIRECT__\");\n addI18nAlias(\"protectionlevel\", \"保护级别\", \"PROTECTIONLEVEL\");\n addI18nCIAlias(\"formatdate\", \"格式化日期\", \"日期格式化\", \"formatdate\", \"dateformat\");\n addI18nCIAlias(\"defaultsort_noerror\", \"不报错\", \"noerror\");\n addI18nCIAlias(\"defaultsort_noreplace\", \"不替换\", \"noreplace\");\n }\n\n @Override\n protected String getSiteName() {\n return \"Wikipedia\";\n }\n\n @Override\n protected String getWikiUrl() {\n return \"http://example.com\";\n }\n\n @Override\n public String getIso639() {\n return", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2074", "language": "Java", "task_type": "method_signature", "source_file": "java/github/whyalwaysmea/BigBoom/app/src/main/java/com/whyalwaysmea/bigboom/view/cast/ui/CastDetailActivity.java", "mask_start_position": 8955, "mask_end_position": 8995, "canonical_solution": "@Override\n public void showLoading() ", "pre_mask_code": "package com.whyalwaysmea.bigboom.view.cast.ui;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v4.widget.SwipeRefreshLayout;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.support.v7.widget.Toolbar;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.jakewharton.rxbinding.support.v7.widget.RxToolbar;\nimport com.whyalwasymea.bigboom.dao.DBCastDao;\nimport com.whyalwasymea.bigboom.dao.DaoSession;\nimport com.whyalwaysmea.bigboom.Constants;\nimport com.whyalwaysmea.bigboom.R;\nimport com.whyalwaysmea.bigboom.base.BaseView;\nimport com.whyalwaysmea.bigboom.base.MvpActivity;\nimport com.whyalwaysmea.bigboom.bean.CastDetail;\nimport com.whyalwaysmea.bigboom.bean.CastWork;\nimport com.whyalwaysmea.bigboom.bean.db.DBCast;\nimport com.whyalwaysmea.bigboom.db.DBManager;\nimport com.whyalwaysmea.bigboom.di.component.DaggerCastComponent;\nimport com.whyalwaysmea.bigboom.di.module.CastModule;\nimport com.whyalwaysmea.bigboom.view.cast.presenter.CastPresenterImp;\nimport com.whyalwaysmea.bigboom.view.cast.ui.adapter.CastAdapter;\nimport com.whyalwaysmea.bigboom.view.cast.ui.adapter.CastWorksAdapter;\nimport com.whyalwaysmea.bigboom.view.cast.view.ICastDetailView;\nimport com.whyalwaysmea.bigboom.utils.DensityUtils;\nimport com.whyalwaysmea.bigboom.widget.FlexibleScrollView;\nimport com.whyalwaysmea.bigboom.widget.GridMarginDecoration;\nimport java.util.List;\nimport javax.inject.Inject;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\nimport butterknife.OnClick;\nimport static com.whyalwaysmea.bigboom.R.id.profile_layout;\n\npublic class CastDetailActivity extends MvpActivity implements ICastDetailView {\n\n @BindView(R.id.toolbar)\n Toolbar mToolbar;\n\n @BindView(R.id.photos_recyclerview)\n RecyclerView mPhotosRecyclerview;\n\n @BindView(R.id.name)\n TextView mName;\n\n @BindView(R.id.name_en)\n TextView mNameEn;\n\n @BindView(R.id.profile_content)\n TextView mProfileContent;\n\n @BindView(profile_layout)\n FrameLayout mProfileLayout;\n\n @BindView(R.id.works_recyclerview)\n RecyclerView mWorksRecyclerview;\n\n @BindView(R.id.all_works)\n TextView mAllWorks;\n\n @BindView(R.id.year)\n TextView mYear;\n\n @BindView(R.id.collect_cast)\n ImageView mCollectCast;\n\n @BindView(R.id.swiperefreshlayout)\n SwipeRefreshLayout mSwiperefreshlayout;\n\n @BindView(R.id.content_view)\n FlexibleScrollView mContentView;\n\n private String mCastId;\n\n private CastDetail mCastDetail;\n\n private GridLayoutManager mGridLayoutManager;\n\n private LinearLayoutManager mLinearLayoutManager;\n\n private CastAdapter mCastAdapter;\n\n private CastWorksAdapter mCastWorksAdapter;\n\n @Inject\n CastPresenterImp mPresenter;\n\n @Override\n protected CastPresenterImp createPresenter(BaseView view) {\n return null;\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_cast_detail);\n ButterKnife.bind(this);\n DaggerCastComponent.builder().castModule(new CastModule(this)).build().inject(this);\n init();\n }\n\n @Override\n protected void initData() {\n mCastId = getIntent().getStringExtra(Constants.KEY.CASTID);\n if (!TextUtils.isEmpty(mCastId)) {\n mPresenter.getCastDetail(mCastId);\n mPresenter.getCastWorks(mCastId, 0);\n }\n }\n\n @Override\n protected void initView() {\n mToolbar.setNavigationIcon(R.drawable.icon_back);\n setSupportActionBar(mToolbar);\n RxToolbar.navigationClicks(mToolbar).subscribe(aVoid -> finish());\n mGridLayoutManager = new GridLayoutManager(this, 2);\n mGridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);\n mGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {\n\n @Override\n public int getSpanSize(int position) {\n if (position == 0) {\n return 2;\n } else {\n return 1;\n }\n }\n });\n mPhotosRecyclerview.setLayoutManager(mGridLayoutManager);\n mPhotosRecyclerview.addItemDecoration(new GridMarginDecoration(mContext.getResources().getDimensionPixelSize(R.dimen.gridlayout_margin_decoration2)));\n mCastAdapter = new CastAdapter(this);\n mPhotosRecyclerview.setAdapter(mCastAdapter);\n mLinearLayoutManager = new LinearLayoutManager(this);\n mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);\n mCastWorksAdapter = new CastWorksAdapter(this);\n mWorksRecyclerview.setLayoutManager(mLinearLayoutManager);\n mWorksRecyclerview.setAdapter(mCastWorksAdapter);\n mWorksRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {\n\n @Override\n public void onScrolled(RecyclerView recyclerView, int dx, int dy) {\n super.onScrolled(recyclerView, dx, dy);\n // 获取到固定的view\n View stickyInfoView = recyclerView.findChildViewUnder(10, DensityUtils.dp2px(mContext, 80));\n if (stickyInfoView != null && stickyInfoView.getContentDescription() != null) {\n mYear.setText(String.valueOf(stickyInfoView.getContentDescription()));\n }\n // Get the sticky view's translationY by the first view below the sticky's height.\n View transInfoView = recyclerView.findChildViewUnder(DensityUtils.dp2px(mContext, 165), DensityUtils.dp2px(mContext, 80));\n if (transInfoView != null && transInfoView.getTag() != null) {\n int transViewStatus = (int) transInfoView.getTag();\n int dealtX = transInfoView.getLeft() - mYear.getMeasuredWidth();\n if (transViewStatus == CastWorksAdapter.HAS_STICKY_VIEW) {\n // If the first view below the sticky's height scroll off the screen,\n // then recovery the sticky view's translationY.\n if (transInfoView.getLeft() > 0 && transInfoView.getLeft() < mYear.getMeasuredWidth() + 10) {\n mYear.setTranslationX(dealtX);\n } else {\n mYear.setTranslationX(0);\n }\n } else if (transViewStatus == CastWorksAdapter.NONE_STICKY_VIEW) {\n mYear.setTranslationX(0);\n }\n }\n }\n });\n mProfileLayout.setOnClickListener(v -> {\n if (mCastDetail != null) {\n Intent intent = new Intent(mContext, CastInfoActivity.class);\n intent.putExtra(Constants.KEY.CAST, mCastDetail);\n startActivity(intent);\n }\n });\n mAllWorks.setOnClickListener(v -> {\n if (mCastId != null) {\n Intent intent = new Intent(mContext, AllWorksActivity.class);\n intent.putExtra(Constants.KEY.CASTID, mCastId);\n startActivity(intent);\n }\n });\n }\n\n @OnClick(R.id.collect_cast)\n public void collectCast() {\n DaoSession daoSession = DBManager.getInstance().getDaoSession();\n DBCastDao dbCastDao = daoSession.getDBCastDao();\n List list = dbCastDao.queryBuilder().where(DBCastDao.Properties.CastId.eq(mCastDetail.getId())).build().list();\n if (list.isEmpty()) {\n DBCast dbCast = new DBCast();\n dbCast.setCastId(mCastDetail.getId());\n dbCast.setImgUrl(mCastDetail.getPhotos().get(0).getImage());\n dbCastDao.insert(dbCast);\n }\n }\n\n @Override\n public void showToast(String msg) {\n super.showToast(msg);\n showSnackbar(mToolbar, msg);\n }\n\n @Override\n public void showDetail(Object o) {\n if (o instanceof CastDetail) {\n CastDetail castDetail = (CastDetail) o;\n mCastDetail = castDetail;\n mToolbar.setTitle(castDetail.getName());\n mName.setText(castDetail.getName());\n mNameEn.setText(castDetail.getName_en());\n mProfileContent.setText(castDetail.getSummary());\n mCastAdapter.addData(castDetail.getPhotos());\n mCastAdapter.setCastId(mCastId);\n mCastAdapter.setCastName(castDetail.getName());\n collectCast();\n } else if (o instanceof CastWork) {\n CastWork castWork = (CastWork) o;\n mCastWorksAdapter.addData(castWork.getWorks());\n mAllWorks.setText(mContext.getResources().getString(R.string.all_works, castWork.getTotal() + \"\"));\n }\n }\n\n ", "post_mask_code": "{\n super.showLoading();\n mSwiperefreshlayout.post(() -> mSwiperefreshlayout.setRefreshing(true));\n }\n\n @Override\n public void hideLoading() {\n super.hideLoading();\n mSwiperefreshlayout.post(() -> mSwiperefreshlayout.setRefreshing(false));\n mSwiperefreshlayout.setEnabled(true);\n mContentView.setVisibility(View.VISIBLE);\n }\n}\n"} {"task_id": "Java_2075", "language": "Java", "task_type": "method_body", "source_file": "java/github/whyalwaysmea/BigBoom/app/src/main/java/com/whyalwaysmea/bigboom/view/cast/ui/CastDetailActivity.java", "mask_start_position": 9158, "mask_end_position": 9372, "canonical_solution": "{\n super.hideLoading();\n mSwiperefreshlayout.post(() -> mSwiperefreshlayout.setRefreshing(false));\n mSwiperefreshlayout.setEnabled(true);\n mContentView.setVisibility(View.VISIBLE);\n }", "pre_mask_code": "package com.whyalwaysmea.bigboom.view.cast.ui;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v4.widget.SwipeRefreshLayout;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.support.v7.widget.Toolbar;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.jakewharton.rxbinding.support.v7.widget.RxToolbar;\nimport com.whyalwasymea.bigboom.dao.DBCastDao;\nimport com.whyalwasymea.bigboom.dao.DaoSession;\nimport com.whyalwaysmea.bigboom.Constants;\nimport com.whyalwaysmea.bigboom.R;\nimport com.whyalwaysmea.bigboom.base.BaseView;\nimport com.whyalwaysmea.bigboom.base.MvpActivity;\nimport com.whyalwaysmea.bigboom.bean.CastDetail;\nimport com.whyalwaysmea.bigboom.bean.CastWork;\nimport com.whyalwaysmea.bigboom.bean.db.DBCast;\nimport com.whyalwaysmea.bigboom.db.DBManager;\nimport com.whyalwaysmea.bigboom.di.component.DaggerCastComponent;\nimport com.whyalwaysmea.bigboom.di.module.CastModule;\nimport com.whyalwaysmea.bigboom.view.cast.presenter.CastPresenterImp;\nimport com.whyalwaysmea.bigboom.view.cast.ui.adapter.CastAdapter;\nimport com.whyalwaysmea.bigboom.view.cast.ui.adapter.CastWorksAdapter;\nimport com.whyalwaysmea.bigboom.view.cast.view.ICastDetailView;\nimport com.whyalwaysmea.bigboom.utils.DensityUtils;\nimport com.whyalwaysmea.bigboom.widget.FlexibleScrollView;\nimport com.whyalwaysmea.bigboom.widget.GridMarginDecoration;\nimport java.util.List;\nimport javax.inject.Inject;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\nimport butterknife.OnClick;\nimport static com.whyalwaysmea.bigboom.R.id.profile_layout;\n\npublic class CastDetailActivity extends MvpActivity implements ICastDetailView {\n\n @BindView(R.id.toolbar)\n Toolbar mToolbar;\n\n @BindView(R.id.photos_recyclerview)\n RecyclerView mPhotosRecyclerview;\n\n @BindView(R.id.name)\n TextView mName;\n\n @BindView(R.id.name_en)\n TextView mNameEn;\n\n @BindView(R.id.profile_content)\n TextView mProfileContent;\n\n @BindView(profile_layout)\n FrameLayout mProfileLayout;\n\n @BindView(R.id.works_recyclerview)\n RecyclerView mWorksRecyclerview;\n\n @BindView(R.id.all_works)\n TextView mAllWorks;\n\n @BindView(R.id.year)\n TextView mYear;\n\n @BindView(R.id.collect_cast)\n ImageView mCollectCast;\n\n @BindView(R.id.swiperefreshlayout)\n SwipeRefreshLayout mSwiperefreshlayout;\n\n @BindView(R.id.content_view)\n FlexibleScrollView mContentView;\n\n private String mCastId;\n\n private CastDetail mCastDetail;\n\n private GridLayoutManager mGridLayoutManager;\n\n private LinearLayoutManager mLinearLayoutManager;\n\n private CastAdapter mCastAdapter;\n\n private CastWorksAdapter mCastWorksAdapter;\n\n @Inject\n CastPresenterImp mPresenter;\n\n @Override\n protected CastPresenterImp createPresenter(BaseView view) {\n return null;\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_cast_detail);\n ButterKnife.bind(this);\n DaggerCastComponent.builder().castModule(new CastModule(this)).build().inject(this);\n init();\n }\n\n @Override\n protected void initData() {\n mCastId = getIntent().getStringExtra(Constants.KEY.CASTID);\n if (!TextUtils.isEmpty(mCastId)) {\n mPresenter.getCastDetail(mCastId);\n mPresenter.getCastWorks(mCastId, 0);\n }\n }\n\n @Override\n protected void initView() {\n mToolbar.setNavigationIcon(R.drawable.icon_back);\n setSupportActionBar(mToolbar);\n RxToolbar.navigationClicks(mToolbar).subscribe(aVoid -> finish());\n mGridLayoutManager = new GridLayoutManager(this, 2);\n mGridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);\n mGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {\n\n @Override\n public int getSpanSize(int position) {\n if (position == 0) {\n return 2;\n } else {\n return 1;\n }\n }\n });\n mPhotosRecyclerview.setLayoutManager(mGridLayoutManager);\n mPhotosRecyclerview.addItemDecoration(new GridMarginDecoration(mContext.getResources().getDimensionPixelSize(R.dimen.gridlayout_margin_decoration2)));\n mCastAdapter = new CastAdapter(this);\n mPhotosRecyclerview.setAdapter(mCastAdapter);\n mLinearLayoutManager = new LinearLayoutManager(this);\n mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);\n mCastWorksAdapter = new CastWorksAdapter(this);\n mWorksRecyclerview.setLayoutManager(mLinearLayoutManager);\n mWorksRecyclerview.setAdapter(mCastWorksAdapter);\n mWorksRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {\n\n @Override\n public void onScrolled(RecyclerView recyclerView, int dx, int dy) {\n super.onScrolled(recyclerView, dx, dy);\n // 获取到固定的view\n View stickyInfoView = recyclerView.findChildViewUnder(10, DensityUtils.dp2px(mContext, 80));\n if (stickyInfoView != null && stickyInfoView.getContentDescription() != null) {\n mYear.setText(String.valueOf(stickyInfoView.getContentDescription()));\n }\n // Get the sticky view's translationY by the first view below the sticky's height.\n View transInfoView = recyclerView.findChildViewUnder(DensityUtils.dp2px(mContext, 165), DensityUtils.dp2px(mContext, 80));\n if (transInfoView != null && transInfoView.getTag() != null) {\n int transViewStatus = (int) transInfoView.getTag();\n int dealtX = transInfoView.getLeft() - mYear.getMeasuredWidth();\n if (transViewStatus == CastWorksAdapter.HAS_STICKY_VIEW) {\n // If the first view below the sticky's height scroll off the screen,\n // then recovery the sticky view's translationY.\n if (transInfoView.getLeft() > 0 && transInfoView.getLeft() < mYear.getMeasuredWidth() + 10) {\n mYear.setTranslationX(dealtX);\n } else {\n mYear.setTranslationX(0);\n }\n } else if (transViewStatus == CastWorksAdapter.NONE_STICKY_VIEW) {\n mYear.setTranslationX(0);\n }\n }\n }\n });\n mProfileLayout.setOnClickListener(v -> {\n if (mCastDetail != null) {\n Intent intent = new Intent(mContext, CastInfoActivity.class);\n intent.putExtra(Constants.KEY.CAST, mCastDetail);\n startActivity(intent);\n }\n });\n mAllWorks.setOnClickListener(v -> {\n if (mCastId != null) {\n Intent intent = new Intent(mContext, AllWorksActivity.class);\n intent.putExtra(Constants.KEY.CASTID, mCastId);\n startActivity(intent);\n }\n });\n }\n\n @OnClick(R.id.collect_cast)\n public void collectCast() {\n DaoSession daoSession = DBManager.getInstance().getDaoSession();\n DBCastDao dbCastDao = daoSession.getDBCastDao();\n List list = dbCastDao.queryBuilder().where(DBCastDao.Properties.CastId.eq(mCastDetail.getId())).build().list();\n if (list.isEmpty()) {\n DBCast dbCast = new DBCast();\n dbCast.setCastId(mCastDetail.getId());\n dbCast.setImgUrl(mCastDetail.getPhotos().get(0).getImage());\n dbCastDao.insert(dbCast);\n }\n }\n\n @Override\n public void showToast(String msg) {\n super.showToast(msg);\n showSnackbar(mToolbar, msg);\n }\n\n @Override\n public void showDetail(Object o) {\n if (o instanceof CastDetail) {\n CastDetail castDetail = (CastDetail) o;\n mCastDetail = castDetail;\n mToolbar.setTitle(castDetail.getName());\n mName.setText(castDetail.getName());\n mNameEn.setText(castDetail.getName_en());\n mProfileContent.setText(castDetail.getSummary());\n mCastAdapter.addData(castDetail.getPhotos());\n mCastAdapter.setCastId(mCastId);\n mCastAdapter.setCastName(castDetail.getName());\n collectCast();\n } else if (o instanceof CastWork) {\n CastWork castWork = (CastWork) o;\n mCastWorksAdapter.addData(castWork.getWorks());\n mAllWorks.setText(mContext.getResources().getString(R.string.all_works, castWork.getTotal() + \"\"));\n }\n }\n\n @Override\n public void showLoading() {\n super.showLoading();\n mSwiperefreshlayout.post(() -> mSwiperefreshlayout.setRefreshing(true));\n }\n\n @Override\n public void hideLoading() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2076", "language": "Java", "task_type": "single_line", "source_file": "java/github/whyalwaysmea/BigBoom/app/src/main/java/com/whyalwaysmea/bigboom/view/cast/ui/CastDetailActivity.java", "mask_start_position": 5812, "mask_end_position": 5815, "canonical_solution": "));", "pre_mask_code": "package com.whyalwaysmea.bigboom.view.cast.ui;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v4.widget.SwipeRefreshLayout;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.support.v7.widget.Toolbar;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.jakewharton.rxbinding.support.v7.widget.RxToolbar;\nimport com.whyalwasymea.bigboom.dao.DBCastDao;\nimport com.whyalwasymea.bigboom.dao.DaoSession;\nimport com.whyalwaysmea.bigboom.Constants;\nimport com.whyalwaysmea.bigboom.R;\nimport com.whyalwaysmea.bigboom.base.BaseView;\nimport com.whyalwaysmea.bigboom.base.MvpActivity;\nimport com.whyalwaysmea.bigboom.bean.CastDetail;\nimport com.whyalwaysmea.bigboom.bean.CastWork;\nimport com.whyalwaysmea.bigboom.bean.db.DBCast;\nimport com.whyalwaysmea.bigboom.db.DBManager;\nimport com.whyalwaysmea.bigboom.di.component.DaggerCastComponent;\nimport com.whyalwaysmea.bigboom.di.module.CastModule;\nimport com.whyalwaysmea.bigboom.view.cast.presenter.CastPresenterImp;\nimport com.whyalwaysmea.bigboom.view.cast.ui.adapter.CastAdapter;\nimport com.whyalwaysmea.bigboom.view.cast.ui.adapter.CastWorksAdapter;\nimport com.whyalwaysmea.bigboom.view.cast.view.ICastDetailView;\nimport com.whyalwaysmea.bigboom.utils.DensityUtils;\nimport com.whyalwaysmea.bigboom.widget.FlexibleScrollView;\nimport com.whyalwaysmea.bigboom.widget.GridMarginDecoration;\nimport java.util.List;\nimport javax.inject.Inject;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\nimport butterknife.OnClick;\nimport static com.whyalwaysmea.bigboom.R.id.profile_layout;\n\npublic class CastDetailActivity extends MvpActivity implements ICastDetailView {\n\n @BindView(R.id.toolbar)\n Toolbar mToolbar;\n\n @BindView(R.id.photos_recyclerview)\n RecyclerView mPhotosRecyclerview;\n\n @BindView(R.id.name)\n TextView mName;\n\n @BindView(R.id.name_en)\n TextView mNameEn;\n\n @BindView(R.id.profile_content)\n TextView mProfileContent;\n\n @BindView(profile_layout)\n FrameLayout mProfileLayout;\n\n @BindView(R.id.works_recyclerview)\n RecyclerView mWorksRecyclerview;\n\n @BindView(R.id.all_works)\n TextView mAllWorks;\n\n @BindView(R.id.year)\n TextView mYear;\n\n @BindView(R.id.collect_cast)\n ImageView mCollectCast;\n\n @BindView(R.id.swiperefreshlayout)\n SwipeRefreshLayout mSwiperefreshlayout;\n\n @BindView(R.id.content_view)\n FlexibleScrollView mContentView;\n\n private String mCastId;\n\n private CastDetail mCastDetail;\n\n private GridLayoutManager mGridLayoutManager;\n\n private LinearLayoutManager mLinearLayoutManager;\n\n private CastAdapter mCastAdapter;\n\n private CastWorksAdapter mCastWorksAdapter;\n\n @Inject\n CastPresenterImp mPresenter;\n\n @Override\n protected CastPresenterImp createPresenter(BaseView view) {\n return null;\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_cast_detail);\n ButterKnife.bind(this);\n DaggerCastComponent.builder().castModule(new CastModule(this)).build().inject(this);\n init();\n }\n\n @Override\n protected void initData() {\n mCastId = getIntent().getStringExtra(Constants.KEY.CASTID);\n if (!TextUtils.isEmpty(mCastId)) {\n mPresenter.getCastDetail(mCastId);\n mPresenter.getCastWorks(mCastId, 0);\n }\n }\n\n @Override\n protected void initView() {\n mToolbar.setNavigationIcon(R.drawable.icon_back);\n setSupportActionBar(mToolbar);\n RxToolbar.navigationClicks(mToolbar).subscribe(aVoid -> finish());\n mGridLayoutManager = new GridLayoutManager(this, 2);\n mGridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);\n mGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {\n\n @Override\n public int getSpanSize(int position) {\n if (position == 0) {\n return 2;\n } else {\n return 1;\n }\n }\n });\n mPhotosRecyclerview.setLayoutManager(mGridLayoutManager);\n mPhotosRecyclerview.addItemDecoration(new GridMarginDecoration(mContext.getResources().getDimensionPixelSize(R.dimen.gridlayout_margin_decoration2)));\n mCastAdapter = new CastAdapter(this);\n mPhotosRecyclerview.setAdapter(mCastAdapter);\n mLinearLayoutManager = new LinearLayoutManager(this);\n mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);\n mCastWorksAdapter = new CastWorksAdapter(this);\n mWorksRecyclerview.setLayoutManager(mLinearLayoutManager);\n mWorksRecyclerview.setAdapter(mCastWorksAdapter);\n mWorksRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {\n\n @Override\n public void onScrolled(RecyclerView recyclerView, int dx, int dy) {\n super.onScrolled(recyclerView, dx, dy);\n // 获取到固定的view\n View stickyInfoView = recyclerView.findChildViewUnder(10, DensityUtils.dp2px(mContext, 80));\n if (stickyInfoView != null && stickyInfoView.getContentDescription() != null) {\n mYear.setText(String.valueOf(stickyInfoView.getContentDescription()));\n }\n // Get the sticky view's translationY by the first view below the sticky's height.\n View transInfoView = recyclerView.findChildViewUnder(DensityUtils.dp2px(mContext, 165), DensityUtils.dp2px(mContext, 80", "post_mask_code": "\n if (transInfoView != null && transInfoView.getTag() != null) {\n int transViewStatus = (int) transInfoView.getTag();\n int dealtX = transInfoView.getLeft() - mYear.getMeasuredWidth();\n if (transViewStatus == CastWorksAdapter.HAS_STICKY_VIEW) {\n // If the first view below the sticky's height scroll off the screen,\n // then recovery the sticky view's translationY.\n if (transInfoView.getLeft() > 0 && transInfoView.getLeft() < mYear.getMeasuredWidth() + 10) {\n mYear.setTranslationX(dealtX);\n } else {\n mYear.setTranslationX(0);\n }\n } else if (transViewStatus == CastWorksAdapter.NONE_STICKY_VIEW) {\n mYear.setTranslationX(0);\n }\n }\n }\n });\n mProfileLayout.setOnClickListener(v -> {\n if (mCastDetail != null) {\n Intent intent = new Intent(mContext, CastInfoActivity.class);\n intent.putExtra(Constants.KEY.CAST, mCastDetail);\n startActivity(intent);\n }\n });\n mAllWorks.setOnClickListener(v -> {\n if (mCastId != null) {\n Intent intent = new Intent(mContext, AllWorksActivity.class);\n intent.putExtra(Constants.KEY.CASTID, mCastId);\n startActivity(intent);\n }\n });\n }\n\n @OnClick(R.id.collect_cast)\n public void collectCast() {\n DaoSession daoSession = DBManager.getInstance().getDaoSession();\n DBCastDao dbCastDao = daoSession.getDBCastDao();\n List list = dbCastDao.queryBuilder().where(DBCastDao.Properties.CastId.eq(mCastDetail.getId())).build().list();\n if (list.isEmpty()) {\n DBCast dbCast = new DBCast();\n dbCast.setCastId(mCastDetail.getId());\n dbCast.setImgUrl(mCastDetail.getPhotos().get(0).getImage());\n dbCastDao.insert(dbCast);\n }\n }\n\n @Override\n public void showToast(String msg) {\n super.showToast(msg);\n showSnackbar(mToolbar, msg);\n }\n\n @Override\n public void showDetail(Object o) {\n if (o instanceof CastDetail) {\n CastDetail castDetail = (CastDetail) o;\n mCastDetail = castDetail;\n mToolbar.setTitle(castDetail.getName());\n mName.setText(castDetail.getName());\n mNameEn.setText(castDetail.getName_en());\n mProfileContent.setText(castDetail.getSummary());\n mCastAdapter.addData(castDetail.getPhotos());\n mCastAdapter.setCastId(mCastId);\n mCastAdapter.setCastName(castDetail.getName());\n collectCast();\n } else if (o instanceof CastWork) {\n CastWork castWork = (CastWork) o;\n mCastWorksAdapter.addData(castWork.getWorks());\n mAllWorks.setText(mContext.getResources().getString(R.string.all_works, castWork.getTotal() + \"\"));\n }\n }\n\n @Override\n public void showLoading() {\n super.showLoading();\n mSwiperefreshlayout.post(() -> mSwiperefreshlayout.setRefreshing(true));\n }\n\n @Override\n public void hideLoading() {\n super.hideLoading();\n mSwiperefreshlayout.post(() -> mSwiperefreshlayout.setRefreshing(false));\n mSwiperefreshlayout.setEnabled(true);\n mContentView.setVisibility(View.VISIBLE);\n }\n}\n"} {"task_id": "Java_2077", "language": "Java", "task_type": "if_statement", "source_file": "java/github/whyalwaysmea/BigBoom/app/src/main/java/com/whyalwaysmea/bigboom/view/cast/ui/CastDetailActivity.java", "mask_start_position": 6322, "mask_end_position": 6587, "canonical_solution": "if (transInfoView.getLeft() > 0 && transInfoView.getLeft() < mYear.getMeasuredWidth() + 10) {\n mYear.setTranslationX(dealtX);\n } else {\n mYear.setTranslationX(0);\n }", "pre_mask_code": "package com.whyalwaysmea.bigboom.view.cast.ui;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v4.widget.SwipeRefreshLayout;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.support.v7.widget.Toolbar;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.jakewharton.rxbinding.support.v7.widget.RxToolbar;\nimport com.whyalwasymea.bigboom.dao.DBCastDao;\nimport com.whyalwasymea.bigboom.dao.DaoSession;\nimport com.whyalwaysmea.bigboom.Constants;\nimport com.whyalwaysmea.bigboom.R;\nimport com.whyalwaysmea.bigboom.base.BaseView;\nimport com.whyalwaysmea.bigboom.base.MvpActivity;\nimport com.whyalwaysmea.bigboom.bean.CastDetail;\nimport com.whyalwaysmea.bigboom.bean.CastWork;\nimport com.whyalwaysmea.bigboom.bean.db.DBCast;\nimport com.whyalwaysmea.bigboom.db.DBManager;\nimport com.whyalwaysmea.bigboom.di.component.DaggerCastComponent;\nimport com.whyalwaysmea.bigboom.di.module.CastModule;\nimport com.whyalwaysmea.bigboom.view.cast.presenter.CastPresenterImp;\nimport com.whyalwaysmea.bigboom.view.cast.ui.adapter.CastAdapter;\nimport com.whyalwaysmea.bigboom.view.cast.ui.adapter.CastWorksAdapter;\nimport com.whyalwaysmea.bigboom.view.cast.view.ICastDetailView;\nimport com.whyalwaysmea.bigboom.utils.DensityUtils;\nimport com.whyalwaysmea.bigboom.widget.FlexibleScrollView;\nimport com.whyalwaysmea.bigboom.widget.GridMarginDecoration;\nimport java.util.List;\nimport javax.inject.Inject;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\nimport butterknife.OnClick;\nimport static com.whyalwaysmea.bigboom.R.id.profile_layout;\n\npublic class CastDetailActivity extends MvpActivity implements ICastDetailView {\n\n @BindView(R.id.toolbar)\n Toolbar mToolbar;\n\n @BindView(R.id.photos_recyclerview)\n RecyclerView mPhotosRecyclerview;\n\n @BindView(R.id.name)\n TextView mName;\n\n @BindView(R.id.name_en)\n TextView mNameEn;\n\n @BindView(R.id.profile_content)\n TextView mProfileContent;\n\n @BindView(profile_layout)\n FrameLayout mProfileLayout;\n\n @BindView(R.id.works_recyclerview)\n RecyclerView mWorksRecyclerview;\n\n @BindView(R.id.all_works)\n TextView mAllWorks;\n\n @BindView(R.id.year)\n TextView mYear;\n\n @BindView(R.id.collect_cast)\n ImageView mCollectCast;\n\n @BindView(R.id.swiperefreshlayout)\n SwipeRefreshLayout mSwiperefreshlayout;\n\n @BindView(R.id.content_view)\n FlexibleScrollView mContentView;\n\n private String mCastId;\n\n private CastDetail mCastDetail;\n\n private GridLayoutManager mGridLayoutManager;\n\n private LinearLayoutManager mLinearLayoutManager;\n\n private CastAdapter mCastAdapter;\n\n private CastWorksAdapter mCastWorksAdapter;\n\n @Inject\n CastPresenterImp mPresenter;\n\n @Override\n protected CastPresenterImp createPresenter(BaseView view) {\n return null;\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_cast_detail);\n ButterKnife.bind(this);\n DaggerCastComponent.builder().castModule(new CastModule(this)).build().inject(this);\n init();\n }\n\n @Override\n protected void initData() {\n mCastId = getIntent().getStringExtra(Constants.KEY.CASTID);\n if (!TextUtils.isEmpty(mCastId)) {\n mPresenter.getCastDetail(mCastId);\n mPresenter.getCastWorks(mCastId, 0);\n }\n }\n\n @Override\n protected void initView() {\n mToolbar.setNavigationIcon(R.drawable.icon_back);\n setSupportActionBar(mToolbar);\n RxToolbar.navigationClicks(mToolbar).subscribe(aVoid -> finish());\n mGridLayoutManager = new GridLayoutManager(this, 2);\n mGridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);\n mGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {\n\n @Override\n public int getSpanSize(int position) {\n if (position == 0) {\n return 2;\n } else {\n return 1;\n }\n }\n });\n mPhotosRecyclerview.setLayoutManager(mGridLayoutManager);\n mPhotosRecyclerview.addItemDecoration(new GridMarginDecoration(mContext.getResources().getDimensionPixelSize(R.dimen.gridlayout_margin_decoration2)));\n mCastAdapter = new CastAdapter(this);\n mPhotosRecyclerview.setAdapter(mCastAdapter);\n mLinearLayoutManager = new LinearLayoutManager(this);\n mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);\n mCastWorksAdapter = new CastWorksAdapter(this);\n mWorksRecyclerview.setLayoutManager(mLinearLayoutManager);\n mWorksRecyclerview.setAdapter(mCastWorksAdapter);\n mWorksRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {\n\n @Override\n public void onScrolled(RecyclerView recyclerView, int dx, int dy) {\n super.onScrolled(recyclerView, dx, dy);\n // 获取到固定的view\n View stickyInfoView = recyclerView.findChildViewUnder(10, DensityUtils.dp2px(mContext, 80));\n if (stickyInfoView != null && stickyInfoView.getContentDescription() != null) {\n mYear.setText(String.valueOf(stickyInfoView.getContentDescription()));\n }\n // Get the sticky view's translationY by the first view below the sticky's height.\n View transInfoView = recyclerView.findChildViewUnder(DensityUtils.dp2px(mContext, 165), DensityUtils.dp2px(mContext, 80));\n if (transInfoView != null && transInfoView.getTag() != null) {\n int transViewStatus = (int) transInfoView.getTag();\n int dealtX = transInfoView.getLeft() - mYear.getMeasuredWidth();\n if (transViewStatus == CastWorksAdapter.HAS_STICKY_VIEW) {\n // If the first view below the sticky's height scroll off the screen,\n // then recovery the sticky view's translationY.\n ", "post_mask_code": "\n } else if (transViewStatus == CastWorksAdapter.NONE_STICKY_VIEW) {\n mYear.setTranslationX(0);\n }\n }\n }\n });\n mProfileLayout.setOnClickListener(v -> {\n if (mCastDetail != null) {\n Intent intent = new Intent(mContext, CastInfoActivity.class);\n intent.putExtra(Constants.KEY.CAST, mCastDetail);\n startActivity(intent);\n }\n });\n mAllWorks.setOnClickListener(v -> {\n if (mCastId != null) {\n Intent intent = new Intent(mContext, AllWorksActivity.class);\n intent.putExtra(Constants.KEY.CASTID, mCastId);\n startActivity(intent);\n }\n });\n }\n\n @OnClick(R.id.collect_cast)\n public void collectCast() {\n DaoSession daoSession = DBManager.getInstance().getDaoSession();\n DBCastDao dbCastDao = daoSession.getDBCastDao();\n List list = dbCastDao.queryBuilder().where(DBCastDao.Properties.CastId.eq(mCastDetail.getId())).build().list();\n if (list.isEmpty()) {\n DBCast dbCast = new DBCast();\n dbCast.setCastId(mCastDetail.getId());\n dbCast.setImgUrl(mCastDetail.getPhotos().get(0).getImage());\n dbCastDao.insert(dbCast);\n }\n }\n\n @Override\n public void showToast(String msg) {\n super.showToast(msg);\n showSnackbar(mToolbar, msg);\n }\n\n @Override\n public void showDetail(Object o) {\n if (o instanceof CastDetail) {\n CastDetail castDetail = (CastDetail) o;\n mCastDetail = castDetail;\n mToolbar.setTitle(castDetail.getName());\n mName.setText(castDetail.getName());\n mNameEn.setText(castDetail.getName_en());\n mProfileContent.setText(castDetail.getSummary());\n mCastAdapter.addData(castDetail.getPhotos());\n mCastAdapter.setCastId(mCastId);\n mCastAdapter.setCastName(castDetail.getName());\n collectCast();\n } else if (o instanceof CastWork) {\n CastWork castWork = (CastWork) o;\n mCastWorksAdapter.addData(castWork.getWorks());\n mAllWorks.setText(mContext.getResources().getString(R.string.all_works, castWork.getTotal() + \"\"));\n }\n }\n\n @Override\n public void showLoading() {\n super.showLoading();\n mSwiperefreshlayout.post(() -> mSwiperefreshlayout.setRefreshing(true));\n }\n\n @Override\n public void hideLoading() {\n super.hideLoading();\n mSwiperefreshlayout.post(() -> mSwiperefreshlayout.setRefreshing(false));\n mSwiperefreshlayout.setEnabled(true);\n mContentView.setVisibility(View.VISIBLE);\n }\n}\n"} {"task_id": "Java_2078", "language": "Java", "task_type": "method_signature", "source_file": "java/github/spotbugs/spotbugs/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/bcp/PatternElement.java", "mask_start_position": 6478, "mask_end_position": 6517, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "/*\n * Bytecode Analysis Framework\n *\n */\npackage edu.umd.cs.findbugs.ba.bcp;\n\nimport javax.annotation.CheckForNull;\nimport org.apache.bcel.generic.ConstantPoolGen;\nimport org.apache.bcel.generic.InstructionHandle;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport edu.umd.cs.findbugs.ba.DataflowAnalysisException;\nimport edu.umd.cs.findbugs.ba.Edge;\nimport edu.umd.cs.findbugs.ba.vna.ValueNumberFrame;\n\n/**\n * A PatternElement is an element of a ByteCodePattern. It potentially matches\n * some number of bytecode instructions.\n */\npublic abstract class PatternElement {\n\n private static final Logger LOG = LoggerFactory.getLogger(PatternElement.class);\n\n private PatternElement next;\n\n private String label;\n\n private String dominatedBy;\n\n private int index;\n\n private boolean allowTrailingEdges = true;\n\n /**\n * Get the next PatternElement.\n */\n public PatternElement getNext() {\n return next;\n }\n\n /**\n * Set the next PatternElement.\n */\n public void setNext(PatternElement patternElement) {\n this.next = patternElement;\n }\n\n /**\n * Set a label for this PatternElement.\n *\n * @param label\n * the label\n * @return this object\n */\n public PatternElement label(String label) {\n this.label = label;\n return this;\n }\n\n /**\n * Get the label of this PatternElement.\n *\n * @return the label, or null if the PatternElement is not labeled\n */\n public String getLabel() {\n return label;\n }\n\n /**\n * Set the label of another pattern element whose first matched instruction\n * must dominate the instruction(s) matched by this element.\n */\n public PatternElement dominatedBy(String dominatedBy) {\n this.dominatedBy = dominatedBy;\n return this;\n }\n\n /**\n * Get the label of the pattern element whose first matched instruction must\n * dominate the instruction(s) matched by this element.\n */\n public String getDominatedBy() {\n return dominatedBy;\n }\n\n /**\n * Set the index. This is just for debugging.\n */\n public void setIndex(int index) {\n this.index = index;\n }\n\n /**\n * Set whether or not this PatternElement allows trailing edges to be\n * matched. By default, trailing edges may be matched. When this value is\n * set to false, it ensures that the successor instruction must be in the\n * same basic block.\n *\n * @param allowTrailingEdges\n * true if trailing edges may be matched, false if trailing edges\n * will never be matched\n */\n public PatternElement setAllowTrailingEdges(boolean allowTrailingEdges) {\n this.allowTrailingEdges = allowTrailingEdges;\n return this;\n }\n\n /**\n * Return whether or not this PatternElement may match trailing edges.\n */\n public boolean allowTrailingEdges() {\n return allowTrailingEdges;\n }\n\n /**\n * Look up a variable definition in given BindingSet.\n *\n * @param varName\n * the name of the variable\n * @param bindingSet\n * the BindingSet to look in\n * @return the Variable, or null if no Variable is bound to the name\n */\n public static Variable lookup(String varName, BindingSet bindingSet) {\n if (bindingSet == null) {\n return null;\n }\n Binding binding = bindingSet.lookup(varName);\n return (binding != null) ? binding.getVariable() : null;\n }\n\n /**\n * Return whether or not this element matches the given instruction with the\n * given Bindings in effect.\n *\n * @param handle\n * the instruction\n * @param cpg\n * the ConstantPoolGen from the method\n * @param before\n * the ValueNumberFrame representing values in the Java stack\n * frame just before the execution of the instruction\n * @param after\n * the ValueNumberFrame representing values in the Java stack\n * frame just after the execution of the instruction\n * @param bindingSet\n * the set of Bindings\n * @return if the match is successful, returns a MatchResult with the\n * PatternElement and BindingSet; if the match is not successful,\n * returns null\n */\n @CheckForNull\n public abstract MatchResult match(InstructionHandle handle, ConstantPoolGen cpg, ValueNumberFrame before, ValueNumberFrame after, BindingSet bindingSet) throws DataflowAnalysisException;\n\n /**\n * Return whether or not it is acceptable to take the given branch.\n *\n * @param edge\n * the Edge representing the branch\n * @param source\n * the source instruction of the branch\n * @return true if the Edge is acceptable, false if not\n */\n public abstract boolean acceptBranch(Edge edge, InstructionHandle source);\n\n /**\n * Return the minimum number of instructions this PatternElement must match\n * in the ByteCodePattern.\n */\n public abstract int minOccur();\n\n /**\n * Return the maximum number of instructions this PatternElement must match\n * in the ByteCodePattern.\n */\n public abstract int maxOccur();\n\n /**\n * Add a variable definition to the given BindingSet, or if there is an\n * existing definition, make sure it is consistent with the new definition.\n *\n * @param varName\n * the name of the variable\n * @param variable\n * the Variable which should be added or checked for consistency\n * @param bindingSet\n * the existing set of bindings\n * @return the updated BindingSet (if the variable is consistent with the\n * previous bindings), or null if the new variable is inconsistent\n * with the previous bindings\n */\n protected static BindingSet addOrCheckDefinition(String varName, Variable variable, BindingSet bindingSet) {\n Variable existingVariable = lookup(varName, bindingSet);\n if (existingVariable == null) {\n bindingSet = new BindingSet(new Binding(varName, variable), bindingSet);\n } else {\n if (!existingVariable.sameAs(variable)) {\n LOG.debug(\"\\tConflicting variable {}: {} != {}\", varName, variable, existingVariable);\n return null;\n }\n }\n return bindingSet;\n }\n\n ", "post_mask_code": "{\n StringBuilder buf = new StringBuilder();\n String className = this.getClass().getName();\n buf.append(className.substring(className.lastIndexOf('.') + 1));\n buf.append('(');\n buf.append(index);\n buf.append(')');\n return buf.toString();\n }\n}\n"} {"task_id": "Java_2079", "language": "Java", "task_type": "method_body", "source_file": "java/github/spotbugs/spotbugs/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/bcp/PatternElement.java", "mask_start_position": 2717, "mask_end_position": 2799, "canonical_solution": "{\n this.allowTrailingEdges = allowTrailingEdges;\n return this;\n }", "pre_mask_code": "/*\n * Bytecode Analysis Framework\n *\n */\npackage edu.umd.cs.findbugs.ba.bcp;\n\nimport javax.annotation.CheckForNull;\nimport org.apache.bcel.generic.ConstantPoolGen;\nimport org.apache.bcel.generic.InstructionHandle;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport edu.umd.cs.findbugs.ba.DataflowAnalysisException;\nimport edu.umd.cs.findbugs.ba.Edge;\nimport edu.umd.cs.findbugs.ba.vna.ValueNumberFrame;\n\n/**\n * A PatternElement is an element of a ByteCodePattern. It potentially matches\n * some number of bytecode instructions.\n */\npublic abstract class PatternElement {\n\n private static final Logger LOG = LoggerFactory.getLogger(PatternElement.class);\n\n private PatternElement next;\n\n private String label;\n\n private String dominatedBy;\n\n private int index;\n\n private boolean allowTrailingEdges = true;\n\n /**\n * Get the next PatternElement.\n */\n public PatternElement getNext() {\n return next;\n }\n\n /**\n * Set the next PatternElement.\n */\n public void setNext(PatternElement patternElement) {\n this.next = patternElement;\n }\n\n /**\n * Set a label for this PatternElement.\n *\n * @param label\n * the label\n * @return this object\n */\n public PatternElement label(String label) {\n this.label = label;\n return this;\n }\n\n /**\n * Get the label of this PatternElement.\n *\n * @return the label, or null if the PatternElement is not labeled\n */\n public String getLabel() {\n return label;\n }\n\n /**\n * Set the label of another pattern element whose first matched instruction\n * must dominate the instruction(s) matched by this element.\n */\n public PatternElement dominatedBy(String dominatedBy) {\n this.dominatedBy = dominatedBy;\n return this;\n }\n\n /**\n * Get the label of the pattern element whose first matched instruction must\n * dominate the instruction(s) matched by this element.\n */\n public String getDominatedBy() {\n return dominatedBy;\n }\n\n /**\n * Set the index. This is just for debugging.\n */\n public void setIndex(int index) {\n this.index = index;\n }\n\n /**\n * Set whether or not this PatternElement allows trailing edges to be\n * matched. By default, trailing edges may be matched. When this value is\n * set to false, it ensures that the successor instruction must be in the\n * same basic block.\n *\n * @param allowTrailingEdges\n * true if trailing edges may be matched, false if trailing edges\n * will never be matched\n */\n public PatternElement setAllowTrailingEdges(boolean allowTrailingEdges) ", "post_mask_code": "\n\n /**\n * Return whether or not this PatternElement may match trailing edges.\n */\n public boolean allowTrailingEdges() {\n return allowTrailingEdges;\n }\n\n /**\n * Look up a variable definition in given BindingSet.\n *\n * @param varName\n * the name of the variable\n * @param bindingSet\n * the BindingSet to look in\n * @return the Variable, or null if no Variable is bound to the name\n */\n public static Variable lookup(String varName, BindingSet bindingSet) {\n if (bindingSet == null) {\n return null;\n }\n Binding binding = bindingSet.lookup(varName);\n return (binding != null) ? binding.getVariable() : null;\n }\n\n /**\n * Return whether or not this element matches the given instruction with the\n * given Bindings in effect.\n *\n * @param handle\n * the instruction\n * @param cpg\n * the ConstantPoolGen from the method\n * @param before\n * the ValueNumberFrame representing values in the Java stack\n * frame just before the execution of the instruction\n * @param after\n * the ValueNumberFrame representing values in the Java stack\n * frame just after the execution of the instruction\n * @param bindingSet\n * the set of Bindings\n * @return if the match is successful, returns a MatchResult with the\n * PatternElement and BindingSet; if the match is not successful,\n * returns null\n */\n @CheckForNull\n public abstract MatchResult match(InstructionHandle handle, ConstantPoolGen cpg, ValueNumberFrame before, ValueNumberFrame after, BindingSet bindingSet) throws DataflowAnalysisException;\n\n /**\n * Return whether or not it is acceptable to take the given branch.\n *\n * @param edge\n * the Edge representing the branch\n * @param source\n * the source instruction of the branch\n * @return true if the Edge is acceptable, false if not\n */\n public abstract boolean acceptBranch(Edge edge, InstructionHandle source);\n\n /**\n * Return the minimum number of instructions this PatternElement must match\n * in the ByteCodePattern.\n */\n public abstract int minOccur();\n\n /**\n * Return the maximum number of instructions this PatternElement must match\n * in the ByteCodePattern.\n */\n public abstract int maxOccur();\n\n /**\n * Add a variable definition to the given BindingSet, or if there is an\n * existing definition, make sure it is consistent with the new definition.\n *\n * @param varName\n * the name of the variable\n * @param variable\n * the Variable which should be added or checked for consistency\n * @param bindingSet\n * the existing set of bindings\n * @return the updated BindingSet (if the variable is consistent with the\n * previous bindings), or null if the new variable is inconsistent\n * with the previous bindings\n */\n protected static BindingSet addOrCheckDefinition(String varName, Variable variable, BindingSet bindingSet) {\n Variable existingVariable = lookup(varName, bindingSet);\n if (existingVariable == null) {\n bindingSet = new BindingSet(new Binding(varName, variable), bindingSet);\n } else {\n if (!existingVariable.sameAs(variable)) {\n LOG.debug(\"\\tConflicting variable {}: {} != {}\", varName, variable, existingVariable);\n return null;\n }\n }\n return bindingSet;\n }\n\n @Override\n public String toString() {\n StringBuilder buf = new StringBuilder();\n String className = this.getClass().getName();\n buf.append(className.substring(className.lastIndexOf('.') + 1));\n buf.append('(');\n buf.append(index);\n buf.append(')');\n return buf.toString();\n }\n}\n"} {"task_id": "Java_2080", "language": "Java", "task_type": "single_line", "source_file": "java/github/spotbugs/spotbugs/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/bcp/PatternElement.java", "mask_start_position": 6635, "mask_end_position": 6694, "canonical_solution": "ppend(className.substring(className.lastIndexOf('.') + 1));", "pre_mask_code": "/*\n * Bytecode Analysis Framework\n *\n */\npackage edu.umd.cs.findbugs.ba.bcp;\n\nimport javax.annotation.CheckForNull;\nimport org.apache.bcel.generic.ConstantPoolGen;\nimport org.apache.bcel.generic.InstructionHandle;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport edu.umd.cs.findbugs.ba.DataflowAnalysisException;\nimport edu.umd.cs.findbugs.ba.Edge;\nimport edu.umd.cs.findbugs.ba.vna.ValueNumberFrame;\n\n/**\n * A PatternElement is an element of a ByteCodePattern. It potentially matches\n * some number of bytecode instructions.\n */\npublic abstract class PatternElement {\n\n private static final Logger LOG = LoggerFactory.getLogger(PatternElement.class);\n\n private PatternElement next;\n\n private String label;\n\n private String dominatedBy;\n\n private int index;\n\n private boolean allowTrailingEdges = true;\n\n /**\n * Get the next PatternElement.\n */\n public PatternElement getNext() {\n return next;\n }\n\n /**\n * Set the next PatternElement.\n */\n public void setNext(PatternElement patternElement) {\n this.next = patternElement;\n }\n\n /**\n * Set a label for this PatternElement.\n *\n * @param label\n * the label\n * @return this object\n */\n public PatternElement label(String label) {\n this.label = label;\n return this;\n }\n\n /**\n * Get the label of this PatternElement.\n *\n * @return the label, or null if the PatternElement is not labeled\n */\n public String getLabel() {\n return label;\n }\n\n /**\n * Set the label of another pattern element whose first matched instruction\n * must dominate the instruction(s) matched by this element.\n */\n public PatternElement dominatedBy(String dominatedBy) {\n this.dominatedBy = dominatedBy;\n return this;\n }\n\n /**\n * Get the label of the pattern element whose first matched instruction must\n * dominate the instruction(s) matched by this element.\n */\n public String getDominatedBy() {\n return dominatedBy;\n }\n\n /**\n * Set the index. This is just for debugging.\n */\n public void setIndex(int index) {\n this.index = index;\n }\n\n /**\n * Set whether or not this PatternElement allows trailing edges to be\n * matched. By default, trailing edges may be matched. When this value is\n * set to false, it ensures that the successor instruction must be in the\n * same basic block.\n *\n * @param allowTrailingEdges\n * true if trailing edges may be matched, false if trailing edges\n * will never be matched\n */\n public PatternElement setAllowTrailingEdges(boolean allowTrailingEdges) {\n this.allowTrailingEdges = allowTrailingEdges;\n return this;\n }\n\n /**\n * Return whether or not this PatternElement may match trailing edges.\n */\n public boolean allowTrailingEdges() {\n return allowTrailingEdges;\n }\n\n /**\n * Look up a variable definition in given BindingSet.\n *\n * @param varName\n * the name of the variable\n * @param bindingSet\n * the BindingSet to look in\n * @return the Variable, or null if no Variable is bound to the name\n */\n public static Variable lookup(String varName, BindingSet bindingSet) {\n if (bindingSet == null) {\n return null;\n }\n Binding binding = bindingSet.lookup(varName);\n return (binding != null) ? binding.getVariable() : null;\n }\n\n /**\n * Return whether or not this element matches the given instruction with the\n * given Bindings in effect.\n *\n * @param handle\n * the instruction\n * @param cpg\n * the ConstantPoolGen from the method\n * @param before\n * the ValueNumberFrame representing values in the Java stack\n * frame just before the execution of the instruction\n * @param after\n * the ValueNumberFrame representing values in the Java stack\n * frame just after the execution of the instruction\n * @param bindingSet\n * the set of Bindings\n * @return if the match is successful, returns a MatchResult with the\n * PatternElement and BindingSet; if the match is not successful,\n * returns null\n */\n @CheckForNull\n public abstract MatchResult match(InstructionHandle handle, ConstantPoolGen cpg, ValueNumberFrame before, ValueNumberFrame after, BindingSet bindingSet) throws DataflowAnalysisException;\n\n /**\n * Return whether or not it is acceptable to take the given branch.\n *\n * @param edge\n * the Edge representing the branch\n * @param source\n * the source instruction of the branch\n * @return true if the Edge is acceptable, false if not\n */\n public abstract boolean acceptBranch(Edge edge, InstructionHandle source);\n\n /**\n * Return the minimum number of instructions this PatternElement must match\n * in the ByteCodePattern.\n */\n public abstract int minOccur();\n\n /**\n * Return the maximum number of instructions this PatternElement must match\n * in the ByteCodePattern.\n */\n public abstract int maxOccur();\n\n /**\n * Add a variable definition to the given BindingSet, or if there is an\n * existing definition, make sure it is consistent with the new definition.\n *\n * @param varName\n * the name of the variable\n * @param variable\n * the Variable which should be added or checked for consistency\n * @param bindingSet\n * the existing set of bindings\n * @return the updated BindingSet (if the variable is consistent with the\n * previous bindings), or null if the new variable is inconsistent\n * with the previous bindings\n */\n protected static BindingSet addOrCheckDefinition(String varName, Variable variable, BindingSet bindingSet) {\n Variable existingVariable = lookup(varName, bindingSet);\n if (existingVariable == null) {\n bindingSet = new BindingSet(new Binding(varName, variable), bindingSet);\n } else {\n if (!existingVariable.sameAs(variable)) {\n LOG.debug(\"\\tConflicting variable {}: {} != {}\", varName, variable, existingVariable);\n return null;\n }\n }\n return bindingSet;\n }\n\n @Override\n public String toString() {\n StringBuilder buf = new StringBuilder();\n String className = this.getClass().getName();\n buf.a", "post_mask_code": "\n buf.append('(');\n buf.append(index);\n buf.append(')');\n return buf.toString();\n }\n}\n"} {"task_id": "Java_2081", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/spotbugs/spotbugs/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/bcp/PatternElement.java", "mask_start_position": 2896, "mask_end_position": 2974, "canonical_solution": "public boolean allowTrailingEdges() {\n return allowTrailingEdges;\n }", "pre_mask_code": "/*\n * Bytecode Analysis Framework\n *\n */\npackage edu.umd.cs.findbugs.ba.bcp;\n\nimport javax.annotation.CheckForNull;\nimport org.apache.bcel.generic.ConstantPoolGen;\nimport org.apache.bcel.generic.InstructionHandle;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport edu.umd.cs.findbugs.ba.DataflowAnalysisException;\nimport edu.umd.cs.findbugs.ba.Edge;\nimport edu.umd.cs.findbugs.ba.vna.ValueNumberFrame;\n\n/**\n * A PatternElement is an element of a ByteCodePattern. It potentially matches\n * some number of bytecode instructions.\n */\npublic abstract class PatternElement {\n\n private static final Logger LOG = LoggerFactory.getLogger(PatternElement.class);\n\n private PatternElement next;\n\n private String label;\n\n private String dominatedBy;\n\n private int index;\n\n private boolean allowTrailingEdges = true;\n\n /**\n * Get the next PatternElement.\n */\n public PatternElement getNext() {\n return next;\n }\n\n /**\n * Set the next PatternElement.\n */\n public void setNext(PatternElement patternElement) {\n this.next = patternElement;\n }\n\n /**\n * Set a label for this PatternElement.\n *\n * @param label\n * the label\n * @return this object\n */\n public PatternElement label(String label) {\n this.label = label;\n return this;\n }\n\n /**\n * Get the label of this PatternElement.\n *\n * @return the label, or null if the PatternElement is not labeled\n */\n public String getLabel() {\n return label;\n }\n\n /**\n * Set the label of another pattern element whose first matched instruction\n * must dominate the instruction(s) matched by this element.\n */\n public PatternElement dominatedBy(String dominatedBy) {\n this.dominatedBy = dominatedBy;\n return this;\n }\n\n /**\n * Get the label of the pattern element whose first matched instruction must\n * dominate the instruction(s) matched by this element.\n */\n public String getDominatedBy() {\n return dominatedBy;\n }\n\n /**\n * Set the index. This is just for debugging.\n */\n public void setIndex(int index) {\n this.index = index;\n }\n\n /**\n * Set whether or not this PatternElement allows trailing edges to be\n * matched. By default, trailing edges may be matched. When this value is\n * set to false, it ensures that the successor instruction must be in the\n * same basic block.\n *\n * @param allowTrailingEdges\n * true if trailing edges may be matched, false if trailing edges\n * will never be matched\n */\n public PatternElement setAllowTrailingEdges(boolean allowTrailingEdges) {\n this.allowTrailingEdges = allowTrailingEdges;\n return this;\n }\n\n /**\n * Return whether or not this PatternElement may match trailing edges.\n */\n ", "post_mask_code": "\n\n /**\n * Look up a variable definition in given BindingSet.\n *\n * @param varName\n * the name of the variable\n * @param bindingSet\n * the BindingSet to look in\n * @return the Variable, or null if no Variable is bound to the name\n */\n public static Variable lookup(String varName, BindingSet bindingSet) {\n if (bindingSet == null) {\n return null;\n }\n Binding binding = bindingSet.lookup(varName);\n return (binding != null) ? binding.getVariable() : null;\n }\n\n /**\n * Return whether or not this element matches the given instruction with the\n * given Bindings in effect.\n *\n * @param handle\n * the instruction\n * @param cpg\n * the ConstantPoolGen from the method\n * @param before\n * the ValueNumberFrame representing values in the Java stack\n * frame just before the execution of the instruction\n * @param after\n * the ValueNumberFrame representing values in the Java stack\n * frame just after the execution of the instruction\n * @param bindingSet\n * the set of Bindings\n * @return if the match is successful, returns a MatchResult with the\n * PatternElement and BindingSet; if the match is not successful,\n * returns null\n */\n @CheckForNull\n public abstract MatchResult match(InstructionHandle handle, ConstantPoolGen cpg, ValueNumberFrame before, ValueNumberFrame after, BindingSet bindingSet) throws DataflowAnalysisException;\n\n /**\n * Return whether or not it is acceptable to take the given branch.\n *\n * @param edge\n * the Edge representing the branch\n * @param source\n * the source instruction of the branch\n * @return true if the Edge is acceptable, false if not\n */\n public abstract boolean acceptBranch(Edge edge, InstructionHandle source);\n\n /**\n * Return the minimum number of instructions this PatternElement must match\n * in the ByteCodePattern.\n */\n public abstract int minOccur();\n\n /**\n * Return the maximum number of instructions this PatternElement must match\n * in the ByteCodePattern.\n */\n public abstract int maxOccur();\n\n /**\n * Add a variable definition to the given BindingSet, or if there is an\n * existing definition, make sure it is consistent with the new definition.\n *\n * @param varName\n * the name of the variable\n * @param variable\n * the Variable which should be added or checked for consistency\n * @param bindingSet\n * the existing set of bindings\n * @return the updated BindingSet (if the variable is consistent with the\n * previous bindings), or null if the new variable is inconsistent\n * with the previous bindings\n */\n protected static BindingSet addOrCheckDefinition(String varName, Variable variable, BindingSet bindingSet) {\n Variable existingVariable = lookup(varName, bindingSet);\n if (existingVariable == null) {\n bindingSet = new BindingSet(new Binding(varName, variable), bindingSet);\n } else {\n if (!existingVariable.sameAs(variable)) {\n LOG.debug(\"\\tConflicting variable {}: {} != {}\", varName, variable, existingVariable);\n return null;\n }\n }\n return bindingSet;\n }\n\n @Override\n public String toString() {\n StringBuilder buf = new StringBuilder();\n String className = this.getClass().getName();\n buf.append(className.substring(className.lastIndexOf('.') + 1));\n buf.append('(');\n buf.append(index);\n buf.append(')');\n return buf.toString();\n }\n}\n"} {"task_id": "Java_2082", "language": "Java", "task_type": "method_signature", "source_file": "java/github/KelpFramework/kelp/core/src/main/java/de/pxav/kelp/core/entity/type/PigEntity.java", "mask_start_position": 1252, "mask_end_position": 1299, "canonical_solution": "static PigEntity create(KelpLocation location) ", "pre_mask_code": "package de.pxav.kelp.core.entity.type;\n\nimport de.pxav.kelp.core.KelpPlugin;\nimport de.pxav.kelp.core.entity.KelpEntity;\nimport de.pxav.kelp.core.entity.KelpEntityType;\nimport de.pxav.kelp.core.entity.type.general.AnimalEntity;\nimport de.pxav.kelp.core.entity.type.general.BreedableAnimalEntity;\nimport de.pxav.kelp.core.entity.type.general.VehicleEntity;\nimport de.pxav.kelp.core.entity.version.EntityTypeVersionTemplate;\nimport de.pxav.kelp.core.world.KelpLocation;\nimport org.bukkit.entity.Entity;\nimport org.bukkit.entity.Pig;\n\npublic interface PigEntity extends AnimalEntity, BreedableAnimalEntity, VehicleEntity {\n\n /**\n * Creates a new entity of this type at the given location.\n *\n * While this creates a new instance, it won't actually spawn the entity.\n * You can first do some modifications on it and then call the\n * {@link KelpEntity#spawn()} method.\n *\n * If you don't want to create a new entity, but just a new kelp\n * entity instance based of an existing bukkit entity, you can use\n * {@link #from(Entity)} instead.\n *\n * @param location The location, where the entity should be spawned later.\n * @return A new instance of a sheep entity.\n */\n ", "post_mask_code": "{\n return (PigEntity) KelpPlugin.getInjector().getInstance(EntityTypeVersionTemplate.class).newKelpEntity(getEntityType(), location.getBukkitLocation());\n }\n\n /**\n * Takes a bukkit entity and converts it to a kelp entity of the same type.\n *\n * This can be used if you are for example handling an event that returns a bukkit entity,\n * but you want to use a kelp entity for your operations. You can also use\n * the more general method provided by {@link de.pxav.kelp.core.entity.KelpEntity the\n * kelp entity base class}: {@link de.pxav.kelp.core.entity.KelpEntity#from(Entity)},\n * but this way you don't have to cast your entity to the specific type\n * manually.\n *\n * @param entity The entity you want to convert.\n * @return The kelp instance of the given bukkit entity.\n */\n static PigEntity from(Entity entity) {\n return (PigEntity) KelpPlugin.getInjector().getInstance(EntityTypeVersionTemplate.class).getKelpEntity(entity);\n }\n\n static KelpEntityType getEntityType() {\n return KelpEntityType.PIG;\n }\n\n @Override\n default KelpEntityType getType() {\n return getEntityType();\n }\n\n boolean hasSaddle();\n\n PigEntity setSaddled(boolean saddled);\n}\n"} {"task_id": "Java_2083", "language": "Java", "task_type": "method_body", "source_file": "java/github/KelpFramework/kelp/core/src/main/java/de/pxav/kelp/core/entity/type/PigEntity.java", "mask_start_position": 2445, "mask_end_position": 2484, "canonical_solution": "{\n return getEntityType();\n }", "pre_mask_code": "package de.pxav.kelp.core.entity.type;\n\nimport de.pxav.kelp.core.KelpPlugin;\nimport de.pxav.kelp.core.entity.KelpEntity;\nimport de.pxav.kelp.core.entity.KelpEntityType;\nimport de.pxav.kelp.core.entity.type.general.AnimalEntity;\nimport de.pxav.kelp.core.entity.type.general.BreedableAnimalEntity;\nimport de.pxav.kelp.core.entity.type.general.VehicleEntity;\nimport de.pxav.kelp.core.entity.version.EntityTypeVersionTemplate;\nimport de.pxav.kelp.core.world.KelpLocation;\nimport org.bukkit.entity.Entity;\nimport org.bukkit.entity.Pig;\n\npublic interface PigEntity extends AnimalEntity, BreedableAnimalEntity, VehicleEntity {\n\n /**\n * Creates a new entity of this type at the given location.\n *\n * While this creates a new instance, it won't actually spawn the entity.\n * You can first do some modifications on it and then call the\n * {@link KelpEntity#spawn()} method.\n *\n * If you don't want to create a new entity, but just a new kelp\n * entity instance based of an existing bukkit entity, you can use\n * {@link #from(Entity)} instead.\n *\n * @param location The location, where the entity should be spawned later.\n * @return A new instance of a sheep entity.\n */\n static PigEntity create(KelpLocation location) {\n return (PigEntity) KelpPlugin.getInjector().getInstance(EntityTypeVersionTemplate.class).newKelpEntity(getEntityType(), location.getBukkitLocation());\n }\n\n /**\n * Takes a bukkit entity and converts it to a kelp entity of the same type.\n *\n * This can be used if you are for example handling an event that returns a bukkit entity,\n * but you want to use a kelp entity for your operations. You can also use\n * the more general method provided by {@link de.pxav.kelp.core.entity.KelpEntity the\n * kelp entity base class}: {@link de.pxav.kelp.core.entity.KelpEntity#from(Entity)},\n * but this way you don't have to cast your entity to the specific type\n * manually.\n *\n * @param entity The entity you want to convert.\n * @return The kelp instance of the given bukkit entity.\n */\n static PigEntity from(Entity entity) {\n return (PigEntity) KelpPlugin.getInjector().getInstance(EntityTypeVersionTemplate.class).getKelpEntity(entity);\n }\n\n static KelpEntityType getEntityType() {\n return KelpEntityType.PIG;\n }\n\n @Override\n default KelpEntityType getType() ", "post_mask_code": "\n\n boolean hasSaddle();\n\n PigEntity setSaddled(boolean saddled);\n}\n"} {"task_id": "Java_2084", "language": "Java", "task_type": "single_line", "source_file": "java/github/KelpFramework/kelp/core/src/main/java/de/pxav/kelp/core/entity/type/PigEntity.java", "mask_start_position": 2360, "mask_end_position": 2386, "canonical_solution": "return KelpEntityType.PIG;", "pre_mask_code": "package de.pxav.kelp.core.entity.type;\n\nimport de.pxav.kelp.core.KelpPlugin;\nimport de.pxav.kelp.core.entity.KelpEntity;\nimport de.pxav.kelp.core.entity.KelpEntityType;\nimport de.pxav.kelp.core.entity.type.general.AnimalEntity;\nimport de.pxav.kelp.core.entity.type.general.BreedableAnimalEntity;\nimport de.pxav.kelp.core.entity.type.general.VehicleEntity;\nimport de.pxav.kelp.core.entity.version.EntityTypeVersionTemplate;\nimport de.pxav.kelp.core.world.KelpLocation;\nimport org.bukkit.entity.Entity;\nimport org.bukkit.entity.Pig;\n\npublic interface PigEntity extends AnimalEntity, BreedableAnimalEntity, VehicleEntity {\n\n /**\n * Creates a new entity of this type at the given location.\n *\n * While this creates a new instance, it won't actually spawn the entity.\n * You can first do some modifications on it and then call the\n * {@link KelpEntity#spawn()} method.\n *\n * If you don't want to create a new entity, but just a new kelp\n * entity instance based of an existing bukkit entity, you can use\n * {@link #from(Entity)} instead.\n *\n * @param location The location, where the entity should be spawned later.\n * @return A new instance of a sheep entity.\n */\n static PigEntity create(KelpLocation location) {\n return (PigEntity) KelpPlugin.getInjector().getInstance(EntityTypeVersionTemplate.class).newKelpEntity(getEntityType(), location.getBukkitLocation());\n }\n\n /**\n * Takes a bukkit entity and converts it to a kelp entity of the same type.\n *\n * This can be used if you are for example handling an event that returns a bukkit entity,\n * but you want to use a kelp entity for your operations. You can also use\n * the more general method provided by {@link de.pxav.kelp.core.entity.KelpEntity the\n * kelp entity base class}: {@link de.pxav.kelp.core.entity.KelpEntity#from(Entity)},\n * but this way you don't have to cast your entity to the specific type\n * manually.\n *\n * @param entity The entity you want to convert.\n * @return The kelp instance of the given bukkit entity.\n */\n static PigEntity from(Entity entity) {\n return (PigEntity) KelpPlugin.getInjector().getInstance(EntityTypeVersionTemplate.class).getKelpEntity(entity);\n }\n\n static KelpEntityType getEntityType() {\n ", "post_mask_code": "\n }\n\n @Override\n default KelpEntityType getType() {\n return getEntityType();\n }\n\n boolean hasSaddle();\n\n PigEntity setSaddled(boolean saddled);\n}\n"} {"task_id": "Java_2085", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/KelpFramework/kelp/core/src/main/java/de/pxav/kelp/core/entity/type/PigEntity.java", "mask_start_position": 2142, "mask_end_position": 2306, "canonical_solution": "static PigEntity from(Entity entity) {\n return (PigEntity) KelpPlugin.getInjector().getInstance(EntityTypeVersionTemplate.class).getKelpEntity(entity);\n }", "pre_mask_code": "package de.pxav.kelp.core.entity.type;\n\nimport de.pxav.kelp.core.KelpPlugin;\nimport de.pxav.kelp.core.entity.KelpEntity;\nimport de.pxav.kelp.core.entity.KelpEntityType;\nimport de.pxav.kelp.core.entity.type.general.AnimalEntity;\nimport de.pxav.kelp.core.entity.type.general.BreedableAnimalEntity;\nimport de.pxav.kelp.core.entity.type.general.VehicleEntity;\nimport de.pxav.kelp.core.entity.version.EntityTypeVersionTemplate;\nimport de.pxav.kelp.core.world.KelpLocation;\nimport org.bukkit.entity.Entity;\nimport org.bukkit.entity.Pig;\n\npublic interface PigEntity extends AnimalEntity, BreedableAnimalEntity, VehicleEntity {\n\n /**\n * Creates a new entity of this type at the given location.\n *\n * While this creates a new instance, it won't actually spawn the entity.\n * You can first do some modifications on it and then call the\n * {@link KelpEntity#spawn()} method.\n *\n * If you don't want to create a new entity, but just a new kelp\n * entity instance based of an existing bukkit entity, you can use\n * {@link #from(Entity)} instead.\n *\n * @param location The location, where the entity should be spawned later.\n * @return A new instance of a sheep entity.\n */\n static PigEntity create(KelpLocation location) {\n return (PigEntity) KelpPlugin.getInjector().getInstance(EntityTypeVersionTemplate.class).newKelpEntity(getEntityType(), location.getBukkitLocation());\n }\n\n /**\n * Takes a bukkit entity and converts it to a kelp entity of the same type.\n *\n * This can be used if you are for example handling an event that returns a bukkit entity,\n * but you want to use a kelp entity for your operations. You can also use\n * the more general method provided by {@link de.pxav.kelp.core.entity.KelpEntity the\n * kelp entity base class}: {@link de.pxav.kelp.core.entity.KelpEntity#from(Entity)},\n * but this way you don't have to cast your entity to the specific type\n * manually.\n *\n * @param entity The entity you want to convert.\n * @return The kelp instance of the given bukkit entity.\n */\n ", "post_mask_code": "\n\n static KelpEntityType getEntityType() {\n return KelpEntityType.PIG;\n }\n\n @Override\n default KelpEntityType getType() {\n return getEntityType();\n }\n\n boolean hasSaddle();\n\n PigEntity setSaddled(boolean saddled);\n}\n"} {"task_id": "Java_2086", "language": "Java", "task_type": "method_signature", "source_file": "java/github/naver/fixture-monkey/fixture-monkey/src/main/java/com/navercorp/fixturemonkey/generator/ByteAnnotatedArbitraryGenerator.java", "mask_start_position": 396, "mask_end_position": 477, "canonical_solution": "@Override\n public Arbitrary generate(AnnotationSource annotationSource) ", "pre_mask_code": "package com.navercorp.fixturemonkey.generator;\n\nimport java.math.BigDecimal;\nimport net.jqwik.api.Arbitraries;\nimport net.jqwik.api.Arbitrary;\nimport net.jqwik.api.arbitraries.ByteArbitrary;\n\npublic class ByteAnnotatedArbitraryGenerator implements AnnotatedArbitraryGenerator {\n\n public static final ByteAnnotatedArbitraryGenerator INSTANCE = new ByteAnnotatedArbitraryGenerator();\n\n ", "post_mask_code": "{\n AnnotatedGeneratorConstraint constraint = AnnotatedGeneratorConstraints.findConstraintByClass(Byte.class, annotationSource);\n return generate(constraint);\n }\n\n private ByteArbitrary generate(AnnotatedGeneratorConstraint constraint) {\n ByteArbitrary arbitrary = Arbitraries.bytes();\n BigDecimal min = constraint.getMin();\n BigDecimal max = constraint.getMax();\n if (min != null && max != null) {\n return arbitrary.between(min.byteValue(), max.byteValue());\n } else if (max != null) {\n return arbitrary.lessOrEqual(max.byteValue());\n } else if (min != null) {\n return arbitrary.greaterOrEqual(min.byteValue());\n } else {\n return arbitrary;\n }\n }\n}\n"} {"task_id": "Java_2087", "language": "Java", "task_type": "method_body", "source_file": "java/github/naver/fixture-monkey/fixture-monkey/src/main/java/com/navercorp/fixturemonkey/generator/ByteAnnotatedArbitraryGenerator.java", "mask_start_position": 477, "mask_end_position": 654, "canonical_solution": "{\n AnnotatedGeneratorConstraint constraint = AnnotatedGeneratorConstraints.findConstraintByClass(Byte.class, annotationSource);\n return generate(constraint);\n }", "pre_mask_code": "package com.navercorp.fixturemonkey.generator;\n\nimport java.math.BigDecimal;\nimport net.jqwik.api.Arbitraries;\nimport net.jqwik.api.Arbitrary;\nimport net.jqwik.api.arbitraries.ByteArbitrary;\n\npublic class ByteAnnotatedArbitraryGenerator implements AnnotatedArbitraryGenerator {\n\n public static final ByteAnnotatedArbitraryGenerator INSTANCE = new ByteAnnotatedArbitraryGenerator();\n\n @Override\n public Arbitrary generate(AnnotationSource annotationSource) ", "post_mask_code": "\n\n private ByteArbitrary generate(AnnotatedGeneratorConstraint constraint) {\n ByteArbitrary arbitrary = Arbitraries.bytes();\n BigDecimal min = constraint.getMin();\n BigDecimal max = constraint.getMax();\n if (min != null && max != null) {\n return arbitrary.between(min.byteValue(), max.byteValue());\n } else if (max != null) {\n return arbitrary.lessOrEqual(max.byteValue());\n } else if (min != null) {\n return arbitrary.greaterOrEqual(min.byteValue());\n } else {\n return arbitrary;\n }\n }\n}\n"} {"task_id": "Java_2088", "language": "Java", "task_type": "single_line", "source_file": "java/github/naver/fixture-monkey/fixture-monkey/src/main/java/com/navercorp/fixturemonkey/generator/ByteAnnotatedArbitraryGenerator.java", "mask_start_position": 555, "mask_end_position": 611, "canonical_solution": "nts.findConstraintByClass(Byte.class, annotationSource);", "pre_mask_code": "package com.navercorp.fixturemonkey.generator;\n\nimport java.math.BigDecimal;\nimport net.jqwik.api.Arbitraries;\nimport net.jqwik.api.Arbitrary;\nimport net.jqwik.api.arbitraries.ByteArbitrary;\n\npublic class ByteAnnotatedArbitraryGenerator implements AnnotatedArbitraryGenerator {\n\n public static final ByteAnnotatedArbitraryGenerator INSTANCE = new ByteAnnotatedArbitraryGenerator();\n\n @Override\n public Arbitrary generate(AnnotationSource annotationSource) {\n AnnotatedGeneratorConstraint constraint = AnnotatedGeneratorConstrai", "post_mask_code": "\n return generate(constraint);\n }\n\n private ByteArbitrary generate(AnnotatedGeneratorConstraint constraint) {\n ByteArbitrary arbitrary = Arbitraries.bytes();\n BigDecimal min = constraint.getMin();\n BigDecimal max = constraint.getMax();\n if (min != null && max != null) {\n return arbitrary.between(min.byteValue(), max.byteValue());\n } else if (max != null) {\n return arbitrary.lessOrEqual(max.byteValue());\n } else if (min != null) {\n return arbitrary.greaterOrEqual(min.byteValue());\n } else {\n return arbitrary;\n }\n }\n}\n"} {"task_id": "Java_2089", "language": "Java", "task_type": "method_signature", "source_file": "java/github/phax/ph-ubl/ph-ubl20/src/main/java/com/helger/ubl20/UBL20WriterBuilder.java", "mask_start_position": 1482, "mask_end_position": 1574, "canonical_solution": "@Nonnull\n public static UBL20WriterBuilder create(@Nonnull final Class aClass) ", "pre_mask_code": "package com.helger.ubl20;\n\nimport javax.annotation.Nonnull;\nimport javax.annotation.concurrent.NotThreadSafe;\nimport com.helger.jaxb.builder.JAXBWriterBuilder;\nimport com.helger.xml.namespace.MapBasedNamespaceContext;\n\n/**\n * A writer builder for UBL 2.0 documents.\n *\n * @author Philip Helger\n * @param \n * The UBL 2.0 implementation class to be read\n */\n@NotThreadSafe\npublic class UBL20WriterBuilder extends JAXBWriterBuilder> {\n\n public UBL20WriterBuilder(@Nonnull final EUBL20DocumentType eDocType) {\n super(eDocType);\n // Create a special namespace context for the passed document type\n final MapBasedNamespaceContext aNSContext = UBL20NamespaceContext.getInstance().getClone();\n // Avoid overwriting an already mapped context\n if (!aNSContext.isNamespaceURIMapped(m_aDocType.getNamespaceURI()))\n aNSContext.addDefaultNamespaceURI(m_aDocType.getNamespaceURI());\n setNamespaceContext(aNSContext);\n }\n\n public UBL20WriterBuilder(@Nonnull final Class aClass) {\n this(UBL20DocumentTypes.getDocumentTypeOfImplementationClass(aClass));\n }\n\n /**\n * Create a new writer builder.\n *\n * @param aClass\n * The UBL class to be written. May not be null.\n * @return The new writer builder. Never null.\n * @param \n * The UBL 2.0 document implementation type\n */\n ", "post_mask_code": "{\n return new UBL20WriterBuilder<>(aClass);\n }\n}\n"} {"task_id": "Java_2090", "language": "Java", "task_type": "method_body", "source_file": "java/github/phax/ph-ubl/ph-ubl20/src/main/java/com/helger/ubl20/UBL20WriterBuilder.java", "mask_start_position": 1574, "mask_end_position": 1630, "canonical_solution": "{\n return new UBL20WriterBuilder<>(aClass);\n }", "pre_mask_code": "package com.helger.ubl20;\n\nimport javax.annotation.Nonnull;\nimport javax.annotation.concurrent.NotThreadSafe;\nimport com.helger.jaxb.builder.JAXBWriterBuilder;\nimport com.helger.xml.namespace.MapBasedNamespaceContext;\n\n/**\n * A writer builder for UBL 2.0 documents.\n *\n * @author Philip Helger\n * @param \n * The UBL 2.0 implementation class to be read\n */\n@NotThreadSafe\npublic class UBL20WriterBuilder extends JAXBWriterBuilder> {\n\n public UBL20WriterBuilder(@Nonnull final EUBL20DocumentType eDocType) {\n super(eDocType);\n // Create a special namespace context for the passed document type\n final MapBasedNamespaceContext aNSContext = UBL20NamespaceContext.getInstance().getClone();\n // Avoid overwriting an already mapped context\n if (!aNSContext.isNamespaceURIMapped(m_aDocType.getNamespaceURI()))\n aNSContext.addDefaultNamespaceURI(m_aDocType.getNamespaceURI());\n setNamespaceContext(aNSContext);\n }\n\n public UBL20WriterBuilder(@Nonnull final Class aClass) {\n this(UBL20DocumentTypes.getDocumentTypeOfImplementationClass(aClass));\n }\n\n /**\n * Create a new writer builder.\n *\n * @param aClass\n * The UBL class to be written. May not be null.\n * @return The new writer builder. Never null.\n * @param \n * The UBL 2.0 document implementation type\n */\n @Nonnull\n public static UBL20WriterBuilder create(@Nonnull final Class aClass) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2091", "language": "Java", "task_type": "single_line", "source_file": "java/github/phax/ph-ubl/ph-ubl20/src/main/java/com/helger/ubl20/UBL20WriterBuilder.java", "mask_start_position": 1620, "mask_end_position": 1624, "canonical_solution": "ss);", "pre_mask_code": "package com.helger.ubl20;\n\nimport javax.annotation.Nonnull;\nimport javax.annotation.concurrent.NotThreadSafe;\nimport com.helger.jaxb.builder.JAXBWriterBuilder;\nimport com.helger.xml.namespace.MapBasedNamespaceContext;\n\n/**\n * A writer builder for UBL 2.0 documents.\n *\n * @author Philip Helger\n * @param \n * The UBL 2.0 implementation class to be read\n */\n@NotThreadSafe\npublic class UBL20WriterBuilder extends JAXBWriterBuilder> {\n\n public UBL20WriterBuilder(@Nonnull final EUBL20DocumentType eDocType) {\n super(eDocType);\n // Create a special namespace context for the passed document type\n final MapBasedNamespaceContext aNSContext = UBL20NamespaceContext.getInstance().getClone();\n // Avoid overwriting an already mapped context\n if (!aNSContext.isNamespaceURIMapped(m_aDocType.getNamespaceURI()))\n aNSContext.addDefaultNamespaceURI(m_aDocType.getNamespaceURI());\n setNamespaceContext(aNSContext);\n }\n\n public UBL20WriterBuilder(@Nonnull final Class aClass) {\n this(UBL20DocumentTypes.getDocumentTypeOfImplementationClass(aClass));\n }\n\n /**\n * Create a new writer builder.\n *\n * @param aClass\n * The UBL class to be written. May not be null.\n * @return The new writer builder. Never null.\n * @param \n * The UBL 2.0 document implementation type\n */\n @Nonnull\n public static UBL20WriterBuilder create(@Nonnull final Class aClass) {\n return new UBL20WriterBuilder<>(aCla", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2092", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/phax/ph-ubl/ph-ubl20/src/main/java/com/helger/ubl20/UBL20WriterBuilder.java", "mask_start_position": 1482, "mask_end_position": 1630, "canonical_solution": "@Nonnull\n public static UBL20WriterBuilder create(@Nonnull final Class aClass) {\n return new UBL20WriterBuilder<>(aClass);\n }", "pre_mask_code": "package com.helger.ubl20;\n\nimport javax.annotation.Nonnull;\nimport javax.annotation.concurrent.NotThreadSafe;\nimport com.helger.jaxb.builder.JAXBWriterBuilder;\nimport com.helger.xml.namespace.MapBasedNamespaceContext;\n\n/**\n * A writer builder for UBL 2.0 documents.\n *\n * @author Philip Helger\n * @param \n * The UBL 2.0 implementation class to be read\n */\n@NotThreadSafe\npublic class UBL20WriterBuilder extends JAXBWriterBuilder> {\n\n public UBL20WriterBuilder(@Nonnull final EUBL20DocumentType eDocType) {\n super(eDocType);\n // Create a special namespace context for the passed document type\n final MapBasedNamespaceContext aNSContext = UBL20NamespaceContext.getInstance().getClone();\n // Avoid overwriting an already mapped context\n if (!aNSContext.isNamespaceURIMapped(m_aDocType.getNamespaceURI()))\n aNSContext.addDefaultNamespaceURI(m_aDocType.getNamespaceURI());\n setNamespaceContext(aNSContext);\n }\n\n public UBL20WriterBuilder(@Nonnull final Class aClass) {\n this(UBL20DocumentTypes.getDocumentTypeOfImplementationClass(aClass));\n }\n\n /**\n * Create a new writer builder.\n *\n * @param aClass\n * The UBL class to be written. May not be null.\n * @return The new writer builder. Never null.\n * @param \n * The UBL 2.0 document implementation type\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2093", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ctripcorp/dal/dal-cluster-client/src/main/java/com/ctrip/framework/dal/cluster/client/cluster/DefaultCluster.java", "mask_start_position": 5719, "mask_end_position": 5789, "canonical_solution": "@Override\n public T unwrap(Class iface) throws SQLException ", "pre_mask_code": "package com.ctrip.framework.dal.cluster.client.cluster;\n\nimport com.ctrip.framework.dal.cluster.client.Cluster;\nimport com.ctrip.framework.dal.cluster.client.base.UnsupportedListenable;\nimport com.ctrip.framework.dal.cluster.client.config.ClusterConfigImpl;\nimport com.ctrip.framework.dal.cluster.client.config.DalConfigCustomizedOption;\nimport com.ctrip.framework.dal.cluster.client.config.LocalizationConfig;\nimport com.ctrip.framework.dal.cluster.client.database.Database;\nimport com.ctrip.framework.dal.cluster.client.database.DatabaseCategory;\nimport com.ctrip.framework.dal.cluster.client.exception.ClusterRuntimeException;\nimport com.ctrip.framework.dal.cluster.client.multihost.ClusterRouteStrategyConfig;\nimport com.ctrip.framework.dal.cluster.client.shard.DatabaseShard;\nimport com.ctrip.framework.dal.cluster.client.sharding.context.DbShardContext;\nimport com.ctrip.framework.dal.cluster.client.sharding.context.TableShardContext;\nimport com.ctrip.framework.dal.cluster.client.sharding.idgen.ClusterIdGeneratorConfig;\nimport java.sql.SQLException;\nimport java.util.*;\n\n/**\n * @author c7ch23en\n */\npublic class DefaultCluster extends UnsupportedListenable implements Cluster {\n\n private ClusterConfigImpl clusterConfig;\n\n private Map databaseShards = new HashMap<>();\n\n private ShardStrategyProxy shardStrategyProxy;\n\n private ClusterIdGeneratorConfig idGeneratorConfig;\n\n private ClusterRouteStrategyConfig routeStrategyConfig;\n\n private LocalizationConfig localizationConfig;\n\n private LocalizationConfig lastLocalizationConfig;\n\n private DalConfigCustomizedOption customizedOption;\n\n public DefaultCluster(ClusterConfigImpl clusterConfig) {\n this.clusterConfig = clusterConfig;\n }\n\n @Override\n public String getClusterName() {\n return clusterConfig.getClusterName();\n }\n\n @Override\n public ClusterType getClusterType() {\n return clusterConfig.getClusterType();\n }\n\n @Override\n public DatabaseCategory getDatabaseCategory() {\n return clusterConfig.getDatabaseCategory();\n }\n\n @Override\n public boolean dbShardingEnabled() {\n return databaseShards.size() > 1;\n }\n\n @Override\n public Integer getDbShard(String tableName, DbShardContext context) {\n return shardStrategyProxy.getDbShard(tableName, context);\n }\n\n @Override\n public Set getAllDbShards() {\n return databaseShards.keySet();\n }\n\n @Override\n public boolean tableShardingEnabled(String tableName) {\n return shardStrategyProxy.tableShardingEnabled(tableName);\n }\n\n @Override\n public String getTableShard(String tableName, TableShardContext context) {\n return shardStrategyProxy.getTableShard(tableName, context);\n }\n\n @Override\n public Set getAllTableShards(String tableName) {\n return shardStrategyProxy.getAllTableShards(tableName);\n }\n\n @Override\n public String getTableShardSeparator(String tableName) {\n return shardStrategyProxy.getTableShardSeparator(tableName);\n }\n\n @Override\n public List getDatabases() {\n List databases = new LinkedList<>();\n for (DatabaseShard databaseShard : databaseShards.values()) {\n databases.addAll(databaseShard.getMasters());\n databases.addAll(databaseShard.getSlaves());\n }\n return databases;\n }\n\n @Override\n public Database getMasterOnShard(int shardIndex) {\n List masters = databaseShards.get(shardIndex).getMasters();\n if (masters == null || masters.isEmpty())\n throw new ClusterRuntimeException(\"no master available\");\n // throw new ClusterRuntimeException(\"multi masters available\");\n return masters.iterator().next();\n }\n\n @Override\n public List getSlavesOnShard(int shardIndex) {\n return databaseShards.get(shardIndex).getSlaves();\n }\n\n @Override\n public ClusterIdGeneratorConfig getIdGeneratorConfig() {\n return idGeneratorConfig;\n }\n\n @Override\n public ClusterRouteStrategyConfig getRouteStrategyConfig() {\n return routeStrategyConfig;\n }\n\n @Override\n public LocalizationConfig getLocalizationConfig() {\n return localizationConfig;\n }\n\n @Override\n public LocalizationConfig getLastLocalizationConfig() {\n return this.lastLocalizationConfig;\n }\n\n @Override\n public DalConfigCustomizedOption getCustomizedOption() {\n return this.customizedOption;\n }\n\n @Override\n public DatabaseShard getDatabaseShard(int shardIndex) {\n return databaseShards.get(shardIndex);\n }\n\n public void setCustomizedOption(DalConfigCustomizedOption customizedOption) {\n this.customizedOption = customizedOption;\n }\n\n public void setLastLocalizationConfig(LocalizationConfig lastConfig) {\n this.lastLocalizationConfig = lastConfig;\n }\n\n public void addDatabaseShard(DatabaseShard databaseShard) {\n databaseShards.put(databaseShard.getShardIndex(), databaseShard);\n }\n\n public void setShardStrategy(ShardStrategyProxy shardStrategyProxy) {\n this.shardStrategyProxy = shardStrategyProxy;\n }\n\n public void setIdGeneratorConfig(ClusterIdGeneratorConfig idGeneratorConfig) {\n this.idGeneratorConfig = idGeneratorConfig;\n }\n\n public void setRouteStrategyConfig(ClusterRouteStrategyConfig routeStrategyConfig) {\n this.routeStrategyConfig = routeStrategyConfig;\n }\n\n public void setLocalizationConfig(LocalizationConfig localizationConfig) {\n this.localizationConfig = localizationConfig;\n }\n\n public void validate() {\n }\n\n ", "post_mask_code": "{\n try {\n return iface.cast(this);\n } catch (ClassCastException e) {\n throw new ClusterRuntimeException(String.format(\"Unable to unwrap %s to %s\", this.toString(), iface.toString()));\n }\n }\n\n @Override\n public boolean isWrapperFor(Class iface) throws SQLException {\n return iface.isInstance(this);\n }\n}\n"} {"task_id": "Java_2094", "language": "Java", "task_type": "method_body", "source_file": "java/github/ctripcorp/dal/dal-cluster-client/src/main/java/com/ctrip/framework/dal/cluster/client/cluster/DefaultCluster.java", "mask_start_position": 4906, "mask_end_position": 4963, "canonical_solution": "{\n this.lastLocalizationConfig = lastConfig;\n }", "pre_mask_code": "package com.ctrip.framework.dal.cluster.client.cluster;\n\nimport com.ctrip.framework.dal.cluster.client.Cluster;\nimport com.ctrip.framework.dal.cluster.client.base.UnsupportedListenable;\nimport com.ctrip.framework.dal.cluster.client.config.ClusterConfigImpl;\nimport com.ctrip.framework.dal.cluster.client.config.DalConfigCustomizedOption;\nimport com.ctrip.framework.dal.cluster.client.config.LocalizationConfig;\nimport com.ctrip.framework.dal.cluster.client.database.Database;\nimport com.ctrip.framework.dal.cluster.client.database.DatabaseCategory;\nimport com.ctrip.framework.dal.cluster.client.exception.ClusterRuntimeException;\nimport com.ctrip.framework.dal.cluster.client.multihost.ClusterRouteStrategyConfig;\nimport com.ctrip.framework.dal.cluster.client.shard.DatabaseShard;\nimport com.ctrip.framework.dal.cluster.client.sharding.context.DbShardContext;\nimport com.ctrip.framework.dal.cluster.client.sharding.context.TableShardContext;\nimport com.ctrip.framework.dal.cluster.client.sharding.idgen.ClusterIdGeneratorConfig;\nimport java.sql.SQLException;\nimport java.util.*;\n\n/**\n * @author c7ch23en\n */\npublic class DefaultCluster extends UnsupportedListenable implements Cluster {\n\n private ClusterConfigImpl clusterConfig;\n\n private Map databaseShards = new HashMap<>();\n\n private ShardStrategyProxy shardStrategyProxy;\n\n private ClusterIdGeneratorConfig idGeneratorConfig;\n\n private ClusterRouteStrategyConfig routeStrategyConfig;\n\n private LocalizationConfig localizationConfig;\n\n private LocalizationConfig lastLocalizationConfig;\n\n private DalConfigCustomizedOption customizedOption;\n\n public DefaultCluster(ClusterConfigImpl clusterConfig) {\n this.clusterConfig = clusterConfig;\n }\n\n @Override\n public String getClusterName() {\n return clusterConfig.getClusterName();\n }\n\n @Override\n public ClusterType getClusterType() {\n return clusterConfig.getClusterType();\n }\n\n @Override\n public DatabaseCategory getDatabaseCategory() {\n return clusterConfig.getDatabaseCategory();\n }\n\n @Override\n public boolean dbShardingEnabled() {\n return databaseShards.size() > 1;\n }\n\n @Override\n public Integer getDbShard(String tableName, DbShardContext context) {\n return shardStrategyProxy.getDbShard(tableName, context);\n }\n\n @Override\n public Set getAllDbShards() {\n return databaseShards.keySet();\n }\n\n @Override\n public boolean tableShardingEnabled(String tableName) {\n return shardStrategyProxy.tableShardingEnabled(tableName);\n }\n\n @Override\n public String getTableShard(String tableName, TableShardContext context) {\n return shardStrategyProxy.getTableShard(tableName, context);\n }\n\n @Override\n public Set getAllTableShards(String tableName) {\n return shardStrategyProxy.getAllTableShards(tableName);\n }\n\n @Override\n public String getTableShardSeparator(String tableName) {\n return shardStrategyProxy.getTableShardSeparator(tableName);\n }\n\n @Override\n public List getDatabases() {\n List databases = new LinkedList<>();\n for (DatabaseShard databaseShard : databaseShards.values()) {\n databases.addAll(databaseShard.getMasters());\n databases.addAll(databaseShard.getSlaves());\n }\n return databases;\n }\n\n @Override\n public Database getMasterOnShard(int shardIndex) {\n List masters = databaseShards.get(shardIndex).getMasters();\n if (masters == null || masters.isEmpty())\n throw new ClusterRuntimeException(\"no master available\");\n // throw new ClusterRuntimeException(\"multi masters available\");\n return masters.iterator().next();\n }\n\n @Override\n public List getSlavesOnShard(int shardIndex) {\n return databaseShards.get(shardIndex).getSlaves();\n }\n\n @Override\n public ClusterIdGeneratorConfig getIdGeneratorConfig() {\n return idGeneratorConfig;\n }\n\n @Override\n public ClusterRouteStrategyConfig getRouteStrategyConfig() {\n return routeStrategyConfig;\n }\n\n @Override\n public LocalizationConfig getLocalizationConfig() {\n return localizationConfig;\n }\n\n @Override\n public LocalizationConfig getLastLocalizationConfig() {\n return this.lastLocalizationConfig;\n }\n\n @Override\n public DalConfigCustomizedOption getCustomizedOption() {\n return this.customizedOption;\n }\n\n @Override\n public DatabaseShard getDatabaseShard(int shardIndex) {\n return databaseShards.get(shardIndex);\n }\n\n public void setCustomizedOption(DalConfigCustomizedOption customizedOption) {\n this.customizedOption = customizedOption;\n }\n\n public void setLastLocalizationConfig(LocalizationConfig lastConfig) ", "post_mask_code": "\n\n public void addDatabaseShard(DatabaseShard databaseShard) {\n databaseShards.put(databaseShard.getShardIndex(), databaseShard);\n }\n\n public void setShardStrategy(ShardStrategyProxy shardStrategyProxy) {\n this.shardStrategyProxy = shardStrategyProxy;\n }\n\n public void setIdGeneratorConfig(ClusterIdGeneratorConfig idGeneratorConfig) {\n this.idGeneratorConfig = idGeneratorConfig;\n }\n\n public void setRouteStrategyConfig(ClusterRouteStrategyConfig routeStrategyConfig) {\n this.routeStrategyConfig = routeStrategyConfig;\n }\n\n public void setLocalizationConfig(LocalizationConfig localizationConfig) {\n this.localizationConfig = localizationConfig;\n }\n\n public void validate() {\n }\n\n @Override\n public T unwrap(Class iface) throws SQLException {\n try {\n return iface.cast(this);\n } catch (ClassCastException e) {\n throw new ClusterRuntimeException(String.format(\"Unable to unwrap %s to %s\", this.toString(), iface.toString()));\n }\n }\n\n @Override\n public boolean isWrapperFor(Class iface) throws SQLException {\n return iface.isInstance(this);\n }\n}\n"} {"task_id": "Java_2095", "language": "Java", "task_type": "single_line", "source_file": "java/github/ctripcorp/dal/dal-cluster-client/src/main/java/com/ctrip/framework/dal/cluster/client/cluster/DefaultCluster.java", "mask_start_position": 4066, "mask_end_position": 4079, "canonical_solution": "eratorConfig;", "pre_mask_code": "package com.ctrip.framework.dal.cluster.client.cluster;\n\nimport com.ctrip.framework.dal.cluster.client.Cluster;\nimport com.ctrip.framework.dal.cluster.client.base.UnsupportedListenable;\nimport com.ctrip.framework.dal.cluster.client.config.ClusterConfigImpl;\nimport com.ctrip.framework.dal.cluster.client.config.DalConfigCustomizedOption;\nimport com.ctrip.framework.dal.cluster.client.config.LocalizationConfig;\nimport com.ctrip.framework.dal.cluster.client.database.Database;\nimport com.ctrip.framework.dal.cluster.client.database.DatabaseCategory;\nimport com.ctrip.framework.dal.cluster.client.exception.ClusterRuntimeException;\nimport com.ctrip.framework.dal.cluster.client.multihost.ClusterRouteStrategyConfig;\nimport com.ctrip.framework.dal.cluster.client.shard.DatabaseShard;\nimport com.ctrip.framework.dal.cluster.client.sharding.context.DbShardContext;\nimport com.ctrip.framework.dal.cluster.client.sharding.context.TableShardContext;\nimport com.ctrip.framework.dal.cluster.client.sharding.idgen.ClusterIdGeneratorConfig;\nimport java.sql.SQLException;\nimport java.util.*;\n\n/**\n * @author c7ch23en\n */\npublic class DefaultCluster extends UnsupportedListenable implements Cluster {\n\n private ClusterConfigImpl clusterConfig;\n\n private Map databaseShards = new HashMap<>();\n\n private ShardStrategyProxy shardStrategyProxy;\n\n private ClusterIdGeneratorConfig idGeneratorConfig;\n\n private ClusterRouteStrategyConfig routeStrategyConfig;\n\n private LocalizationConfig localizationConfig;\n\n private LocalizationConfig lastLocalizationConfig;\n\n private DalConfigCustomizedOption customizedOption;\n\n public DefaultCluster(ClusterConfigImpl clusterConfig) {\n this.clusterConfig = clusterConfig;\n }\n\n @Override\n public String getClusterName() {\n return clusterConfig.getClusterName();\n }\n\n @Override\n public ClusterType getClusterType() {\n return clusterConfig.getClusterType();\n }\n\n @Override\n public DatabaseCategory getDatabaseCategory() {\n return clusterConfig.getDatabaseCategory();\n }\n\n @Override\n public boolean dbShardingEnabled() {\n return databaseShards.size() > 1;\n }\n\n @Override\n public Integer getDbShard(String tableName, DbShardContext context) {\n return shardStrategyProxy.getDbShard(tableName, context);\n }\n\n @Override\n public Set getAllDbShards() {\n return databaseShards.keySet();\n }\n\n @Override\n public boolean tableShardingEnabled(String tableName) {\n return shardStrategyProxy.tableShardingEnabled(tableName);\n }\n\n @Override\n public String getTableShard(String tableName, TableShardContext context) {\n return shardStrategyProxy.getTableShard(tableName, context);\n }\n\n @Override\n public Set getAllTableShards(String tableName) {\n return shardStrategyProxy.getAllTableShards(tableName);\n }\n\n @Override\n public String getTableShardSeparator(String tableName) {\n return shardStrategyProxy.getTableShardSeparator(tableName);\n }\n\n @Override\n public List getDatabases() {\n List databases = new LinkedList<>();\n for (DatabaseShard databaseShard : databaseShards.values()) {\n databases.addAll(databaseShard.getMasters());\n databases.addAll(databaseShard.getSlaves());\n }\n return databases;\n }\n\n @Override\n public Database getMasterOnShard(int shardIndex) {\n List masters = databaseShards.get(shardIndex).getMasters();\n if (masters == null || masters.isEmpty())\n throw new ClusterRuntimeException(\"no master available\");\n // throw new ClusterRuntimeException(\"multi masters available\");\n return masters.iterator().next();\n }\n\n @Override\n public List getSlavesOnShard(int shardIndex) {\n return databaseShards.get(shardIndex).getSlaves();\n }\n\n @Override\n public ClusterIdGeneratorConfig getIdGeneratorConfig() {\n return idGen", "post_mask_code": "\n }\n\n @Override\n public ClusterRouteStrategyConfig getRouteStrategyConfig() {\n return routeStrategyConfig;\n }\n\n @Override\n public LocalizationConfig getLocalizationConfig() {\n return localizationConfig;\n }\n\n @Override\n public LocalizationConfig getLastLocalizationConfig() {\n return this.lastLocalizationConfig;\n }\n\n @Override\n public DalConfigCustomizedOption getCustomizedOption() {\n return this.customizedOption;\n }\n\n @Override\n public DatabaseShard getDatabaseShard(int shardIndex) {\n return databaseShards.get(shardIndex);\n }\n\n public void setCustomizedOption(DalConfigCustomizedOption customizedOption) {\n this.customizedOption = customizedOption;\n }\n\n public void setLastLocalizationConfig(LocalizationConfig lastConfig) {\n this.lastLocalizationConfig = lastConfig;\n }\n\n public void addDatabaseShard(DatabaseShard databaseShard) {\n databaseShards.put(databaseShard.getShardIndex(), databaseShard);\n }\n\n public void setShardStrategy(ShardStrategyProxy shardStrategyProxy) {\n this.shardStrategyProxy = shardStrategyProxy;\n }\n\n public void setIdGeneratorConfig(ClusterIdGeneratorConfig idGeneratorConfig) {\n this.idGeneratorConfig = idGeneratorConfig;\n }\n\n public void setRouteStrategyConfig(ClusterRouteStrategyConfig routeStrategyConfig) {\n this.routeStrategyConfig = routeStrategyConfig;\n }\n\n public void setLocalizationConfig(LocalizationConfig localizationConfig) {\n this.localizationConfig = localizationConfig;\n }\n\n public void validate() {\n }\n\n @Override\n public T unwrap(Class iface) throws SQLException {\n try {\n return iface.cast(this);\n } catch (ClassCastException e) {\n throw new ClusterRuntimeException(String.format(\"Unable to unwrap %s to %s\", this.toString(), iface.toString()));\n }\n }\n\n @Override\n public boolean isWrapperFor(Class iface) throws SQLException {\n return iface.isInstance(this);\n }\n}\n"} {"task_id": "Java_2096", "language": "Java", "task_type": "try_statement", "source_file": "java/github/ctripcorp/dal/dal-cluster-client/src/main/java/com/ctrip/framework/dal/cluster/client/cluster/DefaultCluster.java", "mask_start_position": 5799, "mask_end_position": 6018, "canonical_solution": "try {\n return iface.cast(this);\n } catch (ClassCastException e) {\n throw new ClusterRuntimeException(String.format(\"Unable to unwrap %s to %s\", this.toString(), iface.toString()));\n }", "pre_mask_code": "package com.ctrip.framework.dal.cluster.client.cluster;\n\nimport com.ctrip.framework.dal.cluster.client.Cluster;\nimport com.ctrip.framework.dal.cluster.client.base.UnsupportedListenable;\nimport com.ctrip.framework.dal.cluster.client.config.ClusterConfigImpl;\nimport com.ctrip.framework.dal.cluster.client.config.DalConfigCustomizedOption;\nimport com.ctrip.framework.dal.cluster.client.config.LocalizationConfig;\nimport com.ctrip.framework.dal.cluster.client.database.Database;\nimport com.ctrip.framework.dal.cluster.client.database.DatabaseCategory;\nimport com.ctrip.framework.dal.cluster.client.exception.ClusterRuntimeException;\nimport com.ctrip.framework.dal.cluster.client.multihost.ClusterRouteStrategyConfig;\nimport com.ctrip.framework.dal.cluster.client.shard.DatabaseShard;\nimport com.ctrip.framework.dal.cluster.client.sharding.context.DbShardContext;\nimport com.ctrip.framework.dal.cluster.client.sharding.context.TableShardContext;\nimport com.ctrip.framework.dal.cluster.client.sharding.idgen.ClusterIdGeneratorConfig;\nimport java.sql.SQLException;\nimport java.util.*;\n\n/**\n * @author c7ch23en\n */\npublic class DefaultCluster extends UnsupportedListenable implements Cluster {\n\n private ClusterConfigImpl clusterConfig;\n\n private Map databaseShards = new HashMap<>();\n\n private ShardStrategyProxy shardStrategyProxy;\n\n private ClusterIdGeneratorConfig idGeneratorConfig;\n\n private ClusterRouteStrategyConfig routeStrategyConfig;\n\n private LocalizationConfig localizationConfig;\n\n private LocalizationConfig lastLocalizationConfig;\n\n private DalConfigCustomizedOption customizedOption;\n\n public DefaultCluster(ClusterConfigImpl clusterConfig) {\n this.clusterConfig = clusterConfig;\n }\n\n @Override\n public String getClusterName() {\n return clusterConfig.getClusterName();\n }\n\n @Override\n public ClusterType getClusterType() {\n return clusterConfig.getClusterType();\n }\n\n @Override\n public DatabaseCategory getDatabaseCategory() {\n return clusterConfig.getDatabaseCategory();\n }\n\n @Override\n public boolean dbShardingEnabled() {\n return databaseShards.size() > 1;\n }\n\n @Override\n public Integer getDbShard(String tableName, DbShardContext context) {\n return shardStrategyProxy.getDbShard(tableName, context);\n }\n\n @Override\n public Set getAllDbShards() {\n return databaseShards.keySet();\n }\n\n @Override\n public boolean tableShardingEnabled(String tableName) {\n return shardStrategyProxy.tableShardingEnabled(tableName);\n }\n\n @Override\n public String getTableShard(String tableName, TableShardContext context) {\n return shardStrategyProxy.getTableShard(tableName, context);\n }\n\n @Override\n public Set getAllTableShards(String tableName) {\n return shardStrategyProxy.getAllTableShards(tableName);\n }\n\n @Override\n public String getTableShardSeparator(String tableName) {\n return shardStrategyProxy.getTableShardSeparator(tableName);\n }\n\n @Override\n public List getDatabases() {\n List databases = new LinkedList<>();\n for (DatabaseShard databaseShard : databaseShards.values()) {\n databases.addAll(databaseShard.getMasters());\n databases.addAll(databaseShard.getSlaves());\n }\n return databases;\n }\n\n @Override\n public Database getMasterOnShard(int shardIndex) {\n List masters = databaseShards.get(shardIndex).getMasters();\n if (masters == null || masters.isEmpty())\n throw new ClusterRuntimeException(\"no master available\");\n // throw new ClusterRuntimeException(\"multi masters available\");\n return masters.iterator().next();\n }\n\n @Override\n public List getSlavesOnShard(int shardIndex) {\n return databaseShards.get(shardIndex).getSlaves();\n }\n\n @Override\n public ClusterIdGeneratorConfig getIdGeneratorConfig() {\n return idGeneratorConfig;\n }\n\n @Override\n public ClusterRouteStrategyConfig getRouteStrategyConfig() {\n return routeStrategyConfig;\n }\n\n @Override\n public LocalizationConfig getLocalizationConfig() {\n return localizationConfig;\n }\n\n @Override\n public LocalizationConfig getLastLocalizationConfig() {\n return this.lastLocalizationConfig;\n }\n\n @Override\n public DalConfigCustomizedOption getCustomizedOption() {\n return this.customizedOption;\n }\n\n @Override\n public DatabaseShard getDatabaseShard(int shardIndex) {\n return databaseShards.get(shardIndex);\n }\n\n public void setCustomizedOption(DalConfigCustomizedOption customizedOption) {\n this.customizedOption = customizedOption;\n }\n\n public void setLastLocalizationConfig(LocalizationConfig lastConfig) {\n this.lastLocalizationConfig = lastConfig;\n }\n\n public void addDatabaseShard(DatabaseShard databaseShard) {\n databaseShards.put(databaseShard.getShardIndex(), databaseShard);\n }\n\n public void setShardStrategy(ShardStrategyProxy shardStrategyProxy) {\n this.shardStrategyProxy = shardStrategyProxy;\n }\n\n public void setIdGeneratorConfig(ClusterIdGeneratorConfig idGeneratorConfig) {\n this.idGeneratorConfig = idGeneratorConfig;\n }\n\n public void setRouteStrategyConfig(ClusterRouteStrategyConfig routeStrategyConfig) {\n this.routeStrategyConfig = routeStrategyConfig;\n }\n\n public void setLocalizationConfig(LocalizationConfig localizationConfig) {\n this.localizationConfig = localizationConfig;\n }\n\n public void validate() {\n }\n\n @Override\n public T unwrap(Class iface) throws SQLException {\n ", "post_mask_code": "\n }\n\n @Override\n public boolean isWrapperFor(Class iface) throws SQLException {\n return iface.isInstance(this);\n }\n}\n"} {"task_id": "Java_2097", "language": "Java", "task_type": "method_signature", "source_file": "java/github/NikhilBhutani/Android-Snippets/Firebase/app/src/main/java/github/nikhilbhutani/firebase/Users.java", "mask_start_position": 277, "mask_end_position": 301, "canonical_solution": "public String getName() ", "pre_mask_code": "package github.nikhilbhutani.firebase;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\n\n/**\n * Created by Nikhil Bhutani on 6/5/2016.\n */\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Users {\n\n private String name;\n\n public Users() {\n }\n\n ", "post_mask_code": "{\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n}\n"} {"task_id": "Java_2098", "language": "Java", "task_type": "method_body", "source_file": "java/github/NikhilBhutani/Android-Snippets/Firebase/app/src/main/java/github/nikhilbhutani/firebase/Users.java", "mask_start_position": 368, "mask_end_position": 401, "canonical_solution": "{\n this.name = name;\n }", "pre_mask_code": "package github.nikhilbhutani.firebase;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\n\n/**\n * Created by Nikhil Bhutani on 6/5/2016.\n */\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Users {\n\n private String name;\n\n public Users() {\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2099", "language": "Java", "task_type": "single_line", "source_file": "java/github/NikhilBhutani/Android-Snippets/Firebase/app/src/main/java/github/nikhilbhutani/firebase/Users.java", "mask_start_position": 319, "mask_end_position": 323, "canonical_solution": "ame;", "pre_mask_code": "package github.nikhilbhutani.firebase;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\n\n/**\n * Created by Nikhil Bhutani on 6/5/2016.\n */\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Users {\n\n private String name;\n\n public Users() {\n }\n\n public String getName() {\n return n", "post_mask_code": "\n }\n\n public void setName(String name) {\n this.name = name;\n }\n}\n"} {"task_id": "Java_2100", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ls1intum/Artemis/src/main/java/de/tum/in/www1/artemis/service/scheduled/ScheduleService.java", "mask_start_position": 1253, "mask_end_position": 1334, "canonical_solution": "private void removeScheduledTask(Exercise exercise, ExerciseLifecycle lifecycle) ", "pre_mask_code": "package de.tum.in.www1.artemis.service.scheduled;\n\nimport java.time.ZonedDateTime;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ScheduledFuture;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.enumeration.ExerciseLifecycle;\nimport de.tum.in.www1.artemis.service.ExerciseLifecycleService;\nimport de.tum.in.www1.artemis.service.util.Tuple;\n\n@Service\npublic class ScheduleService {\n\n private final Logger log = LoggerFactory.getLogger(ScheduleService.class);\n\n private final ExerciseLifecycleService exerciseLifecycleService;\n\n private final Map, Set>> scheduledTasks = new HashMap<>();\n\n public ScheduleService(ExerciseLifecycleService exerciseLifecycleService) {\n this.exerciseLifecycleService = exerciseLifecycleService;\n }\n\n private void addScheduledTask(Exercise exercise, ExerciseLifecycle lifecycle, Set> futures) {\n Tuple taskId = new Tuple<>(exercise.getId(), lifecycle);\n scheduledTasks.put(taskId, futures);\n }\n\n ", "post_mask_code": "{\n removeScheduledTask(exercise.getId(), lifecycle);\n }\n\n private void removeScheduledTask(Long exerciseId, ExerciseLifecycle lifecycle) {\n Tuple taskId = new Tuple<>(exerciseId, lifecycle);\n scheduledTasks.remove(taskId);\n }\n\n /**\n * Schedule a task for the given Exercise for the provided ExerciseLifecycle.\n *\n * @param exercise Exercise\n * @param lifecycle ExerciseLifecycle\n * @param task Runnable task to be executed on the lifecycle hook\n */\n void scheduleTask(Exercise exercise, ExerciseLifecycle lifecycle, Runnable task) {\n // no exercise should be scheduled more than once.\n cancelScheduledTaskForLifecycle(exercise.getId(), lifecycle);\n ScheduledFuture scheduledTask = exerciseLifecycleService.scheduleTask(exercise, lifecycle, task);\n addScheduledTask(exercise, lifecycle, Set.of(scheduledTask));\n }\n\n /**\n * Schedule a set of tasks for the given Exercise for the provided ExerciseLifecycle at the given times.\n *\n * @param exercise Exercise\n * @param lifecycle ExerciseLifecycle\n * @param tasks Runnable tasks to be executed at the associated ZonedDateTimes\n */\n void scheduleTask(Exercise exercise, ExerciseLifecycle lifecycle, Set> tasks) {\n // no exercise should be scheduled more than once.\n cancelScheduledTaskForLifecycle(exercise.getId(), lifecycle);\n Set> scheduledTasks = exerciseLifecycleService.scheduleMultipleTasks(exercise, lifecycle, tasks);\n addScheduledTask(exercise, lifecycle, scheduledTasks);\n }\n\n /**\n * Cancel possible schedules tasks for a provided exercise.\n * @param exerciseId if of the exercise for which a potential scheduled task is canceled\n */\n void cancelScheduledTaskForLifecycle(Long exerciseId, ExerciseLifecycle lifecycle) {\n Tuple taskId = new Tuple<>(exerciseId, lifecycle);\n Set> futures = scheduledTasks.get(taskId);\n if (futures != null) {\n log.debug(\"Cancelling scheduled task {} for Exercise (#{}).\", lifecycle, exerciseId);\n futures.forEach(future -> future.cancel(false));\n removeScheduledTask(exerciseId, lifecycle);\n }\n }\n}\n"} {"task_id": "Java_2101", "language": "Java", "task_type": "method_body", "source_file": "java/github/ls1intum/Artemis/src/main/java/de/tum/in/www1/artemis/service/scheduled/ScheduleService.java", "mask_start_position": 1105, "mask_end_position": 1247, "canonical_solution": "{\n Tuple taskId = new Tuple<>(exercise.getId(), lifecycle);\n scheduledTasks.put(taskId, futures);\n }", "pre_mask_code": "package de.tum.in.www1.artemis.service.scheduled;\n\nimport java.time.ZonedDateTime;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ScheduledFuture;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.enumeration.ExerciseLifecycle;\nimport de.tum.in.www1.artemis.service.ExerciseLifecycleService;\nimport de.tum.in.www1.artemis.service.util.Tuple;\n\n@Service\npublic class ScheduleService {\n\n private final Logger log = LoggerFactory.getLogger(ScheduleService.class);\n\n private final ExerciseLifecycleService exerciseLifecycleService;\n\n private final Map, Set>> scheduledTasks = new HashMap<>();\n\n public ScheduleService(ExerciseLifecycleService exerciseLifecycleService) {\n this.exerciseLifecycleService = exerciseLifecycleService;\n }\n\n private void addScheduledTask(Exercise exercise, ExerciseLifecycle lifecycle, Set> futures) ", "post_mask_code": "\n\n private void removeScheduledTask(Exercise exercise, ExerciseLifecycle lifecycle) {\n removeScheduledTask(exercise.getId(), lifecycle);\n }\n\n private void removeScheduledTask(Long exerciseId, ExerciseLifecycle lifecycle) {\n Tuple taskId = new Tuple<>(exerciseId, lifecycle);\n scheduledTasks.remove(taskId);\n }\n\n /**\n * Schedule a task for the given Exercise for the provided ExerciseLifecycle.\n *\n * @param exercise Exercise\n * @param lifecycle ExerciseLifecycle\n * @param task Runnable task to be executed on the lifecycle hook\n */\n void scheduleTask(Exercise exercise, ExerciseLifecycle lifecycle, Runnable task) {\n // no exercise should be scheduled more than once.\n cancelScheduledTaskForLifecycle(exercise.getId(), lifecycle);\n ScheduledFuture scheduledTask = exerciseLifecycleService.scheduleTask(exercise, lifecycle, task);\n addScheduledTask(exercise, lifecycle, Set.of(scheduledTask));\n }\n\n /**\n * Schedule a set of tasks for the given Exercise for the provided ExerciseLifecycle at the given times.\n *\n * @param exercise Exercise\n * @param lifecycle ExerciseLifecycle\n * @param tasks Runnable tasks to be executed at the associated ZonedDateTimes\n */\n void scheduleTask(Exercise exercise, ExerciseLifecycle lifecycle, Set> tasks) {\n // no exercise should be scheduled more than once.\n cancelScheduledTaskForLifecycle(exercise.getId(), lifecycle);\n Set> scheduledTasks = exerciseLifecycleService.scheduleMultipleTasks(exercise, lifecycle, tasks);\n addScheduledTask(exercise, lifecycle, scheduledTasks);\n }\n\n /**\n * Cancel possible schedules tasks for a provided exercise.\n * @param exerciseId if of the exercise for which a potential scheduled task is canceled\n */\n void cancelScheduledTaskForLifecycle(Long exerciseId, ExerciseLifecycle lifecycle) {\n Tuple taskId = new Tuple<>(exerciseId, lifecycle);\n Set> futures = scheduledTasks.get(taskId);\n if (futures != null) {\n log.debug(\"Cancelling scheduled task {} for Exercise (#{}).\", lifecycle, exerciseId);\n futures.forEach(future -> future.cancel(false));\n removeScheduledTask(exerciseId, lifecycle);\n }\n }\n}\n"} {"task_id": "Java_2102", "language": "Java", "task_type": "single_line", "source_file": "java/github/ls1intum/Artemis/src/main/java/de/tum/in/www1/artemis/service/scheduled/ScheduleService.java", "mask_start_position": 2769, "mask_end_position": 2799, "canonical_solution": "(exercise.getId(), lifecycle);", "pre_mask_code": "package de.tum.in.www1.artemis.service.scheduled;\n\nimport java.time.ZonedDateTime;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ScheduledFuture;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.enumeration.ExerciseLifecycle;\nimport de.tum.in.www1.artemis.service.ExerciseLifecycleService;\nimport de.tum.in.www1.artemis.service.util.Tuple;\n\n@Service\npublic class ScheduleService {\n\n private final Logger log = LoggerFactory.getLogger(ScheduleService.class);\n\n private final ExerciseLifecycleService exerciseLifecycleService;\n\n private final Map, Set>> scheduledTasks = new HashMap<>();\n\n public ScheduleService(ExerciseLifecycleService exerciseLifecycleService) {\n this.exerciseLifecycleService = exerciseLifecycleService;\n }\n\n private void addScheduledTask(Exercise exercise, ExerciseLifecycle lifecycle, Set> futures) {\n Tuple taskId = new Tuple<>(exercise.getId(), lifecycle);\n scheduledTasks.put(taskId, futures);\n }\n\n private void removeScheduledTask(Exercise exercise, ExerciseLifecycle lifecycle) {\n removeScheduledTask(exercise.getId(), lifecycle);\n }\n\n private void removeScheduledTask(Long exerciseId, ExerciseLifecycle lifecycle) {\n Tuple taskId = new Tuple<>(exerciseId, lifecycle);\n scheduledTasks.remove(taskId);\n }\n\n /**\n * Schedule a task for the given Exercise for the provided ExerciseLifecycle.\n *\n * @param exercise Exercise\n * @param lifecycle ExerciseLifecycle\n * @param task Runnable task to be executed on the lifecycle hook\n */\n void scheduleTask(Exercise exercise, ExerciseLifecycle lifecycle, Runnable task) {\n // no exercise should be scheduled more than once.\n cancelScheduledTaskForLifecycle(exercise.getId(), lifecycle);\n ScheduledFuture scheduledTask = exerciseLifecycleService.scheduleTask(exercise, lifecycle, task);\n addScheduledTask(exercise, lifecycle, Set.of(scheduledTask));\n }\n\n /**\n * Schedule a set of tasks for the given Exercise for the provided ExerciseLifecycle at the given times.\n *\n * @param exercise Exercise\n * @param lifecycle ExerciseLifecycle\n * @param tasks Runnable tasks to be executed at the associated ZonedDateTimes\n */\n void scheduleTask(Exercise exercise, ExerciseLifecycle lifecycle, Set> tasks) {\n // no exercise should be scheduled more than once.\n cancelScheduledTaskForLifecycle", "post_mask_code": "\n Set> scheduledTasks = exerciseLifecycleService.scheduleMultipleTasks(exercise, lifecycle, tasks);\n addScheduledTask(exercise, lifecycle, scheduledTasks);\n }\n\n /**\n * Cancel possible schedules tasks for a provided exercise.\n * @param exerciseId if of the exercise for which a potential scheduled task is canceled\n */\n void cancelScheduledTaskForLifecycle(Long exerciseId, ExerciseLifecycle lifecycle) {\n Tuple taskId = new Tuple<>(exerciseId, lifecycle);\n Set> futures = scheduledTasks.get(taskId);\n if (futures != null) {\n log.debug(\"Cancelling scheduled task {} for Exercise (#{}).\", lifecycle, exerciseId);\n futures.forEach(future -> future.cancel(false));\n removeScheduledTask(exerciseId, lifecycle);\n }\n }\n}\n"} {"task_id": "Java_2103", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/ls1intum/Artemis/src/main/java/de/tum/in/www1/artemis/service/scheduled/ScheduleService.java", "mask_start_position": 2560, "mask_end_position": 2993, "canonical_solution": "void scheduleTask(Exercise exercise, ExerciseLifecycle lifecycle, Set> tasks) {\n // no exercise should be scheduled more than once.\n cancelScheduledTaskForLifecycle(exercise.getId(), lifecycle);\n Set> scheduledTasks = exerciseLifecycleService.scheduleMultipleTasks(exercise, lifecycle, tasks);\n addScheduledTask(exercise, lifecycle, scheduledTasks);\n }", "pre_mask_code": "package de.tum.in.www1.artemis.service.scheduled;\n\nimport java.time.ZonedDateTime;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ScheduledFuture;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.enumeration.ExerciseLifecycle;\nimport de.tum.in.www1.artemis.service.ExerciseLifecycleService;\nimport de.tum.in.www1.artemis.service.util.Tuple;\n\n@Service\npublic class ScheduleService {\n\n private final Logger log = LoggerFactory.getLogger(ScheduleService.class);\n\n private final ExerciseLifecycleService exerciseLifecycleService;\n\n private final Map, Set>> scheduledTasks = new HashMap<>();\n\n public ScheduleService(ExerciseLifecycleService exerciseLifecycleService) {\n this.exerciseLifecycleService = exerciseLifecycleService;\n }\n\n private void addScheduledTask(Exercise exercise, ExerciseLifecycle lifecycle, Set> futures) {\n Tuple taskId = new Tuple<>(exercise.getId(), lifecycle);\n scheduledTasks.put(taskId, futures);\n }\n\n private void removeScheduledTask(Exercise exercise, ExerciseLifecycle lifecycle) {\n removeScheduledTask(exercise.getId(), lifecycle);\n }\n\n private void removeScheduledTask(Long exerciseId, ExerciseLifecycle lifecycle) {\n Tuple taskId = new Tuple<>(exerciseId, lifecycle);\n scheduledTasks.remove(taskId);\n }\n\n /**\n * Schedule a task for the given Exercise for the provided ExerciseLifecycle.\n *\n * @param exercise Exercise\n * @param lifecycle ExerciseLifecycle\n * @param task Runnable task to be executed on the lifecycle hook\n */\n void scheduleTask(Exercise exercise, ExerciseLifecycle lifecycle, Runnable task) {\n // no exercise should be scheduled more than once.\n cancelScheduledTaskForLifecycle(exercise.getId(), lifecycle);\n ScheduledFuture scheduledTask = exerciseLifecycleService.scheduleTask(exercise, lifecycle, task);\n addScheduledTask(exercise, lifecycle, Set.of(scheduledTask));\n }\n\n /**\n * Schedule a set of tasks for the given Exercise for the provided ExerciseLifecycle at the given times.\n *\n * @param exercise Exercise\n * @param lifecycle ExerciseLifecycle\n * @param tasks Runnable tasks to be executed at the associated ZonedDateTimes\n */\n ", "post_mask_code": "\n\n /**\n * Cancel possible schedules tasks for a provided exercise.\n * @param exerciseId if of the exercise for which a potential scheduled task is canceled\n */\n void cancelScheduledTaskForLifecycle(Long exerciseId, ExerciseLifecycle lifecycle) {\n Tuple taskId = new Tuple<>(exerciseId, lifecycle);\n Set> futures = scheduledTasks.get(taskId);\n if (futures != null) {\n log.debug(\"Cancelling scheduled task {} for Exercise (#{}).\", lifecycle, exerciseId);\n futures.forEach(future -> future.cancel(false));\n removeScheduledTask(exerciseId, lifecycle);\n }\n }\n}\n"} {"task_id": "Java_2104", "language": "Java", "task_type": "method_signature", "source_file": "java/github/zkoss/zkspreadsheet/zssmodel/src/org/zkoss/zss/model/impl/ColumnArrayImpl.java", "mask_start_position": 3739, "mask_end_position": 3784, "canonical_solution": "@Override\n public boolean isCustomWidth() ", "pre_mask_code": "/*\n\n{{IS_NOTE\n\tPurpose:\n\t\t\n\tDescription:\n\t\t\n\tHistory:\n\t\t2013/12/01 , Created by dennis\n}}IS_NOTE\n\n\n{{IS_RIGHT\n}}IS_RIGHT\n*/\npackage org.zkoss.zss.model.impl;\n\nimport org.zkoss.zss.model.SBook;\nimport org.zkoss.zss.model.SCellStyle;\nimport org.zkoss.zss.model.SColumn;\nimport org.zkoss.zss.model.SSheet;\nimport org.zkoss.zss.model.util.Validations;\n\n/**\n * @author dennis\n * @since 3.5.0\n */\npublic class ColumnArrayImpl extends AbstractColumnArrayAdv {\n\n private static final long serialVersionUID = 1L;\n\n private AbstractSheetAdv _sheet;\n\n private AbstractCellStyleAdv _cellStyle;\n\n private Integer _width;\n\n private boolean _hidden = false;\n\n private boolean _customWidth = false;\n\n int _index;\n\n int _lastIndex;\n\n public ColumnArrayImpl(AbstractSheetAdv sheet, int index, int lastIndex) {\n this._sheet = sheet;\n this._index = index;\n this._lastIndex = lastIndex;\n }\n\n @Override\n public int getIndex() {\n checkOrphan();\n return _index;\n }\n\n @Override\n public void checkOrphan() {\n if (_sheet == null) {\n throw new IllegalStateException(\"doesn't connect to parent\");\n }\n }\n\n @Override\n public void destroy() {\n checkOrphan();\n _sheet = null;\n }\n\n @Override\n public SSheet getSheet() {\n checkOrphan();\n return _sheet;\n }\n\n @Override\n public SCellStyle getCellStyle() {\n return getCellStyle(false);\n }\n\n @Override\n public SCellStyle getCellStyle(boolean local) {\n if (local || _cellStyle != null) {\n return _cellStyle;\n }\n checkOrphan();\n return _sheet.getBook().getDefaultCellStyle();\n }\n\n @Override\n public void setCellStyle(SCellStyle cellStyle) {\n Validations.argInstance(cellStyle, AbstractCellStyleAdv.class);\n this._cellStyle = (AbstractCellStyleAdv) cellStyle;\n }\n\n @Override\n public int getWidth() {\n if (_width != null) {\n return _width.intValue();\n }\n checkOrphan();\n return getSheet().getDefaultColumnWidth();\n }\n\n @Override\n public boolean isHidden() {\n return _hidden;\n }\n\n @Override\n public void setWidth(int width) {\n this._width = Integer.valueOf(width);\n }\n\n @Override\n public void setHidden(boolean hidden) {\n if (this._hidden == hidden)\n return;\n this._hidden = hidden;\n // ZSS-988: Subtotal(1xx, range) depends on hidden/unhidden rows/columns\n final SBook book = _sheet.getBook();\n final int row1 = _sheet.getStartRowIndex();\n final int row2 = _sheet.getEndRowIndex();\n final int col1 = getIndex();\n final int col2 = getLastIndex();\n if (row1 >= 0 && row2 >= 0 && col1 >= 0 && col2 >= 0) {\n // ZSS-1047: (side-effect of ZSS-988 and ZSS-1007 which consider setHidden() of SUBTOTAL() function)\n final boolean includePrecedent = false;\n if (!((AbstractBookAdv) book).isPostProcessing()) {\n ModelUpdateUtil.handlePrecedentUpdate(book.getBookSeries(), new RefImpl(book.getBookName(), _sheet.getSheetName(), row1, col1, row2, col2), includePrecedent);\n }\n }\n }\n\n @Override\n public int getLastIndex() {\n return _lastIndex;\n }\n\n @Override\n void setIndex(int index) {\n this._index = index;\n }\n\n @Override\n void setLastIndex(int lastIndex) {\n this._lastIndex = lastIndex;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(super.toString()).append(\"[\").append(getIndex()).append(\"-\").append(getLastIndex()).append(\"]\");\n return sb.toString();\n }\n\n ", "post_mask_code": "{\n return _customWidth || (_width != null && _width != getSheet().getDefaultColumnWidth());\n }\n\n @Override\n public void setCustomWidth(boolean custom) {\n _customWidth = custom;\n }\n\n ColumnArrayImpl cloneColumnArrayImpl(AbstractSheetAdv sheet) {\n return cloneColumnArray(sheet, null);\n }\n\n // ZSS-1132: should skip this Column array in exporting\n public boolean shouldSkip() {\n return !isCustomWidth() && _cellStyle == null && !_hidden;\n }\n\n ColumnArrayImpl cloneColumnArray(AbstractSheetAdv sheet, SBook book) {\n final ColumnArrayImpl tgt = new ColumnArrayImpl(sheet, this._index, this._lastIndex);\n tgt._width = this._width;\n tgt._hidden = this._hidden;\n tgt._customWidth = this._customWidth;\n tgt._cellStyle = (AbstractCellStyleAdv) (this._cellStyle == null ? null : this._cellStyle.cloneCellStyle(book));\n return tgt;\n }\n}\n"} {"task_id": "Java_2105", "language": "Java", "task_type": "method_body", "source_file": "java/github/zkoss/zkspreadsheet/zssmodel/src/org/zkoss/zss/model/impl/ColumnArrayImpl.java", "mask_start_position": 961, "mask_end_position": 1014, "canonical_solution": "{\n checkOrphan();\n return _index;\n }", "pre_mask_code": "/*\n\n{{IS_NOTE\n\tPurpose:\n\t\t\n\tDescription:\n\t\t\n\tHistory:\n\t\t2013/12/01 , Created by dennis\n}}IS_NOTE\n\n\n{{IS_RIGHT\n}}IS_RIGHT\n*/\npackage org.zkoss.zss.model.impl;\n\nimport org.zkoss.zss.model.SBook;\nimport org.zkoss.zss.model.SCellStyle;\nimport org.zkoss.zss.model.SColumn;\nimport org.zkoss.zss.model.SSheet;\nimport org.zkoss.zss.model.util.Validations;\n\n/**\n * @author dennis\n * @since 3.5.0\n */\npublic class ColumnArrayImpl extends AbstractColumnArrayAdv {\n\n private static final long serialVersionUID = 1L;\n\n private AbstractSheetAdv _sheet;\n\n private AbstractCellStyleAdv _cellStyle;\n\n private Integer _width;\n\n private boolean _hidden = false;\n\n private boolean _customWidth = false;\n\n int _index;\n\n int _lastIndex;\n\n public ColumnArrayImpl(AbstractSheetAdv sheet, int index, int lastIndex) {\n this._sheet = sheet;\n this._index = index;\n this._lastIndex = lastIndex;\n }\n\n @Override\n public int getIndex() ", "post_mask_code": "\n\n @Override\n public void checkOrphan() {\n if (_sheet == null) {\n throw new IllegalStateException(\"doesn't connect to parent\");\n }\n }\n\n @Override\n public void destroy() {\n checkOrphan();\n _sheet = null;\n }\n\n @Override\n public SSheet getSheet() {\n checkOrphan();\n return _sheet;\n }\n\n @Override\n public SCellStyle getCellStyle() {\n return getCellStyle(false);\n }\n\n @Override\n public SCellStyle getCellStyle(boolean local) {\n if (local || _cellStyle != null) {\n return _cellStyle;\n }\n checkOrphan();\n return _sheet.getBook().getDefaultCellStyle();\n }\n\n @Override\n public void setCellStyle(SCellStyle cellStyle) {\n Validations.argInstance(cellStyle, AbstractCellStyleAdv.class);\n this._cellStyle = (AbstractCellStyleAdv) cellStyle;\n }\n\n @Override\n public int getWidth() {\n if (_width != null) {\n return _width.intValue();\n }\n checkOrphan();\n return getSheet().getDefaultColumnWidth();\n }\n\n @Override\n public boolean isHidden() {\n return _hidden;\n }\n\n @Override\n public void setWidth(int width) {\n this._width = Integer.valueOf(width);\n }\n\n @Override\n public void setHidden(boolean hidden) {\n if (this._hidden == hidden)\n return;\n this._hidden = hidden;\n // ZSS-988: Subtotal(1xx, range) depends on hidden/unhidden rows/columns\n final SBook book = _sheet.getBook();\n final int row1 = _sheet.getStartRowIndex();\n final int row2 = _sheet.getEndRowIndex();\n final int col1 = getIndex();\n final int col2 = getLastIndex();\n if (row1 >= 0 && row2 >= 0 && col1 >= 0 && col2 >= 0) {\n // ZSS-1047: (side-effect of ZSS-988 and ZSS-1007 which consider setHidden() of SUBTOTAL() function)\n final boolean includePrecedent = false;\n if (!((AbstractBookAdv) book).isPostProcessing()) {\n ModelUpdateUtil.handlePrecedentUpdate(book.getBookSeries(), new RefImpl(book.getBookName(), _sheet.getSheetName(), row1, col1, row2, col2), includePrecedent);\n }\n }\n }\n\n @Override\n public int getLastIndex() {\n return _lastIndex;\n }\n\n @Override\n void setIndex(int index) {\n this._index = index;\n }\n\n @Override\n void setLastIndex(int lastIndex) {\n this._lastIndex = lastIndex;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(super.toString()).append(\"[\").append(getIndex()).append(\"-\").append(getLastIndex()).append(\"]\");\n return sb.toString();\n }\n\n @Override\n public boolean isCustomWidth() {\n return _customWidth || (_width != null && _width != getSheet().getDefaultColumnWidth());\n }\n\n @Override\n public void setCustomWidth(boolean custom) {\n _customWidth = custom;\n }\n\n ColumnArrayImpl cloneColumnArrayImpl(AbstractSheetAdv sheet) {\n return cloneColumnArray(sheet, null);\n }\n\n // ZSS-1132: should skip this Column array in exporting\n public boolean shouldSkip() {\n return !isCustomWidth() && _cellStyle == null && !_hidden;\n }\n\n ColumnArrayImpl cloneColumnArray(AbstractSheetAdv sheet, SBook book) {\n final ColumnArrayImpl tgt = new ColumnArrayImpl(sheet, this._index, this._lastIndex);\n tgt._width = this._width;\n tgt._hidden = this._hidden;\n tgt._customWidth = this._customWidth;\n tgt._cellStyle = (AbstractCellStyleAdv) (this._cellStyle == null ? null : this._cellStyle.cloneCellStyle(book));\n return tgt;\n }\n}\n"} {"task_id": "Java_2106", "language": "Java", "task_type": "single_line", "source_file": "java/github/zkoss/zkspreadsheet/zssmodel/src/org/zkoss/zss/model/impl/ColumnArrayImpl.java", "mask_start_position": 1654, "mask_end_position": 1699, "canonical_solution": "eturn _sheet.getBook().getDefaultCellStyle();", "pre_mask_code": "/*\n\n{{IS_NOTE\n\tPurpose:\n\t\t\n\tDescription:\n\t\t\n\tHistory:\n\t\t2013/12/01 , Created by dennis\n}}IS_NOTE\n\n\n{{IS_RIGHT\n}}IS_RIGHT\n*/\npackage org.zkoss.zss.model.impl;\n\nimport org.zkoss.zss.model.SBook;\nimport org.zkoss.zss.model.SCellStyle;\nimport org.zkoss.zss.model.SColumn;\nimport org.zkoss.zss.model.SSheet;\nimport org.zkoss.zss.model.util.Validations;\n\n/**\n * @author dennis\n * @since 3.5.0\n */\npublic class ColumnArrayImpl extends AbstractColumnArrayAdv {\n\n private static final long serialVersionUID = 1L;\n\n private AbstractSheetAdv _sheet;\n\n private AbstractCellStyleAdv _cellStyle;\n\n private Integer _width;\n\n private boolean _hidden = false;\n\n private boolean _customWidth = false;\n\n int _index;\n\n int _lastIndex;\n\n public ColumnArrayImpl(AbstractSheetAdv sheet, int index, int lastIndex) {\n this._sheet = sheet;\n this._index = index;\n this._lastIndex = lastIndex;\n }\n\n @Override\n public int getIndex() {\n checkOrphan();\n return _index;\n }\n\n @Override\n public void checkOrphan() {\n if (_sheet == null) {\n throw new IllegalStateException(\"doesn't connect to parent\");\n }\n }\n\n @Override\n public void destroy() {\n checkOrphan();\n _sheet = null;\n }\n\n @Override\n public SSheet getSheet() {\n checkOrphan();\n return _sheet;\n }\n\n @Override\n public SCellStyle getCellStyle() {\n return getCellStyle(false);\n }\n\n @Override\n public SCellStyle getCellStyle(boolean local) {\n if (local || _cellStyle != null) {\n return _cellStyle;\n }\n checkOrphan();\n r", "post_mask_code": "\n }\n\n @Override\n public void setCellStyle(SCellStyle cellStyle) {\n Validations.argInstance(cellStyle, AbstractCellStyleAdv.class);\n this._cellStyle = (AbstractCellStyleAdv) cellStyle;\n }\n\n @Override\n public int getWidth() {\n if (_width != null) {\n return _width.intValue();\n }\n checkOrphan();\n return getSheet().getDefaultColumnWidth();\n }\n\n @Override\n public boolean isHidden() {\n return _hidden;\n }\n\n @Override\n public void setWidth(int width) {\n this._width = Integer.valueOf(width);\n }\n\n @Override\n public void setHidden(boolean hidden) {\n if (this._hidden == hidden)\n return;\n this._hidden = hidden;\n // ZSS-988: Subtotal(1xx, range) depends on hidden/unhidden rows/columns\n final SBook book = _sheet.getBook();\n final int row1 = _sheet.getStartRowIndex();\n final int row2 = _sheet.getEndRowIndex();\n final int col1 = getIndex();\n final int col2 = getLastIndex();\n if (row1 >= 0 && row2 >= 0 && col1 >= 0 && col2 >= 0) {\n // ZSS-1047: (side-effect of ZSS-988 and ZSS-1007 which consider setHidden() of SUBTOTAL() function)\n final boolean includePrecedent = false;\n if (!((AbstractBookAdv) book).isPostProcessing()) {\n ModelUpdateUtil.handlePrecedentUpdate(book.getBookSeries(), new RefImpl(book.getBookName(), _sheet.getSheetName(), row1, col1, row2, col2), includePrecedent);\n }\n }\n }\n\n @Override\n public int getLastIndex() {\n return _lastIndex;\n }\n\n @Override\n void setIndex(int index) {\n this._index = index;\n }\n\n @Override\n void setLastIndex(int lastIndex) {\n this._lastIndex = lastIndex;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(super.toString()).append(\"[\").append(getIndex()).append(\"-\").append(getLastIndex()).append(\"]\");\n return sb.toString();\n }\n\n @Override\n public boolean isCustomWidth() {\n return _customWidth || (_width != null && _width != getSheet().getDefaultColumnWidth());\n }\n\n @Override\n public void setCustomWidth(boolean custom) {\n _customWidth = custom;\n }\n\n ColumnArrayImpl cloneColumnArrayImpl(AbstractSheetAdv sheet) {\n return cloneColumnArray(sheet, null);\n }\n\n // ZSS-1132: should skip this Column array in exporting\n public boolean shouldSkip() {\n return !isCustomWidth() && _cellStyle == null && !_hidden;\n }\n\n ColumnArrayImpl cloneColumnArray(AbstractSheetAdv sheet, SBook book) {\n final ColumnArrayImpl tgt = new ColumnArrayImpl(sheet, this._index, this._lastIndex);\n tgt._width = this._width;\n tgt._hidden = this._hidden;\n tgt._customWidth = this._customWidth;\n tgt._cellStyle = (AbstractCellStyleAdv) (this._cellStyle == null ? null : this._cellStyle.cloneCellStyle(book));\n return tgt;\n }\n}\n"} {"task_id": "Java_2107", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openrocket/openrocket/swing/src/net/sf/openrocket/gui/plot/PlotConfiguration.java", "mask_start_position": 12259, "mask_end_position": 12301, "canonical_solution": "public void removePlotDataType(int index) ", "pre_mask_code": "package net.sf.openrocket.gui.plot;\n\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Set;\nimport net.sf.openrocket.l10n.Translator;\nimport net.sf.openrocket.simulation.FlightDataBranch;\nimport net.sf.openrocket.simulation.FlightDataType;\nimport net.sf.openrocket.simulation.FlightEvent;\nimport net.sf.openrocket.startup.Application;\nimport net.sf.openrocket.unit.Unit;\nimport net.sf.openrocket.util.ArrayList;\nimport net.sf.openrocket.util.BugException;\nimport net.sf.openrocket.util.MathUtil;\nimport net.sf.openrocket.util.Pair;\n\npublic class PlotConfiguration implements Cloneable {\n\n private static final Translator trans = Application.getTranslator();\n\n public static final PlotConfiguration[] DEFAULT_CONFIGURATIONS;\n\n static {\n ArrayList configs = new ArrayList();\n PlotConfiguration config;\n // // Vertical motion vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Verticalmotion\"));\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0);\n config.addPlotDataType(FlightDataType.TYPE_VELOCITY_Z);\n config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_Z);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Total motion vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Totalmotion\"));\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0);\n config.addPlotDataType(FlightDataType.TYPE_VELOCITY_TOTAL);\n config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_TOTAL);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Flight side profile\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Flightside\"), FlightDataType.TYPE_POSITION_X);\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Groundtrack\"), FlightDataType.TYPE_POSITION_X);\n config.addPlotDataType(FlightDataType.TYPE_POSITION_Y, 0);\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Stability\"));\n config.addPlotDataType(FlightDataType.TYPE_STABILITY, 0);\n config.addPlotDataType(FlightDataType.TYPE_CP_LOCATION, 1);\n config.addPlotDataType(FlightDataType.TYPE_CG_LOCATION, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Drag coefficients vs. Mach number\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Dragcoef\"), FlightDataType.TYPE_MACH_NUMBER);\n config.addPlotDataType(FlightDataType.TYPE_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_FRICTION_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_BASE_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_PRESSURE_DRAG_COEFF, 0);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Rollcharacteristics\"));\n config.addPlotDataType(FlightDataType.TYPE_ROLL_RATE, 0);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_MOMENT_COEFF, 1);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_FORCING_COEFF, 1);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_DAMPING_COEFF, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.LAUNCHROD, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Angle of attack and orientation vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Angleofattack\"));\n config.addPlotDataType(FlightDataType.TYPE_AOA, 0);\n config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_PHI);\n config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_THETA);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Simulation time step and computation time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Simulationtime\"));\n config.addPlotDataType(FlightDataType.TYPE_TIME_STEP);\n config.addPlotDataType(FlightDataType.TYPE_COMPUTATION_TIME);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n DEFAULT_CONFIGURATIONS = configs.toArray(new PlotConfiguration[0]);\n }\n\n /**\n * Bonus given for the first type being on the first axis\n */\n private static final double BONUS_FIRST_TYPE_ON_FIRST_AXIS = 1.0;\n\n /**\n * Bonus given if the first axis includes zero (to prefer first axis having zero over\n * the others)\n */\n private static final double BONUS_FIRST_AXIS_HAS_ZERO = 2.0;\n\n /**\n * Bonus given for a common zero point on left and right axes.\n */\n private static final double BONUS_COMMON_ZERO = 40.0;\n\n /**\n * Bonus given for only using a single axis.\n */\n private static final double BONUS_ONLY_ONE_AXIS = 50.0;\n\n // 30% of total range\n private static final double INCLUDE_ZERO_DISTANCE = 0.3;\n\n /**\n * The data types to be plotted.\n */\n private ArrayList plotDataTypes = new ArrayList();\n\n private ArrayList plotDataUnits = new ArrayList();\n\n /**\n * The corresponding Axis on which they will be plotted, or null to auto-select.\n */\n private ArrayList plotDataAxes = new ArrayList();\n\n private EnumSet events = EnumSet.noneOf(FlightEvent.Type.class);\n\n private FlightDataType domainAxisType = null;\n\n private Unit domainAxisUnit = null;\n\n /**\n * All available axes.\n */\n private final int axesCount;\n\n private ArrayList allAxes = new ArrayList();\n\n private String name = null;\n\n public PlotConfiguration() {\n this(null, FlightDataType.TYPE_TIME);\n }\n\n public PlotConfiguration(String name) {\n this(name, FlightDataType.TYPE_TIME);\n }\n\n public PlotConfiguration(String name, FlightDataType domainType) {\n this.name = name;\n // Two axes\n allAxes.add(new Axis());\n allAxes.add(new Axis());\n axesCount = 2;\n setDomainAxisType(domainType);\n }\n\n public FlightDataType getDomainAxisType() {\n return domainAxisType;\n }\n\n public void setDomainAxisType(FlightDataType type) {\n boolean setUnit;\n if (domainAxisType != null && domainAxisType.getUnitGroup() == type.getUnitGroup())\n setUnit = false;\n else\n setUnit = true;\n domainAxisType = type;\n if (setUnit)\n domainAxisUnit = domainAxisType.getUnitGroup().getDefaultUnit();\n }\n\n public Unit getDomainAxisUnit() {\n return domainAxisUnit;\n }\n\n public void setDomainAxisUnit(Unit u) {\n if (!domainAxisType.getUnitGroup().contains(u)) {\n throw new IllegalArgumentException(\"Setting unit \" + u + \" to type \" + domainAxisType);\n }\n domainAxisUnit = u;\n }\n\n public void addPlotDataType(FlightDataType type) {\n plotDataTypes.add(type);\n plotDataUnits.add(type.getUnitGroup().getDefaultUnit());\n plotDataAxes.add(-1);\n }\n\n public void addPlotDataType(FlightDataType type, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataTypes.add(type);\n plotDataUnits.add(type.getUnitGroup().getDefaultUnit());\n plotDataAxes.add(axis);\n }\n\n public void setPlotDataType(int index, FlightDataType type) {\n FlightDataType origType = plotDataTypes.get(index);\n plotDataTypes.set(index, type);\n if (origType.getUnitGroup() != type.getUnitGroup()) {\n plotDataUnits.set(index, type.getUnitGroup().getDefaultUnit());\n }\n }\n\n public void setPlotDataUnit(int index, Unit unit) {\n if (!plotDataTypes.get(index).getUnitGroup().contains(unit)) {\n throw new IllegalArgumentException(\"Attempting to set unit \" + unit + \" to group \" + plotDataTypes.get(index).getUnitGroup());\n }\n plotDataUnits.set(index, unit);\n }\n\n public void setPlotDataAxis(int index, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataAxes.set(index, axis);\n }\n\n public void setPlotDataType(int index, FlightDataType type, Unit unit, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataTypes.set(index, type);\n plotDataUnits.set(index, unit);\n plotDataAxes.set(index, axis);\n }\n\n ", "post_mask_code": "{\n plotDataTypes.remove(index);\n plotDataUnits.remove(index);\n plotDataAxes.remove(index);\n }\n\n public FlightDataType getType(int index) {\n return plotDataTypes.get(index);\n }\n\n public Unit getUnit(int index) {\n return plotDataUnits.get(index);\n }\n\n public int getAxis(int index) {\n return plotDataAxes.get(index);\n }\n\n public int getTypeCount() {\n return plotDataTypes.size();\n }\n\n public Set getActiveEvents() {\n return events.clone();\n }\n\n public void setEvent(FlightEvent.Type type, boolean active) {\n if (active) {\n events.add(type);\n } else {\n events.remove(type);\n }\n }\n\n public boolean isEventActive(FlightEvent.Type type) {\n return events.contains(type);\n }\n\n public List getAllAxes() {\n List list = new ArrayList();\n list.addAll(allAxes);\n return list;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * Returns the name of this PlotConfiguration.\n */\n @Override\n public String toString() {\n return name;\n }\n\n /**\n * Find the best combination of the auto-selectable axes.\n *\n * @return\ta new PlotConfiguration with the best fitting auto-selected axes and\n * \t\t\taxes ranges selected.\n */\n public PlotConfiguration fillAutoAxes(FlightDataBranch data) {\n PlotConfiguration config = recursiveFillAutoAxes(data).getU();\n config.fitAxes(data);\n return config;\n }\n\n /**\n * Recursively search for the best combination of the auto-selectable axes.\n * This is a brute-force search method.\n *\n * @return\ta new PlotConfiguration with the best fitting auto-selected axes and\n * \t\t\taxes ranges selected, and the goodness value\n */\n private Pair recursiveFillAutoAxes(FlightDataBranch data) {\n // Create copy to fill in\n PlotConfiguration copy = this.clone();\n int autoindex;\n for (autoindex = 0; autoindex < plotDataAxes.size(); autoindex++) {\n if (plotDataAxes.get(autoindex) < 0)\n break;\n }\n if (autoindex >= plotDataAxes.size()) {\n // All axes have been assigned, just return since we are already the best\n return new Pair(copy, copy.getGoodnessValue(data));\n }\n // Set the auto-selected index one at a time and choose the best one\n PlotConfiguration best = null;\n double bestValue = Double.NEGATIVE_INFINITY;\n for (int i = 0; i < axesCount; i++) {\n copy.plotDataAxes.set(autoindex, i);\n Pair result = copy.recursiveFillAutoAxes(data);\n if (result.getV() > bestValue) {\n best = result.getU();\n bestValue = result.getV();\n }\n }\n return new Pair(best, bestValue);\n }\n\n /**\n * Fit the axes to hold the provided data. All of the plotDataAxis elements must\n * be non-negative.\n *

\n * NOTE: This method assumes that only two axes are used.\n */\n protected void fitAxes(FlightDataBranch data) {\n // Reset axes\n for (Axis a : allAxes) {\n a.reset();\n }\n // Add full range to the axes\n int length = plotDataTypes.size();\n for (int i = 0; i < length; i++) {\n FlightDataType type = plotDataTypes.get(i);\n Unit unit = plotDataUnits.get(i);\n int index = plotDataAxes.get(i);\n if (index < 0) {\n throw new IllegalStateException(\"fitAxes called with auto-selected axis\");\n }\n Axis axis = allAxes.get(index);\n double min = unit.toUnit(data.getMinimum(type));\n double max = unit.toUnit(data.getMaximum(type));\n axis.addBound(min);\n axis.addBound(max);\n }\n // Ensure non-zero (or NaN) range, add a few percent range, include zero if it is close\n for (Axis a : allAxes) {\n if (MathUtil.equals(a.getMinValue(), a.getMaxValue())) {\n a.addBound(a.getMinValue() - 1);\n a.addBound(a.getMaxValue() + 1);\n }\n double addition = a.getRangeLength() * 0.03;\n a.addBound(a.getMinValue() - addition);\n a.addBound(a.getMaxValue() + addition);\n double dist;\n dist = Math.min(Math.abs(a.getMinValue()), Math.abs(a.getMaxValue()));\n if (dist <= a.getRangeLength() * INCLUDE_ZERO_DISTANCE) {\n a.addBound(0);\n }\n }\n // Check whether to use a common zero\n Axis left = allAxes.get(0);\n Axis right = allAxes.get(1);\n if (left.getMinValue() > 0 || left.getMaxValue() < 0 || right.getMinValue() > 0 || right.getMaxValue() < 0 || Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue()))\n return;\n // // Compute common zero\n // TODO: MEDIUM: This algorithm may require tweaking\n double min1 = left.getMinValue();\n double max1 = left.getMaxValue();\n double min2 = right.getMinValue();\n double max2 = right.getMaxValue();\n // Calculate and round scaling factor\n double scale = Math.max(left.getRangeLength(), right.getRangeLength()) / Math.min(left.getRangeLength(), right.getRangeLength());\n scale = roundScale(scale);\n if (right.getRangeLength() > left.getRangeLength()) {\n scale = 1 / scale;\n }\n // Scale right axis, enlarge axes if necessary and scale back\n min2 *= scale;\n max2 *= scale;\n min1 = Math.min(min1, min2);\n min2 = min1;\n max1 = Math.max(max1, max2);\n max2 = max1;\n min2 /= scale;\n max2 /= scale;\n // Apply scale\n left.addBound(min1);\n left.addBound(max1);\n right.addBound(min2);\n right.addBound(max2);\n }\n\n private double roundScale(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 7.5) {\n scale = 10;\n } else if (scale > 4.5) {\n scale = 5;\n } else if (scale > 3) {\n scale = 4;\n } else if (scale > 1.5) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n @SuppressWarnings(\"unused\")\n private double roundScaleUp(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 5) {\n scale = 10;\n } else if (scale > 4) {\n scale = 5;\n } else if (scale > 2) {\n scale = 4;\n } else if (scale > 1) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n @SuppressWarnings(\"unused\")\n private double roundScaleDown(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 5) {\n scale = 5;\n } else if (scale > 4) {\n scale = 4;\n } else if (scale > 2) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n /**\n * Fits the axis ranges to the data and returns the \"goodness value\" of this\n * selection of axes. All plotDataAxis elements must be non-null.\n *

\n * NOTE: This method assumes that all data can fit into the axes ranges and\n * that only two axes are used.\n *\n * @return\ta \"goodness value\", the larger the better.\n */\n protected double getGoodnessValue(FlightDataBranch data) {\n double goodness = 0;\n int length = plotDataTypes.size();\n // Fit the axes ranges to the data\n fitAxes(data);\n /*\n\t\t * Calculate goodness of ranges. 100 points is given if the values fill the\n\t\t * entire range, 0 if they fill none of it.\n\t\t */\n for (int i = 0; i < length; i++) {\n FlightDataType type = plotDataTypes.get(i);\n Unit unit = plotDataUnits.get(i);\n int index = plotDataAxes.get(i);\n if (index < 0) {\n throw new IllegalStateException(\"getGoodnessValue called with auto-selected axis\");\n }\n Axis axis = allAxes.get(index);\n double min = unit.toUnit(data.getMinimum(type));\n double max = unit.toUnit(data.getMaximum(type));\n if (Double.isNaN(min) || Double.isNaN(max))\n continue;\n if (MathUtil.equals(min, max))\n continue;\n double d = (max - min) / axis.getRangeLength();\n // Prioritize small ranges\n d = MathUtil.safeSqrt(d);\n goodness += d * 100.0;\n }\n /*\n\t\t * Add extra points for specific things.\n\t\t */\n // A little for the first type being on the first axis\n if (plotDataAxes.get(0) == 0)\n goodness += BONUS_FIRST_TYPE_ON_FIRST_AXIS;\n // A little bonus if the first axis contains zero\n Axis left = allAxes.get(0);\n if (left.getMinValue() <= 0 && left.getMaxValue() >= 0)\n goodness += BONUS_FIRST_AXIS_HAS_ZERO;\n // A boost if a common zero was used in the ranging\n Axis right = allAxes.get(1);\n if (left.getMinValue() <= 0 && left.getMaxValue() >= 0 && right.getMinValue() <= 0 && right.getMaxValue() >= 0)\n goodness += BONUS_COMMON_ZERO;\n // A boost if only one axis is used\n if (Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue()))\n goodness += BONUS_ONLY_ONE_AXIS;\n return goodness;\n }\n\n /**\n * Reset the units of this configuration to the default units. Returns this\n * PlotConfiguration.\n *\n * @return this PlotConfiguration.\n */\n public PlotConfiguration resetUnits() {\n for (int i = 0; i < plotDataTypes.size(); i++) {\n plotDataUnits.set(i, plotDataTypes.get(i).getUnitGroup().getDefaultUnit());\n }\n return this;\n }\n\n @Override\n public PlotConfiguration clone() {\n try {\n PlotConfiguration copy = (PlotConfiguration) super.clone();\n // Shallow-clone all immutable lists\n copy.plotDataTypes = this.plotDataTypes.clone();\n copy.plotDataAxes = this.plotDataAxes.clone();\n copy.plotDataUnits = this.plotDataUnits.clone();\n copy.events = this.events.clone();\n // Deep-clone all Axis since they are mutable\n copy.allAxes = new ArrayList();\n for (Axis a : this.allAxes) {\n copy.allAxes.add(a.clone());\n }\n return copy;\n } catch (CloneNotSupportedException e) {\n throw new BugException(\"BUG! Could not clone().\");\n }\n }\n}\n"} {"task_id": "Java_2108", "language": "Java", "task_type": "method_body", "source_file": "java/github/openrocket/openrocket/swing/src/net/sf/openrocket/gui/plot/PlotConfiguration.java", "mask_start_position": 9817, "mask_end_position": 9855, "canonical_solution": "{\n return domainAxisType;\n }", "pre_mask_code": "package net.sf.openrocket.gui.plot;\n\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Set;\nimport net.sf.openrocket.l10n.Translator;\nimport net.sf.openrocket.simulation.FlightDataBranch;\nimport net.sf.openrocket.simulation.FlightDataType;\nimport net.sf.openrocket.simulation.FlightEvent;\nimport net.sf.openrocket.startup.Application;\nimport net.sf.openrocket.unit.Unit;\nimport net.sf.openrocket.util.ArrayList;\nimport net.sf.openrocket.util.BugException;\nimport net.sf.openrocket.util.MathUtil;\nimport net.sf.openrocket.util.Pair;\n\npublic class PlotConfiguration implements Cloneable {\n\n private static final Translator trans = Application.getTranslator();\n\n public static final PlotConfiguration[] DEFAULT_CONFIGURATIONS;\n\n static {\n ArrayList configs = new ArrayList();\n PlotConfiguration config;\n // // Vertical motion vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Verticalmotion\"));\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0);\n config.addPlotDataType(FlightDataType.TYPE_VELOCITY_Z);\n config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_Z);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Total motion vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Totalmotion\"));\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0);\n config.addPlotDataType(FlightDataType.TYPE_VELOCITY_TOTAL);\n config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_TOTAL);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Flight side profile\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Flightside\"), FlightDataType.TYPE_POSITION_X);\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Groundtrack\"), FlightDataType.TYPE_POSITION_X);\n config.addPlotDataType(FlightDataType.TYPE_POSITION_Y, 0);\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Stability\"));\n config.addPlotDataType(FlightDataType.TYPE_STABILITY, 0);\n config.addPlotDataType(FlightDataType.TYPE_CP_LOCATION, 1);\n config.addPlotDataType(FlightDataType.TYPE_CG_LOCATION, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Drag coefficients vs. Mach number\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Dragcoef\"), FlightDataType.TYPE_MACH_NUMBER);\n config.addPlotDataType(FlightDataType.TYPE_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_FRICTION_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_BASE_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_PRESSURE_DRAG_COEFF, 0);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Rollcharacteristics\"));\n config.addPlotDataType(FlightDataType.TYPE_ROLL_RATE, 0);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_MOMENT_COEFF, 1);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_FORCING_COEFF, 1);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_DAMPING_COEFF, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.LAUNCHROD, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Angle of attack and orientation vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Angleofattack\"));\n config.addPlotDataType(FlightDataType.TYPE_AOA, 0);\n config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_PHI);\n config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_THETA);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Simulation time step and computation time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Simulationtime\"));\n config.addPlotDataType(FlightDataType.TYPE_TIME_STEP);\n config.addPlotDataType(FlightDataType.TYPE_COMPUTATION_TIME);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n DEFAULT_CONFIGURATIONS = configs.toArray(new PlotConfiguration[0]);\n }\n\n /**\n * Bonus given for the first type being on the first axis\n */\n private static final double BONUS_FIRST_TYPE_ON_FIRST_AXIS = 1.0;\n\n /**\n * Bonus given if the first axis includes zero (to prefer first axis having zero over\n * the others)\n */\n private static final double BONUS_FIRST_AXIS_HAS_ZERO = 2.0;\n\n /**\n * Bonus given for a common zero point on left and right axes.\n */\n private static final double BONUS_COMMON_ZERO = 40.0;\n\n /**\n * Bonus given for only using a single axis.\n */\n private static final double BONUS_ONLY_ONE_AXIS = 50.0;\n\n // 30% of total range\n private static final double INCLUDE_ZERO_DISTANCE = 0.3;\n\n /**\n * The data types to be plotted.\n */\n private ArrayList plotDataTypes = new ArrayList();\n\n private ArrayList plotDataUnits = new ArrayList();\n\n /**\n * The corresponding Axis on which they will be plotted, or null to auto-select.\n */\n private ArrayList plotDataAxes = new ArrayList();\n\n private EnumSet events = EnumSet.noneOf(FlightEvent.Type.class);\n\n private FlightDataType domainAxisType = null;\n\n private Unit domainAxisUnit = null;\n\n /**\n * All available axes.\n */\n private final int axesCount;\n\n private ArrayList allAxes = new ArrayList();\n\n private String name = null;\n\n public PlotConfiguration() {\n this(null, FlightDataType.TYPE_TIME);\n }\n\n public PlotConfiguration(String name) {\n this(name, FlightDataType.TYPE_TIME);\n }\n\n public PlotConfiguration(String name, FlightDataType domainType) {\n this.name = name;\n // Two axes\n allAxes.add(new Axis());\n allAxes.add(new Axis());\n axesCount = 2;\n setDomainAxisType(domainType);\n }\n\n public FlightDataType getDomainAxisType() ", "post_mask_code": "\n\n public void setDomainAxisType(FlightDataType type) {\n boolean setUnit;\n if (domainAxisType != null && domainAxisType.getUnitGroup() == type.getUnitGroup())\n setUnit = false;\n else\n setUnit = true;\n domainAxisType = type;\n if (setUnit)\n domainAxisUnit = domainAxisType.getUnitGroup().getDefaultUnit();\n }\n\n public Unit getDomainAxisUnit() {\n return domainAxisUnit;\n }\n\n public void setDomainAxisUnit(Unit u) {\n if (!domainAxisType.getUnitGroup().contains(u)) {\n throw new IllegalArgumentException(\"Setting unit \" + u + \" to type \" + domainAxisType);\n }\n domainAxisUnit = u;\n }\n\n public void addPlotDataType(FlightDataType type) {\n plotDataTypes.add(type);\n plotDataUnits.add(type.getUnitGroup().getDefaultUnit());\n plotDataAxes.add(-1);\n }\n\n public void addPlotDataType(FlightDataType type, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataTypes.add(type);\n plotDataUnits.add(type.getUnitGroup().getDefaultUnit());\n plotDataAxes.add(axis);\n }\n\n public void setPlotDataType(int index, FlightDataType type) {\n FlightDataType origType = plotDataTypes.get(index);\n plotDataTypes.set(index, type);\n if (origType.getUnitGroup() != type.getUnitGroup()) {\n plotDataUnits.set(index, type.getUnitGroup().getDefaultUnit());\n }\n }\n\n public void setPlotDataUnit(int index, Unit unit) {\n if (!plotDataTypes.get(index).getUnitGroup().contains(unit)) {\n throw new IllegalArgumentException(\"Attempting to set unit \" + unit + \" to group \" + plotDataTypes.get(index).getUnitGroup());\n }\n plotDataUnits.set(index, unit);\n }\n\n public void setPlotDataAxis(int index, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataAxes.set(index, axis);\n }\n\n public void setPlotDataType(int index, FlightDataType type, Unit unit, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataTypes.set(index, type);\n plotDataUnits.set(index, unit);\n plotDataAxes.set(index, axis);\n }\n\n public void removePlotDataType(int index) {\n plotDataTypes.remove(index);\n plotDataUnits.remove(index);\n plotDataAxes.remove(index);\n }\n\n public FlightDataType getType(int index) {\n return plotDataTypes.get(index);\n }\n\n public Unit getUnit(int index) {\n return plotDataUnits.get(index);\n }\n\n public int getAxis(int index) {\n return plotDataAxes.get(index);\n }\n\n public int getTypeCount() {\n return plotDataTypes.size();\n }\n\n public Set getActiveEvents() {\n return events.clone();\n }\n\n public void setEvent(FlightEvent.Type type, boolean active) {\n if (active) {\n events.add(type);\n } else {\n events.remove(type);\n }\n }\n\n public boolean isEventActive(FlightEvent.Type type) {\n return events.contains(type);\n }\n\n public List getAllAxes() {\n List list = new ArrayList();\n list.addAll(allAxes);\n return list;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * Returns the name of this PlotConfiguration.\n */\n @Override\n public String toString() {\n return name;\n }\n\n /**\n * Find the best combination of the auto-selectable axes.\n *\n * @return\ta new PlotConfiguration with the best fitting auto-selected axes and\n * \t\t\taxes ranges selected.\n */\n public PlotConfiguration fillAutoAxes(FlightDataBranch data) {\n PlotConfiguration config = recursiveFillAutoAxes(data).getU();\n config.fitAxes(data);\n return config;\n }\n\n /**\n * Recursively search for the best combination of the auto-selectable axes.\n * This is a brute-force search method.\n *\n * @return\ta new PlotConfiguration with the best fitting auto-selected axes and\n * \t\t\taxes ranges selected, and the goodness value\n */\n private Pair recursiveFillAutoAxes(FlightDataBranch data) {\n // Create copy to fill in\n PlotConfiguration copy = this.clone();\n int autoindex;\n for (autoindex = 0; autoindex < plotDataAxes.size(); autoindex++) {\n if (plotDataAxes.get(autoindex) < 0)\n break;\n }\n if (autoindex >= plotDataAxes.size()) {\n // All axes have been assigned, just return since we are already the best\n return new Pair(copy, copy.getGoodnessValue(data));\n }\n // Set the auto-selected index one at a time and choose the best one\n PlotConfiguration best = null;\n double bestValue = Double.NEGATIVE_INFINITY;\n for (int i = 0; i < axesCount; i++) {\n copy.plotDataAxes.set(autoindex, i);\n Pair result = copy.recursiveFillAutoAxes(data);\n if (result.getV() > bestValue) {\n best = result.getU();\n bestValue = result.getV();\n }\n }\n return new Pair(best, bestValue);\n }\n\n /**\n * Fit the axes to hold the provided data. All of the plotDataAxis elements must\n * be non-negative.\n *

\n * NOTE: This method assumes that only two axes are used.\n */\n protected void fitAxes(FlightDataBranch data) {\n // Reset axes\n for (Axis a : allAxes) {\n a.reset();\n }\n // Add full range to the axes\n int length = plotDataTypes.size();\n for (int i = 0; i < length; i++) {\n FlightDataType type = plotDataTypes.get(i);\n Unit unit = plotDataUnits.get(i);\n int index = plotDataAxes.get(i);\n if (index < 0) {\n throw new IllegalStateException(\"fitAxes called with auto-selected axis\");\n }\n Axis axis = allAxes.get(index);\n double min = unit.toUnit(data.getMinimum(type));\n double max = unit.toUnit(data.getMaximum(type));\n axis.addBound(min);\n axis.addBound(max);\n }\n // Ensure non-zero (or NaN) range, add a few percent range, include zero if it is close\n for (Axis a : allAxes) {\n if (MathUtil.equals(a.getMinValue(), a.getMaxValue())) {\n a.addBound(a.getMinValue() - 1);\n a.addBound(a.getMaxValue() + 1);\n }\n double addition = a.getRangeLength() * 0.03;\n a.addBound(a.getMinValue() - addition);\n a.addBound(a.getMaxValue() + addition);\n double dist;\n dist = Math.min(Math.abs(a.getMinValue()), Math.abs(a.getMaxValue()));\n if (dist <= a.getRangeLength() * INCLUDE_ZERO_DISTANCE) {\n a.addBound(0);\n }\n }\n // Check whether to use a common zero\n Axis left = allAxes.get(0);\n Axis right = allAxes.get(1);\n if (left.getMinValue() > 0 || left.getMaxValue() < 0 || right.getMinValue() > 0 || right.getMaxValue() < 0 || Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue()))\n return;\n // // Compute common zero\n // TODO: MEDIUM: This algorithm may require tweaking\n double min1 = left.getMinValue();\n double max1 = left.getMaxValue();\n double min2 = right.getMinValue();\n double max2 = right.getMaxValue();\n // Calculate and round scaling factor\n double scale = Math.max(left.getRangeLength(), right.getRangeLength()) / Math.min(left.getRangeLength(), right.getRangeLength());\n scale = roundScale(scale);\n if (right.getRangeLength() > left.getRangeLength()) {\n scale = 1 / scale;\n }\n // Scale right axis, enlarge axes if necessary and scale back\n min2 *= scale;\n max2 *= scale;\n min1 = Math.min(min1, min2);\n min2 = min1;\n max1 = Math.max(max1, max2);\n max2 = max1;\n min2 /= scale;\n max2 /= scale;\n // Apply scale\n left.addBound(min1);\n left.addBound(max1);\n right.addBound(min2);\n right.addBound(max2);\n }\n\n private double roundScale(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 7.5) {\n scale = 10;\n } else if (scale > 4.5) {\n scale = 5;\n } else if (scale > 3) {\n scale = 4;\n } else if (scale > 1.5) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n @SuppressWarnings(\"unused\")\n private double roundScaleUp(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 5) {\n scale = 10;\n } else if (scale > 4) {\n scale = 5;\n } else if (scale > 2) {\n scale = 4;\n } else if (scale > 1) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n @SuppressWarnings(\"unused\")\n private double roundScaleDown(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 5) {\n scale = 5;\n } else if (scale > 4) {\n scale = 4;\n } else if (scale > 2) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n /**\n * Fits the axis ranges to the data and returns the \"goodness value\" of this\n * selection of axes. All plotDataAxis elements must be non-null.\n *

\n * NOTE: This method assumes that all data can fit into the axes ranges and\n * that only two axes are used.\n *\n * @return\ta \"goodness value\", the larger the better.\n */\n protected double getGoodnessValue(FlightDataBranch data) {\n double goodness = 0;\n int length = plotDataTypes.size();\n // Fit the axes ranges to the data\n fitAxes(data);\n /*\n\t\t * Calculate goodness of ranges. 100 points is given if the values fill the\n\t\t * entire range, 0 if they fill none of it.\n\t\t */\n for (int i = 0; i < length; i++) {\n FlightDataType type = plotDataTypes.get(i);\n Unit unit = plotDataUnits.get(i);\n int index = plotDataAxes.get(i);\n if (index < 0) {\n throw new IllegalStateException(\"getGoodnessValue called with auto-selected axis\");\n }\n Axis axis = allAxes.get(index);\n double min = unit.toUnit(data.getMinimum(type));\n double max = unit.toUnit(data.getMaximum(type));\n if (Double.isNaN(min) || Double.isNaN(max))\n continue;\n if (MathUtil.equals(min, max))\n continue;\n double d = (max - min) / axis.getRangeLength();\n // Prioritize small ranges\n d = MathUtil.safeSqrt(d);\n goodness += d * 100.0;\n }\n /*\n\t\t * Add extra points for specific things.\n\t\t */\n // A little for the first type being on the first axis\n if (plotDataAxes.get(0) == 0)\n goodness += BONUS_FIRST_TYPE_ON_FIRST_AXIS;\n // A little bonus if the first axis contains zero\n Axis left = allAxes.get(0);\n if (left.getMinValue() <= 0 && left.getMaxValue() >= 0)\n goodness += BONUS_FIRST_AXIS_HAS_ZERO;\n // A boost if a common zero was used in the ranging\n Axis right = allAxes.get(1);\n if (left.getMinValue() <= 0 && left.getMaxValue() >= 0 && right.getMinValue() <= 0 && right.getMaxValue() >= 0)\n goodness += BONUS_COMMON_ZERO;\n // A boost if only one axis is used\n if (Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue()))\n goodness += BONUS_ONLY_ONE_AXIS;\n return goodness;\n }\n\n /**\n * Reset the units of this configuration to the default units. Returns this\n * PlotConfiguration.\n *\n * @return this PlotConfiguration.\n */\n public PlotConfiguration resetUnits() {\n for (int i = 0; i < plotDataTypes.size(); i++) {\n plotDataUnits.set(i, plotDataTypes.get(i).getUnitGroup().getDefaultUnit());\n }\n return this;\n }\n\n @Override\n public PlotConfiguration clone() {\n try {\n PlotConfiguration copy = (PlotConfiguration) super.clone();\n // Shallow-clone all immutable lists\n copy.plotDataTypes = this.plotDataTypes.clone();\n copy.plotDataAxes = this.plotDataAxes.clone();\n copy.plotDataUnits = this.plotDataUnits.clone();\n copy.events = this.events.clone();\n // Deep-clone all Axis since they are mutable\n copy.allAxes = new ArrayList();\n for (Axis a : this.allAxes) {\n copy.allAxes.add(a.clone());\n }\n return copy;\n } catch (CloneNotSupportedException e) {\n throw new BugException(\"BUG! Could not clone().\");\n }\n }\n}\n"} {"task_id": "Java_2109", "language": "Java", "task_type": "single_line", "source_file": "java/github/openrocket/openrocket/swing/src/net/sf/openrocket/gui/plot/PlotConfiguration.java", "mask_start_position": 18174, "mask_end_position": 18178, "canonical_solution": "in1;", "pre_mask_code": "package net.sf.openrocket.gui.plot;\n\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Set;\nimport net.sf.openrocket.l10n.Translator;\nimport net.sf.openrocket.simulation.FlightDataBranch;\nimport net.sf.openrocket.simulation.FlightDataType;\nimport net.sf.openrocket.simulation.FlightEvent;\nimport net.sf.openrocket.startup.Application;\nimport net.sf.openrocket.unit.Unit;\nimport net.sf.openrocket.util.ArrayList;\nimport net.sf.openrocket.util.BugException;\nimport net.sf.openrocket.util.MathUtil;\nimport net.sf.openrocket.util.Pair;\n\npublic class PlotConfiguration implements Cloneable {\n\n private static final Translator trans = Application.getTranslator();\n\n public static final PlotConfiguration[] DEFAULT_CONFIGURATIONS;\n\n static {\n ArrayList configs = new ArrayList();\n PlotConfiguration config;\n // // Vertical motion vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Verticalmotion\"));\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0);\n config.addPlotDataType(FlightDataType.TYPE_VELOCITY_Z);\n config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_Z);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Total motion vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Totalmotion\"));\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0);\n config.addPlotDataType(FlightDataType.TYPE_VELOCITY_TOTAL);\n config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_TOTAL);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Flight side profile\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Flightside\"), FlightDataType.TYPE_POSITION_X);\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Groundtrack\"), FlightDataType.TYPE_POSITION_X);\n config.addPlotDataType(FlightDataType.TYPE_POSITION_Y, 0);\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Stability\"));\n config.addPlotDataType(FlightDataType.TYPE_STABILITY, 0);\n config.addPlotDataType(FlightDataType.TYPE_CP_LOCATION, 1);\n config.addPlotDataType(FlightDataType.TYPE_CG_LOCATION, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Drag coefficients vs. Mach number\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Dragcoef\"), FlightDataType.TYPE_MACH_NUMBER);\n config.addPlotDataType(FlightDataType.TYPE_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_FRICTION_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_BASE_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_PRESSURE_DRAG_COEFF, 0);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Rollcharacteristics\"));\n config.addPlotDataType(FlightDataType.TYPE_ROLL_RATE, 0);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_MOMENT_COEFF, 1);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_FORCING_COEFF, 1);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_DAMPING_COEFF, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.LAUNCHROD, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Angle of attack and orientation vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Angleofattack\"));\n config.addPlotDataType(FlightDataType.TYPE_AOA, 0);\n config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_PHI);\n config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_THETA);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Simulation time step and computation time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Simulationtime\"));\n config.addPlotDataType(FlightDataType.TYPE_TIME_STEP);\n config.addPlotDataType(FlightDataType.TYPE_COMPUTATION_TIME);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n DEFAULT_CONFIGURATIONS = configs.toArray(new PlotConfiguration[0]);\n }\n\n /**\n * Bonus given for the first type being on the first axis\n */\n private static final double BONUS_FIRST_TYPE_ON_FIRST_AXIS = 1.0;\n\n /**\n * Bonus given if the first axis includes zero (to prefer first axis having zero over\n * the others)\n */\n private static final double BONUS_FIRST_AXIS_HAS_ZERO = 2.0;\n\n /**\n * Bonus given for a common zero point on left and right axes.\n */\n private static final double BONUS_COMMON_ZERO = 40.0;\n\n /**\n * Bonus given for only using a single axis.\n */\n private static final double BONUS_ONLY_ONE_AXIS = 50.0;\n\n // 30% of total range\n private static final double INCLUDE_ZERO_DISTANCE = 0.3;\n\n /**\n * The data types to be plotted.\n */\n private ArrayList plotDataTypes = new ArrayList();\n\n private ArrayList plotDataUnits = new ArrayList();\n\n /**\n * The corresponding Axis on which they will be plotted, or null to auto-select.\n */\n private ArrayList plotDataAxes = new ArrayList();\n\n private EnumSet events = EnumSet.noneOf(FlightEvent.Type.class);\n\n private FlightDataType domainAxisType = null;\n\n private Unit domainAxisUnit = null;\n\n /**\n * All available axes.\n */\n private final int axesCount;\n\n private ArrayList allAxes = new ArrayList();\n\n private String name = null;\n\n public PlotConfiguration() {\n this(null, FlightDataType.TYPE_TIME);\n }\n\n public PlotConfiguration(String name) {\n this(name, FlightDataType.TYPE_TIME);\n }\n\n public PlotConfiguration(String name, FlightDataType domainType) {\n this.name = name;\n // Two axes\n allAxes.add(new Axis());\n allAxes.add(new Axis());\n axesCount = 2;\n setDomainAxisType(domainType);\n }\n\n public FlightDataType getDomainAxisType() {\n return domainAxisType;\n }\n\n public void setDomainAxisType(FlightDataType type) {\n boolean setUnit;\n if (domainAxisType != null && domainAxisType.getUnitGroup() == type.getUnitGroup())\n setUnit = false;\n else\n setUnit = true;\n domainAxisType = type;\n if (setUnit)\n domainAxisUnit = domainAxisType.getUnitGroup().getDefaultUnit();\n }\n\n public Unit getDomainAxisUnit() {\n return domainAxisUnit;\n }\n\n public void setDomainAxisUnit(Unit u) {\n if (!domainAxisType.getUnitGroup().contains(u)) {\n throw new IllegalArgumentException(\"Setting unit \" + u + \" to type \" + domainAxisType);\n }\n domainAxisUnit = u;\n }\n\n public void addPlotDataType(FlightDataType type) {\n plotDataTypes.add(type);\n plotDataUnits.add(type.getUnitGroup().getDefaultUnit());\n plotDataAxes.add(-1);\n }\n\n public void addPlotDataType(FlightDataType type, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataTypes.add(type);\n plotDataUnits.add(type.getUnitGroup().getDefaultUnit());\n plotDataAxes.add(axis);\n }\n\n public void setPlotDataType(int index, FlightDataType type) {\n FlightDataType origType = plotDataTypes.get(index);\n plotDataTypes.set(index, type);\n if (origType.getUnitGroup() != type.getUnitGroup()) {\n plotDataUnits.set(index, type.getUnitGroup().getDefaultUnit());\n }\n }\n\n public void setPlotDataUnit(int index, Unit unit) {\n if (!plotDataTypes.get(index).getUnitGroup().contains(unit)) {\n throw new IllegalArgumentException(\"Attempting to set unit \" + unit + \" to group \" + plotDataTypes.get(index).getUnitGroup());\n }\n plotDataUnits.set(index, unit);\n }\n\n public void setPlotDataAxis(int index, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataAxes.set(index, axis);\n }\n\n public void setPlotDataType(int index, FlightDataType type, Unit unit, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataTypes.set(index, type);\n plotDataUnits.set(index, unit);\n plotDataAxes.set(index, axis);\n }\n\n public void removePlotDataType(int index) {\n plotDataTypes.remove(index);\n plotDataUnits.remove(index);\n plotDataAxes.remove(index);\n }\n\n public FlightDataType getType(int index) {\n return plotDataTypes.get(index);\n }\n\n public Unit getUnit(int index) {\n return plotDataUnits.get(index);\n }\n\n public int getAxis(int index) {\n return plotDataAxes.get(index);\n }\n\n public int getTypeCount() {\n return plotDataTypes.size();\n }\n\n public Set getActiveEvents() {\n return events.clone();\n }\n\n public void setEvent(FlightEvent.Type type, boolean active) {\n if (active) {\n events.add(type);\n } else {\n events.remove(type);\n }\n }\n\n public boolean isEventActive(FlightEvent.Type type) {\n return events.contains(type);\n }\n\n public List getAllAxes() {\n List list = new ArrayList();\n list.addAll(allAxes);\n return list;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * Returns the name of this PlotConfiguration.\n */\n @Override\n public String toString() {\n return name;\n }\n\n /**\n * Find the best combination of the auto-selectable axes.\n *\n * @return\ta new PlotConfiguration with the best fitting auto-selected axes and\n * \t\t\taxes ranges selected.\n */\n public PlotConfiguration fillAutoAxes(FlightDataBranch data) {\n PlotConfiguration config = recursiveFillAutoAxes(data).getU();\n config.fitAxes(data);\n return config;\n }\n\n /**\n * Recursively search for the best combination of the auto-selectable axes.\n * This is a brute-force search method.\n *\n * @return\ta new PlotConfiguration with the best fitting auto-selected axes and\n * \t\t\taxes ranges selected, and the goodness value\n */\n private Pair recursiveFillAutoAxes(FlightDataBranch data) {\n // Create copy to fill in\n PlotConfiguration copy = this.clone();\n int autoindex;\n for (autoindex = 0; autoindex < plotDataAxes.size(); autoindex++) {\n if (plotDataAxes.get(autoindex) < 0)\n break;\n }\n if (autoindex >= plotDataAxes.size()) {\n // All axes have been assigned, just return since we are already the best\n return new Pair(copy, copy.getGoodnessValue(data));\n }\n // Set the auto-selected index one at a time and choose the best one\n PlotConfiguration best = null;\n double bestValue = Double.NEGATIVE_INFINITY;\n for (int i = 0; i < axesCount; i++) {\n copy.plotDataAxes.set(autoindex, i);\n Pair result = copy.recursiveFillAutoAxes(data);\n if (result.getV() > bestValue) {\n best = result.getU();\n bestValue = result.getV();\n }\n }\n return new Pair(best, bestValue);\n }\n\n /**\n * Fit the axes to hold the provided data. All of the plotDataAxis elements must\n * be non-negative.\n *

\n * NOTE: This method assumes that only two axes are used.\n */\n protected void fitAxes(FlightDataBranch data) {\n // Reset axes\n for (Axis a : allAxes) {\n a.reset();\n }\n // Add full range to the axes\n int length = plotDataTypes.size();\n for (int i = 0; i < length; i++) {\n FlightDataType type = plotDataTypes.get(i);\n Unit unit = plotDataUnits.get(i);\n int index = plotDataAxes.get(i);\n if (index < 0) {\n throw new IllegalStateException(\"fitAxes called with auto-selected axis\");\n }\n Axis axis = allAxes.get(index);\n double min = unit.toUnit(data.getMinimum(type));\n double max = unit.toUnit(data.getMaximum(type));\n axis.addBound(min);\n axis.addBound(max);\n }\n // Ensure non-zero (or NaN) range, add a few percent range, include zero if it is close\n for (Axis a : allAxes) {\n if (MathUtil.equals(a.getMinValue(), a.getMaxValue())) {\n a.addBound(a.getMinValue() - 1);\n a.addBound(a.getMaxValue() + 1);\n }\n double addition = a.getRangeLength() * 0.03;\n a.addBound(a.getMinValue() - addition);\n a.addBound(a.getMaxValue() + addition);\n double dist;\n dist = Math.min(Math.abs(a.getMinValue()), Math.abs(a.getMaxValue()));\n if (dist <= a.getRangeLength() * INCLUDE_ZERO_DISTANCE) {\n a.addBound(0);\n }\n }\n // Check whether to use a common zero\n Axis left = allAxes.get(0);\n Axis right = allAxes.get(1);\n if (left.getMinValue() > 0 || left.getMaxValue() < 0 || right.getMinValue() > 0 || right.getMaxValue() < 0 || Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue()))\n return;\n // // Compute common zero\n // TODO: MEDIUM: This algorithm may require tweaking\n double min1 = left.getMinValue();\n double max1 = left.getMaxValue();\n double min2 = right.getMinValue();\n double max2 = right.getMaxValue();\n // Calculate and round scaling factor\n double scale = Math.max(left.getRangeLength(), right.getRangeLength()) / Math.min(left.getRangeLength(), right.getRangeLength());\n scale = roundScale(scale);\n if (right.getRangeLength() > left.getRangeLength()) {\n scale = 1 / scale;\n }\n // Scale right axis, enlarge axes if necessary and scale back\n min2 *= scale;\n max2 *= scale;\n min1 = Math.min(min1, min2);\n min2 = m", "post_mask_code": "\n max1 = Math.max(max1, max2);\n max2 = max1;\n min2 /= scale;\n max2 /= scale;\n // Apply scale\n left.addBound(min1);\n left.addBound(max1);\n right.addBound(min2);\n right.addBound(max2);\n }\n\n private double roundScale(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 7.5) {\n scale = 10;\n } else if (scale > 4.5) {\n scale = 5;\n } else if (scale > 3) {\n scale = 4;\n } else if (scale > 1.5) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n @SuppressWarnings(\"unused\")\n private double roundScaleUp(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 5) {\n scale = 10;\n } else if (scale > 4) {\n scale = 5;\n } else if (scale > 2) {\n scale = 4;\n } else if (scale > 1) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n @SuppressWarnings(\"unused\")\n private double roundScaleDown(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 5) {\n scale = 5;\n } else if (scale > 4) {\n scale = 4;\n } else if (scale > 2) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n /**\n * Fits the axis ranges to the data and returns the \"goodness value\" of this\n * selection of axes. All plotDataAxis elements must be non-null.\n *

\n * NOTE: This method assumes that all data can fit into the axes ranges and\n * that only two axes are used.\n *\n * @return\ta \"goodness value\", the larger the better.\n */\n protected double getGoodnessValue(FlightDataBranch data) {\n double goodness = 0;\n int length = plotDataTypes.size();\n // Fit the axes ranges to the data\n fitAxes(data);\n /*\n\t\t * Calculate goodness of ranges. 100 points is given if the values fill the\n\t\t * entire range, 0 if they fill none of it.\n\t\t */\n for (int i = 0; i < length; i++) {\n FlightDataType type = plotDataTypes.get(i);\n Unit unit = plotDataUnits.get(i);\n int index = plotDataAxes.get(i);\n if (index < 0) {\n throw new IllegalStateException(\"getGoodnessValue called with auto-selected axis\");\n }\n Axis axis = allAxes.get(index);\n double min = unit.toUnit(data.getMinimum(type));\n double max = unit.toUnit(data.getMaximum(type));\n if (Double.isNaN(min) || Double.isNaN(max))\n continue;\n if (MathUtil.equals(min, max))\n continue;\n double d = (max - min) / axis.getRangeLength();\n // Prioritize small ranges\n d = MathUtil.safeSqrt(d);\n goodness += d * 100.0;\n }\n /*\n\t\t * Add extra points for specific things.\n\t\t */\n // A little for the first type being on the first axis\n if (plotDataAxes.get(0) == 0)\n goodness += BONUS_FIRST_TYPE_ON_FIRST_AXIS;\n // A little bonus if the first axis contains zero\n Axis left = allAxes.get(0);\n if (left.getMinValue() <= 0 && left.getMaxValue() >= 0)\n goodness += BONUS_FIRST_AXIS_HAS_ZERO;\n // A boost if a common zero was used in the ranging\n Axis right = allAxes.get(1);\n if (left.getMinValue() <= 0 && left.getMaxValue() >= 0 && right.getMinValue() <= 0 && right.getMaxValue() >= 0)\n goodness += BONUS_COMMON_ZERO;\n // A boost if only one axis is used\n if (Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue()))\n goodness += BONUS_ONLY_ONE_AXIS;\n return goodness;\n }\n\n /**\n * Reset the units of this configuration to the default units. Returns this\n * PlotConfiguration.\n *\n * @return this PlotConfiguration.\n */\n public PlotConfiguration resetUnits() {\n for (int i = 0; i < plotDataTypes.size(); i++) {\n plotDataUnits.set(i, plotDataTypes.get(i).getUnitGroup().getDefaultUnit());\n }\n return this;\n }\n\n @Override\n public PlotConfiguration clone() {\n try {\n PlotConfiguration copy = (PlotConfiguration) super.clone();\n // Shallow-clone all immutable lists\n copy.plotDataTypes = this.plotDataTypes.clone();\n copy.plotDataAxes = this.plotDataAxes.clone();\n copy.plotDataUnits = this.plotDataUnits.clone();\n copy.events = this.events.clone();\n // Deep-clone all Axis since they are mutable\n copy.allAxes = new ArrayList();\n for (Axis a : this.allAxes) {\n copy.allAxes.add(a.clone());\n }\n return copy;\n } catch (CloneNotSupportedException e) {\n throw new BugException(\"BUG! Could not clone().\");\n }\n }\n}\n"} {"task_id": "Java_2110", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/openrocket/openrocket/swing/src/net/sf/openrocket/gui/plot/PlotConfiguration.java", "mask_start_position": 13757, "mask_end_position": 13949, "canonical_solution": "public PlotConfiguration fillAutoAxes(FlightDataBranch data) {\n PlotConfiguration config = recursiveFillAutoAxes(data).getU();\n config.fitAxes(data);\n return config;\n }", "pre_mask_code": "package net.sf.openrocket.gui.plot;\n\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Set;\nimport net.sf.openrocket.l10n.Translator;\nimport net.sf.openrocket.simulation.FlightDataBranch;\nimport net.sf.openrocket.simulation.FlightDataType;\nimport net.sf.openrocket.simulation.FlightEvent;\nimport net.sf.openrocket.startup.Application;\nimport net.sf.openrocket.unit.Unit;\nimport net.sf.openrocket.util.ArrayList;\nimport net.sf.openrocket.util.BugException;\nimport net.sf.openrocket.util.MathUtil;\nimport net.sf.openrocket.util.Pair;\n\npublic class PlotConfiguration implements Cloneable {\n\n private static final Translator trans = Application.getTranslator();\n\n public static final PlotConfiguration[] DEFAULT_CONFIGURATIONS;\n\n static {\n ArrayList configs = new ArrayList();\n PlotConfiguration config;\n // // Vertical motion vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Verticalmotion\"));\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0);\n config.addPlotDataType(FlightDataType.TYPE_VELOCITY_Z);\n config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_Z);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Total motion vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Totalmotion\"));\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0);\n config.addPlotDataType(FlightDataType.TYPE_VELOCITY_TOTAL);\n config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_TOTAL);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Flight side profile\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Flightside\"), FlightDataType.TYPE_POSITION_X);\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Groundtrack\"), FlightDataType.TYPE_POSITION_X);\n config.addPlotDataType(FlightDataType.TYPE_POSITION_Y, 0);\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Stability\"));\n config.addPlotDataType(FlightDataType.TYPE_STABILITY, 0);\n config.addPlotDataType(FlightDataType.TYPE_CP_LOCATION, 1);\n config.addPlotDataType(FlightDataType.TYPE_CG_LOCATION, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Drag coefficients vs. Mach number\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Dragcoef\"), FlightDataType.TYPE_MACH_NUMBER);\n config.addPlotDataType(FlightDataType.TYPE_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_FRICTION_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_BASE_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_PRESSURE_DRAG_COEFF, 0);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Rollcharacteristics\"));\n config.addPlotDataType(FlightDataType.TYPE_ROLL_RATE, 0);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_MOMENT_COEFF, 1);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_FORCING_COEFF, 1);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_DAMPING_COEFF, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.LAUNCHROD, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Angle of attack and orientation vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Angleofattack\"));\n config.addPlotDataType(FlightDataType.TYPE_AOA, 0);\n config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_PHI);\n config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_THETA);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Simulation time step and computation time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Simulationtime\"));\n config.addPlotDataType(FlightDataType.TYPE_TIME_STEP);\n config.addPlotDataType(FlightDataType.TYPE_COMPUTATION_TIME);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n DEFAULT_CONFIGURATIONS = configs.toArray(new PlotConfiguration[0]);\n }\n\n /**\n * Bonus given for the first type being on the first axis\n */\n private static final double BONUS_FIRST_TYPE_ON_FIRST_AXIS = 1.0;\n\n /**\n * Bonus given if the first axis includes zero (to prefer first axis having zero over\n * the others)\n */\n private static final double BONUS_FIRST_AXIS_HAS_ZERO = 2.0;\n\n /**\n * Bonus given for a common zero point on left and right axes.\n */\n private static final double BONUS_COMMON_ZERO = 40.0;\n\n /**\n * Bonus given for only using a single axis.\n */\n private static final double BONUS_ONLY_ONE_AXIS = 50.0;\n\n // 30% of total range\n private static final double INCLUDE_ZERO_DISTANCE = 0.3;\n\n /**\n * The data types to be plotted.\n */\n private ArrayList plotDataTypes = new ArrayList();\n\n private ArrayList plotDataUnits = new ArrayList();\n\n /**\n * The corresponding Axis on which they will be plotted, or null to auto-select.\n */\n private ArrayList plotDataAxes = new ArrayList();\n\n private EnumSet events = EnumSet.noneOf(FlightEvent.Type.class);\n\n private FlightDataType domainAxisType = null;\n\n private Unit domainAxisUnit = null;\n\n /**\n * All available axes.\n */\n private final int axesCount;\n\n private ArrayList allAxes = new ArrayList();\n\n private String name = null;\n\n public PlotConfiguration() {\n this(null, FlightDataType.TYPE_TIME);\n }\n\n public PlotConfiguration(String name) {\n this(name, FlightDataType.TYPE_TIME);\n }\n\n public PlotConfiguration(String name, FlightDataType domainType) {\n this.name = name;\n // Two axes\n allAxes.add(new Axis());\n allAxes.add(new Axis());\n axesCount = 2;\n setDomainAxisType(domainType);\n }\n\n public FlightDataType getDomainAxisType() {\n return domainAxisType;\n }\n\n public void setDomainAxisType(FlightDataType type) {\n boolean setUnit;\n if (domainAxisType != null && domainAxisType.getUnitGroup() == type.getUnitGroup())\n setUnit = false;\n else\n setUnit = true;\n domainAxisType = type;\n if (setUnit)\n domainAxisUnit = domainAxisType.getUnitGroup().getDefaultUnit();\n }\n\n public Unit getDomainAxisUnit() {\n return domainAxisUnit;\n }\n\n public void setDomainAxisUnit(Unit u) {\n if (!domainAxisType.getUnitGroup().contains(u)) {\n throw new IllegalArgumentException(\"Setting unit \" + u + \" to type \" + domainAxisType);\n }\n domainAxisUnit = u;\n }\n\n public void addPlotDataType(FlightDataType type) {\n plotDataTypes.add(type);\n plotDataUnits.add(type.getUnitGroup().getDefaultUnit());\n plotDataAxes.add(-1);\n }\n\n public void addPlotDataType(FlightDataType type, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataTypes.add(type);\n plotDataUnits.add(type.getUnitGroup().getDefaultUnit());\n plotDataAxes.add(axis);\n }\n\n public void setPlotDataType(int index, FlightDataType type) {\n FlightDataType origType = plotDataTypes.get(index);\n plotDataTypes.set(index, type);\n if (origType.getUnitGroup() != type.getUnitGroup()) {\n plotDataUnits.set(index, type.getUnitGroup().getDefaultUnit());\n }\n }\n\n public void setPlotDataUnit(int index, Unit unit) {\n if (!plotDataTypes.get(index).getUnitGroup().contains(unit)) {\n throw new IllegalArgumentException(\"Attempting to set unit \" + unit + \" to group \" + plotDataTypes.get(index).getUnitGroup());\n }\n plotDataUnits.set(index, unit);\n }\n\n public void setPlotDataAxis(int index, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataAxes.set(index, axis);\n }\n\n public void setPlotDataType(int index, FlightDataType type, Unit unit, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataTypes.set(index, type);\n plotDataUnits.set(index, unit);\n plotDataAxes.set(index, axis);\n }\n\n public void removePlotDataType(int index) {\n plotDataTypes.remove(index);\n plotDataUnits.remove(index);\n plotDataAxes.remove(index);\n }\n\n public FlightDataType getType(int index) {\n return plotDataTypes.get(index);\n }\n\n public Unit getUnit(int index) {\n return plotDataUnits.get(index);\n }\n\n public int getAxis(int index) {\n return plotDataAxes.get(index);\n }\n\n public int getTypeCount() {\n return plotDataTypes.size();\n }\n\n public Set getActiveEvents() {\n return events.clone();\n }\n\n public void setEvent(FlightEvent.Type type, boolean active) {\n if (active) {\n events.add(type);\n } else {\n events.remove(type);\n }\n }\n\n public boolean isEventActive(FlightEvent.Type type) {\n return events.contains(type);\n }\n\n public List getAllAxes() {\n List list = new ArrayList();\n list.addAll(allAxes);\n return list;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * Returns the name of this PlotConfiguration.\n */\n @Override\n public String toString() {\n return name;\n }\n\n /**\n * Find the best combination of the auto-selectable axes.\n *\n * @return\ta new PlotConfiguration with the best fitting auto-selected axes and\n * \t\t\taxes ranges selected.\n */\n ", "post_mask_code": "\n\n /**\n * Recursively search for the best combination of the auto-selectable axes.\n * This is a brute-force search method.\n *\n * @return\ta new PlotConfiguration with the best fitting auto-selected axes and\n * \t\t\taxes ranges selected, and the goodness value\n */\n private Pair recursiveFillAutoAxes(FlightDataBranch data) {\n // Create copy to fill in\n PlotConfiguration copy = this.clone();\n int autoindex;\n for (autoindex = 0; autoindex < plotDataAxes.size(); autoindex++) {\n if (plotDataAxes.get(autoindex) < 0)\n break;\n }\n if (autoindex >= plotDataAxes.size()) {\n // All axes have been assigned, just return since we are already the best\n return new Pair(copy, copy.getGoodnessValue(data));\n }\n // Set the auto-selected index one at a time and choose the best one\n PlotConfiguration best = null;\n double bestValue = Double.NEGATIVE_INFINITY;\n for (int i = 0; i < axesCount; i++) {\n copy.plotDataAxes.set(autoindex, i);\n Pair result = copy.recursiveFillAutoAxes(data);\n if (result.getV() > bestValue) {\n best = result.getU();\n bestValue = result.getV();\n }\n }\n return new Pair(best, bestValue);\n }\n\n /**\n * Fit the axes to hold the provided data. All of the plotDataAxis elements must\n * be non-negative.\n *

\n * NOTE: This method assumes that only two axes are used.\n */\n protected void fitAxes(FlightDataBranch data) {\n // Reset axes\n for (Axis a : allAxes) {\n a.reset();\n }\n // Add full range to the axes\n int length = plotDataTypes.size();\n for (int i = 0; i < length; i++) {\n FlightDataType type = plotDataTypes.get(i);\n Unit unit = plotDataUnits.get(i);\n int index = plotDataAxes.get(i);\n if (index < 0) {\n throw new IllegalStateException(\"fitAxes called with auto-selected axis\");\n }\n Axis axis = allAxes.get(index);\n double min = unit.toUnit(data.getMinimum(type));\n double max = unit.toUnit(data.getMaximum(type));\n axis.addBound(min);\n axis.addBound(max);\n }\n // Ensure non-zero (or NaN) range, add a few percent range, include zero if it is close\n for (Axis a : allAxes) {\n if (MathUtil.equals(a.getMinValue(), a.getMaxValue())) {\n a.addBound(a.getMinValue() - 1);\n a.addBound(a.getMaxValue() + 1);\n }\n double addition = a.getRangeLength() * 0.03;\n a.addBound(a.getMinValue() - addition);\n a.addBound(a.getMaxValue() + addition);\n double dist;\n dist = Math.min(Math.abs(a.getMinValue()), Math.abs(a.getMaxValue()));\n if (dist <= a.getRangeLength() * INCLUDE_ZERO_DISTANCE) {\n a.addBound(0);\n }\n }\n // Check whether to use a common zero\n Axis left = allAxes.get(0);\n Axis right = allAxes.get(1);\n if (left.getMinValue() > 0 || left.getMaxValue() < 0 || right.getMinValue() > 0 || right.getMaxValue() < 0 || Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue()))\n return;\n // // Compute common zero\n // TODO: MEDIUM: This algorithm may require tweaking\n double min1 = left.getMinValue();\n double max1 = left.getMaxValue();\n double min2 = right.getMinValue();\n double max2 = right.getMaxValue();\n // Calculate and round scaling factor\n double scale = Math.max(left.getRangeLength(), right.getRangeLength()) / Math.min(left.getRangeLength(), right.getRangeLength());\n scale = roundScale(scale);\n if (right.getRangeLength() > left.getRangeLength()) {\n scale = 1 / scale;\n }\n // Scale right axis, enlarge axes if necessary and scale back\n min2 *= scale;\n max2 *= scale;\n min1 = Math.min(min1, min2);\n min2 = min1;\n max1 = Math.max(max1, max2);\n max2 = max1;\n min2 /= scale;\n max2 /= scale;\n // Apply scale\n left.addBound(min1);\n left.addBound(max1);\n right.addBound(min2);\n right.addBound(max2);\n }\n\n private double roundScale(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 7.5) {\n scale = 10;\n } else if (scale > 4.5) {\n scale = 5;\n } else if (scale > 3) {\n scale = 4;\n } else if (scale > 1.5) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n @SuppressWarnings(\"unused\")\n private double roundScaleUp(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 5) {\n scale = 10;\n } else if (scale > 4) {\n scale = 5;\n } else if (scale > 2) {\n scale = 4;\n } else if (scale > 1) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n @SuppressWarnings(\"unused\")\n private double roundScaleDown(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 5) {\n scale = 5;\n } else if (scale > 4) {\n scale = 4;\n } else if (scale > 2) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n /**\n * Fits the axis ranges to the data and returns the \"goodness value\" of this\n * selection of axes. All plotDataAxis elements must be non-null.\n *

\n * NOTE: This method assumes that all data can fit into the axes ranges and\n * that only two axes are used.\n *\n * @return\ta \"goodness value\", the larger the better.\n */\n protected double getGoodnessValue(FlightDataBranch data) {\n double goodness = 0;\n int length = plotDataTypes.size();\n // Fit the axes ranges to the data\n fitAxes(data);\n /*\n\t\t * Calculate goodness of ranges. 100 points is given if the values fill the\n\t\t * entire range, 0 if they fill none of it.\n\t\t */\n for (int i = 0; i < length; i++) {\n FlightDataType type = plotDataTypes.get(i);\n Unit unit = plotDataUnits.get(i);\n int index = plotDataAxes.get(i);\n if (index < 0) {\n throw new IllegalStateException(\"getGoodnessValue called with auto-selected axis\");\n }\n Axis axis = allAxes.get(index);\n double min = unit.toUnit(data.getMinimum(type));\n double max = unit.toUnit(data.getMaximum(type));\n if (Double.isNaN(min) || Double.isNaN(max))\n continue;\n if (MathUtil.equals(min, max))\n continue;\n double d = (max - min) / axis.getRangeLength();\n // Prioritize small ranges\n d = MathUtil.safeSqrt(d);\n goodness += d * 100.0;\n }\n /*\n\t\t * Add extra points for specific things.\n\t\t */\n // A little for the first type being on the first axis\n if (plotDataAxes.get(0) == 0)\n goodness += BONUS_FIRST_TYPE_ON_FIRST_AXIS;\n // A little bonus if the first axis contains zero\n Axis left = allAxes.get(0);\n if (left.getMinValue() <= 0 && left.getMaxValue() >= 0)\n goodness += BONUS_FIRST_AXIS_HAS_ZERO;\n // A boost if a common zero was used in the ranging\n Axis right = allAxes.get(1);\n if (left.getMinValue() <= 0 && left.getMaxValue() >= 0 && right.getMinValue() <= 0 && right.getMaxValue() >= 0)\n goodness += BONUS_COMMON_ZERO;\n // A boost if only one axis is used\n if (Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue()))\n goodness += BONUS_ONLY_ONE_AXIS;\n return goodness;\n }\n\n /**\n * Reset the units of this configuration to the default units. Returns this\n * PlotConfiguration.\n *\n * @return this PlotConfiguration.\n */\n public PlotConfiguration resetUnits() {\n for (int i = 0; i < plotDataTypes.size(); i++) {\n plotDataUnits.set(i, plotDataTypes.get(i).getUnitGroup().getDefaultUnit());\n }\n return this;\n }\n\n @Override\n public PlotConfiguration clone() {\n try {\n PlotConfiguration copy = (PlotConfiguration) super.clone();\n // Shallow-clone all immutable lists\n copy.plotDataTypes = this.plotDataTypes.clone();\n copy.plotDataAxes = this.plotDataAxes.clone();\n copy.plotDataUnits = this.plotDataUnits.clone();\n copy.events = this.events.clone();\n // Deep-clone all Axis since they are mutable\n copy.allAxes = new ArrayList();\n for (Axis a : this.allAxes) {\n copy.allAxes.add(a.clone());\n }\n return copy;\n } catch (CloneNotSupportedException e) {\n throw new BugException(\"BUG! Could not clone().\");\n }\n }\n}\n"} {"task_id": "Java_2111", "language": "Java", "task_type": "for_statement", "source_file": "java/github/openrocket/openrocket/swing/src/net/sf/openrocket/gui/plot/PlotConfiguration.java", "mask_start_position": 22727, "mask_end_position": 22873, "canonical_solution": "for (int i = 0; i < plotDataTypes.size(); i++) {\n plotDataUnits.set(i, plotDataTypes.get(i).getUnitGroup().getDefaultUnit());\n }", "pre_mask_code": "package net.sf.openrocket.gui.plot;\n\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Set;\nimport net.sf.openrocket.l10n.Translator;\nimport net.sf.openrocket.simulation.FlightDataBranch;\nimport net.sf.openrocket.simulation.FlightDataType;\nimport net.sf.openrocket.simulation.FlightEvent;\nimport net.sf.openrocket.startup.Application;\nimport net.sf.openrocket.unit.Unit;\nimport net.sf.openrocket.util.ArrayList;\nimport net.sf.openrocket.util.BugException;\nimport net.sf.openrocket.util.MathUtil;\nimport net.sf.openrocket.util.Pair;\n\npublic class PlotConfiguration implements Cloneable {\n\n private static final Translator trans = Application.getTranslator();\n\n public static final PlotConfiguration[] DEFAULT_CONFIGURATIONS;\n\n static {\n ArrayList configs = new ArrayList();\n PlotConfiguration config;\n // // Vertical motion vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Verticalmotion\"));\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0);\n config.addPlotDataType(FlightDataType.TYPE_VELOCITY_Z);\n config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_Z);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Total motion vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Totalmotion\"));\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0);\n config.addPlotDataType(FlightDataType.TYPE_VELOCITY_TOTAL);\n config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_TOTAL);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Flight side profile\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Flightside\"), FlightDataType.TYPE_POSITION_X);\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Groundtrack\"), FlightDataType.TYPE_POSITION_X);\n config.addPlotDataType(FlightDataType.TYPE_POSITION_Y, 0);\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Stability\"));\n config.addPlotDataType(FlightDataType.TYPE_STABILITY, 0);\n config.addPlotDataType(FlightDataType.TYPE_CP_LOCATION, 1);\n config.addPlotDataType(FlightDataType.TYPE_CG_LOCATION, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Drag coefficients vs. Mach number\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Dragcoef\"), FlightDataType.TYPE_MACH_NUMBER);\n config.addPlotDataType(FlightDataType.TYPE_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_FRICTION_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_BASE_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_PRESSURE_DRAG_COEFF, 0);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Rollcharacteristics\"));\n config.addPlotDataType(FlightDataType.TYPE_ROLL_RATE, 0);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_MOMENT_COEFF, 1);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_FORCING_COEFF, 1);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_DAMPING_COEFF, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.LAUNCHROD, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Angle of attack and orientation vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Angleofattack\"));\n config.addPlotDataType(FlightDataType.TYPE_AOA, 0);\n config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_PHI);\n config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_THETA);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Simulation time step and computation time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Simulationtime\"));\n config.addPlotDataType(FlightDataType.TYPE_TIME_STEP);\n config.addPlotDataType(FlightDataType.TYPE_COMPUTATION_TIME);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n DEFAULT_CONFIGURATIONS = configs.toArray(new PlotConfiguration[0]);\n }\n\n /**\n * Bonus given for the first type being on the first axis\n */\n private static final double BONUS_FIRST_TYPE_ON_FIRST_AXIS = 1.0;\n\n /**\n * Bonus given if the first axis includes zero (to prefer first axis having zero over\n * the others)\n */\n private static final double BONUS_FIRST_AXIS_HAS_ZERO = 2.0;\n\n /**\n * Bonus given for a common zero point on left and right axes.\n */\n private static final double BONUS_COMMON_ZERO = 40.0;\n\n /**\n * Bonus given for only using a single axis.\n */\n private static final double BONUS_ONLY_ONE_AXIS = 50.0;\n\n // 30% of total range\n private static final double INCLUDE_ZERO_DISTANCE = 0.3;\n\n /**\n * The data types to be plotted.\n */\n private ArrayList plotDataTypes = new ArrayList();\n\n private ArrayList plotDataUnits = new ArrayList();\n\n /**\n * The corresponding Axis on which they will be plotted, or null to auto-select.\n */\n private ArrayList plotDataAxes = new ArrayList();\n\n private EnumSet events = EnumSet.noneOf(FlightEvent.Type.class);\n\n private FlightDataType domainAxisType = null;\n\n private Unit domainAxisUnit = null;\n\n /**\n * All available axes.\n */\n private final int axesCount;\n\n private ArrayList allAxes = new ArrayList();\n\n private String name = null;\n\n public PlotConfiguration() {\n this(null, FlightDataType.TYPE_TIME);\n }\n\n public PlotConfiguration(String name) {\n this(name, FlightDataType.TYPE_TIME);\n }\n\n public PlotConfiguration(String name, FlightDataType domainType) {\n this.name = name;\n // Two axes\n allAxes.add(new Axis());\n allAxes.add(new Axis());\n axesCount = 2;\n setDomainAxisType(domainType);\n }\n\n public FlightDataType getDomainAxisType() {\n return domainAxisType;\n }\n\n public void setDomainAxisType(FlightDataType type) {\n boolean setUnit;\n if (domainAxisType != null && domainAxisType.getUnitGroup() == type.getUnitGroup())\n setUnit = false;\n else\n setUnit = true;\n domainAxisType = type;\n if (setUnit)\n domainAxisUnit = domainAxisType.getUnitGroup().getDefaultUnit();\n }\n\n public Unit getDomainAxisUnit() {\n return domainAxisUnit;\n }\n\n public void setDomainAxisUnit(Unit u) {\n if (!domainAxisType.getUnitGroup().contains(u)) {\n throw new IllegalArgumentException(\"Setting unit \" + u + \" to type \" + domainAxisType);\n }\n domainAxisUnit = u;\n }\n\n public void addPlotDataType(FlightDataType type) {\n plotDataTypes.add(type);\n plotDataUnits.add(type.getUnitGroup().getDefaultUnit());\n plotDataAxes.add(-1);\n }\n\n public void addPlotDataType(FlightDataType type, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataTypes.add(type);\n plotDataUnits.add(type.getUnitGroup().getDefaultUnit());\n plotDataAxes.add(axis);\n }\n\n public void setPlotDataType(int index, FlightDataType type) {\n FlightDataType origType = plotDataTypes.get(index);\n plotDataTypes.set(index, type);\n if (origType.getUnitGroup() != type.getUnitGroup()) {\n plotDataUnits.set(index, type.getUnitGroup().getDefaultUnit());\n }\n }\n\n public void setPlotDataUnit(int index, Unit unit) {\n if (!plotDataTypes.get(index).getUnitGroup().contains(unit)) {\n throw new IllegalArgumentException(\"Attempting to set unit \" + unit + \" to group \" + plotDataTypes.get(index).getUnitGroup());\n }\n plotDataUnits.set(index, unit);\n }\n\n public void setPlotDataAxis(int index, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataAxes.set(index, axis);\n }\n\n public void setPlotDataType(int index, FlightDataType type, Unit unit, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataTypes.set(index, type);\n plotDataUnits.set(index, unit);\n plotDataAxes.set(index, axis);\n }\n\n public void removePlotDataType(int index) {\n plotDataTypes.remove(index);\n plotDataUnits.remove(index);\n plotDataAxes.remove(index);\n }\n\n public FlightDataType getType(int index) {\n return plotDataTypes.get(index);\n }\n\n public Unit getUnit(int index) {\n return plotDataUnits.get(index);\n }\n\n public int getAxis(int index) {\n return plotDataAxes.get(index);\n }\n\n public int getTypeCount() {\n return plotDataTypes.size();\n }\n\n public Set getActiveEvents() {\n return events.clone();\n }\n\n public void setEvent(FlightEvent.Type type, boolean active) {\n if (active) {\n events.add(type);\n } else {\n events.remove(type);\n }\n }\n\n public boolean isEventActive(FlightEvent.Type type) {\n return events.contains(type);\n }\n\n public List getAllAxes() {\n List list = new ArrayList();\n list.addAll(allAxes);\n return list;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * Returns the name of this PlotConfiguration.\n */\n @Override\n public String toString() {\n return name;\n }\n\n /**\n * Find the best combination of the auto-selectable axes.\n *\n * @return\ta new PlotConfiguration with the best fitting auto-selected axes and\n * \t\t\taxes ranges selected.\n */\n public PlotConfiguration fillAutoAxes(FlightDataBranch data) {\n PlotConfiguration config = recursiveFillAutoAxes(data).getU();\n config.fitAxes(data);\n return config;\n }\n\n /**\n * Recursively search for the best combination of the auto-selectable axes.\n * This is a brute-force search method.\n *\n * @return\ta new PlotConfiguration with the best fitting auto-selected axes and\n * \t\t\taxes ranges selected, and the goodness value\n */\n private Pair recursiveFillAutoAxes(FlightDataBranch data) {\n // Create copy to fill in\n PlotConfiguration copy = this.clone();\n int autoindex;\n for (autoindex = 0; autoindex < plotDataAxes.size(); autoindex++) {\n if (plotDataAxes.get(autoindex) < 0)\n break;\n }\n if (autoindex >= plotDataAxes.size()) {\n // All axes have been assigned, just return since we are already the best\n return new Pair(copy, copy.getGoodnessValue(data));\n }\n // Set the auto-selected index one at a time and choose the best one\n PlotConfiguration best = null;\n double bestValue = Double.NEGATIVE_INFINITY;\n for (int i = 0; i < axesCount; i++) {\n copy.plotDataAxes.set(autoindex, i);\n Pair result = copy.recursiveFillAutoAxes(data);\n if (result.getV() > bestValue) {\n best = result.getU();\n bestValue = result.getV();\n }\n }\n return new Pair(best, bestValue);\n }\n\n /**\n * Fit the axes to hold the provided data. All of the plotDataAxis elements must\n * be non-negative.\n *

\n * NOTE: This method assumes that only two axes are used.\n */\n protected void fitAxes(FlightDataBranch data) {\n // Reset axes\n for (Axis a : allAxes) {\n a.reset();\n }\n // Add full range to the axes\n int length = plotDataTypes.size();\n for (int i = 0; i < length; i++) {\n FlightDataType type = plotDataTypes.get(i);\n Unit unit = plotDataUnits.get(i);\n int index = plotDataAxes.get(i);\n if (index < 0) {\n throw new IllegalStateException(\"fitAxes called with auto-selected axis\");\n }\n Axis axis = allAxes.get(index);\n double min = unit.toUnit(data.getMinimum(type));\n double max = unit.toUnit(data.getMaximum(type));\n axis.addBound(min);\n axis.addBound(max);\n }\n // Ensure non-zero (or NaN) range, add a few percent range, include zero if it is close\n for (Axis a : allAxes) {\n if (MathUtil.equals(a.getMinValue(), a.getMaxValue())) {\n a.addBound(a.getMinValue() - 1);\n a.addBound(a.getMaxValue() + 1);\n }\n double addition = a.getRangeLength() * 0.03;\n a.addBound(a.getMinValue() - addition);\n a.addBound(a.getMaxValue() + addition);\n double dist;\n dist = Math.min(Math.abs(a.getMinValue()), Math.abs(a.getMaxValue()));\n if (dist <= a.getRangeLength() * INCLUDE_ZERO_DISTANCE) {\n a.addBound(0);\n }\n }\n // Check whether to use a common zero\n Axis left = allAxes.get(0);\n Axis right = allAxes.get(1);\n if (left.getMinValue() > 0 || left.getMaxValue() < 0 || right.getMinValue() > 0 || right.getMaxValue() < 0 || Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue()))\n return;\n // // Compute common zero\n // TODO: MEDIUM: This algorithm may require tweaking\n double min1 = left.getMinValue();\n double max1 = left.getMaxValue();\n double min2 = right.getMinValue();\n double max2 = right.getMaxValue();\n // Calculate and round scaling factor\n double scale = Math.max(left.getRangeLength(), right.getRangeLength()) / Math.min(left.getRangeLength(), right.getRangeLength());\n scale = roundScale(scale);\n if (right.getRangeLength() > left.getRangeLength()) {\n scale = 1 / scale;\n }\n // Scale right axis, enlarge axes if necessary and scale back\n min2 *= scale;\n max2 *= scale;\n min1 = Math.min(min1, min2);\n min2 = min1;\n max1 = Math.max(max1, max2);\n max2 = max1;\n min2 /= scale;\n max2 /= scale;\n // Apply scale\n left.addBound(min1);\n left.addBound(max1);\n right.addBound(min2);\n right.addBound(max2);\n }\n\n private double roundScale(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 7.5) {\n scale = 10;\n } else if (scale > 4.5) {\n scale = 5;\n } else if (scale > 3) {\n scale = 4;\n } else if (scale > 1.5) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n @SuppressWarnings(\"unused\")\n private double roundScaleUp(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 5) {\n scale = 10;\n } else if (scale > 4) {\n scale = 5;\n } else if (scale > 2) {\n scale = 4;\n } else if (scale > 1) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n @SuppressWarnings(\"unused\")\n private double roundScaleDown(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 5) {\n scale = 5;\n } else if (scale > 4) {\n scale = 4;\n } else if (scale > 2) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n /**\n * Fits the axis ranges to the data and returns the \"goodness value\" of this\n * selection of axes. All plotDataAxis elements must be non-null.\n *

\n * NOTE: This method assumes that all data can fit into the axes ranges and\n * that only two axes are used.\n *\n * @return\ta \"goodness value\", the larger the better.\n */\n protected double getGoodnessValue(FlightDataBranch data) {\n double goodness = 0;\n int length = plotDataTypes.size();\n // Fit the axes ranges to the data\n fitAxes(data);\n /*\n\t\t * Calculate goodness of ranges. 100 points is given if the values fill the\n\t\t * entire range, 0 if they fill none of it.\n\t\t */\n for (int i = 0; i < length; i++) {\n FlightDataType type = plotDataTypes.get(i);\n Unit unit = plotDataUnits.get(i);\n int index = plotDataAxes.get(i);\n if (index < 0) {\n throw new IllegalStateException(\"getGoodnessValue called with auto-selected axis\");\n }\n Axis axis = allAxes.get(index);\n double min = unit.toUnit(data.getMinimum(type));\n double max = unit.toUnit(data.getMaximum(type));\n if (Double.isNaN(min) || Double.isNaN(max))\n continue;\n if (MathUtil.equals(min, max))\n continue;\n double d = (max - min) / axis.getRangeLength();\n // Prioritize small ranges\n d = MathUtil.safeSqrt(d);\n goodness += d * 100.0;\n }\n /*\n\t\t * Add extra points for specific things.\n\t\t */\n // A little for the first type being on the first axis\n if (plotDataAxes.get(0) == 0)\n goodness += BONUS_FIRST_TYPE_ON_FIRST_AXIS;\n // A little bonus if the first axis contains zero\n Axis left = allAxes.get(0);\n if (left.getMinValue() <= 0 && left.getMaxValue() >= 0)\n goodness += BONUS_FIRST_AXIS_HAS_ZERO;\n // A boost if a common zero was used in the ranging\n Axis right = allAxes.get(1);\n if (left.getMinValue() <= 0 && left.getMaxValue() >= 0 && right.getMinValue() <= 0 && right.getMaxValue() >= 0)\n goodness += BONUS_COMMON_ZERO;\n // A boost if only one axis is used\n if (Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue()))\n goodness += BONUS_ONLY_ONE_AXIS;\n return goodness;\n }\n\n /**\n * Reset the units of this configuration to the default units. Returns this\n * PlotConfiguration.\n *\n * @return this PlotConfiguration.\n */\n public PlotConfiguration resetUnits() {\n ", "post_mask_code": "\n return this;\n }\n\n @Override\n public PlotConfiguration clone() {\n try {\n PlotConfiguration copy = (PlotConfiguration) super.clone();\n // Shallow-clone all immutable lists\n copy.plotDataTypes = this.plotDataTypes.clone();\n copy.plotDataAxes = this.plotDataAxes.clone();\n copy.plotDataUnits = this.plotDataUnits.clone();\n copy.events = this.events.clone();\n // Deep-clone all Axis since they are mutable\n copy.allAxes = new ArrayList();\n for (Axis a : this.allAxes) {\n copy.allAxes.add(a.clone());\n }\n return copy;\n } catch (CloneNotSupportedException e) {\n throw new BugException(\"BUG! Could not clone().\");\n }\n }\n}\n"} {"task_id": "Java_2112", "language": "Java", "task_type": "while_statement", "source_file": "java/github/openrocket/openrocket/swing/src/net/sf/openrocket/gui/plot/PlotConfiguration.java", "mask_start_position": 18597, "mask_end_position": 18674, "canonical_solution": "while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }", "pre_mask_code": "package net.sf.openrocket.gui.plot;\n\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Set;\nimport net.sf.openrocket.l10n.Translator;\nimport net.sf.openrocket.simulation.FlightDataBranch;\nimport net.sf.openrocket.simulation.FlightDataType;\nimport net.sf.openrocket.simulation.FlightEvent;\nimport net.sf.openrocket.startup.Application;\nimport net.sf.openrocket.unit.Unit;\nimport net.sf.openrocket.util.ArrayList;\nimport net.sf.openrocket.util.BugException;\nimport net.sf.openrocket.util.MathUtil;\nimport net.sf.openrocket.util.Pair;\n\npublic class PlotConfiguration implements Cloneable {\n\n private static final Translator trans = Application.getTranslator();\n\n public static final PlotConfiguration[] DEFAULT_CONFIGURATIONS;\n\n static {\n ArrayList configs = new ArrayList();\n PlotConfiguration config;\n // // Vertical motion vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Verticalmotion\"));\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0);\n config.addPlotDataType(FlightDataType.TYPE_VELOCITY_Z);\n config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_Z);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Total motion vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Totalmotion\"));\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0);\n config.addPlotDataType(FlightDataType.TYPE_VELOCITY_TOTAL);\n config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_TOTAL);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Flight side profile\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Flightside\"), FlightDataType.TYPE_POSITION_X);\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Groundtrack\"), FlightDataType.TYPE_POSITION_X);\n config.addPlotDataType(FlightDataType.TYPE_POSITION_Y, 0);\n config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Stability\"));\n config.addPlotDataType(FlightDataType.TYPE_STABILITY, 0);\n config.addPlotDataType(FlightDataType.TYPE_CP_LOCATION, 1);\n config.addPlotDataType(FlightDataType.TYPE_CG_LOCATION, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Drag coefficients vs. Mach number\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Dragcoef\"), FlightDataType.TYPE_MACH_NUMBER);\n config.addPlotDataType(FlightDataType.TYPE_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_FRICTION_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_BASE_DRAG_COEFF, 0);\n config.addPlotDataType(FlightDataType.TYPE_PRESSURE_DRAG_COEFF, 0);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Rollcharacteristics\"));\n config.addPlotDataType(FlightDataType.TYPE_ROLL_RATE, 0);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_MOMENT_COEFF, 1);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_FORCING_COEFF, 1);\n config.addPlotDataType(FlightDataType.TYPE_ROLL_DAMPING_COEFF, 1);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.LAUNCHROD, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Angle of attack and orientation vs. time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Angleofattack\"));\n config.addPlotDataType(FlightDataType.TYPE_AOA, 0);\n config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_PHI);\n config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_THETA);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n // // Simulation time step and computation time\n config = new PlotConfiguration(trans.get(\"PlotConfiguration.Simulationtime\"));\n config.addPlotDataType(FlightDataType.TYPE_TIME_STEP);\n config.addPlotDataType(FlightDataType.TYPE_COMPUTATION_TIME);\n config.setEvent(FlightEvent.Type.IGNITION, true);\n config.setEvent(FlightEvent.Type.BURNOUT, true);\n config.setEvent(FlightEvent.Type.APOGEE, true);\n config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true);\n config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true);\n config.setEvent(FlightEvent.Type.GROUND_HIT, true);\n config.setEvent(FlightEvent.Type.TUMBLE, true);\n config.setEvent(FlightEvent.Type.EXCEPTION, true);\n configs.add(config);\n DEFAULT_CONFIGURATIONS = configs.toArray(new PlotConfiguration[0]);\n }\n\n /**\n * Bonus given for the first type being on the first axis\n */\n private static final double BONUS_FIRST_TYPE_ON_FIRST_AXIS = 1.0;\n\n /**\n * Bonus given if the first axis includes zero (to prefer first axis having zero over\n * the others)\n */\n private static final double BONUS_FIRST_AXIS_HAS_ZERO = 2.0;\n\n /**\n * Bonus given for a common zero point on left and right axes.\n */\n private static final double BONUS_COMMON_ZERO = 40.0;\n\n /**\n * Bonus given for only using a single axis.\n */\n private static final double BONUS_ONLY_ONE_AXIS = 50.0;\n\n // 30% of total range\n private static final double INCLUDE_ZERO_DISTANCE = 0.3;\n\n /**\n * The data types to be plotted.\n */\n private ArrayList plotDataTypes = new ArrayList();\n\n private ArrayList plotDataUnits = new ArrayList();\n\n /**\n * The corresponding Axis on which they will be plotted, or null to auto-select.\n */\n private ArrayList plotDataAxes = new ArrayList();\n\n private EnumSet events = EnumSet.noneOf(FlightEvent.Type.class);\n\n private FlightDataType domainAxisType = null;\n\n private Unit domainAxisUnit = null;\n\n /**\n * All available axes.\n */\n private final int axesCount;\n\n private ArrayList allAxes = new ArrayList();\n\n private String name = null;\n\n public PlotConfiguration() {\n this(null, FlightDataType.TYPE_TIME);\n }\n\n public PlotConfiguration(String name) {\n this(name, FlightDataType.TYPE_TIME);\n }\n\n public PlotConfiguration(String name, FlightDataType domainType) {\n this.name = name;\n // Two axes\n allAxes.add(new Axis());\n allAxes.add(new Axis());\n axesCount = 2;\n setDomainAxisType(domainType);\n }\n\n public FlightDataType getDomainAxisType() {\n return domainAxisType;\n }\n\n public void setDomainAxisType(FlightDataType type) {\n boolean setUnit;\n if (domainAxisType != null && domainAxisType.getUnitGroup() == type.getUnitGroup())\n setUnit = false;\n else\n setUnit = true;\n domainAxisType = type;\n if (setUnit)\n domainAxisUnit = domainAxisType.getUnitGroup().getDefaultUnit();\n }\n\n public Unit getDomainAxisUnit() {\n return domainAxisUnit;\n }\n\n public void setDomainAxisUnit(Unit u) {\n if (!domainAxisType.getUnitGroup().contains(u)) {\n throw new IllegalArgumentException(\"Setting unit \" + u + \" to type \" + domainAxisType);\n }\n domainAxisUnit = u;\n }\n\n public void addPlotDataType(FlightDataType type) {\n plotDataTypes.add(type);\n plotDataUnits.add(type.getUnitGroup().getDefaultUnit());\n plotDataAxes.add(-1);\n }\n\n public void addPlotDataType(FlightDataType type, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataTypes.add(type);\n plotDataUnits.add(type.getUnitGroup().getDefaultUnit());\n plotDataAxes.add(axis);\n }\n\n public void setPlotDataType(int index, FlightDataType type) {\n FlightDataType origType = plotDataTypes.get(index);\n plotDataTypes.set(index, type);\n if (origType.getUnitGroup() != type.getUnitGroup()) {\n plotDataUnits.set(index, type.getUnitGroup().getDefaultUnit());\n }\n }\n\n public void setPlotDataUnit(int index, Unit unit) {\n if (!plotDataTypes.get(index).getUnitGroup().contains(unit)) {\n throw new IllegalArgumentException(\"Attempting to set unit \" + unit + \" to group \" + plotDataTypes.get(index).getUnitGroup());\n }\n plotDataUnits.set(index, unit);\n }\n\n public void setPlotDataAxis(int index, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataAxes.set(index, axis);\n }\n\n public void setPlotDataType(int index, FlightDataType type, Unit unit, int axis) {\n if (axis >= axesCount) {\n throw new IllegalArgumentException(\"Axis index too large\");\n }\n plotDataTypes.set(index, type);\n plotDataUnits.set(index, unit);\n plotDataAxes.set(index, axis);\n }\n\n public void removePlotDataType(int index) {\n plotDataTypes.remove(index);\n plotDataUnits.remove(index);\n plotDataAxes.remove(index);\n }\n\n public FlightDataType getType(int index) {\n return plotDataTypes.get(index);\n }\n\n public Unit getUnit(int index) {\n return plotDataUnits.get(index);\n }\n\n public int getAxis(int index) {\n return plotDataAxes.get(index);\n }\n\n public int getTypeCount() {\n return plotDataTypes.size();\n }\n\n public Set getActiveEvents() {\n return events.clone();\n }\n\n public void setEvent(FlightEvent.Type type, boolean active) {\n if (active) {\n events.add(type);\n } else {\n events.remove(type);\n }\n }\n\n public boolean isEventActive(FlightEvent.Type type) {\n return events.contains(type);\n }\n\n public List getAllAxes() {\n List list = new ArrayList();\n list.addAll(allAxes);\n return list;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * Returns the name of this PlotConfiguration.\n */\n @Override\n public String toString() {\n return name;\n }\n\n /**\n * Find the best combination of the auto-selectable axes.\n *\n * @return\ta new PlotConfiguration with the best fitting auto-selected axes and\n * \t\t\taxes ranges selected.\n */\n public PlotConfiguration fillAutoAxes(FlightDataBranch data) {\n PlotConfiguration config = recursiveFillAutoAxes(data).getU();\n config.fitAxes(data);\n return config;\n }\n\n /**\n * Recursively search for the best combination of the auto-selectable axes.\n * This is a brute-force search method.\n *\n * @return\ta new PlotConfiguration with the best fitting auto-selected axes and\n * \t\t\taxes ranges selected, and the goodness value\n */\n private Pair recursiveFillAutoAxes(FlightDataBranch data) {\n // Create copy to fill in\n PlotConfiguration copy = this.clone();\n int autoindex;\n for (autoindex = 0; autoindex < plotDataAxes.size(); autoindex++) {\n if (plotDataAxes.get(autoindex) < 0)\n break;\n }\n if (autoindex >= plotDataAxes.size()) {\n // All axes have been assigned, just return since we are already the best\n return new Pair(copy, copy.getGoodnessValue(data));\n }\n // Set the auto-selected index one at a time and choose the best one\n PlotConfiguration best = null;\n double bestValue = Double.NEGATIVE_INFINITY;\n for (int i = 0; i < axesCount; i++) {\n copy.plotDataAxes.set(autoindex, i);\n Pair result = copy.recursiveFillAutoAxes(data);\n if (result.getV() > bestValue) {\n best = result.getU();\n bestValue = result.getV();\n }\n }\n return new Pair(best, bestValue);\n }\n\n /**\n * Fit the axes to hold the provided data. All of the plotDataAxis elements must\n * be non-negative.\n *

\n * NOTE: This method assumes that only two axes are used.\n */\n protected void fitAxes(FlightDataBranch data) {\n // Reset axes\n for (Axis a : allAxes) {\n a.reset();\n }\n // Add full range to the axes\n int length = plotDataTypes.size();\n for (int i = 0; i < length; i++) {\n FlightDataType type = plotDataTypes.get(i);\n Unit unit = plotDataUnits.get(i);\n int index = plotDataAxes.get(i);\n if (index < 0) {\n throw new IllegalStateException(\"fitAxes called with auto-selected axis\");\n }\n Axis axis = allAxes.get(index);\n double min = unit.toUnit(data.getMinimum(type));\n double max = unit.toUnit(data.getMaximum(type));\n axis.addBound(min);\n axis.addBound(max);\n }\n // Ensure non-zero (or NaN) range, add a few percent range, include zero if it is close\n for (Axis a : allAxes) {\n if (MathUtil.equals(a.getMinValue(), a.getMaxValue())) {\n a.addBound(a.getMinValue() - 1);\n a.addBound(a.getMaxValue() + 1);\n }\n double addition = a.getRangeLength() * 0.03;\n a.addBound(a.getMinValue() - addition);\n a.addBound(a.getMaxValue() + addition);\n double dist;\n dist = Math.min(Math.abs(a.getMinValue()), Math.abs(a.getMaxValue()));\n if (dist <= a.getRangeLength() * INCLUDE_ZERO_DISTANCE) {\n a.addBound(0);\n }\n }\n // Check whether to use a common zero\n Axis left = allAxes.get(0);\n Axis right = allAxes.get(1);\n if (left.getMinValue() > 0 || left.getMaxValue() < 0 || right.getMinValue() > 0 || right.getMaxValue() < 0 || Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue()))\n return;\n // // Compute common zero\n // TODO: MEDIUM: This algorithm may require tweaking\n double min1 = left.getMinValue();\n double max1 = left.getMaxValue();\n double min2 = right.getMinValue();\n double max2 = right.getMaxValue();\n // Calculate and round scaling factor\n double scale = Math.max(left.getRangeLength(), right.getRangeLength()) / Math.min(left.getRangeLength(), right.getRangeLength());\n scale = roundScale(scale);\n if (right.getRangeLength() > left.getRangeLength()) {\n scale = 1 / scale;\n }\n // Scale right axis, enlarge axes if necessary and scale back\n min2 *= scale;\n max2 *= scale;\n min1 = Math.min(min1, min2);\n min2 = min1;\n max1 = Math.max(max1, max2);\n max2 = max1;\n min2 /= scale;\n max2 /= scale;\n // Apply scale\n left.addBound(min1);\n left.addBound(max1);\n right.addBound(min2);\n right.addBound(max2);\n }\n\n private double roundScale(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n ", "post_mask_code": "\n if (scale > 7.5) {\n scale = 10;\n } else if (scale > 4.5) {\n scale = 5;\n } else if (scale > 3) {\n scale = 4;\n } else if (scale > 1.5) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n @SuppressWarnings(\"unused\")\n private double roundScaleUp(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 5) {\n scale = 10;\n } else if (scale > 4) {\n scale = 5;\n } else if (scale > 2) {\n scale = 4;\n } else if (scale > 1) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n @SuppressWarnings(\"unused\")\n private double roundScaleDown(double scale) {\n double mul = 1;\n while (scale >= 10) {\n scale /= 10;\n mul *= 10;\n }\n while (scale < 1) {\n scale *= 10;\n mul /= 10;\n }\n if (scale > 5) {\n scale = 5;\n } else if (scale > 4) {\n scale = 4;\n } else if (scale > 2) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale * mul;\n }\n\n /**\n * Fits the axis ranges to the data and returns the \"goodness value\" of this\n * selection of axes. All plotDataAxis elements must be non-null.\n *

\n * NOTE: This method assumes that all data can fit into the axes ranges and\n * that only two axes are used.\n *\n * @return\ta \"goodness value\", the larger the better.\n */\n protected double getGoodnessValue(FlightDataBranch data) {\n double goodness = 0;\n int length = plotDataTypes.size();\n // Fit the axes ranges to the data\n fitAxes(data);\n /*\n\t\t * Calculate goodness of ranges. 100 points is given if the values fill the\n\t\t * entire range, 0 if they fill none of it.\n\t\t */\n for (int i = 0; i < length; i++) {\n FlightDataType type = plotDataTypes.get(i);\n Unit unit = plotDataUnits.get(i);\n int index = plotDataAxes.get(i);\n if (index < 0) {\n throw new IllegalStateException(\"getGoodnessValue called with auto-selected axis\");\n }\n Axis axis = allAxes.get(index);\n double min = unit.toUnit(data.getMinimum(type));\n double max = unit.toUnit(data.getMaximum(type));\n if (Double.isNaN(min) || Double.isNaN(max))\n continue;\n if (MathUtil.equals(min, max))\n continue;\n double d = (max - min) / axis.getRangeLength();\n // Prioritize small ranges\n d = MathUtil.safeSqrt(d);\n goodness += d * 100.0;\n }\n /*\n\t\t * Add extra points for specific things.\n\t\t */\n // A little for the first type being on the first axis\n if (plotDataAxes.get(0) == 0)\n goodness += BONUS_FIRST_TYPE_ON_FIRST_AXIS;\n // A little bonus if the first axis contains zero\n Axis left = allAxes.get(0);\n if (left.getMinValue() <= 0 && left.getMaxValue() >= 0)\n goodness += BONUS_FIRST_AXIS_HAS_ZERO;\n // A boost if a common zero was used in the ranging\n Axis right = allAxes.get(1);\n if (left.getMinValue() <= 0 && left.getMaxValue() >= 0 && right.getMinValue() <= 0 && right.getMaxValue() >= 0)\n goodness += BONUS_COMMON_ZERO;\n // A boost if only one axis is used\n if (Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue()))\n goodness += BONUS_ONLY_ONE_AXIS;\n return goodness;\n }\n\n /**\n * Reset the units of this configuration to the default units. Returns this\n * PlotConfiguration.\n *\n * @return this PlotConfiguration.\n */\n public PlotConfiguration resetUnits() {\n for (int i = 0; i < plotDataTypes.size(); i++) {\n plotDataUnits.set(i, plotDataTypes.get(i).getUnitGroup().getDefaultUnit());\n }\n return this;\n }\n\n @Override\n public PlotConfiguration clone() {\n try {\n PlotConfiguration copy = (PlotConfiguration) super.clone();\n // Shallow-clone all immutable lists\n copy.plotDataTypes = this.plotDataTypes.clone();\n copy.plotDataAxes = this.plotDataAxes.clone();\n copy.plotDataUnits = this.plotDataUnits.clone();\n copy.events = this.events.clone();\n // Deep-clone all Axis since they are mutable\n copy.allAxes = new ArrayList();\n for (Axis a : this.allAxes) {\n copy.allAxes.add(a.clone());\n }\n return copy;\n } catch (CloneNotSupportedException e) {\n throw new BugException(\"BUG! Could not clone().\");\n }\n }\n}\n"} {"task_id": "Java_2113", "language": "Java", "task_type": "method_signature", "source_file": "java/github/dstmath/OppoFramework/A5_8_1_0/src/main/java/android/mtp/MtpDevice.java", "mask_start_position": 3966, "mask_end_position": 3991, "canonical_solution": "public String toString() ", "pre_mask_code": "package android.mtp;\n\nimport android.content.Context;\nimport android.hardware.usb.UsbDevice;\nimport android.hardware.usb.UsbDeviceConnection;\nimport android.os.CancellationSignal;\nimport android.os.CancellationSignal.OnCancelListener;\nimport android.os.ParcelFileDescriptor;\nimport android.os.UserManager;\nimport com.android.internal.annotations.GuardedBy;\nimport com.android.internal.util.Preconditions;\nimport dalvik.system.CloseGuard;\nimport java.io.IOException;\n\npublic final class MtpDevice {\n\n private static final String TAG = \"MtpDevice\";\n\n @GuardedBy(\"mLock\")\n private CloseGuard mCloseGuard = CloseGuard.get();\n\n @GuardedBy(\"mLock\")\n private UsbDeviceConnection mConnection;\n\n private final UsbDevice mDevice;\n\n private final Object mLock = new Object();\n\n private long mNativeContext;\n\n private native void native_close();\n\n private native boolean native_delete_object(int i);\n\n private native void native_discard_event_request(int i);\n\n private native MtpDeviceInfo native_get_device_info();\n\n private native byte[] native_get_object(int i, long j);\n\n private native int[] native_get_object_handles(int i, int i2, int i3);\n\n private native MtpObjectInfo native_get_object_info(int i);\n\n private native long native_get_object_size_long(int i, int i2) throws IOException;\n\n private native int native_get_parent(int i);\n\n private native long native_get_partial_object(int i, long j, long j2, byte[] bArr) throws IOException;\n\n private native int native_get_partial_object_64(int i, long j, long j2, byte[] bArr) throws IOException;\n\n private native int native_get_storage_id(int i);\n\n private native int[] native_get_storage_ids();\n\n private native MtpStorageInfo native_get_storage_info(int i);\n\n private native byte[] native_get_thumbnail(int i);\n\n private native boolean native_import_file(int i, int i2);\n\n private native boolean native_import_file(int i, String str);\n\n private native boolean native_open(String str, int i);\n\n private native MtpEvent native_reap_event_request(int i) throws IOException;\n\n private native boolean native_send_object(int i, long j, int i2);\n\n private native MtpObjectInfo native_send_object_info(MtpObjectInfo mtpObjectInfo);\n\n private native int native_submit_event_request() throws IOException;\n\n static {\n System.loadLibrary(\"media_jni\");\n }\n\n public MtpDevice(UsbDevice device) {\n Preconditions.checkNotNull(device);\n this.mDevice = device;\n }\n\n public boolean open(UsbDeviceConnection connection) {\n boolean result = false;\n Context context = connection.getContext();\n synchronized (this.mLock) {\n if (context != null) {\n if (!((UserManager) context.getSystemService(Context.USER_SERVICE)).hasUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER)) {\n result = native_open(this.mDevice.getDeviceName(), connection.getFileDescriptor());\n }\n }\n if (result) {\n this.mConnection = connection;\n this.mCloseGuard.open(\"close\");\n } else {\n connection.close();\n }\n }\n return result;\n }\n\n public void close() {\n synchronized (this.mLock) {\n if (this.mConnection != null) {\n this.mCloseGuard.close();\n native_close();\n this.mConnection.close();\n this.mConnection = null;\n }\n }\n }\n\n protected void finalize() throws Throwable {\n try {\n if (this.mCloseGuard != null) {\n this.mCloseGuard.warnIfOpen();\n }\n close();\n } finally {\n super.finalize();\n }\n }\n\n public String getDeviceName() {\n return this.mDevice.getDeviceName();\n }\n\n public int getDeviceId() {\n return this.mDevice.getDeviceId();\n }\n\n ", "post_mask_code": "{\n return this.mDevice.getDeviceName();\n }\n\n public MtpDeviceInfo getDeviceInfo() {\n return native_get_device_info();\n }\n\n public int[] getStorageIds() {\n return native_get_storage_ids();\n }\n\n public int[] getObjectHandles(int storageId, int format, int objectHandle) {\n return native_get_object_handles(storageId, format, objectHandle);\n }\n\n public byte[] getObject(int objectHandle, int objectSize) {\n Preconditions.checkArgumentNonnegative(objectSize, \"objectSize should not be negative\");\n return native_get_object(objectHandle, (long) objectSize);\n }\n\n public long getPartialObject(int objectHandle, long offset, long size, byte[] buffer) throws IOException {\n return native_get_partial_object(objectHandle, offset, size, buffer);\n }\n\n public long getPartialObject64(int objectHandle, long offset, long size, byte[] buffer) throws IOException {\n return (long) native_get_partial_object_64(objectHandle, offset, size, buffer);\n }\n\n public byte[] getThumbnail(int objectHandle) {\n return native_get_thumbnail(objectHandle);\n }\n\n public MtpStorageInfo getStorageInfo(int storageId) {\n return native_get_storage_info(storageId);\n }\n\n public MtpObjectInfo getObjectInfo(int objectHandle) {\n return native_get_object_info(objectHandle);\n }\n\n public boolean deleteObject(int objectHandle) {\n return native_delete_object(objectHandle);\n }\n\n public long getParent(int objectHandle) {\n return (long) native_get_parent(objectHandle);\n }\n\n public long getStorageId(int objectHandle) {\n return (long) native_get_storage_id(objectHandle);\n }\n\n public boolean importFile(int objectHandle, String destPath) {\n return native_import_file(objectHandle, destPath);\n }\n\n public boolean importFile(int objectHandle, ParcelFileDescriptor descriptor) {\n return native_import_file(objectHandle, descriptor.getFd());\n }\n\n public boolean sendObject(int objectHandle, long size, ParcelFileDescriptor descriptor) {\n return native_send_object(objectHandle, size, descriptor.getFd());\n }\n\n public MtpObjectInfo sendObjectInfo(MtpObjectInfo info) {\n return native_send_object_info(info);\n }\n\n public MtpEvent readEvent(CancellationSignal signal) throws IOException {\n boolean z = false;\n final int handle = native_submit_event_request();\n if (handle >= 0) {\n z = true;\n }\n Preconditions.checkState(z, \"Other thread is reading an event.\");\n if (signal != null) {\n signal.setOnCancelListener(new OnCancelListener() {\n\n public void onCancel() {\n MtpDevice.this.native_discard_event_request(handle);\n }\n });\n }\n try {\n MtpEvent native_reap_event_request = native_reap_event_request(handle);\n return native_reap_event_request;\n } finally {\n if (signal != null) {\n signal.setOnCancelListener(null);\n }\n }\n }\n\n public long getObjectSizeLong(int handle, int format) throws IOException {\n return native_get_object_size_long(handle, format);\n }\n}\n"} {"task_id": "Java_2114", "language": "Java", "task_type": "method_body", "source_file": "java/github/dstmath/OppoFramework/A5_8_1_0/src/main/java/android/mtp/MtpDevice.java", "mask_start_position": 7186, "mask_end_position": 7253, "canonical_solution": "{\n return native_get_object_size_long(handle, format);\n }", "pre_mask_code": "package android.mtp;\n\nimport android.content.Context;\nimport android.hardware.usb.UsbDevice;\nimport android.hardware.usb.UsbDeviceConnection;\nimport android.os.CancellationSignal;\nimport android.os.CancellationSignal.OnCancelListener;\nimport android.os.ParcelFileDescriptor;\nimport android.os.UserManager;\nimport com.android.internal.annotations.GuardedBy;\nimport com.android.internal.util.Preconditions;\nimport dalvik.system.CloseGuard;\nimport java.io.IOException;\n\npublic final class MtpDevice {\n\n private static final String TAG = \"MtpDevice\";\n\n @GuardedBy(\"mLock\")\n private CloseGuard mCloseGuard = CloseGuard.get();\n\n @GuardedBy(\"mLock\")\n private UsbDeviceConnection mConnection;\n\n private final UsbDevice mDevice;\n\n private final Object mLock = new Object();\n\n private long mNativeContext;\n\n private native void native_close();\n\n private native boolean native_delete_object(int i);\n\n private native void native_discard_event_request(int i);\n\n private native MtpDeviceInfo native_get_device_info();\n\n private native byte[] native_get_object(int i, long j);\n\n private native int[] native_get_object_handles(int i, int i2, int i3);\n\n private native MtpObjectInfo native_get_object_info(int i);\n\n private native long native_get_object_size_long(int i, int i2) throws IOException;\n\n private native int native_get_parent(int i);\n\n private native long native_get_partial_object(int i, long j, long j2, byte[] bArr) throws IOException;\n\n private native int native_get_partial_object_64(int i, long j, long j2, byte[] bArr) throws IOException;\n\n private native int native_get_storage_id(int i);\n\n private native int[] native_get_storage_ids();\n\n private native MtpStorageInfo native_get_storage_info(int i);\n\n private native byte[] native_get_thumbnail(int i);\n\n private native boolean native_import_file(int i, int i2);\n\n private native boolean native_import_file(int i, String str);\n\n private native boolean native_open(String str, int i);\n\n private native MtpEvent native_reap_event_request(int i) throws IOException;\n\n private native boolean native_send_object(int i, long j, int i2);\n\n private native MtpObjectInfo native_send_object_info(MtpObjectInfo mtpObjectInfo);\n\n private native int native_submit_event_request() throws IOException;\n\n static {\n System.loadLibrary(\"media_jni\");\n }\n\n public MtpDevice(UsbDevice device) {\n Preconditions.checkNotNull(device);\n this.mDevice = device;\n }\n\n public boolean open(UsbDeviceConnection connection) {\n boolean result = false;\n Context context = connection.getContext();\n synchronized (this.mLock) {\n if (context != null) {\n if (!((UserManager) context.getSystemService(Context.USER_SERVICE)).hasUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER)) {\n result = native_open(this.mDevice.getDeviceName(), connection.getFileDescriptor());\n }\n }\n if (result) {\n this.mConnection = connection;\n this.mCloseGuard.open(\"close\");\n } else {\n connection.close();\n }\n }\n return result;\n }\n\n public void close() {\n synchronized (this.mLock) {\n if (this.mConnection != null) {\n this.mCloseGuard.close();\n native_close();\n this.mConnection.close();\n this.mConnection = null;\n }\n }\n }\n\n protected void finalize() throws Throwable {\n try {\n if (this.mCloseGuard != null) {\n this.mCloseGuard.warnIfOpen();\n }\n close();\n } finally {\n super.finalize();\n }\n }\n\n public String getDeviceName() {\n return this.mDevice.getDeviceName();\n }\n\n public int getDeviceId() {\n return this.mDevice.getDeviceId();\n }\n\n public String toString() {\n return this.mDevice.getDeviceName();\n }\n\n public MtpDeviceInfo getDeviceInfo() {\n return native_get_device_info();\n }\n\n public int[] getStorageIds() {\n return native_get_storage_ids();\n }\n\n public int[] getObjectHandles(int storageId, int format, int objectHandle) {\n return native_get_object_handles(storageId, format, objectHandle);\n }\n\n public byte[] getObject(int objectHandle, int objectSize) {\n Preconditions.checkArgumentNonnegative(objectSize, \"objectSize should not be negative\");\n return native_get_object(objectHandle, (long) objectSize);\n }\n\n public long getPartialObject(int objectHandle, long offset, long size, byte[] buffer) throws IOException {\n return native_get_partial_object(objectHandle, offset, size, buffer);\n }\n\n public long getPartialObject64(int objectHandle, long offset, long size, byte[] buffer) throws IOException {\n return (long) native_get_partial_object_64(objectHandle, offset, size, buffer);\n }\n\n public byte[] getThumbnail(int objectHandle) {\n return native_get_thumbnail(objectHandle);\n }\n\n public MtpStorageInfo getStorageInfo(int storageId) {\n return native_get_storage_info(storageId);\n }\n\n public MtpObjectInfo getObjectInfo(int objectHandle) {\n return native_get_object_info(objectHandle);\n }\n\n public boolean deleteObject(int objectHandle) {\n return native_delete_object(objectHandle);\n }\n\n public long getParent(int objectHandle) {\n return (long) native_get_parent(objectHandle);\n }\n\n public long getStorageId(int objectHandle) {\n return (long) native_get_storage_id(objectHandle);\n }\n\n public boolean importFile(int objectHandle, String destPath) {\n return native_import_file(objectHandle, destPath);\n }\n\n public boolean importFile(int objectHandle, ParcelFileDescriptor descriptor) {\n return native_import_file(objectHandle, descriptor.getFd());\n }\n\n public boolean sendObject(int objectHandle, long size, ParcelFileDescriptor descriptor) {\n return native_send_object(objectHandle, size, descriptor.getFd());\n }\n\n public MtpObjectInfo sendObjectInfo(MtpObjectInfo info) {\n return native_send_object_info(info);\n }\n\n public MtpEvent readEvent(CancellationSignal signal) throws IOException {\n boolean z = false;\n final int handle = native_submit_event_request();\n if (handle >= 0) {\n z = true;\n }\n Preconditions.checkState(z, \"Other thread is reading an event.\");\n if (signal != null) {\n signal.setOnCancelListener(new OnCancelListener() {\n\n public void onCancel() {\n MtpDevice.this.native_discard_event_request(handle);\n }\n });\n }\n try {\n MtpEvent native_reap_event_request = native_reap_event_request(handle);\n return native_reap_event_request;\n } finally {\n if (signal != null) {\n signal.setOnCancelListener(null);\n }\n }\n }\n\n public long getObjectSizeLong(int handle, int format) throws IOException ", "post_mask_code": "\n}\n"} {"task_id": "Java_2115", "language": "Java", "task_type": "single_line", "source_file": "java/github/dstmath/OppoFramework/A5_8_1_0/src/main/java/android/mtp/MtpDevice.java", "mask_start_position": 5425, "mask_end_position": 5467, "canonical_solution": "return native_delete_object(objectHandle);", "pre_mask_code": "package android.mtp;\n\nimport android.content.Context;\nimport android.hardware.usb.UsbDevice;\nimport android.hardware.usb.UsbDeviceConnection;\nimport android.os.CancellationSignal;\nimport android.os.CancellationSignal.OnCancelListener;\nimport android.os.ParcelFileDescriptor;\nimport android.os.UserManager;\nimport com.android.internal.annotations.GuardedBy;\nimport com.android.internal.util.Preconditions;\nimport dalvik.system.CloseGuard;\nimport java.io.IOException;\n\npublic final class MtpDevice {\n\n private static final String TAG = \"MtpDevice\";\n\n @GuardedBy(\"mLock\")\n private CloseGuard mCloseGuard = CloseGuard.get();\n\n @GuardedBy(\"mLock\")\n private UsbDeviceConnection mConnection;\n\n private final UsbDevice mDevice;\n\n private final Object mLock = new Object();\n\n private long mNativeContext;\n\n private native void native_close();\n\n private native boolean native_delete_object(int i);\n\n private native void native_discard_event_request(int i);\n\n private native MtpDeviceInfo native_get_device_info();\n\n private native byte[] native_get_object(int i, long j);\n\n private native int[] native_get_object_handles(int i, int i2, int i3);\n\n private native MtpObjectInfo native_get_object_info(int i);\n\n private native long native_get_object_size_long(int i, int i2) throws IOException;\n\n private native int native_get_parent(int i);\n\n private native long native_get_partial_object(int i, long j, long j2, byte[] bArr) throws IOException;\n\n private native int native_get_partial_object_64(int i, long j, long j2, byte[] bArr) throws IOException;\n\n private native int native_get_storage_id(int i);\n\n private native int[] native_get_storage_ids();\n\n private native MtpStorageInfo native_get_storage_info(int i);\n\n private native byte[] native_get_thumbnail(int i);\n\n private native boolean native_import_file(int i, int i2);\n\n private native boolean native_import_file(int i, String str);\n\n private native boolean native_open(String str, int i);\n\n private native MtpEvent native_reap_event_request(int i) throws IOException;\n\n private native boolean native_send_object(int i, long j, int i2);\n\n private native MtpObjectInfo native_send_object_info(MtpObjectInfo mtpObjectInfo);\n\n private native int native_submit_event_request() throws IOException;\n\n static {\n System.loadLibrary(\"media_jni\");\n }\n\n public MtpDevice(UsbDevice device) {\n Preconditions.checkNotNull(device);\n this.mDevice = device;\n }\n\n public boolean open(UsbDeviceConnection connection) {\n boolean result = false;\n Context context = connection.getContext();\n synchronized (this.mLock) {\n if (context != null) {\n if (!((UserManager) context.getSystemService(Context.USER_SERVICE)).hasUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER)) {\n result = native_open(this.mDevice.getDeviceName(), connection.getFileDescriptor());\n }\n }\n if (result) {\n this.mConnection = connection;\n this.mCloseGuard.open(\"close\");\n } else {\n connection.close();\n }\n }\n return result;\n }\n\n public void close() {\n synchronized (this.mLock) {\n if (this.mConnection != null) {\n this.mCloseGuard.close();\n native_close();\n this.mConnection.close();\n this.mConnection = null;\n }\n }\n }\n\n protected void finalize() throws Throwable {\n try {\n if (this.mCloseGuard != null) {\n this.mCloseGuard.warnIfOpen();\n }\n close();\n } finally {\n super.finalize();\n }\n }\n\n public String getDeviceName() {\n return this.mDevice.getDeviceName();\n }\n\n public int getDeviceId() {\n return this.mDevice.getDeviceId();\n }\n\n public String toString() {\n return this.mDevice.getDeviceName();\n }\n\n public MtpDeviceInfo getDeviceInfo() {\n return native_get_device_info();\n }\n\n public int[] getStorageIds() {\n return native_get_storage_ids();\n }\n\n public int[] getObjectHandles(int storageId, int format, int objectHandle) {\n return native_get_object_handles(storageId, format, objectHandle);\n }\n\n public byte[] getObject(int objectHandle, int objectSize) {\n Preconditions.checkArgumentNonnegative(objectSize, \"objectSize should not be negative\");\n return native_get_object(objectHandle, (long) objectSize);\n }\n\n public long getPartialObject(int objectHandle, long offset, long size, byte[] buffer) throws IOException {\n return native_get_partial_object(objectHandle, offset, size, buffer);\n }\n\n public long getPartialObject64(int objectHandle, long offset, long size, byte[] buffer) throws IOException {\n return (long) native_get_partial_object_64(objectHandle, offset, size, buffer);\n }\n\n public byte[] getThumbnail(int objectHandle) {\n return native_get_thumbnail(objectHandle);\n }\n\n public MtpStorageInfo getStorageInfo(int storageId) {\n return native_get_storage_info(storageId);\n }\n\n public MtpObjectInfo getObjectInfo(int objectHandle) {\n return native_get_object_info(objectHandle);\n }\n\n public boolean deleteObject(int objectHandle) {\n ", "post_mask_code": "\n }\n\n public long getParent(int objectHandle) {\n return (long) native_get_parent(objectHandle);\n }\n\n public long getStorageId(int objectHandle) {\n return (long) native_get_storage_id(objectHandle);\n }\n\n public boolean importFile(int objectHandle, String destPath) {\n return native_import_file(objectHandle, destPath);\n }\n\n public boolean importFile(int objectHandle, ParcelFileDescriptor descriptor) {\n return native_import_file(objectHandle, descriptor.getFd());\n }\n\n public boolean sendObject(int objectHandle, long size, ParcelFileDescriptor descriptor) {\n return native_send_object(objectHandle, size, descriptor.getFd());\n }\n\n public MtpObjectInfo sendObjectInfo(MtpObjectInfo info) {\n return native_send_object_info(info);\n }\n\n public MtpEvent readEvent(CancellationSignal signal) throws IOException {\n boolean z = false;\n final int handle = native_submit_event_request();\n if (handle >= 0) {\n z = true;\n }\n Preconditions.checkState(z, \"Other thread is reading an event.\");\n if (signal != null) {\n signal.setOnCancelListener(new OnCancelListener() {\n\n public void onCancel() {\n MtpDevice.this.native_discard_event_request(handle);\n }\n });\n }\n try {\n MtpEvent native_reap_event_request = native_reap_event_request(handle);\n return native_reap_event_request;\n } finally {\n if (signal != null) {\n signal.setOnCancelListener(null);\n }\n }\n }\n\n public long getObjectSizeLong(int handle, int format) throws IOException {\n return native_get_object_size_long(handle, format);\n }\n}\n"} {"task_id": "Java_2116", "language": "Java", "task_type": "try_statement", "source_file": "java/github/dstmath/OppoFramework/A5_8_1_0/src/main/java/android/mtp/MtpDevice.java", "mask_start_position": 6838, "mask_end_position": 7101, "canonical_solution": "try {\n MtpEvent native_reap_event_request = native_reap_event_request(handle);\n return native_reap_event_request;\n } finally {\n if (signal != null) {\n signal.setOnCancelListener(null);\n }\n }", "pre_mask_code": "package android.mtp;\n\nimport android.content.Context;\nimport android.hardware.usb.UsbDevice;\nimport android.hardware.usb.UsbDeviceConnection;\nimport android.os.CancellationSignal;\nimport android.os.CancellationSignal.OnCancelListener;\nimport android.os.ParcelFileDescriptor;\nimport android.os.UserManager;\nimport com.android.internal.annotations.GuardedBy;\nimport com.android.internal.util.Preconditions;\nimport dalvik.system.CloseGuard;\nimport java.io.IOException;\n\npublic final class MtpDevice {\n\n private static final String TAG = \"MtpDevice\";\n\n @GuardedBy(\"mLock\")\n private CloseGuard mCloseGuard = CloseGuard.get();\n\n @GuardedBy(\"mLock\")\n private UsbDeviceConnection mConnection;\n\n private final UsbDevice mDevice;\n\n private final Object mLock = new Object();\n\n private long mNativeContext;\n\n private native void native_close();\n\n private native boolean native_delete_object(int i);\n\n private native void native_discard_event_request(int i);\n\n private native MtpDeviceInfo native_get_device_info();\n\n private native byte[] native_get_object(int i, long j);\n\n private native int[] native_get_object_handles(int i, int i2, int i3);\n\n private native MtpObjectInfo native_get_object_info(int i);\n\n private native long native_get_object_size_long(int i, int i2) throws IOException;\n\n private native int native_get_parent(int i);\n\n private native long native_get_partial_object(int i, long j, long j2, byte[] bArr) throws IOException;\n\n private native int native_get_partial_object_64(int i, long j, long j2, byte[] bArr) throws IOException;\n\n private native int native_get_storage_id(int i);\n\n private native int[] native_get_storage_ids();\n\n private native MtpStorageInfo native_get_storage_info(int i);\n\n private native byte[] native_get_thumbnail(int i);\n\n private native boolean native_import_file(int i, int i2);\n\n private native boolean native_import_file(int i, String str);\n\n private native boolean native_open(String str, int i);\n\n private native MtpEvent native_reap_event_request(int i) throws IOException;\n\n private native boolean native_send_object(int i, long j, int i2);\n\n private native MtpObjectInfo native_send_object_info(MtpObjectInfo mtpObjectInfo);\n\n private native int native_submit_event_request() throws IOException;\n\n static {\n System.loadLibrary(\"media_jni\");\n }\n\n public MtpDevice(UsbDevice device) {\n Preconditions.checkNotNull(device);\n this.mDevice = device;\n }\n\n public boolean open(UsbDeviceConnection connection) {\n boolean result = false;\n Context context = connection.getContext();\n synchronized (this.mLock) {\n if (context != null) {\n if (!((UserManager) context.getSystemService(Context.USER_SERVICE)).hasUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER)) {\n result = native_open(this.mDevice.getDeviceName(), connection.getFileDescriptor());\n }\n }\n if (result) {\n this.mConnection = connection;\n this.mCloseGuard.open(\"close\");\n } else {\n connection.close();\n }\n }\n return result;\n }\n\n public void close() {\n synchronized (this.mLock) {\n if (this.mConnection != null) {\n this.mCloseGuard.close();\n native_close();\n this.mConnection.close();\n this.mConnection = null;\n }\n }\n }\n\n protected void finalize() throws Throwable {\n try {\n if (this.mCloseGuard != null) {\n this.mCloseGuard.warnIfOpen();\n }\n close();\n } finally {\n super.finalize();\n }\n }\n\n public String getDeviceName() {\n return this.mDevice.getDeviceName();\n }\n\n public int getDeviceId() {\n return this.mDevice.getDeviceId();\n }\n\n public String toString() {\n return this.mDevice.getDeviceName();\n }\n\n public MtpDeviceInfo getDeviceInfo() {\n return native_get_device_info();\n }\n\n public int[] getStorageIds() {\n return native_get_storage_ids();\n }\n\n public int[] getObjectHandles(int storageId, int format, int objectHandle) {\n return native_get_object_handles(storageId, format, objectHandle);\n }\n\n public byte[] getObject(int objectHandle, int objectSize) {\n Preconditions.checkArgumentNonnegative(objectSize, \"objectSize should not be negative\");\n return native_get_object(objectHandle, (long) objectSize);\n }\n\n public long getPartialObject(int objectHandle, long offset, long size, byte[] buffer) throws IOException {\n return native_get_partial_object(objectHandle, offset, size, buffer);\n }\n\n public long getPartialObject64(int objectHandle, long offset, long size, byte[] buffer) throws IOException {\n return (long) native_get_partial_object_64(objectHandle, offset, size, buffer);\n }\n\n public byte[] getThumbnail(int objectHandle) {\n return native_get_thumbnail(objectHandle);\n }\n\n public MtpStorageInfo getStorageInfo(int storageId) {\n return native_get_storage_info(storageId);\n }\n\n public MtpObjectInfo getObjectInfo(int objectHandle) {\n return native_get_object_info(objectHandle);\n }\n\n public boolean deleteObject(int objectHandle) {\n return native_delete_object(objectHandle);\n }\n\n public long getParent(int objectHandle) {\n return (long) native_get_parent(objectHandle);\n }\n\n public long getStorageId(int objectHandle) {\n return (long) native_get_storage_id(objectHandle);\n }\n\n public boolean importFile(int objectHandle, String destPath) {\n return native_import_file(objectHandle, destPath);\n }\n\n public boolean importFile(int objectHandle, ParcelFileDescriptor descriptor) {\n return native_import_file(objectHandle, descriptor.getFd());\n }\n\n public boolean sendObject(int objectHandle, long size, ParcelFileDescriptor descriptor) {\n return native_send_object(objectHandle, size, descriptor.getFd());\n }\n\n public MtpObjectInfo sendObjectInfo(MtpObjectInfo info) {\n return native_send_object_info(info);\n }\n\n public MtpEvent readEvent(CancellationSignal signal) throws IOException {\n boolean z = false;\n final int handle = native_submit_event_request();\n if (handle >= 0) {\n z = true;\n }\n Preconditions.checkState(z, \"Other thread is reading an event.\");\n if (signal != null) {\n signal.setOnCancelListener(new OnCancelListener() {\n\n public void onCancel() {\n MtpDevice.this.native_discard_event_request(handle);\n }\n });\n }\n ", "post_mask_code": "\n }\n\n public long getObjectSizeLong(int handle, int format) throws IOException {\n return native_get_object_size_long(handle, format);\n }\n}\n"} {"task_id": "Java_2117", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/flink/flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/src/assigners/LocalityAwareSplitAssigner.java", "mask_start_position": 7391, "mask_end_position": 7428, "canonical_solution": "public String[] getNormalizedHosts() ", "pre_mask_code": "package org.apache.flink.connector.file.src.assigners;\n\nimport org.apache.flink.annotation.PublicEvolving;\nimport org.apache.flink.annotation.VisibleForTesting;\nimport org.apache.flink.connector.file.src.FileSourceSplit;\nimport org.apache.flink.metrics.SimpleCounter;\nimport org.apache.flink.util.MathUtils;\nimport org.apache.flink.util.NetUtils;\nimport org.apache.flink.util.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport javax.annotation.Nullable;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.Locale;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport static org.apache.flink.util.Preconditions.checkState;\n\n/**\n * A {@link FileSplitAssigner} that assigns to each host preferably splits that are local, before\n * assigning splits that are not local.\n *\n *

Implementation Note: This class is an adjusted copy of the previous API's class {@link\n * org.apache.flink.api.common.io.LocatableInputSplitAssigner} and reproduces the same assignment\n * logic, for compatibility. The logic has not been changed or optimized.\n */\n@PublicEvolving\npublic class LocalityAwareSplitAssigner implements FileSplitAssigner {\n\n private static final Logger LOG = LoggerFactory.getLogger(LocalityAwareSplitAssigner.class);\n\n /**\n * All unassigned input splits.\n */\n private final HashSet unassigned = new HashSet<>();\n\n /**\n * Input splits indexed by host for local assignment.\n */\n private final HashMap localPerHost = new HashMap<>();\n\n /**\n * Unassigned splits for remote assignment.\n */\n private final LocatableSplitChooser remoteSplitChooser;\n\n private final SimpleCounter localAssignments;\n\n private final SimpleCounter remoteAssignments;\n\n public LocalityAwareSplitAssigner(Collection splits) {\n for (FileSourceSplit split : splits) {\n this.unassigned.add(new SplitWithInfo(split));\n }\n this.remoteSplitChooser = new LocatableSplitChooser(unassigned);\n // this will be replaced with metrics registration once we can expose the metric group\n // properly to the assigners\n this.localAssignments = new SimpleCounter();\n this.remoteAssignments = new SimpleCounter();\n }\n\n @Override\n public Optional getNext(@Nullable String host) {\n // for a null host, we always return a remote split\n if (StringUtils.isNullOrWhitespaceOnly(host)) {\n final Optional split = getRemoteSplit();\n if (split.isPresent()) {\n LOG.info(\"Assigning split to non-localized request: {}\", split);\n }\n return split;\n }\n host = normalizeHostName(host);\n // for any non-null host, we take the list of non-null splits\n final LocatableSplitChooser localSplits = localPerHost.computeIfAbsent(host, (theHost) -> buildChooserForHost(theHost, unassigned));\n final SplitWithInfo localSplit = localSplits.getNextUnassignedMinLocalCountSplit(unassigned);\n if (localSplit != null) {\n checkState(unassigned.remove(localSplit), \"Selected split has already been assigned. This should not happen!\");\n LOG.info(\"Assigning local split to requesting host '{}': {}\", host, localSplit.getSplit());\n localAssignments.inc();\n return Optional.of(localSplit.getSplit());\n }\n // we did not find a local split, return a remote split\n final Optional remoteSplit = getRemoteSplit();\n if (remoteSplit.isPresent()) {\n LOG.info(\"Assigning remote split to requesting host '{}': {}\", host, remoteSplit);\n }\n return remoteSplit;\n }\n\n @Override\n public void addSplits(Collection splits) {\n for (FileSourceSplit split : splits) {\n SplitWithInfo sc = new SplitWithInfo(split);\n remoteSplitChooser.addInputSplit(sc);\n unassigned.add(sc);\n }\n }\n\n @Override\n public Collection remainingSplits() {\n return unassigned.stream().map(SplitWithInfo::getSplit).collect(Collectors.toList());\n }\n\n private Optional getRemoteSplit() {\n final SplitWithInfo split = remoteSplitChooser.getNextUnassignedMinLocalCountSplit(unassigned);\n if (split == null) {\n return Optional.empty();\n }\n checkState(unassigned.remove(split), \"Selected split has already been assigned. This should not happen!\");\n remoteAssignments.inc();\n return Optional.of(split.getSplit());\n }\n\n @VisibleForTesting\n int getNumberOfLocalAssignments() {\n return MathUtils.checkedDownCast(localAssignments.getCount());\n }\n\n @VisibleForTesting\n int getNumberOfRemoteAssignments() {\n return MathUtils.checkedDownCast(remoteAssignments.getCount());\n }\n\n static String normalizeHostName(String hostName) {\n return hostName == null ? null : NetUtils.getHostnameFromFQDN(hostName).toLowerCase(Locale.US);\n }\n\n static String[] normalizeHostNames(String[] hostNames) {\n if (hostNames == null) {\n return null;\n }\n final String[] normalizedHostNames = new String[hostNames.length];\n boolean changed = false;\n for (int i = 0; i < hostNames.length; i++) {\n final String original = hostNames[i];\n final String normalized = normalizeHostName(original);\n normalizedHostNames[i] = normalized;\n // noinspection StringEquality\n changed |= (original != normalized);\n }\n return changed ? normalizedHostNames : hostNames;\n }\n\n private static boolean isLocal(String flinkHost, String[] hosts) {\n if (flinkHost == null || hosts == null) {\n return false;\n }\n for (String h : hosts) {\n if (h != null && h.equals(flinkHost)) {\n return true;\n }\n }\n return false;\n }\n\n private static LocatableSplitChooser buildChooserForHost(String host, Set splits) {\n final LocatableSplitChooser newChooser = new LocatableSplitChooser();\n for (SplitWithInfo splitWithInfo : splits) {\n if (isLocal(host, splitWithInfo.getNormalizedHosts())) {\n splitWithInfo.incrementLocalCount();\n newChooser.addInputSplit(splitWithInfo);\n }\n }\n return newChooser;\n }\n\n /**\n * Wraps a LocatableInputSplit and adds a count for the number of observed hosts that can access\n * the split locally.\n */\n private static class SplitWithInfo {\n\n private final FileSourceSplit split;\n\n private final String[] normalizedHosts;\n\n private int localCount;\n\n public SplitWithInfo(FileSourceSplit split) {\n this.split = split;\n this.normalizedHosts = normalizeHostNames(split.hostnames());\n this.localCount = 0;\n }\n\n public void incrementLocalCount() {\n this.localCount++;\n }\n\n public int getLocalCount() {\n return localCount;\n }\n\n public FileSourceSplit getSplit() {\n return split;\n }\n\n ", "post_mask_code": "{\n return normalizedHosts;\n }\n }\n\n /**\n * Holds a list of LocatableInputSplits and returns the split with the lowest local count. The\n * rational is that splits which are local on few hosts should be preferred over others which\n * have more degrees of freedom for local assignment.\n *\n *

Internally, the splits are stored in a linked list. Sorting the list is not a good\n * solution, as local counts are updated whenever a previously unseen host requests a split.\n * Instead, we track the minimum local count and iteratively look for splits with that minimum\n * count.\n */\n private static class LocatableSplitChooser {\n\n /**\n * list of all input splits.\n */\n private final LinkedList splits = new LinkedList<>();\n\n /**\n * The current minimum local count. We look for splits with this local count.\n */\n private int minLocalCount = -1;\n\n /**\n * The second smallest count observed so far.\n */\n private int nextMinLocalCount = -1;\n\n /**\n * number of elements we need to inspect for the minimum local count.\n */\n private int elementCycleCount = 0;\n\n LocatableSplitChooser() {\n }\n\n LocatableSplitChooser(Collection splits) {\n for (SplitWithInfo split : splits) {\n addInputSplit(split);\n }\n }\n\n /**\n * Adds a single input split.\n */\n void addInputSplit(SplitWithInfo split) {\n int localCount = split.getLocalCount();\n if (minLocalCount == -1) {\n // first split to add\n this.minLocalCount = localCount;\n this.elementCycleCount = 1;\n this.splits.offerFirst(split);\n } else if (localCount < minLocalCount) {\n // split with new min local count\n this.nextMinLocalCount = this.minLocalCount;\n this.minLocalCount = localCount;\n // all other splits have more local host than this one\n this.elementCycleCount = 1;\n splits.offerFirst(split);\n } else if (localCount == minLocalCount) {\n this.elementCycleCount++;\n this.splits.offerFirst(split);\n } else {\n if (localCount < nextMinLocalCount) {\n nextMinLocalCount = localCount;\n }\n splits.offerLast(split);\n }\n }\n\n /**\n * Retrieves a LocatableInputSplit with minimum local count. InputSplits which have already\n * been assigned (i.e., which are not contained in the provided set) are filtered out. The\n * returned input split is NOT removed from the provided set.\n *\n * @param unassignedSplits Set of unassigned input splits.\n * @return An input split with minimum local count or null if all splits have been assigned.\n */\n @Nullable\n SplitWithInfo getNextUnassignedMinLocalCountSplit(Set unassignedSplits) {\n if (splits.size() == 0) {\n return null;\n }\n do {\n elementCycleCount--;\n // take first split of the list\n SplitWithInfo split = splits.pollFirst();\n if (unassignedSplits.contains(split)) {\n int localCount = split.getLocalCount();\n // still unassigned, check local count\n if (localCount > minLocalCount) {\n // re-insert at end of the list and continue to look for split with smaller\n // local count\n splits.offerLast(split);\n // check and update second smallest local count\n if (nextMinLocalCount == -1 || split.getLocalCount() < nextMinLocalCount) {\n nextMinLocalCount = split.getLocalCount();\n }\n split = null;\n }\n } else {\n // split was already assigned\n split = null;\n }\n if (elementCycleCount == 0) {\n // one full cycle, but no split with min local count found\n // update minLocalCnt and element cycle count for next pass over the splits\n minLocalCount = nextMinLocalCount;\n nextMinLocalCount = -1;\n elementCycleCount = splits.size();\n }\n if (split != null) {\n // found a split to assign\n return split;\n }\n } while (elementCycleCount > 0);\n // no split left\n return null;\n }\n }\n}\n"} {"task_id": "Java_2118", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/flink/flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/src/assigners/LocalityAwareSplitAssigner.java", "mask_start_position": 7428, "mask_end_position": 7475, "canonical_solution": "{\n return normalizedHosts;\n }", "pre_mask_code": "package org.apache.flink.connector.file.src.assigners;\n\nimport org.apache.flink.annotation.PublicEvolving;\nimport org.apache.flink.annotation.VisibleForTesting;\nimport org.apache.flink.connector.file.src.FileSourceSplit;\nimport org.apache.flink.metrics.SimpleCounter;\nimport org.apache.flink.util.MathUtils;\nimport org.apache.flink.util.NetUtils;\nimport org.apache.flink.util.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport javax.annotation.Nullable;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.Locale;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport static org.apache.flink.util.Preconditions.checkState;\n\n/**\n * A {@link FileSplitAssigner} that assigns to each host preferably splits that are local, before\n * assigning splits that are not local.\n *\n *

Implementation Note: This class is an adjusted copy of the previous API's class {@link\n * org.apache.flink.api.common.io.LocatableInputSplitAssigner} and reproduces the same assignment\n * logic, for compatibility. The logic has not been changed or optimized.\n */\n@PublicEvolving\npublic class LocalityAwareSplitAssigner implements FileSplitAssigner {\n\n private static final Logger LOG = LoggerFactory.getLogger(LocalityAwareSplitAssigner.class);\n\n /**\n * All unassigned input splits.\n */\n private final HashSet unassigned = new HashSet<>();\n\n /**\n * Input splits indexed by host for local assignment.\n */\n private final HashMap localPerHost = new HashMap<>();\n\n /**\n * Unassigned splits for remote assignment.\n */\n private final LocatableSplitChooser remoteSplitChooser;\n\n private final SimpleCounter localAssignments;\n\n private final SimpleCounter remoteAssignments;\n\n public LocalityAwareSplitAssigner(Collection splits) {\n for (FileSourceSplit split : splits) {\n this.unassigned.add(new SplitWithInfo(split));\n }\n this.remoteSplitChooser = new LocatableSplitChooser(unassigned);\n // this will be replaced with metrics registration once we can expose the metric group\n // properly to the assigners\n this.localAssignments = new SimpleCounter();\n this.remoteAssignments = new SimpleCounter();\n }\n\n @Override\n public Optional getNext(@Nullable String host) {\n // for a null host, we always return a remote split\n if (StringUtils.isNullOrWhitespaceOnly(host)) {\n final Optional split = getRemoteSplit();\n if (split.isPresent()) {\n LOG.info(\"Assigning split to non-localized request: {}\", split);\n }\n return split;\n }\n host = normalizeHostName(host);\n // for any non-null host, we take the list of non-null splits\n final LocatableSplitChooser localSplits = localPerHost.computeIfAbsent(host, (theHost) -> buildChooserForHost(theHost, unassigned));\n final SplitWithInfo localSplit = localSplits.getNextUnassignedMinLocalCountSplit(unassigned);\n if (localSplit != null) {\n checkState(unassigned.remove(localSplit), \"Selected split has already been assigned. This should not happen!\");\n LOG.info(\"Assigning local split to requesting host '{}': {}\", host, localSplit.getSplit());\n localAssignments.inc();\n return Optional.of(localSplit.getSplit());\n }\n // we did not find a local split, return a remote split\n final Optional remoteSplit = getRemoteSplit();\n if (remoteSplit.isPresent()) {\n LOG.info(\"Assigning remote split to requesting host '{}': {}\", host, remoteSplit);\n }\n return remoteSplit;\n }\n\n @Override\n public void addSplits(Collection splits) {\n for (FileSourceSplit split : splits) {\n SplitWithInfo sc = new SplitWithInfo(split);\n remoteSplitChooser.addInputSplit(sc);\n unassigned.add(sc);\n }\n }\n\n @Override\n public Collection remainingSplits() {\n return unassigned.stream().map(SplitWithInfo::getSplit).collect(Collectors.toList());\n }\n\n private Optional getRemoteSplit() {\n final SplitWithInfo split = remoteSplitChooser.getNextUnassignedMinLocalCountSplit(unassigned);\n if (split == null) {\n return Optional.empty();\n }\n checkState(unassigned.remove(split), \"Selected split has already been assigned. This should not happen!\");\n remoteAssignments.inc();\n return Optional.of(split.getSplit());\n }\n\n @VisibleForTesting\n int getNumberOfLocalAssignments() {\n return MathUtils.checkedDownCast(localAssignments.getCount());\n }\n\n @VisibleForTesting\n int getNumberOfRemoteAssignments() {\n return MathUtils.checkedDownCast(remoteAssignments.getCount());\n }\n\n static String normalizeHostName(String hostName) {\n return hostName == null ? null : NetUtils.getHostnameFromFQDN(hostName).toLowerCase(Locale.US);\n }\n\n static String[] normalizeHostNames(String[] hostNames) {\n if (hostNames == null) {\n return null;\n }\n final String[] normalizedHostNames = new String[hostNames.length];\n boolean changed = false;\n for (int i = 0; i < hostNames.length; i++) {\n final String original = hostNames[i];\n final String normalized = normalizeHostName(original);\n normalizedHostNames[i] = normalized;\n // noinspection StringEquality\n changed |= (original != normalized);\n }\n return changed ? normalizedHostNames : hostNames;\n }\n\n private static boolean isLocal(String flinkHost, String[] hosts) {\n if (flinkHost == null || hosts == null) {\n return false;\n }\n for (String h : hosts) {\n if (h != null && h.equals(flinkHost)) {\n return true;\n }\n }\n return false;\n }\n\n private static LocatableSplitChooser buildChooserForHost(String host, Set splits) {\n final LocatableSplitChooser newChooser = new LocatableSplitChooser();\n for (SplitWithInfo splitWithInfo : splits) {\n if (isLocal(host, splitWithInfo.getNormalizedHosts())) {\n splitWithInfo.incrementLocalCount();\n newChooser.addInputSplit(splitWithInfo);\n }\n }\n return newChooser;\n }\n\n /**\n * Wraps a LocatableInputSplit and adds a count for the number of observed hosts that can access\n * the split locally.\n */\n private static class SplitWithInfo {\n\n private final FileSourceSplit split;\n\n private final String[] normalizedHosts;\n\n private int localCount;\n\n public SplitWithInfo(FileSourceSplit split) {\n this.split = split;\n this.normalizedHosts = normalizeHostNames(split.hostnames());\n this.localCount = 0;\n }\n\n public void incrementLocalCount() {\n this.localCount++;\n }\n\n public int getLocalCount() {\n return localCount;\n }\n\n public FileSourceSplit getSplit() {\n return split;\n }\n\n public String[] getNormalizedHosts() ", "post_mask_code": "\n }\n\n /**\n * Holds a list of LocatableInputSplits and returns the split with the lowest local count. The\n * rational is that splits which are local on few hosts should be preferred over others which\n * have more degrees of freedom for local assignment.\n *\n *

Internally, the splits are stored in a linked list. Sorting the list is not a good\n * solution, as local counts are updated whenever a previously unseen host requests a split.\n * Instead, we track the minimum local count and iteratively look for splits with that minimum\n * count.\n */\n private static class LocatableSplitChooser {\n\n /**\n * list of all input splits.\n */\n private final LinkedList splits = new LinkedList<>();\n\n /**\n * The current minimum local count. We look for splits with this local count.\n */\n private int minLocalCount = -1;\n\n /**\n * The second smallest count observed so far.\n */\n private int nextMinLocalCount = -1;\n\n /**\n * number of elements we need to inspect for the minimum local count.\n */\n private int elementCycleCount = 0;\n\n LocatableSplitChooser() {\n }\n\n LocatableSplitChooser(Collection splits) {\n for (SplitWithInfo split : splits) {\n addInputSplit(split);\n }\n }\n\n /**\n * Adds a single input split.\n */\n void addInputSplit(SplitWithInfo split) {\n int localCount = split.getLocalCount();\n if (minLocalCount == -1) {\n // first split to add\n this.minLocalCount = localCount;\n this.elementCycleCount = 1;\n this.splits.offerFirst(split);\n } else if (localCount < minLocalCount) {\n // split with new min local count\n this.nextMinLocalCount = this.minLocalCount;\n this.minLocalCount = localCount;\n // all other splits have more local host than this one\n this.elementCycleCount = 1;\n splits.offerFirst(split);\n } else if (localCount == minLocalCount) {\n this.elementCycleCount++;\n this.splits.offerFirst(split);\n } else {\n if (localCount < nextMinLocalCount) {\n nextMinLocalCount = localCount;\n }\n splits.offerLast(split);\n }\n }\n\n /**\n * Retrieves a LocatableInputSplit with minimum local count. InputSplits which have already\n * been assigned (i.e., which are not contained in the provided set) are filtered out. The\n * returned input split is NOT removed from the provided set.\n *\n * @param unassignedSplits Set of unassigned input splits.\n * @return An input split with minimum local count or null if all splits have been assigned.\n */\n @Nullable\n SplitWithInfo getNextUnassignedMinLocalCountSplit(Set unassignedSplits) {\n if (splits.size() == 0) {\n return null;\n }\n do {\n elementCycleCount--;\n // take first split of the list\n SplitWithInfo split = splits.pollFirst();\n if (unassignedSplits.contains(split)) {\n int localCount = split.getLocalCount();\n // still unassigned, check local count\n if (localCount > minLocalCount) {\n // re-insert at end of the list and continue to look for split with smaller\n // local count\n splits.offerLast(split);\n // check and update second smallest local count\n if (nextMinLocalCount == -1 || split.getLocalCount() < nextMinLocalCount) {\n nextMinLocalCount = split.getLocalCount();\n }\n split = null;\n }\n } else {\n // split was already assigned\n split = null;\n }\n if (elementCycleCount == 0) {\n // one full cycle, but no split with min local count found\n // update minLocalCnt and element cycle count for next pass over the splits\n minLocalCount = nextMinLocalCount;\n nextMinLocalCount = -1;\n elementCycleCount = splits.size();\n }\n if (split != null) {\n // found a split to assign\n return split;\n }\n } while (elementCycleCount > 0);\n // no split left\n return null;\n }\n }\n}\n"} {"task_id": "Java_2119", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/flink/flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/src/assigners/LocalityAwareSplitAssigner.java", "mask_start_position": 7361, "mask_end_position": 7371, "canonical_solution": "urn split;", "pre_mask_code": "package org.apache.flink.connector.file.src.assigners;\n\nimport org.apache.flink.annotation.PublicEvolving;\nimport org.apache.flink.annotation.VisibleForTesting;\nimport org.apache.flink.connector.file.src.FileSourceSplit;\nimport org.apache.flink.metrics.SimpleCounter;\nimport org.apache.flink.util.MathUtils;\nimport org.apache.flink.util.NetUtils;\nimport org.apache.flink.util.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport javax.annotation.Nullable;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.Locale;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport static org.apache.flink.util.Preconditions.checkState;\n\n/**\n * A {@link FileSplitAssigner} that assigns to each host preferably splits that are local, before\n * assigning splits that are not local.\n *\n *

Implementation Note: This class is an adjusted copy of the previous API's class {@link\n * org.apache.flink.api.common.io.LocatableInputSplitAssigner} and reproduces the same assignment\n * logic, for compatibility. The logic has not been changed or optimized.\n */\n@PublicEvolving\npublic class LocalityAwareSplitAssigner implements FileSplitAssigner {\n\n private static final Logger LOG = LoggerFactory.getLogger(LocalityAwareSplitAssigner.class);\n\n /**\n * All unassigned input splits.\n */\n private final HashSet unassigned = new HashSet<>();\n\n /**\n * Input splits indexed by host for local assignment.\n */\n private final HashMap localPerHost = new HashMap<>();\n\n /**\n * Unassigned splits for remote assignment.\n */\n private final LocatableSplitChooser remoteSplitChooser;\n\n private final SimpleCounter localAssignments;\n\n private final SimpleCounter remoteAssignments;\n\n public LocalityAwareSplitAssigner(Collection splits) {\n for (FileSourceSplit split : splits) {\n this.unassigned.add(new SplitWithInfo(split));\n }\n this.remoteSplitChooser = new LocatableSplitChooser(unassigned);\n // this will be replaced with metrics registration once we can expose the metric group\n // properly to the assigners\n this.localAssignments = new SimpleCounter();\n this.remoteAssignments = new SimpleCounter();\n }\n\n @Override\n public Optional getNext(@Nullable String host) {\n // for a null host, we always return a remote split\n if (StringUtils.isNullOrWhitespaceOnly(host)) {\n final Optional split = getRemoteSplit();\n if (split.isPresent()) {\n LOG.info(\"Assigning split to non-localized request: {}\", split);\n }\n return split;\n }\n host = normalizeHostName(host);\n // for any non-null host, we take the list of non-null splits\n final LocatableSplitChooser localSplits = localPerHost.computeIfAbsent(host, (theHost) -> buildChooserForHost(theHost, unassigned));\n final SplitWithInfo localSplit = localSplits.getNextUnassignedMinLocalCountSplit(unassigned);\n if (localSplit != null) {\n checkState(unassigned.remove(localSplit), \"Selected split has already been assigned. This should not happen!\");\n LOG.info(\"Assigning local split to requesting host '{}': {}\", host, localSplit.getSplit());\n localAssignments.inc();\n return Optional.of(localSplit.getSplit());\n }\n // we did not find a local split, return a remote split\n final Optional remoteSplit = getRemoteSplit();\n if (remoteSplit.isPresent()) {\n LOG.info(\"Assigning remote split to requesting host '{}': {}\", host, remoteSplit);\n }\n return remoteSplit;\n }\n\n @Override\n public void addSplits(Collection splits) {\n for (FileSourceSplit split : splits) {\n SplitWithInfo sc = new SplitWithInfo(split);\n remoteSplitChooser.addInputSplit(sc);\n unassigned.add(sc);\n }\n }\n\n @Override\n public Collection remainingSplits() {\n return unassigned.stream().map(SplitWithInfo::getSplit).collect(Collectors.toList());\n }\n\n private Optional getRemoteSplit() {\n final SplitWithInfo split = remoteSplitChooser.getNextUnassignedMinLocalCountSplit(unassigned);\n if (split == null) {\n return Optional.empty();\n }\n checkState(unassigned.remove(split), \"Selected split has already been assigned. This should not happen!\");\n remoteAssignments.inc();\n return Optional.of(split.getSplit());\n }\n\n @VisibleForTesting\n int getNumberOfLocalAssignments() {\n return MathUtils.checkedDownCast(localAssignments.getCount());\n }\n\n @VisibleForTesting\n int getNumberOfRemoteAssignments() {\n return MathUtils.checkedDownCast(remoteAssignments.getCount());\n }\n\n static String normalizeHostName(String hostName) {\n return hostName == null ? null : NetUtils.getHostnameFromFQDN(hostName).toLowerCase(Locale.US);\n }\n\n static String[] normalizeHostNames(String[] hostNames) {\n if (hostNames == null) {\n return null;\n }\n final String[] normalizedHostNames = new String[hostNames.length];\n boolean changed = false;\n for (int i = 0; i < hostNames.length; i++) {\n final String original = hostNames[i];\n final String normalized = normalizeHostName(original);\n normalizedHostNames[i] = normalized;\n // noinspection StringEquality\n changed |= (original != normalized);\n }\n return changed ? normalizedHostNames : hostNames;\n }\n\n private static boolean isLocal(String flinkHost, String[] hosts) {\n if (flinkHost == null || hosts == null) {\n return false;\n }\n for (String h : hosts) {\n if (h != null && h.equals(flinkHost)) {\n return true;\n }\n }\n return false;\n }\n\n private static LocatableSplitChooser buildChooserForHost(String host, Set splits) {\n final LocatableSplitChooser newChooser = new LocatableSplitChooser();\n for (SplitWithInfo splitWithInfo : splits) {\n if (isLocal(host, splitWithInfo.getNormalizedHosts())) {\n splitWithInfo.incrementLocalCount();\n newChooser.addInputSplit(splitWithInfo);\n }\n }\n return newChooser;\n }\n\n /**\n * Wraps a LocatableInputSplit and adds a count for the number of observed hosts that can access\n * the split locally.\n */\n private static class SplitWithInfo {\n\n private final FileSourceSplit split;\n\n private final String[] normalizedHosts;\n\n private int localCount;\n\n public SplitWithInfo(FileSourceSplit split) {\n this.split = split;\n this.normalizedHosts = normalizeHostNames(split.hostnames());\n this.localCount = 0;\n }\n\n public void incrementLocalCount() {\n this.localCount++;\n }\n\n public int getLocalCount() {\n return localCount;\n }\n\n public FileSourceSplit getSplit() {\n ret", "post_mask_code": "\n }\n\n public String[] getNormalizedHosts() {\n return normalizedHosts;\n }\n }\n\n /**\n * Holds a list of LocatableInputSplits and returns the split with the lowest local count. The\n * rational is that splits which are local on few hosts should be preferred over others which\n * have more degrees of freedom for local assignment.\n *\n *

Internally, the splits are stored in a linked list. Sorting the list is not a good\n * solution, as local counts are updated whenever a previously unseen host requests a split.\n * Instead, we track the minimum local count and iteratively look for splits with that minimum\n * count.\n */\n private static class LocatableSplitChooser {\n\n /**\n * list of all input splits.\n */\n private final LinkedList splits = new LinkedList<>();\n\n /**\n * The current minimum local count. We look for splits with this local count.\n */\n private int minLocalCount = -1;\n\n /**\n * The second smallest count observed so far.\n */\n private int nextMinLocalCount = -1;\n\n /**\n * number of elements we need to inspect for the minimum local count.\n */\n private int elementCycleCount = 0;\n\n LocatableSplitChooser() {\n }\n\n LocatableSplitChooser(Collection splits) {\n for (SplitWithInfo split : splits) {\n addInputSplit(split);\n }\n }\n\n /**\n * Adds a single input split.\n */\n void addInputSplit(SplitWithInfo split) {\n int localCount = split.getLocalCount();\n if (minLocalCount == -1) {\n // first split to add\n this.minLocalCount = localCount;\n this.elementCycleCount = 1;\n this.splits.offerFirst(split);\n } else if (localCount < minLocalCount) {\n // split with new min local count\n this.nextMinLocalCount = this.minLocalCount;\n this.minLocalCount = localCount;\n // all other splits have more local host than this one\n this.elementCycleCount = 1;\n splits.offerFirst(split);\n } else if (localCount == minLocalCount) {\n this.elementCycleCount++;\n this.splits.offerFirst(split);\n } else {\n if (localCount < nextMinLocalCount) {\n nextMinLocalCount = localCount;\n }\n splits.offerLast(split);\n }\n }\n\n /**\n * Retrieves a LocatableInputSplit with minimum local count. InputSplits which have already\n * been assigned (i.e., which are not contained in the provided set) are filtered out. The\n * returned input split is NOT removed from the provided set.\n *\n * @param unassignedSplits Set of unassigned input splits.\n * @return An input split with minimum local count or null if all splits have been assigned.\n */\n @Nullable\n SplitWithInfo getNextUnassignedMinLocalCountSplit(Set unassignedSplits) {\n if (splits.size() == 0) {\n return null;\n }\n do {\n elementCycleCount--;\n // take first split of the list\n SplitWithInfo split = splits.pollFirst();\n if (unassignedSplits.contains(split)) {\n int localCount = split.getLocalCount();\n // still unassigned, check local count\n if (localCount > minLocalCount) {\n // re-insert at end of the list and continue to look for split with smaller\n // local count\n splits.offerLast(split);\n // check and update second smallest local count\n if (nextMinLocalCount == -1 || split.getLocalCount() < nextMinLocalCount) {\n nextMinLocalCount = split.getLocalCount();\n }\n split = null;\n }\n } else {\n // split was already assigned\n split = null;\n }\n if (elementCycleCount == 0) {\n // one full cycle, but no split with min local count found\n // update minLocalCnt and element cycle count for next pass over the splits\n minLocalCount = nextMinLocalCount;\n nextMinLocalCount = -1;\n elementCycleCount = splits.size();\n }\n if (split != null) {\n // found a split to assign\n return split;\n }\n } while (elementCycleCount > 0);\n // no split left\n return null;\n }\n }\n}\n"} {"task_id": "Java_2120", "language": "Java", "task_type": "for_statement", "source_file": "java/github/apache/flink/flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/src/assigners/LocalityAwareSplitAssigner.java", "mask_start_position": 5447, "mask_end_position": 5759, "canonical_solution": "for (int i = 0; i < hostNames.length; i++) {\n final String original = hostNames[i];\n final String normalized = normalizeHostName(original);\n normalizedHostNames[i] = normalized;\n // noinspection StringEquality\n changed |= (original != normalized);\n }", "pre_mask_code": "package org.apache.flink.connector.file.src.assigners;\n\nimport org.apache.flink.annotation.PublicEvolving;\nimport org.apache.flink.annotation.VisibleForTesting;\nimport org.apache.flink.connector.file.src.FileSourceSplit;\nimport org.apache.flink.metrics.SimpleCounter;\nimport org.apache.flink.util.MathUtils;\nimport org.apache.flink.util.NetUtils;\nimport org.apache.flink.util.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport javax.annotation.Nullable;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.Locale;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport static org.apache.flink.util.Preconditions.checkState;\n\n/**\n * A {@link FileSplitAssigner} that assigns to each host preferably splits that are local, before\n * assigning splits that are not local.\n *\n *

Implementation Note: This class is an adjusted copy of the previous API's class {@link\n * org.apache.flink.api.common.io.LocatableInputSplitAssigner} and reproduces the same assignment\n * logic, for compatibility. The logic has not been changed or optimized.\n */\n@PublicEvolving\npublic class LocalityAwareSplitAssigner implements FileSplitAssigner {\n\n private static final Logger LOG = LoggerFactory.getLogger(LocalityAwareSplitAssigner.class);\n\n /**\n * All unassigned input splits.\n */\n private final HashSet unassigned = new HashSet<>();\n\n /**\n * Input splits indexed by host for local assignment.\n */\n private final HashMap localPerHost = new HashMap<>();\n\n /**\n * Unassigned splits for remote assignment.\n */\n private final LocatableSplitChooser remoteSplitChooser;\n\n private final SimpleCounter localAssignments;\n\n private final SimpleCounter remoteAssignments;\n\n public LocalityAwareSplitAssigner(Collection splits) {\n for (FileSourceSplit split : splits) {\n this.unassigned.add(new SplitWithInfo(split));\n }\n this.remoteSplitChooser = new LocatableSplitChooser(unassigned);\n // this will be replaced with metrics registration once we can expose the metric group\n // properly to the assigners\n this.localAssignments = new SimpleCounter();\n this.remoteAssignments = new SimpleCounter();\n }\n\n @Override\n public Optional getNext(@Nullable String host) {\n // for a null host, we always return a remote split\n if (StringUtils.isNullOrWhitespaceOnly(host)) {\n final Optional split = getRemoteSplit();\n if (split.isPresent()) {\n LOG.info(\"Assigning split to non-localized request: {}\", split);\n }\n return split;\n }\n host = normalizeHostName(host);\n // for any non-null host, we take the list of non-null splits\n final LocatableSplitChooser localSplits = localPerHost.computeIfAbsent(host, (theHost) -> buildChooserForHost(theHost, unassigned));\n final SplitWithInfo localSplit = localSplits.getNextUnassignedMinLocalCountSplit(unassigned);\n if (localSplit != null) {\n checkState(unassigned.remove(localSplit), \"Selected split has already been assigned. This should not happen!\");\n LOG.info(\"Assigning local split to requesting host '{}': {}\", host, localSplit.getSplit());\n localAssignments.inc();\n return Optional.of(localSplit.getSplit());\n }\n // we did not find a local split, return a remote split\n final Optional remoteSplit = getRemoteSplit();\n if (remoteSplit.isPresent()) {\n LOG.info(\"Assigning remote split to requesting host '{}': {}\", host, remoteSplit);\n }\n return remoteSplit;\n }\n\n @Override\n public void addSplits(Collection splits) {\n for (FileSourceSplit split : splits) {\n SplitWithInfo sc = new SplitWithInfo(split);\n remoteSplitChooser.addInputSplit(sc);\n unassigned.add(sc);\n }\n }\n\n @Override\n public Collection remainingSplits() {\n return unassigned.stream().map(SplitWithInfo::getSplit).collect(Collectors.toList());\n }\n\n private Optional getRemoteSplit() {\n final SplitWithInfo split = remoteSplitChooser.getNextUnassignedMinLocalCountSplit(unassigned);\n if (split == null) {\n return Optional.empty();\n }\n checkState(unassigned.remove(split), \"Selected split has already been assigned. This should not happen!\");\n remoteAssignments.inc();\n return Optional.of(split.getSplit());\n }\n\n @VisibleForTesting\n int getNumberOfLocalAssignments() {\n return MathUtils.checkedDownCast(localAssignments.getCount());\n }\n\n @VisibleForTesting\n int getNumberOfRemoteAssignments() {\n return MathUtils.checkedDownCast(remoteAssignments.getCount());\n }\n\n static String normalizeHostName(String hostName) {\n return hostName == null ? null : NetUtils.getHostnameFromFQDN(hostName).toLowerCase(Locale.US);\n }\n\n static String[] normalizeHostNames(String[] hostNames) {\n if (hostNames == null) {\n return null;\n }\n final String[] normalizedHostNames = new String[hostNames.length];\n boolean changed = false;\n ", "post_mask_code": "\n return changed ? normalizedHostNames : hostNames;\n }\n\n private static boolean isLocal(String flinkHost, String[] hosts) {\n if (flinkHost == null || hosts == null) {\n return false;\n }\n for (String h : hosts) {\n if (h != null && h.equals(flinkHost)) {\n return true;\n }\n }\n return false;\n }\n\n private static LocatableSplitChooser buildChooserForHost(String host, Set splits) {\n final LocatableSplitChooser newChooser = new LocatableSplitChooser();\n for (SplitWithInfo splitWithInfo : splits) {\n if (isLocal(host, splitWithInfo.getNormalizedHosts())) {\n splitWithInfo.incrementLocalCount();\n newChooser.addInputSplit(splitWithInfo);\n }\n }\n return newChooser;\n }\n\n /**\n * Wraps a LocatableInputSplit and adds a count for the number of observed hosts that can access\n * the split locally.\n */\n private static class SplitWithInfo {\n\n private final FileSourceSplit split;\n\n private final String[] normalizedHosts;\n\n private int localCount;\n\n public SplitWithInfo(FileSourceSplit split) {\n this.split = split;\n this.normalizedHosts = normalizeHostNames(split.hostnames());\n this.localCount = 0;\n }\n\n public void incrementLocalCount() {\n this.localCount++;\n }\n\n public int getLocalCount() {\n return localCount;\n }\n\n public FileSourceSplit getSplit() {\n return split;\n }\n\n public String[] getNormalizedHosts() {\n return normalizedHosts;\n }\n }\n\n /**\n * Holds a list of LocatableInputSplits and returns the split with the lowest local count. The\n * rational is that splits which are local on few hosts should be preferred over others which\n * have more degrees of freedom for local assignment.\n *\n *

Internally, the splits are stored in a linked list. Sorting the list is not a good\n * solution, as local counts are updated whenever a previously unseen host requests a split.\n * Instead, we track the minimum local count and iteratively look for splits with that minimum\n * count.\n */\n private static class LocatableSplitChooser {\n\n /**\n * list of all input splits.\n */\n private final LinkedList splits = new LinkedList<>();\n\n /**\n * The current minimum local count. We look for splits with this local count.\n */\n private int minLocalCount = -1;\n\n /**\n * The second smallest count observed so far.\n */\n private int nextMinLocalCount = -1;\n\n /**\n * number of elements we need to inspect for the minimum local count.\n */\n private int elementCycleCount = 0;\n\n LocatableSplitChooser() {\n }\n\n LocatableSplitChooser(Collection splits) {\n for (SplitWithInfo split : splits) {\n addInputSplit(split);\n }\n }\n\n /**\n * Adds a single input split.\n */\n void addInputSplit(SplitWithInfo split) {\n int localCount = split.getLocalCount();\n if (minLocalCount == -1) {\n // first split to add\n this.minLocalCount = localCount;\n this.elementCycleCount = 1;\n this.splits.offerFirst(split);\n } else if (localCount < minLocalCount) {\n // split with new min local count\n this.nextMinLocalCount = this.minLocalCount;\n this.minLocalCount = localCount;\n // all other splits have more local host than this one\n this.elementCycleCount = 1;\n splits.offerFirst(split);\n } else if (localCount == minLocalCount) {\n this.elementCycleCount++;\n this.splits.offerFirst(split);\n } else {\n if (localCount < nextMinLocalCount) {\n nextMinLocalCount = localCount;\n }\n splits.offerLast(split);\n }\n }\n\n /**\n * Retrieves a LocatableInputSplit with minimum local count. InputSplits which have already\n * been assigned (i.e., which are not contained in the provided set) are filtered out. The\n * returned input split is NOT removed from the provided set.\n *\n * @param unassignedSplits Set of unassigned input splits.\n * @return An input split with minimum local count or null if all splits have been assigned.\n */\n @Nullable\n SplitWithInfo getNextUnassignedMinLocalCountSplit(Set unassignedSplits) {\n if (splits.size() == 0) {\n return null;\n }\n do {\n elementCycleCount--;\n // take first split of the list\n SplitWithInfo split = splits.pollFirst();\n if (unassignedSplits.contains(split)) {\n int localCount = split.getLocalCount();\n // still unassigned, check local count\n if (localCount > minLocalCount) {\n // re-insert at end of the list and continue to look for split with smaller\n // local count\n splits.offerLast(split);\n // check and update second smallest local count\n if (nextMinLocalCount == -1 || split.getLocalCount() < nextMinLocalCount) {\n nextMinLocalCount = split.getLocalCount();\n }\n split = null;\n }\n } else {\n // split was already assigned\n split = null;\n }\n if (elementCycleCount == 0) {\n // one full cycle, but no split with min local count found\n // update minLocalCnt and element cycle count for next pass over the splits\n minLocalCount = nextMinLocalCount;\n nextMinLocalCount = -1;\n elementCycleCount = splits.size();\n }\n if (split != null) {\n // found a split to assign\n return split;\n }\n } while (elementCycleCount > 0);\n // no split left\n return null;\n }\n }\n}\n"} {"task_id": "Java_2121", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openmrs/openmrs-module-htmlformentry/api/src/main/java/org/openmrs/module/htmlformentry/handler/RepeatTagHandler.java", "mask_start_position": 1171, "mask_end_position": 1273, "canonical_solution": "@Override\n public void doEndTag(FormEntrySession session, PrintWriter out, Node parent, Node node) ", "pre_mask_code": "package org.openmrs.module.htmlformentry.handler;\n\nimport java.io.PrintWriter;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.openmrs.module.htmlformentry.FormEntrySession;\nimport org.openmrs.module.htmlformentry.action.RepeatControllerAction;\nimport org.w3c.dom.NamedNodeMap;\nimport org.w3c.dom.Node;\n\n/**\n * Currently not used--the {@code } tag is currently handled by\n * {@see org.openmrs.module.htmlformentry.HtmlFormEntryGenerator#applyRepeats(String)}.\n */\npublic abstract class RepeatTagHandler implements IteratingTagHandler {\n\n @Override\n public boolean doStartTag(FormEntrySession session, PrintWriter out, Node parent, Node node) {\n Map attributes = new HashMap();\n NamedNodeMap map = node.getAttributes();\n for (int i = 0; i < map.getLength(); ++i) {\n Node attribute = map.item(i);\n attributes.put(attribute.getNodeName(), attribute.getNodeValue());\n }\n setupBefore(session, attributes);\n session.getSubmissionController().startRepeat(getRepeatAction(session, attributes));\n // recurse to children\n return true;\n }\n\n ", "post_mask_code": "{\n session.getSubmissionController().endRepeat();\n }\n\n protected abstract void setupBefore(FormEntrySession session, Map attributes);\n\n protected abstract RepeatControllerAction getRepeatAction(FormEntrySession session, Map attributes);\n}\n"} {"task_id": "Java_2122", "language": "Java", "task_type": "method_body", "source_file": "java/github/openmrs/openmrs-module-htmlformentry/api/src/main/java/org/openmrs/module/htmlformentry/handler/RepeatTagHandler.java", "mask_start_position": 1273, "mask_end_position": 1335, "canonical_solution": "{\n session.getSubmissionController().endRepeat();\n }", "pre_mask_code": "package org.openmrs.module.htmlformentry.handler;\n\nimport java.io.PrintWriter;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.openmrs.module.htmlformentry.FormEntrySession;\nimport org.openmrs.module.htmlformentry.action.RepeatControllerAction;\nimport org.w3c.dom.NamedNodeMap;\nimport org.w3c.dom.Node;\n\n/**\n * Currently not used--the {@code } tag is currently handled by\n * {@see org.openmrs.module.htmlformentry.HtmlFormEntryGenerator#applyRepeats(String)}.\n */\npublic abstract class RepeatTagHandler implements IteratingTagHandler {\n\n @Override\n public boolean doStartTag(FormEntrySession session, PrintWriter out, Node parent, Node node) {\n Map attributes = new HashMap();\n NamedNodeMap map = node.getAttributes();\n for (int i = 0; i < map.getLength(); ++i) {\n Node attribute = map.item(i);\n attributes.put(attribute.getNodeName(), attribute.getNodeValue());\n }\n setupBefore(session, attributes);\n session.getSubmissionController().startRepeat(getRepeatAction(session, attributes));\n // recurse to children\n return true;\n }\n\n @Override\n public void doEndTag(FormEntrySession session, PrintWriter out, Node parent, Node node) ", "post_mask_code": "\n\n protected abstract void setupBefore(FormEntrySession session, Map attributes);\n\n protected abstract RepeatControllerAction getRepeatAction(FormEntrySession session, Map attributes);\n}\n"} {"task_id": "Java_2123", "language": "Java", "task_type": "single_line", "source_file": "java/github/openmrs/openmrs-module-htmlformentry/api/src/main/java/org/openmrs/module/htmlformentry/handler/RepeatTagHandler.java", "mask_start_position": 1308, "mask_end_position": 1329, "canonical_solution": "roller().endRepeat();", "pre_mask_code": "package org.openmrs.module.htmlformentry.handler;\n\nimport java.io.PrintWriter;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.openmrs.module.htmlformentry.FormEntrySession;\nimport org.openmrs.module.htmlformentry.action.RepeatControllerAction;\nimport org.w3c.dom.NamedNodeMap;\nimport org.w3c.dom.Node;\n\n/**\n * Currently not used--the {@code } tag is currently handled by\n * {@see org.openmrs.module.htmlformentry.HtmlFormEntryGenerator#applyRepeats(String)}.\n */\npublic abstract class RepeatTagHandler implements IteratingTagHandler {\n\n @Override\n public boolean doStartTag(FormEntrySession session, PrintWriter out, Node parent, Node node) {\n Map attributes = new HashMap();\n NamedNodeMap map = node.getAttributes();\n for (int i = 0; i < map.getLength(); ++i) {\n Node attribute = map.item(i);\n attributes.put(attribute.getNodeName(), attribute.getNodeValue());\n }\n setupBefore(session, attributes);\n session.getSubmissionController().startRepeat(getRepeatAction(session, attributes));\n // recurse to children\n return true;\n }\n\n @Override\n public void doEndTag(FormEntrySession session, PrintWriter out, Node parent, Node node) {\n session.getSubmissionCont", "post_mask_code": "\n }\n\n protected abstract void setupBefore(FormEntrySession session, Map attributes);\n\n protected abstract RepeatControllerAction getRepeatAction(FormEntrySession session, Map attributes);\n}\n"} {"task_id": "Java_2124", "language": "Java", "task_type": "for_statement", "source_file": "java/github/openmrs/openmrs-module-htmlformentry/api/src/main/java/org/openmrs/module/htmlformentry/handler/RepeatTagHandler.java", "mask_start_position": 798, "mask_end_position": 972, "canonical_solution": "for (int i = 0; i < map.getLength(); ++i) {\n Node attribute = map.item(i);\n attributes.put(attribute.getNodeName(), attribute.getNodeValue());\n }", "pre_mask_code": "package org.openmrs.module.htmlformentry.handler;\n\nimport java.io.PrintWriter;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.openmrs.module.htmlformentry.FormEntrySession;\nimport org.openmrs.module.htmlformentry.action.RepeatControllerAction;\nimport org.w3c.dom.NamedNodeMap;\nimport org.w3c.dom.Node;\n\n/**\n * Currently not used--the {@code } tag is currently handled by\n * {@see org.openmrs.module.htmlformentry.HtmlFormEntryGenerator#applyRepeats(String)}.\n */\npublic abstract class RepeatTagHandler implements IteratingTagHandler {\n\n @Override\n public boolean doStartTag(FormEntrySession session, PrintWriter out, Node parent, Node node) {\n Map attributes = new HashMap();\n NamedNodeMap map = node.getAttributes();\n ", "post_mask_code": "\n setupBefore(session, attributes);\n session.getSubmissionController().startRepeat(getRepeatAction(session, attributes));\n // recurse to children\n return true;\n }\n\n @Override\n public void doEndTag(FormEntrySession session, PrintWriter out, Node parent, Node node) {\n session.getSubmissionController().endRepeat();\n }\n\n protected abstract void setupBefore(FormEntrySession session, Map attributes);\n\n protected abstract RepeatControllerAction getRepeatAction(FormEntrySession session, Map attributes);\n}\n"} {"task_id": "Java_2125", "language": "Java", "task_type": "method_signature", "source_file": "java/github/leadpony/justify/justify/src/main/java/org/leadpony/justify/api/keyword/KeywordValueSetLoader.java", "mask_start_position": 592, "mask_end_position": 663, "canonical_solution": "@Override\n public Set loadKeywordValueSet(Class type) ", "pre_mask_code": "package org.leadpony.justify.api.keyword;\n\nimport java.util.Collections;\nimport java.util.Set;\n\n/**\n * A loader of the limited keyword value set.\n *\n * @author leadpony\n */\npublic interface KeywordValueSetLoader {\n\n /**\n * Loads the value set of the specified type.\n *\n * @param the type of the value.\n * @param type the class of the value.\n * @return loaded set of values.\n */\n Set loadKeywordValueSet(Class type);\n\n /**\n * A loader which will loads nothing.\n */\n KeywordValueSetLoader NEVER = new KeywordValueSetLoader() {\n\n ", "post_mask_code": "{\n return Collections.emptySet();\n }\n };\n}\n"} {"task_id": "Java_2126", "language": "Java", "task_type": "method_body", "source_file": "java/github/leadpony/justify/justify/src/main/java/org/leadpony/justify/api/keyword/KeywordValueSetLoader.java", "mask_start_position": 663, "mask_end_position": 717, "canonical_solution": "{\n return Collections.emptySet();\n }", "pre_mask_code": "package org.leadpony.justify.api.keyword;\n\nimport java.util.Collections;\nimport java.util.Set;\n\n/**\n * A loader of the limited keyword value set.\n *\n * @author leadpony\n */\npublic interface KeywordValueSetLoader {\n\n /**\n * Loads the value set of the specified type.\n *\n * @param the type of the value.\n * @param type the class of the value.\n * @return loaded set of values.\n */\n Set loadKeywordValueSet(Class type);\n\n /**\n * A loader which will loads nothing.\n */\n KeywordValueSetLoader NEVER = new KeywordValueSetLoader() {\n\n @Override\n public Set loadKeywordValueSet(Class type) ", "post_mask_code": "\n };\n}\n"} {"task_id": "Java_2127", "language": "Java", "task_type": "single_line", "source_file": "java/github/leadpony/justify/justify/src/main/java/org/leadpony/justify/api/keyword/KeywordValueSetLoader.java", "mask_start_position": 695, "mask_end_position": 707, "canonical_solution": ".emptySet();", "pre_mask_code": "package org.leadpony.justify.api.keyword;\n\nimport java.util.Collections;\nimport java.util.Set;\n\n/**\n * A loader of the limited keyword value set.\n *\n * @author leadpony\n */\npublic interface KeywordValueSetLoader {\n\n /**\n * Loads the value set of the specified type.\n *\n * @param the type of the value.\n * @param type the class of the value.\n * @return loaded set of values.\n */\n Set loadKeywordValueSet(Class type);\n\n /**\n * A loader which will loads nothing.\n */\n KeywordValueSetLoader NEVER = new KeywordValueSetLoader() {\n\n @Override\n public Set loadKeywordValueSet(Class type) {\n return Collections", "post_mask_code": "\n }\n };\n}\n"} {"task_id": "Java_2128", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/leadpony/justify/justify/src/main/java/org/leadpony/justify/api/keyword/KeywordValueSetLoader.java", "mask_start_position": 413, "mask_end_position": 459, "canonical_solution": " Set loadKeywordValueSet(Class type);", "pre_mask_code": "package org.leadpony.justify.api.keyword;\n\nimport java.util.Collections;\nimport java.util.Set;\n\n/**\n * A loader of the limited keyword value set.\n *\n * @author leadpony\n */\npublic interface KeywordValueSetLoader {\n\n /**\n * Loads the value set of the specified type.\n *\n * @param the type of the value.\n * @param type the class of the value.\n * @return loaded set of values.\n */\n ", "post_mask_code": "\n\n /**\n * A loader which will loads nothing.\n */\n KeywordValueSetLoader NEVER = new KeywordValueSetLoader() {\n\n @Override\n public Set loadKeywordValueSet(Class type) {\n return Collections.emptySet();\n }\n };\n}\n"} {"task_id": "Java_2129", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse/capella/core/plugins/org.polarsys.capella.core.platform.sirius.ui.project/src/org/polarsys/capella/core/platform/sirius/ui/project/NewProjectAction.java", "mask_start_position": 1159, "mask_end_position": 1193, "canonical_solution": "public void run(IAction action_p) ", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * Thales - initial API and implementation\n * *****************************************************************************\n */\npackage org.polarsys.capella.core.platform.sirius.ui.project;\n\nimport org.eclipse.jface.action.IAction;\nimport org.eclipse.jface.viewers.ISelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.jface.wizard.WizardDialog;\nimport org.eclipse.ui.IViewActionDelegate;\nimport org.eclipse.ui.IViewPart;\nimport org.eclipse.ui.IWorkbenchSite;\nimport org.eclipse.ui.PlatformUI;\n\npublic class NewProjectAction implements IViewActionDelegate {\n\n // The action site.\n private IWorkbenchSite _site;\n\n /**\n * Constructs the new project action.\n */\n public NewProjectAction() {\n // Do nothing.\n }\n\n /**\n * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)\n */\n public void init(IViewPart view_p) {\n _site = view_p.getViewSite();\n }\n\n /**\n * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)\n */\n ", "post_mask_code": "{\n NewProjectWizard wizard = new NewProjectWizard();\n wizard.init(PlatformUI.getWorkbench(), StructuredSelection.EMPTY);\n WizardDialog dialog = new WizardDialog(_site.getShell(), wizard);\n dialog.open();\n }\n\n /**\n * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)\n */\n public void selectionChanged(IAction action_p, ISelection selection_p) {\n // Do nothing.\n }\n\n /**\n * Set site.\n * @param site_p the site to set\n */\n public void setSite(IWorkbenchSite site_p) {\n _site = site_p;\n }\n}\n"} {"task_id": "Java_2130", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse/capella/core/plugins/org.polarsys.capella.core.platform.sirius.ui.project/src/org/polarsys/capella/core/platform/sirius/ui/project/NewProjectAction.java", "mask_start_position": 1011, "mask_end_position": 1056, "canonical_solution": "{\n _site = view_p.getViewSite();\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * Thales - initial API and implementation\n * *****************************************************************************\n */\npackage org.polarsys.capella.core.platform.sirius.ui.project;\n\nimport org.eclipse.jface.action.IAction;\nimport org.eclipse.jface.viewers.ISelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.jface.wizard.WizardDialog;\nimport org.eclipse.ui.IViewActionDelegate;\nimport org.eclipse.ui.IViewPart;\nimport org.eclipse.ui.IWorkbenchSite;\nimport org.eclipse.ui.PlatformUI;\n\npublic class NewProjectAction implements IViewActionDelegate {\n\n // The action site.\n private IWorkbenchSite _site;\n\n /**\n * Constructs the new project action.\n */\n public NewProjectAction() {\n // Do nothing.\n }\n\n /**\n * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)\n */\n public void init(IViewPart view_p) ", "post_mask_code": "\n\n /**\n * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)\n */\n public void run(IAction action_p) {\n NewProjectWizard wizard = new NewProjectWizard();\n wizard.init(PlatformUI.getWorkbench(), StructuredSelection.EMPTY);\n WizardDialog dialog = new WizardDialog(_site.getShell(), wizard);\n dialog.open();\n }\n\n /**\n * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)\n */\n public void selectionChanged(IAction action_p, ISelection selection_p) {\n // Do nothing.\n }\n\n /**\n * Set site.\n * @param site_p the site to set\n */\n public void setSite(IWorkbenchSite site_p) {\n _site = site_p;\n }\n}\n"} {"task_id": "Java_2131", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse/capella/core/plugins/org.polarsys.capella.core.platform.sirius.ui.project/src/org/polarsys/capella/core/platform/sirius/ui/project/NewProjectAction.java", "mask_start_position": 1814, "mask_end_position": 1829, "canonical_solution": "_site = site_p;", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * Thales - initial API and implementation\n * *****************************************************************************\n */\npackage org.polarsys.capella.core.platform.sirius.ui.project;\n\nimport org.eclipse.jface.action.IAction;\nimport org.eclipse.jface.viewers.ISelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.jface.wizard.WizardDialog;\nimport org.eclipse.ui.IViewActionDelegate;\nimport org.eclipse.ui.IViewPart;\nimport org.eclipse.ui.IWorkbenchSite;\nimport org.eclipse.ui.PlatformUI;\n\npublic class NewProjectAction implements IViewActionDelegate {\n\n // The action site.\n private IWorkbenchSite _site;\n\n /**\n * Constructs the new project action.\n */\n public NewProjectAction() {\n // Do nothing.\n }\n\n /**\n * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)\n */\n public void init(IViewPart view_p) {\n _site = view_p.getViewSite();\n }\n\n /**\n * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)\n */\n public void run(IAction action_p) {\n NewProjectWizard wizard = new NewProjectWizard();\n wizard.init(PlatformUI.getWorkbench(), StructuredSelection.EMPTY);\n WizardDialog dialog = new WizardDialog(_site.getShell(), wizard);\n dialog.open();\n }\n\n /**\n * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)\n */\n public void selectionChanged(IAction action_p, ISelection selection_p) {\n // Do nothing.\n }\n\n /**\n * Set site.\n * @param site_p the site to set\n */\n public void setSite(IWorkbenchSite site_p) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2132", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/eclipse/capella/core/plugins/org.polarsys.capella.core.platform.sirius.ui.project/src/org/polarsys/capella/core/platform/sirius/ui/project/NewProjectAction.java", "mask_start_position": 1159, "mask_end_position": 1430, "canonical_solution": "public void run(IAction action_p) {\n NewProjectWizard wizard = new NewProjectWizard();\n wizard.init(PlatformUI.getWorkbench(), StructuredSelection.EMPTY);\n WizardDialog dialog = new WizardDialog(_site.getShell(), wizard);\n dialog.open();\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * Thales - initial API and implementation\n * *****************************************************************************\n */\npackage org.polarsys.capella.core.platform.sirius.ui.project;\n\nimport org.eclipse.jface.action.IAction;\nimport org.eclipse.jface.viewers.ISelection;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.jface.wizard.WizardDialog;\nimport org.eclipse.ui.IViewActionDelegate;\nimport org.eclipse.ui.IViewPart;\nimport org.eclipse.ui.IWorkbenchSite;\nimport org.eclipse.ui.PlatformUI;\n\npublic class NewProjectAction implements IViewActionDelegate {\n\n // The action site.\n private IWorkbenchSite _site;\n\n /**\n * Constructs the new project action.\n */\n public NewProjectAction() {\n // Do nothing.\n }\n\n /**\n * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)\n */\n public void init(IViewPart view_p) {\n _site = view_p.getViewSite();\n }\n\n /**\n * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)\n */\n ", "post_mask_code": "\n\n /**\n * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)\n */\n public void selectionChanged(IAction action_p, ISelection selection_p) {\n // Do nothing.\n }\n\n /**\n * Set site.\n * @param site_p the site to set\n */\n public void setSite(IWorkbenchSite site_p) {\n _site = site_p;\n }\n}\n"} {"task_id": "Java_2133", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse/capella/ext/viatra/plugins/org.polarsys.capella.viatra.core.data.gen/src-gen/org/polarsys/capella/viatra/core/data/interaction/surrogate/AbstractCapabilityRealization.java", "mask_start_position": 2108, "mask_end_position": 2220, "canonical_solution": "public AbstractCapabilityRealization__realizedCapability getAbstractCapabilityRealization__realizedCapability() ", "pre_mask_code": "/**\n * Contributors:\n * Thales - initial API and implementation\n */\npackage org.polarsys.capella.viatra.core.data.interaction.surrogate;\n\nimport org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;\nimport org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedPatternGroup;\nimport org.polarsys.capella.viatra.core.data.interaction.surrogate.AbstractCapabilityRealization__realizedCapability;\nimport org.polarsys.capella.viatra.core.data.interaction.surrogate.AbstractCapabilityRealization__realizingCapability;\n\n/**\n * A pattern group formed of all public patterns defined in AbstractCapabilityRealization.vql.\n *\n *

Use the static instance as any {@link interface org.eclipse.viatra.query.runtime.api.IQueryGroup}, to conveniently prepare\n * a VIATRA Query engine for matching all patterns originally defined in file AbstractCapabilityRealization.vql,\n * in order to achieve better performance than one-by-one on-demand matcher initialization.\n *\n *

From package org.polarsys.capella.viatra.core.data.interaction.surrogate, the group contains the definition of the following patterns:

    \n *
  • AbstractCapabilityRealization__realizedCapability
  • \n *
  • AbstractCapabilityRealization__realizingCapability
  • \n *
\n *\n * @see IQueryGroup\n */\n@SuppressWarnings(\"all\")\npublic final class AbstractCapabilityRealization extends BaseGeneratedPatternGroup {\n\n /**\n * Access the pattern group.\n *\n * @return the singleton instance of the group\n * @throws ViatraQueryRuntimeException if there was an error loading the generated code of pattern specifications\n */\n public static AbstractCapabilityRealization instance() {\n if (INSTANCE == null) {\n INSTANCE = new AbstractCapabilityRealization();\n }\n return INSTANCE;\n }\n\n private static AbstractCapabilityRealization INSTANCE;\n\n private AbstractCapabilityRealization() {\n querySpecifications.add(AbstractCapabilityRealization__realizedCapability.instance());\n querySpecifications.add(AbstractCapabilityRealization__realizingCapability.instance());\n }\n\n ", "post_mask_code": "{\n return AbstractCapabilityRealization__realizedCapability.instance();\n }\n\n public AbstractCapabilityRealization__realizedCapability.Matcher getAbstractCapabilityRealization__realizedCapability(final ViatraQueryEngine engine) {\n return AbstractCapabilityRealization__realizedCapability.Matcher.on(engine);\n }\n\n public AbstractCapabilityRealization__realizingCapability getAbstractCapabilityRealization__realizingCapability() {\n return AbstractCapabilityRealization__realizingCapability.instance();\n }\n\n public AbstractCapabilityRealization__realizingCapability.Matcher getAbstractCapabilityRealization__realizingCapability(final ViatraQueryEngine engine) {\n return AbstractCapabilityRealization__realizingCapability.Matcher.on(engine);\n }\n}\n"} {"task_id": "Java_2134", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse/capella/ext/viatra/plugins/org.polarsys.capella.viatra.core.data.gen/src-gen/org/polarsys/capella/viatra/core/data/interaction/surrogate/AbstractCapabilityRealization.java", "mask_start_position": 2220, "mask_end_position": 2304, "canonical_solution": "{\n return AbstractCapabilityRealization__realizedCapability.instance();\n }", "pre_mask_code": "/**\n * Contributors:\n * Thales - initial API and implementation\n */\npackage org.polarsys.capella.viatra.core.data.interaction.surrogate;\n\nimport org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;\nimport org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedPatternGroup;\nimport org.polarsys.capella.viatra.core.data.interaction.surrogate.AbstractCapabilityRealization__realizedCapability;\nimport org.polarsys.capella.viatra.core.data.interaction.surrogate.AbstractCapabilityRealization__realizingCapability;\n\n/**\n * A pattern group formed of all public patterns defined in AbstractCapabilityRealization.vql.\n *\n *

Use the static instance as any {@link interface org.eclipse.viatra.query.runtime.api.IQueryGroup}, to conveniently prepare\n * a VIATRA Query engine for matching all patterns originally defined in file AbstractCapabilityRealization.vql,\n * in order to achieve better performance than one-by-one on-demand matcher initialization.\n *\n *

From package org.polarsys.capella.viatra.core.data.interaction.surrogate, the group contains the definition of the following patterns:

    \n *
  • AbstractCapabilityRealization__realizedCapability
  • \n *
  • AbstractCapabilityRealization__realizingCapability
  • \n *
\n *\n * @see IQueryGroup\n */\n@SuppressWarnings(\"all\")\npublic final class AbstractCapabilityRealization extends BaseGeneratedPatternGroup {\n\n /**\n * Access the pattern group.\n *\n * @return the singleton instance of the group\n * @throws ViatraQueryRuntimeException if there was an error loading the generated code of pattern specifications\n */\n public static AbstractCapabilityRealization instance() {\n if (INSTANCE == null) {\n INSTANCE = new AbstractCapabilityRealization();\n }\n return INSTANCE;\n }\n\n private static AbstractCapabilityRealization INSTANCE;\n\n private AbstractCapabilityRealization() {\n querySpecifications.add(AbstractCapabilityRealization__realizedCapability.instance());\n querySpecifications.add(AbstractCapabilityRealization__realizingCapability.instance());\n }\n\n public AbstractCapabilityRealization__realizedCapability getAbstractCapabilityRealization__realizedCapability() ", "post_mask_code": "\n\n public AbstractCapabilityRealization__realizedCapability.Matcher getAbstractCapabilityRealization__realizedCapability(final ViatraQueryEngine engine) {\n return AbstractCapabilityRealization__realizedCapability.Matcher.on(engine);\n }\n\n public AbstractCapabilityRealization__realizingCapability getAbstractCapabilityRealization__realizingCapability() {\n return AbstractCapabilityRealization__realizingCapability.instance();\n }\n\n public AbstractCapabilityRealization__realizingCapability.Matcher getAbstractCapabilityRealization__realizingCapability(final ViatraQueryEngine engine) {\n return AbstractCapabilityRealization__realizingCapability.Matcher.on(engine);\n }\n}\n"} {"task_id": "Java_2135", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse/capella/ext/viatra/plugins/org.polarsys.capella.viatra.core.data.gen/src-gen/org/polarsys/capella/viatra/core/data/interaction/surrogate/AbstractCapabilityRealization.java", "mask_start_position": 2960, "mask_end_position": 3002, "canonical_solution": "n__realizingCapability.Matcher.on(engine);", "pre_mask_code": "/**\n * Contributors:\n * Thales - initial API and implementation\n */\npackage org.polarsys.capella.viatra.core.data.interaction.surrogate;\n\nimport org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;\nimport org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedPatternGroup;\nimport org.polarsys.capella.viatra.core.data.interaction.surrogate.AbstractCapabilityRealization__realizedCapability;\nimport org.polarsys.capella.viatra.core.data.interaction.surrogate.AbstractCapabilityRealization__realizingCapability;\n\n/**\n * A pattern group formed of all public patterns defined in AbstractCapabilityRealization.vql.\n *\n *

Use the static instance as any {@link interface org.eclipse.viatra.query.runtime.api.IQueryGroup}, to conveniently prepare\n * a VIATRA Query engine for matching all patterns originally defined in file AbstractCapabilityRealization.vql,\n * in order to achieve better performance than one-by-one on-demand matcher initialization.\n *\n *

From package org.polarsys.capella.viatra.core.data.interaction.surrogate, the group contains the definition of the following patterns:

    \n *
  • AbstractCapabilityRealization__realizedCapability
  • \n *
  • AbstractCapabilityRealization__realizingCapability
  • \n *
\n *\n * @see IQueryGroup\n */\n@SuppressWarnings(\"all\")\npublic final class AbstractCapabilityRealization extends BaseGeneratedPatternGroup {\n\n /**\n * Access the pattern group.\n *\n * @return the singleton instance of the group\n * @throws ViatraQueryRuntimeException if there was an error loading the generated code of pattern specifications\n */\n public static AbstractCapabilityRealization instance() {\n if (INSTANCE == null) {\n INSTANCE = new AbstractCapabilityRealization();\n }\n return INSTANCE;\n }\n\n private static AbstractCapabilityRealization INSTANCE;\n\n private AbstractCapabilityRealization() {\n querySpecifications.add(AbstractCapabilityRealization__realizedCapability.instance());\n querySpecifications.add(AbstractCapabilityRealization__realizingCapability.instance());\n }\n\n public AbstractCapabilityRealization__realizedCapability getAbstractCapabilityRealization__realizedCapability() {\n return AbstractCapabilityRealization__realizedCapability.instance();\n }\n\n public AbstractCapabilityRealization__realizedCapability.Matcher getAbstractCapabilityRealization__realizedCapability(final ViatraQueryEngine engine) {\n return AbstractCapabilityRealization__realizedCapability.Matcher.on(engine);\n }\n\n public AbstractCapabilityRealization__realizingCapability getAbstractCapabilityRealization__realizingCapability() {\n return AbstractCapabilityRealization__realizingCapability.instance();\n }\n\n public AbstractCapabilityRealization__realizingCapability.Matcher getAbstractCapabilityRealization__realizingCapability(final ViatraQueryEngine engine) {\n return AbstractCapabilityRealizatio", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2136", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/eclipse/capella/ext/viatra/plugins/org.polarsys.capella.viatra.core.data.gen/src-gen/org/polarsys/capella/viatra/core/data/interaction/surrogate/AbstractCapabilityRealization.java", "mask_start_position": 1609, "mask_end_position": 1798, "canonical_solution": "public static AbstractCapabilityRealization instance() {\n if (INSTANCE == null) {\n INSTANCE = new AbstractCapabilityRealization();\n }\n return INSTANCE;\n }", "pre_mask_code": "/**\n * Contributors:\n * Thales - initial API and implementation\n */\npackage org.polarsys.capella.viatra.core.data.interaction.surrogate;\n\nimport org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;\nimport org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedPatternGroup;\nimport org.polarsys.capella.viatra.core.data.interaction.surrogate.AbstractCapabilityRealization__realizedCapability;\nimport org.polarsys.capella.viatra.core.data.interaction.surrogate.AbstractCapabilityRealization__realizingCapability;\n\n/**\n * A pattern group formed of all public patterns defined in AbstractCapabilityRealization.vql.\n *\n *

Use the static instance as any {@link interface org.eclipse.viatra.query.runtime.api.IQueryGroup}, to conveniently prepare\n * a VIATRA Query engine for matching all patterns originally defined in file AbstractCapabilityRealization.vql,\n * in order to achieve better performance than one-by-one on-demand matcher initialization.\n *\n *

From package org.polarsys.capella.viatra.core.data.interaction.surrogate, the group contains the definition of the following patterns:

    \n *
  • AbstractCapabilityRealization__realizedCapability
  • \n *
  • AbstractCapabilityRealization__realizingCapability
  • \n *
\n *\n * @see IQueryGroup\n */\n@SuppressWarnings(\"all\")\npublic final class AbstractCapabilityRealization extends BaseGeneratedPatternGroup {\n\n /**\n * Access the pattern group.\n *\n * @return the singleton instance of the group\n * @throws ViatraQueryRuntimeException if there was an error loading the generated code of pattern specifications\n */\n ", "post_mask_code": "\n\n private static AbstractCapabilityRealization INSTANCE;\n\n private AbstractCapabilityRealization() {\n querySpecifications.add(AbstractCapabilityRealization__realizedCapability.instance());\n querySpecifications.add(AbstractCapabilityRealization__realizingCapability.instance());\n }\n\n public AbstractCapabilityRealization__realizedCapability getAbstractCapabilityRealization__realizedCapability() {\n return AbstractCapabilityRealization__realizedCapability.instance();\n }\n\n public AbstractCapabilityRealization__realizedCapability.Matcher getAbstractCapabilityRealization__realizedCapability(final ViatraQueryEngine engine) {\n return AbstractCapabilityRealization__realizedCapability.Matcher.on(engine);\n }\n\n public AbstractCapabilityRealization__realizingCapability getAbstractCapabilityRealization__realizingCapability() {\n return AbstractCapabilityRealization__realizingCapability.instance();\n }\n\n public AbstractCapabilityRealization__realizingCapability.Matcher getAbstractCapabilityRealization__realizingCapability(final ViatraQueryEngine engine) {\n return AbstractCapabilityRealization__realizingCapability.Matcher.on(engine);\n }\n}\n"} {"task_id": "Java_2137", "language": "Java", "task_type": "method_signature", "source_file": "java/github/osiam/osiam/src/main/java/org/osiam/resources/converter/PhotoConverter.java", "mask_start_position": 726, "mask_end_position": 780, "canonical_solution": "@Override\n public Photo toScim(PhotoEntity entity) ", "pre_mask_code": "package org.osiam.resources.converter;\n\nimport org.osiam.resources.exception.OsiamException;\nimport org.osiam.resources.scim.Photo;\nimport org.osiam.storage.entities.PhotoEntity;\nimport org.springframework.stereotype.Service;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\n@Service\npublic class PhotoConverter implements Converter {\n\n @Override\n public PhotoEntity fromScim(Photo scim) {\n PhotoEntity photoEntity = new PhotoEntity();\n photoEntity.setValue(scim.getValueAsURI().toString());\n photoEntity.setType(scim.getType());\n photoEntity.setPrimary(scim.isPrimary());\n photoEntity.setDisplay(scim.getDisplay());\n return photoEntity;\n }\n\n ", "post_mask_code": "{\n Photo scimPhoto;\n try {\n scimPhoto = new Photo.Builder().setType(entity.getType()).setValue(new URI(entity.getValue())).setPrimary(entity.isPrimary()).setDisplay(entity.getDisplay()).build();\n } catch (URISyntaxException e) {\n throw new OsiamException(e.getMessage(), e);\n }\n return scimPhoto;\n }\n}\n"} {"task_id": "Java_2138", "language": "Java", "task_type": "method_body", "source_file": "java/github/osiam/osiam/src/main/java/org/osiam/resources/converter/PhotoConverter.java", "mask_start_position": 423, "mask_end_position": 720, "canonical_solution": "{\n PhotoEntity photoEntity = new PhotoEntity();\n photoEntity.setValue(scim.getValueAsURI().toString());\n photoEntity.setType(scim.getType());\n photoEntity.setPrimary(scim.isPrimary());\n photoEntity.setDisplay(scim.getDisplay());\n return photoEntity;\n }", "pre_mask_code": "package org.osiam.resources.converter;\n\nimport org.osiam.resources.exception.OsiamException;\nimport org.osiam.resources.scim.Photo;\nimport org.osiam.storage.entities.PhotoEntity;\nimport org.springframework.stereotype.Service;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\n@Service\npublic class PhotoConverter implements Converter {\n\n @Override\n public PhotoEntity fromScim(Photo scim) ", "post_mask_code": "\n\n @Override\n public Photo toScim(PhotoEntity entity) {\n Photo scimPhoto;\n try {\n scimPhoto = new Photo.Builder().setType(entity.getType()).setValue(new URI(entity.getValue())).setPrimary(entity.isPrimary()).setDisplay(entity.getDisplay()).build();\n } catch (URISyntaxException e) {\n throw new OsiamException(e.getMessage(), e);\n }\n return scimPhoto;\n }\n}\n"} {"task_id": "Java_2139", "language": "Java", "task_type": "single_line", "source_file": "java/github/osiam/osiam/src/main/java/org/osiam/resources/converter/PhotoConverter.java", "mask_start_position": 801, "mask_end_position": 806, "canonical_solution": "hoto;", "pre_mask_code": "package org.osiam.resources.converter;\n\nimport org.osiam.resources.exception.OsiamException;\nimport org.osiam.resources.scim.Photo;\nimport org.osiam.storage.entities.PhotoEntity;\nimport org.springframework.stereotype.Service;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\n@Service\npublic class PhotoConverter implements Converter {\n\n @Override\n public PhotoEntity fromScim(Photo scim) {\n PhotoEntity photoEntity = new PhotoEntity();\n photoEntity.setValue(scim.getValueAsURI().toString());\n photoEntity.setType(scim.getType());\n photoEntity.setPrimary(scim.isPrimary());\n photoEntity.setDisplay(scim.getDisplay());\n return photoEntity;\n }\n\n @Override\n public Photo toScim(PhotoEntity entity) {\n Photo scimP", "post_mask_code": "\n try {\n scimPhoto = new Photo.Builder().setType(entity.getType()).setValue(new URI(entity.getValue())).setPrimary(entity.isPrimary()).setDisplay(entity.getDisplay()).build();\n } catch (URISyntaxException e) {\n throw new OsiamException(e.getMessage(), e);\n }\n return scimPhoto;\n }\n}\n"} {"task_id": "Java_2140", "language": "Java", "task_type": "try_statement", "source_file": "java/github/osiam/osiam/src/main/java/org/osiam/resources/converter/PhotoConverter.java", "mask_start_position": 815, "mask_end_position": 1107, "canonical_solution": "try {\n scimPhoto = new Photo.Builder().setType(entity.getType()).setValue(new URI(entity.getValue())).setPrimary(entity.isPrimary()).setDisplay(entity.getDisplay()).build();\n } catch (URISyntaxException e) {\n throw new OsiamException(e.getMessage(), e);\n }", "pre_mask_code": "package org.osiam.resources.converter;\n\nimport org.osiam.resources.exception.OsiamException;\nimport org.osiam.resources.scim.Photo;\nimport org.osiam.storage.entities.PhotoEntity;\nimport org.springframework.stereotype.Service;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\n@Service\npublic class PhotoConverter implements Converter {\n\n @Override\n public PhotoEntity fromScim(Photo scim) {\n PhotoEntity photoEntity = new PhotoEntity();\n photoEntity.setValue(scim.getValueAsURI().toString());\n photoEntity.setType(scim.getType());\n photoEntity.setPrimary(scim.isPrimary());\n photoEntity.setDisplay(scim.getDisplay());\n return photoEntity;\n }\n\n @Override\n public Photo toScim(PhotoEntity entity) {\n Photo scimPhoto;\n ", "post_mask_code": "\n return scimPhoto;\n }\n}\n"} {"task_id": "Java_2141", "language": "Java", "task_type": "method_signature", "source_file": "java/github/liangbaika/permission/src/main/java/com/lq/service/impl/SysCoreService.java", "mask_start_position": 1564, "mask_end_position": 1616, "canonical_solution": "public List getRoleAclList(int roleId) ", "pre_mask_code": "package com.lq.service.impl;\n\nimport com.google.common.collect.Lists;\nimport com.lq.entity.SysAcl;\nimport com.lq.entity.SysUser;\nimport com.lq.enums.CahceKeyConst;\nimport com.lq.enums.DataUseful;\nimport com.lq.enums.RoleTypeEnum;\nimport com.lq.model.SysAclModel;\nimport com.lq.model.SysRoleModel;\nimport com.lq.redis.SysCacheServiceOfRedis;\nimport com.lq.repository.SysAclRepository;\nimport com.lq.repository.SysRoleAclRepository;\nimport com.lq.repository.SysRoleRepository;\nimport com.lq.repository.SysRoleUserRepository;\nimport com.lq.service.SysRoleUserService;\nimport com.lq.utils.JsonMapper;\nimport com.lq.utils.LoginHolder;\nimport org.codehaus.jackson.type.TypeReference;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.util.CollectionUtils;\nimport javax.annotation.Resource;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n@Service\npublic class SysCoreService {\n\n @Autowired\n private SysAclRepository sysAclRepository;\n\n @Autowired\n private SysRoleUserRepository sysRoleUserRepository;\n\n @Autowired\n private SysRoleRepository sysRoleRepository;\n\n @Autowired\n private SysRoleAclRepository sysRoleAclRepository;\n\n @Resource(name = \"sysCacheServiceOfRedis\")\n private SysCacheServiceOfRedis sysCacheServiceOfRedis;\n\n public List getCurrentUserAclList() {\n Integer userId = LoginHolder.getUserId();\n return getUserAclListFromCache(userId);\n }\n\n ", "post_mask_code": "{\n List aclIdList = sysRoleAclRepository.getAclIdListByRoleIdList(new ArrayList<>(roleId));\n if (CollectionUtils.isEmpty(aclIdList)) {\n return Lists.newArrayList();\n }\n return sysAclRepository.getByIdList(aclIdList);\n }\n\n public List getUserAclList(int userId) {\n if (isSuperAdmin()) {\n return sysAclRepository.getAll();\n }\n List userRoleIdList = sysRoleUserRepository.getRoleIDListByUserId(userId);\n if (CollectionUtils.isEmpty(userRoleIdList)) {\n return Lists.newArrayList();\n }\n List userAclIdList = sysRoleAclRepository.getAclIdListByRoleIdList(userRoleIdList);\n if (CollectionUtils.isEmpty(userAclIdList)) {\n return Lists.newArrayList();\n }\n return sysAclRepository.getByIdList(userAclIdList);\n }\n\n public List getUserAclListFromCache(int userId) {\n String cacheValue = sysCacheServiceOfRedis.getFromCache(CahceKeyConst.USER_ACLS, String.valueOf(userId));\n if (cacheValue == null) {\n List userAclList = getUserAclList(userId);\n // timeOutSeconds 可以自由配置 建议写在配置文件中, 1800:半小时\n if (!CollectionUtils.isEmpty(userAclList)) {\n sysCacheServiceOfRedis.saveCache(JsonMapper.obj2String(userAclList), 1800, CahceKeyConst.USER_ACLS, String.valueOf(userId));\n }\n return CollectionUtils.isEmpty(userAclList) ? Lists.newArrayList() : userAclList;\n }\n return JsonMapper.string2Obj(cacheValue, new TypeReference>() {\n });\n }\n\n public boolean isSuperAdmin() {\n List roleIDListByUserId = sysRoleUserRepository.getRoleIDListByUserId(LoginHolder.getUserId());\n if (CollectionUtils.isEmpty(roleIDListByUserId)) {\n return false;\n }\n List roles = sysRoleRepository.getRoleByIdList(roleIDListByUserId);\n if (CollectionUtils.isEmpty(roles)) {\n return false;\n }\n for (SysRoleModel role : roles) {\n if (role == null || role.getStatus().equals(DataUseful.NOUSEFUL.getCode())) {\n continue;\n }\n if (role.getType().equals(RoleTypeEnum.SuperAdmin.getCode())) {\n return true;\n }\n }\n return false;\n }\n\n public Boolean hasAclOfThisUrl(String url) {\n if (isSuperAdmin()) {\n return true;\n }\n SysAcl param = new SysAcl();\n param.setUrl(url);\n List sysAcls = sysAclRepository.selectPage(param, null);\n if (CollectionUtils.isEmpty(sysAcls)) {\n return true;\n }\n List currentUserAclList = getCurrentUserAclList();\n Set userAclIdSet = currentUserAclList.stream().map(e -> e.getId()).collect(Collectors.toSet());\n boolean hasValidAcl = false;\n for (SysAcl sysAcl : sysAcls) {\n if (sysAcl == null || sysAcl.getStatus().equals(DataUseful.NOUSEFUL.getCode())) {\n continue;\n }\n hasValidAcl = true;\n if (userAclIdSet.contains(sysAcl.getId())) {\n return true;\n }\n }\n if (!hasValidAcl) {\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_2142", "language": "Java", "task_type": "method_body", "source_file": "java/github/liangbaika/permission/src/main/java/com/lq/service/impl/SysCoreService.java", "mask_start_position": 1453, "mask_end_position": 1558, "canonical_solution": "{\n Integer userId = LoginHolder.getUserId();\n return getUserAclListFromCache(userId);\n }", "pre_mask_code": "package com.lq.service.impl;\n\nimport com.google.common.collect.Lists;\nimport com.lq.entity.SysAcl;\nimport com.lq.entity.SysUser;\nimport com.lq.enums.CahceKeyConst;\nimport com.lq.enums.DataUseful;\nimport com.lq.enums.RoleTypeEnum;\nimport com.lq.model.SysAclModel;\nimport com.lq.model.SysRoleModel;\nimport com.lq.redis.SysCacheServiceOfRedis;\nimport com.lq.repository.SysAclRepository;\nimport com.lq.repository.SysRoleAclRepository;\nimport com.lq.repository.SysRoleRepository;\nimport com.lq.repository.SysRoleUserRepository;\nimport com.lq.service.SysRoleUserService;\nimport com.lq.utils.JsonMapper;\nimport com.lq.utils.LoginHolder;\nimport org.codehaus.jackson.type.TypeReference;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.util.CollectionUtils;\nimport javax.annotation.Resource;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n@Service\npublic class SysCoreService {\n\n @Autowired\n private SysAclRepository sysAclRepository;\n\n @Autowired\n private SysRoleUserRepository sysRoleUserRepository;\n\n @Autowired\n private SysRoleRepository sysRoleRepository;\n\n @Autowired\n private SysRoleAclRepository sysRoleAclRepository;\n\n @Resource(name = \"sysCacheServiceOfRedis\")\n private SysCacheServiceOfRedis sysCacheServiceOfRedis;\n\n public List getCurrentUserAclList() ", "post_mask_code": "\n\n public List getRoleAclList(int roleId) {\n List aclIdList = sysRoleAclRepository.getAclIdListByRoleIdList(new ArrayList<>(roleId));\n if (CollectionUtils.isEmpty(aclIdList)) {\n return Lists.newArrayList();\n }\n return sysAclRepository.getByIdList(aclIdList);\n }\n\n public List getUserAclList(int userId) {\n if (isSuperAdmin()) {\n return sysAclRepository.getAll();\n }\n List userRoleIdList = sysRoleUserRepository.getRoleIDListByUserId(userId);\n if (CollectionUtils.isEmpty(userRoleIdList)) {\n return Lists.newArrayList();\n }\n List userAclIdList = sysRoleAclRepository.getAclIdListByRoleIdList(userRoleIdList);\n if (CollectionUtils.isEmpty(userAclIdList)) {\n return Lists.newArrayList();\n }\n return sysAclRepository.getByIdList(userAclIdList);\n }\n\n public List getUserAclListFromCache(int userId) {\n String cacheValue = sysCacheServiceOfRedis.getFromCache(CahceKeyConst.USER_ACLS, String.valueOf(userId));\n if (cacheValue == null) {\n List userAclList = getUserAclList(userId);\n // timeOutSeconds 可以自由配置 建议写在配置文件中, 1800:半小时\n if (!CollectionUtils.isEmpty(userAclList)) {\n sysCacheServiceOfRedis.saveCache(JsonMapper.obj2String(userAclList), 1800, CahceKeyConst.USER_ACLS, String.valueOf(userId));\n }\n return CollectionUtils.isEmpty(userAclList) ? Lists.newArrayList() : userAclList;\n }\n return JsonMapper.string2Obj(cacheValue, new TypeReference>() {\n });\n }\n\n public boolean isSuperAdmin() {\n List roleIDListByUserId = sysRoleUserRepository.getRoleIDListByUserId(LoginHolder.getUserId());\n if (CollectionUtils.isEmpty(roleIDListByUserId)) {\n return false;\n }\n List roles = sysRoleRepository.getRoleByIdList(roleIDListByUserId);\n if (CollectionUtils.isEmpty(roles)) {\n return false;\n }\n for (SysRoleModel role : roles) {\n if (role == null || role.getStatus().equals(DataUseful.NOUSEFUL.getCode())) {\n continue;\n }\n if (role.getType().equals(RoleTypeEnum.SuperAdmin.getCode())) {\n return true;\n }\n }\n return false;\n }\n\n public Boolean hasAclOfThisUrl(String url) {\n if (isSuperAdmin()) {\n return true;\n }\n SysAcl param = new SysAcl();\n param.setUrl(url);\n List sysAcls = sysAclRepository.selectPage(param, null);\n if (CollectionUtils.isEmpty(sysAcls)) {\n return true;\n }\n List currentUserAclList = getCurrentUserAclList();\n Set userAclIdSet = currentUserAclList.stream().map(e -> e.getId()).collect(Collectors.toSet());\n boolean hasValidAcl = false;\n for (SysAcl sysAcl : sysAcls) {\n if (sysAcl == null || sysAcl.getStatus().equals(DataUseful.NOUSEFUL.getCode())) {\n continue;\n }\n hasValidAcl = true;\n if (userAclIdSet.contains(sysAcl.getId())) {\n return true;\n }\n }\n if (!hasValidAcl) {\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_2143", "language": "Java", "task_type": "single_line", "source_file": "java/github/liangbaika/permission/src/main/java/com/lq/service/impl/SysCoreService.java", "mask_start_position": 1499, "mask_end_position": 1504, "canonical_solution": "Id();", "pre_mask_code": "package com.lq.service.impl;\n\nimport com.google.common.collect.Lists;\nimport com.lq.entity.SysAcl;\nimport com.lq.entity.SysUser;\nimport com.lq.enums.CahceKeyConst;\nimport com.lq.enums.DataUseful;\nimport com.lq.enums.RoleTypeEnum;\nimport com.lq.model.SysAclModel;\nimport com.lq.model.SysRoleModel;\nimport com.lq.redis.SysCacheServiceOfRedis;\nimport com.lq.repository.SysAclRepository;\nimport com.lq.repository.SysRoleAclRepository;\nimport com.lq.repository.SysRoleRepository;\nimport com.lq.repository.SysRoleUserRepository;\nimport com.lq.service.SysRoleUserService;\nimport com.lq.utils.JsonMapper;\nimport com.lq.utils.LoginHolder;\nimport org.codehaus.jackson.type.TypeReference;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.util.CollectionUtils;\nimport javax.annotation.Resource;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n@Service\npublic class SysCoreService {\n\n @Autowired\n private SysAclRepository sysAclRepository;\n\n @Autowired\n private SysRoleUserRepository sysRoleUserRepository;\n\n @Autowired\n private SysRoleRepository sysRoleRepository;\n\n @Autowired\n private SysRoleAclRepository sysRoleAclRepository;\n\n @Resource(name = \"sysCacheServiceOfRedis\")\n private SysCacheServiceOfRedis sysCacheServiceOfRedis;\n\n public List getCurrentUserAclList() {\n Integer userId = LoginHolder.getUser", "post_mask_code": "\n return getUserAclListFromCache(userId);\n }\n\n public List getRoleAclList(int roleId) {\n List aclIdList = sysRoleAclRepository.getAclIdListByRoleIdList(new ArrayList<>(roleId));\n if (CollectionUtils.isEmpty(aclIdList)) {\n return Lists.newArrayList();\n }\n return sysAclRepository.getByIdList(aclIdList);\n }\n\n public List getUserAclList(int userId) {\n if (isSuperAdmin()) {\n return sysAclRepository.getAll();\n }\n List userRoleIdList = sysRoleUserRepository.getRoleIDListByUserId(userId);\n if (CollectionUtils.isEmpty(userRoleIdList)) {\n return Lists.newArrayList();\n }\n List userAclIdList = sysRoleAclRepository.getAclIdListByRoleIdList(userRoleIdList);\n if (CollectionUtils.isEmpty(userAclIdList)) {\n return Lists.newArrayList();\n }\n return sysAclRepository.getByIdList(userAclIdList);\n }\n\n public List getUserAclListFromCache(int userId) {\n String cacheValue = sysCacheServiceOfRedis.getFromCache(CahceKeyConst.USER_ACLS, String.valueOf(userId));\n if (cacheValue == null) {\n List userAclList = getUserAclList(userId);\n // timeOutSeconds 可以自由配置 建议写在配置文件中, 1800:半小时\n if (!CollectionUtils.isEmpty(userAclList)) {\n sysCacheServiceOfRedis.saveCache(JsonMapper.obj2String(userAclList), 1800, CahceKeyConst.USER_ACLS, String.valueOf(userId));\n }\n return CollectionUtils.isEmpty(userAclList) ? Lists.newArrayList() : userAclList;\n }\n return JsonMapper.string2Obj(cacheValue, new TypeReference>() {\n });\n }\n\n public boolean isSuperAdmin() {\n List roleIDListByUserId = sysRoleUserRepository.getRoleIDListByUserId(LoginHolder.getUserId());\n if (CollectionUtils.isEmpty(roleIDListByUserId)) {\n return false;\n }\n List roles = sysRoleRepository.getRoleByIdList(roleIDListByUserId);\n if (CollectionUtils.isEmpty(roles)) {\n return false;\n }\n for (SysRoleModel role : roles) {\n if (role == null || role.getStatus().equals(DataUseful.NOUSEFUL.getCode())) {\n continue;\n }\n if (role.getType().equals(RoleTypeEnum.SuperAdmin.getCode())) {\n return true;\n }\n }\n return false;\n }\n\n public Boolean hasAclOfThisUrl(String url) {\n if (isSuperAdmin()) {\n return true;\n }\n SysAcl param = new SysAcl();\n param.setUrl(url);\n List sysAcls = sysAclRepository.selectPage(param, null);\n if (CollectionUtils.isEmpty(sysAcls)) {\n return true;\n }\n List currentUserAclList = getCurrentUserAclList();\n Set userAclIdSet = currentUserAclList.stream().map(e -> e.getId()).collect(Collectors.toSet());\n boolean hasValidAcl = false;\n for (SysAcl sysAcl : sysAcls) {\n if (sysAcl == null || sysAcl.getStatus().equals(DataUseful.NOUSEFUL.getCode())) {\n continue;\n }\n hasValidAcl = true;\n if (userAclIdSet.contains(sysAcl.getId())) {\n return true;\n }\n }\n if (!hasValidAcl) {\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_2144", "language": "Java", "task_type": "method_signature", "source_file": "java/github/capnkirok/animaniamod/src/main/java/com/animania/addons/catsdogs/common/entity/felids/CatRagdoll.java", "mask_start_position": 425, "mask_end_position": 477, "canonical_solution": "@Override\n public int getSecondaryEggColor() ", "pre_mask_code": "package com.animania.addons.catsdogs.common.entity.felids;\n\nimport net.minecraft.world.World;\n\npublic class CatRagdoll {\n\n public static class EntityTomRagdoll extends EntityTomBase {\n\n public EntityTomRagdoll(World worldIn) {\n super(worldIn);\n this.type = CatType.RAGDOLL;\n }\n\n @Override\n public int getPrimaryEggColor() {\n return 13948116;\n }\n\n ", "post_mask_code": "{\n return 8741209;\n }\n }\n\n public static class EntityQueenRagdoll extends EntityQueenBase {\n\n public EntityQueenRagdoll(World worldIn) {\n super(worldIn);\n this.type = CatType.RAGDOLL;\n }\n\n @Override\n public int getPrimaryEggColor() {\n return 13948116;\n }\n\n @Override\n public int getSecondaryEggColor() {\n return 8741209;\n }\n }\n\n public static class EntityKittenRagdoll extends EntityKittenBase {\n\n public EntityKittenRagdoll(World worldIn) {\n super(worldIn);\n this.type = CatType.RAGDOLL;\n }\n\n @Override\n public int getPrimaryEggColor() {\n return 13948116;\n }\n\n @Override\n public int getSecondaryEggColor() {\n return 8741209;\n }\n }\n}\n"} {"task_id": "Java_2145", "language": "Java", "task_type": "method_body", "source_file": "java/github/capnkirok/animaniamod/src/main/java/com/animania/addons/catsdogs/common/entity/felids/CatRagdoll.java", "mask_start_position": 1296, "mask_end_position": 1335, "canonical_solution": "{\n return 8741209;\n }", "pre_mask_code": "package com.animania.addons.catsdogs.common.entity.felids;\n\nimport net.minecraft.world.World;\n\npublic class CatRagdoll {\n\n public static class EntityTomRagdoll extends EntityTomBase {\n\n public EntityTomRagdoll(World worldIn) {\n super(worldIn);\n this.type = CatType.RAGDOLL;\n }\n\n @Override\n public int getPrimaryEggColor() {\n return 13948116;\n }\n\n @Override\n public int getSecondaryEggColor() {\n return 8741209;\n }\n }\n\n public static class EntityQueenRagdoll extends EntityQueenBase {\n\n public EntityQueenRagdoll(World worldIn) {\n super(worldIn);\n this.type = CatType.RAGDOLL;\n }\n\n @Override\n public int getPrimaryEggColor() {\n return 13948116;\n }\n\n @Override\n public int getSecondaryEggColor() {\n return 8741209;\n }\n }\n\n public static class EntityKittenRagdoll extends EntityKittenBase {\n\n public EntityKittenRagdoll(World worldIn) {\n super(worldIn);\n this.type = CatType.RAGDOLL;\n }\n\n @Override\n public int getPrimaryEggColor() {\n return 13948116;\n }\n\n @Override\n public int getSecondaryEggColor() ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2146", "language": "Java", "task_type": "single_line", "source_file": "java/github/capnkirok/animaniamod/src/main/java/com/animania/addons/catsdogs/common/entity/felids/CatRagdoll.java", "mask_start_position": 394, "mask_end_position": 405, "canonical_solution": "n 13948116;", "pre_mask_code": "package com.animania.addons.catsdogs.common.entity.felids;\n\nimport net.minecraft.world.World;\n\npublic class CatRagdoll {\n\n public static class EntityTomRagdoll extends EntityTomBase {\n\n public EntityTomRagdoll(World worldIn) {\n super(worldIn);\n this.type = CatType.RAGDOLL;\n }\n\n @Override\n public int getPrimaryEggColor() {\n retur", "post_mask_code": "\n }\n\n @Override\n public int getSecondaryEggColor() {\n return 8741209;\n }\n }\n\n public static class EntityQueenRagdoll extends EntityQueenBase {\n\n public EntityQueenRagdoll(World worldIn) {\n super(worldIn);\n this.type = CatType.RAGDOLL;\n }\n\n @Override\n public int getPrimaryEggColor() {\n return 13948116;\n }\n\n @Override\n public int getSecondaryEggColor() {\n return 8741209;\n }\n }\n\n public static class EntityKittenRagdoll extends EntityKittenBase {\n\n public EntityKittenRagdoll(World worldIn) {\n super(worldIn);\n this.type = CatType.RAGDOLL;\n }\n\n @Override\n public int getPrimaryEggColor() {\n return 13948116;\n }\n\n @Override\n public int getSecondaryEggColor() {\n return 8741209;\n }\n }\n}\n"} {"task_id": "Java_2147", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/eclipselink.core.test/src/it/java/org/eclipse/persistence/testing/tests/unitofwork/writechanges/WriteChanges_Release_TestCase.java", "mask_start_position": 497, "mask_end_position": 530, "canonical_solution": "@Override\n public void test() ", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.testing.tests.unitofwork.writechanges;\n\nimport org.eclipse.persistence.internal.sessions.UnitOfWorkImpl;\nimport org.eclipse.persistence.sessions.UnitOfWork;\nimport org.eclipse.persistence.testing.framework.AutoVerifyTestCase;\nimport org.eclipse.persistence.testing.framework.TestErrorException;\n\n/**\n * @author smcritch\n */\npublic class WriteChanges_Release_TestCase extends AutoVerifyTestCase {\n\n ", "post_mask_code": "{\n UnitOfWork uow = getSession().acquireUnitOfWork();\n uow.writeChanges();\n uow.release();\n if (((UnitOfWorkImpl) uow).isInTransaction()) {\n throw new TestErrorException(\"Even though release was called, since we already wrote changes and started the transaction, it must be rolled back.\");\n }\n }\n}\n"} {"task_id": "Java_2148", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/eclipselink.core.test/src/it/java/org/eclipse/persistence/testing/tests/unitofwork/writechanges/WriteChanges_Release_TestCase.java", "mask_start_position": 530, "mask_end_position": 874, "canonical_solution": "{\n UnitOfWork uow = getSession().acquireUnitOfWork();\n uow.writeChanges();\n uow.release();\n if (((UnitOfWorkImpl) uow).isInTransaction()) {\n throw new TestErrorException(\"Even though release was called, since we already wrote changes and started the transaction, it must be rolled back.\");\n }\n }", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.testing.tests.unitofwork.writechanges;\n\nimport org.eclipse.persistence.internal.sessions.UnitOfWorkImpl;\nimport org.eclipse.persistence.sessions.UnitOfWork;\nimport org.eclipse.persistence.testing.framework.AutoVerifyTestCase;\nimport org.eclipse.persistence.testing.framework.TestErrorException;\n\n/**\n * @author smcritch\n */\npublic class WriteChanges_Release_TestCase extends AutoVerifyTestCase {\n\n @Override\n public void test() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2149", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse-ee4j/eclipselink/foundation/eclipselink.core.test/src/it/java/org/eclipse/persistence/testing/tests/unitofwork/writechanges/WriteChanges_Release_TestCase.java", "mask_start_position": 606, "mask_end_position": 618, "canonical_solution": "teChanges();", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.testing.tests.unitofwork.writechanges;\n\nimport org.eclipse.persistence.internal.sessions.UnitOfWorkImpl;\nimport org.eclipse.persistence.sessions.UnitOfWork;\nimport org.eclipse.persistence.testing.framework.AutoVerifyTestCase;\nimport org.eclipse.persistence.testing.framework.TestErrorException;\n\n/**\n * @author smcritch\n */\npublic class WriteChanges_Release_TestCase extends AutoVerifyTestCase {\n\n @Override\n public void test() {\n UnitOfWork uow = getSession().acquireUnitOfWork();\n uow.wri", "post_mask_code": "\n uow.release();\n if (((UnitOfWorkImpl) uow).isInTransaction()) {\n throw new TestErrorException(\"Even though release was called, since we already wrote changes and started the transaction, it must be rolled back.\");\n }\n }\n}\n"} {"task_id": "Java_2150", "language": "Java", "task_type": "method_signature", "source_file": "java/github/liferay/liferay-portal/portal-impl/src/com/liferay/portal/spring/bean/BeanReferenceAnnotationBeanPostProcessor.java", "mask_start_position": 1468, "mask_end_position": 1580, "canonical_solution": "@Override\n public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException ", "pre_mask_code": "package com.liferay.portal.spring.bean;\n\nimport com.liferay.petra.string.StringBundler;\nimport com.liferay.portal.internal.cluster.ClusterableAdvice;\nimport com.liferay.portal.kernel.bean.BeanLocatorException;\nimport com.liferay.portal.kernel.bean.BeanReference;\nimport com.liferay.portal.kernel.bean.PortalBeanLocatorUtil;\nimport com.liferay.portal.kernel.log.Log;\nimport com.liferay.portal.kernel.log.LogFactoryUtil;\nimport com.liferay.portal.kernel.module.framework.service.IdentifiableOSGiService;\nimport java.io.PrintWriter;\nimport java.io.StringWriter;\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.springframework.beans.BeansException;\nimport org.springframework.beans.factory.BeanCreationException;\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.beans.factory.NoSuchBeanDefinitionException;\nimport org.springframework.beans.factory.config.BeanPostProcessor;\nimport org.springframework.util.ReflectionUtils;\n\n/**\n * @author Michael Young\n * @author Shuyang Zhou\n */\npublic class BeanReferenceAnnotationBeanPostProcessor implements BeanPostProcessor {\n\n public BeanReferenceAnnotationBeanPostProcessor(BeanFactory beanFactory) {\n _beanFactory = beanFactory;\n }\n\n public void destroy() {\n _beans.clear();\n }\n\n @Override\n public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {\n return bean;\n }\n\n ", "post_mask_code": "{\n if (!(bean instanceof IdentifiableOSGiService) && beanName.endsWith(\"Service\") && _log.isWarnEnabled()) {\n _log.warn(StringBundler.concat(beanName, \" should implement \", IdentifiableOSGiService.class.getName(), \" for \", ClusterableAdvice.class.getName()));\n }\n _autoInject(bean, beanName, bean.getClass());\n return bean;\n }\n\n private void _autoInject(Object targetBean, String targetBeanName, Class beanClass) {\n if ((beanClass == null) || beanClass.isInterface()) {\n return;\n }\n String className = beanClass.getName();\n if (className.equals(_JAVA_LANG_OBJECT) || className.startsWith(_ORG_SPRINGFRAMEWORK)) {\n return;\n }\n Field[] fields = beanClass.getDeclaredFields();\n for (Field field : fields) {\n BeanReference beanReference = field.getAnnotation(BeanReference.class);\n String referencedBeanName = null;\n Class referencedBeanType = null;\n if (beanReference != null) {\n referencedBeanName = beanReference.name();\n referencedBeanType = beanReference.type();\n } else {\n continue;\n }\n if (!Object.class.equals(referencedBeanType)) {\n referencedBeanName = referencedBeanType.getName();\n }\n Object referencedBean = _beans.get(referencedBeanName);\n if (referencedBean == null) {\n try {\n referencedBean = _beanFactory.getBean(referencedBeanName);\n } catch (NoSuchBeanDefinitionException noSuchBeanDefinitionException) {\n try {\n referencedBean = PortalBeanLocatorUtil.locate(referencedBeanName);\n } catch (BeanLocatorException beanLocatorException) {\n StringWriter stringWriter = new StringWriter();\n try (PrintWriter printWriter = new PrintWriter(stringWriter)) {\n printWriter.print(\"BeanFactory could not find bean: \");\n noSuchBeanDefinitionException.printStackTrace(printWriter);\n printWriter.print(\" and PortalBeanLocator failed with: \");\n printWriter.append(beanLocatorException.getMessage());\n }\n throw new BeanLocatorException(stringWriter.toString(), beanLocatorException);\n }\n }\n _beans.put(referencedBeanName, referencedBean);\n }\n ReflectionUtils.makeAccessible(field);\n try {\n field.set(targetBean, referencedBean);\n } catch (Throwable throwable) {\n throw new BeanCreationException(targetBeanName, \"Could not inject BeanReference fields\", throwable);\n }\n }\n _autoInject(targetBean, targetBeanName, beanClass.getSuperclass());\n }\n\n private static final String _JAVA_LANG_OBJECT = \"java.lang.Object\";\n\n private static final String _ORG_SPRINGFRAMEWORK = \"org.springframework\";\n\n private static final Log _log = LogFactoryUtil.getLog(BeanReferenceAnnotationBeanPostProcessor.class);\n\n private final BeanFactory _beanFactory;\n\n private final Map _beans = new HashMap<>();\n}\n"} {"task_id": "Java_2151", "language": "Java", "task_type": "method_body", "source_file": "java/github/liferay/liferay-portal/portal-impl/src/com/liferay/portal/spring/bean/BeanReferenceAnnotationBeanPostProcessor.java", "mask_start_position": 1580, "mask_end_position": 1948, "canonical_solution": "{\n if (!(bean instanceof IdentifiableOSGiService) && beanName.endsWith(\"Service\") && _log.isWarnEnabled()) {\n _log.warn(StringBundler.concat(beanName, \" should implement \", IdentifiableOSGiService.class.getName(), \" for \", ClusterableAdvice.class.getName()));\n }\n _autoInject(bean, beanName, bean.getClass());\n return bean;\n }", "pre_mask_code": "package com.liferay.portal.spring.bean;\n\nimport com.liferay.petra.string.StringBundler;\nimport com.liferay.portal.internal.cluster.ClusterableAdvice;\nimport com.liferay.portal.kernel.bean.BeanLocatorException;\nimport com.liferay.portal.kernel.bean.BeanReference;\nimport com.liferay.portal.kernel.bean.PortalBeanLocatorUtil;\nimport com.liferay.portal.kernel.log.Log;\nimport com.liferay.portal.kernel.log.LogFactoryUtil;\nimport com.liferay.portal.kernel.module.framework.service.IdentifiableOSGiService;\nimport java.io.PrintWriter;\nimport java.io.StringWriter;\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.springframework.beans.BeansException;\nimport org.springframework.beans.factory.BeanCreationException;\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.beans.factory.NoSuchBeanDefinitionException;\nimport org.springframework.beans.factory.config.BeanPostProcessor;\nimport org.springframework.util.ReflectionUtils;\n\n/**\n * @author Michael Young\n * @author Shuyang Zhou\n */\npublic class BeanReferenceAnnotationBeanPostProcessor implements BeanPostProcessor {\n\n public BeanReferenceAnnotationBeanPostProcessor(BeanFactory beanFactory) {\n _beanFactory = beanFactory;\n }\n\n public void destroy() {\n _beans.clear();\n }\n\n @Override\n public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {\n return bean;\n }\n\n @Override\n public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException ", "post_mask_code": "\n\n private void _autoInject(Object targetBean, String targetBeanName, Class beanClass) {\n if ((beanClass == null) || beanClass.isInterface()) {\n return;\n }\n String className = beanClass.getName();\n if (className.equals(_JAVA_LANG_OBJECT) || className.startsWith(_ORG_SPRINGFRAMEWORK)) {\n return;\n }\n Field[] fields = beanClass.getDeclaredFields();\n for (Field field : fields) {\n BeanReference beanReference = field.getAnnotation(BeanReference.class);\n String referencedBeanName = null;\n Class referencedBeanType = null;\n if (beanReference != null) {\n referencedBeanName = beanReference.name();\n referencedBeanType = beanReference.type();\n } else {\n continue;\n }\n if (!Object.class.equals(referencedBeanType)) {\n referencedBeanName = referencedBeanType.getName();\n }\n Object referencedBean = _beans.get(referencedBeanName);\n if (referencedBean == null) {\n try {\n referencedBean = _beanFactory.getBean(referencedBeanName);\n } catch (NoSuchBeanDefinitionException noSuchBeanDefinitionException) {\n try {\n referencedBean = PortalBeanLocatorUtil.locate(referencedBeanName);\n } catch (BeanLocatorException beanLocatorException) {\n StringWriter stringWriter = new StringWriter();\n try (PrintWriter printWriter = new PrintWriter(stringWriter)) {\n printWriter.print(\"BeanFactory could not find bean: \");\n noSuchBeanDefinitionException.printStackTrace(printWriter);\n printWriter.print(\" and PortalBeanLocator failed with: \");\n printWriter.append(beanLocatorException.getMessage());\n }\n throw new BeanLocatorException(stringWriter.toString(), beanLocatorException);\n }\n }\n _beans.put(referencedBeanName, referencedBean);\n }\n ReflectionUtils.makeAccessible(field);\n try {\n field.set(targetBean, referencedBean);\n } catch (Throwable throwable) {\n throw new BeanCreationException(targetBeanName, \"Could not inject BeanReference fields\", throwable);\n }\n }\n _autoInject(targetBean, targetBeanName, beanClass.getSuperclass());\n }\n\n private static final String _JAVA_LANG_OBJECT = \"java.lang.Object\";\n\n private static final String _ORG_SPRINGFRAMEWORK = \"org.springframework\";\n\n private static final Log _log = LogFactoryUtil.getLog(BeanReferenceAnnotationBeanPostProcessor.class);\n\n private final BeanFactory _beanFactory;\n\n private final Map _beans = new HashMap<>();\n}\n"} {"task_id": "Java_2152", "language": "Java", "task_type": "single_line", "source_file": "java/github/liferay/liferay-portal/portal-impl/src/com/liferay/portal/spring/bean/BeanReferenceAnnotationBeanPostProcessor.java", "mask_start_position": 4533, "mask_end_position": 4565, "canonical_solution": "ame, beanClass.getSuperclass());", "pre_mask_code": "package com.liferay.portal.spring.bean;\n\nimport com.liferay.petra.string.StringBundler;\nimport com.liferay.portal.internal.cluster.ClusterableAdvice;\nimport com.liferay.portal.kernel.bean.BeanLocatorException;\nimport com.liferay.portal.kernel.bean.BeanReference;\nimport com.liferay.portal.kernel.bean.PortalBeanLocatorUtil;\nimport com.liferay.portal.kernel.log.Log;\nimport com.liferay.portal.kernel.log.LogFactoryUtil;\nimport com.liferay.portal.kernel.module.framework.service.IdentifiableOSGiService;\nimport java.io.PrintWriter;\nimport java.io.StringWriter;\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.springframework.beans.BeansException;\nimport org.springframework.beans.factory.BeanCreationException;\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.beans.factory.NoSuchBeanDefinitionException;\nimport org.springframework.beans.factory.config.BeanPostProcessor;\nimport org.springframework.util.ReflectionUtils;\n\n/**\n * @author Michael Young\n * @author Shuyang Zhou\n */\npublic class BeanReferenceAnnotationBeanPostProcessor implements BeanPostProcessor {\n\n public BeanReferenceAnnotationBeanPostProcessor(BeanFactory beanFactory) {\n _beanFactory = beanFactory;\n }\n\n public void destroy() {\n _beans.clear();\n }\n\n @Override\n public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {\n return bean;\n }\n\n @Override\n public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {\n if (!(bean instanceof IdentifiableOSGiService) && beanName.endsWith(\"Service\") && _log.isWarnEnabled()) {\n _log.warn(StringBundler.concat(beanName, \" should implement \", IdentifiableOSGiService.class.getName(), \" for \", ClusterableAdvice.class.getName()));\n }\n _autoInject(bean, beanName, bean.getClass());\n return bean;\n }\n\n private void _autoInject(Object targetBean, String targetBeanName, Class beanClass) {\n if ((beanClass == null) || beanClass.isInterface()) {\n return;\n }\n String className = beanClass.getName();\n if (className.equals(_JAVA_LANG_OBJECT) || className.startsWith(_ORG_SPRINGFRAMEWORK)) {\n return;\n }\n Field[] fields = beanClass.getDeclaredFields();\n for (Field field : fields) {\n BeanReference beanReference = field.getAnnotation(BeanReference.class);\n String referencedBeanName = null;\n Class referencedBeanType = null;\n if (beanReference != null) {\n referencedBeanName = beanReference.name();\n referencedBeanType = beanReference.type();\n } else {\n continue;\n }\n if (!Object.class.equals(referencedBeanType)) {\n referencedBeanName = referencedBeanType.getName();\n }\n Object referencedBean = _beans.get(referencedBeanName);\n if (referencedBean == null) {\n try {\n referencedBean = _beanFactory.getBean(referencedBeanName);\n } catch (NoSuchBeanDefinitionException noSuchBeanDefinitionException) {\n try {\n referencedBean = PortalBeanLocatorUtil.locate(referencedBeanName);\n } catch (BeanLocatorException beanLocatorException) {\n StringWriter stringWriter = new StringWriter();\n try (PrintWriter printWriter = new PrintWriter(stringWriter)) {\n printWriter.print(\"BeanFactory could not find bean: \");\n noSuchBeanDefinitionException.printStackTrace(printWriter);\n printWriter.print(\" and PortalBeanLocator failed with: \");\n printWriter.append(beanLocatorException.getMessage());\n }\n throw new BeanLocatorException(stringWriter.toString(), beanLocatorException);\n }\n }\n _beans.put(referencedBeanName, referencedBean);\n }\n ReflectionUtils.makeAccessible(field);\n try {\n field.set(targetBean, referencedBean);\n } catch (Throwable throwable) {\n throw new BeanCreationException(targetBeanName, \"Could not inject BeanReference fields\", throwable);\n }\n }\n _autoInject(targetBean, targetBeanN", "post_mask_code": "\n }\n\n private static final String _JAVA_LANG_OBJECT = \"java.lang.Object\";\n\n private static final String _ORG_SPRINGFRAMEWORK = \"org.springframework\";\n\n private static final Log _log = LogFactoryUtil.getLog(BeanReferenceAnnotationBeanPostProcessor.class);\n\n private final BeanFactory _beanFactory;\n\n private final Map _beans = new HashMap<>();\n}\n"} {"task_id": "Java_2153", "language": "Java", "task_type": "try_statement", "source_file": "java/github/liferay/liferay-portal/portal-impl/src/com/liferay/portal/spring/bean/BeanReferenceAnnotationBeanPostProcessor.java", "mask_start_position": 4244, "mask_end_position": 4479, "canonical_solution": "try {\n field.set(targetBean, referencedBean);\n } catch (Throwable throwable) {\n throw new BeanCreationException(targetBeanName, \"Could not inject BeanReference fields\", throwable);\n }", "pre_mask_code": "package com.liferay.portal.spring.bean;\n\nimport com.liferay.petra.string.StringBundler;\nimport com.liferay.portal.internal.cluster.ClusterableAdvice;\nimport com.liferay.portal.kernel.bean.BeanLocatorException;\nimport com.liferay.portal.kernel.bean.BeanReference;\nimport com.liferay.portal.kernel.bean.PortalBeanLocatorUtil;\nimport com.liferay.portal.kernel.log.Log;\nimport com.liferay.portal.kernel.log.LogFactoryUtil;\nimport com.liferay.portal.kernel.module.framework.service.IdentifiableOSGiService;\nimport java.io.PrintWriter;\nimport java.io.StringWriter;\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.springframework.beans.BeansException;\nimport org.springframework.beans.factory.BeanCreationException;\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.beans.factory.NoSuchBeanDefinitionException;\nimport org.springframework.beans.factory.config.BeanPostProcessor;\nimport org.springframework.util.ReflectionUtils;\n\n/**\n * @author Michael Young\n * @author Shuyang Zhou\n */\npublic class BeanReferenceAnnotationBeanPostProcessor implements BeanPostProcessor {\n\n public BeanReferenceAnnotationBeanPostProcessor(BeanFactory beanFactory) {\n _beanFactory = beanFactory;\n }\n\n public void destroy() {\n _beans.clear();\n }\n\n @Override\n public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {\n return bean;\n }\n\n @Override\n public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {\n if (!(bean instanceof IdentifiableOSGiService) && beanName.endsWith(\"Service\") && _log.isWarnEnabled()) {\n _log.warn(StringBundler.concat(beanName, \" should implement \", IdentifiableOSGiService.class.getName(), \" for \", ClusterableAdvice.class.getName()));\n }\n _autoInject(bean, beanName, bean.getClass());\n return bean;\n }\n\n private void _autoInject(Object targetBean, String targetBeanName, Class beanClass) {\n if ((beanClass == null) || beanClass.isInterface()) {\n return;\n }\n String className = beanClass.getName();\n if (className.equals(_JAVA_LANG_OBJECT) || className.startsWith(_ORG_SPRINGFRAMEWORK)) {\n return;\n }\n Field[] fields = beanClass.getDeclaredFields();\n for (Field field : fields) {\n BeanReference beanReference = field.getAnnotation(BeanReference.class);\n String referencedBeanName = null;\n Class referencedBeanType = null;\n if (beanReference != null) {\n referencedBeanName = beanReference.name();\n referencedBeanType = beanReference.type();\n } else {\n continue;\n }\n if (!Object.class.equals(referencedBeanType)) {\n referencedBeanName = referencedBeanType.getName();\n }\n Object referencedBean = _beans.get(referencedBeanName);\n if (referencedBean == null) {\n try {\n referencedBean = _beanFactory.getBean(referencedBeanName);\n } catch (NoSuchBeanDefinitionException noSuchBeanDefinitionException) {\n try {\n referencedBean = PortalBeanLocatorUtil.locate(referencedBeanName);\n } catch (BeanLocatorException beanLocatorException) {\n StringWriter stringWriter = new StringWriter();\n try (PrintWriter printWriter = new PrintWriter(stringWriter)) {\n printWriter.print(\"BeanFactory could not find bean: \");\n noSuchBeanDefinitionException.printStackTrace(printWriter);\n printWriter.print(\" and PortalBeanLocator failed with: \");\n printWriter.append(beanLocatorException.getMessage());\n }\n throw new BeanLocatorException(stringWriter.toString(), beanLocatorException);\n }\n }\n _beans.put(referencedBeanName, referencedBean);\n }\n ReflectionUtils.makeAccessible(field);\n ", "post_mask_code": "\n }\n _autoInject(targetBean, targetBeanName, beanClass.getSuperclass());\n }\n\n private static final String _JAVA_LANG_OBJECT = \"java.lang.Object\";\n\n private static final String _ORG_SPRINGFRAMEWORK = \"org.springframework\";\n\n private static final Log _log = LogFactoryUtil.getLog(BeanReferenceAnnotationBeanPostProcessor.class);\n\n private final BeanFactory _beanFactory;\n\n private final Map _beans = new HashMap<>();\n}\n"} {"task_id": "Java_2154", "language": "Java", "task_type": "method_signature", "source_file": "java/github/BukkitPE/BukkitPE/src/main/java/net/BukkitPE/item/ItemSwordIron.java", "mask_start_position": 347, "mask_end_position": 391, "canonical_solution": "@Override\n public int getMaxDurability() ", "pre_mask_code": "package net.BukkitPE.item;\n\n/**\n * BukkitPE Project\n */\npublic class ItemSwordIron extends ItemTool {\n\n public ItemSwordIron() {\n this(0, 1);\n }\n\n public ItemSwordIron(Integer meta) {\n this(meta, 1);\n }\n\n public ItemSwordIron(Integer meta, int count) {\n super(IRON_SWORD, meta, count, \"Iron Sword\");\n }\n\n ", "post_mask_code": "{\n return ItemTool.DURABILITY_IRON;\n }\n\n @Override\n public boolean isSword() {\n return true;\n }\n\n @Override\n public int getTier() {\n return ItemTool.TIER_IRON;\n }\n}\n"} {"task_id": "Java_2155", "language": "Java", "task_type": "method_body", "source_file": "java/github/BukkitPE/BukkitPE/src/main/java/net/BukkitPE/item/ItemSwordIron.java", "mask_start_position": 391, "mask_end_position": 439, "canonical_solution": "{\n return ItemTool.DURABILITY_IRON;\n }", "pre_mask_code": "package net.BukkitPE.item;\n\n/**\n * BukkitPE Project\n */\npublic class ItemSwordIron extends ItemTool {\n\n public ItemSwordIron() {\n this(0, 1);\n }\n\n public ItemSwordIron(Integer meta) {\n this(meta, 1);\n }\n\n public ItemSwordIron(Integer meta, int count) {\n super(IRON_SWORD, meta, count, \"Iron Sword\");\n }\n\n @Override\n public int getMaxDurability() ", "post_mask_code": "\n\n @Override\n public boolean isSword() {\n return true;\n }\n\n @Override\n public int getTier() {\n return ItemTool.TIER_IRON;\n }\n}\n"} {"task_id": "Java_2156", "language": "Java", "task_type": "single_line", "source_file": "java/github/BukkitPE/BukkitPE/src/main/java/net/BukkitPE/item/ItemSwordIron.java", "mask_start_position": 403, "mask_end_position": 433, "canonical_solution": "turn ItemTool.DURABILITY_IRON;", "pre_mask_code": "package net.BukkitPE.item;\n\n/**\n * BukkitPE Project\n */\npublic class ItemSwordIron extends ItemTool {\n\n public ItemSwordIron() {\n this(0, 1);\n }\n\n public ItemSwordIron(Integer meta) {\n this(meta, 1);\n }\n\n public ItemSwordIron(Integer meta, int count) {\n super(IRON_SWORD, meta, count, \"Iron Sword\");\n }\n\n @Override\n public int getMaxDurability() {\n re", "post_mask_code": "\n }\n\n @Override\n public boolean isSword() {\n return true;\n }\n\n @Override\n public int getTier() {\n return ItemTool.TIER_IRON;\n }\n}\n"} {"task_id": "Java_2157", "language": "Java", "task_type": "method_signature", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/iotvideo/v20201215/models/DescribeBalanceResponse.java", "mask_start_position": 993, "mask_end_position": 1022, "canonical_solution": "public String getRequestId() ", "pre_mask_code": "package com.tencentcloudapi.iotvideo.v20201215.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class DescribeBalanceResponse extends AbstractModel {\n\n /**\n * 账户余额,单位:分(人民币)。\n */\n @SerializedName(\"Balance\")\n @Expose\n private Long Balance;\n\n /**\n * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n */\n @SerializedName(\"RequestId\")\n @Expose\n private String RequestId;\n\n /**\n * Get 账户余额,单位:分(人民币)。\n * @return Balance 账户余额,单位:分(人民币)。\n */\n public Long getBalance() {\n return this.Balance;\n }\n\n /**\n * Set 账户余额,单位:分(人民币)。\n * @param Balance 账户余额,单位:分(人民币)。\n */\n public void setBalance(Long Balance) {\n this.Balance = Balance;\n }\n\n /**\n * Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n * @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n */\n ", "post_mask_code": "{\n return this.RequestId;\n }\n\n /**\n * Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n * @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n */\n public void setRequestId(String RequestId) {\n this.RequestId = RequestId;\n }\n\n public DescribeBalanceResponse() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public DescribeBalanceResponse(DescribeBalanceResponse source) {\n if (source.Balance != null) {\n this.Balance = new Long(source.Balance);\n }\n if (source.RequestId != null) {\n this.RequestId = new String(source.RequestId);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) {\n this.setParamSimple(map, prefix + \"Balance\", this.Balance);\n this.setParamSimple(map, prefix + \"RequestId\", this.RequestId);\n }\n}\n"} {"task_id": "Java_2158", "language": "Java", "task_type": "method_body", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/iotvideo/v20201215/models/DescribeBalanceResponse.java", "mask_start_position": 1962, "mask_end_position": 2109, "canonical_solution": "{\n this.setParamSimple(map, prefix + \"Balance\", this.Balance);\n this.setParamSimple(map, prefix + \"RequestId\", this.RequestId);\n }", "pre_mask_code": "package com.tencentcloudapi.iotvideo.v20201215.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class DescribeBalanceResponse extends AbstractModel {\n\n /**\n * 账户余额,单位:分(人民币)。\n */\n @SerializedName(\"Balance\")\n @Expose\n private Long Balance;\n\n /**\n * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n */\n @SerializedName(\"RequestId\")\n @Expose\n private String RequestId;\n\n /**\n * Get 账户余额,单位:分(人民币)。\n * @return Balance 账户余额,单位:分(人民币)。\n */\n public Long getBalance() {\n return this.Balance;\n }\n\n /**\n * Set 账户余额,单位:分(人民币)。\n * @param Balance 账户余额,单位:分(人民币)。\n */\n public void setBalance(Long Balance) {\n this.Balance = Balance;\n }\n\n /**\n * Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n * @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n */\n public String getRequestId() {\n return this.RequestId;\n }\n\n /**\n * Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n * @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n */\n public void setRequestId(String RequestId) {\n this.RequestId = RequestId;\n }\n\n public DescribeBalanceResponse() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public DescribeBalanceResponse(DescribeBalanceResponse source) {\n if (source.Balance != null) {\n this.Balance = new Long(source.Balance);\n }\n if (source.RequestId != null) {\n this.RequestId = new String(source.RequestId);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2159", "language": "Java", "task_type": "single_line", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/iotvideo/v20201215/models/DescribeBalanceResponse.java", "mask_start_position": 2018, "mask_end_position": 2031, "canonical_solution": "his.Balance);", "pre_mask_code": "package com.tencentcloudapi.iotvideo.v20201215.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class DescribeBalanceResponse extends AbstractModel {\n\n /**\n * 账户余额,单位:分(人民币)。\n */\n @SerializedName(\"Balance\")\n @Expose\n private Long Balance;\n\n /**\n * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n */\n @SerializedName(\"RequestId\")\n @Expose\n private String RequestId;\n\n /**\n * Get 账户余额,单位:分(人民币)。\n * @return Balance 账户余额,单位:分(人民币)。\n */\n public Long getBalance() {\n return this.Balance;\n }\n\n /**\n * Set 账户余额,单位:分(人民币)。\n * @param Balance 账户余额,单位:分(人民币)。\n */\n public void setBalance(Long Balance) {\n this.Balance = Balance;\n }\n\n /**\n * Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n * @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n */\n public String getRequestId() {\n return this.RequestId;\n }\n\n /**\n * Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n * @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n */\n public void setRequestId(String RequestId) {\n this.RequestId = RequestId;\n }\n\n public DescribeBalanceResponse() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public DescribeBalanceResponse(DescribeBalanceResponse source) {\n if (source.Balance != null) {\n this.Balance = new Long(source.Balance);\n }\n if (source.RequestId != null) {\n this.RequestId = new String(source.RequestId);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) {\n this.setParamSimple(map, prefix + \"Balance\", t", "post_mask_code": "\n this.setParamSimple(map, prefix + \"RequestId\", this.RequestId);\n }\n}\n"} {"task_id": "Java_2160", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/iotvideo/v20201215/models/DescribeBalanceResponse.java", "mask_start_position": 1203, "mask_end_position": 1289, "canonical_solution": "public void setRequestId(String RequestId) {\n this.RequestId = RequestId;\n }", "pre_mask_code": "package com.tencentcloudapi.iotvideo.v20201215.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class DescribeBalanceResponse extends AbstractModel {\n\n /**\n * 账户余额,单位:分(人民币)。\n */\n @SerializedName(\"Balance\")\n @Expose\n private Long Balance;\n\n /**\n * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n */\n @SerializedName(\"RequestId\")\n @Expose\n private String RequestId;\n\n /**\n * Get 账户余额,单位:分(人民币)。\n * @return Balance 账户余额,单位:分(人民币)。\n */\n public Long getBalance() {\n return this.Balance;\n }\n\n /**\n * Set 账户余额,单位:分(人民币)。\n * @param Balance 账户余额,单位:分(人民币)。\n */\n public void setBalance(Long Balance) {\n this.Balance = Balance;\n }\n\n /**\n * Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n * @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n */\n public String getRequestId() {\n return this.RequestId;\n }\n\n /**\n * Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n * @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n */\n ", "post_mask_code": "\n\n public DescribeBalanceResponse() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public DescribeBalanceResponse(DescribeBalanceResponse source) {\n if (source.Balance != null) {\n this.Balance = new Long(source.Balance);\n }\n if (source.RequestId != null) {\n this.RequestId = new String(source.RequestId);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) {\n this.setParamSimple(map, prefix + \"Balance\", this.Balance);\n this.setParamSimple(map, prefix + \"RequestId\", this.RequestId);\n }\n}\n"} {"task_id": "Java_2161", "language": "Java", "task_type": "method_signature", "source_file": "java/github/algorithm007-class02/algorithm007-class02/Week_06/G20200343040164/LeetCode_221_0164.java", "mask_start_position": 159, "mask_end_position": 201, "canonical_solution": "public int maximalSquare(char[][] matrix) ", "pre_mask_code": "// 在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。\n// Related Topics 动态规划\n// leetcode submit region begin(Prohibit modification and deletion)\nclass Solution {\n\n ", "post_mask_code": "{\n int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;\n int[] dp = new int[cols + 1];\n int maxsqlen = 0, pre = 0;\n for (int i = 1; i <= rows; i++) {\n for (int j = 1; j <= cols; j++) {\n int temp = dp[j];\n if (matrix[i - 1][j - 1] == '1') {\n dp[j] = Math.min(Math.min(dp[j - 1], pre), dp[j]) + 1;\n maxsqlen = Math.max(maxsqlen, dp[j]);\n } else\n dp[j] = 0;\n pre = temp;\n }\n }\n return maxsqlen * maxsqlen;\n }\n}\n// leetcode submit region end(Prohibit modification and deletion)\n"} {"task_id": "Java_2162", "language": "Java", "task_type": "single_line", "source_file": "java/github/algorithm007-class02/algorithm007-class02/Week_06/G20200343040164/LeetCode_221_0164.java", "mask_start_position": 287, "mask_end_position": 314, "canonical_solution": "t[] dp = new int[cols + 1];", "pre_mask_code": "// 在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。\n// Related Topics 动态规划\n// leetcode submit region begin(Prohibit modification and deletion)\nclass Solution {\n\n public int maximalSquare(char[][] matrix) {\n int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;\n in", "post_mask_code": "\n int maxsqlen = 0, pre = 0;\n for (int i = 1; i <= rows; i++) {\n for (int j = 1; j <= cols; j++) {\n int temp = dp[j];\n if (matrix[i - 1][j - 1] == '1') {\n dp[j] = Math.min(Math.min(dp[j - 1], pre), dp[j]) + 1;\n maxsqlen = Math.max(maxsqlen, dp[j]);\n } else\n dp[j] = 0;\n pre = temp;\n }\n }\n return maxsqlen * maxsqlen;\n }\n}\n// leetcode submit region end(Prohibit modification and deletion)\n"} {"task_id": "Java_2163", "language": "Java", "task_type": "for_statement", "source_file": "java/github/algorithm007-class02/algorithm007-class02/Week_06/G20200343040164/LeetCode_221_0164.java", "mask_start_position": 404, "mask_end_position": 751, "canonical_solution": "for (int j = 1; j <= cols; j++) {\n int temp = dp[j];\n if (matrix[i - 1][j - 1] == '1') {\n dp[j] = Math.min(Math.min(dp[j - 1], pre), dp[j]) + 1;\n maxsqlen = Math.max(maxsqlen, dp[j]);\n } else\n dp[j] = 0;\n pre = temp;\n }", "pre_mask_code": "// 在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。\n// Related Topics 动态规划\n// leetcode submit region begin(Prohibit modification and deletion)\nclass Solution {\n\n public int maximalSquare(char[][] matrix) {\n int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;\n int[] dp = new int[cols + 1];\n int maxsqlen = 0, pre = 0;\n for (int i = 1; i <= rows; i++) {\n ", "post_mask_code": "\n }\n return maxsqlen * maxsqlen;\n }\n}\n// leetcode submit region end(Prohibit modification and deletion)\n"} {"task_id": "Java_2164", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cnzx219/QingTingCheat/src/com/tencent/mm/sdk/openapi/WXApiImplV10.java", "mask_start_position": 4823, "mask_end_position": 4892, "canonical_solution": "private boolean sendPayReq(Context paramContext, Bundle paramBundle) ", "pre_mask_code": "package com.tencent.mm.sdk.openapi;\n\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.PackageManager.NameNotFoundException;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport com.tencent.mm.sdk.a.a.b;\nimport com.tencent.mm.sdk.modelbase.BaseReq;\nimport com.tencent.mm.sdk.modelbase.BaseResp;\nimport com.tencent.mm.sdk.modelbiz.AddCardToWXCardPackage.Resp;\nimport com.tencent.mm.sdk.modelmsg.GetMessageFromWX.Req;\nimport com.tencent.mm.sdk.modelmsg.LaunchFromWX.Req;\nimport com.tencent.mm.sdk.modelmsg.SendAuth.Resp;\nimport com.tencent.mm.sdk.modelmsg.SendMessageToWX.Resp;\nimport com.tencent.mm.sdk.modelmsg.ShowMessageFromWX.Req;\nimport com.tencent.mm.sdk.modelpay.PayResp;\n\nfinal class WXApiImplV10 implements IWXAPI {\n\n private static final String TAG = \"MicroMsg.SDK.WXApiImplV10\";\n\n private static String wxappPayEntryClassname = null;\n\n private String appId;\n\n private boolean checkSignature = false;\n\n private Context context;\n\n private boolean detached = false;\n\n WXApiImplV10(Context paramContext, String paramString, boolean paramBoolean) {\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \", appId = \" + paramString + \", checkSignature = \" + paramBoolean);\n this.context = paramContext;\n this.appId = paramString;\n this.checkSignature = paramBoolean;\n }\n\n private boolean checkSumConsistent(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2) {\n if ((paramArrayOfByte1 == null) || (paramArrayOfByte1.length == 0) || (paramArrayOfByte2 == null) || (paramArrayOfByte2.length == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checkSumConsistent fail, invalid arguments\");\n return false;\n }\n if (paramArrayOfByte1.length != paramArrayOfByte2.length) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checkSumConsistent fail, length is different\");\n return false;\n }\n for (int i = 0; ; i++) {\n if (i >= paramArrayOfByte1.length)\n break label66;\n if (paramArrayOfByte1[i] != paramArrayOfByte2[i])\n break;\n }\n label66: return true;\n }\n\n private boolean sendAddCardToWX(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/addCardToWX\");\n String[] arrayOfString = new String[3];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_add_card_to_wx_card_list\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_basereq_transaction\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendJumpToBizProfileReq(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/jumpToBizProfile\");\n String[] arrayOfString = new String[5];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_jump_to_biz_profile_req_to_user_name\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_jump_to_biz_profile_req_ext_msg\");\n arrayOfString[3] = paramBundle.getInt(\"_wxapi_jump_to_biz_profile_req_scene\");\n arrayOfString[4] = paramBundle.getInt(\"_wxapi_jump_to_biz_profile_req_profile_type\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendJumpToBizWebviewReq(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/jumpToBizProfile\");\n String[] arrayOfString = new String[4];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_jump_to_biz_webview_req_to_user_name\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_jump_to_biz_webview_req_ext_msg\");\n arrayOfString[3] = paramBundle.getInt(\"_wxapi_jump_to_biz_webview_req_scene\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n ", "post_mask_code": "{\n if (wxappPayEntryClassname == null) {\n wxappPayEntryClassname = new MMSharedPreferences(paramContext).getString(\"_wxapp_pay_entry_classname_\", null);\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"pay, set wxappPayEntryClassname = \" + wxappPayEntryClassname);\n if (wxappPayEntryClassname == null) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"pay fail, wxappPayEntryClassname is null\");\n return false;\n }\n }\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = paramBundle;\n locala.b = \"com.tencent.mm\";\n locala.c = wxappPayEntryClassname;\n return com.tencent.mm.sdk.a.a.a(paramContext, locala);\n }\n\n public final void detach() {\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"detach\");\n this.detached = true;\n this.context = null;\n }\n\n public final int getWXAppSupportAPI() {\n if (this.detached)\n throw new IllegalStateException(\"getWXAppSupportAPI fail, WXMsgImpl has been detached\");\n if (!isWXAppInstalled()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"open wx app failed, not installed or signature check failed\");\n return 0;\n }\n return new MMSharedPreferences(this.context).getInt(\"_build_info_sdk_int_\", 0);\n }\n\n public final boolean handleIntent(Intent paramIntent, IWXAPIEventHandler paramIWXAPIEventHandler) {\n if (!WXApiImplComm.isIntentFromWx(paramIntent, \"com.tencent.mm.openapi.token\")) {\n com.tencent.mm.sdk.b.a.b(\"MicroMsg.SDK.WXApiImplV10\", \"handleIntent fail, intent not from weixin msg\");\n return false;\n }\n if (this.detached)\n throw new IllegalStateException(\"handleIntent fail, WXMsgImpl has been detached\");\n String str1 = paramIntent.getStringExtra(\"_mmessage_content\");\n int i = paramIntent.getIntExtra(\"_mmessage_sdkVersion\", 0);\n String str2 = paramIntent.getStringExtra(\"_mmessage_appPackage\");\n if ((str2 == null) || (str2.length() == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"invalid argument\");\n return false;\n }\n if (!checkSumConsistent(paramIntent.getByteArrayExtra(\"_mmessage_checksum\"), b.a(str1, i, str2))) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checksum fail\");\n return false;\n }\n int j = paramIntent.getIntExtra(\"_wxapi_command_type\", 0);\n switch(j) {\n case 7:\n case 8:\n default:\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unknown cmd = \" + j);\n return false;\n case 1:\n paramIWXAPIEventHandler.onResp(new SendAuth.Resp(paramIntent.getExtras()));\n return true;\n case 2:\n paramIWXAPIEventHandler.onResp(new SendMessageToWX.Resp(paramIntent.getExtras()));\n return true;\n case 3:\n paramIWXAPIEventHandler.onReq(new GetMessageFromWX.Req(paramIntent.getExtras()));\n return true;\n case 4:\n paramIWXAPIEventHandler.onReq(new ShowMessageFromWX.Req(paramIntent.getExtras()));\n return true;\n case 5:\n paramIWXAPIEventHandler.onResp(new PayResp(paramIntent.getExtras()));\n return true;\n case 6:\n paramIWXAPIEventHandler.onReq(new LaunchFromWX.Req(paramIntent.getExtras()));\n return true;\n case 9:\n }\n paramIWXAPIEventHandler.onResp(new AddCardToWXCardPackage.Resp(paramIntent.getExtras()));\n return true;\n }\n\n public final boolean isWXAppInstalled() {\n if (this.detached)\n throw new IllegalStateException(\"isWXAppInstalled fail, WXMsgImpl has been detached\");\n try {\n PackageInfo localPackageInfo = this.context.getPackageManager().getPackageInfo(\"com.tencent.mm\", 64);\n if (localPackageInfo == null)\n return false;\n boolean bool = WXApiImplComm.validateAppSignature(this.context, localPackageInfo.signatures, this.checkSignature);\n return bool;\n } catch (PackageManager.NameNotFoundException localNameNotFoundException) {\n }\n return false;\n }\n\n public final boolean isWXAppSupportAPI() {\n if (this.detached)\n throw new IllegalStateException(\"isWXAppSupportAPI fail, WXMsgImpl has been detached\");\n return getWXAppSupportAPI() >= 570490883;\n }\n\n public final boolean openWXApp() {\n if (this.detached)\n throw new IllegalStateException(\"openWXApp fail, WXMsgImpl has been detached\");\n if (!isWXAppInstalled()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"open wx app failed, not installed or signature check failed\");\n return false;\n }\n try {\n this.context.startActivity(this.context.getPackageManager().getLaunchIntentForPackage(\"com.tencent.mm\"));\n return true;\n } catch (Exception localException) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"startActivity fail, exception = \" + localException.getMessage());\n }\n return false;\n }\n\n public final boolean registerApp(String paramString) {\n if (this.detached)\n throw new IllegalStateException(\"registerApp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"register app failed for wechat app signature check failed\");\n return false;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"registerApp, appId = \" + paramString);\n if (paramString != null)\n this.appId = paramString;\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"register app \" + this.context.getPackageName());\n com.tencent.mm.sdk.a.a.a.a locala = new com.tencent.mm.sdk.a.a.a.a();\n locala.f = \"com.tencent.mm\";\n locala.g = \"com.tencent.mm.plugin.openapi.Intent.ACTION_HANDLE_APP_REGISTER\";\n locala.d = (\"weixin://registerapp?appid=\" + this.appId);\n return com.tencent.mm.sdk.a.a.a.a(this.context, locala);\n }\n\n public final boolean sendReq(BaseReq paramBaseReq) {\n if (this.detached)\n throw new IllegalStateException(\"sendReq fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq failed for wechat app signature check failed\");\n return false;\n }\n if (!paramBaseReq.checkArgs()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq checkArgs fail\");\n return false;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq, req type = \" + paramBaseReq.getType());\n Bundle localBundle = new Bundle();\n paramBaseReq.toBundle(localBundle);\n if (paramBaseReq.getType() == 5)\n return sendPayReq(this.context, localBundle);\n if (paramBaseReq.getType() == 7)\n return sendJumpToBizProfileReq(this.context, localBundle);\n if (paramBaseReq.getType() == 8)\n return sendJumpToBizWebviewReq(this.context, localBundle);\n if (paramBaseReq.getType() == 9)\n return sendAddCardToWX(this.context, localBundle);\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = localBundle;\n locala.d = (\"weixin://sendreq?appid=\" + this.appId);\n locala.b = \"com.tencent.mm\";\n locala.c = \"com.tencent.mm.plugin.base.stub.WXEntryActivity\";\n return com.tencent.mm.sdk.a.a.a(this.context, locala);\n }\n\n public final boolean sendResp(BaseResp paramBaseResp) {\n if (this.detached)\n throw new IllegalStateException(\"sendResp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendResp failed for wechat app signature check failed\");\n return false;\n }\n if (!paramBaseResp.checkArgs()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendResp checkArgs fail\");\n return false;\n }\n Bundle localBundle = new Bundle();\n paramBaseResp.toBundle(localBundle);\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = localBundle;\n locala.d = (\"weixin://sendresp?appid=\" + this.appId);\n locala.b = \"com.tencent.mm\";\n locala.c = \"com.tencent.mm.plugin.base.stub.WXEntryActivity\";\n return com.tencent.mm.sdk.a.a.a(this.context, locala);\n }\n\n public final void unregisterApp() {\n if (this.detached)\n throw new IllegalStateException(\"unregisterApp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unregister app failed for wechat app signature check failed\");\n return;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"unregisterApp, appId = \" + this.appId);\n if ((this.appId == null) || (this.appId.length() == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unregisterApp fail, appId is empty\");\n return;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"unregister app \" + this.context.getPackageName());\n com.tencent.mm.sdk.a.a.a.a locala = new com.tencent.mm.sdk.a.a.a.a();\n locala.f = \"com.tencent.mm\";\n locala.g = \"com.tencent.mm.plugin.openapi.Intent.ACTION_HANDLE_APP_UNREGISTER\";\n locala.d = (\"weixin://unregisterapp?appid=\" + this.appId);\n com.tencent.mm.sdk.a.a.a.a(this.context, locala);\n }\n}\n"} {"task_id": "Java_2165", "language": "Java", "task_type": "method_body", "source_file": "java/github/cnzx219/QingTingCheat/src/com/tencent/mm/sdk/openapi/WXApiImplV10.java", "mask_start_position": 9371, "mask_end_position": 9555, "canonical_solution": "{\n if (this.detached)\n throw new IllegalStateException(\"isWXAppSupportAPI fail, WXMsgImpl has been detached\");\n return getWXAppSupportAPI() >= 570490883;\n }", "pre_mask_code": "package com.tencent.mm.sdk.openapi;\n\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.PackageManager.NameNotFoundException;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport com.tencent.mm.sdk.a.a.b;\nimport com.tencent.mm.sdk.modelbase.BaseReq;\nimport com.tencent.mm.sdk.modelbase.BaseResp;\nimport com.tencent.mm.sdk.modelbiz.AddCardToWXCardPackage.Resp;\nimport com.tencent.mm.sdk.modelmsg.GetMessageFromWX.Req;\nimport com.tencent.mm.sdk.modelmsg.LaunchFromWX.Req;\nimport com.tencent.mm.sdk.modelmsg.SendAuth.Resp;\nimport com.tencent.mm.sdk.modelmsg.SendMessageToWX.Resp;\nimport com.tencent.mm.sdk.modelmsg.ShowMessageFromWX.Req;\nimport com.tencent.mm.sdk.modelpay.PayResp;\n\nfinal class WXApiImplV10 implements IWXAPI {\n\n private static final String TAG = \"MicroMsg.SDK.WXApiImplV10\";\n\n private static String wxappPayEntryClassname = null;\n\n private String appId;\n\n private boolean checkSignature = false;\n\n private Context context;\n\n private boolean detached = false;\n\n WXApiImplV10(Context paramContext, String paramString, boolean paramBoolean) {\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \", appId = \" + paramString + \", checkSignature = \" + paramBoolean);\n this.context = paramContext;\n this.appId = paramString;\n this.checkSignature = paramBoolean;\n }\n\n private boolean checkSumConsistent(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2) {\n if ((paramArrayOfByte1 == null) || (paramArrayOfByte1.length == 0) || (paramArrayOfByte2 == null) || (paramArrayOfByte2.length == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checkSumConsistent fail, invalid arguments\");\n return false;\n }\n if (paramArrayOfByte1.length != paramArrayOfByte2.length) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checkSumConsistent fail, length is different\");\n return false;\n }\n for (int i = 0; ; i++) {\n if (i >= paramArrayOfByte1.length)\n break label66;\n if (paramArrayOfByte1[i] != paramArrayOfByte2[i])\n break;\n }\n label66: return true;\n }\n\n private boolean sendAddCardToWX(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/addCardToWX\");\n String[] arrayOfString = new String[3];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_add_card_to_wx_card_list\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_basereq_transaction\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendJumpToBizProfileReq(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/jumpToBizProfile\");\n String[] arrayOfString = new String[5];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_jump_to_biz_profile_req_to_user_name\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_jump_to_biz_profile_req_ext_msg\");\n arrayOfString[3] = paramBundle.getInt(\"_wxapi_jump_to_biz_profile_req_scene\");\n arrayOfString[4] = paramBundle.getInt(\"_wxapi_jump_to_biz_profile_req_profile_type\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendJumpToBizWebviewReq(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/jumpToBizProfile\");\n String[] arrayOfString = new String[4];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_jump_to_biz_webview_req_to_user_name\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_jump_to_biz_webview_req_ext_msg\");\n arrayOfString[3] = paramBundle.getInt(\"_wxapi_jump_to_biz_webview_req_scene\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendPayReq(Context paramContext, Bundle paramBundle) {\n if (wxappPayEntryClassname == null) {\n wxappPayEntryClassname = new MMSharedPreferences(paramContext).getString(\"_wxapp_pay_entry_classname_\", null);\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"pay, set wxappPayEntryClassname = \" + wxappPayEntryClassname);\n if (wxappPayEntryClassname == null) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"pay fail, wxappPayEntryClassname is null\");\n return false;\n }\n }\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = paramBundle;\n locala.b = \"com.tencent.mm\";\n locala.c = wxappPayEntryClassname;\n return com.tencent.mm.sdk.a.a.a(paramContext, locala);\n }\n\n public final void detach() {\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"detach\");\n this.detached = true;\n this.context = null;\n }\n\n public final int getWXAppSupportAPI() {\n if (this.detached)\n throw new IllegalStateException(\"getWXAppSupportAPI fail, WXMsgImpl has been detached\");\n if (!isWXAppInstalled()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"open wx app failed, not installed or signature check failed\");\n return 0;\n }\n return new MMSharedPreferences(this.context).getInt(\"_build_info_sdk_int_\", 0);\n }\n\n public final boolean handleIntent(Intent paramIntent, IWXAPIEventHandler paramIWXAPIEventHandler) {\n if (!WXApiImplComm.isIntentFromWx(paramIntent, \"com.tencent.mm.openapi.token\")) {\n com.tencent.mm.sdk.b.a.b(\"MicroMsg.SDK.WXApiImplV10\", \"handleIntent fail, intent not from weixin msg\");\n return false;\n }\n if (this.detached)\n throw new IllegalStateException(\"handleIntent fail, WXMsgImpl has been detached\");\n String str1 = paramIntent.getStringExtra(\"_mmessage_content\");\n int i = paramIntent.getIntExtra(\"_mmessage_sdkVersion\", 0);\n String str2 = paramIntent.getStringExtra(\"_mmessage_appPackage\");\n if ((str2 == null) || (str2.length() == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"invalid argument\");\n return false;\n }\n if (!checkSumConsistent(paramIntent.getByteArrayExtra(\"_mmessage_checksum\"), b.a(str1, i, str2))) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checksum fail\");\n return false;\n }\n int j = paramIntent.getIntExtra(\"_wxapi_command_type\", 0);\n switch(j) {\n case 7:\n case 8:\n default:\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unknown cmd = \" + j);\n return false;\n case 1:\n paramIWXAPIEventHandler.onResp(new SendAuth.Resp(paramIntent.getExtras()));\n return true;\n case 2:\n paramIWXAPIEventHandler.onResp(new SendMessageToWX.Resp(paramIntent.getExtras()));\n return true;\n case 3:\n paramIWXAPIEventHandler.onReq(new GetMessageFromWX.Req(paramIntent.getExtras()));\n return true;\n case 4:\n paramIWXAPIEventHandler.onReq(new ShowMessageFromWX.Req(paramIntent.getExtras()));\n return true;\n case 5:\n paramIWXAPIEventHandler.onResp(new PayResp(paramIntent.getExtras()));\n return true;\n case 6:\n paramIWXAPIEventHandler.onReq(new LaunchFromWX.Req(paramIntent.getExtras()));\n return true;\n case 9:\n }\n paramIWXAPIEventHandler.onResp(new AddCardToWXCardPackage.Resp(paramIntent.getExtras()));\n return true;\n }\n\n public final boolean isWXAppInstalled() {\n if (this.detached)\n throw new IllegalStateException(\"isWXAppInstalled fail, WXMsgImpl has been detached\");\n try {\n PackageInfo localPackageInfo = this.context.getPackageManager().getPackageInfo(\"com.tencent.mm\", 64);\n if (localPackageInfo == null)\n return false;\n boolean bool = WXApiImplComm.validateAppSignature(this.context, localPackageInfo.signatures, this.checkSignature);\n return bool;\n } catch (PackageManager.NameNotFoundException localNameNotFoundException) {\n }\n return false;\n }\n\n public final boolean isWXAppSupportAPI() ", "post_mask_code": "\n\n public final boolean openWXApp() {\n if (this.detached)\n throw new IllegalStateException(\"openWXApp fail, WXMsgImpl has been detached\");\n if (!isWXAppInstalled()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"open wx app failed, not installed or signature check failed\");\n return false;\n }\n try {\n this.context.startActivity(this.context.getPackageManager().getLaunchIntentForPackage(\"com.tencent.mm\"));\n return true;\n } catch (Exception localException) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"startActivity fail, exception = \" + localException.getMessage());\n }\n return false;\n }\n\n public final boolean registerApp(String paramString) {\n if (this.detached)\n throw new IllegalStateException(\"registerApp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"register app failed for wechat app signature check failed\");\n return false;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"registerApp, appId = \" + paramString);\n if (paramString != null)\n this.appId = paramString;\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"register app \" + this.context.getPackageName());\n com.tencent.mm.sdk.a.a.a.a locala = new com.tencent.mm.sdk.a.a.a.a();\n locala.f = \"com.tencent.mm\";\n locala.g = \"com.tencent.mm.plugin.openapi.Intent.ACTION_HANDLE_APP_REGISTER\";\n locala.d = (\"weixin://registerapp?appid=\" + this.appId);\n return com.tencent.mm.sdk.a.a.a.a(this.context, locala);\n }\n\n public final boolean sendReq(BaseReq paramBaseReq) {\n if (this.detached)\n throw new IllegalStateException(\"sendReq fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq failed for wechat app signature check failed\");\n return false;\n }\n if (!paramBaseReq.checkArgs()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq checkArgs fail\");\n return false;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq, req type = \" + paramBaseReq.getType());\n Bundle localBundle = new Bundle();\n paramBaseReq.toBundle(localBundle);\n if (paramBaseReq.getType() == 5)\n return sendPayReq(this.context, localBundle);\n if (paramBaseReq.getType() == 7)\n return sendJumpToBizProfileReq(this.context, localBundle);\n if (paramBaseReq.getType() == 8)\n return sendJumpToBizWebviewReq(this.context, localBundle);\n if (paramBaseReq.getType() == 9)\n return sendAddCardToWX(this.context, localBundle);\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = localBundle;\n locala.d = (\"weixin://sendreq?appid=\" + this.appId);\n locala.b = \"com.tencent.mm\";\n locala.c = \"com.tencent.mm.plugin.base.stub.WXEntryActivity\";\n return com.tencent.mm.sdk.a.a.a(this.context, locala);\n }\n\n public final boolean sendResp(BaseResp paramBaseResp) {\n if (this.detached)\n throw new IllegalStateException(\"sendResp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendResp failed for wechat app signature check failed\");\n return false;\n }\n if (!paramBaseResp.checkArgs()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendResp checkArgs fail\");\n return false;\n }\n Bundle localBundle = new Bundle();\n paramBaseResp.toBundle(localBundle);\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = localBundle;\n locala.d = (\"weixin://sendresp?appid=\" + this.appId);\n locala.b = \"com.tencent.mm\";\n locala.c = \"com.tencent.mm.plugin.base.stub.WXEntryActivity\";\n return com.tencent.mm.sdk.a.a.a(this.context, locala);\n }\n\n public final void unregisterApp() {\n if (this.detached)\n throw new IllegalStateException(\"unregisterApp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unregister app failed for wechat app signature check failed\");\n return;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"unregisterApp, appId = \" + this.appId);\n if ((this.appId == null) || (this.appId.length() == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unregisterApp fail, appId is empty\");\n return;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"unregister app \" + this.context.getPackageName());\n com.tencent.mm.sdk.a.a.a.a locala = new com.tencent.mm.sdk.a.a.a.a();\n locala.f = \"com.tencent.mm\";\n locala.g = \"com.tencent.mm.plugin.openapi.Intent.ACTION_HANDLE_APP_UNREGISTER\";\n locala.d = (\"weixin://unregisterapp?appid=\" + this.appId);\n com.tencent.mm.sdk.a.a.a.a(this.context, locala);\n }\n}\n"} {"task_id": "Java_2166", "language": "Java", "task_type": "single_line", "source_file": "java/github/cnzx219/QingTingCheat/src/com/tencent/mm/sdk/openapi/WXApiImplV10.java", "mask_start_position": 2507, "mask_end_position": 2538, "canonical_solution": "amContext.getContentResolver();", "pre_mask_code": "package com.tencent.mm.sdk.openapi;\n\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.PackageManager.NameNotFoundException;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport com.tencent.mm.sdk.a.a.b;\nimport com.tencent.mm.sdk.modelbase.BaseReq;\nimport com.tencent.mm.sdk.modelbase.BaseResp;\nimport com.tencent.mm.sdk.modelbiz.AddCardToWXCardPackage.Resp;\nimport com.tencent.mm.sdk.modelmsg.GetMessageFromWX.Req;\nimport com.tencent.mm.sdk.modelmsg.LaunchFromWX.Req;\nimport com.tencent.mm.sdk.modelmsg.SendAuth.Resp;\nimport com.tencent.mm.sdk.modelmsg.SendMessageToWX.Resp;\nimport com.tencent.mm.sdk.modelmsg.ShowMessageFromWX.Req;\nimport com.tencent.mm.sdk.modelpay.PayResp;\n\nfinal class WXApiImplV10 implements IWXAPI {\n\n private static final String TAG = \"MicroMsg.SDK.WXApiImplV10\";\n\n private static String wxappPayEntryClassname = null;\n\n private String appId;\n\n private boolean checkSignature = false;\n\n private Context context;\n\n private boolean detached = false;\n\n WXApiImplV10(Context paramContext, String paramString, boolean paramBoolean) {\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \", appId = \" + paramString + \", checkSignature = \" + paramBoolean);\n this.context = paramContext;\n this.appId = paramString;\n this.checkSignature = paramBoolean;\n }\n\n private boolean checkSumConsistent(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2) {\n if ((paramArrayOfByte1 == null) || (paramArrayOfByte1.length == 0) || (paramArrayOfByte2 == null) || (paramArrayOfByte2.length == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checkSumConsistent fail, invalid arguments\");\n return false;\n }\n if (paramArrayOfByte1.length != paramArrayOfByte2.length) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checkSumConsistent fail, length is different\");\n return false;\n }\n for (int i = 0; ; i++) {\n if (i >= paramArrayOfByte1.length)\n break label66;\n if (paramArrayOfByte1[i] != paramArrayOfByte2[i])\n break;\n }\n label66: return true;\n }\n\n private boolean sendAddCardToWX(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = par", "post_mask_code": "\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/addCardToWX\");\n String[] arrayOfString = new String[3];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_add_card_to_wx_card_list\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_basereq_transaction\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendJumpToBizProfileReq(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/jumpToBizProfile\");\n String[] arrayOfString = new String[5];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_jump_to_biz_profile_req_to_user_name\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_jump_to_biz_profile_req_ext_msg\");\n arrayOfString[3] = paramBundle.getInt(\"_wxapi_jump_to_biz_profile_req_scene\");\n arrayOfString[4] = paramBundle.getInt(\"_wxapi_jump_to_biz_profile_req_profile_type\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendJumpToBizWebviewReq(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/jumpToBizProfile\");\n String[] arrayOfString = new String[4];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_jump_to_biz_webview_req_to_user_name\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_jump_to_biz_webview_req_ext_msg\");\n arrayOfString[3] = paramBundle.getInt(\"_wxapi_jump_to_biz_webview_req_scene\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendPayReq(Context paramContext, Bundle paramBundle) {\n if (wxappPayEntryClassname == null) {\n wxappPayEntryClassname = new MMSharedPreferences(paramContext).getString(\"_wxapp_pay_entry_classname_\", null);\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"pay, set wxappPayEntryClassname = \" + wxappPayEntryClassname);\n if (wxappPayEntryClassname == null) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"pay fail, wxappPayEntryClassname is null\");\n return false;\n }\n }\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = paramBundle;\n locala.b = \"com.tencent.mm\";\n locala.c = wxappPayEntryClassname;\n return com.tencent.mm.sdk.a.a.a(paramContext, locala);\n }\n\n public final void detach() {\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"detach\");\n this.detached = true;\n this.context = null;\n }\n\n public final int getWXAppSupportAPI() {\n if (this.detached)\n throw new IllegalStateException(\"getWXAppSupportAPI fail, WXMsgImpl has been detached\");\n if (!isWXAppInstalled()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"open wx app failed, not installed or signature check failed\");\n return 0;\n }\n return new MMSharedPreferences(this.context).getInt(\"_build_info_sdk_int_\", 0);\n }\n\n public final boolean handleIntent(Intent paramIntent, IWXAPIEventHandler paramIWXAPIEventHandler) {\n if (!WXApiImplComm.isIntentFromWx(paramIntent, \"com.tencent.mm.openapi.token\")) {\n com.tencent.mm.sdk.b.a.b(\"MicroMsg.SDK.WXApiImplV10\", \"handleIntent fail, intent not from weixin msg\");\n return false;\n }\n if (this.detached)\n throw new IllegalStateException(\"handleIntent fail, WXMsgImpl has been detached\");\n String str1 = paramIntent.getStringExtra(\"_mmessage_content\");\n int i = paramIntent.getIntExtra(\"_mmessage_sdkVersion\", 0);\n String str2 = paramIntent.getStringExtra(\"_mmessage_appPackage\");\n if ((str2 == null) || (str2.length() == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"invalid argument\");\n return false;\n }\n if (!checkSumConsistent(paramIntent.getByteArrayExtra(\"_mmessage_checksum\"), b.a(str1, i, str2))) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checksum fail\");\n return false;\n }\n int j = paramIntent.getIntExtra(\"_wxapi_command_type\", 0);\n switch(j) {\n case 7:\n case 8:\n default:\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unknown cmd = \" + j);\n return false;\n case 1:\n paramIWXAPIEventHandler.onResp(new SendAuth.Resp(paramIntent.getExtras()));\n return true;\n case 2:\n paramIWXAPIEventHandler.onResp(new SendMessageToWX.Resp(paramIntent.getExtras()));\n return true;\n case 3:\n paramIWXAPIEventHandler.onReq(new GetMessageFromWX.Req(paramIntent.getExtras()));\n return true;\n case 4:\n paramIWXAPIEventHandler.onReq(new ShowMessageFromWX.Req(paramIntent.getExtras()));\n return true;\n case 5:\n paramIWXAPIEventHandler.onResp(new PayResp(paramIntent.getExtras()));\n return true;\n case 6:\n paramIWXAPIEventHandler.onReq(new LaunchFromWX.Req(paramIntent.getExtras()));\n return true;\n case 9:\n }\n paramIWXAPIEventHandler.onResp(new AddCardToWXCardPackage.Resp(paramIntent.getExtras()));\n return true;\n }\n\n public final boolean isWXAppInstalled() {\n if (this.detached)\n throw new IllegalStateException(\"isWXAppInstalled fail, WXMsgImpl has been detached\");\n try {\n PackageInfo localPackageInfo = this.context.getPackageManager().getPackageInfo(\"com.tencent.mm\", 64);\n if (localPackageInfo == null)\n return false;\n boolean bool = WXApiImplComm.validateAppSignature(this.context, localPackageInfo.signatures, this.checkSignature);\n return bool;\n } catch (PackageManager.NameNotFoundException localNameNotFoundException) {\n }\n return false;\n }\n\n public final boolean isWXAppSupportAPI() {\n if (this.detached)\n throw new IllegalStateException(\"isWXAppSupportAPI fail, WXMsgImpl has been detached\");\n return getWXAppSupportAPI() >= 570490883;\n }\n\n public final boolean openWXApp() {\n if (this.detached)\n throw new IllegalStateException(\"openWXApp fail, WXMsgImpl has been detached\");\n if (!isWXAppInstalled()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"open wx app failed, not installed or signature check failed\");\n return false;\n }\n try {\n this.context.startActivity(this.context.getPackageManager().getLaunchIntentForPackage(\"com.tencent.mm\"));\n return true;\n } catch (Exception localException) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"startActivity fail, exception = \" + localException.getMessage());\n }\n return false;\n }\n\n public final boolean registerApp(String paramString) {\n if (this.detached)\n throw new IllegalStateException(\"registerApp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"register app failed for wechat app signature check failed\");\n return false;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"registerApp, appId = \" + paramString);\n if (paramString != null)\n this.appId = paramString;\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"register app \" + this.context.getPackageName());\n com.tencent.mm.sdk.a.a.a.a locala = new com.tencent.mm.sdk.a.a.a.a();\n locala.f = \"com.tencent.mm\";\n locala.g = \"com.tencent.mm.plugin.openapi.Intent.ACTION_HANDLE_APP_REGISTER\";\n locala.d = (\"weixin://registerapp?appid=\" + this.appId);\n return com.tencent.mm.sdk.a.a.a.a(this.context, locala);\n }\n\n public final boolean sendReq(BaseReq paramBaseReq) {\n if (this.detached)\n throw new IllegalStateException(\"sendReq fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq failed for wechat app signature check failed\");\n return false;\n }\n if (!paramBaseReq.checkArgs()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq checkArgs fail\");\n return false;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq, req type = \" + paramBaseReq.getType());\n Bundle localBundle = new Bundle();\n paramBaseReq.toBundle(localBundle);\n if (paramBaseReq.getType() == 5)\n return sendPayReq(this.context, localBundle);\n if (paramBaseReq.getType() == 7)\n return sendJumpToBizProfileReq(this.context, localBundle);\n if (paramBaseReq.getType() == 8)\n return sendJumpToBizWebviewReq(this.context, localBundle);\n if (paramBaseReq.getType() == 9)\n return sendAddCardToWX(this.context, localBundle);\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = localBundle;\n locala.d = (\"weixin://sendreq?appid=\" + this.appId);\n locala.b = \"com.tencent.mm\";\n locala.c = \"com.tencent.mm.plugin.base.stub.WXEntryActivity\";\n return com.tencent.mm.sdk.a.a.a(this.context, locala);\n }\n\n public final boolean sendResp(BaseResp paramBaseResp) {\n if (this.detached)\n throw new IllegalStateException(\"sendResp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendResp failed for wechat app signature check failed\");\n return false;\n }\n if (!paramBaseResp.checkArgs()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendResp checkArgs fail\");\n return false;\n }\n Bundle localBundle = new Bundle();\n paramBaseResp.toBundle(localBundle);\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = localBundle;\n locala.d = (\"weixin://sendresp?appid=\" + this.appId);\n locala.b = \"com.tencent.mm\";\n locala.c = \"com.tencent.mm.plugin.base.stub.WXEntryActivity\";\n return com.tencent.mm.sdk.a.a.a(this.context, locala);\n }\n\n public final void unregisterApp() {\n if (this.detached)\n throw new IllegalStateException(\"unregisterApp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unregister app failed for wechat app signature check failed\");\n return;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"unregisterApp, appId = \" + this.appId);\n if ((this.appId == null) || (this.appId.length() == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unregisterApp fail, appId is empty\");\n return;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"unregister app \" + this.context.getPackageName());\n com.tencent.mm.sdk.a.a.a.a locala = new com.tencent.mm.sdk.a.a.a.a();\n locala.f = \"com.tencent.mm\";\n locala.g = \"com.tencent.mm.plugin.openapi.Intent.ACTION_HANDLE_APP_UNREGISTER\";\n locala.d = (\"weixin://unregisterapp?appid=\" + this.appId);\n com.tencent.mm.sdk.a.a.a.a(this.context, locala);\n }\n}\n"} {"task_id": "Java_2167", "language": "Java", "task_type": "for_statement", "source_file": "java/github/cnzx219/QingTingCheat/src/com/tencent/mm/sdk/openapi/WXApiImplV10.java", "mask_start_position": 2142, "mask_end_position": 2339, "canonical_solution": "for (int i = 0; ; i++) {\n if (i >= paramArrayOfByte1.length)\n break label66;\n if (paramArrayOfByte1[i] != paramArrayOfByte2[i])\n break;\n }", "pre_mask_code": "package com.tencent.mm.sdk.openapi;\n\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.PackageManager.NameNotFoundException;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport com.tencent.mm.sdk.a.a.b;\nimport com.tencent.mm.sdk.modelbase.BaseReq;\nimport com.tencent.mm.sdk.modelbase.BaseResp;\nimport com.tencent.mm.sdk.modelbiz.AddCardToWXCardPackage.Resp;\nimport com.tencent.mm.sdk.modelmsg.GetMessageFromWX.Req;\nimport com.tencent.mm.sdk.modelmsg.LaunchFromWX.Req;\nimport com.tencent.mm.sdk.modelmsg.SendAuth.Resp;\nimport com.tencent.mm.sdk.modelmsg.SendMessageToWX.Resp;\nimport com.tencent.mm.sdk.modelmsg.ShowMessageFromWX.Req;\nimport com.tencent.mm.sdk.modelpay.PayResp;\n\nfinal class WXApiImplV10 implements IWXAPI {\n\n private static final String TAG = \"MicroMsg.SDK.WXApiImplV10\";\n\n private static String wxappPayEntryClassname = null;\n\n private String appId;\n\n private boolean checkSignature = false;\n\n private Context context;\n\n private boolean detached = false;\n\n WXApiImplV10(Context paramContext, String paramString, boolean paramBoolean) {\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \", appId = \" + paramString + \", checkSignature = \" + paramBoolean);\n this.context = paramContext;\n this.appId = paramString;\n this.checkSignature = paramBoolean;\n }\n\n private boolean checkSumConsistent(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2) {\n if ((paramArrayOfByte1 == null) || (paramArrayOfByte1.length == 0) || (paramArrayOfByte2 == null) || (paramArrayOfByte2.length == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checkSumConsistent fail, invalid arguments\");\n return false;\n }\n if (paramArrayOfByte1.length != paramArrayOfByte2.length) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checkSumConsistent fail, length is different\");\n return false;\n }\n ", "post_mask_code": "\n label66: return true;\n }\n\n private boolean sendAddCardToWX(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/addCardToWX\");\n String[] arrayOfString = new String[3];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_add_card_to_wx_card_list\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_basereq_transaction\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendJumpToBizProfileReq(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/jumpToBizProfile\");\n String[] arrayOfString = new String[5];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_jump_to_biz_profile_req_to_user_name\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_jump_to_biz_profile_req_ext_msg\");\n arrayOfString[3] = paramBundle.getInt(\"_wxapi_jump_to_biz_profile_req_scene\");\n arrayOfString[4] = paramBundle.getInt(\"_wxapi_jump_to_biz_profile_req_profile_type\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendJumpToBizWebviewReq(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/jumpToBizProfile\");\n String[] arrayOfString = new String[4];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_jump_to_biz_webview_req_to_user_name\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_jump_to_biz_webview_req_ext_msg\");\n arrayOfString[3] = paramBundle.getInt(\"_wxapi_jump_to_biz_webview_req_scene\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendPayReq(Context paramContext, Bundle paramBundle) {\n if (wxappPayEntryClassname == null) {\n wxappPayEntryClassname = new MMSharedPreferences(paramContext).getString(\"_wxapp_pay_entry_classname_\", null);\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"pay, set wxappPayEntryClassname = \" + wxappPayEntryClassname);\n if (wxappPayEntryClassname == null) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"pay fail, wxappPayEntryClassname is null\");\n return false;\n }\n }\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = paramBundle;\n locala.b = \"com.tencent.mm\";\n locala.c = wxappPayEntryClassname;\n return com.tencent.mm.sdk.a.a.a(paramContext, locala);\n }\n\n public final void detach() {\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"detach\");\n this.detached = true;\n this.context = null;\n }\n\n public final int getWXAppSupportAPI() {\n if (this.detached)\n throw new IllegalStateException(\"getWXAppSupportAPI fail, WXMsgImpl has been detached\");\n if (!isWXAppInstalled()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"open wx app failed, not installed or signature check failed\");\n return 0;\n }\n return new MMSharedPreferences(this.context).getInt(\"_build_info_sdk_int_\", 0);\n }\n\n public final boolean handleIntent(Intent paramIntent, IWXAPIEventHandler paramIWXAPIEventHandler) {\n if (!WXApiImplComm.isIntentFromWx(paramIntent, \"com.tencent.mm.openapi.token\")) {\n com.tencent.mm.sdk.b.a.b(\"MicroMsg.SDK.WXApiImplV10\", \"handleIntent fail, intent not from weixin msg\");\n return false;\n }\n if (this.detached)\n throw new IllegalStateException(\"handleIntent fail, WXMsgImpl has been detached\");\n String str1 = paramIntent.getStringExtra(\"_mmessage_content\");\n int i = paramIntent.getIntExtra(\"_mmessage_sdkVersion\", 0);\n String str2 = paramIntent.getStringExtra(\"_mmessage_appPackage\");\n if ((str2 == null) || (str2.length() == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"invalid argument\");\n return false;\n }\n if (!checkSumConsistent(paramIntent.getByteArrayExtra(\"_mmessage_checksum\"), b.a(str1, i, str2))) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checksum fail\");\n return false;\n }\n int j = paramIntent.getIntExtra(\"_wxapi_command_type\", 0);\n switch(j) {\n case 7:\n case 8:\n default:\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unknown cmd = \" + j);\n return false;\n case 1:\n paramIWXAPIEventHandler.onResp(new SendAuth.Resp(paramIntent.getExtras()));\n return true;\n case 2:\n paramIWXAPIEventHandler.onResp(new SendMessageToWX.Resp(paramIntent.getExtras()));\n return true;\n case 3:\n paramIWXAPIEventHandler.onReq(new GetMessageFromWX.Req(paramIntent.getExtras()));\n return true;\n case 4:\n paramIWXAPIEventHandler.onReq(new ShowMessageFromWX.Req(paramIntent.getExtras()));\n return true;\n case 5:\n paramIWXAPIEventHandler.onResp(new PayResp(paramIntent.getExtras()));\n return true;\n case 6:\n paramIWXAPIEventHandler.onReq(new LaunchFromWX.Req(paramIntent.getExtras()));\n return true;\n case 9:\n }\n paramIWXAPIEventHandler.onResp(new AddCardToWXCardPackage.Resp(paramIntent.getExtras()));\n return true;\n }\n\n public final boolean isWXAppInstalled() {\n if (this.detached)\n throw new IllegalStateException(\"isWXAppInstalled fail, WXMsgImpl has been detached\");\n try {\n PackageInfo localPackageInfo = this.context.getPackageManager().getPackageInfo(\"com.tencent.mm\", 64);\n if (localPackageInfo == null)\n return false;\n boolean bool = WXApiImplComm.validateAppSignature(this.context, localPackageInfo.signatures, this.checkSignature);\n return bool;\n } catch (PackageManager.NameNotFoundException localNameNotFoundException) {\n }\n return false;\n }\n\n public final boolean isWXAppSupportAPI() {\n if (this.detached)\n throw new IllegalStateException(\"isWXAppSupportAPI fail, WXMsgImpl has been detached\");\n return getWXAppSupportAPI() >= 570490883;\n }\n\n public final boolean openWXApp() {\n if (this.detached)\n throw new IllegalStateException(\"openWXApp fail, WXMsgImpl has been detached\");\n if (!isWXAppInstalled()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"open wx app failed, not installed or signature check failed\");\n return false;\n }\n try {\n this.context.startActivity(this.context.getPackageManager().getLaunchIntentForPackage(\"com.tencent.mm\"));\n return true;\n } catch (Exception localException) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"startActivity fail, exception = \" + localException.getMessage());\n }\n return false;\n }\n\n public final boolean registerApp(String paramString) {\n if (this.detached)\n throw new IllegalStateException(\"registerApp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"register app failed for wechat app signature check failed\");\n return false;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"registerApp, appId = \" + paramString);\n if (paramString != null)\n this.appId = paramString;\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"register app \" + this.context.getPackageName());\n com.tencent.mm.sdk.a.a.a.a locala = new com.tencent.mm.sdk.a.a.a.a();\n locala.f = \"com.tencent.mm\";\n locala.g = \"com.tencent.mm.plugin.openapi.Intent.ACTION_HANDLE_APP_REGISTER\";\n locala.d = (\"weixin://registerapp?appid=\" + this.appId);\n return com.tencent.mm.sdk.a.a.a.a(this.context, locala);\n }\n\n public final boolean sendReq(BaseReq paramBaseReq) {\n if (this.detached)\n throw new IllegalStateException(\"sendReq fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq failed for wechat app signature check failed\");\n return false;\n }\n if (!paramBaseReq.checkArgs()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq checkArgs fail\");\n return false;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq, req type = \" + paramBaseReq.getType());\n Bundle localBundle = new Bundle();\n paramBaseReq.toBundle(localBundle);\n if (paramBaseReq.getType() == 5)\n return sendPayReq(this.context, localBundle);\n if (paramBaseReq.getType() == 7)\n return sendJumpToBizProfileReq(this.context, localBundle);\n if (paramBaseReq.getType() == 8)\n return sendJumpToBizWebviewReq(this.context, localBundle);\n if (paramBaseReq.getType() == 9)\n return sendAddCardToWX(this.context, localBundle);\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = localBundle;\n locala.d = (\"weixin://sendreq?appid=\" + this.appId);\n locala.b = \"com.tencent.mm\";\n locala.c = \"com.tencent.mm.plugin.base.stub.WXEntryActivity\";\n return com.tencent.mm.sdk.a.a.a(this.context, locala);\n }\n\n public final boolean sendResp(BaseResp paramBaseResp) {\n if (this.detached)\n throw new IllegalStateException(\"sendResp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendResp failed for wechat app signature check failed\");\n return false;\n }\n if (!paramBaseResp.checkArgs()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendResp checkArgs fail\");\n return false;\n }\n Bundle localBundle = new Bundle();\n paramBaseResp.toBundle(localBundle);\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = localBundle;\n locala.d = (\"weixin://sendresp?appid=\" + this.appId);\n locala.b = \"com.tencent.mm\";\n locala.c = \"com.tencent.mm.plugin.base.stub.WXEntryActivity\";\n return com.tencent.mm.sdk.a.a.a(this.context, locala);\n }\n\n public final void unregisterApp() {\n if (this.detached)\n throw new IllegalStateException(\"unregisterApp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unregister app failed for wechat app signature check failed\");\n return;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"unregisterApp, appId = \" + this.appId);\n if ((this.appId == null) || (this.appId.length() == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unregisterApp fail, appId is empty\");\n return;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"unregister app \" + this.context.getPackageName());\n com.tencent.mm.sdk.a.a.a.a locala = new com.tencent.mm.sdk.a.a.a.a();\n locala.f = \"com.tencent.mm\";\n locala.g = \"com.tencent.mm.plugin.openapi.Intent.ACTION_HANDLE_APP_UNREGISTER\";\n locala.d = (\"weixin://unregisterapp?appid=\" + this.appId);\n com.tencent.mm.sdk.a.a.a.a(this.context, locala);\n }\n}\n"} {"task_id": "Java_2168", "language": "Java", "task_type": "try_statement", "source_file": "java/github/cnzx219/QingTingCheat/src/com/tencent/mm/sdk/openapi/WXApiImplV10.java", "mask_start_position": 8859, "mask_end_position": 9296, "canonical_solution": "try {\n PackageInfo localPackageInfo = this.context.getPackageManager().getPackageInfo(\"com.tencent.mm\", 64);\n if (localPackageInfo == null)\n return false;\n boolean bool = WXApiImplComm.validateAppSignature(this.context, localPackageInfo.signatures, this.checkSignature);\n return bool;\n } catch (PackageManager.NameNotFoundException localNameNotFoundException) {\n }", "pre_mask_code": "package com.tencent.mm.sdk.openapi;\n\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.PackageManager.NameNotFoundException;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport com.tencent.mm.sdk.a.a.b;\nimport com.tencent.mm.sdk.modelbase.BaseReq;\nimport com.tencent.mm.sdk.modelbase.BaseResp;\nimport com.tencent.mm.sdk.modelbiz.AddCardToWXCardPackage.Resp;\nimport com.tencent.mm.sdk.modelmsg.GetMessageFromWX.Req;\nimport com.tencent.mm.sdk.modelmsg.LaunchFromWX.Req;\nimport com.tencent.mm.sdk.modelmsg.SendAuth.Resp;\nimport com.tencent.mm.sdk.modelmsg.SendMessageToWX.Resp;\nimport com.tencent.mm.sdk.modelmsg.ShowMessageFromWX.Req;\nimport com.tencent.mm.sdk.modelpay.PayResp;\n\nfinal class WXApiImplV10 implements IWXAPI {\n\n private static final String TAG = \"MicroMsg.SDK.WXApiImplV10\";\n\n private static String wxappPayEntryClassname = null;\n\n private String appId;\n\n private boolean checkSignature = false;\n\n private Context context;\n\n private boolean detached = false;\n\n WXApiImplV10(Context paramContext, String paramString, boolean paramBoolean) {\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \", appId = \" + paramString + \", checkSignature = \" + paramBoolean);\n this.context = paramContext;\n this.appId = paramString;\n this.checkSignature = paramBoolean;\n }\n\n private boolean checkSumConsistent(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2) {\n if ((paramArrayOfByte1 == null) || (paramArrayOfByte1.length == 0) || (paramArrayOfByte2 == null) || (paramArrayOfByte2.length == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checkSumConsistent fail, invalid arguments\");\n return false;\n }\n if (paramArrayOfByte1.length != paramArrayOfByte2.length) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checkSumConsistent fail, length is different\");\n return false;\n }\n for (int i = 0; ; i++) {\n if (i >= paramArrayOfByte1.length)\n break label66;\n if (paramArrayOfByte1[i] != paramArrayOfByte2[i])\n break;\n }\n label66: return true;\n }\n\n private boolean sendAddCardToWX(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/addCardToWX\");\n String[] arrayOfString = new String[3];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_add_card_to_wx_card_list\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_basereq_transaction\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendJumpToBizProfileReq(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/jumpToBizProfile\");\n String[] arrayOfString = new String[5];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_jump_to_biz_profile_req_to_user_name\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_jump_to_biz_profile_req_ext_msg\");\n arrayOfString[3] = paramBundle.getInt(\"_wxapi_jump_to_biz_profile_req_scene\");\n arrayOfString[4] = paramBundle.getInt(\"_wxapi_jump_to_biz_profile_req_profile_type\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendJumpToBizWebviewReq(Context paramContext, Bundle paramBundle) {\n ContentResolver localContentResolver = paramContext.getContentResolver();\n Uri localUri = Uri.parse(\"content://com.tencent.mm.sdk.comm.provider/jumpToBizProfile\");\n String[] arrayOfString = new String[4];\n arrayOfString[0] = this.appId;\n arrayOfString[1] = paramBundle.getString(\"_wxapi_jump_to_biz_webview_req_to_user_name\");\n arrayOfString[2] = paramBundle.getString(\"_wxapi_jump_to_biz_webview_req_ext_msg\");\n arrayOfString[3] = paramBundle.getInt(\"_wxapi_jump_to_biz_webview_req_scene\");\n Cursor localCursor = localContentResolver.query(localUri, null, null, arrayOfString, null);\n if (localCursor != null)\n localCursor.close();\n return true;\n }\n\n private boolean sendPayReq(Context paramContext, Bundle paramBundle) {\n if (wxappPayEntryClassname == null) {\n wxappPayEntryClassname = new MMSharedPreferences(paramContext).getString(\"_wxapp_pay_entry_classname_\", null);\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"pay, set wxappPayEntryClassname = \" + wxappPayEntryClassname);\n if (wxappPayEntryClassname == null) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"pay fail, wxappPayEntryClassname is null\");\n return false;\n }\n }\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = paramBundle;\n locala.b = \"com.tencent.mm\";\n locala.c = wxappPayEntryClassname;\n return com.tencent.mm.sdk.a.a.a(paramContext, locala);\n }\n\n public final void detach() {\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"detach\");\n this.detached = true;\n this.context = null;\n }\n\n public final int getWXAppSupportAPI() {\n if (this.detached)\n throw new IllegalStateException(\"getWXAppSupportAPI fail, WXMsgImpl has been detached\");\n if (!isWXAppInstalled()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"open wx app failed, not installed or signature check failed\");\n return 0;\n }\n return new MMSharedPreferences(this.context).getInt(\"_build_info_sdk_int_\", 0);\n }\n\n public final boolean handleIntent(Intent paramIntent, IWXAPIEventHandler paramIWXAPIEventHandler) {\n if (!WXApiImplComm.isIntentFromWx(paramIntent, \"com.tencent.mm.openapi.token\")) {\n com.tencent.mm.sdk.b.a.b(\"MicroMsg.SDK.WXApiImplV10\", \"handleIntent fail, intent not from weixin msg\");\n return false;\n }\n if (this.detached)\n throw new IllegalStateException(\"handleIntent fail, WXMsgImpl has been detached\");\n String str1 = paramIntent.getStringExtra(\"_mmessage_content\");\n int i = paramIntent.getIntExtra(\"_mmessage_sdkVersion\", 0);\n String str2 = paramIntent.getStringExtra(\"_mmessage_appPackage\");\n if ((str2 == null) || (str2.length() == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"invalid argument\");\n return false;\n }\n if (!checkSumConsistent(paramIntent.getByteArrayExtra(\"_mmessage_checksum\"), b.a(str1, i, str2))) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"checksum fail\");\n return false;\n }\n int j = paramIntent.getIntExtra(\"_wxapi_command_type\", 0);\n switch(j) {\n case 7:\n case 8:\n default:\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unknown cmd = \" + j);\n return false;\n case 1:\n paramIWXAPIEventHandler.onResp(new SendAuth.Resp(paramIntent.getExtras()));\n return true;\n case 2:\n paramIWXAPIEventHandler.onResp(new SendMessageToWX.Resp(paramIntent.getExtras()));\n return true;\n case 3:\n paramIWXAPIEventHandler.onReq(new GetMessageFromWX.Req(paramIntent.getExtras()));\n return true;\n case 4:\n paramIWXAPIEventHandler.onReq(new ShowMessageFromWX.Req(paramIntent.getExtras()));\n return true;\n case 5:\n paramIWXAPIEventHandler.onResp(new PayResp(paramIntent.getExtras()));\n return true;\n case 6:\n paramIWXAPIEventHandler.onReq(new LaunchFromWX.Req(paramIntent.getExtras()));\n return true;\n case 9:\n }\n paramIWXAPIEventHandler.onResp(new AddCardToWXCardPackage.Resp(paramIntent.getExtras()));\n return true;\n }\n\n public final boolean isWXAppInstalled() {\n if (this.detached)\n throw new IllegalStateException(\"isWXAppInstalled fail, WXMsgImpl has been detached\");\n ", "post_mask_code": "\n return false;\n }\n\n public final boolean isWXAppSupportAPI() {\n if (this.detached)\n throw new IllegalStateException(\"isWXAppSupportAPI fail, WXMsgImpl has been detached\");\n return getWXAppSupportAPI() >= 570490883;\n }\n\n public final boolean openWXApp() {\n if (this.detached)\n throw new IllegalStateException(\"openWXApp fail, WXMsgImpl has been detached\");\n if (!isWXAppInstalled()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"open wx app failed, not installed or signature check failed\");\n return false;\n }\n try {\n this.context.startActivity(this.context.getPackageManager().getLaunchIntentForPackage(\"com.tencent.mm\"));\n return true;\n } catch (Exception localException) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"startActivity fail, exception = \" + localException.getMessage());\n }\n return false;\n }\n\n public final boolean registerApp(String paramString) {\n if (this.detached)\n throw new IllegalStateException(\"registerApp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"register app failed for wechat app signature check failed\");\n return false;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"registerApp, appId = \" + paramString);\n if (paramString != null)\n this.appId = paramString;\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"register app \" + this.context.getPackageName());\n com.tencent.mm.sdk.a.a.a.a locala = new com.tencent.mm.sdk.a.a.a.a();\n locala.f = \"com.tencent.mm\";\n locala.g = \"com.tencent.mm.plugin.openapi.Intent.ACTION_HANDLE_APP_REGISTER\";\n locala.d = (\"weixin://registerapp?appid=\" + this.appId);\n return com.tencent.mm.sdk.a.a.a.a(this.context, locala);\n }\n\n public final boolean sendReq(BaseReq paramBaseReq) {\n if (this.detached)\n throw new IllegalStateException(\"sendReq fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq failed for wechat app signature check failed\");\n return false;\n }\n if (!paramBaseReq.checkArgs()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq checkArgs fail\");\n return false;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"sendReq, req type = \" + paramBaseReq.getType());\n Bundle localBundle = new Bundle();\n paramBaseReq.toBundle(localBundle);\n if (paramBaseReq.getType() == 5)\n return sendPayReq(this.context, localBundle);\n if (paramBaseReq.getType() == 7)\n return sendJumpToBizProfileReq(this.context, localBundle);\n if (paramBaseReq.getType() == 8)\n return sendJumpToBizWebviewReq(this.context, localBundle);\n if (paramBaseReq.getType() == 9)\n return sendAddCardToWX(this.context, localBundle);\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = localBundle;\n locala.d = (\"weixin://sendreq?appid=\" + this.appId);\n locala.b = \"com.tencent.mm\";\n locala.c = \"com.tencent.mm.plugin.base.stub.WXEntryActivity\";\n return com.tencent.mm.sdk.a.a.a(this.context, locala);\n }\n\n public final boolean sendResp(BaseResp paramBaseResp) {\n if (this.detached)\n throw new IllegalStateException(\"sendResp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendResp failed for wechat app signature check failed\");\n return false;\n }\n if (!paramBaseResp.checkArgs()) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"sendResp checkArgs fail\");\n return false;\n }\n Bundle localBundle = new Bundle();\n paramBaseResp.toBundle(localBundle);\n com.tencent.mm.sdk.a.a.a locala = new com.tencent.mm.sdk.a.a.a();\n locala.e = localBundle;\n locala.d = (\"weixin://sendresp?appid=\" + this.appId);\n locala.b = \"com.tencent.mm\";\n locala.c = \"com.tencent.mm.plugin.base.stub.WXEntryActivity\";\n return com.tencent.mm.sdk.a.a.a(this.context, locala);\n }\n\n public final void unregisterApp() {\n if (this.detached)\n throw new IllegalStateException(\"unregisterApp fail, WXMsgImpl has been detached\");\n if (!WXApiImplComm.validateAppSignatureForPackage(this.context, \"com.tencent.mm\", this.checkSignature)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unregister app failed for wechat app signature check failed\");\n return;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"unregisterApp, appId = \" + this.appId);\n if ((this.appId == null) || (this.appId.length() == 0)) {\n com.tencent.mm.sdk.b.a.a(\"MicroMsg.SDK.WXApiImplV10\", \"unregisterApp fail, appId is empty\");\n return;\n }\n com.tencent.mm.sdk.b.a.c(\"MicroMsg.SDK.WXApiImplV10\", \"unregister app \" + this.context.getPackageName());\n com.tencent.mm.sdk.a.a.a.a locala = new com.tencent.mm.sdk.a.a.a.a();\n locala.f = \"com.tencent.mm\";\n locala.g = \"com.tencent.mm.plugin.openapi.Intent.ACTION_HANDLE_APP_UNREGISTER\";\n locala.d = (\"weixin://unregisterapp?appid=\" + this.appId);\n com.tencent.mm.sdk.a.a.a.a(this.context, locala);\n }\n}\n"} {"task_id": "Java_2169", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse-ee4j/eclipselink/jpa/org.eclipse.persistence.jpa.jpql/src/main/java/org/eclipse/persistence/jpa/jpql/tools/model/ListChangeEvent.java", "mask_start_position": 1735, "mask_end_position": 1809, "canonical_solution": "@Override\n @SuppressWarnings(\"unchecked\")\n public List getList() ", "pre_mask_code": "// Oracle - initial API and implementation\npackage org.eclipse.persistence.jpa.jpql.tools.model;\n\nimport java.util.List;\nimport org.eclipse.persistence.jpa.jpql.tools.model.query.ListHolderStateObject;\nimport org.eclipse.persistence.jpa.jpql.tools.model.query.StateObject;\nimport org.eclipse.persistence.jpa.jpql.utility.iterable.ListIterable;\nimport org.eclipse.persistence.jpa.jpql.utility.iterable.SnapshotCloneListIterable;\n\n/**\n * The default implementation of {@link IListChangeListener} where the generics is the type of the\n * items.\n *\n * @version 2.4\n * @since 2.4\n * @author Pascal Filion\n */\npublic class ListChangeEvent implements IListChangeEvent {\n\n private int endIndex;\n\n private EventType eventType;\n\n private List items;\n\n private List list;\n\n private String listName;\n\n /**\n * The source where the modification occurred and that fired the event.\n */\n private StateObject source;\n\n private int startIndex;\n\n /**\n * Creates a new ListChangeEvent.\n *\n * @param source The source where the modification occurred and that fired the event\n */\n public ListChangeEvent(StateObject source, List list, EventType eventType, String listName, List items, int startIndex, int endIndex) {\n super();\n this.list = list;\n this.items = items;\n this.source = source;\n this.endIndex = endIndex;\n this.listName = listName;\n this.eventType = eventType;\n this.startIndex = startIndex;\n }\n\n @Override\n public int getEndIndex() {\n return endIndex;\n }\n\n @Override\n public EventType getEventType() {\n return eventType;\n }\n\n ", "post_mask_code": "{\n return (List) list;\n }\n\n @Override\n public String getListName() {\n return listName;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public > S getSource() {\n return (S) source;\n }\n\n @Override\n public int getStartIndex() {\n return startIndex;\n }\n\n @Override\n public ListIterable items() {\n return new SnapshotCloneListIterable<>(items);\n }\n\n @Override\n public int itemsSize() {\n return items.size();\n }\n}\n"} {"task_id": "Java_2170", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse-ee4j/eclipselink/jpa/org.eclipse.persistence.jpa.jpql/src/main/java/org/eclipse/persistence/jpa/jpql/tools/model/ListChangeEvent.java", "mask_start_position": 1612, "mask_end_position": 1644, "canonical_solution": "{\n return endIndex;\n }", "pre_mask_code": "// Oracle - initial API and implementation\npackage org.eclipse.persistence.jpa.jpql.tools.model;\n\nimport java.util.List;\nimport org.eclipse.persistence.jpa.jpql.tools.model.query.ListHolderStateObject;\nimport org.eclipse.persistence.jpa.jpql.tools.model.query.StateObject;\nimport org.eclipse.persistence.jpa.jpql.utility.iterable.ListIterable;\nimport org.eclipse.persistence.jpa.jpql.utility.iterable.SnapshotCloneListIterable;\n\n/**\n * The default implementation of {@link IListChangeListener} where the generics is the type of the\n * items.\n *\n * @version 2.4\n * @since 2.4\n * @author Pascal Filion\n */\npublic class ListChangeEvent implements IListChangeEvent {\n\n private int endIndex;\n\n private EventType eventType;\n\n private List items;\n\n private List list;\n\n private String listName;\n\n /**\n * The source where the modification occurred and that fired the event.\n */\n private StateObject source;\n\n private int startIndex;\n\n /**\n * Creates a new ListChangeEvent.\n *\n * @param source The source where the modification occurred and that fired the event\n */\n public ListChangeEvent(StateObject source, List list, EventType eventType, String listName, List items, int startIndex, int endIndex) {\n super();\n this.list = list;\n this.items = items;\n this.source = source;\n this.endIndex = endIndex;\n this.listName = listName;\n this.eventType = eventType;\n this.startIndex = startIndex;\n }\n\n @Override\n public int getEndIndex() ", "post_mask_code": "\n\n @Override\n public EventType getEventType() {\n return eventType;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public List getList() {\n return (List) list;\n }\n\n @Override\n public String getListName() {\n return listName;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public > S getSource() {\n return (S) source;\n }\n\n @Override\n public int getStartIndex() {\n return startIndex;\n }\n\n @Override\n public ListIterable items() {\n return new SnapshotCloneListIterable<>(items);\n }\n\n @Override\n public int itemsSize() {\n return items.size();\n }\n}\n"} {"task_id": "Java_2171", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse-ee4j/eclipselink/jpa/org.eclipse.persistence.jpa.jpql/src/main/java/org/eclipse/persistence/jpa/jpql/tools/model/ListChangeEvent.java", "mask_start_position": 1915, "mask_end_position": 1921, "canonical_solution": "tName;", "pre_mask_code": "// Oracle - initial API and implementation\npackage org.eclipse.persistence.jpa.jpql.tools.model;\n\nimport java.util.List;\nimport org.eclipse.persistence.jpa.jpql.tools.model.query.ListHolderStateObject;\nimport org.eclipse.persistence.jpa.jpql.tools.model.query.StateObject;\nimport org.eclipse.persistence.jpa.jpql.utility.iterable.ListIterable;\nimport org.eclipse.persistence.jpa.jpql.utility.iterable.SnapshotCloneListIterable;\n\n/**\n * The default implementation of {@link IListChangeListener} where the generics is the type of the\n * items.\n *\n * @version 2.4\n * @since 2.4\n * @author Pascal Filion\n */\npublic class ListChangeEvent implements IListChangeEvent {\n\n private int endIndex;\n\n private EventType eventType;\n\n private List items;\n\n private List list;\n\n private String listName;\n\n /**\n * The source where the modification occurred and that fired the event.\n */\n private StateObject source;\n\n private int startIndex;\n\n /**\n * Creates a new ListChangeEvent.\n *\n * @param source The source where the modification occurred and that fired the event\n */\n public ListChangeEvent(StateObject source, List list, EventType eventType, String listName, List items, int startIndex, int endIndex) {\n super();\n this.list = list;\n this.items = items;\n this.source = source;\n this.endIndex = endIndex;\n this.listName = listName;\n this.eventType = eventType;\n this.startIndex = startIndex;\n }\n\n @Override\n public int getEndIndex() {\n return endIndex;\n }\n\n @Override\n public EventType getEventType() {\n return eventType;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public List getList() {\n return (List) list;\n }\n\n @Override\n public String getListName() {\n return lis", "post_mask_code": "\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public > S getSource() {\n return (S) source;\n }\n\n @Override\n public int getStartIndex() {\n return startIndex;\n }\n\n @Override\n public ListIterable items() {\n return new SnapshotCloneListIterable<>(items);\n }\n\n @Override\n public int itemsSize() {\n return items.size();\n }\n}\n"} {"task_id": "Java_2172", "language": "Java", "task_type": "method_signature", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/datetime/timezone/SpannableUtil.java", "mask_start_position": 451, "mask_end_position": 545, "canonical_solution": "public static Spannable getResourcesText(Resources res, @StringRes int resId, Object... args) ", "pre_mask_code": "package com.android.settings.datetime.timezone;\n\nimport android.annotation.StringRes;\nimport android.content.res.Resources;\nimport android.text.Spannable;\nimport android.text.SpannableStringBuilder;\nimport java.util.Formatter;\nimport java.util.Locale;\n\npublic class SpannableUtil {\n\n /**\n * {@class Resources} has no method to format string resource with {@class Spannable} a\n * rguments. It's a helper method for this purpose.\n */\n ", "post_mask_code": "{\n final Locale locale = res.getConfiguration().getLocales().get(0);\n final SpannableStringBuilder builder = new SpannableStringBuilder();\n new Formatter(builder, locale).format(res.getString(resId), args);\n return builder;\n }\n}\n"} {"task_id": "Java_2173", "language": "Java", "task_type": "method_body", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/datetime/timezone/SpannableUtil.java", "mask_start_position": 545, "mask_end_position": 802, "canonical_solution": "{\n final Locale locale = res.getConfiguration().getLocales().get(0);\n final SpannableStringBuilder builder = new SpannableStringBuilder();\n new Formatter(builder, locale).format(res.getString(resId), args);\n return builder;\n }", "pre_mask_code": "package com.android.settings.datetime.timezone;\n\nimport android.annotation.StringRes;\nimport android.content.res.Resources;\nimport android.text.Spannable;\nimport android.text.SpannableStringBuilder;\nimport java.util.Formatter;\nimport java.util.Locale;\n\npublic class SpannableUtil {\n\n /**\n * {@class Resources} has no method to format string resource with {@class Spannable} a\n * rguments. It's a helper method for this purpose.\n */\n public static Spannable getResourcesText(Resources res, @StringRes int resId, Object... args) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2174", "language": "Java", "task_type": "single_line", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/datetime/timezone/SpannableUtil.java", "mask_start_position": 790, "mask_end_position": 796, "canonical_solution": "ilder;", "pre_mask_code": "package com.android.settings.datetime.timezone;\n\nimport android.annotation.StringRes;\nimport android.content.res.Resources;\nimport android.text.Spannable;\nimport android.text.SpannableStringBuilder;\nimport java.util.Formatter;\nimport java.util.Locale;\n\npublic class SpannableUtil {\n\n /**\n * {@class Resources} has no method to format string resource with {@class Spannable} a\n * rguments. It's a helper method for this purpose.\n */\n public static Spannable getResourcesText(Resources res, @StringRes int resId, Object... args) {\n final Locale locale = res.getConfiguration().getLocales().get(0);\n final SpannableStringBuilder builder = new SpannableStringBuilder();\n new Formatter(builder, locale).format(res.getString(resId), args);\n return bu", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2175", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/datetime/timezone/SpannableUtil.java", "mask_start_position": 451, "mask_end_position": 802, "canonical_solution": "public static Spannable getResourcesText(Resources res, @StringRes int resId, Object... args) {\n final Locale locale = res.getConfiguration().getLocales().get(0);\n final SpannableStringBuilder builder = new SpannableStringBuilder();\n new Formatter(builder, locale).format(res.getString(resId), args);\n return builder;\n }", "pre_mask_code": "package com.android.settings.datetime.timezone;\n\nimport android.annotation.StringRes;\nimport android.content.res.Resources;\nimport android.text.Spannable;\nimport android.text.SpannableStringBuilder;\nimport java.util.Formatter;\nimport java.util.Locale;\n\npublic class SpannableUtil {\n\n /**\n * {@class Resources} has no method to format string resource with {@class Spannable} a\n * rguments. It's a helper method for this purpose.\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2176", "language": "Java", "task_type": "method_signature", "source_file": "java/github/facebook/buck/src/com/facebook/buck/jvm/java/ZipEntryJavaFileObject.java", "mask_start_position": 2187, "mask_end_position": 2240, "canonical_solution": "@Override\n public void close() throws IOException ", "pre_mask_code": "package com.facebook.buck.jvm.java;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.CharStreams;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\nimport javax.annotation.Nullable;\nimport javax.annotation.concurrent.GuardedBy;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\n\nclass ZipEntryJavaFileObject extends SimpleJavaFileObject implements Closeable {\n\n private final ZipFile zipFile;\n\n private final ZipEntry zipEntry;\n\n @GuardedBy(\"this\")\n @Nullable\n private String contents;\n\n public ZipEntryJavaFileObject(ZipFile zipFile, ZipEntry zipEntry) {\n super(createURIFromEntry(zipEntry), JavaFileObject.Kind.SOURCE);\n this.zipFile = zipFile;\n this.zipEntry = zipEntry;\n }\n\n /**\n * Creates a canonical URI that represents the {@link ZipEntry}. This URI starts with {@code\n * \"string:///\"} because {@link JavaCompiler} does not seem to tolerate URIs that start with\n * {@code \"jar:///\"}, even though that would be more appropriate.\n */\n private static URI createURIFromEntry(ZipEntry entry) {\n try {\n return new URI(\"string:///\" + entry.getName());\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Returns the contents of the {@link ZipEntry} as a string. Ensures that the entry is read at\n * most once.\n */\n private synchronized String getContentsAsString() {\n if (contents != null) {\n return contents;\n }\n try (InputStream inputStream = zipFile.getInputStream(zipEntry);\n InputStreamReader isr = new InputStreamReader(inputStream, Charsets.UTF_8)) {\n contents = CharStreams.toString(isr);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return contents;\n }\n\n /**\n * Closes the {@link ZipFile} this entry was loaded from. Use with care.\n */\n ", "post_mask_code": "{\n zipFile.close();\n }\n\n @Override\n public CharSequence getCharContent(boolean ignoreEncodingErrors) {\n return getContentsAsString();\n }\n}\n"} {"task_id": "Java_2177", "language": "Java", "task_type": "method_body", "source_file": "java/github/facebook/buck/src/com/facebook/buck/jvm/java/ZipEntryJavaFileObject.java", "mask_start_position": 1321, "mask_end_position": 1496, "canonical_solution": "{\n try {\n return new URI(\"string:///\" + entry.getName());\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n }", "pre_mask_code": "package com.facebook.buck.jvm.java;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.CharStreams;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\nimport javax.annotation.Nullable;\nimport javax.annotation.concurrent.GuardedBy;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\n\nclass ZipEntryJavaFileObject extends SimpleJavaFileObject implements Closeable {\n\n private final ZipFile zipFile;\n\n private final ZipEntry zipEntry;\n\n @GuardedBy(\"this\")\n @Nullable\n private String contents;\n\n public ZipEntryJavaFileObject(ZipFile zipFile, ZipEntry zipEntry) {\n super(createURIFromEntry(zipEntry), JavaFileObject.Kind.SOURCE);\n this.zipFile = zipFile;\n this.zipEntry = zipEntry;\n }\n\n /**\n * Creates a canonical URI that represents the {@link ZipEntry}. This URI starts with {@code\n * \"string:///\"} because {@link JavaCompiler} does not seem to tolerate URIs that start with\n * {@code \"jar:///\"}, even though that would be more appropriate.\n */\n private static URI createURIFromEntry(ZipEntry entry) ", "post_mask_code": "\n\n /**\n * Returns the contents of the {@link ZipEntry} as a string. Ensures that the entry is read at\n * most once.\n */\n private synchronized String getContentsAsString() {\n if (contents != null) {\n return contents;\n }\n try (InputStream inputStream = zipFile.getInputStream(zipEntry);\n InputStreamReader isr = new InputStreamReader(inputStream, Charsets.UTF_8)) {\n contents = CharStreams.toString(isr);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return contents;\n }\n\n /**\n * Closes the {@link ZipFile} this entry was loaded from. Use with care.\n */\n @Override\n public void close() throws IOException {\n zipFile.close();\n }\n\n @Override\n public CharSequence getCharContent(boolean ignoreEncodingErrors) {\n return getContentsAsString();\n }\n}\n"} {"task_id": "Java_2178", "language": "Java", "task_type": "single_line", "source_file": "java/github/facebook/buck/src/com/facebook/buck/jvm/java/ZipEntryJavaFileObject.java", "mask_start_position": 2074, "mask_end_position": 2082, "canonical_solution": "ontents;", "pre_mask_code": "package com.facebook.buck.jvm.java;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.CharStreams;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\nimport javax.annotation.Nullable;\nimport javax.annotation.concurrent.GuardedBy;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\n\nclass ZipEntryJavaFileObject extends SimpleJavaFileObject implements Closeable {\n\n private final ZipFile zipFile;\n\n private final ZipEntry zipEntry;\n\n @GuardedBy(\"this\")\n @Nullable\n private String contents;\n\n public ZipEntryJavaFileObject(ZipFile zipFile, ZipEntry zipEntry) {\n super(createURIFromEntry(zipEntry), JavaFileObject.Kind.SOURCE);\n this.zipFile = zipFile;\n this.zipEntry = zipEntry;\n }\n\n /**\n * Creates a canonical URI that represents the {@link ZipEntry}. This URI starts with {@code\n * \"string:///\"} because {@link JavaCompiler} does not seem to tolerate URIs that start with\n * {@code \"jar:///\"}, even though that would be more appropriate.\n */\n private static URI createURIFromEntry(ZipEntry entry) {\n try {\n return new URI(\"string:///\" + entry.getName());\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Returns the contents of the {@link ZipEntry} as a string. Ensures that the entry is read at\n * most once.\n */\n private synchronized String getContentsAsString() {\n if (contents != null) {\n return contents;\n }\n try (InputStream inputStream = zipFile.getInputStream(zipEntry);\n InputStreamReader isr = new InputStreamReader(inputStream, Charsets.UTF_8)) {\n contents = CharStreams.toString(isr);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return c", "post_mask_code": "\n }\n\n /**\n * Closes the {@link ZipFile} this entry was loaded from. Use with care.\n */\n @Override\n public void close() throws IOException {\n zipFile.close();\n }\n\n @Override\n public CharSequence getCharContent(boolean ignoreEncodingErrors) {\n return getContentsAsString();\n }\n}\n"} {"task_id": "Java_2179", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/facebook/buck/src/com/facebook/buck/jvm/java/ZipEntryJavaFileObject.java", "mask_start_position": 1267, "mask_end_position": 1496, "canonical_solution": "private static URI createURIFromEntry(ZipEntry entry) {\n try {\n return new URI(\"string:///\" + entry.getName());\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n }", "pre_mask_code": "package com.facebook.buck.jvm.java;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.CharStreams;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\nimport javax.annotation.Nullable;\nimport javax.annotation.concurrent.GuardedBy;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\n\nclass ZipEntryJavaFileObject extends SimpleJavaFileObject implements Closeable {\n\n private final ZipFile zipFile;\n\n private final ZipEntry zipEntry;\n\n @GuardedBy(\"this\")\n @Nullable\n private String contents;\n\n public ZipEntryJavaFileObject(ZipFile zipFile, ZipEntry zipEntry) {\n super(createURIFromEntry(zipEntry), JavaFileObject.Kind.SOURCE);\n this.zipFile = zipFile;\n this.zipEntry = zipEntry;\n }\n\n /**\n * Creates a canonical URI that represents the {@link ZipEntry}. This URI starts with {@code\n * \"string:///\"} because {@link JavaCompiler} does not seem to tolerate URIs that start with\n * {@code \"jar:///\"}, even though that would be more appropriate.\n */\n ", "post_mask_code": "\n\n /**\n * Returns the contents of the {@link ZipEntry} as a string. Ensures that the entry is read at\n * most once.\n */\n private synchronized String getContentsAsString() {\n if (contents != null) {\n return contents;\n }\n try (InputStream inputStream = zipFile.getInputStream(zipEntry);\n InputStreamReader isr = new InputStreamReader(inputStream, Charsets.UTF_8)) {\n contents = CharStreams.toString(isr);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return contents;\n }\n\n /**\n * Closes the {@link ZipFile} this entry was loaded from. Use with care.\n */\n @Override\n public void close() throws IOException {\n zipFile.close();\n }\n\n @Override\n public CharSequence getCharContent(boolean ignoreEncodingErrors) {\n return getContentsAsString();\n }\n}\n"} {"task_id": "Java_2180", "language": "Java", "task_type": "try_statement", "source_file": "java/github/facebook/buck/src/com/facebook/buck/jvm/java/ZipEntryJavaFileObject.java", "mask_start_position": 1331, "mask_end_position": 1490, "canonical_solution": "try {\n return new URI(\"string:///\" + entry.getName());\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }", "pre_mask_code": "package com.facebook.buck.jvm.java;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.CharStreams;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\nimport javax.annotation.Nullable;\nimport javax.annotation.concurrent.GuardedBy;\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.SimpleJavaFileObject;\n\nclass ZipEntryJavaFileObject extends SimpleJavaFileObject implements Closeable {\n\n private final ZipFile zipFile;\n\n private final ZipEntry zipEntry;\n\n @GuardedBy(\"this\")\n @Nullable\n private String contents;\n\n public ZipEntryJavaFileObject(ZipFile zipFile, ZipEntry zipEntry) {\n super(createURIFromEntry(zipEntry), JavaFileObject.Kind.SOURCE);\n this.zipFile = zipFile;\n this.zipEntry = zipEntry;\n }\n\n /**\n * Creates a canonical URI that represents the {@link ZipEntry}. This URI starts with {@code\n * \"string:///\"} because {@link JavaCompiler} does not seem to tolerate URIs that start with\n * {@code \"jar:///\"}, even though that would be more appropriate.\n */\n private static URI createURIFromEntry(ZipEntry entry) {\n ", "post_mask_code": "\n }\n\n /**\n * Returns the contents of the {@link ZipEntry} as a string. Ensures that the entry is read at\n * most once.\n */\n private synchronized String getContentsAsString() {\n if (contents != null) {\n return contents;\n }\n try (InputStream inputStream = zipFile.getInputStream(zipEntry);\n InputStreamReader isr = new InputStreamReader(inputStream, Charsets.UTF_8)) {\n contents = CharStreams.toString(isr);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return contents;\n }\n\n /**\n * Closes the {@link ZipFile} this entry was loaded from. Use with care.\n */\n @Override\n public void close() throws IOException {\n zipFile.close();\n }\n\n @Override\n public CharSequence getCharContent(boolean ignoreEncodingErrors) {\n return getContentsAsString();\n }\n}\n"} {"task_id": "Java_2181", "language": "Java", "task_type": "method_signature", "source_file": "java/github/yuchuangu85/Android_Framework_Source/android/databinding/tool/reflection/ModelClass.java", "mask_start_position": 11233, "mask_end_position": 11266, "canonical_solution": "public String getCanonicalName() ", "pre_mask_code": "package android.databinding.tool.reflection;\n\nimport android.databinding.tool.reflection.Callable.Type;\nimport android.databinding.tool.util.L;\nimport android.databinding.tool.util.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport static android.databinding.tool.reflection.Callable.CAN_BE_INVALIDATED;\nimport static android.databinding.tool.reflection.Callable.DYNAMIC;\nimport static android.databinding.tool.reflection.Callable.STATIC;\n\npublic abstract class ModelClass {\n\n public abstract String toJavaCode();\n\n /**\n * @return whether this ModelClass represents an array.\n */\n public abstract boolean isArray();\n\n /**\n * For arrays, lists, and maps, this returns the contained value. For other types, null\n * is returned.\n *\n * @return The component type for arrays, the value type for maps, and the element type\n * for lists.\n */\n public abstract ModelClass getComponentType();\n\n /**\n * @return Whether or not this ModelClass can be treated as a List. This means\n * it is a java.util.List, or one of the Sparse*Array classes.\n */\n public boolean isList() {\n for (ModelClass listType : ModelAnalyzer.getInstance().getListTypes()) {\n if (listType != null) {\n if (listType.isAssignableFrom(this)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * @return whether or not this ModelClass can be considered a Map or not.\n */\n public boolean isMap() {\n return ModelAnalyzer.getInstance().getMapType().isAssignableFrom(erasure());\n }\n\n /**\n * @return whether or not this ModelClass is a java.lang.String.\n */\n public boolean isString() {\n return ModelAnalyzer.getInstance().getStringType().equals(this);\n }\n\n /**\n * @return whether or not this ModelClass represents a Reference type.\n */\n public abstract boolean isNullable();\n\n /**\n * @return whether or not this ModelClass represents a primitive type.\n */\n public abstract boolean isPrimitive();\n\n /**\n * @return whether or not this ModelClass represents a Java boolean\n */\n public abstract boolean isBoolean();\n\n /**\n * @return whether or not this ModelClass represents a Java char\n */\n public abstract boolean isChar();\n\n /**\n * @return whether or not this ModelClass represents a Java byte\n */\n public abstract boolean isByte();\n\n /**\n * @return whether or not this ModelClass represents a Java short\n */\n public abstract boolean isShort();\n\n /**\n * @return whether or not this ModelClass represents a Java int\n */\n public abstract boolean isInt();\n\n /**\n * @return whether or not this ModelClass represents a Java long\n */\n public abstract boolean isLong();\n\n /**\n * @return whether or not this ModelClass represents a Java float\n */\n public abstract boolean isFloat();\n\n /**\n * @return whether or not this ModelClass represents a Java double\n */\n public abstract boolean isDouble();\n\n /**\n * @return whether or not this has type parameters\n */\n public abstract boolean isGeneric();\n\n /**\n * @return a list of Generic type paramters for the class. For example, if the class\n * is List<T>, then the return value will be a list containing T. null is returned\n * if this is not a generic type\n */\n public abstract List getTypeArguments();\n\n /**\n * @return whether this is a type variable. For example, in List<T>, T is a type variable.\n * However, List<String>, String is not a type variable.\n */\n public abstract boolean isTypeVar();\n\n /**\n * @return whether this is a wildcard type argument or not.\n */\n public abstract boolean isWildcard();\n\n /**\n * @return whether or not this ModelClass is java.lang.Object and not a primitive or subclass.\n */\n public boolean isObject() {\n return ModelAnalyzer.getInstance().getObjectType().equals(this);\n }\n\n /**\n * @return whether or not this ModelClass is an interface\n */\n public abstract boolean isInterface();\n\n /**\n * @return whether or not his is a ViewDataBinding subclass.\n */\n public boolean isViewDataBinding() {\n return ModelAnalyzer.getInstance().getViewDataBindingType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this ModelClass type extends ViewStub.\n */\n public boolean extendsViewStub() {\n return ModelAnalyzer.getInstance().getViewStubType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this is an Observable type such as ObservableMap, ObservableList,\n * or Observable.\n */\n public boolean isObservable() {\n ModelAnalyzer modelAnalyzer = ModelAnalyzer.getInstance();\n return modelAnalyzer.getObservableType().isAssignableFrom(this) || modelAnalyzer.getObservableListType().isAssignableFrom(this) || modelAnalyzer.getObservableMapType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this is an ObservableField, or any of the primitive versions\n * such as ObservableBoolean and ObservableInt\n */\n public boolean isObservableField() {\n ModelClass erasure = erasure();\n for (ModelClass observableField : ModelAnalyzer.getInstance().getObservableFieldTypes()) {\n if (observableField.isAssignableFrom(erasure)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @return whether or not this ModelClass represents a void\n */\n public abstract boolean isVoid();\n\n /**\n * When this is a boxed type, such as Integer, this will return the unboxed value,\n * such as int. If this is not a boxed type, this is returned.\n *\n * @return The unboxed type of the class that this ModelClass represents or this if it isn't a\n * boxed type.\n */\n public abstract ModelClass unbox();\n\n /**\n * When this is a primitive type, such as boolean, this will return the boxed value,\n * such as Boolean. If this is not a primitive type, this is returned.\n *\n * @return The boxed type of the class that this ModelClass represents or this if it isn't a\n * primitive type.\n */\n public abstract ModelClass box();\n\n /**\n * Returns whether or not the type associated with that can be assigned to\n * the type associated with this ModelClass. If this and that only require boxing or unboxing\n * then true is returned.\n *\n * @param that the ModelClass to compare.\n * @return true if that requires only boxing or if that is an\n * implementation of or subclass of this.\n */\n public abstract boolean isAssignableFrom(ModelClass that);\n\n /**\n * Returns an array containing all public methods (or protected if allowProtected is true)\n * on the type represented by this ModelClass with the name name and can\n * take the passed-in types as arguments. This will also work if the arguments match\n * VarArgs parameter.\n *\n * @param name The name of the method to find.\n * @param args The types that the method should accept.\n * @param staticOnly Whether only static methods should be returned or both instance methods\n * and static methods are valid.\n * @param allowProtected true if the method can be protected as well as public.\n *\n * @return An array containing all public methods with the name name and taking\n * args parameters.\n */\n public ModelMethod[] getMethods(String name, List args, boolean staticOnly, boolean allowProtected) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if ((method.isPublic() || (allowProtected && method.isProtected())) && (!staticOnly || method.isStatic()) && name.equals(method.getName()) && method.acceptsArguments(args)) {\n matching.add(method);\n }\n }\n return matching.toArray(new ModelMethod[matching.size()]);\n }\n\n /**\n * Returns all public instance methods with the given name and number of parameters.\n *\n * @param name The name of the method to find.\n * @param numParameters The number of parameters that the method should take\n * @return An array containing all public methods with the given name and number of parameters.\n */\n public ModelMethod[] getMethods(String name, int numParameters) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if (method.isPublic() && !method.isStatic() && name.equals(method.getName()) && method.getParameterTypes().length == numParameters) {\n matching.add(method);\n }\n }\n return matching.toArray(new ModelMethod[matching.size()]);\n }\n\n /**\n * Returns the public method with the name name with the parameters that\n * best match args. staticOnly governs whether a static or instance method\n * will be returned. If no matching method was found, null is returned.\n *\n * @param name The method name to find\n * @param args The arguments that the method should accept\n * @param staticOnly true if the returned method must be static or false if it does not\n * matter.\n * @param allowProtected true if the method can be protected as well as public.\n */\n public ModelMethod getMethod(String name, List args, boolean staticOnly, boolean allowProtected) {\n ModelMethod[] methods = getMethods(name, args, staticOnly, allowProtected);\n L.d(\"looking methods for %s. static only ? %s . method count: %d\", name, staticOnly, methods.length);\n for (ModelMethod method : methods) {\n L.d(\"method: %s, %s\", method.getName(), method.isStatic());\n }\n if (methods.length == 0) {\n return null;\n }\n ModelMethod bestMethod = methods[0];\n for (int i = 1; i < methods.length; i++) {\n if (methods[i].isBetterArgMatchThan(bestMethod, args)) {\n bestMethod = methods[i];\n }\n }\n return bestMethod;\n }\n\n /**\n * If this represents a class, the super class that it extends is returned. If this\n * represents an interface, the interface that this extends is returned.\n * null is returned if this is not a class or interface, such as an int, or\n * if it is java.lang.Object or an interface that does not extend any other type.\n *\n * @return The class or interface that this ModelClass extends or null.\n */\n public abstract ModelClass getSuperclass();\n\n /**\n * @return A String representation of the class or interface that this represents, not\n * including any type arguments.\n */\n ", "post_mask_code": "{\n return erasure().toJavaCode();\n }\n\n /**\n * @return The class or interface name of this type or the primitive type if it isn't a\n * reference type.\n */\n public String getSimpleName() {\n final String canonicalName = getCanonicalName();\n final int dotIndex = canonicalName.lastIndexOf('.');\n if (dotIndex >= 0) {\n return canonicalName.substring(dotIndex + 1);\n }\n return canonicalName;\n }\n\n /**\n * Returns this class type without any generic type arguments.\n * @return this class type without any generic type arguments.\n */\n public abstract ModelClass erasure();\n\n /**\n * Since when this class is available. Important for Binding expressions so that we don't\n * call non-existing APIs when setting UI.\n *\n * @return The SDK_INT where this method was added. If it is not a framework method, should\n * return 1.\n */\n public int getMinApi() {\n return SdkUtil.getMinApi(this);\n }\n\n /**\n * Returns the JNI description of the method which can be used to lookup it in SDK.\n * @see TypeUtil\n */\n public abstract String getJniDescription();\n\n /**\n * Returns a list of all abstract methods in the type.\n */\n @NotNull\n public List getAbstractMethods() {\n ArrayList abstractMethods = new ArrayList();\n ModelMethod[] methods = getDeclaredMethods();\n for (ModelMethod method : methods) {\n if (method.isAbstract()) {\n abstractMethods.add(method);\n }\n }\n return abstractMethods;\n }\n\n /**\n * Returns the getter method or field that the name refers to.\n * @param name The name of the field or the body of the method name -- can be name(),\n * getName(), or isName().\n * @param staticOnly Whether this should look for static methods and fields or instance\n * versions\n * @return the getter method or field that the name refers to or null if none can be found.\n */\n public Callable findGetterOrField(String name, boolean staticOnly) {\n if (\"length\".equals(name) && isArray()) {\n return new Callable(Type.FIELD, name, null, ModelAnalyzer.getInstance().loadPrimitive(\"int\"), 0, 0, null);\n }\n String capitalized = StringUtils.capitalize(name);\n String[] methodNames = { \"get\" + capitalized, \"is\" + capitalized, name };\n for (String methodName : methodNames) {\n ModelMethod[] methods = getMethods(methodName, new ArrayList(), staticOnly, false);\n for (ModelMethod method : methods) {\n if (method.isPublic() && (!staticOnly || method.isStatic()) && !method.getReturnType(Arrays.asList(method.getParameterTypes())).isVoid()) {\n int flags = DYNAMIC;\n if (method.isStatic()) {\n flags |= STATIC;\n }\n if (method.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n } else {\n // if method is not bindable, look for a backing field\n final ModelField backingField = getField(name, true, method.isStatic());\n L.d(\"backing field for method %s is %s\", method.getName(), backingField == null ? \"NOT FOUND\" : backingField.getName());\n if (backingField != null && backingField.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n }\n }\n final ModelMethod setterMethod = findSetter(method, name);\n final String setterName = setterMethod == null ? null : setterMethod.getName();\n final Callable result = new Callable(Callable.Type.METHOD, methodName, setterName, method.getReturnType(null), method.getParameterTypes().length, flags, method);\n return result;\n }\n }\n }\n // could not find a method. Look for a public field\n ModelField publicField = null;\n if (staticOnly) {\n publicField = getField(name, false, true);\n } else {\n // first check non-static\n publicField = getField(name, false, false);\n if (publicField == null) {\n publicField = getField(name, false, true);\n }\n }\n if (publicField == null) {\n return null;\n }\n ModelClass fieldType = publicField.getFieldType();\n int flags = 0;\n String setterFieldName = name;\n if (publicField.isStatic()) {\n flags |= STATIC;\n }\n if (!publicField.isFinal()) {\n setterFieldName = null;\n flags |= DYNAMIC;\n }\n if (publicField.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n }\n return new Callable(Callable.Type.FIELD, name, setterFieldName, fieldType, 0, flags, null);\n }\n\n public ModelMethod findInstanceGetter(String name) {\n String capitalized = StringUtils.capitalize(name);\n String[] methodNames = { \"get\" + capitalized, \"is\" + capitalized, name };\n for (String methodName : methodNames) {\n ModelMethod[] methods = getMethods(methodName, new ArrayList(), false, false);\n for (ModelMethod method : methods) {\n if (method.isPublic() && !method.isStatic() && !method.getReturnType(Arrays.asList(method.getParameterTypes())).isVoid()) {\n return method;\n }\n }\n }\n return null;\n }\n\n private ModelField getField(String name, boolean allowPrivate, boolean isStatic) {\n ModelField[] fields = getDeclaredFields();\n for (ModelField field : fields) {\n boolean nameMatch = name.equals(field.getName()) || name.equals(stripFieldName(field.getName()));\n if (nameMatch && field.isStatic() == isStatic && (allowPrivate || field.isPublic())) {\n return field;\n }\n }\n return null;\n }\n\n private ModelMethod findSetter(ModelMethod getter, String originalName) {\n final String capitalized = StringUtils.capitalize(originalName);\n final String[] possibleNames;\n if (originalName.equals(getter.getName())) {\n possibleNames = new String[] { originalName, \"set\" + capitalized };\n } else if (getter.getName().startsWith(\"is\")) {\n possibleNames = new String[] { \"set\" + capitalized, \"setIs\" + capitalized };\n } else {\n possibleNames = new String[] { \"set\" + capitalized };\n }\n for (String name : possibleNames) {\n List methods = findMethods(name, getter.isStatic());\n ModelClass param = getter.getReturnType(null);\n for (ModelMethod method : methods) {\n ModelClass[] parameterTypes = method.getParameterTypes();\n if (parameterTypes != null && parameterTypes.length == 1 && parameterTypes[0].equals(param) && method.isStatic() == getter.isStatic()) {\n return method;\n }\n }\n }\n return null;\n }\n\n /**\n * Finds public methods that matches the given name exactly. These may be resolved into\n * listener methods during Expr.resolveListeners.\n */\n @NotNull\n public List findMethods(String name, boolean staticOnly) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if (method.getName().equals(name) && (!staticOnly || method.isStatic()) && method.isPublic()) {\n matching.add(method);\n }\n }\n return matching;\n }\n\n public boolean isIncomplete() {\n if (isTypeVar() || isWildcard()) {\n return true;\n }\n List typeArgs = getTypeArguments();\n if (typeArgs != null) {\n for (ModelClass typeArg : typeArgs) {\n if (typeArg.isIncomplete()) {\n return true;\n }\n }\n }\n return false;\n }\n\n protected abstract ModelField[] getDeclaredFields();\n\n protected abstract ModelMethod[] getDeclaredMethods();\n\n private static String stripFieldName(String fieldName) {\n // TODO: Make this configurable through IntelliJ\n if (fieldName.length() > 2) {\n final char start = fieldName.charAt(2);\n if (fieldName.startsWith(\"m_\") && Character.isJavaIdentifierStart(start)) {\n return Character.toLowerCase(start) + fieldName.substring(3);\n }\n }\n if (fieldName.length() > 1) {\n final char start = fieldName.charAt(1);\n final char fieldIdentifier = fieldName.charAt(0);\n final boolean strip;\n if (fieldIdentifier == '_') {\n strip = true;\n } else if (fieldIdentifier == 'm' && Character.isJavaIdentifierStart(start) && !Character.isLowerCase(start)) {\n strip = true;\n } else {\n // not mUppercase format\n strip = false;\n }\n if (strip) {\n return Character.toLowerCase(start) + fieldName.substring(2);\n }\n }\n return fieldName;\n }\n}\n"} {"task_id": "Java_2182", "language": "Java", "task_type": "method_body", "source_file": "java/github/yuchuangu85/Android_Framework_Source/android/databinding/tool/reflection/ModelClass.java", "mask_start_position": 17056, "mask_end_position": 17440, "canonical_solution": "{\n ModelField[] fields = getDeclaredFields();\n for (ModelField field : fields) {\n boolean nameMatch = name.equals(field.getName()) || name.equals(stripFieldName(field.getName()));\n if (nameMatch && field.isStatic() == isStatic && (allowPrivate || field.isPublic())) {\n return field;\n }\n }\n return null;\n }", "pre_mask_code": "package android.databinding.tool.reflection;\n\nimport android.databinding.tool.reflection.Callable.Type;\nimport android.databinding.tool.util.L;\nimport android.databinding.tool.util.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport static android.databinding.tool.reflection.Callable.CAN_BE_INVALIDATED;\nimport static android.databinding.tool.reflection.Callable.DYNAMIC;\nimport static android.databinding.tool.reflection.Callable.STATIC;\n\npublic abstract class ModelClass {\n\n public abstract String toJavaCode();\n\n /**\n * @return whether this ModelClass represents an array.\n */\n public abstract boolean isArray();\n\n /**\n * For arrays, lists, and maps, this returns the contained value. For other types, null\n * is returned.\n *\n * @return The component type for arrays, the value type for maps, and the element type\n * for lists.\n */\n public abstract ModelClass getComponentType();\n\n /**\n * @return Whether or not this ModelClass can be treated as a List. This means\n * it is a java.util.List, or one of the Sparse*Array classes.\n */\n public boolean isList() {\n for (ModelClass listType : ModelAnalyzer.getInstance().getListTypes()) {\n if (listType != null) {\n if (listType.isAssignableFrom(this)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * @return whether or not this ModelClass can be considered a Map or not.\n */\n public boolean isMap() {\n return ModelAnalyzer.getInstance().getMapType().isAssignableFrom(erasure());\n }\n\n /**\n * @return whether or not this ModelClass is a java.lang.String.\n */\n public boolean isString() {\n return ModelAnalyzer.getInstance().getStringType().equals(this);\n }\n\n /**\n * @return whether or not this ModelClass represents a Reference type.\n */\n public abstract boolean isNullable();\n\n /**\n * @return whether or not this ModelClass represents a primitive type.\n */\n public abstract boolean isPrimitive();\n\n /**\n * @return whether or not this ModelClass represents a Java boolean\n */\n public abstract boolean isBoolean();\n\n /**\n * @return whether or not this ModelClass represents a Java char\n */\n public abstract boolean isChar();\n\n /**\n * @return whether or not this ModelClass represents a Java byte\n */\n public abstract boolean isByte();\n\n /**\n * @return whether or not this ModelClass represents a Java short\n */\n public abstract boolean isShort();\n\n /**\n * @return whether or not this ModelClass represents a Java int\n */\n public abstract boolean isInt();\n\n /**\n * @return whether or not this ModelClass represents a Java long\n */\n public abstract boolean isLong();\n\n /**\n * @return whether or not this ModelClass represents a Java float\n */\n public abstract boolean isFloat();\n\n /**\n * @return whether or not this ModelClass represents a Java double\n */\n public abstract boolean isDouble();\n\n /**\n * @return whether or not this has type parameters\n */\n public abstract boolean isGeneric();\n\n /**\n * @return a list of Generic type paramters for the class. For example, if the class\n * is List<T>, then the return value will be a list containing T. null is returned\n * if this is not a generic type\n */\n public abstract List getTypeArguments();\n\n /**\n * @return whether this is a type variable. For example, in List<T>, T is a type variable.\n * However, List<String>, String is not a type variable.\n */\n public abstract boolean isTypeVar();\n\n /**\n * @return whether this is a wildcard type argument or not.\n */\n public abstract boolean isWildcard();\n\n /**\n * @return whether or not this ModelClass is java.lang.Object and not a primitive or subclass.\n */\n public boolean isObject() {\n return ModelAnalyzer.getInstance().getObjectType().equals(this);\n }\n\n /**\n * @return whether or not this ModelClass is an interface\n */\n public abstract boolean isInterface();\n\n /**\n * @return whether or not his is a ViewDataBinding subclass.\n */\n public boolean isViewDataBinding() {\n return ModelAnalyzer.getInstance().getViewDataBindingType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this ModelClass type extends ViewStub.\n */\n public boolean extendsViewStub() {\n return ModelAnalyzer.getInstance().getViewStubType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this is an Observable type such as ObservableMap, ObservableList,\n * or Observable.\n */\n public boolean isObservable() {\n ModelAnalyzer modelAnalyzer = ModelAnalyzer.getInstance();\n return modelAnalyzer.getObservableType().isAssignableFrom(this) || modelAnalyzer.getObservableListType().isAssignableFrom(this) || modelAnalyzer.getObservableMapType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this is an ObservableField, or any of the primitive versions\n * such as ObservableBoolean and ObservableInt\n */\n public boolean isObservableField() {\n ModelClass erasure = erasure();\n for (ModelClass observableField : ModelAnalyzer.getInstance().getObservableFieldTypes()) {\n if (observableField.isAssignableFrom(erasure)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @return whether or not this ModelClass represents a void\n */\n public abstract boolean isVoid();\n\n /**\n * When this is a boxed type, such as Integer, this will return the unboxed value,\n * such as int. If this is not a boxed type, this is returned.\n *\n * @return The unboxed type of the class that this ModelClass represents or this if it isn't a\n * boxed type.\n */\n public abstract ModelClass unbox();\n\n /**\n * When this is a primitive type, such as boolean, this will return the boxed value,\n * such as Boolean. If this is not a primitive type, this is returned.\n *\n * @return The boxed type of the class that this ModelClass represents or this if it isn't a\n * primitive type.\n */\n public abstract ModelClass box();\n\n /**\n * Returns whether or not the type associated with that can be assigned to\n * the type associated with this ModelClass. If this and that only require boxing or unboxing\n * then true is returned.\n *\n * @param that the ModelClass to compare.\n * @return true if that requires only boxing or if that is an\n * implementation of or subclass of this.\n */\n public abstract boolean isAssignableFrom(ModelClass that);\n\n /**\n * Returns an array containing all public methods (or protected if allowProtected is true)\n * on the type represented by this ModelClass with the name name and can\n * take the passed-in types as arguments. This will also work if the arguments match\n * VarArgs parameter.\n *\n * @param name The name of the method to find.\n * @param args The types that the method should accept.\n * @param staticOnly Whether only static methods should be returned or both instance methods\n * and static methods are valid.\n * @param allowProtected true if the method can be protected as well as public.\n *\n * @return An array containing all public methods with the name name and taking\n * args parameters.\n */\n public ModelMethod[] getMethods(String name, List args, boolean staticOnly, boolean allowProtected) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if ((method.isPublic() || (allowProtected && method.isProtected())) && (!staticOnly || method.isStatic()) && name.equals(method.getName()) && method.acceptsArguments(args)) {\n matching.add(method);\n }\n }\n return matching.toArray(new ModelMethod[matching.size()]);\n }\n\n /**\n * Returns all public instance methods with the given name and number of parameters.\n *\n * @param name The name of the method to find.\n * @param numParameters The number of parameters that the method should take\n * @return An array containing all public methods with the given name and number of parameters.\n */\n public ModelMethod[] getMethods(String name, int numParameters) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if (method.isPublic() && !method.isStatic() && name.equals(method.getName()) && method.getParameterTypes().length == numParameters) {\n matching.add(method);\n }\n }\n return matching.toArray(new ModelMethod[matching.size()]);\n }\n\n /**\n * Returns the public method with the name name with the parameters that\n * best match args. staticOnly governs whether a static or instance method\n * will be returned. If no matching method was found, null is returned.\n *\n * @param name The method name to find\n * @param args The arguments that the method should accept\n * @param staticOnly true if the returned method must be static or false if it does not\n * matter.\n * @param allowProtected true if the method can be protected as well as public.\n */\n public ModelMethod getMethod(String name, List args, boolean staticOnly, boolean allowProtected) {\n ModelMethod[] methods = getMethods(name, args, staticOnly, allowProtected);\n L.d(\"looking methods for %s. static only ? %s . method count: %d\", name, staticOnly, methods.length);\n for (ModelMethod method : methods) {\n L.d(\"method: %s, %s\", method.getName(), method.isStatic());\n }\n if (methods.length == 0) {\n return null;\n }\n ModelMethod bestMethod = methods[0];\n for (int i = 1; i < methods.length; i++) {\n if (methods[i].isBetterArgMatchThan(bestMethod, args)) {\n bestMethod = methods[i];\n }\n }\n return bestMethod;\n }\n\n /**\n * If this represents a class, the super class that it extends is returned. If this\n * represents an interface, the interface that this extends is returned.\n * null is returned if this is not a class or interface, such as an int, or\n * if it is java.lang.Object or an interface that does not extend any other type.\n *\n * @return The class or interface that this ModelClass extends or null.\n */\n public abstract ModelClass getSuperclass();\n\n /**\n * @return A String representation of the class or interface that this represents, not\n * including any type arguments.\n */\n public String getCanonicalName() {\n return erasure().toJavaCode();\n }\n\n /**\n * @return The class or interface name of this type or the primitive type if it isn't a\n * reference type.\n */\n public String getSimpleName() {\n final String canonicalName = getCanonicalName();\n final int dotIndex = canonicalName.lastIndexOf('.');\n if (dotIndex >= 0) {\n return canonicalName.substring(dotIndex + 1);\n }\n return canonicalName;\n }\n\n /**\n * Returns this class type without any generic type arguments.\n * @return this class type without any generic type arguments.\n */\n public abstract ModelClass erasure();\n\n /**\n * Since when this class is available. Important for Binding expressions so that we don't\n * call non-existing APIs when setting UI.\n *\n * @return The SDK_INT where this method was added. If it is not a framework method, should\n * return 1.\n */\n public int getMinApi() {\n return SdkUtil.getMinApi(this);\n }\n\n /**\n * Returns the JNI description of the method which can be used to lookup it in SDK.\n * @see TypeUtil\n */\n public abstract String getJniDescription();\n\n /**\n * Returns a list of all abstract methods in the type.\n */\n @NotNull\n public List getAbstractMethods() {\n ArrayList abstractMethods = new ArrayList();\n ModelMethod[] methods = getDeclaredMethods();\n for (ModelMethod method : methods) {\n if (method.isAbstract()) {\n abstractMethods.add(method);\n }\n }\n return abstractMethods;\n }\n\n /**\n * Returns the getter method or field that the name refers to.\n * @param name The name of the field or the body of the method name -- can be name(),\n * getName(), or isName().\n * @param staticOnly Whether this should look for static methods and fields or instance\n * versions\n * @return the getter method or field that the name refers to or null if none can be found.\n */\n public Callable findGetterOrField(String name, boolean staticOnly) {\n if (\"length\".equals(name) && isArray()) {\n return new Callable(Type.FIELD, name, null, ModelAnalyzer.getInstance().loadPrimitive(\"int\"), 0, 0, null);\n }\n String capitalized = StringUtils.capitalize(name);\n String[] methodNames = { \"get\" + capitalized, \"is\" + capitalized, name };\n for (String methodName : methodNames) {\n ModelMethod[] methods = getMethods(methodName, new ArrayList(), staticOnly, false);\n for (ModelMethod method : methods) {\n if (method.isPublic() && (!staticOnly || method.isStatic()) && !method.getReturnType(Arrays.asList(method.getParameterTypes())).isVoid()) {\n int flags = DYNAMIC;\n if (method.isStatic()) {\n flags |= STATIC;\n }\n if (method.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n } else {\n // if method is not bindable, look for a backing field\n final ModelField backingField = getField(name, true, method.isStatic());\n L.d(\"backing field for method %s is %s\", method.getName(), backingField == null ? \"NOT FOUND\" : backingField.getName());\n if (backingField != null && backingField.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n }\n }\n final ModelMethod setterMethod = findSetter(method, name);\n final String setterName = setterMethod == null ? null : setterMethod.getName();\n final Callable result = new Callable(Callable.Type.METHOD, methodName, setterName, method.getReturnType(null), method.getParameterTypes().length, flags, method);\n return result;\n }\n }\n }\n // could not find a method. Look for a public field\n ModelField publicField = null;\n if (staticOnly) {\n publicField = getField(name, false, true);\n } else {\n // first check non-static\n publicField = getField(name, false, false);\n if (publicField == null) {\n publicField = getField(name, false, true);\n }\n }\n if (publicField == null) {\n return null;\n }\n ModelClass fieldType = publicField.getFieldType();\n int flags = 0;\n String setterFieldName = name;\n if (publicField.isStatic()) {\n flags |= STATIC;\n }\n if (!publicField.isFinal()) {\n setterFieldName = null;\n flags |= DYNAMIC;\n }\n if (publicField.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n }\n return new Callable(Callable.Type.FIELD, name, setterFieldName, fieldType, 0, flags, null);\n }\n\n public ModelMethod findInstanceGetter(String name) {\n String capitalized = StringUtils.capitalize(name);\n String[] methodNames = { \"get\" + capitalized, \"is\" + capitalized, name };\n for (String methodName : methodNames) {\n ModelMethod[] methods = getMethods(methodName, new ArrayList(), false, false);\n for (ModelMethod method : methods) {\n if (method.isPublic() && !method.isStatic() && !method.getReturnType(Arrays.asList(method.getParameterTypes())).isVoid()) {\n return method;\n }\n }\n }\n return null;\n }\n\n private ModelField getField(String name, boolean allowPrivate, boolean isStatic) ", "post_mask_code": "\n\n private ModelMethod findSetter(ModelMethod getter, String originalName) {\n final String capitalized = StringUtils.capitalize(originalName);\n final String[] possibleNames;\n if (originalName.equals(getter.getName())) {\n possibleNames = new String[] { originalName, \"set\" + capitalized };\n } else if (getter.getName().startsWith(\"is\")) {\n possibleNames = new String[] { \"set\" + capitalized, \"setIs\" + capitalized };\n } else {\n possibleNames = new String[] { \"set\" + capitalized };\n }\n for (String name : possibleNames) {\n List methods = findMethods(name, getter.isStatic());\n ModelClass param = getter.getReturnType(null);\n for (ModelMethod method : methods) {\n ModelClass[] parameterTypes = method.getParameterTypes();\n if (parameterTypes != null && parameterTypes.length == 1 && parameterTypes[0].equals(param) && method.isStatic() == getter.isStatic()) {\n return method;\n }\n }\n }\n return null;\n }\n\n /**\n * Finds public methods that matches the given name exactly. These may be resolved into\n * listener methods during Expr.resolveListeners.\n */\n @NotNull\n public List findMethods(String name, boolean staticOnly) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if (method.getName().equals(name) && (!staticOnly || method.isStatic()) && method.isPublic()) {\n matching.add(method);\n }\n }\n return matching;\n }\n\n public boolean isIncomplete() {\n if (isTypeVar() || isWildcard()) {\n return true;\n }\n List typeArgs = getTypeArguments();\n if (typeArgs != null) {\n for (ModelClass typeArg : typeArgs) {\n if (typeArg.isIncomplete()) {\n return true;\n }\n }\n }\n return false;\n }\n\n protected abstract ModelField[] getDeclaredFields();\n\n protected abstract ModelMethod[] getDeclaredMethods();\n\n private static String stripFieldName(String fieldName) {\n // TODO: Make this configurable through IntelliJ\n if (fieldName.length() > 2) {\n final char start = fieldName.charAt(2);\n if (fieldName.startsWith(\"m_\") && Character.isJavaIdentifierStart(start)) {\n return Character.toLowerCase(start) + fieldName.substring(3);\n }\n }\n if (fieldName.length() > 1) {\n final char start = fieldName.charAt(1);\n final char fieldIdentifier = fieldName.charAt(0);\n final boolean strip;\n if (fieldIdentifier == '_') {\n strip = true;\n } else if (fieldIdentifier == 'm' && Character.isJavaIdentifierStart(start) && !Character.isLowerCase(start)) {\n strip = true;\n } else {\n // not mUppercase format\n strip = false;\n }\n if (strip) {\n return Character.toLowerCase(start) + fieldName.substring(2);\n }\n }\n return fieldName;\n }\n}\n"} {"task_id": "Java_2183", "language": "Java", "task_type": "single_line", "source_file": "java/github/yuchuangu85/Android_Framework_Source/android/databinding/tool/reflection/ModelClass.java", "mask_start_position": 18550, "mask_end_position": 18556, "canonical_solution": " null;", "pre_mask_code": "package android.databinding.tool.reflection;\n\nimport android.databinding.tool.reflection.Callable.Type;\nimport android.databinding.tool.util.L;\nimport android.databinding.tool.util.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport static android.databinding.tool.reflection.Callable.CAN_BE_INVALIDATED;\nimport static android.databinding.tool.reflection.Callable.DYNAMIC;\nimport static android.databinding.tool.reflection.Callable.STATIC;\n\npublic abstract class ModelClass {\n\n public abstract String toJavaCode();\n\n /**\n * @return whether this ModelClass represents an array.\n */\n public abstract boolean isArray();\n\n /**\n * For arrays, lists, and maps, this returns the contained value. For other types, null\n * is returned.\n *\n * @return The component type for arrays, the value type for maps, and the element type\n * for lists.\n */\n public abstract ModelClass getComponentType();\n\n /**\n * @return Whether or not this ModelClass can be treated as a List. This means\n * it is a java.util.List, or one of the Sparse*Array classes.\n */\n public boolean isList() {\n for (ModelClass listType : ModelAnalyzer.getInstance().getListTypes()) {\n if (listType != null) {\n if (listType.isAssignableFrom(this)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * @return whether or not this ModelClass can be considered a Map or not.\n */\n public boolean isMap() {\n return ModelAnalyzer.getInstance().getMapType().isAssignableFrom(erasure());\n }\n\n /**\n * @return whether or not this ModelClass is a java.lang.String.\n */\n public boolean isString() {\n return ModelAnalyzer.getInstance().getStringType().equals(this);\n }\n\n /**\n * @return whether or not this ModelClass represents a Reference type.\n */\n public abstract boolean isNullable();\n\n /**\n * @return whether or not this ModelClass represents a primitive type.\n */\n public abstract boolean isPrimitive();\n\n /**\n * @return whether or not this ModelClass represents a Java boolean\n */\n public abstract boolean isBoolean();\n\n /**\n * @return whether or not this ModelClass represents a Java char\n */\n public abstract boolean isChar();\n\n /**\n * @return whether or not this ModelClass represents a Java byte\n */\n public abstract boolean isByte();\n\n /**\n * @return whether or not this ModelClass represents a Java short\n */\n public abstract boolean isShort();\n\n /**\n * @return whether or not this ModelClass represents a Java int\n */\n public abstract boolean isInt();\n\n /**\n * @return whether or not this ModelClass represents a Java long\n */\n public abstract boolean isLong();\n\n /**\n * @return whether or not this ModelClass represents a Java float\n */\n public abstract boolean isFloat();\n\n /**\n * @return whether or not this ModelClass represents a Java double\n */\n public abstract boolean isDouble();\n\n /**\n * @return whether or not this has type parameters\n */\n public abstract boolean isGeneric();\n\n /**\n * @return a list of Generic type paramters for the class. For example, if the class\n * is List<T>, then the return value will be a list containing T. null is returned\n * if this is not a generic type\n */\n public abstract List getTypeArguments();\n\n /**\n * @return whether this is a type variable. For example, in List<T>, T is a type variable.\n * However, List<String>, String is not a type variable.\n */\n public abstract boolean isTypeVar();\n\n /**\n * @return whether this is a wildcard type argument or not.\n */\n public abstract boolean isWildcard();\n\n /**\n * @return whether or not this ModelClass is java.lang.Object and not a primitive or subclass.\n */\n public boolean isObject() {\n return ModelAnalyzer.getInstance().getObjectType().equals(this);\n }\n\n /**\n * @return whether or not this ModelClass is an interface\n */\n public abstract boolean isInterface();\n\n /**\n * @return whether or not his is a ViewDataBinding subclass.\n */\n public boolean isViewDataBinding() {\n return ModelAnalyzer.getInstance().getViewDataBindingType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this ModelClass type extends ViewStub.\n */\n public boolean extendsViewStub() {\n return ModelAnalyzer.getInstance().getViewStubType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this is an Observable type such as ObservableMap, ObservableList,\n * or Observable.\n */\n public boolean isObservable() {\n ModelAnalyzer modelAnalyzer = ModelAnalyzer.getInstance();\n return modelAnalyzer.getObservableType().isAssignableFrom(this) || modelAnalyzer.getObservableListType().isAssignableFrom(this) || modelAnalyzer.getObservableMapType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this is an ObservableField, or any of the primitive versions\n * such as ObservableBoolean and ObservableInt\n */\n public boolean isObservableField() {\n ModelClass erasure = erasure();\n for (ModelClass observableField : ModelAnalyzer.getInstance().getObservableFieldTypes()) {\n if (observableField.isAssignableFrom(erasure)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @return whether or not this ModelClass represents a void\n */\n public abstract boolean isVoid();\n\n /**\n * When this is a boxed type, such as Integer, this will return the unboxed value,\n * such as int. If this is not a boxed type, this is returned.\n *\n * @return The unboxed type of the class that this ModelClass represents or this if it isn't a\n * boxed type.\n */\n public abstract ModelClass unbox();\n\n /**\n * When this is a primitive type, such as boolean, this will return the boxed value,\n * such as Boolean. If this is not a primitive type, this is returned.\n *\n * @return The boxed type of the class that this ModelClass represents or this if it isn't a\n * primitive type.\n */\n public abstract ModelClass box();\n\n /**\n * Returns whether or not the type associated with that can be assigned to\n * the type associated with this ModelClass. If this and that only require boxing or unboxing\n * then true is returned.\n *\n * @param that the ModelClass to compare.\n * @return true if that requires only boxing or if that is an\n * implementation of or subclass of this.\n */\n public abstract boolean isAssignableFrom(ModelClass that);\n\n /**\n * Returns an array containing all public methods (or protected if allowProtected is true)\n * on the type represented by this ModelClass with the name name and can\n * take the passed-in types as arguments. This will also work if the arguments match\n * VarArgs parameter.\n *\n * @param name The name of the method to find.\n * @param args The types that the method should accept.\n * @param staticOnly Whether only static methods should be returned or both instance methods\n * and static methods are valid.\n * @param allowProtected true if the method can be protected as well as public.\n *\n * @return An array containing all public methods with the name name and taking\n * args parameters.\n */\n public ModelMethod[] getMethods(String name, List args, boolean staticOnly, boolean allowProtected) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if ((method.isPublic() || (allowProtected && method.isProtected())) && (!staticOnly || method.isStatic()) && name.equals(method.getName()) && method.acceptsArguments(args)) {\n matching.add(method);\n }\n }\n return matching.toArray(new ModelMethod[matching.size()]);\n }\n\n /**\n * Returns all public instance methods with the given name and number of parameters.\n *\n * @param name The name of the method to find.\n * @param numParameters The number of parameters that the method should take\n * @return An array containing all public methods with the given name and number of parameters.\n */\n public ModelMethod[] getMethods(String name, int numParameters) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if (method.isPublic() && !method.isStatic() && name.equals(method.getName()) && method.getParameterTypes().length == numParameters) {\n matching.add(method);\n }\n }\n return matching.toArray(new ModelMethod[matching.size()]);\n }\n\n /**\n * Returns the public method with the name name with the parameters that\n * best match args. staticOnly governs whether a static or instance method\n * will be returned. If no matching method was found, null is returned.\n *\n * @param name The method name to find\n * @param args The arguments that the method should accept\n * @param staticOnly true if the returned method must be static or false if it does not\n * matter.\n * @param allowProtected true if the method can be protected as well as public.\n */\n public ModelMethod getMethod(String name, List args, boolean staticOnly, boolean allowProtected) {\n ModelMethod[] methods = getMethods(name, args, staticOnly, allowProtected);\n L.d(\"looking methods for %s. static only ? %s . method count: %d\", name, staticOnly, methods.length);\n for (ModelMethod method : methods) {\n L.d(\"method: %s, %s\", method.getName(), method.isStatic());\n }\n if (methods.length == 0) {\n return null;\n }\n ModelMethod bestMethod = methods[0];\n for (int i = 1; i < methods.length; i++) {\n if (methods[i].isBetterArgMatchThan(bestMethod, args)) {\n bestMethod = methods[i];\n }\n }\n return bestMethod;\n }\n\n /**\n * If this represents a class, the super class that it extends is returned. If this\n * represents an interface, the interface that this extends is returned.\n * null is returned if this is not a class or interface, such as an int, or\n * if it is java.lang.Object or an interface that does not extend any other type.\n *\n * @return The class or interface that this ModelClass extends or null.\n */\n public abstract ModelClass getSuperclass();\n\n /**\n * @return A String representation of the class or interface that this represents, not\n * including any type arguments.\n */\n public String getCanonicalName() {\n return erasure().toJavaCode();\n }\n\n /**\n * @return The class or interface name of this type or the primitive type if it isn't a\n * reference type.\n */\n public String getSimpleName() {\n final String canonicalName = getCanonicalName();\n final int dotIndex = canonicalName.lastIndexOf('.');\n if (dotIndex >= 0) {\n return canonicalName.substring(dotIndex + 1);\n }\n return canonicalName;\n }\n\n /**\n * Returns this class type without any generic type arguments.\n * @return this class type without any generic type arguments.\n */\n public abstract ModelClass erasure();\n\n /**\n * Since when this class is available. Important for Binding expressions so that we don't\n * call non-existing APIs when setting UI.\n *\n * @return The SDK_INT where this method was added. If it is not a framework method, should\n * return 1.\n */\n public int getMinApi() {\n return SdkUtil.getMinApi(this);\n }\n\n /**\n * Returns the JNI description of the method which can be used to lookup it in SDK.\n * @see TypeUtil\n */\n public abstract String getJniDescription();\n\n /**\n * Returns a list of all abstract methods in the type.\n */\n @NotNull\n public List getAbstractMethods() {\n ArrayList abstractMethods = new ArrayList();\n ModelMethod[] methods = getDeclaredMethods();\n for (ModelMethod method : methods) {\n if (method.isAbstract()) {\n abstractMethods.add(method);\n }\n }\n return abstractMethods;\n }\n\n /**\n * Returns the getter method or field that the name refers to.\n * @param name The name of the field or the body of the method name -- can be name(),\n * getName(), or isName().\n * @param staticOnly Whether this should look for static methods and fields or instance\n * versions\n * @return the getter method or field that the name refers to or null if none can be found.\n */\n public Callable findGetterOrField(String name, boolean staticOnly) {\n if (\"length\".equals(name) && isArray()) {\n return new Callable(Type.FIELD, name, null, ModelAnalyzer.getInstance().loadPrimitive(\"int\"), 0, 0, null);\n }\n String capitalized = StringUtils.capitalize(name);\n String[] methodNames = { \"get\" + capitalized, \"is\" + capitalized, name };\n for (String methodName : methodNames) {\n ModelMethod[] methods = getMethods(methodName, new ArrayList(), staticOnly, false);\n for (ModelMethod method : methods) {\n if (method.isPublic() && (!staticOnly || method.isStatic()) && !method.getReturnType(Arrays.asList(method.getParameterTypes())).isVoid()) {\n int flags = DYNAMIC;\n if (method.isStatic()) {\n flags |= STATIC;\n }\n if (method.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n } else {\n // if method is not bindable, look for a backing field\n final ModelField backingField = getField(name, true, method.isStatic());\n L.d(\"backing field for method %s is %s\", method.getName(), backingField == null ? \"NOT FOUND\" : backingField.getName());\n if (backingField != null && backingField.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n }\n }\n final ModelMethod setterMethod = findSetter(method, name);\n final String setterName = setterMethod == null ? null : setterMethod.getName();\n final Callable result = new Callable(Callable.Type.METHOD, methodName, setterName, method.getReturnType(null), method.getParameterTypes().length, flags, method);\n return result;\n }\n }\n }\n // could not find a method. Look for a public field\n ModelField publicField = null;\n if (staticOnly) {\n publicField = getField(name, false, true);\n } else {\n // first check non-static\n publicField = getField(name, false, false);\n if (publicField == null) {\n publicField = getField(name, false, true);\n }\n }\n if (publicField == null) {\n return null;\n }\n ModelClass fieldType = publicField.getFieldType();\n int flags = 0;\n String setterFieldName = name;\n if (publicField.isStatic()) {\n flags |= STATIC;\n }\n if (!publicField.isFinal()) {\n setterFieldName = null;\n flags |= DYNAMIC;\n }\n if (publicField.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n }\n return new Callable(Callable.Type.FIELD, name, setterFieldName, fieldType, 0, flags, null);\n }\n\n public ModelMethod findInstanceGetter(String name) {\n String capitalized = StringUtils.capitalize(name);\n String[] methodNames = { \"get\" + capitalized, \"is\" + capitalized, name };\n for (String methodName : methodNames) {\n ModelMethod[] methods = getMethods(methodName, new ArrayList(), false, false);\n for (ModelMethod method : methods) {\n if (method.isPublic() && !method.isStatic() && !method.getReturnType(Arrays.asList(method.getParameterTypes())).isVoid()) {\n return method;\n }\n }\n }\n return null;\n }\n\n private ModelField getField(String name, boolean allowPrivate, boolean isStatic) {\n ModelField[] fields = getDeclaredFields();\n for (ModelField field : fields) {\n boolean nameMatch = name.equals(field.getName()) || name.equals(stripFieldName(field.getName()));\n if (nameMatch && field.isStatic() == isStatic && (allowPrivate || field.isPublic())) {\n return field;\n }\n }\n return null;\n }\n\n private ModelMethod findSetter(ModelMethod getter, String originalName) {\n final String capitalized = StringUtils.capitalize(originalName);\n final String[] possibleNames;\n if (originalName.equals(getter.getName())) {\n possibleNames = new String[] { originalName, \"set\" + capitalized };\n } else if (getter.getName().startsWith(\"is\")) {\n possibleNames = new String[] { \"set\" + capitalized, \"setIs\" + capitalized };\n } else {\n possibleNames = new String[] { \"set\" + capitalized };\n }\n for (String name : possibleNames) {\n List methods = findMethods(name, getter.isStatic());\n ModelClass param = getter.getReturnType(null);\n for (ModelMethod method : methods) {\n ModelClass[] parameterTypes = method.getParameterTypes();\n if (parameterTypes != null && parameterTypes.length == 1 && parameterTypes[0].equals(param) && method.isStatic() == getter.isStatic()) {\n return method;\n }\n }\n }\n return", "post_mask_code": "\n }\n\n /**\n * Finds public methods that matches the given name exactly. These may be resolved into\n * listener methods during Expr.resolveListeners.\n */\n @NotNull\n public List findMethods(String name, boolean staticOnly) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if (method.getName().equals(name) && (!staticOnly || method.isStatic()) && method.isPublic()) {\n matching.add(method);\n }\n }\n return matching;\n }\n\n public boolean isIncomplete() {\n if (isTypeVar() || isWildcard()) {\n return true;\n }\n List typeArgs = getTypeArguments();\n if (typeArgs != null) {\n for (ModelClass typeArg : typeArgs) {\n if (typeArg.isIncomplete()) {\n return true;\n }\n }\n }\n return false;\n }\n\n protected abstract ModelField[] getDeclaredFields();\n\n protected abstract ModelMethod[] getDeclaredMethods();\n\n private static String stripFieldName(String fieldName) {\n // TODO: Make this configurable through IntelliJ\n if (fieldName.length() > 2) {\n final char start = fieldName.charAt(2);\n if (fieldName.startsWith(\"m_\") && Character.isJavaIdentifierStart(start)) {\n return Character.toLowerCase(start) + fieldName.substring(3);\n }\n }\n if (fieldName.length() > 1) {\n final char start = fieldName.charAt(1);\n final char fieldIdentifier = fieldName.charAt(0);\n final boolean strip;\n if (fieldIdentifier == '_') {\n strip = true;\n } else if (fieldIdentifier == 'm' && Character.isJavaIdentifierStart(start) && !Character.isLowerCase(start)) {\n strip = true;\n } else {\n // not mUppercase format\n strip = false;\n }\n if (strip) {\n return Character.toLowerCase(start) + fieldName.substring(2);\n }\n }\n return fieldName;\n }\n}\n"} {"task_id": "Java_2184", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/yuchuangu85/Android_Framework_Source/android/databinding/tool/reflection/ModelClass.java", "mask_start_position": 11233, "mask_end_position": 11312, "canonical_solution": "public String getCanonicalName() {\n return erasure().toJavaCode();\n }", "pre_mask_code": "package android.databinding.tool.reflection;\n\nimport android.databinding.tool.reflection.Callable.Type;\nimport android.databinding.tool.util.L;\nimport android.databinding.tool.util.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport static android.databinding.tool.reflection.Callable.CAN_BE_INVALIDATED;\nimport static android.databinding.tool.reflection.Callable.DYNAMIC;\nimport static android.databinding.tool.reflection.Callable.STATIC;\n\npublic abstract class ModelClass {\n\n public abstract String toJavaCode();\n\n /**\n * @return whether this ModelClass represents an array.\n */\n public abstract boolean isArray();\n\n /**\n * For arrays, lists, and maps, this returns the contained value. For other types, null\n * is returned.\n *\n * @return The component type for arrays, the value type for maps, and the element type\n * for lists.\n */\n public abstract ModelClass getComponentType();\n\n /**\n * @return Whether or not this ModelClass can be treated as a List. This means\n * it is a java.util.List, or one of the Sparse*Array classes.\n */\n public boolean isList() {\n for (ModelClass listType : ModelAnalyzer.getInstance().getListTypes()) {\n if (listType != null) {\n if (listType.isAssignableFrom(this)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * @return whether or not this ModelClass can be considered a Map or not.\n */\n public boolean isMap() {\n return ModelAnalyzer.getInstance().getMapType().isAssignableFrom(erasure());\n }\n\n /**\n * @return whether or not this ModelClass is a java.lang.String.\n */\n public boolean isString() {\n return ModelAnalyzer.getInstance().getStringType().equals(this);\n }\n\n /**\n * @return whether or not this ModelClass represents a Reference type.\n */\n public abstract boolean isNullable();\n\n /**\n * @return whether or not this ModelClass represents a primitive type.\n */\n public abstract boolean isPrimitive();\n\n /**\n * @return whether or not this ModelClass represents a Java boolean\n */\n public abstract boolean isBoolean();\n\n /**\n * @return whether or not this ModelClass represents a Java char\n */\n public abstract boolean isChar();\n\n /**\n * @return whether or not this ModelClass represents a Java byte\n */\n public abstract boolean isByte();\n\n /**\n * @return whether or not this ModelClass represents a Java short\n */\n public abstract boolean isShort();\n\n /**\n * @return whether or not this ModelClass represents a Java int\n */\n public abstract boolean isInt();\n\n /**\n * @return whether or not this ModelClass represents a Java long\n */\n public abstract boolean isLong();\n\n /**\n * @return whether or not this ModelClass represents a Java float\n */\n public abstract boolean isFloat();\n\n /**\n * @return whether or not this ModelClass represents a Java double\n */\n public abstract boolean isDouble();\n\n /**\n * @return whether or not this has type parameters\n */\n public abstract boolean isGeneric();\n\n /**\n * @return a list of Generic type paramters for the class. For example, if the class\n * is List<T>, then the return value will be a list containing T. null is returned\n * if this is not a generic type\n */\n public abstract List getTypeArguments();\n\n /**\n * @return whether this is a type variable. For example, in List<T>, T is a type variable.\n * However, List<String>, String is not a type variable.\n */\n public abstract boolean isTypeVar();\n\n /**\n * @return whether this is a wildcard type argument or not.\n */\n public abstract boolean isWildcard();\n\n /**\n * @return whether or not this ModelClass is java.lang.Object and not a primitive or subclass.\n */\n public boolean isObject() {\n return ModelAnalyzer.getInstance().getObjectType().equals(this);\n }\n\n /**\n * @return whether or not this ModelClass is an interface\n */\n public abstract boolean isInterface();\n\n /**\n * @return whether or not his is a ViewDataBinding subclass.\n */\n public boolean isViewDataBinding() {\n return ModelAnalyzer.getInstance().getViewDataBindingType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this ModelClass type extends ViewStub.\n */\n public boolean extendsViewStub() {\n return ModelAnalyzer.getInstance().getViewStubType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this is an Observable type such as ObservableMap, ObservableList,\n * or Observable.\n */\n public boolean isObservable() {\n ModelAnalyzer modelAnalyzer = ModelAnalyzer.getInstance();\n return modelAnalyzer.getObservableType().isAssignableFrom(this) || modelAnalyzer.getObservableListType().isAssignableFrom(this) || modelAnalyzer.getObservableMapType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this is an ObservableField, or any of the primitive versions\n * such as ObservableBoolean and ObservableInt\n */\n public boolean isObservableField() {\n ModelClass erasure = erasure();\n for (ModelClass observableField : ModelAnalyzer.getInstance().getObservableFieldTypes()) {\n if (observableField.isAssignableFrom(erasure)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @return whether or not this ModelClass represents a void\n */\n public abstract boolean isVoid();\n\n /**\n * When this is a boxed type, such as Integer, this will return the unboxed value,\n * such as int. If this is not a boxed type, this is returned.\n *\n * @return The unboxed type of the class that this ModelClass represents or this if it isn't a\n * boxed type.\n */\n public abstract ModelClass unbox();\n\n /**\n * When this is a primitive type, such as boolean, this will return the boxed value,\n * such as Boolean. If this is not a primitive type, this is returned.\n *\n * @return The boxed type of the class that this ModelClass represents or this if it isn't a\n * primitive type.\n */\n public abstract ModelClass box();\n\n /**\n * Returns whether or not the type associated with that can be assigned to\n * the type associated with this ModelClass. If this and that only require boxing or unboxing\n * then true is returned.\n *\n * @param that the ModelClass to compare.\n * @return true if that requires only boxing or if that is an\n * implementation of or subclass of this.\n */\n public abstract boolean isAssignableFrom(ModelClass that);\n\n /**\n * Returns an array containing all public methods (or protected if allowProtected is true)\n * on the type represented by this ModelClass with the name name and can\n * take the passed-in types as arguments. This will also work if the arguments match\n * VarArgs parameter.\n *\n * @param name The name of the method to find.\n * @param args The types that the method should accept.\n * @param staticOnly Whether only static methods should be returned or both instance methods\n * and static methods are valid.\n * @param allowProtected true if the method can be protected as well as public.\n *\n * @return An array containing all public methods with the name name and taking\n * args parameters.\n */\n public ModelMethod[] getMethods(String name, List args, boolean staticOnly, boolean allowProtected) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if ((method.isPublic() || (allowProtected && method.isProtected())) && (!staticOnly || method.isStatic()) && name.equals(method.getName()) && method.acceptsArguments(args)) {\n matching.add(method);\n }\n }\n return matching.toArray(new ModelMethod[matching.size()]);\n }\n\n /**\n * Returns all public instance methods with the given name and number of parameters.\n *\n * @param name The name of the method to find.\n * @param numParameters The number of parameters that the method should take\n * @return An array containing all public methods with the given name and number of parameters.\n */\n public ModelMethod[] getMethods(String name, int numParameters) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if (method.isPublic() && !method.isStatic() && name.equals(method.getName()) && method.getParameterTypes().length == numParameters) {\n matching.add(method);\n }\n }\n return matching.toArray(new ModelMethod[matching.size()]);\n }\n\n /**\n * Returns the public method with the name name with the parameters that\n * best match args. staticOnly governs whether a static or instance method\n * will be returned. If no matching method was found, null is returned.\n *\n * @param name The method name to find\n * @param args The arguments that the method should accept\n * @param staticOnly true if the returned method must be static or false if it does not\n * matter.\n * @param allowProtected true if the method can be protected as well as public.\n */\n public ModelMethod getMethod(String name, List args, boolean staticOnly, boolean allowProtected) {\n ModelMethod[] methods = getMethods(name, args, staticOnly, allowProtected);\n L.d(\"looking methods for %s. static only ? %s . method count: %d\", name, staticOnly, methods.length);\n for (ModelMethod method : methods) {\n L.d(\"method: %s, %s\", method.getName(), method.isStatic());\n }\n if (methods.length == 0) {\n return null;\n }\n ModelMethod bestMethod = methods[0];\n for (int i = 1; i < methods.length; i++) {\n if (methods[i].isBetterArgMatchThan(bestMethod, args)) {\n bestMethod = methods[i];\n }\n }\n return bestMethod;\n }\n\n /**\n * If this represents a class, the super class that it extends is returned. If this\n * represents an interface, the interface that this extends is returned.\n * null is returned if this is not a class or interface, such as an int, or\n * if it is java.lang.Object or an interface that does not extend any other type.\n *\n * @return The class or interface that this ModelClass extends or null.\n */\n public abstract ModelClass getSuperclass();\n\n /**\n * @return A String representation of the class or interface that this represents, not\n * including any type arguments.\n */\n ", "post_mask_code": "\n\n /**\n * @return The class or interface name of this type or the primitive type if it isn't a\n * reference type.\n */\n public String getSimpleName() {\n final String canonicalName = getCanonicalName();\n final int dotIndex = canonicalName.lastIndexOf('.');\n if (dotIndex >= 0) {\n return canonicalName.substring(dotIndex + 1);\n }\n return canonicalName;\n }\n\n /**\n * Returns this class type without any generic type arguments.\n * @return this class type without any generic type arguments.\n */\n public abstract ModelClass erasure();\n\n /**\n * Since when this class is available. Important for Binding expressions so that we don't\n * call non-existing APIs when setting UI.\n *\n * @return The SDK_INT where this method was added. If it is not a framework method, should\n * return 1.\n */\n public int getMinApi() {\n return SdkUtil.getMinApi(this);\n }\n\n /**\n * Returns the JNI description of the method which can be used to lookup it in SDK.\n * @see TypeUtil\n */\n public abstract String getJniDescription();\n\n /**\n * Returns a list of all abstract methods in the type.\n */\n @NotNull\n public List getAbstractMethods() {\n ArrayList abstractMethods = new ArrayList();\n ModelMethod[] methods = getDeclaredMethods();\n for (ModelMethod method : methods) {\n if (method.isAbstract()) {\n abstractMethods.add(method);\n }\n }\n return abstractMethods;\n }\n\n /**\n * Returns the getter method or field that the name refers to.\n * @param name The name of the field or the body of the method name -- can be name(),\n * getName(), or isName().\n * @param staticOnly Whether this should look for static methods and fields or instance\n * versions\n * @return the getter method or field that the name refers to or null if none can be found.\n */\n public Callable findGetterOrField(String name, boolean staticOnly) {\n if (\"length\".equals(name) && isArray()) {\n return new Callable(Type.FIELD, name, null, ModelAnalyzer.getInstance().loadPrimitive(\"int\"), 0, 0, null);\n }\n String capitalized = StringUtils.capitalize(name);\n String[] methodNames = { \"get\" + capitalized, \"is\" + capitalized, name };\n for (String methodName : methodNames) {\n ModelMethod[] methods = getMethods(methodName, new ArrayList(), staticOnly, false);\n for (ModelMethod method : methods) {\n if (method.isPublic() && (!staticOnly || method.isStatic()) && !method.getReturnType(Arrays.asList(method.getParameterTypes())).isVoid()) {\n int flags = DYNAMIC;\n if (method.isStatic()) {\n flags |= STATIC;\n }\n if (method.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n } else {\n // if method is not bindable, look for a backing field\n final ModelField backingField = getField(name, true, method.isStatic());\n L.d(\"backing field for method %s is %s\", method.getName(), backingField == null ? \"NOT FOUND\" : backingField.getName());\n if (backingField != null && backingField.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n }\n }\n final ModelMethod setterMethod = findSetter(method, name);\n final String setterName = setterMethod == null ? null : setterMethod.getName();\n final Callable result = new Callable(Callable.Type.METHOD, methodName, setterName, method.getReturnType(null), method.getParameterTypes().length, flags, method);\n return result;\n }\n }\n }\n // could not find a method. Look for a public field\n ModelField publicField = null;\n if (staticOnly) {\n publicField = getField(name, false, true);\n } else {\n // first check non-static\n publicField = getField(name, false, false);\n if (publicField == null) {\n publicField = getField(name, false, true);\n }\n }\n if (publicField == null) {\n return null;\n }\n ModelClass fieldType = publicField.getFieldType();\n int flags = 0;\n String setterFieldName = name;\n if (publicField.isStatic()) {\n flags |= STATIC;\n }\n if (!publicField.isFinal()) {\n setterFieldName = null;\n flags |= DYNAMIC;\n }\n if (publicField.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n }\n return new Callable(Callable.Type.FIELD, name, setterFieldName, fieldType, 0, flags, null);\n }\n\n public ModelMethod findInstanceGetter(String name) {\n String capitalized = StringUtils.capitalize(name);\n String[] methodNames = { \"get\" + capitalized, \"is\" + capitalized, name };\n for (String methodName : methodNames) {\n ModelMethod[] methods = getMethods(methodName, new ArrayList(), false, false);\n for (ModelMethod method : methods) {\n if (method.isPublic() && !method.isStatic() && !method.getReturnType(Arrays.asList(method.getParameterTypes())).isVoid()) {\n return method;\n }\n }\n }\n return null;\n }\n\n private ModelField getField(String name, boolean allowPrivate, boolean isStatic) {\n ModelField[] fields = getDeclaredFields();\n for (ModelField field : fields) {\n boolean nameMatch = name.equals(field.getName()) || name.equals(stripFieldName(field.getName()));\n if (nameMatch && field.isStatic() == isStatic && (allowPrivate || field.isPublic())) {\n return field;\n }\n }\n return null;\n }\n\n private ModelMethod findSetter(ModelMethod getter, String originalName) {\n final String capitalized = StringUtils.capitalize(originalName);\n final String[] possibleNames;\n if (originalName.equals(getter.getName())) {\n possibleNames = new String[] { originalName, \"set\" + capitalized };\n } else if (getter.getName().startsWith(\"is\")) {\n possibleNames = new String[] { \"set\" + capitalized, \"setIs\" + capitalized };\n } else {\n possibleNames = new String[] { \"set\" + capitalized };\n }\n for (String name : possibleNames) {\n List methods = findMethods(name, getter.isStatic());\n ModelClass param = getter.getReturnType(null);\n for (ModelMethod method : methods) {\n ModelClass[] parameterTypes = method.getParameterTypes();\n if (parameterTypes != null && parameterTypes.length == 1 && parameterTypes[0].equals(param) && method.isStatic() == getter.isStatic()) {\n return method;\n }\n }\n }\n return null;\n }\n\n /**\n * Finds public methods that matches the given name exactly. These may be resolved into\n * listener methods during Expr.resolveListeners.\n */\n @NotNull\n public List findMethods(String name, boolean staticOnly) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if (method.getName().equals(name) && (!staticOnly || method.isStatic()) && method.isPublic()) {\n matching.add(method);\n }\n }\n return matching;\n }\n\n public boolean isIncomplete() {\n if (isTypeVar() || isWildcard()) {\n return true;\n }\n List typeArgs = getTypeArguments();\n if (typeArgs != null) {\n for (ModelClass typeArg : typeArgs) {\n if (typeArg.isIncomplete()) {\n return true;\n }\n }\n }\n return false;\n }\n\n protected abstract ModelField[] getDeclaredFields();\n\n protected abstract ModelMethod[] getDeclaredMethods();\n\n private static String stripFieldName(String fieldName) {\n // TODO: Make this configurable through IntelliJ\n if (fieldName.length() > 2) {\n final char start = fieldName.charAt(2);\n if (fieldName.startsWith(\"m_\") && Character.isJavaIdentifierStart(start)) {\n return Character.toLowerCase(start) + fieldName.substring(3);\n }\n }\n if (fieldName.length() > 1) {\n final char start = fieldName.charAt(1);\n final char fieldIdentifier = fieldName.charAt(0);\n final boolean strip;\n if (fieldIdentifier == '_') {\n strip = true;\n } else if (fieldIdentifier == 'm' && Character.isJavaIdentifierStart(start) && !Character.isLowerCase(start)) {\n strip = true;\n } else {\n // not mUppercase format\n strip = false;\n }\n if (strip) {\n return Character.toLowerCase(start) + fieldName.substring(2);\n }\n }\n return fieldName;\n }\n}\n"} {"task_id": "Java_2185", "language": "Java", "task_type": "for_statement", "source_file": "java/github/yuchuangu85/Android_Framework_Source/android/databinding/tool/reflection/ModelClass.java", "mask_start_position": 10382, "mask_end_position": 10558, "canonical_solution": "for (int i = 1; i < methods.length; i++) {\n if (methods[i].isBetterArgMatchThan(bestMethod, args)) {\n bestMethod = methods[i];\n }\n }", "pre_mask_code": "package android.databinding.tool.reflection;\n\nimport android.databinding.tool.reflection.Callable.Type;\nimport android.databinding.tool.util.L;\nimport android.databinding.tool.util.StringUtils;\nimport org.jetbrains.annotations.NotNull;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport static android.databinding.tool.reflection.Callable.CAN_BE_INVALIDATED;\nimport static android.databinding.tool.reflection.Callable.DYNAMIC;\nimport static android.databinding.tool.reflection.Callable.STATIC;\n\npublic abstract class ModelClass {\n\n public abstract String toJavaCode();\n\n /**\n * @return whether this ModelClass represents an array.\n */\n public abstract boolean isArray();\n\n /**\n * For arrays, lists, and maps, this returns the contained value. For other types, null\n * is returned.\n *\n * @return The component type for arrays, the value type for maps, and the element type\n * for lists.\n */\n public abstract ModelClass getComponentType();\n\n /**\n * @return Whether or not this ModelClass can be treated as a List. This means\n * it is a java.util.List, or one of the Sparse*Array classes.\n */\n public boolean isList() {\n for (ModelClass listType : ModelAnalyzer.getInstance().getListTypes()) {\n if (listType != null) {\n if (listType.isAssignableFrom(this)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * @return whether or not this ModelClass can be considered a Map or not.\n */\n public boolean isMap() {\n return ModelAnalyzer.getInstance().getMapType().isAssignableFrom(erasure());\n }\n\n /**\n * @return whether or not this ModelClass is a java.lang.String.\n */\n public boolean isString() {\n return ModelAnalyzer.getInstance().getStringType().equals(this);\n }\n\n /**\n * @return whether or not this ModelClass represents a Reference type.\n */\n public abstract boolean isNullable();\n\n /**\n * @return whether or not this ModelClass represents a primitive type.\n */\n public abstract boolean isPrimitive();\n\n /**\n * @return whether or not this ModelClass represents a Java boolean\n */\n public abstract boolean isBoolean();\n\n /**\n * @return whether or not this ModelClass represents a Java char\n */\n public abstract boolean isChar();\n\n /**\n * @return whether or not this ModelClass represents a Java byte\n */\n public abstract boolean isByte();\n\n /**\n * @return whether or not this ModelClass represents a Java short\n */\n public abstract boolean isShort();\n\n /**\n * @return whether or not this ModelClass represents a Java int\n */\n public abstract boolean isInt();\n\n /**\n * @return whether or not this ModelClass represents a Java long\n */\n public abstract boolean isLong();\n\n /**\n * @return whether or not this ModelClass represents a Java float\n */\n public abstract boolean isFloat();\n\n /**\n * @return whether or not this ModelClass represents a Java double\n */\n public abstract boolean isDouble();\n\n /**\n * @return whether or not this has type parameters\n */\n public abstract boolean isGeneric();\n\n /**\n * @return a list of Generic type paramters for the class. For example, if the class\n * is List<T>, then the return value will be a list containing T. null is returned\n * if this is not a generic type\n */\n public abstract List getTypeArguments();\n\n /**\n * @return whether this is a type variable. For example, in List<T>, T is a type variable.\n * However, List<String>, String is not a type variable.\n */\n public abstract boolean isTypeVar();\n\n /**\n * @return whether this is a wildcard type argument or not.\n */\n public abstract boolean isWildcard();\n\n /**\n * @return whether or not this ModelClass is java.lang.Object and not a primitive or subclass.\n */\n public boolean isObject() {\n return ModelAnalyzer.getInstance().getObjectType().equals(this);\n }\n\n /**\n * @return whether or not this ModelClass is an interface\n */\n public abstract boolean isInterface();\n\n /**\n * @return whether or not his is a ViewDataBinding subclass.\n */\n public boolean isViewDataBinding() {\n return ModelAnalyzer.getInstance().getViewDataBindingType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this ModelClass type extends ViewStub.\n */\n public boolean extendsViewStub() {\n return ModelAnalyzer.getInstance().getViewStubType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this is an Observable type such as ObservableMap, ObservableList,\n * or Observable.\n */\n public boolean isObservable() {\n ModelAnalyzer modelAnalyzer = ModelAnalyzer.getInstance();\n return modelAnalyzer.getObservableType().isAssignableFrom(this) || modelAnalyzer.getObservableListType().isAssignableFrom(this) || modelAnalyzer.getObservableMapType().isAssignableFrom(this);\n }\n\n /**\n * @return whether or not this is an ObservableField, or any of the primitive versions\n * such as ObservableBoolean and ObservableInt\n */\n public boolean isObservableField() {\n ModelClass erasure = erasure();\n for (ModelClass observableField : ModelAnalyzer.getInstance().getObservableFieldTypes()) {\n if (observableField.isAssignableFrom(erasure)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @return whether or not this ModelClass represents a void\n */\n public abstract boolean isVoid();\n\n /**\n * When this is a boxed type, such as Integer, this will return the unboxed value,\n * such as int. If this is not a boxed type, this is returned.\n *\n * @return The unboxed type of the class that this ModelClass represents or this if it isn't a\n * boxed type.\n */\n public abstract ModelClass unbox();\n\n /**\n * When this is a primitive type, such as boolean, this will return the boxed value,\n * such as Boolean. If this is not a primitive type, this is returned.\n *\n * @return The boxed type of the class that this ModelClass represents or this if it isn't a\n * primitive type.\n */\n public abstract ModelClass box();\n\n /**\n * Returns whether or not the type associated with that can be assigned to\n * the type associated with this ModelClass. If this and that only require boxing or unboxing\n * then true is returned.\n *\n * @param that the ModelClass to compare.\n * @return true if that requires only boxing or if that is an\n * implementation of or subclass of this.\n */\n public abstract boolean isAssignableFrom(ModelClass that);\n\n /**\n * Returns an array containing all public methods (or protected if allowProtected is true)\n * on the type represented by this ModelClass with the name name and can\n * take the passed-in types as arguments. This will also work if the arguments match\n * VarArgs parameter.\n *\n * @param name The name of the method to find.\n * @param args The types that the method should accept.\n * @param staticOnly Whether only static methods should be returned or both instance methods\n * and static methods are valid.\n * @param allowProtected true if the method can be protected as well as public.\n *\n * @return An array containing all public methods with the name name and taking\n * args parameters.\n */\n public ModelMethod[] getMethods(String name, List args, boolean staticOnly, boolean allowProtected) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if ((method.isPublic() || (allowProtected && method.isProtected())) && (!staticOnly || method.isStatic()) && name.equals(method.getName()) && method.acceptsArguments(args)) {\n matching.add(method);\n }\n }\n return matching.toArray(new ModelMethod[matching.size()]);\n }\n\n /**\n * Returns all public instance methods with the given name and number of parameters.\n *\n * @param name The name of the method to find.\n * @param numParameters The number of parameters that the method should take\n * @return An array containing all public methods with the given name and number of parameters.\n */\n public ModelMethod[] getMethods(String name, int numParameters) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if (method.isPublic() && !method.isStatic() && name.equals(method.getName()) && method.getParameterTypes().length == numParameters) {\n matching.add(method);\n }\n }\n return matching.toArray(new ModelMethod[matching.size()]);\n }\n\n /**\n * Returns the public method with the name name with the parameters that\n * best match args. staticOnly governs whether a static or instance method\n * will be returned. If no matching method was found, null is returned.\n *\n * @param name The method name to find\n * @param args The arguments that the method should accept\n * @param staticOnly true if the returned method must be static or false if it does not\n * matter.\n * @param allowProtected true if the method can be protected as well as public.\n */\n public ModelMethod getMethod(String name, List args, boolean staticOnly, boolean allowProtected) {\n ModelMethod[] methods = getMethods(name, args, staticOnly, allowProtected);\n L.d(\"looking methods for %s. static only ? %s . method count: %d\", name, staticOnly, methods.length);\n for (ModelMethod method : methods) {\n L.d(\"method: %s, %s\", method.getName(), method.isStatic());\n }\n if (methods.length == 0) {\n return null;\n }\n ModelMethod bestMethod = methods[0];\n ", "post_mask_code": "\n return bestMethod;\n }\n\n /**\n * If this represents a class, the super class that it extends is returned. If this\n * represents an interface, the interface that this extends is returned.\n * null is returned if this is not a class or interface, such as an int, or\n * if it is java.lang.Object or an interface that does not extend any other type.\n *\n * @return The class or interface that this ModelClass extends or null.\n */\n public abstract ModelClass getSuperclass();\n\n /**\n * @return A String representation of the class or interface that this represents, not\n * including any type arguments.\n */\n public String getCanonicalName() {\n return erasure().toJavaCode();\n }\n\n /**\n * @return The class or interface name of this type or the primitive type if it isn't a\n * reference type.\n */\n public String getSimpleName() {\n final String canonicalName = getCanonicalName();\n final int dotIndex = canonicalName.lastIndexOf('.');\n if (dotIndex >= 0) {\n return canonicalName.substring(dotIndex + 1);\n }\n return canonicalName;\n }\n\n /**\n * Returns this class type without any generic type arguments.\n * @return this class type without any generic type arguments.\n */\n public abstract ModelClass erasure();\n\n /**\n * Since when this class is available. Important for Binding expressions so that we don't\n * call non-existing APIs when setting UI.\n *\n * @return The SDK_INT where this method was added. If it is not a framework method, should\n * return 1.\n */\n public int getMinApi() {\n return SdkUtil.getMinApi(this);\n }\n\n /**\n * Returns the JNI description of the method which can be used to lookup it in SDK.\n * @see TypeUtil\n */\n public abstract String getJniDescription();\n\n /**\n * Returns a list of all abstract methods in the type.\n */\n @NotNull\n public List getAbstractMethods() {\n ArrayList abstractMethods = new ArrayList();\n ModelMethod[] methods = getDeclaredMethods();\n for (ModelMethod method : methods) {\n if (method.isAbstract()) {\n abstractMethods.add(method);\n }\n }\n return abstractMethods;\n }\n\n /**\n * Returns the getter method or field that the name refers to.\n * @param name The name of the field or the body of the method name -- can be name(),\n * getName(), or isName().\n * @param staticOnly Whether this should look for static methods and fields or instance\n * versions\n * @return the getter method or field that the name refers to or null if none can be found.\n */\n public Callable findGetterOrField(String name, boolean staticOnly) {\n if (\"length\".equals(name) && isArray()) {\n return new Callable(Type.FIELD, name, null, ModelAnalyzer.getInstance().loadPrimitive(\"int\"), 0, 0, null);\n }\n String capitalized = StringUtils.capitalize(name);\n String[] methodNames = { \"get\" + capitalized, \"is\" + capitalized, name };\n for (String methodName : methodNames) {\n ModelMethod[] methods = getMethods(methodName, new ArrayList(), staticOnly, false);\n for (ModelMethod method : methods) {\n if (method.isPublic() && (!staticOnly || method.isStatic()) && !method.getReturnType(Arrays.asList(method.getParameterTypes())).isVoid()) {\n int flags = DYNAMIC;\n if (method.isStatic()) {\n flags |= STATIC;\n }\n if (method.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n } else {\n // if method is not bindable, look for a backing field\n final ModelField backingField = getField(name, true, method.isStatic());\n L.d(\"backing field for method %s is %s\", method.getName(), backingField == null ? \"NOT FOUND\" : backingField.getName());\n if (backingField != null && backingField.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n }\n }\n final ModelMethod setterMethod = findSetter(method, name);\n final String setterName = setterMethod == null ? null : setterMethod.getName();\n final Callable result = new Callable(Callable.Type.METHOD, methodName, setterName, method.getReturnType(null), method.getParameterTypes().length, flags, method);\n return result;\n }\n }\n }\n // could not find a method. Look for a public field\n ModelField publicField = null;\n if (staticOnly) {\n publicField = getField(name, false, true);\n } else {\n // first check non-static\n publicField = getField(name, false, false);\n if (publicField == null) {\n publicField = getField(name, false, true);\n }\n }\n if (publicField == null) {\n return null;\n }\n ModelClass fieldType = publicField.getFieldType();\n int flags = 0;\n String setterFieldName = name;\n if (publicField.isStatic()) {\n flags |= STATIC;\n }\n if (!publicField.isFinal()) {\n setterFieldName = null;\n flags |= DYNAMIC;\n }\n if (publicField.isBindable()) {\n flags |= CAN_BE_INVALIDATED;\n }\n return new Callable(Callable.Type.FIELD, name, setterFieldName, fieldType, 0, flags, null);\n }\n\n public ModelMethod findInstanceGetter(String name) {\n String capitalized = StringUtils.capitalize(name);\n String[] methodNames = { \"get\" + capitalized, \"is\" + capitalized, name };\n for (String methodName : methodNames) {\n ModelMethod[] methods = getMethods(methodName, new ArrayList(), false, false);\n for (ModelMethod method : methods) {\n if (method.isPublic() && !method.isStatic() && !method.getReturnType(Arrays.asList(method.getParameterTypes())).isVoid()) {\n return method;\n }\n }\n }\n return null;\n }\n\n private ModelField getField(String name, boolean allowPrivate, boolean isStatic) {\n ModelField[] fields = getDeclaredFields();\n for (ModelField field : fields) {\n boolean nameMatch = name.equals(field.getName()) || name.equals(stripFieldName(field.getName()));\n if (nameMatch && field.isStatic() == isStatic && (allowPrivate || field.isPublic())) {\n return field;\n }\n }\n return null;\n }\n\n private ModelMethod findSetter(ModelMethod getter, String originalName) {\n final String capitalized = StringUtils.capitalize(originalName);\n final String[] possibleNames;\n if (originalName.equals(getter.getName())) {\n possibleNames = new String[] { originalName, \"set\" + capitalized };\n } else if (getter.getName().startsWith(\"is\")) {\n possibleNames = new String[] { \"set\" + capitalized, \"setIs\" + capitalized };\n } else {\n possibleNames = new String[] { \"set\" + capitalized };\n }\n for (String name : possibleNames) {\n List methods = findMethods(name, getter.isStatic());\n ModelClass param = getter.getReturnType(null);\n for (ModelMethod method : methods) {\n ModelClass[] parameterTypes = method.getParameterTypes();\n if (parameterTypes != null && parameterTypes.length == 1 && parameterTypes[0].equals(param) && method.isStatic() == getter.isStatic()) {\n return method;\n }\n }\n }\n return null;\n }\n\n /**\n * Finds public methods that matches the given name exactly. These may be resolved into\n * listener methods during Expr.resolveListeners.\n */\n @NotNull\n public List findMethods(String name, boolean staticOnly) {\n ModelMethod[] methods = getDeclaredMethods();\n ArrayList matching = new ArrayList();\n for (ModelMethod method : methods) {\n if (method.getName().equals(name) && (!staticOnly || method.isStatic()) && method.isPublic()) {\n matching.add(method);\n }\n }\n return matching;\n }\n\n public boolean isIncomplete() {\n if (isTypeVar() || isWildcard()) {\n return true;\n }\n List typeArgs = getTypeArguments();\n if (typeArgs != null) {\n for (ModelClass typeArg : typeArgs) {\n if (typeArg.isIncomplete()) {\n return true;\n }\n }\n }\n return false;\n }\n\n protected abstract ModelField[] getDeclaredFields();\n\n protected abstract ModelMethod[] getDeclaredMethods();\n\n private static String stripFieldName(String fieldName) {\n // TODO: Make this configurable through IntelliJ\n if (fieldName.length() > 2) {\n final char start = fieldName.charAt(2);\n if (fieldName.startsWith(\"m_\") && Character.isJavaIdentifierStart(start)) {\n return Character.toLowerCase(start) + fieldName.substring(3);\n }\n }\n if (fieldName.length() > 1) {\n final char start = fieldName.charAt(1);\n final char fieldIdentifier = fieldName.charAt(0);\n final boolean strip;\n if (fieldIdentifier == '_') {\n strip = true;\n } else if (fieldIdentifier == 'm' && Character.isJavaIdentifierStart(start) && !Character.isLowerCase(start)) {\n strip = true;\n } else {\n // not mUppercase format\n strip = false;\n }\n if (strip) {\n return Character.toLowerCase(start) + fieldName.substring(2);\n }\n }\n return fieldName;\n }\n}\n"} {"task_id": "Java_2186", "language": "Java", "task_type": "method_signature", "source_file": "java/github/algorithmfoundry/Foundry/Components/CommonCore/Test/gov/sandia/cognition/evaluator/ValueClamperTest.java", "mask_start_position": 1599, "mask_end_position": 1626, "canonical_solution": "public void testEvaluate() ", "pre_mask_code": "/*\n * File: ValueClamperTest.java\n * Authors: Justin Basilico\n * Company: Sandia National Laboratories\n * Project: Cognitive Foundry\n * \n * See CopyrightHistory.txt for complete details.\n * \n */\npackage gov.sandia.cognition.evaluator;\n\nimport junit.framework.TestCase;\n\n/**\n * Tests of ValueClamper\n * @author Justin Basilico\n * @since 3.0\n */\npublic class ValueClamperTest extends TestCase {\n\n /**\n * Creates a new test.\n *\n * @param testName The test name.\n */\n public ValueClamperTest(String testName) {\n super(testName);\n }\n\n /**\n * Test of constructors of class ValueClamper.\n */\n public void testConstructors() {\n Double minimum = null;\n Double maximum = null;\n ValueClamper instance = new ValueClamper();\n assertSame(minimum, instance.getMinimum());\n assertSame(maximum, instance.getMaximum());\n minimum = 10.01;\n maximum = 20.02;\n instance = new ValueClamper(minimum, maximum);\n assertSame(minimum, instance.getMinimum());\n assertSame(maximum, instance.getMaximum());\n }\n\n public void testClone() {\n System.out.println(\"Clone\");\n Double minimum = 10.0;\n Double maximum = 20.0;\n ValueClamper instance = new ValueClamper(minimum, maximum);\n ValueClamper clone = instance.clone();\n assertNotNull(clone);\n assertNotSame(instance, clone);\n }\n\n /**\n * Test of evaluate method, of class ValueClamper.\n */\n ", "post_mask_code": "{\n Double minimum = 10.01;\n Double maximum = 20.02;\n Double input = 0.0;\n ValueClamper instance = new ValueClamper(minimum, maximum);\n assertNull(instance.evaluate(null));\n input = 15.51;\n assertSame(input, instance.evaluate(input));\n input = 10.00;\n assertSame(minimum, instance.evaluate(input));\n input = 20.03;\n assertSame(maximum, instance.evaluate(input));\n input = 0.0;\n instance.setMinimum(null);\n assertSame(input, instance.evaluate(input));\n input = 40.00;\n instance.setMaximum(null);\n assertSame(input, instance.evaluate(input));\n }\n\n /**\n * Test of getMinimum method, of class ValueClamper.\n */\n public void testGetMinimum() {\n this.testSetMinimum();\n }\n\n /**\n * Test of setMinimum method, of class ValueClamper.\n */\n public void testSetMinimum() {\n Double minimum = null;\n ValueClamper instance = new ValueClamper();\n assertSame(minimum, instance.getMinimum());\n minimum = 20.08;\n instance.setMinimum(minimum);\n assertSame(minimum, instance.getMinimum());\n minimum = 10.03;\n instance.setMinimum(minimum);\n assertSame(minimum, instance.getMinimum());\n minimum = null;\n instance.setMinimum(minimum);\n assertSame(minimum, instance.getMinimum());\n }\n\n /**\n * Test of getMaximum method, of class ValueClamper.\n */\n public void testGetMaximum() {\n this.testSetMaximum();\n }\n\n /**\n * Test of setMaximum method, of class ValueClamper.\n */\n public void testSetMaximum() {\n Double maximum = null;\n ValueClamper instance = new ValueClamper();\n assertSame(maximum, instance.getMaximum());\n maximum = 20.08;\n instance.setMaximum(maximum);\n assertSame(maximum, instance.getMaximum());\n maximum = 10.03;\n instance.setMaximum(maximum);\n assertSame(maximum, instance.getMaximum());\n maximum = null;\n instance.setMaximum(maximum);\n assertSame(maximum, instance.getMaximum());\n }\n}\n"} {"task_id": "Java_2187", "language": "Java", "task_type": "method_body", "source_file": "java/github/algorithmfoundry/Foundry/Components/CommonCore/Test/gov/sandia/cognition/evaluator/ValueClamperTest.java", "mask_start_position": 2414, "mask_end_position": 2452, "canonical_solution": "{\n this.testSetMinimum();\n }", "pre_mask_code": "/*\n * File: ValueClamperTest.java\n * Authors: Justin Basilico\n * Company: Sandia National Laboratories\n * Project: Cognitive Foundry\n * \n * See CopyrightHistory.txt for complete details.\n * \n */\npackage gov.sandia.cognition.evaluator;\n\nimport junit.framework.TestCase;\n\n/**\n * Tests of ValueClamper\n * @author Justin Basilico\n * @since 3.0\n */\npublic class ValueClamperTest extends TestCase {\n\n /**\n * Creates a new test.\n *\n * @param testName The test name.\n */\n public ValueClamperTest(String testName) {\n super(testName);\n }\n\n /**\n * Test of constructors of class ValueClamper.\n */\n public void testConstructors() {\n Double minimum = null;\n Double maximum = null;\n ValueClamper instance = new ValueClamper();\n assertSame(minimum, instance.getMinimum());\n assertSame(maximum, instance.getMaximum());\n minimum = 10.01;\n maximum = 20.02;\n instance = new ValueClamper(minimum, maximum);\n assertSame(minimum, instance.getMinimum());\n assertSame(maximum, instance.getMaximum());\n }\n\n public void testClone() {\n System.out.println(\"Clone\");\n Double minimum = 10.0;\n Double maximum = 20.0;\n ValueClamper instance = new ValueClamper(minimum, maximum);\n ValueClamper clone = instance.clone();\n assertNotNull(clone);\n assertNotSame(instance, clone);\n }\n\n /**\n * Test of evaluate method, of class ValueClamper.\n */\n public void testEvaluate() {\n Double minimum = 10.01;\n Double maximum = 20.02;\n Double input = 0.0;\n ValueClamper instance = new ValueClamper(minimum, maximum);\n assertNull(instance.evaluate(null));\n input = 15.51;\n assertSame(input, instance.evaluate(input));\n input = 10.00;\n assertSame(minimum, instance.evaluate(input));\n input = 20.03;\n assertSame(maximum, instance.evaluate(input));\n input = 0.0;\n instance.setMinimum(null);\n assertSame(input, instance.evaluate(input));\n input = 40.00;\n instance.setMaximum(null);\n assertSame(input, instance.evaluate(input));\n }\n\n /**\n * Test of getMinimum method, of class ValueClamper.\n */\n public void testGetMinimum() ", "post_mask_code": "\n\n /**\n * Test of setMinimum method, of class ValueClamper.\n */\n public void testSetMinimum() {\n Double minimum = null;\n ValueClamper instance = new ValueClamper();\n assertSame(minimum, instance.getMinimum());\n minimum = 20.08;\n instance.setMinimum(minimum);\n assertSame(minimum, instance.getMinimum());\n minimum = 10.03;\n instance.setMinimum(minimum);\n assertSame(minimum, instance.getMinimum());\n minimum = null;\n instance.setMinimum(minimum);\n assertSame(minimum, instance.getMinimum());\n }\n\n /**\n * Test of getMaximum method, of class ValueClamper.\n */\n public void testGetMaximum() {\n this.testSetMaximum();\n }\n\n /**\n * Test of setMaximum method, of class ValueClamper.\n */\n public void testSetMaximum() {\n Double maximum = null;\n ValueClamper instance = new ValueClamper();\n assertSame(maximum, instance.getMaximum());\n maximum = 20.08;\n instance.setMaximum(maximum);\n assertSame(maximum, instance.getMaximum());\n maximum = 10.03;\n instance.setMaximum(maximum);\n assertSame(maximum, instance.getMaximum());\n maximum = null;\n instance.setMaximum(maximum);\n assertSame(maximum, instance.getMaximum());\n }\n}\n"} {"task_id": "Java_2188", "language": "Java", "task_type": "single_line", "source_file": "java/github/algorithmfoundry/Foundry/Components/CommonCore/Test/gov/sandia/cognition/evaluator/ValueClamperTest.java", "mask_start_position": 1294, "mask_end_position": 1307, "canonical_solution": "ximum = 20.0;", "pre_mask_code": "/*\n * File: ValueClamperTest.java\n * Authors: Justin Basilico\n * Company: Sandia National Laboratories\n * Project: Cognitive Foundry\n * \n * See CopyrightHistory.txt for complete details.\n * \n */\npackage gov.sandia.cognition.evaluator;\n\nimport junit.framework.TestCase;\n\n/**\n * Tests of ValueClamper\n * @author Justin Basilico\n * @since 3.0\n */\npublic class ValueClamperTest extends TestCase {\n\n /**\n * Creates a new test.\n *\n * @param testName The test name.\n */\n public ValueClamperTest(String testName) {\n super(testName);\n }\n\n /**\n * Test of constructors of class ValueClamper.\n */\n public void testConstructors() {\n Double minimum = null;\n Double maximum = null;\n ValueClamper instance = new ValueClamper();\n assertSame(minimum, instance.getMinimum());\n assertSame(maximum, instance.getMaximum());\n minimum = 10.01;\n maximum = 20.02;\n instance = new ValueClamper(minimum, maximum);\n assertSame(minimum, instance.getMinimum());\n assertSame(maximum, instance.getMaximum());\n }\n\n public void testClone() {\n System.out.println(\"Clone\");\n Double minimum = 10.0;\n Double ma", "post_mask_code": "\n ValueClamper instance = new ValueClamper(minimum, maximum);\n ValueClamper clone = instance.clone();\n assertNotNull(clone);\n assertNotSame(instance, clone);\n }\n\n /**\n * Test of evaluate method, of class ValueClamper.\n */\n public void testEvaluate() {\n Double minimum = 10.01;\n Double maximum = 20.02;\n Double input = 0.0;\n ValueClamper instance = new ValueClamper(minimum, maximum);\n assertNull(instance.evaluate(null));\n input = 15.51;\n assertSame(input, instance.evaluate(input));\n input = 10.00;\n assertSame(minimum, instance.evaluate(input));\n input = 20.03;\n assertSame(maximum, instance.evaluate(input));\n input = 0.0;\n instance.setMinimum(null);\n assertSame(input, instance.evaluate(input));\n input = 40.00;\n instance.setMaximum(null);\n assertSame(input, instance.evaluate(input));\n }\n\n /**\n * Test of getMinimum method, of class ValueClamper.\n */\n public void testGetMinimum() {\n this.testSetMinimum();\n }\n\n /**\n * Test of setMinimum method, of class ValueClamper.\n */\n public void testSetMinimum() {\n Double minimum = null;\n ValueClamper instance = new ValueClamper();\n assertSame(minimum, instance.getMinimum());\n minimum = 20.08;\n instance.setMinimum(minimum);\n assertSame(minimum, instance.getMinimum());\n minimum = 10.03;\n instance.setMinimum(minimum);\n assertSame(minimum, instance.getMinimum());\n minimum = null;\n instance.setMinimum(minimum);\n assertSame(minimum, instance.getMinimum());\n }\n\n /**\n * Test of getMaximum method, of class ValueClamper.\n */\n public void testGetMaximum() {\n this.testSetMaximum();\n }\n\n /**\n * Test of setMaximum method, of class ValueClamper.\n */\n public void testSetMaximum() {\n Double maximum = null;\n ValueClamper instance = new ValueClamper();\n assertSame(maximum, instance.getMaximum());\n maximum = 20.08;\n instance.setMaximum(maximum);\n assertSame(maximum, instance.getMaximum());\n maximum = 10.03;\n instance.setMaximum(maximum);\n assertSame(maximum, instance.getMaximum());\n maximum = null;\n instance.setMaximum(maximum);\n assertSame(maximum, instance.getMaximum());\n }\n}\n"} {"task_id": "Java_2189", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/algorithmfoundry/Foundry/Components/CommonCore/Test/gov/sandia/cognition/evaluator/ValueClamperTest.java", "mask_start_position": 688, "mask_end_position": 1177, "canonical_solution": "public void testConstructors() {\n Double minimum = null;\n Double maximum = null;\n ValueClamper instance = new ValueClamper();\n assertSame(minimum, instance.getMinimum());\n assertSame(maximum, instance.getMaximum());\n minimum = 10.01;\n maximum = 20.02;\n instance = new ValueClamper(minimum, maximum);\n assertSame(minimum, instance.getMinimum());\n assertSame(maximum, instance.getMaximum());\n }", "pre_mask_code": "/*\n * File: ValueClamperTest.java\n * Authors: Justin Basilico\n * Company: Sandia National Laboratories\n * Project: Cognitive Foundry\n * \n * See CopyrightHistory.txt for complete details.\n * \n */\npackage gov.sandia.cognition.evaluator;\n\nimport junit.framework.TestCase;\n\n/**\n * Tests of ValueClamper\n * @author Justin Basilico\n * @since 3.0\n */\npublic class ValueClamperTest extends TestCase {\n\n /**\n * Creates a new test.\n *\n * @param testName The test name.\n */\n public ValueClamperTest(String testName) {\n super(testName);\n }\n\n /**\n * Test of constructors of class ValueClamper.\n */\n ", "post_mask_code": "\n\n public void testClone() {\n System.out.println(\"Clone\");\n Double minimum = 10.0;\n Double maximum = 20.0;\n ValueClamper instance = new ValueClamper(minimum, maximum);\n ValueClamper clone = instance.clone();\n assertNotNull(clone);\n assertNotSame(instance, clone);\n }\n\n /**\n * Test of evaluate method, of class ValueClamper.\n */\n public void testEvaluate() {\n Double minimum = 10.01;\n Double maximum = 20.02;\n Double input = 0.0;\n ValueClamper instance = new ValueClamper(minimum, maximum);\n assertNull(instance.evaluate(null));\n input = 15.51;\n assertSame(input, instance.evaluate(input));\n input = 10.00;\n assertSame(minimum, instance.evaluate(input));\n input = 20.03;\n assertSame(maximum, instance.evaluate(input));\n input = 0.0;\n instance.setMinimum(null);\n assertSame(input, instance.evaluate(input));\n input = 40.00;\n instance.setMaximum(null);\n assertSame(input, instance.evaluate(input));\n }\n\n /**\n * Test of getMinimum method, of class ValueClamper.\n */\n public void testGetMinimum() {\n this.testSetMinimum();\n }\n\n /**\n * Test of setMinimum method, of class ValueClamper.\n */\n public void testSetMinimum() {\n Double minimum = null;\n ValueClamper instance = new ValueClamper();\n assertSame(minimum, instance.getMinimum());\n minimum = 20.08;\n instance.setMinimum(minimum);\n assertSame(minimum, instance.getMinimum());\n minimum = 10.03;\n instance.setMinimum(minimum);\n assertSame(minimum, instance.getMinimum());\n minimum = null;\n instance.setMinimum(minimum);\n assertSame(minimum, instance.getMinimum());\n }\n\n /**\n * Test of getMaximum method, of class ValueClamper.\n */\n public void testGetMaximum() {\n this.testSetMaximum();\n }\n\n /**\n * Test of setMaximum method, of class ValueClamper.\n */\n public void testSetMaximum() {\n Double maximum = null;\n ValueClamper instance = new ValueClamper();\n assertSame(maximum, instance.getMaximum());\n maximum = 20.08;\n instance.setMaximum(maximum);\n assertSame(maximum, instance.getMaximum());\n maximum = 10.03;\n instance.setMaximum(maximum);\n assertSame(maximum, instance.getMaximum());\n maximum = null;\n instance.setMaximum(maximum);\n assertSame(maximum, instance.getMaximum());\n }\n}\n"} {"task_id": "Java_2190", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/lucene/lucene/core/src/java/org/apache/lucene/util/CharsRefBuilder.java", "mask_start_position": 3391, "mask_end_position": 3413, "canonical_solution": "public CharsRef get() ", "pre_mask_code": "package org.apache.lucene.util;\n\n/**\n * A builder for {@link CharsRef} instances.\n *\n * @lucene.internal\n */\npublic class CharsRefBuilder implements Appendable {\n\n private static final String NULL_STRING = \"null\";\n\n private final CharsRef ref;\n\n public CharsRefBuilder() {\n ref = new CharsRef();\n }\n\n /**\n * Return a reference to the chars of this builder.\n */\n public char[] chars() {\n return ref.chars;\n }\n\n /**\n * Return the number of chars in this buffer.\n */\n public int length() {\n return ref.length;\n }\n\n /**\n * Set the length.\n */\n public void setLength(int length) {\n this.ref.length = length;\n }\n\n /**\n * Return the char at the given offset.\n */\n public char charAt(int offset) {\n return ref.chars[offset];\n }\n\n public void setCharAt(int offset, char b) {\n ref.chars[offset] = b;\n }\n\n /**\n * Reset this builder to the empty state.\n */\n public void clear() {\n ref.length = 0;\n }\n\n @Override\n public CharsRefBuilder append(CharSequence csq) {\n if (csq == null) {\n return append(NULL_STRING);\n }\n return append(csq, 0, csq.length());\n }\n\n @Override\n public CharsRefBuilder append(CharSequence csq, int start, int end) {\n if (csq == null) {\n return append(NULL_STRING);\n }\n grow(ref.length + end - start);\n for (int i = start; i < end; ++i) {\n setCharAt(ref.length++, csq.charAt(i));\n }\n return this;\n }\n\n @Override\n public CharsRefBuilder append(char c) {\n grow(ref.length + 1);\n setCharAt(ref.length++, c);\n return this;\n }\n\n /**\n * Copies the given {@link CharsRef} referenced content into this instance.\n */\n public void copyChars(CharsRef other) {\n copyChars(other.chars, other.offset, other.length);\n }\n\n /**\n * Used to grow the reference array.\n */\n public void grow(int newLength) {\n ref.chars = ArrayUtil.grow(ref.chars, newLength);\n }\n\n /**\n * Copy the provided bytes, interpreted as UTF-8 bytes.\n */\n public void copyUTF8Bytes(byte[] bytes, int offset, int length) {\n grow(length);\n ref.length = UnicodeUtil.UTF8toUTF16(bytes, offset, length, ref.chars);\n }\n\n /**\n * Copy the provided bytes, interpreted as UTF-8 bytes.\n */\n public void copyUTF8Bytes(BytesRef bytes) {\n copyUTF8Bytes(bytes.bytes, bytes.offset, bytes.length);\n }\n\n /**\n * Copies the given array into this instance.\n */\n public void copyChars(char[] otherChars, int otherOffset, int otherLength) {\n grow(otherLength);\n System.arraycopy(otherChars, otherOffset, ref.chars, 0, otherLength);\n ref.length = otherLength;\n }\n\n /**\n * Appends the given array to this CharsRef\n */\n public void append(char[] otherChars, int otherOffset, int otherLength) {\n int newLen = ref.length + otherLength;\n grow(newLen);\n System.arraycopy(otherChars, otherOffset, ref.chars, ref.length, otherLength);\n ref.length = newLen;\n }\n\n /**\n * Return a {@link CharsRef} that points to the internal content of this builder. Any update to\n * the content of this builder might invalidate the provided ref and vice-versa.\n */\n ", "post_mask_code": "{\n assert ref.offset == 0 : \"Modifying the offset of the returned ref is illegal\";\n return ref;\n }\n\n /**\n * Build a new {@link CharsRef} that has the same content as this builder.\n */\n public CharsRef toCharsRef() {\n return new CharsRef(ArrayUtil.copyOfSubArray(ref.chars, 0, ref.length), 0, ref.length);\n }\n\n @Override\n public String toString() {\n return get().toString();\n }\n\n @Override\n public boolean equals(Object obj) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int hashCode() {\n throw new UnsupportedOperationException();\n }\n}\n"} {"task_id": "Java_2191", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/lucene/lucene/core/src/java/org/apache/lucene/util/CharsRefBuilder.java", "mask_start_position": 1324, "mask_end_position": 1575, "canonical_solution": "{\n if (csq == null) {\n return append(NULL_STRING);\n }\n grow(ref.length + end - start);\n for (int i = start; i < end; ++i) {\n setCharAt(ref.length++, csq.charAt(i));\n }\n return this;\n }", "pre_mask_code": "package org.apache.lucene.util;\n\n/**\n * A builder for {@link CharsRef} instances.\n *\n * @lucene.internal\n */\npublic class CharsRefBuilder implements Appendable {\n\n private static final String NULL_STRING = \"null\";\n\n private final CharsRef ref;\n\n public CharsRefBuilder() {\n ref = new CharsRef();\n }\n\n /**\n * Return a reference to the chars of this builder.\n */\n public char[] chars() {\n return ref.chars;\n }\n\n /**\n * Return the number of chars in this buffer.\n */\n public int length() {\n return ref.length;\n }\n\n /**\n * Set the length.\n */\n public void setLength(int length) {\n this.ref.length = length;\n }\n\n /**\n * Return the char at the given offset.\n */\n public char charAt(int offset) {\n return ref.chars[offset];\n }\n\n public void setCharAt(int offset, char b) {\n ref.chars[offset] = b;\n }\n\n /**\n * Reset this builder to the empty state.\n */\n public void clear() {\n ref.length = 0;\n }\n\n @Override\n public CharsRefBuilder append(CharSequence csq) {\n if (csq == null) {\n return append(NULL_STRING);\n }\n return append(csq, 0, csq.length());\n }\n\n @Override\n public CharsRefBuilder append(CharSequence csq, int start, int end) ", "post_mask_code": "\n\n @Override\n public CharsRefBuilder append(char c) {\n grow(ref.length + 1);\n setCharAt(ref.length++, c);\n return this;\n }\n\n /**\n * Copies the given {@link CharsRef} referenced content into this instance.\n */\n public void copyChars(CharsRef other) {\n copyChars(other.chars, other.offset, other.length);\n }\n\n /**\n * Used to grow the reference array.\n */\n public void grow(int newLength) {\n ref.chars = ArrayUtil.grow(ref.chars, newLength);\n }\n\n /**\n * Copy the provided bytes, interpreted as UTF-8 bytes.\n */\n public void copyUTF8Bytes(byte[] bytes, int offset, int length) {\n grow(length);\n ref.length = UnicodeUtil.UTF8toUTF16(bytes, offset, length, ref.chars);\n }\n\n /**\n * Copy the provided bytes, interpreted as UTF-8 bytes.\n */\n public void copyUTF8Bytes(BytesRef bytes) {\n copyUTF8Bytes(bytes.bytes, bytes.offset, bytes.length);\n }\n\n /**\n * Copies the given array into this instance.\n */\n public void copyChars(char[] otherChars, int otherOffset, int otherLength) {\n grow(otherLength);\n System.arraycopy(otherChars, otherOffset, ref.chars, 0, otherLength);\n ref.length = otherLength;\n }\n\n /**\n * Appends the given array to this CharsRef\n */\n public void append(char[] otherChars, int otherOffset, int otherLength) {\n int newLen = ref.length + otherLength;\n grow(newLen);\n System.arraycopy(otherChars, otherOffset, ref.chars, ref.length, otherLength);\n ref.length = newLen;\n }\n\n /**\n * Return a {@link CharsRef} that points to the internal content of this builder. Any update to\n * the content of this builder might invalidate the provided ref and vice-versa.\n */\n public CharsRef get() {\n assert ref.offset == 0 : \"Modifying the offset of the returned ref is illegal\";\n return ref;\n }\n\n /**\n * Build a new {@link CharsRef} that has the same content as this builder.\n */\n public CharsRef toCharsRef() {\n return new CharsRef(ArrayUtil.copyOfSubArray(ref.chars, 0, ref.length), 0, ref.length);\n }\n\n @Override\n public String toString() {\n return get().toString();\n }\n\n @Override\n public boolean equals(Object obj) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int hashCode() {\n throw new UnsupportedOperationException();\n }\n}\n"} {"task_id": "Java_2192", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/lucene/lucene/core/src/java/org/apache/lucene/util/CharsRefBuilder.java", "mask_start_position": 2707, "mask_end_position": 2719, "canonical_solution": "therLength);", "pre_mask_code": "package org.apache.lucene.util;\n\n/**\n * A builder for {@link CharsRef} instances.\n *\n * @lucene.internal\n */\npublic class CharsRefBuilder implements Appendable {\n\n private static final String NULL_STRING = \"null\";\n\n private final CharsRef ref;\n\n public CharsRefBuilder() {\n ref = new CharsRef();\n }\n\n /**\n * Return a reference to the chars of this builder.\n */\n public char[] chars() {\n return ref.chars;\n }\n\n /**\n * Return the number of chars in this buffer.\n */\n public int length() {\n return ref.length;\n }\n\n /**\n * Set the length.\n */\n public void setLength(int length) {\n this.ref.length = length;\n }\n\n /**\n * Return the char at the given offset.\n */\n public char charAt(int offset) {\n return ref.chars[offset];\n }\n\n public void setCharAt(int offset, char b) {\n ref.chars[offset] = b;\n }\n\n /**\n * Reset this builder to the empty state.\n */\n public void clear() {\n ref.length = 0;\n }\n\n @Override\n public CharsRefBuilder append(CharSequence csq) {\n if (csq == null) {\n return append(NULL_STRING);\n }\n return append(csq, 0, csq.length());\n }\n\n @Override\n public CharsRefBuilder append(CharSequence csq, int start, int end) {\n if (csq == null) {\n return append(NULL_STRING);\n }\n grow(ref.length + end - start);\n for (int i = start; i < end; ++i) {\n setCharAt(ref.length++, csq.charAt(i));\n }\n return this;\n }\n\n @Override\n public CharsRefBuilder append(char c) {\n grow(ref.length + 1);\n setCharAt(ref.length++, c);\n return this;\n }\n\n /**\n * Copies the given {@link CharsRef} referenced content into this instance.\n */\n public void copyChars(CharsRef other) {\n copyChars(other.chars, other.offset, other.length);\n }\n\n /**\n * Used to grow the reference array.\n */\n public void grow(int newLength) {\n ref.chars = ArrayUtil.grow(ref.chars, newLength);\n }\n\n /**\n * Copy the provided bytes, interpreted as UTF-8 bytes.\n */\n public void copyUTF8Bytes(byte[] bytes, int offset, int length) {\n grow(length);\n ref.length = UnicodeUtil.UTF8toUTF16(bytes, offset, length, ref.chars);\n }\n\n /**\n * Copy the provided bytes, interpreted as UTF-8 bytes.\n */\n public void copyUTF8Bytes(BytesRef bytes) {\n copyUTF8Bytes(bytes.bytes, bytes.offset, bytes.length);\n }\n\n /**\n * Copies the given array into this instance.\n */\n public void copyChars(char[] otherChars, int otherOffset, int otherLength) {\n grow(o", "post_mask_code": "\n System.arraycopy(otherChars, otherOffset, ref.chars, 0, otherLength);\n ref.length = otherLength;\n }\n\n /**\n * Appends the given array to this CharsRef\n */\n public void append(char[] otherChars, int otherOffset, int otherLength) {\n int newLen = ref.length + otherLength;\n grow(newLen);\n System.arraycopy(otherChars, otherOffset, ref.chars, ref.length, otherLength);\n ref.length = newLen;\n }\n\n /**\n * Return a {@link CharsRef} that points to the internal content of this builder. Any update to\n * the content of this builder might invalidate the provided ref and vice-versa.\n */\n public CharsRef get() {\n assert ref.offset == 0 : \"Modifying the offset of the returned ref is illegal\";\n return ref;\n }\n\n /**\n * Build a new {@link CharsRef} that has the same content as this builder.\n */\n public CharsRef toCharsRef() {\n return new CharsRef(ArrayUtil.copyOfSubArray(ref.chars, 0, ref.length), 0, ref.length);\n }\n\n @Override\n public String toString() {\n return get().toString();\n }\n\n @Override\n public boolean equals(Object obj) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int hashCode() {\n throw new UnsupportedOperationException();\n }\n}\n"} {"task_id": "Java_2193", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/apache/lucene/lucene/core/src/java/org/apache/lucene/util/CharsRefBuilder.java", "mask_start_position": 2907, "mask_end_position": 3171, "canonical_solution": "public void append(char[] otherChars, int otherOffset, int otherLength) {\n int newLen = ref.length + otherLength;\n grow(newLen);\n System.arraycopy(otherChars, otherOffset, ref.chars, ref.length, otherLength);\n ref.length = newLen;\n }", "pre_mask_code": "package org.apache.lucene.util;\n\n/**\n * A builder for {@link CharsRef} instances.\n *\n * @lucene.internal\n */\npublic class CharsRefBuilder implements Appendable {\n\n private static final String NULL_STRING = \"null\";\n\n private final CharsRef ref;\n\n public CharsRefBuilder() {\n ref = new CharsRef();\n }\n\n /**\n * Return a reference to the chars of this builder.\n */\n public char[] chars() {\n return ref.chars;\n }\n\n /**\n * Return the number of chars in this buffer.\n */\n public int length() {\n return ref.length;\n }\n\n /**\n * Set the length.\n */\n public void setLength(int length) {\n this.ref.length = length;\n }\n\n /**\n * Return the char at the given offset.\n */\n public char charAt(int offset) {\n return ref.chars[offset];\n }\n\n public void setCharAt(int offset, char b) {\n ref.chars[offset] = b;\n }\n\n /**\n * Reset this builder to the empty state.\n */\n public void clear() {\n ref.length = 0;\n }\n\n @Override\n public CharsRefBuilder append(CharSequence csq) {\n if (csq == null) {\n return append(NULL_STRING);\n }\n return append(csq, 0, csq.length());\n }\n\n @Override\n public CharsRefBuilder append(CharSequence csq, int start, int end) {\n if (csq == null) {\n return append(NULL_STRING);\n }\n grow(ref.length + end - start);\n for (int i = start; i < end; ++i) {\n setCharAt(ref.length++, csq.charAt(i));\n }\n return this;\n }\n\n @Override\n public CharsRefBuilder append(char c) {\n grow(ref.length + 1);\n setCharAt(ref.length++, c);\n return this;\n }\n\n /**\n * Copies the given {@link CharsRef} referenced content into this instance.\n */\n public void copyChars(CharsRef other) {\n copyChars(other.chars, other.offset, other.length);\n }\n\n /**\n * Used to grow the reference array.\n */\n public void grow(int newLength) {\n ref.chars = ArrayUtil.grow(ref.chars, newLength);\n }\n\n /**\n * Copy the provided bytes, interpreted as UTF-8 bytes.\n */\n public void copyUTF8Bytes(byte[] bytes, int offset, int length) {\n grow(length);\n ref.length = UnicodeUtil.UTF8toUTF16(bytes, offset, length, ref.chars);\n }\n\n /**\n * Copy the provided bytes, interpreted as UTF-8 bytes.\n */\n public void copyUTF8Bytes(BytesRef bytes) {\n copyUTF8Bytes(bytes.bytes, bytes.offset, bytes.length);\n }\n\n /**\n * Copies the given array into this instance.\n */\n public void copyChars(char[] otherChars, int otherOffset, int otherLength) {\n grow(otherLength);\n System.arraycopy(otherChars, otherOffset, ref.chars, 0, otherLength);\n ref.length = otherLength;\n }\n\n /**\n * Appends the given array to this CharsRef\n */\n ", "post_mask_code": "\n\n /**\n * Return a {@link CharsRef} that points to the internal content of this builder. Any update to\n * the content of this builder might invalidate the provided ref and vice-versa.\n */\n public CharsRef get() {\n assert ref.offset == 0 : \"Modifying the offset of the returned ref is illegal\";\n return ref;\n }\n\n /**\n * Build a new {@link CharsRef} that has the same content as this builder.\n */\n public CharsRef toCharsRef() {\n return new CharsRef(ArrayUtil.copyOfSubArray(ref.chars, 0, ref.length), 0, ref.length);\n }\n\n @Override\n public String toString() {\n return get().toString();\n }\n\n @Override\n public boolean equals(Object obj) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int hashCode() {\n throw new UnsupportedOperationException();\n }\n}\n"} {"task_id": "Java_2194", "language": "Java", "task_type": "for_statement", "source_file": "java/github/apache/lucene/lucene/core/src/java/org/apache/lucene/util/CharsRefBuilder.java", "mask_start_position": 1451, "mask_end_position": 1548, "canonical_solution": "for (int i = start; i < end; ++i) {\n setCharAt(ref.length++, csq.charAt(i));\n }", "pre_mask_code": "package org.apache.lucene.util;\n\n/**\n * A builder for {@link CharsRef} instances.\n *\n * @lucene.internal\n */\npublic class CharsRefBuilder implements Appendable {\n\n private static final String NULL_STRING = \"null\";\n\n private final CharsRef ref;\n\n public CharsRefBuilder() {\n ref = new CharsRef();\n }\n\n /**\n * Return a reference to the chars of this builder.\n */\n public char[] chars() {\n return ref.chars;\n }\n\n /**\n * Return the number of chars in this buffer.\n */\n public int length() {\n return ref.length;\n }\n\n /**\n * Set the length.\n */\n public void setLength(int length) {\n this.ref.length = length;\n }\n\n /**\n * Return the char at the given offset.\n */\n public char charAt(int offset) {\n return ref.chars[offset];\n }\n\n public void setCharAt(int offset, char b) {\n ref.chars[offset] = b;\n }\n\n /**\n * Reset this builder to the empty state.\n */\n public void clear() {\n ref.length = 0;\n }\n\n @Override\n public CharsRefBuilder append(CharSequence csq) {\n if (csq == null) {\n return append(NULL_STRING);\n }\n return append(csq, 0, csq.length());\n }\n\n @Override\n public CharsRefBuilder append(CharSequence csq, int start, int end) {\n if (csq == null) {\n return append(NULL_STRING);\n }\n grow(ref.length + end - start);\n ", "post_mask_code": "\n return this;\n }\n\n @Override\n public CharsRefBuilder append(char c) {\n grow(ref.length + 1);\n setCharAt(ref.length++, c);\n return this;\n }\n\n /**\n * Copies the given {@link CharsRef} referenced content into this instance.\n */\n public void copyChars(CharsRef other) {\n copyChars(other.chars, other.offset, other.length);\n }\n\n /**\n * Used to grow the reference array.\n */\n public void grow(int newLength) {\n ref.chars = ArrayUtil.grow(ref.chars, newLength);\n }\n\n /**\n * Copy the provided bytes, interpreted as UTF-8 bytes.\n */\n public void copyUTF8Bytes(byte[] bytes, int offset, int length) {\n grow(length);\n ref.length = UnicodeUtil.UTF8toUTF16(bytes, offset, length, ref.chars);\n }\n\n /**\n * Copy the provided bytes, interpreted as UTF-8 bytes.\n */\n public void copyUTF8Bytes(BytesRef bytes) {\n copyUTF8Bytes(bytes.bytes, bytes.offset, bytes.length);\n }\n\n /**\n * Copies the given array into this instance.\n */\n public void copyChars(char[] otherChars, int otherOffset, int otherLength) {\n grow(otherLength);\n System.arraycopy(otherChars, otherOffset, ref.chars, 0, otherLength);\n ref.length = otherLength;\n }\n\n /**\n * Appends the given array to this CharsRef\n */\n public void append(char[] otherChars, int otherOffset, int otherLength) {\n int newLen = ref.length + otherLength;\n grow(newLen);\n System.arraycopy(otherChars, otherOffset, ref.chars, ref.length, otherLength);\n ref.length = newLen;\n }\n\n /**\n * Return a {@link CharsRef} that points to the internal content of this builder. Any update to\n * the content of this builder might invalidate the provided ref and vice-versa.\n */\n public CharsRef get() {\n assert ref.offset == 0 : \"Modifying the offset of the returned ref is illegal\";\n return ref;\n }\n\n /**\n * Build a new {@link CharsRef} that has the same content as this builder.\n */\n public CharsRef toCharsRef() {\n return new CharsRef(ArrayUtil.copyOfSubArray(ref.chars, 0, ref.length), 0, ref.length);\n }\n\n @Override\n public String toString() {\n return get().toString();\n }\n\n @Override\n public boolean equals(Object obj) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int hashCode() {\n throw new UnsupportedOperationException();\n }\n}\n"} {"task_id": "Java_2195", "language": "Java", "task_type": "method_signature", "source_file": "java/github/vipshop/Saturn/saturn-core/src/main/java/com/vip/saturn/job/executor/PeriodicTruncateNohupOutService.java", "mask_start_position": 2017, "mask_end_position": 2053, "canonical_solution": "@Override\n public void run() ", "pre_mask_code": "package com.vip.saturn.job.executor;\n\nimport com.vip.saturn.job.threads.SaturnThreadFactory;\nimport com.vip.saturn.job.utils.LogEvents;\nimport com.vip.saturn.job.utils.LogUtils;\nimport com.vip.saturn.job.utils.SystemEnvProperties;\nimport org.apache.commons.lang3.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.FileNotFoundException;\nimport java.io.RandomAccessFile;\nimport java.nio.channels.FileChannel;\nimport java.util.Random;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * Regular truncate saturn-nohup.out while the size is over specified limit.\n */\npublic class PeriodicTruncateNohupOutService {\n\n private static final Logger log = LoggerFactory.getLogger(PeriodicTruncateNohupOutService.class);\n\n private static final long TRUNCATE_SIZE = 0;\n\n private ScheduledExecutorService truncateLogService;\n\n public PeriodicTruncateNohupOutService(String executorName) {\n truncateLogService = Executors.newScheduledThreadPool(1, new SaturnThreadFactory(executorName + \"-truncate-nohup-out-thread\", false));\n }\n\n public void start() {\n LogUtils.info(log, LogEvents.ExecutorEvent.INIT, \"start PeriodicTruncateNohupOutService\");\n if (StringUtils.isBlank(SystemEnvProperties.VIP_SATURN_LOG_OUTFILE)) {\n LogUtils.warn(log, LogEvents.ExecutorEvent.INIT, \"File path of saturn-nohup.out is not set, please check.\");\n return;\n }\n truncateLogService.scheduleAtFixedRate(new TruncateLogRunnable(), new Random().nextInt(10), SystemEnvProperties.VIP_SATURN_CHECK_NOHUPOUT_SIZE_INTERVAL_IN_SEC, TimeUnit.SECONDS);\n }\n\n public void shutdown() {\n LogUtils.info(log, LogEvents.ExecutorEvent.SHUTDOWN, \"shutdown PeriodicTruncateNohupOutService\");\n if (truncateLogService != null) {\n truncateLogService.shutdownNow();\n }\n }\n\n private class TruncateLogRunnable implements Runnable {\n\n ", "post_mask_code": "{\n try (RandomAccessFile file = new RandomAccessFile(SystemEnvProperties.VIP_SATURN_LOG_OUTFILE, \"rw\");\n FileChannel fc = file.getChannel()) {\n if (fc.size() > SystemEnvProperties.VIP_SATURN_NOHUPOUT_SIZE_LIMIT_IN_BYTES) {\n LogUtils.info(log, TruncateLogRunnable.class.getCanonicalName(), \"truncate {} as size over {} bytes\", SystemEnvProperties.VIP_SATURN_LOG_OUTFILE, SystemEnvProperties.VIP_SATURN_NOHUPOUT_SIZE_LIMIT_IN_BYTES);\n fc.truncate(TRUNCATE_SIZE);\n }\n } catch (FileNotFoundException e) {\n LogUtils.debug(log, TruncateLogRunnable.class.getCanonicalName(), \"saturn-nohup.out is not found:\", SystemEnvProperties.VIP_SATURN_LOG_OUTFILE, e);\n } catch (Exception e) {\n LogUtils.debug(log, TruncateLogRunnable.class.getCanonicalName(), \"exception throws during handle saturn-nohup.out\", e);\n }\n }\n }\n}\n"} {"task_id": "Java_2196", "language": "Java", "task_type": "method_body", "source_file": "java/github/vipshop/Saturn/saturn-core/src/main/java/com/vip/saturn/job/executor/PeriodicTruncateNohupOutService.java", "mask_start_position": 1735, "mask_end_position": 1946, "canonical_solution": "{\n LogUtils.info(log, LogEvents.ExecutorEvent.SHUTDOWN, \"shutdown PeriodicTruncateNohupOutService\");\n if (truncateLogService != null) {\n truncateLogService.shutdownNow();\n }\n }", "pre_mask_code": "package com.vip.saturn.job.executor;\n\nimport com.vip.saturn.job.threads.SaturnThreadFactory;\nimport com.vip.saturn.job.utils.LogEvents;\nimport com.vip.saturn.job.utils.LogUtils;\nimport com.vip.saturn.job.utils.SystemEnvProperties;\nimport org.apache.commons.lang3.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.FileNotFoundException;\nimport java.io.RandomAccessFile;\nimport java.nio.channels.FileChannel;\nimport java.util.Random;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * Regular truncate saturn-nohup.out while the size is over specified limit.\n */\npublic class PeriodicTruncateNohupOutService {\n\n private static final Logger log = LoggerFactory.getLogger(PeriodicTruncateNohupOutService.class);\n\n private static final long TRUNCATE_SIZE = 0;\n\n private ScheduledExecutorService truncateLogService;\n\n public PeriodicTruncateNohupOutService(String executorName) {\n truncateLogService = Executors.newScheduledThreadPool(1, new SaturnThreadFactory(executorName + \"-truncate-nohup-out-thread\", false));\n }\n\n public void start() {\n LogUtils.info(log, LogEvents.ExecutorEvent.INIT, \"start PeriodicTruncateNohupOutService\");\n if (StringUtils.isBlank(SystemEnvProperties.VIP_SATURN_LOG_OUTFILE)) {\n LogUtils.warn(log, LogEvents.ExecutorEvent.INIT, \"File path of saturn-nohup.out is not set, please check.\");\n return;\n }\n truncateLogService.scheduleAtFixedRate(new TruncateLogRunnable(), new Random().nextInt(10), SystemEnvProperties.VIP_SATURN_CHECK_NOHUPOUT_SIZE_INTERVAL_IN_SEC, TimeUnit.SECONDS);\n }\n\n public void shutdown() ", "post_mask_code": "\n\n private class TruncateLogRunnable implements Runnable {\n\n @Override\n public void run() {\n try (RandomAccessFile file = new RandomAccessFile(SystemEnvProperties.VIP_SATURN_LOG_OUTFILE, \"rw\");\n FileChannel fc = file.getChannel()) {\n if (fc.size() > SystemEnvProperties.VIP_SATURN_NOHUPOUT_SIZE_LIMIT_IN_BYTES) {\n LogUtils.info(log, TruncateLogRunnable.class.getCanonicalName(), \"truncate {} as size over {} bytes\", SystemEnvProperties.VIP_SATURN_LOG_OUTFILE, SystemEnvProperties.VIP_SATURN_NOHUPOUT_SIZE_LIMIT_IN_BYTES);\n fc.truncate(TRUNCATE_SIZE);\n }\n } catch (FileNotFoundException e) {\n LogUtils.debug(log, TruncateLogRunnable.class.getCanonicalName(), \"saturn-nohup.out is not found:\", SystemEnvProperties.VIP_SATURN_LOG_OUTFILE, e);\n } catch (Exception e) {\n LogUtils.debug(log, TruncateLogRunnable.class.getCanonicalName(), \"exception throws during handle saturn-nohup.out\", e);\n }\n }\n }\n}\n"} {"task_id": "Java_2197", "language": "Java", "task_type": "single_line", "source_file": "java/github/vipshop/Saturn/saturn-core/src/main/java/com/vip/saturn/job/executor/PeriodicTruncateNohupOutService.java", "mask_start_position": 1633, "mask_end_position": 1700, "canonical_solution": ".VIP_SATURN_CHECK_NOHUPOUT_SIZE_INTERVAL_IN_SEC, TimeUnit.SECONDS);", "pre_mask_code": "package com.vip.saturn.job.executor;\n\nimport com.vip.saturn.job.threads.SaturnThreadFactory;\nimport com.vip.saturn.job.utils.LogEvents;\nimport com.vip.saturn.job.utils.LogUtils;\nimport com.vip.saturn.job.utils.SystemEnvProperties;\nimport org.apache.commons.lang3.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.io.FileNotFoundException;\nimport java.io.RandomAccessFile;\nimport java.nio.channels.FileChannel;\nimport java.util.Random;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * Regular truncate saturn-nohup.out while the size is over specified limit.\n */\npublic class PeriodicTruncateNohupOutService {\n\n private static final Logger log = LoggerFactory.getLogger(PeriodicTruncateNohupOutService.class);\n\n private static final long TRUNCATE_SIZE = 0;\n\n private ScheduledExecutorService truncateLogService;\n\n public PeriodicTruncateNohupOutService(String executorName) {\n truncateLogService = Executors.newScheduledThreadPool(1, new SaturnThreadFactory(executorName + \"-truncate-nohup-out-thread\", false));\n }\n\n public void start() {\n LogUtils.info(log, LogEvents.ExecutorEvent.INIT, \"start PeriodicTruncateNohupOutService\");\n if (StringUtils.isBlank(SystemEnvProperties.VIP_SATURN_LOG_OUTFILE)) {\n LogUtils.warn(log, LogEvents.ExecutorEvent.INIT, \"File path of saturn-nohup.out is not set, please check.\");\n return;\n }\n truncateLogService.scheduleAtFixedRate(new TruncateLogRunnable(), new Random().nextInt(10), SystemEnvProperties", "post_mask_code": "\n }\n\n public void shutdown() {\n LogUtils.info(log, LogEvents.ExecutorEvent.SHUTDOWN, \"shutdown PeriodicTruncateNohupOutService\");\n if (truncateLogService != null) {\n truncateLogService.shutdownNow();\n }\n }\n\n private class TruncateLogRunnable implements Runnable {\n\n @Override\n public void run() {\n try (RandomAccessFile file = new RandomAccessFile(SystemEnvProperties.VIP_SATURN_LOG_OUTFILE, \"rw\");\n FileChannel fc = file.getChannel()) {\n if (fc.size() > SystemEnvProperties.VIP_SATURN_NOHUPOUT_SIZE_LIMIT_IN_BYTES) {\n LogUtils.info(log, TruncateLogRunnable.class.getCanonicalName(), \"truncate {} as size over {} bytes\", SystemEnvProperties.VIP_SATURN_LOG_OUTFILE, SystemEnvProperties.VIP_SATURN_NOHUPOUT_SIZE_LIMIT_IN_BYTES);\n fc.truncate(TRUNCATE_SIZE);\n }\n } catch (FileNotFoundException e) {\n LogUtils.debug(log, TruncateLogRunnable.class.getCanonicalName(), \"saturn-nohup.out is not found:\", SystemEnvProperties.VIP_SATURN_LOG_OUTFILE, e);\n } catch (Exception e) {\n LogUtils.debug(log, TruncateLogRunnable.class.getCanonicalName(), \"exception throws during handle saturn-nohup.out\", e);\n }\n }\n }\n}\n"} {"task_id": "Java_2198", "language": "Java", "task_type": "method_signature", "source_file": "java/github/slackapi/java-slack-sdk/bolt/src/main/java/com/slack/api/bolt/service/builtin/FileInstallationService.java", "mask_start_position": 3832, "mask_end_position": 3928, "canonical_solution": "@Override\n public Installer findInstaller(String enterpriseId, String teamId, String userId) ", "pre_mask_code": "package com.slack.api.bolt.service.builtin;\n\nimport com.slack.api.bolt.AppConfig;\nimport com.slack.api.bolt.model.Bot;\nimport com.slack.api.bolt.model.Installer;\nimport com.slack.api.bolt.model.builtin.DefaultBot;\nimport com.slack.api.bolt.model.builtin.DefaultInstaller;\nimport com.slack.api.bolt.service.InstallationService;\nimport com.slack.api.bolt.util.JsonOps;\nimport lombok.extern.slf4j.Slf4j;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Optional;\nimport static java.util.stream.Collectors.joining;\n\n@Slf4j\npublic class FileInstallationService implements InstallationService {\n\n public static final String DEFAULT_ROOT_DIR = System.getProperty(\"user.home\") + File.separator + \".slack-app\";\n\n private final AppConfig config;\n\n private final String rootDir;\n\n private boolean historicalDataEnabled;\n\n public FileInstallationService(AppConfig config) {\n this(config, DEFAULT_ROOT_DIR);\n }\n\n public FileInstallationService(AppConfig config, String rootDir) {\n this.config = config;\n this.rootDir = rootDir;\n }\n\n @Override\n public boolean isHistoricalDataEnabled() {\n return historicalDataEnabled;\n }\n\n @Override\n public void setHistoricalDataEnabled(boolean isHistoricalDataEnabled) {\n this.historicalDataEnabled = isHistoricalDataEnabled;\n }\n\n @Override\n public void saveInstallerAndBot(Installer installer) throws Exception {\n save(getInstallerPath(installer), installer.getInstalledAt(), JsonOps.toJsonString(installer));\n save(getBotPath(installer.getEnterpriseId(), installer.getTeamId()), installer.getInstalledAt(), JsonOps.toJsonString(installer.toBot()));\n }\n\n @Override\n public void saveBot(Bot bot) throws Exception {\n save(getBotPath(bot.getEnterpriseId(), bot.getTeamId()), bot.getInstalledAt(), JsonOps.toJsonString(bot));\n }\n\n @Override\n public void deleteBot(Bot bot) throws Exception {\n Files.deleteIfExists(Paths.get(getBotPath(bot.getEnterpriseId(), bot.getTeamId())));\n }\n\n @Override\n public void deleteInstaller(Installer installer) throws Exception {\n Files.deleteIfExists(Paths.get(getInstallerPath(installer)));\n }\n\n @Override\n public Bot findBot(String enterpriseId, String teamId) {\n try {\n String json = null;\n if (enterpriseId != null) {\n // try finding org-level bot token first\n try {\n json = loadFileContent(getBotPath(enterpriseId, null));\n } catch (IOException e) {\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultBot.class);\n }\n // not found - going to find workspace level installation\n }\n try {\n json = loadFileContent(getBotPath(enterpriseId, teamId));\n } catch (IOException e) {\n }\n if (json == null && enterpriseId != null) {\n json = loadFileContent(getBotPath(null, teamId));\n if (json != null) {\n Bot bot = JsonOps.fromJson(json, DefaultBot.class);\n bot.setEnterpriseId(enterpriseId);\n save(getBotPath(enterpriseId, teamId), bot.getInstalledAt(), JsonOps.toJsonString(bot));\n return bot;\n }\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultBot.class);\n } else {\n return null;\n }\n } catch (IOException e) {\n log.warn(\"Failed to load a bot user (enterprise_id: {}, team_id: {})\", enterpriseId, teamId);\n return null;\n }\n }\n\n ", "post_mask_code": "{\n try {\n String json = null;\n if (enterpriseId != null) {\n // try finding org-level user token first\n try {\n json = loadFileContent(getInstallerPath(enterpriseId, null, userId));\n } catch (IOException e) {\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultInstaller.class);\n }\n // not found - going to find workspace level installation\n }\n try {\n json = loadFileContent(getInstallerPath(enterpriseId, teamId, userId));\n } catch (IOException e) {\n }\n if (json == null && enterpriseId != null) {\n json = loadFileContent(getInstallerPath(null, teamId, userId));\n if (json != null) {\n Installer i = JsonOps.fromJson(json, DefaultInstaller.class);\n i.setEnterpriseId(enterpriseId);\n save(getInstallerPath(enterpriseId, teamId, userId), i.getInstalledAt(), JsonOps.toJsonString(i));\n return i;\n }\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultInstaller.class);\n } else {\n return null;\n }\n } catch (IOException e) {\n log.warn(\"Failed to load an installer user (enterprise_id: {}, team_id: {})\", enterpriseId, teamId);\n return null;\n }\n }\n\n @Override\n public void deleteAll(String enterpriseId, String teamId) {\n String keyPrefix = Optional.ofNullable(enterpriseId).orElse(\"none\") + \"-\" + Optional.ofNullable(teamId).orElse(\"none\");\n deleteAllFilesMatchingPrefix(keyPrefix, getBaseDir() + File.separator + \"installer\");\n deleteAllFilesMatchingPrefix(keyPrefix, getBaseDir() + File.separator + \"bot\");\n }\n\n private static void deleteAllFilesMatchingPrefix(String keyPrefix, String dir) {\n try {\n Files.walk(Paths.get(dir)).filter(Files::isRegularFile).forEach(path -> {\n if (path.getFileName().startsWith(keyPrefix)) {\n try {\n Files.delete(path);\n } catch (IOException e) {\n log.error(\"Failed to delete a file: {}\", path.toString(), e);\n }\n }\n });\n } catch (IOException e) {\n log.error(\"Failed to scan files under installer directory: {}\", dir);\n }\n }\n\n private String getInstallerPath(Installer i) throws IOException {\n return getInstallerPath(i.getEnterpriseId(), i.getTeamId(), i.getInstallerUserId());\n }\n\n private String getInstallerPath(String enterpriseId, String teamId, String userId) throws IOException {\n String dir = getBaseDir() + File.separator + \"installer\";\n Path dirPath = Paths.get(dir);\n if (!Files.exists(dirPath)) {\n Files.createDirectories(dirPath);\n }\n String key = Optional.ofNullable(enterpriseId).orElse(\"none\") + \"-\" + Optional.ofNullable(teamId).orElse(\"none\") + \"-\" + userId;\n if (isHistoricalDataEnabled()) {\n key = key + \"-latest\";\n }\n return dir + File.separator + key;\n }\n\n private String getBotPath(String enterpriseId, String teamId) throws IOException {\n String dir = getBaseDir() + File.separator + \"bot\";\n Path dirPath = Paths.get(dir);\n if (!Files.exists(dirPath)) {\n Files.createDirectories(dirPath);\n }\n String key = Optional.ofNullable(enterpriseId).orElse(\"none\") + \"-\" + Optional.ofNullable(teamId).orElse(\"none\");\n if (isHistoricalDataEnabled()) {\n key = key + \"-latest\";\n }\n return dir + File.separator + key;\n }\n\n private String getBaseDir() {\n return rootDir + File.separator + config.getClientId() + File.separator + \"installation\";\n }\n\n private void save(String path, Long installedAt, String json) throws IOException {\n // latest\n Files.write(Paths.get(path), json.getBytes());\n if (isHistoricalDataEnabled()) {\n // the historical data\n Files.write(Paths.get(path.replaceFirst(\"-latest$\", \"-\" + installedAt)), json.getBytes());\n }\n }\n\n private String loadFileContent(String filepath) throws IOException {\n String content = Files.readAllLines(Paths.get(filepath)).stream().collect(joining());\n if (content == null || content.trim().isEmpty() || content.trim().equals(\"null\")) {\n return null;\n }\n return content;\n }\n}\n"} {"task_id": "Java_2199", "language": "Java", "task_type": "method_body", "source_file": "java/github/slackapi/java-slack-sdk/bolt/src/main/java/com/slack/api/bolt/service/builtin/FileInstallationService.java", "mask_start_position": 1517, "mask_end_position": 1775, "canonical_solution": "{\n save(getInstallerPath(installer), installer.getInstalledAt(), JsonOps.toJsonString(installer));\n save(getBotPath(installer.getEnterpriseId(), installer.getTeamId()), installer.getInstalledAt(), JsonOps.toJsonString(installer.toBot()));\n }", "pre_mask_code": "package com.slack.api.bolt.service.builtin;\n\nimport com.slack.api.bolt.AppConfig;\nimport com.slack.api.bolt.model.Bot;\nimport com.slack.api.bolt.model.Installer;\nimport com.slack.api.bolt.model.builtin.DefaultBot;\nimport com.slack.api.bolt.model.builtin.DefaultInstaller;\nimport com.slack.api.bolt.service.InstallationService;\nimport com.slack.api.bolt.util.JsonOps;\nimport lombok.extern.slf4j.Slf4j;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Optional;\nimport static java.util.stream.Collectors.joining;\n\n@Slf4j\npublic class FileInstallationService implements InstallationService {\n\n public static final String DEFAULT_ROOT_DIR = System.getProperty(\"user.home\") + File.separator + \".slack-app\";\n\n private final AppConfig config;\n\n private final String rootDir;\n\n private boolean historicalDataEnabled;\n\n public FileInstallationService(AppConfig config) {\n this(config, DEFAULT_ROOT_DIR);\n }\n\n public FileInstallationService(AppConfig config, String rootDir) {\n this.config = config;\n this.rootDir = rootDir;\n }\n\n @Override\n public boolean isHistoricalDataEnabled() {\n return historicalDataEnabled;\n }\n\n @Override\n public void setHistoricalDataEnabled(boolean isHistoricalDataEnabled) {\n this.historicalDataEnabled = isHistoricalDataEnabled;\n }\n\n @Override\n public void saveInstallerAndBot(Installer installer) throws Exception ", "post_mask_code": "\n\n @Override\n public void saveBot(Bot bot) throws Exception {\n save(getBotPath(bot.getEnterpriseId(), bot.getTeamId()), bot.getInstalledAt(), JsonOps.toJsonString(bot));\n }\n\n @Override\n public void deleteBot(Bot bot) throws Exception {\n Files.deleteIfExists(Paths.get(getBotPath(bot.getEnterpriseId(), bot.getTeamId())));\n }\n\n @Override\n public void deleteInstaller(Installer installer) throws Exception {\n Files.deleteIfExists(Paths.get(getInstallerPath(installer)));\n }\n\n @Override\n public Bot findBot(String enterpriseId, String teamId) {\n try {\n String json = null;\n if (enterpriseId != null) {\n // try finding org-level bot token first\n try {\n json = loadFileContent(getBotPath(enterpriseId, null));\n } catch (IOException e) {\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultBot.class);\n }\n // not found - going to find workspace level installation\n }\n try {\n json = loadFileContent(getBotPath(enterpriseId, teamId));\n } catch (IOException e) {\n }\n if (json == null && enterpriseId != null) {\n json = loadFileContent(getBotPath(null, teamId));\n if (json != null) {\n Bot bot = JsonOps.fromJson(json, DefaultBot.class);\n bot.setEnterpriseId(enterpriseId);\n save(getBotPath(enterpriseId, teamId), bot.getInstalledAt(), JsonOps.toJsonString(bot));\n return bot;\n }\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultBot.class);\n } else {\n return null;\n }\n } catch (IOException e) {\n log.warn(\"Failed to load a bot user (enterprise_id: {}, team_id: {})\", enterpriseId, teamId);\n return null;\n }\n }\n\n @Override\n public Installer findInstaller(String enterpriseId, String teamId, String userId) {\n try {\n String json = null;\n if (enterpriseId != null) {\n // try finding org-level user token first\n try {\n json = loadFileContent(getInstallerPath(enterpriseId, null, userId));\n } catch (IOException e) {\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultInstaller.class);\n }\n // not found - going to find workspace level installation\n }\n try {\n json = loadFileContent(getInstallerPath(enterpriseId, teamId, userId));\n } catch (IOException e) {\n }\n if (json == null && enterpriseId != null) {\n json = loadFileContent(getInstallerPath(null, teamId, userId));\n if (json != null) {\n Installer i = JsonOps.fromJson(json, DefaultInstaller.class);\n i.setEnterpriseId(enterpriseId);\n save(getInstallerPath(enterpriseId, teamId, userId), i.getInstalledAt(), JsonOps.toJsonString(i));\n return i;\n }\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultInstaller.class);\n } else {\n return null;\n }\n } catch (IOException e) {\n log.warn(\"Failed to load an installer user (enterprise_id: {}, team_id: {})\", enterpriseId, teamId);\n return null;\n }\n }\n\n @Override\n public void deleteAll(String enterpriseId, String teamId) {\n String keyPrefix = Optional.ofNullable(enterpriseId).orElse(\"none\") + \"-\" + Optional.ofNullable(teamId).orElse(\"none\");\n deleteAllFilesMatchingPrefix(keyPrefix, getBaseDir() + File.separator + \"installer\");\n deleteAllFilesMatchingPrefix(keyPrefix, getBaseDir() + File.separator + \"bot\");\n }\n\n private static void deleteAllFilesMatchingPrefix(String keyPrefix, String dir) {\n try {\n Files.walk(Paths.get(dir)).filter(Files::isRegularFile).forEach(path -> {\n if (path.getFileName().startsWith(keyPrefix)) {\n try {\n Files.delete(path);\n } catch (IOException e) {\n log.error(\"Failed to delete a file: {}\", path.toString(), e);\n }\n }\n });\n } catch (IOException e) {\n log.error(\"Failed to scan files under installer directory: {}\", dir);\n }\n }\n\n private String getInstallerPath(Installer i) throws IOException {\n return getInstallerPath(i.getEnterpriseId(), i.getTeamId(), i.getInstallerUserId());\n }\n\n private String getInstallerPath(String enterpriseId, String teamId, String userId) throws IOException {\n String dir = getBaseDir() + File.separator + \"installer\";\n Path dirPath = Paths.get(dir);\n if (!Files.exists(dirPath)) {\n Files.createDirectories(dirPath);\n }\n String key = Optional.ofNullable(enterpriseId).orElse(\"none\") + \"-\" + Optional.ofNullable(teamId).orElse(\"none\") + \"-\" + userId;\n if (isHistoricalDataEnabled()) {\n key = key + \"-latest\";\n }\n return dir + File.separator + key;\n }\n\n private String getBotPath(String enterpriseId, String teamId) throws IOException {\n String dir = getBaseDir() + File.separator + \"bot\";\n Path dirPath = Paths.get(dir);\n if (!Files.exists(dirPath)) {\n Files.createDirectories(dirPath);\n }\n String key = Optional.ofNullable(enterpriseId).orElse(\"none\") + \"-\" + Optional.ofNullable(teamId).orElse(\"none\");\n if (isHistoricalDataEnabled()) {\n key = key + \"-latest\";\n }\n return dir + File.separator + key;\n }\n\n private String getBaseDir() {\n return rootDir + File.separator + config.getClientId() + File.separator + \"installation\";\n }\n\n private void save(String path, Long installedAt, String json) throws IOException {\n // latest\n Files.write(Paths.get(path), json.getBytes());\n if (isHistoricalDataEnabled()) {\n // the historical data\n Files.write(Paths.get(path.replaceFirst(\"-latest$\", \"-\" + installedAt)), json.getBytes());\n }\n }\n\n private String loadFileContent(String filepath) throws IOException {\n String content = Files.readAllLines(Paths.get(filepath)).stream().collect(joining());\n if (content == null || content.trim().isEmpty() || content.trim().equals(\"null\")) {\n return null;\n }\n return content;\n }\n}\n"} {"task_id": "Java_2200", "language": "Java", "task_type": "single_line", "source_file": "java/github/slackapi/java-slack-sdk/bolt/src/main/java/com/slack/api/bolt/service/builtin/FileInstallationService.java", "mask_start_position": 2254, "mask_end_position": 2288, "canonical_solution": "get(getInstallerPath(installer)));", "pre_mask_code": "package com.slack.api.bolt.service.builtin;\n\nimport com.slack.api.bolt.AppConfig;\nimport com.slack.api.bolt.model.Bot;\nimport com.slack.api.bolt.model.Installer;\nimport com.slack.api.bolt.model.builtin.DefaultBot;\nimport com.slack.api.bolt.model.builtin.DefaultInstaller;\nimport com.slack.api.bolt.service.InstallationService;\nimport com.slack.api.bolt.util.JsonOps;\nimport lombok.extern.slf4j.Slf4j;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Optional;\nimport static java.util.stream.Collectors.joining;\n\n@Slf4j\npublic class FileInstallationService implements InstallationService {\n\n public static final String DEFAULT_ROOT_DIR = System.getProperty(\"user.home\") + File.separator + \".slack-app\";\n\n private final AppConfig config;\n\n private final String rootDir;\n\n private boolean historicalDataEnabled;\n\n public FileInstallationService(AppConfig config) {\n this(config, DEFAULT_ROOT_DIR);\n }\n\n public FileInstallationService(AppConfig config, String rootDir) {\n this.config = config;\n this.rootDir = rootDir;\n }\n\n @Override\n public boolean isHistoricalDataEnabled() {\n return historicalDataEnabled;\n }\n\n @Override\n public void setHistoricalDataEnabled(boolean isHistoricalDataEnabled) {\n this.historicalDataEnabled = isHistoricalDataEnabled;\n }\n\n @Override\n public void saveInstallerAndBot(Installer installer) throws Exception {\n save(getInstallerPath(installer), installer.getInstalledAt(), JsonOps.toJsonString(installer));\n save(getBotPath(installer.getEnterpriseId(), installer.getTeamId()), installer.getInstalledAt(), JsonOps.toJsonString(installer.toBot()));\n }\n\n @Override\n public void saveBot(Bot bot) throws Exception {\n save(getBotPath(bot.getEnterpriseId(), bot.getTeamId()), bot.getInstalledAt(), JsonOps.toJsonString(bot));\n }\n\n @Override\n public void deleteBot(Bot bot) throws Exception {\n Files.deleteIfExists(Paths.get(getBotPath(bot.getEnterpriseId(), bot.getTeamId())));\n }\n\n @Override\n public void deleteInstaller(Installer installer) throws Exception {\n Files.deleteIfExists(Paths.", "post_mask_code": "\n }\n\n @Override\n public Bot findBot(String enterpriseId, String teamId) {\n try {\n String json = null;\n if (enterpriseId != null) {\n // try finding org-level bot token first\n try {\n json = loadFileContent(getBotPath(enterpriseId, null));\n } catch (IOException e) {\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultBot.class);\n }\n // not found - going to find workspace level installation\n }\n try {\n json = loadFileContent(getBotPath(enterpriseId, teamId));\n } catch (IOException e) {\n }\n if (json == null && enterpriseId != null) {\n json = loadFileContent(getBotPath(null, teamId));\n if (json != null) {\n Bot bot = JsonOps.fromJson(json, DefaultBot.class);\n bot.setEnterpriseId(enterpriseId);\n save(getBotPath(enterpriseId, teamId), bot.getInstalledAt(), JsonOps.toJsonString(bot));\n return bot;\n }\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultBot.class);\n } else {\n return null;\n }\n } catch (IOException e) {\n log.warn(\"Failed to load a bot user (enterprise_id: {}, team_id: {})\", enterpriseId, teamId);\n return null;\n }\n }\n\n @Override\n public Installer findInstaller(String enterpriseId, String teamId, String userId) {\n try {\n String json = null;\n if (enterpriseId != null) {\n // try finding org-level user token first\n try {\n json = loadFileContent(getInstallerPath(enterpriseId, null, userId));\n } catch (IOException e) {\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultInstaller.class);\n }\n // not found - going to find workspace level installation\n }\n try {\n json = loadFileContent(getInstallerPath(enterpriseId, teamId, userId));\n } catch (IOException e) {\n }\n if (json == null && enterpriseId != null) {\n json = loadFileContent(getInstallerPath(null, teamId, userId));\n if (json != null) {\n Installer i = JsonOps.fromJson(json, DefaultInstaller.class);\n i.setEnterpriseId(enterpriseId);\n save(getInstallerPath(enterpriseId, teamId, userId), i.getInstalledAt(), JsonOps.toJsonString(i));\n return i;\n }\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultInstaller.class);\n } else {\n return null;\n }\n } catch (IOException e) {\n log.warn(\"Failed to load an installer user (enterprise_id: {}, team_id: {})\", enterpriseId, teamId);\n return null;\n }\n }\n\n @Override\n public void deleteAll(String enterpriseId, String teamId) {\n String keyPrefix = Optional.ofNullable(enterpriseId).orElse(\"none\") + \"-\" + Optional.ofNullable(teamId).orElse(\"none\");\n deleteAllFilesMatchingPrefix(keyPrefix, getBaseDir() + File.separator + \"installer\");\n deleteAllFilesMatchingPrefix(keyPrefix, getBaseDir() + File.separator + \"bot\");\n }\n\n private static void deleteAllFilesMatchingPrefix(String keyPrefix, String dir) {\n try {\n Files.walk(Paths.get(dir)).filter(Files::isRegularFile).forEach(path -> {\n if (path.getFileName().startsWith(keyPrefix)) {\n try {\n Files.delete(path);\n } catch (IOException e) {\n log.error(\"Failed to delete a file: {}\", path.toString(), e);\n }\n }\n });\n } catch (IOException e) {\n log.error(\"Failed to scan files under installer directory: {}\", dir);\n }\n }\n\n private String getInstallerPath(Installer i) throws IOException {\n return getInstallerPath(i.getEnterpriseId(), i.getTeamId(), i.getInstallerUserId());\n }\n\n private String getInstallerPath(String enterpriseId, String teamId, String userId) throws IOException {\n String dir = getBaseDir() + File.separator + \"installer\";\n Path dirPath = Paths.get(dir);\n if (!Files.exists(dirPath)) {\n Files.createDirectories(dirPath);\n }\n String key = Optional.ofNullable(enterpriseId).orElse(\"none\") + \"-\" + Optional.ofNullable(teamId).orElse(\"none\") + \"-\" + userId;\n if (isHistoricalDataEnabled()) {\n key = key + \"-latest\";\n }\n return dir + File.separator + key;\n }\n\n private String getBotPath(String enterpriseId, String teamId) throws IOException {\n String dir = getBaseDir() + File.separator + \"bot\";\n Path dirPath = Paths.get(dir);\n if (!Files.exists(dirPath)) {\n Files.createDirectories(dirPath);\n }\n String key = Optional.ofNullable(enterpriseId).orElse(\"none\") + \"-\" + Optional.ofNullable(teamId).orElse(\"none\");\n if (isHistoricalDataEnabled()) {\n key = key + \"-latest\";\n }\n return dir + File.separator + key;\n }\n\n private String getBaseDir() {\n return rootDir + File.separator + config.getClientId() + File.separator + \"installation\";\n }\n\n private void save(String path, Long installedAt, String json) throws IOException {\n // latest\n Files.write(Paths.get(path), json.getBytes());\n if (isHistoricalDataEnabled()) {\n // the historical data\n Files.write(Paths.get(path.replaceFirst(\"-latest$\", \"-\" + installedAt)), json.getBytes());\n }\n }\n\n private String loadFileContent(String filepath) throws IOException {\n String content = Files.readAllLines(Paths.get(filepath)).stream().collect(joining());\n if (content == null || content.trim().isEmpty() || content.trim().equals(\"null\")) {\n return null;\n }\n return content;\n }\n}\n"} {"task_id": "Java_2201", "language": "Java", "task_type": "try_statement", "source_file": "java/github/slackapi/java-slack-sdk/bolt/src/main/java/com/slack/api/bolt/service/builtin/FileInstallationService.java", "mask_start_position": 2895, "mask_end_position": 3026, "canonical_solution": "try {\n json = loadFileContent(getBotPath(enterpriseId, teamId));\n } catch (IOException e) {\n }", "pre_mask_code": "package com.slack.api.bolt.service.builtin;\n\nimport com.slack.api.bolt.AppConfig;\nimport com.slack.api.bolt.model.Bot;\nimport com.slack.api.bolt.model.Installer;\nimport com.slack.api.bolt.model.builtin.DefaultBot;\nimport com.slack.api.bolt.model.builtin.DefaultInstaller;\nimport com.slack.api.bolt.service.InstallationService;\nimport com.slack.api.bolt.util.JsonOps;\nimport lombok.extern.slf4j.Slf4j;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Optional;\nimport static java.util.stream.Collectors.joining;\n\n@Slf4j\npublic class FileInstallationService implements InstallationService {\n\n public static final String DEFAULT_ROOT_DIR = System.getProperty(\"user.home\") + File.separator + \".slack-app\";\n\n private final AppConfig config;\n\n private final String rootDir;\n\n private boolean historicalDataEnabled;\n\n public FileInstallationService(AppConfig config) {\n this(config, DEFAULT_ROOT_DIR);\n }\n\n public FileInstallationService(AppConfig config, String rootDir) {\n this.config = config;\n this.rootDir = rootDir;\n }\n\n @Override\n public boolean isHistoricalDataEnabled() {\n return historicalDataEnabled;\n }\n\n @Override\n public void setHistoricalDataEnabled(boolean isHistoricalDataEnabled) {\n this.historicalDataEnabled = isHistoricalDataEnabled;\n }\n\n @Override\n public void saveInstallerAndBot(Installer installer) throws Exception {\n save(getInstallerPath(installer), installer.getInstalledAt(), JsonOps.toJsonString(installer));\n save(getBotPath(installer.getEnterpriseId(), installer.getTeamId()), installer.getInstalledAt(), JsonOps.toJsonString(installer.toBot()));\n }\n\n @Override\n public void saveBot(Bot bot) throws Exception {\n save(getBotPath(bot.getEnterpriseId(), bot.getTeamId()), bot.getInstalledAt(), JsonOps.toJsonString(bot));\n }\n\n @Override\n public void deleteBot(Bot bot) throws Exception {\n Files.deleteIfExists(Paths.get(getBotPath(bot.getEnterpriseId(), bot.getTeamId())));\n }\n\n @Override\n public void deleteInstaller(Installer installer) throws Exception {\n Files.deleteIfExists(Paths.get(getInstallerPath(installer)));\n }\n\n @Override\n public Bot findBot(String enterpriseId, String teamId) {\n try {\n String json = null;\n if (enterpriseId != null) {\n // try finding org-level bot token first\n try {\n json = loadFileContent(getBotPath(enterpriseId, null));\n } catch (IOException e) {\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultBot.class);\n }\n // not found - going to find workspace level installation\n }\n ", "post_mask_code": "\n if (json == null && enterpriseId != null) {\n json = loadFileContent(getBotPath(null, teamId));\n if (json != null) {\n Bot bot = JsonOps.fromJson(json, DefaultBot.class);\n bot.setEnterpriseId(enterpriseId);\n save(getBotPath(enterpriseId, teamId), bot.getInstalledAt(), JsonOps.toJsonString(bot));\n return bot;\n }\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultBot.class);\n } else {\n return null;\n }\n } catch (IOException e) {\n log.warn(\"Failed to load a bot user (enterprise_id: {}, team_id: {})\", enterpriseId, teamId);\n return null;\n }\n }\n\n @Override\n public Installer findInstaller(String enterpriseId, String teamId, String userId) {\n try {\n String json = null;\n if (enterpriseId != null) {\n // try finding org-level user token first\n try {\n json = loadFileContent(getInstallerPath(enterpriseId, null, userId));\n } catch (IOException e) {\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultInstaller.class);\n }\n // not found - going to find workspace level installation\n }\n try {\n json = loadFileContent(getInstallerPath(enterpriseId, teamId, userId));\n } catch (IOException e) {\n }\n if (json == null && enterpriseId != null) {\n json = loadFileContent(getInstallerPath(null, teamId, userId));\n if (json != null) {\n Installer i = JsonOps.fromJson(json, DefaultInstaller.class);\n i.setEnterpriseId(enterpriseId);\n save(getInstallerPath(enterpriseId, teamId, userId), i.getInstalledAt(), JsonOps.toJsonString(i));\n return i;\n }\n }\n if (json != null) {\n return JsonOps.fromJson(json, DefaultInstaller.class);\n } else {\n return null;\n }\n } catch (IOException e) {\n log.warn(\"Failed to load an installer user (enterprise_id: {}, team_id: {})\", enterpriseId, teamId);\n return null;\n }\n }\n\n @Override\n public void deleteAll(String enterpriseId, String teamId) {\n String keyPrefix = Optional.ofNullable(enterpriseId).orElse(\"none\") + \"-\" + Optional.ofNullable(teamId).orElse(\"none\");\n deleteAllFilesMatchingPrefix(keyPrefix, getBaseDir() + File.separator + \"installer\");\n deleteAllFilesMatchingPrefix(keyPrefix, getBaseDir() + File.separator + \"bot\");\n }\n\n private static void deleteAllFilesMatchingPrefix(String keyPrefix, String dir) {\n try {\n Files.walk(Paths.get(dir)).filter(Files::isRegularFile).forEach(path -> {\n if (path.getFileName().startsWith(keyPrefix)) {\n try {\n Files.delete(path);\n } catch (IOException e) {\n log.error(\"Failed to delete a file: {}\", path.toString(), e);\n }\n }\n });\n } catch (IOException e) {\n log.error(\"Failed to scan files under installer directory: {}\", dir);\n }\n }\n\n private String getInstallerPath(Installer i) throws IOException {\n return getInstallerPath(i.getEnterpriseId(), i.getTeamId(), i.getInstallerUserId());\n }\n\n private String getInstallerPath(String enterpriseId, String teamId, String userId) throws IOException {\n String dir = getBaseDir() + File.separator + \"installer\";\n Path dirPath = Paths.get(dir);\n if (!Files.exists(dirPath)) {\n Files.createDirectories(dirPath);\n }\n String key = Optional.ofNullable(enterpriseId).orElse(\"none\") + \"-\" + Optional.ofNullable(teamId).orElse(\"none\") + \"-\" + userId;\n if (isHistoricalDataEnabled()) {\n key = key + \"-latest\";\n }\n return dir + File.separator + key;\n }\n\n private String getBotPath(String enterpriseId, String teamId) throws IOException {\n String dir = getBaseDir() + File.separator + \"bot\";\n Path dirPath = Paths.get(dir);\n if (!Files.exists(dirPath)) {\n Files.createDirectories(dirPath);\n }\n String key = Optional.ofNullable(enterpriseId).orElse(\"none\") + \"-\" + Optional.ofNullable(teamId).orElse(\"none\");\n if (isHistoricalDataEnabled()) {\n key = key + \"-latest\";\n }\n return dir + File.separator + key;\n }\n\n private String getBaseDir() {\n return rootDir + File.separator + config.getClientId() + File.separator + \"installation\";\n }\n\n private void save(String path, Long installedAt, String json) throws IOException {\n // latest\n Files.write(Paths.get(path), json.getBytes());\n if (isHistoricalDataEnabled()) {\n // the historical data\n Files.write(Paths.get(path.replaceFirst(\"-latest$\", \"-\" + installedAt)), json.getBytes());\n }\n }\n\n private String loadFileContent(String filepath) throws IOException {\n String content = Files.readAllLines(Paths.get(filepath)).stream().collect(joining());\n if (content == null || content.trim().isEmpty() || content.trim().equals(\"null\")) {\n return null;\n }\n return content;\n }\n}\n"} {"task_id": "Java_2202", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openjdk/jdk/src/java.base/share/classes/javax/net/ssl/SNIHostName.java", "mask_start_position": 8570, "mask_end_position": 8606, "canonical_solution": "@Override\n public int hashCode() ", "pre_mask_code": "package javax.net.ssl;\n\nimport java.net.IDN;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.CodingErrorAction;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.charset.CharsetDecoder;\nimport java.nio.charset.CharacterCodingException;\nimport java.util.Locale;\nimport java.util.Objects;\nimport java.util.regex.Pattern;\nimport java.util.regex.PatternSyntaxException;\n\n/**\n * Instances of this class represent a server name of type\n * {@link StandardConstants#SNI_HOST_NAME host_name} in a Server Name\n * Indication (SNI) extension.\n *

\n * As described in section 3, \"Server Name Indication\", of\n * TLS Extensions (RFC 6066),\n * \"HostName\" contains the fully qualified DNS hostname of the server, as\n * understood by the client. The encoded server name value of a hostname is\n * represented as a byte string using ASCII encoding without a trailing dot.\n * This allows the support of Internationalized Domain Names (IDN) through\n * the use of A-labels (the ASCII-Compatible Encoding (ACE) form of a valid\n * string of Internationalized Domain Names for Applications (IDNA)) defined\n * in RFC 5890.\n *

\n * Note that {@code SNIHostName} objects are immutable.\n *\n * @see SNIServerName\n * @see StandardConstants#SNI_HOST_NAME\n *\n * @since 1.8\n */\npublic final class SNIHostName extends SNIServerName {\n\n // the decoded string value of the server name\n private final String hostname;\n\n /**\n * Creates an {@code SNIHostName} using the specified hostname.\n *

\n * Note that per RFC 6066,\n * the encoded server name value of a hostname is\n * {@link StandardCharsets#US_ASCII}-compliant. In this method,\n * {@code hostname} can be a user-friendly Internationalized Domain Name\n * (IDN). {@link IDN#toASCII(String, int)} is used to enforce the\n * restrictions on ASCII characters in hostnames (see\n * RFC 3490,\n * RFC 1122,\n * RFC 1123) and\n * translate the {@code hostname} into ASCII Compatible Encoding (ACE), as:\n *

\n     *     IDN.toASCII(hostname, IDN.USE_STD3_ASCII_RULES);\n     * 
\n *

\n * The {@code hostname} argument is illegal if it:\n *

    \n *
  • {@code hostname} is empty,
  • \n *
  • {@code hostname} ends with a trailing dot,
  • \n *
  • {@code hostname} is not a valid Internationalized\n * Domain Name (IDN) compliant with the RFC 3490 specification.
  • \n *
\n * @param hostname\n * the hostname of this server name\n *\n * @throws NullPointerException if {@code hostname} is {@code null}\n * @throws IllegalArgumentException if {@code hostname} is illegal\n */\n public SNIHostName(String hostname) {\n // IllegalArgumentException will be thrown if {@code hostname} is\n // not a valid IDN.\n super(StandardConstants.SNI_HOST_NAME, (hostname = IDN.toASCII(Objects.requireNonNull(hostname, \"Server name value of host_name cannot be null\"), IDN.USE_STD3_ASCII_RULES)).getBytes(StandardCharsets.US_ASCII));\n this.hostname = hostname;\n // check the validity of the string hostname\n checkHostName();\n }\n\n /**\n * Creates an {@code SNIHostName} using the specified encoded value.\n *

\n * This method is normally used to parse the encoded name value in a\n * requested SNI extension.\n *

\n * Per RFC 6066,\n * the encoded name value of a hostname is\n * {@link StandardCharsets#US_ASCII}-compliant. However, in the previous\n * version of the SNI extension (\n * RFC 4366),\n * the encoded hostname is represented as a byte string using UTF-8\n * encoding. For the purpose of version tolerance, this method allows\n * that the charset of {@code encoded} argument can be\n * {@link StandardCharsets#UTF_8}, as well as\n * {@link StandardCharsets#US_ASCII}. {@link IDN#toASCII(String)} is used\n * to translate the {@code encoded} argument into ASCII Compatible\n * Encoding (ACE) hostname.\n *

\n * It is strongly recommended that this constructor is only used to parse\n * the encoded name value in a requested SNI extension. Otherwise, to\n * comply with RFC 6066,\n * please always use {@link StandardCharsets#US_ASCII}-compliant charset\n * and enforce the restrictions on ASCII characters in hostnames (see\n * RFC 3490,\n * RFC 1122,\n * RFC 1123)\n * for {@code encoded} argument, or use\n * {@link SNIHostName#SNIHostName(String)} instead.\n *

\n * The {@code encoded} argument is illegal if it:\n *

    \n *
  • {@code encoded} is empty,
  • \n *
  • {@code encoded} ends with a trailing dot,
  • \n *
  • {@code encoded} is not encoded in\n * {@link StandardCharsets#US_ASCII} or\n * {@link StandardCharsets#UTF_8}-compliant charset,
  • \n *
  • {@code encoded} is not a valid Internationalized\n * Domain Name (IDN) compliant with the RFC 3490 specification.
  • \n *
\n *\n *

\n * Note that the {@code encoded} byte array is cloned\n * to protect against subsequent modification.\n *\n * @param encoded\n * the encoded hostname of this server name\n *\n * @throws NullPointerException if {@code encoded} is {@code null}\n * @throws IllegalArgumentException if {@code encoded} is illegal\n */\n public SNIHostName(byte[] encoded) {\n // NullPointerException will be thrown if {@code encoded} is null\n super(StandardConstants.SNI_HOST_NAME, encoded);\n // Compliance: RFC 4366 requires that the hostname is represented\n // as a byte string using UTF_8 encoding [UTF8]\n try {\n // Please don't use {@link String} constructors because they\n // do not report coding errors.\n CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);\n this.hostname = IDN.toASCII(decoder.decode(ByteBuffer.wrap(encoded)).toString(), IDN.USE_STD3_ASCII_RULES);\n } catch (RuntimeException | CharacterCodingException e) {\n throw new IllegalArgumentException(\"The encoded server name value is invalid\", e);\n }\n // check the validity of the string hostname\n checkHostName();\n }\n\n /**\n * Returns the {@link StandardCharsets#US_ASCII}-compliant hostname of\n * this {@code SNIHostName} object.\n *

\n * Note that, per\n * RFC 6066, the\n * returned hostname may be an internationalized domain name that\n * contains A-labels. See\n * RFC 5890\n * for more information about the detailed A-label specification.\n *\n * @return the {@link StandardCharsets#US_ASCII}-compliant hostname\n * of this {@code SNIHostName} object\n */\n public String getAsciiName() {\n return hostname;\n }\n\n /**\n * Compares this server name to the specified object.\n *

\n * Per RFC 6066, DNS\n * hostnames are case-insensitive. Two server hostnames are equal if,\n * and only if, they have the same name type, and the hostnames are\n * equal in a case-independent comparison.\n *\n * @param other\n * the other server name object to compare with.\n * @return true if, and only if, the {@code other} is considered\n * equal to this instance\n */\n @Override\n public boolean equals(Object other) {\n if (this == other) {\n return true;\n }\n if (other instanceof SNIHostName) {\n return hostname.equalsIgnoreCase(((SNIHostName) other).hostname);\n }\n return false;\n }\n\n /**\n * Returns a hash code value for this {@code SNIHostName}.\n *

\n * The hash code value is generated using the case-insensitive hostname\n * of this {@code SNIHostName}.\n *\n * @return a hash code value for this {@code SNIHostName}.\n */\n ", "post_mask_code": "{\n // 17/31: prime number to decrease collisions\n int result = 17;\n result = 31 * result + hostname.toUpperCase(Locale.ENGLISH).hashCode();\n return result;\n }\n\n /**\n * Returns a string representation of the object, including the DNS\n * hostname in this {@code SNIHostName} object.\n *

\n * The exact details of the representation are unspecified and subject\n * to change, but the following may be regarded as typical:\n *

\n     *     \"type=host_name (0), value={@literal }\"\n     * 
\n * The \"{@literal }\" is an ASCII representation of the hostname,\n * which may contains A-labels. For example, a returned value of an pseudo\n * hostname may look like:\n *
\n     *     \"type=host_name (0), value=www.example.com\"\n     * 
\n * or\n *
\n     *     \"type=host_name (0), value=xn--fsqu00a.xn--0zwm56d\"\n     * 
\n *

\n * Please NOTE that the exact details of the representation are unspecified\n * and subject to change.\n *\n * @return a string representation of the object.\n */\n @Override\n public String toString() {\n return \"type=host_name (0), value=\" + hostname;\n }\n\n /**\n * Creates an {@link SNIMatcher} object for {@code SNIHostName}s.\n *

\n * This method can be used by a server to verify the acceptable\n * {@code SNIHostName}s. For example,\n *

\n     *     SNIMatcher matcher =\n     *         SNIHostName.createSNIMatcher(\"www\\\\.example\\\\.com\");\n     * 
\n * will accept the hostname \"www.example.com\".\n *
\n     *     SNIMatcher matcher =\n     *         SNIHostName.createSNIMatcher(\"www\\\\.example\\\\.(com|org)\");\n     * 
\n * will accept hostnames \"www.example.com\" and \"www.example.org\".\n *\n * @param regex\n * the \n * regular expression pattern\n * representing the hostname(s) to match\n * @return a {@code SNIMatcher} object for {@code SNIHostName}s\n * @throws NullPointerException if {@code regex} is\n * {@code null}\n * @throws PatternSyntaxException if the regular expression's\n * syntax is invalid\n */\n public static SNIMatcher createSNIMatcher(String regex) {\n if (regex == null) {\n throw new NullPointerException(\"The regular expression cannot be null\");\n }\n return new SNIHostNameMatcher(regex);\n }\n\n // check the validity of the string hostname\n private void checkHostName() {\n if (hostname.isEmpty()) {\n throw new IllegalArgumentException(\"Server name value of host_name cannot be empty\");\n }\n if (hostname.endsWith(\".\")) {\n throw new IllegalArgumentException(\"Server name value of host_name cannot have the trailing dot\");\n }\n }\n\n private static final class SNIHostNameMatcher extends SNIMatcher {\n\n // the compiled representation of a regular expression.\n private final Pattern pattern;\n\n /**\n * Creates an SNIHostNameMatcher object.\n *\n * @param regex\n * the \n * regular expression pattern\n * representing the hostname(s) to match\n * @throws NullPointerException if {@code regex} is\n * {@code null}\n * @throws PatternSyntaxException if the regular expression's syntax\n * is invalid\n */\n SNIHostNameMatcher(String regex) {\n super(StandardConstants.SNI_HOST_NAME);\n pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);\n }\n\n /**\n * Attempts to match the given {@link SNIServerName}.\n *\n * @param serverName\n * the {@link SNIServerName} instance on which this matcher\n * performs match operations\n *\n * @return {@code true} if, and only if, the matcher matches the\n * given {@code serverName}\n *\n * @throws NullPointerException if {@code serverName} is {@code null}\n * @throws IllegalArgumentException if {@code serverName} is\n * not of {@code StandardConstants#SNI_HOST_NAME} type\n *\n * @see SNIServerName\n */\n @Override\n public boolean matches(SNIServerName serverName) {\n if (serverName == null) {\n throw new NullPointerException(\"The SNIServerName argument cannot be null\");\n }\n SNIHostName hostname;\n if (!(serverName instanceof SNIHostName)) {\n if (serverName.getType() != StandardConstants.SNI_HOST_NAME) {\n throw new IllegalArgumentException(\"The server name type is not host_name\");\n }\n try {\n hostname = new SNIHostName(serverName.getEncoded());\n } catch (NullPointerException | IllegalArgumentException e) {\n return false;\n }\n } else {\n hostname = (SNIHostName) serverName;\n }\n // Let's first try the ascii name matching\n String asciiName = hostname.getAsciiName();\n if (pattern.matcher(asciiName).matches()) {\n return true;\n }\n // May be an internationalized domain name, check the Unicode\n return pattern.matcher(IDN.toUnicode(asciiName)).matches();\n }\n }\n}\n"} {"task_id": "Java_2203", "language": "Java", "task_type": "method_body", "source_file": "java/github/openjdk/jdk/src/java.base/share/classes/javax/net/ssl/SNIHostName.java", "mask_start_position": 8606, "mask_end_position": 8795, "canonical_solution": "{\n // 17/31: prime number to decrease collisions\n int result = 17;\n result = 31 * result + hostname.toUpperCase(Locale.ENGLISH).hashCode();\n return result;\n }", "pre_mask_code": "package javax.net.ssl;\n\nimport java.net.IDN;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.CodingErrorAction;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.charset.CharsetDecoder;\nimport java.nio.charset.CharacterCodingException;\nimport java.util.Locale;\nimport java.util.Objects;\nimport java.util.regex.Pattern;\nimport java.util.regex.PatternSyntaxException;\n\n/**\n * Instances of this class represent a server name of type\n * {@link StandardConstants#SNI_HOST_NAME host_name} in a Server Name\n * Indication (SNI) extension.\n *

\n * As described in section 3, \"Server Name Indication\", of\n * TLS Extensions (RFC 6066),\n * \"HostName\" contains the fully qualified DNS hostname of the server, as\n * understood by the client. The encoded server name value of a hostname is\n * represented as a byte string using ASCII encoding without a trailing dot.\n * This allows the support of Internationalized Domain Names (IDN) through\n * the use of A-labels (the ASCII-Compatible Encoding (ACE) form of a valid\n * string of Internationalized Domain Names for Applications (IDNA)) defined\n * in RFC 5890.\n *

\n * Note that {@code SNIHostName} objects are immutable.\n *\n * @see SNIServerName\n * @see StandardConstants#SNI_HOST_NAME\n *\n * @since 1.8\n */\npublic final class SNIHostName extends SNIServerName {\n\n // the decoded string value of the server name\n private final String hostname;\n\n /**\n * Creates an {@code SNIHostName} using the specified hostname.\n *

\n * Note that per RFC 6066,\n * the encoded server name value of a hostname is\n * {@link StandardCharsets#US_ASCII}-compliant. In this method,\n * {@code hostname} can be a user-friendly Internationalized Domain Name\n * (IDN). {@link IDN#toASCII(String, int)} is used to enforce the\n * restrictions on ASCII characters in hostnames (see\n * RFC 3490,\n * RFC 1122,\n * RFC 1123) and\n * translate the {@code hostname} into ASCII Compatible Encoding (ACE), as:\n *

\n     *     IDN.toASCII(hostname, IDN.USE_STD3_ASCII_RULES);\n     * 
\n *

\n * The {@code hostname} argument is illegal if it:\n *

    \n *
  • {@code hostname} is empty,
  • \n *
  • {@code hostname} ends with a trailing dot,
  • \n *
  • {@code hostname} is not a valid Internationalized\n * Domain Name (IDN) compliant with the RFC 3490 specification.
  • \n *
\n * @param hostname\n * the hostname of this server name\n *\n * @throws NullPointerException if {@code hostname} is {@code null}\n * @throws IllegalArgumentException if {@code hostname} is illegal\n */\n public SNIHostName(String hostname) {\n // IllegalArgumentException will be thrown if {@code hostname} is\n // not a valid IDN.\n super(StandardConstants.SNI_HOST_NAME, (hostname = IDN.toASCII(Objects.requireNonNull(hostname, \"Server name value of host_name cannot be null\"), IDN.USE_STD3_ASCII_RULES)).getBytes(StandardCharsets.US_ASCII));\n this.hostname = hostname;\n // check the validity of the string hostname\n checkHostName();\n }\n\n /**\n * Creates an {@code SNIHostName} using the specified encoded value.\n *

\n * This method is normally used to parse the encoded name value in a\n * requested SNI extension.\n *

\n * Per RFC 6066,\n * the encoded name value of a hostname is\n * {@link StandardCharsets#US_ASCII}-compliant. However, in the previous\n * version of the SNI extension (\n * RFC 4366),\n * the encoded hostname is represented as a byte string using UTF-8\n * encoding. For the purpose of version tolerance, this method allows\n * that the charset of {@code encoded} argument can be\n * {@link StandardCharsets#UTF_8}, as well as\n * {@link StandardCharsets#US_ASCII}. {@link IDN#toASCII(String)} is used\n * to translate the {@code encoded} argument into ASCII Compatible\n * Encoding (ACE) hostname.\n *

\n * It is strongly recommended that this constructor is only used to parse\n * the encoded name value in a requested SNI extension. Otherwise, to\n * comply with RFC 6066,\n * please always use {@link StandardCharsets#US_ASCII}-compliant charset\n * and enforce the restrictions on ASCII characters in hostnames (see\n * RFC 3490,\n * RFC 1122,\n * RFC 1123)\n * for {@code encoded} argument, or use\n * {@link SNIHostName#SNIHostName(String)} instead.\n *

\n * The {@code encoded} argument is illegal if it:\n *

    \n *
  • {@code encoded} is empty,
  • \n *
  • {@code encoded} ends with a trailing dot,
  • \n *
  • {@code encoded} is not encoded in\n * {@link StandardCharsets#US_ASCII} or\n * {@link StandardCharsets#UTF_8}-compliant charset,
  • \n *
  • {@code encoded} is not a valid Internationalized\n * Domain Name (IDN) compliant with the RFC 3490 specification.
  • \n *
\n *\n *

\n * Note that the {@code encoded} byte array is cloned\n * to protect against subsequent modification.\n *\n * @param encoded\n * the encoded hostname of this server name\n *\n * @throws NullPointerException if {@code encoded} is {@code null}\n * @throws IllegalArgumentException if {@code encoded} is illegal\n */\n public SNIHostName(byte[] encoded) {\n // NullPointerException will be thrown if {@code encoded} is null\n super(StandardConstants.SNI_HOST_NAME, encoded);\n // Compliance: RFC 4366 requires that the hostname is represented\n // as a byte string using UTF_8 encoding [UTF8]\n try {\n // Please don't use {@link String} constructors because they\n // do not report coding errors.\n CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);\n this.hostname = IDN.toASCII(decoder.decode(ByteBuffer.wrap(encoded)).toString(), IDN.USE_STD3_ASCII_RULES);\n } catch (RuntimeException | CharacterCodingException e) {\n throw new IllegalArgumentException(\"The encoded server name value is invalid\", e);\n }\n // check the validity of the string hostname\n checkHostName();\n }\n\n /**\n * Returns the {@link StandardCharsets#US_ASCII}-compliant hostname of\n * this {@code SNIHostName} object.\n *

\n * Note that, per\n * RFC 6066, the\n * returned hostname may be an internationalized domain name that\n * contains A-labels. See\n * RFC 5890\n * for more information about the detailed A-label specification.\n *\n * @return the {@link StandardCharsets#US_ASCII}-compliant hostname\n * of this {@code SNIHostName} object\n */\n public String getAsciiName() {\n return hostname;\n }\n\n /**\n * Compares this server name to the specified object.\n *

\n * Per RFC 6066, DNS\n * hostnames are case-insensitive. Two server hostnames are equal if,\n * and only if, they have the same name type, and the hostnames are\n * equal in a case-independent comparison.\n *\n * @param other\n * the other server name object to compare with.\n * @return true if, and only if, the {@code other} is considered\n * equal to this instance\n */\n @Override\n public boolean equals(Object other) {\n if (this == other) {\n return true;\n }\n if (other instanceof SNIHostName) {\n return hostname.equalsIgnoreCase(((SNIHostName) other).hostname);\n }\n return false;\n }\n\n /**\n * Returns a hash code value for this {@code SNIHostName}.\n *

\n * The hash code value is generated using the case-insensitive hostname\n * of this {@code SNIHostName}.\n *\n * @return a hash code value for this {@code SNIHostName}.\n */\n @Override\n public int hashCode() ", "post_mask_code": "\n\n /**\n * Returns a string representation of the object, including the DNS\n * hostname in this {@code SNIHostName} object.\n *

\n * The exact details of the representation are unspecified and subject\n * to change, but the following may be regarded as typical:\n *

\n     *     \"type=host_name (0), value={@literal }\"\n     * 
\n * The \"{@literal }\" is an ASCII representation of the hostname,\n * which may contains A-labels. For example, a returned value of an pseudo\n * hostname may look like:\n *
\n     *     \"type=host_name (0), value=www.example.com\"\n     * 
\n * or\n *
\n     *     \"type=host_name (0), value=xn--fsqu00a.xn--0zwm56d\"\n     * 
\n *

\n * Please NOTE that the exact details of the representation are unspecified\n * and subject to change.\n *\n * @return a string representation of the object.\n */\n @Override\n public String toString() {\n return \"type=host_name (0), value=\" + hostname;\n }\n\n /**\n * Creates an {@link SNIMatcher} object for {@code SNIHostName}s.\n *

\n * This method can be used by a server to verify the acceptable\n * {@code SNIHostName}s. For example,\n *

\n     *     SNIMatcher matcher =\n     *         SNIHostName.createSNIMatcher(\"www\\\\.example\\\\.com\");\n     * 
\n * will accept the hostname \"www.example.com\".\n *
\n     *     SNIMatcher matcher =\n     *         SNIHostName.createSNIMatcher(\"www\\\\.example\\\\.(com|org)\");\n     * 
\n * will accept hostnames \"www.example.com\" and \"www.example.org\".\n *\n * @param regex\n * the \n * regular expression pattern\n * representing the hostname(s) to match\n * @return a {@code SNIMatcher} object for {@code SNIHostName}s\n * @throws NullPointerException if {@code regex} is\n * {@code null}\n * @throws PatternSyntaxException if the regular expression's\n * syntax is invalid\n */\n public static SNIMatcher createSNIMatcher(String regex) {\n if (regex == null) {\n throw new NullPointerException(\"The regular expression cannot be null\");\n }\n return new SNIHostNameMatcher(regex);\n }\n\n // check the validity of the string hostname\n private void checkHostName() {\n if (hostname.isEmpty()) {\n throw new IllegalArgumentException(\"Server name value of host_name cannot be empty\");\n }\n if (hostname.endsWith(\".\")) {\n throw new IllegalArgumentException(\"Server name value of host_name cannot have the trailing dot\");\n }\n }\n\n private static final class SNIHostNameMatcher extends SNIMatcher {\n\n // the compiled representation of a regular expression.\n private final Pattern pattern;\n\n /**\n * Creates an SNIHostNameMatcher object.\n *\n * @param regex\n * the \n * regular expression pattern\n * representing the hostname(s) to match\n * @throws NullPointerException if {@code regex} is\n * {@code null}\n * @throws PatternSyntaxException if the regular expression's syntax\n * is invalid\n */\n SNIHostNameMatcher(String regex) {\n super(StandardConstants.SNI_HOST_NAME);\n pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);\n }\n\n /**\n * Attempts to match the given {@link SNIServerName}.\n *\n * @param serverName\n * the {@link SNIServerName} instance on which this matcher\n * performs match operations\n *\n * @return {@code true} if, and only if, the matcher matches the\n * given {@code serverName}\n *\n * @throws NullPointerException if {@code serverName} is {@code null}\n * @throws IllegalArgumentException if {@code serverName} is\n * not of {@code StandardConstants#SNI_HOST_NAME} type\n *\n * @see SNIServerName\n */\n @Override\n public boolean matches(SNIServerName serverName) {\n if (serverName == null) {\n throw new NullPointerException(\"The SNIServerName argument cannot be null\");\n }\n SNIHostName hostname;\n if (!(serverName instanceof SNIHostName)) {\n if (serverName.getType() != StandardConstants.SNI_HOST_NAME) {\n throw new IllegalArgumentException(\"The server name type is not host_name\");\n }\n try {\n hostname = new SNIHostName(serverName.getEncoded());\n } catch (NullPointerException | IllegalArgumentException e) {\n return false;\n }\n } else {\n hostname = (SNIHostName) serverName;\n }\n // Let's first try the ascii name matching\n String asciiName = hostname.getAsciiName();\n if (pattern.matcher(asciiName).matches()) {\n return true;\n }\n // May be an internationalized domain name, check the Unicode\n return pattern.matcher(IDN.toUnicode(asciiName)).matches();\n }\n }\n}\n"} {"task_id": "Java_2204", "language": "Java", "task_type": "single_line", "source_file": "java/github/openjdk/jdk/src/java.base/share/classes/javax/net/ssl/SNIHostName.java", "mask_start_position": 8696, "mask_end_position": 8766, "canonical_solution": "esult = 31 * result + hostname.toUpperCase(Locale.ENGLISH).hashCode();", "pre_mask_code": "package javax.net.ssl;\n\nimport java.net.IDN;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.CodingErrorAction;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.charset.CharsetDecoder;\nimport java.nio.charset.CharacterCodingException;\nimport java.util.Locale;\nimport java.util.Objects;\nimport java.util.regex.Pattern;\nimport java.util.regex.PatternSyntaxException;\n\n/**\n * Instances of this class represent a server name of type\n * {@link StandardConstants#SNI_HOST_NAME host_name} in a Server Name\n * Indication (SNI) extension.\n *

\n * As described in section 3, \"Server Name Indication\", of\n * TLS Extensions (RFC 6066),\n * \"HostName\" contains the fully qualified DNS hostname of the server, as\n * understood by the client. The encoded server name value of a hostname is\n * represented as a byte string using ASCII encoding without a trailing dot.\n * This allows the support of Internationalized Domain Names (IDN) through\n * the use of A-labels (the ASCII-Compatible Encoding (ACE) form of a valid\n * string of Internationalized Domain Names for Applications (IDNA)) defined\n * in RFC 5890.\n *

\n * Note that {@code SNIHostName} objects are immutable.\n *\n * @see SNIServerName\n * @see StandardConstants#SNI_HOST_NAME\n *\n * @since 1.8\n */\npublic final class SNIHostName extends SNIServerName {\n\n // the decoded string value of the server name\n private final String hostname;\n\n /**\n * Creates an {@code SNIHostName} using the specified hostname.\n *

\n * Note that per RFC 6066,\n * the encoded server name value of a hostname is\n * {@link StandardCharsets#US_ASCII}-compliant. In this method,\n * {@code hostname} can be a user-friendly Internationalized Domain Name\n * (IDN). {@link IDN#toASCII(String, int)} is used to enforce the\n * restrictions on ASCII characters in hostnames (see\n * RFC 3490,\n * RFC 1122,\n * RFC 1123) and\n * translate the {@code hostname} into ASCII Compatible Encoding (ACE), as:\n *

\n     *     IDN.toASCII(hostname, IDN.USE_STD3_ASCII_RULES);\n     * 
\n *

\n * The {@code hostname} argument is illegal if it:\n *

    \n *
  • {@code hostname} is empty,
  • \n *
  • {@code hostname} ends with a trailing dot,
  • \n *
  • {@code hostname} is not a valid Internationalized\n * Domain Name (IDN) compliant with the RFC 3490 specification.
  • \n *
\n * @param hostname\n * the hostname of this server name\n *\n * @throws NullPointerException if {@code hostname} is {@code null}\n * @throws IllegalArgumentException if {@code hostname} is illegal\n */\n public SNIHostName(String hostname) {\n // IllegalArgumentException will be thrown if {@code hostname} is\n // not a valid IDN.\n super(StandardConstants.SNI_HOST_NAME, (hostname = IDN.toASCII(Objects.requireNonNull(hostname, \"Server name value of host_name cannot be null\"), IDN.USE_STD3_ASCII_RULES)).getBytes(StandardCharsets.US_ASCII));\n this.hostname = hostname;\n // check the validity of the string hostname\n checkHostName();\n }\n\n /**\n * Creates an {@code SNIHostName} using the specified encoded value.\n *

\n * This method is normally used to parse the encoded name value in a\n * requested SNI extension.\n *

\n * Per RFC 6066,\n * the encoded name value of a hostname is\n * {@link StandardCharsets#US_ASCII}-compliant. However, in the previous\n * version of the SNI extension (\n * RFC 4366),\n * the encoded hostname is represented as a byte string using UTF-8\n * encoding. For the purpose of version tolerance, this method allows\n * that the charset of {@code encoded} argument can be\n * {@link StandardCharsets#UTF_8}, as well as\n * {@link StandardCharsets#US_ASCII}. {@link IDN#toASCII(String)} is used\n * to translate the {@code encoded} argument into ASCII Compatible\n * Encoding (ACE) hostname.\n *

\n * It is strongly recommended that this constructor is only used to parse\n * the encoded name value in a requested SNI extension. Otherwise, to\n * comply with RFC 6066,\n * please always use {@link StandardCharsets#US_ASCII}-compliant charset\n * and enforce the restrictions on ASCII characters in hostnames (see\n * RFC 3490,\n * RFC 1122,\n * RFC 1123)\n * for {@code encoded} argument, or use\n * {@link SNIHostName#SNIHostName(String)} instead.\n *

\n * The {@code encoded} argument is illegal if it:\n *

    \n *
  • {@code encoded} is empty,
  • \n *
  • {@code encoded} ends with a trailing dot,
  • \n *
  • {@code encoded} is not encoded in\n * {@link StandardCharsets#US_ASCII} or\n * {@link StandardCharsets#UTF_8}-compliant charset,
  • \n *
  • {@code encoded} is not a valid Internationalized\n * Domain Name (IDN) compliant with the RFC 3490 specification.
  • \n *
\n *\n *

\n * Note that the {@code encoded} byte array is cloned\n * to protect against subsequent modification.\n *\n * @param encoded\n * the encoded hostname of this server name\n *\n * @throws NullPointerException if {@code encoded} is {@code null}\n * @throws IllegalArgumentException if {@code encoded} is illegal\n */\n public SNIHostName(byte[] encoded) {\n // NullPointerException will be thrown if {@code encoded} is null\n super(StandardConstants.SNI_HOST_NAME, encoded);\n // Compliance: RFC 4366 requires that the hostname is represented\n // as a byte string using UTF_8 encoding [UTF8]\n try {\n // Please don't use {@link String} constructors because they\n // do not report coding errors.\n CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);\n this.hostname = IDN.toASCII(decoder.decode(ByteBuffer.wrap(encoded)).toString(), IDN.USE_STD3_ASCII_RULES);\n } catch (RuntimeException | CharacterCodingException e) {\n throw new IllegalArgumentException(\"The encoded server name value is invalid\", e);\n }\n // check the validity of the string hostname\n checkHostName();\n }\n\n /**\n * Returns the {@link StandardCharsets#US_ASCII}-compliant hostname of\n * this {@code SNIHostName} object.\n *

\n * Note that, per\n * RFC 6066, the\n * returned hostname may be an internationalized domain name that\n * contains A-labels. See\n * RFC 5890\n * for more information about the detailed A-label specification.\n *\n * @return the {@link StandardCharsets#US_ASCII}-compliant hostname\n * of this {@code SNIHostName} object\n */\n public String getAsciiName() {\n return hostname;\n }\n\n /**\n * Compares this server name to the specified object.\n *

\n * Per RFC 6066, DNS\n * hostnames are case-insensitive. Two server hostnames are equal if,\n * and only if, they have the same name type, and the hostnames are\n * equal in a case-independent comparison.\n *\n * @param other\n * the other server name object to compare with.\n * @return true if, and only if, the {@code other} is considered\n * equal to this instance\n */\n @Override\n public boolean equals(Object other) {\n if (this == other) {\n return true;\n }\n if (other instanceof SNIHostName) {\n return hostname.equalsIgnoreCase(((SNIHostName) other).hostname);\n }\n return false;\n }\n\n /**\n * Returns a hash code value for this {@code SNIHostName}.\n *

\n * The hash code value is generated using the case-insensitive hostname\n * of this {@code SNIHostName}.\n *\n * @return a hash code value for this {@code SNIHostName}.\n */\n @Override\n public int hashCode() {\n // 17/31: prime number to decrease collisions\n int result = 17;\n r", "post_mask_code": "\n return result;\n }\n\n /**\n * Returns a string representation of the object, including the DNS\n * hostname in this {@code SNIHostName} object.\n *

\n * The exact details of the representation are unspecified and subject\n * to change, but the following may be regarded as typical:\n *

\n     *     \"type=host_name (0), value={@literal }\"\n     * 
\n * The \"{@literal }\" is an ASCII representation of the hostname,\n * which may contains A-labels. For example, a returned value of an pseudo\n * hostname may look like:\n *
\n     *     \"type=host_name (0), value=www.example.com\"\n     * 
\n * or\n *
\n     *     \"type=host_name (0), value=xn--fsqu00a.xn--0zwm56d\"\n     * 
\n *

\n * Please NOTE that the exact details of the representation are unspecified\n * and subject to change.\n *\n * @return a string representation of the object.\n */\n @Override\n public String toString() {\n return \"type=host_name (0), value=\" + hostname;\n }\n\n /**\n * Creates an {@link SNIMatcher} object for {@code SNIHostName}s.\n *

\n * This method can be used by a server to verify the acceptable\n * {@code SNIHostName}s. For example,\n *

\n     *     SNIMatcher matcher =\n     *         SNIHostName.createSNIMatcher(\"www\\\\.example\\\\.com\");\n     * 
\n * will accept the hostname \"www.example.com\".\n *
\n     *     SNIMatcher matcher =\n     *         SNIHostName.createSNIMatcher(\"www\\\\.example\\\\.(com|org)\");\n     * 
\n * will accept hostnames \"www.example.com\" and \"www.example.org\".\n *\n * @param regex\n * the \n * regular expression pattern\n * representing the hostname(s) to match\n * @return a {@code SNIMatcher} object for {@code SNIHostName}s\n * @throws NullPointerException if {@code regex} is\n * {@code null}\n * @throws PatternSyntaxException if the regular expression's\n * syntax is invalid\n */\n public static SNIMatcher createSNIMatcher(String regex) {\n if (regex == null) {\n throw new NullPointerException(\"The regular expression cannot be null\");\n }\n return new SNIHostNameMatcher(regex);\n }\n\n // check the validity of the string hostname\n private void checkHostName() {\n if (hostname.isEmpty()) {\n throw new IllegalArgumentException(\"Server name value of host_name cannot be empty\");\n }\n if (hostname.endsWith(\".\")) {\n throw new IllegalArgumentException(\"Server name value of host_name cannot have the trailing dot\");\n }\n }\n\n private static final class SNIHostNameMatcher extends SNIMatcher {\n\n // the compiled representation of a regular expression.\n private final Pattern pattern;\n\n /**\n * Creates an SNIHostNameMatcher object.\n *\n * @param regex\n * the \n * regular expression pattern\n * representing the hostname(s) to match\n * @throws NullPointerException if {@code regex} is\n * {@code null}\n * @throws PatternSyntaxException if the regular expression's syntax\n * is invalid\n */\n SNIHostNameMatcher(String regex) {\n super(StandardConstants.SNI_HOST_NAME);\n pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);\n }\n\n /**\n * Attempts to match the given {@link SNIServerName}.\n *\n * @param serverName\n * the {@link SNIServerName} instance on which this matcher\n * performs match operations\n *\n * @return {@code true} if, and only if, the matcher matches the\n * given {@code serverName}\n *\n * @throws NullPointerException if {@code serverName} is {@code null}\n * @throws IllegalArgumentException if {@code serverName} is\n * not of {@code StandardConstants#SNI_HOST_NAME} type\n *\n * @see SNIServerName\n */\n @Override\n public boolean matches(SNIServerName serverName) {\n if (serverName == null) {\n throw new NullPointerException(\"The SNIServerName argument cannot be null\");\n }\n SNIHostName hostname;\n if (!(serverName instanceof SNIHostName)) {\n if (serverName.getType() != StandardConstants.SNI_HOST_NAME) {\n throw new IllegalArgumentException(\"The server name type is not host_name\");\n }\n try {\n hostname = new SNIHostName(serverName.getEncoded());\n } catch (NullPointerException | IllegalArgumentException e) {\n return false;\n }\n } else {\n hostname = (SNIHostName) serverName;\n }\n // Let's first try the ascii name matching\n String asciiName = hostname.getAsciiName();\n if (pattern.matcher(asciiName).matches()) {\n return true;\n }\n // May be an internationalized domain name, check the Unicode\n return pattern.matcher(IDN.toUnicode(asciiName)).matches();\n }\n }\n}\n"} {"task_id": "Java_2205", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/openjdk/jdk/src/java.base/share/classes/javax/net/ssl/SNIHostName.java", "mask_start_position": 10892, "mask_end_position": 11125, "canonical_solution": "public static SNIMatcher createSNIMatcher(String regex) {\n if (regex == null) {\n throw new NullPointerException(\"The regular expression cannot be null\");\n }\n return new SNIHostNameMatcher(regex);\n }", "pre_mask_code": "package javax.net.ssl;\n\nimport java.net.IDN;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.CodingErrorAction;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.charset.CharsetDecoder;\nimport java.nio.charset.CharacterCodingException;\nimport java.util.Locale;\nimport java.util.Objects;\nimport java.util.regex.Pattern;\nimport java.util.regex.PatternSyntaxException;\n\n/**\n * Instances of this class represent a server name of type\n * {@link StandardConstants#SNI_HOST_NAME host_name} in a Server Name\n * Indication (SNI) extension.\n *

\n * As described in section 3, \"Server Name Indication\", of\n * TLS Extensions (RFC 6066),\n * \"HostName\" contains the fully qualified DNS hostname of the server, as\n * understood by the client. The encoded server name value of a hostname is\n * represented as a byte string using ASCII encoding without a trailing dot.\n * This allows the support of Internationalized Domain Names (IDN) through\n * the use of A-labels (the ASCII-Compatible Encoding (ACE) form of a valid\n * string of Internationalized Domain Names for Applications (IDNA)) defined\n * in RFC 5890.\n *

\n * Note that {@code SNIHostName} objects are immutable.\n *\n * @see SNIServerName\n * @see StandardConstants#SNI_HOST_NAME\n *\n * @since 1.8\n */\npublic final class SNIHostName extends SNIServerName {\n\n // the decoded string value of the server name\n private final String hostname;\n\n /**\n * Creates an {@code SNIHostName} using the specified hostname.\n *

\n * Note that per RFC 6066,\n * the encoded server name value of a hostname is\n * {@link StandardCharsets#US_ASCII}-compliant. In this method,\n * {@code hostname} can be a user-friendly Internationalized Domain Name\n * (IDN). {@link IDN#toASCII(String, int)} is used to enforce the\n * restrictions on ASCII characters in hostnames (see\n * RFC 3490,\n * RFC 1122,\n * RFC 1123) and\n * translate the {@code hostname} into ASCII Compatible Encoding (ACE), as:\n *

\n     *     IDN.toASCII(hostname, IDN.USE_STD3_ASCII_RULES);\n     * 
\n *

\n * The {@code hostname} argument is illegal if it:\n *

    \n *
  • {@code hostname} is empty,
  • \n *
  • {@code hostname} ends with a trailing dot,
  • \n *
  • {@code hostname} is not a valid Internationalized\n * Domain Name (IDN) compliant with the RFC 3490 specification.
  • \n *
\n * @param hostname\n * the hostname of this server name\n *\n * @throws NullPointerException if {@code hostname} is {@code null}\n * @throws IllegalArgumentException if {@code hostname} is illegal\n */\n public SNIHostName(String hostname) {\n // IllegalArgumentException will be thrown if {@code hostname} is\n // not a valid IDN.\n super(StandardConstants.SNI_HOST_NAME, (hostname = IDN.toASCII(Objects.requireNonNull(hostname, \"Server name value of host_name cannot be null\"), IDN.USE_STD3_ASCII_RULES)).getBytes(StandardCharsets.US_ASCII));\n this.hostname = hostname;\n // check the validity of the string hostname\n checkHostName();\n }\n\n /**\n * Creates an {@code SNIHostName} using the specified encoded value.\n *

\n * This method is normally used to parse the encoded name value in a\n * requested SNI extension.\n *

\n * Per RFC 6066,\n * the encoded name value of a hostname is\n * {@link StandardCharsets#US_ASCII}-compliant. However, in the previous\n * version of the SNI extension (\n * RFC 4366),\n * the encoded hostname is represented as a byte string using UTF-8\n * encoding. For the purpose of version tolerance, this method allows\n * that the charset of {@code encoded} argument can be\n * {@link StandardCharsets#UTF_8}, as well as\n * {@link StandardCharsets#US_ASCII}. {@link IDN#toASCII(String)} is used\n * to translate the {@code encoded} argument into ASCII Compatible\n * Encoding (ACE) hostname.\n *

\n * It is strongly recommended that this constructor is only used to parse\n * the encoded name value in a requested SNI extension. Otherwise, to\n * comply with RFC 6066,\n * please always use {@link StandardCharsets#US_ASCII}-compliant charset\n * and enforce the restrictions on ASCII characters in hostnames (see\n * RFC 3490,\n * RFC 1122,\n * RFC 1123)\n * for {@code encoded} argument, or use\n * {@link SNIHostName#SNIHostName(String)} instead.\n *

\n * The {@code encoded} argument is illegal if it:\n *

    \n *
  • {@code encoded} is empty,
  • \n *
  • {@code encoded} ends with a trailing dot,
  • \n *
  • {@code encoded} is not encoded in\n * {@link StandardCharsets#US_ASCII} or\n * {@link StandardCharsets#UTF_8}-compliant charset,
  • \n *
  • {@code encoded} is not a valid Internationalized\n * Domain Name (IDN) compliant with the RFC 3490 specification.
  • \n *
\n *\n *

\n * Note that the {@code encoded} byte array is cloned\n * to protect against subsequent modification.\n *\n * @param encoded\n * the encoded hostname of this server name\n *\n * @throws NullPointerException if {@code encoded} is {@code null}\n * @throws IllegalArgumentException if {@code encoded} is illegal\n */\n public SNIHostName(byte[] encoded) {\n // NullPointerException will be thrown if {@code encoded} is null\n super(StandardConstants.SNI_HOST_NAME, encoded);\n // Compliance: RFC 4366 requires that the hostname is represented\n // as a byte string using UTF_8 encoding [UTF8]\n try {\n // Please don't use {@link String} constructors because they\n // do not report coding errors.\n CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);\n this.hostname = IDN.toASCII(decoder.decode(ByteBuffer.wrap(encoded)).toString(), IDN.USE_STD3_ASCII_RULES);\n } catch (RuntimeException | CharacterCodingException e) {\n throw new IllegalArgumentException(\"The encoded server name value is invalid\", e);\n }\n // check the validity of the string hostname\n checkHostName();\n }\n\n /**\n * Returns the {@link StandardCharsets#US_ASCII}-compliant hostname of\n * this {@code SNIHostName} object.\n *

\n * Note that, per\n * RFC 6066, the\n * returned hostname may be an internationalized domain name that\n * contains A-labels. See\n * RFC 5890\n * for more information about the detailed A-label specification.\n *\n * @return the {@link StandardCharsets#US_ASCII}-compliant hostname\n * of this {@code SNIHostName} object\n */\n public String getAsciiName() {\n return hostname;\n }\n\n /**\n * Compares this server name to the specified object.\n *

\n * Per RFC 6066, DNS\n * hostnames are case-insensitive. Two server hostnames are equal if,\n * and only if, they have the same name type, and the hostnames are\n * equal in a case-independent comparison.\n *\n * @param other\n * the other server name object to compare with.\n * @return true if, and only if, the {@code other} is considered\n * equal to this instance\n */\n @Override\n public boolean equals(Object other) {\n if (this == other) {\n return true;\n }\n if (other instanceof SNIHostName) {\n return hostname.equalsIgnoreCase(((SNIHostName) other).hostname);\n }\n return false;\n }\n\n /**\n * Returns a hash code value for this {@code SNIHostName}.\n *

\n * The hash code value is generated using the case-insensitive hostname\n * of this {@code SNIHostName}.\n *\n * @return a hash code value for this {@code SNIHostName}.\n */\n @Override\n public int hashCode() {\n // 17/31: prime number to decrease collisions\n int result = 17;\n result = 31 * result + hostname.toUpperCase(Locale.ENGLISH).hashCode();\n return result;\n }\n\n /**\n * Returns a string representation of the object, including the DNS\n * hostname in this {@code SNIHostName} object.\n *

\n * The exact details of the representation are unspecified and subject\n * to change, but the following may be regarded as typical:\n *

\n     *     \"type=host_name (0), value={@literal }\"\n     * 
\n * The \"{@literal }\" is an ASCII representation of the hostname,\n * which may contains A-labels. For example, a returned value of an pseudo\n * hostname may look like:\n *
\n     *     \"type=host_name (0), value=www.example.com\"\n     * 
\n * or\n *
\n     *     \"type=host_name (0), value=xn--fsqu00a.xn--0zwm56d\"\n     * 
\n *

\n * Please NOTE that the exact details of the representation are unspecified\n * and subject to change.\n *\n * @return a string representation of the object.\n */\n @Override\n public String toString() {\n return \"type=host_name (0), value=\" + hostname;\n }\n\n /**\n * Creates an {@link SNIMatcher} object for {@code SNIHostName}s.\n *

\n * This method can be used by a server to verify the acceptable\n * {@code SNIHostName}s. For example,\n *

\n     *     SNIMatcher matcher =\n     *         SNIHostName.createSNIMatcher(\"www\\\\.example\\\\.com\");\n     * 
\n * will accept the hostname \"www.example.com\".\n *
\n     *     SNIMatcher matcher =\n     *         SNIHostName.createSNIMatcher(\"www\\\\.example\\\\.(com|org)\");\n     * 
\n * will accept hostnames \"www.example.com\" and \"www.example.org\".\n *\n * @param regex\n * the \n * regular expression pattern\n * representing the hostname(s) to match\n * @return a {@code SNIMatcher} object for {@code SNIHostName}s\n * @throws NullPointerException if {@code regex} is\n * {@code null}\n * @throws PatternSyntaxException if the regular expression's\n * syntax is invalid\n */\n ", "post_mask_code": "\n\n // check the validity of the string hostname\n private void checkHostName() {\n if (hostname.isEmpty()) {\n throw new IllegalArgumentException(\"Server name value of host_name cannot be empty\");\n }\n if (hostname.endsWith(\".\")) {\n throw new IllegalArgumentException(\"Server name value of host_name cannot have the trailing dot\");\n }\n }\n\n private static final class SNIHostNameMatcher extends SNIMatcher {\n\n // the compiled representation of a regular expression.\n private final Pattern pattern;\n\n /**\n * Creates an SNIHostNameMatcher object.\n *\n * @param regex\n * the \n * regular expression pattern\n * representing the hostname(s) to match\n * @throws NullPointerException if {@code regex} is\n * {@code null}\n * @throws PatternSyntaxException if the regular expression's syntax\n * is invalid\n */\n SNIHostNameMatcher(String regex) {\n super(StandardConstants.SNI_HOST_NAME);\n pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);\n }\n\n /**\n * Attempts to match the given {@link SNIServerName}.\n *\n * @param serverName\n * the {@link SNIServerName} instance on which this matcher\n * performs match operations\n *\n * @return {@code true} if, and only if, the matcher matches the\n * given {@code serverName}\n *\n * @throws NullPointerException if {@code serverName} is {@code null}\n * @throws IllegalArgumentException if {@code serverName} is\n * not of {@code StandardConstants#SNI_HOST_NAME} type\n *\n * @see SNIServerName\n */\n @Override\n public boolean matches(SNIServerName serverName) {\n if (serverName == null) {\n throw new NullPointerException(\"The SNIServerName argument cannot be null\");\n }\n SNIHostName hostname;\n if (!(serverName instanceof SNIHostName)) {\n if (serverName.getType() != StandardConstants.SNI_HOST_NAME) {\n throw new IllegalArgumentException(\"The server name type is not host_name\");\n }\n try {\n hostname = new SNIHostName(serverName.getEncoded());\n } catch (NullPointerException | IllegalArgumentException e) {\n return false;\n }\n } else {\n hostname = (SNIHostName) serverName;\n }\n // Let's first try the ascii name matching\n String asciiName = hostname.getAsciiName();\n if (pattern.matcher(asciiName).matches()) {\n return true;\n }\n // May be an internationalized domain name, check the Unicode\n return pattern.matcher(IDN.toUnicode(asciiName)).matches();\n }\n }\n}\n"} {"task_id": "Java_2206", "language": "Java", "task_type": "try_statement", "source_file": "java/github/openjdk/jdk/src/java.base/share/classes/javax/net/ssl/SNIHostName.java", "mask_start_position": 13544, "mask_end_position": 13752, "canonical_solution": "try {\n hostname = new SNIHostName(serverName.getEncoded());\n } catch (NullPointerException | IllegalArgumentException e) {\n return false;\n }", "pre_mask_code": "package javax.net.ssl;\n\nimport java.net.IDN;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.CodingErrorAction;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.charset.CharsetDecoder;\nimport java.nio.charset.CharacterCodingException;\nimport java.util.Locale;\nimport java.util.Objects;\nimport java.util.regex.Pattern;\nimport java.util.regex.PatternSyntaxException;\n\n/**\n * Instances of this class represent a server name of type\n * {@link StandardConstants#SNI_HOST_NAME host_name} in a Server Name\n * Indication (SNI) extension.\n *

\n * As described in section 3, \"Server Name Indication\", of\n * TLS Extensions (RFC 6066),\n * \"HostName\" contains the fully qualified DNS hostname of the server, as\n * understood by the client. The encoded server name value of a hostname is\n * represented as a byte string using ASCII encoding without a trailing dot.\n * This allows the support of Internationalized Domain Names (IDN) through\n * the use of A-labels (the ASCII-Compatible Encoding (ACE) form of a valid\n * string of Internationalized Domain Names for Applications (IDNA)) defined\n * in RFC 5890.\n *

\n * Note that {@code SNIHostName} objects are immutable.\n *\n * @see SNIServerName\n * @see StandardConstants#SNI_HOST_NAME\n *\n * @since 1.8\n */\npublic final class SNIHostName extends SNIServerName {\n\n // the decoded string value of the server name\n private final String hostname;\n\n /**\n * Creates an {@code SNIHostName} using the specified hostname.\n *

\n * Note that per RFC 6066,\n * the encoded server name value of a hostname is\n * {@link StandardCharsets#US_ASCII}-compliant. In this method,\n * {@code hostname} can be a user-friendly Internationalized Domain Name\n * (IDN). {@link IDN#toASCII(String, int)} is used to enforce the\n * restrictions on ASCII characters in hostnames (see\n * RFC 3490,\n * RFC 1122,\n * RFC 1123) and\n * translate the {@code hostname} into ASCII Compatible Encoding (ACE), as:\n *

\n     *     IDN.toASCII(hostname, IDN.USE_STD3_ASCII_RULES);\n     * 
\n *

\n * The {@code hostname} argument is illegal if it:\n *

    \n *
  • {@code hostname} is empty,
  • \n *
  • {@code hostname} ends with a trailing dot,
  • \n *
  • {@code hostname} is not a valid Internationalized\n * Domain Name (IDN) compliant with the RFC 3490 specification.
  • \n *
\n * @param hostname\n * the hostname of this server name\n *\n * @throws NullPointerException if {@code hostname} is {@code null}\n * @throws IllegalArgumentException if {@code hostname} is illegal\n */\n public SNIHostName(String hostname) {\n // IllegalArgumentException will be thrown if {@code hostname} is\n // not a valid IDN.\n super(StandardConstants.SNI_HOST_NAME, (hostname = IDN.toASCII(Objects.requireNonNull(hostname, \"Server name value of host_name cannot be null\"), IDN.USE_STD3_ASCII_RULES)).getBytes(StandardCharsets.US_ASCII));\n this.hostname = hostname;\n // check the validity of the string hostname\n checkHostName();\n }\n\n /**\n * Creates an {@code SNIHostName} using the specified encoded value.\n *

\n * This method is normally used to parse the encoded name value in a\n * requested SNI extension.\n *

\n * Per RFC 6066,\n * the encoded name value of a hostname is\n * {@link StandardCharsets#US_ASCII}-compliant. However, in the previous\n * version of the SNI extension (\n * RFC 4366),\n * the encoded hostname is represented as a byte string using UTF-8\n * encoding. For the purpose of version tolerance, this method allows\n * that the charset of {@code encoded} argument can be\n * {@link StandardCharsets#UTF_8}, as well as\n * {@link StandardCharsets#US_ASCII}. {@link IDN#toASCII(String)} is used\n * to translate the {@code encoded} argument into ASCII Compatible\n * Encoding (ACE) hostname.\n *

\n * It is strongly recommended that this constructor is only used to parse\n * the encoded name value in a requested SNI extension. Otherwise, to\n * comply with RFC 6066,\n * please always use {@link StandardCharsets#US_ASCII}-compliant charset\n * and enforce the restrictions on ASCII characters in hostnames (see\n * RFC 3490,\n * RFC 1122,\n * RFC 1123)\n * for {@code encoded} argument, or use\n * {@link SNIHostName#SNIHostName(String)} instead.\n *

\n * The {@code encoded} argument is illegal if it:\n *

    \n *
  • {@code encoded} is empty,
  • \n *
  • {@code encoded} ends with a trailing dot,
  • \n *
  • {@code encoded} is not encoded in\n * {@link StandardCharsets#US_ASCII} or\n * {@link StandardCharsets#UTF_8}-compliant charset,
  • \n *
  • {@code encoded} is not a valid Internationalized\n * Domain Name (IDN) compliant with the RFC 3490 specification.
  • \n *
\n *\n *

\n * Note that the {@code encoded} byte array is cloned\n * to protect against subsequent modification.\n *\n * @param encoded\n * the encoded hostname of this server name\n *\n * @throws NullPointerException if {@code encoded} is {@code null}\n * @throws IllegalArgumentException if {@code encoded} is illegal\n */\n public SNIHostName(byte[] encoded) {\n // NullPointerException will be thrown if {@code encoded} is null\n super(StandardConstants.SNI_HOST_NAME, encoded);\n // Compliance: RFC 4366 requires that the hostname is represented\n // as a byte string using UTF_8 encoding [UTF8]\n try {\n // Please don't use {@link String} constructors because they\n // do not report coding errors.\n CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);\n this.hostname = IDN.toASCII(decoder.decode(ByteBuffer.wrap(encoded)).toString(), IDN.USE_STD3_ASCII_RULES);\n } catch (RuntimeException | CharacterCodingException e) {\n throw new IllegalArgumentException(\"The encoded server name value is invalid\", e);\n }\n // check the validity of the string hostname\n checkHostName();\n }\n\n /**\n * Returns the {@link StandardCharsets#US_ASCII}-compliant hostname of\n * this {@code SNIHostName} object.\n *

\n * Note that, per\n * RFC 6066, the\n * returned hostname may be an internationalized domain name that\n * contains A-labels. See\n * RFC 5890\n * for more information about the detailed A-label specification.\n *\n * @return the {@link StandardCharsets#US_ASCII}-compliant hostname\n * of this {@code SNIHostName} object\n */\n public String getAsciiName() {\n return hostname;\n }\n\n /**\n * Compares this server name to the specified object.\n *

\n * Per RFC 6066, DNS\n * hostnames are case-insensitive. Two server hostnames are equal if,\n * and only if, they have the same name type, and the hostnames are\n * equal in a case-independent comparison.\n *\n * @param other\n * the other server name object to compare with.\n * @return true if, and only if, the {@code other} is considered\n * equal to this instance\n */\n @Override\n public boolean equals(Object other) {\n if (this == other) {\n return true;\n }\n if (other instanceof SNIHostName) {\n return hostname.equalsIgnoreCase(((SNIHostName) other).hostname);\n }\n return false;\n }\n\n /**\n * Returns a hash code value for this {@code SNIHostName}.\n *

\n * The hash code value is generated using the case-insensitive hostname\n * of this {@code SNIHostName}.\n *\n * @return a hash code value for this {@code SNIHostName}.\n */\n @Override\n public int hashCode() {\n // 17/31: prime number to decrease collisions\n int result = 17;\n result = 31 * result + hostname.toUpperCase(Locale.ENGLISH).hashCode();\n return result;\n }\n\n /**\n * Returns a string representation of the object, including the DNS\n * hostname in this {@code SNIHostName} object.\n *

\n * The exact details of the representation are unspecified and subject\n * to change, but the following may be regarded as typical:\n *

\n     *     \"type=host_name (0), value={@literal }\"\n     * 
\n * The \"{@literal }\" is an ASCII representation of the hostname,\n * which may contains A-labels. For example, a returned value of an pseudo\n * hostname may look like:\n *
\n     *     \"type=host_name (0), value=www.example.com\"\n     * 
\n * or\n *
\n     *     \"type=host_name (0), value=xn--fsqu00a.xn--0zwm56d\"\n     * 
\n *

\n * Please NOTE that the exact details of the representation are unspecified\n * and subject to change.\n *\n * @return a string representation of the object.\n */\n @Override\n public String toString() {\n return \"type=host_name (0), value=\" + hostname;\n }\n\n /**\n * Creates an {@link SNIMatcher} object for {@code SNIHostName}s.\n *

\n * This method can be used by a server to verify the acceptable\n * {@code SNIHostName}s. For example,\n *

\n     *     SNIMatcher matcher =\n     *         SNIHostName.createSNIMatcher(\"www\\\\.example\\\\.com\");\n     * 
\n * will accept the hostname \"www.example.com\".\n *
\n     *     SNIMatcher matcher =\n     *         SNIHostName.createSNIMatcher(\"www\\\\.example\\\\.(com|org)\");\n     * 
\n * will accept hostnames \"www.example.com\" and \"www.example.org\".\n *\n * @param regex\n * the \n * regular expression pattern\n * representing the hostname(s) to match\n * @return a {@code SNIMatcher} object for {@code SNIHostName}s\n * @throws NullPointerException if {@code regex} is\n * {@code null}\n * @throws PatternSyntaxException if the regular expression's\n * syntax is invalid\n */\n public static SNIMatcher createSNIMatcher(String regex) {\n if (regex == null) {\n throw new NullPointerException(\"The regular expression cannot be null\");\n }\n return new SNIHostNameMatcher(regex);\n }\n\n // check the validity of the string hostname\n private void checkHostName() {\n if (hostname.isEmpty()) {\n throw new IllegalArgumentException(\"Server name value of host_name cannot be empty\");\n }\n if (hostname.endsWith(\".\")) {\n throw new IllegalArgumentException(\"Server name value of host_name cannot have the trailing dot\");\n }\n }\n\n private static final class SNIHostNameMatcher extends SNIMatcher {\n\n // the compiled representation of a regular expression.\n private final Pattern pattern;\n\n /**\n * Creates an SNIHostNameMatcher object.\n *\n * @param regex\n * the \n * regular expression pattern\n * representing the hostname(s) to match\n * @throws NullPointerException if {@code regex} is\n * {@code null}\n * @throws PatternSyntaxException if the regular expression's syntax\n * is invalid\n */\n SNIHostNameMatcher(String regex) {\n super(StandardConstants.SNI_HOST_NAME);\n pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);\n }\n\n /**\n * Attempts to match the given {@link SNIServerName}.\n *\n * @param serverName\n * the {@link SNIServerName} instance on which this matcher\n * performs match operations\n *\n * @return {@code true} if, and only if, the matcher matches the\n * given {@code serverName}\n *\n * @throws NullPointerException if {@code serverName} is {@code null}\n * @throws IllegalArgumentException if {@code serverName} is\n * not of {@code StandardConstants#SNI_HOST_NAME} type\n *\n * @see SNIServerName\n */\n @Override\n public boolean matches(SNIServerName serverName) {\n if (serverName == null) {\n throw new NullPointerException(\"The SNIServerName argument cannot be null\");\n }\n SNIHostName hostname;\n if (!(serverName instanceof SNIHostName)) {\n if (serverName.getType() != StandardConstants.SNI_HOST_NAME) {\n throw new IllegalArgumentException(\"The server name type is not host_name\");\n }\n ", "post_mask_code": "\n } else {\n hostname = (SNIHostName) serverName;\n }\n // Let's first try the ascii name matching\n String asciiName = hostname.getAsciiName();\n if (pattern.matcher(asciiName).matches()) {\n return true;\n }\n // May be an internationalized domain name, check the Unicode\n return pattern.matcher(IDN.toUnicode(asciiName)).matches();\n }\n }\n}\n"} {"task_id": "Java_2207", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openaphid/android-flip/FlipView/Demo/src/com/aphidmobile/flip/demo/FlipComplexLayoutActivity.java", "mask_start_position": 439, "mask_end_position": 501, "canonical_solution": "@Override\n public void onCreate(Bundle savedInstanceState) ", "pre_mask_code": "package com.aphidmobile.flip.demo;\n\nimport android.app.Activity;\nimport android.graphics.Bitmap;\nimport android.os.Bundle;\nimport com.aphidmobile.flip.FlipViewController;\nimport com.aphidmobile.flip.demo.adapter.TravelAdapter;\nimport com.aphidmobile.flipview.demo.R;\n\npublic class FlipComplexLayoutActivity extends Activity {\n\n private FlipViewController flipView;\n\n /**\n * Called when the activity is first created.\n */\n ", "post_mask_code": "{\n super.onCreate(savedInstanceState);\n setTitle(R.string.activity_title);\n flipView = new FlipViewController(this);\n // Use RGB_565 can reduce peak memory usage on large screen device, but it's up to you to choose the best bitmap format\n flipView.setAnimationBitmapFormat(Bitmap.Config.RGB_565);\n flipView.setAdapter(new TravelAdapter(this));\n setContentView(flipView);\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n flipView.onResume();\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n flipView.onPause();\n }\n}\n"} {"task_id": "Java_2208", "language": "Java", "task_type": "method_body", "source_file": "java/github/openaphid/android-flip/FlipView/Demo/src/com/aphidmobile/flip/demo/FlipComplexLayoutActivity.java", "mask_start_position": 1079, "mask_end_position": 1139, "canonical_solution": "{\n super.onPause();\n flipView.onPause();\n }", "pre_mask_code": "package com.aphidmobile.flip.demo;\n\nimport android.app.Activity;\nimport android.graphics.Bitmap;\nimport android.os.Bundle;\nimport com.aphidmobile.flip.FlipViewController;\nimport com.aphidmobile.flip.demo.adapter.TravelAdapter;\nimport com.aphidmobile.flipview.demo.R;\n\npublic class FlipComplexLayoutActivity extends Activity {\n\n private FlipViewController flipView;\n\n /**\n * Called when the activity is first created.\n */\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setTitle(R.string.activity_title);\n flipView = new FlipViewController(this);\n // Use RGB_565 can reduce peak memory usage on large screen device, but it's up to you to choose the best bitmap format\n flipView.setAnimationBitmapFormat(Bitmap.Config.RGB_565);\n flipView.setAdapter(new TravelAdapter(this));\n setContentView(flipView);\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n flipView.onResume();\n }\n\n @Override\n protected void onPause() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2209", "language": "Java", "task_type": "single_line", "source_file": "java/github/openaphid/android-flip/FlipView/Demo/src/com/aphidmobile/flip/demo/FlipComplexLayoutActivity.java", "mask_start_position": 619, "mask_end_position": 638, "canonical_solution": "ewController(this);", "pre_mask_code": "package com.aphidmobile.flip.demo;\n\nimport android.app.Activity;\nimport android.graphics.Bitmap;\nimport android.os.Bundle;\nimport com.aphidmobile.flip.FlipViewController;\nimport com.aphidmobile.flip.demo.adapter.TravelAdapter;\nimport com.aphidmobile.flipview.demo.R;\n\npublic class FlipComplexLayoutActivity extends Activity {\n\n private FlipViewController flipView;\n\n /**\n * Called when the activity is first created.\n */\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setTitle(R.string.activity_title);\n flipView = new FlipVi", "post_mask_code": "\n // Use RGB_565 can reduce peak memory usage on large screen device, but it's up to you to choose the best bitmap format\n flipView.setAnimationBitmapFormat(Bitmap.Config.RGB_565);\n flipView.setAdapter(new TravelAdapter(this));\n setContentView(flipView);\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n flipView.onResume();\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n flipView.onPause();\n }\n}\n"} {"task_id": "Java_2210", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/openaphid/android-flip/FlipView/Demo/src/com/aphidmobile/flip/demo/FlipComplexLayoutActivity.java", "mask_start_position": 439, "mask_end_position": 926, "canonical_solution": "@Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setTitle(R.string.activity_title);\n flipView = new FlipViewController(this);\n // Use RGB_565 can reduce peak memory usage on large screen device, but it's up to you to choose the best bitmap format\n flipView.setAnimationBitmapFormat(Bitmap.Config.RGB_565);\n flipView.setAdapter(new TravelAdapter(this));\n setContentView(flipView);\n }", "pre_mask_code": "package com.aphidmobile.flip.demo;\n\nimport android.app.Activity;\nimport android.graphics.Bitmap;\nimport android.os.Bundle;\nimport com.aphidmobile.flip.FlipViewController;\nimport com.aphidmobile.flip.demo.adapter.TravelAdapter;\nimport com.aphidmobile.flipview.demo.R;\n\npublic class FlipComplexLayoutActivity extends Activity {\n\n private FlipViewController flipView;\n\n /**\n * Called when the activity is first created.\n */\n ", "post_mask_code": "\n\n @Override\n protected void onResume() {\n super.onResume();\n flipView.onResume();\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n flipView.onPause();\n }\n}\n"} {"task_id": "Java_2211", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/apache/gobblin/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/version/FileStatusAware.java", "mask_start_position": 457, "mask_end_position": 498, "canonical_solution": "public Set getFileStatuses();", "pre_mask_code": "package org.apache.gobblin.data.management.version;\n\nimport java.util.Set;\nimport org.apache.hadoop.fs.FileStatus;\n\n/**\n * A {@link FileSystemDatasetVersion} that is aware {@link FileStatus}s or its paths\n */\npublic interface FileStatusAware {\n\n /**\n * Get the set of {@link FileStatus}s that are included in this dataset version or the {@link FileStatus} of the dataset\n * version itself (In which case the set has one file status).\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2212", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/geronimo/plugins/axis/geronimo-axis-builder/src/main/java/org/apache/geronimo/axis/builder/LightweightTypeInfoBuilder.java", "mask_start_position": 3525, "mask_end_position": 3680, "canonical_solution": "private void populateInternalTypeInfo(Class javaClass, QName typeQName, SchemaTypeKey key, TypeInfo.UpdatableTypeInfo typeInfo) throws DeploymentException ", "pre_mask_code": "package org.apache.geronimo.axis.builder;\n\nimport java.beans.IntrospectionException;\nimport java.beans.Introspector;\nimport java.beans.PropertyDescriptor;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.xml.namespace.QName;\nimport org.apache.axis.description.ElementDesc;\nimport org.apache.axis.description.FieldDesc;\nimport org.apache.axis.encoding.ser.ArrayDeserializerFactory;\nimport org.apache.axis.encoding.ser.ArraySerializerFactory;\nimport org.apache.axis.encoding.ser.BeanDeserializerFactory;\nimport org.apache.axis.encoding.ser.BeanSerializerFactory;\nimport org.apache.geronimo.axis.client.TypeInfo;\nimport org.apache.geronimo.common.DeploymentException;\nimport org.apache.geronimo.kernel.ClassLoading;\nimport org.apache.geronimo.webservices.builder.SchemaTypeKey;\nimport org.apache.geronimo.webservices.builder.WSDescriptorParser;\nimport org.apache.openejb.jee.JavaWsdlMapping;\nimport org.apache.xmlbeans.SchemaParticle;\nimport org.apache.xmlbeans.SchemaType;\nimport org.osgi.framework.Bundle;\n\npublic class LightweightTypeInfoBuilder implements TypeInfoBuilder {\n\n private final Bundle cl;\n\n private final Map schemaTypeKeyToSchemaTypeMap;\n\n private final Set wrapperElementQNames;\n\n public LightweightTypeInfoBuilder(Bundle bundle, Map schemaTypeKeyToSchemaTypeMap, Set wrapperElementQNames) {\n this.cl = bundle;\n this.schemaTypeKeyToSchemaTypeMap = schemaTypeKeyToSchemaTypeMap;\n this.wrapperElementQNames = wrapperElementQNames;\n }\n\n public List buildTypeInfo(JavaWsdlMapping mapping) throws DeploymentException {\n List typeInfoList = new ArrayList();\n for (Iterator iterator = schemaTypeKeyToSchemaTypeMap.keySet().iterator(); iterator.hasNext(); ) {\n SchemaTypeKey key = (SchemaTypeKey) iterator.next();\n if (!key.isElement() && !key.isAnonymous()) {\n QName typeQName = key.getqName();\n String namespace = typeQName.getNamespaceURI();\n String packageName = WSDescriptorParser.getPackageFromNamespace(namespace, mapping);\n String classShortName = typeQName.getLocalPart();\n String className = packageName + \".\" + classShortName;\n Class clazz = null;\n try {\n clazz = ClassLoading.loadClass(className, cl);\n } catch (ClassNotFoundException e) {\n throw new DeploymentException(\"Could not load java type\", e);\n }\n Class serializerFactoryClass = BeanSerializerFactory.class;\n Class deserializerFactoryClass = BeanDeserializerFactory.class;\n if (clazz.isArray()) {\n serializerFactoryClass = ArraySerializerFactory.class;\n deserializerFactoryClass = ArrayDeserializerFactory.class;\n }\n TypeInfo.UpdatableTypeInfo internalTypeInfo = new TypeInfo.UpdatableTypeInfo();\n internalTypeInfo.setClazz(clazz);\n internalTypeInfo.setQName(typeQName);\n internalTypeInfo.setSerializerClass(serializerFactoryClass);\n internalTypeInfo.setDeserializerClass(deserializerFactoryClass);\n populateInternalTypeInfo(clazz, typeQName, key, internalTypeInfo);\n typeInfoList.add(internalTypeInfo.buildTypeInfo());\n }\n }\n return typeInfoList;\n }\n\n ", "post_mask_code": "{\n SchemaType schemaType = (SchemaType) schemaTypeKeyToSchemaTypeMap.get(key);\n if (schemaType == null) {\n throw new DeploymentException(\"Schema type key \" + key + \" not found in analyzed schema: \" + schemaTypeKeyToSchemaTypeMap);\n }\n typeInfo.setCanSearchParents(schemaType.getDerivationType() == SchemaType.DT_RESTRICTION);\n Map nameToType = new HashMap();\n if (null == schemaType.getContentModel()) {\n } else if (SchemaParticle.SEQUENCE == schemaType.getContentModel().getParticleType() || SchemaParticle.ALL == schemaType.getContentModel().getParticleType()) {\n SchemaParticle[] properties = schemaType.getContentModel().getParticleChildren();\n for (int i = 0; i < properties.length; i++) {\n SchemaParticle parameter = properties[i];\n // throw new DeploymentException(parameter.getName() + \" is not an element in schema \" + schemaType.getName());\n nameToType.put(parameter.getName(), parameter);\n }\n } else if (SchemaParticle.ELEMENT == schemaType.getContentModel().getParticleType()) {\n SchemaParticle parameter = schemaType.getContentModel();\n nameToType.put(parameter.getName(), parameter);\n } else {\n throw new DeploymentException(\"Only all, choice and sequence particle types are supported.\" + \" SchemaType name =\" + schemaType.getName());\n }\n PropertyDescriptor[] descriptors;\n try {\n descriptors = Introspector.getBeanInfo(javaClass).getPropertyDescriptors();\n } catch (IntrospectionException e) {\n throw new DeploymentException(\"Class \" + javaClass + \" is not a valid javabean\", e);\n }\n Map nameToClass = new HashMap();\n for (int i = 0; i < descriptors.length; i++) {\n nameToClass.put(descriptors[i].getName(), descriptors[i].getPropertyType());\n }\n int idx = 0;\n FieldDesc[] fields = new FieldDesc[nameToType.size()];\n typeInfo.setFields(fields);\n for (Iterator iter = nameToType.entrySet().iterator(); iter.hasNext(); ) {\n Map.Entry entry = (Map.Entry) iter.next();\n QName fieldQName = (QName) entry.getKey();\n String fieldName = fieldQName.getLocalPart();\n SchemaParticle particle = (SchemaParticle) entry.getValue();\n ElementDesc elementDesc = new ElementDesc();\n elementDesc.setFieldName(fieldName);\n Class javaType = (Class) nameToClass.get(fieldName);\n if (null == javaType) {\n throw new DeploymentException(\"Field \" + fieldName + \" is not defined by class \" + javaClass.getName());\n }\n elementDesc.setNillable(particle.isNillable());\n elementDesc.setXmlName(fieldQName);\n elementDesc.setXmlType(particle.getType().getName());\n if (javaType.isArray()) {\n elementDesc.setMinOccurs(particle.getIntMinOccurs());\n elementDesc.setMaxOccurs(particle.getIntMaxOccurs());\n // TODO axis seems to have the wrong name for this property based on how it is used\n elementDesc.setMaxOccursUnbounded(particle.getIntMaxOccurs() > 1);\n }\n fields[idx++] = elementDesc;\n }\n }\n}\n"} {"task_id": "Java_2213", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/geronimo/plugins/axis/geronimo-axis-builder/src/main/java/org/apache/geronimo/axis/builder/LightweightTypeInfoBuilder.java", "mask_start_position": 4065, "mask_end_position": 4084, "canonical_solution": "pe = new HashMap();", "pre_mask_code": "package org.apache.geronimo.axis.builder;\n\nimport java.beans.IntrospectionException;\nimport java.beans.Introspector;\nimport java.beans.PropertyDescriptor;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.xml.namespace.QName;\nimport org.apache.axis.description.ElementDesc;\nimport org.apache.axis.description.FieldDesc;\nimport org.apache.axis.encoding.ser.ArrayDeserializerFactory;\nimport org.apache.axis.encoding.ser.ArraySerializerFactory;\nimport org.apache.axis.encoding.ser.BeanDeserializerFactory;\nimport org.apache.axis.encoding.ser.BeanSerializerFactory;\nimport org.apache.geronimo.axis.client.TypeInfo;\nimport org.apache.geronimo.common.DeploymentException;\nimport org.apache.geronimo.kernel.ClassLoading;\nimport org.apache.geronimo.webservices.builder.SchemaTypeKey;\nimport org.apache.geronimo.webservices.builder.WSDescriptorParser;\nimport org.apache.openejb.jee.JavaWsdlMapping;\nimport org.apache.xmlbeans.SchemaParticle;\nimport org.apache.xmlbeans.SchemaType;\nimport org.osgi.framework.Bundle;\n\npublic class LightweightTypeInfoBuilder implements TypeInfoBuilder {\n\n private final Bundle cl;\n\n private final Map schemaTypeKeyToSchemaTypeMap;\n\n private final Set wrapperElementQNames;\n\n public LightweightTypeInfoBuilder(Bundle bundle, Map schemaTypeKeyToSchemaTypeMap, Set wrapperElementQNames) {\n this.cl = bundle;\n this.schemaTypeKeyToSchemaTypeMap = schemaTypeKeyToSchemaTypeMap;\n this.wrapperElementQNames = wrapperElementQNames;\n }\n\n public List buildTypeInfo(JavaWsdlMapping mapping) throws DeploymentException {\n List typeInfoList = new ArrayList();\n for (Iterator iterator = schemaTypeKeyToSchemaTypeMap.keySet().iterator(); iterator.hasNext(); ) {\n SchemaTypeKey key = (SchemaTypeKey) iterator.next();\n if (!key.isElement() && !key.isAnonymous()) {\n QName typeQName = key.getqName();\n String namespace = typeQName.getNamespaceURI();\n String packageName = WSDescriptorParser.getPackageFromNamespace(namespace, mapping);\n String classShortName = typeQName.getLocalPart();\n String className = packageName + \".\" + classShortName;\n Class clazz = null;\n try {\n clazz = ClassLoading.loadClass(className, cl);\n } catch (ClassNotFoundException e) {\n throw new DeploymentException(\"Could not load java type\", e);\n }\n Class serializerFactoryClass = BeanSerializerFactory.class;\n Class deserializerFactoryClass = BeanDeserializerFactory.class;\n if (clazz.isArray()) {\n serializerFactoryClass = ArraySerializerFactory.class;\n deserializerFactoryClass = ArrayDeserializerFactory.class;\n }\n TypeInfo.UpdatableTypeInfo internalTypeInfo = new TypeInfo.UpdatableTypeInfo();\n internalTypeInfo.setClazz(clazz);\n internalTypeInfo.setQName(typeQName);\n internalTypeInfo.setSerializerClass(serializerFactoryClass);\n internalTypeInfo.setDeserializerClass(deserializerFactoryClass);\n populateInternalTypeInfo(clazz, typeQName, key, internalTypeInfo);\n typeInfoList.add(internalTypeInfo.buildTypeInfo());\n }\n }\n return typeInfoList;\n }\n\n private void populateInternalTypeInfo(Class javaClass, QName typeQName, SchemaTypeKey key, TypeInfo.UpdatableTypeInfo typeInfo) throws DeploymentException {\n SchemaType schemaType = (SchemaType) schemaTypeKeyToSchemaTypeMap.get(key);\n if (schemaType == null) {\n throw new DeploymentException(\"Schema type key \" + key + \" not found in analyzed schema: \" + schemaTypeKeyToSchemaTypeMap);\n }\n typeInfo.setCanSearchParents(schemaType.getDerivationType() == SchemaType.DT_RESTRICTION);\n Map nameToTy", "post_mask_code": "\n if (null == schemaType.getContentModel()) {\n } else if (SchemaParticle.SEQUENCE == schemaType.getContentModel().getParticleType() || SchemaParticle.ALL == schemaType.getContentModel().getParticleType()) {\n SchemaParticle[] properties = schemaType.getContentModel().getParticleChildren();\n for (int i = 0; i < properties.length; i++) {\n SchemaParticle parameter = properties[i];\n // throw new DeploymentException(parameter.getName() + \" is not an element in schema \" + schemaType.getName());\n nameToType.put(parameter.getName(), parameter);\n }\n } else if (SchemaParticle.ELEMENT == schemaType.getContentModel().getParticleType()) {\n SchemaParticle parameter = schemaType.getContentModel();\n nameToType.put(parameter.getName(), parameter);\n } else {\n throw new DeploymentException(\"Only all, choice and sequence particle types are supported.\" + \" SchemaType name =\" + schemaType.getName());\n }\n PropertyDescriptor[] descriptors;\n try {\n descriptors = Introspector.getBeanInfo(javaClass).getPropertyDescriptors();\n } catch (IntrospectionException e) {\n throw new DeploymentException(\"Class \" + javaClass + \" is not a valid javabean\", e);\n }\n Map nameToClass = new HashMap();\n for (int i = 0; i < descriptors.length; i++) {\n nameToClass.put(descriptors[i].getName(), descriptors[i].getPropertyType());\n }\n int idx = 0;\n FieldDesc[] fields = new FieldDesc[nameToType.size()];\n typeInfo.setFields(fields);\n for (Iterator iter = nameToType.entrySet().iterator(); iter.hasNext(); ) {\n Map.Entry entry = (Map.Entry) iter.next();\n QName fieldQName = (QName) entry.getKey();\n String fieldName = fieldQName.getLocalPart();\n SchemaParticle particle = (SchemaParticle) entry.getValue();\n ElementDesc elementDesc = new ElementDesc();\n elementDesc.setFieldName(fieldName);\n Class javaType = (Class) nameToClass.get(fieldName);\n if (null == javaType) {\n throw new DeploymentException(\"Field \" + fieldName + \" is not defined by class \" + javaClass.getName());\n }\n elementDesc.setNillable(particle.isNillable());\n elementDesc.setXmlName(fieldQName);\n elementDesc.setXmlType(particle.getType().getName());\n if (javaType.isArray()) {\n elementDesc.setMinOccurs(particle.getIntMinOccurs());\n elementDesc.setMaxOccurs(particle.getIntMaxOccurs());\n // TODO axis seems to have the wrong name for this property based on how it is used\n elementDesc.setMaxOccursUnbounded(particle.getIntMaxOccurs() > 1);\n }\n fields[idx++] = elementDesc;\n }\n }\n}\n"} {"task_id": "Java_2214", "language": "Java", "task_type": "for_statement", "source_file": "java/github/apache/geronimo/plugins/axis/geronimo-axis-builder/src/main/java/org/apache/geronimo/axis/builder/LightweightTypeInfoBuilder.java", "mask_start_position": 4411, "mask_end_position": 4720, "canonical_solution": "for (int i = 0; i < properties.length; i++) {\n SchemaParticle parameter = properties[i];\n // throw new DeploymentException(parameter.getName() + \" is not an element in schema \" + schemaType.getName());\n nameToType.put(parameter.getName(), parameter);\n }", "pre_mask_code": "package org.apache.geronimo.axis.builder;\n\nimport java.beans.IntrospectionException;\nimport java.beans.Introspector;\nimport java.beans.PropertyDescriptor;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.xml.namespace.QName;\nimport org.apache.axis.description.ElementDesc;\nimport org.apache.axis.description.FieldDesc;\nimport org.apache.axis.encoding.ser.ArrayDeserializerFactory;\nimport org.apache.axis.encoding.ser.ArraySerializerFactory;\nimport org.apache.axis.encoding.ser.BeanDeserializerFactory;\nimport org.apache.axis.encoding.ser.BeanSerializerFactory;\nimport org.apache.geronimo.axis.client.TypeInfo;\nimport org.apache.geronimo.common.DeploymentException;\nimport org.apache.geronimo.kernel.ClassLoading;\nimport org.apache.geronimo.webservices.builder.SchemaTypeKey;\nimport org.apache.geronimo.webservices.builder.WSDescriptorParser;\nimport org.apache.openejb.jee.JavaWsdlMapping;\nimport org.apache.xmlbeans.SchemaParticle;\nimport org.apache.xmlbeans.SchemaType;\nimport org.osgi.framework.Bundle;\n\npublic class LightweightTypeInfoBuilder implements TypeInfoBuilder {\n\n private final Bundle cl;\n\n private final Map schemaTypeKeyToSchemaTypeMap;\n\n private final Set wrapperElementQNames;\n\n public LightweightTypeInfoBuilder(Bundle bundle, Map schemaTypeKeyToSchemaTypeMap, Set wrapperElementQNames) {\n this.cl = bundle;\n this.schemaTypeKeyToSchemaTypeMap = schemaTypeKeyToSchemaTypeMap;\n this.wrapperElementQNames = wrapperElementQNames;\n }\n\n public List buildTypeInfo(JavaWsdlMapping mapping) throws DeploymentException {\n List typeInfoList = new ArrayList();\n for (Iterator iterator = schemaTypeKeyToSchemaTypeMap.keySet().iterator(); iterator.hasNext(); ) {\n SchemaTypeKey key = (SchemaTypeKey) iterator.next();\n if (!key.isElement() && !key.isAnonymous()) {\n QName typeQName = key.getqName();\n String namespace = typeQName.getNamespaceURI();\n String packageName = WSDescriptorParser.getPackageFromNamespace(namespace, mapping);\n String classShortName = typeQName.getLocalPart();\n String className = packageName + \".\" + classShortName;\n Class clazz = null;\n try {\n clazz = ClassLoading.loadClass(className, cl);\n } catch (ClassNotFoundException e) {\n throw new DeploymentException(\"Could not load java type\", e);\n }\n Class serializerFactoryClass = BeanSerializerFactory.class;\n Class deserializerFactoryClass = BeanDeserializerFactory.class;\n if (clazz.isArray()) {\n serializerFactoryClass = ArraySerializerFactory.class;\n deserializerFactoryClass = ArrayDeserializerFactory.class;\n }\n TypeInfo.UpdatableTypeInfo internalTypeInfo = new TypeInfo.UpdatableTypeInfo();\n internalTypeInfo.setClazz(clazz);\n internalTypeInfo.setQName(typeQName);\n internalTypeInfo.setSerializerClass(serializerFactoryClass);\n internalTypeInfo.setDeserializerClass(deserializerFactoryClass);\n populateInternalTypeInfo(clazz, typeQName, key, internalTypeInfo);\n typeInfoList.add(internalTypeInfo.buildTypeInfo());\n }\n }\n return typeInfoList;\n }\n\n private void populateInternalTypeInfo(Class javaClass, QName typeQName, SchemaTypeKey key, TypeInfo.UpdatableTypeInfo typeInfo) throws DeploymentException {\n SchemaType schemaType = (SchemaType) schemaTypeKeyToSchemaTypeMap.get(key);\n if (schemaType == null) {\n throw new DeploymentException(\"Schema type key \" + key + \" not found in analyzed schema: \" + schemaTypeKeyToSchemaTypeMap);\n }\n typeInfo.setCanSearchParents(schemaType.getDerivationType() == SchemaType.DT_RESTRICTION);\n Map nameToType = new HashMap();\n if (null == schemaType.getContentModel()) {\n } else if (SchemaParticle.SEQUENCE == schemaType.getContentModel().getParticleType() || SchemaParticle.ALL == schemaType.getContentModel().getParticleType()) {\n SchemaParticle[] properties = schemaType.getContentModel().getParticleChildren();\n ", "post_mask_code": "\n } else if (SchemaParticle.ELEMENT == schemaType.getContentModel().getParticleType()) {\n SchemaParticle parameter = schemaType.getContentModel();\n nameToType.put(parameter.getName(), parameter);\n } else {\n throw new DeploymentException(\"Only all, choice and sequence particle types are supported.\" + \" SchemaType name =\" + schemaType.getName());\n }\n PropertyDescriptor[] descriptors;\n try {\n descriptors = Introspector.getBeanInfo(javaClass).getPropertyDescriptors();\n } catch (IntrospectionException e) {\n throw new DeploymentException(\"Class \" + javaClass + \" is not a valid javabean\", e);\n }\n Map nameToClass = new HashMap();\n for (int i = 0; i < descriptors.length; i++) {\n nameToClass.put(descriptors[i].getName(), descriptors[i].getPropertyType());\n }\n int idx = 0;\n FieldDesc[] fields = new FieldDesc[nameToType.size()];\n typeInfo.setFields(fields);\n for (Iterator iter = nameToType.entrySet().iterator(); iter.hasNext(); ) {\n Map.Entry entry = (Map.Entry) iter.next();\n QName fieldQName = (QName) entry.getKey();\n String fieldName = fieldQName.getLocalPart();\n SchemaParticle particle = (SchemaParticle) entry.getValue();\n ElementDesc elementDesc = new ElementDesc();\n elementDesc.setFieldName(fieldName);\n Class javaType = (Class) nameToClass.get(fieldName);\n if (null == javaType) {\n throw new DeploymentException(\"Field \" + fieldName + \" is not defined by class \" + javaClass.getName());\n }\n elementDesc.setNillable(particle.isNillable());\n elementDesc.setXmlName(fieldQName);\n elementDesc.setXmlType(particle.getType().getName());\n if (javaType.isArray()) {\n elementDesc.setMinOccurs(particle.getIntMinOccurs());\n elementDesc.setMaxOccurs(particle.getIntMaxOccurs());\n // TODO axis seems to have the wrong name for this property based on how it is used\n elementDesc.setMaxOccursUnbounded(particle.getIntMaxOccurs() > 1);\n }\n fields[idx++] = elementDesc;\n }\n }\n}\n"} {"task_id": "Java_2215", "language": "Java", "task_type": "try_statement", "source_file": "java/github/apache/geronimo/plugins/axis/geronimo-axis-builder/src/main/java/org/apache/geronimo/axis/builder/LightweightTypeInfoBuilder.java", "mask_start_position": 2359, "mask_end_position": 2584, "canonical_solution": "try {\n clazz = ClassLoading.loadClass(className, cl);\n } catch (ClassNotFoundException e) {\n throw new DeploymentException(\"Could not load java type\", e);\n }", "pre_mask_code": "package org.apache.geronimo.axis.builder;\n\nimport java.beans.IntrospectionException;\nimport java.beans.Introspector;\nimport java.beans.PropertyDescriptor;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.xml.namespace.QName;\nimport org.apache.axis.description.ElementDesc;\nimport org.apache.axis.description.FieldDesc;\nimport org.apache.axis.encoding.ser.ArrayDeserializerFactory;\nimport org.apache.axis.encoding.ser.ArraySerializerFactory;\nimport org.apache.axis.encoding.ser.BeanDeserializerFactory;\nimport org.apache.axis.encoding.ser.BeanSerializerFactory;\nimport org.apache.geronimo.axis.client.TypeInfo;\nimport org.apache.geronimo.common.DeploymentException;\nimport org.apache.geronimo.kernel.ClassLoading;\nimport org.apache.geronimo.webservices.builder.SchemaTypeKey;\nimport org.apache.geronimo.webservices.builder.WSDescriptorParser;\nimport org.apache.openejb.jee.JavaWsdlMapping;\nimport org.apache.xmlbeans.SchemaParticle;\nimport org.apache.xmlbeans.SchemaType;\nimport org.osgi.framework.Bundle;\n\npublic class LightweightTypeInfoBuilder implements TypeInfoBuilder {\n\n private final Bundle cl;\n\n private final Map schemaTypeKeyToSchemaTypeMap;\n\n private final Set wrapperElementQNames;\n\n public LightweightTypeInfoBuilder(Bundle bundle, Map schemaTypeKeyToSchemaTypeMap, Set wrapperElementQNames) {\n this.cl = bundle;\n this.schemaTypeKeyToSchemaTypeMap = schemaTypeKeyToSchemaTypeMap;\n this.wrapperElementQNames = wrapperElementQNames;\n }\n\n public List buildTypeInfo(JavaWsdlMapping mapping) throws DeploymentException {\n List typeInfoList = new ArrayList();\n for (Iterator iterator = schemaTypeKeyToSchemaTypeMap.keySet().iterator(); iterator.hasNext(); ) {\n SchemaTypeKey key = (SchemaTypeKey) iterator.next();\n if (!key.isElement() && !key.isAnonymous()) {\n QName typeQName = key.getqName();\n String namespace = typeQName.getNamespaceURI();\n String packageName = WSDescriptorParser.getPackageFromNamespace(namespace, mapping);\n String classShortName = typeQName.getLocalPart();\n String className = packageName + \".\" + classShortName;\n Class clazz = null;\n ", "post_mask_code": "\n Class serializerFactoryClass = BeanSerializerFactory.class;\n Class deserializerFactoryClass = BeanDeserializerFactory.class;\n if (clazz.isArray()) {\n serializerFactoryClass = ArraySerializerFactory.class;\n deserializerFactoryClass = ArrayDeserializerFactory.class;\n }\n TypeInfo.UpdatableTypeInfo internalTypeInfo = new TypeInfo.UpdatableTypeInfo();\n internalTypeInfo.setClazz(clazz);\n internalTypeInfo.setQName(typeQName);\n internalTypeInfo.setSerializerClass(serializerFactoryClass);\n internalTypeInfo.setDeserializerClass(deserializerFactoryClass);\n populateInternalTypeInfo(clazz, typeQName, key, internalTypeInfo);\n typeInfoList.add(internalTypeInfo.buildTypeInfo());\n }\n }\n return typeInfoList;\n }\n\n private void populateInternalTypeInfo(Class javaClass, QName typeQName, SchemaTypeKey key, TypeInfo.UpdatableTypeInfo typeInfo) throws DeploymentException {\n SchemaType schemaType = (SchemaType) schemaTypeKeyToSchemaTypeMap.get(key);\n if (schemaType == null) {\n throw new DeploymentException(\"Schema type key \" + key + \" not found in analyzed schema: \" + schemaTypeKeyToSchemaTypeMap);\n }\n typeInfo.setCanSearchParents(schemaType.getDerivationType() == SchemaType.DT_RESTRICTION);\n Map nameToType = new HashMap();\n if (null == schemaType.getContentModel()) {\n } else if (SchemaParticle.SEQUENCE == schemaType.getContentModel().getParticleType() || SchemaParticle.ALL == schemaType.getContentModel().getParticleType()) {\n SchemaParticle[] properties = schemaType.getContentModel().getParticleChildren();\n for (int i = 0; i < properties.length; i++) {\n SchemaParticle parameter = properties[i];\n // throw new DeploymentException(parameter.getName() + \" is not an element in schema \" + schemaType.getName());\n nameToType.put(parameter.getName(), parameter);\n }\n } else if (SchemaParticle.ELEMENT == schemaType.getContentModel().getParticleType()) {\n SchemaParticle parameter = schemaType.getContentModel();\n nameToType.put(parameter.getName(), parameter);\n } else {\n throw new DeploymentException(\"Only all, choice and sequence particle types are supported.\" + \" SchemaType name =\" + schemaType.getName());\n }\n PropertyDescriptor[] descriptors;\n try {\n descriptors = Introspector.getBeanInfo(javaClass).getPropertyDescriptors();\n } catch (IntrospectionException e) {\n throw new DeploymentException(\"Class \" + javaClass + \" is not a valid javabean\", e);\n }\n Map nameToClass = new HashMap();\n for (int i = 0; i < descriptors.length; i++) {\n nameToClass.put(descriptors[i].getName(), descriptors[i].getPropertyType());\n }\n int idx = 0;\n FieldDesc[] fields = new FieldDesc[nameToType.size()];\n typeInfo.setFields(fields);\n for (Iterator iter = nameToType.entrySet().iterator(); iter.hasNext(); ) {\n Map.Entry entry = (Map.Entry) iter.next();\n QName fieldQName = (QName) entry.getKey();\n String fieldName = fieldQName.getLocalPart();\n SchemaParticle particle = (SchemaParticle) entry.getValue();\n ElementDesc elementDesc = new ElementDesc();\n elementDesc.setFieldName(fieldName);\n Class javaType = (Class) nameToClass.get(fieldName);\n if (null == javaType) {\n throw new DeploymentException(\"Field \" + fieldName + \" is not defined by class \" + javaClass.getName());\n }\n elementDesc.setNillable(particle.isNillable());\n elementDesc.setXmlName(fieldQName);\n elementDesc.setXmlType(particle.getType().getName());\n if (javaType.isArray()) {\n elementDesc.setMinOccurs(particle.getIntMinOccurs());\n elementDesc.setMaxOccurs(particle.getIntMaxOccurs());\n // TODO axis seems to have the wrong name for this property based on how it is used\n elementDesc.setMaxOccursUnbounded(particle.getIntMaxOccurs() > 1);\n }\n fields[idx++] = elementDesc;\n }\n }\n}\n"} {"task_id": "Java_2216", "language": "Java", "task_type": "method_signature", "source_file": "java/github/BaseXdb/basex/basex-core/src/main/java/org/basex/query/util/list/ExprList.java", "mask_start_position": 874, "mask_end_position": 942, "canonical_solution": "public static Expr[] concat(final Expr[] source, final Expr... add) ", "pre_mask_code": "package org.basex.query.util.list;\n\nimport org.basex.query.expr.*;\nimport org.basex.util.*;\nimport org.basex.util.list.*;\n\n/**\n * Resizable-array implementation for XQuery expressions.\n *\n * @author Christian Gruen\n */\npublic final class ExprList extends ObjectList {\n\n public ExprList() {\n this(1);\n }\n\n /**\n * Constructor with initial capacity.\n * @param capacity array capacity\n */\n public ExprList(final long capacity) {\n super(new Expr[Array.checkCapacity(capacity)]);\n }\n\n /**\n * Constructor, specifying an initial entry.\n * @param element array capacity\n */\n public ExprList(final Expr element) {\n super(element);\n size = 1;\n }\n\n /**\n * Concatenates entries.\n * @param source source elements\n * @param add elements to be added\n * @return array\n */\n ", "post_mask_code": "{\n final int sl = source.length, al = add.length;\n final Expr[] tmp = new Expr[sl + al];\n Array.copy(source, sl, tmp);\n Array.copyFromStart(add, al, tmp, sl);\n return tmp;\n }\n\n @Override\n protected Expr[] newArray(final int s) {\n return new Expr[s];\n }\n}\n"} {"task_id": "Java_2217", "language": "Java", "task_type": "method_body", "source_file": "java/github/BaseXdb/basex/basex-core/src/main/java/org/basex/query/util/list/ExprList.java", "mask_start_position": 942, "mask_end_position": 1154, "canonical_solution": "{\n final int sl = source.length, al = add.length;\n final Expr[] tmp = new Expr[sl + al];\n Array.copy(source, sl, tmp);\n Array.copyFromStart(add, al, tmp, sl);\n return tmp;\n }", "pre_mask_code": "package org.basex.query.util.list;\n\nimport org.basex.query.expr.*;\nimport org.basex.util.*;\nimport org.basex.util.list.*;\n\n/**\n * Resizable-array implementation for XQuery expressions.\n *\n * @author Christian Gruen\n */\npublic final class ExprList extends ObjectList {\n\n public ExprList() {\n this(1);\n }\n\n /**\n * Constructor with initial capacity.\n * @param capacity array capacity\n */\n public ExprList(final long capacity) {\n super(new Expr[Array.checkCapacity(capacity)]);\n }\n\n /**\n * Constructor, specifying an initial entry.\n * @param element array capacity\n */\n public ExprList(final Expr element) {\n super(element);\n size = 1;\n }\n\n /**\n * Concatenates entries.\n * @param source source elements\n * @param add elements to be added\n * @return array\n */\n public static Expr[] concat(final Expr[] source, final Expr... add) ", "post_mask_code": "\n\n @Override\n protected Expr[] newArray(final int s) {\n return new Expr[s];\n }\n}\n"} {"task_id": "Java_2218", "language": "Java", "task_type": "single_line", "source_file": "java/github/BaseXdb/basex/basex-core/src/main/java/org/basex/query/util/list/ExprList.java", "mask_start_position": 1228, "mask_end_position": 1242, "canonical_solution": "n new Expr[s];", "pre_mask_code": "package org.basex.query.util.list;\n\nimport org.basex.query.expr.*;\nimport org.basex.util.*;\nimport org.basex.util.list.*;\n\n/**\n * Resizable-array implementation for XQuery expressions.\n *\n * @author Christian Gruen\n */\npublic final class ExprList extends ObjectList {\n\n public ExprList() {\n this(1);\n }\n\n /**\n * Constructor with initial capacity.\n * @param capacity array capacity\n */\n public ExprList(final long capacity) {\n super(new Expr[Array.checkCapacity(capacity)]);\n }\n\n /**\n * Constructor, specifying an initial entry.\n * @param element array capacity\n */\n public ExprList(final Expr element) {\n super(element);\n size = 1;\n }\n\n /**\n * Concatenates entries.\n * @param source source elements\n * @param add elements to be added\n * @return array\n */\n public static Expr[] concat(final Expr[] source, final Expr... add) {\n final int sl = source.length, al = add.length;\n final Expr[] tmp = new Expr[sl + al];\n Array.copy(source, sl, tmp);\n Array.copyFromStart(add, al, tmp, sl);\n return tmp;\n }\n\n @Override\n protected Expr[] newArray(final int s) {\n retur", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2219", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/BaseXdb/basex/basex-core/src/main/java/org/basex/query/util/list/ExprList.java", "mask_start_position": 874, "mask_end_position": 1154, "canonical_solution": "public static Expr[] concat(final Expr[] source, final Expr... add) {\n final int sl = source.length, al = add.length;\n final Expr[] tmp = new Expr[sl + al];\n Array.copy(source, sl, tmp);\n Array.copyFromStart(add, al, tmp, sl);\n return tmp;\n }", "pre_mask_code": "package org.basex.query.util.list;\n\nimport org.basex.query.expr.*;\nimport org.basex.util.*;\nimport org.basex.util.list.*;\n\n/**\n * Resizable-array implementation for XQuery expressions.\n *\n * @author Christian Gruen\n */\npublic final class ExprList extends ObjectList {\n\n public ExprList() {\n this(1);\n }\n\n /**\n * Constructor with initial capacity.\n * @param capacity array capacity\n */\n public ExprList(final long capacity) {\n super(new Expr[Array.checkCapacity(capacity)]);\n }\n\n /**\n * Constructor, specifying an initial entry.\n * @param element array capacity\n */\n public ExprList(final Expr element) {\n super(element);\n size = 1;\n }\n\n /**\n * Concatenates entries.\n * @param source source elements\n * @param add elements to be added\n * @return array\n */\n ", "post_mask_code": "\n\n @Override\n protected Expr[] newArray(final int s) {\n return new Expr[s];\n }\n}\n"} {"task_id": "Java_2220", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ControlSystemStudio/cs-studio/applications/apputil/apputil-plugins/org.csstudio.utility.eliza/src/org/csstudio/utility/eliza/TestMain.java", "mask_start_position": 212, "mask_end_position": 251, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "package org.csstudio.utility.eliza;\n\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Shell;\n\n/**\n * Standalone SWT Test of ElizaGUI\n * @author Kay Kasemir\n */\npublic class TestMain {\n\n ", "post_mask_code": "{\n final Display display = new Display();\n final Shell shell = new Shell(display);\n shell.setBounds(400, 100, 300, 350);\n new ElizaGUI(shell);\n shell.open();\n // Message loop left to the application\n while (!shell.isDisposed()) if (!display.readAndDispatch())\n display.sleep();\n display.dispose();\n }\n}\n"} {"task_id": "Java_2221", "language": "Java", "task_type": "method_body", "source_file": "java/github/ControlSystemStudio/cs-studio/applications/apputil/apputil-plugins/org.csstudio.utility.eliza/src/org/csstudio/utility/eliza/TestMain.java", "mask_start_position": 251, "mask_end_position": 621, "canonical_solution": "{\n final Display display = new Display();\n final Shell shell = new Shell(display);\n shell.setBounds(400, 100, 300, 350);\n new ElizaGUI(shell);\n shell.open();\n // Message loop left to the application\n while (!shell.isDisposed()) if (!display.readAndDispatch())\n display.sleep();\n display.dispose();\n }", "pre_mask_code": "package org.csstudio.utility.eliza;\n\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Shell;\n\n/**\n * Standalone SWT Test of ElizaGUI\n * @author Kay Kasemir\n */\npublic class TestMain {\n\n public static void main(String[] args) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2222", "language": "Java", "task_type": "single_line", "source_file": "java/github/ControlSystemStudio/cs-studio/applications/apputil/apputil-plugins/org.csstudio.utility.eliza/src/org/csstudio/utility/eliza/TestMain.java", "mask_start_position": 440, "mask_end_position": 443, "canonical_solution": "();", "pre_mask_code": "package org.csstudio.utility.eliza;\n\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Shell;\n\n/**\n * Standalone SWT Test of ElizaGUI\n * @author Kay Kasemir\n */\npublic class TestMain {\n\n public static void main(String[] args) {\n final Display display = new Display();\n final Shell shell = new Shell(display);\n shell.setBounds(400, 100, 300, 350);\n new ElizaGUI(shell);\n shell.open", "post_mask_code": "\n // Message loop left to the application\n while (!shell.isDisposed()) if (!display.readAndDispatch())\n display.sleep();\n display.dispose();\n }\n}\n"} {"task_id": "Java_2223", "language": "Java", "task_type": "while_statement", "source_file": "java/github/ControlSystemStudio/cs-studio/applications/apputil/apputil-plugins/org.csstudio.utility.eliza/src/org/csstudio/utility/eliza/TestMain.java", "mask_start_position": 500, "mask_end_position": 588, "canonical_solution": "while (!shell.isDisposed()) if (!display.readAndDispatch())\n display.sleep();", "pre_mask_code": "package org.csstudio.utility.eliza;\n\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Shell;\n\n/**\n * Standalone SWT Test of ElizaGUI\n * @author Kay Kasemir\n */\npublic class TestMain {\n\n public static void main(String[] args) {\n final Display display = new Display();\n final Shell shell = new Shell(display);\n shell.setBounds(400, 100, 300, 350);\n new ElizaGUI(shell);\n shell.open();\n // Message loop left to the application\n ", "post_mask_code": "\n display.dispose();\n }\n}\n"} {"task_id": "Java_2224", "language": "Java", "task_type": "method_signature", "source_file": "java/github/nuxeo/nuxeo/nuxeo-features/nuxeo-platform-oauth/src/main/java/org/nuxeo/ecm/platform/oauth2/providers/AbstractOAuth2UserEmailProvider.java", "mask_start_position": 498, "mask_end_position": 619, "canonical_solution": "@Override\n protected String getOrCreateServiceUser(HttpServletRequest request, String accessToken) throws IOException ", "pre_mask_code": "package org.nuxeo.ecm.platform.oauth2.providers;\n\nimport org.nuxeo.ecm.platform.oauth2.tokens.NuxeoOAuth2Token;\nimport javax.servlet.http.HttpServletRequest;\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * {@link org.nuxeo.ecm.platform.oauth2.providers.OAuth2ServiceProvider} that relies on the user's email as key.\n *\n * @since 7.3\n */\npublic abstract class AbstractOAuth2UserEmailProvider extends NuxeoOAuth2ServiceProvider {\n\n ", "post_mask_code": "{\n String email = getUserEmail(accessToken);\n String userId = getServiceUserId(email);\n if (userId == null) {\n String nuxeoLogin = request.getUserPrincipal().getName();\n Map fields = new HashMap<>();\n fields.put(NuxeoOAuth2Token.KEY_SERVICE_LOGIN, email);\n userId = getServiceUserStore().store(nuxeoLogin, fields);\n }\n return userId;\n }\n\n @Override\n protected String getServiceUserId(String email) {\n Map filter = new HashMap<>();\n filter.put(NuxeoOAuth2Token.KEY_SERVICE_LOGIN, email);\n return getServiceUserStore().find(filter);\n }\n\n protected abstract String getUserEmail(String accessToken) throws IOException;\n}\n"} {"task_id": "Java_2225", "language": "Java", "task_type": "method_body", "source_file": "java/github/nuxeo/nuxeo/nuxeo-features/nuxeo-platform-oauth/src/main/java/org/nuxeo/ecm/platform/oauth2/providers/AbstractOAuth2UserEmailProvider.java", "mask_start_position": 1121, "mask_end_position": 1302, "canonical_solution": "{\n Map filter = new HashMap<>();\n filter.put(NuxeoOAuth2Token.KEY_SERVICE_LOGIN, email);\n return getServiceUserStore().find(filter);\n }", "pre_mask_code": "package org.nuxeo.ecm.platform.oauth2.providers;\n\nimport org.nuxeo.ecm.platform.oauth2.tokens.NuxeoOAuth2Token;\nimport javax.servlet.http.HttpServletRequest;\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * {@link org.nuxeo.ecm.platform.oauth2.providers.OAuth2ServiceProvider} that relies on the user's email as key.\n *\n * @since 7.3\n */\npublic abstract class AbstractOAuth2UserEmailProvider extends NuxeoOAuth2ServiceProvider {\n\n @Override\n protected String getOrCreateServiceUser(HttpServletRequest request, String accessToken) throws IOException {\n String email = getUserEmail(accessToken);\n String userId = getServiceUserId(email);\n if (userId == null) {\n String nuxeoLogin = request.getUserPrincipal().getName();\n Map fields = new HashMap<>();\n fields.put(NuxeoOAuth2Token.KEY_SERVICE_LOGIN, email);\n userId = getServiceUserStore().store(nuxeoLogin, fields);\n }\n return userId;\n }\n\n @Override\n protected String getServiceUserId(String email) ", "post_mask_code": "\n\n protected abstract String getUserEmail(String accessToken) throws IOException;\n}\n"} {"task_id": "Java_2226", "language": "Java", "task_type": "single_line", "source_file": "java/github/nuxeo/nuxeo/nuxeo-features/nuxeo-platform-oauth/src/main/java/org/nuxeo/ecm/platform/oauth2/providers/AbstractOAuth2UserEmailProvider.java", "mask_start_position": 664, "mask_end_position": 670, "canonical_solution": "oken);", "pre_mask_code": "package org.nuxeo.ecm.platform.oauth2.providers;\n\nimport org.nuxeo.ecm.platform.oauth2.tokens.NuxeoOAuth2Token;\nimport javax.servlet.http.HttpServletRequest;\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * {@link org.nuxeo.ecm.platform.oauth2.providers.OAuth2ServiceProvider} that relies on the user's email as key.\n *\n * @since 7.3\n */\npublic abstract class AbstractOAuth2UserEmailProvider extends NuxeoOAuth2ServiceProvider {\n\n @Override\n protected String getOrCreateServiceUser(HttpServletRequest request, String accessToken) throws IOException {\n String email = getUserEmail(accessT", "post_mask_code": "\n String userId = getServiceUserId(email);\n if (userId == null) {\n String nuxeoLogin = request.getUserPrincipal().getName();\n Map fields = new HashMap<>();\n fields.put(NuxeoOAuth2Token.KEY_SERVICE_LOGIN, email);\n userId = getServiceUserStore().store(nuxeoLogin, fields);\n }\n return userId;\n }\n\n @Override\n protected String getServiceUserId(String email) {\n Map filter = new HashMap<>();\n filter.put(NuxeoOAuth2Token.KEY_SERVICE_LOGIN, email);\n return getServiceUserStore().find(filter);\n }\n\n protected abstract String getUserEmail(String accessToken) throws IOException;\n}\n"} {"task_id": "Java_2227", "language": "Java", "task_type": "method_signature", "source_file": "java/github/hortonworks/cloudbreak/mock-infrastructure/src/generated/com/sequenceiq/mock/swagger/model/ApiConfig.java", "mask_start_position": 7293, "mask_end_position": 7357, "canonical_solution": "public void setValidationState(ValidationState validationState) ", "pre_mask_code": "package com.sequenceiq.mock.swagger.model;\n\nimport java.util.Objects;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.sequenceiq.mock.swagger.model.ValidationState;\nimport io.swagger.annotations.ApiModel;\nimport io.swagger.annotations.ApiModelProperty;\nimport org.springframework.validation.annotation.Validated;\nimport javax.validation.Valid;\nimport javax.validation.constraints.*;\n\n/**\n * Model for a configuration parameter. When an entry's <i>value</i> property is not available, it means the entry is not configured. This means that the default value for the entry, if any, will be used. Setting a value to <i>null</i> also can be used to unset any previously set value for the parameter, reverting to the default value (if any).\n */\n@ApiModel(description = \"Model for a configuration parameter. When an entry's value property is not available, it means the entry is not configured. This means that the default value for the entry, if any, will be used. Setting a value to null also can be used to unset any previously set value for the parameter, reverting to the default value (if any).\")\n@Validated\n@javax.annotation.Generated(value = \"io.swagger.codegen.languages.SpringCodegen\", date = \"2020-10-26T08:01:08.932+01:00\")\npublic class ApiConfig {\n\n @JsonProperty(\"name\")\n private String name = null;\n\n @JsonProperty(\"value\")\n private String value = null;\n\n @JsonProperty(\"required\")\n private Boolean required = null;\n\n @JsonProperty(\"default\")\n private String _default = null;\n\n @JsonProperty(\"displayName\")\n private String displayName = null;\n\n @JsonProperty(\"description\")\n private String description = null;\n\n @JsonProperty(\"relatedName\")\n private String relatedName = null;\n\n @JsonProperty(\"sensitive\")\n private Boolean sensitive = null;\n\n @JsonProperty(\"validationState\")\n private ValidationState validationState = null;\n\n @JsonProperty(\"validationMessage\")\n private String validationMessage = null;\n\n @JsonProperty(\"validationWarningsSuppressed\")\n private Boolean validationWarningsSuppressed = null;\n\n public ApiConfig name(String name) {\n this.name = name;\n return this;\n }\n\n /**\n * Readonly. The canonical name that identifies this configuration parameter.\n * @return name\n */\n @ApiModelProperty(value = \"Readonly. The canonical name that identifies this configuration parameter.\")\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public ApiConfig value(String value) {\n this.value = value;\n return this;\n }\n\n /**\n * The user-defined value. When absent, the default value (if any) will be used. Can also be absent, when enumerating allowed configs.\n * @return value\n */\n @ApiModelProperty(value = \"The user-defined value. When absent, the default value (if any) will be used. Can also be absent, when enumerating allowed configs.\")\n public String getValue() {\n return value;\n }\n\n public void setValue(String value) {\n this.value = value;\n }\n\n public ApiConfig required(Boolean required) {\n this.required = required;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. Whether this configuration is required for the object. If any required configuration is not set, operations on the object may not work.\n * @return required\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. Whether this configuration is required for the object. If any required configuration is not set, operations on the object may not work.\")\n public Boolean isRequired() {\n return required;\n }\n\n public void setRequired(Boolean required) {\n this.required = required;\n }\n\n public ApiConfig _default(String _default) {\n this._default = _default;\n return this;\n }\n\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. The default value.\")\n public String getDefault() {\n return _default;\n }\n\n public void setDefault(String _default) {\n this._default = _default;\n }\n\n public ApiConfig displayName(String displayName) {\n this.displayName = displayName;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. A user-friendly name of the parameters, as would have been shown in the web UI.\n * @return displayName\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. A user-friendly name of the parameters, as would have been shown in the web UI.\")\n public String getDisplayName() {\n return displayName;\n }\n\n public void setDisplayName(String displayName) {\n this.displayName = displayName;\n }\n\n public ApiConfig description(String description) {\n this.description = description;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. A textual description of the parameter.\n * @return description\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. A textual description of the parameter.\")\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public ApiConfig relatedName(String relatedName) {\n this.relatedName = relatedName;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. If applicable, contains the related configuration variable used by the source project.\n * @return relatedName\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. If applicable, contains the related configuration variable used by the source project.\")\n public String getRelatedName() {\n return relatedName;\n }\n\n public void setRelatedName(String relatedName) {\n this.relatedName = relatedName;\n }\n\n public ApiConfig sensitive(Boolean sensitive) {\n this.sensitive = sensitive;\n return this;\n }\n\n /**\n * Readonly. Whether this configuration is sensitive, i.e. contains information such as passwords, which might affect how the value of this configuration might be shared by the caller. Available since v14.\n * @return sensitive\n */\n @ApiModelProperty(value = \"Readonly. Whether this configuration is sensitive, i.e. contains information such as passwords, which might affect how the value of this configuration might be shared by the caller. Available since v14.\")\n public Boolean isSensitive() {\n return sensitive;\n }\n\n public void setSensitive(Boolean sensitive) {\n this.sensitive = sensitive;\n }\n\n public ApiConfig validationState(ValidationState validationState) {\n this.validationState = validationState;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. State of the configuration parameter after validation.\n * @return validationState\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. State of the configuration parameter after validation.\")\n @Valid\n public ValidationState getValidationState() {\n return validationState;\n }\n\n ", "post_mask_code": "{\n this.validationState = validationState;\n }\n\n public ApiConfig validationMessage(String validationMessage) {\n this.validationMessage = validationMessage;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. A message explaining the parameter's validation state.\n * @return validationMessage\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. A message explaining the parameter's validation state.\")\n public String getValidationMessage() {\n return validationMessage;\n }\n\n public void setValidationMessage(String validationMessage) {\n this.validationMessage = validationMessage;\n }\n\n public ApiConfig validationWarningsSuppressed(Boolean validationWarningsSuppressed) {\n this.validationWarningsSuppressed = validationWarningsSuppressed;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. Whether validation warnings associated with this parameter are suppressed. In general, suppressed validation warnings are hidden in the Cloudera Manager UI. Configurations that do not produce warnings will not contain this field.\n * @return validationWarningsSuppressed\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. Whether validation warnings associated with this parameter are suppressed. In general, suppressed validation warnings are hidden in the Cloudera Manager UI. Configurations that do not produce warnings will not contain this field.\")\n public Boolean isValidationWarningsSuppressed() {\n return validationWarningsSuppressed;\n }\n\n public void setValidationWarningsSuppressed(Boolean validationWarningsSuppressed) {\n this.validationWarningsSuppressed = validationWarningsSuppressed;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ApiConfig apiConfig = (ApiConfig) o;\n return Objects.equals(this.name, apiConfig.name) && Objects.equals(this.value, apiConfig.value) && Objects.equals(this.required, apiConfig.required) && Objects.equals(this._default, apiConfig._default) && Objects.equals(this.displayName, apiConfig.displayName) && Objects.equals(this.description, apiConfig.description) && Objects.equals(this.relatedName, apiConfig.relatedName) && Objects.equals(this.sensitive, apiConfig.sensitive) && Objects.equals(this.validationState, apiConfig.validationState) && Objects.equals(this.validationMessage, apiConfig.validationMessage) && Objects.equals(this.validationWarningsSuppressed, apiConfig.validationWarningsSuppressed);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value, required, _default, displayName, description, relatedName, sensitive, validationState, validationMessage, validationWarningsSuppressed);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ApiConfig {\\n\");\n sb.append(\" name: \").append(toIndentedString(name)).append(\"\\n\");\n sb.append(\" value: \").append(toIndentedString(value)).append(\"\\n\");\n sb.append(\" required: \").append(toIndentedString(required)).append(\"\\n\");\n sb.append(\" _default: \").append(toIndentedString(_default)).append(\"\\n\");\n sb.append(\" displayName: \").append(toIndentedString(displayName)).append(\"\\n\");\n sb.append(\" description: \").append(toIndentedString(description)).append(\"\\n\");\n sb.append(\" relatedName: \").append(toIndentedString(relatedName)).append(\"\\n\");\n sb.append(\" sensitive: \").append(toIndentedString(sensitive)).append(\"\\n\");\n sb.append(\" validationState: \").append(toIndentedString(validationState)).append(\"\\n\");\n sb.append(\" validationMessage: \").append(toIndentedString(validationMessage)).append(\"\\n\");\n sb.append(\" validationWarningsSuppressed: \").append(toIndentedString(validationWarningsSuppressed)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_2228", "language": "Java", "task_type": "method_body", "source_file": "java/github/hortonworks/cloudbreak/mock-infrastructure/src/generated/com/sequenceiq/mock/swagger/model/ApiConfig.java", "mask_start_position": 6846, "mask_end_position": 6922, "canonical_solution": "{\n this.validationState = validationState;\n return this;\n }", "pre_mask_code": "package com.sequenceiq.mock.swagger.model;\n\nimport java.util.Objects;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.sequenceiq.mock.swagger.model.ValidationState;\nimport io.swagger.annotations.ApiModel;\nimport io.swagger.annotations.ApiModelProperty;\nimport org.springframework.validation.annotation.Validated;\nimport javax.validation.Valid;\nimport javax.validation.constraints.*;\n\n/**\n * Model for a configuration parameter. When an entry's <i>value</i> property is not available, it means the entry is not configured. This means that the default value for the entry, if any, will be used. Setting a value to <i>null</i> also can be used to unset any previously set value for the parameter, reverting to the default value (if any).\n */\n@ApiModel(description = \"Model for a configuration parameter. When an entry's value property is not available, it means the entry is not configured. This means that the default value for the entry, if any, will be used. Setting a value to null also can be used to unset any previously set value for the parameter, reverting to the default value (if any).\")\n@Validated\n@javax.annotation.Generated(value = \"io.swagger.codegen.languages.SpringCodegen\", date = \"2020-10-26T08:01:08.932+01:00\")\npublic class ApiConfig {\n\n @JsonProperty(\"name\")\n private String name = null;\n\n @JsonProperty(\"value\")\n private String value = null;\n\n @JsonProperty(\"required\")\n private Boolean required = null;\n\n @JsonProperty(\"default\")\n private String _default = null;\n\n @JsonProperty(\"displayName\")\n private String displayName = null;\n\n @JsonProperty(\"description\")\n private String description = null;\n\n @JsonProperty(\"relatedName\")\n private String relatedName = null;\n\n @JsonProperty(\"sensitive\")\n private Boolean sensitive = null;\n\n @JsonProperty(\"validationState\")\n private ValidationState validationState = null;\n\n @JsonProperty(\"validationMessage\")\n private String validationMessage = null;\n\n @JsonProperty(\"validationWarningsSuppressed\")\n private Boolean validationWarningsSuppressed = null;\n\n public ApiConfig name(String name) {\n this.name = name;\n return this;\n }\n\n /**\n * Readonly. The canonical name that identifies this configuration parameter.\n * @return name\n */\n @ApiModelProperty(value = \"Readonly. The canonical name that identifies this configuration parameter.\")\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public ApiConfig value(String value) {\n this.value = value;\n return this;\n }\n\n /**\n * The user-defined value. When absent, the default value (if any) will be used. Can also be absent, when enumerating allowed configs.\n * @return value\n */\n @ApiModelProperty(value = \"The user-defined value. When absent, the default value (if any) will be used. Can also be absent, when enumerating allowed configs.\")\n public String getValue() {\n return value;\n }\n\n public void setValue(String value) {\n this.value = value;\n }\n\n public ApiConfig required(Boolean required) {\n this.required = required;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. Whether this configuration is required for the object. If any required configuration is not set, operations on the object may not work.\n * @return required\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. Whether this configuration is required for the object. If any required configuration is not set, operations on the object may not work.\")\n public Boolean isRequired() {\n return required;\n }\n\n public void setRequired(Boolean required) {\n this.required = required;\n }\n\n public ApiConfig _default(String _default) {\n this._default = _default;\n return this;\n }\n\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. The default value.\")\n public String getDefault() {\n return _default;\n }\n\n public void setDefault(String _default) {\n this._default = _default;\n }\n\n public ApiConfig displayName(String displayName) {\n this.displayName = displayName;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. A user-friendly name of the parameters, as would have been shown in the web UI.\n * @return displayName\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. A user-friendly name of the parameters, as would have been shown in the web UI.\")\n public String getDisplayName() {\n return displayName;\n }\n\n public void setDisplayName(String displayName) {\n this.displayName = displayName;\n }\n\n public ApiConfig description(String description) {\n this.description = description;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. A textual description of the parameter.\n * @return description\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. A textual description of the parameter.\")\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public ApiConfig relatedName(String relatedName) {\n this.relatedName = relatedName;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. If applicable, contains the related configuration variable used by the source project.\n * @return relatedName\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. If applicable, contains the related configuration variable used by the source project.\")\n public String getRelatedName() {\n return relatedName;\n }\n\n public void setRelatedName(String relatedName) {\n this.relatedName = relatedName;\n }\n\n public ApiConfig sensitive(Boolean sensitive) {\n this.sensitive = sensitive;\n return this;\n }\n\n /**\n * Readonly. Whether this configuration is sensitive, i.e. contains information such as passwords, which might affect how the value of this configuration might be shared by the caller. Available since v14.\n * @return sensitive\n */\n @ApiModelProperty(value = \"Readonly. Whether this configuration is sensitive, i.e. contains information such as passwords, which might affect how the value of this configuration might be shared by the caller. Available since v14.\")\n public Boolean isSensitive() {\n return sensitive;\n }\n\n public void setSensitive(Boolean sensitive) {\n this.sensitive = sensitive;\n }\n\n public ApiConfig validationState(ValidationState validationState) ", "post_mask_code": "\n\n /**\n * Readonly. Requires \\\"full\\\" view. State of the configuration parameter after validation.\n * @return validationState\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. State of the configuration parameter after validation.\")\n @Valid\n public ValidationState getValidationState() {\n return validationState;\n }\n\n public void setValidationState(ValidationState validationState) {\n this.validationState = validationState;\n }\n\n public ApiConfig validationMessage(String validationMessage) {\n this.validationMessage = validationMessage;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. A message explaining the parameter's validation state.\n * @return validationMessage\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. A message explaining the parameter's validation state.\")\n public String getValidationMessage() {\n return validationMessage;\n }\n\n public void setValidationMessage(String validationMessage) {\n this.validationMessage = validationMessage;\n }\n\n public ApiConfig validationWarningsSuppressed(Boolean validationWarningsSuppressed) {\n this.validationWarningsSuppressed = validationWarningsSuppressed;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. Whether validation warnings associated with this parameter are suppressed. In general, suppressed validation warnings are hidden in the Cloudera Manager UI. Configurations that do not produce warnings will not contain this field.\n * @return validationWarningsSuppressed\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. Whether validation warnings associated with this parameter are suppressed. In general, suppressed validation warnings are hidden in the Cloudera Manager UI. Configurations that do not produce warnings will not contain this field.\")\n public Boolean isValidationWarningsSuppressed() {\n return validationWarningsSuppressed;\n }\n\n public void setValidationWarningsSuppressed(Boolean validationWarningsSuppressed) {\n this.validationWarningsSuppressed = validationWarningsSuppressed;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ApiConfig apiConfig = (ApiConfig) o;\n return Objects.equals(this.name, apiConfig.name) && Objects.equals(this.value, apiConfig.value) && Objects.equals(this.required, apiConfig.required) && Objects.equals(this._default, apiConfig._default) && Objects.equals(this.displayName, apiConfig.displayName) && Objects.equals(this.description, apiConfig.description) && Objects.equals(this.relatedName, apiConfig.relatedName) && Objects.equals(this.sensitive, apiConfig.sensitive) && Objects.equals(this.validationState, apiConfig.validationState) && Objects.equals(this.validationMessage, apiConfig.validationMessage) && Objects.equals(this.validationWarningsSuppressed, apiConfig.validationWarningsSuppressed);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value, required, _default, displayName, description, relatedName, sensitive, validationState, validationMessage, validationWarningsSuppressed);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ApiConfig {\\n\");\n sb.append(\" name: \").append(toIndentedString(name)).append(\"\\n\");\n sb.append(\" value: \").append(toIndentedString(value)).append(\"\\n\");\n sb.append(\" required: \").append(toIndentedString(required)).append(\"\\n\");\n sb.append(\" _default: \").append(toIndentedString(_default)).append(\"\\n\");\n sb.append(\" displayName: \").append(toIndentedString(displayName)).append(\"\\n\");\n sb.append(\" description: \").append(toIndentedString(description)).append(\"\\n\");\n sb.append(\" relatedName: \").append(toIndentedString(relatedName)).append(\"\\n\");\n sb.append(\" sensitive: \").append(toIndentedString(sensitive)).append(\"\\n\");\n sb.append(\" validationState: \").append(toIndentedString(validationState)).append(\"\\n\");\n sb.append(\" validationMessage: \").append(toIndentedString(validationMessage)).append(\"\\n\");\n sb.append(\" validationWarningsSuppressed: \").append(toIndentedString(validationWarningsSuppressed)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_2229", "language": "Java", "task_type": "single_line", "source_file": "java/github/hortonworks/cloudbreak/mock-infrastructure/src/generated/com/sequenceiq/mock/swagger/model/ApiConfig.java", "mask_start_position": 4148, "mask_end_position": 4163, "canonical_solution": "eturn _default;", "pre_mask_code": "package com.sequenceiq.mock.swagger.model;\n\nimport java.util.Objects;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.sequenceiq.mock.swagger.model.ValidationState;\nimport io.swagger.annotations.ApiModel;\nimport io.swagger.annotations.ApiModelProperty;\nimport org.springframework.validation.annotation.Validated;\nimport javax.validation.Valid;\nimport javax.validation.constraints.*;\n\n/**\n * Model for a configuration parameter. When an entry's <i>value</i> property is not available, it means the entry is not configured. This means that the default value for the entry, if any, will be used. Setting a value to <i>null</i> also can be used to unset any previously set value for the parameter, reverting to the default value (if any).\n */\n@ApiModel(description = \"Model for a configuration parameter. When an entry's value property is not available, it means the entry is not configured. This means that the default value for the entry, if any, will be used. Setting a value to null also can be used to unset any previously set value for the parameter, reverting to the default value (if any).\")\n@Validated\n@javax.annotation.Generated(value = \"io.swagger.codegen.languages.SpringCodegen\", date = \"2020-10-26T08:01:08.932+01:00\")\npublic class ApiConfig {\n\n @JsonProperty(\"name\")\n private String name = null;\n\n @JsonProperty(\"value\")\n private String value = null;\n\n @JsonProperty(\"required\")\n private Boolean required = null;\n\n @JsonProperty(\"default\")\n private String _default = null;\n\n @JsonProperty(\"displayName\")\n private String displayName = null;\n\n @JsonProperty(\"description\")\n private String description = null;\n\n @JsonProperty(\"relatedName\")\n private String relatedName = null;\n\n @JsonProperty(\"sensitive\")\n private Boolean sensitive = null;\n\n @JsonProperty(\"validationState\")\n private ValidationState validationState = null;\n\n @JsonProperty(\"validationMessage\")\n private String validationMessage = null;\n\n @JsonProperty(\"validationWarningsSuppressed\")\n private Boolean validationWarningsSuppressed = null;\n\n public ApiConfig name(String name) {\n this.name = name;\n return this;\n }\n\n /**\n * Readonly. The canonical name that identifies this configuration parameter.\n * @return name\n */\n @ApiModelProperty(value = \"Readonly. The canonical name that identifies this configuration parameter.\")\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public ApiConfig value(String value) {\n this.value = value;\n return this;\n }\n\n /**\n * The user-defined value. When absent, the default value (if any) will be used. Can also be absent, when enumerating allowed configs.\n * @return value\n */\n @ApiModelProperty(value = \"The user-defined value. When absent, the default value (if any) will be used. Can also be absent, when enumerating allowed configs.\")\n public String getValue() {\n return value;\n }\n\n public void setValue(String value) {\n this.value = value;\n }\n\n public ApiConfig required(Boolean required) {\n this.required = required;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. Whether this configuration is required for the object. If any required configuration is not set, operations on the object may not work.\n * @return required\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. Whether this configuration is required for the object. If any required configuration is not set, operations on the object may not work.\")\n public Boolean isRequired() {\n return required;\n }\n\n public void setRequired(Boolean required) {\n this.required = required;\n }\n\n public ApiConfig _default(String _default) {\n this._default = _default;\n return this;\n }\n\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. The default value.\")\n public String getDefault() {\n r", "post_mask_code": "\n }\n\n public void setDefault(String _default) {\n this._default = _default;\n }\n\n public ApiConfig displayName(String displayName) {\n this.displayName = displayName;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. A user-friendly name of the parameters, as would have been shown in the web UI.\n * @return displayName\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. A user-friendly name of the parameters, as would have been shown in the web UI.\")\n public String getDisplayName() {\n return displayName;\n }\n\n public void setDisplayName(String displayName) {\n this.displayName = displayName;\n }\n\n public ApiConfig description(String description) {\n this.description = description;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. A textual description of the parameter.\n * @return description\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. A textual description of the parameter.\")\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public ApiConfig relatedName(String relatedName) {\n this.relatedName = relatedName;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. If applicable, contains the related configuration variable used by the source project.\n * @return relatedName\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. If applicable, contains the related configuration variable used by the source project.\")\n public String getRelatedName() {\n return relatedName;\n }\n\n public void setRelatedName(String relatedName) {\n this.relatedName = relatedName;\n }\n\n public ApiConfig sensitive(Boolean sensitive) {\n this.sensitive = sensitive;\n return this;\n }\n\n /**\n * Readonly. Whether this configuration is sensitive, i.e. contains information such as passwords, which might affect how the value of this configuration might be shared by the caller. Available since v14.\n * @return sensitive\n */\n @ApiModelProperty(value = \"Readonly. Whether this configuration is sensitive, i.e. contains information such as passwords, which might affect how the value of this configuration might be shared by the caller. Available since v14.\")\n public Boolean isSensitive() {\n return sensitive;\n }\n\n public void setSensitive(Boolean sensitive) {\n this.sensitive = sensitive;\n }\n\n public ApiConfig validationState(ValidationState validationState) {\n this.validationState = validationState;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. State of the configuration parameter after validation.\n * @return validationState\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. State of the configuration parameter after validation.\")\n @Valid\n public ValidationState getValidationState() {\n return validationState;\n }\n\n public void setValidationState(ValidationState validationState) {\n this.validationState = validationState;\n }\n\n public ApiConfig validationMessage(String validationMessage) {\n this.validationMessage = validationMessage;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. A message explaining the parameter's validation state.\n * @return validationMessage\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. A message explaining the parameter's validation state.\")\n public String getValidationMessage() {\n return validationMessage;\n }\n\n public void setValidationMessage(String validationMessage) {\n this.validationMessage = validationMessage;\n }\n\n public ApiConfig validationWarningsSuppressed(Boolean validationWarningsSuppressed) {\n this.validationWarningsSuppressed = validationWarningsSuppressed;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. Whether validation warnings associated with this parameter are suppressed. In general, suppressed validation warnings are hidden in the Cloudera Manager UI. Configurations that do not produce warnings will not contain this field.\n * @return validationWarningsSuppressed\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. Whether validation warnings associated with this parameter are suppressed. In general, suppressed validation warnings are hidden in the Cloudera Manager UI. Configurations that do not produce warnings will not contain this field.\")\n public Boolean isValidationWarningsSuppressed() {\n return validationWarningsSuppressed;\n }\n\n public void setValidationWarningsSuppressed(Boolean validationWarningsSuppressed) {\n this.validationWarningsSuppressed = validationWarningsSuppressed;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ApiConfig apiConfig = (ApiConfig) o;\n return Objects.equals(this.name, apiConfig.name) && Objects.equals(this.value, apiConfig.value) && Objects.equals(this.required, apiConfig.required) && Objects.equals(this._default, apiConfig._default) && Objects.equals(this.displayName, apiConfig.displayName) && Objects.equals(this.description, apiConfig.description) && Objects.equals(this.relatedName, apiConfig.relatedName) && Objects.equals(this.sensitive, apiConfig.sensitive) && Objects.equals(this.validationState, apiConfig.validationState) && Objects.equals(this.validationMessage, apiConfig.validationMessage) && Objects.equals(this.validationWarningsSuppressed, apiConfig.validationWarningsSuppressed);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value, required, _default, displayName, description, relatedName, sensitive, validationState, validationMessage, validationWarningsSuppressed);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ApiConfig {\\n\");\n sb.append(\" name: \").append(toIndentedString(name)).append(\"\\n\");\n sb.append(\" value: \").append(toIndentedString(value)).append(\"\\n\");\n sb.append(\" required: \").append(toIndentedString(required)).append(\"\\n\");\n sb.append(\" _default: \").append(toIndentedString(_default)).append(\"\\n\");\n sb.append(\" displayName: \").append(toIndentedString(displayName)).append(\"\\n\");\n sb.append(\" description: \").append(toIndentedString(description)).append(\"\\n\");\n sb.append(\" relatedName: \").append(toIndentedString(relatedName)).append(\"\\n\");\n sb.append(\" sensitive: \").append(toIndentedString(sensitive)).append(\"\\n\");\n sb.append(\" validationState: \").append(toIndentedString(validationState)).append(\"\\n\");\n sb.append(\" validationMessage: \").append(toIndentedString(validationMessage)).append(\"\\n\");\n sb.append(\" validationWarningsSuppressed: \").append(toIndentedString(validationWarningsSuppressed)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_2230", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/hortonworks/cloudbreak/mock-infrastructure/src/generated/com/sequenceiq/mock/swagger/model/ApiConfig.java", "mask_start_position": 2925, "mask_end_position": 3144, "canonical_solution": "@ApiModelProperty(value = \"The user-defined value. When absent, the default value (if any) will be used. Can also be absent, when enumerating allowed configs.\")\n public String getValue() {\n return value;\n }", "pre_mask_code": "package com.sequenceiq.mock.swagger.model;\n\nimport java.util.Objects;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.sequenceiq.mock.swagger.model.ValidationState;\nimport io.swagger.annotations.ApiModel;\nimport io.swagger.annotations.ApiModelProperty;\nimport org.springframework.validation.annotation.Validated;\nimport javax.validation.Valid;\nimport javax.validation.constraints.*;\n\n/**\n * Model for a configuration parameter. When an entry's <i>value</i> property is not available, it means the entry is not configured. This means that the default value for the entry, if any, will be used. Setting a value to <i>null</i> also can be used to unset any previously set value for the parameter, reverting to the default value (if any).\n */\n@ApiModel(description = \"Model for a configuration parameter. When an entry's value property is not available, it means the entry is not configured. This means that the default value for the entry, if any, will be used. Setting a value to null also can be used to unset any previously set value for the parameter, reverting to the default value (if any).\")\n@Validated\n@javax.annotation.Generated(value = \"io.swagger.codegen.languages.SpringCodegen\", date = \"2020-10-26T08:01:08.932+01:00\")\npublic class ApiConfig {\n\n @JsonProperty(\"name\")\n private String name = null;\n\n @JsonProperty(\"value\")\n private String value = null;\n\n @JsonProperty(\"required\")\n private Boolean required = null;\n\n @JsonProperty(\"default\")\n private String _default = null;\n\n @JsonProperty(\"displayName\")\n private String displayName = null;\n\n @JsonProperty(\"description\")\n private String description = null;\n\n @JsonProperty(\"relatedName\")\n private String relatedName = null;\n\n @JsonProperty(\"sensitive\")\n private Boolean sensitive = null;\n\n @JsonProperty(\"validationState\")\n private ValidationState validationState = null;\n\n @JsonProperty(\"validationMessage\")\n private String validationMessage = null;\n\n @JsonProperty(\"validationWarningsSuppressed\")\n private Boolean validationWarningsSuppressed = null;\n\n public ApiConfig name(String name) {\n this.name = name;\n return this;\n }\n\n /**\n * Readonly. The canonical name that identifies this configuration parameter.\n * @return name\n */\n @ApiModelProperty(value = \"Readonly. The canonical name that identifies this configuration parameter.\")\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public ApiConfig value(String value) {\n this.value = value;\n return this;\n }\n\n /**\n * The user-defined value. When absent, the default value (if any) will be used. Can also be absent, when enumerating allowed configs.\n * @return value\n */\n ", "post_mask_code": "\n\n public void setValue(String value) {\n this.value = value;\n }\n\n public ApiConfig required(Boolean required) {\n this.required = required;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. Whether this configuration is required for the object. If any required configuration is not set, operations on the object may not work.\n * @return required\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. Whether this configuration is required for the object. If any required configuration is not set, operations on the object may not work.\")\n public Boolean isRequired() {\n return required;\n }\n\n public void setRequired(Boolean required) {\n this.required = required;\n }\n\n public ApiConfig _default(String _default) {\n this._default = _default;\n return this;\n }\n\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. The default value.\")\n public String getDefault() {\n return _default;\n }\n\n public void setDefault(String _default) {\n this._default = _default;\n }\n\n public ApiConfig displayName(String displayName) {\n this.displayName = displayName;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. A user-friendly name of the parameters, as would have been shown in the web UI.\n * @return displayName\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. A user-friendly name of the parameters, as would have been shown in the web UI.\")\n public String getDisplayName() {\n return displayName;\n }\n\n public void setDisplayName(String displayName) {\n this.displayName = displayName;\n }\n\n public ApiConfig description(String description) {\n this.description = description;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. A textual description of the parameter.\n * @return description\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. A textual description of the parameter.\")\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public ApiConfig relatedName(String relatedName) {\n this.relatedName = relatedName;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. If applicable, contains the related configuration variable used by the source project.\n * @return relatedName\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. If applicable, contains the related configuration variable used by the source project.\")\n public String getRelatedName() {\n return relatedName;\n }\n\n public void setRelatedName(String relatedName) {\n this.relatedName = relatedName;\n }\n\n public ApiConfig sensitive(Boolean sensitive) {\n this.sensitive = sensitive;\n return this;\n }\n\n /**\n * Readonly. Whether this configuration is sensitive, i.e. contains information such as passwords, which might affect how the value of this configuration might be shared by the caller. Available since v14.\n * @return sensitive\n */\n @ApiModelProperty(value = \"Readonly. Whether this configuration is sensitive, i.e. contains information such as passwords, which might affect how the value of this configuration might be shared by the caller. Available since v14.\")\n public Boolean isSensitive() {\n return sensitive;\n }\n\n public void setSensitive(Boolean sensitive) {\n this.sensitive = sensitive;\n }\n\n public ApiConfig validationState(ValidationState validationState) {\n this.validationState = validationState;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. State of the configuration parameter after validation.\n * @return validationState\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. State of the configuration parameter after validation.\")\n @Valid\n public ValidationState getValidationState() {\n return validationState;\n }\n\n public void setValidationState(ValidationState validationState) {\n this.validationState = validationState;\n }\n\n public ApiConfig validationMessage(String validationMessage) {\n this.validationMessage = validationMessage;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. A message explaining the parameter's validation state.\n * @return validationMessage\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. A message explaining the parameter's validation state.\")\n public String getValidationMessage() {\n return validationMessage;\n }\n\n public void setValidationMessage(String validationMessage) {\n this.validationMessage = validationMessage;\n }\n\n public ApiConfig validationWarningsSuppressed(Boolean validationWarningsSuppressed) {\n this.validationWarningsSuppressed = validationWarningsSuppressed;\n return this;\n }\n\n /**\n * Readonly. Requires \\\"full\\\" view. Whether validation warnings associated with this parameter are suppressed. In general, suppressed validation warnings are hidden in the Cloudera Manager UI. Configurations that do not produce warnings will not contain this field.\n * @return validationWarningsSuppressed\n */\n @ApiModelProperty(value = \"Readonly. Requires \\\"full\\\" view. Whether validation warnings associated with this parameter are suppressed. In general, suppressed validation warnings are hidden in the Cloudera Manager UI. Configurations that do not produce warnings will not contain this field.\")\n public Boolean isValidationWarningsSuppressed() {\n return validationWarningsSuppressed;\n }\n\n public void setValidationWarningsSuppressed(Boolean validationWarningsSuppressed) {\n this.validationWarningsSuppressed = validationWarningsSuppressed;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ApiConfig apiConfig = (ApiConfig) o;\n return Objects.equals(this.name, apiConfig.name) && Objects.equals(this.value, apiConfig.value) && Objects.equals(this.required, apiConfig.required) && Objects.equals(this._default, apiConfig._default) && Objects.equals(this.displayName, apiConfig.displayName) && Objects.equals(this.description, apiConfig.description) && Objects.equals(this.relatedName, apiConfig.relatedName) && Objects.equals(this.sensitive, apiConfig.sensitive) && Objects.equals(this.validationState, apiConfig.validationState) && Objects.equals(this.validationMessage, apiConfig.validationMessage) && Objects.equals(this.validationWarningsSuppressed, apiConfig.validationWarningsSuppressed);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value, required, _default, displayName, description, relatedName, sensitive, validationState, validationMessage, validationWarningsSuppressed);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ApiConfig {\\n\");\n sb.append(\" name: \").append(toIndentedString(name)).append(\"\\n\");\n sb.append(\" value: \").append(toIndentedString(value)).append(\"\\n\");\n sb.append(\" required: \").append(toIndentedString(required)).append(\"\\n\");\n sb.append(\" _default: \").append(toIndentedString(_default)).append(\"\\n\");\n sb.append(\" displayName: \").append(toIndentedString(displayName)).append(\"\\n\");\n sb.append(\" description: \").append(toIndentedString(description)).append(\"\\n\");\n sb.append(\" relatedName: \").append(toIndentedString(relatedName)).append(\"\\n\");\n sb.append(\" sensitive: \").append(toIndentedString(sensitive)).append(\"\\n\");\n sb.append(\" validationState: \").append(toIndentedString(validationState)).append(\"\\n\");\n sb.append(\" validationMessage: \").append(toIndentedString(validationMessage)).append(\"\\n\");\n sb.append(\" validationWarningsSuppressed: \").append(toIndentedString(validationWarningsSuppressed)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n"} {"task_id": "Java_2231", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cdapio/coopr/coopr-cli/src/main/java/co/cask/coopr/shell/command/GetClusterCommand.java", "mask_start_position": 999, "mask_end_position": 1044, "canonical_solution": "@Override\n public String getDescription() ", "pre_mask_code": "package co.cask.coopr.shell.command;\n\nimport co.cask.common.cli.Arguments;\nimport co.cask.coopr.client.ClusterClient;\nimport co.cask.coopr.shell.CLIConfig;\nimport co.cask.coopr.shell.util.CliUtil;\nimport com.google.inject.Inject;\nimport java.io.PrintStream;\nimport static co.cask.coopr.shell.util.Constants.CLUSTER_ID_KEY;\n\n/**\n * Gets the cluster.\n */\npublic class GetClusterCommand extends AbstractAuthCommand {\n\n private final ClusterClient clusterClient;\n\n @Inject\n private GetClusterCommand(ClusterClient clusterClient, CLIConfig cliConfig) {\n super(cliConfig);\n this.clusterClient = clusterClient;\n }\n\n @Override\n public void perform(Arguments arguments, PrintStream printStream) throws Exception {\n String id = arguments.get(CLUSTER_ID_KEY);\n printStream.print(CliUtil.getPrettyJson(clusterClient.getCluster(id)));\n }\n\n @Override\n public String getPattern() {\n return String.format(\"get cluster <%s>\", CLUSTER_ID_KEY);\n }\n\n ", "post_mask_code": "{\n return \"Get the cluster by id\";\n }\n}\n"} {"task_id": "Java_2232", "language": "Java", "task_type": "method_body", "source_file": "java/github/cdapio/coopr/coopr-cli/src/main/java/co/cask/coopr/shell/command/GetClusterCommand.java", "mask_start_position": 920, "mask_end_position": 993, "canonical_solution": "{\n return String.format(\"get cluster <%s>\", CLUSTER_ID_KEY);\n }", "pre_mask_code": "package co.cask.coopr.shell.command;\n\nimport co.cask.common.cli.Arguments;\nimport co.cask.coopr.client.ClusterClient;\nimport co.cask.coopr.shell.CLIConfig;\nimport co.cask.coopr.shell.util.CliUtil;\nimport com.google.inject.Inject;\nimport java.io.PrintStream;\nimport static co.cask.coopr.shell.util.Constants.CLUSTER_ID_KEY;\n\n/**\n * Gets the cluster.\n */\npublic class GetClusterCommand extends AbstractAuthCommand {\n\n private final ClusterClient clusterClient;\n\n @Inject\n private GetClusterCommand(ClusterClient clusterClient, CLIConfig cliConfig) {\n super(cliConfig);\n this.clusterClient = clusterClient;\n }\n\n @Override\n public void perform(Arguments arguments, PrintStream printStream) throws Exception {\n String id = arguments.get(CLUSTER_ID_KEY);\n printStream.print(CliUtil.getPrettyJson(clusterClient.getCluster(id)));\n }\n\n @Override\n public String getPattern() ", "post_mask_code": "\n\n @Override\n public String getDescription() {\n return \"Get the cluster by id\";\n }\n}\n"} {"task_id": "Java_2233", "language": "Java", "task_type": "single_line", "source_file": "java/github/cdapio/coopr/coopr-cli/src/main/java/co/cask/coopr/shell/command/GetClusterCommand.java", "mask_start_position": 1057, "mask_end_position": 1085, "canonical_solution": "urn \"Get the cluster by id\";", "pre_mask_code": "package co.cask.coopr.shell.command;\n\nimport co.cask.common.cli.Arguments;\nimport co.cask.coopr.client.ClusterClient;\nimport co.cask.coopr.shell.CLIConfig;\nimport co.cask.coopr.shell.util.CliUtil;\nimport com.google.inject.Inject;\nimport java.io.PrintStream;\nimport static co.cask.coopr.shell.util.Constants.CLUSTER_ID_KEY;\n\n/**\n * Gets the cluster.\n */\npublic class GetClusterCommand extends AbstractAuthCommand {\n\n private final ClusterClient clusterClient;\n\n @Inject\n private GetClusterCommand(ClusterClient clusterClient, CLIConfig cliConfig) {\n super(cliConfig);\n this.clusterClient = clusterClient;\n }\n\n @Override\n public void perform(Arguments arguments, PrintStream printStream) throws Exception {\n String id = arguments.get(CLUSTER_ID_KEY);\n printStream.print(CliUtil.getPrettyJson(clusterClient.getCluster(id)));\n }\n\n @Override\n public String getPattern() {\n return String.format(\"get cluster <%s>\", CLUSTER_ID_KEY);\n }\n\n @Override\n public String getDescription() {\n ret", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2234", "language": "Java", "task_type": "method_signature", "source_file": "java/github/googleapis/google-http-java-client/google-http-client/src/main/java/com/google/api/client/http/MultipartContent.java", "mask_start_position": 5531, "mask_end_position": 5619, "canonical_solution": "public MultipartContent setContentParts(Collection contentParts) ", "pre_mask_code": "package com.google.api.client.http;\n\nimport com.google.api.client.util.Preconditions;\nimport com.google.api.client.util.StreamingContent;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.OutputStreamWriter;\nimport java.io.Writer;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.UUID;\n\n/**\n * Serializes MIME multipart content as specified by RFC 2387: The MIME Multipart/Related Content-type\n * and RFC 2046: Multipurpose Internet\n * Mail Extensions: The Multipart/mixed (primary) subtype.\n *\n *

By default the media type is {@code \"multipart/related; boundary=__END_OF_PART____\"}, but this may be customized by calling {@link #setMediaType(HttpMediaType)}, {@link\n * #getMediaType()}, or {@link #setBoundary(String)}.\n *\n *

Implementation is not thread-safe.\n *\n * @since 1.14\n * @author Yaniv Inbar\n */\npublic class MultipartContent extends AbstractHttpContent {\n\n static final String NEWLINE = \"\\r\\n\";\n\n private static final String TWO_DASHES = \"--\";\n\n /**\n * Parts of the HTTP multipart request.\n */\n private ArrayList parts = new ArrayList<>();\n\n public MultipartContent() {\n this(\"__END_OF_PART__\" + UUID.randomUUID().toString() + \"__\");\n }\n\n public MultipartContent(String boundary) {\n super(new HttpMediaType(\"multipart/related\").setParameter(\"boundary\", boundary));\n }\n\n public void writeTo(OutputStream out) throws IOException {\n Writer writer = new OutputStreamWriter(out, getCharset());\n String boundary = getBoundary();\n for (Part part : parts) {\n HttpHeaders headers = new HttpHeaders().setAcceptEncoding(null);\n if (part.headers != null) {\n headers.fromHttpHeaders(part.headers);\n }\n headers.setContentEncoding(null).setUserAgent(null).setContentType(null).setContentLength(null).set(\"Content-Transfer-Encoding\", null);\n // analyze the content\n HttpContent content = part.content;\n StreamingContent streamingContent = null;\n if (content != null) {\n headers.set(\"Content-Transfer-Encoding\", Arrays.asList(\"binary\"));\n headers.setContentType(content.getType());\n HttpEncoding encoding = part.encoding;\n long contentLength;\n if (encoding == null) {\n contentLength = content.getLength();\n streamingContent = content;\n } else {\n headers.setContentEncoding(encoding.getName());\n streamingContent = new HttpEncodingStreamingContent(content, encoding);\n contentLength = AbstractHttpContent.computeLength(content);\n }\n if (contentLength != -1) {\n headers.setContentLength(contentLength);\n }\n }\n // write multipart-body from RFC 1521 §7.2.1\n // write encapsulation\n // write delimiter\n writer.write(TWO_DASHES);\n writer.write(boundary);\n writer.write(NEWLINE);\n // write body-part; message from RFC 822 §4.1\n // write message fields\n HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer);\n if (streamingContent != null) {\n writer.write(NEWLINE);\n writer.flush();\n // write message text/body\n streamingContent.writeTo(out);\n }\n // terminate encapsulation\n writer.write(NEWLINE);\n }\n // write close-delimiter\n writer.write(TWO_DASHES);\n writer.write(boundary);\n writer.write(TWO_DASHES);\n writer.write(NEWLINE);\n writer.flush();\n }\n\n @Override\n public boolean retrySupported() {\n for (Part part : parts) {\n if (!part.content.retrySupported()) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public MultipartContent setMediaType(HttpMediaType mediaType) {\n super.setMediaType(mediaType);\n return this;\n }\n\n /**\n * Returns an unmodifiable view of the parts of the HTTP multipart request.\n */\n public final Collection getParts() {\n return Collections.unmodifiableCollection(parts);\n }\n\n /**\n * Adds an HTTP multipart part.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent addPart(Part part) {\n parts.add(Preconditions.checkNotNull(part));\n return this;\n }\n\n /**\n * Sets the parts of the HTTP multipart request.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent setParts(Collection parts) {\n this.parts = new ArrayList<>(parts);\n return this;\n }\n\n /**\n * Sets the HTTP content parts of the HTTP multipart request, where each part is assumed to have\n * no HTTP headers and no encoding.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n ", "post_mask_code": "{\n this.parts = new ArrayList<>(contentParts.size());\n for (HttpContent contentPart : contentParts) {\n addPart(new Part(contentPart));\n }\n return this;\n }\n\n /**\n * Returns the boundary string to use.\n */\n public final String getBoundary() {\n return getMediaType().getParameter(\"boundary\");\n }\n\n /**\n * Sets the boundary string to use.\n *\n *

Defaults to {@code \"END_OF_PART\"}.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent setBoundary(String boundary) {\n getMediaType().setParameter(\"boundary\", Preconditions.checkNotNull(boundary));\n return this;\n }\n\n /**\n * Single part of a multi-part request.\n *\n *

Implementation is not thread-safe.\n */\n public static final class Part {\n\n /**\n * HTTP content or {@code null} for none.\n */\n HttpContent content;\n\n /**\n * HTTP headers or {@code null} for none.\n */\n HttpHeaders headers;\n\n /**\n * HTTP encoding or {@code null} for none.\n */\n HttpEncoding encoding;\n\n public Part() {\n this(null);\n }\n\n /**\n * @param content HTTP content or {@code null} for none\n */\n public Part(HttpContent content) {\n this(null, content);\n }\n\n /**\n * @param headers HTTP headers or {@code null} for none\n * @param content HTTP content or {@code null} for none\n */\n public Part(HttpHeaders headers, HttpContent content) {\n setHeaders(headers);\n setContent(content);\n }\n\n /**\n * Sets the HTTP content or {@code null} for none.\n */\n public Part setContent(HttpContent content) {\n this.content = content;\n return this;\n }\n\n /**\n * Returns the HTTP content or {@code null} for none.\n */\n public HttpContent getContent() {\n return content;\n }\n\n /**\n * Sets the HTTP headers or {@code null} for none.\n */\n public Part setHeaders(HttpHeaders headers) {\n this.headers = headers;\n return this;\n }\n\n /**\n * Returns the HTTP headers or {@code null} for none.\n */\n public HttpHeaders getHeaders() {\n return headers;\n }\n\n /**\n * Sets the HTTP encoding or {@code null} for none.\n */\n public Part setEncoding(HttpEncoding encoding) {\n this.encoding = encoding;\n return this;\n }\n\n /**\n * Returns the HTTP encoding or {@code null} for none.\n */\n public HttpEncoding getEncoding() {\n return encoding;\n }\n }\n}\n"} {"task_id": "Java_2235", "language": "Java", "task_type": "method_body", "source_file": "java/github/googleapis/google-http-java-client/google-http-client/src/main/java/com/google/api/client/http/MultipartContent.java", "mask_start_position": 6297, "mask_end_position": 6412, "canonical_solution": "{\n getMediaType().setParameter(\"boundary\", Preconditions.checkNotNull(boundary));\n return this;\n }", "pre_mask_code": "package com.google.api.client.http;\n\nimport com.google.api.client.util.Preconditions;\nimport com.google.api.client.util.StreamingContent;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.OutputStreamWriter;\nimport java.io.Writer;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.UUID;\n\n/**\n * Serializes MIME multipart content as specified by RFC 2387: The MIME Multipart/Related Content-type\n * and RFC 2046: Multipurpose Internet\n * Mail Extensions: The Multipart/mixed (primary) subtype.\n *\n *

By default the media type is {@code \"multipart/related; boundary=__END_OF_PART____\"}, but this may be customized by calling {@link #setMediaType(HttpMediaType)}, {@link\n * #getMediaType()}, or {@link #setBoundary(String)}.\n *\n *

Implementation is not thread-safe.\n *\n * @since 1.14\n * @author Yaniv Inbar\n */\npublic class MultipartContent extends AbstractHttpContent {\n\n static final String NEWLINE = \"\\r\\n\";\n\n private static final String TWO_DASHES = \"--\";\n\n /**\n * Parts of the HTTP multipart request.\n */\n private ArrayList parts = new ArrayList<>();\n\n public MultipartContent() {\n this(\"__END_OF_PART__\" + UUID.randomUUID().toString() + \"__\");\n }\n\n public MultipartContent(String boundary) {\n super(new HttpMediaType(\"multipart/related\").setParameter(\"boundary\", boundary));\n }\n\n public void writeTo(OutputStream out) throws IOException {\n Writer writer = new OutputStreamWriter(out, getCharset());\n String boundary = getBoundary();\n for (Part part : parts) {\n HttpHeaders headers = new HttpHeaders().setAcceptEncoding(null);\n if (part.headers != null) {\n headers.fromHttpHeaders(part.headers);\n }\n headers.setContentEncoding(null).setUserAgent(null).setContentType(null).setContentLength(null).set(\"Content-Transfer-Encoding\", null);\n // analyze the content\n HttpContent content = part.content;\n StreamingContent streamingContent = null;\n if (content != null) {\n headers.set(\"Content-Transfer-Encoding\", Arrays.asList(\"binary\"));\n headers.setContentType(content.getType());\n HttpEncoding encoding = part.encoding;\n long contentLength;\n if (encoding == null) {\n contentLength = content.getLength();\n streamingContent = content;\n } else {\n headers.setContentEncoding(encoding.getName());\n streamingContent = new HttpEncodingStreamingContent(content, encoding);\n contentLength = AbstractHttpContent.computeLength(content);\n }\n if (contentLength != -1) {\n headers.setContentLength(contentLength);\n }\n }\n // write multipart-body from RFC 1521 §7.2.1\n // write encapsulation\n // write delimiter\n writer.write(TWO_DASHES);\n writer.write(boundary);\n writer.write(NEWLINE);\n // write body-part; message from RFC 822 §4.1\n // write message fields\n HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer);\n if (streamingContent != null) {\n writer.write(NEWLINE);\n writer.flush();\n // write message text/body\n streamingContent.writeTo(out);\n }\n // terminate encapsulation\n writer.write(NEWLINE);\n }\n // write close-delimiter\n writer.write(TWO_DASHES);\n writer.write(boundary);\n writer.write(TWO_DASHES);\n writer.write(NEWLINE);\n writer.flush();\n }\n\n @Override\n public boolean retrySupported() {\n for (Part part : parts) {\n if (!part.content.retrySupported()) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public MultipartContent setMediaType(HttpMediaType mediaType) {\n super.setMediaType(mediaType);\n return this;\n }\n\n /**\n * Returns an unmodifiable view of the parts of the HTTP multipart request.\n */\n public final Collection getParts() {\n return Collections.unmodifiableCollection(parts);\n }\n\n /**\n * Adds an HTTP multipart part.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent addPart(Part part) {\n parts.add(Preconditions.checkNotNull(part));\n return this;\n }\n\n /**\n * Sets the parts of the HTTP multipart request.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent setParts(Collection parts) {\n this.parts = new ArrayList<>(parts);\n return this;\n }\n\n /**\n * Sets the HTTP content parts of the HTTP multipart request, where each part is assumed to have\n * no HTTP headers and no encoding.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent setContentParts(Collection contentParts) {\n this.parts = new ArrayList<>(contentParts.size());\n for (HttpContent contentPart : contentParts) {\n addPart(new Part(contentPart));\n }\n return this;\n }\n\n /**\n * Returns the boundary string to use.\n */\n public final String getBoundary() {\n return getMediaType().getParameter(\"boundary\");\n }\n\n /**\n * Sets the boundary string to use.\n *\n *

Defaults to {@code \"END_OF_PART\"}.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent setBoundary(String boundary) ", "post_mask_code": "\n\n /**\n * Single part of a multi-part request.\n *\n *

Implementation is not thread-safe.\n */\n public static final class Part {\n\n /**\n * HTTP content or {@code null} for none.\n */\n HttpContent content;\n\n /**\n * HTTP headers or {@code null} for none.\n */\n HttpHeaders headers;\n\n /**\n * HTTP encoding or {@code null} for none.\n */\n HttpEncoding encoding;\n\n public Part() {\n this(null);\n }\n\n /**\n * @param content HTTP content or {@code null} for none\n */\n public Part(HttpContent content) {\n this(null, content);\n }\n\n /**\n * @param headers HTTP headers or {@code null} for none\n * @param content HTTP content or {@code null} for none\n */\n public Part(HttpHeaders headers, HttpContent content) {\n setHeaders(headers);\n setContent(content);\n }\n\n /**\n * Sets the HTTP content or {@code null} for none.\n */\n public Part setContent(HttpContent content) {\n this.content = content;\n return this;\n }\n\n /**\n * Returns the HTTP content or {@code null} for none.\n */\n public HttpContent getContent() {\n return content;\n }\n\n /**\n * Sets the HTTP headers or {@code null} for none.\n */\n public Part setHeaders(HttpHeaders headers) {\n this.headers = headers;\n return this;\n }\n\n /**\n * Returns the HTTP headers or {@code null} for none.\n */\n public HttpHeaders getHeaders() {\n return headers;\n }\n\n /**\n * Sets the HTTP encoding or {@code null} for none.\n */\n public Part setEncoding(HttpEncoding encoding) {\n this.encoding = encoding;\n return this;\n }\n\n /**\n * Returns the HTTP encoding or {@code null} for none.\n */\n public HttpEncoding getEncoding() {\n return encoding;\n }\n }\n}\n"} {"task_id": "Java_2236", "language": "Java", "task_type": "single_line", "source_file": "java/github/googleapis/google-http-java-client/google-http-client/src/main/java/com/google/api/client/http/MultipartContent.java", "mask_start_position": 1687, "mask_end_position": 1696, "canonical_solution": "undary();", "pre_mask_code": "package com.google.api.client.http;\n\nimport com.google.api.client.util.Preconditions;\nimport com.google.api.client.util.StreamingContent;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.OutputStreamWriter;\nimport java.io.Writer;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.UUID;\n\n/**\n * Serializes MIME multipart content as specified by RFC 2387: The MIME Multipart/Related Content-type\n * and RFC 2046: Multipurpose Internet\n * Mail Extensions: The Multipart/mixed (primary) subtype.\n *\n *

By default the media type is {@code \"multipart/related; boundary=__END_OF_PART____\"}, but this may be customized by calling {@link #setMediaType(HttpMediaType)}, {@link\n * #getMediaType()}, or {@link #setBoundary(String)}.\n *\n *

Implementation is not thread-safe.\n *\n * @since 1.14\n * @author Yaniv Inbar\n */\npublic class MultipartContent extends AbstractHttpContent {\n\n static final String NEWLINE = \"\\r\\n\";\n\n private static final String TWO_DASHES = \"--\";\n\n /**\n * Parts of the HTTP multipart request.\n */\n private ArrayList parts = new ArrayList<>();\n\n public MultipartContent() {\n this(\"__END_OF_PART__\" + UUID.randomUUID().toString() + \"__\");\n }\n\n public MultipartContent(String boundary) {\n super(new HttpMediaType(\"multipart/related\").setParameter(\"boundary\", boundary));\n }\n\n public void writeTo(OutputStream out) throws IOException {\n Writer writer = new OutputStreamWriter(out, getCharset());\n String boundary = getBo", "post_mask_code": "\n for (Part part : parts) {\n HttpHeaders headers = new HttpHeaders().setAcceptEncoding(null);\n if (part.headers != null) {\n headers.fromHttpHeaders(part.headers);\n }\n headers.setContentEncoding(null).setUserAgent(null).setContentType(null).setContentLength(null).set(\"Content-Transfer-Encoding\", null);\n // analyze the content\n HttpContent content = part.content;\n StreamingContent streamingContent = null;\n if (content != null) {\n headers.set(\"Content-Transfer-Encoding\", Arrays.asList(\"binary\"));\n headers.setContentType(content.getType());\n HttpEncoding encoding = part.encoding;\n long contentLength;\n if (encoding == null) {\n contentLength = content.getLength();\n streamingContent = content;\n } else {\n headers.setContentEncoding(encoding.getName());\n streamingContent = new HttpEncodingStreamingContent(content, encoding);\n contentLength = AbstractHttpContent.computeLength(content);\n }\n if (contentLength != -1) {\n headers.setContentLength(contentLength);\n }\n }\n // write multipart-body from RFC 1521 §7.2.1\n // write encapsulation\n // write delimiter\n writer.write(TWO_DASHES);\n writer.write(boundary);\n writer.write(NEWLINE);\n // write body-part; message from RFC 822 §4.1\n // write message fields\n HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer);\n if (streamingContent != null) {\n writer.write(NEWLINE);\n writer.flush();\n // write message text/body\n streamingContent.writeTo(out);\n }\n // terminate encapsulation\n writer.write(NEWLINE);\n }\n // write close-delimiter\n writer.write(TWO_DASHES);\n writer.write(boundary);\n writer.write(TWO_DASHES);\n writer.write(NEWLINE);\n writer.flush();\n }\n\n @Override\n public boolean retrySupported() {\n for (Part part : parts) {\n if (!part.content.retrySupported()) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public MultipartContent setMediaType(HttpMediaType mediaType) {\n super.setMediaType(mediaType);\n return this;\n }\n\n /**\n * Returns an unmodifiable view of the parts of the HTTP multipart request.\n */\n public final Collection getParts() {\n return Collections.unmodifiableCollection(parts);\n }\n\n /**\n * Adds an HTTP multipart part.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent addPart(Part part) {\n parts.add(Preconditions.checkNotNull(part));\n return this;\n }\n\n /**\n * Sets the parts of the HTTP multipart request.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent setParts(Collection parts) {\n this.parts = new ArrayList<>(parts);\n return this;\n }\n\n /**\n * Sets the HTTP content parts of the HTTP multipart request, where each part is assumed to have\n * no HTTP headers and no encoding.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent setContentParts(Collection contentParts) {\n this.parts = new ArrayList<>(contentParts.size());\n for (HttpContent contentPart : contentParts) {\n addPart(new Part(contentPart));\n }\n return this;\n }\n\n /**\n * Returns the boundary string to use.\n */\n public final String getBoundary() {\n return getMediaType().getParameter(\"boundary\");\n }\n\n /**\n * Sets the boundary string to use.\n *\n *

Defaults to {@code \"END_OF_PART\"}.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent setBoundary(String boundary) {\n getMediaType().setParameter(\"boundary\", Preconditions.checkNotNull(boundary));\n return this;\n }\n\n /**\n * Single part of a multi-part request.\n *\n *

Implementation is not thread-safe.\n */\n public static final class Part {\n\n /**\n * HTTP content or {@code null} for none.\n */\n HttpContent content;\n\n /**\n * HTTP headers or {@code null} for none.\n */\n HttpHeaders headers;\n\n /**\n * HTTP encoding or {@code null} for none.\n */\n HttpEncoding encoding;\n\n public Part() {\n this(null);\n }\n\n /**\n * @param content HTTP content or {@code null} for none\n */\n public Part(HttpContent content) {\n this(null, content);\n }\n\n /**\n * @param headers HTTP headers or {@code null} for none\n * @param content HTTP content or {@code null} for none\n */\n public Part(HttpHeaders headers, HttpContent content) {\n setHeaders(headers);\n setContent(content);\n }\n\n /**\n * Sets the HTTP content or {@code null} for none.\n */\n public Part setContent(HttpContent content) {\n this.content = content;\n return this;\n }\n\n /**\n * Returns the HTTP content or {@code null} for none.\n */\n public HttpContent getContent() {\n return content;\n }\n\n /**\n * Sets the HTTP headers or {@code null} for none.\n */\n public Part setHeaders(HttpHeaders headers) {\n this.headers = headers;\n return this;\n }\n\n /**\n * Returns the HTTP headers or {@code null} for none.\n */\n public HttpHeaders getHeaders() {\n return headers;\n }\n\n /**\n * Sets the HTTP encoding or {@code null} for none.\n */\n public Part setEncoding(HttpEncoding encoding) {\n this.encoding = encoding;\n return this;\n }\n\n /**\n * Returns the HTTP encoding or {@code null} for none.\n */\n public HttpEncoding getEncoding() {\n return encoding;\n }\n }\n}\n"} {"task_id": "Java_2237", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/googleapis/google-http-java-client/google-http-client/src/main/java/com/google/api/client/http/MultipartContent.java", "mask_start_position": 6244, "mask_end_position": 6412, "canonical_solution": "public MultipartContent setBoundary(String boundary) {\n getMediaType().setParameter(\"boundary\", Preconditions.checkNotNull(boundary));\n return this;\n }", "pre_mask_code": "package com.google.api.client.http;\n\nimport com.google.api.client.util.Preconditions;\nimport com.google.api.client.util.StreamingContent;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.OutputStreamWriter;\nimport java.io.Writer;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.UUID;\n\n/**\n * Serializes MIME multipart content as specified by RFC 2387: The MIME Multipart/Related Content-type\n * and RFC 2046: Multipurpose Internet\n * Mail Extensions: The Multipart/mixed (primary) subtype.\n *\n *

By default the media type is {@code \"multipart/related; boundary=__END_OF_PART____\"}, but this may be customized by calling {@link #setMediaType(HttpMediaType)}, {@link\n * #getMediaType()}, or {@link #setBoundary(String)}.\n *\n *

Implementation is not thread-safe.\n *\n * @since 1.14\n * @author Yaniv Inbar\n */\npublic class MultipartContent extends AbstractHttpContent {\n\n static final String NEWLINE = \"\\r\\n\";\n\n private static final String TWO_DASHES = \"--\";\n\n /**\n * Parts of the HTTP multipart request.\n */\n private ArrayList parts = new ArrayList<>();\n\n public MultipartContent() {\n this(\"__END_OF_PART__\" + UUID.randomUUID().toString() + \"__\");\n }\n\n public MultipartContent(String boundary) {\n super(new HttpMediaType(\"multipart/related\").setParameter(\"boundary\", boundary));\n }\n\n public void writeTo(OutputStream out) throws IOException {\n Writer writer = new OutputStreamWriter(out, getCharset());\n String boundary = getBoundary();\n for (Part part : parts) {\n HttpHeaders headers = new HttpHeaders().setAcceptEncoding(null);\n if (part.headers != null) {\n headers.fromHttpHeaders(part.headers);\n }\n headers.setContentEncoding(null).setUserAgent(null).setContentType(null).setContentLength(null).set(\"Content-Transfer-Encoding\", null);\n // analyze the content\n HttpContent content = part.content;\n StreamingContent streamingContent = null;\n if (content != null) {\n headers.set(\"Content-Transfer-Encoding\", Arrays.asList(\"binary\"));\n headers.setContentType(content.getType());\n HttpEncoding encoding = part.encoding;\n long contentLength;\n if (encoding == null) {\n contentLength = content.getLength();\n streamingContent = content;\n } else {\n headers.setContentEncoding(encoding.getName());\n streamingContent = new HttpEncodingStreamingContent(content, encoding);\n contentLength = AbstractHttpContent.computeLength(content);\n }\n if (contentLength != -1) {\n headers.setContentLength(contentLength);\n }\n }\n // write multipart-body from RFC 1521 §7.2.1\n // write encapsulation\n // write delimiter\n writer.write(TWO_DASHES);\n writer.write(boundary);\n writer.write(NEWLINE);\n // write body-part; message from RFC 822 §4.1\n // write message fields\n HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer);\n if (streamingContent != null) {\n writer.write(NEWLINE);\n writer.flush();\n // write message text/body\n streamingContent.writeTo(out);\n }\n // terminate encapsulation\n writer.write(NEWLINE);\n }\n // write close-delimiter\n writer.write(TWO_DASHES);\n writer.write(boundary);\n writer.write(TWO_DASHES);\n writer.write(NEWLINE);\n writer.flush();\n }\n\n @Override\n public boolean retrySupported() {\n for (Part part : parts) {\n if (!part.content.retrySupported()) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public MultipartContent setMediaType(HttpMediaType mediaType) {\n super.setMediaType(mediaType);\n return this;\n }\n\n /**\n * Returns an unmodifiable view of the parts of the HTTP multipart request.\n */\n public final Collection getParts() {\n return Collections.unmodifiableCollection(parts);\n }\n\n /**\n * Adds an HTTP multipart part.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent addPart(Part part) {\n parts.add(Preconditions.checkNotNull(part));\n return this;\n }\n\n /**\n * Sets the parts of the HTTP multipart request.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent setParts(Collection parts) {\n this.parts = new ArrayList<>(parts);\n return this;\n }\n\n /**\n * Sets the HTTP content parts of the HTTP multipart request, where each part is assumed to have\n * no HTTP headers and no encoding.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public MultipartContent setContentParts(Collection contentParts) {\n this.parts = new ArrayList<>(contentParts.size());\n for (HttpContent contentPart : contentParts) {\n addPart(new Part(contentPart));\n }\n return this;\n }\n\n /**\n * Returns the boundary string to use.\n */\n public final String getBoundary() {\n return getMediaType().getParameter(\"boundary\");\n }\n\n /**\n * Sets the boundary string to use.\n *\n *

Defaults to {@code \"END_OF_PART\"}.\n *\n *

Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n ", "post_mask_code": "\n\n /**\n * Single part of a multi-part request.\n *\n *

Implementation is not thread-safe.\n */\n public static final class Part {\n\n /**\n * HTTP content or {@code null} for none.\n */\n HttpContent content;\n\n /**\n * HTTP headers or {@code null} for none.\n */\n HttpHeaders headers;\n\n /**\n * HTTP encoding or {@code null} for none.\n */\n HttpEncoding encoding;\n\n public Part() {\n this(null);\n }\n\n /**\n * @param content HTTP content or {@code null} for none\n */\n public Part(HttpContent content) {\n this(null, content);\n }\n\n /**\n * @param headers HTTP headers or {@code null} for none\n * @param content HTTP content or {@code null} for none\n */\n public Part(HttpHeaders headers, HttpContent content) {\n setHeaders(headers);\n setContent(content);\n }\n\n /**\n * Sets the HTTP content or {@code null} for none.\n */\n public Part setContent(HttpContent content) {\n this.content = content;\n return this;\n }\n\n /**\n * Returns the HTTP content or {@code null} for none.\n */\n public HttpContent getContent() {\n return content;\n }\n\n /**\n * Sets the HTTP headers or {@code null} for none.\n */\n public Part setHeaders(HttpHeaders headers) {\n this.headers = headers;\n return this;\n }\n\n /**\n * Returns the HTTP headers or {@code null} for none.\n */\n public HttpHeaders getHeaders() {\n return headers;\n }\n\n /**\n * Sets the HTTP encoding or {@code null} for none.\n */\n public Part setEncoding(HttpEncoding encoding) {\n this.encoding = encoding;\n return this;\n }\n\n /**\n * Returns the HTTP encoding or {@code null} for none.\n */\n public HttpEncoding getEncoding() {\n return encoding;\n }\n }\n}\n"} {"task_id": "Java_2238", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/netbeans/enterprise/websvc.jaxwsmodel/src/org/netbeans/modules/websvc/api/jaxws/bindings/impl/BindingsComponentImpl.java", "mask_start_position": 777, "mask_end_position": 850, "canonical_solution": "protected Object getAttributeValueOf(Attribute attr, String stringValue) ", "pre_mask_code": "package org.netbeans.modules.websvc.api.jaxws.bindings.impl;\n\nimport java.util.List;\nimport javax.xml.namespace.QName;\nimport org.netbeans.modules.websvc.api.jaxws.bindings.BindingsComponent;\nimport org.netbeans.modules.websvc.api.jaxws.bindings.BindingsModel;\nimport org.netbeans.modules.xml.xam.dom.Attribute;\nimport org.netbeans.modules.xml.xam.dom.AbstractDocumentComponent;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.NodeList;\n\n/**\n * @author Roderico Cruz\n */\npublic abstract class BindingsComponentImpl extends AbstractDocumentComponent implements BindingsComponent {\n\n /**\n * Creates a new instance of BindingsComponentImpl\n */\n public BindingsComponentImpl(BindingsModelImpl model, Element e) {\n super(model, e);\n }\n\n ", "post_mask_code": "{\n return stringValue;\n }\n\n protected void populateChildren(List children) {\n NodeList nl = getPeer().getChildNodes();\n if (nl != null) {\n for (int i = 0; i < nl.getLength(); i++) {\n org.w3c.dom.Node n = nl.item(i);\n if (n instanceof Element) {\n BindingsModel bindingsModel = getModel();\n BindingsComponentImpl comp = (BindingsComponentImpl) bindingsModel.getFactory().create((Element) n, this);\n if (comp != null) {\n children.add(comp);\n }\n }\n }\n }\n }\n\n protected abstract String getNamespaceURI();\n\n public BindingsModelImpl getModel() {\n return (BindingsModelImpl) super.getModel();\n }\n\n protected static org.w3c.dom.Element createNewElement(QName qName, BindingsModel model) {\n return model.getDocument().createElementNS(qName.getNamespaceURI(), qName.getLocalPart());\n }\n\n protected static org.w3c.dom.Element createPrefixedElement(QName qName, BindingsModel model) {\n org.w3c.dom.Element e = createNewElement(qName, model);\n e.setPrefix(qName.getPrefix());\n return e;\n }\n}\n"} {"task_id": "Java_2239", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/netbeans/enterprise/websvc.jaxwsmodel/src/org/netbeans/modules/websvc/api/jaxws/bindings/impl/BindingsComponentImpl.java", "mask_start_position": 1770, "mask_end_position": 1876, "canonical_solution": "{\n return model.getDocument().createElementNS(qName.getNamespaceURI(), qName.getLocalPart());\n }", "pre_mask_code": "package org.netbeans.modules.websvc.api.jaxws.bindings.impl;\n\nimport java.util.List;\nimport javax.xml.namespace.QName;\nimport org.netbeans.modules.websvc.api.jaxws.bindings.BindingsComponent;\nimport org.netbeans.modules.websvc.api.jaxws.bindings.BindingsModel;\nimport org.netbeans.modules.xml.xam.dom.Attribute;\nimport org.netbeans.modules.xml.xam.dom.AbstractDocumentComponent;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.NodeList;\n\n/**\n * @author Roderico Cruz\n */\npublic abstract class BindingsComponentImpl extends AbstractDocumentComponent implements BindingsComponent {\n\n /**\n * Creates a new instance of BindingsComponentImpl\n */\n public BindingsComponentImpl(BindingsModelImpl model, Element e) {\n super(model, e);\n }\n\n protected Object getAttributeValueOf(Attribute attr, String stringValue) {\n return stringValue;\n }\n\n protected void populateChildren(List children) {\n NodeList nl = getPeer().getChildNodes();\n if (nl != null) {\n for (int i = 0; i < nl.getLength(); i++) {\n org.w3c.dom.Node n = nl.item(i);\n if (n instanceof Element) {\n BindingsModel bindingsModel = getModel();\n BindingsComponentImpl comp = (BindingsComponentImpl) bindingsModel.getFactory().create((Element) n, this);\n if (comp != null) {\n children.add(comp);\n }\n }\n }\n }\n }\n\n protected abstract String getNamespaceURI();\n\n public BindingsModelImpl getModel() {\n return (BindingsModelImpl) super.getModel();\n }\n\n protected static org.w3c.dom.Element createNewElement(QName qName, BindingsModel model) ", "post_mask_code": "\n\n protected static org.w3c.dom.Element createPrefixedElement(QName qName, BindingsModel model) {\n org.w3c.dom.Element e = createNewElement(qName, model);\n e.setPrefix(qName.getPrefix());\n return e;\n }\n}\n"} {"task_id": "Java_2240", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/netbeans/enterprise/websvc.jaxwsmodel/src/org/netbeans/modules/websvc/api/jaxws/bindings/impl/BindingsComponentImpl.java", "mask_start_position": 2021, "mask_end_position": 2040, "canonical_solution": "ment(qName, model);", "pre_mask_code": "package org.netbeans.modules.websvc.api.jaxws.bindings.impl;\n\nimport java.util.List;\nimport javax.xml.namespace.QName;\nimport org.netbeans.modules.websvc.api.jaxws.bindings.BindingsComponent;\nimport org.netbeans.modules.websvc.api.jaxws.bindings.BindingsModel;\nimport org.netbeans.modules.xml.xam.dom.Attribute;\nimport org.netbeans.modules.xml.xam.dom.AbstractDocumentComponent;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.NodeList;\n\n/**\n * @author Roderico Cruz\n */\npublic abstract class BindingsComponentImpl extends AbstractDocumentComponent implements BindingsComponent {\n\n /**\n * Creates a new instance of BindingsComponentImpl\n */\n public BindingsComponentImpl(BindingsModelImpl model, Element e) {\n super(model, e);\n }\n\n protected Object getAttributeValueOf(Attribute attr, String stringValue) {\n return stringValue;\n }\n\n protected void populateChildren(List children) {\n NodeList nl = getPeer().getChildNodes();\n if (nl != null) {\n for (int i = 0; i < nl.getLength(); i++) {\n org.w3c.dom.Node n = nl.item(i);\n if (n instanceof Element) {\n BindingsModel bindingsModel = getModel();\n BindingsComponentImpl comp = (BindingsComponentImpl) bindingsModel.getFactory().create((Element) n, this);\n if (comp != null) {\n children.add(comp);\n }\n }\n }\n }\n }\n\n protected abstract String getNamespaceURI();\n\n public BindingsModelImpl getModel() {\n return (BindingsModelImpl) super.getModel();\n }\n\n protected static org.w3c.dom.Element createNewElement(QName qName, BindingsModel model) {\n return model.getDocument().createElementNS(qName.getNamespaceURI(), qName.getLocalPart());\n }\n\n protected static org.w3c.dom.Element createPrefixedElement(QName qName, BindingsModel model) {\n org.w3c.dom.Element e = createNewEle", "post_mask_code": "\n e.setPrefix(qName.getPrefix());\n return e;\n }\n}\n"} {"task_id": "Java_2241", "language": "Java", "task_type": "for_statement", "source_file": "java/github/apache/netbeans/enterprise/websvc.jaxwsmodel/src/org/netbeans/modules/websvc/api/jaxws/bindings/impl/BindingsComponentImpl.java", "mask_start_position": 1046, "mask_end_position": 1508, "canonical_solution": "for (int i = 0; i < nl.getLength(); i++) {\n org.w3c.dom.Node n = nl.item(i);\n if (n instanceof Element) {\n BindingsModel bindingsModel = getModel();\n BindingsComponentImpl comp = (BindingsComponentImpl) bindingsModel.getFactory().create((Element) n, this);\n if (comp != null) {\n children.add(comp);\n }\n }\n }", "pre_mask_code": "package org.netbeans.modules.websvc.api.jaxws.bindings.impl;\n\nimport java.util.List;\nimport javax.xml.namespace.QName;\nimport org.netbeans.modules.websvc.api.jaxws.bindings.BindingsComponent;\nimport org.netbeans.modules.websvc.api.jaxws.bindings.BindingsModel;\nimport org.netbeans.modules.xml.xam.dom.Attribute;\nimport org.netbeans.modules.xml.xam.dom.AbstractDocumentComponent;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.NodeList;\n\n/**\n * @author Roderico Cruz\n */\npublic abstract class BindingsComponentImpl extends AbstractDocumentComponent implements BindingsComponent {\n\n /**\n * Creates a new instance of BindingsComponentImpl\n */\n public BindingsComponentImpl(BindingsModelImpl model, Element e) {\n super(model, e);\n }\n\n protected Object getAttributeValueOf(Attribute attr, String stringValue) {\n return stringValue;\n }\n\n protected void populateChildren(List children) {\n NodeList nl = getPeer().getChildNodes();\n if (nl != null) {\n ", "post_mask_code": "\n }\n }\n\n protected abstract String getNamespaceURI();\n\n public BindingsModelImpl getModel() {\n return (BindingsModelImpl) super.getModel();\n }\n\n protected static org.w3c.dom.Element createNewElement(QName qName, BindingsModel model) {\n return model.getDocument().createElementNS(qName.getNamespaceURI(), qName.getLocalPart());\n }\n\n protected static org.w3c.dom.Element createPrefixedElement(QName qName, BindingsModel model) {\n org.w3c.dom.Element e = createNewElement(qName, model);\n e.setPrefix(qName.getPrefix());\n return e;\n }\n}\n"} {"task_id": "Java_2242", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ProtocolSupport/ProtocolSupport/src/protocolsupport/protocol/packet/middleimpl/serverbound/login/v_7_8_9r1_9r2_10_11_12r1_12r2_13_14r1_14r2_15_16r1_16r2_17r1_17r2/LoginStart.java", "mask_start_position": 434, "mask_end_position": 488, "canonical_solution": "@Override\n protected void read(ByteBuf clientdata) ", "pre_mask_code": "package protocolsupport.protocol.packet.middleimpl.serverbound.login.v_7_8_9r1_9r2_10_11_12r1_12r2_13_14r1_14r2_15_16r1_16r2_17r1_17r2;\n\nimport io.netty.buffer.ByteBuf;\nimport protocolsupport.protocol.codec.StringCodec;\nimport protocolsupport.protocol.packet.middle.serverbound.login.MiddleLoginStart;\n\npublic class LoginStart extends MiddleLoginStart {\n\n public LoginStart(MiddlePacketInit init) {\n super(init);\n }\n\n ", "post_mask_code": "{\n name = StringCodec.readVarIntUTF8String(clientdata, 16);\n }\n}\n"} {"task_id": "Java_2243", "language": "Java", "task_type": "method_body", "source_file": "java/github/ProtocolSupport/ProtocolSupport/src/protocolsupport/protocol/packet/middleimpl/serverbound/login/v_7_8_9r1_9r2_10_11_12r1_12r2_13_14r1_14r2_15_16r1_16r2_17r1_17r2/LoginStart.java", "mask_start_position": 488, "mask_end_position": 560, "canonical_solution": "{\n name = StringCodec.readVarIntUTF8String(clientdata, 16);\n }", "pre_mask_code": "package protocolsupport.protocol.packet.middleimpl.serverbound.login.v_7_8_9r1_9r2_10_11_12r1_12r2_13_14r1_14r2_15_16r1_16r2_17r1_17r2;\n\nimport io.netty.buffer.ByteBuf;\nimport protocolsupport.protocol.codec.StringCodec;\nimport protocolsupport.protocol.packet.middle.serverbound.login.MiddleLoginStart;\n\npublic class LoginStart extends MiddleLoginStart {\n\n public LoginStart(MiddlePacketInit init) {\n super(init);\n }\n\n @Override\n protected void read(ByteBuf clientdata) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2244", "language": "Java", "task_type": "single_line", "source_file": "java/github/ProtocolSupport/ProtocolSupport/src/protocolsupport/protocol/packet/middleimpl/serverbound/login/v_7_8_9r1_9r2_10_11_12r1_12r2_13_14r1_14r2_15_16r1_16r2_17r1_17r2/LoginStart.java", "mask_start_position": 515, "mask_end_position": 554, "canonical_solution": "c.readVarIntUTF8String(clientdata, 16);", "pre_mask_code": "package protocolsupport.protocol.packet.middleimpl.serverbound.login.v_7_8_9r1_9r2_10_11_12r1_12r2_13_14r1_14r2_15_16r1_16r2_17r1_17r2;\n\nimport io.netty.buffer.ByteBuf;\nimport protocolsupport.protocol.codec.StringCodec;\nimport protocolsupport.protocol.packet.middle.serverbound.login.MiddleLoginStart;\n\npublic class LoginStart extends MiddleLoginStart {\n\n public LoginStart(MiddlePacketInit init) {\n super(init);\n }\n\n @Override\n protected void read(ByteBuf clientdata) {\n name = StringCode", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2245", "language": "Java", "task_type": "method_signature", "source_file": "java/github/spirom/learning-spark-with-java/src/main/java/streaming/Windowing.java", "mask_start_position": 1268, "mask_end_position": 1307, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "package streaming;\n\nimport org.apache.spark.api.java.JavaSparkContext;\nimport org.apache.spark.sql.SparkSession;\nimport org.apache.spark.streaming.Duration;\nimport org.apache.spark.streaming.api.java.JavaDStream;\nimport org.apache.spark.streaming.api.java.JavaStreamingContext;\nimport streaming.util.CSVFileStreamGenerator;\nimport streaming.util.StreamingItem;\nimport java.io.IOException;\n\n/**\n * The windowing methods on a stream allow you to create a derived stream whose batches contain data from some\n * number fo the most recent batches in the parent stream, and producing a batch per some number of parent\n * stream batches (default is one.)\n *\n * Both the sliding window size and the batch frequency are specified as durations, which must be integer\n * multiples of the parent stream's batch duration. Of course, the parent stream could itself have been\n * derived from another stream, so its batch duration will not necessarily be the duration specified for the\n * JavaStreamingContext.\n *\n * This example creates two derived streams with different window and slide durations. All three streams print\n * their batch size every time they produce a batch, so you can compare the number of records across streams\n * and batches.\n */\npublic class Windowing {\n\n ", "post_mask_code": "{\n // The \"modern\" way to initialize Spark is to create a SparkSession\n // although they really come from the world of Spark SQL, and Dataset\n // and DataFrame.\n SparkSession spark = SparkSession.builder().appName(\"streaming-Windowing\").master(\"local[4]\").getOrCreate();\n // Operating on a raw RDD actually requires access to the more low\n // level SparkContext -- get the special Java version for convenience\n JavaSparkContext sc = new JavaSparkContext(spark.sparkContext());\n // streams will produce data every second (note: it would be nice if this was Java 8's Duration class,\n // but it isn't -- it comes from org.apache.spark.streaming)\n JavaStreamingContext ssc = new JavaStreamingContext(sc, new Duration(1000));\n // use the utility class to produce a sequence of 10 files, each containing 100 records\n CSVFileStreamGenerator fm = new CSVFileStreamGenerator(10, 100, 500);\n // create the stream, which will contain the rows of the individual files as strings\n // -- notice we can create the stream even though this directory won't have any data until we call\n JavaDStream streamOfRecords = ssc.textFileStream(fm.getDestination().getAbsolutePath());\n // Create a derived stream that will produce a batch every second (just like its parent) but the\n // batch will contain data from the parent stream's most recent two batches\n JavaDStream threeSecondsEverySecond = streamOfRecords.window(new Duration(3000));\n // Another derived stream, this time creating batch every two seconds, but containing the data from\n // the parent stream's most recent five batches\n JavaDStream fiveSecondsEveryTwoSeconds = streamOfRecords.window(new Duration(5000), new Duration(2000));\n // Register functions to print the batch sizes in all three of the streams. Notice that:\n // 1) Each stream identifies itself as either [original], [window 3s] or [window 3s slide 2s]\n // 2) The \"window duration\" is how far back int he parent's stream is included in very batch\n // 3) The \"slide duration\" is how often a \"windowed\" batch is produced byt he derived stream (default is the\n // same as the parent's \"batch duration\")\n // 4) You will see output from the [window 3s] stream every second, but only every two seconds from\n // [window 3s slide 2s] -- and you can check the item counts against the right number of most recent item\n // counts from the [original] stream.\n // 5) Time stamps are included to help you keep track of the batches\n streamOfRecords.foreachRDD((rdd, timeStamp) -> System.out.println(\"[original] TS: \" + timeStamp + \" Item count = \" + rdd.count()));\n threeSecondsEverySecond.foreachRDD((rdd, timeStamp) -> System.out.println(\"[window 3s] TS: \" + timeStamp + \" Item count = \" + rdd.count()));\n fiveSecondsEveryTwoSeconds.foreachRDD((rdd, timeStamp) -> System.out.println(\"[window 5s slide 2s] TS: \" + timeStamp + \" Item count = \" + rdd.count()));\n // start streaming\n System.out.println(\"*** about to start streaming\");\n ssc.start();\n Thread t = new Thread() {\n\n public void run() {\n try {\n // A curious fact about files based streaming is that any files written\n // before the first RDD is produced are ignored. So wait longer than\n // that before producing files.\n Thread.sleep(2000);\n System.out.println(\"*** producing data\");\n // start producing files\n fm.makeFiles();\n // give it time to get processed\n Thread.sleep(10000);\n } catch (InterruptedException ie) {\n } catch (IOException ioe) {\n throw new RuntimeException(\"problem in background thread\", ioe);\n }\n ssc.stop();\n System.out.println(\"*** stopping streaming\");\n }\n };\n t.start();\n try {\n ssc.awaitTermination();\n } catch (InterruptedException ie) {\n }\n System.out.println(\"*** Streaming terminated\");\n }\n}\n"} {"task_id": "Java_2246", "language": "Java", "task_type": "single_line", "source_file": "java/github/spirom/learning-spark-with-java/src/main/java/streaming/Windowing.java", "mask_start_position": 4116, "mask_end_position": 4249, "canonical_solution": "condsEverySecond.foreachRDD((rdd, timeStamp) -> System.out.println(\"[window 3s] TS: \" + timeStamp + \" Item count = \" + rdd.count()));", "pre_mask_code": "package streaming;\n\nimport org.apache.spark.api.java.JavaSparkContext;\nimport org.apache.spark.sql.SparkSession;\nimport org.apache.spark.streaming.Duration;\nimport org.apache.spark.streaming.api.java.JavaDStream;\nimport org.apache.spark.streaming.api.java.JavaStreamingContext;\nimport streaming.util.CSVFileStreamGenerator;\nimport streaming.util.StreamingItem;\nimport java.io.IOException;\n\n/**\n * The windowing methods on a stream allow you to create a derived stream whose batches contain data from some\n * number fo the most recent batches in the parent stream, and producing a batch per some number of parent\n * stream batches (default is one.)\n *\n * Both the sliding window size and the batch frequency are specified as durations, which must be integer\n * multiples of the parent stream's batch duration. Of course, the parent stream could itself have been\n * derived from another stream, so its batch duration will not necessarily be the duration specified for the\n * JavaStreamingContext.\n *\n * This example creates two derived streams with different window and slide durations. All three streams print\n * their batch size every time they produce a batch, so you can compare the number of records across streams\n * and batches.\n */\npublic class Windowing {\n\n public static void main(String[] args) {\n // The \"modern\" way to initialize Spark is to create a SparkSession\n // although they really come from the world of Spark SQL, and Dataset\n // and DataFrame.\n SparkSession spark = SparkSession.builder().appName(\"streaming-Windowing\").master(\"local[4]\").getOrCreate();\n // Operating on a raw RDD actually requires access to the more low\n // level SparkContext -- get the special Java version for convenience\n JavaSparkContext sc = new JavaSparkContext(spark.sparkContext());\n // streams will produce data every second (note: it would be nice if this was Java 8's Duration class,\n // but it isn't -- it comes from org.apache.spark.streaming)\n JavaStreamingContext ssc = new JavaStreamingContext(sc, new Duration(1000));\n // use the utility class to produce a sequence of 10 files, each containing 100 records\n CSVFileStreamGenerator fm = new CSVFileStreamGenerator(10, 100, 500);\n // create the stream, which will contain the rows of the individual files as strings\n // -- notice we can create the stream even though this directory won't have any data until we call\n JavaDStream streamOfRecords = ssc.textFileStream(fm.getDestination().getAbsolutePath());\n // Create a derived stream that will produce a batch every second (just like its parent) but the\n // batch will contain data from the parent stream's most recent two batches\n JavaDStream threeSecondsEverySecond = streamOfRecords.window(new Duration(3000));\n // Another derived stream, this time creating batch every two seconds, but containing the data from\n // the parent stream's most recent five batches\n JavaDStream fiveSecondsEveryTwoSeconds = streamOfRecords.window(new Duration(5000), new Duration(2000));\n // Register functions to print the batch sizes in all three of the streams. Notice that:\n // 1) Each stream identifies itself as either [original], [window 3s] or [window 3s slide 2s]\n // 2) The \"window duration\" is how far back int he parent's stream is included in very batch\n // 3) The \"slide duration\" is how often a \"windowed\" batch is produced byt he derived stream (default is the\n // same as the parent's \"batch duration\")\n // 4) You will see output from the [window 3s] stream every second, but only every two seconds from\n // [window 3s slide 2s] -- and you can check the item counts against the right number of most recent item\n // counts from the [original] stream.\n // 5) Time stamps are included to help you keep track of the batches\n streamOfRecords.foreachRDD((rdd, timeStamp) -> System.out.println(\"[original] TS: \" + timeStamp + \" Item count = \" + rdd.count()));\n threeSe", "post_mask_code": "\n fiveSecondsEveryTwoSeconds.foreachRDD((rdd, timeStamp) -> System.out.println(\"[window 5s slide 2s] TS: \" + timeStamp + \" Item count = \" + rdd.count()));\n // start streaming\n System.out.println(\"*** about to start streaming\");\n ssc.start();\n Thread t = new Thread() {\n\n public void run() {\n try {\n // A curious fact about files based streaming is that any files written\n // before the first RDD is produced are ignored. So wait longer than\n // that before producing files.\n Thread.sleep(2000);\n System.out.println(\"*** producing data\");\n // start producing files\n fm.makeFiles();\n // give it time to get processed\n Thread.sleep(10000);\n } catch (InterruptedException ie) {\n } catch (IOException ioe) {\n throw new RuntimeException(\"problem in background thread\", ioe);\n }\n ssc.stop();\n System.out.println(\"*** stopping streaming\");\n }\n };\n t.start();\n try {\n ssc.awaitTermination();\n } catch (InterruptedException ie) {\n }\n System.out.println(\"*** Streaming terminated\");\n }\n}\n"} {"task_id": "Java_2247", "language": "Java", "task_type": "try_statement", "source_file": "java/github/spirom/learning-spark-with-java/src/main/java/streaming/Windowing.java", "mask_start_position": 5459, "mask_end_position": 5554, "canonical_solution": "try {\n ssc.awaitTermination();\n } catch (InterruptedException ie) {\n }", "pre_mask_code": "package streaming;\n\nimport org.apache.spark.api.java.JavaSparkContext;\nimport org.apache.spark.sql.SparkSession;\nimport org.apache.spark.streaming.Duration;\nimport org.apache.spark.streaming.api.java.JavaDStream;\nimport org.apache.spark.streaming.api.java.JavaStreamingContext;\nimport streaming.util.CSVFileStreamGenerator;\nimport streaming.util.StreamingItem;\nimport java.io.IOException;\n\n/**\n * The windowing methods on a stream allow you to create a derived stream whose batches contain data from some\n * number fo the most recent batches in the parent stream, and producing a batch per some number of parent\n * stream batches (default is one.)\n *\n * Both the sliding window size and the batch frequency are specified as durations, which must be integer\n * multiples of the parent stream's batch duration. Of course, the parent stream could itself have been\n * derived from another stream, so its batch duration will not necessarily be the duration specified for the\n * JavaStreamingContext.\n *\n * This example creates two derived streams with different window and slide durations. All three streams print\n * their batch size every time they produce a batch, so you can compare the number of records across streams\n * and batches.\n */\npublic class Windowing {\n\n public static void main(String[] args) {\n // The \"modern\" way to initialize Spark is to create a SparkSession\n // although they really come from the world of Spark SQL, and Dataset\n // and DataFrame.\n SparkSession spark = SparkSession.builder().appName(\"streaming-Windowing\").master(\"local[4]\").getOrCreate();\n // Operating on a raw RDD actually requires access to the more low\n // level SparkContext -- get the special Java version for convenience\n JavaSparkContext sc = new JavaSparkContext(spark.sparkContext());\n // streams will produce data every second (note: it would be nice if this was Java 8's Duration class,\n // but it isn't -- it comes from org.apache.spark.streaming)\n JavaStreamingContext ssc = new JavaStreamingContext(sc, new Duration(1000));\n // use the utility class to produce a sequence of 10 files, each containing 100 records\n CSVFileStreamGenerator fm = new CSVFileStreamGenerator(10, 100, 500);\n // create the stream, which will contain the rows of the individual files as strings\n // -- notice we can create the stream even though this directory won't have any data until we call\n JavaDStream streamOfRecords = ssc.textFileStream(fm.getDestination().getAbsolutePath());\n // Create a derived stream that will produce a batch every second (just like its parent) but the\n // batch will contain data from the parent stream's most recent two batches\n JavaDStream threeSecondsEverySecond = streamOfRecords.window(new Duration(3000));\n // Another derived stream, this time creating batch every two seconds, but containing the data from\n // the parent stream's most recent five batches\n JavaDStream fiveSecondsEveryTwoSeconds = streamOfRecords.window(new Duration(5000), new Duration(2000));\n // Register functions to print the batch sizes in all three of the streams. Notice that:\n // 1) Each stream identifies itself as either [original], [window 3s] or [window 3s slide 2s]\n // 2) The \"window duration\" is how far back int he parent's stream is included in very batch\n // 3) The \"slide duration\" is how often a \"windowed\" batch is produced byt he derived stream (default is the\n // same as the parent's \"batch duration\")\n // 4) You will see output from the [window 3s] stream every second, but only every two seconds from\n // [window 3s slide 2s] -- and you can check the item counts against the right number of most recent item\n // counts from the [original] stream.\n // 5) Time stamps are included to help you keep track of the batches\n streamOfRecords.foreachRDD((rdd, timeStamp) -> System.out.println(\"[original] TS: \" + timeStamp + \" Item count = \" + rdd.count()));\n threeSecondsEverySecond.foreachRDD((rdd, timeStamp) -> System.out.println(\"[window 3s] TS: \" + timeStamp + \" Item count = \" + rdd.count()));\n fiveSecondsEveryTwoSeconds.foreachRDD((rdd, timeStamp) -> System.out.println(\"[window 5s slide 2s] TS: \" + timeStamp + \" Item count = \" + rdd.count()));\n // start streaming\n System.out.println(\"*** about to start streaming\");\n ssc.start();\n Thread t = new Thread() {\n\n public void run() {\n try {\n // A curious fact about files based streaming is that any files written\n // before the first RDD is produced are ignored. So wait longer than\n // that before producing files.\n Thread.sleep(2000);\n System.out.println(\"*** producing data\");\n // start producing files\n fm.makeFiles();\n // give it time to get processed\n Thread.sleep(10000);\n } catch (InterruptedException ie) {\n } catch (IOException ioe) {\n throw new RuntimeException(\"problem in background thread\", ioe);\n }\n ssc.stop();\n System.out.println(\"*** stopping streaming\");\n }\n };\n t.start();\n ", "post_mask_code": "\n System.out.println(\"*** Streaming terminated\");\n }\n}\n"} {"task_id": "Java_2248", "language": "Java", "task_type": "method_signature", "source_file": "java/github/droidcon/iosched/android/src/main/java/com/funkyandroid/droidcon/uk/iosched/util/HelpUtils.java", "mask_start_position": 3778, "mask_end_position": 3839, "canonical_solution": "public void onClick(DialogInterface dialog, int whichButton) ", "pre_mask_code": "package com.funkyandroid.droidcon.uk.iosched.util;\n\nimport com.funkyandroid.droidcon.uk.iosched.R;\nimport android.app.AlertDialog;\nimport android.app.Dialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.os.Bundle;\nimport android.support.v4.app.DialogFragment;\nimport android.support.v4.app.Fragment;\nimport android.support.v4.app.FragmentActivity;\nimport android.support.v4.app.FragmentManager;\nimport android.support.v4.app.FragmentTransaction;\nimport android.text.Html;\nimport android.text.SpannableString;\nimport android.text.SpannableStringBuilder;\nimport android.text.method.LinkMovementMethod;\nimport android.text.style.ClickableSpan;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.webkit.WebView;\nimport android.widget.TextView;\n\n/**\n * This is a set of helper methods for showing contextual help information in the app.\n */\npublic class HelpUtils {\n\n public static void showAbout(FragmentActivity activity) {\n FragmentManager fm = activity.getSupportFragmentManager();\n FragmentTransaction ft = fm.beginTransaction();\n Fragment prev = fm.findFragmentByTag(\"dialog_about\");\n if (prev != null) {\n ft.remove(prev);\n }\n ft.addToBackStack(null);\n new AboutDialog().show(ft, \"dialog_about\");\n }\n\n public static class AboutDialog extends DialogFragment {\n\n private static final String VERSION_UNAVAILABLE = \"N/A\";\n\n public AboutDialog() {\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n // Get app version\n PackageManager pm = getActivity().getPackageManager();\n String packageName = getActivity().getPackageName();\n String versionName;\n try {\n PackageInfo info = pm.getPackageInfo(packageName, 0);\n versionName = info.versionName;\n } catch (PackageManager.NameNotFoundException e) {\n versionName = VERSION_UNAVAILABLE;\n }\n // Build the about body view and append the link to see OSS licenses\n SpannableStringBuilder aboutBody = new SpannableStringBuilder();\n aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));\n SpannableString licensesLink = new SpannableString(getString(R.string.about_licenses));\n licensesLink.setSpan(new ClickableSpan() {\n\n @Override\n public void onClick(View view) {\n HelpUtils.showOpenSourceLicenses(getActivity());\n }\n }, 0, licensesLink.length(), 0);\n aboutBody.append(\"\\n\\n\");\n aboutBody.append(licensesLink);\n SpannableString eulaLink = new SpannableString(getString(R.string.about_eula));\n eulaLink.setSpan(new ClickableSpan() {\n\n @Override\n public void onClick(View view) {\n HelpUtils.showEula(getActivity());\n }\n }, 0, eulaLink.length(), 0);\n aboutBody.append(\"\\n\\n\");\n aboutBody.append(eulaLink);\n LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.dialog_about, null);\n aboutBodyView.setText(aboutBody);\n aboutBodyView.setMovementMethod(new LinkMovementMethod());\n return new AlertDialog.Builder(getActivity()).setTitle(R.string.title_about).setView(aboutBodyView).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n\n ", "post_mask_code": "{\n dialog.dismiss();\n }\n }).create();\n }\n }\n\n public static void showOpenSourceLicenses(FragmentActivity activity) {\n FragmentManager fm = activity.getSupportFragmentManager();\n FragmentTransaction ft = fm.beginTransaction();\n Fragment prev = fm.findFragmentByTag(\"dialog_licenses\");\n if (prev != null) {\n ft.remove(prev);\n }\n ft.addToBackStack(null);\n new OpenSourceLicensesDialog().show(ft, \"dialog_licenses\");\n }\n\n public static class OpenSourceLicensesDialog extends DialogFragment {\n\n public OpenSourceLicensesDialog() {\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n WebView webView = new WebView(getActivity());\n webView.loadUrl(\"file:///android_asset/licenses.html\");\n return new AlertDialog.Builder(getActivity()).setTitle(R.string.about_licenses).setView(webView).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n dialog.dismiss();\n }\n }).create();\n }\n }\n\n public static void showEula(FragmentActivity activity) {\n FragmentManager fm = activity.getSupportFragmentManager();\n FragmentTransaction ft = fm.beginTransaction();\n Fragment prev = fm.findFragmentByTag(\"dialog_eula\");\n if (prev != null) {\n ft.remove(prev);\n }\n ft.addToBackStack(null);\n new EulaDialog().show(ft, \"dialog_eula\");\n }\n\n public static class EulaDialog extends DialogFragment {\n\n public EulaDialog() {\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n int padding = getResources().getDimensionPixelSize(R.dimen.content_padding_normal);\n TextView eulaTextView = new TextView(getActivity());\n eulaTextView.setText(Html.fromHtml(getString(R.string.eula_text)));\n eulaTextView.setMovementMethod(LinkMovementMethod.getInstance());\n eulaTextView.setPadding(padding, padding, padding, padding);\n return new AlertDialog.Builder(getActivity()).setTitle(R.string.about_eula).setView(eulaTextView).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n dialog.dismiss();\n }\n }).create();\n }\n }\n}\n"} {"task_id": "Java_2249", "language": "Java", "task_type": "method_body", "source_file": "java/github/droidcon/iosched/android/src/main/java/com/funkyandroid/droidcon/uk/iosched/util/HelpUtils.java", "mask_start_position": 2607, "mask_end_position": 2695, "canonical_solution": "{\n HelpUtils.showOpenSourceLicenses(getActivity());\n }", "pre_mask_code": "package com.funkyandroid.droidcon.uk.iosched.util;\n\nimport com.funkyandroid.droidcon.uk.iosched.R;\nimport android.app.AlertDialog;\nimport android.app.Dialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.os.Bundle;\nimport android.support.v4.app.DialogFragment;\nimport android.support.v4.app.Fragment;\nimport android.support.v4.app.FragmentActivity;\nimport android.support.v4.app.FragmentManager;\nimport android.support.v4.app.FragmentTransaction;\nimport android.text.Html;\nimport android.text.SpannableString;\nimport android.text.SpannableStringBuilder;\nimport android.text.method.LinkMovementMethod;\nimport android.text.style.ClickableSpan;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.webkit.WebView;\nimport android.widget.TextView;\n\n/**\n * This is a set of helper methods for showing contextual help information in the app.\n */\npublic class HelpUtils {\n\n public static void showAbout(FragmentActivity activity) {\n FragmentManager fm = activity.getSupportFragmentManager();\n FragmentTransaction ft = fm.beginTransaction();\n Fragment prev = fm.findFragmentByTag(\"dialog_about\");\n if (prev != null) {\n ft.remove(prev);\n }\n ft.addToBackStack(null);\n new AboutDialog().show(ft, \"dialog_about\");\n }\n\n public static class AboutDialog extends DialogFragment {\n\n private static final String VERSION_UNAVAILABLE = \"N/A\";\n\n public AboutDialog() {\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n // Get app version\n PackageManager pm = getActivity().getPackageManager();\n String packageName = getActivity().getPackageName();\n String versionName;\n try {\n PackageInfo info = pm.getPackageInfo(packageName, 0);\n versionName = info.versionName;\n } catch (PackageManager.NameNotFoundException e) {\n versionName = VERSION_UNAVAILABLE;\n }\n // Build the about body view and append the link to see OSS licenses\n SpannableStringBuilder aboutBody = new SpannableStringBuilder();\n aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));\n SpannableString licensesLink = new SpannableString(getString(R.string.about_licenses));\n licensesLink.setSpan(new ClickableSpan() {\n\n @Override\n public void onClick(View view) ", "post_mask_code": "\n }, 0, licensesLink.length(), 0);\n aboutBody.append(\"\\n\\n\");\n aboutBody.append(licensesLink);\n SpannableString eulaLink = new SpannableString(getString(R.string.about_eula));\n eulaLink.setSpan(new ClickableSpan() {\n\n @Override\n public void onClick(View view) {\n HelpUtils.showEula(getActivity());\n }\n }, 0, eulaLink.length(), 0);\n aboutBody.append(\"\\n\\n\");\n aboutBody.append(eulaLink);\n LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.dialog_about, null);\n aboutBodyView.setText(aboutBody);\n aboutBodyView.setMovementMethod(new LinkMovementMethod());\n return new AlertDialog.Builder(getActivity()).setTitle(R.string.title_about).setView(aboutBodyView).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n dialog.dismiss();\n }\n }).create();\n }\n }\n\n public static void showOpenSourceLicenses(FragmentActivity activity) {\n FragmentManager fm = activity.getSupportFragmentManager();\n FragmentTransaction ft = fm.beginTransaction();\n Fragment prev = fm.findFragmentByTag(\"dialog_licenses\");\n if (prev != null) {\n ft.remove(prev);\n }\n ft.addToBackStack(null);\n new OpenSourceLicensesDialog().show(ft, \"dialog_licenses\");\n }\n\n public static class OpenSourceLicensesDialog extends DialogFragment {\n\n public OpenSourceLicensesDialog() {\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n WebView webView = new WebView(getActivity());\n webView.loadUrl(\"file:///android_asset/licenses.html\");\n return new AlertDialog.Builder(getActivity()).setTitle(R.string.about_licenses).setView(webView).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n dialog.dismiss();\n }\n }).create();\n }\n }\n\n public static void showEula(FragmentActivity activity) {\n FragmentManager fm = activity.getSupportFragmentManager();\n FragmentTransaction ft = fm.beginTransaction();\n Fragment prev = fm.findFragmentByTag(\"dialog_eula\");\n if (prev != null) {\n ft.remove(prev);\n }\n ft.addToBackStack(null);\n new EulaDialog().show(ft, \"dialog_eula\");\n }\n\n public static class EulaDialog extends DialogFragment {\n\n public EulaDialog() {\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n int padding = getResources().getDimensionPixelSize(R.dimen.content_padding_normal);\n TextView eulaTextView = new TextView(getActivity());\n eulaTextView.setText(Html.fromHtml(getString(R.string.eula_text)));\n eulaTextView.setMovementMethod(LinkMovementMethod.getInstance());\n eulaTextView.setPadding(padding, padding, padding, padding);\n return new AlertDialog.Builder(getActivity()).setTitle(R.string.about_eula).setView(eulaTextView).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n dialog.dismiss();\n }\n }).create();\n }\n }\n}\n"} {"task_id": "Java_2250", "language": "Java", "task_type": "single_line", "source_file": "java/github/droidcon/iosched/android/src/main/java/com/funkyandroid/droidcon/uk/iosched/util/HelpUtils.java", "mask_start_position": 1182, "mask_end_position": 1195, "canonical_solution": "ransaction();", "pre_mask_code": "package com.funkyandroid.droidcon.uk.iosched.util;\n\nimport com.funkyandroid.droidcon.uk.iosched.R;\nimport android.app.AlertDialog;\nimport android.app.Dialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.os.Bundle;\nimport android.support.v4.app.DialogFragment;\nimport android.support.v4.app.Fragment;\nimport android.support.v4.app.FragmentActivity;\nimport android.support.v4.app.FragmentManager;\nimport android.support.v4.app.FragmentTransaction;\nimport android.text.Html;\nimport android.text.SpannableString;\nimport android.text.SpannableStringBuilder;\nimport android.text.method.LinkMovementMethod;\nimport android.text.style.ClickableSpan;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.webkit.WebView;\nimport android.widget.TextView;\n\n/**\n * This is a set of helper methods for showing contextual help information in the app.\n */\npublic class HelpUtils {\n\n public static void showAbout(FragmentActivity activity) {\n FragmentManager fm = activity.getSupportFragmentManager();\n FragmentTransaction ft = fm.beginT", "post_mask_code": "\n Fragment prev = fm.findFragmentByTag(\"dialog_about\");\n if (prev != null) {\n ft.remove(prev);\n }\n ft.addToBackStack(null);\n new AboutDialog().show(ft, \"dialog_about\");\n }\n\n public static class AboutDialog extends DialogFragment {\n\n private static final String VERSION_UNAVAILABLE = \"N/A\";\n\n public AboutDialog() {\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n // Get app version\n PackageManager pm = getActivity().getPackageManager();\n String packageName = getActivity().getPackageName();\n String versionName;\n try {\n PackageInfo info = pm.getPackageInfo(packageName, 0);\n versionName = info.versionName;\n } catch (PackageManager.NameNotFoundException e) {\n versionName = VERSION_UNAVAILABLE;\n }\n // Build the about body view and append the link to see OSS licenses\n SpannableStringBuilder aboutBody = new SpannableStringBuilder();\n aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));\n SpannableString licensesLink = new SpannableString(getString(R.string.about_licenses));\n licensesLink.setSpan(new ClickableSpan() {\n\n @Override\n public void onClick(View view) {\n HelpUtils.showOpenSourceLicenses(getActivity());\n }\n }, 0, licensesLink.length(), 0);\n aboutBody.append(\"\\n\\n\");\n aboutBody.append(licensesLink);\n SpannableString eulaLink = new SpannableString(getString(R.string.about_eula));\n eulaLink.setSpan(new ClickableSpan() {\n\n @Override\n public void onClick(View view) {\n HelpUtils.showEula(getActivity());\n }\n }, 0, eulaLink.length(), 0);\n aboutBody.append(\"\\n\\n\");\n aboutBody.append(eulaLink);\n LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.dialog_about, null);\n aboutBodyView.setText(aboutBody);\n aboutBodyView.setMovementMethod(new LinkMovementMethod());\n return new AlertDialog.Builder(getActivity()).setTitle(R.string.title_about).setView(aboutBodyView).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n dialog.dismiss();\n }\n }).create();\n }\n }\n\n public static void showOpenSourceLicenses(FragmentActivity activity) {\n FragmentManager fm = activity.getSupportFragmentManager();\n FragmentTransaction ft = fm.beginTransaction();\n Fragment prev = fm.findFragmentByTag(\"dialog_licenses\");\n if (prev != null) {\n ft.remove(prev);\n }\n ft.addToBackStack(null);\n new OpenSourceLicensesDialog().show(ft, \"dialog_licenses\");\n }\n\n public static class OpenSourceLicensesDialog extends DialogFragment {\n\n public OpenSourceLicensesDialog() {\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n WebView webView = new WebView(getActivity());\n webView.loadUrl(\"file:///android_asset/licenses.html\");\n return new AlertDialog.Builder(getActivity()).setTitle(R.string.about_licenses).setView(webView).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n dialog.dismiss();\n }\n }).create();\n }\n }\n\n public static void showEula(FragmentActivity activity) {\n FragmentManager fm = activity.getSupportFragmentManager();\n FragmentTransaction ft = fm.beginTransaction();\n Fragment prev = fm.findFragmentByTag(\"dialog_eula\");\n if (prev != null) {\n ft.remove(prev);\n }\n ft.addToBackStack(null);\n new EulaDialog().show(ft, \"dialog_eula\");\n }\n\n public static class EulaDialog extends DialogFragment {\n\n public EulaDialog() {\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n int padding = getResources().getDimensionPixelSize(R.dimen.content_padding_normal);\n TextView eulaTextView = new TextView(getActivity());\n eulaTextView.setText(Html.fromHtml(getString(R.string.eula_text)));\n eulaTextView.setMovementMethod(LinkMovementMethod.getInstance());\n eulaTextView.setPadding(padding, padding, padding, padding);\n return new AlertDialog.Builder(getActivity()).setTitle(R.string.about_eula).setView(eulaTextView).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n dialog.dismiss();\n }\n }).create();\n }\n }\n}\n"} {"task_id": "Java_2251", "language": "Java", "task_type": "try_statement", "source_file": "java/github/droidcon/iosched/android/src/main/java/com/funkyandroid/droidcon/uk/iosched/util/HelpUtils.java", "mask_start_position": 1878, "mask_end_position": 2129, "canonical_solution": "try {\n PackageInfo info = pm.getPackageInfo(packageName, 0);\n versionName = info.versionName;\n } catch (PackageManager.NameNotFoundException e) {\n versionName = VERSION_UNAVAILABLE;\n }", "pre_mask_code": "package com.funkyandroid.droidcon.uk.iosched.util;\n\nimport com.funkyandroid.droidcon.uk.iosched.R;\nimport android.app.AlertDialog;\nimport android.app.Dialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.os.Bundle;\nimport android.support.v4.app.DialogFragment;\nimport android.support.v4.app.Fragment;\nimport android.support.v4.app.FragmentActivity;\nimport android.support.v4.app.FragmentManager;\nimport android.support.v4.app.FragmentTransaction;\nimport android.text.Html;\nimport android.text.SpannableString;\nimport android.text.SpannableStringBuilder;\nimport android.text.method.LinkMovementMethod;\nimport android.text.style.ClickableSpan;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.webkit.WebView;\nimport android.widget.TextView;\n\n/**\n * This is a set of helper methods for showing contextual help information in the app.\n */\npublic class HelpUtils {\n\n public static void showAbout(FragmentActivity activity) {\n FragmentManager fm = activity.getSupportFragmentManager();\n FragmentTransaction ft = fm.beginTransaction();\n Fragment prev = fm.findFragmentByTag(\"dialog_about\");\n if (prev != null) {\n ft.remove(prev);\n }\n ft.addToBackStack(null);\n new AboutDialog().show(ft, \"dialog_about\");\n }\n\n public static class AboutDialog extends DialogFragment {\n\n private static final String VERSION_UNAVAILABLE = \"N/A\";\n\n public AboutDialog() {\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n // Get app version\n PackageManager pm = getActivity().getPackageManager();\n String packageName = getActivity().getPackageName();\n String versionName;\n ", "post_mask_code": "\n // Build the about body view and append the link to see OSS licenses\n SpannableStringBuilder aboutBody = new SpannableStringBuilder();\n aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));\n SpannableString licensesLink = new SpannableString(getString(R.string.about_licenses));\n licensesLink.setSpan(new ClickableSpan() {\n\n @Override\n public void onClick(View view) {\n HelpUtils.showOpenSourceLicenses(getActivity());\n }\n }, 0, licensesLink.length(), 0);\n aboutBody.append(\"\\n\\n\");\n aboutBody.append(licensesLink);\n SpannableString eulaLink = new SpannableString(getString(R.string.about_eula));\n eulaLink.setSpan(new ClickableSpan() {\n\n @Override\n public void onClick(View view) {\n HelpUtils.showEula(getActivity());\n }\n }, 0, eulaLink.length(), 0);\n aboutBody.append(\"\\n\\n\");\n aboutBody.append(eulaLink);\n LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.dialog_about, null);\n aboutBodyView.setText(aboutBody);\n aboutBodyView.setMovementMethod(new LinkMovementMethod());\n return new AlertDialog.Builder(getActivity()).setTitle(R.string.title_about).setView(aboutBodyView).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n dialog.dismiss();\n }\n }).create();\n }\n }\n\n public static void showOpenSourceLicenses(FragmentActivity activity) {\n FragmentManager fm = activity.getSupportFragmentManager();\n FragmentTransaction ft = fm.beginTransaction();\n Fragment prev = fm.findFragmentByTag(\"dialog_licenses\");\n if (prev != null) {\n ft.remove(prev);\n }\n ft.addToBackStack(null);\n new OpenSourceLicensesDialog().show(ft, \"dialog_licenses\");\n }\n\n public static class OpenSourceLicensesDialog extends DialogFragment {\n\n public OpenSourceLicensesDialog() {\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n WebView webView = new WebView(getActivity());\n webView.loadUrl(\"file:///android_asset/licenses.html\");\n return new AlertDialog.Builder(getActivity()).setTitle(R.string.about_licenses).setView(webView).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n dialog.dismiss();\n }\n }).create();\n }\n }\n\n public static void showEula(FragmentActivity activity) {\n FragmentManager fm = activity.getSupportFragmentManager();\n FragmentTransaction ft = fm.beginTransaction();\n Fragment prev = fm.findFragmentByTag(\"dialog_eula\");\n if (prev != null) {\n ft.remove(prev);\n }\n ft.addToBackStack(null);\n new EulaDialog().show(ft, \"dialog_eula\");\n }\n\n public static class EulaDialog extends DialogFragment {\n\n public EulaDialog() {\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n int padding = getResources().getDimensionPixelSize(R.dimen.content_padding_normal);\n TextView eulaTextView = new TextView(getActivity());\n eulaTextView.setText(Html.fromHtml(getString(R.string.eula_text)));\n eulaTextView.setMovementMethod(LinkMovementMethod.getInstance());\n eulaTextView.setPadding(padding, padding, padding, padding);\n return new AlertDialog.Builder(getActivity()).setTitle(R.string.about_eula).setView(eulaTextView).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n dialog.dismiss();\n }\n }).create();\n }\n }\n}\n"} {"task_id": "Java_2252", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/maven-resolver/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferEvent.java", "mask_start_position": 9355, "mask_end_position": 9413, "canonical_solution": "public Builder setTransferredBytes(long transferredBytes) ", "pre_mask_code": "package org.eclipse.aether.transfer;\n\nimport java.nio.ByteBuffer;\nimport static java.util.Objects.requireNonNull;\nimport org.eclipse.aether.RepositorySystemSession;\n\n/**\n * An event fired to a transfer listener during an artifact/metadata transfer.\n *\n * @see TransferListener\n * @see TransferEvent.Builder\n */\npublic final class TransferEvent {\n\n /**\n * The type of the event.\n */\n public enum EventType {\n\n /**\n * @see TransferListener#transferInitiated(TransferEvent)\n */\n INITIATED,\n /**\n * @see TransferListener#transferStarted(TransferEvent)\n */\n STARTED,\n /**\n * @see TransferListener#transferProgressed(TransferEvent)\n */\n PROGRESSED,\n /**\n * @see TransferListener#transferCorrupted(TransferEvent)\n */\n CORRUPTED,\n /**\n * @see TransferListener#transferSucceeded(TransferEvent)\n */\n SUCCEEDED,\n /**\n * @see TransferListener#transferFailed(TransferEvent)\n */\n FAILED\n }\n\n /**\n * The type of the request/transfer being performed.\n */\n public enum RequestType {\n\n GET,\n /**\n * Check artifact/metadata existence only.\n */\n GET_EXISTENCE,\n PUT\n }\n\n private final EventType type;\n\n private final RequestType requestType;\n\n private final RepositorySystemSession session;\n\n private final TransferResource resource;\n\n private final ByteBuffer dataBuffer;\n\n private final long transferredBytes;\n\n private final Exception exception;\n\n TransferEvent(Builder builder) {\n type = builder.type;\n requestType = builder.requestType;\n session = builder.session;\n resource = builder.resource;\n dataBuffer = builder.dataBuffer;\n transferredBytes = builder.transferredBytes;\n exception = builder.exception;\n }\n\n /**\n * Gets the type of the event.\n *\n * @return The type of the event, never {@code null}.\n */\n public EventType getType() {\n return type;\n }\n\n /**\n * Gets the type of the request/transfer.\n *\n * @return The type of the request/transfer, never {@code null}.\n */\n public RequestType getRequestType() {\n return requestType;\n }\n\n /**\n * Gets the repository system session during which the event occurred.\n *\n * @return The repository system session during which the event occurred, never {@code null}.\n */\n public RepositorySystemSession getSession() {\n return session;\n }\n\n /**\n * Gets the resource that is being transferred.\n *\n * @return The resource being transferred, never {@code null}.\n */\n public TransferResource getResource() {\n return resource;\n }\n\n /**\n * Gets the total number of bytes that have been transferred since the download/upload of the resource was started.\n * If a download has been resumed, the returned count includes the bytes that were already downloaded during the\n * previous attempt. In other words, the ratio of transferred bytes to the content length of the resource indicates\n * the percentage of transfer completion.\n *\n * @return The total number of bytes that have been transferred since the transfer started, never negative.\n * @see #getDataLength()\n * @see TransferResource#getResumeOffset()\n */\n public long getTransferredBytes() {\n return transferredBytes;\n }\n\n /**\n * Gets the byte buffer holding the transferred bytes since the last event. A listener must assume this buffer to be\n * owned by the event source and must not change any byte in this buffer. Also, the buffer is only valid for the\n * duration of the event callback, i.e. the next event might reuse the same buffer (with updated contents).\n * Therefore, if the actual event processing is deferred, the byte buffer would have to be cloned to create an\n * immutable snapshot of its contents.\n *\n * @return The (read-only) byte buffer or {@code null} if not applicable to the event, i.e. if the event type is not\n * {@link EventType#PROGRESSED}.\n */\n public ByteBuffer getDataBuffer() {\n return (dataBuffer != null) ? dataBuffer.asReadOnlyBuffer() : null;\n }\n\n /**\n * Gets the number of bytes that have been transferred since the last event.\n *\n * @return The number of bytes that have been transferred since the last event, possibly zero but never negative.\n * @see #getTransferredBytes()\n */\n public int getDataLength() {\n return (dataBuffer != null) ? dataBuffer.remaining() : 0;\n }\n\n /**\n * Gets the error that occurred during the transfer.\n *\n * @return The error that occurred or {@code null} if none.\n */\n public Exception getException() {\n return exception;\n }\n\n @Override\n public String toString() {\n return getRequestType() + \" \" + getType() + \" \" + getResource();\n }\n\n /**\n * A builder to create transfer events.\n */\n public static final class Builder {\n\n EventType type;\n\n RequestType requestType;\n\n final RepositorySystemSession session;\n\n final TransferResource resource;\n\n ByteBuffer dataBuffer;\n\n long transferredBytes;\n\n Exception exception;\n\n /**\n * Creates a new transfer event builder for the specified session and the given resource.\n *\n * @param session The repository system session, must not be {@code null}.\n * @param resource The resource being transferred, must not be {@code null}.\n */\n public Builder(RepositorySystemSession session, TransferResource resource) {\n this.session = requireNonNull(session, \"repository system session cannot be null\");\n this.resource = requireNonNull(resource, \"transfer resource cannot be null\");\n type = EventType.INITIATED;\n requestType = RequestType.GET;\n }\n\n private Builder(Builder prototype) {\n session = prototype.session;\n resource = prototype.resource;\n type = prototype.type;\n requestType = prototype.requestType;\n dataBuffer = prototype.dataBuffer;\n transferredBytes = prototype.transferredBytes;\n exception = prototype.exception;\n }\n\n /**\n * Creates a new transfer event builder from the current values of this builder. The state of this builder\n * remains unchanged.\n *\n * @return The new event builder, never {@code null}.\n */\n public Builder copy() {\n return new Builder(this);\n }\n\n /**\n * Sets the type of the event and resets event-specific fields. In more detail, the data buffer and the\n * exception fields are set to {@code null}. Furthermore, the total number of transferred bytes is set to\n * {@code 0} if the event type is {@link EventType#STARTED}.\n *\n * @param type The type of the event, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder resetType(EventType type) {\n this.type = requireNonNull(type, \"event type cannot be null\");\n dataBuffer = null;\n exception = null;\n switch(type) {\n case INITIATED:\n case STARTED:\n transferredBytes = 0L;\n default:\n }\n return this;\n }\n\n /**\n * Sets the type of the event. When re-using the same builder to generate a sequence of events for one transfer,\n * {@link #resetType(TransferEvent.EventType)} might be more handy.\n *\n * @param type The type of the event, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setType(EventType type) {\n this.type = requireNonNull(type, \"event type cannot be null\");\n return this;\n }\n\n /**\n * Sets the type of the request/transfer.\n *\n * @param requestType The request/transfer type, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setRequestType(RequestType requestType) {\n this.requestType = requireNonNull(requestType, \"request type cannot be null\");\n return this;\n }\n\n /**\n * Sets the total number of bytes that have been transferred so far during the download/upload of the resource.\n * If a download is being resumed, the count must include the bytes that were already downloaded in the previous\n * attempt and from which the current transfer started. In this case, the event type {@link EventType#STARTED}\n * should indicate from what byte the download resumes.\n *\n * @param transferredBytes The total number of bytes that have been transferred so far during the\n * download/upload of the resource, must not be negative.\n * @return This event builder for chaining, never {@code null}.\n * @see TransferResource#setResumeOffset(long)\n */\n ", "post_mask_code": "{\n if (transferredBytes < 0L) {\n throw new IllegalArgumentException(\"number of transferred bytes cannot be negative\");\n }\n this.transferredBytes = transferredBytes;\n return this;\n }\n\n /**\n * Increments the total number of bytes that have been transferred so far during the download/upload.\n *\n * @param transferredBytes The number of bytes that have been transferred since the last event, must not be\n * negative.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder addTransferredBytes(long transferredBytes) {\n if (transferredBytes < 0L) {\n throw new IllegalArgumentException(\"number of transferred bytes cannot be negative\");\n }\n this.transferredBytes += transferredBytes;\n return this;\n }\n\n /**\n * Sets the byte buffer holding the transferred bytes since the last event.\n *\n * @param buffer The byte buffer holding the transferred bytes since the last event, may be {@code null} if not\n * applicable to the event.\n * @param offset The starting point of valid bytes in the array.\n * @param length The number of valid bytes, must not be negative.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setDataBuffer(byte[] buffer, int offset, int length) {\n return setDataBuffer((buffer != null) ? ByteBuffer.wrap(buffer, offset, length) : null);\n }\n\n /**\n * Sets the byte buffer holding the transferred bytes since the last event.\n *\n * @param dataBuffer The byte buffer holding the transferred bytes since the last event, may be {@code null} if\n * not applicable to the event.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setDataBuffer(ByteBuffer dataBuffer) {\n this.dataBuffer = dataBuffer;\n return this;\n }\n\n /**\n * Sets the error that occurred during the transfer.\n *\n * @param exception The error that occurred during the transfer, may be {@code null} if none.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setException(Exception exception) {\n this.exception = exception;\n return this;\n }\n\n /**\n * Builds a new transfer event from the current values of this builder. The state of the builder itself remains\n * unchanged.\n *\n * @return The transfer event, never {@code null}.\n */\n public TransferEvent build() {\n return new TransferEvent(this);\n }\n }\n}\n"} {"task_id": "Java_2253", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/maven-resolver/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferEvent.java", "mask_start_position": 8449, "mask_end_position": 8576, "canonical_solution": "{\n this.requestType = requireNonNull(requestType, \"request type cannot be null\");\n return this;\n }", "pre_mask_code": "package org.eclipse.aether.transfer;\n\nimport java.nio.ByteBuffer;\nimport static java.util.Objects.requireNonNull;\nimport org.eclipse.aether.RepositorySystemSession;\n\n/**\n * An event fired to a transfer listener during an artifact/metadata transfer.\n *\n * @see TransferListener\n * @see TransferEvent.Builder\n */\npublic final class TransferEvent {\n\n /**\n * The type of the event.\n */\n public enum EventType {\n\n /**\n * @see TransferListener#transferInitiated(TransferEvent)\n */\n INITIATED,\n /**\n * @see TransferListener#transferStarted(TransferEvent)\n */\n STARTED,\n /**\n * @see TransferListener#transferProgressed(TransferEvent)\n */\n PROGRESSED,\n /**\n * @see TransferListener#transferCorrupted(TransferEvent)\n */\n CORRUPTED,\n /**\n * @see TransferListener#transferSucceeded(TransferEvent)\n */\n SUCCEEDED,\n /**\n * @see TransferListener#transferFailed(TransferEvent)\n */\n FAILED\n }\n\n /**\n * The type of the request/transfer being performed.\n */\n public enum RequestType {\n\n GET,\n /**\n * Check artifact/metadata existence only.\n */\n GET_EXISTENCE,\n PUT\n }\n\n private final EventType type;\n\n private final RequestType requestType;\n\n private final RepositorySystemSession session;\n\n private final TransferResource resource;\n\n private final ByteBuffer dataBuffer;\n\n private final long transferredBytes;\n\n private final Exception exception;\n\n TransferEvent(Builder builder) {\n type = builder.type;\n requestType = builder.requestType;\n session = builder.session;\n resource = builder.resource;\n dataBuffer = builder.dataBuffer;\n transferredBytes = builder.transferredBytes;\n exception = builder.exception;\n }\n\n /**\n * Gets the type of the event.\n *\n * @return The type of the event, never {@code null}.\n */\n public EventType getType() {\n return type;\n }\n\n /**\n * Gets the type of the request/transfer.\n *\n * @return The type of the request/transfer, never {@code null}.\n */\n public RequestType getRequestType() {\n return requestType;\n }\n\n /**\n * Gets the repository system session during which the event occurred.\n *\n * @return The repository system session during which the event occurred, never {@code null}.\n */\n public RepositorySystemSession getSession() {\n return session;\n }\n\n /**\n * Gets the resource that is being transferred.\n *\n * @return The resource being transferred, never {@code null}.\n */\n public TransferResource getResource() {\n return resource;\n }\n\n /**\n * Gets the total number of bytes that have been transferred since the download/upload of the resource was started.\n * If a download has been resumed, the returned count includes the bytes that were already downloaded during the\n * previous attempt. In other words, the ratio of transferred bytes to the content length of the resource indicates\n * the percentage of transfer completion.\n *\n * @return The total number of bytes that have been transferred since the transfer started, never negative.\n * @see #getDataLength()\n * @see TransferResource#getResumeOffset()\n */\n public long getTransferredBytes() {\n return transferredBytes;\n }\n\n /**\n * Gets the byte buffer holding the transferred bytes since the last event. A listener must assume this buffer to be\n * owned by the event source and must not change any byte in this buffer. Also, the buffer is only valid for the\n * duration of the event callback, i.e. the next event might reuse the same buffer (with updated contents).\n * Therefore, if the actual event processing is deferred, the byte buffer would have to be cloned to create an\n * immutable snapshot of its contents.\n *\n * @return The (read-only) byte buffer or {@code null} if not applicable to the event, i.e. if the event type is not\n * {@link EventType#PROGRESSED}.\n */\n public ByteBuffer getDataBuffer() {\n return (dataBuffer != null) ? dataBuffer.asReadOnlyBuffer() : null;\n }\n\n /**\n * Gets the number of bytes that have been transferred since the last event.\n *\n * @return The number of bytes that have been transferred since the last event, possibly zero but never negative.\n * @see #getTransferredBytes()\n */\n public int getDataLength() {\n return (dataBuffer != null) ? dataBuffer.remaining() : 0;\n }\n\n /**\n * Gets the error that occurred during the transfer.\n *\n * @return The error that occurred or {@code null} if none.\n */\n public Exception getException() {\n return exception;\n }\n\n @Override\n public String toString() {\n return getRequestType() + \" \" + getType() + \" \" + getResource();\n }\n\n /**\n * A builder to create transfer events.\n */\n public static final class Builder {\n\n EventType type;\n\n RequestType requestType;\n\n final RepositorySystemSession session;\n\n final TransferResource resource;\n\n ByteBuffer dataBuffer;\n\n long transferredBytes;\n\n Exception exception;\n\n /**\n * Creates a new transfer event builder for the specified session and the given resource.\n *\n * @param session The repository system session, must not be {@code null}.\n * @param resource The resource being transferred, must not be {@code null}.\n */\n public Builder(RepositorySystemSession session, TransferResource resource) {\n this.session = requireNonNull(session, \"repository system session cannot be null\");\n this.resource = requireNonNull(resource, \"transfer resource cannot be null\");\n type = EventType.INITIATED;\n requestType = RequestType.GET;\n }\n\n private Builder(Builder prototype) {\n session = prototype.session;\n resource = prototype.resource;\n type = prototype.type;\n requestType = prototype.requestType;\n dataBuffer = prototype.dataBuffer;\n transferredBytes = prototype.transferredBytes;\n exception = prototype.exception;\n }\n\n /**\n * Creates a new transfer event builder from the current values of this builder. The state of this builder\n * remains unchanged.\n *\n * @return The new event builder, never {@code null}.\n */\n public Builder copy() {\n return new Builder(this);\n }\n\n /**\n * Sets the type of the event and resets event-specific fields. In more detail, the data buffer and the\n * exception fields are set to {@code null}. Furthermore, the total number of transferred bytes is set to\n * {@code 0} if the event type is {@link EventType#STARTED}.\n *\n * @param type The type of the event, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder resetType(EventType type) {\n this.type = requireNonNull(type, \"event type cannot be null\");\n dataBuffer = null;\n exception = null;\n switch(type) {\n case INITIATED:\n case STARTED:\n transferredBytes = 0L;\n default:\n }\n return this;\n }\n\n /**\n * Sets the type of the event. When re-using the same builder to generate a sequence of events for one transfer,\n * {@link #resetType(TransferEvent.EventType)} might be more handy.\n *\n * @param type The type of the event, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setType(EventType type) {\n this.type = requireNonNull(type, \"event type cannot be null\");\n return this;\n }\n\n /**\n * Sets the type of the request/transfer.\n *\n * @param requestType The request/transfer type, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setRequestType(RequestType requestType) ", "post_mask_code": "\n\n /**\n * Sets the total number of bytes that have been transferred so far during the download/upload of the resource.\n * If a download is being resumed, the count must include the bytes that were already downloaded in the previous\n * attempt and from which the current transfer started. In this case, the event type {@link EventType#STARTED}\n * should indicate from what byte the download resumes.\n *\n * @param transferredBytes The total number of bytes that have been transferred so far during the\n * download/upload of the resource, must not be negative.\n * @return This event builder for chaining, never {@code null}.\n * @see TransferResource#setResumeOffset(long)\n */\n public Builder setTransferredBytes(long transferredBytes) {\n if (transferredBytes < 0L) {\n throw new IllegalArgumentException(\"number of transferred bytes cannot be negative\");\n }\n this.transferredBytes = transferredBytes;\n return this;\n }\n\n /**\n * Increments the total number of bytes that have been transferred so far during the download/upload.\n *\n * @param transferredBytes The number of bytes that have been transferred since the last event, must not be\n * negative.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder addTransferredBytes(long transferredBytes) {\n if (transferredBytes < 0L) {\n throw new IllegalArgumentException(\"number of transferred bytes cannot be negative\");\n }\n this.transferredBytes += transferredBytes;\n return this;\n }\n\n /**\n * Sets the byte buffer holding the transferred bytes since the last event.\n *\n * @param buffer The byte buffer holding the transferred bytes since the last event, may be {@code null} if not\n * applicable to the event.\n * @param offset The starting point of valid bytes in the array.\n * @param length The number of valid bytes, must not be negative.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setDataBuffer(byte[] buffer, int offset, int length) {\n return setDataBuffer((buffer != null) ? ByteBuffer.wrap(buffer, offset, length) : null);\n }\n\n /**\n * Sets the byte buffer holding the transferred bytes since the last event.\n *\n * @param dataBuffer The byte buffer holding the transferred bytes since the last event, may be {@code null} if\n * not applicable to the event.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setDataBuffer(ByteBuffer dataBuffer) {\n this.dataBuffer = dataBuffer;\n return this;\n }\n\n /**\n * Sets the error that occurred during the transfer.\n *\n * @param exception The error that occurred during the transfer, may be {@code null} if none.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setException(Exception exception) {\n this.exception = exception;\n return this;\n }\n\n /**\n * Builds a new transfer event from the current values of this builder. The state of the builder itself remains\n * unchanged.\n *\n * @return The transfer event, never {@code null}.\n */\n public TransferEvent build() {\n return new TransferEvent(this);\n }\n }\n}\n"} {"task_id": "Java_2254", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/maven-resolver/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferEvent.java", "mask_start_position": 10329, "mask_end_position": 10331, "canonical_solution": "s;", "pre_mask_code": "package org.eclipse.aether.transfer;\n\nimport java.nio.ByteBuffer;\nimport static java.util.Objects.requireNonNull;\nimport org.eclipse.aether.RepositorySystemSession;\n\n/**\n * An event fired to a transfer listener during an artifact/metadata transfer.\n *\n * @see TransferListener\n * @see TransferEvent.Builder\n */\npublic final class TransferEvent {\n\n /**\n * The type of the event.\n */\n public enum EventType {\n\n /**\n * @see TransferListener#transferInitiated(TransferEvent)\n */\n INITIATED,\n /**\n * @see TransferListener#transferStarted(TransferEvent)\n */\n STARTED,\n /**\n * @see TransferListener#transferProgressed(TransferEvent)\n */\n PROGRESSED,\n /**\n * @see TransferListener#transferCorrupted(TransferEvent)\n */\n CORRUPTED,\n /**\n * @see TransferListener#transferSucceeded(TransferEvent)\n */\n SUCCEEDED,\n /**\n * @see TransferListener#transferFailed(TransferEvent)\n */\n FAILED\n }\n\n /**\n * The type of the request/transfer being performed.\n */\n public enum RequestType {\n\n GET,\n /**\n * Check artifact/metadata existence only.\n */\n GET_EXISTENCE,\n PUT\n }\n\n private final EventType type;\n\n private final RequestType requestType;\n\n private final RepositorySystemSession session;\n\n private final TransferResource resource;\n\n private final ByteBuffer dataBuffer;\n\n private final long transferredBytes;\n\n private final Exception exception;\n\n TransferEvent(Builder builder) {\n type = builder.type;\n requestType = builder.requestType;\n session = builder.session;\n resource = builder.resource;\n dataBuffer = builder.dataBuffer;\n transferredBytes = builder.transferredBytes;\n exception = builder.exception;\n }\n\n /**\n * Gets the type of the event.\n *\n * @return The type of the event, never {@code null}.\n */\n public EventType getType() {\n return type;\n }\n\n /**\n * Gets the type of the request/transfer.\n *\n * @return The type of the request/transfer, never {@code null}.\n */\n public RequestType getRequestType() {\n return requestType;\n }\n\n /**\n * Gets the repository system session during which the event occurred.\n *\n * @return The repository system session during which the event occurred, never {@code null}.\n */\n public RepositorySystemSession getSession() {\n return session;\n }\n\n /**\n * Gets the resource that is being transferred.\n *\n * @return The resource being transferred, never {@code null}.\n */\n public TransferResource getResource() {\n return resource;\n }\n\n /**\n * Gets the total number of bytes that have been transferred since the download/upload of the resource was started.\n * If a download has been resumed, the returned count includes the bytes that were already downloaded during the\n * previous attempt. In other words, the ratio of transferred bytes to the content length of the resource indicates\n * the percentage of transfer completion.\n *\n * @return The total number of bytes that have been transferred since the transfer started, never negative.\n * @see #getDataLength()\n * @see TransferResource#getResumeOffset()\n */\n public long getTransferredBytes() {\n return transferredBytes;\n }\n\n /**\n * Gets the byte buffer holding the transferred bytes since the last event. A listener must assume this buffer to be\n * owned by the event source and must not change any byte in this buffer. Also, the buffer is only valid for the\n * duration of the event callback, i.e. the next event might reuse the same buffer (with updated contents).\n * Therefore, if the actual event processing is deferred, the byte buffer would have to be cloned to create an\n * immutable snapshot of its contents.\n *\n * @return The (read-only) byte buffer or {@code null} if not applicable to the event, i.e. if the event type is not\n * {@link EventType#PROGRESSED}.\n */\n public ByteBuffer getDataBuffer() {\n return (dataBuffer != null) ? dataBuffer.asReadOnlyBuffer() : null;\n }\n\n /**\n * Gets the number of bytes that have been transferred since the last event.\n *\n * @return The number of bytes that have been transferred since the last event, possibly zero but never negative.\n * @see #getTransferredBytes()\n */\n public int getDataLength() {\n return (dataBuffer != null) ? dataBuffer.remaining() : 0;\n }\n\n /**\n * Gets the error that occurred during the transfer.\n *\n * @return The error that occurred or {@code null} if none.\n */\n public Exception getException() {\n return exception;\n }\n\n @Override\n public String toString() {\n return getRequestType() + \" \" + getType() + \" \" + getResource();\n }\n\n /**\n * A builder to create transfer events.\n */\n public static final class Builder {\n\n EventType type;\n\n RequestType requestType;\n\n final RepositorySystemSession session;\n\n final TransferResource resource;\n\n ByteBuffer dataBuffer;\n\n long transferredBytes;\n\n Exception exception;\n\n /**\n * Creates a new transfer event builder for the specified session and the given resource.\n *\n * @param session The repository system session, must not be {@code null}.\n * @param resource The resource being transferred, must not be {@code null}.\n */\n public Builder(RepositorySystemSession session, TransferResource resource) {\n this.session = requireNonNull(session, \"repository system session cannot be null\");\n this.resource = requireNonNull(resource, \"transfer resource cannot be null\");\n type = EventType.INITIATED;\n requestType = RequestType.GET;\n }\n\n private Builder(Builder prototype) {\n session = prototype.session;\n resource = prototype.resource;\n type = prototype.type;\n requestType = prototype.requestType;\n dataBuffer = prototype.dataBuffer;\n transferredBytes = prototype.transferredBytes;\n exception = prototype.exception;\n }\n\n /**\n * Creates a new transfer event builder from the current values of this builder. The state of this builder\n * remains unchanged.\n *\n * @return The new event builder, never {@code null}.\n */\n public Builder copy() {\n return new Builder(this);\n }\n\n /**\n * Sets the type of the event and resets event-specific fields. In more detail, the data buffer and the\n * exception fields are set to {@code null}. Furthermore, the total number of transferred bytes is set to\n * {@code 0} if the event type is {@link EventType#STARTED}.\n *\n * @param type The type of the event, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder resetType(EventType type) {\n this.type = requireNonNull(type, \"event type cannot be null\");\n dataBuffer = null;\n exception = null;\n switch(type) {\n case INITIATED:\n case STARTED:\n transferredBytes = 0L;\n default:\n }\n return this;\n }\n\n /**\n * Sets the type of the event. When re-using the same builder to generate a sequence of events for one transfer,\n * {@link #resetType(TransferEvent.EventType)} might be more handy.\n *\n * @param type The type of the event, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setType(EventType type) {\n this.type = requireNonNull(type, \"event type cannot be null\");\n return this;\n }\n\n /**\n * Sets the type of the request/transfer.\n *\n * @param requestType The request/transfer type, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setRequestType(RequestType requestType) {\n this.requestType = requireNonNull(requestType, \"request type cannot be null\");\n return this;\n }\n\n /**\n * Sets the total number of bytes that have been transferred so far during the download/upload of the resource.\n * If a download is being resumed, the count must include the bytes that were already downloaded in the previous\n * attempt and from which the current transfer started. In this case, the event type {@link EventType#STARTED}\n * should indicate from what byte the download resumes.\n *\n * @param transferredBytes The total number of bytes that have been transferred so far during the\n * download/upload of the resource, must not be negative.\n * @return This event builder for chaining, never {@code null}.\n * @see TransferResource#setResumeOffset(long)\n */\n public Builder setTransferredBytes(long transferredBytes) {\n if (transferredBytes < 0L) {\n throw new IllegalArgumentException(\"number of transferred bytes cannot be negative\");\n }\n this.transferredBytes = transferredBytes;\n return this;\n }\n\n /**\n * Increments the total number of bytes that have been transferred so far during the download/upload.\n *\n * @param transferredBytes The number of bytes that have been transferred since the last event, must not be\n * negative.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder addTransferredBytes(long transferredBytes) {\n if (transferredBytes < 0L) {\n throw new IllegalArgumentException(\"number of transferred bytes cannot be negative\");\n }\n this.transferredBytes += transferredBytes;\n return thi", "post_mask_code": "\n }\n\n /**\n * Sets the byte buffer holding the transferred bytes since the last event.\n *\n * @param buffer The byte buffer holding the transferred bytes since the last event, may be {@code null} if not\n * applicable to the event.\n * @param offset The starting point of valid bytes in the array.\n * @param length The number of valid bytes, must not be negative.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setDataBuffer(byte[] buffer, int offset, int length) {\n return setDataBuffer((buffer != null) ? ByteBuffer.wrap(buffer, offset, length) : null);\n }\n\n /**\n * Sets the byte buffer holding the transferred bytes since the last event.\n *\n * @param dataBuffer The byte buffer holding the transferred bytes since the last event, may be {@code null} if\n * not applicable to the event.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setDataBuffer(ByteBuffer dataBuffer) {\n this.dataBuffer = dataBuffer;\n return this;\n }\n\n /**\n * Sets the error that occurred during the transfer.\n *\n * @param exception The error that occurred during the transfer, may be {@code null} if none.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setException(Exception exception) {\n this.exception = exception;\n return this;\n }\n\n /**\n * Builds a new transfer event from the current values of this builder. The state of the builder itself remains\n * unchanged.\n *\n * @return The transfer event, never {@code null}.\n */\n public TransferEvent build() {\n return new TransferEvent(this);\n }\n }\n}\n"} {"task_id": "Java_2255", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/apache/maven-resolver/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferEvent.java", "mask_start_position": 8394, "mask_end_position": 8576, "canonical_solution": "public Builder setRequestType(RequestType requestType) {\n this.requestType = requireNonNull(requestType, \"request type cannot be null\");\n return this;\n }", "pre_mask_code": "package org.eclipse.aether.transfer;\n\nimport java.nio.ByteBuffer;\nimport static java.util.Objects.requireNonNull;\nimport org.eclipse.aether.RepositorySystemSession;\n\n/**\n * An event fired to a transfer listener during an artifact/metadata transfer.\n *\n * @see TransferListener\n * @see TransferEvent.Builder\n */\npublic final class TransferEvent {\n\n /**\n * The type of the event.\n */\n public enum EventType {\n\n /**\n * @see TransferListener#transferInitiated(TransferEvent)\n */\n INITIATED,\n /**\n * @see TransferListener#transferStarted(TransferEvent)\n */\n STARTED,\n /**\n * @see TransferListener#transferProgressed(TransferEvent)\n */\n PROGRESSED,\n /**\n * @see TransferListener#transferCorrupted(TransferEvent)\n */\n CORRUPTED,\n /**\n * @see TransferListener#transferSucceeded(TransferEvent)\n */\n SUCCEEDED,\n /**\n * @see TransferListener#transferFailed(TransferEvent)\n */\n FAILED\n }\n\n /**\n * The type of the request/transfer being performed.\n */\n public enum RequestType {\n\n GET,\n /**\n * Check artifact/metadata existence only.\n */\n GET_EXISTENCE,\n PUT\n }\n\n private final EventType type;\n\n private final RequestType requestType;\n\n private final RepositorySystemSession session;\n\n private final TransferResource resource;\n\n private final ByteBuffer dataBuffer;\n\n private final long transferredBytes;\n\n private final Exception exception;\n\n TransferEvent(Builder builder) {\n type = builder.type;\n requestType = builder.requestType;\n session = builder.session;\n resource = builder.resource;\n dataBuffer = builder.dataBuffer;\n transferredBytes = builder.transferredBytes;\n exception = builder.exception;\n }\n\n /**\n * Gets the type of the event.\n *\n * @return The type of the event, never {@code null}.\n */\n public EventType getType() {\n return type;\n }\n\n /**\n * Gets the type of the request/transfer.\n *\n * @return The type of the request/transfer, never {@code null}.\n */\n public RequestType getRequestType() {\n return requestType;\n }\n\n /**\n * Gets the repository system session during which the event occurred.\n *\n * @return The repository system session during which the event occurred, never {@code null}.\n */\n public RepositorySystemSession getSession() {\n return session;\n }\n\n /**\n * Gets the resource that is being transferred.\n *\n * @return The resource being transferred, never {@code null}.\n */\n public TransferResource getResource() {\n return resource;\n }\n\n /**\n * Gets the total number of bytes that have been transferred since the download/upload of the resource was started.\n * If a download has been resumed, the returned count includes the bytes that were already downloaded during the\n * previous attempt. In other words, the ratio of transferred bytes to the content length of the resource indicates\n * the percentage of transfer completion.\n *\n * @return The total number of bytes that have been transferred since the transfer started, never negative.\n * @see #getDataLength()\n * @see TransferResource#getResumeOffset()\n */\n public long getTransferredBytes() {\n return transferredBytes;\n }\n\n /**\n * Gets the byte buffer holding the transferred bytes since the last event. A listener must assume this buffer to be\n * owned by the event source and must not change any byte in this buffer. Also, the buffer is only valid for the\n * duration of the event callback, i.e. the next event might reuse the same buffer (with updated contents).\n * Therefore, if the actual event processing is deferred, the byte buffer would have to be cloned to create an\n * immutable snapshot of its contents.\n *\n * @return The (read-only) byte buffer or {@code null} if not applicable to the event, i.e. if the event type is not\n * {@link EventType#PROGRESSED}.\n */\n public ByteBuffer getDataBuffer() {\n return (dataBuffer != null) ? dataBuffer.asReadOnlyBuffer() : null;\n }\n\n /**\n * Gets the number of bytes that have been transferred since the last event.\n *\n * @return The number of bytes that have been transferred since the last event, possibly zero but never negative.\n * @see #getTransferredBytes()\n */\n public int getDataLength() {\n return (dataBuffer != null) ? dataBuffer.remaining() : 0;\n }\n\n /**\n * Gets the error that occurred during the transfer.\n *\n * @return The error that occurred or {@code null} if none.\n */\n public Exception getException() {\n return exception;\n }\n\n @Override\n public String toString() {\n return getRequestType() + \" \" + getType() + \" \" + getResource();\n }\n\n /**\n * A builder to create transfer events.\n */\n public static final class Builder {\n\n EventType type;\n\n RequestType requestType;\n\n final RepositorySystemSession session;\n\n final TransferResource resource;\n\n ByteBuffer dataBuffer;\n\n long transferredBytes;\n\n Exception exception;\n\n /**\n * Creates a new transfer event builder for the specified session and the given resource.\n *\n * @param session The repository system session, must not be {@code null}.\n * @param resource The resource being transferred, must not be {@code null}.\n */\n public Builder(RepositorySystemSession session, TransferResource resource) {\n this.session = requireNonNull(session, \"repository system session cannot be null\");\n this.resource = requireNonNull(resource, \"transfer resource cannot be null\");\n type = EventType.INITIATED;\n requestType = RequestType.GET;\n }\n\n private Builder(Builder prototype) {\n session = prototype.session;\n resource = prototype.resource;\n type = prototype.type;\n requestType = prototype.requestType;\n dataBuffer = prototype.dataBuffer;\n transferredBytes = prototype.transferredBytes;\n exception = prototype.exception;\n }\n\n /**\n * Creates a new transfer event builder from the current values of this builder. The state of this builder\n * remains unchanged.\n *\n * @return The new event builder, never {@code null}.\n */\n public Builder copy() {\n return new Builder(this);\n }\n\n /**\n * Sets the type of the event and resets event-specific fields. In more detail, the data buffer and the\n * exception fields are set to {@code null}. Furthermore, the total number of transferred bytes is set to\n * {@code 0} if the event type is {@link EventType#STARTED}.\n *\n * @param type The type of the event, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder resetType(EventType type) {\n this.type = requireNonNull(type, \"event type cannot be null\");\n dataBuffer = null;\n exception = null;\n switch(type) {\n case INITIATED:\n case STARTED:\n transferredBytes = 0L;\n default:\n }\n return this;\n }\n\n /**\n * Sets the type of the event. When re-using the same builder to generate a sequence of events for one transfer,\n * {@link #resetType(TransferEvent.EventType)} might be more handy.\n *\n * @param type The type of the event, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setType(EventType type) {\n this.type = requireNonNull(type, \"event type cannot be null\");\n return this;\n }\n\n /**\n * Sets the type of the request/transfer.\n *\n * @param requestType The request/transfer type, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n ", "post_mask_code": "\n\n /**\n * Sets the total number of bytes that have been transferred so far during the download/upload of the resource.\n * If a download is being resumed, the count must include the bytes that were already downloaded in the previous\n * attempt and from which the current transfer started. In this case, the event type {@link EventType#STARTED}\n * should indicate from what byte the download resumes.\n *\n * @param transferredBytes The total number of bytes that have been transferred so far during the\n * download/upload of the resource, must not be negative.\n * @return This event builder for chaining, never {@code null}.\n * @see TransferResource#setResumeOffset(long)\n */\n public Builder setTransferredBytes(long transferredBytes) {\n if (transferredBytes < 0L) {\n throw new IllegalArgumentException(\"number of transferred bytes cannot be negative\");\n }\n this.transferredBytes = transferredBytes;\n return this;\n }\n\n /**\n * Increments the total number of bytes that have been transferred so far during the download/upload.\n *\n * @param transferredBytes The number of bytes that have been transferred since the last event, must not be\n * negative.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder addTransferredBytes(long transferredBytes) {\n if (transferredBytes < 0L) {\n throw new IllegalArgumentException(\"number of transferred bytes cannot be negative\");\n }\n this.transferredBytes += transferredBytes;\n return this;\n }\n\n /**\n * Sets the byte buffer holding the transferred bytes since the last event.\n *\n * @param buffer The byte buffer holding the transferred bytes since the last event, may be {@code null} if not\n * applicable to the event.\n * @param offset The starting point of valid bytes in the array.\n * @param length The number of valid bytes, must not be negative.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setDataBuffer(byte[] buffer, int offset, int length) {\n return setDataBuffer((buffer != null) ? ByteBuffer.wrap(buffer, offset, length) : null);\n }\n\n /**\n * Sets the byte buffer holding the transferred bytes since the last event.\n *\n * @param dataBuffer The byte buffer holding the transferred bytes since the last event, may be {@code null} if\n * not applicable to the event.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setDataBuffer(ByteBuffer dataBuffer) {\n this.dataBuffer = dataBuffer;\n return this;\n }\n\n /**\n * Sets the error that occurred during the transfer.\n *\n * @param exception The error that occurred during the transfer, may be {@code null} if none.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setException(Exception exception) {\n this.exception = exception;\n return this;\n }\n\n /**\n * Builds a new transfer event from the current values of this builder. The state of the builder itself remains\n * unchanged.\n *\n * @return The transfer event, never {@code null}.\n */\n public TransferEvent build() {\n return new TransferEvent(this);\n }\n }\n}\n"} {"task_id": "Java_2256", "language": "Java", "task_type": "switch_case", "source_file": "java/github/apache/maven-resolver/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferEvent.java", "mask_start_position": 7415, "mask_end_position": 7573, "canonical_solution": "switch(type) {\n case INITIATED:\n case STARTED:\n transferredBytes = 0L;\n default:\n }", "pre_mask_code": "package org.eclipse.aether.transfer;\n\nimport java.nio.ByteBuffer;\nimport static java.util.Objects.requireNonNull;\nimport org.eclipse.aether.RepositorySystemSession;\n\n/**\n * An event fired to a transfer listener during an artifact/metadata transfer.\n *\n * @see TransferListener\n * @see TransferEvent.Builder\n */\npublic final class TransferEvent {\n\n /**\n * The type of the event.\n */\n public enum EventType {\n\n /**\n * @see TransferListener#transferInitiated(TransferEvent)\n */\n INITIATED,\n /**\n * @see TransferListener#transferStarted(TransferEvent)\n */\n STARTED,\n /**\n * @see TransferListener#transferProgressed(TransferEvent)\n */\n PROGRESSED,\n /**\n * @see TransferListener#transferCorrupted(TransferEvent)\n */\n CORRUPTED,\n /**\n * @see TransferListener#transferSucceeded(TransferEvent)\n */\n SUCCEEDED,\n /**\n * @see TransferListener#transferFailed(TransferEvent)\n */\n FAILED\n }\n\n /**\n * The type of the request/transfer being performed.\n */\n public enum RequestType {\n\n GET,\n /**\n * Check artifact/metadata existence only.\n */\n GET_EXISTENCE,\n PUT\n }\n\n private final EventType type;\n\n private final RequestType requestType;\n\n private final RepositorySystemSession session;\n\n private final TransferResource resource;\n\n private final ByteBuffer dataBuffer;\n\n private final long transferredBytes;\n\n private final Exception exception;\n\n TransferEvent(Builder builder) {\n type = builder.type;\n requestType = builder.requestType;\n session = builder.session;\n resource = builder.resource;\n dataBuffer = builder.dataBuffer;\n transferredBytes = builder.transferredBytes;\n exception = builder.exception;\n }\n\n /**\n * Gets the type of the event.\n *\n * @return The type of the event, never {@code null}.\n */\n public EventType getType() {\n return type;\n }\n\n /**\n * Gets the type of the request/transfer.\n *\n * @return The type of the request/transfer, never {@code null}.\n */\n public RequestType getRequestType() {\n return requestType;\n }\n\n /**\n * Gets the repository system session during which the event occurred.\n *\n * @return The repository system session during which the event occurred, never {@code null}.\n */\n public RepositorySystemSession getSession() {\n return session;\n }\n\n /**\n * Gets the resource that is being transferred.\n *\n * @return The resource being transferred, never {@code null}.\n */\n public TransferResource getResource() {\n return resource;\n }\n\n /**\n * Gets the total number of bytes that have been transferred since the download/upload of the resource was started.\n * If a download has been resumed, the returned count includes the bytes that were already downloaded during the\n * previous attempt. In other words, the ratio of transferred bytes to the content length of the resource indicates\n * the percentage of transfer completion.\n *\n * @return The total number of bytes that have been transferred since the transfer started, never negative.\n * @see #getDataLength()\n * @see TransferResource#getResumeOffset()\n */\n public long getTransferredBytes() {\n return transferredBytes;\n }\n\n /**\n * Gets the byte buffer holding the transferred bytes since the last event. A listener must assume this buffer to be\n * owned by the event source and must not change any byte in this buffer. Also, the buffer is only valid for the\n * duration of the event callback, i.e. the next event might reuse the same buffer (with updated contents).\n * Therefore, if the actual event processing is deferred, the byte buffer would have to be cloned to create an\n * immutable snapshot of its contents.\n *\n * @return The (read-only) byte buffer or {@code null} if not applicable to the event, i.e. if the event type is not\n * {@link EventType#PROGRESSED}.\n */\n public ByteBuffer getDataBuffer() {\n return (dataBuffer != null) ? dataBuffer.asReadOnlyBuffer() : null;\n }\n\n /**\n * Gets the number of bytes that have been transferred since the last event.\n *\n * @return The number of bytes that have been transferred since the last event, possibly zero but never negative.\n * @see #getTransferredBytes()\n */\n public int getDataLength() {\n return (dataBuffer != null) ? dataBuffer.remaining() : 0;\n }\n\n /**\n * Gets the error that occurred during the transfer.\n *\n * @return The error that occurred or {@code null} if none.\n */\n public Exception getException() {\n return exception;\n }\n\n @Override\n public String toString() {\n return getRequestType() + \" \" + getType() + \" \" + getResource();\n }\n\n /**\n * A builder to create transfer events.\n */\n public static final class Builder {\n\n EventType type;\n\n RequestType requestType;\n\n final RepositorySystemSession session;\n\n final TransferResource resource;\n\n ByteBuffer dataBuffer;\n\n long transferredBytes;\n\n Exception exception;\n\n /**\n * Creates a new transfer event builder for the specified session and the given resource.\n *\n * @param session The repository system session, must not be {@code null}.\n * @param resource The resource being transferred, must not be {@code null}.\n */\n public Builder(RepositorySystemSession session, TransferResource resource) {\n this.session = requireNonNull(session, \"repository system session cannot be null\");\n this.resource = requireNonNull(resource, \"transfer resource cannot be null\");\n type = EventType.INITIATED;\n requestType = RequestType.GET;\n }\n\n private Builder(Builder prototype) {\n session = prototype.session;\n resource = prototype.resource;\n type = prototype.type;\n requestType = prototype.requestType;\n dataBuffer = prototype.dataBuffer;\n transferredBytes = prototype.transferredBytes;\n exception = prototype.exception;\n }\n\n /**\n * Creates a new transfer event builder from the current values of this builder. The state of this builder\n * remains unchanged.\n *\n * @return The new event builder, never {@code null}.\n */\n public Builder copy() {\n return new Builder(this);\n }\n\n /**\n * Sets the type of the event and resets event-specific fields. In more detail, the data buffer and the\n * exception fields are set to {@code null}. Furthermore, the total number of transferred bytes is set to\n * {@code 0} if the event type is {@link EventType#STARTED}.\n *\n * @param type The type of the event, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder resetType(EventType type) {\n this.type = requireNonNull(type, \"event type cannot be null\");\n dataBuffer = null;\n exception = null;\n ", "post_mask_code": "\n return this;\n }\n\n /**\n * Sets the type of the event. When re-using the same builder to generate a sequence of events for one transfer,\n * {@link #resetType(TransferEvent.EventType)} might be more handy.\n *\n * @param type The type of the event, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setType(EventType type) {\n this.type = requireNonNull(type, \"event type cannot be null\");\n return this;\n }\n\n /**\n * Sets the type of the request/transfer.\n *\n * @param requestType The request/transfer type, must not be {@code null}.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setRequestType(RequestType requestType) {\n this.requestType = requireNonNull(requestType, \"request type cannot be null\");\n return this;\n }\n\n /**\n * Sets the total number of bytes that have been transferred so far during the download/upload of the resource.\n * If a download is being resumed, the count must include the bytes that were already downloaded in the previous\n * attempt and from which the current transfer started. In this case, the event type {@link EventType#STARTED}\n * should indicate from what byte the download resumes.\n *\n * @param transferredBytes The total number of bytes that have been transferred so far during the\n * download/upload of the resource, must not be negative.\n * @return This event builder for chaining, never {@code null}.\n * @see TransferResource#setResumeOffset(long)\n */\n public Builder setTransferredBytes(long transferredBytes) {\n if (transferredBytes < 0L) {\n throw new IllegalArgumentException(\"number of transferred bytes cannot be negative\");\n }\n this.transferredBytes = transferredBytes;\n return this;\n }\n\n /**\n * Increments the total number of bytes that have been transferred so far during the download/upload.\n *\n * @param transferredBytes The number of bytes that have been transferred since the last event, must not be\n * negative.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder addTransferredBytes(long transferredBytes) {\n if (transferredBytes < 0L) {\n throw new IllegalArgumentException(\"number of transferred bytes cannot be negative\");\n }\n this.transferredBytes += transferredBytes;\n return this;\n }\n\n /**\n * Sets the byte buffer holding the transferred bytes since the last event.\n *\n * @param buffer The byte buffer holding the transferred bytes since the last event, may be {@code null} if not\n * applicable to the event.\n * @param offset The starting point of valid bytes in the array.\n * @param length The number of valid bytes, must not be negative.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setDataBuffer(byte[] buffer, int offset, int length) {\n return setDataBuffer((buffer != null) ? ByteBuffer.wrap(buffer, offset, length) : null);\n }\n\n /**\n * Sets the byte buffer holding the transferred bytes since the last event.\n *\n * @param dataBuffer The byte buffer holding the transferred bytes since the last event, may be {@code null} if\n * not applicable to the event.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setDataBuffer(ByteBuffer dataBuffer) {\n this.dataBuffer = dataBuffer;\n return this;\n }\n\n /**\n * Sets the error that occurred during the transfer.\n *\n * @param exception The error that occurred during the transfer, may be {@code null} if none.\n * @return This event builder for chaining, never {@code null}.\n */\n public Builder setException(Exception exception) {\n this.exception = exception;\n return this;\n }\n\n /**\n * Builds a new transfer event from the current values of this builder. The state of the builder itself remains\n * unchanged.\n *\n * @return The transfer event, never {@code null}.\n */\n public TransferEvent build() {\n return new TransferEvent(this);\n }\n }\n}\n"} {"task_id": "Java_2257", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/aosp-mirror/platform_packages_apps_settings/src/com/android/settings/homepage/contextualcards/ContextualCardFeatureProvider.java", "mask_start_position": 303, "mask_end_position": 331, "canonical_solution": "Cursor getContextualCards();", "pre_mask_code": "package com.android.settings.homepage.contextualcards;\n\nimport android.content.Context;\nimport android.database.Cursor;\n\n/**\n * Feature provider for the contextual card feature.\n */\npublic interface ContextualCardFeatureProvider {\n\n /**\n * Get contextual cards from the card provider\n */\n ", "post_mask_code": "\n\n /**\n * Mark a specific {@link ContextualCard} as dismissed with dismissal signal in the database\n * to indicate that the card has been dismissed.\n *\n * @param context Context\n * @param cardName The card name of the ContextualCard which is dismissed by user.\n * @return The number of rows updated\n */\n int markCardAsDismissed(Context context, String cardName);\n}\n"} {"task_id": "Java_2258", "language": "Java", "task_type": "method_signature", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.tests.spec10.callback_fat.common/test-applications/callback/src/com/ibm/ws/jpa/fvt/callback/listeners/defaultlistener/DefaultCallbackListenerPrivate.java", "mask_start_position": 1183, "mask_end_position": 1254, "canonical_solution": "@SuppressWarnings(\"unused\")\n private void postUpdate(Object entity) ", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.jpa.fvt.callback.listeners.defaultlistener;\n\nimport com.ibm.ws.jpa.fvt.callback.AbstractCallbackListener;\n\npublic class DefaultCallbackListenerPrivate extends AbstractCallbackListener {\n\n private final static DefaultCallbackListenerPrivate _singleton = new DefaultCallbackListenerPrivate();\n\n public final static AbstractCallbackListener getSingleton() {\n return _singleton;\n }\n\n public final static void reset() {\n _singleton.resetCallbackData();\n }\n\n @SuppressWarnings(\"unused\")\n private void prePersist(Object entity) {\n _singleton.doPrePersist(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void postPersist(Object entity) {\n _singleton.doPostPersist(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void preUpdate(Object entity) {\n _singleton.doPreUpdate(ProtectionType.PT_PRIVATE);\n }\n\n ", "post_mask_code": "{\n _singleton.doPostUpdate(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void preRemove(Object entity) {\n _singleton.doPreRemove(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void postRemove(Object entity) {\n _singleton.doPostRemove(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void postLoad(Object entity) {\n _singleton.doPostLoad(ProtectionType.PT_PRIVATE);\n }\n}\n"} {"task_id": "Java_2259", "language": "Java", "task_type": "method_body", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.tests.spec10.callback_fat.common/test-applications/callback/src/com/ibm/ws/jpa/fvt/callback/listeners/defaultlistener/DefaultCallbackListenerPrivate.java", "mask_start_position": 698, "mask_end_position": 745, "canonical_solution": "{\n _singleton.resetCallbackData();\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.jpa.fvt.callback.listeners.defaultlistener;\n\nimport com.ibm.ws.jpa.fvt.callback.AbstractCallbackListener;\n\npublic class DefaultCallbackListenerPrivate extends AbstractCallbackListener {\n\n private final static DefaultCallbackListenerPrivate _singleton = new DefaultCallbackListenerPrivate();\n\n public final static AbstractCallbackListener getSingleton() {\n return _singleton;\n }\n\n public final static void reset() ", "post_mask_code": "\n\n @SuppressWarnings(\"unused\")\n private void prePersist(Object entity) {\n _singleton.doPrePersist(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void postPersist(Object entity) {\n _singleton.doPostPersist(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void preUpdate(Object entity) {\n _singleton.doPreUpdate(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void postUpdate(Object entity) {\n _singleton.doPostUpdate(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void preRemove(Object entity) {\n _singleton.doPreRemove(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void postRemove(Object entity) {\n _singleton.doPostRemove(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void postLoad(Object entity) {\n _singleton.doPostLoad(ProtectionType.PT_PRIVATE);\n }\n}\n"} {"task_id": "Java_2260", "language": "Java", "task_type": "single_line", "source_file": "java/github/OpenLiberty/open-liberty/dev/com.ibm.ws.jpa.tests.spec10.callback_fat.common/test-applications/callback/src/com/ibm/ws/jpa/fvt/callback/listeners/defaultlistener/DefaultCallbackListenerPrivate.java", "mask_start_position": 1409, "mask_end_position": 1457, "canonical_solution": "ingleton.doPreRemove(ProtectionType.PT_PRIVATE);", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage com.ibm.ws.jpa.fvt.callback.listeners.defaultlistener;\n\nimport com.ibm.ws.jpa.fvt.callback.AbstractCallbackListener;\n\npublic class DefaultCallbackListenerPrivate extends AbstractCallbackListener {\n\n private final static DefaultCallbackListenerPrivate _singleton = new DefaultCallbackListenerPrivate();\n\n public final static AbstractCallbackListener getSingleton() {\n return _singleton;\n }\n\n public final static void reset() {\n _singleton.resetCallbackData();\n }\n\n @SuppressWarnings(\"unused\")\n private void prePersist(Object entity) {\n _singleton.doPrePersist(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void postPersist(Object entity) {\n _singleton.doPostPersist(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void preUpdate(Object entity) {\n _singleton.doPreUpdate(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void postUpdate(Object entity) {\n _singleton.doPostUpdate(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void preRemove(Object entity) {\n _s", "post_mask_code": "\n }\n\n @SuppressWarnings(\"unused\")\n private void postRemove(Object entity) {\n _singleton.doPostRemove(ProtectionType.PT_PRIVATE);\n }\n\n @SuppressWarnings(\"unused\")\n private void postLoad(Object entity) {\n _singleton.doPostLoad(ProtectionType.PT_PRIVATE);\n }\n}\n"} {"task_id": "Java_2261", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/pravega/pravega/common/src/main/java/io/pravega/common/util/SortedIndex.java", "mask_start_position": 1751, "mask_end_position": 1774, "canonical_solution": "V getCeiling(long key);", "pre_mask_code": "package io.pravega.common.util;\n\nimport java.util.function.Consumer;\n\n/**\n * Defines an Index that orders its IndexEntries by an Int64 (long) Key.\n *

\n * Notes:\n *

    \n *
  • Implementations of this interface are not necessarily thread-safe and no assumptions should be made about\n * multi-thread consistency.\n *
  • No implementation of this class should be able to index null values. As such, for all the retrieval methods,\n * a null value can be safely interpreted as no result found.\n *
\n *\n * @param The type of the IndexEntries.\n */\npublic interface SortedIndex {\n\n /**\n * Clears the contents of the Index.\n */\n void clear();\n\n /**\n * Inserts the given item into the Index. If there already exists an item with the same key, it will be overridden.\n *\n * @param item The item to insert.\n * @return The displaced item, if any.\n */\n V put(V item);\n\n /**\n * Removes any item with the given key from the Index.\n *\n * @param key The key of the item to remove.\n * @return The removed item, or null if nothing was removed.\n */\n V remove(long key);\n\n /**\n * Gets a value indicating the number of items in the Index.\n *\n * @return Integer indicating the size or number of items in the Index.\n */\n int size();\n\n /**\n * Gets an item with the given key.\n *\n * @param key The key to search by.\n * @return The requested item, if it exists, or null if it doesn't.\n */\n V get(long key);\n\n /**\n * Gets the smallest item whose key is greater than or equal to the given key.\n *\n * @param key the Key to search by.\n * @return The sought item, or null if it doesn't exist.\n */\n ", "post_mask_code": "\n\n /**\n * Gets the largest item whose key is smaller than or equal to the given key.\n *\n * @param key the Key to search by.\n * @return The sought item, or null if it doesn't exist.\n */\n V getFloor(long key);\n\n /**\n * Gets the smallest item in the index.\n *\n * @return The sought item, or null (if no items in the index).\n */\n V getFirst();\n\n /**\n * Gets the largest item in the index.\n *\n * @return The sought item, or null (if no items in the index).\n */\n V getLast();\n\n /**\n * Iterates through each item in the Index, in natural order, and calls the given consumer on all of them.\n *\n * @param consumer The consumer to invoke.\n * @throws java.util.ConcurrentModificationException If the Index is modified while this method is executing.\n */\n void forEach(Consumer consumer);\n\n /**\n * Defines a generic entry into an Index.\n */\n interface IndexEntry {\n\n /**\n * Gets a value representing the key of the entry. The Key should not change for the lifetime of the entry and\n * should be very cheap to return (as it is used very frequently).\n *\n * @return The entry key.\n */\n long key();\n }\n}\n"} {"task_id": "Java_2262", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse-archived/packagedrone/bundles/org.eclipse.packagedrone.web.common/src/org/eclipse/packagedrone/web/common/InterfaceExtender.java", "mask_start_position": 596, "mask_end_position": 691, "canonical_solution": "public default List getViews(final HttpServletRequest request, final Object object) ", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBH SYSTEMS GmbH - initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.packagedrone.web.common;\n\nimport java.util.List;\nimport javax.servlet.http.HttpServletRequest;\nimport org.eclipse.packagedrone.web.common.menu.MenuEntry;\n\npublic interface InterfaceExtender {\n\n public default List getActions(final HttpServletRequest request, final Object object) {\n return null;\n }\n\n ", "post_mask_code": "{\n return null;\n }\n\n public default List getMainMenuEntries(final HttpServletRequest request) {\n return null;\n }\n}\n"} {"task_id": "Java_2263", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse-archived/packagedrone/bundles/org.eclipse.packagedrone.web.common/src/org/eclipse/packagedrone/web/common/InterfaceExtender.java", "mask_start_position": 809, "mask_end_position": 837, "canonical_solution": "{\n return null;\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBH SYSTEMS GmbH - initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.packagedrone.web.common;\n\nimport java.util.List;\nimport javax.servlet.http.HttpServletRequest;\nimport org.eclipse.packagedrone.web.common.menu.MenuEntry;\n\npublic interface InterfaceExtender {\n\n public default List getActions(final HttpServletRequest request, final Object object) {\n return null;\n }\n\n public default List getViews(final HttpServletRequest request, final Object object) {\n return null;\n }\n\n public default List getMainMenuEntries(final HttpServletRequest request) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2264", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse-archived/packagedrone/bundles/org.eclipse.packagedrone.web.common/src/org/eclipse/packagedrone/web/common/InterfaceExtender.java", "mask_start_position": 575, "mask_end_position": 584, "canonical_solution": "urn null;", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBH SYSTEMS GmbH - initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.packagedrone.web.common;\n\nimport java.util.List;\nimport javax.servlet.http.HttpServletRequest;\nimport org.eclipse.packagedrone.web.common.menu.MenuEntry;\n\npublic interface InterfaceExtender {\n\n public default List getActions(final HttpServletRequest request, final Object object) {\n ret", "post_mask_code": "\n }\n\n public default List getViews(final HttpServletRequest request, final Object object) {\n return null;\n }\n\n public default List getMainMenuEntries(final HttpServletRequest request) {\n return null;\n }\n}\n"} {"task_id": "Java_2265", "language": "Java", "task_type": "method_signature", "source_file": "java/github/rackshift/rackshift/rackshift-server/src/main/java/io/rackshift/job/SyncOutBandJob.java", "mask_start_position": 1118, "mask_end_position": 1206, "canonical_solution": "@Scheduled(fixedDelay = 300 * 1000)\n public void updatePowerOutBandStatusScheduler() ", "pre_mask_code": "package io.rackshift.job;\n\nimport io.rackshift.constants.RackHDConstants;\nimport io.rackshift.mybatis.domain.BareMetal;\nimport io.rackshift.mybatis.domain.BareMetalExample;\nimport io.rackshift.mybatis.domain.OutBand;\nimport io.rackshift.mybatis.domain.OutBandExample;\nimport io.rackshift.mybatis.mapper.BareMetalMapper;\nimport io.rackshift.mybatis.mapper.OutBandMapper;\nimport io.rackshift.service.RackHDService;\nimport io.rackshift.utils.IPMIUtil;\nimport io.rackshift.utils.LogUtil;\nimport org.apache.commons.collections.CollectionUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.springframework.scheduling.annotation.Scheduled;\nimport org.springframework.stereotype.Service;\nimport javax.annotation.Resource;\nimport java.time.Duration;\nimport java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.List;\n\n/**\n * ipmi定时扫描任务 更新物理机开关机状态 已经新添加物理机到ipmi被动发现\n */\n@Service\npublic class SyncOutBandJob {\n\n @Resource\n private OutBandMapper outBandMapper;\n\n @Resource\n private BareMetalMapper bareMetalMapper;\n\n @Resource\n private RackHDService rackHDService;\n\n ", "post_mask_code": "{\n // 测试每一个自发现机器带外的连通性,并且查看是否有物理机关联该带外ip(手动导入,不存在mac地址的只是视为信息纳管和基本开关机流程控制,因此不需要同步至物理机和RackHD)\n LocalDateTime before = LocalDateTime.now();\n LogUtil.info(String.format(\"开始带外物理机状态更新 标记%s:时间:%s\", before.getDayOfMonth(), before.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:MM:SS\"))));\n OutBandExample pmOutBandExample = new OutBandExample();\n List pmOutBandList = outBandMapper.selectByExample(pmOutBandExample);\n if (pmOutBandList.size() == 0) {\n return;\n }\n updatePowerOutBandStatus(pmOutBandList);\n LocalDateTime now = LocalDateTime.now();\n LogUtil.info(String.format(\"结束开始带外物理机状态更新 标记%s:时间:%s,总共耗时:%s秒\", before.getDayOfMonth(), now.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:MM:SS\")), Duration.between(before, now).getSeconds()));\n }\n\n public void updatePowerOutBandStatus(List pmOutBandList) {\n if (CollectionUtils.isNotEmpty(pmOutBandList)) {\n pmOutBandList.forEach(o -> {\n IPMIUtil.Account account = new IPMIUtil.Account(o.getIp(), o.getUserName(), o.getPwd());\n // 找出对应ip的mac地址的物理机把mac地址回写到带外\n BareMetalExample pmExample = new BareMetalExample();\n pmExample.createCriteria().andIdEqualTo(o.getBareMetalId());\n List pms = bareMetalMapper.selectByExample(pmExample);\n try {\n // ip存在但是账号密码为空\n if (StringUtils.isAnyBlank(account.getHost(), account.getUserName(), account.getPwd())) {\n setStatusBeforeIPMI(o, pms, RackHDConstants.PM_OUT_BAND_UNKNOW);\n return;\n }\n String ipmiResult = IPMIUtil.exeCommand(account, \"power status\");\n o.setStatus(RackHDConstants.PM_OUT_BAND_ON);\n outBandMapper.updateByPrimaryKeySelective(o);\n if (pms.size() > 0) {\n // 根据ipmi请求的返回结果判断物理机是开机还是关机状态\n pms.stream().forEach(p -> {\n // 同时更新物理机的mac地址到带外列表\n o.setMac(p.getBmcMac());\n outBandMapper.updateByPrimaryKey(o);\n updatePmStatusInfo(ipmiResult, p);\n String nodeId = p.getServerId();\n if (StringUtils.isBlank(nodeId)) {\n return;\n }\n if (rackHDService.createOrUpdateObm(o, p))\n return;\n });\n }\n } catch (Exception e) {\n setStatusBeforeIPMI(o, pms, RackHDConstants.PM_OUT_BAND_OFF);\n }\n });\n }\n }\n\n private void setStatusBeforeIPMI(OutBand o, List pms, String outBandStatus) {\n o.setStatus(outBandStatus);\n outBandMapper.updateByPrimaryKeySelective(o);\n pms.stream().forEach(p -> {\n updatePmStatusInfo(RackHDConstants.PM_POWER_UNKNOWN, p);\n });\n return;\n }\n\n private void updatePmStatusInfo(String ipmiResult, BareMetal machine) {\n // 返回结果一般是 Chassis power on/off\n if (StringUtils.isNotBlank(ipmiResult) && ipmiResult.contains(RackHDConstants.PM_POWER_ON)) {\n machine.setPower(RackHDConstants.PM_POWER_ON);\n } else if (StringUtils.isNotBlank(ipmiResult) && ipmiResult.contains(RackHDConstants.PM_POWER_OFF)) {\n machine.setPower(RackHDConstants.PM_POWER_OFF);\n } else {\n machine.setPower(RackHDConstants.PM_POWER_UNKNOWN);\n }\n bareMetalMapper.updateByPrimaryKeySelective(machine);\n }\n}\n"} {"task_id": "Java_2266", "language": "Java", "task_type": "method_body", "source_file": "java/github/rackshift/rackshift/rackshift-server/src/main/java/io/rackshift/job/SyncOutBandJob.java", "mask_start_position": 4123, "mask_end_position": 4353, "canonical_solution": "{\n o.setStatus(outBandStatus);\n outBandMapper.updateByPrimaryKeySelective(o);\n pms.stream().forEach(p -> {\n updatePmStatusInfo(RackHDConstants.PM_POWER_UNKNOWN, p);\n });\n return;\n }", "pre_mask_code": "package io.rackshift.job;\n\nimport io.rackshift.constants.RackHDConstants;\nimport io.rackshift.mybatis.domain.BareMetal;\nimport io.rackshift.mybatis.domain.BareMetalExample;\nimport io.rackshift.mybatis.domain.OutBand;\nimport io.rackshift.mybatis.domain.OutBandExample;\nimport io.rackshift.mybatis.mapper.BareMetalMapper;\nimport io.rackshift.mybatis.mapper.OutBandMapper;\nimport io.rackshift.service.RackHDService;\nimport io.rackshift.utils.IPMIUtil;\nimport io.rackshift.utils.LogUtil;\nimport org.apache.commons.collections.CollectionUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.springframework.scheduling.annotation.Scheduled;\nimport org.springframework.stereotype.Service;\nimport javax.annotation.Resource;\nimport java.time.Duration;\nimport java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.List;\n\n/**\n * ipmi定时扫描任务 更新物理机开关机状态 已经新添加物理机到ipmi被动发现\n */\n@Service\npublic class SyncOutBandJob {\n\n @Resource\n private OutBandMapper outBandMapper;\n\n @Resource\n private BareMetalMapper bareMetalMapper;\n\n @Resource\n private RackHDService rackHDService;\n\n @Scheduled(fixedDelay = 300 * 1000)\n public void updatePowerOutBandStatusScheduler() {\n // 测试每一个自发现机器带外的连通性,并且查看是否有物理机关联该带外ip(手动导入,不存在mac地址的只是视为信息纳管和基本开关机流程控制,因此不需要同步至物理机和RackHD)\n LocalDateTime before = LocalDateTime.now();\n LogUtil.info(String.format(\"开始带外物理机状态更新 标记%s:时间:%s\", before.getDayOfMonth(), before.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:MM:SS\"))));\n OutBandExample pmOutBandExample = new OutBandExample();\n List pmOutBandList = outBandMapper.selectByExample(pmOutBandExample);\n if (pmOutBandList.size() == 0) {\n return;\n }\n updatePowerOutBandStatus(pmOutBandList);\n LocalDateTime now = LocalDateTime.now();\n LogUtil.info(String.format(\"结束开始带外物理机状态更新 标记%s:时间:%s,总共耗时:%s秒\", before.getDayOfMonth(), now.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:MM:SS\")), Duration.between(before, now).getSeconds()));\n }\n\n public void updatePowerOutBandStatus(List pmOutBandList) {\n if (CollectionUtils.isNotEmpty(pmOutBandList)) {\n pmOutBandList.forEach(o -> {\n IPMIUtil.Account account = new IPMIUtil.Account(o.getIp(), o.getUserName(), o.getPwd());\n // 找出对应ip的mac地址的物理机把mac地址回写到带外\n BareMetalExample pmExample = new BareMetalExample();\n pmExample.createCriteria().andIdEqualTo(o.getBareMetalId());\n List pms = bareMetalMapper.selectByExample(pmExample);\n try {\n // ip存在但是账号密码为空\n if (StringUtils.isAnyBlank(account.getHost(), account.getUserName(), account.getPwd())) {\n setStatusBeforeIPMI(o, pms, RackHDConstants.PM_OUT_BAND_UNKNOW);\n return;\n }\n String ipmiResult = IPMIUtil.exeCommand(account, \"power status\");\n o.setStatus(RackHDConstants.PM_OUT_BAND_ON);\n outBandMapper.updateByPrimaryKeySelective(o);\n if (pms.size() > 0) {\n // 根据ipmi请求的返回结果判断物理机是开机还是关机状态\n pms.stream().forEach(p -> {\n // 同时更新物理机的mac地址到带外列表\n o.setMac(p.getBmcMac());\n outBandMapper.updateByPrimaryKey(o);\n updatePmStatusInfo(ipmiResult, p);\n String nodeId = p.getServerId();\n if (StringUtils.isBlank(nodeId)) {\n return;\n }\n if (rackHDService.createOrUpdateObm(o, p))\n return;\n });\n }\n } catch (Exception e) {\n setStatusBeforeIPMI(o, pms, RackHDConstants.PM_OUT_BAND_OFF);\n }\n });\n }\n }\n\n private void setStatusBeforeIPMI(OutBand o, List pms, String outBandStatus) ", "post_mask_code": "\n\n private void updatePmStatusInfo(String ipmiResult, BareMetal machine) {\n // 返回结果一般是 Chassis power on/off\n if (StringUtils.isNotBlank(ipmiResult) && ipmiResult.contains(RackHDConstants.PM_POWER_ON)) {\n machine.setPower(RackHDConstants.PM_POWER_ON);\n } else if (StringUtils.isNotBlank(ipmiResult) && ipmiResult.contains(RackHDConstants.PM_POWER_OFF)) {\n machine.setPower(RackHDConstants.PM_POWER_OFF);\n } else {\n machine.setPower(RackHDConstants.PM_POWER_UNKNOWN);\n }\n bareMetalMapper.updateByPrimaryKeySelective(machine);\n }\n}\n"} {"task_id": "Java_2267", "language": "Java", "task_type": "single_line", "source_file": "java/github/rackshift/rackshift/rackshift-server/src/main/java/io/rackshift/job/SyncOutBandJob.java", "mask_start_position": 4943, "mask_end_position": 4954, "canonical_solution": "e(machine);", "pre_mask_code": "package io.rackshift.job;\n\nimport io.rackshift.constants.RackHDConstants;\nimport io.rackshift.mybatis.domain.BareMetal;\nimport io.rackshift.mybatis.domain.BareMetalExample;\nimport io.rackshift.mybatis.domain.OutBand;\nimport io.rackshift.mybatis.domain.OutBandExample;\nimport io.rackshift.mybatis.mapper.BareMetalMapper;\nimport io.rackshift.mybatis.mapper.OutBandMapper;\nimport io.rackshift.service.RackHDService;\nimport io.rackshift.utils.IPMIUtil;\nimport io.rackshift.utils.LogUtil;\nimport org.apache.commons.collections.CollectionUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.springframework.scheduling.annotation.Scheduled;\nimport org.springframework.stereotype.Service;\nimport javax.annotation.Resource;\nimport java.time.Duration;\nimport java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.List;\n\n/**\n * ipmi定时扫描任务 更新物理机开关机状态 已经新添加物理机到ipmi被动发现\n */\n@Service\npublic class SyncOutBandJob {\n\n @Resource\n private OutBandMapper outBandMapper;\n\n @Resource\n private BareMetalMapper bareMetalMapper;\n\n @Resource\n private RackHDService rackHDService;\n\n @Scheduled(fixedDelay = 300 * 1000)\n public void updatePowerOutBandStatusScheduler() {\n // 测试每一个自发现机器带外的连通性,并且查看是否有物理机关联该带外ip(手动导入,不存在mac地址的只是视为信息纳管和基本开关机流程控制,因此不需要同步至物理机和RackHD)\n LocalDateTime before = LocalDateTime.now();\n LogUtil.info(String.format(\"开始带外物理机状态更新 标记%s:时间:%s\", before.getDayOfMonth(), before.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:MM:SS\"))));\n OutBandExample pmOutBandExample = new OutBandExample();\n List pmOutBandList = outBandMapper.selectByExample(pmOutBandExample);\n if (pmOutBandList.size() == 0) {\n return;\n }\n updatePowerOutBandStatus(pmOutBandList);\n LocalDateTime now = LocalDateTime.now();\n LogUtil.info(String.format(\"结束开始带外物理机状态更新 标记%s:时间:%s,总共耗时:%s秒\", before.getDayOfMonth(), now.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:MM:SS\")), Duration.between(before, now).getSeconds()));\n }\n\n public void updatePowerOutBandStatus(List pmOutBandList) {\n if (CollectionUtils.isNotEmpty(pmOutBandList)) {\n pmOutBandList.forEach(o -> {\n IPMIUtil.Account account = new IPMIUtil.Account(o.getIp(), o.getUserName(), o.getPwd());\n // 找出对应ip的mac地址的物理机把mac地址回写到带外\n BareMetalExample pmExample = new BareMetalExample();\n pmExample.createCriteria().andIdEqualTo(o.getBareMetalId());\n List pms = bareMetalMapper.selectByExample(pmExample);\n try {\n // ip存在但是账号密码为空\n if (StringUtils.isAnyBlank(account.getHost(), account.getUserName(), account.getPwd())) {\n setStatusBeforeIPMI(o, pms, RackHDConstants.PM_OUT_BAND_UNKNOW);\n return;\n }\n String ipmiResult = IPMIUtil.exeCommand(account, \"power status\");\n o.setStatus(RackHDConstants.PM_OUT_BAND_ON);\n outBandMapper.updateByPrimaryKeySelective(o);\n if (pms.size() > 0) {\n // 根据ipmi请求的返回结果判断物理机是开机还是关机状态\n pms.stream().forEach(p -> {\n // 同时更新物理机的mac地址到带外列表\n o.setMac(p.getBmcMac());\n outBandMapper.updateByPrimaryKey(o);\n updatePmStatusInfo(ipmiResult, p);\n String nodeId = p.getServerId();\n if (StringUtils.isBlank(nodeId)) {\n return;\n }\n if (rackHDService.createOrUpdateObm(o, p))\n return;\n });\n }\n } catch (Exception e) {\n setStatusBeforeIPMI(o, pms, RackHDConstants.PM_OUT_BAND_OFF);\n }\n });\n }\n }\n\n private void setStatusBeforeIPMI(OutBand o, List pms, String outBandStatus) {\n o.setStatus(outBandStatus);\n outBandMapper.updateByPrimaryKeySelective(o);\n pms.stream().forEach(p -> {\n updatePmStatusInfo(RackHDConstants.PM_POWER_UNKNOWN, p);\n });\n return;\n }\n\n private void updatePmStatusInfo(String ipmiResult, BareMetal machine) {\n // 返回结果一般是 Chassis power on/off\n if (StringUtils.isNotBlank(ipmiResult) && ipmiResult.contains(RackHDConstants.PM_POWER_ON)) {\n machine.setPower(RackHDConstants.PM_POWER_ON);\n } else if (StringUtils.isNotBlank(ipmiResult) && ipmiResult.contains(RackHDConstants.PM_POWER_OFF)) {\n machine.setPower(RackHDConstants.PM_POWER_OFF);\n } else {\n machine.setPower(RackHDConstants.PM_POWER_UNKNOWN);\n }\n bareMetalMapper.updateByPrimaryKeySelectiv", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2268", "language": "Java", "task_type": "method_signature", "source_file": "java/github/2006-Scape/2006Scape/2006Scape Server/src/main/java/com/rs2/game/content/skills/farming/FruitTree.java", "mask_start_position": 22154, "mask_end_position": 22229, "canonical_solution": "public boolean plantSapling(int objectX, int objectY, final int saplingId) ", "pre_mask_code": "package com.rs2.game.content.skills.farming;\n\n/**\n * @author ArrowzFtw\n */\nimport java.awt.Point;\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.rs2.GameEngine;\nimport com.rs2.event.CycleEvent;\nimport com.rs2.event.CycleEventContainer;\nimport com.rs2.event.CycleEventHandler;\nimport com.rs2.game.content.skills.SkillConstants;\nimport com.rs2.game.players.Player;\nimport com.rs2.util.Misc;\n\n/**\n * Created by IntelliJ IDEA. User: vayken Date: 24/02/12 Time: 20:34 To change\n * this template use File | Settings | File Templates.\n */\npublic class FruitTree {\n\n private Player player;\n\n // set of global constants for Farming\n private static final double COMPOST_CHANCE = 0.9;\n\n private static final double SUPERCOMPOST_CHANCE = 0.7;\n\n private static final double CLEARING_EXPERIENCE = 4;\n\n public FruitTree(Player player) {\n this.player = player;\n }\n\n // Farming data\n public int[] fruitTreeStages = new int[4];\n\n public int[] fruitTreeSaplings = new int[4];\n\n public int[] fruitTreeState = new int[4];\n\n public long[] fruitTreeTimer = new long[4];\n\n public double[] diseaseChance = { 1, 1, 1, 1 };\n\n public boolean[] hasFullyGrown = { false, false, false, false };\n\n public boolean[] fruitTreeWatched = { false, false, false, false, false, false, false, false };\n\n public static final int MAIN_FRUIT_TREE_CONFIG = 503;\n\n /* This is the enum holding the seeds info */\n public enum FruitTreeData {\n\n APPLE(5496, 1955, 1, 27, new int[] { 5986, 9 }, 120, 0.20, 22, 8.5, 0x08, 0x14, 0x0e, 0x21, 0x22, 1199.5, 12, 18),\n BANANA(5497, 1963, 1, 33, new int[] { 5386, 4 }, 120, 0.20, 28, 10.5, 0x23, 0x2f, 0x29, 0x3c, 0x3d, 1750.5, 12, 18),\n ORANGE(5498, 2108, 1, 39, new int[] { 5406, 3 }, 120, 0.20, 35.5, 13.5, 0x48, 0x54, 0x4e, 0x61, 0x62, 2470.2, 12, 18),\n CURRY(5499, 5970, 1, 42, new int[] { 5416, 5 }, 120, 0.25, 40, 15, 0x63, 0x6f, 0x69, 0x7c, 0x7d, 2906.9, 12, 18),\n PINEAPPLE(5500, 2114, 1, 51, new int[] { 5982, 10 }, 120, 0.25, 57, 21.5, 0x88, 0x94, 0x8e, 0xa1, 0xa2, 4605.7, 12, 18),\n PAPAYA(5501, 5972, 1, 57, new int[] { 2114, 10 }, 120, 0.25, 72, 27, 0xa3, 0xaf, 0xa9, 0xbc, 0xbd, 6146.4, 12, 18),\n PALM(5502, 5974, 1, 68, new int[] { 5972, 15 }, 120, 0.25, 170.5, 41.5, 0xc8, 0xd4, 0xce, 0xe1, 0xe2, 10150.1, 12, 18);\n\n private int saplingId;\n\n private int harvestId;\n\n private int saplingAmount;\n\n private int levelRequired;\n\n private int[] paymentToWatch;\n\n private int growthTime;\n\n private double diseaseChance;\n\n private double plantingXp;\n\n private double harvestXp;\n\n private int startingState;\n\n private int endingState;\n\n private int limitState;\n\n private int stumpState;\n\n private int checkHealthState;\n\n private double checkHealthExperience;\n\n private int diseaseDiffValue;\n\n private int deathDiffValue;\n\n private static Map saplings = new HashMap();\n\n static {\n for (FruitTreeData data : FruitTreeData.values()) {\n saplings.put(data.saplingId, data);\n }\n }\n\n FruitTreeData(int saplingId, int harvestId, int saplingAmount, int levelRequired, int[] paymentToWatch, int growthTime, double diseaseChance, double plantingXp, double harvestXp, int startingState, int endingState, int limitState, int stumpState, int checkHealthState, double checkHealthExperience, int diseaseDiffValue, int deathDiffValue) {\n this.saplingId = saplingId;\n this.harvestId = harvestId;\n this.saplingAmount = saplingAmount;\n this.levelRequired = levelRequired;\n this.paymentToWatch = paymentToWatch;\n this.growthTime = growthTime;\n this.diseaseChance = diseaseChance;\n this.plantingXp = plantingXp;\n this.harvestXp = harvestXp;\n this.startingState = startingState;\n this.endingState = endingState;\n this.limitState = limitState;\n this.stumpState = stumpState;\n this.checkHealthState = checkHealthState;\n this.checkHealthExperience = checkHealthExperience;\n this.diseaseDiffValue = diseaseDiffValue;\n this.deathDiffValue = deathDiffValue;\n }\n\n public static FruitTreeData forId(int saplingId) {\n return saplings.get(saplingId);\n }\n\n public int getSapplingId() {\n return saplingId;\n }\n\n public int getHarvestId() {\n return harvestId;\n }\n\n public int getSapplingAmount() {\n return saplingAmount;\n }\n\n public int getLevelRequired() {\n return levelRequired;\n }\n\n public int[] getPaymentToWatch() {\n return paymentToWatch;\n }\n\n public int getGrowthTime() {\n return growthTime;\n }\n\n public double getDiseaseChance() {\n return diseaseChance;\n }\n\n public double getPlantingXp() {\n return plantingXp;\n }\n\n public double getHarvestXp() {\n return harvestXp;\n }\n\n public int getStartingState() {\n return startingState;\n }\n\n public int getEndingState() {\n return endingState;\n }\n\n public int getLimitState() {\n return limitState;\n }\n\n public int getStumpState() {\n return stumpState;\n }\n\n public int getCheckHealthState() {\n return checkHealthState;\n }\n\n public double getCheckHealthXp() {\n return checkHealthExperience;\n }\n\n public int getDiseaseDiffValue() {\n return diseaseDiffValue;\n }\n\n public int getDeathDiffValue() {\n return deathDiffValue;\n }\n }\n\n /* This is the enum data about the different patches */\n public enum FruitTreeFieldsData {\n\n BRIMHAVEN(0, new Point[] { new Point(2764, 3212), new Point(2765, 3213) }, 2330), CATHERBY(1, new Point[] { new Point(2860, 3433), new Point(2861, 3434) }, 2331), TREE_STRONGHOLD(2, new Point[] { new Point(2475, 3445), new Point(2476, 3446) }, 2343), TREE_VILLAGE(3, new Point[] { new Point(2489, 3179), new Point(2890, 3180) }, 2344);\n\n private int fruitTreeIndex;\n\n private Point[] fruitTreePosition;\n\n private int npcId;\n\n private static Map npcsProtecting = new HashMap();\n\n static {\n for (FruitTreeFieldsData data : FruitTreeFieldsData.values()) {\n npcsProtecting.put(data.npcId, data);\n }\n }\n\n public static FruitTreeFieldsData forId(int npcId) {\n return npcsProtecting.get(npcId);\n }\n\n FruitTreeFieldsData(int fruitTreeIndex, Point[] fruitTreePosition, int npcId) {\n this.fruitTreeIndex = fruitTreeIndex;\n this.fruitTreePosition = fruitTreePosition;\n this.npcId = npcId;\n }\n\n public static FruitTreeFieldsData forIdPosition(int x, int y) {\n for (FruitTreeFieldsData fruitTreeFieldsData : FruitTreeFieldsData.values()) {\n if (FarmingConstants.inRangeArea(fruitTreeFieldsData.getFruitTreePosition()[0], fruitTreeFieldsData.getFruitTreePosition()[1], x, y)) {\n return fruitTreeFieldsData;\n }\n }\n return null;\n }\n\n public int getFruitTreeIndex() {\n return fruitTreeIndex;\n }\n\n public Point[] getFruitTreePosition() {\n return fruitTreePosition;\n }\n\n public int getNpcId() {\n return npcId;\n }\n }\n\n /* This is the enum that hold the different data for inspecting the plant */\n public enum InspectData {\n\n APPLE(5496, new String[][] { { \"The apple sapling has only just been planted.\" }, { \"The apple sapling grows into a small stump.\" }, { \"The apple stump grows a little larger.\" }, { \"The apple tree grows a small canopy.\" }, { \"The apple tree grows a second small canopy.\" }, { \"The apple tree grows larger.\" }, { \"The apple tree is ready to be harvested.\" } }),\n BANANA(5497, new String[][] { { \"The banana sapling has only just been planted.\" }, { \"The banana sapling grows 3 segments high, with 2 leaves.\" }, { \"The banana tree grows 2 more leaves.\" }, { \"The banana tree grows 5 segments high, and has some small bananas.\" }, { \"The banana tree grows a bit larger.\" }, { \"The banana tree grows a bit larger.\" }, { \"The banana tree is ready to be harvested.\" } }),\n ORANGE(5498, new String[][] { { \"The orange sapling has only just been planted.\" }, { \"The orange sapling grows slightly taller.\" }, { \"The orange sapling grows even taller.\" }, { \"The orange tree grows a small canopy.\" }, { \"The orange tree grows taller.\" }, { \"The orange tree grows wider and taller.\" }, { \"The oranges on the tree are ready to be harvested.\" } }),\n CURRY(5499, new String[][] { { \"The curry sapling has only just been planted.\" }, { \"The curry trunk grows towards the north.\" }, { \"The curry trunk grows towards the north.\" }, { \"The curry tree grows upwards.\" }, { \"The curry trunk grows towards the south.\" }, { \"The curry trunk grows towards the south.\" }, { \"The curry tree is ready to be harvested.\" } }),\n PINEAPPLE(5500, new String[][] { { \"The pineapple sapling has only just been planted.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant base turns brown.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant is ready to be harvested.\" } }),\n PAPAYA(5501, new String[][] { { \"The papaya sapling has only just been planted.\" }, { \"The papaya sapling grows a little larger.\" }, { \"The papaya tree grows a little larger.\" }, { \"The papaya tree grows a bit larger.\" }, { \"The papaya tree grows some small yellow fruit.\" }, { \"The papaya tree grows larger.\" }, { \"The papaya tree is ready to be harvested.\" } }),\n PALM(5502, new String[][] { { \"The palm sapling has only just been planted.\" }, { \"The palm sapling grows a little larger.\" }, { \"The palm stump grows a little larger.\" }, { \"The palm tree grows a small canopy.\" }, { \"The palm tree grows taller.\" }, { \"The palm tree grows more leaves.\" }, { \"The palm tree is ready to be harvested.\" } });\n\n private int saplingId;\n\n private String[][] messages;\n\n private static Map saplings = new HashMap();\n\n static {\n for (InspectData data : InspectData.values()) {\n saplings.put(data.saplingId, data);\n }\n }\n\n InspectData(int saplingId, String[][] messages) {\n this.saplingId = saplingId;\n this.messages = messages;\n }\n\n public static InspectData forId(int saplingId) {\n return saplings.get(saplingId);\n }\n\n public int getSapplingId() {\n return saplingId;\n }\n\n public String[][] getMessages() {\n return messages;\n }\n }\n\n /* update all the patch states */\n public void updateFruitTreeStates() {\n // brimhaven - catherby - tree stronghold - tree village\n int[] configValues = new int[fruitTreeStages.length];\n int configValue;\n for (int i = 0; i < fruitTreeStages.length; i++) {\n configValues[i] = getConfigValue(fruitTreeStages[i], fruitTreeSaplings[i], fruitTreeState[i], i);\n }\n configValue = (configValues[0] << 16) + (configValues[1] << 8 << 16) + configValues[2] + (configValues[3] << 8);\n player.getPacketSender().sendConfig(MAIN_FRUIT_TREE_CONFIG, configValue);\n }\n\n /* getting the different config values */\n public int getConfigValue(int fruitTreeStage, int saplingId, int plantState, int index) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(saplingId);\n switch(fruitTreeStage) {\n case // weed\n 0:\n return 0x00;\n case // weed cleared\n 1:\n return 0x01;\n case 2:\n return 0x02;\n case 3:\n return 0x03;\n }\n if (fruitTreeData == null) {\n return -1;\n }\n if (fruitTreeStage > fruitTreeData.getEndingState() - fruitTreeData.getStartingState() - 1) {\n hasFullyGrown[index] = true;\n }\n if (plantState == 6)\n return fruitTreeData.getStumpState();\n if (getPlantState(plantState, fruitTreeData, fruitTreeStage) == 3)\n return fruitTreeData.getCheckHealthState();\n return getPlantState(plantState, fruitTreeData, fruitTreeStage);\n }\n\n /* getting the plant states */\n public int getPlantState(int plantState, FruitTreeData fruitTreeData, int fruitTreeStage) {\n int value = fruitTreeData.getStartingState() + fruitTreeStage - 4;\n switch(plantState) {\n case 0:\n return value;\n case 1:\n return value + fruitTreeData.getDiseaseDiffValue();\n case 2:\n return value + fruitTreeData.getDeathDiffValue();\n case 3:\n return fruitTreeData.getCheckHealthState();\n }\n return -1;\n }\n\n /* calculating the disease chance and making the plant grow */\n public void doCalculations() {\n for (int i = 0; i < fruitTreeSaplings.length; i++) {\n if (fruitTreeStages[i] > 0 && fruitTreeStages[i] <= 3 && GameEngine.getMinutesCounter() - fruitTreeTimer[i] >= 5) {\n fruitTreeStages[i]--;\n fruitTreeTimer[i] = GameEngine.getMinutesCounter();\n updateFruitTreeStates();\n continue;\n }\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[i]);\n if (fruitTreeData == null) {\n continue;\n }\n long difference = GameEngine.getMinutesCounter() - fruitTreeTimer[i];\n long growth = fruitTreeData.getGrowthTime();\n int nbStates = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int state = (int) (difference * nbStates / growth);\n if (fruitTreeTimer[i] == 0 || fruitTreeState[i] == 2 || fruitTreeState[i] == 3 || (state > nbStates)) {\n continue;\n }\n if (4 + state != fruitTreeStages[i]) {\n if (fruitTreeStages[i] + fruitTreeData.getStartingState() == fruitTreeData.getLimitState() + 3) {\n fruitTreeStages[i] = fruitTreeData.getEndingState() - fruitTreeData.getStartingState() + 7;\n fruitTreeState[i] = 3;\n updateFruitTreeStates();\n continue;\n }\n fruitTreeStages[i] = 4 + state;\n if (fruitTreeStages[i] <= 4 + state)\n for (int j = fruitTreeStages[i]; j <= 4 + state; j++) doStateCalculation(i);\n updateFruitTreeStates();\n }\n }\n }\n\n /**\n * Woodcutting action\n *\n * @param = tree id\n * @param x\n * = tree x location\n * @param y\n * = tree y location\n * @return\n */\n public boolean cut(final int x, final int y) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(x, y);\n if (fruitTreeFieldsData == null)\n return false;\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null)\n return false;\n if (player.getItemAssistant().freeSlots() <= 0) {\n player.getPacketSender().sendMessage(\"Not enough space in your inventory.\");\n return true;\n }\n if (ChopTree.getAxe(player) == null) {\n return true;\n }\n player.getPacketSender().sendMessage(\"You swing your axe at the tree.\");\n final int emoteId = ChopTree.getAxe(player).getAnimation();\n player.startAnimation(emoteId);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.getPacketSender().sendMessage(\"You cut down the tree.\");\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 6;\n updateFruitTreeStates();\n container.stop();\n }\n\n @Override\n public void stop() {\n player.startAnimation(-1, 0);\n }\n }, 5);\n return true;\n }\n\n public void modifyStage(int i) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[i]);\n if (fruitTreeData == null)\n return;\n long difference = GameEngine.getMinutesCounter() - fruitTreeTimer[i];\n long growth = fruitTreeData.getGrowthTime();\n int nbStates = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int state = (int) (difference * nbStates / growth);\n fruitTreeStages[i] = 4 + state;\n updateFruitTreeStates();\n }\n\n /* calculations about the diseasing chance */\n public void doStateCalculation(int index) {\n if (fruitTreeState[index] == 2) {\n return;\n }\n // if the patch is diseased, it dies, if its watched by a farmer, it\n // goes back to normal\n if (fruitTreeState[index] == 1) {\n if (fruitTreeWatched[index]) {\n fruitTreeState[index] = 0;\n FruitTreeData bushesData = FruitTreeData.forId(fruitTreeSaplings[index]);\n if (bushesData == null)\n return;\n System.out.println(fruitTreeSaplings[index]);\n int difference = bushesData.getEndingState() - bushesData.getStartingState();\n int growth = bushesData.getGrowthTime();\n fruitTreeTimer[index] += (growth / difference);\n modifyStage(index);\n } else {\n fruitTreeState[index] = 2;\n }\n }\n if (fruitTreeState[index] == 5 && fruitTreeStages[index] != 2) {\n fruitTreeState[index] = 0;\n }\n if (fruitTreeState[index] == 0 && fruitTreeStages[index] >= 5 && !hasFullyGrown[index]) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[index]);\n if (fruitTreeData == null) {\n return;\n }\n double chance = diseaseChance[index] * fruitTreeData.getDiseaseChance();\n int maxChance = (int) chance * 100;\n if (Misc.random(100) <= maxChance) {\n fruitTreeState[index] = 1;\n }\n }\n }\n\n /* clearing the patch with a rake of a spade */\n public boolean clearPatch(int objectX, int objectY, int itemId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n int finalAnimation;\n int finalDelay;\n if (fruitTreeFieldsData == null || (itemId != FarmingConstants.RAKE && itemId != FarmingConstants.SPADE)) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] <= 3) {\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.RAKE)) {\n player.getDialogueHandler().sendStatement(\"You need a rake to clear this path.\");\n return true;\n } else {\n finalAnimation = FarmingConstants.RAKING_ANIM;\n finalDelay = 5;\n }\n } else {\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.SPADE)) {\n player.getDialogueHandler().sendStatement(\"You need a spade to clear this path.\");\n return true;\n } else {\n finalAnimation = FarmingConstants.SPADE_ANIM;\n finalDelay = 3;\n }\n }\n final int animation = finalAnimation;\n player.stopPlayer(true);\n player.startAnimation(animation);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.startAnimation(animation);\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] <= 2) {\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()]++;\n player.getItemAssistant().addItem(6055, 1);\n } else {\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] = 3;\n container.stop();\n }\n player.getPlayerAssistant().addSkillXP(CLEARING_EXPERIENCE, SkillConstants.FARMING.ordinal());\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n updateFruitTreeStates();\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n container.stop();\n return;\n }\n }\n\n @Override\n public void stop() {\n resetFruitTrees(fruitTreeFieldsData.getFruitTreeIndex());\n player.getPacketSender().sendMessage(\"You clear the patch.\");\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, finalDelay);\n return true;\n }\n\n /* planting the saplings */\n ", "post_mask_code": "{\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n final FruitTreeData fruitTreeData = FruitTreeData.forId(saplingId);\n if (fruitTreeFieldsData == null || fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] != 3) {\n player.getPacketSender().sendMessage(\"You can't plant a sapling here.\");\n return true;\n }\n if (fruitTreeData.getLevelRequired() > player.playerLevel[SkillConstants.FARMING.ordinal()]) {\n player.getDialogueHandler().sendStatement(\"You need a farming level of \" + fruitTreeData.getLevelRequired() + \" to plant this sapling.\");\n return true;\n }\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.TROWEL)) {\n player.getDialogueHandler().sendStatement(\"You need a trowel to plant the sapling here.\");\n return true;\n }\n player.startAnimation(FarmingConstants.PLANTING_POT_ANIM);\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] = 4;\n player.getItemAssistant().removeItem(saplingId, 1);\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()] = saplingId;\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getPlantingXp(), SkillConstants.FARMING.ordinal());\n container.stop();\n }\n\n @Override\n public void stop() {\n updateFruitTreeStates();\n player.stopPlayer(false);\n }\n }, 3);\n return true;\n }\n\n /* harvesting the plant resulted */\n public boolean harvestOrCheckHealth(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n System.out.println(fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] + fruitTreeData.getStartingState() + \" \" + (fruitTreeData.getLimitState() - 4));\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] + fruitTreeData.getStartingState() == fruitTreeData.getLimitState() + 4) {\n cut(objectX, objectY);\n return true;\n }\n if (player.getItemAssistant().freeSlots() <= 0) {\n player.getPacketSender().sendMessage(\"Not enough space in your inventory.\");\n return true;\n }\n player.startAnimation(832);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n if (player.getItemAssistant().freeSlots() <= 0) {\n container.stop();\n return;\n }\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getPacketSender().sendMessage(\"You examine the tree for signs of disease and find that it's in perfect health.\");\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getCheckHealthXp(), SkillConstants.FARMING.ordinal());\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n hasFullyGrown[fruitTreeFieldsData.getFruitTreeIndex()] = false;\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter() - fruitTreeData.getGrowthTime();\n modifyStage(fruitTreeFieldsData.getFruitTreeIndex());\n container.stop();\n return;\n }\n player.getPacketSender().sendMessage(\"You harvest the crop, and pick a fruit.\");\n player.getItemAssistant().addItem(fruitTreeData.getHarvestId(), 1);\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getHarvestXp(), SkillConstants.FARMING.ordinal());\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n int difference = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int growth = fruitTreeData.getGrowthTime();\n lowerStage(fruitTreeFieldsData.getFruitTreeIndex(), growth - (growth / difference) * (difference + 5 - fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()]));\n modifyStage(fruitTreeFieldsData.getFruitTreeIndex());\n container.stop();\n }\n\n @Override\n public void stop() {\n // TODO Auto-generated method stub\n }\n }, 2);\n return true;\n }\n\n /* lowering the stage */\n public void lowerStage(int index, int timer) {\n hasFullyGrown[index] = false;\n fruitTreeTimer[index] -= timer;\n }\n\n /* putting compost onto the plant */\n public boolean putCompost(int objectX, int objectY, final int itemId) {\n if (itemId != 6032 && itemId != 6034) {\n return false;\n }\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] != 3 || fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 5) {\n player.getPacketSender().sendMessage(\"This patch doesn't need compost.\");\n return true;\n }\n player.getItemAssistant().removeItem(itemId, 1);\n player.getItemAssistant().addItem(1925, 1);\n player.getPacketSender().sendMessage(\"You pour some \" + (itemId == 6034 ? \"super\" : \"\") + \"compost on the patch.\");\n player.startAnimation(FarmingConstants.PUTTING_COMPOST);\n player.getPlayerAssistant().addSkillXP(itemId == 6034 ? Compost.SUPER_COMPOST_EXP_USE : Compost.COMPOST_EXP_USE, SkillConstants.FARMING.ordinal());\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n diseaseChance[fruitTreeFieldsData.getFruitTreeIndex()] *= itemId == 6032 ? COMPOST_CHANCE : SUPERCOMPOST_CHANCE;\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 5;\n container.stop();\n }\n\n @Override\n public void stop() {\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, 7);\n return true;\n }\n\n /* inspecting a plant */\n public boolean inspect(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n final InspectData inspectData = InspectData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 1) {\n player.getDialogueHandler().sendStatement(\"This plant is diseased. Use a plant cure on it to cure it, \", \"or clear the patch with a spade.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 2) {\n player.getDialogueHandler().sendStatement(\"This plant is dead. You did not cure it while it was diseased.\", \"Clear the patch with a spade.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getDialogueHandler().sendStatement(\"This plant has fully grown. You can check it's health\", \"to gain some farming experiences.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 6) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree stump, to remove it, use a \", \"spade on it to clear the patch\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 0) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree patch. The soil has not been treated.\", \"The patch needs weeding.\");\n } else if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree patch. The soil has not been treated.\", \"The patch is empty and weeded.\");\n } else if (inspectData != null && fruitTreeData != null) {\n player.getPacketSender().sendMessage(\"You bend down and start to inspect the patch...\");\n player.startAnimation(1331);\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] - 4 < inspectData.getMessages().length - 2) {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] - 4]);\n } else if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] < fruitTreeData.getEndingState() - fruitTreeData.getStartingState() + 2) {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[inspectData.getMessages().length - 2]);\n } else {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[inspectData.getMessages().length - 1]);\n }\n container.stop();\n }\n\n @Override\n public void stop() {\n player.startAnimation(1332);\n player.stopPlayer(false);\n }\n }, 5);\n }\n return true;\n }\n\n /* opening the corresponding guide about the patch */\n public boolean guide(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n player.getSkillInterfaces().farmingComplex(4);\n player.getSkillInterfaces().selected = 20;\n return true;\n }\n\n /* Curing the plant */\n public boolean pruneArea(int objectX, int objectY, int itemId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null || (itemId != FarmingConstants.SECATEURS && itemId != FarmingConstants.MAGIC_SECATEURS)) {\n return false;\n }\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] != 1) {\n player.getPacketSender().sendMessage(\"This area doesn't need to be pruned.\");\n return true;\n }\n player.startAnimation(FarmingConstants.PRUNING_ANIM);\n player.stopPlayer(true);\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.getPacketSender().sendMessage(\"You prune the area with your secateurs.\");\n container.stop();\n }\n\n @Override\n public void stop() {\n updateFruitTreeStates();\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, 15);\n return true;\n }\n\n private void resetFruitTrees(int index) {\n fruitTreeSaplings[index] = 0;\n fruitTreeState[index] = 0;\n diseaseChance[index] = 1;\n hasFullyGrown[index] = false;\n fruitTreeWatched[index] = false;\n }\n\n /* checking if the patch is raked */\n public boolean checkIfRaked(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null)\n return false;\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3)\n return true;\n return false;\n }\n}\n"} {"task_id": "Java_2269", "language": "Java", "task_type": "method_body", "source_file": "java/github/2006-Scape/2006Scape/2006Scape Server/src/main/java/com/rs2/game/content/skills/farming/FruitTree.java", "mask_start_position": 5278, "mask_end_position": 5323, "canonical_solution": "{\n return startingState;\n }", "pre_mask_code": "package com.rs2.game.content.skills.farming;\n\n/**\n * @author ArrowzFtw\n */\nimport java.awt.Point;\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.rs2.GameEngine;\nimport com.rs2.event.CycleEvent;\nimport com.rs2.event.CycleEventContainer;\nimport com.rs2.event.CycleEventHandler;\nimport com.rs2.game.content.skills.SkillConstants;\nimport com.rs2.game.players.Player;\nimport com.rs2.util.Misc;\n\n/**\n * Created by IntelliJ IDEA. User: vayken Date: 24/02/12 Time: 20:34 To change\n * this template use File | Settings | File Templates.\n */\npublic class FruitTree {\n\n private Player player;\n\n // set of global constants for Farming\n private static final double COMPOST_CHANCE = 0.9;\n\n private static final double SUPERCOMPOST_CHANCE = 0.7;\n\n private static final double CLEARING_EXPERIENCE = 4;\n\n public FruitTree(Player player) {\n this.player = player;\n }\n\n // Farming data\n public int[] fruitTreeStages = new int[4];\n\n public int[] fruitTreeSaplings = new int[4];\n\n public int[] fruitTreeState = new int[4];\n\n public long[] fruitTreeTimer = new long[4];\n\n public double[] diseaseChance = { 1, 1, 1, 1 };\n\n public boolean[] hasFullyGrown = { false, false, false, false };\n\n public boolean[] fruitTreeWatched = { false, false, false, false, false, false, false, false };\n\n public static final int MAIN_FRUIT_TREE_CONFIG = 503;\n\n /* This is the enum holding the seeds info */\n public enum FruitTreeData {\n\n APPLE(5496, 1955, 1, 27, new int[] { 5986, 9 }, 120, 0.20, 22, 8.5, 0x08, 0x14, 0x0e, 0x21, 0x22, 1199.5, 12, 18),\n BANANA(5497, 1963, 1, 33, new int[] { 5386, 4 }, 120, 0.20, 28, 10.5, 0x23, 0x2f, 0x29, 0x3c, 0x3d, 1750.5, 12, 18),\n ORANGE(5498, 2108, 1, 39, new int[] { 5406, 3 }, 120, 0.20, 35.5, 13.5, 0x48, 0x54, 0x4e, 0x61, 0x62, 2470.2, 12, 18),\n CURRY(5499, 5970, 1, 42, new int[] { 5416, 5 }, 120, 0.25, 40, 15, 0x63, 0x6f, 0x69, 0x7c, 0x7d, 2906.9, 12, 18),\n PINEAPPLE(5500, 2114, 1, 51, new int[] { 5982, 10 }, 120, 0.25, 57, 21.5, 0x88, 0x94, 0x8e, 0xa1, 0xa2, 4605.7, 12, 18),\n PAPAYA(5501, 5972, 1, 57, new int[] { 2114, 10 }, 120, 0.25, 72, 27, 0xa3, 0xaf, 0xa9, 0xbc, 0xbd, 6146.4, 12, 18),\n PALM(5502, 5974, 1, 68, new int[] { 5972, 15 }, 120, 0.25, 170.5, 41.5, 0xc8, 0xd4, 0xce, 0xe1, 0xe2, 10150.1, 12, 18);\n\n private int saplingId;\n\n private int harvestId;\n\n private int saplingAmount;\n\n private int levelRequired;\n\n private int[] paymentToWatch;\n\n private int growthTime;\n\n private double diseaseChance;\n\n private double plantingXp;\n\n private double harvestXp;\n\n private int startingState;\n\n private int endingState;\n\n private int limitState;\n\n private int stumpState;\n\n private int checkHealthState;\n\n private double checkHealthExperience;\n\n private int diseaseDiffValue;\n\n private int deathDiffValue;\n\n private static Map saplings = new HashMap();\n\n static {\n for (FruitTreeData data : FruitTreeData.values()) {\n saplings.put(data.saplingId, data);\n }\n }\n\n FruitTreeData(int saplingId, int harvestId, int saplingAmount, int levelRequired, int[] paymentToWatch, int growthTime, double diseaseChance, double plantingXp, double harvestXp, int startingState, int endingState, int limitState, int stumpState, int checkHealthState, double checkHealthExperience, int diseaseDiffValue, int deathDiffValue) {\n this.saplingId = saplingId;\n this.harvestId = harvestId;\n this.saplingAmount = saplingAmount;\n this.levelRequired = levelRequired;\n this.paymentToWatch = paymentToWatch;\n this.growthTime = growthTime;\n this.diseaseChance = diseaseChance;\n this.plantingXp = plantingXp;\n this.harvestXp = harvestXp;\n this.startingState = startingState;\n this.endingState = endingState;\n this.limitState = limitState;\n this.stumpState = stumpState;\n this.checkHealthState = checkHealthState;\n this.checkHealthExperience = checkHealthExperience;\n this.diseaseDiffValue = diseaseDiffValue;\n this.deathDiffValue = deathDiffValue;\n }\n\n public static FruitTreeData forId(int saplingId) {\n return saplings.get(saplingId);\n }\n\n public int getSapplingId() {\n return saplingId;\n }\n\n public int getHarvestId() {\n return harvestId;\n }\n\n public int getSapplingAmount() {\n return saplingAmount;\n }\n\n public int getLevelRequired() {\n return levelRequired;\n }\n\n public int[] getPaymentToWatch() {\n return paymentToWatch;\n }\n\n public int getGrowthTime() {\n return growthTime;\n }\n\n public double getDiseaseChance() {\n return diseaseChance;\n }\n\n public double getPlantingXp() {\n return plantingXp;\n }\n\n public double getHarvestXp() {\n return harvestXp;\n }\n\n public int getStartingState() ", "post_mask_code": "\n\n public int getEndingState() {\n return endingState;\n }\n\n public int getLimitState() {\n return limitState;\n }\n\n public int getStumpState() {\n return stumpState;\n }\n\n public int getCheckHealthState() {\n return checkHealthState;\n }\n\n public double getCheckHealthXp() {\n return checkHealthExperience;\n }\n\n public int getDiseaseDiffValue() {\n return diseaseDiffValue;\n }\n\n public int getDeathDiffValue() {\n return deathDiffValue;\n }\n }\n\n /* This is the enum data about the different patches */\n public enum FruitTreeFieldsData {\n\n BRIMHAVEN(0, new Point[] { new Point(2764, 3212), new Point(2765, 3213) }, 2330), CATHERBY(1, new Point[] { new Point(2860, 3433), new Point(2861, 3434) }, 2331), TREE_STRONGHOLD(2, new Point[] { new Point(2475, 3445), new Point(2476, 3446) }, 2343), TREE_VILLAGE(3, new Point[] { new Point(2489, 3179), new Point(2890, 3180) }, 2344);\n\n private int fruitTreeIndex;\n\n private Point[] fruitTreePosition;\n\n private int npcId;\n\n private static Map npcsProtecting = new HashMap();\n\n static {\n for (FruitTreeFieldsData data : FruitTreeFieldsData.values()) {\n npcsProtecting.put(data.npcId, data);\n }\n }\n\n public static FruitTreeFieldsData forId(int npcId) {\n return npcsProtecting.get(npcId);\n }\n\n FruitTreeFieldsData(int fruitTreeIndex, Point[] fruitTreePosition, int npcId) {\n this.fruitTreeIndex = fruitTreeIndex;\n this.fruitTreePosition = fruitTreePosition;\n this.npcId = npcId;\n }\n\n public static FruitTreeFieldsData forIdPosition(int x, int y) {\n for (FruitTreeFieldsData fruitTreeFieldsData : FruitTreeFieldsData.values()) {\n if (FarmingConstants.inRangeArea(fruitTreeFieldsData.getFruitTreePosition()[0], fruitTreeFieldsData.getFruitTreePosition()[1], x, y)) {\n return fruitTreeFieldsData;\n }\n }\n return null;\n }\n\n public int getFruitTreeIndex() {\n return fruitTreeIndex;\n }\n\n public Point[] getFruitTreePosition() {\n return fruitTreePosition;\n }\n\n public int getNpcId() {\n return npcId;\n }\n }\n\n /* This is the enum that hold the different data for inspecting the plant */\n public enum InspectData {\n\n APPLE(5496, new String[][] { { \"The apple sapling has only just been planted.\" }, { \"The apple sapling grows into a small stump.\" }, { \"The apple stump grows a little larger.\" }, { \"The apple tree grows a small canopy.\" }, { \"The apple tree grows a second small canopy.\" }, { \"The apple tree grows larger.\" }, { \"The apple tree is ready to be harvested.\" } }),\n BANANA(5497, new String[][] { { \"The banana sapling has only just been planted.\" }, { \"The banana sapling grows 3 segments high, with 2 leaves.\" }, { \"The banana tree grows 2 more leaves.\" }, { \"The banana tree grows 5 segments high, and has some small bananas.\" }, { \"The banana tree grows a bit larger.\" }, { \"The banana tree grows a bit larger.\" }, { \"The banana tree is ready to be harvested.\" } }),\n ORANGE(5498, new String[][] { { \"The orange sapling has only just been planted.\" }, { \"The orange sapling grows slightly taller.\" }, { \"The orange sapling grows even taller.\" }, { \"The orange tree grows a small canopy.\" }, { \"The orange tree grows taller.\" }, { \"The orange tree grows wider and taller.\" }, { \"The oranges on the tree are ready to be harvested.\" } }),\n CURRY(5499, new String[][] { { \"The curry sapling has only just been planted.\" }, { \"The curry trunk grows towards the north.\" }, { \"The curry trunk grows towards the north.\" }, { \"The curry tree grows upwards.\" }, { \"The curry trunk grows towards the south.\" }, { \"The curry trunk grows towards the south.\" }, { \"The curry tree is ready to be harvested.\" } }),\n PINEAPPLE(5500, new String[][] { { \"The pineapple sapling has only just been planted.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant base turns brown.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant is ready to be harvested.\" } }),\n PAPAYA(5501, new String[][] { { \"The papaya sapling has only just been planted.\" }, { \"The papaya sapling grows a little larger.\" }, { \"The papaya tree grows a little larger.\" }, { \"The papaya tree grows a bit larger.\" }, { \"The papaya tree grows some small yellow fruit.\" }, { \"The papaya tree grows larger.\" }, { \"The papaya tree is ready to be harvested.\" } }),\n PALM(5502, new String[][] { { \"The palm sapling has only just been planted.\" }, { \"The palm sapling grows a little larger.\" }, { \"The palm stump grows a little larger.\" }, { \"The palm tree grows a small canopy.\" }, { \"The palm tree grows taller.\" }, { \"The palm tree grows more leaves.\" }, { \"The palm tree is ready to be harvested.\" } });\n\n private int saplingId;\n\n private String[][] messages;\n\n private static Map saplings = new HashMap();\n\n static {\n for (InspectData data : InspectData.values()) {\n saplings.put(data.saplingId, data);\n }\n }\n\n InspectData(int saplingId, String[][] messages) {\n this.saplingId = saplingId;\n this.messages = messages;\n }\n\n public static InspectData forId(int saplingId) {\n return saplings.get(saplingId);\n }\n\n public int getSapplingId() {\n return saplingId;\n }\n\n public String[][] getMessages() {\n return messages;\n }\n }\n\n /* update all the patch states */\n public void updateFruitTreeStates() {\n // brimhaven - catherby - tree stronghold - tree village\n int[] configValues = new int[fruitTreeStages.length];\n int configValue;\n for (int i = 0; i < fruitTreeStages.length; i++) {\n configValues[i] = getConfigValue(fruitTreeStages[i], fruitTreeSaplings[i], fruitTreeState[i], i);\n }\n configValue = (configValues[0] << 16) + (configValues[1] << 8 << 16) + configValues[2] + (configValues[3] << 8);\n player.getPacketSender().sendConfig(MAIN_FRUIT_TREE_CONFIG, configValue);\n }\n\n /* getting the different config values */\n public int getConfigValue(int fruitTreeStage, int saplingId, int plantState, int index) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(saplingId);\n switch(fruitTreeStage) {\n case // weed\n 0:\n return 0x00;\n case // weed cleared\n 1:\n return 0x01;\n case 2:\n return 0x02;\n case 3:\n return 0x03;\n }\n if (fruitTreeData == null) {\n return -1;\n }\n if (fruitTreeStage > fruitTreeData.getEndingState() - fruitTreeData.getStartingState() - 1) {\n hasFullyGrown[index] = true;\n }\n if (plantState == 6)\n return fruitTreeData.getStumpState();\n if (getPlantState(plantState, fruitTreeData, fruitTreeStage) == 3)\n return fruitTreeData.getCheckHealthState();\n return getPlantState(plantState, fruitTreeData, fruitTreeStage);\n }\n\n /* getting the plant states */\n public int getPlantState(int plantState, FruitTreeData fruitTreeData, int fruitTreeStage) {\n int value = fruitTreeData.getStartingState() + fruitTreeStage - 4;\n switch(plantState) {\n case 0:\n return value;\n case 1:\n return value + fruitTreeData.getDiseaseDiffValue();\n case 2:\n return value + fruitTreeData.getDeathDiffValue();\n case 3:\n return fruitTreeData.getCheckHealthState();\n }\n return -1;\n }\n\n /* calculating the disease chance and making the plant grow */\n public void doCalculations() {\n for (int i = 0; i < fruitTreeSaplings.length; i++) {\n if (fruitTreeStages[i] > 0 && fruitTreeStages[i] <= 3 && GameEngine.getMinutesCounter() - fruitTreeTimer[i] >= 5) {\n fruitTreeStages[i]--;\n fruitTreeTimer[i] = GameEngine.getMinutesCounter();\n updateFruitTreeStates();\n continue;\n }\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[i]);\n if (fruitTreeData == null) {\n continue;\n }\n long difference = GameEngine.getMinutesCounter() - fruitTreeTimer[i];\n long growth = fruitTreeData.getGrowthTime();\n int nbStates = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int state = (int) (difference * nbStates / growth);\n if (fruitTreeTimer[i] == 0 || fruitTreeState[i] == 2 || fruitTreeState[i] == 3 || (state > nbStates)) {\n continue;\n }\n if (4 + state != fruitTreeStages[i]) {\n if (fruitTreeStages[i] + fruitTreeData.getStartingState() == fruitTreeData.getLimitState() + 3) {\n fruitTreeStages[i] = fruitTreeData.getEndingState() - fruitTreeData.getStartingState() + 7;\n fruitTreeState[i] = 3;\n updateFruitTreeStates();\n continue;\n }\n fruitTreeStages[i] = 4 + state;\n if (fruitTreeStages[i] <= 4 + state)\n for (int j = fruitTreeStages[i]; j <= 4 + state; j++) doStateCalculation(i);\n updateFruitTreeStates();\n }\n }\n }\n\n /**\n * Woodcutting action\n *\n * @param = tree id\n * @param x\n * = tree x location\n * @param y\n * = tree y location\n * @return\n */\n public boolean cut(final int x, final int y) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(x, y);\n if (fruitTreeFieldsData == null)\n return false;\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null)\n return false;\n if (player.getItemAssistant().freeSlots() <= 0) {\n player.getPacketSender().sendMessage(\"Not enough space in your inventory.\");\n return true;\n }\n if (ChopTree.getAxe(player) == null) {\n return true;\n }\n player.getPacketSender().sendMessage(\"You swing your axe at the tree.\");\n final int emoteId = ChopTree.getAxe(player).getAnimation();\n player.startAnimation(emoteId);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.getPacketSender().sendMessage(\"You cut down the tree.\");\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 6;\n updateFruitTreeStates();\n container.stop();\n }\n\n @Override\n public void stop() {\n player.startAnimation(-1, 0);\n }\n }, 5);\n return true;\n }\n\n public void modifyStage(int i) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[i]);\n if (fruitTreeData == null)\n return;\n long difference = GameEngine.getMinutesCounter() - fruitTreeTimer[i];\n long growth = fruitTreeData.getGrowthTime();\n int nbStates = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int state = (int) (difference * nbStates / growth);\n fruitTreeStages[i] = 4 + state;\n updateFruitTreeStates();\n }\n\n /* calculations about the diseasing chance */\n public void doStateCalculation(int index) {\n if (fruitTreeState[index] == 2) {\n return;\n }\n // if the patch is diseased, it dies, if its watched by a farmer, it\n // goes back to normal\n if (fruitTreeState[index] == 1) {\n if (fruitTreeWatched[index]) {\n fruitTreeState[index] = 0;\n FruitTreeData bushesData = FruitTreeData.forId(fruitTreeSaplings[index]);\n if (bushesData == null)\n return;\n System.out.println(fruitTreeSaplings[index]);\n int difference = bushesData.getEndingState() - bushesData.getStartingState();\n int growth = bushesData.getGrowthTime();\n fruitTreeTimer[index] += (growth / difference);\n modifyStage(index);\n } else {\n fruitTreeState[index] = 2;\n }\n }\n if (fruitTreeState[index] == 5 && fruitTreeStages[index] != 2) {\n fruitTreeState[index] = 0;\n }\n if (fruitTreeState[index] == 0 && fruitTreeStages[index] >= 5 && !hasFullyGrown[index]) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[index]);\n if (fruitTreeData == null) {\n return;\n }\n double chance = diseaseChance[index] * fruitTreeData.getDiseaseChance();\n int maxChance = (int) chance * 100;\n if (Misc.random(100) <= maxChance) {\n fruitTreeState[index] = 1;\n }\n }\n }\n\n /* clearing the patch with a rake of a spade */\n public boolean clearPatch(int objectX, int objectY, int itemId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n int finalAnimation;\n int finalDelay;\n if (fruitTreeFieldsData == null || (itemId != FarmingConstants.RAKE && itemId != FarmingConstants.SPADE)) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] <= 3) {\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.RAKE)) {\n player.getDialogueHandler().sendStatement(\"You need a rake to clear this path.\");\n return true;\n } else {\n finalAnimation = FarmingConstants.RAKING_ANIM;\n finalDelay = 5;\n }\n } else {\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.SPADE)) {\n player.getDialogueHandler().sendStatement(\"You need a spade to clear this path.\");\n return true;\n } else {\n finalAnimation = FarmingConstants.SPADE_ANIM;\n finalDelay = 3;\n }\n }\n final int animation = finalAnimation;\n player.stopPlayer(true);\n player.startAnimation(animation);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.startAnimation(animation);\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] <= 2) {\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()]++;\n player.getItemAssistant().addItem(6055, 1);\n } else {\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] = 3;\n container.stop();\n }\n player.getPlayerAssistant().addSkillXP(CLEARING_EXPERIENCE, SkillConstants.FARMING.ordinal());\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n updateFruitTreeStates();\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n container.stop();\n return;\n }\n }\n\n @Override\n public void stop() {\n resetFruitTrees(fruitTreeFieldsData.getFruitTreeIndex());\n player.getPacketSender().sendMessage(\"You clear the patch.\");\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, finalDelay);\n return true;\n }\n\n /* planting the saplings */\n public boolean plantSapling(int objectX, int objectY, final int saplingId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n final FruitTreeData fruitTreeData = FruitTreeData.forId(saplingId);\n if (fruitTreeFieldsData == null || fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] != 3) {\n player.getPacketSender().sendMessage(\"You can't plant a sapling here.\");\n return true;\n }\n if (fruitTreeData.getLevelRequired() > player.playerLevel[SkillConstants.FARMING.ordinal()]) {\n player.getDialogueHandler().sendStatement(\"You need a farming level of \" + fruitTreeData.getLevelRequired() + \" to plant this sapling.\");\n return true;\n }\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.TROWEL)) {\n player.getDialogueHandler().sendStatement(\"You need a trowel to plant the sapling here.\");\n return true;\n }\n player.startAnimation(FarmingConstants.PLANTING_POT_ANIM);\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] = 4;\n player.getItemAssistant().removeItem(saplingId, 1);\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()] = saplingId;\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getPlantingXp(), SkillConstants.FARMING.ordinal());\n container.stop();\n }\n\n @Override\n public void stop() {\n updateFruitTreeStates();\n player.stopPlayer(false);\n }\n }, 3);\n return true;\n }\n\n /* harvesting the plant resulted */\n public boolean harvestOrCheckHealth(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n System.out.println(fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] + fruitTreeData.getStartingState() + \" \" + (fruitTreeData.getLimitState() - 4));\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] + fruitTreeData.getStartingState() == fruitTreeData.getLimitState() + 4) {\n cut(objectX, objectY);\n return true;\n }\n if (player.getItemAssistant().freeSlots() <= 0) {\n player.getPacketSender().sendMessage(\"Not enough space in your inventory.\");\n return true;\n }\n player.startAnimation(832);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n if (player.getItemAssistant().freeSlots() <= 0) {\n container.stop();\n return;\n }\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getPacketSender().sendMessage(\"You examine the tree for signs of disease and find that it's in perfect health.\");\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getCheckHealthXp(), SkillConstants.FARMING.ordinal());\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n hasFullyGrown[fruitTreeFieldsData.getFruitTreeIndex()] = false;\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter() - fruitTreeData.getGrowthTime();\n modifyStage(fruitTreeFieldsData.getFruitTreeIndex());\n container.stop();\n return;\n }\n player.getPacketSender().sendMessage(\"You harvest the crop, and pick a fruit.\");\n player.getItemAssistant().addItem(fruitTreeData.getHarvestId(), 1);\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getHarvestXp(), SkillConstants.FARMING.ordinal());\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n int difference = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int growth = fruitTreeData.getGrowthTime();\n lowerStage(fruitTreeFieldsData.getFruitTreeIndex(), growth - (growth / difference) * (difference + 5 - fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()]));\n modifyStage(fruitTreeFieldsData.getFruitTreeIndex());\n container.stop();\n }\n\n @Override\n public void stop() {\n // TODO Auto-generated method stub\n }\n }, 2);\n return true;\n }\n\n /* lowering the stage */\n public void lowerStage(int index, int timer) {\n hasFullyGrown[index] = false;\n fruitTreeTimer[index] -= timer;\n }\n\n /* putting compost onto the plant */\n public boolean putCompost(int objectX, int objectY, final int itemId) {\n if (itemId != 6032 && itemId != 6034) {\n return false;\n }\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] != 3 || fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 5) {\n player.getPacketSender().sendMessage(\"This patch doesn't need compost.\");\n return true;\n }\n player.getItemAssistant().removeItem(itemId, 1);\n player.getItemAssistant().addItem(1925, 1);\n player.getPacketSender().sendMessage(\"You pour some \" + (itemId == 6034 ? \"super\" : \"\") + \"compost on the patch.\");\n player.startAnimation(FarmingConstants.PUTTING_COMPOST);\n player.getPlayerAssistant().addSkillXP(itemId == 6034 ? Compost.SUPER_COMPOST_EXP_USE : Compost.COMPOST_EXP_USE, SkillConstants.FARMING.ordinal());\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n diseaseChance[fruitTreeFieldsData.getFruitTreeIndex()] *= itemId == 6032 ? COMPOST_CHANCE : SUPERCOMPOST_CHANCE;\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 5;\n container.stop();\n }\n\n @Override\n public void stop() {\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, 7);\n return true;\n }\n\n /* inspecting a plant */\n public boolean inspect(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n final InspectData inspectData = InspectData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 1) {\n player.getDialogueHandler().sendStatement(\"This plant is diseased. Use a plant cure on it to cure it, \", \"or clear the patch with a spade.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 2) {\n player.getDialogueHandler().sendStatement(\"This plant is dead. You did not cure it while it was diseased.\", \"Clear the patch with a spade.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getDialogueHandler().sendStatement(\"This plant has fully grown. You can check it's health\", \"to gain some farming experiences.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 6) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree stump, to remove it, use a \", \"spade on it to clear the patch\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 0) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree patch. The soil has not been treated.\", \"The patch needs weeding.\");\n } else if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree patch. The soil has not been treated.\", \"The patch is empty and weeded.\");\n } else if (inspectData != null && fruitTreeData != null) {\n player.getPacketSender().sendMessage(\"You bend down and start to inspect the patch...\");\n player.startAnimation(1331);\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] - 4 < inspectData.getMessages().length - 2) {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] - 4]);\n } else if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] < fruitTreeData.getEndingState() - fruitTreeData.getStartingState() + 2) {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[inspectData.getMessages().length - 2]);\n } else {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[inspectData.getMessages().length - 1]);\n }\n container.stop();\n }\n\n @Override\n public void stop() {\n player.startAnimation(1332);\n player.stopPlayer(false);\n }\n }, 5);\n }\n return true;\n }\n\n /* opening the corresponding guide about the patch */\n public boolean guide(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n player.getSkillInterfaces().farmingComplex(4);\n player.getSkillInterfaces().selected = 20;\n return true;\n }\n\n /* Curing the plant */\n public boolean pruneArea(int objectX, int objectY, int itemId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null || (itemId != FarmingConstants.SECATEURS && itemId != FarmingConstants.MAGIC_SECATEURS)) {\n return false;\n }\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] != 1) {\n player.getPacketSender().sendMessage(\"This area doesn't need to be pruned.\");\n return true;\n }\n player.startAnimation(FarmingConstants.PRUNING_ANIM);\n player.stopPlayer(true);\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.getPacketSender().sendMessage(\"You prune the area with your secateurs.\");\n container.stop();\n }\n\n @Override\n public void stop() {\n updateFruitTreeStates();\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, 15);\n return true;\n }\n\n private void resetFruitTrees(int index) {\n fruitTreeSaplings[index] = 0;\n fruitTreeState[index] = 0;\n diseaseChance[index] = 1;\n hasFullyGrown[index] = false;\n fruitTreeWatched[index] = false;\n }\n\n /* checking if the patch is raked */\n public boolean checkIfRaked(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null)\n return false;\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3)\n return true;\n return false;\n }\n}\n"} {"task_id": "Java_2270", "language": "Java", "task_type": "single_line", "source_file": "java/github/2006-Scape/2006Scape/2006Scape Server/src/main/java/com/rs2/game/content/skills/farming/FruitTree.java", "mask_start_position": 23641, "mask_end_position": 23651, "canonical_solution": "yer(true);", "pre_mask_code": "package com.rs2.game.content.skills.farming;\n\n/**\n * @author ArrowzFtw\n */\nimport java.awt.Point;\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.rs2.GameEngine;\nimport com.rs2.event.CycleEvent;\nimport com.rs2.event.CycleEventContainer;\nimport com.rs2.event.CycleEventHandler;\nimport com.rs2.game.content.skills.SkillConstants;\nimport com.rs2.game.players.Player;\nimport com.rs2.util.Misc;\n\n/**\n * Created by IntelliJ IDEA. User: vayken Date: 24/02/12 Time: 20:34 To change\n * this template use File | Settings | File Templates.\n */\npublic class FruitTree {\n\n private Player player;\n\n // set of global constants for Farming\n private static final double COMPOST_CHANCE = 0.9;\n\n private static final double SUPERCOMPOST_CHANCE = 0.7;\n\n private static final double CLEARING_EXPERIENCE = 4;\n\n public FruitTree(Player player) {\n this.player = player;\n }\n\n // Farming data\n public int[] fruitTreeStages = new int[4];\n\n public int[] fruitTreeSaplings = new int[4];\n\n public int[] fruitTreeState = new int[4];\n\n public long[] fruitTreeTimer = new long[4];\n\n public double[] diseaseChance = { 1, 1, 1, 1 };\n\n public boolean[] hasFullyGrown = { false, false, false, false };\n\n public boolean[] fruitTreeWatched = { false, false, false, false, false, false, false, false };\n\n public static final int MAIN_FRUIT_TREE_CONFIG = 503;\n\n /* This is the enum holding the seeds info */\n public enum FruitTreeData {\n\n APPLE(5496, 1955, 1, 27, new int[] { 5986, 9 }, 120, 0.20, 22, 8.5, 0x08, 0x14, 0x0e, 0x21, 0x22, 1199.5, 12, 18),\n BANANA(5497, 1963, 1, 33, new int[] { 5386, 4 }, 120, 0.20, 28, 10.5, 0x23, 0x2f, 0x29, 0x3c, 0x3d, 1750.5, 12, 18),\n ORANGE(5498, 2108, 1, 39, new int[] { 5406, 3 }, 120, 0.20, 35.5, 13.5, 0x48, 0x54, 0x4e, 0x61, 0x62, 2470.2, 12, 18),\n CURRY(5499, 5970, 1, 42, new int[] { 5416, 5 }, 120, 0.25, 40, 15, 0x63, 0x6f, 0x69, 0x7c, 0x7d, 2906.9, 12, 18),\n PINEAPPLE(5500, 2114, 1, 51, new int[] { 5982, 10 }, 120, 0.25, 57, 21.5, 0x88, 0x94, 0x8e, 0xa1, 0xa2, 4605.7, 12, 18),\n PAPAYA(5501, 5972, 1, 57, new int[] { 2114, 10 }, 120, 0.25, 72, 27, 0xa3, 0xaf, 0xa9, 0xbc, 0xbd, 6146.4, 12, 18),\n PALM(5502, 5974, 1, 68, new int[] { 5972, 15 }, 120, 0.25, 170.5, 41.5, 0xc8, 0xd4, 0xce, 0xe1, 0xe2, 10150.1, 12, 18);\n\n private int saplingId;\n\n private int harvestId;\n\n private int saplingAmount;\n\n private int levelRequired;\n\n private int[] paymentToWatch;\n\n private int growthTime;\n\n private double diseaseChance;\n\n private double plantingXp;\n\n private double harvestXp;\n\n private int startingState;\n\n private int endingState;\n\n private int limitState;\n\n private int stumpState;\n\n private int checkHealthState;\n\n private double checkHealthExperience;\n\n private int diseaseDiffValue;\n\n private int deathDiffValue;\n\n private static Map saplings = new HashMap();\n\n static {\n for (FruitTreeData data : FruitTreeData.values()) {\n saplings.put(data.saplingId, data);\n }\n }\n\n FruitTreeData(int saplingId, int harvestId, int saplingAmount, int levelRequired, int[] paymentToWatch, int growthTime, double diseaseChance, double plantingXp, double harvestXp, int startingState, int endingState, int limitState, int stumpState, int checkHealthState, double checkHealthExperience, int diseaseDiffValue, int deathDiffValue) {\n this.saplingId = saplingId;\n this.harvestId = harvestId;\n this.saplingAmount = saplingAmount;\n this.levelRequired = levelRequired;\n this.paymentToWatch = paymentToWatch;\n this.growthTime = growthTime;\n this.diseaseChance = diseaseChance;\n this.plantingXp = plantingXp;\n this.harvestXp = harvestXp;\n this.startingState = startingState;\n this.endingState = endingState;\n this.limitState = limitState;\n this.stumpState = stumpState;\n this.checkHealthState = checkHealthState;\n this.checkHealthExperience = checkHealthExperience;\n this.diseaseDiffValue = diseaseDiffValue;\n this.deathDiffValue = deathDiffValue;\n }\n\n public static FruitTreeData forId(int saplingId) {\n return saplings.get(saplingId);\n }\n\n public int getSapplingId() {\n return saplingId;\n }\n\n public int getHarvestId() {\n return harvestId;\n }\n\n public int getSapplingAmount() {\n return saplingAmount;\n }\n\n public int getLevelRequired() {\n return levelRequired;\n }\n\n public int[] getPaymentToWatch() {\n return paymentToWatch;\n }\n\n public int getGrowthTime() {\n return growthTime;\n }\n\n public double getDiseaseChance() {\n return diseaseChance;\n }\n\n public double getPlantingXp() {\n return plantingXp;\n }\n\n public double getHarvestXp() {\n return harvestXp;\n }\n\n public int getStartingState() {\n return startingState;\n }\n\n public int getEndingState() {\n return endingState;\n }\n\n public int getLimitState() {\n return limitState;\n }\n\n public int getStumpState() {\n return stumpState;\n }\n\n public int getCheckHealthState() {\n return checkHealthState;\n }\n\n public double getCheckHealthXp() {\n return checkHealthExperience;\n }\n\n public int getDiseaseDiffValue() {\n return diseaseDiffValue;\n }\n\n public int getDeathDiffValue() {\n return deathDiffValue;\n }\n }\n\n /* This is the enum data about the different patches */\n public enum FruitTreeFieldsData {\n\n BRIMHAVEN(0, new Point[] { new Point(2764, 3212), new Point(2765, 3213) }, 2330), CATHERBY(1, new Point[] { new Point(2860, 3433), new Point(2861, 3434) }, 2331), TREE_STRONGHOLD(2, new Point[] { new Point(2475, 3445), new Point(2476, 3446) }, 2343), TREE_VILLAGE(3, new Point[] { new Point(2489, 3179), new Point(2890, 3180) }, 2344);\n\n private int fruitTreeIndex;\n\n private Point[] fruitTreePosition;\n\n private int npcId;\n\n private static Map npcsProtecting = new HashMap();\n\n static {\n for (FruitTreeFieldsData data : FruitTreeFieldsData.values()) {\n npcsProtecting.put(data.npcId, data);\n }\n }\n\n public static FruitTreeFieldsData forId(int npcId) {\n return npcsProtecting.get(npcId);\n }\n\n FruitTreeFieldsData(int fruitTreeIndex, Point[] fruitTreePosition, int npcId) {\n this.fruitTreeIndex = fruitTreeIndex;\n this.fruitTreePosition = fruitTreePosition;\n this.npcId = npcId;\n }\n\n public static FruitTreeFieldsData forIdPosition(int x, int y) {\n for (FruitTreeFieldsData fruitTreeFieldsData : FruitTreeFieldsData.values()) {\n if (FarmingConstants.inRangeArea(fruitTreeFieldsData.getFruitTreePosition()[0], fruitTreeFieldsData.getFruitTreePosition()[1], x, y)) {\n return fruitTreeFieldsData;\n }\n }\n return null;\n }\n\n public int getFruitTreeIndex() {\n return fruitTreeIndex;\n }\n\n public Point[] getFruitTreePosition() {\n return fruitTreePosition;\n }\n\n public int getNpcId() {\n return npcId;\n }\n }\n\n /* This is the enum that hold the different data for inspecting the plant */\n public enum InspectData {\n\n APPLE(5496, new String[][] { { \"The apple sapling has only just been planted.\" }, { \"The apple sapling grows into a small stump.\" }, { \"The apple stump grows a little larger.\" }, { \"The apple tree grows a small canopy.\" }, { \"The apple tree grows a second small canopy.\" }, { \"The apple tree grows larger.\" }, { \"The apple tree is ready to be harvested.\" } }),\n BANANA(5497, new String[][] { { \"The banana sapling has only just been planted.\" }, { \"The banana sapling grows 3 segments high, with 2 leaves.\" }, { \"The banana tree grows 2 more leaves.\" }, { \"The banana tree grows 5 segments high, and has some small bananas.\" }, { \"The banana tree grows a bit larger.\" }, { \"The banana tree grows a bit larger.\" }, { \"The banana tree is ready to be harvested.\" } }),\n ORANGE(5498, new String[][] { { \"The orange sapling has only just been planted.\" }, { \"The orange sapling grows slightly taller.\" }, { \"The orange sapling grows even taller.\" }, { \"The orange tree grows a small canopy.\" }, { \"The orange tree grows taller.\" }, { \"The orange tree grows wider and taller.\" }, { \"The oranges on the tree are ready to be harvested.\" } }),\n CURRY(5499, new String[][] { { \"The curry sapling has only just been planted.\" }, { \"The curry trunk grows towards the north.\" }, { \"The curry trunk grows towards the north.\" }, { \"The curry tree grows upwards.\" }, { \"The curry trunk grows towards the south.\" }, { \"The curry trunk grows towards the south.\" }, { \"The curry tree is ready to be harvested.\" } }),\n PINEAPPLE(5500, new String[][] { { \"The pineapple sapling has only just been planted.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant base turns brown.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant is ready to be harvested.\" } }),\n PAPAYA(5501, new String[][] { { \"The papaya sapling has only just been planted.\" }, { \"The papaya sapling grows a little larger.\" }, { \"The papaya tree grows a little larger.\" }, { \"The papaya tree grows a bit larger.\" }, { \"The papaya tree grows some small yellow fruit.\" }, { \"The papaya tree grows larger.\" }, { \"The papaya tree is ready to be harvested.\" } }),\n PALM(5502, new String[][] { { \"The palm sapling has only just been planted.\" }, { \"The palm sapling grows a little larger.\" }, { \"The palm stump grows a little larger.\" }, { \"The palm tree grows a small canopy.\" }, { \"The palm tree grows taller.\" }, { \"The palm tree grows more leaves.\" }, { \"The palm tree is ready to be harvested.\" } });\n\n private int saplingId;\n\n private String[][] messages;\n\n private static Map saplings = new HashMap();\n\n static {\n for (InspectData data : InspectData.values()) {\n saplings.put(data.saplingId, data);\n }\n }\n\n InspectData(int saplingId, String[][] messages) {\n this.saplingId = saplingId;\n this.messages = messages;\n }\n\n public static InspectData forId(int saplingId) {\n return saplings.get(saplingId);\n }\n\n public int getSapplingId() {\n return saplingId;\n }\n\n public String[][] getMessages() {\n return messages;\n }\n }\n\n /* update all the patch states */\n public void updateFruitTreeStates() {\n // brimhaven - catherby - tree stronghold - tree village\n int[] configValues = new int[fruitTreeStages.length];\n int configValue;\n for (int i = 0; i < fruitTreeStages.length; i++) {\n configValues[i] = getConfigValue(fruitTreeStages[i], fruitTreeSaplings[i], fruitTreeState[i], i);\n }\n configValue = (configValues[0] << 16) + (configValues[1] << 8 << 16) + configValues[2] + (configValues[3] << 8);\n player.getPacketSender().sendConfig(MAIN_FRUIT_TREE_CONFIG, configValue);\n }\n\n /* getting the different config values */\n public int getConfigValue(int fruitTreeStage, int saplingId, int plantState, int index) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(saplingId);\n switch(fruitTreeStage) {\n case // weed\n 0:\n return 0x00;\n case // weed cleared\n 1:\n return 0x01;\n case 2:\n return 0x02;\n case 3:\n return 0x03;\n }\n if (fruitTreeData == null) {\n return -1;\n }\n if (fruitTreeStage > fruitTreeData.getEndingState() - fruitTreeData.getStartingState() - 1) {\n hasFullyGrown[index] = true;\n }\n if (plantState == 6)\n return fruitTreeData.getStumpState();\n if (getPlantState(plantState, fruitTreeData, fruitTreeStage) == 3)\n return fruitTreeData.getCheckHealthState();\n return getPlantState(plantState, fruitTreeData, fruitTreeStage);\n }\n\n /* getting the plant states */\n public int getPlantState(int plantState, FruitTreeData fruitTreeData, int fruitTreeStage) {\n int value = fruitTreeData.getStartingState() + fruitTreeStage - 4;\n switch(plantState) {\n case 0:\n return value;\n case 1:\n return value + fruitTreeData.getDiseaseDiffValue();\n case 2:\n return value + fruitTreeData.getDeathDiffValue();\n case 3:\n return fruitTreeData.getCheckHealthState();\n }\n return -1;\n }\n\n /* calculating the disease chance and making the plant grow */\n public void doCalculations() {\n for (int i = 0; i < fruitTreeSaplings.length; i++) {\n if (fruitTreeStages[i] > 0 && fruitTreeStages[i] <= 3 && GameEngine.getMinutesCounter() - fruitTreeTimer[i] >= 5) {\n fruitTreeStages[i]--;\n fruitTreeTimer[i] = GameEngine.getMinutesCounter();\n updateFruitTreeStates();\n continue;\n }\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[i]);\n if (fruitTreeData == null) {\n continue;\n }\n long difference = GameEngine.getMinutesCounter() - fruitTreeTimer[i];\n long growth = fruitTreeData.getGrowthTime();\n int nbStates = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int state = (int) (difference * nbStates / growth);\n if (fruitTreeTimer[i] == 0 || fruitTreeState[i] == 2 || fruitTreeState[i] == 3 || (state > nbStates)) {\n continue;\n }\n if (4 + state != fruitTreeStages[i]) {\n if (fruitTreeStages[i] + fruitTreeData.getStartingState() == fruitTreeData.getLimitState() + 3) {\n fruitTreeStages[i] = fruitTreeData.getEndingState() - fruitTreeData.getStartingState() + 7;\n fruitTreeState[i] = 3;\n updateFruitTreeStates();\n continue;\n }\n fruitTreeStages[i] = 4 + state;\n if (fruitTreeStages[i] <= 4 + state)\n for (int j = fruitTreeStages[i]; j <= 4 + state; j++) doStateCalculation(i);\n updateFruitTreeStates();\n }\n }\n }\n\n /**\n * Woodcutting action\n *\n * @param = tree id\n * @param x\n * = tree x location\n * @param y\n * = tree y location\n * @return\n */\n public boolean cut(final int x, final int y) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(x, y);\n if (fruitTreeFieldsData == null)\n return false;\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null)\n return false;\n if (player.getItemAssistant().freeSlots() <= 0) {\n player.getPacketSender().sendMessage(\"Not enough space in your inventory.\");\n return true;\n }\n if (ChopTree.getAxe(player) == null) {\n return true;\n }\n player.getPacketSender().sendMessage(\"You swing your axe at the tree.\");\n final int emoteId = ChopTree.getAxe(player).getAnimation();\n player.startAnimation(emoteId);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.getPacketSender().sendMessage(\"You cut down the tree.\");\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 6;\n updateFruitTreeStates();\n container.stop();\n }\n\n @Override\n public void stop() {\n player.startAnimation(-1, 0);\n }\n }, 5);\n return true;\n }\n\n public void modifyStage(int i) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[i]);\n if (fruitTreeData == null)\n return;\n long difference = GameEngine.getMinutesCounter() - fruitTreeTimer[i];\n long growth = fruitTreeData.getGrowthTime();\n int nbStates = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int state = (int) (difference * nbStates / growth);\n fruitTreeStages[i] = 4 + state;\n updateFruitTreeStates();\n }\n\n /* calculations about the diseasing chance */\n public void doStateCalculation(int index) {\n if (fruitTreeState[index] == 2) {\n return;\n }\n // if the patch is diseased, it dies, if its watched by a farmer, it\n // goes back to normal\n if (fruitTreeState[index] == 1) {\n if (fruitTreeWatched[index]) {\n fruitTreeState[index] = 0;\n FruitTreeData bushesData = FruitTreeData.forId(fruitTreeSaplings[index]);\n if (bushesData == null)\n return;\n System.out.println(fruitTreeSaplings[index]);\n int difference = bushesData.getEndingState() - bushesData.getStartingState();\n int growth = bushesData.getGrowthTime();\n fruitTreeTimer[index] += (growth / difference);\n modifyStage(index);\n } else {\n fruitTreeState[index] = 2;\n }\n }\n if (fruitTreeState[index] == 5 && fruitTreeStages[index] != 2) {\n fruitTreeState[index] = 0;\n }\n if (fruitTreeState[index] == 0 && fruitTreeStages[index] >= 5 && !hasFullyGrown[index]) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[index]);\n if (fruitTreeData == null) {\n return;\n }\n double chance = diseaseChance[index] * fruitTreeData.getDiseaseChance();\n int maxChance = (int) chance * 100;\n if (Misc.random(100) <= maxChance) {\n fruitTreeState[index] = 1;\n }\n }\n }\n\n /* clearing the patch with a rake of a spade */\n public boolean clearPatch(int objectX, int objectY, int itemId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n int finalAnimation;\n int finalDelay;\n if (fruitTreeFieldsData == null || (itemId != FarmingConstants.RAKE && itemId != FarmingConstants.SPADE)) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] <= 3) {\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.RAKE)) {\n player.getDialogueHandler().sendStatement(\"You need a rake to clear this path.\");\n return true;\n } else {\n finalAnimation = FarmingConstants.RAKING_ANIM;\n finalDelay = 5;\n }\n } else {\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.SPADE)) {\n player.getDialogueHandler().sendStatement(\"You need a spade to clear this path.\");\n return true;\n } else {\n finalAnimation = FarmingConstants.SPADE_ANIM;\n finalDelay = 3;\n }\n }\n final int animation = finalAnimation;\n player.stopPlayer(true);\n player.startAnimation(animation);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.startAnimation(animation);\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] <= 2) {\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()]++;\n player.getItemAssistant().addItem(6055, 1);\n } else {\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] = 3;\n container.stop();\n }\n player.getPlayerAssistant().addSkillXP(CLEARING_EXPERIENCE, SkillConstants.FARMING.ordinal());\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n updateFruitTreeStates();\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n container.stop();\n return;\n }\n }\n\n @Override\n public void stop() {\n resetFruitTrees(fruitTreeFieldsData.getFruitTreeIndex());\n player.getPacketSender().sendMessage(\"You clear the patch.\");\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, finalDelay);\n return true;\n }\n\n /* planting the saplings */\n public boolean plantSapling(int objectX, int objectY, final int saplingId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n final FruitTreeData fruitTreeData = FruitTreeData.forId(saplingId);\n if (fruitTreeFieldsData == null || fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] != 3) {\n player.getPacketSender().sendMessage(\"You can't plant a sapling here.\");\n return true;\n }\n if (fruitTreeData.getLevelRequired() > player.playerLevel[SkillConstants.FARMING.ordinal()]) {\n player.getDialogueHandler().sendStatement(\"You need a farming level of \" + fruitTreeData.getLevelRequired() + \" to plant this sapling.\");\n return true;\n }\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.TROWEL)) {\n player.getDialogueHandler().sendStatement(\"You need a trowel to plant the sapling here.\");\n return true;\n }\n player.startAnimation(FarmingConstants.PLANTING_POT_ANIM);\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] = 4;\n player.getItemAssistant().removeItem(saplingId, 1);\n player.stopPla", "post_mask_code": "\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()] = saplingId;\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getPlantingXp(), SkillConstants.FARMING.ordinal());\n container.stop();\n }\n\n @Override\n public void stop() {\n updateFruitTreeStates();\n player.stopPlayer(false);\n }\n }, 3);\n return true;\n }\n\n /* harvesting the plant resulted */\n public boolean harvestOrCheckHealth(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n System.out.println(fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] + fruitTreeData.getStartingState() + \" \" + (fruitTreeData.getLimitState() - 4));\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] + fruitTreeData.getStartingState() == fruitTreeData.getLimitState() + 4) {\n cut(objectX, objectY);\n return true;\n }\n if (player.getItemAssistant().freeSlots() <= 0) {\n player.getPacketSender().sendMessage(\"Not enough space in your inventory.\");\n return true;\n }\n player.startAnimation(832);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n if (player.getItemAssistant().freeSlots() <= 0) {\n container.stop();\n return;\n }\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getPacketSender().sendMessage(\"You examine the tree for signs of disease and find that it's in perfect health.\");\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getCheckHealthXp(), SkillConstants.FARMING.ordinal());\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n hasFullyGrown[fruitTreeFieldsData.getFruitTreeIndex()] = false;\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter() - fruitTreeData.getGrowthTime();\n modifyStage(fruitTreeFieldsData.getFruitTreeIndex());\n container.stop();\n return;\n }\n player.getPacketSender().sendMessage(\"You harvest the crop, and pick a fruit.\");\n player.getItemAssistant().addItem(fruitTreeData.getHarvestId(), 1);\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getHarvestXp(), SkillConstants.FARMING.ordinal());\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n int difference = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int growth = fruitTreeData.getGrowthTime();\n lowerStage(fruitTreeFieldsData.getFruitTreeIndex(), growth - (growth / difference) * (difference + 5 - fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()]));\n modifyStage(fruitTreeFieldsData.getFruitTreeIndex());\n container.stop();\n }\n\n @Override\n public void stop() {\n // TODO Auto-generated method stub\n }\n }, 2);\n return true;\n }\n\n /* lowering the stage */\n public void lowerStage(int index, int timer) {\n hasFullyGrown[index] = false;\n fruitTreeTimer[index] -= timer;\n }\n\n /* putting compost onto the plant */\n public boolean putCompost(int objectX, int objectY, final int itemId) {\n if (itemId != 6032 && itemId != 6034) {\n return false;\n }\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] != 3 || fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 5) {\n player.getPacketSender().sendMessage(\"This patch doesn't need compost.\");\n return true;\n }\n player.getItemAssistant().removeItem(itemId, 1);\n player.getItemAssistant().addItem(1925, 1);\n player.getPacketSender().sendMessage(\"You pour some \" + (itemId == 6034 ? \"super\" : \"\") + \"compost on the patch.\");\n player.startAnimation(FarmingConstants.PUTTING_COMPOST);\n player.getPlayerAssistant().addSkillXP(itemId == 6034 ? Compost.SUPER_COMPOST_EXP_USE : Compost.COMPOST_EXP_USE, SkillConstants.FARMING.ordinal());\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n diseaseChance[fruitTreeFieldsData.getFruitTreeIndex()] *= itemId == 6032 ? COMPOST_CHANCE : SUPERCOMPOST_CHANCE;\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 5;\n container.stop();\n }\n\n @Override\n public void stop() {\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, 7);\n return true;\n }\n\n /* inspecting a plant */\n public boolean inspect(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n final InspectData inspectData = InspectData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 1) {\n player.getDialogueHandler().sendStatement(\"This plant is diseased. Use a plant cure on it to cure it, \", \"or clear the patch with a spade.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 2) {\n player.getDialogueHandler().sendStatement(\"This plant is dead. You did not cure it while it was diseased.\", \"Clear the patch with a spade.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getDialogueHandler().sendStatement(\"This plant has fully grown. You can check it's health\", \"to gain some farming experiences.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 6) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree stump, to remove it, use a \", \"spade on it to clear the patch\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 0) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree patch. The soil has not been treated.\", \"The patch needs weeding.\");\n } else if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree patch. The soil has not been treated.\", \"The patch is empty and weeded.\");\n } else if (inspectData != null && fruitTreeData != null) {\n player.getPacketSender().sendMessage(\"You bend down and start to inspect the patch...\");\n player.startAnimation(1331);\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] - 4 < inspectData.getMessages().length - 2) {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] - 4]);\n } else if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] < fruitTreeData.getEndingState() - fruitTreeData.getStartingState() + 2) {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[inspectData.getMessages().length - 2]);\n } else {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[inspectData.getMessages().length - 1]);\n }\n container.stop();\n }\n\n @Override\n public void stop() {\n player.startAnimation(1332);\n player.stopPlayer(false);\n }\n }, 5);\n }\n return true;\n }\n\n /* opening the corresponding guide about the patch */\n public boolean guide(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n player.getSkillInterfaces().farmingComplex(4);\n player.getSkillInterfaces().selected = 20;\n return true;\n }\n\n /* Curing the plant */\n public boolean pruneArea(int objectX, int objectY, int itemId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null || (itemId != FarmingConstants.SECATEURS && itemId != FarmingConstants.MAGIC_SECATEURS)) {\n return false;\n }\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] != 1) {\n player.getPacketSender().sendMessage(\"This area doesn't need to be pruned.\");\n return true;\n }\n player.startAnimation(FarmingConstants.PRUNING_ANIM);\n player.stopPlayer(true);\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.getPacketSender().sendMessage(\"You prune the area with your secateurs.\");\n container.stop();\n }\n\n @Override\n public void stop() {\n updateFruitTreeStates();\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, 15);\n return true;\n }\n\n private void resetFruitTrees(int index) {\n fruitTreeSaplings[index] = 0;\n fruitTreeState[index] = 0;\n diseaseChance[index] = 1;\n hasFullyGrown[index] = false;\n fruitTreeWatched[index] = false;\n }\n\n /* checking if the patch is raked */\n public boolean checkIfRaked(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null)\n return false;\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3)\n return true;\n return false;\n }\n}\n"} {"task_id": "Java_2271", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/2006-Scape/2006Scape/2006Scape Server/src/main/java/com/rs2/game/content/skills/farming/FruitTree.java", "mask_start_position": 36336, "mask_end_position": 36695, "canonical_solution": "public boolean checkIfRaked(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null)\n return false;\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3)\n return true;\n return false;\n }", "pre_mask_code": "package com.rs2.game.content.skills.farming;\n\n/**\n * @author ArrowzFtw\n */\nimport java.awt.Point;\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.rs2.GameEngine;\nimport com.rs2.event.CycleEvent;\nimport com.rs2.event.CycleEventContainer;\nimport com.rs2.event.CycleEventHandler;\nimport com.rs2.game.content.skills.SkillConstants;\nimport com.rs2.game.players.Player;\nimport com.rs2.util.Misc;\n\n/**\n * Created by IntelliJ IDEA. User: vayken Date: 24/02/12 Time: 20:34 To change\n * this template use File | Settings | File Templates.\n */\npublic class FruitTree {\n\n private Player player;\n\n // set of global constants for Farming\n private static final double COMPOST_CHANCE = 0.9;\n\n private static final double SUPERCOMPOST_CHANCE = 0.7;\n\n private static final double CLEARING_EXPERIENCE = 4;\n\n public FruitTree(Player player) {\n this.player = player;\n }\n\n // Farming data\n public int[] fruitTreeStages = new int[4];\n\n public int[] fruitTreeSaplings = new int[4];\n\n public int[] fruitTreeState = new int[4];\n\n public long[] fruitTreeTimer = new long[4];\n\n public double[] diseaseChance = { 1, 1, 1, 1 };\n\n public boolean[] hasFullyGrown = { false, false, false, false };\n\n public boolean[] fruitTreeWatched = { false, false, false, false, false, false, false, false };\n\n public static final int MAIN_FRUIT_TREE_CONFIG = 503;\n\n /* This is the enum holding the seeds info */\n public enum FruitTreeData {\n\n APPLE(5496, 1955, 1, 27, new int[] { 5986, 9 }, 120, 0.20, 22, 8.5, 0x08, 0x14, 0x0e, 0x21, 0x22, 1199.5, 12, 18),\n BANANA(5497, 1963, 1, 33, new int[] { 5386, 4 }, 120, 0.20, 28, 10.5, 0x23, 0x2f, 0x29, 0x3c, 0x3d, 1750.5, 12, 18),\n ORANGE(5498, 2108, 1, 39, new int[] { 5406, 3 }, 120, 0.20, 35.5, 13.5, 0x48, 0x54, 0x4e, 0x61, 0x62, 2470.2, 12, 18),\n CURRY(5499, 5970, 1, 42, new int[] { 5416, 5 }, 120, 0.25, 40, 15, 0x63, 0x6f, 0x69, 0x7c, 0x7d, 2906.9, 12, 18),\n PINEAPPLE(5500, 2114, 1, 51, new int[] { 5982, 10 }, 120, 0.25, 57, 21.5, 0x88, 0x94, 0x8e, 0xa1, 0xa2, 4605.7, 12, 18),\n PAPAYA(5501, 5972, 1, 57, new int[] { 2114, 10 }, 120, 0.25, 72, 27, 0xa3, 0xaf, 0xa9, 0xbc, 0xbd, 6146.4, 12, 18),\n PALM(5502, 5974, 1, 68, new int[] { 5972, 15 }, 120, 0.25, 170.5, 41.5, 0xc8, 0xd4, 0xce, 0xe1, 0xe2, 10150.1, 12, 18);\n\n private int saplingId;\n\n private int harvestId;\n\n private int saplingAmount;\n\n private int levelRequired;\n\n private int[] paymentToWatch;\n\n private int growthTime;\n\n private double diseaseChance;\n\n private double plantingXp;\n\n private double harvestXp;\n\n private int startingState;\n\n private int endingState;\n\n private int limitState;\n\n private int stumpState;\n\n private int checkHealthState;\n\n private double checkHealthExperience;\n\n private int diseaseDiffValue;\n\n private int deathDiffValue;\n\n private static Map saplings = new HashMap();\n\n static {\n for (FruitTreeData data : FruitTreeData.values()) {\n saplings.put(data.saplingId, data);\n }\n }\n\n FruitTreeData(int saplingId, int harvestId, int saplingAmount, int levelRequired, int[] paymentToWatch, int growthTime, double diseaseChance, double plantingXp, double harvestXp, int startingState, int endingState, int limitState, int stumpState, int checkHealthState, double checkHealthExperience, int diseaseDiffValue, int deathDiffValue) {\n this.saplingId = saplingId;\n this.harvestId = harvestId;\n this.saplingAmount = saplingAmount;\n this.levelRequired = levelRequired;\n this.paymentToWatch = paymentToWatch;\n this.growthTime = growthTime;\n this.diseaseChance = diseaseChance;\n this.plantingXp = plantingXp;\n this.harvestXp = harvestXp;\n this.startingState = startingState;\n this.endingState = endingState;\n this.limitState = limitState;\n this.stumpState = stumpState;\n this.checkHealthState = checkHealthState;\n this.checkHealthExperience = checkHealthExperience;\n this.diseaseDiffValue = diseaseDiffValue;\n this.deathDiffValue = deathDiffValue;\n }\n\n public static FruitTreeData forId(int saplingId) {\n return saplings.get(saplingId);\n }\n\n public int getSapplingId() {\n return saplingId;\n }\n\n public int getHarvestId() {\n return harvestId;\n }\n\n public int getSapplingAmount() {\n return saplingAmount;\n }\n\n public int getLevelRequired() {\n return levelRequired;\n }\n\n public int[] getPaymentToWatch() {\n return paymentToWatch;\n }\n\n public int getGrowthTime() {\n return growthTime;\n }\n\n public double getDiseaseChance() {\n return diseaseChance;\n }\n\n public double getPlantingXp() {\n return plantingXp;\n }\n\n public double getHarvestXp() {\n return harvestXp;\n }\n\n public int getStartingState() {\n return startingState;\n }\n\n public int getEndingState() {\n return endingState;\n }\n\n public int getLimitState() {\n return limitState;\n }\n\n public int getStumpState() {\n return stumpState;\n }\n\n public int getCheckHealthState() {\n return checkHealthState;\n }\n\n public double getCheckHealthXp() {\n return checkHealthExperience;\n }\n\n public int getDiseaseDiffValue() {\n return diseaseDiffValue;\n }\n\n public int getDeathDiffValue() {\n return deathDiffValue;\n }\n }\n\n /* This is the enum data about the different patches */\n public enum FruitTreeFieldsData {\n\n BRIMHAVEN(0, new Point[] { new Point(2764, 3212), new Point(2765, 3213) }, 2330), CATHERBY(1, new Point[] { new Point(2860, 3433), new Point(2861, 3434) }, 2331), TREE_STRONGHOLD(2, new Point[] { new Point(2475, 3445), new Point(2476, 3446) }, 2343), TREE_VILLAGE(3, new Point[] { new Point(2489, 3179), new Point(2890, 3180) }, 2344);\n\n private int fruitTreeIndex;\n\n private Point[] fruitTreePosition;\n\n private int npcId;\n\n private static Map npcsProtecting = new HashMap();\n\n static {\n for (FruitTreeFieldsData data : FruitTreeFieldsData.values()) {\n npcsProtecting.put(data.npcId, data);\n }\n }\n\n public static FruitTreeFieldsData forId(int npcId) {\n return npcsProtecting.get(npcId);\n }\n\n FruitTreeFieldsData(int fruitTreeIndex, Point[] fruitTreePosition, int npcId) {\n this.fruitTreeIndex = fruitTreeIndex;\n this.fruitTreePosition = fruitTreePosition;\n this.npcId = npcId;\n }\n\n public static FruitTreeFieldsData forIdPosition(int x, int y) {\n for (FruitTreeFieldsData fruitTreeFieldsData : FruitTreeFieldsData.values()) {\n if (FarmingConstants.inRangeArea(fruitTreeFieldsData.getFruitTreePosition()[0], fruitTreeFieldsData.getFruitTreePosition()[1], x, y)) {\n return fruitTreeFieldsData;\n }\n }\n return null;\n }\n\n public int getFruitTreeIndex() {\n return fruitTreeIndex;\n }\n\n public Point[] getFruitTreePosition() {\n return fruitTreePosition;\n }\n\n public int getNpcId() {\n return npcId;\n }\n }\n\n /* This is the enum that hold the different data for inspecting the plant */\n public enum InspectData {\n\n APPLE(5496, new String[][] { { \"The apple sapling has only just been planted.\" }, { \"The apple sapling grows into a small stump.\" }, { \"The apple stump grows a little larger.\" }, { \"The apple tree grows a small canopy.\" }, { \"The apple tree grows a second small canopy.\" }, { \"The apple tree grows larger.\" }, { \"The apple tree is ready to be harvested.\" } }),\n BANANA(5497, new String[][] { { \"The banana sapling has only just been planted.\" }, { \"The banana sapling grows 3 segments high, with 2 leaves.\" }, { \"The banana tree grows 2 more leaves.\" }, { \"The banana tree grows 5 segments high, and has some small bananas.\" }, { \"The banana tree grows a bit larger.\" }, { \"The banana tree grows a bit larger.\" }, { \"The banana tree is ready to be harvested.\" } }),\n ORANGE(5498, new String[][] { { \"The orange sapling has only just been planted.\" }, { \"The orange sapling grows slightly taller.\" }, { \"The orange sapling grows even taller.\" }, { \"The orange tree grows a small canopy.\" }, { \"The orange tree grows taller.\" }, { \"The orange tree grows wider and taller.\" }, { \"The oranges on the tree are ready to be harvested.\" } }),\n CURRY(5499, new String[][] { { \"The curry sapling has only just been planted.\" }, { \"The curry trunk grows towards the north.\" }, { \"The curry trunk grows towards the north.\" }, { \"The curry tree grows upwards.\" }, { \"The curry trunk grows towards the south.\" }, { \"The curry trunk grows towards the south.\" }, { \"The curry tree is ready to be harvested.\" } }),\n PINEAPPLE(5500, new String[][] { { \"The pineapple sapling has only just been planted.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant base turns brown.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant is ready to be harvested.\" } }),\n PAPAYA(5501, new String[][] { { \"The papaya sapling has only just been planted.\" }, { \"The papaya sapling grows a little larger.\" }, { \"The papaya tree grows a little larger.\" }, { \"The papaya tree grows a bit larger.\" }, { \"The papaya tree grows some small yellow fruit.\" }, { \"The papaya tree grows larger.\" }, { \"The papaya tree is ready to be harvested.\" } }),\n PALM(5502, new String[][] { { \"The palm sapling has only just been planted.\" }, { \"The palm sapling grows a little larger.\" }, { \"The palm stump grows a little larger.\" }, { \"The palm tree grows a small canopy.\" }, { \"The palm tree grows taller.\" }, { \"The palm tree grows more leaves.\" }, { \"The palm tree is ready to be harvested.\" } });\n\n private int saplingId;\n\n private String[][] messages;\n\n private static Map saplings = new HashMap();\n\n static {\n for (InspectData data : InspectData.values()) {\n saplings.put(data.saplingId, data);\n }\n }\n\n InspectData(int saplingId, String[][] messages) {\n this.saplingId = saplingId;\n this.messages = messages;\n }\n\n public static InspectData forId(int saplingId) {\n return saplings.get(saplingId);\n }\n\n public int getSapplingId() {\n return saplingId;\n }\n\n public String[][] getMessages() {\n return messages;\n }\n }\n\n /* update all the patch states */\n public void updateFruitTreeStates() {\n // brimhaven - catherby - tree stronghold - tree village\n int[] configValues = new int[fruitTreeStages.length];\n int configValue;\n for (int i = 0; i < fruitTreeStages.length; i++) {\n configValues[i] = getConfigValue(fruitTreeStages[i], fruitTreeSaplings[i], fruitTreeState[i], i);\n }\n configValue = (configValues[0] << 16) + (configValues[1] << 8 << 16) + configValues[2] + (configValues[3] << 8);\n player.getPacketSender().sendConfig(MAIN_FRUIT_TREE_CONFIG, configValue);\n }\n\n /* getting the different config values */\n public int getConfigValue(int fruitTreeStage, int saplingId, int plantState, int index) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(saplingId);\n switch(fruitTreeStage) {\n case // weed\n 0:\n return 0x00;\n case // weed cleared\n 1:\n return 0x01;\n case 2:\n return 0x02;\n case 3:\n return 0x03;\n }\n if (fruitTreeData == null) {\n return -1;\n }\n if (fruitTreeStage > fruitTreeData.getEndingState() - fruitTreeData.getStartingState() - 1) {\n hasFullyGrown[index] = true;\n }\n if (plantState == 6)\n return fruitTreeData.getStumpState();\n if (getPlantState(plantState, fruitTreeData, fruitTreeStage) == 3)\n return fruitTreeData.getCheckHealthState();\n return getPlantState(plantState, fruitTreeData, fruitTreeStage);\n }\n\n /* getting the plant states */\n public int getPlantState(int plantState, FruitTreeData fruitTreeData, int fruitTreeStage) {\n int value = fruitTreeData.getStartingState() + fruitTreeStage - 4;\n switch(plantState) {\n case 0:\n return value;\n case 1:\n return value + fruitTreeData.getDiseaseDiffValue();\n case 2:\n return value + fruitTreeData.getDeathDiffValue();\n case 3:\n return fruitTreeData.getCheckHealthState();\n }\n return -1;\n }\n\n /* calculating the disease chance and making the plant grow */\n public void doCalculations() {\n for (int i = 0; i < fruitTreeSaplings.length; i++) {\n if (fruitTreeStages[i] > 0 && fruitTreeStages[i] <= 3 && GameEngine.getMinutesCounter() - fruitTreeTimer[i] >= 5) {\n fruitTreeStages[i]--;\n fruitTreeTimer[i] = GameEngine.getMinutesCounter();\n updateFruitTreeStates();\n continue;\n }\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[i]);\n if (fruitTreeData == null) {\n continue;\n }\n long difference = GameEngine.getMinutesCounter() - fruitTreeTimer[i];\n long growth = fruitTreeData.getGrowthTime();\n int nbStates = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int state = (int) (difference * nbStates / growth);\n if (fruitTreeTimer[i] == 0 || fruitTreeState[i] == 2 || fruitTreeState[i] == 3 || (state > nbStates)) {\n continue;\n }\n if (4 + state != fruitTreeStages[i]) {\n if (fruitTreeStages[i] + fruitTreeData.getStartingState() == fruitTreeData.getLimitState() + 3) {\n fruitTreeStages[i] = fruitTreeData.getEndingState() - fruitTreeData.getStartingState() + 7;\n fruitTreeState[i] = 3;\n updateFruitTreeStates();\n continue;\n }\n fruitTreeStages[i] = 4 + state;\n if (fruitTreeStages[i] <= 4 + state)\n for (int j = fruitTreeStages[i]; j <= 4 + state; j++) doStateCalculation(i);\n updateFruitTreeStates();\n }\n }\n }\n\n /**\n * Woodcutting action\n *\n * @param = tree id\n * @param x\n * = tree x location\n * @param y\n * = tree y location\n * @return\n */\n public boolean cut(final int x, final int y) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(x, y);\n if (fruitTreeFieldsData == null)\n return false;\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null)\n return false;\n if (player.getItemAssistant().freeSlots() <= 0) {\n player.getPacketSender().sendMessage(\"Not enough space in your inventory.\");\n return true;\n }\n if (ChopTree.getAxe(player) == null) {\n return true;\n }\n player.getPacketSender().sendMessage(\"You swing your axe at the tree.\");\n final int emoteId = ChopTree.getAxe(player).getAnimation();\n player.startAnimation(emoteId);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.getPacketSender().sendMessage(\"You cut down the tree.\");\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 6;\n updateFruitTreeStates();\n container.stop();\n }\n\n @Override\n public void stop() {\n player.startAnimation(-1, 0);\n }\n }, 5);\n return true;\n }\n\n public void modifyStage(int i) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[i]);\n if (fruitTreeData == null)\n return;\n long difference = GameEngine.getMinutesCounter() - fruitTreeTimer[i];\n long growth = fruitTreeData.getGrowthTime();\n int nbStates = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int state = (int) (difference * nbStates / growth);\n fruitTreeStages[i] = 4 + state;\n updateFruitTreeStates();\n }\n\n /* calculations about the diseasing chance */\n public void doStateCalculation(int index) {\n if (fruitTreeState[index] == 2) {\n return;\n }\n // if the patch is diseased, it dies, if its watched by a farmer, it\n // goes back to normal\n if (fruitTreeState[index] == 1) {\n if (fruitTreeWatched[index]) {\n fruitTreeState[index] = 0;\n FruitTreeData bushesData = FruitTreeData.forId(fruitTreeSaplings[index]);\n if (bushesData == null)\n return;\n System.out.println(fruitTreeSaplings[index]);\n int difference = bushesData.getEndingState() - bushesData.getStartingState();\n int growth = bushesData.getGrowthTime();\n fruitTreeTimer[index] += (growth / difference);\n modifyStage(index);\n } else {\n fruitTreeState[index] = 2;\n }\n }\n if (fruitTreeState[index] == 5 && fruitTreeStages[index] != 2) {\n fruitTreeState[index] = 0;\n }\n if (fruitTreeState[index] == 0 && fruitTreeStages[index] >= 5 && !hasFullyGrown[index]) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[index]);\n if (fruitTreeData == null) {\n return;\n }\n double chance = diseaseChance[index] * fruitTreeData.getDiseaseChance();\n int maxChance = (int) chance * 100;\n if (Misc.random(100) <= maxChance) {\n fruitTreeState[index] = 1;\n }\n }\n }\n\n /* clearing the patch with a rake of a spade */\n public boolean clearPatch(int objectX, int objectY, int itemId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n int finalAnimation;\n int finalDelay;\n if (fruitTreeFieldsData == null || (itemId != FarmingConstants.RAKE && itemId != FarmingConstants.SPADE)) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] <= 3) {\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.RAKE)) {\n player.getDialogueHandler().sendStatement(\"You need a rake to clear this path.\");\n return true;\n } else {\n finalAnimation = FarmingConstants.RAKING_ANIM;\n finalDelay = 5;\n }\n } else {\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.SPADE)) {\n player.getDialogueHandler().sendStatement(\"You need a spade to clear this path.\");\n return true;\n } else {\n finalAnimation = FarmingConstants.SPADE_ANIM;\n finalDelay = 3;\n }\n }\n final int animation = finalAnimation;\n player.stopPlayer(true);\n player.startAnimation(animation);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.startAnimation(animation);\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] <= 2) {\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()]++;\n player.getItemAssistant().addItem(6055, 1);\n } else {\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] = 3;\n container.stop();\n }\n player.getPlayerAssistant().addSkillXP(CLEARING_EXPERIENCE, SkillConstants.FARMING.ordinal());\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n updateFruitTreeStates();\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n container.stop();\n return;\n }\n }\n\n @Override\n public void stop() {\n resetFruitTrees(fruitTreeFieldsData.getFruitTreeIndex());\n player.getPacketSender().sendMessage(\"You clear the patch.\");\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, finalDelay);\n return true;\n }\n\n /* planting the saplings */\n public boolean plantSapling(int objectX, int objectY, final int saplingId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n final FruitTreeData fruitTreeData = FruitTreeData.forId(saplingId);\n if (fruitTreeFieldsData == null || fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] != 3) {\n player.getPacketSender().sendMessage(\"You can't plant a sapling here.\");\n return true;\n }\n if (fruitTreeData.getLevelRequired() > player.playerLevel[SkillConstants.FARMING.ordinal()]) {\n player.getDialogueHandler().sendStatement(\"You need a farming level of \" + fruitTreeData.getLevelRequired() + \" to plant this sapling.\");\n return true;\n }\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.TROWEL)) {\n player.getDialogueHandler().sendStatement(\"You need a trowel to plant the sapling here.\");\n return true;\n }\n player.startAnimation(FarmingConstants.PLANTING_POT_ANIM);\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] = 4;\n player.getItemAssistant().removeItem(saplingId, 1);\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()] = saplingId;\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getPlantingXp(), SkillConstants.FARMING.ordinal());\n container.stop();\n }\n\n @Override\n public void stop() {\n updateFruitTreeStates();\n player.stopPlayer(false);\n }\n }, 3);\n return true;\n }\n\n /* harvesting the plant resulted */\n public boolean harvestOrCheckHealth(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n System.out.println(fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] + fruitTreeData.getStartingState() + \" \" + (fruitTreeData.getLimitState() - 4));\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] + fruitTreeData.getStartingState() == fruitTreeData.getLimitState() + 4) {\n cut(objectX, objectY);\n return true;\n }\n if (player.getItemAssistant().freeSlots() <= 0) {\n player.getPacketSender().sendMessage(\"Not enough space in your inventory.\");\n return true;\n }\n player.startAnimation(832);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n if (player.getItemAssistant().freeSlots() <= 0) {\n container.stop();\n return;\n }\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getPacketSender().sendMessage(\"You examine the tree for signs of disease and find that it's in perfect health.\");\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getCheckHealthXp(), SkillConstants.FARMING.ordinal());\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n hasFullyGrown[fruitTreeFieldsData.getFruitTreeIndex()] = false;\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter() - fruitTreeData.getGrowthTime();\n modifyStage(fruitTreeFieldsData.getFruitTreeIndex());\n container.stop();\n return;\n }\n player.getPacketSender().sendMessage(\"You harvest the crop, and pick a fruit.\");\n player.getItemAssistant().addItem(fruitTreeData.getHarvestId(), 1);\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getHarvestXp(), SkillConstants.FARMING.ordinal());\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n int difference = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int growth = fruitTreeData.getGrowthTime();\n lowerStage(fruitTreeFieldsData.getFruitTreeIndex(), growth - (growth / difference) * (difference + 5 - fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()]));\n modifyStage(fruitTreeFieldsData.getFruitTreeIndex());\n container.stop();\n }\n\n @Override\n public void stop() {\n // TODO Auto-generated method stub\n }\n }, 2);\n return true;\n }\n\n /* lowering the stage */\n public void lowerStage(int index, int timer) {\n hasFullyGrown[index] = false;\n fruitTreeTimer[index] -= timer;\n }\n\n /* putting compost onto the plant */\n public boolean putCompost(int objectX, int objectY, final int itemId) {\n if (itemId != 6032 && itemId != 6034) {\n return false;\n }\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] != 3 || fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 5) {\n player.getPacketSender().sendMessage(\"This patch doesn't need compost.\");\n return true;\n }\n player.getItemAssistant().removeItem(itemId, 1);\n player.getItemAssistant().addItem(1925, 1);\n player.getPacketSender().sendMessage(\"You pour some \" + (itemId == 6034 ? \"super\" : \"\") + \"compost on the patch.\");\n player.startAnimation(FarmingConstants.PUTTING_COMPOST);\n player.getPlayerAssistant().addSkillXP(itemId == 6034 ? Compost.SUPER_COMPOST_EXP_USE : Compost.COMPOST_EXP_USE, SkillConstants.FARMING.ordinal());\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n diseaseChance[fruitTreeFieldsData.getFruitTreeIndex()] *= itemId == 6032 ? COMPOST_CHANCE : SUPERCOMPOST_CHANCE;\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 5;\n container.stop();\n }\n\n @Override\n public void stop() {\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, 7);\n return true;\n }\n\n /* inspecting a plant */\n public boolean inspect(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n final InspectData inspectData = InspectData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 1) {\n player.getDialogueHandler().sendStatement(\"This plant is diseased. Use a plant cure on it to cure it, \", \"or clear the patch with a spade.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 2) {\n player.getDialogueHandler().sendStatement(\"This plant is dead. You did not cure it while it was diseased.\", \"Clear the patch with a spade.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getDialogueHandler().sendStatement(\"This plant has fully grown. You can check it's health\", \"to gain some farming experiences.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 6) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree stump, to remove it, use a \", \"spade on it to clear the patch\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 0) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree patch. The soil has not been treated.\", \"The patch needs weeding.\");\n } else if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree patch. The soil has not been treated.\", \"The patch is empty and weeded.\");\n } else if (inspectData != null && fruitTreeData != null) {\n player.getPacketSender().sendMessage(\"You bend down and start to inspect the patch...\");\n player.startAnimation(1331);\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] - 4 < inspectData.getMessages().length - 2) {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] - 4]);\n } else if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] < fruitTreeData.getEndingState() - fruitTreeData.getStartingState() + 2) {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[inspectData.getMessages().length - 2]);\n } else {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[inspectData.getMessages().length - 1]);\n }\n container.stop();\n }\n\n @Override\n public void stop() {\n player.startAnimation(1332);\n player.stopPlayer(false);\n }\n }, 5);\n }\n return true;\n }\n\n /* opening the corresponding guide about the patch */\n public boolean guide(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n player.getSkillInterfaces().farmingComplex(4);\n player.getSkillInterfaces().selected = 20;\n return true;\n }\n\n /* Curing the plant */\n public boolean pruneArea(int objectX, int objectY, int itemId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null || (itemId != FarmingConstants.SECATEURS && itemId != FarmingConstants.MAGIC_SECATEURS)) {\n return false;\n }\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] != 1) {\n player.getPacketSender().sendMessage(\"This area doesn't need to be pruned.\");\n return true;\n }\n player.startAnimation(FarmingConstants.PRUNING_ANIM);\n player.stopPlayer(true);\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.getPacketSender().sendMessage(\"You prune the area with your secateurs.\");\n container.stop();\n }\n\n @Override\n public void stop() {\n updateFruitTreeStates();\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, 15);\n return true;\n }\n\n private void resetFruitTrees(int index) {\n fruitTreeSaplings[index] = 0;\n fruitTreeState[index] = 0;\n diseaseChance[index] = 1;\n hasFullyGrown[index] = false;\n fruitTreeWatched[index] = false;\n }\n\n /* checking if the patch is raked */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2272", "language": "Java", "task_type": "switch_case", "source_file": "java/github/2006-Scape/2006Scape/2006Scape Server/src/main/java/com/rs2/game/content/skills/farming/FruitTree.java", "mask_start_position": 13141, "mask_end_position": 13475, "canonical_solution": "switch(plantState) {\n case 0:\n return value;\n case 1:\n return value + fruitTreeData.getDiseaseDiffValue();\n case 2:\n return value + fruitTreeData.getDeathDiffValue();\n case 3:\n return fruitTreeData.getCheckHealthState();\n }", "pre_mask_code": "package com.rs2.game.content.skills.farming;\n\n/**\n * @author ArrowzFtw\n */\nimport java.awt.Point;\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.rs2.GameEngine;\nimport com.rs2.event.CycleEvent;\nimport com.rs2.event.CycleEventContainer;\nimport com.rs2.event.CycleEventHandler;\nimport com.rs2.game.content.skills.SkillConstants;\nimport com.rs2.game.players.Player;\nimport com.rs2.util.Misc;\n\n/**\n * Created by IntelliJ IDEA. User: vayken Date: 24/02/12 Time: 20:34 To change\n * this template use File | Settings | File Templates.\n */\npublic class FruitTree {\n\n private Player player;\n\n // set of global constants for Farming\n private static final double COMPOST_CHANCE = 0.9;\n\n private static final double SUPERCOMPOST_CHANCE = 0.7;\n\n private static final double CLEARING_EXPERIENCE = 4;\n\n public FruitTree(Player player) {\n this.player = player;\n }\n\n // Farming data\n public int[] fruitTreeStages = new int[4];\n\n public int[] fruitTreeSaplings = new int[4];\n\n public int[] fruitTreeState = new int[4];\n\n public long[] fruitTreeTimer = new long[4];\n\n public double[] diseaseChance = { 1, 1, 1, 1 };\n\n public boolean[] hasFullyGrown = { false, false, false, false };\n\n public boolean[] fruitTreeWatched = { false, false, false, false, false, false, false, false };\n\n public static final int MAIN_FRUIT_TREE_CONFIG = 503;\n\n /* This is the enum holding the seeds info */\n public enum FruitTreeData {\n\n APPLE(5496, 1955, 1, 27, new int[] { 5986, 9 }, 120, 0.20, 22, 8.5, 0x08, 0x14, 0x0e, 0x21, 0x22, 1199.5, 12, 18),\n BANANA(5497, 1963, 1, 33, new int[] { 5386, 4 }, 120, 0.20, 28, 10.5, 0x23, 0x2f, 0x29, 0x3c, 0x3d, 1750.5, 12, 18),\n ORANGE(5498, 2108, 1, 39, new int[] { 5406, 3 }, 120, 0.20, 35.5, 13.5, 0x48, 0x54, 0x4e, 0x61, 0x62, 2470.2, 12, 18),\n CURRY(5499, 5970, 1, 42, new int[] { 5416, 5 }, 120, 0.25, 40, 15, 0x63, 0x6f, 0x69, 0x7c, 0x7d, 2906.9, 12, 18),\n PINEAPPLE(5500, 2114, 1, 51, new int[] { 5982, 10 }, 120, 0.25, 57, 21.5, 0x88, 0x94, 0x8e, 0xa1, 0xa2, 4605.7, 12, 18),\n PAPAYA(5501, 5972, 1, 57, new int[] { 2114, 10 }, 120, 0.25, 72, 27, 0xa3, 0xaf, 0xa9, 0xbc, 0xbd, 6146.4, 12, 18),\n PALM(5502, 5974, 1, 68, new int[] { 5972, 15 }, 120, 0.25, 170.5, 41.5, 0xc8, 0xd4, 0xce, 0xe1, 0xe2, 10150.1, 12, 18);\n\n private int saplingId;\n\n private int harvestId;\n\n private int saplingAmount;\n\n private int levelRequired;\n\n private int[] paymentToWatch;\n\n private int growthTime;\n\n private double diseaseChance;\n\n private double plantingXp;\n\n private double harvestXp;\n\n private int startingState;\n\n private int endingState;\n\n private int limitState;\n\n private int stumpState;\n\n private int checkHealthState;\n\n private double checkHealthExperience;\n\n private int diseaseDiffValue;\n\n private int deathDiffValue;\n\n private static Map saplings = new HashMap();\n\n static {\n for (FruitTreeData data : FruitTreeData.values()) {\n saplings.put(data.saplingId, data);\n }\n }\n\n FruitTreeData(int saplingId, int harvestId, int saplingAmount, int levelRequired, int[] paymentToWatch, int growthTime, double diseaseChance, double plantingXp, double harvestXp, int startingState, int endingState, int limitState, int stumpState, int checkHealthState, double checkHealthExperience, int diseaseDiffValue, int deathDiffValue) {\n this.saplingId = saplingId;\n this.harvestId = harvestId;\n this.saplingAmount = saplingAmount;\n this.levelRequired = levelRequired;\n this.paymentToWatch = paymentToWatch;\n this.growthTime = growthTime;\n this.diseaseChance = diseaseChance;\n this.plantingXp = plantingXp;\n this.harvestXp = harvestXp;\n this.startingState = startingState;\n this.endingState = endingState;\n this.limitState = limitState;\n this.stumpState = stumpState;\n this.checkHealthState = checkHealthState;\n this.checkHealthExperience = checkHealthExperience;\n this.diseaseDiffValue = diseaseDiffValue;\n this.deathDiffValue = deathDiffValue;\n }\n\n public static FruitTreeData forId(int saplingId) {\n return saplings.get(saplingId);\n }\n\n public int getSapplingId() {\n return saplingId;\n }\n\n public int getHarvestId() {\n return harvestId;\n }\n\n public int getSapplingAmount() {\n return saplingAmount;\n }\n\n public int getLevelRequired() {\n return levelRequired;\n }\n\n public int[] getPaymentToWatch() {\n return paymentToWatch;\n }\n\n public int getGrowthTime() {\n return growthTime;\n }\n\n public double getDiseaseChance() {\n return diseaseChance;\n }\n\n public double getPlantingXp() {\n return plantingXp;\n }\n\n public double getHarvestXp() {\n return harvestXp;\n }\n\n public int getStartingState() {\n return startingState;\n }\n\n public int getEndingState() {\n return endingState;\n }\n\n public int getLimitState() {\n return limitState;\n }\n\n public int getStumpState() {\n return stumpState;\n }\n\n public int getCheckHealthState() {\n return checkHealthState;\n }\n\n public double getCheckHealthXp() {\n return checkHealthExperience;\n }\n\n public int getDiseaseDiffValue() {\n return diseaseDiffValue;\n }\n\n public int getDeathDiffValue() {\n return deathDiffValue;\n }\n }\n\n /* This is the enum data about the different patches */\n public enum FruitTreeFieldsData {\n\n BRIMHAVEN(0, new Point[] { new Point(2764, 3212), new Point(2765, 3213) }, 2330), CATHERBY(1, new Point[] { new Point(2860, 3433), new Point(2861, 3434) }, 2331), TREE_STRONGHOLD(2, new Point[] { new Point(2475, 3445), new Point(2476, 3446) }, 2343), TREE_VILLAGE(3, new Point[] { new Point(2489, 3179), new Point(2890, 3180) }, 2344);\n\n private int fruitTreeIndex;\n\n private Point[] fruitTreePosition;\n\n private int npcId;\n\n private static Map npcsProtecting = new HashMap();\n\n static {\n for (FruitTreeFieldsData data : FruitTreeFieldsData.values()) {\n npcsProtecting.put(data.npcId, data);\n }\n }\n\n public static FruitTreeFieldsData forId(int npcId) {\n return npcsProtecting.get(npcId);\n }\n\n FruitTreeFieldsData(int fruitTreeIndex, Point[] fruitTreePosition, int npcId) {\n this.fruitTreeIndex = fruitTreeIndex;\n this.fruitTreePosition = fruitTreePosition;\n this.npcId = npcId;\n }\n\n public static FruitTreeFieldsData forIdPosition(int x, int y) {\n for (FruitTreeFieldsData fruitTreeFieldsData : FruitTreeFieldsData.values()) {\n if (FarmingConstants.inRangeArea(fruitTreeFieldsData.getFruitTreePosition()[0], fruitTreeFieldsData.getFruitTreePosition()[1], x, y)) {\n return fruitTreeFieldsData;\n }\n }\n return null;\n }\n\n public int getFruitTreeIndex() {\n return fruitTreeIndex;\n }\n\n public Point[] getFruitTreePosition() {\n return fruitTreePosition;\n }\n\n public int getNpcId() {\n return npcId;\n }\n }\n\n /* This is the enum that hold the different data for inspecting the plant */\n public enum InspectData {\n\n APPLE(5496, new String[][] { { \"The apple sapling has only just been planted.\" }, { \"The apple sapling grows into a small stump.\" }, { \"The apple stump grows a little larger.\" }, { \"The apple tree grows a small canopy.\" }, { \"The apple tree grows a second small canopy.\" }, { \"The apple tree grows larger.\" }, { \"The apple tree is ready to be harvested.\" } }),\n BANANA(5497, new String[][] { { \"The banana sapling has only just been planted.\" }, { \"The banana sapling grows 3 segments high, with 2 leaves.\" }, { \"The banana tree grows 2 more leaves.\" }, { \"The banana tree grows 5 segments high, and has some small bananas.\" }, { \"The banana tree grows a bit larger.\" }, { \"The banana tree grows a bit larger.\" }, { \"The banana tree is ready to be harvested.\" } }),\n ORANGE(5498, new String[][] { { \"The orange sapling has only just been planted.\" }, { \"The orange sapling grows slightly taller.\" }, { \"The orange sapling grows even taller.\" }, { \"The orange tree grows a small canopy.\" }, { \"The orange tree grows taller.\" }, { \"The orange tree grows wider and taller.\" }, { \"The oranges on the tree are ready to be harvested.\" } }),\n CURRY(5499, new String[][] { { \"The curry sapling has only just been planted.\" }, { \"The curry trunk grows towards the north.\" }, { \"The curry trunk grows towards the north.\" }, { \"The curry tree grows upwards.\" }, { \"The curry trunk grows towards the south.\" }, { \"The curry trunk grows towards the south.\" }, { \"The curry tree is ready to be harvested.\" } }),\n PINEAPPLE(5500, new String[][] { { \"The pineapple sapling has only just been planted.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant base turns brown.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant is ready to be harvested.\" } }),\n PAPAYA(5501, new String[][] { { \"The papaya sapling has only just been planted.\" }, { \"The papaya sapling grows a little larger.\" }, { \"The papaya tree grows a little larger.\" }, { \"The papaya tree grows a bit larger.\" }, { \"The papaya tree grows some small yellow fruit.\" }, { \"The papaya tree grows larger.\" }, { \"The papaya tree is ready to be harvested.\" } }),\n PALM(5502, new String[][] { { \"The palm sapling has only just been planted.\" }, { \"The palm sapling grows a little larger.\" }, { \"The palm stump grows a little larger.\" }, { \"The palm tree grows a small canopy.\" }, { \"The palm tree grows taller.\" }, { \"The palm tree grows more leaves.\" }, { \"The palm tree is ready to be harvested.\" } });\n\n private int saplingId;\n\n private String[][] messages;\n\n private static Map saplings = new HashMap();\n\n static {\n for (InspectData data : InspectData.values()) {\n saplings.put(data.saplingId, data);\n }\n }\n\n InspectData(int saplingId, String[][] messages) {\n this.saplingId = saplingId;\n this.messages = messages;\n }\n\n public static InspectData forId(int saplingId) {\n return saplings.get(saplingId);\n }\n\n public int getSapplingId() {\n return saplingId;\n }\n\n public String[][] getMessages() {\n return messages;\n }\n }\n\n /* update all the patch states */\n public void updateFruitTreeStates() {\n // brimhaven - catherby - tree stronghold - tree village\n int[] configValues = new int[fruitTreeStages.length];\n int configValue;\n for (int i = 0; i < fruitTreeStages.length; i++) {\n configValues[i] = getConfigValue(fruitTreeStages[i], fruitTreeSaplings[i], fruitTreeState[i], i);\n }\n configValue = (configValues[0] << 16) + (configValues[1] << 8 << 16) + configValues[2] + (configValues[3] << 8);\n player.getPacketSender().sendConfig(MAIN_FRUIT_TREE_CONFIG, configValue);\n }\n\n /* getting the different config values */\n public int getConfigValue(int fruitTreeStage, int saplingId, int plantState, int index) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(saplingId);\n switch(fruitTreeStage) {\n case // weed\n 0:\n return 0x00;\n case // weed cleared\n 1:\n return 0x01;\n case 2:\n return 0x02;\n case 3:\n return 0x03;\n }\n if (fruitTreeData == null) {\n return -1;\n }\n if (fruitTreeStage > fruitTreeData.getEndingState() - fruitTreeData.getStartingState() - 1) {\n hasFullyGrown[index] = true;\n }\n if (plantState == 6)\n return fruitTreeData.getStumpState();\n if (getPlantState(plantState, fruitTreeData, fruitTreeStage) == 3)\n return fruitTreeData.getCheckHealthState();\n return getPlantState(plantState, fruitTreeData, fruitTreeStage);\n }\n\n /* getting the plant states */\n public int getPlantState(int plantState, FruitTreeData fruitTreeData, int fruitTreeStage) {\n int value = fruitTreeData.getStartingState() + fruitTreeStage - 4;\n ", "post_mask_code": "\n return -1;\n }\n\n /* calculating the disease chance and making the plant grow */\n public void doCalculations() {\n for (int i = 0; i < fruitTreeSaplings.length; i++) {\n if (fruitTreeStages[i] > 0 && fruitTreeStages[i] <= 3 && GameEngine.getMinutesCounter() - fruitTreeTimer[i] >= 5) {\n fruitTreeStages[i]--;\n fruitTreeTimer[i] = GameEngine.getMinutesCounter();\n updateFruitTreeStates();\n continue;\n }\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[i]);\n if (fruitTreeData == null) {\n continue;\n }\n long difference = GameEngine.getMinutesCounter() - fruitTreeTimer[i];\n long growth = fruitTreeData.getGrowthTime();\n int nbStates = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int state = (int) (difference * nbStates / growth);\n if (fruitTreeTimer[i] == 0 || fruitTreeState[i] == 2 || fruitTreeState[i] == 3 || (state > nbStates)) {\n continue;\n }\n if (4 + state != fruitTreeStages[i]) {\n if (fruitTreeStages[i] + fruitTreeData.getStartingState() == fruitTreeData.getLimitState() + 3) {\n fruitTreeStages[i] = fruitTreeData.getEndingState() - fruitTreeData.getStartingState() + 7;\n fruitTreeState[i] = 3;\n updateFruitTreeStates();\n continue;\n }\n fruitTreeStages[i] = 4 + state;\n if (fruitTreeStages[i] <= 4 + state)\n for (int j = fruitTreeStages[i]; j <= 4 + state; j++) doStateCalculation(i);\n updateFruitTreeStates();\n }\n }\n }\n\n /**\n * Woodcutting action\n *\n * @param = tree id\n * @param x\n * = tree x location\n * @param y\n * = tree y location\n * @return\n */\n public boolean cut(final int x, final int y) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(x, y);\n if (fruitTreeFieldsData == null)\n return false;\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null)\n return false;\n if (player.getItemAssistant().freeSlots() <= 0) {\n player.getPacketSender().sendMessage(\"Not enough space in your inventory.\");\n return true;\n }\n if (ChopTree.getAxe(player) == null) {\n return true;\n }\n player.getPacketSender().sendMessage(\"You swing your axe at the tree.\");\n final int emoteId = ChopTree.getAxe(player).getAnimation();\n player.startAnimation(emoteId);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.getPacketSender().sendMessage(\"You cut down the tree.\");\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 6;\n updateFruitTreeStates();\n container.stop();\n }\n\n @Override\n public void stop() {\n player.startAnimation(-1, 0);\n }\n }, 5);\n return true;\n }\n\n public void modifyStage(int i) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[i]);\n if (fruitTreeData == null)\n return;\n long difference = GameEngine.getMinutesCounter() - fruitTreeTimer[i];\n long growth = fruitTreeData.getGrowthTime();\n int nbStates = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int state = (int) (difference * nbStates / growth);\n fruitTreeStages[i] = 4 + state;\n updateFruitTreeStates();\n }\n\n /* calculations about the diseasing chance */\n public void doStateCalculation(int index) {\n if (fruitTreeState[index] == 2) {\n return;\n }\n // if the patch is diseased, it dies, if its watched by a farmer, it\n // goes back to normal\n if (fruitTreeState[index] == 1) {\n if (fruitTreeWatched[index]) {\n fruitTreeState[index] = 0;\n FruitTreeData bushesData = FruitTreeData.forId(fruitTreeSaplings[index]);\n if (bushesData == null)\n return;\n System.out.println(fruitTreeSaplings[index]);\n int difference = bushesData.getEndingState() - bushesData.getStartingState();\n int growth = bushesData.getGrowthTime();\n fruitTreeTimer[index] += (growth / difference);\n modifyStage(index);\n } else {\n fruitTreeState[index] = 2;\n }\n }\n if (fruitTreeState[index] == 5 && fruitTreeStages[index] != 2) {\n fruitTreeState[index] = 0;\n }\n if (fruitTreeState[index] == 0 && fruitTreeStages[index] >= 5 && !hasFullyGrown[index]) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[index]);\n if (fruitTreeData == null) {\n return;\n }\n double chance = diseaseChance[index] * fruitTreeData.getDiseaseChance();\n int maxChance = (int) chance * 100;\n if (Misc.random(100) <= maxChance) {\n fruitTreeState[index] = 1;\n }\n }\n }\n\n /* clearing the patch with a rake of a spade */\n public boolean clearPatch(int objectX, int objectY, int itemId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n int finalAnimation;\n int finalDelay;\n if (fruitTreeFieldsData == null || (itemId != FarmingConstants.RAKE && itemId != FarmingConstants.SPADE)) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] <= 3) {\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.RAKE)) {\n player.getDialogueHandler().sendStatement(\"You need a rake to clear this path.\");\n return true;\n } else {\n finalAnimation = FarmingConstants.RAKING_ANIM;\n finalDelay = 5;\n }\n } else {\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.SPADE)) {\n player.getDialogueHandler().sendStatement(\"You need a spade to clear this path.\");\n return true;\n } else {\n finalAnimation = FarmingConstants.SPADE_ANIM;\n finalDelay = 3;\n }\n }\n final int animation = finalAnimation;\n player.stopPlayer(true);\n player.startAnimation(animation);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.startAnimation(animation);\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] <= 2) {\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()]++;\n player.getItemAssistant().addItem(6055, 1);\n } else {\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] = 3;\n container.stop();\n }\n player.getPlayerAssistant().addSkillXP(CLEARING_EXPERIENCE, SkillConstants.FARMING.ordinal());\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n updateFruitTreeStates();\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n container.stop();\n return;\n }\n }\n\n @Override\n public void stop() {\n resetFruitTrees(fruitTreeFieldsData.getFruitTreeIndex());\n player.getPacketSender().sendMessage(\"You clear the patch.\");\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, finalDelay);\n return true;\n }\n\n /* planting the saplings */\n public boolean plantSapling(int objectX, int objectY, final int saplingId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n final FruitTreeData fruitTreeData = FruitTreeData.forId(saplingId);\n if (fruitTreeFieldsData == null || fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] != 3) {\n player.getPacketSender().sendMessage(\"You can't plant a sapling here.\");\n return true;\n }\n if (fruitTreeData.getLevelRequired() > player.playerLevel[SkillConstants.FARMING.ordinal()]) {\n player.getDialogueHandler().sendStatement(\"You need a farming level of \" + fruitTreeData.getLevelRequired() + \" to plant this sapling.\");\n return true;\n }\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.TROWEL)) {\n player.getDialogueHandler().sendStatement(\"You need a trowel to plant the sapling here.\");\n return true;\n }\n player.startAnimation(FarmingConstants.PLANTING_POT_ANIM);\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] = 4;\n player.getItemAssistant().removeItem(saplingId, 1);\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()] = saplingId;\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getPlantingXp(), SkillConstants.FARMING.ordinal());\n container.stop();\n }\n\n @Override\n public void stop() {\n updateFruitTreeStates();\n player.stopPlayer(false);\n }\n }, 3);\n return true;\n }\n\n /* harvesting the plant resulted */\n public boolean harvestOrCheckHealth(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n System.out.println(fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] + fruitTreeData.getStartingState() + \" \" + (fruitTreeData.getLimitState() - 4));\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] + fruitTreeData.getStartingState() == fruitTreeData.getLimitState() + 4) {\n cut(objectX, objectY);\n return true;\n }\n if (player.getItemAssistant().freeSlots() <= 0) {\n player.getPacketSender().sendMessage(\"Not enough space in your inventory.\");\n return true;\n }\n player.startAnimation(832);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n if (player.getItemAssistant().freeSlots() <= 0) {\n container.stop();\n return;\n }\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getPacketSender().sendMessage(\"You examine the tree for signs of disease and find that it's in perfect health.\");\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getCheckHealthXp(), SkillConstants.FARMING.ordinal());\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n hasFullyGrown[fruitTreeFieldsData.getFruitTreeIndex()] = false;\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter() - fruitTreeData.getGrowthTime();\n modifyStage(fruitTreeFieldsData.getFruitTreeIndex());\n container.stop();\n return;\n }\n player.getPacketSender().sendMessage(\"You harvest the crop, and pick a fruit.\");\n player.getItemAssistant().addItem(fruitTreeData.getHarvestId(), 1);\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getHarvestXp(), SkillConstants.FARMING.ordinal());\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n int difference = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int growth = fruitTreeData.getGrowthTime();\n lowerStage(fruitTreeFieldsData.getFruitTreeIndex(), growth - (growth / difference) * (difference + 5 - fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()]));\n modifyStage(fruitTreeFieldsData.getFruitTreeIndex());\n container.stop();\n }\n\n @Override\n public void stop() {\n // TODO Auto-generated method stub\n }\n }, 2);\n return true;\n }\n\n /* lowering the stage */\n public void lowerStage(int index, int timer) {\n hasFullyGrown[index] = false;\n fruitTreeTimer[index] -= timer;\n }\n\n /* putting compost onto the plant */\n public boolean putCompost(int objectX, int objectY, final int itemId) {\n if (itemId != 6032 && itemId != 6034) {\n return false;\n }\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] != 3 || fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 5) {\n player.getPacketSender().sendMessage(\"This patch doesn't need compost.\");\n return true;\n }\n player.getItemAssistant().removeItem(itemId, 1);\n player.getItemAssistant().addItem(1925, 1);\n player.getPacketSender().sendMessage(\"You pour some \" + (itemId == 6034 ? \"super\" : \"\") + \"compost on the patch.\");\n player.startAnimation(FarmingConstants.PUTTING_COMPOST);\n player.getPlayerAssistant().addSkillXP(itemId == 6034 ? Compost.SUPER_COMPOST_EXP_USE : Compost.COMPOST_EXP_USE, SkillConstants.FARMING.ordinal());\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n diseaseChance[fruitTreeFieldsData.getFruitTreeIndex()] *= itemId == 6032 ? COMPOST_CHANCE : SUPERCOMPOST_CHANCE;\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 5;\n container.stop();\n }\n\n @Override\n public void stop() {\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, 7);\n return true;\n }\n\n /* inspecting a plant */\n public boolean inspect(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n final InspectData inspectData = InspectData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 1) {\n player.getDialogueHandler().sendStatement(\"This plant is diseased. Use a plant cure on it to cure it, \", \"or clear the patch with a spade.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 2) {\n player.getDialogueHandler().sendStatement(\"This plant is dead. You did not cure it while it was diseased.\", \"Clear the patch with a spade.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getDialogueHandler().sendStatement(\"This plant has fully grown. You can check it's health\", \"to gain some farming experiences.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 6) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree stump, to remove it, use a \", \"spade on it to clear the patch\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 0) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree patch. The soil has not been treated.\", \"The patch needs weeding.\");\n } else if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree patch. The soil has not been treated.\", \"The patch is empty and weeded.\");\n } else if (inspectData != null && fruitTreeData != null) {\n player.getPacketSender().sendMessage(\"You bend down and start to inspect the patch...\");\n player.startAnimation(1331);\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] - 4 < inspectData.getMessages().length - 2) {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] - 4]);\n } else if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] < fruitTreeData.getEndingState() - fruitTreeData.getStartingState() + 2) {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[inspectData.getMessages().length - 2]);\n } else {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[inspectData.getMessages().length - 1]);\n }\n container.stop();\n }\n\n @Override\n public void stop() {\n player.startAnimation(1332);\n player.stopPlayer(false);\n }\n }, 5);\n }\n return true;\n }\n\n /* opening the corresponding guide about the patch */\n public boolean guide(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n player.getSkillInterfaces().farmingComplex(4);\n player.getSkillInterfaces().selected = 20;\n return true;\n }\n\n /* Curing the plant */\n public boolean pruneArea(int objectX, int objectY, int itemId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null || (itemId != FarmingConstants.SECATEURS && itemId != FarmingConstants.MAGIC_SECATEURS)) {\n return false;\n }\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] != 1) {\n player.getPacketSender().sendMessage(\"This area doesn't need to be pruned.\");\n return true;\n }\n player.startAnimation(FarmingConstants.PRUNING_ANIM);\n player.stopPlayer(true);\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.getPacketSender().sendMessage(\"You prune the area with your secateurs.\");\n container.stop();\n }\n\n @Override\n public void stop() {\n updateFruitTreeStates();\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, 15);\n return true;\n }\n\n private void resetFruitTrees(int index) {\n fruitTreeSaplings[index] = 0;\n fruitTreeState[index] = 0;\n diseaseChance[index] = 1;\n hasFullyGrown[index] = false;\n fruitTreeWatched[index] = false;\n }\n\n /* checking if the patch is raked */\n public boolean checkIfRaked(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null)\n return false;\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3)\n return true;\n return false;\n }\n}\n"} {"task_id": "Java_2273", "language": "Java", "task_type": "for_statement", "source_file": "java/github/2006-Scape/2006Scape/2006Scape Server/src/main/java/com/rs2/game/content/skills/farming/FruitTree.java", "mask_start_position": 11536, "mask_end_position": 11706, "canonical_solution": "for (int i = 0; i < fruitTreeStages.length; i++) {\n configValues[i] = getConfigValue(fruitTreeStages[i], fruitTreeSaplings[i], fruitTreeState[i], i);\n }", "pre_mask_code": "package com.rs2.game.content.skills.farming;\n\n/**\n * @author ArrowzFtw\n */\nimport java.awt.Point;\nimport java.util.HashMap;\nimport java.util.Map;\nimport com.rs2.GameEngine;\nimport com.rs2.event.CycleEvent;\nimport com.rs2.event.CycleEventContainer;\nimport com.rs2.event.CycleEventHandler;\nimport com.rs2.game.content.skills.SkillConstants;\nimport com.rs2.game.players.Player;\nimport com.rs2.util.Misc;\n\n/**\n * Created by IntelliJ IDEA. User: vayken Date: 24/02/12 Time: 20:34 To change\n * this template use File | Settings | File Templates.\n */\npublic class FruitTree {\n\n private Player player;\n\n // set of global constants for Farming\n private static final double COMPOST_CHANCE = 0.9;\n\n private static final double SUPERCOMPOST_CHANCE = 0.7;\n\n private static final double CLEARING_EXPERIENCE = 4;\n\n public FruitTree(Player player) {\n this.player = player;\n }\n\n // Farming data\n public int[] fruitTreeStages = new int[4];\n\n public int[] fruitTreeSaplings = new int[4];\n\n public int[] fruitTreeState = new int[4];\n\n public long[] fruitTreeTimer = new long[4];\n\n public double[] diseaseChance = { 1, 1, 1, 1 };\n\n public boolean[] hasFullyGrown = { false, false, false, false };\n\n public boolean[] fruitTreeWatched = { false, false, false, false, false, false, false, false };\n\n public static final int MAIN_FRUIT_TREE_CONFIG = 503;\n\n /* This is the enum holding the seeds info */\n public enum FruitTreeData {\n\n APPLE(5496, 1955, 1, 27, new int[] { 5986, 9 }, 120, 0.20, 22, 8.5, 0x08, 0x14, 0x0e, 0x21, 0x22, 1199.5, 12, 18),\n BANANA(5497, 1963, 1, 33, new int[] { 5386, 4 }, 120, 0.20, 28, 10.5, 0x23, 0x2f, 0x29, 0x3c, 0x3d, 1750.5, 12, 18),\n ORANGE(5498, 2108, 1, 39, new int[] { 5406, 3 }, 120, 0.20, 35.5, 13.5, 0x48, 0x54, 0x4e, 0x61, 0x62, 2470.2, 12, 18),\n CURRY(5499, 5970, 1, 42, new int[] { 5416, 5 }, 120, 0.25, 40, 15, 0x63, 0x6f, 0x69, 0x7c, 0x7d, 2906.9, 12, 18),\n PINEAPPLE(5500, 2114, 1, 51, new int[] { 5982, 10 }, 120, 0.25, 57, 21.5, 0x88, 0x94, 0x8e, 0xa1, 0xa2, 4605.7, 12, 18),\n PAPAYA(5501, 5972, 1, 57, new int[] { 2114, 10 }, 120, 0.25, 72, 27, 0xa3, 0xaf, 0xa9, 0xbc, 0xbd, 6146.4, 12, 18),\n PALM(5502, 5974, 1, 68, new int[] { 5972, 15 }, 120, 0.25, 170.5, 41.5, 0xc8, 0xd4, 0xce, 0xe1, 0xe2, 10150.1, 12, 18);\n\n private int saplingId;\n\n private int harvestId;\n\n private int saplingAmount;\n\n private int levelRequired;\n\n private int[] paymentToWatch;\n\n private int growthTime;\n\n private double diseaseChance;\n\n private double plantingXp;\n\n private double harvestXp;\n\n private int startingState;\n\n private int endingState;\n\n private int limitState;\n\n private int stumpState;\n\n private int checkHealthState;\n\n private double checkHealthExperience;\n\n private int diseaseDiffValue;\n\n private int deathDiffValue;\n\n private static Map saplings = new HashMap();\n\n static {\n for (FruitTreeData data : FruitTreeData.values()) {\n saplings.put(data.saplingId, data);\n }\n }\n\n FruitTreeData(int saplingId, int harvestId, int saplingAmount, int levelRequired, int[] paymentToWatch, int growthTime, double diseaseChance, double plantingXp, double harvestXp, int startingState, int endingState, int limitState, int stumpState, int checkHealthState, double checkHealthExperience, int diseaseDiffValue, int deathDiffValue) {\n this.saplingId = saplingId;\n this.harvestId = harvestId;\n this.saplingAmount = saplingAmount;\n this.levelRequired = levelRequired;\n this.paymentToWatch = paymentToWatch;\n this.growthTime = growthTime;\n this.diseaseChance = diseaseChance;\n this.plantingXp = plantingXp;\n this.harvestXp = harvestXp;\n this.startingState = startingState;\n this.endingState = endingState;\n this.limitState = limitState;\n this.stumpState = stumpState;\n this.checkHealthState = checkHealthState;\n this.checkHealthExperience = checkHealthExperience;\n this.diseaseDiffValue = diseaseDiffValue;\n this.deathDiffValue = deathDiffValue;\n }\n\n public static FruitTreeData forId(int saplingId) {\n return saplings.get(saplingId);\n }\n\n public int getSapplingId() {\n return saplingId;\n }\n\n public int getHarvestId() {\n return harvestId;\n }\n\n public int getSapplingAmount() {\n return saplingAmount;\n }\n\n public int getLevelRequired() {\n return levelRequired;\n }\n\n public int[] getPaymentToWatch() {\n return paymentToWatch;\n }\n\n public int getGrowthTime() {\n return growthTime;\n }\n\n public double getDiseaseChance() {\n return diseaseChance;\n }\n\n public double getPlantingXp() {\n return plantingXp;\n }\n\n public double getHarvestXp() {\n return harvestXp;\n }\n\n public int getStartingState() {\n return startingState;\n }\n\n public int getEndingState() {\n return endingState;\n }\n\n public int getLimitState() {\n return limitState;\n }\n\n public int getStumpState() {\n return stumpState;\n }\n\n public int getCheckHealthState() {\n return checkHealthState;\n }\n\n public double getCheckHealthXp() {\n return checkHealthExperience;\n }\n\n public int getDiseaseDiffValue() {\n return diseaseDiffValue;\n }\n\n public int getDeathDiffValue() {\n return deathDiffValue;\n }\n }\n\n /* This is the enum data about the different patches */\n public enum FruitTreeFieldsData {\n\n BRIMHAVEN(0, new Point[] { new Point(2764, 3212), new Point(2765, 3213) }, 2330), CATHERBY(1, new Point[] { new Point(2860, 3433), new Point(2861, 3434) }, 2331), TREE_STRONGHOLD(2, new Point[] { new Point(2475, 3445), new Point(2476, 3446) }, 2343), TREE_VILLAGE(3, new Point[] { new Point(2489, 3179), new Point(2890, 3180) }, 2344);\n\n private int fruitTreeIndex;\n\n private Point[] fruitTreePosition;\n\n private int npcId;\n\n private static Map npcsProtecting = new HashMap();\n\n static {\n for (FruitTreeFieldsData data : FruitTreeFieldsData.values()) {\n npcsProtecting.put(data.npcId, data);\n }\n }\n\n public static FruitTreeFieldsData forId(int npcId) {\n return npcsProtecting.get(npcId);\n }\n\n FruitTreeFieldsData(int fruitTreeIndex, Point[] fruitTreePosition, int npcId) {\n this.fruitTreeIndex = fruitTreeIndex;\n this.fruitTreePosition = fruitTreePosition;\n this.npcId = npcId;\n }\n\n public static FruitTreeFieldsData forIdPosition(int x, int y) {\n for (FruitTreeFieldsData fruitTreeFieldsData : FruitTreeFieldsData.values()) {\n if (FarmingConstants.inRangeArea(fruitTreeFieldsData.getFruitTreePosition()[0], fruitTreeFieldsData.getFruitTreePosition()[1], x, y)) {\n return fruitTreeFieldsData;\n }\n }\n return null;\n }\n\n public int getFruitTreeIndex() {\n return fruitTreeIndex;\n }\n\n public Point[] getFruitTreePosition() {\n return fruitTreePosition;\n }\n\n public int getNpcId() {\n return npcId;\n }\n }\n\n /* This is the enum that hold the different data for inspecting the plant */\n public enum InspectData {\n\n APPLE(5496, new String[][] { { \"The apple sapling has only just been planted.\" }, { \"The apple sapling grows into a small stump.\" }, { \"The apple stump grows a little larger.\" }, { \"The apple tree grows a small canopy.\" }, { \"The apple tree grows a second small canopy.\" }, { \"The apple tree grows larger.\" }, { \"The apple tree is ready to be harvested.\" } }),\n BANANA(5497, new String[][] { { \"The banana sapling has only just been planted.\" }, { \"The banana sapling grows 3 segments high, with 2 leaves.\" }, { \"The banana tree grows 2 more leaves.\" }, { \"The banana tree grows 5 segments high, and has some small bananas.\" }, { \"The banana tree grows a bit larger.\" }, { \"The banana tree grows a bit larger.\" }, { \"The banana tree is ready to be harvested.\" } }),\n ORANGE(5498, new String[][] { { \"The orange sapling has only just been planted.\" }, { \"The orange sapling grows slightly taller.\" }, { \"The orange sapling grows even taller.\" }, { \"The orange tree grows a small canopy.\" }, { \"The orange tree grows taller.\" }, { \"The orange tree grows wider and taller.\" }, { \"The oranges on the tree are ready to be harvested.\" } }),\n CURRY(5499, new String[][] { { \"The curry sapling has only just been planted.\" }, { \"The curry trunk grows towards the north.\" }, { \"The curry trunk grows towards the north.\" }, { \"The curry tree grows upwards.\" }, { \"The curry trunk grows towards the south.\" }, { \"The curry trunk grows towards the south.\" }, { \"The curry tree is ready to be harvested.\" } }),\n PINEAPPLE(5500, new String[][] { { \"The pineapple sapling has only just been planted.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant base turns brown.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant grows larger.\" }, { \"The pineapple plant is ready to be harvested.\" } }),\n PAPAYA(5501, new String[][] { { \"The papaya sapling has only just been planted.\" }, { \"The papaya sapling grows a little larger.\" }, { \"The papaya tree grows a little larger.\" }, { \"The papaya tree grows a bit larger.\" }, { \"The papaya tree grows some small yellow fruit.\" }, { \"The papaya tree grows larger.\" }, { \"The papaya tree is ready to be harvested.\" } }),\n PALM(5502, new String[][] { { \"The palm sapling has only just been planted.\" }, { \"The palm sapling grows a little larger.\" }, { \"The palm stump grows a little larger.\" }, { \"The palm tree grows a small canopy.\" }, { \"The palm tree grows taller.\" }, { \"The palm tree grows more leaves.\" }, { \"The palm tree is ready to be harvested.\" } });\n\n private int saplingId;\n\n private String[][] messages;\n\n private static Map saplings = new HashMap();\n\n static {\n for (InspectData data : InspectData.values()) {\n saplings.put(data.saplingId, data);\n }\n }\n\n InspectData(int saplingId, String[][] messages) {\n this.saplingId = saplingId;\n this.messages = messages;\n }\n\n public static InspectData forId(int saplingId) {\n return saplings.get(saplingId);\n }\n\n public int getSapplingId() {\n return saplingId;\n }\n\n public String[][] getMessages() {\n return messages;\n }\n }\n\n /* update all the patch states */\n public void updateFruitTreeStates() {\n // brimhaven - catherby - tree stronghold - tree village\n int[] configValues = new int[fruitTreeStages.length];\n int configValue;\n ", "post_mask_code": "\n configValue = (configValues[0] << 16) + (configValues[1] << 8 << 16) + configValues[2] + (configValues[3] << 8);\n player.getPacketSender().sendConfig(MAIN_FRUIT_TREE_CONFIG, configValue);\n }\n\n /* getting the different config values */\n public int getConfigValue(int fruitTreeStage, int saplingId, int plantState, int index) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(saplingId);\n switch(fruitTreeStage) {\n case // weed\n 0:\n return 0x00;\n case // weed cleared\n 1:\n return 0x01;\n case 2:\n return 0x02;\n case 3:\n return 0x03;\n }\n if (fruitTreeData == null) {\n return -1;\n }\n if (fruitTreeStage > fruitTreeData.getEndingState() - fruitTreeData.getStartingState() - 1) {\n hasFullyGrown[index] = true;\n }\n if (plantState == 6)\n return fruitTreeData.getStumpState();\n if (getPlantState(plantState, fruitTreeData, fruitTreeStage) == 3)\n return fruitTreeData.getCheckHealthState();\n return getPlantState(plantState, fruitTreeData, fruitTreeStage);\n }\n\n /* getting the plant states */\n public int getPlantState(int plantState, FruitTreeData fruitTreeData, int fruitTreeStage) {\n int value = fruitTreeData.getStartingState() + fruitTreeStage - 4;\n switch(plantState) {\n case 0:\n return value;\n case 1:\n return value + fruitTreeData.getDiseaseDiffValue();\n case 2:\n return value + fruitTreeData.getDeathDiffValue();\n case 3:\n return fruitTreeData.getCheckHealthState();\n }\n return -1;\n }\n\n /* calculating the disease chance and making the plant grow */\n public void doCalculations() {\n for (int i = 0; i < fruitTreeSaplings.length; i++) {\n if (fruitTreeStages[i] > 0 && fruitTreeStages[i] <= 3 && GameEngine.getMinutesCounter() - fruitTreeTimer[i] >= 5) {\n fruitTreeStages[i]--;\n fruitTreeTimer[i] = GameEngine.getMinutesCounter();\n updateFruitTreeStates();\n continue;\n }\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[i]);\n if (fruitTreeData == null) {\n continue;\n }\n long difference = GameEngine.getMinutesCounter() - fruitTreeTimer[i];\n long growth = fruitTreeData.getGrowthTime();\n int nbStates = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int state = (int) (difference * nbStates / growth);\n if (fruitTreeTimer[i] == 0 || fruitTreeState[i] == 2 || fruitTreeState[i] == 3 || (state > nbStates)) {\n continue;\n }\n if (4 + state != fruitTreeStages[i]) {\n if (fruitTreeStages[i] + fruitTreeData.getStartingState() == fruitTreeData.getLimitState() + 3) {\n fruitTreeStages[i] = fruitTreeData.getEndingState() - fruitTreeData.getStartingState() + 7;\n fruitTreeState[i] = 3;\n updateFruitTreeStates();\n continue;\n }\n fruitTreeStages[i] = 4 + state;\n if (fruitTreeStages[i] <= 4 + state)\n for (int j = fruitTreeStages[i]; j <= 4 + state; j++) doStateCalculation(i);\n updateFruitTreeStates();\n }\n }\n }\n\n /**\n * Woodcutting action\n *\n * @param = tree id\n * @param x\n * = tree x location\n * @param y\n * = tree y location\n * @return\n */\n public boolean cut(final int x, final int y) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(x, y);\n if (fruitTreeFieldsData == null)\n return false;\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null)\n return false;\n if (player.getItemAssistant().freeSlots() <= 0) {\n player.getPacketSender().sendMessage(\"Not enough space in your inventory.\");\n return true;\n }\n if (ChopTree.getAxe(player) == null) {\n return true;\n }\n player.getPacketSender().sendMessage(\"You swing your axe at the tree.\");\n final int emoteId = ChopTree.getAxe(player).getAnimation();\n player.startAnimation(emoteId);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.getPacketSender().sendMessage(\"You cut down the tree.\");\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 6;\n updateFruitTreeStates();\n container.stop();\n }\n\n @Override\n public void stop() {\n player.startAnimation(-1, 0);\n }\n }, 5);\n return true;\n }\n\n public void modifyStage(int i) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[i]);\n if (fruitTreeData == null)\n return;\n long difference = GameEngine.getMinutesCounter() - fruitTreeTimer[i];\n long growth = fruitTreeData.getGrowthTime();\n int nbStates = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int state = (int) (difference * nbStates / growth);\n fruitTreeStages[i] = 4 + state;\n updateFruitTreeStates();\n }\n\n /* calculations about the diseasing chance */\n public void doStateCalculation(int index) {\n if (fruitTreeState[index] == 2) {\n return;\n }\n // if the patch is diseased, it dies, if its watched by a farmer, it\n // goes back to normal\n if (fruitTreeState[index] == 1) {\n if (fruitTreeWatched[index]) {\n fruitTreeState[index] = 0;\n FruitTreeData bushesData = FruitTreeData.forId(fruitTreeSaplings[index]);\n if (bushesData == null)\n return;\n System.out.println(fruitTreeSaplings[index]);\n int difference = bushesData.getEndingState() - bushesData.getStartingState();\n int growth = bushesData.getGrowthTime();\n fruitTreeTimer[index] += (growth / difference);\n modifyStage(index);\n } else {\n fruitTreeState[index] = 2;\n }\n }\n if (fruitTreeState[index] == 5 && fruitTreeStages[index] != 2) {\n fruitTreeState[index] = 0;\n }\n if (fruitTreeState[index] == 0 && fruitTreeStages[index] >= 5 && !hasFullyGrown[index]) {\n FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[index]);\n if (fruitTreeData == null) {\n return;\n }\n double chance = diseaseChance[index] * fruitTreeData.getDiseaseChance();\n int maxChance = (int) chance * 100;\n if (Misc.random(100) <= maxChance) {\n fruitTreeState[index] = 1;\n }\n }\n }\n\n /* clearing the patch with a rake of a spade */\n public boolean clearPatch(int objectX, int objectY, int itemId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n int finalAnimation;\n int finalDelay;\n if (fruitTreeFieldsData == null || (itemId != FarmingConstants.RAKE && itemId != FarmingConstants.SPADE)) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] <= 3) {\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.RAKE)) {\n player.getDialogueHandler().sendStatement(\"You need a rake to clear this path.\");\n return true;\n } else {\n finalAnimation = FarmingConstants.RAKING_ANIM;\n finalDelay = 5;\n }\n } else {\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.SPADE)) {\n player.getDialogueHandler().sendStatement(\"You need a spade to clear this path.\");\n return true;\n } else {\n finalAnimation = FarmingConstants.SPADE_ANIM;\n finalDelay = 3;\n }\n }\n final int animation = finalAnimation;\n player.stopPlayer(true);\n player.startAnimation(animation);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.startAnimation(animation);\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] <= 2) {\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()]++;\n player.getItemAssistant().addItem(6055, 1);\n } else {\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] = 3;\n container.stop();\n }\n player.getPlayerAssistant().addSkillXP(CLEARING_EXPERIENCE, SkillConstants.FARMING.ordinal());\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n updateFruitTreeStates();\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n container.stop();\n return;\n }\n }\n\n @Override\n public void stop() {\n resetFruitTrees(fruitTreeFieldsData.getFruitTreeIndex());\n player.getPacketSender().sendMessage(\"You clear the patch.\");\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, finalDelay);\n return true;\n }\n\n /* planting the saplings */\n public boolean plantSapling(int objectX, int objectY, final int saplingId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n final FruitTreeData fruitTreeData = FruitTreeData.forId(saplingId);\n if (fruitTreeFieldsData == null || fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] != 3) {\n player.getPacketSender().sendMessage(\"You can't plant a sapling here.\");\n return true;\n }\n if (fruitTreeData.getLevelRequired() > player.playerLevel[SkillConstants.FARMING.ordinal()]) {\n player.getDialogueHandler().sendStatement(\"You need a farming level of \" + fruitTreeData.getLevelRequired() + \" to plant this sapling.\");\n return true;\n }\n if (!player.getItemAssistant().playerHasItem(FarmingConstants.TROWEL)) {\n player.getDialogueHandler().sendStatement(\"You need a trowel to plant the sapling here.\");\n return true;\n }\n player.startAnimation(FarmingConstants.PLANTING_POT_ANIM);\n fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] = 4;\n player.getItemAssistant().removeItem(saplingId, 1);\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()] = saplingId;\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getPlantingXp(), SkillConstants.FARMING.ordinal());\n container.stop();\n }\n\n @Override\n public void stop() {\n updateFruitTreeStates();\n player.stopPlayer(false);\n }\n }, 3);\n return true;\n }\n\n /* harvesting the plant resulted */\n public boolean harvestOrCheckHealth(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n System.out.println(fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] + fruitTreeData.getStartingState() + \" \" + (fruitTreeData.getLimitState() - 4));\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] + fruitTreeData.getStartingState() == fruitTreeData.getLimitState() + 4) {\n cut(objectX, objectY);\n return true;\n }\n if (player.getItemAssistant().freeSlots() <= 0) {\n player.getPacketSender().sendMessage(\"Not enough space in your inventory.\");\n return true;\n }\n player.startAnimation(832);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n if (player.getItemAssistant().freeSlots() <= 0) {\n container.stop();\n return;\n }\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getPacketSender().sendMessage(\"You examine the tree for signs of disease and find that it's in perfect health.\");\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getCheckHealthXp(), SkillConstants.FARMING.ordinal());\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n hasFullyGrown[fruitTreeFieldsData.getFruitTreeIndex()] = false;\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter() - fruitTreeData.getGrowthTime();\n modifyStage(fruitTreeFieldsData.getFruitTreeIndex());\n container.stop();\n return;\n }\n player.getPacketSender().sendMessage(\"You harvest the crop, and pick a fruit.\");\n player.getItemAssistant().addItem(fruitTreeData.getHarvestId(), 1);\n player.getPlayerAssistant().addSkillXP(fruitTreeData.getHarvestXp(), SkillConstants.FARMING.ordinal());\n fruitTreeTimer[fruitTreeFieldsData.getFruitTreeIndex()] = GameEngine.getMinutesCounter();\n int difference = fruitTreeData.getEndingState() - fruitTreeData.getStartingState();\n int growth = fruitTreeData.getGrowthTime();\n lowerStage(fruitTreeFieldsData.getFruitTreeIndex(), growth - (growth / difference) * (difference + 5 - fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()]));\n modifyStage(fruitTreeFieldsData.getFruitTreeIndex());\n container.stop();\n }\n\n @Override\n public void stop() {\n // TODO Auto-generated method stub\n }\n }, 2);\n return true;\n }\n\n /* lowering the stage */\n public void lowerStage(int index, int timer) {\n hasFullyGrown[index] = false;\n fruitTreeTimer[index] -= timer;\n }\n\n /* putting compost onto the plant */\n public boolean putCompost(int objectX, int objectY, final int itemId) {\n if (itemId != 6032 && itemId != 6034) {\n return false;\n }\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] != 3 || fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 5) {\n player.getPacketSender().sendMessage(\"This patch doesn't need compost.\");\n return true;\n }\n player.getItemAssistant().removeItem(itemId, 1);\n player.getItemAssistant().addItem(1925, 1);\n player.getPacketSender().sendMessage(\"You pour some \" + (itemId == 6034 ? \"super\" : \"\") + \"compost on the patch.\");\n player.startAnimation(FarmingConstants.PUTTING_COMPOST);\n player.getPlayerAssistant().addSkillXP(itemId == 6034 ? Compost.SUPER_COMPOST_EXP_USE : Compost.COMPOST_EXP_USE, SkillConstants.FARMING.ordinal());\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n diseaseChance[fruitTreeFieldsData.getFruitTreeIndex()] *= itemId == 6032 ? COMPOST_CHANCE : SUPERCOMPOST_CHANCE;\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 5;\n container.stop();\n }\n\n @Override\n public void stop() {\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, 7);\n return true;\n }\n\n /* inspecting a plant */\n public boolean inspect(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n final InspectData inspectData = InspectData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 1) {\n player.getDialogueHandler().sendStatement(\"This plant is diseased. Use a plant cure on it to cure it, \", \"or clear the patch with a spade.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 2) {\n player.getDialogueHandler().sendStatement(\"This plant is dead. You did not cure it while it was diseased.\", \"Clear the patch with a spade.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getDialogueHandler().sendStatement(\"This plant has fully grown. You can check it's health\", \"to gain some farming experiences.\");\n return true;\n } else if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] == 6) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree stump, to remove it, use a \", \"spade on it to clear the patch\");\n return true;\n }\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 0) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree patch. The soil has not been treated.\", \"The patch needs weeding.\");\n } else if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3) {\n player.getDialogueHandler().sendStatement(\"This is a fruit tree patch. The soil has not been treated.\", \"The patch is empty and weeded.\");\n } else if (inspectData != null && fruitTreeData != null) {\n player.getPacketSender().sendMessage(\"You bend down and start to inspect the patch...\");\n player.startAnimation(1331);\n player.stopPlayer(true);\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] - 4 < inspectData.getMessages().length - 2) {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] - 4]);\n } else if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] < fruitTreeData.getEndingState() - fruitTreeData.getStartingState() + 2) {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[inspectData.getMessages().length - 2]);\n } else {\n player.getDialogueHandler().sendStatement(inspectData.getMessages()[inspectData.getMessages().length - 1]);\n }\n container.stop();\n }\n\n @Override\n public void stop() {\n player.startAnimation(1332);\n player.stopPlayer(false);\n }\n }, 5);\n }\n return true;\n }\n\n /* opening the corresponding guide about the patch */\n public boolean guide(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n player.getSkillInterfaces().farmingComplex(4);\n player.getSkillInterfaces().selected = 20;\n return true;\n }\n\n /* Curing the plant */\n public boolean pruneArea(int objectX, int objectY, int itemId) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null || (itemId != FarmingConstants.SECATEURS && itemId != FarmingConstants.MAGIC_SECATEURS)) {\n return false;\n }\n final FruitTreeData fruitTreeData = FruitTreeData.forId(fruitTreeSaplings[fruitTreeFieldsData.getFruitTreeIndex()]);\n if (fruitTreeData == null) {\n return false;\n }\n if (!SkillConstants.getEnabled(SkillConstants.FARMING.ordinal())) {\n player.getPacketSender().sendMessage(\"This skill is currently disabled.\");\n return true;\n }\n if (fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] != 1) {\n player.getPacketSender().sendMessage(\"This area doesn't need to be pruned.\");\n return true;\n }\n player.startAnimation(FarmingConstants.PRUNING_ANIM);\n player.stopPlayer(true);\n fruitTreeState[fruitTreeFieldsData.getFruitTreeIndex()] = 0;\n CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() {\n\n @Override\n public void execute(CycleEventContainer container) {\n player.getPacketSender().sendMessage(\"You prune the area with your secateurs.\");\n container.stop();\n }\n\n @Override\n public void stop() {\n updateFruitTreeStates();\n player.stopPlayer(false);\n player.getPlayerAssistant().resetAnimation();\n }\n }, 15);\n return true;\n }\n\n private void resetFruitTrees(int index) {\n fruitTreeSaplings[index] = 0;\n fruitTreeState[index] = 0;\n diseaseChance[index] = 1;\n hasFullyGrown[index] = false;\n fruitTreeWatched[index] = false;\n }\n\n /* checking if the patch is raked */\n public boolean checkIfRaked(int objectX, int objectY) {\n final FruitTreeFieldsData fruitTreeFieldsData = FruitTreeFieldsData.forIdPosition(objectX, objectY);\n if (fruitTreeFieldsData == null)\n return false;\n if (fruitTreeStages[fruitTreeFieldsData.getFruitTreeIndex()] == 3)\n return true;\n return false;\n }\n}\n"} {"task_id": "Java_2274", "language": "Java", "task_type": "method_signature", "source_file": "java/github/owlcs/owlapi/api/src/main/java/org/semanticweb/owlapi/profiles/violations/UseOfNonEquivalentClassExpression.java", "mask_start_position": 1204, "mask_end_position": 1289, "canonical_solution": "@Override\n public Optional accept(OWLProfileViolationVisitorEx visitor) ", "pre_mask_code": "/* This file is part of the OWL API.\n *\n */\npackage org.semanticweb.owlapi.profiles.violations;\n\nimport java.util.Optional;\nimport org.semanticweb.owlapi.model.OWLAxiom;\nimport org.semanticweb.owlapi.model.OWLClassExpression;\nimport org.semanticweb.owlapi.model.OWLOntology;\nimport org.semanticweb.owlapi.profiles.OWLProfileViolation;\nimport org.semanticweb.owlapi.profiles.OWLProfileViolationVisitor;\nimport org.semanticweb.owlapi.profiles.OWLProfileViolationVisitorEx;\n\n/**\n * @author Matthew Horridge, The University of Manchester, Information Management Group\n */\npublic class UseOfNonEquivalentClassExpression extends OWLProfileViolation {\n\n /**\n * @param ontology ontology\n * @param axiom axiom\n * @param classExpression class expression\n */\n public UseOfNonEquivalentClassExpression(OWLOntology ontology, OWLAxiom axiom, OWLClassExpression classExpression) {\n super(ontology, axiom, classExpression);\n }\n\n @Override\n public OWLClassExpression getExpression() {\n return (OWLClassExpression) super.getExpression();\n }\n\n @Override\n public void accept(OWLProfileViolationVisitor visitor) {\n visitor.visit(this);\n }\n\n ", "post_mask_code": "{\n return visitor.visit(this);\n }\n\n @Override\n public String toString() {\n return toString(\"Use of non-equivalent class expression in position that requires an equivalent class expression: %s\", getExpression());\n }\n}\n"} {"task_id": "Java_2275", "language": "Java", "task_type": "method_body", "source_file": "java/github/owlcs/owlapi/api/src/main/java/org/semanticweb/owlapi/profiles/violations/UseOfNonEquivalentClassExpression.java", "mask_start_position": 1377, "mask_end_position": 1529, "canonical_solution": "{\n return toString(\"Use of non-equivalent class expression in position that requires an equivalent class expression: %s\", getExpression());\n }", "pre_mask_code": "/* This file is part of the OWL API.\n *\n */\npackage org.semanticweb.owlapi.profiles.violations;\n\nimport java.util.Optional;\nimport org.semanticweb.owlapi.model.OWLAxiom;\nimport org.semanticweb.owlapi.model.OWLClassExpression;\nimport org.semanticweb.owlapi.model.OWLOntology;\nimport org.semanticweb.owlapi.profiles.OWLProfileViolation;\nimport org.semanticweb.owlapi.profiles.OWLProfileViolationVisitor;\nimport org.semanticweb.owlapi.profiles.OWLProfileViolationVisitorEx;\n\n/**\n * @author Matthew Horridge, The University of Manchester, Information Management Group\n */\npublic class UseOfNonEquivalentClassExpression extends OWLProfileViolation {\n\n /**\n * @param ontology ontology\n * @param axiom axiom\n * @param classExpression class expression\n */\n public UseOfNonEquivalentClassExpression(OWLOntology ontology, OWLAxiom axiom, OWLClassExpression classExpression) {\n super(ontology, axiom, classExpression);\n }\n\n @Override\n public OWLClassExpression getExpression() {\n return (OWLClassExpression) super.getExpression();\n }\n\n @Override\n public void accept(OWLProfileViolationVisitor visitor) {\n visitor.visit(this);\n }\n\n @Override\n public Optional accept(OWLProfileViolationVisitorEx visitor) {\n return visitor.visit(this);\n }\n\n @Override\n public String toString() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2276", "language": "Java", "task_type": "single_line", "source_file": "java/github/owlcs/owlapi/api/src/main/java/org/semanticweb/owlapi/profiles/violations/UseOfNonEquivalentClassExpression.java", "mask_start_position": 1061, "mask_end_position": 1081, "canonical_solution": "per.getExpression();", "pre_mask_code": "/* This file is part of the OWL API.\n *\n */\npackage org.semanticweb.owlapi.profiles.violations;\n\nimport java.util.Optional;\nimport org.semanticweb.owlapi.model.OWLAxiom;\nimport org.semanticweb.owlapi.model.OWLClassExpression;\nimport org.semanticweb.owlapi.model.OWLOntology;\nimport org.semanticweb.owlapi.profiles.OWLProfileViolation;\nimport org.semanticweb.owlapi.profiles.OWLProfileViolationVisitor;\nimport org.semanticweb.owlapi.profiles.OWLProfileViolationVisitorEx;\n\n/**\n * @author Matthew Horridge, The University of Manchester, Information Management Group\n */\npublic class UseOfNonEquivalentClassExpression extends OWLProfileViolation {\n\n /**\n * @param ontology ontology\n * @param axiom axiom\n * @param classExpression class expression\n */\n public UseOfNonEquivalentClassExpression(OWLOntology ontology, OWLAxiom axiom, OWLClassExpression classExpression) {\n super(ontology, axiom, classExpression);\n }\n\n @Override\n public OWLClassExpression getExpression() {\n return (OWLClassExpression) su", "post_mask_code": "\n }\n\n @Override\n public void accept(OWLProfileViolationVisitor visitor) {\n visitor.visit(this);\n }\n\n @Override\n public Optional accept(OWLProfileViolationVisitorEx visitor) {\n return visitor.visit(this);\n }\n\n @Override\n public String toString() {\n return toString(\"Use of non-equivalent class expression in position that requires an equivalent class expression: %s\", getExpression());\n }\n}\n"} {"task_id": "Java_2277", "language": "Java", "task_type": "method_signature", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/plugin/backup/movemodel/g.java", "mask_start_position": 881, "mask_end_position": 913, "canonical_solution": "public static ArrayList Wj() ", "pre_mask_code": "package com.tencent.mm.plugin.backup.movemodel;\n\nimport com.tencent.mm.plugin.backup.movemodel.b.c;\nimport com.tencent.mm.sdk.platformtools.ah;\nimport com.tencent.mm.sdk.platformtools.v;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic final class g implements c {\n\n private static ArrayList eaA = null;\n\n private static ArrayList eaw = new ArrayList();\n\n private static boolean eay = false;\n\n private static List efQ = null;\n\n public b egg;\n\n public c ekX;\n\n public ah ekY;\n\n public Object lock = new Object();\n\n public static ArrayList Tu() {\n return eaw;\n }\n\n public static void Y(List list) {\n efQ = list;\n }\n\n public static List Wi() {\n return efQ;\n }\n\n public static void q(ArrayList arrayList) {\n eaA = arrayList;\n }\n\n ", "post_mask_code": "{\n return eaA;\n }\n\n public static boolean Wk() {\n return eay;\n }\n\n public final void a(long j, long j2, ArrayList arrayList, boolean z) {\n v.i(\"MicroMsg.BakMoveChooseServer\", \"onCalcuChooseProgress progress:%d, converSize%d\", Long.valueOf(j), Long.valueOf(j2));\n if (z) {\n eaw = (ArrayList) arrayList.clone();\n }\n if (this.ekX != null) {\n this.ekX.a(j, j2, arrayList, z);\n }\n }\n\n public final void p(ArrayList arrayList) {\n Collections.sort(arrayList);\n eaw = (ArrayList) arrayList.clone();\n eay = true;\n if (this.ekX != null) {\n this.ekX.p(arrayList);\n }\n }\n}\n"} {"task_id": "Java_2278", "language": "Java", "task_type": "method_body", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/plugin/backup/movemodel/g.java", "mask_start_position": 843, "mask_end_position": 875, "canonical_solution": "{\n eaA = arrayList;\n }", "pre_mask_code": "package com.tencent.mm.plugin.backup.movemodel;\n\nimport com.tencent.mm.plugin.backup.movemodel.b.c;\nimport com.tencent.mm.sdk.platformtools.ah;\nimport com.tencent.mm.sdk.platformtools.v;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic final class g implements c {\n\n private static ArrayList eaA = null;\n\n private static ArrayList eaw = new ArrayList();\n\n private static boolean eay = false;\n\n private static List efQ = null;\n\n public b egg;\n\n public c ekX;\n\n public ah ekY;\n\n public Object lock = new Object();\n\n public static ArrayList Tu() {\n return eaw;\n }\n\n public static void Y(List list) {\n efQ = list;\n }\n\n public static List Wi() {\n return efQ;\n }\n\n public static void q(ArrayList arrayList) ", "post_mask_code": "\n\n public static ArrayList Wj() {\n return eaA;\n }\n\n public static boolean Wk() {\n return eay;\n }\n\n public final void a(long j, long j2, ArrayList arrayList, boolean z) {\n v.i(\"MicroMsg.BakMoveChooseServer\", \"onCalcuChooseProgress progress:%d, converSize%d\", Long.valueOf(j), Long.valueOf(j2));\n if (z) {\n eaw = (ArrayList) arrayList.clone();\n }\n if (this.ekX != null) {\n this.ekX.a(j, j2, arrayList, z);\n }\n }\n\n public final void p(ArrayList arrayList) {\n Collections.sort(arrayList);\n eaw = (ArrayList) arrayList.clone();\n eay = true;\n if (this.ekX != null) {\n this.ekX.p(arrayList);\n }\n }\n}\n"} {"task_id": "Java_2279", "language": "Java", "task_type": "single_line", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/plugin/backup/movemodel/g.java", "mask_start_position": 925, "mask_end_position": 934, "canonical_solution": "turn eaA;", "pre_mask_code": "package com.tencent.mm.plugin.backup.movemodel;\n\nimport com.tencent.mm.plugin.backup.movemodel.b.c;\nimport com.tencent.mm.sdk.platformtools.ah;\nimport com.tencent.mm.sdk.platformtools.v;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic final class g implements c {\n\n private static ArrayList eaA = null;\n\n private static ArrayList eaw = new ArrayList();\n\n private static boolean eay = false;\n\n private static List efQ = null;\n\n public b egg;\n\n public c ekX;\n\n public ah ekY;\n\n public Object lock = new Object();\n\n public static ArrayList Tu() {\n return eaw;\n }\n\n public static void Y(List list) {\n efQ = list;\n }\n\n public static List Wi() {\n return efQ;\n }\n\n public static void q(ArrayList arrayList) {\n eaA = arrayList;\n }\n\n public static ArrayList Wj() {\n re", "post_mask_code": "\n }\n\n public static boolean Wk() {\n return eay;\n }\n\n public final void a(long j, long j2, ArrayList arrayList, boolean z) {\n v.i(\"MicroMsg.BakMoveChooseServer\", \"onCalcuChooseProgress progress:%d, converSize%d\", Long.valueOf(j), Long.valueOf(j2));\n if (z) {\n eaw = (ArrayList) arrayList.clone();\n }\n if (this.ekX != null) {\n this.ekX.a(j, j2, arrayList, z);\n }\n }\n\n public final void p(ArrayList arrayList) {\n Collections.sort(arrayList);\n eaw = (ArrayList) arrayList.clone();\n eay = true;\n if (this.ekX != null) {\n this.ekX.p(arrayList);\n }\n }\n}\n"} {"task_id": "Java_2280", "language": "Java", "task_type": "method_signature", "source_file": "java/github/kreativekorp/openxion/main/java/OpenXION/src/com/kreative/openxion/ast/XNConstantDeclaration.java", "mask_start_position": 430, "mask_end_position": 471, "canonical_solution": "protected String toString(String indent) ", "pre_mask_code": "/*\n *

\n * @since OpenXION 0.9\n * @author Rebecca G. Bettencourt, Kreative Software\n */\npackage com.kreative.openxion.ast;\n\npublic class XNConstantDeclaration extends XNStatement {\n\n private static final long serialVersionUID = 101L;\n\n public String identifier;\n\n public XNExpression value;\n\n public XNConstantDeclaration(String id, XNExpression v) {\n this.identifier = id;\n this.value = v;\n }\n\n ", "post_mask_code": "{\n return indent + \"const \" + identifier + \" = \" + value.toString();\n }\n}\n"} {"task_id": "Java_2281", "language": "Java", "task_type": "method_body", "source_file": "java/github/kreativekorp/openxion/main/java/OpenXION/src/com/kreative/openxion/ast/XNConstantDeclaration.java", "mask_start_position": 471, "mask_end_position": 552, "canonical_solution": "{\n return indent + \"const \" + identifier + \" = \" + value.toString();\n }", "pre_mask_code": "/*\n *

\n * @since OpenXION 0.9\n * @author Rebecca G. Bettencourt, Kreative Software\n */\npackage com.kreative.openxion.ast;\n\npublic class XNConstantDeclaration extends XNStatement {\n\n private static final long serialVersionUID = 101L;\n\n public String identifier;\n\n public XNExpression value;\n\n public XNConstantDeclaration(String id, XNExpression v) {\n this.identifier = id;\n this.value = v;\n }\n\n protected String toString(String indent) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2282", "language": "Java", "task_type": "single_line", "source_file": "java/github/kreativekorp/openxion/main/java/OpenXION/src/com/kreative/openxion/ast/XNConstantDeclaration.java", "mask_start_position": 515, "mask_end_position": 546, "canonical_solution": "ier + \" = \" + value.toString();", "pre_mask_code": "/*\n *

\n * @since OpenXION 0.9\n * @author Rebecca G. Bettencourt, Kreative Software\n */\npackage com.kreative.openxion.ast;\n\npublic class XNConstantDeclaration extends XNStatement {\n\n private static final long serialVersionUID = 101L;\n\n public String identifier;\n\n public XNExpression value;\n\n public XNConstantDeclaration(String id, XNExpression v) {\n this.identifier = id;\n this.value = v;\n }\n\n protected String toString(String indent) {\n return indent + \"const \" + identif", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2283", "language": "Java", "task_type": "method_signature", "source_file": "java/github/protegeproject/webprotege/webprotege-server-core/src/main/java/edu/stanford/bmir/protege/web/server/crud/SetEntityCrudKitSettingsActionHandler.java", "mask_start_position": 2539, "mask_end_position": 2665, "canonical_solution": "@Nullable\n @Override\n protected BuiltInAction getRequiredExecutableBuiltInAction(SetEntityCrudKitSettingsAction action) ", "pre_mask_code": "package edu.stanford.bmir.protege.web.server.crud;\n\nimport edu.stanford.bmir.protege.web.server.access.AccessManager;\nimport edu.stanford.bmir.protege.web.server.change.FindAndReplaceIRIPrefixChangeGeneratorFactory;\nimport edu.stanford.bmir.protege.web.server.change.HasApplyChanges;\nimport edu.stanford.bmir.protege.web.server.crud.persistence.ProjectEntityCrudKitSettings;\nimport edu.stanford.bmir.protege.web.server.crud.persistence.ProjectEntityCrudKitSettingsRepository;\nimport edu.stanford.bmir.protege.web.server.dispatch.AbstractProjectActionHandler;\nimport edu.stanford.bmir.protege.web.server.dispatch.ExecutionContext;\nimport edu.stanford.bmir.protege.web.shared.access.BuiltInAction;\nimport edu.stanford.bmir.protege.web.shared.crud.IRIPrefixUpdateStrategy;\nimport edu.stanford.bmir.protege.web.shared.crud.SetEntityCrudKitSettingsAction;\nimport edu.stanford.bmir.protege.web.shared.crud.SetEntityCrudKitSettingsResult;\nimport edu.stanford.bmir.protege.web.shared.project.ProjectId;\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\nimport javax.inject.Inject;\nimport static edu.stanford.bmir.protege.web.shared.access.BuiltInAction.EDIT_NEW_ENTITY_SETTINGS;\n\n/**\n * Author: Matthew Horridge
\n * Stanford University
\n * Bio-Medical Informatics Research Group
\n * Date: 8/19/13\n */\npublic class SetEntityCrudKitSettingsActionHandler extends AbstractProjectActionHandler {\n\n @Nonnull\n private final ProjectId projectId;\n\n @Nonnull\n private final ProjectEntityCrudKitSettingsRepository repository;\n\n @Nonnull\n private final HasApplyChanges changeManager;\n\n @Nonnull\n private final FindAndReplaceIRIPrefixChangeGeneratorFactory findAndReplaceIRIPrefixChangeGeneratorFactory;\n\n @Inject\n public SetEntityCrudKitSettingsActionHandler(@Nonnull AccessManager accessManager, @Nonnull ProjectId projectId, @Nonnull ProjectEntityCrudKitSettingsRepository repository, @Nonnull HasApplyChanges changeManager, @Nonnull FindAndReplaceIRIPrefixChangeGeneratorFactory findAndReplaceIRIPrefixChangeGeneratorFactory) {\n super(accessManager);\n this.projectId = projectId;\n this.repository = repository;\n this.changeManager = changeManager;\n this.findAndReplaceIRIPrefixChangeGeneratorFactory = findAndReplaceIRIPrefixChangeGeneratorFactory;\n }\n\n @Nonnull\n public Class getActionClass() {\n return SetEntityCrudKitSettingsAction.class;\n }\n\n ", "post_mask_code": "{\n return EDIT_NEW_ENTITY_SETTINGS;\n }\n\n @Nonnull\n @Override\n public SetEntityCrudKitSettingsResult execute(@Nonnull SetEntityCrudKitSettingsAction action, @Nonnull ExecutionContext executionContext) {\n var projectSettings = ProjectEntityCrudKitSettings.get(projectId, action.getToSettings());\n repository.save(projectSettings);\n if (action.getPrefixUpdateStrategy() == IRIPrefixUpdateStrategy.FIND_AND_REPLACE) {\n var fromPrefix = action.getFromSettings().getPrefixSettings().getIRIPrefix();\n var toPrefix = action.getToSettings().getPrefixSettings().getIRIPrefix();\n var changeGenerator = findAndReplaceIRIPrefixChangeGeneratorFactory.create(fromPrefix, toPrefix);\n changeManager.applyChanges(executionContext.getUserId(), changeGenerator);\n }\n return new SetEntityCrudKitSettingsResult();\n }\n}\n"} {"task_id": "Java_2284", "language": "Java", "task_type": "method_body", "source_file": "java/github/protegeproject/webprotege/webprotege-server-core/src/main/java/edu/stanford/bmir/protege/web/server/crud/SetEntityCrudKitSettingsActionHandler.java", "mask_start_position": 2665, "mask_end_position": 2713, "canonical_solution": "{\n return EDIT_NEW_ENTITY_SETTINGS;\n }", "pre_mask_code": "package edu.stanford.bmir.protege.web.server.crud;\n\nimport edu.stanford.bmir.protege.web.server.access.AccessManager;\nimport edu.stanford.bmir.protege.web.server.change.FindAndReplaceIRIPrefixChangeGeneratorFactory;\nimport edu.stanford.bmir.protege.web.server.change.HasApplyChanges;\nimport edu.stanford.bmir.protege.web.server.crud.persistence.ProjectEntityCrudKitSettings;\nimport edu.stanford.bmir.protege.web.server.crud.persistence.ProjectEntityCrudKitSettingsRepository;\nimport edu.stanford.bmir.protege.web.server.dispatch.AbstractProjectActionHandler;\nimport edu.stanford.bmir.protege.web.server.dispatch.ExecutionContext;\nimport edu.stanford.bmir.protege.web.shared.access.BuiltInAction;\nimport edu.stanford.bmir.protege.web.shared.crud.IRIPrefixUpdateStrategy;\nimport edu.stanford.bmir.protege.web.shared.crud.SetEntityCrudKitSettingsAction;\nimport edu.stanford.bmir.protege.web.shared.crud.SetEntityCrudKitSettingsResult;\nimport edu.stanford.bmir.protege.web.shared.project.ProjectId;\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\nimport javax.inject.Inject;\nimport static edu.stanford.bmir.protege.web.shared.access.BuiltInAction.EDIT_NEW_ENTITY_SETTINGS;\n\n/**\n * Author: Matthew Horridge
\n * Stanford University
\n * Bio-Medical Informatics Research Group
\n * Date: 8/19/13\n */\npublic class SetEntityCrudKitSettingsActionHandler extends AbstractProjectActionHandler {\n\n @Nonnull\n private final ProjectId projectId;\n\n @Nonnull\n private final ProjectEntityCrudKitSettingsRepository repository;\n\n @Nonnull\n private final HasApplyChanges changeManager;\n\n @Nonnull\n private final FindAndReplaceIRIPrefixChangeGeneratorFactory findAndReplaceIRIPrefixChangeGeneratorFactory;\n\n @Inject\n public SetEntityCrudKitSettingsActionHandler(@Nonnull AccessManager accessManager, @Nonnull ProjectId projectId, @Nonnull ProjectEntityCrudKitSettingsRepository repository, @Nonnull HasApplyChanges changeManager, @Nonnull FindAndReplaceIRIPrefixChangeGeneratorFactory findAndReplaceIRIPrefixChangeGeneratorFactory) {\n super(accessManager);\n this.projectId = projectId;\n this.repository = repository;\n this.changeManager = changeManager;\n this.findAndReplaceIRIPrefixChangeGeneratorFactory = findAndReplaceIRIPrefixChangeGeneratorFactory;\n }\n\n @Nonnull\n public Class getActionClass() {\n return SetEntityCrudKitSettingsAction.class;\n }\n\n @Nullable\n @Override\n protected BuiltInAction getRequiredExecutableBuiltInAction(SetEntityCrudKitSettingsAction action) ", "post_mask_code": "\n\n @Nonnull\n @Override\n public SetEntityCrudKitSettingsResult execute(@Nonnull SetEntityCrudKitSettingsAction action, @Nonnull ExecutionContext executionContext) {\n var projectSettings = ProjectEntityCrudKitSettings.get(projectId, action.getToSettings());\n repository.save(projectSettings);\n if (action.getPrefixUpdateStrategy() == IRIPrefixUpdateStrategy.FIND_AND_REPLACE) {\n var fromPrefix = action.getFromSettings().getPrefixSettings().getIRIPrefix();\n var toPrefix = action.getToSettings().getPrefixSettings().getIRIPrefix();\n var changeGenerator = findAndReplaceIRIPrefixChangeGeneratorFactory.create(fromPrefix, toPrefix);\n changeManager.applyChanges(executionContext.getUserId(), changeGenerator);\n }\n return new SetEntityCrudKitSettingsResult();\n }\n}\n"} {"task_id": "Java_2285", "language": "Java", "task_type": "single_line", "source_file": "java/github/protegeproject/webprotege/webprotege-server-core/src/main/java/edu/stanford/bmir/protege/web/server/crud/SetEntityCrudKitSettingsActionHandler.java", "mask_start_position": 2675, "mask_end_position": 2707, "canonical_solution": "return EDIT_NEW_ENTITY_SETTINGS;", "pre_mask_code": "package edu.stanford.bmir.protege.web.server.crud;\n\nimport edu.stanford.bmir.protege.web.server.access.AccessManager;\nimport edu.stanford.bmir.protege.web.server.change.FindAndReplaceIRIPrefixChangeGeneratorFactory;\nimport edu.stanford.bmir.protege.web.server.change.HasApplyChanges;\nimport edu.stanford.bmir.protege.web.server.crud.persistence.ProjectEntityCrudKitSettings;\nimport edu.stanford.bmir.protege.web.server.crud.persistence.ProjectEntityCrudKitSettingsRepository;\nimport edu.stanford.bmir.protege.web.server.dispatch.AbstractProjectActionHandler;\nimport edu.stanford.bmir.protege.web.server.dispatch.ExecutionContext;\nimport edu.stanford.bmir.protege.web.shared.access.BuiltInAction;\nimport edu.stanford.bmir.protege.web.shared.crud.IRIPrefixUpdateStrategy;\nimport edu.stanford.bmir.protege.web.shared.crud.SetEntityCrudKitSettingsAction;\nimport edu.stanford.bmir.protege.web.shared.crud.SetEntityCrudKitSettingsResult;\nimport edu.stanford.bmir.protege.web.shared.project.ProjectId;\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\nimport javax.inject.Inject;\nimport static edu.stanford.bmir.protege.web.shared.access.BuiltInAction.EDIT_NEW_ENTITY_SETTINGS;\n\n/**\n * Author: Matthew Horridge
\n * Stanford University
\n * Bio-Medical Informatics Research Group
\n * Date: 8/19/13\n */\npublic class SetEntityCrudKitSettingsActionHandler extends AbstractProjectActionHandler {\n\n @Nonnull\n private final ProjectId projectId;\n\n @Nonnull\n private final ProjectEntityCrudKitSettingsRepository repository;\n\n @Nonnull\n private final HasApplyChanges changeManager;\n\n @Nonnull\n private final FindAndReplaceIRIPrefixChangeGeneratorFactory findAndReplaceIRIPrefixChangeGeneratorFactory;\n\n @Inject\n public SetEntityCrudKitSettingsActionHandler(@Nonnull AccessManager accessManager, @Nonnull ProjectId projectId, @Nonnull ProjectEntityCrudKitSettingsRepository repository, @Nonnull HasApplyChanges changeManager, @Nonnull FindAndReplaceIRIPrefixChangeGeneratorFactory findAndReplaceIRIPrefixChangeGeneratorFactory) {\n super(accessManager);\n this.projectId = projectId;\n this.repository = repository;\n this.changeManager = changeManager;\n this.findAndReplaceIRIPrefixChangeGeneratorFactory = findAndReplaceIRIPrefixChangeGeneratorFactory;\n }\n\n @Nonnull\n public Class getActionClass() {\n return SetEntityCrudKitSettingsAction.class;\n }\n\n @Nullable\n @Override\n protected BuiltInAction getRequiredExecutableBuiltInAction(SetEntityCrudKitSettingsAction action) {\n ", "post_mask_code": "\n }\n\n @Nonnull\n @Override\n public SetEntityCrudKitSettingsResult execute(@Nonnull SetEntityCrudKitSettingsAction action, @Nonnull ExecutionContext executionContext) {\n var projectSettings = ProjectEntityCrudKitSettings.get(projectId, action.getToSettings());\n repository.save(projectSettings);\n if (action.getPrefixUpdateStrategy() == IRIPrefixUpdateStrategy.FIND_AND_REPLACE) {\n var fromPrefix = action.getFromSettings().getPrefixSettings().getIRIPrefix();\n var toPrefix = action.getToSettings().getPrefixSettings().getIRIPrefix();\n var changeGenerator = findAndReplaceIRIPrefixChangeGeneratorFactory.create(fromPrefix, toPrefix);\n changeManager.applyChanges(executionContext.getUserId(), changeGenerator);\n }\n return new SetEntityCrudKitSettingsResult();\n }\n}\n"} {"task_id": "Java_2286", "language": "Java", "task_type": "method_signature", "source_file": "java/github/micronaut-projects/micronaut-core/runtime/src/main/java/io/micronaut/health/HeartbeatTask.java", "mask_start_position": 1767, "mask_end_position": 1837, "canonical_solution": "@Override\n public void onApplicationEvent(ServiceReadyEvent event) ", "pre_mask_code": "package io.micronaut.health;\n\nimport io.micronaut.context.event.ApplicationEventListener;\nimport io.micronaut.context.event.ApplicationEventPublisher;\nimport io.micronaut.discovery.ServiceInstance;\nimport io.micronaut.discovery.event.ServiceReadyEvent;\nimport io.micronaut.scheduling.annotation.Scheduled;\nimport jakarta.inject.Singleton;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/**\n * A scheduled task that sends a periodic heartbeat whilst the server is active.\n *\n * @author graemerocher\n * @since 1.0\n */\n@Singleton\n@HeartbeatEnabled\npublic class HeartbeatTask implements ApplicationEventListener {\n\n private final Set eventsReference = ConcurrentHashMap.newKeySet();\n\n private final ApplicationEventPublisher eventPublisher;\n\n private final CurrentHealthStatus currentHealthStatus;\n\n /**\n * @param eventPublisher To publish the events related to heartbeat\n * @param configuration The configurations for heartbeat\n * @param currentHealthStatus The current status of health indicator\n */\n public HeartbeatTask(ApplicationEventPublisher eventPublisher, HeartbeatConfiguration configuration, CurrentHealthStatus currentHealthStatus) {\n this.eventPublisher = eventPublisher;\n this.currentHealthStatus = currentHealthStatus;\n }\n\n /**\n * Publish the heartbeat event with current health status.\n */\n @Scheduled(fixedDelay = \"${micronaut.heartbeat.interval:15s}\", initialDelay = \"${micronaut.heartbeat.initial-delay:5s}\")\n public void pulsate() {\n for (ServiceInstance instance : eventsReference) {\n eventPublisher.publishEvent(new HeartbeatEvent(instance, currentHealthStatus.current()));\n }\n }\n\n ", "post_mask_code": "{\n eventsReference.add(event.getSource());\n }\n}\n"} {"task_id": "Java_2287", "language": "Java", "task_type": "method_body", "source_file": "java/github/micronaut-projects/micronaut-core/runtime/src/main/java/io/micronaut/health/HeartbeatTask.java", "mask_start_position": 1837, "mask_end_position": 1892, "canonical_solution": "{\n eventsReference.add(event.getSource());\n }", "pre_mask_code": "package io.micronaut.health;\n\nimport io.micronaut.context.event.ApplicationEventListener;\nimport io.micronaut.context.event.ApplicationEventPublisher;\nimport io.micronaut.discovery.ServiceInstance;\nimport io.micronaut.discovery.event.ServiceReadyEvent;\nimport io.micronaut.scheduling.annotation.Scheduled;\nimport jakarta.inject.Singleton;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/**\n * A scheduled task that sends a periodic heartbeat whilst the server is active.\n *\n * @author graemerocher\n * @since 1.0\n */\n@Singleton\n@HeartbeatEnabled\npublic class HeartbeatTask implements ApplicationEventListener {\n\n private final Set eventsReference = ConcurrentHashMap.newKeySet();\n\n private final ApplicationEventPublisher eventPublisher;\n\n private final CurrentHealthStatus currentHealthStatus;\n\n /**\n * @param eventPublisher To publish the events related to heartbeat\n * @param configuration The configurations for heartbeat\n * @param currentHealthStatus The current status of health indicator\n */\n public HeartbeatTask(ApplicationEventPublisher eventPublisher, HeartbeatConfiguration configuration, CurrentHealthStatus currentHealthStatus) {\n this.eventPublisher = eventPublisher;\n this.currentHealthStatus = currentHealthStatus;\n }\n\n /**\n * Publish the heartbeat event with current health status.\n */\n @Scheduled(fixedDelay = \"${micronaut.heartbeat.interval:15s}\", initialDelay = \"${micronaut.heartbeat.initial-delay:5s}\")\n public void pulsate() {\n for (ServiceInstance instance : eventsReference) {\n eventPublisher.publishEvent(new HeartbeatEvent(instance, currentHealthStatus.current()));\n }\n }\n\n @Override\n public void onApplicationEvent(ServiceReadyEvent event) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2288", "language": "Java", "task_type": "single_line", "source_file": "java/github/micronaut-projects/micronaut-core/runtime/src/main/java/io/micronaut/health/HeartbeatTask.java", "mask_start_position": 1875, "mask_end_position": 1886, "canonical_solution": "tSource());", "pre_mask_code": "package io.micronaut.health;\n\nimport io.micronaut.context.event.ApplicationEventListener;\nimport io.micronaut.context.event.ApplicationEventPublisher;\nimport io.micronaut.discovery.ServiceInstance;\nimport io.micronaut.discovery.event.ServiceReadyEvent;\nimport io.micronaut.scheduling.annotation.Scheduled;\nimport jakarta.inject.Singleton;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/**\n * A scheduled task that sends a periodic heartbeat whilst the server is active.\n *\n * @author graemerocher\n * @since 1.0\n */\n@Singleton\n@HeartbeatEnabled\npublic class HeartbeatTask implements ApplicationEventListener {\n\n private final Set eventsReference = ConcurrentHashMap.newKeySet();\n\n private final ApplicationEventPublisher eventPublisher;\n\n private final CurrentHealthStatus currentHealthStatus;\n\n /**\n * @param eventPublisher To publish the events related to heartbeat\n * @param configuration The configurations for heartbeat\n * @param currentHealthStatus The current status of health indicator\n */\n public HeartbeatTask(ApplicationEventPublisher eventPublisher, HeartbeatConfiguration configuration, CurrentHealthStatus currentHealthStatus) {\n this.eventPublisher = eventPublisher;\n this.currentHealthStatus = currentHealthStatus;\n }\n\n /**\n * Publish the heartbeat event with current health status.\n */\n @Scheduled(fixedDelay = \"${micronaut.heartbeat.interval:15s}\", initialDelay = \"${micronaut.heartbeat.initial-delay:5s}\")\n public void pulsate() {\n for (ServiceInstance instance : eventsReference) {\n eventPublisher.publishEvent(new HeartbeatEvent(instance, currentHealthStatus.current()));\n }\n }\n\n @Override\n public void onApplicationEvent(ServiceReadyEvent event) {\n eventsReference.add(event.ge", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2289", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/micronaut-projects/micronaut-core/runtime/src/main/java/io/micronaut/health/HeartbeatTask.java", "mask_start_position": 1436, "mask_end_position": 1761, "canonical_solution": "@Scheduled(fixedDelay = \"${micronaut.heartbeat.interval:15s}\", initialDelay = \"${micronaut.heartbeat.initial-delay:5s}\")\n public void pulsate() {\n for (ServiceInstance instance : eventsReference) {\n eventPublisher.publishEvent(new HeartbeatEvent(instance, currentHealthStatus.current()));\n }\n }", "pre_mask_code": "package io.micronaut.health;\n\nimport io.micronaut.context.event.ApplicationEventListener;\nimport io.micronaut.context.event.ApplicationEventPublisher;\nimport io.micronaut.discovery.ServiceInstance;\nimport io.micronaut.discovery.event.ServiceReadyEvent;\nimport io.micronaut.scheduling.annotation.Scheduled;\nimport jakarta.inject.Singleton;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/**\n * A scheduled task that sends a periodic heartbeat whilst the server is active.\n *\n * @author graemerocher\n * @since 1.0\n */\n@Singleton\n@HeartbeatEnabled\npublic class HeartbeatTask implements ApplicationEventListener {\n\n private final Set eventsReference = ConcurrentHashMap.newKeySet();\n\n private final ApplicationEventPublisher eventPublisher;\n\n private final CurrentHealthStatus currentHealthStatus;\n\n /**\n * @param eventPublisher To publish the events related to heartbeat\n * @param configuration The configurations for heartbeat\n * @param currentHealthStatus The current status of health indicator\n */\n public HeartbeatTask(ApplicationEventPublisher eventPublisher, HeartbeatConfiguration configuration, CurrentHealthStatus currentHealthStatus) {\n this.eventPublisher = eventPublisher;\n this.currentHealthStatus = currentHealthStatus;\n }\n\n /**\n * Publish the heartbeat event with current health status.\n */\n ", "post_mask_code": "\n\n @Override\n public void onApplicationEvent(ServiceReadyEvent event) {\n eventsReference.add(event.getSource());\n }\n}\n"} {"task_id": "Java_2290", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate10_8_1_0/src/main/java/com/android/internal/telephony/uicc/IccCardApplicationStatus.java", "mask_start_position": 7891, "mask_end_position": 7919, "canonical_solution": "private void loge(String s) ", "pre_mask_code": "package com.android.internal.telephony.uicc;\n\nimport android.telephony.Rlog;\nimport com.android.internal.telephony.uicc.IccCardStatus.PinState;\n\npublic class IccCardApplicationStatus {\n\n public String aid;\n\n public String app_label;\n\n public AppState app_state;\n\n public AppType app_type;\n\n public PersoSubState perso_substate;\n\n public PinState pin1;\n\n public int pin1_replaced;\n\n public PinState pin2;\n\n public enum AppState {\n\n APPSTATE_UNKNOWN,\n APPSTATE_DETECTED,\n APPSTATE_PIN,\n APPSTATE_PUK,\n APPSTATE_SUBSCRIPTION_PERSO,\n APPSTATE_READY;\n\n boolean isPinRequired() {\n return this == APPSTATE_PIN;\n }\n\n boolean isPukRequired() {\n return this == APPSTATE_PUK;\n }\n\n boolean isSubscriptionPersoEnabled() {\n return this == APPSTATE_SUBSCRIPTION_PERSO;\n }\n\n boolean isAppReady() {\n return this == APPSTATE_READY;\n }\n\n boolean isAppNotReady() {\n if (this == APPSTATE_UNKNOWN || this == APPSTATE_DETECTED) {\n return true;\n }\n return false;\n }\n }\n\n public enum AppType {\n\n APPTYPE_UNKNOWN,\n APPTYPE_SIM,\n APPTYPE_USIM,\n APPTYPE_RUIM,\n APPTYPE_CSIM,\n APPTYPE_ISIM\n }\n\n public enum PersoSubState {\n\n PERSOSUBSTATE_UNKNOWN,\n PERSOSUBSTATE_IN_PROGRESS,\n PERSOSUBSTATE_READY,\n PERSOSUBSTATE_SIM_NETWORK,\n PERSOSUBSTATE_SIM_NETWORK_SUBSET,\n PERSOSUBSTATE_SIM_CORPORATE,\n PERSOSUBSTATE_SIM_SERVICE_PROVIDER,\n PERSOSUBSTATE_SIM_SIM,\n PERSOSUBSTATE_SIM_NETWORK_PUK,\n PERSOSUBSTATE_SIM_NETWORK_SUBSET_PUK,\n PERSOSUBSTATE_SIM_CORPORATE_PUK,\n PERSOSUBSTATE_SIM_SERVICE_PROVIDER_PUK,\n PERSOSUBSTATE_SIM_SIM_PUK,\n PERSOSUBSTATE_RUIM_NETWORK1,\n PERSOSUBSTATE_RUIM_NETWORK2,\n PERSOSUBSTATE_RUIM_HRPD,\n PERSOSUBSTATE_RUIM_CORPORATE,\n PERSOSUBSTATE_RUIM_SERVICE_PROVIDER,\n PERSOSUBSTATE_RUIM_RUIM,\n PERSOSUBSTATE_RUIM_NETWORK1_PUK,\n PERSOSUBSTATE_RUIM_NETWORK2_PUK,\n PERSOSUBSTATE_RUIM_HRPD_PUK,\n PERSOSUBSTATE_RUIM_CORPORATE_PUK,\n PERSOSUBSTATE_RUIM_SERVICE_PROVIDER_PUK,\n PERSOSUBSTATE_RUIM_RUIM_PUK;\n\n boolean isPersoSubStateUnknown() {\n return this == PERSOSUBSTATE_UNKNOWN;\n }\n }\n\n public AppType AppTypeFromRILInt(int type) {\n switch(type) {\n case 0:\n return AppType.APPTYPE_UNKNOWN;\n case 1:\n return AppType.APPTYPE_SIM;\n case 2:\n return AppType.APPTYPE_USIM;\n case 3:\n return AppType.APPTYPE_RUIM;\n case 4:\n return AppType.APPTYPE_CSIM;\n case 5:\n return AppType.APPTYPE_ISIM;\n default:\n AppType newType = AppType.APPTYPE_UNKNOWN;\n loge(\"AppTypeFromRILInt: bad RIL_AppType: \" + type + \" use APPTYPE_UNKNOWN\");\n return newType;\n }\n }\n\n public AppState AppStateFromRILInt(int state) {\n switch(state) {\n case 0:\n return AppState.APPSTATE_UNKNOWN;\n case 1:\n return AppState.APPSTATE_DETECTED;\n case 2:\n return AppState.APPSTATE_PIN;\n case 3:\n return AppState.APPSTATE_PUK;\n case 4:\n return AppState.APPSTATE_SUBSCRIPTION_PERSO;\n case 5:\n return AppState.APPSTATE_READY;\n default:\n AppState newState = AppState.APPSTATE_UNKNOWN;\n loge(\"AppStateFromRILInt: bad state: \" + state + \" use APPSTATE_UNKNOWN\");\n return newState;\n }\n }\n\n public PersoSubState PersoSubstateFromRILInt(int substate) {\n switch(substate) {\n case 0:\n return PersoSubState.PERSOSUBSTATE_UNKNOWN;\n case 1:\n return PersoSubState.PERSOSUBSTATE_IN_PROGRESS;\n case 2:\n return PersoSubState.PERSOSUBSTATE_READY;\n case 3:\n return PersoSubState.PERSOSUBSTATE_SIM_NETWORK;\n case 4:\n return PersoSubState.PERSOSUBSTATE_SIM_NETWORK_SUBSET;\n case 5:\n return PersoSubState.PERSOSUBSTATE_SIM_CORPORATE;\n case 6:\n return PersoSubState.PERSOSUBSTATE_SIM_SERVICE_PROVIDER;\n case 7:\n return PersoSubState.PERSOSUBSTATE_SIM_SIM;\n case 8:\n return PersoSubState.PERSOSUBSTATE_SIM_NETWORK_PUK;\n case 9:\n return PersoSubState.PERSOSUBSTATE_SIM_NETWORK_SUBSET_PUK;\n case 10:\n return PersoSubState.PERSOSUBSTATE_SIM_CORPORATE_PUK;\n case 11:\n return PersoSubState.PERSOSUBSTATE_SIM_SERVICE_PROVIDER_PUK;\n case 12:\n return PersoSubState.PERSOSUBSTATE_SIM_SIM_PUK;\n case 13:\n return PersoSubState.PERSOSUBSTATE_RUIM_NETWORK1;\n case 14:\n return PersoSubState.PERSOSUBSTATE_RUIM_NETWORK2;\n case 15:\n return PersoSubState.PERSOSUBSTATE_RUIM_HRPD;\n case 16:\n return PersoSubState.PERSOSUBSTATE_RUIM_CORPORATE;\n case 17:\n return PersoSubState.PERSOSUBSTATE_RUIM_SERVICE_PROVIDER;\n case 18:\n return PersoSubState.PERSOSUBSTATE_RUIM_RUIM;\n case 19:\n return PersoSubState.PERSOSUBSTATE_RUIM_NETWORK1_PUK;\n case 20:\n return PersoSubState.PERSOSUBSTATE_RUIM_NETWORK2_PUK;\n case 21:\n return PersoSubState.PERSOSUBSTATE_RUIM_HRPD_PUK;\n case 22:\n return PersoSubState.PERSOSUBSTATE_RUIM_CORPORATE_PUK;\n case 23:\n return PersoSubState.PERSOSUBSTATE_RUIM_SERVICE_PROVIDER_PUK;\n case 24:\n return PersoSubState.PERSOSUBSTATE_RUIM_RUIM_PUK;\n default:\n PersoSubState newSubState = PersoSubState.PERSOSUBSTATE_UNKNOWN;\n loge(\"PersoSubstateFromRILInt: bad substate: \" + substate + \" use PERSOSUBSTATE_UNKNOWN\");\n return newSubState;\n }\n }\n\n public PinState PinStateFromRILInt(int state) {\n switch(state) {\n case 0:\n return PinState.PINSTATE_UNKNOWN;\n case 1:\n return PinState.PINSTATE_ENABLED_NOT_VERIFIED;\n case 2:\n return PinState.PINSTATE_ENABLED_VERIFIED;\n case 3:\n return PinState.PINSTATE_DISABLED;\n case 4:\n return PinState.PINSTATE_ENABLED_BLOCKED;\n case 5:\n return PinState.PINSTATE_ENABLED_PERM_BLOCKED;\n default:\n PinState newPinState = PinState.PINSTATE_UNKNOWN;\n loge(\"PinStateFromRILInt: bad pin state: \" + state + \" use PINSTATE_UNKNOWN\");\n return newPinState;\n }\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"{\").append(this.app_type).append(\",\").append(this.app_state);\n if (this.app_state == AppState.APPSTATE_SUBSCRIPTION_PERSO) {\n sb.append(\",\").append(this.perso_substate);\n }\n if (!(this.app_type == AppType.APPTYPE_CSIM || this.app_type == AppType.APPTYPE_USIM)) {\n if (this.app_type == AppType.APPTYPE_ISIM) {\n }\n sb.append(\"}\");\n return sb.toString();\n }\n sb.append(\",pin1=\").append(this.pin1);\n sb.append(\",pin2=\").append(this.pin2);\n sb.append(\"}\");\n return sb.toString();\n }\n\n ", "post_mask_code": "{\n Rlog.e(\"IccCardApplicationStatus\", s);\n }\n}\n"} {"task_id": "Java_2291", "language": "Java", "task_type": "method_body", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate10_8_1_0/src/main/java/com/android/internal/telephony/uicc/IccCardApplicationStatus.java", "mask_start_position": 833, "mask_end_position": 900, "canonical_solution": "{\n return this == APPSTATE_SUBSCRIPTION_PERSO;\n }", "pre_mask_code": "package com.android.internal.telephony.uicc;\n\nimport android.telephony.Rlog;\nimport com.android.internal.telephony.uicc.IccCardStatus.PinState;\n\npublic class IccCardApplicationStatus {\n\n public String aid;\n\n public String app_label;\n\n public AppState app_state;\n\n public AppType app_type;\n\n public PersoSubState perso_substate;\n\n public PinState pin1;\n\n public int pin1_replaced;\n\n public PinState pin2;\n\n public enum AppState {\n\n APPSTATE_UNKNOWN,\n APPSTATE_DETECTED,\n APPSTATE_PIN,\n APPSTATE_PUK,\n APPSTATE_SUBSCRIPTION_PERSO,\n APPSTATE_READY;\n\n boolean isPinRequired() {\n return this == APPSTATE_PIN;\n }\n\n boolean isPukRequired() {\n return this == APPSTATE_PUK;\n }\n\n boolean isSubscriptionPersoEnabled() ", "post_mask_code": "\n\n boolean isAppReady() {\n return this == APPSTATE_READY;\n }\n\n boolean isAppNotReady() {\n if (this == APPSTATE_UNKNOWN || this == APPSTATE_DETECTED) {\n return true;\n }\n return false;\n }\n }\n\n public enum AppType {\n\n APPTYPE_UNKNOWN,\n APPTYPE_SIM,\n APPTYPE_USIM,\n APPTYPE_RUIM,\n APPTYPE_CSIM,\n APPTYPE_ISIM\n }\n\n public enum PersoSubState {\n\n PERSOSUBSTATE_UNKNOWN,\n PERSOSUBSTATE_IN_PROGRESS,\n PERSOSUBSTATE_READY,\n PERSOSUBSTATE_SIM_NETWORK,\n PERSOSUBSTATE_SIM_NETWORK_SUBSET,\n PERSOSUBSTATE_SIM_CORPORATE,\n PERSOSUBSTATE_SIM_SERVICE_PROVIDER,\n PERSOSUBSTATE_SIM_SIM,\n PERSOSUBSTATE_SIM_NETWORK_PUK,\n PERSOSUBSTATE_SIM_NETWORK_SUBSET_PUK,\n PERSOSUBSTATE_SIM_CORPORATE_PUK,\n PERSOSUBSTATE_SIM_SERVICE_PROVIDER_PUK,\n PERSOSUBSTATE_SIM_SIM_PUK,\n PERSOSUBSTATE_RUIM_NETWORK1,\n PERSOSUBSTATE_RUIM_NETWORK2,\n PERSOSUBSTATE_RUIM_HRPD,\n PERSOSUBSTATE_RUIM_CORPORATE,\n PERSOSUBSTATE_RUIM_SERVICE_PROVIDER,\n PERSOSUBSTATE_RUIM_RUIM,\n PERSOSUBSTATE_RUIM_NETWORK1_PUK,\n PERSOSUBSTATE_RUIM_NETWORK2_PUK,\n PERSOSUBSTATE_RUIM_HRPD_PUK,\n PERSOSUBSTATE_RUIM_CORPORATE_PUK,\n PERSOSUBSTATE_RUIM_SERVICE_PROVIDER_PUK,\n PERSOSUBSTATE_RUIM_RUIM_PUK;\n\n boolean isPersoSubStateUnknown() {\n return this == PERSOSUBSTATE_UNKNOWN;\n }\n }\n\n public AppType AppTypeFromRILInt(int type) {\n switch(type) {\n case 0:\n return AppType.APPTYPE_UNKNOWN;\n case 1:\n return AppType.APPTYPE_SIM;\n case 2:\n return AppType.APPTYPE_USIM;\n case 3:\n return AppType.APPTYPE_RUIM;\n case 4:\n return AppType.APPTYPE_CSIM;\n case 5:\n return AppType.APPTYPE_ISIM;\n default:\n AppType newType = AppType.APPTYPE_UNKNOWN;\n loge(\"AppTypeFromRILInt: bad RIL_AppType: \" + type + \" use APPTYPE_UNKNOWN\");\n return newType;\n }\n }\n\n public AppState AppStateFromRILInt(int state) {\n switch(state) {\n case 0:\n return AppState.APPSTATE_UNKNOWN;\n case 1:\n return AppState.APPSTATE_DETECTED;\n case 2:\n return AppState.APPSTATE_PIN;\n case 3:\n return AppState.APPSTATE_PUK;\n case 4:\n return AppState.APPSTATE_SUBSCRIPTION_PERSO;\n case 5:\n return AppState.APPSTATE_READY;\n default:\n AppState newState = AppState.APPSTATE_UNKNOWN;\n loge(\"AppStateFromRILInt: bad state: \" + state + \" use APPSTATE_UNKNOWN\");\n return newState;\n }\n }\n\n public PersoSubState PersoSubstateFromRILInt(int substate) {\n switch(substate) {\n case 0:\n return PersoSubState.PERSOSUBSTATE_UNKNOWN;\n case 1:\n return PersoSubState.PERSOSUBSTATE_IN_PROGRESS;\n case 2:\n return PersoSubState.PERSOSUBSTATE_READY;\n case 3:\n return PersoSubState.PERSOSUBSTATE_SIM_NETWORK;\n case 4:\n return PersoSubState.PERSOSUBSTATE_SIM_NETWORK_SUBSET;\n case 5:\n return PersoSubState.PERSOSUBSTATE_SIM_CORPORATE;\n case 6:\n return PersoSubState.PERSOSUBSTATE_SIM_SERVICE_PROVIDER;\n case 7:\n return PersoSubState.PERSOSUBSTATE_SIM_SIM;\n case 8:\n return PersoSubState.PERSOSUBSTATE_SIM_NETWORK_PUK;\n case 9:\n return PersoSubState.PERSOSUBSTATE_SIM_NETWORK_SUBSET_PUK;\n case 10:\n return PersoSubState.PERSOSUBSTATE_SIM_CORPORATE_PUK;\n case 11:\n return PersoSubState.PERSOSUBSTATE_SIM_SERVICE_PROVIDER_PUK;\n case 12:\n return PersoSubState.PERSOSUBSTATE_SIM_SIM_PUK;\n case 13:\n return PersoSubState.PERSOSUBSTATE_RUIM_NETWORK1;\n case 14:\n return PersoSubState.PERSOSUBSTATE_RUIM_NETWORK2;\n case 15:\n return PersoSubState.PERSOSUBSTATE_RUIM_HRPD;\n case 16:\n return PersoSubState.PERSOSUBSTATE_RUIM_CORPORATE;\n case 17:\n return PersoSubState.PERSOSUBSTATE_RUIM_SERVICE_PROVIDER;\n case 18:\n return PersoSubState.PERSOSUBSTATE_RUIM_RUIM;\n case 19:\n return PersoSubState.PERSOSUBSTATE_RUIM_NETWORK1_PUK;\n case 20:\n return PersoSubState.PERSOSUBSTATE_RUIM_NETWORK2_PUK;\n case 21:\n return PersoSubState.PERSOSUBSTATE_RUIM_HRPD_PUK;\n case 22:\n return PersoSubState.PERSOSUBSTATE_RUIM_CORPORATE_PUK;\n case 23:\n return PersoSubState.PERSOSUBSTATE_RUIM_SERVICE_PROVIDER_PUK;\n case 24:\n return PersoSubState.PERSOSUBSTATE_RUIM_RUIM_PUK;\n default:\n PersoSubState newSubState = PersoSubState.PERSOSUBSTATE_UNKNOWN;\n loge(\"PersoSubstateFromRILInt: bad substate: \" + substate + \" use PERSOSUBSTATE_UNKNOWN\");\n return newSubState;\n }\n }\n\n public PinState PinStateFromRILInt(int state) {\n switch(state) {\n case 0:\n return PinState.PINSTATE_UNKNOWN;\n case 1:\n return PinState.PINSTATE_ENABLED_NOT_VERIFIED;\n case 2:\n return PinState.PINSTATE_ENABLED_VERIFIED;\n case 3:\n return PinState.PINSTATE_DISABLED;\n case 4:\n return PinState.PINSTATE_ENABLED_BLOCKED;\n case 5:\n return PinState.PINSTATE_ENABLED_PERM_BLOCKED;\n default:\n PinState newPinState = PinState.PINSTATE_UNKNOWN;\n loge(\"PinStateFromRILInt: bad pin state: \" + state + \" use PINSTATE_UNKNOWN\");\n return newPinState;\n }\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"{\").append(this.app_type).append(\",\").append(this.app_state);\n if (this.app_state == AppState.APPSTATE_SUBSCRIPTION_PERSO) {\n sb.append(\",\").append(this.perso_substate);\n }\n if (!(this.app_type == AppType.APPTYPE_CSIM || this.app_type == AppType.APPTYPE_USIM)) {\n if (this.app_type == AppType.APPTYPE_ISIM) {\n }\n sb.append(\"}\");\n return sb.toString();\n }\n sb.append(\",pin1=\").append(this.pin1);\n sb.append(\",pin2=\").append(this.pin2);\n sb.append(\"}\");\n return sb.toString();\n }\n\n private void loge(String s) {\n Rlog.e(\"IccCardApplicationStatus\", s);\n }\n}\n"} {"task_id": "Java_2292", "language": "Java", "task_type": "single_line", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate10_8_1_0/src/main/java/com/android/internal/telephony/uicc/IccCardApplicationStatus.java", "mask_start_position": 7844, "mask_end_position": 7849, "canonical_solution": "\"}\");", "pre_mask_code": "package com.android.internal.telephony.uicc;\n\nimport android.telephony.Rlog;\nimport com.android.internal.telephony.uicc.IccCardStatus.PinState;\n\npublic class IccCardApplicationStatus {\n\n public String aid;\n\n public String app_label;\n\n public AppState app_state;\n\n public AppType app_type;\n\n public PersoSubState perso_substate;\n\n public PinState pin1;\n\n public int pin1_replaced;\n\n public PinState pin2;\n\n public enum AppState {\n\n APPSTATE_UNKNOWN,\n APPSTATE_DETECTED,\n APPSTATE_PIN,\n APPSTATE_PUK,\n APPSTATE_SUBSCRIPTION_PERSO,\n APPSTATE_READY;\n\n boolean isPinRequired() {\n return this == APPSTATE_PIN;\n }\n\n boolean isPukRequired() {\n return this == APPSTATE_PUK;\n }\n\n boolean isSubscriptionPersoEnabled() {\n return this == APPSTATE_SUBSCRIPTION_PERSO;\n }\n\n boolean isAppReady() {\n return this == APPSTATE_READY;\n }\n\n boolean isAppNotReady() {\n if (this == APPSTATE_UNKNOWN || this == APPSTATE_DETECTED) {\n return true;\n }\n return false;\n }\n }\n\n public enum AppType {\n\n APPTYPE_UNKNOWN,\n APPTYPE_SIM,\n APPTYPE_USIM,\n APPTYPE_RUIM,\n APPTYPE_CSIM,\n APPTYPE_ISIM\n }\n\n public enum PersoSubState {\n\n PERSOSUBSTATE_UNKNOWN,\n PERSOSUBSTATE_IN_PROGRESS,\n PERSOSUBSTATE_READY,\n PERSOSUBSTATE_SIM_NETWORK,\n PERSOSUBSTATE_SIM_NETWORK_SUBSET,\n PERSOSUBSTATE_SIM_CORPORATE,\n PERSOSUBSTATE_SIM_SERVICE_PROVIDER,\n PERSOSUBSTATE_SIM_SIM,\n PERSOSUBSTATE_SIM_NETWORK_PUK,\n PERSOSUBSTATE_SIM_NETWORK_SUBSET_PUK,\n PERSOSUBSTATE_SIM_CORPORATE_PUK,\n PERSOSUBSTATE_SIM_SERVICE_PROVIDER_PUK,\n PERSOSUBSTATE_SIM_SIM_PUK,\n PERSOSUBSTATE_RUIM_NETWORK1,\n PERSOSUBSTATE_RUIM_NETWORK2,\n PERSOSUBSTATE_RUIM_HRPD,\n PERSOSUBSTATE_RUIM_CORPORATE,\n PERSOSUBSTATE_RUIM_SERVICE_PROVIDER,\n PERSOSUBSTATE_RUIM_RUIM,\n PERSOSUBSTATE_RUIM_NETWORK1_PUK,\n PERSOSUBSTATE_RUIM_NETWORK2_PUK,\n PERSOSUBSTATE_RUIM_HRPD_PUK,\n PERSOSUBSTATE_RUIM_CORPORATE_PUK,\n PERSOSUBSTATE_RUIM_SERVICE_PROVIDER_PUK,\n PERSOSUBSTATE_RUIM_RUIM_PUK;\n\n boolean isPersoSubStateUnknown() {\n return this == PERSOSUBSTATE_UNKNOWN;\n }\n }\n\n public AppType AppTypeFromRILInt(int type) {\n switch(type) {\n case 0:\n return AppType.APPTYPE_UNKNOWN;\n case 1:\n return AppType.APPTYPE_SIM;\n case 2:\n return AppType.APPTYPE_USIM;\n case 3:\n return AppType.APPTYPE_RUIM;\n case 4:\n return AppType.APPTYPE_CSIM;\n case 5:\n return AppType.APPTYPE_ISIM;\n default:\n AppType newType = AppType.APPTYPE_UNKNOWN;\n loge(\"AppTypeFromRILInt: bad RIL_AppType: \" + type + \" use APPTYPE_UNKNOWN\");\n return newType;\n }\n }\n\n public AppState AppStateFromRILInt(int state) {\n switch(state) {\n case 0:\n return AppState.APPSTATE_UNKNOWN;\n case 1:\n return AppState.APPSTATE_DETECTED;\n case 2:\n return AppState.APPSTATE_PIN;\n case 3:\n return AppState.APPSTATE_PUK;\n case 4:\n return AppState.APPSTATE_SUBSCRIPTION_PERSO;\n case 5:\n return AppState.APPSTATE_READY;\n default:\n AppState newState = AppState.APPSTATE_UNKNOWN;\n loge(\"AppStateFromRILInt: bad state: \" + state + \" use APPSTATE_UNKNOWN\");\n return newState;\n }\n }\n\n public PersoSubState PersoSubstateFromRILInt(int substate) {\n switch(substate) {\n case 0:\n return PersoSubState.PERSOSUBSTATE_UNKNOWN;\n case 1:\n return PersoSubState.PERSOSUBSTATE_IN_PROGRESS;\n case 2:\n return PersoSubState.PERSOSUBSTATE_READY;\n case 3:\n return PersoSubState.PERSOSUBSTATE_SIM_NETWORK;\n case 4:\n return PersoSubState.PERSOSUBSTATE_SIM_NETWORK_SUBSET;\n case 5:\n return PersoSubState.PERSOSUBSTATE_SIM_CORPORATE;\n case 6:\n return PersoSubState.PERSOSUBSTATE_SIM_SERVICE_PROVIDER;\n case 7:\n return PersoSubState.PERSOSUBSTATE_SIM_SIM;\n case 8:\n return PersoSubState.PERSOSUBSTATE_SIM_NETWORK_PUK;\n case 9:\n return PersoSubState.PERSOSUBSTATE_SIM_NETWORK_SUBSET_PUK;\n case 10:\n return PersoSubState.PERSOSUBSTATE_SIM_CORPORATE_PUK;\n case 11:\n return PersoSubState.PERSOSUBSTATE_SIM_SERVICE_PROVIDER_PUK;\n case 12:\n return PersoSubState.PERSOSUBSTATE_SIM_SIM_PUK;\n case 13:\n return PersoSubState.PERSOSUBSTATE_RUIM_NETWORK1;\n case 14:\n return PersoSubState.PERSOSUBSTATE_RUIM_NETWORK2;\n case 15:\n return PersoSubState.PERSOSUBSTATE_RUIM_HRPD;\n case 16:\n return PersoSubState.PERSOSUBSTATE_RUIM_CORPORATE;\n case 17:\n return PersoSubState.PERSOSUBSTATE_RUIM_SERVICE_PROVIDER;\n case 18:\n return PersoSubState.PERSOSUBSTATE_RUIM_RUIM;\n case 19:\n return PersoSubState.PERSOSUBSTATE_RUIM_NETWORK1_PUK;\n case 20:\n return PersoSubState.PERSOSUBSTATE_RUIM_NETWORK2_PUK;\n case 21:\n return PersoSubState.PERSOSUBSTATE_RUIM_HRPD_PUK;\n case 22:\n return PersoSubState.PERSOSUBSTATE_RUIM_CORPORATE_PUK;\n case 23:\n return PersoSubState.PERSOSUBSTATE_RUIM_SERVICE_PROVIDER_PUK;\n case 24:\n return PersoSubState.PERSOSUBSTATE_RUIM_RUIM_PUK;\n default:\n PersoSubState newSubState = PersoSubState.PERSOSUBSTATE_UNKNOWN;\n loge(\"PersoSubstateFromRILInt: bad substate: \" + substate + \" use PERSOSUBSTATE_UNKNOWN\");\n return newSubState;\n }\n }\n\n public PinState PinStateFromRILInt(int state) {\n switch(state) {\n case 0:\n return PinState.PINSTATE_UNKNOWN;\n case 1:\n return PinState.PINSTATE_ENABLED_NOT_VERIFIED;\n case 2:\n return PinState.PINSTATE_ENABLED_VERIFIED;\n case 3:\n return PinState.PINSTATE_DISABLED;\n case 4:\n return PinState.PINSTATE_ENABLED_BLOCKED;\n case 5:\n return PinState.PINSTATE_ENABLED_PERM_BLOCKED;\n default:\n PinState newPinState = PinState.PINSTATE_UNKNOWN;\n loge(\"PinStateFromRILInt: bad pin state: \" + state + \" use PINSTATE_UNKNOWN\");\n return newPinState;\n }\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"{\").append(this.app_type).append(\",\").append(this.app_state);\n if (this.app_state == AppState.APPSTATE_SUBSCRIPTION_PERSO) {\n sb.append(\",\").append(this.perso_substate);\n }\n if (!(this.app_type == AppType.APPTYPE_CSIM || this.app_type == AppType.APPTYPE_USIM)) {\n if (this.app_type == AppType.APPTYPE_ISIM) {\n }\n sb.append(\"}\");\n return sb.toString();\n }\n sb.append(\",pin1=\").append(this.pin1);\n sb.append(\",pin2=\").append(this.pin2);\n sb.append(", "post_mask_code": "\n return sb.toString();\n }\n\n private void loge(String s) {\n Rlog.e(\"IccCardApplicationStatus\", s);\n }\n}\n"} {"task_id": "Java_2293", "language": "Java", "task_type": "method_signature", "source_file": "java/github/magefree/mage/Mage.Sets/src/mage/cards/t/TsabosDecree.java", "mask_start_position": 1787, "mask_end_position": 1849, "canonical_solution": "@Override\n public boolean apply(Game game, Ability source) ", "pre_mask_code": "package mage.cards.t;\n\nimport mage.MageObject;\nimport mage.abilities.Ability;\nimport mage.abilities.effects.OneShotEffect;\nimport mage.cards.CardImpl;\nimport mage.cards.CardSetInfo;\nimport mage.cards.CardsImpl;\nimport mage.choices.Choice;\nimport mage.choices.ChoiceCreatureType;\nimport mage.constants.CardType;\nimport mage.constants.Outcome;\nimport mage.constants.SubType;\nimport mage.filter.FilterCard;\nimport mage.filter.common.FilterCreaturePermanent;\nimport mage.game.Game;\nimport mage.game.permanent.Permanent;\nimport mage.players.Player;\nimport mage.target.TargetPlayer;\nimport java.util.UUID;\n\n/**\n * @author fireshoes\n */\npublic final class TsabosDecree extends CardImpl {\n\n public TsabosDecree(UUID ownerId, CardSetInfo setInfo) {\n super(ownerId, setInfo, new CardType[] { CardType.INSTANT }, \"{5}{B}\");\n // Choose a creature type. Target player reveals their hand and discards all creature cards of that type. Then destroy all creatures of that type that player controls. They can't be regenerated.\n this.getSpellAbility().addEffect(new TsabosDecreeEffect());\n this.getSpellAbility().addTarget(new TargetPlayer());\n }\n\n private TsabosDecree(final TsabosDecree card) {\n super(card);\n }\n\n @Override\n public TsabosDecree copy() {\n return new TsabosDecree(this);\n }\n}\n\nclass TsabosDecreeEffect extends OneShotEffect {\n\n TsabosDecreeEffect() {\n super(Outcome.UnboostCreature);\n staticText = \"Choose a creature type. Target player reveals their hand and discards \" + \"all creature cards of that type. Then destroy all creatures of that type that player controls. \" + \"They can't be regenerated\";\n }\n\n private TsabosDecreeEffect(final TsabosDecreeEffect effect) {\n super(effect);\n }\n\n ", "post_mask_code": "{\n Player player = game.getPlayer(source.getControllerId());\n Player targetPlayer = game.getPlayer(targetPointer.getFirst(game, source));\n MageObject sourceObject = game.getObject(source.getSourceId());\n if (player == null) {\n return false;\n }\n if (sourceObject == null) {\n return false;\n }\n Choice typeChoice = new ChoiceCreatureType(sourceObject);\n if (!player.choose(outcome, typeChoice, game)) {\n return false;\n }\n game.informPlayers(sourceObject.getLogName() + \" chosen type: \" + typeChoice.getChoice());\n targetPlayer.revealCards(\"hand of \" + targetPlayer.getName(), targetPlayer.getHand(), game);\n FilterCard filterCard = new FilterCard();\n filterCard.add(SubType.byDescription(typeChoice.getChoice()).getPredicate());\n targetPlayer.discard(new CardsImpl(targetPlayer.getHand().getCards(filterCard, game)), false, source, game);\n FilterCreaturePermanent filterCreaturePermanent = new FilterCreaturePermanent();\n filterCreaturePermanent.add(SubType.byDescription(typeChoice.getChoice()).getPredicate());\n for (Permanent creature : game.getBattlefield().getActivePermanents(filterCreaturePermanent, source.getSourceId(), game)) {\n if (creature.isControlledBy(targetPlayer.getId())) {\n creature.destroy(source, game, true);\n }\n }\n return true;\n }\n\n @Override\n public TsabosDecreeEffect copy() {\n return new TsabosDecreeEffect(this);\n }\n}\n"} {"task_id": "Java_2294", "language": "Java", "task_type": "method_body", "source_file": "java/github/magefree/mage/Mage.Sets/src/mage/cards/t/TsabosDecree.java", "mask_start_position": 3365, "mask_end_position": 3417, "canonical_solution": "{\n return new TsabosDecreeEffect(this);\n }", "pre_mask_code": "package mage.cards.t;\n\nimport mage.MageObject;\nimport mage.abilities.Ability;\nimport mage.abilities.effects.OneShotEffect;\nimport mage.cards.CardImpl;\nimport mage.cards.CardSetInfo;\nimport mage.cards.CardsImpl;\nimport mage.choices.Choice;\nimport mage.choices.ChoiceCreatureType;\nimport mage.constants.CardType;\nimport mage.constants.Outcome;\nimport mage.constants.SubType;\nimport mage.filter.FilterCard;\nimport mage.filter.common.FilterCreaturePermanent;\nimport mage.game.Game;\nimport mage.game.permanent.Permanent;\nimport mage.players.Player;\nimport mage.target.TargetPlayer;\nimport java.util.UUID;\n\n/**\n * @author fireshoes\n */\npublic final class TsabosDecree extends CardImpl {\n\n public TsabosDecree(UUID ownerId, CardSetInfo setInfo) {\n super(ownerId, setInfo, new CardType[] { CardType.INSTANT }, \"{5}{B}\");\n // Choose a creature type. Target player reveals their hand and discards all creature cards of that type. Then destroy all creatures of that type that player controls. They can't be regenerated.\n this.getSpellAbility().addEffect(new TsabosDecreeEffect());\n this.getSpellAbility().addTarget(new TargetPlayer());\n }\n\n private TsabosDecree(final TsabosDecree card) {\n super(card);\n }\n\n @Override\n public TsabosDecree copy() {\n return new TsabosDecree(this);\n }\n}\n\nclass TsabosDecreeEffect extends OneShotEffect {\n\n TsabosDecreeEffect() {\n super(Outcome.UnboostCreature);\n staticText = \"Choose a creature type. Target player reveals their hand and discards \" + \"all creature cards of that type. Then destroy all creatures of that type that player controls. \" + \"They can't be regenerated\";\n }\n\n private TsabosDecreeEffect(final TsabosDecreeEffect effect) {\n super(effect);\n }\n\n @Override\n public boolean apply(Game game, Ability source) {\n Player player = game.getPlayer(source.getControllerId());\n Player targetPlayer = game.getPlayer(targetPointer.getFirst(game, source));\n MageObject sourceObject = game.getObject(source.getSourceId());\n if (player == null) {\n return false;\n }\n if (sourceObject == null) {\n return false;\n }\n Choice typeChoice = new ChoiceCreatureType(sourceObject);\n if (!player.choose(outcome, typeChoice, game)) {\n return false;\n }\n game.informPlayers(sourceObject.getLogName() + \" chosen type: \" + typeChoice.getChoice());\n targetPlayer.revealCards(\"hand of \" + targetPlayer.getName(), targetPlayer.getHand(), game);\n FilterCard filterCard = new FilterCard();\n filterCard.add(SubType.byDescription(typeChoice.getChoice()).getPredicate());\n targetPlayer.discard(new CardsImpl(targetPlayer.getHand().getCards(filterCard, game)), false, source, game);\n FilterCreaturePermanent filterCreaturePermanent = new FilterCreaturePermanent();\n filterCreaturePermanent.add(SubType.byDescription(typeChoice.getChoice()).getPredicate());\n for (Permanent creature : game.getBattlefield().getActivePermanents(filterCreaturePermanent, source.getSourceId(), game)) {\n if (creature.isControlledBy(targetPlayer.getId())) {\n creature.destroy(source, game, true);\n }\n }\n return true;\n }\n\n @Override\n public TsabosDecreeEffect copy() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2295", "language": "Java", "task_type": "single_line", "source_file": "java/github/magefree/mage/Mage.Sets/src/mage/cards/t/TsabosDecree.java", "mask_start_position": 2761, "mask_end_position": 2822, "canonical_solution": ".getHand().getCards(filterCard, game)), false, source, game);", "pre_mask_code": "package mage.cards.t;\n\nimport mage.MageObject;\nimport mage.abilities.Ability;\nimport mage.abilities.effects.OneShotEffect;\nimport mage.cards.CardImpl;\nimport mage.cards.CardSetInfo;\nimport mage.cards.CardsImpl;\nimport mage.choices.Choice;\nimport mage.choices.ChoiceCreatureType;\nimport mage.constants.CardType;\nimport mage.constants.Outcome;\nimport mage.constants.SubType;\nimport mage.filter.FilterCard;\nimport mage.filter.common.FilterCreaturePermanent;\nimport mage.game.Game;\nimport mage.game.permanent.Permanent;\nimport mage.players.Player;\nimport mage.target.TargetPlayer;\nimport java.util.UUID;\n\n/**\n * @author fireshoes\n */\npublic final class TsabosDecree extends CardImpl {\n\n public TsabosDecree(UUID ownerId, CardSetInfo setInfo) {\n super(ownerId, setInfo, new CardType[] { CardType.INSTANT }, \"{5}{B}\");\n // Choose a creature type. Target player reveals their hand and discards all creature cards of that type. Then destroy all creatures of that type that player controls. They can't be regenerated.\n this.getSpellAbility().addEffect(new TsabosDecreeEffect());\n this.getSpellAbility().addTarget(new TargetPlayer());\n }\n\n private TsabosDecree(final TsabosDecree card) {\n super(card);\n }\n\n @Override\n public TsabosDecree copy() {\n return new TsabosDecree(this);\n }\n}\n\nclass TsabosDecreeEffect extends OneShotEffect {\n\n TsabosDecreeEffect() {\n super(Outcome.UnboostCreature);\n staticText = \"Choose a creature type. Target player reveals their hand and discards \" + \"all creature cards of that type. Then destroy all creatures of that type that player controls. \" + \"They can't be regenerated\";\n }\n\n private TsabosDecreeEffect(final TsabosDecreeEffect effect) {\n super(effect);\n }\n\n @Override\n public boolean apply(Game game, Ability source) {\n Player player = game.getPlayer(source.getControllerId());\n Player targetPlayer = game.getPlayer(targetPointer.getFirst(game, source));\n MageObject sourceObject = game.getObject(source.getSourceId());\n if (player == null) {\n return false;\n }\n if (sourceObject == null) {\n return false;\n }\n Choice typeChoice = new ChoiceCreatureType(sourceObject);\n if (!player.choose(outcome, typeChoice, game)) {\n return false;\n }\n game.informPlayers(sourceObject.getLogName() + \" chosen type: \" + typeChoice.getChoice());\n targetPlayer.revealCards(\"hand of \" + targetPlayer.getName(), targetPlayer.getHand(), game);\n FilterCard filterCard = new FilterCard();\n filterCard.add(SubType.byDescription(typeChoice.getChoice()).getPredicate());\n targetPlayer.discard(new CardsImpl(targetPlayer", "post_mask_code": "\n FilterCreaturePermanent filterCreaturePermanent = new FilterCreaturePermanent();\n filterCreaturePermanent.add(SubType.byDescription(typeChoice.getChoice()).getPredicate());\n for (Permanent creature : game.getBattlefield().getActivePermanents(filterCreaturePermanent, source.getSourceId(), game)) {\n if (creature.isControlledBy(targetPlayer.getId())) {\n creature.destroy(source, game, true);\n }\n }\n return true;\n }\n\n @Override\n public TsabosDecreeEffect copy() {\n return new TsabosDecreeEffect(this);\n }\n}\n"} {"task_id": "Java_2296", "language": "Java", "task_type": "method_signature", "source_file": "java/github/couchbase/kafka-connect-couchbase/src/main/java/com/couchbase/connect/kafka/handler/sink/ConcurrencyHint.java", "mask_start_position": 2303, "mask_end_position": 2346, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "package com.couchbase.connect.kafka.handler.sink;\n\nimport java.util.HashSet;\nimport java.util.Objects;\nimport static java.util.Objects.requireNonNull;\n\n/**\n * Used for concurrency control. Determines which actions may\n * be performed concurrently.\n *

\n * If two actions have concurrency hints with equal values,\n * the first action must complete before the second is started.\n *

\n * Example: Using document IDs as hint values is a way to express\n * the constraint that different documents may be updated in parallel,\n * but updates to the same document must be applied sequentially.\n *\n * @see #of(Object)\n * @see #alwaysConcurrent()\n * @see #neverConcurrent()\n */\npublic class ConcurrencyHint {\n\n /**\n * Indicates the action may be performed concurrently with any other action\n * whose hint value is NOT EQUAL to this one.\n *\n * @param value the value that must be unique withing a batch of concurrent operations.\n * Must be the sort of thing you can safely insert in a {@link HashSet}.\n */\n public static ConcurrencyHint of(Object value) {\n return new ConcurrencyHint(value);\n }\n\n /**\n * Returns a special hint indicating the action may be performed concurrently\n * with any other action, regardless of the other action's concurrency hint.\n */\n public static ConcurrencyHint alwaysConcurrent() {\n return ALWAYS_CONCURRENT;\n }\n\n /**\n * Returns a special hint indicating the action must never be performed concurrently\n * with any other action, regardless of the other action's concurrency hint.\n *

\n * In other words, all prior actions will be completed before this action is performed,\n * and this action will be completed before any subsequent actions are performed.\n *

\n * Takes precedence over {@link #alwaysConcurrent()}.\n */\n public static ConcurrencyHint neverConcurrent() {\n return NEVER_CONCURRENT;\n }\n\n private final Object value;\n\n private static final ConcurrencyHint NEVER_CONCURRENT = new ConcurrencyHint(new Object()) {\n\n @Override\n public String toString() {\n return \"ConcurrencyHint.NEVER_CONCURRENT\";\n }\n };\n\n private static final ConcurrencyHint ALWAYS_CONCURRENT = new ConcurrencyHint(new Object()) {\n\n ", "post_mask_code": "{\n return \"ConcurrencyHint.ALWAYS_CONCURRENT\";\n }\n };\n\n private ConcurrencyHint(Object value) {\n this.value = requireNonNull(value);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ConcurrencyHint that = (ConcurrencyHint) o;\n return value.equals(that.value);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(value);\n }\n\n @Override\n public String toString() {\n return \"ConcurrencyHint{\" + \"value=\" + value + '}';\n }\n}\n"} {"task_id": "Java_2297", "language": "Java", "task_type": "method_body", "source_file": "java/github/couchbase/kafka-connect-couchbase/src/main/java/com/couchbase/connect/kafka/handler/sink/ConcurrencyHint.java", "mask_start_position": 2567, "mask_end_position": 2794, "canonical_solution": "{\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ConcurrencyHint that = (ConcurrencyHint) o;\n return value.equals(that.value);\n }", "pre_mask_code": "package com.couchbase.connect.kafka.handler.sink;\n\nimport java.util.HashSet;\nimport java.util.Objects;\nimport static java.util.Objects.requireNonNull;\n\n/**\n * Used for concurrency control. Determines which actions may\n * be performed concurrently.\n *

\n * If two actions have concurrency hints with equal values,\n * the first action must complete before the second is started.\n *

\n * Example: Using document IDs as hint values is a way to express\n * the constraint that different documents may be updated in parallel,\n * but updates to the same document must be applied sequentially.\n *\n * @see #of(Object)\n * @see #alwaysConcurrent()\n * @see #neverConcurrent()\n */\npublic class ConcurrencyHint {\n\n /**\n * Indicates the action may be performed concurrently with any other action\n * whose hint value is NOT EQUAL to this one.\n *\n * @param value the value that must be unique withing a batch of concurrent operations.\n * Must be the sort of thing you can safely insert in a {@link HashSet}.\n */\n public static ConcurrencyHint of(Object value) {\n return new ConcurrencyHint(value);\n }\n\n /**\n * Returns a special hint indicating the action may be performed concurrently\n * with any other action, regardless of the other action's concurrency hint.\n */\n public static ConcurrencyHint alwaysConcurrent() {\n return ALWAYS_CONCURRENT;\n }\n\n /**\n * Returns a special hint indicating the action must never be performed concurrently\n * with any other action, regardless of the other action's concurrency hint.\n *

\n * In other words, all prior actions will be completed before this action is performed,\n * and this action will be completed before any subsequent actions are performed.\n *

\n * Takes precedence over {@link #alwaysConcurrent()}.\n */\n public static ConcurrencyHint neverConcurrent() {\n return NEVER_CONCURRENT;\n }\n\n private final Object value;\n\n private static final ConcurrencyHint NEVER_CONCURRENT = new ConcurrencyHint(new Object()) {\n\n @Override\n public String toString() {\n return \"ConcurrencyHint.NEVER_CONCURRENT\";\n }\n };\n\n private static final ConcurrencyHint ALWAYS_CONCURRENT = new ConcurrencyHint(new Object()) {\n\n @Override\n public String toString() {\n return \"ConcurrencyHint.ALWAYS_CONCURRENT\";\n }\n };\n\n private ConcurrencyHint(Object value) {\n this.value = requireNonNull(value);\n }\n\n @Override\n public boolean equals(Object o) ", "post_mask_code": "\n\n @Override\n public int hashCode() {\n return Objects.hash(value);\n }\n\n @Override\n public String toString() {\n return \"ConcurrencyHint{\" + \"value=\" + value + '}';\n }\n}\n"} {"task_id": "Java_2298", "language": "Java", "task_type": "single_line", "source_file": "java/github/couchbase/kafka-connect-couchbase/src/main/java/com/couchbase/connect/kafka/handler/sink/ConcurrencyHint.java", "mask_start_position": 2383, "mask_end_position": 2403, "canonical_solution": ".ALWAYS_CONCURRENT\";", "pre_mask_code": "package com.couchbase.connect.kafka.handler.sink;\n\nimport java.util.HashSet;\nimport java.util.Objects;\nimport static java.util.Objects.requireNonNull;\n\n/**\n * Used for concurrency control. Determines which actions may\n * be performed concurrently.\n *

\n * If two actions have concurrency hints with equal values,\n * the first action must complete before the second is started.\n *

\n * Example: Using document IDs as hint values is a way to express\n * the constraint that different documents may be updated in parallel,\n * but updates to the same document must be applied sequentially.\n *\n * @see #of(Object)\n * @see #alwaysConcurrent()\n * @see #neverConcurrent()\n */\npublic class ConcurrencyHint {\n\n /**\n * Indicates the action may be performed concurrently with any other action\n * whose hint value is NOT EQUAL to this one.\n *\n * @param value the value that must be unique withing a batch of concurrent operations.\n * Must be the sort of thing you can safely insert in a {@link HashSet}.\n */\n public static ConcurrencyHint of(Object value) {\n return new ConcurrencyHint(value);\n }\n\n /**\n * Returns a special hint indicating the action may be performed concurrently\n * with any other action, regardless of the other action's concurrency hint.\n */\n public static ConcurrencyHint alwaysConcurrent() {\n return ALWAYS_CONCURRENT;\n }\n\n /**\n * Returns a special hint indicating the action must never be performed concurrently\n * with any other action, regardless of the other action's concurrency hint.\n *

\n * In other words, all prior actions will be completed before this action is performed,\n * and this action will be completed before any subsequent actions are performed.\n *

\n * Takes precedence over {@link #alwaysConcurrent()}.\n */\n public static ConcurrencyHint neverConcurrent() {\n return NEVER_CONCURRENT;\n }\n\n private final Object value;\n\n private static final ConcurrencyHint NEVER_CONCURRENT = new ConcurrencyHint(new Object()) {\n\n @Override\n public String toString() {\n return \"ConcurrencyHint.NEVER_CONCURRENT\";\n }\n };\n\n private static final ConcurrencyHint ALWAYS_CONCURRENT = new ConcurrencyHint(new Object()) {\n\n @Override\n public String toString() {\n return \"ConcurrencyHint", "post_mask_code": "\n }\n };\n\n private ConcurrencyHint(Object value) {\n this.value = requireNonNull(value);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ConcurrencyHint that = (ConcurrencyHint) o;\n return value.equals(that.value);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(value);\n }\n\n @Override\n public String toString() {\n return \"ConcurrencyHint{\" + \"value=\" + value + '}';\n }\n}\n"} {"task_id": "Java_2299", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/couchbase/kafka-connect-couchbase/src/main/java/com/couchbase/connect/kafka/handler/sink/ConcurrencyHint.java", "mask_start_position": 1311, "mask_end_position": 1401, "canonical_solution": "public static ConcurrencyHint alwaysConcurrent() {\n return ALWAYS_CONCURRENT;\n }", "pre_mask_code": "package com.couchbase.connect.kafka.handler.sink;\n\nimport java.util.HashSet;\nimport java.util.Objects;\nimport static java.util.Objects.requireNonNull;\n\n/**\n * Used for concurrency control. Determines which actions may\n * be performed concurrently.\n *

\n * If two actions have concurrency hints with equal values,\n * the first action must complete before the second is started.\n *

\n * Example: Using document IDs as hint values is a way to express\n * the constraint that different documents may be updated in parallel,\n * but updates to the same document must be applied sequentially.\n *\n * @see #of(Object)\n * @see #alwaysConcurrent()\n * @see #neverConcurrent()\n */\npublic class ConcurrencyHint {\n\n /**\n * Indicates the action may be performed concurrently with any other action\n * whose hint value is NOT EQUAL to this one.\n *\n * @param value the value that must be unique withing a batch of concurrent operations.\n * Must be the sort of thing you can safely insert in a {@link HashSet}.\n */\n public static ConcurrencyHint of(Object value) {\n return new ConcurrencyHint(value);\n }\n\n /**\n * Returns a special hint indicating the action may be performed concurrently\n * with any other action, regardless of the other action's concurrency hint.\n */\n ", "post_mask_code": "\n\n /**\n * Returns a special hint indicating the action must never be performed concurrently\n * with any other action, regardless of the other action's concurrency hint.\n *

\n * In other words, all prior actions will be completed before this action is performed,\n * and this action will be completed before any subsequent actions are performed.\n *

\n * Takes precedence over {@link #alwaysConcurrent()}.\n */\n public static ConcurrencyHint neverConcurrent() {\n return NEVER_CONCURRENT;\n }\n\n private final Object value;\n\n private static final ConcurrencyHint NEVER_CONCURRENT = new ConcurrencyHint(new Object()) {\n\n @Override\n public String toString() {\n return \"ConcurrencyHint.NEVER_CONCURRENT\";\n }\n };\n\n private static final ConcurrencyHint ALWAYS_CONCURRENT = new ConcurrencyHint(new Object()) {\n\n @Override\n public String toString() {\n return \"ConcurrencyHint.ALWAYS_CONCURRENT\";\n }\n };\n\n private ConcurrencyHint(Object value) {\n this.value = requireNonNull(value);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n ConcurrencyHint that = (ConcurrencyHint) o;\n return value.equals(that.value);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(value);\n }\n\n @Override\n public String toString() {\n return \"ConcurrencyHint{\" + \"value=\" + value + '}';\n }\n}\n"} {"task_id": "Java_2300", "language": "Java", "task_type": "method_signature", "source_file": "java/github/quelea-projection/Quelea/Quelea/src/main/java/org/quelea/data/bible/BibleSearchDialog.java", "mask_start_position": 6090, "mask_end_position": 6111, "canonical_solution": "public void cancel() ", "pre_mask_code": "/*\n * This file is part of Quelea, free projection software for churches.\n * \n *\n */\npackage org.quelea.data.bible;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport javafx.application.Platform;\nimport javafx.beans.value.ChangeListener;\nimport javafx.beans.value.ObservableValue;\nimport javafx.event.ActionEvent;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.control.ComboBox;\nimport javafx.scene.control.ScrollPane;\nimport javafx.scene.control.SplitPane;\nimport javafx.scene.control.TextField;\nimport javafx.scene.image.Image;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.layout.BorderPane;\nimport javafx.scene.layout.FlowPane;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.StackPane;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.Text;\nimport javafx.stage.Stage;\nimport javafx.stage.WindowEvent;\nimport org.quelea.data.displayable.BiblePassage;\nimport org.quelea.services.languages.LabelGrabber;\nimport org.quelea.services.utils.QueleaProperties;\nimport org.quelea.windows.main.QueleaApp;\nimport org.quelea.windows.main.widgets.LoadingPane;\n\n/**\n * A dialog that can be used for searching for bible passages.\n *

\n * @author mjrb5\n */\npublic class BibleSearchDialog extends Stage implements BibleChangeListener {\n\n private TextField searchField;\n\n private BibleSearchTreeView searchResults;\n\n private ComboBox bibles;\n\n private ScrollPane scrollPane;\n\n private LoadingPane overlay;\n\n private FlowPane chapterPane;\n\n private final Button addToSchedule;\n\n private final Text resultsField;\n\n /**\n * Create a new bible searcher dialog.\n */\n public BibleSearchDialog() {\n BorderPane mainPane = new BorderPane();\n setTitle(LabelGrabber.INSTANCE.getLabel(\"bible.search.title\"));\n getIcons().add(new Image(\"file:icons/search.png\"));\n overlay = new LoadingPane();\n searchField = new TextField();\n bibles = new ComboBox<>();\n bibles.setEditable(false);\n chapterPane = new FlowPane();\n scrollPane = new ScrollPane();\n scrollPane.setContent(chapterPane);\n searchResults = new BibleSearchTreeView(scrollPane, bibles);\n resultsField = new Text(\" \" + LabelGrabber.INSTANCE.getLabel(\"bible.search.keep.typing\"));\n resultsField.setFont(Font.font(\"Sans\", 14));\n resultsField.getStyleClass().add(\"text\");\n addToSchedule = new Button(LabelGrabber.INSTANCE.getLabel(\"add.to.schedule.text\"), new ImageView(new Image(\"file:icons/tick.png\")));\n BibleManager.get().registerBibleChangeListener(this);\n updateBibles();\n // top panel\n HBox northPanel = new HBox();\n northPanel.setPadding(new Insets(5, 5, 5, 5));\n northPanel.getChildren().addAll(bibles, searchField, addToSchedule, resultsField);\n mainPane.setTop(northPanel);\n // center panel\n StackPane searchPane = new StackPane();\n searchPane.getChildren().addAll(searchResults, overlay);\n SplitPane centerPanel = new SplitPane();\n centerPanel.setDividerPosition(0, 0.3);\n centerPanel.getItems().addAll(searchPane, scrollPane);\n mainPane.setCenter(centerPanel);\n // Sizing\n this.setHeight(600);\n this.setWidth(800);\n this.setMinHeight(300);\n this.setMinWidth(500);\n // Event handlers\n bibles.setOnAction((javafx.event.ActionEvent t) -> {\n searchResults.resetRoot();\n update();\n });\n searchField.textProperty().addListener((ObservableValue ov, String t, String t1) -> {\n update();\n });\n addToSchedule.setOnAction((ActionEvent t) -> {\n if (searchResults.getSelectionModel().getSelectedItem().getValue() instanceof BibleVerse) {\n BibleChapter chap = (BibleChapter) searchResults.getSelectionModel().getSelectedItem().getValue().getParent();\n Bible bib = (Bible) chap.getParent().getParent();\n BiblePassage passage = new BiblePassage(bib.getBibleName(), chap.getBook() + \" \" + chap.toString(), chap.getVerses(), false);\n QueleaApp.get().getMainWindow().getMainPanel().getSchedulePanel().getScheduleList().add(passage);\n }\n });\n setOnShown((WindowEvent event) -> {\n if (!BibleManager.get().isIndexInit()) {\n BibleManager.get().refreshAndLoad();\n }\n });\n reset();\n Scene scene = new Scene(mainPane);\n if (QueleaProperties.get().getUseDarkTheme()) {\n scene.getStylesheets().add(\"org/modena_dark.css\");\n }\n setScene(scene);\n }\n\n public final void reset() {\n searchField.setText(LabelGrabber.INSTANCE.getLabel(\"initial.search.text\"));\n searchField.focusedProperty().addListener(new ChangeListener() {\n\n @Override\n public void changed(ObservableValue ov, Boolean t, Boolean t1) {\n if (t1) {\n searchField.setText(\"\");\n searchField.focusedProperty().removeListener(this);\n }\n }\n });\n searchField.setDisable(true);\n BibleManager.get().runOnIndexInit(() -> {\n searchField.setDisable(false);\n });\n }\n\n private ExecutorService updateExecutor = Executors.newSingleThreadExecutor();\n\n private ExecRunnable lastUpdateRunnable = null;\n\n private interface ExecRunnable extends Runnable {\n\n void cancel();\n }\n\n /**\n * Update the results based on the entered text.\n */\n private void update() {\n final String text = searchField.getText();\n if (text.length() > 3) {\n if (BibleManager.get().isIndexInit()) {\n searchResults.reset();\n overlay.show();\n ExecRunnable execRunnable = new ExecRunnable() {\n\n private volatile boolean cancel = false;\n\n ", "post_mask_code": "{\n cancel = true;\n }\n\n public void run() {\n if (cancel) {\n return;\n }\n final BibleChapter[] results = BibleManager.get().getIndex().filter(text, null);\n Platform.runLater(() -> {\n searchResults.reset();\n if (!text.trim().isEmpty()) {\n for (BibleChapter chapter : results) {\n if (bibles.getSelectionModel().getSelectedIndex() == 0 || chapter.getBook().getBible().getName().equals(bibles.getSelectionModel().getSelectedItem())) {\n for (BibleVerse verse : chapter.getVerses()) {\n if (verse.getText().toLowerCase().contains(text.toLowerCase())) {\n searchResults.add(verse);\n }\n }\n }\n }\n }\n overlay.hide();\n String resultsfoundSuffix = LabelGrabber.INSTANCE.getLabel(\"bible.search.results.found\");\n if (searchResults.size() == 1 && LabelGrabber.INSTANCE.isLocallyDefined(\"bible.search.result.found\")) {\n resultsfoundSuffix = LabelGrabber.INSTANCE.getLabel(\"bible.search.result.found\");\n }\n resultsField.setText(\" \" + searchResults.size() + \" \" + resultsfoundSuffix);\n });\n }\n };\n if (lastUpdateRunnable != null) {\n lastUpdateRunnable.cancel();\n }\n lastUpdateRunnable = execRunnable;\n updateExecutor.submit(execRunnable);\n }\n }\n searchResults.reset();\n resultsField.setText(\" \" + LabelGrabber.INSTANCE.getLabel(\"bible.search.keep.typing\"));\n chapterPane.getChildren().clear();\n }\n\n /**\n * Update the list of bibles on this search dialog.\n */\n @Override\n public final void updateBibles() {\n bibles.itemsProperty().get().clear();\n bibles.itemsProperty().get().add(LabelGrabber.INSTANCE.getLabel(\"all.text\"));\n for (Bible bible : BibleManager.get().getBibles()) {\n bibles.itemsProperty().get().add(bible.getName());\n }\n bibles.getSelectionModel().selectFirst();\n }\n}\n"} {"task_id": "Java_2301", "language": "Java", "task_type": "method_body", "source_file": "java/github/quelea-projection/Quelea/Quelea/src/main/java/org/quelea/data/bible/BibleSearchDialog.java", "mask_start_position": 6111, "mask_end_position": 6173, "canonical_solution": "{\n cancel = true;\n }", "pre_mask_code": "/*\n * This file is part of Quelea, free projection software for churches.\n * \n *\n */\npackage org.quelea.data.bible;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport javafx.application.Platform;\nimport javafx.beans.value.ChangeListener;\nimport javafx.beans.value.ObservableValue;\nimport javafx.event.ActionEvent;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.control.ComboBox;\nimport javafx.scene.control.ScrollPane;\nimport javafx.scene.control.SplitPane;\nimport javafx.scene.control.TextField;\nimport javafx.scene.image.Image;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.layout.BorderPane;\nimport javafx.scene.layout.FlowPane;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.StackPane;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.Text;\nimport javafx.stage.Stage;\nimport javafx.stage.WindowEvent;\nimport org.quelea.data.displayable.BiblePassage;\nimport org.quelea.services.languages.LabelGrabber;\nimport org.quelea.services.utils.QueleaProperties;\nimport org.quelea.windows.main.QueleaApp;\nimport org.quelea.windows.main.widgets.LoadingPane;\n\n/**\n * A dialog that can be used for searching for bible passages.\n *

\n * @author mjrb5\n */\npublic class BibleSearchDialog extends Stage implements BibleChangeListener {\n\n private TextField searchField;\n\n private BibleSearchTreeView searchResults;\n\n private ComboBox bibles;\n\n private ScrollPane scrollPane;\n\n private LoadingPane overlay;\n\n private FlowPane chapterPane;\n\n private final Button addToSchedule;\n\n private final Text resultsField;\n\n /**\n * Create a new bible searcher dialog.\n */\n public BibleSearchDialog() {\n BorderPane mainPane = new BorderPane();\n setTitle(LabelGrabber.INSTANCE.getLabel(\"bible.search.title\"));\n getIcons().add(new Image(\"file:icons/search.png\"));\n overlay = new LoadingPane();\n searchField = new TextField();\n bibles = new ComboBox<>();\n bibles.setEditable(false);\n chapterPane = new FlowPane();\n scrollPane = new ScrollPane();\n scrollPane.setContent(chapterPane);\n searchResults = new BibleSearchTreeView(scrollPane, bibles);\n resultsField = new Text(\" \" + LabelGrabber.INSTANCE.getLabel(\"bible.search.keep.typing\"));\n resultsField.setFont(Font.font(\"Sans\", 14));\n resultsField.getStyleClass().add(\"text\");\n addToSchedule = new Button(LabelGrabber.INSTANCE.getLabel(\"add.to.schedule.text\"), new ImageView(new Image(\"file:icons/tick.png\")));\n BibleManager.get().registerBibleChangeListener(this);\n updateBibles();\n // top panel\n HBox northPanel = new HBox();\n northPanel.setPadding(new Insets(5, 5, 5, 5));\n northPanel.getChildren().addAll(bibles, searchField, addToSchedule, resultsField);\n mainPane.setTop(northPanel);\n // center panel\n StackPane searchPane = new StackPane();\n searchPane.getChildren().addAll(searchResults, overlay);\n SplitPane centerPanel = new SplitPane();\n centerPanel.setDividerPosition(0, 0.3);\n centerPanel.getItems().addAll(searchPane, scrollPane);\n mainPane.setCenter(centerPanel);\n // Sizing\n this.setHeight(600);\n this.setWidth(800);\n this.setMinHeight(300);\n this.setMinWidth(500);\n // Event handlers\n bibles.setOnAction((javafx.event.ActionEvent t) -> {\n searchResults.resetRoot();\n update();\n });\n searchField.textProperty().addListener((ObservableValue ov, String t, String t1) -> {\n update();\n });\n addToSchedule.setOnAction((ActionEvent t) -> {\n if (searchResults.getSelectionModel().getSelectedItem().getValue() instanceof BibleVerse) {\n BibleChapter chap = (BibleChapter) searchResults.getSelectionModel().getSelectedItem().getValue().getParent();\n Bible bib = (Bible) chap.getParent().getParent();\n BiblePassage passage = new BiblePassage(bib.getBibleName(), chap.getBook() + \" \" + chap.toString(), chap.getVerses(), false);\n QueleaApp.get().getMainWindow().getMainPanel().getSchedulePanel().getScheduleList().add(passage);\n }\n });\n setOnShown((WindowEvent event) -> {\n if (!BibleManager.get().isIndexInit()) {\n BibleManager.get().refreshAndLoad();\n }\n });\n reset();\n Scene scene = new Scene(mainPane);\n if (QueleaProperties.get().getUseDarkTheme()) {\n scene.getStylesheets().add(\"org/modena_dark.css\");\n }\n setScene(scene);\n }\n\n public final void reset() {\n searchField.setText(LabelGrabber.INSTANCE.getLabel(\"initial.search.text\"));\n searchField.focusedProperty().addListener(new ChangeListener() {\n\n @Override\n public void changed(ObservableValue ov, Boolean t, Boolean t1) {\n if (t1) {\n searchField.setText(\"\");\n searchField.focusedProperty().removeListener(this);\n }\n }\n });\n searchField.setDisable(true);\n BibleManager.get().runOnIndexInit(() -> {\n searchField.setDisable(false);\n });\n }\n\n private ExecutorService updateExecutor = Executors.newSingleThreadExecutor();\n\n private ExecRunnable lastUpdateRunnable = null;\n\n private interface ExecRunnable extends Runnable {\n\n void cancel();\n }\n\n /**\n * Update the results based on the entered text.\n */\n private void update() {\n final String text = searchField.getText();\n if (text.length() > 3) {\n if (BibleManager.get().isIndexInit()) {\n searchResults.reset();\n overlay.show();\n ExecRunnable execRunnable = new ExecRunnable() {\n\n private volatile boolean cancel = false;\n\n public void cancel() ", "post_mask_code": "\n\n public void run() {\n if (cancel) {\n return;\n }\n final BibleChapter[] results = BibleManager.get().getIndex().filter(text, null);\n Platform.runLater(() -> {\n searchResults.reset();\n if (!text.trim().isEmpty()) {\n for (BibleChapter chapter : results) {\n if (bibles.getSelectionModel().getSelectedIndex() == 0 || chapter.getBook().getBible().getName().equals(bibles.getSelectionModel().getSelectedItem())) {\n for (BibleVerse verse : chapter.getVerses()) {\n if (verse.getText().toLowerCase().contains(text.toLowerCase())) {\n searchResults.add(verse);\n }\n }\n }\n }\n }\n overlay.hide();\n String resultsfoundSuffix = LabelGrabber.INSTANCE.getLabel(\"bible.search.results.found\");\n if (searchResults.size() == 1 && LabelGrabber.INSTANCE.isLocallyDefined(\"bible.search.result.found\")) {\n resultsfoundSuffix = LabelGrabber.INSTANCE.getLabel(\"bible.search.result.found\");\n }\n resultsField.setText(\" \" + searchResults.size() + \" \" + resultsfoundSuffix);\n });\n }\n };\n if (lastUpdateRunnable != null) {\n lastUpdateRunnable.cancel();\n }\n lastUpdateRunnable = execRunnable;\n updateExecutor.submit(execRunnable);\n }\n }\n searchResults.reset();\n resultsField.setText(\" \" + LabelGrabber.INSTANCE.getLabel(\"bible.search.keep.typing\"));\n chapterPane.getChildren().clear();\n }\n\n /**\n * Update the list of bibles on this search dialog.\n */\n @Override\n public final void updateBibles() {\n bibles.itemsProperty().get().clear();\n bibles.itemsProperty().get().add(LabelGrabber.INSTANCE.getLabel(\"all.text\"));\n for (Bible bible : BibleManager.get().getBibles()) {\n bibles.itemsProperty().get().add(bible.getName());\n }\n bibles.getSelectionModel().selectFirst();\n }\n}\n"} {"task_id": "Java_2302", "language": "Java", "task_type": "single_line", "source_file": "java/github/quelea-projection/Quelea/Quelea/src/main/java/org/quelea/data/bible/BibleSearchDialog.java", "mask_start_position": 5297, "mask_end_position": 5304, "canonical_solution": "(true);", "pre_mask_code": "/*\n * This file is part of Quelea, free projection software for churches.\n * \n *\n */\npackage org.quelea.data.bible;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport javafx.application.Platform;\nimport javafx.beans.value.ChangeListener;\nimport javafx.beans.value.ObservableValue;\nimport javafx.event.ActionEvent;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.control.ComboBox;\nimport javafx.scene.control.ScrollPane;\nimport javafx.scene.control.SplitPane;\nimport javafx.scene.control.TextField;\nimport javafx.scene.image.Image;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.layout.BorderPane;\nimport javafx.scene.layout.FlowPane;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.StackPane;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.Text;\nimport javafx.stage.Stage;\nimport javafx.stage.WindowEvent;\nimport org.quelea.data.displayable.BiblePassage;\nimport org.quelea.services.languages.LabelGrabber;\nimport org.quelea.services.utils.QueleaProperties;\nimport org.quelea.windows.main.QueleaApp;\nimport org.quelea.windows.main.widgets.LoadingPane;\n\n/**\n * A dialog that can be used for searching for bible passages.\n *

\n * @author mjrb5\n */\npublic class BibleSearchDialog extends Stage implements BibleChangeListener {\n\n private TextField searchField;\n\n private BibleSearchTreeView searchResults;\n\n private ComboBox bibles;\n\n private ScrollPane scrollPane;\n\n private LoadingPane overlay;\n\n private FlowPane chapterPane;\n\n private final Button addToSchedule;\n\n private final Text resultsField;\n\n /**\n * Create a new bible searcher dialog.\n */\n public BibleSearchDialog() {\n BorderPane mainPane = new BorderPane();\n setTitle(LabelGrabber.INSTANCE.getLabel(\"bible.search.title\"));\n getIcons().add(new Image(\"file:icons/search.png\"));\n overlay = new LoadingPane();\n searchField = new TextField();\n bibles = new ComboBox<>();\n bibles.setEditable(false);\n chapterPane = new FlowPane();\n scrollPane = new ScrollPane();\n scrollPane.setContent(chapterPane);\n searchResults = new BibleSearchTreeView(scrollPane, bibles);\n resultsField = new Text(\" \" + LabelGrabber.INSTANCE.getLabel(\"bible.search.keep.typing\"));\n resultsField.setFont(Font.font(\"Sans\", 14));\n resultsField.getStyleClass().add(\"text\");\n addToSchedule = new Button(LabelGrabber.INSTANCE.getLabel(\"add.to.schedule.text\"), new ImageView(new Image(\"file:icons/tick.png\")));\n BibleManager.get().registerBibleChangeListener(this);\n updateBibles();\n // top panel\n HBox northPanel = new HBox();\n northPanel.setPadding(new Insets(5, 5, 5, 5));\n northPanel.getChildren().addAll(bibles, searchField, addToSchedule, resultsField);\n mainPane.setTop(northPanel);\n // center panel\n StackPane searchPane = new StackPane();\n searchPane.getChildren().addAll(searchResults, overlay);\n SplitPane centerPanel = new SplitPane();\n centerPanel.setDividerPosition(0, 0.3);\n centerPanel.getItems().addAll(searchPane, scrollPane);\n mainPane.setCenter(centerPanel);\n // Sizing\n this.setHeight(600);\n this.setWidth(800);\n this.setMinHeight(300);\n this.setMinWidth(500);\n // Event handlers\n bibles.setOnAction((javafx.event.ActionEvent t) -> {\n searchResults.resetRoot();\n update();\n });\n searchField.textProperty().addListener((ObservableValue ov, String t, String t1) -> {\n update();\n });\n addToSchedule.setOnAction((ActionEvent t) -> {\n if (searchResults.getSelectionModel().getSelectedItem().getValue() instanceof BibleVerse) {\n BibleChapter chap = (BibleChapter) searchResults.getSelectionModel().getSelectedItem().getValue().getParent();\n Bible bib = (Bible) chap.getParent().getParent();\n BiblePassage passage = new BiblePassage(bib.getBibleName(), chap.getBook() + \" \" + chap.toString(), chap.getVerses(), false);\n QueleaApp.get().getMainWindow().getMainPanel().getSchedulePanel().getScheduleList().add(passage);\n }\n });\n setOnShown((WindowEvent event) -> {\n if (!BibleManager.get().isIndexInit()) {\n BibleManager.get().refreshAndLoad();\n }\n });\n reset();\n Scene scene = new Scene(mainPane);\n if (QueleaProperties.get().getUseDarkTheme()) {\n scene.getStylesheets().add(\"org/modena_dark.css\");\n }\n setScene(scene);\n }\n\n public final void reset() {\n searchField.setText(LabelGrabber.INSTANCE.getLabel(\"initial.search.text\"));\n searchField.focusedProperty().addListener(new ChangeListener() {\n\n @Override\n public void changed(ObservableValue ov, Boolean t, Boolean t1) {\n if (t1) {\n searchField.setText(\"\");\n searchField.focusedProperty().removeListener(this);\n }\n }\n });\n searchField.setDisable", "post_mask_code": "\n BibleManager.get().runOnIndexInit(() -> {\n searchField.setDisable(false);\n });\n }\n\n private ExecutorService updateExecutor = Executors.newSingleThreadExecutor();\n\n private ExecRunnable lastUpdateRunnable = null;\n\n private interface ExecRunnable extends Runnable {\n\n void cancel();\n }\n\n /**\n * Update the results based on the entered text.\n */\n private void update() {\n final String text = searchField.getText();\n if (text.length() > 3) {\n if (BibleManager.get().isIndexInit()) {\n searchResults.reset();\n overlay.show();\n ExecRunnable execRunnable = new ExecRunnable() {\n\n private volatile boolean cancel = false;\n\n public void cancel() {\n cancel = true;\n }\n\n public void run() {\n if (cancel) {\n return;\n }\n final BibleChapter[] results = BibleManager.get().getIndex().filter(text, null);\n Platform.runLater(() -> {\n searchResults.reset();\n if (!text.trim().isEmpty()) {\n for (BibleChapter chapter : results) {\n if (bibles.getSelectionModel().getSelectedIndex() == 0 || chapter.getBook().getBible().getName().equals(bibles.getSelectionModel().getSelectedItem())) {\n for (BibleVerse verse : chapter.getVerses()) {\n if (verse.getText().toLowerCase().contains(text.toLowerCase())) {\n searchResults.add(verse);\n }\n }\n }\n }\n }\n overlay.hide();\n String resultsfoundSuffix = LabelGrabber.INSTANCE.getLabel(\"bible.search.results.found\");\n if (searchResults.size() == 1 && LabelGrabber.INSTANCE.isLocallyDefined(\"bible.search.result.found\")) {\n resultsfoundSuffix = LabelGrabber.INSTANCE.getLabel(\"bible.search.result.found\");\n }\n resultsField.setText(\" \" + searchResults.size() + \" \" + resultsfoundSuffix);\n });\n }\n };\n if (lastUpdateRunnable != null) {\n lastUpdateRunnable.cancel();\n }\n lastUpdateRunnable = execRunnable;\n updateExecutor.submit(execRunnable);\n }\n }\n searchResults.reset();\n resultsField.setText(\" \" + LabelGrabber.INSTANCE.getLabel(\"bible.search.keep.typing\"));\n chapterPane.getChildren().clear();\n }\n\n /**\n * Update the list of bibles on this search dialog.\n */\n @Override\n public final void updateBibles() {\n bibles.itemsProperty().get().clear();\n bibles.itemsProperty().get().add(LabelGrabber.INSTANCE.getLabel(\"all.text\"));\n for (Bible bible : BibleManager.get().getBibles()) {\n bibles.itemsProperty().get().add(bible.getName());\n }\n bibles.getSelectionModel().selectFirst();\n }\n}\n"} {"task_id": "Java_2303", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/quelea-projection/Quelea/Quelea/src/main/java/org/quelea/data/bible/BibleSearchDialog.java", "mask_start_position": 8410, "mask_end_position": 8780, "canonical_solution": "@Override\n public final void updateBibles() {\n bibles.itemsProperty().get().clear();\n bibles.itemsProperty().get().add(LabelGrabber.INSTANCE.getLabel(\"all.text\"));\n for (Bible bible : BibleManager.get().getBibles()) {\n bibles.itemsProperty().get().add(bible.getName());\n }\n bibles.getSelectionModel().selectFirst();\n }", "pre_mask_code": "/*\n * This file is part of Quelea, free projection software for churches.\n * \n *\n */\npackage org.quelea.data.bible;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport javafx.application.Platform;\nimport javafx.beans.value.ChangeListener;\nimport javafx.beans.value.ObservableValue;\nimport javafx.event.ActionEvent;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.control.ComboBox;\nimport javafx.scene.control.ScrollPane;\nimport javafx.scene.control.SplitPane;\nimport javafx.scene.control.TextField;\nimport javafx.scene.image.Image;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.layout.BorderPane;\nimport javafx.scene.layout.FlowPane;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.StackPane;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.Text;\nimport javafx.stage.Stage;\nimport javafx.stage.WindowEvent;\nimport org.quelea.data.displayable.BiblePassage;\nimport org.quelea.services.languages.LabelGrabber;\nimport org.quelea.services.utils.QueleaProperties;\nimport org.quelea.windows.main.QueleaApp;\nimport org.quelea.windows.main.widgets.LoadingPane;\n\n/**\n * A dialog that can be used for searching for bible passages.\n *

\n * @author mjrb5\n */\npublic class BibleSearchDialog extends Stage implements BibleChangeListener {\n\n private TextField searchField;\n\n private BibleSearchTreeView searchResults;\n\n private ComboBox bibles;\n\n private ScrollPane scrollPane;\n\n private LoadingPane overlay;\n\n private FlowPane chapterPane;\n\n private final Button addToSchedule;\n\n private final Text resultsField;\n\n /**\n * Create a new bible searcher dialog.\n */\n public BibleSearchDialog() {\n BorderPane mainPane = new BorderPane();\n setTitle(LabelGrabber.INSTANCE.getLabel(\"bible.search.title\"));\n getIcons().add(new Image(\"file:icons/search.png\"));\n overlay = new LoadingPane();\n searchField = new TextField();\n bibles = new ComboBox<>();\n bibles.setEditable(false);\n chapterPane = new FlowPane();\n scrollPane = new ScrollPane();\n scrollPane.setContent(chapterPane);\n searchResults = new BibleSearchTreeView(scrollPane, bibles);\n resultsField = new Text(\" \" + LabelGrabber.INSTANCE.getLabel(\"bible.search.keep.typing\"));\n resultsField.setFont(Font.font(\"Sans\", 14));\n resultsField.getStyleClass().add(\"text\");\n addToSchedule = new Button(LabelGrabber.INSTANCE.getLabel(\"add.to.schedule.text\"), new ImageView(new Image(\"file:icons/tick.png\")));\n BibleManager.get().registerBibleChangeListener(this);\n updateBibles();\n // top panel\n HBox northPanel = new HBox();\n northPanel.setPadding(new Insets(5, 5, 5, 5));\n northPanel.getChildren().addAll(bibles, searchField, addToSchedule, resultsField);\n mainPane.setTop(northPanel);\n // center panel\n StackPane searchPane = new StackPane();\n searchPane.getChildren().addAll(searchResults, overlay);\n SplitPane centerPanel = new SplitPane();\n centerPanel.setDividerPosition(0, 0.3);\n centerPanel.getItems().addAll(searchPane, scrollPane);\n mainPane.setCenter(centerPanel);\n // Sizing\n this.setHeight(600);\n this.setWidth(800);\n this.setMinHeight(300);\n this.setMinWidth(500);\n // Event handlers\n bibles.setOnAction((javafx.event.ActionEvent t) -> {\n searchResults.resetRoot();\n update();\n });\n searchField.textProperty().addListener((ObservableValue ov, String t, String t1) -> {\n update();\n });\n addToSchedule.setOnAction((ActionEvent t) -> {\n if (searchResults.getSelectionModel().getSelectedItem().getValue() instanceof BibleVerse) {\n BibleChapter chap = (BibleChapter) searchResults.getSelectionModel().getSelectedItem().getValue().getParent();\n Bible bib = (Bible) chap.getParent().getParent();\n BiblePassage passage = new BiblePassage(bib.getBibleName(), chap.getBook() + \" \" + chap.toString(), chap.getVerses(), false);\n QueleaApp.get().getMainWindow().getMainPanel().getSchedulePanel().getScheduleList().add(passage);\n }\n });\n setOnShown((WindowEvent event) -> {\n if (!BibleManager.get().isIndexInit()) {\n BibleManager.get().refreshAndLoad();\n }\n });\n reset();\n Scene scene = new Scene(mainPane);\n if (QueleaProperties.get().getUseDarkTheme()) {\n scene.getStylesheets().add(\"org/modena_dark.css\");\n }\n setScene(scene);\n }\n\n public final void reset() {\n searchField.setText(LabelGrabber.INSTANCE.getLabel(\"initial.search.text\"));\n searchField.focusedProperty().addListener(new ChangeListener() {\n\n @Override\n public void changed(ObservableValue ov, Boolean t, Boolean t1) {\n if (t1) {\n searchField.setText(\"\");\n searchField.focusedProperty().removeListener(this);\n }\n }\n });\n searchField.setDisable(true);\n BibleManager.get().runOnIndexInit(() -> {\n searchField.setDisable(false);\n });\n }\n\n private ExecutorService updateExecutor = Executors.newSingleThreadExecutor();\n\n private ExecRunnable lastUpdateRunnable = null;\n\n private interface ExecRunnable extends Runnable {\n\n void cancel();\n }\n\n /**\n * Update the results based on the entered text.\n */\n private void update() {\n final String text = searchField.getText();\n if (text.length() > 3) {\n if (BibleManager.get().isIndexInit()) {\n searchResults.reset();\n overlay.show();\n ExecRunnable execRunnable = new ExecRunnable() {\n\n private volatile boolean cancel = false;\n\n public void cancel() {\n cancel = true;\n }\n\n public void run() {\n if (cancel) {\n return;\n }\n final BibleChapter[] results = BibleManager.get().getIndex().filter(text, null);\n Platform.runLater(() -> {\n searchResults.reset();\n if (!text.trim().isEmpty()) {\n for (BibleChapter chapter : results) {\n if (bibles.getSelectionModel().getSelectedIndex() == 0 || chapter.getBook().getBible().getName().equals(bibles.getSelectionModel().getSelectedItem())) {\n for (BibleVerse verse : chapter.getVerses()) {\n if (verse.getText().toLowerCase().contains(text.toLowerCase())) {\n searchResults.add(verse);\n }\n }\n }\n }\n }\n overlay.hide();\n String resultsfoundSuffix = LabelGrabber.INSTANCE.getLabel(\"bible.search.results.found\");\n if (searchResults.size() == 1 && LabelGrabber.INSTANCE.isLocallyDefined(\"bible.search.result.found\")) {\n resultsfoundSuffix = LabelGrabber.INSTANCE.getLabel(\"bible.search.result.found\");\n }\n resultsField.setText(\" \" + searchResults.size() + \" \" + resultsfoundSuffix);\n });\n }\n };\n if (lastUpdateRunnable != null) {\n lastUpdateRunnable.cancel();\n }\n lastUpdateRunnable = execRunnable;\n updateExecutor.submit(execRunnable);\n }\n }\n searchResults.reset();\n resultsField.setText(\" \" + LabelGrabber.INSTANCE.getLabel(\"bible.search.keep.typing\"));\n chapterPane.getChildren().clear();\n }\n\n /**\n * Update the list of bibles on this search dialog.\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2304", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/jaxws/wsa/w2j/document/literal/delimiter/Client.java", "mask_start_position": 2906, "mask_end_position": 2952, "canonical_solution": "private void getPortJavaEE() throws Exception ", "pre_mask_code": "package com.sun.ts.tests.jaxws.wsa.w2j.document.literal.delimiter;\n\nimport com.sun.ts.lib.util.*;\nimport com.sun.ts.lib.porting.*;\nimport com.sun.ts.lib.harness.*;\nimport jakarta.xml.soap.SOAPBody;\nimport jakarta.xml.soap.SOAPException;\nimport com.sun.ts.tests.jaxws.wsa.common.ActionNotSupportedException;\nimport com.sun.ts.tests.jaxws.common.*;\nimport java.net.URL;\nimport jakarta.xml.ws.*;\nimport jakarta.xml.soap.*;\nimport java.util.Properties;\nimport javax.xml.namespace.QName;\nimport com.sun.javatest.Status;\nimport javax.naming.InitialContext;\n\npublic class Client extends ServiceEETest {\n\n // The webserver defaults (overidden by harness properties)\n private static final String PROTOCOL = \"http\";\n\n private static final String HOSTNAME = \"localhost\";\n\n private static final int PORTNUM = 8000;\n\n // The webserver host and port property names (harness properties)\n private static final String WEBSERVERHOSTPROP = \"webServerHost\";\n\n private static final String WEBSERVERPORTPROP = \"webServerPort\";\n\n private static final String MODEPROP = \"platform.mode\";\n\n String modeProperty = null;\n\n private static final String PKG_NAME = \"com.sun.ts.tests.jaxws.wsa.w2j.document.literal.delimiter.\";\n\n private TSURL ctsurl = new TSURL();\n\n private Properties props = null;\n\n private String hostname = HOSTNAME;\n\n private int portnum = PORTNUM;\n\n // URL properties used by the test\n private static final String ENDPOINT_URL = \"wsaw2jdldelimitertest.endpoint.1\";\n\n private static final String WSDLLOC_URL = \"wsaw2jdldelimitertest.wsdlloc.1\";\n\n private String url = null;\n\n // service and port information\n private static final String NAMESPACEURI = \"urn:example.com\";\n\n private static final String SERVICE_NAME = \"AddNumbersService\";\n\n private static final String PORT_NAME = \"AddNumbersPort\";\n\n private QName SERVICE_QNAME = new QName(NAMESPACEURI, SERVICE_NAME);\n\n private QName PORT_QNAME = new QName(NAMESPACEURI, PORT_NAME);\n\n private URL wsdlurl = null;\n\n AddNumbersPortType port = null;\n\n static AddNumbersService service = null;\n\n private void getTestURLs() throws Exception {\n TestUtil.logMsg(\"Get URL's used by the test\");\n String file = JAXWS_Util.getURLFromProp(ENDPOINT_URL);\n url = ctsurl.getURLString(PROTOCOL, hostname, portnum, file);\n file = JAXWS_Util.getURLFromProp(WSDLLOC_URL);\n wsdlurl = ctsurl.getURL(PROTOCOL, hostname, portnum, file);\n TestUtil.logMsg(\"Service Endpoint URL: \" + url);\n TestUtil.logMsg(\"WSDL Location URL: \" + wsdlurl);\n }\n\n private void getPortStandalone() throws Exception {\n port = (AddNumbersPortType) JAXWS_Util.getPort(wsdlurl, SERVICE_QNAME, AddNumbersService.class, PORT_QNAME, AddNumbersPortType.class);\n TestUtil.logMsg(\"port=\" + port);\n JAXWS_Util.setTargetEndpointAddress(port, url);\n }\n\n ", "post_mask_code": "{\n TestUtil.logMsg(\"Obtain service via WebServiceRef annotation\");\n TestUtil.logMsg(\"service=\" + service);\n port = (AddNumbersPortType) service.getAddNumbersPort();\n TestUtil.logMsg(\"port=\" + port);\n TestUtil.logMsg(\"Obtained port\");\n JAXWS_Util.dumpTargetEndpointAddress(port);\n }\n\n public static void main(String[] args) {\n Client theTests = new Client();\n Status s = theTests.run(args, System.out, System.err);\n s.exit();\n }\n\n /* Test setup */\n public void setup(String[] args, Properties p) throws Fault {\n props = p;\n boolean pass = true;\n try {\n hostname = p.getProperty(WEBSERVERHOSTPROP);\n if (hostname == null)\n pass = false;\n else if (hostname.equals(\"\"))\n pass = false;\n try {\n portnum = Integer.parseInt(p.getProperty(WEBSERVERPORTPROP));\n } catch (Exception e) {\n TestUtil.printStackTrace(e);\n pass = false;\n }\n modeProperty = p.getProperty(MODEPROP);\n if (modeProperty.equals(\"standalone\")) {\n getTestURLs();\n getPortStandalone();\n } else {\n TestUtil.logMsg(\"WebServiceRef is not set in Client (get it from specific vehicle)\");\n service = (AddNumbersService) getSharedObject();\n getTestURLs();\n getPortJavaEE();\n }\n } catch (Exception e) {\n TestUtil.printStackTrace(e);\n throw new Fault(\"setup failed:\", e);\n }\n if (!pass) {\n TestUtil.logErr(\"Please specify host & port of web server \" + \"in config properties: \" + WEBSERVERHOSTPROP + \", \" + WEBSERVERPORTPROP);\n throw new Fault(\"setup failed:\");\n }\n logMsg(\"setup ok\");\n }\n\n public void cleanup() throws Fault {\n logMsg(\"cleanup ok\");\n }\n\n /*\n * @testName: testURNDefaultInputOutputActions\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4004.1; WSAMD:SPEC:4004.2;\n *\n * @test_Strategy: Test default action pattern for WSDL input/output with URN\n * targetNamespace\n *\n */\n public void testURNDefaultInputOutputActions() throws Fault {\n TestUtil.logMsg(\"testURNDefaultInputOutputActions\");\n boolean pass = true;\n try {\n int result = port.addNumbers(10, 10);\n if (result != 20) {\n TestUtil.logErr(\"result mismatch, expected 20, received \" + result);\n pass = false;\n } else\n TestUtil.logMsg(\"result match\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNDefaultInputOutputActions failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNDefaultInputOutputActions failed\");\n }\n\n /*\n * @testName: testURNDefaultFaultAction\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4004.3;\n *\n * @test_Strategy: Test default action pattern for WSDL fault with URN\n * targetNamespace\n *\n */\n public void testURNDefaultFaultAction() throws Fault {\n TestUtil.logMsg(\"testURNDefaultFaultAction\");\n boolean pass = true;\n try {\n port.addNumbers(-10, 10);\n TestUtil.logErr(\"AddNumbersFault_Exception must be thrown\");\n pass = false;\n } catch (AddNumbersFault_Exception ex) {\n TestUtil.logMsg(\"AddNumbersFault_Exception was thrown as expected\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNDefaultFaultAction failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNDefaultAddFaultAction failed\");\n }\n\n /*\n * @testName: testURNExplicitInputOutputActions\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4003; WSAMD:SPEC:4003.1;\n * WSAMD:SPEC:4003.1; JAXWS:SPEC:2077; JAXWS:SPEC:2078; JAXWS:SPEC:2079;\n *\n * @test_Strategy: Test explicit association for WSDL input/output with URN\n * targetNamespace\n *\n */\n public void testURNExplicitInputOutputActions() throws Fault {\n TestUtil.logMsg(\"testURNExplicitInputOutputActions\");\n boolean pass = true;\n try {\n int result = port.addNumbers2(10, 10);\n if (result != 20) {\n TestUtil.logErr(\"result mismatch, expected 20, received \" + result);\n pass = false;\n } else\n TestUtil.logMsg(\"result match\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNExplicitInputOutputActions failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNExplicitInputOutputActions failed\");\n }\n\n /*\n * @testName: testURNExplicitFaultAction\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4003; WSAMD:SPEC:4003.3;\n * JAXWS:SPEC:2080; JAXWS:SPEC:2081; JAXWS:SPEC:2082; JAXWS:SPEC:2083;\n *\n * @test_Strategy: Test explicit association for WSDL fault with URN\n * targetNamespace\n *\n */\n public void testURNExplicitFaultAction() throws Fault {\n TestUtil.logMsg(\"testURNExplicitFaultAction\");\n boolean pass = true;\n try {\n int result = port.addNumbers2(-10, 10);\n TestUtil.logErr(\"AddNumbersFault_Exception must be thrown\");\n pass = false;\n } catch (AddNumbersFault_Exception ex) {\n TestUtil.logMsg(\"AddNumbersFault_Exception was thrown as expected\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNExplicitFaultAction failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNExplicitFaultAction failed\");\n }\n}\n"} {"task_id": "Java_2305", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/jaxws/wsa/w2j/document/literal/delimiter/Client.java", "mask_start_position": 4886, "mask_end_position": 4923, "canonical_solution": "{\n logMsg(\"cleanup ok\");\n }", "pre_mask_code": "package com.sun.ts.tests.jaxws.wsa.w2j.document.literal.delimiter;\n\nimport com.sun.ts.lib.util.*;\nimport com.sun.ts.lib.porting.*;\nimport com.sun.ts.lib.harness.*;\nimport jakarta.xml.soap.SOAPBody;\nimport jakarta.xml.soap.SOAPException;\nimport com.sun.ts.tests.jaxws.wsa.common.ActionNotSupportedException;\nimport com.sun.ts.tests.jaxws.common.*;\nimport java.net.URL;\nimport jakarta.xml.ws.*;\nimport jakarta.xml.soap.*;\nimport java.util.Properties;\nimport javax.xml.namespace.QName;\nimport com.sun.javatest.Status;\nimport javax.naming.InitialContext;\n\npublic class Client extends ServiceEETest {\n\n // The webserver defaults (overidden by harness properties)\n private static final String PROTOCOL = \"http\";\n\n private static final String HOSTNAME = \"localhost\";\n\n private static final int PORTNUM = 8000;\n\n // The webserver host and port property names (harness properties)\n private static final String WEBSERVERHOSTPROP = \"webServerHost\";\n\n private static final String WEBSERVERPORTPROP = \"webServerPort\";\n\n private static final String MODEPROP = \"platform.mode\";\n\n String modeProperty = null;\n\n private static final String PKG_NAME = \"com.sun.ts.tests.jaxws.wsa.w2j.document.literal.delimiter.\";\n\n private TSURL ctsurl = new TSURL();\n\n private Properties props = null;\n\n private String hostname = HOSTNAME;\n\n private int portnum = PORTNUM;\n\n // URL properties used by the test\n private static final String ENDPOINT_URL = \"wsaw2jdldelimitertest.endpoint.1\";\n\n private static final String WSDLLOC_URL = \"wsaw2jdldelimitertest.wsdlloc.1\";\n\n private String url = null;\n\n // service and port information\n private static final String NAMESPACEURI = \"urn:example.com\";\n\n private static final String SERVICE_NAME = \"AddNumbersService\";\n\n private static final String PORT_NAME = \"AddNumbersPort\";\n\n private QName SERVICE_QNAME = new QName(NAMESPACEURI, SERVICE_NAME);\n\n private QName PORT_QNAME = new QName(NAMESPACEURI, PORT_NAME);\n\n private URL wsdlurl = null;\n\n AddNumbersPortType port = null;\n\n static AddNumbersService service = null;\n\n private void getTestURLs() throws Exception {\n TestUtil.logMsg(\"Get URL's used by the test\");\n String file = JAXWS_Util.getURLFromProp(ENDPOINT_URL);\n url = ctsurl.getURLString(PROTOCOL, hostname, portnum, file);\n file = JAXWS_Util.getURLFromProp(WSDLLOC_URL);\n wsdlurl = ctsurl.getURL(PROTOCOL, hostname, portnum, file);\n TestUtil.logMsg(\"Service Endpoint URL: \" + url);\n TestUtil.logMsg(\"WSDL Location URL: \" + wsdlurl);\n }\n\n private void getPortStandalone() throws Exception {\n port = (AddNumbersPortType) JAXWS_Util.getPort(wsdlurl, SERVICE_QNAME, AddNumbersService.class, PORT_QNAME, AddNumbersPortType.class);\n TestUtil.logMsg(\"port=\" + port);\n JAXWS_Util.setTargetEndpointAddress(port, url);\n }\n\n private void getPortJavaEE() throws Exception {\n TestUtil.logMsg(\"Obtain service via WebServiceRef annotation\");\n TestUtil.logMsg(\"service=\" + service);\n port = (AddNumbersPortType) service.getAddNumbersPort();\n TestUtil.logMsg(\"port=\" + port);\n TestUtil.logMsg(\"Obtained port\");\n JAXWS_Util.dumpTargetEndpointAddress(port);\n }\n\n public static void main(String[] args) {\n Client theTests = new Client();\n Status s = theTests.run(args, System.out, System.err);\n s.exit();\n }\n\n /* Test setup */\n public void setup(String[] args, Properties p) throws Fault {\n props = p;\n boolean pass = true;\n try {\n hostname = p.getProperty(WEBSERVERHOSTPROP);\n if (hostname == null)\n pass = false;\n else if (hostname.equals(\"\"))\n pass = false;\n try {\n portnum = Integer.parseInt(p.getProperty(WEBSERVERPORTPROP));\n } catch (Exception e) {\n TestUtil.printStackTrace(e);\n pass = false;\n }\n modeProperty = p.getProperty(MODEPROP);\n if (modeProperty.equals(\"standalone\")) {\n getTestURLs();\n getPortStandalone();\n } else {\n TestUtil.logMsg(\"WebServiceRef is not set in Client (get it from specific vehicle)\");\n service = (AddNumbersService) getSharedObject();\n getTestURLs();\n getPortJavaEE();\n }\n } catch (Exception e) {\n TestUtil.printStackTrace(e);\n throw new Fault(\"setup failed:\", e);\n }\n if (!pass) {\n TestUtil.logErr(\"Please specify host & port of web server \" + \"in config properties: \" + WEBSERVERHOSTPROP + \", \" + WEBSERVERPORTPROP);\n throw new Fault(\"setup failed:\");\n }\n logMsg(\"setup ok\");\n }\n\n public void cleanup() throws Fault ", "post_mask_code": "\n\n /*\n * @testName: testURNDefaultInputOutputActions\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4004.1; WSAMD:SPEC:4004.2;\n *\n * @test_Strategy: Test default action pattern for WSDL input/output with URN\n * targetNamespace\n *\n */\n public void testURNDefaultInputOutputActions() throws Fault {\n TestUtil.logMsg(\"testURNDefaultInputOutputActions\");\n boolean pass = true;\n try {\n int result = port.addNumbers(10, 10);\n if (result != 20) {\n TestUtil.logErr(\"result mismatch, expected 20, received \" + result);\n pass = false;\n } else\n TestUtil.logMsg(\"result match\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNDefaultInputOutputActions failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNDefaultInputOutputActions failed\");\n }\n\n /*\n * @testName: testURNDefaultFaultAction\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4004.3;\n *\n * @test_Strategy: Test default action pattern for WSDL fault with URN\n * targetNamespace\n *\n */\n public void testURNDefaultFaultAction() throws Fault {\n TestUtil.logMsg(\"testURNDefaultFaultAction\");\n boolean pass = true;\n try {\n port.addNumbers(-10, 10);\n TestUtil.logErr(\"AddNumbersFault_Exception must be thrown\");\n pass = false;\n } catch (AddNumbersFault_Exception ex) {\n TestUtil.logMsg(\"AddNumbersFault_Exception was thrown as expected\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNDefaultFaultAction failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNDefaultAddFaultAction failed\");\n }\n\n /*\n * @testName: testURNExplicitInputOutputActions\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4003; WSAMD:SPEC:4003.1;\n * WSAMD:SPEC:4003.1; JAXWS:SPEC:2077; JAXWS:SPEC:2078; JAXWS:SPEC:2079;\n *\n * @test_Strategy: Test explicit association for WSDL input/output with URN\n * targetNamespace\n *\n */\n public void testURNExplicitInputOutputActions() throws Fault {\n TestUtil.logMsg(\"testURNExplicitInputOutputActions\");\n boolean pass = true;\n try {\n int result = port.addNumbers2(10, 10);\n if (result != 20) {\n TestUtil.logErr(\"result mismatch, expected 20, received \" + result);\n pass = false;\n } else\n TestUtil.logMsg(\"result match\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNExplicitInputOutputActions failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNExplicitInputOutputActions failed\");\n }\n\n /*\n * @testName: testURNExplicitFaultAction\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4003; WSAMD:SPEC:4003.3;\n * JAXWS:SPEC:2080; JAXWS:SPEC:2081; JAXWS:SPEC:2082; JAXWS:SPEC:2083;\n *\n * @test_Strategy: Test explicit association for WSDL fault with URN\n * targetNamespace\n *\n */\n public void testURNExplicitFaultAction() throws Fault {\n TestUtil.logMsg(\"testURNExplicitFaultAction\");\n boolean pass = true;\n try {\n int result = port.addNumbers2(-10, 10);\n TestUtil.logErr(\"AddNumbersFault_Exception must be thrown\");\n pass = false;\n } catch (AddNumbersFault_Exception ex) {\n TestUtil.logMsg(\"AddNumbersFault_Exception was thrown as expected\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNExplicitFaultAction failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNExplicitFaultAction failed\");\n }\n}\n"} {"task_id": "Java_2306", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/jaxws/wsa/w2j/document/literal/delimiter/Client.java", "mask_start_position": 7375, "mask_end_position": 7378, "canonical_solution": "ue;", "pre_mask_code": "package com.sun.ts.tests.jaxws.wsa.w2j.document.literal.delimiter;\n\nimport com.sun.ts.lib.util.*;\nimport com.sun.ts.lib.porting.*;\nimport com.sun.ts.lib.harness.*;\nimport jakarta.xml.soap.SOAPBody;\nimport jakarta.xml.soap.SOAPException;\nimport com.sun.ts.tests.jaxws.wsa.common.ActionNotSupportedException;\nimport com.sun.ts.tests.jaxws.common.*;\nimport java.net.URL;\nimport jakarta.xml.ws.*;\nimport jakarta.xml.soap.*;\nimport java.util.Properties;\nimport javax.xml.namespace.QName;\nimport com.sun.javatest.Status;\nimport javax.naming.InitialContext;\n\npublic class Client extends ServiceEETest {\n\n // The webserver defaults (overidden by harness properties)\n private static final String PROTOCOL = \"http\";\n\n private static final String HOSTNAME = \"localhost\";\n\n private static final int PORTNUM = 8000;\n\n // The webserver host and port property names (harness properties)\n private static final String WEBSERVERHOSTPROP = \"webServerHost\";\n\n private static final String WEBSERVERPORTPROP = \"webServerPort\";\n\n private static final String MODEPROP = \"platform.mode\";\n\n String modeProperty = null;\n\n private static final String PKG_NAME = \"com.sun.ts.tests.jaxws.wsa.w2j.document.literal.delimiter.\";\n\n private TSURL ctsurl = new TSURL();\n\n private Properties props = null;\n\n private String hostname = HOSTNAME;\n\n private int portnum = PORTNUM;\n\n // URL properties used by the test\n private static final String ENDPOINT_URL = \"wsaw2jdldelimitertest.endpoint.1\";\n\n private static final String WSDLLOC_URL = \"wsaw2jdldelimitertest.wsdlloc.1\";\n\n private String url = null;\n\n // service and port information\n private static final String NAMESPACEURI = \"urn:example.com\";\n\n private static final String SERVICE_NAME = \"AddNumbersService\";\n\n private static final String PORT_NAME = \"AddNumbersPort\";\n\n private QName SERVICE_QNAME = new QName(NAMESPACEURI, SERVICE_NAME);\n\n private QName PORT_QNAME = new QName(NAMESPACEURI, PORT_NAME);\n\n private URL wsdlurl = null;\n\n AddNumbersPortType port = null;\n\n static AddNumbersService service = null;\n\n private void getTestURLs() throws Exception {\n TestUtil.logMsg(\"Get URL's used by the test\");\n String file = JAXWS_Util.getURLFromProp(ENDPOINT_URL);\n url = ctsurl.getURLString(PROTOCOL, hostname, portnum, file);\n file = JAXWS_Util.getURLFromProp(WSDLLOC_URL);\n wsdlurl = ctsurl.getURL(PROTOCOL, hostname, portnum, file);\n TestUtil.logMsg(\"Service Endpoint URL: \" + url);\n TestUtil.logMsg(\"WSDL Location URL: \" + wsdlurl);\n }\n\n private void getPortStandalone() throws Exception {\n port = (AddNumbersPortType) JAXWS_Util.getPort(wsdlurl, SERVICE_QNAME, AddNumbersService.class, PORT_QNAME, AddNumbersPortType.class);\n TestUtil.logMsg(\"port=\" + port);\n JAXWS_Util.setTargetEndpointAddress(port, url);\n }\n\n private void getPortJavaEE() throws Exception {\n TestUtil.logMsg(\"Obtain service via WebServiceRef annotation\");\n TestUtil.logMsg(\"service=\" + service);\n port = (AddNumbersPortType) service.getAddNumbersPort();\n TestUtil.logMsg(\"port=\" + port);\n TestUtil.logMsg(\"Obtained port\");\n JAXWS_Util.dumpTargetEndpointAddress(port);\n }\n\n public static void main(String[] args) {\n Client theTests = new Client();\n Status s = theTests.run(args, System.out, System.err);\n s.exit();\n }\n\n /* Test setup */\n public void setup(String[] args, Properties p) throws Fault {\n props = p;\n boolean pass = true;\n try {\n hostname = p.getProperty(WEBSERVERHOSTPROP);\n if (hostname == null)\n pass = false;\n else if (hostname.equals(\"\"))\n pass = false;\n try {\n portnum = Integer.parseInt(p.getProperty(WEBSERVERPORTPROP));\n } catch (Exception e) {\n TestUtil.printStackTrace(e);\n pass = false;\n }\n modeProperty = p.getProperty(MODEPROP);\n if (modeProperty.equals(\"standalone\")) {\n getTestURLs();\n getPortStandalone();\n } else {\n TestUtil.logMsg(\"WebServiceRef is not set in Client (get it from specific vehicle)\");\n service = (AddNumbersService) getSharedObject();\n getTestURLs();\n getPortJavaEE();\n }\n } catch (Exception e) {\n TestUtil.printStackTrace(e);\n throw new Fault(\"setup failed:\", e);\n }\n if (!pass) {\n TestUtil.logErr(\"Please specify host & port of web server \" + \"in config properties: \" + WEBSERVERHOSTPROP + \", \" + WEBSERVERPORTPROP);\n throw new Fault(\"setup failed:\");\n }\n logMsg(\"setup ok\");\n }\n\n public void cleanup() throws Fault {\n logMsg(\"cleanup ok\");\n }\n\n /*\n * @testName: testURNDefaultInputOutputActions\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4004.1; WSAMD:SPEC:4004.2;\n *\n * @test_Strategy: Test default action pattern for WSDL input/output with URN\n * targetNamespace\n *\n */\n public void testURNDefaultInputOutputActions() throws Fault {\n TestUtil.logMsg(\"testURNDefaultInputOutputActions\");\n boolean pass = true;\n try {\n int result = port.addNumbers(10, 10);\n if (result != 20) {\n TestUtil.logErr(\"result mismatch, expected 20, received \" + result);\n pass = false;\n } else\n TestUtil.logMsg(\"result match\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNDefaultInputOutputActions failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNDefaultInputOutputActions failed\");\n }\n\n /*\n * @testName: testURNDefaultFaultAction\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4004.3;\n *\n * @test_Strategy: Test default action pattern for WSDL fault with URN\n * targetNamespace\n *\n */\n public void testURNDefaultFaultAction() throws Fault {\n TestUtil.logMsg(\"testURNDefaultFaultAction\");\n boolean pass = true;\n try {\n port.addNumbers(-10, 10);\n TestUtil.logErr(\"AddNumbersFault_Exception must be thrown\");\n pass = false;\n } catch (AddNumbersFault_Exception ex) {\n TestUtil.logMsg(\"AddNumbersFault_Exception was thrown as expected\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNDefaultFaultAction failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNDefaultAddFaultAction failed\");\n }\n\n /*\n * @testName: testURNExplicitInputOutputActions\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4003; WSAMD:SPEC:4003.1;\n * WSAMD:SPEC:4003.1; JAXWS:SPEC:2077; JAXWS:SPEC:2078; JAXWS:SPEC:2079;\n *\n * @test_Strategy: Test explicit association for WSDL input/output with URN\n * targetNamespace\n *\n */\n public void testURNExplicitInputOutputActions() throws Fault {\n TestUtil.logMsg(\"testURNExplicitInputOutputActions\");\n boolean pass = tr", "post_mask_code": "\n try {\n int result = port.addNumbers2(10, 10);\n if (result != 20) {\n TestUtil.logErr(\"result mismatch, expected 20, received \" + result);\n pass = false;\n } else\n TestUtil.logMsg(\"result match\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNExplicitInputOutputActions failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNExplicitInputOutputActions failed\");\n }\n\n /*\n * @testName: testURNExplicitFaultAction\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4003; WSAMD:SPEC:4003.3;\n * JAXWS:SPEC:2080; JAXWS:SPEC:2081; JAXWS:SPEC:2082; JAXWS:SPEC:2083;\n *\n * @test_Strategy: Test explicit association for WSDL fault with URN\n * targetNamespace\n *\n */\n public void testURNExplicitFaultAction() throws Fault {\n TestUtil.logMsg(\"testURNExplicitFaultAction\");\n boolean pass = true;\n try {\n int result = port.addNumbers2(-10, 10);\n TestUtil.logErr(\"AddNumbersFault_Exception must be thrown\");\n pass = false;\n } catch (AddNumbersFault_Exception ex) {\n TestUtil.logMsg(\"AddNumbersFault_Exception was thrown as expected\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNExplicitFaultAction failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNExplicitFaultAction failed\");\n }\n}\n"} {"task_id": "Java_2307", "language": "Java", "task_type": "try_statement", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/jaxws/wsa/w2j/document/literal/delimiter/Client.java", "mask_start_position": 3807, "mask_end_position": 4015, "canonical_solution": "try {\n portnum = Integer.parseInt(p.getProperty(WEBSERVERPORTPROP));\n } catch (Exception e) {\n TestUtil.printStackTrace(e);\n pass = false;\n }", "pre_mask_code": "package com.sun.ts.tests.jaxws.wsa.w2j.document.literal.delimiter;\n\nimport com.sun.ts.lib.util.*;\nimport com.sun.ts.lib.porting.*;\nimport com.sun.ts.lib.harness.*;\nimport jakarta.xml.soap.SOAPBody;\nimport jakarta.xml.soap.SOAPException;\nimport com.sun.ts.tests.jaxws.wsa.common.ActionNotSupportedException;\nimport com.sun.ts.tests.jaxws.common.*;\nimport java.net.URL;\nimport jakarta.xml.ws.*;\nimport jakarta.xml.soap.*;\nimport java.util.Properties;\nimport javax.xml.namespace.QName;\nimport com.sun.javatest.Status;\nimport javax.naming.InitialContext;\n\npublic class Client extends ServiceEETest {\n\n // The webserver defaults (overidden by harness properties)\n private static final String PROTOCOL = \"http\";\n\n private static final String HOSTNAME = \"localhost\";\n\n private static final int PORTNUM = 8000;\n\n // The webserver host and port property names (harness properties)\n private static final String WEBSERVERHOSTPROP = \"webServerHost\";\n\n private static final String WEBSERVERPORTPROP = \"webServerPort\";\n\n private static final String MODEPROP = \"platform.mode\";\n\n String modeProperty = null;\n\n private static final String PKG_NAME = \"com.sun.ts.tests.jaxws.wsa.w2j.document.literal.delimiter.\";\n\n private TSURL ctsurl = new TSURL();\n\n private Properties props = null;\n\n private String hostname = HOSTNAME;\n\n private int portnum = PORTNUM;\n\n // URL properties used by the test\n private static final String ENDPOINT_URL = \"wsaw2jdldelimitertest.endpoint.1\";\n\n private static final String WSDLLOC_URL = \"wsaw2jdldelimitertest.wsdlloc.1\";\n\n private String url = null;\n\n // service and port information\n private static final String NAMESPACEURI = \"urn:example.com\";\n\n private static final String SERVICE_NAME = \"AddNumbersService\";\n\n private static final String PORT_NAME = \"AddNumbersPort\";\n\n private QName SERVICE_QNAME = new QName(NAMESPACEURI, SERVICE_NAME);\n\n private QName PORT_QNAME = new QName(NAMESPACEURI, PORT_NAME);\n\n private URL wsdlurl = null;\n\n AddNumbersPortType port = null;\n\n static AddNumbersService service = null;\n\n private void getTestURLs() throws Exception {\n TestUtil.logMsg(\"Get URL's used by the test\");\n String file = JAXWS_Util.getURLFromProp(ENDPOINT_URL);\n url = ctsurl.getURLString(PROTOCOL, hostname, portnum, file);\n file = JAXWS_Util.getURLFromProp(WSDLLOC_URL);\n wsdlurl = ctsurl.getURL(PROTOCOL, hostname, portnum, file);\n TestUtil.logMsg(\"Service Endpoint URL: \" + url);\n TestUtil.logMsg(\"WSDL Location URL: \" + wsdlurl);\n }\n\n private void getPortStandalone() throws Exception {\n port = (AddNumbersPortType) JAXWS_Util.getPort(wsdlurl, SERVICE_QNAME, AddNumbersService.class, PORT_QNAME, AddNumbersPortType.class);\n TestUtil.logMsg(\"port=\" + port);\n JAXWS_Util.setTargetEndpointAddress(port, url);\n }\n\n private void getPortJavaEE() throws Exception {\n TestUtil.logMsg(\"Obtain service via WebServiceRef annotation\");\n TestUtil.logMsg(\"service=\" + service);\n port = (AddNumbersPortType) service.getAddNumbersPort();\n TestUtil.logMsg(\"port=\" + port);\n TestUtil.logMsg(\"Obtained port\");\n JAXWS_Util.dumpTargetEndpointAddress(port);\n }\n\n public static void main(String[] args) {\n Client theTests = new Client();\n Status s = theTests.run(args, System.out, System.err);\n s.exit();\n }\n\n /* Test setup */\n public void setup(String[] args, Properties p) throws Fault {\n props = p;\n boolean pass = true;\n try {\n hostname = p.getProperty(WEBSERVERHOSTPROP);\n if (hostname == null)\n pass = false;\n else if (hostname.equals(\"\"))\n pass = false;\n ", "post_mask_code": "\n modeProperty = p.getProperty(MODEPROP);\n if (modeProperty.equals(\"standalone\")) {\n getTestURLs();\n getPortStandalone();\n } else {\n TestUtil.logMsg(\"WebServiceRef is not set in Client (get it from specific vehicle)\");\n service = (AddNumbersService) getSharedObject();\n getTestURLs();\n getPortJavaEE();\n }\n } catch (Exception e) {\n TestUtil.printStackTrace(e);\n throw new Fault(\"setup failed:\", e);\n }\n if (!pass) {\n TestUtil.logErr(\"Please specify host & port of web server \" + \"in config properties: \" + WEBSERVERHOSTPROP + \", \" + WEBSERVERPORTPROP);\n throw new Fault(\"setup failed:\");\n }\n logMsg(\"setup ok\");\n }\n\n public void cleanup() throws Fault {\n logMsg(\"cleanup ok\");\n }\n\n /*\n * @testName: testURNDefaultInputOutputActions\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4004.1; WSAMD:SPEC:4004.2;\n *\n * @test_Strategy: Test default action pattern for WSDL input/output with URN\n * targetNamespace\n *\n */\n public void testURNDefaultInputOutputActions() throws Fault {\n TestUtil.logMsg(\"testURNDefaultInputOutputActions\");\n boolean pass = true;\n try {\n int result = port.addNumbers(10, 10);\n if (result != 20) {\n TestUtil.logErr(\"result mismatch, expected 20, received \" + result);\n pass = false;\n } else\n TestUtil.logMsg(\"result match\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNDefaultInputOutputActions failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNDefaultInputOutputActions failed\");\n }\n\n /*\n * @testName: testURNDefaultFaultAction\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4004.3;\n *\n * @test_Strategy: Test default action pattern for WSDL fault with URN\n * targetNamespace\n *\n */\n public void testURNDefaultFaultAction() throws Fault {\n TestUtil.logMsg(\"testURNDefaultFaultAction\");\n boolean pass = true;\n try {\n port.addNumbers(-10, 10);\n TestUtil.logErr(\"AddNumbersFault_Exception must be thrown\");\n pass = false;\n } catch (AddNumbersFault_Exception ex) {\n TestUtil.logMsg(\"AddNumbersFault_Exception was thrown as expected\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNDefaultFaultAction failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNDefaultAddFaultAction failed\");\n }\n\n /*\n * @testName: testURNExplicitInputOutputActions\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4003; WSAMD:SPEC:4003.1;\n * WSAMD:SPEC:4003.1; JAXWS:SPEC:2077; JAXWS:SPEC:2078; JAXWS:SPEC:2079;\n *\n * @test_Strategy: Test explicit association for WSDL input/output with URN\n * targetNamespace\n *\n */\n public void testURNExplicitInputOutputActions() throws Fault {\n TestUtil.logMsg(\"testURNExplicitInputOutputActions\");\n boolean pass = true;\n try {\n int result = port.addNumbers2(10, 10);\n if (result != 20) {\n TestUtil.logErr(\"result mismatch, expected 20, received \" + result);\n pass = false;\n } else\n TestUtil.logMsg(\"result match\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNExplicitInputOutputActions failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNExplicitInputOutputActions failed\");\n }\n\n /*\n * @testName: testURNExplicitFaultAction\n *\n * @assertion_ids: WSAMD:SPEC:4004; WSAMD:SPEC:4003; WSAMD:SPEC:4003.3;\n * JAXWS:SPEC:2080; JAXWS:SPEC:2081; JAXWS:SPEC:2082; JAXWS:SPEC:2083;\n *\n * @test_Strategy: Test explicit association for WSDL fault with URN\n * targetNamespace\n *\n */\n public void testURNExplicitFaultAction() throws Fault {\n TestUtil.logMsg(\"testURNExplicitFaultAction\");\n boolean pass = true;\n try {\n int result = port.addNumbers2(-10, 10);\n TestUtil.logErr(\"AddNumbersFault_Exception must be thrown\");\n pass = false;\n } catch (AddNumbersFault_Exception ex) {\n TestUtil.logMsg(\"AddNumbersFault_Exception was thrown as expected\");\n } catch (Exception e) {\n TestUtil.logErr(\"Caught exception: \" + e.getMessage());\n TestUtil.printStackTrace(e);\n throw new Fault(\"testURNExplicitFaultAction failed\", e);\n }\n if (!pass)\n throw new Fault(\"testURNExplicitFaultAction failed\");\n }\n}\n"} {"task_id": "Java_2308", "language": "Java", "task_type": "method_signature", "source_file": "java/github/liferay/liferay-portal/modules/apps/message-boards/message-boards-service/src/main/java/com/liferay/message/boards/internal/upgrade/v4_0_0/MBCategoryThreadCountUpgradeProcess.java", "mask_start_position": 231, "mask_end_position": 289, "canonical_solution": "@Override\n protected void doUpgrade() throws Exception ", "pre_mask_code": "package com.liferay.message.boards.internal.upgrade.v4_0_0;\n\nimport com.liferay.portal.kernel.upgrade.UpgradeProcess;\n\n/**\n * @author Preston Crary\n */\npublic class MBCategoryThreadCountUpgradeProcess extends UpgradeProcess {\n\n ", "post_mask_code": "{\n runSQL(\"alter table MBCategory drop column threadCount\");\n }\n}\n"} {"task_id": "Java_2309", "language": "Java", "task_type": "method_body", "source_file": "java/github/liferay/liferay-portal/modules/apps/message-boards/message-boards-service/src/main/java/com/liferay/message/boards/internal/upgrade/v4_0_0/MBCategoryThreadCountUpgradeProcess.java", "mask_start_position": 289, "mask_end_position": 362, "canonical_solution": "{\n runSQL(\"alter table MBCategory drop column threadCount\");\n }", "pre_mask_code": "package com.liferay.message.boards.internal.upgrade.v4_0_0;\n\nimport com.liferay.portal.kernel.upgrade.UpgradeProcess;\n\n/**\n * @author Preston Crary\n */\npublic class MBCategoryThreadCountUpgradeProcess extends UpgradeProcess {\n\n @Override\n protected void doUpgrade() throws Exception ", "post_mask_code": "\n}\n"} {"task_id": "Java_2310", "language": "Java", "task_type": "single_line", "source_file": "java/github/liferay/liferay-portal/modules/apps/message-boards/message-boards-service/src/main/java/com/liferay/message/boards/internal/upgrade/v4_0_0/MBCategoryThreadCountUpgradeProcess.java", "mask_start_position": 299, "mask_end_position": 356, "canonical_solution": "runSQL(\"alter table MBCategory drop column threadCount\");", "pre_mask_code": "package com.liferay.message.boards.internal.upgrade.v4_0_0;\n\nimport com.liferay.portal.kernel.upgrade.UpgradeProcess;\n\n/**\n * @author Preston Crary\n */\npublic class MBCategoryThreadCountUpgradeProcess extends UpgradeProcess {\n\n @Override\n protected void doUpgrade() throws Exception {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2311", "language": "Java", "task_type": "method_signature", "source_file": "java/github/roboconf/roboconf-platform/core/roboconf-core/src/main/java/net/roboconf/core/commands/EmailCommandInstruction.java", "mask_start_position": 1893, "mask_end_position": 1916, "canonical_solution": "public String getMsg() ", "pre_mask_code": "/**\n * The present code is developed in the scope of the joint LINAGORA -\n * Université Joseph Fourier - Floralis research program and is designated\n * as a \"Result\" pursuant to the terms and conditions of the LINAGORA\n * - Université Joseph Fourier - Floralis research program. Each copyright\n * holder of Results enumerated here above fully & independently holds complete\n */\npackage net.roboconf.core.commands;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport net.roboconf.core.errors.ErrorCode;\nimport net.roboconf.core.model.ParsingError;\nimport net.roboconf.core.utils.Utils;\n\n/**\n * @author Vincent Zurczak - Linagora\n */\npublic class EmailCommandInstruction extends AbstractCommandInstruction {\n\n static final String PREFIX = \"email\";\n\n private String msg;\n\n private final List tos = new ArrayList<>();\n\n /**\n * Constructor.\n * @param context\n * @param instruction\n * @param line\n */\n EmailCommandInstruction(Context context, String instruction, int line) {\n super(context, instruction, line);\n Pattern p = Pattern.compile(PREFIX + \"\\\\s+(.*)\\\\s*with\\\\s+(.*)\", Pattern.CASE_INSENSITIVE);\n Matcher m = p.matcher(instruction);\n if (m.matches()) {\n this.syntaxicallyCorrect = true;\n this.tos.addAll(Utils.splitNicely(m.group(1), \",\"));\n this.msg = m.group(2).trim().replace(\"\\\\n\", \"\\n\");\n }\n }\n\n /*\n\t * (non-Javadoc)\n\t * @see net.roboconf.core.commands.AbstractCommandInstruction#doValidate()\n\t */\n @Override\n public List doValidate() {\n List result = new ArrayList<>();\n if (Utils.isEmptyOrWhitespaces(this.msg))\n result.add(error(ErrorCode.CMD_EMAIL_NO_MESSAGE));\n return result;\n }\n\n /**\n * @return the msg\n */\n ", "post_mask_code": "{\n return this.msg;\n }\n\n /**\n * @return the tos\n */\n public List getTos() {\n return this.tos;\n }\n}\n"} {"task_id": "Java_2312", "language": "Java", "task_type": "method_body", "source_file": "java/github/roboconf/roboconf-platform/core/roboconf-core/src/main/java/net/roboconf/core/commands/EmailCommandInstruction.java", "mask_start_position": 2022, "mask_end_position": 2054, "canonical_solution": "{\n return this.tos;\n }", "pre_mask_code": "/**\n * The present code is developed in the scope of the joint LINAGORA -\n * Université Joseph Fourier - Floralis research program and is designated\n * as a \"Result\" pursuant to the terms and conditions of the LINAGORA\n * - Université Joseph Fourier - Floralis research program. Each copyright\n * holder of Results enumerated here above fully & independently holds complete\n */\npackage net.roboconf.core.commands;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport net.roboconf.core.errors.ErrorCode;\nimport net.roboconf.core.model.ParsingError;\nimport net.roboconf.core.utils.Utils;\n\n/**\n * @author Vincent Zurczak - Linagora\n */\npublic class EmailCommandInstruction extends AbstractCommandInstruction {\n\n static final String PREFIX = \"email\";\n\n private String msg;\n\n private final List tos = new ArrayList<>();\n\n /**\n * Constructor.\n * @param context\n * @param instruction\n * @param line\n */\n EmailCommandInstruction(Context context, String instruction, int line) {\n super(context, instruction, line);\n Pattern p = Pattern.compile(PREFIX + \"\\\\s+(.*)\\\\s*with\\\\s+(.*)\", Pattern.CASE_INSENSITIVE);\n Matcher m = p.matcher(instruction);\n if (m.matches()) {\n this.syntaxicallyCorrect = true;\n this.tos.addAll(Utils.splitNicely(m.group(1), \",\"));\n this.msg = m.group(2).trim().replace(\"\\\\n\", \"\\n\");\n }\n }\n\n /*\n\t * (non-Javadoc)\n\t * @see net.roboconf.core.commands.AbstractCommandInstruction#doValidate()\n\t */\n @Override\n public List doValidate() {\n List result = new ArrayList<>();\n if (Utils.isEmptyOrWhitespaces(this.msg))\n result.add(error(ErrorCode.CMD_EMAIL_NO_MESSAGE));\n return result;\n }\n\n /**\n * @return the msg\n */\n public String getMsg() {\n return this.msg;\n }\n\n /**\n * @return the tos\n */\n public List getTos() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2313", "language": "Java", "task_type": "single_line", "source_file": "java/github/roboconf/roboconf-platform/core/roboconf-core/src/main/java/net/roboconf/core/commands/EmailCommandInstruction.java", "mask_start_position": 1838, "mask_end_position": 1842, "canonical_solution": "ult;", "pre_mask_code": "/**\n * The present code is developed in the scope of the joint LINAGORA -\n * Université Joseph Fourier - Floralis research program and is designated\n * as a \"Result\" pursuant to the terms and conditions of the LINAGORA\n * - Université Joseph Fourier - Floralis research program. Each copyright\n * holder of Results enumerated here above fully & independently holds complete\n */\npackage net.roboconf.core.commands;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport net.roboconf.core.errors.ErrorCode;\nimport net.roboconf.core.model.ParsingError;\nimport net.roboconf.core.utils.Utils;\n\n/**\n * @author Vincent Zurczak - Linagora\n */\npublic class EmailCommandInstruction extends AbstractCommandInstruction {\n\n static final String PREFIX = \"email\";\n\n private String msg;\n\n private final List tos = new ArrayList<>();\n\n /**\n * Constructor.\n * @param context\n * @param instruction\n * @param line\n */\n EmailCommandInstruction(Context context, String instruction, int line) {\n super(context, instruction, line);\n Pattern p = Pattern.compile(PREFIX + \"\\\\s+(.*)\\\\s*with\\\\s+(.*)\", Pattern.CASE_INSENSITIVE);\n Matcher m = p.matcher(instruction);\n if (m.matches()) {\n this.syntaxicallyCorrect = true;\n this.tos.addAll(Utils.splitNicely(m.group(1), \",\"));\n this.msg = m.group(2).trim().replace(\"\\\\n\", \"\\n\");\n }\n }\n\n /*\n\t * (non-Javadoc)\n\t * @see net.roboconf.core.commands.AbstractCommandInstruction#doValidate()\n\t */\n @Override\n public List doValidate() {\n List result = new ArrayList<>();\n if (Utils.isEmptyOrWhitespaces(this.msg))\n result.add(error(ErrorCode.CMD_EMAIL_NO_MESSAGE));\n return res", "post_mask_code": "\n }\n\n /**\n * @return the msg\n */\n public String getMsg() {\n return this.msg;\n }\n\n /**\n * @return the tos\n */\n public List getTos() {\n return this.tos;\n }\n}\n"} {"task_id": "Java_2314", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/roboconf/roboconf-platform/core/roboconf-core/src/main/java/net/roboconf/core/commands/EmailCommandInstruction.java", "mask_start_position": 1993, "mask_end_position": 2054, "canonical_solution": "public List getTos() {\n return this.tos;\n }", "pre_mask_code": "/**\n * The present code is developed in the scope of the joint LINAGORA -\n * Université Joseph Fourier - Floralis research program and is designated\n * as a \"Result\" pursuant to the terms and conditions of the LINAGORA\n * - Université Joseph Fourier - Floralis research program. Each copyright\n * holder of Results enumerated here above fully & independently holds complete\n */\npackage net.roboconf.core.commands;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport net.roboconf.core.errors.ErrorCode;\nimport net.roboconf.core.model.ParsingError;\nimport net.roboconf.core.utils.Utils;\n\n/**\n * @author Vincent Zurczak - Linagora\n */\npublic class EmailCommandInstruction extends AbstractCommandInstruction {\n\n static final String PREFIX = \"email\";\n\n private String msg;\n\n private final List tos = new ArrayList<>();\n\n /**\n * Constructor.\n * @param context\n * @param instruction\n * @param line\n */\n EmailCommandInstruction(Context context, String instruction, int line) {\n super(context, instruction, line);\n Pattern p = Pattern.compile(PREFIX + \"\\\\s+(.*)\\\\s*with\\\\s+(.*)\", Pattern.CASE_INSENSITIVE);\n Matcher m = p.matcher(instruction);\n if (m.matches()) {\n this.syntaxicallyCorrect = true;\n this.tos.addAll(Utils.splitNicely(m.group(1), \",\"));\n this.msg = m.group(2).trim().replace(\"\\\\n\", \"\\n\");\n }\n }\n\n /*\n\t * (non-Javadoc)\n\t * @see net.roboconf.core.commands.AbstractCommandInstruction#doValidate()\n\t */\n @Override\n public List doValidate() {\n List result = new ArrayList<>();\n if (Utils.isEmptyOrWhitespaces(this.msg))\n result.add(error(ErrorCode.CMD_EMAIL_NO_MESSAGE));\n return result;\n }\n\n /**\n * @return the msg\n */\n public String getMsg() {\n return this.msg;\n }\n\n /**\n * @return the tos\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2315", "language": "Java", "task_type": "method_signature", "source_file": "java/github/bonitasoft/bonita-studio/tests/org.bonitasoft.studio.tests/src/org/bonitasoft/studio/tests/util/Await.java", "mask_start_position": 284, "mask_end_position": 415, "canonical_solution": "public static void waitUntil(Supplier condition, int timeout, int interval) throws TimeoutException, InterruptedException ", "pre_mask_code": "package org.bonitasoft.studio.tests.util;\n\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.function.Supplier;\n\npublic class Await {\n\n ", "post_mask_code": "{\n var countDownLatch = new CountDownLatch(1);\n var shouldExitThread = new AtomicBoolean();\n shouldExitThread.set(false);\n new Thread(() -> {\n var result = false;\n while (!result && !shouldExitThread.get()) {\n result = condition.get();\n try {\n Thread.sleep(interval);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n if (result) {\n countDownLatch.countDown();\n }\n }, \"Wait condition thread\").start();\n if (!countDownLatch.await(timeout, TimeUnit.MILLISECONDS)) {\n shouldExitThread.set(true);\n throw new TimeoutException(String.format(\"Failed to evaluate condtion after %sms\", timeout));\n }\n }\n}\n"} {"task_id": "Java_2316", "language": "Java", "task_type": "single_line", "source_file": "java/github/bonitasoft/bonita-studio/tests/org.bonitasoft.studio.tests/src/org/bonitasoft/studio/tests/util/Await.java", "mask_start_position": 509, "mask_end_position": 520, "canonical_solution": "cBoolean();", "pre_mask_code": "package org.bonitasoft.studio.tests.util;\n\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.function.Supplier;\n\npublic class Await {\n\n public static void waitUntil(Supplier condition, int timeout, int interval) throws TimeoutException, InterruptedException {\n var countDownLatch = new CountDownLatch(1);\n var shouldExitThread = new Atomi", "post_mask_code": "\n shouldExitThread.set(false);\n new Thread(() -> {\n var result = false;\n while (!result && !shouldExitThread.get()) {\n result = condition.get();\n try {\n Thread.sleep(interval);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n if (result) {\n countDownLatch.countDown();\n }\n }, \"Wait condition thread\").start();\n if (!countDownLatch.await(timeout, TimeUnit.MILLISECONDS)) {\n shouldExitThread.set(true);\n throw new TimeoutException(String.format(\"Failed to evaluate condtion after %sms\", timeout));\n }\n }\n}\n"} {"task_id": "Java_2317", "language": "Java", "task_type": "while_statement", "source_file": "java/github/bonitasoft/bonita-studio/tests/org.bonitasoft.studio.tests/src/org/bonitasoft/studio/tests/util/Await.java", "mask_start_position": 629, "mask_end_position": 915, "canonical_solution": "while (!result && !shouldExitThread.get()) {\n result = condition.get();\n try {\n Thread.sleep(interval);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }", "pre_mask_code": "package org.bonitasoft.studio.tests.util;\n\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.function.Supplier;\n\npublic class Await {\n\n public static void waitUntil(Supplier condition, int timeout, int interval) throws TimeoutException, InterruptedException {\n var countDownLatch = new CountDownLatch(1);\n var shouldExitThread = new AtomicBoolean();\n shouldExitThread.set(false);\n new Thread(() -> {\n var result = false;\n ", "post_mask_code": "\n if (result) {\n countDownLatch.countDown();\n }\n }, \"Wait condition thread\").start();\n if (!countDownLatch.await(timeout, TimeUnit.MILLISECONDS)) {\n shouldExitThread.set(true);\n throw new TimeoutException(String.format(\"Failed to evaluate condtion after %sms\", timeout));\n }\n }\n}\n"} {"task_id": "Java_2318", "language": "Java", "task_type": "try_statement", "source_file": "java/github/bonitasoft/bonita-studio/tests/org.bonitasoft.studio.tests/src/org/bonitasoft/studio/tests/util/Await.java", "mask_start_position": 732, "mask_end_position": 901, "canonical_solution": "try {\n Thread.sleep(interval);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }", "pre_mask_code": "package org.bonitasoft.studio.tests.util;\n\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.function.Supplier;\n\npublic class Await {\n\n public static void waitUntil(Supplier condition, int timeout, int interval) throws TimeoutException, InterruptedException {\n var countDownLatch = new CountDownLatch(1);\n var shouldExitThread = new AtomicBoolean();\n shouldExitThread.set(false);\n new Thread(() -> {\n var result = false;\n while (!result && !shouldExitThread.get()) {\n result = condition.get();\n ", "post_mask_code": "\n }\n if (result) {\n countDownLatch.countDown();\n }\n }, \"Wait condition thread\").start();\n if (!countDownLatch.await(timeout, TimeUnit.MILLISECONDS)) {\n shouldExitThread.set(true);\n throw new TimeoutException(String.format(\"Failed to evaluate condtion after %sms\", timeout));\n }\n }\n}\n"} {"task_id": "Java_2319", "language": "Java", "task_type": "method_signature", "source_file": "java/github/intomylife/SpringCloud/springcloudalibaba-nacos-config/config-service/config-master-service/nacos-1.2.1/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java", "mask_start_position": 2523, "mask_end_position": 2546, "canonical_solution": "public void mergeAll() ", "pre_mask_code": "package com.alibaba.nacos.config.server.service.merge;\n\nimport com.alibaba.nacos.config.server.manager.TaskManager;\nimport com.alibaba.nacos.config.server.model.ConfigInfo;\nimport com.alibaba.nacos.config.server.model.ConfigInfoAggr;\nimport com.alibaba.nacos.config.server.model.ConfigInfoChanged;\nimport com.alibaba.nacos.config.server.model.Page;\nimport com.alibaba.nacos.config.server.service.PersistService;\nimport com.alibaba.nacos.config.server.utils.ContentUtils;\nimport com.alibaba.nacos.config.server.utils.TimeUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport static com.alibaba.nacos.core.utils.SystemUtils.LOCAL_IP;\n\n/**\n * 数据聚合服务。\n *

\n * 启动时做全量聚合 + 修改数据触发的单条聚合\n *\n * @author jiuRen\n */\n@Service\npublic class MergeDatumService {\n\n private PersistService persistService;\n\n static final int INIT_THREAD_COUNT = 40;\n\n static final AtomicInteger FINISHED = new AtomicInteger();\n\n static int total = 0;\n\n @Autowired\n public MergeDatumService(PersistService persistService) {\n this.persistService = persistService;\n mergeTasks = new TaskManager(\"com.alibaba.nacos.MergeDatum\");\n mergeTasks.setDefaultTaskProcessor(new MergeTaskProcessor(persistService, this));\n }\n\n static List> splitList(List list, int count) {\n List> result = new ArrayList>(count);\n for (int i = 0; i < count; i++) {\n result.add(new ArrayList());\n }\n for (int i = 0; i < list.size(); i++) {\n ConfigInfoChanged config = list.get(i);\n result.get(i % count).add(config);\n }\n return result;\n }\n\n /**\n * 数据变更后调用,添加聚合任务\n */\n public void addMergeTask(String dataId, String groupId, String tenant, String tag, String clientIp) {\n MergeDataTask task = new MergeDataTask(dataId, groupId, tenant, tag, clientIp);\n mergeTasks.addTask(task.getId(), task);\n }\n\n /**\n * 数据变更后调用,添加聚合任务\n */\n public void addMergeTask(String dataId, String groupId, String tenant, String clientIp) {\n MergeDataTask task = new MergeDataTask(dataId, groupId, tenant, clientIp);\n mergeTasks.addTask(task.getId(), task);\n }\n\n ", "post_mask_code": "{\n for (ConfigInfoChanged item : persistService.findAllAggrGroup()) {\n addMergeTask(item.getDataId(), item.getGroup(), item.getTenant(), LOCAL_IP);\n }\n }\n\n class MergeAllDataWorker extends Thread {\n\n static final int PAGE_SIZE = 10000;\n\n private List configInfoList;\n\n public MergeAllDataWorker(List configInfoList) {\n super(\"MergeAllDataWorker\");\n this.configInfoList = configInfoList;\n }\n\n @Override\n public void run() {\n for (ConfigInfoChanged configInfo : configInfoList) {\n String dataId = configInfo.getDataId();\n String group = configInfo.getGroup();\n String tenant = configInfo.getTenant();\n try {\n List datumList = new ArrayList();\n int rowCount = persistService.aggrConfigInfoCount(dataId, group, tenant);\n int pageCount = (int) Math.ceil(rowCount * 1.0 / PAGE_SIZE);\n for (int pageNo = 1; pageNo <= pageCount; pageNo++) {\n Page page = persistService.findConfigInfoAggrByPage(dataId, group, tenant, pageNo, PAGE_SIZE);\n if (page != null) {\n datumList.addAll(page.getPageItems());\n log.info(\"[merge-query] {}, {}, size/total={}/{}\", dataId, group, datumList.size(), rowCount);\n }\n }\n final Timestamp time = TimeUtils.getCurrentTime();\n // 聚合\n if (datumList.size() > 0) {\n ConfigInfo cf = MergeTaskProcessor.merge(dataId, group, tenant, datumList);\n persistService.insertOrUpdate(null, null, cf, time, null, false);\n log.info(\"[merge-ok] {}, {}, size={}, length={}, md5={}, content={}\", dataId, group, datumList.size(), cf.getContent().length(), cf.getMd5(), ContentUtils.truncateContent(cf.getContent()));\n } else // 删除\n {\n persistService.removeConfigInfo(dataId, group, tenant, LOCAL_IP, null);\n log.warn(\"[merge-delete] delete config info because no datum. dataId=\" + dataId + \", groupId=\" + group);\n }\n } catch (Exception e) {\n log.info(\"[merge-error] \" + dataId + \", \" + group + \", \" + e.toString(), e);\n }\n FINISHED.incrementAndGet();\n if (FINISHED.get() % 100 == 0) {\n log.info(\"[all-merge-dump] {} / {}\", FINISHED.get(), total);\n }\n }\n log.info(\"[all-merge-dump] {} / {}\", FINISHED.get(), total);\n }\n }\n\n private static final Logger log = LoggerFactory.getLogger(MergeDatumService.class);\n\n final TaskManager mergeTasks;\n}\n"} {"task_id": "Java_2320", "language": "Java", "task_type": "method_body", "source_file": "java/github/intomylife/SpringCloud/springcloudalibaba-nacos-config/config-service/config-master-service/nacos-1.2.1/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java", "mask_start_position": 2379, "mask_end_position": 2517, "canonical_solution": "{\n MergeDataTask task = new MergeDataTask(dataId, groupId, tenant, clientIp);\n mergeTasks.addTask(task.getId(), task);\n }", "pre_mask_code": "package com.alibaba.nacos.config.server.service.merge;\n\nimport com.alibaba.nacos.config.server.manager.TaskManager;\nimport com.alibaba.nacos.config.server.model.ConfigInfo;\nimport com.alibaba.nacos.config.server.model.ConfigInfoAggr;\nimport com.alibaba.nacos.config.server.model.ConfigInfoChanged;\nimport com.alibaba.nacos.config.server.model.Page;\nimport com.alibaba.nacos.config.server.service.PersistService;\nimport com.alibaba.nacos.config.server.utils.ContentUtils;\nimport com.alibaba.nacos.config.server.utils.TimeUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport static com.alibaba.nacos.core.utils.SystemUtils.LOCAL_IP;\n\n/**\n * 数据聚合服务。\n *

\n * 启动时做全量聚合 + 修改数据触发的单条聚合\n *\n * @author jiuRen\n */\n@Service\npublic class MergeDatumService {\n\n private PersistService persistService;\n\n static final int INIT_THREAD_COUNT = 40;\n\n static final AtomicInteger FINISHED = new AtomicInteger();\n\n static int total = 0;\n\n @Autowired\n public MergeDatumService(PersistService persistService) {\n this.persistService = persistService;\n mergeTasks = new TaskManager(\"com.alibaba.nacos.MergeDatum\");\n mergeTasks.setDefaultTaskProcessor(new MergeTaskProcessor(persistService, this));\n }\n\n static List> splitList(List list, int count) {\n List> result = new ArrayList>(count);\n for (int i = 0; i < count; i++) {\n result.add(new ArrayList());\n }\n for (int i = 0; i < list.size(); i++) {\n ConfigInfoChanged config = list.get(i);\n result.get(i % count).add(config);\n }\n return result;\n }\n\n /**\n * 数据变更后调用,添加聚合任务\n */\n public void addMergeTask(String dataId, String groupId, String tenant, String tag, String clientIp) {\n MergeDataTask task = new MergeDataTask(dataId, groupId, tenant, tag, clientIp);\n mergeTasks.addTask(task.getId(), task);\n }\n\n /**\n * 数据变更后调用,添加聚合任务\n */\n public void addMergeTask(String dataId, String groupId, String tenant, String clientIp) ", "post_mask_code": "\n\n public void mergeAll() {\n for (ConfigInfoChanged item : persistService.findAllAggrGroup()) {\n addMergeTask(item.getDataId(), item.getGroup(), item.getTenant(), LOCAL_IP);\n }\n }\n\n class MergeAllDataWorker extends Thread {\n\n static final int PAGE_SIZE = 10000;\n\n private List configInfoList;\n\n public MergeAllDataWorker(List configInfoList) {\n super(\"MergeAllDataWorker\");\n this.configInfoList = configInfoList;\n }\n\n @Override\n public void run() {\n for (ConfigInfoChanged configInfo : configInfoList) {\n String dataId = configInfo.getDataId();\n String group = configInfo.getGroup();\n String tenant = configInfo.getTenant();\n try {\n List datumList = new ArrayList();\n int rowCount = persistService.aggrConfigInfoCount(dataId, group, tenant);\n int pageCount = (int) Math.ceil(rowCount * 1.0 / PAGE_SIZE);\n for (int pageNo = 1; pageNo <= pageCount; pageNo++) {\n Page page = persistService.findConfigInfoAggrByPage(dataId, group, tenant, pageNo, PAGE_SIZE);\n if (page != null) {\n datumList.addAll(page.getPageItems());\n log.info(\"[merge-query] {}, {}, size/total={}/{}\", dataId, group, datumList.size(), rowCount);\n }\n }\n final Timestamp time = TimeUtils.getCurrentTime();\n // 聚合\n if (datumList.size() > 0) {\n ConfigInfo cf = MergeTaskProcessor.merge(dataId, group, tenant, datumList);\n persistService.insertOrUpdate(null, null, cf, time, null, false);\n log.info(\"[merge-ok] {}, {}, size={}, length={}, md5={}, content={}\", dataId, group, datumList.size(), cf.getContent().length(), cf.getMd5(), ContentUtils.truncateContent(cf.getContent()));\n } else // 删除\n {\n persistService.removeConfigInfo(dataId, group, tenant, LOCAL_IP, null);\n log.warn(\"[merge-delete] delete config info because no datum. dataId=\" + dataId + \", groupId=\" + group);\n }\n } catch (Exception e) {\n log.info(\"[merge-error] \" + dataId + \", \" + group + \", \" + e.toString(), e);\n }\n FINISHED.incrementAndGet();\n if (FINISHED.get() % 100 == 0) {\n log.info(\"[all-merge-dump] {} / {}\", FINISHED.get(), total);\n }\n }\n log.info(\"[all-merge-dump] {} / {}\", FINISHED.get(), total);\n }\n }\n\n private static final Logger log = LoggerFactory.getLogger(MergeDatumService.class);\n\n final TaskManager mergeTasks;\n}\n"} {"task_id": "Java_2321", "language": "Java", "task_type": "single_line", "source_file": "java/github/intomylife/SpringCloud/springcloudalibaba-nacos-config/config-service/config-master-service/nacos-1.2.1/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java", "mask_start_position": 1606, "mask_end_position": 1662, "canonical_solution": " result = new ArrayList>(count);", "pre_mask_code": "package com.alibaba.nacos.config.server.service.merge;\n\nimport com.alibaba.nacos.config.server.manager.TaskManager;\nimport com.alibaba.nacos.config.server.model.ConfigInfo;\nimport com.alibaba.nacos.config.server.model.ConfigInfoAggr;\nimport com.alibaba.nacos.config.server.model.ConfigInfoChanged;\nimport com.alibaba.nacos.config.server.model.Page;\nimport com.alibaba.nacos.config.server.service.PersistService;\nimport com.alibaba.nacos.config.server.utils.ContentUtils;\nimport com.alibaba.nacos.config.server.utils.TimeUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport static com.alibaba.nacos.core.utils.SystemUtils.LOCAL_IP;\n\n/**\n * 数据聚合服务。\n *

\n * 启动时做全量聚合 + 修改数据触发的单条聚合\n *\n * @author jiuRen\n */\n@Service\npublic class MergeDatumService {\n\n private PersistService persistService;\n\n static final int INIT_THREAD_COUNT = 40;\n\n static final AtomicInteger FINISHED = new AtomicInteger();\n\n static int total = 0;\n\n @Autowired\n public MergeDatumService(PersistService persistService) {\n this.persistService = persistService;\n mergeTasks = new TaskManager(\"com.alibaba.nacos.MergeDatum\");\n mergeTasks.setDefaultTaskProcessor(new MergeTaskProcessor(persistService, this));\n }\n\n static List> splitList(List list, int count) {\n List>", "post_mask_code": "\n for (int i = 0; i < count; i++) {\n result.add(new ArrayList());\n }\n for (int i = 0; i < list.size(); i++) {\n ConfigInfoChanged config = list.get(i);\n result.get(i % count).add(config);\n }\n return result;\n }\n\n /**\n * 数据变更后调用,添加聚合任务\n */\n public void addMergeTask(String dataId, String groupId, String tenant, String tag, String clientIp) {\n MergeDataTask task = new MergeDataTask(dataId, groupId, tenant, tag, clientIp);\n mergeTasks.addTask(task.getId(), task);\n }\n\n /**\n * 数据变更后调用,添加聚合任务\n */\n public void addMergeTask(String dataId, String groupId, String tenant, String clientIp) {\n MergeDataTask task = new MergeDataTask(dataId, groupId, tenant, clientIp);\n mergeTasks.addTask(task.getId(), task);\n }\n\n public void mergeAll() {\n for (ConfigInfoChanged item : persistService.findAllAggrGroup()) {\n addMergeTask(item.getDataId(), item.getGroup(), item.getTenant(), LOCAL_IP);\n }\n }\n\n class MergeAllDataWorker extends Thread {\n\n static final int PAGE_SIZE = 10000;\n\n private List configInfoList;\n\n public MergeAllDataWorker(List configInfoList) {\n super(\"MergeAllDataWorker\");\n this.configInfoList = configInfoList;\n }\n\n @Override\n public void run() {\n for (ConfigInfoChanged configInfo : configInfoList) {\n String dataId = configInfo.getDataId();\n String group = configInfo.getGroup();\n String tenant = configInfo.getTenant();\n try {\n List datumList = new ArrayList();\n int rowCount = persistService.aggrConfigInfoCount(dataId, group, tenant);\n int pageCount = (int) Math.ceil(rowCount * 1.0 / PAGE_SIZE);\n for (int pageNo = 1; pageNo <= pageCount; pageNo++) {\n Page page = persistService.findConfigInfoAggrByPage(dataId, group, tenant, pageNo, PAGE_SIZE);\n if (page != null) {\n datumList.addAll(page.getPageItems());\n log.info(\"[merge-query] {}, {}, size/total={}/{}\", dataId, group, datumList.size(), rowCount);\n }\n }\n final Timestamp time = TimeUtils.getCurrentTime();\n // 聚合\n if (datumList.size() > 0) {\n ConfigInfo cf = MergeTaskProcessor.merge(dataId, group, tenant, datumList);\n persistService.insertOrUpdate(null, null, cf, time, null, false);\n log.info(\"[merge-ok] {}, {}, size={}, length={}, md5={}, content={}\", dataId, group, datumList.size(), cf.getContent().length(), cf.getMd5(), ContentUtils.truncateContent(cf.getContent()));\n } else // 删除\n {\n persistService.removeConfigInfo(dataId, group, tenant, LOCAL_IP, null);\n log.warn(\"[merge-delete] delete config info because no datum. dataId=\" + dataId + \", groupId=\" + group);\n }\n } catch (Exception e) {\n log.info(\"[merge-error] \" + dataId + \", \" + group + \", \" + e.toString(), e);\n }\n FINISHED.incrementAndGet();\n if (FINISHED.get() % 100 == 0) {\n log.info(\"[all-merge-dump] {} / {}\", FINISHED.get(), total);\n }\n }\n log.info(\"[all-merge-dump] {} / {}\", FINISHED.get(), total);\n }\n }\n\n private static final Logger log = LoggerFactory.getLogger(MergeDatumService.class);\n\n final TaskManager mergeTasks;\n}\n"} {"task_id": "Java_2322", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/intomylife/SpringCloud/springcloudalibaba-nacos-config/config-service/config-master-service/nacos-1.2.1/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java", "mask_start_position": 2291, "mask_end_position": 2517, "canonical_solution": "public void addMergeTask(String dataId, String groupId, String tenant, String clientIp) {\n MergeDataTask task = new MergeDataTask(dataId, groupId, tenant, clientIp);\n mergeTasks.addTask(task.getId(), task);\n }", "pre_mask_code": "package com.alibaba.nacos.config.server.service.merge;\n\nimport com.alibaba.nacos.config.server.manager.TaskManager;\nimport com.alibaba.nacos.config.server.model.ConfigInfo;\nimport com.alibaba.nacos.config.server.model.ConfigInfoAggr;\nimport com.alibaba.nacos.config.server.model.ConfigInfoChanged;\nimport com.alibaba.nacos.config.server.model.Page;\nimport com.alibaba.nacos.config.server.service.PersistService;\nimport com.alibaba.nacos.config.server.utils.ContentUtils;\nimport com.alibaba.nacos.config.server.utils.TimeUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport static com.alibaba.nacos.core.utils.SystemUtils.LOCAL_IP;\n\n/**\n * 数据聚合服务。\n *

\n * 启动时做全量聚合 + 修改数据触发的单条聚合\n *\n * @author jiuRen\n */\n@Service\npublic class MergeDatumService {\n\n private PersistService persistService;\n\n static final int INIT_THREAD_COUNT = 40;\n\n static final AtomicInteger FINISHED = new AtomicInteger();\n\n static int total = 0;\n\n @Autowired\n public MergeDatumService(PersistService persistService) {\n this.persistService = persistService;\n mergeTasks = new TaskManager(\"com.alibaba.nacos.MergeDatum\");\n mergeTasks.setDefaultTaskProcessor(new MergeTaskProcessor(persistService, this));\n }\n\n static List> splitList(List list, int count) {\n List> result = new ArrayList>(count);\n for (int i = 0; i < count; i++) {\n result.add(new ArrayList());\n }\n for (int i = 0; i < list.size(); i++) {\n ConfigInfoChanged config = list.get(i);\n result.get(i % count).add(config);\n }\n return result;\n }\n\n /**\n * 数据变更后调用,添加聚合任务\n */\n public void addMergeTask(String dataId, String groupId, String tenant, String tag, String clientIp) {\n MergeDataTask task = new MergeDataTask(dataId, groupId, tenant, tag, clientIp);\n mergeTasks.addTask(task.getId(), task);\n }\n\n /**\n * 数据变更后调用,添加聚合任务\n */\n ", "post_mask_code": "\n\n public void mergeAll() {\n for (ConfigInfoChanged item : persistService.findAllAggrGroup()) {\n addMergeTask(item.getDataId(), item.getGroup(), item.getTenant(), LOCAL_IP);\n }\n }\n\n class MergeAllDataWorker extends Thread {\n\n static final int PAGE_SIZE = 10000;\n\n private List configInfoList;\n\n public MergeAllDataWorker(List configInfoList) {\n super(\"MergeAllDataWorker\");\n this.configInfoList = configInfoList;\n }\n\n @Override\n public void run() {\n for (ConfigInfoChanged configInfo : configInfoList) {\n String dataId = configInfo.getDataId();\n String group = configInfo.getGroup();\n String tenant = configInfo.getTenant();\n try {\n List datumList = new ArrayList();\n int rowCount = persistService.aggrConfigInfoCount(dataId, group, tenant);\n int pageCount = (int) Math.ceil(rowCount * 1.0 / PAGE_SIZE);\n for (int pageNo = 1; pageNo <= pageCount; pageNo++) {\n Page page = persistService.findConfigInfoAggrByPage(dataId, group, tenant, pageNo, PAGE_SIZE);\n if (page != null) {\n datumList.addAll(page.getPageItems());\n log.info(\"[merge-query] {}, {}, size/total={}/{}\", dataId, group, datumList.size(), rowCount);\n }\n }\n final Timestamp time = TimeUtils.getCurrentTime();\n // 聚合\n if (datumList.size() > 0) {\n ConfigInfo cf = MergeTaskProcessor.merge(dataId, group, tenant, datumList);\n persistService.insertOrUpdate(null, null, cf, time, null, false);\n log.info(\"[merge-ok] {}, {}, size={}, length={}, md5={}, content={}\", dataId, group, datumList.size(), cf.getContent().length(), cf.getMd5(), ContentUtils.truncateContent(cf.getContent()));\n } else // 删除\n {\n persistService.removeConfigInfo(dataId, group, tenant, LOCAL_IP, null);\n log.warn(\"[merge-delete] delete config info because no datum. dataId=\" + dataId + \", groupId=\" + group);\n }\n } catch (Exception e) {\n log.info(\"[merge-error] \" + dataId + \", \" + group + \", \" + e.toString(), e);\n }\n FINISHED.incrementAndGet();\n if (FINISHED.get() % 100 == 0) {\n log.info(\"[all-merge-dump] {} / {}\", FINISHED.get(), total);\n }\n }\n log.info(\"[all-merge-dump] {} / {}\", FINISHED.get(), total);\n }\n }\n\n private static final Logger log = LoggerFactory.getLogger(MergeDatumService.class);\n\n final TaskManager mergeTasks;\n}\n"} {"task_id": "Java_2323", "language": "Java", "task_type": "for_statement", "source_file": "java/github/intomylife/SpringCloud/springcloudalibaba-nacos-config/config-service/config-master-service/nacos-1.2.1/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java", "mask_start_position": 3637, "mask_end_position": 4107, "canonical_solution": "for (int pageNo = 1; pageNo <= pageCount; pageNo++) {\n Page page = persistService.findConfigInfoAggrByPage(dataId, group, tenant, pageNo, PAGE_SIZE);\n if (page != null) {\n datumList.addAll(page.getPageItems());\n log.info(\"[merge-query] {}, {}, size/total={}/{}\", dataId, group, datumList.size(), rowCount);\n }\n }", "pre_mask_code": "package com.alibaba.nacos.config.server.service.merge;\n\nimport com.alibaba.nacos.config.server.manager.TaskManager;\nimport com.alibaba.nacos.config.server.model.ConfigInfo;\nimport com.alibaba.nacos.config.server.model.ConfigInfoAggr;\nimport com.alibaba.nacos.config.server.model.ConfigInfoChanged;\nimport com.alibaba.nacos.config.server.model.Page;\nimport com.alibaba.nacos.config.server.service.PersistService;\nimport com.alibaba.nacos.config.server.utils.ContentUtils;\nimport com.alibaba.nacos.config.server.utils.TimeUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport static com.alibaba.nacos.core.utils.SystemUtils.LOCAL_IP;\n\n/**\n * 数据聚合服务。\n *

\n * 启动时做全量聚合 + 修改数据触发的单条聚合\n *\n * @author jiuRen\n */\n@Service\npublic class MergeDatumService {\n\n private PersistService persistService;\n\n static final int INIT_THREAD_COUNT = 40;\n\n static final AtomicInteger FINISHED = new AtomicInteger();\n\n static int total = 0;\n\n @Autowired\n public MergeDatumService(PersistService persistService) {\n this.persistService = persistService;\n mergeTasks = new TaskManager(\"com.alibaba.nacos.MergeDatum\");\n mergeTasks.setDefaultTaskProcessor(new MergeTaskProcessor(persistService, this));\n }\n\n static List> splitList(List list, int count) {\n List> result = new ArrayList>(count);\n for (int i = 0; i < count; i++) {\n result.add(new ArrayList());\n }\n for (int i = 0; i < list.size(); i++) {\n ConfigInfoChanged config = list.get(i);\n result.get(i % count).add(config);\n }\n return result;\n }\n\n /**\n * 数据变更后调用,添加聚合任务\n */\n public void addMergeTask(String dataId, String groupId, String tenant, String tag, String clientIp) {\n MergeDataTask task = new MergeDataTask(dataId, groupId, tenant, tag, clientIp);\n mergeTasks.addTask(task.getId(), task);\n }\n\n /**\n * 数据变更后调用,添加聚合任务\n */\n public void addMergeTask(String dataId, String groupId, String tenant, String clientIp) {\n MergeDataTask task = new MergeDataTask(dataId, groupId, tenant, clientIp);\n mergeTasks.addTask(task.getId(), task);\n }\n\n public void mergeAll() {\n for (ConfigInfoChanged item : persistService.findAllAggrGroup()) {\n addMergeTask(item.getDataId(), item.getGroup(), item.getTenant(), LOCAL_IP);\n }\n }\n\n class MergeAllDataWorker extends Thread {\n\n static final int PAGE_SIZE = 10000;\n\n private List configInfoList;\n\n public MergeAllDataWorker(List configInfoList) {\n super(\"MergeAllDataWorker\");\n this.configInfoList = configInfoList;\n }\n\n @Override\n public void run() {\n for (ConfigInfoChanged configInfo : configInfoList) {\n String dataId = configInfo.getDataId();\n String group = configInfo.getGroup();\n String tenant = configInfo.getTenant();\n try {\n List datumList = new ArrayList();\n int rowCount = persistService.aggrConfigInfoCount(dataId, group, tenant);\n int pageCount = (int) Math.ceil(rowCount * 1.0 / PAGE_SIZE);\n ", "post_mask_code": "\n final Timestamp time = TimeUtils.getCurrentTime();\n // 聚合\n if (datumList.size() > 0) {\n ConfigInfo cf = MergeTaskProcessor.merge(dataId, group, tenant, datumList);\n persistService.insertOrUpdate(null, null, cf, time, null, false);\n log.info(\"[merge-ok] {}, {}, size={}, length={}, md5={}, content={}\", dataId, group, datumList.size(), cf.getContent().length(), cf.getMd5(), ContentUtils.truncateContent(cf.getContent()));\n } else // 删除\n {\n persistService.removeConfigInfo(dataId, group, tenant, LOCAL_IP, null);\n log.warn(\"[merge-delete] delete config info because no datum. dataId=\" + dataId + \", groupId=\" + group);\n }\n } catch (Exception e) {\n log.info(\"[merge-error] \" + dataId + \", \" + group + \", \" + e.toString(), e);\n }\n FINISHED.incrementAndGet();\n if (FINISHED.get() % 100 == 0) {\n log.info(\"[all-merge-dump] {} / {}\", FINISHED.get(), total);\n }\n }\n log.info(\"[all-merge-dump] {} / {}\", FINISHED.get(), total);\n }\n }\n\n private static final Logger log = LoggerFactory.getLogger(MergeDatumService.class);\n\n final TaskManager mergeTasks;\n}\n"} {"task_id": "Java_2324", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ISID/iPLAss/iplass-web/src/main/java/org/iplass/mtp/impl/tenant/web/MetaTenantWebInfo.java", "mask_start_position": 2093, "mask_end_position": 2132, "canonical_solution": "public void setHomeUrl(String homeUrl) ", "pre_mask_code": "package org.iplass.mtp.impl.tenant.web;\n\nimport org.codehaus.groovy.GroovyBugError;\nimport org.iplass.mtp.command.RequestContext;\nimport org.iplass.mtp.impl.core.ExecuteContext;\nimport org.iplass.mtp.impl.core.TenantContext;\nimport org.iplass.mtp.impl.metadata.MetaData;\nimport org.iplass.mtp.impl.script.Script;\nimport org.iplass.mtp.impl.script.ScriptContext;\nimport org.iplass.mtp.impl.script.ScriptEngine;\nimport org.iplass.mtp.impl.tenant.MetaTenant.MetaTenantHandler;\nimport org.iplass.mtp.impl.tenant.MetaTenantConfig;\nimport org.iplass.mtp.impl.util.ObjectUtil;\nimport org.iplass.mtp.tenant.Tenant;\nimport org.iplass.mtp.tenant.web.TenantWebInfo;\nimport org.iplass.mtp.util.StringUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class MetaTenantWebInfo extends MetaTenantConfig {\n\n private static final long serialVersionUID = -8722898685664541128L;\n\n private static final Logger logger = LoggerFactory.getLogger(MetaTenantWebInfo.class);\n\n private boolean usePreview;\n\n private String loginUrlSelector;\n\n /**\n * 再認証URLセレクター\n */\n private String reAuthUrlSelector;\n\n private String errorUrlSelector;\n\n /**\n * HOMEのURL\n */\n private String homeUrl;\n\n private String urlForRequest;\n\n public MetaTenantWebInfo() {\n }\n\n public boolean isUsePreview() {\n return usePreview;\n }\n\n public void setUsePreview(boolean usePreview) {\n this.usePreview = usePreview;\n }\n\n public String getLoginUrlSelector() {\n return loginUrlSelector;\n }\n\n public void setLoginUrlSelector(String loginUrlSelector) {\n this.loginUrlSelector = loginUrlSelector;\n }\n\n public String getReAuthUrlSelector() {\n return reAuthUrlSelector;\n }\n\n public void setReAuthUrlSelector(String reAuthUrlSelector) {\n this.reAuthUrlSelector = reAuthUrlSelector;\n }\n\n public String getErrorUrlSelector() {\n return errorUrlSelector;\n }\n\n public void setErrorUrlSelector(String errorUrlSelector) {\n this.errorUrlSelector = errorUrlSelector;\n }\n\n ", "post_mask_code": "{\n this.homeUrl = homeUrl;\n }\n\n public String getHomeUrl() {\n return homeUrl;\n }\n\n public String getUrlForRequest() {\n return urlForRequest;\n }\n\n public void setUrlForRequest(String urlForRequest) {\n this.urlForRequest = urlForRequest;\n }\n\n @Override\n public MetaData copy() {\n return ObjectUtil.deepCopy(this);\n }\n\n @Override\n public void applyConfig(TenantWebInfo definition) {\n setUsePreview(definition.isUsePreview());\n setLoginUrlSelector(definition.getLoginUrlSelector());\n setReAuthUrlSelector(definition.getReAuthUrlSelector());\n setErrorUrlSelector(definition.getErrorUrlSelector());\n setHomeUrl(definition.getHomeUrl());\n setUrlForRequest(definition.getUrlForRequest());\n }\n\n @Override\n public TenantWebInfo currentConfig() {\n TenantWebInfo definition = new TenantWebInfo();\n definition.setUsePreview(usePreview);\n definition.setLoginUrlSelector(loginUrlSelector);\n definition.setReAuthUrlSelector(reAuthUrlSelector);\n definition.setErrorUrlSelector(errorUrlSelector);\n definition.setHomeUrl(getHomeUrl());\n definition.setUrlForRequest(getUrlForRequest());\n return definition;\n }\n\n @Override\n public MetaTenantWebInfoRuntime createRuntime(MetaTenantHandler tenantRuntime) {\n return new MetaTenantWebInfoRuntime(tenantRuntime);\n }\n\n public class MetaTenantWebInfoRuntime extends MetaTenantConfigRuntime {\n\n private static final String SCRIPT_PREFIX_LOGIN_URL_SELECTOR = \"MetaTenantHandler_loginUrlSelector\";\n\n private static final String SCRIPT_PREFIX_REAUTH_URL_SELECTOR = \"MetaTenantHandler_reAuthUrlSelector\";\n\n private static final String SCRIPT_PREFIX_ERROR_URL_SELECTOR = \"MetaTenantHandler_errorUrlSelector\";\n\n private Script loginUrlSelectorScript;\n\n private Script reAuthUrlSelectorScript;\n\n private Script errorUrlSelectorScript;\n\n public MetaTenantWebInfoRuntime(MetaTenantHandler tenantRuntime) {\n TenantContext tc = ExecuteContext.getCurrentContext().getTenantContext();\n ScriptEngine scriptEngine = tc.getScriptEngine();\n try {\n if (!StringUtil.isEmpty(loginUrlSelector)) {\n loginUrlSelectorScript = scriptEngine.createScript(loginUrlSelector, SCRIPT_PREFIX_LOGIN_URL_SELECTOR + \"_\" + tenantRuntime.getMetaData().getId());\n }\n // 再認証URLセレクター\n if (!StringUtil.isEmpty(reAuthUrlSelector)) {\n reAuthUrlSelectorScript = scriptEngine.createScript(reAuthUrlSelector, SCRIPT_PREFIX_REAUTH_URL_SELECTOR + \"_\" + tenantRuntime.getMetaData().getId());\n }\n if (!StringUtil.isEmpty(errorUrlSelector)) {\n errorUrlSelectorScript = scriptEngine.createScript(errorUrlSelector, SCRIPT_PREFIX_ERROR_URL_SELECTOR + \"_\" + tenantRuntime.getMetaData().getId());\n }\n } catch (GroovyBugError | NoClassDefFoundError e) {\n setIllegalStateException(new RuntimeException(e));\n } catch (RuntimeException e) {\n setIllegalStateException(e);\n }\n }\n\n @Override\n public MetaData getMetaData() {\n return MetaTenantWebInfo.this;\n }\n\n @Override\n public void applyMetaDataToTenant(Tenant tenant) {\n }\n\n public String loginUrlSelector(RequestContext context, String path) {\n if (loginUrlSelectorScript == null) {\n return null;\n } else {\n ScriptContext sc = ExecuteContext.getCurrentContext().getTenantContext().getScriptEngine().newScriptContext();\n sc.setAttribute(\"request\", context);\n sc.setAttribute(\"path\", path);\n Object res = null;\n try {\n res = loginUrlSelectorScript.eval(sc);\n } catch (RuntimeException e) {\n logger.error(\"fail on LoginUrlSelector: \" + e.getMessage(), e);\n }\n if (res == null) {\n return null;\n } else {\n return res.toString();\n }\n }\n }\n\n public String reAuthUrlSelector(RequestContext context, String path) {\n if (reAuthUrlSelectorScript == null) {\n return null;\n } else {\n ScriptContext sc = ExecuteContext.getCurrentContext().getTenantContext().getScriptEngine().newScriptContext();\n sc.setAttribute(\"request\", context);\n sc.setAttribute(\"path\", path);\n Object res = null;\n try {\n res = reAuthUrlSelectorScript.eval(sc);\n } catch (RuntimeException e) {\n logger.error(\"fail on ReAuthUrlSelector: \" + e.getMessage(), e);\n }\n if (res == null) {\n return null;\n } else {\n return res.toString();\n }\n }\n }\n\n public String errorUrlSelector(Throwable exp, RequestContext context, String path) {\n if (errorUrlSelectorScript == null) {\n return null;\n } else {\n ScriptContext sc = ExecuteContext.getCurrentContext().getTenantContext().getScriptEngine().newScriptContext();\n sc.setAttribute(\"request\", context);\n sc.setAttribute(\"path\", path);\n sc.setAttribute(\"exception\", exp);\n Object res = null;\n try {\n res = errorUrlSelectorScript.eval(sc);\n } catch (RuntimeException e) {\n logger.error(\"fail on ErrorUrlSelectorScript: \" + e.getMessage(), e);\n }\n if (res == null) {\n return null;\n } else {\n return res.toString();\n }\n }\n }\n }\n}\n"} {"task_id": "Java_2325", "language": "Java", "task_type": "method_body", "source_file": "java/github/ISID/iPLAss/iplass-web/src/main/java/org/iplass/mtp/impl/tenant/web/MetaTenantWebInfo.java", "mask_start_position": 1430, "mask_end_position": 1475, "canonical_solution": "{\n this.usePreview = usePreview;\n }", "pre_mask_code": "package org.iplass.mtp.impl.tenant.web;\n\nimport org.codehaus.groovy.GroovyBugError;\nimport org.iplass.mtp.command.RequestContext;\nimport org.iplass.mtp.impl.core.ExecuteContext;\nimport org.iplass.mtp.impl.core.TenantContext;\nimport org.iplass.mtp.impl.metadata.MetaData;\nimport org.iplass.mtp.impl.script.Script;\nimport org.iplass.mtp.impl.script.ScriptContext;\nimport org.iplass.mtp.impl.script.ScriptEngine;\nimport org.iplass.mtp.impl.tenant.MetaTenant.MetaTenantHandler;\nimport org.iplass.mtp.impl.tenant.MetaTenantConfig;\nimport org.iplass.mtp.impl.util.ObjectUtil;\nimport org.iplass.mtp.tenant.Tenant;\nimport org.iplass.mtp.tenant.web.TenantWebInfo;\nimport org.iplass.mtp.util.StringUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class MetaTenantWebInfo extends MetaTenantConfig {\n\n private static final long serialVersionUID = -8722898685664541128L;\n\n private static final Logger logger = LoggerFactory.getLogger(MetaTenantWebInfo.class);\n\n private boolean usePreview;\n\n private String loginUrlSelector;\n\n /**\n * 再認証URLセレクター\n */\n private String reAuthUrlSelector;\n\n private String errorUrlSelector;\n\n /**\n * HOMEのURL\n */\n private String homeUrl;\n\n private String urlForRequest;\n\n public MetaTenantWebInfo() {\n }\n\n public boolean isUsePreview() {\n return usePreview;\n }\n\n public void setUsePreview(boolean usePreview) ", "post_mask_code": "\n\n public String getLoginUrlSelector() {\n return loginUrlSelector;\n }\n\n public void setLoginUrlSelector(String loginUrlSelector) {\n this.loginUrlSelector = loginUrlSelector;\n }\n\n public String getReAuthUrlSelector() {\n return reAuthUrlSelector;\n }\n\n public void setReAuthUrlSelector(String reAuthUrlSelector) {\n this.reAuthUrlSelector = reAuthUrlSelector;\n }\n\n public String getErrorUrlSelector() {\n return errorUrlSelector;\n }\n\n public void setErrorUrlSelector(String errorUrlSelector) {\n this.errorUrlSelector = errorUrlSelector;\n }\n\n public void setHomeUrl(String homeUrl) {\n this.homeUrl = homeUrl;\n }\n\n public String getHomeUrl() {\n return homeUrl;\n }\n\n public String getUrlForRequest() {\n return urlForRequest;\n }\n\n public void setUrlForRequest(String urlForRequest) {\n this.urlForRequest = urlForRequest;\n }\n\n @Override\n public MetaData copy() {\n return ObjectUtil.deepCopy(this);\n }\n\n @Override\n public void applyConfig(TenantWebInfo definition) {\n setUsePreview(definition.isUsePreview());\n setLoginUrlSelector(definition.getLoginUrlSelector());\n setReAuthUrlSelector(definition.getReAuthUrlSelector());\n setErrorUrlSelector(definition.getErrorUrlSelector());\n setHomeUrl(definition.getHomeUrl());\n setUrlForRequest(definition.getUrlForRequest());\n }\n\n @Override\n public TenantWebInfo currentConfig() {\n TenantWebInfo definition = new TenantWebInfo();\n definition.setUsePreview(usePreview);\n definition.setLoginUrlSelector(loginUrlSelector);\n definition.setReAuthUrlSelector(reAuthUrlSelector);\n definition.setErrorUrlSelector(errorUrlSelector);\n definition.setHomeUrl(getHomeUrl());\n definition.setUrlForRequest(getUrlForRequest());\n return definition;\n }\n\n @Override\n public MetaTenantWebInfoRuntime createRuntime(MetaTenantHandler tenantRuntime) {\n return new MetaTenantWebInfoRuntime(tenantRuntime);\n }\n\n public class MetaTenantWebInfoRuntime extends MetaTenantConfigRuntime {\n\n private static final String SCRIPT_PREFIX_LOGIN_URL_SELECTOR = \"MetaTenantHandler_loginUrlSelector\";\n\n private static final String SCRIPT_PREFIX_REAUTH_URL_SELECTOR = \"MetaTenantHandler_reAuthUrlSelector\";\n\n private static final String SCRIPT_PREFIX_ERROR_URL_SELECTOR = \"MetaTenantHandler_errorUrlSelector\";\n\n private Script loginUrlSelectorScript;\n\n private Script reAuthUrlSelectorScript;\n\n private Script errorUrlSelectorScript;\n\n public MetaTenantWebInfoRuntime(MetaTenantHandler tenantRuntime) {\n TenantContext tc = ExecuteContext.getCurrentContext().getTenantContext();\n ScriptEngine scriptEngine = tc.getScriptEngine();\n try {\n if (!StringUtil.isEmpty(loginUrlSelector)) {\n loginUrlSelectorScript = scriptEngine.createScript(loginUrlSelector, SCRIPT_PREFIX_LOGIN_URL_SELECTOR + \"_\" + tenantRuntime.getMetaData().getId());\n }\n // 再認証URLセレクター\n if (!StringUtil.isEmpty(reAuthUrlSelector)) {\n reAuthUrlSelectorScript = scriptEngine.createScript(reAuthUrlSelector, SCRIPT_PREFIX_REAUTH_URL_SELECTOR + \"_\" + tenantRuntime.getMetaData().getId());\n }\n if (!StringUtil.isEmpty(errorUrlSelector)) {\n errorUrlSelectorScript = scriptEngine.createScript(errorUrlSelector, SCRIPT_PREFIX_ERROR_URL_SELECTOR + \"_\" + tenantRuntime.getMetaData().getId());\n }\n } catch (GroovyBugError | NoClassDefFoundError e) {\n setIllegalStateException(new RuntimeException(e));\n } catch (RuntimeException e) {\n setIllegalStateException(e);\n }\n }\n\n @Override\n public MetaData getMetaData() {\n return MetaTenantWebInfo.this;\n }\n\n @Override\n public void applyMetaDataToTenant(Tenant tenant) {\n }\n\n public String loginUrlSelector(RequestContext context, String path) {\n if (loginUrlSelectorScript == null) {\n return null;\n } else {\n ScriptContext sc = ExecuteContext.getCurrentContext().getTenantContext().getScriptEngine().newScriptContext();\n sc.setAttribute(\"request\", context);\n sc.setAttribute(\"path\", path);\n Object res = null;\n try {\n res = loginUrlSelectorScript.eval(sc);\n } catch (RuntimeException e) {\n logger.error(\"fail on LoginUrlSelector: \" + e.getMessage(), e);\n }\n if (res == null) {\n return null;\n } else {\n return res.toString();\n }\n }\n }\n\n public String reAuthUrlSelector(RequestContext context, String path) {\n if (reAuthUrlSelectorScript == null) {\n return null;\n } else {\n ScriptContext sc = ExecuteContext.getCurrentContext().getTenantContext().getScriptEngine().newScriptContext();\n sc.setAttribute(\"request\", context);\n sc.setAttribute(\"path\", path);\n Object res = null;\n try {\n res = reAuthUrlSelectorScript.eval(sc);\n } catch (RuntimeException e) {\n logger.error(\"fail on ReAuthUrlSelector: \" + e.getMessage(), e);\n }\n if (res == null) {\n return null;\n } else {\n return res.toString();\n }\n }\n }\n\n public String errorUrlSelector(Throwable exp, RequestContext context, String path) {\n if (errorUrlSelectorScript == null) {\n return null;\n } else {\n ScriptContext sc = ExecuteContext.getCurrentContext().getTenantContext().getScriptEngine().newScriptContext();\n sc.setAttribute(\"request\", context);\n sc.setAttribute(\"path\", path);\n sc.setAttribute(\"exception\", exp);\n Object res = null;\n try {\n res = errorUrlSelectorScript.eval(sc);\n } catch (RuntimeException e) {\n logger.error(\"fail on ErrorUrlSelectorScript: \" + e.getMessage(), e);\n }\n if (res == null) {\n return null;\n } else {\n return res.toString();\n }\n }\n }\n }\n}\n"} {"task_id": "Java_2326", "language": "Java", "task_type": "single_line", "source_file": "java/github/ISID/iPLAss/iplass-web/src/main/java/org/iplass/mtp/impl/tenant/web/MetaTenantWebInfo.java", "mask_start_position": 2300, "mask_end_position": 2305, "canonical_solution": "uest;", "pre_mask_code": "package org.iplass.mtp.impl.tenant.web;\n\nimport org.codehaus.groovy.GroovyBugError;\nimport org.iplass.mtp.command.RequestContext;\nimport org.iplass.mtp.impl.core.ExecuteContext;\nimport org.iplass.mtp.impl.core.TenantContext;\nimport org.iplass.mtp.impl.metadata.MetaData;\nimport org.iplass.mtp.impl.script.Script;\nimport org.iplass.mtp.impl.script.ScriptContext;\nimport org.iplass.mtp.impl.script.ScriptEngine;\nimport org.iplass.mtp.impl.tenant.MetaTenant.MetaTenantHandler;\nimport org.iplass.mtp.impl.tenant.MetaTenantConfig;\nimport org.iplass.mtp.impl.util.ObjectUtil;\nimport org.iplass.mtp.tenant.Tenant;\nimport org.iplass.mtp.tenant.web.TenantWebInfo;\nimport org.iplass.mtp.util.StringUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class MetaTenantWebInfo extends MetaTenantConfig {\n\n private static final long serialVersionUID = -8722898685664541128L;\n\n private static final Logger logger = LoggerFactory.getLogger(MetaTenantWebInfo.class);\n\n private boolean usePreview;\n\n private String loginUrlSelector;\n\n /**\n * 再認証URLセレクター\n */\n private String reAuthUrlSelector;\n\n private String errorUrlSelector;\n\n /**\n * HOMEのURL\n */\n private String homeUrl;\n\n private String urlForRequest;\n\n public MetaTenantWebInfo() {\n }\n\n public boolean isUsePreview() {\n return usePreview;\n }\n\n public void setUsePreview(boolean usePreview) {\n this.usePreview = usePreview;\n }\n\n public String getLoginUrlSelector() {\n return loginUrlSelector;\n }\n\n public void setLoginUrlSelector(String loginUrlSelector) {\n this.loginUrlSelector = loginUrlSelector;\n }\n\n public String getReAuthUrlSelector() {\n return reAuthUrlSelector;\n }\n\n public void setReAuthUrlSelector(String reAuthUrlSelector) {\n this.reAuthUrlSelector = reAuthUrlSelector;\n }\n\n public String getErrorUrlSelector() {\n return errorUrlSelector;\n }\n\n public void setErrorUrlSelector(String errorUrlSelector) {\n this.errorUrlSelector = errorUrlSelector;\n }\n\n public void setHomeUrl(String homeUrl) {\n this.homeUrl = homeUrl;\n }\n\n public String getHomeUrl() {\n return homeUrl;\n }\n\n public String getUrlForRequest() {\n return urlForReq", "post_mask_code": "\n }\n\n public void setUrlForRequest(String urlForRequest) {\n this.urlForRequest = urlForRequest;\n }\n\n @Override\n public MetaData copy() {\n return ObjectUtil.deepCopy(this);\n }\n\n @Override\n public void applyConfig(TenantWebInfo definition) {\n setUsePreview(definition.isUsePreview());\n setLoginUrlSelector(definition.getLoginUrlSelector());\n setReAuthUrlSelector(definition.getReAuthUrlSelector());\n setErrorUrlSelector(definition.getErrorUrlSelector());\n setHomeUrl(definition.getHomeUrl());\n setUrlForRequest(definition.getUrlForRequest());\n }\n\n @Override\n public TenantWebInfo currentConfig() {\n TenantWebInfo definition = new TenantWebInfo();\n definition.setUsePreview(usePreview);\n definition.setLoginUrlSelector(loginUrlSelector);\n definition.setReAuthUrlSelector(reAuthUrlSelector);\n definition.setErrorUrlSelector(errorUrlSelector);\n definition.setHomeUrl(getHomeUrl());\n definition.setUrlForRequest(getUrlForRequest());\n return definition;\n }\n\n @Override\n public MetaTenantWebInfoRuntime createRuntime(MetaTenantHandler tenantRuntime) {\n return new MetaTenantWebInfoRuntime(tenantRuntime);\n }\n\n public class MetaTenantWebInfoRuntime extends MetaTenantConfigRuntime {\n\n private static final String SCRIPT_PREFIX_LOGIN_URL_SELECTOR = \"MetaTenantHandler_loginUrlSelector\";\n\n private static final String SCRIPT_PREFIX_REAUTH_URL_SELECTOR = \"MetaTenantHandler_reAuthUrlSelector\";\n\n private static final String SCRIPT_PREFIX_ERROR_URL_SELECTOR = \"MetaTenantHandler_errorUrlSelector\";\n\n private Script loginUrlSelectorScript;\n\n private Script reAuthUrlSelectorScript;\n\n private Script errorUrlSelectorScript;\n\n public MetaTenantWebInfoRuntime(MetaTenantHandler tenantRuntime) {\n TenantContext tc = ExecuteContext.getCurrentContext().getTenantContext();\n ScriptEngine scriptEngine = tc.getScriptEngine();\n try {\n if (!StringUtil.isEmpty(loginUrlSelector)) {\n loginUrlSelectorScript = scriptEngine.createScript(loginUrlSelector, SCRIPT_PREFIX_LOGIN_URL_SELECTOR + \"_\" + tenantRuntime.getMetaData().getId());\n }\n // 再認証URLセレクター\n if (!StringUtil.isEmpty(reAuthUrlSelector)) {\n reAuthUrlSelectorScript = scriptEngine.createScript(reAuthUrlSelector, SCRIPT_PREFIX_REAUTH_URL_SELECTOR + \"_\" + tenantRuntime.getMetaData().getId());\n }\n if (!StringUtil.isEmpty(errorUrlSelector)) {\n errorUrlSelectorScript = scriptEngine.createScript(errorUrlSelector, SCRIPT_PREFIX_ERROR_URL_SELECTOR + \"_\" + tenantRuntime.getMetaData().getId());\n }\n } catch (GroovyBugError | NoClassDefFoundError e) {\n setIllegalStateException(new RuntimeException(e));\n } catch (RuntimeException e) {\n setIllegalStateException(e);\n }\n }\n\n @Override\n public MetaData getMetaData() {\n return MetaTenantWebInfo.this;\n }\n\n @Override\n public void applyMetaDataToTenant(Tenant tenant) {\n }\n\n public String loginUrlSelector(RequestContext context, String path) {\n if (loginUrlSelectorScript == null) {\n return null;\n } else {\n ScriptContext sc = ExecuteContext.getCurrentContext().getTenantContext().getScriptEngine().newScriptContext();\n sc.setAttribute(\"request\", context);\n sc.setAttribute(\"path\", path);\n Object res = null;\n try {\n res = loginUrlSelectorScript.eval(sc);\n } catch (RuntimeException e) {\n logger.error(\"fail on LoginUrlSelector: \" + e.getMessage(), e);\n }\n if (res == null) {\n return null;\n } else {\n return res.toString();\n }\n }\n }\n\n public String reAuthUrlSelector(RequestContext context, String path) {\n if (reAuthUrlSelectorScript == null) {\n return null;\n } else {\n ScriptContext sc = ExecuteContext.getCurrentContext().getTenantContext().getScriptEngine().newScriptContext();\n sc.setAttribute(\"request\", context);\n sc.setAttribute(\"path\", path);\n Object res = null;\n try {\n res = reAuthUrlSelectorScript.eval(sc);\n } catch (RuntimeException e) {\n logger.error(\"fail on ReAuthUrlSelector: \" + e.getMessage(), e);\n }\n if (res == null) {\n return null;\n } else {\n return res.toString();\n }\n }\n }\n\n public String errorUrlSelector(Throwable exp, RequestContext context, String path) {\n if (errorUrlSelectorScript == null) {\n return null;\n } else {\n ScriptContext sc = ExecuteContext.getCurrentContext().getTenantContext().getScriptEngine().newScriptContext();\n sc.setAttribute(\"request\", context);\n sc.setAttribute(\"path\", path);\n sc.setAttribute(\"exception\", exp);\n Object res = null;\n try {\n res = errorUrlSelectorScript.eval(sc);\n } catch (RuntimeException e) {\n logger.error(\"fail on ErrorUrlSelectorScript: \" + e.getMessage(), e);\n }\n if (res == null) {\n return null;\n } else {\n return res.toString();\n }\n }\n }\n }\n}\n"} {"task_id": "Java_2327", "language": "Java", "task_type": "try_statement", "source_file": "java/github/ISID/iPLAss/iplass-web/src/main/java/org/iplass/mtp/impl/tenant/web/MetaTenantWebInfo.java", "mask_start_position": 7809, "mask_end_position": 8028, "canonical_solution": "try {\n res = errorUrlSelectorScript.eval(sc);\n } catch (RuntimeException e) {\n logger.error(\"fail on ErrorUrlSelectorScript: \" + e.getMessage(), e);\n }", "pre_mask_code": "package org.iplass.mtp.impl.tenant.web;\n\nimport org.codehaus.groovy.GroovyBugError;\nimport org.iplass.mtp.command.RequestContext;\nimport org.iplass.mtp.impl.core.ExecuteContext;\nimport org.iplass.mtp.impl.core.TenantContext;\nimport org.iplass.mtp.impl.metadata.MetaData;\nimport org.iplass.mtp.impl.script.Script;\nimport org.iplass.mtp.impl.script.ScriptContext;\nimport org.iplass.mtp.impl.script.ScriptEngine;\nimport org.iplass.mtp.impl.tenant.MetaTenant.MetaTenantHandler;\nimport org.iplass.mtp.impl.tenant.MetaTenantConfig;\nimport org.iplass.mtp.impl.util.ObjectUtil;\nimport org.iplass.mtp.tenant.Tenant;\nimport org.iplass.mtp.tenant.web.TenantWebInfo;\nimport org.iplass.mtp.util.StringUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class MetaTenantWebInfo extends MetaTenantConfig {\n\n private static final long serialVersionUID = -8722898685664541128L;\n\n private static final Logger logger = LoggerFactory.getLogger(MetaTenantWebInfo.class);\n\n private boolean usePreview;\n\n private String loginUrlSelector;\n\n /**\n * 再認証URLセレクター\n */\n private String reAuthUrlSelector;\n\n private String errorUrlSelector;\n\n /**\n * HOMEのURL\n */\n private String homeUrl;\n\n private String urlForRequest;\n\n public MetaTenantWebInfo() {\n }\n\n public boolean isUsePreview() {\n return usePreview;\n }\n\n public void setUsePreview(boolean usePreview) {\n this.usePreview = usePreview;\n }\n\n public String getLoginUrlSelector() {\n return loginUrlSelector;\n }\n\n public void setLoginUrlSelector(String loginUrlSelector) {\n this.loginUrlSelector = loginUrlSelector;\n }\n\n public String getReAuthUrlSelector() {\n return reAuthUrlSelector;\n }\n\n public void setReAuthUrlSelector(String reAuthUrlSelector) {\n this.reAuthUrlSelector = reAuthUrlSelector;\n }\n\n public String getErrorUrlSelector() {\n return errorUrlSelector;\n }\n\n public void setErrorUrlSelector(String errorUrlSelector) {\n this.errorUrlSelector = errorUrlSelector;\n }\n\n public void setHomeUrl(String homeUrl) {\n this.homeUrl = homeUrl;\n }\n\n public String getHomeUrl() {\n return homeUrl;\n }\n\n public String getUrlForRequest() {\n return urlForRequest;\n }\n\n public void setUrlForRequest(String urlForRequest) {\n this.urlForRequest = urlForRequest;\n }\n\n @Override\n public MetaData copy() {\n return ObjectUtil.deepCopy(this);\n }\n\n @Override\n public void applyConfig(TenantWebInfo definition) {\n setUsePreview(definition.isUsePreview());\n setLoginUrlSelector(definition.getLoginUrlSelector());\n setReAuthUrlSelector(definition.getReAuthUrlSelector());\n setErrorUrlSelector(definition.getErrorUrlSelector());\n setHomeUrl(definition.getHomeUrl());\n setUrlForRequest(definition.getUrlForRequest());\n }\n\n @Override\n public TenantWebInfo currentConfig() {\n TenantWebInfo definition = new TenantWebInfo();\n definition.setUsePreview(usePreview);\n definition.setLoginUrlSelector(loginUrlSelector);\n definition.setReAuthUrlSelector(reAuthUrlSelector);\n definition.setErrorUrlSelector(errorUrlSelector);\n definition.setHomeUrl(getHomeUrl());\n definition.setUrlForRequest(getUrlForRequest());\n return definition;\n }\n\n @Override\n public MetaTenantWebInfoRuntime createRuntime(MetaTenantHandler tenantRuntime) {\n return new MetaTenantWebInfoRuntime(tenantRuntime);\n }\n\n public class MetaTenantWebInfoRuntime extends MetaTenantConfigRuntime {\n\n private static final String SCRIPT_PREFIX_LOGIN_URL_SELECTOR = \"MetaTenantHandler_loginUrlSelector\";\n\n private static final String SCRIPT_PREFIX_REAUTH_URL_SELECTOR = \"MetaTenantHandler_reAuthUrlSelector\";\n\n private static final String SCRIPT_PREFIX_ERROR_URL_SELECTOR = \"MetaTenantHandler_errorUrlSelector\";\n\n private Script loginUrlSelectorScript;\n\n private Script reAuthUrlSelectorScript;\n\n private Script errorUrlSelectorScript;\n\n public MetaTenantWebInfoRuntime(MetaTenantHandler tenantRuntime) {\n TenantContext tc = ExecuteContext.getCurrentContext().getTenantContext();\n ScriptEngine scriptEngine = tc.getScriptEngine();\n try {\n if (!StringUtil.isEmpty(loginUrlSelector)) {\n loginUrlSelectorScript = scriptEngine.createScript(loginUrlSelector, SCRIPT_PREFIX_LOGIN_URL_SELECTOR + \"_\" + tenantRuntime.getMetaData().getId());\n }\n // 再認証URLセレクター\n if (!StringUtil.isEmpty(reAuthUrlSelector)) {\n reAuthUrlSelectorScript = scriptEngine.createScript(reAuthUrlSelector, SCRIPT_PREFIX_REAUTH_URL_SELECTOR + \"_\" + tenantRuntime.getMetaData().getId());\n }\n if (!StringUtil.isEmpty(errorUrlSelector)) {\n errorUrlSelectorScript = scriptEngine.createScript(errorUrlSelector, SCRIPT_PREFIX_ERROR_URL_SELECTOR + \"_\" + tenantRuntime.getMetaData().getId());\n }\n } catch (GroovyBugError | NoClassDefFoundError e) {\n setIllegalStateException(new RuntimeException(e));\n } catch (RuntimeException e) {\n setIllegalStateException(e);\n }\n }\n\n @Override\n public MetaData getMetaData() {\n return MetaTenantWebInfo.this;\n }\n\n @Override\n public void applyMetaDataToTenant(Tenant tenant) {\n }\n\n public String loginUrlSelector(RequestContext context, String path) {\n if (loginUrlSelectorScript == null) {\n return null;\n } else {\n ScriptContext sc = ExecuteContext.getCurrentContext().getTenantContext().getScriptEngine().newScriptContext();\n sc.setAttribute(\"request\", context);\n sc.setAttribute(\"path\", path);\n Object res = null;\n try {\n res = loginUrlSelectorScript.eval(sc);\n } catch (RuntimeException e) {\n logger.error(\"fail on LoginUrlSelector: \" + e.getMessage(), e);\n }\n if (res == null) {\n return null;\n } else {\n return res.toString();\n }\n }\n }\n\n public String reAuthUrlSelector(RequestContext context, String path) {\n if (reAuthUrlSelectorScript == null) {\n return null;\n } else {\n ScriptContext sc = ExecuteContext.getCurrentContext().getTenantContext().getScriptEngine().newScriptContext();\n sc.setAttribute(\"request\", context);\n sc.setAttribute(\"path\", path);\n Object res = null;\n try {\n res = reAuthUrlSelectorScript.eval(sc);\n } catch (RuntimeException e) {\n logger.error(\"fail on ReAuthUrlSelector: \" + e.getMessage(), e);\n }\n if (res == null) {\n return null;\n } else {\n return res.toString();\n }\n }\n }\n\n public String errorUrlSelector(Throwable exp, RequestContext context, String path) {\n if (errorUrlSelectorScript == null) {\n return null;\n } else {\n ScriptContext sc = ExecuteContext.getCurrentContext().getTenantContext().getScriptEngine().newScriptContext();\n sc.setAttribute(\"request\", context);\n sc.setAttribute(\"path\", path);\n sc.setAttribute(\"exception\", exp);\n Object res = null;\n ", "post_mask_code": "\n if (res == null) {\n return null;\n } else {\n return res.toString();\n }\n }\n }\n }\n}\n"} {"task_id": "Java_2328", "language": "Java", "task_type": "method_signature", "source_file": "java/github/dstmath/OppoFramework/A72n_10_0_0/src/main/java/com/color/inner/view/TextureViewWrapper.java", "mask_start_position": 277, "mask_end_position": 371, "canonical_solution": "public static void setCallBackSizeChangeWhenLayerUpdate(TextureView view, boolean doCallBack) ", "pre_mask_code": "package com.color.inner.view;\n\nimport android.util.Log;\nimport android.view.OppoBaseTextureView;\nimport android.view.TextureView;\nimport com.color.util.ColorTypeCastingHelper;\n\npublic class TextureViewWrapper {\n\n private static final String TAG = \"TextureViewWrapper\";\n\n ", "post_mask_code": "{\n try {\n typeCasting(view).setCallBackSizeChangeWhenLayerUpdate(doCallBack);\n } catch (Exception e) {\n Log.e(TAG, e.toString());\n }\n }\n\n private static OppoBaseTextureView typeCasting(TextureView textureView) {\n return (OppoBaseTextureView) ColorTypeCastingHelper.typeCasting(OppoBaseTextureView.class, textureView);\n }\n}\n"} {"task_id": "Java_2329", "language": "Java", "task_type": "method_body", "source_file": "java/github/dstmath/OppoFramework/A72n_10_0_0/src/main/java/com/color/inner/view/TextureViewWrapper.java", "mask_start_position": 630, "mask_end_position": 750, "canonical_solution": "{\n return (OppoBaseTextureView) ColorTypeCastingHelper.typeCasting(OppoBaseTextureView.class, textureView);\n }", "pre_mask_code": "package com.color.inner.view;\n\nimport android.util.Log;\nimport android.view.OppoBaseTextureView;\nimport android.view.TextureView;\nimport com.color.util.ColorTypeCastingHelper;\n\npublic class TextureViewWrapper {\n\n private static final String TAG = \"TextureViewWrapper\";\n\n public static void setCallBackSizeChangeWhenLayerUpdate(TextureView view, boolean doCallBack) {\n try {\n typeCasting(view).setCallBackSizeChangeWhenLayerUpdate(doCallBack);\n } catch (Exception e) {\n Log.e(TAG, e.toString());\n }\n }\n\n private static OppoBaseTextureView typeCasting(TextureView textureView) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2330", "language": "Java", "task_type": "single_line", "source_file": "java/github/dstmath/OppoFramework/A72n_10_0_0/src/main/java/com/color/inner/view/TextureViewWrapper.java", "mask_start_position": 740, "mask_end_position": 744, "canonical_solution": "ew);", "pre_mask_code": "package com.color.inner.view;\n\nimport android.util.Log;\nimport android.view.OppoBaseTextureView;\nimport android.view.TextureView;\nimport com.color.util.ColorTypeCastingHelper;\n\npublic class TextureViewWrapper {\n\n private static final String TAG = \"TextureViewWrapper\";\n\n public static void setCallBackSizeChangeWhenLayerUpdate(TextureView view, boolean doCallBack) {\n try {\n typeCasting(view).setCallBackSizeChangeWhenLayerUpdate(doCallBack);\n } catch (Exception e) {\n Log.e(TAG, e.toString());\n }\n }\n\n private static OppoBaseTextureView typeCasting(TextureView textureView) {\n return (OppoBaseTextureView) ColorTypeCastingHelper.typeCasting(OppoBaseTextureView.class, textureVi", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2331", "language": "Java", "task_type": "try_statement", "source_file": "java/github/dstmath/OppoFramework/A72n_10_0_0/src/main/java/com/color/inner/view/TextureViewWrapper.java", "mask_start_position": 381, "mask_end_position": 546, "canonical_solution": "try {\n typeCasting(view).setCallBackSizeChangeWhenLayerUpdate(doCallBack);\n } catch (Exception e) {\n Log.e(TAG, e.toString());\n }", "pre_mask_code": "package com.color.inner.view;\n\nimport android.util.Log;\nimport android.view.OppoBaseTextureView;\nimport android.view.TextureView;\nimport com.color.util.ColorTypeCastingHelper;\n\npublic class TextureViewWrapper {\n\n private static final String TAG = \"TextureViewWrapper\";\n\n public static void setCallBackSizeChangeWhenLayerUpdate(TextureView view, boolean doCallBack) {\n ", "post_mask_code": "\n }\n\n private static OppoBaseTextureView typeCasting(TextureView textureView) {\n return (OppoBaseTextureView) ColorTypeCastingHelper.typeCasting(OppoBaseTextureView.class, textureView);\n }\n}\n"} {"task_id": "Java_2332", "language": "Java", "task_type": "method_signature", "source_file": "java/github/speedment/jpa-streamer/criteria/src/main/java/com/speedment/jpastreamer/criteria/CriteriaFactory.java", "mask_start_position": 2315, "mask_end_position": 2481, "canonical_solution": "default Criteria createCriteria(final EntityManager entityManager, final Class entityClass, final Class returnClass) ", "pre_mask_code": "/*\n * JPAstreamer - Express JPA queries with Java Streams\n *\n *\n * See: http://example.com\n */\npackage com.speedment.jpastreamer.criteria;\n\nimport static java.util.Objects.requireNonNull;\nimport javax.persistence.EntityManager;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Root;\n\n/**\n * @author Mislav Milicevic\n * @since 0.0.9\n */\npublic interface CriteriaFactory {\n\n /**\n * Creates and returns a {@code Criteria} containing the provided {@code builder},\n * {@code query} and {@code root}.\n *\n * @param builder to store in the {@code Criteria}\n * @param query to store in the {@code Criteria}\n * @param root to store in the {@code Criteria}\n * @param root entity\n * @param type returned by the query\n * @return a {@code Criteria} containing the provided {@code builder},\n * {@code query} and {@code root}\n */\n Criteria createCriteria(final CriteriaBuilder builder, final CriteriaQuery query, final Root root);\n\n /**\n * Creates and returns a {@code Criteria} where the {@code CriteriaBuilder},\n * {@code CriteriaQuery} and {@code Root} are created by the provided {@code entityManager}.\n *\n * @param entityManager used to create the necessary {@code Criteria} objects\n * @param entityClass used to define the result model of the stored query and root\n * @param root entity\n * @return a {@code Criteria}\n */\n default Criteria createCriteria(final EntityManager entityManager, final Class entityClass) {\n return createCriteria(entityManager, entityClass, entityClass);\n }\n\n /**\n * Creates and returns a {@code Criteria} where the {@code CriteriaBuilder},\n * {@code CriteriaQuery} and {@code Root} are created by the provided {@code entityManager}.\n *\n * @param entityManager used to create the necessary {@code Criteria} objects\n * @param entityClass used to define the result model of the root\n * @param returnClass used to define the result model of the query\n * @param root entity\n * @param query return entity\n * @return a {@code Criteria}\n */\n ", "post_mask_code": "{\n requireNonNull(entityManager);\n requireNonNull(entityClass);\n requireNonNull(returnClass);\n final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();\n final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(returnClass);\n final Root root = criteriaQuery.from(entityClass);\n return createCriteria(criteriaBuilder, criteriaQuery, root);\n }\n}\n"} {"task_id": "Java_2333", "language": "Java", "task_type": "method_body", "source_file": "java/github/speedment/jpa-streamer/criteria/src/main/java/com/speedment/jpastreamer/criteria/CriteriaFactory.java", "mask_start_position": 1694, "mask_end_position": 1773, "canonical_solution": "{\n return createCriteria(entityManager, entityClass, entityClass);\n }", "pre_mask_code": "/*\n * JPAstreamer - Express JPA queries with Java Streams\n *\n *\n * See: http://example.com\n */\npackage com.speedment.jpastreamer.criteria;\n\nimport static java.util.Objects.requireNonNull;\nimport javax.persistence.EntityManager;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Root;\n\n/**\n * @author Mislav Milicevic\n * @since 0.0.9\n */\npublic interface CriteriaFactory {\n\n /**\n * Creates and returns a {@code Criteria} containing the provided {@code builder},\n * {@code query} and {@code root}.\n *\n * @param builder to store in the {@code Criteria}\n * @param query to store in the {@code Criteria}\n * @param root to store in the {@code Criteria}\n * @param root entity\n * @param type returned by the query\n * @return a {@code Criteria} containing the provided {@code builder},\n * {@code query} and {@code root}\n */\n Criteria createCriteria(final CriteriaBuilder builder, final CriteriaQuery query, final Root root);\n\n /**\n * Creates and returns a {@code Criteria} where the {@code CriteriaBuilder},\n * {@code CriteriaQuery} and {@code Root} are created by the provided {@code entityManager}.\n *\n * @param entityManager used to create the necessary {@code Criteria} objects\n * @param entityClass used to define the result model of the stored query and root\n * @param root entity\n * @return a {@code Criteria}\n */\n default Criteria createCriteria(final EntityManager entityManager, final Class entityClass) ", "post_mask_code": "\n\n /**\n * Creates and returns a {@code Criteria} where the {@code CriteriaBuilder},\n * {@code CriteriaQuery} and {@code Root} are created by the provided {@code entityManager}.\n *\n * @param entityManager used to create the necessary {@code Criteria} objects\n * @param entityClass used to define the result model of the root\n * @param returnClass used to define the result model of the query\n * @param root entity\n * @param query return entity\n * @return a {@code Criteria}\n */\n default Criteria createCriteria(final EntityManager entityManager, final Class entityClass, final Class returnClass) {\n requireNonNull(entityManager);\n requireNonNull(entityClass);\n requireNonNull(returnClass);\n final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();\n final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(returnClass);\n final Root root = criteriaQuery.from(entityClass);\n return createCriteria(criteriaBuilder, criteriaQuery, root);\n }\n}\n"} {"task_id": "Java_2334", "language": "Java", "task_type": "single_line", "source_file": "java/github/speedment/jpa-streamer/criteria/src/main/java/com/speedment/jpastreamer/criteria/CriteriaFactory.java", "mask_start_position": 2572, "mask_end_position": 2595, "canonical_solution": "reNonNull(returnClass);", "pre_mask_code": "/*\n * JPAstreamer - Express JPA queries with Java Streams\n *\n *\n * See: http://example.com\n */\npackage com.speedment.jpastreamer.criteria;\n\nimport static java.util.Objects.requireNonNull;\nimport javax.persistence.EntityManager;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Root;\n\n/**\n * @author Mislav Milicevic\n * @since 0.0.9\n */\npublic interface CriteriaFactory {\n\n /**\n * Creates and returns a {@code Criteria} containing the provided {@code builder},\n * {@code query} and {@code root}.\n *\n * @param builder to store in the {@code Criteria}\n * @param query to store in the {@code Criteria}\n * @param root to store in the {@code Criteria}\n * @param root entity\n * @param type returned by the query\n * @return a {@code Criteria} containing the provided {@code builder},\n * {@code query} and {@code root}\n */\n Criteria createCriteria(final CriteriaBuilder builder, final CriteriaQuery query, final Root root);\n\n /**\n * Creates and returns a {@code Criteria} where the {@code CriteriaBuilder},\n * {@code CriteriaQuery} and {@code Root} are created by the provided {@code entityManager}.\n *\n * @param entityManager used to create the necessary {@code Criteria} objects\n * @param entityClass used to define the result model of the stored query and root\n * @param root entity\n * @return a {@code Criteria}\n */\n default Criteria createCriteria(final EntityManager entityManager, final Class entityClass) {\n return createCriteria(entityManager, entityClass, entityClass);\n }\n\n /**\n * Creates and returns a {@code Criteria} where the {@code CriteriaBuilder},\n * {@code CriteriaQuery} and {@code Root} are created by the provided {@code entityManager}.\n *\n * @param entityManager used to create the necessary {@code Criteria} objects\n * @param entityClass used to define the result model of the root\n * @param returnClass used to define the result model of the query\n * @param root entity\n * @param query return entity\n * @return a {@code Criteria}\n */\n default Criteria createCriteria(final EntityManager entityManager, final Class entityClass, final Class returnClass) {\n requireNonNull(entityManager);\n requireNonNull(entityClass);\n requi", "post_mask_code": "\n final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();\n final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(returnClass);\n final Root root = criteriaQuery.from(entityClass);\n return createCriteria(criteriaBuilder, criteriaQuery, root);\n }\n}\n"} {"task_id": "Java_2335", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/speedment/jpa-streamer/criteria/src/main/java/com/speedment/jpastreamer/criteria/CriteriaFactory.java", "mask_start_position": 1569, "mask_end_position": 1773, "canonical_solution": "default Criteria createCriteria(final EntityManager entityManager, final Class entityClass) {\n return createCriteria(entityManager, entityClass, entityClass);\n }", "pre_mask_code": "/*\n * JPAstreamer - Express JPA queries with Java Streams\n *\n *\n * See: http://example.com\n */\npackage com.speedment.jpastreamer.criteria;\n\nimport static java.util.Objects.requireNonNull;\nimport javax.persistence.EntityManager;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Root;\n\n/**\n * @author Mislav Milicevic\n * @since 0.0.9\n */\npublic interface CriteriaFactory {\n\n /**\n * Creates and returns a {@code Criteria} containing the provided {@code builder},\n * {@code query} and {@code root}.\n *\n * @param builder to store in the {@code Criteria}\n * @param query to store in the {@code Criteria}\n * @param root to store in the {@code Criteria}\n * @param root entity\n * @param type returned by the query\n * @return a {@code Criteria} containing the provided {@code builder},\n * {@code query} and {@code root}\n */\n Criteria createCriteria(final CriteriaBuilder builder, final CriteriaQuery query, final Root root);\n\n /**\n * Creates and returns a {@code Criteria} where the {@code CriteriaBuilder},\n * {@code CriteriaQuery} and {@code Root} are created by the provided {@code entityManager}.\n *\n * @param entityManager used to create the necessary {@code Criteria} objects\n * @param entityClass used to define the result model of the stored query and root\n * @param root entity\n * @return a {@code Criteria}\n */\n ", "post_mask_code": "\n\n /**\n * Creates and returns a {@code Criteria} where the {@code CriteriaBuilder},\n * {@code CriteriaQuery} and {@code Root} are created by the provided {@code entityManager}.\n *\n * @param entityManager used to create the necessary {@code Criteria} objects\n * @param entityClass used to define the result model of the root\n * @param returnClass used to define the result model of the query\n * @param root entity\n * @param query return entity\n * @return a {@code Criteria}\n */\n default Criteria createCriteria(final EntityManager entityManager, final Class entityClass, final Class returnClass) {\n requireNonNull(entityManager);\n requireNonNull(entityClass);\n requireNonNull(returnClass);\n final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();\n final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(returnClass);\n final Root root = criteriaQuery.from(entityClass);\n return createCriteria(criteriaBuilder, criteriaQuery, root);\n }\n}\n"} {"task_id": "Java_2336", "language": "Java", "task_type": "method_signature", "source_file": "java/github/uber-common/android-build-eval/mobile_app1/module85/src/main/java/module85packageJava0/Foo44.java", "mask_start_position": 232, "mask_end_position": 251, "canonical_solution": "public void foo2() ", "pre_mask_code": "package module85packageJava0;\n\nimport java.lang.Integer;\n\npublic class Foo44 {\n\n Integer int0;\n\n public void foo0() {\n new module85packageJava0.Foo43().foo4();\n }\n\n public void foo1() {\n foo0();\n }\n\n ", "post_mask_code": "{\n foo1();\n }\n\n public void foo3() {\n foo2();\n }\n\n public void foo4() {\n foo3();\n }\n}\n"} {"task_id": "Java_2337", "language": "Java", "task_type": "method_body", "source_file": "java/github/uber-common/android-build-eval/mobile_app1/module85/src/main/java/module85packageJava0/Foo44.java", "mask_start_position": 203, "mask_end_position": 226, "canonical_solution": "{\n foo0();\n }", "pre_mask_code": "package module85packageJava0;\n\nimport java.lang.Integer;\n\npublic class Foo44 {\n\n Integer int0;\n\n public void foo0() {\n new module85packageJava0.Foo43().foo4();\n }\n\n public void foo1() ", "post_mask_code": "\n\n public void foo2() {\n foo1();\n }\n\n public void foo3() {\n foo2();\n }\n\n public void foo4() {\n foo3();\n }\n}\n"} {"task_id": "Java_2338", "language": "Java", "task_type": "single_line", "source_file": "java/github/uber-common/android-build-eval/mobile_app1/module85/src/main/java/module85packageJava0/Foo44.java", "mask_start_position": 264, "mask_end_position": 268, "canonical_solution": "1();", "pre_mask_code": "package module85packageJava0;\n\nimport java.lang.Integer;\n\npublic class Foo44 {\n\n Integer int0;\n\n public void foo0() {\n new module85packageJava0.Foo43().foo4();\n }\n\n public void foo1() {\n foo0();\n }\n\n public void foo2() {\n foo", "post_mask_code": "\n }\n\n public void foo3() {\n foo2();\n }\n\n public void foo4() {\n foo3();\n }\n}\n"} {"task_id": "Java_2339", "language": "Java", "task_type": "method_signature", "source_file": "java/github/kredel/java-algebra-system/trc/edu/jas/integrate/ElementaryIntegrationLazardTest.java", "mask_start_position": 1493, "mask_end_position": 1530, "canonical_solution": "@Override\n protected void setUp() ", "pre_mask_code": "package edu.jas.integrate;\n\nimport edu.jas.arith.BigRational;\nimport edu.jas.kern.ComputerThreads;\nimport edu.jas.poly.GenPolynomial;\nimport edu.jas.poly.GenPolynomialRing;\nimport edu.jas.poly.PolyUtil;\nimport edu.jas.poly.TermOrder;\nimport edu.jas.ufd.Quotient;\nimport edu.jas.ufd.QuotientRing;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\n\n/**\n * Quotient over BigRational GenPolynomial tests with JUnit. Test Lazard Rioboo\n * algorithm.\n * @author Heinz Kredel\n */\npublic class ElementaryIntegrationLazardTest extends TestCase {\n\n public static void main(String[] args) {\n junit.textui.TestRunner.run(suite());\n }\n\n /**\n * Constructs a ElementaryIntegrationLazardTest object.\n * @param name String.\n */\n public ElementaryIntegrationLazardTest(String name) {\n super(name);\n }\n\n public static Test suite() {\n TestSuite suite = new TestSuite(ElementaryIntegrationLazardTest.class);\n return suite;\n }\n\n TermOrder tord;\n\n QuotientRing qfac;\n\n GenPolynomialRing mfac;\n\n ElementaryIntegration integrator;\n\n QuotIntegral rint;\n\n Quotient a;\n\n Quotient b;\n\n Quotient c;\n\n Quotient d;\n\n Quotient e;\n\n // only univariate polynomials\n int rl = 1;\n\n int kl = 5;\n\n int ll = 3;\n\n int el = 4;\n\n float q = 0.4f;\n\n ", "post_mask_code": "{\n a = b = c = d = e = null;\n tord = new TermOrder(TermOrder.INVLEX);\n BigRational br = new BigRational(1);\n String[] vars = new String[] { \"x\" };\n mfac = new GenPolynomialRing(br, rl, tord, vars);\n qfac = new QuotientRing(mfac);\n integrator = new ElementaryIntegrationLazard(br);\n }\n\n @Override\n protected void tearDown() {\n a = b = c = d = e = null;\n qfac = null;\n ComputerThreads.terminate();\n }\n\n public void testRational() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + 2 * i, el + i, q);\n b = integrator.deriviative(a);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test 1/p pure logarithm integral.\n */\n public void testPureLogarithm1() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = new Quotient(qfac, qfac.getONE().num, a.den);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test p'/p pure logarithm integral.\n */\n public void testPureLogarithmD() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n b = new Quotient(qfac, pp, a.den);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with p'/p logarithm integral.\n */\n public void testRationalWithLogarithmD() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n c = new Quotient(qfac, pp, a.den);\n e = b.sum(c);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with 1/p logarithm integral.\n */\n public void xtestRationalWithLogarithm1() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n d = new Quotient(qfac, qfac.getONE().num, a.den);\n e = b.sum(d);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with p'/p + 1/p logarithm integral.\n */\n public void testRationalWithLogarithm() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n c = new Quotient(qfac, pp, a.den);\n d = new Quotient(qfac, qfac.getONE().num, a.den);\n e = b.sum(c).sum(d);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test rational integral with quotient coefficients.\n */\n public void testRationalRecursive() {\n QuotientRing> qqfac;\n GenPolynomialRing> qmfac;\n ElementaryIntegration> qintegrator;\n QuotIntegral> qrint;\n String[] vars = new String[] { \"y\" };\n qmfac = new GenPolynomialRing>(qfac, 1, tord, vars);\n qqfac = new QuotientRing>(qmfac);\n qintegrator = new ElementaryIntegration>(qfac);\n Quotient> qa, qb;\n for (int i = 0; i < 2; i++) {\n qa = qqfac.random(2, ll, el, q);\n qb = qintegrator.deriviative(qa);\n qrint = qintegrator.integrate(qb);\n assertTrue(\"isIntegral \", qintegrator.isIntegral(qrint));\n }\n }\n\n /**\n * Test mixed rational integral.\n */\n public void testMixedRational() {\n BigRational br = new BigRational(1);\n String[] vars = new String[] { \"x\" };\n GenPolynomialRing pfac = new GenPolynomialRing(br, vars);\n QuotientRing qfac = new QuotientRing(pfac);\n GenPolynomial n = pfac.parse(\"(3*x^16-19*x^15+43*x^14-20*x^13-91*x^12+183*x^11-81*x^10-166*x^9+271*x^8-101*x^7-127*x^6+168*x^5-53*x^4-31*x^3+41*x^2-2*x-2)\");\n GenPolynomial d = pfac.parse(\"(4*x^14-20*x^13+28*x^12+24*x^11-108*x^10+84*x^9+76*x^8-176*x^7+76*x^6+84*x^5-108*x^4+24*x^3+28*x^2-20*x+4)\");\n Quotient a = new Quotient(qfac, n, d);\n QuotIntegral rint = integrator.integrate(a);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n Quotient b = qfac.parse(\"{ 3*x^16-19*x^15+43*x^14-20*x^13-91*x^12+183*x^11-81*x^10-166*x^9+271*x^8-101*x^7-127*x^6+168*x^5-53*x^4-31*x^3+41*x^2-2*x-2 | 4*x^14-20*x^13+28*x^12+24*x^11-108*x^10+84*x^9+76*x^8-176*x^7+76*x^6+84*x^5-108*x^4+24*x^3+28*x^2-20*x+4 }\");\n assertEquals(\"a == b: \", a, b);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n}\n"} {"task_id": "Java_2340", "language": "Java", "task_type": "method_body", "source_file": "java/github/kredel/java-algebra-system/trc/edu/jas/integrate/ElementaryIntegrationLazardTest.java", "mask_start_position": 2082, "mask_end_position": 2348, "canonical_solution": "{\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + 2 * i, el + i, q);\n b = integrator.deriviative(a);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }", "pre_mask_code": "package edu.jas.integrate;\n\nimport edu.jas.arith.BigRational;\nimport edu.jas.kern.ComputerThreads;\nimport edu.jas.poly.GenPolynomial;\nimport edu.jas.poly.GenPolynomialRing;\nimport edu.jas.poly.PolyUtil;\nimport edu.jas.poly.TermOrder;\nimport edu.jas.ufd.Quotient;\nimport edu.jas.ufd.QuotientRing;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\n\n/**\n * Quotient over BigRational GenPolynomial tests with JUnit. Test Lazard Rioboo\n * algorithm.\n * @author Heinz Kredel\n */\npublic class ElementaryIntegrationLazardTest extends TestCase {\n\n public static void main(String[] args) {\n junit.textui.TestRunner.run(suite());\n }\n\n /**\n * Constructs a ElementaryIntegrationLazardTest object.\n * @param name String.\n */\n public ElementaryIntegrationLazardTest(String name) {\n super(name);\n }\n\n public static Test suite() {\n TestSuite suite = new TestSuite(ElementaryIntegrationLazardTest.class);\n return suite;\n }\n\n TermOrder tord;\n\n QuotientRing qfac;\n\n GenPolynomialRing mfac;\n\n ElementaryIntegration integrator;\n\n QuotIntegral rint;\n\n Quotient a;\n\n Quotient b;\n\n Quotient c;\n\n Quotient d;\n\n Quotient e;\n\n // only univariate polynomials\n int rl = 1;\n\n int kl = 5;\n\n int ll = 3;\n\n int el = 4;\n\n float q = 0.4f;\n\n @Override\n protected void setUp() {\n a = b = c = d = e = null;\n tord = new TermOrder(TermOrder.INVLEX);\n BigRational br = new BigRational(1);\n String[] vars = new String[] { \"x\" };\n mfac = new GenPolynomialRing(br, rl, tord, vars);\n qfac = new QuotientRing(mfac);\n integrator = new ElementaryIntegrationLazard(br);\n }\n\n @Override\n protected void tearDown() {\n a = b = c = d = e = null;\n qfac = null;\n ComputerThreads.terminate();\n }\n\n public void testRational() ", "post_mask_code": "\n\n /**\n * Test 1/p pure logarithm integral.\n */\n public void testPureLogarithm1() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = new Quotient(qfac, qfac.getONE().num, a.den);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test p'/p pure logarithm integral.\n */\n public void testPureLogarithmD() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n b = new Quotient(qfac, pp, a.den);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with p'/p logarithm integral.\n */\n public void testRationalWithLogarithmD() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n c = new Quotient(qfac, pp, a.den);\n e = b.sum(c);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with 1/p logarithm integral.\n */\n public void xtestRationalWithLogarithm1() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n d = new Quotient(qfac, qfac.getONE().num, a.den);\n e = b.sum(d);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with p'/p + 1/p logarithm integral.\n */\n public void testRationalWithLogarithm() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n c = new Quotient(qfac, pp, a.den);\n d = new Quotient(qfac, qfac.getONE().num, a.den);\n e = b.sum(c).sum(d);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test rational integral with quotient coefficients.\n */\n public void testRationalRecursive() {\n QuotientRing> qqfac;\n GenPolynomialRing> qmfac;\n ElementaryIntegration> qintegrator;\n QuotIntegral> qrint;\n String[] vars = new String[] { \"y\" };\n qmfac = new GenPolynomialRing>(qfac, 1, tord, vars);\n qqfac = new QuotientRing>(qmfac);\n qintegrator = new ElementaryIntegration>(qfac);\n Quotient> qa, qb;\n for (int i = 0; i < 2; i++) {\n qa = qqfac.random(2, ll, el, q);\n qb = qintegrator.deriviative(qa);\n qrint = qintegrator.integrate(qb);\n assertTrue(\"isIntegral \", qintegrator.isIntegral(qrint));\n }\n }\n\n /**\n * Test mixed rational integral.\n */\n public void testMixedRational() {\n BigRational br = new BigRational(1);\n String[] vars = new String[] { \"x\" };\n GenPolynomialRing pfac = new GenPolynomialRing(br, vars);\n QuotientRing qfac = new QuotientRing(pfac);\n GenPolynomial n = pfac.parse(\"(3*x^16-19*x^15+43*x^14-20*x^13-91*x^12+183*x^11-81*x^10-166*x^9+271*x^8-101*x^7-127*x^6+168*x^5-53*x^4-31*x^3+41*x^2-2*x-2)\");\n GenPolynomial d = pfac.parse(\"(4*x^14-20*x^13+28*x^12+24*x^11-108*x^10+84*x^9+76*x^8-176*x^7+76*x^6+84*x^5-108*x^4+24*x^3+28*x^2-20*x+4)\");\n Quotient a = new Quotient(qfac, n, d);\n QuotIntegral rint = integrator.integrate(a);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n Quotient b = qfac.parse(\"{ 3*x^16-19*x^15+43*x^14-20*x^13-91*x^12+183*x^11-81*x^10-166*x^9+271*x^8-101*x^7-127*x^6+168*x^5-53*x^4-31*x^3+41*x^2-2*x-2 | 4*x^14-20*x^13+28*x^12+24*x^11-108*x^10+84*x^9+76*x^8-176*x^7+76*x^6+84*x^5-108*x^4+24*x^3+28*x^2-20*x+4 }\");\n assertEquals(\"a == b: \", a, b);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n}\n"} {"task_id": "Java_2341", "language": "Java", "task_type": "single_line", "source_file": "java/github/kredel/java-algebra-system/trc/edu/jas/integrate/ElementaryIntegrationLazardTest.java", "mask_start_position": 6606, "mask_end_position": 6644, "canonical_solution": "ional> rint = integrator.integrate(a);", "pre_mask_code": "package edu.jas.integrate;\n\nimport edu.jas.arith.BigRational;\nimport edu.jas.kern.ComputerThreads;\nimport edu.jas.poly.GenPolynomial;\nimport edu.jas.poly.GenPolynomialRing;\nimport edu.jas.poly.PolyUtil;\nimport edu.jas.poly.TermOrder;\nimport edu.jas.ufd.Quotient;\nimport edu.jas.ufd.QuotientRing;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\n\n/**\n * Quotient over BigRational GenPolynomial tests with JUnit. Test Lazard Rioboo\n * algorithm.\n * @author Heinz Kredel\n */\npublic class ElementaryIntegrationLazardTest extends TestCase {\n\n public static void main(String[] args) {\n junit.textui.TestRunner.run(suite());\n }\n\n /**\n * Constructs a ElementaryIntegrationLazardTest object.\n * @param name String.\n */\n public ElementaryIntegrationLazardTest(String name) {\n super(name);\n }\n\n public static Test suite() {\n TestSuite suite = new TestSuite(ElementaryIntegrationLazardTest.class);\n return suite;\n }\n\n TermOrder tord;\n\n QuotientRing qfac;\n\n GenPolynomialRing mfac;\n\n ElementaryIntegration integrator;\n\n QuotIntegral rint;\n\n Quotient a;\n\n Quotient b;\n\n Quotient c;\n\n Quotient d;\n\n Quotient e;\n\n // only univariate polynomials\n int rl = 1;\n\n int kl = 5;\n\n int ll = 3;\n\n int el = 4;\n\n float q = 0.4f;\n\n @Override\n protected void setUp() {\n a = b = c = d = e = null;\n tord = new TermOrder(TermOrder.INVLEX);\n BigRational br = new BigRational(1);\n String[] vars = new String[] { \"x\" };\n mfac = new GenPolynomialRing(br, rl, tord, vars);\n qfac = new QuotientRing(mfac);\n integrator = new ElementaryIntegrationLazard(br);\n }\n\n @Override\n protected void tearDown() {\n a = b = c = d = e = null;\n qfac = null;\n ComputerThreads.terminate();\n }\n\n public void testRational() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + 2 * i, el + i, q);\n b = integrator.deriviative(a);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test 1/p pure logarithm integral.\n */\n public void testPureLogarithm1() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = new Quotient(qfac, qfac.getONE().num, a.den);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test p'/p pure logarithm integral.\n */\n public void testPureLogarithmD() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n b = new Quotient(qfac, pp, a.den);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with p'/p logarithm integral.\n */\n public void testRationalWithLogarithmD() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n c = new Quotient(qfac, pp, a.den);\n e = b.sum(c);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with 1/p logarithm integral.\n */\n public void xtestRationalWithLogarithm1() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n d = new Quotient(qfac, qfac.getONE().num, a.den);\n e = b.sum(d);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with p'/p + 1/p logarithm integral.\n */\n public void testRationalWithLogarithm() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n c = new Quotient(qfac, pp, a.den);\n d = new Quotient(qfac, qfac.getONE().num, a.den);\n e = b.sum(c).sum(d);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test rational integral with quotient coefficients.\n */\n public void testRationalRecursive() {\n QuotientRing> qqfac;\n GenPolynomialRing> qmfac;\n ElementaryIntegration> qintegrator;\n QuotIntegral> qrint;\n String[] vars = new String[] { \"y\" };\n qmfac = new GenPolynomialRing>(qfac, 1, tord, vars);\n qqfac = new QuotientRing>(qmfac);\n qintegrator = new ElementaryIntegration>(qfac);\n Quotient> qa, qb;\n for (int i = 0; i < 2; i++) {\n qa = qqfac.random(2, ll, el, q);\n qb = qintegrator.deriviative(qa);\n qrint = qintegrator.integrate(qb);\n assertTrue(\"isIntegral \", qintegrator.isIntegral(qrint));\n }\n }\n\n /**\n * Test mixed rational integral.\n */\n public void testMixedRational() {\n BigRational br = new BigRational(1);\n String[] vars = new String[] { \"x\" };\n GenPolynomialRing pfac = new GenPolynomialRing(br, vars);\n QuotientRing qfac = new QuotientRing(pfac);\n GenPolynomial n = pfac.parse(\"(3*x^16-19*x^15+43*x^14-20*x^13-91*x^12+183*x^11-81*x^10-166*x^9+271*x^8-101*x^7-127*x^6+168*x^5-53*x^4-31*x^3+41*x^2-2*x-2)\");\n GenPolynomial d = pfac.parse(\"(4*x^14-20*x^13+28*x^12+24*x^11-108*x^10+84*x^9+76*x^8-176*x^7+76*x^6+84*x^5-108*x^4+24*x^3+28*x^2-20*x+4)\");\n Quotient a = new Quotient(qfac, n, d);\n QuotIntegral b = qfac.parse(\"{ 3*x^16-19*x^15+43*x^14-20*x^13-91*x^12+183*x^11-81*x^10-166*x^9+271*x^8-101*x^7-127*x^6+168*x^5-53*x^4-31*x^3+41*x^2-2*x-2 | 4*x^14-20*x^13+28*x^12+24*x^11-108*x^10+84*x^9+76*x^8-176*x^7+76*x^6+84*x^5-108*x^4+24*x^3+28*x^2-20*x+4 }\");\n assertEquals(\"a == b: \", a, b);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n}\n"} {"task_id": "Java_2342", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/kredel/java-algebra-system/trc/edu/jas/integrate/ElementaryIntegrationLazardTest.java", "mask_start_position": 2411, "mask_end_position": 2738, "canonical_solution": "public void testPureLogarithm1() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = new Quotient(qfac, qfac.getONE().num, a.den);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }", "pre_mask_code": "package edu.jas.integrate;\n\nimport edu.jas.arith.BigRational;\nimport edu.jas.kern.ComputerThreads;\nimport edu.jas.poly.GenPolynomial;\nimport edu.jas.poly.GenPolynomialRing;\nimport edu.jas.poly.PolyUtil;\nimport edu.jas.poly.TermOrder;\nimport edu.jas.ufd.Quotient;\nimport edu.jas.ufd.QuotientRing;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\n\n/**\n * Quotient over BigRational GenPolynomial tests with JUnit. Test Lazard Rioboo\n * algorithm.\n * @author Heinz Kredel\n */\npublic class ElementaryIntegrationLazardTest extends TestCase {\n\n public static void main(String[] args) {\n junit.textui.TestRunner.run(suite());\n }\n\n /**\n * Constructs a ElementaryIntegrationLazardTest object.\n * @param name String.\n */\n public ElementaryIntegrationLazardTest(String name) {\n super(name);\n }\n\n public static Test suite() {\n TestSuite suite = new TestSuite(ElementaryIntegrationLazardTest.class);\n return suite;\n }\n\n TermOrder tord;\n\n QuotientRing qfac;\n\n GenPolynomialRing mfac;\n\n ElementaryIntegration integrator;\n\n QuotIntegral rint;\n\n Quotient a;\n\n Quotient b;\n\n Quotient c;\n\n Quotient d;\n\n Quotient e;\n\n // only univariate polynomials\n int rl = 1;\n\n int kl = 5;\n\n int ll = 3;\n\n int el = 4;\n\n float q = 0.4f;\n\n @Override\n protected void setUp() {\n a = b = c = d = e = null;\n tord = new TermOrder(TermOrder.INVLEX);\n BigRational br = new BigRational(1);\n String[] vars = new String[] { \"x\" };\n mfac = new GenPolynomialRing(br, rl, tord, vars);\n qfac = new QuotientRing(mfac);\n integrator = new ElementaryIntegrationLazard(br);\n }\n\n @Override\n protected void tearDown() {\n a = b = c = d = e = null;\n qfac = null;\n ComputerThreads.terminate();\n }\n\n public void testRational() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + 2 * i, el + i, q);\n b = integrator.deriviative(a);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test 1/p pure logarithm integral.\n */\n ", "post_mask_code": "\n\n /**\n * Test p'/p pure logarithm integral.\n */\n public void testPureLogarithmD() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n b = new Quotient(qfac, pp, a.den);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with p'/p logarithm integral.\n */\n public void testRationalWithLogarithmD() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n c = new Quotient(qfac, pp, a.den);\n e = b.sum(c);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with 1/p logarithm integral.\n */\n public void xtestRationalWithLogarithm1() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n d = new Quotient(qfac, qfac.getONE().num, a.den);\n e = b.sum(d);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with p'/p + 1/p logarithm integral.\n */\n public void testRationalWithLogarithm() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n c = new Quotient(qfac, pp, a.den);\n d = new Quotient(qfac, qfac.getONE().num, a.den);\n e = b.sum(c).sum(d);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test rational integral with quotient coefficients.\n */\n public void testRationalRecursive() {\n QuotientRing> qqfac;\n GenPolynomialRing> qmfac;\n ElementaryIntegration> qintegrator;\n QuotIntegral> qrint;\n String[] vars = new String[] { \"y\" };\n qmfac = new GenPolynomialRing>(qfac, 1, tord, vars);\n qqfac = new QuotientRing>(qmfac);\n qintegrator = new ElementaryIntegration>(qfac);\n Quotient> qa, qb;\n for (int i = 0; i < 2; i++) {\n qa = qqfac.random(2, ll, el, q);\n qb = qintegrator.deriviative(qa);\n qrint = qintegrator.integrate(qb);\n assertTrue(\"isIntegral \", qintegrator.isIntegral(qrint));\n }\n }\n\n /**\n * Test mixed rational integral.\n */\n public void testMixedRational() {\n BigRational br = new BigRational(1);\n String[] vars = new String[] { \"x\" };\n GenPolynomialRing pfac = new GenPolynomialRing(br, vars);\n QuotientRing qfac = new QuotientRing(pfac);\n GenPolynomial n = pfac.parse(\"(3*x^16-19*x^15+43*x^14-20*x^13-91*x^12+183*x^11-81*x^10-166*x^9+271*x^8-101*x^7-127*x^6+168*x^5-53*x^4-31*x^3+41*x^2-2*x-2)\");\n GenPolynomial d = pfac.parse(\"(4*x^14-20*x^13+28*x^12+24*x^11-108*x^10+84*x^9+76*x^8-176*x^7+76*x^6+84*x^5-108*x^4+24*x^3+28*x^2-20*x+4)\");\n Quotient a = new Quotient(qfac, n, d);\n QuotIntegral rint = integrator.integrate(a);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n Quotient b = qfac.parse(\"{ 3*x^16-19*x^15+43*x^14-20*x^13-91*x^12+183*x^11-81*x^10-166*x^9+271*x^8-101*x^7-127*x^6+168*x^5-53*x^4-31*x^3+41*x^2-2*x-2 | 4*x^14-20*x^13+28*x^12+24*x^11-108*x^10+84*x^9+76*x^8-176*x^7+76*x^6+84*x^5-108*x^4+24*x^3+28*x^2-20*x+4 }\");\n assertEquals(\"a == b: \", a, b);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n}\n"} {"task_id": "Java_2343", "language": "Java", "task_type": "for_statement", "source_file": "java/github/kredel/java-algebra-system/trc/edu/jas/integrate/ElementaryIntegrationLazardTest.java", "mask_start_position": 2454, "mask_end_position": 2732, "canonical_solution": "for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = new Quotient(qfac, qfac.getONE().num, a.den);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }", "pre_mask_code": "package edu.jas.integrate;\n\nimport edu.jas.arith.BigRational;\nimport edu.jas.kern.ComputerThreads;\nimport edu.jas.poly.GenPolynomial;\nimport edu.jas.poly.GenPolynomialRing;\nimport edu.jas.poly.PolyUtil;\nimport edu.jas.poly.TermOrder;\nimport edu.jas.ufd.Quotient;\nimport edu.jas.ufd.QuotientRing;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\n\n/**\n * Quotient over BigRational GenPolynomial tests with JUnit. Test Lazard Rioboo\n * algorithm.\n * @author Heinz Kredel\n */\npublic class ElementaryIntegrationLazardTest extends TestCase {\n\n public static void main(String[] args) {\n junit.textui.TestRunner.run(suite());\n }\n\n /**\n * Constructs a ElementaryIntegrationLazardTest object.\n * @param name String.\n */\n public ElementaryIntegrationLazardTest(String name) {\n super(name);\n }\n\n public static Test suite() {\n TestSuite suite = new TestSuite(ElementaryIntegrationLazardTest.class);\n return suite;\n }\n\n TermOrder tord;\n\n QuotientRing qfac;\n\n GenPolynomialRing mfac;\n\n ElementaryIntegration integrator;\n\n QuotIntegral rint;\n\n Quotient a;\n\n Quotient b;\n\n Quotient c;\n\n Quotient d;\n\n Quotient e;\n\n // only univariate polynomials\n int rl = 1;\n\n int kl = 5;\n\n int ll = 3;\n\n int el = 4;\n\n float q = 0.4f;\n\n @Override\n protected void setUp() {\n a = b = c = d = e = null;\n tord = new TermOrder(TermOrder.INVLEX);\n BigRational br = new BigRational(1);\n String[] vars = new String[] { \"x\" };\n mfac = new GenPolynomialRing(br, rl, tord, vars);\n qfac = new QuotientRing(mfac);\n integrator = new ElementaryIntegrationLazard(br);\n }\n\n @Override\n protected void tearDown() {\n a = b = c = d = e = null;\n qfac = null;\n ComputerThreads.terminate();\n }\n\n public void testRational() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + 2 * i, el + i, q);\n b = integrator.deriviative(a);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test 1/p pure logarithm integral.\n */\n public void testPureLogarithm1() {\n ", "post_mask_code": "\n }\n\n /**\n * Test p'/p pure logarithm integral.\n */\n public void testPureLogarithmD() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n b = new Quotient(qfac, pp, a.den);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with p'/p logarithm integral.\n */\n public void testRationalWithLogarithmD() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n c = new Quotient(qfac, pp, a.den);\n e = b.sum(c);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with 1/p logarithm integral.\n */\n public void xtestRationalWithLogarithm1() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n d = new Quotient(qfac, qfac.getONE().num, a.den);\n e = b.sum(d);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test mixed rational with p'/p + 1/p logarithm integral.\n */\n public void testRationalWithLogarithm() {\n for (int i = 0; i < 3; i++) {\n a = qfac.random(kl, ll + i, el + i, q);\n b = integrator.deriviative(a);\n GenPolynomial pp = PolyUtil.baseDeriviative(a.den);\n c = new Quotient(qfac, pp, a.den);\n d = new Quotient(qfac, qfac.getONE().num, a.den);\n e = b.sum(c).sum(d);\n rint = integrator.integrate(e);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n }\n\n /**\n * Test rational integral with quotient coefficients.\n */\n public void testRationalRecursive() {\n QuotientRing> qqfac;\n GenPolynomialRing> qmfac;\n ElementaryIntegration> qintegrator;\n QuotIntegral> qrint;\n String[] vars = new String[] { \"y\" };\n qmfac = new GenPolynomialRing>(qfac, 1, tord, vars);\n qqfac = new QuotientRing>(qmfac);\n qintegrator = new ElementaryIntegration>(qfac);\n Quotient> qa, qb;\n for (int i = 0; i < 2; i++) {\n qa = qqfac.random(2, ll, el, q);\n qb = qintegrator.deriviative(qa);\n qrint = qintegrator.integrate(qb);\n assertTrue(\"isIntegral \", qintegrator.isIntegral(qrint));\n }\n }\n\n /**\n * Test mixed rational integral.\n */\n public void testMixedRational() {\n BigRational br = new BigRational(1);\n String[] vars = new String[] { \"x\" };\n GenPolynomialRing pfac = new GenPolynomialRing(br, vars);\n QuotientRing qfac = new QuotientRing(pfac);\n GenPolynomial n = pfac.parse(\"(3*x^16-19*x^15+43*x^14-20*x^13-91*x^12+183*x^11-81*x^10-166*x^9+271*x^8-101*x^7-127*x^6+168*x^5-53*x^4-31*x^3+41*x^2-2*x-2)\");\n GenPolynomial d = pfac.parse(\"(4*x^14-20*x^13+28*x^12+24*x^11-108*x^10+84*x^9+76*x^8-176*x^7+76*x^6+84*x^5-108*x^4+24*x^3+28*x^2-20*x+4)\");\n Quotient a = new Quotient(qfac, n, d);\n QuotIntegral rint = integrator.integrate(a);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n Quotient b = qfac.parse(\"{ 3*x^16-19*x^15+43*x^14-20*x^13-91*x^12+183*x^11-81*x^10-166*x^9+271*x^8-101*x^7-127*x^6+168*x^5-53*x^4-31*x^3+41*x^2-2*x-2 | 4*x^14-20*x^13+28*x^12+24*x^11-108*x^10+84*x^9+76*x^8-176*x^7+76*x^6+84*x^5-108*x^4+24*x^3+28*x^2-20*x+4 }\");\n assertEquals(\"a == b: \", a, b);\n rint = integrator.integrate(b);\n assertTrue(\"isIntegral \", integrator.isIntegral(rint));\n }\n}\n"} {"task_id": "Java_2344", "language": "Java", "task_type": "method_signature", "source_file": "java/github/algorithm006-class02/algorithm006-class02/Week_03/G20200343030514/Leetcode_54_514.java", "mask_start_position": 36, "mask_end_position": 64, "canonical_solution": "public int jump(int[] nums) ", "pre_mask_code": "class Solution {\n\n // greedy\n ", "post_mask_code": "{\n if (nums == null || nums.length == 0) {\n return 0;\n }\n int count = 0;\n int end = 0;\n int maxPosition = 0;\n for (int i = 0; i < nums.length - 1; i++) {\n if (nums[i] + i > maxPosition) {\n maxPosition = nums[i] + i;\n }\n if (i == end) {\n end = maxPosition;\n count++;\n }\n }\n return count;\n }\n}\n"} {"task_id": "Java_2345", "language": "Java", "task_type": "method_body", "source_file": "java/github/algorithm006-class02/algorithm006-class02/Week_03/G20200343030514/Leetcode_54_514.java", "mask_start_position": 64, "mask_end_position": 512, "canonical_solution": "{\n if (nums == null || nums.length == 0) {\n return 0;\n }\n int count = 0;\n int end = 0;\n int maxPosition = 0;\n for (int i = 0; i < nums.length - 1; i++) {\n if (nums[i] + i > maxPosition) {\n maxPosition = nums[i] + i;\n }\n if (i == end) {\n end = maxPosition;\n count++;\n }\n }\n return count;\n }", "pre_mask_code": "class Solution {\n\n // greedy\n public int jump(int[] nums) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2346", "language": "Java", "task_type": "single_line", "source_file": "java/github/algorithm006-class02/algorithm006-class02/Week_03/G20200343030514/Leetcode_54_514.java", "mask_start_position": 186, "mask_end_position": 189, "canonical_solution": " 0;", "pre_mask_code": "class Solution {\n\n // greedy\n public int jump(int[] nums) {\n if (nums == null || nums.length == 0) {\n return 0;\n }\n int count = 0;\n int end =", "post_mask_code": "\n int maxPosition = 0;\n for (int i = 0; i < nums.length - 1; i++) {\n if (nums[i] + i > maxPosition) {\n maxPosition = nums[i] + i;\n }\n if (i == end) {\n end = maxPosition;\n count++;\n }\n }\n return count;\n }\n}\n"} {"task_id": "Java_2347", "language": "Java", "task_type": "for_statement", "source_file": "java/github/algorithm006-class02/algorithm006-class02/Week_03/G20200343030514/Leetcode_54_514.java", "mask_start_position": 227, "mask_end_position": 484, "canonical_solution": "for (int i = 0; i < nums.length - 1; i++) {\n if (nums[i] + i > maxPosition) {\n maxPosition = nums[i] + i;\n }\n if (i == end) {\n end = maxPosition;\n count++;\n }\n }", "pre_mask_code": "class Solution {\n\n // greedy\n public int jump(int[] nums) {\n if (nums == null || nums.length == 0) {\n return 0;\n }\n int count = 0;\n int end = 0;\n int maxPosition = 0;\n ", "post_mask_code": "\n return count;\n }\n}\n"} {"task_id": "Java_2348", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/ontop/ontop/engine/reformulation/core/src/main/java/it/unibz/inf/ontop/injection/OntopReformulationConfiguration.java", "mask_start_position": 559, "mask_end_position": 635, "canonical_solution": "QueryReformulator loadQueryReformulator() throws OBDASpecificationException;", "pre_mask_code": "package it.unibz.inf.ontop.injection;\n\nimport it.unibz.inf.ontop.answering.reformulation.QueryReformulator;\nimport it.unibz.inf.ontop.answering.reformulation.input.InputQueryFactory;\nimport it.unibz.inf.ontop.exception.OBDASpecificationException;\n\npublic interface OntopReformulationConfiguration extends OntopOBDAConfiguration, OntopOptimizationConfiguration {\n\n @Override\n OntopReformulationSettings getSettings();\n\n /**\n * To call ONLY when interested by query REFORMULATION, not FULL query ANSWERING\n * (no query evaluation).\n */\n ", "post_mask_code": "\n\n InputQueryFactory getInputQueryFactory();\n\n interface OntopReformulationBuilderFragment> {\n\n B enableExistentialReasoning(boolean enable);\n }\n\n interface Builder> extends OntopReformulationBuilderFragment, OntopOBDAConfiguration.Builder, OntopOptimizationConfiguration.Builder {\n\n @Override\n OntopReformulationConfiguration build();\n }\n}\n"} {"task_id": "Java_2349", "language": "Java", "task_type": "method_signature", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/live/v20180801/models/DescribeScreenShotSheetNumListRequest.java", "mask_start_position": 1193, "mask_end_position": 1222, "canonical_solution": "public String getStartTime() ", "pre_mask_code": "package com.tencentcloudapi.live.v20180801.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class DescribeScreenShotSheetNumListRequest extends AbstractModel {\n\n /**\n * utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n @SerializedName(\"StartTime\")\n @Expose\n private String StartTime;\n\n /**\n * utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n @SerializedName(\"EndTime\")\n @Expose\n private String EndTime;\n\n /**\n * 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n @SerializedName(\"Zone\")\n @Expose\n private String Zone;\n\n /**\n * 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n @SerializedName(\"PushDomains\")\n @Expose\n private String[] PushDomains;\n\n /**\n * 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n @SerializedName(\"Granularity\")\n @Expose\n private String Granularity;\n\n /**\n * Get utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n * @return StartTime utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n ", "post_mask_code": "{\n return this.StartTime;\n }\n\n /**\n * Set utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n * @param StartTime utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n public void setStartTime(String StartTime) {\n this.StartTime = StartTime;\n }\n\n /**\n * Get utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n * @return EndTime utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n public String getEndTime() {\n return this.EndTime;\n }\n\n /**\n * Set utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n * @param EndTime utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n public void setEndTime(String EndTime) {\n this.EndTime = EndTime;\n }\n\n /**\n * Get 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n * @return Zone 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n public String getZone() {\n return this.Zone;\n }\n\n /**\n * Set 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n * @param Zone 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n public void setZone(String Zone) {\n this.Zone = Zone;\n }\n\n /**\n * Get 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n * @return PushDomains 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n public String[] getPushDomains() {\n return this.PushDomains;\n }\n\n /**\n * Set 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n * @param PushDomains 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n public void setPushDomains(String[] PushDomains) {\n this.PushDomains = PushDomains;\n }\n\n /**\n * Get 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n * @return Granularity 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n public String getGranularity() {\n return this.Granularity;\n }\n\n /**\n * Set 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n * @param Granularity 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n public void setGranularity(String Granularity) {\n this.Granularity = Granularity;\n }\n\n public DescribeScreenShotSheetNumListRequest() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public DescribeScreenShotSheetNumListRequest(DescribeScreenShotSheetNumListRequest source) {\n if (source.StartTime != null) {\n this.StartTime = new String(source.StartTime);\n }\n if (source.EndTime != null) {\n this.EndTime = new String(source.EndTime);\n }\n if (source.Zone != null) {\n this.Zone = new String(source.Zone);\n }\n if (source.PushDomains != null) {\n this.PushDomains = new String[source.PushDomains.length];\n for (int i = 0; i < source.PushDomains.length; i++) {\n this.PushDomains[i] = new String(source.PushDomains[i]);\n }\n }\n if (source.Granularity != null) {\n this.Granularity = new String(source.Granularity);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) {\n this.setParamSimple(map, prefix + \"StartTime\", this.StartTime);\n this.setParamSimple(map, prefix + \"EndTime\", this.EndTime);\n this.setParamSimple(map, prefix + \"Zone\", this.Zone);\n this.setParamArraySimple(map, prefix + \"PushDomains.\", this.PushDomains);\n this.setParamSimple(map, prefix + \"Granularity\", this.Granularity);\n }\n}\n"} {"task_id": "Java_2350", "language": "Java", "task_type": "method_body", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/live/v20180801/models/DescribeScreenShotSheetNumListRequest.java", "mask_start_position": 2128, "mask_end_position": 2161, "canonical_solution": "{\n return this.Zone;\n }", "pre_mask_code": "package com.tencentcloudapi.live.v20180801.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class DescribeScreenShotSheetNumListRequest extends AbstractModel {\n\n /**\n * utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n @SerializedName(\"StartTime\")\n @Expose\n private String StartTime;\n\n /**\n * utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n @SerializedName(\"EndTime\")\n @Expose\n private String EndTime;\n\n /**\n * 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n @SerializedName(\"Zone\")\n @Expose\n private String Zone;\n\n /**\n * 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n @SerializedName(\"PushDomains\")\n @Expose\n private String[] PushDomains;\n\n /**\n * 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n @SerializedName(\"Granularity\")\n @Expose\n private String Granularity;\n\n /**\n * Get utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n * @return StartTime utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n public String getStartTime() {\n return this.StartTime;\n }\n\n /**\n * Set utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n * @param StartTime utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n public void setStartTime(String StartTime) {\n this.StartTime = StartTime;\n }\n\n /**\n * Get utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n * @return EndTime utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n public String getEndTime() {\n return this.EndTime;\n }\n\n /**\n * Set utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n * @param EndTime utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n public void setEndTime(String EndTime) {\n this.EndTime = EndTime;\n }\n\n /**\n * Get 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n * @return Zone 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n public String getZone() ", "post_mask_code": "\n\n /**\n * Set 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n * @param Zone 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n public void setZone(String Zone) {\n this.Zone = Zone;\n }\n\n /**\n * Get 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n * @return PushDomains 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n public String[] getPushDomains() {\n return this.PushDomains;\n }\n\n /**\n * Set 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n * @param PushDomains 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n public void setPushDomains(String[] PushDomains) {\n this.PushDomains = PushDomains;\n }\n\n /**\n * Get 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n * @return Granularity 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n public String getGranularity() {\n return this.Granularity;\n }\n\n /**\n * Set 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n * @param Granularity 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n public void setGranularity(String Granularity) {\n this.Granularity = Granularity;\n }\n\n public DescribeScreenShotSheetNumListRequest() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public DescribeScreenShotSheetNumListRequest(DescribeScreenShotSheetNumListRequest source) {\n if (source.StartTime != null) {\n this.StartTime = new String(source.StartTime);\n }\n if (source.EndTime != null) {\n this.EndTime = new String(source.EndTime);\n }\n if (source.Zone != null) {\n this.Zone = new String(source.Zone);\n }\n if (source.PushDomains != null) {\n this.PushDomains = new String[source.PushDomains.length];\n for (int i = 0; i < source.PushDomains.length; i++) {\n this.PushDomains[i] = new String(source.PushDomains[i]);\n }\n }\n if (source.Granularity != null) {\n this.Granularity = new String(source.Granularity);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) {\n this.setParamSimple(map, prefix + \"StartTime\", this.StartTime);\n this.setParamSimple(map, prefix + \"EndTime\", this.EndTime);\n this.setParamSimple(map, prefix + \"Zone\", this.Zone);\n this.setParamArraySimple(map, prefix + \"PushDomains.\", this.PushDomains);\n this.setParamSimple(map, prefix + \"Granularity\", this.Granularity);\n }\n}\n"} {"task_id": "Java_2351", "language": "Java", "task_type": "single_line", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/live/v20180801/models/DescribeScreenShotSheetNumListRequest.java", "mask_start_position": 1451, "mask_end_position": 1461, "canonical_solution": "StartTime;", "pre_mask_code": "package com.tencentcloudapi.live.v20180801.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class DescribeScreenShotSheetNumListRequest extends AbstractModel {\n\n /**\n * utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n @SerializedName(\"StartTime\")\n @Expose\n private String StartTime;\n\n /**\n * utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n @SerializedName(\"EndTime\")\n @Expose\n private String EndTime;\n\n /**\n * 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n @SerializedName(\"Zone\")\n @Expose\n private String Zone;\n\n /**\n * 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n @SerializedName(\"PushDomains\")\n @Expose\n private String[] PushDomains;\n\n /**\n * 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n @SerializedName(\"Granularity\")\n @Expose\n private String Granularity;\n\n /**\n * Get utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n * @return StartTime utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n public String getStartTime() {\n return this.StartTime;\n }\n\n /**\n * Set utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n * @param StartTime utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n public void setStartTime(String StartTime) {\n this.StartTime = ", "post_mask_code": "\n }\n\n /**\n * Get utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n * @return EndTime utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n public String getEndTime() {\n return this.EndTime;\n }\n\n /**\n * Set utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n * @param EndTime utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n public void setEndTime(String EndTime) {\n this.EndTime = EndTime;\n }\n\n /**\n * Get 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n * @return Zone 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n public String getZone() {\n return this.Zone;\n }\n\n /**\n * Set 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n * @param Zone 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n public void setZone(String Zone) {\n this.Zone = Zone;\n }\n\n /**\n * Get 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n * @return PushDomains 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n public String[] getPushDomains() {\n return this.PushDomains;\n }\n\n /**\n * Set 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n * @param PushDomains 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n public void setPushDomains(String[] PushDomains) {\n this.PushDomains = PushDomains;\n }\n\n /**\n * Get 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n * @return Granularity 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n public String getGranularity() {\n return this.Granularity;\n }\n\n /**\n * Set 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n * @param Granularity 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n public void setGranularity(String Granularity) {\n this.Granularity = Granularity;\n }\n\n public DescribeScreenShotSheetNumListRequest() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public DescribeScreenShotSheetNumListRequest(DescribeScreenShotSheetNumListRequest source) {\n if (source.StartTime != null) {\n this.StartTime = new String(source.StartTime);\n }\n if (source.EndTime != null) {\n this.EndTime = new String(source.EndTime);\n }\n if (source.Zone != null) {\n this.Zone = new String(source.Zone);\n }\n if (source.PushDomains != null) {\n this.PushDomains = new String[source.PushDomains.length];\n for (int i = 0; i < source.PushDomains.length; i++) {\n this.PushDomains[i] = new String(source.PushDomains[i]);\n }\n }\n if (source.Granularity != null) {\n this.Granularity = new String(source.Granularity);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) {\n this.setParamSimple(map, prefix + \"StartTime\", this.StartTime);\n this.setParamSimple(map, prefix + \"EndTime\", this.EndTime);\n this.setParamSimple(map, prefix + \"Zone\", this.Zone);\n this.setParamArraySimple(map, prefix + \"PushDomains.\", this.PushDomains);\n this.setParamSimple(map, prefix + \"Granularity\", this.Granularity);\n }\n}\n"} {"task_id": "Java_2352", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/live/v20180801/models/DescribeScreenShotSheetNumListRequest.java", "mask_start_position": 1381, "mask_end_position": 1467, "canonical_solution": "public void setStartTime(String StartTime) {\n this.StartTime = StartTime;\n }", "pre_mask_code": "package com.tencentcloudapi.live.v20180801.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class DescribeScreenShotSheetNumListRequest extends AbstractModel {\n\n /**\n * utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n @SerializedName(\"StartTime\")\n @Expose\n private String StartTime;\n\n /**\n * utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n @SerializedName(\"EndTime\")\n @Expose\n private String EndTime;\n\n /**\n * 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n @SerializedName(\"Zone\")\n @Expose\n private String Zone;\n\n /**\n * 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n @SerializedName(\"PushDomains\")\n @Expose\n private String[] PushDomains;\n\n /**\n * 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n @SerializedName(\"Granularity\")\n @Expose\n private String Granularity;\n\n /**\n * Get utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n * @return StartTime utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n public String getStartTime() {\n return this.StartTime;\n }\n\n /**\n * Set utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n * @param StartTime utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n ", "post_mask_code": "\n\n /**\n * Get utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n * @return EndTime utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n public String getEndTime() {\n return this.EndTime;\n }\n\n /**\n * Set utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n * @param EndTime utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n public void setEndTime(String EndTime) {\n this.EndTime = EndTime;\n }\n\n /**\n * Get 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n * @return Zone 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n public String getZone() {\n return this.Zone;\n }\n\n /**\n * Set 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n * @param Zone 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n public void setZone(String Zone) {\n this.Zone = Zone;\n }\n\n /**\n * Get 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n * @return PushDomains 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n public String[] getPushDomains() {\n return this.PushDomains;\n }\n\n /**\n * Set 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n * @param PushDomains 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n public void setPushDomains(String[] PushDomains) {\n this.PushDomains = PushDomains;\n }\n\n /**\n * Get 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n * @return Granularity 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n public String getGranularity() {\n return this.Granularity;\n }\n\n /**\n * Set 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n * @param Granularity 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n public void setGranularity(String Granularity) {\n this.Granularity = Granularity;\n }\n\n public DescribeScreenShotSheetNumListRequest() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public DescribeScreenShotSheetNumListRequest(DescribeScreenShotSheetNumListRequest source) {\n if (source.StartTime != null) {\n this.StartTime = new String(source.StartTime);\n }\n if (source.EndTime != null) {\n this.EndTime = new String(source.EndTime);\n }\n if (source.Zone != null) {\n this.Zone = new String(source.Zone);\n }\n if (source.PushDomains != null) {\n this.PushDomains = new String[source.PushDomains.length];\n for (int i = 0; i < source.PushDomains.length; i++) {\n this.PushDomains[i] = new String(source.PushDomains[i]);\n }\n }\n if (source.Granularity != null) {\n this.Granularity = new String(source.Granularity);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) {\n this.setParamSimple(map, prefix + \"StartTime\", this.StartTime);\n this.setParamSimple(map, prefix + \"EndTime\", this.EndTime);\n this.setParamSimple(map, prefix + \"Zone\", this.Zone);\n this.setParamArraySimple(map, prefix + \"PushDomains.\", this.PushDomains);\n this.setParamSimple(map, prefix + \"Granularity\", this.Granularity);\n }\n}\n"} {"task_id": "Java_2353", "language": "Java", "task_type": "for_statement", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/live/v20180801/models/DescribeScreenShotSheetNumListRequest.java", "mask_start_position": 4309, "mask_end_position": 4449, "canonical_solution": "for (int i = 0; i < source.PushDomains.length; i++) {\n this.PushDomains[i] = new String(source.PushDomains[i]);\n }", "pre_mask_code": "package com.tencentcloudapi.live.v20180801.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class DescribeScreenShotSheetNumListRequest extends AbstractModel {\n\n /**\n * utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n @SerializedName(\"StartTime\")\n @Expose\n private String StartTime;\n\n /**\n * utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n @SerializedName(\"EndTime\")\n @Expose\n private String EndTime;\n\n /**\n * 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n @SerializedName(\"Zone\")\n @Expose\n private String Zone;\n\n /**\n * 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n @SerializedName(\"PushDomains\")\n @Expose\n private String[] PushDomains;\n\n /**\n * 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n @SerializedName(\"Granularity\")\n @Expose\n private String Granularity;\n\n /**\n * Get utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n * @return StartTime utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n public String getStartTime() {\n return this.StartTime;\n }\n\n /**\n * Set utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n * @param StartTime utc起始时间,格式为yyyy-mm-ddTHH:MM:SSZ\n */\n public void setStartTime(String StartTime) {\n this.StartTime = StartTime;\n }\n\n /**\n * Get utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n * @return EndTime utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n public String getEndTime() {\n return this.EndTime;\n }\n\n /**\n * Set utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n * @param EndTime utc结束时间,格式为yyyy-mm-ddTHH:MM:SSZ,支持查询最近1年数据。\n */\n public void setEndTime(String EndTime) {\n this.EndTime = EndTime;\n }\n\n /**\n * Get 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n * @return Zone 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n public String getZone() {\n return this.Zone;\n }\n\n /**\n * Set 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n * @param Zone 地域信息,可选值包括Mainland,Oversea,前者是查询中国大陆范围内的数据,后者是除中国大陆范围之外的数据,若不传该参数,则查询所有地区的数据。\n */\n public void setZone(String Zone) {\n this.Zone = Zone;\n }\n\n /**\n * Get 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n * @return PushDomains 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n public String[] getPushDomains() {\n return this.PushDomains;\n }\n\n /**\n * Set 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n * @param PushDomains 推流域名(支持查询2019年11 月1日之后的域名维度数据)。\n */\n public void setPushDomains(String[] PushDomains) {\n this.PushDomains = PushDomains;\n }\n\n /**\n * Get 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n * @return Granularity 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n public String getGranularity() {\n return this.Granularity;\n }\n\n /**\n * Set 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n * @param Granularity 数据维度,数据延迟1个半小时,可选值包括:1、Minute(5分钟粒度,最大支持查询时间范围是31天),2、Day(天粒度,默认值,按照北京时间做跨天处理,最大支持查询时间范围是186天当天)。\n */\n public void setGranularity(String Granularity) {\n this.Granularity = Granularity;\n }\n\n public DescribeScreenShotSheetNumListRequest() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public DescribeScreenShotSheetNumListRequest(DescribeScreenShotSheetNumListRequest source) {\n if (source.StartTime != null) {\n this.StartTime = new String(source.StartTime);\n }\n if (source.EndTime != null) {\n this.EndTime = new String(source.EndTime);\n }\n if (source.Zone != null) {\n this.Zone = new String(source.Zone);\n }\n if (source.PushDomains != null) {\n this.PushDomains = new String[source.PushDomains.length];\n ", "post_mask_code": "\n }\n if (source.Granularity != null) {\n this.Granularity = new String(source.Granularity);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) {\n this.setParamSimple(map, prefix + \"StartTime\", this.StartTime);\n this.setParamSimple(map, prefix + \"EndTime\", this.EndTime);\n this.setParamSimple(map, prefix + \"Zone\", this.Zone);\n this.setParamArraySimple(map, prefix + \"PushDomains.\", this.PushDomains);\n this.setParamSimple(map, prefix + \"Granularity\", this.Granularity);\n }\n}\n"} {"task_id": "Java_2354", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/2006-Scape/2006Scape/2006Scape Server/src/main/java/com/rs2/event/EventContext.java", "mask_start_position": 220, "mask_end_position": 248, "canonical_solution": "void breakSubscriberChain();", "pre_mask_code": "package com.rs2.event;\n\n/**\n * Represents the context of an {@link Event}\n *\n * @author Ryley Kimmel \n */\npublic interface EventContext {\n\n /**\n * Breaks the chain of subscribers.\n */\n ", "post_mask_code": "\n\n /**\n * Repairs the chain of subscribers.\n */\n void repairSubscriberChain();\n\n /**\n * Checks whether or not the subscriber chain is broken.\n *\n * @return {@code true} if and only if the chain is broken, otherwise\n * {@code false}.\n */\n boolean isChainBroken();\n}\n"} {"task_id": "Java_2355", "language": "Java", "task_type": "method_signature", "source_file": "java/github/zhisheng17/flink-learning/flink-learning-examples/src/main/java/com/zhisheng/examples/streaming/restartStrategy/AEMain.java", "mask_start_position": 970, "mask_end_position": 1060, "canonical_solution": "@Override\n public void run(SourceContext sourceContext) throws Exception ", "pre_mask_code": "package com.zhisheng.examples.streaming.restartStrategy;\n\nimport org.apache.flink.api.common.functions.MapFunction;\nimport org.apache.flink.api.common.restartstrategy.RestartStrategies;\nimport org.apache.flink.api.java.utils.ParameterTool;\nimport org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;\nimport org.apache.flink.streaming.api.functions.source.SourceFunction;\n\n/**\n * Desc: 测试重启代码出现异常,导致触发重启策略\n * Created by zhisheng on 2019-04-19\n * blog:http://example.com\n * 微信公众号:zhisheng\n */\npublic class AEMain {\n\n public static void main(String[] args) throws Exception {\n // 创建流运行环境\n StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();\n env.getConfig().setGlobalJobParameters(ParameterTool.fromArgs(args));\n // 每隔 5s 重启一次,尝试三次如果 Job 还没有起来则停止\n env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 5000));\n env.addSource(new SourceFunction() {\n\n ", "post_mask_code": "{\n while (true) {\n sourceContext.collect(System.currentTimeMillis());\n }\n }\n\n @Override\n public void cancel() {\n }\n }).map((MapFunction) aLong -> aLong / 0).print();\n env.execute(\"zhisheng RestartStrategy example\");\n }\n}\n"} {"task_id": "Java_2356", "language": "Java", "task_type": "method_body", "source_file": "java/github/zhisheng17/flink-learning/flink-learning-examples/src/main/java/com/zhisheng/examples/streaming/restartStrategy/AEMain.java", "mask_start_position": 1060, "mask_end_position": 1195, "canonical_solution": "{\n while (true) {\n sourceContext.collect(System.currentTimeMillis());\n }\n }", "pre_mask_code": "package com.zhisheng.examples.streaming.restartStrategy;\n\nimport org.apache.flink.api.common.functions.MapFunction;\nimport org.apache.flink.api.common.restartstrategy.RestartStrategies;\nimport org.apache.flink.api.java.utils.ParameterTool;\nimport org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;\nimport org.apache.flink.streaming.api.functions.source.SourceFunction;\n\n/**\n * Desc: 测试重启代码出现异常,导致触发重启策略\n * Created by zhisheng on 2019-04-19\n * blog:http://example.com\n * 微信公众号:zhisheng\n */\npublic class AEMain {\n\n public static void main(String[] args) throws Exception {\n // 创建流运行环境\n StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();\n env.getConfig().setGlobalJobParameters(ParameterTool.fromArgs(args));\n // 每隔 5s 重启一次,尝试三次如果 Job 还没有起来则停止\n env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 5000));\n env.addSource(new SourceFunction() {\n\n @Override\n public void run(SourceContext sourceContext) throws Exception ", "post_mask_code": "\n\n @Override\n public void cancel() {\n }\n }).map((MapFunction) aLong -> aLong / 0).print();\n env.execute(\"zhisheng RestartStrategy example\");\n }\n}\n"} {"task_id": "Java_2357", "language": "Java", "task_type": "single_line", "source_file": "java/github/zhisheng17/flink-learning/flink-learning-examples/src/main/java/com/zhisheng/examples/streaming/restartStrategy/AEMain.java", "mask_start_position": 704, "mask_end_position": 707, "canonical_solution": "();", "pre_mask_code": "package com.zhisheng.examples.streaming.restartStrategy;\n\nimport org.apache.flink.api.common.functions.MapFunction;\nimport org.apache.flink.api.common.restartstrategy.RestartStrategies;\nimport org.apache.flink.api.java.utils.ParameterTool;\nimport org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;\nimport org.apache.flink.streaming.api.functions.source.SourceFunction;\n\n/**\n * Desc: 测试重启代码出现异常,导致触发重启策略\n * Created by zhisheng on 2019-04-19\n * blog:http://example.com\n * 微信公众号:zhisheng\n */\npublic class AEMain {\n\n public static void main(String[] args) throws Exception {\n // 创建流运行环境\n StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment", "post_mask_code": "\n env.getConfig().setGlobalJobParameters(ParameterTool.fromArgs(args));\n // 每隔 5s 重启一次,尝试三次如果 Job 还没有起来则停止\n env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 5000));\n env.addSource(new SourceFunction() {\n\n @Override\n public void run(SourceContext sourceContext) throws Exception {\n while (true) {\n sourceContext.collect(System.currentTimeMillis());\n }\n }\n\n @Override\n public void cancel() {\n }\n }).map((MapFunction) aLong -> aLong / 0).print();\n env.execute(\"zhisheng RestartStrategy example\");\n }\n}\n"} {"task_id": "Java_2358", "language": "Java", "task_type": "while_statement", "source_file": "java/github/zhisheng17/flink-learning/flink-learning-examples/src/main/java/com/zhisheng/examples/streaming/restartStrategy/AEMain.java", "mask_start_position": 1078, "mask_end_position": 1181, "canonical_solution": "while (true) {\n sourceContext.collect(System.currentTimeMillis());\n }", "pre_mask_code": "package com.zhisheng.examples.streaming.restartStrategy;\n\nimport org.apache.flink.api.common.functions.MapFunction;\nimport org.apache.flink.api.common.restartstrategy.RestartStrategies;\nimport org.apache.flink.api.java.utils.ParameterTool;\nimport org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;\nimport org.apache.flink.streaming.api.functions.source.SourceFunction;\n\n/**\n * Desc: 测试重启代码出现异常,导致触发重启策略\n * Created by zhisheng on 2019-04-19\n * blog:http://example.com\n * 微信公众号:zhisheng\n */\npublic class AEMain {\n\n public static void main(String[] args) throws Exception {\n // 创建流运行环境\n StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();\n env.getConfig().setGlobalJobParameters(ParameterTool.fromArgs(args));\n // 每隔 5s 重启一次,尝试三次如果 Job 还没有起来则停止\n env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 5000));\n env.addSource(new SourceFunction() {\n\n @Override\n public void run(SourceContext sourceContext) throws Exception {\n ", "post_mask_code": "\n }\n\n @Override\n public void cancel() {\n }\n }).map((MapFunction) aLong -> aLong / 0).print();\n env.execute(\"zhisheng RestartStrategy example\");\n }\n}\n"} {"task_id": "Java_2359", "language": "Java", "task_type": "method_signature", "source_file": "java/github/locationtech/udig-platform/plugins/org.locationtech.udig.catalog.jgrass/src/org/locationtech/udig/catalog/jgrass/activeregion/dialogs/CatalogJGrassMapsetsTreeViewer.java", "mask_start_position": 10423, "mask_end_position": 10458, "canonical_solution": "public Image getImage(Object arg0) ", "pre_mask_code": "package org.locationtech.udig.catalog.jgrass.activeregion.dialogs;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\nimport java.util.Vector;\nimport org.locationtech.udig.catalog.CatalogPlugin;\nimport org.locationtech.udig.catalog.ICatalog;\nimport org.locationtech.udig.catalog.IResolve;\nimport org.eclipse.jface.viewers.ILabelProvider;\nimport org.eclipse.jface.viewers.ILabelProviderListener;\nimport org.eclipse.jface.viewers.ISelectionChangedListener;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.ITreeContentProvider;\nimport org.eclipse.jface.viewers.LabelProviderChangedEvent;\nimport org.eclipse.jface.viewers.SelectionChangedEvent;\nimport org.eclipse.jface.viewers.TreeViewer;\nimport org.eclipse.jface.viewers.Viewer;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.ui.dialogs.FilteredTree;\nimport org.eclipse.ui.dialogs.PatternFilter;\nimport org.eclipse.ui.plugin.AbstractUIPlugin;\nimport org.locationtech.udig.catalog.jgrass.JGrassPlugin;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassMapGeoResource;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassMapsetGeoResource;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassService;\n\n/**\n *

\n * This class supplies a tree viewer containing the JGrass mapsets that are in the catalog When a\n * mapset is selected it is passed to the WidgetObservers that are registered with this class.\n *

\n *\n * @author Andrea Antonello - www.hydrologis.com\n * @since 1.1.0\n */\npublic class CatalogJGrassMapsetsTreeViewer extends Composite implements ISelectionChangedListener, IResourcesSelector {\n\n private final HashMap itemsMap = new HashMap();\n\n private LabelProvider labelProvider = null;\n\n private List itemLayers;\n\n /**\n * @param parent\n * @param style\n * @param selectionStyle the tree selection style (single or multiple)\n * @param mapType the types of map to be filtered out (ex.\n * {@link FeatureLayerTreeViewer.SHAPELAYER})\n */\n public CatalogJGrassMapsetsTreeViewer(Composite parent, int style, int selectionStyle) {\n super(parent, style);\n setLayout(new GridLayout(1, false));\n GridData gridData = new GridData();\n gridData.grabExcessHorizontalSpace = true;\n gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;\n gridData.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;\n gridData.grabExcessVerticalSpace = true;\n setLayoutData(gridData);\n // Create the tree viewer to display the file tree\n PatternFilter patternFilter = new PatternFilter();\n final FilteredTree filter = new FilteredTree(this, selectionStyle, patternFilter);\n final TreeViewer tv = filter.getViewer();\n tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));\n tv.setContentProvider(new ContentProvider());\n labelProvider = new LabelProvider();\n tv.setLabelProvider(labelProvider);\n // pass a non-null that will be ignored //$NON-NLS-1$\n tv.setInput(\"dummy\");\n tv.addSelectionChangedListener(this);\n }\n\n public void selectionChanged(SelectionChangedEvent event) {\n // if the selection is empty clear the label\n if (event.getSelection().isEmpty()) {\n return;\n }\n if (event.getSelection() instanceof IStructuredSelection) {\n IStructuredSelection selection = (IStructuredSelection) event.getSelection();\n Vector itemNames = new Vector();\n for (Iterator iterator = selection.iterator(); iterator.hasNext(); ) {\n Object domain = iterator.next();\n String value = labelProvider.getText(domain);\n itemNames.add(value);\n }\n itemLayers = new ArrayList();\n for (String name : itemNames) {\n JGrassMapsetGeoResource tmpLayer = itemsMap.get(name);\n if (tmpLayer != null) {\n itemLayers.add(tmpLayer);\n }\n }\n }\n }\n\n /**\n * This class provides the content for the tree in FileTree\n */\n private class ContentProvider implements ITreeContentProvider {\n\n /**\n * Gets the children of the specified object\n *\n * @param arg0 the parent object\n * @return Object[]\n */\n public Object[] getChildren(Object arg0) {\n if (arg0 instanceof JGrassService) {\n JGrassService map = (JGrassService) arg0;\n List layers = null;\n try {\n layers = map.members(null);\n } catch (IOException e) {\n e.printStackTrace();\n }\n if (layers == null)\n return null;\n return filteredLayers(layers);\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return null;\n }\n return null;\n }\n\n private Object[] filteredLayers(List layers) {\n Vector filteredLayers = new Vector();\n for (IResolve layer : layers) {\n if (layer instanceof JGrassMapsetGeoResource) {\n filteredLayers.add((JGrassMapsetGeoResource) layer);\n itemsMap.put(((JGrassMapsetGeoResource) layer).getTitle(), (JGrassMapsetGeoResource) layer);\n }\n }\n /*\n * now let's sort them for nice visualization\n */\n HashMap tmp = new HashMap();\n for (JGrassMapsetGeoResource resource : filteredLayers) {\n tmp.put(resource.getTitle(), resource);\n }\n Map sortedMap = new TreeMap(tmp);\n filteredLayers.removeAllElements();\n for (JGrassMapsetGeoResource map : sortedMap.values()) {\n filteredLayers.add(map);\n }\n return filteredLayers.toArray();\n }\n\n /**\n * Gets the parent of the specified object\n *\n * @param arg0 the object\n * @return Object\n */\n public Object getParent(Object arg0) {\n if (arg0 instanceof JGrassMapsetGeoResource) {\n return null;\n } else if (arg0 instanceof JGrassMapGeoResource) {\n try {\n return ((JGrassMapGeoResource) arg0).parent(null);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return null;\n }\n\n /**\n * Returns whether the passed object has children\n *\n * @param arg0 the parent object\n * @return boolean\n */\n public boolean hasChildren(Object arg0) {\n if (arg0 instanceof JGrassService) {\n return true;\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return false;\n }\n return false;\n }\n\n /**\n * Gets the root element(s) of the tree\n *\n * @param arg0 the input data\n * @return Object[]\n */\n public Object[] getElements(Object arg0) {\n // add the service to the catalog\n ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();\n try {\n ArrayList finalCatalogMembers = new ArrayList();\n List allCatalogMembers = catalog.members(null);\n for (IResolve resolve : allCatalogMembers) {\n if (resolve instanceof JGrassService) {\n finalCatalogMembers.add(resolve);\n }\n }\n if (finalCatalogMembers.size() > 0) {\n return finalCatalogMembers.toArray();\n } else {\n return null;\n }\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * Disposes any created resources\n */\n public void dispose() {\n // Nothing to dispose\n }\n\n /**\n * Called when the input changes\n *\n * @param arg0 the viewer\n * @param arg1 the old input\n * @param arg2 the new input\n */\n public void inputChanged(Viewer arg0, Object arg1, Object arg2) {\n // Nothing to change\n }\n }\n\n /**\n * This class provides the labels for the file tree\n */\n private static class LabelProvider implements ILabelProvider {\n\n // The listeners\n private final List listeners;\n\n // Images for tree nodes\n private final Image rasterMaps;\n\n private final Image mainRasterMaps;\n\n // Label provider state: preserve case of file names/directories\n /**\n * Constructs a FileTreeLabelProvider\n */\n public LabelProvider() {\n // Create the list to hold the listeners\n listeners = new ArrayList();\n // Create the images\n mainRasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, \"icons/obj16/jgrassloc_obj.gif\").createImage();\n rasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, \"icons/obj16/jgrass_obj.gif\").createImage();\n }\n\n // * Sets the preserve case attribute\n // * @param preserveCase the preserve case attribute\n // // Since this attribute affects how the labels are computed,\n // // notify all the listeners of the change.\n /**\n * Gets the image to display for a node in the tree\n *\n * @param arg0 the node\n * @return Image\n */\n ", "post_mask_code": "{\n if (arg0 instanceof JGrassService) {\n return mainRasterMaps;\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return rasterMaps;\n } else {\n return null;\n }\n }\n\n /**\n * Gets the text to display for a node in the tree\n *\n * @param arg0 the node\n * @return String\n */\n public String getText(Object arg0) {\n String text = null;\n try {\n if (arg0 instanceof JGrassMapsetGeoResource) {\n text = ((JGrassMapsetGeoResource) arg0).getTitle();\n } else if (arg0 instanceof JGrassService) {\n text = ((JGrassService) arg0).getInfo(null).getTitle();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return text;\n }\n\n /**\n * Adds a listener to this label provider\n *\n * @param arg0 the listener\n */\n public void addListener(ILabelProviderListener arg0) {\n listeners.add(arg0);\n }\n\n /**\n * Called when this LabelProvider is being disposed\n */\n public void dispose() {\n // Dispose the images\n if (rasterMaps != null)\n rasterMaps.dispose();\n }\n\n /**\n * Returns whether changes to the specified property on the specified element would affect\n * the label for the element\n *\n * @param arg0 the element\n * @param arg1 the property\n * @return boolean\n */\n public boolean isLabelProperty(Object arg0, String arg1) {\n return false;\n }\n\n /**\n * Removes the listener\n *\n * @param arg0 the listener to remove\n */\n public void removeListener(ILabelProviderListener arg0) {\n listeners.remove(arg0);\n }\n }\n\n public List getSelectedLayers() {\n return itemLayers;\n }\n\n public int getType() {\n return 0;\n }\n}\n"} {"task_id": "Java_2360", "language": "Java", "task_type": "method_body", "source_file": "java/github/locationtech/udig-platform/plugins/org.locationtech.udig.catalog.jgrass/src/org/locationtech/udig/catalog/jgrass/activeregion/dialogs/CatalogJGrassMapsetsTreeViewer.java", "mask_start_position": 8709, "mask_end_position": 8754, "canonical_solution": "{\n // Nothing to dispose\n }", "pre_mask_code": "package org.locationtech.udig.catalog.jgrass.activeregion.dialogs;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\nimport java.util.Vector;\nimport org.locationtech.udig.catalog.CatalogPlugin;\nimport org.locationtech.udig.catalog.ICatalog;\nimport org.locationtech.udig.catalog.IResolve;\nimport org.eclipse.jface.viewers.ILabelProvider;\nimport org.eclipse.jface.viewers.ILabelProviderListener;\nimport org.eclipse.jface.viewers.ISelectionChangedListener;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.ITreeContentProvider;\nimport org.eclipse.jface.viewers.LabelProviderChangedEvent;\nimport org.eclipse.jface.viewers.SelectionChangedEvent;\nimport org.eclipse.jface.viewers.TreeViewer;\nimport org.eclipse.jface.viewers.Viewer;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.ui.dialogs.FilteredTree;\nimport org.eclipse.ui.dialogs.PatternFilter;\nimport org.eclipse.ui.plugin.AbstractUIPlugin;\nimport org.locationtech.udig.catalog.jgrass.JGrassPlugin;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassMapGeoResource;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassMapsetGeoResource;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassService;\n\n/**\n *

\n * This class supplies a tree viewer containing the JGrass mapsets that are in the catalog When a\n * mapset is selected it is passed to the WidgetObservers that are registered with this class.\n *

\n *\n * @author Andrea Antonello - www.hydrologis.com\n * @since 1.1.0\n */\npublic class CatalogJGrassMapsetsTreeViewer extends Composite implements ISelectionChangedListener, IResourcesSelector {\n\n private final HashMap itemsMap = new HashMap();\n\n private LabelProvider labelProvider = null;\n\n private List itemLayers;\n\n /**\n * @param parent\n * @param style\n * @param selectionStyle the tree selection style (single or multiple)\n * @param mapType the types of map to be filtered out (ex.\n * {@link FeatureLayerTreeViewer.SHAPELAYER})\n */\n public CatalogJGrassMapsetsTreeViewer(Composite parent, int style, int selectionStyle) {\n super(parent, style);\n setLayout(new GridLayout(1, false));\n GridData gridData = new GridData();\n gridData.grabExcessHorizontalSpace = true;\n gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;\n gridData.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;\n gridData.grabExcessVerticalSpace = true;\n setLayoutData(gridData);\n // Create the tree viewer to display the file tree\n PatternFilter patternFilter = new PatternFilter();\n final FilteredTree filter = new FilteredTree(this, selectionStyle, patternFilter);\n final TreeViewer tv = filter.getViewer();\n tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));\n tv.setContentProvider(new ContentProvider());\n labelProvider = new LabelProvider();\n tv.setLabelProvider(labelProvider);\n // pass a non-null that will be ignored //$NON-NLS-1$\n tv.setInput(\"dummy\");\n tv.addSelectionChangedListener(this);\n }\n\n public void selectionChanged(SelectionChangedEvent event) {\n // if the selection is empty clear the label\n if (event.getSelection().isEmpty()) {\n return;\n }\n if (event.getSelection() instanceof IStructuredSelection) {\n IStructuredSelection selection = (IStructuredSelection) event.getSelection();\n Vector itemNames = new Vector();\n for (Iterator iterator = selection.iterator(); iterator.hasNext(); ) {\n Object domain = iterator.next();\n String value = labelProvider.getText(domain);\n itemNames.add(value);\n }\n itemLayers = new ArrayList();\n for (String name : itemNames) {\n JGrassMapsetGeoResource tmpLayer = itemsMap.get(name);\n if (tmpLayer != null) {\n itemLayers.add(tmpLayer);\n }\n }\n }\n }\n\n /**\n * This class provides the content for the tree in FileTree\n */\n private class ContentProvider implements ITreeContentProvider {\n\n /**\n * Gets the children of the specified object\n *\n * @param arg0 the parent object\n * @return Object[]\n */\n public Object[] getChildren(Object arg0) {\n if (arg0 instanceof JGrassService) {\n JGrassService map = (JGrassService) arg0;\n List layers = null;\n try {\n layers = map.members(null);\n } catch (IOException e) {\n e.printStackTrace();\n }\n if (layers == null)\n return null;\n return filteredLayers(layers);\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return null;\n }\n return null;\n }\n\n private Object[] filteredLayers(List layers) {\n Vector filteredLayers = new Vector();\n for (IResolve layer : layers) {\n if (layer instanceof JGrassMapsetGeoResource) {\n filteredLayers.add((JGrassMapsetGeoResource) layer);\n itemsMap.put(((JGrassMapsetGeoResource) layer).getTitle(), (JGrassMapsetGeoResource) layer);\n }\n }\n /*\n * now let's sort them for nice visualization\n */\n HashMap tmp = new HashMap();\n for (JGrassMapsetGeoResource resource : filteredLayers) {\n tmp.put(resource.getTitle(), resource);\n }\n Map sortedMap = new TreeMap(tmp);\n filteredLayers.removeAllElements();\n for (JGrassMapsetGeoResource map : sortedMap.values()) {\n filteredLayers.add(map);\n }\n return filteredLayers.toArray();\n }\n\n /**\n * Gets the parent of the specified object\n *\n * @param arg0 the object\n * @return Object\n */\n public Object getParent(Object arg0) {\n if (arg0 instanceof JGrassMapsetGeoResource) {\n return null;\n } else if (arg0 instanceof JGrassMapGeoResource) {\n try {\n return ((JGrassMapGeoResource) arg0).parent(null);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return null;\n }\n\n /**\n * Returns whether the passed object has children\n *\n * @param arg0 the parent object\n * @return boolean\n */\n public boolean hasChildren(Object arg0) {\n if (arg0 instanceof JGrassService) {\n return true;\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return false;\n }\n return false;\n }\n\n /**\n * Gets the root element(s) of the tree\n *\n * @param arg0 the input data\n * @return Object[]\n */\n public Object[] getElements(Object arg0) {\n // add the service to the catalog\n ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();\n try {\n ArrayList finalCatalogMembers = new ArrayList();\n List allCatalogMembers = catalog.members(null);\n for (IResolve resolve : allCatalogMembers) {\n if (resolve instanceof JGrassService) {\n finalCatalogMembers.add(resolve);\n }\n }\n if (finalCatalogMembers.size() > 0) {\n return finalCatalogMembers.toArray();\n } else {\n return null;\n }\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * Disposes any created resources\n */\n public void dispose() ", "post_mask_code": "\n\n /**\n * Called when the input changes\n *\n * @param arg0 the viewer\n * @param arg1 the old input\n * @param arg2 the new input\n */\n public void inputChanged(Viewer arg0, Object arg1, Object arg2) {\n // Nothing to change\n }\n }\n\n /**\n * This class provides the labels for the file tree\n */\n private static class LabelProvider implements ILabelProvider {\n\n // The listeners\n private final List listeners;\n\n // Images for tree nodes\n private final Image rasterMaps;\n\n private final Image mainRasterMaps;\n\n // Label provider state: preserve case of file names/directories\n /**\n * Constructs a FileTreeLabelProvider\n */\n public LabelProvider() {\n // Create the list to hold the listeners\n listeners = new ArrayList();\n // Create the images\n mainRasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, \"icons/obj16/jgrassloc_obj.gif\").createImage();\n rasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, \"icons/obj16/jgrass_obj.gif\").createImage();\n }\n\n // * Sets the preserve case attribute\n // * @param preserveCase the preserve case attribute\n // // Since this attribute affects how the labels are computed,\n // // notify all the listeners of the change.\n /**\n * Gets the image to display for a node in the tree\n *\n * @param arg0 the node\n * @return Image\n */\n public Image getImage(Object arg0) {\n if (arg0 instanceof JGrassService) {\n return mainRasterMaps;\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return rasterMaps;\n } else {\n return null;\n }\n }\n\n /**\n * Gets the text to display for a node in the tree\n *\n * @param arg0 the node\n * @return String\n */\n public String getText(Object arg0) {\n String text = null;\n try {\n if (arg0 instanceof JGrassMapsetGeoResource) {\n text = ((JGrassMapsetGeoResource) arg0).getTitle();\n } else if (arg0 instanceof JGrassService) {\n text = ((JGrassService) arg0).getInfo(null).getTitle();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return text;\n }\n\n /**\n * Adds a listener to this label provider\n *\n * @param arg0 the listener\n */\n public void addListener(ILabelProviderListener arg0) {\n listeners.add(arg0);\n }\n\n /**\n * Called when this LabelProvider is being disposed\n */\n public void dispose() {\n // Dispose the images\n if (rasterMaps != null)\n rasterMaps.dispose();\n }\n\n /**\n * Returns whether changes to the specified property on the specified element would affect\n * the label for the element\n *\n * @param arg0 the element\n * @param arg1 the property\n * @return boolean\n */\n public boolean isLabelProperty(Object arg0, String arg1) {\n return false;\n }\n\n /**\n * Removes the listener\n *\n * @param arg0 the listener to remove\n */\n public void removeListener(ILabelProviderListener arg0) {\n listeners.remove(arg0);\n }\n }\n\n public List getSelectedLayers() {\n return itemLayers;\n }\n\n public int getType() {\n return 0;\n }\n}\n"} {"task_id": "Java_2361", "language": "Java", "task_type": "single_line", "source_file": "java/github/locationtech/udig-platform/plugins/org.locationtech.udig.catalog.jgrass/src/org/locationtech/udig/catalog/jgrass/activeregion/dialogs/CatalogJGrassMapsetsTreeViewer.java", "mask_start_position": 7116, "mask_end_position": 7119, "canonical_solution": "ll;", "pre_mask_code": "package org.locationtech.udig.catalog.jgrass.activeregion.dialogs;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\nimport java.util.Vector;\nimport org.locationtech.udig.catalog.CatalogPlugin;\nimport org.locationtech.udig.catalog.ICatalog;\nimport org.locationtech.udig.catalog.IResolve;\nimport org.eclipse.jface.viewers.ILabelProvider;\nimport org.eclipse.jface.viewers.ILabelProviderListener;\nimport org.eclipse.jface.viewers.ISelectionChangedListener;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.ITreeContentProvider;\nimport org.eclipse.jface.viewers.LabelProviderChangedEvent;\nimport org.eclipse.jface.viewers.SelectionChangedEvent;\nimport org.eclipse.jface.viewers.TreeViewer;\nimport org.eclipse.jface.viewers.Viewer;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.ui.dialogs.FilteredTree;\nimport org.eclipse.ui.dialogs.PatternFilter;\nimport org.eclipse.ui.plugin.AbstractUIPlugin;\nimport org.locationtech.udig.catalog.jgrass.JGrassPlugin;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassMapGeoResource;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassMapsetGeoResource;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassService;\n\n/**\n *

\n * This class supplies a tree viewer containing the JGrass mapsets that are in the catalog When a\n * mapset is selected it is passed to the WidgetObservers that are registered with this class.\n *

\n *\n * @author Andrea Antonello - www.hydrologis.com\n * @since 1.1.0\n */\npublic class CatalogJGrassMapsetsTreeViewer extends Composite implements ISelectionChangedListener, IResourcesSelector {\n\n private final HashMap itemsMap = new HashMap();\n\n private LabelProvider labelProvider = null;\n\n private List itemLayers;\n\n /**\n * @param parent\n * @param style\n * @param selectionStyle the tree selection style (single or multiple)\n * @param mapType the types of map to be filtered out (ex.\n * {@link FeatureLayerTreeViewer.SHAPELAYER})\n */\n public CatalogJGrassMapsetsTreeViewer(Composite parent, int style, int selectionStyle) {\n super(parent, style);\n setLayout(new GridLayout(1, false));\n GridData gridData = new GridData();\n gridData.grabExcessHorizontalSpace = true;\n gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;\n gridData.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;\n gridData.grabExcessVerticalSpace = true;\n setLayoutData(gridData);\n // Create the tree viewer to display the file tree\n PatternFilter patternFilter = new PatternFilter();\n final FilteredTree filter = new FilteredTree(this, selectionStyle, patternFilter);\n final TreeViewer tv = filter.getViewer();\n tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));\n tv.setContentProvider(new ContentProvider());\n labelProvider = new LabelProvider();\n tv.setLabelProvider(labelProvider);\n // pass a non-null that will be ignored //$NON-NLS-1$\n tv.setInput(\"dummy\");\n tv.addSelectionChangedListener(this);\n }\n\n public void selectionChanged(SelectionChangedEvent event) {\n // if the selection is empty clear the label\n if (event.getSelection().isEmpty()) {\n return;\n }\n if (event.getSelection() instanceof IStructuredSelection) {\n IStructuredSelection selection = (IStructuredSelection) event.getSelection();\n Vector itemNames = new Vector();\n for (Iterator iterator = selection.iterator(); iterator.hasNext(); ) {\n Object domain = iterator.next();\n String value = labelProvider.getText(domain);\n itemNames.add(value);\n }\n itemLayers = new ArrayList();\n for (String name : itemNames) {\n JGrassMapsetGeoResource tmpLayer = itemsMap.get(name);\n if (tmpLayer != null) {\n itemLayers.add(tmpLayer);\n }\n }\n }\n }\n\n /**\n * This class provides the content for the tree in FileTree\n */\n private class ContentProvider implements ITreeContentProvider {\n\n /**\n * Gets the children of the specified object\n *\n * @param arg0 the parent object\n * @return Object[]\n */\n public Object[] getChildren(Object arg0) {\n if (arg0 instanceof JGrassService) {\n JGrassService map = (JGrassService) arg0;\n List layers = null;\n try {\n layers = map.members(null);\n } catch (IOException e) {\n e.printStackTrace();\n }\n if (layers == null)\n return null;\n return filteredLayers(layers);\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return null;\n }\n return null;\n }\n\n private Object[] filteredLayers(List layers) {\n Vector filteredLayers = new Vector();\n for (IResolve layer : layers) {\n if (layer instanceof JGrassMapsetGeoResource) {\n filteredLayers.add((JGrassMapsetGeoResource) layer);\n itemsMap.put(((JGrassMapsetGeoResource) layer).getTitle(), (JGrassMapsetGeoResource) layer);\n }\n }\n /*\n * now let's sort them for nice visualization\n */\n HashMap tmp = new HashMap();\n for (JGrassMapsetGeoResource resource : filteredLayers) {\n tmp.put(resource.getTitle(), resource);\n }\n Map sortedMap = new TreeMap(tmp);\n filteredLayers.removeAllElements();\n for (JGrassMapsetGeoResource map : sortedMap.values()) {\n filteredLayers.add(map);\n }\n return filteredLayers.toArray();\n }\n\n /**\n * Gets the parent of the specified object\n *\n * @param arg0 the object\n * @return Object\n */\n public Object getParent(Object arg0) {\n if (arg0 instanceof JGrassMapsetGeoResource) {\n return null;\n } else if (arg0 instanceof JGrassMapGeoResource) {\n try {\n return ((JGrassMapGeoResource) arg0).parent(null);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return nu", "post_mask_code": "\n }\n\n /**\n * Returns whether the passed object has children\n *\n * @param arg0 the parent object\n * @return boolean\n */\n public boolean hasChildren(Object arg0) {\n if (arg0 instanceof JGrassService) {\n return true;\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return false;\n }\n return false;\n }\n\n /**\n * Gets the root element(s) of the tree\n *\n * @param arg0 the input data\n * @return Object[]\n */\n public Object[] getElements(Object arg0) {\n // add the service to the catalog\n ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();\n try {\n ArrayList finalCatalogMembers = new ArrayList();\n List allCatalogMembers = catalog.members(null);\n for (IResolve resolve : allCatalogMembers) {\n if (resolve instanceof JGrassService) {\n finalCatalogMembers.add(resolve);\n }\n }\n if (finalCatalogMembers.size() > 0) {\n return finalCatalogMembers.toArray();\n } else {\n return null;\n }\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * Disposes any created resources\n */\n public void dispose() {\n // Nothing to dispose\n }\n\n /**\n * Called when the input changes\n *\n * @param arg0 the viewer\n * @param arg1 the old input\n * @param arg2 the new input\n */\n public void inputChanged(Viewer arg0, Object arg1, Object arg2) {\n // Nothing to change\n }\n }\n\n /**\n * This class provides the labels for the file tree\n */\n private static class LabelProvider implements ILabelProvider {\n\n // The listeners\n private final List listeners;\n\n // Images for tree nodes\n private final Image rasterMaps;\n\n private final Image mainRasterMaps;\n\n // Label provider state: preserve case of file names/directories\n /**\n * Constructs a FileTreeLabelProvider\n */\n public LabelProvider() {\n // Create the list to hold the listeners\n listeners = new ArrayList();\n // Create the images\n mainRasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, \"icons/obj16/jgrassloc_obj.gif\").createImage();\n rasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, \"icons/obj16/jgrass_obj.gif\").createImage();\n }\n\n // * Sets the preserve case attribute\n // * @param preserveCase the preserve case attribute\n // // Since this attribute affects how the labels are computed,\n // // notify all the listeners of the change.\n /**\n * Gets the image to display for a node in the tree\n *\n * @param arg0 the node\n * @return Image\n */\n public Image getImage(Object arg0) {\n if (arg0 instanceof JGrassService) {\n return mainRasterMaps;\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return rasterMaps;\n } else {\n return null;\n }\n }\n\n /**\n * Gets the text to display for a node in the tree\n *\n * @param arg0 the node\n * @return String\n */\n public String getText(Object arg0) {\n String text = null;\n try {\n if (arg0 instanceof JGrassMapsetGeoResource) {\n text = ((JGrassMapsetGeoResource) arg0).getTitle();\n } else if (arg0 instanceof JGrassService) {\n text = ((JGrassService) arg0).getInfo(null).getTitle();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return text;\n }\n\n /**\n * Adds a listener to this label provider\n *\n * @param arg0 the listener\n */\n public void addListener(ILabelProviderListener arg0) {\n listeners.add(arg0);\n }\n\n /**\n * Called when this LabelProvider is being disposed\n */\n public void dispose() {\n // Dispose the images\n if (rasterMaps != null)\n rasterMaps.dispose();\n }\n\n /**\n * Returns whether changes to the specified property on the specified element would affect\n * the label for the element\n *\n * @param arg0 the element\n * @param arg1 the property\n * @return boolean\n */\n public boolean isLabelProperty(Object arg0, String arg1) {\n return false;\n }\n\n /**\n * Removes the listener\n *\n * @param arg0 the listener to remove\n */\n public void removeListener(ILabelProviderListener arg0) {\n listeners.remove(arg0);\n }\n }\n\n public List getSelectedLayers() {\n return itemLayers;\n }\n\n public int getType() {\n return 0;\n }\n}\n"} {"task_id": "Java_2362", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/locationtech/udig-platform/plugins/org.locationtech.udig.catalog.jgrass/src/org/locationtech/udig/catalog/jgrass/activeregion/dialogs/CatalogJGrassMapsetsTreeViewer.java", "mask_start_position": 12342, "mask_end_position": 12445, "canonical_solution": "public void removeListener(ILabelProviderListener arg0) {\n listeners.remove(arg0);\n }", "pre_mask_code": "package org.locationtech.udig.catalog.jgrass.activeregion.dialogs;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\nimport java.util.Vector;\nimport org.locationtech.udig.catalog.CatalogPlugin;\nimport org.locationtech.udig.catalog.ICatalog;\nimport org.locationtech.udig.catalog.IResolve;\nimport org.eclipse.jface.viewers.ILabelProvider;\nimport org.eclipse.jface.viewers.ILabelProviderListener;\nimport org.eclipse.jface.viewers.ISelectionChangedListener;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.ITreeContentProvider;\nimport org.eclipse.jface.viewers.LabelProviderChangedEvent;\nimport org.eclipse.jface.viewers.SelectionChangedEvent;\nimport org.eclipse.jface.viewers.TreeViewer;\nimport org.eclipse.jface.viewers.Viewer;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.ui.dialogs.FilteredTree;\nimport org.eclipse.ui.dialogs.PatternFilter;\nimport org.eclipse.ui.plugin.AbstractUIPlugin;\nimport org.locationtech.udig.catalog.jgrass.JGrassPlugin;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassMapGeoResource;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassMapsetGeoResource;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassService;\n\n/**\n *

\n * This class supplies a tree viewer containing the JGrass mapsets that are in the catalog When a\n * mapset is selected it is passed to the WidgetObservers that are registered with this class.\n *

\n *\n * @author Andrea Antonello - www.hydrologis.com\n * @since 1.1.0\n */\npublic class CatalogJGrassMapsetsTreeViewer extends Composite implements ISelectionChangedListener, IResourcesSelector {\n\n private final HashMap itemsMap = new HashMap();\n\n private LabelProvider labelProvider = null;\n\n private List itemLayers;\n\n /**\n * @param parent\n * @param style\n * @param selectionStyle the tree selection style (single or multiple)\n * @param mapType the types of map to be filtered out (ex.\n * {@link FeatureLayerTreeViewer.SHAPELAYER})\n */\n public CatalogJGrassMapsetsTreeViewer(Composite parent, int style, int selectionStyle) {\n super(parent, style);\n setLayout(new GridLayout(1, false));\n GridData gridData = new GridData();\n gridData.grabExcessHorizontalSpace = true;\n gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;\n gridData.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;\n gridData.grabExcessVerticalSpace = true;\n setLayoutData(gridData);\n // Create the tree viewer to display the file tree\n PatternFilter patternFilter = new PatternFilter();\n final FilteredTree filter = new FilteredTree(this, selectionStyle, patternFilter);\n final TreeViewer tv = filter.getViewer();\n tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));\n tv.setContentProvider(new ContentProvider());\n labelProvider = new LabelProvider();\n tv.setLabelProvider(labelProvider);\n // pass a non-null that will be ignored //$NON-NLS-1$\n tv.setInput(\"dummy\");\n tv.addSelectionChangedListener(this);\n }\n\n public void selectionChanged(SelectionChangedEvent event) {\n // if the selection is empty clear the label\n if (event.getSelection().isEmpty()) {\n return;\n }\n if (event.getSelection() instanceof IStructuredSelection) {\n IStructuredSelection selection = (IStructuredSelection) event.getSelection();\n Vector itemNames = new Vector();\n for (Iterator iterator = selection.iterator(); iterator.hasNext(); ) {\n Object domain = iterator.next();\n String value = labelProvider.getText(domain);\n itemNames.add(value);\n }\n itemLayers = new ArrayList();\n for (String name : itemNames) {\n JGrassMapsetGeoResource tmpLayer = itemsMap.get(name);\n if (tmpLayer != null) {\n itemLayers.add(tmpLayer);\n }\n }\n }\n }\n\n /**\n * This class provides the content for the tree in FileTree\n */\n private class ContentProvider implements ITreeContentProvider {\n\n /**\n * Gets the children of the specified object\n *\n * @param arg0 the parent object\n * @return Object[]\n */\n public Object[] getChildren(Object arg0) {\n if (arg0 instanceof JGrassService) {\n JGrassService map = (JGrassService) arg0;\n List layers = null;\n try {\n layers = map.members(null);\n } catch (IOException e) {\n e.printStackTrace();\n }\n if (layers == null)\n return null;\n return filteredLayers(layers);\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return null;\n }\n return null;\n }\n\n private Object[] filteredLayers(List layers) {\n Vector filteredLayers = new Vector();\n for (IResolve layer : layers) {\n if (layer instanceof JGrassMapsetGeoResource) {\n filteredLayers.add((JGrassMapsetGeoResource) layer);\n itemsMap.put(((JGrassMapsetGeoResource) layer).getTitle(), (JGrassMapsetGeoResource) layer);\n }\n }\n /*\n * now let's sort them for nice visualization\n */\n HashMap tmp = new HashMap();\n for (JGrassMapsetGeoResource resource : filteredLayers) {\n tmp.put(resource.getTitle(), resource);\n }\n Map sortedMap = new TreeMap(tmp);\n filteredLayers.removeAllElements();\n for (JGrassMapsetGeoResource map : sortedMap.values()) {\n filteredLayers.add(map);\n }\n return filteredLayers.toArray();\n }\n\n /**\n * Gets the parent of the specified object\n *\n * @param arg0 the object\n * @return Object\n */\n public Object getParent(Object arg0) {\n if (arg0 instanceof JGrassMapsetGeoResource) {\n return null;\n } else if (arg0 instanceof JGrassMapGeoResource) {\n try {\n return ((JGrassMapGeoResource) arg0).parent(null);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return null;\n }\n\n /**\n * Returns whether the passed object has children\n *\n * @param arg0 the parent object\n * @return boolean\n */\n public boolean hasChildren(Object arg0) {\n if (arg0 instanceof JGrassService) {\n return true;\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return false;\n }\n return false;\n }\n\n /**\n * Gets the root element(s) of the tree\n *\n * @param arg0 the input data\n * @return Object[]\n */\n public Object[] getElements(Object arg0) {\n // add the service to the catalog\n ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();\n try {\n ArrayList finalCatalogMembers = new ArrayList();\n List allCatalogMembers = catalog.members(null);\n for (IResolve resolve : allCatalogMembers) {\n if (resolve instanceof JGrassService) {\n finalCatalogMembers.add(resolve);\n }\n }\n if (finalCatalogMembers.size() > 0) {\n return finalCatalogMembers.toArray();\n } else {\n return null;\n }\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * Disposes any created resources\n */\n public void dispose() {\n // Nothing to dispose\n }\n\n /**\n * Called when the input changes\n *\n * @param arg0 the viewer\n * @param arg1 the old input\n * @param arg2 the new input\n */\n public void inputChanged(Viewer arg0, Object arg1, Object arg2) {\n // Nothing to change\n }\n }\n\n /**\n * This class provides the labels for the file tree\n */\n private static class LabelProvider implements ILabelProvider {\n\n // The listeners\n private final List listeners;\n\n // Images for tree nodes\n private final Image rasterMaps;\n\n private final Image mainRasterMaps;\n\n // Label provider state: preserve case of file names/directories\n /**\n * Constructs a FileTreeLabelProvider\n */\n public LabelProvider() {\n // Create the list to hold the listeners\n listeners = new ArrayList();\n // Create the images\n mainRasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, \"icons/obj16/jgrassloc_obj.gif\").createImage();\n rasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, \"icons/obj16/jgrass_obj.gif\").createImage();\n }\n\n // * Sets the preserve case attribute\n // * @param preserveCase the preserve case attribute\n // // Since this attribute affects how the labels are computed,\n // // notify all the listeners of the change.\n /**\n * Gets the image to display for a node in the tree\n *\n * @param arg0 the node\n * @return Image\n */\n public Image getImage(Object arg0) {\n if (arg0 instanceof JGrassService) {\n return mainRasterMaps;\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return rasterMaps;\n } else {\n return null;\n }\n }\n\n /**\n * Gets the text to display for a node in the tree\n *\n * @param arg0 the node\n * @return String\n */\n public String getText(Object arg0) {\n String text = null;\n try {\n if (arg0 instanceof JGrassMapsetGeoResource) {\n text = ((JGrassMapsetGeoResource) arg0).getTitle();\n } else if (arg0 instanceof JGrassService) {\n text = ((JGrassService) arg0).getInfo(null).getTitle();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return text;\n }\n\n /**\n * Adds a listener to this label provider\n *\n * @param arg0 the listener\n */\n public void addListener(ILabelProviderListener arg0) {\n listeners.add(arg0);\n }\n\n /**\n * Called when this LabelProvider is being disposed\n */\n public void dispose() {\n // Dispose the images\n if (rasterMaps != null)\n rasterMaps.dispose();\n }\n\n /**\n * Returns whether changes to the specified property on the specified element would affect\n * the label for the element\n *\n * @param arg0 the element\n * @param arg1 the property\n * @return boolean\n */\n public boolean isLabelProperty(Object arg0, String arg1) {\n return false;\n }\n\n /**\n * Removes the listener\n *\n * @param arg0 the listener to remove\n */\n ", "post_mask_code": "\n }\n\n public List getSelectedLayers() {\n return itemLayers;\n }\n\n public int getType() {\n return 0;\n }\n}\n"} {"task_id": "Java_2363", "language": "Java", "task_type": "for_statement", "source_file": "java/github/locationtech/udig-platform/plugins/org.locationtech.udig.catalog.jgrass/src/org/locationtech/udig/catalog/jgrass/activeregion/dialogs/CatalogJGrassMapsetsTreeViewer.java", "mask_start_position": 3883, "mask_end_position": 4116, "canonical_solution": "for (Iterator iterator = selection.iterator(); iterator.hasNext(); ) {\n Object domain = iterator.next();\n String value = labelProvider.getText(domain);\n itemNames.add(value);\n }", "pre_mask_code": "package org.locationtech.udig.catalog.jgrass.activeregion.dialogs;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\nimport java.util.Vector;\nimport org.locationtech.udig.catalog.CatalogPlugin;\nimport org.locationtech.udig.catalog.ICatalog;\nimport org.locationtech.udig.catalog.IResolve;\nimport org.eclipse.jface.viewers.ILabelProvider;\nimport org.eclipse.jface.viewers.ILabelProviderListener;\nimport org.eclipse.jface.viewers.ISelectionChangedListener;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.ITreeContentProvider;\nimport org.eclipse.jface.viewers.LabelProviderChangedEvent;\nimport org.eclipse.jface.viewers.SelectionChangedEvent;\nimport org.eclipse.jface.viewers.TreeViewer;\nimport org.eclipse.jface.viewers.Viewer;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.ui.dialogs.FilteredTree;\nimport org.eclipse.ui.dialogs.PatternFilter;\nimport org.eclipse.ui.plugin.AbstractUIPlugin;\nimport org.locationtech.udig.catalog.jgrass.JGrassPlugin;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassMapGeoResource;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassMapsetGeoResource;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassService;\n\n/**\n *

\n * This class supplies a tree viewer containing the JGrass mapsets that are in the catalog When a\n * mapset is selected it is passed to the WidgetObservers that are registered with this class.\n *

\n *\n * @author Andrea Antonello - www.hydrologis.com\n * @since 1.1.0\n */\npublic class CatalogJGrassMapsetsTreeViewer extends Composite implements ISelectionChangedListener, IResourcesSelector {\n\n private final HashMap itemsMap = new HashMap();\n\n private LabelProvider labelProvider = null;\n\n private List itemLayers;\n\n /**\n * @param parent\n * @param style\n * @param selectionStyle the tree selection style (single or multiple)\n * @param mapType the types of map to be filtered out (ex.\n * {@link FeatureLayerTreeViewer.SHAPELAYER})\n */\n public CatalogJGrassMapsetsTreeViewer(Composite parent, int style, int selectionStyle) {\n super(parent, style);\n setLayout(new GridLayout(1, false));\n GridData gridData = new GridData();\n gridData.grabExcessHorizontalSpace = true;\n gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;\n gridData.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;\n gridData.grabExcessVerticalSpace = true;\n setLayoutData(gridData);\n // Create the tree viewer to display the file tree\n PatternFilter patternFilter = new PatternFilter();\n final FilteredTree filter = new FilteredTree(this, selectionStyle, patternFilter);\n final TreeViewer tv = filter.getViewer();\n tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));\n tv.setContentProvider(new ContentProvider());\n labelProvider = new LabelProvider();\n tv.setLabelProvider(labelProvider);\n // pass a non-null that will be ignored //$NON-NLS-1$\n tv.setInput(\"dummy\");\n tv.addSelectionChangedListener(this);\n }\n\n public void selectionChanged(SelectionChangedEvent event) {\n // if the selection is empty clear the label\n if (event.getSelection().isEmpty()) {\n return;\n }\n if (event.getSelection() instanceof IStructuredSelection) {\n IStructuredSelection selection = (IStructuredSelection) event.getSelection();\n Vector itemNames = new Vector();\n ", "post_mask_code": "\n itemLayers = new ArrayList();\n for (String name : itemNames) {\n JGrassMapsetGeoResource tmpLayer = itemsMap.get(name);\n if (tmpLayer != null) {\n itemLayers.add(tmpLayer);\n }\n }\n }\n }\n\n /**\n * This class provides the content for the tree in FileTree\n */\n private class ContentProvider implements ITreeContentProvider {\n\n /**\n * Gets the children of the specified object\n *\n * @param arg0 the parent object\n * @return Object[]\n */\n public Object[] getChildren(Object arg0) {\n if (arg0 instanceof JGrassService) {\n JGrassService map = (JGrassService) arg0;\n List layers = null;\n try {\n layers = map.members(null);\n } catch (IOException e) {\n e.printStackTrace();\n }\n if (layers == null)\n return null;\n return filteredLayers(layers);\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return null;\n }\n return null;\n }\n\n private Object[] filteredLayers(List layers) {\n Vector filteredLayers = new Vector();\n for (IResolve layer : layers) {\n if (layer instanceof JGrassMapsetGeoResource) {\n filteredLayers.add((JGrassMapsetGeoResource) layer);\n itemsMap.put(((JGrassMapsetGeoResource) layer).getTitle(), (JGrassMapsetGeoResource) layer);\n }\n }\n /*\n * now let's sort them for nice visualization\n */\n HashMap tmp = new HashMap();\n for (JGrassMapsetGeoResource resource : filteredLayers) {\n tmp.put(resource.getTitle(), resource);\n }\n Map sortedMap = new TreeMap(tmp);\n filteredLayers.removeAllElements();\n for (JGrassMapsetGeoResource map : sortedMap.values()) {\n filteredLayers.add(map);\n }\n return filteredLayers.toArray();\n }\n\n /**\n * Gets the parent of the specified object\n *\n * @param arg0 the object\n * @return Object\n */\n public Object getParent(Object arg0) {\n if (arg0 instanceof JGrassMapsetGeoResource) {\n return null;\n } else if (arg0 instanceof JGrassMapGeoResource) {\n try {\n return ((JGrassMapGeoResource) arg0).parent(null);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return null;\n }\n\n /**\n * Returns whether the passed object has children\n *\n * @param arg0 the parent object\n * @return boolean\n */\n public boolean hasChildren(Object arg0) {\n if (arg0 instanceof JGrassService) {\n return true;\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return false;\n }\n return false;\n }\n\n /**\n * Gets the root element(s) of the tree\n *\n * @param arg0 the input data\n * @return Object[]\n */\n public Object[] getElements(Object arg0) {\n // add the service to the catalog\n ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();\n try {\n ArrayList finalCatalogMembers = new ArrayList();\n List allCatalogMembers = catalog.members(null);\n for (IResolve resolve : allCatalogMembers) {\n if (resolve instanceof JGrassService) {\n finalCatalogMembers.add(resolve);\n }\n }\n if (finalCatalogMembers.size() > 0) {\n return finalCatalogMembers.toArray();\n } else {\n return null;\n }\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * Disposes any created resources\n */\n public void dispose() {\n // Nothing to dispose\n }\n\n /**\n * Called when the input changes\n *\n * @param arg0 the viewer\n * @param arg1 the old input\n * @param arg2 the new input\n */\n public void inputChanged(Viewer arg0, Object arg1, Object arg2) {\n // Nothing to change\n }\n }\n\n /**\n * This class provides the labels for the file tree\n */\n private static class LabelProvider implements ILabelProvider {\n\n // The listeners\n private final List listeners;\n\n // Images for tree nodes\n private final Image rasterMaps;\n\n private final Image mainRasterMaps;\n\n // Label provider state: preserve case of file names/directories\n /**\n * Constructs a FileTreeLabelProvider\n */\n public LabelProvider() {\n // Create the list to hold the listeners\n listeners = new ArrayList();\n // Create the images\n mainRasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, \"icons/obj16/jgrassloc_obj.gif\").createImage();\n rasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, \"icons/obj16/jgrass_obj.gif\").createImage();\n }\n\n // * Sets the preserve case attribute\n // * @param preserveCase the preserve case attribute\n // // Since this attribute affects how the labels are computed,\n // // notify all the listeners of the change.\n /**\n * Gets the image to display for a node in the tree\n *\n * @param arg0 the node\n * @return Image\n */\n public Image getImage(Object arg0) {\n if (arg0 instanceof JGrassService) {\n return mainRasterMaps;\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return rasterMaps;\n } else {\n return null;\n }\n }\n\n /**\n * Gets the text to display for a node in the tree\n *\n * @param arg0 the node\n * @return String\n */\n public String getText(Object arg0) {\n String text = null;\n try {\n if (arg0 instanceof JGrassMapsetGeoResource) {\n text = ((JGrassMapsetGeoResource) arg0).getTitle();\n } else if (arg0 instanceof JGrassService) {\n text = ((JGrassService) arg0).getInfo(null).getTitle();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return text;\n }\n\n /**\n * Adds a listener to this label provider\n *\n * @param arg0 the listener\n */\n public void addListener(ILabelProviderListener arg0) {\n listeners.add(arg0);\n }\n\n /**\n * Called when this LabelProvider is being disposed\n */\n public void dispose() {\n // Dispose the images\n if (rasterMaps != null)\n rasterMaps.dispose();\n }\n\n /**\n * Returns whether changes to the specified property on the specified element would affect\n * the label for the element\n *\n * @param arg0 the element\n * @param arg1 the property\n * @return boolean\n */\n public boolean isLabelProperty(Object arg0, String arg1) {\n return false;\n }\n\n /**\n * Removes the listener\n *\n * @param arg0 the listener to remove\n */\n public void removeListener(ILabelProviderListener arg0) {\n listeners.remove(arg0);\n }\n }\n\n public List getSelectedLayers() {\n return itemLayers;\n }\n\n public int getType() {\n return 0;\n }\n}\n"} {"task_id": "Java_2364", "language": "Java", "task_type": "try_statement", "source_file": "java/github/locationtech/udig-platform/plugins/org.locationtech.udig.catalog.jgrass/src/org/locationtech/udig/catalog/jgrass/activeregion/dialogs/CatalogJGrassMapsetsTreeViewer.java", "mask_start_position": 10965, "mask_end_position": 11348, "canonical_solution": "try {\n if (arg0 instanceof JGrassMapsetGeoResource) {\n text = ((JGrassMapsetGeoResource) arg0).getTitle();\n } else if (arg0 instanceof JGrassService) {\n text = ((JGrassService) arg0).getInfo(null).getTitle();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }", "pre_mask_code": "package org.locationtech.udig.catalog.jgrass.activeregion.dialogs;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\nimport java.util.Vector;\nimport org.locationtech.udig.catalog.CatalogPlugin;\nimport org.locationtech.udig.catalog.ICatalog;\nimport org.locationtech.udig.catalog.IResolve;\nimport org.eclipse.jface.viewers.ILabelProvider;\nimport org.eclipse.jface.viewers.ILabelProviderListener;\nimport org.eclipse.jface.viewers.ISelectionChangedListener;\nimport org.eclipse.jface.viewers.IStructuredSelection;\nimport org.eclipse.jface.viewers.ITreeContentProvider;\nimport org.eclipse.jface.viewers.LabelProviderChangedEvent;\nimport org.eclipse.jface.viewers.SelectionChangedEvent;\nimport org.eclipse.jface.viewers.TreeViewer;\nimport org.eclipse.jface.viewers.Viewer;\nimport org.eclipse.swt.graphics.Image;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.ui.dialogs.FilteredTree;\nimport org.eclipse.ui.dialogs.PatternFilter;\nimport org.eclipse.ui.plugin.AbstractUIPlugin;\nimport org.locationtech.udig.catalog.jgrass.JGrassPlugin;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassMapGeoResource;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassMapsetGeoResource;\nimport org.locationtech.udig.catalog.jgrass.core.JGrassService;\n\n/**\n *

\n * This class supplies a tree viewer containing the JGrass mapsets that are in the catalog When a\n * mapset is selected it is passed to the WidgetObservers that are registered with this class.\n *

\n *\n * @author Andrea Antonello - www.hydrologis.com\n * @since 1.1.0\n */\npublic class CatalogJGrassMapsetsTreeViewer extends Composite implements ISelectionChangedListener, IResourcesSelector {\n\n private final HashMap itemsMap = new HashMap();\n\n private LabelProvider labelProvider = null;\n\n private List itemLayers;\n\n /**\n * @param parent\n * @param style\n * @param selectionStyle the tree selection style (single or multiple)\n * @param mapType the types of map to be filtered out (ex.\n * {@link FeatureLayerTreeViewer.SHAPELAYER})\n */\n public CatalogJGrassMapsetsTreeViewer(Composite parent, int style, int selectionStyle) {\n super(parent, style);\n setLayout(new GridLayout(1, false));\n GridData gridData = new GridData();\n gridData.grabExcessHorizontalSpace = true;\n gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;\n gridData.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;\n gridData.grabExcessVerticalSpace = true;\n setLayoutData(gridData);\n // Create the tree viewer to display the file tree\n PatternFilter patternFilter = new PatternFilter();\n final FilteredTree filter = new FilteredTree(this, selectionStyle, patternFilter);\n final TreeViewer tv = filter.getViewer();\n tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));\n tv.setContentProvider(new ContentProvider());\n labelProvider = new LabelProvider();\n tv.setLabelProvider(labelProvider);\n // pass a non-null that will be ignored //$NON-NLS-1$\n tv.setInput(\"dummy\");\n tv.addSelectionChangedListener(this);\n }\n\n public void selectionChanged(SelectionChangedEvent event) {\n // if the selection is empty clear the label\n if (event.getSelection().isEmpty()) {\n return;\n }\n if (event.getSelection() instanceof IStructuredSelection) {\n IStructuredSelection selection = (IStructuredSelection) event.getSelection();\n Vector itemNames = new Vector();\n for (Iterator iterator = selection.iterator(); iterator.hasNext(); ) {\n Object domain = iterator.next();\n String value = labelProvider.getText(domain);\n itemNames.add(value);\n }\n itemLayers = new ArrayList();\n for (String name : itemNames) {\n JGrassMapsetGeoResource tmpLayer = itemsMap.get(name);\n if (tmpLayer != null) {\n itemLayers.add(tmpLayer);\n }\n }\n }\n }\n\n /**\n * This class provides the content for the tree in FileTree\n */\n private class ContentProvider implements ITreeContentProvider {\n\n /**\n * Gets the children of the specified object\n *\n * @param arg0 the parent object\n * @return Object[]\n */\n public Object[] getChildren(Object arg0) {\n if (arg0 instanceof JGrassService) {\n JGrassService map = (JGrassService) arg0;\n List layers = null;\n try {\n layers = map.members(null);\n } catch (IOException e) {\n e.printStackTrace();\n }\n if (layers == null)\n return null;\n return filteredLayers(layers);\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return null;\n }\n return null;\n }\n\n private Object[] filteredLayers(List layers) {\n Vector filteredLayers = new Vector();\n for (IResolve layer : layers) {\n if (layer instanceof JGrassMapsetGeoResource) {\n filteredLayers.add((JGrassMapsetGeoResource) layer);\n itemsMap.put(((JGrassMapsetGeoResource) layer).getTitle(), (JGrassMapsetGeoResource) layer);\n }\n }\n /*\n * now let's sort them for nice visualization\n */\n HashMap tmp = new HashMap();\n for (JGrassMapsetGeoResource resource : filteredLayers) {\n tmp.put(resource.getTitle(), resource);\n }\n Map sortedMap = new TreeMap(tmp);\n filteredLayers.removeAllElements();\n for (JGrassMapsetGeoResource map : sortedMap.values()) {\n filteredLayers.add(map);\n }\n return filteredLayers.toArray();\n }\n\n /**\n * Gets the parent of the specified object\n *\n * @param arg0 the object\n * @return Object\n */\n public Object getParent(Object arg0) {\n if (arg0 instanceof JGrassMapsetGeoResource) {\n return null;\n } else if (arg0 instanceof JGrassMapGeoResource) {\n try {\n return ((JGrassMapGeoResource) arg0).parent(null);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return null;\n }\n\n /**\n * Returns whether the passed object has children\n *\n * @param arg0 the parent object\n * @return boolean\n */\n public boolean hasChildren(Object arg0) {\n if (arg0 instanceof JGrassService) {\n return true;\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return false;\n }\n return false;\n }\n\n /**\n * Gets the root element(s) of the tree\n *\n * @param arg0 the input data\n * @return Object[]\n */\n public Object[] getElements(Object arg0) {\n // add the service to the catalog\n ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();\n try {\n ArrayList finalCatalogMembers = new ArrayList();\n List allCatalogMembers = catalog.members(null);\n for (IResolve resolve : allCatalogMembers) {\n if (resolve instanceof JGrassService) {\n finalCatalogMembers.add(resolve);\n }\n }\n if (finalCatalogMembers.size() > 0) {\n return finalCatalogMembers.toArray();\n } else {\n return null;\n }\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * Disposes any created resources\n */\n public void dispose() {\n // Nothing to dispose\n }\n\n /**\n * Called when the input changes\n *\n * @param arg0 the viewer\n * @param arg1 the old input\n * @param arg2 the new input\n */\n public void inputChanged(Viewer arg0, Object arg1, Object arg2) {\n // Nothing to change\n }\n }\n\n /**\n * This class provides the labels for the file tree\n */\n private static class LabelProvider implements ILabelProvider {\n\n // The listeners\n private final List listeners;\n\n // Images for tree nodes\n private final Image rasterMaps;\n\n private final Image mainRasterMaps;\n\n // Label provider state: preserve case of file names/directories\n /**\n * Constructs a FileTreeLabelProvider\n */\n public LabelProvider() {\n // Create the list to hold the listeners\n listeners = new ArrayList();\n // Create the images\n mainRasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, \"icons/obj16/jgrassloc_obj.gif\").createImage();\n rasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, \"icons/obj16/jgrass_obj.gif\").createImage();\n }\n\n // * Sets the preserve case attribute\n // * @param preserveCase the preserve case attribute\n // // Since this attribute affects how the labels are computed,\n // // notify all the listeners of the change.\n /**\n * Gets the image to display for a node in the tree\n *\n * @param arg0 the node\n * @return Image\n */\n public Image getImage(Object arg0) {\n if (arg0 instanceof JGrassService) {\n return mainRasterMaps;\n } else if (arg0 instanceof JGrassMapsetGeoResource) {\n return rasterMaps;\n } else {\n return null;\n }\n }\n\n /**\n * Gets the text to display for a node in the tree\n *\n * @param arg0 the node\n * @return String\n */\n public String getText(Object arg0) {\n String text = null;\n ", "post_mask_code": "\n return text;\n }\n\n /**\n * Adds a listener to this label provider\n *\n * @param arg0 the listener\n */\n public void addListener(ILabelProviderListener arg0) {\n listeners.add(arg0);\n }\n\n /**\n * Called when this LabelProvider is being disposed\n */\n public void dispose() {\n // Dispose the images\n if (rasterMaps != null)\n rasterMaps.dispose();\n }\n\n /**\n * Returns whether changes to the specified property on the specified element would affect\n * the label for the element\n *\n * @param arg0 the element\n * @param arg1 the property\n * @return boolean\n */\n public boolean isLabelProperty(Object arg0, String arg1) {\n return false;\n }\n\n /**\n * Removes the listener\n *\n * @param arg0 the listener to remove\n */\n public void removeListener(ILabelProviderListener arg0) {\n listeners.remove(arg0);\n }\n }\n\n public List getSelectedLayers() {\n return itemLayers;\n }\n\n public int getType() {\n return 0;\n }\n}\n"} {"task_id": "Java_2365", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ISID/iPLAss/iplass-admin/src/main/java/org/iplass/adminconsole/client/base/ui/widget/form/MtpTextItem.java", "mask_start_position": 403, "mask_end_position": 423, "canonical_solution": "private void init() ", "pre_mask_code": "package org.iplass.adminconsole.client.base.ui.widget.form;\n\nimport com.smartgwt.client.widgets.form.fields.TextItem;\n\npublic class MtpTextItem extends TextItem {\n\n public MtpTextItem() {\n init();\n }\n\n public MtpTextItem(String name) {\n super(name);\n init();\n }\n\n public MtpTextItem(String name, String title) {\n super(name, title);\n init();\n }\n\n ", "post_mask_code": "{\n setWidth(\"100%\");\n setBrowserSpellCheck(false);\n }\n}\n"} {"task_id": "Java_2366", "language": "Java", "task_type": "method_body", "source_file": "java/github/ISID/iPLAss/iplass-admin/src/main/java/org/iplass/adminconsole/client/base/ui/widget/form/MtpTextItem.java", "mask_start_position": 423, "mask_end_position": 493, "canonical_solution": "{\n setWidth(\"100%\");\n setBrowserSpellCheck(false);\n }", "pre_mask_code": "package org.iplass.adminconsole.client.base.ui.widget.form;\n\nimport com.smartgwt.client.widgets.form.fields.TextItem;\n\npublic class MtpTextItem extends TextItem {\n\n public MtpTextItem() {\n init();\n }\n\n public MtpTextItem(String name) {\n super(name);\n init();\n }\n\n public MtpTextItem(String name, String title) {\n super(name, title);\n init();\n }\n\n private void init() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2367", "language": "Java", "task_type": "single_line", "source_file": "java/github/ISID/iPLAss/iplass-admin/src/main/java/org/iplass/adminconsole/client/base/ui/widget/form/MtpTextItem.java", "mask_start_position": 470, "mask_end_position": 487, "canonical_solution": "pellCheck(false);", "pre_mask_code": "package org.iplass.adminconsole.client.base.ui.widget.form;\n\nimport com.smartgwt.client.widgets.form.fields.TextItem;\n\npublic class MtpTextItem extends TextItem {\n\n public MtpTextItem() {\n init();\n }\n\n public MtpTextItem(String name) {\n super(name);\n init();\n }\n\n public MtpTextItem(String name, String title) {\n super(name, title);\n init();\n }\n\n private void init() {\n setWidth(\"100%\");\n setBrowserS", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2368", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jenkinsci/pipeline-utility-steps-plugin/src/main/java/org/jenkinsci/plugins/pipeline/utility/steps/shaded/org/yaml/snakeyaml/representer/Representer.java", "mask_start_position": 6064, "mask_end_position": 6174, "canonical_solution": "@SuppressWarnings(\"unchecked\")\n protected void checkGlobalTag(Property property, Node node, Object object) ", "pre_mask_code": "package org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer;\n\nimport java.beans.IntrospectionException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.DumperOptions.FlowStyle;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.MappingNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.error.YAMLException;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.introspector.Property;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Node;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeId;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeTuple;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.ScalarNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.SequenceNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Tag;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer.Represent;\n\n/**\n * Represent JavaBeans\n */\npublic class Representer extends SafeRepresenter {\n\n public Representer() {\n this.representers.put(null, new RepresentJavaBean());\n }\n\n protected class RepresentJavaBean implements Represent {\n\n public Node representData(Object data) {\n try {\n return representJavaBean(getProperties(data.getClass()), data);\n } catch (IntrospectionException e) {\n throw new YAMLException(e);\n }\n }\n }\n\n /**\n * Tag logic:\n * - explicit root tag is set in serializer\n * - if there is a predefined class tag it is used\n * - a global tag with class name is always used as tag. The JavaBean parent\n * of the specified JavaBean may set another tag (tag:yaml.org,2002:map)\n * when the property class is the same as runtime class\n *\n * @param properties\n * JavaBean getters\n * @param javaBean\n * instance for Node\n * @return Node to get serialized\n */\n protected MappingNode representJavaBean(Set properties, Object javaBean) {\n List value = new ArrayList(properties.size());\n Tag tag;\n Tag customTag = classTags.get(javaBean.getClass());\n tag = customTag != null ? customTag : new Tag(javaBean.getClass());\n // flow style will be chosen by BaseRepresenter\n MappingNode node = new MappingNode(tag, value, null);\n representedObjects.put(javaBean, node);\n boolean bestStyle = true;\n for (Property property : properties) {\n Object memberValue = property.get(javaBean);\n Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue.getClass());\n NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue, customPropertyTag);\n if (tuple == null) {\n continue;\n }\n if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) {\n bestStyle = false;\n }\n Node nodeValue = tuple.getValueNode();\n if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {\n bestStyle = false;\n }\n value.add(tuple);\n }\n if (defaultFlowStyle != FlowStyle.AUTO) {\n node.setFlowStyle(defaultFlowStyle.getStyleBoolean());\n } else {\n node.setFlowStyle(bestStyle);\n }\n return node;\n }\n\n /**\n * Represent one JavaBean property.\n *\n * @param javaBean\n * - the instance to be represented\n * @param property\n * - the property of the instance\n * @param propertyValue\n * - value to be represented\n * @param customTag\n * - user defined Tag\n * @return NodeTuple to be used in a MappingNode. Return null to skip the\n * property\n */\n protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {\n ScalarNode nodeKey = (ScalarNode) representData(property.getName());\n // the first occurrence of the node must keep the tag\n boolean hasAlias = this.representedObjects.containsKey(propertyValue);\n Node nodeValue = representData(propertyValue);\n if (propertyValue != null && !hasAlias) {\n NodeId nodeId = nodeValue.getNodeId();\n if (customTag == null) {\n if (nodeId == NodeId.scalar) {\n if (propertyValue instanceof Enum) {\n nodeValue.setTag(Tag.STR);\n }\n } else {\n if (nodeId == NodeId.mapping) {\n if (property.getType() == propertyValue.getClass()) {\n if (!(propertyValue instanceof Map)) {\n if (!nodeValue.getTag().equals(Tag.SET)) {\n nodeValue.setTag(Tag.MAP);\n }\n }\n }\n }\n checkGlobalTag(property, nodeValue, propertyValue);\n }\n }\n }\n return new NodeTuple(nodeKey, nodeValue);\n }\n\n /**\n * Remove redundant global tag for a type safe (generic) collection if it is\n * the same as defined by the JavaBean property\n *\n * @param property\n * - JavaBean property\n * @param node\n * - representation of the property\n * @param object\n * - instance represented by the node\n */\n ", "post_mask_code": "{\n // Skip primitive arrays.\n if (object.getClass().isArray() && object.getClass().getComponentType().isPrimitive()) {\n return;\n }\n Class[] arguments = property.getActualTypeArguments();\n if (arguments != null) {\n if (node.getNodeId() == NodeId.sequence) {\n // apply map tag where class is the same\n Class t = arguments[0];\n SequenceNode snode = (SequenceNode) node;\n Iterable memberList = Collections.EMPTY_LIST;\n if (object.getClass().isArray()) {\n memberList = Arrays.asList((Object[]) object);\n } else if (object instanceof Iterable) {\n // list\n memberList = (Iterable) object;\n }\n Iterator iter = memberList.iterator();\n if (iter.hasNext()) {\n for (Node childNode : snode.getValue()) {\n Object member = iter.next();\n if (member != null) {\n if (t.equals(member.getClass()))\n if (childNode.getNodeId() == NodeId.mapping) {\n childNode.setTag(Tag.MAP);\n }\n }\n }\n }\n } else if (object instanceof Set) {\n Class t = arguments[0];\n MappingNode mnode = (MappingNode) node;\n Iterator iter = mnode.getValue().iterator();\n Set set = (Set) object;\n for (Object member : set) {\n NodeTuple tuple = iter.next();\n Node keyNode = tuple.getKeyNode();\n if (t.equals(member.getClass())) {\n if (keyNode.getNodeId() == NodeId.mapping) {\n keyNode.setTag(Tag.MAP);\n }\n }\n }\n } else if (object instanceof Map) {\n Class keyType = arguments[0];\n Class valueType = arguments[1];\n MappingNode mnode = (MappingNode) node;\n for (NodeTuple tuple : mnode.getValue()) {\n resetTag(keyType, tuple.getKeyNode());\n resetTag(valueType, tuple.getValueNode());\n }\n } else {\n // the type for collection entries cannot be\n // detected\n }\n }\n }\n\n private void resetTag(Class type, Node node) {\n Tag tag = node.getTag();\n if (tag.matches(type)) {\n if (Enum.class.isAssignableFrom(type)) {\n node.setTag(Tag.STR);\n } else {\n node.setTag(Tag.MAP);\n }\n }\n }\n\n /**\n * Get JavaBean properties to be serialised. The order is respected. This\n * method may be overridden to provide custom property selection or order.\n *\n * @param type\n * - JavaBean to inspect the properties\n * @return properties to serialise\n */\n protected Set getProperties(Class type) throws IntrospectionException {\n return getPropertyUtils().getProperties(type);\n }\n}\n"} {"task_id": "Java_2369", "language": "Java", "task_type": "method_body", "source_file": "java/github/jenkinsci/pipeline-utility-steps-plugin/src/main/java/org/jenkinsci/plugins/pipeline/utility/steps/shaded/org/yaml/snakeyaml/representer/Representer.java", "mask_start_position": 1662, "mask_end_position": 1878, "canonical_solution": "{\n try {\n return representJavaBean(getProperties(data.getClass()), data);\n } catch (IntrospectionException e) {\n throw new YAMLException(e);\n }\n }", "pre_mask_code": "package org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer;\n\nimport java.beans.IntrospectionException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.DumperOptions.FlowStyle;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.MappingNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.error.YAMLException;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.introspector.Property;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Node;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeId;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeTuple;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.ScalarNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.SequenceNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Tag;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer.Represent;\n\n/**\n * Represent JavaBeans\n */\npublic class Representer extends SafeRepresenter {\n\n public Representer() {\n this.representers.put(null, new RepresentJavaBean());\n }\n\n protected class RepresentJavaBean implements Represent {\n\n public Node representData(Object data) ", "post_mask_code": "\n }\n\n /**\n * Tag logic:\n * - explicit root tag is set in serializer\n * - if there is a predefined class tag it is used\n * - a global tag with class name is always used as tag. The JavaBean parent\n * of the specified JavaBean may set another tag (tag:yaml.org,2002:map)\n * when the property class is the same as runtime class\n *\n * @param properties\n * JavaBean getters\n * @param javaBean\n * instance for Node\n * @return Node to get serialized\n */\n protected MappingNode representJavaBean(Set properties, Object javaBean) {\n List value = new ArrayList(properties.size());\n Tag tag;\n Tag customTag = classTags.get(javaBean.getClass());\n tag = customTag != null ? customTag : new Tag(javaBean.getClass());\n // flow style will be chosen by BaseRepresenter\n MappingNode node = new MappingNode(tag, value, null);\n representedObjects.put(javaBean, node);\n boolean bestStyle = true;\n for (Property property : properties) {\n Object memberValue = property.get(javaBean);\n Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue.getClass());\n NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue, customPropertyTag);\n if (tuple == null) {\n continue;\n }\n if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) {\n bestStyle = false;\n }\n Node nodeValue = tuple.getValueNode();\n if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {\n bestStyle = false;\n }\n value.add(tuple);\n }\n if (defaultFlowStyle != FlowStyle.AUTO) {\n node.setFlowStyle(defaultFlowStyle.getStyleBoolean());\n } else {\n node.setFlowStyle(bestStyle);\n }\n return node;\n }\n\n /**\n * Represent one JavaBean property.\n *\n * @param javaBean\n * - the instance to be represented\n * @param property\n * - the property of the instance\n * @param propertyValue\n * - value to be represented\n * @param customTag\n * - user defined Tag\n * @return NodeTuple to be used in a MappingNode. Return null to skip the\n * property\n */\n protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {\n ScalarNode nodeKey = (ScalarNode) representData(property.getName());\n // the first occurrence of the node must keep the tag\n boolean hasAlias = this.representedObjects.containsKey(propertyValue);\n Node nodeValue = representData(propertyValue);\n if (propertyValue != null && !hasAlias) {\n NodeId nodeId = nodeValue.getNodeId();\n if (customTag == null) {\n if (nodeId == NodeId.scalar) {\n if (propertyValue instanceof Enum) {\n nodeValue.setTag(Tag.STR);\n }\n } else {\n if (nodeId == NodeId.mapping) {\n if (property.getType() == propertyValue.getClass()) {\n if (!(propertyValue instanceof Map)) {\n if (!nodeValue.getTag().equals(Tag.SET)) {\n nodeValue.setTag(Tag.MAP);\n }\n }\n }\n }\n checkGlobalTag(property, nodeValue, propertyValue);\n }\n }\n }\n return new NodeTuple(nodeKey, nodeValue);\n }\n\n /**\n * Remove redundant global tag for a type safe (generic) collection if it is\n * the same as defined by the JavaBean property\n *\n * @param property\n * - JavaBean property\n * @param node\n * - representation of the property\n * @param object\n * - instance represented by the node\n */\n @SuppressWarnings(\"unchecked\")\n protected void checkGlobalTag(Property property, Node node, Object object) {\n // Skip primitive arrays.\n if (object.getClass().isArray() && object.getClass().getComponentType().isPrimitive()) {\n return;\n }\n Class[] arguments = property.getActualTypeArguments();\n if (arguments != null) {\n if (node.getNodeId() == NodeId.sequence) {\n // apply map tag where class is the same\n Class t = arguments[0];\n SequenceNode snode = (SequenceNode) node;\n Iterable memberList = Collections.EMPTY_LIST;\n if (object.getClass().isArray()) {\n memberList = Arrays.asList((Object[]) object);\n } else if (object instanceof Iterable) {\n // list\n memberList = (Iterable) object;\n }\n Iterator iter = memberList.iterator();\n if (iter.hasNext()) {\n for (Node childNode : snode.getValue()) {\n Object member = iter.next();\n if (member != null) {\n if (t.equals(member.getClass()))\n if (childNode.getNodeId() == NodeId.mapping) {\n childNode.setTag(Tag.MAP);\n }\n }\n }\n }\n } else if (object instanceof Set) {\n Class t = arguments[0];\n MappingNode mnode = (MappingNode) node;\n Iterator iter = mnode.getValue().iterator();\n Set set = (Set) object;\n for (Object member : set) {\n NodeTuple tuple = iter.next();\n Node keyNode = tuple.getKeyNode();\n if (t.equals(member.getClass())) {\n if (keyNode.getNodeId() == NodeId.mapping) {\n keyNode.setTag(Tag.MAP);\n }\n }\n }\n } else if (object instanceof Map) {\n Class keyType = arguments[0];\n Class valueType = arguments[1];\n MappingNode mnode = (MappingNode) node;\n for (NodeTuple tuple : mnode.getValue()) {\n resetTag(keyType, tuple.getKeyNode());\n resetTag(valueType, tuple.getValueNode());\n }\n } else {\n // the type for collection entries cannot be\n // detected\n }\n }\n }\n\n private void resetTag(Class type, Node node) {\n Tag tag = node.getTag();\n if (tag.matches(type)) {\n if (Enum.class.isAssignableFrom(type)) {\n node.setTag(Tag.STR);\n } else {\n node.setTag(Tag.MAP);\n }\n }\n }\n\n /**\n * Get JavaBean properties to be serialised. The order is respected. This\n * method may be overridden to provide custom property selection or order.\n *\n * @param type\n * - JavaBean to inspect the properties\n * @return properties to serialise\n */\n protected Set getProperties(Class type) throws IntrospectionException {\n return getPropertyUtils().getProperties(type);\n }\n}\n"} {"task_id": "Java_2370", "language": "Java", "task_type": "single_line", "source_file": "java/github/jenkinsci/pipeline-utility-steps-plugin/src/main/java/org/jenkinsci/plugins/pipeline/utility/steps/shaded/org/yaml/snakeyaml/representer/Representer.java", "mask_start_position": 6384, "mask_end_position": 6402, "canonical_solution": "alTypeArguments();", "pre_mask_code": "package org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer;\n\nimport java.beans.IntrospectionException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.DumperOptions.FlowStyle;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.MappingNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.error.YAMLException;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.introspector.Property;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Node;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeId;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeTuple;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.ScalarNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.SequenceNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Tag;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer.Represent;\n\n/**\n * Represent JavaBeans\n */\npublic class Representer extends SafeRepresenter {\n\n public Representer() {\n this.representers.put(null, new RepresentJavaBean());\n }\n\n protected class RepresentJavaBean implements Represent {\n\n public Node representData(Object data) {\n try {\n return representJavaBean(getProperties(data.getClass()), data);\n } catch (IntrospectionException e) {\n throw new YAMLException(e);\n }\n }\n }\n\n /**\n * Tag logic:\n * - explicit root tag is set in serializer\n * - if there is a predefined class tag it is used\n * - a global tag with class name is always used as tag. The JavaBean parent\n * of the specified JavaBean may set another tag (tag:yaml.org,2002:map)\n * when the property class is the same as runtime class\n *\n * @param properties\n * JavaBean getters\n * @param javaBean\n * instance for Node\n * @return Node to get serialized\n */\n protected MappingNode representJavaBean(Set properties, Object javaBean) {\n List value = new ArrayList(properties.size());\n Tag tag;\n Tag customTag = classTags.get(javaBean.getClass());\n tag = customTag != null ? customTag : new Tag(javaBean.getClass());\n // flow style will be chosen by BaseRepresenter\n MappingNode node = new MappingNode(tag, value, null);\n representedObjects.put(javaBean, node);\n boolean bestStyle = true;\n for (Property property : properties) {\n Object memberValue = property.get(javaBean);\n Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue.getClass());\n NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue, customPropertyTag);\n if (tuple == null) {\n continue;\n }\n if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) {\n bestStyle = false;\n }\n Node nodeValue = tuple.getValueNode();\n if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {\n bestStyle = false;\n }\n value.add(tuple);\n }\n if (defaultFlowStyle != FlowStyle.AUTO) {\n node.setFlowStyle(defaultFlowStyle.getStyleBoolean());\n } else {\n node.setFlowStyle(bestStyle);\n }\n return node;\n }\n\n /**\n * Represent one JavaBean property.\n *\n * @param javaBean\n * - the instance to be represented\n * @param property\n * - the property of the instance\n * @param propertyValue\n * - value to be represented\n * @param customTag\n * - user defined Tag\n * @return NodeTuple to be used in a MappingNode. Return null to skip the\n * property\n */\n protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {\n ScalarNode nodeKey = (ScalarNode) representData(property.getName());\n // the first occurrence of the node must keep the tag\n boolean hasAlias = this.representedObjects.containsKey(propertyValue);\n Node nodeValue = representData(propertyValue);\n if (propertyValue != null && !hasAlias) {\n NodeId nodeId = nodeValue.getNodeId();\n if (customTag == null) {\n if (nodeId == NodeId.scalar) {\n if (propertyValue instanceof Enum) {\n nodeValue.setTag(Tag.STR);\n }\n } else {\n if (nodeId == NodeId.mapping) {\n if (property.getType() == propertyValue.getClass()) {\n if (!(propertyValue instanceof Map)) {\n if (!nodeValue.getTag().equals(Tag.SET)) {\n nodeValue.setTag(Tag.MAP);\n }\n }\n }\n }\n checkGlobalTag(property, nodeValue, propertyValue);\n }\n }\n }\n return new NodeTuple(nodeKey, nodeValue);\n }\n\n /**\n * Remove redundant global tag for a type safe (generic) collection if it is\n * the same as defined by the JavaBean property\n *\n * @param property\n * - JavaBean property\n * @param node\n * - representation of the property\n * @param object\n * - instance represented by the node\n */\n @SuppressWarnings(\"unchecked\")\n protected void checkGlobalTag(Property property, Node node, Object object) {\n // Skip primitive arrays.\n if (object.getClass().isArray() && object.getClass().getComponentType().isPrimitive()) {\n return;\n }\n Class[] arguments = property.getActu", "post_mask_code": "\n if (arguments != null) {\n if (node.getNodeId() == NodeId.sequence) {\n // apply map tag where class is the same\n Class t = arguments[0];\n SequenceNode snode = (SequenceNode) node;\n Iterable memberList = Collections.EMPTY_LIST;\n if (object.getClass().isArray()) {\n memberList = Arrays.asList((Object[]) object);\n } else if (object instanceof Iterable) {\n // list\n memberList = (Iterable) object;\n }\n Iterator iter = memberList.iterator();\n if (iter.hasNext()) {\n for (Node childNode : snode.getValue()) {\n Object member = iter.next();\n if (member != null) {\n if (t.equals(member.getClass()))\n if (childNode.getNodeId() == NodeId.mapping) {\n childNode.setTag(Tag.MAP);\n }\n }\n }\n }\n } else if (object instanceof Set) {\n Class t = arguments[0];\n MappingNode mnode = (MappingNode) node;\n Iterator iter = mnode.getValue().iterator();\n Set set = (Set) object;\n for (Object member : set) {\n NodeTuple tuple = iter.next();\n Node keyNode = tuple.getKeyNode();\n if (t.equals(member.getClass())) {\n if (keyNode.getNodeId() == NodeId.mapping) {\n keyNode.setTag(Tag.MAP);\n }\n }\n }\n } else if (object instanceof Map) {\n Class keyType = arguments[0];\n Class valueType = arguments[1];\n MappingNode mnode = (MappingNode) node;\n for (NodeTuple tuple : mnode.getValue()) {\n resetTag(keyType, tuple.getKeyNode());\n resetTag(valueType, tuple.getValueNode());\n }\n } else {\n // the type for collection entries cannot be\n // detected\n }\n }\n }\n\n private void resetTag(Class type, Node node) {\n Tag tag = node.getTag();\n if (tag.matches(type)) {\n if (Enum.class.isAssignableFrom(type)) {\n node.setTag(Tag.STR);\n } else {\n node.setTag(Tag.MAP);\n }\n }\n }\n\n /**\n * Get JavaBean properties to be serialised. The order is respected. This\n * method may be overridden to provide custom property selection or order.\n *\n * @param type\n * - JavaBean to inspect the properties\n * @return properties to serialise\n */\n protected Set getProperties(Class type) throws IntrospectionException {\n return getPropertyUtils().getProperties(type);\n }\n}\n"} {"task_id": "Java_2371", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/jenkinsci/pipeline-utility-steps-plugin/src/main/java/org/jenkinsci/plugins/pipeline/utility/steps/shaded/org/yaml/snakeyaml/representer/Representer.java", "mask_start_position": 9398, "mask_end_position": 9558, "canonical_solution": "protected Set getProperties(Class type) throws IntrospectionException {\n return getPropertyUtils().getProperties(type);\n }", "pre_mask_code": "package org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer;\n\nimport java.beans.IntrospectionException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.DumperOptions.FlowStyle;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.MappingNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.error.YAMLException;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.introspector.Property;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Node;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeId;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeTuple;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.ScalarNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.SequenceNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Tag;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer.Represent;\n\n/**\n * Represent JavaBeans\n */\npublic class Representer extends SafeRepresenter {\n\n public Representer() {\n this.representers.put(null, new RepresentJavaBean());\n }\n\n protected class RepresentJavaBean implements Represent {\n\n public Node representData(Object data) {\n try {\n return representJavaBean(getProperties(data.getClass()), data);\n } catch (IntrospectionException e) {\n throw new YAMLException(e);\n }\n }\n }\n\n /**\n * Tag logic:\n * - explicit root tag is set in serializer\n * - if there is a predefined class tag it is used\n * - a global tag with class name is always used as tag. The JavaBean parent\n * of the specified JavaBean may set another tag (tag:yaml.org,2002:map)\n * when the property class is the same as runtime class\n *\n * @param properties\n * JavaBean getters\n * @param javaBean\n * instance for Node\n * @return Node to get serialized\n */\n protected MappingNode representJavaBean(Set properties, Object javaBean) {\n List value = new ArrayList(properties.size());\n Tag tag;\n Tag customTag = classTags.get(javaBean.getClass());\n tag = customTag != null ? customTag : new Tag(javaBean.getClass());\n // flow style will be chosen by BaseRepresenter\n MappingNode node = new MappingNode(tag, value, null);\n representedObjects.put(javaBean, node);\n boolean bestStyle = true;\n for (Property property : properties) {\n Object memberValue = property.get(javaBean);\n Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue.getClass());\n NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue, customPropertyTag);\n if (tuple == null) {\n continue;\n }\n if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) {\n bestStyle = false;\n }\n Node nodeValue = tuple.getValueNode();\n if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {\n bestStyle = false;\n }\n value.add(tuple);\n }\n if (defaultFlowStyle != FlowStyle.AUTO) {\n node.setFlowStyle(defaultFlowStyle.getStyleBoolean());\n } else {\n node.setFlowStyle(bestStyle);\n }\n return node;\n }\n\n /**\n * Represent one JavaBean property.\n *\n * @param javaBean\n * - the instance to be represented\n * @param property\n * - the property of the instance\n * @param propertyValue\n * - value to be represented\n * @param customTag\n * - user defined Tag\n * @return NodeTuple to be used in a MappingNode. Return null to skip the\n * property\n */\n protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {\n ScalarNode nodeKey = (ScalarNode) representData(property.getName());\n // the first occurrence of the node must keep the tag\n boolean hasAlias = this.representedObjects.containsKey(propertyValue);\n Node nodeValue = representData(propertyValue);\n if (propertyValue != null && !hasAlias) {\n NodeId nodeId = nodeValue.getNodeId();\n if (customTag == null) {\n if (nodeId == NodeId.scalar) {\n if (propertyValue instanceof Enum) {\n nodeValue.setTag(Tag.STR);\n }\n } else {\n if (nodeId == NodeId.mapping) {\n if (property.getType() == propertyValue.getClass()) {\n if (!(propertyValue instanceof Map)) {\n if (!nodeValue.getTag().equals(Tag.SET)) {\n nodeValue.setTag(Tag.MAP);\n }\n }\n }\n }\n checkGlobalTag(property, nodeValue, propertyValue);\n }\n }\n }\n return new NodeTuple(nodeKey, nodeValue);\n }\n\n /**\n * Remove redundant global tag for a type safe (generic) collection if it is\n * the same as defined by the JavaBean property\n *\n * @param property\n * - JavaBean property\n * @param node\n * - representation of the property\n * @param object\n * - instance represented by the node\n */\n @SuppressWarnings(\"unchecked\")\n protected void checkGlobalTag(Property property, Node node, Object object) {\n // Skip primitive arrays.\n if (object.getClass().isArray() && object.getClass().getComponentType().isPrimitive()) {\n return;\n }\n Class[] arguments = property.getActualTypeArguments();\n if (arguments != null) {\n if (node.getNodeId() == NodeId.sequence) {\n // apply map tag where class is the same\n Class t = arguments[0];\n SequenceNode snode = (SequenceNode) node;\n Iterable memberList = Collections.EMPTY_LIST;\n if (object.getClass().isArray()) {\n memberList = Arrays.asList((Object[]) object);\n } else if (object instanceof Iterable) {\n // list\n memberList = (Iterable) object;\n }\n Iterator iter = memberList.iterator();\n if (iter.hasNext()) {\n for (Node childNode : snode.getValue()) {\n Object member = iter.next();\n if (member != null) {\n if (t.equals(member.getClass()))\n if (childNode.getNodeId() == NodeId.mapping) {\n childNode.setTag(Tag.MAP);\n }\n }\n }\n }\n } else if (object instanceof Set) {\n Class t = arguments[0];\n MappingNode mnode = (MappingNode) node;\n Iterator iter = mnode.getValue().iterator();\n Set set = (Set) object;\n for (Object member : set) {\n NodeTuple tuple = iter.next();\n Node keyNode = tuple.getKeyNode();\n if (t.equals(member.getClass())) {\n if (keyNode.getNodeId() == NodeId.mapping) {\n keyNode.setTag(Tag.MAP);\n }\n }\n }\n } else if (object instanceof Map) {\n Class keyType = arguments[0];\n Class valueType = arguments[1];\n MappingNode mnode = (MappingNode) node;\n for (NodeTuple tuple : mnode.getValue()) {\n resetTag(keyType, tuple.getKeyNode());\n resetTag(valueType, tuple.getValueNode());\n }\n } else {\n // the type for collection entries cannot be\n // detected\n }\n }\n }\n\n private void resetTag(Class type, Node node) {\n Tag tag = node.getTag();\n if (tag.matches(type)) {\n if (Enum.class.isAssignableFrom(type)) {\n node.setTag(Tag.STR);\n } else {\n node.setTag(Tag.MAP);\n }\n }\n }\n\n /**\n * Get JavaBean properties to be serialised. The order is respected. This\n * method may be overridden to provide custom property selection or order.\n *\n * @param type\n * - JavaBean to inspect the properties\n * @return properties to serialise\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2372", "language": "Java", "task_type": "try_statement", "source_file": "java/github/jenkinsci/pipeline-utility-steps-plugin/src/main/java/org/jenkinsci/plugins/pipeline/utility/steps/shaded/org/yaml/snakeyaml/representer/Representer.java", "mask_start_position": 1676, "mask_end_position": 1868, "canonical_solution": "try {\n return representJavaBean(getProperties(data.getClass()), data);\n } catch (IntrospectionException e) {\n throw new YAMLException(e);\n }", "pre_mask_code": "package org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer;\n\nimport java.beans.IntrospectionException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.DumperOptions.FlowStyle;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.MappingNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.error.YAMLException;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.introspector.Property;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Node;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeId;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeTuple;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.ScalarNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.SequenceNode;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Tag;\nimport org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer.Represent;\n\n/**\n * Represent JavaBeans\n */\npublic class Representer extends SafeRepresenter {\n\n public Representer() {\n this.representers.put(null, new RepresentJavaBean());\n }\n\n protected class RepresentJavaBean implements Represent {\n\n public Node representData(Object data) {\n ", "post_mask_code": "\n }\n }\n\n /**\n * Tag logic:\n * - explicit root tag is set in serializer\n * - if there is a predefined class tag it is used\n * - a global tag with class name is always used as tag. The JavaBean parent\n * of the specified JavaBean may set another tag (tag:yaml.org,2002:map)\n * when the property class is the same as runtime class\n *\n * @param properties\n * JavaBean getters\n * @param javaBean\n * instance for Node\n * @return Node to get serialized\n */\n protected MappingNode representJavaBean(Set properties, Object javaBean) {\n List value = new ArrayList(properties.size());\n Tag tag;\n Tag customTag = classTags.get(javaBean.getClass());\n tag = customTag != null ? customTag : new Tag(javaBean.getClass());\n // flow style will be chosen by BaseRepresenter\n MappingNode node = new MappingNode(tag, value, null);\n representedObjects.put(javaBean, node);\n boolean bestStyle = true;\n for (Property property : properties) {\n Object memberValue = property.get(javaBean);\n Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue.getClass());\n NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue, customPropertyTag);\n if (tuple == null) {\n continue;\n }\n if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) {\n bestStyle = false;\n }\n Node nodeValue = tuple.getValueNode();\n if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {\n bestStyle = false;\n }\n value.add(tuple);\n }\n if (defaultFlowStyle != FlowStyle.AUTO) {\n node.setFlowStyle(defaultFlowStyle.getStyleBoolean());\n } else {\n node.setFlowStyle(bestStyle);\n }\n return node;\n }\n\n /**\n * Represent one JavaBean property.\n *\n * @param javaBean\n * - the instance to be represented\n * @param property\n * - the property of the instance\n * @param propertyValue\n * - value to be represented\n * @param customTag\n * - user defined Tag\n * @return NodeTuple to be used in a MappingNode. Return null to skip the\n * property\n */\n protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {\n ScalarNode nodeKey = (ScalarNode) representData(property.getName());\n // the first occurrence of the node must keep the tag\n boolean hasAlias = this.representedObjects.containsKey(propertyValue);\n Node nodeValue = representData(propertyValue);\n if (propertyValue != null && !hasAlias) {\n NodeId nodeId = nodeValue.getNodeId();\n if (customTag == null) {\n if (nodeId == NodeId.scalar) {\n if (propertyValue instanceof Enum) {\n nodeValue.setTag(Tag.STR);\n }\n } else {\n if (nodeId == NodeId.mapping) {\n if (property.getType() == propertyValue.getClass()) {\n if (!(propertyValue instanceof Map)) {\n if (!nodeValue.getTag().equals(Tag.SET)) {\n nodeValue.setTag(Tag.MAP);\n }\n }\n }\n }\n checkGlobalTag(property, nodeValue, propertyValue);\n }\n }\n }\n return new NodeTuple(nodeKey, nodeValue);\n }\n\n /**\n * Remove redundant global tag for a type safe (generic) collection if it is\n * the same as defined by the JavaBean property\n *\n * @param property\n * - JavaBean property\n * @param node\n * - representation of the property\n * @param object\n * - instance represented by the node\n */\n @SuppressWarnings(\"unchecked\")\n protected void checkGlobalTag(Property property, Node node, Object object) {\n // Skip primitive arrays.\n if (object.getClass().isArray() && object.getClass().getComponentType().isPrimitive()) {\n return;\n }\n Class[] arguments = property.getActualTypeArguments();\n if (arguments != null) {\n if (node.getNodeId() == NodeId.sequence) {\n // apply map tag where class is the same\n Class t = arguments[0];\n SequenceNode snode = (SequenceNode) node;\n Iterable memberList = Collections.EMPTY_LIST;\n if (object.getClass().isArray()) {\n memberList = Arrays.asList((Object[]) object);\n } else if (object instanceof Iterable) {\n // list\n memberList = (Iterable) object;\n }\n Iterator iter = memberList.iterator();\n if (iter.hasNext()) {\n for (Node childNode : snode.getValue()) {\n Object member = iter.next();\n if (member != null) {\n if (t.equals(member.getClass()))\n if (childNode.getNodeId() == NodeId.mapping) {\n childNode.setTag(Tag.MAP);\n }\n }\n }\n }\n } else if (object instanceof Set) {\n Class t = arguments[0];\n MappingNode mnode = (MappingNode) node;\n Iterator iter = mnode.getValue().iterator();\n Set set = (Set) object;\n for (Object member : set) {\n NodeTuple tuple = iter.next();\n Node keyNode = tuple.getKeyNode();\n if (t.equals(member.getClass())) {\n if (keyNode.getNodeId() == NodeId.mapping) {\n keyNode.setTag(Tag.MAP);\n }\n }\n }\n } else if (object instanceof Map) {\n Class keyType = arguments[0];\n Class valueType = arguments[1];\n MappingNode mnode = (MappingNode) node;\n for (NodeTuple tuple : mnode.getValue()) {\n resetTag(keyType, tuple.getKeyNode());\n resetTag(valueType, tuple.getValueNode());\n }\n } else {\n // the type for collection entries cannot be\n // detected\n }\n }\n }\n\n private void resetTag(Class type, Node node) {\n Tag tag = node.getTag();\n if (tag.matches(type)) {\n if (Enum.class.isAssignableFrom(type)) {\n node.setTag(Tag.STR);\n } else {\n node.setTag(Tag.MAP);\n }\n }\n }\n\n /**\n * Get JavaBean properties to be serialised. The order is respected. This\n * method may be overridden to provide custom property selection or order.\n *\n * @param type\n * - JavaBean to inspect the properties\n * @return properties to serialise\n */\n protected Set getProperties(Class type) throws IntrospectionException {\n return getPropertyUtils().getProperties(type);\n }\n}\n"} {"task_id": "Java_2373", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/makersoft/mybatis-shards/src/main/java/org/makersoft/shards/cfg/ShardConfiguration.java", "mask_start_position": 402, "mask_end_position": 423, "canonical_solution": "Integer getShardId();", "pre_mask_code": "package org.makersoft.shards.cfg;\n\nimport java.util.List;\nimport javax.sql.DataSource;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.makersoft.shards.ShardId;\n\n/**\n * 用于描述分区的配置信息,不同的物理分区可包含不同的{@link SqlSessionFactory}和多个逻辑分区{@link ShardId}\n *\n * @version 2012-8-1 下午10:00:00\n * @author Feng Kuok\n */\npublic interface ShardConfiguration {\n\n /**\n * @return 此物理分区的唯一ID\n */\n ", "post_mask_code": "\n\n List getShardIds();\n\n DataSource getShardDataSource();\n\n /**\n * @see SqlSessionFactory\n * @return 此物理分区的{@link SqlSessionFactory}\n */\n SqlSessionFactory getSqlSessionFactory();\n // * @return locations of MyBatis mapper files\n}\n"} {"task_id": "Java_2374", "language": "Java", "task_type": "method_signature", "source_file": "java/github/dotCMS/core/dotCMS/src/main/java/com/dotmarketing/portlets/dashboard/business/DashboardFactory.java", "mask_start_position": 13905, "mask_end_position": 13985, "canonical_solution": "protected String getHostQueryForClickstream(String runDashboardFieldContentlet) ", "pre_mask_code": "package com.dotmarketing.portlets.dashboard.business;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport com.dotmarketing.beans.Host;\nimport com.dotmarketing.beans.Inode;\nimport com.dotmarketing.db.DbConnectionFactory;\nimport com.dotmarketing.exception.DotDataException;\nimport com.dotmarketing.exception.DotHibernateException;\nimport com.dotmarketing.exception.DotSecurityException;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummary;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummary404;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryContent;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryPage;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryReferer;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryVisits;\nimport com.dotmarketing.portlets.dashboard.model.DashboardWorkStream;\nimport com.dotmarketing.portlets.dashboard.model.TopAsset;\nimport com.dotmarketing.portlets.dashboard.model.ViewType;\nimport com.dotmarketing.portlets.structure.model.Structure;\nimport com.dotmarketing.util.UtilMethods;\nimport com.liferay.portal.model.User;\n\npublic abstract class DashboardFactory {\n\n protected String getSummaryPagesQuery() {\n StringBuilder queryBuilder = new StringBuilder(\"\");\n if (DbConnectionFactory.isPostgres() || DbConnectionFactory.isOracle()) {\n // Find contentlets type 'html page'\n queryBuilder.append(\"SELECT COUNT(*) AS hits, contentlet_version_info.live_inode AS inode, \").append(\"(identifier.parent_path || identifier.asset_name) AS uri \").append(\"FROM clickstream_request cr \").append(\"JOIN contentlet ON (contentlet.identifier = cr.associated_identifier) \").append(\"JOIN structure ON (structure.inode = contentlet.structure_inode) \").append(\"JOIN identifier ON (identifier.id = contentlet.identifier) \").append(\"JOIN contentlet_version_info ON (contentlet_version_info.identifier = identifier.id) \").append(\"WHERE EXTRACT(DAY FROM cr.timestampper) = ? AND EXTRACT(MONTH FROM cr.timestampper) = ? AND EXTRACT(YEAR FROM cr.timestampper) = ? \").append(\"AND cr.host_id = ? AND structure.structuretype = \").append(Structure.STRUCTURE_TYPE_HTMLPAGE).append(\" \").append(\"GROUP BY associated_identifier, (identifier.parent_path || identifier.asset_name), contentlet_version_info.live_inode\");\n } else if (DbConnectionFactory.isMySql()) {\n // MySQL Query Builder\n // Find contentlets type 'html page'\n queryBuilder.append(\"SELECT COUNT(*) AS hits, contentlet_version_info.live_inode AS inode, \").append(\"CONCAT(identifier.parent_path, identifier.asset_name) AS uri \").append(\"FROM clickstream_request cr \").append(\"JOIN contentlet ON (contentlet.identifier = cr.associated_identifier) \").append(\"JOIN structure ON (structure.inode = contentlet.structure_inode) \").append(\"JOIN identifier ON (identifier.id = contentlet.identifier) \").append(\"JOIN contentlet_version_info ON (contentlet_version_info.identifier = identifier.id) \").append(\"WHERE DAY(cr.timestampper) = ? AND MONTH(cr.timestampper) = ? AND YEAR(cr.timestampper) = ? \").append(\"AND cr.host_id = ? AND structure.structuretype = \").append(Structure.STRUCTURE_TYPE_HTMLPAGE).append(\" \").append(\"GROUP BY associated_identifier, CONCAT(identifier.parent_path, identifier.asset_name), contentlet_version_info.live_inode\");\n } else if (DbConnectionFactory.isMsSql()) {\n // MsSQL Query Builder\n // Find contentlets type 'html page'\n queryBuilder.append(\"SELECT COUNT(*) AS hits, contentlet_version_info.live_inode AS inode, \").append(\"(identifier.parent_path + identifier.asset_name) AS uri \").append(\"FROM clickstream_request cr \").append(\"JOIN contentlet ON (contentlet.identifier = cr.associated_identifier) \").append(\"JOIN structure ON (structure.inode = contentlet.structure_inode) \").append(\"JOIN identifier ON (identifier.id = contentlet.identifier) \").append(\"JOIN contentlet_version_info ON (contentlet_version_info.identifier = identifier.id) \").append(\"WHERE DATEPART(DAY, cr.timestampper) = ? AND DATEPART(MONTH, cr.timestampper) = ? AND DATEPART(YEAR, cr.timestampper) = ? \").append(\"AND cr.host_id = ? AND structure.structuretype = \").append(Structure.STRUCTURE_TYPE_HTMLPAGE).append(\" \").append(\"GROUP BY associated_identifier, (identifier.parent_path + identifier.asset_name), contentlet_version_info.live_inode\");\n }\n return queryBuilder.toString();\n }\n\n protected String getSummaryContentQuery() {\n return (DbConnectionFactory.isPostgres() || DbConnectionFactory.isOracle()) ? \" select count(*) as hits, identifier.parent_path as uri ,contentlet.identifier as inode, contentlet.title as title from clickstream_request \" + \" join identifier on identifier.id = associated_identifier join multi_tree on associated_identifier = parent1 join contentlet on contentlet.identifier = multi_tree.child \" + \" where extract(day from timestampper) = ? and extract(month from timestampper) = ? and \" + \" extract(year from timestampper) = ? and host_id = ?\" + \" group by associated_identifier, identifier.parent_path,contentlet.identifier,contentlet.title \" : DbConnectionFactory.isMySql() ? \" select count(*) as hits, identifier.parent_path as uri ,contentlet.identifier as inode, contentlet.title as title from clickstream_request \" + \" join identifier on identifier.id = associated_identifier join multi_tree on associated_identifier = parent1 join contentlet on contentlet.identifier = multi_tree.child \" + \" where DAY(timestampper) = ? and MONTH(timestampper) = ? and YEAR(timestampper) = ? \" + \" and host_id = ? group by associated_identifier, identifier.parent_path,contentlet.identifier,contentlet.title \" : DbConnectionFactory.isMsSql() ? \" select count(*) as hits, identifier.parent_path as uri ,contentlet.identifier as inode, contentlet.title as title from clickstream_request \" + \" join identifier on identifier.id = associated_identifier join multi_tree on associated_identifier = parent1 join contentlet on contentlet.identifier = multi_tree.child \" + \" where DATEPART(day, timestampper) = ? and DATEPART(month, timestampper) = ? and DATEPART(year, timestampper) = ? \" + \" and host_id = ? group by associated_identifier, identifier.parent_path,contentlet.identifier,contentlet.title \" : \"\";\n }\n\n protected String getWorkstreamQuery(String hostId) {\n return \" inode, asset_type, mod_user_id, host_id, mod_date,case when deleted = 1 then 'Deleted' else case when live_inode IS NOT NULL then 'Published' else 'Saved' end end as action, name from( \" + \" select contentlet.inode as inode, case when st.structuretype=\" + Structure.STRUCTURE_TYPE_FILEASSET + \" then 'contentlet' else 'file_asset' end as asset_type, \" + \" mod_user as mod_user_id, identifier.host_inode as host_id, contentlet.mod_date,lang_info.live_inode,lang_info.working_inode,lang_info.deleted, coalesce(contentlet.title,contentlet.identifier) as name \" + \" from contentlet_version_info lang_info join contentlet on (contentlet.identifier = lang_info.identifier) join identifier identifier on (identifier.id = contentlet.identifier) \" + \" join structure st on (contentlet.structure_inode=st.inode) \" + \" UNION ALL \" + \" select template.inode as inode, 'template' as asset_type, mod_user as mod_user_id, identifier.host_inode as host_id, mod_date, temp_info.live_inode,temp_info.working_inode,temp_info.deleted, coalesce(template.title,template.identifier) as name \" + \" from template_version_info temp_info join template on(template.identifier = temp_info.identifier) join identifier identifier on identifier.id = template.identifier \" + \" UNION ALL \" + \" select \" + Inode.Type.CONTAINERS.getTableName() + \".inode as inode, 'container' as asset_type, mod_user as mod_user_id, identifier.host_inode as host_id, mod_date, con_info.live_inode,con_info.working_inode,con_info.deleted, coalesce(\" + Inode.Type.CONTAINERS.getTableName() + \".title,\" + Inode.Type.CONTAINERS.getTableName() + \".identifier) as name \" + \" from container_version_info con_info join \" + Inode.Type.CONTAINERS.getTableName() + \" on(\" + Inode.Type.CONTAINERS.getTableName() + \".identifier = con_info.identifier) join identifier identifier on (identifier.id = \" + Inode.Type.CONTAINERS.getTableName() + \".identifier) \" + \" UNION ALL \" + \" select links.inode as inode, 'link' as asset_type, mod_user as mod_user_id, identifier.host_inode as host_id, mod_date, links_info.live_inode,links_info.working_inode,links_info.deleted, coalesce(links.title,links.identifier) as name \" + \" from link_version_info links_info join links on(links_info.identifier= links.identifier) join identifier identifier on (identifier.id = links.identifier) \" + \" )assets where mod_date>(select coalesce(max(mod_date),\" + (DbConnectionFactory.isPostgres() ? \"'1970-01-01 00:00:00')\" : (DbConnectionFactory.isOracle()) ? \"TO_TIMESTAMP('1970-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS'))\" : (DbConnectionFactory.isMySql()) ? \"STR_TO_DATE('1970-01-01','%Y-%m-%d'))\" : (DbConnectionFactory.isMsSql()) ? \"CAST('1970-01-01' AS DATETIME))\" : \"\") + \" from analytic_summary_workstream) and host_id = '\" + hostId + \"' order by assets.mod_date,assets.name asc \";\n }\n\n protected String getTopAssetsQuery() {\n // This query counts contentlets\n StringBuilder sbCountContentlets = new StringBuilder(\"SELECT identifier.host_inode as host_inode, \").append(\"COUNT(contentlet.inode) AS count, 'contentlet' AS asset_type \").append(\"FROM contentlet_version_info contentinfo JOIN identifier ON (identifier.id = contentinfo.identifier) \").append(\"JOIN contentlet ON (contentlet.identifier = identifier.id) JOIN structure ON (contentlet.structure_inode = structure.inode) \").append(\"WHERE identifier.host_inode = ? \").append(\" AND contentinfo.live_inode IS NOT NULL \").append(\"GROUP BY identifier.host_inode\");\n return sbCountContentlets.toString();\n }\n\n protected String getIdentifierColumn() {\n return \"contentlet.identifier\";\n }\n\n protected String getWorkstreamListQuery() {\n return new StringBuilder(\"select distinct {analytic_summary_workstream.*}, user_.firstname as username, contentlet.title as hostname \").append(\" from analytic_summary_workstream, user_ , contentlet,contentlet_version_info contentinfo \").append(\" where user_.userid = analytic_summary_workstream.mod_user_id and contentlet.identifier = analytic_summary_workstream.host_id \").append(\" and contentlet.identifier = contentinfo.identifier and contentinfo.live_inode is not null and analytic_summary_workstream.name is not null \").append(\" and user_.delete_in_progress = \").append(DbConnectionFactory.getDBFalse()).toString();\n }\n\n protected String getWorkstreamCountQuery() {\n return new StringBuilder(\"select count(distinct analytic_summary_workstream.id) as summaryCount from analytic_summary_workstream, user_, contentlet,contentlet_version_info info where\").append(\" user_.userid = analytic_summary_workstream.mod_user_id and contentlet.identifier = analytic_summary_workstream.host_id \").append(\" and contentlet.identifier = info.identifier and info.live_inode is not null and analytic_summary_workstream.name is not null \").append(\" and user_.delete_in_progress = \").append(DbConnectionFactory.getDBFalse()).toString();\n }\n\n protected StringBuffer getHostListQuery(boolean hasCategory, String selectedCategories, String runDashboardFieldContentlet) {\n StringBuffer query = new StringBuffer();\n query.append(\"select \" + (DbConnectionFactory.isOracle() || DbConnectionFactory.isMsSql() ? \"\" : \" distinct \") + (\" {contentlet.*}, \") + \"coalesce(d.page_views,0) as totalpageviews, \" + \"CASE WHEN contentinfo.live_inode is not null THEN 'Live' \" + \" ELSE 'Stopped' \" + \"END AS status \" + \"from contentlet_version_info contentinfo,inode contentlet_1_ , contentlet \" + \"left join \" + \"(\" + \"select sum(page_views) as page_views, host_id from analytic_summary join \" + \"analytic_summary_period on analytic_summary.summary_period_id = analytic_summary_period.id \" + \"and analytic_summary_period.full_date > ? and analytic_summary_period.full_date < ? \" + \"group by host_id\" + \") \" + (DbConnectionFactory.isMsSql() ? \" as d\" : DbConnectionFactory.isOracle() ? \" d \" : \" as d\") + \" on d.host_id = contentlet.identifier \" + (hasCategory ? \" join tree on tree.child = contentlet.inode and tree.parent in(\" + selectedCategories + \") \" : \"\") + \"join structure s on contentlet.structure_inode = s.inode \" + \"where contentlet_1_.type = 'contentlet' and contentlet.inode = contentlet_1_.inode and s.name ='Host' and contentlet.identifier = contentinfo.identifier \" + \"and contentlet.title <> 'System Host' and contentinfo.working_inode = contentlet.inode \" + (UtilMethods.isSet(runDashboardFieldContentlet) ? \" and contentlet.\" + runDashboardFieldContentlet + \"= \" + DbConnectionFactory.getDBTrue() + \"\" : \"\") + \" \");\n return query;\n }\n\n protected StringBuffer getHostListCountQuery(boolean hasCategory, String selectedCategories, String runDashboardFieldContentlet) {\n StringBuffer query = new StringBuffer();\n query.append(\"select count(distinct contentlet.inode) as total \" + \"from contentlet_version_info contentinfo,inode contentlet_1_ , contentlet \" + (hasCategory ? \" join tree on tree.child = contentlet.inode and tree.parent in(\" + selectedCategories + \") \" : \"\") + \"join structure s on contentlet.structure_inode = s.inode \" + \"where contentlet_1_.type = 'contentlet' and contentlet.inode = contentlet_1_.inode and s.name ='Host' \" + \"and contentlet.title <> 'System Host' and contentlet.identifier = contentinfo.identifier and contentinfo.working_inode = contentlet.inode \" + (UtilMethods.isSet(runDashboardFieldContentlet) ? \" and contentlet.\" + runDashboardFieldContentlet + \"= \" + DbConnectionFactory.getDBTrue() + \"\" : \"\") + \" \");\n return query;\n }\n\n ", "post_mask_code": "{\n String query = \" select contentlet.identifier as host_id from contentlet, structure s,contentlet_version_info info \" + \" where contentlet.structure_inode = s.inode and s.name ='Host' and contentlet.identifier = info.identifier \" + \" and contentlet.title <> 'System Host' and info.working_inode = contentlet.inode \" + (UtilMethods.isSet(runDashboardFieldContentlet) ? \" and contentlet.\" + runDashboardFieldContentlet + \"= \" + DbConnectionFactory.getDBTrue() + \"\" : \"\") + \" group by contentlet.identifier \";\n return query;\n }\n\n /**\n * @param user\n * @param includeArchived\n * @param params\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getHostList(User user, boolean includeArchived, Map params, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param includeArchived\n * @param params\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getHostListCount(User user, boolean includeArchived, Map params) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param userId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getWorkStreamList(User user, String hostId, String userId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param userId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getWorkStreamListCount(User user, String hostId, String userId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public DashboardSummary getDashboardSummary(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param viewType\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getDashboardSummaryVisits(String hostId, ViewType viewType, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getTopReferers(String hostId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getTopReferersCount(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getTopPages(String hostId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getTopPagesCount(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getTopContent(String hostId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getTopContentCount(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param showIgnored\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List get404s(String userId, String hostId, boolean showIgnored, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param showIgnored\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long get404Count(String userId, String hostId, boolean showIgnored, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param id\n * @param ignored\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public void setIgnored(User user, long id, boolean ignored) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @return\n * @throws DotDataException\n * @throws DotSecurityException\n */\n abstract public List getTopAssets(User user, String hostId) throws DotDataException;\n\n abstract public void populateAnalyticSummaryTables();\n\n /**\n * @param month\n * @param year\n * @return\n */\n abstract public int checkPeriodData(int month, int year);\n}\n"} {"task_id": "Java_2375", "language": "Java", "task_type": "method_body", "source_file": "java/github/dotCMS/core/dotCMS/src/main/java/com/dotmarketing/portlets/dashboard/business/DashboardFactory.java", "mask_start_position": 9978, "mask_end_position": 10025, "canonical_solution": "{\n return \"contentlet.identifier\";\n }", "pre_mask_code": "package com.dotmarketing.portlets.dashboard.business;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport com.dotmarketing.beans.Host;\nimport com.dotmarketing.beans.Inode;\nimport com.dotmarketing.db.DbConnectionFactory;\nimport com.dotmarketing.exception.DotDataException;\nimport com.dotmarketing.exception.DotHibernateException;\nimport com.dotmarketing.exception.DotSecurityException;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummary;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummary404;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryContent;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryPage;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryReferer;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryVisits;\nimport com.dotmarketing.portlets.dashboard.model.DashboardWorkStream;\nimport com.dotmarketing.portlets.dashboard.model.TopAsset;\nimport com.dotmarketing.portlets.dashboard.model.ViewType;\nimport com.dotmarketing.portlets.structure.model.Structure;\nimport com.dotmarketing.util.UtilMethods;\nimport com.liferay.portal.model.User;\n\npublic abstract class DashboardFactory {\n\n protected String getSummaryPagesQuery() {\n StringBuilder queryBuilder = new StringBuilder(\"\");\n if (DbConnectionFactory.isPostgres() || DbConnectionFactory.isOracle()) {\n // Find contentlets type 'html page'\n queryBuilder.append(\"SELECT COUNT(*) AS hits, contentlet_version_info.live_inode AS inode, \").append(\"(identifier.parent_path || identifier.asset_name) AS uri \").append(\"FROM clickstream_request cr \").append(\"JOIN contentlet ON (contentlet.identifier = cr.associated_identifier) \").append(\"JOIN structure ON (structure.inode = contentlet.structure_inode) \").append(\"JOIN identifier ON (identifier.id = contentlet.identifier) \").append(\"JOIN contentlet_version_info ON (contentlet_version_info.identifier = identifier.id) \").append(\"WHERE EXTRACT(DAY FROM cr.timestampper) = ? AND EXTRACT(MONTH FROM cr.timestampper) = ? AND EXTRACT(YEAR FROM cr.timestampper) = ? \").append(\"AND cr.host_id = ? AND structure.structuretype = \").append(Structure.STRUCTURE_TYPE_HTMLPAGE).append(\" \").append(\"GROUP BY associated_identifier, (identifier.parent_path || identifier.asset_name), contentlet_version_info.live_inode\");\n } else if (DbConnectionFactory.isMySql()) {\n // MySQL Query Builder\n // Find contentlets type 'html page'\n queryBuilder.append(\"SELECT COUNT(*) AS hits, contentlet_version_info.live_inode AS inode, \").append(\"CONCAT(identifier.parent_path, identifier.asset_name) AS uri \").append(\"FROM clickstream_request cr \").append(\"JOIN contentlet ON (contentlet.identifier = cr.associated_identifier) \").append(\"JOIN structure ON (structure.inode = contentlet.structure_inode) \").append(\"JOIN identifier ON (identifier.id = contentlet.identifier) \").append(\"JOIN contentlet_version_info ON (contentlet_version_info.identifier = identifier.id) \").append(\"WHERE DAY(cr.timestampper) = ? AND MONTH(cr.timestampper) = ? AND YEAR(cr.timestampper) = ? \").append(\"AND cr.host_id = ? AND structure.structuretype = \").append(Structure.STRUCTURE_TYPE_HTMLPAGE).append(\" \").append(\"GROUP BY associated_identifier, CONCAT(identifier.parent_path, identifier.asset_name), contentlet_version_info.live_inode\");\n } else if (DbConnectionFactory.isMsSql()) {\n // MsSQL Query Builder\n // Find contentlets type 'html page'\n queryBuilder.append(\"SELECT COUNT(*) AS hits, contentlet_version_info.live_inode AS inode, \").append(\"(identifier.parent_path + identifier.asset_name) AS uri \").append(\"FROM clickstream_request cr \").append(\"JOIN contentlet ON (contentlet.identifier = cr.associated_identifier) \").append(\"JOIN structure ON (structure.inode = contentlet.structure_inode) \").append(\"JOIN identifier ON (identifier.id = contentlet.identifier) \").append(\"JOIN contentlet_version_info ON (contentlet_version_info.identifier = identifier.id) \").append(\"WHERE DATEPART(DAY, cr.timestampper) = ? AND DATEPART(MONTH, cr.timestampper) = ? AND DATEPART(YEAR, cr.timestampper) = ? \").append(\"AND cr.host_id = ? AND structure.structuretype = \").append(Structure.STRUCTURE_TYPE_HTMLPAGE).append(\" \").append(\"GROUP BY associated_identifier, (identifier.parent_path + identifier.asset_name), contentlet_version_info.live_inode\");\n }\n return queryBuilder.toString();\n }\n\n protected String getSummaryContentQuery() {\n return (DbConnectionFactory.isPostgres() || DbConnectionFactory.isOracle()) ? \" select count(*) as hits, identifier.parent_path as uri ,contentlet.identifier as inode, contentlet.title as title from clickstream_request \" + \" join identifier on identifier.id = associated_identifier join multi_tree on associated_identifier = parent1 join contentlet on contentlet.identifier = multi_tree.child \" + \" where extract(day from timestampper) = ? and extract(month from timestampper) = ? and \" + \" extract(year from timestampper) = ? and host_id = ?\" + \" group by associated_identifier, identifier.parent_path,contentlet.identifier,contentlet.title \" : DbConnectionFactory.isMySql() ? \" select count(*) as hits, identifier.parent_path as uri ,contentlet.identifier as inode, contentlet.title as title from clickstream_request \" + \" join identifier on identifier.id = associated_identifier join multi_tree on associated_identifier = parent1 join contentlet on contentlet.identifier = multi_tree.child \" + \" where DAY(timestampper) = ? and MONTH(timestampper) = ? and YEAR(timestampper) = ? \" + \" and host_id = ? group by associated_identifier, identifier.parent_path,contentlet.identifier,contentlet.title \" : DbConnectionFactory.isMsSql() ? \" select count(*) as hits, identifier.parent_path as uri ,contentlet.identifier as inode, contentlet.title as title from clickstream_request \" + \" join identifier on identifier.id = associated_identifier join multi_tree on associated_identifier = parent1 join contentlet on contentlet.identifier = multi_tree.child \" + \" where DATEPART(day, timestampper) = ? and DATEPART(month, timestampper) = ? and DATEPART(year, timestampper) = ? \" + \" and host_id = ? group by associated_identifier, identifier.parent_path,contentlet.identifier,contentlet.title \" : \"\";\n }\n\n protected String getWorkstreamQuery(String hostId) {\n return \" inode, asset_type, mod_user_id, host_id, mod_date,case when deleted = 1 then 'Deleted' else case when live_inode IS NOT NULL then 'Published' else 'Saved' end end as action, name from( \" + \" select contentlet.inode as inode, case when st.structuretype=\" + Structure.STRUCTURE_TYPE_FILEASSET + \" then 'contentlet' else 'file_asset' end as asset_type, \" + \" mod_user as mod_user_id, identifier.host_inode as host_id, contentlet.mod_date,lang_info.live_inode,lang_info.working_inode,lang_info.deleted, coalesce(contentlet.title,contentlet.identifier) as name \" + \" from contentlet_version_info lang_info join contentlet on (contentlet.identifier = lang_info.identifier) join identifier identifier on (identifier.id = contentlet.identifier) \" + \" join structure st on (contentlet.structure_inode=st.inode) \" + \" UNION ALL \" + \" select template.inode as inode, 'template' as asset_type, mod_user as mod_user_id, identifier.host_inode as host_id, mod_date, temp_info.live_inode,temp_info.working_inode,temp_info.deleted, coalesce(template.title,template.identifier) as name \" + \" from template_version_info temp_info join template on(template.identifier = temp_info.identifier) join identifier identifier on identifier.id = template.identifier \" + \" UNION ALL \" + \" select \" + Inode.Type.CONTAINERS.getTableName() + \".inode as inode, 'container' as asset_type, mod_user as mod_user_id, identifier.host_inode as host_id, mod_date, con_info.live_inode,con_info.working_inode,con_info.deleted, coalesce(\" + Inode.Type.CONTAINERS.getTableName() + \".title,\" + Inode.Type.CONTAINERS.getTableName() + \".identifier) as name \" + \" from container_version_info con_info join \" + Inode.Type.CONTAINERS.getTableName() + \" on(\" + Inode.Type.CONTAINERS.getTableName() + \".identifier = con_info.identifier) join identifier identifier on (identifier.id = \" + Inode.Type.CONTAINERS.getTableName() + \".identifier) \" + \" UNION ALL \" + \" select links.inode as inode, 'link' as asset_type, mod_user as mod_user_id, identifier.host_inode as host_id, mod_date, links_info.live_inode,links_info.working_inode,links_info.deleted, coalesce(links.title,links.identifier) as name \" + \" from link_version_info links_info join links on(links_info.identifier= links.identifier) join identifier identifier on (identifier.id = links.identifier) \" + \" )assets where mod_date>(select coalesce(max(mod_date),\" + (DbConnectionFactory.isPostgres() ? \"'1970-01-01 00:00:00')\" : (DbConnectionFactory.isOracle()) ? \"TO_TIMESTAMP('1970-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS'))\" : (DbConnectionFactory.isMySql()) ? \"STR_TO_DATE('1970-01-01','%Y-%m-%d'))\" : (DbConnectionFactory.isMsSql()) ? \"CAST('1970-01-01' AS DATETIME))\" : \"\") + \" from analytic_summary_workstream) and host_id = '\" + hostId + \"' order by assets.mod_date,assets.name asc \";\n }\n\n protected String getTopAssetsQuery() {\n // This query counts contentlets\n StringBuilder sbCountContentlets = new StringBuilder(\"SELECT identifier.host_inode as host_inode, \").append(\"COUNT(contentlet.inode) AS count, 'contentlet' AS asset_type \").append(\"FROM contentlet_version_info contentinfo JOIN identifier ON (identifier.id = contentinfo.identifier) \").append(\"JOIN contentlet ON (contentlet.identifier = identifier.id) JOIN structure ON (contentlet.structure_inode = structure.inode) \").append(\"WHERE identifier.host_inode = ? \").append(\" AND contentinfo.live_inode IS NOT NULL \").append(\"GROUP BY identifier.host_inode\");\n return sbCountContentlets.toString();\n }\n\n protected String getIdentifierColumn() ", "post_mask_code": "\n\n protected String getWorkstreamListQuery() {\n return new StringBuilder(\"select distinct {analytic_summary_workstream.*}, user_.firstname as username, contentlet.title as hostname \").append(\" from analytic_summary_workstream, user_ , contentlet,contentlet_version_info contentinfo \").append(\" where user_.userid = analytic_summary_workstream.mod_user_id and contentlet.identifier = analytic_summary_workstream.host_id \").append(\" and contentlet.identifier = contentinfo.identifier and contentinfo.live_inode is not null and analytic_summary_workstream.name is not null \").append(\" and user_.delete_in_progress = \").append(DbConnectionFactory.getDBFalse()).toString();\n }\n\n protected String getWorkstreamCountQuery() {\n return new StringBuilder(\"select count(distinct analytic_summary_workstream.id) as summaryCount from analytic_summary_workstream, user_, contentlet,contentlet_version_info info where\").append(\" user_.userid = analytic_summary_workstream.mod_user_id and contentlet.identifier = analytic_summary_workstream.host_id \").append(\" and contentlet.identifier = info.identifier and info.live_inode is not null and analytic_summary_workstream.name is not null \").append(\" and user_.delete_in_progress = \").append(DbConnectionFactory.getDBFalse()).toString();\n }\n\n protected StringBuffer getHostListQuery(boolean hasCategory, String selectedCategories, String runDashboardFieldContentlet) {\n StringBuffer query = new StringBuffer();\n query.append(\"select \" + (DbConnectionFactory.isOracle() || DbConnectionFactory.isMsSql() ? \"\" : \" distinct \") + (\" {contentlet.*}, \") + \"coalesce(d.page_views,0) as totalpageviews, \" + \"CASE WHEN contentinfo.live_inode is not null THEN 'Live' \" + \" ELSE 'Stopped' \" + \"END AS status \" + \"from contentlet_version_info contentinfo,inode contentlet_1_ , contentlet \" + \"left join \" + \"(\" + \"select sum(page_views) as page_views, host_id from analytic_summary join \" + \"analytic_summary_period on analytic_summary.summary_period_id = analytic_summary_period.id \" + \"and analytic_summary_period.full_date > ? and analytic_summary_period.full_date < ? \" + \"group by host_id\" + \") \" + (DbConnectionFactory.isMsSql() ? \" as d\" : DbConnectionFactory.isOracle() ? \" d \" : \" as d\") + \" on d.host_id = contentlet.identifier \" + (hasCategory ? \" join tree on tree.child = contentlet.inode and tree.parent in(\" + selectedCategories + \") \" : \"\") + \"join structure s on contentlet.structure_inode = s.inode \" + \"where contentlet_1_.type = 'contentlet' and contentlet.inode = contentlet_1_.inode and s.name ='Host' and contentlet.identifier = contentinfo.identifier \" + \"and contentlet.title <> 'System Host' and contentinfo.working_inode = contentlet.inode \" + (UtilMethods.isSet(runDashboardFieldContentlet) ? \" and contentlet.\" + runDashboardFieldContentlet + \"= \" + DbConnectionFactory.getDBTrue() + \"\" : \"\") + \" \");\n return query;\n }\n\n protected StringBuffer getHostListCountQuery(boolean hasCategory, String selectedCategories, String runDashboardFieldContentlet) {\n StringBuffer query = new StringBuffer();\n query.append(\"select count(distinct contentlet.inode) as total \" + \"from contentlet_version_info contentinfo,inode contentlet_1_ , contentlet \" + (hasCategory ? \" join tree on tree.child = contentlet.inode and tree.parent in(\" + selectedCategories + \") \" : \"\") + \"join structure s on contentlet.structure_inode = s.inode \" + \"where contentlet_1_.type = 'contentlet' and contentlet.inode = contentlet_1_.inode and s.name ='Host' \" + \"and contentlet.title <> 'System Host' and contentlet.identifier = contentinfo.identifier and contentinfo.working_inode = contentlet.inode \" + (UtilMethods.isSet(runDashboardFieldContentlet) ? \" and contentlet.\" + runDashboardFieldContentlet + \"= \" + DbConnectionFactory.getDBTrue() + \"\" : \"\") + \" \");\n return query;\n }\n\n protected String getHostQueryForClickstream(String runDashboardFieldContentlet) {\n String query = \" select contentlet.identifier as host_id from contentlet, structure s,contentlet_version_info info \" + \" where contentlet.structure_inode = s.inode and s.name ='Host' and contentlet.identifier = info.identifier \" + \" and contentlet.title <> 'System Host' and info.working_inode = contentlet.inode \" + (UtilMethods.isSet(runDashboardFieldContentlet) ? \" and contentlet.\" + runDashboardFieldContentlet + \"= \" + DbConnectionFactory.getDBTrue() + \"\" : \"\") + \" group by contentlet.identifier \";\n return query;\n }\n\n /**\n * @param user\n * @param includeArchived\n * @param params\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getHostList(User user, boolean includeArchived, Map params, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param includeArchived\n * @param params\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getHostListCount(User user, boolean includeArchived, Map params) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param userId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getWorkStreamList(User user, String hostId, String userId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param userId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getWorkStreamListCount(User user, String hostId, String userId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public DashboardSummary getDashboardSummary(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param viewType\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getDashboardSummaryVisits(String hostId, ViewType viewType, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getTopReferers(String hostId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getTopReferersCount(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getTopPages(String hostId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getTopPagesCount(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getTopContent(String hostId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getTopContentCount(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param showIgnored\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List get404s(String userId, String hostId, boolean showIgnored, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param showIgnored\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long get404Count(String userId, String hostId, boolean showIgnored, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param id\n * @param ignored\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public void setIgnored(User user, long id, boolean ignored) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @return\n * @throws DotDataException\n * @throws DotSecurityException\n */\n abstract public List getTopAssets(User user, String hostId) throws DotDataException;\n\n abstract public void populateAnalyticSummaryTables();\n\n /**\n * @param month\n * @param year\n * @return\n */\n abstract public int checkPeriodData(int month, int year);\n}\n"} {"task_id": "Java_2376", "language": "Java", "task_type": "single_line", "source_file": "java/github/dotCMS/core/dotCMS/src/main/java/com/dotmarketing/portlets/dashboard/business/DashboardFactory.java", "mask_start_position": 1290, "mask_end_position": 1314, "canonical_solution": "= new StringBuilder(\"\");", "pre_mask_code": "package com.dotmarketing.portlets.dashboard.business;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport com.dotmarketing.beans.Host;\nimport com.dotmarketing.beans.Inode;\nimport com.dotmarketing.db.DbConnectionFactory;\nimport com.dotmarketing.exception.DotDataException;\nimport com.dotmarketing.exception.DotHibernateException;\nimport com.dotmarketing.exception.DotSecurityException;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummary;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummary404;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryContent;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryPage;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryReferer;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryVisits;\nimport com.dotmarketing.portlets.dashboard.model.DashboardWorkStream;\nimport com.dotmarketing.portlets.dashboard.model.TopAsset;\nimport com.dotmarketing.portlets.dashboard.model.ViewType;\nimport com.dotmarketing.portlets.structure.model.Structure;\nimport com.dotmarketing.util.UtilMethods;\nimport com.liferay.portal.model.User;\n\npublic abstract class DashboardFactory {\n\n protected String getSummaryPagesQuery() {\n StringBuilder queryBuilder ", "post_mask_code": "\n if (DbConnectionFactory.isPostgres() || DbConnectionFactory.isOracle()) {\n // Find contentlets type 'html page'\n queryBuilder.append(\"SELECT COUNT(*) AS hits, contentlet_version_info.live_inode AS inode, \").append(\"(identifier.parent_path || identifier.asset_name) AS uri \").append(\"FROM clickstream_request cr \").append(\"JOIN contentlet ON (contentlet.identifier = cr.associated_identifier) \").append(\"JOIN structure ON (structure.inode = contentlet.structure_inode) \").append(\"JOIN identifier ON (identifier.id = contentlet.identifier) \").append(\"JOIN contentlet_version_info ON (contentlet_version_info.identifier = identifier.id) \").append(\"WHERE EXTRACT(DAY FROM cr.timestampper) = ? AND EXTRACT(MONTH FROM cr.timestampper) = ? AND EXTRACT(YEAR FROM cr.timestampper) = ? \").append(\"AND cr.host_id = ? AND structure.structuretype = \").append(Structure.STRUCTURE_TYPE_HTMLPAGE).append(\" \").append(\"GROUP BY associated_identifier, (identifier.parent_path || identifier.asset_name), contentlet_version_info.live_inode\");\n } else if (DbConnectionFactory.isMySql()) {\n // MySQL Query Builder\n // Find contentlets type 'html page'\n queryBuilder.append(\"SELECT COUNT(*) AS hits, contentlet_version_info.live_inode AS inode, \").append(\"CONCAT(identifier.parent_path, identifier.asset_name) AS uri \").append(\"FROM clickstream_request cr \").append(\"JOIN contentlet ON (contentlet.identifier = cr.associated_identifier) \").append(\"JOIN structure ON (structure.inode = contentlet.structure_inode) \").append(\"JOIN identifier ON (identifier.id = contentlet.identifier) \").append(\"JOIN contentlet_version_info ON (contentlet_version_info.identifier = identifier.id) \").append(\"WHERE DAY(cr.timestampper) = ? AND MONTH(cr.timestampper) = ? AND YEAR(cr.timestampper) = ? \").append(\"AND cr.host_id = ? AND structure.structuretype = \").append(Structure.STRUCTURE_TYPE_HTMLPAGE).append(\" \").append(\"GROUP BY associated_identifier, CONCAT(identifier.parent_path, identifier.asset_name), contentlet_version_info.live_inode\");\n } else if (DbConnectionFactory.isMsSql()) {\n // MsSQL Query Builder\n // Find contentlets type 'html page'\n queryBuilder.append(\"SELECT COUNT(*) AS hits, contentlet_version_info.live_inode AS inode, \").append(\"(identifier.parent_path + identifier.asset_name) AS uri \").append(\"FROM clickstream_request cr \").append(\"JOIN contentlet ON (contentlet.identifier = cr.associated_identifier) \").append(\"JOIN structure ON (structure.inode = contentlet.structure_inode) \").append(\"JOIN identifier ON (identifier.id = contentlet.identifier) \").append(\"JOIN contentlet_version_info ON (contentlet_version_info.identifier = identifier.id) \").append(\"WHERE DATEPART(DAY, cr.timestampper) = ? AND DATEPART(MONTH, cr.timestampper) = ? AND DATEPART(YEAR, cr.timestampper) = ? \").append(\"AND cr.host_id = ? AND structure.structuretype = \").append(Structure.STRUCTURE_TYPE_HTMLPAGE).append(\" \").append(\"GROUP BY associated_identifier, (identifier.parent_path + identifier.asset_name), contentlet_version_info.live_inode\");\n }\n return queryBuilder.toString();\n }\n\n protected String getSummaryContentQuery() {\n return (DbConnectionFactory.isPostgres() || DbConnectionFactory.isOracle()) ? \" select count(*) as hits, identifier.parent_path as uri ,contentlet.identifier as inode, contentlet.title as title from clickstream_request \" + \" join identifier on identifier.id = associated_identifier join multi_tree on associated_identifier = parent1 join contentlet on contentlet.identifier = multi_tree.child \" + \" where extract(day from timestampper) = ? and extract(month from timestampper) = ? and \" + \" extract(year from timestampper) = ? and host_id = ?\" + \" group by associated_identifier, identifier.parent_path,contentlet.identifier,contentlet.title \" : DbConnectionFactory.isMySql() ? \" select count(*) as hits, identifier.parent_path as uri ,contentlet.identifier as inode, contentlet.title as title from clickstream_request \" + \" join identifier on identifier.id = associated_identifier join multi_tree on associated_identifier = parent1 join contentlet on contentlet.identifier = multi_tree.child \" + \" where DAY(timestampper) = ? and MONTH(timestampper) = ? and YEAR(timestampper) = ? \" + \" and host_id = ? group by associated_identifier, identifier.parent_path,contentlet.identifier,contentlet.title \" : DbConnectionFactory.isMsSql() ? \" select count(*) as hits, identifier.parent_path as uri ,contentlet.identifier as inode, contentlet.title as title from clickstream_request \" + \" join identifier on identifier.id = associated_identifier join multi_tree on associated_identifier = parent1 join contentlet on contentlet.identifier = multi_tree.child \" + \" where DATEPART(day, timestampper) = ? and DATEPART(month, timestampper) = ? and DATEPART(year, timestampper) = ? \" + \" and host_id = ? group by associated_identifier, identifier.parent_path,contentlet.identifier,contentlet.title \" : \"\";\n }\n\n protected String getWorkstreamQuery(String hostId) {\n return \" inode, asset_type, mod_user_id, host_id, mod_date,case when deleted = 1 then 'Deleted' else case when live_inode IS NOT NULL then 'Published' else 'Saved' end end as action, name from( \" + \" select contentlet.inode as inode, case when st.structuretype=\" + Structure.STRUCTURE_TYPE_FILEASSET + \" then 'contentlet' else 'file_asset' end as asset_type, \" + \" mod_user as mod_user_id, identifier.host_inode as host_id, contentlet.mod_date,lang_info.live_inode,lang_info.working_inode,lang_info.deleted, coalesce(contentlet.title,contentlet.identifier) as name \" + \" from contentlet_version_info lang_info join contentlet on (contentlet.identifier = lang_info.identifier) join identifier identifier on (identifier.id = contentlet.identifier) \" + \" join structure st on (contentlet.structure_inode=st.inode) \" + \" UNION ALL \" + \" select template.inode as inode, 'template' as asset_type, mod_user as mod_user_id, identifier.host_inode as host_id, mod_date, temp_info.live_inode,temp_info.working_inode,temp_info.deleted, coalesce(template.title,template.identifier) as name \" + \" from template_version_info temp_info join template on(template.identifier = temp_info.identifier) join identifier identifier on identifier.id = template.identifier \" + \" UNION ALL \" + \" select \" + Inode.Type.CONTAINERS.getTableName() + \".inode as inode, 'container' as asset_type, mod_user as mod_user_id, identifier.host_inode as host_id, mod_date, con_info.live_inode,con_info.working_inode,con_info.deleted, coalesce(\" + Inode.Type.CONTAINERS.getTableName() + \".title,\" + Inode.Type.CONTAINERS.getTableName() + \".identifier) as name \" + \" from container_version_info con_info join \" + Inode.Type.CONTAINERS.getTableName() + \" on(\" + Inode.Type.CONTAINERS.getTableName() + \".identifier = con_info.identifier) join identifier identifier on (identifier.id = \" + Inode.Type.CONTAINERS.getTableName() + \".identifier) \" + \" UNION ALL \" + \" select links.inode as inode, 'link' as asset_type, mod_user as mod_user_id, identifier.host_inode as host_id, mod_date, links_info.live_inode,links_info.working_inode,links_info.deleted, coalesce(links.title,links.identifier) as name \" + \" from link_version_info links_info join links on(links_info.identifier= links.identifier) join identifier identifier on (identifier.id = links.identifier) \" + \" )assets where mod_date>(select coalesce(max(mod_date),\" + (DbConnectionFactory.isPostgres() ? \"'1970-01-01 00:00:00')\" : (DbConnectionFactory.isOracle()) ? \"TO_TIMESTAMP('1970-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS'))\" : (DbConnectionFactory.isMySql()) ? \"STR_TO_DATE('1970-01-01','%Y-%m-%d'))\" : (DbConnectionFactory.isMsSql()) ? \"CAST('1970-01-01' AS DATETIME))\" : \"\") + \" from analytic_summary_workstream) and host_id = '\" + hostId + \"' order by assets.mod_date,assets.name asc \";\n }\n\n protected String getTopAssetsQuery() {\n // This query counts contentlets\n StringBuilder sbCountContentlets = new StringBuilder(\"SELECT identifier.host_inode as host_inode, \").append(\"COUNT(contentlet.inode) AS count, 'contentlet' AS asset_type \").append(\"FROM contentlet_version_info contentinfo JOIN identifier ON (identifier.id = contentinfo.identifier) \").append(\"JOIN contentlet ON (contentlet.identifier = identifier.id) JOIN structure ON (contentlet.structure_inode = structure.inode) \").append(\"WHERE identifier.host_inode = ? \").append(\" AND contentinfo.live_inode IS NOT NULL \").append(\"GROUP BY identifier.host_inode\");\n return sbCountContentlets.toString();\n }\n\n protected String getIdentifierColumn() {\n return \"contentlet.identifier\";\n }\n\n protected String getWorkstreamListQuery() {\n return new StringBuilder(\"select distinct {analytic_summary_workstream.*}, user_.firstname as username, contentlet.title as hostname \").append(\" from analytic_summary_workstream, user_ , contentlet,contentlet_version_info contentinfo \").append(\" where user_.userid = analytic_summary_workstream.mod_user_id and contentlet.identifier = analytic_summary_workstream.host_id \").append(\" and contentlet.identifier = contentinfo.identifier and contentinfo.live_inode is not null and analytic_summary_workstream.name is not null \").append(\" and user_.delete_in_progress = \").append(DbConnectionFactory.getDBFalse()).toString();\n }\n\n protected String getWorkstreamCountQuery() {\n return new StringBuilder(\"select count(distinct analytic_summary_workstream.id) as summaryCount from analytic_summary_workstream, user_, contentlet,contentlet_version_info info where\").append(\" user_.userid = analytic_summary_workstream.mod_user_id and contentlet.identifier = analytic_summary_workstream.host_id \").append(\" and contentlet.identifier = info.identifier and info.live_inode is not null and analytic_summary_workstream.name is not null \").append(\" and user_.delete_in_progress = \").append(DbConnectionFactory.getDBFalse()).toString();\n }\n\n protected StringBuffer getHostListQuery(boolean hasCategory, String selectedCategories, String runDashboardFieldContentlet) {\n StringBuffer query = new StringBuffer();\n query.append(\"select \" + (DbConnectionFactory.isOracle() || DbConnectionFactory.isMsSql() ? \"\" : \" distinct \") + (\" {contentlet.*}, \") + \"coalesce(d.page_views,0) as totalpageviews, \" + \"CASE WHEN contentinfo.live_inode is not null THEN 'Live' \" + \" ELSE 'Stopped' \" + \"END AS status \" + \"from contentlet_version_info contentinfo,inode contentlet_1_ , contentlet \" + \"left join \" + \"(\" + \"select sum(page_views) as page_views, host_id from analytic_summary join \" + \"analytic_summary_period on analytic_summary.summary_period_id = analytic_summary_period.id \" + \"and analytic_summary_period.full_date > ? and analytic_summary_period.full_date < ? \" + \"group by host_id\" + \") \" + (DbConnectionFactory.isMsSql() ? \" as d\" : DbConnectionFactory.isOracle() ? \" d \" : \" as d\") + \" on d.host_id = contentlet.identifier \" + (hasCategory ? \" join tree on tree.child = contentlet.inode and tree.parent in(\" + selectedCategories + \") \" : \"\") + \"join structure s on contentlet.structure_inode = s.inode \" + \"where contentlet_1_.type = 'contentlet' and contentlet.inode = contentlet_1_.inode and s.name ='Host' and contentlet.identifier = contentinfo.identifier \" + \"and contentlet.title <> 'System Host' and contentinfo.working_inode = contentlet.inode \" + (UtilMethods.isSet(runDashboardFieldContentlet) ? \" and contentlet.\" + runDashboardFieldContentlet + \"= \" + DbConnectionFactory.getDBTrue() + \"\" : \"\") + \" \");\n return query;\n }\n\n protected StringBuffer getHostListCountQuery(boolean hasCategory, String selectedCategories, String runDashboardFieldContentlet) {\n StringBuffer query = new StringBuffer();\n query.append(\"select count(distinct contentlet.inode) as total \" + \"from contentlet_version_info contentinfo,inode contentlet_1_ , contentlet \" + (hasCategory ? \" join tree on tree.child = contentlet.inode and tree.parent in(\" + selectedCategories + \") \" : \"\") + \"join structure s on contentlet.structure_inode = s.inode \" + \"where contentlet_1_.type = 'contentlet' and contentlet.inode = contentlet_1_.inode and s.name ='Host' \" + \"and contentlet.title <> 'System Host' and contentlet.identifier = contentinfo.identifier and contentinfo.working_inode = contentlet.inode \" + (UtilMethods.isSet(runDashboardFieldContentlet) ? \" and contentlet.\" + runDashboardFieldContentlet + \"= \" + DbConnectionFactory.getDBTrue() + \"\" : \"\") + \" \");\n return query;\n }\n\n protected String getHostQueryForClickstream(String runDashboardFieldContentlet) {\n String query = \" select contentlet.identifier as host_id from contentlet, structure s,contentlet_version_info info \" + \" where contentlet.structure_inode = s.inode and s.name ='Host' and contentlet.identifier = info.identifier \" + \" and contentlet.title <> 'System Host' and info.working_inode = contentlet.inode \" + (UtilMethods.isSet(runDashboardFieldContentlet) ? \" and contentlet.\" + runDashboardFieldContentlet + \"= \" + DbConnectionFactory.getDBTrue() + \"\" : \"\") + \" group by contentlet.identifier \";\n return query;\n }\n\n /**\n * @param user\n * @param includeArchived\n * @param params\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getHostList(User user, boolean includeArchived, Map params, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param includeArchived\n * @param params\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getHostListCount(User user, boolean includeArchived, Map params) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param userId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getWorkStreamList(User user, String hostId, String userId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param userId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getWorkStreamListCount(User user, String hostId, String userId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public DashboardSummary getDashboardSummary(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param viewType\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getDashboardSummaryVisits(String hostId, ViewType viewType, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getTopReferers(String hostId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getTopReferersCount(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getTopPages(String hostId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getTopPagesCount(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getTopContent(String hostId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getTopContentCount(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param showIgnored\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List get404s(String userId, String hostId, boolean showIgnored, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param showIgnored\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long get404Count(String userId, String hostId, boolean showIgnored, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param id\n * @param ignored\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public void setIgnored(User user, long id, boolean ignored) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @return\n * @throws DotDataException\n * @throws DotSecurityException\n */\n abstract public List getTopAssets(User user, String hostId) throws DotDataException;\n\n abstract public void populateAnalyticSummaryTables();\n\n /**\n * @param month\n * @param year\n * @return\n */\n abstract public int checkPeriodData(int month, int year);\n}\n"} {"task_id": "Java_2377", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/dotCMS/core/dotCMS/src/main/java/com/dotmarketing/portlets/dashboard/business/DashboardFactory.java", "mask_start_position": 18856, "mask_end_position": 18986, "canonical_solution": "abstract public long getTopContentCount(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;", "pre_mask_code": "package com.dotmarketing.portlets.dashboard.business;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport com.dotmarketing.beans.Host;\nimport com.dotmarketing.beans.Inode;\nimport com.dotmarketing.db.DbConnectionFactory;\nimport com.dotmarketing.exception.DotDataException;\nimport com.dotmarketing.exception.DotHibernateException;\nimport com.dotmarketing.exception.DotSecurityException;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummary;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummary404;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryContent;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryPage;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryReferer;\nimport com.dotmarketing.portlets.dashboard.model.DashboardSummaryVisits;\nimport com.dotmarketing.portlets.dashboard.model.DashboardWorkStream;\nimport com.dotmarketing.portlets.dashboard.model.TopAsset;\nimport com.dotmarketing.portlets.dashboard.model.ViewType;\nimport com.dotmarketing.portlets.structure.model.Structure;\nimport com.dotmarketing.util.UtilMethods;\nimport com.liferay.portal.model.User;\n\npublic abstract class DashboardFactory {\n\n protected String getSummaryPagesQuery() {\n StringBuilder queryBuilder = new StringBuilder(\"\");\n if (DbConnectionFactory.isPostgres() || DbConnectionFactory.isOracle()) {\n // Find contentlets type 'html page'\n queryBuilder.append(\"SELECT COUNT(*) AS hits, contentlet_version_info.live_inode AS inode, \").append(\"(identifier.parent_path || identifier.asset_name) AS uri \").append(\"FROM clickstream_request cr \").append(\"JOIN contentlet ON (contentlet.identifier = cr.associated_identifier) \").append(\"JOIN structure ON (structure.inode = contentlet.structure_inode) \").append(\"JOIN identifier ON (identifier.id = contentlet.identifier) \").append(\"JOIN contentlet_version_info ON (contentlet_version_info.identifier = identifier.id) \").append(\"WHERE EXTRACT(DAY FROM cr.timestampper) = ? AND EXTRACT(MONTH FROM cr.timestampper) = ? AND EXTRACT(YEAR FROM cr.timestampper) = ? \").append(\"AND cr.host_id = ? AND structure.structuretype = \").append(Structure.STRUCTURE_TYPE_HTMLPAGE).append(\" \").append(\"GROUP BY associated_identifier, (identifier.parent_path || identifier.asset_name), contentlet_version_info.live_inode\");\n } else if (DbConnectionFactory.isMySql()) {\n // MySQL Query Builder\n // Find contentlets type 'html page'\n queryBuilder.append(\"SELECT COUNT(*) AS hits, contentlet_version_info.live_inode AS inode, \").append(\"CONCAT(identifier.parent_path, identifier.asset_name) AS uri \").append(\"FROM clickstream_request cr \").append(\"JOIN contentlet ON (contentlet.identifier = cr.associated_identifier) \").append(\"JOIN structure ON (structure.inode = contentlet.structure_inode) \").append(\"JOIN identifier ON (identifier.id = contentlet.identifier) \").append(\"JOIN contentlet_version_info ON (contentlet_version_info.identifier = identifier.id) \").append(\"WHERE DAY(cr.timestampper) = ? AND MONTH(cr.timestampper) = ? AND YEAR(cr.timestampper) = ? \").append(\"AND cr.host_id = ? AND structure.structuretype = \").append(Structure.STRUCTURE_TYPE_HTMLPAGE).append(\" \").append(\"GROUP BY associated_identifier, CONCAT(identifier.parent_path, identifier.asset_name), contentlet_version_info.live_inode\");\n } else if (DbConnectionFactory.isMsSql()) {\n // MsSQL Query Builder\n // Find contentlets type 'html page'\n queryBuilder.append(\"SELECT COUNT(*) AS hits, contentlet_version_info.live_inode AS inode, \").append(\"(identifier.parent_path + identifier.asset_name) AS uri \").append(\"FROM clickstream_request cr \").append(\"JOIN contentlet ON (contentlet.identifier = cr.associated_identifier) \").append(\"JOIN structure ON (structure.inode = contentlet.structure_inode) \").append(\"JOIN identifier ON (identifier.id = contentlet.identifier) \").append(\"JOIN contentlet_version_info ON (contentlet_version_info.identifier = identifier.id) \").append(\"WHERE DATEPART(DAY, cr.timestampper) = ? AND DATEPART(MONTH, cr.timestampper) = ? AND DATEPART(YEAR, cr.timestampper) = ? \").append(\"AND cr.host_id = ? AND structure.structuretype = \").append(Structure.STRUCTURE_TYPE_HTMLPAGE).append(\" \").append(\"GROUP BY associated_identifier, (identifier.parent_path + identifier.asset_name), contentlet_version_info.live_inode\");\n }\n return queryBuilder.toString();\n }\n\n protected String getSummaryContentQuery() {\n return (DbConnectionFactory.isPostgres() || DbConnectionFactory.isOracle()) ? \" select count(*) as hits, identifier.parent_path as uri ,contentlet.identifier as inode, contentlet.title as title from clickstream_request \" + \" join identifier on identifier.id = associated_identifier join multi_tree on associated_identifier = parent1 join contentlet on contentlet.identifier = multi_tree.child \" + \" where extract(day from timestampper) = ? and extract(month from timestampper) = ? and \" + \" extract(year from timestampper) = ? and host_id = ?\" + \" group by associated_identifier, identifier.parent_path,contentlet.identifier,contentlet.title \" : DbConnectionFactory.isMySql() ? \" select count(*) as hits, identifier.parent_path as uri ,contentlet.identifier as inode, contentlet.title as title from clickstream_request \" + \" join identifier on identifier.id = associated_identifier join multi_tree on associated_identifier = parent1 join contentlet on contentlet.identifier = multi_tree.child \" + \" where DAY(timestampper) = ? and MONTH(timestampper) = ? and YEAR(timestampper) = ? \" + \" and host_id = ? group by associated_identifier, identifier.parent_path,contentlet.identifier,contentlet.title \" : DbConnectionFactory.isMsSql() ? \" select count(*) as hits, identifier.parent_path as uri ,contentlet.identifier as inode, contentlet.title as title from clickstream_request \" + \" join identifier on identifier.id = associated_identifier join multi_tree on associated_identifier = parent1 join contentlet on contentlet.identifier = multi_tree.child \" + \" where DATEPART(day, timestampper) = ? and DATEPART(month, timestampper) = ? and DATEPART(year, timestampper) = ? \" + \" and host_id = ? group by associated_identifier, identifier.parent_path,contentlet.identifier,contentlet.title \" : \"\";\n }\n\n protected String getWorkstreamQuery(String hostId) {\n return \" inode, asset_type, mod_user_id, host_id, mod_date,case when deleted = 1 then 'Deleted' else case when live_inode IS NOT NULL then 'Published' else 'Saved' end end as action, name from( \" + \" select contentlet.inode as inode, case when st.structuretype=\" + Structure.STRUCTURE_TYPE_FILEASSET + \" then 'contentlet' else 'file_asset' end as asset_type, \" + \" mod_user as mod_user_id, identifier.host_inode as host_id, contentlet.mod_date,lang_info.live_inode,lang_info.working_inode,lang_info.deleted, coalesce(contentlet.title,contentlet.identifier) as name \" + \" from contentlet_version_info lang_info join contentlet on (contentlet.identifier = lang_info.identifier) join identifier identifier on (identifier.id = contentlet.identifier) \" + \" join structure st on (contentlet.structure_inode=st.inode) \" + \" UNION ALL \" + \" select template.inode as inode, 'template' as asset_type, mod_user as mod_user_id, identifier.host_inode as host_id, mod_date, temp_info.live_inode,temp_info.working_inode,temp_info.deleted, coalesce(template.title,template.identifier) as name \" + \" from template_version_info temp_info join template on(template.identifier = temp_info.identifier) join identifier identifier on identifier.id = template.identifier \" + \" UNION ALL \" + \" select \" + Inode.Type.CONTAINERS.getTableName() + \".inode as inode, 'container' as asset_type, mod_user as mod_user_id, identifier.host_inode as host_id, mod_date, con_info.live_inode,con_info.working_inode,con_info.deleted, coalesce(\" + Inode.Type.CONTAINERS.getTableName() + \".title,\" + Inode.Type.CONTAINERS.getTableName() + \".identifier) as name \" + \" from container_version_info con_info join \" + Inode.Type.CONTAINERS.getTableName() + \" on(\" + Inode.Type.CONTAINERS.getTableName() + \".identifier = con_info.identifier) join identifier identifier on (identifier.id = \" + Inode.Type.CONTAINERS.getTableName() + \".identifier) \" + \" UNION ALL \" + \" select links.inode as inode, 'link' as asset_type, mod_user as mod_user_id, identifier.host_inode as host_id, mod_date, links_info.live_inode,links_info.working_inode,links_info.deleted, coalesce(links.title,links.identifier) as name \" + \" from link_version_info links_info join links on(links_info.identifier= links.identifier) join identifier identifier on (identifier.id = links.identifier) \" + \" )assets where mod_date>(select coalesce(max(mod_date),\" + (DbConnectionFactory.isPostgres() ? \"'1970-01-01 00:00:00')\" : (DbConnectionFactory.isOracle()) ? \"TO_TIMESTAMP('1970-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS'))\" : (DbConnectionFactory.isMySql()) ? \"STR_TO_DATE('1970-01-01','%Y-%m-%d'))\" : (DbConnectionFactory.isMsSql()) ? \"CAST('1970-01-01' AS DATETIME))\" : \"\") + \" from analytic_summary_workstream) and host_id = '\" + hostId + \"' order by assets.mod_date,assets.name asc \";\n }\n\n protected String getTopAssetsQuery() {\n // This query counts contentlets\n StringBuilder sbCountContentlets = new StringBuilder(\"SELECT identifier.host_inode as host_inode, \").append(\"COUNT(contentlet.inode) AS count, 'contentlet' AS asset_type \").append(\"FROM contentlet_version_info contentinfo JOIN identifier ON (identifier.id = contentinfo.identifier) \").append(\"JOIN contentlet ON (contentlet.identifier = identifier.id) JOIN structure ON (contentlet.structure_inode = structure.inode) \").append(\"WHERE identifier.host_inode = ? \").append(\" AND contentinfo.live_inode IS NOT NULL \").append(\"GROUP BY identifier.host_inode\");\n return sbCountContentlets.toString();\n }\n\n protected String getIdentifierColumn() {\n return \"contentlet.identifier\";\n }\n\n protected String getWorkstreamListQuery() {\n return new StringBuilder(\"select distinct {analytic_summary_workstream.*}, user_.firstname as username, contentlet.title as hostname \").append(\" from analytic_summary_workstream, user_ , contentlet,contentlet_version_info contentinfo \").append(\" where user_.userid = analytic_summary_workstream.mod_user_id and contentlet.identifier = analytic_summary_workstream.host_id \").append(\" and contentlet.identifier = contentinfo.identifier and contentinfo.live_inode is not null and analytic_summary_workstream.name is not null \").append(\" and user_.delete_in_progress = \").append(DbConnectionFactory.getDBFalse()).toString();\n }\n\n protected String getWorkstreamCountQuery() {\n return new StringBuilder(\"select count(distinct analytic_summary_workstream.id) as summaryCount from analytic_summary_workstream, user_, contentlet,contentlet_version_info info where\").append(\" user_.userid = analytic_summary_workstream.mod_user_id and contentlet.identifier = analytic_summary_workstream.host_id \").append(\" and contentlet.identifier = info.identifier and info.live_inode is not null and analytic_summary_workstream.name is not null \").append(\" and user_.delete_in_progress = \").append(DbConnectionFactory.getDBFalse()).toString();\n }\n\n protected StringBuffer getHostListQuery(boolean hasCategory, String selectedCategories, String runDashboardFieldContentlet) {\n StringBuffer query = new StringBuffer();\n query.append(\"select \" + (DbConnectionFactory.isOracle() || DbConnectionFactory.isMsSql() ? \"\" : \" distinct \") + (\" {contentlet.*}, \") + \"coalesce(d.page_views,0) as totalpageviews, \" + \"CASE WHEN contentinfo.live_inode is not null THEN 'Live' \" + \" ELSE 'Stopped' \" + \"END AS status \" + \"from contentlet_version_info contentinfo,inode contentlet_1_ , contentlet \" + \"left join \" + \"(\" + \"select sum(page_views) as page_views, host_id from analytic_summary join \" + \"analytic_summary_period on analytic_summary.summary_period_id = analytic_summary_period.id \" + \"and analytic_summary_period.full_date > ? and analytic_summary_period.full_date < ? \" + \"group by host_id\" + \") \" + (DbConnectionFactory.isMsSql() ? \" as d\" : DbConnectionFactory.isOracle() ? \" d \" : \" as d\") + \" on d.host_id = contentlet.identifier \" + (hasCategory ? \" join tree on tree.child = contentlet.inode and tree.parent in(\" + selectedCategories + \") \" : \"\") + \"join structure s on contentlet.structure_inode = s.inode \" + \"where contentlet_1_.type = 'contentlet' and contentlet.inode = contentlet_1_.inode and s.name ='Host' and contentlet.identifier = contentinfo.identifier \" + \"and contentlet.title <> 'System Host' and contentinfo.working_inode = contentlet.inode \" + (UtilMethods.isSet(runDashboardFieldContentlet) ? \" and contentlet.\" + runDashboardFieldContentlet + \"= \" + DbConnectionFactory.getDBTrue() + \"\" : \"\") + \" \");\n return query;\n }\n\n protected StringBuffer getHostListCountQuery(boolean hasCategory, String selectedCategories, String runDashboardFieldContentlet) {\n StringBuffer query = new StringBuffer();\n query.append(\"select count(distinct contentlet.inode) as total \" + \"from contentlet_version_info contentinfo,inode contentlet_1_ , contentlet \" + (hasCategory ? \" join tree on tree.child = contentlet.inode and tree.parent in(\" + selectedCategories + \") \" : \"\") + \"join structure s on contentlet.structure_inode = s.inode \" + \"where contentlet_1_.type = 'contentlet' and contentlet.inode = contentlet_1_.inode and s.name ='Host' \" + \"and contentlet.title <> 'System Host' and contentlet.identifier = contentinfo.identifier and contentinfo.working_inode = contentlet.inode \" + (UtilMethods.isSet(runDashboardFieldContentlet) ? \" and contentlet.\" + runDashboardFieldContentlet + \"= \" + DbConnectionFactory.getDBTrue() + \"\" : \"\") + \" \");\n return query;\n }\n\n protected String getHostQueryForClickstream(String runDashboardFieldContentlet) {\n String query = \" select contentlet.identifier as host_id from contentlet, structure s,contentlet_version_info info \" + \" where contentlet.structure_inode = s.inode and s.name ='Host' and contentlet.identifier = info.identifier \" + \" and contentlet.title <> 'System Host' and info.working_inode = contentlet.inode \" + (UtilMethods.isSet(runDashboardFieldContentlet) ? \" and contentlet.\" + runDashboardFieldContentlet + \"= \" + DbConnectionFactory.getDBTrue() + \"\" : \"\") + \" group by contentlet.identifier \";\n return query;\n }\n\n /**\n * @param user\n * @param includeArchived\n * @param params\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getHostList(User user, boolean includeArchived, Map params, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param includeArchived\n * @param params\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getHostListCount(User user, boolean includeArchived, Map params) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param userId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getWorkStreamList(User user, String hostId, String userId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param userId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getWorkStreamListCount(User user, String hostId, String userId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public DashboardSummary getDashboardSummary(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param viewType\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getDashboardSummaryVisits(String hostId, ViewType viewType, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getTopReferers(String hostId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getTopReferersCount(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getTopPages(String hostId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long getTopPagesCount(String hostId, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List getTopContent(String hostId, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param hostId\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n ", "post_mask_code": "\n\n /**\n * @param user\n * @param hostId\n * @param showIgnored\n * @param fromDate\n * @param toDate\n * @param limit\n * @param offset\n * @param sortBy\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public List get404s(String userId, String hostId, boolean showIgnored, Date fromDate, Date toDate, int limit, int offset, String sortBy) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @param showIgnored\n * @param fromDate\n * @param toDate\n * @return\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public long get404Count(String userId, String hostId, boolean showIgnored, Date fromDate, Date toDate) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param id\n * @param ignored\n * @throws DotDataException\n * @throws DotHibernateException\n */\n abstract public void setIgnored(User user, long id, boolean ignored) throws DotDataException, DotHibernateException;\n\n /**\n * @param user\n * @param hostId\n * @return\n * @throws DotDataException\n * @throws DotSecurityException\n */\n abstract public List getTopAssets(User user, String hostId) throws DotDataException;\n\n abstract public void populateAnalyticSummaryTables();\n\n /**\n * @param month\n * @param year\n * @return\n */\n abstract public int checkPeriodData(int month, int year);\n}\n"} {"task_id": "Java_2378", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/android/service/autofill/FillContext.java", "mask_start_position": 547, "mask_end_position": 598, "canonical_solution": "public FillContext createFromParcel(Parcel parcel) ", "pre_mask_code": "package android.service.autofill;\n\nimport android.app.assist.AssistStructure;\nimport android.app.assist.AssistStructure.ViewNode;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.Parcelable.Creator;\nimport android.util.ArrayMap;\nimport android.util.SparseIntArray;\nimport android.view.autofill.AutofillId;\nimport android.view.autofill.Helper;\nimport java.util.LinkedList;\n\npublic final class FillContext implements Parcelable {\n\n public static final Creator CREATOR = new Creator() {\n\n ", "post_mask_code": "{\n return new FillContext(parcel, null);\n }\n\n public FillContext[] newArray(int size) {\n return new FillContext[size];\n }\n };\n\n private final int mRequestId;\n\n private final AssistStructure mStructure;\n\n private ArrayMap mViewNodeLookupTable;\n\n public FillContext(int requestId, AssistStructure structure) {\n this.mRequestId = requestId;\n this.mStructure = structure;\n }\n\n private FillContext(Parcel parcel) {\n this(parcel.readInt(), (AssistStructure) parcel.readParcelable(null));\n }\n\n public int getRequestId() {\n return this.mRequestId;\n }\n\n public AssistStructure getStructure() {\n return this.mStructure;\n }\n\n public String toString() {\n if (!Helper.sDebug) {\n return super.toString();\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"FillContext [reqId=\");\n stringBuilder.append(this.mRequestId);\n stringBuilder.append(\"]\");\n return stringBuilder.toString();\n }\n\n public int describeContents() {\n return 0;\n }\n\n public void writeToParcel(Parcel parcel, int flags) {\n parcel.writeInt(this.mRequestId);\n parcel.writeParcelable(this.mStructure, flags);\n }\n\n /* JADX WARNING: Removed duplicated region for block: B:31:0x0099 A:{LOOP_END, LOOP:4: B:29:0x0093->B:31:0x0099} */\n /* Code decompiled incorrectly, please refer to instructions dump. */\n public ViewNode[] findViewNodesByAutofillIds(AutofillId[] ids) {\n int i;\n int lookupTableIndex;\n LinkedList nodesToProcess = new LinkedList();\n ViewNode[] foundNodes = new ViewNode[ids.length];\n SparseIntArray missingNodeIndexes = new SparseIntArray(ids.length);\n int i2 = 0;\n for (i = 0; i < ids.length; i++) {\n if (this.mViewNodeLookupTable != null) {\n lookupTableIndex = this.mViewNodeLookupTable.indexOfKey(ids[i]);\n if (lookupTableIndex >= 0) {\n foundNodes[i] = (ViewNode) this.mViewNodeLookupTable.valueAt(lookupTableIndex);\n } else {\n missingNodeIndexes.put(i, 0);\n }\n } else {\n missingNodeIndexes.put(i, 0);\n }\n }\n i = this.mStructure.getWindowNodeCount();\n for (lookupTableIndex = 0; lookupTableIndex < i; lookupTableIndex++) {\n nodesToProcess.add(this.mStructure.getWindowNodeAt(lookupTableIndex).getRootViewNode());\n }\n while (missingNodeIndexes.size() > 0 && !nodesToProcess.isEmpty()) {\n ViewNode node = (ViewNode) nodesToProcess.removeFirst();\n int i3 = 0;\n while (i3 < missingNodeIndexes.size()) {\n int index = missingNodeIndexes.keyAt(i3);\n AutofillId id = ids[index];\n if (id.equals(node.getAutofillId())) {\n foundNodes[index] = node;\n if (this.mViewNodeLookupTable == null) {\n this.mViewNodeLookupTable = new ArrayMap(ids.length);\n }\n this.mViewNodeLookupTable.put(id, node);\n missingNodeIndexes.removeAt(i3);\n for (i3 = 0; i3 < node.getChildCount(); i3++) {\n nodesToProcess.addLast(node.getChildAt(i3));\n }\n } else {\n i3++;\n }\n }\n while (i3 < node.getChildCount()) {\n }\n }\n while (i2 < missingNodeIndexes.size()) {\n if (this.mViewNodeLookupTable == null) {\n this.mViewNodeLookupTable = new ArrayMap(missingNodeIndexes.size());\n }\n this.mViewNodeLookupTable.put(ids[missingNodeIndexes.keyAt(i2)], null);\n i2++;\n }\n return foundNodes;\n }\n}\n"} {"task_id": "Java_2379", "language": "Java", "task_type": "method_body", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/android/service/autofill/FillContext.java", "mask_start_position": 598, "mask_end_position": 659, "canonical_solution": "{\n return new FillContext(parcel, null);\n }", "pre_mask_code": "package android.service.autofill;\n\nimport android.app.assist.AssistStructure;\nimport android.app.assist.AssistStructure.ViewNode;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.Parcelable.Creator;\nimport android.util.ArrayMap;\nimport android.util.SparseIntArray;\nimport android.view.autofill.AutofillId;\nimport android.view.autofill.Helper;\nimport java.util.LinkedList;\n\npublic final class FillContext implements Parcelable {\n\n public static final Creator CREATOR = new Creator() {\n\n public FillContext createFromParcel(Parcel parcel) ", "post_mask_code": "\n\n public FillContext[] newArray(int size) {\n return new FillContext[size];\n }\n };\n\n private final int mRequestId;\n\n private final AssistStructure mStructure;\n\n private ArrayMap mViewNodeLookupTable;\n\n public FillContext(int requestId, AssistStructure structure) {\n this.mRequestId = requestId;\n this.mStructure = structure;\n }\n\n private FillContext(Parcel parcel) {\n this(parcel.readInt(), (AssistStructure) parcel.readParcelable(null));\n }\n\n public int getRequestId() {\n return this.mRequestId;\n }\n\n public AssistStructure getStructure() {\n return this.mStructure;\n }\n\n public String toString() {\n if (!Helper.sDebug) {\n return super.toString();\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"FillContext [reqId=\");\n stringBuilder.append(this.mRequestId);\n stringBuilder.append(\"]\");\n return stringBuilder.toString();\n }\n\n public int describeContents() {\n return 0;\n }\n\n public void writeToParcel(Parcel parcel, int flags) {\n parcel.writeInt(this.mRequestId);\n parcel.writeParcelable(this.mStructure, flags);\n }\n\n /* JADX WARNING: Removed duplicated region for block: B:31:0x0099 A:{LOOP_END, LOOP:4: B:29:0x0093->B:31:0x0099} */\n /* Code decompiled incorrectly, please refer to instructions dump. */\n public ViewNode[] findViewNodesByAutofillIds(AutofillId[] ids) {\n int i;\n int lookupTableIndex;\n LinkedList nodesToProcess = new LinkedList();\n ViewNode[] foundNodes = new ViewNode[ids.length];\n SparseIntArray missingNodeIndexes = new SparseIntArray(ids.length);\n int i2 = 0;\n for (i = 0; i < ids.length; i++) {\n if (this.mViewNodeLookupTable != null) {\n lookupTableIndex = this.mViewNodeLookupTable.indexOfKey(ids[i]);\n if (lookupTableIndex >= 0) {\n foundNodes[i] = (ViewNode) this.mViewNodeLookupTable.valueAt(lookupTableIndex);\n } else {\n missingNodeIndexes.put(i, 0);\n }\n } else {\n missingNodeIndexes.put(i, 0);\n }\n }\n i = this.mStructure.getWindowNodeCount();\n for (lookupTableIndex = 0; lookupTableIndex < i; lookupTableIndex++) {\n nodesToProcess.add(this.mStructure.getWindowNodeAt(lookupTableIndex).getRootViewNode());\n }\n while (missingNodeIndexes.size() > 0 && !nodesToProcess.isEmpty()) {\n ViewNode node = (ViewNode) nodesToProcess.removeFirst();\n int i3 = 0;\n while (i3 < missingNodeIndexes.size()) {\n int index = missingNodeIndexes.keyAt(i3);\n AutofillId id = ids[index];\n if (id.equals(node.getAutofillId())) {\n foundNodes[index] = node;\n if (this.mViewNodeLookupTable == null) {\n this.mViewNodeLookupTable = new ArrayMap(ids.length);\n }\n this.mViewNodeLookupTable.put(id, node);\n missingNodeIndexes.removeAt(i3);\n for (i3 = 0; i3 < node.getChildCount(); i3++) {\n nodesToProcess.addLast(node.getChildAt(i3));\n }\n } else {\n i3++;\n }\n }\n while (i3 < node.getChildCount()) {\n }\n }\n while (i2 < missingNodeIndexes.size()) {\n if (this.mViewNodeLookupTable == null) {\n this.mViewNodeLookupTable = new ArrayMap(missingNodeIndexes.size());\n }\n this.mViewNodeLookupTable.put(ids[missingNodeIndexes.keyAt(i2)], null);\n i2++;\n }\n return foundNodes;\n }\n}\n"} {"task_id": "Java_2380", "language": "Java", "task_type": "single_line", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/android/service/autofill/FillContext.java", "mask_start_position": 1667, "mask_end_position": 1690, "canonical_solution": "ringBuilder.toString();", "pre_mask_code": "package android.service.autofill;\n\nimport android.app.assist.AssistStructure;\nimport android.app.assist.AssistStructure.ViewNode;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.Parcelable.Creator;\nimport android.util.ArrayMap;\nimport android.util.SparseIntArray;\nimport android.view.autofill.AutofillId;\nimport android.view.autofill.Helper;\nimport java.util.LinkedList;\n\npublic final class FillContext implements Parcelable {\n\n public static final Creator CREATOR = new Creator() {\n\n public FillContext createFromParcel(Parcel parcel) {\n return new FillContext(parcel, null);\n }\n\n public FillContext[] newArray(int size) {\n return new FillContext[size];\n }\n };\n\n private final int mRequestId;\n\n private final AssistStructure mStructure;\n\n private ArrayMap mViewNodeLookupTable;\n\n public FillContext(int requestId, AssistStructure structure) {\n this.mRequestId = requestId;\n this.mStructure = structure;\n }\n\n private FillContext(Parcel parcel) {\n this(parcel.readInt(), (AssistStructure) parcel.readParcelable(null));\n }\n\n public int getRequestId() {\n return this.mRequestId;\n }\n\n public AssistStructure getStructure() {\n return this.mStructure;\n }\n\n public String toString() {\n if (!Helper.sDebug) {\n return super.toString();\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"FillContext [reqId=\");\n stringBuilder.append(this.mRequestId);\n stringBuilder.append(\"]\");\n return st", "post_mask_code": "\n }\n\n public int describeContents() {\n return 0;\n }\n\n public void writeToParcel(Parcel parcel, int flags) {\n parcel.writeInt(this.mRequestId);\n parcel.writeParcelable(this.mStructure, flags);\n }\n\n /* JADX WARNING: Removed duplicated region for block: B:31:0x0099 A:{LOOP_END, LOOP:4: B:29:0x0093->B:31:0x0099} */\n /* Code decompiled incorrectly, please refer to instructions dump. */\n public ViewNode[] findViewNodesByAutofillIds(AutofillId[] ids) {\n int i;\n int lookupTableIndex;\n LinkedList nodesToProcess = new LinkedList();\n ViewNode[] foundNodes = new ViewNode[ids.length];\n SparseIntArray missingNodeIndexes = new SparseIntArray(ids.length);\n int i2 = 0;\n for (i = 0; i < ids.length; i++) {\n if (this.mViewNodeLookupTable != null) {\n lookupTableIndex = this.mViewNodeLookupTable.indexOfKey(ids[i]);\n if (lookupTableIndex >= 0) {\n foundNodes[i] = (ViewNode) this.mViewNodeLookupTable.valueAt(lookupTableIndex);\n } else {\n missingNodeIndexes.put(i, 0);\n }\n } else {\n missingNodeIndexes.put(i, 0);\n }\n }\n i = this.mStructure.getWindowNodeCount();\n for (lookupTableIndex = 0; lookupTableIndex < i; lookupTableIndex++) {\n nodesToProcess.add(this.mStructure.getWindowNodeAt(lookupTableIndex).getRootViewNode());\n }\n while (missingNodeIndexes.size() > 0 && !nodesToProcess.isEmpty()) {\n ViewNode node = (ViewNode) nodesToProcess.removeFirst();\n int i3 = 0;\n while (i3 < missingNodeIndexes.size()) {\n int index = missingNodeIndexes.keyAt(i3);\n AutofillId id = ids[index];\n if (id.equals(node.getAutofillId())) {\n foundNodes[index] = node;\n if (this.mViewNodeLookupTable == null) {\n this.mViewNodeLookupTable = new ArrayMap(ids.length);\n }\n this.mViewNodeLookupTable.put(id, node);\n missingNodeIndexes.removeAt(i3);\n for (i3 = 0; i3 < node.getChildCount(); i3++) {\n nodesToProcess.addLast(node.getChildAt(i3));\n }\n } else {\n i3++;\n }\n }\n while (i3 < node.getChildCount()) {\n }\n }\n while (i2 < missingNodeIndexes.size()) {\n if (this.mViewNodeLookupTable == null) {\n this.mViewNodeLookupTable = new ArrayMap(missingNodeIndexes.size());\n }\n this.mViewNodeLookupTable.put(ids[missingNodeIndexes.keyAt(i2)], null);\n i2++;\n }\n return foundNodes;\n }\n}\n"} {"task_id": "Java_2381", "language": "Java", "task_type": "for_statement", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/android/service/autofill/FillContext.java", "mask_start_position": 3012, "mask_end_position": 3193, "canonical_solution": "for (lookupTableIndex = 0; lookupTableIndex < i; lookupTableIndex++) {\n nodesToProcess.add(this.mStructure.getWindowNodeAt(lookupTableIndex).getRootViewNode());\n }", "pre_mask_code": "package android.service.autofill;\n\nimport android.app.assist.AssistStructure;\nimport android.app.assist.AssistStructure.ViewNode;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.Parcelable.Creator;\nimport android.util.ArrayMap;\nimport android.util.SparseIntArray;\nimport android.view.autofill.AutofillId;\nimport android.view.autofill.Helper;\nimport java.util.LinkedList;\n\npublic final class FillContext implements Parcelable {\n\n public static final Creator CREATOR = new Creator() {\n\n public FillContext createFromParcel(Parcel parcel) {\n return new FillContext(parcel, null);\n }\n\n public FillContext[] newArray(int size) {\n return new FillContext[size];\n }\n };\n\n private final int mRequestId;\n\n private final AssistStructure mStructure;\n\n private ArrayMap mViewNodeLookupTable;\n\n public FillContext(int requestId, AssistStructure structure) {\n this.mRequestId = requestId;\n this.mStructure = structure;\n }\n\n private FillContext(Parcel parcel) {\n this(parcel.readInt(), (AssistStructure) parcel.readParcelable(null));\n }\n\n public int getRequestId() {\n return this.mRequestId;\n }\n\n public AssistStructure getStructure() {\n return this.mStructure;\n }\n\n public String toString() {\n if (!Helper.sDebug) {\n return super.toString();\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"FillContext [reqId=\");\n stringBuilder.append(this.mRequestId);\n stringBuilder.append(\"]\");\n return stringBuilder.toString();\n }\n\n public int describeContents() {\n return 0;\n }\n\n public void writeToParcel(Parcel parcel, int flags) {\n parcel.writeInt(this.mRequestId);\n parcel.writeParcelable(this.mStructure, flags);\n }\n\n /* JADX WARNING: Removed duplicated region for block: B:31:0x0099 A:{LOOP_END, LOOP:4: B:29:0x0093->B:31:0x0099} */\n /* Code decompiled incorrectly, please refer to instructions dump. */\n public ViewNode[] findViewNodesByAutofillIds(AutofillId[] ids) {\n int i;\n int lookupTableIndex;\n LinkedList nodesToProcess = new LinkedList();\n ViewNode[] foundNodes = new ViewNode[ids.length];\n SparseIntArray missingNodeIndexes = new SparseIntArray(ids.length);\n int i2 = 0;\n for (i = 0; i < ids.length; i++) {\n if (this.mViewNodeLookupTable != null) {\n lookupTableIndex = this.mViewNodeLookupTable.indexOfKey(ids[i]);\n if (lookupTableIndex >= 0) {\n foundNodes[i] = (ViewNode) this.mViewNodeLookupTable.valueAt(lookupTableIndex);\n } else {\n missingNodeIndexes.put(i, 0);\n }\n } else {\n missingNodeIndexes.put(i, 0);\n }\n }\n i = this.mStructure.getWindowNodeCount();\n ", "post_mask_code": "\n while (missingNodeIndexes.size() > 0 && !nodesToProcess.isEmpty()) {\n ViewNode node = (ViewNode) nodesToProcess.removeFirst();\n int i3 = 0;\n while (i3 < missingNodeIndexes.size()) {\n int index = missingNodeIndexes.keyAt(i3);\n AutofillId id = ids[index];\n if (id.equals(node.getAutofillId())) {\n foundNodes[index] = node;\n if (this.mViewNodeLookupTable == null) {\n this.mViewNodeLookupTable = new ArrayMap(ids.length);\n }\n this.mViewNodeLookupTable.put(id, node);\n missingNodeIndexes.removeAt(i3);\n for (i3 = 0; i3 < node.getChildCount(); i3++) {\n nodesToProcess.addLast(node.getChildAt(i3));\n }\n } else {\n i3++;\n }\n }\n while (i3 < node.getChildCount()) {\n }\n }\n while (i2 < missingNodeIndexes.size()) {\n if (this.mViewNodeLookupTable == null) {\n this.mViewNodeLookupTable = new ArrayMap(missingNodeIndexes.size());\n }\n this.mViewNodeLookupTable.put(ids[missingNodeIndexes.keyAt(i2)], null);\n i2++;\n }\n return foundNodes;\n }\n}\n"} {"task_id": "Java_2382", "language": "Java", "task_type": "while_statement", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/android/service/autofill/FillContext.java", "mask_start_position": 4149, "mask_end_position": 4198, "canonical_solution": "while (i3 < node.getChildCount()) {\n }", "pre_mask_code": "package android.service.autofill;\n\nimport android.app.assist.AssistStructure;\nimport android.app.assist.AssistStructure.ViewNode;\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.os.Parcelable.Creator;\nimport android.util.ArrayMap;\nimport android.util.SparseIntArray;\nimport android.view.autofill.AutofillId;\nimport android.view.autofill.Helper;\nimport java.util.LinkedList;\n\npublic final class FillContext implements Parcelable {\n\n public static final Creator CREATOR = new Creator() {\n\n public FillContext createFromParcel(Parcel parcel) {\n return new FillContext(parcel, null);\n }\n\n public FillContext[] newArray(int size) {\n return new FillContext[size];\n }\n };\n\n private final int mRequestId;\n\n private final AssistStructure mStructure;\n\n private ArrayMap mViewNodeLookupTable;\n\n public FillContext(int requestId, AssistStructure structure) {\n this.mRequestId = requestId;\n this.mStructure = structure;\n }\n\n private FillContext(Parcel parcel) {\n this(parcel.readInt(), (AssistStructure) parcel.readParcelable(null));\n }\n\n public int getRequestId() {\n return this.mRequestId;\n }\n\n public AssistStructure getStructure() {\n return this.mStructure;\n }\n\n public String toString() {\n if (!Helper.sDebug) {\n return super.toString();\n }\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"FillContext [reqId=\");\n stringBuilder.append(this.mRequestId);\n stringBuilder.append(\"]\");\n return stringBuilder.toString();\n }\n\n public int describeContents() {\n return 0;\n }\n\n public void writeToParcel(Parcel parcel, int flags) {\n parcel.writeInt(this.mRequestId);\n parcel.writeParcelable(this.mStructure, flags);\n }\n\n /* JADX WARNING: Removed duplicated region for block: B:31:0x0099 A:{LOOP_END, LOOP:4: B:29:0x0093->B:31:0x0099} */\n /* Code decompiled incorrectly, please refer to instructions dump. */\n public ViewNode[] findViewNodesByAutofillIds(AutofillId[] ids) {\n int i;\n int lookupTableIndex;\n LinkedList nodesToProcess = new LinkedList();\n ViewNode[] foundNodes = new ViewNode[ids.length];\n SparseIntArray missingNodeIndexes = new SparseIntArray(ids.length);\n int i2 = 0;\n for (i = 0; i < ids.length; i++) {\n if (this.mViewNodeLookupTable != null) {\n lookupTableIndex = this.mViewNodeLookupTable.indexOfKey(ids[i]);\n if (lookupTableIndex >= 0) {\n foundNodes[i] = (ViewNode) this.mViewNodeLookupTable.valueAt(lookupTableIndex);\n } else {\n missingNodeIndexes.put(i, 0);\n }\n } else {\n missingNodeIndexes.put(i, 0);\n }\n }\n i = this.mStructure.getWindowNodeCount();\n for (lookupTableIndex = 0; lookupTableIndex < i; lookupTableIndex++) {\n nodesToProcess.add(this.mStructure.getWindowNodeAt(lookupTableIndex).getRootViewNode());\n }\n while (missingNodeIndexes.size() > 0 && !nodesToProcess.isEmpty()) {\n ViewNode node = (ViewNode) nodesToProcess.removeFirst();\n int i3 = 0;\n while (i3 < missingNodeIndexes.size()) {\n int index = missingNodeIndexes.keyAt(i3);\n AutofillId id = ids[index];\n if (id.equals(node.getAutofillId())) {\n foundNodes[index] = node;\n if (this.mViewNodeLookupTable == null) {\n this.mViewNodeLookupTable = new ArrayMap(ids.length);\n }\n this.mViewNodeLookupTable.put(id, node);\n missingNodeIndexes.removeAt(i3);\n for (i3 = 0; i3 < node.getChildCount(); i3++) {\n nodesToProcess.addLast(node.getChildAt(i3));\n }\n } else {\n i3++;\n }\n }\n ", "post_mask_code": "\n }\n while (i2 < missingNodeIndexes.size()) {\n if (this.mViewNodeLookupTable == null) {\n this.mViewNodeLookupTable = new ArrayMap(missingNodeIndexes.size());\n }\n this.mViewNodeLookupTable.put(ids[missingNodeIndexes.keyAt(i2)], null);\n i2++;\n }\n return foundNodes;\n }\n}\n"} {"task_id": "Java_2383", "language": "Java", "task_type": "method_signature", "source_file": "java/github/GoogleCloudPlatform/java-docs-samples/healthcare/v1/src/main/java/snippets/healthcare/datasets/DatasetCreate.java", "mask_start_position": 2586, "mask_end_position": 2651, "canonical_solution": "private static CloudHealthcare createClient() throws IOException ", "pre_mask_code": "package snippets.healthcare.datasets;\n\nimport com.google.api.client.http.HttpRequestInitializer;\nimport com.google.api.client.http.javanet.NetHttpTransport;\nimport com.google.api.client.json.JsonFactory;\nimport com.google.api.client.json.jackson2.JacksonFactory;\nimport com.google.api.services.healthcare.v1.CloudHealthcare;\nimport com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets;\nimport com.google.api.services.healthcare.v1.CloudHealthcareScopes;\nimport com.google.api.services.healthcare.v1.model.Dataset;\nimport com.google.api.services.healthcare.v1.model.Operation;\nimport com.google.auth.http.HttpCredentialsAdapter;\nimport com.google.auth.oauth2.GoogleCredentials;\nimport java.io.IOException;\nimport java.util.Collections;\n\npublic class DatasetCreate {\n\n private static final String DATASET_NAME = \"projects/%s/locations/%s/datasets/%s\";\n\n private static final JsonFactory JSON_FACTORY = new JacksonFactory();\n\n private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();\n\n public static void datasetCreate(String projectId, String regionId, String datasetId) throws IOException {\n // Initialize the client, which will be used to interact with the service.\n CloudHealthcare client = createClient();\n // Configure the dataset to be created.\n Dataset dataset = new Dataset();\n dataset.setTimeZone(\"America/Chicago\");\n // Create request and configure any parameters.\n String parentName = String.format(\"projects/%s/locations/%s\", projectId, regionId);\n Datasets.Create request = client.projects().locations().datasets().create(parentName, dataset);\n request.setDatasetId(datasetId);\n // Execute the request, wait for the operation to complete, and process the results.\n try {\n Operation operation = request.execute();\n System.out.println(operation.toPrettyString());\n while (operation.getDone() == null || !operation.getDone()) {\n // Update the status of the operation with another request.\n // Pause for 500ms between requests.\n Thread.sleep(500);\n operation = client.projects().locations().datasets().operations().get(operation.getName()).execute();\n }\n System.out.println(\"Dataset created. Response content: \" + operation.getResponse());\n } catch (Exception ex) {\n System.out.printf(\"Error during request execution: %s\\n\", ex.toString());\n ex.printStackTrace(System.out);\n }\n }\n\n ", "post_mask_code": "{\n // Use Application Default Credentials (ADC) to authenticate the requests\n // For more information see http://example.com\n GoogleCredentials credential = GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));\n // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.\n HttpRequestInitializer requestInitializer = request -> {\n new HttpCredentialsAdapter(credential).initialize(request);\n // 1 minute connect timeout\n request.setConnectTimeout(60000);\n // 1 minute read timeout\n request.setReadTimeout(60000);\n };\n // Build the client for interacting with the service.\n return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer).setApplicationName(\"your-application-name\").build();\n }\n}\n"} {"task_id": "Java_2384", "language": "Java", "task_type": "single_line", "source_file": "java/github/GoogleCloudPlatform/java-docs-samples/healthcare/v1/src/main/java/snippets/healthcare/datasets/DatasetCreate.java", "mask_start_position": 1653, "mask_end_position": 1673, "canonical_solution": "arentName, dataset);", "pre_mask_code": "package snippets.healthcare.datasets;\n\nimport com.google.api.client.http.HttpRequestInitializer;\nimport com.google.api.client.http.javanet.NetHttpTransport;\nimport com.google.api.client.json.JsonFactory;\nimport com.google.api.client.json.jackson2.JacksonFactory;\nimport com.google.api.services.healthcare.v1.CloudHealthcare;\nimport com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets;\nimport com.google.api.services.healthcare.v1.CloudHealthcareScopes;\nimport com.google.api.services.healthcare.v1.model.Dataset;\nimport com.google.api.services.healthcare.v1.model.Operation;\nimport com.google.auth.http.HttpCredentialsAdapter;\nimport com.google.auth.oauth2.GoogleCredentials;\nimport java.io.IOException;\nimport java.util.Collections;\n\npublic class DatasetCreate {\n\n private static final String DATASET_NAME = \"projects/%s/locations/%s/datasets/%s\";\n\n private static final JsonFactory JSON_FACTORY = new JacksonFactory();\n\n private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();\n\n public static void datasetCreate(String projectId, String regionId, String datasetId) throws IOException {\n // Initialize the client, which will be used to interact with the service.\n CloudHealthcare client = createClient();\n // Configure the dataset to be created.\n Dataset dataset = new Dataset();\n dataset.setTimeZone(\"America/Chicago\");\n // Create request and configure any parameters.\n String parentName = String.format(\"projects/%s/locations/%s\", projectId, regionId);\n Datasets.Create request = client.projects().locations().datasets().create(p", "post_mask_code": "\n request.setDatasetId(datasetId);\n // Execute the request, wait for the operation to complete, and process the results.\n try {\n Operation operation = request.execute();\n System.out.println(operation.toPrettyString());\n while (operation.getDone() == null || !operation.getDone()) {\n // Update the status of the operation with another request.\n // Pause for 500ms between requests.\n Thread.sleep(500);\n operation = client.projects().locations().datasets().operations().get(operation.getName()).execute();\n }\n System.out.println(\"Dataset created. Response content: \" + operation.getResponse());\n } catch (Exception ex) {\n System.out.printf(\"Error during request execution: %s\\n\", ex.toString());\n ex.printStackTrace(System.out);\n }\n }\n\n private static CloudHealthcare createClient() throws IOException {\n // Use Application Default Credentials (ADC) to authenticate the requests\n // For more information see http://example.com\n GoogleCredentials credential = GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));\n // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.\n HttpRequestInitializer requestInitializer = request -> {\n new HttpCredentialsAdapter(credential).initialize(request);\n // 1 minute connect timeout\n request.setConnectTimeout(60000);\n // 1 minute read timeout\n request.setReadTimeout(60000);\n };\n // Build the client for interacting with the service.\n return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer).setApplicationName(\"your-application-name\").build();\n }\n}\n"} {"task_id": "Java_2385", "language": "Java", "task_type": "while_statement", "source_file": "java/github/GoogleCloudPlatform/java-docs-samples/healthcare/v1/src/main/java/snippets/healthcare/datasets/DatasetCreate.java", "mask_start_position": 1947, "mask_end_position": 2304, "canonical_solution": "while (operation.getDone() == null || !operation.getDone()) {\n // Update the status of the operation with another request.\n // Pause for 500ms between requests.\n Thread.sleep(500);\n operation = client.projects().locations().datasets().operations().get(operation.getName()).execute();\n }", "pre_mask_code": "package snippets.healthcare.datasets;\n\nimport com.google.api.client.http.HttpRequestInitializer;\nimport com.google.api.client.http.javanet.NetHttpTransport;\nimport com.google.api.client.json.JsonFactory;\nimport com.google.api.client.json.jackson2.JacksonFactory;\nimport com.google.api.services.healthcare.v1.CloudHealthcare;\nimport com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets;\nimport com.google.api.services.healthcare.v1.CloudHealthcareScopes;\nimport com.google.api.services.healthcare.v1.model.Dataset;\nimport com.google.api.services.healthcare.v1.model.Operation;\nimport com.google.auth.http.HttpCredentialsAdapter;\nimport com.google.auth.oauth2.GoogleCredentials;\nimport java.io.IOException;\nimport java.util.Collections;\n\npublic class DatasetCreate {\n\n private static final String DATASET_NAME = \"projects/%s/locations/%s/datasets/%s\";\n\n private static final JsonFactory JSON_FACTORY = new JacksonFactory();\n\n private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();\n\n public static void datasetCreate(String projectId, String regionId, String datasetId) throws IOException {\n // Initialize the client, which will be used to interact with the service.\n CloudHealthcare client = createClient();\n // Configure the dataset to be created.\n Dataset dataset = new Dataset();\n dataset.setTimeZone(\"America/Chicago\");\n // Create request and configure any parameters.\n String parentName = String.format(\"projects/%s/locations/%s\", projectId, regionId);\n Datasets.Create request = client.projects().locations().datasets().create(parentName, dataset);\n request.setDatasetId(datasetId);\n // Execute the request, wait for the operation to complete, and process the results.\n try {\n Operation operation = request.execute();\n System.out.println(operation.toPrettyString());\n ", "post_mask_code": "\n System.out.println(\"Dataset created. Response content: \" + operation.getResponse());\n } catch (Exception ex) {\n System.out.printf(\"Error during request execution: %s\\n\", ex.toString());\n ex.printStackTrace(System.out);\n }\n }\n\n private static CloudHealthcare createClient() throws IOException {\n // Use Application Default Credentials (ADC) to authenticate the requests\n // For more information see http://example.com\n GoogleCredentials credential = GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));\n // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.\n HttpRequestInitializer requestInitializer = request -> {\n new HttpCredentialsAdapter(credential).initialize(request);\n // 1 minute connect timeout\n request.setConnectTimeout(60000);\n // 1 minute read timeout\n request.setReadTimeout(60000);\n };\n // Build the client for interacting with the service.\n return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer).setApplicationName(\"your-application-name\").build();\n }\n}\n"} {"task_id": "Java_2386", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Scandit/barcodescanner-sdk-cordova/src/android/com/mirasense/scanditsdk/plugin/PickerStateMachine.java", "mask_start_position": 1593, "mask_end_position": 1653, "canonical_solution": "private void updateSettingsState(ScanSettings scanSettings) ", "pre_mask_code": "package com.mirasense.scanditsdk.plugin;\n\nimport com.scandit.barcodepicker.ScanSession;\nimport com.scandit.barcodepicker.ScanSettings;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.Map;\n\n/**\n * @brief Simple state machine for managing the different states of the barcode picker\n */\nclass PickerStateMachine {\n\n // must match values of JS wrapper\n public final static int STOPPED = 2;\n\n public final static int PAUSED = 1;\n\n public final static int ACTIVE = 3;\n\n private final BarcodePickerWithSearchBar mPicker;\n\n private int mCurrentState = STOPPED;\n\n private WeakReference mCallback;\n\n private boolean mMatrixScanEnabled = false;\n\n /**\n * Create a new picker state machine.\n * @param picker The picker for which to control the states. Must not be null.\n * @param scanSettings The initial scan settings, used to set parts of the initial state.\n * @param callback The state change callback gets invoked whenever the state of the picker\n * changes. The callback is stored as a weak reference, so make sure to keep a\n * reference to the object around.\n */\n PickerStateMachine(BarcodePickerWithSearchBar picker, ScanSettings scanSettings, Callback callback) {\n mPicker = picker;\n mCallback = new WeakReference(callback);\n updateSettingsState(scanSettings);\n }\n\n public void applyScanSettings(ScanSettings scanSettings) {\n mPicker.applyScanSettings(scanSettings);\n updateSettingsState(scanSettings);\n }\n\n ", "post_mask_code": "{\n if (mMatrixScanEnabled != scanSettings.isMatrixScanEnabled()) {\n mMatrixScanEnabled = scanSettings.isMatrixScanEnabled();\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerSwitchedMatrixScanState(mPicker, mMatrixScanEnabled);\n }\n }\n }\n\n public int getState() {\n return mCurrentState;\n }\n\n public int setState(int state) {\n if (mCurrentState == state) {\n return state;\n }\n switch(state) {\n case ACTIVE:\n transitionToActiveState(false);\n break;\n case PAUSED:\n transitionToPausedState();\n break;\n case STOPPED:\n transitionToStoppedState();\n break;\n }\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, state);\n }\n mCurrentState = state;\n return state;\n }\n\n public boolean isMatrixScanEnabled() {\n return mMatrixScanEnabled;\n }\n\n protected void setTrackedCodeStates(Map trackedCodeStates) {\n mPicker.setTrackedCodeStates(trackedCodeStates);\n }\n\n public void startScanning(boolean paused) {\n if (mCurrentState == ACTIVE) {\n return;\n }\n if (!paused) {\n transitionToActiveState(true);\n mCurrentState = ACTIVE;\n } else {\n transitionToPausedState();\n mCurrentState = PAUSED;\n }\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, mCurrentState);\n }\n }\n\n private void transitionToStoppedState() {\n if (mCurrentState == ACTIVE || mCurrentState == PAUSED) {\n mPicker.stopScanning();\n }\n }\n\n private void transitionToPausedState() {\n if (mCurrentState == ACTIVE) {\n mPicker.pauseScanning();\n return;\n }\n if (mCurrentState == STOPPED) {\n mPicker.startScanning(true);\n }\n }\n\n private void transitionToActiveState(boolean useStartInsteadOfResume) {\n if (mCurrentState == STOPPED) {\n mPicker.startScanning();\n }\n if (mCurrentState == PAUSED) {\n if (useStartInsteadOfResume) {\n mPicker.startScanning();\n } else {\n mPicker.resumeScanning();\n }\n }\n }\n\n public BarcodePickerWithSearchBar getPicker() {\n return mPicker;\n }\n\n /**\n * Implements the logic of handling picker state changes sent from the didScan callback.\n * @param nextState The next state.\n * @param session The implementation calls stopScanning/pauseScanning if the provided session\n * is non-null.\n */\n public void switchToNextScanState(int nextState, ScanSession session) {\n if (nextState == STOPPED) {\n if (mCurrentState == ACTIVE || mCurrentState == PAUSED) {\n if (session != null) {\n session.stopScanning();\n } else {\n mPicker.stopScanning();\n }\n }\n mCurrentState = STOPPED;\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, STOPPED);\n }\n return;\n }\n if (nextState == PAUSED) {\n if (mCurrentState == ACTIVE) {\n if (session != null) {\n session.pauseScanning();\n } else {\n mPicker.pauseScanning();\n }\n }\n mCurrentState = PAUSED;\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, PAUSED);\n }\n }\n }\n\n interface Callback {\n\n /**\n * Invoked whenever the state of the barcode picker changes to a new state.\n *\n * @param picker The picker\n * @param newState the new state of the picker\n */\n void pickerEnteredState(BarcodePickerWithSearchBar picker, int newState);\n\n /**\n * Invoked whenever the picker starts or stops using matrix scan.\n *\n * @param picker The picker\n * @param matrixScan Whether matrix scan is enabled.\n */\n void pickerSwitchedMatrixScanState(BarcodePickerWithSearchBar picker, boolean matrixScan);\n }\n}\n"} {"task_id": "Java_2387", "language": "Java", "task_type": "method_body", "source_file": "java/github/Scandit/barcodescanner-sdk-cordova/src/android/com/mirasense/scanditsdk/plugin/PickerStateMachine.java", "mask_start_position": 2933, "mask_end_position": 3347, "canonical_solution": "{\n if (mCurrentState == ACTIVE) {\n return;\n }\n if (!paused) {\n transitionToActiveState(true);\n mCurrentState = ACTIVE;\n } else {\n transitionToPausedState();\n mCurrentState = PAUSED;\n }\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, mCurrentState);\n }\n }", "pre_mask_code": "package com.mirasense.scanditsdk.plugin;\n\nimport com.scandit.barcodepicker.ScanSession;\nimport com.scandit.barcodepicker.ScanSettings;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.Map;\n\n/**\n * @brief Simple state machine for managing the different states of the barcode picker\n */\nclass PickerStateMachine {\n\n // must match values of JS wrapper\n public final static int STOPPED = 2;\n\n public final static int PAUSED = 1;\n\n public final static int ACTIVE = 3;\n\n private final BarcodePickerWithSearchBar mPicker;\n\n private int mCurrentState = STOPPED;\n\n private WeakReference mCallback;\n\n private boolean mMatrixScanEnabled = false;\n\n /**\n * Create a new picker state machine.\n * @param picker The picker for which to control the states. Must not be null.\n * @param scanSettings The initial scan settings, used to set parts of the initial state.\n * @param callback The state change callback gets invoked whenever the state of the picker\n * changes. The callback is stored as a weak reference, so make sure to keep a\n * reference to the object around.\n */\n PickerStateMachine(BarcodePickerWithSearchBar picker, ScanSettings scanSettings, Callback callback) {\n mPicker = picker;\n mCallback = new WeakReference(callback);\n updateSettingsState(scanSettings);\n }\n\n public void applyScanSettings(ScanSettings scanSettings) {\n mPicker.applyScanSettings(scanSettings);\n updateSettingsState(scanSettings);\n }\n\n private void updateSettingsState(ScanSettings scanSettings) {\n if (mMatrixScanEnabled != scanSettings.isMatrixScanEnabled()) {\n mMatrixScanEnabled = scanSettings.isMatrixScanEnabled();\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerSwitchedMatrixScanState(mPicker, mMatrixScanEnabled);\n }\n }\n }\n\n public int getState() {\n return mCurrentState;\n }\n\n public int setState(int state) {\n if (mCurrentState == state) {\n return state;\n }\n switch(state) {\n case ACTIVE:\n transitionToActiveState(false);\n break;\n case PAUSED:\n transitionToPausedState();\n break;\n case STOPPED:\n transitionToStoppedState();\n break;\n }\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, state);\n }\n mCurrentState = state;\n return state;\n }\n\n public boolean isMatrixScanEnabled() {\n return mMatrixScanEnabled;\n }\n\n protected void setTrackedCodeStates(Map trackedCodeStates) {\n mPicker.setTrackedCodeStates(trackedCodeStates);\n }\n\n public void startScanning(boolean paused) ", "post_mask_code": "\n\n private void transitionToStoppedState() {\n if (mCurrentState == ACTIVE || mCurrentState == PAUSED) {\n mPicker.stopScanning();\n }\n }\n\n private void transitionToPausedState() {\n if (mCurrentState == ACTIVE) {\n mPicker.pauseScanning();\n return;\n }\n if (mCurrentState == STOPPED) {\n mPicker.startScanning(true);\n }\n }\n\n private void transitionToActiveState(boolean useStartInsteadOfResume) {\n if (mCurrentState == STOPPED) {\n mPicker.startScanning();\n }\n if (mCurrentState == PAUSED) {\n if (useStartInsteadOfResume) {\n mPicker.startScanning();\n } else {\n mPicker.resumeScanning();\n }\n }\n }\n\n public BarcodePickerWithSearchBar getPicker() {\n return mPicker;\n }\n\n /**\n * Implements the logic of handling picker state changes sent from the didScan callback.\n * @param nextState The next state.\n * @param session The implementation calls stopScanning/pauseScanning if the provided session\n * is non-null.\n */\n public void switchToNextScanState(int nextState, ScanSession session) {\n if (nextState == STOPPED) {\n if (mCurrentState == ACTIVE || mCurrentState == PAUSED) {\n if (session != null) {\n session.stopScanning();\n } else {\n mPicker.stopScanning();\n }\n }\n mCurrentState = STOPPED;\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, STOPPED);\n }\n return;\n }\n if (nextState == PAUSED) {\n if (mCurrentState == ACTIVE) {\n if (session != null) {\n session.pauseScanning();\n } else {\n mPicker.pauseScanning();\n }\n }\n mCurrentState = PAUSED;\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, PAUSED);\n }\n }\n }\n\n interface Callback {\n\n /**\n * Invoked whenever the state of the barcode picker changes to a new state.\n *\n * @param picker The picker\n * @param newState the new state of the picker\n */\n void pickerEnteredState(BarcodePickerWithSearchBar picker, int newState);\n\n /**\n * Invoked whenever the picker starts or stops using matrix scan.\n *\n * @param picker The picker\n * @param matrixScan Whether matrix scan is enabled.\n */\n void pickerSwitchedMatrixScanState(BarcodePickerWithSearchBar picker, boolean matrixScan);\n }\n}\n"} {"task_id": "Java_2388", "language": "Java", "task_type": "single_line", "source_file": "java/github/Scandit/barcodescanner-sdk-cordova/src/android/com/mirasense/scanditsdk/plugin/PickerStateMachine.java", "mask_start_position": 3245, "mask_end_position": 3246, "canonical_solution": ";", "pre_mask_code": "package com.mirasense.scanditsdk.plugin;\n\nimport com.scandit.barcodepicker.ScanSession;\nimport com.scandit.barcodepicker.ScanSettings;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.Map;\n\n/**\n * @brief Simple state machine for managing the different states of the barcode picker\n */\nclass PickerStateMachine {\n\n // must match values of JS wrapper\n public final static int STOPPED = 2;\n\n public final static int PAUSED = 1;\n\n public final static int ACTIVE = 3;\n\n private final BarcodePickerWithSearchBar mPicker;\n\n private int mCurrentState = STOPPED;\n\n private WeakReference mCallback;\n\n private boolean mMatrixScanEnabled = false;\n\n /**\n * Create a new picker state machine.\n * @param picker The picker for which to control the states. Must not be null.\n * @param scanSettings The initial scan settings, used to set parts of the initial state.\n * @param callback The state change callback gets invoked whenever the state of the picker\n * changes. The callback is stored as a weak reference, so make sure to keep a\n * reference to the object around.\n */\n PickerStateMachine(BarcodePickerWithSearchBar picker, ScanSettings scanSettings, Callback callback) {\n mPicker = picker;\n mCallback = new WeakReference(callback);\n updateSettingsState(scanSettings);\n }\n\n public void applyScanSettings(ScanSettings scanSettings) {\n mPicker.applyScanSettings(scanSettings);\n updateSettingsState(scanSettings);\n }\n\n private void updateSettingsState(ScanSettings scanSettings) {\n if (mMatrixScanEnabled != scanSettings.isMatrixScanEnabled()) {\n mMatrixScanEnabled = scanSettings.isMatrixScanEnabled();\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerSwitchedMatrixScanState(mPicker, mMatrixScanEnabled);\n }\n }\n }\n\n public int getState() {\n return mCurrentState;\n }\n\n public int setState(int state) {\n if (mCurrentState == state) {\n return state;\n }\n switch(state) {\n case ACTIVE:\n transitionToActiveState(false);\n break;\n case PAUSED:\n transitionToPausedState();\n break;\n case STOPPED:\n transitionToStoppedState();\n break;\n }\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, state);\n }\n mCurrentState = state;\n return state;\n }\n\n public boolean isMatrixScanEnabled() {\n return mMatrixScanEnabled;\n }\n\n protected void setTrackedCodeStates(Map trackedCodeStates) {\n mPicker.setTrackedCodeStates(trackedCodeStates);\n }\n\n public void startScanning(boolean paused) {\n if (mCurrentState == ACTIVE) {\n return;\n }\n if (!paused) {\n transitionToActiveState(true);\n mCurrentState = ACTIVE;\n } else {\n transitionToPausedState();\n mCurrentState = PAUSED;\n }\n Callback cb = mCallback.get()", "post_mask_code": "\n if (cb != null) {\n cb.pickerEnteredState(mPicker, mCurrentState);\n }\n }\n\n private void transitionToStoppedState() {\n if (mCurrentState == ACTIVE || mCurrentState == PAUSED) {\n mPicker.stopScanning();\n }\n }\n\n private void transitionToPausedState() {\n if (mCurrentState == ACTIVE) {\n mPicker.pauseScanning();\n return;\n }\n if (mCurrentState == STOPPED) {\n mPicker.startScanning(true);\n }\n }\n\n private void transitionToActiveState(boolean useStartInsteadOfResume) {\n if (mCurrentState == STOPPED) {\n mPicker.startScanning();\n }\n if (mCurrentState == PAUSED) {\n if (useStartInsteadOfResume) {\n mPicker.startScanning();\n } else {\n mPicker.resumeScanning();\n }\n }\n }\n\n public BarcodePickerWithSearchBar getPicker() {\n return mPicker;\n }\n\n /**\n * Implements the logic of handling picker state changes sent from the didScan callback.\n * @param nextState The next state.\n * @param session The implementation calls stopScanning/pauseScanning if the provided session\n * is non-null.\n */\n public void switchToNextScanState(int nextState, ScanSession session) {\n if (nextState == STOPPED) {\n if (mCurrentState == ACTIVE || mCurrentState == PAUSED) {\n if (session != null) {\n session.stopScanning();\n } else {\n mPicker.stopScanning();\n }\n }\n mCurrentState = STOPPED;\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, STOPPED);\n }\n return;\n }\n if (nextState == PAUSED) {\n if (mCurrentState == ACTIVE) {\n if (session != null) {\n session.pauseScanning();\n } else {\n mPicker.pauseScanning();\n }\n }\n mCurrentState = PAUSED;\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, PAUSED);\n }\n }\n }\n\n interface Callback {\n\n /**\n * Invoked whenever the state of the barcode picker changes to a new state.\n *\n * @param picker The picker\n * @param newState the new state of the picker\n */\n void pickerEnteredState(BarcodePickerWithSearchBar picker, int newState);\n\n /**\n * Invoked whenever the picker starts or stops using matrix scan.\n *\n * @param picker The picker\n * @param matrixScan Whether matrix scan is enabled.\n */\n void pickerSwitchedMatrixScanState(BarcodePickerWithSearchBar picker, boolean matrixScan);\n }\n}\n"} {"task_id": "Java_2389", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Scandit/barcodescanner-sdk-cordova/src/android/com/mirasense/scanditsdk/plugin/PickerStateMachine.java", "mask_start_position": 5789, "mask_end_position": 5862, "canonical_solution": "void pickerEnteredState(BarcodePickerWithSearchBar picker, int newState);", "pre_mask_code": "package com.mirasense.scanditsdk.plugin;\n\nimport com.scandit.barcodepicker.ScanSession;\nimport com.scandit.barcodepicker.ScanSettings;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.Map;\n\n/**\n * @brief Simple state machine for managing the different states of the barcode picker\n */\nclass PickerStateMachine {\n\n // must match values of JS wrapper\n public final static int STOPPED = 2;\n\n public final static int PAUSED = 1;\n\n public final static int ACTIVE = 3;\n\n private final BarcodePickerWithSearchBar mPicker;\n\n private int mCurrentState = STOPPED;\n\n private WeakReference mCallback;\n\n private boolean mMatrixScanEnabled = false;\n\n /**\n * Create a new picker state machine.\n * @param picker The picker for which to control the states. Must not be null.\n * @param scanSettings The initial scan settings, used to set parts of the initial state.\n * @param callback The state change callback gets invoked whenever the state of the picker\n * changes. The callback is stored as a weak reference, so make sure to keep a\n * reference to the object around.\n */\n PickerStateMachine(BarcodePickerWithSearchBar picker, ScanSettings scanSettings, Callback callback) {\n mPicker = picker;\n mCallback = new WeakReference(callback);\n updateSettingsState(scanSettings);\n }\n\n public void applyScanSettings(ScanSettings scanSettings) {\n mPicker.applyScanSettings(scanSettings);\n updateSettingsState(scanSettings);\n }\n\n private void updateSettingsState(ScanSettings scanSettings) {\n if (mMatrixScanEnabled != scanSettings.isMatrixScanEnabled()) {\n mMatrixScanEnabled = scanSettings.isMatrixScanEnabled();\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerSwitchedMatrixScanState(mPicker, mMatrixScanEnabled);\n }\n }\n }\n\n public int getState() {\n return mCurrentState;\n }\n\n public int setState(int state) {\n if (mCurrentState == state) {\n return state;\n }\n switch(state) {\n case ACTIVE:\n transitionToActiveState(false);\n break;\n case PAUSED:\n transitionToPausedState();\n break;\n case STOPPED:\n transitionToStoppedState();\n break;\n }\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, state);\n }\n mCurrentState = state;\n return state;\n }\n\n public boolean isMatrixScanEnabled() {\n return mMatrixScanEnabled;\n }\n\n protected void setTrackedCodeStates(Map trackedCodeStates) {\n mPicker.setTrackedCodeStates(trackedCodeStates);\n }\n\n public void startScanning(boolean paused) {\n if (mCurrentState == ACTIVE) {\n return;\n }\n if (!paused) {\n transitionToActiveState(true);\n mCurrentState = ACTIVE;\n } else {\n transitionToPausedState();\n mCurrentState = PAUSED;\n }\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, mCurrentState);\n }\n }\n\n private void transitionToStoppedState() {\n if (mCurrentState == ACTIVE || mCurrentState == PAUSED) {\n mPicker.stopScanning();\n }\n }\n\n private void transitionToPausedState() {\n if (mCurrentState == ACTIVE) {\n mPicker.pauseScanning();\n return;\n }\n if (mCurrentState == STOPPED) {\n mPicker.startScanning(true);\n }\n }\n\n private void transitionToActiveState(boolean useStartInsteadOfResume) {\n if (mCurrentState == STOPPED) {\n mPicker.startScanning();\n }\n if (mCurrentState == PAUSED) {\n if (useStartInsteadOfResume) {\n mPicker.startScanning();\n } else {\n mPicker.resumeScanning();\n }\n }\n }\n\n public BarcodePickerWithSearchBar getPicker() {\n return mPicker;\n }\n\n /**\n * Implements the logic of handling picker state changes sent from the didScan callback.\n * @param nextState The next state.\n * @param session The implementation calls stopScanning/pauseScanning if the provided session\n * is non-null.\n */\n public void switchToNextScanState(int nextState, ScanSession session) {\n if (nextState == STOPPED) {\n if (mCurrentState == ACTIVE || mCurrentState == PAUSED) {\n if (session != null) {\n session.stopScanning();\n } else {\n mPicker.stopScanning();\n }\n }\n mCurrentState = STOPPED;\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, STOPPED);\n }\n return;\n }\n if (nextState == PAUSED) {\n if (mCurrentState == ACTIVE) {\n if (session != null) {\n session.pauseScanning();\n } else {\n mPicker.pauseScanning();\n }\n }\n mCurrentState = PAUSED;\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, PAUSED);\n }\n }\n }\n\n interface Callback {\n\n /**\n * Invoked whenever the state of the barcode picker changes to a new state.\n *\n * @param picker The picker\n * @param newState the new state of the picker\n */\n ", "post_mask_code": "\n\n /**\n * Invoked whenever the picker starts or stops using matrix scan.\n *\n * @param picker The picker\n * @param matrixScan Whether matrix scan is enabled.\n */\n void pickerSwitchedMatrixScanState(BarcodePickerWithSearchBar picker, boolean matrixScan);\n }\n}\n"} {"task_id": "Java_2390", "language": "Java", "task_type": "switch_case", "source_file": "java/github/Scandit/barcodescanner-sdk-cordova/src/android/com/mirasense/scanditsdk/plugin/PickerStateMachine.java", "mask_start_position": 2163, "mask_end_position": 2468, "canonical_solution": "switch(state) {\n case ACTIVE:\n transitionToActiveState(false);\n break;\n case PAUSED:\n transitionToPausedState();\n break;\n case STOPPED:\n transitionToStoppedState();\n break;\n }", "pre_mask_code": "package com.mirasense.scanditsdk.plugin;\n\nimport com.scandit.barcodepicker.ScanSession;\nimport com.scandit.barcodepicker.ScanSettings;\nimport org.json.JSONObject;\nimport java.lang.ref.WeakReference;\nimport java.util.Map;\n\n/**\n * @brief Simple state machine for managing the different states of the barcode picker\n */\nclass PickerStateMachine {\n\n // must match values of JS wrapper\n public final static int STOPPED = 2;\n\n public final static int PAUSED = 1;\n\n public final static int ACTIVE = 3;\n\n private final BarcodePickerWithSearchBar mPicker;\n\n private int mCurrentState = STOPPED;\n\n private WeakReference mCallback;\n\n private boolean mMatrixScanEnabled = false;\n\n /**\n * Create a new picker state machine.\n * @param picker The picker for which to control the states. Must not be null.\n * @param scanSettings The initial scan settings, used to set parts of the initial state.\n * @param callback The state change callback gets invoked whenever the state of the picker\n * changes. The callback is stored as a weak reference, so make sure to keep a\n * reference to the object around.\n */\n PickerStateMachine(BarcodePickerWithSearchBar picker, ScanSettings scanSettings, Callback callback) {\n mPicker = picker;\n mCallback = new WeakReference(callback);\n updateSettingsState(scanSettings);\n }\n\n public void applyScanSettings(ScanSettings scanSettings) {\n mPicker.applyScanSettings(scanSettings);\n updateSettingsState(scanSettings);\n }\n\n private void updateSettingsState(ScanSettings scanSettings) {\n if (mMatrixScanEnabled != scanSettings.isMatrixScanEnabled()) {\n mMatrixScanEnabled = scanSettings.isMatrixScanEnabled();\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerSwitchedMatrixScanState(mPicker, mMatrixScanEnabled);\n }\n }\n }\n\n public int getState() {\n return mCurrentState;\n }\n\n public int setState(int state) {\n if (mCurrentState == state) {\n return state;\n }\n ", "post_mask_code": "\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, state);\n }\n mCurrentState = state;\n return state;\n }\n\n public boolean isMatrixScanEnabled() {\n return mMatrixScanEnabled;\n }\n\n protected void setTrackedCodeStates(Map trackedCodeStates) {\n mPicker.setTrackedCodeStates(trackedCodeStates);\n }\n\n public void startScanning(boolean paused) {\n if (mCurrentState == ACTIVE) {\n return;\n }\n if (!paused) {\n transitionToActiveState(true);\n mCurrentState = ACTIVE;\n } else {\n transitionToPausedState();\n mCurrentState = PAUSED;\n }\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, mCurrentState);\n }\n }\n\n private void transitionToStoppedState() {\n if (mCurrentState == ACTIVE || mCurrentState == PAUSED) {\n mPicker.stopScanning();\n }\n }\n\n private void transitionToPausedState() {\n if (mCurrentState == ACTIVE) {\n mPicker.pauseScanning();\n return;\n }\n if (mCurrentState == STOPPED) {\n mPicker.startScanning(true);\n }\n }\n\n private void transitionToActiveState(boolean useStartInsteadOfResume) {\n if (mCurrentState == STOPPED) {\n mPicker.startScanning();\n }\n if (mCurrentState == PAUSED) {\n if (useStartInsteadOfResume) {\n mPicker.startScanning();\n } else {\n mPicker.resumeScanning();\n }\n }\n }\n\n public BarcodePickerWithSearchBar getPicker() {\n return mPicker;\n }\n\n /**\n * Implements the logic of handling picker state changes sent from the didScan callback.\n * @param nextState The next state.\n * @param session The implementation calls stopScanning/pauseScanning if the provided session\n * is non-null.\n */\n public void switchToNextScanState(int nextState, ScanSession session) {\n if (nextState == STOPPED) {\n if (mCurrentState == ACTIVE || mCurrentState == PAUSED) {\n if (session != null) {\n session.stopScanning();\n } else {\n mPicker.stopScanning();\n }\n }\n mCurrentState = STOPPED;\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, STOPPED);\n }\n return;\n }\n if (nextState == PAUSED) {\n if (mCurrentState == ACTIVE) {\n if (session != null) {\n session.pauseScanning();\n } else {\n mPicker.pauseScanning();\n }\n }\n mCurrentState = PAUSED;\n Callback cb = mCallback.get();\n if (cb != null) {\n cb.pickerEnteredState(mPicker, PAUSED);\n }\n }\n }\n\n interface Callback {\n\n /**\n * Invoked whenever the state of the barcode picker changes to a new state.\n *\n * @param picker The picker\n * @param newState the new state of the picker\n */\n void pickerEnteredState(BarcodePickerWithSearchBar picker, int newState);\n\n /**\n * Invoked whenever the picker starts or stops using matrix scan.\n *\n * @param picker The picker\n * @param matrixScan Whether matrix scan is enabled.\n */\n void pickerSwitchedMatrixScanState(BarcodePickerWithSearchBar picker, boolean matrixScan);\n }\n}\n"} {"task_id": "Java_2391", "language": "Java", "task_type": "method_signature", "source_file": "java/github/JakeWharton/u2020/app/src/internalDebug/java/com/jakewharton/u2020/data/DebugDataModule.java", "mask_start_position": 4487, "mask_end_position": 4627, "canonical_solution": "@Provides\n @Singleton\n @NetworkVariancePercent\n Preference provideNetworkVariancePercent(RxSharedPreferences preferences) ", "pre_mask_code": "package com.jakewharton.u2020.data;\n\nimport android.app.Application;\nimport android.content.SharedPreferences;\nimport com.f2prateek.rx.preferences.Preference;\nimport com.f2prateek.rx.preferences.RxSharedPreferences;\nimport com.jakewharton.picasso.OkHttp3Downloader;\nimport com.jakewharton.u2020.IsInstrumentationTest;\nimport com.jakewharton.u2020.data.api.DebugApiModule;\nimport com.jakewharton.u2020.data.api.oauth.AccessToken;\nimport com.jakewharton.u2020.data.prefs.InetSocketAddressPreferenceAdapter;\nimport com.jakewharton.u2020.intentfactory.CapturingIntentFactory;\nimport com.jakewharton.u2020.intentfactory.IntentFactory;\nimport com.squareup.picasso.Picasso;\nimport dagger.Module;\nimport dagger.Provides;\nimport java.net.InetSocketAddress;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport javax.inject.Singleton;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLSocketFactory;\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.X509TrustManager;\nimport okhttp3.OkHttpClient;\nimport retrofit2.mock.NetworkBehavior;\nimport timber.log.Timber;\n\n@Module(includes = DebugApiModule.class, complete = false, library = true, overrides = true)\npublic final class DebugDataModule {\n\n private static final int DEFAULT_ANIMATION_SPEED = 1;\n\n // Debug indicators displayed\n private static final boolean DEFAULT_PICASSO_DEBUGGING = false;\n\n // No pixel grid overlay.\n private static final boolean DEFAULT_PIXEL_GRID_ENABLED = false;\n\n // No pixel ratio overlay.\n private static final boolean DEFAULT_PIXEL_RATIO_ENABLED = false;\n\n // No crazy 3D view tree.\n private static final boolean DEFAULT_SCALPEL_ENABLED = false;\n\n // Draw views by default.\n private static final boolean DEFAULT_SCALPEL_WIREFRAME_ENABLED = false;\n\n // Show debug drawer first time.\n private static final boolean DEFAULT_SEEN_DEBUG_DRAWER = false;\n\n // Capture external intents.\n private static final boolean DEFAULT_CAPTURE_INTENTS = true;\n\n @Provides\n @Singleton\n RxSharedPreferences provideRxSharedPreferences(SharedPreferences prefs) {\n return RxSharedPreferences.create(prefs);\n }\n\n @Provides\n @Singleton\n IntentFactory provideIntentFactory(@IsMockMode boolean isMockMode, @CaptureIntents Preference captureIntents) {\n return new CapturingIntentFactory(IntentFactory.REAL, () -> isMockMode && captureIntents.get());\n }\n\n @Provides\n @Singleton\n OkHttpClient provideOkHttpClient(Application app, Preference networkProxyAddress) {\n return DataModule.createOkHttpClient(app).sslSocketFactory(createBadSslSocketFactory()).proxy(InetSocketAddressPreferenceAdapter.createProxy(networkProxyAddress.get())).build();\n }\n\n @Provides\n @Singleton\n @AccessToken\n Preference provideAccessToken(RxSharedPreferences prefs, @ApiEndpoint Preference endpoint) {\n // Return an endpoint-specific preference.\n return prefs.getString(\"access-token-\" + endpoint.get());\n }\n\n @Provides\n @Singleton\n @ApiEndpoint\n Preference provideEndpointPreference(RxSharedPreferences preferences) {\n return preferences.getString(\"debug_endpoint\", ApiEndpoints.MOCK_MODE.url);\n }\n\n @Provides\n @Singleton\n @IsMockMode\n boolean provideIsMockMode(@ApiEndpoint Preference endpoint, @IsInstrumentationTest boolean isInstrumentationTest) {\n // Running in an instrumentation forces mock mode.\n return isInstrumentationTest || ApiEndpoints.isMockMode(endpoint.get());\n }\n\n @Provides\n @Singleton\n @NetworkDelay\n Preference provideNetworkDelay(RxSharedPreferences preferences) {\n return preferences.getLong(\"debug_network_delay\", 2000l);\n }\n\n @Provides\n @Singleton\n @NetworkFailurePercent\n Preference provideNetworkFailurePercent(RxSharedPreferences preferences) {\n return preferences.getInteger(\"debug_network_failure_percent\", 3);\n }\n\n @Provides\n @Singleton\n @NetworkErrorPercent\n Preference provideNetworkErrorPercent(RxSharedPreferences preferences) {\n return preferences.getInteger(\"debug_network_error_percent\", 0);\n }\n\n @Provides\n @Singleton\n Preference provideNetworkErrorCode(RxSharedPreferences preferences) {\n return preferences.getEnum(\"debug_network_error_code\", NetworkErrorCode.HTTP_500, NetworkErrorCode.class);\n }\n\n ", "post_mask_code": "{\n return preferences.getInteger(\"debug_network_variance_percent\", 40);\n }\n\n @Provides\n @Singleton\n Preference provideNetworkProxyAddress(RxSharedPreferences preferences) {\n return preferences.getObject(\"debug_network_proxy\", InetSocketAddressPreferenceAdapter.INSTANCE);\n }\n\n @Provides\n @Singleton\n @CaptureIntents\n Preference provideCaptureIntentsPreference(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_capture_intents\", DEFAULT_CAPTURE_INTENTS);\n }\n\n @Provides\n @Singleton\n @AnimationSpeed\n Preference provideAnimationSpeed(RxSharedPreferences preferences) {\n return preferences.getInteger(\"debug_animation_speed\", DEFAULT_ANIMATION_SPEED);\n }\n\n @Provides\n @Singleton\n @PicassoDebugging\n Preference providePicassoDebugging(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_picasso_debugging\", DEFAULT_PICASSO_DEBUGGING);\n }\n\n @Provides\n @Singleton\n @PixelGridEnabled\n Preference providePixelGridEnabled(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_pixel_grid_enabled\", DEFAULT_PIXEL_GRID_ENABLED);\n }\n\n @Provides\n @Singleton\n @PixelRatioEnabled\n Preference providePixelRatioEnabled(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_pixel_ratio_enabled\", DEFAULT_PIXEL_RATIO_ENABLED);\n }\n\n @Provides\n @Singleton\n @SeenDebugDrawer\n Preference provideSeenDebugDrawer(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_seen_debug_drawer\", DEFAULT_SEEN_DEBUG_DRAWER);\n }\n\n @Provides\n @Singleton\n @ScalpelEnabled\n Preference provideScalpelEnabled(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_scalpel_enabled\", DEFAULT_SCALPEL_ENABLED);\n }\n\n @Provides\n @Singleton\n @ScalpelWireframeEnabled\n Preference provideScalpelWireframeEnabled(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_scalpel_wireframe_drawer\", DEFAULT_SCALPEL_WIREFRAME_ENABLED);\n }\n\n @Provides\n @Singleton\n Picasso providePicasso(OkHttpClient client, NetworkBehavior behavior, @IsMockMode boolean isMockMode, Application app) {\n Picasso.Builder builder = new Picasso.Builder(app).downloader(new OkHttp3Downloader(client));\n if (isMockMode) {\n builder.addRequestHandler(new MockRequestHandler(behavior, app.getAssets()));\n }\n builder.listener((picasso, uri, exception) -> {\n Timber.e(exception, \"Error while loading image %s\", uri);\n });\n return builder.build();\n }\n\n private static SSLSocketFactory createBadSslSocketFactory() {\n try {\n // Construct SSLSocketFactory that accepts any cert.\n SSLContext context = SSLContext.getInstance(\"TLS\");\n TrustManager permissive = new X509TrustManager() {\n\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n };\n context.init(null, new TrustManager[] { permissive }, null);\n return context.getSocketFactory();\n } catch (Exception e) {\n throw new AssertionError(e);\n }\n }\n}\n"} {"task_id": "Java_2392", "language": "Java", "task_type": "method_body", "source_file": "java/github/JakeWharton/u2020/app/src/internalDebug/java/com/jakewharton/u2020/data/DebugDataModule.java", "mask_start_position": 6017, "mask_end_position": 6121, "canonical_solution": "{\n return preferences.getBoolean(\"debug_pixel_ratio_enabled\", DEFAULT_PIXEL_RATIO_ENABLED);\n }", "pre_mask_code": "package com.jakewharton.u2020.data;\n\nimport android.app.Application;\nimport android.content.SharedPreferences;\nimport com.f2prateek.rx.preferences.Preference;\nimport com.f2prateek.rx.preferences.RxSharedPreferences;\nimport com.jakewharton.picasso.OkHttp3Downloader;\nimport com.jakewharton.u2020.IsInstrumentationTest;\nimport com.jakewharton.u2020.data.api.DebugApiModule;\nimport com.jakewharton.u2020.data.api.oauth.AccessToken;\nimport com.jakewharton.u2020.data.prefs.InetSocketAddressPreferenceAdapter;\nimport com.jakewharton.u2020.intentfactory.CapturingIntentFactory;\nimport com.jakewharton.u2020.intentfactory.IntentFactory;\nimport com.squareup.picasso.Picasso;\nimport dagger.Module;\nimport dagger.Provides;\nimport java.net.InetSocketAddress;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport javax.inject.Singleton;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLSocketFactory;\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.X509TrustManager;\nimport okhttp3.OkHttpClient;\nimport retrofit2.mock.NetworkBehavior;\nimport timber.log.Timber;\n\n@Module(includes = DebugApiModule.class, complete = false, library = true, overrides = true)\npublic final class DebugDataModule {\n\n private static final int DEFAULT_ANIMATION_SPEED = 1;\n\n // Debug indicators displayed\n private static final boolean DEFAULT_PICASSO_DEBUGGING = false;\n\n // No pixel grid overlay.\n private static final boolean DEFAULT_PIXEL_GRID_ENABLED = false;\n\n // No pixel ratio overlay.\n private static final boolean DEFAULT_PIXEL_RATIO_ENABLED = false;\n\n // No crazy 3D view tree.\n private static final boolean DEFAULT_SCALPEL_ENABLED = false;\n\n // Draw views by default.\n private static final boolean DEFAULT_SCALPEL_WIREFRAME_ENABLED = false;\n\n // Show debug drawer first time.\n private static final boolean DEFAULT_SEEN_DEBUG_DRAWER = false;\n\n // Capture external intents.\n private static final boolean DEFAULT_CAPTURE_INTENTS = true;\n\n @Provides\n @Singleton\n RxSharedPreferences provideRxSharedPreferences(SharedPreferences prefs) {\n return RxSharedPreferences.create(prefs);\n }\n\n @Provides\n @Singleton\n IntentFactory provideIntentFactory(@IsMockMode boolean isMockMode, @CaptureIntents Preference captureIntents) {\n return new CapturingIntentFactory(IntentFactory.REAL, () -> isMockMode && captureIntents.get());\n }\n\n @Provides\n @Singleton\n OkHttpClient provideOkHttpClient(Application app, Preference networkProxyAddress) {\n return DataModule.createOkHttpClient(app).sslSocketFactory(createBadSslSocketFactory()).proxy(InetSocketAddressPreferenceAdapter.createProxy(networkProxyAddress.get())).build();\n }\n\n @Provides\n @Singleton\n @AccessToken\n Preference provideAccessToken(RxSharedPreferences prefs, @ApiEndpoint Preference endpoint) {\n // Return an endpoint-specific preference.\n return prefs.getString(\"access-token-\" + endpoint.get());\n }\n\n @Provides\n @Singleton\n @ApiEndpoint\n Preference provideEndpointPreference(RxSharedPreferences preferences) {\n return preferences.getString(\"debug_endpoint\", ApiEndpoints.MOCK_MODE.url);\n }\n\n @Provides\n @Singleton\n @IsMockMode\n boolean provideIsMockMode(@ApiEndpoint Preference endpoint, @IsInstrumentationTest boolean isInstrumentationTest) {\n // Running in an instrumentation forces mock mode.\n return isInstrumentationTest || ApiEndpoints.isMockMode(endpoint.get());\n }\n\n @Provides\n @Singleton\n @NetworkDelay\n Preference provideNetworkDelay(RxSharedPreferences preferences) {\n return preferences.getLong(\"debug_network_delay\", 2000l);\n }\n\n @Provides\n @Singleton\n @NetworkFailurePercent\n Preference provideNetworkFailurePercent(RxSharedPreferences preferences) {\n return preferences.getInteger(\"debug_network_failure_percent\", 3);\n }\n\n @Provides\n @Singleton\n @NetworkErrorPercent\n Preference provideNetworkErrorPercent(RxSharedPreferences preferences) {\n return preferences.getInteger(\"debug_network_error_percent\", 0);\n }\n\n @Provides\n @Singleton\n Preference provideNetworkErrorCode(RxSharedPreferences preferences) {\n return preferences.getEnum(\"debug_network_error_code\", NetworkErrorCode.HTTP_500, NetworkErrorCode.class);\n }\n\n @Provides\n @Singleton\n @NetworkVariancePercent\n Preference provideNetworkVariancePercent(RxSharedPreferences preferences) {\n return preferences.getInteger(\"debug_network_variance_percent\", 40);\n }\n\n @Provides\n @Singleton\n Preference provideNetworkProxyAddress(RxSharedPreferences preferences) {\n return preferences.getObject(\"debug_network_proxy\", InetSocketAddressPreferenceAdapter.INSTANCE);\n }\n\n @Provides\n @Singleton\n @CaptureIntents\n Preference provideCaptureIntentsPreference(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_capture_intents\", DEFAULT_CAPTURE_INTENTS);\n }\n\n @Provides\n @Singleton\n @AnimationSpeed\n Preference provideAnimationSpeed(RxSharedPreferences preferences) {\n return preferences.getInteger(\"debug_animation_speed\", DEFAULT_ANIMATION_SPEED);\n }\n\n @Provides\n @Singleton\n @PicassoDebugging\n Preference providePicassoDebugging(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_picasso_debugging\", DEFAULT_PICASSO_DEBUGGING);\n }\n\n @Provides\n @Singleton\n @PixelGridEnabled\n Preference providePixelGridEnabled(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_pixel_grid_enabled\", DEFAULT_PIXEL_GRID_ENABLED);\n }\n\n @Provides\n @Singleton\n @PixelRatioEnabled\n Preference providePixelRatioEnabled(RxSharedPreferences preferences) ", "post_mask_code": "\n\n @Provides\n @Singleton\n @SeenDebugDrawer\n Preference provideSeenDebugDrawer(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_seen_debug_drawer\", DEFAULT_SEEN_DEBUG_DRAWER);\n }\n\n @Provides\n @Singleton\n @ScalpelEnabled\n Preference provideScalpelEnabled(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_scalpel_enabled\", DEFAULT_SCALPEL_ENABLED);\n }\n\n @Provides\n @Singleton\n @ScalpelWireframeEnabled\n Preference provideScalpelWireframeEnabled(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_scalpel_wireframe_drawer\", DEFAULT_SCALPEL_WIREFRAME_ENABLED);\n }\n\n @Provides\n @Singleton\n Picasso providePicasso(OkHttpClient client, NetworkBehavior behavior, @IsMockMode boolean isMockMode, Application app) {\n Picasso.Builder builder = new Picasso.Builder(app).downloader(new OkHttp3Downloader(client));\n if (isMockMode) {\n builder.addRequestHandler(new MockRequestHandler(behavior, app.getAssets()));\n }\n builder.listener((picasso, uri, exception) -> {\n Timber.e(exception, \"Error while loading image %s\", uri);\n });\n return builder.build();\n }\n\n private static SSLSocketFactory createBadSslSocketFactory() {\n try {\n // Construct SSLSocketFactory that accepts any cert.\n SSLContext context = SSLContext.getInstance(\"TLS\");\n TrustManager permissive = new X509TrustManager() {\n\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n };\n context.init(null, new TrustManager[] { permissive }, null);\n return context.getSocketFactory();\n } catch (Exception e) {\n throw new AssertionError(e);\n }\n }\n}\n"} {"task_id": "Java_2393", "language": "Java", "task_type": "single_line", "source_file": "java/github/JakeWharton/u2020/app/src/internalDebug/java/com/jakewharton/u2020/data/DebugDataModule.java", "mask_start_position": 2427, "mask_end_position": 2437, "canonical_solution": "ts.get());", "pre_mask_code": "package com.jakewharton.u2020.data;\n\nimport android.app.Application;\nimport android.content.SharedPreferences;\nimport com.f2prateek.rx.preferences.Preference;\nimport com.f2prateek.rx.preferences.RxSharedPreferences;\nimport com.jakewharton.picasso.OkHttp3Downloader;\nimport com.jakewharton.u2020.IsInstrumentationTest;\nimport com.jakewharton.u2020.data.api.DebugApiModule;\nimport com.jakewharton.u2020.data.api.oauth.AccessToken;\nimport com.jakewharton.u2020.data.prefs.InetSocketAddressPreferenceAdapter;\nimport com.jakewharton.u2020.intentfactory.CapturingIntentFactory;\nimport com.jakewharton.u2020.intentfactory.IntentFactory;\nimport com.squareup.picasso.Picasso;\nimport dagger.Module;\nimport dagger.Provides;\nimport java.net.InetSocketAddress;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport javax.inject.Singleton;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLSocketFactory;\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.X509TrustManager;\nimport okhttp3.OkHttpClient;\nimport retrofit2.mock.NetworkBehavior;\nimport timber.log.Timber;\n\n@Module(includes = DebugApiModule.class, complete = false, library = true, overrides = true)\npublic final class DebugDataModule {\n\n private static final int DEFAULT_ANIMATION_SPEED = 1;\n\n // Debug indicators displayed\n private static final boolean DEFAULT_PICASSO_DEBUGGING = false;\n\n // No pixel grid overlay.\n private static final boolean DEFAULT_PIXEL_GRID_ENABLED = false;\n\n // No pixel ratio overlay.\n private static final boolean DEFAULT_PIXEL_RATIO_ENABLED = false;\n\n // No crazy 3D view tree.\n private static final boolean DEFAULT_SCALPEL_ENABLED = false;\n\n // Draw views by default.\n private static final boolean DEFAULT_SCALPEL_WIREFRAME_ENABLED = false;\n\n // Show debug drawer first time.\n private static final boolean DEFAULT_SEEN_DEBUG_DRAWER = false;\n\n // Capture external intents.\n private static final boolean DEFAULT_CAPTURE_INTENTS = true;\n\n @Provides\n @Singleton\n RxSharedPreferences provideRxSharedPreferences(SharedPreferences prefs) {\n return RxSharedPreferences.create(prefs);\n }\n\n @Provides\n @Singleton\n IntentFactory provideIntentFactory(@IsMockMode boolean isMockMode, @CaptureIntents Preference captureIntents) {\n return new CapturingIntentFactory(IntentFactory.REAL, () -> isMockMode && captureInten", "post_mask_code": "\n }\n\n @Provides\n @Singleton\n OkHttpClient provideOkHttpClient(Application app, Preference networkProxyAddress) {\n return DataModule.createOkHttpClient(app).sslSocketFactory(createBadSslSocketFactory()).proxy(InetSocketAddressPreferenceAdapter.createProxy(networkProxyAddress.get())).build();\n }\n\n @Provides\n @Singleton\n @AccessToken\n Preference provideAccessToken(RxSharedPreferences prefs, @ApiEndpoint Preference endpoint) {\n // Return an endpoint-specific preference.\n return prefs.getString(\"access-token-\" + endpoint.get());\n }\n\n @Provides\n @Singleton\n @ApiEndpoint\n Preference provideEndpointPreference(RxSharedPreferences preferences) {\n return preferences.getString(\"debug_endpoint\", ApiEndpoints.MOCK_MODE.url);\n }\n\n @Provides\n @Singleton\n @IsMockMode\n boolean provideIsMockMode(@ApiEndpoint Preference endpoint, @IsInstrumentationTest boolean isInstrumentationTest) {\n // Running in an instrumentation forces mock mode.\n return isInstrumentationTest || ApiEndpoints.isMockMode(endpoint.get());\n }\n\n @Provides\n @Singleton\n @NetworkDelay\n Preference provideNetworkDelay(RxSharedPreferences preferences) {\n return preferences.getLong(\"debug_network_delay\", 2000l);\n }\n\n @Provides\n @Singleton\n @NetworkFailurePercent\n Preference provideNetworkFailurePercent(RxSharedPreferences preferences) {\n return preferences.getInteger(\"debug_network_failure_percent\", 3);\n }\n\n @Provides\n @Singleton\n @NetworkErrorPercent\n Preference provideNetworkErrorPercent(RxSharedPreferences preferences) {\n return preferences.getInteger(\"debug_network_error_percent\", 0);\n }\n\n @Provides\n @Singleton\n Preference provideNetworkErrorCode(RxSharedPreferences preferences) {\n return preferences.getEnum(\"debug_network_error_code\", NetworkErrorCode.HTTP_500, NetworkErrorCode.class);\n }\n\n @Provides\n @Singleton\n @NetworkVariancePercent\n Preference provideNetworkVariancePercent(RxSharedPreferences preferences) {\n return preferences.getInteger(\"debug_network_variance_percent\", 40);\n }\n\n @Provides\n @Singleton\n Preference provideNetworkProxyAddress(RxSharedPreferences preferences) {\n return preferences.getObject(\"debug_network_proxy\", InetSocketAddressPreferenceAdapter.INSTANCE);\n }\n\n @Provides\n @Singleton\n @CaptureIntents\n Preference provideCaptureIntentsPreference(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_capture_intents\", DEFAULT_CAPTURE_INTENTS);\n }\n\n @Provides\n @Singleton\n @AnimationSpeed\n Preference provideAnimationSpeed(RxSharedPreferences preferences) {\n return preferences.getInteger(\"debug_animation_speed\", DEFAULT_ANIMATION_SPEED);\n }\n\n @Provides\n @Singleton\n @PicassoDebugging\n Preference providePicassoDebugging(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_picasso_debugging\", DEFAULT_PICASSO_DEBUGGING);\n }\n\n @Provides\n @Singleton\n @PixelGridEnabled\n Preference providePixelGridEnabled(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_pixel_grid_enabled\", DEFAULT_PIXEL_GRID_ENABLED);\n }\n\n @Provides\n @Singleton\n @PixelRatioEnabled\n Preference providePixelRatioEnabled(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_pixel_ratio_enabled\", DEFAULT_PIXEL_RATIO_ENABLED);\n }\n\n @Provides\n @Singleton\n @SeenDebugDrawer\n Preference provideSeenDebugDrawer(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_seen_debug_drawer\", DEFAULT_SEEN_DEBUG_DRAWER);\n }\n\n @Provides\n @Singleton\n @ScalpelEnabled\n Preference provideScalpelEnabled(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_scalpel_enabled\", DEFAULT_SCALPEL_ENABLED);\n }\n\n @Provides\n @Singleton\n @ScalpelWireframeEnabled\n Preference provideScalpelWireframeEnabled(RxSharedPreferences preferences) {\n return preferences.getBoolean(\"debug_scalpel_wireframe_drawer\", DEFAULT_SCALPEL_WIREFRAME_ENABLED);\n }\n\n @Provides\n @Singleton\n Picasso providePicasso(OkHttpClient client, NetworkBehavior behavior, @IsMockMode boolean isMockMode, Application app) {\n Picasso.Builder builder = new Picasso.Builder(app).downloader(new OkHttp3Downloader(client));\n if (isMockMode) {\n builder.addRequestHandler(new MockRequestHandler(behavior, app.getAssets()));\n }\n builder.listener((picasso, uri, exception) -> {\n Timber.e(exception, \"Error while loading image %s\", uri);\n });\n return builder.build();\n }\n\n private static SSLSocketFactory createBadSslSocketFactory() {\n try {\n // Construct SSLSocketFactory that accepts any cert.\n SSLContext context = SSLContext.getInstance(\"TLS\");\n TrustManager permissive = new X509TrustManager() {\n\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n };\n context.init(null, new TrustManager[] { permissive }, null);\n return context.getSocketFactory();\n } catch (Exception e) {\n throw new AssertionError(e);\n }\n }\n}\n"} {"task_id": "Java_2394", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/ambari/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/HostRoleCommandStatusSummaryDTO.java", "mask_start_position": 4074, "mask_end_position": 4131, "canonical_solution": "public HostRoleCommandStatusSummaryDTO failed(int count) ", "pre_mask_code": "package org.apache.ambari.server.orm.dao;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport org.apache.ambari.server.actionmanager.HostRoleStatus;\n\n/**\n * Summary for a single stage with summary counts for the tasks for that stage.\n */\npublic class HostRoleCommandStatusSummaryDTO {\n\n private Long m_stageId = Long.valueOf(0L);\n\n private Long m_minTime = Long.valueOf(0L);\n\n private Long m_maxTime = Long.valueOf(Long.MAX_VALUE);\n\n private boolean m_skippable = false;\n\n private Map m_counts = new HashMap<>();\n\n private List m_tasksStatus = new ArrayList<>();\n\n /**\n * Constructor invoked by JPA. See {{@link HostRoleCommandDAO#findAggregateCounts(Long)}}\n */\n public HostRoleCommandStatusSummaryDTO(Number skippable, Number minStartTime, Number maxEndTime, Number stageId, Number aborted, Number completed, Number failed, Number holding, Number holdingFailed, Number holdingTimedout, Number inProgress, Number pending, Number queued, Number timedout, Number skippedFailed) {\n m_stageId = Long.valueOf(null == stageId ? 0L : stageId.longValue());\n if (null != skippable) {\n m_skippable = (1 == skippable.intValue());\n }\n if (null != minStartTime) {\n m_minTime = Long.valueOf(minStartTime.longValue());\n }\n if (null != maxEndTime) {\n m_maxTime = Long.valueOf(maxEndTime.longValue());\n }\n put(HostRoleStatus.ABORTED, aborted);\n put(HostRoleStatus.COMPLETED, completed);\n put(HostRoleStatus.FAILED, failed);\n put(HostRoleStatus.HOLDING, holding);\n put(HostRoleStatus.HOLDING_FAILED, holdingFailed);\n put(HostRoleStatus.HOLDING_TIMEDOUT, holdingTimedout);\n put(HostRoleStatus.IN_PROGRESS, inProgress);\n put(HostRoleStatus.PENDING, pending);\n put(HostRoleStatus.QUEUED, queued);\n put(HostRoleStatus.TIMEDOUT, timedout);\n put(HostRoleStatus.SKIPPED_FAILED, skippedFailed);\n }\n\n @SuppressWarnings(\"boxing\")\n private void put(HostRoleStatus status, Number number) {\n if (null != number) {\n m_counts.put(status, number.intValue());\n for (int i = 0; i < number.intValue(); i++) {\n m_tasksStatus.add(status);\n }\n } else {\n m_counts.put(status, 0);\n }\n }\n\n /**\n * @return the stage id for this summary\n */\n Long getStageId() {\n return m_stageId;\n }\n\n /**\n * @return the task result counts, by status\n */\n public Map getCounts() {\n return m_counts;\n }\n\n /**\n * @return the list of tasks status, expanded to cover all tasks for the stage\n */\n public List getTaskStatuses() {\n return m_tasksStatus;\n }\n\n /**\n * @return the total number of tasks for the stage\n */\n public int getTaskTotal() {\n return m_tasksStatus.size();\n }\n\n /**\n * @return {@code true} if the stage is skippable\n */\n public boolean isStageSkippable() {\n return m_skippable;\n }\n\n /**\n * @return the start time, minimum, for the tasks\n */\n public Long getStartTime() {\n return m_minTime;\n }\n\n /**\n * @return the end time, maximum, for the tasks\n */\n public Long getEndTime() {\n return m_maxTime;\n }\n\n /**\n * For testing, create an empty summary.\n */\n public static HostRoleCommandStatusSummaryDTO create() {\n return new HostRoleCommandStatusSummaryDTO(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, // timedout\n 0L, // skippedFailed\n 0L);\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#COMPLETED} tasks\n */\n public HostRoleCommandStatusSummaryDTO completed(int count) {\n put(HostRoleStatus.COMPLETED, Integer.valueOf(count));\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#FAILED} tasks\n */\n ", "post_mask_code": "{\n put(HostRoleStatus.FAILED, Integer.valueOf(count));\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#ABORTED} tasks\n */\n public HostRoleCommandStatusSummaryDTO aborted(int count) {\n put(HostRoleStatus.ABORTED, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#TIMEDOUT} tasks\n */\n public HostRoleCommandStatusSummaryDTO timedout(int count) {\n put(HostRoleStatus.TIMEDOUT, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#IN_PROGRESS} tasks\n */\n public HostRoleCommandStatusSummaryDTO inProgress(int count) {\n put(HostRoleStatus.IN_PROGRESS, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#PENDING} tasks\n */\n public HostRoleCommandStatusSummaryDTO pending(int count) {\n put(HostRoleStatus.PENDING, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#QUEUED} tasks\n */\n public HostRoleCommandStatusSummaryDTO queued(int count) {\n put(HostRoleStatus.QUEUED, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#SKIPPED_FAILED} tasks\n */\n public HostRoleCommandStatusSummaryDTO skippedFailed(int count) {\n put(HostRoleStatus.SKIPPED_FAILED, count);\n return this;\n }\n}\n"} {"task_id": "Java_2395", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/ambari/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/HostRoleCommandStatusSummaryDTO.java", "mask_start_position": 3409, "mask_end_position": 3442, "canonical_solution": "{\n return m_maxTime;\n }", "pre_mask_code": "package org.apache.ambari.server.orm.dao;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport org.apache.ambari.server.actionmanager.HostRoleStatus;\n\n/**\n * Summary for a single stage with summary counts for the tasks for that stage.\n */\npublic class HostRoleCommandStatusSummaryDTO {\n\n private Long m_stageId = Long.valueOf(0L);\n\n private Long m_minTime = Long.valueOf(0L);\n\n private Long m_maxTime = Long.valueOf(Long.MAX_VALUE);\n\n private boolean m_skippable = false;\n\n private Map m_counts = new HashMap<>();\n\n private List m_tasksStatus = new ArrayList<>();\n\n /**\n * Constructor invoked by JPA. See {{@link HostRoleCommandDAO#findAggregateCounts(Long)}}\n */\n public HostRoleCommandStatusSummaryDTO(Number skippable, Number minStartTime, Number maxEndTime, Number stageId, Number aborted, Number completed, Number failed, Number holding, Number holdingFailed, Number holdingTimedout, Number inProgress, Number pending, Number queued, Number timedout, Number skippedFailed) {\n m_stageId = Long.valueOf(null == stageId ? 0L : stageId.longValue());\n if (null != skippable) {\n m_skippable = (1 == skippable.intValue());\n }\n if (null != minStartTime) {\n m_minTime = Long.valueOf(minStartTime.longValue());\n }\n if (null != maxEndTime) {\n m_maxTime = Long.valueOf(maxEndTime.longValue());\n }\n put(HostRoleStatus.ABORTED, aborted);\n put(HostRoleStatus.COMPLETED, completed);\n put(HostRoleStatus.FAILED, failed);\n put(HostRoleStatus.HOLDING, holding);\n put(HostRoleStatus.HOLDING_FAILED, holdingFailed);\n put(HostRoleStatus.HOLDING_TIMEDOUT, holdingTimedout);\n put(HostRoleStatus.IN_PROGRESS, inProgress);\n put(HostRoleStatus.PENDING, pending);\n put(HostRoleStatus.QUEUED, queued);\n put(HostRoleStatus.TIMEDOUT, timedout);\n put(HostRoleStatus.SKIPPED_FAILED, skippedFailed);\n }\n\n @SuppressWarnings(\"boxing\")\n private void put(HostRoleStatus status, Number number) {\n if (null != number) {\n m_counts.put(status, number.intValue());\n for (int i = 0; i < number.intValue(); i++) {\n m_tasksStatus.add(status);\n }\n } else {\n m_counts.put(status, 0);\n }\n }\n\n /**\n * @return the stage id for this summary\n */\n Long getStageId() {\n return m_stageId;\n }\n\n /**\n * @return the task result counts, by status\n */\n public Map getCounts() {\n return m_counts;\n }\n\n /**\n * @return the list of tasks status, expanded to cover all tasks for the stage\n */\n public List getTaskStatuses() {\n return m_tasksStatus;\n }\n\n /**\n * @return the total number of tasks for the stage\n */\n public int getTaskTotal() {\n return m_tasksStatus.size();\n }\n\n /**\n * @return {@code true} if the stage is skippable\n */\n public boolean isStageSkippable() {\n return m_skippable;\n }\n\n /**\n * @return the start time, minimum, for the tasks\n */\n public Long getStartTime() {\n return m_minTime;\n }\n\n /**\n * @return the end time, maximum, for the tasks\n */\n public Long getEndTime() ", "post_mask_code": "\n\n /**\n * For testing, create an empty summary.\n */\n public static HostRoleCommandStatusSummaryDTO create() {\n return new HostRoleCommandStatusSummaryDTO(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, // timedout\n 0L, // skippedFailed\n 0L);\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#COMPLETED} tasks\n */\n public HostRoleCommandStatusSummaryDTO completed(int count) {\n put(HostRoleStatus.COMPLETED, Integer.valueOf(count));\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#FAILED} tasks\n */\n public HostRoleCommandStatusSummaryDTO failed(int count) {\n put(HostRoleStatus.FAILED, Integer.valueOf(count));\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#ABORTED} tasks\n */\n public HostRoleCommandStatusSummaryDTO aborted(int count) {\n put(HostRoleStatus.ABORTED, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#TIMEDOUT} tasks\n */\n public HostRoleCommandStatusSummaryDTO timedout(int count) {\n put(HostRoleStatus.TIMEDOUT, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#IN_PROGRESS} tasks\n */\n public HostRoleCommandStatusSummaryDTO inProgress(int count) {\n put(HostRoleStatus.IN_PROGRESS, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#PENDING} tasks\n */\n public HostRoleCommandStatusSummaryDTO pending(int count) {\n put(HostRoleStatus.PENDING, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#QUEUED} tasks\n */\n public HostRoleCommandStatusSummaryDTO queued(int count) {\n put(HostRoleStatus.QUEUED, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#SKIPPED_FAILED} tasks\n */\n public HostRoleCommandStatusSummaryDTO skippedFailed(int count) {\n put(HostRoleStatus.SKIPPED_FAILED, count);\n return this;\n }\n}\n"} {"task_id": "Java_2396", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/ambari/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/HostRoleCommandStatusSummaryDTO.java", "mask_start_position": 4179, "mask_end_position": 4192, "canonical_solution": "ueOf(count));", "pre_mask_code": "package org.apache.ambari.server.orm.dao;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport org.apache.ambari.server.actionmanager.HostRoleStatus;\n\n/**\n * Summary for a single stage with summary counts for the tasks for that stage.\n */\npublic class HostRoleCommandStatusSummaryDTO {\n\n private Long m_stageId = Long.valueOf(0L);\n\n private Long m_minTime = Long.valueOf(0L);\n\n private Long m_maxTime = Long.valueOf(Long.MAX_VALUE);\n\n private boolean m_skippable = false;\n\n private Map m_counts = new HashMap<>();\n\n private List m_tasksStatus = new ArrayList<>();\n\n /**\n * Constructor invoked by JPA. See {{@link HostRoleCommandDAO#findAggregateCounts(Long)}}\n */\n public HostRoleCommandStatusSummaryDTO(Number skippable, Number minStartTime, Number maxEndTime, Number stageId, Number aborted, Number completed, Number failed, Number holding, Number holdingFailed, Number holdingTimedout, Number inProgress, Number pending, Number queued, Number timedout, Number skippedFailed) {\n m_stageId = Long.valueOf(null == stageId ? 0L : stageId.longValue());\n if (null != skippable) {\n m_skippable = (1 == skippable.intValue());\n }\n if (null != minStartTime) {\n m_minTime = Long.valueOf(minStartTime.longValue());\n }\n if (null != maxEndTime) {\n m_maxTime = Long.valueOf(maxEndTime.longValue());\n }\n put(HostRoleStatus.ABORTED, aborted);\n put(HostRoleStatus.COMPLETED, completed);\n put(HostRoleStatus.FAILED, failed);\n put(HostRoleStatus.HOLDING, holding);\n put(HostRoleStatus.HOLDING_FAILED, holdingFailed);\n put(HostRoleStatus.HOLDING_TIMEDOUT, holdingTimedout);\n put(HostRoleStatus.IN_PROGRESS, inProgress);\n put(HostRoleStatus.PENDING, pending);\n put(HostRoleStatus.QUEUED, queued);\n put(HostRoleStatus.TIMEDOUT, timedout);\n put(HostRoleStatus.SKIPPED_FAILED, skippedFailed);\n }\n\n @SuppressWarnings(\"boxing\")\n private void put(HostRoleStatus status, Number number) {\n if (null != number) {\n m_counts.put(status, number.intValue());\n for (int i = 0; i < number.intValue(); i++) {\n m_tasksStatus.add(status);\n }\n } else {\n m_counts.put(status, 0);\n }\n }\n\n /**\n * @return the stage id for this summary\n */\n Long getStageId() {\n return m_stageId;\n }\n\n /**\n * @return the task result counts, by status\n */\n public Map getCounts() {\n return m_counts;\n }\n\n /**\n * @return the list of tasks status, expanded to cover all tasks for the stage\n */\n public List getTaskStatuses() {\n return m_tasksStatus;\n }\n\n /**\n * @return the total number of tasks for the stage\n */\n public int getTaskTotal() {\n return m_tasksStatus.size();\n }\n\n /**\n * @return {@code true} if the stage is skippable\n */\n public boolean isStageSkippable() {\n return m_skippable;\n }\n\n /**\n * @return the start time, minimum, for the tasks\n */\n public Long getStartTime() {\n return m_minTime;\n }\n\n /**\n * @return the end time, maximum, for the tasks\n */\n public Long getEndTime() {\n return m_maxTime;\n }\n\n /**\n * For testing, create an empty summary.\n */\n public static HostRoleCommandStatusSummaryDTO create() {\n return new HostRoleCommandStatusSummaryDTO(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, // timedout\n 0L, // skippedFailed\n 0L);\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#COMPLETED} tasks\n */\n public HostRoleCommandStatusSummaryDTO completed(int count) {\n put(HostRoleStatus.COMPLETED, Integer.valueOf(count));\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#FAILED} tasks\n */\n public HostRoleCommandStatusSummaryDTO failed(int count) {\n put(HostRoleStatus.FAILED, Integer.val", "post_mask_code": "\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#ABORTED} tasks\n */\n public HostRoleCommandStatusSummaryDTO aborted(int count) {\n put(HostRoleStatus.ABORTED, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#TIMEDOUT} tasks\n */\n public HostRoleCommandStatusSummaryDTO timedout(int count) {\n put(HostRoleStatus.TIMEDOUT, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#IN_PROGRESS} tasks\n */\n public HostRoleCommandStatusSummaryDTO inProgress(int count) {\n put(HostRoleStatus.IN_PROGRESS, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#PENDING} tasks\n */\n public HostRoleCommandStatusSummaryDTO pending(int count) {\n put(HostRoleStatus.PENDING, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#QUEUED} tasks\n */\n public HostRoleCommandStatusSummaryDTO queued(int count) {\n put(HostRoleStatus.QUEUED, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#SKIPPED_FAILED} tasks\n */\n public HostRoleCommandStatusSummaryDTO skippedFailed(int count) {\n put(HostRoleStatus.SKIPPED_FAILED, count);\n return this;\n }\n}\n"} {"task_id": "Java_2397", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/apache/ambari/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/HostRoleCommandStatusSummaryDTO.java", "mask_start_position": 4544, "mask_end_position": 4676, "canonical_solution": "public HostRoleCommandStatusSummaryDTO timedout(int count) {\n put(HostRoleStatus.TIMEDOUT, count);\n return this;\n }", "pre_mask_code": "package org.apache.ambari.server.orm.dao;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport org.apache.ambari.server.actionmanager.HostRoleStatus;\n\n/**\n * Summary for a single stage with summary counts for the tasks for that stage.\n */\npublic class HostRoleCommandStatusSummaryDTO {\n\n private Long m_stageId = Long.valueOf(0L);\n\n private Long m_minTime = Long.valueOf(0L);\n\n private Long m_maxTime = Long.valueOf(Long.MAX_VALUE);\n\n private boolean m_skippable = false;\n\n private Map m_counts = new HashMap<>();\n\n private List m_tasksStatus = new ArrayList<>();\n\n /**\n * Constructor invoked by JPA. See {{@link HostRoleCommandDAO#findAggregateCounts(Long)}}\n */\n public HostRoleCommandStatusSummaryDTO(Number skippable, Number minStartTime, Number maxEndTime, Number stageId, Number aborted, Number completed, Number failed, Number holding, Number holdingFailed, Number holdingTimedout, Number inProgress, Number pending, Number queued, Number timedout, Number skippedFailed) {\n m_stageId = Long.valueOf(null == stageId ? 0L : stageId.longValue());\n if (null != skippable) {\n m_skippable = (1 == skippable.intValue());\n }\n if (null != minStartTime) {\n m_minTime = Long.valueOf(minStartTime.longValue());\n }\n if (null != maxEndTime) {\n m_maxTime = Long.valueOf(maxEndTime.longValue());\n }\n put(HostRoleStatus.ABORTED, aborted);\n put(HostRoleStatus.COMPLETED, completed);\n put(HostRoleStatus.FAILED, failed);\n put(HostRoleStatus.HOLDING, holding);\n put(HostRoleStatus.HOLDING_FAILED, holdingFailed);\n put(HostRoleStatus.HOLDING_TIMEDOUT, holdingTimedout);\n put(HostRoleStatus.IN_PROGRESS, inProgress);\n put(HostRoleStatus.PENDING, pending);\n put(HostRoleStatus.QUEUED, queued);\n put(HostRoleStatus.TIMEDOUT, timedout);\n put(HostRoleStatus.SKIPPED_FAILED, skippedFailed);\n }\n\n @SuppressWarnings(\"boxing\")\n private void put(HostRoleStatus status, Number number) {\n if (null != number) {\n m_counts.put(status, number.intValue());\n for (int i = 0; i < number.intValue(); i++) {\n m_tasksStatus.add(status);\n }\n } else {\n m_counts.put(status, 0);\n }\n }\n\n /**\n * @return the stage id for this summary\n */\n Long getStageId() {\n return m_stageId;\n }\n\n /**\n * @return the task result counts, by status\n */\n public Map getCounts() {\n return m_counts;\n }\n\n /**\n * @return the list of tasks status, expanded to cover all tasks for the stage\n */\n public List getTaskStatuses() {\n return m_tasksStatus;\n }\n\n /**\n * @return the total number of tasks for the stage\n */\n public int getTaskTotal() {\n return m_tasksStatus.size();\n }\n\n /**\n * @return {@code true} if the stage is skippable\n */\n public boolean isStageSkippable() {\n return m_skippable;\n }\n\n /**\n * @return the start time, minimum, for the tasks\n */\n public Long getStartTime() {\n return m_minTime;\n }\n\n /**\n * @return the end time, maximum, for the tasks\n */\n public Long getEndTime() {\n return m_maxTime;\n }\n\n /**\n * For testing, create an empty summary.\n */\n public static HostRoleCommandStatusSummaryDTO create() {\n return new HostRoleCommandStatusSummaryDTO(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, // timedout\n 0L, // skippedFailed\n 0L);\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#COMPLETED} tasks\n */\n public HostRoleCommandStatusSummaryDTO completed(int count) {\n put(HostRoleStatus.COMPLETED, Integer.valueOf(count));\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#FAILED} tasks\n */\n public HostRoleCommandStatusSummaryDTO failed(int count) {\n put(HostRoleStatus.FAILED, Integer.valueOf(count));\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#ABORTED} tasks\n */\n public HostRoleCommandStatusSummaryDTO aborted(int count) {\n put(HostRoleStatus.ABORTED, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#TIMEDOUT} tasks\n */\n ", "post_mask_code": "\n\n /**\n * For testing, set the number of {@link HostRoleStatus#IN_PROGRESS} tasks\n */\n public HostRoleCommandStatusSummaryDTO inProgress(int count) {\n put(HostRoleStatus.IN_PROGRESS, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#PENDING} tasks\n */\n public HostRoleCommandStatusSummaryDTO pending(int count) {\n put(HostRoleStatus.PENDING, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#QUEUED} tasks\n */\n public HostRoleCommandStatusSummaryDTO queued(int count) {\n put(HostRoleStatus.QUEUED, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#SKIPPED_FAILED} tasks\n */\n public HostRoleCommandStatusSummaryDTO skippedFailed(int count) {\n put(HostRoleStatus.SKIPPED_FAILED, count);\n return this;\n }\n}\n"} {"task_id": "Java_2398", "language": "Java", "task_type": "for_statement", "source_file": "java/github/apache/ambari/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/HostRoleCommandStatusSummaryDTO.java", "mask_start_position": 2253, "mask_end_position": 2355, "canonical_solution": "for (int i = 0; i < number.intValue(); i++) {\n m_tasksStatus.add(status);\n }", "pre_mask_code": "package org.apache.ambari.server.orm.dao;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport org.apache.ambari.server.actionmanager.HostRoleStatus;\n\n/**\n * Summary for a single stage with summary counts for the tasks for that stage.\n */\npublic class HostRoleCommandStatusSummaryDTO {\n\n private Long m_stageId = Long.valueOf(0L);\n\n private Long m_minTime = Long.valueOf(0L);\n\n private Long m_maxTime = Long.valueOf(Long.MAX_VALUE);\n\n private boolean m_skippable = false;\n\n private Map m_counts = new HashMap<>();\n\n private List m_tasksStatus = new ArrayList<>();\n\n /**\n * Constructor invoked by JPA. See {{@link HostRoleCommandDAO#findAggregateCounts(Long)}}\n */\n public HostRoleCommandStatusSummaryDTO(Number skippable, Number minStartTime, Number maxEndTime, Number stageId, Number aborted, Number completed, Number failed, Number holding, Number holdingFailed, Number holdingTimedout, Number inProgress, Number pending, Number queued, Number timedout, Number skippedFailed) {\n m_stageId = Long.valueOf(null == stageId ? 0L : stageId.longValue());\n if (null != skippable) {\n m_skippable = (1 == skippable.intValue());\n }\n if (null != minStartTime) {\n m_minTime = Long.valueOf(minStartTime.longValue());\n }\n if (null != maxEndTime) {\n m_maxTime = Long.valueOf(maxEndTime.longValue());\n }\n put(HostRoleStatus.ABORTED, aborted);\n put(HostRoleStatus.COMPLETED, completed);\n put(HostRoleStatus.FAILED, failed);\n put(HostRoleStatus.HOLDING, holding);\n put(HostRoleStatus.HOLDING_FAILED, holdingFailed);\n put(HostRoleStatus.HOLDING_TIMEDOUT, holdingTimedout);\n put(HostRoleStatus.IN_PROGRESS, inProgress);\n put(HostRoleStatus.PENDING, pending);\n put(HostRoleStatus.QUEUED, queued);\n put(HostRoleStatus.TIMEDOUT, timedout);\n put(HostRoleStatus.SKIPPED_FAILED, skippedFailed);\n }\n\n @SuppressWarnings(\"boxing\")\n private void put(HostRoleStatus status, Number number) {\n if (null != number) {\n m_counts.put(status, number.intValue());\n ", "post_mask_code": "\n } else {\n m_counts.put(status, 0);\n }\n }\n\n /**\n * @return the stage id for this summary\n */\n Long getStageId() {\n return m_stageId;\n }\n\n /**\n * @return the task result counts, by status\n */\n public Map getCounts() {\n return m_counts;\n }\n\n /**\n * @return the list of tasks status, expanded to cover all tasks for the stage\n */\n public List getTaskStatuses() {\n return m_tasksStatus;\n }\n\n /**\n * @return the total number of tasks for the stage\n */\n public int getTaskTotal() {\n return m_tasksStatus.size();\n }\n\n /**\n * @return {@code true} if the stage is skippable\n */\n public boolean isStageSkippable() {\n return m_skippable;\n }\n\n /**\n * @return the start time, minimum, for the tasks\n */\n public Long getStartTime() {\n return m_minTime;\n }\n\n /**\n * @return the end time, maximum, for the tasks\n */\n public Long getEndTime() {\n return m_maxTime;\n }\n\n /**\n * For testing, create an empty summary.\n */\n public static HostRoleCommandStatusSummaryDTO create() {\n return new HostRoleCommandStatusSummaryDTO(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, // timedout\n 0L, // skippedFailed\n 0L);\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#COMPLETED} tasks\n */\n public HostRoleCommandStatusSummaryDTO completed(int count) {\n put(HostRoleStatus.COMPLETED, Integer.valueOf(count));\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#FAILED} tasks\n */\n public HostRoleCommandStatusSummaryDTO failed(int count) {\n put(HostRoleStatus.FAILED, Integer.valueOf(count));\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#ABORTED} tasks\n */\n public HostRoleCommandStatusSummaryDTO aborted(int count) {\n put(HostRoleStatus.ABORTED, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#TIMEDOUT} tasks\n */\n public HostRoleCommandStatusSummaryDTO timedout(int count) {\n put(HostRoleStatus.TIMEDOUT, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#IN_PROGRESS} tasks\n */\n public HostRoleCommandStatusSummaryDTO inProgress(int count) {\n put(HostRoleStatus.IN_PROGRESS, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#PENDING} tasks\n */\n public HostRoleCommandStatusSummaryDTO pending(int count) {\n put(HostRoleStatus.PENDING, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#QUEUED} tasks\n */\n public HostRoleCommandStatusSummaryDTO queued(int count) {\n put(HostRoleStatus.QUEUED, count);\n return this;\n }\n\n /**\n * For testing, set the number of {@link HostRoleStatus#SKIPPED_FAILED} tasks\n */\n public HostRoleCommandStatusSummaryDTO skippedFailed(int count) {\n put(HostRoleStatus.SKIPPED_FAILED, count);\n return this;\n }\n}\n"} {"task_id": "Java_2399", "language": "Java", "task_type": "method_signature", "source_file": "java/github/open-telemetry/opentelemetry-java-instrumentation/instrumentation/spring/spring-boot-autoconfigure/src/main/java/io/opentelemetry/instrumentation/spring/autoconfigure/exporters/otlp/OtlpGrpcSpanExporterProperties.java", "mask_start_position": 1046, "mask_end_position": 1089, "canonical_solution": "@Nullable\n public Duration getTimeout() ", "pre_mask_code": "/*\n * Copyright The OpenTelemetry Authors\n */\npackage io.opentelemetry.instrumentation.spring.autoconfigure.exporters.otlp;\n\nimport java.time.Duration;\nimport javax.annotation.Nullable;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n/**\n * Configuration for {@link io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter}.\n *\n *

Get Exporter Service Name\n *\n *

Get Exporter Endpoint\n *\n *

Get max wait time for Collector to process Span Batches\n */\n@ConfigurationProperties(prefix = \"otel.exporter.otlp\")\npublic final class OtlpGrpcSpanExporterProperties {\n\n private boolean enabled = true;\n\n @Nullable\n private String endpoint;\n\n @Nullable\n private Duration timeout;\n\n public boolean isEnabled() {\n return enabled;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n @Nullable\n public String getEndpoint() {\n return endpoint;\n }\n\n public void setEndpoint(String endpoint) {\n this.endpoint = endpoint;\n }\n\n ", "post_mask_code": "{\n return timeout;\n }\n\n public void setTimeout(Duration timeout) {\n this.timeout = timeout;\n }\n}\n"} {"task_id": "Java_2400", "language": "Java", "task_type": "method_body", "source_file": "java/github/open-telemetry/opentelemetry-java-instrumentation/instrumentation/spring/spring-boot-autoconfigure/src/main/java/io/opentelemetry/instrumentation/spring/autoconfigure/exporters/otlp/OtlpGrpcSpanExporterProperties.java", "mask_start_position": 833, "mask_end_position": 872, "canonical_solution": "{\n this.enabled = enabled;\n }", "pre_mask_code": "/*\n * Copyright The OpenTelemetry Authors\n */\npackage io.opentelemetry.instrumentation.spring.autoconfigure.exporters.otlp;\n\nimport java.time.Duration;\nimport javax.annotation.Nullable;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n/**\n * Configuration for {@link io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter}.\n *\n *

Get Exporter Service Name\n *\n *

Get Exporter Endpoint\n *\n *

Get max wait time for Collector to process Span Batches\n */\n@ConfigurationProperties(prefix = \"otel.exporter.otlp\")\npublic final class OtlpGrpcSpanExporterProperties {\n\n private boolean enabled = true;\n\n @Nullable\n private String endpoint;\n\n @Nullable\n private Duration timeout;\n\n public boolean isEnabled() {\n return enabled;\n }\n\n public void setEnabled(boolean enabled) ", "post_mask_code": "\n\n @Nullable\n public String getEndpoint() {\n return endpoint;\n }\n\n public void setEndpoint(String endpoint) {\n this.endpoint = endpoint;\n }\n\n @Nullable\n public Duration getTimeout() {\n return timeout;\n }\n\n public void setTimeout(Duration timeout) {\n this.timeout = timeout;\n }\n}\n"} {"task_id": "Java_2401", "language": "Java", "task_type": "single_line", "source_file": "java/github/open-telemetry/opentelemetry-java-instrumentation/instrumentation/spring/spring-boot-autoconfigure/src/main/java/io/opentelemetry/instrumentation/spring/autoconfigure/exporters/otlp/OtlpGrpcSpanExporterProperties.java", "mask_start_position": 1196, "mask_end_position": 1200, "canonical_solution": "out;", "pre_mask_code": "/*\n * Copyright The OpenTelemetry Authors\n */\npackage io.opentelemetry.instrumentation.spring.autoconfigure.exporters.otlp;\n\nimport java.time.Duration;\nimport javax.annotation.Nullable;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n/**\n * Configuration for {@link io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter}.\n *\n *

Get Exporter Service Name\n *\n *

Get Exporter Endpoint\n *\n *

Get max wait time for Collector to process Span Batches\n */\n@ConfigurationProperties(prefix = \"otel.exporter.otlp\")\npublic final class OtlpGrpcSpanExporterProperties {\n\n private boolean enabled = true;\n\n @Nullable\n private String endpoint;\n\n @Nullable\n private Duration timeout;\n\n public boolean isEnabled() {\n return enabled;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n @Nullable\n public String getEndpoint() {\n return endpoint;\n }\n\n public void setEndpoint(String endpoint) {\n this.endpoint = endpoint;\n }\n\n @Nullable\n public Duration getTimeout() {\n return timeout;\n }\n\n public void setTimeout(Duration timeout) {\n this.timeout = time", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2402", "language": "Java", "task_type": "method_signature", "source_file": "java/github/freenet/fred/src/freenet/client/filter/FlacPacket.java", "mask_start_position": 1094, "mask_end_position": 1134, "canonical_solution": "public BlockType getMetadataBlockType() ", "pre_mask_code": "package freenet.client.filter;\n\nimport java.nio.ByteBuffer;\n\npublic abstract class FlacPacket extends CodecPacket {\n\n FlacPacket(byte[] payload) {\n super(payload);\n }\n}\n\nclass FlacMetadataBlock extends FlacPacket {\n\n enum BlockType {\n\n STREAMINFO,\n PADDING,\n APPLICATION,\n SEEKTABLE,\n VORBIS_COMMENT,\n CUESHEET,\n PICTURE,\n UNKNOWN,\n INVALID\n }\n\n private FlacMetadataBlockHeader header = new FlacMetadataBlockHeader();\n\n FlacMetadataBlock(int header, byte[] payload) {\n super(payload);\n this.header.lastMetadataBlock = ((header & 0x80000000) >>> 31) == 1 ? true : false;\n this.header.block_type = (byte) ((header & 0x7F000000) >>> 24);\n this.header.length = (header & 0x00FFFFFF);\n }\n\n @Override\n public byte[] toArray() {\n ByteBuffer bb = ByteBuffer.allocate(getLength());\n bb.putInt(header.toInt());\n bb.put(payload);\n return bb.array();\n }\n\n public boolean isLastMetadataBlock() {\n return header.lastMetadataBlock;\n }\n\n ", "post_mask_code": "{\n switch(header.block_type) {\n case 0:\n return BlockType.STREAMINFO;\n case 1:\n return BlockType.PADDING;\n case 2:\n return BlockType.APPLICATION;\n case 3:\n return BlockType.SEEKTABLE;\n case 4:\n return BlockType.VORBIS_COMMENT;\n case 5:\n return BlockType.CUESHEET;\n case 6:\n return BlockType.PICTURE;\n case 127:\n return BlockType.INVALID;\n default:\n return BlockType.UNKNOWN;\n }\n }\n\n public void setMetadataBlockType(BlockType type) {\n switch(type) {\n case STREAMINFO:\n this.header.block_type = 0;\n break;\n case PADDING:\n this.header.block_type = 1;\n break;\n case APPLICATION:\n this.header.block_type = 2;\n break;\n case SEEKTABLE:\n this.header.block_type = 3;\n break;\n case VORBIS_COMMENT:\n this.header.block_type = 4;\n break;\n case CUESHEET:\n this.header.block_type = 5;\n break;\n case PICTURE:\n this.header.block_type = 6;\n break;\n }\n }\n\n public FlacMetadataBlockHeader getHeader() {\n FlacMetadataBlockHeader newHeader = new FlacMetadataBlockHeader();\n newHeader.lastMetadataBlock = this.header.lastMetadataBlock;\n newHeader.block_type = this.header.block_type;\n newHeader.length = this.header.length;\n return newHeader;\n }\n\n public int getLength() {\n return 4 + header.length;\n }\n\n class FlacMetadataBlockHeader {\n\n boolean lastMetadataBlock;\n\n byte block_type;\n\n int length;\n\n public int toInt() {\n return ((lastMetadataBlock ? 1 : 0) << 31) | (block_type << 24) | length;\n }\n }\n}\n\nclass FlacFrame extends FlacPacket {\n\n FlacFrame(byte[] payload) {\n super(payload);\n }\n}\n"} {"task_id": "Java_2403", "language": "Java", "task_type": "method_body", "source_file": "java/github/freenet/fred/src/freenet/client/filter/FlacPacket.java", "mask_start_position": 1040, "mask_end_position": 1088, "canonical_solution": "{\n return header.lastMetadataBlock;\n }", "pre_mask_code": "package freenet.client.filter;\n\nimport java.nio.ByteBuffer;\n\npublic abstract class FlacPacket extends CodecPacket {\n\n FlacPacket(byte[] payload) {\n super(payload);\n }\n}\n\nclass FlacMetadataBlock extends FlacPacket {\n\n enum BlockType {\n\n STREAMINFO,\n PADDING,\n APPLICATION,\n SEEKTABLE,\n VORBIS_COMMENT,\n CUESHEET,\n PICTURE,\n UNKNOWN,\n INVALID\n }\n\n private FlacMetadataBlockHeader header = new FlacMetadataBlockHeader();\n\n FlacMetadataBlock(int header, byte[] payload) {\n super(payload);\n this.header.lastMetadataBlock = ((header & 0x80000000) >>> 31) == 1 ? true : false;\n this.header.block_type = (byte) ((header & 0x7F000000) >>> 24);\n this.header.length = (header & 0x00FFFFFF);\n }\n\n @Override\n public byte[] toArray() {\n ByteBuffer bb = ByteBuffer.allocate(getLength());\n bb.putInt(header.toInt());\n bb.put(payload);\n return bb.array();\n }\n\n public boolean isLastMetadataBlock() ", "post_mask_code": "\n\n public BlockType getMetadataBlockType() {\n switch(header.block_type) {\n case 0:\n return BlockType.STREAMINFO;\n case 1:\n return BlockType.PADDING;\n case 2:\n return BlockType.APPLICATION;\n case 3:\n return BlockType.SEEKTABLE;\n case 4:\n return BlockType.VORBIS_COMMENT;\n case 5:\n return BlockType.CUESHEET;\n case 6:\n return BlockType.PICTURE;\n case 127:\n return BlockType.INVALID;\n default:\n return BlockType.UNKNOWN;\n }\n }\n\n public void setMetadataBlockType(BlockType type) {\n switch(type) {\n case STREAMINFO:\n this.header.block_type = 0;\n break;\n case PADDING:\n this.header.block_type = 1;\n break;\n case APPLICATION:\n this.header.block_type = 2;\n break;\n case SEEKTABLE:\n this.header.block_type = 3;\n break;\n case VORBIS_COMMENT:\n this.header.block_type = 4;\n break;\n case CUESHEET:\n this.header.block_type = 5;\n break;\n case PICTURE:\n this.header.block_type = 6;\n break;\n }\n }\n\n public FlacMetadataBlockHeader getHeader() {\n FlacMetadataBlockHeader newHeader = new FlacMetadataBlockHeader();\n newHeader.lastMetadataBlock = this.header.lastMetadataBlock;\n newHeader.block_type = this.header.block_type;\n newHeader.length = this.header.length;\n return newHeader;\n }\n\n public int getLength() {\n return 4 + header.length;\n }\n\n class FlacMetadataBlockHeader {\n\n boolean lastMetadataBlock;\n\n byte block_type;\n\n int length;\n\n public int toInt() {\n return ((lastMetadataBlock ? 1 : 0) << 31) | (block_type << 24) | length;\n }\n }\n}\n\nclass FlacFrame extends FlacPacket {\n\n FlacFrame(byte[] payload) {\n super(payload);\n }\n}\n"} {"task_id": "Java_2404", "language": "Java", "task_type": "single_line", "source_file": "java/github/freenet/fred/src/freenet/client/filter/FlacPacket.java", "mask_start_position": 957, "mask_end_position": 964, "canonical_solution": "yload);", "pre_mask_code": "package freenet.client.filter;\n\nimport java.nio.ByteBuffer;\n\npublic abstract class FlacPacket extends CodecPacket {\n\n FlacPacket(byte[] payload) {\n super(payload);\n }\n}\n\nclass FlacMetadataBlock extends FlacPacket {\n\n enum BlockType {\n\n STREAMINFO,\n PADDING,\n APPLICATION,\n SEEKTABLE,\n VORBIS_COMMENT,\n CUESHEET,\n PICTURE,\n UNKNOWN,\n INVALID\n }\n\n private FlacMetadataBlockHeader header = new FlacMetadataBlockHeader();\n\n FlacMetadataBlock(int header, byte[] payload) {\n super(payload);\n this.header.lastMetadataBlock = ((header & 0x80000000) >>> 31) == 1 ? true : false;\n this.header.block_type = (byte) ((header & 0x7F000000) >>> 24);\n this.header.length = (header & 0x00FFFFFF);\n }\n\n @Override\n public byte[] toArray() {\n ByteBuffer bb = ByteBuffer.allocate(getLength());\n bb.putInt(header.toInt());\n bb.put(pa", "post_mask_code": "\n return bb.array();\n }\n\n public boolean isLastMetadataBlock() {\n return header.lastMetadataBlock;\n }\n\n public BlockType getMetadataBlockType() {\n switch(header.block_type) {\n case 0:\n return BlockType.STREAMINFO;\n case 1:\n return BlockType.PADDING;\n case 2:\n return BlockType.APPLICATION;\n case 3:\n return BlockType.SEEKTABLE;\n case 4:\n return BlockType.VORBIS_COMMENT;\n case 5:\n return BlockType.CUESHEET;\n case 6:\n return BlockType.PICTURE;\n case 127:\n return BlockType.INVALID;\n default:\n return BlockType.UNKNOWN;\n }\n }\n\n public void setMetadataBlockType(BlockType type) {\n switch(type) {\n case STREAMINFO:\n this.header.block_type = 0;\n break;\n case PADDING:\n this.header.block_type = 1;\n break;\n case APPLICATION:\n this.header.block_type = 2;\n break;\n case SEEKTABLE:\n this.header.block_type = 3;\n break;\n case VORBIS_COMMENT:\n this.header.block_type = 4;\n break;\n case CUESHEET:\n this.header.block_type = 5;\n break;\n case PICTURE:\n this.header.block_type = 6;\n break;\n }\n }\n\n public FlacMetadataBlockHeader getHeader() {\n FlacMetadataBlockHeader newHeader = new FlacMetadataBlockHeader();\n newHeader.lastMetadataBlock = this.header.lastMetadataBlock;\n newHeader.block_type = this.header.block_type;\n newHeader.length = this.header.length;\n return newHeader;\n }\n\n public int getLength() {\n return 4 + header.length;\n }\n\n class FlacMetadataBlockHeader {\n\n boolean lastMetadataBlock;\n\n byte block_type;\n\n int length;\n\n public int toInt() {\n return ((lastMetadataBlock ? 1 : 0) << 31) | (block_type << 24) | length;\n }\n }\n}\n\nclass FlacFrame extends FlacPacket {\n\n FlacFrame(byte[] payload) {\n super(payload);\n }\n}\n"} {"task_id": "Java_2405", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cpsing/tddl/tddl-parser/src/main/java/com/alibaba/cobar/parser/ast/stmt/dal/ShowBinLogEvent.java", "mask_start_position": 736, "mask_end_position": 760, "canonical_solution": "public Limit getLimit() ", "pre_mask_code": "package com.alibaba.cobar.parser.ast.stmt.dal;\n\nimport com.alibaba.cobar.parser.ast.expression.Expression;\nimport com.alibaba.cobar.parser.ast.fragment.Limit;\nimport com.alibaba.cobar.parser.visitor.SQLASTVisitor;\n\n/**\n * @author QIU Shuo\n */\npublic class ShowBinLogEvent extends DALShowStatement {\n\n private final String logName;\n\n private final Expression pos;\n\n private final Limit limit;\n\n public ShowBinLogEvent(String logName, Expression pos, Limit limit) {\n this.logName = logName;\n this.pos = pos;\n this.limit = limit;\n }\n\n public String getLogName() {\n return logName;\n }\n\n public Expression getPos() {\n return pos;\n }\n\n ", "post_mask_code": "{\n return limit;\n }\n\n @Override\n public void accept(SQLASTVisitor visitor) {\n visitor.visit(this);\n }\n}\n"} {"task_id": "Java_2406", "language": "Java", "task_type": "method_body", "source_file": "java/github/cpsing/tddl/tddl-parser/src/main/java/com/alibaba/cobar/parser/ast/stmt/dal/ShowBinLogEvent.java", "mask_start_position": 639, "mask_end_position": 670, "canonical_solution": "{\n return logName;\n }", "pre_mask_code": "package com.alibaba.cobar.parser.ast.stmt.dal;\n\nimport com.alibaba.cobar.parser.ast.expression.Expression;\nimport com.alibaba.cobar.parser.ast.fragment.Limit;\nimport com.alibaba.cobar.parser.visitor.SQLASTVisitor;\n\n/**\n * @author QIU Shuo\n */\npublic class ShowBinLogEvent extends DALShowStatement {\n\n private final String logName;\n\n private final Expression pos;\n\n private final Limit limit;\n\n public ShowBinLogEvent(String logName, Expression pos, Limit limit) {\n this.logName = logName;\n this.pos = pos;\n this.limit = limit;\n }\n\n public String getLogName() ", "post_mask_code": "\n\n public Expression getPos() {\n return pos;\n }\n\n public Limit getLimit() {\n return limit;\n }\n\n @Override\n public void accept(SQLASTVisitor visitor) {\n visitor.visit(this);\n }\n}\n"} {"task_id": "Java_2407", "language": "Java", "task_type": "single_line", "source_file": "java/github/cpsing/tddl/tddl-parser/src/main/java/com/alibaba/cobar/parser/ast/stmt/dal/ShowBinLogEvent.java", "mask_start_position": 861, "mask_end_position": 881, "canonical_solution": "visitor.visit(this);", "pre_mask_code": "package com.alibaba.cobar.parser.ast.stmt.dal;\n\nimport com.alibaba.cobar.parser.ast.expression.Expression;\nimport com.alibaba.cobar.parser.ast.fragment.Limit;\nimport com.alibaba.cobar.parser.visitor.SQLASTVisitor;\n\n/**\n * @author QIU Shuo\n */\npublic class ShowBinLogEvent extends DALShowStatement {\n\n private final String logName;\n\n private final Expression pos;\n\n private final Limit limit;\n\n public ShowBinLogEvent(String logName, Expression pos, Limit limit) {\n this.logName = logName;\n this.pos = pos;\n this.limit = limit;\n }\n\n public String getLogName() {\n return logName;\n }\n\n public Expression getPos() {\n return pos;\n }\n\n public Limit getLimit() {\n return limit;\n }\n\n @Override\n public void accept(SQLASTVisitor visitor) {\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2408", "language": "Java", "task_type": "method_signature", "source_file": "java/github/mattwright324/youtube-comment-suite/src/main/java/io/mattw/youtube/commentsuite/fxml/SCManageTagsModal.java", "mask_start_position": 2518, "mask_end_position": 2548, "canonical_solution": "private void refreshAllTags() ", "pre_mask_code": "package io.mattw.youtube.commentsuite.fxml;\n\nimport com.google.common.eventbus.Subscribe;\nimport io.mattw.youtube.commentsuite.CommentSuite;\nimport io.mattw.youtube.commentsuite.db.CommentDatabase;\nimport io.mattw.youtube.commentsuite.db.YouTubeComment;\nimport io.mattw.youtube.commentsuite.events.TagsChangeEvent;\nimport javafx.fxml.FXML;\nimport javafx.fxml.FXMLLoader;\nimport javafx.scene.control.*;\nimport javafx.scene.layout.VBox;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport java.io.IOException;\nimport java.sql.SQLException;\nimport java.util.List;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static javafx.application.Platform.runLater;\n\npublic class SCManageTagsModal extends VBox {\n\n private static final Logger logger = LogManager.getLogger();\n\n @FXML\n private Label lblAbout;\n\n @FXML\n private ListView allTags;\n\n @FXML\n private TextField tags;\n\n @FXML\n private Button btnAdd, btnRemove, btnSelect, btnFinish;\n\n private final CommentDatabase database;\n\n private List selected;\n\n public SCManageTagsModal() {\n logger.debug(\"Initialize SCManageTagsModal\");\n database = CommentSuite.getDatabase();\n CommentSuite.getEventBus().register(this);\n FXMLLoader loader = new FXMLLoader(getClass().getResource(\"SCManageTagsModal.fxml\"));\n loader.setController(this);\n loader.setRoot(this);\n try {\n loader.load();\n allTags.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);\n refreshAllTags();\n btnAdd.setOnAction(ae -> {\n try {\n database.comments().associateTags(toComments(), toTags());\n } catch (SQLException e) {\n e.printStackTrace();\n }\n });\n btnRemove.setOnAction(ae -> {\n try {\n database.comments().deassociateTags(toComments(), toTags());\n } catch (SQLException e) {\n e.printStackTrace();\n }\n });\n btnSelect.setOnAction(ae -> runLater(() -> tags.setText(String.join(\", \", allTags.getSelectionModel().getSelectedItems()))));\n } catch (IOException e) {\n logger.error(e);\n e.printStackTrace();\n }\n }\n\n @Subscribe\n public void tagsChangeEvent(TagsChangeEvent tagsChangeEvent) {\n refreshAllTags();\n }\n\n ", "post_mask_code": "{\n try {\n final List tags = database.comments().getAllTags();\n runLater(() -> {\n allTags.getItems().clear();\n allTags.getItems().addAll(tags);\n });\n } catch (SQLException e) {\n logger.error(e);\n }\n }\n\n public void withComments(List selected) {\n this.selected = selected;\n runLater(() -> lblAbout.setText(String.format(\"%s comments(s) selected\", selected.size())));\n }\n\n public List toComments() {\n return selected.stream().map(SearchCommentsListItem::getComment).collect(Collectors.toList());\n }\n\n public List toTags() {\n return Stream.of(tags.getText().split(\",\")).map(String::trim).collect(Collectors.toList());\n }\n\n public Button getBtnFinish() {\n return btnFinish;\n }\n}\n"} {"task_id": "Java_2409", "language": "Java", "task_type": "method_body", "source_file": "java/github/mattwright324/youtube-comment-suite/src/main/java/io/mattw/youtube/commentsuite/fxml/SCManageTagsModal.java", "mask_start_position": 3257, "mask_end_position": 3364, "canonical_solution": "{\n return Stream.of(tags.getText().split(\",\")).map(String::trim).collect(Collectors.toList());\n }", "pre_mask_code": "package io.mattw.youtube.commentsuite.fxml;\n\nimport com.google.common.eventbus.Subscribe;\nimport io.mattw.youtube.commentsuite.CommentSuite;\nimport io.mattw.youtube.commentsuite.db.CommentDatabase;\nimport io.mattw.youtube.commentsuite.db.YouTubeComment;\nimport io.mattw.youtube.commentsuite.events.TagsChangeEvent;\nimport javafx.fxml.FXML;\nimport javafx.fxml.FXMLLoader;\nimport javafx.scene.control.*;\nimport javafx.scene.layout.VBox;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport java.io.IOException;\nimport java.sql.SQLException;\nimport java.util.List;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static javafx.application.Platform.runLater;\n\npublic class SCManageTagsModal extends VBox {\n\n private static final Logger logger = LogManager.getLogger();\n\n @FXML\n private Label lblAbout;\n\n @FXML\n private ListView allTags;\n\n @FXML\n private TextField tags;\n\n @FXML\n private Button btnAdd, btnRemove, btnSelect, btnFinish;\n\n private final CommentDatabase database;\n\n private List selected;\n\n public SCManageTagsModal() {\n logger.debug(\"Initialize SCManageTagsModal\");\n database = CommentSuite.getDatabase();\n CommentSuite.getEventBus().register(this);\n FXMLLoader loader = new FXMLLoader(getClass().getResource(\"SCManageTagsModal.fxml\"));\n loader.setController(this);\n loader.setRoot(this);\n try {\n loader.load();\n allTags.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);\n refreshAllTags();\n btnAdd.setOnAction(ae -> {\n try {\n database.comments().associateTags(toComments(), toTags());\n } catch (SQLException e) {\n e.printStackTrace();\n }\n });\n btnRemove.setOnAction(ae -> {\n try {\n database.comments().deassociateTags(toComments(), toTags());\n } catch (SQLException e) {\n e.printStackTrace();\n }\n });\n btnSelect.setOnAction(ae -> runLater(() -> tags.setText(String.join(\", \", allTags.getSelectionModel().getSelectedItems()))));\n } catch (IOException e) {\n logger.error(e);\n e.printStackTrace();\n }\n }\n\n @Subscribe\n public void tagsChangeEvent(TagsChangeEvent tagsChangeEvent) {\n refreshAllTags();\n }\n\n private void refreshAllTags() {\n try {\n final List tags = database.comments().getAllTags();\n runLater(() -> {\n allTags.getItems().clear();\n allTags.getItems().addAll(tags);\n });\n } catch (SQLException e) {\n logger.error(e);\n }\n }\n\n public void withComments(List selected) {\n this.selected = selected;\n runLater(() -> lblAbout.setText(String.format(\"%s comments(s) selected\", selected.size())));\n }\n\n public List toComments() {\n return selected.stream().map(SearchCommentsListItem::getComment).collect(Collectors.toList());\n }\n\n public List toTags() ", "post_mask_code": "\n\n public Button getBtnFinish() {\n return btnFinish;\n }\n}\n"} {"task_id": "Java_2410", "language": "Java", "task_type": "single_line", "source_file": "java/github/mattwright324/youtube-comment-suite/src/main/java/io/mattw/youtube/commentsuite/fxml/SCManageTagsModal.java", "mask_start_position": 3336, "mask_end_position": 3358, "canonical_solution": "(Collectors.toList());", "pre_mask_code": "package io.mattw.youtube.commentsuite.fxml;\n\nimport com.google.common.eventbus.Subscribe;\nimport io.mattw.youtube.commentsuite.CommentSuite;\nimport io.mattw.youtube.commentsuite.db.CommentDatabase;\nimport io.mattw.youtube.commentsuite.db.YouTubeComment;\nimport io.mattw.youtube.commentsuite.events.TagsChangeEvent;\nimport javafx.fxml.FXML;\nimport javafx.fxml.FXMLLoader;\nimport javafx.scene.control.*;\nimport javafx.scene.layout.VBox;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport java.io.IOException;\nimport java.sql.SQLException;\nimport java.util.List;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static javafx.application.Platform.runLater;\n\npublic class SCManageTagsModal extends VBox {\n\n private static final Logger logger = LogManager.getLogger();\n\n @FXML\n private Label lblAbout;\n\n @FXML\n private ListView allTags;\n\n @FXML\n private TextField tags;\n\n @FXML\n private Button btnAdd, btnRemove, btnSelect, btnFinish;\n\n private final CommentDatabase database;\n\n private List selected;\n\n public SCManageTagsModal() {\n logger.debug(\"Initialize SCManageTagsModal\");\n database = CommentSuite.getDatabase();\n CommentSuite.getEventBus().register(this);\n FXMLLoader loader = new FXMLLoader(getClass().getResource(\"SCManageTagsModal.fxml\"));\n loader.setController(this);\n loader.setRoot(this);\n try {\n loader.load();\n allTags.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);\n refreshAllTags();\n btnAdd.setOnAction(ae -> {\n try {\n database.comments().associateTags(toComments(), toTags());\n } catch (SQLException e) {\n e.printStackTrace();\n }\n });\n btnRemove.setOnAction(ae -> {\n try {\n database.comments().deassociateTags(toComments(), toTags());\n } catch (SQLException e) {\n e.printStackTrace();\n }\n });\n btnSelect.setOnAction(ae -> runLater(() -> tags.setText(String.join(\", \", allTags.getSelectionModel().getSelectedItems()))));\n } catch (IOException e) {\n logger.error(e);\n e.printStackTrace();\n }\n }\n\n @Subscribe\n public void tagsChangeEvent(TagsChangeEvent tagsChangeEvent) {\n refreshAllTags();\n }\n\n private void refreshAllTags() {\n try {\n final List tags = database.comments().getAllTags();\n runLater(() -> {\n allTags.getItems().clear();\n allTags.getItems().addAll(tags);\n });\n } catch (SQLException e) {\n logger.error(e);\n }\n }\n\n public void withComments(List selected) {\n this.selected = selected;\n runLater(() -> lblAbout.setText(String.format(\"%s comments(s) selected\", selected.size())));\n }\n\n public List toComments() {\n return selected.stream().map(SearchCommentsListItem::getComment).collect(Collectors.toList());\n }\n\n public List toTags() {\n return Stream.of(tags.getText().split(\",\")).map(String::trim).collect", "post_mask_code": "\n }\n\n public Button getBtnFinish() {\n return btnFinish;\n }\n}\n"} {"task_id": "Java_2411", "language": "Java", "task_type": "try_statement", "source_file": "java/github/mattwright324/youtube-comment-suite/src/main/java/io/mattw/youtube/commentsuite/fxml/SCManageTagsModal.java", "mask_start_position": 2558, "mask_end_position": 2847, "canonical_solution": "try {\n final List tags = database.comments().getAllTags();\n runLater(() -> {\n allTags.getItems().clear();\n allTags.getItems().addAll(tags);\n });\n } catch (SQLException e) {\n logger.error(e);\n }", "pre_mask_code": "package io.mattw.youtube.commentsuite.fxml;\n\nimport com.google.common.eventbus.Subscribe;\nimport io.mattw.youtube.commentsuite.CommentSuite;\nimport io.mattw.youtube.commentsuite.db.CommentDatabase;\nimport io.mattw.youtube.commentsuite.db.YouTubeComment;\nimport io.mattw.youtube.commentsuite.events.TagsChangeEvent;\nimport javafx.fxml.FXML;\nimport javafx.fxml.FXMLLoader;\nimport javafx.scene.control.*;\nimport javafx.scene.layout.VBox;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport java.io.IOException;\nimport java.sql.SQLException;\nimport java.util.List;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static javafx.application.Platform.runLater;\n\npublic class SCManageTagsModal extends VBox {\n\n private static final Logger logger = LogManager.getLogger();\n\n @FXML\n private Label lblAbout;\n\n @FXML\n private ListView allTags;\n\n @FXML\n private TextField tags;\n\n @FXML\n private Button btnAdd, btnRemove, btnSelect, btnFinish;\n\n private final CommentDatabase database;\n\n private List selected;\n\n public SCManageTagsModal() {\n logger.debug(\"Initialize SCManageTagsModal\");\n database = CommentSuite.getDatabase();\n CommentSuite.getEventBus().register(this);\n FXMLLoader loader = new FXMLLoader(getClass().getResource(\"SCManageTagsModal.fxml\"));\n loader.setController(this);\n loader.setRoot(this);\n try {\n loader.load();\n allTags.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);\n refreshAllTags();\n btnAdd.setOnAction(ae -> {\n try {\n database.comments().associateTags(toComments(), toTags());\n } catch (SQLException e) {\n e.printStackTrace();\n }\n });\n btnRemove.setOnAction(ae -> {\n try {\n database.comments().deassociateTags(toComments(), toTags());\n } catch (SQLException e) {\n e.printStackTrace();\n }\n });\n btnSelect.setOnAction(ae -> runLater(() -> tags.setText(String.join(\", \", allTags.getSelectionModel().getSelectedItems()))));\n } catch (IOException e) {\n logger.error(e);\n e.printStackTrace();\n }\n }\n\n @Subscribe\n public void tagsChangeEvent(TagsChangeEvent tagsChangeEvent) {\n refreshAllTags();\n }\n\n private void refreshAllTags() {\n ", "post_mask_code": "\n }\n\n public void withComments(List selected) {\n this.selected = selected;\n runLater(() -> lblAbout.setText(String.format(\"%s comments(s) selected\", selected.size())));\n }\n\n public List toComments() {\n return selected.stream().map(SearchCommentsListItem::getComment).collect(Collectors.toList());\n }\n\n public List toTags() {\n return Stream.of(tags.getText().split(\",\")).map(String::trim).collect(Collectors.toList());\n }\n\n public Button getBtnFinish() {\n return btnFinish;\n }\n}\n"} {"task_id": "Java_2412", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/activemq-artemis/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionConsumerFlowCreditMessage.java", "mask_start_position": 1050, "mask_end_position": 1099, "canonical_solution": "@Override\n protected String getPacketString() ", "pre_mask_code": "package org.apache.activemq.artemis.core.protocol.core.impl.wireformat;\n\nimport org.apache.activemq.artemis.api.core.ActiveMQBuffer;\nimport org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;\n\npublic class SessionConsumerFlowCreditMessage extends PacketImpl {\n\n private long consumerID;\n\n private int credits;\n\n public SessionConsumerFlowCreditMessage(final long consumerID, final int credits) {\n super(SESS_FLOWTOKEN);\n this.consumerID = consumerID;\n this.credits = credits;\n }\n\n public SessionConsumerFlowCreditMessage() {\n super(SESS_FLOWTOKEN);\n }\n\n public long getConsumerID() {\n return consumerID;\n }\n\n public int getCredits() {\n return credits;\n }\n\n @Override\n public void encodeRest(final ActiveMQBuffer buffer) {\n buffer.writeLong(consumerID);\n buffer.writeInt(credits);\n }\n\n @Override\n public void decodeRest(final ActiveMQBuffer buffer) {\n consumerID = buffer.readLong();\n credits = buffer.readInt();\n }\n\n ", "post_mask_code": "{\n return super.getPacketString() + \", consumerID=\" + consumerID + \", credits=\" + credits;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = super.hashCode();\n result = prime * result + (int) (consumerID ^ (consumerID >>> 32));\n result = prime * result + credits;\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (!super.equals(obj))\n return false;\n if (!(obj instanceof SessionConsumerFlowCreditMessage))\n return false;\n SessionConsumerFlowCreditMessage other = (SessionConsumerFlowCreditMessage) obj;\n if (consumerID != other.consumerID)\n return false;\n if (credits != other.credits)\n return false;\n return true;\n }\n}\n"} {"task_id": "Java_2413", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/activemq-artemis/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionConsumerFlowCreditMessage.java", "mask_start_position": 1244, "mask_end_position": 1462, "canonical_solution": "{\n final int prime = 31;\n int result = super.hashCode();\n result = prime * result + (int) (consumerID ^ (consumerID >>> 32));\n result = prime * result + credits;\n return result;\n }", "pre_mask_code": "package org.apache.activemq.artemis.core.protocol.core.impl.wireformat;\n\nimport org.apache.activemq.artemis.api.core.ActiveMQBuffer;\nimport org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;\n\npublic class SessionConsumerFlowCreditMessage extends PacketImpl {\n\n private long consumerID;\n\n private int credits;\n\n public SessionConsumerFlowCreditMessage(final long consumerID, final int credits) {\n super(SESS_FLOWTOKEN);\n this.consumerID = consumerID;\n this.credits = credits;\n }\n\n public SessionConsumerFlowCreditMessage() {\n super(SESS_FLOWTOKEN);\n }\n\n public long getConsumerID() {\n return consumerID;\n }\n\n public int getCredits() {\n return credits;\n }\n\n @Override\n public void encodeRest(final ActiveMQBuffer buffer) {\n buffer.writeLong(consumerID);\n buffer.writeInt(credits);\n }\n\n @Override\n public void decodeRest(final ActiveMQBuffer buffer) {\n consumerID = buffer.readLong();\n credits = buffer.readInt();\n }\n\n @Override\n protected String getPacketString() {\n return super.getPacketString() + \", consumerID=\" + consumerID + \", credits=\" + credits;\n }\n\n @Override\n public int hashCode() ", "post_mask_code": "\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (!super.equals(obj))\n return false;\n if (!(obj instanceof SessionConsumerFlowCreditMessage))\n return false;\n SessionConsumerFlowCreditMessage other = (SessionConsumerFlowCreditMessage) obj;\n if (consumerID != other.consumerID)\n return false;\n if (credits != other.credits)\n return false;\n return true;\n }\n}\n"} {"task_id": "Java_2414", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/activemq-artemis/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/SessionConsumerFlowCreditMessage.java", "mask_start_position": 1759, "mask_end_position": 1804, "canonical_solution": "her = (SessionConsumerFlowCreditMessage) obj;", "pre_mask_code": "package org.apache.activemq.artemis.core.protocol.core.impl.wireformat;\n\nimport org.apache.activemq.artemis.api.core.ActiveMQBuffer;\nimport org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;\n\npublic class SessionConsumerFlowCreditMessage extends PacketImpl {\n\n private long consumerID;\n\n private int credits;\n\n public SessionConsumerFlowCreditMessage(final long consumerID, final int credits) {\n super(SESS_FLOWTOKEN);\n this.consumerID = consumerID;\n this.credits = credits;\n }\n\n public SessionConsumerFlowCreditMessage() {\n super(SESS_FLOWTOKEN);\n }\n\n public long getConsumerID() {\n return consumerID;\n }\n\n public int getCredits() {\n return credits;\n }\n\n @Override\n public void encodeRest(final ActiveMQBuffer buffer) {\n buffer.writeLong(consumerID);\n buffer.writeInt(credits);\n }\n\n @Override\n public void decodeRest(final ActiveMQBuffer buffer) {\n consumerID = buffer.readLong();\n credits = buffer.readInt();\n }\n\n @Override\n protected String getPacketString() {\n return super.getPacketString() + \", consumerID=\" + consumerID + \", credits=\" + credits;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = super.hashCode();\n result = prime * result + (int) (consumerID ^ (consumerID >>> 32));\n result = prime * result + credits;\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (!super.equals(obj))\n return false;\n if (!(obj instanceof SessionConsumerFlowCreditMessage))\n return false;\n SessionConsumerFlowCreditMessage ot", "post_mask_code": "\n if (consumerID != other.consumerID)\n return false;\n if (credits != other.credits)\n return false;\n return true;\n }\n}\n"} {"task_id": "Java_2415", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ApsaraDB/galaxycdc/polardbx-cdc-common/src/main/java/com/aliyun/polardbx/binlog/AddressUtil.java", "mask_start_position": 2590, "mask_end_position": 2653, "canonical_solution": "private static boolean isValidHostAddress(InetAddress address) ", "pre_mask_code": "package com.aliyun.polardbx.binlog;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.net.InetAddress;\nimport java.net.NetworkInterface;\nimport java.util.Enumeration;\nimport java.util.regex.Pattern;\n\n/**\n * @author chengjin.lyf on 2020/7/22 4:51 下午\n * @since 1.0.25\n */\npublic class AddressUtil {\n\n private static final String LOCALHOST_IP = \"127.0.0.1\";\n\n private static final String EMPTY_IP = \"0.0.0.0\";\n\n private static final Pattern IP_PATTERN = Pattern.compile(\"[0-9]{1,3}(\\\\.[0-9]{1,3}){3,}\");\n\n private static final Logger logger = LoggerFactory.getLogger(AddressUtil.class);\n\n public static InetAddress getHostAddress() {\n InetAddress localAddress = null;\n try {\n localAddress = InetAddress.getLocalHost();\n if (isValidHostAddress(localAddress)) {\n return localAddress;\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving local host ip address, try scan network card ip address. cause: \" + e.getMessage());\n }\n try {\n Enumeration interfaces = NetworkInterface.getNetworkInterfaces();\n if (interfaces != null) {\n while (interfaces.hasMoreElements()) {\n try {\n NetworkInterface network = interfaces.nextElement();\n Enumeration addresses = network.getInetAddresses();\n if (addresses != null) {\n while (addresses.hasMoreElements()) {\n try {\n InetAddress address = addresses.nextElement();\n if (isValidHostAddress(address)) {\n return address;\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving network card ip address. cause:\" + e.getMessage());\n }\n }\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving network card ip address. cause:\" + e.getMessage());\n }\n }\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving network card ip address. cause:\" + e.getMessage());\n }\n logger.error(\"Could not get local host ip address, will use 127.0.0.1 instead.\");\n return localAddress;\n }\n\n ", "post_mask_code": "{\n if (address == null || address.isLoopbackAddress()) {\n return false;\n }\n String name = address.getHostAddress();\n return (name != null && !EMPTY_IP.equals(name) && !LOCALHOST_IP.equals(name) && IP_PATTERN.matcher(name).matches());\n }\n}\n"} {"task_id": "Java_2416", "language": "Java", "task_type": "method_body", "source_file": "java/github/ApsaraDB/galaxycdc/polardbx-cdc-common/src/main/java/com/aliyun/polardbx/binlog/AddressUtil.java", "mask_start_position": 2653, "mask_end_position": 2931, "canonical_solution": "{\n if (address == null || address.isLoopbackAddress()) {\n return false;\n }\n String name = address.getHostAddress();\n return (name != null && !EMPTY_IP.equals(name) && !LOCALHOST_IP.equals(name) && IP_PATTERN.matcher(name).matches());\n }", "pre_mask_code": "package com.aliyun.polardbx.binlog;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.net.InetAddress;\nimport java.net.NetworkInterface;\nimport java.util.Enumeration;\nimport java.util.regex.Pattern;\n\n/**\n * @author chengjin.lyf on 2020/7/22 4:51 下午\n * @since 1.0.25\n */\npublic class AddressUtil {\n\n private static final String LOCALHOST_IP = \"127.0.0.1\";\n\n private static final String EMPTY_IP = \"0.0.0.0\";\n\n private static final Pattern IP_PATTERN = Pattern.compile(\"[0-9]{1,3}(\\\\.[0-9]{1,3}){3,}\");\n\n private static final Logger logger = LoggerFactory.getLogger(AddressUtil.class);\n\n public static InetAddress getHostAddress() {\n InetAddress localAddress = null;\n try {\n localAddress = InetAddress.getLocalHost();\n if (isValidHostAddress(localAddress)) {\n return localAddress;\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving local host ip address, try scan network card ip address. cause: \" + e.getMessage());\n }\n try {\n Enumeration interfaces = NetworkInterface.getNetworkInterfaces();\n if (interfaces != null) {\n while (interfaces.hasMoreElements()) {\n try {\n NetworkInterface network = interfaces.nextElement();\n Enumeration addresses = network.getInetAddresses();\n if (addresses != null) {\n while (addresses.hasMoreElements()) {\n try {\n InetAddress address = addresses.nextElement();\n if (isValidHostAddress(address)) {\n return address;\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving network card ip address. cause:\" + e.getMessage());\n }\n }\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving network card ip address. cause:\" + e.getMessage());\n }\n }\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving network card ip address. cause:\" + e.getMessage());\n }\n logger.error(\"Could not get local host ip address, will use 127.0.0.1 instead.\");\n return localAddress;\n }\n\n private static boolean isValidHostAddress(InetAddress address) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2417", "language": "Java", "task_type": "single_line", "source_file": "java/github/ApsaraDB/galaxycdc/polardbx-cdc-common/src/main/java/com/aliyun/polardbx/binlog/AddressUtil.java", "mask_start_position": 2769, "mask_end_position": 2800, "canonical_solution": "ame = address.getHostAddress();", "pre_mask_code": "package com.aliyun.polardbx.binlog;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.net.InetAddress;\nimport java.net.NetworkInterface;\nimport java.util.Enumeration;\nimport java.util.regex.Pattern;\n\n/**\n * @author chengjin.lyf on 2020/7/22 4:51 下午\n * @since 1.0.25\n */\npublic class AddressUtil {\n\n private static final String LOCALHOST_IP = \"127.0.0.1\";\n\n private static final String EMPTY_IP = \"0.0.0.0\";\n\n private static final Pattern IP_PATTERN = Pattern.compile(\"[0-9]{1,3}(\\\\.[0-9]{1,3}){3,}\");\n\n private static final Logger logger = LoggerFactory.getLogger(AddressUtil.class);\n\n public static InetAddress getHostAddress() {\n InetAddress localAddress = null;\n try {\n localAddress = InetAddress.getLocalHost();\n if (isValidHostAddress(localAddress)) {\n return localAddress;\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving local host ip address, try scan network card ip address. cause: \" + e.getMessage());\n }\n try {\n Enumeration interfaces = NetworkInterface.getNetworkInterfaces();\n if (interfaces != null) {\n while (interfaces.hasMoreElements()) {\n try {\n NetworkInterface network = interfaces.nextElement();\n Enumeration addresses = network.getInetAddresses();\n if (addresses != null) {\n while (addresses.hasMoreElements()) {\n try {\n InetAddress address = addresses.nextElement();\n if (isValidHostAddress(address)) {\n return address;\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving network card ip address. cause:\" + e.getMessage());\n }\n }\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving network card ip address. cause:\" + e.getMessage());\n }\n }\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving network card ip address. cause:\" + e.getMessage());\n }\n logger.error(\"Could not get local host ip address, will use 127.0.0.1 instead.\");\n return localAddress;\n }\n\n private static boolean isValidHostAddress(InetAddress address) {\n if (address == null || address.isLoopbackAddress()) {\n return false;\n }\n String n", "post_mask_code": "\n return (name != null && !EMPTY_IP.equals(name) && !LOCALHOST_IP.equals(name) && IP_PATTERN.matcher(name).matches());\n }\n}\n"} {"task_id": "Java_2418", "language": "Java", "task_type": "try_statement", "source_file": "java/github/ApsaraDB/galaxycdc/polardbx-cdc-common/src/main/java/com/aliyun/polardbx/binlog/AddressUtil.java", "mask_start_position": 1593, "mask_end_position": 2057, "canonical_solution": "try {\n InetAddress address = addresses.nextElement();\n if (isValidHostAddress(address)) {\n return address;\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving network card ip address. cause:\" + e.getMessage());\n }", "pre_mask_code": "package com.aliyun.polardbx.binlog;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.net.InetAddress;\nimport java.net.NetworkInterface;\nimport java.util.Enumeration;\nimport java.util.regex.Pattern;\n\n/**\n * @author chengjin.lyf on 2020/7/22 4:51 下午\n * @since 1.0.25\n */\npublic class AddressUtil {\n\n private static final String LOCALHOST_IP = \"127.0.0.1\";\n\n private static final String EMPTY_IP = \"0.0.0.0\";\n\n private static final Pattern IP_PATTERN = Pattern.compile(\"[0-9]{1,3}(\\\\.[0-9]{1,3}){3,}\");\n\n private static final Logger logger = LoggerFactory.getLogger(AddressUtil.class);\n\n public static InetAddress getHostAddress() {\n InetAddress localAddress = null;\n try {\n localAddress = InetAddress.getLocalHost();\n if (isValidHostAddress(localAddress)) {\n return localAddress;\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving local host ip address, try scan network card ip address. cause: \" + e.getMessage());\n }\n try {\n Enumeration interfaces = NetworkInterface.getNetworkInterfaces();\n if (interfaces != null) {\n while (interfaces.hasMoreElements()) {\n try {\n NetworkInterface network = interfaces.nextElement();\n Enumeration addresses = network.getInetAddresses();\n if (addresses != null) {\n while (addresses.hasMoreElements()) {\n ", "post_mask_code": "\n }\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving network card ip address. cause:\" + e.getMessage());\n }\n }\n }\n } catch (Throwable e) {\n logger.warn(\"Failed to retriving network card ip address. cause:\" + e.getMessage());\n }\n logger.error(\"Could not get local host ip address, will use 127.0.0.1 instead.\");\n return localAddress;\n }\n\n private static boolean isValidHostAddress(InetAddress address) {\n if (address == null || address.isLoopbackAddress()) {\n return false;\n }\n String name = address.getHostAddress();\n return (name != null && !EMPTY_IP.equals(name) && !LOCALHOST_IP.equals(name) && IP_PATTERN.matcher(name).matches());\n }\n}\n"} {"task_id": "Java_2419", "language": "Java", "task_type": "method_signature", "source_file": "java/github/kangjianwei/LearningJDK/src/sun/util/resources/cldr/ext/TimeZoneNames_en_SD.java", "mask_start_position": 199, "mask_end_position": 254, "canonical_solution": "@Override\n protected final Object[][] getContents() ", "pre_mask_code": "/*\n * COPYRIGHT AND PERMISSION NOTICE\n *\n */\npackage sun.util.resources.cldr.ext;\n\nimport sun.util.resources.TimeZoneNamesBundle;\n\npublic class TimeZoneNames_en_SD extends TimeZoneNamesBundle {\n\n ", "post_mask_code": "{\n final String[] Africa_Central = new String[] { \"Central Africa Time\", \"CAT\", \"Central African Summer Time\", \"CAST\", \"Central Africa Time\", \"CAT\" };\n final String[] Africa_Eastern = new String[] { \"East Africa Time\", \"EAT\", \"Eastern African Summer Time\", \"EAST\", \"Eastern Africa Time\", \"EAT\" };\n final String[] Africa_Southern = new String[] { \"South Africa Standard Time\", \"SAST\", \"South Africa Summer Time\", \"SAST\", \"South Africa Time\", \"SAT\" };\n final String[] Africa_Western = new String[] { \"West Africa Standard Time\", \"WAT\", \"West Africa Summer Time\", \"WAST\", \"West Africa Time\", \"WAT\" };\n final Object[][] data = new Object[][] { { \"UTC\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Nairobi\", Africa_Eastern }, { \"Africa/Libreville\", Africa_Western }, { \"Africa/Lusaka\", Africa_Central }, { \"Africa/Gaborone\", Africa_Central }, { \"Africa/Maputo\", Africa_Central }, { \"Africa/Windhoek\", Africa_Central }, { \"Africa/Mbabane\", Africa_Southern }, { \"Africa/Mogadishu\", Africa_Eastern }, { \"Asia/Famagusta\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Harare\", Africa_Central }, { \"Africa/Douala\", Africa_Western }, { \"Pacific/Bougainville\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Asmera\", Africa_Eastern }, { \"Europe/Ulyanovsk\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Kampala\", Africa_Eastern }, { \"Africa/Sao_Tome\", Africa_Western }, { \"Africa/Khartoum\", Africa_Central }, { \"Africa/Malabo\", Africa_Western }, { \"Africa/Johannesburg\", Africa_Southern }, { \"Africa/Ndjamena\", Africa_Western }, { \"Africa/Bujumbura\", Africa_Central }, { \"Africa/Bangui\", Africa_Western }, { \"Africa/Lagos\", Africa_Western }, { \"Africa/Brazzaville\", Africa_Western }, { \"Africa/Luanda\", Africa_Western }, { \"Africa/Porto-Novo\", Africa_Western }, { \"Europe/Astrakhan\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Juba\", Africa_Eastern }, { \"Asia/Srednekolymsk\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Europe/Saratov\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Dar_es_Salaam\", Africa_Eastern }, { \"Antarctica/Palmer\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Maseru\", Africa_Southern }, { \"Africa/Kinshasa\", Africa_Western }, { \"Africa/Addis_Ababa\", Africa_Eastern }, { \"Africa/Lubumbashi\", Africa_Central }, { \"Africa/Djibouti\", Africa_Eastern }, { \"Africa/Kigali\", Africa_Central }, { \"Indian/Antananarivo\", Africa_Eastern }, { \"America/Punta_Arenas\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Niamey\", Africa_Western }, { \"Indian/Mayotte\", Africa_Eastern }, { \"Africa/Blantyre\", Africa_Central }, { \"Indian/Comoro\", Africa_Eastern } };\n return data;\n }\n}\n"} {"task_id": "Java_2420", "language": "Java", "task_type": "single_line", "source_file": "java/github/kangjianwei/LearningJDK/src/sun/util/resources/cldr/ext/TimeZoneNames_en_SD.java", "mask_start_position": 476, "mask_end_position": 564, "canonical_solution": "ica Time\", \"EAT\", \"Eastern African Summer Time\", \"EAST\", \"Eastern Africa Time\", \"EAT\" };", "pre_mask_code": "/*\n * COPYRIGHT AND PERMISSION NOTICE\n *\n */\npackage sun.util.resources.cldr.ext;\n\nimport sun.util.resources.TimeZoneNamesBundle;\n\npublic class TimeZoneNames_en_SD extends TimeZoneNamesBundle {\n\n @Override\n protected final Object[][] getContents() {\n final String[] Africa_Central = new String[] { \"Central Africa Time\", \"CAT\", \"Central African Summer Time\", \"CAST\", \"Central Africa Time\", \"CAT\" };\n final String[] Africa_Eastern = new String[] { \"East Afr", "post_mask_code": "\n final String[] Africa_Southern = new String[] { \"South Africa Standard Time\", \"SAST\", \"South Africa Summer Time\", \"SAST\", \"South Africa Time\", \"SAT\" };\n final String[] Africa_Western = new String[] { \"West Africa Standard Time\", \"WAT\", \"West Africa Summer Time\", \"WAST\", \"West Africa Time\", \"WAT\" };\n final Object[][] data = new Object[][] { { \"UTC\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Nairobi\", Africa_Eastern }, { \"Africa/Libreville\", Africa_Western }, { \"Africa/Lusaka\", Africa_Central }, { \"Africa/Gaborone\", Africa_Central }, { \"Africa/Maputo\", Africa_Central }, { \"Africa/Windhoek\", Africa_Central }, { \"Africa/Mbabane\", Africa_Southern }, { \"Africa/Mogadishu\", Africa_Eastern }, { \"Asia/Famagusta\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Harare\", Africa_Central }, { \"Africa/Douala\", Africa_Western }, { \"Pacific/Bougainville\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Asmera\", Africa_Eastern }, { \"Europe/Ulyanovsk\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Kampala\", Africa_Eastern }, { \"Africa/Sao_Tome\", Africa_Western }, { \"Africa/Khartoum\", Africa_Central }, { \"Africa/Malabo\", Africa_Western }, { \"Africa/Johannesburg\", Africa_Southern }, { \"Africa/Ndjamena\", Africa_Western }, { \"Africa/Bujumbura\", Africa_Central }, { \"Africa/Bangui\", Africa_Western }, { \"Africa/Lagos\", Africa_Western }, { \"Africa/Brazzaville\", Africa_Western }, { \"Africa/Luanda\", Africa_Western }, { \"Africa/Porto-Novo\", Africa_Western }, { \"Europe/Astrakhan\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Juba\", Africa_Eastern }, { \"Asia/Srednekolymsk\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Europe/Saratov\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Dar_es_Salaam\", Africa_Eastern }, { \"Antarctica/Palmer\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Maseru\", Africa_Southern }, { \"Africa/Kinshasa\", Africa_Western }, { \"Africa/Addis_Ababa\", Africa_Eastern }, { \"Africa/Lubumbashi\", Africa_Central }, { \"Africa/Djibouti\", Africa_Eastern }, { \"Africa/Kigali\", Africa_Central }, { \"Indian/Antananarivo\", Africa_Eastern }, { \"America/Punta_Arenas\", new String[] { \"\", \"\", \"\", \"\", \"\", \"\" } }, { \"Africa/Niamey\", Africa_Western }, { \"Indian/Mayotte\", Africa_Eastern }, { \"Africa/Blantyre\", Africa_Central }, { \"Indian/Comoro\", Africa_Eastern } };\n return data;\n }\n}\n"} {"task_id": "Java_2421", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Android-Avanzado/androidapp/S08-api-minitwitter/CL19-TweetListAdapter/app/src/main/java/com/androidavanzado/cl05_minitwitter/TweetListFragment.java", "mask_start_position": 1382, "mask_end_position": 1444, "canonical_solution": "@Override\n public void onCreate(Bundle savedInstanceState) ", "pre_mask_code": "package com.androidavanzado.cl05_minitwitter;\n\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport com.androidavanzado.cl05_minitwitter.retrofit.response.Tweet;\nimport java.util.List;\n\npublic class TweetListFragment extends Fragment {\n\n // TODO: Customize parameter argument names\n private static final String ARG_COLUMN_COUNT = \"column-count\";\n\n // TODO: Customize parameters\n private int mColumnCount = 1;\n\n RecyclerView recyclerView;\n\n MyTweetRecyclerViewAdapter adapter;\n\n List tweetList;\n\n /**\n * Mandatory empty constructor for the fragment manager to instantiate the\n * fragment (e.g. upon screen orientation changes).\n */\n public TweetListFragment() {\n }\n\n // TODO: Customize parameter initialization\n @SuppressWarnings(\"unused\")\n public static TweetListFragment newInstance(int columnCount) {\n TweetListFragment fragment = new TweetListFragment();\n Bundle args = new Bundle();\n args.putInt(ARG_COLUMN_COUNT, columnCount);\n fragment.setArguments(args);\n return fragment;\n }\n\n ", "post_mask_code": "{\n super.onCreate(savedInstanceState);\n if (getArguments() != null) {\n mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);\n }\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(R.layout.fragment_tweet_list, container, false);\n // Set the adapter\n if (view instanceof RecyclerView) {\n Context context = view.getContext();\n recyclerView = (RecyclerView) view;\n if (mColumnCount <= 1) {\n recyclerView.setLayoutManager(new LinearLayoutManager(context));\n } else {\n recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));\n }\n loadTweetData();\n }\n return view;\n }\n\n private void loadTweetData() {\n adapter = new MyTweetRecyclerViewAdapter(getActivity(), tweetList);\n recyclerView.setAdapter(adapter);\n }\n}\n"} {"task_id": "Java_2422", "language": "Java", "task_type": "method_body", "source_file": "java/github/Android-Avanzado/androidapp/S08-api-minitwitter/CL19-TweetListAdapter/app/src/main/java/com/androidavanzado/cl05_minitwitter/TweetListFragment.java", "mask_start_position": 1157, "mask_end_position": 1376, "canonical_solution": "{\n TweetListFragment fragment = new TweetListFragment();\n Bundle args = new Bundle();\n args.putInt(ARG_COLUMN_COUNT, columnCount);\n fragment.setArguments(args);\n return fragment;\n }", "pre_mask_code": "package com.androidavanzado.cl05_minitwitter;\n\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport com.androidavanzado.cl05_minitwitter.retrofit.response.Tweet;\nimport java.util.List;\n\npublic class TweetListFragment extends Fragment {\n\n // TODO: Customize parameter argument names\n private static final String ARG_COLUMN_COUNT = \"column-count\";\n\n // TODO: Customize parameters\n private int mColumnCount = 1;\n\n RecyclerView recyclerView;\n\n MyTweetRecyclerViewAdapter adapter;\n\n List tweetList;\n\n /**\n * Mandatory empty constructor for the fragment manager to instantiate the\n * fragment (e.g. upon screen orientation changes).\n */\n public TweetListFragment() {\n }\n\n // TODO: Customize parameter initialization\n @SuppressWarnings(\"unused\")\n public static TweetListFragment newInstance(int columnCount) ", "post_mask_code": "\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (getArguments() != null) {\n mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);\n }\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(R.layout.fragment_tweet_list, container, false);\n // Set the adapter\n if (view instanceof RecyclerView) {\n Context context = view.getContext();\n recyclerView = (RecyclerView) view;\n if (mColumnCount <= 1) {\n recyclerView.setLayoutManager(new LinearLayoutManager(context));\n } else {\n recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));\n }\n loadTweetData();\n }\n return view;\n }\n\n private void loadTweetData() {\n adapter = new MyTweetRecyclerViewAdapter(getActivity(), tweetList);\n recyclerView.setAdapter(adapter);\n }\n}\n"} {"task_id": "Java_2423", "language": "Java", "task_type": "single_line", "source_file": "java/github/Android-Avanzado/androidapp/S08-api-minitwitter/CL19-TweetListAdapter/app/src/main/java/com/androidavanzado/cl05_minitwitter/TweetListFragment.java", "mask_start_position": 1323, "mask_end_position": 1345, "canonical_solution": "nt.setArguments(args);", "pre_mask_code": "package com.androidavanzado.cl05_minitwitter;\n\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport com.androidavanzado.cl05_minitwitter.retrofit.response.Tweet;\nimport java.util.List;\n\npublic class TweetListFragment extends Fragment {\n\n // TODO: Customize parameter argument names\n private static final String ARG_COLUMN_COUNT = \"column-count\";\n\n // TODO: Customize parameters\n private int mColumnCount = 1;\n\n RecyclerView recyclerView;\n\n MyTweetRecyclerViewAdapter adapter;\n\n List tweetList;\n\n /**\n * Mandatory empty constructor for the fragment manager to instantiate the\n * fragment (e.g. upon screen orientation changes).\n */\n public TweetListFragment() {\n }\n\n // TODO: Customize parameter initialization\n @SuppressWarnings(\"unused\")\n public static TweetListFragment newInstance(int columnCount) {\n TweetListFragment fragment = new TweetListFragment();\n Bundle args = new Bundle();\n args.putInt(ARG_COLUMN_COUNT, columnCount);\n fragme", "post_mask_code": "\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (getArguments() != null) {\n mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);\n }\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(R.layout.fragment_tweet_list, container, false);\n // Set the adapter\n if (view instanceof RecyclerView) {\n Context context = view.getContext();\n recyclerView = (RecyclerView) view;\n if (mColumnCount <= 1) {\n recyclerView.setLayoutManager(new LinearLayoutManager(context));\n } else {\n recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));\n }\n loadTweetData();\n }\n return view;\n }\n\n private void loadTweetData() {\n adapter = new MyTweetRecyclerViewAdapter(getActivity(), tweetList);\n recyclerView.setAdapter(adapter);\n }\n}\n"} {"task_id": "Java_2424", "language": "Java", "task_type": "method_signature", "source_file": "java/github/TNG/JGiven/jgiven-core/src/main/java/com/tngtech/jgiven/impl/Scenario.java", "mask_start_position": 2208, "mask_end_position": 2292, "canonical_solution": "public static Scenario create(Class stepsClass) ", "pre_mask_code": "package com.tngtech.jgiven.impl;\n\n/**\n * A default scenario implementation that takes three type arguments,\n * one for each stage.\n *\n * @param the Given stage\n * @param then When stage\n * @param then Then stage\n */\npublic class Scenario extends ScenarioBase {\n\n private GIVEN givenStage;\n\n private WHEN whenStage;\n\n private THEN thenStage;\n\n private final Class givenClass;\n\n private final Class whenClass;\n\n private final Class thenClass;\n\n private Scenario(Class stageClass) {\n this.givenClass = stageClass;\n this.whenClass = null;\n this.thenClass = null;\n }\n\n public Scenario(Class givenClass, Class whenClass, Class thenClass) {\n this.givenClass = givenClass;\n this.whenClass = whenClass;\n this.thenClass = thenClass;\n }\n\n public GIVEN getGivenStage() {\n return givenStage;\n }\n\n public WHEN getWhenStage() {\n return whenStage;\n }\n\n public THEN getThenStage() {\n return thenStage;\n }\n\n public void addIntroWord(String word) {\n executor.addIntroWord(word);\n }\n\n /**\n * Creates a scenario with 3 different steps classes.\n *\n * To share state between the different steps instances use the\n * {@link com.tngtech.jgiven.annotation.ScenarioState} annotation\n *\n * @param givenClass the Given steps class\n * @param whenClass the When steps class\n * @param thenClass the Then steps class\n * @return the new scenario\n */\n public static Scenario create(Class givenClass, Class whenClass, Class thenClass) {\n return new Scenario(givenClass, whenClass, thenClass);\n }\n\n /**\n * Creates a scenario with a single steps class.\n * Only creates a single steps instance for all three step types,\n * so no {@link com.tngtech.jgiven.annotation.ScenarioState} annotations are needed\n * to share state between the different steps instances.\n *\n * @param stepsClass the class to use for given, when and then steps\n * @return the new scenario\n */\n ", "post_mask_code": "{\n return new Scenario(stepsClass);\n }\n\n /**\n * Describes the scenario. Must be called before any step invocation.\n * @param description the description\n * @return this for a fluent interface\n */\n @Override\n public Scenario startScenario(String description) {\n super.startScenario(description);\n return this;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n protected void initialize() {\n super.initialize();\n if (whenClass == null) {\n givenStage = (GIVEN) executor.addStage(givenClass);\n whenStage = (WHEN) givenStage;\n thenStage = (THEN) givenStage;\n } else {\n givenStage = executor.addStage(givenClass);\n whenStage = executor.addStage(whenClass);\n thenStage = executor.addStage(thenClass);\n }\n }\n\n public Scenario as(String description) {\n return startScenario(description);\n }\n\n public GIVEN given() {\n return given(\"Given\");\n }\n\n public WHEN when() {\n return when(\"When\");\n }\n\n public THEN then() {\n return then(\"Then\");\n }\n\n public GIVEN given(String translatedGiven) {\n addIntroWord(translatedGiven);\n return getGivenStage();\n }\n\n public WHEN when(String translatedWhen) {\n addIntroWord(translatedWhen);\n return getWhenStage();\n }\n\n public THEN then(String translatedThen) {\n addIntroWord(translatedThen);\n return getThenStage();\n }\n}\n"} {"task_id": "Java_2425", "language": "Java", "task_type": "method_body", "source_file": "java/github/TNG/JGiven/jgiven-core/src/main/java/com/tngtech/jgiven/impl/Scenario.java", "mask_start_position": 3328, "mask_end_position": 3366, "canonical_solution": "{\n return given(\"Given\");\n }", "pre_mask_code": "package com.tngtech.jgiven.impl;\n\n/**\n * A default scenario implementation that takes three type arguments,\n * one for each stage.\n *\n * @param the Given stage\n * @param then When stage\n * @param then Then stage\n */\npublic class Scenario extends ScenarioBase {\n\n private GIVEN givenStage;\n\n private WHEN whenStage;\n\n private THEN thenStage;\n\n private final Class givenClass;\n\n private final Class whenClass;\n\n private final Class thenClass;\n\n private Scenario(Class stageClass) {\n this.givenClass = stageClass;\n this.whenClass = null;\n this.thenClass = null;\n }\n\n public Scenario(Class givenClass, Class whenClass, Class thenClass) {\n this.givenClass = givenClass;\n this.whenClass = whenClass;\n this.thenClass = thenClass;\n }\n\n public GIVEN getGivenStage() {\n return givenStage;\n }\n\n public WHEN getWhenStage() {\n return whenStage;\n }\n\n public THEN getThenStage() {\n return thenStage;\n }\n\n public void addIntroWord(String word) {\n executor.addIntroWord(word);\n }\n\n /**\n * Creates a scenario with 3 different steps classes.\n *\n * To share state between the different steps instances use the\n * {@link com.tngtech.jgiven.annotation.ScenarioState} annotation\n *\n * @param givenClass the Given steps class\n * @param whenClass the When steps class\n * @param thenClass the Then steps class\n * @return the new scenario\n */\n public static Scenario create(Class givenClass, Class whenClass, Class thenClass) {\n return new Scenario(givenClass, whenClass, thenClass);\n }\n\n /**\n * Creates a scenario with a single steps class.\n * Only creates a single steps instance for all three step types,\n * so no {@link com.tngtech.jgiven.annotation.ScenarioState} annotations are needed\n * to share state between the different steps instances.\n *\n * @param stepsClass the class to use for given, when and then steps\n * @return the new scenario\n */\n public static Scenario create(Class stepsClass) {\n return new Scenario(stepsClass);\n }\n\n /**\n * Describes the scenario. Must be called before any step invocation.\n * @param description the description\n * @return this for a fluent interface\n */\n @Override\n public Scenario startScenario(String description) {\n super.startScenario(description);\n return this;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n protected void initialize() {\n super.initialize();\n if (whenClass == null) {\n givenStage = (GIVEN) executor.addStage(givenClass);\n whenStage = (WHEN) givenStage;\n thenStage = (THEN) givenStage;\n } else {\n givenStage = executor.addStage(givenClass);\n whenStage = executor.addStage(whenClass);\n thenStage = executor.addStage(thenClass);\n }\n }\n\n public Scenario as(String description) {\n return startScenario(description);\n }\n\n public GIVEN given() ", "post_mask_code": "\n\n public WHEN when() {\n return when(\"When\");\n }\n\n public THEN then() {\n return then(\"Then\");\n }\n\n public GIVEN given(String translatedGiven) {\n addIntroWord(translatedGiven);\n return getGivenStage();\n }\n\n public WHEN when(String translatedWhen) {\n addIntroWord(translatedWhen);\n return getWhenStage();\n }\n\n public THEN then(String translatedThen) {\n addIntroWord(translatedThen);\n return getThenStage();\n }\n}\n"} {"task_id": "Java_2426", "language": "Java", "task_type": "single_line", "source_file": "java/github/TNG/JGiven/jgiven-core/src/main/java/com/tngtech/jgiven/impl/Scenario.java", "mask_start_position": 2678, "mask_end_position": 2689, "canonical_solution": "eturn this;", "pre_mask_code": "package com.tngtech.jgiven.impl;\n\n/**\n * A default scenario implementation that takes three type arguments,\n * one for each stage.\n *\n * @param the Given stage\n * @param then When stage\n * @param then Then stage\n */\npublic class Scenario extends ScenarioBase {\n\n private GIVEN givenStage;\n\n private WHEN whenStage;\n\n private THEN thenStage;\n\n private final Class givenClass;\n\n private final Class whenClass;\n\n private final Class thenClass;\n\n private Scenario(Class stageClass) {\n this.givenClass = stageClass;\n this.whenClass = null;\n this.thenClass = null;\n }\n\n public Scenario(Class givenClass, Class whenClass, Class thenClass) {\n this.givenClass = givenClass;\n this.whenClass = whenClass;\n this.thenClass = thenClass;\n }\n\n public GIVEN getGivenStage() {\n return givenStage;\n }\n\n public WHEN getWhenStage() {\n return whenStage;\n }\n\n public THEN getThenStage() {\n return thenStage;\n }\n\n public void addIntroWord(String word) {\n executor.addIntroWord(word);\n }\n\n /**\n * Creates a scenario with 3 different steps classes.\n *\n * To share state between the different steps instances use the\n * {@link com.tngtech.jgiven.annotation.ScenarioState} annotation\n *\n * @param givenClass the Given steps class\n * @param whenClass the When steps class\n * @param thenClass the Then steps class\n * @return the new scenario\n */\n public static Scenario create(Class givenClass, Class whenClass, Class thenClass) {\n return new Scenario(givenClass, whenClass, thenClass);\n }\n\n /**\n * Creates a scenario with a single steps class.\n * Only creates a single steps instance for all three step types,\n * so no {@link com.tngtech.jgiven.annotation.ScenarioState} annotations are needed\n * to share state between the different steps instances.\n *\n * @param stepsClass the class to use for given, when and then steps\n * @return the new scenario\n */\n public static Scenario create(Class stepsClass) {\n return new Scenario(stepsClass);\n }\n\n /**\n * Describes the scenario. Must be called before any step invocation.\n * @param description the description\n * @return this for a fluent interface\n */\n @Override\n public Scenario startScenario(String description) {\n super.startScenario(description);\n r", "post_mask_code": "\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n protected void initialize() {\n super.initialize();\n if (whenClass == null) {\n givenStage = (GIVEN) executor.addStage(givenClass);\n whenStage = (WHEN) givenStage;\n thenStage = (THEN) givenStage;\n } else {\n givenStage = executor.addStage(givenClass);\n whenStage = executor.addStage(whenClass);\n thenStage = executor.addStage(thenClass);\n }\n }\n\n public Scenario as(String description) {\n return startScenario(description);\n }\n\n public GIVEN given() {\n return given(\"Given\");\n }\n\n public WHEN when() {\n return when(\"When\");\n }\n\n public THEN then() {\n return then(\"Then\");\n }\n\n public GIVEN given(String translatedGiven) {\n addIntroWord(translatedGiven);\n return getGivenStage();\n }\n\n public WHEN when(String translatedWhen) {\n addIntroWord(translatedWhen);\n return getWhenStage();\n }\n\n public THEN then(String translatedThen) {\n addIntroWord(translatedThen);\n return getThenStage();\n }\n}\n"} {"task_id": "Java_2427", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/TNG/JGiven/jgiven-core/src/main/java/com/tngtech/jgiven/impl/Scenario.java", "mask_start_position": 2542, "mask_end_position": 2695, "canonical_solution": "@Override\n public Scenario startScenario(String description) {\n super.startScenario(description);\n return this;\n }", "pre_mask_code": "package com.tngtech.jgiven.impl;\n\n/**\n * A default scenario implementation that takes three type arguments,\n * one for each stage.\n *\n * @param the Given stage\n * @param then When stage\n * @param then Then stage\n */\npublic class Scenario extends ScenarioBase {\n\n private GIVEN givenStage;\n\n private WHEN whenStage;\n\n private THEN thenStage;\n\n private final Class givenClass;\n\n private final Class whenClass;\n\n private final Class thenClass;\n\n private Scenario(Class stageClass) {\n this.givenClass = stageClass;\n this.whenClass = null;\n this.thenClass = null;\n }\n\n public Scenario(Class givenClass, Class whenClass, Class thenClass) {\n this.givenClass = givenClass;\n this.whenClass = whenClass;\n this.thenClass = thenClass;\n }\n\n public GIVEN getGivenStage() {\n return givenStage;\n }\n\n public WHEN getWhenStage() {\n return whenStage;\n }\n\n public THEN getThenStage() {\n return thenStage;\n }\n\n public void addIntroWord(String word) {\n executor.addIntroWord(word);\n }\n\n /**\n * Creates a scenario with 3 different steps classes.\n *\n * To share state between the different steps instances use the\n * {@link com.tngtech.jgiven.annotation.ScenarioState} annotation\n *\n * @param givenClass the Given steps class\n * @param whenClass the When steps class\n * @param thenClass the Then steps class\n * @return the new scenario\n */\n public static Scenario create(Class givenClass, Class whenClass, Class thenClass) {\n return new Scenario(givenClass, whenClass, thenClass);\n }\n\n /**\n * Creates a scenario with a single steps class.\n * Only creates a single steps instance for all three step types,\n * so no {@link com.tngtech.jgiven.annotation.ScenarioState} annotations are needed\n * to share state between the different steps instances.\n *\n * @param stepsClass the class to use for given, when and then steps\n * @return the new scenario\n */\n public static Scenario create(Class stepsClass) {\n return new Scenario(stepsClass);\n }\n\n /**\n * Describes the scenario. Must be called before any step invocation.\n * @param description the description\n * @return this for a fluent interface\n */\n ", "post_mask_code": "\n\n @Override\n @SuppressWarnings(\"unchecked\")\n protected void initialize() {\n super.initialize();\n if (whenClass == null) {\n givenStage = (GIVEN) executor.addStage(givenClass);\n whenStage = (WHEN) givenStage;\n thenStage = (THEN) givenStage;\n } else {\n givenStage = executor.addStage(givenClass);\n whenStage = executor.addStage(whenClass);\n thenStage = executor.addStage(thenClass);\n }\n }\n\n public Scenario as(String description) {\n return startScenario(description);\n }\n\n public GIVEN given() {\n return given(\"Given\");\n }\n\n public WHEN when() {\n return when(\"When\");\n }\n\n public THEN then() {\n return then(\"Then\");\n }\n\n public GIVEN given(String translatedGiven) {\n addIntroWord(translatedGiven);\n return getGivenStage();\n }\n\n public WHEN when(String translatedWhen) {\n addIntroWord(translatedWhen);\n return getWhenStage();\n }\n\n public THEN then(String translatedThen) {\n addIntroWord(translatedThen);\n return getThenStage();\n }\n}\n"} {"task_id": "Java_2428", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SkriptLang/Skript/src/main/java/ch/njol/skript/expressions/ExprEnchantmentOfferCost.java", "mask_start_position": 3155, "mask_end_position": 3204, "canonical_solution": "@Override\n protected String getPropertyName() ", "pre_mask_code": "/**\n * This file is part of Skript.\n */\npackage ch.njol.skript.expressions;\n\nimport org.bukkit.enchantments.EnchantmentOffer;\nimport org.bukkit.event.Event;\nimport org.eclipse.jdt.annotation.Nullable;\nimport ch.njol.skript.Skript;\nimport ch.njol.skript.classes.Changer.ChangeMode;\nimport ch.njol.skript.doc.Description;\nimport ch.njol.skript.doc.Examples;\nimport ch.njol.skript.doc.Name;\nimport ch.njol.skript.doc.RequiredPlugins;\nimport ch.njol.skript.doc.Since;\nimport ch.njol.skript.expressions.base.SimplePropertyExpression;\nimport ch.njol.skript.util.Experience;\nimport ch.njol.util.coll.CollectionUtils;\n\n@Name(\"Enchantment Offer Enchantment Cost\")\n@Description({ \"The cost of an enchantment offer. This is displayed to the right of an enchantment offer.\", \" If the cost is changed, it will always be at least 1.\", \" This changes how many levels are required to enchant, but does not change the number of levels removed.\", \" To change the number of levels removed, use the enchant event.\" })\n@Examples(\"set cost of enchantment offer 1 to 50\")\n@Since(\"2.5\")\n@RequiredPlugins(\"1.11 or newer\")\npublic class ExprEnchantmentOfferCost extends SimplePropertyExpression {\n\n static {\n if (Skript.classExists(\"org.bukkit.enchantments.EnchantmentOffer\"))\n register(ExprEnchantmentOfferCost.class, Long.class, \"[enchant[ment]] cost\", \"enchantmentoffers\");\n }\n\n @Override\n public Long convert(final EnchantmentOffer offer) {\n return (long) offer.getCost();\n }\n\n @Override\n @Nullable\n public Class[] acceptChange(ChangeMode mode) {\n if (mode == ChangeMode.REMOVE || mode == ChangeMode.REMOVE_ALL || mode == ChangeMode.RESET)\n return null;\n return CollectionUtils.array(Number.class, Experience.class);\n }\n\n @Override\n public void change(Event event, @Nullable Object[] delta, ChangeMode mode) {\n EnchantmentOffer[] offers = getExpr().getArray(event);\n if (offers.length == 0 || delta == null)\n return;\n Object c = delta[0];\n int cost = c instanceof Number ? ((Number) c).intValue() : ((Experience) c).getXP();\n if (cost < 1)\n return;\n int change;\n switch(mode) {\n case SET:\n for (EnchantmentOffer offer : offers) offer.setCost(cost);\n break;\n case ADD:\n for (EnchantmentOffer offer : offers) {\n change = offer.getCost() + cost;\n if (change < 1)\n return;\n offer.setCost(change);\n }\n break;\n case REMOVE:\n for (EnchantmentOffer offer : offers) {\n change = offer.getCost() - cost;\n if (change < 1)\n return;\n offer.setCost(change);\n }\n break;\n case RESET:\n case DELETE:\n case REMOVE_ALL:\n assert false;\n }\n }\n\n @Override\n public Class getReturnType() {\n return Long.class;\n }\n\n ", "post_mask_code": "{\n return \"enchantment cost\";\n }\n}\n"} {"task_id": "Java_2429", "language": "Java", "task_type": "method_body", "source_file": "java/github/SkriptLang/Skript/src/main/java/ch/njol/skript/expressions/ExprEnchantmentOfferCost.java", "mask_start_position": 1472, "mask_end_position": 1518, "canonical_solution": "{\n return (long) offer.getCost();\n }", "pre_mask_code": "/**\n * This file is part of Skript.\n */\npackage ch.njol.skript.expressions;\n\nimport org.bukkit.enchantments.EnchantmentOffer;\nimport org.bukkit.event.Event;\nimport org.eclipse.jdt.annotation.Nullable;\nimport ch.njol.skript.Skript;\nimport ch.njol.skript.classes.Changer.ChangeMode;\nimport ch.njol.skript.doc.Description;\nimport ch.njol.skript.doc.Examples;\nimport ch.njol.skript.doc.Name;\nimport ch.njol.skript.doc.RequiredPlugins;\nimport ch.njol.skript.doc.Since;\nimport ch.njol.skript.expressions.base.SimplePropertyExpression;\nimport ch.njol.skript.util.Experience;\nimport ch.njol.util.coll.CollectionUtils;\n\n@Name(\"Enchantment Offer Enchantment Cost\")\n@Description({ \"The cost of an enchantment offer. This is displayed to the right of an enchantment offer.\", \" If the cost is changed, it will always be at least 1.\", \" This changes how many levels are required to enchant, but does not change the number of levels removed.\", \" To change the number of levels removed, use the enchant event.\" })\n@Examples(\"set cost of enchantment offer 1 to 50\")\n@Since(\"2.5\")\n@RequiredPlugins(\"1.11 or newer\")\npublic class ExprEnchantmentOfferCost extends SimplePropertyExpression {\n\n static {\n if (Skript.classExists(\"org.bukkit.enchantments.EnchantmentOffer\"))\n register(ExprEnchantmentOfferCost.class, Long.class, \"[enchant[ment]] cost\", \"enchantmentoffers\");\n }\n\n @Override\n public Long convert(final EnchantmentOffer offer) ", "post_mask_code": "\n\n @Override\n @Nullable\n public Class[] acceptChange(ChangeMode mode) {\n if (mode == ChangeMode.REMOVE || mode == ChangeMode.REMOVE_ALL || mode == ChangeMode.RESET)\n return null;\n return CollectionUtils.array(Number.class, Experience.class);\n }\n\n @Override\n public void change(Event event, @Nullable Object[] delta, ChangeMode mode) {\n EnchantmentOffer[] offers = getExpr().getArray(event);\n if (offers.length == 0 || delta == null)\n return;\n Object c = delta[0];\n int cost = c instanceof Number ? ((Number) c).intValue() : ((Experience) c).getXP();\n if (cost < 1)\n return;\n int change;\n switch(mode) {\n case SET:\n for (EnchantmentOffer offer : offers) offer.setCost(cost);\n break;\n case ADD:\n for (EnchantmentOffer offer : offers) {\n change = offer.getCost() + cost;\n if (change < 1)\n return;\n offer.setCost(change);\n }\n break;\n case REMOVE:\n for (EnchantmentOffer offer : offers) {\n change = offer.getCost() - cost;\n if (change < 1)\n return;\n offer.setCost(change);\n }\n break;\n case RESET:\n case DELETE:\n case REMOVE_ALL:\n assert false;\n }\n }\n\n @Override\n public Class getReturnType() {\n return Long.class;\n }\n\n @Override\n protected String getPropertyName() {\n return \"enchantment cost\";\n }\n}\n"} {"task_id": "Java_2430", "language": "Java", "task_type": "single_line", "source_file": "java/github/SkriptLang/Skript/src/main/java/ch/njol/skript/expressions/ExprEnchantmentOfferCost.java", "mask_start_position": 2204, "mask_end_position": 2214, "canonical_solution": "nt change;", "pre_mask_code": "/**\n * This file is part of Skript.\n */\npackage ch.njol.skript.expressions;\n\nimport org.bukkit.enchantments.EnchantmentOffer;\nimport org.bukkit.event.Event;\nimport org.eclipse.jdt.annotation.Nullable;\nimport ch.njol.skript.Skript;\nimport ch.njol.skript.classes.Changer.ChangeMode;\nimport ch.njol.skript.doc.Description;\nimport ch.njol.skript.doc.Examples;\nimport ch.njol.skript.doc.Name;\nimport ch.njol.skript.doc.RequiredPlugins;\nimport ch.njol.skript.doc.Since;\nimport ch.njol.skript.expressions.base.SimplePropertyExpression;\nimport ch.njol.skript.util.Experience;\nimport ch.njol.util.coll.CollectionUtils;\n\n@Name(\"Enchantment Offer Enchantment Cost\")\n@Description({ \"The cost of an enchantment offer. This is displayed to the right of an enchantment offer.\", \" If the cost is changed, it will always be at least 1.\", \" This changes how many levels are required to enchant, but does not change the number of levels removed.\", \" To change the number of levels removed, use the enchant event.\" })\n@Examples(\"set cost of enchantment offer 1 to 50\")\n@Since(\"2.5\")\n@RequiredPlugins(\"1.11 or newer\")\npublic class ExprEnchantmentOfferCost extends SimplePropertyExpression {\n\n static {\n if (Skript.classExists(\"org.bukkit.enchantments.EnchantmentOffer\"))\n register(ExprEnchantmentOfferCost.class, Long.class, \"[enchant[ment]] cost\", \"enchantmentoffers\");\n }\n\n @Override\n public Long convert(final EnchantmentOffer offer) {\n return (long) offer.getCost();\n }\n\n @Override\n @Nullable\n public Class[] acceptChange(ChangeMode mode) {\n if (mode == ChangeMode.REMOVE || mode == ChangeMode.REMOVE_ALL || mode == ChangeMode.RESET)\n return null;\n return CollectionUtils.array(Number.class, Experience.class);\n }\n\n @Override\n public void change(Event event, @Nullable Object[] delta, ChangeMode mode) {\n EnchantmentOffer[] offers = getExpr().getArray(event);\n if (offers.length == 0 || delta == null)\n return;\n Object c = delta[0];\n int cost = c instanceof Number ? ((Number) c).intValue() : ((Experience) c).getXP();\n if (cost < 1)\n return;\n i", "post_mask_code": "\n switch(mode) {\n case SET:\n for (EnchantmentOffer offer : offers) offer.setCost(cost);\n break;\n case ADD:\n for (EnchantmentOffer offer : offers) {\n change = offer.getCost() + cost;\n if (change < 1)\n return;\n offer.setCost(change);\n }\n break;\n case REMOVE:\n for (EnchantmentOffer offer : offers) {\n change = offer.getCost() - cost;\n if (change < 1)\n return;\n offer.setCost(change);\n }\n break;\n case RESET:\n case DELETE:\n case REMOVE_ALL:\n assert false;\n }\n }\n\n @Override\n public Class getReturnType() {\n return Long.class;\n }\n\n @Override\n protected String getPropertyName() {\n return \"enchantment cost\";\n }\n}\n"} {"task_id": "Java_2431", "language": "Java", "task_type": "method_signature", "source_file": "java/github/KscSDK/ksc-sdk-java/ksc-sdk-java-vcs/src/main/java/com/ksc/vcs/model/transform/UpdateNotifyCfgRequestMarshaller.java", "mask_start_position": 1911, "mask_end_position": 2011, "canonical_solution": "@Override\n public void validateArgument(UpdateNotifyCfgRequest originalRequest) throws Exception ", "pre_mask_code": "package com.ksc.vcs.model.transform;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.ksc.KscClientException;\nimport com.ksc.Request;\nimport com.ksc.http.HttpMethodName;\nimport com.ksc.transform.Marshaller;\nimport com.ksc.util.StringUtils;\nimport com.ksc.vcs.model.ParamConstant;\nimport com.ksc.vcs.model.UpdateNotifyCfgRequest;\nimport org.apache.http.HttpHeaders;\nimport org.apache.http.entity.ContentType;\nimport java.io.ByteArrayInputStream;\n\n/**\n * UpdateNotifyCfgRequest Marshaller\n */\npublic class UpdateNotifyCfgRequestMarshaller extends BaseMarshaller implements Marshaller, UpdateNotifyCfgRequest> {\n\n private static UpdateNotifyCfgRequestMarshaller instance;\n\n private UpdateNotifyCfgRequestMarshaller() {\n }\n\n public synchronized static UpdateNotifyCfgRequestMarshaller getInstance() {\n if (instance == null) {\n instance = new UpdateNotifyCfgRequestMarshaller();\n }\n return instance;\n }\n\n @Override\n public Request marshall(UpdateNotifyCfgRequest updateNotifyCfgRequest) throws Exception {\n Request request = this.doCommonProc(updateNotifyCfgRequest, HttpMethodName.PUT, ParamConstant.UPDATE_NOTIFY_CFG_ACTION, updateNotifyCfgRequest.getVersion());\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());\n request.addParameter(ParamConstant.UNIQUE_NAME, updateNotifyCfgRequest.getUniqueName());\n request.addParameter(ParamConstant.APP, updateNotifyCfgRequest.getApp());\n ObjectMapper objectMapper = new ObjectMapper();\n String serviceRecogCfgListStr = objectMapper.writeValueAsString(updateNotifyCfgRequest.getNotifyCfg());\n request.setContent(new ByteArrayInputStream(serviceRecogCfgListStr.getBytes(\"UTF-8\")));\n return request;\n }\n\n ", "post_mask_code": "{\n if (originalRequest == null || StringUtils.isNullOrEmpty(originalRequest.getUniqueName()) || StringUtils.isNullOrEmpty(originalRequest.getApp()) || originalRequest.getNotifyCfg() == null) {\n throw new KscClientException(\"Invalid argument passed to marshall(...)\");\n }\n }\n}\n"} {"task_id": "Java_2432", "language": "Java", "task_type": "method_body", "source_file": "java/github/KscSDK/ksc-sdk-java/ksc-sdk-java-vcs/src/main/java/com/ksc/vcs/model/transform/UpdateNotifyCfgRequestMarshaller.java", "mask_start_position": 878, "mask_end_position": 1015, "canonical_solution": "{\n if (instance == null) {\n instance = new UpdateNotifyCfgRequestMarshaller();\n }\n return instance;\n }", "pre_mask_code": "package com.ksc.vcs.model.transform;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.ksc.KscClientException;\nimport com.ksc.Request;\nimport com.ksc.http.HttpMethodName;\nimport com.ksc.transform.Marshaller;\nimport com.ksc.util.StringUtils;\nimport com.ksc.vcs.model.ParamConstant;\nimport com.ksc.vcs.model.UpdateNotifyCfgRequest;\nimport org.apache.http.HttpHeaders;\nimport org.apache.http.entity.ContentType;\nimport java.io.ByteArrayInputStream;\n\n/**\n * UpdateNotifyCfgRequest Marshaller\n */\npublic class UpdateNotifyCfgRequestMarshaller extends BaseMarshaller implements Marshaller, UpdateNotifyCfgRequest> {\n\n private static UpdateNotifyCfgRequestMarshaller instance;\n\n private UpdateNotifyCfgRequestMarshaller() {\n }\n\n public synchronized static UpdateNotifyCfgRequestMarshaller getInstance() ", "post_mask_code": "\n\n @Override\n public Request marshall(UpdateNotifyCfgRequest updateNotifyCfgRequest) throws Exception {\n Request request = this.doCommonProc(updateNotifyCfgRequest, HttpMethodName.PUT, ParamConstant.UPDATE_NOTIFY_CFG_ACTION, updateNotifyCfgRequest.getVersion());\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());\n request.addParameter(ParamConstant.UNIQUE_NAME, updateNotifyCfgRequest.getUniqueName());\n request.addParameter(ParamConstant.APP, updateNotifyCfgRequest.getApp());\n ObjectMapper objectMapper = new ObjectMapper();\n String serviceRecogCfgListStr = objectMapper.writeValueAsString(updateNotifyCfgRequest.getNotifyCfg());\n request.setContent(new ByteArrayInputStream(serviceRecogCfgListStr.getBytes(\"UTF-8\")));\n return request;\n }\n\n @Override\n public void validateArgument(UpdateNotifyCfgRequest originalRequest) throws Exception {\n if (originalRequest == null || StringUtils.isNullOrEmpty(originalRequest.getUniqueName()) || StringUtils.isNullOrEmpty(originalRequest.getApp()) || originalRequest.getNotifyCfg() == null) {\n throw new KscClientException(\"Invalid argument passed to marshall(...)\");\n }\n }\n}\n"} {"task_id": "Java_2433", "language": "Java", "task_type": "single_line", "source_file": "java/github/KscSDK/ksc-sdk-java/ksc-sdk-java-vcs/src/main/java/com/ksc/vcs/model/transform/UpdateNotifyCfgRequestMarshaller.java", "mask_start_position": 1481, "mask_end_position": 1529, "canonical_solution": "E_NAME, updateNotifyCfgRequest.getUniqueName());", "pre_mask_code": "package com.ksc.vcs.model.transform;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.ksc.KscClientException;\nimport com.ksc.Request;\nimport com.ksc.http.HttpMethodName;\nimport com.ksc.transform.Marshaller;\nimport com.ksc.util.StringUtils;\nimport com.ksc.vcs.model.ParamConstant;\nimport com.ksc.vcs.model.UpdateNotifyCfgRequest;\nimport org.apache.http.HttpHeaders;\nimport org.apache.http.entity.ContentType;\nimport java.io.ByteArrayInputStream;\n\n/**\n * UpdateNotifyCfgRequest Marshaller\n */\npublic class UpdateNotifyCfgRequestMarshaller extends BaseMarshaller implements Marshaller, UpdateNotifyCfgRequest> {\n\n private static UpdateNotifyCfgRequestMarshaller instance;\n\n private UpdateNotifyCfgRequestMarshaller() {\n }\n\n public synchronized static UpdateNotifyCfgRequestMarshaller getInstance() {\n if (instance == null) {\n instance = new UpdateNotifyCfgRequestMarshaller();\n }\n return instance;\n }\n\n @Override\n public Request marshall(UpdateNotifyCfgRequest updateNotifyCfgRequest) throws Exception {\n Request request = this.doCommonProc(updateNotifyCfgRequest, HttpMethodName.PUT, ParamConstant.UPDATE_NOTIFY_CFG_ACTION, updateNotifyCfgRequest.getVersion());\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());\n request.addParameter(ParamConstant.UNIQU", "post_mask_code": "\n request.addParameter(ParamConstant.APP, updateNotifyCfgRequest.getApp());\n ObjectMapper objectMapper = new ObjectMapper();\n String serviceRecogCfgListStr = objectMapper.writeValueAsString(updateNotifyCfgRequest.getNotifyCfg());\n request.setContent(new ByteArrayInputStream(serviceRecogCfgListStr.getBytes(\"UTF-8\")));\n return request;\n }\n\n @Override\n public void validateArgument(UpdateNotifyCfgRequest originalRequest) throws Exception {\n if (originalRequest == null || StringUtils.isNullOrEmpty(originalRequest.getUniqueName()) || StringUtils.isNullOrEmpty(originalRequest.getApp()) || originalRequest.getNotifyCfg() == null) {\n throw new KscClientException(\"Invalid argument passed to marshall(...)\");\n }\n }\n}\n"} {"task_id": "Java_2434", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ihmcrobotics/ihmc-open-robotics-software/ihmc-communication/src/main/java/us/ihmc/communication/packetCommunicator/KryoPacketCloningSendingTask.java", "mask_start_position": 2127, "mask_end_position": 2154, "canonical_solution": "public boolean isRunning() ", "pre_mask_code": "package us.ihmc.communication.packetCommunicator;\n\nimport java.util.ArrayList;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport com.esotericsoftware.kryo.Kryo;\nimport us.ihmc.communication.net.NetClassList;\nimport us.ihmc.communication.net.PacketConsumer;\nimport us.ihmc.communication.packets.Packet;\n\npublic class KryoPacketCloningSendingTask implements Callable {\n\n private PacketConsumer consumer;\n\n private final ConcurrentLinkedQueue packetQueue = new ConcurrentLinkedQueue();\n\n private Packet packetToSend;\n\n private final AtomicBoolean isRunning = new AtomicBoolean();\n\n private final Kryo kryo = new Kryo();\n\n private final ArrayList> packetList = new ArrayList>();\n\n private final boolean clonePackets = true;\n\n // should just populate the class list using the passed in classes instead of the whole classlist\n public KryoPacketCloningSendingTask(NetClassList classList, PacketConsumer consumer) {\n classList.getPacketClassList(packetList);\n for (Class clazz : packetList) {\n kryo.register(clazz);\n }\n for (Class type : classList.getPacketFieldList()) {\n kryo.register(type);\n }\n this.consumer = consumer;\n }\n\n public void setConsumer(PacketConsumer consumer) {\n this.consumer = consumer;\n }\n\n public PacketConsumer getConsumer() {\n return this.consumer;\n }\n\n public void submitPacket(Packet packet) {\n packetQueue.add(packet);\n }\n\n @Override\n public Void call() throws Exception {\n isRunning.set(true);\n while ((packetToSend = packetQueue.poll()) != null) {\n if (packetList.contains(packetToSend.getClass()) && clonePackets) {\n Packet clonedPacket = kryo.copy(packetToSend);\n consumer.receivedPacket(clonedPacket);\n } else {\n consumer.receivedPacket(packetToSend);\n }\n }\n isRunning.set(false);\n return null;\n }\n\n ", "post_mask_code": "{\n return isRunning.get();\n }\n}\n"} {"task_id": "Java_2435", "language": "Java", "task_type": "method_body", "source_file": "java/github/ihmcrobotics/ihmc-open-robotics-software/ihmc-communication/src/main/java/us/ihmc/communication/packetCommunicator/KryoPacketCloningSendingTask.java", "mask_start_position": 1575, "mask_end_position": 1615, "canonical_solution": "{\n packetQueue.add(packet);\n }", "pre_mask_code": "package us.ihmc.communication.packetCommunicator;\n\nimport java.util.ArrayList;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport com.esotericsoftware.kryo.Kryo;\nimport us.ihmc.communication.net.NetClassList;\nimport us.ihmc.communication.net.PacketConsumer;\nimport us.ihmc.communication.packets.Packet;\n\npublic class KryoPacketCloningSendingTask implements Callable {\n\n private PacketConsumer consumer;\n\n private final ConcurrentLinkedQueue packetQueue = new ConcurrentLinkedQueue();\n\n private Packet packetToSend;\n\n private final AtomicBoolean isRunning = new AtomicBoolean();\n\n private final Kryo kryo = new Kryo();\n\n private final ArrayList> packetList = new ArrayList>();\n\n private final boolean clonePackets = true;\n\n // should just populate the class list using the passed in classes instead of the whole classlist\n public KryoPacketCloningSendingTask(NetClassList classList, PacketConsumer consumer) {\n classList.getPacketClassList(packetList);\n for (Class clazz : packetList) {\n kryo.register(clazz);\n }\n for (Class type : classList.getPacketFieldList()) {\n kryo.register(type);\n }\n this.consumer = consumer;\n }\n\n public void setConsumer(PacketConsumer consumer) {\n this.consumer = consumer;\n }\n\n public PacketConsumer getConsumer() {\n return this.consumer;\n }\n\n public void submitPacket(Packet packet) ", "post_mask_code": "\n\n @Override\n public Void call() throws Exception {\n isRunning.set(true);\n while ((packetToSend = packetQueue.poll()) != null) {\n if (packetList.contains(packetToSend.getClass()) && clonePackets) {\n Packet clonedPacket = kryo.copy(packetToSend);\n consumer.receivedPacket(clonedPacket);\n } else {\n consumer.receivedPacket(packetToSend);\n }\n }\n isRunning.set(false);\n return null;\n }\n\n public boolean isRunning() {\n return isRunning.get();\n }\n}\n"} {"task_id": "Java_2436", "language": "Java", "task_type": "single_line", "source_file": "java/github/ihmcrobotics/ihmc-open-robotics-software/ihmc-communication/src/main/java/us/ihmc/communication/packetCommunicator/KryoPacketCloningSendingTask.java", "mask_start_position": 2105, "mask_end_position": 2115, "canonical_solution": "turn null;", "pre_mask_code": "package us.ihmc.communication.packetCommunicator;\n\nimport java.util.ArrayList;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport com.esotericsoftware.kryo.Kryo;\nimport us.ihmc.communication.net.NetClassList;\nimport us.ihmc.communication.net.PacketConsumer;\nimport us.ihmc.communication.packets.Packet;\n\npublic class KryoPacketCloningSendingTask implements Callable {\n\n private PacketConsumer consumer;\n\n private final ConcurrentLinkedQueue packetQueue = new ConcurrentLinkedQueue();\n\n private Packet packetToSend;\n\n private final AtomicBoolean isRunning = new AtomicBoolean();\n\n private final Kryo kryo = new Kryo();\n\n private final ArrayList> packetList = new ArrayList>();\n\n private final boolean clonePackets = true;\n\n // should just populate the class list using the passed in classes instead of the whole classlist\n public KryoPacketCloningSendingTask(NetClassList classList, PacketConsumer consumer) {\n classList.getPacketClassList(packetList);\n for (Class clazz : packetList) {\n kryo.register(clazz);\n }\n for (Class type : classList.getPacketFieldList()) {\n kryo.register(type);\n }\n this.consumer = consumer;\n }\n\n public void setConsumer(PacketConsumer consumer) {\n this.consumer = consumer;\n }\n\n public PacketConsumer getConsumer() {\n return this.consumer;\n }\n\n public void submitPacket(Packet packet) {\n packetQueue.add(packet);\n }\n\n @Override\n public Void call() throws Exception {\n isRunning.set(true);\n while ((packetToSend = packetQueue.poll()) != null) {\n if (packetList.contains(packetToSend.getClass()) && clonePackets) {\n Packet clonedPacket = kryo.copy(packetToSend);\n consumer.receivedPacket(clonedPacket);\n } else {\n consumer.receivedPacket(packetToSend);\n }\n }\n isRunning.set(false);\n re", "post_mask_code": "\n }\n\n public boolean isRunning() {\n return isRunning.get();\n }\n}\n"} {"task_id": "Java_2437", "language": "Java", "task_type": "while_statement", "source_file": "java/github/ihmcrobotics/ihmc-open-robotics-software/ihmc-communication/src/main/java/us/ihmc/communication/packetCommunicator/KryoPacketCloningSendingTask.java", "mask_start_position": 1710, "mask_end_position": 2064, "canonical_solution": "while ((packetToSend = packetQueue.poll()) != null) {\n if (packetList.contains(packetToSend.getClass()) && clonePackets) {\n Packet clonedPacket = kryo.copy(packetToSend);\n consumer.receivedPacket(clonedPacket);\n } else {\n consumer.receivedPacket(packetToSend);\n }\n }", "pre_mask_code": "package us.ihmc.communication.packetCommunicator;\n\nimport java.util.ArrayList;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport com.esotericsoftware.kryo.Kryo;\nimport us.ihmc.communication.net.NetClassList;\nimport us.ihmc.communication.net.PacketConsumer;\nimport us.ihmc.communication.packets.Packet;\n\npublic class KryoPacketCloningSendingTask implements Callable {\n\n private PacketConsumer consumer;\n\n private final ConcurrentLinkedQueue packetQueue = new ConcurrentLinkedQueue();\n\n private Packet packetToSend;\n\n private final AtomicBoolean isRunning = new AtomicBoolean();\n\n private final Kryo kryo = new Kryo();\n\n private final ArrayList> packetList = new ArrayList>();\n\n private final boolean clonePackets = true;\n\n // should just populate the class list using the passed in classes instead of the whole classlist\n public KryoPacketCloningSendingTask(NetClassList classList, PacketConsumer consumer) {\n classList.getPacketClassList(packetList);\n for (Class clazz : packetList) {\n kryo.register(clazz);\n }\n for (Class type : classList.getPacketFieldList()) {\n kryo.register(type);\n }\n this.consumer = consumer;\n }\n\n public void setConsumer(PacketConsumer consumer) {\n this.consumer = consumer;\n }\n\n public PacketConsumer getConsumer() {\n return this.consumer;\n }\n\n public void submitPacket(Packet packet) {\n packetQueue.add(packet);\n }\n\n @Override\n public Void call() throws Exception {\n isRunning.set(true);\n ", "post_mask_code": "\n isRunning.set(false);\n return null;\n }\n\n public boolean isRunning() {\n return isRunning.get();\n }\n}\n"} {"task_id": "Java_2438", "language": "Java", "task_type": "method_signature", "source_file": "java/github/OCR4all/OCR4all/src/main/java/de/uniwue/batch/process/ResultGenerationStrategy.java", "mask_start_position": 878, "mask_end_position": 909, "canonical_solution": "public String getProcessName() ", "pre_mask_code": "package de.uniwue.batch.process;\n\n/**\n * Defines result generation strategies.\n *\n * @author Herbert Baier\n * @version 1.0\n * @since 1.8\n */\npublic enum ResultGenerationStrategy {\n\n combine(\"fillUp\"), groundTruth(\"gt\"), prediction(\"pred\");\n\n public static final ResultGenerationStrategy defaultStrategy = combine;\n\n /**\n * The argument in the batch workflow configuration.\n */\n public static final String argument = \"--strategy\";\n\n /**\n * The process name.\n */\n private final String processName;\n\n /**\n * Creates a result generation strategy.\n *\n * @param processName The process name.\n * @since 1.8\n */\n private ResultGenerationStrategy(String processName) {\n this.processName = processName;\n }\n\n /**\n * Returns the process name.\n *\n * @return The process name.\n * @since 1.8\n */\n ", "post_mask_code": "{\n return processName;\n }\n}\n"} {"task_id": "Java_2439", "language": "Java", "task_type": "method_body", "source_file": "java/github/OCR4all/OCR4all/src/main/java/de/uniwue/batch/process/ResultGenerationStrategy.java", "mask_start_position": 909, "mask_end_position": 944, "canonical_solution": "{\n return processName;\n }", "pre_mask_code": "package de.uniwue.batch.process;\n\n/**\n * Defines result generation strategies.\n *\n * @author Herbert Baier\n * @version 1.0\n * @since 1.8\n */\npublic enum ResultGenerationStrategy {\n\n combine(\"fillUp\"), groundTruth(\"gt\"), prediction(\"pred\");\n\n public static final ResultGenerationStrategy defaultStrategy = combine;\n\n /**\n * The argument in the batch workflow configuration.\n */\n public static final String argument = \"--strategy\";\n\n /**\n * The process name.\n */\n private final String processName;\n\n /**\n * Creates a result generation strategy.\n *\n * @param processName The process name.\n * @since 1.8\n */\n private ResultGenerationStrategy(String processName) {\n this.processName = processName;\n }\n\n /**\n * Returns the process name.\n *\n * @return The process name.\n * @since 1.8\n */\n public String getProcessName() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2440", "language": "Java", "task_type": "single_line", "source_file": "java/github/OCR4all/OCR4all/src/main/java/de/uniwue/batch/process/ResultGenerationStrategy.java", "mask_start_position": 936, "mask_end_position": 938, "canonical_solution": "e;", "pre_mask_code": "package de.uniwue.batch.process;\n\n/**\n * Defines result generation strategies.\n *\n * @author Herbert Baier\n * @version 1.0\n * @since 1.8\n */\npublic enum ResultGenerationStrategy {\n\n combine(\"fillUp\"), groundTruth(\"gt\"), prediction(\"pred\");\n\n public static final ResultGenerationStrategy defaultStrategy = combine;\n\n /**\n * The argument in the batch workflow configuration.\n */\n public static final String argument = \"--strategy\";\n\n /**\n * The process name.\n */\n private final String processName;\n\n /**\n * Creates a result generation strategy.\n *\n * @param processName The process name.\n * @since 1.8\n */\n private ResultGenerationStrategy(String processName) {\n this.processName = processName;\n }\n\n /**\n * Returns the process name.\n *\n * @return The process name.\n * @since 1.8\n */\n public String getProcessName() {\n return processNam", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2441", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/OCR4all/OCR4all/src/main/java/de/uniwue/batch/process/ResultGenerationStrategy.java", "mask_start_position": 878, "mask_end_position": 944, "canonical_solution": "public String getProcessName() {\n return processName;\n }", "pre_mask_code": "package de.uniwue.batch.process;\n\n/**\n * Defines result generation strategies.\n *\n * @author Herbert Baier\n * @version 1.0\n * @since 1.8\n */\npublic enum ResultGenerationStrategy {\n\n combine(\"fillUp\"), groundTruth(\"gt\"), prediction(\"pred\");\n\n public static final ResultGenerationStrategy defaultStrategy = combine;\n\n /**\n * The argument in the batch workflow configuration.\n */\n public static final String argument = \"--strategy\";\n\n /**\n * The process name.\n */\n private final String processName;\n\n /**\n * Creates a result generation strategy.\n *\n * @param processName The process name.\n * @since 1.8\n */\n private ResultGenerationStrategy(String processName) {\n this.processName = processName;\n }\n\n /**\n * Returns the process name.\n *\n * @return The process name.\n * @since 1.8\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2442", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/ejb/ee/pm/manyXone/uni/btob/BDVC.java", "mask_start_position": 491, "mask_end_position": 521, "canonical_solution": "public void setName(String v) ", "pre_mask_code": "package com.sun.ts.tests.ejb.ee.pm.manyXone.uni.btob;\n\npublic class BDVC implements java.io.Serializable {\n\n private String id;\n\n private String name;\n\n private int value;\n\n public BDVC(String id, String name, int value) {\n this.id = id;\n this.name = name;\n this.value = value;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String v) {\n id = v;\n }\n\n public String getName() {\n return name;\n }\n\n ", "post_mask_code": "{\n name = v;\n }\n\n public int getValue() {\n return value;\n }\n\n public void setValue(int v) {\n value = v;\n }\n}\n"} {"task_id": "Java_2443", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/ejb/ee/pm/manyXone/uni/btob/BDVC.java", "mask_start_position": 344, "mask_end_position": 370, "canonical_solution": "{\n return id;\n }", "pre_mask_code": "package com.sun.ts.tests.ejb.ee.pm.manyXone.uni.btob;\n\npublic class BDVC implements java.io.Serializable {\n\n private String id;\n\n private String name;\n\n private int value;\n\n public BDVC(String id, String name, int value) {\n this.id = id;\n this.name = name;\n this.value = value;\n }\n\n public String getId() ", "post_mask_code": "\n\n public void setId(String v) {\n id = v;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String v) {\n name = v;\n }\n\n public int getValue() {\n return value;\n }\n\n public void setValue(int v) {\n value = v;\n }\n}\n"} {"task_id": "Java_2444", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/ejb/ee/pm/manyXone/uni/btob/BDVC.java", "mask_start_position": 415, "mask_end_position": 421, "canonical_solution": "d = v;", "pre_mask_code": "package com.sun.ts.tests.ejb.ee.pm.manyXone.uni.btob;\n\npublic class BDVC implements java.io.Serializable {\n\n private String id;\n\n private String name;\n\n private int value;\n\n public BDVC(String id, String name, int value) {\n this.id = id;\n this.name = name;\n this.value = value;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String v) {\n i", "post_mask_code": "\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String v) {\n name = v;\n }\n\n public int getValue() {\n return value;\n }\n\n public void setValue(int v) {\n value = v;\n }\n}\n"} {"task_id": "Java_2445", "language": "Java", "task_type": "method_signature", "source_file": "java/github/spring-projects/spring-boot/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java", "mask_start_position": 2054, "mask_end_position": 2079, "canonical_solution": "public Object getValue() ", "pre_mask_code": "package org.springframework.boot.context.properties.source;\n\nimport org.springframework.boot.origin.Origin;\nimport org.springframework.boot.origin.OriginProvider;\nimport org.springframework.boot.origin.OriginTrackedValue;\nimport org.springframework.core.style.ToStringCreator;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ObjectUtils;\n\n/**\n * A single configuration property obtained from a {@link ConfigurationPropertySource}\n * consisting of a {@link #getName() name}, {@link #getValue() value} and optional\n * {@link #getOrigin() origin}.\n *\n * @author Phillip Webb\n * @author Madhura Bhave\n * @since 2.0.0\n */\npublic final class ConfigurationProperty implements OriginProvider, Comparable {\n\n private final ConfigurationPropertyName name;\n\n private final Object value;\n\n private final ConfigurationPropertySource source;\n\n private final Origin origin;\n\n public ConfigurationProperty(ConfigurationPropertyName name, Object value, Origin origin) {\n this(null, name, value, origin);\n }\n\n private ConfigurationProperty(ConfigurationPropertySource source, ConfigurationPropertyName name, Object value, Origin origin) {\n Assert.notNull(name, \"Name must not be null\");\n Assert.notNull(value, \"Value must not be null\");\n this.source = source;\n this.name = name;\n this.value = value;\n this.origin = origin;\n }\n\n /**\n * Return the {@link ConfigurationPropertySource} that provided the property or\n * {@code null} if the source is unknown.\n * @return the configuration property source\n * @since 2.6.0\n */\n public ConfigurationPropertySource getSource() {\n return this.source;\n }\n\n /**\n * Return the name of the configuration property.\n * @return the configuration property name\n */\n public ConfigurationPropertyName getName() {\n return this.name;\n }\n\n /**\n * Return the value of the configuration property.\n * @return the configuration property value\n */\n ", "post_mask_code": "{\n return this.value;\n }\n\n @Override\n public Origin getOrigin() {\n return this.origin;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n ConfigurationProperty other = (ConfigurationProperty) obj;\n boolean result = true;\n result = result && ObjectUtils.nullSafeEquals(this.name, other.name);\n result = result && ObjectUtils.nullSafeEquals(this.value, other.value);\n return result;\n }\n\n @Override\n public int hashCode() {\n int result = ObjectUtils.nullSafeHashCode(this.name);\n result = 31 * result + ObjectUtils.nullSafeHashCode(this.value);\n return result;\n }\n\n @Override\n public String toString() {\n return new ToStringCreator(this).append(\"name\", this.name).append(\"value\", this.value).append(\"origin\", this.origin).toString();\n }\n\n @Override\n public int compareTo(ConfigurationProperty other) {\n return this.name.compareTo(other.name);\n }\n\n static ConfigurationProperty of(ConfigurationPropertyName name, OriginTrackedValue value) {\n if (value == null) {\n return null;\n }\n return new ConfigurationProperty(name, value.getValue(), value.getOrigin());\n }\n\n static ConfigurationProperty of(ConfigurationPropertySource source, ConfigurationPropertyName name, Object value, Origin origin) {\n if (value == null) {\n return null;\n }\n return new ConfigurationProperty(source, name, value, origin);\n }\n}\n"} {"task_id": "Java_2446", "language": "Java", "task_type": "method_body", "source_file": "java/github/spring-projects/spring-boot/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java", "mask_start_position": 2159, "mask_end_position": 2194, "canonical_solution": "{\n return this.origin;\n }", "pre_mask_code": "package org.springframework.boot.context.properties.source;\n\nimport org.springframework.boot.origin.Origin;\nimport org.springframework.boot.origin.OriginProvider;\nimport org.springframework.boot.origin.OriginTrackedValue;\nimport org.springframework.core.style.ToStringCreator;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ObjectUtils;\n\n/**\n * A single configuration property obtained from a {@link ConfigurationPropertySource}\n * consisting of a {@link #getName() name}, {@link #getValue() value} and optional\n * {@link #getOrigin() origin}.\n *\n * @author Phillip Webb\n * @author Madhura Bhave\n * @since 2.0.0\n */\npublic final class ConfigurationProperty implements OriginProvider, Comparable {\n\n private final ConfigurationPropertyName name;\n\n private final Object value;\n\n private final ConfigurationPropertySource source;\n\n private final Origin origin;\n\n public ConfigurationProperty(ConfigurationPropertyName name, Object value, Origin origin) {\n this(null, name, value, origin);\n }\n\n private ConfigurationProperty(ConfigurationPropertySource source, ConfigurationPropertyName name, Object value, Origin origin) {\n Assert.notNull(name, \"Name must not be null\");\n Assert.notNull(value, \"Value must not be null\");\n this.source = source;\n this.name = name;\n this.value = value;\n this.origin = origin;\n }\n\n /**\n * Return the {@link ConfigurationPropertySource} that provided the property or\n * {@code null} if the source is unknown.\n * @return the configuration property source\n * @since 2.6.0\n */\n public ConfigurationPropertySource getSource() {\n return this.source;\n }\n\n /**\n * Return the name of the configuration property.\n * @return the configuration property name\n */\n public ConfigurationPropertyName getName() {\n return this.name;\n }\n\n /**\n * Return the value of the configuration property.\n * @return the configuration property value\n */\n public Object getValue() {\n return this.value;\n }\n\n @Override\n public Origin getOrigin() ", "post_mask_code": "\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n ConfigurationProperty other = (ConfigurationProperty) obj;\n boolean result = true;\n result = result && ObjectUtils.nullSafeEquals(this.name, other.name);\n result = result && ObjectUtils.nullSafeEquals(this.value, other.value);\n return result;\n }\n\n @Override\n public int hashCode() {\n int result = ObjectUtils.nullSafeHashCode(this.name);\n result = 31 * result + ObjectUtils.nullSafeHashCode(this.value);\n return result;\n }\n\n @Override\n public String toString() {\n return new ToStringCreator(this).append(\"name\", this.name).append(\"value\", this.value).append(\"origin\", this.origin).toString();\n }\n\n @Override\n public int compareTo(ConfigurationProperty other) {\n return this.name.compareTo(other.name);\n }\n\n static ConfigurationProperty of(ConfigurationPropertyName name, OriginTrackedValue value) {\n if (value == null) {\n return null;\n }\n return new ConfigurationProperty(name, value.getValue(), value.getOrigin());\n }\n\n static ConfigurationProperty of(ConfigurationPropertySource source, ConfigurationPropertyName name, Object value, Origin origin) {\n if (value == null) {\n return null;\n }\n return new ConfigurationProperty(source, name, value, origin);\n }\n}\n"} {"task_id": "Java_2447", "language": "Java", "task_type": "single_line", "source_file": "java/github/spring-projects/spring-boot/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java", "mask_start_position": 2652, "mask_end_position": 2662, "canonical_solution": "er.value);", "pre_mask_code": "package org.springframework.boot.context.properties.source;\n\nimport org.springframework.boot.origin.Origin;\nimport org.springframework.boot.origin.OriginProvider;\nimport org.springframework.boot.origin.OriginTrackedValue;\nimport org.springframework.core.style.ToStringCreator;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ObjectUtils;\n\n/**\n * A single configuration property obtained from a {@link ConfigurationPropertySource}\n * consisting of a {@link #getName() name}, {@link #getValue() value} and optional\n * {@link #getOrigin() origin}.\n *\n * @author Phillip Webb\n * @author Madhura Bhave\n * @since 2.0.0\n */\npublic final class ConfigurationProperty implements OriginProvider, Comparable {\n\n private final ConfigurationPropertyName name;\n\n private final Object value;\n\n private final ConfigurationPropertySource source;\n\n private final Origin origin;\n\n public ConfigurationProperty(ConfigurationPropertyName name, Object value, Origin origin) {\n this(null, name, value, origin);\n }\n\n private ConfigurationProperty(ConfigurationPropertySource source, ConfigurationPropertyName name, Object value, Origin origin) {\n Assert.notNull(name, \"Name must not be null\");\n Assert.notNull(value, \"Value must not be null\");\n this.source = source;\n this.name = name;\n this.value = value;\n this.origin = origin;\n }\n\n /**\n * Return the {@link ConfigurationPropertySource} that provided the property or\n * {@code null} if the source is unknown.\n * @return the configuration property source\n * @since 2.6.0\n */\n public ConfigurationPropertySource getSource() {\n return this.source;\n }\n\n /**\n * Return the name of the configuration property.\n * @return the configuration property name\n */\n public ConfigurationPropertyName getName() {\n return this.name;\n }\n\n /**\n * Return the value of the configuration property.\n * @return the configuration property value\n */\n public Object getValue() {\n return this.value;\n }\n\n @Override\n public Origin getOrigin() {\n return this.origin;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n ConfigurationProperty other = (ConfigurationProperty) obj;\n boolean result = true;\n result = result && ObjectUtils.nullSafeEquals(this.name, other.name);\n result = result && ObjectUtils.nullSafeEquals(this.value, oth", "post_mask_code": "\n return result;\n }\n\n @Override\n public int hashCode() {\n int result = ObjectUtils.nullSafeHashCode(this.name);\n result = 31 * result + ObjectUtils.nullSafeHashCode(this.value);\n return result;\n }\n\n @Override\n public String toString() {\n return new ToStringCreator(this).append(\"name\", this.name).append(\"value\", this.value).append(\"origin\", this.origin).toString();\n }\n\n @Override\n public int compareTo(ConfigurationProperty other) {\n return this.name.compareTo(other.name);\n }\n\n static ConfigurationProperty of(ConfigurationPropertyName name, OriginTrackedValue value) {\n if (value == null) {\n return null;\n }\n return new ConfigurationProperty(name, value.getValue(), value.getOrigin());\n }\n\n static ConfigurationProperty of(ConfigurationPropertySource source, ConfigurationPropertyName name, Object value, Origin origin) {\n if (value == null) {\n return null;\n }\n return new ConfigurationProperty(source, name, value, origin);\n }\n}\n"} {"task_id": "Java_2448", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/spring-projects/spring-boot/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java", "mask_start_position": 1648, "mask_end_position": 1730, "canonical_solution": "public ConfigurationPropertySource getSource() {\n return this.source;\n }", "pre_mask_code": "package org.springframework.boot.context.properties.source;\n\nimport org.springframework.boot.origin.Origin;\nimport org.springframework.boot.origin.OriginProvider;\nimport org.springframework.boot.origin.OriginTrackedValue;\nimport org.springframework.core.style.ToStringCreator;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ObjectUtils;\n\n/**\n * A single configuration property obtained from a {@link ConfigurationPropertySource}\n * consisting of a {@link #getName() name}, {@link #getValue() value} and optional\n * {@link #getOrigin() origin}.\n *\n * @author Phillip Webb\n * @author Madhura Bhave\n * @since 2.0.0\n */\npublic final class ConfigurationProperty implements OriginProvider, Comparable {\n\n private final ConfigurationPropertyName name;\n\n private final Object value;\n\n private final ConfigurationPropertySource source;\n\n private final Origin origin;\n\n public ConfigurationProperty(ConfigurationPropertyName name, Object value, Origin origin) {\n this(null, name, value, origin);\n }\n\n private ConfigurationProperty(ConfigurationPropertySource source, ConfigurationPropertyName name, Object value, Origin origin) {\n Assert.notNull(name, \"Name must not be null\");\n Assert.notNull(value, \"Value must not be null\");\n this.source = source;\n this.name = name;\n this.value = value;\n this.origin = origin;\n }\n\n /**\n * Return the {@link ConfigurationPropertySource} that provided the property or\n * {@code null} if the source is unknown.\n * @return the configuration property source\n * @since 2.6.0\n */\n ", "post_mask_code": "\n\n /**\n * Return the name of the configuration property.\n * @return the configuration property name\n */\n public ConfigurationPropertyName getName() {\n return this.name;\n }\n\n /**\n * Return the value of the configuration property.\n * @return the configuration property value\n */\n public Object getValue() {\n return this.value;\n }\n\n @Override\n public Origin getOrigin() {\n return this.origin;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n ConfigurationProperty other = (ConfigurationProperty) obj;\n boolean result = true;\n result = result && ObjectUtils.nullSafeEquals(this.name, other.name);\n result = result && ObjectUtils.nullSafeEquals(this.value, other.value);\n return result;\n }\n\n @Override\n public int hashCode() {\n int result = ObjectUtils.nullSafeHashCode(this.name);\n result = 31 * result + ObjectUtils.nullSafeHashCode(this.value);\n return result;\n }\n\n @Override\n public String toString() {\n return new ToStringCreator(this).append(\"name\", this.name).append(\"value\", this.value).append(\"origin\", this.origin).toString();\n }\n\n @Override\n public int compareTo(ConfigurationProperty other) {\n return this.name.compareTo(other.name);\n }\n\n static ConfigurationProperty of(ConfigurationPropertyName name, OriginTrackedValue value) {\n if (value == null) {\n return null;\n }\n return new ConfigurationProperty(name, value.getValue(), value.getOrigin());\n }\n\n static ConfigurationProperty of(ConfigurationPropertySource source, ConfigurationPropertyName name, Object value, Origin origin) {\n if (value == null) {\n return null;\n }\n return new ConfigurationProperty(source, name, value, origin);\n }\n}\n"} {"task_id": "Java_2449", "language": "Java", "task_type": "method_signature", "source_file": "java/github/bcdev/beam/beam-meris-smac/src/main/java/org/esa/beam/smac/SmacAlgorithm.java", "mask_start_position": 2531, "mask_end_position": 2602, "canonical_solution": "public final void setSensorCoefficients(SmacSensorCoefficients coeffs) ", "pre_mask_code": "package org.esa.beam.smac;\n\nimport org.esa.beam.util.Guardian;\n\n/**\n * Implements the SMAC algorithm as specified by the original source code of H.Rahman and G.Dedieu.\n */\npublic final class SmacAlgorithm {\n\n private static final double _cdr = Math.PI / 180.0;\n\n private static final double _crd = 180.0 / Math.PI;\n\n private static final double _invMaxPressure = 1.0 / 1013.0;\n\n private static final double _oneQuarter = 1.0 / 4.0;\n\n private static final double _twoThird = 2.0 / 3.0;\n\n // sensor calibration variables\n private double _A0taup;\n\n private double _A1taup;\n\n private double _a0P;\n\n private double _a1P;\n\n private double _a2P;\n\n private double _a3P;\n\n private double _a4P;\n\n private double _ao3;\n\n private double _no3;\n\n private double _ah2o;\n\n private double _nh2o;\n\n private double _ao2;\n\n private double _no2;\n\n private double _po2;\n\n private double _aco2;\n\n private double _nco2;\n\n private double _pco2;\n\n private double _ach4;\n\n private double _nch4;\n\n private double _pch4;\n\n private double _ano2;\n\n private double _nno2;\n\n private double _pno2;\n\n private double _aco;\n\n private double _nco;\n\n private double _pco;\n\n private double _a0T;\n\n private double _a1T;\n\n private double _a2T;\n\n private double _a3T;\n\n private double _a0s;\n\n private double _a1s;\n\n private double _a2s;\n\n private double _a3s;\n\n private double _taur;\n\n private double _resr1;\n\n private double _resr2;\n\n private double _resr3;\n\n private double _resa1;\n\n private double _resa2;\n\n private double _resa3;\n\n private double _resa4;\n\n private double _rest1;\n\n private double _rest2;\n\n private double _rest3;\n\n private double _rest4;\n\n private double _wo, _onemwo;\n\n private double _gc;\n\n private double _ak, _ak2, _pfac;\n\n private double _b, _onepb, _onemb, _onepb2, _onemb2;\n\n private double _ww;\n\n private boolean _calcTo3;\n\n private boolean _calcTh2o;\n\n private boolean _calcTo2;\n\n private boolean _calcUo2;\n\n private boolean _calcTco2;\n\n private boolean _calcUco2;\n\n private boolean _calcTch4;\n\n private boolean _calcUch4;\n\n private boolean _calcTno2;\n\n private boolean _calcUno2;\n\n private boolean _calcTco;\n\n private boolean _calcUco;\n\n /**\n * Sets the sensor adjustment coefficients. Must be set BEFORE running the algorithm.\n *\n * @param coeffs a class implementing the SmacSensorCoefficients\n */\n ", "post_mask_code": "{\n Guardian.assertNotNull(\"coefficients\", coeffs);\n _A0taup = coeffs.getA0taup();\n _A1taup = coeffs.getA1taup();\n // ozone coefficients\n _ao3 = coeffs.getAo3();\n _no3 = coeffs.getNo3();\n _calcTo3 = true;\n if (_ao3 == 0.0) {\n _calcTo3 = false;\n }\n // water vapour coefficients\n _ah2o = coeffs.getAh2o();\n _nh2o = coeffs.getNh2o();\n _calcTh2o = true;\n if (_ah2o == 0.0) {\n _calcTh2o = false;\n }\n // oxygene coefficients\n _ao2 = coeffs.getAo2();\n _no2 = coeffs.getNo2();\n _calcTo2 = true;\n if (_ao2 == 0.0) {\n _calcTo2 = false;\n }\n _po2 = coeffs.getPo2();\n _calcUo2 = true;\n if (_po2 == 0.0) {\n _calcUo2 = false;\n }\n // co2 coefficients\n _aco2 = coeffs.getAco2();\n _nco2 = coeffs.getNco2();\n _calcTco2 = true;\n if (_aco2 == 0.0) {\n _calcTco2 = false;\n }\n _pco2 = coeffs.getPco2();\n _calcUco2 = true;\n if (_pco2 == 0.0) {\n _calcUco2 = false;\n }\n // methane coefficients\n _ach4 = coeffs.getAch4();\n _nch4 = coeffs.getNch4();\n _calcTch4 = true;\n if (_ach4 == 0.0) {\n _calcTch4 = false;\n }\n _pch4 = coeffs.getPch4();\n _calcUch4 = true;\n if (_pch4 == 0.0) {\n _calcUch4 = false;\n }\n // no2 coefficients\n _ano2 = coeffs.getAno2();\n _nno2 = coeffs.getNno2();\n _calcTno2 = true;\n if (_ano2 == 0.0) {\n _calcTno2 = false;\n }\n _pno2 = coeffs.getPno2();\n _calcUno2 = true;\n if (_pno2 == 0.0) {\n _calcUno2 = false;\n }\n // co coefficients\n _aco = coeffs.getAco();\n _nco = coeffs.getNco();\n _calcTco = true;\n if (_aco == 0.0) {\n _calcTco = false;\n }\n _pco = coeffs.getPco();\n _calcUco = true;\n if (_pco == 0.0) {\n _calcUco = false;\n }\n // scattering transmission coefficients\n _a0T = coeffs.getA0T();\n _a1T = coeffs.getA1T();\n _a2T = coeffs.getA2T();\n _a3T = coeffs.getA3T();\n // spherical albedo coefficients\n _a0s = coeffs.getA0s();\n _a1s = coeffs.getA1s();\n _a2s = coeffs.getA2s();\n _a3s = coeffs.getA3s();\n // molecular optical depth\n _taur = coeffs.getTaur();\n // residual rayleigh\n _resr1 = coeffs.getResr1();\n _resr2 = coeffs.getResr2();\n _resr3 = coeffs.getResr3();\n // aerosol reflectance\n _a0P = coeffs.getA0P();\n _a1P = coeffs.getA1P();\n _a2P = coeffs.getA2P();\n _a3P = coeffs.getA3P();\n _a4P = coeffs.getA4P();\n _wo = coeffs.getWo();\n _gc = coeffs.getGc();\n // residual aerosols\n _resa1 = coeffs.getResa1();\n _resa2 = coeffs.getResa2();\n _resa3 = coeffs.getResa3();\n _resa4 = coeffs.getResa4();\n // residual transmission\n _rest1 = coeffs.getRest1();\n _rest2 = coeffs.getRest2();\n _rest3 = coeffs.getRest3();\n _rest4 = coeffs.getRest4();\n // do some calculations which are NOT product dependent\n _ak2 = (1.0 - _wo) * 3.0 * (1.0 - _wo * _gc);\n _ak = Math.sqrt(_ak2);\n _b = _twoThird * _ak / (1.0 - _wo * _gc);\n _onepb = 1.0 + _b;\n _onepb2 = _onepb * _onepb;\n _onemb = 1.0 - _b;\n _onemb2 = _onemb * _onemb;\n _ww = _wo * _oneQuarter;\n _onemwo = 1.0 - _wo;\n _pfac = _ak / (3.0 * (1.0 - _wo * _gc));\n }\n\n /**\n * Performs the SMAC algorithm.\n *\n * @param sza array of sun zenith angles in decimal degrees\n * @param saa array of sun azimuth angles in decimal degrees\n * @param vza array of view zenith angles in decimal degrees\n * @param vaa array of view azimuth angles in decimal degrees\n * @param taup550 array of aerosol optical thickness at 550nm\n * @param uh2o array of water vapour concentrations\n * @param uo3 array of ozone concentrations\n * @param airPressure array of air pressure in hPa\n * @param process boolean array indicating whether a pixel has to be processed or not\n * @param invalid the value set for invalid pixels, i.e. the ones excluded by the process parameter\n * @param r_toa array of top of atmosphere reflectances to be corrected\n * @param r_surfRecycle if not null and of correct size this array will be reused for the return\n * values\n * @return array of corrected surface reflectances\n */\n public final float[] run(float[] sza, float[] saa, float[] vza, float[] vaa, float[] taup550, float[] uh2o, float[] uo3, float[] airPressure, boolean[] process, float invalid, float[] r_toa, float[] r_surfRecycle) {\n // array to be returned\n float[] r_return;\n double us, invUs, us2, uv, invUv, usTimesuv, invUsTimesUv;\n double dphi, Peq, m, s, cksi, ksiD;\n double taup, tautot, Res_6s;\n double uo2, uco2, uch4, uno2, uco;\n double to3, th2o, to2, tco2, tch4, tno2, tco;\n double ttetas, ttetav;\n double ray_phase, ray_ref, taurz, Res_ray;\n double aer_phase, aer_ref, Res_aer;\n double atm_ref, tg;\n double d, del, dp, e, f, ss;\n double q1, q2, q3;\n double c1, c2, cp1, cp2;\n double x, y, z;\n double aa1, aa2, aa3;\n double temp;\n // try to reuse the recyle array to prevent memory waste. We can reuse if\n // a) it's present and\n // b) has the same size as the input vector\n if ((r_surfRecycle == null) || (r_surfRecycle.length != r_toa.length)) {\n r_return = new float[r_toa.length];\n } else {\n r_return = r_surfRecycle;\n }\n // loop over vectors\n int n;\n for (n = 0; n < r_toa.length; n++) {\n // check for process flag. If set to false we must set the default value for\n // invalid pixels and process the next pixel\n if (!process[n]) {\n r_return[n] = invalid;\n continue;\n }\n // parameter setup\n us = Math.cos(sza[n] * _cdr);\n invUs = 1.0 / us;\n us2 = us * us;\n uv = Math.cos(vza[n] * _cdr);\n invUv = 1.0 / uv;\n usTimesuv = us * uv;\n invUsTimesUv = 1.0 / usTimesuv;\n dphi = (saa[n] - vaa[n]) * _cdr;\n Peq = airPressure[n] * _invMaxPressure;\n m = invUs + invUv;\n /*------ 2) aerosol optical depth in the spectral band, taup */\n taup = _A0taup + _A1taup * taup550[n];\n /*------ 3) gaseous transmissions (downward and upward paths)*/\n uo2 = 1.0;\n if (_calcUo2) {\n uo2 = Math.pow(Peq, _po2);\n }\n uco2 = 1.0;\n if (_calcUco2) {\n uco2 = Math.pow(Peq, _pco2);\n }\n uch4 = 1.0;\n if (_calcUch4) {\n uch4 = Math.pow(Peq, _pch4);\n }\n uno2 = 1.0;\n if (_calcUno2) {\n uno2 = Math.pow(Peq, _pno2);\n }\n uco = 1.0;\n if (_calcUco) {\n uco = Math.pow(Peq, _pco);\n }\n /*------ 4) if uh2o <= 0 and uo3 <= 0 no gaseous absorption is computed*/\n to3 = 1.0;\n th2o = 1.0;\n to2 = 1.0;\n tco2 = 1.0;\n tch4 = 1.0;\n tno2 = 1.0;\n tco = 1.0;\n if ((uh2o[n] > 0.) || (uo3[n] > 0.)) {\n if (_calcTo3) {\n to3 = Math.exp(_ao3 * Math.pow((uo3[n] * m), _no3));\n }\n if (_calcTh2o) {\n th2o = Math.exp(_ah2o * Math.pow((uh2o[n] * m), _nh2o));\n }\n if (_calcTo2) {\n to2 = Math.exp(_ao2 * Math.pow((uo2 * m), _no2));\n }\n if (_calcTco2) {\n tco2 = Math.exp(_aco2 * Math.pow((uco2 * m), _nco2));\n }\n if (_calcTch4) {\n tch4 = Math.exp(_ach4 * Math.pow((uch4 * m), _nch4));\n }\n if (_calcTno2) {\n tno2 = Math.exp(_ano2 * Math.pow((uno2 * m), _nno2));\n }\n if (_calcTco) {\n tco = Math.exp(_aco * Math.pow((uco * m), _nco));\n }\n }\n /*------ 5) Total scattering transmission */\n temp = _a2T * Peq + _a3T;\n ttetas = _a0T + _a1T * taup550[n] * invUs + temp / (1.0 + us);\n /* upward */\n ttetav = _a0T + _a1T * taup550[n] * invUv + temp / (1.0 + uv);\n /*------ 6) spherical albedo of the atmosphere */\n s = _a0s * Peq + _a3s + _a1s * taup550[n] + _a2s * taup550[n] * taup550[n];\n /*------ 7) scattering angle cosine */\n cksi = -(usTimesuv + (Math.sqrt(1.0 - us2) * Math.sqrt(1.0 - uv * uv) * Math.cos(dphi)));\n if (cksi < -1) {\n cksi = -1.0;\n }\n /*------ 8) scattering angle in degree */\n ksiD = _crd * Math.acos(cksi);\n /*------ 9) rayleigh atmospheric reflectance */\n /* pour 6s on a delta = 0.0279 */\n ray_phase = 0.7190443 * (1.0 + (cksi * cksi)) + 0.0412742;\n taurz = _taur * Peq;\n ray_ref = (taurz * ray_phase) * _oneQuarter * invUsTimesUv;\n temp = taurz * ray_phase * invUsTimesUv;\n Res_ray = _resr1 + _resr2 * temp + _resr3 * temp * temp;\n /*------ 10) aerosol atmospheric reflectance */\n temp = ksiD * ksiD;\n aer_phase = _a0P + _a1P * ksiD + _a2P * temp + _a3P * temp * ksiD + _a4P * temp * temp;\n // now the uncommented block :-)\n temp = 1.0 / (4.0 * (1.0 - _ak2 * us2));\n e = -3.0 * us2 * _wo * temp;\n f = -_onemwo * 3.0 * _gc * us2 * _wo * temp;\n dp = e / (3.0 * us) + us * f;\n d = e + f;\n del = Math.exp(_ak * taup) * _onepb2 - Math.exp(-_ak * taup) * _onemb2;\n ss = us / (1.0 - _ak2 * us2);\n temp = 3.0 * us;\n q1 = 2.0 + temp + _onemwo * temp * _gc * (1.0 + 2.0 * us);\n q2 = 2.0 - temp - _onemwo * temp * _gc * (1.0 - 2.0 * us);\n q3 = q2 * Math.exp(-taup * invUs);\n temp = (_ww * ss) / del;\n c1 = temp * (q1 * Math.exp(_ak * taup) * _onepb + q3 * _onemb);\n c2 = -temp * (q1 * Math.exp(-_ak * taup) * _onemb + q3 * _onepb);\n cp1 = c1 * _pfac;\n cp2 = -c2 * _pfac;\n temp = _wo * 3.0 * _gc * uv;\n z = d - temp * dp + _wo * aer_phase * _oneQuarter;\n x = c1 - temp * cp1;\n y = c2 - temp * cp2;\n temp = _ak * uv;\n aa1 = uv / (1.0 + temp);\n aa2 = uv / (1.0 - temp);\n aa3 = usTimesuv / (us + uv);\n aer_ref = x * aa1 * (1.0 - Math.exp(-taup / aa1));\n aer_ref += y * aa2 * (1.0 - Math.exp(-taup / aa2));\n aer_ref += z * aa3 * (1.0 - Math.exp(-taup / aa3));\n aer_ref *= invUsTimesUv;\n temp = taup * m * cksi;\n Res_aer = (_resa1 + _resa2 * temp + _resa3 * temp * temp) + _resa4 * temp * temp * temp;\n tautot = taup + taurz;\n temp = tautot * m * cksi;\n Res_6s = (_rest1 + _rest2 * temp + _rest3 * temp * temp) + _rest4 * temp * temp * temp;\n /*------ 11) total atmospheric reflectance */\n atm_ref = ray_ref - Res_ray + aer_ref - Res_aer + Res_6s;\n /*-------- reflectance at toa*/\n tg = th2o * to3 * to2 * tco2 * tch4 * tco * tno2;\n /* reflectance at surface */\n temp = r_toa[n] - (atm_ref * tg);\n temp = temp / ((tg * ttetas * ttetav) + (temp * s));\n r_return[n] = (float) temp;\n }\n return r_return;\n }\n}\n"} {"task_id": "Java_2450", "language": "Java", "task_type": "single_line", "source_file": "java/github/bcdev/beam/beam-meris-smac/src/main/java/org/esa/beam/smac/SmacAlgorithm.java", "mask_start_position": 8103, "mask_end_position": 8116, "canonical_solution": "dp, e, f, ss;", "pre_mask_code": "package org.esa.beam.smac;\n\nimport org.esa.beam.util.Guardian;\n\n/**\n * Implements the SMAC algorithm as specified by the original source code of H.Rahman and G.Dedieu.\n */\npublic final class SmacAlgorithm {\n\n private static final double _cdr = Math.PI / 180.0;\n\n private static final double _crd = 180.0 / Math.PI;\n\n private static final double _invMaxPressure = 1.0 / 1013.0;\n\n private static final double _oneQuarter = 1.0 / 4.0;\n\n private static final double _twoThird = 2.0 / 3.0;\n\n // sensor calibration variables\n private double _A0taup;\n\n private double _A1taup;\n\n private double _a0P;\n\n private double _a1P;\n\n private double _a2P;\n\n private double _a3P;\n\n private double _a4P;\n\n private double _ao3;\n\n private double _no3;\n\n private double _ah2o;\n\n private double _nh2o;\n\n private double _ao2;\n\n private double _no2;\n\n private double _po2;\n\n private double _aco2;\n\n private double _nco2;\n\n private double _pco2;\n\n private double _ach4;\n\n private double _nch4;\n\n private double _pch4;\n\n private double _ano2;\n\n private double _nno2;\n\n private double _pno2;\n\n private double _aco;\n\n private double _nco;\n\n private double _pco;\n\n private double _a0T;\n\n private double _a1T;\n\n private double _a2T;\n\n private double _a3T;\n\n private double _a0s;\n\n private double _a1s;\n\n private double _a2s;\n\n private double _a3s;\n\n private double _taur;\n\n private double _resr1;\n\n private double _resr2;\n\n private double _resr3;\n\n private double _resa1;\n\n private double _resa2;\n\n private double _resa3;\n\n private double _resa4;\n\n private double _rest1;\n\n private double _rest2;\n\n private double _rest3;\n\n private double _rest4;\n\n private double _wo, _onemwo;\n\n private double _gc;\n\n private double _ak, _ak2, _pfac;\n\n private double _b, _onepb, _onemb, _onepb2, _onemb2;\n\n private double _ww;\n\n private boolean _calcTo3;\n\n private boolean _calcTh2o;\n\n private boolean _calcTo2;\n\n private boolean _calcUo2;\n\n private boolean _calcTco2;\n\n private boolean _calcUco2;\n\n private boolean _calcTch4;\n\n private boolean _calcUch4;\n\n private boolean _calcTno2;\n\n private boolean _calcUno2;\n\n private boolean _calcTco;\n\n private boolean _calcUco;\n\n /**\n * Sets the sensor adjustment coefficients. Must be set BEFORE running the algorithm.\n *\n * @param coeffs a class implementing the SmacSensorCoefficients\n */\n public final void setSensorCoefficients(SmacSensorCoefficients coeffs) {\n Guardian.assertNotNull(\"coefficients\", coeffs);\n _A0taup = coeffs.getA0taup();\n _A1taup = coeffs.getA1taup();\n // ozone coefficients\n _ao3 = coeffs.getAo3();\n _no3 = coeffs.getNo3();\n _calcTo3 = true;\n if (_ao3 == 0.0) {\n _calcTo3 = false;\n }\n // water vapour coefficients\n _ah2o = coeffs.getAh2o();\n _nh2o = coeffs.getNh2o();\n _calcTh2o = true;\n if (_ah2o == 0.0) {\n _calcTh2o = false;\n }\n // oxygene coefficients\n _ao2 = coeffs.getAo2();\n _no2 = coeffs.getNo2();\n _calcTo2 = true;\n if (_ao2 == 0.0) {\n _calcTo2 = false;\n }\n _po2 = coeffs.getPo2();\n _calcUo2 = true;\n if (_po2 == 0.0) {\n _calcUo2 = false;\n }\n // co2 coefficients\n _aco2 = coeffs.getAco2();\n _nco2 = coeffs.getNco2();\n _calcTco2 = true;\n if (_aco2 == 0.0) {\n _calcTco2 = false;\n }\n _pco2 = coeffs.getPco2();\n _calcUco2 = true;\n if (_pco2 == 0.0) {\n _calcUco2 = false;\n }\n // methane coefficients\n _ach4 = coeffs.getAch4();\n _nch4 = coeffs.getNch4();\n _calcTch4 = true;\n if (_ach4 == 0.0) {\n _calcTch4 = false;\n }\n _pch4 = coeffs.getPch4();\n _calcUch4 = true;\n if (_pch4 == 0.0) {\n _calcUch4 = false;\n }\n // no2 coefficients\n _ano2 = coeffs.getAno2();\n _nno2 = coeffs.getNno2();\n _calcTno2 = true;\n if (_ano2 == 0.0) {\n _calcTno2 = false;\n }\n _pno2 = coeffs.getPno2();\n _calcUno2 = true;\n if (_pno2 == 0.0) {\n _calcUno2 = false;\n }\n // co coefficients\n _aco = coeffs.getAco();\n _nco = coeffs.getNco();\n _calcTco = true;\n if (_aco == 0.0) {\n _calcTco = false;\n }\n _pco = coeffs.getPco();\n _calcUco = true;\n if (_pco == 0.0) {\n _calcUco = false;\n }\n // scattering transmission coefficients\n _a0T = coeffs.getA0T();\n _a1T = coeffs.getA1T();\n _a2T = coeffs.getA2T();\n _a3T = coeffs.getA3T();\n // spherical albedo coefficients\n _a0s = coeffs.getA0s();\n _a1s = coeffs.getA1s();\n _a2s = coeffs.getA2s();\n _a3s = coeffs.getA3s();\n // molecular optical depth\n _taur = coeffs.getTaur();\n // residual rayleigh\n _resr1 = coeffs.getResr1();\n _resr2 = coeffs.getResr2();\n _resr3 = coeffs.getResr3();\n // aerosol reflectance\n _a0P = coeffs.getA0P();\n _a1P = coeffs.getA1P();\n _a2P = coeffs.getA2P();\n _a3P = coeffs.getA3P();\n _a4P = coeffs.getA4P();\n _wo = coeffs.getWo();\n _gc = coeffs.getGc();\n // residual aerosols\n _resa1 = coeffs.getResa1();\n _resa2 = coeffs.getResa2();\n _resa3 = coeffs.getResa3();\n _resa4 = coeffs.getResa4();\n // residual transmission\n _rest1 = coeffs.getRest1();\n _rest2 = coeffs.getRest2();\n _rest3 = coeffs.getRest3();\n _rest4 = coeffs.getRest4();\n // do some calculations which are NOT product dependent\n _ak2 = (1.0 - _wo) * 3.0 * (1.0 - _wo * _gc);\n _ak = Math.sqrt(_ak2);\n _b = _twoThird * _ak / (1.0 - _wo * _gc);\n _onepb = 1.0 + _b;\n _onepb2 = _onepb * _onepb;\n _onemb = 1.0 - _b;\n _onemb2 = _onemb * _onemb;\n _ww = _wo * _oneQuarter;\n _onemwo = 1.0 - _wo;\n _pfac = _ak / (3.0 * (1.0 - _wo * _gc));\n }\n\n /**\n * Performs the SMAC algorithm.\n *\n * @param sza array of sun zenith angles in decimal degrees\n * @param saa array of sun azimuth angles in decimal degrees\n * @param vza array of view zenith angles in decimal degrees\n * @param vaa array of view azimuth angles in decimal degrees\n * @param taup550 array of aerosol optical thickness at 550nm\n * @param uh2o array of water vapour concentrations\n * @param uo3 array of ozone concentrations\n * @param airPressure array of air pressure in hPa\n * @param process boolean array indicating whether a pixel has to be processed or not\n * @param invalid the value set for invalid pixels, i.e. the ones excluded by the process parameter\n * @param r_toa array of top of atmosphere reflectances to be corrected\n * @param r_surfRecycle if not null and of correct size this array will be reused for the return\n * values\n * @return array of corrected surface reflectances\n */\n public final float[] run(float[] sza, float[] saa, float[] vza, float[] vaa, float[] taup550, float[] uh2o, float[] uo3, float[] airPressure, boolean[] process, float invalid, float[] r_toa, float[] r_surfRecycle) {\n // array to be returned\n float[] r_return;\n double us, invUs, us2, uv, invUv, usTimesuv, invUsTimesUv;\n double dphi, Peq, m, s, cksi, ksiD;\n double taup, tautot, Res_6s;\n double uo2, uco2, uch4, uno2, uco;\n double to3, th2o, to2, tco2, tch4, tno2, tco;\n double ttetas, ttetav;\n double ray_phase, ray_ref, taurz, Res_ray;\n double aer_phase, aer_ref, Res_aer;\n double atm_ref, tg;\n double d, del, ", "post_mask_code": "\n double q1, q2, q3;\n double c1, c2, cp1, cp2;\n double x, y, z;\n double aa1, aa2, aa3;\n double temp;\n // try to reuse the recyle array to prevent memory waste. We can reuse if\n // a) it's present and\n // b) has the same size as the input vector\n if ((r_surfRecycle == null) || (r_surfRecycle.length != r_toa.length)) {\n r_return = new float[r_toa.length];\n } else {\n r_return = r_surfRecycle;\n }\n // loop over vectors\n int n;\n for (n = 0; n < r_toa.length; n++) {\n // check for process flag. If set to false we must set the default value for\n // invalid pixels and process the next pixel\n if (!process[n]) {\n r_return[n] = invalid;\n continue;\n }\n // parameter setup\n us = Math.cos(sza[n] * _cdr);\n invUs = 1.0 / us;\n us2 = us * us;\n uv = Math.cos(vza[n] * _cdr);\n invUv = 1.0 / uv;\n usTimesuv = us * uv;\n invUsTimesUv = 1.0 / usTimesuv;\n dphi = (saa[n] - vaa[n]) * _cdr;\n Peq = airPressure[n] * _invMaxPressure;\n m = invUs + invUv;\n /*------ 2) aerosol optical depth in the spectral band, taup */\n taup = _A0taup + _A1taup * taup550[n];\n /*------ 3) gaseous transmissions (downward and upward paths)*/\n uo2 = 1.0;\n if (_calcUo2) {\n uo2 = Math.pow(Peq, _po2);\n }\n uco2 = 1.0;\n if (_calcUco2) {\n uco2 = Math.pow(Peq, _pco2);\n }\n uch4 = 1.0;\n if (_calcUch4) {\n uch4 = Math.pow(Peq, _pch4);\n }\n uno2 = 1.0;\n if (_calcUno2) {\n uno2 = Math.pow(Peq, _pno2);\n }\n uco = 1.0;\n if (_calcUco) {\n uco = Math.pow(Peq, _pco);\n }\n /*------ 4) if uh2o <= 0 and uo3 <= 0 no gaseous absorption is computed*/\n to3 = 1.0;\n th2o = 1.0;\n to2 = 1.0;\n tco2 = 1.0;\n tch4 = 1.0;\n tno2 = 1.0;\n tco = 1.0;\n if ((uh2o[n] > 0.) || (uo3[n] > 0.)) {\n if (_calcTo3) {\n to3 = Math.exp(_ao3 * Math.pow((uo3[n] * m), _no3));\n }\n if (_calcTh2o) {\n th2o = Math.exp(_ah2o * Math.pow((uh2o[n] * m), _nh2o));\n }\n if (_calcTo2) {\n to2 = Math.exp(_ao2 * Math.pow((uo2 * m), _no2));\n }\n if (_calcTco2) {\n tco2 = Math.exp(_aco2 * Math.pow((uco2 * m), _nco2));\n }\n if (_calcTch4) {\n tch4 = Math.exp(_ach4 * Math.pow((uch4 * m), _nch4));\n }\n if (_calcTno2) {\n tno2 = Math.exp(_ano2 * Math.pow((uno2 * m), _nno2));\n }\n if (_calcTco) {\n tco = Math.exp(_aco * Math.pow((uco * m), _nco));\n }\n }\n /*------ 5) Total scattering transmission */\n temp = _a2T * Peq + _a3T;\n ttetas = _a0T + _a1T * taup550[n] * invUs + temp / (1.0 + us);\n /* upward */\n ttetav = _a0T + _a1T * taup550[n] * invUv + temp / (1.0 + uv);\n /*------ 6) spherical albedo of the atmosphere */\n s = _a0s * Peq + _a3s + _a1s * taup550[n] + _a2s * taup550[n] * taup550[n];\n /*------ 7) scattering angle cosine */\n cksi = -(usTimesuv + (Math.sqrt(1.0 - us2) * Math.sqrt(1.0 - uv * uv) * Math.cos(dphi)));\n if (cksi < -1) {\n cksi = -1.0;\n }\n /*------ 8) scattering angle in degree */\n ksiD = _crd * Math.acos(cksi);\n /*------ 9) rayleigh atmospheric reflectance */\n /* pour 6s on a delta = 0.0279 */\n ray_phase = 0.7190443 * (1.0 + (cksi * cksi)) + 0.0412742;\n taurz = _taur * Peq;\n ray_ref = (taurz * ray_phase) * _oneQuarter * invUsTimesUv;\n temp = taurz * ray_phase * invUsTimesUv;\n Res_ray = _resr1 + _resr2 * temp + _resr3 * temp * temp;\n /*------ 10) aerosol atmospheric reflectance */\n temp = ksiD * ksiD;\n aer_phase = _a0P + _a1P * ksiD + _a2P * temp + _a3P * temp * ksiD + _a4P * temp * temp;\n // now the uncommented block :-)\n temp = 1.0 / (4.0 * (1.0 - _ak2 * us2));\n e = -3.0 * us2 * _wo * temp;\n f = -_onemwo * 3.0 * _gc * us2 * _wo * temp;\n dp = e / (3.0 * us) + us * f;\n d = e + f;\n del = Math.exp(_ak * taup) * _onepb2 - Math.exp(-_ak * taup) * _onemb2;\n ss = us / (1.0 - _ak2 * us2);\n temp = 3.0 * us;\n q1 = 2.0 + temp + _onemwo * temp * _gc * (1.0 + 2.0 * us);\n q2 = 2.0 - temp - _onemwo * temp * _gc * (1.0 - 2.0 * us);\n q3 = q2 * Math.exp(-taup * invUs);\n temp = (_ww * ss) / del;\n c1 = temp * (q1 * Math.exp(_ak * taup) * _onepb + q3 * _onemb);\n c2 = -temp * (q1 * Math.exp(-_ak * taup) * _onemb + q3 * _onepb);\n cp1 = c1 * _pfac;\n cp2 = -c2 * _pfac;\n temp = _wo * 3.0 * _gc * uv;\n z = d - temp * dp + _wo * aer_phase * _oneQuarter;\n x = c1 - temp * cp1;\n y = c2 - temp * cp2;\n temp = _ak * uv;\n aa1 = uv / (1.0 + temp);\n aa2 = uv / (1.0 - temp);\n aa3 = usTimesuv / (us + uv);\n aer_ref = x * aa1 * (1.0 - Math.exp(-taup / aa1));\n aer_ref += y * aa2 * (1.0 - Math.exp(-taup / aa2));\n aer_ref += z * aa3 * (1.0 - Math.exp(-taup / aa3));\n aer_ref *= invUsTimesUv;\n temp = taup * m * cksi;\n Res_aer = (_resa1 + _resa2 * temp + _resa3 * temp * temp) + _resa4 * temp * temp * temp;\n tautot = taup + taurz;\n temp = tautot * m * cksi;\n Res_6s = (_rest1 + _rest2 * temp + _rest3 * temp * temp) + _rest4 * temp * temp * temp;\n /*------ 11) total atmospheric reflectance */\n atm_ref = ray_ref - Res_ray + aer_ref - Res_aer + Res_6s;\n /*-------- reflectance at toa*/\n tg = th2o * to3 * to2 * tco2 * tch4 * tco * tno2;\n /* reflectance at surface */\n temp = r_toa[n] - (atm_ref * tg);\n temp = temp / ((tg * ttetas * ttetav) + (temp * s));\n r_return[n] = (float) temp;\n }\n return r_return;\n }\n}\n"} {"task_id": "Java_2451", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Teradata/kylo/core/file-metadata/file-metadata-core/src/main/java/com/thinkbiganalytics/kylo/metadata/file/service/FileMetadataService.java", "mask_start_position": 4158, "mask_end_position": 4228, "canonical_solution": "public static FileMetadata detectFromFile(File file) throws Exception ", "pre_mask_code": "package com.thinkbiganalytics.kylo.metadata.file.service;\n\nimport com.thinkbiganalytics.kylo.metadata.file.FileMetadata;\nimport com.thinkbiganalytics.kylo.tika.detector.CSVDetector;\nimport com.thinkbiganalytics.kylo.tika.detector.InputStreamUtil;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.tika.Tika;\nimport org.apache.tika.config.TikaConfig;\nimport org.apache.tika.detect.AutoDetectReader;\nimport org.apache.tika.detect.XmlRootExtractor;\nimport org.apache.tika.io.TikaInputStream;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.mime.MediaType;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.nio.charset.Charset;\nimport java.nio.charset.StandardCharsets;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.xml.namespace.QName;\n\n/**\n * Detect file metadata using Apache Tika\n */\npublic class FileMetadataService {\n\n static int bytesToTest = 512000;\n\n /**\n * Detect file format and metadata/mimetype from the incoming input sream\n *\n * @param is the file input stream\n * @param fileName the name of the file (optional)\n * @return the metadata object\n */\n public static FileMetadata detectFromStream(InputStream is, String fileName) throws Exception {\n Tika tika = new Tika();\n TikaConfig tikaConfig = new TikaConfig();\n Metadata md = new Metadata();\n md.set(Metadata.RESOURCE_NAME_KEY, fileName);\n Charset charset = StandardCharsets.ISO_8859_1;\n byte[] header = InputStreamUtil.readHeader(is, bytesToTest);\n AutoDetectReader reader = new AutoDetectReader(InputStreamUtil.asStream(header));\n charset = reader.getCharset();\n MediaType mediaType = null;\n if (fileName != null && fileName.endsWith(\".csv\")) {\n mediaType = detectCsv(InputStreamUtil.asStream(header), md);\n } else {\n mediaType = tika.getDetector().detect(TikaInputStream.get(InputStreamUtil.asStream(header)), md);\n // manually call the csv detector if it is a text file that is not matched.\n // this is needed, and cannot be added to the /META-INF/services/org.apache.tika.detect.Detector file since there is no guarantee of order\n // we first want to detect the type from the core tika mimetypes.\n // then if we didnt get a concrete type attempt to parse it via csv\n if (mediaType.equals(MediaType.TEXT_PLAIN)) {\n mediaType = detectCsv(InputStreamUtil.asStream(header), md);\n } else if (mediaType.equals(MediaType.APPLICATION_XML)) {\n XmlRootExtractor rowTagExtractor = new XmlRootExtractor();\n QName root = rowTagExtractor.extractRootElement(InputStreamUtil.asStream(header));\n if (root != null) {\n String rowTag = root.getLocalPart();\n md.set(\"rowTag\", rowTag);\n } else {\n // unable to detect RowTag from XML!!\n }\n }\n }\n if (mediaType == null) {\n mediaType = MediaType.OCTET_STREAM;\n }\n FileMetadata fileMetadata = new FileMetadata(mediaType.toString());\n fileMetadata.addProperties(metadataToMap(md));\n fileMetadata.setSubType(mediaType.getSubtype());\n String encoding = charset.name();\n fileMetadata.setEncoding(StringUtils.isBlank(encoding) ? StandardCharsets.UTF_8.name() : encoding);\n return fileMetadata;\n }\n\n private static MediaType detectCsv(InputStream inputStream, Metadata md) throws Exception {\n CSVDetector d = new CSVDetector();\n return d.detect(inputStream, md);\n }\n\n private static Map metadataToMap(Metadata metadata) {\n Map map = new HashMap<>();\n for (String name : metadata.names()) {\n String firstValue = metadata.get(name);\n map.put(name, firstValue);\n }\n return map;\n }\n\n /**\n * Detect metadata for a specific file\n *\n * @param file the file to inspect\n * @return the metadata for that file\n */\n ", "post_mask_code": "{\n InputStream inputStream = FileUtils.openInputStream(file);\n return detectFromStream(inputStream, file.getName());\n }\n}\n"} {"task_id": "Java_2452", "language": "Java", "task_type": "method_body", "source_file": "java/github/Teradata/kylo/core/file-metadata/file-metadata-core/src/main/java/com/thinkbiganalytics/kylo/metadata/file/service/FileMetadataService.java", "mask_start_position": 3779, "mask_end_position": 4005, "canonical_solution": "{\n Map map = new HashMap<>();\n for (String name : metadata.names()) {\n String firstValue = metadata.get(name);\n map.put(name, firstValue);\n }\n return map;\n }", "pre_mask_code": "package com.thinkbiganalytics.kylo.metadata.file.service;\n\nimport com.thinkbiganalytics.kylo.metadata.file.FileMetadata;\nimport com.thinkbiganalytics.kylo.tika.detector.CSVDetector;\nimport com.thinkbiganalytics.kylo.tika.detector.InputStreamUtil;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.tika.Tika;\nimport org.apache.tika.config.TikaConfig;\nimport org.apache.tika.detect.AutoDetectReader;\nimport org.apache.tika.detect.XmlRootExtractor;\nimport org.apache.tika.io.TikaInputStream;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.mime.MediaType;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.nio.charset.Charset;\nimport java.nio.charset.StandardCharsets;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.xml.namespace.QName;\n\n/**\n * Detect file metadata using Apache Tika\n */\npublic class FileMetadataService {\n\n static int bytesToTest = 512000;\n\n /**\n * Detect file format and metadata/mimetype from the incoming input sream\n *\n * @param is the file input stream\n * @param fileName the name of the file (optional)\n * @return the metadata object\n */\n public static FileMetadata detectFromStream(InputStream is, String fileName) throws Exception {\n Tika tika = new Tika();\n TikaConfig tikaConfig = new TikaConfig();\n Metadata md = new Metadata();\n md.set(Metadata.RESOURCE_NAME_KEY, fileName);\n Charset charset = StandardCharsets.ISO_8859_1;\n byte[] header = InputStreamUtil.readHeader(is, bytesToTest);\n AutoDetectReader reader = new AutoDetectReader(InputStreamUtil.asStream(header));\n charset = reader.getCharset();\n MediaType mediaType = null;\n if (fileName != null && fileName.endsWith(\".csv\")) {\n mediaType = detectCsv(InputStreamUtil.asStream(header), md);\n } else {\n mediaType = tika.getDetector().detect(TikaInputStream.get(InputStreamUtil.asStream(header)), md);\n // manually call the csv detector if it is a text file that is not matched.\n // this is needed, and cannot be added to the /META-INF/services/org.apache.tika.detect.Detector file since there is no guarantee of order\n // we first want to detect the type from the core tika mimetypes.\n // then if we didnt get a concrete type attempt to parse it via csv\n if (mediaType.equals(MediaType.TEXT_PLAIN)) {\n mediaType = detectCsv(InputStreamUtil.asStream(header), md);\n } else if (mediaType.equals(MediaType.APPLICATION_XML)) {\n XmlRootExtractor rowTagExtractor = new XmlRootExtractor();\n QName root = rowTagExtractor.extractRootElement(InputStreamUtil.asStream(header));\n if (root != null) {\n String rowTag = root.getLocalPart();\n md.set(\"rowTag\", rowTag);\n } else {\n // unable to detect RowTag from XML!!\n }\n }\n }\n if (mediaType == null) {\n mediaType = MediaType.OCTET_STREAM;\n }\n FileMetadata fileMetadata = new FileMetadata(mediaType.toString());\n fileMetadata.addProperties(metadataToMap(md));\n fileMetadata.setSubType(mediaType.getSubtype());\n String encoding = charset.name();\n fileMetadata.setEncoding(StringUtils.isBlank(encoding) ? StandardCharsets.UTF_8.name() : encoding);\n return fileMetadata;\n }\n\n private static MediaType detectCsv(InputStream inputStream, Metadata md) throws Exception {\n CSVDetector d = new CSVDetector();\n return d.detect(inputStream, md);\n }\n\n private static Map metadataToMap(Metadata metadata) ", "post_mask_code": "\n\n /**\n * Detect metadata for a specific file\n *\n * @param file the file to inspect\n * @return the metadata for that file\n */\n public static FileMetadata detectFromFile(File file) throws Exception {\n InputStream inputStream = FileUtils.openInputStream(file);\n return detectFromStream(inputStream, file.getName());\n }\n}\n"} {"task_id": "Java_2453", "language": "Java", "task_type": "single_line", "source_file": "java/github/Teradata/kylo/core/file-metadata/file-metadata-core/src/main/java/com/thinkbiganalytics/kylo/metadata/file/service/FileMetadataService.java", "mask_start_position": 3676, "mask_end_position": 3699, "canonical_solution": "etect(inputStream, md);", "pre_mask_code": "package com.thinkbiganalytics.kylo.metadata.file.service;\n\nimport com.thinkbiganalytics.kylo.metadata.file.FileMetadata;\nimport com.thinkbiganalytics.kylo.tika.detector.CSVDetector;\nimport com.thinkbiganalytics.kylo.tika.detector.InputStreamUtil;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.tika.Tika;\nimport org.apache.tika.config.TikaConfig;\nimport org.apache.tika.detect.AutoDetectReader;\nimport org.apache.tika.detect.XmlRootExtractor;\nimport org.apache.tika.io.TikaInputStream;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.mime.MediaType;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.nio.charset.Charset;\nimport java.nio.charset.StandardCharsets;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.xml.namespace.QName;\n\n/**\n * Detect file metadata using Apache Tika\n */\npublic class FileMetadataService {\n\n static int bytesToTest = 512000;\n\n /**\n * Detect file format and metadata/mimetype from the incoming input sream\n *\n * @param is the file input stream\n * @param fileName the name of the file (optional)\n * @return the metadata object\n */\n public static FileMetadata detectFromStream(InputStream is, String fileName) throws Exception {\n Tika tika = new Tika();\n TikaConfig tikaConfig = new TikaConfig();\n Metadata md = new Metadata();\n md.set(Metadata.RESOURCE_NAME_KEY, fileName);\n Charset charset = StandardCharsets.ISO_8859_1;\n byte[] header = InputStreamUtil.readHeader(is, bytesToTest);\n AutoDetectReader reader = new AutoDetectReader(InputStreamUtil.asStream(header));\n charset = reader.getCharset();\n MediaType mediaType = null;\n if (fileName != null && fileName.endsWith(\".csv\")) {\n mediaType = detectCsv(InputStreamUtil.asStream(header), md);\n } else {\n mediaType = tika.getDetector().detect(TikaInputStream.get(InputStreamUtil.asStream(header)), md);\n // manually call the csv detector if it is a text file that is not matched.\n // this is needed, and cannot be added to the /META-INF/services/org.apache.tika.detect.Detector file since there is no guarantee of order\n // we first want to detect the type from the core tika mimetypes.\n // then if we didnt get a concrete type attempt to parse it via csv\n if (mediaType.equals(MediaType.TEXT_PLAIN)) {\n mediaType = detectCsv(InputStreamUtil.asStream(header), md);\n } else if (mediaType.equals(MediaType.APPLICATION_XML)) {\n XmlRootExtractor rowTagExtractor = new XmlRootExtractor();\n QName root = rowTagExtractor.extractRootElement(InputStreamUtil.asStream(header));\n if (root != null) {\n String rowTag = root.getLocalPart();\n md.set(\"rowTag\", rowTag);\n } else {\n // unable to detect RowTag from XML!!\n }\n }\n }\n if (mediaType == null) {\n mediaType = MediaType.OCTET_STREAM;\n }\n FileMetadata fileMetadata = new FileMetadata(mediaType.toString());\n fileMetadata.addProperties(metadataToMap(md));\n fileMetadata.setSubType(mediaType.getSubtype());\n String encoding = charset.name();\n fileMetadata.setEncoding(StringUtils.isBlank(encoding) ? StandardCharsets.UTF_8.name() : encoding);\n return fileMetadata;\n }\n\n private static MediaType detectCsv(InputStream inputStream, Metadata md) throws Exception {\n CSVDetector d = new CSVDetector();\n return d.d", "post_mask_code": "\n }\n\n private static Map metadataToMap(Metadata metadata) {\n Map map = new HashMap<>();\n for (String name : metadata.names()) {\n String firstValue = metadata.get(name);\n map.put(name, firstValue);\n }\n return map;\n }\n\n /**\n * Detect metadata for a specific file\n *\n * @param file the file to inspect\n * @return the metadata for that file\n */\n public static FileMetadata detectFromFile(File file) throws Exception {\n InputStream inputStream = FileUtils.openInputStream(file);\n return detectFromStream(inputStream, file.getName());\n }\n}\n"} {"task_id": "Java_2454", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Teradata/kylo/core/file-metadata/file-metadata-core/src/main/java/com/thinkbiganalytics/kylo/metadata/file/service/FileMetadataService.java", "mask_start_position": 4158, "mask_end_position": 4364, "canonical_solution": "public static FileMetadata detectFromFile(File file) throws Exception {\n InputStream inputStream = FileUtils.openInputStream(file);\n return detectFromStream(inputStream, file.getName());\n }", "pre_mask_code": "package com.thinkbiganalytics.kylo.metadata.file.service;\n\nimport com.thinkbiganalytics.kylo.metadata.file.FileMetadata;\nimport com.thinkbiganalytics.kylo.tika.detector.CSVDetector;\nimport com.thinkbiganalytics.kylo.tika.detector.InputStreamUtil;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.tika.Tika;\nimport org.apache.tika.config.TikaConfig;\nimport org.apache.tika.detect.AutoDetectReader;\nimport org.apache.tika.detect.XmlRootExtractor;\nimport org.apache.tika.io.TikaInputStream;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.mime.MediaType;\nimport java.io.File;\nimport java.io.InputStream;\nimport java.nio.charset.Charset;\nimport java.nio.charset.StandardCharsets;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.xml.namespace.QName;\n\n/**\n * Detect file metadata using Apache Tika\n */\npublic class FileMetadataService {\n\n static int bytesToTest = 512000;\n\n /**\n * Detect file format and metadata/mimetype from the incoming input sream\n *\n * @param is the file input stream\n * @param fileName the name of the file (optional)\n * @return the metadata object\n */\n public static FileMetadata detectFromStream(InputStream is, String fileName) throws Exception {\n Tika tika = new Tika();\n TikaConfig tikaConfig = new TikaConfig();\n Metadata md = new Metadata();\n md.set(Metadata.RESOURCE_NAME_KEY, fileName);\n Charset charset = StandardCharsets.ISO_8859_1;\n byte[] header = InputStreamUtil.readHeader(is, bytesToTest);\n AutoDetectReader reader = new AutoDetectReader(InputStreamUtil.asStream(header));\n charset = reader.getCharset();\n MediaType mediaType = null;\n if (fileName != null && fileName.endsWith(\".csv\")) {\n mediaType = detectCsv(InputStreamUtil.asStream(header), md);\n } else {\n mediaType = tika.getDetector().detect(TikaInputStream.get(InputStreamUtil.asStream(header)), md);\n // manually call the csv detector if it is a text file that is not matched.\n // this is needed, and cannot be added to the /META-INF/services/org.apache.tika.detect.Detector file since there is no guarantee of order\n // we first want to detect the type from the core tika mimetypes.\n // then if we didnt get a concrete type attempt to parse it via csv\n if (mediaType.equals(MediaType.TEXT_PLAIN)) {\n mediaType = detectCsv(InputStreamUtil.asStream(header), md);\n } else if (mediaType.equals(MediaType.APPLICATION_XML)) {\n XmlRootExtractor rowTagExtractor = new XmlRootExtractor();\n QName root = rowTagExtractor.extractRootElement(InputStreamUtil.asStream(header));\n if (root != null) {\n String rowTag = root.getLocalPart();\n md.set(\"rowTag\", rowTag);\n } else {\n // unable to detect RowTag from XML!!\n }\n }\n }\n if (mediaType == null) {\n mediaType = MediaType.OCTET_STREAM;\n }\n FileMetadata fileMetadata = new FileMetadata(mediaType.toString());\n fileMetadata.addProperties(metadataToMap(md));\n fileMetadata.setSubType(mediaType.getSubtype());\n String encoding = charset.name();\n fileMetadata.setEncoding(StringUtils.isBlank(encoding) ? StandardCharsets.UTF_8.name() : encoding);\n return fileMetadata;\n }\n\n private static MediaType detectCsv(InputStream inputStream, Metadata md) throws Exception {\n CSVDetector d = new CSVDetector();\n return d.detect(inputStream, md);\n }\n\n private static Map metadataToMap(Metadata metadata) {\n Map map = new HashMap<>();\n for (String name : metadata.names()) {\n String firstValue = metadata.get(name);\n map.put(name, firstValue);\n }\n return map;\n }\n\n /**\n * Detect metadata for a specific file\n *\n * @param file the file to inspect\n * @return the metadata for that file\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2455", "language": "Java", "task_type": "method_signature", "source_file": "java/github/pentaho/pentaho-kettle/engine/src/main/java/org/pentaho/di/trans/step/errorhandling/Stream.java", "mask_start_position": 3212, "mask_end_position": 3261, "canonical_solution": "public void setStreamIcon(StreamIcon streamIcon) ", "pre_mask_code": "/*! ******************************************************************************\n *\n * Pentaho Data Integration\n *\n *\n *******************************************************************************\n *\n *\n ******************************************************************************/\npackage org.pentaho.di.trans.step.errorhandling;\n\nimport org.pentaho.di.core.Const;\nimport org.pentaho.di.trans.step.StepMeta;\n\npublic class Stream implements StreamInterface {\n\n private String description;\n\n private StreamType streamType;\n\n private StepMeta stepMeta;\n\n private StreamIcon streamIcon;\n\n private Object subject;\n\n /**\n * @param streamType\n * @param stepname\n * @param stepMeta\n * @param description\n */\n public Stream(StreamType streamType, StepMeta stepMeta, String description, StreamIcon streamIcon, Object subject) {\n this.streamType = streamType;\n this.stepMeta = stepMeta;\n this.description = description;\n this.streamIcon = streamIcon;\n this.subject = subject;\n }\n\n public Stream(StreamInterface stream) {\n this(stream.getStreamType(), stream.getStepMeta(), stream.getDescription(), stream.getStreamIcon(), stream.getSubject());\n }\n\n public String toString() {\n if (stepMeta == null) {\n return \"Stream type \" + streamType + Const.CR + description;\n } else {\n return \"Stream type \" + streamType + \" for step '\" + stepMeta.getName() + \"'\" + Const.CR + description;\n }\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof StreamInterface)) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n StreamInterface stream = (StreamInterface) obj;\n if (description.equals(stream.getDescription())) {\n return true;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return description.hashCode();\n }\n\n public String getStepname() {\n if (stepMeta == null) {\n return null;\n }\n return stepMeta.getName();\n }\n\n /**\n * @return the description\n */\n public String getDescription() {\n return description;\n }\n\n /**\n * @param description\n * the description to set\n */\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * @return the streamType\n */\n public StreamType getStreamType() {\n return streamType;\n }\n\n /**\n * @param streamType\n * the streamType to set\n */\n public void setStreamType(StreamType streamType) {\n this.streamType = streamType;\n }\n\n /**\n * @return the stepMeta\n */\n public StepMeta getStepMeta() {\n return stepMeta;\n }\n\n /**\n * @param stepMeta\n * the stepMeta to set\n */\n public void setStepMeta(StepMeta stepMeta) {\n this.stepMeta = stepMeta;\n }\n\n /**\n * @return the streamIcon\n */\n public StreamIcon getStreamIcon() {\n return streamIcon;\n }\n\n /**\n * @param streamIcon\n * the streamIcon to set\n */\n ", "post_mask_code": "{\n this.streamIcon = streamIcon;\n }\n\n /**\n * @return the subject\n */\n public Object getSubject() {\n return subject;\n }\n\n /**\n * @param subject\n * the subject to set\n */\n public void setSubject(Object subject) {\n this.subject = subject;\n }\n}\n"} {"task_id": "Java_2456", "language": "Java", "task_type": "method_body", "source_file": "java/github/pentaho/pentaho-kettle/engine/src/main/java/org/pentaho/di/trans/step/errorhandling/Stream.java", "mask_start_position": 3093, "mask_end_position": 3127, "canonical_solution": "{\n return streamIcon;\n }", "pre_mask_code": "/*! ******************************************************************************\n *\n * Pentaho Data Integration\n *\n *\n *******************************************************************************\n *\n *\n ******************************************************************************/\npackage org.pentaho.di.trans.step.errorhandling;\n\nimport org.pentaho.di.core.Const;\nimport org.pentaho.di.trans.step.StepMeta;\n\npublic class Stream implements StreamInterface {\n\n private String description;\n\n private StreamType streamType;\n\n private StepMeta stepMeta;\n\n private StreamIcon streamIcon;\n\n private Object subject;\n\n /**\n * @param streamType\n * @param stepname\n * @param stepMeta\n * @param description\n */\n public Stream(StreamType streamType, StepMeta stepMeta, String description, StreamIcon streamIcon, Object subject) {\n this.streamType = streamType;\n this.stepMeta = stepMeta;\n this.description = description;\n this.streamIcon = streamIcon;\n this.subject = subject;\n }\n\n public Stream(StreamInterface stream) {\n this(stream.getStreamType(), stream.getStepMeta(), stream.getDescription(), stream.getStreamIcon(), stream.getSubject());\n }\n\n public String toString() {\n if (stepMeta == null) {\n return \"Stream type \" + streamType + Const.CR + description;\n } else {\n return \"Stream type \" + streamType + \" for step '\" + stepMeta.getName() + \"'\" + Const.CR + description;\n }\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof StreamInterface)) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n StreamInterface stream = (StreamInterface) obj;\n if (description.equals(stream.getDescription())) {\n return true;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return description.hashCode();\n }\n\n public String getStepname() {\n if (stepMeta == null) {\n return null;\n }\n return stepMeta.getName();\n }\n\n /**\n * @return the description\n */\n public String getDescription() {\n return description;\n }\n\n /**\n * @param description\n * the description to set\n */\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * @return the streamType\n */\n public StreamType getStreamType() {\n return streamType;\n }\n\n /**\n * @param streamType\n * the streamType to set\n */\n public void setStreamType(StreamType streamType) {\n this.streamType = streamType;\n }\n\n /**\n * @return the stepMeta\n */\n public StepMeta getStepMeta() {\n return stepMeta;\n }\n\n /**\n * @param stepMeta\n * the stepMeta to set\n */\n public void setStepMeta(StepMeta stepMeta) {\n this.stepMeta = stepMeta;\n }\n\n /**\n * @return the streamIcon\n */\n public StreamIcon getStreamIcon() ", "post_mask_code": "\n\n /**\n * @param streamIcon\n * the streamIcon to set\n */\n public void setStreamIcon(StreamIcon streamIcon) {\n this.streamIcon = streamIcon;\n }\n\n /**\n * @return the subject\n */\n public Object getSubject() {\n return subject;\n }\n\n /**\n * @param subject\n * the subject to set\n */\n public void setSubject(Object subject) {\n this.subject = subject;\n }\n}\n"} {"task_id": "Java_2457", "language": "Java", "task_type": "single_line", "source_file": "java/github/pentaho/pentaho-kettle/engine/src/main/java/org/pentaho/di/trans/step/errorhandling/Stream.java", "mask_start_position": 1764, "mask_end_position": 1778, "canonical_solution": "nterface) obj;", "pre_mask_code": "/*! ******************************************************************************\n *\n * Pentaho Data Integration\n *\n *\n *******************************************************************************\n *\n *\n ******************************************************************************/\npackage org.pentaho.di.trans.step.errorhandling;\n\nimport org.pentaho.di.core.Const;\nimport org.pentaho.di.trans.step.StepMeta;\n\npublic class Stream implements StreamInterface {\n\n private String description;\n\n private StreamType streamType;\n\n private StepMeta stepMeta;\n\n private StreamIcon streamIcon;\n\n private Object subject;\n\n /**\n * @param streamType\n * @param stepname\n * @param stepMeta\n * @param description\n */\n public Stream(StreamType streamType, StepMeta stepMeta, String description, StreamIcon streamIcon, Object subject) {\n this.streamType = streamType;\n this.stepMeta = stepMeta;\n this.description = description;\n this.streamIcon = streamIcon;\n this.subject = subject;\n }\n\n public Stream(StreamInterface stream) {\n this(stream.getStreamType(), stream.getStepMeta(), stream.getDescription(), stream.getStreamIcon(), stream.getSubject());\n }\n\n public String toString() {\n if (stepMeta == null) {\n return \"Stream type \" + streamType + Const.CR + description;\n } else {\n return \"Stream type \" + streamType + \" for step '\" + stepMeta.getName() + \"'\" + Const.CR + description;\n }\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof StreamInterface)) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n StreamInterface stream = (StreamI", "post_mask_code": "\n if (description.equals(stream.getDescription())) {\n return true;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return description.hashCode();\n }\n\n public String getStepname() {\n if (stepMeta == null) {\n return null;\n }\n return stepMeta.getName();\n }\n\n /**\n * @return the description\n */\n public String getDescription() {\n return description;\n }\n\n /**\n * @param description\n * the description to set\n */\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * @return the streamType\n */\n public StreamType getStreamType() {\n return streamType;\n }\n\n /**\n * @param streamType\n * the streamType to set\n */\n public void setStreamType(StreamType streamType) {\n this.streamType = streamType;\n }\n\n /**\n * @return the stepMeta\n */\n public StepMeta getStepMeta() {\n return stepMeta;\n }\n\n /**\n * @param stepMeta\n * the stepMeta to set\n */\n public void setStepMeta(StepMeta stepMeta) {\n this.stepMeta = stepMeta;\n }\n\n /**\n * @return the streamIcon\n */\n public StreamIcon getStreamIcon() {\n return streamIcon;\n }\n\n /**\n * @param streamIcon\n * the streamIcon to set\n */\n public void setStreamIcon(StreamIcon streamIcon) {\n this.streamIcon = streamIcon;\n }\n\n /**\n * @return the subject\n */\n public Object getSubject() {\n return subject;\n }\n\n /**\n * @param subject\n * the subject to set\n */\n public void setSubject(Object subject) {\n this.subject = subject;\n }\n}\n"} {"task_id": "Java_2458", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/pentaho/pentaho-kettle/engine/src/main/java/org/pentaho/di/trans/step/errorhandling/Stream.java", "mask_start_position": 2184, "mask_end_position": 2250, "canonical_solution": "public String getDescription() {\n return description;\n }", "pre_mask_code": "/*! ******************************************************************************\n *\n * Pentaho Data Integration\n *\n *\n *******************************************************************************\n *\n *\n ******************************************************************************/\npackage org.pentaho.di.trans.step.errorhandling;\n\nimport org.pentaho.di.core.Const;\nimport org.pentaho.di.trans.step.StepMeta;\n\npublic class Stream implements StreamInterface {\n\n private String description;\n\n private StreamType streamType;\n\n private StepMeta stepMeta;\n\n private StreamIcon streamIcon;\n\n private Object subject;\n\n /**\n * @param streamType\n * @param stepname\n * @param stepMeta\n * @param description\n */\n public Stream(StreamType streamType, StepMeta stepMeta, String description, StreamIcon streamIcon, Object subject) {\n this.streamType = streamType;\n this.stepMeta = stepMeta;\n this.description = description;\n this.streamIcon = streamIcon;\n this.subject = subject;\n }\n\n public Stream(StreamInterface stream) {\n this(stream.getStreamType(), stream.getStepMeta(), stream.getDescription(), stream.getStreamIcon(), stream.getSubject());\n }\n\n public String toString() {\n if (stepMeta == null) {\n return \"Stream type \" + streamType + Const.CR + description;\n } else {\n return \"Stream type \" + streamType + \" for step '\" + stepMeta.getName() + \"'\" + Const.CR + description;\n }\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof StreamInterface)) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n StreamInterface stream = (StreamInterface) obj;\n if (description.equals(stream.getDescription())) {\n return true;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return description.hashCode();\n }\n\n public String getStepname() {\n if (stepMeta == null) {\n return null;\n }\n return stepMeta.getName();\n }\n\n /**\n * @return the description\n */\n ", "post_mask_code": "\n\n /**\n * @param description\n * the description to set\n */\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * @return the streamType\n */\n public StreamType getStreamType() {\n return streamType;\n }\n\n /**\n * @param streamType\n * the streamType to set\n */\n public void setStreamType(StreamType streamType) {\n this.streamType = streamType;\n }\n\n /**\n * @return the stepMeta\n */\n public StepMeta getStepMeta() {\n return stepMeta;\n }\n\n /**\n * @param stepMeta\n * the stepMeta to set\n */\n public void setStepMeta(StepMeta stepMeta) {\n this.stepMeta = stepMeta;\n }\n\n /**\n * @return the streamIcon\n */\n public StreamIcon getStreamIcon() {\n return streamIcon;\n }\n\n /**\n * @param streamIcon\n * the streamIcon to set\n */\n public void setStreamIcon(StreamIcon streamIcon) {\n this.streamIcon = streamIcon;\n }\n\n /**\n * @return the subject\n */\n public Object getSubject() {\n return subject;\n }\n\n /**\n * @param subject\n * the subject to set\n */\n public void setSubject(Object subject) {\n this.subject = subject;\n }\n}\n"} {"task_id": "Java_2459", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/geosdi/geo-platform/geoplatform-experimental/geoplatform-elastic-search/geoplatform-elastic-search-api/src/main/java/org/geosdi/geoplatform/experimental/el/threadpool/spi/finder/GPThreadPoolExecutorFinder.java", "mask_start_position": 706, "mask_end_position": 737, "canonical_solution": "ExecutorService findExecutor();", "pre_mask_code": "/**\n * geo-platform\n * Rich webgis framework\n * http://geo-platform.org\n * ====================================================================\n *\n * ====================================================================\n */\npackage org.geosdi.geoplatform.experimental.el.threadpool.spi.finder;\n\nimport org.geosdi.geoplatform.threadpool.support.spi.finder.GPThreadPoolExecutorFinderSupport;\nimport java.util.concurrent.ExecutorService;\n\n/**\n * @author Giuseppe La Scaleia - CNR IMAA geoSDI Group\n * @email example@nnthink.com\n */\npublic interface GPThreadPoolExecutorFinder extends GPThreadPoolExecutorFinderSupport {\n\n /**\n * @return {@link ExecutorService}\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2460", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse-ee4j/eclipselink/jpa/eclipselink.jpa.test/src/it/java/org/eclipse/persistence/testing/tests/jpa/fieldaccess/advanced/FAServerTestSuite.java", "mask_start_position": 424, "mask_end_position": 451, "canonical_solution": "public static Test suite() ", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.testing.tests.jpa.fieldaccess.advanced;\n\nimport org.eclipse.persistence.testing.framework.junit.JUnitTestCase;\nimport junit.framework.TestSuite;\nimport junit.framework.Test;\n\n/**\n *

Purpose: To collect the tests that will run against Application Server only.\n */\npublic class FAServerTestSuite extends TestSuite {\n\n ", "post_mask_code": "{\n JUnitTestCase.initializePlatform();\n TestSuite suite = new TestSuite();\n suite.setName(\"Fieldaccess Advanced ServerTestSuite\");\n suite.addTest(AdvancedJPAJunitTest.suite());\n suite.addTest(AdvancedJunitTest.suite());\n suite.addTest(CallbackEventJUnitTestSuite.suite());\n suite.addTest(EntityManagerJUnitTestSuite.suiteSpring());\n suite.addTest(ExtendedPersistenceContextJUnitTestSuite.suite());\n suite.addTest(JoinedAttributeAdvancedJunitTest.suiteSpring());\n suite.addTest(NamedNativeQueryJUnitTest.suite());\n suite.addTest(OptimisticConcurrencyJUnitTestSuite.suite());\n suite.addTest(ReportQueryAdvancedJUnitTest.suite());\n suite.addTest(ReportQueryConstructorExpressionTestSuite.suite());\n suite.addTest(ReportQueryMultipleReturnTestSuite.suite());\n suite.addTest(SQLResultSetMappingTestSuite.suite());\n suite.addTest(UpdateAllQueryAdvancedJunitTest.suite());\n return suite;\n }\n}\n"} {"task_id": "Java_2461", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse-ee4j/eclipselink/jpa/eclipselink.jpa.test/src/it/java/org/eclipse/persistence/testing/tests/jpa/fieldaccess/advanced/FAServerTestSuite.java", "mask_start_position": 1180, "mask_end_position": 1236, "canonical_solution": "Test(ReportQueryConstructorExpressionTestSuite.suite());", "pre_mask_code": "// Oracle - initial API and implementation from Oracle TopLink\npackage org.eclipse.persistence.testing.tests.jpa.fieldaccess.advanced;\n\nimport org.eclipse.persistence.testing.framework.junit.JUnitTestCase;\nimport junit.framework.TestSuite;\nimport junit.framework.Test;\n\n/**\n *

Purpose: To collect the tests that will run against Application Server only.\n */\npublic class FAServerTestSuite extends TestSuite {\n\n public static Test suite() {\n JUnitTestCase.initializePlatform();\n TestSuite suite = new TestSuite();\n suite.setName(\"Fieldaccess Advanced ServerTestSuite\");\n suite.addTest(AdvancedJPAJunitTest.suite());\n suite.addTest(AdvancedJunitTest.suite());\n suite.addTest(CallbackEventJUnitTestSuite.suite());\n suite.addTest(EntityManagerJUnitTestSuite.suiteSpring());\n suite.addTest(ExtendedPersistenceContextJUnitTestSuite.suite());\n suite.addTest(JoinedAttributeAdvancedJunitTest.suiteSpring());\n suite.addTest(NamedNativeQueryJUnitTest.suite());\n suite.addTest(OptimisticConcurrencyJUnitTestSuite.suite());\n suite.addTest(ReportQueryAdvancedJUnitTest.suite());\n suite.add", "post_mask_code": "\n suite.addTest(ReportQueryMultipleReturnTestSuite.suite());\n suite.addTest(SQLResultSetMappingTestSuite.suite());\n suite.addTest(UpdateAllQueryAdvancedJunitTest.suite());\n return suite;\n }\n}\n"} {"task_id": "Java_2462", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Apicurio/apicurio-studio/back-end/hub-core/src/main/java/io/apicurio/hub/core/util/FormatUtils.java", "mask_start_position": 1709, "mask_end_position": 1776, "canonical_solution": "public static String formatJson(String content) throws IOException ", "pre_mask_code": "package io.apicurio.hub.core.util;\n\nimport java.io.IOException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.SerializationFeature;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLFactory;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;\n\n/**\n * @author example@nnthink.com\n */\npublic class FormatUtils {\n\n private static ObjectMapper jsonMapper = new ObjectMapper();\n\n private static ObjectMapper yamlMapper;\n\n static {\n YAMLFactory factory = new YAMLFactory();\n factory.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);\n factory.enable(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS);\n yamlMapper = new ObjectMapper(factory);\n jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);\n }\n\n /**\n * Converts the content from JSON to YAML format.\n * @param content\n * @throws IOException\n */\n public static String jsonToYaml(String content) throws IOException {\n JsonNode tree = jsonMapper.reader().readTree(content);\n return yamlMapper.writeValueAsString(tree);\n }\n\n /**\n * Converts the content from YAML to JSON format.\n * @param content\n * @throws IOException\n */\n public static String yamlToJson(String content) throws IOException {\n JsonNode tree = yamlMapper.reader().readTree(content);\n return jsonMapper.writeValueAsString(tree);\n }\n\n /**\n * Takes JSON content and formats with a standard 2 spaces per indent. This\n * is used to take (potentially) unformatted JSON and convert it to formatted JSON.\n * @param content\n * @throws IOException\n */\n ", "post_mask_code": "{\n // If it's already formatted, do nothing.\n if (content.contains(\"\\n\")) {\n return content;\n }\n JsonNode tree = jsonMapper.reader().readTree(content);\n return jsonMapper.writeValueAsString(tree);\n }\n}\n"} {"task_id": "Java_2463", "language": "Java", "task_type": "method_body", "source_file": "java/github/Apicurio/apicurio-studio/back-end/hub-core/src/main/java/io/apicurio/hub/core/util/FormatUtils.java", "mask_start_position": 1776, "mask_end_position": 2024, "canonical_solution": "{\n // If it's already formatted, do nothing.\n if (content.contains(\"\\n\")) {\n return content;\n }\n JsonNode tree = jsonMapper.reader().readTree(content);\n return jsonMapper.writeValueAsString(tree);\n }", "pre_mask_code": "package io.apicurio.hub.core.util;\n\nimport java.io.IOException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.SerializationFeature;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLFactory;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;\n\n/**\n * @author example@nnthink.com\n */\npublic class FormatUtils {\n\n private static ObjectMapper jsonMapper = new ObjectMapper();\n\n private static ObjectMapper yamlMapper;\n\n static {\n YAMLFactory factory = new YAMLFactory();\n factory.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);\n factory.enable(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS);\n yamlMapper = new ObjectMapper(factory);\n jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);\n }\n\n /**\n * Converts the content from JSON to YAML format.\n * @param content\n * @throws IOException\n */\n public static String jsonToYaml(String content) throws IOException {\n JsonNode tree = jsonMapper.reader().readTree(content);\n return yamlMapper.writeValueAsString(tree);\n }\n\n /**\n * Converts the content from YAML to JSON format.\n * @param content\n * @throws IOException\n */\n public static String yamlToJson(String content) throws IOException {\n JsonNode tree = yamlMapper.reader().readTree(content);\n return jsonMapper.writeValueAsString(tree);\n }\n\n /**\n * Takes JSON content and formats with a standard 2 spaces per indent. This\n * is used to take (potentially) unformatted JSON and convert it to formatted JSON.\n * @param content\n * @throws IOException\n */\n public static String formatJson(String content) throws IOException ", "post_mask_code": "\n}\n"} {"task_id": "Java_2464", "language": "Java", "task_type": "single_line", "source_file": "java/github/Apicurio/apicurio-studio/back-end/hub-core/src/main/java/io/apicurio/hub/core/util/FormatUtils.java", "mask_start_position": 1999, "mask_end_position": 2018, "canonical_solution": "alueAsString(tree);", "pre_mask_code": "package io.apicurio.hub.core.util;\n\nimport java.io.IOException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.SerializationFeature;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLFactory;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;\n\n/**\n * @author example@nnthink.com\n */\npublic class FormatUtils {\n\n private static ObjectMapper jsonMapper = new ObjectMapper();\n\n private static ObjectMapper yamlMapper;\n\n static {\n YAMLFactory factory = new YAMLFactory();\n factory.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);\n factory.enable(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS);\n yamlMapper = new ObjectMapper(factory);\n jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);\n }\n\n /**\n * Converts the content from JSON to YAML format.\n * @param content\n * @throws IOException\n */\n public static String jsonToYaml(String content) throws IOException {\n JsonNode tree = jsonMapper.reader().readTree(content);\n return yamlMapper.writeValueAsString(tree);\n }\n\n /**\n * Converts the content from YAML to JSON format.\n * @param content\n * @throws IOException\n */\n public static String yamlToJson(String content) throws IOException {\n JsonNode tree = yamlMapper.reader().readTree(content);\n return jsonMapper.writeValueAsString(tree);\n }\n\n /**\n * Takes JSON content and formats with a standard 2 spaces per indent. This\n * is used to take (potentially) unformatted JSON and convert it to formatted JSON.\n * @param content\n * @throws IOException\n */\n public static String formatJson(String content) throws IOException {\n // If it's already formatted, do nothing.\n if (content.contains(\"\\n\")) {\n return content;\n }\n JsonNode tree = jsonMapper.reader().readTree(content);\n return jsonMapper.writeV", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2465", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Apicurio/apicurio-studio/back-end/hub-core/src/main/java/io/apicurio/hub/core/util/FormatUtils.java", "mask_start_position": 966, "mask_end_position": 1155, "canonical_solution": "public static String jsonToYaml(String content) throws IOException {\n JsonNode tree = jsonMapper.reader().readTree(content);\n return yamlMapper.writeValueAsString(tree);\n }", "pre_mask_code": "package io.apicurio.hub.core.util;\n\nimport java.io.IOException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.SerializationFeature;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLFactory;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;\n\n/**\n * @author example@nnthink.com\n */\npublic class FormatUtils {\n\n private static ObjectMapper jsonMapper = new ObjectMapper();\n\n private static ObjectMapper yamlMapper;\n\n static {\n YAMLFactory factory = new YAMLFactory();\n factory.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);\n factory.enable(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS);\n yamlMapper = new ObjectMapper(factory);\n jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);\n }\n\n /**\n * Converts the content from JSON to YAML format.\n * @param content\n * @throws IOException\n */\n ", "post_mask_code": "\n\n /**\n * Converts the content from YAML to JSON format.\n * @param content\n * @throws IOException\n */\n public static String yamlToJson(String content) throws IOException {\n JsonNode tree = yamlMapper.reader().readTree(content);\n return jsonMapper.writeValueAsString(tree);\n }\n\n /**\n * Takes JSON content and formats with a standard 2 spaces per indent. This\n * is used to take (potentially) unformatted JSON and convert it to formatted JSON.\n * @param content\n * @throws IOException\n */\n public static String formatJson(String content) throws IOException {\n // If it's already formatted, do nothing.\n if (content.contains(\"\\n\")) {\n return content;\n }\n JsonNode tree = jsonMapper.reader().readTree(content);\n return jsonMapper.writeValueAsString(tree);\n }\n}\n"} {"task_id": "Java_2466", "language": "Java", "task_type": "method_signature", "source_file": "java/github/nuxeo/nuxeo/nuxeo-services/nuxeo-platform-directory/nuxeo-platform-directory-ldap/src/main/java/org/nuxeo/ecm/directory/ldap/LDAPFilterBuilder.java", "mask_start_position": 5710, "mask_end_position": 5767, "canonical_solution": "public void walkAndMultiExpression(MultiExpression expr) ", "pre_mask_code": "package org.nuxeo.ecm.directory.ldap;\n\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.nuxeo.ecm.core.query.QueryParseException;\nimport org.nuxeo.ecm.core.query.sql.model.BooleanLiteral;\nimport org.nuxeo.ecm.core.query.sql.model.DateLiteral;\nimport org.nuxeo.ecm.core.query.sql.model.DoubleLiteral;\nimport org.nuxeo.ecm.core.query.sql.model.Expression;\nimport org.nuxeo.ecm.core.query.sql.model.Function;\nimport org.nuxeo.ecm.core.query.sql.model.IntegerLiteral;\nimport org.nuxeo.ecm.core.query.sql.model.Literal;\nimport org.nuxeo.ecm.core.query.sql.model.LiteralList;\nimport org.nuxeo.ecm.core.query.sql.model.MultiExpression;\nimport org.nuxeo.ecm.core.query.sql.model.Operand;\nimport org.nuxeo.ecm.core.query.sql.model.Operator;\nimport org.nuxeo.ecm.core.query.sql.model.Predicate;\nimport org.nuxeo.ecm.core.query.sql.model.Reference;\nimport org.nuxeo.ecm.core.query.sql.model.StringLiteral;\nimport org.nuxeo.ecm.core.schema.types.Field;\nimport org.nuxeo.ecm.core.schema.types.primitives.BooleanType;\n\n/**\n * Creates an LDAP query filter from a Nuxeo Expression.\n *\n * @since 10.3\n */\npublic class LDAPFilterBuilder {\n\n protected static final String DATE_CAST = \"DATE\";\n\n protected final LDAPDirectory directory;\n\n public StringBuilder filter = new StringBuilder();\n\n public int paramIndex = 0;\n\n public final List params = new ArrayList<>();\n\n public LDAPFilterBuilder(LDAPDirectory directory) {\n this.directory = directory;\n }\n\n public void walk(Expression expression) {\n if (expression instanceof MultiExpression && ((MultiExpression) expression).predicates.isEmpty()) {\n // special-case empty query\n return;\n } else {\n walkExpression(expression);\n }\n }\n\n public void walkExpression(Expression expr) {\n Operator op = expr.operator;\n Operand lvalue = expr.lvalue;\n Operand rvalue = expr.rvalue;\n Reference ref = lvalue instanceof Reference ? (Reference) lvalue : null;\n String name = ref != null ? ref.name : null;\n String cast = ref != null ? ref.cast : null;\n if (DATE_CAST.equals(cast)) {\n checkDateLiteralForCast(op, rvalue, name);\n }\n if (op == Operator.SUM) {\n throw new QueryParseException(\"SUM\");\n } else if (op == Operator.SUB) {\n throw new QueryParseException(\"SUB\");\n } else if (op == Operator.MUL) {\n throw new QueryParseException(\"MUL\");\n } else if (op == Operator.DIV) {\n throw new QueryParseException(\"DIV\");\n } else if (op == Operator.LT) {\n walkLt(lvalue, rvalue);\n } else if (op == Operator.GT) {\n walkGt(lvalue, rvalue);\n } else if (op == Operator.EQ) {\n walkEq(lvalue, rvalue);\n } else if (op == Operator.NOTEQ) {\n walkNotEq(lvalue, rvalue);\n } else if (op == Operator.LTEQ) {\n walkLtEq(lvalue, rvalue);\n } else if (op == Operator.GTEQ) {\n walkGtEq(lvalue, rvalue);\n } else if (op == Operator.AND) {\n if (expr instanceof MultiExpression) {\n walkAndMultiExpression((MultiExpression) expr);\n } else {\n walkAnd(expr);\n }\n } else if (op == Operator.NOT) {\n walkNot(lvalue);\n } else if (op == Operator.OR) {\n if (expr instanceof MultiExpression) {\n walkOrMultiExpression((MultiExpression) expr);\n } else {\n walkOr(expr);\n }\n } else if (op == Operator.LIKE) {\n walkLike(lvalue, rvalue, true, false);\n } else if (op == Operator.ILIKE) {\n walkLike(lvalue, rvalue, true, true);\n } else if (op == Operator.NOTLIKE) {\n walkLike(lvalue, rvalue, false, false);\n } else if (op == Operator.NOTILIKE) {\n walkLike(lvalue, rvalue, false, true);\n } else if (op == Operator.IN) {\n walkIn(lvalue, rvalue, true);\n } else if (op == Operator.NOTIN) {\n walkIn(lvalue, rvalue, false);\n } else if (op == Operator.ISNULL) {\n walkIsNull(lvalue);\n } else if (op == Operator.ISNOTNULL) {\n walkIsNotNull(lvalue);\n } else if (op == Operator.BETWEEN) {\n walkBetween(lvalue, rvalue, true);\n } else if (op == Operator.NOTBETWEEN) {\n walkBetween(lvalue, rvalue, false);\n } else {\n throw new QueryParseException(\"Unknown operator: \" + op);\n }\n }\n\n protected void checkDateLiteralForCast(Operator op, Operand value, String name) {\n if (op == Operator.BETWEEN || op == Operator.NOTBETWEEN) {\n LiteralList l = (LiteralList) value;\n checkDateLiteralForCast(l.get(0), name);\n checkDateLiteralForCast(l.get(1), name);\n } else {\n checkDateLiteralForCast(value, name);\n }\n }\n\n protected void checkDateLiteralForCast(Operand value, String name) {\n if (value instanceof DateLiteral && !((DateLiteral) value).onlyDate) {\n throw new QueryParseException(\"DATE() cast must be used with DATE literal, not TIMESTAMP: \" + name);\n }\n }\n\n public void walkNot(Operand value) {\n filter.append(\"(!\");\n walkOperand(value);\n filter.append(')');\n }\n\n public void walkIsNull(Operand value) {\n filter.append(\"(!\");\n walkIsNotNull(value);\n filter.append(')');\n }\n\n public void walkIsNotNull(Operand value) {\n filter.append('(');\n walkReference(value);\n filter.append(\"=*)\");\n }\n\n ", "post_mask_code": "{\n walkMulti(\"&\", expr.predicates);\n }\n\n public void walkAnd(Expression expr) {\n walkMulti(\"&\", Arrays.asList(expr.lvalue, expr.rvalue));\n }\n\n public void walkOrMultiExpression(MultiExpression expr) {\n walkMulti(\"|\", expr.predicates);\n }\n\n public void walkOr(Expression expr) {\n walkMulti(\"|\", Arrays.asList(expr.lvalue, expr.rvalue));\n }\n\n protected void walkMulti(String op, List values) {\n if (values.size() == 1) {\n walkOperand(values.get(0));\n } else {\n filter.append('(');\n filter.append(op);\n for (Operand value : values) {\n walkOperand(value);\n }\n filter.append(')');\n }\n }\n\n public void walkEq(Operand lvalue, Operand rvalue) {\n walkBinOp(\"=\", lvalue, rvalue);\n }\n\n public void walkNotEq(Operand lvalue, Operand rvalue) {\n filter.append(\"(!\");\n walkEq(lvalue, rvalue);\n filter.append(')');\n }\n\n public void walkLt(Operand lvalue, Operand rvalue) {\n walkBinOp(\"<\", lvalue, rvalue);\n }\n\n public void walkGt(Operand lvalue, Operand rvalue) {\n walkBinOp(\">\", lvalue, rvalue);\n }\n\n public void walkLtEq(Operand lvalue, Operand rvalue) {\n walkBinOp(\"<=\", lvalue, rvalue);\n }\n\n public void walkGtEq(Operand lvalue, Operand rvalue) {\n walkBinOp(\">=\", lvalue, rvalue);\n }\n\n protected void walkBinOp(String op, Operand lvalue, Operand rvalue) {\n filter.append('(');\n Field field = walkReference(lvalue);\n filter.append(op);\n if (field.getType() instanceof BooleanType) {\n rvalue = makeBoolean(rvalue);\n }\n walkLiteral(rvalue);\n filter.append(')');\n }\n\n protected Operand makeBoolean(Operand rvalue) {\n if (rvalue instanceof BooleanLiteral) {\n return rvalue;\n }\n long v;\n if (!(rvalue instanceof IntegerLiteral) || ((v = ((IntegerLiteral) rvalue).value) != 0 && v != 1)) {\n throw new QueryParseException(\"Boolean expressions require boolean or literal 0 or 1 as right argument\");\n }\n return new BooleanLiteral(v == 1);\n }\n\n public void walkBetween(Operand lvalue, Operand rvalue, boolean positive) {\n LiteralList list = (LiteralList) rvalue;\n Literal left = list.get(0);\n Literal right = list.get(1);\n if (!positive) {\n filter.append(\"(!\");\n }\n filter.append(\"(&\");\n walkGtEq(lvalue, left);\n walkLtEq(lvalue, right);\n filter.append(')');\n if (!positive) {\n filter.append(')');\n }\n }\n\n public void walkIn(Operand lvalue, Operand rvalue, boolean positive) {\n if (!positive) {\n filter.append(\"(!\");\n }\n filter.append(\"(|\");\n for (Literal value : (LiteralList) rvalue) {\n walkEq(lvalue, value);\n }\n filter.append(')');\n if (!positive) {\n filter.append(')');\n }\n }\n\n public void walkLike(Operand lvalue, Operand rvalue, boolean positive, boolean caseInsensitive) {\n if (!(rvalue instanceof StringLiteral)) {\n throw new QueryParseException(\"Invalid LIKE, right hand side must be a string: \" + rvalue);\n }\n String like = ((StringLiteral) rvalue).value;\n if (caseInsensitive) {\n like = like.toLowerCase();\n }\n if (!positive) {\n filter.append(\"(!\");\n }\n filter.append('(');\n walkReference(lvalue);\n filter.append('=');\n walkLikeWildcard(like);\n filter.append(')');\n if (!positive) {\n filter.append(')');\n }\n }\n\n /**\n * Turns a NXQL LIKE pattern into an LDAP wildcard.\n *

\n * % and _ are standard wildcards, and \\ escapes them.\n */\n public void walkLikeWildcard(String like) {\n StringBuilder param = new StringBuilder();\n char[] chars = like.toCharArray();\n boolean escape = false;\n for (int i = 0; i < chars.length; i++) {\n char c = chars[i];\n boolean escapeNext = false;\n if (escape) {\n param.append(c);\n } else {\n switch(c) {\n case '%':\n if (param.length() != 0) {\n addFilterParam(param.toString());\n param.setLength(0);\n }\n filter.append('*');\n break;\n case // interpret it as an escaped _, not a wildcard\n '_':\n param.append(c);\n break;\n case '\\\\':\n escapeNext = true;\n break;\n default:\n param.append(c);\n break;\n }\n }\n escape = escapeNext;\n }\n if (escape) {\n throw new QueryParseException(\"Invalid LIKE parameter ending with escape character\");\n }\n if (param.length() != 0) {\n addFilterParam(param.toString());\n }\n }\n\n public void walkOperand(Operand operand) {\n if (operand instanceof Literal) {\n walkLiteral((Literal) operand);\n } else if (operand instanceof Function) {\n walkFunction((Function) operand);\n } else if (operand instanceof Expression) {\n walkExpression((Expression) operand);\n } else if (operand instanceof Reference) {\n walkReference((Reference) operand);\n } else {\n throw new QueryParseException(\"Unknown operand: \" + operand);\n }\n }\n\n public void walkLiteral(Operand operand) {\n if (!(operand instanceof Literal)) {\n throw new QueryParseException(\"Requires literal instead of: \" + operand);\n }\n Literal lit = (Literal) operand;\n if (lit instanceof BooleanLiteral) {\n walkBooleanLiteral((BooleanLiteral) lit);\n } else if (lit instanceof DateLiteral) {\n walkDateLiteral((DateLiteral) lit);\n } else if (lit instanceof DoubleLiteral) {\n walkDoubleLiteral((DoubleLiteral) lit);\n } else if (lit instanceof IntegerLiteral) {\n walkIntegerLiteral((IntegerLiteral) lit);\n } else if (lit instanceof StringLiteral) {\n walkStringLiteral((StringLiteral) lit);\n } else {\n throw new QueryParseException(\"Unknown literal: \" + lit);\n }\n }\n\n public void walkBooleanLiteral(BooleanLiteral lit) {\n addFilterParam(Boolean.valueOf(lit.value));\n }\n\n public void walkDateLiteral(DateLiteral lit) {\n if (lit.onlyDate) {\n throw new QueryParseException(\"Cannot use only date in LDAP query: \" + lit);\n }\n // let LDAP library serialize it\n addFilterParam(lit.toCalendar());\n }\n\n public void walkDoubleLiteral(DoubleLiteral lit) {\n addFilterParam(Double.valueOf(lit.value));\n }\n\n public void walkIntegerLiteral(IntegerLiteral lit) {\n addFilterParam(Long.valueOf(lit.value));\n }\n\n public void walkStringLiteral(StringLiteral lit) {\n addFilterParam(lit.value);\n }\n\n protected void addFilterParam(Serializable value) {\n filter.append('{');\n filter.append(paramIndex++);\n filter.append('}');\n params.add(value);\n }\n\n public Object walkFunction(Function func) {\n throw new QueryParseException(func.name);\n }\n\n public Field walkReference(Operand value) {\n if (!(value instanceof Reference)) {\n throw new QueryParseException(\"Invalid query, left hand side must be a property: \" + value);\n }\n String name = ((Reference) value).name;\n if (directory.isReference(name)) {\n throw new QueryParseException(\"Column: \" + name + \" is a reference and cannot be queried for directory: \" + directory.getName());\n }\n Field field = directory.getSchemaFieldMap().get(name);\n if (field == null) {\n throw new QueryParseException(\"No column: \" + name + \" for directory: \" + directory.getName());\n }\n String backend = directory.getFieldMapper().getBackendField(name);\n filter.append(backend);\n return field;\n }\n}\n"} {"task_id": "Java_2467", "language": "Java", "task_type": "method_body", "source_file": "java/github/nuxeo/nuxeo/nuxeo-services/nuxeo-platform-directory/nuxeo-platform-directory-ldap/src/main/java/org/nuxeo/ecm/directory/ldap/LDAPFilterBuilder.java", "mask_start_position": 13076, "mask_end_position": 13118, "canonical_solution": "{\n addFilterParam(lit.value);\n }", "pre_mask_code": "package org.nuxeo.ecm.directory.ldap;\n\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.nuxeo.ecm.core.query.QueryParseException;\nimport org.nuxeo.ecm.core.query.sql.model.BooleanLiteral;\nimport org.nuxeo.ecm.core.query.sql.model.DateLiteral;\nimport org.nuxeo.ecm.core.query.sql.model.DoubleLiteral;\nimport org.nuxeo.ecm.core.query.sql.model.Expression;\nimport org.nuxeo.ecm.core.query.sql.model.Function;\nimport org.nuxeo.ecm.core.query.sql.model.IntegerLiteral;\nimport org.nuxeo.ecm.core.query.sql.model.Literal;\nimport org.nuxeo.ecm.core.query.sql.model.LiteralList;\nimport org.nuxeo.ecm.core.query.sql.model.MultiExpression;\nimport org.nuxeo.ecm.core.query.sql.model.Operand;\nimport org.nuxeo.ecm.core.query.sql.model.Operator;\nimport org.nuxeo.ecm.core.query.sql.model.Predicate;\nimport org.nuxeo.ecm.core.query.sql.model.Reference;\nimport org.nuxeo.ecm.core.query.sql.model.StringLiteral;\nimport org.nuxeo.ecm.core.schema.types.Field;\nimport org.nuxeo.ecm.core.schema.types.primitives.BooleanType;\n\n/**\n * Creates an LDAP query filter from a Nuxeo Expression.\n *\n * @since 10.3\n */\npublic class LDAPFilterBuilder {\n\n protected static final String DATE_CAST = \"DATE\";\n\n protected final LDAPDirectory directory;\n\n public StringBuilder filter = new StringBuilder();\n\n public int paramIndex = 0;\n\n public final List params = new ArrayList<>();\n\n public LDAPFilterBuilder(LDAPDirectory directory) {\n this.directory = directory;\n }\n\n public void walk(Expression expression) {\n if (expression instanceof MultiExpression && ((MultiExpression) expression).predicates.isEmpty()) {\n // special-case empty query\n return;\n } else {\n walkExpression(expression);\n }\n }\n\n public void walkExpression(Expression expr) {\n Operator op = expr.operator;\n Operand lvalue = expr.lvalue;\n Operand rvalue = expr.rvalue;\n Reference ref = lvalue instanceof Reference ? (Reference) lvalue : null;\n String name = ref != null ? ref.name : null;\n String cast = ref != null ? ref.cast : null;\n if (DATE_CAST.equals(cast)) {\n checkDateLiteralForCast(op, rvalue, name);\n }\n if (op == Operator.SUM) {\n throw new QueryParseException(\"SUM\");\n } else if (op == Operator.SUB) {\n throw new QueryParseException(\"SUB\");\n } else if (op == Operator.MUL) {\n throw new QueryParseException(\"MUL\");\n } else if (op == Operator.DIV) {\n throw new QueryParseException(\"DIV\");\n } else if (op == Operator.LT) {\n walkLt(lvalue, rvalue);\n } else if (op == Operator.GT) {\n walkGt(lvalue, rvalue);\n } else if (op == Operator.EQ) {\n walkEq(lvalue, rvalue);\n } else if (op == Operator.NOTEQ) {\n walkNotEq(lvalue, rvalue);\n } else if (op == Operator.LTEQ) {\n walkLtEq(lvalue, rvalue);\n } else if (op == Operator.GTEQ) {\n walkGtEq(lvalue, rvalue);\n } else if (op == Operator.AND) {\n if (expr instanceof MultiExpression) {\n walkAndMultiExpression((MultiExpression) expr);\n } else {\n walkAnd(expr);\n }\n } else if (op == Operator.NOT) {\n walkNot(lvalue);\n } else if (op == Operator.OR) {\n if (expr instanceof MultiExpression) {\n walkOrMultiExpression((MultiExpression) expr);\n } else {\n walkOr(expr);\n }\n } else if (op == Operator.LIKE) {\n walkLike(lvalue, rvalue, true, false);\n } else if (op == Operator.ILIKE) {\n walkLike(lvalue, rvalue, true, true);\n } else if (op == Operator.NOTLIKE) {\n walkLike(lvalue, rvalue, false, false);\n } else if (op == Operator.NOTILIKE) {\n walkLike(lvalue, rvalue, false, true);\n } else if (op == Operator.IN) {\n walkIn(lvalue, rvalue, true);\n } else if (op == Operator.NOTIN) {\n walkIn(lvalue, rvalue, false);\n } else if (op == Operator.ISNULL) {\n walkIsNull(lvalue);\n } else if (op == Operator.ISNOTNULL) {\n walkIsNotNull(lvalue);\n } else if (op == Operator.BETWEEN) {\n walkBetween(lvalue, rvalue, true);\n } else if (op == Operator.NOTBETWEEN) {\n walkBetween(lvalue, rvalue, false);\n } else {\n throw new QueryParseException(\"Unknown operator: \" + op);\n }\n }\n\n protected void checkDateLiteralForCast(Operator op, Operand value, String name) {\n if (op == Operator.BETWEEN || op == Operator.NOTBETWEEN) {\n LiteralList l = (LiteralList) value;\n checkDateLiteralForCast(l.get(0), name);\n checkDateLiteralForCast(l.get(1), name);\n } else {\n checkDateLiteralForCast(value, name);\n }\n }\n\n protected void checkDateLiteralForCast(Operand value, String name) {\n if (value instanceof DateLiteral && !((DateLiteral) value).onlyDate) {\n throw new QueryParseException(\"DATE() cast must be used with DATE literal, not TIMESTAMP: \" + name);\n }\n }\n\n public void walkNot(Operand value) {\n filter.append(\"(!\");\n walkOperand(value);\n filter.append(')');\n }\n\n public void walkIsNull(Operand value) {\n filter.append(\"(!\");\n walkIsNotNull(value);\n filter.append(')');\n }\n\n public void walkIsNotNull(Operand value) {\n filter.append('(');\n walkReference(value);\n filter.append(\"=*)\");\n }\n\n public void walkAndMultiExpression(MultiExpression expr) {\n walkMulti(\"&\", expr.predicates);\n }\n\n public void walkAnd(Expression expr) {\n walkMulti(\"&\", Arrays.asList(expr.lvalue, expr.rvalue));\n }\n\n public void walkOrMultiExpression(MultiExpression expr) {\n walkMulti(\"|\", expr.predicates);\n }\n\n public void walkOr(Expression expr) {\n walkMulti(\"|\", Arrays.asList(expr.lvalue, expr.rvalue));\n }\n\n protected void walkMulti(String op, List values) {\n if (values.size() == 1) {\n walkOperand(values.get(0));\n } else {\n filter.append('(');\n filter.append(op);\n for (Operand value : values) {\n walkOperand(value);\n }\n filter.append(')');\n }\n }\n\n public void walkEq(Operand lvalue, Operand rvalue) {\n walkBinOp(\"=\", lvalue, rvalue);\n }\n\n public void walkNotEq(Operand lvalue, Operand rvalue) {\n filter.append(\"(!\");\n walkEq(lvalue, rvalue);\n filter.append(')');\n }\n\n public void walkLt(Operand lvalue, Operand rvalue) {\n walkBinOp(\"<\", lvalue, rvalue);\n }\n\n public void walkGt(Operand lvalue, Operand rvalue) {\n walkBinOp(\">\", lvalue, rvalue);\n }\n\n public void walkLtEq(Operand lvalue, Operand rvalue) {\n walkBinOp(\"<=\", lvalue, rvalue);\n }\n\n public void walkGtEq(Operand lvalue, Operand rvalue) {\n walkBinOp(\">=\", lvalue, rvalue);\n }\n\n protected void walkBinOp(String op, Operand lvalue, Operand rvalue) {\n filter.append('(');\n Field field = walkReference(lvalue);\n filter.append(op);\n if (field.getType() instanceof BooleanType) {\n rvalue = makeBoolean(rvalue);\n }\n walkLiteral(rvalue);\n filter.append(')');\n }\n\n protected Operand makeBoolean(Operand rvalue) {\n if (rvalue instanceof BooleanLiteral) {\n return rvalue;\n }\n long v;\n if (!(rvalue instanceof IntegerLiteral) || ((v = ((IntegerLiteral) rvalue).value) != 0 && v != 1)) {\n throw new QueryParseException(\"Boolean expressions require boolean or literal 0 or 1 as right argument\");\n }\n return new BooleanLiteral(v == 1);\n }\n\n public void walkBetween(Operand lvalue, Operand rvalue, boolean positive) {\n LiteralList list = (LiteralList) rvalue;\n Literal left = list.get(0);\n Literal right = list.get(1);\n if (!positive) {\n filter.append(\"(!\");\n }\n filter.append(\"(&\");\n walkGtEq(lvalue, left);\n walkLtEq(lvalue, right);\n filter.append(')');\n if (!positive) {\n filter.append(')');\n }\n }\n\n public void walkIn(Operand lvalue, Operand rvalue, boolean positive) {\n if (!positive) {\n filter.append(\"(!\");\n }\n filter.append(\"(|\");\n for (Literal value : (LiteralList) rvalue) {\n walkEq(lvalue, value);\n }\n filter.append(')');\n if (!positive) {\n filter.append(')');\n }\n }\n\n public void walkLike(Operand lvalue, Operand rvalue, boolean positive, boolean caseInsensitive) {\n if (!(rvalue instanceof StringLiteral)) {\n throw new QueryParseException(\"Invalid LIKE, right hand side must be a string: \" + rvalue);\n }\n String like = ((StringLiteral) rvalue).value;\n if (caseInsensitive) {\n like = like.toLowerCase();\n }\n if (!positive) {\n filter.append(\"(!\");\n }\n filter.append('(');\n walkReference(lvalue);\n filter.append('=');\n walkLikeWildcard(like);\n filter.append(')');\n if (!positive) {\n filter.append(')');\n }\n }\n\n /**\n * Turns a NXQL LIKE pattern into an LDAP wildcard.\n *

\n * % and _ are standard wildcards, and \\ escapes them.\n */\n public void walkLikeWildcard(String like) {\n StringBuilder param = new StringBuilder();\n char[] chars = like.toCharArray();\n boolean escape = false;\n for (int i = 0; i < chars.length; i++) {\n char c = chars[i];\n boolean escapeNext = false;\n if (escape) {\n param.append(c);\n } else {\n switch(c) {\n case '%':\n if (param.length() != 0) {\n addFilterParam(param.toString());\n param.setLength(0);\n }\n filter.append('*');\n break;\n case // interpret it as an escaped _, not a wildcard\n '_':\n param.append(c);\n break;\n case '\\\\':\n escapeNext = true;\n break;\n default:\n param.append(c);\n break;\n }\n }\n escape = escapeNext;\n }\n if (escape) {\n throw new QueryParseException(\"Invalid LIKE parameter ending with escape character\");\n }\n if (param.length() != 0) {\n addFilterParam(param.toString());\n }\n }\n\n public void walkOperand(Operand operand) {\n if (operand instanceof Literal) {\n walkLiteral((Literal) operand);\n } else if (operand instanceof Function) {\n walkFunction((Function) operand);\n } else if (operand instanceof Expression) {\n walkExpression((Expression) operand);\n } else if (operand instanceof Reference) {\n walkReference((Reference) operand);\n } else {\n throw new QueryParseException(\"Unknown operand: \" + operand);\n }\n }\n\n public void walkLiteral(Operand operand) {\n if (!(operand instanceof Literal)) {\n throw new QueryParseException(\"Requires literal instead of: \" + operand);\n }\n Literal lit = (Literal) operand;\n if (lit instanceof BooleanLiteral) {\n walkBooleanLiteral((BooleanLiteral) lit);\n } else if (lit instanceof DateLiteral) {\n walkDateLiteral((DateLiteral) lit);\n } else if (lit instanceof DoubleLiteral) {\n walkDoubleLiteral((DoubleLiteral) lit);\n } else if (lit instanceof IntegerLiteral) {\n walkIntegerLiteral((IntegerLiteral) lit);\n } else if (lit instanceof StringLiteral) {\n walkStringLiteral((StringLiteral) lit);\n } else {\n throw new QueryParseException(\"Unknown literal: \" + lit);\n }\n }\n\n public void walkBooleanLiteral(BooleanLiteral lit) {\n addFilterParam(Boolean.valueOf(lit.value));\n }\n\n public void walkDateLiteral(DateLiteral lit) {\n if (lit.onlyDate) {\n throw new QueryParseException(\"Cannot use only date in LDAP query: \" + lit);\n }\n // let LDAP library serialize it\n addFilterParam(lit.toCalendar());\n }\n\n public void walkDoubleLiteral(DoubleLiteral lit) {\n addFilterParam(Double.valueOf(lit.value));\n }\n\n public void walkIntegerLiteral(IntegerLiteral lit) {\n addFilterParam(Long.valueOf(lit.value));\n }\n\n public void walkStringLiteral(StringLiteral lit) ", "post_mask_code": "\n\n protected void addFilterParam(Serializable value) {\n filter.append('{');\n filter.append(paramIndex++);\n filter.append('}');\n params.add(value);\n }\n\n public Object walkFunction(Function func) {\n throw new QueryParseException(func.name);\n }\n\n public Field walkReference(Operand value) {\n if (!(value instanceof Reference)) {\n throw new QueryParseException(\"Invalid query, left hand side must be a property: \" + value);\n }\n String name = ((Reference) value).name;\n if (directory.isReference(name)) {\n throw new QueryParseException(\"Column: \" + name + \" is a reference and cannot be queried for directory: \" + directory.getName());\n }\n Field field = directory.getSchemaFieldMap().get(name);\n if (field == null) {\n throw new QueryParseException(\"No column: \" + name + \" for directory: \" + directory.getName());\n }\n String backend = directory.getFieldMapper().getBackendField(name);\n filter.append(backend);\n return field;\n }\n}\n"} {"task_id": "Java_2468", "language": "Java", "task_type": "single_line", "source_file": "java/github/nuxeo/nuxeo/nuxeo-services/nuxeo-platform-directory/nuxeo-platform-directory-ldap/src/main/java/org/nuxeo/ecm/directory/ldap/LDAPFilterBuilder.java", "mask_start_position": 9339, "mask_end_position": 9356, "canonical_solution": "eference(lvalue);", "pre_mask_code": "package org.nuxeo.ecm.directory.ldap;\n\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.nuxeo.ecm.core.query.QueryParseException;\nimport org.nuxeo.ecm.core.query.sql.model.BooleanLiteral;\nimport org.nuxeo.ecm.core.query.sql.model.DateLiteral;\nimport org.nuxeo.ecm.core.query.sql.model.DoubleLiteral;\nimport org.nuxeo.ecm.core.query.sql.model.Expression;\nimport org.nuxeo.ecm.core.query.sql.model.Function;\nimport org.nuxeo.ecm.core.query.sql.model.IntegerLiteral;\nimport org.nuxeo.ecm.core.query.sql.model.Literal;\nimport org.nuxeo.ecm.core.query.sql.model.LiteralList;\nimport org.nuxeo.ecm.core.query.sql.model.MultiExpression;\nimport org.nuxeo.ecm.core.query.sql.model.Operand;\nimport org.nuxeo.ecm.core.query.sql.model.Operator;\nimport org.nuxeo.ecm.core.query.sql.model.Predicate;\nimport org.nuxeo.ecm.core.query.sql.model.Reference;\nimport org.nuxeo.ecm.core.query.sql.model.StringLiteral;\nimport org.nuxeo.ecm.core.schema.types.Field;\nimport org.nuxeo.ecm.core.schema.types.primitives.BooleanType;\n\n/**\n * Creates an LDAP query filter from a Nuxeo Expression.\n *\n * @since 10.3\n */\npublic class LDAPFilterBuilder {\n\n protected static final String DATE_CAST = \"DATE\";\n\n protected final LDAPDirectory directory;\n\n public StringBuilder filter = new StringBuilder();\n\n public int paramIndex = 0;\n\n public final List params = new ArrayList<>();\n\n public LDAPFilterBuilder(LDAPDirectory directory) {\n this.directory = directory;\n }\n\n public void walk(Expression expression) {\n if (expression instanceof MultiExpression && ((MultiExpression) expression).predicates.isEmpty()) {\n // special-case empty query\n return;\n } else {\n walkExpression(expression);\n }\n }\n\n public void walkExpression(Expression expr) {\n Operator op = expr.operator;\n Operand lvalue = expr.lvalue;\n Operand rvalue = expr.rvalue;\n Reference ref = lvalue instanceof Reference ? (Reference) lvalue : null;\n String name = ref != null ? ref.name : null;\n String cast = ref != null ? ref.cast : null;\n if (DATE_CAST.equals(cast)) {\n checkDateLiteralForCast(op, rvalue, name);\n }\n if (op == Operator.SUM) {\n throw new QueryParseException(\"SUM\");\n } else if (op == Operator.SUB) {\n throw new QueryParseException(\"SUB\");\n } else if (op == Operator.MUL) {\n throw new QueryParseException(\"MUL\");\n } else if (op == Operator.DIV) {\n throw new QueryParseException(\"DIV\");\n } else if (op == Operator.LT) {\n walkLt(lvalue, rvalue);\n } else if (op == Operator.GT) {\n walkGt(lvalue, rvalue);\n } else if (op == Operator.EQ) {\n walkEq(lvalue, rvalue);\n } else if (op == Operator.NOTEQ) {\n walkNotEq(lvalue, rvalue);\n } else if (op == Operator.LTEQ) {\n walkLtEq(lvalue, rvalue);\n } else if (op == Operator.GTEQ) {\n walkGtEq(lvalue, rvalue);\n } else if (op == Operator.AND) {\n if (expr instanceof MultiExpression) {\n walkAndMultiExpression((MultiExpression) expr);\n } else {\n walkAnd(expr);\n }\n } else if (op == Operator.NOT) {\n walkNot(lvalue);\n } else if (op == Operator.OR) {\n if (expr instanceof MultiExpression) {\n walkOrMultiExpression((MultiExpression) expr);\n } else {\n walkOr(expr);\n }\n } else if (op == Operator.LIKE) {\n walkLike(lvalue, rvalue, true, false);\n } else if (op == Operator.ILIKE) {\n walkLike(lvalue, rvalue, true, true);\n } else if (op == Operator.NOTLIKE) {\n walkLike(lvalue, rvalue, false, false);\n } else if (op == Operator.NOTILIKE) {\n walkLike(lvalue, rvalue, false, true);\n } else if (op == Operator.IN) {\n walkIn(lvalue, rvalue, true);\n } else if (op == Operator.NOTIN) {\n walkIn(lvalue, rvalue, false);\n } else if (op == Operator.ISNULL) {\n walkIsNull(lvalue);\n } else if (op == Operator.ISNOTNULL) {\n walkIsNotNull(lvalue);\n } else if (op == Operator.BETWEEN) {\n walkBetween(lvalue, rvalue, true);\n } else if (op == Operator.NOTBETWEEN) {\n walkBetween(lvalue, rvalue, false);\n } else {\n throw new QueryParseException(\"Unknown operator: \" + op);\n }\n }\n\n protected void checkDateLiteralForCast(Operator op, Operand value, String name) {\n if (op == Operator.BETWEEN || op == Operator.NOTBETWEEN) {\n LiteralList l = (LiteralList) value;\n checkDateLiteralForCast(l.get(0), name);\n checkDateLiteralForCast(l.get(1), name);\n } else {\n checkDateLiteralForCast(value, name);\n }\n }\n\n protected void checkDateLiteralForCast(Operand value, String name) {\n if (value instanceof DateLiteral && !((DateLiteral) value).onlyDate) {\n throw new QueryParseException(\"DATE() cast must be used with DATE literal, not TIMESTAMP: \" + name);\n }\n }\n\n public void walkNot(Operand value) {\n filter.append(\"(!\");\n walkOperand(value);\n filter.append(')');\n }\n\n public void walkIsNull(Operand value) {\n filter.append(\"(!\");\n walkIsNotNull(value);\n filter.append(')');\n }\n\n public void walkIsNotNull(Operand value) {\n filter.append('(');\n walkReference(value);\n filter.append(\"=*)\");\n }\n\n public void walkAndMultiExpression(MultiExpression expr) {\n walkMulti(\"&\", expr.predicates);\n }\n\n public void walkAnd(Expression expr) {\n walkMulti(\"&\", Arrays.asList(expr.lvalue, expr.rvalue));\n }\n\n public void walkOrMultiExpression(MultiExpression expr) {\n walkMulti(\"|\", expr.predicates);\n }\n\n public void walkOr(Expression expr) {\n walkMulti(\"|\", Arrays.asList(expr.lvalue, expr.rvalue));\n }\n\n protected void walkMulti(String op, List values) {\n if (values.size() == 1) {\n walkOperand(values.get(0));\n } else {\n filter.append('(');\n filter.append(op);\n for (Operand value : values) {\n walkOperand(value);\n }\n filter.append(')');\n }\n }\n\n public void walkEq(Operand lvalue, Operand rvalue) {\n walkBinOp(\"=\", lvalue, rvalue);\n }\n\n public void walkNotEq(Operand lvalue, Operand rvalue) {\n filter.append(\"(!\");\n walkEq(lvalue, rvalue);\n filter.append(')');\n }\n\n public void walkLt(Operand lvalue, Operand rvalue) {\n walkBinOp(\"<\", lvalue, rvalue);\n }\n\n public void walkGt(Operand lvalue, Operand rvalue) {\n walkBinOp(\">\", lvalue, rvalue);\n }\n\n public void walkLtEq(Operand lvalue, Operand rvalue) {\n walkBinOp(\"<=\", lvalue, rvalue);\n }\n\n public void walkGtEq(Operand lvalue, Operand rvalue) {\n walkBinOp(\">=\", lvalue, rvalue);\n }\n\n protected void walkBinOp(String op, Operand lvalue, Operand rvalue) {\n filter.append('(');\n Field field = walkReference(lvalue);\n filter.append(op);\n if (field.getType() instanceof BooleanType) {\n rvalue = makeBoolean(rvalue);\n }\n walkLiteral(rvalue);\n filter.append(')');\n }\n\n protected Operand makeBoolean(Operand rvalue) {\n if (rvalue instanceof BooleanLiteral) {\n return rvalue;\n }\n long v;\n if (!(rvalue instanceof IntegerLiteral) || ((v = ((IntegerLiteral) rvalue).value) != 0 && v != 1)) {\n throw new QueryParseException(\"Boolean expressions require boolean or literal 0 or 1 as right argument\");\n }\n return new BooleanLiteral(v == 1);\n }\n\n public void walkBetween(Operand lvalue, Operand rvalue, boolean positive) {\n LiteralList list = (LiteralList) rvalue;\n Literal left = list.get(0);\n Literal right = list.get(1);\n if (!positive) {\n filter.append(\"(!\");\n }\n filter.append(\"(&\");\n walkGtEq(lvalue, left);\n walkLtEq(lvalue, right);\n filter.append(')');\n if (!positive) {\n filter.append(')');\n }\n }\n\n public void walkIn(Operand lvalue, Operand rvalue, boolean positive) {\n if (!positive) {\n filter.append(\"(!\");\n }\n filter.append(\"(|\");\n for (Literal value : (LiteralList) rvalue) {\n walkEq(lvalue, value);\n }\n filter.append(')');\n if (!positive) {\n filter.append(')');\n }\n }\n\n public void walkLike(Operand lvalue, Operand rvalue, boolean positive, boolean caseInsensitive) {\n if (!(rvalue instanceof StringLiteral)) {\n throw new QueryParseException(\"Invalid LIKE, right hand side must be a string: \" + rvalue);\n }\n String like = ((StringLiteral) rvalue).value;\n if (caseInsensitive) {\n like = like.toLowerCase();\n }\n if (!positive) {\n filter.append(\"(!\");\n }\n filter.append('(');\n walkR", "post_mask_code": "\n filter.append('=');\n walkLikeWildcard(like);\n filter.append(')');\n if (!positive) {\n filter.append(')');\n }\n }\n\n /**\n * Turns a NXQL LIKE pattern into an LDAP wildcard.\n *

\n * % and _ are standard wildcards, and \\ escapes them.\n */\n public void walkLikeWildcard(String like) {\n StringBuilder param = new StringBuilder();\n char[] chars = like.toCharArray();\n boolean escape = false;\n for (int i = 0; i < chars.length; i++) {\n char c = chars[i];\n boolean escapeNext = false;\n if (escape) {\n param.append(c);\n } else {\n switch(c) {\n case '%':\n if (param.length() != 0) {\n addFilterParam(param.toString());\n param.setLength(0);\n }\n filter.append('*');\n break;\n case // interpret it as an escaped _, not a wildcard\n '_':\n param.append(c);\n break;\n case '\\\\':\n escapeNext = true;\n break;\n default:\n param.append(c);\n break;\n }\n }\n escape = escapeNext;\n }\n if (escape) {\n throw new QueryParseException(\"Invalid LIKE parameter ending with escape character\");\n }\n if (param.length() != 0) {\n addFilterParam(param.toString());\n }\n }\n\n public void walkOperand(Operand operand) {\n if (operand instanceof Literal) {\n walkLiteral((Literal) operand);\n } else if (operand instanceof Function) {\n walkFunction((Function) operand);\n } else if (operand instanceof Expression) {\n walkExpression((Expression) operand);\n } else if (operand instanceof Reference) {\n walkReference((Reference) operand);\n } else {\n throw new QueryParseException(\"Unknown operand: \" + operand);\n }\n }\n\n public void walkLiteral(Operand operand) {\n if (!(operand instanceof Literal)) {\n throw new QueryParseException(\"Requires literal instead of: \" + operand);\n }\n Literal lit = (Literal) operand;\n if (lit instanceof BooleanLiteral) {\n walkBooleanLiteral((BooleanLiteral) lit);\n } else if (lit instanceof DateLiteral) {\n walkDateLiteral((DateLiteral) lit);\n } else if (lit instanceof DoubleLiteral) {\n walkDoubleLiteral((DoubleLiteral) lit);\n } else if (lit instanceof IntegerLiteral) {\n walkIntegerLiteral((IntegerLiteral) lit);\n } else if (lit instanceof StringLiteral) {\n walkStringLiteral((StringLiteral) lit);\n } else {\n throw new QueryParseException(\"Unknown literal: \" + lit);\n }\n }\n\n public void walkBooleanLiteral(BooleanLiteral lit) {\n addFilterParam(Boolean.valueOf(lit.value));\n }\n\n public void walkDateLiteral(DateLiteral lit) {\n if (lit.onlyDate) {\n throw new QueryParseException(\"Cannot use only date in LDAP query: \" + lit);\n }\n // let LDAP library serialize it\n addFilterParam(lit.toCalendar());\n }\n\n public void walkDoubleLiteral(DoubleLiteral lit) {\n addFilterParam(Double.valueOf(lit.value));\n }\n\n public void walkIntegerLiteral(IntegerLiteral lit) {\n addFilterParam(Long.valueOf(lit.value));\n }\n\n public void walkStringLiteral(StringLiteral lit) {\n addFilterParam(lit.value);\n }\n\n protected void addFilterParam(Serializable value) {\n filter.append('{');\n filter.append(paramIndex++);\n filter.append('}');\n params.add(value);\n }\n\n public Object walkFunction(Function func) {\n throw new QueryParseException(func.name);\n }\n\n public Field walkReference(Operand value) {\n if (!(value instanceof Reference)) {\n throw new QueryParseException(\"Invalid query, left hand side must be a property: \" + value);\n }\n String name = ((Reference) value).name;\n if (directory.isReference(name)) {\n throw new QueryParseException(\"Column: \" + name + \" is a reference and cannot be queried for directory: \" + directory.getName());\n }\n Field field = directory.getSchemaFieldMap().get(name);\n if (field == null) {\n throw new QueryParseException(\"No column: \" + name + \" for directory: \" + directory.getName());\n }\n String backend = directory.getFieldMapper().getBackendField(name);\n filter.append(backend);\n return field;\n }\n}\n"} {"task_id": "Java_2469", "language": "Java", "task_type": "method_signature", "source_file": "java/github/CS-SI/Orekit/src/main/java/org/orekit/time/OffsetModel.java", "mask_start_position": 2350, "mask_end_position": 2375, "canonical_solution": "public double getSlope() ", "pre_mask_code": "package org.orekit.time;\n\n/**\n * TAI UTC offset model.\n * @see UTCTAIOffsetsLoader\n * @author Luc Maisonobe\n * @since 7.1\n */\npublic class OffsetModel {\n\n /**\n * Date of the offset start.\n */\n private final DateComponents start;\n\n /**\n * Reference date of the linear model as a modified julian day.\n */\n private final int mjdRef;\n\n /**\n * Offset at reference date in seconds (TAI minus UTC).\n */\n private final double offset;\n\n /**\n * Offset slope in seconds per UTC day (TAI minus UTC / dUTC).\n */\n private final double slope;\n\n /**\n * Constructor for a linear offset model.\n *

\n * These models were used prior to 1972.\n *

\n * @param start date of the offset start\n * @param mjdRef reference date of the linear model as a modified julian day\n * @param offset offset at reference date in seconds (TAI minus UTC)\n * @param slope offset slope in seconds per UTC day (TAI minus UTC / dUTC)\n */\n public OffsetModel(final DateComponents start, final int mjdRef, final double offset, final double slope) {\n this.start = start;\n this.mjdRef = mjdRef;\n this.offset = offset;\n this.slope = slope;\n }\n\n /**\n * Constructor for a constant offset model.\n *

\n * These models are used since 1972.\n *

\n * @param start date of the offset start\n * @param offset offset at reference date in seconds (TAI minus UTC)\n */\n public OffsetModel(final DateComponents start, final int offset) {\n this(start, 41317, offset, 0.0);\n }\n\n /**\n * Get the date of the offset start.\n * @return date of the offset start\n */\n public DateComponents getStart() {\n return start;\n }\n\n /**\n * Get the reference date of the linear model as a modified julian day.\n * @return reference date of the linear model as a modified julian day\n */\n public int getMJDRef() {\n return mjdRef;\n }\n\n /**\n * Offset at reference date in seconds (TAI minus UTC).\n * @return offset at reference date in seconds (TAI minus UTC)\n */\n public double getOffset() {\n return offset;\n }\n\n /**\n * Offset slope in seconds per UTC day (TAI minus UTC / dUTC).\n * @return offset slope in seconds per UTC day (TAI minus UTC / dUTC)\n */\n ", "post_mask_code": "{\n return slope;\n }\n}\n"} {"task_id": "Java_2470", "language": "Java", "task_type": "method_body", "source_file": "java/github/CS-SI/Orekit/src/main/java/org/orekit/time/OffsetModel.java", "mask_start_position": 1727, "mask_end_position": 1756, "canonical_solution": "{\n return start;\n }", "pre_mask_code": "package org.orekit.time;\n\n/**\n * TAI UTC offset model.\n * @see UTCTAIOffsetsLoader\n * @author Luc Maisonobe\n * @since 7.1\n */\npublic class OffsetModel {\n\n /**\n * Date of the offset start.\n */\n private final DateComponents start;\n\n /**\n * Reference date of the linear model as a modified julian day.\n */\n private final int mjdRef;\n\n /**\n * Offset at reference date in seconds (TAI minus UTC).\n */\n private final double offset;\n\n /**\n * Offset slope in seconds per UTC day (TAI minus UTC / dUTC).\n */\n private final double slope;\n\n /**\n * Constructor for a linear offset model.\n *

\n * These models were used prior to 1972.\n *

\n * @param start date of the offset start\n * @param mjdRef reference date of the linear model as a modified julian day\n * @param offset offset at reference date in seconds (TAI minus UTC)\n * @param slope offset slope in seconds per UTC day (TAI minus UTC / dUTC)\n */\n public OffsetModel(final DateComponents start, final int mjdRef, final double offset, final double slope) {\n this.start = start;\n this.mjdRef = mjdRef;\n this.offset = offset;\n this.slope = slope;\n }\n\n /**\n * Constructor for a constant offset model.\n *

\n * These models are used since 1972.\n *

\n * @param start date of the offset start\n * @param offset offset at reference date in seconds (TAI minus UTC)\n */\n public OffsetModel(final DateComponents start, final int offset) {\n this(start, 41317, offset, 0.0);\n }\n\n /**\n * Get the date of the offset start.\n * @return date of the offset start\n */\n public DateComponents getStart() ", "post_mask_code": "\n\n /**\n * Get the reference date of the linear model as a modified julian day.\n * @return reference date of the linear model as a modified julian day\n */\n public int getMJDRef() {\n return mjdRef;\n }\n\n /**\n * Offset at reference date in seconds (TAI minus UTC).\n * @return offset at reference date in seconds (TAI minus UTC)\n */\n public double getOffset() {\n return offset;\n }\n\n /**\n * Offset slope in seconds per UTC day (TAI minus UTC / dUTC).\n * @return offset slope in seconds per UTC day (TAI minus UTC / dUTC)\n */\n public double getSlope() {\n return slope;\n }\n}\n"} {"task_id": "Java_2471", "language": "Java", "task_type": "single_line", "source_file": "java/github/CS-SI/Orekit/src/main/java/org/orekit/time/OffsetModel.java", "mask_start_position": 1965, "mask_end_position": 1976, "canonical_solution": "urn mjdRef;", "pre_mask_code": "package org.orekit.time;\n\n/**\n * TAI UTC offset model.\n * @see UTCTAIOffsetsLoader\n * @author Luc Maisonobe\n * @since 7.1\n */\npublic class OffsetModel {\n\n /**\n * Date of the offset start.\n */\n private final DateComponents start;\n\n /**\n * Reference date of the linear model as a modified julian day.\n */\n private final int mjdRef;\n\n /**\n * Offset at reference date in seconds (TAI minus UTC).\n */\n private final double offset;\n\n /**\n * Offset slope in seconds per UTC day (TAI minus UTC / dUTC).\n */\n private final double slope;\n\n /**\n * Constructor for a linear offset model.\n *

\n * These models were used prior to 1972.\n *

\n * @param start date of the offset start\n * @param mjdRef reference date of the linear model as a modified julian day\n * @param offset offset at reference date in seconds (TAI minus UTC)\n * @param slope offset slope in seconds per UTC day (TAI minus UTC / dUTC)\n */\n public OffsetModel(final DateComponents start, final int mjdRef, final double offset, final double slope) {\n this.start = start;\n this.mjdRef = mjdRef;\n this.offset = offset;\n this.slope = slope;\n }\n\n /**\n * Constructor for a constant offset model.\n *

\n * These models are used since 1972.\n *

\n * @param start date of the offset start\n * @param offset offset at reference date in seconds (TAI minus UTC)\n */\n public OffsetModel(final DateComponents start, final int offset) {\n this(start, 41317, offset, 0.0);\n }\n\n /**\n * Get the date of the offset start.\n * @return date of the offset start\n */\n public DateComponents getStart() {\n return start;\n }\n\n /**\n * Get the reference date of the linear model as a modified julian day.\n * @return reference date of the linear model as a modified julian day\n */\n public int getMJDRef() {\n ret", "post_mask_code": "\n }\n\n /**\n * Offset at reference date in seconds (TAI minus UTC).\n * @return offset at reference date in seconds (TAI minus UTC)\n */\n public double getOffset() {\n return offset;\n }\n\n /**\n * Offset slope in seconds per UTC day (TAI minus UTC / dUTC).\n * @return offset slope in seconds per UTC day (TAI minus UTC / dUTC)\n */\n public double getSlope() {\n return slope;\n }\n}\n"} {"task_id": "Java_2472", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/CS-SI/Orekit/src/main/java/org/orekit/time/OffsetModel.java", "mask_start_position": 1929, "mask_end_position": 1982, "canonical_solution": "public int getMJDRef() {\n return mjdRef;\n }", "pre_mask_code": "package org.orekit.time;\n\n/**\n * TAI UTC offset model.\n * @see UTCTAIOffsetsLoader\n * @author Luc Maisonobe\n * @since 7.1\n */\npublic class OffsetModel {\n\n /**\n * Date of the offset start.\n */\n private final DateComponents start;\n\n /**\n * Reference date of the linear model as a modified julian day.\n */\n private final int mjdRef;\n\n /**\n * Offset at reference date in seconds (TAI minus UTC).\n */\n private final double offset;\n\n /**\n * Offset slope in seconds per UTC day (TAI minus UTC / dUTC).\n */\n private final double slope;\n\n /**\n * Constructor for a linear offset model.\n *

\n * These models were used prior to 1972.\n *

\n * @param start date of the offset start\n * @param mjdRef reference date of the linear model as a modified julian day\n * @param offset offset at reference date in seconds (TAI minus UTC)\n * @param slope offset slope in seconds per UTC day (TAI minus UTC / dUTC)\n */\n public OffsetModel(final DateComponents start, final int mjdRef, final double offset, final double slope) {\n this.start = start;\n this.mjdRef = mjdRef;\n this.offset = offset;\n this.slope = slope;\n }\n\n /**\n * Constructor for a constant offset model.\n *

\n * These models are used since 1972.\n *

\n * @param start date of the offset start\n * @param offset offset at reference date in seconds (TAI minus UTC)\n */\n public OffsetModel(final DateComponents start, final int offset) {\n this(start, 41317, offset, 0.0);\n }\n\n /**\n * Get the date of the offset start.\n * @return date of the offset start\n */\n public DateComponents getStart() {\n return start;\n }\n\n /**\n * Get the reference date of the linear model as a modified julian day.\n * @return reference date of the linear model as a modified julian day\n */\n ", "post_mask_code": "\n\n /**\n * Offset at reference date in seconds (TAI minus UTC).\n * @return offset at reference date in seconds (TAI minus UTC)\n */\n public double getOffset() {\n return offset;\n }\n\n /**\n * Offset slope in seconds per UTC day (TAI minus UTC / dUTC).\n * @return offset slope in seconds per UTC day (TAI minus UTC / dUTC)\n */\n public double getSlope() {\n return slope;\n }\n}\n"} {"task_id": "Java_2473", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/huawei/servicehost/normal/IIPEvent4Result.java", "mask_start_position": 1366, "mask_end_position": 1463, "canonical_solution": "public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException ", "pre_mask_code": "package com.huawei.servicehost.normal;\n\nimport android.os.Binder;\nimport android.os.IBinder;\nimport android.os.IInterface;\nimport android.os.Parcel;\nimport android.os.RemoteException;\n\npublic interface IIPEvent4Result extends IInterface {\n\n public static abstract class Stub extends Binder implements IIPEvent4Result {\n\n private static final String DESCRIPTOR = \"com.huawei.servicehost.normal.IIPEvent4Result\";\n\n private static class Proxy implements IIPEvent4Result {\n\n private IBinder mRemote;\n\n Proxy(IBinder remote) {\n this.mRemote = remote;\n }\n\n public IBinder asBinder() {\n return this.mRemote;\n }\n\n public String getInterfaceDescriptor() {\n return Stub.DESCRIPTOR;\n }\n }\n\n public Stub() {\n attachInterface(this, DESCRIPTOR);\n }\n\n public static IIPEvent4Result asInterface(IBinder obj) {\n if (obj == null) {\n return null;\n }\n IInterface iin = obj.queryLocalInterface(DESCRIPTOR);\n if (iin == null || !(iin instanceof IIPEvent4Result)) {\n return new Proxy(obj);\n }\n return (IIPEvent4Result) iin;\n }\n\n public IBinder asBinder() {\n return this;\n }\n\n ", "post_mask_code": "{\n String descriptor = DESCRIPTOR;\n if (code != 1598968902) {\n return super.onTransact(code, data, reply, flags);\n }\n reply.writeString(descriptor);\n return true;\n }\n }\n}\n"} {"task_id": "Java_2474", "language": "Java", "task_type": "method_body", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/huawei/servicehost/normal/IIPEvent4Result.java", "mask_start_position": 653, "mask_end_position": 705, "canonical_solution": "{\n return this.mRemote;\n }", "pre_mask_code": "package com.huawei.servicehost.normal;\n\nimport android.os.Binder;\nimport android.os.IBinder;\nimport android.os.IInterface;\nimport android.os.Parcel;\nimport android.os.RemoteException;\n\npublic interface IIPEvent4Result extends IInterface {\n\n public static abstract class Stub extends Binder implements IIPEvent4Result {\n\n private static final String DESCRIPTOR = \"com.huawei.servicehost.normal.IIPEvent4Result\";\n\n private static class Proxy implements IIPEvent4Result {\n\n private IBinder mRemote;\n\n Proxy(IBinder remote) {\n this.mRemote = remote;\n }\n\n public IBinder asBinder() ", "post_mask_code": "\n\n public String getInterfaceDescriptor() {\n return Stub.DESCRIPTOR;\n }\n }\n\n public Stub() {\n attachInterface(this, DESCRIPTOR);\n }\n\n public static IIPEvent4Result asInterface(IBinder obj) {\n if (obj == null) {\n return null;\n }\n IInterface iin = obj.queryLocalInterface(DESCRIPTOR);\n if (iin == null || !(iin instanceof IIPEvent4Result)) {\n return new Proxy(obj);\n }\n return (IIPEvent4Result) iin;\n }\n\n public IBinder asBinder() {\n return this;\n }\n\n public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {\n String descriptor = DESCRIPTOR;\n if (code != 1598968902) {\n return super.onTransact(code, data, reply, flags);\n }\n reply.writeString(descriptor);\n return true;\n }\n }\n}\n"} {"task_id": "Java_2475", "language": "Java", "task_type": "single_line", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/huawei/servicehost/normal/IIPEvent4Result.java", "mask_start_position": 677, "mask_end_position": 691, "canonical_solution": " this.mRemote;", "pre_mask_code": "package com.huawei.servicehost.normal;\n\nimport android.os.Binder;\nimport android.os.IBinder;\nimport android.os.IInterface;\nimport android.os.Parcel;\nimport android.os.RemoteException;\n\npublic interface IIPEvent4Result extends IInterface {\n\n public static abstract class Stub extends Binder implements IIPEvent4Result {\n\n private static final String DESCRIPTOR = \"com.huawei.servicehost.normal.IIPEvent4Result\";\n\n private static class Proxy implements IIPEvent4Result {\n\n private IBinder mRemote;\n\n Proxy(IBinder remote) {\n this.mRemote = remote;\n }\n\n public IBinder asBinder() {\n return", "post_mask_code": "\n }\n\n public String getInterfaceDescriptor() {\n return Stub.DESCRIPTOR;\n }\n }\n\n public Stub() {\n attachInterface(this, DESCRIPTOR);\n }\n\n public static IIPEvent4Result asInterface(IBinder obj) {\n if (obj == null) {\n return null;\n }\n IInterface iin = obj.queryLocalInterface(DESCRIPTOR);\n if (iin == null || !(iin instanceof IIPEvent4Result)) {\n return new Proxy(obj);\n }\n return (IIPEvent4Result) iin;\n }\n\n public IBinder asBinder() {\n return this;\n }\n\n public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {\n String descriptor = DESCRIPTOR;\n if (code != 1598968902) {\n return super.onTransact(code, data, reply, flags);\n }\n reply.writeString(descriptor);\n return true;\n }\n }\n}\n"} {"task_id": "Java_2476", "language": "Java", "task_type": "method_signature", "source_file": "java/github/zhengxiaopeng/Rocko-Android-Demos/webview-with-viewpager/src/main/java/com/rocko/wwv/widget/HorizontalSlideWebView.java", "mask_start_position": 2306, "mask_end_position": 2377, "canonical_solution": "public void setTopContentHeightPercent(float mTopContentHeightPercent) ", "pre_mask_code": "package com.rocko.wwv.widget;\n\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport android.view.ViewTreeObserver;\nimport android.webkit.WebView;\nimport com.rocko.wwv.R;\n\n/**\n * 在水平方向上有滑动事件的 WebView,目前只支持一处有 slide。\n *\n * @author: Rocko\n * @date 2015-09-29\n */\npublic class HorizontalSlideWebView extends WebView {\n\n private static final String TAG = HorizontalSlideWebView.class.getSimpleName();\n\n private float mHeight;\n\n private float mTopContentHeightPercent = 0.00f;\n\n private float mGalleryHeightPercent = 0.30f;\n\n private float mSlideGalleryHeight;\n\n /**\n * 滑动区域顶部内容所占页面高度,没有则为 0\n */\n private float mTopContentHeight;\n\n private float currentVisiableGalleryHeight;\n\n public HorizontalSlideWebView(Context context) {\n this(context, null);\n }\n\n public HorizontalSlideWebView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.HorizontalSlideWebView);\n mGalleryHeightPercent = typedArray.getFloat(R.styleable.HorizontalSlideWebView_slide_content_height_percent, mGalleryHeightPercent);\n mTopContentHeightPercent = typedArray.getFloat(R.styleable.HorizontalSlideWebView_top_content_height_percent, mTopContentHeightPercent);\n typedArray.recycle();\n getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {\n\n @Override\n public void onGlobalLayout() {\n // First\n getViewTreeObserver().removeGlobalOnLayoutListener(this);\n mHeight = getHeight();\n mSlideGalleryHeight = mHeight * mGalleryHeightPercent;\n mTopContentHeight = mHeight * mTopContentHeightPercent;\n currentVisiableGalleryHeight = mSlideGalleryHeight;\n Log.d(TAG, \"mSlideGalleryHeight: \" + mSlideGalleryHeight + \" mTopContentHeight; \" + mTopContentHeight + \" currentVisiableGalleryHeight: \" + currentVisiableGalleryHeight);\n }\n });\n }\n\n /**\n * 设置滑动区域顶部内容所占页面高度百分比,没有则为 0\n */\n ", "post_mask_code": "{\n this.mTopContentHeightPercent = mTopContentHeightPercent;\n this.mTopContentHeight = mHeight * mTopContentHeightPercent;\n }\n\n public void setSlideGalleryHeightPercent(float mGalleryHeightPercent) {\n this.mGalleryHeightPercent = mGalleryHeightPercent;\n this.mTopContentHeight = mHeight * mGalleryHeightPercent;\n }\n\n /**\n * 设置滑动区域顶部内容所占页面高度,没有则为 0\n */\n public void setTopContentHeight(float mTopContentHeight) {\n this.mTopContentHeight = mTopContentHeight;\n }\n\n public void setSlideGalleryHeight(float mSlideGalleryHeight) {\n this.mSlideGalleryHeight = mSlideGalleryHeight;\n }\n\n @Override\n public boolean canScrollHorizontally(int direction) {\n int verticalScrollOffset = computeVerticalScrollOffset();\n if (verticalScrollOffset < mTopContentHeight) {\n // TopContent 还未完全偏移出去\n Log.i(TAG, \"TopContent 可见\");\n return (direction > mTopContentHeight - verticalScrollOffset) && (direction < mSlideGalleryHeight + verticalScrollOffset);\n } else {\n // TopContent 已经偏移出去,包括 mTopContentHeight为 0\n Log.i(TAG, \"TopContent 不可见\");\n if (verticalScrollOffset < mSlideGalleryHeight + mTopContentHeight) {\n // GalleryContent 可见\n Log.i(TAG, \"GalleryContent 可见\");\n currentVisiableGalleryHeight = mSlideGalleryHeight - (verticalScrollOffset - mTopContentHeight);\n } else {\n // GalleryContent 已经不可见\n Log.i(TAG, \"GalleryContent 不可见\");\n // 重置\n currentVisiableGalleryHeight = mSlideGalleryHeight;\n }\n return (verticalScrollOffset < mSlideGalleryHeight + mTopContentHeight) && direction < currentVisiableGalleryHeight;\n }\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n super.onTouchEvent(event);\n return true;\n }\n}\n"} {"task_id": "Java_2477", "language": "Java", "task_type": "method_body", "source_file": "java/github/zhengxiaopeng/Rocko-Android-Demos/webview-with-viewpager/src/main/java/com/rocko/wwv/widget/HorizontalSlideWebView.java", "mask_start_position": 2838, "mask_end_position": 2897, "canonical_solution": "{\n this.mTopContentHeight = mTopContentHeight;\n }", "pre_mask_code": "package com.rocko.wwv.widget;\n\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport android.view.ViewTreeObserver;\nimport android.webkit.WebView;\nimport com.rocko.wwv.R;\n\n/**\n * 在水平方向上有滑动事件的 WebView,目前只支持一处有 slide。\n *\n * @author: Rocko\n * @date 2015-09-29\n */\npublic class HorizontalSlideWebView extends WebView {\n\n private static final String TAG = HorizontalSlideWebView.class.getSimpleName();\n\n private float mHeight;\n\n private float mTopContentHeightPercent = 0.00f;\n\n private float mGalleryHeightPercent = 0.30f;\n\n private float mSlideGalleryHeight;\n\n /**\n * 滑动区域顶部内容所占页面高度,没有则为 0\n */\n private float mTopContentHeight;\n\n private float currentVisiableGalleryHeight;\n\n public HorizontalSlideWebView(Context context) {\n this(context, null);\n }\n\n public HorizontalSlideWebView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.HorizontalSlideWebView);\n mGalleryHeightPercent = typedArray.getFloat(R.styleable.HorizontalSlideWebView_slide_content_height_percent, mGalleryHeightPercent);\n mTopContentHeightPercent = typedArray.getFloat(R.styleable.HorizontalSlideWebView_top_content_height_percent, mTopContentHeightPercent);\n typedArray.recycle();\n getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {\n\n @Override\n public void onGlobalLayout() {\n // First\n getViewTreeObserver().removeGlobalOnLayoutListener(this);\n mHeight = getHeight();\n mSlideGalleryHeight = mHeight * mGalleryHeightPercent;\n mTopContentHeight = mHeight * mTopContentHeightPercent;\n currentVisiableGalleryHeight = mSlideGalleryHeight;\n Log.d(TAG, \"mSlideGalleryHeight: \" + mSlideGalleryHeight + \" mTopContentHeight; \" + mTopContentHeight + \" currentVisiableGalleryHeight: \" + currentVisiableGalleryHeight);\n }\n });\n }\n\n /**\n * 设置滑动区域顶部内容所占页面高度百分比,没有则为 0\n */\n public void setTopContentHeightPercent(float mTopContentHeightPercent) {\n this.mTopContentHeightPercent = mTopContentHeightPercent;\n this.mTopContentHeight = mHeight * mTopContentHeightPercent;\n }\n\n public void setSlideGalleryHeightPercent(float mGalleryHeightPercent) {\n this.mGalleryHeightPercent = mGalleryHeightPercent;\n this.mTopContentHeight = mHeight * mGalleryHeightPercent;\n }\n\n /**\n * 设置滑动区域顶部内容所占页面高度,没有则为 0\n */\n public void setTopContentHeight(float mTopContentHeight) ", "post_mask_code": "\n\n public void setSlideGalleryHeight(float mSlideGalleryHeight) {\n this.mSlideGalleryHeight = mSlideGalleryHeight;\n }\n\n @Override\n public boolean canScrollHorizontally(int direction) {\n int verticalScrollOffset = computeVerticalScrollOffset();\n if (verticalScrollOffset < mTopContentHeight) {\n // TopContent 还未完全偏移出去\n Log.i(TAG, \"TopContent 可见\");\n return (direction > mTopContentHeight - verticalScrollOffset) && (direction < mSlideGalleryHeight + verticalScrollOffset);\n } else {\n // TopContent 已经偏移出去,包括 mTopContentHeight为 0\n Log.i(TAG, \"TopContent 不可见\");\n if (verticalScrollOffset < mSlideGalleryHeight + mTopContentHeight) {\n // GalleryContent 可见\n Log.i(TAG, \"GalleryContent 可见\");\n currentVisiableGalleryHeight = mSlideGalleryHeight - (verticalScrollOffset - mTopContentHeight);\n } else {\n // GalleryContent 已经不可见\n Log.i(TAG, \"GalleryContent 不可见\");\n // 重置\n currentVisiableGalleryHeight = mSlideGalleryHeight;\n }\n return (verticalScrollOffset < mSlideGalleryHeight + mTopContentHeight) && direction < currentVisiableGalleryHeight;\n }\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n super.onTouchEvent(event);\n return true;\n }\n}\n"} {"task_id": "Java_2478", "language": "Java", "task_type": "single_line", "source_file": "java/github/zhengxiaopeng/Rocko-Android-Demos/webview-with-viewpager/src/main/java/com/rocko/wwv/widget/HorizontalSlideWebView.java", "mask_start_position": 1960, "mask_end_position": 1963, "canonical_solution": "nt;", "pre_mask_code": "package com.rocko.wwv.widget;\n\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport android.view.ViewTreeObserver;\nimport android.webkit.WebView;\nimport com.rocko.wwv.R;\n\n/**\n * 在水平方向上有滑动事件的 WebView,目前只支持一处有 slide。\n *\n * @author: Rocko\n * @date 2015-09-29\n */\npublic class HorizontalSlideWebView extends WebView {\n\n private static final String TAG = HorizontalSlideWebView.class.getSimpleName();\n\n private float mHeight;\n\n private float mTopContentHeightPercent = 0.00f;\n\n private float mGalleryHeightPercent = 0.30f;\n\n private float mSlideGalleryHeight;\n\n /**\n * 滑动区域顶部内容所占页面高度,没有则为 0\n */\n private float mTopContentHeight;\n\n private float currentVisiableGalleryHeight;\n\n public HorizontalSlideWebView(Context context) {\n this(context, null);\n }\n\n public HorizontalSlideWebView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.HorizontalSlideWebView);\n mGalleryHeightPercent = typedArray.getFloat(R.styleable.HorizontalSlideWebView_slide_content_height_percent, mGalleryHeightPercent);\n mTopContentHeightPercent = typedArray.getFloat(R.styleable.HorizontalSlideWebView_top_content_height_percent, mTopContentHeightPercent);\n typedArray.recycle();\n getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {\n\n @Override\n public void onGlobalLayout() {\n // First\n getViewTreeObserver().removeGlobalOnLayoutListener(this);\n mHeight = getHeight();\n mSlideGalleryHeight = mHeight * mGalleryHeightPercent;\n mTopContentHeight = mHeight * mTopContentHeightPerce", "post_mask_code": "\n currentVisiableGalleryHeight = mSlideGalleryHeight;\n Log.d(TAG, \"mSlideGalleryHeight: \" + mSlideGalleryHeight + \" mTopContentHeight; \" + mTopContentHeight + \" currentVisiableGalleryHeight: \" + currentVisiableGalleryHeight);\n }\n });\n }\n\n /**\n * 设置滑动区域顶部内容所占页面高度百分比,没有则为 0\n */\n public void setTopContentHeightPercent(float mTopContentHeightPercent) {\n this.mTopContentHeightPercent = mTopContentHeightPercent;\n this.mTopContentHeight = mHeight * mTopContentHeightPercent;\n }\n\n public void setSlideGalleryHeightPercent(float mGalleryHeightPercent) {\n this.mGalleryHeightPercent = mGalleryHeightPercent;\n this.mTopContentHeight = mHeight * mGalleryHeightPercent;\n }\n\n /**\n * 设置滑动区域顶部内容所占页面高度,没有则为 0\n */\n public void setTopContentHeight(float mTopContentHeight) {\n this.mTopContentHeight = mTopContentHeight;\n }\n\n public void setSlideGalleryHeight(float mSlideGalleryHeight) {\n this.mSlideGalleryHeight = mSlideGalleryHeight;\n }\n\n @Override\n public boolean canScrollHorizontally(int direction) {\n int verticalScrollOffset = computeVerticalScrollOffset();\n if (verticalScrollOffset < mTopContentHeight) {\n // TopContent 还未完全偏移出去\n Log.i(TAG, \"TopContent 可见\");\n return (direction > mTopContentHeight - verticalScrollOffset) && (direction < mSlideGalleryHeight + verticalScrollOffset);\n } else {\n // TopContent 已经偏移出去,包括 mTopContentHeight为 0\n Log.i(TAG, \"TopContent 不可见\");\n if (verticalScrollOffset < mSlideGalleryHeight + mTopContentHeight) {\n // GalleryContent 可见\n Log.i(TAG, \"GalleryContent 可见\");\n currentVisiableGalleryHeight = mSlideGalleryHeight - (verticalScrollOffset - mTopContentHeight);\n } else {\n // GalleryContent 已经不可见\n Log.i(TAG, \"GalleryContent 不可见\");\n // 重置\n currentVisiableGalleryHeight = mSlideGalleryHeight;\n }\n return (verticalScrollOffset < mSlideGalleryHeight + mTopContentHeight) && direction < currentVisiableGalleryHeight;\n }\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n super.onTouchEvent(event);\n return true;\n }\n}\n"} {"task_id": "Java_2479", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/zhengxiaopeng/Rocko-Android-Demos/webview-with-viewpager/src/main/java/com/rocko/wwv/widget/HorizontalSlideWebView.java", "mask_start_position": 2781, "mask_end_position": 2897, "canonical_solution": "public void setTopContentHeight(float mTopContentHeight) {\n this.mTopContentHeight = mTopContentHeight;\n }", "pre_mask_code": "package com.rocko.wwv.widget;\n\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport android.view.ViewTreeObserver;\nimport android.webkit.WebView;\nimport com.rocko.wwv.R;\n\n/**\n * 在水平方向上有滑动事件的 WebView,目前只支持一处有 slide。\n *\n * @author: Rocko\n * @date 2015-09-29\n */\npublic class HorizontalSlideWebView extends WebView {\n\n private static final String TAG = HorizontalSlideWebView.class.getSimpleName();\n\n private float mHeight;\n\n private float mTopContentHeightPercent = 0.00f;\n\n private float mGalleryHeightPercent = 0.30f;\n\n private float mSlideGalleryHeight;\n\n /**\n * 滑动区域顶部内容所占页面高度,没有则为 0\n */\n private float mTopContentHeight;\n\n private float currentVisiableGalleryHeight;\n\n public HorizontalSlideWebView(Context context) {\n this(context, null);\n }\n\n public HorizontalSlideWebView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.HorizontalSlideWebView);\n mGalleryHeightPercent = typedArray.getFloat(R.styleable.HorizontalSlideWebView_slide_content_height_percent, mGalleryHeightPercent);\n mTopContentHeightPercent = typedArray.getFloat(R.styleable.HorizontalSlideWebView_top_content_height_percent, mTopContentHeightPercent);\n typedArray.recycle();\n getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {\n\n @Override\n public void onGlobalLayout() {\n // First\n getViewTreeObserver().removeGlobalOnLayoutListener(this);\n mHeight = getHeight();\n mSlideGalleryHeight = mHeight * mGalleryHeightPercent;\n mTopContentHeight = mHeight * mTopContentHeightPercent;\n currentVisiableGalleryHeight = mSlideGalleryHeight;\n Log.d(TAG, \"mSlideGalleryHeight: \" + mSlideGalleryHeight + \" mTopContentHeight; \" + mTopContentHeight + \" currentVisiableGalleryHeight: \" + currentVisiableGalleryHeight);\n }\n });\n }\n\n /**\n * 设置滑动区域顶部内容所占页面高度百分比,没有则为 0\n */\n public void setTopContentHeightPercent(float mTopContentHeightPercent) {\n this.mTopContentHeightPercent = mTopContentHeightPercent;\n this.mTopContentHeight = mHeight * mTopContentHeightPercent;\n }\n\n public void setSlideGalleryHeightPercent(float mGalleryHeightPercent) {\n this.mGalleryHeightPercent = mGalleryHeightPercent;\n this.mTopContentHeight = mHeight * mGalleryHeightPercent;\n }\n\n /**\n * 设置滑动区域顶部内容所占页面高度,没有则为 0\n */\n ", "post_mask_code": "\n\n public void setSlideGalleryHeight(float mSlideGalleryHeight) {\n this.mSlideGalleryHeight = mSlideGalleryHeight;\n }\n\n @Override\n public boolean canScrollHorizontally(int direction) {\n int verticalScrollOffset = computeVerticalScrollOffset();\n if (verticalScrollOffset < mTopContentHeight) {\n // TopContent 还未完全偏移出去\n Log.i(TAG, \"TopContent 可见\");\n return (direction > mTopContentHeight - verticalScrollOffset) && (direction < mSlideGalleryHeight + verticalScrollOffset);\n } else {\n // TopContent 已经偏移出去,包括 mTopContentHeight为 0\n Log.i(TAG, \"TopContent 不可见\");\n if (verticalScrollOffset < mSlideGalleryHeight + mTopContentHeight) {\n // GalleryContent 可见\n Log.i(TAG, \"GalleryContent 可见\");\n currentVisiableGalleryHeight = mSlideGalleryHeight - (verticalScrollOffset - mTopContentHeight);\n } else {\n // GalleryContent 已经不可见\n Log.i(TAG, \"GalleryContent 不可见\");\n // 重置\n currentVisiableGalleryHeight = mSlideGalleryHeight;\n }\n return (verticalScrollOffset < mSlideGalleryHeight + mTopContentHeight) && direction < currentVisiableGalleryHeight;\n }\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n super.onTouchEvent(event);\n return true;\n }\n}\n"} {"task_id": "Java_2480", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ControlSystemStudio/cs-studio/applications/alarm/alarm-plugins/org.csstudio.alarm.beast.ui/src/org/csstudio/alarm/beast/ui/actions/EditGDCItemDialog.java", "mask_start_position": 784, "mask_end_position": 830, "canonical_solution": "@Override\n protected boolean isResizable() ", "pre_mask_code": "package org.csstudio.alarm.beast.ui.actions;\n\nimport org.csstudio.alarm.beast.ui.Messages;\nimport org.csstudio.ui.util.swt.stringtable.RowEditDialog;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Control;\nimport org.eclipse.swt.widgets.Label;\nimport org.eclipse.swt.widgets.Shell;\nimport org.eclipse.swt.widgets.Text;\n\n/**\n * Dialog that allows users to edit the title and details of a\n * guidance/display/command item.\n *\n * @author Xihui Chen\n */\npublic class EditGDCItemDialog extends RowEditDialog {\n\n private Text titleText, detailsText;\n\n protected EditGDCItemDialog(final Shell parentShell) {\n super(parentShell);\n }\n\n ", "post_mask_code": "{\n return true;\n }\n\n @Override\n protected Control createDialogArea(final Composite parent) {\n final Composite parent_composite = (Composite) super.createDialogArea(parent);\n final Composite composite = new Composite(parent_composite, SWT.NONE);\n composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n composite.setLayout(new GridLayout(2, false));\n GridData gd;\n final Label titleLable = new Label(composite, 0);\n titleLable.setText(Messages.EditGDCItemDialog_Title);\n titleLable.setLayoutData(new GridData());\n titleText = new Text(composite, SWT.BORDER | SWT.SINGLE);\n titleText.setText(rowData[0]);\n gd = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);\n titleText.setLayoutData(gd);\n final Label detailsLable = new Label(composite, SWT.NONE);\n detailsLable.setText(Messages.EditGDCItemDialog_Detail);\n detailsLable.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));\n detailsText = new Text(composite, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);\n gd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);\n gd.widthHint = 300;\n gd.heightHint = 100;\n detailsText.setLayoutData(gd);\n detailsText.setText(rowData[1]);\n return parent_composite;\n }\n\n @SuppressWarnings(\"nls\")\n @Override\n protected void okPressed() {\n rowData[0] = titleText == null ? \"\" : titleText.getText().trim();\n rowData[1] = detailsText == null ? \"\" : detailsText.getText().trim();\n super.okPressed();\n }\n}\n"} {"task_id": "Java_2481", "language": "Java", "task_type": "method_body", "source_file": "java/github/ControlSystemStudio/cs-studio/applications/alarm/alarm-plugins/org.csstudio.alarm.beast.ui/src/org/csstudio/alarm/beast/ui/actions/EditGDCItemDialog.java", "mask_start_position": 2279, "mask_end_position": 2465, "canonical_solution": "{\n rowData[0] = titleText == null ? \"\" : titleText.getText().trim();\n rowData[1] = detailsText == null ? \"\" : detailsText.getText().trim();\n super.okPressed();\n }", "pre_mask_code": "package org.csstudio.alarm.beast.ui.actions;\n\nimport org.csstudio.alarm.beast.ui.Messages;\nimport org.csstudio.ui.util.swt.stringtable.RowEditDialog;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Control;\nimport org.eclipse.swt.widgets.Label;\nimport org.eclipse.swt.widgets.Shell;\nimport org.eclipse.swt.widgets.Text;\n\n/**\n * Dialog that allows users to edit the title and details of a\n * guidance/display/command item.\n *\n * @author Xihui Chen\n */\npublic class EditGDCItemDialog extends RowEditDialog {\n\n private Text titleText, detailsText;\n\n protected EditGDCItemDialog(final Shell parentShell) {\n super(parentShell);\n }\n\n @Override\n protected boolean isResizable() {\n return true;\n }\n\n @Override\n protected Control createDialogArea(final Composite parent) {\n final Composite parent_composite = (Composite) super.createDialogArea(parent);\n final Composite composite = new Composite(parent_composite, SWT.NONE);\n composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n composite.setLayout(new GridLayout(2, false));\n GridData gd;\n final Label titleLable = new Label(composite, 0);\n titleLable.setText(Messages.EditGDCItemDialog_Title);\n titleLable.setLayoutData(new GridData());\n titleText = new Text(composite, SWT.BORDER | SWT.SINGLE);\n titleText.setText(rowData[0]);\n gd = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);\n titleText.setLayoutData(gd);\n final Label detailsLable = new Label(composite, SWT.NONE);\n detailsLable.setText(Messages.EditGDCItemDialog_Detail);\n detailsLable.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));\n detailsText = new Text(composite, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);\n gd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);\n gd.widthHint = 300;\n gd.heightHint = 100;\n detailsText.setLayoutData(gd);\n detailsText.setText(rowData[1]);\n return parent_composite;\n }\n\n @SuppressWarnings(\"nls\")\n @Override\n protected void okPressed() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2482", "language": "Java", "task_type": "single_line", "source_file": "java/github/ControlSystemStudio/cs-studio/applications/alarm/alarm-plugins/org.csstudio.alarm.beast.ui/src/org/csstudio/alarm/beast/ui/actions/EditGDCItemDialog.java", "mask_start_position": 2136, "mask_end_position": 2164, "canonical_solution": "ilsText.setText(rowData[1]);", "pre_mask_code": "package org.csstudio.alarm.beast.ui.actions;\n\nimport org.csstudio.alarm.beast.ui.Messages;\nimport org.csstudio.ui.util.swt.stringtable.RowEditDialog;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Control;\nimport org.eclipse.swt.widgets.Label;\nimport org.eclipse.swt.widgets.Shell;\nimport org.eclipse.swt.widgets.Text;\n\n/**\n * Dialog that allows users to edit the title and details of a\n * guidance/display/command item.\n *\n * @author Xihui Chen\n */\npublic class EditGDCItemDialog extends RowEditDialog {\n\n private Text titleText, detailsText;\n\n protected EditGDCItemDialog(final Shell parentShell) {\n super(parentShell);\n }\n\n @Override\n protected boolean isResizable() {\n return true;\n }\n\n @Override\n protected Control createDialogArea(final Composite parent) {\n final Composite parent_composite = (Composite) super.createDialogArea(parent);\n final Composite composite = new Composite(parent_composite, SWT.NONE);\n composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n composite.setLayout(new GridLayout(2, false));\n GridData gd;\n final Label titleLable = new Label(composite, 0);\n titleLable.setText(Messages.EditGDCItemDialog_Title);\n titleLable.setLayoutData(new GridData());\n titleText = new Text(composite, SWT.BORDER | SWT.SINGLE);\n titleText.setText(rowData[0]);\n gd = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);\n titleText.setLayoutData(gd);\n final Label detailsLable = new Label(composite, SWT.NONE);\n detailsLable.setText(Messages.EditGDCItemDialog_Detail);\n detailsLable.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));\n detailsText = new Text(composite, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);\n gd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);\n gd.widthHint = 300;\n gd.heightHint = 100;\n detailsText.setLayoutData(gd);\n deta", "post_mask_code": "\n return parent_composite;\n }\n\n @SuppressWarnings(\"nls\")\n @Override\n protected void okPressed() {\n rowData[0] = titleText == null ? \"\" : titleText.getText().trim();\n rowData[1] = detailsText == null ? \"\" : detailsText.getText().trim();\n super.okPressed();\n }\n}\n"} {"task_id": "Java_2483", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/android/internal/telephony/SmsNumberUtils.java", "mask_start_position": 21662, "mask_end_position": 21730, "canonical_solution": "private static boolean compareGid1(Phone phone, String serviceGid1) ", "pre_mask_code": "package com.android.internal.telephony;\n\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.SQLException;\nimport android.os.Binder;\nimport android.os.Build;\nimport android.os.PersistableBundle;\nimport android.telephony.CarrierConfigManager;\nimport android.telephony.PhoneNumberUtils;\nimport android.telephony.Rlog;\nimport android.telephony.TelephonyManager;\nimport android.text.TextUtils;\nimport com.android.internal.telephony.HbpcdLookup.MccIdd;\nimport com.android.internal.telephony.HbpcdLookup.MccLookup;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\n\npublic class SmsNumberUtils {\n\n private static int[] ALL_COUNTRY_CODES = null;\n\n private static final int CDMA_HOME_NETWORK = 1;\n\n private static final int CDMA_ROAMING_NETWORK = 2;\n\n private static final boolean DBG = Build.IS_DEBUGGABLE;\n\n private static final int GSM_UMTS_NETWORK = 0;\n\n private static HashMap> IDDS_MAPS = new HashMap();\n\n private static int MAX_COUNTRY_CODES_LENGTH = 0;\n\n private static final int MIN_COUNTRY_AREA_LOCAL_LENGTH = 10;\n\n private static final int NANP_CC = 1;\n\n private static final String NANP_IDD = \"011\";\n\n private static final int NANP_LONG_LENGTH = 11;\n\n private static final int NANP_MEDIUM_LENGTH = 10;\n\n private static final String NANP_NDD = \"1\";\n\n private static final int NANP_SHORT_LENGTH = 7;\n\n private static final int NP_CC_AREA_LOCAL = 104;\n\n private static final int NP_HOMEIDD_CC_AREA_LOCAL = 101;\n\n private static final int NP_INTERNATIONAL_BEGIN = 100;\n\n private static final int NP_LOCALIDD_CC_AREA_LOCAL = 103;\n\n private static final int NP_NANP_AREA_LOCAL = 2;\n\n private static final int NP_NANP_BEGIN = 1;\n\n private static final int NP_NANP_LOCAL = 1;\n\n private static final int NP_NANP_LOCALIDD_CC_AREA_LOCAL = 5;\n\n private static final int NP_NANP_NBPCD_CC_AREA_LOCAL = 4;\n\n private static final int NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL = 6;\n\n private static final int NP_NANP_NDD_AREA_LOCAL = 3;\n\n private static final int NP_NBPCD_CC_AREA_LOCAL = 102;\n\n private static final int NP_NBPCD_HOMEIDD_CC_AREA_LOCAL = 100;\n\n private static final int NP_NONE = 0;\n\n private static final String PLUS_SIGN = \"+\";\n\n private static final String TAG = \"SmsNumberUtils\";\n\n private static class NumberEntry {\n\n public String IDD;\n\n public int countryCode;\n\n public String number;\n\n public NumberEntry(String number) {\n this.number = number;\n }\n }\n\n private static String formatNumber(Context context, String number, String activeMcc, int networkType) {\n if (number == null) {\n throw new IllegalArgumentException(\"number is null\");\n } else if (activeMcc == null || activeMcc.trim().length() == 0) {\n throw new IllegalArgumentException(\"activeMcc is null or empty!\");\n } else {\n String networkPortionNumber = PhoneNumberUtils.extractNetworkPortion(number);\n if (networkPortionNumber == null || networkPortionNumber.length() == 0) {\n throw new IllegalArgumentException(\"Number is invalid!\");\n }\n StringBuilder stringBuilder;\n NumberEntry numberEntry = new NumberEntry(networkPortionNumber);\n ArrayList allIDDs = getAllIDDs(context, activeMcc);\n int nanpState = checkNANP(numberEntry, allIDDs);\n if (DBG) {\n String str = TAG;\n stringBuilder = new StringBuilder();\n stringBuilder.append(\"NANP type: \");\n stringBuilder.append(getNumberPlanType(nanpState));\n Rlog.d(str, stringBuilder.toString());\n }\n if (nanpState == 1 || nanpState == 2 || nanpState == 3) {\n return networkPortionNumber;\n }\n if (nanpState != 4) {\n int iddLength;\n String str2;\n int i = 0;\n if (nanpState == 5) {\n if (networkType == 1) {\n return networkPortionNumber;\n }\n if (networkType == 0) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n iddLength = i;\n stringBuilder = new StringBuilder();\n stringBuilder.append(PLUS_SIGN);\n stringBuilder.append(networkPortionNumber.substring(iddLength));\n return stringBuilder.toString();\n } else if (networkType == 2) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n return networkPortionNumber.substring(i);\n }\n }\n int internationalState = checkInternationalNumberPlan(context, numberEntry, allIDDs, NANP_IDD);\n if (DBG) {\n str2 = TAG;\n StringBuilder stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\"International type: \");\n stringBuilder2.append(getNumberPlanType(internationalState));\n Rlog.d(str2, stringBuilder2.toString());\n }\n str2 = null;\n switch(internationalState) {\n case 100:\n if (networkType == 0) {\n str2 = networkPortionNumber.substring(1);\n break;\n }\n break;\n case 101:\n str2 = networkPortionNumber;\n break;\n case 102:\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(1));\n str2 = stringBuilder.toString();\n break;\n case NP_LOCALIDD_CC_AREA_LOCAL:\n if (networkType == 0 || networkType == 2) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n iddLength = i;\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(iddLength));\n str2 = stringBuilder.toString();\n break;\n }\n case 104:\n int countryCode = numberEntry.countryCode;\n if (!(inExceptionListForNpCcAreaLocal(numberEntry) || networkPortionNumber.length() < 11 || countryCode == 1)) {\n StringBuilder stringBuilder3 = new StringBuilder();\n stringBuilder3.append(NANP_IDD);\n stringBuilder3.append(networkPortionNumber);\n str2 = stringBuilder3.toString();\n break;\n }\n default:\n if (networkPortionNumber.startsWith(PLUS_SIGN) && (networkType == 1 || networkType == 2)) {\n if (!networkPortionNumber.startsWith(\"+011\")) {\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(1));\n str2 = stringBuilder.toString();\n break;\n }\n str2 = networkPortionNumber.substring(1);\n break;\n }\n }\n if (str2 == null) {\n str2 = networkPortionNumber;\n }\n return str2;\n } else if (networkType == 1 || networkType == 2) {\n return networkPortionNumber.substring(1);\n } else {\n return networkPortionNumber;\n }\n }\n }\n\n /* Code decompiled incorrectly, please refer to instructions dump. */\n private static ArrayList getAllIDDs(Context context, String mcc) {\n ArrayList allIDDs = (ArrayList) IDDS_MAPS.get(mcc);\n if (allIDDs != null) {\n return allIDDs;\n }\n allIDDs = new ArrayList();\n String[] projection = new String[] { MccIdd.IDD, \"MCC\" };\n String where = null;\n String[] selectionArgs = null;\n if (mcc != null) {\n where = \"MCC=?\";\n selectionArgs = new String[] { mcc };\n }\n Cursor cursor = null;\n try {\n cursor = context.getContentResolver().query(MccIdd.CONTENT_URI, projection, where, selectionArgs, null);\n if (cursor.getCount() > 0) {\n while (cursor.moveToNext()) {\n String idd = cursor.getString(0);\n if (!allIDDs.contains(idd)) {\n allIDDs.add(idd);\n }\n }\n }\n } catch (SQLException e) {\n Rlog.e(TAG, \"Can't access HbpcdLookup database\", e);\n } catch (Throwable th) {\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n private static int checkNANP(NumberEntry numberEntry, ArrayList allIDDs) {\n boolean isNANP = false;\n String number = numberEntry.number;\n if (number.length() == 7) {\n char firstChar = number.charAt(0);\n if (firstChar >= '2' && firstChar <= '9') {\n isNANP = true;\n for (int i = 1; i < 7; i++) {\n if (!PhoneNumberUtils.isISODigit(number.charAt(i))) {\n isNANP = false;\n break;\n }\n }\n }\n if (isNANP) {\n return 1;\n }\n } else if (number.length() == 10) {\n if (isNANP(number)) {\n return 2;\n }\n } else if (number.length() == 11) {\n if (isNANP(number)) {\n return 3;\n }\n } else if (number.startsWith(PLUS_SIGN)) {\n number = number.substring(1);\n if (number.length() == 11) {\n if (isNANP(number)) {\n return 4;\n }\n } else if (number.startsWith(NANP_IDD) && number.length() == 14 && isNANP(number.substring(3))) {\n return 6;\n }\n } else {\n Iterator it = allIDDs.iterator();\n while (it.hasNext()) {\n String idd = (String) it.next();\n if (number.startsWith(idd)) {\n String number2 = number.substring(idd.length());\n if (number2 != null && number2.startsWith(String.valueOf(1)) && isNANP(number2)) {\n numberEntry.IDD = idd;\n return 5;\n }\n }\n }\n }\n return 0;\n }\n\n private static boolean isNANP(String number) {\n if (number.length() != 10 && (number.length() != 11 || !number.startsWith(\"1\"))) {\n return false;\n }\n if (number.length() == 11) {\n number = number.substring(1);\n }\n return PhoneNumberUtils.isNanp(number);\n }\n\n private static int checkInternationalNumberPlan(Context context, NumberEntry numberEntry, ArrayList allIDDs, String homeIDD) {\n String number = numberEntry.number;\n int countryCode;\n int countryCode2;\n if (number.startsWith(PLUS_SIGN)) {\n String numberNoNBPCD = number.substring(1);\n if (numberNoNBPCD.startsWith(homeIDD)) {\n int countryCode3 = getCountryCode(context, numberNoNBPCD.substring(homeIDD.length()));\n countryCode = countryCode3;\n if (countryCode3 > 0) {\n numberEntry.countryCode = countryCode;\n return 100;\n }\n }\n countryCode2 = getCountryCode(context, numberNoNBPCD);\n countryCode = countryCode2;\n if (countryCode2 > 0) {\n numberEntry.countryCode = countryCode;\n return 102;\n }\n } else if (number.startsWith(homeIDD)) {\n countryCode2 = getCountryCode(context, number.substring(homeIDD.length()));\n countryCode = countryCode2;\n if (countryCode2 > 0) {\n numberEntry.countryCode = countryCode;\n return 101;\n }\n } else {\n Iterator it = allIDDs.iterator();\n while (it.hasNext()) {\n String exitCode = (String) it.next();\n if (number.startsWith(exitCode)) {\n int countryCode4 = getCountryCode(context, number.substring(exitCode.length()));\n countryCode = countryCode4;\n if (countryCode4 > 0) {\n numberEntry.countryCode = countryCode;\n numberEntry.IDD = exitCode;\n return NP_LOCALIDD_CC_AREA_LOCAL;\n }\n }\n }\n if (!number.startsWith(ProxyController.MODEM_0)) {\n int countryCode5 = getCountryCode(context, number);\n countryCode = countryCode5;\n if (countryCode5 > 0) {\n numberEntry.countryCode = countryCode;\n return 104;\n }\n }\n }\n return 0;\n }\n\n private static int getCountryCode(Context context, String number) {\n if (number.length() >= 10) {\n int[] allCCs = getAllCountryCodes(context);\n if (allCCs == null) {\n return -1;\n }\n int i;\n int[] ccArray = new int[MAX_COUNTRY_CODES_LENGTH];\n for (i = 0; i < MAX_COUNTRY_CODES_LENGTH; i++) {\n ccArray[i] = Integer.parseInt(number.substring(0, i + 1));\n }\n for (int tempCC : allCCs) {\n for (int j = 0; j < MAX_COUNTRY_CODES_LENGTH; j++) {\n if (tempCC == ccArray[j]) {\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"Country code = \");\n stringBuilder.append(tempCC);\n Rlog.d(str, stringBuilder.toString());\n }\n return tempCC;\n }\n }\n }\n }\n return -1;\n }\n\n /* Code decompiled incorrectly, please refer to instructions dump. */\n private static int[] getAllCountryCodes(Context context) {\n if (ALL_COUNTRY_CODES != null) {\n return ALL_COUNTRY_CODES;\n }\n Cursor cursor = null;\n try {\n cursor = context.getContentResolver().query(MccLookup.CONTENT_URI, new String[] { MccLookup.COUNTRY_CODE }, null, null, null);\n if (cursor.getCount() > 0) {\n ALL_COUNTRY_CODES = new int[cursor.getCount()];\n int i = 0;\n while (cursor.moveToNext()) {\n int countryCode = cursor.getInt(0);\n int i2 = i + 1;\n ALL_COUNTRY_CODES[i] = countryCode;\n i = String.valueOf(countryCode).trim().length();\n if (i > MAX_COUNTRY_CODES_LENGTH) {\n MAX_COUNTRY_CODES_LENGTH = i;\n }\n i = i2;\n }\n }\n } catch (SQLException e) {\n Rlog.e(TAG, \"Can't access HbpcdLookup database\", e);\n } catch (Throwable th) {\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n private static boolean inExceptionListForNpCcAreaLocal(NumberEntry numberEntry) {\n int countryCode = numberEntry.countryCode;\n return numberEntry.number.length() == 12 && (countryCode == 7 || countryCode == 20 || countryCode == 65 || countryCode == 90);\n }\n\n private static String getNumberPlanType(int state) {\n String numberPlanType = new StringBuilder();\n numberPlanType.append(\"Number Plan type (\");\n numberPlanType.append(state);\n numberPlanType.append(\"): \");\n numberPlanType = numberPlanType.toString();\n if (state == 1) {\n return \"NP_NANP_LOCAL\";\n }\n if (state == 2) {\n return \"NP_NANP_AREA_LOCAL\";\n }\n if (state == 3) {\n return \"NP_NANP_NDD_AREA_LOCAL\";\n }\n if (state == 4) {\n return \"NP_NANP_NBPCD_CC_AREA_LOCAL\";\n }\n if (state == 5) {\n return \"NP_NANP_LOCALIDD_CC_AREA_LOCAL\";\n }\n if (state == 6) {\n return \"NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 100) {\n return \"NP_NBPCD_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 101) {\n return \"NP_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 102) {\n return \"NP_NBPCD_CC_AREA_LOCAL\";\n }\n if (state == NP_LOCALIDD_CC_AREA_LOCAL) {\n return \"NP_LOCALIDD_CC_AREA_LOCAL\";\n }\n if (state == 104) {\n return \"NP_CC_AREA_LOCAL\";\n }\n return \"Unknown type\";\n }\n\n public static String filterDestAddr(Phone phone, String destAddr) {\n if (DBG) {\n Rlog.d(TAG, \"enter filterDestAddr. destAddr=\\\"xxxx\\\"\");\n }\n if (destAddr == null || !PhoneNumberUtils.isGlobalPhoneNumber(destAddr)) {\n Rlog.w(TAG, \"destAddr xxxx is not a global phone number! Nothing changed.\");\n return destAddr;\n }\n String networkOperator = TelephonyManager.from(phone.getContext()).getNetworkOperator(phone.getSubId());\n String result = null;\n if (needToConvert(phone)) {\n int networkType = getNetworkType(phone);\n if (!(networkType == -1 || TextUtils.isEmpty(networkOperator))) {\n String networkMcc = networkOperator.substring(null, 3);\n if (networkMcc != null && networkMcc.trim().length() > 0) {\n result = formatNumber(phone.getContext(), destAddr, networkMcc, networkType);\n }\n }\n }\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"destAddr is \");\n stringBuilder.append(result != null ? \"formatted.\" : \"not formatted.\");\n Rlog.d(str, stringBuilder.toString());\n Rlog.d(TAG, \"leave filterDestAddr, new destAddr=\\\"xxxx\\\"\");\n }\n return result != null ? result : destAddr;\n }\n\n private static int getNetworkType(Phone phone) {\n int phoneType = phone.getPhoneType();\n if (phoneType == 1) {\n return 0;\n }\n if (phoneType == 2) {\n if (isInternationalRoaming(phone)) {\n return 2;\n }\n return 1;\n } else if (!DBG) {\n return -1;\n } else {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"warning! unknown mPhoneType value=\");\n stringBuilder.append(phoneType);\n Rlog.w(str, stringBuilder.toString());\n return -1;\n }\n }\n\n private static boolean isInternationalRoaming(Phone phone) {\n String operatorIsoCountry = TelephonyManager.from(phone.getContext()).getNetworkCountryIsoForPhone(phone.getPhoneId());\n String simIsoCountry = TelephonyManager.from(phone.getContext()).getSimCountryIsoForPhone(phone.getPhoneId());\n boolean internationalRoaming = (TextUtils.isEmpty(operatorIsoCountry) || TextUtils.isEmpty(simIsoCountry) || simIsoCountry.equals(operatorIsoCountry)) ? false : true;\n if (!internationalRoaming) {\n return internationalRoaming;\n }\n if (\"us\".equals(simIsoCountry)) {\n return 1 ^ \"vi\".equals(operatorIsoCountry);\n }\n if (\"vi\".equals(simIsoCountry)) {\n return 1 ^ \"us\".equals(operatorIsoCountry);\n }\n return internationalRoaming;\n }\n\n private static boolean needToConvert(Phone phone) {\n long identity = Binder.clearCallingIdentity();\n try {\n CarrierConfigManager configManager = (CarrierConfigManager) phone.getContext().getSystemService(\"carrier_config\");\n if (configManager != null) {\n PersistableBundle bundle = configManager.getConfig();\n if (bundle != null) {\n boolean z = bundle.getBoolean(\"sms_requires_destination_number_conversion_bool\");\n return z;\n }\n }\n Binder.restoreCallingIdentity(identity);\n return false;\n } finally {\n Binder.restoreCallingIdentity(identity);\n }\n }\n\n ", "post_mask_code": "{\n String gid1 = phone.getGroupIdLevel1();\n boolean ret = true;\n if (TextUtils.isEmpty(serviceGid1)) {\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"compareGid1 serviceGid is empty, return \");\n stringBuilder.append(true);\n Rlog.d(str, stringBuilder.toString());\n }\n return true;\n }\n String str2;\n StringBuilder stringBuilder2;\n int gid_length = serviceGid1.length();\n if (gid1 == null || gid1.length() < gid_length || !gid1.substring(0, gid_length).equalsIgnoreCase(serviceGid1)) {\n if (DBG) {\n str2 = TAG;\n stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\" gid1 \");\n stringBuilder2.append(gid1);\n stringBuilder2.append(\" serviceGid1 \");\n stringBuilder2.append(serviceGid1);\n Rlog.d(str2, stringBuilder2.toString());\n }\n ret = false;\n }\n if (DBG) {\n str2 = TAG;\n stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\"compareGid1 is \");\n stringBuilder2.append(ret ? \"Same\" : \"Different\");\n Rlog.d(str2, stringBuilder2.toString());\n }\n return ret;\n }\n}\n"} {"task_id": "Java_2484", "language": "Java", "task_type": "method_body", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/android/internal/telephony/SmsNumberUtils.java", "mask_start_position": 11573, "mask_end_position": 11844, "canonical_solution": "{\n if (number.length() != 10 && (number.length() != 11 || !number.startsWith(\"1\"))) {\n return false;\n }\n if (number.length() == 11) {\n number = number.substring(1);\n }\n return PhoneNumberUtils.isNanp(number);\n }", "pre_mask_code": "package com.android.internal.telephony;\n\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.SQLException;\nimport android.os.Binder;\nimport android.os.Build;\nimport android.os.PersistableBundle;\nimport android.telephony.CarrierConfigManager;\nimport android.telephony.PhoneNumberUtils;\nimport android.telephony.Rlog;\nimport android.telephony.TelephonyManager;\nimport android.text.TextUtils;\nimport com.android.internal.telephony.HbpcdLookup.MccIdd;\nimport com.android.internal.telephony.HbpcdLookup.MccLookup;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\n\npublic class SmsNumberUtils {\n\n private static int[] ALL_COUNTRY_CODES = null;\n\n private static final int CDMA_HOME_NETWORK = 1;\n\n private static final int CDMA_ROAMING_NETWORK = 2;\n\n private static final boolean DBG = Build.IS_DEBUGGABLE;\n\n private static final int GSM_UMTS_NETWORK = 0;\n\n private static HashMap> IDDS_MAPS = new HashMap();\n\n private static int MAX_COUNTRY_CODES_LENGTH = 0;\n\n private static final int MIN_COUNTRY_AREA_LOCAL_LENGTH = 10;\n\n private static final int NANP_CC = 1;\n\n private static final String NANP_IDD = \"011\";\n\n private static final int NANP_LONG_LENGTH = 11;\n\n private static final int NANP_MEDIUM_LENGTH = 10;\n\n private static final String NANP_NDD = \"1\";\n\n private static final int NANP_SHORT_LENGTH = 7;\n\n private static final int NP_CC_AREA_LOCAL = 104;\n\n private static final int NP_HOMEIDD_CC_AREA_LOCAL = 101;\n\n private static final int NP_INTERNATIONAL_BEGIN = 100;\n\n private static final int NP_LOCALIDD_CC_AREA_LOCAL = 103;\n\n private static final int NP_NANP_AREA_LOCAL = 2;\n\n private static final int NP_NANP_BEGIN = 1;\n\n private static final int NP_NANP_LOCAL = 1;\n\n private static final int NP_NANP_LOCALIDD_CC_AREA_LOCAL = 5;\n\n private static final int NP_NANP_NBPCD_CC_AREA_LOCAL = 4;\n\n private static final int NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL = 6;\n\n private static final int NP_NANP_NDD_AREA_LOCAL = 3;\n\n private static final int NP_NBPCD_CC_AREA_LOCAL = 102;\n\n private static final int NP_NBPCD_HOMEIDD_CC_AREA_LOCAL = 100;\n\n private static final int NP_NONE = 0;\n\n private static final String PLUS_SIGN = \"+\";\n\n private static final String TAG = \"SmsNumberUtils\";\n\n private static class NumberEntry {\n\n public String IDD;\n\n public int countryCode;\n\n public String number;\n\n public NumberEntry(String number) {\n this.number = number;\n }\n }\n\n private static String formatNumber(Context context, String number, String activeMcc, int networkType) {\n if (number == null) {\n throw new IllegalArgumentException(\"number is null\");\n } else if (activeMcc == null || activeMcc.trim().length() == 0) {\n throw new IllegalArgumentException(\"activeMcc is null or empty!\");\n } else {\n String networkPortionNumber = PhoneNumberUtils.extractNetworkPortion(number);\n if (networkPortionNumber == null || networkPortionNumber.length() == 0) {\n throw new IllegalArgumentException(\"Number is invalid!\");\n }\n StringBuilder stringBuilder;\n NumberEntry numberEntry = new NumberEntry(networkPortionNumber);\n ArrayList allIDDs = getAllIDDs(context, activeMcc);\n int nanpState = checkNANP(numberEntry, allIDDs);\n if (DBG) {\n String str = TAG;\n stringBuilder = new StringBuilder();\n stringBuilder.append(\"NANP type: \");\n stringBuilder.append(getNumberPlanType(nanpState));\n Rlog.d(str, stringBuilder.toString());\n }\n if (nanpState == 1 || nanpState == 2 || nanpState == 3) {\n return networkPortionNumber;\n }\n if (nanpState != 4) {\n int iddLength;\n String str2;\n int i = 0;\n if (nanpState == 5) {\n if (networkType == 1) {\n return networkPortionNumber;\n }\n if (networkType == 0) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n iddLength = i;\n stringBuilder = new StringBuilder();\n stringBuilder.append(PLUS_SIGN);\n stringBuilder.append(networkPortionNumber.substring(iddLength));\n return stringBuilder.toString();\n } else if (networkType == 2) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n return networkPortionNumber.substring(i);\n }\n }\n int internationalState = checkInternationalNumberPlan(context, numberEntry, allIDDs, NANP_IDD);\n if (DBG) {\n str2 = TAG;\n StringBuilder stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\"International type: \");\n stringBuilder2.append(getNumberPlanType(internationalState));\n Rlog.d(str2, stringBuilder2.toString());\n }\n str2 = null;\n switch(internationalState) {\n case 100:\n if (networkType == 0) {\n str2 = networkPortionNumber.substring(1);\n break;\n }\n break;\n case 101:\n str2 = networkPortionNumber;\n break;\n case 102:\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(1));\n str2 = stringBuilder.toString();\n break;\n case NP_LOCALIDD_CC_AREA_LOCAL:\n if (networkType == 0 || networkType == 2) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n iddLength = i;\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(iddLength));\n str2 = stringBuilder.toString();\n break;\n }\n case 104:\n int countryCode = numberEntry.countryCode;\n if (!(inExceptionListForNpCcAreaLocal(numberEntry) || networkPortionNumber.length() < 11 || countryCode == 1)) {\n StringBuilder stringBuilder3 = new StringBuilder();\n stringBuilder3.append(NANP_IDD);\n stringBuilder3.append(networkPortionNumber);\n str2 = stringBuilder3.toString();\n break;\n }\n default:\n if (networkPortionNumber.startsWith(PLUS_SIGN) && (networkType == 1 || networkType == 2)) {\n if (!networkPortionNumber.startsWith(\"+011\")) {\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(1));\n str2 = stringBuilder.toString();\n break;\n }\n str2 = networkPortionNumber.substring(1);\n break;\n }\n }\n if (str2 == null) {\n str2 = networkPortionNumber;\n }\n return str2;\n } else if (networkType == 1 || networkType == 2) {\n return networkPortionNumber.substring(1);\n } else {\n return networkPortionNumber;\n }\n }\n }\n\n /* Code decompiled incorrectly, please refer to instructions dump. */\n private static ArrayList getAllIDDs(Context context, String mcc) {\n ArrayList allIDDs = (ArrayList) IDDS_MAPS.get(mcc);\n if (allIDDs != null) {\n return allIDDs;\n }\n allIDDs = new ArrayList();\n String[] projection = new String[] { MccIdd.IDD, \"MCC\" };\n String where = null;\n String[] selectionArgs = null;\n if (mcc != null) {\n where = \"MCC=?\";\n selectionArgs = new String[] { mcc };\n }\n Cursor cursor = null;\n try {\n cursor = context.getContentResolver().query(MccIdd.CONTENT_URI, projection, where, selectionArgs, null);\n if (cursor.getCount() > 0) {\n while (cursor.moveToNext()) {\n String idd = cursor.getString(0);\n if (!allIDDs.contains(idd)) {\n allIDDs.add(idd);\n }\n }\n }\n } catch (SQLException e) {\n Rlog.e(TAG, \"Can't access HbpcdLookup database\", e);\n } catch (Throwable th) {\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n private static int checkNANP(NumberEntry numberEntry, ArrayList allIDDs) {\n boolean isNANP = false;\n String number = numberEntry.number;\n if (number.length() == 7) {\n char firstChar = number.charAt(0);\n if (firstChar >= '2' && firstChar <= '9') {\n isNANP = true;\n for (int i = 1; i < 7; i++) {\n if (!PhoneNumberUtils.isISODigit(number.charAt(i))) {\n isNANP = false;\n break;\n }\n }\n }\n if (isNANP) {\n return 1;\n }\n } else if (number.length() == 10) {\n if (isNANP(number)) {\n return 2;\n }\n } else if (number.length() == 11) {\n if (isNANP(number)) {\n return 3;\n }\n } else if (number.startsWith(PLUS_SIGN)) {\n number = number.substring(1);\n if (number.length() == 11) {\n if (isNANP(number)) {\n return 4;\n }\n } else if (number.startsWith(NANP_IDD) && number.length() == 14 && isNANP(number.substring(3))) {\n return 6;\n }\n } else {\n Iterator it = allIDDs.iterator();\n while (it.hasNext()) {\n String idd = (String) it.next();\n if (number.startsWith(idd)) {\n String number2 = number.substring(idd.length());\n if (number2 != null && number2.startsWith(String.valueOf(1)) && isNANP(number2)) {\n numberEntry.IDD = idd;\n return 5;\n }\n }\n }\n }\n return 0;\n }\n\n private static boolean isNANP(String number) ", "post_mask_code": "\n\n private static int checkInternationalNumberPlan(Context context, NumberEntry numberEntry, ArrayList allIDDs, String homeIDD) {\n String number = numberEntry.number;\n int countryCode;\n int countryCode2;\n if (number.startsWith(PLUS_SIGN)) {\n String numberNoNBPCD = number.substring(1);\n if (numberNoNBPCD.startsWith(homeIDD)) {\n int countryCode3 = getCountryCode(context, numberNoNBPCD.substring(homeIDD.length()));\n countryCode = countryCode3;\n if (countryCode3 > 0) {\n numberEntry.countryCode = countryCode;\n return 100;\n }\n }\n countryCode2 = getCountryCode(context, numberNoNBPCD);\n countryCode = countryCode2;\n if (countryCode2 > 0) {\n numberEntry.countryCode = countryCode;\n return 102;\n }\n } else if (number.startsWith(homeIDD)) {\n countryCode2 = getCountryCode(context, number.substring(homeIDD.length()));\n countryCode = countryCode2;\n if (countryCode2 > 0) {\n numberEntry.countryCode = countryCode;\n return 101;\n }\n } else {\n Iterator it = allIDDs.iterator();\n while (it.hasNext()) {\n String exitCode = (String) it.next();\n if (number.startsWith(exitCode)) {\n int countryCode4 = getCountryCode(context, number.substring(exitCode.length()));\n countryCode = countryCode4;\n if (countryCode4 > 0) {\n numberEntry.countryCode = countryCode;\n numberEntry.IDD = exitCode;\n return NP_LOCALIDD_CC_AREA_LOCAL;\n }\n }\n }\n if (!number.startsWith(ProxyController.MODEM_0)) {\n int countryCode5 = getCountryCode(context, number);\n countryCode = countryCode5;\n if (countryCode5 > 0) {\n numberEntry.countryCode = countryCode;\n return 104;\n }\n }\n }\n return 0;\n }\n\n private static int getCountryCode(Context context, String number) {\n if (number.length() >= 10) {\n int[] allCCs = getAllCountryCodes(context);\n if (allCCs == null) {\n return -1;\n }\n int i;\n int[] ccArray = new int[MAX_COUNTRY_CODES_LENGTH];\n for (i = 0; i < MAX_COUNTRY_CODES_LENGTH; i++) {\n ccArray[i] = Integer.parseInt(number.substring(0, i + 1));\n }\n for (int tempCC : allCCs) {\n for (int j = 0; j < MAX_COUNTRY_CODES_LENGTH; j++) {\n if (tempCC == ccArray[j]) {\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"Country code = \");\n stringBuilder.append(tempCC);\n Rlog.d(str, stringBuilder.toString());\n }\n return tempCC;\n }\n }\n }\n }\n return -1;\n }\n\n /* Code decompiled incorrectly, please refer to instructions dump. */\n private static int[] getAllCountryCodes(Context context) {\n if (ALL_COUNTRY_CODES != null) {\n return ALL_COUNTRY_CODES;\n }\n Cursor cursor = null;\n try {\n cursor = context.getContentResolver().query(MccLookup.CONTENT_URI, new String[] { MccLookup.COUNTRY_CODE }, null, null, null);\n if (cursor.getCount() > 0) {\n ALL_COUNTRY_CODES = new int[cursor.getCount()];\n int i = 0;\n while (cursor.moveToNext()) {\n int countryCode = cursor.getInt(0);\n int i2 = i + 1;\n ALL_COUNTRY_CODES[i] = countryCode;\n i = String.valueOf(countryCode).trim().length();\n if (i > MAX_COUNTRY_CODES_LENGTH) {\n MAX_COUNTRY_CODES_LENGTH = i;\n }\n i = i2;\n }\n }\n } catch (SQLException e) {\n Rlog.e(TAG, \"Can't access HbpcdLookup database\", e);\n } catch (Throwable th) {\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n private static boolean inExceptionListForNpCcAreaLocal(NumberEntry numberEntry) {\n int countryCode = numberEntry.countryCode;\n return numberEntry.number.length() == 12 && (countryCode == 7 || countryCode == 20 || countryCode == 65 || countryCode == 90);\n }\n\n private static String getNumberPlanType(int state) {\n String numberPlanType = new StringBuilder();\n numberPlanType.append(\"Number Plan type (\");\n numberPlanType.append(state);\n numberPlanType.append(\"): \");\n numberPlanType = numberPlanType.toString();\n if (state == 1) {\n return \"NP_NANP_LOCAL\";\n }\n if (state == 2) {\n return \"NP_NANP_AREA_LOCAL\";\n }\n if (state == 3) {\n return \"NP_NANP_NDD_AREA_LOCAL\";\n }\n if (state == 4) {\n return \"NP_NANP_NBPCD_CC_AREA_LOCAL\";\n }\n if (state == 5) {\n return \"NP_NANP_LOCALIDD_CC_AREA_LOCAL\";\n }\n if (state == 6) {\n return \"NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 100) {\n return \"NP_NBPCD_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 101) {\n return \"NP_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 102) {\n return \"NP_NBPCD_CC_AREA_LOCAL\";\n }\n if (state == NP_LOCALIDD_CC_AREA_LOCAL) {\n return \"NP_LOCALIDD_CC_AREA_LOCAL\";\n }\n if (state == 104) {\n return \"NP_CC_AREA_LOCAL\";\n }\n return \"Unknown type\";\n }\n\n public static String filterDestAddr(Phone phone, String destAddr) {\n if (DBG) {\n Rlog.d(TAG, \"enter filterDestAddr. destAddr=\\\"xxxx\\\"\");\n }\n if (destAddr == null || !PhoneNumberUtils.isGlobalPhoneNumber(destAddr)) {\n Rlog.w(TAG, \"destAddr xxxx is not a global phone number! Nothing changed.\");\n return destAddr;\n }\n String networkOperator = TelephonyManager.from(phone.getContext()).getNetworkOperator(phone.getSubId());\n String result = null;\n if (needToConvert(phone)) {\n int networkType = getNetworkType(phone);\n if (!(networkType == -1 || TextUtils.isEmpty(networkOperator))) {\n String networkMcc = networkOperator.substring(null, 3);\n if (networkMcc != null && networkMcc.trim().length() > 0) {\n result = formatNumber(phone.getContext(), destAddr, networkMcc, networkType);\n }\n }\n }\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"destAddr is \");\n stringBuilder.append(result != null ? \"formatted.\" : \"not formatted.\");\n Rlog.d(str, stringBuilder.toString());\n Rlog.d(TAG, \"leave filterDestAddr, new destAddr=\\\"xxxx\\\"\");\n }\n return result != null ? result : destAddr;\n }\n\n private static int getNetworkType(Phone phone) {\n int phoneType = phone.getPhoneType();\n if (phoneType == 1) {\n return 0;\n }\n if (phoneType == 2) {\n if (isInternationalRoaming(phone)) {\n return 2;\n }\n return 1;\n } else if (!DBG) {\n return -1;\n } else {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"warning! unknown mPhoneType value=\");\n stringBuilder.append(phoneType);\n Rlog.w(str, stringBuilder.toString());\n return -1;\n }\n }\n\n private static boolean isInternationalRoaming(Phone phone) {\n String operatorIsoCountry = TelephonyManager.from(phone.getContext()).getNetworkCountryIsoForPhone(phone.getPhoneId());\n String simIsoCountry = TelephonyManager.from(phone.getContext()).getSimCountryIsoForPhone(phone.getPhoneId());\n boolean internationalRoaming = (TextUtils.isEmpty(operatorIsoCountry) || TextUtils.isEmpty(simIsoCountry) || simIsoCountry.equals(operatorIsoCountry)) ? false : true;\n if (!internationalRoaming) {\n return internationalRoaming;\n }\n if (\"us\".equals(simIsoCountry)) {\n return 1 ^ \"vi\".equals(operatorIsoCountry);\n }\n if (\"vi\".equals(simIsoCountry)) {\n return 1 ^ \"us\".equals(operatorIsoCountry);\n }\n return internationalRoaming;\n }\n\n private static boolean needToConvert(Phone phone) {\n long identity = Binder.clearCallingIdentity();\n try {\n CarrierConfigManager configManager = (CarrierConfigManager) phone.getContext().getSystemService(\"carrier_config\");\n if (configManager != null) {\n PersistableBundle bundle = configManager.getConfig();\n if (bundle != null) {\n boolean z = bundle.getBoolean(\"sms_requires_destination_number_conversion_bool\");\n return z;\n }\n }\n Binder.restoreCallingIdentity(identity);\n return false;\n } finally {\n Binder.restoreCallingIdentity(identity);\n }\n }\n\n private static boolean compareGid1(Phone phone, String serviceGid1) {\n String gid1 = phone.getGroupIdLevel1();\n boolean ret = true;\n if (TextUtils.isEmpty(serviceGid1)) {\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"compareGid1 serviceGid is empty, return \");\n stringBuilder.append(true);\n Rlog.d(str, stringBuilder.toString());\n }\n return true;\n }\n String str2;\n StringBuilder stringBuilder2;\n int gid_length = serviceGid1.length();\n if (gid1 == null || gid1.length() < gid_length || !gid1.substring(0, gid_length).equalsIgnoreCase(serviceGid1)) {\n if (DBG) {\n str2 = TAG;\n stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\" gid1 \");\n stringBuilder2.append(gid1);\n stringBuilder2.append(\" serviceGid1 \");\n stringBuilder2.append(serviceGid1);\n Rlog.d(str2, stringBuilder2.toString());\n }\n ret = false;\n }\n if (DBG) {\n str2 = TAG;\n stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\"compareGid1 is \");\n stringBuilder2.append(ret ? \"Same\" : \"Different\");\n Rlog.d(str2, stringBuilder2.toString());\n }\n return ret;\n }\n}\n"} {"task_id": "Java_2485", "language": "Java", "task_type": "single_line", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/android/internal/telephony/SmsNumberUtils.java", "mask_start_position": 19490, "mask_end_position": 19517, "canonical_solution": "ype = phone.getPhoneType();", "pre_mask_code": "package com.android.internal.telephony;\n\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.SQLException;\nimport android.os.Binder;\nimport android.os.Build;\nimport android.os.PersistableBundle;\nimport android.telephony.CarrierConfigManager;\nimport android.telephony.PhoneNumberUtils;\nimport android.telephony.Rlog;\nimport android.telephony.TelephonyManager;\nimport android.text.TextUtils;\nimport com.android.internal.telephony.HbpcdLookup.MccIdd;\nimport com.android.internal.telephony.HbpcdLookup.MccLookup;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\n\npublic class SmsNumberUtils {\n\n private static int[] ALL_COUNTRY_CODES = null;\n\n private static final int CDMA_HOME_NETWORK = 1;\n\n private static final int CDMA_ROAMING_NETWORK = 2;\n\n private static final boolean DBG = Build.IS_DEBUGGABLE;\n\n private static final int GSM_UMTS_NETWORK = 0;\n\n private static HashMap> IDDS_MAPS = new HashMap();\n\n private static int MAX_COUNTRY_CODES_LENGTH = 0;\n\n private static final int MIN_COUNTRY_AREA_LOCAL_LENGTH = 10;\n\n private static final int NANP_CC = 1;\n\n private static final String NANP_IDD = \"011\";\n\n private static final int NANP_LONG_LENGTH = 11;\n\n private static final int NANP_MEDIUM_LENGTH = 10;\n\n private static final String NANP_NDD = \"1\";\n\n private static final int NANP_SHORT_LENGTH = 7;\n\n private static final int NP_CC_AREA_LOCAL = 104;\n\n private static final int NP_HOMEIDD_CC_AREA_LOCAL = 101;\n\n private static final int NP_INTERNATIONAL_BEGIN = 100;\n\n private static final int NP_LOCALIDD_CC_AREA_LOCAL = 103;\n\n private static final int NP_NANP_AREA_LOCAL = 2;\n\n private static final int NP_NANP_BEGIN = 1;\n\n private static final int NP_NANP_LOCAL = 1;\n\n private static final int NP_NANP_LOCALIDD_CC_AREA_LOCAL = 5;\n\n private static final int NP_NANP_NBPCD_CC_AREA_LOCAL = 4;\n\n private static final int NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL = 6;\n\n private static final int NP_NANP_NDD_AREA_LOCAL = 3;\n\n private static final int NP_NBPCD_CC_AREA_LOCAL = 102;\n\n private static final int NP_NBPCD_HOMEIDD_CC_AREA_LOCAL = 100;\n\n private static final int NP_NONE = 0;\n\n private static final String PLUS_SIGN = \"+\";\n\n private static final String TAG = \"SmsNumberUtils\";\n\n private static class NumberEntry {\n\n public String IDD;\n\n public int countryCode;\n\n public String number;\n\n public NumberEntry(String number) {\n this.number = number;\n }\n }\n\n private static String formatNumber(Context context, String number, String activeMcc, int networkType) {\n if (number == null) {\n throw new IllegalArgumentException(\"number is null\");\n } else if (activeMcc == null || activeMcc.trim().length() == 0) {\n throw new IllegalArgumentException(\"activeMcc is null or empty!\");\n } else {\n String networkPortionNumber = PhoneNumberUtils.extractNetworkPortion(number);\n if (networkPortionNumber == null || networkPortionNumber.length() == 0) {\n throw new IllegalArgumentException(\"Number is invalid!\");\n }\n StringBuilder stringBuilder;\n NumberEntry numberEntry = new NumberEntry(networkPortionNumber);\n ArrayList allIDDs = getAllIDDs(context, activeMcc);\n int nanpState = checkNANP(numberEntry, allIDDs);\n if (DBG) {\n String str = TAG;\n stringBuilder = new StringBuilder();\n stringBuilder.append(\"NANP type: \");\n stringBuilder.append(getNumberPlanType(nanpState));\n Rlog.d(str, stringBuilder.toString());\n }\n if (nanpState == 1 || nanpState == 2 || nanpState == 3) {\n return networkPortionNumber;\n }\n if (nanpState != 4) {\n int iddLength;\n String str2;\n int i = 0;\n if (nanpState == 5) {\n if (networkType == 1) {\n return networkPortionNumber;\n }\n if (networkType == 0) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n iddLength = i;\n stringBuilder = new StringBuilder();\n stringBuilder.append(PLUS_SIGN);\n stringBuilder.append(networkPortionNumber.substring(iddLength));\n return stringBuilder.toString();\n } else if (networkType == 2) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n return networkPortionNumber.substring(i);\n }\n }\n int internationalState = checkInternationalNumberPlan(context, numberEntry, allIDDs, NANP_IDD);\n if (DBG) {\n str2 = TAG;\n StringBuilder stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\"International type: \");\n stringBuilder2.append(getNumberPlanType(internationalState));\n Rlog.d(str2, stringBuilder2.toString());\n }\n str2 = null;\n switch(internationalState) {\n case 100:\n if (networkType == 0) {\n str2 = networkPortionNumber.substring(1);\n break;\n }\n break;\n case 101:\n str2 = networkPortionNumber;\n break;\n case 102:\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(1));\n str2 = stringBuilder.toString();\n break;\n case NP_LOCALIDD_CC_AREA_LOCAL:\n if (networkType == 0 || networkType == 2) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n iddLength = i;\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(iddLength));\n str2 = stringBuilder.toString();\n break;\n }\n case 104:\n int countryCode = numberEntry.countryCode;\n if (!(inExceptionListForNpCcAreaLocal(numberEntry) || networkPortionNumber.length() < 11 || countryCode == 1)) {\n StringBuilder stringBuilder3 = new StringBuilder();\n stringBuilder3.append(NANP_IDD);\n stringBuilder3.append(networkPortionNumber);\n str2 = stringBuilder3.toString();\n break;\n }\n default:\n if (networkPortionNumber.startsWith(PLUS_SIGN) && (networkType == 1 || networkType == 2)) {\n if (!networkPortionNumber.startsWith(\"+011\")) {\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(1));\n str2 = stringBuilder.toString();\n break;\n }\n str2 = networkPortionNumber.substring(1);\n break;\n }\n }\n if (str2 == null) {\n str2 = networkPortionNumber;\n }\n return str2;\n } else if (networkType == 1 || networkType == 2) {\n return networkPortionNumber.substring(1);\n } else {\n return networkPortionNumber;\n }\n }\n }\n\n /* Code decompiled incorrectly, please refer to instructions dump. */\n private static ArrayList getAllIDDs(Context context, String mcc) {\n ArrayList allIDDs = (ArrayList) IDDS_MAPS.get(mcc);\n if (allIDDs != null) {\n return allIDDs;\n }\n allIDDs = new ArrayList();\n String[] projection = new String[] { MccIdd.IDD, \"MCC\" };\n String where = null;\n String[] selectionArgs = null;\n if (mcc != null) {\n where = \"MCC=?\";\n selectionArgs = new String[] { mcc };\n }\n Cursor cursor = null;\n try {\n cursor = context.getContentResolver().query(MccIdd.CONTENT_URI, projection, where, selectionArgs, null);\n if (cursor.getCount() > 0) {\n while (cursor.moveToNext()) {\n String idd = cursor.getString(0);\n if (!allIDDs.contains(idd)) {\n allIDDs.add(idd);\n }\n }\n }\n } catch (SQLException e) {\n Rlog.e(TAG, \"Can't access HbpcdLookup database\", e);\n } catch (Throwable th) {\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n private static int checkNANP(NumberEntry numberEntry, ArrayList allIDDs) {\n boolean isNANP = false;\n String number = numberEntry.number;\n if (number.length() == 7) {\n char firstChar = number.charAt(0);\n if (firstChar >= '2' && firstChar <= '9') {\n isNANP = true;\n for (int i = 1; i < 7; i++) {\n if (!PhoneNumberUtils.isISODigit(number.charAt(i))) {\n isNANP = false;\n break;\n }\n }\n }\n if (isNANP) {\n return 1;\n }\n } else if (number.length() == 10) {\n if (isNANP(number)) {\n return 2;\n }\n } else if (number.length() == 11) {\n if (isNANP(number)) {\n return 3;\n }\n } else if (number.startsWith(PLUS_SIGN)) {\n number = number.substring(1);\n if (number.length() == 11) {\n if (isNANP(number)) {\n return 4;\n }\n } else if (number.startsWith(NANP_IDD) && number.length() == 14 && isNANP(number.substring(3))) {\n return 6;\n }\n } else {\n Iterator it = allIDDs.iterator();\n while (it.hasNext()) {\n String idd = (String) it.next();\n if (number.startsWith(idd)) {\n String number2 = number.substring(idd.length());\n if (number2 != null && number2.startsWith(String.valueOf(1)) && isNANP(number2)) {\n numberEntry.IDD = idd;\n return 5;\n }\n }\n }\n }\n return 0;\n }\n\n private static boolean isNANP(String number) {\n if (number.length() != 10 && (number.length() != 11 || !number.startsWith(\"1\"))) {\n return false;\n }\n if (number.length() == 11) {\n number = number.substring(1);\n }\n return PhoneNumberUtils.isNanp(number);\n }\n\n private static int checkInternationalNumberPlan(Context context, NumberEntry numberEntry, ArrayList allIDDs, String homeIDD) {\n String number = numberEntry.number;\n int countryCode;\n int countryCode2;\n if (number.startsWith(PLUS_SIGN)) {\n String numberNoNBPCD = number.substring(1);\n if (numberNoNBPCD.startsWith(homeIDD)) {\n int countryCode3 = getCountryCode(context, numberNoNBPCD.substring(homeIDD.length()));\n countryCode = countryCode3;\n if (countryCode3 > 0) {\n numberEntry.countryCode = countryCode;\n return 100;\n }\n }\n countryCode2 = getCountryCode(context, numberNoNBPCD);\n countryCode = countryCode2;\n if (countryCode2 > 0) {\n numberEntry.countryCode = countryCode;\n return 102;\n }\n } else if (number.startsWith(homeIDD)) {\n countryCode2 = getCountryCode(context, number.substring(homeIDD.length()));\n countryCode = countryCode2;\n if (countryCode2 > 0) {\n numberEntry.countryCode = countryCode;\n return 101;\n }\n } else {\n Iterator it = allIDDs.iterator();\n while (it.hasNext()) {\n String exitCode = (String) it.next();\n if (number.startsWith(exitCode)) {\n int countryCode4 = getCountryCode(context, number.substring(exitCode.length()));\n countryCode = countryCode4;\n if (countryCode4 > 0) {\n numberEntry.countryCode = countryCode;\n numberEntry.IDD = exitCode;\n return NP_LOCALIDD_CC_AREA_LOCAL;\n }\n }\n }\n if (!number.startsWith(ProxyController.MODEM_0)) {\n int countryCode5 = getCountryCode(context, number);\n countryCode = countryCode5;\n if (countryCode5 > 0) {\n numberEntry.countryCode = countryCode;\n return 104;\n }\n }\n }\n return 0;\n }\n\n private static int getCountryCode(Context context, String number) {\n if (number.length() >= 10) {\n int[] allCCs = getAllCountryCodes(context);\n if (allCCs == null) {\n return -1;\n }\n int i;\n int[] ccArray = new int[MAX_COUNTRY_CODES_LENGTH];\n for (i = 0; i < MAX_COUNTRY_CODES_LENGTH; i++) {\n ccArray[i] = Integer.parseInt(number.substring(0, i + 1));\n }\n for (int tempCC : allCCs) {\n for (int j = 0; j < MAX_COUNTRY_CODES_LENGTH; j++) {\n if (tempCC == ccArray[j]) {\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"Country code = \");\n stringBuilder.append(tempCC);\n Rlog.d(str, stringBuilder.toString());\n }\n return tempCC;\n }\n }\n }\n }\n return -1;\n }\n\n /* Code decompiled incorrectly, please refer to instructions dump. */\n private static int[] getAllCountryCodes(Context context) {\n if (ALL_COUNTRY_CODES != null) {\n return ALL_COUNTRY_CODES;\n }\n Cursor cursor = null;\n try {\n cursor = context.getContentResolver().query(MccLookup.CONTENT_URI, new String[] { MccLookup.COUNTRY_CODE }, null, null, null);\n if (cursor.getCount() > 0) {\n ALL_COUNTRY_CODES = new int[cursor.getCount()];\n int i = 0;\n while (cursor.moveToNext()) {\n int countryCode = cursor.getInt(0);\n int i2 = i + 1;\n ALL_COUNTRY_CODES[i] = countryCode;\n i = String.valueOf(countryCode).trim().length();\n if (i > MAX_COUNTRY_CODES_LENGTH) {\n MAX_COUNTRY_CODES_LENGTH = i;\n }\n i = i2;\n }\n }\n } catch (SQLException e) {\n Rlog.e(TAG, \"Can't access HbpcdLookup database\", e);\n } catch (Throwable th) {\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n private static boolean inExceptionListForNpCcAreaLocal(NumberEntry numberEntry) {\n int countryCode = numberEntry.countryCode;\n return numberEntry.number.length() == 12 && (countryCode == 7 || countryCode == 20 || countryCode == 65 || countryCode == 90);\n }\n\n private static String getNumberPlanType(int state) {\n String numberPlanType = new StringBuilder();\n numberPlanType.append(\"Number Plan type (\");\n numberPlanType.append(state);\n numberPlanType.append(\"): \");\n numberPlanType = numberPlanType.toString();\n if (state == 1) {\n return \"NP_NANP_LOCAL\";\n }\n if (state == 2) {\n return \"NP_NANP_AREA_LOCAL\";\n }\n if (state == 3) {\n return \"NP_NANP_NDD_AREA_LOCAL\";\n }\n if (state == 4) {\n return \"NP_NANP_NBPCD_CC_AREA_LOCAL\";\n }\n if (state == 5) {\n return \"NP_NANP_LOCALIDD_CC_AREA_LOCAL\";\n }\n if (state == 6) {\n return \"NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 100) {\n return \"NP_NBPCD_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 101) {\n return \"NP_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 102) {\n return \"NP_NBPCD_CC_AREA_LOCAL\";\n }\n if (state == NP_LOCALIDD_CC_AREA_LOCAL) {\n return \"NP_LOCALIDD_CC_AREA_LOCAL\";\n }\n if (state == 104) {\n return \"NP_CC_AREA_LOCAL\";\n }\n return \"Unknown type\";\n }\n\n public static String filterDestAddr(Phone phone, String destAddr) {\n if (DBG) {\n Rlog.d(TAG, \"enter filterDestAddr. destAddr=\\\"xxxx\\\"\");\n }\n if (destAddr == null || !PhoneNumberUtils.isGlobalPhoneNumber(destAddr)) {\n Rlog.w(TAG, \"destAddr xxxx is not a global phone number! Nothing changed.\");\n return destAddr;\n }\n String networkOperator = TelephonyManager.from(phone.getContext()).getNetworkOperator(phone.getSubId());\n String result = null;\n if (needToConvert(phone)) {\n int networkType = getNetworkType(phone);\n if (!(networkType == -1 || TextUtils.isEmpty(networkOperator))) {\n String networkMcc = networkOperator.substring(null, 3);\n if (networkMcc != null && networkMcc.trim().length() > 0) {\n result = formatNumber(phone.getContext(), destAddr, networkMcc, networkType);\n }\n }\n }\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"destAddr is \");\n stringBuilder.append(result != null ? \"formatted.\" : \"not formatted.\");\n Rlog.d(str, stringBuilder.toString());\n Rlog.d(TAG, \"leave filterDestAddr, new destAddr=\\\"xxxx\\\"\");\n }\n return result != null ? result : destAddr;\n }\n\n private static int getNetworkType(Phone phone) {\n int phoneT", "post_mask_code": "\n if (phoneType == 1) {\n return 0;\n }\n if (phoneType == 2) {\n if (isInternationalRoaming(phone)) {\n return 2;\n }\n return 1;\n } else if (!DBG) {\n return -1;\n } else {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"warning! unknown mPhoneType value=\");\n stringBuilder.append(phoneType);\n Rlog.w(str, stringBuilder.toString());\n return -1;\n }\n }\n\n private static boolean isInternationalRoaming(Phone phone) {\n String operatorIsoCountry = TelephonyManager.from(phone.getContext()).getNetworkCountryIsoForPhone(phone.getPhoneId());\n String simIsoCountry = TelephonyManager.from(phone.getContext()).getSimCountryIsoForPhone(phone.getPhoneId());\n boolean internationalRoaming = (TextUtils.isEmpty(operatorIsoCountry) || TextUtils.isEmpty(simIsoCountry) || simIsoCountry.equals(operatorIsoCountry)) ? false : true;\n if (!internationalRoaming) {\n return internationalRoaming;\n }\n if (\"us\".equals(simIsoCountry)) {\n return 1 ^ \"vi\".equals(operatorIsoCountry);\n }\n if (\"vi\".equals(simIsoCountry)) {\n return 1 ^ \"us\".equals(operatorIsoCountry);\n }\n return internationalRoaming;\n }\n\n private static boolean needToConvert(Phone phone) {\n long identity = Binder.clearCallingIdentity();\n try {\n CarrierConfigManager configManager = (CarrierConfigManager) phone.getContext().getSystemService(\"carrier_config\");\n if (configManager != null) {\n PersistableBundle bundle = configManager.getConfig();\n if (bundle != null) {\n boolean z = bundle.getBoolean(\"sms_requires_destination_number_conversion_bool\");\n return z;\n }\n }\n Binder.restoreCallingIdentity(identity);\n return false;\n } finally {\n Binder.restoreCallingIdentity(identity);\n }\n }\n\n private static boolean compareGid1(Phone phone, String serviceGid1) {\n String gid1 = phone.getGroupIdLevel1();\n boolean ret = true;\n if (TextUtils.isEmpty(serviceGid1)) {\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"compareGid1 serviceGid is empty, return \");\n stringBuilder.append(true);\n Rlog.d(str, stringBuilder.toString());\n }\n return true;\n }\n String str2;\n StringBuilder stringBuilder2;\n int gid_length = serviceGid1.length();\n if (gid1 == null || gid1.length() < gid_length || !gid1.substring(0, gid_length).equalsIgnoreCase(serviceGid1)) {\n if (DBG) {\n str2 = TAG;\n stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\" gid1 \");\n stringBuilder2.append(gid1);\n stringBuilder2.append(\" serviceGid1 \");\n stringBuilder2.append(serviceGid1);\n Rlog.d(str2, stringBuilder2.toString());\n }\n ret = false;\n }\n if (DBG) {\n str2 = TAG;\n stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\"compareGid1 is \");\n stringBuilder2.append(ret ? \"Same\" : \"Different\");\n Rlog.d(str2, stringBuilder2.toString());\n }\n return ret;\n }\n}\n"} {"task_id": "Java_2486", "language": "Java", "task_type": "for_statement", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/android/internal/telephony/SmsNumberUtils.java", "mask_start_position": 10088, "mask_end_position": 10302, "canonical_solution": "for (int i = 1; i < 7; i++) {\n if (!PhoneNumberUtils.isISODigit(number.charAt(i))) {\n isNANP = false;\n break;\n }\n }", "pre_mask_code": "package com.android.internal.telephony;\n\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.SQLException;\nimport android.os.Binder;\nimport android.os.Build;\nimport android.os.PersistableBundle;\nimport android.telephony.CarrierConfigManager;\nimport android.telephony.PhoneNumberUtils;\nimport android.telephony.Rlog;\nimport android.telephony.TelephonyManager;\nimport android.text.TextUtils;\nimport com.android.internal.telephony.HbpcdLookup.MccIdd;\nimport com.android.internal.telephony.HbpcdLookup.MccLookup;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\n\npublic class SmsNumberUtils {\n\n private static int[] ALL_COUNTRY_CODES = null;\n\n private static final int CDMA_HOME_NETWORK = 1;\n\n private static final int CDMA_ROAMING_NETWORK = 2;\n\n private static final boolean DBG = Build.IS_DEBUGGABLE;\n\n private static final int GSM_UMTS_NETWORK = 0;\n\n private static HashMap> IDDS_MAPS = new HashMap();\n\n private static int MAX_COUNTRY_CODES_LENGTH = 0;\n\n private static final int MIN_COUNTRY_AREA_LOCAL_LENGTH = 10;\n\n private static final int NANP_CC = 1;\n\n private static final String NANP_IDD = \"011\";\n\n private static final int NANP_LONG_LENGTH = 11;\n\n private static final int NANP_MEDIUM_LENGTH = 10;\n\n private static final String NANP_NDD = \"1\";\n\n private static final int NANP_SHORT_LENGTH = 7;\n\n private static final int NP_CC_AREA_LOCAL = 104;\n\n private static final int NP_HOMEIDD_CC_AREA_LOCAL = 101;\n\n private static final int NP_INTERNATIONAL_BEGIN = 100;\n\n private static final int NP_LOCALIDD_CC_AREA_LOCAL = 103;\n\n private static final int NP_NANP_AREA_LOCAL = 2;\n\n private static final int NP_NANP_BEGIN = 1;\n\n private static final int NP_NANP_LOCAL = 1;\n\n private static final int NP_NANP_LOCALIDD_CC_AREA_LOCAL = 5;\n\n private static final int NP_NANP_NBPCD_CC_AREA_LOCAL = 4;\n\n private static final int NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL = 6;\n\n private static final int NP_NANP_NDD_AREA_LOCAL = 3;\n\n private static final int NP_NBPCD_CC_AREA_LOCAL = 102;\n\n private static final int NP_NBPCD_HOMEIDD_CC_AREA_LOCAL = 100;\n\n private static final int NP_NONE = 0;\n\n private static final String PLUS_SIGN = \"+\";\n\n private static final String TAG = \"SmsNumberUtils\";\n\n private static class NumberEntry {\n\n public String IDD;\n\n public int countryCode;\n\n public String number;\n\n public NumberEntry(String number) {\n this.number = number;\n }\n }\n\n private static String formatNumber(Context context, String number, String activeMcc, int networkType) {\n if (number == null) {\n throw new IllegalArgumentException(\"number is null\");\n } else if (activeMcc == null || activeMcc.trim().length() == 0) {\n throw new IllegalArgumentException(\"activeMcc is null or empty!\");\n } else {\n String networkPortionNumber = PhoneNumberUtils.extractNetworkPortion(number);\n if (networkPortionNumber == null || networkPortionNumber.length() == 0) {\n throw new IllegalArgumentException(\"Number is invalid!\");\n }\n StringBuilder stringBuilder;\n NumberEntry numberEntry = new NumberEntry(networkPortionNumber);\n ArrayList allIDDs = getAllIDDs(context, activeMcc);\n int nanpState = checkNANP(numberEntry, allIDDs);\n if (DBG) {\n String str = TAG;\n stringBuilder = new StringBuilder();\n stringBuilder.append(\"NANP type: \");\n stringBuilder.append(getNumberPlanType(nanpState));\n Rlog.d(str, stringBuilder.toString());\n }\n if (nanpState == 1 || nanpState == 2 || nanpState == 3) {\n return networkPortionNumber;\n }\n if (nanpState != 4) {\n int iddLength;\n String str2;\n int i = 0;\n if (nanpState == 5) {\n if (networkType == 1) {\n return networkPortionNumber;\n }\n if (networkType == 0) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n iddLength = i;\n stringBuilder = new StringBuilder();\n stringBuilder.append(PLUS_SIGN);\n stringBuilder.append(networkPortionNumber.substring(iddLength));\n return stringBuilder.toString();\n } else if (networkType == 2) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n return networkPortionNumber.substring(i);\n }\n }\n int internationalState = checkInternationalNumberPlan(context, numberEntry, allIDDs, NANP_IDD);\n if (DBG) {\n str2 = TAG;\n StringBuilder stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\"International type: \");\n stringBuilder2.append(getNumberPlanType(internationalState));\n Rlog.d(str2, stringBuilder2.toString());\n }\n str2 = null;\n switch(internationalState) {\n case 100:\n if (networkType == 0) {\n str2 = networkPortionNumber.substring(1);\n break;\n }\n break;\n case 101:\n str2 = networkPortionNumber;\n break;\n case 102:\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(1));\n str2 = stringBuilder.toString();\n break;\n case NP_LOCALIDD_CC_AREA_LOCAL:\n if (networkType == 0 || networkType == 2) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n iddLength = i;\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(iddLength));\n str2 = stringBuilder.toString();\n break;\n }\n case 104:\n int countryCode = numberEntry.countryCode;\n if (!(inExceptionListForNpCcAreaLocal(numberEntry) || networkPortionNumber.length() < 11 || countryCode == 1)) {\n StringBuilder stringBuilder3 = new StringBuilder();\n stringBuilder3.append(NANP_IDD);\n stringBuilder3.append(networkPortionNumber);\n str2 = stringBuilder3.toString();\n break;\n }\n default:\n if (networkPortionNumber.startsWith(PLUS_SIGN) && (networkType == 1 || networkType == 2)) {\n if (!networkPortionNumber.startsWith(\"+011\")) {\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(1));\n str2 = stringBuilder.toString();\n break;\n }\n str2 = networkPortionNumber.substring(1);\n break;\n }\n }\n if (str2 == null) {\n str2 = networkPortionNumber;\n }\n return str2;\n } else if (networkType == 1 || networkType == 2) {\n return networkPortionNumber.substring(1);\n } else {\n return networkPortionNumber;\n }\n }\n }\n\n /* Code decompiled incorrectly, please refer to instructions dump. */\n private static ArrayList getAllIDDs(Context context, String mcc) {\n ArrayList allIDDs = (ArrayList) IDDS_MAPS.get(mcc);\n if (allIDDs != null) {\n return allIDDs;\n }\n allIDDs = new ArrayList();\n String[] projection = new String[] { MccIdd.IDD, \"MCC\" };\n String where = null;\n String[] selectionArgs = null;\n if (mcc != null) {\n where = \"MCC=?\";\n selectionArgs = new String[] { mcc };\n }\n Cursor cursor = null;\n try {\n cursor = context.getContentResolver().query(MccIdd.CONTENT_URI, projection, where, selectionArgs, null);\n if (cursor.getCount() > 0) {\n while (cursor.moveToNext()) {\n String idd = cursor.getString(0);\n if (!allIDDs.contains(idd)) {\n allIDDs.add(idd);\n }\n }\n }\n } catch (SQLException e) {\n Rlog.e(TAG, \"Can't access HbpcdLookup database\", e);\n } catch (Throwable th) {\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n private static int checkNANP(NumberEntry numberEntry, ArrayList allIDDs) {\n boolean isNANP = false;\n String number = numberEntry.number;\n if (number.length() == 7) {\n char firstChar = number.charAt(0);\n if (firstChar >= '2' && firstChar <= '9') {\n isNANP = true;\n ", "post_mask_code": "\n }\n if (isNANP) {\n return 1;\n }\n } else if (number.length() == 10) {\n if (isNANP(number)) {\n return 2;\n }\n } else if (number.length() == 11) {\n if (isNANP(number)) {\n return 3;\n }\n } else if (number.startsWith(PLUS_SIGN)) {\n number = number.substring(1);\n if (number.length() == 11) {\n if (isNANP(number)) {\n return 4;\n }\n } else if (number.startsWith(NANP_IDD) && number.length() == 14 && isNANP(number.substring(3))) {\n return 6;\n }\n } else {\n Iterator it = allIDDs.iterator();\n while (it.hasNext()) {\n String idd = (String) it.next();\n if (number.startsWith(idd)) {\n String number2 = number.substring(idd.length());\n if (number2 != null && number2.startsWith(String.valueOf(1)) && isNANP(number2)) {\n numberEntry.IDD = idd;\n return 5;\n }\n }\n }\n }\n return 0;\n }\n\n private static boolean isNANP(String number) {\n if (number.length() != 10 && (number.length() != 11 || !number.startsWith(\"1\"))) {\n return false;\n }\n if (number.length() == 11) {\n number = number.substring(1);\n }\n return PhoneNumberUtils.isNanp(number);\n }\n\n private static int checkInternationalNumberPlan(Context context, NumberEntry numberEntry, ArrayList allIDDs, String homeIDD) {\n String number = numberEntry.number;\n int countryCode;\n int countryCode2;\n if (number.startsWith(PLUS_SIGN)) {\n String numberNoNBPCD = number.substring(1);\n if (numberNoNBPCD.startsWith(homeIDD)) {\n int countryCode3 = getCountryCode(context, numberNoNBPCD.substring(homeIDD.length()));\n countryCode = countryCode3;\n if (countryCode3 > 0) {\n numberEntry.countryCode = countryCode;\n return 100;\n }\n }\n countryCode2 = getCountryCode(context, numberNoNBPCD);\n countryCode = countryCode2;\n if (countryCode2 > 0) {\n numberEntry.countryCode = countryCode;\n return 102;\n }\n } else if (number.startsWith(homeIDD)) {\n countryCode2 = getCountryCode(context, number.substring(homeIDD.length()));\n countryCode = countryCode2;\n if (countryCode2 > 0) {\n numberEntry.countryCode = countryCode;\n return 101;\n }\n } else {\n Iterator it = allIDDs.iterator();\n while (it.hasNext()) {\n String exitCode = (String) it.next();\n if (number.startsWith(exitCode)) {\n int countryCode4 = getCountryCode(context, number.substring(exitCode.length()));\n countryCode = countryCode4;\n if (countryCode4 > 0) {\n numberEntry.countryCode = countryCode;\n numberEntry.IDD = exitCode;\n return NP_LOCALIDD_CC_AREA_LOCAL;\n }\n }\n }\n if (!number.startsWith(ProxyController.MODEM_0)) {\n int countryCode5 = getCountryCode(context, number);\n countryCode = countryCode5;\n if (countryCode5 > 0) {\n numberEntry.countryCode = countryCode;\n return 104;\n }\n }\n }\n return 0;\n }\n\n private static int getCountryCode(Context context, String number) {\n if (number.length() >= 10) {\n int[] allCCs = getAllCountryCodes(context);\n if (allCCs == null) {\n return -1;\n }\n int i;\n int[] ccArray = new int[MAX_COUNTRY_CODES_LENGTH];\n for (i = 0; i < MAX_COUNTRY_CODES_LENGTH; i++) {\n ccArray[i] = Integer.parseInt(number.substring(0, i + 1));\n }\n for (int tempCC : allCCs) {\n for (int j = 0; j < MAX_COUNTRY_CODES_LENGTH; j++) {\n if (tempCC == ccArray[j]) {\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"Country code = \");\n stringBuilder.append(tempCC);\n Rlog.d(str, stringBuilder.toString());\n }\n return tempCC;\n }\n }\n }\n }\n return -1;\n }\n\n /* Code decompiled incorrectly, please refer to instructions dump. */\n private static int[] getAllCountryCodes(Context context) {\n if (ALL_COUNTRY_CODES != null) {\n return ALL_COUNTRY_CODES;\n }\n Cursor cursor = null;\n try {\n cursor = context.getContentResolver().query(MccLookup.CONTENT_URI, new String[] { MccLookup.COUNTRY_CODE }, null, null, null);\n if (cursor.getCount() > 0) {\n ALL_COUNTRY_CODES = new int[cursor.getCount()];\n int i = 0;\n while (cursor.moveToNext()) {\n int countryCode = cursor.getInt(0);\n int i2 = i + 1;\n ALL_COUNTRY_CODES[i] = countryCode;\n i = String.valueOf(countryCode).trim().length();\n if (i > MAX_COUNTRY_CODES_LENGTH) {\n MAX_COUNTRY_CODES_LENGTH = i;\n }\n i = i2;\n }\n }\n } catch (SQLException e) {\n Rlog.e(TAG, \"Can't access HbpcdLookup database\", e);\n } catch (Throwable th) {\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n private static boolean inExceptionListForNpCcAreaLocal(NumberEntry numberEntry) {\n int countryCode = numberEntry.countryCode;\n return numberEntry.number.length() == 12 && (countryCode == 7 || countryCode == 20 || countryCode == 65 || countryCode == 90);\n }\n\n private static String getNumberPlanType(int state) {\n String numberPlanType = new StringBuilder();\n numberPlanType.append(\"Number Plan type (\");\n numberPlanType.append(state);\n numberPlanType.append(\"): \");\n numberPlanType = numberPlanType.toString();\n if (state == 1) {\n return \"NP_NANP_LOCAL\";\n }\n if (state == 2) {\n return \"NP_NANP_AREA_LOCAL\";\n }\n if (state == 3) {\n return \"NP_NANP_NDD_AREA_LOCAL\";\n }\n if (state == 4) {\n return \"NP_NANP_NBPCD_CC_AREA_LOCAL\";\n }\n if (state == 5) {\n return \"NP_NANP_LOCALIDD_CC_AREA_LOCAL\";\n }\n if (state == 6) {\n return \"NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 100) {\n return \"NP_NBPCD_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 101) {\n return \"NP_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 102) {\n return \"NP_NBPCD_CC_AREA_LOCAL\";\n }\n if (state == NP_LOCALIDD_CC_AREA_LOCAL) {\n return \"NP_LOCALIDD_CC_AREA_LOCAL\";\n }\n if (state == 104) {\n return \"NP_CC_AREA_LOCAL\";\n }\n return \"Unknown type\";\n }\n\n public static String filterDestAddr(Phone phone, String destAddr) {\n if (DBG) {\n Rlog.d(TAG, \"enter filterDestAddr. destAddr=\\\"xxxx\\\"\");\n }\n if (destAddr == null || !PhoneNumberUtils.isGlobalPhoneNumber(destAddr)) {\n Rlog.w(TAG, \"destAddr xxxx is not a global phone number! Nothing changed.\");\n return destAddr;\n }\n String networkOperator = TelephonyManager.from(phone.getContext()).getNetworkOperator(phone.getSubId());\n String result = null;\n if (needToConvert(phone)) {\n int networkType = getNetworkType(phone);\n if (!(networkType == -1 || TextUtils.isEmpty(networkOperator))) {\n String networkMcc = networkOperator.substring(null, 3);\n if (networkMcc != null && networkMcc.trim().length() > 0) {\n result = formatNumber(phone.getContext(), destAddr, networkMcc, networkType);\n }\n }\n }\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"destAddr is \");\n stringBuilder.append(result != null ? \"formatted.\" : \"not formatted.\");\n Rlog.d(str, stringBuilder.toString());\n Rlog.d(TAG, \"leave filterDestAddr, new destAddr=\\\"xxxx\\\"\");\n }\n return result != null ? result : destAddr;\n }\n\n private static int getNetworkType(Phone phone) {\n int phoneType = phone.getPhoneType();\n if (phoneType == 1) {\n return 0;\n }\n if (phoneType == 2) {\n if (isInternationalRoaming(phone)) {\n return 2;\n }\n return 1;\n } else if (!DBG) {\n return -1;\n } else {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"warning! unknown mPhoneType value=\");\n stringBuilder.append(phoneType);\n Rlog.w(str, stringBuilder.toString());\n return -1;\n }\n }\n\n private static boolean isInternationalRoaming(Phone phone) {\n String operatorIsoCountry = TelephonyManager.from(phone.getContext()).getNetworkCountryIsoForPhone(phone.getPhoneId());\n String simIsoCountry = TelephonyManager.from(phone.getContext()).getSimCountryIsoForPhone(phone.getPhoneId());\n boolean internationalRoaming = (TextUtils.isEmpty(operatorIsoCountry) || TextUtils.isEmpty(simIsoCountry) || simIsoCountry.equals(operatorIsoCountry)) ? false : true;\n if (!internationalRoaming) {\n return internationalRoaming;\n }\n if (\"us\".equals(simIsoCountry)) {\n return 1 ^ \"vi\".equals(operatorIsoCountry);\n }\n if (\"vi\".equals(simIsoCountry)) {\n return 1 ^ \"us\".equals(operatorIsoCountry);\n }\n return internationalRoaming;\n }\n\n private static boolean needToConvert(Phone phone) {\n long identity = Binder.clearCallingIdentity();\n try {\n CarrierConfigManager configManager = (CarrierConfigManager) phone.getContext().getSystemService(\"carrier_config\");\n if (configManager != null) {\n PersistableBundle bundle = configManager.getConfig();\n if (bundle != null) {\n boolean z = bundle.getBoolean(\"sms_requires_destination_number_conversion_bool\");\n return z;\n }\n }\n Binder.restoreCallingIdentity(identity);\n return false;\n } finally {\n Binder.restoreCallingIdentity(identity);\n }\n }\n\n private static boolean compareGid1(Phone phone, String serviceGid1) {\n String gid1 = phone.getGroupIdLevel1();\n boolean ret = true;\n if (TextUtils.isEmpty(serviceGid1)) {\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"compareGid1 serviceGid is empty, return \");\n stringBuilder.append(true);\n Rlog.d(str, stringBuilder.toString());\n }\n return true;\n }\n String str2;\n StringBuilder stringBuilder2;\n int gid_length = serviceGid1.length();\n if (gid1 == null || gid1.length() < gid_length || !gid1.substring(0, gid_length).equalsIgnoreCase(serviceGid1)) {\n if (DBG) {\n str2 = TAG;\n stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\" gid1 \");\n stringBuilder2.append(gid1);\n stringBuilder2.append(\" serviceGid1 \");\n stringBuilder2.append(serviceGid1);\n Rlog.d(str2, stringBuilder2.toString());\n }\n ret = false;\n }\n if (DBG) {\n str2 = TAG;\n stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\"compareGid1 is \");\n stringBuilder2.append(ret ? \"Same\" : \"Different\");\n Rlog.d(str2, stringBuilder2.toString());\n }\n return ret;\n }\n}\n"} {"task_id": "Java_2487", "language": "Java", "task_type": "while_statement", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_9_0_0/src/main/java/com/android/internal/telephony/SmsNumberUtils.java", "mask_start_position": 9279, "mask_end_position": 9494, "canonical_solution": "while (cursor.moveToNext()) {\n String idd = cursor.getString(0);\n if (!allIDDs.contains(idd)) {\n allIDDs.add(idd);\n }\n }", "pre_mask_code": "package com.android.internal.telephony;\n\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.SQLException;\nimport android.os.Binder;\nimport android.os.Build;\nimport android.os.PersistableBundle;\nimport android.telephony.CarrierConfigManager;\nimport android.telephony.PhoneNumberUtils;\nimport android.telephony.Rlog;\nimport android.telephony.TelephonyManager;\nimport android.text.TextUtils;\nimport com.android.internal.telephony.HbpcdLookup.MccIdd;\nimport com.android.internal.telephony.HbpcdLookup.MccLookup;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\n\npublic class SmsNumberUtils {\n\n private static int[] ALL_COUNTRY_CODES = null;\n\n private static final int CDMA_HOME_NETWORK = 1;\n\n private static final int CDMA_ROAMING_NETWORK = 2;\n\n private static final boolean DBG = Build.IS_DEBUGGABLE;\n\n private static final int GSM_UMTS_NETWORK = 0;\n\n private static HashMap> IDDS_MAPS = new HashMap();\n\n private static int MAX_COUNTRY_CODES_LENGTH = 0;\n\n private static final int MIN_COUNTRY_AREA_LOCAL_LENGTH = 10;\n\n private static final int NANP_CC = 1;\n\n private static final String NANP_IDD = \"011\";\n\n private static final int NANP_LONG_LENGTH = 11;\n\n private static final int NANP_MEDIUM_LENGTH = 10;\n\n private static final String NANP_NDD = \"1\";\n\n private static final int NANP_SHORT_LENGTH = 7;\n\n private static final int NP_CC_AREA_LOCAL = 104;\n\n private static final int NP_HOMEIDD_CC_AREA_LOCAL = 101;\n\n private static final int NP_INTERNATIONAL_BEGIN = 100;\n\n private static final int NP_LOCALIDD_CC_AREA_LOCAL = 103;\n\n private static final int NP_NANP_AREA_LOCAL = 2;\n\n private static final int NP_NANP_BEGIN = 1;\n\n private static final int NP_NANP_LOCAL = 1;\n\n private static final int NP_NANP_LOCALIDD_CC_AREA_LOCAL = 5;\n\n private static final int NP_NANP_NBPCD_CC_AREA_LOCAL = 4;\n\n private static final int NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL = 6;\n\n private static final int NP_NANP_NDD_AREA_LOCAL = 3;\n\n private static final int NP_NBPCD_CC_AREA_LOCAL = 102;\n\n private static final int NP_NBPCD_HOMEIDD_CC_AREA_LOCAL = 100;\n\n private static final int NP_NONE = 0;\n\n private static final String PLUS_SIGN = \"+\";\n\n private static final String TAG = \"SmsNumberUtils\";\n\n private static class NumberEntry {\n\n public String IDD;\n\n public int countryCode;\n\n public String number;\n\n public NumberEntry(String number) {\n this.number = number;\n }\n }\n\n private static String formatNumber(Context context, String number, String activeMcc, int networkType) {\n if (number == null) {\n throw new IllegalArgumentException(\"number is null\");\n } else if (activeMcc == null || activeMcc.trim().length() == 0) {\n throw new IllegalArgumentException(\"activeMcc is null or empty!\");\n } else {\n String networkPortionNumber = PhoneNumberUtils.extractNetworkPortion(number);\n if (networkPortionNumber == null || networkPortionNumber.length() == 0) {\n throw new IllegalArgumentException(\"Number is invalid!\");\n }\n StringBuilder stringBuilder;\n NumberEntry numberEntry = new NumberEntry(networkPortionNumber);\n ArrayList allIDDs = getAllIDDs(context, activeMcc);\n int nanpState = checkNANP(numberEntry, allIDDs);\n if (DBG) {\n String str = TAG;\n stringBuilder = new StringBuilder();\n stringBuilder.append(\"NANP type: \");\n stringBuilder.append(getNumberPlanType(nanpState));\n Rlog.d(str, stringBuilder.toString());\n }\n if (nanpState == 1 || nanpState == 2 || nanpState == 3) {\n return networkPortionNumber;\n }\n if (nanpState != 4) {\n int iddLength;\n String str2;\n int i = 0;\n if (nanpState == 5) {\n if (networkType == 1) {\n return networkPortionNumber;\n }\n if (networkType == 0) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n iddLength = i;\n stringBuilder = new StringBuilder();\n stringBuilder.append(PLUS_SIGN);\n stringBuilder.append(networkPortionNumber.substring(iddLength));\n return stringBuilder.toString();\n } else if (networkType == 2) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n return networkPortionNumber.substring(i);\n }\n }\n int internationalState = checkInternationalNumberPlan(context, numberEntry, allIDDs, NANP_IDD);\n if (DBG) {\n str2 = TAG;\n StringBuilder stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\"International type: \");\n stringBuilder2.append(getNumberPlanType(internationalState));\n Rlog.d(str2, stringBuilder2.toString());\n }\n str2 = null;\n switch(internationalState) {\n case 100:\n if (networkType == 0) {\n str2 = networkPortionNumber.substring(1);\n break;\n }\n break;\n case 101:\n str2 = networkPortionNumber;\n break;\n case 102:\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(1));\n str2 = stringBuilder.toString();\n break;\n case NP_LOCALIDD_CC_AREA_LOCAL:\n if (networkType == 0 || networkType == 2) {\n if (numberEntry.IDD != null) {\n i = numberEntry.IDD.length();\n }\n iddLength = i;\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(iddLength));\n str2 = stringBuilder.toString();\n break;\n }\n case 104:\n int countryCode = numberEntry.countryCode;\n if (!(inExceptionListForNpCcAreaLocal(numberEntry) || networkPortionNumber.length() < 11 || countryCode == 1)) {\n StringBuilder stringBuilder3 = new StringBuilder();\n stringBuilder3.append(NANP_IDD);\n stringBuilder3.append(networkPortionNumber);\n str2 = stringBuilder3.toString();\n break;\n }\n default:\n if (networkPortionNumber.startsWith(PLUS_SIGN) && (networkType == 1 || networkType == 2)) {\n if (!networkPortionNumber.startsWith(\"+011\")) {\n stringBuilder = new StringBuilder();\n stringBuilder.append(NANP_IDD);\n stringBuilder.append(networkPortionNumber.substring(1));\n str2 = stringBuilder.toString();\n break;\n }\n str2 = networkPortionNumber.substring(1);\n break;\n }\n }\n if (str2 == null) {\n str2 = networkPortionNumber;\n }\n return str2;\n } else if (networkType == 1 || networkType == 2) {\n return networkPortionNumber.substring(1);\n } else {\n return networkPortionNumber;\n }\n }\n }\n\n /* Code decompiled incorrectly, please refer to instructions dump. */\n private static ArrayList getAllIDDs(Context context, String mcc) {\n ArrayList allIDDs = (ArrayList) IDDS_MAPS.get(mcc);\n if (allIDDs != null) {\n return allIDDs;\n }\n allIDDs = new ArrayList();\n String[] projection = new String[] { MccIdd.IDD, \"MCC\" };\n String where = null;\n String[] selectionArgs = null;\n if (mcc != null) {\n where = \"MCC=?\";\n selectionArgs = new String[] { mcc };\n }\n Cursor cursor = null;\n try {\n cursor = context.getContentResolver().query(MccIdd.CONTENT_URI, projection, where, selectionArgs, null);\n if (cursor.getCount() > 0) {\n ", "post_mask_code": "\n }\n } catch (SQLException e) {\n Rlog.e(TAG, \"Can't access HbpcdLookup database\", e);\n } catch (Throwable th) {\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n private static int checkNANP(NumberEntry numberEntry, ArrayList allIDDs) {\n boolean isNANP = false;\n String number = numberEntry.number;\n if (number.length() == 7) {\n char firstChar = number.charAt(0);\n if (firstChar >= '2' && firstChar <= '9') {\n isNANP = true;\n for (int i = 1; i < 7; i++) {\n if (!PhoneNumberUtils.isISODigit(number.charAt(i))) {\n isNANP = false;\n break;\n }\n }\n }\n if (isNANP) {\n return 1;\n }\n } else if (number.length() == 10) {\n if (isNANP(number)) {\n return 2;\n }\n } else if (number.length() == 11) {\n if (isNANP(number)) {\n return 3;\n }\n } else if (number.startsWith(PLUS_SIGN)) {\n number = number.substring(1);\n if (number.length() == 11) {\n if (isNANP(number)) {\n return 4;\n }\n } else if (number.startsWith(NANP_IDD) && number.length() == 14 && isNANP(number.substring(3))) {\n return 6;\n }\n } else {\n Iterator it = allIDDs.iterator();\n while (it.hasNext()) {\n String idd = (String) it.next();\n if (number.startsWith(idd)) {\n String number2 = number.substring(idd.length());\n if (number2 != null && number2.startsWith(String.valueOf(1)) && isNANP(number2)) {\n numberEntry.IDD = idd;\n return 5;\n }\n }\n }\n }\n return 0;\n }\n\n private static boolean isNANP(String number) {\n if (number.length() != 10 && (number.length() != 11 || !number.startsWith(\"1\"))) {\n return false;\n }\n if (number.length() == 11) {\n number = number.substring(1);\n }\n return PhoneNumberUtils.isNanp(number);\n }\n\n private static int checkInternationalNumberPlan(Context context, NumberEntry numberEntry, ArrayList allIDDs, String homeIDD) {\n String number = numberEntry.number;\n int countryCode;\n int countryCode2;\n if (number.startsWith(PLUS_SIGN)) {\n String numberNoNBPCD = number.substring(1);\n if (numberNoNBPCD.startsWith(homeIDD)) {\n int countryCode3 = getCountryCode(context, numberNoNBPCD.substring(homeIDD.length()));\n countryCode = countryCode3;\n if (countryCode3 > 0) {\n numberEntry.countryCode = countryCode;\n return 100;\n }\n }\n countryCode2 = getCountryCode(context, numberNoNBPCD);\n countryCode = countryCode2;\n if (countryCode2 > 0) {\n numberEntry.countryCode = countryCode;\n return 102;\n }\n } else if (number.startsWith(homeIDD)) {\n countryCode2 = getCountryCode(context, number.substring(homeIDD.length()));\n countryCode = countryCode2;\n if (countryCode2 > 0) {\n numberEntry.countryCode = countryCode;\n return 101;\n }\n } else {\n Iterator it = allIDDs.iterator();\n while (it.hasNext()) {\n String exitCode = (String) it.next();\n if (number.startsWith(exitCode)) {\n int countryCode4 = getCountryCode(context, number.substring(exitCode.length()));\n countryCode = countryCode4;\n if (countryCode4 > 0) {\n numberEntry.countryCode = countryCode;\n numberEntry.IDD = exitCode;\n return NP_LOCALIDD_CC_AREA_LOCAL;\n }\n }\n }\n if (!number.startsWith(ProxyController.MODEM_0)) {\n int countryCode5 = getCountryCode(context, number);\n countryCode = countryCode5;\n if (countryCode5 > 0) {\n numberEntry.countryCode = countryCode;\n return 104;\n }\n }\n }\n return 0;\n }\n\n private static int getCountryCode(Context context, String number) {\n if (number.length() >= 10) {\n int[] allCCs = getAllCountryCodes(context);\n if (allCCs == null) {\n return -1;\n }\n int i;\n int[] ccArray = new int[MAX_COUNTRY_CODES_LENGTH];\n for (i = 0; i < MAX_COUNTRY_CODES_LENGTH; i++) {\n ccArray[i] = Integer.parseInt(number.substring(0, i + 1));\n }\n for (int tempCC : allCCs) {\n for (int j = 0; j < MAX_COUNTRY_CODES_LENGTH; j++) {\n if (tempCC == ccArray[j]) {\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"Country code = \");\n stringBuilder.append(tempCC);\n Rlog.d(str, stringBuilder.toString());\n }\n return tempCC;\n }\n }\n }\n }\n return -1;\n }\n\n /* Code decompiled incorrectly, please refer to instructions dump. */\n private static int[] getAllCountryCodes(Context context) {\n if (ALL_COUNTRY_CODES != null) {\n return ALL_COUNTRY_CODES;\n }\n Cursor cursor = null;\n try {\n cursor = context.getContentResolver().query(MccLookup.CONTENT_URI, new String[] { MccLookup.COUNTRY_CODE }, null, null, null);\n if (cursor.getCount() > 0) {\n ALL_COUNTRY_CODES = new int[cursor.getCount()];\n int i = 0;\n while (cursor.moveToNext()) {\n int countryCode = cursor.getInt(0);\n int i2 = i + 1;\n ALL_COUNTRY_CODES[i] = countryCode;\n i = String.valueOf(countryCode).trim().length();\n if (i > MAX_COUNTRY_CODES_LENGTH) {\n MAX_COUNTRY_CODES_LENGTH = i;\n }\n i = i2;\n }\n }\n } catch (SQLException e) {\n Rlog.e(TAG, \"Can't access HbpcdLookup database\", e);\n } catch (Throwable th) {\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n private static boolean inExceptionListForNpCcAreaLocal(NumberEntry numberEntry) {\n int countryCode = numberEntry.countryCode;\n return numberEntry.number.length() == 12 && (countryCode == 7 || countryCode == 20 || countryCode == 65 || countryCode == 90);\n }\n\n private static String getNumberPlanType(int state) {\n String numberPlanType = new StringBuilder();\n numberPlanType.append(\"Number Plan type (\");\n numberPlanType.append(state);\n numberPlanType.append(\"): \");\n numberPlanType = numberPlanType.toString();\n if (state == 1) {\n return \"NP_NANP_LOCAL\";\n }\n if (state == 2) {\n return \"NP_NANP_AREA_LOCAL\";\n }\n if (state == 3) {\n return \"NP_NANP_NDD_AREA_LOCAL\";\n }\n if (state == 4) {\n return \"NP_NANP_NBPCD_CC_AREA_LOCAL\";\n }\n if (state == 5) {\n return \"NP_NANP_LOCALIDD_CC_AREA_LOCAL\";\n }\n if (state == 6) {\n return \"NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 100) {\n return \"NP_NBPCD_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 101) {\n return \"NP_HOMEIDD_CC_AREA_LOCAL\";\n }\n if (state == 102) {\n return \"NP_NBPCD_CC_AREA_LOCAL\";\n }\n if (state == NP_LOCALIDD_CC_AREA_LOCAL) {\n return \"NP_LOCALIDD_CC_AREA_LOCAL\";\n }\n if (state == 104) {\n return \"NP_CC_AREA_LOCAL\";\n }\n return \"Unknown type\";\n }\n\n public static String filterDestAddr(Phone phone, String destAddr) {\n if (DBG) {\n Rlog.d(TAG, \"enter filterDestAddr. destAddr=\\\"xxxx\\\"\");\n }\n if (destAddr == null || !PhoneNumberUtils.isGlobalPhoneNumber(destAddr)) {\n Rlog.w(TAG, \"destAddr xxxx is not a global phone number! Nothing changed.\");\n return destAddr;\n }\n String networkOperator = TelephonyManager.from(phone.getContext()).getNetworkOperator(phone.getSubId());\n String result = null;\n if (needToConvert(phone)) {\n int networkType = getNetworkType(phone);\n if (!(networkType == -1 || TextUtils.isEmpty(networkOperator))) {\n String networkMcc = networkOperator.substring(null, 3);\n if (networkMcc != null && networkMcc.trim().length() > 0) {\n result = formatNumber(phone.getContext(), destAddr, networkMcc, networkType);\n }\n }\n }\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"destAddr is \");\n stringBuilder.append(result != null ? \"formatted.\" : \"not formatted.\");\n Rlog.d(str, stringBuilder.toString());\n Rlog.d(TAG, \"leave filterDestAddr, new destAddr=\\\"xxxx\\\"\");\n }\n return result != null ? result : destAddr;\n }\n\n private static int getNetworkType(Phone phone) {\n int phoneType = phone.getPhoneType();\n if (phoneType == 1) {\n return 0;\n }\n if (phoneType == 2) {\n if (isInternationalRoaming(phone)) {\n return 2;\n }\n return 1;\n } else if (!DBG) {\n return -1;\n } else {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"warning! unknown mPhoneType value=\");\n stringBuilder.append(phoneType);\n Rlog.w(str, stringBuilder.toString());\n return -1;\n }\n }\n\n private static boolean isInternationalRoaming(Phone phone) {\n String operatorIsoCountry = TelephonyManager.from(phone.getContext()).getNetworkCountryIsoForPhone(phone.getPhoneId());\n String simIsoCountry = TelephonyManager.from(phone.getContext()).getSimCountryIsoForPhone(phone.getPhoneId());\n boolean internationalRoaming = (TextUtils.isEmpty(operatorIsoCountry) || TextUtils.isEmpty(simIsoCountry) || simIsoCountry.equals(operatorIsoCountry)) ? false : true;\n if (!internationalRoaming) {\n return internationalRoaming;\n }\n if (\"us\".equals(simIsoCountry)) {\n return 1 ^ \"vi\".equals(operatorIsoCountry);\n }\n if (\"vi\".equals(simIsoCountry)) {\n return 1 ^ \"us\".equals(operatorIsoCountry);\n }\n return internationalRoaming;\n }\n\n private static boolean needToConvert(Phone phone) {\n long identity = Binder.clearCallingIdentity();\n try {\n CarrierConfigManager configManager = (CarrierConfigManager) phone.getContext().getSystemService(\"carrier_config\");\n if (configManager != null) {\n PersistableBundle bundle = configManager.getConfig();\n if (bundle != null) {\n boolean z = bundle.getBoolean(\"sms_requires_destination_number_conversion_bool\");\n return z;\n }\n }\n Binder.restoreCallingIdentity(identity);\n return false;\n } finally {\n Binder.restoreCallingIdentity(identity);\n }\n }\n\n private static boolean compareGid1(Phone phone, String serviceGid1) {\n String gid1 = phone.getGroupIdLevel1();\n boolean ret = true;\n if (TextUtils.isEmpty(serviceGid1)) {\n if (DBG) {\n String str = TAG;\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"compareGid1 serviceGid is empty, return \");\n stringBuilder.append(true);\n Rlog.d(str, stringBuilder.toString());\n }\n return true;\n }\n String str2;\n StringBuilder stringBuilder2;\n int gid_length = serviceGid1.length();\n if (gid1 == null || gid1.length() < gid_length || !gid1.substring(0, gid_length).equalsIgnoreCase(serviceGid1)) {\n if (DBG) {\n str2 = TAG;\n stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\" gid1 \");\n stringBuilder2.append(gid1);\n stringBuilder2.append(\" serviceGid1 \");\n stringBuilder2.append(serviceGid1);\n Rlog.d(str2, stringBuilder2.toString());\n }\n ret = false;\n }\n if (DBG) {\n str2 = TAG;\n stringBuilder2 = new StringBuilder();\n stringBuilder2.append(\"compareGid1 is \");\n stringBuilder2.append(ret ? \"Same\" : \"Different\");\n Rlog.d(str2, stringBuilder2.toString());\n }\n return ret;\n }\n}\n"} {"task_id": "Java_2488", "language": "Java", "task_type": "method_signature", "source_file": "java/github/vaadin/valo-demo/src/main/java/com/vaadin/tests/themes/valo/Tables.java", "mask_start_position": 11303, "mask_end_position": 11402, "canonical_solution": "@Override\n public Object generateCell(Table source, Object itemId, Object columnId) ", "pre_mask_code": "package com.vaadin.tests.themes.valo;\n\nimport com.vaadin.data.Container;\nimport com.vaadin.data.Property.ValueChangeEvent;\nimport com.vaadin.data.Property.ValueChangeListener;\nimport com.vaadin.data.util.IndexedContainer;\nimport com.vaadin.event.dd.DragAndDropEvent;\nimport com.vaadin.event.dd.DropHandler;\nimport com.vaadin.event.dd.acceptcriteria.AcceptAll;\nimport com.vaadin.event.dd.acceptcriteria.AcceptCriterion;\nimport com.vaadin.navigator.View;\nimport com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;\nimport com.vaadin.shared.ui.label.ContentMode;\nimport com.vaadin.ui.Button;\nimport com.vaadin.ui.CheckBox;\nimport com.vaadin.ui.ComboBox;\nimport com.vaadin.ui.DateField;\nimport com.vaadin.ui.Grid;\nimport com.vaadin.ui.Grid.Column;\nimport com.vaadin.ui.Grid.SelectionMode;\nimport com.vaadin.ui.HorizontalLayout;\nimport com.vaadin.ui.Label;\nimport com.vaadin.ui.Notification;\nimport com.vaadin.ui.OptionGroup;\nimport com.vaadin.ui.ProgressBar;\nimport com.vaadin.ui.Slider;\nimport com.vaadin.ui.Table;\nimport com.vaadin.ui.Table.Align;\nimport com.vaadin.ui.Table.ColumnGenerator;\nimport com.vaadin.ui.Table.RowHeaderMode;\nimport com.vaadin.ui.Table.TableDragMode;\nimport com.vaadin.ui.TextField;\nimport com.vaadin.ui.TreeTable;\nimport com.vaadin.ui.VerticalLayout;\nimport com.vaadin.ui.themes.ValoTheme;\n\npublic class Tables extends VerticalLayout implements View {\n\n final IndexedContainer normalContainer = ValoThemeUI.generateContainer(200, false);\n\n final IndexedContainer gridContainer = ValoThemeUI.generateContainer(200, false);\n\n final Container hierarchicalContainer = ValoThemeUI.generateContainer(200, true);\n\n CheckBox hierarchical = new CheckBox(\"Hierarchical\");\n\n CheckBox footer = new CheckBox(\"Footer\", true);\n\n CheckBox sized = new CheckBox(\"Sized\");\n\n CheckBox expandRatios = new CheckBox(\"Expand ratios\");\n\n CheckBox stripes = new CheckBox(\"Stripes\", true);\n\n CheckBox verticalLines = new CheckBox(\"Vertical lines\", true);\n\n CheckBox horizontalLines = new CheckBox(\"Horizontal lines\", true);\n\n CheckBox borderless = new CheckBox(\"Borderless\");\n\n CheckBox headers = new CheckBox(\"Header\", true);\n\n CheckBox compact = new CheckBox(\"Compact\");\n\n CheckBox small = new CheckBox(\"Small\");\n\n CheckBox rowIndex = new CheckBox(\"Row index\", false);\n\n CheckBox rowIcon = new CheckBox(\"Row icon\", false);\n\n CheckBox rowCaption = new CheckBox(\"Row caption\", false);\n\n CheckBox componentsInCells = new CheckBox(\"Components in Cells\", false);\n\n Table table;\n\n Grid grid;\n\n public Tables() {\n setMargin(true);\n setSpacing(true);\n Label h1 = new Label(\"Tables & Grids\");\n h1.addStyleName(ValoTheme.LABEL_H1);\n addComponent(h1);\n Label disclaimer = new Label(\"

Note that most of the toggles only affect the Table component. The Grid component supports footers, expand ratios, row indexes/captions/icons and cell renderers, but those have not been implemented here.

\", ContentMode.HTML);\n disclaimer.setCaption(\"Toggle features/styles\");\n addComponent(disclaimer);\n disclaimer.addStyleName(ValoTheme.LABEL_SMALL);\n HorizontalLayout wrap = new HorizontalLayout();\n wrap.addStyleName(ValoTheme.LAYOUT_HORIZONTAL_WRAPPING);\n wrap.setSpacing(true);\n addComponent(wrap);\n wrap.addComponents(hierarchical, footer, sized, expandRatios, stripes, verticalLines, horizontalLines, borderless, headers, compact, small, rowIndex, rowCaption, rowIcon, componentsInCells);\n ValueChangeListener update = new ValueChangeListener() {\n\n @Override\n public void valueChange(ValueChangeEvent event) {\n if (table == null) {\n table = new Table(\"Table component\");\n table.setContainerDataSource(normalContainer);\n addComponent(table);\n }\n if (grid == null) {\n grid = new Grid(\"Grid component\");\n grid.setContainerDataSource(gridContainer);\n addComponent(grid);\n }\n if (hierarchical.getValue() && table instanceof Table) {\n removeComponent(table);\n table = new TreeTable();\n table.setContainerDataSource(hierarchicalContainer);\n addComponent(table);\n removeComponent(grid);\n } else if (!hierarchical.getValue() && table instanceof TreeTable) {\n removeComponent(table);\n table = new Table();\n table.setContainerDataSource(normalContainer);\n addComponent(table);\n addComponent(grid);\n }\n configure(table, grid, footer.getValue(), sized.getValue(), expandRatios.getValue(), stripes.getValue(), verticalLines.getValue(), horizontalLines.getValue(), borderless.getValue(), headers.getValue(), compact.getValue(), small.getValue(), rowIndex.getValue(), rowCaption.getValue(), rowIcon.getValue(), componentsInCells.getValue());\n }\n };\n hierarchical.addValueChangeListener(update);\n footer.addValueChangeListener(update);\n sized.addValueChangeListener(update);\n expandRatios.addValueChangeListener(update);\n stripes.addValueChangeListener(update);\n verticalLines.addValueChangeListener(update);\n horizontalLines.addValueChangeListener(update);\n borderless.addValueChangeListener(update);\n headers.addValueChangeListener(update);\n compact.addValueChangeListener(update);\n small.addValueChangeListener(update);\n rowIndex.addValueChangeListener(update);\n rowCaption.addValueChangeListener(update);\n rowIcon.addValueChangeListener(update);\n componentsInCells.addValueChangeListener(update);\n footer.setValue(false);\n }\n\n static void configure(Table table, Grid grid, boolean footer, boolean sized, boolean expandRatios, boolean stripes, boolean verticalLines, boolean horizontalLines, boolean borderless, boolean headers, boolean compact, boolean small, boolean rowIndex, boolean rowCaption, boolean rowIcon, boolean componentsInRows) {\n table.setSelectable(true);\n table.setMultiSelect(true);\n grid.setSelectionMode(SelectionMode.MULTI);\n table.setSortEnabled(true);\n for (Column c : grid.getColumns()) {\n if (!c.getPropertyId().equals(\"icon\")) {\n c.setSortable(true);\n }\n c.setHidable(true);\n }\n table.setColumnCollapsingAllowed(true);\n table.setColumnReorderingAllowed(true);\n grid.setColumnReorderingAllowed(true);\n table.setPageLength(6);\n grid.setHeightByRows(6);\n table.addActionHandler(ValoThemeUI.getActionHandler());\n table.setDragMode(TableDragMode.MULTIROW);\n table.setDropHandler(new DropHandler() {\n\n @Override\n public AcceptCriterion getAcceptCriterion() {\n return AcceptAll.get();\n }\n\n @Override\n public void drop(DragAndDropEvent event) {\n Notification.show(event.getTransferable().toString());\n }\n });\n table.setColumnAlignment(ValoThemeUI.DESCRIPTION_PROPERTY, Align.RIGHT);\n table.setColumnAlignment(ValoThemeUI.INDEX_PROPERTY, Align.CENTER);\n table.removeContainerProperty(\"textfield\");\n table.removeGeneratedColumn(\"textfield\");\n table.removeContainerProperty(\"button\");\n table.removeGeneratedColumn(\"button\");\n table.removeContainerProperty(\"label\");\n table.removeGeneratedColumn(\"label\");\n table.removeContainerProperty(\"checkbox\");\n table.removeGeneratedColumn(\"checkbox\");\n table.removeContainerProperty(\"datefield\");\n table.removeGeneratedColumn(\"datefield\");\n table.removeContainerProperty(\"combobox\");\n table.removeGeneratedColumn(\"combobox\");\n table.removeContainerProperty(\"optiongroup\");\n table.removeGeneratedColumn(\"optiongroup\");\n table.removeContainerProperty(\"slider\");\n table.removeGeneratedColumn(\"slider\");\n table.removeContainerProperty(\"progress\");\n table.removeGeneratedColumn(\"progress\");\n if (componentsInRows) {\n table.addContainerProperty(\"textfield\", TextField.class, null);\n table.addGeneratedColumn(\"textfield\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n TextField tf = new TextField();\n tf.setInputPrompt(\"Type here…\");\n if ((Integer) itemId % 2 == 0) {\n tf.addStyleName(ValoTheme.TABLE_BORDERLESS);\n }\n return tf;\n }\n });\n table.addContainerProperty(\"datefield\", TextField.class, null);\n table.addGeneratedColumn(\"datefield\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n DateField tf = new DateField();\n tf.addStyleName(ValoTheme.TABLE_COMPACT);\n if ((Integer) itemId % 2 == 0) {\n tf.addStyleName(ValoTheme.DATEFIELD_BORDERLESS);\n }\n return tf;\n }\n });\n table.addContainerProperty(\"combobox\", TextField.class, null);\n table.addGeneratedColumn(\"combobox\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n ComboBox tf = new ComboBox();\n tf.setInputPrompt(\"Select\");\n tf.addStyleName(ValoTheme.TABLE_COMPACT);\n if ((Integer) itemId % 2 == 0) {\n tf.addStyleName(ValoTheme.DATEFIELD_BORDERLESS);\n }\n return tf;\n }\n });\n table.addContainerProperty(\"button\", Button.class, null);\n table.addGeneratedColumn(\"button\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n Button b = new Button(\"Button\");\n b.addStyleName(ValoTheme.BUTTON_SMALL);\n return b;\n }\n });\n table.addContainerProperty(\"label\", TextField.class, null);\n table.addGeneratedColumn(\"label\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n Label label = new Label(\"Label component\");\n label.setSizeUndefined();\n label.addStyleName(ValoTheme.LABEL_BOLD);\n return label;\n }\n });\n table.addContainerProperty(\"checkbox\", TextField.class, null);\n table.addGeneratedColumn(\"checkbox\", new ColumnGenerator() {\n\n ", "post_mask_code": "{\n CheckBox cb = new CheckBox(null, true);\n return cb;\n }\n });\n table.addContainerProperty(\"optiongroup\", TextField.class, null);\n table.addGeneratedColumn(\"optiongroup\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n OptionGroup op = new OptionGroup();\n op.addItem(\"Male\");\n op.addItem(\"Female\");\n op.addStyleName(ValoTheme.OPTIONGROUP_HORIZONTAL);\n return op;\n }\n });\n table.addContainerProperty(\"slider\", TextField.class, null);\n table.addGeneratedColumn(\"slider\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n Slider s = new Slider();\n s.setValue(30.0);\n return s;\n }\n });\n table.addContainerProperty(\"progress\", TextField.class, null);\n table.addGeneratedColumn(\"progress\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n ProgressBar bar = new ProgressBar();\n bar.setValue(0.7f);\n return bar;\n }\n });\n }\n table.setFooterVisible(footer);\n if (footer) {\n table.setColumnFooter(ValoThemeUI.CAPTION_PROPERTY, \"caption\");\n table.setColumnFooter(ValoThemeUI.DESCRIPTION_PROPERTY, \"description\");\n table.setColumnFooter(ValoThemeUI.ICON_PROPERTY, \"icon\");\n table.setColumnFooter(ValoThemeUI.INDEX_PROPERTY, \"index\");\n }\n if (sized) {\n table.setWidth(\"400px\");\n grid.setWidth(\"400px\");\n table.setHeight(\"300px\");\n grid.setHeight(\"300px\");\n } else {\n table.setSizeUndefined();\n grid.setSizeUndefined();\n }\n if (componentsInRows) {\n table.setWidth(\"100%\");\n } else {\n table.setWidth(null);\n }\n if (expandRatios) {\n if (!sized) {\n table.setWidth(\"100%\");\n }\n }\n table.setColumnExpandRatio(ValoThemeUI.CAPTION_PROPERTY, expandRatios ? 1.0f : 0);\n table.setColumnExpandRatio(ValoThemeUI.DESCRIPTION_PROPERTY, expandRatios ? 1.0f : 0);\n if (!stripes) {\n table.addStyleName(ValoTheme.TABLE_NO_STRIPES);\n } else {\n table.removeStyleName(ValoTheme.TABLE_NO_STRIPES);\n }\n if (!verticalLines) {\n table.addStyleName(ValoTheme.TABLE_NO_VERTICAL_LINES);\n } else {\n table.removeStyleName(ValoTheme.TABLE_NO_VERTICAL_LINES);\n }\n if (!horizontalLines) {\n table.addStyleName(ValoTheme.TABLE_NO_HORIZONTAL_LINES);\n } else {\n table.removeStyleName(ValoTheme.TABLE_NO_HORIZONTAL_LINES);\n }\n if (borderless) {\n table.addStyleName(ValoTheme.TABLE_BORDERLESS);\n } else {\n table.removeStyleName(ValoTheme.TABLE_BORDERLESS);\n }\n if (!headers) {\n table.addStyleName(ValoTheme.TABLE_NO_HEADER);\n } else {\n table.removeStyleName(ValoTheme.TABLE_NO_HEADER);\n }\n if (compact) {\n table.addStyleName(ValoTheme.TABLE_COMPACT);\n } else {\n table.removeStyleName(ValoTheme.TABLE_COMPACT);\n }\n if (small) {\n table.addStyleName(ValoTheme.TABLE_SMALL);\n } else {\n table.removeStyleName(ValoTheme.TABLE_SMALL);\n }\n if (!rowIndex && !rowCaption && rowIcon) {\n table.setRowHeaderMode(RowHeaderMode.HIDDEN);\n }\n if (rowIndex) {\n table.setRowHeaderMode(RowHeaderMode.INDEX);\n }\n if (rowCaption) {\n table.setRowHeaderMode(RowHeaderMode.PROPERTY);\n table.setItemCaptionPropertyId(ValoThemeUI.CAPTION_PROPERTY);\n } else {\n table.setItemCaptionPropertyId(null);\n }\n if (rowIcon) {\n table.setRowHeaderMode(RowHeaderMode.ICON_ONLY);\n table.setItemIconPropertyId(ValoThemeUI.ICON_PROPERTY);\n } else {\n table.setItemIconPropertyId(null);\n }\n }\n\n @Override\n public void enter(ViewChangeEvent event) {\n // TODO Auto-generated method stub\n }\n}\n"} {"task_id": "Java_2489", "language": "Java", "task_type": "method_body", "source_file": "java/github/vaadin/valo-demo/src/main/java/com/vaadin/tests/themes/valo/Tables.java", "mask_start_position": 10459, "mask_end_position": 10621, "canonical_solution": "{\n Button b = new Button(\"Button\");\n b.addStyleName(ValoTheme.BUTTON_SMALL);\n return b;\n }", "pre_mask_code": "package com.vaadin.tests.themes.valo;\n\nimport com.vaadin.data.Container;\nimport com.vaadin.data.Property.ValueChangeEvent;\nimport com.vaadin.data.Property.ValueChangeListener;\nimport com.vaadin.data.util.IndexedContainer;\nimport com.vaadin.event.dd.DragAndDropEvent;\nimport com.vaadin.event.dd.DropHandler;\nimport com.vaadin.event.dd.acceptcriteria.AcceptAll;\nimport com.vaadin.event.dd.acceptcriteria.AcceptCriterion;\nimport com.vaadin.navigator.View;\nimport com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;\nimport com.vaadin.shared.ui.label.ContentMode;\nimport com.vaadin.ui.Button;\nimport com.vaadin.ui.CheckBox;\nimport com.vaadin.ui.ComboBox;\nimport com.vaadin.ui.DateField;\nimport com.vaadin.ui.Grid;\nimport com.vaadin.ui.Grid.Column;\nimport com.vaadin.ui.Grid.SelectionMode;\nimport com.vaadin.ui.HorizontalLayout;\nimport com.vaadin.ui.Label;\nimport com.vaadin.ui.Notification;\nimport com.vaadin.ui.OptionGroup;\nimport com.vaadin.ui.ProgressBar;\nimport com.vaadin.ui.Slider;\nimport com.vaadin.ui.Table;\nimport com.vaadin.ui.Table.Align;\nimport com.vaadin.ui.Table.ColumnGenerator;\nimport com.vaadin.ui.Table.RowHeaderMode;\nimport com.vaadin.ui.Table.TableDragMode;\nimport com.vaadin.ui.TextField;\nimport com.vaadin.ui.TreeTable;\nimport com.vaadin.ui.VerticalLayout;\nimport com.vaadin.ui.themes.ValoTheme;\n\npublic class Tables extends VerticalLayout implements View {\n\n final IndexedContainer normalContainer = ValoThemeUI.generateContainer(200, false);\n\n final IndexedContainer gridContainer = ValoThemeUI.generateContainer(200, false);\n\n final Container hierarchicalContainer = ValoThemeUI.generateContainer(200, true);\n\n CheckBox hierarchical = new CheckBox(\"Hierarchical\");\n\n CheckBox footer = new CheckBox(\"Footer\", true);\n\n CheckBox sized = new CheckBox(\"Sized\");\n\n CheckBox expandRatios = new CheckBox(\"Expand ratios\");\n\n CheckBox stripes = new CheckBox(\"Stripes\", true);\n\n CheckBox verticalLines = new CheckBox(\"Vertical lines\", true);\n\n CheckBox horizontalLines = new CheckBox(\"Horizontal lines\", true);\n\n CheckBox borderless = new CheckBox(\"Borderless\");\n\n CheckBox headers = new CheckBox(\"Header\", true);\n\n CheckBox compact = new CheckBox(\"Compact\");\n\n CheckBox small = new CheckBox(\"Small\");\n\n CheckBox rowIndex = new CheckBox(\"Row index\", false);\n\n CheckBox rowIcon = new CheckBox(\"Row icon\", false);\n\n CheckBox rowCaption = new CheckBox(\"Row caption\", false);\n\n CheckBox componentsInCells = new CheckBox(\"Components in Cells\", false);\n\n Table table;\n\n Grid grid;\n\n public Tables() {\n setMargin(true);\n setSpacing(true);\n Label h1 = new Label(\"Tables & Grids\");\n h1.addStyleName(ValoTheme.LABEL_H1);\n addComponent(h1);\n Label disclaimer = new Label(\"

Note that most of the toggles only affect the Table component. The Grid component supports footers, expand ratios, row indexes/captions/icons and cell renderers, but those have not been implemented here.

\", ContentMode.HTML);\n disclaimer.setCaption(\"Toggle features/styles\");\n addComponent(disclaimer);\n disclaimer.addStyleName(ValoTheme.LABEL_SMALL);\n HorizontalLayout wrap = new HorizontalLayout();\n wrap.addStyleName(ValoTheme.LAYOUT_HORIZONTAL_WRAPPING);\n wrap.setSpacing(true);\n addComponent(wrap);\n wrap.addComponents(hierarchical, footer, sized, expandRatios, stripes, verticalLines, horizontalLines, borderless, headers, compact, small, rowIndex, rowCaption, rowIcon, componentsInCells);\n ValueChangeListener update = new ValueChangeListener() {\n\n @Override\n public void valueChange(ValueChangeEvent event) {\n if (table == null) {\n table = new Table(\"Table component\");\n table.setContainerDataSource(normalContainer);\n addComponent(table);\n }\n if (grid == null) {\n grid = new Grid(\"Grid component\");\n grid.setContainerDataSource(gridContainer);\n addComponent(grid);\n }\n if (hierarchical.getValue() && table instanceof Table) {\n removeComponent(table);\n table = new TreeTable();\n table.setContainerDataSource(hierarchicalContainer);\n addComponent(table);\n removeComponent(grid);\n } else if (!hierarchical.getValue() && table instanceof TreeTable) {\n removeComponent(table);\n table = new Table();\n table.setContainerDataSource(normalContainer);\n addComponent(table);\n addComponent(grid);\n }\n configure(table, grid, footer.getValue(), sized.getValue(), expandRatios.getValue(), stripes.getValue(), verticalLines.getValue(), horizontalLines.getValue(), borderless.getValue(), headers.getValue(), compact.getValue(), small.getValue(), rowIndex.getValue(), rowCaption.getValue(), rowIcon.getValue(), componentsInCells.getValue());\n }\n };\n hierarchical.addValueChangeListener(update);\n footer.addValueChangeListener(update);\n sized.addValueChangeListener(update);\n expandRatios.addValueChangeListener(update);\n stripes.addValueChangeListener(update);\n verticalLines.addValueChangeListener(update);\n horizontalLines.addValueChangeListener(update);\n borderless.addValueChangeListener(update);\n headers.addValueChangeListener(update);\n compact.addValueChangeListener(update);\n small.addValueChangeListener(update);\n rowIndex.addValueChangeListener(update);\n rowCaption.addValueChangeListener(update);\n rowIcon.addValueChangeListener(update);\n componentsInCells.addValueChangeListener(update);\n footer.setValue(false);\n }\n\n static void configure(Table table, Grid grid, boolean footer, boolean sized, boolean expandRatios, boolean stripes, boolean verticalLines, boolean horizontalLines, boolean borderless, boolean headers, boolean compact, boolean small, boolean rowIndex, boolean rowCaption, boolean rowIcon, boolean componentsInRows) {\n table.setSelectable(true);\n table.setMultiSelect(true);\n grid.setSelectionMode(SelectionMode.MULTI);\n table.setSortEnabled(true);\n for (Column c : grid.getColumns()) {\n if (!c.getPropertyId().equals(\"icon\")) {\n c.setSortable(true);\n }\n c.setHidable(true);\n }\n table.setColumnCollapsingAllowed(true);\n table.setColumnReorderingAllowed(true);\n grid.setColumnReorderingAllowed(true);\n table.setPageLength(6);\n grid.setHeightByRows(6);\n table.addActionHandler(ValoThemeUI.getActionHandler());\n table.setDragMode(TableDragMode.MULTIROW);\n table.setDropHandler(new DropHandler() {\n\n @Override\n public AcceptCriterion getAcceptCriterion() {\n return AcceptAll.get();\n }\n\n @Override\n public void drop(DragAndDropEvent event) {\n Notification.show(event.getTransferable().toString());\n }\n });\n table.setColumnAlignment(ValoThemeUI.DESCRIPTION_PROPERTY, Align.RIGHT);\n table.setColumnAlignment(ValoThemeUI.INDEX_PROPERTY, Align.CENTER);\n table.removeContainerProperty(\"textfield\");\n table.removeGeneratedColumn(\"textfield\");\n table.removeContainerProperty(\"button\");\n table.removeGeneratedColumn(\"button\");\n table.removeContainerProperty(\"label\");\n table.removeGeneratedColumn(\"label\");\n table.removeContainerProperty(\"checkbox\");\n table.removeGeneratedColumn(\"checkbox\");\n table.removeContainerProperty(\"datefield\");\n table.removeGeneratedColumn(\"datefield\");\n table.removeContainerProperty(\"combobox\");\n table.removeGeneratedColumn(\"combobox\");\n table.removeContainerProperty(\"optiongroup\");\n table.removeGeneratedColumn(\"optiongroup\");\n table.removeContainerProperty(\"slider\");\n table.removeGeneratedColumn(\"slider\");\n table.removeContainerProperty(\"progress\");\n table.removeGeneratedColumn(\"progress\");\n if (componentsInRows) {\n table.addContainerProperty(\"textfield\", TextField.class, null);\n table.addGeneratedColumn(\"textfield\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n TextField tf = new TextField();\n tf.setInputPrompt(\"Type here…\");\n if ((Integer) itemId % 2 == 0) {\n tf.addStyleName(ValoTheme.TABLE_BORDERLESS);\n }\n return tf;\n }\n });\n table.addContainerProperty(\"datefield\", TextField.class, null);\n table.addGeneratedColumn(\"datefield\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n DateField tf = new DateField();\n tf.addStyleName(ValoTheme.TABLE_COMPACT);\n if ((Integer) itemId % 2 == 0) {\n tf.addStyleName(ValoTheme.DATEFIELD_BORDERLESS);\n }\n return tf;\n }\n });\n table.addContainerProperty(\"combobox\", TextField.class, null);\n table.addGeneratedColumn(\"combobox\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n ComboBox tf = new ComboBox();\n tf.setInputPrompt(\"Select\");\n tf.addStyleName(ValoTheme.TABLE_COMPACT);\n if ((Integer) itemId % 2 == 0) {\n tf.addStyleName(ValoTheme.DATEFIELD_BORDERLESS);\n }\n return tf;\n }\n });\n table.addContainerProperty(\"button\", Button.class, null);\n table.addGeneratedColumn(\"button\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) ", "post_mask_code": "\n });\n table.addContainerProperty(\"label\", TextField.class, null);\n table.addGeneratedColumn(\"label\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n Label label = new Label(\"Label component\");\n label.setSizeUndefined();\n label.addStyleName(ValoTheme.LABEL_BOLD);\n return label;\n }\n });\n table.addContainerProperty(\"checkbox\", TextField.class, null);\n table.addGeneratedColumn(\"checkbox\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n CheckBox cb = new CheckBox(null, true);\n return cb;\n }\n });\n table.addContainerProperty(\"optiongroup\", TextField.class, null);\n table.addGeneratedColumn(\"optiongroup\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n OptionGroup op = new OptionGroup();\n op.addItem(\"Male\");\n op.addItem(\"Female\");\n op.addStyleName(ValoTheme.OPTIONGROUP_HORIZONTAL);\n return op;\n }\n });\n table.addContainerProperty(\"slider\", TextField.class, null);\n table.addGeneratedColumn(\"slider\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n Slider s = new Slider();\n s.setValue(30.0);\n return s;\n }\n });\n table.addContainerProperty(\"progress\", TextField.class, null);\n table.addGeneratedColumn(\"progress\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n ProgressBar bar = new ProgressBar();\n bar.setValue(0.7f);\n return bar;\n }\n });\n }\n table.setFooterVisible(footer);\n if (footer) {\n table.setColumnFooter(ValoThemeUI.CAPTION_PROPERTY, \"caption\");\n table.setColumnFooter(ValoThemeUI.DESCRIPTION_PROPERTY, \"description\");\n table.setColumnFooter(ValoThemeUI.ICON_PROPERTY, \"icon\");\n table.setColumnFooter(ValoThemeUI.INDEX_PROPERTY, \"index\");\n }\n if (sized) {\n table.setWidth(\"400px\");\n grid.setWidth(\"400px\");\n table.setHeight(\"300px\");\n grid.setHeight(\"300px\");\n } else {\n table.setSizeUndefined();\n grid.setSizeUndefined();\n }\n if (componentsInRows) {\n table.setWidth(\"100%\");\n } else {\n table.setWidth(null);\n }\n if (expandRatios) {\n if (!sized) {\n table.setWidth(\"100%\");\n }\n }\n table.setColumnExpandRatio(ValoThemeUI.CAPTION_PROPERTY, expandRatios ? 1.0f : 0);\n table.setColumnExpandRatio(ValoThemeUI.DESCRIPTION_PROPERTY, expandRatios ? 1.0f : 0);\n if (!stripes) {\n table.addStyleName(ValoTheme.TABLE_NO_STRIPES);\n } else {\n table.removeStyleName(ValoTheme.TABLE_NO_STRIPES);\n }\n if (!verticalLines) {\n table.addStyleName(ValoTheme.TABLE_NO_VERTICAL_LINES);\n } else {\n table.removeStyleName(ValoTheme.TABLE_NO_VERTICAL_LINES);\n }\n if (!horizontalLines) {\n table.addStyleName(ValoTheme.TABLE_NO_HORIZONTAL_LINES);\n } else {\n table.removeStyleName(ValoTheme.TABLE_NO_HORIZONTAL_LINES);\n }\n if (borderless) {\n table.addStyleName(ValoTheme.TABLE_BORDERLESS);\n } else {\n table.removeStyleName(ValoTheme.TABLE_BORDERLESS);\n }\n if (!headers) {\n table.addStyleName(ValoTheme.TABLE_NO_HEADER);\n } else {\n table.removeStyleName(ValoTheme.TABLE_NO_HEADER);\n }\n if (compact) {\n table.addStyleName(ValoTheme.TABLE_COMPACT);\n } else {\n table.removeStyleName(ValoTheme.TABLE_COMPACT);\n }\n if (small) {\n table.addStyleName(ValoTheme.TABLE_SMALL);\n } else {\n table.removeStyleName(ValoTheme.TABLE_SMALL);\n }\n if (!rowIndex && !rowCaption && rowIcon) {\n table.setRowHeaderMode(RowHeaderMode.HIDDEN);\n }\n if (rowIndex) {\n table.setRowHeaderMode(RowHeaderMode.INDEX);\n }\n if (rowCaption) {\n table.setRowHeaderMode(RowHeaderMode.PROPERTY);\n table.setItemCaptionPropertyId(ValoThemeUI.CAPTION_PROPERTY);\n } else {\n table.setItemCaptionPropertyId(null);\n }\n if (rowIcon) {\n table.setRowHeaderMode(RowHeaderMode.ICON_ONLY);\n table.setItemIconPropertyId(ValoThemeUI.ICON_PROPERTY);\n } else {\n table.setItemIconPropertyId(null);\n }\n }\n\n @Override\n public void enter(ViewChangeEvent event) {\n // TODO Auto-generated method stub\n }\n}\n"} {"task_id": "Java_2490", "language": "Java", "task_type": "single_line", "source_file": "java/github/vaadin/valo-demo/src/main/java/com/vaadin/tests/themes/valo/Tables.java", "mask_start_position": 8703, "mask_end_position": 8704, "canonical_solution": ";", "pre_mask_code": "package com.vaadin.tests.themes.valo;\n\nimport com.vaadin.data.Container;\nimport com.vaadin.data.Property.ValueChangeEvent;\nimport com.vaadin.data.Property.ValueChangeListener;\nimport com.vaadin.data.util.IndexedContainer;\nimport com.vaadin.event.dd.DragAndDropEvent;\nimport com.vaadin.event.dd.DropHandler;\nimport com.vaadin.event.dd.acceptcriteria.AcceptAll;\nimport com.vaadin.event.dd.acceptcriteria.AcceptCriterion;\nimport com.vaadin.navigator.View;\nimport com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;\nimport com.vaadin.shared.ui.label.ContentMode;\nimport com.vaadin.ui.Button;\nimport com.vaadin.ui.CheckBox;\nimport com.vaadin.ui.ComboBox;\nimport com.vaadin.ui.DateField;\nimport com.vaadin.ui.Grid;\nimport com.vaadin.ui.Grid.Column;\nimport com.vaadin.ui.Grid.SelectionMode;\nimport com.vaadin.ui.HorizontalLayout;\nimport com.vaadin.ui.Label;\nimport com.vaadin.ui.Notification;\nimport com.vaadin.ui.OptionGroup;\nimport com.vaadin.ui.ProgressBar;\nimport com.vaadin.ui.Slider;\nimport com.vaadin.ui.Table;\nimport com.vaadin.ui.Table.Align;\nimport com.vaadin.ui.Table.ColumnGenerator;\nimport com.vaadin.ui.Table.RowHeaderMode;\nimport com.vaadin.ui.Table.TableDragMode;\nimport com.vaadin.ui.TextField;\nimport com.vaadin.ui.TreeTable;\nimport com.vaadin.ui.VerticalLayout;\nimport com.vaadin.ui.themes.ValoTheme;\n\npublic class Tables extends VerticalLayout implements View {\n\n final IndexedContainer normalContainer = ValoThemeUI.generateContainer(200, false);\n\n final IndexedContainer gridContainer = ValoThemeUI.generateContainer(200, false);\n\n final Container hierarchicalContainer = ValoThemeUI.generateContainer(200, true);\n\n CheckBox hierarchical = new CheckBox(\"Hierarchical\");\n\n CheckBox footer = new CheckBox(\"Footer\", true);\n\n CheckBox sized = new CheckBox(\"Sized\");\n\n CheckBox expandRatios = new CheckBox(\"Expand ratios\");\n\n CheckBox stripes = new CheckBox(\"Stripes\", true);\n\n CheckBox verticalLines = new CheckBox(\"Vertical lines\", true);\n\n CheckBox horizontalLines = new CheckBox(\"Horizontal lines\", true);\n\n CheckBox borderless = new CheckBox(\"Borderless\");\n\n CheckBox headers = new CheckBox(\"Header\", true);\n\n CheckBox compact = new CheckBox(\"Compact\");\n\n CheckBox small = new CheckBox(\"Small\");\n\n CheckBox rowIndex = new CheckBox(\"Row index\", false);\n\n CheckBox rowIcon = new CheckBox(\"Row icon\", false);\n\n CheckBox rowCaption = new CheckBox(\"Row caption\", false);\n\n CheckBox componentsInCells = new CheckBox(\"Components in Cells\", false);\n\n Table table;\n\n Grid grid;\n\n public Tables() {\n setMargin(true);\n setSpacing(true);\n Label h1 = new Label(\"Tables & Grids\");\n h1.addStyleName(ValoTheme.LABEL_H1);\n addComponent(h1);\n Label disclaimer = new Label(\"

Note that most of the toggles only affect the Table component. The Grid component supports footers, expand ratios, row indexes/captions/icons and cell renderers, but those have not been implemented here.

\", ContentMode.HTML);\n disclaimer.setCaption(\"Toggle features/styles\");\n addComponent(disclaimer);\n disclaimer.addStyleName(ValoTheme.LABEL_SMALL);\n HorizontalLayout wrap = new HorizontalLayout();\n wrap.addStyleName(ValoTheme.LAYOUT_HORIZONTAL_WRAPPING);\n wrap.setSpacing(true);\n addComponent(wrap);\n wrap.addComponents(hierarchical, footer, sized, expandRatios, stripes, verticalLines, horizontalLines, borderless, headers, compact, small, rowIndex, rowCaption, rowIcon, componentsInCells);\n ValueChangeListener update = new ValueChangeListener() {\n\n @Override\n public void valueChange(ValueChangeEvent event) {\n if (table == null) {\n table = new Table(\"Table component\");\n table.setContainerDataSource(normalContainer);\n addComponent(table);\n }\n if (grid == null) {\n grid = new Grid(\"Grid component\");\n grid.setContainerDataSource(gridContainer);\n addComponent(grid);\n }\n if (hierarchical.getValue() && table instanceof Table) {\n removeComponent(table);\n table = new TreeTable();\n table.setContainerDataSource(hierarchicalContainer);\n addComponent(table);\n removeComponent(grid);\n } else if (!hierarchical.getValue() && table instanceof TreeTable) {\n removeComponent(table);\n table = new Table();\n table.setContainerDataSource(normalContainer);\n addComponent(table);\n addComponent(grid);\n }\n configure(table, grid, footer.getValue(), sized.getValue(), expandRatios.getValue(), stripes.getValue(), verticalLines.getValue(), horizontalLines.getValue(), borderless.getValue(), headers.getValue(), compact.getValue(), small.getValue(), rowIndex.getValue(), rowCaption.getValue(), rowIcon.getValue(), componentsInCells.getValue());\n }\n };\n hierarchical.addValueChangeListener(update);\n footer.addValueChangeListener(update);\n sized.addValueChangeListener(update);\n expandRatios.addValueChangeListener(update);\n stripes.addValueChangeListener(update);\n verticalLines.addValueChangeListener(update);\n horizontalLines.addValueChangeListener(update);\n borderless.addValueChangeListener(update);\n headers.addValueChangeListener(update);\n compact.addValueChangeListener(update);\n small.addValueChangeListener(update);\n rowIndex.addValueChangeListener(update);\n rowCaption.addValueChangeListener(update);\n rowIcon.addValueChangeListener(update);\n componentsInCells.addValueChangeListener(update);\n footer.setValue(false);\n }\n\n static void configure(Table table, Grid grid, boolean footer, boolean sized, boolean expandRatios, boolean stripes, boolean verticalLines, boolean horizontalLines, boolean borderless, boolean headers, boolean compact, boolean small, boolean rowIndex, boolean rowCaption, boolean rowIcon, boolean componentsInRows) {\n table.setSelectable(true);\n table.setMultiSelect(true);\n grid.setSelectionMode(SelectionMode.MULTI);\n table.setSortEnabled(true);\n for (Column c : grid.getColumns()) {\n if (!c.getPropertyId().equals(\"icon\")) {\n c.setSortable(true);\n }\n c.setHidable(true);\n }\n table.setColumnCollapsingAllowed(true);\n table.setColumnReorderingAllowed(true);\n grid.setColumnReorderingAllowed(true);\n table.setPageLength(6);\n grid.setHeightByRows(6);\n table.addActionHandler(ValoThemeUI.getActionHandler());\n table.setDragMode(TableDragMode.MULTIROW);\n table.setDropHandler(new DropHandler() {\n\n @Override\n public AcceptCriterion getAcceptCriterion() {\n return AcceptAll.get();\n }\n\n @Override\n public void drop(DragAndDropEvent event) {\n Notification.show(event.getTransferable().toString());\n }\n });\n table.setColumnAlignment(ValoThemeUI.DESCRIPTION_PROPERTY, Align.RIGHT);\n table.setColumnAlignment(ValoThemeUI.INDEX_PROPERTY, Align.CENTER);\n table.removeContainerProperty(\"textfield\");\n table.removeGeneratedColumn(\"textfield\");\n table.removeContainerProperty(\"button\");\n table.removeGeneratedColumn(\"button\");\n table.removeContainerProperty(\"label\");\n table.removeGeneratedColumn(\"label\");\n table.removeContainerProperty(\"checkbox\");\n table.removeGeneratedColumn(\"checkbox\");\n table.removeContainerProperty(\"datefield\");\n table.removeGeneratedColumn(\"datefield\");\n table.removeContainerProperty(\"combobox\");\n table.removeGeneratedColumn(\"combobox\");\n table.removeContainerProperty(\"optiongroup\");\n table.removeGeneratedColumn(\"optiongroup\");\n table.removeContainerProperty(\"slider\");\n table.removeGeneratedColumn(\"slider\");\n table.removeContainerProperty(\"progress\");\n table.removeGeneratedColumn(\"progress\");\n if (componentsInRows) {\n table.addContainerProperty(\"textfield\", TextField.class, null);\n table.addGeneratedColumn(\"textfield\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n TextField tf = new TextField()", "post_mask_code": "\n tf.setInputPrompt(\"Type here…\");\n if ((Integer) itemId % 2 == 0) {\n tf.addStyleName(ValoTheme.TABLE_BORDERLESS);\n }\n return tf;\n }\n });\n table.addContainerProperty(\"datefield\", TextField.class, null);\n table.addGeneratedColumn(\"datefield\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n DateField tf = new DateField();\n tf.addStyleName(ValoTheme.TABLE_COMPACT);\n if ((Integer) itemId % 2 == 0) {\n tf.addStyleName(ValoTheme.DATEFIELD_BORDERLESS);\n }\n return tf;\n }\n });\n table.addContainerProperty(\"combobox\", TextField.class, null);\n table.addGeneratedColumn(\"combobox\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n ComboBox tf = new ComboBox();\n tf.setInputPrompt(\"Select\");\n tf.addStyleName(ValoTheme.TABLE_COMPACT);\n if ((Integer) itemId % 2 == 0) {\n tf.addStyleName(ValoTheme.DATEFIELD_BORDERLESS);\n }\n return tf;\n }\n });\n table.addContainerProperty(\"button\", Button.class, null);\n table.addGeneratedColumn(\"button\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n Button b = new Button(\"Button\");\n b.addStyleName(ValoTheme.BUTTON_SMALL);\n return b;\n }\n });\n table.addContainerProperty(\"label\", TextField.class, null);\n table.addGeneratedColumn(\"label\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n Label label = new Label(\"Label component\");\n label.setSizeUndefined();\n label.addStyleName(ValoTheme.LABEL_BOLD);\n return label;\n }\n });\n table.addContainerProperty(\"checkbox\", TextField.class, null);\n table.addGeneratedColumn(\"checkbox\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n CheckBox cb = new CheckBox(null, true);\n return cb;\n }\n });\n table.addContainerProperty(\"optiongroup\", TextField.class, null);\n table.addGeneratedColumn(\"optiongroup\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n OptionGroup op = new OptionGroup();\n op.addItem(\"Male\");\n op.addItem(\"Female\");\n op.addStyleName(ValoTheme.OPTIONGROUP_HORIZONTAL);\n return op;\n }\n });\n table.addContainerProperty(\"slider\", TextField.class, null);\n table.addGeneratedColumn(\"slider\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n Slider s = new Slider();\n s.setValue(30.0);\n return s;\n }\n });\n table.addContainerProperty(\"progress\", TextField.class, null);\n table.addGeneratedColumn(\"progress\", new ColumnGenerator() {\n\n @Override\n public Object generateCell(Table source, Object itemId, Object columnId) {\n ProgressBar bar = new ProgressBar();\n bar.setValue(0.7f);\n return bar;\n }\n });\n }\n table.setFooterVisible(footer);\n if (footer) {\n table.setColumnFooter(ValoThemeUI.CAPTION_PROPERTY, \"caption\");\n table.setColumnFooter(ValoThemeUI.DESCRIPTION_PROPERTY, \"description\");\n table.setColumnFooter(ValoThemeUI.ICON_PROPERTY, \"icon\");\n table.setColumnFooter(ValoThemeUI.INDEX_PROPERTY, \"index\");\n }\n if (sized) {\n table.setWidth(\"400px\");\n grid.setWidth(\"400px\");\n table.setHeight(\"300px\");\n grid.setHeight(\"300px\");\n } else {\n table.setSizeUndefined();\n grid.setSizeUndefined();\n }\n if (componentsInRows) {\n table.setWidth(\"100%\");\n } else {\n table.setWidth(null);\n }\n if (expandRatios) {\n if (!sized) {\n table.setWidth(\"100%\");\n }\n }\n table.setColumnExpandRatio(ValoThemeUI.CAPTION_PROPERTY, expandRatios ? 1.0f : 0);\n table.setColumnExpandRatio(ValoThemeUI.DESCRIPTION_PROPERTY, expandRatios ? 1.0f : 0);\n if (!stripes) {\n table.addStyleName(ValoTheme.TABLE_NO_STRIPES);\n } else {\n table.removeStyleName(ValoTheme.TABLE_NO_STRIPES);\n }\n if (!verticalLines) {\n table.addStyleName(ValoTheme.TABLE_NO_VERTICAL_LINES);\n } else {\n table.removeStyleName(ValoTheme.TABLE_NO_VERTICAL_LINES);\n }\n if (!horizontalLines) {\n table.addStyleName(ValoTheme.TABLE_NO_HORIZONTAL_LINES);\n } else {\n table.removeStyleName(ValoTheme.TABLE_NO_HORIZONTAL_LINES);\n }\n if (borderless) {\n table.addStyleName(ValoTheme.TABLE_BORDERLESS);\n } else {\n table.removeStyleName(ValoTheme.TABLE_BORDERLESS);\n }\n if (!headers) {\n table.addStyleName(ValoTheme.TABLE_NO_HEADER);\n } else {\n table.removeStyleName(ValoTheme.TABLE_NO_HEADER);\n }\n if (compact) {\n table.addStyleName(ValoTheme.TABLE_COMPACT);\n } else {\n table.removeStyleName(ValoTheme.TABLE_COMPACT);\n }\n if (small) {\n table.addStyleName(ValoTheme.TABLE_SMALL);\n } else {\n table.removeStyleName(ValoTheme.TABLE_SMALL);\n }\n if (!rowIndex && !rowCaption && rowIcon) {\n table.setRowHeaderMode(RowHeaderMode.HIDDEN);\n }\n if (rowIndex) {\n table.setRowHeaderMode(RowHeaderMode.INDEX);\n }\n if (rowCaption) {\n table.setRowHeaderMode(RowHeaderMode.PROPERTY);\n table.setItemCaptionPropertyId(ValoThemeUI.CAPTION_PROPERTY);\n } else {\n table.setItemCaptionPropertyId(null);\n }\n if (rowIcon) {\n table.setRowHeaderMode(RowHeaderMode.ICON_ONLY);\n table.setItemIconPropertyId(ValoThemeUI.ICON_PROPERTY);\n } else {\n table.setItemIconPropertyId(null);\n }\n }\n\n @Override\n public void enter(ViewChangeEvent event) {\n // TODO Auto-generated method stub\n }\n}\n"} {"task_id": "Java_2491", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ome/bioformats/components/bio-formats-tools/src/loci/formats/tools/PrintFormatTable.java", "mask_start_position": 6723, "mask_end_position": 6762, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "/*\n * #%L\n * Bio-Formats command line tools for reading and converting files\n * %%\n * - Glencoe Software, Inc.\n * - University of Dundee\n * %%\n * #L%\n */\n/*\nContributed 2009 by the Center for BioImage Informatics, UCSB\n*/\npackage loci.formats.tools;\n\nimport loci.formats.IFormatReader;\nimport loci.formats.IFormatWriter;\nimport loci.formats.ImageReader;\nimport loci.formats.ImageWriter;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Utility class for printing a list of formats supported by Bio-Formats.\n */\npublic class PrintFormatTable {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(PrintFormatTable.class);\n\n public enum PrintStyles {\n\n TXT, XML, HTML\n }\n\n // Text\n public static String getTextHeader() {\n return \"\";\n }\n\n public static String getTextFooter() {\n return \"\";\n }\n\n public static String getTextFormatLine(String name, boolean read, boolean write, boolean wmp, String ext) {\n StringBuffer s = new StringBuffer(name);\n if (read)\n s.append(\": can read\");\n if (write)\n s.append(\", can write\");\n if (wmp)\n s.append(\", can write multiple\");\n s.append(\" (\");\n s.append(ext);\n s.append(\")\");\n return s.toString();\n }\n\n // XML\n public static String getXmlHeader() {\n return \"\\n\";\n }\n\n public static String getXmlFooter() {\n return \"\\n\";\n }\n\n public static String getXmlFormatLine(String name, boolean read, boolean write, boolean wmp, String ext) {\n StringBuffer s = new StringBuffer(\"\\n\");\n if (read)\n s.append(\" \\n\");\n if (write)\n s.append(\" \\n\");\n if (wmp) {\n s.append(\" \\n\");\n }\n s.append(\" \\n\\n\");\n return s.toString();\n }\n\n // HTML\n public static String getHtmlHeader() {\n return \"\" + \"\";\n }\n\n public static String getHtmlFooter() {\n return \"
NameReadingWritingExtensions
\";\n }\n\n public static String getHtmlFormatLine(String name, boolean read, boolean write, String ext) {\n StringBuffer s = new StringBuffer(\" \");\n s.append(name);\n s.append(\"\");\n s.append(read ? \"yes\" : \"no\");\n s.append(\"\");\n s.append(write ? \"yes\" : \"no\");\n s.append(\"\");\n s.append(ext);\n s.append(\"\");\n return s.toString();\n }\n\n public static String getHeader(PrintStyles style) {\n if (style == PrintStyles.XML)\n return getXmlHeader();\n if (style == PrintStyles.HTML)\n return getHtmlHeader();\n if (style == PrintStyles.TXT)\n return getTextHeader();\n return \"\";\n }\n\n public static String getFooter(PrintStyles style) {\n if (style == PrintStyles.XML)\n return getXmlFooter();\n if (style == PrintStyles.HTML)\n return getHtmlFooter();\n if (style == PrintStyles.TXT)\n return getTextFooter();\n return \"\";\n }\n\n public static String getFormatLine(PrintStyles style, String name, boolean read, boolean write, boolean wmp, String ext) {\n if (style == PrintStyles.XML) {\n return getXmlFormatLine(name, read, write, wmp, ext);\n }\n if (style == PrintStyles.HTML) {\n return getHtmlFormatLine(name, read, write, ext);\n }\n if (style == PrintStyles.TXT) {\n return getTextFormatLine(name, read, write, wmp, ext);\n }\n return \"\";\n }\n\n public static void printSupportedFormats(String[] args) {\n PrintStyles printStyle = PrintStyles.TXT;\n boolean usage = false;\n if (args != null) {\n for (int i = 0; i < args.length; i++) {\n if (args[i].equals(\"-help\"))\n usage = true;\n else if (args[i].equals(\"-xml\"))\n printStyle = PrintStyles.XML;\n else if (args[i].equals(\"-html\"))\n printStyle = PrintStyles.HTML;\n else if (args[i].equals(\"-txt\"))\n printStyle = PrintStyles.TXT;\n else {\n LOGGER.warn(\"unknown flag: {}; try -help for options\", args[i]);\n }\n }\n }\n if (usage) {\n LOGGER.info(\"Usage: formatlist [-html] [-txt] [-xml]\");\n LOGGER.info(\" -html: show formats in an HTML table\");\n LOGGER.info(\" -txt: show formats in plaintext (default)\");\n LOGGER.info(\" -xml: show formats as XML data\");\n return;\n }\n LOGGER.info(getHeader(printStyle));\n // retrieve all of the file format readers and writers\n ImageReader baseReader = new ImageReader();\n IFormatReader[] readers = baseReader.getReaders();\n ImageWriter baseWriter = new ImageWriter();\n IFormatWriter[] writers = baseWriter.getWriters();\n for (int i = 0; i < readers.length; i++) {\n String readerFormatName = readers[i].getFormat();\n boolean read = true;\n boolean write = false;\n boolean wmp = false;\n // check if there is a corresponding writer\n IFormatWriter writer = null;\n for (int j = 0; j < writers.length; j++) {\n if (writers[j].getFormat().equals(readerFormatName)) {\n writer = writers[j];\n }\n }\n if (writer != null) {\n write = true;\n // this format can be written\n // determine whether or not multiple images can be\n // written to a single file\n if (writer.canDoStacks())\n wmp = true;\n }\n String[] extensions = readers[i].getSuffixes();\n StringBuilder ext = new StringBuilder();\n for (int j = 0; j < extensions.length; j++) {\n ext.append(extensions[j]);\n if (j < extensions.length - 1) {\n ext.append(\", \");\n }\n }\n // display information about the format\n LOGGER.info(getFormatLine(printStyle, readerFormatName, read, write, wmp, ext.toString()));\n }\n LOGGER.info(getFooter(printStyle));\n }\n\n ", "post_mask_code": "{\n printSupportedFormats(args);\n }\n}\n"} {"task_id": "Java_2492", "language": "Java", "task_type": "method_body", "source_file": "java/github/ome/bioformats/components/bio-formats-tools/src/loci/formats/tools/PrintFormatTable.java", "mask_start_position": 6762, "mask_end_position": 6806, "canonical_solution": "{\n printSupportedFormats(args);\n }", "pre_mask_code": "/*\n * #%L\n * Bio-Formats command line tools for reading and converting files\n * %%\n * - Glencoe Software, Inc.\n * - University of Dundee\n * %%\n * #L%\n */\n/*\nContributed 2009 by the Center for BioImage Informatics, UCSB\n*/\npackage loci.formats.tools;\n\nimport loci.formats.IFormatReader;\nimport loci.formats.IFormatWriter;\nimport loci.formats.ImageReader;\nimport loci.formats.ImageWriter;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Utility class for printing a list of formats supported by Bio-Formats.\n */\npublic class PrintFormatTable {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(PrintFormatTable.class);\n\n public enum PrintStyles {\n\n TXT, XML, HTML\n }\n\n // Text\n public static String getTextHeader() {\n return \"\";\n }\n\n public static String getTextFooter() {\n return \"\";\n }\n\n public static String getTextFormatLine(String name, boolean read, boolean write, boolean wmp, String ext) {\n StringBuffer s = new StringBuffer(name);\n if (read)\n s.append(\": can read\");\n if (write)\n s.append(\", can write\");\n if (wmp)\n s.append(\", can write multiple\");\n s.append(\" (\");\n s.append(ext);\n s.append(\")\");\n return s.toString();\n }\n\n // XML\n public static String getXmlHeader() {\n return \"\\n\";\n }\n\n public static String getXmlFooter() {\n return \"\\n\";\n }\n\n public static String getXmlFormatLine(String name, boolean read, boolean write, boolean wmp, String ext) {\n StringBuffer s = new StringBuffer(\"\\n\");\n if (read)\n s.append(\" \\n\");\n if (write)\n s.append(\" \\n\");\n if (wmp) {\n s.append(\" \\n\");\n }\n s.append(\" \\n\\n\");\n return s.toString();\n }\n\n // HTML\n public static String getHtmlHeader() {\n return \"\" + \"\";\n }\n\n public static String getHtmlFooter() {\n return \"
NameReadingWritingExtensions
\";\n }\n\n public static String getHtmlFormatLine(String name, boolean read, boolean write, String ext) {\n StringBuffer s = new StringBuffer(\" \");\n s.append(name);\n s.append(\"\");\n s.append(read ? \"yes\" : \"no\");\n s.append(\"\");\n s.append(write ? \"yes\" : \"no\");\n s.append(\"\");\n s.append(ext);\n s.append(\"\");\n return s.toString();\n }\n\n public static String getHeader(PrintStyles style) {\n if (style == PrintStyles.XML)\n return getXmlHeader();\n if (style == PrintStyles.HTML)\n return getHtmlHeader();\n if (style == PrintStyles.TXT)\n return getTextHeader();\n return \"\";\n }\n\n public static String getFooter(PrintStyles style) {\n if (style == PrintStyles.XML)\n return getXmlFooter();\n if (style == PrintStyles.HTML)\n return getHtmlFooter();\n if (style == PrintStyles.TXT)\n return getTextFooter();\n return \"\";\n }\n\n public static String getFormatLine(PrintStyles style, String name, boolean read, boolean write, boolean wmp, String ext) {\n if (style == PrintStyles.XML) {\n return getXmlFormatLine(name, read, write, wmp, ext);\n }\n if (style == PrintStyles.HTML) {\n return getHtmlFormatLine(name, read, write, ext);\n }\n if (style == PrintStyles.TXT) {\n return getTextFormatLine(name, read, write, wmp, ext);\n }\n return \"\";\n }\n\n public static void printSupportedFormats(String[] args) {\n PrintStyles printStyle = PrintStyles.TXT;\n boolean usage = false;\n if (args != null) {\n for (int i = 0; i < args.length; i++) {\n if (args[i].equals(\"-help\"))\n usage = true;\n else if (args[i].equals(\"-xml\"))\n printStyle = PrintStyles.XML;\n else if (args[i].equals(\"-html\"))\n printStyle = PrintStyles.HTML;\n else if (args[i].equals(\"-txt\"))\n printStyle = PrintStyles.TXT;\n else {\n LOGGER.warn(\"unknown flag: {}; try -help for options\", args[i]);\n }\n }\n }\n if (usage) {\n LOGGER.info(\"Usage: formatlist [-html] [-txt] [-xml]\");\n LOGGER.info(\" -html: show formats in an HTML table\");\n LOGGER.info(\" -txt: show formats in plaintext (default)\");\n LOGGER.info(\" -xml: show formats as XML data\");\n return;\n }\n LOGGER.info(getHeader(printStyle));\n // retrieve all of the file format readers and writers\n ImageReader baseReader = new ImageReader();\n IFormatReader[] readers = baseReader.getReaders();\n ImageWriter baseWriter = new ImageWriter();\n IFormatWriter[] writers = baseWriter.getWriters();\n for (int i = 0; i < readers.length; i++) {\n String readerFormatName = readers[i].getFormat();\n boolean read = true;\n boolean write = false;\n boolean wmp = false;\n // check if there is a corresponding writer\n IFormatWriter writer = null;\n for (int j = 0; j < writers.length; j++) {\n if (writers[j].getFormat().equals(readerFormatName)) {\n writer = writers[j];\n }\n }\n if (writer != null) {\n write = true;\n // this format can be written\n // determine whether or not multiple images can be\n // written to a single file\n if (writer.canDoStacks())\n wmp = true;\n }\n String[] extensions = readers[i].getSuffixes();\n StringBuilder ext = new StringBuilder();\n for (int j = 0; j < extensions.length; j++) {\n ext.append(extensions[j]);\n if (j < extensions.length - 1) {\n ext.append(\", \");\n }\n }\n // display information about the format\n LOGGER.info(getFormatLine(printStyle, readerFormatName, read, write, wmp, ext.toString()));\n }\n LOGGER.info(getFooter(printStyle));\n }\n\n public static void main(String[] args) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2493", "language": "Java", "task_type": "single_line", "source_file": "java/github/ome/bioformats/components/bio-formats-tools/src/loci/formats/tools/PrintFormatTable.java", "mask_start_position": 5334, "mask_end_position": 5349, "canonical_solution": "r.getWriters();", "pre_mask_code": "/*\n * #%L\n * Bio-Formats command line tools for reading and converting files\n * %%\n * - Glencoe Software, Inc.\n * - University of Dundee\n * %%\n * #L%\n */\n/*\nContributed 2009 by the Center for BioImage Informatics, UCSB\n*/\npackage loci.formats.tools;\n\nimport loci.formats.IFormatReader;\nimport loci.formats.IFormatWriter;\nimport loci.formats.ImageReader;\nimport loci.formats.ImageWriter;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Utility class for printing a list of formats supported by Bio-Formats.\n */\npublic class PrintFormatTable {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(PrintFormatTable.class);\n\n public enum PrintStyles {\n\n TXT, XML, HTML\n }\n\n // Text\n public static String getTextHeader() {\n return \"\";\n }\n\n public static String getTextFooter() {\n return \"\";\n }\n\n public static String getTextFormatLine(String name, boolean read, boolean write, boolean wmp, String ext) {\n StringBuffer s = new StringBuffer(name);\n if (read)\n s.append(\": can read\");\n if (write)\n s.append(\", can write\");\n if (wmp)\n s.append(\", can write multiple\");\n s.append(\" (\");\n s.append(ext);\n s.append(\")\");\n return s.toString();\n }\n\n // XML\n public static String getXmlHeader() {\n return \"\\n\";\n }\n\n public static String getXmlFooter() {\n return \"\\n\";\n }\n\n public static String getXmlFormatLine(String name, boolean read, boolean write, boolean wmp, String ext) {\n StringBuffer s = new StringBuffer(\"\\n\");\n if (read)\n s.append(\" \\n\");\n if (write)\n s.append(\" \\n\");\n if (wmp) {\n s.append(\" \\n\");\n }\n s.append(\" \\n\\n\");\n return s.toString();\n }\n\n // HTML\n public static String getHtmlHeader() {\n return \"\" + \"\";\n }\n\n public static String getHtmlFooter() {\n return \"
NameReadingWritingExtensions
\";\n }\n\n public static String getHtmlFormatLine(String name, boolean read, boolean write, String ext) {\n StringBuffer s = new StringBuffer(\" \");\n s.append(name);\n s.append(\"\");\n s.append(read ? \"yes\" : \"no\");\n s.append(\"\");\n s.append(write ? \"yes\" : \"no\");\n s.append(\"\");\n s.append(ext);\n s.append(\"\");\n return s.toString();\n }\n\n public static String getHeader(PrintStyles style) {\n if (style == PrintStyles.XML)\n return getXmlHeader();\n if (style == PrintStyles.HTML)\n return getHtmlHeader();\n if (style == PrintStyles.TXT)\n return getTextHeader();\n return \"\";\n }\n\n public static String getFooter(PrintStyles style) {\n if (style == PrintStyles.XML)\n return getXmlFooter();\n if (style == PrintStyles.HTML)\n return getHtmlFooter();\n if (style == PrintStyles.TXT)\n return getTextFooter();\n return \"\";\n }\n\n public static String getFormatLine(PrintStyles style, String name, boolean read, boolean write, boolean wmp, String ext) {\n if (style == PrintStyles.XML) {\n return getXmlFormatLine(name, read, write, wmp, ext);\n }\n if (style == PrintStyles.HTML) {\n return getHtmlFormatLine(name, read, write, ext);\n }\n if (style == PrintStyles.TXT) {\n return getTextFormatLine(name, read, write, wmp, ext);\n }\n return \"\";\n }\n\n public static void printSupportedFormats(String[] args) {\n PrintStyles printStyle = PrintStyles.TXT;\n boolean usage = false;\n if (args != null) {\n for (int i = 0; i < args.length; i++) {\n if (args[i].equals(\"-help\"))\n usage = true;\n else if (args[i].equals(\"-xml\"))\n printStyle = PrintStyles.XML;\n else if (args[i].equals(\"-html\"))\n printStyle = PrintStyles.HTML;\n else if (args[i].equals(\"-txt\"))\n printStyle = PrintStyles.TXT;\n else {\n LOGGER.warn(\"unknown flag: {}; try -help for options\", args[i]);\n }\n }\n }\n if (usage) {\n LOGGER.info(\"Usage: formatlist [-html] [-txt] [-xml]\");\n LOGGER.info(\" -html: show formats in an HTML table\");\n LOGGER.info(\" -txt: show formats in plaintext (default)\");\n LOGGER.info(\" -xml: show formats as XML data\");\n return;\n }\n LOGGER.info(getHeader(printStyle));\n // retrieve all of the file format readers and writers\n ImageReader baseReader = new ImageReader();\n IFormatReader[] readers = baseReader.getReaders();\n ImageWriter baseWriter = new ImageWriter();\n IFormatWriter[] writers = baseWrite", "post_mask_code": "\n for (int i = 0; i < readers.length; i++) {\n String readerFormatName = readers[i].getFormat();\n boolean read = true;\n boolean write = false;\n boolean wmp = false;\n // check if there is a corresponding writer\n IFormatWriter writer = null;\n for (int j = 0; j < writers.length; j++) {\n if (writers[j].getFormat().equals(readerFormatName)) {\n writer = writers[j];\n }\n }\n if (writer != null) {\n write = true;\n // this format can be written\n // determine whether or not multiple images can be\n // written to a single file\n if (writer.canDoStacks())\n wmp = true;\n }\n String[] extensions = readers[i].getSuffixes();\n StringBuilder ext = new StringBuilder();\n for (int j = 0; j < extensions.length; j++) {\n ext.append(extensions[j]);\n if (j < extensions.length - 1) {\n ext.append(\", \");\n }\n }\n // display information about the format\n LOGGER.info(getFormatLine(printStyle, readerFormatName, read, write, wmp, ext.toString()));\n }\n LOGGER.info(getFooter(printStyle));\n }\n\n public static void main(String[] args) {\n printSupportedFormats(args);\n }\n}\n"} {"task_id": "Java_2494", "language": "Java", "task_type": "for_statement", "source_file": "java/github/ome/bioformats/components/bio-formats-tools/src/loci/formats/tools/PrintFormatTable.java", "mask_start_position": 6294, "mask_end_position": 6501, "canonical_solution": "for (int j = 0; j < extensions.length; j++) {\n ext.append(extensions[j]);\n if (j < extensions.length - 1) {\n ext.append(\", \");\n }\n }", "pre_mask_code": "/*\n * #%L\n * Bio-Formats command line tools for reading and converting files\n * %%\n * - Glencoe Software, Inc.\n * - University of Dundee\n * %%\n * #L%\n */\n/*\nContributed 2009 by the Center for BioImage Informatics, UCSB\n*/\npackage loci.formats.tools;\n\nimport loci.formats.IFormatReader;\nimport loci.formats.IFormatWriter;\nimport loci.formats.ImageReader;\nimport loci.formats.ImageWriter;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Utility class for printing a list of formats supported by Bio-Formats.\n */\npublic class PrintFormatTable {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(PrintFormatTable.class);\n\n public enum PrintStyles {\n\n TXT, XML, HTML\n }\n\n // Text\n public static String getTextHeader() {\n return \"\";\n }\n\n public static String getTextFooter() {\n return \"\";\n }\n\n public static String getTextFormatLine(String name, boolean read, boolean write, boolean wmp, String ext) {\n StringBuffer s = new StringBuffer(name);\n if (read)\n s.append(\": can read\");\n if (write)\n s.append(\", can write\");\n if (wmp)\n s.append(\", can write multiple\");\n s.append(\" (\");\n s.append(ext);\n s.append(\")\");\n return s.toString();\n }\n\n // XML\n public static String getXmlHeader() {\n return \"\\n\";\n }\n\n public static String getXmlFooter() {\n return \"\\n\";\n }\n\n public static String getXmlFormatLine(String name, boolean read, boolean write, boolean wmp, String ext) {\n StringBuffer s = new StringBuffer(\"\\n\");\n if (read)\n s.append(\" \\n\");\n if (write)\n s.append(\" \\n\");\n if (wmp) {\n s.append(\" \\n\");\n }\n s.append(\" \\n\\n\");\n return s.toString();\n }\n\n // HTML\n public static String getHtmlHeader() {\n return \"\" + \"\";\n }\n\n public static String getHtmlFooter() {\n return \"
NameReadingWritingExtensions
\";\n }\n\n public static String getHtmlFormatLine(String name, boolean read, boolean write, String ext) {\n StringBuffer s = new StringBuffer(\" \");\n s.append(name);\n s.append(\"\");\n s.append(read ? \"yes\" : \"no\");\n s.append(\"\");\n s.append(write ? \"yes\" : \"no\");\n s.append(\"\");\n s.append(ext);\n s.append(\"\");\n return s.toString();\n }\n\n public static String getHeader(PrintStyles style) {\n if (style == PrintStyles.XML)\n return getXmlHeader();\n if (style == PrintStyles.HTML)\n return getHtmlHeader();\n if (style == PrintStyles.TXT)\n return getTextHeader();\n return \"\";\n }\n\n public static String getFooter(PrintStyles style) {\n if (style == PrintStyles.XML)\n return getXmlFooter();\n if (style == PrintStyles.HTML)\n return getHtmlFooter();\n if (style == PrintStyles.TXT)\n return getTextFooter();\n return \"\";\n }\n\n public static String getFormatLine(PrintStyles style, String name, boolean read, boolean write, boolean wmp, String ext) {\n if (style == PrintStyles.XML) {\n return getXmlFormatLine(name, read, write, wmp, ext);\n }\n if (style == PrintStyles.HTML) {\n return getHtmlFormatLine(name, read, write, ext);\n }\n if (style == PrintStyles.TXT) {\n return getTextFormatLine(name, read, write, wmp, ext);\n }\n return \"\";\n }\n\n public static void printSupportedFormats(String[] args) {\n PrintStyles printStyle = PrintStyles.TXT;\n boolean usage = false;\n if (args != null) {\n for (int i = 0; i < args.length; i++) {\n if (args[i].equals(\"-help\"))\n usage = true;\n else if (args[i].equals(\"-xml\"))\n printStyle = PrintStyles.XML;\n else if (args[i].equals(\"-html\"))\n printStyle = PrintStyles.HTML;\n else if (args[i].equals(\"-txt\"))\n printStyle = PrintStyles.TXT;\n else {\n LOGGER.warn(\"unknown flag: {}; try -help for options\", args[i]);\n }\n }\n }\n if (usage) {\n LOGGER.info(\"Usage: formatlist [-html] [-txt] [-xml]\");\n LOGGER.info(\" -html: show formats in an HTML table\");\n LOGGER.info(\" -txt: show formats in plaintext (default)\");\n LOGGER.info(\" -xml: show formats as XML data\");\n return;\n }\n LOGGER.info(getHeader(printStyle));\n // retrieve all of the file format readers and writers\n ImageReader baseReader = new ImageReader();\n IFormatReader[] readers = baseReader.getReaders();\n ImageWriter baseWriter = new ImageWriter();\n IFormatWriter[] writers = baseWriter.getWriters();\n for (int i = 0; i < readers.length; i++) {\n String readerFormatName = readers[i].getFormat();\n boolean read = true;\n boolean write = false;\n boolean wmp = false;\n // check if there is a corresponding writer\n IFormatWriter writer = null;\n for (int j = 0; j < writers.length; j++) {\n if (writers[j].getFormat().equals(readerFormatName)) {\n writer = writers[j];\n }\n }\n if (writer != null) {\n write = true;\n // this format can be written\n // determine whether or not multiple images can be\n // written to a single file\n if (writer.canDoStacks())\n wmp = true;\n }\n String[] extensions = readers[i].getSuffixes();\n StringBuilder ext = new StringBuilder();\n ", "post_mask_code": "\n // display information about the format\n LOGGER.info(getFormatLine(printStyle, readerFormatName, read, write, wmp, ext.toString()));\n }\n LOGGER.info(getFooter(printStyle));\n }\n\n public static void main(String[] args) {\n printSupportedFormats(args);\n }\n}\n"} {"task_id": "Java_2495", "language": "Java", "task_type": "method_signature", "source_file": "java/github/remondis-it/remap/src/main/java/com/remondis/remap/ReassignBuilder.java", "mask_start_position": 1077, "mask_end_position": 1152, "canonical_solution": "public MappingConfiguration to(FieldSelector destinationSelector) ", "pre_mask_code": "package com.remondis.remap;\n\nimport static com.remondis.remap.Lang.denyNull;\nimport static com.remondis.remap.MappingConfiguration.getPropertyFromFieldSelector;\nimport java.beans.PropertyDescriptor;\n\n/**\n * Builds a reassign operation.\n *\n * @param The source type.\n * @param The destination type.\n */\npublic class ReassignBuilder {\n\n static final String ASSIGN = \"assign\";\n\n private PropertyDescriptor sourceProperty;\n\n private MappingConfiguration mapping;\n\n private Class destination;\n\n ReassignBuilder(PropertyDescriptor sourceProperty, Class destination, MappingConfiguration mapping) {\n super();\n this.sourceProperty = sourceProperty;\n this.mapping = mapping;\n this.destination = destination;\n }\n\n /**\n * Reassigns a source field to the specified destination field.\n *\n * @param destinationSelector\n * {@link TypedSelector} to select the destination field.\n *\n * @return Returns the {@link MappingConfiguration} for further mapping configuration.\n */\n ", "post_mask_code": "{\n denyNull(\"destinationSelector\", destinationSelector);\n PropertyDescriptor destProperty = getPropertyFromFieldSelector(Target.DESTINATION, ASSIGN, destination, destinationSelector);\n ReassignTransformation transformation = new ReassignTransformation(mapping, sourceProperty, destProperty);\n mapping.addMapping(sourceProperty, destProperty, transformation);\n return mapping;\n }\n}\n"} {"task_id": "Java_2496", "language": "Java", "task_type": "method_body", "source_file": "java/github/remondis-it/remap/src/main/java/com/remondis/remap/ReassignBuilder.java", "mask_start_position": 1152, "mask_end_position": 1568, "canonical_solution": "{\n denyNull(\"destinationSelector\", destinationSelector);\n PropertyDescriptor destProperty = getPropertyFromFieldSelector(Target.DESTINATION, ASSIGN, destination, destinationSelector);\n ReassignTransformation transformation = new ReassignTransformation(mapping, sourceProperty, destProperty);\n mapping.addMapping(sourceProperty, destProperty, transformation);\n return mapping;\n }", "pre_mask_code": "package com.remondis.remap;\n\nimport static com.remondis.remap.Lang.denyNull;\nimport static com.remondis.remap.MappingConfiguration.getPropertyFromFieldSelector;\nimport java.beans.PropertyDescriptor;\n\n/**\n * Builds a reassign operation.\n *\n * @param The source type.\n * @param The destination type.\n */\npublic class ReassignBuilder {\n\n static final String ASSIGN = \"assign\";\n\n private PropertyDescriptor sourceProperty;\n\n private MappingConfiguration mapping;\n\n private Class destination;\n\n ReassignBuilder(PropertyDescriptor sourceProperty, Class destination, MappingConfiguration mapping) {\n super();\n this.sourceProperty = sourceProperty;\n this.mapping = mapping;\n this.destination = destination;\n }\n\n /**\n * Reassigns a source field to the specified destination field.\n *\n * @param destinationSelector\n * {@link TypedSelector} to select the destination field.\n *\n * @return Returns the {@link MappingConfiguration} for further mapping configuration.\n */\n public MappingConfiguration to(FieldSelector destinationSelector) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2497", "language": "Java", "task_type": "single_line", "source_file": "java/github/remondis-it/remap/src/main/java/com/remondis/remap/ReassignBuilder.java", "mask_start_position": 1171, "mask_end_position": 1215, "canonical_solution": "\"destinationSelector\", destinationSelector);", "pre_mask_code": "package com.remondis.remap;\n\nimport static com.remondis.remap.Lang.denyNull;\nimport static com.remondis.remap.MappingConfiguration.getPropertyFromFieldSelector;\nimport java.beans.PropertyDescriptor;\n\n/**\n * Builds a reassign operation.\n *\n * @param The source type.\n * @param The destination type.\n */\npublic class ReassignBuilder {\n\n static final String ASSIGN = \"assign\";\n\n private PropertyDescriptor sourceProperty;\n\n private MappingConfiguration mapping;\n\n private Class destination;\n\n ReassignBuilder(PropertyDescriptor sourceProperty, Class destination, MappingConfiguration mapping) {\n super();\n this.sourceProperty = sourceProperty;\n this.mapping = mapping;\n this.destination = destination;\n }\n\n /**\n * Reassigns a source field to the specified destination field.\n *\n * @param destinationSelector\n * {@link TypedSelector} to select the destination field.\n *\n * @return Returns the {@link MappingConfiguration} for further mapping configuration.\n */\n public MappingConfiguration to(FieldSelector destinationSelector) {\n denyNull(", "post_mask_code": "\n PropertyDescriptor destProperty = getPropertyFromFieldSelector(Target.DESTINATION, ASSIGN, destination, destinationSelector);\n ReassignTransformation transformation = new ReassignTransformation(mapping, sourceProperty, destProperty);\n mapping.addMapping(sourceProperty, destProperty, transformation);\n return mapping;\n }\n}\n"} {"task_id": "Java_2498", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/remondis-it/remap/src/main/java/com/remondis/remap/ReassignBuilder.java", "mask_start_position": 1077, "mask_end_position": 1568, "canonical_solution": "public MappingConfiguration to(FieldSelector destinationSelector) {\n denyNull(\"destinationSelector\", destinationSelector);\n PropertyDescriptor destProperty = getPropertyFromFieldSelector(Target.DESTINATION, ASSIGN, destination, destinationSelector);\n ReassignTransformation transformation = new ReassignTransformation(mapping, sourceProperty, destProperty);\n mapping.addMapping(sourceProperty, destProperty, transformation);\n return mapping;\n }", "pre_mask_code": "package com.remondis.remap;\n\nimport static com.remondis.remap.Lang.denyNull;\nimport static com.remondis.remap.MappingConfiguration.getPropertyFromFieldSelector;\nimport java.beans.PropertyDescriptor;\n\n/**\n * Builds a reassign operation.\n *\n * @param The source type.\n * @param The destination type.\n */\npublic class ReassignBuilder {\n\n static final String ASSIGN = \"assign\";\n\n private PropertyDescriptor sourceProperty;\n\n private MappingConfiguration mapping;\n\n private Class destination;\n\n ReassignBuilder(PropertyDescriptor sourceProperty, Class destination, MappingConfiguration mapping) {\n super();\n this.sourceProperty = sourceProperty;\n this.mapping = mapping;\n this.destination = destination;\n }\n\n /**\n * Reassigns a source field to the specified destination field.\n *\n * @param destinationSelector\n * {@link TypedSelector} to select the destination field.\n *\n * @return Returns the {@link MappingConfiguration} for further mapping configuration.\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2499", "language": "Java", "task_type": "method_signature", "source_file": "java/github/swapnibble/EosCommander/app/src/main/java/io/plactal/eoscommander/util/StringUtils.java", "mask_start_position": 71, "mask_end_position": 120, "canonical_solution": "public static boolean isEmpty(CharSequence data) ", "pre_mask_code": "package io.plactal.eoscommander.util;\n\npublic class StringUtils {\n\n ", "post_mask_code": "{\n return (null == data) || (data.length() <= 0);\n }\n}\n"} {"task_id": "Java_2500", "language": "Java", "task_type": "method_body", "source_file": "java/github/swapnibble/EosCommander/app/src/main/java/io/plactal/eoscommander/util/StringUtils.java", "mask_start_position": 120, "mask_end_position": 182, "canonical_solution": "{\n return (null == data) || (data.length() <= 0);\n }", "pre_mask_code": "package io.plactal.eoscommander.util;\n\npublic class StringUtils {\n\n public static boolean isEmpty(CharSequence data) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2501", "language": "Java", "task_type": "single_line", "source_file": "java/github/swapnibble/EosCommander/app/src/main/java/io/plactal/eoscommander/util/StringUtils.java", "mask_start_position": 151, "mask_end_position": 176, "canonical_solution": " || (data.length() <= 0);", "pre_mask_code": "package io.plactal.eoscommander.util;\n\npublic class StringUtils {\n\n public static boolean isEmpty(CharSequence data) {\n return (null == data)", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2502", "language": "Java", "task_type": "method_signature", "source_file": "java/github/lack006/Android-Hosts-L/code/V7.00/app/src/main/java/com/lack006/hosts_l/Download/CustomDownloadTaskHelper.java", "mask_start_position": 6766, "mask_end_position": 6835, "canonical_solution": "@Override\n protected void onProgressUpdate(Integer... values) ", "pre_mask_code": "package com.lack006.hosts_l.Download;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.os.AsyncTask;\nimport android.view.WindowManager;\nimport android.widget.CheckBox;\nimport android.widget.Toast;\nimport com.lack006.hosts_l.Consistent.Consistent;\nimport com.lack006.hosts_l.CleanCache.CleanCacheHelper;\nimport com.lack006.hosts_l.Clash.InsertClashTaskHelper;\nimport com.lack006.hosts_l.R;\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.List;\nimport static com.lack006.hosts_l.Consistent.Consistent.CONNECTED;\nimport static com.lack006.hosts_l.Consistent.Consistent.CUSTOM_ERROR;\nimport static com.lack006.hosts_l.Consistent.Consistent.DOWNLOAD_CANCEL;\nimport static com.lack006.hosts_l.Consistent.Consistent.MIX_HOSTS;\nimport static com.lack006.hosts_l.Consistent.Consistent.TIME_OUT;\n\n/**\n * Created by lack on 2016/12/15.\n * AndroidHosts-LV7\n */\npublic class CustomDownloadTaskHelper {\n\n private Context mContext = null;\n\n private ProgressDialog mProgressDialog = null;\n\n private ProgressDialog mMixProgressDialog = null;\n\n private CheckBox mCheckBox = null;\n\n private String[] mHosts = null;\n\n private boolean[] mCheck = null;\n\n private boolean mStopFlag = false;\n\n private boolean mIsReError = false;\n\n private boolean mIsKeepScreenOn = false;\n\n private String mUrl = null;\n\n public void download(Context context, String url, String[] hosts, boolean[] check, CheckBox checkBox, boolean keepScreenOn) {\n mContext = context;\n mHosts = hosts;\n mCheck = check;\n mCheckBox = checkBox;\n mUrl = url;\n mIsKeepScreenOn = keepScreenOn;\n CleanCacheHelper cleanCacheHelper = new CleanCacheHelper();\n cleanCacheHelper.cleanHosts(mContext);\n mProgressDialog = new ProgressDialog(mContext);\n mProgressDialog.setMessage(mContext.getString(R.string.connecting));\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n mProgressDialog.setIndeterminate(false);\n mProgressDialog.setCancelable(false);\n mProgressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {\n\n @Override\n public void onClick(DialogInterface dialog, int which) {\n mProgressDialog.setProgress(Consistent.DOWNLOAD_CANCEL);\n mStopFlag = true;\n }\n });\n mProgressDialog.show();\n DownloadHostsTask downloadHostsTask = new DownloadHostsTask();\n downloadHostsTask.execute();\n }\n\n private class DownloadHostsTask extends AsyncTask {\n\n @Override\n protected Boolean doInBackground(Object... objects) {\n File file = mContext.getCacheDir();\n final String CACHE_PATH = file.getAbsolutePath();\n URL url;\n long fileSize;\n long downloadSize = 0;\n try {\n url = new URL(mContext.getString(R.string.ad_url));\n HttpURLConnection con = (HttpURLConnection) url.openConnection();\n con.setConnectTimeout(TIME_OUT);\n con.setRequestProperty(\"Accept-Encoding\", \"identity\");\n InputStream in = con.getInputStream();\n File fileOut = new File(CACHE_PATH + Consistent.HOSTS_FILE);\n FileOutputStream out = new FileOutputStream(fileOut);\n byte[] bytes = new byte[1024];\n int len;\n fileSize = con.getContentLength();\n publishProgress(Consistent.CONNECTED);\n while ((len = in.read(bytes)) != -1) {\n if (mStopFlag) {\n con.disconnect();\n break;\n }\n out.write(bytes, 0, len);\n downloadSize += len;\n publishProgress((int) (downloadSize * 100 / fileSize));\n }\n in.close();\n out.close();\n downloadSize = 0;\n publishProgress(0);\n if (!mStopFlag) {\n mIsReError = true;\n url = new URL(mUrl);\n con = (HttpURLConnection) url.openConnection();\n con.setConnectTimeout(TIME_OUT);\n con.setRequestProperty(\"Accept-Encoding\", \"identity\");\n in = con.getInputStream();\n fileOut = new File(CACHE_PATH + Consistent.RE_FILE);\n out = new FileOutputStream(fileOut);\n bytes = new byte[1024];\n fileSize = con.getContentLength();\n publishProgress(Consistent.CONNECTED);\n while ((len = in.read(bytes)) != -1) {\n if (mStopFlag) {\n con.disconnect();\n break;\n }\n out.write(bytes, 0, len);\n downloadSize += len;\n publishProgress((int) (downloadSize * 100 / fileSize));\n }\n in.close();\n out.close();\n publishProgress(Consistent.MIX_HOSTS);\n mixHosts();\n }\n } catch (Exception e) {\n e.printStackTrace();\n mStopFlag = true;\n if (mIsReError) {\n publishProgress(Consistent.CUSTOM_ERROR);\n } else {\n publishProgress(Consistent.DOWNLOAD_CANCEL);\n }\n }\n return null;\n }\n\n @Override\n protected void onPostExecute(Boolean result) {\n if (mIsKeepScreenOn) {\n ((Activity) mContext).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n Toast.makeText(mContext, mContext.getString(R.string.keep_screen_on_hint_off), Toast.LENGTH_SHORT).show();\n }\n if (!mStopFlag) {\n mMixProgressDialog.cancel();\n InsertClashTaskHelper insertClashTaskHelper = new InsertClashTaskHelper();\n insertClashTaskHelper.insertClashHelper(mContext, mHosts, mCheck, mCheckBox);\n } else {\n CleanCacheHelper cleanCacheHelper = new CleanCacheHelper();\n cleanCacheHelper.cleanHosts(mContext);\n }\n }\n\n ", "post_mask_code": "{\n if (values[0] == CONNECTED) {\n mProgressDialog.setMessage(mContext.getString(R.string.downloading));\n } else if (values[0] == DOWNLOAD_CANCEL) {\n mProgressDialog.cancel();\n } else if (values[0] == MIX_HOSTS) {\n if (mIsKeepScreenOn) {\n ((Activity) mContext).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n Toast.makeText(mContext, mContext.getString(R.string.keep_screen_on_hint_on), Toast.LENGTH_SHORT).show();\n }\n mProgressDialog.cancel();\n mMixProgressDialog = new ProgressDialog(mContext);\n mMixProgressDialog.setMessage(mContext.getString(R.string.mix_hosts));\n mMixProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);\n mMixProgressDialog.setIndeterminate(true);\n mMixProgressDialog.setCancelable(false);\n mMixProgressDialog.show();\n } else if (values[0] == CUSTOM_ERROR) {\n Toast.makeText(mContext, mContext.getString(R.string.custom_error), Toast.LENGTH_SHORT).show();\n mProgressDialog.cancel();\n } else {\n mProgressDialog.setProgress(values[0]);\n }\n }\n\n void mixHosts() {\n File file = mContext.getCacheDir();\n final String CACHE_PATH = file.getAbsolutePath();\n List mReClashList = new ArrayList<>();\n try {\n BufferedReader adReader;\n adReader = new BufferedReader(new FileReader(CACHE_PATH + Consistent.HOSTS_FILE));\n String line;\n while ((line = adReader.readLine()) != null) {\n if (!(line.contains(Consistent.HASH_TAG) || line.equals(\"\"))) {\n mReClashList.add(line.replace(Consistent.LOCAL_HOST + \" \", \"\"));\n }\n }\n adReader.close();\n BufferedReader reReader = new BufferedReader(new FileReader(CACHE_PATH + Consistent.RE_FILE));\n FileOutputStream fileOutputStream = new FileOutputStream(CACHE_PATH + Consistent.HOSTS_FILE, true);\n boolean flag = false;\n while ((line = reReader.readLine()) != null) {\n for (String tmp : mReClashList) {\n if (line.contains(tmp)) {\n flag = true;\n break;\n }\n }\n if (!flag) {\n fileOutputStream.write((line + \"\\n\").getBytes());\n } else {\n flag = false;\n }\n }\n fileOutputStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n}\n"} {"task_id": "Java_2503", "language": "Java", "task_type": "method_body", "source_file": "java/github/lack006/Android-Hosts-L/code/V7.00/app/src/main/java/com/lack006/hosts_l/Download/CustomDownloadTaskHelper.java", "mask_start_position": 2581, "mask_end_position": 2703, "canonical_solution": "{\n mProgressDialog.setProgress(Consistent.DOWNLOAD_CANCEL);\n mStopFlag = true;\n }", "pre_mask_code": "package com.lack006.hosts_l.Download;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.os.AsyncTask;\nimport android.view.WindowManager;\nimport android.widget.CheckBox;\nimport android.widget.Toast;\nimport com.lack006.hosts_l.Consistent.Consistent;\nimport com.lack006.hosts_l.CleanCache.CleanCacheHelper;\nimport com.lack006.hosts_l.Clash.InsertClashTaskHelper;\nimport com.lack006.hosts_l.R;\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.List;\nimport static com.lack006.hosts_l.Consistent.Consistent.CONNECTED;\nimport static com.lack006.hosts_l.Consistent.Consistent.CUSTOM_ERROR;\nimport static com.lack006.hosts_l.Consistent.Consistent.DOWNLOAD_CANCEL;\nimport static com.lack006.hosts_l.Consistent.Consistent.MIX_HOSTS;\nimport static com.lack006.hosts_l.Consistent.Consistent.TIME_OUT;\n\n/**\n * Created by lack on 2016/12/15.\n * AndroidHosts-LV7\n */\npublic class CustomDownloadTaskHelper {\n\n private Context mContext = null;\n\n private ProgressDialog mProgressDialog = null;\n\n private ProgressDialog mMixProgressDialog = null;\n\n private CheckBox mCheckBox = null;\n\n private String[] mHosts = null;\n\n private boolean[] mCheck = null;\n\n private boolean mStopFlag = false;\n\n private boolean mIsReError = false;\n\n private boolean mIsKeepScreenOn = false;\n\n private String mUrl = null;\n\n public void download(Context context, String url, String[] hosts, boolean[] check, CheckBox checkBox, boolean keepScreenOn) {\n mContext = context;\n mHosts = hosts;\n mCheck = check;\n mCheckBox = checkBox;\n mUrl = url;\n mIsKeepScreenOn = keepScreenOn;\n CleanCacheHelper cleanCacheHelper = new CleanCacheHelper();\n cleanCacheHelper.cleanHosts(mContext);\n mProgressDialog = new ProgressDialog(mContext);\n mProgressDialog.setMessage(mContext.getString(R.string.connecting));\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n mProgressDialog.setIndeterminate(false);\n mProgressDialog.setCancelable(false);\n mProgressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {\n\n @Override\n public void onClick(DialogInterface dialog, int which) ", "post_mask_code": "\n });\n mProgressDialog.show();\n DownloadHostsTask downloadHostsTask = new DownloadHostsTask();\n downloadHostsTask.execute();\n }\n\n private class DownloadHostsTask extends AsyncTask {\n\n @Override\n protected Boolean doInBackground(Object... objects) {\n File file = mContext.getCacheDir();\n final String CACHE_PATH = file.getAbsolutePath();\n URL url;\n long fileSize;\n long downloadSize = 0;\n try {\n url = new URL(mContext.getString(R.string.ad_url));\n HttpURLConnection con = (HttpURLConnection) url.openConnection();\n con.setConnectTimeout(TIME_OUT);\n con.setRequestProperty(\"Accept-Encoding\", \"identity\");\n InputStream in = con.getInputStream();\n File fileOut = new File(CACHE_PATH + Consistent.HOSTS_FILE);\n FileOutputStream out = new FileOutputStream(fileOut);\n byte[] bytes = new byte[1024];\n int len;\n fileSize = con.getContentLength();\n publishProgress(Consistent.CONNECTED);\n while ((len = in.read(bytes)) != -1) {\n if (mStopFlag) {\n con.disconnect();\n break;\n }\n out.write(bytes, 0, len);\n downloadSize += len;\n publishProgress((int) (downloadSize * 100 / fileSize));\n }\n in.close();\n out.close();\n downloadSize = 0;\n publishProgress(0);\n if (!mStopFlag) {\n mIsReError = true;\n url = new URL(mUrl);\n con = (HttpURLConnection) url.openConnection();\n con.setConnectTimeout(TIME_OUT);\n con.setRequestProperty(\"Accept-Encoding\", \"identity\");\n in = con.getInputStream();\n fileOut = new File(CACHE_PATH + Consistent.RE_FILE);\n out = new FileOutputStream(fileOut);\n bytes = new byte[1024];\n fileSize = con.getContentLength();\n publishProgress(Consistent.CONNECTED);\n while ((len = in.read(bytes)) != -1) {\n if (mStopFlag) {\n con.disconnect();\n break;\n }\n out.write(bytes, 0, len);\n downloadSize += len;\n publishProgress((int) (downloadSize * 100 / fileSize));\n }\n in.close();\n out.close();\n publishProgress(Consistent.MIX_HOSTS);\n mixHosts();\n }\n } catch (Exception e) {\n e.printStackTrace();\n mStopFlag = true;\n if (mIsReError) {\n publishProgress(Consistent.CUSTOM_ERROR);\n } else {\n publishProgress(Consistent.DOWNLOAD_CANCEL);\n }\n }\n return null;\n }\n\n @Override\n protected void onPostExecute(Boolean result) {\n if (mIsKeepScreenOn) {\n ((Activity) mContext).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n Toast.makeText(mContext, mContext.getString(R.string.keep_screen_on_hint_off), Toast.LENGTH_SHORT).show();\n }\n if (!mStopFlag) {\n mMixProgressDialog.cancel();\n InsertClashTaskHelper insertClashTaskHelper = new InsertClashTaskHelper();\n insertClashTaskHelper.insertClashHelper(mContext, mHosts, mCheck, mCheckBox);\n } else {\n CleanCacheHelper cleanCacheHelper = new CleanCacheHelper();\n cleanCacheHelper.cleanHosts(mContext);\n }\n }\n\n @Override\n protected void onProgressUpdate(Integer... values) {\n if (values[0] == CONNECTED) {\n mProgressDialog.setMessage(mContext.getString(R.string.downloading));\n } else if (values[0] == DOWNLOAD_CANCEL) {\n mProgressDialog.cancel();\n } else if (values[0] == MIX_HOSTS) {\n if (mIsKeepScreenOn) {\n ((Activity) mContext).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n Toast.makeText(mContext, mContext.getString(R.string.keep_screen_on_hint_on), Toast.LENGTH_SHORT).show();\n }\n mProgressDialog.cancel();\n mMixProgressDialog = new ProgressDialog(mContext);\n mMixProgressDialog.setMessage(mContext.getString(R.string.mix_hosts));\n mMixProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);\n mMixProgressDialog.setIndeterminate(true);\n mMixProgressDialog.setCancelable(false);\n mMixProgressDialog.show();\n } else if (values[0] == CUSTOM_ERROR) {\n Toast.makeText(mContext, mContext.getString(R.string.custom_error), Toast.LENGTH_SHORT).show();\n mProgressDialog.cancel();\n } else {\n mProgressDialog.setProgress(values[0]);\n }\n }\n\n void mixHosts() {\n File file = mContext.getCacheDir();\n final String CACHE_PATH = file.getAbsolutePath();\n List mReClashList = new ArrayList<>();\n try {\n BufferedReader adReader;\n adReader = new BufferedReader(new FileReader(CACHE_PATH + Consistent.HOSTS_FILE));\n String line;\n while ((line = adReader.readLine()) != null) {\n if (!(line.contains(Consistent.HASH_TAG) || line.equals(\"\"))) {\n mReClashList.add(line.replace(Consistent.LOCAL_HOST + \" \", \"\"));\n }\n }\n adReader.close();\n BufferedReader reReader = new BufferedReader(new FileReader(CACHE_PATH + Consistent.RE_FILE));\n FileOutputStream fileOutputStream = new FileOutputStream(CACHE_PATH + Consistent.HOSTS_FILE, true);\n boolean flag = false;\n while ((line = reReader.readLine()) != null) {\n for (String tmp : mReClashList) {\n if (line.contains(tmp)) {\n flag = true;\n break;\n }\n }\n if (!flag) {\n fileOutputStream.write((line + \"\\n\").getBytes());\n } else {\n flag = false;\n }\n }\n fileOutputStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n}\n"} {"task_id": "Java_2504", "language": "Java", "task_type": "single_line", "source_file": "java/github/lack006/Android-Hosts-L/code/V7.00/app/src/main/java/com/lack006/hosts_l/Download/CustomDownloadTaskHelper.java", "mask_start_position": 2270, "mask_end_position": 2301, "canonical_solution": "Dialog.setIndeterminate(false);", "pre_mask_code": "package com.lack006.hosts_l.Download;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.os.AsyncTask;\nimport android.view.WindowManager;\nimport android.widget.CheckBox;\nimport android.widget.Toast;\nimport com.lack006.hosts_l.Consistent.Consistent;\nimport com.lack006.hosts_l.CleanCache.CleanCacheHelper;\nimport com.lack006.hosts_l.Clash.InsertClashTaskHelper;\nimport com.lack006.hosts_l.R;\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.List;\nimport static com.lack006.hosts_l.Consistent.Consistent.CONNECTED;\nimport static com.lack006.hosts_l.Consistent.Consistent.CUSTOM_ERROR;\nimport static com.lack006.hosts_l.Consistent.Consistent.DOWNLOAD_CANCEL;\nimport static com.lack006.hosts_l.Consistent.Consistent.MIX_HOSTS;\nimport static com.lack006.hosts_l.Consistent.Consistent.TIME_OUT;\n\n/**\n * Created by lack on 2016/12/15.\n * AndroidHosts-LV7\n */\npublic class CustomDownloadTaskHelper {\n\n private Context mContext = null;\n\n private ProgressDialog mProgressDialog = null;\n\n private ProgressDialog mMixProgressDialog = null;\n\n private CheckBox mCheckBox = null;\n\n private String[] mHosts = null;\n\n private boolean[] mCheck = null;\n\n private boolean mStopFlag = false;\n\n private boolean mIsReError = false;\n\n private boolean mIsKeepScreenOn = false;\n\n private String mUrl = null;\n\n public void download(Context context, String url, String[] hosts, boolean[] check, CheckBox checkBox, boolean keepScreenOn) {\n mContext = context;\n mHosts = hosts;\n mCheck = check;\n mCheckBox = checkBox;\n mUrl = url;\n mIsKeepScreenOn = keepScreenOn;\n CleanCacheHelper cleanCacheHelper = new CleanCacheHelper();\n cleanCacheHelper.cleanHosts(mContext);\n mProgressDialog = new ProgressDialog(mContext);\n mProgressDialog.setMessage(mContext.getString(R.string.connecting));\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n mProgress", "post_mask_code": "\n mProgressDialog.setCancelable(false);\n mProgressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {\n\n @Override\n public void onClick(DialogInterface dialog, int which) {\n mProgressDialog.setProgress(Consistent.DOWNLOAD_CANCEL);\n mStopFlag = true;\n }\n });\n mProgressDialog.show();\n DownloadHostsTask downloadHostsTask = new DownloadHostsTask();\n downloadHostsTask.execute();\n }\n\n private class DownloadHostsTask extends AsyncTask {\n\n @Override\n protected Boolean doInBackground(Object... objects) {\n File file = mContext.getCacheDir();\n final String CACHE_PATH = file.getAbsolutePath();\n URL url;\n long fileSize;\n long downloadSize = 0;\n try {\n url = new URL(mContext.getString(R.string.ad_url));\n HttpURLConnection con = (HttpURLConnection) url.openConnection();\n con.setConnectTimeout(TIME_OUT);\n con.setRequestProperty(\"Accept-Encoding\", \"identity\");\n InputStream in = con.getInputStream();\n File fileOut = new File(CACHE_PATH + Consistent.HOSTS_FILE);\n FileOutputStream out = new FileOutputStream(fileOut);\n byte[] bytes = new byte[1024];\n int len;\n fileSize = con.getContentLength();\n publishProgress(Consistent.CONNECTED);\n while ((len = in.read(bytes)) != -1) {\n if (mStopFlag) {\n con.disconnect();\n break;\n }\n out.write(bytes, 0, len);\n downloadSize += len;\n publishProgress((int) (downloadSize * 100 / fileSize));\n }\n in.close();\n out.close();\n downloadSize = 0;\n publishProgress(0);\n if (!mStopFlag) {\n mIsReError = true;\n url = new URL(mUrl);\n con = (HttpURLConnection) url.openConnection();\n con.setConnectTimeout(TIME_OUT);\n con.setRequestProperty(\"Accept-Encoding\", \"identity\");\n in = con.getInputStream();\n fileOut = new File(CACHE_PATH + Consistent.RE_FILE);\n out = new FileOutputStream(fileOut);\n bytes = new byte[1024];\n fileSize = con.getContentLength();\n publishProgress(Consistent.CONNECTED);\n while ((len = in.read(bytes)) != -1) {\n if (mStopFlag) {\n con.disconnect();\n break;\n }\n out.write(bytes, 0, len);\n downloadSize += len;\n publishProgress((int) (downloadSize * 100 / fileSize));\n }\n in.close();\n out.close();\n publishProgress(Consistent.MIX_HOSTS);\n mixHosts();\n }\n } catch (Exception e) {\n e.printStackTrace();\n mStopFlag = true;\n if (mIsReError) {\n publishProgress(Consistent.CUSTOM_ERROR);\n } else {\n publishProgress(Consistent.DOWNLOAD_CANCEL);\n }\n }\n return null;\n }\n\n @Override\n protected void onPostExecute(Boolean result) {\n if (mIsKeepScreenOn) {\n ((Activity) mContext).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n Toast.makeText(mContext, mContext.getString(R.string.keep_screen_on_hint_off), Toast.LENGTH_SHORT).show();\n }\n if (!mStopFlag) {\n mMixProgressDialog.cancel();\n InsertClashTaskHelper insertClashTaskHelper = new InsertClashTaskHelper();\n insertClashTaskHelper.insertClashHelper(mContext, mHosts, mCheck, mCheckBox);\n } else {\n CleanCacheHelper cleanCacheHelper = new CleanCacheHelper();\n cleanCacheHelper.cleanHosts(mContext);\n }\n }\n\n @Override\n protected void onProgressUpdate(Integer... values) {\n if (values[0] == CONNECTED) {\n mProgressDialog.setMessage(mContext.getString(R.string.downloading));\n } else if (values[0] == DOWNLOAD_CANCEL) {\n mProgressDialog.cancel();\n } else if (values[0] == MIX_HOSTS) {\n if (mIsKeepScreenOn) {\n ((Activity) mContext).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n Toast.makeText(mContext, mContext.getString(R.string.keep_screen_on_hint_on), Toast.LENGTH_SHORT).show();\n }\n mProgressDialog.cancel();\n mMixProgressDialog = new ProgressDialog(mContext);\n mMixProgressDialog.setMessage(mContext.getString(R.string.mix_hosts));\n mMixProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);\n mMixProgressDialog.setIndeterminate(true);\n mMixProgressDialog.setCancelable(false);\n mMixProgressDialog.show();\n } else if (values[0] == CUSTOM_ERROR) {\n Toast.makeText(mContext, mContext.getString(R.string.custom_error), Toast.LENGTH_SHORT).show();\n mProgressDialog.cancel();\n } else {\n mProgressDialog.setProgress(values[0]);\n }\n }\n\n void mixHosts() {\n File file = mContext.getCacheDir();\n final String CACHE_PATH = file.getAbsolutePath();\n List mReClashList = new ArrayList<>();\n try {\n BufferedReader adReader;\n adReader = new BufferedReader(new FileReader(CACHE_PATH + Consistent.HOSTS_FILE));\n String line;\n while ((line = adReader.readLine()) != null) {\n if (!(line.contains(Consistent.HASH_TAG) || line.equals(\"\"))) {\n mReClashList.add(line.replace(Consistent.LOCAL_HOST + \" \", \"\"));\n }\n }\n adReader.close();\n BufferedReader reReader = new BufferedReader(new FileReader(CACHE_PATH + Consistent.RE_FILE));\n FileOutputStream fileOutputStream = new FileOutputStream(CACHE_PATH + Consistent.HOSTS_FILE, true);\n boolean flag = false;\n while ((line = reReader.readLine()) != null) {\n for (String tmp : mReClashList) {\n if (line.contains(tmp)) {\n flag = true;\n break;\n }\n }\n if (!flag) {\n fileOutputStream.write((line + \"\\n\").getBytes());\n } else {\n flag = false;\n }\n }\n fileOutputStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n}\n"} {"task_id": "Java_2505", "language": "Java", "task_type": "while_statement", "source_file": "java/github/lack006/Android-Hosts-L/code/V7.00/app/src/main/java/com/lack006/hosts_l/Download/CustomDownloadTaskHelper.java", "mask_start_position": 5047, "mask_end_position": 5430, "canonical_solution": "while ((len = in.read(bytes)) != -1) {\n if (mStopFlag) {\n con.disconnect();\n break;\n }\n out.write(bytes, 0, len);\n downloadSize += len;\n publishProgress((int) (downloadSize * 100 / fileSize));\n }", "pre_mask_code": "package com.lack006.hosts_l.Download;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.os.AsyncTask;\nimport android.view.WindowManager;\nimport android.widget.CheckBox;\nimport android.widget.Toast;\nimport com.lack006.hosts_l.Consistent.Consistent;\nimport com.lack006.hosts_l.CleanCache.CleanCacheHelper;\nimport com.lack006.hosts_l.Clash.InsertClashTaskHelper;\nimport com.lack006.hosts_l.R;\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.List;\nimport static com.lack006.hosts_l.Consistent.Consistent.CONNECTED;\nimport static com.lack006.hosts_l.Consistent.Consistent.CUSTOM_ERROR;\nimport static com.lack006.hosts_l.Consistent.Consistent.DOWNLOAD_CANCEL;\nimport static com.lack006.hosts_l.Consistent.Consistent.MIX_HOSTS;\nimport static com.lack006.hosts_l.Consistent.Consistent.TIME_OUT;\n\n/**\n * Created by lack on 2016/12/15.\n * AndroidHosts-LV7\n */\npublic class CustomDownloadTaskHelper {\n\n private Context mContext = null;\n\n private ProgressDialog mProgressDialog = null;\n\n private ProgressDialog mMixProgressDialog = null;\n\n private CheckBox mCheckBox = null;\n\n private String[] mHosts = null;\n\n private boolean[] mCheck = null;\n\n private boolean mStopFlag = false;\n\n private boolean mIsReError = false;\n\n private boolean mIsKeepScreenOn = false;\n\n private String mUrl = null;\n\n public void download(Context context, String url, String[] hosts, boolean[] check, CheckBox checkBox, boolean keepScreenOn) {\n mContext = context;\n mHosts = hosts;\n mCheck = check;\n mCheckBox = checkBox;\n mUrl = url;\n mIsKeepScreenOn = keepScreenOn;\n CleanCacheHelper cleanCacheHelper = new CleanCacheHelper();\n cleanCacheHelper.cleanHosts(mContext);\n mProgressDialog = new ProgressDialog(mContext);\n mProgressDialog.setMessage(mContext.getString(R.string.connecting));\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n mProgressDialog.setIndeterminate(false);\n mProgressDialog.setCancelable(false);\n mProgressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {\n\n @Override\n public void onClick(DialogInterface dialog, int which) {\n mProgressDialog.setProgress(Consistent.DOWNLOAD_CANCEL);\n mStopFlag = true;\n }\n });\n mProgressDialog.show();\n DownloadHostsTask downloadHostsTask = new DownloadHostsTask();\n downloadHostsTask.execute();\n }\n\n private class DownloadHostsTask extends AsyncTask {\n\n @Override\n protected Boolean doInBackground(Object... objects) {\n File file = mContext.getCacheDir();\n final String CACHE_PATH = file.getAbsolutePath();\n URL url;\n long fileSize;\n long downloadSize = 0;\n try {\n url = new URL(mContext.getString(R.string.ad_url));\n HttpURLConnection con = (HttpURLConnection) url.openConnection();\n con.setConnectTimeout(TIME_OUT);\n con.setRequestProperty(\"Accept-Encoding\", \"identity\");\n InputStream in = con.getInputStream();\n File fileOut = new File(CACHE_PATH + Consistent.HOSTS_FILE);\n FileOutputStream out = new FileOutputStream(fileOut);\n byte[] bytes = new byte[1024];\n int len;\n fileSize = con.getContentLength();\n publishProgress(Consistent.CONNECTED);\n while ((len = in.read(bytes)) != -1) {\n if (mStopFlag) {\n con.disconnect();\n break;\n }\n out.write(bytes, 0, len);\n downloadSize += len;\n publishProgress((int) (downloadSize * 100 / fileSize));\n }\n in.close();\n out.close();\n downloadSize = 0;\n publishProgress(0);\n if (!mStopFlag) {\n mIsReError = true;\n url = new URL(mUrl);\n con = (HttpURLConnection) url.openConnection();\n con.setConnectTimeout(TIME_OUT);\n con.setRequestProperty(\"Accept-Encoding\", \"identity\");\n in = con.getInputStream();\n fileOut = new File(CACHE_PATH + Consistent.RE_FILE);\n out = new FileOutputStream(fileOut);\n bytes = new byte[1024];\n fileSize = con.getContentLength();\n publishProgress(Consistent.CONNECTED);\n ", "post_mask_code": "\n in.close();\n out.close();\n publishProgress(Consistent.MIX_HOSTS);\n mixHosts();\n }\n } catch (Exception e) {\n e.printStackTrace();\n mStopFlag = true;\n if (mIsReError) {\n publishProgress(Consistent.CUSTOM_ERROR);\n } else {\n publishProgress(Consistent.DOWNLOAD_CANCEL);\n }\n }\n return null;\n }\n\n @Override\n protected void onPostExecute(Boolean result) {\n if (mIsKeepScreenOn) {\n ((Activity) mContext).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n Toast.makeText(mContext, mContext.getString(R.string.keep_screen_on_hint_off), Toast.LENGTH_SHORT).show();\n }\n if (!mStopFlag) {\n mMixProgressDialog.cancel();\n InsertClashTaskHelper insertClashTaskHelper = new InsertClashTaskHelper();\n insertClashTaskHelper.insertClashHelper(mContext, mHosts, mCheck, mCheckBox);\n } else {\n CleanCacheHelper cleanCacheHelper = new CleanCacheHelper();\n cleanCacheHelper.cleanHosts(mContext);\n }\n }\n\n @Override\n protected void onProgressUpdate(Integer... values) {\n if (values[0] == CONNECTED) {\n mProgressDialog.setMessage(mContext.getString(R.string.downloading));\n } else if (values[0] == DOWNLOAD_CANCEL) {\n mProgressDialog.cancel();\n } else if (values[0] == MIX_HOSTS) {\n if (mIsKeepScreenOn) {\n ((Activity) mContext).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n Toast.makeText(mContext, mContext.getString(R.string.keep_screen_on_hint_on), Toast.LENGTH_SHORT).show();\n }\n mProgressDialog.cancel();\n mMixProgressDialog = new ProgressDialog(mContext);\n mMixProgressDialog.setMessage(mContext.getString(R.string.mix_hosts));\n mMixProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);\n mMixProgressDialog.setIndeterminate(true);\n mMixProgressDialog.setCancelable(false);\n mMixProgressDialog.show();\n } else if (values[0] == CUSTOM_ERROR) {\n Toast.makeText(mContext, mContext.getString(R.string.custom_error), Toast.LENGTH_SHORT).show();\n mProgressDialog.cancel();\n } else {\n mProgressDialog.setProgress(values[0]);\n }\n }\n\n void mixHosts() {\n File file = mContext.getCacheDir();\n final String CACHE_PATH = file.getAbsolutePath();\n List mReClashList = new ArrayList<>();\n try {\n BufferedReader adReader;\n adReader = new BufferedReader(new FileReader(CACHE_PATH + Consistent.HOSTS_FILE));\n String line;\n while ((line = adReader.readLine()) != null) {\n if (!(line.contains(Consistent.HASH_TAG) || line.equals(\"\"))) {\n mReClashList.add(line.replace(Consistent.LOCAL_HOST + \" \", \"\"));\n }\n }\n adReader.close();\n BufferedReader reReader = new BufferedReader(new FileReader(CACHE_PATH + Consistent.RE_FILE));\n FileOutputStream fileOutputStream = new FileOutputStream(CACHE_PATH + Consistent.HOSTS_FILE, true);\n boolean flag = false;\n while ((line = reReader.readLine()) != null) {\n for (String tmp : mReClashList) {\n if (line.contains(tmp)) {\n flag = true;\n break;\n }\n }\n if (!flag) {\n fileOutputStream.write((line + \"\\n\").getBytes());\n } else {\n flag = false;\n }\n }\n fileOutputStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n}\n"} {"task_id": "Java_2506", "language": "Java", "task_type": "method_signature", "source_file": "java/github/soot-oss/soot/src/it/java_tests/Complex.java", "mask_start_position": 102, "mask_end_position": 141, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "/*-\n * #%L\n * Soot - a J*va Optimization Framework\n * %%\n * %%\n * #L%\n */\npublic class Complex {\n\n ", "post_mask_code": "{\n int[] a = new int[] { 2, 3, 4, 5, 3, 3, 4, 3, 2 };\n int x = 9;\n int y = 3;\n int z = 4;\n System.out.println(a[x = y = z]);\n }\n}\n"} {"task_id": "Java_2507", "language": "Java", "task_type": "method_body", "source_file": "java/github/soot-oss/soot/src/it/java_tests/Complex.java", "mask_start_position": 141, "mask_end_position": 306, "canonical_solution": "{\n int[] a = new int[] { 2, 3, 4, 5, 3, 3, 4, 3, 2 };\n int x = 9;\n int y = 3;\n int z = 4;\n System.out.println(a[x = y = z]);\n }", "pre_mask_code": "/*-\n * #%L\n * Soot - a J*va Optimization Framework\n * %%\n * %%\n * #L%\n */\npublic class Complex {\n\n public static void main(String[] args) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2508", "language": "Java", "task_type": "single_line", "source_file": "java/github/soot-oss/soot/src/it/java_tests/Complex.java", "mask_start_position": 215, "mask_end_position": 220, "canonical_solution": " = 9;", "pre_mask_code": "/*-\n * #%L\n * Soot - a J*va Optimization Framework\n * %%\n * %%\n * #L%\n */\npublic class Complex {\n\n public static void main(String[] args) {\n int[] a = new int[] { 2, 3, 4, 5, 3, 3, 4, 3, 2 };\n int x", "post_mask_code": "\n int y = 3;\n int z = 4;\n System.out.println(a[x = y = z]);\n }\n}\n"} {"task_id": "Java_2509", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/eclipse-ee4j/jaxrs-api/jaxrs-api/src/main/java/jakarta/ws/rs/ext/ReaderInterceptorContext.java", "mask_start_position": 1847, "mask_end_position": 1890, "canonical_solution": "public void setInputStream(InputStream is);", "pre_mask_code": "package jakarta.ws.rs.ext;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport jakarta.ws.rs.WebApplicationException;\nimport jakarta.ws.rs.core.MultivaluedMap;\n\n/**\n * Context class used by {@link jakarta.ws.rs.ext.ReaderInterceptor} to intercept calls to (@link\n * jakarta.ws.rs.ext.MessageBodyReader#readFrom}. The getters and setters in this context class correspond to the\n * parameters of the intercepted method.\n *\n * @author Santiago Pericas-Geertsen\n * @author Bill Burke\n * @see ReaderInterceptor\n * @see MessageBodyReader\n * @since 2.0\n */\npublic interface ReaderInterceptorContext extends InterceptorContext {\n\n /**\n * Proceed to the next interceptor in the chain. Return the result of the next interceptor invoked. Interceptors MUST\n * explicitly call this method to continue the execution chain; the call to this method in the last interceptor of the\n * chain will invoke the wrapped {@link jakarta.ws.rs.ext.MessageBodyReader#readFrom}.\n *\n * @return result of next interceptor invoked.\n * @throws IOException if an IO error arises or is thrown by the wrapped {@code MessageBodyReader.readFrom} method.\n * @throws jakarta.ws.rs.WebApplicationException thrown by the wrapped {@code MessageBodyReader.readFrom} method.\n */\n public Object proceed() throws IOException, WebApplicationException;\n\n /**\n * Get the input stream of the object to be read. The JAX-RS runtime is responsible for closing the input stream.\n *\n * @return input stream of the object to be read.\n */\n public InputStream getInputStream();\n\n /**\n * Set the input stream of the object to be read. For example, by wrapping it with another input stream. The JAX-RS\n * runtime is responsible for closing the input stream that is set.\n *\n * @param is new input stream.\n */\n ", "post_mask_code": "\n\n /**\n * Get mutable map of HTTP headers.\n *

\n * Note that while the headers are mutable, a {@link ReaderInterceptor reader interceptor} should typically roll-back\n * any header modifications once the call to {@link #proceed() context.proceed()} returns, to avoid externally visible\n * side-effects of the interceptor invocation.\n *

\n *\n * @return map of HTTP headers.\n */\n public MultivaluedMap getHeaders();\n}\n"} {"task_id": "Java_2510", "language": "Java", "task_type": "method_signature", "source_file": "java/github/baomidou/mybatis-plus/mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/injector/SqlRunnerInjector.java", "mask_start_position": 1556, "mask_end_position": 1701, "canonical_solution": "@SuppressWarnings(\"serial\")\n private void createSelectMappedStatement(String mappedStatement, SqlSource sqlSource, final Class resultType) ", "pre_mask_code": "package com.baomidou.mybatisplus.core.injector;\n\nimport com.baomidou.mybatisplus.core.assist.ISqlRunner;\nimport org.apache.ibatis.logging.Log;\nimport org.apache.ibatis.logging.LogFactory;\nimport org.apache.ibatis.mapping.MappedStatement;\nimport org.apache.ibatis.mapping.ResultMap;\nimport org.apache.ibatis.mapping.SqlCommandType;\nimport org.apache.ibatis.mapping.SqlSource;\nimport org.apache.ibatis.scripting.LanguageDriver;\nimport org.apache.ibatis.session.Configuration;\nimport java.util.ArrayList;\nimport java.util.Map;\n\n/**\n * SqlRunner 注入器\n *\n * @author hubin\n * @since 2018-04-08\n */\npublic class SqlRunnerInjector {\n\n private static final Log logger = LogFactory.getLog(SqlRunnerInjector.class);\n\n protected Configuration configuration;\n\n protected LanguageDriver languageDriver;\n\n public void inject(Configuration configuration) {\n this.configuration = configuration;\n this.languageDriver = configuration.getDefaultScriptingLanguageInstance();\n this.initSelectList();\n this.initSelectObjs();\n this.initInsert();\n this.initUpdate();\n this.initDelete();\n this.initCount();\n }\n\n /**\n * 是否已经存在MappedStatement\n *\n * @param mappedStatement\n * @return\n */\n private boolean hasMappedStatement(String mappedStatement) {\n return configuration.hasStatement(mappedStatement, false);\n }\n\n /**\n * 创建查询MappedStatement\n *\n * @param mappedStatement\n * @param sqlSource 执行的sqlSource\n * @param resultType 返回的结果类型\n */\n ", "post_mask_code": "{\n MappedStatement ms = new MappedStatement.Builder(configuration, mappedStatement, sqlSource, SqlCommandType.SELECT).resultMaps(new ArrayList() {\n\n {\n add(new ResultMap.Builder(configuration, \"defaultResultMap\", resultType, new ArrayList<>(0)).build());\n }\n }).build();\n // 缓存\n configuration.addMappedStatement(ms);\n }\n\n /**\n * 创建一个MappedStatement\n *\n * @param mappedStatement\n * @param sqlSource 执行的sqlSource\n * @param sqlCommandType 执行的sqlCommandType\n */\n @SuppressWarnings(\"serial\")\n private void createUpdateMappedStatement(String mappedStatement, SqlSource sqlSource, SqlCommandType sqlCommandType) {\n MappedStatement ms = new MappedStatement.Builder(configuration, mappedStatement, sqlSource, sqlCommandType).resultMaps(new ArrayList() {\n\n {\n add(new ResultMap.Builder(configuration, \"defaultResultMap\", int.class, new ArrayList<>(0)).build());\n }\n }).build();\n // 缓存\n configuration.addMappedStatement(ms);\n }\n\n private void initSelectList() {\n if (hasMappedStatement(ISqlRunner.SELECT_LIST)) {\n logger.warn(\"MappedStatement 'SqlRunner.SelectList' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createSelectMappedStatement(ISqlRunner.SELECT_LIST, sqlSource, Map.class);\n }\n\n private void initSelectObjs() {\n if (hasMappedStatement(ISqlRunner.SELECT_OBJS)) {\n logger.warn(\"MappedStatement 'SqlRunner.SelectObjs' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Object.class);\n createSelectMappedStatement(ISqlRunner.SELECT_OBJS, sqlSource, Object.class);\n }\n\n private void initCount() {\n if (hasMappedStatement(ISqlRunner.COUNT)) {\n logger.warn(\"MappedStatement 'SqlRunner.Count' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createSelectMappedStatement(ISqlRunner.COUNT, sqlSource, Long.class);\n }\n\n private void initInsert() {\n if (hasMappedStatement(ISqlRunner.INSERT)) {\n logger.warn(\"MappedStatement 'SqlRunner.Insert' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createUpdateMappedStatement(ISqlRunner.INSERT, sqlSource, SqlCommandType.INSERT);\n }\n\n private void initUpdate() {\n if (hasMappedStatement(ISqlRunner.UPDATE)) {\n logger.warn(\"MappedStatement 'SqlRunner.Update' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createUpdateMappedStatement(ISqlRunner.UPDATE, sqlSource, SqlCommandType.UPDATE);\n }\n\n private void initDelete() {\n if (hasMappedStatement(ISqlRunner.DELETE)) {\n logger.warn(\"MappedStatement 'SqlRunner.Delete' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createUpdateMappedStatement(ISqlRunner.DELETE, sqlSource, SqlCommandType.DELETE);\n }\n}\n"} {"task_id": "Java_2511", "language": "Java", "task_type": "method_body", "source_file": "java/github/baomidou/mybatis-plus/mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/injector/SqlRunnerInjector.java", "mask_start_position": 2425, "mask_end_position": 2815, "canonical_solution": "{\n MappedStatement ms = new MappedStatement.Builder(configuration, mappedStatement, sqlSource, sqlCommandType).resultMaps(new ArrayList() {\n\n {\n add(new ResultMap.Builder(configuration, \"defaultResultMap\", int.class, new ArrayList<>(0)).build());\n }\n }).build();\n // 缓存\n configuration.addMappedStatement(ms);\n }", "pre_mask_code": "package com.baomidou.mybatisplus.core.injector;\n\nimport com.baomidou.mybatisplus.core.assist.ISqlRunner;\nimport org.apache.ibatis.logging.Log;\nimport org.apache.ibatis.logging.LogFactory;\nimport org.apache.ibatis.mapping.MappedStatement;\nimport org.apache.ibatis.mapping.ResultMap;\nimport org.apache.ibatis.mapping.SqlCommandType;\nimport org.apache.ibatis.mapping.SqlSource;\nimport org.apache.ibatis.scripting.LanguageDriver;\nimport org.apache.ibatis.session.Configuration;\nimport java.util.ArrayList;\nimport java.util.Map;\n\n/**\n * SqlRunner 注入器\n *\n * @author hubin\n * @since 2018-04-08\n */\npublic class SqlRunnerInjector {\n\n private static final Log logger = LogFactory.getLog(SqlRunnerInjector.class);\n\n protected Configuration configuration;\n\n protected LanguageDriver languageDriver;\n\n public void inject(Configuration configuration) {\n this.configuration = configuration;\n this.languageDriver = configuration.getDefaultScriptingLanguageInstance();\n this.initSelectList();\n this.initSelectObjs();\n this.initInsert();\n this.initUpdate();\n this.initDelete();\n this.initCount();\n }\n\n /**\n * 是否已经存在MappedStatement\n *\n * @param mappedStatement\n * @return\n */\n private boolean hasMappedStatement(String mappedStatement) {\n return configuration.hasStatement(mappedStatement, false);\n }\n\n /**\n * 创建查询MappedStatement\n *\n * @param mappedStatement\n * @param sqlSource 执行的sqlSource\n * @param resultType 返回的结果类型\n */\n @SuppressWarnings(\"serial\")\n private void createSelectMappedStatement(String mappedStatement, SqlSource sqlSource, final Class resultType) {\n MappedStatement ms = new MappedStatement.Builder(configuration, mappedStatement, sqlSource, SqlCommandType.SELECT).resultMaps(new ArrayList() {\n\n {\n add(new ResultMap.Builder(configuration, \"defaultResultMap\", resultType, new ArrayList<>(0)).build());\n }\n }).build();\n // 缓存\n configuration.addMappedStatement(ms);\n }\n\n /**\n * 创建一个MappedStatement\n *\n * @param mappedStatement\n * @param sqlSource 执行的sqlSource\n * @param sqlCommandType 执行的sqlCommandType\n */\n @SuppressWarnings(\"serial\")\n private void createUpdateMappedStatement(String mappedStatement, SqlSource sqlSource, SqlCommandType sqlCommandType) ", "post_mask_code": "\n\n private void initSelectList() {\n if (hasMappedStatement(ISqlRunner.SELECT_LIST)) {\n logger.warn(\"MappedStatement 'SqlRunner.SelectList' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createSelectMappedStatement(ISqlRunner.SELECT_LIST, sqlSource, Map.class);\n }\n\n private void initSelectObjs() {\n if (hasMappedStatement(ISqlRunner.SELECT_OBJS)) {\n logger.warn(\"MappedStatement 'SqlRunner.SelectObjs' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Object.class);\n createSelectMappedStatement(ISqlRunner.SELECT_OBJS, sqlSource, Object.class);\n }\n\n private void initCount() {\n if (hasMappedStatement(ISqlRunner.COUNT)) {\n logger.warn(\"MappedStatement 'SqlRunner.Count' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createSelectMappedStatement(ISqlRunner.COUNT, sqlSource, Long.class);\n }\n\n private void initInsert() {\n if (hasMappedStatement(ISqlRunner.INSERT)) {\n logger.warn(\"MappedStatement 'SqlRunner.Insert' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createUpdateMappedStatement(ISqlRunner.INSERT, sqlSource, SqlCommandType.INSERT);\n }\n\n private void initUpdate() {\n if (hasMappedStatement(ISqlRunner.UPDATE)) {\n logger.warn(\"MappedStatement 'SqlRunner.Update' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createUpdateMappedStatement(ISqlRunner.UPDATE, sqlSource, SqlCommandType.UPDATE);\n }\n\n private void initDelete() {\n if (hasMappedStatement(ISqlRunner.DELETE)) {\n logger.warn(\"MappedStatement 'SqlRunner.Delete' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createUpdateMappedStatement(ISqlRunner.DELETE, sqlSource, SqlCommandType.DELETE);\n }\n}\n"} {"task_id": "Java_2512", "language": "Java", "task_type": "single_line", "source_file": "java/github/baomidou/mybatis-plus/mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/injector/SqlRunnerInjector.java", "mask_start_position": 2077, "mask_end_position": 2093, "canonical_solution": "edStatement(ms);", "pre_mask_code": "package com.baomidou.mybatisplus.core.injector;\n\nimport com.baomidou.mybatisplus.core.assist.ISqlRunner;\nimport org.apache.ibatis.logging.Log;\nimport org.apache.ibatis.logging.LogFactory;\nimport org.apache.ibatis.mapping.MappedStatement;\nimport org.apache.ibatis.mapping.ResultMap;\nimport org.apache.ibatis.mapping.SqlCommandType;\nimport org.apache.ibatis.mapping.SqlSource;\nimport org.apache.ibatis.scripting.LanguageDriver;\nimport org.apache.ibatis.session.Configuration;\nimport java.util.ArrayList;\nimport java.util.Map;\n\n/**\n * SqlRunner 注入器\n *\n * @author hubin\n * @since 2018-04-08\n */\npublic class SqlRunnerInjector {\n\n private static final Log logger = LogFactory.getLog(SqlRunnerInjector.class);\n\n protected Configuration configuration;\n\n protected LanguageDriver languageDriver;\n\n public void inject(Configuration configuration) {\n this.configuration = configuration;\n this.languageDriver = configuration.getDefaultScriptingLanguageInstance();\n this.initSelectList();\n this.initSelectObjs();\n this.initInsert();\n this.initUpdate();\n this.initDelete();\n this.initCount();\n }\n\n /**\n * 是否已经存在MappedStatement\n *\n * @param mappedStatement\n * @return\n */\n private boolean hasMappedStatement(String mappedStatement) {\n return configuration.hasStatement(mappedStatement, false);\n }\n\n /**\n * 创建查询MappedStatement\n *\n * @param mappedStatement\n * @param sqlSource 执行的sqlSource\n * @param resultType 返回的结果类型\n */\n @SuppressWarnings(\"serial\")\n private void createSelectMappedStatement(String mappedStatement, SqlSource sqlSource, final Class resultType) {\n MappedStatement ms = new MappedStatement.Builder(configuration, mappedStatement, sqlSource, SqlCommandType.SELECT).resultMaps(new ArrayList() {\n\n {\n add(new ResultMap.Builder(configuration, \"defaultResultMap\", resultType, new ArrayList<>(0)).build());\n }\n }).build();\n // 缓存\n configuration.addMapp", "post_mask_code": "\n }\n\n /**\n * 创建一个MappedStatement\n *\n * @param mappedStatement\n * @param sqlSource 执行的sqlSource\n * @param sqlCommandType 执行的sqlCommandType\n */\n @SuppressWarnings(\"serial\")\n private void createUpdateMappedStatement(String mappedStatement, SqlSource sqlSource, SqlCommandType sqlCommandType) {\n MappedStatement ms = new MappedStatement.Builder(configuration, mappedStatement, sqlSource, sqlCommandType).resultMaps(new ArrayList() {\n\n {\n add(new ResultMap.Builder(configuration, \"defaultResultMap\", int.class, new ArrayList<>(0)).build());\n }\n }).build();\n // 缓存\n configuration.addMappedStatement(ms);\n }\n\n private void initSelectList() {\n if (hasMappedStatement(ISqlRunner.SELECT_LIST)) {\n logger.warn(\"MappedStatement 'SqlRunner.SelectList' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createSelectMappedStatement(ISqlRunner.SELECT_LIST, sqlSource, Map.class);\n }\n\n private void initSelectObjs() {\n if (hasMappedStatement(ISqlRunner.SELECT_OBJS)) {\n logger.warn(\"MappedStatement 'SqlRunner.SelectObjs' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Object.class);\n createSelectMappedStatement(ISqlRunner.SELECT_OBJS, sqlSource, Object.class);\n }\n\n private void initCount() {\n if (hasMappedStatement(ISqlRunner.COUNT)) {\n logger.warn(\"MappedStatement 'SqlRunner.Count' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createSelectMappedStatement(ISqlRunner.COUNT, sqlSource, Long.class);\n }\n\n private void initInsert() {\n if (hasMappedStatement(ISqlRunner.INSERT)) {\n logger.warn(\"MappedStatement 'SqlRunner.Insert' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createUpdateMappedStatement(ISqlRunner.INSERT, sqlSource, SqlCommandType.INSERT);\n }\n\n private void initUpdate() {\n if (hasMappedStatement(ISqlRunner.UPDATE)) {\n logger.warn(\"MappedStatement 'SqlRunner.Update' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createUpdateMappedStatement(ISqlRunner.UPDATE, sqlSource, SqlCommandType.UPDATE);\n }\n\n private void initDelete() {\n if (hasMappedStatement(ISqlRunner.DELETE)) {\n logger.warn(\"MappedStatement 'SqlRunner.Delete' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createUpdateMappedStatement(ISqlRunner.DELETE, sqlSource, SqlCommandType.DELETE);\n }\n}\n"} {"task_id": "Java_2513", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/baomidou/mybatis-plus/mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/injector/SqlRunnerInjector.java", "mask_start_position": 1256, "mask_end_position": 1389, "canonical_solution": "private boolean hasMappedStatement(String mappedStatement) {\n return configuration.hasStatement(mappedStatement, false);\n }", "pre_mask_code": "package com.baomidou.mybatisplus.core.injector;\n\nimport com.baomidou.mybatisplus.core.assist.ISqlRunner;\nimport org.apache.ibatis.logging.Log;\nimport org.apache.ibatis.logging.LogFactory;\nimport org.apache.ibatis.mapping.MappedStatement;\nimport org.apache.ibatis.mapping.ResultMap;\nimport org.apache.ibatis.mapping.SqlCommandType;\nimport org.apache.ibatis.mapping.SqlSource;\nimport org.apache.ibatis.scripting.LanguageDriver;\nimport org.apache.ibatis.session.Configuration;\nimport java.util.ArrayList;\nimport java.util.Map;\n\n/**\n * SqlRunner 注入器\n *\n * @author hubin\n * @since 2018-04-08\n */\npublic class SqlRunnerInjector {\n\n private static final Log logger = LogFactory.getLog(SqlRunnerInjector.class);\n\n protected Configuration configuration;\n\n protected LanguageDriver languageDriver;\n\n public void inject(Configuration configuration) {\n this.configuration = configuration;\n this.languageDriver = configuration.getDefaultScriptingLanguageInstance();\n this.initSelectList();\n this.initSelectObjs();\n this.initInsert();\n this.initUpdate();\n this.initDelete();\n this.initCount();\n }\n\n /**\n * 是否已经存在MappedStatement\n *\n * @param mappedStatement\n * @return\n */\n ", "post_mask_code": "\n\n /**\n * 创建查询MappedStatement\n *\n * @param mappedStatement\n * @param sqlSource 执行的sqlSource\n * @param resultType 返回的结果类型\n */\n @SuppressWarnings(\"serial\")\n private void createSelectMappedStatement(String mappedStatement, SqlSource sqlSource, final Class resultType) {\n MappedStatement ms = new MappedStatement.Builder(configuration, mappedStatement, sqlSource, SqlCommandType.SELECT).resultMaps(new ArrayList() {\n\n {\n add(new ResultMap.Builder(configuration, \"defaultResultMap\", resultType, new ArrayList<>(0)).build());\n }\n }).build();\n // 缓存\n configuration.addMappedStatement(ms);\n }\n\n /**\n * 创建一个MappedStatement\n *\n * @param mappedStatement\n * @param sqlSource 执行的sqlSource\n * @param sqlCommandType 执行的sqlCommandType\n */\n @SuppressWarnings(\"serial\")\n private void createUpdateMappedStatement(String mappedStatement, SqlSource sqlSource, SqlCommandType sqlCommandType) {\n MappedStatement ms = new MappedStatement.Builder(configuration, mappedStatement, sqlSource, sqlCommandType).resultMaps(new ArrayList() {\n\n {\n add(new ResultMap.Builder(configuration, \"defaultResultMap\", int.class, new ArrayList<>(0)).build());\n }\n }).build();\n // 缓存\n configuration.addMappedStatement(ms);\n }\n\n private void initSelectList() {\n if (hasMappedStatement(ISqlRunner.SELECT_LIST)) {\n logger.warn(\"MappedStatement 'SqlRunner.SelectList' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createSelectMappedStatement(ISqlRunner.SELECT_LIST, sqlSource, Map.class);\n }\n\n private void initSelectObjs() {\n if (hasMappedStatement(ISqlRunner.SELECT_OBJS)) {\n logger.warn(\"MappedStatement 'SqlRunner.SelectObjs' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Object.class);\n createSelectMappedStatement(ISqlRunner.SELECT_OBJS, sqlSource, Object.class);\n }\n\n private void initCount() {\n if (hasMappedStatement(ISqlRunner.COUNT)) {\n logger.warn(\"MappedStatement 'SqlRunner.Count' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createSelectMappedStatement(ISqlRunner.COUNT, sqlSource, Long.class);\n }\n\n private void initInsert() {\n if (hasMappedStatement(ISqlRunner.INSERT)) {\n logger.warn(\"MappedStatement 'SqlRunner.Insert' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createUpdateMappedStatement(ISqlRunner.INSERT, sqlSource, SqlCommandType.INSERT);\n }\n\n private void initUpdate() {\n if (hasMappedStatement(ISqlRunner.UPDATE)) {\n logger.warn(\"MappedStatement 'SqlRunner.Update' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createUpdateMappedStatement(ISqlRunner.UPDATE, sqlSource, SqlCommandType.UPDATE);\n }\n\n private void initDelete() {\n if (hasMappedStatement(ISqlRunner.DELETE)) {\n logger.warn(\"MappedStatement 'SqlRunner.Delete' Already Exists\");\n return;\n }\n SqlSource sqlSource = languageDriver.createSqlSource(configuration, ISqlRunner.SQL_SCRIPT, Map.class);\n createUpdateMappedStatement(ISqlRunner.DELETE, sqlSource, SqlCommandType.DELETE);\n }\n}\n"} {"task_id": "Java_2514", "language": "Java", "task_type": "method_signature", "source_file": "java/github/flightstats/hub/src/main/java/com/flightstats/hub/util/SecretFilter.java", "mask_start_position": 274, "mask_end_position": 324, "canonical_solution": "public String redact(String key, String property) ", "pre_mask_code": "package com.flightstats.hub.util;\n\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class SecretFilter {\n\n private final static String redacted = \"[REDACTED]\";\n\n private final static List matchers = Arrays.asList(\"app_key\", \"api_key\", \"password\");\n\n ", "post_mask_code": "{\n boolean shouldRedact = matchers.stream().anyMatch(key::contains);\n return shouldRedact ? redacted : property;\n }\n}\n"} {"task_id": "Java_2515", "language": "Java", "task_type": "method_body", "source_file": "java/github/flightstats/hub/src/main/java/com/flightstats/hub/util/SecretFilter.java", "mask_start_position": 324, "mask_end_position": 456, "canonical_solution": "{\n boolean shouldRedact = matchers.stream().anyMatch(key::contains);\n return shouldRedact ? redacted : property;\n }", "pre_mask_code": "package com.flightstats.hub.util;\n\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class SecretFilter {\n\n private final static String redacted = \"[REDACTED]\";\n\n private final static List matchers = Arrays.asList(\"app_key\", \"api_key\", \"password\");\n\n public String redact(String key, String property) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2516", "language": "Java", "task_type": "single_line", "source_file": "java/github/flightstats/hub/src/main/java/com/flightstats/hub/util/SecretFilter.java", "mask_start_position": 359, "mask_end_position": 399, "canonical_solution": "tchers.stream().anyMatch(key::contains);", "pre_mask_code": "package com.flightstats.hub.util;\n\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class SecretFilter {\n\n private final static String redacted = \"[REDACTED]\";\n\n private final static List matchers = Arrays.asList(\"app_key\", \"api_key\", \"password\");\n\n public String redact(String key, String property) {\n boolean shouldRedact = ma", "post_mask_code": "\n return shouldRedact ? redacted : property;\n }\n}\n"} {"task_id": "Java_2517", "language": "Java", "task_type": "method_signature", "source_file": "java/github/oracle/visualvm/visualvm/libs.profiler/lib.profiler/src-cvm/org/graalvm/visualvm/lib/jfluid/server/system/Histogram.java", "mask_start_position": 299, "mask_end_position": 343, "canonical_solution": "public static InputStream getRawHistogram() ", "pre_mask_code": "package org.graalvm.visualvm.lib.jfluid.server.system;\n\nimport java.io.InputStream;\n\n/**\n * @author Tomas Hurka\n */\npublic class Histogram {\n\n public static boolean isAvailable() {\n return false;\n }\n\n public static boolean initialize(boolean jdk9) {\n return false;\n }\n\n ", "post_mask_code": "{\n return null;\n }\n}\n"} {"task_id": "Java_2518", "language": "Java", "task_type": "method_body", "source_file": "java/github/oracle/visualvm/visualvm/libs.profiler/lib.profiler/src-cvm/org/graalvm/visualvm/lib/jfluid/server/system/Histogram.java", "mask_start_position": 343, "mask_end_position": 371, "canonical_solution": "{\n return null;\n }", "pre_mask_code": "package org.graalvm.visualvm.lib.jfluid.server.system;\n\nimport java.io.InputStream;\n\n/**\n * @author Tomas Hurka\n */\npublic class Histogram {\n\n public static boolean isAvailable() {\n return false;\n }\n\n public static boolean initialize(boolean jdk9) {\n return false;\n }\n\n public static InputStream getRawHistogram() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2519", "language": "Java", "task_type": "single_line", "source_file": "java/github/oracle/visualvm/visualvm/libs.profiler/lib.profiler/src-cvm/org/graalvm/visualvm/lib/jfluid/server/system/Histogram.java", "mask_start_position": 356, "mask_end_position": 365, "canonical_solution": "urn null;", "pre_mask_code": "package org.graalvm.visualvm.lib.jfluid.server.system;\n\nimport java.io.InputStream;\n\n/**\n * @author Tomas Hurka\n */\npublic class Histogram {\n\n public static boolean isAvailable() {\n return false;\n }\n\n public static boolean initialize(boolean jdk9) {\n return false;\n }\n\n public static InputStream getRawHistogram() {\n ret", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2520", "language": "Java", "task_type": "method_signature", "source_file": "java/github/spring-projects/spring-framework/spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java", "mask_start_position": 7887, "mask_end_position": 8061, "canonical_solution": "@Override\n @Nullable\n public Object getScriptedObject(ScriptSource scriptSource, @Nullable Class... actualInterfaces) throws IOException, ScriptCompilationException ", "pre_mask_code": "package org.springframework.scripting.groovy;\n\nimport java.io.IOException;\nimport java.lang.reflect.InvocationTargetException;\nimport groovy.lang.GroovyClassLoader;\nimport groovy.lang.GroovyObject;\nimport groovy.lang.MetaClass;\nimport groovy.lang.Script;\nimport org.codehaus.groovy.control.CompilationFailedException;\nimport org.codehaus.groovy.control.CompilerConfiguration;\nimport org.codehaus.groovy.control.customizers.CompilationCustomizer;\nimport org.springframework.beans.factory.BeanClassLoaderAware;\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.beans.factory.BeanFactoryAware;\nimport org.springframework.beans.factory.config.ConfigurableListableBeanFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.scripting.ScriptCompilationException;\nimport org.springframework.scripting.ScriptFactory;\nimport org.springframework.scripting.ScriptSource;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ClassUtils;\nimport org.springframework.util.ObjectUtils;\nimport org.springframework.util.ReflectionUtils;\n\n/**\n * {@link org.springframework.scripting.ScriptFactory} implementation\n * for a Groovy script.\n *\n *

Typically used in combination with a\n * {@link org.springframework.scripting.support.ScriptFactoryPostProcessor};\n * see the latter's javadoc for a configuration example.\n *\n *

Note: Spring 4.0 supports Groovy 1.8 and higher.\n *\n * @author Juergen Hoeller\n * @author Rob Harrop\n * @author Rod Johnson\n * @since 2.0\n * @see groovy.lang.GroovyClassLoader\n * @see org.springframework.scripting.support.ScriptFactoryPostProcessor\n */\npublic class GroovyScriptFactory implements ScriptFactory, BeanFactoryAware, BeanClassLoaderAware {\n\n private final String scriptSourceLocator;\n\n @Nullable\n private GroovyObjectCustomizer groovyObjectCustomizer;\n\n @Nullable\n private CompilerConfiguration compilerConfiguration;\n\n @Nullable\n private GroovyClassLoader groovyClassLoader;\n\n @Nullable\n private Class scriptClass;\n\n @Nullable\n private Class scriptResultClass;\n\n @Nullable\n private CachedResultHolder cachedResult;\n\n private final Object scriptClassMonitor = new Object();\n\n private boolean wasModifiedForTypeCheck = false;\n\n /**\n * Create a new GroovyScriptFactory for the given script source.\n *

We don't need to specify script interfaces here, since\n * a Groovy script defines its Java interfaces itself.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n */\n public GroovyScriptFactory(String scriptSourceLocator) {\n Assert.hasText(scriptSourceLocator, \"'scriptSourceLocator' must not be empty\");\n this.scriptSourceLocator = scriptSourceLocator;\n }\n\n /**\n * Create a new GroovyScriptFactory for the given script source,\n * specifying a strategy interface that can create a custom MetaClass\n * to supply missing methods and otherwise change the behavior of the object.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n * @param groovyObjectCustomizer a customizer that can set a custom metaclass\n * or make other changes to the GroovyObject created by this factory\n * (may be {@code null})\n * @see GroovyObjectCustomizer#customize\n */\n public GroovyScriptFactory(String scriptSourceLocator, @Nullable GroovyObjectCustomizer groovyObjectCustomizer) {\n this(scriptSourceLocator);\n this.groovyObjectCustomizer = groovyObjectCustomizer;\n }\n\n /**\n * Create a new GroovyScriptFactory for the given script source,\n * specifying a strategy interface that can create a custom MetaClass\n * to supply missing methods and otherwise change the behavior of the object.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n * @param compilerConfiguration a custom compiler configuration to be applied\n * to the GroovyClassLoader (may be {@code null})\n * @since 4.3.3\n * @see GroovyClassLoader#GroovyClassLoader(ClassLoader, CompilerConfiguration)\n */\n public GroovyScriptFactory(String scriptSourceLocator, @Nullable CompilerConfiguration compilerConfiguration) {\n this(scriptSourceLocator);\n this.compilerConfiguration = compilerConfiguration;\n }\n\n /**\n * Create a new GroovyScriptFactory for the given script source,\n * specifying a strategy interface that can customize Groovy's compilation\n * process within the underlying GroovyClassLoader.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n * @param compilationCustomizers one or more customizers to be applied to the\n * GroovyClassLoader compiler configuration\n * @since 4.3.3\n * @see CompilerConfiguration#addCompilationCustomizers\n * @see org.codehaus.groovy.control.customizers.ImportCustomizer\n */\n public GroovyScriptFactory(String scriptSourceLocator, CompilationCustomizer... compilationCustomizers) {\n this(scriptSourceLocator);\n if (!ObjectUtils.isEmpty(compilationCustomizers)) {\n this.compilerConfiguration = new CompilerConfiguration();\n this.compilerConfiguration.addCompilationCustomizers(compilationCustomizers);\n }\n }\n\n @Override\n public void setBeanFactory(BeanFactory beanFactory) {\n if (beanFactory instanceof ConfigurableListableBeanFactory) {\n ((ConfigurableListableBeanFactory) beanFactory).ignoreDependencyType(MetaClass.class);\n }\n }\n\n @Override\n public void setBeanClassLoader(ClassLoader classLoader) {\n if (classLoader instanceof GroovyClassLoader && (this.compilerConfiguration == null || ((GroovyClassLoader) classLoader).hasCompatibleConfiguration(this.compilerConfiguration))) {\n this.groovyClassLoader = (GroovyClassLoader) classLoader;\n } else {\n this.groovyClassLoader = buildGroovyClassLoader(classLoader);\n }\n }\n\n /**\n * Return the GroovyClassLoader used by this script factory.\n */\n public GroovyClassLoader getGroovyClassLoader() {\n synchronized (this.scriptClassMonitor) {\n if (this.groovyClassLoader == null) {\n this.groovyClassLoader = buildGroovyClassLoader(ClassUtils.getDefaultClassLoader());\n }\n return this.groovyClassLoader;\n }\n }\n\n /**\n * Build a {@link GroovyClassLoader} for the given {@code ClassLoader}.\n * @param classLoader the ClassLoader to build a GroovyClassLoader for\n * @since 4.3.3\n */\n protected GroovyClassLoader buildGroovyClassLoader(@Nullable ClassLoader classLoader) {\n return (this.compilerConfiguration != null ? new GroovyClassLoader(classLoader, this.compilerConfiguration) : new GroovyClassLoader(classLoader));\n }\n\n @Override\n public String getScriptSourceLocator() {\n return this.scriptSourceLocator;\n }\n\n /**\n * Groovy scripts determine their interfaces themselves,\n * hence we don't need to explicitly expose interfaces here.\n * @return {@code null} always\n */\n @Override\n @Nullable\n public Class[] getScriptInterfaces() {\n return null;\n }\n\n /**\n * Groovy scripts do not need a config interface,\n * since they expose their setters as public methods.\n */\n @Override\n public boolean requiresConfigInterface() {\n return false;\n }\n\n /**\n * Loads and parses the Groovy script via the GroovyClassLoader.\n * @see groovy.lang.GroovyClassLoader\n */\n ", "post_mask_code": "{\n synchronized (this.scriptClassMonitor) {\n try {\n Class scriptClassToExecute;\n this.wasModifiedForTypeCheck = false;\n if (this.cachedResult != null) {\n Object result = this.cachedResult.object;\n this.cachedResult = null;\n return result;\n }\n if (this.scriptClass == null || scriptSource.isModified()) {\n // New script content...\n this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());\n if (Script.class.isAssignableFrom(this.scriptClass)) {\n // A Groovy script, probably creating an instance: let's execute it.\n Object result = executeScript(scriptSource, this.scriptClass);\n this.scriptResultClass = (result != null ? result.getClass() : null);\n return result;\n } else {\n this.scriptResultClass = this.scriptClass;\n }\n }\n scriptClassToExecute = this.scriptClass;\n // Process re-execution outside of the synchronized block.\n return executeScript(scriptSource, scriptClassToExecute);\n } catch (CompilationFailedException ex) {\n this.scriptClass = null;\n this.scriptResultClass = null;\n throw new ScriptCompilationException(scriptSource, ex);\n }\n }\n }\n\n @Override\n @Nullable\n public Class getScriptedObjectType(ScriptSource scriptSource) throws IOException, ScriptCompilationException {\n synchronized (this.scriptClassMonitor) {\n try {\n if (this.scriptClass == null || scriptSource.isModified()) {\n // New script content...\n this.wasModifiedForTypeCheck = true;\n this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());\n if (Script.class.isAssignableFrom(this.scriptClass)) {\n // A Groovy script, probably creating an instance: let's execute it.\n Object result = executeScript(scriptSource, this.scriptClass);\n this.scriptResultClass = (result != null ? result.getClass() : null);\n this.cachedResult = new CachedResultHolder(result);\n } else {\n this.scriptResultClass = this.scriptClass;\n }\n }\n return this.scriptResultClass;\n } catch (CompilationFailedException ex) {\n this.scriptClass = null;\n this.scriptResultClass = null;\n this.cachedResult = null;\n throw new ScriptCompilationException(scriptSource, ex);\n }\n }\n }\n\n @Override\n public boolean requiresScriptedObjectRefresh(ScriptSource scriptSource) {\n synchronized (this.scriptClassMonitor) {\n return (scriptSource.isModified() || this.wasModifiedForTypeCheck);\n }\n }\n\n /**\n * Instantiate the given Groovy script class and run it if necessary.\n * @param scriptSource the source for the underlying script\n * @param scriptClass the Groovy script class\n * @return the result object (either an instance of the script class\n * or the result of running the script instance)\n * @throws ScriptCompilationException in case of instantiation failure\n */\n @Nullable\n protected Object executeScript(ScriptSource scriptSource, Class scriptClass) throws ScriptCompilationException {\n try {\n GroovyObject goo = (GroovyObject) ReflectionUtils.accessibleConstructor(scriptClass).newInstance();\n if (this.groovyObjectCustomizer != null) {\n // Allow metaclass and other customization.\n this.groovyObjectCustomizer.customize(goo);\n }\n if (goo instanceof Script) {\n // A Groovy script, probably creating an instance: let's execute it.\n return ((Script) goo).run();\n } else {\n // An instance of the scripted class: let's return it as-is.\n return goo;\n }\n } catch (NoSuchMethodException ex) {\n throw new ScriptCompilationException(\"No default constructor on Groovy script class: \" + scriptClass.getName(), ex);\n } catch (InstantiationException ex) {\n throw new ScriptCompilationException(scriptSource, \"Unable to instantiate Groovy script class: \" + scriptClass.getName(), ex);\n } catch (IllegalAccessException ex) {\n throw new ScriptCompilationException(scriptSource, \"Could not access Groovy script constructor: \" + scriptClass.getName(), ex);\n } catch (InvocationTargetException ex) {\n throw new ScriptCompilationException(\"Failed to invoke Groovy script constructor: \" + scriptClass.getName(), ex.getTargetException());\n }\n }\n\n @Override\n public String toString() {\n return \"GroovyScriptFactory: script source locator [\" + this.scriptSourceLocator + \"]\";\n }\n\n /**\n * Wrapper that holds a temporarily cached result object.\n */\n private static class CachedResultHolder {\n\n @Nullable\n public final Object object;\n\n public CachedResultHolder(@Nullable Object object) {\n this.object = object;\n }\n }\n}\n"} {"task_id": "Java_2521", "language": "Java", "task_type": "method_body", "source_file": "java/github/spring-projects/spring-framework/spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java", "mask_start_position": 7209, "mask_end_position": 7257, "canonical_solution": "{\n return this.scriptSourceLocator;\n }", "pre_mask_code": "package org.springframework.scripting.groovy;\n\nimport java.io.IOException;\nimport java.lang.reflect.InvocationTargetException;\nimport groovy.lang.GroovyClassLoader;\nimport groovy.lang.GroovyObject;\nimport groovy.lang.MetaClass;\nimport groovy.lang.Script;\nimport org.codehaus.groovy.control.CompilationFailedException;\nimport org.codehaus.groovy.control.CompilerConfiguration;\nimport org.codehaus.groovy.control.customizers.CompilationCustomizer;\nimport org.springframework.beans.factory.BeanClassLoaderAware;\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.beans.factory.BeanFactoryAware;\nimport org.springframework.beans.factory.config.ConfigurableListableBeanFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.scripting.ScriptCompilationException;\nimport org.springframework.scripting.ScriptFactory;\nimport org.springframework.scripting.ScriptSource;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ClassUtils;\nimport org.springframework.util.ObjectUtils;\nimport org.springframework.util.ReflectionUtils;\n\n/**\n * {@link org.springframework.scripting.ScriptFactory} implementation\n * for a Groovy script.\n *\n *

Typically used in combination with a\n * {@link org.springframework.scripting.support.ScriptFactoryPostProcessor};\n * see the latter's javadoc for a configuration example.\n *\n *

Note: Spring 4.0 supports Groovy 1.8 and higher.\n *\n * @author Juergen Hoeller\n * @author Rob Harrop\n * @author Rod Johnson\n * @since 2.0\n * @see groovy.lang.GroovyClassLoader\n * @see org.springframework.scripting.support.ScriptFactoryPostProcessor\n */\npublic class GroovyScriptFactory implements ScriptFactory, BeanFactoryAware, BeanClassLoaderAware {\n\n private final String scriptSourceLocator;\n\n @Nullable\n private GroovyObjectCustomizer groovyObjectCustomizer;\n\n @Nullable\n private CompilerConfiguration compilerConfiguration;\n\n @Nullable\n private GroovyClassLoader groovyClassLoader;\n\n @Nullable\n private Class scriptClass;\n\n @Nullable\n private Class scriptResultClass;\n\n @Nullable\n private CachedResultHolder cachedResult;\n\n private final Object scriptClassMonitor = new Object();\n\n private boolean wasModifiedForTypeCheck = false;\n\n /**\n * Create a new GroovyScriptFactory for the given script source.\n *

We don't need to specify script interfaces here, since\n * a Groovy script defines its Java interfaces itself.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n */\n public GroovyScriptFactory(String scriptSourceLocator) {\n Assert.hasText(scriptSourceLocator, \"'scriptSourceLocator' must not be empty\");\n this.scriptSourceLocator = scriptSourceLocator;\n }\n\n /**\n * Create a new GroovyScriptFactory for the given script source,\n * specifying a strategy interface that can create a custom MetaClass\n * to supply missing methods and otherwise change the behavior of the object.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n * @param groovyObjectCustomizer a customizer that can set a custom metaclass\n * or make other changes to the GroovyObject created by this factory\n * (may be {@code null})\n * @see GroovyObjectCustomizer#customize\n */\n public GroovyScriptFactory(String scriptSourceLocator, @Nullable GroovyObjectCustomizer groovyObjectCustomizer) {\n this(scriptSourceLocator);\n this.groovyObjectCustomizer = groovyObjectCustomizer;\n }\n\n /**\n * Create a new GroovyScriptFactory for the given script source,\n * specifying a strategy interface that can create a custom MetaClass\n * to supply missing methods and otherwise change the behavior of the object.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n * @param compilerConfiguration a custom compiler configuration to be applied\n * to the GroovyClassLoader (may be {@code null})\n * @since 4.3.3\n * @see GroovyClassLoader#GroovyClassLoader(ClassLoader, CompilerConfiguration)\n */\n public GroovyScriptFactory(String scriptSourceLocator, @Nullable CompilerConfiguration compilerConfiguration) {\n this(scriptSourceLocator);\n this.compilerConfiguration = compilerConfiguration;\n }\n\n /**\n * Create a new GroovyScriptFactory for the given script source,\n * specifying a strategy interface that can customize Groovy's compilation\n * process within the underlying GroovyClassLoader.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n * @param compilationCustomizers one or more customizers to be applied to the\n * GroovyClassLoader compiler configuration\n * @since 4.3.3\n * @see CompilerConfiguration#addCompilationCustomizers\n * @see org.codehaus.groovy.control.customizers.ImportCustomizer\n */\n public GroovyScriptFactory(String scriptSourceLocator, CompilationCustomizer... compilationCustomizers) {\n this(scriptSourceLocator);\n if (!ObjectUtils.isEmpty(compilationCustomizers)) {\n this.compilerConfiguration = new CompilerConfiguration();\n this.compilerConfiguration.addCompilationCustomizers(compilationCustomizers);\n }\n }\n\n @Override\n public void setBeanFactory(BeanFactory beanFactory) {\n if (beanFactory instanceof ConfigurableListableBeanFactory) {\n ((ConfigurableListableBeanFactory) beanFactory).ignoreDependencyType(MetaClass.class);\n }\n }\n\n @Override\n public void setBeanClassLoader(ClassLoader classLoader) {\n if (classLoader instanceof GroovyClassLoader && (this.compilerConfiguration == null || ((GroovyClassLoader) classLoader).hasCompatibleConfiguration(this.compilerConfiguration))) {\n this.groovyClassLoader = (GroovyClassLoader) classLoader;\n } else {\n this.groovyClassLoader = buildGroovyClassLoader(classLoader);\n }\n }\n\n /**\n * Return the GroovyClassLoader used by this script factory.\n */\n public GroovyClassLoader getGroovyClassLoader() {\n synchronized (this.scriptClassMonitor) {\n if (this.groovyClassLoader == null) {\n this.groovyClassLoader = buildGroovyClassLoader(ClassUtils.getDefaultClassLoader());\n }\n return this.groovyClassLoader;\n }\n }\n\n /**\n * Build a {@link GroovyClassLoader} for the given {@code ClassLoader}.\n * @param classLoader the ClassLoader to build a GroovyClassLoader for\n * @since 4.3.3\n */\n protected GroovyClassLoader buildGroovyClassLoader(@Nullable ClassLoader classLoader) {\n return (this.compilerConfiguration != null ? new GroovyClassLoader(classLoader, this.compilerConfiguration) : new GroovyClassLoader(classLoader));\n }\n\n @Override\n public String getScriptSourceLocator() ", "post_mask_code": "\n\n /**\n * Groovy scripts determine their interfaces themselves,\n * hence we don't need to explicitly expose interfaces here.\n * @return {@code null} always\n */\n @Override\n @Nullable\n public Class[] getScriptInterfaces() {\n return null;\n }\n\n /**\n * Groovy scripts do not need a config interface,\n * since they expose their setters as public methods.\n */\n @Override\n public boolean requiresConfigInterface() {\n return false;\n }\n\n /**\n * Loads and parses the Groovy script via the GroovyClassLoader.\n * @see groovy.lang.GroovyClassLoader\n */\n @Override\n @Nullable\n public Object getScriptedObject(ScriptSource scriptSource, @Nullable Class... actualInterfaces) throws IOException, ScriptCompilationException {\n synchronized (this.scriptClassMonitor) {\n try {\n Class scriptClassToExecute;\n this.wasModifiedForTypeCheck = false;\n if (this.cachedResult != null) {\n Object result = this.cachedResult.object;\n this.cachedResult = null;\n return result;\n }\n if (this.scriptClass == null || scriptSource.isModified()) {\n // New script content...\n this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());\n if (Script.class.isAssignableFrom(this.scriptClass)) {\n // A Groovy script, probably creating an instance: let's execute it.\n Object result = executeScript(scriptSource, this.scriptClass);\n this.scriptResultClass = (result != null ? result.getClass() : null);\n return result;\n } else {\n this.scriptResultClass = this.scriptClass;\n }\n }\n scriptClassToExecute = this.scriptClass;\n // Process re-execution outside of the synchronized block.\n return executeScript(scriptSource, scriptClassToExecute);\n } catch (CompilationFailedException ex) {\n this.scriptClass = null;\n this.scriptResultClass = null;\n throw new ScriptCompilationException(scriptSource, ex);\n }\n }\n }\n\n @Override\n @Nullable\n public Class getScriptedObjectType(ScriptSource scriptSource) throws IOException, ScriptCompilationException {\n synchronized (this.scriptClassMonitor) {\n try {\n if (this.scriptClass == null || scriptSource.isModified()) {\n // New script content...\n this.wasModifiedForTypeCheck = true;\n this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());\n if (Script.class.isAssignableFrom(this.scriptClass)) {\n // A Groovy script, probably creating an instance: let's execute it.\n Object result = executeScript(scriptSource, this.scriptClass);\n this.scriptResultClass = (result != null ? result.getClass() : null);\n this.cachedResult = new CachedResultHolder(result);\n } else {\n this.scriptResultClass = this.scriptClass;\n }\n }\n return this.scriptResultClass;\n } catch (CompilationFailedException ex) {\n this.scriptClass = null;\n this.scriptResultClass = null;\n this.cachedResult = null;\n throw new ScriptCompilationException(scriptSource, ex);\n }\n }\n }\n\n @Override\n public boolean requiresScriptedObjectRefresh(ScriptSource scriptSource) {\n synchronized (this.scriptClassMonitor) {\n return (scriptSource.isModified() || this.wasModifiedForTypeCheck);\n }\n }\n\n /**\n * Instantiate the given Groovy script class and run it if necessary.\n * @param scriptSource the source for the underlying script\n * @param scriptClass the Groovy script class\n * @return the result object (either an instance of the script class\n * or the result of running the script instance)\n * @throws ScriptCompilationException in case of instantiation failure\n */\n @Nullable\n protected Object executeScript(ScriptSource scriptSource, Class scriptClass) throws ScriptCompilationException {\n try {\n GroovyObject goo = (GroovyObject) ReflectionUtils.accessibleConstructor(scriptClass).newInstance();\n if (this.groovyObjectCustomizer != null) {\n // Allow metaclass and other customization.\n this.groovyObjectCustomizer.customize(goo);\n }\n if (goo instanceof Script) {\n // A Groovy script, probably creating an instance: let's execute it.\n return ((Script) goo).run();\n } else {\n // An instance of the scripted class: let's return it as-is.\n return goo;\n }\n } catch (NoSuchMethodException ex) {\n throw new ScriptCompilationException(\"No default constructor on Groovy script class: \" + scriptClass.getName(), ex);\n } catch (InstantiationException ex) {\n throw new ScriptCompilationException(scriptSource, \"Unable to instantiate Groovy script class: \" + scriptClass.getName(), ex);\n } catch (IllegalAccessException ex) {\n throw new ScriptCompilationException(scriptSource, \"Could not access Groovy script constructor: \" + scriptClass.getName(), ex);\n } catch (InvocationTargetException ex) {\n throw new ScriptCompilationException(\"Failed to invoke Groovy script constructor: \" + scriptClass.getName(), ex.getTargetException());\n }\n }\n\n @Override\n public String toString() {\n return \"GroovyScriptFactory: script source locator [\" + this.scriptSourceLocator + \"]\";\n }\n\n /**\n * Wrapper that holds a temporarily cached result object.\n */\n private static class CachedResultHolder {\n\n @Nullable\n public final Object object;\n\n public CachedResultHolder(@Nullable Object object) {\n this.object = object;\n }\n }\n}\n"} {"task_id": "Java_2522", "language": "Java", "task_type": "single_line", "source_file": "java/github/spring-projects/spring-framework/spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java", "mask_start_position": 7521, "mask_end_position": 7530, "canonical_solution": "urn null;", "pre_mask_code": "package org.springframework.scripting.groovy;\n\nimport java.io.IOException;\nimport java.lang.reflect.InvocationTargetException;\nimport groovy.lang.GroovyClassLoader;\nimport groovy.lang.GroovyObject;\nimport groovy.lang.MetaClass;\nimport groovy.lang.Script;\nimport org.codehaus.groovy.control.CompilationFailedException;\nimport org.codehaus.groovy.control.CompilerConfiguration;\nimport org.codehaus.groovy.control.customizers.CompilationCustomizer;\nimport org.springframework.beans.factory.BeanClassLoaderAware;\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.beans.factory.BeanFactoryAware;\nimport org.springframework.beans.factory.config.ConfigurableListableBeanFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.scripting.ScriptCompilationException;\nimport org.springframework.scripting.ScriptFactory;\nimport org.springframework.scripting.ScriptSource;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ClassUtils;\nimport org.springframework.util.ObjectUtils;\nimport org.springframework.util.ReflectionUtils;\n\n/**\n * {@link org.springframework.scripting.ScriptFactory} implementation\n * for a Groovy script.\n *\n *

Typically used in combination with a\n * {@link org.springframework.scripting.support.ScriptFactoryPostProcessor};\n * see the latter's javadoc for a configuration example.\n *\n *

Note: Spring 4.0 supports Groovy 1.8 and higher.\n *\n * @author Juergen Hoeller\n * @author Rob Harrop\n * @author Rod Johnson\n * @since 2.0\n * @see groovy.lang.GroovyClassLoader\n * @see org.springframework.scripting.support.ScriptFactoryPostProcessor\n */\npublic class GroovyScriptFactory implements ScriptFactory, BeanFactoryAware, BeanClassLoaderAware {\n\n private final String scriptSourceLocator;\n\n @Nullable\n private GroovyObjectCustomizer groovyObjectCustomizer;\n\n @Nullable\n private CompilerConfiguration compilerConfiguration;\n\n @Nullable\n private GroovyClassLoader groovyClassLoader;\n\n @Nullable\n private Class scriptClass;\n\n @Nullable\n private Class scriptResultClass;\n\n @Nullable\n private CachedResultHolder cachedResult;\n\n private final Object scriptClassMonitor = new Object();\n\n private boolean wasModifiedForTypeCheck = false;\n\n /**\n * Create a new GroovyScriptFactory for the given script source.\n *

We don't need to specify script interfaces here, since\n * a Groovy script defines its Java interfaces itself.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n */\n public GroovyScriptFactory(String scriptSourceLocator) {\n Assert.hasText(scriptSourceLocator, \"'scriptSourceLocator' must not be empty\");\n this.scriptSourceLocator = scriptSourceLocator;\n }\n\n /**\n * Create a new GroovyScriptFactory for the given script source,\n * specifying a strategy interface that can create a custom MetaClass\n * to supply missing methods and otherwise change the behavior of the object.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n * @param groovyObjectCustomizer a customizer that can set a custom metaclass\n * or make other changes to the GroovyObject created by this factory\n * (may be {@code null})\n * @see GroovyObjectCustomizer#customize\n */\n public GroovyScriptFactory(String scriptSourceLocator, @Nullable GroovyObjectCustomizer groovyObjectCustomizer) {\n this(scriptSourceLocator);\n this.groovyObjectCustomizer = groovyObjectCustomizer;\n }\n\n /**\n * Create a new GroovyScriptFactory for the given script source,\n * specifying a strategy interface that can create a custom MetaClass\n * to supply missing methods and otherwise change the behavior of the object.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n * @param compilerConfiguration a custom compiler configuration to be applied\n * to the GroovyClassLoader (may be {@code null})\n * @since 4.3.3\n * @see GroovyClassLoader#GroovyClassLoader(ClassLoader, CompilerConfiguration)\n */\n public GroovyScriptFactory(String scriptSourceLocator, @Nullable CompilerConfiguration compilerConfiguration) {\n this(scriptSourceLocator);\n this.compilerConfiguration = compilerConfiguration;\n }\n\n /**\n * Create a new GroovyScriptFactory for the given script source,\n * specifying a strategy interface that can customize Groovy's compilation\n * process within the underlying GroovyClassLoader.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n * @param compilationCustomizers one or more customizers to be applied to the\n * GroovyClassLoader compiler configuration\n * @since 4.3.3\n * @see CompilerConfiguration#addCompilationCustomizers\n * @see org.codehaus.groovy.control.customizers.ImportCustomizer\n */\n public GroovyScriptFactory(String scriptSourceLocator, CompilationCustomizer... compilationCustomizers) {\n this(scriptSourceLocator);\n if (!ObjectUtils.isEmpty(compilationCustomizers)) {\n this.compilerConfiguration = new CompilerConfiguration();\n this.compilerConfiguration.addCompilationCustomizers(compilationCustomizers);\n }\n }\n\n @Override\n public void setBeanFactory(BeanFactory beanFactory) {\n if (beanFactory instanceof ConfigurableListableBeanFactory) {\n ((ConfigurableListableBeanFactory) beanFactory).ignoreDependencyType(MetaClass.class);\n }\n }\n\n @Override\n public void setBeanClassLoader(ClassLoader classLoader) {\n if (classLoader instanceof GroovyClassLoader && (this.compilerConfiguration == null || ((GroovyClassLoader) classLoader).hasCompatibleConfiguration(this.compilerConfiguration))) {\n this.groovyClassLoader = (GroovyClassLoader) classLoader;\n } else {\n this.groovyClassLoader = buildGroovyClassLoader(classLoader);\n }\n }\n\n /**\n * Return the GroovyClassLoader used by this script factory.\n */\n public GroovyClassLoader getGroovyClassLoader() {\n synchronized (this.scriptClassMonitor) {\n if (this.groovyClassLoader == null) {\n this.groovyClassLoader = buildGroovyClassLoader(ClassUtils.getDefaultClassLoader());\n }\n return this.groovyClassLoader;\n }\n }\n\n /**\n * Build a {@link GroovyClassLoader} for the given {@code ClassLoader}.\n * @param classLoader the ClassLoader to build a GroovyClassLoader for\n * @since 4.3.3\n */\n protected GroovyClassLoader buildGroovyClassLoader(@Nullable ClassLoader classLoader) {\n return (this.compilerConfiguration != null ? new GroovyClassLoader(classLoader, this.compilerConfiguration) : new GroovyClassLoader(classLoader));\n }\n\n @Override\n public String getScriptSourceLocator() {\n return this.scriptSourceLocator;\n }\n\n /**\n * Groovy scripts determine their interfaces themselves,\n * hence we don't need to explicitly expose interfaces here.\n * @return {@code null} always\n */\n @Override\n @Nullable\n public Class[] getScriptInterfaces() {\n ret", "post_mask_code": "\n }\n\n /**\n * Groovy scripts do not need a config interface,\n * since they expose their setters as public methods.\n */\n @Override\n public boolean requiresConfigInterface() {\n return false;\n }\n\n /**\n * Loads and parses the Groovy script via the GroovyClassLoader.\n * @see groovy.lang.GroovyClassLoader\n */\n @Override\n @Nullable\n public Object getScriptedObject(ScriptSource scriptSource, @Nullable Class... actualInterfaces) throws IOException, ScriptCompilationException {\n synchronized (this.scriptClassMonitor) {\n try {\n Class scriptClassToExecute;\n this.wasModifiedForTypeCheck = false;\n if (this.cachedResult != null) {\n Object result = this.cachedResult.object;\n this.cachedResult = null;\n return result;\n }\n if (this.scriptClass == null || scriptSource.isModified()) {\n // New script content...\n this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());\n if (Script.class.isAssignableFrom(this.scriptClass)) {\n // A Groovy script, probably creating an instance: let's execute it.\n Object result = executeScript(scriptSource, this.scriptClass);\n this.scriptResultClass = (result != null ? result.getClass() : null);\n return result;\n } else {\n this.scriptResultClass = this.scriptClass;\n }\n }\n scriptClassToExecute = this.scriptClass;\n // Process re-execution outside of the synchronized block.\n return executeScript(scriptSource, scriptClassToExecute);\n } catch (CompilationFailedException ex) {\n this.scriptClass = null;\n this.scriptResultClass = null;\n throw new ScriptCompilationException(scriptSource, ex);\n }\n }\n }\n\n @Override\n @Nullable\n public Class getScriptedObjectType(ScriptSource scriptSource) throws IOException, ScriptCompilationException {\n synchronized (this.scriptClassMonitor) {\n try {\n if (this.scriptClass == null || scriptSource.isModified()) {\n // New script content...\n this.wasModifiedForTypeCheck = true;\n this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());\n if (Script.class.isAssignableFrom(this.scriptClass)) {\n // A Groovy script, probably creating an instance: let's execute it.\n Object result = executeScript(scriptSource, this.scriptClass);\n this.scriptResultClass = (result != null ? result.getClass() : null);\n this.cachedResult = new CachedResultHolder(result);\n } else {\n this.scriptResultClass = this.scriptClass;\n }\n }\n return this.scriptResultClass;\n } catch (CompilationFailedException ex) {\n this.scriptClass = null;\n this.scriptResultClass = null;\n this.cachedResult = null;\n throw new ScriptCompilationException(scriptSource, ex);\n }\n }\n }\n\n @Override\n public boolean requiresScriptedObjectRefresh(ScriptSource scriptSource) {\n synchronized (this.scriptClassMonitor) {\n return (scriptSource.isModified() || this.wasModifiedForTypeCheck);\n }\n }\n\n /**\n * Instantiate the given Groovy script class and run it if necessary.\n * @param scriptSource the source for the underlying script\n * @param scriptClass the Groovy script class\n * @return the result object (either an instance of the script class\n * or the result of running the script instance)\n * @throws ScriptCompilationException in case of instantiation failure\n */\n @Nullable\n protected Object executeScript(ScriptSource scriptSource, Class scriptClass) throws ScriptCompilationException {\n try {\n GroovyObject goo = (GroovyObject) ReflectionUtils.accessibleConstructor(scriptClass).newInstance();\n if (this.groovyObjectCustomizer != null) {\n // Allow metaclass and other customization.\n this.groovyObjectCustomizer.customize(goo);\n }\n if (goo instanceof Script) {\n // A Groovy script, probably creating an instance: let's execute it.\n return ((Script) goo).run();\n } else {\n // An instance of the scripted class: let's return it as-is.\n return goo;\n }\n } catch (NoSuchMethodException ex) {\n throw new ScriptCompilationException(\"No default constructor on Groovy script class: \" + scriptClass.getName(), ex);\n } catch (InstantiationException ex) {\n throw new ScriptCompilationException(scriptSource, \"Unable to instantiate Groovy script class: \" + scriptClass.getName(), ex);\n } catch (IllegalAccessException ex) {\n throw new ScriptCompilationException(scriptSource, \"Could not access Groovy script constructor: \" + scriptClass.getName(), ex);\n } catch (InvocationTargetException ex) {\n throw new ScriptCompilationException(\"Failed to invoke Groovy script constructor: \" + scriptClass.getName(), ex.getTargetException());\n }\n }\n\n @Override\n public String toString() {\n return \"GroovyScriptFactory: script source locator [\" + this.scriptSourceLocator + \"]\";\n }\n\n /**\n * Wrapper that holds a temporarily cached result object.\n */\n private static class CachedResultHolder {\n\n @Nullable\n public final Object object;\n\n public CachedResultHolder(@Nullable Object object) {\n this.object = object;\n }\n }\n}\n"} {"task_id": "Java_2523", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/spring-projects/spring-framework/spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java", "mask_start_position": 6387, "mask_end_position": 6709, "canonical_solution": "public GroovyClassLoader getGroovyClassLoader() {\n synchronized (this.scriptClassMonitor) {\n if (this.groovyClassLoader == null) {\n this.groovyClassLoader = buildGroovyClassLoader(ClassUtils.getDefaultClassLoader());\n }\n return this.groovyClassLoader;\n }\n }", "pre_mask_code": "package org.springframework.scripting.groovy;\n\nimport java.io.IOException;\nimport java.lang.reflect.InvocationTargetException;\nimport groovy.lang.GroovyClassLoader;\nimport groovy.lang.GroovyObject;\nimport groovy.lang.MetaClass;\nimport groovy.lang.Script;\nimport org.codehaus.groovy.control.CompilationFailedException;\nimport org.codehaus.groovy.control.CompilerConfiguration;\nimport org.codehaus.groovy.control.customizers.CompilationCustomizer;\nimport org.springframework.beans.factory.BeanClassLoaderAware;\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.beans.factory.BeanFactoryAware;\nimport org.springframework.beans.factory.config.ConfigurableListableBeanFactory;\nimport org.springframework.lang.Nullable;\nimport org.springframework.scripting.ScriptCompilationException;\nimport org.springframework.scripting.ScriptFactory;\nimport org.springframework.scripting.ScriptSource;\nimport org.springframework.util.Assert;\nimport org.springframework.util.ClassUtils;\nimport org.springframework.util.ObjectUtils;\nimport org.springframework.util.ReflectionUtils;\n\n/**\n * {@link org.springframework.scripting.ScriptFactory} implementation\n * for a Groovy script.\n *\n *

Typically used in combination with a\n * {@link org.springframework.scripting.support.ScriptFactoryPostProcessor};\n * see the latter's javadoc for a configuration example.\n *\n *

Note: Spring 4.0 supports Groovy 1.8 and higher.\n *\n * @author Juergen Hoeller\n * @author Rob Harrop\n * @author Rod Johnson\n * @since 2.0\n * @see groovy.lang.GroovyClassLoader\n * @see org.springframework.scripting.support.ScriptFactoryPostProcessor\n */\npublic class GroovyScriptFactory implements ScriptFactory, BeanFactoryAware, BeanClassLoaderAware {\n\n private final String scriptSourceLocator;\n\n @Nullable\n private GroovyObjectCustomizer groovyObjectCustomizer;\n\n @Nullable\n private CompilerConfiguration compilerConfiguration;\n\n @Nullable\n private GroovyClassLoader groovyClassLoader;\n\n @Nullable\n private Class scriptClass;\n\n @Nullable\n private Class scriptResultClass;\n\n @Nullable\n private CachedResultHolder cachedResult;\n\n private final Object scriptClassMonitor = new Object();\n\n private boolean wasModifiedForTypeCheck = false;\n\n /**\n * Create a new GroovyScriptFactory for the given script source.\n *

We don't need to specify script interfaces here, since\n * a Groovy script defines its Java interfaces itself.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n */\n public GroovyScriptFactory(String scriptSourceLocator) {\n Assert.hasText(scriptSourceLocator, \"'scriptSourceLocator' must not be empty\");\n this.scriptSourceLocator = scriptSourceLocator;\n }\n\n /**\n * Create a new GroovyScriptFactory for the given script source,\n * specifying a strategy interface that can create a custom MetaClass\n * to supply missing methods and otherwise change the behavior of the object.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n * @param groovyObjectCustomizer a customizer that can set a custom metaclass\n * or make other changes to the GroovyObject created by this factory\n * (may be {@code null})\n * @see GroovyObjectCustomizer#customize\n */\n public GroovyScriptFactory(String scriptSourceLocator, @Nullable GroovyObjectCustomizer groovyObjectCustomizer) {\n this(scriptSourceLocator);\n this.groovyObjectCustomizer = groovyObjectCustomizer;\n }\n\n /**\n * Create a new GroovyScriptFactory for the given script source,\n * specifying a strategy interface that can create a custom MetaClass\n * to supply missing methods and otherwise change the behavior of the object.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n * @param compilerConfiguration a custom compiler configuration to be applied\n * to the GroovyClassLoader (may be {@code null})\n * @since 4.3.3\n * @see GroovyClassLoader#GroovyClassLoader(ClassLoader, CompilerConfiguration)\n */\n public GroovyScriptFactory(String scriptSourceLocator, @Nullable CompilerConfiguration compilerConfiguration) {\n this(scriptSourceLocator);\n this.compilerConfiguration = compilerConfiguration;\n }\n\n /**\n * Create a new GroovyScriptFactory for the given script source,\n * specifying a strategy interface that can customize Groovy's compilation\n * process within the underlying GroovyClassLoader.\n * @param scriptSourceLocator a locator that points to the source of the script.\n * Interpreted by the post-processor that actually creates the script.\n * @param compilationCustomizers one or more customizers to be applied to the\n * GroovyClassLoader compiler configuration\n * @since 4.3.3\n * @see CompilerConfiguration#addCompilationCustomizers\n * @see org.codehaus.groovy.control.customizers.ImportCustomizer\n */\n public GroovyScriptFactory(String scriptSourceLocator, CompilationCustomizer... compilationCustomizers) {\n this(scriptSourceLocator);\n if (!ObjectUtils.isEmpty(compilationCustomizers)) {\n this.compilerConfiguration = new CompilerConfiguration();\n this.compilerConfiguration.addCompilationCustomizers(compilationCustomizers);\n }\n }\n\n @Override\n public void setBeanFactory(BeanFactory beanFactory) {\n if (beanFactory instanceof ConfigurableListableBeanFactory) {\n ((ConfigurableListableBeanFactory) beanFactory).ignoreDependencyType(MetaClass.class);\n }\n }\n\n @Override\n public void setBeanClassLoader(ClassLoader classLoader) {\n if (classLoader instanceof GroovyClassLoader && (this.compilerConfiguration == null || ((GroovyClassLoader) classLoader).hasCompatibleConfiguration(this.compilerConfiguration))) {\n this.groovyClassLoader = (GroovyClassLoader) classLoader;\n } else {\n this.groovyClassLoader = buildGroovyClassLoader(classLoader);\n }\n }\n\n /**\n * Return the GroovyClassLoader used by this script factory.\n */\n ", "post_mask_code": "\n\n /**\n * Build a {@link GroovyClassLoader} for the given {@code ClassLoader}.\n * @param classLoader the ClassLoader to build a GroovyClassLoader for\n * @since 4.3.3\n */\n protected GroovyClassLoader buildGroovyClassLoader(@Nullable ClassLoader classLoader) {\n return (this.compilerConfiguration != null ? new GroovyClassLoader(classLoader, this.compilerConfiguration) : new GroovyClassLoader(classLoader));\n }\n\n @Override\n public String getScriptSourceLocator() {\n return this.scriptSourceLocator;\n }\n\n /**\n * Groovy scripts determine their interfaces themselves,\n * hence we don't need to explicitly expose interfaces here.\n * @return {@code null} always\n */\n @Override\n @Nullable\n public Class[] getScriptInterfaces() {\n return null;\n }\n\n /**\n * Groovy scripts do not need a config interface,\n * since they expose their setters as public methods.\n */\n @Override\n public boolean requiresConfigInterface() {\n return false;\n }\n\n /**\n * Loads and parses the Groovy script via the GroovyClassLoader.\n * @see groovy.lang.GroovyClassLoader\n */\n @Override\n @Nullable\n public Object getScriptedObject(ScriptSource scriptSource, @Nullable Class... actualInterfaces) throws IOException, ScriptCompilationException {\n synchronized (this.scriptClassMonitor) {\n try {\n Class scriptClassToExecute;\n this.wasModifiedForTypeCheck = false;\n if (this.cachedResult != null) {\n Object result = this.cachedResult.object;\n this.cachedResult = null;\n return result;\n }\n if (this.scriptClass == null || scriptSource.isModified()) {\n // New script content...\n this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());\n if (Script.class.isAssignableFrom(this.scriptClass)) {\n // A Groovy script, probably creating an instance: let's execute it.\n Object result = executeScript(scriptSource, this.scriptClass);\n this.scriptResultClass = (result != null ? result.getClass() : null);\n return result;\n } else {\n this.scriptResultClass = this.scriptClass;\n }\n }\n scriptClassToExecute = this.scriptClass;\n // Process re-execution outside of the synchronized block.\n return executeScript(scriptSource, scriptClassToExecute);\n } catch (CompilationFailedException ex) {\n this.scriptClass = null;\n this.scriptResultClass = null;\n throw new ScriptCompilationException(scriptSource, ex);\n }\n }\n }\n\n @Override\n @Nullable\n public Class getScriptedObjectType(ScriptSource scriptSource) throws IOException, ScriptCompilationException {\n synchronized (this.scriptClassMonitor) {\n try {\n if (this.scriptClass == null || scriptSource.isModified()) {\n // New script content...\n this.wasModifiedForTypeCheck = true;\n this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());\n if (Script.class.isAssignableFrom(this.scriptClass)) {\n // A Groovy script, probably creating an instance: let's execute it.\n Object result = executeScript(scriptSource, this.scriptClass);\n this.scriptResultClass = (result != null ? result.getClass() : null);\n this.cachedResult = new CachedResultHolder(result);\n } else {\n this.scriptResultClass = this.scriptClass;\n }\n }\n return this.scriptResultClass;\n } catch (CompilationFailedException ex) {\n this.scriptClass = null;\n this.scriptResultClass = null;\n this.cachedResult = null;\n throw new ScriptCompilationException(scriptSource, ex);\n }\n }\n }\n\n @Override\n public boolean requiresScriptedObjectRefresh(ScriptSource scriptSource) {\n synchronized (this.scriptClassMonitor) {\n return (scriptSource.isModified() || this.wasModifiedForTypeCheck);\n }\n }\n\n /**\n * Instantiate the given Groovy script class and run it if necessary.\n * @param scriptSource the source for the underlying script\n * @param scriptClass the Groovy script class\n * @return the result object (either an instance of the script class\n * or the result of running the script instance)\n * @throws ScriptCompilationException in case of instantiation failure\n */\n @Nullable\n protected Object executeScript(ScriptSource scriptSource, Class scriptClass) throws ScriptCompilationException {\n try {\n GroovyObject goo = (GroovyObject) ReflectionUtils.accessibleConstructor(scriptClass).newInstance();\n if (this.groovyObjectCustomizer != null) {\n // Allow metaclass and other customization.\n this.groovyObjectCustomizer.customize(goo);\n }\n if (goo instanceof Script) {\n // A Groovy script, probably creating an instance: let's execute it.\n return ((Script) goo).run();\n } else {\n // An instance of the scripted class: let's return it as-is.\n return goo;\n }\n } catch (NoSuchMethodException ex) {\n throw new ScriptCompilationException(\"No default constructor on Groovy script class: \" + scriptClass.getName(), ex);\n } catch (InstantiationException ex) {\n throw new ScriptCompilationException(scriptSource, \"Unable to instantiate Groovy script class: \" + scriptClass.getName(), ex);\n } catch (IllegalAccessException ex) {\n throw new ScriptCompilationException(scriptSource, \"Could not access Groovy script constructor: \" + scriptClass.getName(), ex);\n } catch (InvocationTargetException ex) {\n throw new ScriptCompilationException(\"Failed to invoke Groovy script constructor: \" + scriptClass.getName(), ex.getTargetException());\n }\n }\n\n @Override\n public String toString() {\n return \"GroovyScriptFactory: script source locator [\" + this.scriptSourceLocator + \"]\";\n }\n\n /**\n * Wrapper that holds a temporarily cached result object.\n */\n private static class CachedResultHolder {\n\n @Nullable\n public final Object object;\n\n public CachedResultHolder(@Nullable Object object) {\n this.object = object;\n }\n }\n}\n"} {"task_id": "Java_2524", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cincheo/jsweet/transpiler/src/main/java/org/jsweet/transpiler/model/support/ImportElementSupport.java", "mask_start_position": 574, "mask_end_position": 614, "canonical_solution": "@Override\n public boolean isStatic() ", "pre_mask_code": "package org.jsweet.transpiler.model.support;\n\nimport javax.lang.model.element.Element;\nimport javax.lang.model.element.TypeElement;\nimport org.jsweet.transpiler.model.ImportElement;\nimport org.jsweet.transpiler.util.Util;\nimport com.sun.source.tree.ImportTree;\nimport com.sun.source.tree.Tree;\n\n/**\n * See {@link ImportElement}.\n *\n * @author Renaud Pawlak\n * @author Louis Grignon\n */\npublic class ImportElementSupport extends ExtendedElementSupport implements ImportElement {\n\n public ImportElementSupport(ImportTree tree) {\n super(tree);\n }\n\n ", "post_mask_code": "{\n return getTree().isStatic();\n }\n\n @Override\n public TypeElement getImportedType() {\n Tree importedIdentifier = getTree().getQualifiedIdentifier();\n Element importedElement = Util.getElement(importedIdentifier);\n if (getTree().isStatic() || importedElement == null || importedElement.asType() == null) {\n return null;\n }\n return (TypeElement) importedElement;\n }\n\n @Override\n public boolean isWildcard() {\n return getTree().toString().endsWith(\"*\");\n }\n}\n"} {"task_id": "Java_2525", "language": "Java", "task_type": "method_body", "source_file": "java/github/cincheo/jsweet/transpiler/src/main/java/org/jsweet/transpiler/model/support/ImportElementSupport.java", "mask_start_position": 614, "mask_end_position": 658, "canonical_solution": "{\n return getTree().isStatic();\n }", "pre_mask_code": "package org.jsweet.transpiler.model.support;\n\nimport javax.lang.model.element.Element;\nimport javax.lang.model.element.TypeElement;\nimport org.jsweet.transpiler.model.ImportElement;\nimport org.jsweet.transpiler.util.Util;\nimport com.sun.source.tree.ImportTree;\nimport com.sun.source.tree.Tree;\n\n/**\n * See {@link ImportElement}.\n *\n * @author Renaud Pawlak\n * @author Louis Grignon\n */\npublic class ImportElementSupport extends ExtendedElementSupport implements ImportElement {\n\n public ImportElementSupport(ImportTree tree) {\n super(tree);\n }\n\n @Override\n public boolean isStatic() ", "post_mask_code": "\n\n @Override\n public TypeElement getImportedType() {\n Tree importedIdentifier = getTree().getQualifiedIdentifier();\n Element importedElement = Util.getElement(importedIdentifier);\n if (getTree().isStatic() || importedElement == null || importedElement.asType() == null) {\n return null;\n }\n return (TypeElement) importedElement;\n }\n\n @Override\n public boolean isWildcard() {\n return getTree().toString().endsWith(\"*\");\n }\n}\n"} {"task_id": "Java_2526", "language": "Java", "task_type": "single_line", "source_file": "java/github/cincheo/jsweet/transpiler/src/main/java/org/jsweet/transpiler/model/support/ImportElementSupport.java", "mask_start_position": 1030, "mask_end_position": 1037, "canonical_solution": "lement;", "pre_mask_code": "package org.jsweet.transpiler.model.support;\n\nimport javax.lang.model.element.Element;\nimport javax.lang.model.element.TypeElement;\nimport org.jsweet.transpiler.model.ImportElement;\nimport org.jsweet.transpiler.util.Util;\nimport com.sun.source.tree.ImportTree;\nimport com.sun.source.tree.Tree;\n\n/**\n * See {@link ImportElement}.\n *\n * @author Renaud Pawlak\n * @author Louis Grignon\n */\npublic class ImportElementSupport extends ExtendedElementSupport implements ImportElement {\n\n public ImportElementSupport(ImportTree tree) {\n super(tree);\n }\n\n @Override\n public boolean isStatic() {\n return getTree().isStatic();\n }\n\n @Override\n public TypeElement getImportedType() {\n Tree importedIdentifier = getTree().getQualifiedIdentifier();\n Element importedElement = Util.getElement(importedIdentifier);\n if (getTree().isStatic() || importedElement == null || importedElement.asType() == null) {\n return null;\n }\n return (TypeElement) importedE", "post_mask_code": "\n }\n\n @Override\n public boolean isWildcard() {\n return getTree().toString().endsWith(\"*\");\n }\n}\n"} {"task_id": "Java_2527", "language": "Java", "task_type": "method_signature", "source_file": "java/github/java-native-access/jna/src/com/sun/jna/Library.java", "mask_start_position": 8021, "mask_end_position": 8061, "canonical_solution": "public NativeLibrary getNativeLibrary() ", "pre_mask_code": "package com.sun.jna;\n\nimport com.sun.jna.internal.ReflectionUtils;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\n/**\n * Derive from this interface for all native library definitions.\n *\n * Define an instance of your library like this:\n *

\n * MyNativeLibrary INSTANCE = (MyNativeLibrary)\n *     Native.load(\"mylib\", MyNativeLibrary.class);\n * 
\n *

\n * By convention, method names are identical to the native names, although you\n * can map java names to different native names by providing a\n * {@link FunctionMapper} as a value for key {@link #OPTION_FUNCTION_MAPPER}\n * in the options map passed to the\n * {@link Native#load(String, Class, Map)} call.\n *

\n * Although the names for structures and structure fields may be chosen\n * arbitrarily, they should correspond as closely as possible to the native\n * definitions. The same is true for parameter names.\n *

\n * This interface supports multiple, concurrent invocations of any library\n * methods on the Java side. Check your library documentation for its\n * multi-threading requirements on the native side. If a library is not safe\n * for simultaneous multi-threaded access, consider using\n * {@link Native#synchronizedLibrary} to prevent simultaneous multi-threaded\n * access to the native code.\n *

\n * Optional fields
\n * Interface options will be automatically propagated to structures defined\n * within the library provided a call to\n * {@link Native#load(String,Class,Map)} is made prior to instantiating\n * any of those structures. One common way of ensuring this is to declare\n * an INSTANCE field in the interface which holds the\n * load result.\n *

\n * OPTIONS (an instance of {@link Map}),\n * TYPE_MAPPER (an instance of {@link TypeMapper}),\n * STRUCTURE_ALIGNMENT (one of the alignment types defined in\n * {@link Structure}), and STRING_ENCODING (a {@link String}) may also\n * be defined. If no instance of the interface has been instantiated, these\n * fields will be used to determine customization settings for structures and\n * methods defined within the interface.\n *

\n *\n * @author Todd Fast, example@nnthink.com\n * @author Timothy Wall, example@nnthink.com\n */\npublic interface Library {\n\n /**\n * Option key for a {@link TypeMapper} for the library.\n */\n String OPTION_TYPE_MAPPER = \"type-mapper\";\n\n /**\n * Option key for a {@link FunctionMapper} for the library.\n */\n String OPTION_FUNCTION_MAPPER = \"function-mapper\";\n\n /**\n * Option key for an {@link InvocationMapper} for the library.\n */\n String OPTION_INVOCATION_MAPPER = \"invocation-mapper\";\n\n /**\n * Option key for structure alignment type ({@link Integer}), which should\n * be one of the predefined alignment types in {@link Structure}.\n */\n String OPTION_STRUCTURE_ALIGNMENT = \"structure-alignment\";\n\n /**\n *

Option key for per-library String encoding. This affects conversions\n * between Java unicode and native (const char*) strings (as\n * arguments or Structure fields).\n *

\n * Defaults to {@link Native#getDefaultStringEncoding()}.\n */\n String OPTION_STRING_ENCODING = \"string-encoding\";\n\n /**\n * Option key for a boolean flag to allow any Java class instance as a\n * parameter. If no type mapper is found, the object is passed as a\n * pointer.\n * NOTE: This is for use with raw JNI interactions via the\n * JNIEnv data structure.\n */\n String OPTION_ALLOW_OBJECTS = \"allow-objects\";\n\n /**\n * Calling convention for the entire library.\n */\n String OPTION_CALLING_CONVENTION = \"calling-convention\";\n\n /**\n * Flags to use when opening the native library (see {@link Native#open(String,int)})\n */\n String OPTION_OPEN_FLAGS = \"open-flags\";\n\n /**\n *

Class loader to use when searching for native libraries on the\n * resource path (classpath). If not provided the current thread's\n * context class loader is used.

\n * If extracted from the resource path (i.e. bundled in a jar file), the\n * loaded library's lifespan will mirror that of the class loader, which\n * means you can use the same library in isolated contexts without\n * conflict.\n */\n String OPTION_CLASSLOADER = \"classloader\";\n\n static class Handler implements InvocationHandler {\n\n static final Method OBJECT_TOSTRING;\n\n static final Method OBJECT_HASHCODE;\n\n static final Method OBJECT_EQUALS;\n\n static {\n try {\n OBJECT_TOSTRING = Object.class.getMethod(\"toString\");\n OBJECT_HASHCODE = Object.class.getMethod(\"hashCode\");\n OBJECT_EQUALS = Object.class.getMethod(\"equals\", Object.class);\n } catch (Exception e) {\n throw new Error(\"Error retrieving Object.toString() method\");\n }\n }\n\n /**\n * FunctionInfo has to be immutable to to make the object visible\n * to other threads fully initialized. This is a prerequisite for\n * using the class in the double checked locking scenario of {@link Handler#invoke(Object, Method, Object[])}\n */\n private static final class FunctionInfo {\n\n final InvocationHandler handler;\n\n final Function function;\n\n final boolean isVarArgs;\n\n final Object methodHandle;\n\n final Map options;\n\n final Class[] parameterTypes;\n\n FunctionInfo(Object mh) {\n this.handler = null;\n this.function = null;\n this.isVarArgs = false;\n this.options = null;\n this.parameterTypes = null;\n this.methodHandle = mh;\n }\n\n FunctionInfo(InvocationHandler handler, Function function, Class[] parameterTypes, boolean isVarArgs, Map options) {\n this.handler = handler;\n this.function = function;\n this.isVarArgs = isVarArgs;\n this.options = options;\n this.parameterTypes = parameterTypes;\n this.methodHandle = null;\n }\n }\n\n private final NativeLibrary nativeLibrary;\n\n private final Class interfaceClass;\n\n // Library invocation options\n private final Map options;\n\n private final InvocationMapper invocationMapper;\n\n private final Map functions = new WeakHashMap();\n\n public Handler(String libname, Class interfaceClass, Map options) {\n if (libname != null && \"\".equals(libname.trim())) {\n throw new IllegalArgumentException(\"Invalid library name \\\"\" + libname + \"\\\"\");\n }\n if (!interfaceClass.isInterface()) {\n throw new IllegalArgumentException(libname + \" does not implement an interface: \" + interfaceClass.getName());\n }\n this.interfaceClass = interfaceClass;\n this.options = new HashMap(options);\n int callingConvention = AltCallingConvention.class.isAssignableFrom(interfaceClass) ? Function.ALT_CONVENTION : Function.C_CONVENTION;\n if (this.options.get(OPTION_CALLING_CONVENTION) == null) {\n this.options.put(OPTION_CALLING_CONVENTION, Integer.valueOf(callingConvention));\n }\n if (this.options.get(OPTION_CLASSLOADER) == null) {\n this.options.put(OPTION_CLASSLOADER, interfaceClass.getClassLoader());\n }\n this.nativeLibrary = NativeLibrary.getInstance(libname, this.options);\n invocationMapper = (InvocationMapper) this.options.get(OPTION_INVOCATION_MAPPER);\n }\n\n ", "post_mask_code": "{\n return nativeLibrary;\n }\n\n public String getLibraryName() {\n return nativeLibrary.getName();\n }\n\n public Class getInterfaceClass() {\n return interfaceClass;\n }\n\n @Override\n public Object invoke(Object proxy, Method method, Object[] inArgs) throws Throwable {\n // Intercept Object methods\n if (OBJECT_TOSTRING.equals(method)) {\n return \"Proxy interface to \" + nativeLibrary;\n } else if (OBJECT_HASHCODE.equals(method)) {\n return Integer.valueOf(hashCode());\n } else if (OBJECT_EQUALS.equals(method)) {\n Object o = inArgs[0];\n if (o != null && Proxy.isProxyClass(o.getClass())) {\n return Function.valueOf(Proxy.getInvocationHandler(o) == this);\n }\n return Boolean.FALSE;\n }\n // Using the double-checked locking pattern to speed up function calls\n FunctionInfo f = functions.get(method);\n if (f == null) {\n synchronized (functions) {\n f = functions.get(method);\n if (f == null) {\n boolean isDefault = ReflectionUtils.isDefault(method);\n if (!isDefault) {\n boolean isVarArgs = Function.isVarArgs(method);\n InvocationHandler handler = null;\n if (invocationMapper != null) {\n handler = invocationMapper.getInvocationHandler(nativeLibrary, method);\n }\n Function function = null;\n Class[] parameterTypes = null;\n Map options = null;\n if (handler == null) {\n // Find the function to invoke\n function = nativeLibrary.getFunction(method.getName(), method);\n parameterTypes = method.getParameterTypes();\n options = new HashMap(this.options);\n options.put(Function.OPTION_INVOKING_METHOD, method);\n }\n f = new FunctionInfo(handler, function, parameterTypes, isVarArgs, options);\n } else {\n f = new FunctionInfo(ReflectionUtils.getMethodHandle(method));\n }\n functions.put(method, f);\n }\n }\n }\n if (f.methodHandle != null) {\n return ReflectionUtils.invokeDefaultMethod(proxy, f.methodHandle, inArgs);\n } else {\n if (f.isVarArgs) {\n inArgs = Function.concatenateVarArgs(inArgs);\n }\n if (f.handler != null) {\n return f.handler.invoke(proxy, method, inArgs);\n }\n return f.function.invoke(method, f.parameterTypes, method.getReturnType(), inArgs, f.options);\n }\n }\n }\n}\n"} {"task_id": "Java_2528", "language": "Java", "task_type": "method_body", "source_file": "java/github/java-native-access/jna/src/com/sun/jna/Library.java", "mask_start_position": 8147, "mask_end_position": 8202, "canonical_solution": "{\n return nativeLibrary.getName();\n }", "pre_mask_code": "package com.sun.jna;\n\nimport com.sun.jna.internal.ReflectionUtils;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\n/**\n * Derive from this interface for all native library definitions.\n *\n * Define an instance of your library like this:\n *
\n * MyNativeLibrary INSTANCE = (MyNativeLibrary)\n *     Native.load(\"mylib\", MyNativeLibrary.class);\n * 
\n *

\n * By convention, method names are identical to the native names, although you\n * can map java names to different native names by providing a\n * {@link FunctionMapper} as a value for key {@link #OPTION_FUNCTION_MAPPER}\n * in the options map passed to the\n * {@link Native#load(String, Class, Map)} call.\n *

\n * Although the names for structures and structure fields may be chosen\n * arbitrarily, they should correspond as closely as possible to the native\n * definitions. The same is true for parameter names.\n *

\n * This interface supports multiple, concurrent invocations of any library\n * methods on the Java side. Check your library documentation for its\n * multi-threading requirements on the native side. If a library is not safe\n * for simultaneous multi-threaded access, consider using\n * {@link Native#synchronizedLibrary} to prevent simultaneous multi-threaded\n * access to the native code.\n *

\n * Optional fields
\n * Interface options will be automatically propagated to structures defined\n * within the library provided a call to\n * {@link Native#load(String,Class,Map)} is made prior to instantiating\n * any of those structures. One common way of ensuring this is to declare\n * an INSTANCE field in the interface which holds the\n * load result.\n *

\n * OPTIONS (an instance of {@link Map}),\n * TYPE_MAPPER (an instance of {@link TypeMapper}),\n * STRUCTURE_ALIGNMENT (one of the alignment types defined in\n * {@link Structure}), and STRING_ENCODING (a {@link String}) may also\n * be defined. If no instance of the interface has been instantiated, these\n * fields will be used to determine customization settings for structures and\n * methods defined within the interface.\n *

\n *\n * @author Todd Fast, example@nnthink.com\n * @author Timothy Wall, example@nnthink.com\n */\npublic interface Library {\n\n /**\n * Option key for a {@link TypeMapper} for the library.\n */\n String OPTION_TYPE_MAPPER = \"type-mapper\";\n\n /**\n * Option key for a {@link FunctionMapper} for the library.\n */\n String OPTION_FUNCTION_MAPPER = \"function-mapper\";\n\n /**\n * Option key for an {@link InvocationMapper} for the library.\n */\n String OPTION_INVOCATION_MAPPER = \"invocation-mapper\";\n\n /**\n * Option key for structure alignment type ({@link Integer}), which should\n * be one of the predefined alignment types in {@link Structure}.\n */\n String OPTION_STRUCTURE_ALIGNMENT = \"structure-alignment\";\n\n /**\n *

Option key for per-library String encoding. This affects conversions\n * between Java unicode and native (const char*) strings (as\n * arguments or Structure fields).\n *

\n * Defaults to {@link Native#getDefaultStringEncoding()}.\n */\n String OPTION_STRING_ENCODING = \"string-encoding\";\n\n /**\n * Option key for a boolean flag to allow any Java class instance as a\n * parameter. If no type mapper is found, the object is passed as a\n * pointer.\n * NOTE: This is for use with raw JNI interactions via the\n * JNIEnv data structure.\n */\n String OPTION_ALLOW_OBJECTS = \"allow-objects\";\n\n /**\n * Calling convention for the entire library.\n */\n String OPTION_CALLING_CONVENTION = \"calling-convention\";\n\n /**\n * Flags to use when opening the native library (see {@link Native#open(String,int)})\n */\n String OPTION_OPEN_FLAGS = \"open-flags\";\n\n /**\n *

Class loader to use when searching for native libraries on the\n * resource path (classpath). If not provided the current thread's\n * context class loader is used.

\n * If extracted from the resource path (i.e. bundled in a jar file), the\n * loaded library's lifespan will mirror that of the class loader, which\n * means you can use the same library in isolated contexts without\n * conflict.\n */\n String OPTION_CLASSLOADER = \"classloader\";\n\n static class Handler implements InvocationHandler {\n\n static final Method OBJECT_TOSTRING;\n\n static final Method OBJECT_HASHCODE;\n\n static final Method OBJECT_EQUALS;\n\n static {\n try {\n OBJECT_TOSTRING = Object.class.getMethod(\"toString\");\n OBJECT_HASHCODE = Object.class.getMethod(\"hashCode\");\n OBJECT_EQUALS = Object.class.getMethod(\"equals\", Object.class);\n } catch (Exception e) {\n throw new Error(\"Error retrieving Object.toString() method\");\n }\n }\n\n /**\n * FunctionInfo has to be immutable to to make the object visible\n * to other threads fully initialized. This is a prerequisite for\n * using the class in the double checked locking scenario of {@link Handler#invoke(Object, Method, Object[])}\n */\n private static final class FunctionInfo {\n\n final InvocationHandler handler;\n\n final Function function;\n\n final boolean isVarArgs;\n\n final Object methodHandle;\n\n final Map options;\n\n final Class[] parameterTypes;\n\n FunctionInfo(Object mh) {\n this.handler = null;\n this.function = null;\n this.isVarArgs = false;\n this.options = null;\n this.parameterTypes = null;\n this.methodHandle = mh;\n }\n\n FunctionInfo(InvocationHandler handler, Function function, Class[] parameterTypes, boolean isVarArgs, Map options) {\n this.handler = handler;\n this.function = function;\n this.isVarArgs = isVarArgs;\n this.options = options;\n this.parameterTypes = parameterTypes;\n this.methodHandle = null;\n }\n }\n\n private final NativeLibrary nativeLibrary;\n\n private final Class interfaceClass;\n\n // Library invocation options\n private final Map options;\n\n private final InvocationMapper invocationMapper;\n\n private final Map functions = new WeakHashMap();\n\n public Handler(String libname, Class interfaceClass, Map options) {\n if (libname != null && \"\".equals(libname.trim())) {\n throw new IllegalArgumentException(\"Invalid library name \\\"\" + libname + \"\\\"\");\n }\n if (!interfaceClass.isInterface()) {\n throw new IllegalArgumentException(libname + \" does not implement an interface: \" + interfaceClass.getName());\n }\n this.interfaceClass = interfaceClass;\n this.options = new HashMap(options);\n int callingConvention = AltCallingConvention.class.isAssignableFrom(interfaceClass) ? Function.ALT_CONVENTION : Function.C_CONVENTION;\n if (this.options.get(OPTION_CALLING_CONVENTION) == null) {\n this.options.put(OPTION_CALLING_CONVENTION, Integer.valueOf(callingConvention));\n }\n if (this.options.get(OPTION_CLASSLOADER) == null) {\n this.options.put(OPTION_CLASSLOADER, interfaceClass.getClassLoader());\n }\n this.nativeLibrary = NativeLibrary.getInstance(libname, this.options);\n invocationMapper = (InvocationMapper) this.options.get(OPTION_INVOCATION_MAPPER);\n }\n\n public NativeLibrary getNativeLibrary() {\n return nativeLibrary;\n }\n\n public String getLibraryName() ", "post_mask_code": "\n\n public Class getInterfaceClass() {\n return interfaceClass;\n }\n\n @Override\n public Object invoke(Object proxy, Method method, Object[] inArgs) throws Throwable {\n // Intercept Object methods\n if (OBJECT_TOSTRING.equals(method)) {\n return \"Proxy interface to \" + nativeLibrary;\n } else if (OBJECT_HASHCODE.equals(method)) {\n return Integer.valueOf(hashCode());\n } else if (OBJECT_EQUALS.equals(method)) {\n Object o = inArgs[0];\n if (o != null && Proxy.isProxyClass(o.getClass())) {\n return Function.valueOf(Proxy.getInvocationHandler(o) == this);\n }\n return Boolean.FALSE;\n }\n // Using the double-checked locking pattern to speed up function calls\n FunctionInfo f = functions.get(method);\n if (f == null) {\n synchronized (functions) {\n f = functions.get(method);\n if (f == null) {\n boolean isDefault = ReflectionUtils.isDefault(method);\n if (!isDefault) {\n boolean isVarArgs = Function.isVarArgs(method);\n InvocationHandler handler = null;\n if (invocationMapper != null) {\n handler = invocationMapper.getInvocationHandler(nativeLibrary, method);\n }\n Function function = null;\n Class[] parameterTypes = null;\n Map options = null;\n if (handler == null) {\n // Find the function to invoke\n function = nativeLibrary.getFunction(method.getName(), method);\n parameterTypes = method.getParameterTypes();\n options = new HashMap(this.options);\n options.put(Function.OPTION_INVOKING_METHOD, method);\n }\n f = new FunctionInfo(handler, function, parameterTypes, isVarArgs, options);\n } else {\n f = new FunctionInfo(ReflectionUtils.getMethodHandle(method));\n }\n functions.put(method, f);\n }\n }\n }\n if (f.methodHandle != null) {\n return ReflectionUtils.invokeDefaultMethod(proxy, f.methodHandle, inArgs);\n } else {\n if (f.isVarArgs) {\n inArgs = Function.concatenateVarArgs(inArgs);\n }\n if (f.handler != null) {\n return f.handler.invoke(proxy, method, inArgs);\n }\n return f.function.invoke(method, f.parameterTypes, method.getReturnType(), inArgs, f.options);\n }\n }\n }\n}\n"} {"task_id": "Java_2529", "language": "Java", "task_type": "single_line", "source_file": "java/github/java-native-access/jna/src/com/sun/jna/Library.java", "mask_start_position": 8176, "mask_end_position": 8192, "canonical_solution": "brary.getName();", "pre_mask_code": "package com.sun.jna;\n\nimport com.sun.jna.internal.ReflectionUtils;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\n/**\n * Derive from this interface for all native library definitions.\n *\n * Define an instance of your library like this:\n *
\n * MyNativeLibrary INSTANCE = (MyNativeLibrary)\n *     Native.load(\"mylib\", MyNativeLibrary.class);\n * 
\n *

\n * By convention, method names are identical to the native names, although you\n * can map java names to different native names by providing a\n * {@link FunctionMapper} as a value for key {@link #OPTION_FUNCTION_MAPPER}\n * in the options map passed to the\n * {@link Native#load(String, Class, Map)} call.\n *

\n * Although the names for structures and structure fields may be chosen\n * arbitrarily, they should correspond as closely as possible to the native\n * definitions. The same is true for parameter names.\n *

\n * This interface supports multiple, concurrent invocations of any library\n * methods on the Java side. Check your library documentation for its\n * multi-threading requirements on the native side. If a library is not safe\n * for simultaneous multi-threaded access, consider using\n * {@link Native#synchronizedLibrary} to prevent simultaneous multi-threaded\n * access to the native code.\n *

\n * Optional fields
\n * Interface options will be automatically propagated to structures defined\n * within the library provided a call to\n * {@link Native#load(String,Class,Map)} is made prior to instantiating\n * any of those structures. One common way of ensuring this is to declare\n * an INSTANCE field in the interface which holds the\n * load result.\n *

\n * OPTIONS (an instance of {@link Map}),\n * TYPE_MAPPER (an instance of {@link TypeMapper}),\n * STRUCTURE_ALIGNMENT (one of the alignment types defined in\n * {@link Structure}), and STRING_ENCODING (a {@link String}) may also\n * be defined. If no instance of the interface has been instantiated, these\n * fields will be used to determine customization settings for structures and\n * methods defined within the interface.\n *

\n *\n * @author Todd Fast, example@nnthink.com\n * @author Timothy Wall, example@nnthink.com\n */\npublic interface Library {\n\n /**\n * Option key for a {@link TypeMapper} for the library.\n */\n String OPTION_TYPE_MAPPER = \"type-mapper\";\n\n /**\n * Option key for a {@link FunctionMapper} for the library.\n */\n String OPTION_FUNCTION_MAPPER = \"function-mapper\";\n\n /**\n * Option key for an {@link InvocationMapper} for the library.\n */\n String OPTION_INVOCATION_MAPPER = \"invocation-mapper\";\n\n /**\n * Option key for structure alignment type ({@link Integer}), which should\n * be one of the predefined alignment types in {@link Structure}.\n */\n String OPTION_STRUCTURE_ALIGNMENT = \"structure-alignment\";\n\n /**\n *

Option key for per-library String encoding. This affects conversions\n * between Java unicode and native (const char*) strings (as\n * arguments or Structure fields).\n *

\n * Defaults to {@link Native#getDefaultStringEncoding()}.\n */\n String OPTION_STRING_ENCODING = \"string-encoding\";\n\n /**\n * Option key for a boolean flag to allow any Java class instance as a\n * parameter. If no type mapper is found, the object is passed as a\n * pointer.\n * NOTE: This is for use with raw JNI interactions via the\n * JNIEnv data structure.\n */\n String OPTION_ALLOW_OBJECTS = \"allow-objects\";\n\n /**\n * Calling convention for the entire library.\n */\n String OPTION_CALLING_CONVENTION = \"calling-convention\";\n\n /**\n * Flags to use when opening the native library (see {@link Native#open(String,int)})\n */\n String OPTION_OPEN_FLAGS = \"open-flags\";\n\n /**\n *

Class loader to use when searching for native libraries on the\n * resource path (classpath). If not provided the current thread's\n * context class loader is used.

\n * If extracted from the resource path (i.e. bundled in a jar file), the\n * loaded library's lifespan will mirror that of the class loader, which\n * means you can use the same library in isolated contexts without\n * conflict.\n */\n String OPTION_CLASSLOADER = \"classloader\";\n\n static class Handler implements InvocationHandler {\n\n static final Method OBJECT_TOSTRING;\n\n static final Method OBJECT_HASHCODE;\n\n static final Method OBJECT_EQUALS;\n\n static {\n try {\n OBJECT_TOSTRING = Object.class.getMethod(\"toString\");\n OBJECT_HASHCODE = Object.class.getMethod(\"hashCode\");\n OBJECT_EQUALS = Object.class.getMethod(\"equals\", Object.class);\n } catch (Exception e) {\n throw new Error(\"Error retrieving Object.toString() method\");\n }\n }\n\n /**\n * FunctionInfo has to be immutable to to make the object visible\n * to other threads fully initialized. This is a prerequisite for\n * using the class in the double checked locking scenario of {@link Handler#invoke(Object, Method, Object[])}\n */\n private static final class FunctionInfo {\n\n final InvocationHandler handler;\n\n final Function function;\n\n final boolean isVarArgs;\n\n final Object methodHandle;\n\n final Map options;\n\n final Class[] parameterTypes;\n\n FunctionInfo(Object mh) {\n this.handler = null;\n this.function = null;\n this.isVarArgs = false;\n this.options = null;\n this.parameterTypes = null;\n this.methodHandle = mh;\n }\n\n FunctionInfo(InvocationHandler handler, Function function, Class[] parameterTypes, boolean isVarArgs, Map options) {\n this.handler = handler;\n this.function = function;\n this.isVarArgs = isVarArgs;\n this.options = options;\n this.parameterTypes = parameterTypes;\n this.methodHandle = null;\n }\n }\n\n private final NativeLibrary nativeLibrary;\n\n private final Class interfaceClass;\n\n // Library invocation options\n private final Map options;\n\n private final InvocationMapper invocationMapper;\n\n private final Map functions = new WeakHashMap();\n\n public Handler(String libname, Class interfaceClass, Map options) {\n if (libname != null && \"\".equals(libname.trim())) {\n throw new IllegalArgumentException(\"Invalid library name \\\"\" + libname + \"\\\"\");\n }\n if (!interfaceClass.isInterface()) {\n throw new IllegalArgumentException(libname + \" does not implement an interface: \" + interfaceClass.getName());\n }\n this.interfaceClass = interfaceClass;\n this.options = new HashMap(options);\n int callingConvention = AltCallingConvention.class.isAssignableFrom(interfaceClass) ? Function.ALT_CONVENTION : Function.C_CONVENTION;\n if (this.options.get(OPTION_CALLING_CONVENTION) == null) {\n this.options.put(OPTION_CALLING_CONVENTION, Integer.valueOf(callingConvention));\n }\n if (this.options.get(OPTION_CLASSLOADER) == null) {\n this.options.put(OPTION_CLASSLOADER, interfaceClass.getClassLoader());\n }\n this.nativeLibrary = NativeLibrary.getInstance(libname, this.options);\n invocationMapper = (InvocationMapper) this.options.get(OPTION_INVOCATION_MAPPER);\n }\n\n public NativeLibrary getNativeLibrary() {\n return nativeLibrary;\n }\n\n public String getLibraryName() {\n return nativeLi", "post_mask_code": "\n }\n\n public Class getInterfaceClass() {\n return interfaceClass;\n }\n\n @Override\n public Object invoke(Object proxy, Method method, Object[] inArgs) throws Throwable {\n // Intercept Object methods\n if (OBJECT_TOSTRING.equals(method)) {\n return \"Proxy interface to \" + nativeLibrary;\n } else if (OBJECT_HASHCODE.equals(method)) {\n return Integer.valueOf(hashCode());\n } else if (OBJECT_EQUALS.equals(method)) {\n Object o = inArgs[0];\n if (o != null && Proxy.isProxyClass(o.getClass())) {\n return Function.valueOf(Proxy.getInvocationHandler(o) == this);\n }\n return Boolean.FALSE;\n }\n // Using the double-checked locking pattern to speed up function calls\n FunctionInfo f = functions.get(method);\n if (f == null) {\n synchronized (functions) {\n f = functions.get(method);\n if (f == null) {\n boolean isDefault = ReflectionUtils.isDefault(method);\n if (!isDefault) {\n boolean isVarArgs = Function.isVarArgs(method);\n InvocationHandler handler = null;\n if (invocationMapper != null) {\n handler = invocationMapper.getInvocationHandler(nativeLibrary, method);\n }\n Function function = null;\n Class[] parameterTypes = null;\n Map options = null;\n if (handler == null) {\n // Find the function to invoke\n function = nativeLibrary.getFunction(method.getName(), method);\n parameterTypes = method.getParameterTypes();\n options = new HashMap(this.options);\n options.put(Function.OPTION_INVOKING_METHOD, method);\n }\n f = new FunctionInfo(handler, function, parameterTypes, isVarArgs, options);\n } else {\n f = new FunctionInfo(ReflectionUtils.getMethodHandle(method));\n }\n functions.put(method, f);\n }\n }\n }\n if (f.methodHandle != null) {\n return ReflectionUtils.invokeDefaultMethod(proxy, f.methodHandle, inArgs);\n } else {\n if (f.isVarArgs) {\n inArgs = Function.concatenateVarArgs(inArgs);\n }\n if (f.handler != null) {\n return f.handler.invoke(proxy, method, inArgs);\n }\n return f.function.invoke(method, f.parameterTypes, method.getReturnType(), inArgs, f.options);\n }\n }\n }\n}\n"} {"task_id": "Java_2530", "language": "Java", "task_type": "try_statement", "source_file": "java/github/java-native-access/jna/src/com/sun/jna/Library.java", "mask_start_position": 4736, "mask_end_position": 5089, "canonical_solution": "try {\n OBJECT_TOSTRING = Object.class.getMethod(\"toString\");\n OBJECT_HASHCODE = Object.class.getMethod(\"hashCode\");\n OBJECT_EQUALS = Object.class.getMethod(\"equals\", Object.class);\n } catch (Exception e) {\n throw new Error(\"Error retrieving Object.toString() method\");\n }", "pre_mask_code": "package com.sun.jna;\n\nimport com.sun.jna.internal.ReflectionUtils;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\n/**\n * Derive from this interface for all native library definitions.\n *\n * Define an instance of your library like this:\n *
\n * MyNativeLibrary INSTANCE = (MyNativeLibrary)\n *     Native.load(\"mylib\", MyNativeLibrary.class);\n * 
\n *

\n * By convention, method names are identical to the native names, although you\n * can map java names to different native names by providing a\n * {@link FunctionMapper} as a value for key {@link #OPTION_FUNCTION_MAPPER}\n * in the options map passed to the\n * {@link Native#load(String, Class, Map)} call.\n *

\n * Although the names for structures and structure fields may be chosen\n * arbitrarily, they should correspond as closely as possible to the native\n * definitions. The same is true for parameter names.\n *

\n * This interface supports multiple, concurrent invocations of any library\n * methods on the Java side. Check your library documentation for its\n * multi-threading requirements on the native side. If a library is not safe\n * for simultaneous multi-threaded access, consider using\n * {@link Native#synchronizedLibrary} to prevent simultaneous multi-threaded\n * access to the native code.\n *

\n * Optional fields
\n * Interface options will be automatically propagated to structures defined\n * within the library provided a call to\n * {@link Native#load(String,Class,Map)} is made prior to instantiating\n * any of those structures. One common way of ensuring this is to declare\n * an INSTANCE field in the interface which holds the\n * load result.\n *

\n * OPTIONS (an instance of {@link Map}),\n * TYPE_MAPPER (an instance of {@link TypeMapper}),\n * STRUCTURE_ALIGNMENT (one of the alignment types defined in\n * {@link Structure}), and STRING_ENCODING (a {@link String}) may also\n * be defined. If no instance of the interface has been instantiated, these\n * fields will be used to determine customization settings for structures and\n * methods defined within the interface.\n *

\n *\n * @author Todd Fast, example@nnthink.com\n * @author Timothy Wall, example@nnthink.com\n */\npublic interface Library {\n\n /**\n * Option key for a {@link TypeMapper} for the library.\n */\n String OPTION_TYPE_MAPPER = \"type-mapper\";\n\n /**\n * Option key for a {@link FunctionMapper} for the library.\n */\n String OPTION_FUNCTION_MAPPER = \"function-mapper\";\n\n /**\n * Option key for an {@link InvocationMapper} for the library.\n */\n String OPTION_INVOCATION_MAPPER = \"invocation-mapper\";\n\n /**\n * Option key for structure alignment type ({@link Integer}), which should\n * be one of the predefined alignment types in {@link Structure}.\n */\n String OPTION_STRUCTURE_ALIGNMENT = \"structure-alignment\";\n\n /**\n *

Option key for per-library String encoding. This affects conversions\n * between Java unicode and native (const char*) strings (as\n * arguments or Structure fields).\n *

\n * Defaults to {@link Native#getDefaultStringEncoding()}.\n */\n String OPTION_STRING_ENCODING = \"string-encoding\";\n\n /**\n * Option key for a boolean flag to allow any Java class instance as a\n * parameter. If no type mapper is found, the object is passed as a\n * pointer.\n * NOTE: This is for use with raw JNI interactions via the\n * JNIEnv data structure.\n */\n String OPTION_ALLOW_OBJECTS = \"allow-objects\";\n\n /**\n * Calling convention for the entire library.\n */\n String OPTION_CALLING_CONVENTION = \"calling-convention\";\n\n /**\n * Flags to use when opening the native library (see {@link Native#open(String,int)})\n */\n String OPTION_OPEN_FLAGS = \"open-flags\";\n\n /**\n *

Class loader to use when searching for native libraries on the\n * resource path (classpath). If not provided the current thread's\n * context class loader is used.

\n * If extracted from the resource path (i.e. bundled in a jar file), the\n * loaded library's lifespan will mirror that of the class loader, which\n * means you can use the same library in isolated contexts without\n * conflict.\n */\n String OPTION_CLASSLOADER = \"classloader\";\n\n static class Handler implements InvocationHandler {\n\n static final Method OBJECT_TOSTRING;\n\n static final Method OBJECT_HASHCODE;\n\n static final Method OBJECT_EQUALS;\n\n static {\n ", "post_mask_code": "\n }\n\n /**\n * FunctionInfo has to be immutable to to make the object visible\n * to other threads fully initialized. This is a prerequisite for\n * using the class in the double checked locking scenario of {@link Handler#invoke(Object, Method, Object[])}\n */\n private static final class FunctionInfo {\n\n final InvocationHandler handler;\n\n final Function function;\n\n final boolean isVarArgs;\n\n final Object methodHandle;\n\n final Map options;\n\n final Class[] parameterTypes;\n\n FunctionInfo(Object mh) {\n this.handler = null;\n this.function = null;\n this.isVarArgs = false;\n this.options = null;\n this.parameterTypes = null;\n this.methodHandle = mh;\n }\n\n FunctionInfo(InvocationHandler handler, Function function, Class[] parameterTypes, boolean isVarArgs, Map options) {\n this.handler = handler;\n this.function = function;\n this.isVarArgs = isVarArgs;\n this.options = options;\n this.parameterTypes = parameterTypes;\n this.methodHandle = null;\n }\n }\n\n private final NativeLibrary nativeLibrary;\n\n private final Class interfaceClass;\n\n // Library invocation options\n private final Map options;\n\n private final InvocationMapper invocationMapper;\n\n private final Map functions = new WeakHashMap();\n\n public Handler(String libname, Class interfaceClass, Map options) {\n if (libname != null && \"\".equals(libname.trim())) {\n throw new IllegalArgumentException(\"Invalid library name \\\"\" + libname + \"\\\"\");\n }\n if (!interfaceClass.isInterface()) {\n throw new IllegalArgumentException(libname + \" does not implement an interface: \" + interfaceClass.getName());\n }\n this.interfaceClass = interfaceClass;\n this.options = new HashMap(options);\n int callingConvention = AltCallingConvention.class.isAssignableFrom(interfaceClass) ? Function.ALT_CONVENTION : Function.C_CONVENTION;\n if (this.options.get(OPTION_CALLING_CONVENTION) == null) {\n this.options.put(OPTION_CALLING_CONVENTION, Integer.valueOf(callingConvention));\n }\n if (this.options.get(OPTION_CLASSLOADER) == null) {\n this.options.put(OPTION_CLASSLOADER, interfaceClass.getClassLoader());\n }\n this.nativeLibrary = NativeLibrary.getInstance(libname, this.options);\n invocationMapper = (InvocationMapper) this.options.get(OPTION_INVOCATION_MAPPER);\n }\n\n public NativeLibrary getNativeLibrary() {\n return nativeLibrary;\n }\n\n public String getLibraryName() {\n return nativeLibrary.getName();\n }\n\n public Class getInterfaceClass() {\n return interfaceClass;\n }\n\n @Override\n public Object invoke(Object proxy, Method method, Object[] inArgs) throws Throwable {\n // Intercept Object methods\n if (OBJECT_TOSTRING.equals(method)) {\n return \"Proxy interface to \" + nativeLibrary;\n } else if (OBJECT_HASHCODE.equals(method)) {\n return Integer.valueOf(hashCode());\n } else if (OBJECT_EQUALS.equals(method)) {\n Object o = inArgs[0];\n if (o != null && Proxy.isProxyClass(o.getClass())) {\n return Function.valueOf(Proxy.getInvocationHandler(o) == this);\n }\n return Boolean.FALSE;\n }\n // Using the double-checked locking pattern to speed up function calls\n FunctionInfo f = functions.get(method);\n if (f == null) {\n synchronized (functions) {\n f = functions.get(method);\n if (f == null) {\n boolean isDefault = ReflectionUtils.isDefault(method);\n if (!isDefault) {\n boolean isVarArgs = Function.isVarArgs(method);\n InvocationHandler handler = null;\n if (invocationMapper != null) {\n handler = invocationMapper.getInvocationHandler(nativeLibrary, method);\n }\n Function function = null;\n Class[] parameterTypes = null;\n Map options = null;\n if (handler == null) {\n // Find the function to invoke\n function = nativeLibrary.getFunction(method.getName(), method);\n parameterTypes = method.getParameterTypes();\n options = new HashMap(this.options);\n options.put(Function.OPTION_INVOKING_METHOD, method);\n }\n f = new FunctionInfo(handler, function, parameterTypes, isVarArgs, options);\n } else {\n f = new FunctionInfo(ReflectionUtils.getMethodHandle(method));\n }\n functions.put(method, f);\n }\n }\n }\n if (f.methodHandle != null) {\n return ReflectionUtils.invokeDefaultMethod(proxy, f.methodHandle, inArgs);\n } else {\n if (f.isVarArgs) {\n inArgs = Function.concatenateVarArgs(inArgs);\n }\n if (f.handler != null) {\n return f.handler.invoke(proxy, method, inArgs);\n }\n return f.function.invoke(method, f.parameterTypes, method.getReturnType(), inArgs, f.options);\n }\n }\n }\n}\n"} {"task_id": "Java_2531", "language": "Java", "task_type": "method_signature", "source_file": "java/github/nayuki/Project-Euler-solutions/java/p057.java", "mask_start_position": 182, "mask_end_position": 221, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "/* \n * Solution to Project Euler problem 57\n * \n * http://example.com\n * http://example.com\n */\nimport java.math.BigInteger;\n\npublic final class p057 implements EulerSolution {\n\n ", "post_mask_code": "{\n System.out.println(new p057().run());\n }\n\n private static final int LIMIT = 1000;\n\n public String run() {\n BigInteger n = BigInteger.ZERO;\n BigInteger d = BigInteger.ONE;\n int count = 0;\n for (int i = 0; i < LIMIT; i++) {\n BigInteger temp = d.multiply(BigInteger.valueOf(2)).add(n);\n n = d;\n d = temp;\n // Now n/d is the i'th (0-based) continued fraction approximation of sqrt(2) - 1\n if (n.add(d).toString().length() > d.toString().length())\n count++;\n }\n return Integer.toString(count);\n }\n}\n"} {"task_id": "Java_2532", "language": "Java", "task_type": "method_body", "source_file": "java/github/nayuki/Project-Euler-solutions/java/p057.java", "mask_start_position": 221, "mask_end_position": 274, "canonical_solution": "{\n System.out.println(new p057().run());\n }", "pre_mask_code": "/* \n * Solution to Project Euler problem 57\n * \n * http://example.com\n * http://example.com\n */\nimport java.math.BigInteger;\n\npublic final class p057 implements EulerSolution {\n\n public static void main(String[] args) ", "post_mask_code": "\n\n private static final int LIMIT = 1000;\n\n public String run() {\n BigInteger n = BigInteger.ZERO;\n BigInteger d = BigInteger.ONE;\n int count = 0;\n for (int i = 0; i < LIMIT; i++) {\n BigInteger temp = d.multiply(BigInteger.valueOf(2)).add(n);\n n = d;\n d = temp;\n // Now n/d is the i'th (0-based) continued fraction approximation of sqrt(2) - 1\n if (n.add(d).toString().length() > d.toString().length())\n count++;\n }\n return Integer.toString(count);\n }\n}\n"} {"task_id": "Java_2533", "language": "Java", "task_type": "single_line", "source_file": "java/github/nayuki/Project-Euler-solutions/java/p057.java", "mask_start_position": 407, "mask_end_position": 424, "canonical_solution": "= BigInteger.ONE;", "pre_mask_code": "/* \n * Solution to Project Euler problem 57\n * \n * http://example.com\n * http://example.com\n */\nimport java.math.BigInteger;\n\npublic final class p057 implements EulerSolution {\n\n public static void main(String[] args) {\n System.out.println(new p057().run());\n }\n\n private static final int LIMIT = 1000;\n\n public String run() {\n BigInteger n = BigInteger.ZERO;\n BigInteger d ", "post_mask_code": "\n int count = 0;\n for (int i = 0; i < LIMIT; i++) {\n BigInteger temp = d.multiply(BigInteger.valueOf(2)).add(n);\n n = d;\n d = temp;\n // Now n/d is the i'th (0-based) continued fraction approximation of sqrt(2) - 1\n if (n.add(d).toString().length() > d.toString().length())\n count++;\n }\n return Integer.toString(count);\n }\n}\n"} {"task_id": "Java_2534", "language": "Java", "task_type": "for_statement", "source_file": "java/github/nayuki/Project-Euler-solutions/java/p057.java", "mask_start_position": 456, "mask_end_position": 800, "canonical_solution": "for (int i = 0; i < LIMIT; i++) {\n BigInteger temp = d.multiply(BigInteger.valueOf(2)).add(n);\n n = d;\n d = temp;\n // Now n/d is the i'th (0-based) continued fraction approximation of sqrt(2) - 1\n if (n.add(d).toString().length() > d.toString().length())\n count++;\n }", "pre_mask_code": "/* \n * Solution to Project Euler problem 57\n * \n * http://example.com\n * http://example.com\n */\nimport java.math.BigInteger;\n\npublic final class p057 implements EulerSolution {\n\n public static void main(String[] args) {\n System.out.println(new p057().run());\n }\n\n private static final int LIMIT = 1000;\n\n public String run() {\n BigInteger n = BigInteger.ZERO;\n BigInteger d = BigInteger.ONE;\n int count = 0;\n ", "post_mask_code": "\n return Integer.toString(count);\n }\n}\n"} {"task_id": "Java_2535", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_10_1_0/src/main/java/com/android/server/wifi/grs/requestremote/RequestController.java", "mask_start_position": 3039, "mask_end_position": 3057, "canonical_solution": "public void run() ", "pre_mask_code": "package com.android.server.wifi.grs.requestremote;\n\nimport android.provider.Settings;\nimport android.util.Log;\nimport com.android.server.wifi.grs.GrsCallBack;\nimport com.android.server.wifi.grs.utils.ContextUtil;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.CancellationException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\n\npublic class RequestController {\n\n private static final String CAPTIVE_PORTAL_REQUEST_TIME = \"captive_portal_request_time\";\n\n private static final int DEFAULT_TIME = 0;\n\n private static final int SILENT_PERIOD = 300000;\n\n private static final String TAG = \"RequestController\";\n\n private static volatile RequestController sInstance;\n\n private final Object mLock = new Object();\n\n /* access modifiers changed from: private */\n public ExecutorService taskExecutor = Executors.newCachedThreadPool();\n\n public static synchronized RequestController getInstance() {\n RequestController requestController;\n synchronized (RequestController.class) {\n if (sInstance == null) {\n sInstance = new RequestController();\n }\n requestController = sInstance;\n }\n return requestController;\n }\n\n /* access modifiers changed from: private */\n public GrsResponse getSyncServicesUrls() {\n synchronized (this.mLock) {\n if (System.currentTimeMillis() - Long.valueOf(Settings.Global.getLong(ContextUtil.getContext().getContentResolver(), CAPTIVE_PORTAL_REQUEST_TIME, 0)).longValue() < 300000) {\n Log.d(TAG, \"cancel this request because the last request is initiated less than 5 mins ago\");\n return null;\n }\n Settings.Global.putLong(ContextUtil.getContext().getContentResolver(), CAPTIVE_PORTAL_REQUEST_TIME, System.currentTimeMillis());\n Future future = this.taskExecutor.submit(new Callable() {\n\n // java.util.concurrent.Callable\n @Override\n public GrsResponse call() {\n return new GrsRequest().submitExcutorTaskWithTimeout(RequestController.this.taskExecutor);\n }\n });\n try {\n return future.get();\n } catch (CancellationException e) {\n Log.d(TAG, \"when check result, find CancellationException, check others\");\n return null;\n } catch (ExecutionException e2) {\n Log.d(TAG, \"when check result, find ExecutionException, check others\");\n return null;\n } catch (InterruptedException e3) {\n Log.d(TAG, \"when check result, find InterruptedException, check others\");\n return null;\n }\n }\n }\n\n public void getAsyncServicesUrls(final GrsCallBack grsCallBack) {\n this.taskExecutor.submit(new Runnable() {\n\n ", "post_mask_code": "{\n RequestController requestController = RequestController.this;\n requestController.doCallBack(requestController.getSyncServicesUrls(), grsCallBack);\n }\n });\n }\n\n /* access modifiers changed from: private */\n public void doCallBack(GrsResponse grsResponse, GrsCallBack grsCallBack) {\n if (grsCallBack == null) {\n return;\n }\n if (grsResponse == null) {\n Log.d(TAG, \"GrsResponse is null\");\n grsCallBack.onFailure();\n return;\n }\n Log.d(TAG, \"GrsResponse is not null\");\n grsCallBack.onResponse(grsResponse);\n }\n}\n"} {"task_id": "Java_2536", "language": "Java", "task_type": "method_body", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_10_1_0/src/main/java/com/android/server/wifi/grs/requestremote/RequestController.java", "mask_start_position": 3057, "mask_end_position": 3250, "canonical_solution": "{\n RequestController requestController = RequestController.this;\n requestController.doCallBack(requestController.getSyncServicesUrls(), grsCallBack);\n }", "pre_mask_code": "package com.android.server.wifi.grs.requestremote;\n\nimport android.provider.Settings;\nimport android.util.Log;\nimport com.android.server.wifi.grs.GrsCallBack;\nimport com.android.server.wifi.grs.utils.ContextUtil;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.CancellationException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\n\npublic class RequestController {\n\n private static final String CAPTIVE_PORTAL_REQUEST_TIME = \"captive_portal_request_time\";\n\n private static final int DEFAULT_TIME = 0;\n\n private static final int SILENT_PERIOD = 300000;\n\n private static final String TAG = \"RequestController\";\n\n private static volatile RequestController sInstance;\n\n private final Object mLock = new Object();\n\n /* access modifiers changed from: private */\n public ExecutorService taskExecutor = Executors.newCachedThreadPool();\n\n public static synchronized RequestController getInstance() {\n RequestController requestController;\n synchronized (RequestController.class) {\n if (sInstance == null) {\n sInstance = new RequestController();\n }\n requestController = sInstance;\n }\n return requestController;\n }\n\n /* access modifiers changed from: private */\n public GrsResponse getSyncServicesUrls() {\n synchronized (this.mLock) {\n if (System.currentTimeMillis() - Long.valueOf(Settings.Global.getLong(ContextUtil.getContext().getContentResolver(), CAPTIVE_PORTAL_REQUEST_TIME, 0)).longValue() < 300000) {\n Log.d(TAG, \"cancel this request because the last request is initiated less than 5 mins ago\");\n return null;\n }\n Settings.Global.putLong(ContextUtil.getContext().getContentResolver(), CAPTIVE_PORTAL_REQUEST_TIME, System.currentTimeMillis());\n Future future = this.taskExecutor.submit(new Callable() {\n\n // java.util.concurrent.Callable\n @Override\n public GrsResponse call() {\n return new GrsRequest().submitExcutorTaskWithTimeout(RequestController.this.taskExecutor);\n }\n });\n try {\n return future.get();\n } catch (CancellationException e) {\n Log.d(TAG, \"when check result, find CancellationException, check others\");\n return null;\n } catch (ExecutionException e2) {\n Log.d(TAG, \"when check result, find ExecutionException, check others\");\n return null;\n } catch (InterruptedException e3) {\n Log.d(TAG, \"when check result, find InterruptedException, check others\");\n return null;\n }\n }\n }\n\n public void getAsyncServicesUrls(final GrsCallBack grsCallBack) {\n this.taskExecutor.submit(new Runnable() {\n\n public void run() ", "post_mask_code": "\n });\n }\n\n /* access modifiers changed from: private */\n public void doCallBack(GrsResponse grsResponse, GrsCallBack grsCallBack) {\n if (grsCallBack == null) {\n return;\n }\n if (grsResponse == null) {\n Log.d(TAG, \"GrsResponse is null\");\n grsCallBack.onFailure();\n return;\n }\n Log.d(TAG, \"GrsResponse is not null\");\n grsCallBack.onResponse(grsResponse);\n }\n}\n"} {"task_id": "Java_2537", "language": "Java", "task_type": "single_line", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_10_1_0/src/main/java/com/android/server/wifi/grs/requestremote/RequestController.java", "mask_start_position": 1084, "mask_end_position": 1101, "canonical_solution": "equestController;", "pre_mask_code": "package com.android.server.wifi.grs.requestremote;\n\nimport android.provider.Settings;\nimport android.util.Log;\nimport com.android.server.wifi.grs.GrsCallBack;\nimport com.android.server.wifi.grs.utils.ContextUtil;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.CancellationException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\n\npublic class RequestController {\n\n private static final String CAPTIVE_PORTAL_REQUEST_TIME = \"captive_portal_request_time\";\n\n private static final int DEFAULT_TIME = 0;\n\n private static final int SILENT_PERIOD = 300000;\n\n private static final String TAG = \"RequestController\";\n\n private static volatile RequestController sInstance;\n\n private final Object mLock = new Object();\n\n /* access modifiers changed from: private */\n public ExecutorService taskExecutor = Executors.newCachedThreadPool();\n\n public static synchronized RequestController getInstance() {\n RequestController r", "post_mask_code": "\n synchronized (RequestController.class) {\n if (sInstance == null) {\n sInstance = new RequestController();\n }\n requestController = sInstance;\n }\n return requestController;\n }\n\n /* access modifiers changed from: private */\n public GrsResponse getSyncServicesUrls() {\n synchronized (this.mLock) {\n if (System.currentTimeMillis() - Long.valueOf(Settings.Global.getLong(ContextUtil.getContext().getContentResolver(), CAPTIVE_PORTAL_REQUEST_TIME, 0)).longValue() < 300000) {\n Log.d(TAG, \"cancel this request because the last request is initiated less than 5 mins ago\");\n return null;\n }\n Settings.Global.putLong(ContextUtil.getContext().getContentResolver(), CAPTIVE_PORTAL_REQUEST_TIME, System.currentTimeMillis());\n Future future = this.taskExecutor.submit(new Callable() {\n\n // java.util.concurrent.Callable\n @Override\n public GrsResponse call() {\n return new GrsRequest().submitExcutorTaskWithTimeout(RequestController.this.taskExecutor);\n }\n });\n try {\n return future.get();\n } catch (CancellationException e) {\n Log.d(TAG, \"when check result, find CancellationException, check others\");\n return null;\n } catch (ExecutionException e2) {\n Log.d(TAG, \"when check result, find ExecutionException, check others\");\n return null;\n } catch (InterruptedException e3) {\n Log.d(TAG, \"when check result, find InterruptedException, check others\");\n return null;\n }\n }\n }\n\n public void getAsyncServicesUrls(final GrsCallBack grsCallBack) {\n this.taskExecutor.submit(new Runnable() {\n\n public void run() {\n RequestController requestController = RequestController.this;\n requestController.doCallBack(requestController.getSyncServicesUrls(), grsCallBack);\n }\n });\n }\n\n /* access modifiers changed from: private */\n public void doCallBack(GrsResponse grsResponse, GrsCallBack grsCallBack) {\n if (grsCallBack == null) {\n return;\n }\n if (grsResponse == null) {\n Log.d(TAG, \"GrsResponse is null\");\n grsCallBack.onFailure();\n return;\n }\n Log.d(TAG, \"GrsResponse is not null\");\n grsCallBack.onResponse(grsResponse);\n }\n}\n"} {"task_id": "Java_2538", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/SivanLiu/HwFrameWorkSource/Mate20_10_1_0/src/main/java/com/android/server/wifi/grs/requestremote/RequestController.java", "mask_start_position": 3323, "mask_end_position": 3709, "canonical_solution": "public void doCallBack(GrsResponse grsResponse, GrsCallBack grsCallBack) {\n if (grsCallBack == null) {\n return;\n }\n if (grsResponse == null) {\n Log.d(TAG, \"GrsResponse is null\");\n grsCallBack.onFailure();\n return;\n }\n Log.d(TAG, \"GrsResponse is not null\");\n grsCallBack.onResponse(grsResponse);\n }", "pre_mask_code": "package com.android.server.wifi.grs.requestremote;\n\nimport android.provider.Settings;\nimport android.util.Log;\nimport com.android.server.wifi.grs.GrsCallBack;\nimport com.android.server.wifi.grs.utils.ContextUtil;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.CancellationException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\n\npublic class RequestController {\n\n private static final String CAPTIVE_PORTAL_REQUEST_TIME = \"captive_portal_request_time\";\n\n private static final int DEFAULT_TIME = 0;\n\n private static final int SILENT_PERIOD = 300000;\n\n private static final String TAG = \"RequestController\";\n\n private static volatile RequestController sInstance;\n\n private final Object mLock = new Object();\n\n /* access modifiers changed from: private */\n public ExecutorService taskExecutor = Executors.newCachedThreadPool();\n\n public static synchronized RequestController getInstance() {\n RequestController requestController;\n synchronized (RequestController.class) {\n if (sInstance == null) {\n sInstance = new RequestController();\n }\n requestController = sInstance;\n }\n return requestController;\n }\n\n /* access modifiers changed from: private */\n public GrsResponse getSyncServicesUrls() {\n synchronized (this.mLock) {\n if (System.currentTimeMillis() - Long.valueOf(Settings.Global.getLong(ContextUtil.getContext().getContentResolver(), CAPTIVE_PORTAL_REQUEST_TIME, 0)).longValue() < 300000) {\n Log.d(TAG, \"cancel this request because the last request is initiated less than 5 mins ago\");\n return null;\n }\n Settings.Global.putLong(ContextUtil.getContext().getContentResolver(), CAPTIVE_PORTAL_REQUEST_TIME, System.currentTimeMillis());\n Future future = this.taskExecutor.submit(new Callable() {\n\n // java.util.concurrent.Callable\n @Override\n public GrsResponse call() {\n return new GrsRequest().submitExcutorTaskWithTimeout(RequestController.this.taskExecutor);\n }\n });\n try {\n return future.get();\n } catch (CancellationException e) {\n Log.d(TAG, \"when check result, find CancellationException, check others\");\n return null;\n } catch (ExecutionException e2) {\n Log.d(TAG, \"when check result, find ExecutionException, check others\");\n return null;\n } catch (InterruptedException e3) {\n Log.d(TAG, \"when check result, find InterruptedException, check others\");\n return null;\n }\n }\n }\n\n public void getAsyncServicesUrls(final GrsCallBack grsCallBack) {\n this.taskExecutor.submit(new Runnable() {\n\n public void run() {\n RequestController requestController = RequestController.this;\n requestController.doCallBack(requestController.getSyncServicesUrls(), grsCallBack);\n }\n });\n }\n\n /* access modifiers changed from: private */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2539", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jflex-de/jflex/javatests/de/jflex/testcase/fixed_look/FixedlookGoldenTest.java", "mask_start_position": 1062, "mask_end_position": 1115, "canonical_solution": "@Test\n public void goldenTest0() throws Exception ", "pre_mask_code": "// test: fixedlook\npackage de.jflex.testcase.fixed_look;\n\nimport de.jflex.testing.testsuite.golden.AbstractGoldenTest;\nimport de.jflex.testing.testsuite.golden.GoldenInOutFilePair;\nimport de.jflex.util.scanner.ScannerFactory;\nimport java.io.File;\nimport org.junit.Test;\n\n/**\n * test fixed length lookahead, e.g. r1 / \"some text\"\n *\n *

Note: This test was generated from {@code jflex-testsuite-maven-plugin} test cases. The test\n * relies on golden files for testing, expecting the scanner to output logs on the {@code\n * System.out}. Please migrate to proper unit tests, as describe in \n * //javatest/jflex/testcase.\n */\n// TODO Migrate this test to proper unit tests.\npublic class FixedlookGoldenTest extends AbstractGoldenTest {\n\n /**\n * Creates a scanner conforming to the {@code fixedlook.flex} specification.\n */\n private final ScannerFactory scannerFactory = ScannerFactory.of(Fixedlook::new);\n\n private final File testRuntimeDir = new File(\"javatests/de/jflex/testcase/fixed_look\");\n\n ", "post_mask_code": "{\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-0.input\"), new File(testRuntimeDir, \"fixedlook-0.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n\n @Test\n public void goldenTest1() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-1.input\"), new File(testRuntimeDir, \"fixedlook-1.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n\n @Test\n public void goldenTest2() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-2.input\"), new File(testRuntimeDir, \"fixedlook-2.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n\n @Test\n public void goldenTest3() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-3.input\"), new File(testRuntimeDir, \"fixedlook-3.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n}\n"} {"task_id": "Java_2540", "language": "Java", "task_type": "method_body", "source_file": "java/github/jflex-de/jflex/javatests/de/jflex/testcase/fixed_look/FixedlookGoldenTest.java", "mask_start_position": 1995, "mask_end_position": 2376, "canonical_solution": "{\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-2.input\"), new File(testRuntimeDir, \"fixedlook-2.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }", "pre_mask_code": "// test: fixedlook\npackage de.jflex.testcase.fixed_look;\n\nimport de.jflex.testing.testsuite.golden.AbstractGoldenTest;\nimport de.jflex.testing.testsuite.golden.GoldenInOutFilePair;\nimport de.jflex.util.scanner.ScannerFactory;\nimport java.io.File;\nimport org.junit.Test;\n\n/**\n * test fixed length lookahead, e.g. r1 / \"some text\"\n *\n *

Note: This test was generated from {@code jflex-testsuite-maven-plugin} test cases. The test\n * relies on golden files for testing, expecting the scanner to output logs on the {@code\n * System.out}. Please migrate to proper unit tests, as describe in \n * //javatest/jflex/testcase.\n */\n// TODO Migrate this test to proper unit tests.\npublic class FixedlookGoldenTest extends AbstractGoldenTest {\n\n /**\n * Creates a scanner conforming to the {@code fixedlook.flex} specification.\n */\n private final ScannerFactory scannerFactory = ScannerFactory.of(Fixedlook::new);\n\n private final File testRuntimeDir = new File(\"javatests/de/jflex/testcase/fixed_look\");\n\n @Test\n public void goldenTest0() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-0.input\"), new File(testRuntimeDir, \"fixedlook-0.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n\n @Test\n public void goldenTest1() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-1.input\"), new File(testRuntimeDir, \"fixedlook-1.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n\n @Test\n public void goldenTest2() throws Exception ", "post_mask_code": "\n\n @Test\n public void goldenTest3() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-3.input\"), new File(testRuntimeDir, \"fixedlook-3.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n}\n"} {"task_id": "Java_2541", "language": "Java", "task_type": "single_line", "source_file": "java/github/jflex-de/jflex/javatests/de/jflex/testcase/fixed_look/FixedlookGoldenTest.java", "mask_start_position": 1773, "mask_end_position": 1834, "canonical_solution": "nner = scannerFactory.createScannerForFile(golden.inputFile);", "pre_mask_code": "// test: fixedlook\npackage de.jflex.testcase.fixed_look;\n\nimport de.jflex.testing.testsuite.golden.AbstractGoldenTest;\nimport de.jflex.testing.testsuite.golden.GoldenInOutFilePair;\nimport de.jflex.util.scanner.ScannerFactory;\nimport java.io.File;\nimport org.junit.Test;\n\n/**\n * test fixed length lookahead, e.g. r1 / \"some text\"\n *\n *

Note: This test was generated from {@code jflex-testsuite-maven-plugin} test cases. The test\n * relies on golden files for testing, expecting the scanner to output logs on the {@code\n * System.out}. Please migrate to proper unit tests, as describe in \n * //javatest/jflex/testcase.\n */\n// TODO Migrate this test to proper unit tests.\npublic class FixedlookGoldenTest extends AbstractGoldenTest {\n\n /**\n * Creates a scanner conforming to the {@code fixedlook.flex} specification.\n */\n private final ScannerFactory scannerFactory = ScannerFactory.of(Fixedlook::new);\n\n private final File testRuntimeDir = new File(\"javatests/de/jflex/testcase/fixed_look\");\n\n @Test\n public void goldenTest0() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-0.input\"), new File(testRuntimeDir, \"fixedlook-0.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n\n @Test\n public void goldenTest1() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-1.input\"), new File(testRuntimeDir, \"fixedlook-1.output\"));\n compareSystemOutWith(golden);\n Fixedlook sca", "post_mask_code": "\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n\n @Test\n public void goldenTest2() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-2.input\"), new File(testRuntimeDir, \"fixedlook-2.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n\n @Test\n public void goldenTest3() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-3.input\"), new File(testRuntimeDir, \"fixedlook-3.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n}\n"} {"task_id": "Java_2542", "language": "Java", "task_type": "while_statement", "source_file": "java/github/jflex-de/jflex/javatests/de/jflex/testcase/fixed_look/FixedlookGoldenTest.java", "mask_start_position": 2723, "mask_end_position": 2810, "canonical_solution": "while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }", "pre_mask_code": "// test: fixedlook\npackage de.jflex.testcase.fixed_look;\n\nimport de.jflex.testing.testsuite.golden.AbstractGoldenTest;\nimport de.jflex.testing.testsuite.golden.GoldenInOutFilePair;\nimport de.jflex.util.scanner.ScannerFactory;\nimport java.io.File;\nimport org.junit.Test;\n\n/**\n * test fixed length lookahead, e.g. r1 / \"some text\"\n *\n *

Note: This test was generated from {@code jflex-testsuite-maven-plugin} test cases. The test\n * relies on golden files for testing, expecting the scanner to output logs on the {@code\n * System.out}. Please migrate to proper unit tests, as describe in \n * //javatest/jflex/testcase.\n */\n// TODO Migrate this test to proper unit tests.\npublic class FixedlookGoldenTest extends AbstractGoldenTest {\n\n /**\n * Creates a scanner conforming to the {@code fixedlook.flex} specification.\n */\n private final ScannerFactory scannerFactory = ScannerFactory.of(Fixedlook::new);\n\n private final File testRuntimeDir = new File(\"javatests/de/jflex/testcase/fixed_look\");\n\n @Test\n public void goldenTest0() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-0.input\"), new File(testRuntimeDir, \"fixedlook-0.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n\n @Test\n public void goldenTest1() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-1.input\"), new File(testRuntimeDir, \"fixedlook-1.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n\n @Test\n public void goldenTest2() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-2.input\"), new File(testRuntimeDir, \"fixedlook-2.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n while (!scanner.yyatEOF()) {\n System.out.println(scanner.yylex());\n }\n }\n\n @Test\n public void goldenTest3() throws Exception {\n GoldenInOutFilePair golden = new GoldenInOutFilePair(new File(testRuntimeDir, \"fixedlook-3.input\"), new File(testRuntimeDir, \"fixedlook-3.output\"));\n compareSystemOutWith(golden);\n Fixedlook scanner = scannerFactory.createScannerForFile(golden.inputFile);\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2543", "language": "Java", "task_type": "method_signature", "source_file": "java/github/stanfordnlp/CoreNLP/itest/src/edu/stanford/nlp/ie/crf/TestThreadedCRFClassifier.java", "mask_start_position": 3028, "mask_end_position": 3067, "canonical_solution": "void runThreadedTest(Properties props) ", "pre_mask_code": "package edu.stanford.nlp.ie.crf;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.PrintStream;\nimport java.io.UnsupportedEncodingException;\nimport java.util.ArrayList;\nimport java.util.Properties;\nimport edu.stanford.nlp.util.PropertiesUtils;\nimport edu.stanford.nlp.util.StringUtils;\nimport edu.stanford.nlp.util.Timing;\n\npublic class TestThreadedCRFClassifier {\n\n TestThreadedCRFClassifier(Properties props) {\n inputEncoding = props.getProperty(\"inputEncoding\", \"UTF-8\");\n }\n\n // number of threads to run the first specified classifier under\n private static final int DEFAULT_SIM_THREADS = 3;\n\n private static final int DEFAULT_MULTIPLE_THREADS = 2;\n\n private final String inputEncoding;\n\n static CRFClassifier loadClassifier(String loadPath, Properties props) {\n CRFClassifier crf = new CRFClassifier(props);\n crf.loadClassifierNoExceptions(loadPath, props);\n return crf;\n }\n\n String runClassifier(CRFClassifier crf, String testFile) {\n try {\n ByteArrayOutputStream output = new ByteArrayOutputStream();\n crf.classifyAndWriteAnswers(testFile, output, crf.makeReaderAndWriter(), true);\n return output.toString(inputEncoding);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n class CRFThread extends Thread {\n\n private final CRFClassifier crf;\n\n private final String filename;\n\n private final String threadName;\n\n private String resultsString = \"\";\n\n public String getResultsString() {\n return resultsString;\n }\n\n CRFThread(CRFClassifier crf, String filename, String threadName) {\n this.crf = crf;\n this.filename = filename;\n this.threadName = threadName;\n }\n\n @Override\n public void run() {\n Timing t = new Timing();\n resultsString = runClassifier(crf, filename);\n long millis = t.stop();\n System.out.println(\"Thread \" + threadName + \" took \" + millis + \"ms to tag file \" + filename);\n }\n }\n\n /**\n * Sample command line:\n *
\n * java -mx4g edu.stanford.nlp.ie.crf.TestThreadedCRFClassifier\n * -crf1 ../stanford-releases/stanford-ner-models/hgc_175m_600.ser.gz\n * -crf2 ../stanford-releases/stanford-ner-models/dewac_175m_600.ser.gz\n * -testFile ../data/german-ner/deu.testa -inputEncoding iso-8859-1\n */\n public static void main(String[] args) {\n try {\n System.setOut(new PrintStream(System.out, true, \"UTF-8\"));\n System.setErr(new PrintStream(System.err, true, \"UTF-8\"));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n runTest(StringUtils.argsToProperties(args));\n }\n\n static public void runTest(Properties props) {\n TestThreadedCRFClassifier test = new TestThreadedCRFClassifier(props);\n test.runThreadedTest(props);\n }\n\n ", "post_mask_code": "{\n // TODO: check params\n final String testFile = props.getProperty(\"testFile\");\n ArrayList baseResults = new ArrayList<>();\n ArrayList modelNames = new ArrayList<>();\n ArrayList classifiers = new ArrayList<>();\n for (int i = 1; props.getProperty(\"crf\" + Integer.toString(i)) != null; ++i) {\n String model = props.getProperty(\"crf\" + Integer.toString(i));\n CRFClassifier crf = loadClassifier(model, props);\n System.out.println(\"Loaded model \" + model);\n modelNames.add(model);\n classifiers.add(crf);\n String results = runClassifier(crf, testFile);\n // must run twice to account for \"transductive learning\"\n results = runClassifier(crf, testFile);\n baseResults.add(results);\n System.out.println(\"Stored base results for \" + model + \"; length \" + results.length());\n }\n // test to make sure loading and running multiple classifiers\n // hasn't messed with previous results\n for (int i = 0; i < classifiers.size(); ++i) {\n CRFClassifier crf = classifiers.get(i);\n String model = modelNames.get(i);\n String base = baseResults.get(i);\n String repeated = runClassifier(crf, testFile);\n if (!base.equals(repeated)) {\n throw new RuntimeException(\"Repeated unthreaded results \" + \"not the same for \" + model + \" run on file \" + testFile);\n }\n }\n // test the first classifier in several simultaneous threads\n int numThreads = PropertiesUtils.getInt(props, \"simThreads\", DEFAULT_SIM_THREADS);\n ArrayList threads = new ArrayList<>();\n for (int i = 0; i < numThreads; ++i) {\n threads.add(new CRFThread(classifiers.get(0), testFile, \"Simultaneous-\" + i));\n }\n for (int i = 0; i < numThreads; ++i) {\n threads.get(i).start();\n }\n for (int i = 0; i < numThreads; ++i) {\n try {\n threads.get(i).join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n if (baseResults.get(0).equals(threads.get(i).getResultsString())) {\n System.out.println(\"Yay!\");\n } else {\n throw new RuntimeException(\"Results not equal when running \" + modelNames.get(0) + \" under \" + numThreads + \" simultaneous threads\");\n }\n }\n // test multiple classifiers (if given) in multiple threads each\n if (classifiers.size() > 1) {\n numThreads = PropertiesUtils.getInt(props, \"multipleThreads\", DEFAULT_MULTIPLE_THREADS);\n threads = new ArrayList();\n for (int i = 0; i < numThreads * classifiers.size(); ++i) {\n int classifierNum = i % classifiers.size();\n int repeatNum = i / classifiers.size();\n threads.add(new CRFThread(classifiers.get(classifierNum), testFile, (\"Simultaneous-\" + classifierNum + \"-\" + repeatNum)));\n }\n for (CRFThread thread : threads) {\n thread.start();\n }\n for (int i = 0; i < threads.size(); ++i) {\n int classifierNum = i % classifiers.size();\n int repeatNum = i / classifiers.size();\n try {\n threads.get(i).join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n String base = baseResults.get(classifierNum);\n String threadResults = threads.get(i).getResultsString();\n if (base.equals(threadResults)) {\n System.out.println(\"Yay!\");\n } else {\n throw new RuntimeException(\"Results not equal when running \" + modelNames.get(classifierNum) + \" under \" + numThreads + \" threads with \" + classifiers.size() + \" total classifiers\");\n }\n }\n }\n // if no exceptions thrown, great success\n System.out.println(\"Everything worked!\");\n }\n}\n"} {"task_id": "Java_2544", "language": "Java", "task_type": "method_body", "source_file": "java/github/stanfordnlp/CoreNLP/itest/src/edu/stanford/nlp/ie/crf/TestThreadedCRFClassifier.java", "mask_start_position": 1025, "mask_end_position": 1348, "canonical_solution": "{\n try {\n ByteArrayOutputStream output = new ByteArrayOutputStream();\n crf.classifyAndWriteAnswers(testFile, output, crf.makeReaderAndWriter(), true);\n return output.toString(inputEncoding);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }", "pre_mask_code": "package edu.stanford.nlp.ie.crf;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.PrintStream;\nimport java.io.UnsupportedEncodingException;\nimport java.util.ArrayList;\nimport java.util.Properties;\nimport edu.stanford.nlp.util.PropertiesUtils;\nimport edu.stanford.nlp.util.StringUtils;\nimport edu.stanford.nlp.util.Timing;\n\npublic class TestThreadedCRFClassifier {\n\n TestThreadedCRFClassifier(Properties props) {\n inputEncoding = props.getProperty(\"inputEncoding\", \"UTF-8\");\n }\n\n // number of threads to run the first specified classifier under\n private static final int DEFAULT_SIM_THREADS = 3;\n\n private static final int DEFAULT_MULTIPLE_THREADS = 2;\n\n private final String inputEncoding;\n\n static CRFClassifier loadClassifier(String loadPath, Properties props) {\n CRFClassifier crf = new CRFClassifier(props);\n crf.loadClassifierNoExceptions(loadPath, props);\n return crf;\n }\n\n String runClassifier(CRFClassifier crf, String testFile) ", "post_mask_code": "\n\n class CRFThread extends Thread {\n\n private final CRFClassifier crf;\n\n private final String filename;\n\n private final String threadName;\n\n private String resultsString = \"\";\n\n public String getResultsString() {\n return resultsString;\n }\n\n CRFThread(CRFClassifier crf, String filename, String threadName) {\n this.crf = crf;\n this.filename = filename;\n this.threadName = threadName;\n }\n\n @Override\n public void run() {\n Timing t = new Timing();\n resultsString = runClassifier(crf, filename);\n long millis = t.stop();\n System.out.println(\"Thread \" + threadName + \" took \" + millis + \"ms to tag file \" + filename);\n }\n }\n\n /**\n * Sample command line:\n *
\n * java -mx4g edu.stanford.nlp.ie.crf.TestThreadedCRFClassifier\n * -crf1 ../stanford-releases/stanford-ner-models/hgc_175m_600.ser.gz\n * -crf2 ../stanford-releases/stanford-ner-models/dewac_175m_600.ser.gz\n * -testFile ../data/german-ner/deu.testa -inputEncoding iso-8859-1\n */\n public static void main(String[] args) {\n try {\n System.setOut(new PrintStream(System.out, true, \"UTF-8\"));\n System.setErr(new PrintStream(System.err, true, \"UTF-8\"));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n runTest(StringUtils.argsToProperties(args));\n }\n\n static public void runTest(Properties props) {\n TestThreadedCRFClassifier test = new TestThreadedCRFClassifier(props);\n test.runThreadedTest(props);\n }\n\n void runThreadedTest(Properties props) {\n // TODO: check params\n final String testFile = props.getProperty(\"testFile\");\n ArrayList baseResults = new ArrayList<>();\n ArrayList modelNames = new ArrayList<>();\n ArrayList classifiers = new ArrayList<>();\n for (int i = 1; props.getProperty(\"crf\" + Integer.toString(i)) != null; ++i) {\n String model = props.getProperty(\"crf\" + Integer.toString(i));\n CRFClassifier crf = loadClassifier(model, props);\n System.out.println(\"Loaded model \" + model);\n modelNames.add(model);\n classifiers.add(crf);\n String results = runClassifier(crf, testFile);\n // must run twice to account for \"transductive learning\"\n results = runClassifier(crf, testFile);\n baseResults.add(results);\n System.out.println(\"Stored base results for \" + model + \"; length \" + results.length());\n }\n // test to make sure loading and running multiple classifiers\n // hasn't messed with previous results\n for (int i = 0; i < classifiers.size(); ++i) {\n CRFClassifier crf = classifiers.get(i);\n String model = modelNames.get(i);\n String base = baseResults.get(i);\n String repeated = runClassifier(crf, testFile);\n if (!base.equals(repeated)) {\n throw new RuntimeException(\"Repeated unthreaded results \" + \"not the same for \" + model + \" run on file \" + testFile);\n }\n }\n // test the first classifier in several simultaneous threads\n int numThreads = PropertiesUtils.getInt(props, \"simThreads\", DEFAULT_SIM_THREADS);\n ArrayList threads = new ArrayList<>();\n for (int i = 0; i < numThreads; ++i) {\n threads.add(new CRFThread(classifiers.get(0), testFile, \"Simultaneous-\" + i));\n }\n for (int i = 0; i < numThreads; ++i) {\n threads.get(i).start();\n }\n for (int i = 0; i < numThreads; ++i) {\n try {\n threads.get(i).join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n if (baseResults.get(0).equals(threads.get(i).getResultsString())) {\n System.out.println(\"Yay!\");\n } else {\n throw new RuntimeException(\"Results not equal when running \" + modelNames.get(0) + \" under \" + numThreads + \" simultaneous threads\");\n }\n }\n // test multiple classifiers (if given) in multiple threads each\n if (classifiers.size() > 1) {\n numThreads = PropertiesUtils.getInt(props, \"multipleThreads\", DEFAULT_MULTIPLE_THREADS);\n threads = new ArrayList();\n for (int i = 0; i < numThreads * classifiers.size(); ++i) {\n int classifierNum = i % classifiers.size();\n int repeatNum = i / classifiers.size();\n threads.add(new CRFThread(classifiers.get(classifierNum), testFile, (\"Simultaneous-\" + classifierNum + \"-\" + repeatNum)));\n }\n for (CRFThread thread : threads) {\n thread.start();\n }\n for (int i = 0; i < threads.size(); ++i) {\n int classifierNum = i % classifiers.size();\n int repeatNum = i / classifiers.size();\n try {\n threads.get(i).join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n String base = baseResults.get(classifierNum);\n String threadResults = threads.get(i).getResultsString();\n if (base.equals(threadResults)) {\n System.out.println(\"Yay!\");\n } else {\n throw new RuntimeException(\"Results not equal when running \" + modelNames.get(classifierNum) + \" under \" + numThreads + \" threads with \" + classifiers.size() + \" total classifiers\");\n }\n }\n }\n // if no exceptions thrown, great success\n System.out.println(\"Everything worked!\");\n }\n}\n"} {"task_id": "Java_2545", "language": "Java", "task_type": "single_line", "source_file": "java/github/stanfordnlp/CoreNLP/itest/src/edu/stanford/nlp/ie/crf/TestThreadedCRFClassifier.java", "mask_start_position": 7210, "mask_end_position": 7246, "canonical_solution": "m.out.println(\"Everything worked!\");", "pre_mask_code": "package edu.stanford.nlp.ie.crf;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.PrintStream;\nimport java.io.UnsupportedEncodingException;\nimport java.util.ArrayList;\nimport java.util.Properties;\nimport edu.stanford.nlp.util.PropertiesUtils;\nimport edu.stanford.nlp.util.StringUtils;\nimport edu.stanford.nlp.util.Timing;\n\npublic class TestThreadedCRFClassifier {\n\n TestThreadedCRFClassifier(Properties props) {\n inputEncoding = props.getProperty(\"inputEncoding\", \"UTF-8\");\n }\n\n // number of threads to run the first specified classifier under\n private static final int DEFAULT_SIM_THREADS = 3;\n\n private static final int DEFAULT_MULTIPLE_THREADS = 2;\n\n private final String inputEncoding;\n\n static CRFClassifier loadClassifier(String loadPath, Properties props) {\n CRFClassifier crf = new CRFClassifier(props);\n crf.loadClassifierNoExceptions(loadPath, props);\n return crf;\n }\n\n String runClassifier(CRFClassifier crf, String testFile) {\n try {\n ByteArrayOutputStream output = new ByteArrayOutputStream();\n crf.classifyAndWriteAnswers(testFile, output, crf.makeReaderAndWriter(), true);\n return output.toString(inputEncoding);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n class CRFThread extends Thread {\n\n private final CRFClassifier crf;\n\n private final String filename;\n\n private final String threadName;\n\n private String resultsString = \"\";\n\n public String getResultsString() {\n return resultsString;\n }\n\n CRFThread(CRFClassifier crf, String filename, String threadName) {\n this.crf = crf;\n this.filename = filename;\n this.threadName = threadName;\n }\n\n @Override\n public void run() {\n Timing t = new Timing();\n resultsString = runClassifier(crf, filename);\n long millis = t.stop();\n System.out.println(\"Thread \" + threadName + \" took \" + millis + \"ms to tag file \" + filename);\n }\n }\n\n /**\n * Sample command line:\n *
\n * java -mx4g edu.stanford.nlp.ie.crf.TestThreadedCRFClassifier\n * -crf1 ../stanford-releases/stanford-ner-models/hgc_175m_600.ser.gz\n * -crf2 ../stanford-releases/stanford-ner-models/dewac_175m_600.ser.gz\n * -testFile ../data/german-ner/deu.testa -inputEncoding iso-8859-1\n */\n public static void main(String[] args) {\n try {\n System.setOut(new PrintStream(System.out, true, \"UTF-8\"));\n System.setErr(new PrintStream(System.err, true, \"UTF-8\"));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n runTest(StringUtils.argsToProperties(args));\n }\n\n static public void runTest(Properties props) {\n TestThreadedCRFClassifier test = new TestThreadedCRFClassifier(props);\n test.runThreadedTest(props);\n }\n\n void runThreadedTest(Properties props) {\n // TODO: check params\n final String testFile = props.getProperty(\"testFile\");\n ArrayList baseResults = new ArrayList<>();\n ArrayList modelNames = new ArrayList<>();\n ArrayList classifiers = new ArrayList<>();\n for (int i = 1; props.getProperty(\"crf\" + Integer.toString(i)) != null; ++i) {\n String model = props.getProperty(\"crf\" + Integer.toString(i));\n CRFClassifier crf = loadClassifier(model, props);\n System.out.println(\"Loaded model \" + model);\n modelNames.add(model);\n classifiers.add(crf);\n String results = runClassifier(crf, testFile);\n // must run twice to account for \"transductive learning\"\n results = runClassifier(crf, testFile);\n baseResults.add(results);\n System.out.println(\"Stored base results for \" + model + \"; length \" + results.length());\n }\n // test to make sure loading and running multiple classifiers\n // hasn't messed with previous results\n for (int i = 0; i < classifiers.size(); ++i) {\n CRFClassifier crf = classifiers.get(i);\n String model = modelNames.get(i);\n String base = baseResults.get(i);\n String repeated = runClassifier(crf, testFile);\n if (!base.equals(repeated)) {\n throw new RuntimeException(\"Repeated unthreaded results \" + \"not the same for \" + model + \" run on file \" + testFile);\n }\n }\n // test the first classifier in several simultaneous threads\n int numThreads = PropertiesUtils.getInt(props, \"simThreads\", DEFAULT_SIM_THREADS);\n ArrayList threads = new ArrayList<>();\n for (int i = 0; i < numThreads; ++i) {\n threads.add(new CRFThread(classifiers.get(0), testFile, \"Simultaneous-\" + i));\n }\n for (int i = 0; i < numThreads; ++i) {\n threads.get(i).start();\n }\n for (int i = 0; i < numThreads; ++i) {\n try {\n threads.get(i).join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n if (baseResults.get(0).equals(threads.get(i).getResultsString())) {\n System.out.println(\"Yay!\");\n } else {\n throw new RuntimeException(\"Results not equal when running \" + modelNames.get(0) + \" under \" + numThreads + \" simultaneous threads\");\n }\n }\n // test multiple classifiers (if given) in multiple threads each\n if (classifiers.size() > 1) {\n numThreads = PropertiesUtils.getInt(props, \"multipleThreads\", DEFAULT_MULTIPLE_THREADS);\n threads = new ArrayList();\n for (int i = 0; i < numThreads * classifiers.size(); ++i) {\n int classifierNum = i % classifiers.size();\n int repeatNum = i / classifiers.size();\n threads.add(new CRFThread(classifiers.get(classifierNum), testFile, (\"Simultaneous-\" + classifierNum + \"-\" + repeatNum)));\n }\n for (CRFThread thread : threads) {\n thread.start();\n }\n for (int i = 0; i < threads.size(); ++i) {\n int classifierNum = i % classifiers.size();\n int repeatNum = i / classifiers.size();\n try {\n threads.get(i).join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n String base = baseResults.get(classifierNum);\n String threadResults = threads.get(i).getResultsString();\n if (base.equals(threadResults)) {\n System.out.println(\"Yay!\");\n } else {\n throw new RuntimeException(\"Results not equal when running \" + modelNames.get(classifierNum) + \" under \" + numThreads + \" threads with \" + classifiers.size() + \" total classifiers\");\n }\n }\n }\n // if no exceptions thrown, great success\n Syste", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2546", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/stanfordnlp/CoreNLP/itest/src/edu/stanford/nlp/ie/crf/TestThreadedCRFClassifier.java", "mask_start_position": 2489, "mask_end_position": 2848, "canonical_solution": "public static void main(String[] args) {\n try {\n System.setOut(new PrintStream(System.out, true, \"UTF-8\"));\n System.setErr(new PrintStream(System.err, true, \"UTF-8\"));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n runTest(StringUtils.argsToProperties(args));\n }", "pre_mask_code": "package edu.stanford.nlp.ie.crf;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.PrintStream;\nimport java.io.UnsupportedEncodingException;\nimport java.util.ArrayList;\nimport java.util.Properties;\nimport edu.stanford.nlp.util.PropertiesUtils;\nimport edu.stanford.nlp.util.StringUtils;\nimport edu.stanford.nlp.util.Timing;\n\npublic class TestThreadedCRFClassifier {\n\n TestThreadedCRFClassifier(Properties props) {\n inputEncoding = props.getProperty(\"inputEncoding\", \"UTF-8\");\n }\n\n // number of threads to run the first specified classifier under\n private static final int DEFAULT_SIM_THREADS = 3;\n\n private static final int DEFAULT_MULTIPLE_THREADS = 2;\n\n private final String inputEncoding;\n\n static CRFClassifier loadClassifier(String loadPath, Properties props) {\n CRFClassifier crf = new CRFClassifier(props);\n crf.loadClassifierNoExceptions(loadPath, props);\n return crf;\n }\n\n String runClassifier(CRFClassifier crf, String testFile) {\n try {\n ByteArrayOutputStream output = new ByteArrayOutputStream();\n crf.classifyAndWriteAnswers(testFile, output, crf.makeReaderAndWriter(), true);\n return output.toString(inputEncoding);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n class CRFThread extends Thread {\n\n private final CRFClassifier crf;\n\n private final String filename;\n\n private final String threadName;\n\n private String resultsString = \"\";\n\n public String getResultsString() {\n return resultsString;\n }\n\n CRFThread(CRFClassifier crf, String filename, String threadName) {\n this.crf = crf;\n this.filename = filename;\n this.threadName = threadName;\n }\n\n @Override\n public void run() {\n Timing t = new Timing();\n resultsString = runClassifier(crf, filename);\n long millis = t.stop();\n System.out.println(\"Thread \" + threadName + \" took \" + millis + \"ms to tag file \" + filename);\n }\n }\n\n /**\n * Sample command line:\n *
\n * java -mx4g edu.stanford.nlp.ie.crf.TestThreadedCRFClassifier\n * -crf1 ../stanford-releases/stanford-ner-models/hgc_175m_600.ser.gz\n * -crf2 ../stanford-releases/stanford-ner-models/dewac_175m_600.ser.gz\n * -testFile ../data/german-ner/deu.testa -inputEncoding iso-8859-1\n */\n ", "post_mask_code": "\n\n static public void runTest(Properties props) {\n TestThreadedCRFClassifier test = new TestThreadedCRFClassifier(props);\n test.runThreadedTest(props);\n }\n\n void runThreadedTest(Properties props) {\n // TODO: check params\n final String testFile = props.getProperty(\"testFile\");\n ArrayList baseResults = new ArrayList<>();\n ArrayList modelNames = new ArrayList<>();\n ArrayList classifiers = new ArrayList<>();\n for (int i = 1; props.getProperty(\"crf\" + Integer.toString(i)) != null; ++i) {\n String model = props.getProperty(\"crf\" + Integer.toString(i));\n CRFClassifier crf = loadClassifier(model, props);\n System.out.println(\"Loaded model \" + model);\n modelNames.add(model);\n classifiers.add(crf);\n String results = runClassifier(crf, testFile);\n // must run twice to account for \"transductive learning\"\n results = runClassifier(crf, testFile);\n baseResults.add(results);\n System.out.println(\"Stored base results for \" + model + \"; length \" + results.length());\n }\n // test to make sure loading and running multiple classifiers\n // hasn't messed with previous results\n for (int i = 0; i < classifiers.size(); ++i) {\n CRFClassifier crf = classifiers.get(i);\n String model = modelNames.get(i);\n String base = baseResults.get(i);\n String repeated = runClassifier(crf, testFile);\n if (!base.equals(repeated)) {\n throw new RuntimeException(\"Repeated unthreaded results \" + \"not the same for \" + model + \" run on file \" + testFile);\n }\n }\n // test the first classifier in several simultaneous threads\n int numThreads = PropertiesUtils.getInt(props, \"simThreads\", DEFAULT_SIM_THREADS);\n ArrayList threads = new ArrayList<>();\n for (int i = 0; i < numThreads; ++i) {\n threads.add(new CRFThread(classifiers.get(0), testFile, \"Simultaneous-\" + i));\n }\n for (int i = 0; i < numThreads; ++i) {\n threads.get(i).start();\n }\n for (int i = 0; i < numThreads; ++i) {\n try {\n threads.get(i).join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n if (baseResults.get(0).equals(threads.get(i).getResultsString())) {\n System.out.println(\"Yay!\");\n } else {\n throw new RuntimeException(\"Results not equal when running \" + modelNames.get(0) + \" under \" + numThreads + \" simultaneous threads\");\n }\n }\n // test multiple classifiers (if given) in multiple threads each\n if (classifiers.size() > 1) {\n numThreads = PropertiesUtils.getInt(props, \"multipleThreads\", DEFAULT_MULTIPLE_THREADS);\n threads = new ArrayList();\n for (int i = 0; i < numThreads * classifiers.size(); ++i) {\n int classifierNum = i % classifiers.size();\n int repeatNum = i / classifiers.size();\n threads.add(new CRFThread(classifiers.get(classifierNum), testFile, (\"Simultaneous-\" + classifierNum + \"-\" + repeatNum)));\n }\n for (CRFThread thread : threads) {\n thread.start();\n }\n for (int i = 0; i < threads.size(); ++i) {\n int classifierNum = i % classifiers.size();\n int repeatNum = i / classifiers.size();\n try {\n threads.get(i).join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n String base = baseResults.get(classifierNum);\n String threadResults = threads.get(i).getResultsString();\n if (base.equals(threadResults)) {\n System.out.println(\"Yay!\");\n } else {\n throw new RuntimeException(\"Results not equal when running \" + modelNames.get(classifierNum) + \" under \" + numThreads + \" threads with \" + classifiers.size() + \" total classifiers\");\n }\n }\n }\n // if no exceptions thrown, great success\n System.out.println(\"Everything worked!\");\n }\n}\n"} {"task_id": "Java_2547", "language": "Java", "task_type": "for_statement", "source_file": "java/github/stanfordnlp/CoreNLP/itest/src/edu/stanford/nlp/ie/crf/TestThreadedCRFClassifier.java", "mask_start_position": 5865, "mask_end_position": 6193, "canonical_solution": "for (int i = 0; i < numThreads * classifiers.size(); ++i) {\n int classifierNum = i % classifiers.size();\n int repeatNum = i / classifiers.size();\n threads.add(new CRFThread(classifiers.get(classifierNum), testFile, (\"Simultaneous-\" + classifierNum + \"-\" + repeatNum)));\n }", "pre_mask_code": "package edu.stanford.nlp.ie.crf;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.PrintStream;\nimport java.io.UnsupportedEncodingException;\nimport java.util.ArrayList;\nimport java.util.Properties;\nimport edu.stanford.nlp.util.PropertiesUtils;\nimport edu.stanford.nlp.util.StringUtils;\nimport edu.stanford.nlp.util.Timing;\n\npublic class TestThreadedCRFClassifier {\n\n TestThreadedCRFClassifier(Properties props) {\n inputEncoding = props.getProperty(\"inputEncoding\", \"UTF-8\");\n }\n\n // number of threads to run the first specified classifier under\n private static final int DEFAULT_SIM_THREADS = 3;\n\n private static final int DEFAULT_MULTIPLE_THREADS = 2;\n\n private final String inputEncoding;\n\n static CRFClassifier loadClassifier(String loadPath, Properties props) {\n CRFClassifier crf = new CRFClassifier(props);\n crf.loadClassifierNoExceptions(loadPath, props);\n return crf;\n }\n\n String runClassifier(CRFClassifier crf, String testFile) {\n try {\n ByteArrayOutputStream output = new ByteArrayOutputStream();\n crf.classifyAndWriteAnswers(testFile, output, crf.makeReaderAndWriter(), true);\n return output.toString(inputEncoding);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n class CRFThread extends Thread {\n\n private final CRFClassifier crf;\n\n private final String filename;\n\n private final String threadName;\n\n private String resultsString = \"\";\n\n public String getResultsString() {\n return resultsString;\n }\n\n CRFThread(CRFClassifier crf, String filename, String threadName) {\n this.crf = crf;\n this.filename = filename;\n this.threadName = threadName;\n }\n\n @Override\n public void run() {\n Timing t = new Timing();\n resultsString = runClassifier(crf, filename);\n long millis = t.stop();\n System.out.println(\"Thread \" + threadName + \" took \" + millis + \"ms to tag file \" + filename);\n }\n }\n\n /**\n * Sample command line:\n *
\n * java -mx4g edu.stanford.nlp.ie.crf.TestThreadedCRFClassifier\n * -crf1 ../stanford-releases/stanford-ner-models/hgc_175m_600.ser.gz\n * -crf2 ../stanford-releases/stanford-ner-models/dewac_175m_600.ser.gz\n * -testFile ../data/german-ner/deu.testa -inputEncoding iso-8859-1\n */\n public static void main(String[] args) {\n try {\n System.setOut(new PrintStream(System.out, true, \"UTF-8\"));\n System.setErr(new PrintStream(System.err, true, \"UTF-8\"));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n runTest(StringUtils.argsToProperties(args));\n }\n\n static public void runTest(Properties props) {\n TestThreadedCRFClassifier test = new TestThreadedCRFClassifier(props);\n test.runThreadedTest(props);\n }\n\n void runThreadedTest(Properties props) {\n // TODO: check params\n final String testFile = props.getProperty(\"testFile\");\n ArrayList baseResults = new ArrayList<>();\n ArrayList modelNames = new ArrayList<>();\n ArrayList classifiers = new ArrayList<>();\n for (int i = 1; props.getProperty(\"crf\" + Integer.toString(i)) != null; ++i) {\n String model = props.getProperty(\"crf\" + Integer.toString(i));\n CRFClassifier crf = loadClassifier(model, props);\n System.out.println(\"Loaded model \" + model);\n modelNames.add(model);\n classifiers.add(crf);\n String results = runClassifier(crf, testFile);\n // must run twice to account for \"transductive learning\"\n results = runClassifier(crf, testFile);\n baseResults.add(results);\n System.out.println(\"Stored base results for \" + model + \"; length \" + results.length());\n }\n // test to make sure loading and running multiple classifiers\n // hasn't messed with previous results\n for (int i = 0; i < classifiers.size(); ++i) {\n CRFClassifier crf = classifiers.get(i);\n String model = modelNames.get(i);\n String base = baseResults.get(i);\n String repeated = runClassifier(crf, testFile);\n if (!base.equals(repeated)) {\n throw new RuntimeException(\"Repeated unthreaded results \" + \"not the same for \" + model + \" run on file \" + testFile);\n }\n }\n // test the first classifier in several simultaneous threads\n int numThreads = PropertiesUtils.getInt(props, \"simThreads\", DEFAULT_SIM_THREADS);\n ArrayList threads = new ArrayList<>();\n for (int i = 0; i < numThreads; ++i) {\n threads.add(new CRFThread(classifiers.get(0), testFile, \"Simultaneous-\" + i));\n }\n for (int i = 0; i < numThreads; ++i) {\n threads.get(i).start();\n }\n for (int i = 0; i < numThreads; ++i) {\n try {\n threads.get(i).join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n if (baseResults.get(0).equals(threads.get(i).getResultsString())) {\n System.out.println(\"Yay!\");\n } else {\n throw new RuntimeException(\"Results not equal when running \" + modelNames.get(0) + \" under \" + numThreads + \" simultaneous threads\");\n }\n }\n // test multiple classifiers (if given) in multiple threads each\n if (classifiers.size() > 1) {\n numThreads = PropertiesUtils.getInt(props, \"multipleThreads\", DEFAULT_MULTIPLE_THREADS);\n threads = new ArrayList();\n ", "post_mask_code": "\n for (CRFThread thread : threads) {\n thread.start();\n }\n for (int i = 0; i < threads.size(); ++i) {\n int classifierNum = i % classifiers.size();\n int repeatNum = i / classifiers.size();\n try {\n threads.get(i).join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n String base = baseResults.get(classifierNum);\n String threadResults = threads.get(i).getResultsString();\n if (base.equals(threadResults)) {\n System.out.println(\"Yay!\");\n } else {\n throw new RuntimeException(\"Results not equal when running \" + modelNames.get(classifierNum) + \" under \" + numThreads + \" threads with \" + classifiers.size() + \" total classifiers\");\n }\n }\n }\n // if no exceptions thrown, great success\n System.out.println(\"Everything worked!\");\n }\n}\n"} {"task_id": "Java_2548", "language": "Java", "task_type": "try_statement", "source_file": "java/github/stanfordnlp/CoreNLP/itest/src/edu/stanford/nlp/ie/crf/TestThreadedCRFClassifier.java", "mask_start_position": 5119, "mask_end_position": 5271, "canonical_solution": "try {\n threads.get(i).join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }", "pre_mask_code": "package edu.stanford.nlp.ie.crf;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.PrintStream;\nimport java.io.UnsupportedEncodingException;\nimport java.util.ArrayList;\nimport java.util.Properties;\nimport edu.stanford.nlp.util.PropertiesUtils;\nimport edu.stanford.nlp.util.StringUtils;\nimport edu.stanford.nlp.util.Timing;\n\npublic class TestThreadedCRFClassifier {\n\n TestThreadedCRFClassifier(Properties props) {\n inputEncoding = props.getProperty(\"inputEncoding\", \"UTF-8\");\n }\n\n // number of threads to run the first specified classifier under\n private static final int DEFAULT_SIM_THREADS = 3;\n\n private static final int DEFAULT_MULTIPLE_THREADS = 2;\n\n private final String inputEncoding;\n\n static CRFClassifier loadClassifier(String loadPath, Properties props) {\n CRFClassifier crf = new CRFClassifier(props);\n crf.loadClassifierNoExceptions(loadPath, props);\n return crf;\n }\n\n String runClassifier(CRFClassifier crf, String testFile) {\n try {\n ByteArrayOutputStream output = new ByteArrayOutputStream();\n crf.classifyAndWriteAnswers(testFile, output, crf.makeReaderAndWriter(), true);\n return output.toString(inputEncoding);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n class CRFThread extends Thread {\n\n private final CRFClassifier crf;\n\n private final String filename;\n\n private final String threadName;\n\n private String resultsString = \"\";\n\n public String getResultsString() {\n return resultsString;\n }\n\n CRFThread(CRFClassifier crf, String filename, String threadName) {\n this.crf = crf;\n this.filename = filename;\n this.threadName = threadName;\n }\n\n @Override\n public void run() {\n Timing t = new Timing();\n resultsString = runClassifier(crf, filename);\n long millis = t.stop();\n System.out.println(\"Thread \" + threadName + \" took \" + millis + \"ms to tag file \" + filename);\n }\n }\n\n /**\n * Sample command line:\n *
\n * java -mx4g edu.stanford.nlp.ie.crf.TestThreadedCRFClassifier\n * -crf1 ../stanford-releases/stanford-ner-models/hgc_175m_600.ser.gz\n * -crf2 ../stanford-releases/stanford-ner-models/dewac_175m_600.ser.gz\n * -testFile ../data/german-ner/deu.testa -inputEncoding iso-8859-1\n */\n public static void main(String[] args) {\n try {\n System.setOut(new PrintStream(System.out, true, \"UTF-8\"));\n System.setErr(new PrintStream(System.err, true, \"UTF-8\"));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n runTest(StringUtils.argsToProperties(args));\n }\n\n static public void runTest(Properties props) {\n TestThreadedCRFClassifier test = new TestThreadedCRFClassifier(props);\n test.runThreadedTest(props);\n }\n\n void runThreadedTest(Properties props) {\n // TODO: check params\n final String testFile = props.getProperty(\"testFile\");\n ArrayList baseResults = new ArrayList<>();\n ArrayList modelNames = new ArrayList<>();\n ArrayList classifiers = new ArrayList<>();\n for (int i = 1; props.getProperty(\"crf\" + Integer.toString(i)) != null; ++i) {\n String model = props.getProperty(\"crf\" + Integer.toString(i));\n CRFClassifier crf = loadClassifier(model, props);\n System.out.println(\"Loaded model \" + model);\n modelNames.add(model);\n classifiers.add(crf);\n String results = runClassifier(crf, testFile);\n // must run twice to account for \"transductive learning\"\n results = runClassifier(crf, testFile);\n baseResults.add(results);\n System.out.println(\"Stored base results for \" + model + \"; length \" + results.length());\n }\n // test to make sure loading and running multiple classifiers\n // hasn't messed with previous results\n for (int i = 0; i < classifiers.size(); ++i) {\n CRFClassifier crf = classifiers.get(i);\n String model = modelNames.get(i);\n String base = baseResults.get(i);\n String repeated = runClassifier(crf, testFile);\n if (!base.equals(repeated)) {\n throw new RuntimeException(\"Repeated unthreaded results \" + \"not the same for \" + model + \" run on file \" + testFile);\n }\n }\n // test the first classifier in several simultaneous threads\n int numThreads = PropertiesUtils.getInt(props, \"simThreads\", DEFAULT_SIM_THREADS);\n ArrayList threads = new ArrayList<>();\n for (int i = 0; i < numThreads; ++i) {\n threads.add(new CRFThread(classifiers.get(0), testFile, \"Simultaneous-\" + i));\n }\n for (int i = 0; i < numThreads; ++i) {\n threads.get(i).start();\n }\n for (int i = 0; i < numThreads; ++i) {\n ", "post_mask_code": "\n if (baseResults.get(0).equals(threads.get(i).getResultsString())) {\n System.out.println(\"Yay!\");\n } else {\n throw new RuntimeException(\"Results not equal when running \" + modelNames.get(0) + \" under \" + numThreads + \" simultaneous threads\");\n }\n }\n // test multiple classifiers (if given) in multiple threads each\n if (classifiers.size() > 1) {\n numThreads = PropertiesUtils.getInt(props, \"multipleThreads\", DEFAULT_MULTIPLE_THREADS);\n threads = new ArrayList();\n for (int i = 0; i < numThreads * classifiers.size(); ++i) {\n int classifierNum = i % classifiers.size();\n int repeatNum = i / classifiers.size();\n threads.add(new CRFThread(classifiers.get(classifierNum), testFile, (\"Simultaneous-\" + classifierNum + \"-\" + repeatNum)));\n }\n for (CRFThread thread : threads) {\n thread.start();\n }\n for (int i = 0; i < threads.size(); ++i) {\n int classifierNum = i % classifiers.size();\n int repeatNum = i / classifiers.size();\n try {\n threads.get(i).join();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n String base = baseResults.get(classifierNum);\n String threadResults = threads.get(i).getResultsString();\n if (base.equals(threadResults)) {\n System.out.println(\"Yay!\");\n } else {\n throw new RuntimeException(\"Results not equal when running \" + modelNames.get(classifierNum) + \" under \" + numThreads + \" threads with \" + classifiers.size() + \" total classifiers\");\n }\n }\n }\n // if no exceptions thrown, great success\n System.out.println(\"Everything worked!\");\n }\n}\n"} {"task_id": "Java_2549", "language": "Java", "task_type": "method_signature", "source_file": "java/github/journaldev/journaldev/CoreJavaProjects/CoreJavaExamples/src/com/journaldev/array/StringToStringArray.java", "mask_start_position": 176, "mask_end_position": 215, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "package com.journaldev.array;\n\npublic class StringToStringArray {\n\n /**\n * This class shows how to convert String to String Array in java\n * @param args\n */\n ", "post_mask_code": "{\n }\n}\n"} {"task_id": "Java_2550", "language": "Java", "task_type": "method_body", "source_file": "java/github/journaldev/journaldev/CoreJavaProjects/CoreJavaExamples/src/com/journaldev/array/StringToStringArray.java", "mask_start_position": 215, "mask_end_position": 222, "canonical_solution": "{\n }", "pre_mask_code": "package com.journaldev.array;\n\npublic class StringToStringArray {\n\n /**\n * This class shows how to convert String to String Array in java\n * @param args\n */\n public static void main(String[] args) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2551", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/journaldev/journaldev/CoreJavaProjects/CoreJavaExamples/src/com/journaldev/array/StringToStringArray.java", "mask_start_position": 176, "mask_end_position": 222, "canonical_solution": "public static void main(String[] args) {\n }", "pre_mask_code": "package com.journaldev.array;\n\npublic class StringToStringArray {\n\n /**\n * This class shows how to convert String to String Array in java\n * @param args\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2552", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Anuken/Arc/arc-core/src/arc/math/FloatCounter.java", "mask_start_position": 1782, "mask_end_position": 1802, "canonical_solution": "public void reset() ", "pre_mask_code": "package arc.math;\n\n/**\n * Track properties of a stream of float values. The properties (total value, minimum, etc) are updated as values are\n * {@link #put(float)} into the stream.\n * @author xoppa\n */\npublic class FloatCounter {\n\n /**\n * Provides access to the WindowedMean if any (can be null)\n */\n public final WindowedMean mean;\n\n /**\n * The amount of values added\n */\n public int count;\n\n /**\n * The sum of all values\n */\n public float total;\n\n /**\n * The smallest value\n */\n public float min;\n\n /**\n * The largest value\n */\n public float max;\n\n /**\n * The average value (total / count)\n */\n public float average;\n\n /**\n * The latest raw value\n */\n public float latest;\n\n /**\n * The current windowed mean value\n */\n public float value;\n\n /**\n * Construct a new FloatCounter\n * @param windowSize The size of the mean window or 1 or below to not use a windowed mean.\n */\n public FloatCounter(int windowSize) {\n mean = (windowSize > 1) ? new WindowedMean(windowSize) : null;\n reset();\n }\n\n /**\n * Add a value and update all fields.\n * @param value The value to add\n */\n public void put(float value) {\n latest = value;\n total += value;\n count++;\n average = total / count;\n if (mean != null) {\n mean.add(value);\n this.value = mean.mean();\n } else\n this.value = latest;\n if (mean == null || mean.hasEnoughData()) {\n if (this.value < min)\n min = this.value;\n if (this.value > max)\n max = this.value;\n }\n }\n\n /**\n * Reset all values to their default value.\n */\n ", "post_mask_code": "{\n count = 0;\n total = 0f;\n min = Float.MAX_VALUE;\n max = Float.MIN_VALUE;\n average = 0f;\n latest = 0f;\n value = 0f;\n if (mean != null)\n mean.clear();\n }\n}\n"} {"task_id": "Java_2553", "language": "Java", "task_type": "method_body", "source_file": "java/github/Anuken/Arc/arc-core/src/arc/math/FloatCounter.java", "mask_start_position": 1266, "mask_end_position": 1712, "canonical_solution": "{\n latest = value;\n total += value;\n count++;\n average = total / count;\n if (mean != null) {\n mean.add(value);\n this.value = mean.mean();\n } else\n this.value = latest;\n if (mean == null || mean.hasEnoughData()) {\n if (this.value < min)\n min = this.value;\n if (this.value > max)\n max = this.value;\n }\n }", "pre_mask_code": "package arc.math;\n\n/**\n * Track properties of a stream of float values. The properties (total value, minimum, etc) are updated as values are\n * {@link #put(float)} into the stream.\n * @author xoppa\n */\npublic class FloatCounter {\n\n /**\n * Provides access to the WindowedMean if any (can be null)\n */\n public final WindowedMean mean;\n\n /**\n * The amount of values added\n */\n public int count;\n\n /**\n * The sum of all values\n */\n public float total;\n\n /**\n * The smallest value\n */\n public float min;\n\n /**\n * The largest value\n */\n public float max;\n\n /**\n * The average value (total / count)\n */\n public float average;\n\n /**\n * The latest raw value\n */\n public float latest;\n\n /**\n * The current windowed mean value\n */\n public float value;\n\n /**\n * Construct a new FloatCounter\n * @param windowSize The size of the mean window or 1 or below to not use a windowed mean.\n */\n public FloatCounter(int windowSize) {\n mean = (windowSize > 1) ? new WindowedMean(windowSize) : null;\n reset();\n }\n\n /**\n * Add a value and update all fields.\n * @param value The value to add\n */\n public void put(float value) ", "post_mask_code": "\n\n /**\n * Reset all values to their default value.\n */\n public void reset() {\n count = 0;\n total = 0f;\n min = Float.MAX_VALUE;\n max = Float.MIN_VALUE;\n average = 0f;\n latest = 0f;\n value = 0f;\n if (mean != null)\n mean.clear();\n }\n}\n"} {"task_id": "Java_2554", "language": "Java", "task_type": "single_line", "source_file": "java/github/Anuken/Arc/arc-core/src/arc/math/FloatCounter.java", "mask_start_position": 1925, "mask_end_position": 1926, "canonical_solution": ";", "pre_mask_code": "package arc.math;\n\n/**\n * Track properties of a stream of float values. The properties (total value, minimum, etc) are updated as values are\n * {@link #put(float)} into the stream.\n * @author xoppa\n */\npublic class FloatCounter {\n\n /**\n * Provides access to the WindowedMean if any (can be null)\n */\n public final WindowedMean mean;\n\n /**\n * The amount of values added\n */\n public int count;\n\n /**\n * The sum of all values\n */\n public float total;\n\n /**\n * The smallest value\n */\n public float min;\n\n /**\n * The largest value\n */\n public float max;\n\n /**\n * The average value (total / count)\n */\n public float average;\n\n /**\n * The latest raw value\n */\n public float latest;\n\n /**\n * The current windowed mean value\n */\n public float value;\n\n /**\n * Construct a new FloatCounter\n * @param windowSize The size of the mean window or 1 or below to not use a windowed mean.\n */\n public FloatCounter(int windowSize) {\n mean = (windowSize > 1) ? new WindowedMean(windowSize) : null;\n reset();\n }\n\n /**\n * Add a value and update all fields.\n * @param value The value to add\n */\n public void put(float value) {\n latest = value;\n total += value;\n count++;\n average = total / count;\n if (mean != null) {\n mean.add(value);\n this.value = mean.mean();\n } else\n this.value = latest;\n if (mean == null || mean.hasEnoughData()) {\n if (this.value < min)\n min = this.value;\n if (this.value > max)\n max = this.value;\n }\n }\n\n /**\n * Reset all values to their default value.\n */\n public void reset() {\n count = 0;\n total = 0f;\n min = Float.MAX_VALUE;\n max = Float.MIN_VALUE;\n average = 0f", "post_mask_code": "\n latest = 0f;\n value = 0f;\n if (mean != null)\n mean.clear();\n }\n}\n"} {"task_id": "Java_2555", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Anuken/Arc/arc-core/src/arc/math/FloatCounter.java", "mask_start_position": 1237, "mask_end_position": 1712, "canonical_solution": "public void put(float value) {\n latest = value;\n total += value;\n count++;\n average = total / count;\n if (mean != null) {\n mean.add(value);\n this.value = mean.mean();\n } else\n this.value = latest;\n if (mean == null || mean.hasEnoughData()) {\n if (this.value < min)\n min = this.value;\n if (this.value > max)\n max = this.value;\n }\n }", "pre_mask_code": "package arc.math;\n\n/**\n * Track properties of a stream of float values. The properties (total value, minimum, etc) are updated as values are\n * {@link #put(float)} into the stream.\n * @author xoppa\n */\npublic class FloatCounter {\n\n /**\n * Provides access to the WindowedMean if any (can be null)\n */\n public final WindowedMean mean;\n\n /**\n * The amount of values added\n */\n public int count;\n\n /**\n * The sum of all values\n */\n public float total;\n\n /**\n * The smallest value\n */\n public float min;\n\n /**\n * The largest value\n */\n public float max;\n\n /**\n * The average value (total / count)\n */\n public float average;\n\n /**\n * The latest raw value\n */\n public float latest;\n\n /**\n * The current windowed mean value\n */\n public float value;\n\n /**\n * Construct a new FloatCounter\n * @param windowSize The size of the mean window or 1 or below to not use a windowed mean.\n */\n public FloatCounter(int windowSize) {\n mean = (windowSize > 1) ? new WindowedMean(windowSize) : null;\n reset();\n }\n\n /**\n * Add a value and update all fields.\n * @param value The value to add\n */\n ", "post_mask_code": "\n\n /**\n * Reset all values to their default value.\n */\n public void reset() {\n count = 0;\n total = 0f;\n min = Float.MAX_VALUE;\n max = Float.MIN_VALUE;\n average = 0f;\n latest = 0f;\n value = 0f;\n if (mean != null)\n mean.clear();\n }\n}\n"} {"task_id": "Java_2556", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse/xtext-eclipse/org.eclipse.xtext.ui/src/org/eclipse/xtext/ui/editor/hover/html/XtextBrowserInformationControlInput.java", "mask_start_position": 1924, "mask_end_position": 1962, "canonical_solution": "@Override\n public String getHtml() ", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * Christoph Kulla - Initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.xtext.ui.editor.hover.html;\n\nimport org.eclipse.core.runtime.Assert;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.jface.internal.text.html.BrowserInformationControlInput;\nimport org.eclipse.jface.viewers.ILabelProvider;\n\n// Clone from JavadocBrowserInformationControlInput. Following changes have been made:\n// - Changed type of fElement from IJavaElement to EObject.\n// - Removed fLeadingImageWidth, leading images are not yet supported by the XtextHtmlHover\n// - getInputName requires an labelProvider to retrieve the EObjects name.\npublic class XtextBrowserInformationControlInput extends BrowserInformationControlInput {\n\n private final EObject fElement;\n\n private final String fHtml;\n\n private final ILabelProvider fLabelProvider;\n\n /**\n * Creates a new browser information control input.\n *\n * @param previous\n * previous input, or null if none available\n * @param element\n * the element, or null if none available\n * @param html\n * HTML contents, must not be null\n * @param labelProvider\n * used to determinate the input name {@link #getInputName()}.\n */\n public XtextBrowserInformationControlInput(XtextBrowserInformationControlInput previous, EObject element, String html, ILabelProvider labelProvider) {\n super(previous);\n Assert.isNotNull(html);\n fElement = element;\n fHtml = html;\n fLabelProvider = labelProvider;\n }\n\n @Override\n public int getLeadingImageWidth() {\n return 16;\n }\n\n public EObject getElement() {\n return fElement;\n }\n\n ", "post_mask_code": "{\n return fHtml;\n }\n\n @Override\n public Object getInputElement() {\n return fElement;\n }\n\n @Override\n public String getInputName() {\n if (fLabelProvider == null)\n return \"no label provider\";\n return fLabelProvider.getText(fElement);\n }\n}\n"} {"task_id": "Java_2557", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse/xtext-eclipse/org.eclipse.xtext.ui/src/org/eclipse/xtext/ui/editor/hover/html/XtextBrowserInformationControlInput.java", "mask_start_position": 1826, "mask_end_position": 1852, "canonical_solution": "{\n return 16;\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * Christoph Kulla - Initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.xtext.ui.editor.hover.html;\n\nimport org.eclipse.core.runtime.Assert;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.jface.internal.text.html.BrowserInformationControlInput;\nimport org.eclipse.jface.viewers.ILabelProvider;\n\n// Clone from JavadocBrowserInformationControlInput. Following changes have been made:\n// - Changed type of fElement from IJavaElement to EObject.\n// - Removed fLeadingImageWidth, leading images are not yet supported by the XtextHtmlHover\n// - getInputName requires an labelProvider to retrieve the EObjects name.\npublic class XtextBrowserInformationControlInput extends BrowserInformationControlInput {\n\n private final EObject fElement;\n\n private final String fHtml;\n\n private final ILabelProvider fLabelProvider;\n\n /**\n * Creates a new browser information control input.\n *\n * @param previous\n * previous input, or null if none available\n * @param element\n * the element, or null if none available\n * @param html\n * HTML contents, must not be null\n * @param labelProvider\n * used to determinate the input name {@link #getInputName()}.\n */\n public XtextBrowserInformationControlInput(XtextBrowserInformationControlInput previous, EObject element, String html, ILabelProvider labelProvider) {\n super(previous);\n Assert.isNotNull(html);\n fElement = element;\n fHtml = html;\n fLabelProvider = labelProvider;\n }\n\n @Override\n public int getLeadingImageWidth() ", "post_mask_code": "\n\n public EObject getElement() {\n return fElement;\n }\n\n @Override\n public String getHtml() {\n return fHtml;\n }\n\n @Override\n public Object getInputElement() {\n return fElement;\n }\n\n @Override\n public String getInputName() {\n if (fLabelProvider == null)\n return \"no label provider\";\n return fLabelProvider.getText(fElement);\n }\n}\n"} {"task_id": "Java_2558", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse/xtext-eclipse/org.eclipse.xtext.ui/src/org/eclipse/xtext/ui/editor/hover/html/XtextBrowserInformationControlInput.java", "mask_start_position": 2061, "mask_end_position": 2069, "canonical_solution": "Element;", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * Christoph Kulla - Initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.xtext.ui.editor.hover.html;\n\nimport org.eclipse.core.runtime.Assert;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.jface.internal.text.html.BrowserInformationControlInput;\nimport org.eclipse.jface.viewers.ILabelProvider;\n\n// Clone from JavadocBrowserInformationControlInput. Following changes have been made:\n// - Changed type of fElement from IJavaElement to EObject.\n// - Removed fLeadingImageWidth, leading images are not yet supported by the XtextHtmlHover\n// - getInputName requires an labelProvider to retrieve the EObjects name.\npublic class XtextBrowserInformationControlInput extends BrowserInformationControlInput {\n\n private final EObject fElement;\n\n private final String fHtml;\n\n private final ILabelProvider fLabelProvider;\n\n /**\n * Creates a new browser information control input.\n *\n * @param previous\n * previous input, or null if none available\n * @param element\n * the element, or null if none available\n * @param html\n * HTML contents, must not be null\n * @param labelProvider\n * used to determinate the input name {@link #getInputName()}.\n */\n public XtextBrowserInformationControlInput(XtextBrowserInformationControlInput previous, EObject element, String html, ILabelProvider labelProvider) {\n super(previous);\n Assert.isNotNull(html);\n fElement = element;\n fHtml = html;\n fLabelProvider = labelProvider;\n }\n\n @Override\n public int getLeadingImageWidth() {\n return 16;\n }\n\n public EObject getElement() {\n return fElement;\n }\n\n @Override\n public String getHtml() {\n return fHtml;\n }\n\n @Override\n public Object getInputElement() {\n return f", "post_mask_code": "\n }\n\n @Override\n public String getInputName() {\n if (fLabelProvider == null)\n return \"no label provider\";\n return fLabelProvider.getText(fElement);\n }\n}\n"} {"task_id": "Java_2559", "language": "Java", "task_type": "method_signature", "source_file": "java/github/liferay/liferay-portal/modules/apps/object/object-rest-impl/src/main/java/com/liferay/object/rest/internal/jaxrs/exception/mapper/RequiredObjectRelationshipExceptionMapper.java", "mask_start_position": 515, "mask_end_position": 631, "canonical_solution": "@Override\n protected Problem getProblem(RequiredObjectRelationshipException requiredObjectRelationshipException) ", "pre_mask_code": "package com.liferay.object.rest.internal.jaxrs.exception.mapper;\n\nimport com.liferay.object.exception.RequiredObjectRelationshipException;\nimport com.liferay.portal.vulcan.jaxrs.exception.mapper.BaseExceptionMapper;\nimport com.liferay.portal.vulcan.jaxrs.exception.mapper.Problem;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.ext.Provider;\n\n/**\n * @author Marco Leo\n */\n@Provider\npublic class RequiredObjectRelationshipExceptionMapper extends BaseExceptionMapper {\n\n ", "post_mask_code": "{\n return new Problem(Response.Status.BAD_REQUEST, requiredObjectRelationshipException.getMessage());\n }\n}\n"} {"task_id": "Java_2560", "language": "Java", "task_type": "method_body", "source_file": "java/github/liferay/liferay-portal/modules/apps/object/object-rest-impl/src/main/java/com/liferay/object/rest/internal/jaxrs/exception/mapper/RequiredObjectRelationshipExceptionMapper.java", "mask_start_position": 631, "mask_end_position": 745, "canonical_solution": "{\n return new Problem(Response.Status.BAD_REQUEST, requiredObjectRelationshipException.getMessage());\n }", "pre_mask_code": "package com.liferay.object.rest.internal.jaxrs.exception.mapper;\n\nimport com.liferay.object.exception.RequiredObjectRelationshipException;\nimport com.liferay.portal.vulcan.jaxrs.exception.mapper.BaseExceptionMapper;\nimport com.liferay.portal.vulcan.jaxrs.exception.mapper.Problem;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.ext.Provider;\n\n/**\n * @author Marco Leo\n */\n@Provider\npublic class RequiredObjectRelationshipExceptionMapper extends BaseExceptionMapper {\n\n @Override\n protected Problem getProblem(RequiredObjectRelationshipException requiredObjectRelationshipException) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2561", "language": "Java", "task_type": "single_line", "source_file": "java/github/liferay/liferay-portal/modules/apps/object/object-rest-impl/src/main/java/com/liferay/object/rest/internal/jaxrs/exception/mapper/RequiredObjectRelationshipExceptionMapper.java", "mask_start_position": 691, "mask_end_position": 739, "canonical_solution": "quiredObjectRelationshipException.getMessage());", "pre_mask_code": "package com.liferay.object.rest.internal.jaxrs.exception.mapper;\n\nimport com.liferay.object.exception.RequiredObjectRelationshipException;\nimport com.liferay.portal.vulcan.jaxrs.exception.mapper.BaseExceptionMapper;\nimport com.liferay.portal.vulcan.jaxrs.exception.mapper.Problem;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.ext.Provider;\n\n/**\n * @author Marco Leo\n */\n@Provider\npublic class RequiredObjectRelationshipExceptionMapper extends BaseExceptionMapper {\n\n @Override\n protected Problem getProblem(RequiredObjectRelationshipException requiredObjectRelationshipException) {\n return new Problem(Response.Status.BAD_REQUEST, re", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2562", "language": "Java", "task_type": "method_signature", "source_file": "java/github/idempiere/idempiere/org.adempiere.base.process/src/org/compiere/process/LoadBankStatement.java", "mask_start_position": 2665, "mask_end_position": 2716, "canonical_solution": "protected String doIt() throws java.lang.Exception ", "pre_mask_code": "/**\n * ***************************************************************************\n * Product: Adempiere ERP & CRM Smart Business Solution *\n * For the text or an alternative of this public license, you may reach us *\n * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *\n * or via example@nnthink.com or http://example.com *\n * ***************************************************************************\n */\npackage org.compiere.process;\n\nimport java.math.BigDecimal;\nimport java.util.Properties;\nimport java.util.logging.Level;\nimport org.compiere.model.MBankStatementLoader;\nimport org.compiere.util.Env;\n\n/**\n * \tProcess for loading Bank Statements into I_BankStatement\n *\n * \t@author Maarten Klinker, Eldir Tomassen\n * \t@version $Id: LoadBankStatement.java,v 1.2 2006/07/30 00:51:01 jjanke Exp $\n */\n@org.adempiere.base.annotation.Process\npublic class LoadBankStatement extends SvrProcess {\n\n public LoadBankStatement() {\n super();\n log.info(\"LoadBankStatement\");\n }\n\n // LoadBankStatement\n /**\n * \tClient to be imported to\n */\n private int m_AD_Client_ID = 0;\n\n /**\n * Organization to be imported to\n */\n private int m_AD_Org_ID = 0;\n\n /**\n * Ban Statement Loader\n */\n private int m_C_BankStmtLoader_ID = 0;\n\n /**\n * File to be imported\n */\n private String fileName = \"\";\n\n /**\n * Current context\n */\n private Properties m_ctx;\n\n /**\n * Current context\n */\n private MBankStatementLoader m_controller = null;\n\n protected void prepare() {\n log.info(\"\");\n m_ctx = Env.getCtx();\n ProcessInfoParameter[] para = getParameter();\n for (int i = 0; i < para.length; i++) {\n String name = para[i].getParameterName();\n if (name.equals(\"C_BankStatementLoader_ID\"))\n m_C_BankStmtLoader_ID = ((BigDecimal) para[i].getParameter()).intValue();\n else if (name.equals(\"FileName\"))\n fileName = (String) para[i].getParameter();\n else\n log.log(Level.SEVERE, \"Unknown Parameter: \" + name);\n }\n m_AD_Client_ID = Env.getAD_Client_ID(m_ctx);\n if (log.isLoggable(Level.INFO))\n log.info(\"AD_Client_ID=\" + m_AD_Client_ID);\n m_AD_Org_ID = Env.getAD_Org_ID(m_ctx);\n if (log.isLoggable(Level.INFO)) {\n log.info(\"AD_Org_ID=\" + m_AD_Org_ID);\n log.info(\"C_BankStatementLoader_ID=\" + m_C_BankStmtLoader_ID);\n }\n }\n\n // prepare\n /**\n * Perform process.\n * @return Message\n * @throws Exception\n */\n ", "post_mask_code": "{\n log.info(\"LoadBankStatement.doIt\");\n String message = \"@Error@\";\n m_controller = new MBankStatementLoader(m_ctx, m_C_BankStmtLoader_ID, fileName, get_TrxName());\n if (log.isLoggable(Level.INFO))\n log.info(m_controller.toString());\n if (m_controller == null || m_controller.get_ID() == 0)\n log.log(Level.SEVERE, \"Invalid Loader\");\n else // Start loading bank statement lines\n if (!m_controller.loadLines()) {\n message += m_controller.getErrorMessage() + \" - \" + m_controller.getErrorDescription();\n log.log(Level.SEVERE, m_controller.getErrorMessage() + \" - \" + m_controller.getErrorDescription());\n } else {\n if (log.isLoggable(Level.INFO))\n log.info(\"Imported=\" + m_controller.getLoadCount());\n addLog(0, null, new BigDecimal(m_controller.getLoadCount()), \"@Loaded@\");\n message = \"@OK@\";\n }\n return message;\n }\n}\n// LoadBankStatement\n"} {"task_id": "Java_2563", "language": "Java", "task_type": "single_line", "source_file": "java/github/idempiere/idempiere/org.adempiere.base.process/src/org/compiere/process/LoadBankStatement.java", "mask_start_position": 2843, "mask_end_position": 2901, "canonical_solution": "er(m_ctx, m_C_BankStmtLoader_ID, fileName, get_TrxName());", "pre_mask_code": "/**\n * ***************************************************************************\n * Product: Adempiere ERP & CRM Smart Business Solution *\n * For the text or an alternative of this public license, you may reach us *\n * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *\n * or via example@nnthink.com or http://example.com *\n * ***************************************************************************\n */\npackage org.compiere.process;\n\nimport java.math.BigDecimal;\nimport java.util.Properties;\nimport java.util.logging.Level;\nimport org.compiere.model.MBankStatementLoader;\nimport org.compiere.util.Env;\n\n/**\n * \tProcess for loading Bank Statements into I_BankStatement\n *\n * \t@author Maarten Klinker, Eldir Tomassen\n * \t@version $Id: LoadBankStatement.java,v 1.2 2006/07/30 00:51:01 jjanke Exp $\n */\n@org.adempiere.base.annotation.Process\npublic class LoadBankStatement extends SvrProcess {\n\n public LoadBankStatement() {\n super();\n log.info(\"LoadBankStatement\");\n }\n\n // LoadBankStatement\n /**\n * \tClient to be imported to\n */\n private int m_AD_Client_ID = 0;\n\n /**\n * Organization to be imported to\n */\n private int m_AD_Org_ID = 0;\n\n /**\n * Ban Statement Loader\n */\n private int m_C_BankStmtLoader_ID = 0;\n\n /**\n * File to be imported\n */\n private String fileName = \"\";\n\n /**\n * Current context\n */\n private Properties m_ctx;\n\n /**\n * Current context\n */\n private MBankStatementLoader m_controller = null;\n\n protected void prepare() {\n log.info(\"\");\n m_ctx = Env.getCtx();\n ProcessInfoParameter[] para = getParameter();\n for (int i = 0; i < para.length; i++) {\n String name = para[i].getParameterName();\n if (name.equals(\"C_BankStatementLoader_ID\"))\n m_C_BankStmtLoader_ID = ((BigDecimal) para[i].getParameter()).intValue();\n else if (name.equals(\"FileName\"))\n fileName = (String) para[i].getParameter();\n else\n log.log(Level.SEVERE, \"Unknown Parameter: \" + name);\n }\n m_AD_Client_ID = Env.getAD_Client_ID(m_ctx);\n if (log.isLoggable(Level.INFO))\n log.info(\"AD_Client_ID=\" + m_AD_Client_ID);\n m_AD_Org_ID = Env.getAD_Org_ID(m_ctx);\n if (log.isLoggable(Level.INFO)) {\n log.info(\"AD_Org_ID=\" + m_AD_Org_ID);\n log.info(\"C_BankStatementLoader_ID=\" + m_C_BankStmtLoader_ID);\n }\n }\n\n // prepare\n /**\n * Perform process.\n * @return Message\n * @throws Exception\n */\n protected String doIt() throws java.lang.Exception {\n log.info(\"LoadBankStatement.doIt\");\n String message = \"@Error@\";\n m_controller = new MBankStatementLoad", "post_mask_code": "\n if (log.isLoggable(Level.INFO))\n log.info(m_controller.toString());\n if (m_controller == null || m_controller.get_ID() == 0)\n log.log(Level.SEVERE, \"Invalid Loader\");\n else // Start loading bank statement lines\n if (!m_controller.loadLines()) {\n message += m_controller.getErrorMessage() + \" - \" + m_controller.getErrorDescription();\n log.log(Level.SEVERE, m_controller.getErrorMessage() + \" - \" + m_controller.getErrorDescription());\n } else {\n if (log.isLoggable(Level.INFO))\n log.info(\"Imported=\" + m_controller.getLoadCount());\n addLog(0, null, new BigDecimal(m_controller.getLoadCount()), \"@Loaded@\");\n message = \"@OK@\";\n }\n return message;\n }\n}\n// LoadBankStatement\n"} {"task_id": "Java_2564", "language": "Java", "task_type": "for_statement", "source_file": "java/github/idempiere/idempiere/org.adempiere.base.process/src/org/compiere/process/LoadBankStatement.java", "mask_start_position": 1732, "mask_end_position": 2174, "canonical_solution": "for (int i = 0; i < para.length; i++) {\n String name = para[i].getParameterName();\n if (name.equals(\"C_BankStatementLoader_ID\"))\n m_C_BankStmtLoader_ID = ((BigDecimal) para[i].getParameter()).intValue();\n else if (name.equals(\"FileName\"))\n fileName = (String) para[i].getParameter();\n else\n log.log(Level.SEVERE, \"Unknown Parameter: \" + name);\n }", "pre_mask_code": "/**\n * ***************************************************************************\n * Product: Adempiere ERP & CRM Smart Business Solution *\n * For the text or an alternative of this public license, you may reach us *\n * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *\n * or via example@nnthink.com or http://example.com *\n * ***************************************************************************\n */\npackage org.compiere.process;\n\nimport java.math.BigDecimal;\nimport java.util.Properties;\nimport java.util.logging.Level;\nimport org.compiere.model.MBankStatementLoader;\nimport org.compiere.util.Env;\n\n/**\n * \tProcess for loading Bank Statements into I_BankStatement\n *\n * \t@author Maarten Klinker, Eldir Tomassen\n * \t@version $Id: LoadBankStatement.java,v 1.2 2006/07/30 00:51:01 jjanke Exp $\n */\n@org.adempiere.base.annotation.Process\npublic class LoadBankStatement extends SvrProcess {\n\n public LoadBankStatement() {\n super();\n log.info(\"LoadBankStatement\");\n }\n\n // LoadBankStatement\n /**\n * \tClient to be imported to\n */\n private int m_AD_Client_ID = 0;\n\n /**\n * Organization to be imported to\n */\n private int m_AD_Org_ID = 0;\n\n /**\n * Ban Statement Loader\n */\n private int m_C_BankStmtLoader_ID = 0;\n\n /**\n * File to be imported\n */\n private String fileName = \"\";\n\n /**\n * Current context\n */\n private Properties m_ctx;\n\n /**\n * Current context\n */\n private MBankStatementLoader m_controller = null;\n\n protected void prepare() {\n log.info(\"\");\n m_ctx = Env.getCtx();\n ProcessInfoParameter[] para = getParameter();\n ", "post_mask_code": "\n m_AD_Client_ID = Env.getAD_Client_ID(m_ctx);\n if (log.isLoggable(Level.INFO))\n log.info(\"AD_Client_ID=\" + m_AD_Client_ID);\n m_AD_Org_ID = Env.getAD_Org_ID(m_ctx);\n if (log.isLoggable(Level.INFO)) {\n log.info(\"AD_Org_ID=\" + m_AD_Org_ID);\n log.info(\"C_BankStatementLoader_ID=\" + m_C_BankStmtLoader_ID);\n }\n }\n\n // prepare\n /**\n * Perform process.\n * @return Message\n * @throws Exception\n */\n protected String doIt() throws java.lang.Exception {\n log.info(\"LoadBankStatement.doIt\");\n String message = \"@Error@\";\n m_controller = new MBankStatementLoader(m_ctx, m_C_BankStmtLoader_ID, fileName, get_TrxName());\n if (log.isLoggable(Level.INFO))\n log.info(m_controller.toString());\n if (m_controller == null || m_controller.get_ID() == 0)\n log.log(Level.SEVERE, \"Invalid Loader\");\n else // Start loading bank statement lines\n if (!m_controller.loadLines()) {\n message += m_controller.getErrorMessage() + \" - \" + m_controller.getErrorDescription();\n log.log(Level.SEVERE, m_controller.getErrorMessage() + \" - \" + m_controller.getErrorDescription());\n } else {\n if (log.isLoggable(Level.INFO))\n log.info(\"Imported=\" + m_controller.getLoadCount());\n addLog(0, null, new BigDecimal(m_controller.getLoadCount()), \"@Loaded@\");\n message = \"@OK@\";\n }\n return message;\n }\n}\n// LoadBankStatement\n"} {"task_id": "Java_2565", "language": "Java", "task_type": "method_signature", "source_file": "java/github/experdb/eXperDB-Management/eXperDB-Management-Agent/src/main/java/com/k4m/dx/tcontrol/monitoring/schedule/util/lang/TextValue.java", "mask_start_position": 1041, "mask_end_position": 1066, "canonical_solution": "public String toString() ", "pre_mask_code": "package com.k4m.dx.tcontrol.monitoring.schedule.util.lang;\n\npublic class TextValue implements Value, Comparable {\n\n public String value;\n\n public TextValue() {\n }\n\n public TextValue(String value) {\n this.value = (value == null ? \"\" : value);\n }\n\n public int compareTo(Object o) {\n if (o instanceof TextValue) {\n if (this.value == null) {\n return ((TextValue) o).value == null ? 0 : -1;\n }\n return this.value.compareTo(((TextValue) o).value);\n }\n return 1;\n }\n\n public boolean equals(Object o) {\n if (o instanceof TextValue) {\n if (this.value == null) {\n return ((TextValue) o).value == null;\n }\n return this.value.equals(((TextValue) o).value);\n }\n return false;\n }\n\n public int hashCode() {\n if (this.value == null)\n return 0;\n return this.value.hashCode();\n }\n\n public byte getValueType() {\n return ValueEnum.TEXT;\n }\n\n ", "post_mask_code": "{\n return value;\n }\n\n public Object toJavaObject() {\n return this.value;\n }\n}\n"} {"task_id": "Java_2566", "language": "Java", "task_type": "method_body", "source_file": "java/github/experdb/eXperDB-Management/eXperDB-Management-Agent/src/main/java/com/k4m/dx/tcontrol/monitoring/schedule/util/lang/TextValue.java", "mask_start_position": 865, "mask_end_position": 964, "canonical_solution": "{\n if (this.value == null)\n return 0;\n return this.value.hashCode();\n }", "pre_mask_code": "package com.k4m.dx.tcontrol.monitoring.schedule.util.lang;\n\npublic class TextValue implements Value, Comparable {\n\n public String value;\n\n public TextValue() {\n }\n\n public TextValue(String value) {\n this.value = (value == null ? \"\" : value);\n }\n\n public int compareTo(Object o) {\n if (o instanceof TextValue) {\n if (this.value == null) {\n return ((TextValue) o).value == null ? 0 : -1;\n }\n return this.value.compareTo(((TextValue) o).value);\n }\n return 1;\n }\n\n public boolean equals(Object o) {\n if (o instanceof TextValue) {\n if (this.value == null) {\n return ((TextValue) o).value == null;\n }\n return this.value.equals(((TextValue) o).value);\n }\n return false;\n }\n\n public int hashCode() ", "post_mask_code": "\n\n public byte getValueType() {\n return ValueEnum.TEXT;\n }\n\n public String toString() {\n return value;\n }\n\n public Object toJavaObject() {\n return this.value;\n }\n}\n"} {"task_id": "Java_2567", "language": "Java", "task_type": "single_line", "source_file": "java/github/experdb/eXperDB-Management/eXperDB-Management-Agent/src/main/java/com/k4m/dx/tcontrol/monitoring/schedule/util/lang/TextValue.java", "mask_start_position": 1079, "mask_end_position": 1089, "canonical_solution": "urn value;", "pre_mask_code": "package com.k4m.dx.tcontrol.monitoring.schedule.util.lang;\n\npublic class TextValue implements Value, Comparable {\n\n public String value;\n\n public TextValue() {\n }\n\n public TextValue(String value) {\n this.value = (value == null ? \"\" : value);\n }\n\n public int compareTo(Object o) {\n if (o instanceof TextValue) {\n if (this.value == null) {\n return ((TextValue) o).value == null ? 0 : -1;\n }\n return this.value.compareTo(((TextValue) o).value);\n }\n return 1;\n }\n\n public boolean equals(Object o) {\n if (o instanceof TextValue) {\n if (this.value == null) {\n return ((TextValue) o).value == null;\n }\n return this.value.equals(((TextValue) o).value);\n }\n return false;\n }\n\n public int hashCode() {\n if (this.value == null)\n return 0;\n return this.value.hashCode();\n }\n\n public byte getValueType() {\n return ValueEnum.TEXT;\n }\n\n public String toString() {\n ret", "post_mask_code": "\n }\n\n public Object toJavaObject() {\n return this.value;\n }\n}\n"} {"task_id": "Java_2568", "language": "Java", "task_type": "method_signature", "source_file": "java/github/HubSpot/Baragon/BaragonCore/src/main/java/com/hubspot/baragon/models/QueuedRequestId.java", "mask_start_position": 1109, "mask_end_position": 1131, "canonical_solution": "public int getIndex() ", "pre_mask_code": "package com.hubspot.baragon.models;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.google.common.base.MoreObjects;\n\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class QueuedRequestId {\n\n private final String serviceId;\n\n private final String requestId;\n\n private final int index;\n\n public static QueuedRequestId fromString(String value) {\n final String[] splits = value.split(\"\\\\|\", 3);\n return new QueuedRequestId(splits[0], splits[1], Integer.parseInt(splits[2]));\n }\n\n @JsonCreator\n public QueuedRequestId(@JsonProperty(\"serviceId\") String serviceId, @JsonProperty(\"requestId\") String requestId, @JsonProperty(\"index\") int index) {\n this.serviceId = serviceId;\n this.requestId = requestId;\n this.index = index;\n }\n\n public String getServiceId() {\n return serviceId;\n }\n\n public String getRequestId() {\n return requestId;\n }\n\n ", "post_mask_code": "{\n return index;\n }\n\n @JsonIgnore\n public String buildZkPath() {\n return String.format(\"%s|%s|%010d\", serviceId, requestId, index);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n QueuedRequestId that = (QueuedRequestId) o;\n if (index != that.index) {\n return false;\n }\n if (serviceId != null ? !serviceId.equals(that.serviceId) : that.serviceId != null) {\n return false;\n }\n return requestId != null ? requestId.equals(that.requestId) : that.requestId == null;\n }\n\n @Override\n public int hashCode() {\n int result = serviceId != null ? serviceId.hashCode() : 0;\n result = 31 * result + (requestId != null ? requestId.hashCode() : 0);\n result = 31 * result + index;\n return result;\n }\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(this).add(\"serviceId\", serviceId).add(\"requestId\", requestId).add(\"index\", index).toString();\n }\n}\n"} {"task_id": "Java_2569", "language": "Java", "task_type": "method_body", "source_file": "java/github/HubSpot/Baragon/BaragonCore/src/main/java/com/hubspot/baragon/models/QueuedRequestId.java", "mask_start_position": 2149, "mask_end_position": 2292, "canonical_solution": "{\n return MoreObjects.toStringHelper(this).add(\"serviceId\", serviceId).add(\"requestId\", requestId).add(\"index\", index).toString();\n }", "pre_mask_code": "package com.hubspot.baragon.models;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.google.common.base.MoreObjects;\n\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class QueuedRequestId {\n\n private final String serviceId;\n\n private final String requestId;\n\n private final int index;\n\n public static QueuedRequestId fromString(String value) {\n final String[] splits = value.split(\"\\\\|\", 3);\n return new QueuedRequestId(splits[0], splits[1], Integer.parseInt(splits[2]));\n }\n\n @JsonCreator\n public QueuedRequestId(@JsonProperty(\"serviceId\") String serviceId, @JsonProperty(\"requestId\") String requestId, @JsonProperty(\"index\") int index) {\n this.serviceId = serviceId;\n this.requestId = requestId;\n this.index = index;\n }\n\n public String getServiceId() {\n return serviceId;\n }\n\n public String getRequestId() {\n return requestId;\n }\n\n public int getIndex() {\n return index;\n }\n\n @JsonIgnore\n public String buildZkPath() {\n return String.format(\"%s|%s|%010d\", serviceId, requestId, index);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n QueuedRequestId that = (QueuedRequestId) o;\n if (index != that.index) {\n return false;\n }\n if (serviceId != null ? !serviceId.equals(that.serviceId) : that.serviceId != null) {\n return false;\n }\n return requestId != null ? requestId.equals(that.requestId) : that.requestId == null;\n }\n\n @Override\n public int hashCode() {\n int result = serviceId != null ? serviceId.hashCode() : 0;\n result = 31 * result + (requestId != null ? requestId.hashCode() : 0);\n result = 31 * result + index;\n return result;\n }\n\n @Override\n public String toString() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2570", "language": "Java", "task_type": "single_line", "source_file": "java/github/HubSpot/Baragon/BaragonCore/src/main/java/com/hubspot/baragon/models/QueuedRequestId.java", "mask_start_position": 1021, "mask_end_position": 1029, "canonical_solution": "rviceId;", "pre_mask_code": "package com.hubspot.baragon.models;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.google.common.base.MoreObjects;\n\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class QueuedRequestId {\n\n private final String serviceId;\n\n private final String requestId;\n\n private final int index;\n\n public static QueuedRequestId fromString(String value) {\n final String[] splits = value.split(\"\\\\|\", 3);\n return new QueuedRequestId(splits[0], splits[1], Integer.parseInt(splits[2]));\n }\n\n @JsonCreator\n public QueuedRequestId(@JsonProperty(\"serviceId\") String serviceId, @JsonProperty(\"requestId\") String requestId, @JsonProperty(\"index\") int index) {\n this.serviceId = serviceId;\n this.requestId = requestId;\n this.index = index;\n }\n\n public String getServiceId() {\n return se", "post_mask_code": "\n }\n\n public String getRequestId() {\n return requestId;\n }\n\n public int getIndex() {\n return index;\n }\n\n @JsonIgnore\n public String buildZkPath() {\n return String.format(\"%s|%s|%010d\", serviceId, requestId, index);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n QueuedRequestId that = (QueuedRequestId) o;\n if (index != that.index) {\n return false;\n }\n if (serviceId != null ? !serviceId.equals(that.serviceId) : that.serviceId != null) {\n return false;\n }\n return requestId != null ? requestId.equals(that.requestId) : that.requestId == null;\n }\n\n @Override\n public int hashCode() {\n int result = serviceId != null ? serviceId.hashCode() : 0;\n result = 31 * result + (requestId != null ? requestId.hashCode() : 0);\n result = 31 * result + index;\n return result;\n }\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(this).add(\"serviceId\", serviceId).add(\"requestId\", requestId).add(\"index\", index).toString();\n }\n}\n"} {"task_id": "Java_2571", "language": "Java", "task_type": "method_signature", "source_file": "java/github/caveofprogramming/springboot/messagingtest/src/main/java/com/caveofprogramming/service/UserService.java", "mask_start_position": 2475, "mask_end_position": 2524, "canonical_solution": "public void deleteToken(VerificationToken token) ", "pre_mask_code": "package com.caveofprogramming.service;\n\nimport java.util.List;\nimport java.util.UUID;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.GrantedAuthority;\nimport org.springframework.security.core.authority.AuthorityUtils;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.core.userdetails.UsernameNotFoundException;\nimport org.springframework.stereotype.Service;\nimport com.caveofprogramming.model.custom.AccountDataDeleter;\nimport com.caveofprogramming.model.dto.SpringUser;\nimport com.caveofprogramming.model.entity.SiteUser;\nimport com.caveofprogramming.model.entity.TokenType;\nimport com.caveofprogramming.model.entity.VerificationToken;\nimport com.caveofprogramming.model.repository.UserDao;\nimport com.caveofprogramming.model.repository.VerificationDao;\n\n@Service\npublic class UserService implements UserDetailsService {\n\n @Autowired\n private UserDao userDao;\n\n @Autowired\n private AccountDataDeleter dataDeleter;\n\n @Autowired\n private VerificationDao verificationDao;\n\n public void register(SiteUser user) {\n user.setRole(\"ROLE_USER\");\n userDao.save(user);\n }\n\n public void save(SiteUser user) {\n userDao.save(user);\n }\n\n public void deleteAccount(SiteUser user) {\n Long userId = user.getId();\n dataDeleter.deleteUserById(userId);\n }\n\n @Override\n public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {\n SiteUser user = userDao.findByEmail(email);\n if (user == null) {\n // TODO: BUG FIX.\n throw new UsernameNotFoundException(\"User not found\");\n }\n List auth = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRole());\n String password = user.getPassword();\n Boolean enabled = user.getEnabled();\n return new SpringUser(user.getFirstname(), email, password, enabled, true, true, true, auth);\n }\n\n public String createEmailVerificationToken(SiteUser user) {\n VerificationToken token = new VerificationToken(UUID.randomUUID().toString(), user, TokenType.REGISTRATION);\n verificationDao.save(token);\n return token.getToken();\n }\n\n public VerificationToken getVerificationToken(String token) {\n return verificationDao.findByToken(token);\n }\n\n ", "post_mask_code": "{\n verificationDao.delete(token);\n }\n\n public SiteUser get(String email) {\n return userDao.findByEmail(email);\n }\n\n public SiteUser get(Long id) {\n return userDao.findById(id).get();\n }\n\n public String getUserName(Long id) {\n SiteUser user = userDao.findById(id).get();\n return user.getFirstname() + \" \" + user.getSurname();\n }\n\n public Iterable getAll() {\n return userDao.findAll();\n }\n}\n"} {"task_id": "Java_2572", "language": "Java", "task_type": "method_body", "source_file": "java/github/caveofprogramming/springboot/messagingtest/src/main/java/com/caveofprogramming/service/UserService.java", "mask_start_position": 2151, "mask_end_position": 2345, "canonical_solution": "{\n VerificationToken token = new VerificationToken(UUID.randomUUID().toString(), user, TokenType.REGISTRATION);\n verificationDao.save(token);\n return token.getToken();\n }", "pre_mask_code": "package com.caveofprogramming.service;\n\nimport java.util.List;\nimport java.util.UUID;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.GrantedAuthority;\nimport org.springframework.security.core.authority.AuthorityUtils;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.core.userdetails.UsernameNotFoundException;\nimport org.springframework.stereotype.Service;\nimport com.caveofprogramming.model.custom.AccountDataDeleter;\nimport com.caveofprogramming.model.dto.SpringUser;\nimport com.caveofprogramming.model.entity.SiteUser;\nimport com.caveofprogramming.model.entity.TokenType;\nimport com.caveofprogramming.model.entity.VerificationToken;\nimport com.caveofprogramming.model.repository.UserDao;\nimport com.caveofprogramming.model.repository.VerificationDao;\n\n@Service\npublic class UserService implements UserDetailsService {\n\n @Autowired\n private UserDao userDao;\n\n @Autowired\n private AccountDataDeleter dataDeleter;\n\n @Autowired\n private VerificationDao verificationDao;\n\n public void register(SiteUser user) {\n user.setRole(\"ROLE_USER\");\n userDao.save(user);\n }\n\n public void save(SiteUser user) {\n userDao.save(user);\n }\n\n public void deleteAccount(SiteUser user) {\n Long userId = user.getId();\n dataDeleter.deleteUserById(userId);\n }\n\n @Override\n public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {\n SiteUser user = userDao.findByEmail(email);\n if (user == null) {\n // TODO: BUG FIX.\n throw new UsernameNotFoundException(\"User not found\");\n }\n List auth = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRole());\n String password = user.getPassword();\n Boolean enabled = user.getEnabled();\n return new SpringUser(user.getFirstname(), email, password, enabled, true, true, true, auth);\n }\n\n public String createEmailVerificationToken(SiteUser user) ", "post_mask_code": "\n\n public VerificationToken getVerificationToken(String token) {\n return verificationDao.findByToken(token);\n }\n\n public void deleteToken(VerificationToken token) {\n verificationDao.delete(token);\n }\n\n public SiteUser get(String email) {\n return userDao.findByEmail(email);\n }\n\n public SiteUser get(Long id) {\n return userDao.findById(id).get();\n }\n\n public String getUserName(Long id) {\n SiteUser user = userDao.findById(id).get();\n return user.getFirstname() + \" \" + user.getSurname();\n }\n\n public Iterable getAll() {\n return userDao.findAll();\n }\n}\n"} {"task_id": "Java_2573", "language": "Java", "task_type": "single_line", "source_file": "java/github/caveofprogramming/springboot/messagingtest/src/main/java/com/caveofprogramming/service/UserService.java", "mask_start_position": 2729, "mask_end_position": 2739, "canonical_solution": "id).get();", "pre_mask_code": "package com.caveofprogramming.service;\n\nimport java.util.List;\nimport java.util.UUID;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.GrantedAuthority;\nimport org.springframework.security.core.authority.AuthorityUtils;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.core.userdetails.UsernameNotFoundException;\nimport org.springframework.stereotype.Service;\nimport com.caveofprogramming.model.custom.AccountDataDeleter;\nimport com.caveofprogramming.model.dto.SpringUser;\nimport com.caveofprogramming.model.entity.SiteUser;\nimport com.caveofprogramming.model.entity.TokenType;\nimport com.caveofprogramming.model.entity.VerificationToken;\nimport com.caveofprogramming.model.repository.UserDao;\nimport com.caveofprogramming.model.repository.VerificationDao;\n\n@Service\npublic class UserService implements UserDetailsService {\n\n @Autowired\n private UserDao userDao;\n\n @Autowired\n private AccountDataDeleter dataDeleter;\n\n @Autowired\n private VerificationDao verificationDao;\n\n public void register(SiteUser user) {\n user.setRole(\"ROLE_USER\");\n userDao.save(user);\n }\n\n public void save(SiteUser user) {\n userDao.save(user);\n }\n\n public void deleteAccount(SiteUser user) {\n Long userId = user.getId();\n dataDeleter.deleteUserById(userId);\n }\n\n @Override\n public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {\n SiteUser user = userDao.findByEmail(email);\n if (user == null) {\n // TODO: BUG FIX.\n throw new UsernameNotFoundException(\"User not found\");\n }\n List auth = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRole());\n String password = user.getPassword();\n Boolean enabled = user.getEnabled();\n return new SpringUser(user.getFirstname(), email, password, enabled, true, true, true, auth);\n }\n\n public String createEmailVerificationToken(SiteUser user) {\n VerificationToken token = new VerificationToken(UUID.randomUUID().toString(), user, TokenType.REGISTRATION);\n verificationDao.save(token);\n return token.getToken();\n }\n\n public VerificationToken getVerificationToken(String token) {\n return verificationDao.findByToken(token);\n }\n\n public void deleteToken(VerificationToken token) {\n verificationDao.delete(token);\n }\n\n public SiteUser get(String email) {\n return userDao.findByEmail(email);\n }\n\n public SiteUser get(Long id) {\n return userDao.findById(", "post_mask_code": "\n }\n\n public String getUserName(Long id) {\n SiteUser user = userDao.findById(id).get();\n return user.getFirstname() + \" \" + user.getSurname();\n }\n\n public Iterable getAll() {\n return userDao.findAll();\n }\n}\n"} {"task_id": "Java_2574", "language": "Java", "task_type": "method_signature", "source_file": "java/github/mapstruct/mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/common/Assignment.java", "mask_start_position": 1246, "mask_end_position": 1272, "canonical_solution": "public boolean isDirect() ", "pre_mask_code": "package org.mapstruct.ap.internal.model.common;\n\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * Assignment represents all kind of manners a source can be assigned to a target.\n *\n * @author Sjaak Derksen\n */\npublic interface Assignment {\n\n enum AssignmentType {\n\n /**\n * assignment is direct\n */\n DIRECT(true, false),\n /**\n * assignment is type converted\n */\n TYPE_CONVERTED(false, true),\n /**\n * assignment is mapped (builtin/custom)\n */\n MAPPED(false, false),\n /**\n * 2 mapping methods (builtin/custom) are applied to get the target\n */\n MAPPED_TWICE(false, false),\n /**\n * assignment is first mapped (builtin/custom), then the result is type converted\n */\n MAPPED_TYPE_CONVERTED(false, true),\n /**\n * assignment is first type converted, and then mapped (builtin/custom)\n */\n TYPE_CONVERTED_MAPPED(false, true);\n\n private final boolean direct;\n\n private final boolean converted;\n\n AssignmentType(boolean isDirect, boolean isConverted) {\n this.direct = isDirect;\n this.converted = isConverted;\n }\n\n ", "post_mask_code": "{\n return direct;\n }\n\n public boolean isConverted() {\n return converted;\n }\n }\n\n /**\n * returns all types required as import by the assignment statement.\n *\n * @return imported types\n */\n Set getImportTypes();\n\n /**\n * returns all types exception types thrown by this assignment.\n *\n * @return exceptions thrown\n */\n List getThrownTypes();\n\n /**\n * An assignment in itself can wrap another assignment. E.g.:\n *

    \n *
  • a MethodReference can wrap a TypeConversion, another MethodReference and ultimately a Simple
  • \n *
  • a TypeConversion can wrap a MethodReference, and ultimately a Simple
  • \n *
\n *\n * @param assignment the assignment to set\n */\n void setAssignment(Assignment assignment);\n\n /**\n * the source reference being a source-getter, a constant, nested method call, etc.\n *\n * @return source reference\n */\n String getSourceReference();\n\n /**\n * @return true when the source reference is the source parameter (and not a property of the source parameter type)\n */\n boolean isSourceReferenceParameter();\n\n /**\n * the source presence checker reference\n *\n * @return source reference\n */\n PresenceCheck getSourcePresenceCheckerReference();\n\n /**\n * the source type used in the matching process\n *\n * @return source type (can be null)\n */\n Type getSourceType();\n\n /**\n * Creates an unique safe (local) variable name.\n *\n * @param desiredName the desired name\n *\n * @return the desired name, made unique in the scope of the bean mapping.\n */\n String createUniqueVarName(String desiredName);\n\n /**\n * See {@link #setSourceLocalVarName(java.lang.String) }\n *\n * @return local variable name (can be null if not set)\n */\n String getSourceLocalVarName();\n\n /**\n * Returns the source parameter name, to which this assignment applies. Note: the source parameter itself might\n * be mapped by this assignment, or one of its properties\n *\n * @return the source parameter name\n */\n String getSourceParameterName();\n\n /**\n * Replaces the sourceReference at the call site in the assignment in the template with this sourceLocalVarName.\n * The sourceLocalVarName can subsequently be used for e.g. null checking.\n *\n * @param sourceLocalVarName source local variable name\n */\n void setSourceLocalVarName(String sourceLocalVarName);\n\n String getSourceLoopVarName();\n\n /**\n * Replaces the sourceLocalVar or sourceReference at the call site in the assignment in the template with this\n * sourceLoopVarName.\n * The sourceLocalVar can subsequently be used for e.g. null checking.\n *\n * @param sourceLoopVarName loop variable\n */\n void setSourceLoopVarName(String sourceLoopVarName);\n\n /**\n * Returns whether the type of assignment\n *\n * @return {@link AssignmentType}\n */\n AssignmentType getType();\n\n boolean isCallingUpdateMethod();\n}\n"} {"task_id": "Java_2575", "language": "Java", "task_type": "method_body", "source_file": "java/github/mapstruct/mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/common/Assignment.java", "mask_start_position": 1272, "mask_end_position": 1310, "canonical_solution": "{\n return direct;\n }", "pre_mask_code": "package org.mapstruct.ap.internal.model.common;\n\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * Assignment represents all kind of manners a source can be assigned to a target.\n *\n * @author Sjaak Derksen\n */\npublic interface Assignment {\n\n enum AssignmentType {\n\n /**\n * assignment is direct\n */\n DIRECT(true, false),\n /**\n * assignment is type converted\n */\n TYPE_CONVERTED(false, true),\n /**\n * assignment is mapped (builtin/custom)\n */\n MAPPED(false, false),\n /**\n * 2 mapping methods (builtin/custom) are applied to get the target\n */\n MAPPED_TWICE(false, false),\n /**\n * assignment is first mapped (builtin/custom), then the result is type converted\n */\n MAPPED_TYPE_CONVERTED(false, true),\n /**\n * assignment is first type converted, and then mapped (builtin/custom)\n */\n TYPE_CONVERTED_MAPPED(false, true);\n\n private final boolean direct;\n\n private final boolean converted;\n\n AssignmentType(boolean isDirect, boolean isConverted) {\n this.direct = isDirect;\n this.converted = isConverted;\n }\n\n public boolean isDirect() ", "post_mask_code": "\n\n public boolean isConverted() {\n return converted;\n }\n }\n\n /**\n * returns all types required as import by the assignment statement.\n *\n * @return imported types\n */\n Set getImportTypes();\n\n /**\n * returns all types exception types thrown by this assignment.\n *\n * @return exceptions thrown\n */\n List getThrownTypes();\n\n /**\n * An assignment in itself can wrap another assignment. E.g.:\n *
    \n *
  • a MethodReference can wrap a TypeConversion, another MethodReference and ultimately a Simple
  • \n *
  • a TypeConversion can wrap a MethodReference, and ultimately a Simple
  • \n *
\n *\n * @param assignment the assignment to set\n */\n void setAssignment(Assignment assignment);\n\n /**\n * the source reference being a source-getter, a constant, nested method call, etc.\n *\n * @return source reference\n */\n String getSourceReference();\n\n /**\n * @return true when the source reference is the source parameter (and not a property of the source parameter type)\n */\n boolean isSourceReferenceParameter();\n\n /**\n * the source presence checker reference\n *\n * @return source reference\n */\n PresenceCheck getSourcePresenceCheckerReference();\n\n /**\n * the source type used in the matching process\n *\n * @return source type (can be null)\n */\n Type getSourceType();\n\n /**\n * Creates an unique safe (local) variable name.\n *\n * @param desiredName the desired name\n *\n * @return the desired name, made unique in the scope of the bean mapping.\n */\n String createUniqueVarName(String desiredName);\n\n /**\n * See {@link #setSourceLocalVarName(java.lang.String) }\n *\n * @return local variable name (can be null if not set)\n */\n String getSourceLocalVarName();\n\n /**\n * Returns the source parameter name, to which this assignment applies. Note: the source parameter itself might\n * be mapped by this assignment, or one of its properties\n *\n * @return the source parameter name\n */\n String getSourceParameterName();\n\n /**\n * Replaces the sourceReference at the call site in the assignment in the template with this sourceLocalVarName.\n * The sourceLocalVarName can subsequently be used for e.g. null checking.\n *\n * @param sourceLocalVarName source local variable name\n */\n void setSourceLocalVarName(String sourceLocalVarName);\n\n String getSourceLoopVarName();\n\n /**\n * Replaces the sourceLocalVar or sourceReference at the call site in the assignment in the template with this\n * sourceLoopVarName.\n * The sourceLocalVar can subsequently be used for e.g. null checking.\n *\n * @param sourceLoopVarName loop variable\n */\n void setSourceLoopVarName(String sourceLoopVarName);\n\n /**\n * Returns whether the type of assignment\n *\n * @return {@link AssignmentType}\n */\n AssignmentType getType();\n\n boolean isCallingUpdateMethod();\n}\n"} {"task_id": "Java_2576", "language": "Java", "task_type": "single_line", "source_file": "java/github/mapstruct/mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/common/Assignment.java", "mask_start_position": 1369, "mask_end_position": 1380, "canonical_solution": " converted;", "pre_mask_code": "package org.mapstruct.ap.internal.model.common;\n\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * Assignment represents all kind of manners a source can be assigned to a target.\n *\n * @author Sjaak Derksen\n */\npublic interface Assignment {\n\n enum AssignmentType {\n\n /**\n * assignment is direct\n */\n DIRECT(true, false),\n /**\n * assignment is type converted\n */\n TYPE_CONVERTED(false, true),\n /**\n * assignment is mapped (builtin/custom)\n */\n MAPPED(false, false),\n /**\n * 2 mapping methods (builtin/custom) are applied to get the target\n */\n MAPPED_TWICE(false, false),\n /**\n * assignment is first mapped (builtin/custom), then the result is type converted\n */\n MAPPED_TYPE_CONVERTED(false, true),\n /**\n * assignment is first type converted, and then mapped (builtin/custom)\n */\n TYPE_CONVERTED_MAPPED(false, true);\n\n private final boolean direct;\n\n private final boolean converted;\n\n AssignmentType(boolean isDirect, boolean isConverted) {\n this.direct = isDirect;\n this.converted = isConverted;\n }\n\n public boolean isDirect() {\n return direct;\n }\n\n public boolean isConverted() {\n return", "post_mask_code": "\n }\n }\n\n /**\n * returns all types required as import by the assignment statement.\n *\n * @return imported types\n */\n Set getImportTypes();\n\n /**\n * returns all types exception types thrown by this assignment.\n *\n * @return exceptions thrown\n */\n List getThrownTypes();\n\n /**\n * An assignment in itself can wrap another assignment. E.g.:\n *
    \n *
  • a MethodReference can wrap a TypeConversion, another MethodReference and ultimately a Simple
  • \n *
  • a TypeConversion can wrap a MethodReference, and ultimately a Simple
  • \n *
\n *\n * @param assignment the assignment to set\n */\n void setAssignment(Assignment assignment);\n\n /**\n * the source reference being a source-getter, a constant, nested method call, etc.\n *\n * @return source reference\n */\n String getSourceReference();\n\n /**\n * @return true when the source reference is the source parameter (and not a property of the source parameter type)\n */\n boolean isSourceReferenceParameter();\n\n /**\n * the source presence checker reference\n *\n * @return source reference\n */\n PresenceCheck getSourcePresenceCheckerReference();\n\n /**\n * the source type used in the matching process\n *\n * @return source type (can be null)\n */\n Type getSourceType();\n\n /**\n * Creates an unique safe (local) variable name.\n *\n * @param desiredName the desired name\n *\n * @return the desired name, made unique in the scope of the bean mapping.\n */\n String createUniqueVarName(String desiredName);\n\n /**\n * See {@link #setSourceLocalVarName(java.lang.String) }\n *\n * @return local variable name (can be null if not set)\n */\n String getSourceLocalVarName();\n\n /**\n * Returns the source parameter name, to which this assignment applies. Note: the source parameter itself might\n * be mapped by this assignment, or one of its properties\n *\n * @return the source parameter name\n */\n String getSourceParameterName();\n\n /**\n * Replaces the sourceReference at the call site in the assignment in the template with this sourceLocalVarName.\n * The sourceLocalVarName can subsequently be used for e.g. null checking.\n *\n * @param sourceLocalVarName source local variable name\n */\n void setSourceLocalVarName(String sourceLocalVarName);\n\n String getSourceLoopVarName();\n\n /**\n * Replaces the sourceLocalVar or sourceReference at the call site in the assignment in the template with this\n * sourceLoopVarName.\n * The sourceLocalVar can subsequently be used for e.g. null checking.\n *\n * @param sourceLoopVarName loop variable\n */\n void setSourceLoopVarName(String sourceLoopVarName);\n\n /**\n * Returns whether the type of assignment\n *\n * @return {@link AssignmentType}\n */\n AssignmentType getType();\n\n boolean isCallingUpdateMethod();\n}\n"} {"task_id": "Java_2577", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/mapstruct/mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/common/Assignment.java", "mask_start_position": 1528, "mask_end_position": 1555, "canonical_solution": "Set getImportTypes();", "pre_mask_code": "package org.mapstruct.ap.internal.model.common;\n\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * Assignment represents all kind of manners a source can be assigned to a target.\n *\n * @author Sjaak Derksen\n */\npublic interface Assignment {\n\n enum AssignmentType {\n\n /**\n * assignment is direct\n */\n DIRECT(true, false),\n /**\n * assignment is type converted\n */\n TYPE_CONVERTED(false, true),\n /**\n * assignment is mapped (builtin/custom)\n */\n MAPPED(false, false),\n /**\n * 2 mapping methods (builtin/custom) are applied to get the target\n */\n MAPPED_TWICE(false, false),\n /**\n * assignment is first mapped (builtin/custom), then the result is type converted\n */\n MAPPED_TYPE_CONVERTED(false, true),\n /**\n * assignment is first type converted, and then mapped (builtin/custom)\n */\n TYPE_CONVERTED_MAPPED(false, true);\n\n private final boolean direct;\n\n private final boolean converted;\n\n AssignmentType(boolean isDirect, boolean isConverted) {\n this.direct = isDirect;\n this.converted = isConverted;\n }\n\n public boolean isDirect() {\n return direct;\n }\n\n public boolean isConverted() {\n return converted;\n }\n }\n\n /**\n * returns all types required as import by the assignment statement.\n *\n * @return imported types\n */\n ", "post_mask_code": "\n\n /**\n * returns all types exception types thrown by this assignment.\n *\n * @return exceptions thrown\n */\n List getThrownTypes();\n\n /**\n * An assignment in itself can wrap another assignment. E.g.:\n *
    \n *
  • a MethodReference can wrap a TypeConversion, another MethodReference and ultimately a Simple
  • \n *
  • a TypeConversion can wrap a MethodReference, and ultimately a Simple
  • \n *
\n *\n * @param assignment the assignment to set\n */\n void setAssignment(Assignment assignment);\n\n /**\n * the source reference being a source-getter, a constant, nested method call, etc.\n *\n * @return source reference\n */\n String getSourceReference();\n\n /**\n * @return true when the source reference is the source parameter (and not a property of the source parameter type)\n */\n boolean isSourceReferenceParameter();\n\n /**\n * the source presence checker reference\n *\n * @return source reference\n */\n PresenceCheck getSourcePresenceCheckerReference();\n\n /**\n * the source type used in the matching process\n *\n * @return source type (can be null)\n */\n Type getSourceType();\n\n /**\n * Creates an unique safe (local) variable name.\n *\n * @param desiredName the desired name\n *\n * @return the desired name, made unique in the scope of the bean mapping.\n */\n String createUniqueVarName(String desiredName);\n\n /**\n * See {@link #setSourceLocalVarName(java.lang.String) }\n *\n * @return local variable name (can be null if not set)\n */\n String getSourceLocalVarName();\n\n /**\n * Returns the source parameter name, to which this assignment applies. Note: the source parameter itself might\n * be mapped by this assignment, or one of its properties\n *\n * @return the source parameter name\n */\n String getSourceParameterName();\n\n /**\n * Replaces the sourceReference at the call site in the assignment in the template with this sourceLocalVarName.\n * The sourceLocalVarName can subsequently be used for e.g. null checking.\n *\n * @param sourceLocalVarName source local variable name\n */\n void setSourceLocalVarName(String sourceLocalVarName);\n\n String getSourceLoopVarName();\n\n /**\n * Replaces the sourceLocalVar or sourceReference at the call site in the assignment in the template with this\n * sourceLoopVarName.\n * The sourceLocalVar can subsequently be used for e.g. null checking.\n *\n * @param sourceLoopVarName loop variable\n */\n void setSourceLoopVarName(String sourceLoopVarName);\n\n /**\n * Returns whether the type of assignment\n *\n * @return {@link AssignmentType}\n */\n AssignmentType getType();\n\n boolean isCallingUpdateMethod();\n}\n"} {"task_id": "Java_2578", "language": "Java", "task_type": "method_signature", "source_file": "java/github/meteoinfo/MeteoInfo/meteoinfo-image/src/main/java/org/meteoinfo/image/filter/UnsharpFilter.java", "mask_start_position": 488, "mask_end_position": 528, "canonical_solution": "public void setThreshold(int threshold) ", "pre_mask_code": "package org.meteoinfo.image.filter;\n\nimport java.awt.image.BufferedImage;\n\n/**\n * A filter which subtracts Gaussian blur from an image, sharpening it.\n *\n * @author Jerry Huxtable\n */\npublic class UnsharpFilter extends GaussianFilter {\n\n private float amount = 0.5f;\n\n private int threshold = 1;\n\n public UnsharpFilter() {\n radius = 2;\n }\n\n /**\n * Set the threshold value.\n *\n * @param threshold the threshold value\n * @see #getThreshold\n */\n ", "post_mask_code": "{\n this.threshold = threshold;\n }\n\n /**\n * Get the threshold value.\n *\n * @return the threshold value\n * @see #setThreshold\n */\n public int getThreshold() {\n return threshold;\n }\n\n /**\n * Set the amount of sharpening.\n *\n * @param amount the amount min-value 0 max-value 1\n * @see #getAmount\n */\n public void setAmount(float amount) {\n this.amount = amount;\n }\n\n /**\n * Get the amount of sharpening.\n *\n * @return the amount\n * @see #setAmount\n */\n public float getAmount() {\n return amount;\n }\n\n public BufferedImage filter(BufferedImage src, BufferedImage dst) {\n int width = src.getWidth();\n int height = src.getHeight();\n if (dst == null) {\n dst = createCompatibleDestImage(src, null);\n }\n int[] inPixels = new int[width * height];\n int[] outPixels = new int[width * height];\n src.getRGB(0, 0, width, height, inPixels, 0, width);\n if (radius > 0) {\n convolveAndTranspose(kernel, inPixels, outPixels, width, height, alpha, alpha && premultiplyAlpha, false, CLAMP_EDGES);\n convolveAndTranspose(kernel, outPixels, inPixels, height, width, alpha, false, alpha && premultiplyAlpha, CLAMP_EDGES);\n }\n src.getRGB(0, 0, width, height, outPixels, 0, width);\n float a = 4 * amount;\n int index = 0;\n for (int y = 0; y < height; y++) {\n for (int x = 0; x < width; x++) {\n int rgb1 = outPixels[index];\n int r1 = (rgb1 >> 16) & 0xff;\n int g1 = (rgb1 >> 8) & 0xff;\n int b1 = rgb1 & 0xff;\n int rgb2 = inPixels[index];\n int r2 = (rgb2 >> 16) & 0xff;\n int g2 = (rgb2 >> 8) & 0xff;\n int b2 = rgb2 & 0xff;\n if (Math.abs(r1 - r2) >= threshold) {\n r1 = PixelUtils.clamp((int) ((a + 1) * (r1 - r2) + r2));\n }\n if (Math.abs(g1 - g2) >= threshold) {\n g1 = PixelUtils.clamp((int) ((a + 1) * (g1 - g2) + g2));\n }\n if (Math.abs(b1 - b2) >= threshold) {\n b1 = PixelUtils.clamp((int) ((a + 1) * (b1 - b2) + b2));\n }\n inPixels[index] = (rgb1 & 0xff000000) | (r1 << 16) | (g1 << 8) | b1;\n index++;\n }\n }\n dst.setRGB(0, 0, width, height, inPixels, 0, width);\n return dst;\n }\n\n public String toString() {\n return \"Blur/Unsharp Mask...\";\n }\n}\n"} {"task_id": "Java_2579", "language": "Java", "task_type": "method_body", "source_file": "java/github/meteoinfo/MeteoInfo/meteoinfo-image/src/main/java/org/meteoinfo/image/filter/UnsharpFilter.java", "mask_start_position": 528, "mask_end_position": 571, "canonical_solution": "{\n this.threshold = threshold;\n }", "pre_mask_code": "package org.meteoinfo.image.filter;\n\nimport java.awt.image.BufferedImage;\n\n/**\n * A filter which subtracts Gaussian blur from an image, sharpening it.\n *\n * @author Jerry Huxtable\n */\npublic class UnsharpFilter extends GaussianFilter {\n\n private float amount = 0.5f;\n\n private int threshold = 1;\n\n public UnsharpFilter() {\n radius = 2;\n }\n\n /**\n * Set the threshold value.\n *\n * @param threshold the threshold value\n * @see #getThreshold\n */\n public void setThreshold(int threshold) ", "post_mask_code": "\n\n /**\n * Get the threshold value.\n *\n * @return the threshold value\n * @see #setThreshold\n */\n public int getThreshold() {\n return threshold;\n }\n\n /**\n * Set the amount of sharpening.\n *\n * @param amount the amount min-value 0 max-value 1\n * @see #getAmount\n */\n public void setAmount(float amount) {\n this.amount = amount;\n }\n\n /**\n * Get the amount of sharpening.\n *\n * @return the amount\n * @see #setAmount\n */\n public float getAmount() {\n return amount;\n }\n\n public BufferedImage filter(BufferedImage src, BufferedImage dst) {\n int width = src.getWidth();\n int height = src.getHeight();\n if (dst == null) {\n dst = createCompatibleDestImage(src, null);\n }\n int[] inPixels = new int[width * height];\n int[] outPixels = new int[width * height];\n src.getRGB(0, 0, width, height, inPixels, 0, width);\n if (radius > 0) {\n convolveAndTranspose(kernel, inPixels, outPixels, width, height, alpha, alpha && premultiplyAlpha, false, CLAMP_EDGES);\n convolveAndTranspose(kernel, outPixels, inPixels, height, width, alpha, false, alpha && premultiplyAlpha, CLAMP_EDGES);\n }\n src.getRGB(0, 0, width, height, outPixels, 0, width);\n float a = 4 * amount;\n int index = 0;\n for (int y = 0; y < height; y++) {\n for (int x = 0; x < width; x++) {\n int rgb1 = outPixels[index];\n int r1 = (rgb1 >> 16) & 0xff;\n int g1 = (rgb1 >> 8) & 0xff;\n int b1 = rgb1 & 0xff;\n int rgb2 = inPixels[index];\n int r2 = (rgb2 >> 16) & 0xff;\n int g2 = (rgb2 >> 8) & 0xff;\n int b2 = rgb2 & 0xff;\n if (Math.abs(r1 - r2) >= threshold) {\n r1 = PixelUtils.clamp((int) ((a + 1) * (r1 - r2) + r2));\n }\n if (Math.abs(g1 - g2) >= threshold) {\n g1 = PixelUtils.clamp((int) ((a + 1) * (g1 - g2) + g2));\n }\n if (Math.abs(b1 - b2) >= threshold) {\n b1 = PixelUtils.clamp((int) ((a + 1) * (b1 - b2) + b2));\n }\n inPixels[index] = (rgb1 & 0xff000000) | (r1 << 16) | (g1 << 8) | b1;\n index++;\n }\n }\n dst.setRGB(0, 0, width, height, inPixels, 0, width);\n return dst;\n }\n\n public String toString() {\n return \"Blur/Unsharp Mask...\";\n }\n}\n"} {"task_id": "Java_2580", "language": "Java", "task_type": "single_line", "source_file": "java/github/meteoinfo/MeteoInfo/meteoinfo-image/src/main/java/org/meteoinfo/image/filter/UnsharpFilter.java", "mask_start_position": 550, "mask_end_position": 565, "canonical_solution": "ld = threshold;", "pre_mask_code": "package org.meteoinfo.image.filter;\n\nimport java.awt.image.BufferedImage;\n\n/**\n * A filter which subtracts Gaussian blur from an image, sharpening it.\n *\n * @author Jerry Huxtable\n */\npublic class UnsharpFilter extends GaussianFilter {\n\n private float amount = 0.5f;\n\n private int threshold = 1;\n\n public UnsharpFilter() {\n radius = 2;\n }\n\n /**\n * Set the threshold value.\n *\n * @param threshold the threshold value\n * @see #getThreshold\n */\n public void setThreshold(int threshold) {\n this.thresho", "post_mask_code": "\n }\n\n /**\n * Get the threshold value.\n *\n * @return the threshold value\n * @see #setThreshold\n */\n public int getThreshold() {\n return threshold;\n }\n\n /**\n * Set the amount of sharpening.\n *\n * @param amount the amount min-value 0 max-value 1\n * @see #getAmount\n */\n public void setAmount(float amount) {\n this.amount = amount;\n }\n\n /**\n * Get the amount of sharpening.\n *\n * @return the amount\n * @see #setAmount\n */\n public float getAmount() {\n return amount;\n }\n\n public BufferedImage filter(BufferedImage src, BufferedImage dst) {\n int width = src.getWidth();\n int height = src.getHeight();\n if (dst == null) {\n dst = createCompatibleDestImage(src, null);\n }\n int[] inPixels = new int[width * height];\n int[] outPixels = new int[width * height];\n src.getRGB(0, 0, width, height, inPixels, 0, width);\n if (radius > 0) {\n convolveAndTranspose(kernel, inPixels, outPixels, width, height, alpha, alpha && premultiplyAlpha, false, CLAMP_EDGES);\n convolveAndTranspose(kernel, outPixels, inPixels, height, width, alpha, false, alpha && premultiplyAlpha, CLAMP_EDGES);\n }\n src.getRGB(0, 0, width, height, outPixels, 0, width);\n float a = 4 * amount;\n int index = 0;\n for (int y = 0; y < height; y++) {\n for (int x = 0; x < width; x++) {\n int rgb1 = outPixels[index];\n int r1 = (rgb1 >> 16) & 0xff;\n int g1 = (rgb1 >> 8) & 0xff;\n int b1 = rgb1 & 0xff;\n int rgb2 = inPixels[index];\n int r2 = (rgb2 >> 16) & 0xff;\n int g2 = (rgb2 >> 8) & 0xff;\n int b2 = rgb2 & 0xff;\n if (Math.abs(r1 - r2) >= threshold) {\n r1 = PixelUtils.clamp((int) ((a + 1) * (r1 - r2) + r2));\n }\n if (Math.abs(g1 - g2) >= threshold) {\n g1 = PixelUtils.clamp((int) ((a + 1) * (g1 - g2) + g2));\n }\n if (Math.abs(b1 - b2) >= threshold) {\n b1 = PixelUtils.clamp((int) ((a + 1) * (b1 - b2) + b2));\n }\n inPixels[index] = (rgb1 & 0xff000000) | (r1 << 16) | (g1 << 8) | b1;\n index++;\n }\n }\n dst.setRGB(0, 0, width, height, inPixels, 0, width);\n return dst;\n }\n\n public String toString() {\n return \"Blur/Unsharp Mask...\";\n }\n}\n"} {"task_id": "Java_2581", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/meteoinfo/MeteoInfo/meteoinfo-image/src/main/java/org/meteoinfo/image/filter/UnsharpFilter.java", "mask_start_position": 488, "mask_end_position": 571, "canonical_solution": "public void setThreshold(int threshold) {\n this.threshold = threshold;\n }", "pre_mask_code": "package org.meteoinfo.image.filter;\n\nimport java.awt.image.BufferedImage;\n\n/**\n * A filter which subtracts Gaussian blur from an image, sharpening it.\n *\n * @author Jerry Huxtable\n */\npublic class UnsharpFilter extends GaussianFilter {\n\n private float amount = 0.5f;\n\n private int threshold = 1;\n\n public UnsharpFilter() {\n radius = 2;\n }\n\n /**\n * Set the threshold value.\n *\n * @param threshold the threshold value\n * @see #getThreshold\n */\n ", "post_mask_code": "\n\n /**\n * Get the threshold value.\n *\n * @return the threshold value\n * @see #setThreshold\n */\n public int getThreshold() {\n return threshold;\n }\n\n /**\n * Set the amount of sharpening.\n *\n * @param amount the amount min-value 0 max-value 1\n * @see #getAmount\n */\n public void setAmount(float amount) {\n this.amount = amount;\n }\n\n /**\n * Get the amount of sharpening.\n *\n * @return the amount\n * @see #setAmount\n */\n public float getAmount() {\n return amount;\n }\n\n public BufferedImage filter(BufferedImage src, BufferedImage dst) {\n int width = src.getWidth();\n int height = src.getHeight();\n if (dst == null) {\n dst = createCompatibleDestImage(src, null);\n }\n int[] inPixels = new int[width * height];\n int[] outPixels = new int[width * height];\n src.getRGB(0, 0, width, height, inPixels, 0, width);\n if (radius > 0) {\n convolveAndTranspose(kernel, inPixels, outPixels, width, height, alpha, alpha && premultiplyAlpha, false, CLAMP_EDGES);\n convolveAndTranspose(kernel, outPixels, inPixels, height, width, alpha, false, alpha && premultiplyAlpha, CLAMP_EDGES);\n }\n src.getRGB(0, 0, width, height, outPixels, 0, width);\n float a = 4 * amount;\n int index = 0;\n for (int y = 0; y < height; y++) {\n for (int x = 0; x < width; x++) {\n int rgb1 = outPixels[index];\n int r1 = (rgb1 >> 16) & 0xff;\n int g1 = (rgb1 >> 8) & 0xff;\n int b1 = rgb1 & 0xff;\n int rgb2 = inPixels[index];\n int r2 = (rgb2 >> 16) & 0xff;\n int g2 = (rgb2 >> 8) & 0xff;\n int b2 = rgb2 & 0xff;\n if (Math.abs(r1 - r2) >= threshold) {\n r1 = PixelUtils.clamp((int) ((a + 1) * (r1 - r2) + r2));\n }\n if (Math.abs(g1 - g2) >= threshold) {\n g1 = PixelUtils.clamp((int) ((a + 1) * (g1 - g2) + g2));\n }\n if (Math.abs(b1 - b2) >= threshold) {\n b1 = PixelUtils.clamp((int) ((a + 1) * (b1 - b2) + b2));\n }\n inPixels[index] = (rgb1 & 0xff000000) | (r1 << 16) | (g1 << 8) | b1;\n index++;\n }\n }\n dst.setRGB(0, 0, width, height, inPixels, 0, width);\n return dst;\n }\n\n public String toString() {\n return \"Blur/Unsharp Mask...\";\n }\n}\n"} {"task_id": "Java_2582", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Illarion-eV/Illarion-Java/illamapedit/src/main/java/illarion/mapedit/gui/menubands/ViewBand.java", "mask_start_position": 2592, "mask_end_position": 2660, "canonical_solution": "private void renderEmptyTilesButton(@Nonnull TileRenderer renderer) ", "pre_mask_code": "/*\n * This file is part of the Illarion project.\n *\n *\n */\npackage illarion.mapedit.gui.menubands;\n\nimport illarion.mapedit.Lang;\nimport illarion.mapedit.events.map.RepaintRequestEvent;\nimport illarion.mapedit.render.*;\nimport org.bushe.swing.event.EventBus;\nimport org.pushingpixels.flamingo.api.common.JCommandToggleButton;\nimport org.pushingpixels.flamingo.api.ribbon.JRibbonBand;\nimport org.pushingpixels.flamingo.api.ribbon.resize.CoreRibbonResizePolicies.High2Low;\nimport org.pushingpixels.flamingo.api.ribbon.resize.CoreRibbonResizePolicies.Mid2Low;\nimport org.pushingpixels.flamingo.api.ribbon.resize.CoreRibbonResizePolicies.Mirror;\nimport org.pushingpixels.flamingo.api.ribbon.resize.RibbonBandResizePolicy;\nimport javax.annotation.Nonnull;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * @author Tim\n */\npublic class ViewBand extends JRibbonBand {\n\n public ViewBand(@Nonnull RendererManager manager) {\n super(Lang.getMsg(\"gui.viewband.Name\"), null);\n TileRenderer tileRenderer = new TileRenderer(manager);\n manager.addRenderer(new SelectedTileRenderer(manager));\n newRenderButton(manager, tileRenderer);\n newRenderButton(manager, new ItemRenderer(manager));\n renderEmptyTilesButton(tileRenderer);\n newRenderButton(manager, new GridRenderer(manager));\n newRenderButton(manager, new MusicRenderer(manager));\n newRenderButton(manager, new WarpRenderer(manager));\n newRenderButton(manager, new ItemDataRenderer(manager));\n newRenderButton(manager, new AnnotationRenderer(manager));\n newRenderButton(manager, new ObstacleRenderer(manager));\n List resize = new ArrayList<>(3);\n resize.add(new Mirror(getControlPanel()));\n resize.add(new Mid2Low(getControlPanel()));\n resize.add(new High2Low(getControlPanel()));\n setResizePolicies(resize);\n }\n\n private void newRenderButton(@Nonnull RendererManager manager, @Nonnull AbstractMapRenderer renderer) {\n JCommandToggleButton btn = new JCommandToggleButton(renderer.getLocalizedName(), renderer.getRendererIcon());\n btn.getActionModel().setSelected(renderer.isDefaultOn());\n btn.addActionListener(e -> {\n if (btn.getActionModel().isSelected()) {\n manager.addRenderer(renderer);\n } else {\n manager.removeRenderer(renderer);\n }\n });\n if (renderer.isDefaultOn()) {\n manager.addRenderer(renderer);\n }\n addCommandButton(btn, renderer.getPriority());\n }\n\n ", "post_mask_code": "{\n JCommandToggleButton btn = new JCommandToggleButton(renderer.getEmptyTileLocalizedName(), renderer.getEmptyTileRendererIcon());\n btn.getActionModel().setSelected(renderer.isEmptyTileDefaultOn());\n btn.addActionListener(e -> {\n renderer.setRenderEmptyTiles(btn.getActionModel().isSelected());\n EventBus.publish(new RepaintRequestEvent());\n });\n if (renderer.isEmptyTileDefaultOn()) {\n renderer.setRenderEmptyTiles(true);\n }\n addCommandButton(btn, renderer.getEmptyTilePriority());\n }\n}\n"} {"task_id": "Java_2583", "language": "Java", "task_type": "single_line", "source_file": "java/github/Illarion-eV/Illarion-Java/illamapedit/src/main/java/illarion/mapedit/gui/menubands/ViewBand.java", "mask_start_position": 2840, "mask_end_position": 2872, "canonical_solution": "enderer.isEmptyTileDefaultOn());", "pre_mask_code": "/*\n * This file is part of the Illarion project.\n *\n *\n */\npackage illarion.mapedit.gui.menubands;\n\nimport illarion.mapedit.Lang;\nimport illarion.mapedit.events.map.RepaintRequestEvent;\nimport illarion.mapedit.render.*;\nimport org.bushe.swing.event.EventBus;\nimport org.pushingpixels.flamingo.api.common.JCommandToggleButton;\nimport org.pushingpixels.flamingo.api.ribbon.JRibbonBand;\nimport org.pushingpixels.flamingo.api.ribbon.resize.CoreRibbonResizePolicies.High2Low;\nimport org.pushingpixels.flamingo.api.ribbon.resize.CoreRibbonResizePolicies.Mid2Low;\nimport org.pushingpixels.flamingo.api.ribbon.resize.CoreRibbonResizePolicies.Mirror;\nimport org.pushingpixels.flamingo.api.ribbon.resize.RibbonBandResizePolicy;\nimport javax.annotation.Nonnull;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * @author Tim\n */\npublic class ViewBand extends JRibbonBand {\n\n public ViewBand(@Nonnull RendererManager manager) {\n super(Lang.getMsg(\"gui.viewband.Name\"), null);\n TileRenderer tileRenderer = new TileRenderer(manager);\n manager.addRenderer(new SelectedTileRenderer(manager));\n newRenderButton(manager, tileRenderer);\n newRenderButton(manager, new ItemRenderer(manager));\n renderEmptyTilesButton(tileRenderer);\n newRenderButton(manager, new GridRenderer(manager));\n newRenderButton(manager, new MusicRenderer(manager));\n newRenderButton(manager, new WarpRenderer(manager));\n newRenderButton(manager, new ItemDataRenderer(manager));\n newRenderButton(manager, new AnnotationRenderer(manager));\n newRenderButton(manager, new ObstacleRenderer(manager));\n List resize = new ArrayList<>(3);\n resize.add(new Mirror(getControlPanel()));\n resize.add(new Mid2Low(getControlPanel()));\n resize.add(new High2Low(getControlPanel()));\n setResizePolicies(resize);\n }\n\n private void newRenderButton(@Nonnull RendererManager manager, @Nonnull AbstractMapRenderer renderer) {\n JCommandToggleButton btn = new JCommandToggleButton(renderer.getLocalizedName(), renderer.getRendererIcon());\n btn.getActionModel().setSelected(renderer.isDefaultOn());\n btn.addActionListener(e -> {\n if (btn.getActionModel().isSelected()) {\n manager.addRenderer(renderer);\n } else {\n manager.removeRenderer(renderer);\n }\n });\n if (renderer.isDefaultOn()) {\n manager.addRenderer(renderer);\n }\n addCommandButton(btn, renderer.getPriority());\n }\n\n private void renderEmptyTilesButton(@Nonnull TileRenderer renderer) {\n JCommandToggleButton btn = new JCommandToggleButton(renderer.getEmptyTileLocalizedName(), renderer.getEmptyTileRendererIcon());\n btn.getActionModel().setSelected(r", "post_mask_code": "\n btn.addActionListener(e -> {\n renderer.setRenderEmptyTiles(btn.getActionModel().isSelected());\n EventBus.publish(new RepaintRequestEvent());\n });\n if (renderer.isEmptyTileDefaultOn()) {\n renderer.setRenderEmptyTiles(true);\n }\n addCommandButton(btn, renderer.getEmptyTilePriority());\n }\n}\n"} {"task_id": "Java_2584", "language": "Java", "task_type": "method_signature", "source_file": "java/github/wangjianxiandev/WanAndroidMvp/app/src/main/java/com/wjx/android/wanandroidmvp/adapter/ProjectListAdapter.java", "mask_start_position": 1909, "mask_end_position": 2021, "canonical_solution": "@NonNull\n @Override\n public ProjectListHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) ", "pre_mask_code": "package com.wjx.android.wanandroidmvp.adapter;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.graphics.PorterDuff;\nimport android.text.Html;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\nimport com.blankj.utilcode.util.SPUtils;\nimport com.bumptech.glide.Glide;\nimport com.wjx.android.wanandroidmvp.R;\nimport com.wjx.android.wanandroidmvp.base.utils.Constant;\nimport com.wjx.android.wanandroidmvp.base.utils.JumpWebUtils;\nimport com.wjx.android.wanandroidmvp.base.utils.LoginUtils;\nimport com.wjx.android.wanandroidmvp.base.utils.Utils;\nimport com.wjx.android.wanandroidmvp.bean.base.Event;\nimport com.wjx.android.wanandroidmvp.bean.db.Article;\nimport com.wjx.android.wanandroidmvp.ui.activity.LoginActivity;\nimport org.greenrobot.eventbus.EventBus;\nimport java.util.ArrayList;\nimport java.util.List;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\n\n/**\n * Created with Android Studio.\n * Description:\n *\n * @author: Wangjianxian\n * @date: 2019/12/27\n * Time: 18:03\n */\npublic class ProjectListAdapter extends RecyclerView.Adapter {\n\n private Context mContext;\n\n private List
mProjectList = new ArrayList<>();\n\n private boolean isNightMode;\n\n public void setProjectList(List
projectList) {\n mProjectList.clear();\n mProjectList.addAll(projectList);\n notifyDataSetChanged();\n }\n\n public ProjectListAdapter(Context context, List
articleList) {\n mContext = context;\n mProjectList.addAll(articleList);\n isNightMode = SPUtils.getInstance(Constant.CONFIG_SETTINGS).getBoolean(Constant.KEY_NIGHT_MODE, false);\n }\n\n ", "post_mask_code": "{\n View view = LayoutInflater.from(mContext).inflate(R.layout.project_item, parent, false);\n return new ProjectListHolder(view);\n }\n\n @Override\n public void onBindViewHolder(@NonNull ProjectListHolder holder, int position) {\n if (mProjectList != null) {\n Article bean = mProjectList.get(position);\n holder.mProjectTitle.setText(Html.fromHtml(bean.title, Html.FROM_HTML_MODE_COMPACT));\n holder.mProjectAuthor.setText(String.format(mContext.getResources().getString(R.string.article_author), bean.author));\n holder.mProjectDate.setText(bean.niceDate);\n String category = String.format(mContext.getResources().getString(R.string.article_category), bean.superChapterName, bean.chapterName);\n holder.mProjectType.setText(Html.fromHtml(category, Html.FROM_HTML_MODE_COMPACT));\n holder.mProjectContent.setText(bean.desc);\n holder.mProjectImageView.setVisibility(View.VISIBLE);\n holder.mItemTop.setVisibility(View.VISIBLE);\n Glide.with(mContext).load(bean.envelopePic).into(holder.mProjectImageView);\n holder.itemView.setOnClickListener(view -> JumpWebUtils.startWebView(mContext, mProjectList.get(position).title, mProjectList.get(position).link, mProjectList.get(position).articleId, mProjectList.get(position).collect));\n if (!LoginUtils.isLogin()) {\n holder.mCollectView.setSelected(false);\n } else {\n holder.mCollectView.setSelected(bean.collect);\n }\n holder.mCollectView.setOnClickListener(view -> {\n if (!bean.collect) {\n Utils.Vibrate(mContext, 50);\n }\n if (!LoginUtils.isLogin()) {\n Toast.makeText(mContext, \"click\", Toast.LENGTH_SHORT).show();\n Intent intent = new Intent(mContext, LoginActivity.class);\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n mContext.startActivity(intent);\n } else {\n Event event = new Event();\n event.target = Event.TARGET_PROJECT;\n event.type = bean.collect ? Event.TYPE_UNCOLLECT : Event.TYPE_COLLECT;\n event.data = bean.articleId + \";\" + bean.projectType;\n EventBus.getDefault().post(event);\n }\n });\n holder.itemView.getBackground().setColorFilter(mContext.getColor(isNightMode ? R.color.primary_grey_dark : R.color.card_bg), PorterDuff.Mode.SRC_ATOP);\n holder.mProjectDate.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666));\n holder.mProjectType.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666));\n holder.mProjectAuthor.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666));\n holder.mProjectContent.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666));\n }\n }\n\n @Override\n public int getItemCount() {\n return mProjectList == null ? 0 : mProjectList.size();\n }\n\n class ProjectListHolder extends RecyclerView.ViewHolder {\n\n @BindView(R.id.item_project_author)\n TextView mProjectAuthor;\n\n @BindView(R.id.item_project_title)\n TextView mProjectTitle;\n\n @BindView(R.id.item_project_type)\n TextView mProjectType;\n\n @BindView(R.id.item_project_date)\n TextView mProjectDate;\n\n @BindView(R.id.item_project_imageview)\n ImageView mProjectImageView;\n\n @BindView(R.id.item_project_content)\n TextView mProjectContent;\n\n @BindView(R.id.item_list_collect)\n ImageView mCollectView;\n\n @BindView(R.id.item_project_top)\n TextView mItemTop;\n\n public ProjectListHolder(@NonNull View itemView) {\n super(itemView);\n ButterKnife.bind(this, itemView);\n }\n }\n}\n"} {"task_id": "Java_2585", "language": "Java", "task_type": "method_body", "source_file": "java/github/wangjianxiandev/WanAndroidMvp/app/src/main/java/com/wjx/android/wanandroidmvp/adapter/ProjectListAdapter.java", "mask_start_position": 1527, "mask_end_position": 1638, "canonical_solution": "{\n mProjectList.clear();\n mProjectList.addAll(projectList);\n notifyDataSetChanged();\n }", "pre_mask_code": "package com.wjx.android.wanandroidmvp.adapter;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.graphics.PorterDuff;\nimport android.text.Html;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\nimport com.blankj.utilcode.util.SPUtils;\nimport com.bumptech.glide.Glide;\nimport com.wjx.android.wanandroidmvp.R;\nimport com.wjx.android.wanandroidmvp.base.utils.Constant;\nimport com.wjx.android.wanandroidmvp.base.utils.JumpWebUtils;\nimport com.wjx.android.wanandroidmvp.base.utils.LoginUtils;\nimport com.wjx.android.wanandroidmvp.base.utils.Utils;\nimport com.wjx.android.wanandroidmvp.bean.base.Event;\nimport com.wjx.android.wanandroidmvp.bean.db.Article;\nimport com.wjx.android.wanandroidmvp.ui.activity.LoginActivity;\nimport org.greenrobot.eventbus.EventBus;\nimport java.util.ArrayList;\nimport java.util.List;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\n\n/**\n * Created with Android Studio.\n * Description:\n *\n * @author: Wangjianxian\n * @date: 2019/12/27\n * Time: 18:03\n */\npublic class ProjectListAdapter extends RecyclerView.Adapter {\n\n private Context mContext;\n\n private List
mProjectList = new ArrayList<>();\n\n private boolean isNightMode;\n\n public void setProjectList(List
projectList) ", "post_mask_code": "\n\n public ProjectListAdapter(Context context, List
articleList) {\n mContext = context;\n mProjectList.addAll(articleList);\n isNightMode = SPUtils.getInstance(Constant.CONFIG_SETTINGS).getBoolean(Constant.KEY_NIGHT_MODE, false);\n }\n\n @NonNull\n @Override\n public ProjectListHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(mContext).inflate(R.layout.project_item, parent, false);\n return new ProjectListHolder(view);\n }\n\n @Override\n public void onBindViewHolder(@NonNull ProjectListHolder holder, int position) {\n if (mProjectList != null) {\n Article bean = mProjectList.get(position);\n holder.mProjectTitle.setText(Html.fromHtml(bean.title, Html.FROM_HTML_MODE_COMPACT));\n holder.mProjectAuthor.setText(String.format(mContext.getResources().getString(R.string.article_author), bean.author));\n holder.mProjectDate.setText(bean.niceDate);\n String category = String.format(mContext.getResources().getString(R.string.article_category), bean.superChapterName, bean.chapterName);\n holder.mProjectType.setText(Html.fromHtml(category, Html.FROM_HTML_MODE_COMPACT));\n holder.mProjectContent.setText(bean.desc);\n holder.mProjectImageView.setVisibility(View.VISIBLE);\n holder.mItemTop.setVisibility(View.VISIBLE);\n Glide.with(mContext).load(bean.envelopePic).into(holder.mProjectImageView);\n holder.itemView.setOnClickListener(view -> JumpWebUtils.startWebView(mContext, mProjectList.get(position).title, mProjectList.get(position).link, mProjectList.get(position).articleId, mProjectList.get(position).collect));\n if (!LoginUtils.isLogin()) {\n holder.mCollectView.setSelected(false);\n } else {\n holder.mCollectView.setSelected(bean.collect);\n }\n holder.mCollectView.setOnClickListener(view -> {\n if (!bean.collect) {\n Utils.Vibrate(mContext, 50);\n }\n if (!LoginUtils.isLogin()) {\n Toast.makeText(mContext, \"click\", Toast.LENGTH_SHORT).show();\n Intent intent = new Intent(mContext, LoginActivity.class);\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n mContext.startActivity(intent);\n } else {\n Event event = new Event();\n event.target = Event.TARGET_PROJECT;\n event.type = bean.collect ? Event.TYPE_UNCOLLECT : Event.TYPE_COLLECT;\n event.data = bean.articleId + \";\" + bean.projectType;\n EventBus.getDefault().post(event);\n }\n });\n holder.itemView.getBackground().setColorFilter(mContext.getColor(isNightMode ? R.color.primary_grey_dark : R.color.card_bg), PorterDuff.Mode.SRC_ATOP);\n holder.mProjectDate.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666));\n holder.mProjectType.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666));\n holder.mProjectAuthor.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666));\n holder.mProjectContent.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666));\n }\n }\n\n @Override\n public int getItemCount() {\n return mProjectList == null ? 0 : mProjectList.size();\n }\n\n class ProjectListHolder extends RecyclerView.ViewHolder {\n\n @BindView(R.id.item_project_author)\n TextView mProjectAuthor;\n\n @BindView(R.id.item_project_title)\n TextView mProjectTitle;\n\n @BindView(R.id.item_project_type)\n TextView mProjectType;\n\n @BindView(R.id.item_project_date)\n TextView mProjectDate;\n\n @BindView(R.id.item_project_imageview)\n ImageView mProjectImageView;\n\n @BindView(R.id.item_project_content)\n TextView mProjectContent;\n\n @BindView(R.id.item_list_collect)\n ImageView mCollectView;\n\n @BindView(R.id.item_project_top)\n TextView mItemTop;\n\n public ProjectListHolder(@NonNull View itemView) {\n super(itemView);\n ButterKnife.bind(this, itemView);\n }\n }\n}\n"} {"task_id": "Java_2586", "language": "Java", "task_type": "single_line", "source_file": "java/github/wangjianxiandev/WanAndroidMvp/app/src/main/java/com/wjx/android/wanandroidmvp/adapter/ProjectListAdapter.java", "mask_start_position": 1614, "mask_end_position": 1632, "canonical_solution": "yDataSetChanged();", "pre_mask_code": "package com.wjx.android.wanandroidmvp.adapter;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.graphics.PorterDuff;\nimport android.text.Html;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\nimport com.blankj.utilcode.util.SPUtils;\nimport com.bumptech.glide.Glide;\nimport com.wjx.android.wanandroidmvp.R;\nimport com.wjx.android.wanandroidmvp.base.utils.Constant;\nimport com.wjx.android.wanandroidmvp.base.utils.JumpWebUtils;\nimport com.wjx.android.wanandroidmvp.base.utils.LoginUtils;\nimport com.wjx.android.wanandroidmvp.base.utils.Utils;\nimport com.wjx.android.wanandroidmvp.bean.base.Event;\nimport com.wjx.android.wanandroidmvp.bean.db.Article;\nimport com.wjx.android.wanandroidmvp.ui.activity.LoginActivity;\nimport org.greenrobot.eventbus.EventBus;\nimport java.util.ArrayList;\nimport java.util.List;\nimport butterknife.BindView;\nimport butterknife.ButterKnife;\n\n/**\n * Created with Android Studio.\n * Description:\n *\n * @author: Wangjianxian\n * @date: 2019/12/27\n * Time: 18:03\n */\npublic class ProjectListAdapter extends RecyclerView.Adapter {\n\n private Context mContext;\n\n private List
mProjectList = new ArrayList<>();\n\n private boolean isNightMode;\n\n public void setProjectList(List
projectList) {\n mProjectList.clear();\n mProjectList.addAll(projectList);\n notif", "post_mask_code": "\n }\n\n public ProjectListAdapter(Context context, List
articleList) {\n mContext = context;\n mProjectList.addAll(articleList);\n isNightMode = SPUtils.getInstance(Constant.CONFIG_SETTINGS).getBoolean(Constant.KEY_NIGHT_MODE, false);\n }\n\n @NonNull\n @Override\n public ProjectListHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(mContext).inflate(R.layout.project_item, parent, false);\n return new ProjectListHolder(view);\n }\n\n @Override\n public void onBindViewHolder(@NonNull ProjectListHolder holder, int position) {\n if (mProjectList != null) {\n Article bean = mProjectList.get(position);\n holder.mProjectTitle.setText(Html.fromHtml(bean.title, Html.FROM_HTML_MODE_COMPACT));\n holder.mProjectAuthor.setText(String.format(mContext.getResources().getString(R.string.article_author), bean.author));\n holder.mProjectDate.setText(bean.niceDate);\n String category = String.format(mContext.getResources().getString(R.string.article_category), bean.superChapterName, bean.chapterName);\n holder.mProjectType.setText(Html.fromHtml(category, Html.FROM_HTML_MODE_COMPACT));\n holder.mProjectContent.setText(bean.desc);\n holder.mProjectImageView.setVisibility(View.VISIBLE);\n holder.mItemTop.setVisibility(View.VISIBLE);\n Glide.with(mContext).load(bean.envelopePic).into(holder.mProjectImageView);\n holder.itemView.setOnClickListener(view -> JumpWebUtils.startWebView(mContext, mProjectList.get(position).title, mProjectList.get(position).link, mProjectList.get(position).articleId, mProjectList.get(position).collect));\n if (!LoginUtils.isLogin()) {\n holder.mCollectView.setSelected(false);\n } else {\n holder.mCollectView.setSelected(bean.collect);\n }\n holder.mCollectView.setOnClickListener(view -> {\n if (!bean.collect) {\n Utils.Vibrate(mContext, 50);\n }\n if (!LoginUtils.isLogin()) {\n Toast.makeText(mContext, \"click\", Toast.LENGTH_SHORT).show();\n Intent intent = new Intent(mContext, LoginActivity.class);\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n mContext.startActivity(intent);\n } else {\n Event event = new Event();\n event.target = Event.TARGET_PROJECT;\n event.type = bean.collect ? Event.TYPE_UNCOLLECT : Event.TYPE_COLLECT;\n event.data = bean.articleId + \";\" + bean.projectType;\n EventBus.getDefault().post(event);\n }\n });\n holder.itemView.getBackground().setColorFilter(mContext.getColor(isNightMode ? R.color.primary_grey_dark : R.color.card_bg), PorterDuff.Mode.SRC_ATOP);\n holder.mProjectDate.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666));\n holder.mProjectType.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666));\n holder.mProjectAuthor.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666));\n holder.mProjectContent.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666));\n }\n }\n\n @Override\n public int getItemCount() {\n return mProjectList == null ? 0 : mProjectList.size();\n }\n\n class ProjectListHolder extends RecyclerView.ViewHolder {\n\n @BindView(R.id.item_project_author)\n TextView mProjectAuthor;\n\n @BindView(R.id.item_project_title)\n TextView mProjectTitle;\n\n @BindView(R.id.item_project_type)\n TextView mProjectType;\n\n @BindView(R.id.item_project_date)\n TextView mProjectDate;\n\n @BindView(R.id.item_project_imageview)\n ImageView mProjectImageView;\n\n @BindView(R.id.item_project_content)\n TextView mProjectContent;\n\n @BindView(R.id.item_list_collect)\n ImageView mCollectView;\n\n @BindView(R.id.item_project_top)\n TextView mItemTop;\n\n public ProjectListHolder(@NonNull View itemView) {\n super(itemView);\n ButterKnife.bind(this, itemView);\n }\n }\n}\n"} {"task_id": "Java_2587", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/wicket/wicket-examples/src/main/java/org/apache/wicket/examples/datetime/DateTimePage.java", "mask_start_position": 8358, "mask_end_position": 8469, "canonical_solution": "@Override\n public ZoneId getObject(String id, IModel> choices) ", "pre_mask_code": "package org.apache.wicket.examples.datetime;\n\nimport java.time.LocalDate;\nimport java.time.LocalDateTime;\nimport java.time.LocalTime;\nimport java.time.ZoneId;\nimport java.time.ZoneOffset;\nimport java.time.ZonedDateTime;\nimport java.time.format.FormatStyle;\nimport java.time.format.TextStyle;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.stream.Collectors;\nimport org.apache.wicket.Session;\nimport org.apache.wicket.examples.WicketExamplePage;\nimport org.apache.wicket.examples.forminput.FormInputApplication;\nimport org.apache.wicket.extensions.markup.html.form.datetime.LocalDateTextField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.LocalDateTimeField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.LocalDateTimeTextField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.TimeField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.ZonedDateTimeField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.ZonedToLocalDateTimeModel;\nimport org.apache.wicket.markup.html.basic.Label;\nimport org.apache.wicket.markup.html.form.Button;\nimport org.apache.wicket.markup.html.form.DropDownChoice;\nimport org.apache.wicket.markup.html.form.Form;\nimport org.apache.wicket.markup.html.form.FormComponentUpdatingBehavior;\nimport org.apache.wicket.markup.html.form.IChoiceRenderer;\nimport org.apache.wicket.markup.html.link.Link;\nimport org.apache.wicket.markup.html.panel.FeedbackPanel;\nimport org.apache.wicket.model.IModel;\nimport org.apache.wicket.model.PropertyModel;\nimport org.apache.wicket.protocol.http.request.WebClientInfo;\nimport org.apache.wicket.request.http.WebRequest;\n\n/**\n * DateTime example page.\n */\npublic class DateTimePage extends WicketExamplePage {\n\n private static final long serialVersionUID = 1L;\n\n private ZoneId clientZone;\n\n private ZoneId targetZone = ZoneId.of(\"UTC+8\");\n\n @SuppressWarnings(\"unused\")\n private LocalTime time1 = LocalTime.of(22, 15);\n\n @SuppressWarnings(\"unused\")\n private LocalTime time2 = LocalTime.of(22, 15);\n\n @SuppressWarnings(\"unused\")\n private LocalDate date = LocalDate.now();\n\n @SuppressWarnings(\"unused\")\n private LocalDateTime dateTime0 = LocalDateTime.now();\n\n @SuppressWarnings(\"unused\")\n private ZonedDateTime dateTime1 = LocalDateTime.now().atZone(targetZone);\n\n @SuppressWarnings(\"unused\")\n private ZonedDateTime dateTime2 = LocalDateTime.now().atZone(targetZone);\n\n @SuppressWarnings(\"unused\")\n private ZonedDateTime dateTime3 = ZonedDateTime.now();\n\n public DateTimePage() {\n Form form = new Form<>(\"form\");\n this.add(form);\n form.add(new ZoneDropDownChoice(\"zoneSelect\"));\n // Dropdown for selecting locale\n form.add(new LocaleDropDownChoice(\"localeSelect\"));\n // Link to return to default locale\n form.add(new Link(\"defaultLocaleLink\") {\n\n private static final long serialVersionUID = 1L;\n\n public void onClick() {\n WebRequest request = (WebRequest) getRequest();\n getSession().setLocale(request.getLocale());\n }\n });\n form.add(new TimeField(\"time1\", new PropertyModel<>(this, \"time1\")) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected boolean use12HourFormat() {\n return true;\n }\n });\n form.add(new TimeField(\"time2\", new PropertyModel<>(this, \"time2\")) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected boolean use12HourFormat() {\n return false;\n }\n });\n final LocalDateTextField dateField = new LocalDateTextField(\"date\", new PropertyModel<>(this, \"date\"), \"dd-MM-yyyy\", \"d-M-yyyy\");\n form.add(dateField);\n final LocalDateTimeField datetimeField0 = new LocalDateTimeField(\"datetime0\", new PropertyModel<>(this, \"dateTime0\")) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected LocalTime getDefaultTime() {\n return LocalTime.of(0, 0);\n }\n };\n form.add(datetimeField0);\n IModel zonedDateTime1 = new PropertyModel<>(this, \"dateTime1\");\n final LocalDateTimeField datetimeField1 = new LocalDateTimeField(\"datetime1\", new ZonedToLocalDateTimeModel(zonedDateTime1) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected ZoneId getClientTimeZone() {\n return clientZone;\n }\n\n @Override\n protected ZoneId getTargetTimeZone() {\n return targetZone;\n }\n });\n form.add(datetimeField1);\n form.add(new Label(\"datetime1-label\", zonedDateTime1));\n IModel zonedDateTime2 = new PropertyModel<>(this, \"dateTime2\");\n LocalDateTimeTextField datetimeField2 = new LocalDateTimeTextField(\"datetime2\", new ZonedToLocalDateTimeModel(zonedDateTime2) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected ZoneId getClientTimeZone() {\n return clientZone;\n }\n\n @Override\n protected ZoneId getTargetTimeZone() {\n return targetZone;\n }\n }, FormatStyle.SHORT, FormatStyle.SHORT);\n form.add(datetimeField2);\n form.add(new Label(\"datetime2-label\", zonedDateTime2));\n final ZonedDateTimeField datetimeField3 = new ZonedDateTimeField(\"datetime3\", new PropertyModel<>(this, \"dateTime3\"));\n form.add(datetimeField3);\n final FeedbackPanel feedback = new FeedbackPanel(\"feedback\");\n form.add(feedback);\n form.add(new Button(\"submit\"));\n }\n\n @Override\n protected void onInitialize() {\n super.onInitialize();\n clientZone = ((WebClientInfo) Session.get().getClientInfo()).getProperties().getTimeZone().toZoneId();\n }\n\n private final class LocaleChoiceRenderer implements IChoiceRenderer {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public Object getDisplayValue(Locale locale) {\n return locale.getDisplayName(getLocale());\n }\n }\n\n /**\n * Dropdown with Locales.\n */\n private final class LocaleDropDownChoice extends DropDownChoice {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * Construct.\n *\n * @param id\n * component id\n */\n public LocaleDropDownChoice(String id) {\n super(id, FormInputApplication.LOCALES, new LocaleChoiceRenderer());\n setModel(new PropertyModel<>(this, \"session.locale\"));\n add(new FormComponentUpdatingBehavior() {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected void onUpdate() {\n setResponsePage(getPage().getClass());\n }\n });\n }\n }\n\n private class ZoneDropDownChoice extends DropDownChoice {\n\n private static final long serialVersionUID = 1L;\n\n public ZoneDropDownChoice(String id) {\n super(id, new IModel>() {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public List getObject() {\n return ZoneId.getAvailableZoneIds().stream().map(id -> ZoneId.of(id)).collect(Collectors.toList());\n }\n });\n setModel(new PropertyModel(DateTimePage.this, \"clientZone\"));\n setChoiceRenderer(new IChoiceRenderer() {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public Object getDisplayValue(ZoneId object) {\n String name = object.getDisplayName(TextStyle.FULL, getLocale());\n ZoneOffset offset = LocalDateTime.now().atZone(object).getOffset();\n return name + offset;\n }\n\n @Override\n public String getIdValue(ZoneId object, int index) {\n return object.getId();\n }\n\n ", "post_mask_code": "{\n return ZoneId.of(id);\n }\n });\n add(new FormComponentUpdatingBehavior() {\n\n private static final long serialVersionUID = 1L;\n\n protected void onUpdate() {\n // clear raw input of all inputs so that values are reformatted\n getForm().clearInput();\n }\n });\n }\n }\n}\n"} {"task_id": "Java_2588", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/wicket/wicket-examples/src/main/java/org/apache/wicket/examples/datetime/DateTimePage.java", "mask_start_position": 8469, "mask_end_position": 8530, "canonical_solution": "{\n return ZoneId.of(id);\n }", "pre_mask_code": "package org.apache.wicket.examples.datetime;\n\nimport java.time.LocalDate;\nimport java.time.LocalDateTime;\nimport java.time.LocalTime;\nimport java.time.ZoneId;\nimport java.time.ZoneOffset;\nimport java.time.ZonedDateTime;\nimport java.time.format.FormatStyle;\nimport java.time.format.TextStyle;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.stream.Collectors;\nimport org.apache.wicket.Session;\nimport org.apache.wicket.examples.WicketExamplePage;\nimport org.apache.wicket.examples.forminput.FormInputApplication;\nimport org.apache.wicket.extensions.markup.html.form.datetime.LocalDateTextField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.LocalDateTimeField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.LocalDateTimeTextField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.TimeField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.ZonedDateTimeField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.ZonedToLocalDateTimeModel;\nimport org.apache.wicket.markup.html.basic.Label;\nimport org.apache.wicket.markup.html.form.Button;\nimport org.apache.wicket.markup.html.form.DropDownChoice;\nimport org.apache.wicket.markup.html.form.Form;\nimport org.apache.wicket.markup.html.form.FormComponentUpdatingBehavior;\nimport org.apache.wicket.markup.html.form.IChoiceRenderer;\nimport org.apache.wicket.markup.html.link.Link;\nimport org.apache.wicket.markup.html.panel.FeedbackPanel;\nimport org.apache.wicket.model.IModel;\nimport org.apache.wicket.model.PropertyModel;\nimport org.apache.wicket.protocol.http.request.WebClientInfo;\nimport org.apache.wicket.request.http.WebRequest;\n\n/**\n * DateTime example page.\n */\npublic class DateTimePage extends WicketExamplePage {\n\n private static final long serialVersionUID = 1L;\n\n private ZoneId clientZone;\n\n private ZoneId targetZone = ZoneId.of(\"UTC+8\");\n\n @SuppressWarnings(\"unused\")\n private LocalTime time1 = LocalTime.of(22, 15);\n\n @SuppressWarnings(\"unused\")\n private LocalTime time2 = LocalTime.of(22, 15);\n\n @SuppressWarnings(\"unused\")\n private LocalDate date = LocalDate.now();\n\n @SuppressWarnings(\"unused\")\n private LocalDateTime dateTime0 = LocalDateTime.now();\n\n @SuppressWarnings(\"unused\")\n private ZonedDateTime dateTime1 = LocalDateTime.now().atZone(targetZone);\n\n @SuppressWarnings(\"unused\")\n private ZonedDateTime dateTime2 = LocalDateTime.now().atZone(targetZone);\n\n @SuppressWarnings(\"unused\")\n private ZonedDateTime dateTime3 = ZonedDateTime.now();\n\n public DateTimePage() {\n Form form = new Form<>(\"form\");\n this.add(form);\n form.add(new ZoneDropDownChoice(\"zoneSelect\"));\n // Dropdown for selecting locale\n form.add(new LocaleDropDownChoice(\"localeSelect\"));\n // Link to return to default locale\n form.add(new Link(\"defaultLocaleLink\") {\n\n private static final long serialVersionUID = 1L;\n\n public void onClick() {\n WebRequest request = (WebRequest) getRequest();\n getSession().setLocale(request.getLocale());\n }\n });\n form.add(new TimeField(\"time1\", new PropertyModel<>(this, \"time1\")) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected boolean use12HourFormat() {\n return true;\n }\n });\n form.add(new TimeField(\"time2\", new PropertyModel<>(this, \"time2\")) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected boolean use12HourFormat() {\n return false;\n }\n });\n final LocalDateTextField dateField = new LocalDateTextField(\"date\", new PropertyModel<>(this, \"date\"), \"dd-MM-yyyy\", \"d-M-yyyy\");\n form.add(dateField);\n final LocalDateTimeField datetimeField0 = new LocalDateTimeField(\"datetime0\", new PropertyModel<>(this, \"dateTime0\")) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected LocalTime getDefaultTime() {\n return LocalTime.of(0, 0);\n }\n };\n form.add(datetimeField0);\n IModel zonedDateTime1 = new PropertyModel<>(this, \"dateTime1\");\n final LocalDateTimeField datetimeField1 = new LocalDateTimeField(\"datetime1\", new ZonedToLocalDateTimeModel(zonedDateTime1) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected ZoneId getClientTimeZone() {\n return clientZone;\n }\n\n @Override\n protected ZoneId getTargetTimeZone() {\n return targetZone;\n }\n });\n form.add(datetimeField1);\n form.add(new Label(\"datetime1-label\", zonedDateTime1));\n IModel zonedDateTime2 = new PropertyModel<>(this, \"dateTime2\");\n LocalDateTimeTextField datetimeField2 = new LocalDateTimeTextField(\"datetime2\", new ZonedToLocalDateTimeModel(zonedDateTime2) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected ZoneId getClientTimeZone() {\n return clientZone;\n }\n\n @Override\n protected ZoneId getTargetTimeZone() {\n return targetZone;\n }\n }, FormatStyle.SHORT, FormatStyle.SHORT);\n form.add(datetimeField2);\n form.add(new Label(\"datetime2-label\", zonedDateTime2));\n final ZonedDateTimeField datetimeField3 = new ZonedDateTimeField(\"datetime3\", new PropertyModel<>(this, \"dateTime3\"));\n form.add(datetimeField3);\n final FeedbackPanel feedback = new FeedbackPanel(\"feedback\");\n form.add(feedback);\n form.add(new Button(\"submit\"));\n }\n\n @Override\n protected void onInitialize() {\n super.onInitialize();\n clientZone = ((WebClientInfo) Session.get().getClientInfo()).getProperties().getTimeZone().toZoneId();\n }\n\n private final class LocaleChoiceRenderer implements IChoiceRenderer {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public Object getDisplayValue(Locale locale) {\n return locale.getDisplayName(getLocale());\n }\n }\n\n /**\n * Dropdown with Locales.\n */\n private final class LocaleDropDownChoice extends DropDownChoice {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * Construct.\n *\n * @param id\n * component id\n */\n public LocaleDropDownChoice(String id) {\n super(id, FormInputApplication.LOCALES, new LocaleChoiceRenderer());\n setModel(new PropertyModel<>(this, \"session.locale\"));\n add(new FormComponentUpdatingBehavior() {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected void onUpdate() {\n setResponsePage(getPage().getClass());\n }\n });\n }\n }\n\n private class ZoneDropDownChoice extends DropDownChoice {\n\n private static final long serialVersionUID = 1L;\n\n public ZoneDropDownChoice(String id) {\n super(id, new IModel>() {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public List getObject() {\n return ZoneId.getAvailableZoneIds().stream().map(id -> ZoneId.of(id)).collect(Collectors.toList());\n }\n });\n setModel(new PropertyModel(DateTimePage.this, \"clientZone\"));\n setChoiceRenderer(new IChoiceRenderer() {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public Object getDisplayValue(ZoneId object) {\n String name = object.getDisplayName(TextStyle.FULL, getLocale());\n ZoneOffset offset = LocalDateTime.now().atZone(object).getOffset();\n return name + offset;\n }\n\n @Override\n public String getIdValue(ZoneId object, int index) {\n return object.getId();\n }\n\n @Override\n public ZoneId getObject(String id, IModel> choices) ", "post_mask_code": "\n });\n add(new FormComponentUpdatingBehavior() {\n\n private static final long serialVersionUID = 1L;\n\n protected void onUpdate() {\n // clear raw input of all inputs so that values are reformatted\n getForm().clearInput();\n }\n });\n }\n }\n}\n"} {"task_id": "Java_2589", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/wicket/wicket-examples/src/main/java/org/apache/wicket/examples/datetime/DateTimePage.java", "mask_start_position": 3123, "mask_end_position": 3127, "canonical_solution": "());", "pre_mask_code": "package org.apache.wicket.examples.datetime;\n\nimport java.time.LocalDate;\nimport java.time.LocalDateTime;\nimport java.time.LocalTime;\nimport java.time.ZoneId;\nimport java.time.ZoneOffset;\nimport java.time.ZonedDateTime;\nimport java.time.format.FormatStyle;\nimport java.time.format.TextStyle;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.stream.Collectors;\nimport org.apache.wicket.Session;\nimport org.apache.wicket.examples.WicketExamplePage;\nimport org.apache.wicket.examples.forminput.FormInputApplication;\nimport org.apache.wicket.extensions.markup.html.form.datetime.LocalDateTextField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.LocalDateTimeField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.LocalDateTimeTextField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.TimeField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.ZonedDateTimeField;\nimport org.apache.wicket.extensions.markup.html.form.datetime.ZonedToLocalDateTimeModel;\nimport org.apache.wicket.markup.html.basic.Label;\nimport org.apache.wicket.markup.html.form.Button;\nimport org.apache.wicket.markup.html.form.DropDownChoice;\nimport org.apache.wicket.markup.html.form.Form;\nimport org.apache.wicket.markup.html.form.FormComponentUpdatingBehavior;\nimport org.apache.wicket.markup.html.form.IChoiceRenderer;\nimport org.apache.wicket.markup.html.link.Link;\nimport org.apache.wicket.markup.html.panel.FeedbackPanel;\nimport org.apache.wicket.model.IModel;\nimport org.apache.wicket.model.PropertyModel;\nimport org.apache.wicket.protocol.http.request.WebClientInfo;\nimport org.apache.wicket.request.http.WebRequest;\n\n/**\n * DateTime example page.\n */\npublic class DateTimePage extends WicketExamplePage {\n\n private static final long serialVersionUID = 1L;\n\n private ZoneId clientZone;\n\n private ZoneId targetZone = ZoneId.of(\"UTC+8\");\n\n @SuppressWarnings(\"unused\")\n private LocalTime time1 = LocalTime.of(22, 15);\n\n @SuppressWarnings(\"unused\")\n private LocalTime time2 = LocalTime.of(22, 15);\n\n @SuppressWarnings(\"unused\")\n private LocalDate date = LocalDate.now();\n\n @SuppressWarnings(\"unused\")\n private LocalDateTime dateTime0 = LocalDateTime.now();\n\n @SuppressWarnings(\"unused\")\n private ZonedDateTime dateTime1 = LocalDateTime.now().atZone(targetZone);\n\n @SuppressWarnings(\"unused\")\n private ZonedDateTime dateTime2 = LocalDateTime.now().atZone(targetZone);\n\n @SuppressWarnings(\"unused\")\n private ZonedDateTime dateTime3 = ZonedDateTime.now();\n\n public DateTimePage() {\n Form form = new Form<>(\"form\");\n this.add(form);\n form.add(new ZoneDropDownChoice(\"zoneSelect\"));\n // Dropdown for selecting locale\n form.add(new LocaleDropDownChoice(\"localeSelect\"));\n // Link to return to default locale\n form.add(new Link(\"defaultLocaleLink\") {\n\n private static final long serialVersionUID = 1L;\n\n public void onClick() {\n WebRequest request = (WebRequest) getRequest();\n getSession().setLocale(request.getLocale", "post_mask_code": "\n }\n });\n form.add(new TimeField(\"time1\", new PropertyModel<>(this, \"time1\")) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected boolean use12HourFormat() {\n return true;\n }\n });\n form.add(new TimeField(\"time2\", new PropertyModel<>(this, \"time2\")) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected boolean use12HourFormat() {\n return false;\n }\n });\n final LocalDateTextField dateField = new LocalDateTextField(\"date\", new PropertyModel<>(this, \"date\"), \"dd-MM-yyyy\", \"d-M-yyyy\");\n form.add(dateField);\n final LocalDateTimeField datetimeField0 = new LocalDateTimeField(\"datetime0\", new PropertyModel<>(this, \"dateTime0\")) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected LocalTime getDefaultTime() {\n return LocalTime.of(0, 0);\n }\n };\n form.add(datetimeField0);\n IModel zonedDateTime1 = new PropertyModel<>(this, \"dateTime1\");\n final LocalDateTimeField datetimeField1 = new LocalDateTimeField(\"datetime1\", new ZonedToLocalDateTimeModel(zonedDateTime1) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected ZoneId getClientTimeZone() {\n return clientZone;\n }\n\n @Override\n protected ZoneId getTargetTimeZone() {\n return targetZone;\n }\n });\n form.add(datetimeField1);\n form.add(new Label(\"datetime1-label\", zonedDateTime1));\n IModel zonedDateTime2 = new PropertyModel<>(this, \"dateTime2\");\n LocalDateTimeTextField datetimeField2 = new LocalDateTimeTextField(\"datetime2\", new ZonedToLocalDateTimeModel(zonedDateTime2) {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected ZoneId getClientTimeZone() {\n return clientZone;\n }\n\n @Override\n protected ZoneId getTargetTimeZone() {\n return targetZone;\n }\n }, FormatStyle.SHORT, FormatStyle.SHORT);\n form.add(datetimeField2);\n form.add(new Label(\"datetime2-label\", zonedDateTime2));\n final ZonedDateTimeField datetimeField3 = new ZonedDateTimeField(\"datetime3\", new PropertyModel<>(this, \"dateTime3\"));\n form.add(datetimeField3);\n final FeedbackPanel feedback = new FeedbackPanel(\"feedback\");\n form.add(feedback);\n form.add(new Button(\"submit\"));\n }\n\n @Override\n protected void onInitialize() {\n super.onInitialize();\n clientZone = ((WebClientInfo) Session.get().getClientInfo()).getProperties().getTimeZone().toZoneId();\n }\n\n private final class LocaleChoiceRenderer implements IChoiceRenderer {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public Object getDisplayValue(Locale locale) {\n return locale.getDisplayName(getLocale());\n }\n }\n\n /**\n * Dropdown with Locales.\n */\n private final class LocaleDropDownChoice extends DropDownChoice {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * Construct.\n *\n * @param id\n * component id\n */\n public LocaleDropDownChoice(String id) {\n super(id, FormInputApplication.LOCALES, new LocaleChoiceRenderer());\n setModel(new PropertyModel<>(this, \"session.locale\"));\n add(new FormComponentUpdatingBehavior() {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n protected void onUpdate() {\n setResponsePage(getPage().getClass());\n }\n });\n }\n }\n\n private class ZoneDropDownChoice extends DropDownChoice {\n\n private static final long serialVersionUID = 1L;\n\n public ZoneDropDownChoice(String id) {\n super(id, new IModel>() {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public List getObject() {\n return ZoneId.getAvailableZoneIds().stream().map(id -> ZoneId.of(id)).collect(Collectors.toList());\n }\n });\n setModel(new PropertyModel(DateTimePage.this, \"clientZone\"));\n setChoiceRenderer(new IChoiceRenderer() {\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public Object getDisplayValue(ZoneId object) {\n String name = object.getDisplayName(TextStyle.FULL, getLocale());\n ZoneOffset offset = LocalDateTime.now().atZone(object).getOffset();\n return name + offset;\n }\n\n @Override\n public String getIdValue(ZoneId object, int index) {\n return object.getId();\n }\n\n @Override\n public ZoneId getObject(String id, IModel> choices) {\n return ZoneId.of(id);\n }\n });\n add(new FormComponentUpdatingBehavior() {\n\n private static final long serialVersionUID = 1L;\n\n protected void onUpdate() {\n // clear raw input of all inputs so that values are reformatted\n getForm().clearInput();\n }\n });\n }\n }\n}\n"} {"task_id": "Java_2590", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Tencent/bk-job/src/backend/job-gateway/src/main/java/com/tencent/bk/job/gateway/service/impl/EsbJwtServiceImpl.java", "mask_start_position": 2293, "mask_end_position": 2415, "canonical_solution": "private PublicKey buildPublicKey(String pemContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException ", "pre_mask_code": "/*\n * Tencent is pleased to support the open source community by making BK-JOB蓝鲸智云作业平台 available.\n *\n *\n *\n * License for BK-JOB蓝鲸智云作业平台:\n * --------------------------------------------------------------------\n */\npackage com.tencent.bk.job.gateway.service.impl;\n\nimport com.google.common.cache.Cache;\nimport com.google.common.cache.CacheBuilder;\nimport com.tencent.bk.job.gateway.model.esb.EsbJwtInfo;\nimport com.tencent.bk.job.gateway.service.EsbJwtPublicKeyService;\nimport com.tencent.bk.job.gateway.service.EsbJwtService;\nimport io.jsonwebtoken.Claims;\nimport io.jsonwebtoken.Jwts;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.bouncycastle.util.io.pem.PemObject;\nimport org.bouncycastle.util.io.pem.PemReader;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport java.io.IOException;\nimport java.io.StringReader;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PublicKey;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.X509EncodedKeySpec;\nimport java.time.Instant;\nimport java.util.Date;\nimport java.util.LinkedHashMap;\nimport java.util.concurrent.TimeUnit;\n\n@Service\n@Slf4j\npublic class EsbJwtServiceImpl implements EsbJwtService {\n\n private final EsbJwtPublicKeyService esbJwtPublicKeyService;\n\n private PublicKey publicKey;\n\n private final Cache tokenCache = CacheBuilder.newBuilder().maximumSize(99999).expireAfterWrite(30, TimeUnit.SECONDS).build();\n\n @Autowired\n public EsbJwtServiceImpl(EsbJwtPublicKeyService esbJwtPublicKeyService) {\n this.esbJwtPublicKeyService = esbJwtPublicKeyService;\n getAndCachePublicKey();\n }\n\n private void getAndCachePublicKey() {\n try {\n String esbJwtPublicKey = esbJwtPublicKeyService.getEsbJWTPublicKey();\n if (StringUtils.isEmpty(esbJwtPublicKey)) {\n log.error(\"Esb jwt public key is not configured!\");\n return;\n }\n this.publicKey = buildPublicKey(esbJwtPublicKey);\n } catch (Throwable e) {\n // Catch all exception\n log.error(\"Build esb jwt public key caught error!\", e);\n }\n }\n\n ", "post_mask_code": "{\n PemReader pemReader = new PemReader(new StringReader(pemContent));\n PemObject pemObject = pemReader.readPemObject();\n if (pemObject == null) {\n log.error(\"Esb public key pem is illegal!\");\n return null;\n }\n java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());\n X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pemObject.getContent());\n KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n return keyFactory.generatePublic(pubKeySpec);\n }\n\n @Override\n public EsbJwtInfo extractFromJwt(String token) {\n long start = System.currentTimeMillis();\n EsbJwtInfo cacheJwtInfo = tokenCache.getIfPresent(token);\n if (cacheJwtInfo != null) {\n Long tokenExpireAt = cacheJwtInfo.getTokenExpireAt();\n // 如果未超时\n if (tokenExpireAt > Instant.now().getEpochSecond()) {\n return cacheJwtInfo;\n }\n }\n EsbJwtInfo esbJwtInfo;\n try {\n Claims claims = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token).getBody();\n String appCode = \"\";\n if (claims.get(\"app\") != null) {\n LinkedHashMap appProps = claims.get(\"app\", LinkedHashMap.class);\n if (appProps == null) {\n log.warn(\"Invalid JWT token, app is null!\");\n return null;\n }\n boolean isVerified = appProps.get(\"verified\") != null && (boolean) appProps.get(\"verified\");\n appCode = (String) appProps.get(\"app_code\");\n if (StringUtils.isEmpty(appCode)) {\n appCode = (String) appProps.get(\"bk_app_code\");\n }\n if (!isVerified || StringUtils.isEmpty(appCode)) {\n log.warn(\"App code not verified or empty, isVerified:{}, jwtAppCode:{}\", isVerified, appCode);\n return null;\n }\n }\n String username = \"\";\n if (claims.get(\"user\") != null) {\n LinkedHashMap userProps = claims.get(\"user\", LinkedHashMap.class);\n if (userProps == null) {\n log.warn(\"Invalid JWT token, user is null!\");\n return null;\n }\n username = (String) userProps.get(\"username\");\n if (StringUtils.isEmpty(username)) {\n username = (String) userProps.get(\"bk_username\");\n }\n if (StringUtils.isEmpty(username)) {\n log.warn(\"Username is empty!\");\n return null;\n }\n }\n Date expireAt = claims.get(\"exp\", Date.class);\n if (expireAt == null) {\n log.warn(\"Invalid JWT token, exp is null!\");\n return null;\n }\n esbJwtInfo = new EsbJwtInfo(expireAt.getTime(), username, appCode);\n tokenCache.put(token, esbJwtInfo);\n } catch (Exception e) {\n log.warn(\"Verify jwt caught exception\", e);\n return null;\n } finally {\n long cost = System.currentTimeMillis() - start;\n if (cost > 10) {\n log.warn(\"Verify jwt cost too much, cost:{}\", cost);\n }\n }\n return esbJwtInfo;\n }\n}\n"} {"task_id": "Java_2591", "language": "Java", "task_type": "method_body", "source_file": "java/github/Tencent/bk-job/src/backend/job-gateway/src/main/java/com/tencent/bk/job/gateway/service/impl/EsbJwtServiceImpl.java", "mask_start_position": 1815, "mask_end_position": 2287, "canonical_solution": "{\n try {\n String esbJwtPublicKey = esbJwtPublicKeyService.getEsbJWTPublicKey();\n if (StringUtils.isEmpty(esbJwtPublicKey)) {\n log.error(\"Esb jwt public key is not configured!\");\n return;\n }\n this.publicKey = buildPublicKey(esbJwtPublicKey);\n } catch (Throwable e) {\n // Catch all exception\n log.error(\"Build esb jwt public key caught error!\", e);\n }\n }", "pre_mask_code": "/*\n * Tencent is pleased to support the open source community by making BK-JOB蓝鲸智云作业平台 available.\n *\n *\n *\n * License for BK-JOB蓝鲸智云作业平台:\n * --------------------------------------------------------------------\n */\npackage com.tencent.bk.job.gateway.service.impl;\n\nimport com.google.common.cache.Cache;\nimport com.google.common.cache.CacheBuilder;\nimport com.tencent.bk.job.gateway.model.esb.EsbJwtInfo;\nimport com.tencent.bk.job.gateway.service.EsbJwtPublicKeyService;\nimport com.tencent.bk.job.gateway.service.EsbJwtService;\nimport io.jsonwebtoken.Claims;\nimport io.jsonwebtoken.Jwts;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.bouncycastle.util.io.pem.PemObject;\nimport org.bouncycastle.util.io.pem.PemReader;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport java.io.IOException;\nimport java.io.StringReader;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PublicKey;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.X509EncodedKeySpec;\nimport java.time.Instant;\nimport java.util.Date;\nimport java.util.LinkedHashMap;\nimport java.util.concurrent.TimeUnit;\n\n@Service\n@Slf4j\npublic class EsbJwtServiceImpl implements EsbJwtService {\n\n private final EsbJwtPublicKeyService esbJwtPublicKeyService;\n\n private PublicKey publicKey;\n\n private final Cache tokenCache = CacheBuilder.newBuilder().maximumSize(99999).expireAfterWrite(30, TimeUnit.SECONDS).build();\n\n @Autowired\n public EsbJwtServiceImpl(EsbJwtPublicKeyService esbJwtPublicKeyService) {\n this.esbJwtPublicKeyService = esbJwtPublicKeyService;\n getAndCachePublicKey();\n }\n\n private void getAndCachePublicKey() ", "post_mask_code": "\n\n private PublicKey buildPublicKey(String pemContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {\n PemReader pemReader = new PemReader(new StringReader(pemContent));\n PemObject pemObject = pemReader.readPemObject();\n if (pemObject == null) {\n log.error(\"Esb public key pem is illegal!\");\n return null;\n }\n java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());\n X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pemObject.getContent());\n KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n return keyFactory.generatePublic(pubKeySpec);\n }\n\n @Override\n public EsbJwtInfo extractFromJwt(String token) {\n long start = System.currentTimeMillis();\n EsbJwtInfo cacheJwtInfo = tokenCache.getIfPresent(token);\n if (cacheJwtInfo != null) {\n Long tokenExpireAt = cacheJwtInfo.getTokenExpireAt();\n // 如果未超时\n if (tokenExpireAt > Instant.now().getEpochSecond()) {\n return cacheJwtInfo;\n }\n }\n EsbJwtInfo esbJwtInfo;\n try {\n Claims claims = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token).getBody();\n String appCode = \"\";\n if (claims.get(\"app\") != null) {\n LinkedHashMap appProps = claims.get(\"app\", LinkedHashMap.class);\n if (appProps == null) {\n log.warn(\"Invalid JWT token, app is null!\");\n return null;\n }\n boolean isVerified = appProps.get(\"verified\") != null && (boolean) appProps.get(\"verified\");\n appCode = (String) appProps.get(\"app_code\");\n if (StringUtils.isEmpty(appCode)) {\n appCode = (String) appProps.get(\"bk_app_code\");\n }\n if (!isVerified || StringUtils.isEmpty(appCode)) {\n log.warn(\"App code not verified or empty, isVerified:{}, jwtAppCode:{}\", isVerified, appCode);\n return null;\n }\n }\n String username = \"\";\n if (claims.get(\"user\") != null) {\n LinkedHashMap userProps = claims.get(\"user\", LinkedHashMap.class);\n if (userProps == null) {\n log.warn(\"Invalid JWT token, user is null!\");\n return null;\n }\n username = (String) userProps.get(\"username\");\n if (StringUtils.isEmpty(username)) {\n username = (String) userProps.get(\"bk_username\");\n }\n if (StringUtils.isEmpty(username)) {\n log.warn(\"Username is empty!\");\n return null;\n }\n }\n Date expireAt = claims.get(\"exp\", Date.class);\n if (expireAt == null) {\n log.warn(\"Invalid JWT token, exp is null!\");\n return null;\n }\n esbJwtInfo = new EsbJwtInfo(expireAt.getTime(), username, appCode);\n tokenCache.put(token, esbJwtInfo);\n } catch (Exception e) {\n log.warn(\"Verify jwt caught exception\", e);\n return null;\n } finally {\n long cost = System.currentTimeMillis() - start;\n if (cost > 10) {\n log.warn(\"Verify jwt cost too much, cost:{}\", cost);\n }\n }\n return esbJwtInfo;\n }\n}\n"} {"task_id": "Java_2592", "language": "Java", "task_type": "single_line", "source_file": "java/github/Tencent/bk-job/src/backend/job-gateway/src/main/java/com/tencent/bk/job/gateway/service/impl/EsbJwtServiceImpl.java", "mask_start_position": 5779, "mask_end_position": 5797, "canonical_solution": "return esbJwtInfo;", "pre_mask_code": "/*\n * Tencent is pleased to support the open source community by making BK-JOB蓝鲸智云作业平台 available.\n *\n *\n *\n * License for BK-JOB蓝鲸智云作业平台:\n * --------------------------------------------------------------------\n */\npackage com.tencent.bk.job.gateway.service.impl;\n\nimport com.google.common.cache.Cache;\nimport com.google.common.cache.CacheBuilder;\nimport com.tencent.bk.job.gateway.model.esb.EsbJwtInfo;\nimport com.tencent.bk.job.gateway.service.EsbJwtPublicKeyService;\nimport com.tencent.bk.job.gateway.service.EsbJwtService;\nimport io.jsonwebtoken.Claims;\nimport io.jsonwebtoken.Jwts;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.bouncycastle.util.io.pem.PemObject;\nimport org.bouncycastle.util.io.pem.PemReader;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport java.io.IOException;\nimport java.io.StringReader;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PublicKey;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.X509EncodedKeySpec;\nimport java.time.Instant;\nimport java.util.Date;\nimport java.util.LinkedHashMap;\nimport java.util.concurrent.TimeUnit;\n\n@Service\n@Slf4j\npublic class EsbJwtServiceImpl implements EsbJwtService {\n\n private final EsbJwtPublicKeyService esbJwtPublicKeyService;\n\n private PublicKey publicKey;\n\n private final Cache tokenCache = CacheBuilder.newBuilder().maximumSize(99999).expireAfterWrite(30, TimeUnit.SECONDS).build();\n\n @Autowired\n public EsbJwtServiceImpl(EsbJwtPublicKeyService esbJwtPublicKeyService) {\n this.esbJwtPublicKeyService = esbJwtPublicKeyService;\n getAndCachePublicKey();\n }\n\n private void getAndCachePublicKey() {\n try {\n String esbJwtPublicKey = esbJwtPublicKeyService.getEsbJWTPublicKey();\n if (StringUtils.isEmpty(esbJwtPublicKey)) {\n log.error(\"Esb jwt public key is not configured!\");\n return;\n }\n this.publicKey = buildPublicKey(esbJwtPublicKey);\n } catch (Throwable e) {\n // Catch all exception\n log.error(\"Build esb jwt public key caught error!\", e);\n }\n }\n\n private PublicKey buildPublicKey(String pemContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {\n PemReader pemReader = new PemReader(new StringReader(pemContent));\n PemObject pemObject = pemReader.readPemObject();\n if (pemObject == null) {\n log.error(\"Esb public key pem is illegal!\");\n return null;\n }\n java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());\n X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pemObject.getContent());\n KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n return keyFactory.generatePublic(pubKeySpec);\n }\n\n @Override\n public EsbJwtInfo extractFromJwt(String token) {\n long start = System.currentTimeMillis();\n EsbJwtInfo cacheJwtInfo = tokenCache.getIfPresent(token);\n if (cacheJwtInfo != null) {\n Long tokenExpireAt = cacheJwtInfo.getTokenExpireAt();\n // 如果未超时\n if (tokenExpireAt > Instant.now().getEpochSecond()) {\n return cacheJwtInfo;\n }\n }\n EsbJwtInfo esbJwtInfo;\n try {\n Claims claims = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token).getBody();\n String appCode = \"\";\n if (claims.get(\"app\") != null) {\n LinkedHashMap appProps = claims.get(\"app\", LinkedHashMap.class);\n if (appProps == null) {\n log.warn(\"Invalid JWT token, app is null!\");\n return null;\n }\n boolean isVerified = appProps.get(\"verified\") != null && (boolean) appProps.get(\"verified\");\n appCode = (String) appProps.get(\"app_code\");\n if (StringUtils.isEmpty(appCode)) {\n appCode = (String) appProps.get(\"bk_app_code\");\n }\n if (!isVerified || StringUtils.isEmpty(appCode)) {\n log.warn(\"App code not verified or empty, isVerified:{}, jwtAppCode:{}\", isVerified, appCode);\n return null;\n }\n }\n String username = \"\";\n if (claims.get(\"user\") != null) {\n LinkedHashMap userProps = claims.get(\"user\", LinkedHashMap.class);\n if (userProps == null) {\n log.warn(\"Invalid JWT token, user is null!\");\n return null;\n }\n username = (String) userProps.get(\"username\");\n if (StringUtils.isEmpty(username)) {\n username = (String) userProps.get(\"bk_username\");\n }\n if (StringUtils.isEmpty(username)) {\n log.warn(\"Username is empty!\");\n return null;\n }\n }\n Date expireAt = claims.get(\"exp\", Date.class);\n if (expireAt == null) {\n log.warn(\"Invalid JWT token, exp is null!\");\n return null;\n }\n esbJwtInfo = new EsbJwtInfo(expireAt.getTime(), username, appCode);\n tokenCache.put(token, esbJwtInfo);\n } catch (Exception e) {\n log.warn(\"Verify jwt caught exception\", e);\n return null;\n } finally {\n long cost = System.currentTimeMillis() - start;\n if (cost > 10) {\n log.warn(\"Verify jwt cost too much, cost:{}\", cost);\n }\n }\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2593", "language": "Java", "task_type": "try_statement", "source_file": "java/github/Tencent/bk-job/src/backend/job-gateway/src/main/java/com/tencent/bk/job/gateway/service/impl/EsbJwtServiceImpl.java", "mask_start_position": 1825, "mask_end_position": 2281, "canonical_solution": "try {\n String esbJwtPublicKey = esbJwtPublicKeyService.getEsbJWTPublicKey();\n if (StringUtils.isEmpty(esbJwtPublicKey)) {\n log.error(\"Esb jwt public key is not configured!\");\n return;\n }\n this.publicKey = buildPublicKey(esbJwtPublicKey);\n } catch (Throwable e) {\n // Catch all exception\n log.error(\"Build esb jwt public key caught error!\", e);\n }", "pre_mask_code": "/*\n * Tencent is pleased to support the open source community by making BK-JOB蓝鲸智云作业平台 available.\n *\n *\n *\n * License for BK-JOB蓝鲸智云作业平台:\n * --------------------------------------------------------------------\n */\npackage com.tencent.bk.job.gateway.service.impl;\n\nimport com.google.common.cache.Cache;\nimport com.google.common.cache.CacheBuilder;\nimport com.tencent.bk.job.gateway.model.esb.EsbJwtInfo;\nimport com.tencent.bk.job.gateway.service.EsbJwtPublicKeyService;\nimport com.tencent.bk.job.gateway.service.EsbJwtService;\nimport io.jsonwebtoken.Claims;\nimport io.jsonwebtoken.Jwts;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.bouncycastle.util.io.pem.PemObject;\nimport org.bouncycastle.util.io.pem.PemReader;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport java.io.IOException;\nimport java.io.StringReader;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PublicKey;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.X509EncodedKeySpec;\nimport java.time.Instant;\nimport java.util.Date;\nimport java.util.LinkedHashMap;\nimport java.util.concurrent.TimeUnit;\n\n@Service\n@Slf4j\npublic class EsbJwtServiceImpl implements EsbJwtService {\n\n private final EsbJwtPublicKeyService esbJwtPublicKeyService;\n\n private PublicKey publicKey;\n\n private final Cache tokenCache = CacheBuilder.newBuilder().maximumSize(99999).expireAfterWrite(30, TimeUnit.SECONDS).build();\n\n @Autowired\n public EsbJwtServiceImpl(EsbJwtPublicKeyService esbJwtPublicKeyService) {\n this.esbJwtPublicKeyService = esbJwtPublicKeyService;\n getAndCachePublicKey();\n }\n\n private void getAndCachePublicKey() {\n ", "post_mask_code": "\n }\n\n private PublicKey buildPublicKey(String pemContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {\n PemReader pemReader = new PemReader(new StringReader(pemContent));\n PemObject pemObject = pemReader.readPemObject();\n if (pemObject == null) {\n log.error(\"Esb public key pem is illegal!\");\n return null;\n }\n java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());\n X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pemObject.getContent());\n KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n return keyFactory.generatePublic(pubKeySpec);\n }\n\n @Override\n public EsbJwtInfo extractFromJwt(String token) {\n long start = System.currentTimeMillis();\n EsbJwtInfo cacheJwtInfo = tokenCache.getIfPresent(token);\n if (cacheJwtInfo != null) {\n Long tokenExpireAt = cacheJwtInfo.getTokenExpireAt();\n // 如果未超时\n if (tokenExpireAt > Instant.now().getEpochSecond()) {\n return cacheJwtInfo;\n }\n }\n EsbJwtInfo esbJwtInfo;\n try {\n Claims claims = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token).getBody();\n String appCode = \"\";\n if (claims.get(\"app\") != null) {\n LinkedHashMap appProps = claims.get(\"app\", LinkedHashMap.class);\n if (appProps == null) {\n log.warn(\"Invalid JWT token, app is null!\");\n return null;\n }\n boolean isVerified = appProps.get(\"verified\") != null && (boolean) appProps.get(\"verified\");\n appCode = (String) appProps.get(\"app_code\");\n if (StringUtils.isEmpty(appCode)) {\n appCode = (String) appProps.get(\"bk_app_code\");\n }\n if (!isVerified || StringUtils.isEmpty(appCode)) {\n log.warn(\"App code not verified or empty, isVerified:{}, jwtAppCode:{}\", isVerified, appCode);\n return null;\n }\n }\n String username = \"\";\n if (claims.get(\"user\") != null) {\n LinkedHashMap userProps = claims.get(\"user\", LinkedHashMap.class);\n if (userProps == null) {\n log.warn(\"Invalid JWT token, user is null!\");\n return null;\n }\n username = (String) userProps.get(\"username\");\n if (StringUtils.isEmpty(username)) {\n username = (String) userProps.get(\"bk_username\");\n }\n if (StringUtils.isEmpty(username)) {\n log.warn(\"Username is empty!\");\n return null;\n }\n }\n Date expireAt = claims.get(\"exp\", Date.class);\n if (expireAt == null) {\n log.warn(\"Invalid JWT token, exp is null!\");\n return null;\n }\n esbJwtInfo = new EsbJwtInfo(expireAt.getTime(), username, appCode);\n tokenCache.put(token, esbJwtInfo);\n } catch (Exception e) {\n log.warn(\"Verify jwt caught exception\", e);\n return null;\n } finally {\n long cost = System.currentTimeMillis() - start;\n if (cost > 10) {\n log.warn(\"Verify jwt cost too much, cost:{}\", cost);\n }\n }\n return esbJwtInfo;\n }\n}\n"} {"task_id": "Java_2594", "language": "Java", "task_type": "method_signature", "source_file": "java/github/gemini-projects/gemini/gemini-core/src/main/java/it/at7/gemini/api/openapi/OpenApiServiceImpl.java", "mask_start_position": 5846, "mask_end_position": 5926, "canonical_solution": "private void storeOpenAPISchema(OpenAPIBuilder openAPIBuilder, String fileName) ", "pre_mask_code": "package it.at7.gemini.api.openapi;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLFactory;\nimport it.at7.gemini.conf.State;\nimport it.at7.gemini.core.*;\nimport it.at7.gemini.exceptions.GeminiException;\nimport it.at7.gemini.exceptions.GeminiRuntimeException;\nimport it.at7.gemini.schema.Entity;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.core.env.Environment;\nimport org.springframework.core.io.Resource;\nimport org.springframework.stereotype.Service;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\nimport java.util.*;\nimport java.util.function.Consumer;\nimport java.util.stream.Collectors;\n\n@Service\npublic class OpenApiServiceImpl implements OpenApiService, StateListener {\n\n private static final String SERVICE_INFO_DEFAULT_RESOURCE = \"classpath:/service/default-info.yml\";\n\n private final GeminiConfigurationService configurationService;\n\n private final StateManager stateManager;\n\n private final SchemaManager schemaManager;\n\n private final Environment environment;\n\n private final ApplicationContext context;\n\n private List API_INITIALIZER_LISTENER = new ArrayList<>();\n\n private Map builders = new HashMap<>();\n\n @Autowired\n public OpenApiServiceImpl(GeminiConfigurationService configurationService, StateManager stateManager, SchemaManager schemaManager, Environment environment, ApplicationContext context) {\n this.configurationService = configurationService;\n this.stateManager = stateManager;\n this.schemaManager = schemaManager;\n this.environment = environment;\n this.context = context;\n if (configurationService.isOpenapiSchema()) {\n this.stateManager.register(this);\n // openapi spec withRecord all entities\n builders.put(\"ALL\", OpenAPIFile.from(new OpenAPIBuilder(), \"ALL\", \"all.json\"));\n // entities by module... in each dedicated file\n schemaManager.getAllModules().forEach(m -> {\n String moduleName = m.getName().toUpperCase();\n builders.put(moduleName, OpenAPIFile.from(new OpenAPIBuilder(false), moduleName, moduleName.toLowerCase() + \".json\"));\n });\n }\n }\n\n private void createDefaultServiceInfoResource(File serviceInfoResource) throws IOException {\n Resource defaultInfoService = context.getResource(SERVICE_INFO_DEFAULT_RESOURCE);\n serviceInfoResource.getParentFile().mkdirs();\n Files.copy(defaultInfoService.getInputStream(), serviceInfoResource.toPath(), StandardCopyOption.REPLACE_EXISTING);\n }\n\n @Override\n public void onChange(State previous, State actual, Optional transaction) throws GeminiException {\n if (configurationService.isOpenapiSchema()) {\n switch(actual) {\n case API_INITIALIZATION:\n loadServiceInfo();\n makeOpenAPISchema();\n break;\n case API_INITIALIZED:\n API_INITIALIZER_LISTENER.forEach(Runnable::run);\n String localPort = environment.getProperty(\"local.server.port\");\n iterateOverBuilders(b -> b.builder.addServer(\"http://127.0.0.1:\" + localPort + \"/api\", \"Local Server\"));\n iterateOverBuilders(b -> storeOpenAPISchema(b.builder, b.fileName));\n break;\n default:\n break;\n }\n }\n }\n\n private void loadServiceInfo() {\n try {\n File serviceInfoFile = new File(configurationService.getServiceInfoResource());\n if (!serviceInfoFile.exists()) {\n createDefaultServiceInfoResource(serviceInfoFile);\n }\n ObjectMapper mapper = new ObjectMapper(new YAMLFactory());\n GeminiServiceInfoWrapper geminiService = mapper.readValue(serviceInfoFile, GeminiServiceInfoWrapper.class);\n iterateOverBuilders(b -> b.builder.addInfo(geminiService.info));\n } catch (IOException e) {\n throw new GeminiRuntimeException(e);\n }\n }\n\n private void makeOpenAPISchema() {\n Collection allEntities = this.schemaManager.getAllEntities();\n Map> entitiesByModule = allEntities.stream().collect(Collectors.groupingBy(Entity::getModule));\n List orderedModules = entitiesByModule.keySet().stream().sorted(Comparator.comparingInt(ModuleBase::order)).collect(Collectors.toList());\n OpenAPIBuilder allEntityBuilder = this.builders.get(\"ALL\").builder;\n allEntityBuilder.addModulesToTags(orderedModules);\n for (ModuleBase module : orderedModules) {\n List entities = entitiesByModule.get(module);\n entities.forEach(allEntityBuilder::handleEntity);\n String moduleName = module.getName().toUpperCase();\n OpenAPIFile openAPIFile = this.builders.get(moduleName);\n assert openAPIFile != null;\n List otherOpenApiFiles = this.builders.values().stream().filter(f -> !f.key.equals(openAPIFile.key) && !f.key.equals(\"ALL\")).collect(Collectors.toList());\n entities.forEach(e -> {\n openAPIFile.builder.handleEntity(e);\n otherOpenApiFiles.forEach(b -> b.builder.addComponentSchema(e, OpenAPIBuilder.SchemaType.ENTITY));\n if (!e.isEmbedable()) {\n otherOpenApiFiles.forEach(b -> b.builder.addComponentSchema(e, OpenAPIBuilder.SchemaType.ENTITY_LK));\n }\n });\n }\n }\n\n ", "post_mask_code": "{\n String json = openAPIBuilder.toJsonString();\n try {\n String openApiDir = configurationService.getOpenApiDir();\n Path allPath = Paths.get(openApiDir, fileName);\n File file = new File(allPath.toString());\n file.getParentFile().mkdirs();\n Files.write(allPath, json.getBytes());\n } catch (IOException e) {\n throw new GeminiRuntimeException(e);\n }\n }\n\n @Override\n public void addOAuth2PasswordFlow(String name, Map flowParameters) {\n if (configurationService.isOpenapiSchema()) {\n String tokenUrl = (String) flowParameters.get(\"tokenUrl\");\n if (tokenUrl == null || tokenUrl.equals(\"\")) {\n throw new GeminiRuntimeException(\"Unable to initializeSmartModules OAuth2 Password Flow - No tokenUrl Provided\");\n }\n OpenAPIBuilder.SecuritySchema securitySchema = new OpenAPIBuilder.SecuritySchema();\n securitySchema.type = \"oauth2\";\n securitySchema.description = (String) flowParameters.getOrDefault(\"description\", \"See http://example.com\");\n securitySchema.flows = Map.of(\"password\", Map.of(\"tokenUrl\", tokenUrl));\n iterateOverBuilders(b -> b.builder.addSecurityComponent(name, securitySchema));\n }\n }\n\n @Override\n public void secureAllEntities(String securitySchemaName) {\n if (configurationService.isOpenapiSchema()) {\n API_INITIALIZER_LISTENER.add(() -> {\n iterateOverBuilders(b -> b.builder.secureAllEntityPaths(securitySchemaName));\n });\n }\n }\n\n private void iterateOverBuilders(Consumer c) {\n this.builders.values().forEach(c);\n }\n\n static class GeminiServiceInfoWrapper {\n\n public OpenAPIBuilder.Info info;\n }\n\n static class OpenAPIFile {\n\n OpenAPIBuilder builder;\n\n String key;\n\n String fileName;\n\n public OpenAPIFile(OpenAPIBuilder builder, String key, String fileName) {\n this.builder = builder;\n this.key = key;\n this.fileName = fileName;\n }\n\n static OpenAPIFile from(OpenAPIBuilder builder, String key, String fileName) {\n return new OpenAPIFile(builder, key, fileName);\n }\n }\n}\n"} {"task_id": "Java_2595", "language": "Java", "task_type": "method_body", "source_file": "java/github/gemini-projects/gemini/gemini-core/src/main/java/it/at7/gemini/api/openapi/OpenApiServiceImpl.java", "mask_start_position": 2564, "mask_end_position": 2839, "canonical_solution": "{\n Resource defaultInfoService = context.getResource(SERVICE_INFO_DEFAULT_RESOURCE);\n serviceInfoResource.getParentFile().mkdirs();\n Files.copy(defaultInfoService.getInputStream(), serviceInfoResource.toPath(), StandardCopyOption.REPLACE_EXISTING);\n }", "pre_mask_code": "package it.at7.gemini.api.openapi;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLFactory;\nimport it.at7.gemini.conf.State;\nimport it.at7.gemini.core.*;\nimport it.at7.gemini.exceptions.GeminiException;\nimport it.at7.gemini.exceptions.GeminiRuntimeException;\nimport it.at7.gemini.schema.Entity;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.core.env.Environment;\nimport org.springframework.core.io.Resource;\nimport org.springframework.stereotype.Service;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\nimport java.util.*;\nimport java.util.function.Consumer;\nimport java.util.stream.Collectors;\n\n@Service\npublic class OpenApiServiceImpl implements OpenApiService, StateListener {\n\n private static final String SERVICE_INFO_DEFAULT_RESOURCE = \"classpath:/service/default-info.yml\";\n\n private final GeminiConfigurationService configurationService;\n\n private final StateManager stateManager;\n\n private final SchemaManager schemaManager;\n\n private final Environment environment;\n\n private final ApplicationContext context;\n\n private List API_INITIALIZER_LISTENER = new ArrayList<>();\n\n private Map builders = new HashMap<>();\n\n @Autowired\n public OpenApiServiceImpl(GeminiConfigurationService configurationService, StateManager stateManager, SchemaManager schemaManager, Environment environment, ApplicationContext context) {\n this.configurationService = configurationService;\n this.stateManager = stateManager;\n this.schemaManager = schemaManager;\n this.environment = environment;\n this.context = context;\n if (configurationService.isOpenapiSchema()) {\n this.stateManager.register(this);\n // openapi spec withRecord all entities\n builders.put(\"ALL\", OpenAPIFile.from(new OpenAPIBuilder(), \"ALL\", \"all.json\"));\n // entities by module... in each dedicated file\n schemaManager.getAllModules().forEach(m -> {\n String moduleName = m.getName().toUpperCase();\n builders.put(moduleName, OpenAPIFile.from(new OpenAPIBuilder(false), moduleName, moduleName.toLowerCase() + \".json\"));\n });\n }\n }\n\n private void createDefaultServiceInfoResource(File serviceInfoResource) throws IOException ", "post_mask_code": "\n\n @Override\n public void onChange(State previous, State actual, Optional transaction) throws GeminiException {\n if (configurationService.isOpenapiSchema()) {\n switch(actual) {\n case API_INITIALIZATION:\n loadServiceInfo();\n makeOpenAPISchema();\n break;\n case API_INITIALIZED:\n API_INITIALIZER_LISTENER.forEach(Runnable::run);\n String localPort = environment.getProperty(\"local.server.port\");\n iterateOverBuilders(b -> b.builder.addServer(\"http://127.0.0.1:\" + localPort + \"/api\", \"Local Server\"));\n iterateOverBuilders(b -> storeOpenAPISchema(b.builder, b.fileName));\n break;\n default:\n break;\n }\n }\n }\n\n private void loadServiceInfo() {\n try {\n File serviceInfoFile = new File(configurationService.getServiceInfoResource());\n if (!serviceInfoFile.exists()) {\n createDefaultServiceInfoResource(serviceInfoFile);\n }\n ObjectMapper mapper = new ObjectMapper(new YAMLFactory());\n GeminiServiceInfoWrapper geminiService = mapper.readValue(serviceInfoFile, GeminiServiceInfoWrapper.class);\n iterateOverBuilders(b -> b.builder.addInfo(geminiService.info));\n } catch (IOException e) {\n throw new GeminiRuntimeException(e);\n }\n }\n\n private void makeOpenAPISchema() {\n Collection allEntities = this.schemaManager.getAllEntities();\n Map> entitiesByModule = allEntities.stream().collect(Collectors.groupingBy(Entity::getModule));\n List orderedModules = entitiesByModule.keySet().stream().sorted(Comparator.comparingInt(ModuleBase::order)).collect(Collectors.toList());\n OpenAPIBuilder allEntityBuilder = this.builders.get(\"ALL\").builder;\n allEntityBuilder.addModulesToTags(orderedModules);\n for (ModuleBase module : orderedModules) {\n List entities = entitiesByModule.get(module);\n entities.forEach(allEntityBuilder::handleEntity);\n String moduleName = module.getName().toUpperCase();\n OpenAPIFile openAPIFile = this.builders.get(moduleName);\n assert openAPIFile != null;\n List otherOpenApiFiles = this.builders.values().stream().filter(f -> !f.key.equals(openAPIFile.key) && !f.key.equals(\"ALL\")).collect(Collectors.toList());\n entities.forEach(e -> {\n openAPIFile.builder.handleEntity(e);\n otherOpenApiFiles.forEach(b -> b.builder.addComponentSchema(e, OpenAPIBuilder.SchemaType.ENTITY));\n if (!e.isEmbedable()) {\n otherOpenApiFiles.forEach(b -> b.builder.addComponentSchema(e, OpenAPIBuilder.SchemaType.ENTITY_LK));\n }\n });\n }\n }\n\n private void storeOpenAPISchema(OpenAPIBuilder openAPIBuilder, String fileName) {\n String json = openAPIBuilder.toJsonString();\n try {\n String openApiDir = configurationService.getOpenApiDir();\n Path allPath = Paths.get(openApiDir, fileName);\n File file = new File(allPath.toString());\n file.getParentFile().mkdirs();\n Files.write(allPath, json.getBytes());\n } catch (IOException e) {\n throw new GeminiRuntimeException(e);\n }\n }\n\n @Override\n public void addOAuth2PasswordFlow(String name, Map flowParameters) {\n if (configurationService.isOpenapiSchema()) {\n String tokenUrl = (String) flowParameters.get(\"tokenUrl\");\n if (tokenUrl == null || tokenUrl.equals(\"\")) {\n throw new GeminiRuntimeException(\"Unable to initializeSmartModules OAuth2 Password Flow - No tokenUrl Provided\");\n }\n OpenAPIBuilder.SecuritySchema securitySchema = new OpenAPIBuilder.SecuritySchema();\n securitySchema.type = \"oauth2\";\n securitySchema.description = (String) flowParameters.getOrDefault(\"description\", \"See http://example.com\");\n securitySchema.flows = Map.of(\"password\", Map.of(\"tokenUrl\", tokenUrl));\n iterateOverBuilders(b -> b.builder.addSecurityComponent(name, securitySchema));\n }\n }\n\n @Override\n public void secureAllEntities(String securitySchemaName) {\n if (configurationService.isOpenapiSchema()) {\n API_INITIALIZER_LISTENER.add(() -> {\n iterateOverBuilders(b -> b.builder.secureAllEntityPaths(securitySchemaName));\n });\n }\n }\n\n private void iterateOverBuilders(Consumer c) {\n this.builders.values().forEach(c);\n }\n\n static class GeminiServiceInfoWrapper {\n\n public OpenAPIBuilder.Info info;\n }\n\n static class OpenAPIFile {\n\n OpenAPIBuilder builder;\n\n String key;\n\n String fileName;\n\n public OpenAPIFile(OpenAPIBuilder builder, String key, String fileName) {\n this.builder = builder;\n this.key = key;\n this.fileName = fileName;\n }\n\n static OpenAPIFile from(OpenAPIBuilder builder, String key, String fileName) {\n return new OpenAPIFile(builder, key, fileName);\n }\n }\n}\n"} {"task_id": "Java_2596", "language": "Java", "task_type": "single_line", "source_file": "java/github/gemini-projects/gemini/gemini-core/src/main/java/it/at7/gemini/api/openapi/OpenApiServiceImpl.java", "mask_start_position": 2589, "mask_end_position": 2655, "canonical_solution": "tInfoService = context.getResource(SERVICE_INFO_DEFAULT_RESOURCE);", "pre_mask_code": "package it.at7.gemini.api.openapi;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLFactory;\nimport it.at7.gemini.conf.State;\nimport it.at7.gemini.core.*;\nimport it.at7.gemini.exceptions.GeminiException;\nimport it.at7.gemini.exceptions.GeminiRuntimeException;\nimport it.at7.gemini.schema.Entity;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.core.env.Environment;\nimport org.springframework.core.io.Resource;\nimport org.springframework.stereotype.Service;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\nimport java.util.*;\nimport java.util.function.Consumer;\nimport java.util.stream.Collectors;\n\n@Service\npublic class OpenApiServiceImpl implements OpenApiService, StateListener {\n\n private static final String SERVICE_INFO_DEFAULT_RESOURCE = \"classpath:/service/default-info.yml\";\n\n private final GeminiConfigurationService configurationService;\n\n private final StateManager stateManager;\n\n private final SchemaManager schemaManager;\n\n private final Environment environment;\n\n private final ApplicationContext context;\n\n private List API_INITIALIZER_LISTENER = new ArrayList<>();\n\n private Map builders = new HashMap<>();\n\n @Autowired\n public OpenApiServiceImpl(GeminiConfigurationService configurationService, StateManager stateManager, SchemaManager schemaManager, Environment environment, ApplicationContext context) {\n this.configurationService = configurationService;\n this.stateManager = stateManager;\n this.schemaManager = schemaManager;\n this.environment = environment;\n this.context = context;\n if (configurationService.isOpenapiSchema()) {\n this.stateManager.register(this);\n // openapi spec withRecord all entities\n builders.put(\"ALL\", OpenAPIFile.from(new OpenAPIBuilder(), \"ALL\", \"all.json\"));\n // entities by module... in each dedicated file\n schemaManager.getAllModules().forEach(m -> {\n String moduleName = m.getName().toUpperCase();\n builders.put(moduleName, OpenAPIFile.from(new OpenAPIBuilder(false), moduleName, moduleName.toLowerCase() + \".json\"));\n });\n }\n }\n\n private void createDefaultServiceInfoResource(File serviceInfoResource) throws IOException {\n Resource defaul", "post_mask_code": "\n serviceInfoResource.getParentFile().mkdirs();\n Files.copy(defaultInfoService.getInputStream(), serviceInfoResource.toPath(), StandardCopyOption.REPLACE_EXISTING);\n }\n\n @Override\n public void onChange(State previous, State actual, Optional transaction) throws GeminiException {\n if (configurationService.isOpenapiSchema()) {\n switch(actual) {\n case API_INITIALIZATION:\n loadServiceInfo();\n makeOpenAPISchema();\n break;\n case API_INITIALIZED:\n API_INITIALIZER_LISTENER.forEach(Runnable::run);\n String localPort = environment.getProperty(\"local.server.port\");\n iterateOverBuilders(b -> b.builder.addServer(\"http://127.0.0.1:\" + localPort + \"/api\", \"Local Server\"));\n iterateOverBuilders(b -> storeOpenAPISchema(b.builder, b.fileName));\n break;\n default:\n break;\n }\n }\n }\n\n private void loadServiceInfo() {\n try {\n File serviceInfoFile = new File(configurationService.getServiceInfoResource());\n if (!serviceInfoFile.exists()) {\n createDefaultServiceInfoResource(serviceInfoFile);\n }\n ObjectMapper mapper = new ObjectMapper(new YAMLFactory());\n GeminiServiceInfoWrapper geminiService = mapper.readValue(serviceInfoFile, GeminiServiceInfoWrapper.class);\n iterateOverBuilders(b -> b.builder.addInfo(geminiService.info));\n } catch (IOException e) {\n throw new GeminiRuntimeException(e);\n }\n }\n\n private void makeOpenAPISchema() {\n Collection allEntities = this.schemaManager.getAllEntities();\n Map> entitiesByModule = allEntities.stream().collect(Collectors.groupingBy(Entity::getModule));\n List orderedModules = entitiesByModule.keySet().stream().sorted(Comparator.comparingInt(ModuleBase::order)).collect(Collectors.toList());\n OpenAPIBuilder allEntityBuilder = this.builders.get(\"ALL\").builder;\n allEntityBuilder.addModulesToTags(orderedModules);\n for (ModuleBase module : orderedModules) {\n List entities = entitiesByModule.get(module);\n entities.forEach(allEntityBuilder::handleEntity);\n String moduleName = module.getName().toUpperCase();\n OpenAPIFile openAPIFile = this.builders.get(moduleName);\n assert openAPIFile != null;\n List otherOpenApiFiles = this.builders.values().stream().filter(f -> !f.key.equals(openAPIFile.key) && !f.key.equals(\"ALL\")).collect(Collectors.toList());\n entities.forEach(e -> {\n openAPIFile.builder.handleEntity(e);\n otherOpenApiFiles.forEach(b -> b.builder.addComponentSchema(e, OpenAPIBuilder.SchemaType.ENTITY));\n if (!e.isEmbedable()) {\n otherOpenApiFiles.forEach(b -> b.builder.addComponentSchema(e, OpenAPIBuilder.SchemaType.ENTITY_LK));\n }\n });\n }\n }\n\n private void storeOpenAPISchema(OpenAPIBuilder openAPIBuilder, String fileName) {\n String json = openAPIBuilder.toJsonString();\n try {\n String openApiDir = configurationService.getOpenApiDir();\n Path allPath = Paths.get(openApiDir, fileName);\n File file = new File(allPath.toString());\n file.getParentFile().mkdirs();\n Files.write(allPath, json.getBytes());\n } catch (IOException e) {\n throw new GeminiRuntimeException(e);\n }\n }\n\n @Override\n public void addOAuth2PasswordFlow(String name, Map flowParameters) {\n if (configurationService.isOpenapiSchema()) {\n String tokenUrl = (String) flowParameters.get(\"tokenUrl\");\n if (tokenUrl == null || tokenUrl.equals(\"\")) {\n throw new GeminiRuntimeException(\"Unable to initializeSmartModules OAuth2 Password Flow - No tokenUrl Provided\");\n }\n OpenAPIBuilder.SecuritySchema securitySchema = new OpenAPIBuilder.SecuritySchema();\n securitySchema.type = \"oauth2\";\n securitySchema.description = (String) flowParameters.getOrDefault(\"description\", \"See http://example.com\");\n securitySchema.flows = Map.of(\"password\", Map.of(\"tokenUrl\", tokenUrl));\n iterateOverBuilders(b -> b.builder.addSecurityComponent(name, securitySchema));\n }\n }\n\n @Override\n public void secureAllEntities(String securitySchemaName) {\n if (configurationService.isOpenapiSchema()) {\n API_INITIALIZER_LISTENER.add(() -> {\n iterateOverBuilders(b -> b.builder.secureAllEntityPaths(securitySchemaName));\n });\n }\n }\n\n private void iterateOverBuilders(Consumer c) {\n this.builders.values().forEach(c);\n }\n\n static class GeminiServiceInfoWrapper {\n\n public OpenAPIBuilder.Info info;\n }\n\n static class OpenAPIFile {\n\n OpenAPIBuilder builder;\n\n String key;\n\n String fileName;\n\n public OpenAPIFile(OpenAPIBuilder builder, String key, String fileName) {\n this.builder = builder;\n this.key = key;\n this.fileName = fileName;\n }\n\n static OpenAPIFile from(OpenAPIBuilder builder, String key, String fileName) {\n return new OpenAPIFile(builder, key, fileName);\n }\n }\n}\n"} {"task_id": "Java_2597", "language": "Java", "task_type": "try_statement", "source_file": "java/github/gemini-projects/gemini/gemini-core/src/main/java/it/at7/gemini/api/openapi/OpenApiServiceImpl.java", "mask_start_position": 5989, "mask_end_position": 6365, "canonical_solution": "try {\n String openApiDir = configurationService.getOpenApiDir();\n Path allPath = Paths.get(openApiDir, fileName);\n File file = new File(allPath.toString());\n file.getParentFile().mkdirs();\n Files.write(allPath, json.getBytes());\n } catch (IOException e) {\n throw new GeminiRuntimeException(e);\n }", "pre_mask_code": "package it.at7.gemini.api.openapi;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLFactory;\nimport it.at7.gemini.conf.State;\nimport it.at7.gemini.core.*;\nimport it.at7.gemini.exceptions.GeminiException;\nimport it.at7.gemini.exceptions.GeminiRuntimeException;\nimport it.at7.gemini.schema.Entity;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.core.env.Environment;\nimport org.springframework.core.io.Resource;\nimport org.springframework.stereotype.Service;\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\nimport java.util.*;\nimport java.util.function.Consumer;\nimport java.util.stream.Collectors;\n\n@Service\npublic class OpenApiServiceImpl implements OpenApiService, StateListener {\n\n private static final String SERVICE_INFO_DEFAULT_RESOURCE = \"classpath:/service/default-info.yml\";\n\n private final GeminiConfigurationService configurationService;\n\n private final StateManager stateManager;\n\n private final SchemaManager schemaManager;\n\n private final Environment environment;\n\n private final ApplicationContext context;\n\n private List API_INITIALIZER_LISTENER = new ArrayList<>();\n\n private Map builders = new HashMap<>();\n\n @Autowired\n public OpenApiServiceImpl(GeminiConfigurationService configurationService, StateManager stateManager, SchemaManager schemaManager, Environment environment, ApplicationContext context) {\n this.configurationService = configurationService;\n this.stateManager = stateManager;\n this.schemaManager = schemaManager;\n this.environment = environment;\n this.context = context;\n if (configurationService.isOpenapiSchema()) {\n this.stateManager.register(this);\n // openapi spec withRecord all entities\n builders.put(\"ALL\", OpenAPIFile.from(new OpenAPIBuilder(), \"ALL\", \"all.json\"));\n // entities by module... in each dedicated file\n schemaManager.getAllModules().forEach(m -> {\n String moduleName = m.getName().toUpperCase();\n builders.put(moduleName, OpenAPIFile.from(new OpenAPIBuilder(false), moduleName, moduleName.toLowerCase() + \".json\"));\n });\n }\n }\n\n private void createDefaultServiceInfoResource(File serviceInfoResource) throws IOException {\n Resource defaultInfoService = context.getResource(SERVICE_INFO_DEFAULT_RESOURCE);\n serviceInfoResource.getParentFile().mkdirs();\n Files.copy(defaultInfoService.getInputStream(), serviceInfoResource.toPath(), StandardCopyOption.REPLACE_EXISTING);\n }\n\n @Override\n public void onChange(State previous, State actual, Optional transaction) throws GeminiException {\n if (configurationService.isOpenapiSchema()) {\n switch(actual) {\n case API_INITIALIZATION:\n loadServiceInfo();\n makeOpenAPISchema();\n break;\n case API_INITIALIZED:\n API_INITIALIZER_LISTENER.forEach(Runnable::run);\n String localPort = environment.getProperty(\"local.server.port\");\n iterateOverBuilders(b -> b.builder.addServer(\"http://127.0.0.1:\" + localPort + \"/api\", \"Local Server\"));\n iterateOverBuilders(b -> storeOpenAPISchema(b.builder, b.fileName));\n break;\n default:\n break;\n }\n }\n }\n\n private void loadServiceInfo() {\n try {\n File serviceInfoFile = new File(configurationService.getServiceInfoResource());\n if (!serviceInfoFile.exists()) {\n createDefaultServiceInfoResource(serviceInfoFile);\n }\n ObjectMapper mapper = new ObjectMapper(new YAMLFactory());\n GeminiServiceInfoWrapper geminiService = mapper.readValue(serviceInfoFile, GeminiServiceInfoWrapper.class);\n iterateOverBuilders(b -> b.builder.addInfo(geminiService.info));\n } catch (IOException e) {\n throw new GeminiRuntimeException(e);\n }\n }\n\n private void makeOpenAPISchema() {\n Collection allEntities = this.schemaManager.getAllEntities();\n Map> entitiesByModule = allEntities.stream().collect(Collectors.groupingBy(Entity::getModule));\n List orderedModules = entitiesByModule.keySet().stream().sorted(Comparator.comparingInt(ModuleBase::order)).collect(Collectors.toList());\n OpenAPIBuilder allEntityBuilder = this.builders.get(\"ALL\").builder;\n allEntityBuilder.addModulesToTags(orderedModules);\n for (ModuleBase module : orderedModules) {\n List entities = entitiesByModule.get(module);\n entities.forEach(allEntityBuilder::handleEntity);\n String moduleName = module.getName().toUpperCase();\n OpenAPIFile openAPIFile = this.builders.get(moduleName);\n assert openAPIFile != null;\n List otherOpenApiFiles = this.builders.values().stream().filter(f -> !f.key.equals(openAPIFile.key) && !f.key.equals(\"ALL\")).collect(Collectors.toList());\n entities.forEach(e -> {\n openAPIFile.builder.handleEntity(e);\n otherOpenApiFiles.forEach(b -> b.builder.addComponentSchema(e, OpenAPIBuilder.SchemaType.ENTITY));\n if (!e.isEmbedable()) {\n otherOpenApiFiles.forEach(b -> b.builder.addComponentSchema(e, OpenAPIBuilder.SchemaType.ENTITY_LK));\n }\n });\n }\n }\n\n private void storeOpenAPISchema(OpenAPIBuilder openAPIBuilder, String fileName) {\n String json = openAPIBuilder.toJsonString();\n ", "post_mask_code": "\n }\n\n @Override\n public void addOAuth2PasswordFlow(String name, Map flowParameters) {\n if (configurationService.isOpenapiSchema()) {\n String tokenUrl = (String) flowParameters.get(\"tokenUrl\");\n if (tokenUrl == null || tokenUrl.equals(\"\")) {\n throw new GeminiRuntimeException(\"Unable to initializeSmartModules OAuth2 Password Flow - No tokenUrl Provided\");\n }\n OpenAPIBuilder.SecuritySchema securitySchema = new OpenAPIBuilder.SecuritySchema();\n securitySchema.type = \"oauth2\";\n securitySchema.description = (String) flowParameters.getOrDefault(\"description\", \"See http://example.com\");\n securitySchema.flows = Map.of(\"password\", Map.of(\"tokenUrl\", tokenUrl));\n iterateOverBuilders(b -> b.builder.addSecurityComponent(name, securitySchema));\n }\n }\n\n @Override\n public void secureAllEntities(String securitySchemaName) {\n if (configurationService.isOpenapiSchema()) {\n API_INITIALIZER_LISTENER.add(() -> {\n iterateOverBuilders(b -> b.builder.secureAllEntityPaths(securitySchemaName));\n });\n }\n }\n\n private void iterateOverBuilders(Consumer c) {\n this.builders.values().forEach(c);\n }\n\n static class GeminiServiceInfoWrapper {\n\n public OpenAPIBuilder.Info info;\n }\n\n static class OpenAPIFile {\n\n OpenAPIBuilder builder;\n\n String key;\n\n String fileName;\n\n public OpenAPIFile(OpenAPIBuilder builder, String key, String fileName) {\n this.builder = builder;\n this.key = key;\n this.fileName = fileName;\n }\n\n static OpenAPIFile from(OpenAPIBuilder builder, String key, String fileName) {\n return new OpenAPIFile(builder, key, fileName);\n }\n }\n}\n"} {"task_id": "Java_2598", "language": "Java", "task_type": "method_signature", "source_file": "java/github/bonitasoft/bonita-studio/patched-plugins/org.eclipse.ui.views.properties.tabbed/src/org/eclipse/ui/views/properties/tabbed/AbstractTypeMapper.java", "mask_start_position": 439, "mask_end_position": 489, "canonical_solution": "@Override\n public Class mapType(Object object) ", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.ui.views.properties.tabbed;\n\n/**\n * Default implementation of a type mapper.\n *\n * @author Anthony Hunter\n */\npublic class AbstractTypeMapper implements ITypeMapper {\n\n ", "post_mask_code": "{\n return object.getClass();\n }\n}\n"} {"task_id": "Java_2599", "language": "Java", "task_type": "method_body", "source_file": "java/github/bonitasoft/bonita-studio/patched-plugins/org.eclipse.ui.views.properties.tabbed/src/org/eclipse/ui/views/properties/tabbed/AbstractTypeMapper.java", "mask_start_position": 489, "mask_end_position": 530, "canonical_solution": "{\n return object.getClass();\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.ui.views.properties.tabbed;\n\n/**\n * Default implementation of a type mapper.\n *\n * @author Anthony Hunter\n */\npublic class AbstractTypeMapper implements ITypeMapper {\n\n @Override\n public Class mapType(Object object) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2600", "language": "Java", "task_type": "single_line", "source_file": "java/github/bonitasoft/bonita-studio/patched-plugins/org.eclipse.ui.views.properties.tabbed/src/org/eclipse/ui/views/properties/tabbed/AbstractTypeMapper.java", "mask_start_position": 519, "mask_end_position": 524, "canonical_solution": "ss();", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * IBM Corporation - initial API and implementation\n * *****************************************************************************\n */\npackage org.eclipse.ui.views.properties.tabbed;\n\n/**\n * Default implementation of a type mapper.\n *\n * @author Anthony Hunter\n */\npublic class AbstractTypeMapper implements ITypeMapper {\n\n @Override\n public Class mapType(Object object) {\n return object.getCla", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2601", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/zhanyeye/dingtalk-springboot/src/main/java/com/softeng/dingtalk/repository/ExternalPaperRepository.java", "mask_start_position": 361, "mask_end_position": 464, "canonical_solution": "@Query(\"select ep from ExternalPaper ep where ep.vote.id = :vid\")\n ExternalPaper findByVid(int vid);", "pre_mask_code": "package com.softeng.dingtalk.repository;\n\nimport com.softeng.dingtalk.entity.ExternalPaper;\nimport com.softeng.dingtalk.entity.Vote;\nimport org.springframework.data.jpa.repository.Query;\n\npublic interface ExternalPaperRepository extends CustomizedRepository {\n\n /**\n * 查询对应指定投票id的外部论文\n * @param vid\n * @return\n */\n ", "post_mask_code": "\n\n /**\n * 查询指定论文的投票\n * @param id\n * @return\n */\n @Query(\"select ep.vote from ExternalPaper ep where ep.id = :id\")\n Vote findVoteById(int id);\n}\n"} {"task_id": "Java_2602", "language": "Java", "task_type": "method_signature", "source_file": "java/github/springapidev/java-certification/CoderJavaNetBeans/src/com/coderbd/ex70/logicalproblems/ex2/Complexloop.java", "mask_start_position": 106, "mask_end_position": 133, "canonical_solution": "static boolean foo(char c) ", "pre_mask_code": "package com.coderbd.ex70.logicalproblems.ex2;\n\n/**\n * @author J2EE-33\n */\npublic class Complexloop {\n\n ", "post_mask_code": "{\n System.out.print(c);\n return true;\n }\n\n public static void main(String[] argv) {\n int i = 0;\n for (foo('A'); foo('B') && (i < 2); foo('C')) {\n i++;\n foo('D');\n }\n }\n}\n"} {"task_id": "Java_2603", "language": "Java", "task_type": "method_body", "source_file": "java/github/springapidev/java-certification/CoderJavaNetBeans/src/com/coderbd/ex70/logicalproblems/ex2/Complexloop.java", "mask_start_position": 235, "mask_end_position": 366, "canonical_solution": "{\n int i = 0;\n for (foo('A'); foo('B') && (i < 2); foo('C')) {\n i++;\n foo('D');\n }\n }", "pre_mask_code": "package com.coderbd.ex70.logicalproblems.ex2;\n\n/**\n * @author J2EE-33\n */\npublic class Complexloop {\n\n static boolean foo(char c) {\n System.out.print(c);\n return true;\n }\n\n public static void main(String[] argv) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2604", "language": "Java", "task_type": "single_line", "source_file": "java/github/springapidev/java-certification/CoderJavaNetBeans/src/com/coderbd/ex70/logicalproblems/ex2/Complexloop.java", "mask_start_position": 150, "mask_end_position": 163, "canonical_solution": "out.print(c);", "pre_mask_code": "package com.coderbd.ex70.logicalproblems.ex2;\n\n/**\n * @author J2EE-33\n */\npublic class Complexloop {\n\n static boolean foo(char c) {\n System.", "post_mask_code": "\n return true;\n }\n\n public static void main(String[] argv) {\n int i = 0;\n for (foo('A'); foo('B') && (i < 2); foo('C')) {\n i++;\n foo('D');\n }\n }\n}\n"} {"task_id": "Java_2605", "language": "Java", "task_type": "for_statement", "source_file": "java/github/springapidev/java-certification/CoderJavaNetBeans/src/com/coderbd/ex70/logicalproblems/ex2/Complexloop.java", "mask_start_position": 264, "mask_end_position": 360, "canonical_solution": "for (foo('A'); foo('B') && (i < 2); foo('C')) {\n i++;\n foo('D');\n }", "pre_mask_code": "package com.coderbd.ex70.logicalproblems.ex2;\n\n/**\n * @author J2EE-33\n */\npublic class Complexloop {\n\n static boolean foo(char c) {\n System.out.print(c);\n return true;\n }\n\n public static void main(String[] argv) {\n int i = 0;\n ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2606", "language": "Java", "task_type": "method_signature", "source_file": "java/github/pfmiles/kan-java/src/main/java/com/github/pfmiles/kanjava/JavaSourceFile.java", "mask_start_position": 1240, "mask_end_position": 1302, "canonical_solution": "private static URI genMemFileUri(String fileName, String pkg) ", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * pf-miles - initial API and implementation\n * ****************************************************************************\n */\npackage com.github.pfmiles.kanjava;\n\nimport java.io.BufferedReader;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.OutputStream;\nimport java.io.Reader;\nimport java.io.Writer;\nimport java.net.URI;\nimport javax.tools.SimpleJavaFileObject;\nimport com.github.pfmiles.kanjava.compile.DynaCompileUtil;\n\n/**\n * 用作编译时以string形式传入java源文件\n *\n * @author pf_miles\n */\npublic class JavaSourceFile extends SimpleJavaFileObject {\n\n private String fileName;\n\n private String code;\n\n /**\n * 创建内存java源码文件\n *\n * @param fileName\n * 文件名, 如:Test.java\n * @param pkg\n * 类所属包名, 如:com.test\n * @param code\n * 代码\n */\n public JavaSourceFile(String fileName, String pkg, String code) {\n super(genMemFileUri(fileName, pkg), Kind.SOURCE);\n this.fileName = fileName;\n this.code = code;\n }\n\n ", "post_mask_code": "{\n String pkgPath = \"\";\n if (DynaCompileUtil.isNotBlank(pkg))\n pkgPath = pkg.replaceAll(\"\\\\.\", \"/\") + \"/\";\n return URI.create(\"mem:///src/\" + pkgPath + fileName);\n }\n\n public String getName() {\n return this.fileName;\n }\n\n public InputStream openInputStream() throws IOException {\n return new ByteArrayInputStream(this.code.getBytes(\"UTF-8\"));\n }\n\n public OutputStream openOutputStream() throws IOException {\n throw new UnsupportedOperationException();\n }\n\n public Reader openReader(boolean ignoreEncodingErrors) throws IOException {\n return new BufferedReader(new InputStreamReader(this.openInputStream()));\n }\n\n public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {\n return this.code;\n }\n\n public Writer openWriter() throws IOException {\n throw new UnsupportedOperationException();\n }\n\n public boolean delete() {\n throw new UnsupportedOperationException();\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String toString() {\n return uri.toString();\n }\n\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((uri == null) ? 0 : uri.hashCode());\n return result;\n }\n\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n JavaSourceFile other = (JavaSourceFile) obj;\n if (uri == null) {\n if (other.toUri() != null)\n return false;\n } else if (!uri.equals(other.toUri()))\n return false;\n return true;\n }\n}\n"} {"task_id": "Java_2607", "language": "Java", "task_type": "method_body", "source_file": "java/github/pfmiles/kan-java/src/main/java/com/github/pfmiles/kanjava/JavaSourceFile.java", "mask_start_position": 2262, "mask_end_position": 2320, "canonical_solution": "{\n throw new UnsupportedOperationException();\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * pf-miles - initial API and implementation\n * ****************************************************************************\n */\npackage com.github.pfmiles.kanjava;\n\nimport java.io.BufferedReader;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.OutputStream;\nimport java.io.Reader;\nimport java.io.Writer;\nimport java.net.URI;\nimport javax.tools.SimpleJavaFileObject;\nimport com.github.pfmiles.kanjava.compile.DynaCompileUtil;\n\n/**\n * 用作编译时以string形式传入java源文件\n *\n * @author pf_miles\n */\npublic class JavaSourceFile extends SimpleJavaFileObject {\n\n private String fileName;\n\n private String code;\n\n /**\n * 创建内存java源码文件\n *\n * @param fileName\n * 文件名, 如:Test.java\n * @param pkg\n * 类所属包名, 如:com.test\n * @param code\n * 代码\n */\n public JavaSourceFile(String fileName, String pkg, String code) {\n super(genMemFileUri(fileName, pkg), Kind.SOURCE);\n this.fileName = fileName;\n this.code = code;\n }\n\n private static URI genMemFileUri(String fileName, String pkg) {\n String pkgPath = \"\";\n if (DynaCompileUtil.isNotBlank(pkg))\n pkgPath = pkg.replaceAll(\"\\\\.\", \"/\") + \"/\";\n return URI.create(\"mem:///src/\" + pkgPath + fileName);\n }\n\n public String getName() {\n return this.fileName;\n }\n\n public InputStream openInputStream() throws IOException {\n return new ByteArrayInputStream(this.code.getBytes(\"UTF-8\"));\n }\n\n public OutputStream openOutputStream() throws IOException {\n throw new UnsupportedOperationException();\n }\n\n public Reader openReader(boolean ignoreEncodingErrors) throws IOException {\n return new BufferedReader(new InputStreamReader(this.openInputStream()));\n }\n\n public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {\n return this.code;\n }\n\n public Writer openWriter() throws IOException {\n throw new UnsupportedOperationException();\n }\n\n public boolean delete() ", "post_mask_code": "\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String toString() {\n return uri.toString();\n }\n\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((uri == null) ? 0 : uri.hashCode());\n return result;\n }\n\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n JavaSourceFile other = (JavaSourceFile) obj;\n if (uri == null) {\n if (other.toUri() != null)\n return false;\n } else if (!uri.equals(other.toUri()))\n return false;\n return true;\n }\n}\n"} {"task_id": "Java_2608", "language": "Java", "task_type": "single_line", "source_file": "java/github/pfmiles/kan-java/src/main/java/com/github/pfmiles/kanjava/JavaSourceFile.java", "mask_start_position": 1324, "mask_end_position": 1332, "canonical_solution": "th = \"\";", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * Contributors:\n * pf-miles - initial API and implementation\n * ****************************************************************************\n */\npackage com.github.pfmiles.kanjava;\n\nimport java.io.BufferedReader;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.OutputStream;\nimport java.io.Reader;\nimport java.io.Writer;\nimport java.net.URI;\nimport javax.tools.SimpleJavaFileObject;\nimport com.github.pfmiles.kanjava.compile.DynaCompileUtil;\n\n/**\n * 用作编译时以string形式传入java源文件\n *\n * @author pf_miles\n */\npublic class JavaSourceFile extends SimpleJavaFileObject {\n\n private String fileName;\n\n private String code;\n\n /**\n * 创建内存java源码文件\n *\n * @param fileName\n * 文件名, 如:Test.java\n * @param pkg\n * 类所属包名, 如:com.test\n * @param code\n * 代码\n */\n public JavaSourceFile(String fileName, String pkg, String code) {\n super(genMemFileUri(fileName, pkg), Kind.SOURCE);\n this.fileName = fileName;\n this.code = code;\n }\n\n private static URI genMemFileUri(String fileName, String pkg) {\n String pkgPa", "post_mask_code": "\n if (DynaCompileUtil.isNotBlank(pkg))\n pkgPath = pkg.replaceAll(\"\\\\.\", \"/\") + \"/\";\n return URI.create(\"mem:///src/\" + pkgPath + fileName);\n }\n\n public String getName() {\n return this.fileName;\n }\n\n public InputStream openInputStream() throws IOException {\n return new ByteArrayInputStream(this.code.getBytes(\"UTF-8\"));\n }\n\n public OutputStream openOutputStream() throws IOException {\n throw new UnsupportedOperationException();\n }\n\n public Reader openReader(boolean ignoreEncodingErrors) throws IOException {\n return new BufferedReader(new InputStreamReader(this.openInputStream()));\n }\n\n public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {\n return this.code;\n }\n\n public Writer openWriter() throws IOException {\n throw new UnsupportedOperationException();\n }\n\n public boolean delete() {\n throw new UnsupportedOperationException();\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String toString() {\n return uri.toString();\n }\n\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((uri == null) ? 0 : uri.hashCode());\n return result;\n }\n\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n JavaSourceFile other = (JavaSourceFile) obj;\n if (uri == null) {\n if (other.toUri() != null)\n return false;\n } else if (!uri.equals(other.toUri()))\n return false;\n return true;\n }\n}\n"} {"task_id": "Java_2609", "language": "Java", "task_type": "method_signature", "source_file": "java/github/NationalSecurityAgency/ghidra/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/model/JdiModelTargetModuleContainer.java", "mask_start_position": 1197, "mask_end_position": 1266, "canonical_solution": "@Internal\n public JdiModelTargetModule libraryLoaded(String name) ", "pre_mask_code": "package ghidra.dbg.jdi.model;\n\nimport java.util.*;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.stream.Collectors;\nimport com.sun.jdi.ModuleReference;\nimport ghidra.async.AsyncFence;\nimport ghidra.async.AsyncUtils;\nimport ghidra.dbg.error.DebuggerUserException;\nimport ghidra.dbg.target.TargetModule;\nimport ghidra.dbg.target.TargetModuleContainer;\nimport ghidra.dbg.target.schema.*;\nimport ghidra.dbg.target.schema.TargetObjectSchema.ResyncMode;\nimport ghidra.lifecycle.Internal;\nimport ghidra.util.Msg;\n\n@TargetObjectSchemaInfo(name = \"TargetModuleContainer\", elements = { @TargetElementType(type = JdiModelTargetModule.class) }, elementResync = ResyncMode.ONCE, attributes = { @TargetAttributeType(type = Void.class) }, canonicalContainer = true)\npublic class JdiModelTargetModuleContainer extends JdiModelTargetObjectImpl implements TargetModuleContainer {\n\n protected final JdiModelTargetVM vm;\n\n // TODO: Is it possible to load the same object twice?\n protected final Map modulesByName = new HashMap<>();\n\n public JdiModelTargetModuleContainer(JdiModelTargetVM vm) {\n super(vm, \"Modules\");\n this.vm = vm;\n }\n\n ", "post_mask_code": "{\n List allModules = vm.vm.allModules();\n for (ModuleReference ref : allModules) {\n if (JdiModelTargetModule.getUniqueId(ref).equals(name)) {\n JdiModelTargetModule module = getTargetModule(ref);\n changeElements(List.of(), List.of(module), Map.of(), \"Loaded\");\n return module;\n }\n }\n return null;\n }\n\n @Internal\n public void libraryUnloaded(String name) {\n synchronized (this) {\n modulesByName.remove(name);\n }\n changeElements(List.of(name), List.of(), Map.of(), \"Unloaded\");\n }\n\n @Override\n public boolean supportsSyntheticModules() {\n return false;\n }\n\n @Override\n public CompletableFuture addSyntheticModule(String name) {\n throw new DebuggerUserException(\"GDB Does not support synthetic modules\");\n }\n\n protected CompletableFuture updateUsingModules(Map byName) {\n List modules;\n synchronized (this) {\n modules = byName.values().stream().map(this::getTargetModule).collect(Collectors.toList());\n }\n AsyncFence fence = new AsyncFence();\n for (JdiModelTargetModule mod : modules) {\n fence.include(mod.init());\n }\n return fence.ready().thenAccept(__ -> {\n changeElements(List.of(), modules, Map.of(), \"Refreshed\");\n });\n }\n\n @Override\n protected CompletableFuture requestElements(boolean refresh) {\n return doRefresh();\n }\n\n protected CompletableFuture doRefresh() {\n Map map = new HashMap<>();\n List allModules = vm.vm.allModules();\n for (ModuleReference ref : allModules) {\n map.put(JdiModelTargetModule.getUniqueId(ref), ref);\n }\n modulesByName.keySet().retainAll(map.keySet());\n return updateUsingModules(map);\n }\n\n protected synchronized JdiModelTargetModule getTargetModule(ModuleReference module) {\n return modulesByName.computeIfAbsent(JdiModelTargetModule.getUniqueId(module), n -> new JdiModelTargetModule(this, module, true));\n }\n\n public synchronized JdiModelTargetModule getTargetModuleIfPresent(String name) {\n return modulesByName.get(name);\n }\n\n public CompletableFuture refreshInternal() {\n if (!isObserved()) {\n return AsyncUtils.NIL;\n }\n return doRefresh().exceptionally(ex -> {\n Msg.error(this, \"Problem refreshing inferior's modules\", ex);\n return null;\n });\n }\n}\n"} {"task_id": "Java_2610", "language": "Java", "task_type": "method_body", "source_file": "java/github/NationalSecurityAgency/ghidra/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/model/JdiModelTargetModuleContainer.java", "mask_start_position": 1740, "mask_end_position": 1899, "canonical_solution": "{\n synchronized (this) {\n modulesByName.remove(name);\n }\n changeElements(List.of(name), List.of(), Map.of(), \"Unloaded\");\n }", "pre_mask_code": "package ghidra.dbg.jdi.model;\n\nimport java.util.*;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.stream.Collectors;\nimport com.sun.jdi.ModuleReference;\nimport ghidra.async.AsyncFence;\nimport ghidra.async.AsyncUtils;\nimport ghidra.dbg.error.DebuggerUserException;\nimport ghidra.dbg.target.TargetModule;\nimport ghidra.dbg.target.TargetModuleContainer;\nimport ghidra.dbg.target.schema.*;\nimport ghidra.dbg.target.schema.TargetObjectSchema.ResyncMode;\nimport ghidra.lifecycle.Internal;\nimport ghidra.util.Msg;\n\n@TargetObjectSchemaInfo(name = \"TargetModuleContainer\", elements = { @TargetElementType(type = JdiModelTargetModule.class) }, elementResync = ResyncMode.ONCE, attributes = { @TargetAttributeType(type = Void.class) }, canonicalContainer = true)\npublic class JdiModelTargetModuleContainer extends JdiModelTargetObjectImpl implements TargetModuleContainer {\n\n protected final JdiModelTargetVM vm;\n\n // TODO: Is it possible to load the same object twice?\n protected final Map modulesByName = new HashMap<>();\n\n public JdiModelTargetModuleContainer(JdiModelTargetVM vm) {\n super(vm, \"Modules\");\n this.vm = vm;\n }\n\n @Internal\n public JdiModelTargetModule libraryLoaded(String name) {\n List allModules = vm.vm.allModules();\n for (ModuleReference ref : allModules) {\n if (JdiModelTargetModule.getUniqueId(ref).equals(name)) {\n JdiModelTargetModule module = getTargetModule(ref);\n changeElements(List.of(), List.of(module), Map.of(), \"Loaded\");\n return module;\n }\n }\n return null;\n }\n\n @Internal\n public void libraryUnloaded(String name) ", "post_mask_code": "\n\n @Override\n public boolean supportsSyntheticModules() {\n return false;\n }\n\n @Override\n public CompletableFuture addSyntheticModule(String name) {\n throw new DebuggerUserException(\"GDB Does not support synthetic modules\");\n }\n\n protected CompletableFuture updateUsingModules(Map byName) {\n List modules;\n synchronized (this) {\n modules = byName.values().stream().map(this::getTargetModule).collect(Collectors.toList());\n }\n AsyncFence fence = new AsyncFence();\n for (JdiModelTargetModule mod : modules) {\n fence.include(mod.init());\n }\n return fence.ready().thenAccept(__ -> {\n changeElements(List.of(), modules, Map.of(), \"Refreshed\");\n });\n }\n\n @Override\n protected CompletableFuture requestElements(boolean refresh) {\n return doRefresh();\n }\n\n protected CompletableFuture doRefresh() {\n Map map = new HashMap<>();\n List allModules = vm.vm.allModules();\n for (ModuleReference ref : allModules) {\n map.put(JdiModelTargetModule.getUniqueId(ref), ref);\n }\n modulesByName.keySet().retainAll(map.keySet());\n return updateUsingModules(map);\n }\n\n protected synchronized JdiModelTargetModule getTargetModule(ModuleReference module) {\n return modulesByName.computeIfAbsent(JdiModelTargetModule.getUniqueId(module), n -> new JdiModelTargetModule(this, module, true));\n }\n\n public synchronized JdiModelTargetModule getTargetModuleIfPresent(String name) {\n return modulesByName.get(name);\n }\n\n public CompletableFuture refreshInternal() {\n if (!isObserved()) {\n return AsyncUtils.NIL;\n }\n return doRefresh().exceptionally(ex -> {\n Msg.error(this, \"Problem refreshing inferior's modules\", ex);\n return null;\n });\n }\n}\n"} {"task_id": "Java_2611", "language": "Java", "task_type": "single_line", "source_file": "java/github/NationalSecurityAgency/ghidra/Ghidra/Debug/Debugger-jpda/src/main/java/ghidra/dbg/jdi/model/JdiModelTargetModuleContainer.java", "mask_start_position": 1979, "mask_end_position": 1984, "canonical_solution": "alse;", "pre_mask_code": "package ghidra.dbg.jdi.model;\n\nimport java.util.*;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.stream.Collectors;\nimport com.sun.jdi.ModuleReference;\nimport ghidra.async.AsyncFence;\nimport ghidra.async.AsyncUtils;\nimport ghidra.dbg.error.DebuggerUserException;\nimport ghidra.dbg.target.TargetModule;\nimport ghidra.dbg.target.TargetModuleContainer;\nimport ghidra.dbg.target.schema.*;\nimport ghidra.dbg.target.schema.TargetObjectSchema.ResyncMode;\nimport ghidra.lifecycle.Internal;\nimport ghidra.util.Msg;\n\n@TargetObjectSchemaInfo(name = \"TargetModuleContainer\", elements = { @TargetElementType(type = JdiModelTargetModule.class) }, elementResync = ResyncMode.ONCE, attributes = { @TargetAttributeType(type = Void.class) }, canonicalContainer = true)\npublic class JdiModelTargetModuleContainer extends JdiModelTargetObjectImpl implements TargetModuleContainer {\n\n protected final JdiModelTargetVM vm;\n\n // TODO: Is it possible to load the same object twice?\n protected final Map modulesByName = new HashMap<>();\n\n public JdiModelTargetModuleContainer(JdiModelTargetVM vm) {\n super(vm, \"Modules\");\n this.vm = vm;\n }\n\n @Internal\n public JdiModelTargetModule libraryLoaded(String name) {\n List allModules = vm.vm.allModules();\n for (ModuleReference ref : allModules) {\n if (JdiModelTargetModule.getUniqueId(ref).equals(name)) {\n JdiModelTargetModule module = getTargetModule(ref);\n changeElements(List.of(), List.of(module), Map.of(), \"Loaded\");\n return module;\n }\n }\n return null;\n }\n\n @Internal\n public void libraryUnloaded(String name) {\n synchronized (this) {\n modulesByName.remove(name);\n }\n changeElements(List.of(name), List.of(), Map.of(), \"Unloaded\");\n }\n\n @Override\n public boolean supportsSyntheticModules() {\n return f", "post_mask_code": "\n }\n\n @Override\n public CompletableFuture addSyntheticModule(String name) {\n throw new DebuggerUserException(\"GDB Does not support synthetic modules\");\n }\n\n protected CompletableFuture updateUsingModules(Map byName) {\n List modules;\n synchronized (this) {\n modules = byName.values().stream().map(this::getTargetModule).collect(Collectors.toList());\n }\n AsyncFence fence = new AsyncFence();\n for (JdiModelTargetModule mod : modules) {\n fence.include(mod.init());\n }\n return fence.ready().thenAccept(__ -> {\n changeElements(List.of(), modules, Map.of(), \"Refreshed\");\n });\n }\n\n @Override\n protected CompletableFuture requestElements(boolean refresh) {\n return doRefresh();\n }\n\n protected CompletableFuture doRefresh() {\n Map map = new HashMap<>();\n List allModules = vm.vm.allModules();\n for (ModuleReference ref : allModules) {\n map.put(JdiModelTargetModule.getUniqueId(ref), ref);\n }\n modulesByName.keySet().retainAll(map.keySet());\n return updateUsingModules(map);\n }\n\n protected synchronized JdiModelTargetModule getTargetModule(ModuleReference module) {\n return modulesByName.computeIfAbsent(JdiModelTargetModule.getUniqueId(module), n -> new JdiModelTargetModule(this, module, true));\n }\n\n public synchronized JdiModelTargetModule getTargetModuleIfPresent(String name) {\n return modulesByName.get(name);\n }\n\n public CompletableFuture refreshInternal() {\n if (!isObserved()) {\n return AsyncUtils.NIL;\n }\n return doRefresh().exceptionally(ex -> {\n Msg.error(this, \"Problem refreshing inferior's modules\", ex);\n return null;\n });\n }\n}\n"} {"task_id": "Java_2612", "language": "Java", "task_type": "method_signature", "source_file": "java/github/hinemos/hinemos/HinemosClient/src_monitor/com/clustercontrol/monitor/run/composite/TableItemInfoComposite.java", "mask_start_position": 11565, "mask_end_position": 11627, "canonical_solution": "protected Button createButton(Composite parent, String label) ", "pre_mask_code": "package com.clustercontrol.monitor.run.composite;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.eclipse.jface.dialogs.IDialogConstants;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.events.SelectionAdapter;\nimport org.eclipse.swt.events.SelectionEvent;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Button;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Label;\nimport org.eclipse.swt.widgets.Shell;\nimport org.eclipse.swt.widgets.Table;\nimport org.eclipse.swt.widgets.TableItem;\nimport org.eclipse.ui.PlatformUI;\nimport com.clustercontrol.util.WidgetTestUtil;\nimport com.clustercontrol.dialog.CommonDialog;\nimport com.clustercontrol.util.Messages;\n\npublic class TableItemInfoComposite extends Composite {\n\n /**\n * 判定情報一覧 コンポジット。\n */\n protected TableItemListComposite m_infoList = null;\n\n protected ITableItemCompositeDefine m_define = null;\n\n /**\n * 追加 ボタン。\n */\n protected Button m_buttonAdd = null;\n\n /**\n * 変更 ボタン。\n */\n protected Button m_buttonModify = null;\n\n /**\n * 削除 ボタン。\n */\n protected Button m_buttonDelete = null;\n\n protected Button m_buttonCopy = null;\n\n /**\n * 上へ ボタン。\n */\n protected Button m_buttonUp = null;\n\n /**\n * 下へ ボタン。\n */\n protected Button m_buttonDown = null;\n\n public TableItemInfoComposite(Composite parent, int style, ITableItemCompositeDefine define) {\n this(parent, style, define, null);\n }\n\n public TableItemInfoComposite(Composite parent, int style, ITableItemCompositeDefine define, List items) {\n super(parent, style);\n this.m_define = define;\n if (items != null) {\n this.m_define.initTableItemInfoManager(items);\n } else {\n this.m_define.initTableItemInfoManager();\n }\n this.initialize();\n }\n\n protected void initialize() {\n // 変数として利用されるグリッドデータ\n GridData gridData = null;\n GridLayout layout = new GridLayout(1, true);\n layout.marginHeight = 0;\n layout.marginWidth = 0;\n layout.numColumns = 15;\n this.setLayout(layout);\n this.m_infoList = new TableItemListComposite(this, SWT.BORDER, this.m_define);\n WidgetTestUtil.setTestId(this, \"pagelist\", m_infoList);\n gridData = new GridData();\n gridData.horizontalAlignment = GridData.FILL;\n gridData.verticalAlignment = GridData.FILL;\n gridData.grabExcessHorizontalSpace = true;\n gridData.grabExcessVerticalSpace = true;\n gridData.horizontalSpan = 11;\n this.m_infoList.setLayoutData(gridData);\n Composite composite = new Composite(this, SWT.NONE);\n WidgetTestUtil.setTestId(this, \"button\", composite);\n layout = new GridLayout(1, true);\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.MULTI) != 0) {\n layout.numColumns = 2;\n }\n composite.setLayout(layout);\n gridData = new GridData();\n gridData.horizontalAlignment = GridData.FILL;\n gridData.verticalAlignment = GridData.FILL;\n gridData.grabExcessHorizontalSpace = true;\n gridData.grabExcessVerticalSpace = true;\n gridData.horizontalSpan = 4;\n composite.setLayoutData(gridData);\n // 追加ボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.ADD) != 0) {\n this.m_buttonAdd = this.createButton(composite, Messages.getString(\"add\"));\n WidgetTestUtil.setTestId(this, \"add\", m_buttonAdd);\n this.m_buttonAdd.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\n CommonDialog dialog = m_define.createDialog(shell);\n if (dialog.open() == IDialogConstants.OK_ID) {\n m_define.getTableItemInfoManager().add(m_define.getCurrentCreatedItem());\n m_infoList.update();\n }\n }\n });\n }\n // 変更ボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.MODIFY) != 0) {\n this.m_buttonModify = this.createButton(composite, Messages.getString(\"modify\"));\n WidgetTestUtil.setTestId(this, \"modify\", m_buttonModify);\n this.m_buttonModify.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = getSelectedItem();\n if (item != null) {\n Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\n CommonDialog dialog = m_define.createDialog(shell, item);\n if (dialog.open() == IDialogConstants.OK_ID) {\n Table table = m_infoList.getTableViewer().getTable();\n WidgetTestUtil.setTestId(this, \"modify\", table);\n int selectIndex = table.getSelectionIndex();\n m_define.getTableItemInfoManager().modify(item, m_define.getCurrentCreatedItem());\n m_infoList.update();\n table.setSelection(selectIndex);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n // 削除ボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.DELETE) != 0) {\n this.m_buttonDelete = this.createButton(composite, Messages.getString(\"delete\"));\n WidgetTestUtil.setTestId(this, \"delete\", m_buttonDelete);\n this.m_buttonDelete.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n String detail = m_define.getItemsIdentifier(item);\n String[] args = { detail };\n if (MessageDialog.openConfirm(null, Messages.getString(\"confirmed\"), Messages.getString(\"message.monitor.31\", args))) {\n m_define.getTableItemInfoManager().delete(getSelectedItem());\n m_infoList.update();\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.COPY) != 0) {\n this.m_buttonCopy = this.createButton(composite, Messages.getString(\"copy\"));\n WidgetTestUtil.setTestId(this, \"copy\", m_buttonCopy);\n this.m_buttonCopy.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\n CommonDialog dialog = m_define.createDialog(shell, item);\n if (dialog.open() == IDialogConstants.OK_ID) {\n Table table = m_infoList.getTableViewer().getTable();\n WidgetTestUtil.setTestId(this, \"modify\", table);\n int selectIndex = table.getSelectionIndex();\n m_define.getTableItemInfoManager().add(m_define.getCurrentCreatedItem());\n m_infoList.update();\n table.setSelection(selectIndex);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.SPACE) != 0) {\n Label label = new Label(composite, SWT.NONE);\n WidgetTestUtil.setTestId(this, \"space\", label);\n }\n // 上へボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.UP) != 0) {\n this.m_buttonUp = this.createButton(composite, Messages.getString(\"up\"));\n WidgetTestUtil.setTestId(this, \"up\", m_buttonUp);\n this.m_buttonUp.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n if (m_define.getTableItemInfoManager().upOrder(item)) {\n m_infoList.update();\n selectItem(item);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n // 下へボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.DOWN) != 0) {\n this.m_buttonDown = this.createButton(composite, Messages.getString(\"down\"));\n WidgetTestUtil.setTestId(this, \"down\", m_buttonDown);\n this.m_buttonDown.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n if (m_define.getTableItemInfoManager().downOrder(item)) {\n m_infoList.update();\n selectItem(item);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n }\n\n public void setInputData(List list) {\n if (list != null) {\n this.m_infoList.setInputData(list);\n }\n // 必須項目を明示\n this.update();\n }\n\n /* (非 Javadoc)\n\t * @see org.eclipse.swt.widgets.Control#setEnabled(boolean)\n\t */\n @Override\n public void setEnabled(boolean enabled) {\n this.m_infoList.setEnabled(enabled);\n if (this.m_buttonAdd != null) {\n this.m_buttonAdd.setEnabled(enabled);\n }\n if (this.m_buttonModify != null) {\n this.m_buttonModify.setEnabled(enabled);\n }\n if (this.m_buttonDelete != null) {\n this.m_buttonDelete.setEnabled(enabled);\n }\n if (this.m_buttonCopy != null) {\n this.m_buttonCopy.setEnabled(enabled);\n }\n if (this.m_buttonUp != null) {\n this.m_buttonUp.setEnabled(enabled);\n }\n if (this.m_buttonDown != null) {\n this.m_buttonDown.setEnabled(enabled);\n }\n }\n\n ", "post_mask_code": "{\n Button button = new Button(parent, SWT.NONE);\n WidgetTestUtil.setTestId(this, null, button);\n GridData gridData = new GridData();\n gridData.horizontalAlignment = GridData.FILL;\n gridData.grabExcessHorizontalSpace = true;\n button.setLayoutData(gridData);\n button.setText(label);\n return button;\n }\n\n protected void selectItem(T item) {\n Table table = this.m_infoList.getTableViewer().getTable();\n WidgetTestUtil.setTestId(this, null, table);\n TableItem[] items = table.getItems();\n if (items == null || item == null) {\n return;\n }\n for (int i = 0; i < items.length; i++) {\n @SuppressWarnings(\"unchecked\")\n T tmpItem = (T) items[i].getData();\n WidgetTestUtil.setTestId(this, \"items\" + i, items[i]);\n if (item.equals(tmpItem)) {\n table.select(i);\n return;\n }\n }\n }\n\n protected T getSelectedItem() {\n StructuredSelection selection = (StructuredSelection) this.m_infoList.getTableViewer().getSelection();\n @SuppressWarnings(\"unchecked\")\n T tableItemInfo = (T) selection.getFirstElement();\n return tableItemInfo;\n }\n\n public List getItems() {\n return this.m_infoList.getTableItemData();\n }\n}\n"} {"task_id": "Java_2613", "language": "Java", "task_type": "method_body", "source_file": "java/github/hinemos/hinemos/HinemosClient/src_monitor/com/clustercontrol/monitor/run/composite/TableItemInfoComposite.java", "mask_start_position": 3869, "mask_end_position": 4291, "canonical_solution": "{\n Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\n CommonDialog dialog = m_define.createDialog(shell);\n if (dialog.open() == IDialogConstants.OK_ID) {\n m_define.getTableItemInfoManager().add(m_define.getCurrentCreatedItem());\n m_infoList.update();\n }\n }", "pre_mask_code": "package com.clustercontrol.monitor.run.composite;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.eclipse.jface.dialogs.IDialogConstants;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.events.SelectionAdapter;\nimport org.eclipse.swt.events.SelectionEvent;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Button;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Label;\nimport org.eclipse.swt.widgets.Shell;\nimport org.eclipse.swt.widgets.Table;\nimport org.eclipse.swt.widgets.TableItem;\nimport org.eclipse.ui.PlatformUI;\nimport com.clustercontrol.util.WidgetTestUtil;\nimport com.clustercontrol.dialog.CommonDialog;\nimport com.clustercontrol.util.Messages;\n\npublic class TableItemInfoComposite extends Composite {\n\n /**\n * 判定情報一覧 コンポジット。\n */\n protected TableItemListComposite m_infoList = null;\n\n protected ITableItemCompositeDefine m_define = null;\n\n /**\n * 追加 ボタン。\n */\n protected Button m_buttonAdd = null;\n\n /**\n * 変更 ボタン。\n */\n protected Button m_buttonModify = null;\n\n /**\n * 削除 ボタン。\n */\n protected Button m_buttonDelete = null;\n\n protected Button m_buttonCopy = null;\n\n /**\n * 上へ ボタン。\n */\n protected Button m_buttonUp = null;\n\n /**\n * 下へ ボタン。\n */\n protected Button m_buttonDown = null;\n\n public TableItemInfoComposite(Composite parent, int style, ITableItemCompositeDefine define) {\n this(parent, style, define, null);\n }\n\n public TableItemInfoComposite(Composite parent, int style, ITableItemCompositeDefine define, List items) {\n super(parent, style);\n this.m_define = define;\n if (items != null) {\n this.m_define.initTableItemInfoManager(items);\n } else {\n this.m_define.initTableItemInfoManager();\n }\n this.initialize();\n }\n\n protected void initialize() {\n // 変数として利用されるグリッドデータ\n GridData gridData = null;\n GridLayout layout = new GridLayout(1, true);\n layout.marginHeight = 0;\n layout.marginWidth = 0;\n layout.numColumns = 15;\n this.setLayout(layout);\n this.m_infoList = new TableItemListComposite(this, SWT.BORDER, this.m_define);\n WidgetTestUtil.setTestId(this, \"pagelist\", m_infoList);\n gridData = new GridData();\n gridData.horizontalAlignment = GridData.FILL;\n gridData.verticalAlignment = GridData.FILL;\n gridData.grabExcessHorizontalSpace = true;\n gridData.grabExcessVerticalSpace = true;\n gridData.horizontalSpan = 11;\n this.m_infoList.setLayoutData(gridData);\n Composite composite = new Composite(this, SWT.NONE);\n WidgetTestUtil.setTestId(this, \"button\", composite);\n layout = new GridLayout(1, true);\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.MULTI) != 0) {\n layout.numColumns = 2;\n }\n composite.setLayout(layout);\n gridData = new GridData();\n gridData.horizontalAlignment = GridData.FILL;\n gridData.verticalAlignment = GridData.FILL;\n gridData.grabExcessHorizontalSpace = true;\n gridData.grabExcessVerticalSpace = true;\n gridData.horizontalSpan = 4;\n composite.setLayoutData(gridData);\n // 追加ボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.ADD) != 0) {\n this.m_buttonAdd = this.createButton(composite, Messages.getString(\"add\"));\n WidgetTestUtil.setTestId(this, \"add\", m_buttonAdd);\n this.m_buttonAdd.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) ", "post_mask_code": "\n });\n }\n // 変更ボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.MODIFY) != 0) {\n this.m_buttonModify = this.createButton(composite, Messages.getString(\"modify\"));\n WidgetTestUtil.setTestId(this, \"modify\", m_buttonModify);\n this.m_buttonModify.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = getSelectedItem();\n if (item != null) {\n Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\n CommonDialog dialog = m_define.createDialog(shell, item);\n if (dialog.open() == IDialogConstants.OK_ID) {\n Table table = m_infoList.getTableViewer().getTable();\n WidgetTestUtil.setTestId(this, \"modify\", table);\n int selectIndex = table.getSelectionIndex();\n m_define.getTableItemInfoManager().modify(item, m_define.getCurrentCreatedItem());\n m_infoList.update();\n table.setSelection(selectIndex);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n // 削除ボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.DELETE) != 0) {\n this.m_buttonDelete = this.createButton(composite, Messages.getString(\"delete\"));\n WidgetTestUtil.setTestId(this, \"delete\", m_buttonDelete);\n this.m_buttonDelete.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n String detail = m_define.getItemsIdentifier(item);\n String[] args = { detail };\n if (MessageDialog.openConfirm(null, Messages.getString(\"confirmed\"), Messages.getString(\"message.monitor.31\", args))) {\n m_define.getTableItemInfoManager().delete(getSelectedItem());\n m_infoList.update();\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.COPY) != 0) {\n this.m_buttonCopy = this.createButton(composite, Messages.getString(\"copy\"));\n WidgetTestUtil.setTestId(this, \"copy\", m_buttonCopy);\n this.m_buttonCopy.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\n CommonDialog dialog = m_define.createDialog(shell, item);\n if (dialog.open() == IDialogConstants.OK_ID) {\n Table table = m_infoList.getTableViewer().getTable();\n WidgetTestUtil.setTestId(this, \"modify\", table);\n int selectIndex = table.getSelectionIndex();\n m_define.getTableItemInfoManager().add(m_define.getCurrentCreatedItem());\n m_infoList.update();\n table.setSelection(selectIndex);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.SPACE) != 0) {\n Label label = new Label(composite, SWT.NONE);\n WidgetTestUtil.setTestId(this, \"space\", label);\n }\n // 上へボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.UP) != 0) {\n this.m_buttonUp = this.createButton(composite, Messages.getString(\"up\"));\n WidgetTestUtil.setTestId(this, \"up\", m_buttonUp);\n this.m_buttonUp.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n if (m_define.getTableItemInfoManager().upOrder(item)) {\n m_infoList.update();\n selectItem(item);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n // 下へボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.DOWN) != 0) {\n this.m_buttonDown = this.createButton(composite, Messages.getString(\"down\"));\n WidgetTestUtil.setTestId(this, \"down\", m_buttonDown);\n this.m_buttonDown.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n if (m_define.getTableItemInfoManager().downOrder(item)) {\n m_infoList.update();\n selectItem(item);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n }\n\n public void setInputData(List list) {\n if (list != null) {\n this.m_infoList.setInputData(list);\n }\n // 必須項目を明示\n this.update();\n }\n\n /* (非 Javadoc)\n\t * @see org.eclipse.swt.widgets.Control#setEnabled(boolean)\n\t */\n @Override\n public void setEnabled(boolean enabled) {\n this.m_infoList.setEnabled(enabled);\n if (this.m_buttonAdd != null) {\n this.m_buttonAdd.setEnabled(enabled);\n }\n if (this.m_buttonModify != null) {\n this.m_buttonModify.setEnabled(enabled);\n }\n if (this.m_buttonDelete != null) {\n this.m_buttonDelete.setEnabled(enabled);\n }\n if (this.m_buttonCopy != null) {\n this.m_buttonCopy.setEnabled(enabled);\n }\n if (this.m_buttonUp != null) {\n this.m_buttonUp.setEnabled(enabled);\n }\n if (this.m_buttonDown != null) {\n this.m_buttonDown.setEnabled(enabled);\n }\n }\n\n protected Button createButton(Composite parent, String label) {\n Button button = new Button(parent, SWT.NONE);\n WidgetTestUtil.setTestId(this, null, button);\n GridData gridData = new GridData();\n gridData.horizontalAlignment = GridData.FILL;\n gridData.grabExcessHorizontalSpace = true;\n button.setLayoutData(gridData);\n button.setText(label);\n return button;\n }\n\n protected void selectItem(T item) {\n Table table = this.m_infoList.getTableViewer().getTable();\n WidgetTestUtil.setTestId(this, null, table);\n TableItem[] items = table.getItems();\n if (items == null || item == null) {\n return;\n }\n for (int i = 0; i < items.length; i++) {\n @SuppressWarnings(\"unchecked\")\n T tmpItem = (T) items[i].getData();\n WidgetTestUtil.setTestId(this, \"items\" + i, items[i]);\n if (item.equals(tmpItem)) {\n table.select(i);\n return;\n }\n }\n }\n\n protected T getSelectedItem() {\n StructuredSelection selection = (StructuredSelection) this.m_infoList.getTableViewer().getSelection();\n @SuppressWarnings(\"unchecked\")\n T tableItemInfo = (T) selection.getFirstElement();\n return tableItemInfo;\n }\n\n public List getItems() {\n return this.m_infoList.getTableItemData();\n }\n}\n"} {"task_id": "Java_2614", "language": "Java", "task_type": "single_line", "source_file": "java/github/hinemos/hinemos/HinemosClient/src_monitor/com/clustercontrol/monitor/run/composite/TableItemInfoComposite.java", "mask_start_position": 3299, "mask_end_position": 3320, "canonical_solution": "rizontalSpace = true;", "pre_mask_code": "package com.clustercontrol.monitor.run.composite;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.eclipse.jface.dialogs.IDialogConstants;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.events.SelectionAdapter;\nimport org.eclipse.swt.events.SelectionEvent;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Button;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Label;\nimport org.eclipse.swt.widgets.Shell;\nimport org.eclipse.swt.widgets.Table;\nimport org.eclipse.swt.widgets.TableItem;\nimport org.eclipse.ui.PlatformUI;\nimport com.clustercontrol.util.WidgetTestUtil;\nimport com.clustercontrol.dialog.CommonDialog;\nimport com.clustercontrol.util.Messages;\n\npublic class TableItemInfoComposite extends Composite {\n\n /**\n * 判定情報一覧 コンポジット。\n */\n protected TableItemListComposite m_infoList = null;\n\n protected ITableItemCompositeDefine m_define = null;\n\n /**\n * 追加 ボタン。\n */\n protected Button m_buttonAdd = null;\n\n /**\n * 変更 ボタン。\n */\n protected Button m_buttonModify = null;\n\n /**\n * 削除 ボタン。\n */\n protected Button m_buttonDelete = null;\n\n protected Button m_buttonCopy = null;\n\n /**\n * 上へ ボタン。\n */\n protected Button m_buttonUp = null;\n\n /**\n * 下へ ボタン。\n */\n protected Button m_buttonDown = null;\n\n public TableItemInfoComposite(Composite parent, int style, ITableItemCompositeDefine define) {\n this(parent, style, define, null);\n }\n\n public TableItemInfoComposite(Composite parent, int style, ITableItemCompositeDefine define, List items) {\n super(parent, style);\n this.m_define = define;\n if (items != null) {\n this.m_define.initTableItemInfoManager(items);\n } else {\n this.m_define.initTableItemInfoManager();\n }\n this.initialize();\n }\n\n protected void initialize() {\n // 変数として利用されるグリッドデータ\n GridData gridData = null;\n GridLayout layout = new GridLayout(1, true);\n layout.marginHeight = 0;\n layout.marginWidth = 0;\n layout.numColumns = 15;\n this.setLayout(layout);\n this.m_infoList = new TableItemListComposite(this, SWT.BORDER, this.m_define);\n WidgetTestUtil.setTestId(this, \"pagelist\", m_infoList);\n gridData = new GridData();\n gridData.horizontalAlignment = GridData.FILL;\n gridData.verticalAlignment = GridData.FILL;\n gridData.grabExcessHorizontalSpace = true;\n gridData.grabExcessVerticalSpace = true;\n gridData.horizontalSpan = 11;\n this.m_infoList.setLayoutData(gridData);\n Composite composite = new Composite(this, SWT.NONE);\n WidgetTestUtil.setTestId(this, \"button\", composite);\n layout = new GridLayout(1, true);\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.MULTI) != 0) {\n layout.numColumns = 2;\n }\n composite.setLayout(layout);\n gridData = new GridData();\n gridData.horizontalAlignment = GridData.FILL;\n gridData.verticalAlignment = GridData.FILL;\n gridData.grabExcessHo", "post_mask_code": "\n gridData.grabExcessVerticalSpace = true;\n gridData.horizontalSpan = 4;\n composite.setLayoutData(gridData);\n // 追加ボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.ADD) != 0) {\n this.m_buttonAdd = this.createButton(composite, Messages.getString(\"add\"));\n WidgetTestUtil.setTestId(this, \"add\", m_buttonAdd);\n this.m_buttonAdd.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\n CommonDialog dialog = m_define.createDialog(shell);\n if (dialog.open() == IDialogConstants.OK_ID) {\n m_define.getTableItemInfoManager().add(m_define.getCurrentCreatedItem());\n m_infoList.update();\n }\n }\n });\n }\n // 変更ボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.MODIFY) != 0) {\n this.m_buttonModify = this.createButton(composite, Messages.getString(\"modify\"));\n WidgetTestUtil.setTestId(this, \"modify\", m_buttonModify);\n this.m_buttonModify.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = getSelectedItem();\n if (item != null) {\n Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\n CommonDialog dialog = m_define.createDialog(shell, item);\n if (dialog.open() == IDialogConstants.OK_ID) {\n Table table = m_infoList.getTableViewer().getTable();\n WidgetTestUtil.setTestId(this, \"modify\", table);\n int selectIndex = table.getSelectionIndex();\n m_define.getTableItemInfoManager().modify(item, m_define.getCurrentCreatedItem());\n m_infoList.update();\n table.setSelection(selectIndex);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n // 削除ボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.DELETE) != 0) {\n this.m_buttonDelete = this.createButton(composite, Messages.getString(\"delete\"));\n WidgetTestUtil.setTestId(this, \"delete\", m_buttonDelete);\n this.m_buttonDelete.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n String detail = m_define.getItemsIdentifier(item);\n String[] args = { detail };\n if (MessageDialog.openConfirm(null, Messages.getString(\"confirmed\"), Messages.getString(\"message.monitor.31\", args))) {\n m_define.getTableItemInfoManager().delete(getSelectedItem());\n m_infoList.update();\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.COPY) != 0) {\n this.m_buttonCopy = this.createButton(composite, Messages.getString(\"copy\"));\n WidgetTestUtil.setTestId(this, \"copy\", m_buttonCopy);\n this.m_buttonCopy.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\n CommonDialog dialog = m_define.createDialog(shell, item);\n if (dialog.open() == IDialogConstants.OK_ID) {\n Table table = m_infoList.getTableViewer().getTable();\n WidgetTestUtil.setTestId(this, \"modify\", table);\n int selectIndex = table.getSelectionIndex();\n m_define.getTableItemInfoManager().add(m_define.getCurrentCreatedItem());\n m_infoList.update();\n table.setSelection(selectIndex);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.SPACE) != 0) {\n Label label = new Label(composite, SWT.NONE);\n WidgetTestUtil.setTestId(this, \"space\", label);\n }\n // 上へボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.UP) != 0) {\n this.m_buttonUp = this.createButton(composite, Messages.getString(\"up\"));\n WidgetTestUtil.setTestId(this, \"up\", m_buttonUp);\n this.m_buttonUp.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n if (m_define.getTableItemInfoManager().upOrder(item)) {\n m_infoList.update();\n selectItem(item);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n // 下へボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.DOWN) != 0) {\n this.m_buttonDown = this.createButton(composite, Messages.getString(\"down\"));\n WidgetTestUtil.setTestId(this, \"down\", m_buttonDown);\n this.m_buttonDown.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n if (m_define.getTableItemInfoManager().downOrder(item)) {\n m_infoList.update();\n selectItem(item);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n }\n\n public void setInputData(List list) {\n if (list != null) {\n this.m_infoList.setInputData(list);\n }\n // 必須項目を明示\n this.update();\n }\n\n /* (非 Javadoc)\n\t * @see org.eclipse.swt.widgets.Control#setEnabled(boolean)\n\t */\n @Override\n public void setEnabled(boolean enabled) {\n this.m_infoList.setEnabled(enabled);\n if (this.m_buttonAdd != null) {\n this.m_buttonAdd.setEnabled(enabled);\n }\n if (this.m_buttonModify != null) {\n this.m_buttonModify.setEnabled(enabled);\n }\n if (this.m_buttonDelete != null) {\n this.m_buttonDelete.setEnabled(enabled);\n }\n if (this.m_buttonCopy != null) {\n this.m_buttonCopy.setEnabled(enabled);\n }\n if (this.m_buttonUp != null) {\n this.m_buttonUp.setEnabled(enabled);\n }\n if (this.m_buttonDown != null) {\n this.m_buttonDown.setEnabled(enabled);\n }\n }\n\n protected Button createButton(Composite parent, String label) {\n Button button = new Button(parent, SWT.NONE);\n WidgetTestUtil.setTestId(this, null, button);\n GridData gridData = new GridData();\n gridData.horizontalAlignment = GridData.FILL;\n gridData.grabExcessHorizontalSpace = true;\n button.setLayoutData(gridData);\n button.setText(label);\n return button;\n }\n\n protected void selectItem(T item) {\n Table table = this.m_infoList.getTableViewer().getTable();\n WidgetTestUtil.setTestId(this, null, table);\n TableItem[] items = table.getItems();\n if (items == null || item == null) {\n return;\n }\n for (int i = 0; i < items.length; i++) {\n @SuppressWarnings(\"unchecked\")\n T tmpItem = (T) items[i].getData();\n WidgetTestUtil.setTestId(this, \"items\" + i, items[i]);\n if (item.equals(tmpItem)) {\n table.select(i);\n return;\n }\n }\n }\n\n protected T getSelectedItem() {\n StructuredSelection selection = (StructuredSelection) this.m_infoList.getTableViewer().getSelection();\n @SuppressWarnings(\"unchecked\")\n T tableItemInfo = (T) selection.getFirstElement();\n return tableItemInfo;\n }\n\n public List getItems() {\n return this.m_infoList.getTableItemData();\n }\n}\n"} {"task_id": "Java_2615", "language": "Java", "task_type": "for_statement", "source_file": "java/github/hinemos/hinemos/HinemosClient/src_monitor/com/clustercontrol/monitor/run/composite/TableItemInfoComposite.java", "mask_start_position": 12276, "mask_end_position": 12595, "canonical_solution": "for (int i = 0; i < items.length; i++) {\n @SuppressWarnings(\"unchecked\")\n T tmpItem = (T) items[i].getData();\n WidgetTestUtil.setTestId(this, \"items\" + i, items[i]);\n if (item.equals(tmpItem)) {\n table.select(i);\n return;\n }\n }", "pre_mask_code": "package com.clustercontrol.monitor.run.composite;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.eclipse.jface.dialogs.IDialogConstants;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.viewers.StructuredSelection;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.events.SelectionAdapter;\nimport org.eclipse.swt.events.SelectionEvent;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Button;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Label;\nimport org.eclipse.swt.widgets.Shell;\nimport org.eclipse.swt.widgets.Table;\nimport org.eclipse.swt.widgets.TableItem;\nimport org.eclipse.ui.PlatformUI;\nimport com.clustercontrol.util.WidgetTestUtil;\nimport com.clustercontrol.dialog.CommonDialog;\nimport com.clustercontrol.util.Messages;\n\npublic class TableItemInfoComposite extends Composite {\n\n /**\n * 判定情報一覧 コンポジット。\n */\n protected TableItemListComposite m_infoList = null;\n\n protected ITableItemCompositeDefine m_define = null;\n\n /**\n * 追加 ボタン。\n */\n protected Button m_buttonAdd = null;\n\n /**\n * 変更 ボタン。\n */\n protected Button m_buttonModify = null;\n\n /**\n * 削除 ボタン。\n */\n protected Button m_buttonDelete = null;\n\n protected Button m_buttonCopy = null;\n\n /**\n * 上へ ボタン。\n */\n protected Button m_buttonUp = null;\n\n /**\n * 下へ ボタン。\n */\n protected Button m_buttonDown = null;\n\n public TableItemInfoComposite(Composite parent, int style, ITableItemCompositeDefine define) {\n this(parent, style, define, null);\n }\n\n public TableItemInfoComposite(Composite parent, int style, ITableItemCompositeDefine define, List items) {\n super(parent, style);\n this.m_define = define;\n if (items != null) {\n this.m_define.initTableItemInfoManager(items);\n } else {\n this.m_define.initTableItemInfoManager();\n }\n this.initialize();\n }\n\n protected void initialize() {\n // 変数として利用されるグリッドデータ\n GridData gridData = null;\n GridLayout layout = new GridLayout(1, true);\n layout.marginHeight = 0;\n layout.marginWidth = 0;\n layout.numColumns = 15;\n this.setLayout(layout);\n this.m_infoList = new TableItemListComposite(this, SWT.BORDER, this.m_define);\n WidgetTestUtil.setTestId(this, \"pagelist\", m_infoList);\n gridData = new GridData();\n gridData.horizontalAlignment = GridData.FILL;\n gridData.verticalAlignment = GridData.FILL;\n gridData.grabExcessHorizontalSpace = true;\n gridData.grabExcessVerticalSpace = true;\n gridData.horizontalSpan = 11;\n this.m_infoList.setLayoutData(gridData);\n Composite composite = new Composite(this, SWT.NONE);\n WidgetTestUtil.setTestId(this, \"button\", composite);\n layout = new GridLayout(1, true);\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.MULTI) != 0) {\n layout.numColumns = 2;\n }\n composite.setLayout(layout);\n gridData = new GridData();\n gridData.horizontalAlignment = GridData.FILL;\n gridData.verticalAlignment = GridData.FILL;\n gridData.grabExcessHorizontalSpace = true;\n gridData.grabExcessVerticalSpace = true;\n gridData.horizontalSpan = 4;\n composite.setLayoutData(gridData);\n // 追加ボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.ADD) != 0) {\n this.m_buttonAdd = this.createButton(composite, Messages.getString(\"add\"));\n WidgetTestUtil.setTestId(this, \"add\", m_buttonAdd);\n this.m_buttonAdd.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\n CommonDialog dialog = m_define.createDialog(shell);\n if (dialog.open() == IDialogConstants.OK_ID) {\n m_define.getTableItemInfoManager().add(m_define.getCurrentCreatedItem());\n m_infoList.update();\n }\n }\n });\n }\n // 変更ボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.MODIFY) != 0) {\n this.m_buttonModify = this.createButton(composite, Messages.getString(\"modify\"));\n WidgetTestUtil.setTestId(this, \"modify\", m_buttonModify);\n this.m_buttonModify.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = getSelectedItem();\n if (item != null) {\n Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\n CommonDialog dialog = m_define.createDialog(shell, item);\n if (dialog.open() == IDialogConstants.OK_ID) {\n Table table = m_infoList.getTableViewer().getTable();\n WidgetTestUtil.setTestId(this, \"modify\", table);\n int selectIndex = table.getSelectionIndex();\n m_define.getTableItemInfoManager().modify(item, m_define.getCurrentCreatedItem());\n m_infoList.update();\n table.setSelection(selectIndex);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n // 削除ボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.DELETE) != 0) {\n this.m_buttonDelete = this.createButton(composite, Messages.getString(\"delete\"));\n WidgetTestUtil.setTestId(this, \"delete\", m_buttonDelete);\n this.m_buttonDelete.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n String detail = m_define.getItemsIdentifier(item);\n String[] args = { detail };\n if (MessageDialog.openConfirm(null, Messages.getString(\"confirmed\"), Messages.getString(\"message.monitor.31\", args))) {\n m_define.getTableItemInfoManager().delete(getSelectedItem());\n m_infoList.update();\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.COPY) != 0) {\n this.m_buttonCopy = this.createButton(composite, Messages.getString(\"copy\"));\n WidgetTestUtil.setTestId(this, \"copy\", m_buttonCopy);\n this.m_buttonCopy.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\n CommonDialog dialog = m_define.createDialog(shell, item);\n if (dialog.open() == IDialogConstants.OK_ID) {\n Table table = m_infoList.getTableViewer().getTable();\n WidgetTestUtil.setTestId(this, \"modify\", table);\n int selectIndex = table.getSelectionIndex();\n m_define.getTableItemInfoManager().add(m_define.getCurrentCreatedItem());\n m_infoList.update();\n table.setSelection(selectIndex);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.SPACE) != 0) {\n Label label = new Label(composite, SWT.NONE);\n WidgetTestUtil.setTestId(this, \"space\", label);\n }\n // 上へボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.UP) != 0) {\n this.m_buttonUp = this.createButton(composite, Messages.getString(\"up\"));\n WidgetTestUtil.setTestId(this, \"up\", m_buttonUp);\n this.m_buttonUp.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n if (m_define.getTableItemInfoManager().upOrder(item)) {\n m_infoList.update();\n selectItem(item);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n // 下へボタン\n if ((this.m_define.getButtonOptions() & ITableItemCompositeDefine.DOWN) != 0) {\n this.m_buttonDown = this.createButton(composite, Messages.getString(\"down\"));\n WidgetTestUtil.setTestId(this, \"down\", m_buttonDown);\n this.m_buttonDown.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n T item = m_infoList.getTableItem();\n if (item != null) {\n if (m_define.getTableItemInfoManager().downOrder(item)) {\n m_infoList.update();\n selectItem(item);\n }\n } else {\n MessageDialog.openWarning(null, Messages.getString(\"warning\"), Messages.getString(\"message.monitor.30\"));\n }\n }\n });\n }\n }\n\n public void setInputData(List list) {\n if (list != null) {\n this.m_infoList.setInputData(list);\n }\n // 必須項目を明示\n this.update();\n }\n\n /* (非 Javadoc)\n\t * @see org.eclipse.swt.widgets.Control#setEnabled(boolean)\n\t */\n @Override\n public void setEnabled(boolean enabled) {\n this.m_infoList.setEnabled(enabled);\n if (this.m_buttonAdd != null) {\n this.m_buttonAdd.setEnabled(enabled);\n }\n if (this.m_buttonModify != null) {\n this.m_buttonModify.setEnabled(enabled);\n }\n if (this.m_buttonDelete != null) {\n this.m_buttonDelete.setEnabled(enabled);\n }\n if (this.m_buttonCopy != null) {\n this.m_buttonCopy.setEnabled(enabled);\n }\n if (this.m_buttonUp != null) {\n this.m_buttonUp.setEnabled(enabled);\n }\n if (this.m_buttonDown != null) {\n this.m_buttonDown.setEnabled(enabled);\n }\n }\n\n protected Button createButton(Composite parent, String label) {\n Button button = new Button(parent, SWT.NONE);\n WidgetTestUtil.setTestId(this, null, button);\n GridData gridData = new GridData();\n gridData.horizontalAlignment = GridData.FILL;\n gridData.grabExcessHorizontalSpace = true;\n button.setLayoutData(gridData);\n button.setText(label);\n return button;\n }\n\n protected void selectItem(T item) {\n Table table = this.m_infoList.getTableViewer().getTable();\n WidgetTestUtil.setTestId(this, null, table);\n TableItem[] items = table.getItems();\n if (items == null || item == null) {\n return;\n }\n ", "post_mask_code": "\n }\n\n protected T getSelectedItem() {\n StructuredSelection selection = (StructuredSelection) this.m_infoList.getTableViewer().getSelection();\n @SuppressWarnings(\"unchecked\")\n T tableItemInfo = (T) selection.getFirstElement();\n return tableItemInfo;\n }\n\n public List getItems() {\n return this.m_infoList.getTableItemData();\n }\n}\n"} {"task_id": "Java_2616", "language": "Java", "task_type": "method_signature", "source_file": "java/github/MilosKozak/AndroidAPS/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/CommandValueDefinitionMDTType.java", "mask_start_position": 492, "mask_end_position": 536, "canonical_solution": "@Override\n public String commandAction() ", "pre_mask_code": "package info.nightscout.androidaps.plugins.pump.medtronic.defs;\n\nimport info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.CommandValueDefinitionType;\n\n/**\n * Created by andy on 4/5/19.\n */\npublic enum CommandValueDefinitionMDTType implements CommandValueDefinitionType {\n\n GetModel, TuneUp, GetProfile, GetTBR;\n\n @Override\n public String getName() {\n return this.name();\n }\n\n @Override\n public String getDescription() {\n return null;\n }\n\n ", "post_mask_code": "{\n return null;\n }\n}\n"} {"task_id": "Java_2617", "language": "Java", "task_type": "method_body", "source_file": "java/github/MilosKozak/AndroidAPS/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/CommandValueDefinitionMDTType.java", "mask_start_position": 536, "mask_end_position": 564, "canonical_solution": "{\n return null;\n }", "pre_mask_code": "package info.nightscout.androidaps.plugins.pump.medtronic.defs;\n\nimport info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.CommandValueDefinitionType;\n\n/**\n * Created by andy on 4/5/19.\n */\npublic enum CommandValueDefinitionMDTType implements CommandValueDefinitionType {\n\n GetModel, TuneUp, GetProfile, GetTBR;\n\n @Override\n public String getName() {\n return this.name();\n }\n\n @Override\n public String getDescription() {\n return null;\n }\n\n @Override\n public String commandAction() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2618", "language": "Java", "task_type": "single_line", "source_file": "java/github/MilosKozak/AndroidAPS/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/CommandValueDefinitionMDTType.java", "mask_start_position": 476, "mask_end_position": 480, "canonical_solution": "ull;", "pre_mask_code": "package info.nightscout.androidaps.plugins.pump.medtronic.defs;\n\nimport info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.CommandValueDefinitionType;\n\n/**\n * Created by andy on 4/5/19.\n */\npublic enum CommandValueDefinitionMDTType implements CommandValueDefinitionType {\n\n GetModel, TuneUp, GetProfile, GetTBR;\n\n @Override\n public String getName() {\n return this.name();\n }\n\n @Override\n public String getDescription() {\n return n", "post_mask_code": "\n }\n\n @Override\n public String commandAction() {\n return null;\n }\n}\n"} {"task_id": "Java_2619", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ZhongFuCheng3y/msc-Demo/microservicecloud/microservicecloud-eureka-7001/src/main/java/com/atguigu/springcloud/EurekaServer7001_App.java", "mask_start_position": 349, "mask_end_position": 388, "canonical_solution": "public static void main(String[] args) ", "pre_mask_code": "package com.atguigu.springcloud;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;\n\n@SpringBootApplication\n// EurekaServer服务器端启动类,接受其它微服务注册进来\n@EnableEurekaServer\npublic class EurekaServer7001_App {\n\n ", "post_mask_code": "{\n SpringApplication.run(EurekaServer7001_App.class, args);\n }\n}\n"} {"task_id": "Java_2620", "language": "Java", "task_type": "method_body", "source_file": "java/github/ZhongFuCheng3y/msc-Demo/microservicecloud/microservicecloud-eureka-7001/src/main/java/com/atguigu/springcloud/EurekaServer7001_App.java", "mask_start_position": 388, "mask_end_position": 460, "canonical_solution": "{\n SpringApplication.run(EurekaServer7001_App.class, args);\n }", "pre_mask_code": "package com.atguigu.springcloud;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;\n\n@SpringBootApplication\n// EurekaServer服务器端启动类,接受其它微服务注册进来\n@EnableEurekaServer\npublic class EurekaServer7001_App {\n\n public static void main(String[] args) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2621", "language": "Java", "task_type": "single_line", "source_file": "java/github/ZhongFuCheng3y/msc-Demo/microservicecloud/microservicecloud-eureka-7001/src/main/java/com/atguigu/springcloud/EurekaServer7001_App.java", "mask_start_position": 432, "mask_end_position": 454, "canonical_solution": "7001_App.class, args);", "pre_mask_code": "package com.atguigu.springcloud;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;\n\n@SpringBootApplication\n// EurekaServer服务器端启动类,接受其它微服务注册进来\n@EnableEurekaServer\npublic class EurekaServer7001_App {\n\n public static void main(String[] args) {\n SpringApplication.run(EurekaServer", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2622", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ThibaudM/timelapse-sony/app/src/main/java/com/thibaudperso/sonycamera/timelapse/ui/adjustments/SimpleStreamSurfaceView.java", "mask_start_position": 6292, "mask_end_position": 6336, "canonical_solution": "@Override\n public void run() ", "pre_mask_code": "package com.thibaudperso.sonycamera.timelapse.ui.adjustments;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Rect;\nimport android.os.Build;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.ViewGroup.LayoutParams;\nimport com.thibaudperso.sonycamera.timelapse.ui.adjustments.SimpleLiveviewSlicer.Payload;\nimport java.io.IOException;\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport static android.content.ContentValues.TAG;\nimport static com.thibaudperso.sonycamera.timelapse.Constants.LOG_TAG;\n\n/**\n * A SurfaceView based class to draw liveview frames serially.\n */\npublic class SimpleStreamSurfaceView extends SurfaceView implements SurfaceHolder.Callback {\n\n private boolean mWhileFetching;\n\n private final BlockingQueue mJpegQueue = new ArrayBlockingQueue<>(2);\n\n private Thread mDrawerThread;\n\n private Handler mSlicerHandler;\n\n private int mPreviousWidth = 0;\n\n private int mPreviousHeight = 0;\n\n private final Paint mFramePaint;\n\n private SimpleLiveviewSlicer mSlicer;\n\n public SimpleStreamSurfaceView(Context context) {\n super(context);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n public SimpleStreamSurfaceView(Context context, AttributeSet attrs) {\n super(context, attrs);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n public SimpleStreamSurfaceView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n }\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n mWhileFetching = false;\n }\n\n /**\n * Start retrieving and drawing liveview frame data by new threads.\n *\n * @return true if the starting is completed successfully, false otherwise.\n * @throws IllegalStateException when Remote API object is not set.\n */\n public boolean start(final String liveviewUrl) {\n if (mWhileFetching) {\n Log.w(TAG, \"start() already starting.\");\n return false;\n }\n mWhileFetching = true;\n // A thread for retrieving liveview data from server.\n Thread slicerThread = new Thread(new Runnable() {\n\n @Override\n public void run() {\n mSlicer = null;\n try {\n // Create Slicer to open the stream and parse it.\n mSlicer = new SimpleLiveviewSlicer();\n mSlicer.open(liveviewUrl);\n Looper.prepare();\n mSlicerHandler = new Handler();\n while (mWhileFetching) {\n final Payload payload = mSlicer.nextPayload();\n if (payload == null) {\n // never occurs\n Log.e(LOG_TAG, \"Liveview Payload is null.\");\n continue;\n }\n if (mJpegQueue.size() == 2) {\n mJpegQueue.remove();\n }\n mJpegQueue.add(payload.jpegData);\n }\n } catch (IOException e) {\n Log.w(LOG_TAG, \"IOException while fetching: \" + e.getMessage());\n } finally {\n // Finalize\n try {\n if (mSlicer != null) {\n mSlicer.close();\n }\n } catch (IOException e) {\n Log.w(LOG_TAG, \"IOException while closing slicer: \" + e.getMessage());\n }\n if (mDrawerThread != null) {\n mDrawerThread.interrupt();\n }\n mJpegQueue.clear();\n mWhileFetching = false;\n }\n }\n });\n slicerThread.start();\n // A thread for drawing liveview frame fetched by above thread.\n mDrawerThread = new Thread() {\n\n @Override\n public void run() {\n Bitmap frameBitmap = null;\n BitmapFactory.Options factoryOptions = new BitmapFactory.Options();\n factoryOptions.inSampleSize = 1;\n initInBitmap(factoryOptions);\n while (mWhileFetching) {\n try {\n byte[] jpegData = mJpegQueue.take();\n frameBitmap = BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, factoryOptions);\n } catch (IllegalArgumentException e) {\n clearInBitmap(factoryOptions);\n continue;\n } catch (InterruptedException e) {\n Log.i(TAG, \"Drawer thread is Interrupted.\");\n e.printStackTrace();\n break;\n }\n setInBitmap(factoryOptions, frameBitmap);\n drawFrame(frameBitmap);\n }\n if (frameBitmap != null) {\n frameBitmap.recycle();\n }\n mWhileFetching = false;\n }\n };\n mDrawerThread.start();\n return true;\n }\n\n /**\n * Request to stop retrieving and drawing liveview data.\n */\n public void stop() {\n mWhileFetching = false;\n if (mSlicer != null && mSlicerHandler != null) {\n mSlicerHandler.post(new Runnable() {\n\n ", "post_mask_code": "{\n try {\n mSlicer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n });\n mSlicerHandler = null;\n }\n }\n\n /**\n * Check to see whether start() is already called.\n *\n * @return true if start() is already called, false otherwise.\n */\n public boolean isStarted() {\n return mWhileFetching;\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void initInBitmap(BitmapFactory.Options options) {\n options.inBitmap = null;\n options.inMutable = true;\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void clearInBitmap(BitmapFactory.Options options) {\n if (options.inBitmap != null) {\n options.inBitmap.recycle();\n options.inBitmap = null;\n }\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void setInBitmap(BitmapFactory.Options options, Bitmap bitmap) {\n options.inBitmap = bitmap;\n }\n\n // Draw frame bitmap onto a canvas.\n private void drawFrame(Bitmap frame) {\n if (frame.getWidth() != mPreviousWidth || frame.getHeight() != mPreviousHeight) {\n onDetectedFrameSizeChanged(frame.getWidth(), frame.getHeight());\n return;\n }\n Canvas canvas = getHolder().lockCanvas();\n if (canvas == null) {\n return;\n }\n int w = frame.getWidth();\n int h = frame.getHeight();\n Rect src = new Rect(0, 0, w, h);\n float by = Math.min((float) getWidth() / w, (float) getHeight() / h);\n int offsetX = (getWidth() - (int) (w * by)) / 2;\n int offsetY = (getHeight() - (int) (h * by)) / 2;\n Rect dst = new Rect(offsetX, offsetY, getWidth() - offsetX, getHeight() - offsetY);\n canvas.drawBitmap(frame, src, dst, mFramePaint);\n getHolder().unlockCanvasAndPost(canvas);\n }\n\n // Called when the width or height of liveview frame image is changed.\n private void onDetectedFrameSizeChanged(final int width, final int height) {\n mPreviousWidth = width;\n mPreviousHeight = height;\n drawBlackFrame();\n drawBlackFrame();\n // delete triple buffers\n drawBlackFrame();\n ((Activity) getContext()).runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n // Get the SurfaceView layout parameters\n LayoutParams lp = getLayoutParams();\n lp.width = getWidth();\n lp.height = (int) (((float) height / (float) width) * (float) getWidth());\n setLayoutParams(lp);\n }\n });\n }\n\n // Draw black screen.\n private void drawBlackFrame() {\n Canvas canvas = getHolder().lockCanvas();\n if (canvas == null) {\n return;\n }\n Paint paint = new Paint();\n paint.setColor(Color.BLACK);\n paint.setStyle(Paint.Style.FILL);\n canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), paint);\n getHolder().unlockCanvasAndPost(canvas);\n }\n}\n"} {"task_id": "Java_2623", "language": "Java", "task_type": "method_body", "source_file": "java/github/ThibaudM/timelapse-sony/app/src/main/java/com/thibaudperso/sonycamera/timelapse/ui/adjustments/SimpleStreamSurfaceView.java", "mask_start_position": 9133, "mask_end_position": 9486, "canonical_solution": "{\n Canvas canvas = getHolder().lockCanvas();\n if (canvas == null) {\n return;\n }\n Paint paint = new Paint();\n paint.setColor(Color.BLACK);\n paint.setStyle(Paint.Style.FILL);\n canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), paint);\n getHolder().unlockCanvasAndPost(canvas);\n }", "pre_mask_code": "package com.thibaudperso.sonycamera.timelapse.ui.adjustments;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Rect;\nimport android.os.Build;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.ViewGroup.LayoutParams;\nimport com.thibaudperso.sonycamera.timelapse.ui.adjustments.SimpleLiveviewSlicer.Payload;\nimport java.io.IOException;\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport static android.content.ContentValues.TAG;\nimport static com.thibaudperso.sonycamera.timelapse.Constants.LOG_TAG;\n\n/**\n * A SurfaceView based class to draw liveview frames serially.\n */\npublic class SimpleStreamSurfaceView extends SurfaceView implements SurfaceHolder.Callback {\n\n private boolean mWhileFetching;\n\n private final BlockingQueue mJpegQueue = new ArrayBlockingQueue<>(2);\n\n private Thread mDrawerThread;\n\n private Handler mSlicerHandler;\n\n private int mPreviousWidth = 0;\n\n private int mPreviousHeight = 0;\n\n private final Paint mFramePaint;\n\n private SimpleLiveviewSlicer mSlicer;\n\n public SimpleStreamSurfaceView(Context context) {\n super(context);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n public SimpleStreamSurfaceView(Context context, AttributeSet attrs) {\n super(context, attrs);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n public SimpleStreamSurfaceView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n }\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n mWhileFetching = false;\n }\n\n /**\n * Start retrieving and drawing liveview frame data by new threads.\n *\n * @return true if the starting is completed successfully, false otherwise.\n * @throws IllegalStateException when Remote API object is not set.\n */\n public boolean start(final String liveviewUrl) {\n if (mWhileFetching) {\n Log.w(TAG, \"start() already starting.\");\n return false;\n }\n mWhileFetching = true;\n // A thread for retrieving liveview data from server.\n Thread slicerThread = new Thread(new Runnable() {\n\n @Override\n public void run() {\n mSlicer = null;\n try {\n // Create Slicer to open the stream and parse it.\n mSlicer = new SimpleLiveviewSlicer();\n mSlicer.open(liveviewUrl);\n Looper.prepare();\n mSlicerHandler = new Handler();\n while (mWhileFetching) {\n final Payload payload = mSlicer.nextPayload();\n if (payload == null) {\n // never occurs\n Log.e(LOG_TAG, \"Liveview Payload is null.\");\n continue;\n }\n if (mJpegQueue.size() == 2) {\n mJpegQueue.remove();\n }\n mJpegQueue.add(payload.jpegData);\n }\n } catch (IOException e) {\n Log.w(LOG_TAG, \"IOException while fetching: \" + e.getMessage());\n } finally {\n // Finalize\n try {\n if (mSlicer != null) {\n mSlicer.close();\n }\n } catch (IOException e) {\n Log.w(LOG_TAG, \"IOException while closing slicer: \" + e.getMessage());\n }\n if (mDrawerThread != null) {\n mDrawerThread.interrupt();\n }\n mJpegQueue.clear();\n mWhileFetching = false;\n }\n }\n });\n slicerThread.start();\n // A thread for drawing liveview frame fetched by above thread.\n mDrawerThread = new Thread() {\n\n @Override\n public void run() {\n Bitmap frameBitmap = null;\n BitmapFactory.Options factoryOptions = new BitmapFactory.Options();\n factoryOptions.inSampleSize = 1;\n initInBitmap(factoryOptions);\n while (mWhileFetching) {\n try {\n byte[] jpegData = mJpegQueue.take();\n frameBitmap = BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, factoryOptions);\n } catch (IllegalArgumentException e) {\n clearInBitmap(factoryOptions);\n continue;\n } catch (InterruptedException e) {\n Log.i(TAG, \"Drawer thread is Interrupted.\");\n e.printStackTrace();\n break;\n }\n setInBitmap(factoryOptions, frameBitmap);\n drawFrame(frameBitmap);\n }\n if (frameBitmap != null) {\n frameBitmap.recycle();\n }\n mWhileFetching = false;\n }\n };\n mDrawerThread.start();\n return true;\n }\n\n /**\n * Request to stop retrieving and drawing liveview data.\n */\n public void stop() {\n mWhileFetching = false;\n if (mSlicer != null && mSlicerHandler != null) {\n mSlicerHandler.post(new Runnable() {\n\n @Override\n public void run() {\n try {\n mSlicer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n });\n mSlicerHandler = null;\n }\n }\n\n /**\n * Check to see whether start() is already called.\n *\n * @return true if start() is already called, false otherwise.\n */\n public boolean isStarted() {\n return mWhileFetching;\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void initInBitmap(BitmapFactory.Options options) {\n options.inBitmap = null;\n options.inMutable = true;\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void clearInBitmap(BitmapFactory.Options options) {\n if (options.inBitmap != null) {\n options.inBitmap.recycle();\n options.inBitmap = null;\n }\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void setInBitmap(BitmapFactory.Options options, Bitmap bitmap) {\n options.inBitmap = bitmap;\n }\n\n // Draw frame bitmap onto a canvas.\n private void drawFrame(Bitmap frame) {\n if (frame.getWidth() != mPreviousWidth || frame.getHeight() != mPreviousHeight) {\n onDetectedFrameSizeChanged(frame.getWidth(), frame.getHeight());\n return;\n }\n Canvas canvas = getHolder().lockCanvas();\n if (canvas == null) {\n return;\n }\n int w = frame.getWidth();\n int h = frame.getHeight();\n Rect src = new Rect(0, 0, w, h);\n float by = Math.min((float) getWidth() / w, (float) getHeight() / h);\n int offsetX = (getWidth() - (int) (w * by)) / 2;\n int offsetY = (getHeight() - (int) (h * by)) / 2;\n Rect dst = new Rect(offsetX, offsetY, getWidth() - offsetX, getHeight() - offsetY);\n canvas.drawBitmap(frame, src, dst, mFramePaint);\n getHolder().unlockCanvasAndPost(canvas);\n }\n\n // Called when the width or height of liveview frame image is changed.\n private void onDetectedFrameSizeChanged(final int width, final int height) {\n mPreviousWidth = width;\n mPreviousHeight = height;\n drawBlackFrame();\n drawBlackFrame();\n // delete triple buffers\n drawBlackFrame();\n ((Activity) getContext()).runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n // Get the SurfaceView layout parameters\n LayoutParams lp = getLayoutParams();\n lp.width = getWidth();\n lp.height = (int) (((float) height / (float) width) * (float) getWidth());\n setLayoutParams(lp);\n }\n });\n }\n\n // Draw black screen.\n private void drawBlackFrame() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2624", "language": "Java", "task_type": "single_line", "source_file": "java/github/ThibaudM/timelapse-sony/app/src/main/java/com/thibaudperso/sonycamera/timelapse/ui/adjustments/SimpleStreamSurfaceView.java", "mask_start_position": 4930, "mask_end_position": 4974, "canonical_solution": "actoryOptions = new BitmapFactory.Options();", "pre_mask_code": "package com.thibaudperso.sonycamera.timelapse.ui.adjustments;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Rect;\nimport android.os.Build;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.ViewGroup.LayoutParams;\nimport com.thibaudperso.sonycamera.timelapse.ui.adjustments.SimpleLiveviewSlicer.Payload;\nimport java.io.IOException;\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport static android.content.ContentValues.TAG;\nimport static com.thibaudperso.sonycamera.timelapse.Constants.LOG_TAG;\n\n/**\n * A SurfaceView based class to draw liveview frames serially.\n */\npublic class SimpleStreamSurfaceView extends SurfaceView implements SurfaceHolder.Callback {\n\n private boolean mWhileFetching;\n\n private final BlockingQueue mJpegQueue = new ArrayBlockingQueue<>(2);\n\n private Thread mDrawerThread;\n\n private Handler mSlicerHandler;\n\n private int mPreviousWidth = 0;\n\n private int mPreviousHeight = 0;\n\n private final Paint mFramePaint;\n\n private SimpleLiveviewSlicer mSlicer;\n\n public SimpleStreamSurfaceView(Context context) {\n super(context);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n public SimpleStreamSurfaceView(Context context, AttributeSet attrs) {\n super(context, attrs);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n public SimpleStreamSurfaceView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n }\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n mWhileFetching = false;\n }\n\n /**\n * Start retrieving and drawing liveview frame data by new threads.\n *\n * @return true if the starting is completed successfully, false otherwise.\n * @throws IllegalStateException when Remote API object is not set.\n */\n public boolean start(final String liveviewUrl) {\n if (mWhileFetching) {\n Log.w(TAG, \"start() already starting.\");\n return false;\n }\n mWhileFetching = true;\n // A thread for retrieving liveview data from server.\n Thread slicerThread = new Thread(new Runnable() {\n\n @Override\n public void run() {\n mSlicer = null;\n try {\n // Create Slicer to open the stream and parse it.\n mSlicer = new SimpleLiveviewSlicer();\n mSlicer.open(liveviewUrl);\n Looper.prepare();\n mSlicerHandler = new Handler();\n while (mWhileFetching) {\n final Payload payload = mSlicer.nextPayload();\n if (payload == null) {\n // never occurs\n Log.e(LOG_TAG, \"Liveview Payload is null.\");\n continue;\n }\n if (mJpegQueue.size() == 2) {\n mJpegQueue.remove();\n }\n mJpegQueue.add(payload.jpegData);\n }\n } catch (IOException e) {\n Log.w(LOG_TAG, \"IOException while fetching: \" + e.getMessage());\n } finally {\n // Finalize\n try {\n if (mSlicer != null) {\n mSlicer.close();\n }\n } catch (IOException e) {\n Log.w(LOG_TAG, \"IOException while closing slicer: \" + e.getMessage());\n }\n if (mDrawerThread != null) {\n mDrawerThread.interrupt();\n }\n mJpegQueue.clear();\n mWhileFetching = false;\n }\n }\n });\n slicerThread.start();\n // A thread for drawing liveview frame fetched by above thread.\n mDrawerThread = new Thread() {\n\n @Override\n public void run() {\n Bitmap frameBitmap = null;\n BitmapFactory.Options f", "post_mask_code": "\n factoryOptions.inSampleSize = 1;\n initInBitmap(factoryOptions);\n while (mWhileFetching) {\n try {\n byte[] jpegData = mJpegQueue.take();\n frameBitmap = BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, factoryOptions);\n } catch (IllegalArgumentException e) {\n clearInBitmap(factoryOptions);\n continue;\n } catch (InterruptedException e) {\n Log.i(TAG, \"Drawer thread is Interrupted.\");\n e.printStackTrace();\n break;\n }\n setInBitmap(factoryOptions, frameBitmap);\n drawFrame(frameBitmap);\n }\n if (frameBitmap != null) {\n frameBitmap.recycle();\n }\n mWhileFetching = false;\n }\n };\n mDrawerThread.start();\n return true;\n }\n\n /**\n * Request to stop retrieving and drawing liveview data.\n */\n public void stop() {\n mWhileFetching = false;\n if (mSlicer != null && mSlicerHandler != null) {\n mSlicerHandler.post(new Runnable() {\n\n @Override\n public void run() {\n try {\n mSlicer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n });\n mSlicerHandler = null;\n }\n }\n\n /**\n * Check to see whether start() is already called.\n *\n * @return true if start() is already called, false otherwise.\n */\n public boolean isStarted() {\n return mWhileFetching;\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void initInBitmap(BitmapFactory.Options options) {\n options.inBitmap = null;\n options.inMutable = true;\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void clearInBitmap(BitmapFactory.Options options) {\n if (options.inBitmap != null) {\n options.inBitmap.recycle();\n options.inBitmap = null;\n }\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void setInBitmap(BitmapFactory.Options options, Bitmap bitmap) {\n options.inBitmap = bitmap;\n }\n\n // Draw frame bitmap onto a canvas.\n private void drawFrame(Bitmap frame) {\n if (frame.getWidth() != mPreviousWidth || frame.getHeight() != mPreviousHeight) {\n onDetectedFrameSizeChanged(frame.getWidth(), frame.getHeight());\n return;\n }\n Canvas canvas = getHolder().lockCanvas();\n if (canvas == null) {\n return;\n }\n int w = frame.getWidth();\n int h = frame.getHeight();\n Rect src = new Rect(0, 0, w, h);\n float by = Math.min((float) getWidth() / w, (float) getHeight() / h);\n int offsetX = (getWidth() - (int) (w * by)) / 2;\n int offsetY = (getHeight() - (int) (h * by)) / 2;\n Rect dst = new Rect(offsetX, offsetY, getWidth() - offsetX, getHeight() - offsetY);\n canvas.drawBitmap(frame, src, dst, mFramePaint);\n getHolder().unlockCanvasAndPost(canvas);\n }\n\n // Called when the width or height of liveview frame image is changed.\n private void onDetectedFrameSizeChanged(final int width, final int height) {\n mPreviousWidth = width;\n mPreviousHeight = height;\n drawBlackFrame();\n drawBlackFrame();\n // delete triple buffers\n drawBlackFrame();\n ((Activity) getContext()).runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n // Get the SurfaceView layout parameters\n LayoutParams lp = getLayoutParams();\n lp.width = getWidth();\n lp.height = (int) (((float) height / (float) width) * (float) getWidth());\n setLayoutParams(lp);\n }\n });\n }\n\n // Draw black screen.\n private void drawBlackFrame() {\n Canvas canvas = getHolder().lockCanvas();\n if (canvas == null) {\n return;\n }\n Paint paint = new Paint();\n paint.setColor(Color.BLACK);\n paint.setStyle(Paint.Style.FILL);\n canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), paint);\n getHolder().unlockCanvasAndPost(canvas);\n }\n}\n"} {"task_id": "Java_2625", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/ThibaudM/timelapse-sony/app/src/main/java/com/thibaudperso/sonycamera/timelapse/ui/adjustments/SimpleStreamSurfaceView.java", "mask_start_position": 6116, "mask_end_position": 6602, "canonical_solution": "public void stop() {\n mWhileFetching = false;\n if (mSlicer != null && mSlicerHandler != null) {\n mSlicerHandler.post(new Runnable() {\n\n @Override\n public void run() {\n try {\n mSlicer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n });\n mSlicerHandler = null;\n }\n }", "pre_mask_code": "package com.thibaudperso.sonycamera.timelapse.ui.adjustments;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Rect;\nimport android.os.Build;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.ViewGroup.LayoutParams;\nimport com.thibaudperso.sonycamera.timelapse.ui.adjustments.SimpleLiveviewSlicer.Payload;\nimport java.io.IOException;\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport static android.content.ContentValues.TAG;\nimport static com.thibaudperso.sonycamera.timelapse.Constants.LOG_TAG;\n\n/**\n * A SurfaceView based class to draw liveview frames serially.\n */\npublic class SimpleStreamSurfaceView extends SurfaceView implements SurfaceHolder.Callback {\n\n private boolean mWhileFetching;\n\n private final BlockingQueue mJpegQueue = new ArrayBlockingQueue<>(2);\n\n private Thread mDrawerThread;\n\n private Handler mSlicerHandler;\n\n private int mPreviousWidth = 0;\n\n private int mPreviousHeight = 0;\n\n private final Paint mFramePaint;\n\n private SimpleLiveviewSlicer mSlicer;\n\n public SimpleStreamSurfaceView(Context context) {\n super(context);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n public SimpleStreamSurfaceView(Context context, AttributeSet attrs) {\n super(context, attrs);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n public SimpleStreamSurfaceView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n }\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n mWhileFetching = false;\n }\n\n /**\n * Start retrieving and drawing liveview frame data by new threads.\n *\n * @return true if the starting is completed successfully, false otherwise.\n * @throws IllegalStateException when Remote API object is not set.\n */\n public boolean start(final String liveviewUrl) {\n if (mWhileFetching) {\n Log.w(TAG, \"start() already starting.\");\n return false;\n }\n mWhileFetching = true;\n // A thread for retrieving liveview data from server.\n Thread slicerThread = new Thread(new Runnable() {\n\n @Override\n public void run() {\n mSlicer = null;\n try {\n // Create Slicer to open the stream and parse it.\n mSlicer = new SimpleLiveviewSlicer();\n mSlicer.open(liveviewUrl);\n Looper.prepare();\n mSlicerHandler = new Handler();\n while (mWhileFetching) {\n final Payload payload = mSlicer.nextPayload();\n if (payload == null) {\n // never occurs\n Log.e(LOG_TAG, \"Liveview Payload is null.\");\n continue;\n }\n if (mJpegQueue.size() == 2) {\n mJpegQueue.remove();\n }\n mJpegQueue.add(payload.jpegData);\n }\n } catch (IOException e) {\n Log.w(LOG_TAG, \"IOException while fetching: \" + e.getMessage());\n } finally {\n // Finalize\n try {\n if (mSlicer != null) {\n mSlicer.close();\n }\n } catch (IOException e) {\n Log.w(LOG_TAG, \"IOException while closing slicer: \" + e.getMessage());\n }\n if (mDrawerThread != null) {\n mDrawerThread.interrupt();\n }\n mJpegQueue.clear();\n mWhileFetching = false;\n }\n }\n });\n slicerThread.start();\n // A thread for drawing liveview frame fetched by above thread.\n mDrawerThread = new Thread() {\n\n @Override\n public void run() {\n Bitmap frameBitmap = null;\n BitmapFactory.Options factoryOptions = new BitmapFactory.Options();\n factoryOptions.inSampleSize = 1;\n initInBitmap(factoryOptions);\n while (mWhileFetching) {\n try {\n byte[] jpegData = mJpegQueue.take();\n frameBitmap = BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, factoryOptions);\n } catch (IllegalArgumentException e) {\n clearInBitmap(factoryOptions);\n continue;\n } catch (InterruptedException e) {\n Log.i(TAG, \"Drawer thread is Interrupted.\");\n e.printStackTrace();\n break;\n }\n setInBitmap(factoryOptions, frameBitmap);\n drawFrame(frameBitmap);\n }\n if (frameBitmap != null) {\n frameBitmap.recycle();\n }\n mWhileFetching = false;\n }\n };\n mDrawerThread.start();\n return true;\n }\n\n /**\n * Request to stop retrieving and drawing liveview data.\n */\n ", "post_mask_code": "\n\n /**\n * Check to see whether start() is already called.\n *\n * @return true if start() is already called, false otherwise.\n */\n public boolean isStarted() {\n return mWhileFetching;\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void initInBitmap(BitmapFactory.Options options) {\n options.inBitmap = null;\n options.inMutable = true;\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void clearInBitmap(BitmapFactory.Options options) {\n if (options.inBitmap != null) {\n options.inBitmap.recycle();\n options.inBitmap = null;\n }\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void setInBitmap(BitmapFactory.Options options, Bitmap bitmap) {\n options.inBitmap = bitmap;\n }\n\n // Draw frame bitmap onto a canvas.\n private void drawFrame(Bitmap frame) {\n if (frame.getWidth() != mPreviousWidth || frame.getHeight() != mPreviousHeight) {\n onDetectedFrameSizeChanged(frame.getWidth(), frame.getHeight());\n return;\n }\n Canvas canvas = getHolder().lockCanvas();\n if (canvas == null) {\n return;\n }\n int w = frame.getWidth();\n int h = frame.getHeight();\n Rect src = new Rect(0, 0, w, h);\n float by = Math.min((float) getWidth() / w, (float) getHeight() / h);\n int offsetX = (getWidth() - (int) (w * by)) / 2;\n int offsetY = (getHeight() - (int) (h * by)) / 2;\n Rect dst = new Rect(offsetX, offsetY, getWidth() - offsetX, getHeight() - offsetY);\n canvas.drawBitmap(frame, src, dst, mFramePaint);\n getHolder().unlockCanvasAndPost(canvas);\n }\n\n // Called when the width or height of liveview frame image is changed.\n private void onDetectedFrameSizeChanged(final int width, final int height) {\n mPreviousWidth = width;\n mPreviousHeight = height;\n drawBlackFrame();\n drawBlackFrame();\n // delete triple buffers\n drawBlackFrame();\n ((Activity) getContext()).runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n // Get the SurfaceView layout parameters\n LayoutParams lp = getLayoutParams();\n lp.width = getWidth();\n lp.height = (int) (((float) height / (float) width) * (float) getWidth());\n setLayoutParams(lp);\n }\n });\n }\n\n // Draw black screen.\n private void drawBlackFrame() {\n Canvas canvas = getHolder().lockCanvas();\n if (canvas == null) {\n return;\n }\n Paint paint = new Paint();\n paint.setColor(Color.BLACK);\n paint.setStyle(Paint.Style.FILL);\n canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), paint);\n getHolder().unlockCanvasAndPost(canvas);\n }\n}\n"} {"task_id": "Java_2626", "language": "Java", "task_type": "try_statement", "source_file": "java/github/ThibaudM/timelapse-sony/app/src/main/java/com/thibaudperso/sonycamera/timelapse/ui/adjustments/SimpleStreamSurfaceView.java", "mask_start_position": 4115, "mask_end_position": 4401, "canonical_solution": "try {\n if (mSlicer != null) {\n mSlicer.close();\n }\n } catch (IOException e) {\n Log.w(LOG_TAG, \"IOException while closing slicer: \" + e.getMessage());\n }", "pre_mask_code": "package com.thibaudperso.sonycamera.timelapse.ui.adjustments;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Rect;\nimport android.os.Build;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.AttributeSet;\nimport android.util.Log;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.ViewGroup.LayoutParams;\nimport com.thibaudperso.sonycamera.timelapse.ui.adjustments.SimpleLiveviewSlicer.Payload;\nimport java.io.IOException;\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport static android.content.ContentValues.TAG;\nimport static com.thibaudperso.sonycamera.timelapse.Constants.LOG_TAG;\n\n/**\n * A SurfaceView based class to draw liveview frames serially.\n */\npublic class SimpleStreamSurfaceView extends SurfaceView implements SurfaceHolder.Callback {\n\n private boolean mWhileFetching;\n\n private final BlockingQueue mJpegQueue = new ArrayBlockingQueue<>(2);\n\n private Thread mDrawerThread;\n\n private Handler mSlicerHandler;\n\n private int mPreviousWidth = 0;\n\n private int mPreviousHeight = 0;\n\n private final Paint mFramePaint;\n\n private SimpleLiveviewSlicer mSlicer;\n\n public SimpleStreamSurfaceView(Context context) {\n super(context);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n public SimpleStreamSurfaceView(Context context, AttributeSet attrs) {\n super(context, attrs);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n public SimpleStreamSurfaceView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n getHolder().addCallback(this);\n mFramePaint = new Paint();\n mFramePaint.setDither(true);\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n }\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n mWhileFetching = false;\n }\n\n /**\n * Start retrieving and drawing liveview frame data by new threads.\n *\n * @return true if the starting is completed successfully, false otherwise.\n * @throws IllegalStateException when Remote API object is not set.\n */\n public boolean start(final String liveviewUrl) {\n if (mWhileFetching) {\n Log.w(TAG, \"start() already starting.\");\n return false;\n }\n mWhileFetching = true;\n // A thread for retrieving liveview data from server.\n Thread slicerThread = new Thread(new Runnable() {\n\n @Override\n public void run() {\n mSlicer = null;\n try {\n // Create Slicer to open the stream and parse it.\n mSlicer = new SimpleLiveviewSlicer();\n mSlicer.open(liveviewUrl);\n Looper.prepare();\n mSlicerHandler = new Handler();\n while (mWhileFetching) {\n final Payload payload = mSlicer.nextPayload();\n if (payload == null) {\n // never occurs\n Log.e(LOG_TAG, \"Liveview Payload is null.\");\n continue;\n }\n if (mJpegQueue.size() == 2) {\n mJpegQueue.remove();\n }\n mJpegQueue.add(payload.jpegData);\n }\n } catch (IOException e) {\n Log.w(LOG_TAG, \"IOException while fetching: \" + e.getMessage());\n } finally {\n // Finalize\n ", "post_mask_code": "\n if (mDrawerThread != null) {\n mDrawerThread.interrupt();\n }\n mJpegQueue.clear();\n mWhileFetching = false;\n }\n }\n });\n slicerThread.start();\n // A thread for drawing liveview frame fetched by above thread.\n mDrawerThread = new Thread() {\n\n @Override\n public void run() {\n Bitmap frameBitmap = null;\n BitmapFactory.Options factoryOptions = new BitmapFactory.Options();\n factoryOptions.inSampleSize = 1;\n initInBitmap(factoryOptions);\n while (mWhileFetching) {\n try {\n byte[] jpegData = mJpegQueue.take();\n frameBitmap = BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, factoryOptions);\n } catch (IllegalArgumentException e) {\n clearInBitmap(factoryOptions);\n continue;\n } catch (InterruptedException e) {\n Log.i(TAG, \"Drawer thread is Interrupted.\");\n e.printStackTrace();\n break;\n }\n setInBitmap(factoryOptions, frameBitmap);\n drawFrame(frameBitmap);\n }\n if (frameBitmap != null) {\n frameBitmap.recycle();\n }\n mWhileFetching = false;\n }\n };\n mDrawerThread.start();\n return true;\n }\n\n /**\n * Request to stop retrieving and drawing liveview data.\n */\n public void stop() {\n mWhileFetching = false;\n if (mSlicer != null && mSlicerHandler != null) {\n mSlicerHandler.post(new Runnable() {\n\n @Override\n public void run() {\n try {\n mSlicer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n });\n mSlicerHandler = null;\n }\n }\n\n /**\n * Check to see whether start() is already called.\n *\n * @return true if start() is already called, false otherwise.\n */\n public boolean isStarted() {\n return mWhileFetching;\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void initInBitmap(BitmapFactory.Options options) {\n options.inBitmap = null;\n options.inMutable = true;\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void clearInBitmap(BitmapFactory.Options options) {\n if (options.inBitmap != null) {\n options.inBitmap.recycle();\n options.inBitmap = null;\n }\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void setInBitmap(BitmapFactory.Options options, Bitmap bitmap) {\n options.inBitmap = bitmap;\n }\n\n // Draw frame bitmap onto a canvas.\n private void drawFrame(Bitmap frame) {\n if (frame.getWidth() != mPreviousWidth || frame.getHeight() != mPreviousHeight) {\n onDetectedFrameSizeChanged(frame.getWidth(), frame.getHeight());\n return;\n }\n Canvas canvas = getHolder().lockCanvas();\n if (canvas == null) {\n return;\n }\n int w = frame.getWidth();\n int h = frame.getHeight();\n Rect src = new Rect(0, 0, w, h);\n float by = Math.min((float) getWidth() / w, (float) getHeight() / h);\n int offsetX = (getWidth() - (int) (w * by)) / 2;\n int offsetY = (getHeight() - (int) (h * by)) / 2;\n Rect dst = new Rect(offsetX, offsetY, getWidth() - offsetX, getHeight() - offsetY);\n canvas.drawBitmap(frame, src, dst, mFramePaint);\n getHolder().unlockCanvasAndPost(canvas);\n }\n\n // Called when the width or height of liveview frame image is changed.\n private void onDetectedFrameSizeChanged(final int width, final int height) {\n mPreviousWidth = width;\n mPreviousHeight = height;\n drawBlackFrame();\n drawBlackFrame();\n // delete triple buffers\n drawBlackFrame();\n ((Activity) getContext()).runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n // Get the SurfaceView layout parameters\n LayoutParams lp = getLayoutParams();\n lp.width = getWidth();\n lp.height = (int) (((float) height / (float) width) * (float) getWidth());\n setLayoutParams(lp);\n }\n });\n }\n\n // Draw black screen.\n private void drawBlackFrame() {\n Canvas canvas = getHolder().lockCanvas();\n if (canvas == null) {\n return;\n }\n Paint paint = new Paint();\n paint.setColor(Color.BLACK);\n paint.setStyle(Paint.Style.FILL);\n canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), paint);\n getHolder().unlockCanvasAndPost(canvas);\n }\n}\n"} {"task_id": "Java_2627", "language": "Java", "task_type": "method_signature", "source_file": "java/github/huyongli/TigerVideo/TigerVideo/src/main/java/cn/ittiger/video/bean/IFengInfo.java", "mask_start_position": 476, "mask_end_position": 508, "canonical_solution": "public void setTabId(int tabId) ", "pre_mask_code": "package cn.ittiger.video.bean;\n\nimport cn.ittiger.database.annotation.PrimaryKey;\nimport cn.ittiger.video.util.DBManager;\n\n/**\n * @author laohu\n * @site http://ittiger.cn\n */\npublic class IFengInfo {\n\n @PrimaryKey\n private int tabId;\n\n private String itemId;\n\n public IFengInfo() {\n }\n\n public IFengInfo(int tabId, String itemId) {\n this.tabId = tabId;\n this.itemId = itemId;\n }\n\n public int getTabId() {\n return tabId;\n }\n\n ", "post_mask_code": "{\n this.tabId = tabId;\n }\n\n public String getItemId() {\n return itemId;\n }\n\n public void setItemId(String itemId) {\n this.itemId = itemId;\n }\n\n public static void save(IFengInfo iFengInfo) {\n boolean isExist = DBManager.getInstance().getSQLiteDB().queryIfExist(IFengInfo.class, String.valueOf(iFengInfo.getTabId()));\n if (isExist) {\n DBManager.getInstance().getSQLiteDB().update(iFengInfo);\n } else {\n DBManager.getInstance().getSQLiteDB().save(iFengInfo);\n }\n }\n}\n"} {"task_id": "Java_2628", "language": "Java", "task_type": "method_body", "source_file": "java/github/huyongli/TigerVideo/TigerVideo/src/main/java/cn/ittiger/video/bean/IFengInfo.java", "mask_start_position": 508, "mask_end_position": 543, "canonical_solution": "{\n this.tabId = tabId;\n }", "pre_mask_code": "package cn.ittiger.video.bean;\n\nimport cn.ittiger.database.annotation.PrimaryKey;\nimport cn.ittiger.video.util.DBManager;\n\n/**\n * @author laohu\n * @site http://ittiger.cn\n */\npublic class IFengInfo {\n\n @PrimaryKey\n private int tabId;\n\n private String itemId;\n\n public IFengInfo() {\n }\n\n public IFengInfo(int tabId, String itemId) {\n this.tabId = tabId;\n this.itemId = itemId;\n }\n\n public int getTabId() {\n return tabId;\n }\n\n public void setTabId(int tabId) ", "post_mask_code": "\n\n public String getItemId() {\n return itemId;\n }\n\n public void setItemId(String itemId) {\n this.itemId = itemId;\n }\n\n public static void save(IFengInfo iFengInfo) {\n boolean isExist = DBManager.getInstance().getSQLiteDB().queryIfExist(IFengInfo.class, String.valueOf(iFengInfo.getTabId()));\n if (isExist) {\n DBManager.getInstance().getSQLiteDB().update(iFengInfo);\n } else {\n DBManager.getInstance().getSQLiteDB().save(iFengInfo);\n }\n }\n}\n"} {"task_id": "Java_2629", "language": "Java", "task_type": "single_line", "source_file": "java/github/huyongli/TigerVideo/TigerVideo/src/main/java/cn/ittiger/video/bean/IFengInfo.java", "mask_start_position": 585, "mask_end_position": 599, "canonical_solution": "return itemId;", "pre_mask_code": "package cn.ittiger.video.bean;\n\nimport cn.ittiger.database.annotation.PrimaryKey;\nimport cn.ittiger.video.util.DBManager;\n\n/**\n * @author laohu\n * @site http://ittiger.cn\n */\npublic class IFengInfo {\n\n @PrimaryKey\n private int tabId;\n\n private String itemId;\n\n public IFengInfo() {\n }\n\n public IFengInfo(int tabId, String itemId) {\n this.tabId = tabId;\n this.itemId = itemId;\n }\n\n public int getTabId() {\n return tabId;\n }\n\n public void setTabId(int tabId) {\n this.tabId = tabId;\n }\n\n public String getItemId() {\n ", "post_mask_code": "\n }\n\n public void setItemId(String itemId) {\n this.itemId = itemId;\n }\n\n public static void save(IFengInfo iFengInfo) {\n boolean isExist = DBManager.getInstance().getSQLiteDB().queryIfExist(IFengInfo.class, String.valueOf(iFengInfo.getTabId()));\n if (isExist) {\n DBManager.getInstance().getSQLiteDB().update(iFengInfo);\n } else {\n DBManager.getInstance().getSQLiteDB().save(iFengInfo);\n }\n }\n}\n"} {"task_id": "Java_2630", "language": "Java", "task_type": "method_signature", "source_file": "java/github/salaboy/drools-workshop/drools-rest-swarm/drools-shopping-model/src/main/java/org/drools/workshop/model/Item.java", "mask_start_position": 779, "mask_end_position": 818, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage org.drools.workshop.model;\n\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * @author salaboy\n */\n@XmlRootElement\npublic class Item {\n\n private String name;\n\n private int price;\n\n public Item(String name, int price) {\n this.name = name;\n this.price = price;\n }\n\n public Item() {\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getPrice() {\n return price;\n }\n\n public void setPrice(int price) {\n this.price = price;\n }\n\n ", "post_mask_code": "{\n return \"Item{\" + \"name=\" + name + \", price=\" + price + '}';\n }\n\n @Override\n public int hashCode() {\n int hash = 5;\n hash = 73 * hash + (this.name != null ? this.name.hashCode() : 0);\n hash = 73 * hash + this.price;\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Item other = (Item) obj;\n if (this.price != other.price) {\n return false;\n }\n if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {\n return false;\n }\n return true;\n }\n}\n"} {"task_id": "Java_2631", "language": "Java", "task_type": "method_body", "source_file": "java/github/salaboy/drools-workshop/drools-rest-swarm/drools-shopping-model/src/main/java/org/drools/workshop/model/Item.java", "mask_start_position": 610, "mask_end_position": 643, "canonical_solution": "{\n this.name = name;\n }", "pre_mask_code": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage org.drools.workshop.model;\n\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * @author salaboy\n */\n@XmlRootElement\npublic class Item {\n\n private String name;\n\n private int price;\n\n public Item(String name, int price) {\n this.name = name;\n this.price = price;\n }\n\n public Item() {\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) ", "post_mask_code": "\n\n public int getPrice() {\n return price;\n }\n\n public void setPrice(int price) {\n this.price = price;\n }\n\n @Override\n public String toString() {\n return \"Item{\" + \"name=\" + name + \", price=\" + price + '}';\n }\n\n @Override\n public int hashCode() {\n int hash = 5;\n hash = 73 * hash + (this.name != null ? this.name.hashCode() : 0);\n hash = 73 * hash + this.price;\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Item other = (Item) obj;\n if (this.price != other.price) {\n return false;\n }\n if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {\n return false;\n }\n return true;\n }\n}\n"} {"task_id": "Java_2632", "language": "Java", "task_type": "single_line", "source_file": "java/github/salaboy/drools-workshop/drools-rest-swarm/drools-shopping-model/src/main/java/org/drools/workshop/model/Item.java", "mask_start_position": 623, "mask_end_position": 637, "canonical_solution": "s.name = name;", "pre_mask_code": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage org.drools.workshop.model;\n\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * @author salaboy\n */\n@XmlRootElement\npublic class Item {\n\n private String name;\n\n private int price;\n\n public Item(String name, int price) {\n this.name = name;\n this.price = price;\n }\n\n public Item() {\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n thi", "post_mask_code": "\n }\n\n public int getPrice() {\n return price;\n }\n\n public void setPrice(int price) {\n this.price = price;\n }\n\n @Override\n public String toString() {\n return \"Item{\" + \"name=\" + name + \", price=\" + price + '}';\n }\n\n @Override\n public int hashCode() {\n int hash = 5;\n hash = 73 * hash + (this.name != null ? this.name.hashCode() : 0);\n hash = 73 * hash + this.price;\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Item other = (Item) obj;\n if (this.price != other.price) {\n return false;\n }\n if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {\n return false;\n }\n return true;\n }\n}\n"} {"task_id": "Java_2633", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SkriptLang/skript-parser/src/main/java/io/github/syst3ms/skriptparser/log/LogEntry.java", "mask_start_position": 1187, "mask_end_position": 1219, "canonical_solution": "public ErrorType getErrorType() ", "pre_mask_code": "package io.github.syst3ms.skriptparser.log;\n\nimport org.jetbrains.annotations.Nullable;\nimport java.util.List;\nimport java.util.Optional;\n\n/**\n * An entry in Skript's log.\n */\npublic class LogEntry {\n\n private final LogType type;\n\n private final String message;\n\n private final int line;\n\n private final List errorContext;\n\n private final ErrorType errorType;\n\n private final String tip;\n\n public LogEntry(String message, LogType verbosity, int line, List errorContext, @Nullable ErrorType errorType) {\n this(message, verbosity, line, errorContext, errorType, null);\n }\n\n public LogEntry(String message, LogType verbosity, int line, List errorContext, @Nullable ErrorType errorType, @Nullable String tip) {\n this.type = verbosity;\n this.message = message;\n this.line = line;\n this.errorContext = errorContext;\n this.errorType = errorType;\n this.tip = tip;\n }\n\n public String getMessage() {\n return message;\n }\n\n public LogType getType() {\n return type;\n }\n\n List getErrorContext() {\n return errorContext;\n }\n\n ", "post_mask_code": "{\n return errorType;\n }\n\n public Optional getTip() {\n return Optional.ofNullable(tip);\n }\n\n public int getLine() {\n return line;\n }\n}\n"} {"task_id": "Java_2634", "language": "Java", "task_type": "method_body", "source_file": "java/github/SkriptLang/skript-parser/src/main/java/io/github/syst3ms/skriptparser/log/LogEntry.java", "mask_start_position": 1291, "mask_end_position": 1339, "canonical_solution": "{\n return Optional.ofNullable(tip);\n }", "pre_mask_code": "package io.github.syst3ms.skriptparser.log;\n\nimport org.jetbrains.annotations.Nullable;\nimport java.util.List;\nimport java.util.Optional;\n\n/**\n * An entry in Skript's log.\n */\npublic class LogEntry {\n\n private final LogType type;\n\n private final String message;\n\n private final int line;\n\n private final List errorContext;\n\n private final ErrorType errorType;\n\n private final String tip;\n\n public LogEntry(String message, LogType verbosity, int line, List errorContext, @Nullable ErrorType errorType) {\n this(message, verbosity, line, errorContext, errorType, null);\n }\n\n public LogEntry(String message, LogType verbosity, int line, List errorContext, @Nullable ErrorType errorType, @Nullable String tip) {\n this.type = verbosity;\n this.message = message;\n this.line = line;\n this.errorContext = errorContext;\n this.errorType = errorType;\n this.tip = tip;\n }\n\n public String getMessage() {\n return message;\n }\n\n public LogType getType() {\n return type;\n }\n\n List getErrorContext() {\n return errorContext;\n }\n\n public ErrorType getErrorType() {\n return errorType;\n }\n\n public Optional getTip() ", "post_mask_code": "\n\n public int getLine() {\n return line;\n }\n}\n"} {"task_id": "Java_2635", "language": "Java", "task_type": "single_line", "source_file": "java/github/SkriptLang/skript-parser/src/main/java/io/github/syst3ms/skriptparser/log/LogEntry.java", "mask_start_position": 1172, "mask_end_position": 1175, "canonical_solution": "xt;", "pre_mask_code": "package io.github.syst3ms.skriptparser.log;\n\nimport org.jetbrains.annotations.Nullable;\nimport java.util.List;\nimport java.util.Optional;\n\n/**\n * An entry in Skript's log.\n */\npublic class LogEntry {\n\n private final LogType type;\n\n private final String message;\n\n private final int line;\n\n private final List errorContext;\n\n private final ErrorType errorType;\n\n private final String tip;\n\n public LogEntry(String message, LogType verbosity, int line, List errorContext, @Nullable ErrorType errorType) {\n this(message, verbosity, line, errorContext, errorType, null);\n }\n\n public LogEntry(String message, LogType verbosity, int line, List errorContext, @Nullable ErrorType errorType, @Nullable String tip) {\n this.type = verbosity;\n this.message = message;\n this.line = line;\n this.errorContext = errorContext;\n this.errorType = errorType;\n this.tip = tip;\n }\n\n public String getMessage() {\n return message;\n }\n\n public LogType getType() {\n return type;\n }\n\n List getErrorContext() {\n return errorConte", "post_mask_code": "\n }\n\n public ErrorType getErrorType() {\n return errorType;\n }\n\n public Optional getTip() {\n return Optional.ofNullable(tip);\n }\n\n public int getLine() {\n return line;\n }\n}\n"} {"task_id": "Java_2636", "language": "Java", "task_type": "method_signature", "source_file": "java/github/AOKP/packages_apps_Settings/src/com/android/settings/accessibility/ToggleFeaturePreferenceFragment.java", "mask_start_position": 3100, "mask_end_position": 3143, "canonical_solution": "private void removeActionBarToggleSwitch() ", "pre_mask_code": "package com.android.settings.accessibility;\n\nimport android.content.Intent;\nimport android.content.pm.ResolveInfo;\nimport android.os.Bundle;\nimport android.support.v7.preference.Preference;\nimport android.support.v7.preference.PreferenceScreen;\nimport android.view.View;\nimport com.android.settings.R;\nimport com.android.settings.SettingsActivity;\nimport com.android.settings.SettingsPreferenceFragment;\nimport com.android.settings.widget.SwitchBar;\nimport com.android.settings.widget.ToggleSwitch;\n\npublic abstract class ToggleFeaturePreferenceFragment extends SettingsPreferenceFragment {\n\n protected SwitchBar mSwitchBar;\n\n protected ToggleSwitch mToggleSwitch;\n\n protected String mPreferenceKey;\n\n protected CharSequence mSettingsTitle;\n\n protected Intent mSettingsIntent;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n final int resId = getPreferenceScreenResId();\n if (resId <= 0) {\n PreferenceScreen preferenceScreen = getPreferenceManager().createPreferenceScreen(getActivity());\n setPreferenceScreen(preferenceScreen);\n }\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n SettingsActivity activity = (SettingsActivity) getActivity();\n mSwitchBar = activity.getSwitchBar();\n updateSwitchBarText(mSwitchBar);\n mToggleSwitch = mSwitchBar.getSwitch();\n onProcessArguments(getArguments());\n // Show the \"Settings\" menu as if it were a preference screen\n if (mSettingsTitle != null && mSettingsIntent != null) {\n PreferenceScreen preferenceScreen = getPreferenceScreen();\n Preference settingsPref = new Preference(preferenceScreen.getContext());\n settingsPref.setTitle(mSettingsTitle);\n settingsPref.setIconSpaceReserved(true);\n settingsPref.setIntent(mSettingsIntent);\n preferenceScreen.addPreference(settingsPref);\n }\n }\n\n @Override\n public void onActivityCreated(Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n installActionBarToggleSwitch();\n }\n\n @Override\n public void onDestroyView() {\n super.onDestroyView();\n removeActionBarToggleSwitch();\n }\n\n protected void updateSwitchBarText(SwitchBar switchBar) {\n // Implement this to provide meaningful text in switch bar\n switchBar.setSwitchBarText(R.string.accessibility_service_master_switch_title, R.string.accessibility_service_master_switch_title);\n }\n\n protected abstract void onPreferenceToggled(String preferenceKey, boolean enabled);\n\n protected void onInstallSwitchBarToggleSwitch() {\n // Implement this to set a checked listener.\n }\n\n protected void onRemoveSwitchBarToggleSwitch() {\n // Implement this to reset a checked listener.\n }\n\n private void installActionBarToggleSwitch() {\n mSwitchBar.show();\n onInstallSwitchBarToggleSwitch();\n }\n\n ", "post_mask_code": "{\n mToggleSwitch.setOnBeforeCheckedChangeListener(null);\n onRemoveSwitchBarToggleSwitch();\n mSwitchBar.hide();\n }\n\n public void setTitle(String title) {\n getActivity().setTitle(title);\n }\n\n protected void onProcessArguments(Bundle arguments) {\n mPreferenceKey = arguments.getString(AccessibilitySettings.EXTRA_PREFERENCE_KEY);\n if (arguments.containsKey(AccessibilitySettings.EXTRA_CHECKED)) {\n final boolean enabled = arguments.getBoolean(AccessibilitySettings.EXTRA_CHECKED);\n mSwitchBar.setCheckedInternal(enabled);\n }\n if (arguments.containsKey(AccessibilitySettings.EXTRA_RESOLVE_INFO)) {\n ResolveInfo info = arguments.getParcelable(AccessibilitySettings.EXTRA_RESOLVE_INFO);\n getActivity().setTitle(info.loadLabel(getPackageManager()).toString());\n } else if (arguments.containsKey(AccessibilitySettings.EXTRA_TITLE)) {\n setTitle(arguments.getString(AccessibilitySettings.EXTRA_TITLE));\n }\n if (arguments.containsKey(AccessibilitySettings.EXTRA_SUMMARY_RES)) {\n final int summary = arguments.getInt(AccessibilitySettings.EXTRA_SUMMARY_RES);\n mFooterPreferenceMixin.createFooterPreference().setTitle(summary);\n } else if (arguments.containsKey(AccessibilitySettings.EXTRA_SUMMARY)) {\n final CharSequence summary = arguments.getCharSequence(AccessibilitySettings.EXTRA_SUMMARY);\n mFooterPreferenceMixin.createFooterPreference().setTitle(summary);\n }\n }\n}\n"} {"task_id": "Java_2637", "language": "Java", "task_type": "method_body", "source_file": "java/github/AOKP/packages_apps_Settings/src/com/android/settings/accessibility/ToggleFeaturePreferenceFragment.java", "mask_start_position": 2906, "mask_end_position": 2968, "canonical_solution": "{\n // Implement this to reset a checked listener.\n }", "pre_mask_code": "package com.android.settings.accessibility;\n\nimport android.content.Intent;\nimport android.content.pm.ResolveInfo;\nimport android.os.Bundle;\nimport android.support.v7.preference.Preference;\nimport android.support.v7.preference.PreferenceScreen;\nimport android.view.View;\nimport com.android.settings.R;\nimport com.android.settings.SettingsActivity;\nimport com.android.settings.SettingsPreferenceFragment;\nimport com.android.settings.widget.SwitchBar;\nimport com.android.settings.widget.ToggleSwitch;\n\npublic abstract class ToggleFeaturePreferenceFragment extends SettingsPreferenceFragment {\n\n protected SwitchBar mSwitchBar;\n\n protected ToggleSwitch mToggleSwitch;\n\n protected String mPreferenceKey;\n\n protected CharSequence mSettingsTitle;\n\n protected Intent mSettingsIntent;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n final int resId = getPreferenceScreenResId();\n if (resId <= 0) {\n PreferenceScreen preferenceScreen = getPreferenceManager().createPreferenceScreen(getActivity());\n setPreferenceScreen(preferenceScreen);\n }\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n SettingsActivity activity = (SettingsActivity) getActivity();\n mSwitchBar = activity.getSwitchBar();\n updateSwitchBarText(mSwitchBar);\n mToggleSwitch = mSwitchBar.getSwitch();\n onProcessArguments(getArguments());\n // Show the \"Settings\" menu as if it were a preference screen\n if (mSettingsTitle != null && mSettingsIntent != null) {\n PreferenceScreen preferenceScreen = getPreferenceScreen();\n Preference settingsPref = new Preference(preferenceScreen.getContext());\n settingsPref.setTitle(mSettingsTitle);\n settingsPref.setIconSpaceReserved(true);\n settingsPref.setIntent(mSettingsIntent);\n preferenceScreen.addPreference(settingsPref);\n }\n }\n\n @Override\n public void onActivityCreated(Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n installActionBarToggleSwitch();\n }\n\n @Override\n public void onDestroyView() {\n super.onDestroyView();\n removeActionBarToggleSwitch();\n }\n\n protected void updateSwitchBarText(SwitchBar switchBar) {\n // Implement this to provide meaningful text in switch bar\n switchBar.setSwitchBarText(R.string.accessibility_service_master_switch_title, R.string.accessibility_service_master_switch_title);\n }\n\n protected abstract void onPreferenceToggled(String preferenceKey, boolean enabled);\n\n protected void onInstallSwitchBarToggleSwitch() {\n // Implement this to set a checked listener.\n }\n\n protected void onRemoveSwitchBarToggleSwitch() ", "post_mask_code": "\n\n private void installActionBarToggleSwitch() {\n mSwitchBar.show();\n onInstallSwitchBarToggleSwitch();\n }\n\n private void removeActionBarToggleSwitch() {\n mToggleSwitch.setOnBeforeCheckedChangeListener(null);\n onRemoveSwitchBarToggleSwitch();\n mSwitchBar.hide();\n }\n\n public void setTitle(String title) {\n getActivity().setTitle(title);\n }\n\n protected void onProcessArguments(Bundle arguments) {\n mPreferenceKey = arguments.getString(AccessibilitySettings.EXTRA_PREFERENCE_KEY);\n if (arguments.containsKey(AccessibilitySettings.EXTRA_CHECKED)) {\n final boolean enabled = arguments.getBoolean(AccessibilitySettings.EXTRA_CHECKED);\n mSwitchBar.setCheckedInternal(enabled);\n }\n if (arguments.containsKey(AccessibilitySettings.EXTRA_RESOLVE_INFO)) {\n ResolveInfo info = arguments.getParcelable(AccessibilitySettings.EXTRA_RESOLVE_INFO);\n getActivity().setTitle(info.loadLabel(getPackageManager()).toString());\n } else if (arguments.containsKey(AccessibilitySettings.EXTRA_TITLE)) {\n setTitle(arguments.getString(AccessibilitySettings.EXTRA_TITLE));\n }\n if (arguments.containsKey(AccessibilitySettings.EXTRA_SUMMARY_RES)) {\n final int summary = arguments.getInt(AccessibilitySettings.EXTRA_SUMMARY_RES);\n mFooterPreferenceMixin.createFooterPreference().setTitle(summary);\n } else if (arguments.containsKey(AccessibilitySettings.EXTRA_SUMMARY)) {\n final CharSequence summary = arguments.getCharSequence(AccessibilitySettings.EXTRA_SUMMARY);\n mFooterPreferenceMixin.createFooterPreference().setTitle(summary);\n }\n }\n}\n"} {"task_id": "Java_2638", "language": "Java", "task_type": "single_line", "source_file": "java/github/AOKP/packages_apps_Settings/src/com/android/settings/accessibility/ToggleFeaturePreferenceFragment.java", "mask_start_position": 3475, "mask_end_position": 3516, "canonical_solution": "essibilitySettings.EXTRA_PREFERENCE_KEY);", "pre_mask_code": "package com.android.settings.accessibility;\n\nimport android.content.Intent;\nimport android.content.pm.ResolveInfo;\nimport android.os.Bundle;\nimport android.support.v7.preference.Preference;\nimport android.support.v7.preference.PreferenceScreen;\nimport android.view.View;\nimport com.android.settings.R;\nimport com.android.settings.SettingsActivity;\nimport com.android.settings.SettingsPreferenceFragment;\nimport com.android.settings.widget.SwitchBar;\nimport com.android.settings.widget.ToggleSwitch;\n\npublic abstract class ToggleFeaturePreferenceFragment extends SettingsPreferenceFragment {\n\n protected SwitchBar mSwitchBar;\n\n protected ToggleSwitch mToggleSwitch;\n\n protected String mPreferenceKey;\n\n protected CharSequence mSettingsTitle;\n\n protected Intent mSettingsIntent;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n final int resId = getPreferenceScreenResId();\n if (resId <= 0) {\n PreferenceScreen preferenceScreen = getPreferenceManager().createPreferenceScreen(getActivity());\n setPreferenceScreen(preferenceScreen);\n }\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n SettingsActivity activity = (SettingsActivity) getActivity();\n mSwitchBar = activity.getSwitchBar();\n updateSwitchBarText(mSwitchBar);\n mToggleSwitch = mSwitchBar.getSwitch();\n onProcessArguments(getArguments());\n // Show the \"Settings\" menu as if it were a preference screen\n if (mSettingsTitle != null && mSettingsIntent != null) {\n PreferenceScreen preferenceScreen = getPreferenceScreen();\n Preference settingsPref = new Preference(preferenceScreen.getContext());\n settingsPref.setTitle(mSettingsTitle);\n settingsPref.setIconSpaceReserved(true);\n settingsPref.setIntent(mSettingsIntent);\n preferenceScreen.addPreference(settingsPref);\n }\n }\n\n @Override\n public void onActivityCreated(Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n installActionBarToggleSwitch();\n }\n\n @Override\n public void onDestroyView() {\n super.onDestroyView();\n removeActionBarToggleSwitch();\n }\n\n protected void updateSwitchBarText(SwitchBar switchBar) {\n // Implement this to provide meaningful text in switch bar\n switchBar.setSwitchBarText(R.string.accessibility_service_master_switch_title, R.string.accessibility_service_master_switch_title);\n }\n\n protected abstract void onPreferenceToggled(String preferenceKey, boolean enabled);\n\n protected void onInstallSwitchBarToggleSwitch() {\n // Implement this to set a checked listener.\n }\n\n protected void onRemoveSwitchBarToggleSwitch() {\n // Implement this to reset a checked listener.\n }\n\n private void installActionBarToggleSwitch() {\n mSwitchBar.show();\n onInstallSwitchBarToggleSwitch();\n }\n\n private void removeActionBarToggleSwitch() {\n mToggleSwitch.setOnBeforeCheckedChangeListener(null);\n onRemoveSwitchBarToggleSwitch();\n mSwitchBar.hide();\n }\n\n public void setTitle(String title) {\n getActivity().setTitle(title);\n }\n\n protected void onProcessArguments(Bundle arguments) {\n mPreferenceKey = arguments.getString(Acc", "post_mask_code": "\n if (arguments.containsKey(AccessibilitySettings.EXTRA_CHECKED)) {\n final boolean enabled = arguments.getBoolean(AccessibilitySettings.EXTRA_CHECKED);\n mSwitchBar.setCheckedInternal(enabled);\n }\n if (arguments.containsKey(AccessibilitySettings.EXTRA_RESOLVE_INFO)) {\n ResolveInfo info = arguments.getParcelable(AccessibilitySettings.EXTRA_RESOLVE_INFO);\n getActivity().setTitle(info.loadLabel(getPackageManager()).toString());\n } else if (arguments.containsKey(AccessibilitySettings.EXTRA_TITLE)) {\n setTitle(arguments.getString(AccessibilitySettings.EXTRA_TITLE));\n }\n if (arguments.containsKey(AccessibilitySettings.EXTRA_SUMMARY_RES)) {\n final int summary = arguments.getInt(AccessibilitySettings.EXTRA_SUMMARY_RES);\n mFooterPreferenceMixin.createFooterPreference().setTitle(summary);\n } else if (arguments.containsKey(AccessibilitySettings.EXTRA_SUMMARY)) {\n final CharSequence summary = arguments.getCharSequence(AccessibilitySettings.EXTRA_SUMMARY);\n mFooterPreferenceMixin.createFooterPreference().setTitle(summary);\n }\n }\n}\n"} {"task_id": "Java_2639", "language": "Java", "task_type": "method_signature", "source_file": "java/github/qcadoo/mes/mes-plugins/mes-plugins-technologies/src/main/java/com/qcadoo/mes/technologies/imports/productToProductGroupTechnology/ProductToProductGroupTechnologyCellBinderRegistry.java", "mask_start_position": 708, "mask_end_position": 747, "canonical_solution": "@PostConstruct\n private void init() ", "pre_mask_code": "package com.qcadoo.mes.technologies.imports.productToProductGroupTechnology;\n\nimport static com.qcadoo.mes.basic.imports.dtos.CellBinder.required;\nimport javax.annotation.PostConstruct;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport com.qcadoo.mes.basic.imports.dtos.CellBinderRegistry;\nimport com.qcadoo.mes.basic.imports.helpers.CellParser;\nimport com.qcadoo.mes.technologies.constants.ProductToProductGroupFields;\n\n@Component\npublic class ProductToProductGroupTechnologyCellBinderRegistry {\n\n private CellBinderRegistry cellBinderRegistry = new CellBinderRegistry();\n\n @Autowired\n private CellParser productCellParser;\n\n ", "post_mask_code": "{\n cellBinderRegistry.setCellBinder(required(ProductToProductGroupFields.FINAL_PRODUCT, productCellParser));\n cellBinderRegistry.setCellBinder(required(ProductToProductGroupFields.PRODUCT_FAMILY, productCellParser));\n cellBinderRegistry.setCellBinder(required(ProductToProductGroupFields.ORDER_PRODUCT, productCellParser));\n }\n\n public CellBinderRegistry getCellBinderRegistry() {\n return cellBinderRegistry;\n }\n}\n"} {"task_id": "Java_2640", "language": "Java", "task_type": "method_body", "source_file": "java/github/qcadoo/mes/mes-plugins/mes-plugins-technologies/src/main/java/com/qcadoo/mes/technologies/imports/productToProductGroupTechnology/ProductToProductGroupTechnologyCellBinderRegistry.java", "mask_start_position": 1153, "mask_end_position": 1195, "canonical_solution": "{\n return cellBinderRegistry;\n }", "pre_mask_code": "package com.qcadoo.mes.technologies.imports.productToProductGroupTechnology;\n\nimport static com.qcadoo.mes.basic.imports.dtos.CellBinder.required;\nimport javax.annotation.PostConstruct;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport com.qcadoo.mes.basic.imports.dtos.CellBinderRegistry;\nimport com.qcadoo.mes.basic.imports.helpers.CellParser;\nimport com.qcadoo.mes.technologies.constants.ProductToProductGroupFields;\n\n@Component\npublic class ProductToProductGroupTechnologyCellBinderRegistry {\n\n private CellBinderRegistry cellBinderRegistry = new CellBinderRegistry();\n\n @Autowired\n private CellParser productCellParser;\n\n @PostConstruct\n private void init() {\n cellBinderRegistry.setCellBinder(required(ProductToProductGroupFields.FINAL_PRODUCT, productCellParser));\n cellBinderRegistry.setCellBinder(required(ProductToProductGroupFields.PRODUCT_FAMILY, productCellParser));\n cellBinderRegistry.setCellBinder(required(ProductToProductGroupFields.ORDER_PRODUCT, productCellParser));\n }\n\n public CellBinderRegistry getCellBinderRegistry() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2641", "language": "Java", "task_type": "single_line", "source_file": "java/github/qcadoo/mes/mes-plugins/mes-plugins-technologies/src/main/java/com/qcadoo/mes/technologies/imports/productToProductGroupTechnology/ProductToProductGroupTechnologyCellBinderRegistry.java", "mask_start_position": 990, "mask_end_position": 1091, "canonical_solution": "BinderRegistry.setCellBinder(required(ProductToProductGroupFields.ORDER_PRODUCT, productCellParser));", "pre_mask_code": "package com.qcadoo.mes.technologies.imports.productToProductGroupTechnology;\n\nimport static com.qcadoo.mes.basic.imports.dtos.CellBinder.required;\nimport javax.annotation.PostConstruct;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport com.qcadoo.mes.basic.imports.dtos.CellBinderRegistry;\nimport com.qcadoo.mes.basic.imports.helpers.CellParser;\nimport com.qcadoo.mes.technologies.constants.ProductToProductGroupFields;\n\n@Component\npublic class ProductToProductGroupTechnologyCellBinderRegistry {\n\n private CellBinderRegistry cellBinderRegistry = new CellBinderRegistry();\n\n @Autowired\n private CellParser productCellParser;\n\n @PostConstruct\n private void init() {\n cellBinderRegistry.setCellBinder(required(ProductToProductGroupFields.FINAL_PRODUCT, productCellParser));\n cellBinderRegistry.setCellBinder(required(ProductToProductGroupFields.PRODUCT_FAMILY, productCellParser));\n cell", "post_mask_code": "\n }\n\n public CellBinderRegistry getCellBinderRegistry() {\n return cellBinderRegistry;\n }\n}\n"} {"task_id": "Java_2642", "language": "Java", "task_type": "method_signature", "source_file": "java/github/microsoft/botbuilder-java/libraries/bot-dialogs/src/main/java/com/microsoft/recognizers/text/matcher/StringMatcher.java", "mask_start_position": 1963, "mask_end_position": 2023, "canonical_solution": "void init(List> tokenizedValues, String[] ids) ", "pre_mask_code": "package com.microsoft.recognizers.text.matcher;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\nimport java.util.stream.StreamSupport;\n\npublic class StringMatcher {\n\n private final ITokenizer tokenizer;\n\n private final IMatcher matcher;\n\n public StringMatcher(MatchStrategy strategy, ITokenizer tokenizer) {\n this.tokenizer = tokenizer != null ? tokenizer : new SimpleTokenizer();\n switch(strategy) {\n case AcAutomaton:\n matcher = new AcAutomation<>();\n break;\n case TrieTree:\n matcher = new TrieTree<>();\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n\n public StringMatcher(MatchStrategy strategy) {\n this(strategy, null);\n }\n\n public StringMatcher(ITokenizer tokenizer) {\n this(MatchStrategy.TrieTree, tokenizer);\n }\n\n public StringMatcher() {\n this(MatchStrategy.TrieTree, null);\n }\n\n public void init(Iterable values) {\n init(values, StreamSupport.stream(values.spliterator(), false).toArray(size -> new String[size]));\n }\n\n void init(Iterable values, String[] ids) {\n List> tokenizedValues = getTokenizedText(values);\n init(tokenizedValues, ids);\n }\n\n void init(Map> valuesMap) {\n ArrayList values = new ArrayList<>();\n ArrayList ids = new ArrayList<>();\n for (Map.Entry> item : valuesMap.entrySet()) {\n String id = item.getKey();\n for (String value : item.getValue()) {\n values.add(value);\n ids.add(id);\n }\n }\n List> tokenizedValues = getTokenizedText(values);\n init(tokenizedValues, ids.toArray(new String[0]));\n }\n\n ", "post_mask_code": "{\n matcher.init(tokenizedValues, ids);\n }\n\n private List> getTokenizedText(Iterable values) {\n List> result = new ArrayList<>();\n for (String value : values) {\n result.add(tokenizer.tokenize(value).stream().map(i -> i.text).collect(Collectors.toCollection(ArrayList::new)));\n }\n return result;\n }\n\n public Iterable> find(Iterable tokenizedQuery) {\n return matcher.find(tokenizedQuery);\n }\n\n public Iterable> find(String queryText) {\n List queryTokens = tokenizer.tokenize(queryText);\n Iterable tokenizedQueryText = queryTokens.stream().map(t -> t.text).collect(Collectors.toCollection(ArrayList::new));\n List> result = new ArrayList<>();\n for (MatchResult r : find(tokenizedQueryText)) {\n Token startToken = queryTokens.get(r.getStart());\n Token endToken = queryTokens.get(r.getStart() + r.getLength() - 1);\n int start = startToken.getStart();\n int length = endToken.getEnd() - startToken.getStart();\n String rtext = queryText.substring(start, start + length);\n result.add(new MatchResult(start, length, r.getCanonicalValues(), rtext));\n }\n return result;\n }\n}\n"} {"task_id": "Java_2643", "language": "Java", "task_type": "method_body", "source_file": "java/github/microsoft/botbuilder-java/libraries/bot-dialogs/src/main/java/com/microsoft/recognizers/text/matcher/StringMatcher.java", "mask_start_position": 1125, "mask_end_position": 1239, "canonical_solution": "{\n init(values, StreamSupport.stream(values.spliterator(), false).toArray(size -> new String[size]));\n }", "pre_mask_code": "package com.microsoft.recognizers.text.matcher;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\nimport java.util.stream.StreamSupport;\n\npublic class StringMatcher {\n\n private final ITokenizer tokenizer;\n\n private final IMatcher matcher;\n\n public StringMatcher(MatchStrategy strategy, ITokenizer tokenizer) {\n this.tokenizer = tokenizer != null ? tokenizer : new SimpleTokenizer();\n switch(strategy) {\n case AcAutomaton:\n matcher = new AcAutomation<>();\n break;\n case TrieTree:\n matcher = new TrieTree<>();\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n\n public StringMatcher(MatchStrategy strategy) {\n this(strategy, null);\n }\n\n public StringMatcher(ITokenizer tokenizer) {\n this(MatchStrategy.TrieTree, tokenizer);\n }\n\n public StringMatcher() {\n this(MatchStrategy.TrieTree, null);\n }\n\n public void init(Iterable values) ", "post_mask_code": "\n\n void init(Iterable values, String[] ids) {\n List> tokenizedValues = getTokenizedText(values);\n init(tokenizedValues, ids);\n }\n\n void init(Map> valuesMap) {\n ArrayList values = new ArrayList<>();\n ArrayList ids = new ArrayList<>();\n for (Map.Entry> item : valuesMap.entrySet()) {\n String id = item.getKey();\n for (String value : item.getValue()) {\n values.add(value);\n ids.add(id);\n }\n }\n List> tokenizedValues = getTokenizedText(values);\n init(tokenizedValues, ids.toArray(new String[0]));\n }\n\n void init(List> tokenizedValues, String[] ids) {\n matcher.init(tokenizedValues, ids);\n }\n\n private List> getTokenizedText(Iterable values) {\n List> result = new ArrayList<>();\n for (String value : values) {\n result.add(tokenizer.tokenize(value).stream().map(i -> i.text).collect(Collectors.toCollection(ArrayList::new)));\n }\n return result;\n }\n\n public Iterable> find(Iterable tokenizedQuery) {\n return matcher.find(tokenizedQuery);\n }\n\n public Iterable> find(String queryText) {\n List queryTokens = tokenizer.tokenize(queryText);\n Iterable tokenizedQueryText = queryTokens.stream().map(t -> t.text).collect(Collectors.toCollection(ArrayList::new));\n List> result = new ArrayList<>();\n for (MatchResult r : find(tokenizedQueryText)) {\n Token startToken = queryTokens.get(r.getStart());\n Token endToken = queryTokens.get(r.getStart() + r.getLength() - 1);\n int start = startToken.getStart();\n int length = endToken.getEnd() - startToken.getStart();\n String rtext = queryText.substring(start, start + length);\n result.add(new MatchResult(start, length, r.getCanonicalValues(), rtext));\n }\n return result;\n }\n}\n"} {"task_id": "Java_2644", "language": "Java", "task_type": "single_line", "source_file": "java/github/microsoft/botbuilder-java/libraries/bot-dialogs/src/main/java/com/microsoft/recognizers/text/matcher/StringMatcher.java", "mask_start_position": 1912, "mask_end_position": 1951, "canonical_solution": "zedValues, ids.toArray(new String[0]));", "pre_mask_code": "package com.microsoft.recognizers.text.matcher;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\nimport java.util.stream.StreamSupport;\n\npublic class StringMatcher {\n\n private final ITokenizer tokenizer;\n\n private final IMatcher matcher;\n\n public StringMatcher(MatchStrategy strategy, ITokenizer tokenizer) {\n this.tokenizer = tokenizer != null ? tokenizer : new SimpleTokenizer();\n switch(strategy) {\n case AcAutomaton:\n matcher = new AcAutomation<>();\n break;\n case TrieTree:\n matcher = new TrieTree<>();\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n\n public StringMatcher(MatchStrategy strategy) {\n this(strategy, null);\n }\n\n public StringMatcher(ITokenizer tokenizer) {\n this(MatchStrategy.TrieTree, tokenizer);\n }\n\n public StringMatcher() {\n this(MatchStrategy.TrieTree, null);\n }\n\n public void init(Iterable values) {\n init(values, StreamSupport.stream(values.spliterator(), false).toArray(size -> new String[size]));\n }\n\n void init(Iterable values, String[] ids) {\n List> tokenizedValues = getTokenizedText(values);\n init(tokenizedValues, ids);\n }\n\n void init(Map> valuesMap) {\n ArrayList values = new ArrayList<>();\n ArrayList ids = new ArrayList<>();\n for (Map.Entry> item : valuesMap.entrySet()) {\n String id = item.getKey();\n for (String value : item.getValue()) {\n values.add(value);\n ids.add(id);\n }\n }\n List> tokenizedValues = getTokenizedText(values);\n init(tokeni", "post_mask_code": "\n }\n\n void init(List> tokenizedValues, String[] ids) {\n matcher.init(tokenizedValues, ids);\n }\n\n private List> getTokenizedText(Iterable values) {\n List> result = new ArrayList<>();\n for (String value : values) {\n result.add(tokenizer.tokenize(value).stream().map(i -> i.text).collect(Collectors.toCollection(ArrayList::new)));\n }\n return result;\n }\n\n public Iterable> find(Iterable tokenizedQuery) {\n return matcher.find(tokenizedQuery);\n }\n\n public Iterable> find(String queryText) {\n List queryTokens = tokenizer.tokenize(queryText);\n Iterable tokenizedQueryText = queryTokens.stream().map(t -> t.text).collect(Collectors.toCollection(ArrayList::new));\n List> result = new ArrayList<>();\n for (MatchResult r : find(tokenizedQueryText)) {\n Token startToken = queryTokens.get(r.getStart());\n Token endToken = queryTokens.get(r.getStart() + r.getLength() - 1);\n int start = startToken.getStart();\n int length = endToken.getEnd() - startToken.getStart();\n String rtext = queryText.substring(start, start + length);\n result.add(new MatchResult(start, length, r.getCanonicalValues(), rtext));\n }\n return result;\n }\n}\n"} {"task_id": "Java_2645", "language": "Java", "task_type": "switch_case", "source_file": "java/github/microsoft/botbuilder-java/libraries/bot-dialogs/src/main/java/com/microsoft/recognizers/text/matcher/StringMatcher.java", "mask_start_position": 500, "mask_end_position": 798, "canonical_solution": "switch(strategy) {\n case AcAutomaton:\n matcher = new AcAutomation<>();\n break;\n case TrieTree:\n matcher = new TrieTree<>();\n break;\n default:\n throw new IllegalArgumentException();\n }", "pre_mask_code": "package com.microsoft.recognizers.text.matcher;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\nimport java.util.stream.StreamSupport;\n\npublic class StringMatcher {\n\n private final ITokenizer tokenizer;\n\n private final IMatcher matcher;\n\n public StringMatcher(MatchStrategy strategy, ITokenizer tokenizer) {\n this.tokenizer = tokenizer != null ? tokenizer : new SimpleTokenizer();\n ", "post_mask_code": "\n }\n\n public StringMatcher(MatchStrategy strategy) {\n this(strategy, null);\n }\n\n public StringMatcher(ITokenizer tokenizer) {\n this(MatchStrategy.TrieTree, tokenizer);\n }\n\n public StringMatcher() {\n this(MatchStrategy.TrieTree, null);\n }\n\n public void init(Iterable values) {\n init(values, StreamSupport.stream(values.spliterator(), false).toArray(size -> new String[size]));\n }\n\n void init(Iterable values, String[] ids) {\n List> tokenizedValues = getTokenizedText(values);\n init(tokenizedValues, ids);\n }\n\n void init(Map> valuesMap) {\n ArrayList values = new ArrayList<>();\n ArrayList ids = new ArrayList<>();\n for (Map.Entry> item : valuesMap.entrySet()) {\n String id = item.getKey();\n for (String value : item.getValue()) {\n values.add(value);\n ids.add(id);\n }\n }\n List> tokenizedValues = getTokenizedText(values);\n init(tokenizedValues, ids.toArray(new String[0]));\n }\n\n void init(List> tokenizedValues, String[] ids) {\n matcher.init(tokenizedValues, ids);\n }\n\n private List> getTokenizedText(Iterable values) {\n List> result = new ArrayList<>();\n for (String value : values) {\n result.add(tokenizer.tokenize(value).stream().map(i -> i.text).collect(Collectors.toCollection(ArrayList::new)));\n }\n return result;\n }\n\n public Iterable> find(Iterable tokenizedQuery) {\n return matcher.find(tokenizedQuery);\n }\n\n public Iterable> find(String queryText) {\n List queryTokens = tokenizer.tokenize(queryText);\n Iterable tokenizedQueryText = queryTokens.stream().map(t -> t.text).collect(Collectors.toCollection(ArrayList::new));\n List> result = new ArrayList<>();\n for (MatchResult r : find(tokenizedQueryText)) {\n Token startToken = queryTokens.get(r.getStart());\n Token endToken = queryTokens.get(r.getStart() + r.getLength() - 1);\n int start = startToken.getStart();\n int length = endToken.getEnd() - startToken.getStart();\n String rtext = queryText.substring(start, start + length);\n result.add(new MatchResult(start, length, r.getCanonicalValues(), rtext));\n }\n return result;\n }\n}\n"} {"task_id": "Java_2646", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/hss01248/ImageLoader/imageloader/src/main/java/com/hss01248/image/interfaces/ILoader.java", "mask_start_position": 1302, "mask_end_position": 1363, "canonical_solution": "public abstract void download(String url, FileGetter getter);", "pre_mask_code": "package com.hss01248.image.interfaces;\n\nimport android.content.Context;\nimport android.view.View;\nimport com.hss01248.image.config.SingleConfig;\nimport java.io.File;\n\n/**\n * Created by Administrator on 2017/3/14 0014.\n */\npublic abstract class ILoader {\n\n public abstract void init(Context context, int cacheSizeInM);\n\n public abstract void requestAsBitmap(SingleConfig config);\n\n public abstract void requestForNormalDiaplay(SingleConfig config);\n\n public abstract void debug(SingleConfig config);\n\n public abstract void pause();\n\n public abstract void resume();\n\n public abstract void clearDiskCache();\n\n public abstract void clearMomoryCache();\n\n public abstract long getCacheSize();\n\n public abstract void clearCacheByUrl(String url);\n\n public abstract void clearMomoryCache(View view);\n\n public abstract void clearMomoryCache(String url);\n\n public abstract File getFileFromDiskCache(String url);\n\n public abstract void getFileFromDiskCache(String url, FileGetter getter);\n\n public abstract boolean isCached(String url);\n\n public abstract void trimMemory(int level);\n\n public abstract void onLowMemory();\n\n /**\n * 如果有缓存,就直接从缓存里拿,如果没有,就从网上下载\n * 返回的file在图片框架的缓存中,非常规文件名,需要自己拷贝出来.\n *\n * @param url\n * @param getter\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2647", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/directory-server/server-config/src/main/java/org/apache/directory/server/config/beans/ChangePasswordServerBean.java", "mask_start_position": 673, "mask_end_position": 712, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "package org.apache.directory.server.config.beans;\n\nimport org.apache.directory.api.ldap.model.name.Dn;\n\n/**\n * A class used to store the ChangePasswordServer configuration.\n *\n * @author Apache Directory Project\n */\npublic class ChangePasswordServerBean extends DSBasedServerBean {\n\n /**\n * Create a new ChangePasswordServer instance\n */\n public ChangePasswordServerBean() {\n super();\n }\n\n @Override\n public void setSearchBaseDn(Dn searchBaseDn) {\n throw new UnsupportedOperationException(\"No need to set the search base DN, the kerberos server's search base DN is used internally\");\n }\n\n ", "post_mask_code": "{\n return \"ChangePasswordServer\";\n }\n}\n"} {"task_id": "Java_2648", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/directory-server/server-config/src/main/java/org/apache/directory/server/config/beans/ChangePasswordServerBean.java", "mask_start_position": 712, "mask_end_position": 758, "canonical_solution": "{\n return \"ChangePasswordServer\";\n }", "pre_mask_code": "package org.apache.directory.server.config.beans;\n\nimport org.apache.directory.api.ldap.model.name.Dn;\n\n/**\n * A class used to store the ChangePasswordServer configuration.\n *\n * @author Apache Directory Project\n */\npublic class ChangePasswordServerBean extends DSBasedServerBean {\n\n /**\n * Create a new ChangePasswordServer instance\n */\n public ChangePasswordServerBean() {\n super();\n }\n\n @Override\n public void setSearchBaseDn(Dn searchBaseDn) {\n throw new UnsupportedOperationException(\"No need to set the search base DN, the kerberos server's search base DN is used internally\");\n }\n\n @Override\n public String toString() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2649", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/directory-server/server-config/src/main/java/org/apache/directory/server/config/beans/ChangePasswordServerBean.java", "mask_start_position": 725, "mask_end_position": 752, "canonical_solution": "urn \"ChangePasswordServer\";", "pre_mask_code": "package org.apache.directory.server.config.beans;\n\nimport org.apache.directory.api.ldap.model.name.Dn;\n\n/**\n * A class used to store the ChangePasswordServer configuration.\n *\n * @author Apache Directory Project\n */\npublic class ChangePasswordServerBean extends DSBasedServerBean {\n\n /**\n * Create a new ChangePasswordServer instance\n */\n public ChangePasswordServerBean() {\n super();\n }\n\n @Override\n public void setSearchBaseDn(Dn searchBaseDn) {\n throw new UnsupportedOperationException(\"No need to set the search base DN, the kerberos server's search base DN is used internally\");\n }\n\n @Override\n public String toString() {\n ret", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2650", "language": "Java", "task_type": "method_signature", "source_file": "java/github/mariorez/kanban-board/src/main/java/org/seariver/kanbanboard/write/adapter/in/WriteExceptionHandler.java", "mask_start_position": 2887, "mask_end_position": 3007, "canonical_solution": "@ExceptionHandler(DomainException.class)\n public ResponseEntity onDomainException(DomainException exception) ", "pre_mask_code": "package org.seariver.kanbanboard.write.adapter.in;\n\nimport org.seariver.kanbanboard.write.domain.exception.DomainException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.http.converter.HttpMessageNotReadableException;\nimport org.springframework.web.bind.MethodArgumentNotValidException;\nimport org.springframework.web.bind.annotation.ExceptionHandler;\nimport org.springframework.web.bind.annotation.RestControllerAdvice;\nimport org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;\nimport javax.validation.ConstraintViolationException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\nimport static org.springframework.http.HttpStatus.BAD_REQUEST;\n\n@RestControllerAdvice\npublic class WriteExceptionHandler {\n\n public static final String INVALID_FIELD_MESSAGE = \"Invalid field\";\n\n public static final String MALFORMED_JSON_MESSAGE = \"Malformed JSON\";\n\n private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @ExceptionHandler(MethodArgumentTypeMismatchException.class)\n public ResponseEntity onMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException exception) {\n var errors = List.of(new FieldValidationError(exception.getName(), exception.getValue().toString()));\n return getResponseEntity(INVALID_FIELD_MESSAGE, errors, BAD_REQUEST);\n }\n\n @ExceptionHandler(HttpMessageNotReadableException.class)\n public ResponseEntity onHttpMessageNotReadableException(HttpMessageNotReadableException exception) {\n return getResponseEntity(MALFORMED_JSON_MESSAGE, null, BAD_REQUEST);\n }\n\n @ExceptionHandler(ConstraintViolationException.class)\n public ResponseEntity onConstraintViolationException(ConstraintViolationException exception) {\n List errors = exception.getConstraintViolations().stream().map(error -> {\n var fieldPath = error.getPropertyPath().toString();\n var fieldName = fieldPath.substring(fieldPath.lastIndexOf('.') + 1);\n return new FieldValidationError(fieldName, error.getMessage());\n }).collect(Collectors.toList());\n return getResponseEntity(INVALID_FIELD_MESSAGE, errors, BAD_REQUEST);\n }\n\n @ExceptionHandler(MethodArgumentNotValidException.class)\n public ResponseEntity onMethodArgumentNotValidException(MethodArgumentNotValidException exception) {\n List errors = exception.getBindingResult().getFieldErrors().stream().map(fieldError -> new FieldValidationError(fieldError.getField(), fieldError.getDefaultMessage())).collect(Collectors.toList());\n return getResponseEntity(INVALID_FIELD_MESSAGE, errors, BAD_REQUEST);\n }\n\n ", "post_mask_code": "{\n var errors = List.of(new FieldValidationError(\"code\", String.valueOf(exception.getCode())));\n return getResponseEntity(INVALID_FIELD_MESSAGE, errors, BAD_REQUEST);\n }\n\n private ResponseEntity getResponseEntity(String message, List detailedErrors, HttpStatus status) {\n Map errorResult = new HashMap<>(Map.of(\"message\", message));\n if (detailedErrors != null && !detailedErrors.isEmpty()) {\n errorResult.put(\"errors\", detailedErrors);\n }\n if (logger.isWarnEnabled()) {\n logger.warn(errorResult.toString());\n }\n return new ResponseEntity<>(errorResult, status);\n }\n\n static class FieldValidationError {\n\n private final String field;\n\n private final String detail;\n\n public FieldValidationError(String field, String detail) {\n this.field = field;\n this.detail = detail;\n }\n\n public String getField() {\n return field;\n }\n\n public String getDetail() {\n return detail;\n }\n }\n}\n"} {"task_id": "Java_2651", "language": "Java", "task_type": "method_body", "source_file": "java/github/mariorez/kanban-board/src/main/java/org/seariver/kanbanboard/write/adapter/in/WriteExceptionHandler.java", "mask_start_position": 2568, "mask_end_position": 2881, "canonical_solution": "{\n List errors = exception.getBindingResult().getFieldErrors().stream().map(fieldError -> new FieldValidationError(fieldError.getField(), fieldError.getDefaultMessage())).collect(Collectors.toList());\n return getResponseEntity(INVALID_FIELD_MESSAGE, errors, BAD_REQUEST);\n }", "pre_mask_code": "package org.seariver.kanbanboard.write.adapter.in;\n\nimport org.seariver.kanbanboard.write.domain.exception.DomainException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.http.converter.HttpMessageNotReadableException;\nimport org.springframework.web.bind.MethodArgumentNotValidException;\nimport org.springframework.web.bind.annotation.ExceptionHandler;\nimport org.springframework.web.bind.annotation.RestControllerAdvice;\nimport org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;\nimport javax.validation.ConstraintViolationException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\nimport static org.springframework.http.HttpStatus.BAD_REQUEST;\n\n@RestControllerAdvice\npublic class WriteExceptionHandler {\n\n public static final String INVALID_FIELD_MESSAGE = \"Invalid field\";\n\n public static final String MALFORMED_JSON_MESSAGE = \"Malformed JSON\";\n\n private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @ExceptionHandler(MethodArgumentTypeMismatchException.class)\n public ResponseEntity onMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException exception) {\n var errors = List.of(new FieldValidationError(exception.getName(), exception.getValue().toString()));\n return getResponseEntity(INVALID_FIELD_MESSAGE, errors, BAD_REQUEST);\n }\n\n @ExceptionHandler(HttpMessageNotReadableException.class)\n public ResponseEntity onHttpMessageNotReadableException(HttpMessageNotReadableException exception) {\n return getResponseEntity(MALFORMED_JSON_MESSAGE, null, BAD_REQUEST);\n }\n\n @ExceptionHandler(ConstraintViolationException.class)\n public ResponseEntity onConstraintViolationException(ConstraintViolationException exception) {\n List errors = exception.getConstraintViolations().stream().map(error -> {\n var fieldPath = error.getPropertyPath().toString();\n var fieldName = fieldPath.substring(fieldPath.lastIndexOf('.') + 1);\n return new FieldValidationError(fieldName, error.getMessage());\n }).collect(Collectors.toList());\n return getResponseEntity(INVALID_FIELD_MESSAGE, errors, BAD_REQUEST);\n }\n\n @ExceptionHandler(MethodArgumentNotValidException.class)\n public ResponseEntity onMethodArgumentNotValidException(MethodArgumentNotValidException exception) ", "post_mask_code": "\n\n @ExceptionHandler(DomainException.class)\n public ResponseEntity onDomainException(DomainException exception) {\n var errors = List.of(new FieldValidationError(\"code\", String.valueOf(exception.getCode())));\n return getResponseEntity(INVALID_FIELD_MESSAGE, errors, BAD_REQUEST);\n }\n\n private ResponseEntity getResponseEntity(String message, List detailedErrors, HttpStatus status) {\n Map errorResult = new HashMap<>(Map.of(\"message\", message));\n if (detailedErrors != null && !detailedErrors.isEmpty()) {\n errorResult.put(\"errors\", detailedErrors);\n }\n if (logger.isWarnEnabled()) {\n logger.warn(errorResult.toString());\n }\n return new ResponseEntity<>(errorResult, status);\n }\n\n static class FieldValidationError {\n\n private final String field;\n\n private final String detail;\n\n public FieldValidationError(String field, String detail) {\n this.field = field;\n this.detail = detail;\n }\n\n public String getField() {\n return field;\n }\n\n public String getDetail() {\n return detail;\n }\n }\n}\n"} {"task_id": "Java_2652", "language": "Java", "task_type": "single_line", "source_file": "java/github/mariorez/kanban-board/src/main/java/org/seariver/kanbanboard/write/adapter/in/WriteExceptionHandler.java", "mask_start_position": 1349, "mask_end_position": 1436, "canonical_solution": "ist.of(new FieldValidationError(exception.getName(), exception.getValue().toString()));", "pre_mask_code": "package org.seariver.kanbanboard.write.adapter.in;\n\nimport org.seariver.kanbanboard.write.domain.exception.DomainException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.http.converter.HttpMessageNotReadableException;\nimport org.springframework.web.bind.MethodArgumentNotValidException;\nimport org.springframework.web.bind.annotation.ExceptionHandler;\nimport org.springframework.web.bind.annotation.RestControllerAdvice;\nimport org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;\nimport javax.validation.ConstraintViolationException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\nimport static org.springframework.http.HttpStatus.BAD_REQUEST;\n\n@RestControllerAdvice\npublic class WriteExceptionHandler {\n\n public static final String INVALID_FIELD_MESSAGE = \"Invalid field\";\n\n public static final String MALFORMED_JSON_MESSAGE = \"Malformed JSON\";\n\n private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @ExceptionHandler(MethodArgumentTypeMismatchException.class)\n public ResponseEntity onMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException exception) {\n var errors = L", "post_mask_code": "\n return getResponseEntity(INVALID_FIELD_MESSAGE, errors, BAD_REQUEST);\n }\n\n @ExceptionHandler(HttpMessageNotReadableException.class)\n public ResponseEntity onHttpMessageNotReadableException(HttpMessageNotReadableException exception) {\n return getResponseEntity(MALFORMED_JSON_MESSAGE, null, BAD_REQUEST);\n }\n\n @ExceptionHandler(ConstraintViolationException.class)\n public ResponseEntity onConstraintViolationException(ConstraintViolationException exception) {\n List errors = exception.getConstraintViolations().stream().map(error -> {\n var fieldPath = error.getPropertyPath().toString();\n var fieldName = fieldPath.substring(fieldPath.lastIndexOf('.') + 1);\n return new FieldValidationError(fieldName, error.getMessage());\n }).collect(Collectors.toList());\n return getResponseEntity(INVALID_FIELD_MESSAGE, errors, BAD_REQUEST);\n }\n\n @ExceptionHandler(MethodArgumentNotValidException.class)\n public ResponseEntity onMethodArgumentNotValidException(MethodArgumentNotValidException exception) {\n List errors = exception.getBindingResult().getFieldErrors().stream().map(fieldError -> new FieldValidationError(fieldError.getField(), fieldError.getDefaultMessage())).collect(Collectors.toList());\n return getResponseEntity(INVALID_FIELD_MESSAGE, errors, BAD_REQUEST);\n }\n\n @ExceptionHandler(DomainException.class)\n public ResponseEntity onDomainException(DomainException exception) {\n var errors = List.of(new FieldValidationError(\"code\", String.valueOf(exception.getCode())));\n return getResponseEntity(INVALID_FIELD_MESSAGE, errors, BAD_REQUEST);\n }\n\n private ResponseEntity getResponseEntity(String message, List detailedErrors, HttpStatus status) {\n Map errorResult = new HashMap<>(Map.of(\"message\", message));\n if (detailedErrors != null && !detailedErrors.isEmpty()) {\n errorResult.put(\"errors\", detailedErrors);\n }\n if (logger.isWarnEnabled()) {\n logger.warn(errorResult.toString());\n }\n return new ResponseEntity<>(errorResult, status);\n }\n\n static class FieldValidationError {\n\n private final String field;\n\n private final String detail;\n\n public FieldValidationError(String field, String detail) {\n this.field = field;\n this.detail = detail;\n }\n\n public String getField() {\n return field;\n }\n\n public String getDetail() {\n return detail;\n }\n }\n}\n"} {"task_id": "Java_2653", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Samuel-Oliveira/Java_CTe/src/main/java/br/com/swconsultoria/cte/schema_300/cteModalAquaviario/TransformsType.java", "mask_start_position": 1991, "mask_end_position": 2033, "canonical_solution": "public List getTransform() ", "pre_mask_code": "// Este arquivo foi gerado pela Arquitetura JavaTM para Implementação de Referência (JAXB) de Bind XML, v2.2.8-b130911.1802\n// Todas as modificações neste arquivo serão perdidas após a recompilação do esquema de origem.\npackage br.com.swconsultoria.cte.schema_300.cteModalAquaviario;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlType;\n\n/**\n *

Classe Java de TransformsType complex type.\n *\n *

O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe.\n *\n *

\n * <complexType name=\"TransformsType\">\n *   <complexContent>\n *     <restriction base=\"{http://www.w3.org/2001/XMLSchema}anyType\">\n *       <sequence>\n *         <element name=\"Transform\" type=\"{http://example.com\" maxOccurs=\"2\" minOccurs=\"2\"/>\n *       </sequence>\n *     </restriction>\n *   </complexContent>\n * </complexType>\n * 
\n */\n@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"TransformsType\", namespace = \"http://example.com#\", propOrder = { \"transform\" })\npublic class TransformsType {\n\n @XmlElement(name = \"Transform\", namespace = \"http://www.w3.org/2000/09/xmldsig#\", required = true)\n protected List transform;\n\n /**\n * Gets the value of the transform property.\n *\n *

\n * This accessor method returns a reference to the live list,\n * not a snapshot. Therefore any modification you make to the\n * returned list will be present inside the JAXB object.\n * This is why there is not a set method for the transform property.\n *\n *

\n * For example, to add a new item, do as follows:\n *

\n     *    getTransform().add(newItem);\n     * 
\n *\n *

\n * Objects of the following type(s) are allowed in the list\n * {@link TransformType }\n */\n ", "post_mask_code": "{\n if (transform == null) {\n transform = new ArrayList();\n }\n return this.transform;\n }\n}\n"} {"task_id": "Java_2654", "language": "Java", "task_type": "method_body", "source_file": "java/github/Samuel-Oliveira/Java_CTe/src/main/java/br/com/swconsultoria/cte/schema_300/cteModalAquaviario/TransformsType.java", "mask_start_position": 2033, "mask_end_position": 2170, "canonical_solution": "{\n if (transform == null) {\n transform = new ArrayList();\n }\n return this.transform;\n }", "pre_mask_code": "// Este arquivo foi gerado pela Arquitetura JavaTM para Implementação de Referência (JAXB) de Bind XML, v2.2.8-b130911.1802\n// Todas as modificações neste arquivo serão perdidas após a recompilação do esquema de origem.\npackage br.com.swconsultoria.cte.schema_300.cteModalAquaviario;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlType;\n\n/**\n *

Classe Java de TransformsType complex type.\n *\n *

O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe.\n *\n *

\n * <complexType name=\"TransformsType\">\n *   <complexContent>\n *     <restriction base=\"{http://www.w3.org/2001/XMLSchema}anyType\">\n *       <sequence>\n *         <element name=\"Transform\" type=\"{http://example.com\" maxOccurs=\"2\" minOccurs=\"2\"/>\n *       </sequence>\n *     </restriction>\n *   </complexContent>\n * </complexType>\n * 
\n */\n@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"TransformsType\", namespace = \"http://example.com#\", propOrder = { \"transform\" })\npublic class TransformsType {\n\n @XmlElement(name = \"Transform\", namespace = \"http://www.w3.org/2000/09/xmldsig#\", required = true)\n protected List transform;\n\n /**\n * Gets the value of the transform property.\n *\n *

\n * This accessor method returns a reference to the live list,\n * not a snapshot. Therefore any modification you make to the\n * returned list will be present inside the JAXB object.\n * This is why there is not a set method for the transform property.\n *\n *

\n * For example, to add a new item, do as follows:\n *

\n     *    getTransform().add(newItem);\n     * 
\n *\n *

\n * Objects of the following type(s) are allowed in the list\n * {@link TransformType }\n */\n public List getTransform() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2655", "language": "Java", "task_type": "single_line", "source_file": "java/github/Samuel-Oliveira/Java_CTe/src/main/java/br/com/swconsultoria/cte/schema_300/cteModalAquaviario/TransformsType.java", "mask_start_position": 2154, "mask_end_position": 2164, "canonical_solution": "transform;", "pre_mask_code": "// Este arquivo foi gerado pela Arquitetura JavaTM para Implementação de Referência (JAXB) de Bind XML, v2.2.8-b130911.1802\n// Todas as modificações neste arquivo serão perdidas após a recompilação do esquema de origem.\npackage br.com.swconsultoria.cte.schema_300.cteModalAquaviario;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlType;\n\n/**\n *

Classe Java de TransformsType complex type.\n *\n *

O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe.\n *\n *

\n * <complexType name=\"TransformsType\">\n *   <complexContent>\n *     <restriction base=\"{http://www.w3.org/2001/XMLSchema}anyType\">\n *       <sequence>\n *         <element name=\"Transform\" type=\"{http://example.com\" maxOccurs=\"2\" minOccurs=\"2\"/>\n *       </sequence>\n *     </restriction>\n *   </complexContent>\n * </complexType>\n * 
\n */\n@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"TransformsType\", namespace = \"http://example.com#\", propOrder = { \"transform\" })\npublic class TransformsType {\n\n @XmlElement(name = \"Transform\", namespace = \"http://www.w3.org/2000/09/xmldsig#\", required = true)\n protected List transform;\n\n /**\n * Gets the value of the transform property.\n *\n *

\n * This accessor method returns a reference to the live list,\n * not a snapshot. Therefore any modification you make to the\n * returned list will be present inside the JAXB object.\n * This is why there is not a set method for the transform property.\n *\n *

\n * For example, to add a new item, do as follows:\n *

\n     *    getTransform().add(newItem);\n     * 
\n *\n *

\n * Objects of the following type(s) are allowed in the list\n * {@link TransformType }\n */\n public List getTransform() {\n if (transform == null) {\n transform = new ArrayList();\n }\n return this.", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2656", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Samuel-Oliveira/Java_CTe/src/main/java/br/com/swconsultoria/cte/schema_300/cteModalAquaviario/TransformsType.java", "mask_start_position": 1991, "mask_end_position": 2170, "canonical_solution": "public List getTransform() {\n if (transform == null) {\n transform = new ArrayList();\n }\n return this.transform;\n }", "pre_mask_code": "// Este arquivo foi gerado pela Arquitetura JavaTM para Implementação de Referência (JAXB) de Bind XML, v2.2.8-b130911.1802\n// Todas as modificações neste arquivo serão perdidas após a recompilação do esquema de origem.\npackage br.com.swconsultoria.cte.schema_300.cteModalAquaviario;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlType;\n\n/**\n *

Classe Java de TransformsType complex type.\n *\n *

O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe.\n *\n *

\n * <complexType name=\"TransformsType\">\n *   <complexContent>\n *     <restriction base=\"{http://www.w3.org/2001/XMLSchema}anyType\">\n *       <sequence>\n *         <element name=\"Transform\" type=\"{http://example.com\" maxOccurs=\"2\" minOccurs=\"2\"/>\n *       </sequence>\n *     </restriction>\n *   </complexContent>\n * </complexType>\n * 
\n */\n@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"TransformsType\", namespace = \"http://example.com#\", propOrder = { \"transform\" })\npublic class TransformsType {\n\n @XmlElement(name = \"Transform\", namespace = \"http://www.w3.org/2000/09/xmldsig#\", required = true)\n protected List transform;\n\n /**\n * Gets the value of the transform property.\n *\n *

\n * This accessor method returns a reference to the live list,\n * not a snapshot. Therefore any modification you make to the\n * returned list will be present inside the JAXB object.\n * This is why there is not a set method for the transform property.\n *\n *

\n * For example, to add a new item, do as follows:\n *

\n     *    getTransform().add(newItem);\n     * 
\n *\n *

\n * Objects of the following type(s) are allowed in the list\n * {@link TransformType }\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2657", "language": "Java", "task_type": "method_signature", "source_file": "java/github/ContainX/openstack4j/core/src/main/java/org/openstack4j/openstack/manila/domain/actions/SecurityServiceAction.java", "mask_start_position": 671, "mask_end_position": 708, "canonical_solution": "public String getSecurityServiceId() ", "pre_mask_code": "package org.openstack4j.openstack.manila.domain.actions;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.annotation.JsonRootName;\nimport org.openstack4j.model.ModelEntity;\n\n/**\n * Security Service related actions.\n *\n * @author Daniel Gonzalez Nothnagel\n */\npublic class SecurityServiceAction implements ModelEntity {\n\n private static final long serialVersionUID = 1L;\n\n @JsonProperty(\"security_service_id\")\n private String securityServiceId;\n\n protected SecurityServiceAction(String securityServiceId) {\n this.securityServiceId = securityServiceId;\n }\n\n /**\n * @return the security service ID\n */\n ", "post_mask_code": "{\n return securityServiceId;\n }\n\n /**\n * Create an 'add security service' action.\n *\n * @param securityServiceId the security service ID to add\n * @return the add action\n */\n public static Add add(String securityServiceId) {\n return new Add(securityServiceId);\n }\n\n /**\n * Create a 'remove security service' action.\n *\n * @param securityServiceId the security service ID to remove\n * @return the remove action\n */\n public static Remove remove(String securityServiceId) {\n return new Remove(securityServiceId);\n }\n\n @JsonRootName(\"add_security_service\")\n public static class Add extends SecurityServiceAction {\n\n private static final long serialVersionUID = 1L;\n\n public Add(String securityServiceId) {\n super(securityServiceId);\n }\n }\n\n @JsonRootName(\"remove_security_service\")\n public static class Remove extends SecurityServiceAction {\n\n private static final long serialVersionUID = 1L;\n\n public Remove(String securityServiceId) {\n super(securityServiceId);\n }\n }\n}\n"} {"task_id": "Java_2658", "language": "Java", "task_type": "method_body", "source_file": "java/github/ContainX/openstack4j/core/src/main/java/org/openstack4j/openstack/manila/domain/actions/SecurityServiceAction.java", "mask_start_position": 967, "mask_end_position": 1017, "canonical_solution": "{\n return new Add(securityServiceId);\n }", "pre_mask_code": "package org.openstack4j.openstack.manila.domain.actions;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.annotation.JsonRootName;\nimport org.openstack4j.model.ModelEntity;\n\n/**\n * Security Service related actions.\n *\n * @author Daniel Gonzalez Nothnagel\n */\npublic class SecurityServiceAction implements ModelEntity {\n\n private static final long serialVersionUID = 1L;\n\n @JsonProperty(\"security_service_id\")\n private String securityServiceId;\n\n protected SecurityServiceAction(String securityServiceId) {\n this.securityServiceId = securityServiceId;\n }\n\n /**\n * @return the security service ID\n */\n public String getSecurityServiceId() {\n return securityServiceId;\n }\n\n /**\n * Create an 'add security service' action.\n *\n * @param securityServiceId the security service ID to add\n * @return the add action\n */\n public static Add add(String securityServiceId) ", "post_mask_code": "\n\n /**\n * Create a 'remove security service' action.\n *\n * @param securityServiceId the security service ID to remove\n * @return the remove action\n */\n public static Remove remove(String securityServiceId) {\n return new Remove(securityServiceId);\n }\n\n @JsonRootName(\"add_security_service\")\n public static class Add extends SecurityServiceAction {\n\n private static final long serialVersionUID = 1L;\n\n public Add(String securityServiceId) {\n super(securityServiceId);\n }\n }\n\n @JsonRootName(\"remove_security_service\")\n public static class Remove extends SecurityServiceAction {\n\n private static final long serialVersionUID = 1L;\n\n public Remove(String securityServiceId) {\n super(securityServiceId);\n }\n }\n}\n"} {"task_id": "Java_2659", "language": "Java", "task_type": "single_line", "source_file": "java/github/ContainX/openstack4j/core/src/main/java/org/openstack4j/openstack/manila/domain/actions/SecurityServiceAction.java", "mask_start_position": 987, "mask_end_position": 1011, "canonical_solution": " Add(securityServiceId);", "pre_mask_code": "package org.openstack4j.openstack.manila.domain.actions;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.annotation.JsonRootName;\nimport org.openstack4j.model.ModelEntity;\n\n/**\n * Security Service related actions.\n *\n * @author Daniel Gonzalez Nothnagel\n */\npublic class SecurityServiceAction implements ModelEntity {\n\n private static final long serialVersionUID = 1L;\n\n @JsonProperty(\"security_service_id\")\n private String securityServiceId;\n\n protected SecurityServiceAction(String securityServiceId) {\n this.securityServiceId = securityServiceId;\n }\n\n /**\n * @return the security service ID\n */\n public String getSecurityServiceId() {\n return securityServiceId;\n }\n\n /**\n * Create an 'add security service' action.\n *\n * @param securityServiceId the security service ID to add\n * @return the add action\n */\n public static Add add(String securityServiceId) {\n return new", "post_mask_code": "\n }\n\n /**\n * Create a 'remove security service' action.\n *\n * @param securityServiceId the security service ID to remove\n * @return the remove action\n */\n public static Remove remove(String securityServiceId) {\n return new Remove(securityServiceId);\n }\n\n @JsonRootName(\"add_security_service\")\n public static class Add extends SecurityServiceAction {\n\n private static final long serialVersionUID = 1L;\n\n public Add(String securityServiceId) {\n super(securityServiceId);\n }\n }\n\n @JsonRootName(\"remove_security_service\")\n public static class Remove extends SecurityServiceAction {\n\n private static final long serialVersionUID = 1L;\n\n public Remove(String securityServiceId) {\n super(securityServiceId);\n }\n }\n}\n"} {"task_id": "Java_2660", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/ContainX/openstack4j/core/src/main/java/org/openstack4j/openstack/manila/domain/actions/SecurityServiceAction.java", "mask_start_position": 919, "mask_end_position": 1017, "canonical_solution": "public static Add add(String securityServiceId) {\n return new Add(securityServiceId);\n }", "pre_mask_code": "package org.openstack4j.openstack.manila.domain.actions;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.annotation.JsonRootName;\nimport org.openstack4j.model.ModelEntity;\n\n/**\n * Security Service related actions.\n *\n * @author Daniel Gonzalez Nothnagel\n */\npublic class SecurityServiceAction implements ModelEntity {\n\n private static final long serialVersionUID = 1L;\n\n @JsonProperty(\"security_service_id\")\n private String securityServiceId;\n\n protected SecurityServiceAction(String securityServiceId) {\n this.securityServiceId = securityServiceId;\n }\n\n /**\n * @return the security service ID\n */\n public String getSecurityServiceId() {\n return securityServiceId;\n }\n\n /**\n * Create an 'add security service' action.\n *\n * @param securityServiceId the security service ID to add\n * @return the add action\n */\n ", "post_mask_code": "\n\n /**\n * Create a 'remove security service' action.\n *\n * @param securityServiceId the security service ID to remove\n * @return the remove action\n */\n public static Remove remove(String securityServiceId) {\n return new Remove(securityServiceId);\n }\n\n @JsonRootName(\"add_security_service\")\n public static class Add extends SecurityServiceAction {\n\n private static final long serialVersionUID = 1L;\n\n public Add(String securityServiceId) {\n super(securityServiceId);\n }\n }\n\n @JsonRootName(\"remove_security_service\")\n public static class Remove extends SecurityServiceAction {\n\n private static final long serialVersionUID = 1L;\n\n public Remove(String securityServiceId) {\n super(securityServiceId);\n }\n }\n}\n"} {"task_id": "Java_2661", "language": "Java", "task_type": "method_signature", "source_file": "java/github/iterate-ch/cyberduck/osx/src/main/java/ch/cyberduck/ui/cocoa/controller/TransferControllerFactory.java", "mask_start_position": 2024, "mask_end_position": 2087, "canonical_solution": "@Override\n public void callback(int returncode) ", "pre_mask_code": "package ch.cyberduck.ui.cocoa.controller;\n\nimport ch.cyberduck.binding.application.NSAlert;\nimport ch.cyberduck.binding.application.NSApplication;\nimport ch.cyberduck.binding.application.SheetCallback;\nimport ch.cyberduck.core.LocaleFactory;\nimport ch.cyberduck.core.TransferCollection;\nimport ch.cyberduck.core.preferences.PreferencesFactory;\nimport ch.cyberduck.core.threading.BackgroundAction;\nimport ch.cyberduck.core.threading.BackgroundActionRegistry;\nimport org.rococoa.cocoa.foundation.NSUInteger;\n\npublic final class TransferControllerFactory {\n\n private static TransferController shared = null;\n\n private TransferControllerFactory() {\n }\n\n public static TransferController get() {\n synchronized (NSApplication.sharedApplication()) {\n if (null == shared) {\n shared = new TransferController();\n shared.loadBundle();\n }\n return shared;\n }\n }\n\n /**\n * @param app Singleton\n * @return NSApplication.TerminateLater or NSApplication.TerminateNow depending if there are\n * running transfers to be checked first\n */\n public static NSUInteger applicationShouldTerminate(final NSApplication app) {\n if (null == shared) {\n return NSApplication.NSTerminateNow;\n }\n // Saving state of transfer window\n PreferencesFactory.get().setProperty(\"queue.window.open.default\", shared.isVisible());\n if (TransferCollection.defaultCollection().numberOfRunningTransfers() > 0) {\n final NSAlert alert = // title\n NSAlert.// title\n alert(// title\n LocaleFactory.localizedString(\"Transfer in progress\"), // message\n LocaleFactory.localizedString(\"There are files currently being transferred. Quit anyway?\"), LocaleFactory.localizedString(\"Quit\"), // alternative button\n LocaleFactory.localizedString(\"Cancel\"), // other button\n null);\n shared.alert(alert, new SheetCallback() {\n\n ", "post_mask_code": "{\n if (returncode == DEFAULT_OPTION) {\n // Quit\n final BackgroundActionRegistry registry = shared.getRegistry();\n for (BackgroundAction action : registry.toArray(new BackgroundAction[registry.size()])) {\n action.cancel();\n }\n app.replyToApplicationShouldTerminate(true);\n }\n if (returncode == CANCEL_OPTION) {\n // Cancel\n app.replyToApplicationShouldTerminate(false);\n }\n }\n });\n return NSApplication.NSTerminateLater;\n }\n return NSApplication.NSTerminateNow;\n }\n}\n"} {"task_id": "Java_2662", "language": "Java", "task_type": "method_body", "source_file": "java/github/iterate-ch/cyberduck/osx/src/main/java/ch/cyberduck/ui/cocoa/controller/TransferControllerFactory.java", "mask_start_position": 701, "mask_end_position": 940, "canonical_solution": "{\n synchronized (NSApplication.sharedApplication()) {\n if (null == shared) {\n shared = new TransferController();\n shared.loadBundle();\n }\n return shared;\n }\n }", "pre_mask_code": "package ch.cyberduck.ui.cocoa.controller;\n\nimport ch.cyberduck.binding.application.NSAlert;\nimport ch.cyberduck.binding.application.NSApplication;\nimport ch.cyberduck.binding.application.SheetCallback;\nimport ch.cyberduck.core.LocaleFactory;\nimport ch.cyberduck.core.TransferCollection;\nimport ch.cyberduck.core.preferences.PreferencesFactory;\nimport ch.cyberduck.core.threading.BackgroundAction;\nimport ch.cyberduck.core.threading.BackgroundActionRegistry;\nimport org.rococoa.cocoa.foundation.NSUInteger;\n\npublic final class TransferControllerFactory {\n\n private static TransferController shared = null;\n\n private TransferControllerFactory() {\n }\n\n public static TransferController get() ", "post_mask_code": "\n\n /**\n * @param app Singleton\n * @return NSApplication.TerminateLater or NSApplication.TerminateNow depending if there are\n * running transfers to be checked first\n */\n public static NSUInteger applicationShouldTerminate(final NSApplication app) {\n if (null == shared) {\n return NSApplication.NSTerminateNow;\n }\n // Saving state of transfer window\n PreferencesFactory.get().setProperty(\"queue.window.open.default\", shared.isVisible());\n if (TransferCollection.defaultCollection().numberOfRunningTransfers() > 0) {\n final NSAlert alert = // title\n NSAlert.// title\n alert(// title\n LocaleFactory.localizedString(\"Transfer in progress\"), // message\n LocaleFactory.localizedString(\"There are files currently being transferred. Quit anyway?\"), LocaleFactory.localizedString(\"Quit\"), // alternative button\n LocaleFactory.localizedString(\"Cancel\"), // other button\n null);\n shared.alert(alert, new SheetCallback() {\n\n @Override\n public void callback(int returncode) {\n if (returncode == DEFAULT_OPTION) {\n // Quit\n final BackgroundActionRegistry registry = shared.getRegistry();\n for (BackgroundAction action : registry.toArray(new BackgroundAction[registry.size()])) {\n action.cancel();\n }\n app.replyToApplicationShouldTerminate(true);\n }\n if (returncode == CANCEL_OPTION) {\n // Cancel\n app.replyToApplicationShouldTerminate(false);\n }\n }\n });\n return NSApplication.NSTerminateLater;\n }\n return NSApplication.NSTerminateNow;\n }\n}\n"} {"task_id": "Java_2663", "language": "Java", "task_type": "single_line", "source_file": "java/github/iterate-ch/cyberduck/osx/src/main/java/ch/cyberduck/ui/cocoa/controller/TransferControllerFactory.java", "mask_start_position": 2838, "mask_end_position": 2861, "canonical_solution": "ication.NSTerminateNow;", "pre_mask_code": "package ch.cyberduck.ui.cocoa.controller;\n\nimport ch.cyberduck.binding.application.NSAlert;\nimport ch.cyberduck.binding.application.NSApplication;\nimport ch.cyberduck.binding.application.SheetCallback;\nimport ch.cyberduck.core.LocaleFactory;\nimport ch.cyberduck.core.TransferCollection;\nimport ch.cyberduck.core.preferences.PreferencesFactory;\nimport ch.cyberduck.core.threading.BackgroundAction;\nimport ch.cyberduck.core.threading.BackgroundActionRegistry;\nimport org.rococoa.cocoa.foundation.NSUInteger;\n\npublic final class TransferControllerFactory {\n\n private static TransferController shared = null;\n\n private TransferControllerFactory() {\n }\n\n public static TransferController get() {\n synchronized (NSApplication.sharedApplication()) {\n if (null == shared) {\n shared = new TransferController();\n shared.loadBundle();\n }\n return shared;\n }\n }\n\n /**\n * @param app Singleton\n * @return NSApplication.TerminateLater or NSApplication.TerminateNow depending if there are\n * running transfers to be checked first\n */\n public static NSUInteger applicationShouldTerminate(final NSApplication app) {\n if (null == shared) {\n return NSApplication.NSTerminateNow;\n }\n // Saving state of transfer window\n PreferencesFactory.get().setProperty(\"queue.window.open.default\", shared.isVisible());\n if (TransferCollection.defaultCollection().numberOfRunningTransfers() > 0) {\n final NSAlert alert = // title\n NSAlert.// title\n alert(// title\n LocaleFactory.localizedString(\"Transfer in progress\"), // message\n LocaleFactory.localizedString(\"There are files currently being transferred. Quit anyway?\"), LocaleFactory.localizedString(\"Quit\"), // alternative button\n LocaleFactory.localizedString(\"Cancel\"), // other button\n null);\n shared.alert(alert, new SheetCallback() {\n\n @Override\n public void callback(int returncode) {\n if (returncode == DEFAULT_OPTION) {\n // Quit\n final BackgroundActionRegistry registry = shared.getRegistry();\n for (BackgroundAction action : registry.toArray(new BackgroundAction[registry.size()])) {\n action.cancel();\n }\n app.replyToApplicationShouldTerminate(true);\n }\n if (returncode == CANCEL_OPTION) {\n // Cancel\n app.replyToApplicationShouldTerminate(false);\n }\n }\n });\n return NSApplication.NSTerminateLater;\n }\n return NSAppl", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2664", "language": "Java", "task_type": "method_signature", "source_file": "java/github/netindev/Allatori-v3.0/AllatoriSource/src/org/apache/bcel/classfile/LineNumberTable.java", "mask_start_position": 1255, "mask_end_position": 1334, "canonical_solution": "@Override\n public final void dump(DataOutputStream file) throws IOException ", "pre_mask_code": "package org.apache.bcel.classfile;\n\nimport java.io.DataInputStream;\nimport java.io.DataOutputStream;\nimport java.io.IOException;\n\npublic final class LineNumberTable extends Attribute {\n\n private static final long serialVersionUID = -6967221519632128904L;\n\n private int line_number_table_length;\n\n private LineNumber[] line_number_table;\n\n public LineNumberTable(LineNumberTable c) {\n this(c.getNameIndex(), c.getLength(), c.getLineNumberTable(), c.getConstantPool());\n }\n\n public LineNumberTable(int name_index, int length, LineNumber[] line_number_table, ConstantPool constant_pool) {\n super((byte) 4, name_index, length, constant_pool);\n setLineNumberTable(line_number_table);\n }\n\n LineNumberTable(int name_index, int length, DataInputStream file, ConstantPool constant_pool) throws IOException {\n this(name_index, length, (LineNumber[]) null, constant_pool);\n line_number_table_length = file.readUnsignedShort();\n line_number_table = new LineNumber[line_number_table_length];\n for (int i = 0; i < line_number_table_length; i++) line_number_table[i] = new LineNumber(file);\n }\n\n @Override\n public void accept(Visitor v) {\n v.visitLineNumberTable(this);\n }\n\n ", "post_mask_code": "{\n super.dump(file);\n file.writeShort(line_number_table_length);\n for (int i = 0; i < line_number_table_length; i++) line_number_table[i].dump(file);\n }\n\n public final LineNumber[] getLineNumberTable() {\n return line_number_table;\n }\n\n public final void setLineNumberTable(LineNumber[] line_number_table) {\n this.line_number_table = line_number_table;\n line_number_table_length = line_number_table == null ? 0 : line_number_table.length;\n }\n\n @Override\n public final String toString() {\n final StringBuilder buf = new StringBuilder();\n final StringBuilder line = new StringBuilder();\n final String newLine = System.getProperty(\"line.separator\", \"\\n\");\n for (int i = 0; i < line_number_table_length; i++) {\n line.append(line_number_table[i].toString());\n if (i < line_number_table_length - 1)\n line.append(\", \");\n if (line.length() > 72) {\n line.append(newLine);\n buf.append(line.toString());\n line.setLength(0);\n }\n }\n buf.append(line);\n return buf.toString();\n }\n\n public int getSourceLine(int pos) {\n int l = 0;\n int r = line_number_table_length - 1;\n if (r < 0)\n return -1;\n int min_index = -1;\n int min = -1;\n do {\n final int i = (l + r) / 2;\n final int j = line_number_table[i].getStartPC();\n if (j == pos)\n return line_number_table[i].getLineNumber();\n if (pos < j)\n r = i - 1;\n else\n l = i + 1;\n if (j < pos && j > min) {\n min = j;\n min_index = i;\n }\n } while (l <= r);\n if (min_index < 0)\n return -1;\n return line_number_table[min_index].getLineNumber();\n }\n\n @Override\n public Attribute copy(ConstantPool _constant_pool) {\n final LineNumberTable c = (LineNumberTable) clone();\n c.line_number_table = new LineNumber[line_number_table_length];\n for (int i = 0; i < line_number_table_length; i++) c.line_number_table[i] = line_number_table[i].copy();\n c.constant_pool = _constant_pool;\n return c;\n }\n\n public final int getTableLength() {\n return line_number_table_length;\n }\n}\n"} {"task_id": "Java_2665", "language": "Java", "task_type": "method_body", "source_file": "java/github/netindev/Allatori-v3.0/AllatoriSource/src/org/apache/bcel/classfile/LineNumberTable.java", "mask_start_position": 1679, "mask_end_position": 1831, "canonical_solution": "{\n this.line_number_table = line_number_table;\n line_number_table_length = line_number_table == null ? 0 : line_number_table.length;\n }", "pre_mask_code": "package org.apache.bcel.classfile;\n\nimport java.io.DataInputStream;\nimport java.io.DataOutputStream;\nimport java.io.IOException;\n\npublic final class LineNumberTable extends Attribute {\n\n private static final long serialVersionUID = -6967221519632128904L;\n\n private int line_number_table_length;\n\n private LineNumber[] line_number_table;\n\n public LineNumberTable(LineNumberTable c) {\n this(c.getNameIndex(), c.getLength(), c.getLineNumberTable(), c.getConstantPool());\n }\n\n public LineNumberTable(int name_index, int length, LineNumber[] line_number_table, ConstantPool constant_pool) {\n super((byte) 4, name_index, length, constant_pool);\n setLineNumberTable(line_number_table);\n }\n\n LineNumberTable(int name_index, int length, DataInputStream file, ConstantPool constant_pool) throws IOException {\n this(name_index, length, (LineNumber[]) null, constant_pool);\n line_number_table_length = file.readUnsignedShort();\n line_number_table = new LineNumber[line_number_table_length];\n for (int i = 0; i < line_number_table_length; i++) line_number_table[i] = new LineNumber(file);\n }\n\n @Override\n public void accept(Visitor v) {\n v.visitLineNumberTable(this);\n }\n\n @Override\n public final void dump(DataOutputStream file) throws IOException {\n super.dump(file);\n file.writeShort(line_number_table_length);\n for (int i = 0; i < line_number_table_length; i++) line_number_table[i].dump(file);\n }\n\n public final LineNumber[] getLineNumberTable() {\n return line_number_table;\n }\n\n public final void setLineNumberTable(LineNumber[] line_number_table) ", "post_mask_code": "\n\n @Override\n public final String toString() {\n final StringBuilder buf = new StringBuilder();\n final StringBuilder line = new StringBuilder();\n final String newLine = System.getProperty(\"line.separator\", \"\\n\");\n for (int i = 0; i < line_number_table_length; i++) {\n line.append(line_number_table[i].toString());\n if (i < line_number_table_length - 1)\n line.append(\", \");\n if (line.length() > 72) {\n line.append(newLine);\n buf.append(line.toString());\n line.setLength(0);\n }\n }\n buf.append(line);\n return buf.toString();\n }\n\n public int getSourceLine(int pos) {\n int l = 0;\n int r = line_number_table_length - 1;\n if (r < 0)\n return -1;\n int min_index = -1;\n int min = -1;\n do {\n final int i = (l + r) / 2;\n final int j = line_number_table[i].getStartPC();\n if (j == pos)\n return line_number_table[i].getLineNumber();\n if (pos < j)\n r = i - 1;\n else\n l = i + 1;\n if (j < pos && j > min) {\n min = j;\n min_index = i;\n }\n } while (l <= r);\n if (min_index < 0)\n return -1;\n return line_number_table[min_index].getLineNumber();\n }\n\n @Override\n public Attribute copy(ConstantPool _constant_pool) {\n final LineNumberTable c = (LineNumberTable) clone();\n c.line_number_table = new LineNumber[line_number_table_length];\n for (int i = 0; i < line_number_table_length; i++) c.line_number_table[i] = line_number_table[i].copy();\n c.constant_pool = _constant_pool;\n return c;\n }\n\n public final int getTableLength() {\n return line_number_table_length;\n }\n}\n"} {"task_id": "Java_2666", "language": "Java", "task_type": "single_line", "source_file": "java/github/netindev/Allatori-v3.0/AllatoriSource/src/org/apache/bcel/classfile/LineNumberTable.java", "mask_start_position": 3701, "mask_end_position": 3727, "canonical_solution": " line_number_table_length;", "pre_mask_code": "package org.apache.bcel.classfile;\n\nimport java.io.DataInputStream;\nimport java.io.DataOutputStream;\nimport java.io.IOException;\n\npublic final class LineNumberTable extends Attribute {\n\n private static final long serialVersionUID = -6967221519632128904L;\n\n private int line_number_table_length;\n\n private LineNumber[] line_number_table;\n\n public LineNumberTable(LineNumberTable c) {\n this(c.getNameIndex(), c.getLength(), c.getLineNumberTable(), c.getConstantPool());\n }\n\n public LineNumberTable(int name_index, int length, LineNumber[] line_number_table, ConstantPool constant_pool) {\n super((byte) 4, name_index, length, constant_pool);\n setLineNumberTable(line_number_table);\n }\n\n LineNumberTable(int name_index, int length, DataInputStream file, ConstantPool constant_pool) throws IOException {\n this(name_index, length, (LineNumber[]) null, constant_pool);\n line_number_table_length = file.readUnsignedShort();\n line_number_table = new LineNumber[line_number_table_length];\n for (int i = 0; i < line_number_table_length; i++) line_number_table[i] = new LineNumber(file);\n }\n\n @Override\n public void accept(Visitor v) {\n v.visitLineNumberTable(this);\n }\n\n @Override\n public final void dump(DataOutputStream file) throws IOException {\n super.dump(file);\n file.writeShort(line_number_table_length);\n for (int i = 0; i < line_number_table_length; i++) line_number_table[i].dump(file);\n }\n\n public final LineNumber[] getLineNumberTable() {\n return line_number_table;\n }\n\n public final void setLineNumberTable(LineNumber[] line_number_table) {\n this.line_number_table = line_number_table;\n line_number_table_length = line_number_table == null ? 0 : line_number_table.length;\n }\n\n @Override\n public final String toString() {\n final StringBuilder buf = new StringBuilder();\n final StringBuilder line = new StringBuilder();\n final String newLine = System.getProperty(\"line.separator\", \"\\n\");\n for (int i = 0; i < line_number_table_length; i++) {\n line.append(line_number_table[i].toString());\n if (i < line_number_table_length - 1)\n line.append(\", \");\n if (line.length() > 72) {\n line.append(newLine);\n buf.append(line.toString());\n line.setLength(0);\n }\n }\n buf.append(line);\n return buf.toString();\n }\n\n public int getSourceLine(int pos) {\n int l = 0;\n int r = line_number_table_length - 1;\n if (r < 0)\n return -1;\n int min_index = -1;\n int min = -1;\n do {\n final int i = (l + r) / 2;\n final int j = line_number_table[i].getStartPC();\n if (j == pos)\n return line_number_table[i].getLineNumber();\n if (pos < j)\n r = i - 1;\n else\n l = i + 1;\n if (j < pos && j > min) {\n min = j;\n min_index = i;\n }\n } while (l <= r);\n if (min_index < 0)\n return -1;\n return line_number_table[min_index].getLineNumber();\n }\n\n @Override\n public Attribute copy(ConstantPool _constant_pool) {\n final LineNumberTable c = (LineNumberTable) clone();\n c.line_number_table = new LineNumber[line_number_table_length];\n for (int i = 0; i < line_number_table_length; i++) c.line_number_table[i] = line_number_table[i].copy();\n c.constant_pool = _constant_pool;\n return c;\n }\n\n public final int getTableLength() {\n return", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2667", "language": "Java", "task_type": "for_statement", "source_file": "java/github/netindev/Allatori-v3.0/AllatoriSource/src/org/apache/bcel/classfile/LineNumberTable.java", "mask_start_position": 2078, "mask_end_position": 2453, "canonical_solution": "for (int i = 0; i < line_number_table_length; i++) {\n line.append(line_number_table[i].toString());\n if (i < line_number_table_length - 1)\n line.append(\", \");\n if (line.length() > 72) {\n line.append(newLine);\n buf.append(line.toString());\n line.setLength(0);\n }\n }", "pre_mask_code": "package org.apache.bcel.classfile;\n\nimport java.io.DataInputStream;\nimport java.io.DataOutputStream;\nimport java.io.IOException;\n\npublic final class LineNumberTable extends Attribute {\n\n private static final long serialVersionUID = -6967221519632128904L;\n\n private int line_number_table_length;\n\n private LineNumber[] line_number_table;\n\n public LineNumberTable(LineNumberTable c) {\n this(c.getNameIndex(), c.getLength(), c.getLineNumberTable(), c.getConstantPool());\n }\n\n public LineNumberTable(int name_index, int length, LineNumber[] line_number_table, ConstantPool constant_pool) {\n super((byte) 4, name_index, length, constant_pool);\n setLineNumberTable(line_number_table);\n }\n\n LineNumberTable(int name_index, int length, DataInputStream file, ConstantPool constant_pool) throws IOException {\n this(name_index, length, (LineNumber[]) null, constant_pool);\n line_number_table_length = file.readUnsignedShort();\n line_number_table = new LineNumber[line_number_table_length];\n for (int i = 0; i < line_number_table_length; i++) line_number_table[i] = new LineNumber(file);\n }\n\n @Override\n public void accept(Visitor v) {\n v.visitLineNumberTable(this);\n }\n\n @Override\n public final void dump(DataOutputStream file) throws IOException {\n super.dump(file);\n file.writeShort(line_number_table_length);\n for (int i = 0; i < line_number_table_length; i++) line_number_table[i].dump(file);\n }\n\n public final LineNumber[] getLineNumberTable() {\n return line_number_table;\n }\n\n public final void setLineNumberTable(LineNumber[] line_number_table) {\n this.line_number_table = line_number_table;\n line_number_table_length = line_number_table == null ? 0 : line_number_table.length;\n }\n\n @Override\n public final String toString() {\n final StringBuilder buf = new StringBuilder();\n final StringBuilder line = new StringBuilder();\n final String newLine = System.getProperty(\"line.separator\", \"\\n\");\n ", "post_mask_code": "\n buf.append(line);\n return buf.toString();\n }\n\n public int getSourceLine(int pos) {\n int l = 0;\n int r = line_number_table_length - 1;\n if (r < 0)\n return -1;\n int min_index = -1;\n int min = -1;\n do {\n final int i = (l + r) / 2;\n final int j = line_number_table[i].getStartPC();\n if (j == pos)\n return line_number_table[i].getLineNumber();\n if (pos < j)\n r = i - 1;\n else\n l = i + 1;\n if (j < pos && j > min) {\n min = j;\n min_index = i;\n }\n } while (l <= r);\n if (min_index < 0)\n return -1;\n return line_number_table[min_index].getLineNumber();\n }\n\n @Override\n public Attribute copy(ConstantPool _constant_pool) {\n final LineNumberTable c = (LineNumberTable) clone();\n c.line_number_table = new LineNumber[line_number_table_length];\n for (int i = 0; i < line_number_table_length; i++) c.line_number_table[i] = line_number_table[i].copy();\n c.constant_pool = _constant_pool;\n return c;\n }\n\n public final int getTableLength() {\n return line_number_table_length;\n }\n}\n"} {"task_id": "Java_2668", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/incubator-inlong/inlong-tubemq/tubemq-core/src/main/java/org/apache/inlong/tubemq/corerpc/benchemark/RcpService4BenchmarkClient.java", "mask_start_position": 1979, "mask_end_position": 2023, "canonical_solution": "@Override\n public void run() ", "pre_mask_code": "package org.apache.inlong.tubemq.corerpc.benchemark;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\nimport org.apache.inlong.tubemq.corebase.cluster.BrokerInfo;\nimport org.apache.inlong.tubemq.corerpc.RpcConfig;\nimport org.apache.inlong.tubemq.corerpc.RpcConstants;\nimport org.apache.inlong.tubemq.corerpc.RpcServiceFactory;\nimport org.apache.inlong.tubemq.corerpc.netty.NettyClientFactory;\n\npublic class RcpService4BenchmarkClient {\n\n private final ExecutorService executorService = Executors.newCachedThreadPool();\n\n private final String targetHost;\n\n private final int targetPort;\n\n private final RpcServiceFactory rpcServiceFactory;\n\n private final NettyClientFactory clientFactory = new NettyClientFactory();\n\n private SimpleService simpleService;\n\n private int threadNum = 10;\n\n private int invokeTimes = 1000000;\n\n public RcpService4BenchmarkClient(String targetHost, int targetPort, int threadNum, int invokeTimes) {\n this.targetHost = targetHost;\n this.targetPort = targetPort;\n this.threadNum = threadNum;\n this.invokeTimes = invokeTimes;\n RpcConfig config = new RpcConfig();\n config.put(RpcConstants.RPC_CODEC, 6);\n config.put(RpcConstants.CONNECT_TIMEOUT, 3000);\n config.put(RpcConstants.REQUEST_TIMEOUT, 10000);\n clientFactory.configure(config);\n rpcServiceFactory = new RpcServiceFactory(clientFactory);\n BrokerInfo brokerInfo = new BrokerInfo(1, targetHost, targetPort);\n this.simpleService = rpcServiceFactory.getService(SimpleService.class, brokerInfo, config);\n }\n\n public static void main(String[] args) throws Exception {\n new RcpService4BenchmarkClient(\"127.0.0.1\", 8088, 10, 100000).start();\n }\n\n public void start() throws Exception {\n for (int i = 0; i < threadNum; i++) {\n executorService.submit(new Runnable() {\n\n ", "post_mask_code": "{\n long startTime = System.currentTimeMillis();\n for (int j = 0; j < invokeTimes; j++) {\n simpleService.echo(\"This is a test.\");\n }\n System.out.println(Thread.currentThread().getName() + \" execute \" + invokeTimes);\n long endTime = System.currentTimeMillis() - startTime;\n System.out.println(\"cost time:\" + endTime + \" ms\");\n }\n });\n }\n executorService.shutdown();\n executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n }\n}\n"} {"task_id": "Java_2669", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/incubator-inlong/inlong-tubemq/tubemq-core/src/main/java/org/apache/inlong/tubemq/corerpc/benchemark/RcpService4BenchmarkClient.java", "mask_start_position": 1733, "mask_end_position": 1819, "canonical_solution": "{\n new RcpService4BenchmarkClient(\"127.0.0.1\", 8088, 10, 100000).start();\n }", "pre_mask_code": "package org.apache.inlong.tubemq.corerpc.benchemark;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\nimport org.apache.inlong.tubemq.corebase.cluster.BrokerInfo;\nimport org.apache.inlong.tubemq.corerpc.RpcConfig;\nimport org.apache.inlong.tubemq.corerpc.RpcConstants;\nimport org.apache.inlong.tubemq.corerpc.RpcServiceFactory;\nimport org.apache.inlong.tubemq.corerpc.netty.NettyClientFactory;\n\npublic class RcpService4BenchmarkClient {\n\n private final ExecutorService executorService = Executors.newCachedThreadPool();\n\n private final String targetHost;\n\n private final int targetPort;\n\n private final RpcServiceFactory rpcServiceFactory;\n\n private final NettyClientFactory clientFactory = new NettyClientFactory();\n\n private SimpleService simpleService;\n\n private int threadNum = 10;\n\n private int invokeTimes = 1000000;\n\n public RcpService4BenchmarkClient(String targetHost, int targetPort, int threadNum, int invokeTimes) {\n this.targetHost = targetHost;\n this.targetPort = targetPort;\n this.threadNum = threadNum;\n this.invokeTimes = invokeTimes;\n RpcConfig config = new RpcConfig();\n config.put(RpcConstants.RPC_CODEC, 6);\n config.put(RpcConstants.CONNECT_TIMEOUT, 3000);\n config.put(RpcConstants.REQUEST_TIMEOUT, 10000);\n clientFactory.configure(config);\n rpcServiceFactory = new RpcServiceFactory(clientFactory);\n BrokerInfo brokerInfo = new BrokerInfo(1, targetHost, targetPort);\n this.simpleService = rpcServiceFactory.getService(SimpleService.class, brokerInfo, config);\n }\n\n public static void main(String[] args) throws Exception ", "post_mask_code": "\n\n public void start() throws Exception {\n for (int i = 0; i < threadNum; i++) {\n executorService.submit(new Runnable() {\n\n @Override\n public void run() {\n long startTime = System.currentTimeMillis();\n for (int j = 0; j < invokeTimes; j++) {\n simpleService.echo(\"This is a test.\");\n }\n System.out.println(Thread.currentThread().getName() + \" execute \" + invokeTimes);\n long endTime = System.currentTimeMillis() - startTime;\n System.out.println(\"cost time:\" + endTime + \" ms\");\n }\n });\n }\n executorService.shutdown();\n executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n }\n}\n"} {"task_id": "Java_2670", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/incubator-inlong/inlong-tubemq/tubemq-core/src/main/java/org/apache/inlong/tubemq/corerpc/benchemark/RcpService4BenchmarkClient.java", "mask_start_position": 2382, "mask_end_position": 2411, "canonical_solution": "rentTimeMillis() - startTime;", "pre_mask_code": "package org.apache.inlong.tubemq.corerpc.benchemark;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\nimport org.apache.inlong.tubemq.corebase.cluster.BrokerInfo;\nimport org.apache.inlong.tubemq.corerpc.RpcConfig;\nimport org.apache.inlong.tubemq.corerpc.RpcConstants;\nimport org.apache.inlong.tubemq.corerpc.RpcServiceFactory;\nimport org.apache.inlong.tubemq.corerpc.netty.NettyClientFactory;\n\npublic class RcpService4BenchmarkClient {\n\n private final ExecutorService executorService = Executors.newCachedThreadPool();\n\n private final String targetHost;\n\n private final int targetPort;\n\n private final RpcServiceFactory rpcServiceFactory;\n\n private final NettyClientFactory clientFactory = new NettyClientFactory();\n\n private SimpleService simpleService;\n\n private int threadNum = 10;\n\n private int invokeTimes = 1000000;\n\n public RcpService4BenchmarkClient(String targetHost, int targetPort, int threadNum, int invokeTimes) {\n this.targetHost = targetHost;\n this.targetPort = targetPort;\n this.threadNum = threadNum;\n this.invokeTimes = invokeTimes;\n RpcConfig config = new RpcConfig();\n config.put(RpcConstants.RPC_CODEC, 6);\n config.put(RpcConstants.CONNECT_TIMEOUT, 3000);\n config.put(RpcConstants.REQUEST_TIMEOUT, 10000);\n clientFactory.configure(config);\n rpcServiceFactory = new RpcServiceFactory(clientFactory);\n BrokerInfo brokerInfo = new BrokerInfo(1, targetHost, targetPort);\n this.simpleService = rpcServiceFactory.getService(SimpleService.class, brokerInfo, config);\n }\n\n public static void main(String[] args) throws Exception {\n new RcpService4BenchmarkClient(\"127.0.0.1\", 8088, 10, 100000).start();\n }\n\n public void start() throws Exception {\n for (int i = 0; i < threadNum; i++) {\n executorService.submit(new Runnable() {\n\n @Override\n public void run() {\n long startTime = System.currentTimeMillis();\n for (int j = 0; j < invokeTimes; j++) {\n simpleService.echo(\"This is a test.\");\n }\n System.out.println(Thread.currentThread().getName() + \" execute \" + invokeTimes);\n long endTime = System.cur", "post_mask_code": "\n System.out.println(\"cost time:\" + endTime + \" ms\");\n }\n });\n }\n executorService.shutdown();\n executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n }\n}\n"} {"task_id": "Java_2671", "language": "Java", "task_type": "for_statement", "source_file": "java/github/apache/incubator-inlong/inlong-tubemq/tubemq-core/src/main/java/org/apache/inlong/tubemq/corerpc/benchemark/RcpService4BenchmarkClient.java", "mask_start_position": 2110, "mask_end_position": 2234, "canonical_solution": "for (int j = 0; j < invokeTimes; j++) {\n simpleService.echo(\"This is a test.\");\n }", "pre_mask_code": "package org.apache.inlong.tubemq.corerpc.benchemark;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\nimport org.apache.inlong.tubemq.corebase.cluster.BrokerInfo;\nimport org.apache.inlong.tubemq.corerpc.RpcConfig;\nimport org.apache.inlong.tubemq.corerpc.RpcConstants;\nimport org.apache.inlong.tubemq.corerpc.RpcServiceFactory;\nimport org.apache.inlong.tubemq.corerpc.netty.NettyClientFactory;\n\npublic class RcpService4BenchmarkClient {\n\n private final ExecutorService executorService = Executors.newCachedThreadPool();\n\n private final String targetHost;\n\n private final int targetPort;\n\n private final RpcServiceFactory rpcServiceFactory;\n\n private final NettyClientFactory clientFactory = new NettyClientFactory();\n\n private SimpleService simpleService;\n\n private int threadNum = 10;\n\n private int invokeTimes = 1000000;\n\n public RcpService4BenchmarkClient(String targetHost, int targetPort, int threadNum, int invokeTimes) {\n this.targetHost = targetHost;\n this.targetPort = targetPort;\n this.threadNum = threadNum;\n this.invokeTimes = invokeTimes;\n RpcConfig config = new RpcConfig();\n config.put(RpcConstants.RPC_CODEC, 6);\n config.put(RpcConstants.CONNECT_TIMEOUT, 3000);\n config.put(RpcConstants.REQUEST_TIMEOUT, 10000);\n clientFactory.configure(config);\n rpcServiceFactory = new RpcServiceFactory(clientFactory);\n BrokerInfo brokerInfo = new BrokerInfo(1, targetHost, targetPort);\n this.simpleService = rpcServiceFactory.getService(SimpleService.class, brokerInfo, config);\n }\n\n public static void main(String[] args) throws Exception {\n new RcpService4BenchmarkClient(\"127.0.0.1\", 8088, 10, 100000).start();\n }\n\n public void start() throws Exception {\n for (int i = 0; i < threadNum; i++) {\n executorService.submit(new Runnable() {\n\n @Override\n public void run() {\n long startTime = System.currentTimeMillis();\n ", "post_mask_code": "\n System.out.println(Thread.currentThread().getName() + \" execute \" + invokeTimes);\n long endTime = System.currentTimeMillis() - startTime;\n System.out.println(\"cost time:\" + endTime + \" ms\");\n }\n });\n }\n executorService.shutdown();\n executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n }\n}\n"} {"task_id": "Java_2672", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/flink/flink-runtime/src/main/java/org/apache/flink/runtime/leaderelection/LeaderContender.java", "mask_start_position": 1205, "mask_end_position": 1237, "canonical_solution": "default String getDescription() ", "pre_mask_code": "package org.apache.flink.runtime.leaderelection;\n\nimport java.util.UUID;\n\n/**\n * Interface which has to be implemented to take part in the leader election process of the {@link\n * LeaderElectionService}.\n */\npublic interface LeaderContender {\n\n /**\n * Callback method which is called by the {@link LeaderElectionService} upon selecting this\n * instance as the new leader. The method is called with the new leader session ID.\n *\n * @param leaderSessionID New leader session ID\n */\n void grantLeadership(UUID leaderSessionID);\n\n /**\n * Callback method which is called by the {@link LeaderElectionService} upon revoking the\n * leadership of a former leader. This might happen in case that multiple contenders have been\n * granted leadership.\n */\n void revokeLeadership();\n\n /**\n * Callback method which is called by {@link LeaderElectionService} in case of an error in the\n * service thread.\n *\n * @param exception Caught exception\n */\n void handleError(Exception exception);\n\n /**\n * Returns the description of the {@link LeaderContender} for logging purposes.\n *\n * @return Description of this contender.\n */\n ", "post_mask_code": "{\n return \"LeaderContender: \" + getClass().getSimpleName();\n }\n}\n"} {"task_id": "Java_2673", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/flink/flink-runtime/src/main/java/org/apache/flink/runtime/leaderelection/LeaderContender.java", "mask_start_position": 1237, "mask_end_position": 1309, "canonical_solution": "{\n return \"LeaderContender: \" + getClass().getSimpleName();\n }", "pre_mask_code": "package org.apache.flink.runtime.leaderelection;\n\nimport java.util.UUID;\n\n/**\n * Interface which has to be implemented to take part in the leader election process of the {@link\n * LeaderElectionService}.\n */\npublic interface LeaderContender {\n\n /**\n * Callback method which is called by the {@link LeaderElectionService} upon selecting this\n * instance as the new leader. The method is called with the new leader session ID.\n *\n * @param leaderSessionID New leader session ID\n */\n void grantLeadership(UUID leaderSessionID);\n\n /**\n * Callback method which is called by the {@link LeaderElectionService} upon revoking the\n * leadership of a former leader. This might happen in case that multiple contenders have been\n * granted leadership.\n */\n void revokeLeadership();\n\n /**\n * Callback method which is called by {@link LeaderElectionService} in case of an error in the\n * service thread.\n *\n * @param exception Caught exception\n */\n void handleError(Exception exception);\n\n /**\n * Returns the description of the {@link LeaderContender} for logging purposes.\n *\n * @return Description of this contender.\n */\n default String getDescription() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2674", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/flink/flink-runtime/src/main/java/org/apache/flink/runtime/leaderelection/LeaderContender.java", "mask_start_position": 1294, "mask_end_position": 1303, "canonical_solution": "leName();", "pre_mask_code": "package org.apache.flink.runtime.leaderelection;\n\nimport java.util.UUID;\n\n/**\n * Interface which has to be implemented to take part in the leader election process of the {@link\n * LeaderElectionService}.\n */\npublic interface LeaderContender {\n\n /**\n * Callback method which is called by the {@link LeaderElectionService} upon selecting this\n * instance as the new leader. The method is called with the new leader session ID.\n *\n * @param leaderSessionID New leader session ID\n */\n void grantLeadership(UUID leaderSessionID);\n\n /**\n * Callback method which is called by the {@link LeaderElectionService} upon revoking the\n * leadership of a former leader. This might happen in case that multiple contenders have been\n * granted leadership.\n */\n void revokeLeadership();\n\n /**\n * Callback method which is called by {@link LeaderElectionService} in case of an error in the\n * service thread.\n *\n * @param exception Caught exception\n */\n void handleError(Exception exception);\n\n /**\n * Returns the description of the {@link LeaderContender} for logging purposes.\n *\n * @return Description of this contender.\n */\n default String getDescription() {\n return \"LeaderContender: \" + getClass().getSimp", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2675", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/apache/flink/flink-runtime/src/main/java/org/apache/flink/runtime/leaderelection/LeaderContender.java", "mask_start_position": 1205, "mask_end_position": 1309, "canonical_solution": "default String getDescription() {\n return \"LeaderContender: \" + getClass().getSimpleName();\n }", "pre_mask_code": "package org.apache.flink.runtime.leaderelection;\n\nimport java.util.UUID;\n\n/**\n * Interface which has to be implemented to take part in the leader election process of the {@link\n * LeaderElectionService}.\n */\npublic interface LeaderContender {\n\n /**\n * Callback method which is called by the {@link LeaderElectionService} upon selecting this\n * instance as the new leader. The method is called with the new leader session ID.\n *\n * @param leaderSessionID New leader session ID\n */\n void grantLeadership(UUID leaderSessionID);\n\n /**\n * Callback method which is called by the {@link LeaderElectionService} upon revoking the\n * leadership of a former leader. This might happen in case that multiple contenders have been\n * granted leadership.\n */\n void revokeLeadership();\n\n /**\n * Callback method which is called by {@link LeaderElectionService} in case of an error in the\n * service thread.\n *\n * @param exception Caught exception\n */\n void handleError(Exception exception);\n\n /**\n * Returns the description of the {@link LeaderContender} for logging purposes.\n *\n * @return Description of this contender.\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2676", "language": "Java", "task_type": "method_signature", "source_file": "java/github/queencodemonkey/building-a-custom-camera-application/app/src/area/java/com/randomlytyping/camera/CameraAreaActivity.java", "mask_start_position": 10738, "mask_end_position": 10770, "canonical_solution": "private void hidePictureTaken() ", "pre_mask_code": "package com.randomlytyping.camera;\n\nimport android.app.Activity;\nimport android.content.pm.PackageManager;\nimport android.graphics.Bitmap;\nimport android.graphics.Rect;\nimport android.hardware.Camera;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ImageButton;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport java.util.ArrayList;\n\n/**\n * Created by Huyen Tue Dao on 5/13/14.\n */\npublic class CameraAreaActivity extends Activity implements View.OnClickListener, View.OnTouchListener, Preview.PreviewListener {\n\n /**\n * ID value for a particular camera (front or back) that was not found.\n */\n private static final int NO_CAMERA = -1;\n\n /**\n * Whether the currently open camera is the front-facing camera.\n */\n private static final String STATE_IS_FRONT_CAMERA = \"isFrontCamera\";\n\n @SuppressWarnings(\"unused\")\n private static final String TAG = \"CameraAreaActivity\";\n\n // Views\n private TextView mErrorTextView;\n\n private ImageView mPictureView;\n\n private ImageButton mCaptureButton;\n\n private ImageButton mSwitchButton;\n\n private Preview mPreview;\n\n // Camera fields\n private Camera mCamera;\n\n private boolean mIsFrontCamera;\n\n private int mBackCameraId;\n\n private int mFrontCameraId;\n\n // Threading/runnables\n private long mHidePictureDelay;\n\n private Handler mHandler;\n\n private Runnable mHidePictureRunnable = new Runnable() {\n\n @Override\n public void run() {\n hidePictureTaken();\n }\n };\n\n // Activity lifecycle\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_camera_area);\n // Grab reference to the TextView for display errors.\n mErrorTextView = (TextView) findViewById(R.id.error_text);\n // Grab references to the picture-taking-related views.\n mPictureView = (ImageView) findViewById(R.id.picture_taken);\n mCaptureButton = (ImageButton) findViewById(R.id.capture_button);\n // Grab references to camera-switching-related views.\n mSwitchButton = (ImageButton) findViewById(R.id.switch_button);\n // Grab reference to the preview.\n mPreview = (Preview) findViewById(R.id.preview);\n mPreview.setListener(this);\n /*\n If the device actually has a camera, set up the surface holder.\n Otherwise, display an error message.\n */\n if (hasCamera()) {\n /*\n If the activity contains a valid SurfaceView for the preview, then set it up.\n Otherwise, display an error message.\n */\n if (mPreview != null) {\n /* Initialize fields for executing code on the UI thread. We are using this for\n hiding the preview of a taken picture after a short delay. */\n mHidePictureDelay = getResources().getInteger(R.integer.picture_taken_show_duration);\n mHandler = new Handler(Looper.getMainLooper());\n // Get back-facing camera info.\n mBackCameraId = findCameraId(false);\n // If the device has a front-facing camera, determine what camera we open first.\n if (hasFrontCamera()) {\n mFrontCameraId = findCameraId(true);\n mIsFrontCamera = savedInstanceState != null && savedInstanceState.getBoolean(STATE_IS_FRONT_CAMERA, false);\n mSwitchButton.setOnClickListener(this);\n } else {\n mFrontCameraId = NO_CAMERA;\n mSwitchButton.setVisibility(View.GONE);\n }\n hideError();\n } else {\n /* Disable picture-taking button if there is no camera preview since we cannot take\n pictures with the Camera if there is no preview. */\n mCaptureButton.setEnabled(false);\n showError(R.string.error_preview_surface_view_does_not_exist);\n }\n } else {\n showError(R.string.error_no_camera);\n }\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n // If there is a hardware camera then open it and start setting up the preview surface.\n if (mPreview != null && hasCamera()) {\n openCamera();\n mCaptureButton.setOnTouchListener(this);\n mCaptureButton.setOnClickListener(this);\n }\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n // Close the camera while we are not using so that other applications can use it.\n closeCamera();\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n // Save which camera is currently open to state.\n outState.putBoolean(STATE_IS_FRONT_CAMERA, mIsFrontCamera);\n }\n\n // Camera setup\n /**\n * Check whether the device actually has a camera.\n *\n * @return True if the device has a camera, false otherwise.\n */\n private boolean hasCamera() {\n final PackageManager packageManager = getPackageManager();\n return packageManager != null && packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA);\n }\n\n /**\n * Check whether the device has a front-facing camera.\n *\n * @return True if the device has a front-facing camera; false otherwise.\n */\n private boolean hasFrontCamera() {\n final PackageManager packageManager = getPackageManager();\n return packageManager != null && packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);\n }\n\n /**\n * Returns the camera ID (an integer between 0 and {@link android.hardware.Camera#getNumberOfCameras()})\n * for either the first front-facing or first back-facing camera.\n *\n * @param front True to find the first front-facing camera; false to find the first back-facing\n * camera.\n *\n * @return The camera ID for the requested camera as an integer between between 0 and {@link\n * android.hardware.Camera#getNumberOfCameras()} or -1 if there was no matching camera.\n */\n private int findCameraId(boolean front) {\n final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();\n final int cameraCount = Camera.getNumberOfCameras();\n /* Iterate through 0…getNumberOfCameras - 1 to find the camera ID of the first front or\n the first back camera. */\n for (int i = 0; i < cameraCount; i++) {\n Camera.getCameraInfo(i, cameraInfo);\n if ((front && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) || (!front && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)) {\n return i;\n }\n }\n return NO_CAMERA;\n }\n\n /**\n * Returns a {@link android.hardware.Camera.CameraInfo} instance containing information on the\n * currently open camera.\n *\n * @return A {@link android.hardware.Camera.CameraInfo} instance containing information on the\n * currently open camera or `null` if no camera is open.\n */\n private Camera.CameraInfo getCameraInfo() {\n final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();\n Camera.getCameraInfo(mIsFrontCamera ? mFrontCameraId : mBackCameraId, cameraInfo);\n return cameraInfo;\n }\n\n /**\n * Open the first back-facing camera and grab a {@link android.hardware.Camera} instance.\n */\n private void openCamera() {\n if (mCamera != null) {\n if (mPreview.isStarted()) {\n mPreview.stop();\n }\n mCamera.cancelAutoFocus();\n mCamera.release();\n }\n mCamera = Camera.open(mIsFrontCamera ? mFrontCameraId : mBackCameraId);\n final Camera.CameraInfo cameraInfo = getCameraInfo();\n mPreview.setCamera(mCamera, cameraInfo);\n mPreview.start();\n final Camera.Parameters parameters = mCamera.getParameters();\n if (parameters.getMaxNumFocusAreas() > 0) {\n mPreview.startFocusAreaSelection();\n mPreview.setListener(this);\n } else {\n mPreview.stopFocusAreaSelection();\n mPreview.setListener(null);\n }\n }\n\n /**\n * Close the camera and release the previously obtained {@link android.hardware.Camera} instance\n * to make sure that other applications can grab the camera if needed.\n */\n private void closeCamera() {\n if (mCamera != null) {\n mPreview.setCamera(null, null);\n mCamera.release();\n mCamera = null;\n }\n }\n\n /**\n * Toggles the camera if we have two cameras available and starts the preview for the new\n * camera.\n */\n private void switchCamera() {\n if (mFrontCameraId != NO_CAMERA) {\n mIsFrontCamera = !mIsFrontCamera;\n openCamera();\n }\n }\n\n // Auto-focus\n private final Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {\n\n @Override\n public void onAutoFocus(boolean success, Camera camera) {\n }\n };\n\n // Picture taking\n /**\n * Callback for retrieving JPEG data when a picture is taken.\n */\n private final Camera.PictureCallback mJpegCallback = new Camera.PictureCallback() {\n\n @Override\n public void onPictureTaken(byte[] data, Camera camera) {\n showPicture(CameraUtils.bitmapFromRawBytes(data, mPictureView.getWidth(), mPictureView.getHeight()));\n }\n };\n\n /**\n * Checks if the camera is open and takes a picture, retrieving JPEG data.\n */\n private void takePicture() {\n if (mCamera != null) {\n // Take picture and capture raw image data.\n mCamera.takePicture(null, null, mJpegCallback);\n }\n }\n\n // Show/hide picture taken\n /**\n * Displays a picture taken with the {@link android.hardware.Camera} and hides the preview and\n * capture button.\n *\n * @param bitmap A {@link android.graphics.Bitmap} containing the picture taken.\n */\n private void showPicture(Bitmap bitmap) {\n mPictureView.setImageBitmap(bitmap);\n mPictureView.setVisibility(View.VISIBLE);\n mPreview.setVisibility(View.INVISIBLE);\n mCaptureButton.setVisibility(View.GONE);\n mHandler.postDelayed(mHidePictureRunnable, mHidePictureDelay);\n }\n\n /**\n * Hides any shown picture and shows the preview and capture button.\n */\n ", "post_mask_code": "{\n mPreview.start();\n mPictureView.setVisibility(View.INVISIBLE);\n mPreview.setVisibility(View.VISIBLE);\n mCaptureButton.setVisibility(View.VISIBLE);\n }\n\n // Show/hide error text\n /**\n * Show an error message text and hide the camera preview.\n *\n * @param errorResourceId A resource ID for the error string resource.\n */\n private void showError(int errorResourceId) {\n mErrorTextView.setText(errorResourceId);\n mErrorTextView.setVisibility(View.VISIBLE);\n mPreview.setVisibility(View.GONE);\n }\n\n /**\n * Hides the error message text and show the camera preview.\n */\n private void hideError() {\n mErrorTextView.setVisibility(View.GONE);\n mPreview.setVisibility(View.VISIBLE);\n }\n\n // View.OnClickListener implementation\n @Override\n public void onClick(View v) {\n if (v == mSwitchButton) {\n switchCamera();\n } else if (v == mCaptureButton) {\n takePicture();\n }\n }\n\n // View.OnTouchListener implementation\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if (v == mCaptureButton) {\n switch(event.getAction() & MotionEvent.ACTION_MASK) {\n case MotionEvent.ACTION_DOWN:\n mCamera.autoFocus(mAutoFocusCallback);\n return false;\n }\n }\n return false;\n }\n\n // PreviewListener implementation\n @Override\n public void onAutoFocus() {\n mCamera.autoFocus(mAutoFocusCallback);\n }\n\n @Override\n public void onFocusAreaChange(Rect area) {\n if (mCamera != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n final Camera.Parameters parameters = mCamera.getParameters();\n ArrayList focusAreas = new ArrayList();\n focusAreas.add(new Camera.Area(area, 10));\n parameters.setFocusAreas(focusAreas);\n mCamera.setParameters(parameters);\n mCamera.autoFocus(mAutoFocusCallback);\n }\n }\n\n @Override\n public void onMeteringAreaChange(Rect area) {\n if (mCamera != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n final Camera.Parameters parameters = mCamera.getParameters();\n ArrayList meteringAreas = new ArrayList();\n meteringAreas.add(new Camera.Area(area, 10));\n parameters.setMeteringAreas(meteringAreas);\n mCamera.setParameters(parameters);\n mCamera.autoFocus(mAutoFocusCallback);\n }\n }\n}\n"} {"task_id": "Java_2677", "language": "Java", "task_type": "method_body", "source_file": "java/github/queencodemonkey/building-a-custom-camera-application/app/src/area/java/com/randomlytyping/camera/CameraAreaActivity.java", "mask_start_position": 9016, "mask_end_position": 9148, "canonical_solution": "{\n if (mFrontCameraId != NO_CAMERA) {\n mIsFrontCamera = !mIsFrontCamera;\n openCamera();\n }\n }", "pre_mask_code": "package com.randomlytyping.camera;\n\nimport android.app.Activity;\nimport android.content.pm.PackageManager;\nimport android.graphics.Bitmap;\nimport android.graphics.Rect;\nimport android.hardware.Camera;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ImageButton;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport java.util.ArrayList;\n\n/**\n * Created by Huyen Tue Dao on 5/13/14.\n */\npublic class CameraAreaActivity extends Activity implements View.OnClickListener, View.OnTouchListener, Preview.PreviewListener {\n\n /**\n * ID value for a particular camera (front or back) that was not found.\n */\n private static final int NO_CAMERA = -1;\n\n /**\n * Whether the currently open camera is the front-facing camera.\n */\n private static final String STATE_IS_FRONT_CAMERA = \"isFrontCamera\";\n\n @SuppressWarnings(\"unused\")\n private static final String TAG = \"CameraAreaActivity\";\n\n // Views\n private TextView mErrorTextView;\n\n private ImageView mPictureView;\n\n private ImageButton mCaptureButton;\n\n private ImageButton mSwitchButton;\n\n private Preview mPreview;\n\n // Camera fields\n private Camera mCamera;\n\n private boolean mIsFrontCamera;\n\n private int mBackCameraId;\n\n private int mFrontCameraId;\n\n // Threading/runnables\n private long mHidePictureDelay;\n\n private Handler mHandler;\n\n private Runnable mHidePictureRunnable = new Runnable() {\n\n @Override\n public void run() {\n hidePictureTaken();\n }\n };\n\n // Activity lifecycle\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_camera_area);\n // Grab reference to the TextView for display errors.\n mErrorTextView = (TextView) findViewById(R.id.error_text);\n // Grab references to the picture-taking-related views.\n mPictureView = (ImageView) findViewById(R.id.picture_taken);\n mCaptureButton = (ImageButton) findViewById(R.id.capture_button);\n // Grab references to camera-switching-related views.\n mSwitchButton = (ImageButton) findViewById(R.id.switch_button);\n // Grab reference to the preview.\n mPreview = (Preview) findViewById(R.id.preview);\n mPreview.setListener(this);\n /*\n If the device actually has a camera, set up the surface holder.\n Otherwise, display an error message.\n */\n if (hasCamera()) {\n /*\n If the activity contains a valid SurfaceView for the preview, then set it up.\n Otherwise, display an error message.\n */\n if (mPreview != null) {\n /* Initialize fields for executing code on the UI thread. We are using this for\n hiding the preview of a taken picture after a short delay. */\n mHidePictureDelay = getResources().getInteger(R.integer.picture_taken_show_duration);\n mHandler = new Handler(Looper.getMainLooper());\n // Get back-facing camera info.\n mBackCameraId = findCameraId(false);\n // If the device has a front-facing camera, determine what camera we open first.\n if (hasFrontCamera()) {\n mFrontCameraId = findCameraId(true);\n mIsFrontCamera = savedInstanceState != null && savedInstanceState.getBoolean(STATE_IS_FRONT_CAMERA, false);\n mSwitchButton.setOnClickListener(this);\n } else {\n mFrontCameraId = NO_CAMERA;\n mSwitchButton.setVisibility(View.GONE);\n }\n hideError();\n } else {\n /* Disable picture-taking button if there is no camera preview since we cannot take\n pictures with the Camera if there is no preview. */\n mCaptureButton.setEnabled(false);\n showError(R.string.error_preview_surface_view_does_not_exist);\n }\n } else {\n showError(R.string.error_no_camera);\n }\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n // If there is a hardware camera then open it and start setting up the preview surface.\n if (mPreview != null && hasCamera()) {\n openCamera();\n mCaptureButton.setOnTouchListener(this);\n mCaptureButton.setOnClickListener(this);\n }\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n // Close the camera while we are not using so that other applications can use it.\n closeCamera();\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n // Save which camera is currently open to state.\n outState.putBoolean(STATE_IS_FRONT_CAMERA, mIsFrontCamera);\n }\n\n // Camera setup\n /**\n * Check whether the device actually has a camera.\n *\n * @return True if the device has a camera, false otherwise.\n */\n private boolean hasCamera() {\n final PackageManager packageManager = getPackageManager();\n return packageManager != null && packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA);\n }\n\n /**\n * Check whether the device has a front-facing camera.\n *\n * @return True if the device has a front-facing camera; false otherwise.\n */\n private boolean hasFrontCamera() {\n final PackageManager packageManager = getPackageManager();\n return packageManager != null && packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);\n }\n\n /**\n * Returns the camera ID (an integer between 0 and {@link android.hardware.Camera#getNumberOfCameras()})\n * for either the first front-facing or first back-facing camera.\n *\n * @param front True to find the first front-facing camera; false to find the first back-facing\n * camera.\n *\n * @return The camera ID for the requested camera as an integer between between 0 and {@link\n * android.hardware.Camera#getNumberOfCameras()} or -1 if there was no matching camera.\n */\n private int findCameraId(boolean front) {\n final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();\n final int cameraCount = Camera.getNumberOfCameras();\n /* Iterate through 0…getNumberOfCameras - 1 to find the camera ID of the first front or\n the first back camera. */\n for (int i = 0; i < cameraCount; i++) {\n Camera.getCameraInfo(i, cameraInfo);\n if ((front && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) || (!front && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)) {\n return i;\n }\n }\n return NO_CAMERA;\n }\n\n /**\n * Returns a {@link android.hardware.Camera.CameraInfo} instance containing information on the\n * currently open camera.\n *\n * @return A {@link android.hardware.Camera.CameraInfo} instance containing information on the\n * currently open camera or `null` if no camera is open.\n */\n private Camera.CameraInfo getCameraInfo() {\n final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();\n Camera.getCameraInfo(mIsFrontCamera ? mFrontCameraId : mBackCameraId, cameraInfo);\n return cameraInfo;\n }\n\n /**\n * Open the first back-facing camera and grab a {@link android.hardware.Camera} instance.\n */\n private void openCamera() {\n if (mCamera != null) {\n if (mPreview.isStarted()) {\n mPreview.stop();\n }\n mCamera.cancelAutoFocus();\n mCamera.release();\n }\n mCamera = Camera.open(mIsFrontCamera ? mFrontCameraId : mBackCameraId);\n final Camera.CameraInfo cameraInfo = getCameraInfo();\n mPreview.setCamera(mCamera, cameraInfo);\n mPreview.start();\n final Camera.Parameters parameters = mCamera.getParameters();\n if (parameters.getMaxNumFocusAreas() > 0) {\n mPreview.startFocusAreaSelection();\n mPreview.setListener(this);\n } else {\n mPreview.stopFocusAreaSelection();\n mPreview.setListener(null);\n }\n }\n\n /**\n * Close the camera and release the previously obtained {@link android.hardware.Camera} instance\n * to make sure that other applications can grab the camera if needed.\n */\n private void closeCamera() {\n if (mCamera != null) {\n mPreview.setCamera(null, null);\n mCamera.release();\n mCamera = null;\n }\n }\n\n /**\n * Toggles the camera if we have two cameras available and starts the preview for the new\n * camera.\n */\n private void switchCamera() ", "post_mask_code": "\n\n // Auto-focus\n private final Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {\n\n @Override\n public void onAutoFocus(boolean success, Camera camera) {\n }\n };\n\n // Picture taking\n /**\n * Callback for retrieving JPEG data when a picture is taken.\n */\n private final Camera.PictureCallback mJpegCallback = new Camera.PictureCallback() {\n\n @Override\n public void onPictureTaken(byte[] data, Camera camera) {\n showPicture(CameraUtils.bitmapFromRawBytes(data, mPictureView.getWidth(), mPictureView.getHeight()));\n }\n };\n\n /**\n * Checks if the camera is open and takes a picture, retrieving JPEG data.\n */\n private void takePicture() {\n if (mCamera != null) {\n // Take picture and capture raw image data.\n mCamera.takePicture(null, null, mJpegCallback);\n }\n }\n\n // Show/hide picture taken\n /**\n * Displays a picture taken with the {@link android.hardware.Camera} and hides the preview and\n * capture button.\n *\n * @param bitmap A {@link android.graphics.Bitmap} containing the picture taken.\n */\n private void showPicture(Bitmap bitmap) {\n mPictureView.setImageBitmap(bitmap);\n mPictureView.setVisibility(View.VISIBLE);\n mPreview.setVisibility(View.INVISIBLE);\n mCaptureButton.setVisibility(View.GONE);\n mHandler.postDelayed(mHidePictureRunnable, mHidePictureDelay);\n }\n\n /**\n * Hides any shown picture and shows the preview and capture button.\n */\n private void hidePictureTaken() {\n mPreview.start();\n mPictureView.setVisibility(View.INVISIBLE);\n mPreview.setVisibility(View.VISIBLE);\n mCaptureButton.setVisibility(View.VISIBLE);\n }\n\n // Show/hide error text\n /**\n * Show an error message text and hide the camera preview.\n *\n * @param errorResourceId A resource ID for the error string resource.\n */\n private void showError(int errorResourceId) {\n mErrorTextView.setText(errorResourceId);\n mErrorTextView.setVisibility(View.VISIBLE);\n mPreview.setVisibility(View.GONE);\n }\n\n /**\n * Hides the error message text and show the camera preview.\n */\n private void hideError() {\n mErrorTextView.setVisibility(View.GONE);\n mPreview.setVisibility(View.VISIBLE);\n }\n\n // View.OnClickListener implementation\n @Override\n public void onClick(View v) {\n if (v == mSwitchButton) {\n switchCamera();\n } else if (v == mCaptureButton) {\n takePicture();\n }\n }\n\n // View.OnTouchListener implementation\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if (v == mCaptureButton) {\n switch(event.getAction() & MotionEvent.ACTION_MASK) {\n case MotionEvent.ACTION_DOWN:\n mCamera.autoFocus(mAutoFocusCallback);\n return false;\n }\n }\n return false;\n }\n\n // PreviewListener implementation\n @Override\n public void onAutoFocus() {\n mCamera.autoFocus(mAutoFocusCallback);\n }\n\n @Override\n public void onFocusAreaChange(Rect area) {\n if (mCamera != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n final Camera.Parameters parameters = mCamera.getParameters();\n ArrayList focusAreas = new ArrayList();\n focusAreas.add(new Camera.Area(area, 10));\n parameters.setFocusAreas(focusAreas);\n mCamera.setParameters(parameters);\n mCamera.autoFocus(mAutoFocusCallback);\n }\n }\n\n @Override\n public void onMeteringAreaChange(Rect area) {\n if (mCamera != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n final Camera.Parameters parameters = mCamera.getParameters();\n ArrayList meteringAreas = new ArrayList();\n meteringAreas.add(new Camera.Area(area, 10));\n parameters.setMeteringAreas(meteringAreas);\n mCamera.setParameters(parameters);\n mCamera.autoFocus(mAutoFocusCallback);\n }\n }\n}\n"} {"task_id": "Java_2678", "language": "Java", "task_type": "single_line", "source_file": "java/github/queencodemonkey/building-a-custom-camera-application/app/src/area/java/com/randomlytyping/camera/CameraAreaActivity.java", "mask_start_position": 5083, "mask_end_position": 5096, "canonical_solution": "FrontCamera);", "pre_mask_code": "package com.randomlytyping.camera;\n\nimport android.app.Activity;\nimport android.content.pm.PackageManager;\nimport android.graphics.Bitmap;\nimport android.graphics.Rect;\nimport android.hardware.Camera;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ImageButton;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport java.util.ArrayList;\n\n/**\n * Created by Huyen Tue Dao on 5/13/14.\n */\npublic class CameraAreaActivity extends Activity implements View.OnClickListener, View.OnTouchListener, Preview.PreviewListener {\n\n /**\n * ID value for a particular camera (front or back) that was not found.\n */\n private static final int NO_CAMERA = -1;\n\n /**\n * Whether the currently open camera is the front-facing camera.\n */\n private static final String STATE_IS_FRONT_CAMERA = \"isFrontCamera\";\n\n @SuppressWarnings(\"unused\")\n private static final String TAG = \"CameraAreaActivity\";\n\n // Views\n private TextView mErrorTextView;\n\n private ImageView mPictureView;\n\n private ImageButton mCaptureButton;\n\n private ImageButton mSwitchButton;\n\n private Preview mPreview;\n\n // Camera fields\n private Camera mCamera;\n\n private boolean mIsFrontCamera;\n\n private int mBackCameraId;\n\n private int mFrontCameraId;\n\n // Threading/runnables\n private long mHidePictureDelay;\n\n private Handler mHandler;\n\n private Runnable mHidePictureRunnable = new Runnable() {\n\n @Override\n public void run() {\n hidePictureTaken();\n }\n };\n\n // Activity lifecycle\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_camera_area);\n // Grab reference to the TextView for display errors.\n mErrorTextView = (TextView) findViewById(R.id.error_text);\n // Grab references to the picture-taking-related views.\n mPictureView = (ImageView) findViewById(R.id.picture_taken);\n mCaptureButton = (ImageButton) findViewById(R.id.capture_button);\n // Grab references to camera-switching-related views.\n mSwitchButton = (ImageButton) findViewById(R.id.switch_button);\n // Grab reference to the preview.\n mPreview = (Preview) findViewById(R.id.preview);\n mPreview.setListener(this);\n /*\n If the device actually has a camera, set up the surface holder.\n Otherwise, display an error message.\n */\n if (hasCamera()) {\n /*\n If the activity contains a valid SurfaceView for the preview, then set it up.\n Otherwise, display an error message.\n */\n if (mPreview != null) {\n /* Initialize fields for executing code on the UI thread. We are using this for\n hiding the preview of a taken picture after a short delay. */\n mHidePictureDelay = getResources().getInteger(R.integer.picture_taken_show_duration);\n mHandler = new Handler(Looper.getMainLooper());\n // Get back-facing camera info.\n mBackCameraId = findCameraId(false);\n // If the device has a front-facing camera, determine what camera we open first.\n if (hasFrontCamera()) {\n mFrontCameraId = findCameraId(true);\n mIsFrontCamera = savedInstanceState != null && savedInstanceState.getBoolean(STATE_IS_FRONT_CAMERA, false);\n mSwitchButton.setOnClickListener(this);\n } else {\n mFrontCameraId = NO_CAMERA;\n mSwitchButton.setVisibility(View.GONE);\n }\n hideError();\n } else {\n /* Disable picture-taking button if there is no camera preview since we cannot take\n pictures with the Camera if there is no preview. */\n mCaptureButton.setEnabled(false);\n showError(R.string.error_preview_surface_view_does_not_exist);\n }\n } else {\n showError(R.string.error_no_camera);\n }\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n // If there is a hardware camera then open it and start setting up the preview surface.\n if (mPreview != null && hasCamera()) {\n openCamera();\n mCaptureButton.setOnTouchListener(this);\n mCaptureButton.setOnClickListener(this);\n }\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n // Close the camera while we are not using so that other applications can use it.\n closeCamera();\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n // Save which camera is currently open to state.\n outState.putBoolean(STATE_IS_FRONT_CAMERA, mIs", "post_mask_code": "\n }\n\n // Camera setup\n /**\n * Check whether the device actually has a camera.\n *\n * @return True if the device has a camera, false otherwise.\n */\n private boolean hasCamera() {\n final PackageManager packageManager = getPackageManager();\n return packageManager != null && packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA);\n }\n\n /**\n * Check whether the device has a front-facing camera.\n *\n * @return True if the device has a front-facing camera; false otherwise.\n */\n private boolean hasFrontCamera() {\n final PackageManager packageManager = getPackageManager();\n return packageManager != null && packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);\n }\n\n /**\n * Returns the camera ID (an integer between 0 and {@link android.hardware.Camera#getNumberOfCameras()})\n * for either the first front-facing or first back-facing camera.\n *\n * @param front True to find the first front-facing camera; false to find the first back-facing\n * camera.\n *\n * @return The camera ID for the requested camera as an integer between between 0 and {@link\n * android.hardware.Camera#getNumberOfCameras()} or -1 if there was no matching camera.\n */\n private int findCameraId(boolean front) {\n final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();\n final int cameraCount = Camera.getNumberOfCameras();\n /* Iterate through 0…getNumberOfCameras - 1 to find the camera ID of the first front or\n the first back camera. */\n for (int i = 0; i < cameraCount; i++) {\n Camera.getCameraInfo(i, cameraInfo);\n if ((front && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) || (!front && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)) {\n return i;\n }\n }\n return NO_CAMERA;\n }\n\n /**\n * Returns a {@link android.hardware.Camera.CameraInfo} instance containing information on the\n * currently open camera.\n *\n * @return A {@link android.hardware.Camera.CameraInfo} instance containing information on the\n * currently open camera or `null` if no camera is open.\n */\n private Camera.CameraInfo getCameraInfo() {\n final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();\n Camera.getCameraInfo(mIsFrontCamera ? mFrontCameraId : mBackCameraId, cameraInfo);\n return cameraInfo;\n }\n\n /**\n * Open the first back-facing camera and grab a {@link android.hardware.Camera} instance.\n */\n private void openCamera() {\n if (mCamera != null) {\n if (mPreview.isStarted()) {\n mPreview.stop();\n }\n mCamera.cancelAutoFocus();\n mCamera.release();\n }\n mCamera = Camera.open(mIsFrontCamera ? mFrontCameraId : mBackCameraId);\n final Camera.CameraInfo cameraInfo = getCameraInfo();\n mPreview.setCamera(mCamera, cameraInfo);\n mPreview.start();\n final Camera.Parameters parameters = mCamera.getParameters();\n if (parameters.getMaxNumFocusAreas() > 0) {\n mPreview.startFocusAreaSelection();\n mPreview.setListener(this);\n } else {\n mPreview.stopFocusAreaSelection();\n mPreview.setListener(null);\n }\n }\n\n /**\n * Close the camera and release the previously obtained {@link android.hardware.Camera} instance\n * to make sure that other applications can grab the camera if needed.\n */\n private void closeCamera() {\n if (mCamera != null) {\n mPreview.setCamera(null, null);\n mCamera.release();\n mCamera = null;\n }\n }\n\n /**\n * Toggles the camera if we have two cameras available and starts the preview for the new\n * camera.\n */\n private void switchCamera() {\n if (mFrontCameraId != NO_CAMERA) {\n mIsFrontCamera = !mIsFrontCamera;\n openCamera();\n }\n }\n\n // Auto-focus\n private final Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {\n\n @Override\n public void onAutoFocus(boolean success, Camera camera) {\n }\n };\n\n // Picture taking\n /**\n * Callback for retrieving JPEG data when a picture is taken.\n */\n private final Camera.PictureCallback mJpegCallback = new Camera.PictureCallback() {\n\n @Override\n public void onPictureTaken(byte[] data, Camera camera) {\n showPicture(CameraUtils.bitmapFromRawBytes(data, mPictureView.getWidth(), mPictureView.getHeight()));\n }\n };\n\n /**\n * Checks if the camera is open and takes a picture, retrieving JPEG data.\n */\n private void takePicture() {\n if (mCamera != null) {\n // Take picture and capture raw image data.\n mCamera.takePicture(null, null, mJpegCallback);\n }\n }\n\n // Show/hide picture taken\n /**\n * Displays a picture taken with the {@link android.hardware.Camera} and hides the preview and\n * capture button.\n *\n * @param bitmap A {@link android.graphics.Bitmap} containing the picture taken.\n */\n private void showPicture(Bitmap bitmap) {\n mPictureView.setImageBitmap(bitmap);\n mPictureView.setVisibility(View.VISIBLE);\n mPreview.setVisibility(View.INVISIBLE);\n mCaptureButton.setVisibility(View.GONE);\n mHandler.postDelayed(mHidePictureRunnable, mHidePictureDelay);\n }\n\n /**\n * Hides any shown picture and shows the preview and capture button.\n */\n private void hidePictureTaken() {\n mPreview.start();\n mPictureView.setVisibility(View.INVISIBLE);\n mPreview.setVisibility(View.VISIBLE);\n mCaptureButton.setVisibility(View.VISIBLE);\n }\n\n // Show/hide error text\n /**\n * Show an error message text and hide the camera preview.\n *\n * @param errorResourceId A resource ID for the error string resource.\n */\n private void showError(int errorResourceId) {\n mErrorTextView.setText(errorResourceId);\n mErrorTextView.setVisibility(View.VISIBLE);\n mPreview.setVisibility(View.GONE);\n }\n\n /**\n * Hides the error message text and show the camera preview.\n */\n private void hideError() {\n mErrorTextView.setVisibility(View.GONE);\n mPreview.setVisibility(View.VISIBLE);\n }\n\n // View.OnClickListener implementation\n @Override\n public void onClick(View v) {\n if (v == mSwitchButton) {\n switchCamera();\n } else if (v == mCaptureButton) {\n takePicture();\n }\n }\n\n // View.OnTouchListener implementation\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if (v == mCaptureButton) {\n switch(event.getAction() & MotionEvent.ACTION_MASK) {\n case MotionEvent.ACTION_DOWN:\n mCamera.autoFocus(mAutoFocusCallback);\n return false;\n }\n }\n return false;\n }\n\n // PreviewListener implementation\n @Override\n public void onAutoFocus() {\n mCamera.autoFocus(mAutoFocusCallback);\n }\n\n @Override\n public void onFocusAreaChange(Rect area) {\n if (mCamera != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n final Camera.Parameters parameters = mCamera.getParameters();\n ArrayList focusAreas = new ArrayList();\n focusAreas.add(new Camera.Area(area, 10));\n parameters.setFocusAreas(focusAreas);\n mCamera.setParameters(parameters);\n mCamera.autoFocus(mAutoFocusCallback);\n }\n }\n\n @Override\n public void onMeteringAreaChange(Rect area) {\n if (mCamera != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n final Camera.Parameters parameters = mCamera.getParameters();\n ArrayList meteringAreas = new ArrayList();\n meteringAreas.add(new Camera.Area(area, 10));\n parameters.setMeteringAreas(meteringAreas);\n mCamera.setParameters(parameters);\n mCamera.autoFocus(mAutoFocusCallback);\n }\n }\n}\n"} {"task_id": "Java_2679", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/queencodemonkey/building-a-custom-camera-application/app/src/area/java/com/randomlytyping/camera/CameraAreaActivity.java", "mask_start_position": 11148, "mask_end_position": 11343, "canonical_solution": "private void showError(int errorResourceId) {\n mErrorTextView.setText(errorResourceId);\n mErrorTextView.setVisibility(View.VISIBLE);\n mPreview.setVisibility(View.GONE);\n }", "pre_mask_code": "package com.randomlytyping.camera;\n\nimport android.app.Activity;\nimport android.content.pm.PackageManager;\nimport android.graphics.Bitmap;\nimport android.graphics.Rect;\nimport android.hardware.Camera;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ImageButton;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport java.util.ArrayList;\n\n/**\n * Created by Huyen Tue Dao on 5/13/14.\n */\npublic class CameraAreaActivity extends Activity implements View.OnClickListener, View.OnTouchListener, Preview.PreviewListener {\n\n /**\n * ID value for a particular camera (front or back) that was not found.\n */\n private static final int NO_CAMERA = -1;\n\n /**\n * Whether the currently open camera is the front-facing camera.\n */\n private static final String STATE_IS_FRONT_CAMERA = \"isFrontCamera\";\n\n @SuppressWarnings(\"unused\")\n private static final String TAG = \"CameraAreaActivity\";\n\n // Views\n private TextView mErrorTextView;\n\n private ImageView mPictureView;\n\n private ImageButton mCaptureButton;\n\n private ImageButton mSwitchButton;\n\n private Preview mPreview;\n\n // Camera fields\n private Camera mCamera;\n\n private boolean mIsFrontCamera;\n\n private int mBackCameraId;\n\n private int mFrontCameraId;\n\n // Threading/runnables\n private long mHidePictureDelay;\n\n private Handler mHandler;\n\n private Runnable mHidePictureRunnable = new Runnable() {\n\n @Override\n public void run() {\n hidePictureTaken();\n }\n };\n\n // Activity lifecycle\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_camera_area);\n // Grab reference to the TextView for display errors.\n mErrorTextView = (TextView) findViewById(R.id.error_text);\n // Grab references to the picture-taking-related views.\n mPictureView = (ImageView) findViewById(R.id.picture_taken);\n mCaptureButton = (ImageButton) findViewById(R.id.capture_button);\n // Grab references to camera-switching-related views.\n mSwitchButton = (ImageButton) findViewById(R.id.switch_button);\n // Grab reference to the preview.\n mPreview = (Preview) findViewById(R.id.preview);\n mPreview.setListener(this);\n /*\n If the device actually has a camera, set up the surface holder.\n Otherwise, display an error message.\n */\n if (hasCamera()) {\n /*\n If the activity contains a valid SurfaceView for the preview, then set it up.\n Otherwise, display an error message.\n */\n if (mPreview != null) {\n /* Initialize fields for executing code on the UI thread. We are using this for\n hiding the preview of a taken picture after a short delay. */\n mHidePictureDelay = getResources().getInteger(R.integer.picture_taken_show_duration);\n mHandler = new Handler(Looper.getMainLooper());\n // Get back-facing camera info.\n mBackCameraId = findCameraId(false);\n // If the device has a front-facing camera, determine what camera we open first.\n if (hasFrontCamera()) {\n mFrontCameraId = findCameraId(true);\n mIsFrontCamera = savedInstanceState != null && savedInstanceState.getBoolean(STATE_IS_FRONT_CAMERA, false);\n mSwitchButton.setOnClickListener(this);\n } else {\n mFrontCameraId = NO_CAMERA;\n mSwitchButton.setVisibility(View.GONE);\n }\n hideError();\n } else {\n /* Disable picture-taking button if there is no camera preview since we cannot take\n pictures with the Camera if there is no preview. */\n mCaptureButton.setEnabled(false);\n showError(R.string.error_preview_surface_view_does_not_exist);\n }\n } else {\n showError(R.string.error_no_camera);\n }\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n // If there is a hardware camera then open it and start setting up the preview surface.\n if (mPreview != null && hasCamera()) {\n openCamera();\n mCaptureButton.setOnTouchListener(this);\n mCaptureButton.setOnClickListener(this);\n }\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n // Close the camera while we are not using so that other applications can use it.\n closeCamera();\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n // Save which camera is currently open to state.\n outState.putBoolean(STATE_IS_FRONT_CAMERA, mIsFrontCamera);\n }\n\n // Camera setup\n /**\n * Check whether the device actually has a camera.\n *\n * @return True if the device has a camera, false otherwise.\n */\n private boolean hasCamera() {\n final PackageManager packageManager = getPackageManager();\n return packageManager != null && packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA);\n }\n\n /**\n * Check whether the device has a front-facing camera.\n *\n * @return True if the device has a front-facing camera; false otherwise.\n */\n private boolean hasFrontCamera() {\n final PackageManager packageManager = getPackageManager();\n return packageManager != null && packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);\n }\n\n /**\n * Returns the camera ID (an integer between 0 and {@link android.hardware.Camera#getNumberOfCameras()})\n * for either the first front-facing or first back-facing camera.\n *\n * @param front True to find the first front-facing camera; false to find the first back-facing\n * camera.\n *\n * @return The camera ID for the requested camera as an integer between between 0 and {@link\n * android.hardware.Camera#getNumberOfCameras()} or -1 if there was no matching camera.\n */\n private int findCameraId(boolean front) {\n final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();\n final int cameraCount = Camera.getNumberOfCameras();\n /* Iterate through 0…getNumberOfCameras - 1 to find the camera ID of the first front or\n the first back camera. */\n for (int i = 0; i < cameraCount; i++) {\n Camera.getCameraInfo(i, cameraInfo);\n if ((front && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) || (!front && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)) {\n return i;\n }\n }\n return NO_CAMERA;\n }\n\n /**\n * Returns a {@link android.hardware.Camera.CameraInfo} instance containing information on the\n * currently open camera.\n *\n * @return A {@link android.hardware.Camera.CameraInfo} instance containing information on the\n * currently open camera or `null` if no camera is open.\n */\n private Camera.CameraInfo getCameraInfo() {\n final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();\n Camera.getCameraInfo(mIsFrontCamera ? mFrontCameraId : mBackCameraId, cameraInfo);\n return cameraInfo;\n }\n\n /**\n * Open the first back-facing camera and grab a {@link android.hardware.Camera} instance.\n */\n private void openCamera() {\n if (mCamera != null) {\n if (mPreview.isStarted()) {\n mPreview.stop();\n }\n mCamera.cancelAutoFocus();\n mCamera.release();\n }\n mCamera = Camera.open(mIsFrontCamera ? mFrontCameraId : mBackCameraId);\n final Camera.CameraInfo cameraInfo = getCameraInfo();\n mPreview.setCamera(mCamera, cameraInfo);\n mPreview.start();\n final Camera.Parameters parameters = mCamera.getParameters();\n if (parameters.getMaxNumFocusAreas() > 0) {\n mPreview.startFocusAreaSelection();\n mPreview.setListener(this);\n } else {\n mPreview.stopFocusAreaSelection();\n mPreview.setListener(null);\n }\n }\n\n /**\n * Close the camera and release the previously obtained {@link android.hardware.Camera} instance\n * to make sure that other applications can grab the camera if needed.\n */\n private void closeCamera() {\n if (mCamera != null) {\n mPreview.setCamera(null, null);\n mCamera.release();\n mCamera = null;\n }\n }\n\n /**\n * Toggles the camera if we have two cameras available and starts the preview for the new\n * camera.\n */\n private void switchCamera() {\n if (mFrontCameraId != NO_CAMERA) {\n mIsFrontCamera = !mIsFrontCamera;\n openCamera();\n }\n }\n\n // Auto-focus\n private final Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {\n\n @Override\n public void onAutoFocus(boolean success, Camera camera) {\n }\n };\n\n // Picture taking\n /**\n * Callback for retrieving JPEG data when a picture is taken.\n */\n private final Camera.PictureCallback mJpegCallback = new Camera.PictureCallback() {\n\n @Override\n public void onPictureTaken(byte[] data, Camera camera) {\n showPicture(CameraUtils.bitmapFromRawBytes(data, mPictureView.getWidth(), mPictureView.getHeight()));\n }\n };\n\n /**\n * Checks if the camera is open and takes a picture, retrieving JPEG data.\n */\n private void takePicture() {\n if (mCamera != null) {\n // Take picture and capture raw image data.\n mCamera.takePicture(null, null, mJpegCallback);\n }\n }\n\n // Show/hide picture taken\n /**\n * Displays a picture taken with the {@link android.hardware.Camera} and hides the preview and\n * capture button.\n *\n * @param bitmap A {@link android.graphics.Bitmap} containing the picture taken.\n */\n private void showPicture(Bitmap bitmap) {\n mPictureView.setImageBitmap(bitmap);\n mPictureView.setVisibility(View.VISIBLE);\n mPreview.setVisibility(View.INVISIBLE);\n mCaptureButton.setVisibility(View.GONE);\n mHandler.postDelayed(mHidePictureRunnable, mHidePictureDelay);\n }\n\n /**\n * Hides any shown picture and shows the preview and capture button.\n */\n private void hidePictureTaken() {\n mPreview.start();\n mPictureView.setVisibility(View.INVISIBLE);\n mPreview.setVisibility(View.VISIBLE);\n mCaptureButton.setVisibility(View.VISIBLE);\n }\n\n // Show/hide error text\n /**\n * Show an error message text and hide the camera preview.\n *\n * @param errorResourceId A resource ID for the error string resource.\n */\n ", "post_mask_code": "\n\n /**\n * Hides the error message text and show the camera preview.\n */\n private void hideError() {\n mErrorTextView.setVisibility(View.GONE);\n mPreview.setVisibility(View.VISIBLE);\n }\n\n // View.OnClickListener implementation\n @Override\n public void onClick(View v) {\n if (v == mSwitchButton) {\n switchCamera();\n } else if (v == mCaptureButton) {\n takePicture();\n }\n }\n\n // View.OnTouchListener implementation\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if (v == mCaptureButton) {\n switch(event.getAction() & MotionEvent.ACTION_MASK) {\n case MotionEvent.ACTION_DOWN:\n mCamera.autoFocus(mAutoFocusCallback);\n return false;\n }\n }\n return false;\n }\n\n // PreviewListener implementation\n @Override\n public void onAutoFocus() {\n mCamera.autoFocus(mAutoFocusCallback);\n }\n\n @Override\n public void onFocusAreaChange(Rect area) {\n if (mCamera != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n final Camera.Parameters parameters = mCamera.getParameters();\n ArrayList focusAreas = new ArrayList();\n focusAreas.add(new Camera.Area(area, 10));\n parameters.setFocusAreas(focusAreas);\n mCamera.setParameters(parameters);\n mCamera.autoFocus(mAutoFocusCallback);\n }\n }\n\n @Override\n public void onMeteringAreaChange(Rect area) {\n if (mCamera != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n final Camera.Parameters parameters = mCamera.getParameters();\n ArrayList meteringAreas = new ArrayList();\n meteringAreas.add(new Camera.Area(area, 10));\n parameters.setMeteringAreas(meteringAreas);\n mCamera.setParameters(parameters);\n mCamera.autoFocus(mAutoFocusCallback);\n }\n }\n}\n"} {"task_id": "Java_2680", "language": "Java", "task_type": "switch_case", "source_file": "java/github/queencodemonkey/building-a-custom-camera-application/app/src/area/java/com/randomlytyping/camera/CameraAreaActivity.java", "mask_start_position": 11958, "mask_end_position": 12164, "canonical_solution": "switch(event.getAction() & MotionEvent.ACTION_MASK) {\n case MotionEvent.ACTION_DOWN:\n mCamera.autoFocus(mAutoFocusCallback);\n return false;\n }", "pre_mask_code": "package com.randomlytyping.camera;\n\nimport android.app.Activity;\nimport android.content.pm.PackageManager;\nimport android.graphics.Bitmap;\nimport android.graphics.Rect;\nimport android.hardware.Camera;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ImageButton;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport java.util.ArrayList;\n\n/**\n * Created by Huyen Tue Dao on 5/13/14.\n */\npublic class CameraAreaActivity extends Activity implements View.OnClickListener, View.OnTouchListener, Preview.PreviewListener {\n\n /**\n * ID value for a particular camera (front or back) that was not found.\n */\n private static final int NO_CAMERA = -1;\n\n /**\n * Whether the currently open camera is the front-facing camera.\n */\n private static final String STATE_IS_FRONT_CAMERA = \"isFrontCamera\";\n\n @SuppressWarnings(\"unused\")\n private static final String TAG = \"CameraAreaActivity\";\n\n // Views\n private TextView mErrorTextView;\n\n private ImageView mPictureView;\n\n private ImageButton mCaptureButton;\n\n private ImageButton mSwitchButton;\n\n private Preview mPreview;\n\n // Camera fields\n private Camera mCamera;\n\n private boolean mIsFrontCamera;\n\n private int mBackCameraId;\n\n private int mFrontCameraId;\n\n // Threading/runnables\n private long mHidePictureDelay;\n\n private Handler mHandler;\n\n private Runnable mHidePictureRunnable = new Runnable() {\n\n @Override\n public void run() {\n hidePictureTaken();\n }\n };\n\n // Activity lifecycle\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_camera_area);\n // Grab reference to the TextView for display errors.\n mErrorTextView = (TextView) findViewById(R.id.error_text);\n // Grab references to the picture-taking-related views.\n mPictureView = (ImageView) findViewById(R.id.picture_taken);\n mCaptureButton = (ImageButton) findViewById(R.id.capture_button);\n // Grab references to camera-switching-related views.\n mSwitchButton = (ImageButton) findViewById(R.id.switch_button);\n // Grab reference to the preview.\n mPreview = (Preview) findViewById(R.id.preview);\n mPreview.setListener(this);\n /*\n If the device actually has a camera, set up the surface holder.\n Otherwise, display an error message.\n */\n if (hasCamera()) {\n /*\n If the activity contains a valid SurfaceView for the preview, then set it up.\n Otherwise, display an error message.\n */\n if (mPreview != null) {\n /* Initialize fields for executing code on the UI thread. We are using this for\n hiding the preview of a taken picture after a short delay. */\n mHidePictureDelay = getResources().getInteger(R.integer.picture_taken_show_duration);\n mHandler = new Handler(Looper.getMainLooper());\n // Get back-facing camera info.\n mBackCameraId = findCameraId(false);\n // If the device has a front-facing camera, determine what camera we open first.\n if (hasFrontCamera()) {\n mFrontCameraId = findCameraId(true);\n mIsFrontCamera = savedInstanceState != null && savedInstanceState.getBoolean(STATE_IS_FRONT_CAMERA, false);\n mSwitchButton.setOnClickListener(this);\n } else {\n mFrontCameraId = NO_CAMERA;\n mSwitchButton.setVisibility(View.GONE);\n }\n hideError();\n } else {\n /* Disable picture-taking button if there is no camera preview since we cannot take\n pictures with the Camera if there is no preview. */\n mCaptureButton.setEnabled(false);\n showError(R.string.error_preview_surface_view_does_not_exist);\n }\n } else {\n showError(R.string.error_no_camera);\n }\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n // If there is a hardware camera then open it and start setting up the preview surface.\n if (mPreview != null && hasCamera()) {\n openCamera();\n mCaptureButton.setOnTouchListener(this);\n mCaptureButton.setOnClickListener(this);\n }\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n // Close the camera while we are not using so that other applications can use it.\n closeCamera();\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n // Save which camera is currently open to state.\n outState.putBoolean(STATE_IS_FRONT_CAMERA, mIsFrontCamera);\n }\n\n // Camera setup\n /**\n * Check whether the device actually has a camera.\n *\n * @return True if the device has a camera, false otherwise.\n */\n private boolean hasCamera() {\n final PackageManager packageManager = getPackageManager();\n return packageManager != null && packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA);\n }\n\n /**\n * Check whether the device has a front-facing camera.\n *\n * @return True if the device has a front-facing camera; false otherwise.\n */\n private boolean hasFrontCamera() {\n final PackageManager packageManager = getPackageManager();\n return packageManager != null && packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);\n }\n\n /**\n * Returns the camera ID (an integer between 0 and {@link android.hardware.Camera#getNumberOfCameras()})\n * for either the first front-facing or first back-facing camera.\n *\n * @param front True to find the first front-facing camera; false to find the first back-facing\n * camera.\n *\n * @return The camera ID for the requested camera as an integer between between 0 and {@link\n * android.hardware.Camera#getNumberOfCameras()} or -1 if there was no matching camera.\n */\n private int findCameraId(boolean front) {\n final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();\n final int cameraCount = Camera.getNumberOfCameras();\n /* Iterate through 0…getNumberOfCameras - 1 to find the camera ID of the first front or\n the first back camera. */\n for (int i = 0; i < cameraCount; i++) {\n Camera.getCameraInfo(i, cameraInfo);\n if ((front && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) || (!front && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)) {\n return i;\n }\n }\n return NO_CAMERA;\n }\n\n /**\n * Returns a {@link android.hardware.Camera.CameraInfo} instance containing information on the\n * currently open camera.\n *\n * @return A {@link android.hardware.Camera.CameraInfo} instance containing information on the\n * currently open camera or `null` if no camera is open.\n */\n private Camera.CameraInfo getCameraInfo() {\n final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();\n Camera.getCameraInfo(mIsFrontCamera ? mFrontCameraId : mBackCameraId, cameraInfo);\n return cameraInfo;\n }\n\n /**\n * Open the first back-facing camera and grab a {@link android.hardware.Camera} instance.\n */\n private void openCamera() {\n if (mCamera != null) {\n if (mPreview.isStarted()) {\n mPreview.stop();\n }\n mCamera.cancelAutoFocus();\n mCamera.release();\n }\n mCamera = Camera.open(mIsFrontCamera ? mFrontCameraId : mBackCameraId);\n final Camera.CameraInfo cameraInfo = getCameraInfo();\n mPreview.setCamera(mCamera, cameraInfo);\n mPreview.start();\n final Camera.Parameters parameters = mCamera.getParameters();\n if (parameters.getMaxNumFocusAreas() > 0) {\n mPreview.startFocusAreaSelection();\n mPreview.setListener(this);\n } else {\n mPreview.stopFocusAreaSelection();\n mPreview.setListener(null);\n }\n }\n\n /**\n * Close the camera and release the previously obtained {@link android.hardware.Camera} instance\n * to make sure that other applications can grab the camera if needed.\n */\n private void closeCamera() {\n if (mCamera != null) {\n mPreview.setCamera(null, null);\n mCamera.release();\n mCamera = null;\n }\n }\n\n /**\n * Toggles the camera if we have two cameras available and starts the preview for the new\n * camera.\n */\n private void switchCamera() {\n if (mFrontCameraId != NO_CAMERA) {\n mIsFrontCamera = !mIsFrontCamera;\n openCamera();\n }\n }\n\n // Auto-focus\n private final Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {\n\n @Override\n public void onAutoFocus(boolean success, Camera camera) {\n }\n };\n\n // Picture taking\n /**\n * Callback for retrieving JPEG data when a picture is taken.\n */\n private final Camera.PictureCallback mJpegCallback = new Camera.PictureCallback() {\n\n @Override\n public void onPictureTaken(byte[] data, Camera camera) {\n showPicture(CameraUtils.bitmapFromRawBytes(data, mPictureView.getWidth(), mPictureView.getHeight()));\n }\n };\n\n /**\n * Checks if the camera is open and takes a picture, retrieving JPEG data.\n */\n private void takePicture() {\n if (mCamera != null) {\n // Take picture and capture raw image data.\n mCamera.takePicture(null, null, mJpegCallback);\n }\n }\n\n // Show/hide picture taken\n /**\n * Displays a picture taken with the {@link android.hardware.Camera} and hides the preview and\n * capture button.\n *\n * @param bitmap A {@link android.graphics.Bitmap} containing the picture taken.\n */\n private void showPicture(Bitmap bitmap) {\n mPictureView.setImageBitmap(bitmap);\n mPictureView.setVisibility(View.VISIBLE);\n mPreview.setVisibility(View.INVISIBLE);\n mCaptureButton.setVisibility(View.GONE);\n mHandler.postDelayed(mHidePictureRunnable, mHidePictureDelay);\n }\n\n /**\n * Hides any shown picture and shows the preview and capture button.\n */\n private void hidePictureTaken() {\n mPreview.start();\n mPictureView.setVisibility(View.INVISIBLE);\n mPreview.setVisibility(View.VISIBLE);\n mCaptureButton.setVisibility(View.VISIBLE);\n }\n\n // Show/hide error text\n /**\n * Show an error message text and hide the camera preview.\n *\n * @param errorResourceId A resource ID for the error string resource.\n */\n private void showError(int errorResourceId) {\n mErrorTextView.setText(errorResourceId);\n mErrorTextView.setVisibility(View.VISIBLE);\n mPreview.setVisibility(View.GONE);\n }\n\n /**\n * Hides the error message text and show the camera preview.\n */\n private void hideError() {\n mErrorTextView.setVisibility(View.GONE);\n mPreview.setVisibility(View.VISIBLE);\n }\n\n // View.OnClickListener implementation\n @Override\n public void onClick(View v) {\n if (v == mSwitchButton) {\n switchCamera();\n } else if (v == mCaptureButton) {\n takePicture();\n }\n }\n\n // View.OnTouchListener implementation\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if (v == mCaptureButton) {\n ", "post_mask_code": "\n }\n return false;\n }\n\n // PreviewListener implementation\n @Override\n public void onAutoFocus() {\n mCamera.autoFocus(mAutoFocusCallback);\n }\n\n @Override\n public void onFocusAreaChange(Rect area) {\n if (mCamera != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n final Camera.Parameters parameters = mCamera.getParameters();\n ArrayList focusAreas = new ArrayList();\n focusAreas.add(new Camera.Area(area, 10));\n parameters.setFocusAreas(focusAreas);\n mCamera.setParameters(parameters);\n mCamera.autoFocus(mAutoFocusCallback);\n }\n }\n\n @Override\n public void onMeteringAreaChange(Rect area) {\n if (mCamera != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n final Camera.Parameters parameters = mCamera.getParameters();\n ArrayList meteringAreas = new ArrayList();\n meteringAreas.add(new Camera.Area(area, 10));\n parameters.setMeteringAreas(meteringAreas);\n mCamera.setParameters(parameters);\n mCamera.autoFocus(mAutoFocusCallback);\n }\n }\n}\n"} {"task_id": "Java_2681", "language": "Java", "task_type": "for_statement", "source_file": "java/github/queencodemonkey/building-a-custom-camera-application/app/src/area/java/com/randomlytyping/camera/CameraAreaActivity.java", "mask_start_position": 6706, "mask_end_position": 7006, "canonical_solution": "for (int i = 0; i < cameraCount; i++) {\n Camera.getCameraInfo(i, cameraInfo);\n if ((front && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) || (!front && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)) {\n return i;\n }\n }", "pre_mask_code": "package com.randomlytyping.camera;\n\nimport android.app.Activity;\nimport android.content.pm.PackageManager;\nimport android.graphics.Bitmap;\nimport android.graphics.Rect;\nimport android.hardware.Camera;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.util.Log;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ImageButton;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport java.util.ArrayList;\n\n/**\n * Created by Huyen Tue Dao on 5/13/14.\n */\npublic class CameraAreaActivity extends Activity implements View.OnClickListener, View.OnTouchListener, Preview.PreviewListener {\n\n /**\n * ID value for a particular camera (front or back) that was not found.\n */\n private static final int NO_CAMERA = -1;\n\n /**\n * Whether the currently open camera is the front-facing camera.\n */\n private static final String STATE_IS_FRONT_CAMERA = \"isFrontCamera\";\n\n @SuppressWarnings(\"unused\")\n private static final String TAG = \"CameraAreaActivity\";\n\n // Views\n private TextView mErrorTextView;\n\n private ImageView mPictureView;\n\n private ImageButton mCaptureButton;\n\n private ImageButton mSwitchButton;\n\n private Preview mPreview;\n\n // Camera fields\n private Camera mCamera;\n\n private boolean mIsFrontCamera;\n\n private int mBackCameraId;\n\n private int mFrontCameraId;\n\n // Threading/runnables\n private long mHidePictureDelay;\n\n private Handler mHandler;\n\n private Runnable mHidePictureRunnable = new Runnable() {\n\n @Override\n public void run() {\n hidePictureTaken();\n }\n };\n\n // Activity lifecycle\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_camera_area);\n // Grab reference to the TextView for display errors.\n mErrorTextView = (TextView) findViewById(R.id.error_text);\n // Grab references to the picture-taking-related views.\n mPictureView = (ImageView) findViewById(R.id.picture_taken);\n mCaptureButton = (ImageButton) findViewById(R.id.capture_button);\n // Grab references to camera-switching-related views.\n mSwitchButton = (ImageButton) findViewById(R.id.switch_button);\n // Grab reference to the preview.\n mPreview = (Preview) findViewById(R.id.preview);\n mPreview.setListener(this);\n /*\n If the device actually has a camera, set up the surface holder.\n Otherwise, display an error message.\n */\n if (hasCamera()) {\n /*\n If the activity contains a valid SurfaceView for the preview, then set it up.\n Otherwise, display an error message.\n */\n if (mPreview != null) {\n /* Initialize fields for executing code on the UI thread. We are using this for\n hiding the preview of a taken picture after a short delay. */\n mHidePictureDelay = getResources().getInteger(R.integer.picture_taken_show_duration);\n mHandler = new Handler(Looper.getMainLooper());\n // Get back-facing camera info.\n mBackCameraId = findCameraId(false);\n // If the device has a front-facing camera, determine what camera we open first.\n if (hasFrontCamera()) {\n mFrontCameraId = findCameraId(true);\n mIsFrontCamera = savedInstanceState != null && savedInstanceState.getBoolean(STATE_IS_FRONT_CAMERA, false);\n mSwitchButton.setOnClickListener(this);\n } else {\n mFrontCameraId = NO_CAMERA;\n mSwitchButton.setVisibility(View.GONE);\n }\n hideError();\n } else {\n /* Disable picture-taking button if there is no camera preview since we cannot take\n pictures with the Camera if there is no preview. */\n mCaptureButton.setEnabled(false);\n showError(R.string.error_preview_surface_view_does_not_exist);\n }\n } else {\n showError(R.string.error_no_camera);\n }\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n // If there is a hardware camera then open it and start setting up the preview surface.\n if (mPreview != null && hasCamera()) {\n openCamera();\n mCaptureButton.setOnTouchListener(this);\n mCaptureButton.setOnClickListener(this);\n }\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n // Close the camera while we are not using so that other applications can use it.\n closeCamera();\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n // Save which camera is currently open to state.\n outState.putBoolean(STATE_IS_FRONT_CAMERA, mIsFrontCamera);\n }\n\n // Camera setup\n /**\n * Check whether the device actually has a camera.\n *\n * @return True if the device has a camera, false otherwise.\n */\n private boolean hasCamera() {\n final PackageManager packageManager = getPackageManager();\n return packageManager != null && packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA);\n }\n\n /**\n * Check whether the device has a front-facing camera.\n *\n * @return True if the device has a front-facing camera; false otherwise.\n */\n private boolean hasFrontCamera() {\n final PackageManager packageManager = getPackageManager();\n return packageManager != null && packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);\n }\n\n /**\n * Returns the camera ID (an integer between 0 and {@link android.hardware.Camera#getNumberOfCameras()})\n * for either the first front-facing or first back-facing camera.\n *\n * @param front True to find the first front-facing camera; false to find the first back-facing\n * camera.\n *\n * @return The camera ID for the requested camera as an integer between between 0 and {@link\n * android.hardware.Camera#getNumberOfCameras()} or -1 if there was no matching camera.\n */\n private int findCameraId(boolean front) {\n final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();\n final int cameraCount = Camera.getNumberOfCameras();\n /* Iterate through 0…getNumberOfCameras - 1 to find the camera ID of the first front or\n the first back camera. */\n ", "post_mask_code": "\n return NO_CAMERA;\n }\n\n /**\n * Returns a {@link android.hardware.Camera.CameraInfo} instance containing information on the\n * currently open camera.\n *\n * @return A {@link android.hardware.Camera.CameraInfo} instance containing information on the\n * currently open camera or `null` if no camera is open.\n */\n private Camera.CameraInfo getCameraInfo() {\n final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();\n Camera.getCameraInfo(mIsFrontCamera ? mFrontCameraId : mBackCameraId, cameraInfo);\n return cameraInfo;\n }\n\n /**\n * Open the first back-facing camera and grab a {@link android.hardware.Camera} instance.\n */\n private void openCamera() {\n if (mCamera != null) {\n if (mPreview.isStarted()) {\n mPreview.stop();\n }\n mCamera.cancelAutoFocus();\n mCamera.release();\n }\n mCamera = Camera.open(mIsFrontCamera ? mFrontCameraId : mBackCameraId);\n final Camera.CameraInfo cameraInfo = getCameraInfo();\n mPreview.setCamera(mCamera, cameraInfo);\n mPreview.start();\n final Camera.Parameters parameters = mCamera.getParameters();\n if (parameters.getMaxNumFocusAreas() > 0) {\n mPreview.startFocusAreaSelection();\n mPreview.setListener(this);\n } else {\n mPreview.stopFocusAreaSelection();\n mPreview.setListener(null);\n }\n }\n\n /**\n * Close the camera and release the previously obtained {@link android.hardware.Camera} instance\n * to make sure that other applications can grab the camera if needed.\n */\n private void closeCamera() {\n if (mCamera != null) {\n mPreview.setCamera(null, null);\n mCamera.release();\n mCamera = null;\n }\n }\n\n /**\n * Toggles the camera if we have two cameras available and starts the preview for the new\n * camera.\n */\n private void switchCamera() {\n if (mFrontCameraId != NO_CAMERA) {\n mIsFrontCamera = !mIsFrontCamera;\n openCamera();\n }\n }\n\n // Auto-focus\n private final Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {\n\n @Override\n public void onAutoFocus(boolean success, Camera camera) {\n }\n };\n\n // Picture taking\n /**\n * Callback for retrieving JPEG data when a picture is taken.\n */\n private final Camera.PictureCallback mJpegCallback = new Camera.PictureCallback() {\n\n @Override\n public void onPictureTaken(byte[] data, Camera camera) {\n showPicture(CameraUtils.bitmapFromRawBytes(data, mPictureView.getWidth(), mPictureView.getHeight()));\n }\n };\n\n /**\n * Checks if the camera is open and takes a picture, retrieving JPEG data.\n */\n private void takePicture() {\n if (mCamera != null) {\n // Take picture and capture raw image data.\n mCamera.takePicture(null, null, mJpegCallback);\n }\n }\n\n // Show/hide picture taken\n /**\n * Displays a picture taken with the {@link android.hardware.Camera} and hides the preview and\n * capture button.\n *\n * @param bitmap A {@link android.graphics.Bitmap} containing the picture taken.\n */\n private void showPicture(Bitmap bitmap) {\n mPictureView.setImageBitmap(bitmap);\n mPictureView.setVisibility(View.VISIBLE);\n mPreview.setVisibility(View.INVISIBLE);\n mCaptureButton.setVisibility(View.GONE);\n mHandler.postDelayed(mHidePictureRunnable, mHidePictureDelay);\n }\n\n /**\n * Hides any shown picture and shows the preview and capture button.\n */\n private void hidePictureTaken() {\n mPreview.start();\n mPictureView.setVisibility(View.INVISIBLE);\n mPreview.setVisibility(View.VISIBLE);\n mCaptureButton.setVisibility(View.VISIBLE);\n }\n\n // Show/hide error text\n /**\n * Show an error message text and hide the camera preview.\n *\n * @param errorResourceId A resource ID for the error string resource.\n */\n private void showError(int errorResourceId) {\n mErrorTextView.setText(errorResourceId);\n mErrorTextView.setVisibility(View.VISIBLE);\n mPreview.setVisibility(View.GONE);\n }\n\n /**\n * Hides the error message text and show the camera preview.\n */\n private void hideError() {\n mErrorTextView.setVisibility(View.GONE);\n mPreview.setVisibility(View.VISIBLE);\n }\n\n // View.OnClickListener implementation\n @Override\n public void onClick(View v) {\n if (v == mSwitchButton) {\n switchCamera();\n } else if (v == mCaptureButton) {\n takePicture();\n }\n }\n\n // View.OnTouchListener implementation\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if (v == mCaptureButton) {\n switch(event.getAction() & MotionEvent.ACTION_MASK) {\n case MotionEvent.ACTION_DOWN:\n mCamera.autoFocus(mAutoFocusCallback);\n return false;\n }\n }\n return false;\n }\n\n // PreviewListener implementation\n @Override\n public void onAutoFocus() {\n mCamera.autoFocus(mAutoFocusCallback);\n }\n\n @Override\n public void onFocusAreaChange(Rect area) {\n if (mCamera != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n final Camera.Parameters parameters = mCamera.getParameters();\n ArrayList focusAreas = new ArrayList();\n focusAreas.add(new Camera.Area(area, 10));\n parameters.setFocusAreas(focusAreas);\n mCamera.setParameters(parameters);\n mCamera.autoFocus(mAutoFocusCallback);\n }\n }\n\n @Override\n public void onMeteringAreaChange(Rect area) {\n if (mCamera != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n final Camera.Parameters parameters = mCamera.getParameters();\n ArrayList meteringAreas = new ArrayList();\n meteringAreas.add(new Camera.Area(area, 10));\n parameters.setMeteringAreas(meteringAreas);\n mCamera.setParameters(parameters);\n mCamera.autoFocus(mAutoFocusCallback);\n }\n }\n}\n"} {"task_id": "Java_2682", "language": "Java", "task_type": "method_signature", "source_file": "java/github/elastic/elasticsearch/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/ClusterStateWaitUntilThresholdStep.java", "mask_start_position": 5371, "mask_end_position": 5411, "canonical_solution": "ClusterStateWaitStep getStepToExecute() ", "pre_mask_code": "package org.elasticsearch.xpack.core.ilm;\n\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.elasticsearch.cluster.ClusterState;\nimport org.elasticsearch.cluster.metadata.IndexMetadata;\nimport org.elasticsearch.core.Nullable;\nimport org.elasticsearch.common.Strings;\nimport org.elasticsearch.core.TimeValue;\nimport org.elasticsearch.index.Index;\nimport org.elasticsearch.xpack.core.ilm.step.info.SingleMessageFieldInfo;\nimport java.time.Clock;\nimport java.util.Locale;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport static org.elasticsearch.xpack.core.ilm.LifecycleExecutionState.fromIndexMetadata;\n\n/**\n * This step wraps an {@link ClusterStateWaitStep} in order to be able to manipulate what the next step will be, depending on the result of\n * the wrapped {@link ClusterStateWaitStep}.\n *

\n * If the action response is complete, the {@link ClusterStateWaitUntilThresholdStep}'s nextStepKey will be the nextStepKey of the\n * wrapped action. When the threshold level is surpassed, if the underlying step's condition was not met, the nextStepKey will be changed to\n * the provided {@link #nextKeyOnThresholdBreach} and this step will stop waiting.\n *\n * Failures encountered whilst executing the wrapped action will be propagated directly.\n */\npublic class ClusterStateWaitUntilThresholdStep extends ClusterStateWaitStep {\n\n private static final Logger logger = LogManager.getLogger(ClusterStateWaitUntilThresholdStep.class);\n\n private final ClusterStateWaitStep stepToExecute;\n\n private final StepKey nextKeyOnThresholdBreach;\n\n private final AtomicBoolean thresholdPassed = new AtomicBoolean(false);\n\n public ClusterStateWaitUntilThresholdStep(ClusterStateWaitStep stepToExecute, StepKey nextKeyOnThresholdBreach) {\n super(stepToExecute.getKey(), stepToExecute.getNextStepKey());\n this.stepToExecute = stepToExecute;\n this.nextKeyOnThresholdBreach = nextKeyOnThresholdBreach;\n }\n\n @Override\n public boolean isRetryable() {\n return true;\n }\n\n @Override\n public Result isConditionMet(Index index, ClusterState clusterState) {\n IndexMetadata idxMeta = clusterState.metadata().index(index);\n if (idxMeta == null) {\n // Index must have been since deleted, ignore it\n logger.debug(\"[{}] lifecycle action for index [{}] executed but index no longer exists\", getKey().getAction(), index.getName());\n return new Result(false, null);\n }\n Result stepResult = stepToExecute.isConditionMet(index, clusterState);\n if (stepResult.isComplete() == false) {\n // checking the threshold after we execute the step to make sure we execute the wrapped step at least once (because time is a\n // wonderful thing)\n TimeValue retryThreshold = LifecycleSettings.LIFECYCLE_STEP_WAIT_TIME_THRESHOLD_SETTING.get(idxMeta.getSettings());\n LifecycleExecutionState lifecycleState = fromIndexMetadata(idxMeta);\n if (stepToExecute.isCompletable() == false) {\n // we may not have passed the time threshold, but the step is not completable due to a different reason\n thresholdPassed.set(true);\n String message = String.format(Locale.ROOT, \"[%s] lifecycle step, as part of [%s] action, for index [%s] Is not \" + \"completable, reason: [%s]. Abandoning execution and moving to the next fallback step [%s]\", getKey().getName(), getKey().getAction(), idxMeta.getIndex().getName(), Strings.toString(stepResult.getInfomationContext()), nextKeyOnThresholdBreach);\n logger.debug(message);\n return new Result(true, new SingleMessageFieldInfo(message));\n }\n if (waitedMoreThanThresholdLevel(retryThreshold, lifecycleState, Clock.systemUTC())) {\n // we retried this step enough, next step will be the configured to {@code nextKeyOnThresholdBreach}\n thresholdPassed.set(true);\n String message = String.format(Locale.ROOT, \"[%s] lifecycle step, as part of [%s] action, for index [%s] executed for\" + \" more than [%s]. Abandoning execution and moving to the next fallback step [%s]\", getKey().getName(), getKey().getAction(), idxMeta.getIndex().getName(), retryThreshold, nextKeyOnThresholdBreach);\n logger.debug(message);\n return new Result(true, new SingleMessageFieldInfo(message));\n }\n }\n return stepResult;\n }\n\n static boolean waitedMoreThanThresholdLevel(@Nullable TimeValue retryThreshold, LifecycleExecutionState lifecycleState, Clock clock) {\n assert lifecycleState.getStepTime() != null : \"lifecycle state [\" + lifecycleState + \"] does not have the step time set\";\n if (retryThreshold != null) {\n // return true if the threshold was surpassed and false otherwise\n return (lifecycleState.getStepTime() + retryThreshold.millis()) < clock.millis();\n }\n return false;\n }\n\n @Override\n public StepKey getNextStepKey() {\n if (thresholdPassed.get()) {\n return nextKeyOnThresholdBreach;\n } else {\n return super.getNextStepKey();\n }\n }\n\n /**\n * Represents the {@link ClusterStateWaitStep} that's wrapped by this branching step.\n */\n ", "post_mask_code": "{\n return stepToExecute;\n }\n\n /**\n * The step key to be reported as the {@link ClusterStateWaitUntilThresholdStep#getNextStepKey()} if the index configured a max wait\n * time using {@link LifecycleSettings#LIFECYCLE_STEP_WAIT_TIME_THRESHOLD_SETTING} and the threshold was passed.\n */\n StepKey getNextKeyOnThreshold() {\n return nextKeyOnThresholdBreach;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (super.equals(o) == false) {\n return false;\n }\n ClusterStateWaitUntilThresholdStep that = (ClusterStateWaitUntilThresholdStep) o;\n return super.equals(o) && Objects.equals(stepToExecute, that.stepToExecute) && Objects.equals(nextKeyOnThresholdBreach, that.nextKeyOnThresholdBreach);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), stepToExecute, nextKeyOnThresholdBreach);\n }\n}\n"} {"task_id": "Java_2683", "language": "Java", "task_type": "method_body", "source_file": "java/github/elastic/elasticsearch/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/ClusterStateWaitUntilThresholdStep.java", "mask_start_position": 4669, "mask_end_position": 5048, "canonical_solution": "{\n assert lifecycleState.getStepTime() != null : \"lifecycle state [\" + lifecycleState + \"] does not have the step time set\";\n if (retryThreshold != null) {\n // return true if the threshold was surpassed and false otherwise\n return (lifecycleState.getStepTime() + retryThreshold.millis()) < clock.millis();\n }\n return false;\n }", "pre_mask_code": "package org.elasticsearch.xpack.core.ilm;\n\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.elasticsearch.cluster.ClusterState;\nimport org.elasticsearch.cluster.metadata.IndexMetadata;\nimport org.elasticsearch.core.Nullable;\nimport org.elasticsearch.common.Strings;\nimport org.elasticsearch.core.TimeValue;\nimport org.elasticsearch.index.Index;\nimport org.elasticsearch.xpack.core.ilm.step.info.SingleMessageFieldInfo;\nimport java.time.Clock;\nimport java.util.Locale;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport static org.elasticsearch.xpack.core.ilm.LifecycleExecutionState.fromIndexMetadata;\n\n/**\n * This step wraps an {@link ClusterStateWaitStep} in order to be able to manipulate what the next step will be, depending on the result of\n * the wrapped {@link ClusterStateWaitStep}.\n *

\n * If the action response is complete, the {@link ClusterStateWaitUntilThresholdStep}'s nextStepKey will be the nextStepKey of the\n * wrapped action. When the threshold level is surpassed, if the underlying step's condition was not met, the nextStepKey will be changed to\n * the provided {@link #nextKeyOnThresholdBreach} and this step will stop waiting.\n *\n * Failures encountered whilst executing the wrapped action will be propagated directly.\n */\npublic class ClusterStateWaitUntilThresholdStep extends ClusterStateWaitStep {\n\n private static final Logger logger = LogManager.getLogger(ClusterStateWaitUntilThresholdStep.class);\n\n private final ClusterStateWaitStep stepToExecute;\n\n private final StepKey nextKeyOnThresholdBreach;\n\n private final AtomicBoolean thresholdPassed = new AtomicBoolean(false);\n\n public ClusterStateWaitUntilThresholdStep(ClusterStateWaitStep stepToExecute, StepKey nextKeyOnThresholdBreach) {\n super(stepToExecute.getKey(), stepToExecute.getNextStepKey());\n this.stepToExecute = stepToExecute;\n this.nextKeyOnThresholdBreach = nextKeyOnThresholdBreach;\n }\n\n @Override\n public boolean isRetryable() {\n return true;\n }\n\n @Override\n public Result isConditionMet(Index index, ClusterState clusterState) {\n IndexMetadata idxMeta = clusterState.metadata().index(index);\n if (idxMeta == null) {\n // Index must have been since deleted, ignore it\n logger.debug(\"[{}] lifecycle action for index [{}] executed but index no longer exists\", getKey().getAction(), index.getName());\n return new Result(false, null);\n }\n Result stepResult = stepToExecute.isConditionMet(index, clusterState);\n if (stepResult.isComplete() == false) {\n // checking the threshold after we execute the step to make sure we execute the wrapped step at least once (because time is a\n // wonderful thing)\n TimeValue retryThreshold = LifecycleSettings.LIFECYCLE_STEP_WAIT_TIME_THRESHOLD_SETTING.get(idxMeta.getSettings());\n LifecycleExecutionState lifecycleState = fromIndexMetadata(idxMeta);\n if (stepToExecute.isCompletable() == false) {\n // we may not have passed the time threshold, but the step is not completable due to a different reason\n thresholdPassed.set(true);\n String message = String.format(Locale.ROOT, \"[%s] lifecycle step, as part of [%s] action, for index [%s] Is not \" + \"completable, reason: [%s]. Abandoning execution and moving to the next fallback step [%s]\", getKey().getName(), getKey().getAction(), idxMeta.getIndex().getName(), Strings.toString(stepResult.getInfomationContext()), nextKeyOnThresholdBreach);\n logger.debug(message);\n return new Result(true, new SingleMessageFieldInfo(message));\n }\n if (waitedMoreThanThresholdLevel(retryThreshold, lifecycleState, Clock.systemUTC())) {\n // we retried this step enough, next step will be the configured to {@code nextKeyOnThresholdBreach}\n thresholdPassed.set(true);\n String message = String.format(Locale.ROOT, \"[%s] lifecycle step, as part of [%s] action, for index [%s] executed for\" + \" more than [%s]. Abandoning execution and moving to the next fallback step [%s]\", getKey().getName(), getKey().getAction(), idxMeta.getIndex().getName(), retryThreshold, nextKeyOnThresholdBreach);\n logger.debug(message);\n return new Result(true, new SingleMessageFieldInfo(message));\n }\n }\n return stepResult;\n }\n\n static boolean waitedMoreThanThresholdLevel(@Nullable TimeValue retryThreshold, LifecycleExecutionState lifecycleState, Clock clock) ", "post_mask_code": "\n\n @Override\n public StepKey getNextStepKey() {\n if (thresholdPassed.get()) {\n return nextKeyOnThresholdBreach;\n } else {\n return super.getNextStepKey();\n }\n }\n\n /**\n * Represents the {@link ClusterStateWaitStep} that's wrapped by this branching step.\n */\n ClusterStateWaitStep getStepToExecute() {\n return stepToExecute;\n }\n\n /**\n * The step key to be reported as the {@link ClusterStateWaitUntilThresholdStep#getNextStepKey()} if the index configured a max wait\n * time using {@link LifecycleSettings#LIFECYCLE_STEP_WAIT_TIME_THRESHOLD_SETTING} and the threshold was passed.\n */\n StepKey getNextKeyOnThreshold() {\n return nextKeyOnThresholdBreach;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (super.equals(o) == false) {\n return false;\n }\n ClusterStateWaitUntilThresholdStep that = (ClusterStateWaitUntilThresholdStep) o;\n return super.equals(o) && Objects.equals(stepToExecute, that.stepToExecute) && Objects.equals(nextKeyOnThresholdBreach, that.nextKeyOnThresholdBreach);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), stepToExecute, nextKeyOnThresholdBreach);\n }\n}\n"} {"task_id": "Java_2684", "language": "Java", "task_type": "single_line", "source_file": "java/github/elastic/elasticsearch/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/ClusterStateWaitUntilThresholdStep.java", "mask_start_position": 6411, "mask_end_position": 6471, "canonical_solution": "(super.hashCode(), stepToExecute, nextKeyOnThresholdBreach);", "pre_mask_code": "package org.elasticsearch.xpack.core.ilm;\n\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.elasticsearch.cluster.ClusterState;\nimport org.elasticsearch.cluster.metadata.IndexMetadata;\nimport org.elasticsearch.core.Nullable;\nimport org.elasticsearch.common.Strings;\nimport org.elasticsearch.core.TimeValue;\nimport org.elasticsearch.index.Index;\nimport org.elasticsearch.xpack.core.ilm.step.info.SingleMessageFieldInfo;\nimport java.time.Clock;\nimport java.util.Locale;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport static org.elasticsearch.xpack.core.ilm.LifecycleExecutionState.fromIndexMetadata;\n\n/**\n * This step wraps an {@link ClusterStateWaitStep} in order to be able to manipulate what the next step will be, depending on the result of\n * the wrapped {@link ClusterStateWaitStep}.\n *

\n * If the action response is complete, the {@link ClusterStateWaitUntilThresholdStep}'s nextStepKey will be the nextStepKey of the\n * wrapped action. When the threshold level is surpassed, if the underlying step's condition was not met, the nextStepKey will be changed to\n * the provided {@link #nextKeyOnThresholdBreach} and this step will stop waiting.\n *\n * Failures encountered whilst executing the wrapped action will be propagated directly.\n */\npublic class ClusterStateWaitUntilThresholdStep extends ClusterStateWaitStep {\n\n private static final Logger logger = LogManager.getLogger(ClusterStateWaitUntilThresholdStep.class);\n\n private final ClusterStateWaitStep stepToExecute;\n\n private final StepKey nextKeyOnThresholdBreach;\n\n private final AtomicBoolean thresholdPassed = new AtomicBoolean(false);\n\n public ClusterStateWaitUntilThresholdStep(ClusterStateWaitStep stepToExecute, StepKey nextKeyOnThresholdBreach) {\n super(stepToExecute.getKey(), stepToExecute.getNextStepKey());\n this.stepToExecute = stepToExecute;\n this.nextKeyOnThresholdBreach = nextKeyOnThresholdBreach;\n }\n\n @Override\n public boolean isRetryable() {\n return true;\n }\n\n @Override\n public Result isConditionMet(Index index, ClusterState clusterState) {\n IndexMetadata idxMeta = clusterState.metadata().index(index);\n if (idxMeta == null) {\n // Index must have been since deleted, ignore it\n logger.debug(\"[{}] lifecycle action for index [{}] executed but index no longer exists\", getKey().getAction(), index.getName());\n return new Result(false, null);\n }\n Result stepResult = stepToExecute.isConditionMet(index, clusterState);\n if (stepResult.isComplete() == false) {\n // checking the threshold after we execute the step to make sure we execute the wrapped step at least once (because time is a\n // wonderful thing)\n TimeValue retryThreshold = LifecycleSettings.LIFECYCLE_STEP_WAIT_TIME_THRESHOLD_SETTING.get(idxMeta.getSettings());\n LifecycleExecutionState lifecycleState = fromIndexMetadata(idxMeta);\n if (stepToExecute.isCompletable() == false) {\n // we may not have passed the time threshold, but the step is not completable due to a different reason\n thresholdPassed.set(true);\n String message = String.format(Locale.ROOT, \"[%s] lifecycle step, as part of [%s] action, for index [%s] Is not \" + \"completable, reason: [%s]. Abandoning execution and moving to the next fallback step [%s]\", getKey().getName(), getKey().getAction(), idxMeta.getIndex().getName(), Strings.toString(stepResult.getInfomationContext()), nextKeyOnThresholdBreach);\n logger.debug(message);\n return new Result(true, new SingleMessageFieldInfo(message));\n }\n if (waitedMoreThanThresholdLevel(retryThreshold, lifecycleState, Clock.systemUTC())) {\n // we retried this step enough, next step will be the configured to {@code nextKeyOnThresholdBreach}\n thresholdPassed.set(true);\n String message = String.format(Locale.ROOT, \"[%s] lifecycle step, as part of [%s] action, for index [%s] executed for\" + \" more than [%s]. Abandoning execution and moving to the next fallback step [%s]\", getKey().getName(), getKey().getAction(), idxMeta.getIndex().getName(), retryThreshold, nextKeyOnThresholdBreach);\n logger.debug(message);\n return new Result(true, new SingleMessageFieldInfo(message));\n }\n }\n return stepResult;\n }\n\n static boolean waitedMoreThanThresholdLevel(@Nullable TimeValue retryThreshold, LifecycleExecutionState lifecycleState, Clock clock) {\n assert lifecycleState.getStepTime() != null : \"lifecycle state [\" + lifecycleState + \"] does not have the step time set\";\n if (retryThreshold != null) {\n // return true if the threshold was surpassed and false otherwise\n return (lifecycleState.getStepTime() + retryThreshold.millis()) < clock.millis();\n }\n return false;\n }\n\n @Override\n public StepKey getNextStepKey() {\n if (thresholdPassed.get()) {\n return nextKeyOnThresholdBreach;\n } else {\n return super.getNextStepKey();\n }\n }\n\n /**\n * Represents the {@link ClusterStateWaitStep} that's wrapped by this branching step.\n */\n ClusterStateWaitStep getStepToExecute() {\n return stepToExecute;\n }\n\n /**\n * The step key to be reported as the {@link ClusterStateWaitUntilThresholdStep#getNextStepKey()} if the index configured a max wait\n * time using {@link LifecycleSettings#LIFECYCLE_STEP_WAIT_TIME_THRESHOLD_SETTING} and the threshold was passed.\n */\n StepKey getNextKeyOnThreshold() {\n return nextKeyOnThresholdBreach;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (super.equals(o) == false) {\n return false;\n }\n ClusterStateWaitUntilThresholdStep that = (ClusterStateWaitUntilThresholdStep) o;\n return super.equals(o) && Objects.equals(stepToExecute, that.stepToExecute) && Objects.equals(nextKeyOnThresholdBreach, that.nextKeyOnThresholdBreach);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2685", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/elastic/elasticsearch/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/ClusterStateWaitUntilThresholdStep.java", "mask_start_position": 5371, "mask_end_position": 5448, "canonical_solution": "ClusterStateWaitStep getStepToExecute() {\n return stepToExecute;\n }", "pre_mask_code": "package org.elasticsearch.xpack.core.ilm;\n\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.elasticsearch.cluster.ClusterState;\nimport org.elasticsearch.cluster.metadata.IndexMetadata;\nimport org.elasticsearch.core.Nullable;\nimport org.elasticsearch.common.Strings;\nimport org.elasticsearch.core.TimeValue;\nimport org.elasticsearch.index.Index;\nimport org.elasticsearch.xpack.core.ilm.step.info.SingleMessageFieldInfo;\nimport java.time.Clock;\nimport java.util.Locale;\nimport java.util.Objects;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport static org.elasticsearch.xpack.core.ilm.LifecycleExecutionState.fromIndexMetadata;\n\n/**\n * This step wraps an {@link ClusterStateWaitStep} in order to be able to manipulate what the next step will be, depending on the result of\n * the wrapped {@link ClusterStateWaitStep}.\n *

\n * If the action response is complete, the {@link ClusterStateWaitUntilThresholdStep}'s nextStepKey will be the nextStepKey of the\n * wrapped action. When the threshold level is surpassed, if the underlying step's condition was not met, the nextStepKey will be changed to\n * the provided {@link #nextKeyOnThresholdBreach} and this step will stop waiting.\n *\n * Failures encountered whilst executing the wrapped action will be propagated directly.\n */\npublic class ClusterStateWaitUntilThresholdStep extends ClusterStateWaitStep {\n\n private static final Logger logger = LogManager.getLogger(ClusterStateWaitUntilThresholdStep.class);\n\n private final ClusterStateWaitStep stepToExecute;\n\n private final StepKey nextKeyOnThresholdBreach;\n\n private final AtomicBoolean thresholdPassed = new AtomicBoolean(false);\n\n public ClusterStateWaitUntilThresholdStep(ClusterStateWaitStep stepToExecute, StepKey nextKeyOnThresholdBreach) {\n super(stepToExecute.getKey(), stepToExecute.getNextStepKey());\n this.stepToExecute = stepToExecute;\n this.nextKeyOnThresholdBreach = nextKeyOnThresholdBreach;\n }\n\n @Override\n public boolean isRetryable() {\n return true;\n }\n\n @Override\n public Result isConditionMet(Index index, ClusterState clusterState) {\n IndexMetadata idxMeta = clusterState.metadata().index(index);\n if (idxMeta == null) {\n // Index must have been since deleted, ignore it\n logger.debug(\"[{}] lifecycle action for index [{}] executed but index no longer exists\", getKey().getAction(), index.getName());\n return new Result(false, null);\n }\n Result stepResult = stepToExecute.isConditionMet(index, clusterState);\n if (stepResult.isComplete() == false) {\n // checking the threshold after we execute the step to make sure we execute the wrapped step at least once (because time is a\n // wonderful thing)\n TimeValue retryThreshold = LifecycleSettings.LIFECYCLE_STEP_WAIT_TIME_THRESHOLD_SETTING.get(idxMeta.getSettings());\n LifecycleExecutionState lifecycleState = fromIndexMetadata(idxMeta);\n if (stepToExecute.isCompletable() == false) {\n // we may not have passed the time threshold, but the step is not completable due to a different reason\n thresholdPassed.set(true);\n String message = String.format(Locale.ROOT, \"[%s] lifecycle step, as part of [%s] action, for index [%s] Is not \" + \"completable, reason: [%s]. Abandoning execution and moving to the next fallback step [%s]\", getKey().getName(), getKey().getAction(), idxMeta.getIndex().getName(), Strings.toString(stepResult.getInfomationContext()), nextKeyOnThresholdBreach);\n logger.debug(message);\n return new Result(true, new SingleMessageFieldInfo(message));\n }\n if (waitedMoreThanThresholdLevel(retryThreshold, lifecycleState, Clock.systemUTC())) {\n // we retried this step enough, next step will be the configured to {@code nextKeyOnThresholdBreach}\n thresholdPassed.set(true);\n String message = String.format(Locale.ROOT, \"[%s] lifecycle step, as part of [%s] action, for index [%s] executed for\" + \" more than [%s]. Abandoning execution and moving to the next fallback step [%s]\", getKey().getName(), getKey().getAction(), idxMeta.getIndex().getName(), retryThreshold, nextKeyOnThresholdBreach);\n logger.debug(message);\n return new Result(true, new SingleMessageFieldInfo(message));\n }\n }\n return stepResult;\n }\n\n static boolean waitedMoreThanThresholdLevel(@Nullable TimeValue retryThreshold, LifecycleExecutionState lifecycleState, Clock clock) {\n assert lifecycleState.getStepTime() != null : \"lifecycle state [\" + lifecycleState + \"] does not have the step time set\";\n if (retryThreshold != null) {\n // return true if the threshold was surpassed and false otherwise\n return (lifecycleState.getStepTime() + retryThreshold.millis()) < clock.millis();\n }\n return false;\n }\n\n @Override\n public StepKey getNextStepKey() {\n if (thresholdPassed.get()) {\n return nextKeyOnThresholdBreach;\n } else {\n return super.getNextStepKey();\n }\n }\n\n /**\n * Represents the {@link ClusterStateWaitStep} that's wrapped by this branching step.\n */\n ", "post_mask_code": "\n\n /**\n * The step key to be reported as the {@link ClusterStateWaitUntilThresholdStep#getNextStepKey()} if the index configured a max wait\n * time using {@link LifecycleSettings#LIFECYCLE_STEP_WAIT_TIME_THRESHOLD_SETTING} and the threshold was passed.\n */\n StepKey getNextKeyOnThreshold() {\n return nextKeyOnThresholdBreach;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (super.equals(o) == false) {\n return false;\n }\n ClusterStateWaitUntilThresholdStep that = (ClusterStateWaitUntilThresholdStep) o;\n return super.equals(o) && Objects.equals(stepToExecute, that.stepToExecute) && Objects.equals(nextKeyOnThresholdBreach, that.nextKeyOnThresholdBreach);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), stepToExecute, nextKeyOnThresholdBreach);\n }\n}\n"} {"task_id": "Java_2686", "language": "Java", "task_type": "method_signature", "source_file": "java/github/allon2/dactor/dactor/src/main/java/cn/ymotel/dactor/async/web/view/DownloadView.java", "mask_start_position": 290, "mask_end_position": 375, "canonical_solution": "@Override\n public void renderInner(ServletMessage message, String defaultMessage) ", "pre_mask_code": "package cn.ymotel.dactor.async.web.view;\n\nimport cn.ymotel.dactor.message.ServletMessage;\nimport java.io.File;\n\npublic class DownloadView extends StreamView {\n\n public static String FILE_NAME = \"_FileName\";\n\n public static String getFILE_NAME() {\n return FILE_NAME;\n }\n\n ", "post_mask_code": "{\n String fileName = \"\";\n if (message.getContext().containsKey(FILE_NAME)) {\n fileName = (String) message.getContext().get(FILE_NAME);\n } else {\n Object obj = message.getContext().get(this.getContent());\n if (obj instanceof File) {\n fileName = ((File) obj).getName();\n }\n }\n message.getResponse().setHeader(\"Content-Disposition\", \"attachment; filename=\" + fileName);\n super.renderInner(message, defaultMessage);\n }\n}\n"} {"task_id": "Java_2687", "language": "Java", "task_type": "method_body", "source_file": "java/github/allon2/dactor/dactor/src/main/java/cn/ymotel/dactor/async/web/view/DownloadView.java", "mask_start_position": 251, "mask_end_position": 284, "canonical_solution": "{\n return FILE_NAME;\n }", "pre_mask_code": "package cn.ymotel.dactor.async.web.view;\n\nimport cn.ymotel.dactor.message.ServletMessage;\nimport java.io.File;\n\npublic class DownloadView extends StreamView {\n\n public static String FILE_NAME = \"_FileName\";\n\n public static String getFILE_NAME() ", "post_mask_code": "\n\n @Override\n public void renderInner(ServletMessage message, String defaultMessage) {\n String fileName = \"\";\n if (message.getContext().containsKey(FILE_NAME)) {\n fileName = (String) message.getContext().get(FILE_NAME);\n } else {\n Object obj = message.getContext().get(this.getContent());\n if (obj instanceof File) {\n fileName = ((File) obj).getName();\n }\n }\n message.getResponse().setHeader(\"Content-Disposition\", \"attachment; filename=\" + fileName);\n super.renderInner(message, defaultMessage);\n }\n}\n"} {"task_id": "Java_2688", "language": "Java", "task_type": "single_line", "source_file": "java/github/allon2/dactor/dactor/src/main/java/cn/ymotel/dactor/async/web/view/DownloadView.java", "mask_start_position": 862, "mask_end_position": 887, "canonical_solution": "message, defaultMessage);", "pre_mask_code": "package cn.ymotel.dactor.async.web.view;\n\nimport cn.ymotel.dactor.message.ServletMessage;\nimport java.io.File;\n\npublic class DownloadView extends StreamView {\n\n public static String FILE_NAME = \"_FileName\";\n\n public static String getFILE_NAME() {\n return FILE_NAME;\n }\n\n @Override\n public void renderInner(ServletMessage message, String defaultMessage) {\n String fileName = \"\";\n if (message.getContext().containsKey(FILE_NAME)) {\n fileName = (String) message.getContext().get(FILE_NAME);\n } else {\n Object obj = message.getContext().get(this.getContent());\n if (obj instanceof File) {\n fileName = ((File) obj).getName();\n }\n }\n message.getResponse().setHeader(\"Content-Disposition\", \"attachment; filename=\" + fileName);\n super.renderInner(", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2689", "language": "Java", "task_type": "method_signature", "source_file": "java/github/kongshanxuelin/ruoyiplus/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java", "mask_start_position": 1018, "mask_end_position": 1082, "canonical_solution": "@Override\n public String selectConfigByKey(String configKey) ", "pre_mask_code": "package com.ruoyi.system.service.impl;\n\nimport java.util.List;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport com.ruoyi.common.constant.UserConstants;\nimport com.ruoyi.common.support.Convert;\nimport com.ruoyi.common.utils.StringUtils;\nimport com.ruoyi.system.domain.SysConfig;\nimport com.ruoyi.system.mapper.SysConfigMapper;\nimport com.ruoyi.system.service.ISysConfigService;\n\n/**\n * 参数配置 服务层实现\n *\n * @author ruoyi\n */\n@Service\npublic class SysConfigServiceImpl implements ISysConfigService {\n\n @Autowired\n private SysConfigMapper configMapper;\n\n /**\n * 查询参数配置信息\n *\n * @param configId 参数配置ID\n * @return 参数配置信息\n */\n @Override\n public SysConfig selectConfigById(Long configId) {\n SysConfig config = new SysConfig();\n config.setConfigId(configId);\n return configMapper.selectConfig(config);\n }\n\n /**\n * 根据键名查询参数配置信息\n *\n * @param configKey 参数key\n * @return 参数键值\n */\n ", "post_mask_code": "{\n SysConfig config = new SysConfig();\n config.setConfigKey(configKey);\n SysConfig retConfig = configMapper.selectConfig(config);\n return StringUtils.isNotNull(retConfig) ? retConfig.getConfigValue() : \"\";\n }\n\n /**\n * 查询参数配置列表\n *\n * @param config 参数配置信息\n * @return 参数配置集合\n */\n @Override\n public List selectConfigList(SysConfig config) {\n return configMapper.selectConfigList(config);\n }\n\n /**\n * 新增参数配置\n *\n * @param config 参数配置信息\n * @return 结果\n */\n @Override\n public int insertConfig(SysConfig config) {\n return configMapper.insertConfig(config);\n }\n\n /**\n * 修改参数配置\n *\n * @param config 参数配置信息\n * @return 结果\n */\n @Override\n public int updateConfig(SysConfig config) {\n return configMapper.updateConfig(config);\n }\n\n /**\n * 批量删除参数配置对象\n *\n * @param ids 需要删除的数据ID\n * @return 结果\n */\n @Override\n public int deleteConfigByIds(String ids) {\n return configMapper.deleteConfigByIds(Convert.toStrArray(ids));\n }\n\n /**\n * 校验参数键名是否唯一\n *\n * @param config 参数配置信息\n * @return 结果\n */\n @Override\n public String checkConfigKeyUnique(SysConfig config) {\n Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();\n SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey());\n if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) {\n return UserConstants.CONFIG_KEY_NOT_UNIQUE;\n }\n return UserConstants.CONFIG_KEY_UNIQUE;\n }\n}\n"} {"task_id": "Java_2690", "language": "Java", "task_type": "method_body", "source_file": "java/github/kongshanxuelin/ruoyiplus/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java", "mask_start_position": 780, "mask_end_position": 919, "canonical_solution": "{\n SysConfig config = new SysConfig();\n config.setConfigId(configId);\n return configMapper.selectConfig(config);\n }", "pre_mask_code": "package com.ruoyi.system.service.impl;\n\nimport java.util.List;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport com.ruoyi.common.constant.UserConstants;\nimport com.ruoyi.common.support.Convert;\nimport com.ruoyi.common.utils.StringUtils;\nimport com.ruoyi.system.domain.SysConfig;\nimport com.ruoyi.system.mapper.SysConfigMapper;\nimport com.ruoyi.system.service.ISysConfigService;\n\n/**\n * 参数配置 服务层实现\n *\n * @author ruoyi\n */\n@Service\npublic class SysConfigServiceImpl implements ISysConfigService {\n\n @Autowired\n private SysConfigMapper configMapper;\n\n /**\n * 查询参数配置信息\n *\n * @param configId 参数配置ID\n * @return 参数配置信息\n */\n @Override\n public SysConfig selectConfigById(Long configId) ", "post_mask_code": "\n\n /**\n * 根据键名查询参数配置信息\n *\n * @param configKey 参数key\n * @return 参数键值\n */\n @Override\n public String selectConfigByKey(String configKey) {\n SysConfig config = new SysConfig();\n config.setConfigKey(configKey);\n SysConfig retConfig = configMapper.selectConfig(config);\n return StringUtils.isNotNull(retConfig) ? retConfig.getConfigValue() : \"\";\n }\n\n /**\n * 查询参数配置列表\n *\n * @param config 参数配置信息\n * @return 参数配置集合\n */\n @Override\n public List selectConfigList(SysConfig config) {\n return configMapper.selectConfigList(config);\n }\n\n /**\n * 新增参数配置\n *\n * @param config 参数配置信息\n * @return 结果\n */\n @Override\n public int insertConfig(SysConfig config) {\n return configMapper.insertConfig(config);\n }\n\n /**\n * 修改参数配置\n *\n * @param config 参数配置信息\n * @return 结果\n */\n @Override\n public int updateConfig(SysConfig config) {\n return configMapper.updateConfig(config);\n }\n\n /**\n * 批量删除参数配置对象\n *\n * @param ids 需要删除的数据ID\n * @return 结果\n */\n @Override\n public int deleteConfigByIds(String ids) {\n return configMapper.deleteConfigByIds(Convert.toStrArray(ids));\n }\n\n /**\n * 校验参数键名是否唯一\n *\n * @param config 参数配置信息\n * @return 结果\n */\n @Override\n public String checkConfigKeyUnique(SysConfig config) {\n Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();\n SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey());\n if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) {\n return UserConstants.CONFIG_KEY_NOT_UNIQUE;\n }\n return UserConstants.CONFIG_KEY_UNIQUE;\n }\n}\n"} {"task_id": "Java_2691", "language": "Java", "task_type": "single_line", "source_file": "java/github/kongshanxuelin/ruoyiplus/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java", "mask_start_position": 2732, "mask_end_position": 2734, "canonical_solution": "E;", "pre_mask_code": "package com.ruoyi.system.service.impl;\n\nimport java.util.List;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport com.ruoyi.common.constant.UserConstants;\nimport com.ruoyi.common.support.Convert;\nimport com.ruoyi.common.utils.StringUtils;\nimport com.ruoyi.system.domain.SysConfig;\nimport com.ruoyi.system.mapper.SysConfigMapper;\nimport com.ruoyi.system.service.ISysConfigService;\n\n/**\n * 参数配置 服务层实现\n *\n * @author ruoyi\n */\n@Service\npublic class SysConfigServiceImpl implements ISysConfigService {\n\n @Autowired\n private SysConfigMapper configMapper;\n\n /**\n * 查询参数配置信息\n *\n * @param configId 参数配置ID\n * @return 参数配置信息\n */\n @Override\n public SysConfig selectConfigById(Long configId) {\n SysConfig config = new SysConfig();\n config.setConfigId(configId);\n return configMapper.selectConfig(config);\n }\n\n /**\n * 根据键名查询参数配置信息\n *\n * @param configKey 参数key\n * @return 参数键值\n */\n @Override\n public String selectConfigByKey(String configKey) {\n SysConfig config = new SysConfig();\n config.setConfigKey(configKey);\n SysConfig retConfig = configMapper.selectConfig(config);\n return StringUtils.isNotNull(retConfig) ? retConfig.getConfigValue() : \"\";\n }\n\n /**\n * 查询参数配置列表\n *\n * @param config 参数配置信息\n * @return 参数配置集合\n */\n @Override\n public List selectConfigList(SysConfig config) {\n return configMapper.selectConfigList(config);\n }\n\n /**\n * 新增参数配置\n *\n * @param config 参数配置信息\n * @return 结果\n */\n @Override\n public int insertConfig(SysConfig config) {\n return configMapper.insertConfig(config);\n }\n\n /**\n * 修改参数配置\n *\n * @param config 参数配置信息\n * @return 结果\n */\n @Override\n public int updateConfig(SysConfig config) {\n return configMapper.updateConfig(config);\n }\n\n /**\n * 批量删除参数配置对象\n *\n * @param ids 需要删除的数据ID\n * @return 结果\n */\n @Override\n public int deleteConfigByIds(String ids) {\n return configMapper.deleteConfigByIds(Convert.toStrArray(ids));\n }\n\n /**\n * 校验参数键名是否唯一\n *\n * @param config 参数配置信息\n * @return 结果\n */\n @Override\n public String checkConfigKeyUnique(SysConfig config) {\n Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();\n SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey());\n if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) {\n return UserConstants.CONFIG_KEY_NOT_UNIQUE;\n }\n return UserConstants.CONFIG_KEY_UNIQU", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2692", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/kongshanxuelin/ruoyiplus/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java", "mask_start_position": 2046, "mask_end_position": 2180, "canonical_solution": "@Override\n public int deleteConfigByIds(String ids) {\n return configMapper.deleteConfigByIds(Convert.toStrArray(ids));\n }", "pre_mask_code": "package com.ruoyi.system.service.impl;\n\nimport java.util.List;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport com.ruoyi.common.constant.UserConstants;\nimport com.ruoyi.common.support.Convert;\nimport com.ruoyi.common.utils.StringUtils;\nimport com.ruoyi.system.domain.SysConfig;\nimport com.ruoyi.system.mapper.SysConfigMapper;\nimport com.ruoyi.system.service.ISysConfigService;\n\n/**\n * 参数配置 服务层实现\n *\n * @author ruoyi\n */\n@Service\npublic class SysConfigServiceImpl implements ISysConfigService {\n\n @Autowired\n private SysConfigMapper configMapper;\n\n /**\n * 查询参数配置信息\n *\n * @param configId 参数配置ID\n * @return 参数配置信息\n */\n @Override\n public SysConfig selectConfigById(Long configId) {\n SysConfig config = new SysConfig();\n config.setConfigId(configId);\n return configMapper.selectConfig(config);\n }\n\n /**\n * 根据键名查询参数配置信息\n *\n * @param configKey 参数key\n * @return 参数键值\n */\n @Override\n public String selectConfigByKey(String configKey) {\n SysConfig config = new SysConfig();\n config.setConfigKey(configKey);\n SysConfig retConfig = configMapper.selectConfig(config);\n return StringUtils.isNotNull(retConfig) ? retConfig.getConfigValue() : \"\";\n }\n\n /**\n * 查询参数配置列表\n *\n * @param config 参数配置信息\n * @return 参数配置集合\n */\n @Override\n public List selectConfigList(SysConfig config) {\n return configMapper.selectConfigList(config);\n }\n\n /**\n * 新增参数配置\n *\n * @param config 参数配置信息\n * @return 结果\n */\n @Override\n public int insertConfig(SysConfig config) {\n return configMapper.insertConfig(config);\n }\n\n /**\n * 修改参数配置\n *\n * @param config 参数配置信息\n * @return 结果\n */\n @Override\n public int updateConfig(SysConfig config) {\n return configMapper.updateConfig(config);\n }\n\n /**\n * 批量删除参数配置对象\n *\n * @param ids 需要删除的数据ID\n * @return 结果\n */\n ", "post_mask_code": "\n\n /**\n * 校验参数键名是否唯一\n *\n * @param config 参数配置信息\n * @return 结果\n */\n @Override\n public String checkConfigKeyUnique(SysConfig config) {\n Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();\n SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey());\n if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) {\n return UserConstants.CONFIG_KEY_NOT_UNIQUE;\n }\n return UserConstants.CONFIG_KEY_UNIQUE;\n }\n}\n"} {"task_id": "Java_2693", "language": "Java", "task_type": "method_signature", "source_file": "java/github/lealone/Lealone/lealone-sql/src/main/java/org/lealone/sql/expression/subquery/SubQuery.java", "mask_start_position": 1824, "mask_end_position": 1888, "canonical_solution": "@Override\n public Expression optimize(ServerSession session) ", "pre_mask_code": "/*\n * Initial Developer: H2 Group\n */\npackage org.lealone.sql.expression.subquery;\n\nimport java.util.ArrayList;\nimport org.lealone.common.exceptions.DbException;\nimport org.lealone.db.api.ErrorCode;\nimport org.lealone.db.result.Result;\nimport org.lealone.db.session.ServerSession;\nimport org.lealone.db.value.Value;\nimport org.lealone.db.value.ValueArray;\nimport org.lealone.db.value.ValueNull;\nimport org.lealone.sql.expression.Expression;\nimport org.lealone.sql.expression.ExpressionList;\nimport org.lealone.sql.expression.visitor.ExpressionVisitor;\nimport org.lealone.sql.query.Query;\n\n/**\n * A query returning a single value.\n * Subqueries are used inside other statements.\n *\n * @author H2 Group\n * @author zhh\n */\npublic class SubQuery extends Expression {\n\n private final Query query;\n\n private Expression expression;\n\n public SubQuery(Query query) {\n this.query = query;\n }\n\n @Override\n public Value getValue(ServerSession session) {\n query.setSession(session);\n Result result = query.query(2);\n try {\n int rowcount = result.getRowCount();\n if (rowcount > 1) {\n throw DbException.get(ErrorCode.SCALAR_SUBQUERY_CONTAINS_MORE_THAN_ONE_ROW);\n }\n Value v;\n if (rowcount <= 0) {\n v = ValueNull.INSTANCE;\n } else {\n result.next();\n Value[] values = result.currentRow();\n if (result.getVisibleColumnCount() == 1) {\n v = values[0];\n } else {\n v = ValueArray.get(values);\n }\n }\n return v;\n } finally {\n result.close();\n }\n }\n\n @Override\n public int getType() {\n return getExpression().getType();\n }\n\n ", "post_mask_code": "{\n query.prepare();\n return this;\n }\n\n @Override\n public int getScale() {\n return getExpression().getScale();\n }\n\n @Override\n public long getPrecision() {\n return getExpression().getPrecision();\n }\n\n @Override\n public int getDisplaySize() {\n return getExpression().getDisplaySize();\n }\n\n @Override\n public String getSQL(boolean isDistributed) {\n return \"(\" + query.getPlanSQL() + \")\";\n }\n\n private Expression getExpression() {\n if (expression == null) {\n ArrayList expressions = query.getExpressions();\n int columnCount = query.getColumnCount();\n if (columnCount == 1) {\n expression = expressions.get(0);\n } else {\n Expression[] list = new Expression[columnCount];\n for (int i = 0; i < columnCount; i++) {\n list[i] = expressions.get(i);\n }\n expression = new ExpressionList(list);\n }\n }\n return expression;\n }\n\n public Query getQuery() {\n return query;\n }\n\n @Override\n public int getCost() {\n return query.getCostAsExpression();\n }\n\n @Override\n public Expression[] getExpressionColumns(ServerSession session) {\n return getExpression().getExpressionColumns(session);\n }\n\n @Override\n public R accept(ExpressionVisitor visitor) {\n return visitor.visitSubQuery(this);\n }\n}\n"} {"task_id": "Java_2694", "language": "Java", "task_type": "method_body", "source_file": "java/github/lealone/Lealone/lealone-sql/src/main/java/org/lealone/sql/expression/subquery/SubQuery.java", "mask_start_position": 2302, "mask_end_position": 2356, "canonical_solution": "{\n return \"(\" + query.getPlanSQL() + \")\";\n }", "pre_mask_code": "/*\n * Initial Developer: H2 Group\n */\npackage org.lealone.sql.expression.subquery;\n\nimport java.util.ArrayList;\nimport org.lealone.common.exceptions.DbException;\nimport org.lealone.db.api.ErrorCode;\nimport org.lealone.db.result.Result;\nimport org.lealone.db.session.ServerSession;\nimport org.lealone.db.value.Value;\nimport org.lealone.db.value.ValueArray;\nimport org.lealone.db.value.ValueNull;\nimport org.lealone.sql.expression.Expression;\nimport org.lealone.sql.expression.ExpressionList;\nimport org.lealone.sql.expression.visitor.ExpressionVisitor;\nimport org.lealone.sql.query.Query;\n\n/**\n * A query returning a single value.\n * Subqueries are used inside other statements.\n *\n * @author H2 Group\n * @author zhh\n */\npublic class SubQuery extends Expression {\n\n private final Query query;\n\n private Expression expression;\n\n public SubQuery(Query query) {\n this.query = query;\n }\n\n @Override\n public Value getValue(ServerSession session) {\n query.setSession(session);\n Result result = query.query(2);\n try {\n int rowcount = result.getRowCount();\n if (rowcount > 1) {\n throw DbException.get(ErrorCode.SCALAR_SUBQUERY_CONTAINS_MORE_THAN_ONE_ROW);\n }\n Value v;\n if (rowcount <= 0) {\n v = ValueNull.INSTANCE;\n } else {\n result.next();\n Value[] values = result.currentRow();\n if (result.getVisibleColumnCount() == 1) {\n v = values[0];\n } else {\n v = ValueArray.get(values);\n }\n }\n return v;\n } finally {\n result.close();\n }\n }\n\n @Override\n public int getType() {\n return getExpression().getType();\n }\n\n @Override\n public Expression optimize(ServerSession session) {\n query.prepare();\n return this;\n }\n\n @Override\n public int getScale() {\n return getExpression().getScale();\n }\n\n @Override\n public long getPrecision() {\n return getExpression().getPrecision();\n }\n\n @Override\n public int getDisplaySize() {\n return getExpression().getDisplaySize();\n }\n\n @Override\n public String getSQL(boolean isDistributed) ", "post_mask_code": "\n\n private Expression getExpression() {\n if (expression == null) {\n ArrayList expressions = query.getExpressions();\n int columnCount = query.getColumnCount();\n if (columnCount == 1) {\n expression = expressions.get(0);\n } else {\n Expression[] list = new Expression[columnCount];\n for (int i = 0; i < columnCount; i++) {\n list[i] = expressions.get(i);\n }\n expression = new ExpressionList(list);\n }\n }\n return expression;\n }\n\n public Query getQuery() {\n return query;\n }\n\n @Override\n public int getCost() {\n return query.getCostAsExpression();\n }\n\n @Override\n public Expression[] getExpressionColumns(ServerSession session) {\n return getExpression().getExpressionColumns(session);\n }\n\n @Override\n public R accept(ExpressionVisitor visitor) {\n return visitor.visitSubQuery(this);\n }\n}\n"} {"task_id": "Java_2695", "language": "Java", "task_type": "single_line", "source_file": "java/github/lealone/Lealone/lealone-sql/src/main/java/org/lealone/sql/expression/subquery/SubQuery.java", "mask_start_position": 1784, "mask_end_position": 1812, "canonical_solution": "n getExpression().getType();", "pre_mask_code": "/*\n * Initial Developer: H2 Group\n */\npackage org.lealone.sql.expression.subquery;\n\nimport java.util.ArrayList;\nimport org.lealone.common.exceptions.DbException;\nimport org.lealone.db.api.ErrorCode;\nimport org.lealone.db.result.Result;\nimport org.lealone.db.session.ServerSession;\nimport org.lealone.db.value.Value;\nimport org.lealone.db.value.ValueArray;\nimport org.lealone.db.value.ValueNull;\nimport org.lealone.sql.expression.Expression;\nimport org.lealone.sql.expression.ExpressionList;\nimport org.lealone.sql.expression.visitor.ExpressionVisitor;\nimport org.lealone.sql.query.Query;\n\n/**\n * A query returning a single value.\n * Subqueries are used inside other statements.\n *\n * @author H2 Group\n * @author zhh\n */\npublic class SubQuery extends Expression {\n\n private final Query query;\n\n private Expression expression;\n\n public SubQuery(Query query) {\n this.query = query;\n }\n\n @Override\n public Value getValue(ServerSession session) {\n query.setSession(session);\n Result result = query.query(2);\n try {\n int rowcount = result.getRowCount();\n if (rowcount > 1) {\n throw DbException.get(ErrorCode.SCALAR_SUBQUERY_CONTAINS_MORE_THAN_ONE_ROW);\n }\n Value v;\n if (rowcount <= 0) {\n v = ValueNull.INSTANCE;\n } else {\n result.next();\n Value[] values = result.currentRow();\n if (result.getVisibleColumnCount() == 1) {\n v = values[0];\n } else {\n v = ValueArray.get(values);\n }\n }\n return v;\n } finally {\n result.close();\n }\n }\n\n @Override\n public int getType() {\n retur", "post_mask_code": "\n }\n\n @Override\n public Expression optimize(ServerSession session) {\n query.prepare();\n return this;\n }\n\n @Override\n public int getScale() {\n return getExpression().getScale();\n }\n\n @Override\n public long getPrecision() {\n return getExpression().getPrecision();\n }\n\n @Override\n public int getDisplaySize() {\n return getExpression().getDisplaySize();\n }\n\n @Override\n public String getSQL(boolean isDistributed) {\n return \"(\" + query.getPlanSQL() + \")\";\n }\n\n private Expression getExpression() {\n if (expression == null) {\n ArrayList expressions = query.getExpressions();\n int columnCount = query.getColumnCount();\n if (columnCount == 1) {\n expression = expressions.get(0);\n } else {\n Expression[] list = new Expression[columnCount];\n for (int i = 0; i < columnCount; i++) {\n list[i] = expressions.get(i);\n }\n expression = new ExpressionList(list);\n }\n }\n return expression;\n }\n\n public Query getQuery() {\n return query;\n }\n\n @Override\n public int getCost() {\n return query.getCostAsExpression();\n }\n\n @Override\n public Expression[] getExpressionColumns(ServerSession session) {\n return getExpression().getExpressionColumns(session);\n }\n\n @Override\n public R accept(ExpressionVisitor visitor) {\n return visitor.visitSubQuery(this);\n }\n}\n"} {"task_id": "Java_2696", "language": "Java", "task_type": "for_statement", "source_file": "java/github/lealone/Lealone/lealone-sql/src/main/java/org/lealone/sql/expression/subquery/SubQuery.java", "mask_start_position": 2746, "mask_end_position": 2853, "canonical_solution": "for (int i = 0; i < columnCount; i++) {\n list[i] = expressions.get(i);\n }", "pre_mask_code": "/*\n * Initial Developer: H2 Group\n */\npackage org.lealone.sql.expression.subquery;\n\nimport java.util.ArrayList;\nimport org.lealone.common.exceptions.DbException;\nimport org.lealone.db.api.ErrorCode;\nimport org.lealone.db.result.Result;\nimport org.lealone.db.session.ServerSession;\nimport org.lealone.db.value.Value;\nimport org.lealone.db.value.ValueArray;\nimport org.lealone.db.value.ValueNull;\nimport org.lealone.sql.expression.Expression;\nimport org.lealone.sql.expression.ExpressionList;\nimport org.lealone.sql.expression.visitor.ExpressionVisitor;\nimport org.lealone.sql.query.Query;\n\n/**\n * A query returning a single value.\n * Subqueries are used inside other statements.\n *\n * @author H2 Group\n * @author zhh\n */\npublic class SubQuery extends Expression {\n\n private final Query query;\n\n private Expression expression;\n\n public SubQuery(Query query) {\n this.query = query;\n }\n\n @Override\n public Value getValue(ServerSession session) {\n query.setSession(session);\n Result result = query.query(2);\n try {\n int rowcount = result.getRowCount();\n if (rowcount > 1) {\n throw DbException.get(ErrorCode.SCALAR_SUBQUERY_CONTAINS_MORE_THAN_ONE_ROW);\n }\n Value v;\n if (rowcount <= 0) {\n v = ValueNull.INSTANCE;\n } else {\n result.next();\n Value[] values = result.currentRow();\n if (result.getVisibleColumnCount() == 1) {\n v = values[0];\n } else {\n v = ValueArray.get(values);\n }\n }\n return v;\n } finally {\n result.close();\n }\n }\n\n @Override\n public int getType() {\n return getExpression().getType();\n }\n\n @Override\n public Expression optimize(ServerSession session) {\n query.prepare();\n return this;\n }\n\n @Override\n public int getScale() {\n return getExpression().getScale();\n }\n\n @Override\n public long getPrecision() {\n return getExpression().getPrecision();\n }\n\n @Override\n public int getDisplaySize() {\n return getExpression().getDisplaySize();\n }\n\n @Override\n public String getSQL(boolean isDistributed) {\n return \"(\" + query.getPlanSQL() + \")\";\n }\n\n private Expression getExpression() {\n if (expression == null) {\n ArrayList expressions = query.getExpressions();\n int columnCount = query.getColumnCount();\n if (columnCount == 1) {\n expression = expressions.get(0);\n } else {\n Expression[] list = new Expression[columnCount];\n ", "post_mask_code": "\n expression = new ExpressionList(list);\n }\n }\n return expression;\n }\n\n public Query getQuery() {\n return query;\n }\n\n @Override\n public int getCost() {\n return query.getCostAsExpression();\n }\n\n @Override\n public Expression[] getExpressionColumns(ServerSession session) {\n return getExpression().getExpressionColumns(session);\n }\n\n @Override\n public R accept(ExpressionVisitor visitor) {\n return visitor.visitSubQuery(this);\n }\n}\n"} {"task_id": "Java_2697", "language": "Java", "task_type": "method_signature", "source_file": "java/github/aliyun/aliyun-openapi-java-sdk/aliyun-java-sdk-hbr/src/main/java/com/aliyuncs/hbr/model/v20170908/UpdateVmClientFlowControlPolicyResponse.java", "mask_start_position": 699, "mask_end_position": 739, "canonical_solution": "public void setSuccess(Boolean success) ", "pre_mask_code": "package com.aliyuncs.hbr.model.v20170908;\n\nimport com.aliyuncs.AcsResponse;\nimport com.aliyuncs.hbr.transform.v20170908.UpdateVmClientFlowControlPolicyResponseUnmarshaller;\nimport com.aliyuncs.transform.UnmarshallerContext;\n\n/**\n * @author auto create\n * @version\n */\npublic class UpdateVmClientFlowControlPolicyResponse extends AcsResponse {\n\n private String requestId;\n\n private Boolean success;\n\n private String code;\n\n private String message;\n\n public String getRequestId() {\n return this.requestId;\n }\n\n public void setRequestId(String requestId) {\n this.requestId = requestId;\n }\n\n public Boolean getSuccess() {\n return this.success;\n }\n\n ", "post_mask_code": "{\n this.success = success;\n }\n\n public String getCode() {\n return this.code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getMessage() {\n return this.message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n @Override\n public UpdateVmClientFlowControlPolicyResponse getInstance(UnmarshallerContext context) {\n return UpdateVmClientFlowControlPolicyResponseUnmarshaller.unmarshall(this, context);\n }\n\n @Override\n public boolean checkShowJsonItemName() {\n return false;\n }\n}\n"} {"task_id": "Java_2698", "language": "Java", "task_type": "method_body", "source_file": "java/github/aliyun/aliyun-openapi-java-sdk/aliyun-java-sdk-hbr/src/main/java/com/aliyuncs/hbr/model/v20170908/UpdateVmClientFlowControlPolicyResponse.java", "mask_start_position": 880, "mask_end_position": 913, "canonical_solution": "{\n this.code = code;\n }", "pre_mask_code": "package com.aliyuncs.hbr.model.v20170908;\n\nimport com.aliyuncs.AcsResponse;\nimport com.aliyuncs.hbr.transform.v20170908.UpdateVmClientFlowControlPolicyResponseUnmarshaller;\nimport com.aliyuncs.transform.UnmarshallerContext;\n\n/**\n * @author auto create\n * @version\n */\npublic class UpdateVmClientFlowControlPolicyResponse extends AcsResponse {\n\n private String requestId;\n\n private Boolean success;\n\n private String code;\n\n private String message;\n\n public String getRequestId() {\n return this.requestId;\n }\n\n public void setRequestId(String requestId) {\n this.requestId = requestId;\n }\n\n public Boolean getSuccess() {\n return this.success;\n }\n\n public void setSuccess(Boolean success) {\n this.success = success;\n }\n\n public String getCode() {\n return this.code;\n }\n\n public void setCode(String code) ", "post_mask_code": "\n\n public String getMessage() {\n return this.message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n @Override\n public UpdateVmClientFlowControlPolicyResponse getInstance(UnmarshallerContext context) {\n return UpdateVmClientFlowControlPolicyResponseUnmarshaller.unmarshall(this, context);\n }\n\n @Override\n public boolean checkShowJsonItemName() {\n return false;\n }\n}\n"} {"task_id": "Java_2699", "language": "Java", "task_type": "single_line", "source_file": "java/github/aliyun/aliyun-openapi-java-sdk/aliyun-java-sdk-hbr/src/main/java/com/aliyuncs/hbr/model/v20170908/UpdateVmClientFlowControlPolicyResponse.java", "mask_start_position": 825, "mask_end_position": 835, "canonical_solution": "this.code;", "pre_mask_code": "package com.aliyuncs.hbr.model.v20170908;\n\nimport com.aliyuncs.AcsResponse;\nimport com.aliyuncs.hbr.transform.v20170908.UpdateVmClientFlowControlPolicyResponseUnmarshaller;\nimport com.aliyuncs.transform.UnmarshallerContext;\n\n/**\n * @author auto create\n * @version\n */\npublic class UpdateVmClientFlowControlPolicyResponse extends AcsResponse {\n\n private String requestId;\n\n private Boolean success;\n\n private String code;\n\n private String message;\n\n public String getRequestId() {\n return this.requestId;\n }\n\n public void setRequestId(String requestId) {\n this.requestId = requestId;\n }\n\n public Boolean getSuccess() {\n return this.success;\n }\n\n public void setSuccess(Boolean success) {\n this.success = success;\n }\n\n public String getCode() {\n return ", "post_mask_code": "\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getMessage() {\n return this.message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n @Override\n public UpdateVmClientFlowControlPolicyResponse getInstance(UnmarshallerContext context) {\n return UpdateVmClientFlowControlPolicyResponseUnmarshaller.unmarshall(this, context);\n }\n\n @Override\n public boolean checkShowJsonItemName() {\n return false;\n }\n}\n"} {"task_id": "Java_2700", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCacheDestroyRequest.java", "mask_start_position": 727, "mask_end_position": 800, "canonical_solution": "@Override\n public ClientResponse process(ClientConnectionContext ctx) ", "pre_mask_code": "package org.apache.ignite.internal.processors.platform.client.cache;\n\nimport org.apache.ignite.binary.BinaryRawReader;\nimport org.apache.ignite.internal.processors.platform.client.ClientConnectionContext;\nimport org.apache.ignite.internal.processors.platform.client.ClientRequest;\nimport org.apache.ignite.internal.processors.platform.client.ClientResponse;\n\n/**\n * Cache destroy request.\n */\npublic class ClientCacheDestroyRequest extends ClientRequest {\n\n /**\n * Cache ID.\n */\n private final int cacheId;\n\n /**\n * Constructor.\n *\n * @param reader Reader.\n */\n public ClientCacheDestroyRequest(BinaryRawReader reader) {\n super(reader);\n cacheId = reader.readInt();\n }\n\n ", "post_mask_code": "{\n String cacheName = ClientCacheRequest.cacheDescriptor(ctx, cacheId).cacheName();\n ctx.kernalContext().grid().destroyCache(cacheName);\n return super.process(ctx);\n }\n}\n"} {"task_id": "Java_2701", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCacheDestroyRequest.java", "mask_start_position": 800, "mask_end_position": 991, "canonical_solution": "{\n String cacheName = ClientCacheRequest.cacheDescriptor(ctx, cacheId).cacheName();\n ctx.kernalContext().grid().destroyCache(cacheName);\n return super.process(ctx);\n }", "pre_mask_code": "package org.apache.ignite.internal.processors.platform.client.cache;\n\nimport org.apache.ignite.binary.BinaryRawReader;\nimport org.apache.ignite.internal.processors.platform.client.ClientConnectionContext;\nimport org.apache.ignite.internal.processors.platform.client.ClientRequest;\nimport org.apache.ignite.internal.processors.platform.client.ClientResponse;\n\n/**\n * Cache destroy request.\n */\npublic class ClientCacheDestroyRequest extends ClientRequest {\n\n /**\n * Cache ID.\n */\n private final int cacheId;\n\n /**\n * Constructor.\n *\n * @param reader Reader.\n */\n public ClientCacheDestroyRequest(BinaryRawReader reader) {\n super(reader);\n cacheId = reader.readInt();\n }\n\n @Override\n public ClientResponse process(ClientConnectionContext ctx) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2702", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCacheDestroyRequest.java", "mask_start_position": 810, "mask_end_position": 890, "canonical_solution": "String cacheName = ClientCacheRequest.cacheDescriptor(ctx, cacheId).cacheName();", "pre_mask_code": "package org.apache.ignite.internal.processors.platform.client.cache;\n\nimport org.apache.ignite.binary.BinaryRawReader;\nimport org.apache.ignite.internal.processors.platform.client.ClientConnectionContext;\nimport org.apache.ignite.internal.processors.platform.client.ClientRequest;\nimport org.apache.ignite.internal.processors.platform.client.ClientResponse;\n\n/**\n * Cache destroy request.\n */\npublic class ClientCacheDestroyRequest extends ClientRequest {\n\n /**\n * Cache ID.\n */\n private final int cacheId;\n\n /**\n * Constructor.\n *\n * @param reader Reader.\n */\n public ClientCacheDestroyRequest(BinaryRawReader reader) {\n super(reader);\n cacheId = reader.readInt();\n }\n\n @Override\n public ClientResponse process(ClientConnectionContext ctx) {\n ", "post_mask_code": "\n ctx.kernalContext().grid().destroyCache(cacheName);\n return super.process(ctx);\n }\n}\n"} {"task_id": "Java_2703", "language": "Java", "task_type": "method_signature", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/apigateway/v20180808/models/Environment.java", "mask_start_position": 1692, "mask_end_position": 1723, "canonical_solution": "public String getVersionName() ", "pre_mask_code": "package com.tencentcloudapi.apigateway.v20180808.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class Environment extends AbstractModel {\n\n /**\n * 环境名称。\n */\n @SerializedName(\"EnvironmentName\")\n @Expose\n private String EnvironmentName;\n\n /**\n * 访问路径。\n */\n @SerializedName(\"Url\")\n @Expose\n private String Url;\n\n /**\n * 发布状态,1 表示已发布,0 表示未发布。\n */\n @SerializedName(\"Status\")\n @Expose\n private Long Status;\n\n /**\n * 运行版本。\n */\n @SerializedName(\"VersionName\")\n @Expose\n private String VersionName;\n\n /**\n * Get 环境名称。\n * @return EnvironmentName 环境名称。\n */\n public String getEnvironmentName() {\n return this.EnvironmentName;\n }\n\n /**\n * Set 环境名称。\n * @param EnvironmentName 环境名称。\n */\n public void setEnvironmentName(String EnvironmentName) {\n this.EnvironmentName = EnvironmentName;\n }\n\n /**\n * Get 访问路径。\n * @return Url 访问路径。\n */\n public String getUrl() {\n return this.Url;\n }\n\n /**\n * Set 访问路径。\n * @param Url 访问路径。\n */\n public void setUrl(String Url) {\n this.Url = Url;\n }\n\n /**\n * Get 发布状态,1 表示已发布,0 表示未发布。\n * @return Status 发布状态,1 表示已发布,0 表示未发布。\n */\n public Long getStatus() {\n return this.Status;\n }\n\n /**\n * Set 发布状态,1 表示已发布,0 表示未发布。\n * @param Status 发布状态,1 表示已发布,0 表示未发布。\n */\n public void setStatus(Long Status) {\n this.Status = Status;\n }\n\n /**\n * Get 运行版本。\n * @return VersionName 运行版本。\n */\n ", "post_mask_code": "{\n return this.VersionName;\n }\n\n /**\n * Set 运行版本。\n * @param VersionName 运行版本。\n */\n public void setVersionName(String VersionName) {\n this.VersionName = VersionName;\n }\n\n public Environment() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public Environment(Environment source) {\n if (source.EnvironmentName != null) {\n this.EnvironmentName = new String(source.EnvironmentName);\n }\n if (source.Url != null) {\n this.Url = new String(source.Url);\n }\n if (source.Status != null) {\n this.Status = new Long(source.Status);\n }\n if (source.VersionName != null) {\n this.VersionName = new String(source.VersionName);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) {\n this.setParamSimple(map, prefix + \"EnvironmentName\", this.EnvironmentName);\n this.setParamSimple(map, prefix + \"Url\", this.Url);\n this.setParamSimple(map, prefix + \"Status\", this.Status);\n this.setParamSimple(map, prefix + \"VersionName\", this.VersionName);\n }\n}\n"} {"task_id": "Java_2704", "language": "Java", "task_type": "method_body", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/apigateway/v20180808/models/Environment.java", "mask_start_position": 1261, "mask_end_position": 1292, "canonical_solution": "{\n this.Url = Url;\n }", "pre_mask_code": "package com.tencentcloudapi.apigateway.v20180808.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class Environment extends AbstractModel {\n\n /**\n * 环境名称。\n */\n @SerializedName(\"EnvironmentName\")\n @Expose\n private String EnvironmentName;\n\n /**\n * 访问路径。\n */\n @SerializedName(\"Url\")\n @Expose\n private String Url;\n\n /**\n * 发布状态,1 表示已发布,0 表示未发布。\n */\n @SerializedName(\"Status\")\n @Expose\n private Long Status;\n\n /**\n * 运行版本。\n */\n @SerializedName(\"VersionName\")\n @Expose\n private String VersionName;\n\n /**\n * Get 环境名称。\n * @return EnvironmentName 环境名称。\n */\n public String getEnvironmentName() {\n return this.EnvironmentName;\n }\n\n /**\n * Set 环境名称。\n * @param EnvironmentName 环境名称。\n */\n public void setEnvironmentName(String EnvironmentName) {\n this.EnvironmentName = EnvironmentName;\n }\n\n /**\n * Get 访问路径。\n * @return Url 访问路径。\n */\n public String getUrl() {\n return this.Url;\n }\n\n /**\n * Set 访问路径。\n * @param Url 访问路径。\n */\n public void setUrl(String Url) ", "post_mask_code": "\n\n /**\n * Get 发布状态,1 表示已发布,0 表示未发布。\n * @return Status 发布状态,1 表示已发布,0 表示未发布。\n */\n public Long getStatus() {\n return this.Status;\n }\n\n /**\n * Set 发布状态,1 表示已发布,0 表示未发布。\n * @param Status 发布状态,1 表示已发布,0 表示未发布。\n */\n public void setStatus(Long Status) {\n this.Status = Status;\n }\n\n /**\n * Get 运行版本。\n * @return VersionName 运行版本。\n */\n public String getVersionName() {\n return this.VersionName;\n }\n\n /**\n * Set 运行版本。\n * @param VersionName 运行版本。\n */\n public void setVersionName(String VersionName) {\n this.VersionName = VersionName;\n }\n\n public Environment() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public Environment(Environment source) {\n if (source.EnvironmentName != null) {\n this.EnvironmentName = new String(source.EnvironmentName);\n }\n if (source.Url != null) {\n this.Url = new String(source.Url);\n }\n if (source.Status != null) {\n this.Status = new Long(source.Status);\n }\n if (source.VersionName != null) {\n this.VersionName = new String(source.VersionName);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) {\n this.setParamSimple(map, prefix + \"EnvironmentName\", this.EnvironmentName);\n this.setParamSimple(map, prefix + \"Url\", this.Url);\n this.setParamSimple(map, prefix + \"Status\", this.Status);\n this.setParamSimple(map, prefix + \"VersionName\", this.VersionName);\n }\n}\n"} {"task_id": "Java_2705", "language": "Java", "task_type": "single_line", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/apigateway/v20180808/models/Environment.java", "mask_start_position": 843, "mask_end_position": 857, "canonical_solution": "vironmentName;", "pre_mask_code": "package com.tencentcloudapi.apigateway.v20180808.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class Environment extends AbstractModel {\n\n /**\n * 环境名称。\n */\n @SerializedName(\"EnvironmentName\")\n @Expose\n private String EnvironmentName;\n\n /**\n * 访问路径。\n */\n @SerializedName(\"Url\")\n @Expose\n private String Url;\n\n /**\n * 发布状态,1 表示已发布,0 表示未发布。\n */\n @SerializedName(\"Status\")\n @Expose\n private Long Status;\n\n /**\n * 运行版本。\n */\n @SerializedName(\"VersionName\")\n @Expose\n private String VersionName;\n\n /**\n * Get 环境名称。\n * @return EnvironmentName 环境名称。\n */\n public String getEnvironmentName() {\n return this.En", "post_mask_code": "\n }\n\n /**\n * Set 环境名称。\n * @param EnvironmentName 环境名称。\n */\n public void setEnvironmentName(String EnvironmentName) {\n this.EnvironmentName = EnvironmentName;\n }\n\n /**\n * Get 访问路径。\n * @return Url 访问路径。\n */\n public String getUrl() {\n return this.Url;\n }\n\n /**\n * Set 访问路径。\n * @param Url 访问路径。\n */\n public void setUrl(String Url) {\n this.Url = Url;\n }\n\n /**\n * Get 发布状态,1 表示已发布,0 表示未发布。\n * @return Status 发布状态,1 表示已发布,0 表示未发布。\n */\n public Long getStatus() {\n return this.Status;\n }\n\n /**\n * Set 发布状态,1 表示已发布,0 表示未发布。\n * @param Status 发布状态,1 表示已发布,0 表示未发布。\n */\n public void setStatus(Long Status) {\n this.Status = Status;\n }\n\n /**\n * Get 运行版本。\n * @return VersionName 运行版本。\n */\n public String getVersionName() {\n return this.VersionName;\n }\n\n /**\n * Set 运行版本。\n * @param VersionName 运行版本。\n */\n public void setVersionName(String VersionName) {\n this.VersionName = VersionName;\n }\n\n public Environment() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public Environment(Environment source) {\n if (source.EnvironmentName != null) {\n this.EnvironmentName = new String(source.EnvironmentName);\n }\n if (source.Url != null) {\n this.Url = new String(source.Url);\n }\n if (source.Status != null) {\n this.Status = new Long(source.Status);\n }\n if (source.VersionName != null) {\n this.VersionName = new String(source.VersionName);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) {\n this.setParamSimple(map, prefix + \"EnvironmentName\", this.EnvironmentName);\n this.setParamSimple(map, prefix + \"Url\", this.Url);\n this.setParamSimple(map, prefix + \"Status\", this.Status);\n this.setParamSimple(map, prefix + \"VersionName\", this.VersionName);\n }\n}\n"} {"task_id": "Java_2706", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/TencentCloud/tencentcloud-sdk-java/src/main/java/com/tencentcloudapi/apigateway/v20180808/models/Environment.java", "mask_start_position": 784, "mask_end_position": 863, "canonical_solution": "public String getEnvironmentName() {\n return this.EnvironmentName;\n }", "pre_mask_code": "package com.tencentcloudapi.apigateway.v20180808.models;\n\nimport com.tencentcloudapi.common.AbstractModel;\nimport com.google.gson.annotations.SerializedName;\nimport com.google.gson.annotations.Expose;\nimport java.util.HashMap;\n\npublic class Environment extends AbstractModel {\n\n /**\n * 环境名称。\n */\n @SerializedName(\"EnvironmentName\")\n @Expose\n private String EnvironmentName;\n\n /**\n * 访问路径。\n */\n @SerializedName(\"Url\")\n @Expose\n private String Url;\n\n /**\n * 发布状态,1 表示已发布,0 表示未发布。\n */\n @SerializedName(\"Status\")\n @Expose\n private Long Status;\n\n /**\n * 运行版本。\n */\n @SerializedName(\"VersionName\")\n @Expose\n private String VersionName;\n\n /**\n * Get 环境名称。\n * @return EnvironmentName 环境名称。\n */\n ", "post_mask_code": "\n\n /**\n * Set 环境名称。\n * @param EnvironmentName 环境名称。\n */\n public void setEnvironmentName(String EnvironmentName) {\n this.EnvironmentName = EnvironmentName;\n }\n\n /**\n * Get 访问路径。\n * @return Url 访问路径。\n */\n public String getUrl() {\n return this.Url;\n }\n\n /**\n * Set 访问路径。\n * @param Url 访问路径。\n */\n public void setUrl(String Url) {\n this.Url = Url;\n }\n\n /**\n * Get 发布状态,1 表示已发布,0 表示未发布。\n * @return Status 发布状态,1 表示已发布,0 表示未发布。\n */\n public Long getStatus() {\n return this.Status;\n }\n\n /**\n * Set 发布状态,1 表示已发布,0 表示未发布。\n * @param Status 发布状态,1 表示已发布,0 表示未发布。\n */\n public void setStatus(Long Status) {\n this.Status = Status;\n }\n\n /**\n * Get 运行版本。\n * @return VersionName 运行版本。\n */\n public String getVersionName() {\n return this.VersionName;\n }\n\n /**\n * Set 运行版本。\n * @param VersionName 运行版本。\n */\n public void setVersionName(String VersionName) {\n this.VersionName = VersionName;\n }\n\n public Environment() {\n }\n\n /**\n * NOTE: Any ambiguous key set via .set(\"AnyKey\", \"value\") will be a shallow copy,\n * and any explicit key, i.e Foo, set via .setFoo(\"value\") will be a deep copy.\n */\n public Environment(Environment source) {\n if (source.EnvironmentName != null) {\n this.EnvironmentName = new String(source.EnvironmentName);\n }\n if (source.Url != null) {\n this.Url = new String(source.Url);\n }\n if (source.Status != null) {\n this.Status = new Long(source.Status);\n }\n if (source.VersionName != null) {\n this.VersionName = new String(source.VersionName);\n }\n }\n\n /**\n * Internal implementation, normal users should not use it.\n */\n public void toMap(HashMap map, String prefix) {\n this.setParamSimple(map, prefix + \"EnvironmentName\", this.EnvironmentName);\n this.setParamSimple(map, prefix + \"Url\", this.Url);\n this.setParamSimple(map, prefix + \"Status\", this.Status);\n this.setParamSimple(map, prefix + \"VersionName\", this.VersionName);\n }\n}\n"} {"task_id": "Java_2707", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/lucene/lucene/analysis/stempel/src/java/org/egothor/stemmer/MultiTrie2.java", "mask_start_position": 5625, "mask_end_position": 5691, "canonical_solution": "@Override\n public void add(CharSequence key, CharSequence cmd) ", "pre_mask_code": "/*\n Egothor Software License version 1.00\n on behalf of the Egothor Project.\n All rights reserved.\n\n This software is copyrighted by the \"Egothor developers\". If this\n license applies to a single file or document, the \"Egothor developers\"\n are the people or entities mentioned as copyright holders in that file\n or document. If this license applies to the Egothor project as a\n whole, the copyright holders are the people or entities mentioned in\n the file CREDITS. This file can be found in the same location as this\n license in the distribution.\n\n written permission, please contact example@nnthink.com\n 4. Products derived from this software may not be called \"Egothor\",\n nor may \"Egothor\" appear in their name, without prior written\n permission from Leo.G@seznam.cz.\n\n In addition, we request that you include in the end-user documentation\n provided with the redistribution and/or in the software itself an\n acknowledgement equivalent to the following:\n \"This product includes software developed by the Egothor Project.\n http://example.com\"\n\n created by Leo Galambos (Leo.G@seznam.cz).\n*/\npackage org.egothor.stemmer;\n\nimport java.io.DataInput;\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * The MultiTrie is a Trie of Tries.\n *\n *

It stores words and their associated patch commands. The MultiTrie handles patch commands\n * broken into their constituent parts, as a MultiTrie does, but the commands are delimited by the\n * skip command.\n */\npublic class MultiTrie2 extends MultiTrie {\n\n /**\n * Constructor for the MultiTrie object.\n *\n * @param is the input stream\n * @exception IOException if an I/O error occurs\n */\n public MultiTrie2(DataInput is) throws IOException {\n super(is);\n }\n\n /**\n * Constructor for the MultiTrie2 object\n *\n * @param forward set to true if the elements should be read left to right\n */\n public MultiTrie2(boolean forward) {\n super(forward);\n }\n\n /**\n * Return the element that is stored in a cell associated with the given key.\n *\n * @param key the key to the cell holding the desired element\n * @return the element\n */\n @Override\n public CharSequence getFully(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getFully(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Return the element that is stored as last on a path belonging to the given key.\n *\n * @param key the key associated with the desired element\n * @return the element that is stored as last on a path\n */\n @Override\n public CharSequence getLastOnPath(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getLastOnPath(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Write this data structure to the given output stream.\n *\n * @param os the output stream\n * @exception IOException if an I/O error occurs\n */\n @Override\n public void store(DataOutput os) throws IOException {\n super.store(os);\n }\n\n /**\n * Add an element to this structure consisting of the given key and patch command.\n *\n *

This method will return without executing if the cmd parameter's length is 0.\n *\n * @param key the key\n * @param cmd the patch command\n */\n ", "post_mask_code": "{\n if (cmd.length() == 0) {\n return;\n }\n CharSequence[] p = decompose(cmd);\n int levels = p.length;\n while (levels >= tries.size()) {\n tries.add(new Trie(forward));\n }\n CharSequence lastkey = key;\n for (int i = 0; i < levels; i++) {\n if (key.length() > 0) {\n tries.get(i).add(key, p[i]);\n lastkey = key;\n } else {\n tries.get(i).add(lastkey, p[i]);\n }\n if (p[i].length() > 0 && p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n }\n if (key.length() > 0) {\n tries.get(levels).add(key, EOM_NODE);\n } else {\n tries.get(levels).add(lastkey, EOM_NODE);\n }\n }\n\n /**\n * Break the given patch command into its constituent pieces. The pieces are delimited by NOOP\n * commands.\n *\n * @param cmd the patch command\n * @return an array containing the pieces of the command\n */\n public CharSequence[] decompose(CharSequence cmd) {\n int parts = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n parts++;\n i = next + 2;\n } else {\n parts++;\n i = next;\n }\n }\n CharSequence[] part = new CharSequence[parts];\n int x = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n part[x++] = cmd.subSequence(i, i + 2);\n i = next + 2;\n } else {\n part[x++] = (next < 0) ? cmd.subSequence(i, cmd.length()) : cmd.subSequence(i, next);\n i = next;\n }\n }\n return part;\n }\n\n /**\n * Remove empty rows from the given Trie and return the newly reduced Trie.\n *\n * @param by the Trie to reduce\n * @return the newly reduced Trie\n */\n @Override\n public Trie reduce(Reduce by) {\n List h = new ArrayList<>();\n for (Trie trie : tries) h.add(trie.reduce(by));\n MultiTrie2 m = new MultiTrie2(forward);\n m.tries = h;\n return m;\n }\n\n private boolean cannotFollow(char after, char goes) {\n switch(after) {\n case '-':\n case 'D':\n return after == goes;\n }\n return false;\n }\n\n private CharSequence skip(CharSequence in, int count) {\n if (forward) {\n return in.subSequence(count, in.length());\n } else {\n return in.subSequence(0, in.length() - count);\n }\n }\n\n private int dashEven(CharSequence in, int from) {\n while (from < in.length()) {\n if (in.charAt(from) == '-') {\n return from;\n } else {\n from += 2;\n }\n }\n return -1;\n }\n\n @SuppressWarnings(\"fallthrough\")\n private int lengthPP(CharSequence cmd) {\n int len = 0;\n for (int i = 0; i < cmd.length(); i++) {\n switch(cmd.charAt(i++)) {\n case '-':\n case 'D':\n len += cmd.charAt(i) - 'a' + 1;\n break;\n case 'R':\n len++;\n /* intentional fallthrough */\n case 'I':\n break;\n }\n }\n return len;\n }\n}\n"} {"task_id": "Java_2708", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/lucene/lucene/analysis/stempel/src/java/org/egothor/stemmer/MultiTrie2.java", "mask_start_position": 5307, "mask_end_position": 5339, "canonical_solution": "{\n super.store(os);\n }", "pre_mask_code": "/*\n Egothor Software License version 1.00\n on behalf of the Egothor Project.\n All rights reserved.\n\n This software is copyrighted by the \"Egothor developers\". If this\n license applies to a single file or document, the \"Egothor developers\"\n are the people or entities mentioned as copyright holders in that file\n or document. If this license applies to the Egothor project as a\n whole, the copyright holders are the people or entities mentioned in\n the file CREDITS. This file can be found in the same location as this\n license in the distribution.\n\n written permission, please contact example@nnthink.com\n 4. Products derived from this software may not be called \"Egothor\",\n nor may \"Egothor\" appear in their name, without prior written\n permission from Leo.G@seznam.cz.\n\n In addition, we request that you include in the end-user documentation\n provided with the redistribution and/or in the software itself an\n acknowledgement equivalent to the following:\n \"This product includes software developed by the Egothor Project.\n http://example.com\"\n\n created by Leo Galambos (Leo.G@seznam.cz).\n*/\npackage org.egothor.stemmer;\n\nimport java.io.DataInput;\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * The MultiTrie is a Trie of Tries.\n *\n *

It stores words and their associated patch commands. The MultiTrie handles patch commands\n * broken into their constituent parts, as a MultiTrie does, but the commands are delimited by the\n * skip command.\n */\npublic class MultiTrie2 extends MultiTrie {\n\n /**\n * Constructor for the MultiTrie object.\n *\n * @param is the input stream\n * @exception IOException if an I/O error occurs\n */\n public MultiTrie2(DataInput is) throws IOException {\n super(is);\n }\n\n /**\n * Constructor for the MultiTrie2 object\n *\n * @param forward set to true if the elements should be read left to right\n */\n public MultiTrie2(boolean forward) {\n super(forward);\n }\n\n /**\n * Return the element that is stored in a cell associated with the given key.\n *\n * @param key the key to the cell holding the desired element\n * @return the element\n */\n @Override\n public CharSequence getFully(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getFully(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Return the element that is stored as last on a path belonging to the given key.\n *\n * @param key the key associated with the desired element\n * @return the element that is stored as last on a path\n */\n @Override\n public CharSequence getLastOnPath(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getLastOnPath(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Write this data structure to the given output stream.\n *\n * @param os the output stream\n * @exception IOException if an I/O error occurs\n */\n @Override\n public void store(DataOutput os) throws IOException ", "post_mask_code": "\n\n /**\n * Add an element to this structure consisting of the given key and patch command.\n *\n *

This method will return without executing if the cmd parameter's length is 0.\n *\n * @param key the key\n * @param cmd the patch command\n */\n @Override\n public void add(CharSequence key, CharSequence cmd) {\n if (cmd.length() == 0) {\n return;\n }\n CharSequence[] p = decompose(cmd);\n int levels = p.length;\n while (levels >= tries.size()) {\n tries.add(new Trie(forward));\n }\n CharSequence lastkey = key;\n for (int i = 0; i < levels; i++) {\n if (key.length() > 0) {\n tries.get(i).add(key, p[i]);\n lastkey = key;\n } else {\n tries.get(i).add(lastkey, p[i]);\n }\n if (p[i].length() > 0 && p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n }\n if (key.length() > 0) {\n tries.get(levels).add(key, EOM_NODE);\n } else {\n tries.get(levels).add(lastkey, EOM_NODE);\n }\n }\n\n /**\n * Break the given patch command into its constituent pieces. The pieces are delimited by NOOP\n * commands.\n *\n * @param cmd the patch command\n * @return an array containing the pieces of the command\n */\n public CharSequence[] decompose(CharSequence cmd) {\n int parts = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n parts++;\n i = next + 2;\n } else {\n parts++;\n i = next;\n }\n }\n CharSequence[] part = new CharSequence[parts];\n int x = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n part[x++] = cmd.subSequence(i, i + 2);\n i = next + 2;\n } else {\n part[x++] = (next < 0) ? cmd.subSequence(i, cmd.length()) : cmd.subSequence(i, next);\n i = next;\n }\n }\n return part;\n }\n\n /**\n * Remove empty rows from the given Trie and return the newly reduced Trie.\n *\n * @param by the Trie to reduce\n * @return the newly reduced Trie\n */\n @Override\n public Trie reduce(Reduce by) {\n List h = new ArrayList<>();\n for (Trie trie : tries) h.add(trie.reduce(by));\n MultiTrie2 m = new MultiTrie2(forward);\n m.tries = h;\n return m;\n }\n\n private boolean cannotFollow(char after, char goes) {\n switch(after) {\n case '-':\n case 'D':\n return after == goes;\n }\n return false;\n }\n\n private CharSequence skip(CharSequence in, int count) {\n if (forward) {\n return in.subSequence(count, in.length());\n } else {\n return in.subSequence(0, in.length() - count);\n }\n }\n\n private int dashEven(CharSequence in, int from) {\n while (from < in.length()) {\n if (in.charAt(from) == '-') {\n return from;\n } else {\n from += 2;\n }\n }\n return -1;\n }\n\n @SuppressWarnings(\"fallthrough\")\n private int lengthPP(CharSequence cmd) {\n int len = 0;\n for (int i = 0; i < cmd.length(); i++) {\n switch(cmd.charAt(i++)) {\n case '-':\n case 'D':\n len += cmd.charAt(i) - 'a' + 1;\n break;\n case 'R':\n len++;\n /* intentional fallthrough */\n case 'I':\n break;\n }\n }\n return len;\n }\n}\n"} {"task_id": "Java_2709", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/lucene/lucene/analysis/stempel/src/java/org/egothor/stemmer/MultiTrie2.java", "mask_start_position": 7238, "mask_end_position": 7253, "canonical_solution": "equence[parts];", "pre_mask_code": "/*\n Egothor Software License version 1.00\n on behalf of the Egothor Project.\n All rights reserved.\n\n This software is copyrighted by the \"Egothor developers\". If this\n license applies to a single file or document, the \"Egothor developers\"\n are the people or entities mentioned as copyright holders in that file\n or document. If this license applies to the Egothor project as a\n whole, the copyright holders are the people or entities mentioned in\n the file CREDITS. This file can be found in the same location as this\n license in the distribution.\n\n written permission, please contact example@nnthink.com\n 4. Products derived from this software may not be called \"Egothor\",\n nor may \"Egothor\" appear in their name, without prior written\n permission from Leo.G@seznam.cz.\n\n In addition, we request that you include in the end-user documentation\n provided with the redistribution and/or in the software itself an\n acknowledgement equivalent to the following:\n \"This product includes software developed by the Egothor Project.\n http://example.com\"\n\n created by Leo Galambos (Leo.G@seznam.cz).\n*/\npackage org.egothor.stemmer;\n\nimport java.io.DataInput;\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * The MultiTrie is a Trie of Tries.\n *\n *

It stores words and their associated patch commands. The MultiTrie handles patch commands\n * broken into their constituent parts, as a MultiTrie does, but the commands are delimited by the\n * skip command.\n */\npublic class MultiTrie2 extends MultiTrie {\n\n /**\n * Constructor for the MultiTrie object.\n *\n * @param is the input stream\n * @exception IOException if an I/O error occurs\n */\n public MultiTrie2(DataInput is) throws IOException {\n super(is);\n }\n\n /**\n * Constructor for the MultiTrie2 object\n *\n * @param forward set to true if the elements should be read left to right\n */\n public MultiTrie2(boolean forward) {\n super(forward);\n }\n\n /**\n * Return the element that is stored in a cell associated with the given key.\n *\n * @param key the key to the cell holding the desired element\n * @return the element\n */\n @Override\n public CharSequence getFully(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getFully(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Return the element that is stored as last on a path belonging to the given key.\n *\n * @param key the key associated with the desired element\n * @return the element that is stored as last on a path\n */\n @Override\n public CharSequence getLastOnPath(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getLastOnPath(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Write this data structure to the given output stream.\n *\n * @param os the output stream\n * @exception IOException if an I/O error occurs\n */\n @Override\n public void store(DataOutput os) throws IOException {\n super.store(os);\n }\n\n /**\n * Add an element to this structure consisting of the given key and patch command.\n *\n *

This method will return without executing if the cmd parameter's length is 0.\n *\n * @param key the key\n * @param cmd the patch command\n */\n @Override\n public void add(CharSequence key, CharSequence cmd) {\n if (cmd.length() == 0) {\n return;\n }\n CharSequence[] p = decompose(cmd);\n int levels = p.length;\n while (levels >= tries.size()) {\n tries.add(new Trie(forward));\n }\n CharSequence lastkey = key;\n for (int i = 0; i < levels; i++) {\n if (key.length() > 0) {\n tries.get(i).add(key, p[i]);\n lastkey = key;\n } else {\n tries.get(i).add(lastkey, p[i]);\n }\n if (p[i].length() > 0 && p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n }\n if (key.length() > 0) {\n tries.get(levels).add(key, EOM_NODE);\n } else {\n tries.get(levels).add(lastkey, EOM_NODE);\n }\n }\n\n /**\n * Break the given patch command into its constituent pieces. The pieces are delimited by NOOP\n * commands.\n *\n * @param cmd the patch command\n * @return an array containing the pieces of the command\n */\n public CharSequence[] decompose(CharSequence cmd) {\n int parts = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n parts++;\n i = next + 2;\n } else {\n parts++;\n i = next;\n }\n }\n CharSequence[] part = new CharS", "post_mask_code": "\n int x = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n part[x++] = cmd.subSequence(i, i + 2);\n i = next + 2;\n } else {\n part[x++] = (next < 0) ? cmd.subSequence(i, cmd.length()) : cmd.subSequence(i, next);\n i = next;\n }\n }\n return part;\n }\n\n /**\n * Remove empty rows from the given Trie and return the newly reduced Trie.\n *\n * @param by the Trie to reduce\n * @return the newly reduced Trie\n */\n @Override\n public Trie reduce(Reduce by) {\n List h = new ArrayList<>();\n for (Trie trie : tries) h.add(trie.reduce(by));\n MultiTrie2 m = new MultiTrie2(forward);\n m.tries = h;\n return m;\n }\n\n private boolean cannotFollow(char after, char goes) {\n switch(after) {\n case '-':\n case 'D':\n return after == goes;\n }\n return false;\n }\n\n private CharSequence skip(CharSequence in, int count) {\n if (forward) {\n return in.subSequence(count, in.length());\n } else {\n return in.subSequence(0, in.length() - count);\n }\n }\n\n private int dashEven(CharSequence in, int from) {\n while (from < in.length()) {\n if (in.charAt(from) == '-') {\n return from;\n } else {\n from += 2;\n }\n }\n return -1;\n }\n\n @SuppressWarnings(\"fallthrough\")\n private int lengthPP(CharSequence cmd) {\n int len = 0;\n for (int i = 0; i < cmd.length(); i++) {\n switch(cmd.charAt(i++)) {\n case '-':\n case 'D':\n len += cmd.charAt(i) - 'a' + 1;\n break;\n case 'R':\n len++;\n /* intentional fallthrough */\n case 'I':\n break;\n }\n }\n return len;\n }\n}\n"} {"task_id": "Java_2710", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/apache/lucene/lucene/analysis/stempel/src/java/org/egothor/stemmer/MultiTrie2.java", "mask_start_position": 5241, "mask_end_position": 5339, "canonical_solution": "@Override\n public void store(DataOutput os) throws IOException {\n super.store(os);\n }", "pre_mask_code": "/*\n Egothor Software License version 1.00\n on behalf of the Egothor Project.\n All rights reserved.\n\n This software is copyrighted by the \"Egothor developers\". If this\n license applies to a single file or document, the \"Egothor developers\"\n are the people or entities mentioned as copyright holders in that file\n or document. If this license applies to the Egothor project as a\n whole, the copyright holders are the people or entities mentioned in\n the file CREDITS. This file can be found in the same location as this\n license in the distribution.\n\n written permission, please contact example@nnthink.com\n 4. Products derived from this software may not be called \"Egothor\",\n nor may \"Egothor\" appear in their name, without prior written\n permission from Leo.G@seznam.cz.\n\n In addition, we request that you include in the end-user documentation\n provided with the redistribution and/or in the software itself an\n acknowledgement equivalent to the following:\n \"This product includes software developed by the Egothor Project.\n http://example.com\"\n\n created by Leo Galambos (Leo.G@seznam.cz).\n*/\npackage org.egothor.stemmer;\n\nimport java.io.DataInput;\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * The MultiTrie is a Trie of Tries.\n *\n *

It stores words and their associated patch commands. The MultiTrie handles patch commands\n * broken into their constituent parts, as a MultiTrie does, but the commands are delimited by the\n * skip command.\n */\npublic class MultiTrie2 extends MultiTrie {\n\n /**\n * Constructor for the MultiTrie object.\n *\n * @param is the input stream\n * @exception IOException if an I/O error occurs\n */\n public MultiTrie2(DataInput is) throws IOException {\n super(is);\n }\n\n /**\n * Constructor for the MultiTrie2 object\n *\n * @param forward set to true if the elements should be read left to right\n */\n public MultiTrie2(boolean forward) {\n super(forward);\n }\n\n /**\n * Return the element that is stored in a cell associated with the given key.\n *\n * @param key the key to the cell holding the desired element\n * @return the element\n */\n @Override\n public CharSequence getFully(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getFully(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Return the element that is stored as last on a path belonging to the given key.\n *\n * @param key the key associated with the desired element\n * @return the element that is stored as last on a path\n */\n @Override\n public CharSequence getLastOnPath(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getLastOnPath(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Write this data structure to the given output stream.\n *\n * @param os the output stream\n * @exception IOException if an I/O error occurs\n */\n ", "post_mask_code": "\n\n /**\n * Add an element to this structure consisting of the given key and patch command.\n *\n *

This method will return without executing if the cmd parameter's length is 0.\n *\n * @param key the key\n * @param cmd the patch command\n */\n @Override\n public void add(CharSequence key, CharSequence cmd) {\n if (cmd.length() == 0) {\n return;\n }\n CharSequence[] p = decompose(cmd);\n int levels = p.length;\n while (levels >= tries.size()) {\n tries.add(new Trie(forward));\n }\n CharSequence lastkey = key;\n for (int i = 0; i < levels; i++) {\n if (key.length() > 0) {\n tries.get(i).add(key, p[i]);\n lastkey = key;\n } else {\n tries.get(i).add(lastkey, p[i]);\n }\n if (p[i].length() > 0 && p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n }\n if (key.length() > 0) {\n tries.get(levels).add(key, EOM_NODE);\n } else {\n tries.get(levels).add(lastkey, EOM_NODE);\n }\n }\n\n /**\n * Break the given patch command into its constituent pieces. The pieces are delimited by NOOP\n * commands.\n *\n * @param cmd the patch command\n * @return an array containing the pieces of the command\n */\n public CharSequence[] decompose(CharSequence cmd) {\n int parts = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n parts++;\n i = next + 2;\n } else {\n parts++;\n i = next;\n }\n }\n CharSequence[] part = new CharSequence[parts];\n int x = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n part[x++] = cmd.subSequence(i, i + 2);\n i = next + 2;\n } else {\n part[x++] = (next < 0) ? cmd.subSequence(i, cmd.length()) : cmd.subSequence(i, next);\n i = next;\n }\n }\n return part;\n }\n\n /**\n * Remove empty rows from the given Trie and return the newly reduced Trie.\n *\n * @param by the Trie to reduce\n * @return the newly reduced Trie\n */\n @Override\n public Trie reduce(Reduce by) {\n List h = new ArrayList<>();\n for (Trie trie : tries) h.add(trie.reduce(by));\n MultiTrie2 m = new MultiTrie2(forward);\n m.tries = h;\n return m;\n }\n\n private boolean cannotFollow(char after, char goes) {\n switch(after) {\n case '-':\n case 'D':\n return after == goes;\n }\n return false;\n }\n\n private CharSequence skip(CharSequence in, int count) {\n if (forward) {\n return in.subSequence(count, in.length());\n } else {\n return in.subSequence(0, in.length() - count);\n }\n }\n\n private int dashEven(CharSequence in, int from) {\n while (from < in.length()) {\n if (in.charAt(from) == '-') {\n return from;\n } else {\n from += 2;\n }\n }\n return -1;\n }\n\n @SuppressWarnings(\"fallthrough\")\n private int lengthPP(CharSequence cmd) {\n int len = 0;\n for (int i = 0; i < cmd.length(); i++) {\n switch(cmd.charAt(i++)) {\n case '-':\n case 'D':\n len += cmd.charAt(i) - 'a' + 1;\n break;\n case 'R':\n len++;\n /* intentional fallthrough */\n case 'I':\n break;\n }\n }\n return len;\n }\n}\n"} {"task_id": "Java_2711", "language": "Java", "task_type": "switch_case", "source_file": "java/github/apache/lucene/lucene/analysis/stempel/src/java/org/egothor/stemmer/MultiTrie2.java", "mask_start_position": 8170, "mask_end_position": 8277, "canonical_solution": "switch(after) {\n case '-':\n case 'D':\n return after == goes;\n }", "pre_mask_code": "/*\n Egothor Software License version 1.00\n on behalf of the Egothor Project.\n All rights reserved.\n\n This software is copyrighted by the \"Egothor developers\". If this\n license applies to a single file or document, the \"Egothor developers\"\n are the people or entities mentioned as copyright holders in that file\n or document. If this license applies to the Egothor project as a\n whole, the copyright holders are the people or entities mentioned in\n the file CREDITS. This file can be found in the same location as this\n license in the distribution.\n\n written permission, please contact example@nnthink.com\n 4. Products derived from this software may not be called \"Egothor\",\n nor may \"Egothor\" appear in their name, without prior written\n permission from Leo.G@seznam.cz.\n\n In addition, we request that you include in the end-user documentation\n provided with the redistribution and/or in the software itself an\n acknowledgement equivalent to the following:\n \"This product includes software developed by the Egothor Project.\n http://example.com\"\n\n created by Leo Galambos (Leo.G@seznam.cz).\n*/\npackage org.egothor.stemmer;\n\nimport java.io.DataInput;\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * The MultiTrie is a Trie of Tries.\n *\n *

It stores words and their associated patch commands. The MultiTrie handles patch commands\n * broken into their constituent parts, as a MultiTrie does, but the commands are delimited by the\n * skip command.\n */\npublic class MultiTrie2 extends MultiTrie {\n\n /**\n * Constructor for the MultiTrie object.\n *\n * @param is the input stream\n * @exception IOException if an I/O error occurs\n */\n public MultiTrie2(DataInput is) throws IOException {\n super(is);\n }\n\n /**\n * Constructor for the MultiTrie2 object\n *\n * @param forward set to true if the elements should be read left to right\n */\n public MultiTrie2(boolean forward) {\n super(forward);\n }\n\n /**\n * Return the element that is stored in a cell associated with the given key.\n *\n * @param key the key to the cell holding the desired element\n * @return the element\n */\n @Override\n public CharSequence getFully(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getFully(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Return the element that is stored as last on a path belonging to the given key.\n *\n * @param key the key associated with the desired element\n * @return the element that is stored as last on a path\n */\n @Override\n public CharSequence getLastOnPath(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getLastOnPath(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Write this data structure to the given output stream.\n *\n * @param os the output stream\n * @exception IOException if an I/O error occurs\n */\n @Override\n public void store(DataOutput os) throws IOException {\n super.store(os);\n }\n\n /**\n * Add an element to this structure consisting of the given key and patch command.\n *\n *

This method will return without executing if the cmd parameter's length is 0.\n *\n * @param key the key\n * @param cmd the patch command\n */\n @Override\n public void add(CharSequence key, CharSequence cmd) {\n if (cmd.length() == 0) {\n return;\n }\n CharSequence[] p = decompose(cmd);\n int levels = p.length;\n while (levels >= tries.size()) {\n tries.add(new Trie(forward));\n }\n CharSequence lastkey = key;\n for (int i = 0; i < levels; i++) {\n if (key.length() > 0) {\n tries.get(i).add(key, p[i]);\n lastkey = key;\n } else {\n tries.get(i).add(lastkey, p[i]);\n }\n if (p[i].length() > 0 && p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n }\n if (key.length() > 0) {\n tries.get(levels).add(key, EOM_NODE);\n } else {\n tries.get(levels).add(lastkey, EOM_NODE);\n }\n }\n\n /**\n * Break the given patch command into its constituent pieces. The pieces are delimited by NOOP\n * commands.\n *\n * @param cmd the patch command\n * @return an array containing the pieces of the command\n */\n public CharSequence[] decompose(CharSequence cmd) {\n int parts = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n parts++;\n i = next + 2;\n } else {\n parts++;\n i = next;\n }\n }\n CharSequence[] part = new CharSequence[parts];\n int x = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n part[x++] = cmd.subSequence(i, i + 2);\n i = next + 2;\n } else {\n part[x++] = (next < 0) ? cmd.subSequence(i, cmd.length()) : cmd.subSequence(i, next);\n i = next;\n }\n }\n return part;\n }\n\n /**\n * Remove empty rows from the given Trie and return the newly reduced Trie.\n *\n * @param by the Trie to reduce\n * @return the newly reduced Trie\n */\n @Override\n public Trie reduce(Reduce by) {\n List h = new ArrayList<>();\n for (Trie trie : tries) h.add(trie.reduce(by));\n MultiTrie2 m = new MultiTrie2(forward);\n m.tries = h;\n return m;\n }\n\n private boolean cannotFollow(char after, char goes) {\n ", "post_mask_code": "\n return false;\n }\n\n private CharSequence skip(CharSequence in, int count) {\n if (forward) {\n return in.subSequence(count, in.length());\n } else {\n return in.subSequence(0, in.length() - count);\n }\n }\n\n private int dashEven(CharSequence in, int from) {\n while (from < in.length()) {\n if (in.charAt(from) == '-') {\n return from;\n } else {\n from += 2;\n }\n }\n return -1;\n }\n\n @SuppressWarnings(\"fallthrough\")\n private int lengthPP(CharSequence cmd) {\n int len = 0;\n for (int i = 0; i < cmd.length(); i++) {\n switch(cmd.charAt(i++)) {\n case '-':\n case 'D':\n len += cmd.charAt(i) - 'a' + 1;\n break;\n case 'R':\n len++;\n /* intentional fallthrough */\n case 'I':\n break;\n }\n }\n return len;\n }\n}\n"} {"task_id": "Java_2712", "language": "Java", "task_type": "for_statement", "source_file": "java/github/apache/lucene/lucene/analysis/stempel/src/java/org/egothor/stemmer/MultiTrie2.java", "mask_start_position": 8909, "mask_end_position": 9294, "canonical_solution": "for (int i = 0; i < cmd.length(); i++) {\n switch(cmd.charAt(i++)) {\n case '-':\n case 'D':\n len += cmd.charAt(i) - 'a' + 1;\n break;\n case 'R':\n len++;\n /* intentional fallthrough */\n case 'I':\n break;\n }\n }", "pre_mask_code": "/*\n Egothor Software License version 1.00\n on behalf of the Egothor Project.\n All rights reserved.\n\n This software is copyrighted by the \"Egothor developers\". If this\n license applies to a single file or document, the \"Egothor developers\"\n are the people or entities mentioned as copyright holders in that file\n or document. If this license applies to the Egothor project as a\n whole, the copyright holders are the people or entities mentioned in\n the file CREDITS. This file can be found in the same location as this\n license in the distribution.\n\n written permission, please contact example@nnthink.com\n 4. Products derived from this software may not be called \"Egothor\",\n nor may \"Egothor\" appear in their name, without prior written\n permission from Leo.G@seznam.cz.\n\n In addition, we request that you include in the end-user documentation\n provided with the redistribution and/or in the software itself an\n acknowledgement equivalent to the following:\n \"This product includes software developed by the Egothor Project.\n http://example.com\"\n\n created by Leo Galambos (Leo.G@seznam.cz).\n*/\npackage org.egothor.stemmer;\n\nimport java.io.DataInput;\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * The MultiTrie is a Trie of Tries.\n *\n *

It stores words and their associated patch commands. The MultiTrie handles patch commands\n * broken into their constituent parts, as a MultiTrie does, but the commands are delimited by the\n * skip command.\n */\npublic class MultiTrie2 extends MultiTrie {\n\n /**\n * Constructor for the MultiTrie object.\n *\n * @param is the input stream\n * @exception IOException if an I/O error occurs\n */\n public MultiTrie2(DataInput is) throws IOException {\n super(is);\n }\n\n /**\n * Constructor for the MultiTrie2 object\n *\n * @param forward set to true if the elements should be read left to right\n */\n public MultiTrie2(boolean forward) {\n super(forward);\n }\n\n /**\n * Return the element that is stored in a cell associated with the given key.\n *\n * @param key the key to the cell holding the desired element\n * @return the element\n */\n @Override\n public CharSequence getFully(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getFully(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Return the element that is stored as last on a path belonging to the given key.\n *\n * @param key the key associated with the desired element\n * @return the element that is stored as last on a path\n */\n @Override\n public CharSequence getLastOnPath(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getLastOnPath(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Write this data structure to the given output stream.\n *\n * @param os the output stream\n * @exception IOException if an I/O error occurs\n */\n @Override\n public void store(DataOutput os) throws IOException {\n super.store(os);\n }\n\n /**\n * Add an element to this structure consisting of the given key and patch command.\n *\n *

This method will return without executing if the cmd parameter's length is 0.\n *\n * @param key the key\n * @param cmd the patch command\n */\n @Override\n public void add(CharSequence key, CharSequence cmd) {\n if (cmd.length() == 0) {\n return;\n }\n CharSequence[] p = decompose(cmd);\n int levels = p.length;\n while (levels >= tries.size()) {\n tries.add(new Trie(forward));\n }\n CharSequence lastkey = key;\n for (int i = 0; i < levels; i++) {\n if (key.length() > 0) {\n tries.get(i).add(key, p[i]);\n lastkey = key;\n } else {\n tries.get(i).add(lastkey, p[i]);\n }\n if (p[i].length() > 0 && p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n }\n if (key.length() > 0) {\n tries.get(levels).add(key, EOM_NODE);\n } else {\n tries.get(levels).add(lastkey, EOM_NODE);\n }\n }\n\n /**\n * Break the given patch command into its constituent pieces. The pieces are delimited by NOOP\n * commands.\n *\n * @param cmd the patch command\n * @return an array containing the pieces of the command\n */\n public CharSequence[] decompose(CharSequence cmd) {\n int parts = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n parts++;\n i = next + 2;\n } else {\n parts++;\n i = next;\n }\n }\n CharSequence[] part = new CharSequence[parts];\n int x = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n part[x++] = cmd.subSequence(i, i + 2);\n i = next + 2;\n } else {\n part[x++] = (next < 0) ? cmd.subSequence(i, cmd.length()) : cmd.subSequence(i, next);\n i = next;\n }\n }\n return part;\n }\n\n /**\n * Remove empty rows from the given Trie and return the newly reduced Trie.\n *\n * @param by the Trie to reduce\n * @return the newly reduced Trie\n */\n @Override\n public Trie reduce(Reduce by) {\n List h = new ArrayList<>();\n for (Trie trie : tries) h.add(trie.reduce(by));\n MultiTrie2 m = new MultiTrie2(forward);\n m.tries = h;\n return m;\n }\n\n private boolean cannotFollow(char after, char goes) {\n switch(after) {\n case '-':\n case 'D':\n return after == goes;\n }\n return false;\n }\n\n private CharSequence skip(CharSequence in, int count) {\n if (forward) {\n return in.subSequence(count, in.length());\n } else {\n return in.subSequence(0, in.length() - count);\n }\n }\n\n private int dashEven(CharSequence in, int from) {\n while (from < in.length()) {\n if (in.charAt(from) == '-') {\n return from;\n } else {\n from += 2;\n }\n }\n return -1;\n }\n\n @SuppressWarnings(\"fallthrough\")\n private int lengthPP(CharSequence cmd) {\n int len = 0;\n ", "post_mask_code": "\n return len;\n }\n}\n"} {"task_id": "Java_2713", "language": "Java", "task_type": "while_statement", "source_file": "java/github/apache/lucene/lucene/analysis/stempel/src/java/org/egothor/stemmer/MultiTrie2.java", "mask_start_position": 8600, "mask_end_position": 8771, "canonical_solution": "while (from < in.length()) {\n if (in.charAt(from) == '-') {\n return from;\n } else {\n from += 2;\n }\n }", "pre_mask_code": "/*\n Egothor Software License version 1.00\n on behalf of the Egothor Project.\n All rights reserved.\n\n This software is copyrighted by the \"Egothor developers\". If this\n license applies to a single file or document, the \"Egothor developers\"\n are the people or entities mentioned as copyright holders in that file\n or document. If this license applies to the Egothor project as a\n whole, the copyright holders are the people or entities mentioned in\n the file CREDITS. This file can be found in the same location as this\n license in the distribution.\n\n written permission, please contact example@nnthink.com\n 4. Products derived from this software may not be called \"Egothor\",\n nor may \"Egothor\" appear in their name, without prior written\n permission from Leo.G@seznam.cz.\n\n In addition, we request that you include in the end-user documentation\n provided with the redistribution and/or in the software itself an\n acknowledgement equivalent to the following:\n \"This product includes software developed by the Egothor Project.\n http://example.com\"\n\n created by Leo Galambos (Leo.G@seznam.cz).\n*/\npackage org.egothor.stemmer;\n\nimport java.io.DataInput;\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * The MultiTrie is a Trie of Tries.\n *\n *

It stores words and their associated patch commands. The MultiTrie handles patch commands\n * broken into their constituent parts, as a MultiTrie does, but the commands are delimited by the\n * skip command.\n */\npublic class MultiTrie2 extends MultiTrie {\n\n /**\n * Constructor for the MultiTrie object.\n *\n * @param is the input stream\n * @exception IOException if an I/O error occurs\n */\n public MultiTrie2(DataInput is) throws IOException {\n super(is);\n }\n\n /**\n * Constructor for the MultiTrie2 object\n *\n * @param forward set to true if the elements should be read left to right\n */\n public MultiTrie2(boolean forward) {\n super(forward);\n }\n\n /**\n * Return the element that is stored in a cell associated with the given key.\n *\n * @param key the key to the cell holding the desired element\n * @return the element\n */\n @Override\n public CharSequence getFully(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getFully(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Return the element that is stored as last on a path belonging to the given key.\n *\n * @param key the key associated with the desired element\n * @return the element that is stored as last on a path\n */\n @Override\n public CharSequence getLastOnPath(CharSequence key) {\n StringBuilder result = new StringBuilder(tries.size() * 2);\n try {\n CharSequence lastkey = key;\n CharSequence[] p = new CharSequence[tries.size()];\n char lastch = ' ';\n for (int i = 0; i < tries.size(); i++) {\n CharSequence r = tries.get(i).getLastOnPath(lastkey);\n if (r == null || (r.length() == 1 && r.charAt(0) == EOM)) {\n return result;\n }\n if (cannotFollow(lastch, r.charAt(0))) {\n return result;\n } else {\n lastch = r.charAt(r.length() - 2);\n }\n p[i] = r;\n if (p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n result.append(r);\n if (key.length() != 0) {\n lastkey = key;\n }\n }\n } catch (@SuppressWarnings(\"unused\") IndexOutOfBoundsException x) {\n }\n return result;\n }\n\n /**\n * Write this data structure to the given output stream.\n *\n * @param os the output stream\n * @exception IOException if an I/O error occurs\n */\n @Override\n public void store(DataOutput os) throws IOException {\n super.store(os);\n }\n\n /**\n * Add an element to this structure consisting of the given key and patch command.\n *\n *

This method will return without executing if the cmd parameter's length is 0.\n *\n * @param key the key\n * @param cmd the patch command\n */\n @Override\n public void add(CharSequence key, CharSequence cmd) {\n if (cmd.length() == 0) {\n return;\n }\n CharSequence[] p = decompose(cmd);\n int levels = p.length;\n while (levels >= tries.size()) {\n tries.add(new Trie(forward));\n }\n CharSequence lastkey = key;\n for (int i = 0; i < levels; i++) {\n if (key.length() > 0) {\n tries.get(i).add(key, p[i]);\n lastkey = key;\n } else {\n tries.get(i).add(lastkey, p[i]);\n }\n if (p[i].length() > 0 && p[i].charAt(0) == '-') {\n if (i > 0) {\n key = skip(key, lengthPP(p[i - 1]));\n }\n key = skip(key, lengthPP(p[i]));\n }\n }\n if (key.length() > 0) {\n tries.get(levels).add(key, EOM_NODE);\n } else {\n tries.get(levels).add(lastkey, EOM_NODE);\n }\n }\n\n /**\n * Break the given patch command into its constituent pieces. The pieces are delimited by NOOP\n * commands.\n *\n * @param cmd the patch command\n * @return an array containing the pieces of the command\n */\n public CharSequence[] decompose(CharSequence cmd) {\n int parts = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n parts++;\n i = next + 2;\n } else {\n parts++;\n i = next;\n }\n }\n CharSequence[] part = new CharSequence[parts];\n int x = 0;\n for (int i = 0; 0 <= i && i < cmd.length(); ) {\n int next = dashEven(cmd, i);\n if (i == next) {\n part[x++] = cmd.subSequence(i, i + 2);\n i = next + 2;\n } else {\n part[x++] = (next < 0) ? cmd.subSequence(i, cmd.length()) : cmd.subSequence(i, next);\n i = next;\n }\n }\n return part;\n }\n\n /**\n * Remove empty rows from the given Trie and return the newly reduced Trie.\n *\n * @param by the Trie to reduce\n * @return the newly reduced Trie\n */\n @Override\n public Trie reduce(Reduce by) {\n List h = new ArrayList<>();\n for (Trie trie : tries) h.add(trie.reduce(by));\n MultiTrie2 m = new MultiTrie2(forward);\n m.tries = h;\n return m;\n }\n\n private boolean cannotFollow(char after, char goes) {\n switch(after) {\n case '-':\n case 'D':\n return after == goes;\n }\n return false;\n }\n\n private CharSequence skip(CharSequence in, int count) {\n if (forward) {\n return in.subSequence(count, in.length());\n } else {\n return in.subSequence(0, in.length() - count);\n }\n }\n\n private int dashEven(CharSequence in, int from) {\n ", "post_mask_code": "\n return -1;\n }\n\n @SuppressWarnings(\"fallthrough\")\n private int lengthPP(CharSequence cmd) {\n int len = 0;\n for (int i = 0; i < cmd.length(); i++) {\n switch(cmd.charAt(i++)) {\n case '-':\n case 'D':\n len += cmd.charAt(i) - 'a' + 1;\n break;\n case 'R':\n len++;\n /* intentional fallthrough */\n case 'I':\n break;\n }\n }\n return len;\n }\n}\n"} {"task_id": "Java_2714", "language": "Java", "task_type": "method_signature", "source_file": "java/github/csob/paymentgateway/Integration Examples/eAPI v1.5/java/eAPI-v15-connector/src/main/java/cz/monetplus/mips/eapi/v15/modes/PaymentProcessMode.java", "mask_start_position": 803, "mask_end_position": 854, "canonical_solution": "@Override\n public void proc(ArgsConfig aConfig) ", "pre_mask_code": "package cz.monetplus.mips.eapi.v15.modes;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport cz.monetplus.mips.eapi.v15.ArgsConfig;\nimport cz.monetplus.mips.eapi.v15.RunMode;\nimport cz.monetplus.mips.eapi.v15.ArgsConfig.RunModeEnum;\nimport cz.monetplus.mips.eapi.v15.service.MipsException;\nimport cz.monetplus.mips.eapi.v15.service.NativeApiV15Service;\nimport cz.monetplus.mips.eapi.v15.service.RespCode;\n\n@Component\npublic class PaymentProcessMode implements RunMode {\n\n private static final Logger LOG = LoggerFactory.getLogger(PaymentProcessMode.class);\n\n @Autowired\n private NativeApiV15Service nativeApiV1Service;\n\n ", "post_mask_code": "{\n try {\n if (StringUtils.trimToNull(aConfig.payId) == null) {\n throw new MipsException(RespCode.INVALID_PARAM, \"Missing mandatory parameter payId\");\n }\n String address = nativeApiV1Service.paymentProcess(aConfig.payId);\n LOG.info(\"To open payment in web browser go to \" + address);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public RunModeEnum getMode() {\n return RunModeEnum.PAYMENT_PROCESS;\n }\n}\n"} {"task_id": "Java_2715", "language": "Java", "task_type": "method_body", "source_file": "java/github/csob/paymentgateway/Integration Examples/eAPI v1.5/java/eAPI-v15-connector/src/main/java/cz/monetplus/mips/eapi/v15/modes/PaymentProcessMode.java", "mask_start_position": 1342, "mask_end_position": 1393, "canonical_solution": "{\n return RunModeEnum.PAYMENT_PROCESS;\n }", "pre_mask_code": "package cz.monetplus.mips.eapi.v15.modes;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport cz.monetplus.mips.eapi.v15.ArgsConfig;\nimport cz.monetplus.mips.eapi.v15.RunMode;\nimport cz.monetplus.mips.eapi.v15.ArgsConfig.RunModeEnum;\nimport cz.monetplus.mips.eapi.v15.service.MipsException;\nimport cz.monetplus.mips.eapi.v15.service.NativeApiV15Service;\nimport cz.monetplus.mips.eapi.v15.service.RespCode;\n\n@Component\npublic class PaymentProcessMode implements RunMode {\n\n private static final Logger LOG = LoggerFactory.getLogger(PaymentProcessMode.class);\n\n @Autowired\n private NativeApiV15Service nativeApiV1Service;\n\n @Override\n public void proc(ArgsConfig aConfig) {\n try {\n if (StringUtils.trimToNull(aConfig.payId) == null) {\n throw new MipsException(RespCode.INVALID_PARAM, \"Missing mandatory parameter payId\");\n }\n String address = nativeApiV1Service.paymentProcess(aConfig.payId);\n LOG.info(\"To open payment in web browser go to \" + address);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public RunModeEnum getMode() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2716", "language": "Java", "task_type": "single_line", "source_file": "java/github/csob/paymentgateway/Integration Examples/eAPI v1.5/java/eAPI-v15-connector/src/main/java/cz/monetplus/mips/eapi/v15/modes/PaymentProcessMode.java", "mask_start_position": 1359, "mask_end_position": 1387, "canonical_solution": "RunModeEnum.PAYMENT_PROCESS;", "pre_mask_code": "package cz.monetplus.mips.eapi.v15.modes;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport cz.monetplus.mips.eapi.v15.ArgsConfig;\nimport cz.monetplus.mips.eapi.v15.RunMode;\nimport cz.monetplus.mips.eapi.v15.ArgsConfig.RunModeEnum;\nimport cz.monetplus.mips.eapi.v15.service.MipsException;\nimport cz.monetplus.mips.eapi.v15.service.NativeApiV15Service;\nimport cz.monetplus.mips.eapi.v15.service.RespCode;\n\n@Component\npublic class PaymentProcessMode implements RunMode {\n\n private static final Logger LOG = LoggerFactory.getLogger(PaymentProcessMode.class);\n\n @Autowired\n private NativeApiV15Service nativeApiV1Service;\n\n @Override\n public void proc(ArgsConfig aConfig) {\n try {\n if (StringUtils.trimToNull(aConfig.payId) == null) {\n throw new MipsException(RespCode.INVALID_PARAM, \"Missing mandatory parameter payId\");\n }\n String address = nativeApiV1Service.paymentProcess(aConfig.payId);\n LOG.info(\"To open payment in web browser go to \" + address);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public RunModeEnum getMode() {\n return ", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2717", "language": "Java", "task_type": "try_statement", "source_file": "java/github/csob/paymentgateway/Integration Examples/eAPI v1.5/java/eAPI-v15-connector/src/main/java/cz/monetplus/mips/eapi/v15/modes/PaymentProcessMode.java", "mask_start_position": 864, "mask_end_position": 1287, "canonical_solution": "try {\n if (StringUtils.trimToNull(aConfig.payId) == null) {\n throw new MipsException(RespCode.INVALID_PARAM, \"Missing mandatory parameter payId\");\n }\n String address = nativeApiV1Service.paymentProcess(aConfig.payId);\n LOG.info(\"To open payment in web browser go to \" + address);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }", "pre_mask_code": "package cz.monetplus.mips.eapi.v15.modes;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport cz.monetplus.mips.eapi.v15.ArgsConfig;\nimport cz.monetplus.mips.eapi.v15.RunMode;\nimport cz.monetplus.mips.eapi.v15.ArgsConfig.RunModeEnum;\nimport cz.monetplus.mips.eapi.v15.service.MipsException;\nimport cz.monetplus.mips.eapi.v15.service.NativeApiV15Service;\nimport cz.monetplus.mips.eapi.v15.service.RespCode;\n\n@Component\npublic class PaymentProcessMode implements RunMode {\n\n private static final Logger LOG = LoggerFactory.getLogger(PaymentProcessMode.class);\n\n @Autowired\n private NativeApiV15Service nativeApiV1Service;\n\n @Override\n public void proc(ArgsConfig aConfig) {\n ", "post_mask_code": "\n }\n\n @Override\n public RunModeEnum getMode() {\n return RunModeEnum.PAYMENT_PROCESS;\n }\n}\n"} {"task_id": "Java_2718", "language": "Java", "task_type": "method_signature", "source_file": "java/github/mcekovic/tennis-crystal-ball/tennis-stats/src/main/java/org/strangeforest/tcb/stats/jobs/RefreshComputedDataJob.java", "mask_start_position": 964, "mask_end_position": 991, "canonical_solution": "private void clearCaches() ", "pre_mask_code": "package org.strangeforest.tcb.stats.jobs;\n\nimport org.slf4j.*;\nimport org.springframework.beans.factory.annotation.*;\nimport org.springframework.context.annotation.*;\nimport org.springframework.scheduling.annotation.*;\nimport org.springframework.stereotype.*;\nimport org.strangeforest.tcb.stats.service.*;\n\n@Component\n@Profile(\"jobs\")\npublic class RefreshComputedDataJob {\n\n @Autowired\n private DataLoadCommand dataLoadCommand;\n\n @Autowired\n private DataService dataService;\n\n private static final Logger LOGGER = LoggerFactory.getLogger(RefreshComputedDataJob.class);\n\n @Scheduled(cron = \"${tennis-stats.jobs.refresh-computed-data:0 52 5 * * MON}\")\n public void refreshComputedData() {\n if (dataLoadCommand.execute(\"RefreshComputedData\", \"-rc\", \"-c 1\") == 0) {\n try {\n dataLoadCommand.execute(\"Vacuum\", \"-vc\", \"-c 1\");\n } finally {\n clearCaches();\n }\n }\n }\n\n ", "post_mask_code": "{\n var cacheCount = dataService.clearCaches(\".*\");\n LOGGER.info(\"{} cache(s) cleared.\", cacheCount);\n }\n}\n"} {"task_id": "Java_2719", "language": "Java", "task_type": "method_body", "source_file": "java/github/mcekovic/tennis-crystal-ball/tennis-stats/src/main/java/org/strangeforest/tcb/stats/jobs/RefreshComputedDataJob.java", "mask_start_position": 991, "mask_end_position": 1111, "canonical_solution": "{\n var cacheCount = dataService.clearCaches(\".*\");\n LOGGER.info(\"{} cache(s) cleared.\", cacheCount);\n }", "pre_mask_code": "package org.strangeforest.tcb.stats.jobs;\n\nimport org.slf4j.*;\nimport org.springframework.beans.factory.annotation.*;\nimport org.springframework.context.annotation.*;\nimport org.springframework.scheduling.annotation.*;\nimport org.springframework.stereotype.*;\nimport org.strangeforest.tcb.stats.service.*;\n\n@Component\n@Profile(\"jobs\")\npublic class RefreshComputedDataJob {\n\n @Autowired\n private DataLoadCommand dataLoadCommand;\n\n @Autowired\n private DataService dataService;\n\n private static final Logger LOGGER = LoggerFactory.getLogger(RefreshComputedDataJob.class);\n\n @Scheduled(cron = \"${tennis-stats.jobs.refresh-computed-data:0 52 5 * * MON}\")\n public void refreshComputedData() {\n if (dataLoadCommand.execute(\"RefreshComputedData\", \"-rc\", \"-c 1\") == 0) {\n try {\n dataLoadCommand.execute(\"Vacuum\", \"-vc\", \"-c 1\");\n } finally {\n clearCaches();\n }\n }\n }\n\n private void clearCaches() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2720", "language": "Java", "task_type": "single_line", "source_file": "java/github/mcekovic/tennis-crystal-ball/tennis-stats/src/main/java/org/strangeforest/tcb/stats/jobs/RefreshComputedDataJob.java", "mask_start_position": 1078, "mask_end_position": 1105, "canonical_solution": "(s) cleared.\", cacheCount);", "pre_mask_code": "package org.strangeforest.tcb.stats.jobs;\n\nimport org.slf4j.*;\nimport org.springframework.beans.factory.annotation.*;\nimport org.springframework.context.annotation.*;\nimport org.springframework.scheduling.annotation.*;\nimport org.springframework.stereotype.*;\nimport org.strangeforest.tcb.stats.service.*;\n\n@Component\n@Profile(\"jobs\")\npublic class RefreshComputedDataJob {\n\n @Autowired\n private DataLoadCommand dataLoadCommand;\n\n @Autowired\n private DataService dataService;\n\n private static final Logger LOGGER = LoggerFactory.getLogger(RefreshComputedDataJob.class);\n\n @Scheduled(cron = \"${tennis-stats.jobs.refresh-computed-data:0 52 5 * * MON}\")\n public void refreshComputedData() {\n if (dataLoadCommand.execute(\"RefreshComputedData\", \"-rc\", \"-c 1\") == 0) {\n try {\n dataLoadCommand.execute(\"Vacuum\", \"-vc\", \"-c 1\");\n } finally {\n clearCaches();\n }\n }\n }\n\n private void clearCaches() {\n var cacheCount = dataService.clearCaches(\".*\");\n LOGGER.info(\"{} cache", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2721", "language": "Java", "task_type": "try_statement", "source_file": "java/github/mcekovic/tennis-crystal-ball/tennis-stats/src/main/java/org/strangeforest/tcb/stats/jobs/RefreshComputedDataJob.java", "mask_start_position": 802, "mask_end_position": 942, "canonical_solution": "try {\n dataLoadCommand.execute(\"Vacuum\", \"-vc\", \"-c 1\");\n } finally {\n clearCaches();\n }", "pre_mask_code": "package org.strangeforest.tcb.stats.jobs;\n\nimport org.slf4j.*;\nimport org.springframework.beans.factory.annotation.*;\nimport org.springframework.context.annotation.*;\nimport org.springframework.scheduling.annotation.*;\nimport org.springframework.stereotype.*;\nimport org.strangeforest.tcb.stats.service.*;\n\n@Component\n@Profile(\"jobs\")\npublic class RefreshComputedDataJob {\n\n @Autowired\n private DataLoadCommand dataLoadCommand;\n\n @Autowired\n private DataService dataService;\n\n private static final Logger LOGGER = LoggerFactory.getLogger(RefreshComputedDataJob.class);\n\n @Scheduled(cron = \"${tennis-stats.jobs.refresh-computed-data:0 52 5 * * MON}\")\n public void refreshComputedData() {\n if (dataLoadCommand.execute(\"RefreshComputedData\", \"-rc\", \"-c 1\") == 0) {\n ", "post_mask_code": "\n }\n }\n\n private void clearCaches() {\n var cacheCount = dataService.clearCaches(\".*\");\n LOGGER.info(\"{} cache(s) cleared.\", cacheCount);\n }\n}\n"} {"task_id": "Java_2722", "language": "Java", "task_type": "method_signature", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/kernel/a/b.java", "mask_start_position": 1389, "mask_end_position": 1452, "canonical_solution": "public final /* synthetic */\n Object aq(Object obj) ", "pre_mask_code": "package com.tencent.mm.kernel.a;\n\nimport com.tencent.mm.kernel.f;\nimport com.tencent.mm.kernel.plugin.ProcessProfile;\nimport com.tencent.mm.sdk.platformtools.v;\nimport com.tencent.mm.vending.c.a;\nimport com.tencent.mm.vending.g.c;\nimport com.tencent.mm.vending.g.d;\nimport com.tencent.mm.vending.g.g;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport junit.framework.Assert;\n\npublic final class b {\n\n private f cjN = new f();\n\n private boolean cld = false;\n\n private HashMap, e> cle = new HashMap();\n\n public c clf;\n\n protected final synchronized d a(com.tencent.mm.vending.h.d dVar) {\n c bp;\n final long currentTimeMillis = System.currentTimeMillis();\n a(\"boot start to execute task on scheduler [%s]...\", dVar.getType());\n this.cld = true;\n final ArrayList vq = this.cjN.vq();\n a(\"boot task execution chain ... %s\", vq);\n ArrayList vp = this.cjN.vp();\n if (vp.size() > 0) {\n throw new RuntimeException(\"Found cycle dependencies! Between \" + vp);\n }\n a(\"boot check tasks cycle dependency ok...\", new Object[0]);\n bp = g.bKO().bp(true);\n final ProcessProfile uZ = com.tencent.mm.kernel.g.vt().uZ();\n bp.b(dVar).c(new a(this) {\n\n final b /* synthetic */\n clh;\n\n ", "post_mask_code": "{\n Iterator it = vq.iterator();\n while (it.hasNext()) {\n b.a((e) it.next(), uZ);\n }\n b.a(\"boot task execution all done in [%s].\", b.H(currentTimeMillis));\n return null;\n }\n });\n return bp.bKK();\n }\n\n public static void a(e eVar, ProcessProfile processProfile) {\n a(\"boot task executing [%s]...\", eVar);\n eVar.execute(processProfile);\n }\n\n public final synchronized void a(e eVar, e eVar2) {\n Assert.assertNotNull(eVar);\n if (!this.cle.containsKey(eVar.getClass())) {\n this.cle.put(eVar.getClass(), eVar);\n }\n this.cjN.n(eVar, eVar2);\n }\n\n public static final void a(String str, Object... objArr) {\n if (objArr.length == 0) {\n v.i(\"MMKernel.Boot\", str);\n } else {\n v.i(\"MMKernel.Boot\", str, objArr);\n }\n }\n\n public static String H(long j) {\n return (System.currentTimeMillis() - j) + \"ms\";\n }\n}\n"} {"task_id": "Java_2723", "language": "Java", "task_type": "method_body", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/kernel/a/b.java", "mask_start_position": 1837, "mask_end_position": 1930, "canonical_solution": "{\n a(\"boot task executing [%s]...\", eVar);\n eVar.execute(processProfile);\n }", "pre_mask_code": "package com.tencent.mm.kernel.a;\n\nimport com.tencent.mm.kernel.f;\nimport com.tencent.mm.kernel.plugin.ProcessProfile;\nimport com.tencent.mm.sdk.platformtools.v;\nimport com.tencent.mm.vending.c.a;\nimport com.tencent.mm.vending.g.c;\nimport com.tencent.mm.vending.g.d;\nimport com.tencent.mm.vending.g.g;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport junit.framework.Assert;\n\npublic final class b {\n\n private f cjN = new f();\n\n private boolean cld = false;\n\n private HashMap, e> cle = new HashMap();\n\n public c clf;\n\n protected final synchronized d a(com.tencent.mm.vending.h.d dVar) {\n c bp;\n final long currentTimeMillis = System.currentTimeMillis();\n a(\"boot start to execute task on scheduler [%s]...\", dVar.getType());\n this.cld = true;\n final ArrayList vq = this.cjN.vq();\n a(\"boot task execution chain ... %s\", vq);\n ArrayList vp = this.cjN.vp();\n if (vp.size() > 0) {\n throw new RuntimeException(\"Found cycle dependencies! Between \" + vp);\n }\n a(\"boot check tasks cycle dependency ok...\", new Object[0]);\n bp = g.bKO().bp(true);\n final ProcessProfile uZ = com.tencent.mm.kernel.g.vt().uZ();\n bp.b(dVar).c(new a(this) {\n\n final b /* synthetic */\n clh;\n\n public final /* synthetic */\n Object aq(Object obj) {\n Iterator it = vq.iterator();\n while (it.hasNext()) {\n b.a((e) it.next(), uZ);\n }\n b.a(\"boot task execution all done in [%s].\", b.H(currentTimeMillis));\n return null;\n }\n });\n return bp.bKK();\n }\n\n public static void a(e eVar, ProcessProfile processProfile) ", "post_mask_code": "\n\n public final synchronized void a(e eVar, e eVar2) {\n Assert.assertNotNull(eVar);\n if (!this.cle.containsKey(eVar.getClass())) {\n this.cle.put(eVar.getClass(), eVar);\n }\n this.cjN.n(eVar, eVar2);\n }\n\n public static final void a(String str, Object... objArr) {\n if (objArr.length == 0) {\n v.i(\"MMKernel.Boot\", str);\n } else {\n v.i(\"MMKernel.Boot\", str, objArr);\n }\n }\n\n public static String H(long j) {\n return (System.currentTimeMillis() - j) + \"ms\";\n }\n}\n"} {"task_id": "Java_2724", "language": "Java", "task_type": "single_line", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/kernel/a/b.java", "mask_start_position": 1124, "mask_end_position": 1174, "canonical_solution": "eck tasks cycle dependency ok...\", new Object[0]);", "pre_mask_code": "package com.tencent.mm.kernel.a;\n\nimport com.tencent.mm.kernel.f;\nimport com.tencent.mm.kernel.plugin.ProcessProfile;\nimport com.tencent.mm.sdk.platformtools.v;\nimport com.tencent.mm.vending.c.a;\nimport com.tencent.mm.vending.g.c;\nimport com.tencent.mm.vending.g.d;\nimport com.tencent.mm.vending.g.g;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport junit.framework.Assert;\n\npublic final class b {\n\n private f cjN = new f();\n\n private boolean cld = false;\n\n private HashMap, e> cle = new HashMap();\n\n public c clf;\n\n protected final synchronized d a(com.tencent.mm.vending.h.d dVar) {\n c bp;\n final long currentTimeMillis = System.currentTimeMillis();\n a(\"boot start to execute task on scheduler [%s]...\", dVar.getType());\n this.cld = true;\n final ArrayList vq = this.cjN.vq();\n a(\"boot task execution chain ... %s\", vq);\n ArrayList vp = this.cjN.vp();\n if (vp.size() > 0) {\n throw new RuntimeException(\"Found cycle dependencies! Between \" + vp);\n }\n a(\"boot ch", "post_mask_code": "\n bp = g.bKO().bp(true);\n final ProcessProfile uZ = com.tencent.mm.kernel.g.vt().uZ();\n bp.b(dVar).c(new a(this) {\n\n final b /* synthetic */\n clh;\n\n public final /* synthetic */\n Object aq(Object obj) {\n Iterator it = vq.iterator();\n while (it.hasNext()) {\n b.a((e) it.next(), uZ);\n }\n b.a(\"boot task execution all done in [%s].\", b.H(currentTimeMillis));\n return null;\n }\n });\n return bp.bKK();\n }\n\n public static void a(e eVar, ProcessProfile processProfile) {\n a(\"boot task executing [%s]...\", eVar);\n eVar.execute(processProfile);\n }\n\n public final synchronized void a(e eVar, e eVar2) {\n Assert.assertNotNull(eVar);\n if (!this.cle.containsKey(eVar.getClass())) {\n this.cle.put(eVar.getClass(), eVar);\n }\n this.cjN.n(eVar, eVar2);\n }\n\n public static final void a(String str, Object... objArr) {\n if (objArr.length == 0) {\n v.i(\"MMKernel.Boot\", str);\n } else {\n v.i(\"MMKernel.Boot\", str, objArr);\n }\n }\n\n public static String H(long j) {\n return (System.currentTimeMillis() - j) + \"ms\";\n }\n}\n"} {"task_id": "Java_2725", "language": "Java", "task_type": "while_statement", "source_file": "java/github/zhangxhbeta/wechat6.5.3/app/src/main/wechat6.5.3/com/tencent/mm/kernel/a/b.java", "mask_start_position": 1515, "mask_end_position": 1599, "canonical_solution": "while (it.hasNext()) {\n b.a((e) it.next(), uZ);\n }", "pre_mask_code": "package com.tencent.mm.kernel.a;\n\nimport com.tencent.mm.kernel.f;\nimport com.tencent.mm.kernel.plugin.ProcessProfile;\nimport com.tencent.mm.sdk.platformtools.v;\nimport com.tencent.mm.vending.c.a;\nimport com.tencent.mm.vending.g.c;\nimport com.tencent.mm.vending.g.d;\nimport com.tencent.mm.vending.g.g;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport junit.framework.Assert;\n\npublic final class b {\n\n private f cjN = new f();\n\n private boolean cld = false;\n\n private HashMap, e> cle = new HashMap();\n\n public c clf;\n\n protected final synchronized d a(com.tencent.mm.vending.h.d dVar) {\n c bp;\n final long currentTimeMillis = System.currentTimeMillis();\n a(\"boot start to execute task on scheduler [%s]...\", dVar.getType());\n this.cld = true;\n final ArrayList vq = this.cjN.vq();\n a(\"boot task execution chain ... %s\", vq);\n ArrayList vp = this.cjN.vp();\n if (vp.size() > 0) {\n throw new RuntimeException(\"Found cycle dependencies! Between \" + vp);\n }\n a(\"boot check tasks cycle dependency ok...\", new Object[0]);\n bp = g.bKO().bp(true);\n final ProcessProfile uZ = com.tencent.mm.kernel.g.vt().uZ();\n bp.b(dVar).c(new a(this) {\n\n final b /* synthetic */\n clh;\n\n public final /* synthetic */\n Object aq(Object obj) {\n Iterator it = vq.iterator();\n ", "post_mask_code": "\n b.a(\"boot task execution all done in [%s].\", b.H(currentTimeMillis));\n return null;\n }\n });\n return bp.bKK();\n }\n\n public static void a(e eVar, ProcessProfile processProfile) {\n a(\"boot task executing [%s]...\", eVar);\n eVar.execute(processProfile);\n }\n\n public final synchronized void a(e eVar, e eVar2) {\n Assert.assertNotNull(eVar);\n if (!this.cle.containsKey(eVar.getClass())) {\n this.cle.put(eVar.getClass(), eVar);\n }\n this.cjN.n(eVar, eVar2);\n }\n\n public static final void a(String str, Object... objArr) {\n if (objArr.length == 0) {\n v.i(\"MMKernel.Boot\", str);\n } else {\n v.i(\"MMKernel.Boot\", str, objArr);\n }\n }\n\n public static String H(long j) {\n return (System.currentTimeMillis() - j) + \"ms\";\n }\n}\n"} {"task_id": "Java_2726", "language": "Java", "task_type": "method_signature", "source_file": "java/github/liferay/liferay-portal/portal-impl/src/com/liferay/portal/security/pwd/CompositePasswordEncryptor.java", "mask_start_position": 1081, "mask_end_position": 1216, "canonical_solution": "@Override\n public String encrypt(String algorithm, String plainTextPassword, String encryptedPassword) throws PwdEncryptorException ", "pre_mask_code": "package com.liferay.portal.security.pwd;\n\nimport com.liferay.petra.string.CharPool;\nimport com.liferay.petra.string.StringBundler;\nimport com.liferay.petra.string.StringPool;\nimport com.liferay.portal.kernel.exception.PwdEncryptorException;\nimport com.liferay.portal.kernel.log.Log;\nimport com.liferay.portal.kernel.log.LogFactoryUtil;\nimport com.liferay.portal.kernel.security.pwd.PasswordEncryptor;\nimport com.liferay.portal.kernel.security.pwd.PasswordEncryptorUtil;\nimport com.liferay.portal.kernel.util.ClassUtil;\nimport com.liferay.portal.kernel.util.StringUtil;\nimport com.liferay.portal.kernel.util.Validator;\nimport com.liferay.portal.util.PropsValues;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * @author Michael C. Han\n */\npublic class CompositePasswordEncryptor extends BasePasswordEncryptor implements PasswordEncryptor {\n\n public void afterPropertiesSet() {\n if (_defaultAlgorithmPasswordEncryptor == null) {\n _defaultAlgorithmPasswordEncryptor = _select(getDefaultPasswordAlgorithmType());\n }\n }\n\n ", "post_mask_code": "{\n if (Validator.isNull(plainTextPassword)) {\n throw new PwdEncryptorException(\"Unable to encrypt blank password\");\n }\n String legacyAlgorithm = PropsValues.PASSWORDS_ENCRYPTION_ALGORITHM_LEGACY;\n if (_log.isDebugEnabled() && Validator.isNotNull(legacyAlgorithm)) {\n if (Validator.isNull(encryptedPassword)) {\n _log.debug(StringBundler.concat(\"Using legacy detection scheme for algorithm \", legacyAlgorithm, \" with empty current password\"));\n } else {\n _log.debug(StringBundler.concat(\"Using legacy detection scheme for algorithm \", legacyAlgorithm, \" with provided current password\"));\n }\n }\n boolean prependAlgorithm = true;\n if (Validator.isNotNull(encryptedPassword) && (encryptedPassword.charAt(0) != CharPool.OPEN_CURLY_BRACE)) {\n algorithm = legacyAlgorithm;\n prependAlgorithm = false;\n if (_log.isDebugEnabled()) {\n _log.debug(\"Using legacy algorithm \" + algorithm);\n }\n } else if (Validator.isNotNull(encryptedPassword) && (encryptedPassword.charAt(0) == CharPool.OPEN_CURLY_BRACE)) {\n int index = encryptedPassword.indexOf(CharPool.CLOSE_CURLY_BRACE);\n if (index > 0) {\n algorithm = encryptedPassword.substring(1, index);\n encryptedPassword = encryptedPassword.substring(index + 1);\n }\n if (_log.isDebugEnabled()) {\n _log.debug(\"Upgraded password to use algorithm \" + algorithm);\n }\n }\n if (Validator.isNull(algorithm)) {\n algorithm = getDefaultPasswordAlgorithmType();\n }\n PasswordEncryptor passwordEncryptor = _select(algorithm);\n String newEncryptedPassword = passwordEncryptor.encrypt(algorithm, plainTextPassword, encryptedPassword);\n if (!prependAlgorithm) {\n if (_log.isDebugEnabled()) {\n _log.debug(\"Generated password without algorithm prefix using \" + algorithm);\n }\n return newEncryptedPassword;\n }\n if (_log.isDebugEnabled()) {\n _log.debug(\"Generated password with algorithm prefix using \" + algorithm);\n }\n return StringBundler.concat(StringPool.OPEN_CURLY_BRACE, _getAlgorithmName(algorithm), StringPool.CLOSE_CURLY_BRACE, newEncryptedPassword);\n }\n\n @Override\n public String[] getSupportedAlgorithmTypes() {\n throw new UnsupportedOperationException();\n }\n\n public void setDefaultPasswordEncryptor(PasswordEncryptor defaultPasswordEncryptor) {\n _defaultPasswordEncryptor = defaultPasswordEncryptor;\n }\n\n public void setPasswordEncryptors(List passwordEncryptors) {\n for (PasswordEncryptor passwordEncryptor : passwordEncryptors) {\n if (_log.isDebugEnabled()) {\n _log.debug(\"Registering \" + passwordEncryptor);\n }\n String[] supportedAlgorithmTypes = passwordEncryptor.getSupportedAlgorithmTypes();\n if (_log.isDebugEnabled()) {\n Class clazz = passwordEncryptor.getClass();\n _log.debug(StringBundler.concat(\"Registering \", StringUtil.merge(supportedAlgorithmTypes), \" for \", clazz.getName()));\n }\n for (String supportedAlgorithmType : supportedAlgorithmTypes) {\n _passwordEncryptors.put(supportedAlgorithmType, passwordEncryptor);\n }\n }\n }\n\n private String _getAlgorithmName(String algorithm) {\n int index = algorithm.indexOf(CharPool.SLASH);\n if (index > 0) {\n return algorithm.substring(0, index);\n }\n return algorithm;\n }\n\n private PasswordEncryptor _select(String algorithm) {\n if (Validator.isNull(algorithm)) {\n throw new IllegalArgumentException(\"Invalid algorithm\");\n }\n PasswordEncryptor passwordEncryptor = null;\n if (algorithm.startsWith(PasswordEncryptorUtil.TYPE_BCRYPT)) {\n passwordEncryptor = _passwordEncryptors.get(PasswordEncryptorUtil.TYPE_BCRYPT);\n } else if (algorithm.startsWith(PasswordEncryptorUtil.TYPE_PBKDF2)) {\n passwordEncryptor = _passwordEncryptors.get(PasswordEncryptorUtil.TYPE_PBKDF2);\n } else {\n passwordEncryptor = _passwordEncryptors.get(algorithm);\n }\n if (passwordEncryptor == null) {\n if (_log.isDebugEnabled()) {\n _log.debug(\"No password encryptor found for \" + algorithm);\n }\n passwordEncryptor = _defaultPasswordEncryptor;\n }\n if (_log.isDebugEnabled()) {\n _log.debug(StringBundler.concat(\"Found \", ClassUtil.getClassName(passwordEncryptor), \" to encrypt password using \", algorithm));\n }\n return passwordEncryptor;\n }\n\n private static final Log _log = LogFactoryUtil.getLog(CompositePasswordEncryptor.class);\n\n private PasswordEncryptor _defaultAlgorithmPasswordEncryptor;\n\n private PasswordEncryptor _defaultPasswordEncryptor;\n\n private final Map _passwordEncryptors = new HashMap<>();\n}\n"} {"task_id": "Java_2727", "language": "Java", "task_type": "method_body", "source_file": "java/github/liferay/liferay-portal/portal-impl/src/com/liferay/portal/security/pwd/CompositePasswordEncryptor.java", "mask_start_position": 907, "mask_end_position": 1075, "canonical_solution": "{\n if (_defaultAlgorithmPasswordEncryptor == null) {\n _defaultAlgorithmPasswordEncryptor = _select(getDefaultPasswordAlgorithmType());\n }\n }", "pre_mask_code": "package com.liferay.portal.security.pwd;\n\nimport com.liferay.petra.string.CharPool;\nimport com.liferay.petra.string.StringBundler;\nimport com.liferay.petra.string.StringPool;\nimport com.liferay.portal.kernel.exception.PwdEncryptorException;\nimport com.liferay.portal.kernel.log.Log;\nimport com.liferay.portal.kernel.log.LogFactoryUtil;\nimport com.liferay.portal.kernel.security.pwd.PasswordEncryptor;\nimport com.liferay.portal.kernel.security.pwd.PasswordEncryptorUtil;\nimport com.liferay.portal.kernel.util.ClassUtil;\nimport com.liferay.portal.kernel.util.StringUtil;\nimport com.liferay.portal.kernel.util.Validator;\nimport com.liferay.portal.util.PropsValues;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * @author Michael C. Han\n */\npublic class CompositePasswordEncryptor extends BasePasswordEncryptor implements PasswordEncryptor {\n\n public void afterPropertiesSet() ", "post_mask_code": "\n\n @Override\n public String encrypt(String algorithm, String plainTextPassword, String encryptedPassword) throws PwdEncryptorException {\n if (Validator.isNull(plainTextPassword)) {\n throw new PwdEncryptorException(\"Unable to encrypt blank password\");\n }\n String legacyAlgorithm = PropsValues.PASSWORDS_ENCRYPTION_ALGORITHM_LEGACY;\n if (_log.isDebugEnabled() && Validator.isNotNull(legacyAlgorithm)) {\n if (Validator.isNull(encryptedPassword)) {\n _log.debug(StringBundler.concat(\"Using legacy detection scheme for algorithm \", legacyAlgorithm, \" with empty current password\"));\n } else {\n _log.debug(StringBundler.concat(\"Using legacy detection scheme for algorithm \", legacyAlgorithm, \" with provided current password\"));\n }\n }\n boolean prependAlgorithm = true;\n if (Validator.isNotNull(encryptedPassword) && (encryptedPassword.charAt(0) != CharPool.OPEN_CURLY_BRACE)) {\n algorithm = legacyAlgorithm;\n prependAlgorithm = false;\n if (_log.isDebugEnabled()) {\n _log.debug(\"Using legacy algorithm \" + algorithm);\n }\n } else if (Validator.isNotNull(encryptedPassword) && (encryptedPassword.charAt(0) == CharPool.OPEN_CURLY_BRACE)) {\n int index = encryptedPassword.indexOf(CharPool.CLOSE_CURLY_BRACE);\n if (index > 0) {\n algorithm = encryptedPassword.substring(1, index);\n encryptedPassword = encryptedPassword.substring(index + 1);\n }\n if (_log.isDebugEnabled()) {\n _log.debug(\"Upgraded password to use algorithm \" + algorithm);\n }\n }\n if (Validator.isNull(algorithm)) {\n algorithm = getDefaultPasswordAlgorithmType();\n }\n PasswordEncryptor passwordEncryptor = _select(algorithm);\n String newEncryptedPassword = passwordEncryptor.encrypt(algorithm, plainTextPassword, encryptedPassword);\n if (!prependAlgorithm) {\n if (_log.isDebugEnabled()) {\n _log.debug(\"Generated password without algorithm prefix using \" + algorithm);\n }\n return newEncryptedPassword;\n }\n if (_log.isDebugEnabled()) {\n _log.debug(\"Generated password with algorithm prefix using \" + algorithm);\n }\n return StringBundler.concat(StringPool.OPEN_CURLY_BRACE, _getAlgorithmName(algorithm), StringPool.CLOSE_CURLY_BRACE, newEncryptedPassword);\n }\n\n @Override\n public String[] getSupportedAlgorithmTypes() {\n throw new UnsupportedOperationException();\n }\n\n public void setDefaultPasswordEncryptor(PasswordEncryptor defaultPasswordEncryptor) {\n _defaultPasswordEncryptor = defaultPasswordEncryptor;\n }\n\n public void setPasswordEncryptors(List passwordEncryptors) {\n for (PasswordEncryptor passwordEncryptor : passwordEncryptors) {\n if (_log.isDebugEnabled()) {\n _log.debug(\"Registering \" + passwordEncryptor);\n }\n String[] supportedAlgorithmTypes = passwordEncryptor.getSupportedAlgorithmTypes();\n if (_log.isDebugEnabled()) {\n Class clazz = passwordEncryptor.getClass();\n _log.debug(StringBundler.concat(\"Registering \", StringUtil.merge(supportedAlgorithmTypes), \" for \", clazz.getName()));\n }\n for (String supportedAlgorithmType : supportedAlgorithmTypes) {\n _passwordEncryptors.put(supportedAlgorithmType, passwordEncryptor);\n }\n }\n }\n\n private String _getAlgorithmName(String algorithm) {\n int index = algorithm.indexOf(CharPool.SLASH);\n if (index > 0) {\n return algorithm.substring(0, index);\n }\n return algorithm;\n }\n\n private PasswordEncryptor _select(String algorithm) {\n if (Validator.isNull(algorithm)) {\n throw new IllegalArgumentException(\"Invalid algorithm\");\n }\n PasswordEncryptor passwordEncryptor = null;\n if (algorithm.startsWith(PasswordEncryptorUtil.TYPE_BCRYPT)) {\n passwordEncryptor = _passwordEncryptors.get(PasswordEncryptorUtil.TYPE_BCRYPT);\n } else if (algorithm.startsWith(PasswordEncryptorUtil.TYPE_PBKDF2)) {\n passwordEncryptor = _passwordEncryptors.get(PasswordEncryptorUtil.TYPE_PBKDF2);\n } else {\n passwordEncryptor = _passwordEncryptors.get(algorithm);\n }\n if (passwordEncryptor == null) {\n if (_log.isDebugEnabled()) {\n _log.debug(\"No password encryptor found for \" + algorithm);\n }\n passwordEncryptor = _defaultPasswordEncryptor;\n }\n if (_log.isDebugEnabled()) {\n _log.debug(StringBundler.concat(\"Found \", ClassUtil.getClassName(passwordEncryptor), \" to encrypt password using \", algorithm));\n }\n return passwordEncryptor;\n }\n\n private static final Log _log = LogFactoryUtil.getLog(CompositePasswordEncryptor.class);\n\n private PasswordEncryptor _defaultAlgorithmPasswordEncryptor;\n\n private PasswordEncryptor _defaultPasswordEncryptor;\n\n private final Map _passwordEncryptors = new HashMap<>();\n}\n"} {"task_id": "Java_2728", "language": "Java", "task_type": "single_line", "source_file": "java/github/liferay/liferay-portal/portal-impl/src/com/liferay/portal/security/pwd/CompositePasswordEncryptor.java", "mask_start_position": 1385, "mask_end_position": 1443, "canonical_solution": "rithm = PropsValues.PASSWORDS_ENCRYPTION_ALGORITHM_LEGACY;", "pre_mask_code": "package com.liferay.portal.security.pwd;\n\nimport com.liferay.petra.string.CharPool;\nimport com.liferay.petra.string.StringBundler;\nimport com.liferay.petra.string.StringPool;\nimport com.liferay.portal.kernel.exception.PwdEncryptorException;\nimport com.liferay.portal.kernel.log.Log;\nimport com.liferay.portal.kernel.log.LogFactoryUtil;\nimport com.liferay.portal.kernel.security.pwd.PasswordEncryptor;\nimport com.liferay.portal.kernel.security.pwd.PasswordEncryptorUtil;\nimport com.liferay.portal.kernel.util.ClassUtil;\nimport com.liferay.portal.kernel.util.StringUtil;\nimport com.liferay.portal.kernel.util.Validator;\nimport com.liferay.portal.util.PropsValues;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * @author Michael C. Han\n */\npublic class CompositePasswordEncryptor extends BasePasswordEncryptor implements PasswordEncryptor {\n\n public void afterPropertiesSet() {\n if (_defaultAlgorithmPasswordEncryptor == null) {\n _defaultAlgorithmPasswordEncryptor = _select(getDefaultPasswordAlgorithmType());\n }\n }\n\n @Override\n public String encrypt(String algorithm, String plainTextPassword, String encryptedPassword) throws PwdEncryptorException {\n if (Validator.isNull(plainTextPassword)) {\n throw new PwdEncryptorException(\"Unable to encrypt blank password\");\n }\n String legacyAlgo", "post_mask_code": "\n if (_log.isDebugEnabled() && Validator.isNotNull(legacyAlgorithm)) {\n if (Validator.isNull(encryptedPassword)) {\n _log.debug(StringBundler.concat(\"Using legacy detection scheme for algorithm \", legacyAlgorithm, \" with empty current password\"));\n } else {\n _log.debug(StringBundler.concat(\"Using legacy detection scheme for algorithm \", legacyAlgorithm, \" with provided current password\"));\n }\n }\n boolean prependAlgorithm = true;\n if (Validator.isNotNull(encryptedPassword) && (encryptedPassword.charAt(0) != CharPool.OPEN_CURLY_BRACE)) {\n algorithm = legacyAlgorithm;\n prependAlgorithm = false;\n if (_log.isDebugEnabled()) {\n _log.debug(\"Using legacy algorithm \" + algorithm);\n }\n } else if (Validator.isNotNull(encryptedPassword) && (encryptedPassword.charAt(0) == CharPool.OPEN_CURLY_BRACE)) {\n int index = encryptedPassword.indexOf(CharPool.CLOSE_CURLY_BRACE);\n if (index > 0) {\n algorithm = encryptedPassword.substring(1, index);\n encryptedPassword = encryptedPassword.substring(index + 1);\n }\n if (_log.isDebugEnabled()) {\n _log.debug(\"Upgraded password to use algorithm \" + algorithm);\n }\n }\n if (Validator.isNull(algorithm)) {\n algorithm = getDefaultPasswordAlgorithmType();\n }\n PasswordEncryptor passwordEncryptor = _select(algorithm);\n String newEncryptedPassword = passwordEncryptor.encrypt(algorithm, plainTextPassword, encryptedPassword);\n if (!prependAlgorithm) {\n if (_log.isDebugEnabled()) {\n _log.debug(\"Generated password without algorithm prefix using \" + algorithm);\n }\n return newEncryptedPassword;\n }\n if (_log.isDebugEnabled()) {\n _log.debug(\"Generated password with algorithm prefix using \" + algorithm);\n }\n return StringBundler.concat(StringPool.OPEN_CURLY_BRACE, _getAlgorithmName(algorithm), StringPool.CLOSE_CURLY_BRACE, newEncryptedPassword);\n }\n\n @Override\n public String[] getSupportedAlgorithmTypes() {\n throw new UnsupportedOperationException();\n }\n\n public void setDefaultPasswordEncryptor(PasswordEncryptor defaultPasswordEncryptor) {\n _defaultPasswordEncryptor = defaultPasswordEncryptor;\n }\n\n public void setPasswordEncryptors(List passwordEncryptors) {\n for (PasswordEncryptor passwordEncryptor : passwordEncryptors) {\n if (_log.isDebugEnabled()) {\n _log.debug(\"Registering \" + passwordEncryptor);\n }\n String[] supportedAlgorithmTypes = passwordEncryptor.getSupportedAlgorithmTypes();\n if (_log.isDebugEnabled()) {\n Class clazz = passwordEncryptor.getClass();\n _log.debug(StringBundler.concat(\"Registering \", StringUtil.merge(supportedAlgorithmTypes), \" for \", clazz.getName()));\n }\n for (String supportedAlgorithmType : supportedAlgorithmTypes) {\n _passwordEncryptors.put(supportedAlgorithmType, passwordEncryptor);\n }\n }\n }\n\n private String _getAlgorithmName(String algorithm) {\n int index = algorithm.indexOf(CharPool.SLASH);\n if (index > 0) {\n return algorithm.substring(0, index);\n }\n return algorithm;\n }\n\n private PasswordEncryptor _select(String algorithm) {\n if (Validator.isNull(algorithm)) {\n throw new IllegalArgumentException(\"Invalid algorithm\");\n }\n PasswordEncryptor passwordEncryptor = null;\n if (algorithm.startsWith(PasswordEncryptorUtil.TYPE_BCRYPT)) {\n passwordEncryptor = _passwordEncryptors.get(PasswordEncryptorUtil.TYPE_BCRYPT);\n } else if (algorithm.startsWith(PasswordEncryptorUtil.TYPE_PBKDF2)) {\n passwordEncryptor = _passwordEncryptors.get(PasswordEncryptorUtil.TYPE_PBKDF2);\n } else {\n passwordEncryptor = _passwordEncryptors.get(algorithm);\n }\n if (passwordEncryptor == null) {\n if (_log.isDebugEnabled()) {\n _log.debug(\"No password encryptor found for \" + algorithm);\n }\n passwordEncryptor = _defaultPasswordEncryptor;\n }\n if (_log.isDebugEnabled()) {\n _log.debug(StringBundler.concat(\"Found \", ClassUtil.getClassName(passwordEncryptor), \" to encrypt password using \", algorithm));\n }\n return passwordEncryptor;\n }\n\n private static final Log _log = LogFactoryUtil.getLog(CompositePasswordEncryptor.class);\n\n private PasswordEncryptor _defaultAlgorithmPasswordEncryptor;\n\n private PasswordEncryptor _defaultPasswordEncryptor;\n\n private final Map _passwordEncryptors = new HashMap<>();\n}\n"} {"task_id": "Java_2729", "language": "Java", "task_type": "method_signature", "source_file": "java/github/gnembon/carpetmod/src/main/java/carpet/logging/logHelpers/PathfindingVisualizer.java", "mask_start_position": 978, "mask_end_position": 1093, "canonical_solution": "private static void drawParticleLine(EntityPlayerMP player, Vec3d from, Vec3d to, float ratio, boolean successful) ", "pre_mask_code": "package carpet.logging.logHelpers;\n\nimport carpet.logging.LoggerRegistry;\nimport com.mojang.brigadier.StringReader;\nimport com.mojang.brigadier.exceptions.CommandSyntaxException;\nimport net.minecraft.command.arguments.ParticleArgument;\nimport net.minecraft.entity.Entity;\nimport net.minecraft.entity.player.EntityPlayerMP;\nimport net.minecraft.particles.IParticleData;\nimport net.minecraft.util.math.Vec3d;\nimport net.minecraft.world.WorldServer;\n\npublic class PathfindingVisualizer {\n\n private static IParticleData failedPath;\n\n private static IParticleData successfulPath;\n\n private static IParticleData lvl1;\n\n private static IParticleData lvl2;\n\n private static IParticleData lvl3;\n\n static {\n failedPath = parseParticle(\"angry_villager\");\n successfulPath = parseParticle(\"happy_villager\");\n lvl1 = parseParticle(\"dust 1 1 0 1\");\n lvl2 = parseParticle(\"dust 1 0.5 0 1\");\n lvl3 = parseParticle(\"dust 1 0 0 1\");\n }\n\n ", "post_mask_code": "{\n IParticleData accent = successful ? successfulPath : failedPath;\n IParticleData color = (ratio < 2) ? lvl1 : ((ratio < 4) ? lvl2 : lvl3);\n ((WorldServer) player.world).spawnParticle(player, accent, true, from.x, from.y, from.z, 5, 0.5, 0.5, 0.5, 0.0);\n double lineLengthSq = from.squareDistanceTo(to);\n if (lineLengthSq == 0)\n return;\n Vec3d incvec = to.subtract(from).normalize();\n int pcount = 0;\n for (Vec3d delta = new Vec3d(0.0, 0.0, 0.0); delta.lengthSquared() < lineLengthSq; delta = delta.add(incvec.scale(player.world.rand.nextFloat()))) {\n ((WorldServer) player.world).spawnParticle(player, color, true, delta.x + from.x, delta.y + from.y, delta.z + from.z, 1, 0.0, 0.0, 0.0, 0.0);\n }\n }\n\n private static IParticleData parseParticle(String name) {\n try {\n return ParticleArgument.parseParticle(new StringReader(name));\n } catch (CommandSyntaxException e) {\n throw new RuntimeException(\"No such particle: \" + name);\n }\n }\n\n public static void slowPath(Entity entity, Vec3d target, float miliseconds, boolean successful) {\n if (!LoggerRegistry.__pathfinding)\n return;\n LoggerRegistry.getLogger(\"pathfinding\").log((option, player) -> {\n if (!(player instanceof EntityPlayerMP))\n return null;\n int minDuration = Integer.parseInt(option);\n if (miliseconds < minDuration)\n return null;\n if (player.getDistanceSq(entity) > 1000 && player.getDistanceSq(target) > 1000)\n return null;\n if (minDuration < 1)\n minDuration = 1;\n drawParticleLine((EntityPlayerMP) player, entity.getPositionVector(), target, miliseconds / minDuration, successful);\n return null;\n });\n }\n}\n"} {"task_id": "Java_2730", "language": "Java", "task_type": "method_body", "source_file": "java/github/gnembon/carpetmod/src/main/java/carpet/logging/logHelpers/PathfindingVisualizer.java", "mask_start_position": 1943, "mask_end_position": 2163, "canonical_solution": "{\n try {\n return ParticleArgument.parseParticle(new StringReader(name));\n } catch (CommandSyntaxException e) {\n throw new RuntimeException(\"No such particle: \" + name);\n }\n }", "pre_mask_code": "package carpet.logging.logHelpers;\n\nimport carpet.logging.LoggerRegistry;\nimport com.mojang.brigadier.StringReader;\nimport com.mojang.brigadier.exceptions.CommandSyntaxException;\nimport net.minecraft.command.arguments.ParticleArgument;\nimport net.minecraft.entity.Entity;\nimport net.minecraft.entity.player.EntityPlayerMP;\nimport net.minecraft.particles.IParticleData;\nimport net.minecraft.util.math.Vec3d;\nimport net.minecraft.world.WorldServer;\n\npublic class PathfindingVisualizer {\n\n private static IParticleData failedPath;\n\n private static IParticleData successfulPath;\n\n private static IParticleData lvl1;\n\n private static IParticleData lvl2;\n\n private static IParticleData lvl3;\n\n static {\n failedPath = parseParticle(\"angry_villager\");\n successfulPath = parseParticle(\"happy_villager\");\n lvl1 = parseParticle(\"dust 1 1 0 1\");\n lvl2 = parseParticle(\"dust 1 0.5 0 1\");\n lvl3 = parseParticle(\"dust 1 0 0 1\");\n }\n\n private static void drawParticleLine(EntityPlayerMP player, Vec3d from, Vec3d to, float ratio, boolean successful) {\n IParticleData accent = successful ? successfulPath : failedPath;\n IParticleData color = (ratio < 2) ? lvl1 : ((ratio < 4) ? lvl2 : lvl3);\n ((WorldServer) player.world).spawnParticle(player, accent, true, from.x, from.y, from.z, 5, 0.5, 0.5, 0.5, 0.0);\n double lineLengthSq = from.squareDistanceTo(to);\n if (lineLengthSq == 0)\n return;\n Vec3d incvec = to.subtract(from).normalize();\n int pcount = 0;\n for (Vec3d delta = new Vec3d(0.0, 0.0, 0.0); delta.lengthSquared() < lineLengthSq; delta = delta.add(incvec.scale(player.world.rand.nextFloat()))) {\n ((WorldServer) player.world).spawnParticle(player, color, true, delta.x + from.x, delta.y + from.y, delta.z + from.z, 1, 0.0, 0.0, 0.0, 0.0);\n }\n }\n\n private static IParticleData parseParticle(String name) ", "post_mask_code": "\n\n public static void slowPath(Entity entity, Vec3d target, float miliseconds, boolean successful) {\n if (!LoggerRegistry.__pathfinding)\n return;\n LoggerRegistry.getLogger(\"pathfinding\").log((option, player) -> {\n if (!(player instanceof EntityPlayerMP))\n return null;\n int minDuration = Integer.parseInt(option);\n if (miliseconds < minDuration)\n return null;\n if (player.getDistanceSq(entity) > 1000 && player.getDistanceSq(target) > 1000)\n return null;\n if (minDuration < 1)\n minDuration = 1;\n drawParticleLine((EntityPlayerMP) player, entity.getPositionVector(), target, miliseconds / minDuration, successful);\n return null;\n });\n }\n}\n"} {"task_id": "Java_2731", "language": "Java", "task_type": "single_line", "source_file": "java/github/gnembon/carpetmod/src/main/java/carpet/logging/logHelpers/PathfindingVisualizer.java", "mask_start_position": 1207, "mask_end_position": 1247, "canonical_solution": "2) ? lvl1 : ((ratio < 4) ? lvl2 : lvl3);", "pre_mask_code": "package carpet.logging.logHelpers;\n\nimport carpet.logging.LoggerRegistry;\nimport com.mojang.brigadier.StringReader;\nimport com.mojang.brigadier.exceptions.CommandSyntaxException;\nimport net.minecraft.command.arguments.ParticleArgument;\nimport net.minecraft.entity.Entity;\nimport net.minecraft.entity.player.EntityPlayerMP;\nimport net.minecraft.particles.IParticleData;\nimport net.minecraft.util.math.Vec3d;\nimport net.minecraft.world.WorldServer;\n\npublic class PathfindingVisualizer {\n\n private static IParticleData failedPath;\n\n private static IParticleData successfulPath;\n\n private static IParticleData lvl1;\n\n private static IParticleData lvl2;\n\n private static IParticleData lvl3;\n\n static {\n failedPath = parseParticle(\"angry_villager\");\n successfulPath = parseParticle(\"happy_villager\");\n lvl1 = parseParticle(\"dust 1 1 0 1\");\n lvl2 = parseParticle(\"dust 1 0.5 0 1\");\n lvl3 = parseParticle(\"dust 1 0 0 1\");\n }\n\n private static void drawParticleLine(EntityPlayerMP player, Vec3d from, Vec3d to, float ratio, boolean successful) {\n IParticleData accent = successful ? successfulPath : failedPath;\n IParticleData color = (ratio < ", "post_mask_code": "\n ((WorldServer) player.world).spawnParticle(player, accent, true, from.x, from.y, from.z, 5, 0.5, 0.5, 0.5, 0.0);\n double lineLengthSq = from.squareDistanceTo(to);\n if (lineLengthSq == 0)\n return;\n Vec3d incvec = to.subtract(from).normalize();\n int pcount = 0;\n for (Vec3d delta = new Vec3d(0.0, 0.0, 0.0); delta.lengthSquared() < lineLengthSq; delta = delta.add(incvec.scale(player.world.rand.nextFloat()))) {\n ((WorldServer) player.world).spawnParticle(player, color, true, delta.x + from.x, delta.y + from.y, delta.z + from.z, 1, 0.0, 0.0, 0.0, 0.0);\n }\n }\n\n private static IParticleData parseParticle(String name) {\n try {\n return ParticleArgument.parseParticle(new StringReader(name));\n } catch (CommandSyntaxException e) {\n throw new RuntimeException(\"No such particle: \" + name);\n }\n }\n\n public static void slowPath(Entity entity, Vec3d target, float miliseconds, boolean successful) {\n if (!LoggerRegistry.__pathfinding)\n return;\n LoggerRegistry.getLogger(\"pathfinding\").log((option, player) -> {\n if (!(player instanceof EntityPlayerMP))\n return null;\n int minDuration = Integer.parseInt(option);\n if (miliseconds < minDuration)\n return null;\n if (player.getDistanceSq(entity) > 1000 && player.getDistanceSq(target) > 1000)\n return null;\n if (minDuration < 1)\n minDuration = 1;\n drawParticleLine((EntityPlayerMP) player, entity.getPositionVector(), target, miliseconds / minDuration, successful);\n return null;\n });\n }\n}\n"} {"task_id": "Java_2732", "language": "Java", "task_type": "for_statement", "source_file": "java/github/gnembon/carpetmod/src/main/java/carpet/logging/logHelpers/PathfindingVisualizer.java", "mask_start_position": 1563, "mask_end_position": 1875, "canonical_solution": "for (Vec3d delta = new Vec3d(0.0, 0.0, 0.0); delta.lengthSquared() < lineLengthSq; delta = delta.add(incvec.scale(player.world.rand.nextFloat()))) {\n ((WorldServer) player.world).spawnParticle(player, color, true, delta.x + from.x, delta.y + from.y, delta.z + from.z, 1, 0.0, 0.0, 0.0, 0.0);\n }", "pre_mask_code": "package carpet.logging.logHelpers;\n\nimport carpet.logging.LoggerRegistry;\nimport com.mojang.brigadier.StringReader;\nimport com.mojang.brigadier.exceptions.CommandSyntaxException;\nimport net.minecraft.command.arguments.ParticleArgument;\nimport net.minecraft.entity.Entity;\nimport net.minecraft.entity.player.EntityPlayerMP;\nimport net.minecraft.particles.IParticleData;\nimport net.minecraft.util.math.Vec3d;\nimport net.minecraft.world.WorldServer;\n\npublic class PathfindingVisualizer {\n\n private static IParticleData failedPath;\n\n private static IParticleData successfulPath;\n\n private static IParticleData lvl1;\n\n private static IParticleData lvl2;\n\n private static IParticleData lvl3;\n\n static {\n failedPath = parseParticle(\"angry_villager\");\n successfulPath = parseParticle(\"happy_villager\");\n lvl1 = parseParticle(\"dust 1 1 0 1\");\n lvl2 = parseParticle(\"dust 1 0.5 0 1\");\n lvl3 = parseParticle(\"dust 1 0 0 1\");\n }\n\n private static void drawParticleLine(EntityPlayerMP player, Vec3d from, Vec3d to, float ratio, boolean successful) {\n IParticleData accent = successful ? successfulPath : failedPath;\n IParticleData color = (ratio < 2) ? lvl1 : ((ratio < 4) ? lvl2 : lvl3);\n ((WorldServer) player.world).spawnParticle(player, accent, true, from.x, from.y, from.z, 5, 0.5, 0.5, 0.5, 0.0);\n double lineLengthSq = from.squareDistanceTo(to);\n if (lineLengthSq == 0)\n return;\n Vec3d incvec = to.subtract(from).normalize();\n int pcount = 0;\n ", "post_mask_code": "\n }\n\n private static IParticleData parseParticle(String name) {\n try {\n return ParticleArgument.parseParticle(new StringReader(name));\n } catch (CommandSyntaxException e) {\n throw new RuntimeException(\"No such particle: \" + name);\n }\n }\n\n public static void slowPath(Entity entity, Vec3d target, float miliseconds, boolean successful) {\n if (!LoggerRegistry.__pathfinding)\n return;\n LoggerRegistry.getLogger(\"pathfinding\").log((option, player) -> {\n if (!(player instanceof EntityPlayerMP))\n return null;\n int minDuration = Integer.parseInt(option);\n if (miliseconds < minDuration)\n return null;\n if (player.getDistanceSq(entity) > 1000 && player.getDistanceSq(target) > 1000)\n return null;\n if (minDuration < 1)\n minDuration = 1;\n drawParticleLine((EntityPlayerMP) player, entity.getPositionVector(), target, miliseconds / minDuration, successful);\n return null;\n });\n }\n}\n"} {"task_id": "Java_2733", "language": "Java", "task_type": "try_statement", "source_file": "java/github/gnembon/carpetmod/src/main/java/carpet/logging/logHelpers/PathfindingVisualizer.java", "mask_start_position": 1953, "mask_end_position": 2157, "canonical_solution": "try {\n return ParticleArgument.parseParticle(new StringReader(name));\n } catch (CommandSyntaxException e) {\n throw new RuntimeException(\"No such particle: \" + name);\n }", "pre_mask_code": "package carpet.logging.logHelpers;\n\nimport carpet.logging.LoggerRegistry;\nimport com.mojang.brigadier.StringReader;\nimport com.mojang.brigadier.exceptions.CommandSyntaxException;\nimport net.minecraft.command.arguments.ParticleArgument;\nimport net.minecraft.entity.Entity;\nimport net.minecraft.entity.player.EntityPlayerMP;\nimport net.minecraft.particles.IParticleData;\nimport net.minecraft.util.math.Vec3d;\nimport net.minecraft.world.WorldServer;\n\npublic class PathfindingVisualizer {\n\n private static IParticleData failedPath;\n\n private static IParticleData successfulPath;\n\n private static IParticleData lvl1;\n\n private static IParticleData lvl2;\n\n private static IParticleData lvl3;\n\n static {\n failedPath = parseParticle(\"angry_villager\");\n successfulPath = parseParticle(\"happy_villager\");\n lvl1 = parseParticle(\"dust 1 1 0 1\");\n lvl2 = parseParticle(\"dust 1 0.5 0 1\");\n lvl3 = parseParticle(\"dust 1 0 0 1\");\n }\n\n private static void drawParticleLine(EntityPlayerMP player, Vec3d from, Vec3d to, float ratio, boolean successful) {\n IParticleData accent = successful ? successfulPath : failedPath;\n IParticleData color = (ratio < 2) ? lvl1 : ((ratio < 4) ? lvl2 : lvl3);\n ((WorldServer) player.world).spawnParticle(player, accent, true, from.x, from.y, from.z, 5, 0.5, 0.5, 0.5, 0.0);\n double lineLengthSq = from.squareDistanceTo(to);\n if (lineLengthSq == 0)\n return;\n Vec3d incvec = to.subtract(from).normalize();\n int pcount = 0;\n for (Vec3d delta = new Vec3d(0.0, 0.0, 0.0); delta.lengthSquared() < lineLengthSq; delta = delta.add(incvec.scale(player.world.rand.nextFloat()))) {\n ((WorldServer) player.world).spawnParticle(player, color, true, delta.x + from.x, delta.y + from.y, delta.z + from.z, 1, 0.0, 0.0, 0.0, 0.0);\n }\n }\n\n private static IParticleData parseParticle(String name) {\n ", "post_mask_code": "\n }\n\n public static void slowPath(Entity entity, Vec3d target, float miliseconds, boolean successful) {\n if (!LoggerRegistry.__pathfinding)\n return;\n LoggerRegistry.getLogger(\"pathfinding\").log((option, player) -> {\n if (!(player instanceof EntityPlayerMP))\n return null;\n int minDuration = Integer.parseInt(option);\n if (miliseconds < minDuration)\n return null;\n if (player.getDistanceSq(entity) > 1000 && player.getDistanceSq(target) > 1000)\n return null;\n if (minDuration < 1)\n minDuration = 1;\n drawParticleLine((EntityPlayerMP) player, entity.getPositionVector(), target, miliseconds / minDuration, successful);\n return null;\n });\n }\n}\n"} {"task_id": "Java_2734", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jcryptool/crypto/org.jcryptool.analysis.freqanalysis/src/org/jcryptool/analysis/freqanalysis/ui/SimpleAnalysisUI.java", "mask_start_position": 2642, "mask_end_position": 2665, "canonical_solution": "private void initGUI() ", "pre_mask_code": "package org.jcryptool.analysis.freqanalysis.ui;\n\nimport java.math.BigInteger;\nimport java.util.Observable;\nimport java.util.Observer;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.IStatus;\nimport org.eclipse.core.runtime.Status;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.dialogs.TitleAreaDialog;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.events.MouseAdapter;\nimport org.eclipse.swt.events.MouseEvent;\nimport org.eclipse.swt.events.SelectionAdapter;\nimport org.eclipse.swt.events.SelectionEvent;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Button;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Control;\nimport org.eclipse.swt.widgets.Group;\nimport org.eclipse.swt.widgets.Label;\nimport org.eclipse.swt.widgets.Shell;\nimport org.eclipse.swt.widgets.Spinner;\nimport org.eclipse.swt.widgets.TabFolder;\nimport org.eclipse.swt.widgets.TabItem;\nimport org.eclipse.swt.widgets.Text;\nimport org.jcryptool.analysis.freqanalysis.calc.FreqAnalysisCalc;\nimport org.jcryptool.core.operations.algorithm.classic.textmodify.TransformData;\nimport org.jcryptool.crypto.ui.background.BackgroundJob;\nimport org.jcryptool.crypto.ui.textloader.ui.wizard.TextLoadController;\nimport org.jcryptool.crypto.ui.textsource.TextInputWithSource;\n\n/**\n * @author SLeischnig\n */\npublic class SimpleAnalysisUI extends AbstractAnalysisUI {\n\n private Composite composite0;\n\n private Composite composite1;\n\n private Group group1;\n\n private Label label1;\n\n private Button button4;\n\n private Composite composite2;\n\n private Group group4;\n\n private Label label2;\n\n private Group group2;\n\n private Composite composite3;\n\n private TabFolder tabFolder1;\n\n private TabItem tabItem1;\n\n private TabItem tabItem2;\n\n private Composite composite4;\n\n private Label label3;\n\n private Label label4;\n\n private Label label5;\n\n private Text text1;\n\n private TextInputWithSource source;\n\n private FreqAnalysisCalc myAnalysis;\n\n TransformData myModifySettings;\n\n private TextLoadController textloader;\n\n public FreqAnalysisCalc return__freqanalysis;\n\n private static final int simpleFreqAnalysis_text_max_length = 999999;\n\n private TextInputWithSource lastSuccessfullLoadedText;\n\n public SimpleAnalysisUI(final Composite parent, final int style) {\n super(parent, style);\n initGUI();\n hideObject(group2, button3.getSelection());\n myModifySettings = new TransformData();\n myModifySettings.setUnmodified();\n }\n\n ", "post_mask_code": "{\n setLayout(new GridLayout());\n composite0 = new Composite(this, SWT.NONE);\n composite0.setLayout(new GridLayout(2, false));\n composite0.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));\n textloader = new TextLoadController(composite0, this, SWT.NONE, true, true);\n textloader.addObserver(new Observer() {\n\n @Override\n public void update(Observable o, Object arg) {\n if (textloader.getText() != null) {\n myGraph.getFrequencyGraph().setInstruction(Messages.FreqAnalysisGraph_graph1);\n myGraph.redraw();\n if (textloader.getText().getText().length() < simpleFreqAnalysis_text_max_length) {\n text = textloader.getText().getText();\n lastSuccessfullLoadedText = textloader.getText();\n source = textloader.getText();\n } else {\n boolean result = MessageDialog.openQuestion(SimpleAnalysisUI.this.getShell(), Messages.SimpleAnalysisUI_warning, Messages.SimpleAnalysisUI_warning_text);\n if (result) {\n text = textloader.getText().getText();\n source = textloader.getText();\n } else {\n textloader.setTextData(lastSuccessfullLoadedText, null, true);\n source = lastSuccessfullLoadedText;\n return;\n }\n }\n recalcSourceInfo();\n myGraph.getFrequencyGraph().setInstruction(Messages.FreqAnalysisGraph_shiftgraph0);\n if (text.equals(\"\") || text == null) {\n MessageDialog.openInformation(getShell(), Messages.AbstractAnalysisUI_0, Messages.AbstractAnalysisUI_2);\n } else {\n recalcGraph();\n }\n }\n }\n });\n // @Override\n // String line;\n // @Override\n // @Override\n composite1 = new Composite(this, SWT.NONE);\n composite1.setLayout(new GridLayout(2, false));\n composite1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n group1 = new Group(composite1, SWT.NONE);\n group1.setLayout(new GridLayout());\n group1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n group1.setText(Messages.SimpleAnalysisUI_graphlabel);\n myGraph = new CustomFreqCanvas(group1, SWT.NONE);\n myGraph.setLayout(new GridLayout());\n myGraph.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n group4 = new Group(composite1, SWT.NONE);\n group4.setLayout(new GridLayout());\n group4.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true));\n group4.setText(Messages.SimpleAnalysisUI_properties);\n tabFolder1 = new TabFolder(group4, SWT.NONE);\n tabItem1 = new TabItem(tabFolder1, SWT.NONE);\n tabItem1.setText(Messages.FullAnalysisUI_firsttablabel);\n composite3 = new Composite(tabFolder1, SWT.NONE);\n composite3.setLayout(new GridLayout());\n composite3.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n tabItem1.setControl(composite3);\n composite2 = new Composite(composite3, SWT.NONE);\n composite2.setLayout(new GridLayout());\n composite2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n button3 = new Button(composite2, SWT.RADIO);\n button3.setText(Messages.SimpleAnalysisUI_monoalphabetic);\n button3.setSelection(true);\n button3.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent evt) {\n polyOnOffSelected(evt);\n }\n });\n button4 = new Button(composite2, SWT.RADIO);\n button4.setText(Messages.SimpleAnalysisUI_polyalphabetic);\n button4.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent evt) {\n polyOnOffSelected(evt);\n }\n });\n Label lblPolyalphabetic = new Label(composite2, SWT.WRAP);\n lblPolyalphabetic.setText(Messages.FullAnalysisUI_6);\n GridData layoutData = new GridData(SWT.FILL, SWT.CENTER, true, false);\n layoutData.widthHint = 100;\n lblPolyalphabetic.setLayoutData(layoutData);\n group2 = new Group(composite2, SWT.NONE);\n group2.setLayout(new GridLayout(2, false));\n group2.setText(Messages.SimpleAnalysisUI_vigeneresettings);\n spinner1 = new Spinner(group2, SWT.NONE);\n spinner1.addMouseListener(new MouseAdapter() {\n\n @Override\n public void mouseDown(MouseEvent evt) {\n recalcGraph();\n }\n });\n spinner1.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent evt) {\n changedVigOptions();\n }\n });\n spinner1.setSelection(1);\n label1 = new Label(group2, SWT.NONE);\n label1.setText(Messages.SimpleAnalysisUI_keylength);\n spinner2 = new Spinner(group2, SWT.NONE);\n spinner2.addMouseListener(new MouseAdapter() {\n\n @Override\n public void mouseDown(MouseEvent evt) {\n recalcGraph();\n }\n });\n spinner2.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent evt) {\n changedVigOptions();\n }\n });\n spinner2.setSelection(0);\n label2 = new Label(group2, SWT.NONE);\n label2.setText(Messages.SimpleAnalysisUI_offset);\n // @Override\n tabItem2 = new TabItem(tabFolder1, SWT.NONE);\n tabItem2.setText(Messages.FullAnalysisUI_thirdtablabel);\n composite4 = new Composite(tabFolder1, SWT.NONE);\n composite4.setLayout(new GridLayout());\n tabItem2.setControl(composite4);\n label3 = new Label(composite4, SWT.WRAP);\n GridData layoutData1 = new GridData(SWT.FILL, SWT.FILL, true, false);\n label3.setLayoutData(layoutData1);\n label4 = new Label(composite4, SWT.WRAP);\n GridData layoutData2 = new GridData(SWT.FILL, SWT.FILL, true, false);\n label4.setLayoutData(layoutData2);\n label5 = new Label(composite4, SWT.NONE);\n label5.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));\n text1 = new Text(composite4, SWT.V_SCROLL | SWT.BORDER | SWT.MULTI | SWT.WRAP);\n text1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n recalcSourceInfo();\n tabFolder1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n tabFolder1.setSelection(0);\n layout();\n }\n\n /**\n * Method for aggregating information about source text file.\n */\n protected void recalcSourceInfo() {\n if (text == null) {\n label3.setText(Messages.FullAnalysisUI_source + \" -\");\n label4.setText(Messages.FullAnalysisUI_textlength + \" -\");\n text1.setText(\"\");\n composite4.layout(new Control[] { label3, label4 });\n } else {\n label3.setText(Messages.FullAnalysisUI_source + \" \" + source.toString());\n String totalLength = Integer.toString(text.length());\n label4.setText(Messages.FullAnalysisUI_textlength + \" \" + totalLength);\n label5.setText(Messages.FullAnalysisUI_textexcerpt);\n text1.setText(text.substring(0, (text.length() > 1000) ? 1000 : text.length()) + ((text.length() > 1000) ? \"...\" : \"\"));\n text1.setEditable(false);\n }\n }\n\n /**\n * executes a TextModify Wizard.\n *\n * @param the Settings that have to be displayed at the beginning.\n * @return the selected settings.\n */\n public class FreqAnalysisJob extends BackgroundJob {\n\n private String text;\n\n private int myLength;\n\n private int myOffset;\n\n private String myOverlayAlphabet;\n\n public TransformData myModifySettings;\n\n @Override\n public String name() {\n return \"Frequency Analysis\";\n }\n\n @Override\n public IStatus computation(IProgressMonitor monitor) {\n SimpleAnalysisUI.this.return__freqanalysis = new FreqAnalysisCalc(this.text, this.myLength, this.myOffset, this.myModifySettings);\n return Status.OK_STATUS;\n }\n }\n\n /**\n * frequency analysis main procedure\n */\n @Override\n protected void analyze() {\n FreqAnalysisJob job = new FreqAnalysisJob();\n job.text = text;\n job.myLength = myLength;\n job.myOffset = myOffset;\n job.myModifySettings = myModifySettings;\n job.finalizeListeners.add(status -> {\n getDisplay().syncExec(() -> {\n job.liftNoClickDisplaySynced(getDisplay());\n if (status == Status.OK_STATUS) {\n myAnalysis = return__freqanalysis;\n myGraph.setAnalysis(myAnalysis);\n }\n });\n });\n job.imposeNoClickDisplayCurrentShellSynced(getDisplay());\n job.runInBackground();\n }\n\n /**\n * excludes a control from the Layout calculation\n *\n * @param that\n * @param hideit\n */\n private void hideObject(final Control that, final boolean hideit) {\n GridData GData = (GridData) that.getLayoutData();\n // the (GData != null) test is to work around a NullPointerException (bug #95)\n // happening after one leaves the Frequency Analysis open\n // while closing down JCrypTool, then restarts JCrypTool\n if (GData != null) {\n GData.exclude = true && hideit;\n }\n that.setVisible(true && !hideit);\n Control[] myArray = { that };\n layout(myArray);\n }\n\n private void polyOnOffSelected(final SelectionEvent evt) {\n hideObject(group2, button3.getSelection());\n }\n\n private void changedVigOptions() {\n if (spinner1.getSelection() < 1) {\n spinner1.setSelection(1);\n }\n if (spinner2.getSelection() < 0) {\n spinner2.setSelection(0);\n }\n spinner1.setMinimum(1);\n spinner1.setMaximum(999999);\n spinner2.setMinimum(0);\n spinner2.setMaximum(spinner1.getSelection() - 1);\n if (spinner2.getSelection() >= spinner1.getSelection()) {\n spinner2.setSelection(spinner1.getSelection() - 1);\n }\n spinner2.setMaximum(spinner1.getSelection());\n }\n\n public final void execute(final int keyLength, final int keyPos, final boolean resetShift, final boolean executeCalc) {\n if (keyLength > 0) {\n if (keyLength == 1) {\n button3.setSelection(true);\n button4.setSelection(false);\n } else {\n button3.setSelection(false);\n button4.setSelection(true);\n }\n polyOnOffSelected(null);\n spinner1.setSelection(keyLength);\n changedVigOptions();\n if (keyPos < 0) {\n recalcGraph();\n }\n }\n if (keyPos > -1) {\n spinner2.setSelection(keyPos);\n changedVigOptions();\n recalcGraph();\n }\n if (resetShift) {\n myGraph.getFrequencyGraph().resetDrag();\n }\n if (executeCalc) {\n if (checkEditor()) {\n text = getEditorText();\n recalcGraph();\n }\n }\n }\n\n public void resetClick() {\n // TODO Auto-generated method stub\n }\n}\n"} {"task_id": "Java_2735", "language": "Java", "task_type": "method_body", "source_file": "java/github/jcryptool/crypto/org.jcryptool.analysis.freqanalysis/src/org/jcryptool/analysis/freqanalysis/ui/SimpleAnalysisUI.java", "mask_start_position": 8142, "mask_end_position": 8188, "canonical_solution": "{\n recalcGraph();\n }", "pre_mask_code": "package org.jcryptool.analysis.freqanalysis.ui;\n\nimport java.math.BigInteger;\nimport java.util.Observable;\nimport java.util.Observer;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.IStatus;\nimport org.eclipse.core.runtime.Status;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.dialogs.TitleAreaDialog;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.events.MouseAdapter;\nimport org.eclipse.swt.events.MouseEvent;\nimport org.eclipse.swt.events.SelectionAdapter;\nimport org.eclipse.swt.events.SelectionEvent;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Button;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Control;\nimport org.eclipse.swt.widgets.Group;\nimport org.eclipse.swt.widgets.Label;\nimport org.eclipse.swt.widgets.Shell;\nimport org.eclipse.swt.widgets.Spinner;\nimport org.eclipse.swt.widgets.TabFolder;\nimport org.eclipse.swt.widgets.TabItem;\nimport org.eclipse.swt.widgets.Text;\nimport org.jcryptool.analysis.freqanalysis.calc.FreqAnalysisCalc;\nimport org.jcryptool.core.operations.algorithm.classic.textmodify.TransformData;\nimport org.jcryptool.crypto.ui.background.BackgroundJob;\nimport org.jcryptool.crypto.ui.textloader.ui.wizard.TextLoadController;\nimport org.jcryptool.crypto.ui.textsource.TextInputWithSource;\n\n/**\n * @author SLeischnig\n */\npublic class SimpleAnalysisUI extends AbstractAnalysisUI {\n\n private Composite composite0;\n\n private Composite composite1;\n\n private Group group1;\n\n private Label label1;\n\n private Button button4;\n\n private Composite composite2;\n\n private Group group4;\n\n private Label label2;\n\n private Group group2;\n\n private Composite composite3;\n\n private TabFolder tabFolder1;\n\n private TabItem tabItem1;\n\n private TabItem tabItem2;\n\n private Composite composite4;\n\n private Label label3;\n\n private Label label4;\n\n private Label label5;\n\n private Text text1;\n\n private TextInputWithSource source;\n\n private FreqAnalysisCalc myAnalysis;\n\n TransformData myModifySettings;\n\n private TextLoadController textloader;\n\n public FreqAnalysisCalc return__freqanalysis;\n\n private static final int simpleFreqAnalysis_text_max_length = 999999;\n\n private TextInputWithSource lastSuccessfullLoadedText;\n\n public SimpleAnalysisUI(final Composite parent, final int style) {\n super(parent, style);\n initGUI();\n hideObject(group2, button3.getSelection());\n myModifySettings = new TransformData();\n myModifySettings.setUnmodified();\n }\n\n private void initGUI() {\n setLayout(new GridLayout());\n composite0 = new Composite(this, SWT.NONE);\n composite0.setLayout(new GridLayout(2, false));\n composite0.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));\n textloader = new TextLoadController(composite0, this, SWT.NONE, true, true);\n textloader.addObserver(new Observer() {\n\n @Override\n public void update(Observable o, Object arg) {\n if (textloader.getText() != null) {\n myGraph.getFrequencyGraph().setInstruction(Messages.FreqAnalysisGraph_graph1);\n myGraph.redraw();\n if (textloader.getText().getText().length() < simpleFreqAnalysis_text_max_length) {\n text = textloader.getText().getText();\n lastSuccessfullLoadedText = textloader.getText();\n source = textloader.getText();\n } else {\n boolean result = MessageDialog.openQuestion(SimpleAnalysisUI.this.getShell(), Messages.SimpleAnalysisUI_warning, Messages.SimpleAnalysisUI_warning_text);\n if (result) {\n text = textloader.getText().getText();\n source = textloader.getText();\n } else {\n textloader.setTextData(lastSuccessfullLoadedText, null, true);\n source = lastSuccessfullLoadedText;\n return;\n }\n }\n recalcSourceInfo();\n myGraph.getFrequencyGraph().setInstruction(Messages.FreqAnalysisGraph_shiftgraph0);\n if (text.equals(\"\") || text == null) {\n MessageDialog.openInformation(getShell(), Messages.AbstractAnalysisUI_0, Messages.AbstractAnalysisUI_2);\n } else {\n recalcGraph();\n }\n }\n }\n });\n // @Override\n // String line;\n // @Override\n // @Override\n composite1 = new Composite(this, SWT.NONE);\n composite1.setLayout(new GridLayout(2, false));\n composite1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n group1 = new Group(composite1, SWT.NONE);\n group1.setLayout(new GridLayout());\n group1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n group1.setText(Messages.SimpleAnalysisUI_graphlabel);\n myGraph = new CustomFreqCanvas(group1, SWT.NONE);\n myGraph.setLayout(new GridLayout());\n myGraph.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n group4 = new Group(composite1, SWT.NONE);\n group4.setLayout(new GridLayout());\n group4.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true));\n group4.setText(Messages.SimpleAnalysisUI_properties);\n tabFolder1 = new TabFolder(group4, SWT.NONE);\n tabItem1 = new TabItem(tabFolder1, SWT.NONE);\n tabItem1.setText(Messages.FullAnalysisUI_firsttablabel);\n composite3 = new Composite(tabFolder1, SWT.NONE);\n composite3.setLayout(new GridLayout());\n composite3.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n tabItem1.setControl(composite3);\n composite2 = new Composite(composite3, SWT.NONE);\n composite2.setLayout(new GridLayout());\n composite2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n button3 = new Button(composite2, SWT.RADIO);\n button3.setText(Messages.SimpleAnalysisUI_monoalphabetic);\n button3.setSelection(true);\n button3.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent evt) {\n polyOnOffSelected(evt);\n }\n });\n button4 = new Button(composite2, SWT.RADIO);\n button4.setText(Messages.SimpleAnalysisUI_polyalphabetic);\n button4.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent evt) {\n polyOnOffSelected(evt);\n }\n });\n Label lblPolyalphabetic = new Label(composite2, SWT.WRAP);\n lblPolyalphabetic.setText(Messages.FullAnalysisUI_6);\n GridData layoutData = new GridData(SWT.FILL, SWT.CENTER, true, false);\n layoutData.widthHint = 100;\n lblPolyalphabetic.setLayoutData(layoutData);\n group2 = new Group(composite2, SWT.NONE);\n group2.setLayout(new GridLayout(2, false));\n group2.setText(Messages.SimpleAnalysisUI_vigeneresettings);\n spinner1 = new Spinner(group2, SWT.NONE);\n spinner1.addMouseListener(new MouseAdapter() {\n\n @Override\n public void mouseDown(MouseEvent evt) {\n recalcGraph();\n }\n });\n spinner1.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent evt) {\n changedVigOptions();\n }\n });\n spinner1.setSelection(1);\n label1 = new Label(group2, SWT.NONE);\n label1.setText(Messages.SimpleAnalysisUI_keylength);\n spinner2 = new Spinner(group2, SWT.NONE);\n spinner2.addMouseListener(new MouseAdapter() {\n\n @Override\n public void mouseDown(MouseEvent evt) ", "post_mask_code": "\n });\n spinner2.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent evt) {\n changedVigOptions();\n }\n });\n spinner2.setSelection(0);\n label2 = new Label(group2, SWT.NONE);\n label2.setText(Messages.SimpleAnalysisUI_offset);\n // @Override\n tabItem2 = new TabItem(tabFolder1, SWT.NONE);\n tabItem2.setText(Messages.FullAnalysisUI_thirdtablabel);\n composite4 = new Composite(tabFolder1, SWT.NONE);\n composite4.setLayout(new GridLayout());\n tabItem2.setControl(composite4);\n label3 = new Label(composite4, SWT.WRAP);\n GridData layoutData1 = new GridData(SWT.FILL, SWT.FILL, true, false);\n label3.setLayoutData(layoutData1);\n label4 = new Label(composite4, SWT.WRAP);\n GridData layoutData2 = new GridData(SWT.FILL, SWT.FILL, true, false);\n label4.setLayoutData(layoutData2);\n label5 = new Label(composite4, SWT.NONE);\n label5.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));\n text1 = new Text(composite4, SWT.V_SCROLL | SWT.BORDER | SWT.MULTI | SWT.WRAP);\n text1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n recalcSourceInfo();\n tabFolder1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n tabFolder1.setSelection(0);\n layout();\n }\n\n /**\n * Method for aggregating information about source text file.\n */\n protected void recalcSourceInfo() {\n if (text == null) {\n label3.setText(Messages.FullAnalysisUI_source + \" -\");\n label4.setText(Messages.FullAnalysisUI_textlength + \" -\");\n text1.setText(\"\");\n composite4.layout(new Control[] { label3, label4 });\n } else {\n label3.setText(Messages.FullAnalysisUI_source + \" \" + source.toString());\n String totalLength = Integer.toString(text.length());\n label4.setText(Messages.FullAnalysisUI_textlength + \" \" + totalLength);\n label5.setText(Messages.FullAnalysisUI_textexcerpt);\n text1.setText(text.substring(0, (text.length() > 1000) ? 1000 : text.length()) + ((text.length() > 1000) ? \"...\" : \"\"));\n text1.setEditable(false);\n }\n }\n\n /**\n * executes a TextModify Wizard.\n *\n * @param the Settings that have to be displayed at the beginning.\n * @return the selected settings.\n */\n public class FreqAnalysisJob extends BackgroundJob {\n\n private String text;\n\n private int myLength;\n\n private int myOffset;\n\n private String myOverlayAlphabet;\n\n public TransformData myModifySettings;\n\n @Override\n public String name() {\n return \"Frequency Analysis\";\n }\n\n @Override\n public IStatus computation(IProgressMonitor monitor) {\n SimpleAnalysisUI.this.return__freqanalysis = new FreqAnalysisCalc(this.text, this.myLength, this.myOffset, this.myModifySettings);\n return Status.OK_STATUS;\n }\n }\n\n /**\n * frequency analysis main procedure\n */\n @Override\n protected void analyze() {\n FreqAnalysisJob job = new FreqAnalysisJob();\n job.text = text;\n job.myLength = myLength;\n job.myOffset = myOffset;\n job.myModifySettings = myModifySettings;\n job.finalizeListeners.add(status -> {\n getDisplay().syncExec(() -> {\n job.liftNoClickDisplaySynced(getDisplay());\n if (status == Status.OK_STATUS) {\n myAnalysis = return__freqanalysis;\n myGraph.setAnalysis(myAnalysis);\n }\n });\n });\n job.imposeNoClickDisplayCurrentShellSynced(getDisplay());\n job.runInBackground();\n }\n\n /**\n * excludes a control from the Layout calculation\n *\n * @param that\n * @param hideit\n */\n private void hideObject(final Control that, final boolean hideit) {\n GridData GData = (GridData) that.getLayoutData();\n // the (GData != null) test is to work around a NullPointerException (bug #95)\n // happening after one leaves the Frequency Analysis open\n // while closing down JCrypTool, then restarts JCrypTool\n if (GData != null) {\n GData.exclude = true && hideit;\n }\n that.setVisible(true && !hideit);\n Control[] myArray = { that };\n layout(myArray);\n }\n\n private void polyOnOffSelected(final SelectionEvent evt) {\n hideObject(group2, button3.getSelection());\n }\n\n private void changedVigOptions() {\n if (spinner1.getSelection() < 1) {\n spinner1.setSelection(1);\n }\n if (spinner2.getSelection() < 0) {\n spinner2.setSelection(0);\n }\n spinner1.setMinimum(1);\n spinner1.setMaximum(999999);\n spinner2.setMinimum(0);\n spinner2.setMaximum(spinner1.getSelection() - 1);\n if (spinner2.getSelection() >= spinner1.getSelection()) {\n spinner2.setSelection(spinner1.getSelection() - 1);\n }\n spinner2.setMaximum(spinner1.getSelection());\n }\n\n public final void execute(final int keyLength, final int keyPos, final boolean resetShift, final boolean executeCalc) {\n if (keyLength > 0) {\n if (keyLength == 1) {\n button3.setSelection(true);\n button4.setSelection(false);\n } else {\n button3.setSelection(false);\n button4.setSelection(true);\n }\n polyOnOffSelected(null);\n spinner1.setSelection(keyLength);\n changedVigOptions();\n if (keyPos < 0) {\n recalcGraph();\n }\n }\n if (keyPos > -1) {\n spinner2.setSelection(keyPos);\n changedVigOptions();\n recalcGraph();\n }\n if (resetShift) {\n myGraph.getFrequencyGraph().resetDrag();\n }\n if (executeCalc) {\n if (checkEditor()) {\n text = getEditorText();\n recalcGraph();\n }\n }\n }\n\n public void resetClick() {\n // TODO Auto-generated method stub\n }\n}\n"} {"task_id": "Java_2736", "language": "Java", "task_type": "single_line", "source_file": "java/github/jcryptool/crypto/org.jcryptool.analysis.freqanalysis/src/org/jcryptool/analysis/freqanalysis/ui/SimpleAnalysisUI.java", "mask_start_position": 5893, "mask_end_position": 5901, "canonical_solution": "yout());", "pre_mask_code": "package org.jcryptool.analysis.freqanalysis.ui;\n\nimport java.math.BigInteger;\nimport java.util.Observable;\nimport java.util.Observer;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.IStatus;\nimport org.eclipse.core.runtime.Status;\nimport org.eclipse.jface.dialogs.MessageDialog;\nimport org.eclipse.jface.dialogs.TitleAreaDialog;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.events.MouseAdapter;\nimport org.eclipse.swt.events.MouseEvent;\nimport org.eclipse.swt.events.SelectionAdapter;\nimport org.eclipse.swt.events.SelectionEvent;\nimport org.eclipse.swt.layout.GridData;\nimport org.eclipse.swt.layout.GridLayout;\nimport org.eclipse.swt.widgets.Button;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Control;\nimport org.eclipse.swt.widgets.Group;\nimport org.eclipse.swt.widgets.Label;\nimport org.eclipse.swt.widgets.Shell;\nimport org.eclipse.swt.widgets.Spinner;\nimport org.eclipse.swt.widgets.TabFolder;\nimport org.eclipse.swt.widgets.TabItem;\nimport org.eclipse.swt.widgets.Text;\nimport org.jcryptool.analysis.freqanalysis.calc.FreqAnalysisCalc;\nimport org.jcryptool.core.operations.algorithm.classic.textmodify.TransformData;\nimport org.jcryptool.crypto.ui.background.BackgroundJob;\nimport org.jcryptool.crypto.ui.textloader.ui.wizard.TextLoadController;\nimport org.jcryptool.crypto.ui.textsource.TextInputWithSource;\n\n/**\n * @author SLeischnig\n */\npublic class SimpleAnalysisUI extends AbstractAnalysisUI {\n\n private Composite composite0;\n\n private Composite composite1;\n\n private Group group1;\n\n private Label label1;\n\n private Button button4;\n\n private Composite composite2;\n\n private Group group4;\n\n private Label label2;\n\n private Group group2;\n\n private Composite composite3;\n\n private TabFolder tabFolder1;\n\n private TabItem tabItem1;\n\n private TabItem tabItem2;\n\n private Composite composite4;\n\n private Label label3;\n\n private Label label4;\n\n private Label label5;\n\n private Text text1;\n\n private TextInputWithSource source;\n\n private FreqAnalysisCalc myAnalysis;\n\n TransformData myModifySettings;\n\n private TextLoadController textloader;\n\n public FreqAnalysisCalc return__freqanalysis;\n\n private static final int simpleFreqAnalysis_text_max_length = 999999;\n\n private TextInputWithSource lastSuccessfullLoadedText;\n\n public SimpleAnalysisUI(final Composite parent, final int style) {\n super(parent, style);\n initGUI();\n hideObject(group2, button3.getSelection());\n myModifySettings = new TransformData();\n myModifySettings.setUnmodified();\n }\n\n private void initGUI() {\n setLayout(new GridLayout());\n composite0 = new Composite(this, SWT.NONE);\n composite0.setLayout(new GridLayout(2, false));\n composite0.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));\n textloader = new TextLoadController(composite0, this, SWT.NONE, true, true);\n textloader.addObserver(new Observer() {\n\n @Override\n public void update(Observable o, Object arg) {\n if (textloader.getText() != null) {\n myGraph.getFrequencyGraph().setInstruction(Messages.FreqAnalysisGraph_graph1);\n myGraph.redraw();\n if (textloader.getText().getText().length() < simpleFreqAnalysis_text_max_length) {\n text = textloader.getText().getText();\n lastSuccessfullLoadedText = textloader.getText();\n source = textloader.getText();\n } else {\n boolean result = MessageDialog.openQuestion(SimpleAnalysisUI.this.getShell(), Messages.SimpleAnalysisUI_warning, Messages.SimpleAnalysisUI_warning_text);\n if (result) {\n text = textloader.getText().getText();\n source = textloader.getText();\n } else {\n textloader.setTextData(lastSuccessfullLoadedText, null, true);\n source = lastSuccessfullLoadedText;\n return;\n }\n }\n recalcSourceInfo();\n myGraph.getFrequencyGraph().setInstruction(Messages.FreqAnalysisGraph_shiftgraph0);\n if (text.equals(\"\") || text == null) {\n MessageDialog.openInformation(getShell(), Messages.AbstractAnalysisUI_0, Messages.AbstractAnalysisUI_2);\n } else {\n recalcGraph();\n }\n }\n }\n });\n // @Override\n // String line;\n // @Override\n // @Override\n composite1 = new Composite(this, SWT.NONE);\n composite1.setLayout(new GridLayout(2, false));\n composite1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n group1 = new Group(composite1, SWT.NONE);\n group1.setLayout(new GridLayout());\n group1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n group1.setText(Messages.SimpleAnalysisUI_graphlabel);\n myGraph = new CustomFreqCanvas(group1, SWT.NONE);\n myGraph.setLayout(new GridLayout());\n myGraph.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n group4 = new Group(composite1, SWT.NONE);\n group4.setLayout(new GridLayout());\n group4.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true));\n group4.setText(Messages.SimpleAnalysisUI_properties);\n tabFolder1 = new TabFolder(group4, SWT.NONE);\n tabItem1 = new TabItem(tabFolder1, SWT.NONE);\n tabItem1.setText(Messages.FullAnalysisUI_firsttablabel);\n composite3 = new Composite(tabFolder1, SWT.NONE);\n composite3.setLayout(new GridLa", "post_mask_code": "\n composite3.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n tabItem1.setControl(composite3);\n composite2 = new Composite(composite3, SWT.NONE);\n composite2.setLayout(new GridLayout());\n composite2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n button3 = new Button(composite2, SWT.RADIO);\n button3.setText(Messages.SimpleAnalysisUI_monoalphabetic);\n button3.setSelection(true);\n button3.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent evt) {\n polyOnOffSelected(evt);\n }\n });\n button4 = new Button(composite2, SWT.RADIO);\n button4.setText(Messages.SimpleAnalysisUI_polyalphabetic);\n button4.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent evt) {\n polyOnOffSelected(evt);\n }\n });\n Label lblPolyalphabetic = new Label(composite2, SWT.WRAP);\n lblPolyalphabetic.setText(Messages.FullAnalysisUI_6);\n GridData layoutData = new GridData(SWT.FILL, SWT.CENTER, true, false);\n layoutData.widthHint = 100;\n lblPolyalphabetic.setLayoutData(layoutData);\n group2 = new Group(composite2, SWT.NONE);\n group2.setLayout(new GridLayout(2, false));\n group2.setText(Messages.SimpleAnalysisUI_vigeneresettings);\n spinner1 = new Spinner(group2, SWT.NONE);\n spinner1.addMouseListener(new MouseAdapter() {\n\n @Override\n public void mouseDown(MouseEvent evt) {\n recalcGraph();\n }\n });\n spinner1.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent evt) {\n changedVigOptions();\n }\n });\n spinner1.setSelection(1);\n label1 = new Label(group2, SWT.NONE);\n label1.setText(Messages.SimpleAnalysisUI_keylength);\n spinner2 = new Spinner(group2, SWT.NONE);\n spinner2.addMouseListener(new MouseAdapter() {\n\n @Override\n public void mouseDown(MouseEvent evt) {\n recalcGraph();\n }\n });\n spinner2.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent evt) {\n changedVigOptions();\n }\n });\n spinner2.setSelection(0);\n label2 = new Label(group2, SWT.NONE);\n label2.setText(Messages.SimpleAnalysisUI_offset);\n // @Override\n tabItem2 = new TabItem(tabFolder1, SWT.NONE);\n tabItem2.setText(Messages.FullAnalysisUI_thirdtablabel);\n composite4 = new Composite(tabFolder1, SWT.NONE);\n composite4.setLayout(new GridLayout());\n tabItem2.setControl(composite4);\n label3 = new Label(composite4, SWT.WRAP);\n GridData layoutData1 = new GridData(SWT.FILL, SWT.FILL, true, false);\n label3.setLayoutData(layoutData1);\n label4 = new Label(composite4, SWT.WRAP);\n GridData layoutData2 = new GridData(SWT.FILL, SWT.FILL, true, false);\n label4.setLayoutData(layoutData2);\n label5 = new Label(composite4, SWT.NONE);\n label5.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));\n text1 = new Text(composite4, SWT.V_SCROLL | SWT.BORDER | SWT.MULTI | SWT.WRAP);\n text1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n recalcSourceInfo();\n tabFolder1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n tabFolder1.setSelection(0);\n layout();\n }\n\n /**\n * Method for aggregating information about source text file.\n */\n protected void recalcSourceInfo() {\n if (text == null) {\n label3.setText(Messages.FullAnalysisUI_source + \" -\");\n label4.setText(Messages.FullAnalysisUI_textlength + \" -\");\n text1.setText(\"\");\n composite4.layout(new Control[] { label3, label4 });\n } else {\n label3.setText(Messages.FullAnalysisUI_source + \" \" + source.toString());\n String totalLength = Integer.toString(text.length());\n label4.setText(Messages.FullAnalysisUI_textlength + \" \" + totalLength);\n label5.setText(Messages.FullAnalysisUI_textexcerpt);\n text1.setText(text.substring(0, (text.length() > 1000) ? 1000 : text.length()) + ((text.length() > 1000) ? \"...\" : \"\"));\n text1.setEditable(false);\n }\n }\n\n /**\n * executes a TextModify Wizard.\n *\n * @param the Settings that have to be displayed at the beginning.\n * @return the selected settings.\n */\n public class FreqAnalysisJob extends BackgroundJob {\n\n private String text;\n\n private int myLength;\n\n private int myOffset;\n\n private String myOverlayAlphabet;\n\n public TransformData myModifySettings;\n\n @Override\n public String name() {\n return \"Frequency Analysis\";\n }\n\n @Override\n public IStatus computation(IProgressMonitor monitor) {\n SimpleAnalysisUI.this.return__freqanalysis = new FreqAnalysisCalc(this.text, this.myLength, this.myOffset, this.myModifySettings);\n return Status.OK_STATUS;\n }\n }\n\n /**\n * frequency analysis main procedure\n */\n @Override\n protected void analyze() {\n FreqAnalysisJob job = new FreqAnalysisJob();\n job.text = text;\n job.myLength = myLength;\n job.myOffset = myOffset;\n job.myModifySettings = myModifySettings;\n job.finalizeListeners.add(status -> {\n getDisplay().syncExec(() -> {\n job.liftNoClickDisplaySynced(getDisplay());\n if (status == Status.OK_STATUS) {\n myAnalysis = return__freqanalysis;\n myGraph.setAnalysis(myAnalysis);\n }\n });\n });\n job.imposeNoClickDisplayCurrentShellSynced(getDisplay());\n job.runInBackground();\n }\n\n /**\n * excludes a control from the Layout calculation\n *\n * @param that\n * @param hideit\n */\n private void hideObject(final Control that, final boolean hideit) {\n GridData GData = (GridData) that.getLayoutData();\n // the (GData != null) test is to work around a NullPointerException (bug #95)\n // happening after one leaves the Frequency Analysis open\n // while closing down JCrypTool, then restarts JCrypTool\n if (GData != null) {\n GData.exclude = true && hideit;\n }\n that.setVisible(true && !hideit);\n Control[] myArray = { that };\n layout(myArray);\n }\n\n private void polyOnOffSelected(final SelectionEvent evt) {\n hideObject(group2, button3.getSelection());\n }\n\n private void changedVigOptions() {\n if (spinner1.getSelection() < 1) {\n spinner1.setSelection(1);\n }\n if (spinner2.getSelection() < 0) {\n spinner2.setSelection(0);\n }\n spinner1.setMinimum(1);\n spinner1.setMaximum(999999);\n spinner2.setMinimum(0);\n spinner2.setMaximum(spinner1.getSelection() - 1);\n if (spinner2.getSelection() >= spinner1.getSelection()) {\n spinner2.setSelection(spinner1.getSelection() - 1);\n }\n spinner2.setMaximum(spinner1.getSelection());\n }\n\n public final void execute(final int keyLength, final int keyPos, final boolean resetShift, final boolean executeCalc) {\n if (keyLength > 0) {\n if (keyLength == 1) {\n button3.setSelection(true);\n button4.setSelection(false);\n } else {\n button3.setSelection(false);\n button4.setSelection(true);\n }\n polyOnOffSelected(null);\n spinner1.setSelection(keyLength);\n changedVigOptions();\n if (keyPos < 0) {\n recalcGraph();\n }\n }\n if (keyPos > -1) {\n spinner2.setSelection(keyPos);\n changedVigOptions();\n recalcGraph();\n }\n if (resetShift) {\n myGraph.getFrequencyGraph().resetDrag();\n }\n if (executeCalc) {\n if (checkEditor()) {\n text = getEditorText();\n recalcGraph();\n }\n }\n }\n\n public void resetClick() {\n // TODO Auto-generated method stub\n }\n}\n"} {"task_id": "Java_2737", "language": "Java", "task_type": "method_signature", "source_file": "java/github/micromata/projectforge/projectforge-wicket/src/main/java/org/projectforge/web/core/SearchAreaPanel.java", "mask_start_position": 5595, "mask_end_position": 5671, "canonical_solution": "@Override\n protected IModel getModel(final Object object) ", "pre_mask_code": "// Project ProjectForge Community Edition\n// www.projectforge.org\npackage org.projectforge.web.core;\n\nimport org.apache.wicket.Component;\nimport org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;\nimport org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;\nimport org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable;\nimport org.apache.wicket.markup.html.WebPage;\nimport org.apache.wicket.markup.html.basic.Label;\nimport org.apache.wicket.markup.html.link.Link;\nimport org.apache.wicket.markup.html.panel.Panel;\nimport org.apache.wicket.model.IModel;\nimport org.apache.wicket.model.Model;\nimport org.apache.wicket.request.mapper.parameter.PageParameters;\nimport org.apache.wicket.spring.injection.annot.SpringBean;\nimport org.projectforge.business.task.TaskDependentFilter;\nimport org.projectforge.common.BeanHelper;\nimport org.projectforge.framework.persistence.api.BaseSearchFilter;\nimport org.projectforge.framework.persistence.api.ExtendedBaseDO;\nimport org.projectforge.framework.persistence.api.SearchDao;\nimport org.projectforge.framework.persistence.api.SearchResultData;\nimport org.projectforge.framework.persistence.database.StatisticsCache;\nimport org.projectforge.framework.utils.NumberFormatter;\nimport org.projectforge.web.registry.WebRegistryEntry;\nimport org.projectforge.web.wicket.*;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SearchAreaPanel extends Panel {\n\n private static final long serialVersionUID = -4258095807245346743L;\n\n private static final int MAXIMUM_ENTRIES_WITHOUT_FILTER_SETTINGS = 10000;\n\n @SpringBean\n private SearchDao searchDao;\n\n @SpringBean\n private StatisticsCache statisticsCache;\n\n /**\n * @param page Needed, because in constructor this panel is not yet added to a page.\n * @param id\n * @param filter\n * @param registryEntry the area to show.\n */\n @SuppressWarnings(\"serial\")\n public SearchAreaPanel(final WebPage page, final String id, final SearchPageFilter filter, final WebRegistryEntry webRegistryEntry) {\n super(id);\n final long millis = System.currentTimeMillis();\n final Class> listPageColumnsCreatorClass = webRegistryEntry.getListPageColumnsCreatorClass();\n final IListPageColumnsCreator listPageColumnsCreator = listPageColumnsCreatorClass == null ? null : (IListPageColumnsCreator) BeanHelper.newInstance(listPageColumnsCreatorClass, PageParameters.class, new PageParameters());\n if (listPageColumnsCreator == null) {\n setVisible(false);\n return;\n }\n if (listPageColumnsCreator instanceof AbstractListPage) {\n ((AbstractListPage) listPageColumnsCreator).setCalledBySearchPage(true);\n }\n final Integer number = statisticsCache.getNumberOfEntities(webRegistryEntry.getDOClass());\n final Class registeredFilterClass = webRegistryEntry.getSearchFilterClass();\n final boolean isTaskDependentFilter = registeredFilterClass != null && TaskDependentFilter.class.isAssignableFrom(registeredFilterClass);\n if (number > MAXIMUM_ENTRIES_WITHOUT_FILTER_SETTINGS && (filter.getSearchString() == null || filter.getSearchString().length() < 3) && (isTaskDependentFilter == false || filter.getTask() == null) && filter.getStartTimeOfModification() == null && filter.getStopTimeOfModification() == null) {\n // Don't search to large tables if to less filter settings are given.\n setVisible(false);\n return;\n }\n filter.updateUseModificationFilterFlag();\n final BaseSearchFilter baseSearchFilter;\n if (isTaskDependentFilter == true) {\n baseSearchFilter = (BaseSearchFilter) BeanHelper.newInstance(registeredFilterClass, new Class[] { BaseSearchFilter.class }, filter);\n ((TaskDependentFilter) baseSearchFilter).setTaskId(filter.getTaskId());\n baseSearchFilter.copyBaseSearchFieldsFrom(filter);\n } else {\n baseSearchFilter = filter;\n }\n final List searchResult = searchDao.getEntries(baseSearchFilter, webRegistryEntry.getDOClass(), webRegistryEntry.getDao());\n boolean hasError = false;\n if (searchResult == null) {\n // An error occured!\n hasError = true;\n } else if (searchResult.size() == 0) {\n // No hits.\n setVisible(false);\n return;\n }\n boolean hasMore = false;\n if (hasError == true) {\n add(WicketUtils.getInvisibleComponent(\"dataTable\"));\n } else {\n final List> list = new ArrayList>();\n for (final SearchResultData data : searchResult) {\n if (data.getDataObject() != null) {\n list.add(data.getDataObject());\n } else {\n // Empty entry means: more entries found.\n hasMore = true;\n break;\n }\n }\n final List columns = listPageColumnsCreator.createColumns(page, false);\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n final DataTable dataTable = new DefaultDataTable(\"dataTable\", columns, new MySortableDataProvider(\"NOSORT\", SortOrder.DESCENDING) {\n\n @Override\n public List getList() {\n return list;\n }\n\n ", "post_mask_code": "{\n return new Model((Serializable) object);\n }\n }, filter.getMaxRows());\n add(dataTable);\n }\n final Label hasMoreEntries;\n if (hasError == true) {\n hasMoreEntries = new Label(\"hasMoreEntries\", page.getString(\"search.error\") + \" | \");\n } else {\n hasMoreEntries = new Label(\"hasMoreEntries\", page.getString(\"moreEntriesAvailable\") + \" | \");\n hasMoreEntries.setVisible(false);\n }\n add(hasMoreEntries);\n Component showMoreEntrieslink = null;\n if (hasMore == true) {\n final int maxRows = filter.getMaxRows();\n if (maxRows < SearchForm.MAX_PAGE_SIZE) {\n showMoreEntrieslink = new Link(\"showMoreEntrieslink\") {\n\n /**\n * @see org.apache.wicket.markup.html.link.Link#onClick()\n */\n @Override\n public void onClick() {\n for (final int number : AbstractListForm.PAGE_SIZES) {\n if (number > maxRows) {\n filter.setMaxRows(number);\n break;\n }\n }\n filter.setArea(webRegistryEntry.getId());\n }\n };\n add(showMoreEntrieslink);\n } else {\n hasMoreEntries.setVisible(true);\n }\n }\n if (showMoreEntrieslink == null) {\n add(new Label(\"showMoreEntrieslink\", \"[invisible]\").setVisible(false));\n }\n if (listPageColumnsCreator instanceof AbstractListPage) {\n add(new Link(\"listPageLink\") {\n\n /**\n * @see org.apache.wicket.markup.html.link.Link#onClick()\n */\n @Override\n public void onClick() {\n final AbstractListPage listPage = (AbstractListPage) listPageColumnsCreator;\n listPage.copySearchFieldsFrom(filter);\n setResponsePage(listPage);\n }\n });\n } else {\n add(new Label(\"listPageLink\", \"[invisible]\").setVisible(false));\n }\n final long duration = System.currentTimeMillis() - millis;\n add(new Label(\"areaTitle\", page.getString(webRegistryEntry.getI18nTitleHeading())));\n add(new Label(\"timeOfSearch\", NumberFormatter.format(duration)));\n }\n}\n"} {"task_id": "Java_2738", "language": "Java", "task_type": "method_body", "source_file": "java/github/micromata/projectforge/projectforge-wicket/src/main/java/org/projectforge/web/core/SearchAreaPanel.java", "mask_start_position": 6662, "mask_end_position": 7036, "canonical_solution": "{\n for (final int number : AbstractListForm.PAGE_SIZES) {\n if (number > maxRows) {\n filter.setMaxRows(number);\n break;\n }\n }\n filter.setArea(webRegistryEntry.getId());\n }", "pre_mask_code": "// Project ProjectForge Community Edition\n// www.projectforge.org\npackage org.projectforge.web.core;\n\nimport org.apache.wicket.Component;\nimport org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;\nimport org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;\nimport org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable;\nimport org.apache.wicket.markup.html.WebPage;\nimport org.apache.wicket.markup.html.basic.Label;\nimport org.apache.wicket.markup.html.link.Link;\nimport org.apache.wicket.markup.html.panel.Panel;\nimport org.apache.wicket.model.IModel;\nimport org.apache.wicket.model.Model;\nimport org.apache.wicket.request.mapper.parameter.PageParameters;\nimport org.apache.wicket.spring.injection.annot.SpringBean;\nimport org.projectforge.business.task.TaskDependentFilter;\nimport org.projectforge.common.BeanHelper;\nimport org.projectforge.framework.persistence.api.BaseSearchFilter;\nimport org.projectforge.framework.persistence.api.ExtendedBaseDO;\nimport org.projectforge.framework.persistence.api.SearchDao;\nimport org.projectforge.framework.persistence.api.SearchResultData;\nimport org.projectforge.framework.persistence.database.StatisticsCache;\nimport org.projectforge.framework.utils.NumberFormatter;\nimport org.projectforge.web.registry.WebRegistryEntry;\nimport org.projectforge.web.wicket.*;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SearchAreaPanel extends Panel {\n\n private static final long serialVersionUID = -4258095807245346743L;\n\n private static final int MAXIMUM_ENTRIES_WITHOUT_FILTER_SETTINGS = 10000;\n\n @SpringBean\n private SearchDao searchDao;\n\n @SpringBean\n private StatisticsCache statisticsCache;\n\n /**\n * @param page Needed, because in constructor this panel is not yet added to a page.\n * @param id\n * @param filter\n * @param registryEntry the area to show.\n */\n @SuppressWarnings(\"serial\")\n public SearchAreaPanel(final WebPage page, final String id, final SearchPageFilter filter, final WebRegistryEntry webRegistryEntry) {\n super(id);\n final long millis = System.currentTimeMillis();\n final Class> listPageColumnsCreatorClass = webRegistryEntry.getListPageColumnsCreatorClass();\n final IListPageColumnsCreator listPageColumnsCreator = listPageColumnsCreatorClass == null ? null : (IListPageColumnsCreator) BeanHelper.newInstance(listPageColumnsCreatorClass, PageParameters.class, new PageParameters());\n if (listPageColumnsCreator == null) {\n setVisible(false);\n return;\n }\n if (listPageColumnsCreator instanceof AbstractListPage) {\n ((AbstractListPage) listPageColumnsCreator).setCalledBySearchPage(true);\n }\n final Integer number = statisticsCache.getNumberOfEntities(webRegistryEntry.getDOClass());\n final Class registeredFilterClass = webRegistryEntry.getSearchFilterClass();\n final boolean isTaskDependentFilter = registeredFilterClass != null && TaskDependentFilter.class.isAssignableFrom(registeredFilterClass);\n if (number > MAXIMUM_ENTRIES_WITHOUT_FILTER_SETTINGS && (filter.getSearchString() == null || filter.getSearchString().length() < 3) && (isTaskDependentFilter == false || filter.getTask() == null) && filter.getStartTimeOfModification() == null && filter.getStopTimeOfModification() == null) {\n // Don't search to large tables if to less filter settings are given.\n setVisible(false);\n return;\n }\n filter.updateUseModificationFilterFlag();\n final BaseSearchFilter baseSearchFilter;\n if (isTaskDependentFilter == true) {\n baseSearchFilter = (BaseSearchFilter) BeanHelper.newInstance(registeredFilterClass, new Class[] { BaseSearchFilter.class }, filter);\n ((TaskDependentFilter) baseSearchFilter).setTaskId(filter.getTaskId());\n baseSearchFilter.copyBaseSearchFieldsFrom(filter);\n } else {\n baseSearchFilter = filter;\n }\n final List searchResult = searchDao.getEntries(baseSearchFilter, webRegistryEntry.getDOClass(), webRegistryEntry.getDao());\n boolean hasError = false;\n if (searchResult == null) {\n // An error occured!\n hasError = true;\n } else if (searchResult.size() == 0) {\n // No hits.\n setVisible(false);\n return;\n }\n boolean hasMore = false;\n if (hasError == true) {\n add(WicketUtils.getInvisibleComponent(\"dataTable\"));\n } else {\n final List> list = new ArrayList>();\n for (final SearchResultData data : searchResult) {\n if (data.getDataObject() != null) {\n list.add(data.getDataObject());\n } else {\n // Empty entry means: more entries found.\n hasMore = true;\n break;\n }\n }\n final List columns = listPageColumnsCreator.createColumns(page, false);\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n final DataTable dataTable = new DefaultDataTable(\"dataTable\", columns, new MySortableDataProvider(\"NOSORT\", SortOrder.DESCENDING) {\n\n @Override\n public List getList() {\n return list;\n }\n\n @Override\n protected IModel getModel(final Object object) {\n return new Model((Serializable) object);\n }\n }, filter.getMaxRows());\n add(dataTable);\n }\n final Label hasMoreEntries;\n if (hasError == true) {\n hasMoreEntries = new Label(\"hasMoreEntries\", page.getString(\"search.error\") + \" | \");\n } else {\n hasMoreEntries = new Label(\"hasMoreEntries\", page.getString(\"moreEntriesAvailable\") + \" | \");\n hasMoreEntries.setVisible(false);\n }\n add(hasMoreEntries);\n Component showMoreEntrieslink = null;\n if (hasMore == true) {\n final int maxRows = filter.getMaxRows();\n if (maxRows < SearchForm.MAX_PAGE_SIZE) {\n showMoreEntrieslink = new Link(\"showMoreEntrieslink\") {\n\n /**\n * @see org.apache.wicket.markup.html.link.Link#onClick()\n */\n @Override\n public void onClick() ", "post_mask_code": "\n };\n add(showMoreEntrieslink);\n } else {\n hasMoreEntries.setVisible(true);\n }\n }\n if (showMoreEntrieslink == null) {\n add(new Label(\"showMoreEntrieslink\", \"[invisible]\").setVisible(false));\n }\n if (listPageColumnsCreator instanceof AbstractListPage) {\n add(new Link(\"listPageLink\") {\n\n /**\n * @see org.apache.wicket.markup.html.link.Link#onClick()\n */\n @Override\n public void onClick() {\n final AbstractListPage listPage = (AbstractListPage) listPageColumnsCreator;\n listPage.copySearchFieldsFrom(filter);\n setResponsePage(listPage);\n }\n });\n } else {\n add(new Label(\"listPageLink\", \"[invisible]\").setVisible(false));\n }\n final long duration = System.currentTimeMillis() - millis;\n add(new Label(\"areaTitle\", page.getString(webRegistryEntry.getI18nTitleHeading())));\n add(new Label(\"timeOfSearch\", NumberFormatter.format(duration)));\n }\n}\n"} {"task_id": "Java_2739", "language": "Java", "task_type": "single_line", "source_file": "java/github/micromata/projectforge/projectforge-wicket/src/main/java/org/projectforge/web/core/SearchAreaPanel.java", "mask_start_position": 7770, "mask_end_position": 7807, "canonical_solution": "istPage.copySearchFieldsFrom(filter);", "pre_mask_code": "// Project ProjectForge Community Edition\n// www.projectforge.org\npackage org.projectforge.web.core;\n\nimport org.apache.wicket.Component;\nimport org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;\nimport org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;\nimport org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable;\nimport org.apache.wicket.markup.html.WebPage;\nimport org.apache.wicket.markup.html.basic.Label;\nimport org.apache.wicket.markup.html.link.Link;\nimport org.apache.wicket.markup.html.panel.Panel;\nimport org.apache.wicket.model.IModel;\nimport org.apache.wicket.model.Model;\nimport org.apache.wicket.request.mapper.parameter.PageParameters;\nimport org.apache.wicket.spring.injection.annot.SpringBean;\nimport org.projectforge.business.task.TaskDependentFilter;\nimport org.projectforge.common.BeanHelper;\nimport org.projectforge.framework.persistence.api.BaseSearchFilter;\nimport org.projectforge.framework.persistence.api.ExtendedBaseDO;\nimport org.projectforge.framework.persistence.api.SearchDao;\nimport org.projectforge.framework.persistence.api.SearchResultData;\nimport org.projectforge.framework.persistence.database.StatisticsCache;\nimport org.projectforge.framework.utils.NumberFormatter;\nimport org.projectforge.web.registry.WebRegistryEntry;\nimport org.projectforge.web.wicket.*;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SearchAreaPanel extends Panel {\n\n private static final long serialVersionUID = -4258095807245346743L;\n\n private static final int MAXIMUM_ENTRIES_WITHOUT_FILTER_SETTINGS = 10000;\n\n @SpringBean\n private SearchDao searchDao;\n\n @SpringBean\n private StatisticsCache statisticsCache;\n\n /**\n * @param page Needed, because in constructor this panel is not yet added to a page.\n * @param id\n * @param filter\n * @param registryEntry the area to show.\n */\n @SuppressWarnings(\"serial\")\n public SearchAreaPanel(final WebPage page, final String id, final SearchPageFilter filter, final WebRegistryEntry webRegistryEntry) {\n super(id);\n final long millis = System.currentTimeMillis();\n final Class> listPageColumnsCreatorClass = webRegistryEntry.getListPageColumnsCreatorClass();\n final IListPageColumnsCreator listPageColumnsCreator = listPageColumnsCreatorClass == null ? null : (IListPageColumnsCreator) BeanHelper.newInstance(listPageColumnsCreatorClass, PageParameters.class, new PageParameters());\n if (listPageColumnsCreator == null) {\n setVisible(false);\n return;\n }\n if (listPageColumnsCreator instanceof AbstractListPage) {\n ((AbstractListPage) listPageColumnsCreator).setCalledBySearchPage(true);\n }\n final Integer number = statisticsCache.getNumberOfEntities(webRegistryEntry.getDOClass());\n final Class registeredFilterClass = webRegistryEntry.getSearchFilterClass();\n final boolean isTaskDependentFilter = registeredFilterClass != null && TaskDependentFilter.class.isAssignableFrom(registeredFilterClass);\n if (number > MAXIMUM_ENTRIES_WITHOUT_FILTER_SETTINGS && (filter.getSearchString() == null || filter.getSearchString().length() < 3) && (isTaskDependentFilter == false || filter.getTask() == null) && filter.getStartTimeOfModification() == null && filter.getStopTimeOfModification() == null) {\n // Don't search to large tables if to less filter settings are given.\n setVisible(false);\n return;\n }\n filter.updateUseModificationFilterFlag();\n final BaseSearchFilter baseSearchFilter;\n if (isTaskDependentFilter == true) {\n baseSearchFilter = (BaseSearchFilter) BeanHelper.newInstance(registeredFilterClass, new Class[] { BaseSearchFilter.class }, filter);\n ((TaskDependentFilter) baseSearchFilter).setTaskId(filter.getTaskId());\n baseSearchFilter.copyBaseSearchFieldsFrom(filter);\n } else {\n baseSearchFilter = filter;\n }\n final List searchResult = searchDao.getEntries(baseSearchFilter, webRegistryEntry.getDOClass(), webRegistryEntry.getDao());\n boolean hasError = false;\n if (searchResult == null) {\n // An error occured!\n hasError = true;\n } else if (searchResult.size() == 0) {\n // No hits.\n setVisible(false);\n return;\n }\n boolean hasMore = false;\n if (hasError == true) {\n add(WicketUtils.getInvisibleComponent(\"dataTable\"));\n } else {\n final List> list = new ArrayList>();\n for (final SearchResultData data : searchResult) {\n if (data.getDataObject() != null) {\n list.add(data.getDataObject());\n } else {\n // Empty entry means: more entries found.\n hasMore = true;\n break;\n }\n }\n final List columns = listPageColumnsCreator.createColumns(page, false);\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n final DataTable dataTable = new DefaultDataTable(\"dataTable\", columns, new MySortableDataProvider(\"NOSORT\", SortOrder.DESCENDING) {\n\n @Override\n public List getList() {\n return list;\n }\n\n @Override\n protected IModel getModel(final Object object) {\n return new Model((Serializable) object);\n }\n }, filter.getMaxRows());\n add(dataTable);\n }\n final Label hasMoreEntries;\n if (hasError == true) {\n hasMoreEntries = new Label(\"hasMoreEntries\", page.getString(\"search.error\") + \" | \");\n } else {\n hasMoreEntries = new Label(\"hasMoreEntries\", page.getString(\"moreEntriesAvailable\") + \" | \");\n hasMoreEntries.setVisible(false);\n }\n add(hasMoreEntries);\n Component showMoreEntrieslink = null;\n if (hasMore == true) {\n final int maxRows = filter.getMaxRows();\n if (maxRows < SearchForm.MAX_PAGE_SIZE) {\n showMoreEntrieslink = new Link(\"showMoreEntrieslink\") {\n\n /**\n * @see org.apache.wicket.markup.html.link.Link#onClick()\n */\n @Override\n public void onClick() {\n for (final int number : AbstractListForm.PAGE_SIZES) {\n if (number > maxRows) {\n filter.setMaxRows(number);\n break;\n }\n }\n filter.setArea(webRegistryEntry.getId());\n }\n };\n add(showMoreEntrieslink);\n } else {\n hasMoreEntries.setVisible(true);\n }\n }\n if (showMoreEntrieslink == null) {\n add(new Label(\"showMoreEntrieslink\", \"[invisible]\").setVisible(false));\n }\n if (listPageColumnsCreator instanceof AbstractListPage) {\n add(new Link(\"listPageLink\") {\n\n /**\n * @see org.apache.wicket.markup.html.link.Link#onClick()\n */\n @Override\n public void onClick() {\n final AbstractListPage listPage = (AbstractListPage) listPageColumnsCreator;\n l", "post_mask_code": "\n setResponsePage(listPage);\n }\n });\n } else {\n add(new Label(\"listPageLink\", \"[invisible]\").setVisible(false));\n }\n final long duration = System.currentTimeMillis() - millis;\n add(new Label(\"areaTitle\", page.getString(webRegistryEntry.getI18nTitleHeading())));\n add(new Label(\"timeOfSearch\", NumberFormatter.format(duration)));\n }\n}\n"} {"task_id": "Java_2740", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/micromata/projectforge/projectforge-wicket/src/main/java/org/projectforge/web/core/SearchAreaPanel.java", "mask_start_position": 7584, "mask_end_position": 7872, "canonical_solution": "@Override\n public void onClick() {\n final AbstractListPage listPage = (AbstractListPage) listPageColumnsCreator;\n listPage.copySearchFieldsFrom(filter);\n setResponsePage(listPage);\n }", "pre_mask_code": "// Project ProjectForge Community Edition\n// www.projectforge.org\npackage org.projectforge.web.core;\n\nimport org.apache.wicket.Component;\nimport org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;\nimport org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;\nimport org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable;\nimport org.apache.wicket.markup.html.WebPage;\nimport org.apache.wicket.markup.html.basic.Label;\nimport org.apache.wicket.markup.html.link.Link;\nimport org.apache.wicket.markup.html.panel.Panel;\nimport org.apache.wicket.model.IModel;\nimport org.apache.wicket.model.Model;\nimport org.apache.wicket.request.mapper.parameter.PageParameters;\nimport org.apache.wicket.spring.injection.annot.SpringBean;\nimport org.projectforge.business.task.TaskDependentFilter;\nimport org.projectforge.common.BeanHelper;\nimport org.projectforge.framework.persistence.api.BaseSearchFilter;\nimport org.projectforge.framework.persistence.api.ExtendedBaseDO;\nimport org.projectforge.framework.persistence.api.SearchDao;\nimport org.projectforge.framework.persistence.api.SearchResultData;\nimport org.projectforge.framework.persistence.database.StatisticsCache;\nimport org.projectforge.framework.utils.NumberFormatter;\nimport org.projectforge.web.registry.WebRegistryEntry;\nimport org.projectforge.web.wicket.*;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class SearchAreaPanel extends Panel {\n\n private static final long serialVersionUID = -4258095807245346743L;\n\n private static final int MAXIMUM_ENTRIES_WITHOUT_FILTER_SETTINGS = 10000;\n\n @SpringBean\n private SearchDao searchDao;\n\n @SpringBean\n private StatisticsCache statisticsCache;\n\n /**\n * @param page Needed, because in constructor this panel is not yet added to a page.\n * @param id\n * @param filter\n * @param registryEntry the area to show.\n */\n @SuppressWarnings(\"serial\")\n public SearchAreaPanel(final WebPage page, final String id, final SearchPageFilter filter, final WebRegistryEntry webRegistryEntry) {\n super(id);\n final long millis = System.currentTimeMillis();\n final Class> listPageColumnsCreatorClass = webRegistryEntry.getListPageColumnsCreatorClass();\n final IListPageColumnsCreator listPageColumnsCreator = listPageColumnsCreatorClass == null ? null : (IListPageColumnsCreator) BeanHelper.newInstance(listPageColumnsCreatorClass, PageParameters.class, new PageParameters());\n if (listPageColumnsCreator == null) {\n setVisible(false);\n return;\n }\n if (listPageColumnsCreator instanceof AbstractListPage) {\n ((AbstractListPage) listPageColumnsCreator).setCalledBySearchPage(true);\n }\n final Integer number = statisticsCache.getNumberOfEntities(webRegistryEntry.getDOClass());\n final Class registeredFilterClass = webRegistryEntry.getSearchFilterClass();\n final boolean isTaskDependentFilter = registeredFilterClass != null && TaskDependentFilter.class.isAssignableFrom(registeredFilterClass);\n if (number > MAXIMUM_ENTRIES_WITHOUT_FILTER_SETTINGS && (filter.getSearchString() == null || filter.getSearchString().length() < 3) && (isTaskDependentFilter == false || filter.getTask() == null) && filter.getStartTimeOfModification() == null && filter.getStopTimeOfModification() == null) {\n // Don't search to large tables if to less filter settings are given.\n setVisible(false);\n return;\n }\n filter.updateUseModificationFilterFlag();\n final BaseSearchFilter baseSearchFilter;\n if (isTaskDependentFilter == true) {\n baseSearchFilter = (BaseSearchFilter) BeanHelper.newInstance(registeredFilterClass, new Class[] { BaseSearchFilter.class }, filter);\n ((TaskDependentFilter) baseSearchFilter).setTaskId(filter.getTaskId());\n baseSearchFilter.copyBaseSearchFieldsFrom(filter);\n } else {\n baseSearchFilter = filter;\n }\n final List searchResult = searchDao.getEntries(baseSearchFilter, webRegistryEntry.getDOClass(), webRegistryEntry.getDao());\n boolean hasError = false;\n if (searchResult == null) {\n // An error occured!\n hasError = true;\n } else if (searchResult.size() == 0) {\n // No hits.\n setVisible(false);\n return;\n }\n boolean hasMore = false;\n if (hasError == true) {\n add(WicketUtils.getInvisibleComponent(\"dataTable\"));\n } else {\n final List> list = new ArrayList>();\n for (final SearchResultData data : searchResult) {\n if (data.getDataObject() != null) {\n list.add(data.getDataObject());\n } else {\n // Empty entry means: more entries found.\n hasMore = true;\n break;\n }\n }\n final List columns = listPageColumnsCreator.createColumns(page, false);\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n final DataTable dataTable = new DefaultDataTable(\"dataTable\", columns, new MySortableDataProvider(\"NOSORT\", SortOrder.DESCENDING) {\n\n @Override\n public List getList() {\n return list;\n }\n\n @Override\n protected IModel getModel(final Object object) {\n return new Model((Serializable) object);\n }\n }, filter.getMaxRows());\n add(dataTable);\n }\n final Label hasMoreEntries;\n if (hasError == true) {\n hasMoreEntries = new Label(\"hasMoreEntries\", page.getString(\"search.error\") + \" | \");\n } else {\n hasMoreEntries = new Label(\"hasMoreEntries\", page.getString(\"moreEntriesAvailable\") + \" | \");\n hasMoreEntries.setVisible(false);\n }\n add(hasMoreEntries);\n Component showMoreEntrieslink = null;\n if (hasMore == true) {\n final int maxRows = filter.getMaxRows();\n if (maxRows < SearchForm.MAX_PAGE_SIZE) {\n showMoreEntrieslink = new Link(\"showMoreEntrieslink\") {\n\n /**\n * @see org.apache.wicket.markup.html.link.Link#onClick()\n */\n @Override\n public void onClick() {\n for (final int number : AbstractListForm.PAGE_SIZES) {\n if (number > maxRows) {\n filter.setMaxRows(number);\n break;\n }\n }\n filter.setArea(webRegistryEntry.getId());\n }\n };\n add(showMoreEntrieslink);\n } else {\n hasMoreEntries.setVisible(true);\n }\n }\n if (showMoreEntrieslink == null) {\n add(new Label(\"showMoreEntrieslink\", \"[invisible]\").setVisible(false));\n }\n if (listPageColumnsCreator instanceof AbstractListPage) {\n add(new Link(\"listPageLink\") {\n\n /**\n * @see org.apache.wicket.markup.html.link.Link#onClick()\n */\n ", "post_mask_code": "\n });\n } else {\n add(new Label(\"listPageLink\", \"[invisible]\").setVisible(false));\n }\n final long duration = System.currentTimeMillis() - millis;\n add(new Label(\"areaTitle\", page.getString(webRegistryEntry.getI18nTitleHeading())));\n add(new Label(\"timeOfSearch\", NumberFormatter.format(duration)));\n }\n}\n"} {"task_id": "Java_2741", "language": "Java", "task_type": "method_signature", "source_file": "java/github/konsoletyper/teavm/classlib/src/main/java/org/teavm/classlib/java/util/jar/TJarUtils.java", "mask_start_position": 215, "mask_end_position": 272, "canonical_solution": "static boolean asciiEqualsIgnoreCase(byte[] a, byte[] b) ", "pre_mask_code": "package org.teavm.classlib.java.util.jar;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.ByteBuffer;\nimport java.util.Arrays;\n\nfinal class TJarUtils {\n\n private TJarUtils() {\n }\n\n ", "post_mask_code": "{\n if (a.length != b.length) {\n return false;\n }\n for (int i = 0; i < a.length; ++i) {\n if (Character.toLowerCase((char) a[i]) != Character.toLowerCase((char) b[i])) {\n return false;\n }\n }\n return true;\n }\n\n static byte[] readFullyAndClose(InputStream input) throws IOException {\n ByteBuffer result = ByteBuffer.wrap(new byte[Math.min(512, input.available())]);\n while (true) {\n if (result.remaining() == 0) {\n result = ByteBuffer.wrap(Arrays.copyOf(result.array(), result.capacity() * 2));\n }\n int actuallyRead = input.read(result.array(), result.position(), result.remaining());\n if (actuallyRead == -1) {\n break;\n }\n result.position(result.position() + actuallyRead);\n }\n byte[] b = Arrays.copyOf(result.array(), result.position());\n input.close();\n return b;\n }\n}\n"} {"task_id": "Java_2742", "language": "Java", "task_type": "method_body", "source_file": "java/github/konsoletyper/teavm/classlib/src/main/java/org/teavm/classlib/java/util/jar/TJarUtils.java", "mask_start_position": 272, "mask_end_position": 563, "canonical_solution": "{\n if (a.length != b.length) {\n return false;\n }\n for (int i = 0; i < a.length; ++i) {\n if (Character.toLowerCase((char) a[i]) != Character.toLowerCase((char) b[i])) {\n return false;\n }\n }\n return true;\n }", "pre_mask_code": "package org.teavm.classlib.java.util.jar;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.ByteBuffer;\nimport java.util.Arrays;\n\nfinal class TJarUtils {\n\n private TJarUtils() {\n }\n\n static boolean asciiEqualsIgnoreCase(byte[] a, byte[] b) ", "post_mask_code": "\n\n static byte[] readFullyAndClose(InputStream input) throws IOException {\n ByteBuffer result = ByteBuffer.wrap(new byte[Math.min(512, input.available())]);\n while (true) {\n if (result.remaining() == 0) {\n result = ByteBuffer.wrap(Arrays.copyOf(result.array(), result.capacity() * 2));\n }\n int actuallyRead = input.read(result.array(), result.position(), result.remaining());\n if (actuallyRead == -1) {\n break;\n }\n result.position(result.position() + actuallyRead);\n }\n byte[] b = Arrays.copyOf(result.array(), result.position());\n input.close();\n return b;\n }\n}\n"} {"task_id": "Java_2743", "language": "Java", "task_type": "single_line", "source_file": "java/github/konsoletyper/teavm/classlib/src/main/java/org/teavm/classlib/java/util/jar/TJarUtils.java", "mask_start_position": 553, "mask_end_position": 557, "canonical_solution": "rue;", "pre_mask_code": "package org.teavm.classlib.java.util.jar;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.ByteBuffer;\nimport java.util.Arrays;\n\nfinal class TJarUtils {\n\n private TJarUtils() {\n }\n\n static boolean asciiEqualsIgnoreCase(byte[] a, byte[] b) {\n if (a.length != b.length) {\n return false;\n }\n for (int i = 0; i < a.length; ++i) {\n if (Character.toLowerCase((char) a[i]) != Character.toLowerCase((char) b[i])) {\n return false;\n }\n }\n return t", "post_mask_code": "\n }\n\n static byte[] readFullyAndClose(InputStream input) throws IOException {\n ByteBuffer result = ByteBuffer.wrap(new byte[Math.min(512, input.available())]);\n while (true) {\n if (result.remaining() == 0) {\n result = ByteBuffer.wrap(Arrays.copyOf(result.array(), result.capacity() * 2));\n }\n int actuallyRead = input.read(result.array(), result.position(), result.remaining());\n if (actuallyRead == -1) {\n break;\n }\n result.position(result.position() + actuallyRead);\n }\n byte[] b = Arrays.copyOf(result.array(), result.position());\n input.close();\n return b;\n }\n}\n"} {"task_id": "Java_2744", "language": "Java", "task_type": "for_statement", "source_file": "java/github/konsoletyper/teavm/classlib/src/main/java/org/teavm/classlib/java/util/jar/TJarUtils.java", "mask_start_position": 354, "mask_end_position": 536, "canonical_solution": "for (int i = 0; i < a.length; ++i) {\n if (Character.toLowerCase((char) a[i]) != Character.toLowerCase((char) b[i])) {\n return false;\n }\n }", "pre_mask_code": "package org.teavm.classlib.java.util.jar;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.ByteBuffer;\nimport java.util.Arrays;\n\nfinal class TJarUtils {\n\n private TJarUtils() {\n }\n\n static boolean asciiEqualsIgnoreCase(byte[] a, byte[] b) {\n if (a.length != b.length) {\n return false;\n }\n ", "post_mask_code": "\n return true;\n }\n\n static byte[] readFullyAndClose(InputStream input) throws IOException {\n ByteBuffer result = ByteBuffer.wrap(new byte[Math.min(512, input.available())]);\n while (true) {\n if (result.remaining() == 0) {\n result = ByteBuffer.wrap(Arrays.copyOf(result.array(), result.capacity() * 2));\n }\n int actuallyRead = input.read(result.array(), result.position(), result.remaining());\n if (actuallyRead == -1) {\n break;\n }\n result.position(result.position() + actuallyRead);\n }\n byte[] b = Arrays.copyOf(result.array(), result.position());\n input.close();\n return b;\n }\n}\n"} {"task_id": "Java_2745", "language": "Java", "task_type": "while_statement", "source_file": "java/github/konsoletyper/teavm/classlib/src/main/java/org/teavm/classlib/java/util/jar/TJarUtils.java", "mask_start_position": 738, "mask_end_position": 1151, "canonical_solution": "while (true) {\n if (result.remaining() == 0) {\n result = ByteBuffer.wrap(Arrays.copyOf(result.array(), result.capacity() * 2));\n }\n int actuallyRead = input.read(result.array(), result.position(), result.remaining());\n if (actuallyRead == -1) {\n break;\n }\n result.position(result.position() + actuallyRead);\n }", "pre_mask_code": "package org.teavm.classlib.java.util.jar;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.ByteBuffer;\nimport java.util.Arrays;\n\nfinal class TJarUtils {\n\n private TJarUtils() {\n }\n\n static boolean asciiEqualsIgnoreCase(byte[] a, byte[] b) {\n if (a.length != b.length) {\n return false;\n }\n for (int i = 0; i < a.length; ++i) {\n if (Character.toLowerCase((char) a[i]) != Character.toLowerCase((char) b[i])) {\n return false;\n }\n }\n return true;\n }\n\n static byte[] readFullyAndClose(InputStream input) throws IOException {\n ByteBuffer result = ByteBuffer.wrap(new byte[Math.min(512, input.available())]);\n ", "post_mask_code": "\n byte[] b = Arrays.copyOf(result.array(), result.position());\n input.close();\n return b;\n }\n}\n"} {"task_id": "Java_2746", "language": "Java", "task_type": "method_signature", "source_file": "java/github/flowable/flowable-engine/modules/flowable5-compatibility-testdata/src/main/java/org/flowable/compatibility/testdata/generator/AsyncFailingJobTestDataGenerator.java", "mask_start_position": 350, "mask_end_position": 422, "canonical_solution": "@Override\n public void generateTestData(ProcessEngine processEngine) ", "pre_mask_code": "package org.flowable.compatibility.testdata.generator;\n\nimport org.activiti.engine.ProcessEngine;\nimport org.activiti.engine.RepositoryService;\nimport org.activiti.engine.RuntimeService;\nimport org.flowable.compatibility.testdata.Flowable5TestDataGenerator;\n\npublic class AsyncFailingJobTestDataGenerator implements Flowable5TestDataGenerator {\n\n ", "post_mask_code": "{\n RepositoryService repositoryService = processEngine.getRepositoryService();\n repositoryService.createDeployment().addClasspathResource(\"async-failing-expression.bpmn20.xml\").deploy();\n RuntimeService runtimeService = processEngine.getRuntimeService();\n runtimeService.startProcessInstanceByKey(\"asyncFailingExpression\");\n }\n}\n"} {"task_id": "Java_2747", "language": "Java", "task_type": "method_body", "source_file": "java/github/flowable/flowable-engine/modules/flowable5-compatibility-testdata/src/main/java/org/flowable/compatibility/testdata/generator/AsyncFailingJobTestDataGenerator.java", "mask_start_position": 422, "mask_end_position": 779, "canonical_solution": "{\n RepositoryService repositoryService = processEngine.getRepositoryService();\n repositoryService.createDeployment().addClasspathResource(\"async-failing-expression.bpmn20.xml\").deploy();\n RuntimeService runtimeService = processEngine.getRuntimeService();\n runtimeService.startProcessInstanceByKey(\"asyncFailingExpression\");\n }", "pre_mask_code": "package org.flowable.compatibility.testdata.generator;\n\nimport org.activiti.engine.ProcessEngine;\nimport org.activiti.engine.RepositoryService;\nimport org.activiti.engine.RuntimeService;\nimport org.flowable.compatibility.testdata.Flowable5TestDataGenerator;\n\npublic class AsyncFailingJobTestDataGenerator implements Flowable5TestDataGenerator {\n\n @Override\n public void generateTestData(ProcessEngine processEngine) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2748", "language": "Java", "task_type": "single_line", "source_file": "java/github/flowable/flowable-engine/modules/flowable5-compatibility-testdata/src/main/java/org/flowable/compatibility/testdata/generator/AsyncFailingJobTestDataGenerator.java", "mask_start_position": 579, "mask_end_position": 622, "canonical_solution": "c-failing-expression.bpmn20.xml\").deploy();", "pre_mask_code": "package org.flowable.compatibility.testdata.generator;\n\nimport org.activiti.engine.ProcessEngine;\nimport org.activiti.engine.RepositoryService;\nimport org.activiti.engine.RuntimeService;\nimport org.flowable.compatibility.testdata.Flowable5TestDataGenerator;\n\npublic class AsyncFailingJobTestDataGenerator implements Flowable5TestDataGenerator {\n\n @Override\n public void generateTestData(ProcessEngine processEngine) {\n RepositoryService repositoryService = processEngine.getRepositoryService();\n repositoryService.createDeployment().addClasspathResource(\"asyn", "post_mask_code": "\n RuntimeService runtimeService = processEngine.getRuntimeService();\n runtimeService.startProcessInstanceByKey(\"asyncFailingExpression\");\n }\n}\n"} {"task_id": "Java_2749", "language": "Java", "task_type": "method_signature", "source_file": "java/github/xixifeng/fastquery/src/main/java/org/fastquery/util/FastQueryJSONObject.java", "mask_start_position": 1272, "mask_end_position": 1309, "canonical_solution": "public static int getSlowQueryTime() ", "pre_mask_code": "/*\n *\n *\n * For more information, please see http://example.com.\n *\n */\npackage org.fastquery.util;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Pattern;\nimport org.apache.commons.lang3.StringUtils;\nimport org.fastquery.core.RepositoryException;\nimport com.alibaba.fastjson.JSONArray;\nimport com.alibaba.fastjson.JSONObject;\n\n/**\n * @author xixifeng (example@nnthink.com)\n */\npublic class FastQueryJSONObject {\n\n private static final String DEBUG = \"debug\";\n\n private static JSONObject jo;\n\n private FastQueryJSONObject() {\n }\n\n static synchronized void setJsonObject(JSONObject o) {\n if (jo == null) {\n jo = o;\n } else {\n throw new RepositoryException(\"fastquery.json不能重复装载\");\n }\n }\n\n public static String getBasedir() {\n return jo.getString(\"basedir\");\n }\n\n public static boolean getDebug() {\n return (boolean) jo.getOrDefault(DEBUG, false);\n }\n\n public static List getQueries() {\n List strs = new ArrayList<>();\n JSONArray jsonArray = jo.getJSONArray(\"queries\");\n if (jsonArray == null) {\n return strs;\n }\n jsonArray.forEach(s -> strs.add(s.toString()));\n return strs;\n }\n\n ", "post_mask_code": "{\n return jo.getIntValue(\"slowQueryTime\");\n }\n\n static void check() {\n List strs = getQueries();\n for (String str : strs) {\n if (StringUtils.EMPTY.equals(str)) {\n continue;\n }\n if (str.charAt(0) == '/') {\n throw new RepositoryException(String.format(\"fastquery.json-> queries配置错误,\\\"%s\\\"的开头不应该有\\\"/\\\"\", str));\n }\n if (str.charAt(str.length() - 1) != '/') {\n throw new RepositoryException(String.format(\"fastquery.json-> queries配置错误,\\\"%s\\\"的末尾必须加\\\"/\\\"\", str));\n }\n }\n if (jo.containsKey(DEBUG)) {\n Object debug = jo.get(DEBUG);\n if (!(debug instanceof Boolean)) {\n throw new RepositoryException(\"fastquery.json -> debug 它的值只能是true或false,也可以不用配置,要配,请配置正确\");\n }\n }\n String slowQueryTime = jo.getString(\"slowQueryTime\");\n if (slowQueryTime != null && !Pattern.matches(\"\\\\d+\", slowQueryTime)) {\n throw new RepositoryException(\"fastquery.json -> slowQueryTime 它的值只能是数字\");\n }\n }\n}\n"} {"task_id": "Java_2750", "language": "Java", "task_type": "method_body", "source_file": "java/github/xixifeng/fastquery/src/main/java/org/fastquery/util/FastQueryJSONObject.java", "mask_start_position": 627, "mask_end_position": 774, "canonical_solution": "{\n if (jo == null) {\n jo = o;\n } else {\n throw new RepositoryException(\"fastquery.json不能重复装载\");\n }\n }", "pre_mask_code": "/*\n *\n *\n * For more information, please see http://example.com.\n *\n */\npackage org.fastquery.util;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Pattern;\nimport org.apache.commons.lang3.StringUtils;\nimport org.fastquery.core.RepositoryException;\nimport com.alibaba.fastjson.JSONArray;\nimport com.alibaba.fastjson.JSONObject;\n\n/**\n * @author xixifeng (example@nnthink.com)\n */\npublic class FastQueryJSONObject {\n\n private static final String DEBUG = \"debug\";\n\n private static JSONObject jo;\n\n private FastQueryJSONObject() {\n }\n\n static synchronized void setJsonObject(JSONObject o) ", "post_mask_code": "\n\n public static String getBasedir() {\n return jo.getString(\"basedir\");\n }\n\n public static boolean getDebug() {\n return (boolean) jo.getOrDefault(DEBUG, false);\n }\n\n public static List getQueries() {\n List strs = new ArrayList<>();\n JSONArray jsonArray = jo.getJSONArray(\"queries\");\n if (jsonArray == null) {\n return strs;\n }\n jsonArray.forEach(s -> strs.add(s.toString()));\n return strs;\n }\n\n public static int getSlowQueryTime() {\n return jo.getIntValue(\"slowQueryTime\");\n }\n\n static void check() {\n List strs = getQueries();\n for (String str : strs) {\n if (StringUtils.EMPTY.equals(str)) {\n continue;\n }\n if (str.charAt(0) == '/') {\n throw new RepositoryException(String.format(\"fastquery.json-> queries配置错误,\\\"%s\\\"的开头不应该有\\\"/\\\"\", str));\n }\n if (str.charAt(str.length() - 1) != '/') {\n throw new RepositoryException(String.format(\"fastquery.json-> queries配置错误,\\\"%s\\\"的末尾必须加\\\"/\\\"\", str));\n }\n }\n if (jo.containsKey(DEBUG)) {\n Object debug = jo.get(DEBUG);\n if (!(debug instanceof Boolean)) {\n throw new RepositoryException(\"fastquery.json -> debug 它的值只能是true或false,也可以不用配置,要配,请配置正确\");\n }\n }\n String slowQueryTime = jo.getString(\"slowQueryTime\");\n if (slowQueryTime != null && !Pattern.matches(\"\\\\d+\", slowQueryTime)) {\n throw new RepositoryException(\"fastquery.json -> slowQueryTime 它的值只能是数字\");\n }\n }\n}\n"} {"task_id": "Java_2751", "language": "Java", "task_type": "single_line", "source_file": "java/github/xixifeng/fastquery/src/main/java/org/fastquery/util/FastQueryJSONObject.java", "mask_start_position": 836, "mask_end_position": 855, "canonical_solution": "tString(\"basedir\");", "pre_mask_code": "/*\n *\n *\n * For more information, please see http://example.com.\n *\n */\npackage org.fastquery.util;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Pattern;\nimport org.apache.commons.lang3.StringUtils;\nimport org.fastquery.core.RepositoryException;\nimport com.alibaba.fastjson.JSONArray;\nimport com.alibaba.fastjson.JSONObject;\n\n/**\n * @author xixifeng (example@nnthink.com)\n */\npublic class FastQueryJSONObject {\n\n private static final String DEBUG = \"debug\";\n\n private static JSONObject jo;\n\n private FastQueryJSONObject() {\n }\n\n static synchronized void setJsonObject(JSONObject o) {\n if (jo == null) {\n jo = o;\n } else {\n throw new RepositoryException(\"fastquery.json不能重复装载\");\n }\n }\n\n public static String getBasedir() {\n return jo.ge", "post_mask_code": "\n }\n\n public static boolean getDebug() {\n return (boolean) jo.getOrDefault(DEBUG, false);\n }\n\n public static List getQueries() {\n List strs = new ArrayList<>();\n JSONArray jsonArray = jo.getJSONArray(\"queries\");\n if (jsonArray == null) {\n return strs;\n }\n jsonArray.forEach(s -> strs.add(s.toString()));\n return strs;\n }\n\n public static int getSlowQueryTime() {\n return jo.getIntValue(\"slowQueryTime\");\n }\n\n static void check() {\n List strs = getQueries();\n for (String str : strs) {\n if (StringUtils.EMPTY.equals(str)) {\n continue;\n }\n if (str.charAt(0) == '/') {\n throw new RepositoryException(String.format(\"fastquery.json-> queries配置错误,\\\"%s\\\"的开头不应该有\\\"/\\\"\", str));\n }\n if (str.charAt(str.length() - 1) != '/') {\n throw new RepositoryException(String.format(\"fastquery.json-> queries配置错误,\\\"%s\\\"的末尾必须加\\\"/\\\"\", str));\n }\n }\n if (jo.containsKey(DEBUG)) {\n Object debug = jo.get(DEBUG);\n if (!(debug instanceof Boolean)) {\n throw new RepositoryException(\"fastquery.json -> debug 它的值只能是true或false,也可以不用配置,要配,请配置正确\");\n }\n }\n String slowQueryTime = jo.getString(\"slowQueryTime\");\n if (slowQueryTime != null && !Pattern.matches(\"\\\\d+\", slowQueryTime)) {\n throw new RepositoryException(\"fastquery.json -> slowQueryTime 它的值只能是数字\");\n }\n }\n}\n"} {"task_id": "Java_2752", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jindrapetrik/jpexs-decompiler/libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/types/SHAPE.java", "mask_start_position": 2387, "mask_end_position": 2426, "canonical_solution": "public SHAPE resize(double multiplier) ", "pre_mask_code": "package com.jpexs.decompiler.flash.types;\n\nimport com.jpexs.decompiler.flash.SWF;\nimport com.jpexs.decompiler.flash.exporters.shape.PathExporter;\nimport com.jpexs.decompiler.flash.tags.base.NeedsCharacters;\nimport com.jpexs.decompiler.flash.types.annotations.SWFArray;\nimport com.jpexs.decompiler.flash.types.annotations.SWFType;\nimport com.jpexs.decompiler.flash.types.shaperecords.EndShapeRecord;\nimport com.jpexs.decompiler.flash.types.shaperecords.SHAPERECORD;\nimport java.awt.Shape;\nimport java.awt.geom.Area;\nimport java.awt.geom.GeneralPath;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * @author JPEXS\n */\npublic class SHAPE implements NeedsCharacters, Serializable {\n\n @SWFType(value = BasicType.UB, count = 4)\n public int numFillBits;\n\n @SWFType(value = BasicType.UB, count = 4)\n public int numLineBits;\n\n @SWFArray(value = \"record\")\n public List shapeRecords;\n\n private Shape cachedOutline;\n\n @Override\n public void getNeededCharacters(Set needed) {\n for (SHAPERECORD r : shapeRecords) {\n r.getNeededCharacters(needed);\n }\n }\n\n @Override\n public boolean replaceCharacter(int oldCharacterId, int newCharacterId) {\n boolean modified = false;\n for (SHAPERECORD r : shapeRecords) {\n modified |= r.replaceCharacter(oldCharacterId, newCharacterId);\n }\n return modified;\n }\n\n @Override\n public boolean removeCharacter(int characterId) {\n boolean modified = false;\n for (SHAPERECORD r : shapeRecords) {\n modified |= r.removeCharacter(characterId);\n }\n return modified;\n }\n\n public RECT getBounds() {\n return SHAPERECORD.getBounds(shapeRecords);\n }\n\n public Shape getOutline(SWF swf, boolean stroked) {\n if (cachedOutline != null) {\n return cachedOutline;\n }\n List strokes = new ArrayList<>();\n List paths = PathExporter.export(swf, this, strokes);\n Area area = new Area();\n for (GeneralPath path : paths) {\n area.add(new Area(path));\n }\n if (stroked) {\n for (GeneralPath path : strokes) {\n area.add(new Area(path));\n }\n }\n cachedOutline = area;\n return area;\n }\n\n ", "post_mask_code": "{\n return resize(multiplier, multiplier);\n }\n\n public SHAPE resize(double multiplierX, double multiplierY) {\n SHAPE ret = new SHAPE();\n ret.numFillBits = numFillBits;\n ret.numLineBits = numLineBits;\n List recs = new ArrayList<>();\n for (SHAPERECORD r : shapeRecords) {\n SHAPERECORD c = r.resize(multiplierX, multiplierY);\n recs.add(c);\n }\n ret.shapeRecords = recs;\n return ret;\n }\n\n public static SHAPE createEmpty(int shapeNum) {\n SHAPE ret = new SHAPE();\n ret.shapeRecords = new ArrayList<>();\n ret.shapeRecords.add(new EndShapeRecord());\n return ret;\n }\n}\n"} {"task_id": "Java_2753", "language": "Java", "task_type": "method_body", "source_file": "java/github/jindrapetrik/jpexs-decompiler/libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/types/SHAPE.java", "mask_start_position": 1740, "mask_end_position": 1799, "canonical_solution": "{\n return SHAPERECORD.getBounds(shapeRecords);\n }", "pre_mask_code": "package com.jpexs.decompiler.flash.types;\n\nimport com.jpexs.decompiler.flash.SWF;\nimport com.jpexs.decompiler.flash.exporters.shape.PathExporter;\nimport com.jpexs.decompiler.flash.tags.base.NeedsCharacters;\nimport com.jpexs.decompiler.flash.types.annotations.SWFArray;\nimport com.jpexs.decompiler.flash.types.annotations.SWFType;\nimport com.jpexs.decompiler.flash.types.shaperecords.EndShapeRecord;\nimport com.jpexs.decompiler.flash.types.shaperecords.SHAPERECORD;\nimport java.awt.Shape;\nimport java.awt.geom.Area;\nimport java.awt.geom.GeneralPath;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * @author JPEXS\n */\npublic class SHAPE implements NeedsCharacters, Serializable {\n\n @SWFType(value = BasicType.UB, count = 4)\n public int numFillBits;\n\n @SWFType(value = BasicType.UB, count = 4)\n public int numLineBits;\n\n @SWFArray(value = \"record\")\n public List shapeRecords;\n\n private Shape cachedOutline;\n\n @Override\n public void getNeededCharacters(Set needed) {\n for (SHAPERECORD r : shapeRecords) {\n r.getNeededCharacters(needed);\n }\n }\n\n @Override\n public boolean replaceCharacter(int oldCharacterId, int newCharacterId) {\n boolean modified = false;\n for (SHAPERECORD r : shapeRecords) {\n modified |= r.replaceCharacter(oldCharacterId, newCharacterId);\n }\n return modified;\n }\n\n @Override\n public boolean removeCharacter(int characterId) {\n boolean modified = false;\n for (SHAPERECORD r : shapeRecords) {\n modified |= r.removeCharacter(characterId);\n }\n return modified;\n }\n\n public RECT getBounds() ", "post_mask_code": "\n\n public Shape getOutline(SWF swf, boolean stroked) {\n if (cachedOutline != null) {\n return cachedOutline;\n }\n List strokes = new ArrayList<>();\n List paths = PathExporter.export(swf, this, strokes);\n Area area = new Area();\n for (GeneralPath path : paths) {\n area.add(new Area(path));\n }\n if (stroked) {\n for (GeneralPath path : strokes) {\n area.add(new Area(path));\n }\n }\n cachedOutline = area;\n return area;\n }\n\n public SHAPE resize(double multiplier) {\n return resize(multiplier, multiplier);\n }\n\n public SHAPE resize(double multiplierX, double multiplierY) {\n SHAPE ret = new SHAPE();\n ret.numFillBits = numFillBits;\n ret.numLineBits = numLineBits;\n List recs = new ArrayList<>();\n for (SHAPERECORD r : shapeRecords) {\n SHAPERECORD c = r.resize(multiplierX, multiplierY);\n recs.add(c);\n }\n ret.shapeRecords = recs;\n return ret;\n }\n\n public static SHAPE createEmpty(int shapeNum) {\n SHAPE ret = new SHAPE();\n ret.shapeRecords = new ArrayList<>();\n ret.shapeRecords.add(new EndShapeRecord());\n return ret;\n }\n}\n"} {"task_id": "Java_2754", "language": "Java", "task_type": "single_line", "source_file": "java/github/jindrapetrik/jpexs-decompiler/libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/types/SHAPE.java", "mask_start_position": 3110, "mask_end_position": 3117, "canonical_solution": "rn ret;", "pre_mask_code": "package com.jpexs.decompiler.flash.types;\n\nimport com.jpexs.decompiler.flash.SWF;\nimport com.jpexs.decompiler.flash.exporters.shape.PathExporter;\nimport com.jpexs.decompiler.flash.tags.base.NeedsCharacters;\nimport com.jpexs.decompiler.flash.types.annotations.SWFArray;\nimport com.jpexs.decompiler.flash.types.annotations.SWFType;\nimport com.jpexs.decompiler.flash.types.shaperecords.EndShapeRecord;\nimport com.jpexs.decompiler.flash.types.shaperecords.SHAPERECORD;\nimport java.awt.Shape;\nimport java.awt.geom.Area;\nimport java.awt.geom.GeneralPath;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * @author JPEXS\n */\npublic class SHAPE implements NeedsCharacters, Serializable {\n\n @SWFType(value = BasicType.UB, count = 4)\n public int numFillBits;\n\n @SWFType(value = BasicType.UB, count = 4)\n public int numLineBits;\n\n @SWFArray(value = \"record\")\n public List shapeRecords;\n\n private Shape cachedOutline;\n\n @Override\n public void getNeededCharacters(Set needed) {\n for (SHAPERECORD r : shapeRecords) {\n r.getNeededCharacters(needed);\n }\n }\n\n @Override\n public boolean replaceCharacter(int oldCharacterId, int newCharacterId) {\n boolean modified = false;\n for (SHAPERECORD r : shapeRecords) {\n modified |= r.replaceCharacter(oldCharacterId, newCharacterId);\n }\n return modified;\n }\n\n @Override\n public boolean removeCharacter(int characterId) {\n boolean modified = false;\n for (SHAPERECORD r : shapeRecords) {\n modified |= r.removeCharacter(characterId);\n }\n return modified;\n }\n\n public RECT getBounds() {\n return SHAPERECORD.getBounds(shapeRecords);\n }\n\n public Shape getOutline(SWF swf, boolean stroked) {\n if (cachedOutline != null) {\n return cachedOutline;\n }\n List strokes = new ArrayList<>();\n List paths = PathExporter.export(swf, this, strokes);\n Area area = new Area();\n for (GeneralPath path : paths) {\n area.add(new Area(path));\n }\n if (stroked) {\n for (GeneralPath path : strokes) {\n area.add(new Area(path));\n }\n }\n cachedOutline = area;\n return area;\n }\n\n public SHAPE resize(double multiplier) {\n return resize(multiplier, multiplier);\n }\n\n public SHAPE resize(double multiplierX, double multiplierY) {\n SHAPE ret = new SHAPE();\n ret.numFillBits = numFillBits;\n ret.numLineBits = numLineBits;\n List recs = new ArrayList<>();\n for (SHAPERECORD r : shapeRecords) {\n SHAPERECORD c = r.resize(multiplierX, multiplierY);\n recs.add(c);\n }\n ret.shapeRecords = recs;\n return ret;\n }\n\n public static SHAPE createEmpty(int shapeNum) {\n SHAPE ret = new SHAPE();\n ret.shapeRecords = new ArrayList<>();\n ret.shapeRecords.add(new EndShapeRecord());\n retu", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2755", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Engidea/FreeRoutingNew/src/interactive/state/StateMenu.java", "mask_start_position": 1598, "mask_end_position": 1657, "canonical_solution": "public StateInteractive swap_pin(PlaPointFloat p_location) ", "pre_mask_code": "package interactive.state;\n\nimport freert.planar.PlaPointFloat;\nimport interactive.Actlog;\nimport interactive.IteraBoard;\nimport interactive.LogfileScope;\nimport java.util.Collection;\nimport java.util.Set;\nimport board.BrdLayerStructure;\nimport board.items.BrdItem;\nimport board.varie.ItemSelectionChoice;\nimport board.varie.ItemSelectionFilter;\n\n/**\n * Common base class for the main menus, which can be selected in the tool bar.\n *\n * @author Alfons Wirtz\n */\npublic class StateMenu extends StateInteractive {\n\n public StateMenu(IteraBoard p_board_handle, Actlog p_logfile) {\n super(null, p_board_handle, p_logfile);\n this.return_state = this;\n }\n\n public javax.swing.JPopupMenu get_popup_menu() {\n return i_brd.get_panel().popup_menu_main;\n }\n\n /**\n * Selects items at p_location. Returns a new instance of SelectedItemState with the selected items, if something was selected.\n */\n public StateInteractive select_items(PlaPointFloat p_location) {\n i_brd.display_layer_messsage();\n Set picked_items = i_brd.pick_items(p_location);\n boolean something_found = (picked_items.size() > 0);\n StateInteractive result;\n if (something_found) {\n result = StateSelectedItem.get_instance(picked_items, this, i_brd, this.actlog);\n i_brd.screen_messages.set_status_message(resources.getString(\"in_select_mode\"));\n actlog_start_scope(LogfileScope.START_SELECT, p_location);\n } else {\n result = this;\n }\n i_brd.repaint();\n return result;\n }\n\n ", "post_mask_code": "{\n ItemSelectionFilter selection_filter = new ItemSelectionFilter(ItemSelectionChoice.PINS);\n Collection picked_items = i_brd.pick_items(p_location, selection_filter);\n StateInteractive result = this;\n if (picked_items.size() > 0) {\n BrdItem first_item = picked_items.iterator().next();\n if (!(first_item instanceof board.items.BrdAbitPin)) {\n System.out.println(\"MenuState.swap_pin: Pin expected\");\n return this;\n }\n board.items.BrdAbitPin selected_pin = (board.items.BrdAbitPin) first_item;\n result = StatePinSwap.get_instance(selected_pin, this, i_brd, this.actlog);\n } else {\n i_brd.screen_messages.set_status_message(resources.getString(\"no_pin_selected\"));\n }\n i_brd.repaint();\n return result;\n }\n\n private void change_layer_next(int delta) {\n if (delta == 0)\n return;\n // increase the current layer to the next signal layer\n BrdLayerStructure layer_structure = r_brd.layer_structure;\n int current_layer_no = i_brd.itera_settings.layer_no;\n int layer_count = layer_structure.size();\n for (int index = 0; index < layer_count; index++) {\n current_layer_no += delta;\n // if we are going up and we went above the maximum, get back to a safe value\n if (delta > 0 && current_layer_no >= layer_count)\n current_layer_no = 0;\n // if we are going down and we went below, go back to the top\n if (delta < 0 && current_layer_no < 0)\n current_layer_no = layer_count - 1;\n // if the layer is good, then we are done\n if (layer_structure.is_signal(current_layer_no))\n break;\n }\n i_brd.set_current_layer(current_layer_no);\n }\n\n /**\n * Action to be taken when a key shortcut is pressed.\n */\n public StateInteractive key_typed(char p_key_char) {\n StateInteractive curr_return_state = this;\n if (p_key_char == 'b') {\n i_brd.redo();\n } else if (p_key_char == 'd') {\n return new StateMenuDrag(i_brd, actlog);\n } else if (p_key_char == 'e') {\n // It seems to me that this is quite useful to understand what is happening... damiano\n StateExpandTest expand = new StateExpandTest(this, i_brd);\n expand.expand_test_init(i_brd.get_current_mouse_position());\n return expand;\n } else if (p_key_char == 'g') {\n i_brd.toggle_ratsnest();\n } else if (p_key_char == 'i') {\n curr_return_state = select_items(i_brd.get_current_mouse_position());\n } else if (p_key_char == 'p') {\n i_brd.itera_settings.set_push_enabled(!i_brd.itera_settings.push_enabled);\n i_brd.get_panel().board_frame.refresh_windows();\n } else if (p_key_char == 'r') {\n curr_return_state = new StateMenuRoute(i_brd, actlog);\n } else if (p_key_char == 's') {\n curr_return_state = new StateMenuSelect(i_brd, actlog);\n } else if (p_key_char == 't') {\n curr_return_state = StateRoute.get_instance(i_brd.get_current_mouse_position(), this, i_brd, actlog);\n } else if (p_key_char == 'u') {\n i_brd.undo();\n } else if (p_key_char == 'v') {\n i_brd.toggle_clearance_violations();\n } else if (p_key_char == 'w') {\n curr_return_state = swap_pin(i_brd.get_current_mouse_position());\n } else if (p_key_char == '+') {\n change_layer_next(1);\n } else if (p_key_char == '-') {\n change_layer_next(-1);\n } else {\n curr_return_state = super.key_typed(p_key_char);\n }\n return curr_return_state;\n }\n\n /**\n * Do nothing on complete.\n */\n @Override\n public StateInteractive complete() {\n return this;\n }\n\n /**\n * Do nothing on cancel.\n */\n @Override\n public StateInteractive cancel() {\n return this;\n }\n\n @Override\n public void set_toolbar() {\n i_brd.get_panel().board_frame.set_menu_toolbar();\n }\n}\n"} {"task_id": "Java_2756", "language": "Java", "task_type": "method_body", "source_file": "java/github/Engidea/FreeRoutingNew/src/interactive/state/StateMenu.java", "mask_start_position": 5782, "mask_end_position": 5847, "canonical_solution": "{\n i_brd.get_panel().board_frame.set_menu_toolbar();\n }", "pre_mask_code": "package interactive.state;\n\nimport freert.planar.PlaPointFloat;\nimport interactive.Actlog;\nimport interactive.IteraBoard;\nimport interactive.LogfileScope;\nimport java.util.Collection;\nimport java.util.Set;\nimport board.BrdLayerStructure;\nimport board.items.BrdItem;\nimport board.varie.ItemSelectionChoice;\nimport board.varie.ItemSelectionFilter;\n\n/**\n * Common base class for the main menus, which can be selected in the tool bar.\n *\n * @author Alfons Wirtz\n */\npublic class StateMenu extends StateInteractive {\n\n public StateMenu(IteraBoard p_board_handle, Actlog p_logfile) {\n super(null, p_board_handle, p_logfile);\n this.return_state = this;\n }\n\n public javax.swing.JPopupMenu get_popup_menu() {\n return i_brd.get_panel().popup_menu_main;\n }\n\n /**\n * Selects items at p_location. Returns a new instance of SelectedItemState with the selected items, if something was selected.\n */\n public StateInteractive select_items(PlaPointFloat p_location) {\n i_brd.display_layer_messsage();\n Set picked_items = i_brd.pick_items(p_location);\n boolean something_found = (picked_items.size() > 0);\n StateInteractive result;\n if (something_found) {\n result = StateSelectedItem.get_instance(picked_items, this, i_brd, this.actlog);\n i_brd.screen_messages.set_status_message(resources.getString(\"in_select_mode\"));\n actlog_start_scope(LogfileScope.START_SELECT, p_location);\n } else {\n result = this;\n }\n i_brd.repaint();\n return result;\n }\n\n public StateInteractive swap_pin(PlaPointFloat p_location) {\n ItemSelectionFilter selection_filter = new ItemSelectionFilter(ItemSelectionChoice.PINS);\n Collection picked_items = i_brd.pick_items(p_location, selection_filter);\n StateInteractive result = this;\n if (picked_items.size() > 0) {\n BrdItem first_item = picked_items.iterator().next();\n if (!(first_item instanceof board.items.BrdAbitPin)) {\n System.out.println(\"MenuState.swap_pin: Pin expected\");\n return this;\n }\n board.items.BrdAbitPin selected_pin = (board.items.BrdAbitPin) first_item;\n result = StatePinSwap.get_instance(selected_pin, this, i_brd, this.actlog);\n } else {\n i_brd.screen_messages.set_status_message(resources.getString(\"no_pin_selected\"));\n }\n i_brd.repaint();\n return result;\n }\n\n private void change_layer_next(int delta) {\n if (delta == 0)\n return;\n // increase the current layer to the next signal layer\n BrdLayerStructure layer_structure = r_brd.layer_structure;\n int current_layer_no = i_brd.itera_settings.layer_no;\n int layer_count = layer_structure.size();\n for (int index = 0; index < layer_count; index++) {\n current_layer_no += delta;\n // if we are going up and we went above the maximum, get back to a safe value\n if (delta > 0 && current_layer_no >= layer_count)\n current_layer_no = 0;\n // if we are going down and we went below, go back to the top\n if (delta < 0 && current_layer_no < 0)\n current_layer_no = layer_count - 1;\n // if the layer is good, then we are done\n if (layer_structure.is_signal(current_layer_no))\n break;\n }\n i_brd.set_current_layer(current_layer_no);\n }\n\n /**\n * Action to be taken when a key shortcut is pressed.\n */\n public StateInteractive key_typed(char p_key_char) {\n StateInteractive curr_return_state = this;\n if (p_key_char == 'b') {\n i_brd.redo();\n } else if (p_key_char == 'd') {\n return new StateMenuDrag(i_brd, actlog);\n } else if (p_key_char == 'e') {\n // It seems to me that this is quite useful to understand what is happening... damiano\n StateExpandTest expand = new StateExpandTest(this, i_brd);\n expand.expand_test_init(i_brd.get_current_mouse_position());\n return expand;\n } else if (p_key_char == 'g') {\n i_brd.toggle_ratsnest();\n } else if (p_key_char == 'i') {\n curr_return_state = select_items(i_brd.get_current_mouse_position());\n } else if (p_key_char == 'p') {\n i_brd.itera_settings.set_push_enabled(!i_brd.itera_settings.push_enabled);\n i_brd.get_panel().board_frame.refresh_windows();\n } else if (p_key_char == 'r') {\n curr_return_state = new StateMenuRoute(i_brd, actlog);\n } else if (p_key_char == 's') {\n curr_return_state = new StateMenuSelect(i_brd, actlog);\n } else if (p_key_char == 't') {\n curr_return_state = StateRoute.get_instance(i_brd.get_current_mouse_position(), this, i_brd, actlog);\n } else if (p_key_char == 'u') {\n i_brd.undo();\n } else if (p_key_char == 'v') {\n i_brd.toggle_clearance_violations();\n } else if (p_key_char == 'w') {\n curr_return_state = swap_pin(i_brd.get_current_mouse_position());\n } else if (p_key_char == '+') {\n change_layer_next(1);\n } else if (p_key_char == '-') {\n change_layer_next(-1);\n } else {\n curr_return_state = super.key_typed(p_key_char);\n }\n return curr_return_state;\n }\n\n /**\n * Do nothing on complete.\n */\n @Override\n public StateInteractive complete() {\n return this;\n }\n\n /**\n * Do nothing on cancel.\n */\n @Override\n public StateInteractive cancel() {\n return this;\n }\n\n @Override\n public void set_toolbar() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2757", "language": "Java", "task_type": "single_line", "source_file": "java/github/Engidea/FreeRoutingNew/src/interactive/state/StateMenu.java", "mask_start_position": 1776, "mask_end_position": 1847, "canonical_solution": "BrdItem> picked_items = i_brd.pick_items(p_location, selection_filter);", "pre_mask_code": "package interactive.state;\n\nimport freert.planar.PlaPointFloat;\nimport interactive.Actlog;\nimport interactive.IteraBoard;\nimport interactive.LogfileScope;\nimport java.util.Collection;\nimport java.util.Set;\nimport board.BrdLayerStructure;\nimport board.items.BrdItem;\nimport board.varie.ItemSelectionChoice;\nimport board.varie.ItemSelectionFilter;\n\n/**\n * Common base class for the main menus, which can be selected in the tool bar.\n *\n * @author Alfons Wirtz\n */\npublic class StateMenu extends StateInteractive {\n\n public StateMenu(IteraBoard p_board_handle, Actlog p_logfile) {\n super(null, p_board_handle, p_logfile);\n this.return_state = this;\n }\n\n public javax.swing.JPopupMenu get_popup_menu() {\n return i_brd.get_panel().popup_menu_main;\n }\n\n /**\n * Selects items at p_location. Returns a new instance of SelectedItemState with the selected items, if something was selected.\n */\n public StateInteractive select_items(PlaPointFloat p_location) {\n i_brd.display_layer_messsage();\n Set picked_items = i_brd.pick_items(p_location);\n boolean something_found = (picked_items.size() > 0);\n StateInteractive result;\n if (something_found) {\n result = StateSelectedItem.get_instance(picked_items, this, i_brd, this.actlog);\n i_brd.screen_messages.set_status_message(resources.getString(\"in_select_mode\"));\n actlog_start_scope(LogfileScope.START_SELECT, p_location);\n } else {\n result = this;\n }\n i_brd.repaint();\n return result;\n }\n\n public StateInteractive swap_pin(PlaPointFloat p_location) {\n ItemSelectionFilter selection_filter = new ItemSelectionFilter(ItemSelectionChoice.PINS);\n Collection<", "post_mask_code": "\n StateInteractive result = this;\n if (picked_items.size() > 0) {\n BrdItem first_item = picked_items.iterator().next();\n if (!(first_item instanceof board.items.BrdAbitPin)) {\n System.out.println(\"MenuState.swap_pin: Pin expected\");\n return this;\n }\n board.items.BrdAbitPin selected_pin = (board.items.BrdAbitPin) first_item;\n result = StatePinSwap.get_instance(selected_pin, this, i_brd, this.actlog);\n } else {\n i_brd.screen_messages.set_status_message(resources.getString(\"no_pin_selected\"));\n }\n i_brd.repaint();\n return result;\n }\n\n private void change_layer_next(int delta) {\n if (delta == 0)\n return;\n // increase the current layer to the next signal layer\n BrdLayerStructure layer_structure = r_brd.layer_structure;\n int current_layer_no = i_brd.itera_settings.layer_no;\n int layer_count = layer_structure.size();\n for (int index = 0; index < layer_count; index++) {\n current_layer_no += delta;\n // if we are going up and we went above the maximum, get back to a safe value\n if (delta > 0 && current_layer_no >= layer_count)\n current_layer_no = 0;\n // if we are going down and we went below, go back to the top\n if (delta < 0 && current_layer_no < 0)\n current_layer_no = layer_count - 1;\n // if the layer is good, then we are done\n if (layer_structure.is_signal(current_layer_no))\n break;\n }\n i_brd.set_current_layer(current_layer_no);\n }\n\n /**\n * Action to be taken when a key shortcut is pressed.\n */\n public StateInteractive key_typed(char p_key_char) {\n StateInteractive curr_return_state = this;\n if (p_key_char == 'b') {\n i_brd.redo();\n } else if (p_key_char == 'd') {\n return new StateMenuDrag(i_brd, actlog);\n } else if (p_key_char == 'e') {\n // It seems to me that this is quite useful to understand what is happening... damiano\n StateExpandTest expand = new StateExpandTest(this, i_brd);\n expand.expand_test_init(i_brd.get_current_mouse_position());\n return expand;\n } else if (p_key_char == 'g') {\n i_brd.toggle_ratsnest();\n } else if (p_key_char == 'i') {\n curr_return_state = select_items(i_brd.get_current_mouse_position());\n } else if (p_key_char == 'p') {\n i_brd.itera_settings.set_push_enabled(!i_brd.itera_settings.push_enabled);\n i_brd.get_panel().board_frame.refresh_windows();\n } else if (p_key_char == 'r') {\n curr_return_state = new StateMenuRoute(i_brd, actlog);\n } else if (p_key_char == 's') {\n curr_return_state = new StateMenuSelect(i_brd, actlog);\n } else if (p_key_char == 't') {\n curr_return_state = StateRoute.get_instance(i_brd.get_current_mouse_position(), this, i_brd, actlog);\n } else if (p_key_char == 'u') {\n i_brd.undo();\n } else if (p_key_char == 'v') {\n i_brd.toggle_clearance_violations();\n } else if (p_key_char == 'w') {\n curr_return_state = swap_pin(i_brd.get_current_mouse_position());\n } else if (p_key_char == '+') {\n change_layer_next(1);\n } else if (p_key_char == '-') {\n change_layer_next(-1);\n } else {\n curr_return_state = super.key_typed(p_key_char);\n }\n return curr_return_state;\n }\n\n /**\n * Do nothing on complete.\n */\n @Override\n public StateInteractive complete() {\n return this;\n }\n\n /**\n * Do nothing on cancel.\n */\n @Override\n public StateInteractive cancel() {\n return this;\n }\n\n @Override\n public void set_toolbar() {\n i_brd.get_panel().board_frame.set_menu_toolbar();\n }\n}\n"} {"task_id": "Java_2758", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Engidea/FreeRoutingNew/src/interactive/state/StateMenu.java", "mask_start_position": 5533, "mask_end_position": 5610, "canonical_solution": "@Override\n public StateInteractive complete() {\n return this;\n }", "pre_mask_code": "package interactive.state;\n\nimport freert.planar.PlaPointFloat;\nimport interactive.Actlog;\nimport interactive.IteraBoard;\nimport interactive.LogfileScope;\nimport java.util.Collection;\nimport java.util.Set;\nimport board.BrdLayerStructure;\nimport board.items.BrdItem;\nimport board.varie.ItemSelectionChoice;\nimport board.varie.ItemSelectionFilter;\n\n/**\n * Common base class for the main menus, which can be selected in the tool bar.\n *\n * @author Alfons Wirtz\n */\npublic class StateMenu extends StateInteractive {\n\n public StateMenu(IteraBoard p_board_handle, Actlog p_logfile) {\n super(null, p_board_handle, p_logfile);\n this.return_state = this;\n }\n\n public javax.swing.JPopupMenu get_popup_menu() {\n return i_brd.get_panel().popup_menu_main;\n }\n\n /**\n * Selects items at p_location. Returns a new instance of SelectedItemState with the selected items, if something was selected.\n */\n public StateInteractive select_items(PlaPointFloat p_location) {\n i_brd.display_layer_messsage();\n Set picked_items = i_brd.pick_items(p_location);\n boolean something_found = (picked_items.size() > 0);\n StateInteractive result;\n if (something_found) {\n result = StateSelectedItem.get_instance(picked_items, this, i_brd, this.actlog);\n i_brd.screen_messages.set_status_message(resources.getString(\"in_select_mode\"));\n actlog_start_scope(LogfileScope.START_SELECT, p_location);\n } else {\n result = this;\n }\n i_brd.repaint();\n return result;\n }\n\n public StateInteractive swap_pin(PlaPointFloat p_location) {\n ItemSelectionFilter selection_filter = new ItemSelectionFilter(ItemSelectionChoice.PINS);\n Collection picked_items = i_brd.pick_items(p_location, selection_filter);\n StateInteractive result = this;\n if (picked_items.size() > 0) {\n BrdItem first_item = picked_items.iterator().next();\n if (!(first_item instanceof board.items.BrdAbitPin)) {\n System.out.println(\"MenuState.swap_pin: Pin expected\");\n return this;\n }\n board.items.BrdAbitPin selected_pin = (board.items.BrdAbitPin) first_item;\n result = StatePinSwap.get_instance(selected_pin, this, i_brd, this.actlog);\n } else {\n i_brd.screen_messages.set_status_message(resources.getString(\"no_pin_selected\"));\n }\n i_brd.repaint();\n return result;\n }\n\n private void change_layer_next(int delta) {\n if (delta == 0)\n return;\n // increase the current layer to the next signal layer\n BrdLayerStructure layer_structure = r_brd.layer_structure;\n int current_layer_no = i_brd.itera_settings.layer_no;\n int layer_count = layer_structure.size();\n for (int index = 0; index < layer_count; index++) {\n current_layer_no += delta;\n // if we are going up and we went above the maximum, get back to a safe value\n if (delta > 0 && current_layer_no >= layer_count)\n current_layer_no = 0;\n // if we are going down and we went below, go back to the top\n if (delta < 0 && current_layer_no < 0)\n current_layer_no = layer_count - 1;\n // if the layer is good, then we are done\n if (layer_structure.is_signal(current_layer_no))\n break;\n }\n i_brd.set_current_layer(current_layer_no);\n }\n\n /**\n * Action to be taken when a key shortcut is pressed.\n */\n public StateInteractive key_typed(char p_key_char) {\n StateInteractive curr_return_state = this;\n if (p_key_char == 'b') {\n i_brd.redo();\n } else if (p_key_char == 'd') {\n return new StateMenuDrag(i_brd, actlog);\n } else if (p_key_char == 'e') {\n // It seems to me that this is quite useful to understand what is happening... damiano\n StateExpandTest expand = new StateExpandTest(this, i_brd);\n expand.expand_test_init(i_brd.get_current_mouse_position());\n return expand;\n } else if (p_key_char == 'g') {\n i_brd.toggle_ratsnest();\n } else if (p_key_char == 'i') {\n curr_return_state = select_items(i_brd.get_current_mouse_position());\n } else if (p_key_char == 'p') {\n i_brd.itera_settings.set_push_enabled(!i_brd.itera_settings.push_enabled);\n i_brd.get_panel().board_frame.refresh_windows();\n } else if (p_key_char == 'r') {\n curr_return_state = new StateMenuRoute(i_brd, actlog);\n } else if (p_key_char == 's') {\n curr_return_state = new StateMenuSelect(i_brd, actlog);\n } else if (p_key_char == 't') {\n curr_return_state = StateRoute.get_instance(i_brd.get_current_mouse_position(), this, i_brd, actlog);\n } else if (p_key_char == 'u') {\n i_brd.undo();\n } else if (p_key_char == 'v') {\n i_brd.toggle_clearance_violations();\n } else if (p_key_char == 'w') {\n curr_return_state = swap_pin(i_brd.get_current_mouse_position());\n } else if (p_key_char == '+') {\n change_layer_next(1);\n } else if (p_key_char == '-') {\n change_layer_next(-1);\n } else {\n curr_return_state = super.key_typed(p_key_char);\n }\n return curr_return_state;\n }\n\n /**\n * Do nothing on complete.\n */\n ", "post_mask_code": "\n\n /**\n * Do nothing on cancel.\n */\n @Override\n public StateInteractive cancel() {\n return this;\n }\n\n @Override\n public void set_toolbar() {\n i_brd.get_panel().board_frame.set_menu_toolbar();\n }\n}\n"} {"task_id": "Java_2759", "language": "Java", "task_type": "method_signature", "source_file": "java/github/mimilewis/MapleStory143/src/main/java/tools/data/output/BAOSByteOutputStream.java", "mask_start_position": 747, "mask_end_position": 791, "canonical_solution": "@Override\n public void writeByte(byte b) ", "pre_mask_code": "package tools.data.output;\n\nimport java.io.ByteArrayOutputStream;\n\n/**\n * Uses a byte array to output a stream of bytes.\n *\n * @author Frz\n * @version 1.0\n * @since Revision 352\n */\npublic class BAOSByteOutputStream implements ByteOutputStream {\n\n private final ByteArrayOutputStream baos;\n\n /**\n * Class constructor - Wraps the stream around a Java BAOS.\n *\n * @param baos The ByteArrayOutputStream to wrap this around.\n */\n public BAOSByteOutputStream(ByteArrayOutputStream baos) {\n super();\n this.baos = baos;\n }\n\n /**\n * Writes a byte to the stream.\n *\n * @param b The byte to write to the stream.\n * @see tools.data.output.ByteOutputStream#writeByte(byte)\n */\n ", "post_mask_code": "{\n baos.write(b);\n }\n}\n"} {"task_id": "Java_2760", "language": "Java", "task_type": "method_body", "source_file": "java/github/mimilewis/MapleStory143/src/main/java/tools/data/output/BAOSByteOutputStream.java", "mask_start_position": 791, "mask_end_position": 821, "canonical_solution": "{\n baos.write(b);\n }", "pre_mask_code": "package tools.data.output;\n\nimport java.io.ByteArrayOutputStream;\n\n/**\n * Uses a byte array to output a stream of bytes.\n *\n * @author Frz\n * @version 1.0\n * @since Revision 352\n */\npublic class BAOSByteOutputStream implements ByteOutputStream {\n\n private final ByteArrayOutputStream baos;\n\n /**\n * Class constructor - Wraps the stream around a Java BAOS.\n *\n * @param baos The ByteArrayOutputStream to wrap this around.\n */\n public BAOSByteOutputStream(ByteArrayOutputStream baos) {\n super();\n this.baos = baos;\n }\n\n /**\n * Writes a byte to the stream.\n *\n * @param b The byte to write to the stream.\n * @see tools.data.output.ByteOutputStream#writeByte(byte)\n */\n @Override\n public void writeByte(byte b) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2761", "language": "Java", "task_type": "single_line", "source_file": "java/github/mimilewis/MapleStory143/src/main/java/tools/data/output/BAOSByteOutputStream.java", "mask_start_position": 802, "mask_end_position": 815, "canonical_solution": "aos.write(b);", "pre_mask_code": "package tools.data.output;\n\nimport java.io.ByteArrayOutputStream;\n\n/**\n * Uses a byte array to output a stream of bytes.\n *\n * @author Frz\n * @version 1.0\n * @since Revision 352\n */\npublic class BAOSByteOutputStream implements ByteOutputStream {\n\n private final ByteArrayOutputStream baos;\n\n /**\n * Class constructor - Wraps the stream around a Java BAOS.\n *\n * @param baos The ByteArrayOutputStream to wrap this around.\n */\n public BAOSByteOutputStream(ByteArrayOutputStream baos) {\n super();\n this.baos = baos;\n }\n\n /**\n * Writes a byte to the stream.\n *\n * @param b The byte to write to the stream.\n * @see tools.data.output.ByteOutputStream#writeByte(byte)\n */\n @Override\n public void writeByte(byte b) {\n b", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2762", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/mimilewis/MapleStory143/src/main/java/tools/data/output/BAOSByteOutputStream.java", "mask_start_position": 747, "mask_end_position": 821, "canonical_solution": "@Override\n public void writeByte(byte b) {\n baos.write(b);\n }", "pre_mask_code": "package tools.data.output;\n\nimport java.io.ByteArrayOutputStream;\n\n/**\n * Uses a byte array to output a stream of bytes.\n *\n * @author Frz\n * @version 1.0\n * @since Revision 352\n */\npublic class BAOSByteOutputStream implements ByteOutputStream {\n\n private final ByteArrayOutputStream baos;\n\n /**\n * Class constructor - Wraps the stream around a Java BAOS.\n *\n * @param baos The ByteArrayOutputStream to wrap this around.\n */\n public BAOSByteOutputStream(ByteArrayOutputStream baos) {\n super();\n this.baos = baos;\n }\n\n /**\n * Writes a byte to the stream.\n *\n * @param b The byte to write to the stream.\n * @see tools.data.output.ByteOutputStream#writeByte(byte)\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2763", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Azure/azure-sdk-for-java/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/DeploymentSlot.java", "mask_start_position": 2158, "mask_end_position": 2203, "canonical_solution": "void warDeploy(File warFile, String appName);", "pre_mask_code": "package com.azure.resourcemanager.appservice.models;\n\nimport com.azure.core.annotation.Fluent;\nimport com.azure.resourcemanager.appservice.AppServiceManager;\nimport com.azure.resourcemanager.appservice.fluent.models.SiteInner;\nimport com.azure.resourcemanager.resources.fluentcore.arm.models.HasParent;\nimport com.azure.resourcemanager.resources.fluentcore.arm.models.IndependentChildResource;\nimport com.azure.resourcemanager.resources.fluentcore.model.Creatable;\nimport com.azure.resourcemanager.resources.fluentcore.model.Updatable;\nimport java.io.File;\nimport java.io.InputStream;\nimport reactor.core.publisher.Mono;\n\n/**\n * An immutable client-side representation of an Azure Web App deployment slot.\n */\n@Fluent\npublic interface DeploymentSlot extends IndependentChildResource, WebDeploymentSlotBasic, SupportsOneDeploy, DeploymentSlotBase, Updatable>, HasParent {\n\n /**\n * Deploys a WAR file onto the Azure specialized Tomcat on this web app.\n *\n * @param warFile the WAR file to upload\n */\n void warDeploy(File warFile);\n\n /**\n * Deploys a WAR file onto the Azure specialized Tomcat on this web app.\n *\n * @param warFile the WAR file to upload\n * @return a completable of the operation\n */\n Mono warDeployAsync(File warFile);\n\n /**\n * Deploys a WAR file onto the Azure specialized Tomcat on this web app.\n *\n * @param warFile the WAR file to upload\n * @param length the length of the file\n */\n void warDeploy(InputStream warFile, long length);\n\n /**\n * Deploys a WAR file onto the Azure specialized Tomcat on this web app.\n *\n * @param warFile the WAR file to upload\n * @param length the length of the file\n * @return a completable of the operation\n */\n Mono warDeployAsync(InputStream warFile, long length);\n\n /**\n * Deploys a WAR file onto the Azure specialized Tomcat on this web app.\n *\n * @param warFile the WAR file to upload\n * @param appName the name of the app, default to \"ROOT\" when not provided\n */\n ", "post_mask_code": "\n\n /**\n * Deploys a WAR file onto the Azure specialized Tomcat on this web app.\n *\n * @param warFile the WAR file to upload\n * @param appName the name of the app, default to \"ROOT\" when not provided\n * @return a completable of the operation\n */\n Mono warDeployAsync(File warFile, String appName);\n\n /**\n * Deploys a WAR file onto the Azure specialized Tomcat on this web app.\n *\n * @param warFile the WAR file to upload\n * @param length the length of the file\n * @param appName the name of the app, default to \"ROOT\" when not provided\n */\n void warDeploy(InputStream warFile, long length, String appName);\n\n /**\n * Deploys a WAR file onto the Azure specialized Tomcat on this web app.\n *\n * @param warFile the WAR file to upload\n * @param length the length of the file\n * @param appName the name of the app, default to \"ROOT\" when not provided\n * @return a completable of the operation\n */\n Mono warDeployAsync(InputStream warFile, long length, String appName);\n\n /**\n * ***********************************************************\n * Fluent interfaces to provision a deployment slot\n * ************************************************************\n */\n /**\n * Container interface for all the definitions that need to be implemented.\n */\n interface Definition extends DefinitionStages.Blank, DefinitionStages.WithConfiguration, DefinitionStages.WithCreate {\n }\n\n /**\n * Grouping of all the deployment slot definition stages.\n */\n interface DefinitionStages {\n\n /**\n * The first stage of the deployment slot definition.\n */\n interface Blank extends WithConfiguration {\n }\n\n /**\n * A deployment slot definition allowing the configuration to clone from to be specified.\n */\n interface WithConfiguration {\n\n /**\n * Creates the deployment slot with brand new site configurations.\n *\n * @return the next stage of the definition\n */\n WithCreate withBrandNewConfiguration();\n\n /**\n * Copies the site configurations from the web app the deployment slot belongs to.\n *\n * @return the next stage of the definition\n */\n WithCreate withConfigurationFromParent();\n\n /**\n * Copies the site configurations from a given web app.\n *\n * @param webApp the web app to copy the configurations from\n * @return the next stage of the definition\n */\n WithCreate withConfigurationFromWebApp(WebApp webApp);\n\n /**\n * Copies the site configurations from a given deployment slot.\n *\n * @param deploymentSlot the deployment slot to copy the configurations from\n * @return the next stage of the definition\n */\n WithCreate withConfigurationFromDeploymentSlot(DeploymentSlot deploymentSlot);\n }\n\n /**\n * A site definition with sufficient inputs to create a new web app / deployments slot in the cloud, but\n * exposing additional optional inputs to specify.\n */\n interface WithCreate extends Creatable, WebAppBase.DefinitionStages.WithCreate {\n }\n }\n}\n"} {"task_id": "Java_2764", "language": "Java", "task_type": "method_signature", "source_file": "java/github/knowm/XChange/xchange-examples/src/main/java/org/knowm/xchange/examples/btctrade/trade/TradeHistoryDemo.java", "mask_start_position": 1065, "mask_end_position": 1131, "canonical_solution": "private static void generic(Exchange exchange) throws IOException ", "pre_mask_code": "package org.knowm.xchange.examples.btctrade.trade;\n\nimport java.io.IOException;\nimport org.knowm.xchange.Exchange;\nimport org.knowm.xchange.ExchangeFactory;\nimport org.knowm.xchange.ExchangeSpecification;\nimport org.knowm.xchange.btctrade.BTCTradeExchange;\nimport org.knowm.xchange.btctrade.dto.trade.BTCTradeOrder;\nimport org.knowm.xchange.btctrade.service.BTCTradeTradeServiceRaw;\nimport org.knowm.xchange.dto.marketdata.Trades;\nimport org.knowm.xchange.dto.trade.OpenOrders;\nimport org.knowm.xchange.service.trade.TradeService;\n\npublic class TradeHistoryDemo {\n\n public static void main(String[] args) throws IOException {\n // API key with Read Only Permission or All Permissions.\n String publicKey = args[0];\n String privateKey = args[1];\n ExchangeSpecification spec = new ExchangeSpecification(BTCTradeExchange.class);\n spec.setApiKey(publicKey);\n spec.setSecretKey(privateKey);\n Exchange btcTrade = ExchangeFactory.INSTANCE.createExchange(spec);\n generic(btcTrade);\n raw(btcTrade);\n }\n\n ", "post_mask_code": "{\n TradeService tradeService = exchange.getTradeService();\n OpenOrders openOrders = tradeService.getOpenOrders();\n System.out.println(\"Open orders: \" + openOrders);\n Trades trades = tradeService.getTradeHistory(tradeService.createTradeHistoryParams());\n System.out.println(\"Trades: \" + trades);\n }\n\n private static void raw(Exchange exchange) throws IOException {\n BTCTradeTradeServiceRaw tradeService = (BTCTradeTradeServiceRaw) exchange.getTradeService();\n BTCTradeOrder[] orders = tradeService.getBTCTradeOrders(0, \"open\");\n System.out.println(\"Open orders: \" + orders.length);\n String orderId = orders.length > 0 ? orders[0].getId() : \"1\";\n BTCTradeOrder order = tradeService.getBTCTradeOrder(orderId);\n System.out.println(\"Order status: \" + order.getStatus());\n }\n}\n"} {"task_id": "Java_2765", "language": "Java", "task_type": "method_body", "source_file": "java/github/knowm/XChange/xchange-examples/src/main/java/org/knowm/xchange/examples/btctrade/trade/TradeHistoryDemo.java", "mask_start_position": 1534, "mask_end_position": 1985, "canonical_solution": "{\n BTCTradeTradeServiceRaw tradeService = (BTCTradeTradeServiceRaw) exchange.getTradeService();\n BTCTradeOrder[] orders = tradeService.getBTCTradeOrders(0, \"open\");\n System.out.println(\"Open orders: \" + orders.length);\n String orderId = orders.length > 0 ? orders[0].getId() : \"1\";\n BTCTradeOrder order = tradeService.getBTCTradeOrder(orderId);\n System.out.println(\"Order status: \" + order.getStatus());\n }", "pre_mask_code": "package org.knowm.xchange.examples.btctrade.trade;\n\nimport java.io.IOException;\nimport org.knowm.xchange.Exchange;\nimport org.knowm.xchange.ExchangeFactory;\nimport org.knowm.xchange.ExchangeSpecification;\nimport org.knowm.xchange.btctrade.BTCTradeExchange;\nimport org.knowm.xchange.btctrade.dto.trade.BTCTradeOrder;\nimport org.knowm.xchange.btctrade.service.BTCTradeTradeServiceRaw;\nimport org.knowm.xchange.dto.marketdata.Trades;\nimport org.knowm.xchange.dto.trade.OpenOrders;\nimport org.knowm.xchange.service.trade.TradeService;\n\npublic class TradeHistoryDemo {\n\n public static void main(String[] args) throws IOException {\n // API key with Read Only Permission or All Permissions.\n String publicKey = args[0];\n String privateKey = args[1];\n ExchangeSpecification spec = new ExchangeSpecification(BTCTradeExchange.class);\n spec.setApiKey(publicKey);\n spec.setSecretKey(privateKey);\n Exchange btcTrade = ExchangeFactory.INSTANCE.createExchange(spec);\n generic(btcTrade);\n raw(btcTrade);\n }\n\n private static void generic(Exchange exchange) throws IOException {\n TradeService tradeService = exchange.getTradeService();\n OpenOrders openOrders = tradeService.getOpenOrders();\n System.out.println(\"Open orders: \" + openOrders);\n Trades trades = tradeService.getTradeHistory(tradeService.createTradeHistoryParams());\n System.out.println(\"Trades: \" + trades);\n }\n\n private static void raw(Exchange exchange) throws IOException ", "post_mask_code": "\n}\n"} {"task_id": "Java_2766", "language": "Java", "task_type": "single_line", "source_file": "java/github/knowm/XChange/xchange-examples/src/main/java/org/knowm/xchange/examples/btctrade/trade/TradeHistoryDemo.java", "mask_start_position": 1027, "mask_end_position": 1030, "canonical_solution": "e);", "pre_mask_code": "package org.knowm.xchange.examples.btctrade.trade;\n\nimport java.io.IOException;\nimport org.knowm.xchange.Exchange;\nimport org.knowm.xchange.ExchangeFactory;\nimport org.knowm.xchange.ExchangeSpecification;\nimport org.knowm.xchange.btctrade.BTCTradeExchange;\nimport org.knowm.xchange.btctrade.dto.trade.BTCTradeOrder;\nimport org.knowm.xchange.btctrade.service.BTCTradeTradeServiceRaw;\nimport org.knowm.xchange.dto.marketdata.Trades;\nimport org.knowm.xchange.dto.trade.OpenOrders;\nimport org.knowm.xchange.service.trade.TradeService;\n\npublic class TradeHistoryDemo {\n\n public static void main(String[] args) throws IOException {\n // API key with Read Only Permission or All Permissions.\n String publicKey = args[0];\n String privateKey = args[1];\n ExchangeSpecification spec = new ExchangeSpecification(BTCTradeExchange.class);\n spec.setApiKey(publicKey);\n spec.setSecretKey(privateKey);\n Exchange btcTrade = ExchangeFactory.INSTANCE.createExchange(spec);\n generic(btcTrad", "post_mask_code": "\n raw(btcTrade);\n }\n\n private static void generic(Exchange exchange) throws IOException {\n TradeService tradeService = exchange.getTradeService();\n OpenOrders openOrders = tradeService.getOpenOrders();\n System.out.println(\"Open orders: \" + openOrders);\n Trades trades = tradeService.getTradeHistory(tradeService.createTradeHistoryParams());\n System.out.println(\"Trades: \" + trades);\n }\n\n private static void raw(Exchange exchange) throws IOException {\n BTCTradeTradeServiceRaw tradeService = (BTCTradeTradeServiceRaw) exchange.getTradeService();\n BTCTradeOrder[] orders = tradeService.getBTCTradeOrders(0, \"open\");\n System.out.println(\"Open orders: \" + orders.length);\n String orderId = orders.length > 0 ? orders[0].getId() : \"1\";\n BTCTradeOrder order = tradeService.getBTCTradeOrder(orderId);\n System.out.println(\"Order status: \" + order.getStatus());\n }\n}\n"} {"task_id": "Java_2767", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Hotel-Reservation-Service/FillTheForm/filltheform/src/main/java/com/hrs/filltheform/main/MainActivityModel.java", "mask_start_position": 7227, "mask_end_position": 7287, "canonical_solution": "public void setAccessibilityServiceEnabled(boolean enabled) ", "pre_mask_code": "package com.hrs.filltheform.main;\n\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport com.hrs.filltheform.common.PropertyChangedListener;\nimport java.util.List;\n\n/**\n * This model class holds the state and manages behavior of the MainActivity.\n */\npublic class MainActivityModel implements Parcelable {\n\n public static final String PROPERTY_PERMISSIONS_HEADER = \"property_permissions_header\";\n\n public static final String PROPERTY_SYSTEM_ALERT_WINDOW_CONTAINER = \"property_system_alert_window_container\";\n\n public static final String PROPERTY_SYSTEM_ALERT_WINDOW_PERMISSION = \"property_system_alert_window_permission\";\n\n public static final String PROPERTY_READ_EXTERNAL_STORAGE_CONTAINER = \"property_read_external_storage_container\";\n\n public static final String PROPERTY_READ_EXTERNAL_STORAGE_PERMISSION = \"property_read_external_storage_permission\";\n\n public static final String PROPERTY_LOAD_CONFIGURATION_FILE_CONTAINER = \"property_load_configuration_file_container\";\n\n public static final String PROPERTY_LOAD_CONFIGURATION_FILE_BUTTON = \"property_load_configuration_file_button\";\n\n public static final String PROPERTY_SELECT_CONFIGURATION_FILE_BUTTON = \"property_select_configuration_file_button\";\n\n public static final String PROPERTY_CONFIGURATION_FILE_ATTRIBUTES = \"property_configuration_file_attributes\";\n\n public static final String PROPERTY_SAVE_CONFIGURATION_FILE_ATTRIBUTES = \"property_save_configuration_file_attributes\";\n\n public static final String PROPERTY_CONFIGURATION_LOADING_IN_PROGRESS = \"property_configuration_loading_in_progress\";\n\n public static final String PROPERTY_ACCESSIBILITY_SERVICE_CONTAINER = \"property_accessibility_service_container\";\n\n public static final String PROPERTY_ACCESSIBILITY_SERVICE_BUTTON = \"property_accessibility_service_button\";\n\n public static final String PROPERTY_LOADED_PACKAGE_NAMES_CONTAINER = \"property_loaded_package_names_container\";\n\n public static final String PROPERTY_LOADED_PACKAGE_NAMES_EMPTY = \"property_loaded_package_names_empty\";\n\n public static final String PROPERTY_LOADED_PACKAGE_NAMES_LIST = \"property_loaded_package_names_list\";\n\n private PropertyChangedListener propertyChangedListener;\n\n private boolean permissionsHeaderVisible = true;\n\n private boolean systemAlertWindowContainerVisible = true;\n\n private boolean readExternalStorageContainerVisible = true;\n\n private boolean accessibilityServiceContainerVisible = true;\n\n private boolean loadConfigurationFileContainerVisible = false;\n\n private String configurationFilePath;\n\n private String configurationFileName;\n\n private boolean loadedPackageNamesContainerVisible = false;\n\n private boolean loadedPackageNamesEmptyVisible = false;\n\n private boolean loadedPackageNamesListVisible = false;\n\n private List loadedPackageNames;\n\n private boolean configurationLoadingInProgress = false;\n\n public MainActivityModel() {\n }\n\n // Permissions header\n public boolean isPermissionsHeaderVisible() {\n return permissionsHeaderVisible;\n }\n\n private void setPermissionHeaderVisible(boolean permissionHeaderVisible) {\n this.permissionsHeaderVisible = permissionHeaderVisible;\n notifyPropertyChanged(PROPERTY_PERMISSIONS_HEADER);\n }\n\n // Permission buttons\n public void onEnableSystemAlertWindowContainerButtonClicked() {\n notifyPropertyChanged(PROPERTY_SYSTEM_ALERT_WINDOW_PERMISSION);\n }\n\n public void onEnableReadExternalStorageButtonClicked() {\n notifyPropertyChanged(PROPERTY_READ_EXTERNAL_STORAGE_PERMISSION);\n }\n\n // Permissions enable/disable\n public void setSystemAlertWindowPermissionEnabled(boolean enabled) {\n setSystemAlertWindowContainerVisible(!enabled);\n }\n\n public void setReadExternalStorageEnabled(boolean enabled) {\n setReadExternalStorageContainerVisible(!enabled);\n }\n\n // Permission view containers\n public boolean isSystemAlertWindowContainerVisible() {\n return systemAlertWindowContainerVisible;\n }\n\n private void setSystemAlertWindowContainerVisible(boolean systemAlertWindowContainerVisible) {\n this.systemAlertWindowContainerVisible = systemAlertWindowContainerVisible;\n notifyPropertyChanged(PROPERTY_SYSTEM_ALERT_WINDOW_CONTAINER);\n }\n\n public boolean isReadExternalStorageContainerVisible() {\n return readExternalStorageContainerVisible;\n }\n\n private void setReadExternalStorageContainerVisible(boolean readExternalStorageContainerVisible) {\n this.readExternalStorageContainerVisible = readExternalStorageContainerVisible;\n notifyPropertyChanged(PROPERTY_READ_EXTERNAL_STORAGE_CONTAINER);\n }\n\n // Load configuration file\n public void checkIfLoadingOfConfigurationFileIsAllowed() {\n boolean allowed;\n allowed = !(systemAlertWindowContainerVisible || accessibilityServiceContainerVisible || readExternalStorageContainerVisible);\n setLoadConfigurationFileContainerVisible(allowed);\n setLoadedPackageNamesContainerVisible(allowed);\n setPermissionHeaderVisible(!allowed);\n notifyPropertyChanged(PROPERTY_CONFIGURATION_FILE_ATTRIBUTES);\n notifyPropertyChanged(PROPERTY_CONFIGURATION_LOADING_IN_PROGRESS);\n }\n\n public boolean isLoadConfigurationFileContainerVisible() {\n return loadConfigurationFileContainerVisible;\n }\n\n private void setLoadConfigurationFileContainerVisible(boolean loadConfigurationFileContainerVisible) {\n this.loadConfigurationFileContainerVisible = loadConfigurationFileContainerVisible;\n notifyPropertyChanged(PROPERTY_LOAD_CONFIGURATION_FILE_CONTAINER);\n }\n\n public void onLoadConfigurationFileButtonClicked() {\n setLoadedPackageNamesListVisible(false);\n setConfigurationLoadingInProgress(true);\n notifyPropertyChanged(PROPERTY_LOAD_CONFIGURATION_FILE_BUTTON);\n }\n\n public void onSelectConfigurationFileButtonClicked() {\n notifyPropertyChanged(PROPERTY_SELECT_CONFIGURATION_FILE_BUTTON);\n }\n\n public String getConfigurationFilePath() {\n return configurationFilePath;\n }\n\n public String getConfigurationFileName() {\n return configurationFileName;\n }\n\n public void setConfigurationFileAttributes(String configurationFilePath, String configurationFileName) {\n this.configurationFilePath = configurationFilePath;\n this.configurationFileName = configurationFileName;\n notifyPropertyChanged(PROPERTY_CONFIGURATION_FILE_ATTRIBUTES);\n }\n\n public void saveConfigurationFileAttributes() {\n notifyPropertyChanged(PROPERTY_SAVE_CONFIGURATION_FILE_ATTRIBUTES);\n }\n\n public boolean isConfigurationLoadingInProgress() {\n return configurationLoadingInProgress;\n }\n\n private void setConfigurationLoadingInProgress(boolean configurationLoadingInProgress) {\n this.configurationLoadingInProgress = configurationLoadingInProgress;\n notifyPropertyChanged(PROPERTY_CONFIGURATION_LOADING_IN_PROGRESS);\n }\n\n // Accessibility service\n public void onEnableAccessibilityServiceButtonClicked() {\n notifyPropertyChanged(PROPERTY_ACCESSIBILITY_SERVICE_BUTTON);\n }\n\n ", "post_mask_code": "{\n setAccessibilityServiceContainerVisible(!enabled);\n }\n\n public boolean isAccessibilityServiceContainerVisible() {\n return accessibilityServiceContainerVisible;\n }\n\n private void setAccessibilityServiceContainerVisible(boolean accessibilityServiceContainerVisible) {\n this.accessibilityServiceContainerVisible = accessibilityServiceContainerVisible;\n notifyPropertyChanged(PROPERTY_ACCESSIBILITY_SERVICE_CONTAINER);\n }\n\n // Package names\n public List getLoadedPackageNames() {\n return loadedPackageNames;\n }\n\n public void onPackageNamesLoaded(List loadedPackageNames) {\n this.loadedPackageNames = loadedPackageNames;\n setConfigurationLoadingInProgress(false);\n if (loadedPackageNames == null || loadedPackageNames.isEmpty()) {\n setLoadedPackageNamesEmptyVisible(true);\n setLoadedPackageNamesListVisible(false);\n } else {\n setLoadedPackageNamesEmptyVisible(false);\n setLoadedPackageNamesListVisible(true);\n }\n }\n\n public boolean isLoadedPackageNamesListVisible() {\n return loadedPackageNamesListVisible;\n }\n\n private void setLoadedPackageNamesListVisible(boolean loadedPackageNamesListVisible) {\n this.loadedPackageNamesListVisible = loadedPackageNamesListVisible;\n notifyPropertyChanged(PROPERTY_LOADED_PACKAGE_NAMES_LIST);\n }\n\n public boolean isLoadedPackageNamesContainerVisible() {\n return loadedPackageNamesContainerVisible;\n }\n\n private void setLoadedPackageNamesContainerVisible(boolean loadedPackageNamesContainerVisible) {\n this.loadedPackageNamesContainerVisible = loadedPackageNamesContainerVisible;\n notifyPropertyChanged(PROPERTY_LOADED_PACKAGE_NAMES_CONTAINER);\n }\n\n // Property changes\n public void setPropertyChangedListener(PropertyChangedListener propertyChangedListener) {\n this.propertyChangedListener = propertyChangedListener;\n }\n\n private void notifyPropertyChanged(String property) {\n if (propertyChangedListener != null) {\n propertyChangedListener.onPropertyChanged(property);\n }\n }\n\n public boolean isLoadedPackageNamesEmptyVisible() {\n return loadedPackageNamesEmptyVisible;\n }\n\n private void setLoadedPackageNamesEmptyVisible(boolean loadedPackageNamesEmptyVisible) {\n this.loadedPackageNamesEmptyVisible = loadedPackageNamesEmptyVisible;\n notifyPropertyChanged(PROPERTY_LOADED_PACKAGE_NAMES_EMPTY);\n }\n\n // Parcelable\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeByte(permissionsHeaderVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(systemAlertWindowContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(readExternalStorageContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(accessibilityServiceContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(loadConfigurationFileContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeString(this.configurationFilePath);\n dest.writeString(this.configurationFileName);\n dest.writeByte(loadedPackageNamesContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(loadedPackageNamesEmptyVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(loadedPackageNamesListVisible ? (byte) 1 : (byte) 0);\n dest.writeStringList(this.loadedPackageNames);\n dest.writeByte(configurationLoadingInProgress ? (byte) 1 : (byte) 0);\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n protected MainActivityModel(Parcel in) {\n this.permissionsHeaderVisible = in.readByte() != 0;\n this.systemAlertWindowContainerVisible = in.readByte() != 0;\n this.readExternalStorageContainerVisible = in.readByte() != 0;\n this.accessibilityServiceContainerVisible = in.readByte() != 0;\n this.loadConfigurationFileContainerVisible = in.readByte() != 0;\n this.configurationFilePath = in.readString();\n this.configurationFileName = in.readString();\n this.loadedPackageNamesContainerVisible = in.readByte() != 0;\n this.loadedPackageNamesEmptyVisible = in.readByte() != 0;\n this.loadedPackageNamesListVisible = in.readByte() != 0;\n this.loadedPackageNames = in.createStringArrayList();\n this.configurationLoadingInProgress = in.readByte() != 0;\n }\n\n public static final Creator CREATOR = new Creator() {\n\n public MainActivityModel createFromParcel(Parcel source) {\n return new MainActivityModel(source);\n }\n\n public MainActivityModel[] newArray(int size) {\n return new MainActivityModel[size];\n }\n };\n}\n"} {"task_id": "Java_2768", "language": "Java", "task_type": "method_body", "source_file": "java/github/Hotel-Reservation-Service/FillTheForm/filltheform/src/main/java/com/hrs/filltheform/main/MainActivityModel.java", "mask_start_position": 9339, "mask_end_position": 9468, "canonical_solution": "{\n if (propertyChangedListener != null) {\n propertyChangedListener.onPropertyChanged(property);\n }\n }", "pre_mask_code": "package com.hrs.filltheform.main;\n\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport com.hrs.filltheform.common.PropertyChangedListener;\nimport java.util.List;\n\n/**\n * This model class holds the state and manages behavior of the MainActivity.\n */\npublic class MainActivityModel implements Parcelable {\n\n public static final String PROPERTY_PERMISSIONS_HEADER = \"property_permissions_header\";\n\n public static final String PROPERTY_SYSTEM_ALERT_WINDOW_CONTAINER = \"property_system_alert_window_container\";\n\n public static final String PROPERTY_SYSTEM_ALERT_WINDOW_PERMISSION = \"property_system_alert_window_permission\";\n\n public static final String PROPERTY_READ_EXTERNAL_STORAGE_CONTAINER = \"property_read_external_storage_container\";\n\n public static final String PROPERTY_READ_EXTERNAL_STORAGE_PERMISSION = \"property_read_external_storage_permission\";\n\n public static final String PROPERTY_LOAD_CONFIGURATION_FILE_CONTAINER = \"property_load_configuration_file_container\";\n\n public static final String PROPERTY_LOAD_CONFIGURATION_FILE_BUTTON = \"property_load_configuration_file_button\";\n\n public static final String PROPERTY_SELECT_CONFIGURATION_FILE_BUTTON = \"property_select_configuration_file_button\";\n\n public static final String PROPERTY_CONFIGURATION_FILE_ATTRIBUTES = \"property_configuration_file_attributes\";\n\n public static final String PROPERTY_SAVE_CONFIGURATION_FILE_ATTRIBUTES = \"property_save_configuration_file_attributes\";\n\n public static final String PROPERTY_CONFIGURATION_LOADING_IN_PROGRESS = \"property_configuration_loading_in_progress\";\n\n public static final String PROPERTY_ACCESSIBILITY_SERVICE_CONTAINER = \"property_accessibility_service_container\";\n\n public static final String PROPERTY_ACCESSIBILITY_SERVICE_BUTTON = \"property_accessibility_service_button\";\n\n public static final String PROPERTY_LOADED_PACKAGE_NAMES_CONTAINER = \"property_loaded_package_names_container\";\n\n public static final String PROPERTY_LOADED_PACKAGE_NAMES_EMPTY = \"property_loaded_package_names_empty\";\n\n public static final String PROPERTY_LOADED_PACKAGE_NAMES_LIST = \"property_loaded_package_names_list\";\n\n private PropertyChangedListener propertyChangedListener;\n\n private boolean permissionsHeaderVisible = true;\n\n private boolean systemAlertWindowContainerVisible = true;\n\n private boolean readExternalStorageContainerVisible = true;\n\n private boolean accessibilityServiceContainerVisible = true;\n\n private boolean loadConfigurationFileContainerVisible = false;\n\n private String configurationFilePath;\n\n private String configurationFileName;\n\n private boolean loadedPackageNamesContainerVisible = false;\n\n private boolean loadedPackageNamesEmptyVisible = false;\n\n private boolean loadedPackageNamesListVisible = false;\n\n private List loadedPackageNames;\n\n private boolean configurationLoadingInProgress = false;\n\n public MainActivityModel() {\n }\n\n // Permissions header\n public boolean isPermissionsHeaderVisible() {\n return permissionsHeaderVisible;\n }\n\n private void setPermissionHeaderVisible(boolean permissionHeaderVisible) {\n this.permissionsHeaderVisible = permissionHeaderVisible;\n notifyPropertyChanged(PROPERTY_PERMISSIONS_HEADER);\n }\n\n // Permission buttons\n public void onEnableSystemAlertWindowContainerButtonClicked() {\n notifyPropertyChanged(PROPERTY_SYSTEM_ALERT_WINDOW_PERMISSION);\n }\n\n public void onEnableReadExternalStorageButtonClicked() {\n notifyPropertyChanged(PROPERTY_READ_EXTERNAL_STORAGE_PERMISSION);\n }\n\n // Permissions enable/disable\n public void setSystemAlertWindowPermissionEnabled(boolean enabled) {\n setSystemAlertWindowContainerVisible(!enabled);\n }\n\n public void setReadExternalStorageEnabled(boolean enabled) {\n setReadExternalStorageContainerVisible(!enabled);\n }\n\n // Permission view containers\n public boolean isSystemAlertWindowContainerVisible() {\n return systemAlertWindowContainerVisible;\n }\n\n private void setSystemAlertWindowContainerVisible(boolean systemAlertWindowContainerVisible) {\n this.systemAlertWindowContainerVisible = systemAlertWindowContainerVisible;\n notifyPropertyChanged(PROPERTY_SYSTEM_ALERT_WINDOW_CONTAINER);\n }\n\n public boolean isReadExternalStorageContainerVisible() {\n return readExternalStorageContainerVisible;\n }\n\n private void setReadExternalStorageContainerVisible(boolean readExternalStorageContainerVisible) {\n this.readExternalStorageContainerVisible = readExternalStorageContainerVisible;\n notifyPropertyChanged(PROPERTY_READ_EXTERNAL_STORAGE_CONTAINER);\n }\n\n // Load configuration file\n public void checkIfLoadingOfConfigurationFileIsAllowed() {\n boolean allowed;\n allowed = !(systemAlertWindowContainerVisible || accessibilityServiceContainerVisible || readExternalStorageContainerVisible);\n setLoadConfigurationFileContainerVisible(allowed);\n setLoadedPackageNamesContainerVisible(allowed);\n setPermissionHeaderVisible(!allowed);\n notifyPropertyChanged(PROPERTY_CONFIGURATION_FILE_ATTRIBUTES);\n notifyPropertyChanged(PROPERTY_CONFIGURATION_LOADING_IN_PROGRESS);\n }\n\n public boolean isLoadConfigurationFileContainerVisible() {\n return loadConfigurationFileContainerVisible;\n }\n\n private void setLoadConfigurationFileContainerVisible(boolean loadConfigurationFileContainerVisible) {\n this.loadConfigurationFileContainerVisible = loadConfigurationFileContainerVisible;\n notifyPropertyChanged(PROPERTY_LOAD_CONFIGURATION_FILE_CONTAINER);\n }\n\n public void onLoadConfigurationFileButtonClicked() {\n setLoadedPackageNamesListVisible(false);\n setConfigurationLoadingInProgress(true);\n notifyPropertyChanged(PROPERTY_LOAD_CONFIGURATION_FILE_BUTTON);\n }\n\n public void onSelectConfigurationFileButtonClicked() {\n notifyPropertyChanged(PROPERTY_SELECT_CONFIGURATION_FILE_BUTTON);\n }\n\n public String getConfigurationFilePath() {\n return configurationFilePath;\n }\n\n public String getConfigurationFileName() {\n return configurationFileName;\n }\n\n public void setConfigurationFileAttributes(String configurationFilePath, String configurationFileName) {\n this.configurationFilePath = configurationFilePath;\n this.configurationFileName = configurationFileName;\n notifyPropertyChanged(PROPERTY_CONFIGURATION_FILE_ATTRIBUTES);\n }\n\n public void saveConfigurationFileAttributes() {\n notifyPropertyChanged(PROPERTY_SAVE_CONFIGURATION_FILE_ATTRIBUTES);\n }\n\n public boolean isConfigurationLoadingInProgress() {\n return configurationLoadingInProgress;\n }\n\n private void setConfigurationLoadingInProgress(boolean configurationLoadingInProgress) {\n this.configurationLoadingInProgress = configurationLoadingInProgress;\n notifyPropertyChanged(PROPERTY_CONFIGURATION_LOADING_IN_PROGRESS);\n }\n\n // Accessibility service\n public void onEnableAccessibilityServiceButtonClicked() {\n notifyPropertyChanged(PROPERTY_ACCESSIBILITY_SERVICE_BUTTON);\n }\n\n public void setAccessibilityServiceEnabled(boolean enabled) {\n setAccessibilityServiceContainerVisible(!enabled);\n }\n\n public boolean isAccessibilityServiceContainerVisible() {\n return accessibilityServiceContainerVisible;\n }\n\n private void setAccessibilityServiceContainerVisible(boolean accessibilityServiceContainerVisible) {\n this.accessibilityServiceContainerVisible = accessibilityServiceContainerVisible;\n notifyPropertyChanged(PROPERTY_ACCESSIBILITY_SERVICE_CONTAINER);\n }\n\n // Package names\n public List getLoadedPackageNames() {\n return loadedPackageNames;\n }\n\n public void onPackageNamesLoaded(List loadedPackageNames) {\n this.loadedPackageNames = loadedPackageNames;\n setConfigurationLoadingInProgress(false);\n if (loadedPackageNames == null || loadedPackageNames.isEmpty()) {\n setLoadedPackageNamesEmptyVisible(true);\n setLoadedPackageNamesListVisible(false);\n } else {\n setLoadedPackageNamesEmptyVisible(false);\n setLoadedPackageNamesListVisible(true);\n }\n }\n\n public boolean isLoadedPackageNamesListVisible() {\n return loadedPackageNamesListVisible;\n }\n\n private void setLoadedPackageNamesListVisible(boolean loadedPackageNamesListVisible) {\n this.loadedPackageNamesListVisible = loadedPackageNamesListVisible;\n notifyPropertyChanged(PROPERTY_LOADED_PACKAGE_NAMES_LIST);\n }\n\n public boolean isLoadedPackageNamesContainerVisible() {\n return loadedPackageNamesContainerVisible;\n }\n\n private void setLoadedPackageNamesContainerVisible(boolean loadedPackageNamesContainerVisible) {\n this.loadedPackageNamesContainerVisible = loadedPackageNamesContainerVisible;\n notifyPropertyChanged(PROPERTY_LOADED_PACKAGE_NAMES_CONTAINER);\n }\n\n // Property changes\n public void setPropertyChangedListener(PropertyChangedListener propertyChangedListener) {\n this.propertyChangedListener = propertyChangedListener;\n }\n\n private void notifyPropertyChanged(String property) ", "post_mask_code": "\n\n public boolean isLoadedPackageNamesEmptyVisible() {\n return loadedPackageNamesEmptyVisible;\n }\n\n private void setLoadedPackageNamesEmptyVisible(boolean loadedPackageNamesEmptyVisible) {\n this.loadedPackageNamesEmptyVisible = loadedPackageNamesEmptyVisible;\n notifyPropertyChanged(PROPERTY_LOADED_PACKAGE_NAMES_EMPTY);\n }\n\n // Parcelable\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeByte(permissionsHeaderVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(systemAlertWindowContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(readExternalStorageContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(accessibilityServiceContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(loadConfigurationFileContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeString(this.configurationFilePath);\n dest.writeString(this.configurationFileName);\n dest.writeByte(loadedPackageNamesContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(loadedPackageNamesEmptyVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(loadedPackageNamesListVisible ? (byte) 1 : (byte) 0);\n dest.writeStringList(this.loadedPackageNames);\n dest.writeByte(configurationLoadingInProgress ? (byte) 1 : (byte) 0);\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n protected MainActivityModel(Parcel in) {\n this.permissionsHeaderVisible = in.readByte() != 0;\n this.systemAlertWindowContainerVisible = in.readByte() != 0;\n this.readExternalStorageContainerVisible = in.readByte() != 0;\n this.accessibilityServiceContainerVisible = in.readByte() != 0;\n this.loadConfigurationFileContainerVisible = in.readByte() != 0;\n this.configurationFilePath = in.readString();\n this.configurationFileName = in.readString();\n this.loadedPackageNamesContainerVisible = in.readByte() != 0;\n this.loadedPackageNamesEmptyVisible = in.readByte() != 0;\n this.loadedPackageNamesListVisible = in.readByte() != 0;\n this.loadedPackageNames = in.createStringArrayList();\n this.configurationLoadingInProgress = in.readByte() != 0;\n }\n\n public static final Creator CREATOR = new Creator() {\n\n public MainActivityModel createFromParcel(Parcel source) {\n return new MainActivityModel(source);\n }\n\n public MainActivityModel[] newArray(int size) {\n return new MainActivityModel[size];\n }\n };\n}\n"} {"task_id": "Java_2769", "language": "Java", "task_type": "single_line", "source_file": "java/github/Hotel-Reservation-Service/FillTheForm/filltheform/src/main/java/com/hrs/filltheform/main/MainActivityModel.java", "mask_start_position": 4988, "mask_end_position": 5031, "canonical_solution": "ConfigurationFileContainerVisible(allowed);", "pre_mask_code": "package com.hrs.filltheform.main;\n\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport com.hrs.filltheform.common.PropertyChangedListener;\nimport java.util.List;\n\n/**\n * This model class holds the state and manages behavior of the MainActivity.\n */\npublic class MainActivityModel implements Parcelable {\n\n public static final String PROPERTY_PERMISSIONS_HEADER = \"property_permissions_header\";\n\n public static final String PROPERTY_SYSTEM_ALERT_WINDOW_CONTAINER = \"property_system_alert_window_container\";\n\n public static final String PROPERTY_SYSTEM_ALERT_WINDOW_PERMISSION = \"property_system_alert_window_permission\";\n\n public static final String PROPERTY_READ_EXTERNAL_STORAGE_CONTAINER = \"property_read_external_storage_container\";\n\n public static final String PROPERTY_READ_EXTERNAL_STORAGE_PERMISSION = \"property_read_external_storage_permission\";\n\n public static final String PROPERTY_LOAD_CONFIGURATION_FILE_CONTAINER = \"property_load_configuration_file_container\";\n\n public static final String PROPERTY_LOAD_CONFIGURATION_FILE_BUTTON = \"property_load_configuration_file_button\";\n\n public static final String PROPERTY_SELECT_CONFIGURATION_FILE_BUTTON = \"property_select_configuration_file_button\";\n\n public static final String PROPERTY_CONFIGURATION_FILE_ATTRIBUTES = \"property_configuration_file_attributes\";\n\n public static final String PROPERTY_SAVE_CONFIGURATION_FILE_ATTRIBUTES = \"property_save_configuration_file_attributes\";\n\n public static final String PROPERTY_CONFIGURATION_LOADING_IN_PROGRESS = \"property_configuration_loading_in_progress\";\n\n public static final String PROPERTY_ACCESSIBILITY_SERVICE_CONTAINER = \"property_accessibility_service_container\";\n\n public static final String PROPERTY_ACCESSIBILITY_SERVICE_BUTTON = \"property_accessibility_service_button\";\n\n public static final String PROPERTY_LOADED_PACKAGE_NAMES_CONTAINER = \"property_loaded_package_names_container\";\n\n public static final String PROPERTY_LOADED_PACKAGE_NAMES_EMPTY = \"property_loaded_package_names_empty\";\n\n public static final String PROPERTY_LOADED_PACKAGE_NAMES_LIST = \"property_loaded_package_names_list\";\n\n private PropertyChangedListener propertyChangedListener;\n\n private boolean permissionsHeaderVisible = true;\n\n private boolean systemAlertWindowContainerVisible = true;\n\n private boolean readExternalStorageContainerVisible = true;\n\n private boolean accessibilityServiceContainerVisible = true;\n\n private boolean loadConfigurationFileContainerVisible = false;\n\n private String configurationFilePath;\n\n private String configurationFileName;\n\n private boolean loadedPackageNamesContainerVisible = false;\n\n private boolean loadedPackageNamesEmptyVisible = false;\n\n private boolean loadedPackageNamesListVisible = false;\n\n private List loadedPackageNames;\n\n private boolean configurationLoadingInProgress = false;\n\n public MainActivityModel() {\n }\n\n // Permissions header\n public boolean isPermissionsHeaderVisible() {\n return permissionsHeaderVisible;\n }\n\n private void setPermissionHeaderVisible(boolean permissionHeaderVisible) {\n this.permissionsHeaderVisible = permissionHeaderVisible;\n notifyPropertyChanged(PROPERTY_PERMISSIONS_HEADER);\n }\n\n // Permission buttons\n public void onEnableSystemAlertWindowContainerButtonClicked() {\n notifyPropertyChanged(PROPERTY_SYSTEM_ALERT_WINDOW_PERMISSION);\n }\n\n public void onEnableReadExternalStorageButtonClicked() {\n notifyPropertyChanged(PROPERTY_READ_EXTERNAL_STORAGE_PERMISSION);\n }\n\n // Permissions enable/disable\n public void setSystemAlertWindowPermissionEnabled(boolean enabled) {\n setSystemAlertWindowContainerVisible(!enabled);\n }\n\n public void setReadExternalStorageEnabled(boolean enabled) {\n setReadExternalStorageContainerVisible(!enabled);\n }\n\n // Permission view containers\n public boolean isSystemAlertWindowContainerVisible() {\n return systemAlertWindowContainerVisible;\n }\n\n private void setSystemAlertWindowContainerVisible(boolean systemAlertWindowContainerVisible) {\n this.systemAlertWindowContainerVisible = systemAlertWindowContainerVisible;\n notifyPropertyChanged(PROPERTY_SYSTEM_ALERT_WINDOW_CONTAINER);\n }\n\n public boolean isReadExternalStorageContainerVisible() {\n return readExternalStorageContainerVisible;\n }\n\n private void setReadExternalStorageContainerVisible(boolean readExternalStorageContainerVisible) {\n this.readExternalStorageContainerVisible = readExternalStorageContainerVisible;\n notifyPropertyChanged(PROPERTY_READ_EXTERNAL_STORAGE_CONTAINER);\n }\n\n // Load configuration file\n public void checkIfLoadingOfConfigurationFileIsAllowed() {\n boolean allowed;\n allowed = !(systemAlertWindowContainerVisible || accessibilityServiceContainerVisible || readExternalStorageContainerVisible);\n setLoad", "post_mask_code": "\n setLoadedPackageNamesContainerVisible(allowed);\n setPermissionHeaderVisible(!allowed);\n notifyPropertyChanged(PROPERTY_CONFIGURATION_FILE_ATTRIBUTES);\n notifyPropertyChanged(PROPERTY_CONFIGURATION_LOADING_IN_PROGRESS);\n }\n\n public boolean isLoadConfigurationFileContainerVisible() {\n return loadConfigurationFileContainerVisible;\n }\n\n private void setLoadConfigurationFileContainerVisible(boolean loadConfigurationFileContainerVisible) {\n this.loadConfigurationFileContainerVisible = loadConfigurationFileContainerVisible;\n notifyPropertyChanged(PROPERTY_LOAD_CONFIGURATION_FILE_CONTAINER);\n }\n\n public void onLoadConfigurationFileButtonClicked() {\n setLoadedPackageNamesListVisible(false);\n setConfigurationLoadingInProgress(true);\n notifyPropertyChanged(PROPERTY_LOAD_CONFIGURATION_FILE_BUTTON);\n }\n\n public void onSelectConfigurationFileButtonClicked() {\n notifyPropertyChanged(PROPERTY_SELECT_CONFIGURATION_FILE_BUTTON);\n }\n\n public String getConfigurationFilePath() {\n return configurationFilePath;\n }\n\n public String getConfigurationFileName() {\n return configurationFileName;\n }\n\n public void setConfigurationFileAttributes(String configurationFilePath, String configurationFileName) {\n this.configurationFilePath = configurationFilePath;\n this.configurationFileName = configurationFileName;\n notifyPropertyChanged(PROPERTY_CONFIGURATION_FILE_ATTRIBUTES);\n }\n\n public void saveConfigurationFileAttributes() {\n notifyPropertyChanged(PROPERTY_SAVE_CONFIGURATION_FILE_ATTRIBUTES);\n }\n\n public boolean isConfigurationLoadingInProgress() {\n return configurationLoadingInProgress;\n }\n\n private void setConfigurationLoadingInProgress(boolean configurationLoadingInProgress) {\n this.configurationLoadingInProgress = configurationLoadingInProgress;\n notifyPropertyChanged(PROPERTY_CONFIGURATION_LOADING_IN_PROGRESS);\n }\n\n // Accessibility service\n public void onEnableAccessibilityServiceButtonClicked() {\n notifyPropertyChanged(PROPERTY_ACCESSIBILITY_SERVICE_BUTTON);\n }\n\n public void setAccessibilityServiceEnabled(boolean enabled) {\n setAccessibilityServiceContainerVisible(!enabled);\n }\n\n public boolean isAccessibilityServiceContainerVisible() {\n return accessibilityServiceContainerVisible;\n }\n\n private void setAccessibilityServiceContainerVisible(boolean accessibilityServiceContainerVisible) {\n this.accessibilityServiceContainerVisible = accessibilityServiceContainerVisible;\n notifyPropertyChanged(PROPERTY_ACCESSIBILITY_SERVICE_CONTAINER);\n }\n\n // Package names\n public List getLoadedPackageNames() {\n return loadedPackageNames;\n }\n\n public void onPackageNamesLoaded(List loadedPackageNames) {\n this.loadedPackageNames = loadedPackageNames;\n setConfigurationLoadingInProgress(false);\n if (loadedPackageNames == null || loadedPackageNames.isEmpty()) {\n setLoadedPackageNamesEmptyVisible(true);\n setLoadedPackageNamesListVisible(false);\n } else {\n setLoadedPackageNamesEmptyVisible(false);\n setLoadedPackageNamesListVisible(true);\n }\n }\n\n public boolean isLoadedPackageNamesListVisible() {\n return loadedPackageNamesListVisible;\n }\n\n private void setLoadedPackageNamesListVisible(boolean loadedPackageNamesListVisible) {\n this.loadedPackageNamesListVisible = loadedPackageNamesListVisible;\n notifyPropertyChanged(PROPERTY_LOADED_PACKAGE_NAMES_LIST);\n }\n\n public boolean isLoadedPackageNamesContainerVisible() {\n return loadedPackageNamesContainerVisible;\n }\n\n private void setLoadedPackageNamesContainerVisible(boolean loadedPackageNamesContainerVisible) {\n this.loadedPackageNamesContainerVisible = loadedPackageNamesContainerVisible;\n notifyPropertyChanged(PROPERTY_LOADED_PACKAGE_NAMES_CONTAINER);\n }\n\n // Property changes\n public void setPropertyChangedListener(PropertyChangedListener propertyChangedListener) {\n this.propertyChangedListener = propertyChangedListener;\n }\n\n private void notifyPropertyChanged(String property) {\n if (propertyChangedListener != null) {\n propertyChangedListener.onPropertyChanged(property);\n }\n }\n\n public boolean isLoadedPackageNamesEmptyVisible() {\n return loadedPackageNamesEmptyVisible;\n }\n\n private void setLoadedPackageNamesEmptyVisible(boolean loadedPackageNamesEmptyVisible) {\n this.loadedPackageNamesEmptyVisible = loadedPackageNamesEmptyVisible;\n notifyPropertyChanged(PROPERTY_LOADED_PACKAGE_NAMES_EMPTY);\n }\n\n // Parcelable\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeByte(permissionsHeaderVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(systemAlertWindowContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(readExternalStorageContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(accessibilityServiceContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(loadConfigurationFileContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeString(this.configurationFilePath);\n dest.writeString(this.configurationFileName);\n dest.writeByte(loadedPackageNamesContainerVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(loadedPackageNamesEmptyVisible ? (byte) 1 : (byte) 0);\n dest.writeByte(loadedPackageNamesListVisible ? (byte) 1 : (byte) 0);\n dest.writeStringList(this.loadedPackageNames);\n dest.writeByte(configurationLoadingInProgress ? (byte) 1 : (byte) 0);\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n protected MainActivityModel(Parcel in) {\n this.permissionsHeaderVisible = in.readByte() != 0;\n this.systemAlertWindowContainerVisible = in.readByte() != 0;\n this.readExternalStorageContainerVisible = in.readByte() != 0;\n this.accessibilityServiceContainerVisible = in.readByte() != 0;\n this.loadConfigurationFileContainerVisible = in.readByte() != 0;\n this.configurationFilePath = in.readString();\n this.configurationFileName = in.readString();\n this.loadedPackageNamesContainerVisible = in.readByte() != 0;\n this.loadedPackageNamesEmptyVisible = in.readByte() != 0;\n this.loadedPackageNamesListVisible = in.readByte() != 0;\n this.loadedPackageNames = in.createStringArrayList();\n this.configurationLoadingInProgress = in.readByte() != 0;\n }\n\n public static final Creator CREATOR = new Creator() {\n\n public MainActivityModel createFromParcel(Parcel source) {\n return new MainActivityModel(source);\n }\n\n public MainActivityModel[] newArray(int size) {\n return new MainActivityModel[size];\n }\n };\n}\n"} {"task_id": "Java_2770", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/BiglySoftware/BiglyBT/core/src/com/biglybt/pif/ipfilter/IPBlocked.java", "mask_start_position": 227, "mask_end_position": 265, "canonical_solution": "public String getBlockedTorrentName();", "pre_mask_code": "package com.biglybt.pif.ipfilter;\n\n/**\n * @author parg\n */\npublic interface IPBlocked {\n\n public String getBlockedIP();\n\n /**\n * returns the torrent name the IP was blocked trying to access\n * @return\n */\n ", "post_mask_code": "\n\n public long getBlockedTime();\n\n public IPRange getBlockingRange();\n}\n"} {"task_id": "Java_2771", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openhab/openhab-addons/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/DS2405.java", "mask_start_position": 726, "mask_end_position": 791, "canonical_solution": "@Override\n public void configureChannels() throws OwException ", "pre_mask_code": "package org.openhab.binding.onewire.internal.device;\n\nimport org.eclipse.jdt.annotation.NonNullByDefault;\nimport org.openhab.binding.onewire.internal.DigitalIoConfig;\nimport org.openhab.binding.onewire.internal.OwException;\nimport org.openhab.binding.onewire.internal.SensorId;\nimport org.openhab.binding.onewire.internal.handler.OwBaseThingHandler;\nimport org.openhab.binding.onewire.internal.owserver.OwserverDeviceParameter;\n\n/**\n * The {@link DS2405} class defines an DS2405 device\n *\n * @author Jan N. Klug - Initial contribution\n */\n@NonNullByDefault\npublic class DS2405 extends AbstractDigitalOwDevice {\n\n public DS2405(SensorId sensorId, OwBaseThingHandler callback) {\n super(sensorId, callback);\n }\n\n ", "post_mask_code": "{\n OwserverDeviceParameter inParam = new OwserverDeviceParameter(\"uncached/\", \"/sensed\");\n OwserverDeviceParameter outParam = new OwserverDeviceParameter(\"/PIO\");\n ioConfig.add(new DigitalIoConfig(callback.getThing(), 0, inParam, outParam));\n fullInParam = inParam;\n fullOutParam = outParam;\n super.configureChannels();\n }\n}\n"} {"task_id": "Java_2772", "language": "Java", "task_type": "method_body", "source_file": "java/github/openhab/openhab-addons/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/DS2405.java", "mask_start_position": 791, "mask_end_position": 1158, "canonical_solution": "{\n OwserverDeviceParameter inParam = new OwserverDeviceParameter(\"uncached/\", \"/sensed\");\n OwserverDeviceParameter outParam = new OwserverDeviceParameter(\"/PIO\");\n ioConfig.add(new DigitalIoConfig(callback.getThing(), 0, inParam, outParam));\n fullInParam = inParam;\n fullOutParam = outParam;\n super.configureChannels();\n }", "pre_mask_code": "package org.openhab.binding.onewire.internal.device;\n\nimport org.eclipse.jdt.annotation.NonNullByDefault;\nimport org.openhab.binding.onewire.internal.DigitalIoConfig;\nimport org.openhab.binding.onewire.internal.OwException;\nimport org.openhab.binding.onewire.internal.SensorId;\nimport org.openhab.binding.onewire.internal.handler.OwBaseThingHandler;\nimport org.openhab.binding.onewire.internal.owserver.OwserverDeviceParameter;\n\n/**\n * The {@link DS2405} class defines an DS2405 device\n *\n * @author Jan N. Klug - Initial contribution\n */\n@NonNullByDefault\npublic class DS2405 extends AbstractDigitalOwDevice {\n\n public DS2405(SensorId sensorId, OwBaseThingHandler callback) {\n super(sensorId, callback);\n }\n\n @Override\n public void configureChannels() throws OwException ", "post_mask_code": "\n}\n"} {"task_id": "Java_2773", "language": "Java", "task_type": "single_line", "source_file": "java/github/openhab/openhab-addons/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/DS2405.java", "mask_start_position": 1081, "mask_end_position": 1084, "canonical_solution": "am;", "pre_mask_code": "package org.openhab.binding.onewire.internal.device;\n\nimport org.eclipse.jdt.annotation.NonNullByDefault;\nimport org.openhab.binding.onewire.internal.DigitalIoConfig;\nimport org.openhab.binding.onewire.internal.OwException;\nimport org.openhab.binding.onewire.internal.SensorId;\nimport org.openhab.binding.onewire.internal.handler.OwBaseThingHandler;\nimport org.openhab.binding.onewire.internal.owserver.OwserverDeviceParameter;\n\n/**\n * The {@link DS2405} class defines an DS2405 device\n *\n * @author Jan N. Klug - Initial contribution\n */\n@NonNullByDefault\npublic class DS2405 extends AbstractDigitalOwDevice {\n\n public DS2405(SensorId sensorId, OwBaseThingHandler callback) {\n super(sensorId, callback);\n }\n\n @Override\n public void configureChannels() throws OwException {\n OwserverDeviceParameter inParam = new OwserverDeviceParameter(\"uncached/\", \"/sensed\");\n OwserverDeviceParameter outParam = new OwserverDeviceParameter(\"/PIO\");\n ioConfig.add(new DigitalIoConfig(callback.getThing(), 0, inParam, outParam));\n fullInParam = inPar", "post_mask_code": "\n fullOutParam = outParam;\n super.configureChannels();\n }\n}\n"} {"task_id": "Java_2774", "language": "Java", "task_type": "method_signature", "source_file": "java/github/mikaelzero/PageTransformer/app/src/main/java/trans/miaoyongjun/ptf/MainActivity.java", "mask_start_position": 309, "mask_end_position": 374, "canonical_solution": "@Override\n protected void onCreate(Bundle savedInstanceState) ", "pre_mask_code": "package trans.miaoyongjun.ptf;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport miaoyongjun.pagetransformer.TransitionEffect;\n\npublic class MainActivity extends AppCompatActivity implements View.OnClickListener {\n\n ", "post_mask_code": "{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n findViewById(R.id.slowBtn).setOnClickListener(this);\n findViewById(R.id.zoom).setOnClickListener(this);\n findViewById(R.id.zoomStack).setOnClickListener(this);\n findViewById(R.id.cube).setOnClickListener(this);\n findViewById(R.id.depth).setOnClickListener(this);\n }\n\n @Override\n public void onClick(View v) {\n switch(v.getId()) {\n case R.id.slowBtn:\n ShowActivity.transitionEffect = TransitionEffect.SlowBackground;\n startActivity(new Intent(MainActivity.this, ShowActivity.class));\n break;\n case R.id.zoom:\n ShowZoomActivity.transitionEffect = TransitionEffect.Zoom;\n startActivity(new Intent(MainActivity.this, ShowZoomActivity.class));\n break;\n case R.id.zoomStack:\n ShowActivity.transitionEffect = TransitionEffect.ZoomStack;\n startActivity(new Intent(MainActivity.this, ShowActivity.class));\n break;\n case R.id.cube:\n ShowActivity.transitionEffect = TransitionEffect.Cube;\n startActivity(new Intent(MainActivity.this, ShowActivity.class));\n break;\n case R.id.depth:\n ShowActivity.transitionEffect = TransitionEffect.Depth;\n startActivity(new Intent(MainActivity.this, ShowActivity.class));\n break;\n }\n }\n}\n"} {"task_id": "Java_2775", "language": "Java", "task_type": "method_body", "source_file": "java/github/mikaelzero/PageTransformer/app/src/main/java/trans/miaoyongjun/ptf/MainActivity.java", "mask_start_position": 374, "mask_end_position": 772, "canonical_solution": "{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n findViewById(R.id.slowBtn).setOnClickListener(this);\n findViewById(R.id.zoom).setOnClickListener(this);\n findViewById(R.id.zoomStack).setOnClickListener(this);\n findViewById(R.id.cube).setOnClickListener(this);\n findViewById(R.id.depth).setOnClickListener(this);\n }", "pre_mask_code": "package trans.miaoyongjun.ptf;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport miaoyongjun.pagetransformer.TransitionEffect;\n\npublic class MainActivity extends AppCompatActivity implements View.OnClickListener {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) ", "post_mask_code": "\n\n @Override\n public void onClick(View v) {\n switch(v.getId()) {\n case R.id.slowBtn:\n ShowActivity.transitionEffect = TransitionEffect.SlowBackground;\n startActivity(new Intent(MainActivity.this, ShowActivity.class));\n break;\n case R.id.zoom:\n ShowZoomActivity.transitionEffect = TransitionEffect.Zoom;\n startActivity(new Intent(MainActivity.this, ShowZoomActivity.class));\n break;\n case R.id.zoomStack:\n ShowActivity.transitionEffect = TransitionEffect.ZoomStack;\n startActivity(new Intent(MainActivity.this, ShowActivity.class));\n break;\n case R.id.cube:\n ShowActivity.transitionEffect = TransitionEffect.Cube;\n startActivity(new Intent(MainActivity.this, ShowActivity.class));\n break;\n case R.id.depth:\n ShowActivity.transitionEffect = TransitionEffect.Depth;\n startActivity(new Intent(MainActivity.this, ShowActivity.class));\n break;\n }\n }\n}\n"} {"task_id": "Java_2776", "language": "Java", "task_type": "single_line", "source_file": "java/github/mikaelzero/PageTransformer/app/src/main/java/trans/miaoyongjun/ptf/MainActivity.java", "mask_start_position": 508, "mask_end_position": 528, "canonical_solution": "ClickListener(this);", "pre_mask_code": "package trans.miaoyongjun.ptf;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport miaoyongjun.pagetransformer.TransitionEffect;\n\npublic class MainActivity extends AppCompatActivity implements View.OnClickListener {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n findViewById(R.id.slowBtn).setOn", "post_mask_code": "\n findViewById(R.id.zoom).setOnClickListener(this);\n findViewById(R.id.zoomStack).setOnClickListener(this);\n findViewById(R.id.cube).setOnClickListener(this);\n findViewById(R.id.depth).setOnClickListener(this);\n }\n\n @Override\n public void onClick(View v) {\n switch(v.getId()) {\n case R.id.slowBtn:\n ShowActivity.transitionEffect = TransitionEffect.SlowBackground;\n startActivity(new Intent(MainActivity.this, ShowActivity.class));\n break;\n case R.id.zoom:\n ShowZoomActivity.transitionEffect = TransitionEffect.Zoom;\n startActivity(new Intent(MainActivity.this, ShowZoomActivity.class));\n break;\n case R.id.zoomStack:\n ShowActivity.transitionEffect = TransitionEffect.ZoomStack;\n startActivity(new Intent(MainActivity.this, ShowActivity.class));\n break;\n case R.id.cube:\n ShowActivity.transitionEffect = TransitionEffect.Cube;\n startActivity(new Intent(MainActivity.this, ShowActivity.class));\n break;\n case R.id.depth:\n ShowActivity.transitionEffect = TransitionEffect.Depth;\n startActivity(new Intent(MainActivity.this, ShowActivity.class));\n break;\n }\n }\n}\n"} {"task_id": "Java_2777", "language": "Java", "task_type": "method_signature", "source_file": "java/github/zheng-wang/irontest/irontest-core-server/src/main/java/io/irontest/models/assertion/JSONPathAssertionProperties.java", "mask_start_position": 642, "mask_end_position": 701, "canonical_solution": "public void setExpectedValueJSON(String expectedValueJSON) ", "pre_mask_code": "package io.irontest.models.assertion;\n\nimport com.fasterxml.jackson.annotation.JsonView;\nimport io.irontest.models.Properties;\nimport io.irontest.resources.ResourceJsonViews;\n\n@JsonView({ ResourceJsonViews.TeststepEdit.class, ResourceJsonViews.TestcaseExport.class })\npublic class JSONPathAssertionProperties extends Properties {\n\n private String jsonPath;\n\n private String expectedValueJSON;\n\n public String getJsonPath() {\n return jsonPath;\n }\n\n public void setJsonPath(String jsonPath) {\n this.jsonPath = jsonPath;\n }\n\n public String getExpectedValueJSON() {\n return expectedValueJSON;\n }\n\n ", "post_mask_code": "{\n this.expectedValueJSON = expectedValueJSON;\n }\n}\n"} {"task_id": "Java_2778", "language": "Java", "task_type": "method_body", "source_file": "java/github/zheng-wang/irontest/irontest-core-server/src/main/java/io/irontest/models/assertion/JSONPathAssertionProperties.java", "mask_start_position": 511, "mask_end_position": 552, "canonical_solution": "{\n this.jsonPath = jsonPath;\n }", "pre_mask_code": "package io.irontest.models.assertion;\n\nimport com.fasterxml.jackson.annotation.JsonView;\nimport io.irontest.models.Properties;\nimport io.irontest.resources.ResourceJsonViews;\n\n@JsonView({ ResourceJsonViews.TeststepEdit.class, ResourceJsonViews.TestcaseExport.class })\npublic class JSONPathAssertionProperties extends Properties {\n\n private String jsonPath;\n\n private String expectedValueJSON;\n\n public String getJsonPath() {\n return jsonPath;\n }\n\n public void setJsonPath(String jsonPath) ", "post_mask_code": "\n\n public String getExpectedValueJSON() {\n return expectedValueJSON;\n }\n\n public void setExpectedValueJSON(String expectedValueJSON) {\n this.expectedValueJSON = expectedValueJSON;\n }\n}\n"} {"task_id": "Java_2779", "language": "Java", "task_type": "single_line", "source_file": "java/github/zheng-wang/irontest/irontest-core-server/src/main/java/io/irontest/models/assertion/JSONPathAssertionProperties.java", "mask_start_position": 446, "mask_end_position": 458, "canonical_solution": "rn jsonPath;", "pre_mask_code": "package io.irontest.models.assertion;\n\nimport com.fasterxml.jackson.annotation.JsonView;\nimport io.irontest.models.Properties;\nimport io.irontest.resources.ResourceJsonViews;\n\n@JsonView({ ResourceJsonViews.TeststepEdit.class, ResourceJsonViews.TestcaseExport.class })\npublic class JSONPathAssertionProperties extends Properties {\n\n private String jsonPath;\n\n private String expectedValueJSON;\n\n public String getJsonPath() {\n retu", "post_mask_code": "\n }\n\n public void setJsonPath(String jsonPath) {\n this.jsonPath = jsonPath;\n }\n\n public String getExpectedValueJSON() {\n return expectedValueJSON;\n }\n\n public void setExpectedValueJSON(String expectedValueJSON) {\n this.expectedValueJSON = expectedValueJSON;\n }\n}\n"} {"task_id": "Java_2780", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/usergrid/stack/core/src/main/java/org/apache/usergrid/corepersistence/pipeline/read/collect/ConnectionRefFilter.java", "mask_start_position": 1126, "mask_end_position": 1251, "canonical_solution": "@Override\n public Observable> call(final Observable> filterResultObservable) ", "pre_mask_code": "package org.apache.usergrid.corepersistence.pipeline.read.collect;\n\nimport org.apache.usergrid.corepersistence.pipeline.read.AbstractFilter;\nimport org.apache.usergrid.corepersistence.pipeline.read.EdgePath;\nimport org.apache.usergrid.corepersistence.pipeline.read.FilterResult;\nimport org.apache.usergrid.persistence.ConnectionRef;\nimport org.apache.usergrid.persistence.cassandra.ConnectionRefImpl;\nimport org.apache.usergrid.persistence.model.entity.Id;\nimport com.google.common.base.Optional;\nimport com.google.inject.Inject;\nimport com.google.inject.assistedinject.Assisted;\nimport rx.Observable;\n\n/**\n * This class only exists for 1.0 compatibility, remove once services no longer need connection refs\n */\npublic class ConnectionRefFilter extends AbstractFilter, FilterResult> {\n\n private final Id sourceId;\n\n private final String connectionType;\n\n @Inject\n public ConnectionRefFilter(@Assisted(\"sourceId\") final Id sourceId, @Assisted(\"connectionType\") final String connectionType) {\n this.sourceId = sourceId;\n this.connectionType = connectionType;\n }\n\n ", "post_mask_code": "{\n return filterResultObservable.map(targetResult -> {\n final Id targetId = targetResult.getValue();\n final ConnectionRef ref = new ConnectionRefImpl(sourceId.getType(), sourceId.getUuid(), connectionType, targetId.getType(), targetId.getUuid());\n return new FilterResult<>(ref, Optional.absent());\n });\n }\n}\n"} {"task_id": "Java_2781", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/usergrid/stack/core/src/main/java/org/apache/usergrid/corepersistence/pipeline/read/collect/ConnectionRefFilter.java", "mask_start_position": 1251, "mask_end_position": 1617, "canonical_solution": "{\n return filterResultObservable.map(targetResult -> {\n final Id targetId = targetResult.getValue();\n final ConnectionRef ref = new ConnectionRefImpl(sourceId.getType(), sourceId.getUuid(), connectionType, targetId.getType(), targetId.getUuid());\n return new FilterResult<>(ref, Optional.absent());\n });\n }", "pre_mask_code": "package org.apache.usergrid.corepersistence.pipeline.read.collect;\n\nimport org.apache.usergrid.corepersistence.pipeline.read.AbstractFilter;\nimport org.apache.usergrid.corepersistence.pipeline.read.EdgePath;\nimport org.apache.usergrid.corepersistence.pipeline.read.FilterResult;\nimport org.apache.usergrid.persistence.ConnectionRef;\nimport org.apache.usergrid.persistence.cassandra.ConnectionRefImpl;\nimport org.apache.usergrid.persistence.model.entity.Id;\nimport com.google.common.base.Optional;\nimport com.google.inject.Inject;\nimport com.google.inject.assistedinject.Assisted;\nimport rx.Observable;\n\n/**\n * This class only exists for 1.0 compatibility, remove once services no longer need connection refs\n */\npublic class ConnectionRefFilter extends AbstractFilter, FilterResult> {\n\n private final Id sourceId;\n\n private final String connectionType;\n\n @Inject\n public ConnectionRefFilter(@Assisted(\"sourceId\") final Id sourceId, @Assisted(\"connectionType\") final String connectionType) {\n this.sourceId = sourceId;\n this.connectionType = connectionType;\n }\n\n @Override\n public Observable> call(final Observable> filterResultObservable) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2782", "language": "Java", "task_type": "method_signature", "source_file": "java/github/odpi/egeria/open-metadata-implementation/frameworks/governance-action-framework/src/main/java/org/odpi/openmetadata/frameworks/governanceaction/search/SearchClassifications.java", "mask_start_position": 3243, "mask_end_position": 3303, "canonical_solution": "@Override\n public boolean equals(Object objectToCompare) ", "pre_mask_code": "/* Copyright Contributors to the ODPi Egeria project. */\npackage org.odpi.openmetadata.frameworks.governanceaction.search;\n\nimport com.fasterxml.jackson.annotation.JsonAutoDetect;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\nimport static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;\nimport static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;\n\n/**\n * The SearchClassifications class provides support for searching against one or more classifications using a variety of\n * comparison mechanisms.\n */\n@JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class SearchClassifications implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private List conditions;\n\n private MatchCriteria matchCriteria;\n\n public SearchClassifications() {\n super();\n // Setup defaults\n matchCriteria = MatchCriteria.ALL;\n }\n\n /**\n * Copy/clone constructor.\n *\n * @param templateProperties template object to copy.\n */\n public SearchClassifications(SearchClassifications templateProperties) {\n /*\n * An empty properties object is created in the private variable declaration so nothing to do.\n */\n if (templateProperties != null) {\n this.matchCriteria = templateProperties.getMatchCriteria();\n this.conditions = new ArrayList<>();\n this.conditions.addAll(templateProperties.getConditions());\n }\n }\n\n /**\n * Retrieve the classification conditions against which to match.\n *\n * @return {@code List}\n */\n public List getConditions() {\n return conditions;\n }\n\n /**\n * Set the classification conditions against which to match.\n *\n * @param conditions against which to match\n */\n public void setConditions(List conditions) {\n this.conditions = conditions;\n }\n\n /**\n * Retrieve the criteria against which to match the classifications.\n *\n * @return MatchCriteria\n */\n public MatchCriteria getMatchCriteria() {\n return matchCriteria;\n }\n\n /**\n * Set the criteria against which to match the classifications.\n *\n * @param matchCriteria against which to match the classifications\n */\n public void setMatchCriteria(MatchCriteria matchCriteria) {\n this.matchCriteria = matchCriteria;\n }\n\n /**\n * Standard toString method.\n *\n * @return JSON style description of variables.\n */\n @Override\n public String toString() {\n return \"SearchClassifications{\" + \"matchCriteria=\" + matchCriteria + \", conditions=\" + conditions + '}';\n }\n\n /**\n * Validate that an object is equal depending on their stored values.\n *\n * @param objectToCompare object\n * @return boolean result\n */\n ", "post_mask_code": "{\n if (this == objectToCompare) {\n return true;\n }\n if (!(objectToCompare instanceof SearchClassifications)) {\n return false;\n }\n SearchClassifications that = (SearchClassifications) objectToCompare;\n return getMatchCriteria() == that.getMatchCriteria() && Objects.equals(getConditions(), that.getConditions());\n }\n\n /**\n * Return a hash code based on the property values\n *\n * @return int hash code\n */\n @Override\n public int hashCode() {\n return Objects.hash(getMatchCriteria(), getConditions());\n }\n}\n"} {"task_id": "Java_2783", "language": "Java", "task_type": "method_body", "source_file": "java/github/odpi/egeria/open-metadata-implementation/frameworks/governance-action-framework/src/main/java/org/odpi/openmetadata/frameworks/governanceaction/search/SearchClassifications.java", "mask_start_position": 3303, "mask_end_position": 3684, "canonical_solution": "{\n if (this == objectToCompare) {\n return true;\n }\n if (!(objectToCompare instanceof SearchClassifications)) {\n return false;\n }\n SearchClassifications that = (SearchClassifications) objectToCompare;\n return getMatchCriteria() == that.getMatchCriteria() && Objects.equals(getConditions(), that.getConditions());\n }", "pre_mask_code": "/* Copyright Contributors to the ODPi Egeria project. */\npackage org.odpi.openmetadata.frameworks.governanceaction.search;\n\nimport com.fasterxml.jackson.annotation.JsonAutoDetect;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\nimport static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;\nimport static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;\n\n/**\n * The SearchClassifications class provides support for searching against one or more classifications using a variety of\n * comparison mechanisms.\n */\n@JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class SearchClassifications implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private List conditions;\n\n private MatchCriteria matchCriteria;\n\n public SearchClassifications() {\n super();\n // Setup defaults\n matchCriteria = MatchCriteria.ALL;\n }\n\n /**\n * Copy/clone constructor.\n *\n * @param templateProperties template object to copy.\n */\n public SearchClassifications(SearchClassifications templateProperties) {\n /*\n * An empty properties object is created in the private variable declaration so nothing to do.\n */\n if (templateProperties != null) {\n this.matchCriteria = templateProperties.getMatchCriteria();\n this.conditions = new ArrayList<>();\n this.conditions.addAll(templateProperties.getConditions());\n }\n }\n\n /**\n * Retrieve the classification conditions against which to match.\n *\n * @return {@code List}\n */\n public List getConditions() {\n return conditions;\n }\n\n /**\n * Set the classification conditions against which to match.\n *\n * @param conditions against which to match\n */\n public void setConditions(List conditions) {\n this.conditions = conditions;\n }\n\n /**\n * Retrieve the criteria against which to match the classifications.\n *\n * @return MatchCriteria\n */\n public MatchCriteria getMatchCriteria() {\n return matchCriteria;\n }\n\n /**\n * Set the criteria against which to match the classifications.\n *\n * @param matchCriteria against which to match the classifications\n */\n public void setMatchCriteria(MatchCriteria matchCriteria) {\n this.matchCriteria = matchCriteria;\n }\n\n /**\n * Standard toString method.\n *\n * @return JSON style description of variables.\n */\n @Override\n public String toString() {\n return \"SearchClassifications{\" + \"matchCriteria=\" + matchCriteria + \", conditions=\" + conditions + '}';\n }\n\n /**\n * Validate that an object is equal depending on their stored values.\n *\n * @param objectToCompare object\n * @return boolean result\n */\n @Override\n public boolean equals(Object objectToCompare) ", "post_mask_code": "\n\n /**\n * Return a hash code based on the property values\n *\n * @return int hash code\n */\n @Override\n public int hashCode() {\n return Objects.hash(getMatchCriteria(), getConditions());\n }\n}\n"} {"task_id": "Java_2784", "language": "Java", "task_type": "single_line", "source_file": "java/github/odpi/egeria/open-metadata-implementation/frameworks/governance-action-framework/src/main/java/org/odpi/openmetadata/frameworks/governanceaction/search/SearchClassifications.java", "mask_start_position": 3881, "mask_end_position": 3900, "canonical_solution": ", getConditions());", "pre_mask_code": "/* Copyright Contributors to the ODPi Egeria project. */\npackage org.odpi.openmetadata.frameworks.governanceaction.search;\n\nimport com.fasterxml.jackson.annotation.JsonAutoDetect;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\nimport static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;\nimport static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;\n\n/**\n * The SearchClassifications class provides support for searching against one or more classifications using a variety of\n * comparison mechanisms.\n */\n@JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class SearchClassifications implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private List conditions;\n\n private MatchCriteria matchCriteria;\n\n public SearchClassifications() {\n super();\n // Setup defaults\n matchCriteria = MatchCriteria.ALL;\n }\n\n /**\n * Copy/clone constructor.\n *\n * @param templateProperties template object to copy.\n */\n public SearchClassifications(SearchClassifications templateProperties) {\n /*\n * An empty properties object is created in the private variable declaration so nothing to do.\n */\n if (templateProperties != null) {\n this.matchCriteria = templateProperties.getMatchCriteria();\n this.conditions = new ArrayList<>();\n this.conditions.addAll(templateProperties.getConditions());\n }\n }\n\n /**\n * Retrieve the classification conditions against which to match.\n *\n * @return {@code List}\n */\n public List getConditions() {\n return conditions;\n }\n\n /**\n * Set the classification conditions against which to match.\n *\n * @param conditions against which to match\n */\n public void setConditions(List conditions) {\n this.conditions = conditions;\n }\n\n /**\n * Retrieve the criteria against which to match the classifications.\n *\n * @return MatchCriteria\n */\n public MatchCriteria getMatchCriteria() {\n return matchCriteria;\n }\n\n /**\n * Set the criteria against which to match the classifications.\n *\n * @param matchCriteria against which to match the classifications\n */\n public void setMatchCriteria(MatchCriteria matchCriteria) {\n this.matchCriteria = matchCriteria;\n }\n\n /**\n * Standard toString method.\n *\n * @return JSON style description of variables.\n */\n @Override\n public String toString() {\n return \"SearchClassifications{\" + \"matchCriteria=\" + matchCriteria + \", conditions=\" + conditions + '}';\n }\n\n /**\n * Validate that an object is equal depending on their stored values.\n *\n * @param objectToCompare object\n * @return boolean result\n */\n @Override\n public boolean equals(Object objectToCompare) {\n if (this == objectToCompare) {\n return true;\n }\n if (!(objectToCompare instanceof SearchClassifications)) {\n return false;\n }\n SearchClassifications that = (SearchClassifications) objectToCompare;\n return getMatchCriteria() == that.getMatchCriteria() && Objects.equals(getConditions(), that.getConditions());\n }\n\n /**\n * Return a hash code based on the property values\n *\n * @return int hash code\n */\n @Override\n public int hashCode() {\n return Objects.hash(getMatchCriteria()", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2785", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/odpi/egeria/open-metadata-implementation/frameworks/governance-action-framework/src/main/java/org/odpi/openmetadata/frameworks/governanceaction/search/SearchClassifications.java", "mask_start_position": 2202, "mask_end_position": 2315, "canonical_solution": "public void setConditions(List conditions) {\n this.conditions = conditions;\n }", "pre_mask_code": "/* Copyright Contributors to the ODPi Egeria project. */\npackage org.odpi.openmetadata.frameworks.governanceaction.search;\n\nimport com.fasterxml.jackson.annotation.JsonAutoDetect;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\nimport static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;\nimport static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;\n\n/**\n * The SearchClassifications class provides support for searching against one or more classifications using a variety of\n * comparison mechanisms.\n */\n@JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class SearchClassifications implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private List conditions;\n\n private MatchCriteria matchCriteria;\n\n public SearchClassifications() {\n super();\n // Setup defaults\n matchCriteria = MatchCriteria.ALL;\n }\n\n /**\n * Copy/clone constructor.\n *\n * @param templateProperties template object to copy.\n */\n public SearchClassifications(SearchClassifications templateProperties) {\n /*\n * An empty properties object is created in the private variable declaration so nothing to do.\n */\n if (templateProperties != null) {\n this.matchCriteria = templateProperties.getMatchCriteria();\n this.conditions = new ArrayList<>();\n this.conditions.addAll(templateProperties.getConditions());\n }\n }\n\n /**\n * Retrieve the classification conditions against which to match.\n *\n * @return {@code List}\n */\n public List getConditions() {\n return conditions;\n }\n\n /**\n * Set the classification conditions against which to match.\n *\n * @param conditions against which to match\n */\n ", "post_mask_code": "\n\n /**\n * Retrieve the criteria against which to match the classifications.\n *\n * @return MatchCriteria\n */\n public MatchCriteria getMatchCriteria() {\n return matchCriteria;\n }\n\n /**\n * Set the criteria against which to match the classifications.\n *\n * @param matchCriteria against which to match the classifications\n */\n public void setMatchCriteria(MatchCriteria matchCriteria) {\n this.matchCriteria = matchCriteria;\n }\n\n /**\n * Standard toString method.\n *\n * @return JSON style description of variables.\n */\n @Override\n public String toString() {\n return \"SearchClassifications{\" + \"matchCriteria=\" + matchCriteria + \", conditions=\" + conditions + '}';\n }\n\n /**\n * Validate that an object is equal depending on their stored values.\n *\n * @param objectToCompare object\n * @return boolean result\n */\n @Override\n public boolean equals(Object objectToCompare) {\n if (this == objectToCompare) {\n return true;\n }\n if (!(objectToCompare instanceof SearchClassifications)) {\n return false;\n }\n SearchClassifications that = (SearchClassifications) objectToCompare;\n return getMatchCriteria() == that.getMatchCriteria() && Objects.equals(getConditions(), that.getConditions());\n }\n\n /**\n * Return a hash code based on the property values\n *\n * @return int hash code\n */\n @Override\n public int hashCode() {\n return Objects.hash(getMatchCriteria(), getConditions());\n }\n}\n"} {"task_id": "Java_2786", "language": "Java", "task_type": "method_signature", "source_file": "java/github/zolyfarkas/spf4j/spf4j-core/src/main/java/org/spf4j/perf/io/OpenFilesSampler.java", "mask_start_position": 3866, "mask_end_position": 3918, "canonical_solution": "@Deprecated\n public static long getNrOpenFiles() ", "pre_mask_code": "/*\n *\n *\n * Additionally licensed with:\n *\n */\npackage org.spf4j.perf.io;\n\nimport edu.umd.cs.findbugs.annotations.SuppressFBWarnings;\nimport java.time.Instant;\nimport org.spf4j.base.AbstractRunnable;\nimport org.spf4j.concurrent.DefaultScheduler;\nimport org.spf4j.perf.impl.RecorderFactory;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.annotation.Nullable;\nimport org.spf4j.os.OperatingSystem;\nimport org.spf4j.base.Runtime;\nimport org.spf4j.base.SysExits;\nimport org.spf4j.jmx.JmxExport;\nimport org.spf4j.jmx.Registry;\nimport org.spf4j.perf.MeasurementRecorder;\nimport org.spf4j.tsdb2.avro.MeasurementType;\nimport org.spf4j.unix.Lsof;\n\n/**\n * This class allows you to poll and recordAt to a file the heap commitxted and heap used for your java process. start\n * data recording by calling the startMemoryUsageSampling method, stop the data recording by calling the method:\n * startMemoryUsageSampling.\n *\n * @author zoly\n */\npublic final class OpenFilesSampler {\n\n private static ScheduledFuture samplingFuture;\n\n private static AccumulatorRunnable accumulator;\n\n private static volatile CharSequence lastWarnLsof = \"\";\n\n private static volatile Instant lastWarnLsofTime;\n\n static {\n Runtime.queueHook(2, new AbstractRunnable(true) {\n\n @Override\n public void doRun() {\n stop();\n }\n });\n Registry.export(OpenFilesSampler.class);\n }\n\n private OpenFilesSampler() {\n }\n\n public static void start(final long sampleTimeMillis) {\n long maxFileDescriptorCount = OperatingSystem.getMaxFileDescriptorCount();\n start(sampleTimeMillis, maxFileDescriptorCount - maxFileDescriptorCount / 10, maxFileDescriptorCount, true);\n }\n\n @JmxExport\n public static void start(@JmxExport(\"sampleTimeMillis\") final long sampleTimeMillis, @JmxExport(\"shutdownOnError\") final boolean shutdownOnError) {\n long maxFileDescriptorCount = OperatingSystem.getMaxFileDescriptorCount();\n start(sampleTimeMillis, maxFileDescriptorCount - maxFileDescriptorCount / 10, maxFileDescriptorCount, shutdownOnError);\n }\n\n @JmxExport\n public static String getWarnLsofDetail() {\n return lastWarnLsof.toString();\n }\n\n @JmxExport\n @Nullable\n public static synchronized String getWarnLsofTime() {\n Instant lwt = lastWarnLsofTime;\n if (lwt == null) {\n return null;\n } else {\n return lwt.toString();\n }\n }\n\n public static synchronized void start(final long sampleTimeMillis, final long warnThreshold, final long errorThreshold, final boolean shutdownOnError) {\n if (samplingFuture == null) {\n accumulator = new AccumulatorRunnable(errorThreshold, shutdownOnError, warnThreshold, (int) sampleTimeMillis);\n samplingFuture = DefaultScheduler.INSTANCE.scheduleWithFixedDelay(accumulator, sampleTimeMillis, sampleTimeMillis, TimeUnit.MILLISECONDS);\n } else {\n throw new IllegalStateException(\"Open file usage sampling already started \" + samplingFuture);\n }\n }\n\n @JmxExport\n public static synchronized void stop() {\n if (samplingFuture != null) {\n samplingFuture.cancel(false);\n samplingFuture = null;\n accumulator = null;\n }\n }\n\n @JmxExport\n public static synchronized boolean isStarted() {\n return samplingFuture != null;\n }\n\n @JmxExport\n public static String getLsof() {\n CharSequence lsofOutput = Lsof.getLsofOutput();\n return lsofOutput == null ? \"unable to obtain lsof\" : lsofOutput.toString();\n }\n\n @Deprecated\n public static long getMaxNrOpenFiles() {\n return OperatingSystem.getMaxFileDescriptorCount();\n }\n\n ", "post_mask_code": "{\n return OperatingSystem.getOpenFileDescriptorCount();\n }\n\n @JmxExport\n public static long getWarnThreshold() {\n if (accumulator == null) {\n return -1;\n }\n return accumulator.getWarnThreshold();\n }\n\n @JmxExport\n public static long getErrorThreshold() {\n if (accumulator == null) {\n return -1;\n }\n return accumulator.getErrorThreshold();\n }\n\n private static class AccumulatorRunnable extends AbstractRunnable {\n\n private final long errorThreshold;\n\n private final boolean shutdownOnError;\n\n private final long warnThreshold;\n\n private final MeasurementRecorder nrOpenFiles;\n\n AccumulatorRunnable(final long errorThreshold, final boolean shutdownOnError, final long warnThreshold, final int sampleMillis) {\n this.errorThreshold = errorThreshold;\n this.shutdownOnError = shutdownOnError;\n this.warnThreshold = warnThreshold;\n this.nrOpenFiles = RecorderFactory.createDirectRecorder(\"process.nr_open_files\", \"count\", sampleMillis, MeasurementType.GAUGE);\n }\n\n @Override\n @SuppressFBWarnings(\"PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS\")\n public void doRun() {\n long time = System.currentTimeMillis();\n long nrOf = OperatingSystem.getOpenFileDescriptorCount();\n if (nrOf > errorThreshold) {\n lastWarnLsof = Lsof.getLsofOutput();\n lastWarnLsofTime = Instant.now();\n Logger log = Logger.getLogger(OpenFilesSampler.class.getName());\n log.log(Level.SEVERE, \"Nr open files is {0} and exceeds error threshold {1}, detail:\\n{2}\", new Object[] { nrOf, errorThreshold, lastWarnLsof });\n if (shutdownOnError) {\n Runtime.goDownWithError(null, SysExits.EX_IOERR);\n }\n } else if (nrOf > warnThreshold) {\n lastWarnLsof = Lsof.getLsofOutput();\n lastWarnLsofTime = Instant.now();\n Logger log = Logger.getLogger(OpenFilesSampler.class.getName());\n log.log(Level.WARNING, \"Nr open files is {0} and exceeds warn threshold {1}, detail:\\n{2} \", new Object[] { nrOf, warnThreshold, lastWarnLsof });\n if (!Runtime.gc(60000)) {\n log.warning(\"Unable to trigger GC although running low on file resources\");\n } else {\n log.log(Level.WARNING, \"gc executed nr open files reduced by {0} files\", nrOf - OperatingSystem.getOpenFileDescriptorCount());\n }\n }\n this.nrOpenFiles.recordAt(time, nrOf);\n }\n\n public long getErrorThreshold() {\n return errorThreshold;\n }\n\n public boolean isShutdownOnError() {\n return shutdownOnError;\n }\n\n public long getWarnThreshold() {\n return warnThreshold;\n }\n }\n}\n"} {"task_id": "Java_2787", "language": "Java", "task_type": "method_body", "source_file": "java/github/zolyfarkas/spf4j/spf4j-core/src/main/java/org/spf4j/perf/io/OpenFilesSampler.java", "mask_start_position": 4045, "mask_end_position": 4167, "canonical_solution": "{\n if (accumulator == null) {\n return -1;\n }\n return accumulator.getWarnThreshold();\n }", "pre_mask_code": "/*\n *\n *\n * Additionally licensed with:\n *\n */\npackage org.spf4j.perf.io;\n\nimport edu.umd.cs.findbugs.annotations.SuppressFBWarnings;\nimport java.time.Instant;\nimport org.spf4j.base.AbstractRunnable;\nimport org.spf4j.concurrent.DefaultScheduler;\nimport org.spf4j.perf.impl.RecorderFactory;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.annotation.Nullable;\nimport org.spf4j.os.OperatingSystem;\nimport org.spf4j.base.Runtime;\nimport org.spf4j.base.SysExits;\nimport org.spf4j.jmx.JmxExport;\nimport org.spf4j.jmx.Registry;\nimport org.spf4j.perf.MeasurementRecorder;\nimport org.spf4j.tsdb2.avro.MeasurementType;\nimport org.spf4j.unix.Lsof;\n\n/**\n * This class allows you to poll and recordAt to a file the heap commitxted and heap used for your java process. start\n * data recording by calling the startMemoryUsageSampling method, stop the data recording by calling the method:\n * startMemoryUsageSampling.\n *\n * @author zoly\n */\npublic final class OpenFilesSampler {\n\n private static ScheduledFuture samplingFuture;\n\n private static AccumulatorRunnable accumulator;\n\n private static volatile CharSequence lastWarnLsof = \"\";\n\n private static volatile Instant lastWarnLsofTime;\n\n static {\n Runtime.queueHook(2, new AbstractRunnable(true) {\n\n @Override\n public void doRun() {\n stop();\n }\n });\n Registry.export(OpenFilesSampler.class);\n }\n\n private OpenFilesSampler() {\n }\n\n public static void start(final long sampleTimeMillis) {\n long maxFileDescriptorCount = OperatingSystem.getMaxFileDescriptorCount();\n start(sampleTimeMillis, maxFileDescriptorCount - maxFileDescriptorCount / 10, maxFileDescriptorCount, true);\n }\n\n @JmxExport\n public static void start(@JmxExport(\"sampleTimeMillis\") final long sampleTimeMillis, @JmxExport(\"shutdownOnError\") final boolean shutdownOnError) {\n long maxFileDescriptorCount = OperatingSystem.getMaxFileDescriptorCount();\n start(sampleTimeMillis, maxFileDescriptorCount - maxFileDescriptorCount / 10, maxFileDescriptorCount, shutdownOnError);\n }\n\n @JmxExport\n public static String getWarnLsofDetail() {\n return lastWarnLsof.toString();\n }\n\n @JmxExport\n @Nullable\n public static synchronized String getWarnLsofTime() {\n Instant lwt = lastWarnLsofTime;\n if (lwt == null) {\n return null;\n } else {\n return lwt.toString();\n }\n }\n\n public static synchronized void start(final long sampleTimeMillis, final long warnThreshold, final long errorThreshold, final boolean shutdownOnError) {\n if (samplingFuture == null) {\n accumulator = new AccumulatorRunnable(errorThreshold, shutdownOnError, warnThreshold, (int) sampleTimeMillis);\n samplingFuture = DefaultScheduler.INSTANCE.scheduleWithFixedDelay(accumulator, sampleTimeMillis, sampleTimeMillis, TimeUnit.MILLISECONDS);\n } else {\n throw new IllegalStateException(\"Open file usage sampling already started \" + samplingFuture);\n }\n }\n\n @JmxExport\n public static synchronized void stop() {\n if (samplingFuture != null) {\n samplingFuture.cancel(false);\n samplingFuture = null;\n accumulator = null;\n }\n }\n\n @JmxExport\n public static synchronized boolean isStarted() {\n return samplingFuture != null;\n }\n\n @JmxExport\n public static String getLsof() {\n CharSequence lsofOutput = Lsof.getLsofOutput();\n return lsofOutput == null ? \"unable to obtain lsof\" : lsofOutput.toString();\n }\n\n @Deprecated\n public static long getMaxNrOpenFiles() {\n return OperatingSystem.getMaxFileDescriptorCount();\n }\n\n @Deprecated\n public static long getNrOpenFiles() {\n return OperatingSystem.getOpenFileDescriptorCount();\n }\n\n @JmxExport\n public static long getWarnThreshold() ", "post_mask_code": "\n\n @JmxExport\n public static long getErrorThreshold() {\n if (accumulator == null) {\n return -1;\n }\n return accumulator.getErrorThreshold();\n }\n\n private static class AccumulatorRunnable extends AbstractRunnable {\n\n private final long errorThreshold;\n\n private final boolean shutdownOnError;\n\n private final long warnThreshold;\n\n private final MeasurementRecorder nrOpenFiles;\n\n AccumulatorRunnable(final long errorThreshold, final boolean shutdownOnError, final long warnThreshold, final int sampleMillis) {\n this.errorThreshold = errorThreshold;\n this.shutdownOnError = shutdownOnError;\n this.warnThreshold = warnThreshold;\n this.nrOpenFiles = RecorderFactory.createDirectRecorder(\"process.nr_open_files\", \"count\", sampleMillis, MeasurementType.GAUGE);\n }\n\n @Override\n @SuppressFBWarnings(\"PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS\")\n public void doRun() {\n long time = System.currentTimeMillis();\n long nrOf = OperatingSystem.getOpenFileDescriptorCount();\n if (nrOf > errorThreshold) {\n lastWarnLsof = Lsof.getLsofOutput();\n lastWarnLsofTime = Instant.now();\n Logger log = Logger.getLogger(OpenFilesSampler.class.getName());\n log.log(Level.SEVERE, \"Nr open files is {0} and exceeds error threshold {1}, detail:\\n{2}\", new Object[] { nrOf, errorThreshold, lastWarnLsof });\n if (shutdownOnError) {\n Runtime.goDownWithError(null, SysExits.EX_IOERR);\n }\n } else if (nrOf > warnThreshold) {\n lastWarnLsof = Lsof.getLsofOutput();\n lastWarnLsofTime = Instant.now();\n Logger log = Logger.getLogger(OpenFilesSampler.class.getName());\n log.log(Level.WARNING, \"Nr open files is {0} and exceeds warn threshold {1}, detail:\\n{2} \", new Object[] { nrOf, warnThreshold, lastWarnLsof });\n if (!Runtime.gc(60000)) {\n log.warning(\"Unable to trigger GC although running low on file resources\");\n } else {\n log.log(Level.WARNING, \"gc executed nr open files reduced by {0} files\", nrOf - OperatingSystem.getOpenFileDescriptorCount());\n }\n }\n this.nrOpenFiles.recordAt(time, nrOf);\n }\n\n public long getErrorThreshold() {\n return errorThreshold;\n }\n\n public boolean isShutdownOnError() {\n return shutdownOnError;\n }\n\n public long getWarnThreshold() {\n return warnThreshold;\n }\n }\n}\n"} {"task_id": "Java_2788", "language": "Java", "task_type": "single_line", "source_file": "java/github/zolyfarkas/spf4j/spf4j-core/src/main/java/org/spf4j/perf/io/OpenFilesSampler.java", "mask_start_position": 1708, "mask_end_position": 1719, "canonical_solution": "torCount();", "pre_mask_code": "/*\n *\n *\n * Additionally licensed with:\n *\n */\npackage org.spf4j.perf.io;\n\nimport edu.umd.cs.findbugs.annotations.SuppressFBWarnings;\nimport java.time.Instant;\nimport org.spf4j.base.AbstractRunnable;\nimport org.spf4j.concurrent.DefaultScheduler;\nimport org.spf4j.perf.impl.RecorderFactory;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.annotation.Nullable;\nimport org.spf4j.os.OperatingSystem;\nimport org.spf4j.base.Runtime;\nimport org.spf4j.base.SysExits;\nimport org.spf4j.jmx.JmxExport;\nimport org.spf4j.jmx.Registry;\nimport org.spf4j.perf.MeasurementRecorder;\nimport org.spf4j.tsdb2.avro.MeasurementType;\nimport org.spf4j.unix.Lsof;\n\n/**\n * This class allows you to poll and recordAt to a file the heap commitxted and heap used for your java process. start\n * data recording by calling the startMemoryUsageSampling method, stop the data recording by calling the method:\n * startMemoryUsageSampling.\n *\n * @author zoly\n */\npublic final class OpenFilesSampler {\n\n private static ScheduledFuture samplingFuture;\n\n private static AccumulatorRunnable accumulator;\n\n private static volatile CharSequence lastWarnLsof = \"\";\n\n private static volatile Instant lastWarnLsofTime;\n\n static {\n Runtime.queueHook(2, new AbstractRunnable(true) {\n\n @Override\n public void doRun() {\n stop();\n }\n });\n Registry.export(OpenFilesSampler.class);\n }\n\n private OpenFilesSampler() {\n }\n\n public static void start(final long sampleTimeMillis) {\n long maxFileDescriptorCount = OperatingSystem.getMaxFileDescrip", "post_mask_code": "\n start(sampleTimeMillis, maxFileDescriptorCount - maxFileDescriptorCount / 10, maxFileDescriptorCount, true);\n }\n\n @JmxExport\n public static void start(@JmxExport(\"sampleTimeMillis\") final long sampleTimeMillis, @JmxExport(\"shutdownOnError\") final boolean shutdownOnError) {\n long maxFileDescriptorCount = OperatingSystem.getMaxFileDescriptorCount();\n start(sampleTimeMillis, maxFileDescriptorCount - maxFileDescriptorCount / 10, maxFileDescriptorCount, shutdownOnError);\n }\n\n @JmxExport\n public static String getWarnLsofDetail() {\n return lastWarnLsof.toString();\n }\n\n @JmxExport\n @Nullable\n public static synchronized String getWarnLsofTime() {\n Instant lwt = lastWarnLsofTime;\n if (lwt == null) {\n return null;\n } else {\n return lwt.toString();\n }\n }\n\n public static synchronized void start(final long sampleTimeMillis, final long warnThreshold, final long errorThreshold, final boolean shutdownOnError) {\n if (samplingFuture == null) {\n accumulator = new AccumulatorRunnable(errorThreshold, shutdownOnError, warnThreshold, (int) sampleTimeMillis);\n samplingFuture = DefaultScheduler.INSTANCE.scheduleWithFixedDelay(accumulator, sampleTimeMillis, sampleTimeMillis, TimeUnit.MILLISECONDS);\n } else {\n throw new IllegalStateException(\"Open file usage sampling already started \" + samplingFuture);\n }\n }\n\n @JmxExport\n public static synchronized void stop() {\n if (samplingFuture != null) {\n samplingFuture.cancel(false);\n samplingFuture = null;\n accumulator = null;\n }\n }\n\n @JmxExport\n public static synchronized boolean isStarted() {\n return samplingFuture != null;\n }\n\n @JmxExport\n public static String getLsof() {\n CharSequence lsofOutput = Lsof.getLsofOutput();\n return lsofOutput == null ? \"unable to obtain lsof\" : lsofOutput.toString();\n }\n\n @Deprecated\n public static long getMaxNrOpenFiles() {\n return OperatingSystem.getMaxFileDescriptorCount();\n }\n\n @Deprecated\n public static long getNrOpenFiles() {\n return OperatingSystem.getOpenFileDescriptorCount();\n }\n\n @JmxExport\n public static long getWarnThreshold() {\n if (accumulator == null) {\n return -1;\n }\n return accumulator.getWarnThreshold();\n }\n\n @JmxExport\n public static long getErrorThreshold() {\n if (accumulator == null) {\n return -1;\n }\n return accumulator.getErrorThreshold();\n }\n\n private static class AccumulatorRunnable extends AbstractRunnable {\n\n private final long errorThreshold;\n\n private final boolean shutdownOnError;\n\n private final long warnThreshold;\n\n private final MeasurementRecorder nrOpenFiles;\n\n AccumulatorRunnable(final long errorThreshold, final boolean shutdownOnError, final long warnThreshold, final int sampleMillis) {\n this.errorThreshold = errorThreshold;\n this.shutdownOnError = shutdownOnError;\n this.warnThreshold = warnThreshold;\n this.nrOpenFiles = RecorderFactory.createDirectRecorder(\"process.nr_open_files\", \"count\", sampleMillis, MeasurementType.GAUGE);\n }\n\n @Override\n @SuppressFBWarnings(\"PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS\")\n public void doRun() {\n long time = System.currentTimeMillis();\n long nrOf = OperatingSystem.getOpenFileDescriptorCount();\n if (nrOf > errorThreshold) {\n lastWarnLsof = Lsof.getLsofOutput();\n lastWarnLsofTime = Instant.now();\n Logger log = Logger.getLogger(OpenFilesSampler.class.getName());\n log.log(Level.SEVERE, \"Nr open files is {0} and exceeds error threshold {1}, detail:\\n{2}\", new Object[] { nrOf, errorThreshold, lastWarnLsof });\n if (shutdownOnError) {\n Runtime.goDownWithError(null, SysExits.EX_IOERR);\n }\n } else if (nrOf > warnThreshold) {\n lastWarnLsof = Lsof.getLsofOutput();\n lastWarnLsofTime = Instant.now();\n Logger log = Logger.getLogger(OpenFilesSampler.class.getName());\n log.log(Level.WARNING, \"Nr open files is {0} and exceeds warn threshold {1}, detail:\\n{2} \", new Object[] { nrOf, warnThreshold, lastWarnLsof });\n if (!Runtime.gc(60000)) {\n log.warning(\"Unable to trigger GC although running low on file resources\");\n } else {\n log.log(Level.WARNING, \"gc executed nr open files reduced by {0} files\", nrOf - OperatingSystem.getOpenFileDescriptorCount());\n }\n }\n this.nrOpenFiles.recordAt(time, nrOf);\n }\n\n public long getErrorThreshold() {\n return errorThreshold;\n }\n\n public boolean isShutdownOnError() {\n return shutdownOnError;\n }\n\n public long getWarnThreshold() {\n return warnThreshold;\n }\n }\n}\n"} {"task_id": "Java_2789", "language": "Java", "task_type": "method_signature", "source_file": "java/github/baiyuliang/QRobot/app/src/main/java/com/byl/qrobot/bean/Answer.java", "mask_start_position": 1170, "mask_end_position": 1211, "canonical_solution": "public void setJsoninfo(String jsoninfo) ", "pre_mask_code": "package com.byl.qrobot.bean;\n\nimport org.json.JSONObject;\nimport java.util.List;\n\n/**\n * 机器人回答类\n * Created by baiyuliang on 2016-5-12.\n */\npublic class Answer {\n\n // 返回码\n private String code;\n\n // 内容\n private String text;\n\n // 链接\n private String url;\n\n // 新闻列表\n private List listNews;\n\n // 菜谱列表\n private List listCook;\n\n private String jsoninfo;\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public List getListNews() {\n return listNews;\n }\n\n public void setListNews(List listNews) {\n this.listNews = listNews;\n }\n\n public List getListCook() {\n return listCook;\n }\n\n public void setListCook(List listCook) {\n this.listCook = listCook;\n }\n\n public String getJsoninfo() {\n return jsoninfo;\n }\n\n ", "post_mask_code": "{\n this.jsoninfo = jsoninfo;\n }\n}\n"} {"task_id": "Java_2790", "language": "Java", "task_type": "method_body", "source_file": "java/github/baiyuliang/QRobot/app/src/main/java/com/byl/qrobot/bean/Answer.java", "mask_start_position": 550, "mask_end_position": 578, "canonical_solution": "{\n return text;\n }", "pre_mask_code": "package com.byl.qrobot.bean;\n\nimport org.json.JSONObject;\nimport java.util.List;\n\n/**\n * 机器人回答类\n * Created by baiyuliang on 2016-5-12.\n */\npublic class Answer {\n\n // 返回码\n private String code;\n\n // 内容\n private String text;\n\n // 链接\n private String url;\n\n // 新闻列表\n private List listNews;\n\n // 菜谱列表\n private List listCook;\n\n private String jsoninfo;\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getText() ", "post_mask_code": "\n\n public void setText(String text) {\n this.text = text;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public List getListNews() {\n return listNews;\n }\n\n public void setListNews(List listNews) {\n this.listNews = listNews;\n }\n\n public List getListCook() {\n return listCook;\n }\n\n public void setListCook(List listCook) {\n this.listCook = listCook;\n }\n\n public String getJsoninfo() {\n return jsoninfo;\n }\n\n public void setJsoninfo(String jsoninfo) {\n this.jsoninfo = jsoninfo;\n }\n}\n"} {"task_id": "Java_2791", "language": "Java", "task_type": "single_line", "source_file": "java/github/baiyuliang/QRobot/app/src/main/java/com/byl/qrobot/bean/Answer.java", "mask_start_position": 987, "mask_end_position": 1000, "canonical_solution": "urn listCook;", "pre_mask_code": "package com.byl.qrobot.bean;\n\nimport org.json.JSONObject;\nimport java.util.List;\n\n/**\n * 机器人回答类\n * Created by baiyuliang on 2016-5-12.\n */\npublic class Answer {\n\n // 返回码\n private String code;\n\n // 内容\n private String text;\n\n // 链接\n private String url;\n\n // 新闻列表\n private List listNews;\n\n // 菜谱列表\n private List listCook;\n\n private String jsoninfo;\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public List getListNews() {\n return listNews;\n }\n\n public void setListNews(List listNews) {\n this.listNews = listNews;\n }\n\n public List getListCook() {\n ret", "post_mask_code": "\n }\n\n public void setListCook(List listCook) {\n this.listCook = listCook;\n }\n\n public String getJsoninfo() {\n return jsoninfo;\n }\n\n public void setJsoninfo(String jsoninfo) {\n this.jsoninfo = jsoninfo;\n }\n}\n"} {"task_id": "Java_2792", "language": "Java", "task_type": "method_signature", "source_file": "java/github/wildfly/wildfly/ee/src/main/java/org/jboss/as/ee/component/deployers/EEResourceReferenceProcessorRegistry.java", "mask_start_position": 556, "mask_end_position": 666, "canonical_solution": "public void registerResourceReferenceProcessor(final EEResourceReferenceProcessor resourceReferenceProcessor) ", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source.\n * as indicated by the @author tags. See the copyright.txt file in the\n * distribution for a full listing of individual contributors.\n *\n */\npackage org.jboss.as.ee.component.deployers;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport org.jboss.as.ee.logging.EeLogger;\n\npublic class EEResourceReferenceProcessorRegistry {\n\n private final Map resourceReferenceProcessors = new ConcurrentHashMap();\n\n ", "post_mask_code": "{\n if (resourceReferenceProcessor == null) {\n throw EeLogger.ROOT_LOGGER.nullResourceReference();\n }\n final String resourceReferenceType = resourceReferenceProcessor.getResourceReferenceType();\n if (resourceReferenceType == null || resourceReferenceType.trim().isEmpty()) {\n throw EeLogger.ROOT_LOGGER.nullOrEmptyResourceReferenceType();\n }\n resourceReferenceProcessors.put(resourceReferenceType, resourceReferenceProcessor);\n }\n\n public EEResourceReferenceProcessor getResourceReferenceProcessor(final String resourceReferenceType) {\n return resourceReferenceProcessors.get(resourceReferenceType);\n }\n}\n"} {"task_id": "Java_2793", "language": "Java", "task_type": "method_body", "source_file": "java/github/wildfly/wildfly/ee/src/main/java/org/jboss/as/ee/component/deployers/EEResourceReferenceProcessorRegistry.java", "mask_start_position": 1269, "mask_end_position": 1347, "canonical_solution": "{\n return resourceReferenceProcessors.get(resourceReferenceType);\n }", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source.\n * as indicated by the @author tags. See the copyright.txt file in the\n * distribution for a full listing of individual contributors.\n *\n */\npackage org.jboss.as.ee.component.deployers;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport org.jboss.as.ee.logging.EeLogger;\n\npublic class EEResourceReferenceProcessorRegistry {\n\n private final Map resourceReferenceProcessors = new ConcurrentHashMap();\n\n public void registerResourceReferenceProcessor(final EEResourceReferenceProcessor resourceReferenceProcessor) {\n if (resourceReferenceProcessor == null) {\n throw EeLogger.ROOT_LOGGER.nullResourceReference();\n }\n final String resourceReferenceType = resourceReferenceProcessor.getResourceReferenceType();\n if (resourceReferenceType == null || resourceReferenceType.trim().isEmpty()) {\n throw EeLogger.ROOT_LOGGER.nullOrEmptyResourceReferenceType();\n }\n resourceReferenceProcessors.put(resourceReferenceType, resourceReferenceProcessor);\n }\n\n public EEResourceReferenceProcessor getResourceReferenceProcessor(final String resourceReferenceType) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2794", "language": "Java", "task_type": "single_line", "source_file": "java/github/wildfly/wildfly/ee/src/main/java/org/jboss/as/ee/component/deployers/EEResourceReferenceProcessorRegistry.java", "mask_start_position": 1291, "mask_end_position": 1341, "canonical_solution": "rceReferenceProcessors.get(resourceReferenceType);", "pre_mask_code": "/*\n * JBoss, Home of Professional Open Source.\n * as indicated by the @author tags. See the copyright.txt file in the\n * distribution for a full listing of individual contributors.\n *\n */\npackage org.jboss.as.ee.component.deployers;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport org.jboss.as.ee.logging.EeLogger;\n\npublic class EEResourceReferenceProcessorRegistry {\n\n private final Map resourceReferenceProcessors = new ConcurrentHashMap();\n\n public void registerResourceReferenceProcessor(final EEResourceReferenceProcessor resourceReferenceProcessor) {\n if (resourceReferenceProcessor == null) {\n throw EeLogger.ROOT_LOGGER.nullResourceReference();\n }\n final String resourceReferenceType = resourceReferenceProcessor.getResourceReferenceType();\n if (resourceReferenceType == null || resourceReferenceType.trim().isEmpty()) {\n throw EeLogger.ROOT_LOGGER.nullOrEmptyResourceReferenceType();\n }\n resourceReferenceProcessors.put(resourceReferenceType, resourceReferenceProcessor);\n }\n\n public EEResourceReferenceProcessor getResourceReferenceProcessor(final String resourceReferenceType) {\n return resou", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2795", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openhab/openhab-core/bundles/org.openhab.core.io.rest.sitemap/src/main/java/org/openhab/core/io/rest/sitemap/internal/JerseyResponseBuilderUtils.java", "mask_start_position": 1254, "mask_end_position": 1303, "canonical_solution": "public static DTO created(final String location) ", "pre_mask_code": "package org.openhab.core.io.rest.sitemap.internal;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport org.openhab.core.io.rest.sitemap.internal.JerseyResponseBuilderUtils.JerseyResponseBuilderDTO.ContextDTO;\nimport org.openhab.core.io.rest.sitemap.internal.JerseyResponseBuilderUtils.JerseyResponseBuilderDTO.ContextDTO.StreamInfoDTO;\nimport org.osgi.dto.DTO;\n\n/**\n * Data transfer object until UIs are fixed.\n *\n *

\n * {@link http://example.com}\n *\n * @author Markus Rathgeb - Initial contribution\n */\npublic class JerseyResponseBuilderUtils extends DTO {\n\n public static class JerseyResponseBuilderDTO extends DTO {\n\n public static class ContextDTO extends DTO {\n\n public static class StreamInfoDTO extends DTO {\n\n int bufferSize;\n\n boolean directWrite;\n\n boolean isCommitted;\n\n boolean isClosed;\n }\n\n public Map> headers;\n\n public StreamInfoDTO committingOutputStream;\n\n public List entityAnnotations;\n\n public StreamInfoDTO entityStream;\n }\n\n public String status;\n\n public ContextDTO context;\n }\n\n ", "post_mask_code": "{\n JerseyResponseBuilderDTO jrbDTO = new JerseyResponseBuilderDTO();\n jrbDTO.status = \"CREATED\";\n jrbDTO.context = new ContextDTO();\n jrbDTO.context.headers = new HashMap<>();\n jrbDTO.context.headers.put(\"Location\", List.of(location));\n jrbDTO.context.committingOutputStream = new StreamInfoDTO();\n jrbDTO.context.committingOutputStream.bufferSize = 0;\n jrbDTO.context.committingOutputStream.directWrite = true;\n jrbDTO.context.committingOutputStream.isCommitted = false;\n jrbDTO.context.committingOutputStream.isClosed = false;\n jrbDTO.context.entityAnnotations = new ArrayList<>(0);\n jrbDTO.context.entityStream = new StreamInfoDTO();\n jrbDTO.context.entityStream.bufferSize = 0;\n jrbDTO.context.entityStream.directWrite = true;\n jrbDTO.context.entityStream.isCommitted = false;\n jrbDTO.context.entityStream.isClosed = false;\n return jrbDTO;\n }\n}\n"} {"task_id": "Java_2796", "language": "Java", "task_type": "single_line", "source_file": "java/github/openhab/openhab-core/bundles/org.openhab.core.io.rest.sitemap/src/main/java/org/openhab/core/io/rest/sitemap/internal/JerseyResponseBuilderUtils.java", "mask_start_position": 1410, "mask_end_position": 1413, "canonical_solution": "D\";", "pre_mask_code": "package org.openhab.core.io.rest.sitemap.internal;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport org.openhab.core.io.rest.sitemap.internal.JerseyResponseBuilderUtils.JerseyResponseBuilderDTO.ContextDTO;\nimport org.openhab.core.io.rest.sitemap.internal.JerseyResponseBuilderUtils.JerseyResponseBuilderDTO.ContextDTO.StreamInfoDTO;\nimport org.osgi.dto.DTO;\n\n/**\n * Data transfer object until UIs are fixed.\n *\n *

\n * {@link http://example.com}\n *\n * @author Markus Rathgeb - Initial contribution\n */\npublic class JerseyResponseBuilderUtils extends DTO {\n\n public static class JerseyResponseBuilderDTO extends DTO {\n\n public static class ContextDTO extends DTO {\n\n public static class StreamInfoDTO extends DTO {\n\n int bufferSize;\n\n boolean directWrite;\n\n boolean isCommitted;\n\n boolean isClosed;\n }\n\n public Map> headers;\n\n public StreamInfoDTO committingOutputStream;\n\n public List entityAnnotations;\n\n public StreamInfoDTO entityStream;\n }\n\n public String status;\n\n public ContextDTO context;\n }\n\n public static DTO created(final String location) {\n JerseyResponseBuilderDTO jrbDTO = new JerseyResponseBuilderDTO();\n jrbDTO.status = \"CREATE", "post_mask_code": "\n jrbDTO.context = new ContextDTO();\n jrbDTO.context.headers = new HashMap<>();\n jrbDTO.context.headers.put(\"Location\", List.of(location));\n jrbDTO.context.committingOutputStream = new StreamInfoDTO();\n jrbDTO.context.committingOutputStream.bufferSize = 0;\n jrbDTO.context.committingOutputStream.directWrite = true;\n jrbDTO.context.committingOutputStream.isCommitted = false;\n jrbDTO.context.committingOutputStream.isClosed = false;\n jrbDTO.context.entityAnnotations = new ArrayList<>(0);\n jrbDTO.context.entityStream = new StreamInfoDTO();\n jrbDTO.context.entityStream.bufferSize = 0;\n jrbDTO.context.entityStream.directWrite = true;\n jrbDTO.context.entityStream.isCommitted = false;\n jrbDTO.context.entityStream.isClosed = false;\n return jrbDTO;\n }\n}\n"} {"task_id": "Java_2797", "language": "Java", "task_type": "method_signature", "source_file": "java/github/glyptodon/guacamole-client/extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/connection/ModeledConnectionRecord.java", "mask_start_position": 1256, "mask_end_position": 1308, "canonical_solution": "@Override\n public String getSharingProfileName() ", "pre_mask_code": "package org.apache.guacamole.auth.jdbc.connection;\n\nimport org.apache.guacamole.auth.jdbc.base.ModeledActivityRecord;\nimport org.apache.guacamole.net.auth.ConnectionRecord;\n\n/**\n * A ConnectionRecord which is backed by a database model.\n */\npublic class ModeledConnectionRecord extends ModeledActivityRecord implements ConnectionRecord {\n\n /**\n * The model object backing this connection record.\n */\n private final ConnectionRecordModel model;\n\n /**\n * Creates a new ModeledConnectionRecord backed by the given model object.\n * Changes to this record will affect the backing model object, and changes\n * to the backing model object will affect this record.\n *\n * @param model\n * The model object to use to back this connection record.\n */\n public ModeledConnectionRecord(ConnectionRecordModel model) {\n super(model);\n this.model = model;\n }\n\n @Override\n public String getConnectionIdentifier() {\n return model.getConnectionIdentifier();\n }\n\n @Override\n public String getConnectionName() {\n return model.getConnectionName();\n }\n\n @Override\n public String getSharingProfileIdentifier() {\n return model.getSharingProfileIdentifier();\n }\n\n ", "post_mask_code": "{\n return model.getSharingProfileName();\n }\n}\n"} {"task_id": "Java_2798", "language": "Java", "task_type": "method_body", "source_file": "java/github/glyptodon/guacamole-client/extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/connection/ModeledConnectionRecord.java", "mask_start_position": 1308, "mask_end_position": 1361, "canonical_solution": "{\n return model.getSharingProfileName();\n }", "pre_mask_code": "package org.apache.guacamole.auth.jdbc.connection;\n\nimport org.apache.guacamole.auth.jdbc.base.ModeledActivityRecord;\nimport org.apache.guacamole.net.auth.ConnectionRecord;\n\n/**\n * A ConnectionRecord which is backed by a database model.\n */\npublic class ModeledConnectionRecord extends ModeledActivityRecord implements ConnectionRecord {\n\n /**\n * The model object backing this connection record.\n */\n private final ConnectionRecordModel model;\n\n /**\n * Creates a new ModeledConnectionRecord backed by the given model object.\n * Changes to this record will affect the backing model object, and changes\n * to the backing model object will affect this record.\n *\n * @param model\n * The model object to use to back this connection record.\n */\n public ModeledConnectionRecord(ConnectionRecordModel model) {\n super(model);\n this.model = model;\n }\n\n @Override\n public String getConnectionIdentifier() {\n return model.getConnectionIdentifier();\n }\n\n @Override\n public String getConnectionName() {\n return model.getConnectionName();\n }\n\n @Override\n public String getSharingProfileIdentifier() {\n return model.getSharingProfileIdentifier();\n }\n\n @Override\n public String getSharingProfileName() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2799", "language": "Java", "task_type": "single_line", "source_file": "java/github/glyptodon/guacamole-client/extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/connection/ModeledConnectionRecord.java", "mask_start_position": 982, "mask_end_position": 1018, "canonical_solution": "urn model.getConnectionIdentifier();", "pre_mask_code": "package org.apache.guacamole.auth.jdbc.connection;\n\nimport org.apache.guacamole.auth.jdbc.base.ModeledActivityRecord;\nimport org.apache.guacamole.net.auth.ConnectionRecord;\n\n/**\n * A ConnectionRecord which is backed by a database model.\n */\npublic class ModeledConnectionRecord extends ModeledActivityRecord implements ConnectionRecord {\n\n /**\n * The model object backing this connection record.\n */\n private final ConnectionRecordModel model;\n\n /**\n * Creates a new ModeledConnectionRecord backed by the given model object.\n * Changes to this record will affect the backing model object, and changes\n * to the backing model object will affect this record.\n *\n * @param model\n * The model object to use to back this connection record.\n */\n public ModeledConnectionRecord(ConnectionRecordModel model) {\n super(model);\n this.model = model;\n }\n\n @Override\n public String getConnectionIdentifier() {\n ret", "post_mask_code": "\n }\n\n @Override\n public String getConnectionName() {\n return model.getConnectionName();\n }\n\n @Override\n public String getSharingProfileIdentifier() {\n return model.getSharingProfileIdentifier();\n }\n\n @Override\n public String getSharingProfileName() {\n return model.getSharingProfileName();\n }\n}\n"} {"task_id": "Java_2800", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse-ee4j/jersey/core-server/src/main/java/org/glassfish/jersey/server/wadl/processor/WadlModelProcessor.java", "mask_start_position": 3497, "mask_end_position": 3586, "canonical_solution": "@Override\n public Response apply(ContainerRequestContext containerRequestContext) ", "pre_mask_code": "package org.glassfish.jersey.server.wadl.processor;\n\nimport java.io.ByteArrayOutputStream;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport javax.ws.rs.HttpMethod;\nimport javax.ws.rs.ProcessingException;\nimport javax.ws.rs.container.ContainerRequestContext;\nimport javax.ws.rs.core.Configuration;\nimport javax.ws.rs.core.Context;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.UriInfo;\nimport javax.annotation.Priority;\nimport javax.inject.Inject;\nimport javax.inject.Provider;\nimport javax.xml.bind.Marshaller;\nimport org.glassfish.jersey.internal.util.PropertiesHelper;\nimport org.glassfish.jersey.message.internal.MediaTypes;\nimport org.glassfish.jersey.process.Inflector;\nimport org.glassfish.jersey.server.ExtendedUriInfo;\nimport org.glassfish.jersey.server.ServerProperties;\nimport org.glassfish.jersey.server.model.ModelProcessor;\nimport org.glassfish.jersey.server.model.Resource;\nimport org.glassfish.jersey.server.model.ResourceModel;\nimport org.glassfish.jersey.server.model.RuntimeResource;\nimport org.glassfish.jersey.server.model.internal.ModelProcessorUtil;\nimport org.glassfish.jersey.server.wadl.WadlApplicationContext;\nimport org.glassfish.jersey.server.wadl.internal.WadlResource;\nimport org.glassfish.jersey.server.wadl.internal.WadlUtils;\nimport com.sun.research.ws.wadl.Application;\n\n/**\n * WADL {@link ModelProcessor model processor} which enhance resource model by WADL related resources (like \"/application.wadl\").\n * The provider should be registered using\n * {@link org.glassfish.jersey.server.wadl.internal.WadlAutoDiscoverable} or by\n * {@link org.glassfish.jersey.server.wadl.WadlFeature} if auto-discovery is disabled.\n *\n * @author Miroslav Fuksa\n */\n@Priority(10000)\npublic class WadlModelProcessor implements ModelProcessor {\n\n private final List methodList;\n\n /**\n * Create new WADL model processor instance.\n */\n public WadlModelProcessor() {\n methodList = new ArrayList<>();\n methodList.add(new ModelProcessorUtil.Method(HttpMethod.OPTIONS, MediaType.WILDCARD_TYPE, MediaTypes.WADL_TYPE, OptionsHandler.class));\n }\n\n @Override\n public ResourceModel processResourceModel(final ResourceModel resourceModel, final Configuration configuration) {\n final boolean disabled = PropertiesHelper.isProperty(configuration.getProperty(ServerProperties.WADL_FEATURE_DISABLE));\n if (disabled) {\n return resourceModel;\n }\n final ResourceModel.Builder builder = ModelProcessorUtil.enhanceResourceModel(resourceModel, false, methodList, true);\n // Do not add WadlResource if already present in the classes (i.e. added during scanning).\n if (!configuration.getClasses().contains(WadlResource.class)) {\n final Resource wadlResource = Resource.builder(WadlResource.class).build();\n builder.addResource(wadlResource);\n }\n return builder.build();\n }\n\n /**\n * OPTIONS resource method handler that serves resource WADL.\n */\n public static class OptionsHandler implements Inflector {\n\n private final String lastModified = new SimpleDateFormat(WadlResource.HTTPDATEFORMAT).format(new Date());\n\n @Inject\n private Provider extendedUriInfo;\n\n @Context\n private WadlApplicationContext wadlApplicationContext;\n\n ", "post_mask_code": "{\n final RuntimeResource resource = extendedUriInfo.get().getMatchedRuntimeResources().get(0);\n // TODO: support multiple resources, see ignored tests in WadlResourceTest.Wadl8Test\n final UriInfo uriInfo = containerRequestContext.getUriInfo();\n final Application wadlApplication = wadlApplicationContext.getApplication(uriInfo, resource.getResources().get(0), WadlUtils.isDetailedWadlRequested(uriInfo));\n if (wadlApplication == null) {\n // wadlApplication can be null if limited WADL is requested and all content\n // of wadlApplication is invisible in limited WADL\n return Response.status(Response.Status.NOT_FOUND).build();\n }\n byte[] bytes;\n try {\n final Marshaller marshaller = wadlApplicationContext.getJAXBContext().createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);\n final ByteArrayOutputStream os = new ByteArrayOutputStream();\n marshaller.marshal(wadlApplication, os);\n bytes = os.toByteArray();\n os.close();\n } catch (Exception e) {\n throw new ProcessingException(\"Could not marshal the wadl Application.\", e);\n }\n return Response.ok().type(MediaTypes.WADL_TYPE).allow(ModelProcessorUtil.getAllowedMethods(resource)).header(\"Last-modified\", lastModified).entity(bytes).build();\n }\n }\n\n @Override\n public ResourceModel processSubResource(ResourceModel resourceModel, Configuration configuration) {\n final boolean disabled = PropertiesHelper.isProperty(configuration.getProperty(ServerProperties.WADL_FEATURE_DISABLE));\n if (disabled) {\n return resourceModel;\n }\n return ModelProcessorUtil.enhanceResourceModel(resourceModel, true, methodList, true).build();\n }\n}\n"} {"task_id": "Java_2801", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse-ee4j/jersey/core-server/src/main/java/org/glassfish/jersey/server/wadl/processor/WadlModelProcessor.java", "mask_start_position": 5212, "mask_end_position": 5518, "canonical_solution": "{\n final boolean disabled = PropertiesHelper.isProperty(configuration.getProperty(ServerProperties.WADL_FEATURE_DISABLE));\n if (disabled) {\n return resourceModel;\n }\n return ModelProcessorUtil.enhanceResourceModel(resourceModel, true, methodList, true).build();\n }", "pre_mask_code": "package org.glassfish.jersey.server.wadl.processor;\n\nimport java.io.ByteArrayOutputStream;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport javax.ws.rs.HttpMethod;\nimport javax.ws.rs.ProcessingException;\nimport javax.ws.rs.container.ContainerRequestContext;\nimport javax.ws.rs.core.Configuration;\nimport javax.ws.rs.core.Context;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.UriInfo;\nimport javax.annotation.Priority;\nimport javax.inject.Inject;\nimport javax.inject.Provider;\nimport javax.xml.bind.Marshaller;\nimport org.glassfish.jersey.internal.util.PropertiesHelper;\nimport org.glassfish.jersey.message.internal.MediaTypes;\nimport org.glassfish.jersey.process.Inflector;\nimport org.glassfish.jersey.server.ExtendedUriInfo;\nimport org.glassfish.jersey.server.ServerProperties;\nimport org.glassfish.jersey.server.model.ModelProcessor;\nimport org.glassfish.jersey.server.model.Resource;\nimport org.glassfish.jersey.server.model.ResourceModel;\nimport org.glassfish.jersey.server.model.RuntimeResource;\nimport org.glassfish.jersey.server.model.internal.ModelProcessorUtil;\nimport org.glassfish.jersey.server.wadl.WadlApplicationContext;\nimport org.glassfish.jersey.server.wadl.internal.WadlResource;\nimport org.glassfish.jersey.server.wadl.internal.WadlUtils;\nimport com.sun.research.ws.wadl.Application;\n\n/**\n * WADL {@link ModelProcessor model processor} which enhance resource model by WADL related resources (like \"/application.wadl\").\n * The provider should be registered using\n * {@link org.glassfish.jersey.server.wadl.internal.WadlAutoDiscoverable} or by\n * {@link org.glassfish.jersey.server.wadl.WadlFeature} if auto-discovery is disabled.\n *\n * @author Miroslav Fuksa\n */\n@Priority(10000)\npublic class WadlModelProcessor implements ModelProcessor {\n\n private final List methodList;\n\n /**\n * Create new WADL model processor instance.\n */\n public WadlModelProcessor() {\n methodList = new ArrayList<>();\n methodList.add(new ModelProcessorUtil.Method(HttpMethod.OPTIONS, MediaType.WILDCARD_TYPE, MediaTypes.WADL_TYPE, OptionsHandler.class));\n }\n\n @Override\n public ResourceModel processResourceModel(final ResourceModel resourceModel, final Configuration configuration) {\n final boolean disabled = PropertiesHelper.isProperty(configuration.getProperty(ServerProperties.WADL_FEATURE_DISABLE));\n if (disabled) {\n return resourceModel;\n }\n final ResourceModel.Builder builder = ModelProcessorUtil.enhanceResourceModel(resourceModel, false, methodList, true);\n // Do not add WadlResource if already present in the classes (i.e. added during scanning).\n if (!configuration.getClasses().contains(WadlResource.class)) {\n final Resource wadlResource = Resource.builder(WadlResource.class).build();\n builder.addResource(wadlResource);\n }\n return builder.build();\n }\n\n /**\n * OPTIONS resource method handler that serves resource WADL.\n */\n public static class OptionsHandler implements Inflector {\n\n private final String lastModified = new SimpleDateFormat(WadlResource.HTTPDATEFORMAT).format(new Date());\n\n @Inject\n private Provider extendedUriInfo;\n\n @Context\n private WadlApplicationContext wadlApplicationContext;\n\n @Override\n public Response apply(ContainerRequestContext containerRequestContext) {\n final RuntimeResource resource = extendedUriInfo.get().getMatchedRuntimeResources().get(0);\n // TODO: support multiple resources, see ignored tests in WadlResourceTest.Wadl8Test\n final UriInfo uriInfo = containerRequestContext.getUriInfo();\n final Application wadlApplication = wadlApplicationContext.getApplication(uriInfo, resource.getResources().get(0), WadlUtils.isDetailedWadlRequested(uriInfo));\n if (wadlApplication == null) {\n // wadlApplication can be null if limited WADL is requested and all content\n // of wadlApplication is invisible in limited WADL\n return Response.status(Response.Status.NOT_FOUND).build();\n }\n byte[] bytes;\n try {\n final Marshaller marshaller = wadlApplicationContext.getJAXBContext().createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);\n final ByteArrayOutputStream os = new ByteArrayOutputStream();\n marshaller.marshal(wadlApplication, os);\n bytes = os.toByteArray();\n os.close();\n } catch (Exception e) {\n throw new ProcessingException(\"Could not marshal the wadl Application.\", e);\n }\n return Response.ok().type(MediaTypes.WADL_TYPE).allow(ModelProcessorUtil.getAllowedMethods(resource)).header(\"Last-modified\", lastModified).entity(bytes).build();\n }\n }\n\n @Override\n public ResourceModel processSubResource(ResourceModel resourceModel, Configuration configuration) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2802", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse-ee4j/jersey/core-server/src/main/java/org/glassfish/jersey/server/wadl/processor/WadlModelProcessor.java", "mask_start_position": 4347, "mask_end_position": 4351, "canonical_solution": "tes;", "pre_mask_code": "package org.glassfish.jersey.server.wadl.processor;\n\nimport java.io.ByteArrayOutputStream;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport javax.ws.rs.HttpMethod;\nimport javax.ws.rs.ProcessingException;\nimport javax.ws.rs.container.ContainerRequestContext;\nimport javax.ws.rs.core.Configuration;\nimport javax.ws.rs.core.Context;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.UriInfo;\nimport javax.annotation.Priority;\nimport javax.inject.Inject;\nimport javax.inject.Provider;\nimport javax.xml.bind.Marshaller;\nimport org.glassfish.jersey.internal.util.PropertiesHelper;\nimport org.glassfish.jersey.message.internal.MediaTypes;\nimport org.glassfish.jersey.process.Inflector;\nimport org.glassfish.jersey.server.ExtendedUriInfo;\nimport org.glassfish.jersey.server.ServerProperties;\nimport org.glassfish.jersey.server.model.ModelProcessor;\nimport org.glassfish.jersey.server.model.Resource;\nimport org.glassfish.jersey.server.model.ResourceModel;\nimport org.glassfish.jersey.server.model.RuntimeResource;\nimport org.glassfish.jersey.server.model.internal.ModelProcessorUtil;\nimport org.glassfish.jersey.server.wadl.WadlApplicationContext;\nimport org.glassfish.jersey.server.wadl.internal.WadlResource;\nimport org.glassfish.jersey.server.wadl.internal.WadlUtils;\nimport com.sun.research.ws.wadl.Application;\n\n/**\n * WADL {@link ModelProcessor model processor} which enhance resource model by WADL related resources (like \"/application.wadl\").\n * The provider should be registered using\n * {@link org.glassfish.jersey.server.wadl.internal.WadlAutoDiscoverable} or by\n * {@link org.glassfish.jersey.server.wadl.WadlFeature} if auto-discovery is disabled.\n *\n * @author Miroslav Fuksa\n */\n@Priority(10000)\npublic class WadlModelProcessor implements ModelProcessor {\n\n private final List methodList;\n\n /**\n * Create new WADL model processor instance.\n */\n public WadlModelProcessor() {\n methodList = new ArrayList<>();\n methodList.add(new ModelProcessorUtil.Method(HttpMethod.OPTIONS, MediaType.WILDCARD_TYPE, MediaTypes.WADL_TYPE, OptionsHandler.class));\n }\n\n @Override\n public ResourceModel processResourceModel(final ResourceModel resourceModel, final Configuration configuration) {\n final boolean disabled = PropertiesHelper.isProperty(configuration.getProperty(ServerProperties.WADL_FEATURE_DISABLE));\n if (disabled) {\n return resourceModel;\n }\n final ResourceModel.Builder builder = ModelProcessorUtil.enhanceResourceModel(resourceModel, false, methodList, true);\n // Do not add WadlResource if already present in the classes (i.e. added during scanning).\n if (!configuration.getClasses().contains(WadlResource.class)) {\n final Resource wadlResource = Resource.builder(WadlResource.class).build();\n builder.addResource(wadlResource);\n }\n return builder.build();\n }\n\n /**\n * OPTIONS resource method handler that serves resource WADL.\n */\n public static class OptionsHandler implements Inflector {\n\n private final String lastModified = new SimpleDateFormat(WadlResource.HTTPDATEFORMAT).format(new Date());\n\n @Inject\n private Provider extendedUriInfo;\n\n @Context\n private WadlApplicationContext wadlApplicationContext;\n\n @Override\n public Response apply(ContainerRequestContext containerRequestContext) {\n final RuntimeResource resource = extendedUriInfo.get().getMatchedRuntimeResources().get(0);\n // TODO: support multiple resources, see ignored tests in WadlResourceTest.Wadl8Test\n final UriInfo uriInfo = containerRequestContext.getUriInfo();\n final Application wadlApplication = wadlApplicationContext.getApplication(uriInfo, resource.getResources().get(0), WadlUtils.isDetailedWadlRequested(uriInfo));\n if (wadlApplication == null) {\n // wadlApplication can be null if limited WADL is requested and all content\n // of wadlApplication is invisible in limited WADL\n return Response.status(Response.Status.NOT_FOUND).build();\n }\n byte[] by", "post_mask_code": "\n try {\n final Marshaller marshaller = wadlApplicationContext.getJAXBContext().createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);\n final ByteArrayOutputStream os = new ByteArrayOutputStream();\n marshaller.marshal(wadlApplication, os);\n bytes = os.toByteArray();\n os.close();\n } catch (Exception e) {\n throw new ProcessingException(\"Could not marshal the wadl Application.\", e);\n }\n return Response.ok().type(MediaTypes.WADL_TYPE).allow(ModelProcessorUtil.getAllowedMethods(resource)).header(\"Last-modified\", lastModified).entity(bytes).build();\n }\n }\n\n @Override\n public ResourceModel processSubResource(ResourceModel resourceModel, Configuration configuration) {\n final boolean disabled = PropertiesHelper.isProperty(configuration.getProperty(ServerProperties.WADL_FEATURE_DISABLE));\n if (disabled) {\n return resourceModel;\n }\n return ModelProcessorUtil.enhanceResourceModel(resourceModel, true, methodList, true).build();\n }\n}\n"} {"task_id": "Java_2803", "language": "Java", "task_type": "method_signature", "source_file": "java/github/dmolony/dm3270/src/com/bytezone/dm3270/extended/ResponseCommand.java", "mask_start_position": 420, "mask_end_position": 458, "canonical_solution": "@Override\n public String getName() ", "pre_mask_code": "package com.bytezone.dm3270.extended;\n\nimport com.bytezone.dm3270.utilities.Dm3270Utility;\n\npublic class ResponseCommand extends AbstractExtendedCommand {\n\n public ResponseCommand(CommandHeader commandHeader, byte[] buffer, int offset, int length) {\n super(commandHeader, buffer, offset, length);\n if (length != 1)\n System.out.println(Dm3270Utility.toHex(buffer, offset, length));\n }\n\n ", "post_mask_code": "{\n return \"Response\";\n }\n\n @Override\n public String toString() {\n return String.format(\"Rsp: %02X\", data[0]);\n }\n}\n"} {"task_id": "Java_2804", "language": "Java", "task_type": "method_body", "source_file": "java/github/dmolony/dm3270/src/com/bytezone/dm3270/extended/ResponseCommand.java", "mask_start_position": 458, "mask_end_position": 492, "canonical_solution": "{\n return \"Response\";\n }", "pre_mask_code": "package com.bytezone.dm3270.extended;\n\nimport com.bytezone.dm3270.utilities.Dm3270Utility;\n\npublic class ResponseCommand extends AbstractExtendedCommand {\n\n public ResponseCommand(CommandHeader commandHeader, byte[] buffer, int offset, int length) {\n super(commandHeader, buffer, offset, length);\n if (length != 1)\n System.out.println(Dm3270Utility.toHex(buffer, offset, length));\n }\n\n @Override\n public String getName() ", "post_mask_code": "\n\n @Override\n public String toString() {\n return String.format(\"Rsp: %02X\", data[0]);\n }\n}\n"} {"task_id": "Java_2805", "language": "Java", "task_type": "single_line", "source_file": "java/github/dmolony/dm3270/src/com/bytezone/dm3270/extended/ResponseCommand.java", "mask_start_position": 585, "mask_end_position": 590, "canonical_solution": "[0]);", "pre_mask_code": "package com.bytezone.dm3270.extended;\n\nimport com.bytezone.dm3270.utilities.Dm3270Utility;\n\npublic class ResponseCommand extends AbstractExtendedCommand {\n\n public ResponseCommand(CommandHeader commandHeader, byte[] buffer, int offset, int length) {\n super(commandHeader, buffer, offset, length);\n if (length != 1)\n System.out.println(Dm3270Utility.toHex(buffer, offset, length));\n }\n\n @Override\n public String getName() {\n return \"Response\";\n }\n\n @Override\n public String toString() {\n return String.format(\"Rsp: %02X\", data", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2806", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SerNet/verinice/sernet.gs.ui.rcp.main/src/sernet/verinice/rcp/search/tables/TableMenuListener.java", "mask_start_position": 1439, "mask_end_position": 1496, "canonical_solution": "private boolean hasNoColumnEntries(IMenuManager manager) ", "pre_mask_code": "package sernet.verinice.rcp.search.tables;\n\nimport org.eclipse.jface.action.Action;\nimport org.eclipse.jface.action.IMenuListener;\nimport org.eclipse.jface.action.IMenuManager;\nimport org.eclipse.jface.action.Separator;\nimport sernet.verinice.model.search.VeriniceSearchResultTable;\nimport sernet.verinice.rcp.search.Messages;\nimport sernet.verinice.rcp.search.SearchView;\nimport sernet.verinice.rcp.search.column.ColumnStoreFactory;\nimport sernet.verinice.rcp.search.column.IColumn;\nimport sernet.verinice.rcp.search.column.IColumnStore;\n\npublic class TableMenuListener implements IMenuListener {\n\n private final SearchView searchView;\n\n private IColumnStore columnStore;\n\n private VeriniceSearchResultTable vSearchResultObject;\n\n public TableMenuListener(SearchView searchView, VeriniceSearchResultTable vSearchResultObject) {\n this.searchView = searchView;\n columnStore = ColumnStoreFactory.getColumnStore(vSearchResultObject.getEntityTypeId());\n this.vSearchResultObject = vSearchResultObject;\n }\n\n @Override\n public void menuAboutToShow(IMenuManager manager) {\n if (hasNoColumnEntries(manager)) {\n for (IColumn col : columnStore.getAllColumns()) {\n manager.add(new ColumnContribution(this.searchView, col, vSearchResultObject));\n }\n manager.add(new Separator());\n manager.add(new RestoreDefaultAction());\n }\n }\n\n ", "post_mask_code": "{\n return manager.getItems() != null && manager.getItems().length == 0;\n }\n\n private class RestoreDefaultAction extends Action {\n\n public RestoreDefaultAction() {\n setText(Messages.SearchView_6);\n setToolTipText(Messages.SearchView_6);\n }\n\n @Override\n public void run() {\n columnStore.restoreDefault();\n searchView.setTableViewer(vSearchResultObject);\n }\n }\n}\n"} {"task_id": "Java_2807", "language": "Java", "task_type": "method_body", "source_file": "java/github/SerNet/verinice/sernet.gs.ui.rcp.main/src/sernet/verinice/rcp/search/tables/TableMenuListener.java", "mask_start_position": 1496, "mask_end_position": 1580, "canonical_solution": "{\n return manager.getItems() != null && manager.getItems().length == 0;\n }", "pre_mask_code": "package sernet.verinice.rcp.search.tables;\n\nimport org.eclipse.jface.action.Action;\nimport org.eclipse.jface.action.IMenuListener;\nimport org.eclipse.jface.action.IMenuManager;\nimport org.eclipse.jface.action.Separator;\nimport sernet.verinice.model.search.VeriniceSearchResultTable;\nimport sernet.verinice.rcp.search.Messages;\nimport sernet.verinice.rcp.search.SearchView;\nimport sernet.verinice.rcp.search.column.ColumnStoreFactory;\nimport sernet.verinice.rcp.search.column.IColumn;\nimport sernet.verinice.rcp.search.column.IColumnStore;\n\npublic class TableMenuListener implements IMenuListener {\n\n private final SearchView searchView;\n\n private IColumnStore columnStore;\n\n private VeriniceSearchResultTable vSearchResultObject;\n\n public TableMenuListener(SearchView searchView, VeriniceSearchResultTable vSearchResultObject) {\n this.searchView = searchView;\n columnStore = ColumnStoreFactory.getColumnStore(vSearchResultObject.getEntityTypeId());\n this.vSearchResultObject = vSearchResultObject;\n }\n\n @Override\n public void menuAboutToShow(IMenuManager manager) {\n if (hasNoColumnEntries(manager)) {\n for (IColumn col : columnStore.getAllColumns()) {\n manager.add(new ColumnContribution(this.searchView, col, vSearchResultObject));\n }\n manager.add(new Separator());\n manager.add(new RestoreDefaultAction());\n }\n }\n\n private boolean hasNoColumnEntries(IMenuManager manager) ", "post_mask_code": "\n\n private class RestoreDefaultAction extends Action {\n\n public RestoreDefaultAction() {\n setText(Messages.SearchView_6);\n setToolTipText(Messages.SearchView_6);\n }\n\n @Override\n public void run() {\n columnStore.restoreDefault();\n searchView.setTableViewer(vSearchResultObject);\n }\n }\n}\n"} {"task_id": "Java_2808", "language": "Java", "task_type": "single_line", "source_file": "java/github/SerNet/verinice/sernet.gs.ui.rcp.main/src/sernet/verinice/rcp/search/tables/TableMenuListener.java", "mask_start_position": 1870, "mask_end_position": 1872, "canonical_solution": ");", "pre_mask_code": "package sernet.verinice.rcp.search.tables;\n\nimport org.eclipse.jface.action.Action;\nimport org.eclipse.jface.action.IMenuListener;\nimport org.eclipse.jface.action.IMenuManager;\nimport org.eclipse.jface.action.Separator;\nimport sernet.verinice.model.search.VeriniceSearchResultTable;\nimport sernet.verinice.rcp.search.Messages;\nimport sernet.verinice.rcp.search.SearchView;\nimport sernet.verinice.rcp.search.column.ColumnStoreFactory;\nimport sernet.verinice.rcp.search.column.IColumn;\nimport sernet.verinice.rcp.search.column.IColumnStore;\n\npublic class TableMenuListener implements IMenuListener {\n\n private final SearchView searchView;\n\n private IColumnStore columnStore;\n\n private VeriniceSearchResultTable vSearchResultObject;\n\n public TableMenuListener(SearchView searchView, VeriniceSearchResultTable vSearchResultObject) {\n this.searchView = searchView;\n columnStore = ColumnStoreFactory.getColumnStore(vSearchResultObject.getEntityTypeId());\n this.vSearchResultObject = vSearchResultObject;\n }\n\n @Override\n public void menuAboutToShow(IMenuManager manager) {\n if (hasNoColumnEntries(manager)) {\n for (IColumn col : columnStore.getAllColumns()) {\n manager.add(new ColumnContribution(this.searchView, col, vSearchResultObject));\n }\n manager.add(new Separator());\n manager.add(new RestoreDefaultAction());\n }\n }\n\n private boolean hasNoColumnEntries(IMenuManager manager) {\n return manager.getItems() != null && manager.getItems().length == 0;\n }\n\n private class RestoreDefaultAction extends Action {\n\n public RestoreDefaultAction() {\n setText(Messages.SearchView_6);\n setToolTipText(Messages.SearchView_6);\n }\n\n @Override\n public void run() {\n columnStore.restoreDefault(", "post_mask_code": "\n searchView.setTableViewer(vSearchResultObject);\n }\n }\n}\n"} {"task_id": "Java_2809", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/opennlp/opennlp-tools/src/main/java/opennlp/tools/postag/WordTagSampleStream.java", "mask_start_position": 991, "mask_end_position": 1034, "canonical_solution": "public POSSample read() throws IOException ", "pre_mask_code": "package opennlp.tools.postag;\n\nimport java.io.IOException;\nimport opennlp.tools.util.FilterObjectStream;\nimport opennlp.tools.util.InvalidFormatException;\nimport opennlp.tools.util.ObjectStream;\n\n/**\n * A stream filter which reads a sentence per line which contains\n * words and tags in word_tag format and outputs a {@link POSSample} objects.\n */\npublic class WordTagSampleStream extends FilterObjectStream {\n\n /**\n * Initializes the current instance.\n *\n * @param sentences the sentences\n */\n public WordTagSampleStream(ObjectStream sentences) {\n super(sentences);\n }\n\n /**\n * Parses the next sentence and return the next\n * {@link POSSample} object.\n *\n * If an error occurs an empty {@link POSSample} object is returned\n * and an warning message is logged. Usually it does not matter if one\n * of many sentences is ignored.\n *\n * TODO: An exception in error case should be thrown.\n */\n ", "post_mask_code": "{\n String sentence = samples.read();\n if (sentence != null) {\n POSSample sample;\n try {\n sample = POSSample.parse(sentence);\n } catch (InvalidFormatException e) {\n System.out.println(\"Error during parsing, ignoring sentence: \" + sentence);\n sample = new POSSample(new String[] {}, new String[] {});\n }\n return sample;\n } else {\n // sentences stream is exhausted\n return null;\n }\n }\n}\n"} {"task_id": "Java_2810", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/opennlp/opennlp-tools/src/main/java/opennlp/tools/postag/WordTagSampleStream.java", "mask_start_position": 1056, "mask_end_position": 1077, "canonical_solution": "nce = samples.read();", "pre_mask_code": "package opennlp.tools.postag;\n\nimport java.io.IOException;\nimport opennlp.tools.util.FilterObjectStream;\nimport opennlp.tools.util.InvalidFormatException;\nimport opennlp.tools.util.ObjectStream;\n\n/**\n * A stream filter which reads a sentence per line which contains\n * words and tags in word_tag format and outputs a {@link POSSample} objects.\n */\npublic class WordTagSampleStream extends FilterObjectStream {\n\n /**\n * Initializes the current instance.\n *\n * @param sentences the sentences\n */\n public WordTagSampleStream(ObjectStream sentences) {\n super(sentences);\n }\n\n /**\n * Parses the next sentence and return the next\n * {@link POSSample} object.\n *\n * If an error occurs an empty {@link POSSample} object is returned\n * and an warning message is logged. Usually it does not matter if one\n * of many sentences is ignored.\n *\n * TODO: An exception in error case should be thrown.\n */\n public POSSample read() throws IOException {\n String sente", "post_mask_code": "\n if (sentence != null) {\n POSSample sample;\n try {\n sample = POSSample.parse(sentence);\n } catch (InvalidFormatException e) {\n System.out.println(\"Error during parsing, ignoring sentence: \" + sentence);\n sample = new POSSample(new String[] {}, new String[] {});\n }\n return sample;\n } else {\n // sentences stream is exhausted\n return null;\n }\n }\n}\n"} {"task_id": "Java_2811", "language": "Java", "task_type": "try_statement", "source_file": "java/github/apache/opennlp/opennlp-tools/src/main/java/opennlp/tools/postag/WordTagSampleStream.java", "mask_start_position": 1152, "mask_end_position": 1438, "canonical_solution": "try {\n sample = POSSample.parse(sentence);\n } catch (InvalidFormatException e) {\n System.out.println(\"Error during parsing, ignoring sentence: \" + sentence);\n sample = new POSSample(new String[] {}, new String[] {});\n }", "pre_mask_code": "package opennlp.tools.postag;\n\nimport java.io.IOException;\nimport opennlp.tools.util.FilterObjectStream;\nimport opennlp.tools.util.InvalidFormatException;\nimport opennlp.tools.util.ObjectStream;\n\n/**\n * A stream filter which reads a sentence per line which contains\n * words and tags in word_tag format and outputs a {@link POSSample} objects.\n */\npublic class WordTagSampleStream extends FilterObjectStream {\n\n /**\n * Initializes the current instance.\n *\n * @param sentences the sentences\n */\n public WordTagSampleStream(ObjectStream sentences) {\n super(sentences);\n }\n\n /**\n * Parses the next sentence and return the next\n * {@link POSSample} object.\n *\n * If an error occurs an empty {@link POSSample} object is returned\n * and an warning message is logged. Usually it does not matter if one\n * of many sentences is ignored.\n *\n * TODO: An exception in error case should be thrown.\n */\n public POSSample read() throws IOException {\n String sentence = samples.read();\n if (sentence != null) {\n POSSample sample;\n ", "post_mask_code": "\n return sample;\n } else {\n // sentences stream is exhausted\n return null;\n }\n }\n}\n"} {"task_id": "Java_2812", "language": "Java", "task_type": "method_signature", "source_file": "java/github/release-engineering/pom-manipulation-ext/core/src/main/java/org/commonjava/maven/ext/core/state/GroovyState.java", "mask_start_position": 785, "mask_end_position": 859, "canonical_solution": "public void initialise(Properties userProps) throws ManipulationException ", "pre_mask_code": "package org.commonjava.maven.ext.core.state;\n\nimport org.commonjava.maven.ext.annotation.ConfigValue;\nimport org.commonjava.maven.ext.common.ManipulationException;\nimport java.util.Properties;\n\n/**\n * Captures configuration relating to groovy script execution.\n */\npublic class GroovyState implements State {\n\n /**\n * The name of the property which contains a comma separated list of remote groovy scripts to load.\n *

\n     * -DgroovyScripts=org.foo:bar-script,....\n     * 
\n */\n @ConfigValue(docIndex = \"groovy.html\")\n private static final String GROOVY_SCRIPT = \"groovyScripts\";\n\n private String groovyScripts;\n\n public GroovyState(final Properties userProps) throws ManipulationException {\n initialise(userProps);\n }\n\n ", "post_mask_code": "{\n groovyScripts = userProps.getProperty(GROOVY_SCRIPT);\n // Catch old style groovy configuration. Not doc'ed as config value.\n if (userProps.getProperty(\"groovyManipulatorPrecedence\") != null) {\n throw new ManipulationException(\"groovyManipulatorPrecedence is no longer valid\");\n }\n }\n\n /**\n * Enabled ONLY if groovyScripts is provided in the user properties / CLI -D options.\n *\n * @see State#isEnabled()\n */\n @Override\n public boolean isEnabled() {\n return groovyScripts != null && !groovyScripts.isEmpty();\n }\n\n public String getGroovyScripts() {\n return groovyScripts;\n }\n}\n"} {"task_id": "Java_2813", "language": "Java", "task_type": "method_body", "source_file": "java/github/release-engineering/pom-manipulation-ext/core/src/main/java/org/commonjava/maven/ext/core/state/GroovyState.java", "mask_start_position": 1488, "mask_end_position": 1525, "canonical_solution": "{\n return groovyScripts;\n }", "pre_mask_code": "package org.commonjava.maven.ext.core.state;\n\nimport org.commonjava.maven.ext.annotation.ConfigValue;\nimport org.commonjava.maven.ext.common.ManipulationException;\nimport java.util.Properties;\n\n/**\n * Captures configuration relating to groovy script execution.\n */\npublic class GroovyState implements State {\n\n /**\n * The name of the property which contains a comma separated list of remote groovy scripts to load.\n *
\n     * -DgroovyScripts=org.foo:bar-script,....\n     * 
\n */\n @ConfigValue(docIndex = \"groovy.html\")\n private static final String GROOVY_SCRIPT = \"groovyScripts\";\n\n private String groovyScripts;\n\n public GroovyState(final Properties userProps) throws ManipulationException {\n initialise(userProps);\n }\n\n public void initialise(Properties userProps) throws ManipulationException {\n groovyScripts = userProps.getProperty(GROOVY_SCRIPT);\n // Catch old style groovy configuration. Not doc'ed as config value.\n if (userProps.getProperty(\"groovyManipulatorPrecedence\") != null) {\n throw new ManipulationException(\"groovyManipulatorPrecedence is no longer valid\");\n }\n }\n\n /**\n * Enabled ONLY if groovyScripts is provided in the user properties / CLI -D options.\n *\n * @see State#isEnabled()\n */\n @Override\n public boolean isEnabled() {\n return groovyScripts != null && !groovyScripts.isEmpty();\n }\n\n public String getGroovyScripts() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2814", "language": "Java", "task_type": "single_line", "source_file": "java/github/release-engineering/pom-manipulation-ext/core/src/main/java/org/commonjava/maven/ext/core/state/GroovyState.java", "mask_start_position": 1424, "mask_end_position": 1443, "canonical_solution": "yScripts.isEmpty();", "pre_mask_code": "package org.commonjava.maven.ext.core.state;\n\nimport org.commonjava.maven.ext.annotation.ConfigValue;\nimport org.commonjava.maven.ext.common.ManipulationException;\nimport java.util.Properties;\n\n/**\n * Captures configuration relating to groovy script execution.\n */\npublic class GroovyState implements State {\n\n /**\n * The name of the property which contains a comma separated list of remote groovy scripts to load.\n *
\n     * -DgroovyScripts=org.foo:bar-script,....\n     * 
\n */\n @ConfigValue(docIndex = \"groovy.html\")\n private static final String GROOVY_SCRIPT = \"groovyScripts\";\n\n private String groovyScripts;\n\n public GroovyState(final Properties userProps) throws ManipulationException {\n initialise(userProps);\n }\n\n public void initialise(Properties userProps) throws ManipulationException {\n groovyScripts = userProps.getProperty(GROOVY_SCRIPT);\n // Catch old style groovy configuration. Not doc'ed as config value.\n if (userProps.getProperty(\"groovyManipulatorPrecedence\") != null) {\n throw new ManipulationException(\"groovyManipulatorPrecedence is no longer valid\");\n }\n }\n\n /**\n * Enabled ONLY if groovyScripts is provided in the user properties / CLI -D options.\n *\n * @see State#isEnabled()\n */\n @Override\n public boolean isEnabled() {\n return groovyScripts != null && !groov", "post_mask_code": "\n }\n\n public String getGroovyScripts() {\n return groovyScripts;\n }\n}\n"} {"task_id": "Java_2815", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/release-engineering/pom-manipulation-ext/core/src/main/java/org/commonjava/maven/ext/core/state/GroovyState.java", "mask_start_position": 1335, "mask_end_position": 1449, "canonical_solution": "@Override\n public boolean isEnabled() {\n return groovyScripts != null && !groovyScripts.isEmpty();\n }", "pre_mask_code": "package org.commonjava.maven.ext.core.state;\n\nimport org.commonjava.maven.ext.annotation.ConfigValue;\nimport org.commonjava.maven.ext.common.ManipulationException;\nimport java.util.Properties;\n\n/**\n * Captures configuration relating to groovy script execution.\n */\npublic class GroovyState implements State {\n\n /**\n * The name of the property which contains a comma separated list of remote groovy scripts to load.\n *
\n     * -DgroovyScripts=org.foo:bar-script,....\n     * 
\n */\n @ConfigValue(docIndex = \"groovy.html\")\n private static final String GROOVY_SCRIPT = \"groovyScripts\";\n\n private String groovyScripts;\n\n public GroovyState(final Properties userProps) throws ManipulationException {\n initialise(userProps);\n }\n\n public void initialise(Properties userProps) throws ManipulationException {\n groovyScripts = userProps.getProperty(GROOVY_SCRIPT);\n // Catch old style groovy configuration. Not doc'ed as config value.\n if (userProps.getProperty(\"groovyManipulatorPrecedence\") != null) {\n throw new ManipulationException(\"groovyManipulatorPrecedence is no longer valid\");\n }\n }\n\n /**\n * Enabled ONLY if groovyScripts is provided in the user properties / CLI -D options.\n *\n * @see State#isEnabled()\n */\n ", "post_mask_code": "\n\n public String getGroovyScripts() {\n return groovyScripts;\n }\n}\n"} {"task_id": "Java_2816", "language": "Java", "task_type": "method_signature", "source_file": "java/github/javaee/jaxb-v2/jaxb-ri/runtime/impl/src/main/java/com/sun/xml/bind/v2/runtime/property/ArrayReferenceNodeProperty.java", "mask_start_position": 3379, "mask_end_position": 3470, "canonical_solution": "public void createBodyUnmarshaller(UnmarshallerChain chain, QNameMap loaders) ", "pre_mask_code": "package com.sun.xml.bind.v2.runtime.property;\n\nimport java.io.IOException;\nimport javax.xml.bind.JAXBException;\nimport javax.xml.bind.annotation.DomHandler;\nimport javax.xml.stream.XMLStreamException;\nimport com.sun.xml.bind.v2.ClassFactory;\nimport com.sun.xml.bind.v2.model.core.PropertyKind;\nimport com.sun.xml.bind.v2.model.core.WildcardMode;\nimport com.sun.xml.bind.v2.model.runtime.RuntimeElement;\nimport com.sun.xml.bind.v2.model.runtime.RuntimeReferencePropertyInfo;\nimport com.sun.xml.bind.v2.runtime.JAXBContextImpl;\nimport com.sun.xml.bind.v2.runtime.JaxBeanInfo;\nimport com.sun.xml.bind.v2.runtime.XMLSerializer;\nimport com.sun.xml.bind.v2.runtime.reflect.Accessor;\nimport com.sun.xml.bind.v2.runtime.reflect.ListIterator;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.ChildLoader;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.Loader;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.Receiver;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.WildcardLoader;\nimport com.sun.xml.bind.v2.util.QNameMap;\nimport org.xml.sax.SAXException;\n\n/**\n * @author Kohsuke Kawaguchi\n */\nclass ArrayReferenceNodeProperty extends ArrayERProperty {\n\n /**\n * Expected element names and what class to unmarshal.\n */\n private final QNameMap expectedElements = new QNameMap();\n\n private final boolean isMixed;\n\n private final DomHandler domHandler;\n\n private final WildcardMode wcMode;\n\n public ArrayReferenceNodeProperty(JAXBContextImpl p, RuntimeReferencePropertyInfo prop) {\n super(p, prop, prop.getXmlName(), prop.isCollectionNillable());\n for (RuntimeElement e : prop.getElements()) {\n JaxBeanInfo bi = p.getOrCreate(e);\n expectedElements.put(e.getElementName().getNamespaceURI(), e.getElementName().getLocalPart(), bi);\n }\n isMixed = prop.isMixed();\n if (prop.getWildcard() != null) {\n domHandler = (DomHandler) ClassFactory.create(prop.getDOMHandler());\n wcMode = prop.getWildcard();\n } else {\n domHandler = null;\n wcMode = null;\n }\n }\n\n protected final void serializeListBody(BeanT o, XMLSerializer w, ListT list) throws IOException, XMLStreamException, SAXException {\n ListIterator itr = lister.iterator(list, w);\n while (itr.hasNext()) {\n try {\n ItemT item = itr.next();\n if (item != null) {\n if (isMixed && item.getClass() == String.class) {\n w.text((String) item, null);\n } else {\n JaxBeanInfo bi = w.grammar.getBeanInfo(item, true);\n if (bi.jaxbType == Object.class && domHandler != null)\n // even if 'v' is a DOM node, it always derive from Object,\n // so the getBeanInfo returns BeanInfo for Object\n w.writeDom(item, domHandler, o, fieldName);\n else\n bi.serializeRoot(item, w);\n }\n }\n } catch (JAXBException e) {\n w.reportError(fieldName, e);\n // recover by ignoring this item\n }\n }\n }\n\n ", "post_mask_code": "{\n final int offset = chain.allocateOffset();\n Receiver recv = new ReceiverImpl(offset);\n for (QNameMap.Entry n : expectedElements.entrySet()) {\n final JaxBeanInfo beanInfo = n.getValue();\n loaders.put(n.nsUri, n.localName, new ChildLoader(beanInfo.getLoader(chain.context, true), recv));\n }\n if (isMixed) {\n // handler for processing mixed contents.\n loaders.put(TEXT_HANDLER, new ChildLoader(new MixedTextLoader(recv), null));\n }\n if (domHandler != null) {\n loaders.put(CATCH_ALL, new ChildLoader(new WildcardLoader(domHandler, wcMode), recv));\n }\n }\n\n private static final class MixedTextLoader extends Loader {\n\n private final Receiver recv;\n\n public MixedTextLoader(Receiver recv) {\n super(true);\n this.recv = recv;\n }\n\n public void text(UnmarshallingContext.State state, CharSequence text) throws SAXException {\n if (// length 0 text is pointless\n text.length() != 0)\n recv.receive(state, text.toString());\n }\n }\n\n public PropertyKind getKind() {\n return PropertyKind.REFERENCE;\n }\n\n @Override\n public Accessor getElementPropertyAccessor(String nsUri, String localName) {\n // TODO: unwrap JAXBElement\n if (wrapperTagName != null) {\n if (wrapperTagName.equals(nsUri, localName))\n return acc;\n } else {\n if (expectedElements.containsKey(nsUri, localName))\n return acc;\n }\n return null;\n }\n}\n"} {"task_id": "Java_2817", "language": "Java", "task_type": "method_body", "source_file": "java/github/javaee/jaxb-v2/jaxb-ri/runtime/impl/src/main/java/com/sun/xml/bind/v2/runtime/property/ArrayReferenceNodeProperty.java", "mask_start_position": 4466, "mask_end_position": 4609, "canonical_solution": "{\n if (// length 0 text is pointless\n text.length() != 0)\n recv.receive(state, text.toString());\n }", "pre_mask_code": "package com.sun.xml.bind.v2.runtime.property;\n\nimport java.io.IOException;\nimport javax.xml.bind.JAXBException;\nimport javax.xml.bind.annotation.DomHandler;\nimport javax.xml.stream.XMLStreamException;\nimport com.sun.xml.bind.v2.ClassFactory;\nimport com.sun.xml.bind.v2.model.core.PropertyKind;\nimport com.sun.xml.bind.v2.model.core.WildcardMode;\nimport com.sun.xml.bind.v2.model.runtime.RuntimeElement;\nimport com.sun.xml.bind.v2.model.runtime.RuntimeReferencePropertyInfo;\nimport com.sun.xml.bind.v2.runtime.JAXBContextImpl;\nimport com.sun.xml.bind.v2.runtime.JaxBeanInfo;\nimport com.sun.xml.bind.v2.runtime.XMLSerializer;\nimport com.sun.xml.bind.v2.runtime.reflect.Accessor;\nimport com.sun.xml.bind.v2.runtime.reflect.ListIterator;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.ChildLoader;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.Loader;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.Receiver;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.WildcardLoader;\nimport com.sun.xml.bind.v2.util.QNameMap;\nimport org.xml.sax.SAXException;\n\n/**\n * @author Kohsuke Kawaguchi\n */\nclass ArrayReferenceNodeProperty extends ArrayERProperty {\n\n /**\n * Expected element names and what class to unmarshal.\n */\n private final QNameMap expectedElements = new QNameMap();\n\n private final boolean isMixed;\n\n private final DomHandler domHandler;\n\n private final WildcardMode wcMode;\n\n public ArrayReferenceNodeProperty(JAXBContextImpl p, RuntimeReferencePropertyInfo prop) {\n super(p, prop, prop.getXmlName(), prop.isCollectionNillable());\n for (RuntimeElement e : prop.getElements()) {\n JaxBeanInfo bi = p.getOrCreate(e);\n expectedElements.put(e.getElementName().getNamespaceURI(), e.getElementName().getLocalPart(), bi);\n }\n isMixed = prop.isMixed();\n if (prop.getWildcard() != null) {\n domHandler = (DomHandler) ClassFactory.create(prop.getDOMHandler());\n wcMode = prop.getWildcard();\n } else {\n domHandler = null;\n wcMode = null;\n }\n }\n\n protected final void serializeListBody(BeanT o, XMLSerializer w, ListT list) throws IOException, XMLStreamException, SAXException {\n ListIterator itr = lister.iterator(list, w);\n while (itr.hasNext()) {\n try {\n ItemT item = itr.next();\n if (item != null) {\n if (isMixed && item.getClass() == String.class) {\n w.text((String) item, null);\n } else {\n JaxBeanInfo bi = w.grammar.getBeanInfo(item, true);\n if (bi.jaxbType == Object.class && domHandler != null)\n // even if 'v' is a DOM node, it always derive from Object,\n // so the getBeanInfo returns BeanInfo for Object\n w.writeDom(item, domHandler, o, fieldName);\n else\n bi.serializeRoot(item, w);\n }\n }\n } catch (JAXBException e) {\n w.reportError(fieldName, e);\n // recover by ignoring this item\n }\n }\n }\n\n public void createBodyUnmarshaller(UnmarshallerChain chain, QNameMap loaders) {\n final int offset = chain.allocateOffset();\n Receiver recv = new ReceiverImpl(offset);\n for (QNameMap.Entry n : expectedElements.entrySet()) {\n final JaxBeanInfo beanInfo = n.getValue();\n loaders.put(n.nsUri, n.localName, new ChildLoader(beanInfo.getLoader(chain.context, true), recv));\n }\n if (isMixed) {\n // handler for processing mixed contents.\n loaders.put(TEXT_HANDLER, new ChildLoader(new MixedTextLoader(recv), null));\n }\n if (domHandler != null) {\n loaders.put(CATCH_ALL, new ChildLoader(new WildcardLoader(domHandler, wcMode), recv));\n }\n }\n\n private static final class MixedTextLoader extends Loader {\n\n private final Receiver recv;\n\n public MixedTextLoader(Receiver recv) {\n super(true);\n this.recv = recv;\n }\n\n public void text(UnmarshallingContext.State state, CharSequence text) throws SAXException ", "post_mask_code": "\n }\n\n public PropertyKind getKind() {\n return PropertyKind.REFERENCE;\n }\n\n @Override\n public Accessor getElementPropertyAccessor(String nsUri, String localName) {\n // TODO: unwrap JAXBElement\n if (wrapperTagName != null) {\n if (wrapperTagName.equals(nsUri, localName))\n return acc;\n } else {\n if (expectedElements.containsKey(nsUri, localName))\n return acc;\n }\n return null;\n }\n}\n"} {"task_id": "Java_2818", "language": "Java", "task_type": "single_line", "source_file": "java/github/javaee/jaxb-v2/jaxb-ri/runtime/impl/src/main/java/com/sun/xml/bind/v2/runtime/property/ArrayReferenceNodeProperty.java", "mask_start_position": 2410, "mask_end_position": 2413, "canonical_solution": "w);", "pre_mask_code": "package com.sun.xml.bind.v2.runtime.property;\n\nimport java.io.IOException;\nimport javax.xml.bind.JAXBException;\nimport javax.xml.bind.annotation.DomHandler;\nimport javax.xml.stream.XMLStreamException;\nimport com.sun.xml.bind.v2.ClassFactory;\nimport com.sun.xml.bind.v2.model.core.PropertyKind;\nimport com.sun.xml.bind.v2.model.core.WildcardMode;\nimport com.sun.xml.bind.v2.model.runtime.RuntimeElement;\nimport com.sun.xml.bind.v2.model.runtime.RuntimeReferencePropertyInfo;\nimport com.sun.xml.bind.v2.runtime.JAXBContextImpl;\nimport com.sun.xml.bind.v2.runtime.JaxBeanInfo;\nimport com.sun.xml.bind.v2.runtime.XMLSerializer;\nimport com.sun.xml.bind.v2.runtime.reflect.Accessor;\nimport com.sun.xml.bind.v2.runtime.reflect.ListIterator;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.ChildLoader;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.Loader;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.Receiver;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext;\nimport com.sun.xml.bind.v2.runtime.unmarshaller.WildcardLoader;\nimport com.sun.xml.bind.v2.util.QNameMap;\nimport org.xml.sax.SAXException;\n\n/**\n * @author Kohsuke Kawaguchi\n */\nclass ArrayReferenceNodeProperty extends ArrayERProperty {\n\n /**\n * Expected element names and what class to unmarshal.\n */\n private final QNameMap expectedElements = new QNameMap();\n\n private final boolean isMixed;\n\n private final DomHandler domHandler;\n\n private final WildcardMode wcMode;\n\n public ArrayReferenceNodeProperty(JAXBContextImpl p, RuntimeReferencePropertyInfo prop) {\n super(p, prop, prop.getXmlName(), prop.isCollectionNillable());\n for (RuntimeElement e : prop.getElements()) {\n JaxBeanInfo bi = p.getOrCreate(e);\n expectedElements.put(e.getElementName().getNamespaceURI(), e.getElementName().getLocalPart(), bi);\n }\n isMixed = prop.isMixed();\n if (prop.getWildcard() != null) {\n domHandler = (DomHandler) ClassFactory.create(prop.getDOMHandler());\n wcMode = prop.getWildcard();\n } else {\n domHandler = null;\n wcMode = null;\n }\n }\n\n protected final void serializeListBody(BeanT o, XMLSerializer w, ListT list) throws IOException, XMLStreamException, SAXException {\n ListIterator itr = lister.iterator(list, ", "post_mask_code": "\n while (itr.hasNext()) {\n try {\n ItemT item = itr.next();\n if (item != null) {\n if (isMixed && item.getClass() == String.class) {\n w.text((String) item, null);\n } else {\n JaxBeanInfo bi = w.grammar.getBeanInfo(item, true);\n if (bi.jaxbType == Object.class && domHandler != null)\n // even if 'v' is a DOM node, it always derive from Object,\n // so the getBeanInfo returns BeanInfo for Object\n w.writeDom(item, domHandler, o, fieldName);\n else\n bi.serializeRoot(item, w);\n }\n }\n } catch (JAXBException e) {\n w.reportError(fieldName, e);\n // recover by ignoring this item\n }\n }\n }\n\n public void createBodyUnmarshaller(UnmarshallerChain chain, QNameMap loaders) {\n final int offset = chain.allocateOffset();\n Receiver recv = new ReceiverImpl(offset);\n for (QNameMap.Entry n : expectedElements.entrySet()) {\n final JaxBeanInfo beanInfo = n.getValue();\n loaders.put(n.nsUri, n.localName, new ChildLoader(beanInfo.getLoader(chain.context, true), recv));\n }\n if (isMixed) {\n // handler for processing mixed contents.\n loaders.put(TEXT_HANDLER, new ChildLoader(new MixedTextLoader(recv), null));\n }\n if (domHandler != null) {\n loaders.put(CATCH_ALL, new ChildLoader(new WildcardLoader(domHandler, wcMode), recv));\n }\n }\n\n private static final class MixedTextLoader extends Loader {\n\n private final Receiver recv;\n\n public MixedTextLoader(Receiver recv) {\n super(true);\n this.recv = recv;\n }\n\n public void text(UnmarshallingContext.State state, CharSequence text) throws SAXException {\n if (// length 0 text is pointless\n text.length() != 0)\n recv.receive(state, text.toString());\n }\n }\n\n public PropertyKind getKind() {\n return PropertyKind.REFERENCE;\n }\n\n @Override\n public Accessor getElementPropertyAccessor(String nsUri, String localName) {\n // TODO: unwrap JAXBElement\n if (wrapperTagName != null) {\n if (wrapperTagName.equals(nsUri, localName))\n return acc;\n } else {\n if (expectedElements.containsKey(nsUri, localName))\n return acc;\n }\n return null;\n }\n}\n"} {"task_id": "Java_2819", "language": "Java", "task_type": "method_signature", "source_file": "java/github/fetlife/android/FetLife/fetlife/src/main/java/com/bitlove/fetlife/util/ServerIdUtil.java", "mask_start_position": 366, "mask_end_position": 416, "canonical_solution": "public static boolean isServerId(String serverId) ", "pre_mask_code": "package com.bitlove.fetlife.util;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class ServerIdUtil {\n\n // Note: Temporarily duplicated\n private static final String SERVER_ID_PREFIX = \"SERVER_ID_PREFIX:\";\n\n private static Map idCache = Collections.synchronizedMap(new HashMap());\n\n ", "post_mask_code": "{\n return serverId.startsWith(SERVER_ID_PREFIX);\n }\n\n public static void setLocalId(String serverId, String localId) {\n if (!serverId.startsWith(SERVER_ID_PREFIX)) {\n serverId = SERVER_ID_PREFIX + serverId;\n }\n idCache.put(serverId, localId);\n }\n\n public static String getLocalId(String serverId) {\n return idCache.get(serverId);\n }\n\n public static boolean containsServerId(String serverId) {\n return idCache.containsKey(serverId);\n }\n\n public static String prefixServerId(String serverId) {\n return SERVER_ID_PREFIX + serverId;\n }\n\n public static String removePrefix(String serverId) {\n return serverId.substring(SERVER_ID_PREFIX.length());\n }\n}\n"} {"task_id": "Java_2820", "language": "Java", "task_type": "method_body", "source_file": "java/github/fetlife/android/FetLife/fetlife/src/main/java/com/bitlove/fetlife/util/ServerIdUtil.java", "mask_start_position": 983, "mask_end_position": 1034, "canonical_solution": "{\n return SERVER_ID_PREFIX + serverId;\n }", "pre_mask_code": "package com.bitlove.fetlife.util;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class ServerIdUtil {\n\n // Note: Temporarily duplicated\n private static final String SERVER_ID_PREFIX = \"SERVER_ID_PREFIX:\";\n\n private static Map idCache = Collections.synchronizedMap(new HashMap());\n\n public static boolean isServerId(String serverId) {\n return serverId.startsWith(SERVER_ID_PREFIX);\n }\n\n public static void setLocalId(String serverId, String localId) {\n if (!serverId.startsWith(SERVER_ID_PREFIX)) {\n serverId = SERVER_ID_PREFIX + serverId;\n }\n idCache.put(serverId, localId);\n }\n\n public static String getLocalId(String serverId) {\n return idCache.get(serverId);\n }\n\n public static boolean containsServerId(String serverId) {\n return idCache.containsKey(serverId);\n }\n\n public static String prefixServerId(String serverId) ", "post_mask_code": "\n\n public static String removePrefix(String serverId) {\n return serverId.substring(SERVER_ID_PREFIX.length());\n }\n}\n"} {"task_id": "Java_2821", "language": "Java", "task_type": "single_line", "source_file": "java/github/fetlife/android/FetLife/fetlife/src/main/java/com/bitlove/fetlife/util/ServerIdUtil.java", "mask_start_position": 1102, "mask_end_position": 1154, "canonical_solution": "eturn serverId.substring(SERVER_ID_PREFIX.length());", "pre_mask_code": "package com.bitlove.fetlife.util;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class ServerIdUtil {\n\n // Note: Temporarily duplicated\n private static final String SERVER_ID_PREFIX = \"SERVER_ID_PREFIX:\";\n\n private static Map idCache = Collections.synchronizedMap(new HashMap());\n\n public static boolean isServerId(String serverId) {\n return serverId.startsWith(SERVER_ID_PREFIX);\n }\n\n public static void setLocalId(String serverId, String localId) {\n if (!serverId.startsWith(SERVER_ID_PREFIX)) {\n serverId = SERVER_ID_PREFIX + serverId;\n }\n idCache.put(serverId, localId);\n }\n\n public static String getLocalId(String serverId) {\n return idCache.get(serverId);\n }\n\n public static boolean containsServerId(String serverId) {\n return idCache.containsKey(serverId);\n }\n\n public static String prefixServerId(String serverId) {\n return SERVER_ID_PREFIX + serverId;\n }\n\n public static String removePrefix(String serverId) {\n r", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2822", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openjdk/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java", "mask_start_position": 202993, "mask_end_position": 203021, "canonical_solution": "public final void compute() ", "pre_mask_code": "package java.util.concurrent;\n\nimport java.io.ObjectStreamField;\nimport java.io.Serializable;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.AbstractMap;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Hashtable;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.Spliterator;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.concurrent.locks.LockSupport;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\nimport java.util.function.Consumer;\nimport java.util.function.DoubleBinaryOperator;\nimport java.util.function.Function;\nimport java.util.function.IntBinaryOperator;\nimport java.util.function.LongBinaryOperator;\nimport java.util.function.Predicate;\nimport java.util.function.ToDoubleBiFunction;\nimport java.util.function.ToDoubleFunction;\nimport java.util.function.ToIntBiFunction;\nimport java.util.function.ToIntFunction;\nimport java.util.function.ToLongBiFunction;\nimport java.util.function.ToLongFunction;\nimport java.util.stream.Stream;\nimport jdk.internal.misc.Unsafe;\n\n/**\n * A hash table supporting full concurrency of retrievals and\n * high expected concurrency for updates. This class obeys the\n * same functional specification as {@link java.util.Hashtable}, and\n * includes versions of methods corresponding to each method of\n * {@code Hashtable}. However, even though all operations are\n * thread-safe, retrieval operations do not entail locking,\n * and there is not any support for locking the entire table\n * in a way that prevents all access. This class is fully\n * interoperable with {@code Hashtable} in programs that rely on its\n * thread safety but not on its synchronization details.\n *\n *

Retrieval operations (including {@code get}) generally do not\n * block, so may overlap with update operations (including {@code put}\n * and {@code remove}). Retrievals reflect the results of the most\n * recently completed update operations holding upon their\n * onset. (More formally, an update operation for a given key bears a\n * happens-before relation with any (non-null) retrieval for\n * that key reporting the updated value.) For aggregate operations\n * such as {@code putAll} and {@code clear}, concurrent retrievals may\n * reflect insertion or removal of only some entries. Similarly,\n * Iterators, Spliterators and Enumerations return elements reflecting the\n * state of the hash table at some point at or since the creation of the\n * iterator/enumeration. They do not throw {@link\n * java.util.ConcurrentModificationException ConcurrentModificationException}.\n * However, iterators are designed to be used by only one thread at a time.\n * Bear in mind that the results of aggregate status methods including\n * {@code size}, {@code isEmpty}, and {@code containsValue} are typically\n * useful only when a map is not undergoing concurrent updates in other threads.\n * Otherwise the results of these methods reflect transient states\n * that may be adequate for monitoring or estimation purposes, but not\n * for program control.\n *\n *

The table is dynamically expanded when there are too many\n * collisions (i.e., keys that have distinct hash codes but fall into\n * the same slot modulo the table size), with the expected average\n * effect of maintaining roughly two bins per mapping (corresponding\n * to a 0.75 load factor threshold for resizing). There may be much\n * variance around this average as mappings are added and removed, but\n * overall, this maintains a commonly accepted time/space tradeoff for\n * hash tables. However, resizing this or any other kind of hash\n * table may be a relatively slow operation. When possible, it is a\n * good idea to provide a size estimate as an optional {@code\n * initialCapacity} constructor argument. An additional optional\n * {@code loadFactor} constructor argument provides a further means of\n * customizing initial table capacity by specifying the table density\n * to be used in calculating the amount of space to allocate for the\n * given number of elements. Also, for compatibility with previous\n * versions of this class, constructors may optionally specify an\n * expected {@code concurrencyLevel} as an additional hint for\n * internal sizing. Note that using many keys with exactly the same\n * {@code hashCode()} is a sure way to slow down performance of any\n * hash table. To ameliorate impact, when keys are {@link Comparable},\n * this class may use comparison order among keys to help break ties.\n *\n *

A {@link Set} projection of a ConcurrentHashMap may be created\n * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed\n * (using {@link #keySet(Object)} when only keys are of interest, and the\n * mapped values are (perhaps transiently) not used or all take the\n * same mapping value.\n *\n *

A ConcurrentHashMap can be used as a scalable frequency map (a\n * form of histogram or multiset) by using {@link\n * java.util.concurrent.atomic.LongAdder} values and initializing via\n * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count\n * to a {@code ConcurrentHashMap freqs}, you can use\n * {@code freqs.computeIfAbsent(key, k -> new LongAdder()).increment();}\n *\n *

This class and its views and iterators implement all of the\n * optional methods of the {@link Map} and {@link Iterator}\n * interfaces.\n *\n *

Like {@link Hashtable} but unlike {@link HashMap}, this class\n * does not allow {@code null} to be used as a key or value.\n *\n *

ConcurrentHashMaps support a set of sequential and parallel bulk\n * operations that, unlike most {@link Stream} methods, are designed\n * to be safely, and often sensibly, applied even with maps that are\n * being concurrently updated by other threads; for example, when\n * computing a snapshot summary of the values in a shared registry.\n * There are three kinds of operation, each with four forms, accepting\n * functions with keys, values, entries, and (key, value) pairs as\n * arguments and/or return values. Because the elements of a\n * ConcurrentHashMap are not ordered in any particular way, and may be\n * processed in different orders in different parallel executions, the\n * correctness of supplied functions should not depend on any\n * ordering, or on any other objects or values that may transiently\n * change while computation is in progress; and except for forEach\n * actions, should ideally be side-effect-free. Bulk operations on\n * {@link Map.Entry} objects do not support method {@code setValue}.\n *\n *

    \n *
  • forEach: Performs a given action on each element.\n * A variant form applies a given transformation on each element\n * before performing the action.\n *\n *
  • search: Returns the first available non-null result of\n * applying a given function on each element; skipping further\n * search when a result is found.\n *\n *
  • reduce: Accumulates each element. The supplied reduction\n * function cannot rely on ordering (more formally, it should be\n * both associative and commutative). There are five variants:\n *\n *
      \n *\n *
    • Plain reductions. (There is not a form of this method for\n * (key, value) function arguments since there is no corresponding\n * return type.)\n *\n *
    • Mapped reductions that accumulate the results of a given\n * function applied to each element.\n *\n *
    • Reductions to scalar doubles, longs, and ints, using a\n * given basis value.\n *\n *
    \n *
\n *\n *

These bulk operations accept a {@code parallelismThreshold}\n * argument. Methods proceed sequentially if the current map size is\n * estimated to be less than the given threshold. Using a value of\n * {@code Long.MAX_VALUE} suppresses all parallelism. Using a value\n * of {@code 1} results in maximal parallelism by partitioning into\n * enough subtasks to fully utilize the {@link\n * ForkJoinPool#commonPool()} that is used for all parallel\n * computations. Normally, you would initially choose one of these\n * extreme values, and then measure performance of using in-between\n * values that trade off overhead versus throughput.\n *\n *

The concurrency properties of bulk operations follow\n * from those of ConcurrentHashMap: Any non-null result returned\n * from {@code get(key)} and related access methods bears a\n * happens-before relation with the associated insertion or\n * update. The result of any bulk operation reflects the\n * composition of these per-element relations (but is not\n * necessarily atomic with respect to the map as a whole unless it\n * is somehow known to be quiescent). Conversely, because keys\n * and values in the map are never null, null serves as a reliable\n * atomic indicator of the current lack of any result. To\n * maintain this property, null serves as an implicit basis for\n * all non-scalar reduction operations. For the double, long, and\n * int versions, the basis should be one that, when combined with\n * any other value, returns that other value (more formally, it\n * should be the identity element for the reduction). Most common\n * reductions have these properties; for example, computing a sum\n * with basis 0 or a minimum with basis MAX_VALUE.\n *\n *

Search and transformation functions provided as arguments\n * should similarly return null to indicate the lack of any result\n * (in which case it is not used). In the case of mapped\n * reductions, this also enables transformations to serve as\n * filters, returning null (or, in the case of primitive\n * specializations, the identity basis) if the element should not\n * be combined. You can create compound transformations and\n * filterings by composing them yourself under this \"null means\n * there is nothing there now\" rule before using them in search or\n * reduce operations.\n *\n *

Methods accepting and/or returning Entry arguments maintain\n * key-value associations. They may be useful for example when\n * finding the key for the greatest value. Note that \"plain\" Entry\n * arguments can be supplied using {@code new\n * AbstractMap.SimpleEntry(k,v)}.\n *\n *

Bulk operations may complete abruptly, throwing an\n * exception encountered in the application of a supplied\n * function. Bear in mind when handling such exceptions that other\n * concurrently executing functions could also have thrown\n * exceptions, or would have done so if the first exception had\n * not occurred.\n *\n *

Speedups for parallel compared to sequential forms are common\n * but not guaranteed. Parallel operations involving brief functions\n * on small maps may execute more slowly than sequential forms if the\n * underlying work to parallelize the computation is more expensive\n * than the computation itself. Similarly, parallelization may not\n * lead to much actual parallelism if all processors are busy\n * performing unrelated tasks.\n *\n *

All arguments to all task methods must be non-null.\n *\n *

This class is a member of the\n * \n * Java Collections Framework.\n *\n * @since 1.5\n * @author Doug Lea\n * @param the type of keys maintained by this map\n * @param the type of mapped values\n */\npublic class ConcurrentHashMap extends AbstractMap implements ConcurrentMap, Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n /*\n * Overview:\n *\n * The primary design goal of this hash table is to maintain\n * concurrent readability (typically method get(), but also\n * iterators and related methods) while minimizing update\n * contention. Secondary goals are to keep space consumption about\n * the same or better than java.util.HashMap, and to support high\n * initial insertion rates on an empty table by many threads.\n *\n * This map usually acts as a binned (bucketed) hash table. Each\n * key-value mapping is held in a Node. Most nodes are instances\n * of the basic Node class with hash, key, value, and next\n * fields. However, various subclasses exist: TreeNodes are\n * arranged in balanced trees, not lists. TreeBins hold the roots\n * of sets of TreeNodes. ForwardingNodes are placed at the heads\n * of bins during resizing. ReservationNodes are used as\n * placeholders while establishing values in computeIfAbsent and\n * related methods. The types TreeBin, ForwardingNode, and\n * ReservationNode do not hold normal user keys, values, or\n * hashes, and are readily distinguishable during search etc\n * because they have negative hash fields and null key and value\n * fields. (These special nodes are either uncommon or transient,\n * so the impact of carrying around some unused fields is\n * insignificant.)\n *\n * The table is lazily initialized to a power-of-two size upon the\n * first insertion. Each bin in the table normally contains a\n * list of Nodes (most often, the list has only zero or one Node).\n * Table accesses require volatile/atomic reads, writes, and\n * CASes. Because there is no other way to arrange this without\n * adding further indirections, we use intrinsics\n * (jdk.internal.misc.Unsafe) operations.\n *\n * We use the top (sign) bit of Node hash fields for control\n * purposes -- it is available anyway because of addressing\n * constraints. Nodes with negative hash fields are specially\n * handled or ignored in map methods.\n *\n * Insertion (via put or its variants) of the first node in an\n * empty bin is performed by just CASing it to the bin. This is\n * by far the most common case for put operations under most\n * key/hash distributions. Other update operations (insert,\n * delete, and replace) require locks. We do not want to waste\n * the space required to associate a distinct lock object with\n * each bin, so instead use the first node of a bin list itself as\n * a lock. Locking support for these locks relies on builtin\n * \"synchronized\" monitors.\n *\n * Using the first node of a list as a lock does not by itself\n * suffice though: When a node is locked, any update must first\n * validate that it is still the first node after locking it, and\n * retry if not. Because new nodes are always appended to lists,\n * once a node is first in a bin, it remains first until deleted\n * or the bin becomes invalidated (upon resizing).\n *\n * The main disadvantage of per-bin locks is that other update\n * operations on other nodes in a bin list protected by the same\n * lock can stall, for example when user equals() or mapping\n * functions take a long time. However, statistically, under\n * random hash codes, this is not a common problem. Ideally, the\n * frequency of nodes in bins follows a Poisson distribution\n * (http://example.com) with a\n * parameter of about 0.5 on average, given the resizing threshold\n * of 0.75, although with a large variance because of resizing\n * granularity. Ignoring variance, the expected occurrences of\n * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The\n * first values are:\n *\n * 0: 0.60653066\n * 1: 0.30326533\n * 2: 0.07581633\n * 3: 0.01263606\n * 4: 0.00157952\n * 5: 0.00015795\n * 6: 0.00001316\n * 7: 0.00000094\n * 8: 0.00000006\n * more: less than 1 in ten million\n *\n * Lock contention probability for two threads accessing distinct\n * elements is roughly 1 / (8 * #elements) under random hashes.\n *\n * Actual hash code distributions encountered in practice\n * sometimes deviate significantly from uniform randomness. This\n * includes the case when N > (1<<30), so some keys MUST collide.\n * Similarly for dumb or hostile usages in which multiple keys are\n * designed to have identical hash codes or ones that differs only\n * in masked-out high bits. So we use a secondary strategy that\n * applies when the number of nodes in a bin exceeds a\n * threshold. These TreeBins use a balanced tree to hold nodes (a\n * specialized form of red-black trees), bounding search time to\n * O(log N). Each search step in a TreeBin is at least twice as\n * slow as in a regular list, but given that N cannot exceed\n * (1<<64) (before running out of addresses) this bounds search\n * steps, lock hold times, etc, to reasonable constants (roughly\n * 100 nodes inspected per operation worst case) so long as keys\n * are Comparable (which is very common -- String, Long, etc).\n * TreeBin nodes (TreeNodes) also maintain the same \"next\"\n * traversal pointers as regular nodes, so can be traversed in\n * iterators in the same way.\n *\n * The table is resized when occupancy exceeds a percentage\n * threshold (nominally, 0.75, but see below). Any thread\n * noticing an overfull bin may assist in resizing after the\n * initiating thread allocates and sets up the replacement array.\n * However, rather than stalling, these other threads may proceed\n * with insertions etc. The use of TreeBins shields us from the\n * worst case effects of overfilling while resizes are in\n * progress. Resizing proceeds by transferring bins, one by one,\n * from the table to the next table. However, threads claim small\n * blocks of indices to transfer (via field transferIndex) before\n * doing so, reducing contention. A generation stamp in field\n * sizeCtl ensures that resizings do not overlap. Because we are\n * using power-of-two expansion, the elements from each bin must\n * either stay at same index, or move with a power of two\n * offset. We eliminate unnecessary node creation by catching\n * cases where old nodes can be reused because their next fields\n * won't change. On average, only about one-sixth of them need\n * cloning when a table doubles. The nodes they replace will be\n * garbage collectible as soon as they are no longer referenced by\n * any reader thread that may be in the midst of concurrently\n * traversing table. Upon transfer, the old table bin contains\n * only a special forwarding node (with hash field \"MOVED\") that\n * contains the next table as its key. On encountering a\n * forwarding node, access and update operations restart, using\n * the new table.\n *\n * Each bin transfer requires its bin lock, which can stall\n * waiting for locks while resizing. However, because other\n * threads can join in and help resize rather than contend for\n * locks, average aggregate waits become shorter as resizing\n * progresses. The transfer operation must also ensure that all\n * accessible bins in both the old and new table are usable by any\n * traversal. This is arranged in part by proceeding from the\n * last bin (table.length - 1) up towards the first. Upon seeing\n * a forwarding node, traversals (see class Traverser) arrange to\n * move to the new table without revisiting nodes. To ensure that\n * no intervening nodes are skipped even when moved out of order,\n * a stack (see class TableStack) is created on first encounter of\n * a forwarding node during a traversal, to maintain its place if\n * later processing the current table. The need for these\n * save/restore mechanics is relatively rare, but when one\n * forwarding node is encountered, typically many more will be.\n * So Traversers use a simple caching scheme to avoid creating so\n * many new TableStack nodes. (Thanks to Peter Levart for\n * suggesting use of a stack here.)\n *\n * The traversal scheme also applies to partial traversals of\n * ranges of bins (via an alternate Traverser constructor)\n * to support partitioned aggregate operations. Also, read-only\n * operations give up if ever forwarded to a null table, which\n * provides support for shutdown-style clearing, which is also not\n * currently implemented.\n *\n * Lazy table initialization minimizes footprint until first use,\n * and also avoids resizings when the first operation is from a\n * putAll, constructor with map argument, or deserialization.\n * These cases attempt to override the initial capacity settings,\n * but harmlessly fail to take effect in cases of races.\n *\n * The element count is maintained using a specialization of\n * LongAdder. We need to incorporate a specialization rather than\n * just use a LongAdder in order to access implicit\n * contention-sensing that leads to creation of multiple\n * CounterCells. The counter mechanics avoid contention on\n * updates but can encounter cache thrashing if read too\n * frequently during concurrent access. To avoid reading so often,\n * resizing under contention is attempted only upon adding to a\n * bin already holding two or more nodes. Under uniform hash\n * distributions, the probability of this occurring at threshold\n * is around 13%, meaning that only about 1 in 8 puts check\n * threshold (and after resizing, many fewer do so).\n *\n * TreeBins use a special form of comparison for search and\n * related operations (which is the main reason we cannot use\n * existing collections such as TreeMaps). TreeBins contain\n * Comparable elements, but may contain others, as well as\n * elements that are Comparable but not necessarily Comparable for\n * the same T, so we cannot invoke compareTo among them. To handle\n * this, the tree is ordered primarily by hash value, then by\n * Comparable.compareTo order if applicable. On lookup at a node,\n * if elements are not comparable or compare as 0 then both left\n * and right children may need to be searched in the case of tied\n * hash values. (This corresponds to the full list search that\n * would be necessary if all elements were non-Comparable and had\n * tied hashes.) On insertion, to keep a total ordering (or as\n * close as is required here) across rebalancings, we compare\n * classes and identityHashCodes as tie-breakers. The red-black\n * balancing code is updated from pre-jdk-collections\n * (http://example.com)\n * based in turn on Cormen, Leiserson, and Rivest \"Introduction to\n * Algorithms\" (CLR).\n *\n * TreeBins also require an additional locking mechanism. While\n * list traversal is always possible by readers even during\n * updates, tree traversal is not, mainly because of tree-rotations\n * that may change the root node and/or its linkages. TreeBins\n * include a simple read-write lock mechanism parasitic on the\n * main bin-synchronization strategy: Structural adjustments\n * associated with an insertion or removal are already bin-locked\n * (and so cannot conflict with other writers) but must wait for\n * ongoing readers to finish. Since there can be only one such\n * waiter, we use a simple scheme using a single \"waiter\" field to\n * block writers. However, readers need never block. If the root\n * lock is held, they proceed along the slow traversal path (via\n * next-pointers) until the lock becomes available or the list is\n * exhausted, whichever comes first. These cases are not fast, but\n * maximize aggregate expected throughput.\n *\n * Maintaining API and serialization compatibility with previous\n * versions of this class introduces several oddities. Mainly: We\n * leave untouched but unused constructor arguments referring to\n * concurrencyLevel. We accept a loadFactor constructor argument,\n * but apply it only to initial table capacity (which is the only\n * time that we can guarantee to honor it.) We also declare an\n * unused \"Segment\" class that is instantiated in minimal form\n * only when serializing.\n *\n * Also, solely for compatibility with previous versions of this\n * class, it extends AbstractMap, even though all of its methods\n * are overridden, so it is just useless baggage.\n *\n * This file is organized to make things a little easier to follow\n * while reading than they might otherwise: First the main static\n * declarations and utilities, then fields, then main public\n * methods (with a few factorings of multiple public methods into\n * internal ones), then sizing methods, trees, traversers, and\n * bulk operations.\n */\n /**\n * The largest possible table capacity. This value must be\n * exactly 1<<30 to stay within Java array allocation and indexing\n * bounds for power of two table sizes, and is further required\n * because the top two bits of 32bit hash fields are used for\n * control purposes.\n */\n private static final int MAXIMUM_CAPACITY = 1 << 30;\n\n /**\n * The default initial table capacity. Must be a power of 2\n * (i.e., at least 1) and at most MAXIMUM_CAPACITY.\n */\n private static final int DEFAULT_CAPACITY = 16;\n\n /**\n * The largest possible (non-power of two) array size.\n * Needed by toArray and related methods.\n */\n static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;\n\n /**\n * The default concurrency level for this table. Unused but\n * defined for compatibility with previous versions of this class.\n */\n private static final int DEFAULT_CONCURRENCY_LEVEL = 16;\n\n /**\n * The load factor for this table. Overrides of this value in\n * constructors affect only the initial table capacity. The\n * actual floating point value isn't normally used -- it is\n * simpler to use expressions such as {@code n - (n >>> 2)} for\n * the associated resizing threshold.\n */\n private static final float LOAD_FACTOR = 0.75f;\n\n /**\n * The bin count threshold for using a tree rather than list for a\n * bin. Bins are converted to trees when adding an element to a\n * bin with at least this many nodes. The value must be greater\n * than 2, and should be at least 8 to mesh with assumptions in\n * tree removal about conversion back to plain bins upon\n * shrinkage.\n */\n static final int TREEIFY_THRESHOLD = 8;\n\n /**\n * The bin count threshold for untreeifying a (split) bin during a\n * resize operation. Should be less than TREEIFY_THRESHOLD, and at\n * most 6 to mesh with shrinkage detection under removal.\n */\n static final int UNTREEIFY_THRESHOLD = 6;\n\n /**\n * The smallest table capacity for which bins may be treeified.\n * (Otherwise the table is resized if too many nodes in a bin.)\n * The value should be at least 4 * TREEIFY_THRESHOLD to avoid\n * conflicts between resizing and treeification thresholds.\n */\n static final int MIN_TREEIFY_CAPACITY = 64;\n\n /**\n * Minimum number of rebinnings per transfer step. Ranges are\n * subdivided to allow multiple resizer threads. This value\n * serves as a lower bound to avoid resizers encountering\n * excessive memory contention. The value should be at least\n * DEFAULT_CAPACITY.\n */\n private static final int MIN_TRANSFER_STRIDE = 16;\n\n /**\n * The number of bits used for generation stamp in sizeCtl.\n * Must be at least 6 for 32bit arrays.\n */\n private static final int RESIZE_STAMP_BITS = 16;\n\n /**\n * The maximum number of threads that can help resize.\n * Must fit in 32 - RESIZE_STAMP_BITS bits.\n */\n private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;\n\n /**\n * The bit shift for recording size stamp in sizeCtl.\n */\n private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;\n\n /*\n * Encodings for Node hash fields. See above for explanation.\n */\n // hash for forwarding nodes\n static final int MOVED = -1;\n\n // hash for roots of trees\n static final int TREEBIN = -2;\n\n static final int RESERVED = -3;\n\n // usable bits of normal node hash\n static final int HASH_BITS = 0x7fffffff;\n\n /**\n * Number of CPUS, to place bounds on some sizings\n */\n static final int NCPU = Runtime.getRuntime().availableProcessors();\n\n /**\n * Serialized pseudo-fields, provided only for jdk7 compatibility.\n * @serialField segments Segment[]\n * The segments, each of which is a specialized hash table.\n * @serialField segmentMask int\n * Mask value for indexing into segments. The upper bits of a\n * key's hash code are used to choose the segment.\n * @serialField segmentShift int\n * Shift value for indexing within segments.\n */\n private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(\"segments\", Segment[].class), new ObjectStreamField(\"segmentMask\", Integer.TYPE), new ObjectStreamField(\"segmentShift\", Integer.TYPE) };\n\n /**\n * Key-value entry. This class is never exported out as a\n * user-mutable Map.Entry (i.e., one supporting setValue; see\n * MapEntry below), but can be used for read-only traversals used\n * in bulk tasks. Subclasses of Node with a negative hash field\n * are special, and contain null keys and values (but are never\n * exported). Otherwise, keys and vals are never null.\n */\n static class Node implements Map.Entry {\n\n final int hash;\n\n final K key;\n\n volatile V val;\n\n volatile Node next;\n\n Node(int hash, K key, V val) {\n this.hash = hash;\n this.key = key;\n this.val = val;\n }\n\n Node(int hash, K key, V val, Node next) {\n this(hash, key, val);\n this.next = next;\n }\n\n public final K getKey() {\n return key;\n }\n\n public final V getValue() {\n return val;\n }\n\n public final int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public final String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public final V setValue(V value) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean equals(Object o) {\n Object k, v, u;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == (u = val) || v.equals(u)));\n }\n\n /**\n * Virtualized support for map.get(); overridden in subclasses.\n */\n Node find(int h, Object k) {\n Node e = this;\n if (k != null) {\n do {\n K ek;\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n } while ((e = e.next) != null);\n }\n return null;\n }\n }\n\n /**\n * Spreads (XORs) higher bits of hash to lower and also forces top\n * bit to 0. Because the table uses power-of-two masking, sets of\n * hashes that vary only in bits above the current mask will\n * always collide. (Among known examples are sets of Float keys\n * holding consecutive whole numbers in small tables.) So we\n * apply a transform that spreads the impact of higher bits\n * downward. There is a tradeoff between speed, utility, and\n * quality of bit-spreading. Because many common sets of hashes\n * are already reasonably distributed (so don't benefit from\n * spreading), and because we use trees to handle large sets of\n * collisions in bins, we just XOR some shifted bits in the\n * cheapest possible way to reduce systematic lossage, as well as\n * to incorporate impact of the highest bits that would otherwise\n * never be used in index calculations because of table bounds.\n */\n static final int spread(int h) {\n return (h ^ (h >>> 16)) & HASH_BITS;\n }\n\n /**\n * Returns a power of two table size for the given desired capacity.\n * See Hackers Delight, sec 3.2\n */\n private static final int tableSizeFor(int c) {\n int n = -1 >>> Integer.numberOfLeadingZeros(c - 1);\n return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;\n }\n\n /**\n * Returns x's Class if it is of the form \"class C implements\n * Comparable\", else null.\n */\n static Class comparableClassFor(Object x) {\n if (x instanceof Comparable) {\n Class c;\n Type[] ts, as;\n ParameterizedType p;\n if (// bypass checks\n (c = x.getClass()) == String.class)\n return c;\n if ((ts = c.getGenericInterfaces()) != null) {\n for (Type t : ts) {\n if ((t instanceof ParameterizedType) && ((p = (ParameterizedType) t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && // type arg is c\n as[0] == c)\n return c;\n }\n }\n }\n return null;\n }\n\n /**\n * Returns k.compareTo(x) if x matches kc (k's screened comparable\n * class), else 0.\n */\n // for cast to Comparable\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n static int compareComparables(Class kc, Object k, Object x) {\n return (x == null || x.getClass() != kc ? 0 : ((Comparable) k).compareTo(x));\n }\n\n /* ---------------- Table element access -------------- */\n /*\n * Atomic access methods are used for table elements as well as\n * elements of in-progress next table while resizing. All uses of\n * the tab arguments must be null checked by callers. All callers\n * also paranoically precheck that tab's length is not zero (or an\n * equivalent check), thus ensuring that any index argument taking\n * the form of a hash value anded with (length - 1) is a valid\n * index. Note that, to be correct wrt arbitrary concurrency\n * errors by users, these checks must operate on local variables,\n * which accounts for some odd-looking inline assignments below.\n * Note that calls to setTabAt always occur within locked regions,\n * and so require only release ordering.\n */\n @SuppressWarnings(\"unchecked\")\n static final Node tabAt(Node[] tab, int i) {\n return (Node) U.getReferenceAcquire(tab, ((long) i << ASHIFT) + ABASE);\n }\n\n static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {\n return U.compareAndSetReference(tab, ((long) i << ASHIFT) + ABASE, c, v);\n }\n\n static final void setTabAt(Node[] tab, int i, Node v) {\n U.putReferenceRelease(tab, ((long) i << ASHIFT) + ABASE, v);\n }\n\n /**\n * The array of bins. Lazily initialized upon first insertion.\n * Size is always a power of two. Accessed directly by iterators.\n */\n transient volatile Node[] table;\n\n /**\n * The next table to use; non-null only while resizing.\n */\n private transient volatile Node[] nextTable;\n\n /**\n * Base counter value, used mainly when there is no contention,\n * but also as a fallback during table initialization\n * races. Updated via CAS.\n */\n private transient volatile long baseCount;\n\n /**\n * Table initialization and resizing control. When negative, the\n * table is being initialized or resized: -1 for initialization,\n * else -(1 + the number of active resizing threads). Otherwise,\n * when table is null, holds the initial table size to use upon\n * creation, or 0 for default. After initialization, holds the\n * next element count value upon which to resize the table.\n */\n private transient volatile int sizeCtl;\n\n /**\n * The next table index (plus one) to split while resizing.\n */\n private transient volatile int transferIndex;\n\n /**\n * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.\n */\n private transient volatile int cellsBusy;\n\n /**\n * Table of counter cells. When non-null, size is a power of 2.\n */\n private transient volatile CounterCell[] counterCells;\n\n // views\n private transient KeySetView keySet;\n\n private transient ValuesView values;\n\n private transient EntrySetView entrySet;\n\n /**\n * Creates a new, empty map with the default initial table size (16).\n */\n public ConcurrentHashMap() {\n }\n\n /**\n * Creates a new, empty map with an initial table size\n * accommodating the specified number of elements without the need\n * to dynamically resize.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n */\n public ConcurrentHashMap(int initialCapacity) {\n this(initialCapacity, LOAD_FACTOR, 1);\n }\n\n /**\n * Creates a new map with the same mappings as the given map.\n *\n * @param m the map\n */\n public ConcurrentHashMap(Map m) {\n this.sizeCtl = DEFAULT_CAPACITY;\n putAll(m);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}) and\n * initial table density ({@code loadFactor}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative or the load factor is nonpositive\n *\n * @since 1.6\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor) {\n this(initialCapacity, loadFactor, 1);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}), initial\n * table density ({@code loadFactor}), and number of concurrently\n * updating threads ({@code concurrencyLevel}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @param concurrencyLevel the estimated number of concurrently\n * updating threads. The implementation may use this value as\n * a sizing hint.\n * @throws IllegalArgumentException if the initial capacity is\n * negative or the load factor or concurrencyLevel are\n * nonpositive\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) {\n if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)\n throw new IllegalArgumentException();\n if (// Use at least as many bins\n initialCapacity < concurrencyLevel)\n // as estimated threads\n initialCapacity = concurrencyLevel;\n long size = (long) (1.0 + (long) initialCapacity / loadFactor);\n int cap = (size >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) size);\n this.sizeCtl = cap;\n }\n\n // Original (since JDK1.2) Map methods\n public int size() {\n long n = sumCount();\n return ((n < 0L) ? 0 : (n > (long) Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) n);\n }\n\n public boolean isEmpty() {\n // ignore transient negative values\n return sumCount() <= 0L;\n }\n\n /**\n * Returns the value to which the specified key is mapped,\n * or {@code null} if this map contains no mapping for the key.\n *\n *

More formally, if this map contains a mapping from a key\n * {@code k} to a value {@code v} such that {@code key.equals(k)},\n * then this method returns {@code v}; otherwise it returns\n * {@code null}. (There can be at most one such mapping.)\n *\n * @throws NullPointerException if the specified key is null\n */\n public V get(Object key) {\n Node[] tab;\n Node e, p;\n int n, eh;\n K ek;\n int h = spread(key.hashCode());\n if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) {\n if ((eh = e.hash) == h) {\n if ((ek = e.key) == key || (ek != null && key.equals(ek)))\n return e.val;\n } else if (eh < 0)\n return (p = e.find(h, key)) != null ? p.val : null;\n while ((e = e.next) != null) {\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek))))\n return e.val;\n }\n }\n return null;\n }\n\n /**\n * Tests if the specified object is a key in this table.\n *\n * @param key possible key\n * @return {@code true} if and only if the specified object\n * is a key in this table, as determined by the\n * {@code equals} method; {@code false} otherwise\n * @throws NullPointerException if the specified key is null\n */\n public boolean containsKey(Object key) {\n return get(key) != null;\n }\n\n /**\n * Returns {@code true} if this map maps one or more keys to the\n * specified value. Note: This method may require a full traversal\n * of the map, and is much slower than method {@code containsKey}.\n *\n * @param value value whose presence in this map is to be tested\n * @return {@code true} if this map maps one or more keys to the\n * specified value\n * @throws NullPointerException if the specified value is null\n */\n public boolean containsValue(Object value) {\n if (value == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V v;\n if ((v = p.val) == value || (v != null && value.equals(v)))\n return true;\n }\n }\n return false;\n }\n\n /**\n * Maps the specified key to the specified value in this table.\n * Neither the key nor the value can be null.\n *\n *

The value can be retrieved by calling the {@code get} method\n * with a key that is equal to the original key.\n *\n * @param key key with which the specified value is to be associated\n * @param value value to be associated with the specified key\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key or value is null\n */\n public V put(K key, V value) {\n return putVal(key, value, false);\n }\n\n /**\n * Implementation for put and putIfAbsent\n */\n final V putVal(K key, V value, boolean onlyIfAbsent) {\n if (key == null || value == null)\n throw new NullPointerException();\n int hash = spread(key.hashCode());\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {\n if (casTabAt(tab, i, null, new Node(hash, key, value)))\n // no lock when adding to empty bin\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n onlyIfAbsent && fh == hash && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n V oldVal = null;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n oldVal = e.val;\n if (!onlyIfAbsent)\n e.val = value;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n pred.next = new Node(hash, key, value);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n Node p;\n binCount = 2;\n if ((p = ((TreeBin) f).putTreeVal(hash, key, value)) != null) {\n oldVal = p.val;\n if (!onlyIfAbsent)\n p.val = value;\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (oldVal != null)\n return oldVal;\n break;\n }\n }\n }\n addCount(1L, binCount);\n return null;\n }\n\n /**\n * Copies all of the mappings from the specified map to this one.\n * These mappings replace any mappings that this map had for any of the\n * keys currently in the specified map.\n *\n * @param m mappings to be stored in this map\n */\n public void putAll(Map m) {\n tryPresize(m.size());\n for (Map.Entry e : m.entrySet()) putVal(e.getKey(), e.getValue(), false);\n }\n\n /**\n * Removes the key (and its corresponding value) from this map.\n * This method does nothing if the key is not in the map.\n *\n * @param key the key that needs to be removed\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key is null\n */\n public V remove(Object key) {\n return replaceNode(key, null, null);\n }\n\n /**\n * Implementation for the four public remove/replace methods:\n * Replaces node value with v, conditional upon match of cv if\n * non-null. If resulting value is null, delete.\n */\n final V replaceNode(Object key, V value, Object cv) {\n int hash = spread(key.hashCode());\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0 || (f = tabAt(tab, i = (n - 1) & hash)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n V oldVal = null;\n boolean validated = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n validated = true;\n for (Node e = f, pred = null; ; ) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n V ev = e.val;\n if (cv == null || cv == ev || (ev != null && cv.equals(ev))) {\n oldVal = ev;\n if (value != null)\n e.val = value;\n else if (pred != null)\n pred.next = e.next;\n else\n setTabAt(tab, i, e.next);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n validated = true;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(hash, key, null)) != null) {\n V pv = p.val;\n if (cv == null || cv == pv || (pv != null && cv.equals(pv))) {\n oldVal = pv;\n if (value != null)\n p.val = value;\n else if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (validated) {\n if (oldVal != null) {\n if (value == null)\n addCount(-1L, -1);\n return oldVal;\n }\n break;\n }\n }\n }\n return null;\n }\n\n /**\n * Removes all of the mappings from this map.\n */\n public void clear() {\n // negative number of deletions\n long delta = 0L;\n int i = 0;\n Node[] tab = table;\n while (tab != null && i < tab.length) {\n int fh;\n Node f = tabAt(tab, i);\n if (f == null)\n ++i;\n else if ((fh = f.hash) == MOVED) {\n tab = helpTransfer(tab, f);\n // restart\n i = 0;\n } else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node p = (fh >= 0 ? f : (f instanceof TreeBin) ? ((TreeBin) f).first : null);\n while (p != null) {\n --delta;\n p = p.next;\n }\n setTabAt(tab, i++, null);\n }\n }\n }\n }\n if (delta != 0L)\n addCount(delta, -1);\n }\n\n /**\n * Returns a {@link Set} view of the keys contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from this map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations. It does not support the {@code add} or\n * {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public KeySetView keySet() {\n KeySetView ks;\n if ((ks = keySet) != null)\n return ks;\n return keySet = new KeySetView(this, null);\n }\n\n /**\n * Returns a {@link Collection} view of the values contained in this map.\n * The collection is backed by the map, so changes to the map are\n * reflected in the collection, and vice-versa. The collection\n * supports element removal, which removes the corresponding\n * mapping from this map, via the {@code Iterator.remove},\n * {@code Collection.remove}, {@code removeAll},\n * {@code retainAll}, and {@code clear} operations. It does not\n * support the {@code add} or {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}\n * and {@link Spliterator#NONNULL}.\n *\n * @return the collection view\n */\n public Collection values() {\n ValuesView vs;\n if ((vs = values) != null)\n return vs;\n return values = new ValuesView(this);\n }\n\n /**\n * Returns a {@link Set} view of the mappings contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from the map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public Set> entrySet() {\n EntrySetView es;\n if ((es = entrySet) != null)\n return es;\n return entrySet = new EntrySetView(this);\n }\n\n /**\n * Returns the hash code value for this {@link Map}, i.e.,\n * the sum of, for each key-value pair in the map,\n * {@code key.hashCode() ^ value.hashCode()}.\n *\n * @return the hash code value for this map\n */\n public int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) h += p.key.hashCode() ^ p.val.hashCode();\n }\n return h;\n }\n\n /**\n * Returns a string representation of this map. The string\n * representation consists of a list of key-value mappings (in no\n * particular order) enclosed in braces (\"{@code {}}\"). Adjacent\n * mappings are separated by the characters {@code \", \"} (comma\n * and space). Each key-value mapping is rendered as the key\n * followed by an equals sign (\"{@code =}\") followed by the\n * associated value.\n *\n * @return a string representation of this map\n */\n public String toString() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n StringBuilder sb = new StringBuilder();\n sb.append('{');\n Node p;\n if ((p = it.advance()) != null) {\n for (; ; ) {\n K k = p.key;\n V v = p.val;\n sb.append(k == this ? \"(this Map)\" : k);\n sb.append('=');\n sb.append(v == this ? \"(this Map)\" : v);\n if ((p = it.advance()) == null)\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append('}').toString();\n }\n\n /**\n * Compares the specified object with this map for equality.\n * Returns {@code true} if the given object is a map with the same\n * mappings as this map. This operation may return misleading\n * results if either map is concurrently modified during execution\n * of this method.\n *\n * @param o object to be compared for equality with this map\n * @return {@code true} if the specified object is equal to this map\n */\n public boolean equals(Object o) {\n if (o != this) {\n if (!(o instanceof Map))\n return false;\n Map m = (Map) o;\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n for (Node p; (p = it.advance()) != null; ) {\n V val = p.val;\n Object v = m.get(p.key);\n if (v == null || (v != val && !v.equals(val)))\n return false;\n }\n for (Map.Entry e : m.entrySet()) {\n Object mk, mv, v;\n if ((mk = e.getKey()) == null || (mv = e.getValue()) == null || (v = get(mk)) == null || (mv != v && !mv.equals(v)))\n return false;\n }\n }\n return true;\n }\n\n /**\n * Stripped-down version of helper class used in previous version,\n * declared for the sake of serialization compatibility.\n */\n static class Segment extends ReentrantLock implements Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n final float loadFactor;\n\n Segment(float lf) {\n this.loadFactor = lf;\n }\n }\n\n /**\n * Saves this map to a stream (that is, serializes it).\n *\n * @param s the stream\n * @throws java.io.IOException if an I/O error occurs\n * @serialData\n * the serialized fields, followed by the key (Object) and value\n * (Object) for each key-value mapping, followed by a null pair.\n * The key-value mappings are emitted in no particular order.\n */\n private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {\n // For serialization compatibility\n // Emulate segment calculation from previous version of this class\n int sshift = 0;\n int ssize = 1;\n while (ssize < DEFAULT_CONCURRENCY_LEVEL) {\n ++sshift;\n ssize <<= 1;\n }\n int segmentShift = 32 - sshift;\n int segmentMask = ssize - 1;\n @SuppressWarnings(\"unchecked\")\n Segment[] segments = (Segment[]) new Segment[DEFAULT_CONCURRENCY_LEVEL];\n for (int i = 0; i < segments.length; ++i) segments[i] = new Segment(LOAD_FACTOR);\n java.io.ObjectOutputStream.PutField streamFields = s.putFields();\n streamFields.put(\"segments\", segments);\n streamFields.put(\"segmentShift\", segmentShift);\n streamFields.put(\"segmentMask\", segmentMask);\n s.writeFields();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n s.writeObject(p.key);\n s.writeObject(p.val);\n }\n }\n s.writeObject(null);\n s.writeObject(null);\n }\n\n /**\n * Reconstitutes this map from a stream (that is, deserializes it).\n * @param s the stream\n * @throws ClassNotFoundException if the class of a serialized object\n * could not be found\n * @throws java.io.IOException if an I/O error occurs\n */\n private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {\n /*\n * To improve performance in typical cases, we create nodes\n * while reading, then place in table once size is known.\n * However, we must also validate uniqueness and deal with\n * overpopulated bins while doing so, which requires\n * specialized versions of putVal mechanics.\n */\n // force exclusion for table construction\n sizeCtl = -1;\n s.defaultReadObject();\n long size = 0L;\n Node p = null;\n for (; ; ) {\n @SuppressWarnings(\"unchecked\")\n K k = (K) s.readObject();\n @SuppressWarnings(\"unchecked\")\n V v = (V) s.readObject();\n if (k != null && v != null) {\n p = new Node(spread(k.hashCode()), k, v, p);\n ++size;\n } else\n break;\n }\n if (size == 0L)\n sizeCtl = 0;\n else {\n long ts = (long) (1.0 + size / LOAD_FACTOR);\n int n = (ts >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) ts);\n @SuppressWarnings(\"unchecked\")\n Node[] tab = (Node[]) new Node[n];\n int mask = n - 1;\n long added = 0L;\n while (p != null) {\n boolean insertAtFront;\n Node next = p.next, first;\n int h = p.hash, j = h & mask;\n if ((first = tabAt(tab, j)) == null)\n insertAtFront = true;\n else {\n K k = p.key;\n if (first.hash < 0) {\n TreeBin t = (TreeBin) first;\n if (t.putTreeVal(h, k, p.val) == null)\n ++added;\n insertAtFront = false;\n } else {\n int binCount = 0;\n insertAtFront = true;\n Node q;\n K qk;\n for (q = first; q != null; q = q.next) {\n if (q.hash == h && ((qk = q.key) == k || (qk != null && k.equals(qk)))) {\n insertAtFront = false;\n break;\n }\n ++binCount;\n }\n if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {\n insertAtFront = false;\n ++added;\n p.next = first;\n TreeNode hd = null, tl = null;\n for (q = p; q != null; q = q.next) {\n TreeNode t = new TreeNode(q.hash, q.key, q.val, null, null);\n if ((t.prev = tl) == null)\n hd = t;\n else\n tl.next = t;\n tl = t;\n }\n setTabAt(tab, j, new TreeBin(hd));\n }\n }\n }\n if (insertAtFront) {\n ++added;\n p.next = first;\n setTabAt(tab, j, p);\n }\n p = next;\n }\n table = tab;\n sizeCtl = n - (n >>> 2);\n baseCount = added;\n }\n }\n\n // ConcurrentMap methods\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V putIfAbsent(K key, V value) {\n return putVal(key, value, true);\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object key, Object value) {\n if (key == null)\n throw new NullPointerException();\n return value != null && replaceNode(key, null, value) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if any of the arguments are null\n */\n public boolean replace(K key, V oldValue, V newValue) {\n if (key == null || oldValue == null || newValue == null)\n throw new NullPointerException();\n return replaceNode(key, newValue, oldValue) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V replace(K key, V value) {\n if (key == null || value == null)\n throw new NullPointerException();\n return replaceNode(key, value, null);\n }\n\n // Overrides of JDK8+ Map extension method defaults\n /**\n * Returns the value to which the specified key is mapped, or the\n * given default value if this map contains no mapping for the\n * key.\n *\n * @param key the key whose associated value is to be returned\n * @param defaultValue the value to return if this map contains\n * no mapping for the given key\n * @return the mapping for the key, if present; else the default value\n * @throws NullPointerException if the specified key is null\n */\n public V getOrDefault(Object key, V defaultValue) {\n V v;\n return (v = get(key)) == null ? defaultValue : v;\n }\n\n public void forEach(BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n action.accept(p.key, p.val);\n }\n }\n }\n\n public void replaceAll(BiFunction function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V oldValue = p.val;\n for (K key = p.key; ; ) {\n V newValue = function.apply(key, oldValue);\n if (newValue == null)\n throw new NullPointerException();\n if (replaceNode(key, newValue, oldValue) != null || (oldValue = get(key)) == null)\n break;\n }\n }\n }\n }\n\n boolean removeEntryIf(Predicate> function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n Map.Entry e = new AbstractMap.SimpleImmutableEntry<>(k, v);\n if (function.test(e) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n boolean removeValueIf(Predicate function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n if (function.test(v) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n /**\n * If the specified key is not already associated with a value,\n * attempts to compute its value using the given mapping function\n * and enters it into this map unless {@code null}. The entire\n * method invocation is performed atomically. The supplied\n * function is invoked exactly once per invocation of this method\n * if the key is absent, else not at all. Some attempted update\n * operations on this map by other threads may be blocked while\n * computation is in progress, so the computation should be short\n * and simple.\n *\n *

The mapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param mappingFunction the function to compute a value\n * @return the current (existing or computed) value associated with\n * the specified key, or null if the computed value is null\n * @throws NullPointerException if the specified key or mappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the mappingFunction does so,\n * in which case the mapping is left unestablished\n */\n public V computeIfAbsent(K key, Function mappingFunction) {\n if (key == null || mappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = mappingFunction.apply(key)) != null)\n node = new Node(h, key, val);\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n fh == h && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n boolean added = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = e.val;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n if ((val = mappingFunction.apply(key)) != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n added = true;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null)\n val = p.val;\n else if ((val = mappingFunction.apply(key)) != null) {\n added = true;\n t.putTreeVal(h, key, val);\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (!added)\n return val;\n break;\n }\n }\n }\n if (val != null)\n addCount(1L, binCount);\n return val;\n }\n\n /**\n * If the value for the specified key is present, attempts to\n * compute a new mapping given the key and its current mapped\n * value. The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method if the key is present, else not at all. Some\n * attempted update operations on this map by other threads may be\n * blocked while computation is in progress, so the computation\n * should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which a value may be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V computeIfPresent(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null) {\n val = remappingFunction.apply(key, p.val);\n if (val != null)\n p.val = val;\n else {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0)\n break;\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * Attempts to compute a mapping for the specified key and its\n * current mapped value (or {@code null} if there is no current\n * mapping). The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method. Some attempted update operations on this map by\n * other threads may be blocked while computation is in progress,\n * so the computation should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V compute(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = remappingFunction.apply(key, null)) != null) {\n delta = 1;\n node = new Node(h, key, val);\n }\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n val = remappingFunction.apply(key, null);\n if (val != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n delta = 1;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 1;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null)\n p = r.findTreeNode(h, key, null);\n else\n p = null;\n V pv = (p == null) ? null : p.val;\n val = remappingFunction.apply(key, pv);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * If the specified key is not already associated with a\n * (non-null) value, associates it with the given value.\n * Otherwise, replaces the value with the results of the given\n * remapping function, or removes if {@code null}. The entire\n * method invocation is performed atomically. Some attempted\n * update operations on this map by other threads may be blocked\n * while computation is in progress, so the computation should be\n * short and simple, and must not attempt to update any other\n * mappings of this Map.\n *\n * @param key key with which the specified value is to be associated\n * @param value the value to use if absent\n * @param remappingFunction the function to recompute a value if present\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or the\n * remappingFunction is null\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V merge(K key, V value, BiFunction remappingFunction) {\n if (key == null || value == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n if (casTabAt(tab, i, null, new Node(h, key, value))) {\n delta = 1;\n val = value;\n break;\n }\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(e.val, value);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n delta = 1;\n val = value;\n pred.next = new Node(h, key, val);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r = t.root;\n TreeNode p = (r == null) ? null : r.findTreeNode(h, key, null);\n val = (p == null) ? value : remappingFunction.apply(p.val, value);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n // Hashtable legacy methods\n /**\n * Tests if some key maps into the specified value in this table.\n *\n *

Note that this method is identical in functionality to\n * {@link #containsValue(Object)}, and exists solely to ensure\n * full compatibility with class {@link java.util.Hashtable},\n * which supported this method prior to introduction of the\n * Java Collections Framework.\n *\n * @param value a value to search for\n * @return {@code true} if and only if some key maps to the\n * {@code value} argument in this table as\n * determined by the {@code equals} method;\n * {@code false} otherwise\n * @throws NullPointerException if the specified value is null\n */\n public boolean contains(Object value) {\n return containsValue(value);\n }\n\n /**\n * Returns an enumeration of the keys in this table.\n *\n * @return an enumeration of the keys in this table\n * @see #keySet()\n */\n public Enumeration keys() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, this);\n }\n\n /**\n * Returns an enumeration of the values in this table.\n *\n * @return an enumeration of the values in this table\n * @see #values()\n */\n public Enumeration elements() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, this);\n }\n\n // ConcurrentHashMap-only methods\n /**\n * Returns the number of mappings. This method should be used\n * instead of {@link #size} because a ConcurrentHashMap may\n * contain more mappings than can be represented as an int. The\n * value returned is an estimate; the actual count may differ if\n * there are concurrent insertions or removals.\n *\n * @return the number of mappings\n * @since 1.8\n */\n public long mappingCount() {\n long n = sumCount();\n // ignore transient negative values\n return (n < 0L) ? 0L : n;\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param the element type of the returned set\n * @return the new set\n * @since 1.8\n */\n public static KeySetView newKeySet() {\n return new KeySetView(new ConcurrentHashMap(), Boolean.TRUE);\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @param the element type of the returned set\n * @return the new set\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n * @since 1.8\n */\n public static KeySetView newKeySet(int initialCapacity) {\n return new KeySetView(new ConcurrentHashMap(initialCapacity), Boolean.TRUE);\n }\n\n /**\n * Returns a {@link Set} view of the keys in this map, using the\n * given common mapped value for any additions (i.e., {@link\n * Collection#add} and {@link Collection#addAll(Collection)}).\n * This is of course only appropriate if it is acceptable to use\n * the same value for all additions from this view.\n *\n * @param mappedValue the mapped value to use for any additions\n * @return the set view\n * @throws NullPointerException if the mappedValue is null\n */\n public KeySetView keySet(V mappedValue) {\n if (mappedValue == null)\n throw new NullPointerException();\n return new KeySetView(this, mappedValue);\n }\n\n /**\n * A node inserted at head of bins during transfer operations.\n */\n static final class ForwardingNode extends Node {\n\n final Node[] nextTable;\n\n ForwardingNode(Node[] tab) {\n super(MOVED, null, null);\n this.nextTable = tab;\n }\n\n Node find(int h, Object k) {\n // loop to avoid arbitrarily deep recursion on forwarding nodes\n outer: for (Node[] tab = nextTable; ; ) {\n Node e;\n int n;\n if (k == null || tab == null || (n = tab.length) == 0 || (e = tabAt(tab, (n - 1) & h)) == null)\n return null;\n for (; ; ) {\n int eh;\n K ek;\n if ((eh = e.hash) == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n if (eh < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n continue outer;\n } else\n return e.find(h, k);\n }\n if ((e = e.next) == null)\n return null;\n }\n }\n }\n }\n\n /**\n * A place-holder node used in computeIfAbsent and compute.\n */\n static final class ReservationNode extends Node {\n\n ReservationNode() {\n super(RESERVED, null, null);\n }\n\n Node find(int h, Object k) {\n return null;\n }\n }\n\n /* ---------------- Table Initialization and Resizing -------------- */\n /**\n * Returns the stamp bits for resizing a table of size n.\n * Must be negative when shifted left by RESIZE_STAMP_SHIFT.\n */\n static final int resizeStamp(int n) {\n return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));\n }\n\n /**\n * Initializes table, using the size recorded in sizeCtl.\n */\n private final Node[] initTable() {\n Node[] tab;\n int sc;\n while ((tab = table) == null || tab.length == 0) {\n if ((sc = sizeCtl) < 0)\n // lost initialization race; just spin\n Thread.yield();\n else if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if ((tab = table) == null || tab.length == 0) {\n int n = (sc > 0) ? sc : DEFAULT_CAPACITY;\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = tab = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n break;\n }\n }\n return tab;\n }\n\n /**\n * Adds to count, and if table is too small and not already\n * resizing, initiates transfer. If already resizing, helps\n * perform transfer if work is available. Rechecks occupancy\n * after a transfer to see if another resize is already needed\n * because resizings are lagging additions.\n *\n * @param x the count to add\n * @param check if <0, don't check resize, if <= 1 only check if uncontended\n */\n private final void addCount(long x, int check) {\n CounterCell[] cs;\n long b, s;\n if ((cs = counterCells) != null || !U.compareAndSetLong(this, BASECOUNT, b = baseCount, s = b + x)) {\n CounterCell c;\n long v;\n int m;\n boolean uncontended = true;\n if (cs == null || (m = cs.length - 1) < 0 || (c = cs[ThreadLocalRandom.getProbe() & m]) == null || !(uncontended = U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))) {\n fullAddCount(x, uncontended);\n return;\n }\n if (check <= 1)\n return;\n s = sumCount();\n }\n if (check >= 0) {\n Node[] tab, nt;\n int n, sc;\n while (s >= (long) (sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) {\n int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT;\n if (sc < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || (nt = nextTable) == null || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1))\n transfer(tab, nt);\n } else if (U.compareAndSetInt(this, SIZECTL, sc, rs + 2))\n transfer(tab, null);\n s = sumCount();\n }\n }\n }\n\n /**\n * Helps transfer if a resize is in progress.\n */\n final Node[] helpTransfer(Node[] tab, Node f) {\n Node[] nextTab;\n int sc;\n if (tab != null && (f instanceof ForwardingNode) && (nextTab = ((ForwardingNode) f).nextTable) != null) {\n int rs = resizeStamp(tab.length) << RESIZE_STAMP_SHIFT;\n while (nextTab == nextTable && table == tab && (sc = sizeCtl) < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1)) {\n transfer(tab, nextTab);\n break;\n }\n }\n return nextTab;\n }\n return table;\n }\n\n /**\n * Tries to presize table to accommodate the given number of elements.\n *\n * @param size number of elements (doesn't need to be perfectly accurate)\n */\n private final void tryPresize(int size) {\n int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(size + (size >>> 1) + 1);\n int sc;\n while ((sc = sizeCtl) >= 0) {\n Node[] tab = table;\n int n;\n if (tab == null || (n = tab.length) == 0) {\n n = (sc > c) ? sc : c;\n if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if (table == tab) {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n }\n } else if (c <= sc || n >= MAXIMUM_CAPACITY)\n break;\n else if (tab == table) {\n int rs = resizeStamp(n);\n if (U.compareAndSetInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2))\n transfer(tab, null);\n }\n }\n }\n\n /**\n * Moves and/or copies the nodes in each bin to new table. See\n * above for explanation.\n */\n private final void transfer(Node[] tab, Node[] nextTab) {\n int n = tab.length, stride;\n if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)\n // subdivide range\n stride = MIN_TRANSFER_STRIDE;\n if (nextTab == null) {\n // initiating\n try {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n << 1];\n nextTab = nt;\n } catch (Throwable ex) {\n // try to cope with OOME\n sizeCtl = Integer.MAX_VALUE;\n return;\n }\n nextTable = nextTab;\n transferIndex = n;\n }\n int nextn = nextTab.length;\n ForwardingNode fwd = new ForwardingNode(nextTab);\n boolean advance = true;\n // to ensure sweep before committing nextTab\n boolean finishing = false;\n for (int i = 0, bound = 0; ; ) {\n Node f;\n int fh;\n while (advance) {\n int nextIndex, nextBound;\n if (--i >= bound || finishing)\n advance = false;\n else if ((nextIndex = transferIndex) <= 0) {\n i = -1;\n advance = false;\n } else if (U.compareAndSetInt(this, TRANSFERINDEX, nextIndex, nextBound = (nextIndex > stride ? nextIndex - stride : 0))) {\n bound = nextBound;\n i = nextIndex - 1;\n advance = false;\n }\n }\n if (i < 0 || i >= n || i + n >= nextn) {\n int sc;\n if (finishing) {\n nextTable = null;\n table = nextTab;\n sizeCtl = (n << 1) - (n >>> 1);\n return;\n }\n if (U.compareAndSetInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {\n if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)\n return;\n finishing = advance = true;\n // recheck before commit\n i = n;\n }\n } else if ((f = tabAt(tab, i)) == null)\n advance = casTabAt(tab, i, null, fwd);\n else if ((fh = f.hash) == MOVED)\n // already processed\n advance = true;\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node ln, hn;\n if (fh >= 0) {\n int runBit = fh & n;\n Node lastRun = f;\n for (Node p = f.next; p != null; p = p.next) {\n int b = p.hash & n;\n if (b != runBit) {\n runBit = b;\n lastRun = p;\n }\n }\n if (runBit == 0) {\n ln = lastRun;\n hn = null;\n } else {\n hn = lastRun;\n ln = null;\n }\n for (Node p = f; p != lastRun; p = p.next) {\n int ph = p.hash;\n K pk = p.key;\n V pv = p.val;\n if ((ph & n) == 0)\n ln = new Node(ph, pk, pv, ln);\n else\n hn = new Node(ph, pk, pv, hn);\n }\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof TreeBin) {\n TreeBin t = (TreeBin) f;\n TreeNode lo = null, loTail = null;\n TreeNode hi = null, hiTail = null;\n int lc = 0, hc = 0;\n for (Node e = t.first; e != null; e = e.next) {\n int h = e.hash;\n TreeNode p = new TreeNode(h, e.key, e.val, null, null);\n if ((h & n) == 0) {\n if ((p.prev = loTail) == null)\n lo = p;\n else\n loTail.next = p;\n loTail = p;\n ++lc;\n } else {\n if ((p.prev = hiTail) == null)\n hi = p;\n else\n hiTail.next = p;\n hiTail = p;\n ++hc;\n }\n }\n ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : (hc != 0) ? new TreeBin(lo) : t;\n hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : (lc != 0) ? new TreeBin(hi) : t;\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n }\n }\n }\n\n /**\n * A padded cell for distributing counts. Adapted from LongAdder\n * and Striped64. See their internal docs for explanation.\n */\n @jdk.internal.vm.annotation.Contended\n static final class CounterCell {\n\n volatile long value;\n\n CounterCell(long x) {\n value = x;\n }\n }\n\n final long sumCount() {\n CounterCell[] cs = counterCells;\n long sum = baseCount;\n if (cs != null) {\n for (CounterCell c : cs) if (c != null)\n sum += c.value;\n }\n return sum;\n }\n\n // See LongAdder version for explanation\n private final void fullAddCount(long x, boolean wasUncontended) {\n int h;\n if ((h = ThreadLocalRandom.getProbe()) == 0) {\n // force initialization\n ThreadLocalRandom.localInit();\n h = ThreadLocalRandom.getProbe();\n wasUncontended = true;\n }\n // True if last slot nonempty\n boolean collide = false;\n for (; ; ) {\n CounterCell[] cs;\n CounterCell c;\n int n;\n long v;\n if ((cs = counterCells) != null && (n = cs.length) > 0) {\n if ((c = cs[(n - 1) & h]) == null) {\n if (cellsBusy == 0) {\n // Try to attach new Cell\n // Optimistic create\n CounterCell r = new CounterCell(x);\n if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean created = false;\n try {\n // Recheck under lock\n CounterCell[] rs;\n int m, j;\n if ((rs = counterCells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) {\n rs[j] = r;\n created = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (created)\n break;\n // Slot is now non-empty\n continue;\n }\n }\n collide = false;\n } else if (// CAS already known to fail\n !wasUncontended)\n // Continue after rehash\n wasUncontended = true;\n else if (U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))\n break;\n else if (counterCells != cs || n >= NCPU)\n // At max size or stale\n collide = false;\n else if (!collide)\n collide = true;\n else if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n try {\n if (// Expand table unless stale\n counterCells == cs)\n counterCells = Arrays.copyOf(cs, n << 1);\n } finally {\n cellsBusy = 0;\n }\n collide = false;\n // Retry with expanded table\n continue;\n }\n h = ThreadLocalRandom.advanceProbe(h);\n } else if (cellsBusy == 0 && counterCells == cs && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean init = false;\n try {\n // Initialize table\n if (counterCells == cs) {\n CounterCell[] rs = new CounterCell[2];\n rs[h & 1] = new CounterCell(x);\n counterCells = rs;\n init = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (init)\n break;\n } else if (U.compareAndSetLong(this, BASECOUNT, v = baseCount, v + x))\n // Fall back on using base\n break;\n }\n }\n\n /**\n * Replaces all linked nodes in bin at given index unless table is\n * too small, in which case resizes instead.\n */\n private final void treeifyBin(Node[] tab, int index) {\n Node b;\n int n;\n if (tab != null) {\n if ((n = tab.length) < MIN_TREEIFY_CAPACITY)\n tryPresize(n << 1);\n else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {\n synchronized (b) {\n if (tabAt(tab, index) == b) {\n TreeNode hd = null, tl = null;\n for (Node e = b; e != null; e = e.next) {\n TreeNode p = new TreeNode(e.hash, e.key, e.val, null, null);\n if ((p.prev = tl) == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n setTabAt(tab, index, new TreeBin(hd));\n }\n }\n }\n }\n }\n\n /**\n * Returns a list of non-TreeNodes replacing those in given list.\n */\n static Node untreeify(Node b) {\n Node hd = null, tl = null;\n for (Node q = b; q != null; q = q.next) {\n Node p = new Node(q.hash, q.key, q.val);\n if (tl == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n return hd;\n }\n\n /**\n * Nodes for use in TreeBins.\n */\n static final class TreeNode extends Node {\n\n // red-black tree links\n TreeNode parent;\n\n TreeNode left;\n\n TreeNode right;\n\n // needed to unlink next upon deletion\n TreeNode prev;\n\n boolean red;\n\n TreeNode(int hash, K key, V val, Node next, TreeNode parent) {\n super(hash, key, val, next);\n this.parent = parent;\n }\n\n Node find(int h, Object k) {\n return findTreeNode(h, k, null);\n }\n\n /**\n * Returns the TreeNode (or null if not found) for the given key\n * starting at given root.\n */\n final TreeNode findTreeNode(int h, Object k, Class kc) {\n if (k != null) {\n TreeNode p = this;\n do {\n int ph, dir;\n K pk;\n TreeNode q;\n TreeNode pl = p.left, pr = p.right;\n if ((ph = p.hash) > h)\n p = pl;\n else if (ph < h)\n p = pr;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if (pl == null)\n p = pr;\n else if (pr == null)\n p = pl;\n else if ((kc != null || (kc = comparableClassFor(k)) != null) && (dir = compareComparables(kc, k, pk)) != 0)\n p = (dir < 0) ? pl : pr;\n else if ((q = pr.findTreeNode(h, k, kc)) != null)\n return q;\n else\n p = pl;\n } while (p != null);\n }\n return null;\n }\n }\n\n /**\n * TreeNodes used at the heads of bins. TreeBins do not hold user\n * keys or values, but instead point to list of TreeNodes and\n * their root. They also maintain a parasitic read-write lock\n * forcing writers (who hold bin lock) to wait for readers (who do\n * not) to complete before tree restructuring operations.\n */\n static final class TreeBin extends Node {\n\n TreeNode root;\n\n volatile TreeNode first;\n\n volatile Thread waiter;\n\n volatile int lockState;\n\n // values for lockState\n // set while holding write lock\n static final int WRITER = 1;\n\n // set when waiting for write lock\n static final int WAITER = 2;\n\n // increment value for setting read lock\n static final int READER = 4;\n\n /**\n * Tie-breaking utility for ordering insertions when equal\n * hashCodes and non-comparable. We don't require a total\n * order, just a consistent insertion rule to maintain\n * equivalence across rebalancings. Tie-breaking further than\n * necessary simplifies testing a bit.\n */\n static int tieBreakOrder(Object a, Object b) {\n int d;\n if (a == null || b == null || (d = a.getClass().getName().compareTo(b.getClass().getName())) == 0)\n d = (System.identityHashCode(a) <= System.identityHashCode(b) ? -1 : 1);\n return d;\n }\n\n /**\n * Creates bin with initial set of nodes headed by b.\n */\n TreeBin(TreeNode b) {\n super(TREEBIN, null, null);\n this.first = b;\n TreeNode r = null;\n for (TreeNode x = b, next; x != null; x = next) {\n next = (TreeNode) x.next;\n x.left = x.right = null;\n if (r == null) {\n x.parent = null;\n x.red = false;\n r = x;\n } else {\n K k = x.key;\n int h = x.hash;\n Class kc = null;\n for (TreeNode p = r; ; ) {\n int dir, ph;\n K pk = p.key;\n if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0)\n dir = tieBreakOrder(k, pk);\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n x.parent = xp;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n r = balanceInsertion(r, x);\n break;\n }\n }\n }\n }\n this.root = r;\n assert checkInvariants(root);\n }\n\n /**\n * Acquires write lock for tree restructuring.\n */\n private final void lockRoot() {\n if (!U.compareAndSetInt(this, LOCKSTATE, 0, WRITER))\n // offload to separate method\n contendedLock();\n }\n\n /**\n * Releases write lock for tree restructuring.\n */\n private final void unlockRoot() {\n lockState = 0;\n }\n\n /**\n * Possibly blocks awaiting root lock.\n */\n private final void contendedLock() {\n boolean waiting = false;\n for (int s; ; ) {\n if (((s = lockState) & ~WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, WRITER)) {\n if (waiting)\n waiter = null;\n return;\n }\n } else if ((s & WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, s | WAITER)) {\n waiting = true;\n waiter = Thread.currentThread();\n }\n } else if (waiting)\n LockSupport.park(this);\n }\n }\n\n /**\n * Returns matching node or null if none. Tries to search\n * using tree comparisons from root, but continues linear\n * search when lock not available.\n */\n final Node find(int h, Object k) {\n if (k != null) {\n for (Node e = first; e != null; ) {\n int s;\n K ek;\n if (((s = lockState) & (WAITER | WRITER)) != 0) {\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n e = e.next;\n } else if (U.compareAndSetInt(this, LOCKSTATE, s, s + READER)) {\n TreeNode r, p;\n try {\n p = ((r = root) == null ? null : r.findTreeNode(h, k, null));\n } finally {\n Thread w;\n if (U.getAndAddInt(this, LOCKSTATE, -READER) == (READER | WAITER) && (w = waiter) != null)\n LockSupport.unpark(w);\n }\n return p;\n }\n }\n }\n return null;\n }\n\n /**\n * Finds or adds a node.\n * @return null if added\n */\n final TreeNode putTreeVal(int h, K k, V v) {\n Class kc = null;\n boolean searched = false;\n for (TreeNode p = root; ; ) {\n int dir, ph;\n K pk;\n if (p == null) {\n first = root = new TreeNode(h, k, v, null, null);\n break;\n } else if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) {\n if (!searched) {\n TreeNode q, ch;\n searched = true;\n if (((ch = p.left) != null && (q = ch.findTreeNode(h, k, kc)) != null) || ((ch = p.right) != null && (q = ch.findTreeNode(h, k, kc)) != null))\n return q;\n }\n dir = tieBreakOrder(k, pk);\n }\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n TreeNode x, f = first;\n first = x = new TreeNode(h, k, v, f, xp);\n if (f != null)\n f.prev = x;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n if (!xp.red)\n x.red = true;\n else {\n lockRoot();\n try {\n root = balanceInsertion(root, x);\n } finally {\n unlockRoot();\n }\n }\n break;\n }\n }\n assert checkInvariants(root);\n return null;\n }\n\n /**\n * Removes the given node, that must be present before this\n * call. This is messier than typical red-black deletion code\n * because we cannot swap the contents of an interior node\n * with a leaf successor that is pinned by \"next\" pointers\n * that are accessible independently of lock. So instead we\n * swap the tree linkages.\n *\n * @return true if now too small, so should be untreeified\n */\n final boolean removeTreeNode(TreeNode p) {\n TreeNode next = (TreeNode) p.next;\n // unlink traversal pointers\n TreeNode pred = p.prev;\n TreeNode r, rl;\n if (pred == null)\n first = next;\n else\n pred.next = next;\n if (next != null)\n next.prev = pred;\n if (first == null) {\n root = null;\n return true;\n }\n if (// too small\n (r = root) == null || r.right == null || (rl = r.left) == null || rl.left == null)\n return true;\n lockRoot();\n try {\n TreeNode replacement;\n TreeNode pl = p.left;\n TreeNode pr = p.right;\n if (pl != null && pr != null) {\n TreeNode s = pr, sl;\n while (// find successor\n (sl = s.left) != null) s = sl;\n // swap colors\n boolean c = s.red;\n // swap colors\n s.red = p.red;\n // swap colors\n p.red = c;\n TreeNode sr = s.right;\n TreeNode pp = p.parent;\n if (s == pr) {\n // p was s's direct parent\n p.parent = s;\n s.right = p;\n } else {\n TreeNode sp = s.parent;\n if ((p.parent = sp) != null) {\n if (s == sp.left)\n sp.left = p;\n else\n sp.right = p;\n }\n if ((s.right = pr) != null)\n pr.parent = s;\n }\n p.left = null;\n if ((p.right = sr) != null)\n sr.parent = p;\n if ((s.left = pl) != null)\n pl.parent = s;\n if ((s.parent = pp) == null)\n r = s;\n else if (p == pp.left)\n pp.left = s;\n else\n pp.right = s;\n if (sr != null)\n replacement = sr;\n else\n replacement = p;\n } else if (pl != null)\n replacement = pl;\n else if (pr != null)\n replacement = pr;\n else\n replacement = p;\n if (replacement != p) {\n TreeNode pp = replacement.parent = p.parent;\n if (pp == null)\n r = replacement;\n else if (p == pp.left)\n pp.left = replacement;\n else\n pp.right = replacement;\n p.left = p.right = p.parent = null;\n }\n root = (p.red) ? r : balanceDeletion(r, replacement);\n if (p == replacement) {\n // detach pointers\n TreeNode pp;\n if ((pp = p.parent) != null) {\n if (p == pp.left)\n pp.left = null;\n else if (p == pp.right)\n pp.right = null;\n p.parent = null;\n }\n }\n } finally {\n unlockRoot();\n }\n assert checkInvariants(root);\n return false;\n }\n\n // Red-black tree methods, all adapted from CLR\n static TreeNode rotateLeft(TreeNode root, TreeNode p) {\n TreeNode r, pp, rl;\n if (p != null && (r = p.right) != null) {\n if ((rl = p.right = r.left) != null)\n rl.parent = p;\n if ((pp = r.parent = p.parent) == null)\n (root = r).red = false;\n else if (pp.left == p)\n pp.left = r;\n else\n pp.right = r;\n r.left = p;\n p.parent = r;\n }\n return root;\n }\n\n static TreeNode rotateRight(TreeNode root, TreeNode p) {\n TreeNode l, pp, lr;\n if (p != null && (l = p.left) != null) {\n if ((lr = p.left = l.right) != null)\n lr.parent = p;\n if ((pp = l.parent = p.parent) == null)\n (root = l).red = false;\n else if (pp.right == p)\n pp.right = l;\n else\n pp.left = l;\n l.right = p;\n p.parent = l;\n }\n return root;\n }\n\n static TreeNode balanceInsertion(TreeNode root, TreeNode x) {\n x.red = true;\n for (TreeNode xp, xpp, xppl, xppr; ; ) {\n if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (!xp.red || (xpp = xp.parent) == null)\n return root;\n if (xp == (xppl = xpp.left)) {\n if ((xppr = xpp.right) != null && xppr.red) {\n xppr.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.right) {\n root = rotateLeft(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateRight(root, xpp);\n }\n }\n }\n } else {\n if (xppl != null && xppl.red) {\n xppl.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.left) {\n root = rotateRight(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateLeft(root, xpp);\n }\n }\n }\n }\n }\n }\n\n static TreeNode balanceDeletion(TreeNode root, TreeNode x) {\n for (TreeNode xp, xpl, xpr; ; ) {\n if (x == null || x == root)\n return root;\n else if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (x.red) {\n x.red = false;\n return root;\n } else if ((xpl = xp.left) == x) {\n if ((xpr = xp.right) != null && xpr.red) {\n xpr.red = false;\n xp.red = true;\n root = rotateLeft(root, xp);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr == null)\n x = xp;\n else {\n TreeNode sl = xpr.left, sr = xpr.right;\n if ((sr == null || !sr.red) && (sl == null || !sl.red)) {\n xpr.red = true;\n x = xp;\n } else {\n if (sr == null || !sr.red) {\n if (sl != null)\n sl.red = false;\n xpr.red = true;\n root = rotateRight(root, xpr);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr != null) {\n xpr.red = (xp == null) ? false : xp.red;\n if ((sr = xpr.right) != null)\n sr.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateLeft(root, xp);\n }\n x = root;\n }\n }\n } else {\n // symmetric\n if (xpl != null && xpl.red) {\n xpl.red = false;\n xp.red = true;\n root = rotateRight(root, xp);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl == null)\n x = xp;\n else {\n TreeNode sl = xpl.left, sr = xpl.right;\n if ((sl == null || !sl.red) && (sr == null || !sr.red)) {\n xpl.red = true;\n x = xp;\n } else {\n if (sl == null || !sl.red) {\n if (sr != null)\n sr.red = false;\n xpl.red = true;\n root = rotateLeft(root, xpl);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl != null) {\n xpl.red = (xp == null) ? false : xp.red;\n if ((sl = xpl.left) != null)\n sl.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateRight(root, xp);\n }\n x = root;\n }\n }\n }\n }\n }\n\n /**\n * Checks invariants recursively for the tree of Nodes rooted at t.\n */\n static boolean checkInvariants(TreeNode t) {\n TreeNode tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode) t.next;\n if (tb != null && tb.next != t)\n return false;\n if (tn != null && tn.prev != t)\n return false;\n if (tp != null && t != tp.left && t != tp.right)\n return false;\n if (tl != null && (tl.parent != t || tl.hash > t.hash))\n return false;\n if (tr != null && (tr.parent != t || tr.hash < t.hash))\n return false;\n if (t.red && tl != null && tl.red && tr != null && tr.red)\n return false;\n if (tl != null && !checkInvariants(tl))\n return false;\n if (tr != null && !checkInvariants(tr))\n return false;\n return true;\n }\n\n private static final long LOCKSTATE = U.objectFieldOffset(TreeBin.class, \"lockState\");\n }\n\n /**\n * Records the table, its length, and current traversal index for a\n * traverser that must process a region of a forwarded table before\n * proceeding with current table.\n */\n static final class TableStack {\n\n int length;\n\n int index;\n\n Node[] tab;\n\n TableStack next;\n }\n\n /**\n * Encapsulates traversal for methods such as containsValue; also\n * serves as a base class for other iterators and spliterators.\n *\n * Method advance visits once each still-valid node that was\n * reachable upon iterator construction. It might miss some that\n * were added to a bin after the bin was visited, which is OK wrt\n * consistency guarantees. Maintaining this property in the face\n * of possible ongoing resizes requires a fair amount of\n * bookkeeping state that is difficult to optimize away amidst\n * volatile accesses. Even so, traversal maintains reasonable\n * throughput.\n *\n * Normally, iteration proceeds bin-by-bin traversing lists.\n * However, if the table has been resized, then all future steps\n * must traverse both the bin at the current index as well as at\n * (index + baseSize); and so on for further resizings. To\n * paranoically cope with potential sharing by users of iterators\n * across threads, iteration terminates if a bounds checks fails\n * for a table read.\n */\n static class Traverser {\n\n // current table; updated if resized\n Node[] tab;\n\n // the next entry to use\n Node next;\n\n // to save/restore on ForwardingNodes\n TableStack stack, spare;\n\n // index of bin to use next\n int index;\n\n // current index of initial table\n int baseIndex;\n\n // index bound for initial table\n int baseLimit;\n\n // initial table size\n final int baseSize;\n\n Traverser(Node[] tab, int size, int index, int limit) {\n this.tab = tab;\n this.baseSize = size;\n this.baseIndex = this.index = index;\n this.baseLimit = limit;\n this.next = null;\n }\n\n /**\n * Advances if possible, returning next valid node, or null if none.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n // must use locals in checks\n Node[] t;\n // must use locals in checks\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n // visit upper slots if present\n index = ++baseIndex;\n }\n }\n\n /**\n * Saves traversal state upon encountering a forwarding node.\n */\n private void pushState(Node[] t, int i, int n) {\n // reuse if possible\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n /**\n * Possibly pops traversal state.\n *\n * @param n length of current table\n */\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /**\n * Base of key, value, and entry Iterators. Adds fields to\n * Traverser to support iterator.remove.\n */\n static class BaseIterator extends Traverser {\n\n final ConcurrentHashMap map;\n\n Node lastReturned;\n\n BaseIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n advance();\n }\n\n public final boolean hasNext() {\n return next != null;\n }\n\n public final boolean hasMoreElements() {\n return next != null;\n }\n\n public final void remove() {\n Node p;\n if ((p = lastReturned) == null)\n throw new IllegalStateException();\n lastReturned = null;\n map.replaceNode(p.key, null, null);\n }\n }\n\n static final class KeyIterator extends BaseIterator implements Iterator, Enumeration {\n\n KeyIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final K next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n lastReturned = p;\n advance();\n return k;\n }\n\n public final K nextElement() {\n return next();\n }\n }\n\n static final class ValueIterator extends BaseIterator implements Iterator, Enumeration {\n\n ValueIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final V next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n V v = p.val;\n lastReturned = p;\n advance();\n return v;\n }\n\n public final V nextElement() {\n return next();\n }\n }\n\n static final class EntryIterator extends BaseIterator implements Iterator> {\n\n EntryIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final Map.Entry next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n V v = p.val;\n lastReturned = p;\n advance();\n return new MapEntry(k, v, map);\n }\n }\n\n static final class MapEntry implements Map.Entry {\n\n final K key;\n\n V val;\n\n final ConcurrentHashMap map;\n\n MapEntry(K key, V val, ConcurrentHashMap map) {\n this.key = key;\n this.val = val;\n this.map = map;\n }\n\n public K getKey() {\n return key;\n }\n\n public V getValue() {\n return val;\n }\n\n public int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public boolean equals(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == val || v.equals(val)));\n }\n\n /**\n * Sets our entry's value and writes through to the map. The\n * value to return is somewhat arbitrary here. Since we do not\n * necessarily track asynchronous changes, the most recent\n * \"previous\" value could be different from what we return (or\n * could even have been removed, in which case the put will\n * re-establish). We do not and cannot guarantee more.\n */\n public V setValue(V value) {\n if (value == null)\n throw new NullPointerException();\n V v = val;\n val = value;\n map.put(key, value);\n return v;\n }\n }\n\n static final class KeySpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n KeySpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public KeySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new KeySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.key);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class ValueSpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n ValueSpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public ValueSpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new ValueSpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.val);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class EntrySpliterator extends Traverser implements Spliterator> {\n\n // To export MapEntry\n final ConcurrentHashMap map;\n\n // size estimate\n long est;\n\n EntrySpliterator(Node[] tab, int size, int index, int limit, long est, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n this.est = est;\n }\n\n public EntrySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new EntrySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1, map);\n }\n\n public void forEachRemaining(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n\n public boolean tryAdvance(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(new MapEntry(p.key, p.val, map));\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n // Parallel bulk operations\n /**\n * Computes initial batch value for bulk tasks. The returned value\n * is approximately exp2 of the number of times (minus one) to\n * split task by two before executing leaf action. This value is\n * faster to compute and more convenient to use as a guide to\n * splitting than is the depth, since it is used while dividing by\n * two anyway.\n */\n final int batchFor(long b) {\n long n;\n if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)\n return 0;\n // slack of 4\n int sp = ForkJoinPool.getCommonPoolParallelism() << 2;\n return (b <= 0L || (n /= b) >= sp) ? sp : (int) n;\n }\n\n /**\n * Performs the given action for each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiFunction transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each (key, value), or null if none. Upon\n * success, further element processing is suppressed and the\n * results of any other parallel invocations of the search\n * function are ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each (key, value), or null if none\n * @since 1.8\n */\n public U search(long parallelismThreshold, BiFunction searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public U reduce(long parallelismThreshold, BiFunction transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public double reduceToDouble(long parallelismThreshold, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public long reduceToLong(long parallelismThreshold, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public int reduceToInt(long parallelismThreshold, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each key, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each key, or null if none\n * @since 1.8\n */\n public U searchKeys(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all keys using the given\n * reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all keys using the given\n * reducer to combine values, or null if none\n * @since 1.8\n */\n public K reduceKeys(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public U reduceKeys(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public double reduceKeysToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public long reduceKeysToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public int reduceKeysToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachValueTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedValueTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each value, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each value, or null if none\n * @since 1.8\n */\n public U searchValues(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all values using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all values\n * @since 1.8\n */\n public V reduceValues(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public U reduceValues(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public double reduceValuesToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public long reduceValuesToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public int reduceValuesToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Function, ? extends U> transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each entry, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each entry, or null if none\n * @since 1.8\n */\n public U searchEntries(long parallelismThreshold, Function, ? extends U> searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all entries using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all entries\n * @since 1.8\n */\n public Map.Entry reduceEntries(long parallelismThreshold, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public U reduceEntries(long parallelismThreshold, Function, ? extends U> transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public double reduceEntriesToDouble(long parallelismThreshold, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public long reduceEntriesToLong(long parallelismThreshold, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public int reduceEntriesToInt(long parallelismThreshold, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n abstract static class CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n final ConcurrentHashMap map;\n\n CollectionView(ConcurrentHashMap map) {\n this.map = map;\n }\n\n /**\n * Returns the map backing this view.\n *\n * @return the map backing this view\n */\n public ConcurrentHashMap getMap() {\n return map;\n }\n\n /**\n * Removes all of the elements from this view, by removing all\n * the mappings from the map backing this view.\n */\n public final void clear() {\n map.clear();\n }\n\n public final int size() {\n return map.size();\n }\n\n public final boolean isEmpty() {\n return map.isEmpty();\n }\n\n // implementations below rely on concrete classes supplying these\n /**\n * Returns an iterator over the elements in this collection.\n *\n *

The returned iterator is\n * weakly consistent.\n *\n * @return an iterator over the elements in this collection\n */\n public abstract Iterator iterator();\n\n public abstract boolean contains(Object o);\n\n public abstract boolean remove(Object o);\n\n private static final String OOME_MSG = \"Required array size too large\";\n\n public final Object[] toArray() {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int n = (int) sz;\n Object[] r = new Object[n];\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = e;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n @SuppressWarnings(\"unchecked\")\n public final T[] toArray(T[] a) {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int m = (int) sz;\n T[] r = (a.length >= m) ? a : (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), m);\n int n = r.length;\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = (T) e;\n }\n if (a == r && i < n) {\n r[i] = null;\n return r;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n /**\n * Returns a string representation of this collection.\n * The string representation consists of the string representations\n * of the collection's elements in the order they are returned by\n * its iterator, enclosed in square brackets ({@code \"[]\"}).\n * Adjacent elements are separated by the characters {@code \", \"}\n * (comma and space). Elements are converted to strings as by\n * {@link String#valueOf(Object)}.\n *\n * @return a string representation of this collection\n */\n public final String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append('[');\n Iterator it = iterator();\n if (it.hasNext()) {\n for (; ; ) {\n Object e = it.next();\n sb.append(e == this ? \"(this Collection)\" : e);\n if (!it.hasNext())\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append(']').toString();\n }\n\n public final boolean containsAll(Collection c) {\n if (c != this) {\n for (Object e : c) {\n if (e == null || !contains(e))\n return false;\n }\n }\n return true;\n }\n\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n // Use (c instanceof Set) as a hint that lookup in c is as\n // efficient as this view\n Node[] t;\n if ((t = map.table) == null) {\n return false;\n } else if (c instanceof Set && c.size() > t.length) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n } else {\n for (Object e : c) modified |= remove(e);\n }\n return modified;\n }\n\n public final boolean retainAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (!c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of keys, in\n * which additions may optionally be enabled by mapping to a\n * common value. This class cannot be directly instantiated.\n * See {@link #keySet() keySet()},\n * {@link #keySet(Object) keySet(V)},\n * {@link #newKeySet() newKeySet()},\n * {@link #newKeySet(int) newKeySet(int)}.\n *\n * @since 1.8\n */\n public static class KeySetView extends CollectionView implements Set, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n // Conditionally serializable\n @SuppressWarnings(\"serial\")\n private final V value;\n\n KeySetView(ConcurrentHashMap map, V value) {\n super(map);\n this.value = value;\n }\n\n /**\n * Returns the default mapped value for additions,\n * or {@code null} if additions are not supported.\n *\n * @return the default mapped value for additions, or {@code null}\n * if not supported\n */\n public V getMappedValue() {\n return value;\n }\n\n /**\n * {@inheritDoc}\n * @throws NullPointerException if the specified key is null\n */\n public boolean contains(Object o) {\n return map.containsKey(o);\n }\n\n /**\n * Removes the key from this map view, by removing the key (and its\n * corresponding value) from the backing map. This method does\n * nothing if the key is not in the map.\n *\n * @param o the key to be removed from the backing map\n * @return {@code true} if the backing map contained the specified key\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object o) {\n return map.remove(o) != null;\n }\n\n /**\n * @return an iterator over the keys of the backing map\n */\n public Iterator iterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, m);\n }\n\n /**\n * Adds the specified key to this set view by mapping the key to\n * the default mapped value in the backing map, if defined.\n *\n * @param e key to be added\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the specified key is null\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean add(K e) {\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n return map.putVal(e, v, true) == null;\n }\n\n /**\n * Adds all of the elements in the specified collection to this set,\n * as if by calling {@link #add} on each one.\n *\n * @param c the elements to be inserted into this set\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the collection or any of its\n * elements are {@code null}\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean addAll(Collection c) {\n boolean added = false;\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n for (K e : c) {\n if (map.putVal(e, v, true) == null)\n added = true;\n }\n return added;\n }\n\n public int hashCode() {\n int h = 0;\n for (K e : this) h += e.hashCode();\n return h;\n }\n\n public boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeySpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.key);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Collection} of\n * values, in which additions are disabled. This class cannot be\n * directly instantiated. See {@link #values()}.\n */\n static final class ValuesView extends CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n ValuesView(ConcurrentHashMap map) {\n super(map);\n }\n\n public final boolean contains(Object o) {\n return map.containsValue(o);\n }\n\n public final boolean remove(Object o) {\n if (o != null) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (o.equals(it.next())) {\n it.remove();\n return true;\n }\n }\n }\n return false;\n }\n\n public final Iterator iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, m);\n }\n\n public final boolean add(V e) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean addAll(Collection c) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n\n public boolean removeIf(Predicate filter) {\n return map.removeValueIf(filter);\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueSpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.val);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of (key, value)\n * entries. This class cannot be directly instantiated. See\n * {@link #entrySet()}.\n */\n static final class EntrySetView extends CollectionView> implements Set>, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n EntrySetView(ConcurrentHashMap map) {\n super(map);\n }\n\n public boolean contains(Object o) {\n Object k, v, r;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (r = map.get(k)) != null && (v = e.getValue()) != null && (v == r || v.equals(r)));\n }\n\n public boolean remove(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && map.remove(k, v));\n }\n\n /**\n * @return an iterator over the entries of the backing map\n */\n public Iterator> iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntryIterator(t, f, 0, f, m);\n }\n\n public boolean add(Entry e) {\n return map.putVal(e.getKey(), e.getValue(), false) == null;\n }\n\n public boolean addAll(Collection> c) {\n boolean added = false;\n for (Entry e : c) {\n if (add(e))\n added = true;\n }\n return added;\n }\n\n public boolean removeIf(Predicate> filter) {\n return map.removeEntryIf(filter);\n }\n\n public final int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n h += p.hashCode();\n }\n }\n return h;\n }\n\n public final boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator> spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntrySpliterator(t, f, 0, f, n < 0L ? 0L : n, m);\n }\n\n public void forEach(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n }\n }\n\n /**\n * Base class for bulk tasks. Repeats some fields and code from\n * class Traverser, because we need to subclass CountedCompleter.\n */\n @SuppressWarnings(\"serial\")\n abstract static class BulkTask extends CountedCompleter {\n\n // same as Traverser\n Node[] tab;\n\n Node next;\n\n TableStack stack, spare;\n\n int index;\n\n int baseIndex;\n\n int baseLimit;\n\n final int baseSize;\n\n // split control\n int batch;\n\n BulkTask(BulkTask par, int b, int i, int f, Node[] t) {\n super(par);\n this.batch = b;\n this.index = this.baseIndex = i;\n if ((this.tab = t) == null)\n this.baseSize = this.baseLimit = 0;\n else if (par == null)\n this.baseSize = this.baseLimit = t.length;\n else {\n this.baseLimit = f;\n this.baseSize = par.baseSize;\n }\n }\n\n /**\n * Same as Traverser version.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n Node[] t;\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n private void pushState(Node[] t, int i, int n) {\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /*\n * Task classes. Coded in a regular but ugly format/style to\n * simplify checks that each variant differs in the right way from\n * others. The null screenings exist because compilers cannot tell\n * that we've already null-checked task arguments, so we force\n * simplest hoisted bypass to help avoid convoluted traps.\n */\n @SuppressWarnings(\"serial\")\n static final class ForEachKeyTask extends BulkTask {\n\n final Consumer action;\n\n ForEachKeyTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachValueTask extends BulkTask {\n\n final Consumer action;\n\n ForEachValueTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachValueTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachEntryTask extends BulkTask {\n\n final Consumer> action;\n\n ForEachEntryTask(BulkTask p, int b, int i, int f, Node[] t, Consumer> action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer> action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachMappingTask extends BulkTask {\n\n final BiConsumer action;\n\n ForEachMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiConsumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final BiConsumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key, p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedKeyTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedKeyTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedValueTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedValueTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n ", "post_mask_code": "{\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedValueTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedEntryTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final Consumer action;\n\n ForEachTransformedEntryTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedMappingTask extends BulkTask {\n\n final BiFunction transformer;\n\n final Consumer action;\n\n ForEachTransformedMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchKeysTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchKeysTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchValuesTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchValuesTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchEntriesTask extends BulkTask {\n\n final Function, ? extends U> searchFunction;\n\n final AtomicReference result;\n\n SearchEntriesTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function, ? extends U> searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n return;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchMappingsTask extends BulkTask {\n\n final BiFunction searchFunction;\n\n final AtomicReference result;\n\n SearchMappingsTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final BiFunction searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key, p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceKeysTask extends BulkTask {\n\n final BiFunction reducer;\n\n K result;\n\n ReduceKeysTask rights, nextRight;\n\n ReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, ReduceKeysTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final K getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n K r = null;\n for (Node p; (p = advance()) != null; ) {\n K u = p.key;\n r = (r == null) ? u : u == null ? r : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceKeysTask t = (ReduceKeysTask) c, s = t.rights;\n while (s != null) {\n K tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceValuesTask extends BulkTask {\n\n final BiFunction reducer;\n\n V result;\n\n ReduceValuesTask rights, nextRight;\n\n ReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceValuesTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final V getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n V r = null;\n for (Node p; (p = advance()) != null; ) {\n V v = p.val;\n r = (r == null) ? v : reducer.apply(r, v);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceValuesTask t = (ReduceValuesTask) c, s = t.rights;\n while (s != null) {\n V tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceEntriesTask extends BulkTask> {\n\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n\n Map.Entry result;\n\n ReduceEntriesTask rights, nextRight;\n\n ReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceEntriesTask nextRight, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final Map.Entry getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n Map.Entry r = null;\n for (Node p; (p = advance()) != null; ) r = (r == null) ? p : reducer.apply(r, p);\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceEntriesTask t = (ReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n Map.Entry tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceKeysTask rights, nextRight;\n\n MapReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysTask t = (MapReduceKeysTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceValuesTask rights, nextRight;\n\n MapReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesTask t = (MapReduceValuesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceEntriesTask rights, nextRight;\n\n MapReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesTask nextRight, Function, ? extends U> transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesTask t = (MapReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsTask extends BulkTask {\n\n final BiFunction transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceMappingsTask rights, nextRight;\n\n MapReduceMappingsTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsTask nextRight, BiFunction transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsTask t = (MapReduceMappingsTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceKeysToDoubleTask rights, nextRight;\n\n MapReduceKeysToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToDoubleTask t = (MapReduceKeysToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceValuesToDoubleTask rights, nextRight;\n\n MapReduceValuesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToDoubleTask t = (MapReduceValuesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction> transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceEntriesToDoubleTask rights, nextRight;\n\n MapReduceEntriesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToDoubleTask nextRight, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction> transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToDoubleTask t = (MapReduceEntriesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToDoubleTask extends BulkTask {\n\n final ToDoubleBiFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceMappingsToDoubleTask rights, nextRight;\n\n MapReduceMappingsToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToDoubleTask nextRight, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleBiFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToDoubleTask t = (MapReduceMappingsToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceKeysToLongTask rights, nextRight;\n\n MapReduceKeysToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToLongTask t = (MapReduceKeysToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceValuesToLongTask rights, nextRight;\n\n MapReduceValuesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToLongTask t = (MapReduceValuesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToLongTask extends BulkTask {\n\n final ToLongFunction> transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceEntriesToLongTask rights, nextRight;\n\n MapReduceEntriesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToLongTask nextRight, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction> transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToLongTask t = (MapReduceEntriesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToLongTask extends BulkTask {\n\n final ToLongBiFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceMappingsToLongTask rights, nextRight;\n\n MapReduceMappingsToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToLongTask nextRight, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongBiFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToLongTask t = (MapReduceMappingsToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceKeysToIntTask rights, nextRight;\n\n MapReduceKeysToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToIntTask t = (MapReduceKeysToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceValuesToIntTask rights, nextRight;\n\n MapReduceValuesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToIntTask t = (MapReduceValuesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToIntTask extends BulkTask {\n\n final ToIntFunction> transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceEntriesToIntTask rights, nextRight;\n\n MapReduceEntriesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToIntTask nextRight, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction> transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToIntTask t = (MapReduceEntriesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToIntTask extends BulkTask {\n\n final ToIntBiFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceMappingsToIntTask rights, nextRight;\n\n MapReduceMappingsToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToIntTask nextRight, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntBiFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToIntTask t = (MapReduceMappingsToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n // Unsafe mechanics\n private static final Unsafe U = Unsafe.getUnsafe();\n\n private static final long SIZECTL = U.objectFieldOffset(ConcurrentHashMap.class, \"sizeCtl\");\n\n private static final long TRANSFERINDEX = U.objectFieldOffset(ConcurrentHashMap.class, \"transferIndex\");\n\n private static final long BASECOUNT = U.objectFieldOffset(ConcurrentHashMap.class, \"baseCount\");\n\n private static final long CELLSBUSY = U.objectFieldOffset(ConcurrentHashMap.class, \"cellsBusy\");\n\n private static final long CELLVALUE = U.objectFieldOffset(CounterCell.class, \"value\");\n\n private static final int ABASE = U.arrayBaseOffset(Node[].class);\n\n private static final int ASHIFT;\n\n static {\n int scale = U.arrayIndexScale(Node[].class);\n if ((scale & (scale - 1)) != 0)\n throw new ExceptionInInitializerError(\"array index scale not a power of two\");\n ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);\n // Reduce the risk of rare disastrous classloading in first call to\n Class ensureLoaded = LockSupport.class;\n // Eager class load observed to help JIT during startup\n ensureLoaded = ReservationNode.class;\n }\n}\n"} {"task_id": "Java_2823", "language": "Java", "task_type": "method_body", "source_file": "java/github/openjdk/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java", "mask_start_position": 94211, "mask_end_position": 94247, "canonical_solution": "{\n return null;\n }", "pre_mask_code": "package java.util.concurrent;\n\nimport java.io.ObjectStreamField;\nimport java.io.Serializable;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.AbstractMap;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Hashtable;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.Spliterator;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.concurrent.locks.LockSupport;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\nimport java.util.function.Consumer;\nimport java.util.function.DoubleBinaryOperator;\nimport java.util.function.Function;\nimport java.util.function.IntBinaryOperator;\nimport java.util.function.LongBinaryOperator;\nimport java.util.function.Predicate;\nimport java.util.function.ToDoubleBiFunction;\nimport java.util.function.ToDoubleFunction;\nimport java.util.function.ToIntBiFunction;\nimport java.util.function.ToIntFunction;\nimport java.util.function.ToLongBiFunction;\nimport java.util.function.ToLongFunction;\nimport java.util.stream.Stream;\nimport jdk.internal.misc.Unsafe;\n\n/**\n * A hash table supporting full concurrency of retrievals and\n * high expected concurrency for updates. This class obeys the\n * same functional specification as {@link java.util.Hashtable}, and\n * includes versions of methods corresponding to each method of\n * {@code Hashtable}. However, even though all operations are\n * thread-safe, retrieval operations do not entail locking,\n * and there is not any support for locking the entire table\n * in a way that prevents all access. This class is fully\n * interoperable with {@code Hashtable} in programs that rely on its\n * thread safety but not on its synchronization details.\n *\n *

Retrieval operations (including {@code get}) generally do not\n * block, so may overlap with update operations (including {@code put}\n * and {@code remove}). Retrievals reflect the results of the most\n * recently completed update operations holding upon their\n * onset. (More formally, an update operation for a given key bears a\n * happens-before relation with any (non-null) retrieval for\n * that key reporting the updated value.) For aggregate operations\n * such as {@code putAll} and {@code clear}, concurrent retrievals may\n * reflect insertion or removal of only some entries. Similarly,\n * Iterators, Spliterators and Enumerations return elements reflecting the\n * state of the hash table at some point at or since the creation of the\n * iterator/enumeration. They do not throw {@link\n * java.util.ConcurrentModificationException ConcurrentModificationException}.\n * However, iterators are designed to be used by only one thread at a time.\n * Bear in mind that the results of aggregate status methods including\n * {@code size}, {@code isEmpty}, and {@code containsValue} are typically\n * useful only when a map is not undergoing concurrent updates in other threads.\n * Otherwise the results of these methods reflect transient states\n * that may be adequate for monitoring or estimation purposes, but not\n * for program control.\n *\n *

The table is dynamically expanded when there are too many\n * collisions (i.e., keys that have distinct hash codes but fall into\n * the same slot modulo the table size), with the expected average\n * effect of maintaining roughly two bins per mapping (corresponding\n * to a 0.75 load factor threshold for resizing). There may be much\n * variance around this average as mappings are added and removed, but\n * overall, this maintains a commonly accepted time/space tradeoff for\n * hash tables. However, resizing this or any other kind of hash\n * table may be a relatively slow operation. When possible, it is a\n * good idea to provide a size estimate as an optional {@code\n * initialCapacity} constructor argument. An additional optional\n * {@code loadFactor} constructor argument provides a further means of\n * customizing initial table capacity by specifying the table density\n * to be used in calculating the amount of space to allocate for the\n * given number of elements. Also, for compatibility with previous\n * versions of this class, constructors may optionally specify an\n * expected {@code concurrencyLevel} as an additional hint for\n * internal sizing. Note that using many keys with exactly the same\n * {@code hashCode()} is a sure way to slow down performance of any\n * hash table. To ameliorate impact, when keys are {@link Comparable},\n * this class may use comparison order among keys to help break ties.\n *\n *

A {@link Set} projection of a ConcurrentHashMap may be created\n * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed\n * (using {@link #keySet(Object)} when only keys are of interest, and the\n * mapped values are (perhaps transiently) not used or all take the\n * same mapping value.\n *\n *

A ConcurrentHashMap can be used as a scalable frequency map (a\n * form of histogram or multiset) by using {@link\n * java.util.concurrent.atomic.LongAdder} values and initializing via\n * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count\n * to a {@code ConcurrentHashMap freqs}, you can use\n * {@code freqs.computeIfAbsent(key, k -> new LongAdder()).increment();}\n *\n *

This class and its views and iterators implement all of the\n * optional methods of the {@link Map} and {@link Iterator}\n * interfaces.\n *\n *

Like {@link Hashtable} but unlike {@link HashMap}, this class\n * does not allow {@code null} to be used as a key or value.\n *\n *

ConcurrentHashMaps support a set of sequential and parallel bulk\n * operations that, unlike most {@link Stream} methods, are designed\n * to be safely, and often sensibly, applied even with maps that are\n * being concurrently updated by other threads; for example, when\n * computing a snapshot summary of the values in a shared registry.\n * There are three kinds of operation, each with four forms, accepting\n * functions with keys, values, entries, and (key, value) pairs as\n * arguments and/or return values. Because the elements of a\n * ConcurrentHashMap are not ordered in any particular way, and may be\n * processed in different orders in different parallel executions, the\n * correctness of supplied functions should not depend on any\n * ordering, or on any other objects or values that may transiently\n * change while computation is in progress; and except for forEach\n * actions, should ideally be side-effect-free. Bulk operations on\n * {@link Map.Entry} objects do not support method {@code setValue}.\n *\n *

    \n *
  • forEach: Performs a given action on each element.\n * A variant form applies a given transformation on each element\n * before performing the action.\n *\n *
  • search: Returns the first available non-null result of\n * applying a given function on each element; skipping further\n * search when a result is found.\n *\n *
  • reduce: Accumulates each element. The supplied reduction\n * function cannot rely on ordering (more formally, it should be\n * both associative and commutative). There are five variants:\n *\n *
      \n *\n *
    • Plain reductions. (There is not a form of this method for\n * (key, value) function arguments since there is no corresponding\n * return type.)\n *\n *
    • Mapped reductions that accumulate the results of a given\n * function applied to each element.\n *\n *
    • Reductions to scalar doubles, longs, and ints, using a\n * given basis value.\n *\n *
    \n *
\n *\n *

These bulk operations accept a {@code parallelismThreshold}\n * argument. Methods proceed sequentially if the current map size is\n * estimated to be less than the given threshold. Using a value of\n * {@code Long.MAX_VALUE} suppresses all parallelism. Using a value\n * of {@code 1} results in maximal parallelism by partitioning into\n * enough subtasks to fully utilize the {@link\n * ForkJoinPool#commonPool()} that is used for all parallel\n * computations. Normally, you would initially choose one of these\n * extreme values, and then measure performance of using in-between\n * values that trade off overhead versus throughput.\n *\n *

The concurrency properties of bulk operations follow\n * from those of ConcurrentHashMap: Any non-null result returned\n * from {@code get(key)} and related access methods bears a\n * happens-before relation with the associated insertion or\n * update. The result of any bulk operation reflects the\n * composition of these per-element relations (but is not\n * necessarily atomic with respect to the map as a whole unless it\n * is somehow known to be quiescent). Conversely, because keys\n * and values in the map are never null, null serves as a reliable\n * atomic indicator of the current lack of any result. To\n * maintain this property, null serves as an implicit basis for\n * all non-scalar reduction operations. For the double, long, and\n * int versions, the basis should be one that, when combined with\n * any other value, returns that other value (more formally, it\n * should be the identity element for the reduction). Most common\n * reductions have these properties; for example, computing a sum\n * with basis 0 or a minimum with basis MAX_VALUE.\n *\n *

Search and transformation functions provided as arguments\n * should similarly return null to indicate the lack of any result\n * (in which case it is not used). In the case of mapped\n * reductions, this also enables transformations to serve as\n * filters, returning null (or, in the case of primitive\n * specializations, the identity basis) if the element should not\n * be combined. You can create compound transformations and\n * filterings by composing them yourself under this \"null means\n * there is nothing there now\" rule before using them in search or\n * reduce operations.\n *\n *

Methods accepting and/or returning Entry arguments maintain\n * key-value associations. They may be useful for example when\n * finding the key for the greatest value. Note that \"plain\" Entry\n * arguments can be supplied using {@code new\n * AbstractMap.SimpleEntry(k,v)}.\n *\n *

Bulk operations may complete abruptly, throwing an\n * exception encountered in the application of a supplied\n * function. Bear in mind when handling such exceptions that other\n * concurrently executing functions could also have thrown\n * exceptions, or would have done so if the first exception had\n * not occurred.\n *\n *

Speedups for parallel compared to sequential forms are common\n * but not guaranteed. Parallel operations involving brief functions\n * on small maps may execute more slowly than sequential forms if the\n * underlying work to parallelize the computation is more expensive\n * than the computation itself. Similarly, parallelization may not\n * lead to much actual parallelism if all processors are busy\n * performing unrelated tasks.\n *\n *

All arguments to all task methods must be non-null.\n *\n *

This class is a member of the\n * \n * Java Collections Framework.\n *\n * @since 1.5\n * @author Doug Lea\n * @param the type of keys maintained by this map\n * @param the type of mapped values\n */\npublic class ConcurrentHashMap extends AbstractMap implements ConcurrentMap, Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n /*\n * Overview:\n *\n * The primary design goal of this hash table is to maintain\n * concurrent readability (typically method get(), but also\n * iterators and related methods) while minimizing update\n * contention. Secondary goals are to keep space consumption about\n * the same or better than java.util.HashMap, and to support high\n * initial insertion rates on an empty table by many threads.\n *\n * This map usually acts as a binned (bucketed) hash table. Each\n * key-value mapping is held in a Node. Most nodes are instances\n * of the basic Node class with hash, key, value, and next\n * fields. However, various subclasses exist: TreeNodes are\n * arranged in balanced trees, not lists. TreeBins hold the roots\n * of sets of TreeNodes. ForwardingNodes are placed at the heads\n * of bins during resizing. ReservationNodes are used as\n * placeholders while establishing values in computeIfAbsent and\n * related methods. The types TreeBin, ForwardingNode, and\n * ReservationNode do not hold normal user keys, values, or\n * hashes, and are readily distinguishable during search etc\n * because they have negative hash fields and null key and value\n * fields. (These special nodes are either uncommon or transient,\n * so the impact of carrying around some unused fields is\n * insignificant.)\n *\n * The table is lazily initialized to a power-of-two size upon the\n * first insertion. Each bin in the table normally contains a\n * list of Nodes (most often, the list has only zero or one Node).\n * Table accesses require volatile/atomic reads, writes, and\n * CASes. Because there is no other way to arrange this without\n * adding further indirections, we use intrinsics\n * (jdk.internal.misc.Unsafe) operations.\n *\n * We use the top (sign) bit of Node hash fields for control\n * purposes -- it is available anyway because of addressing\n * constraints. Nodes with negative hash fields are specially\n * handled or ignored in map methods.\n *\n * Insertion (via put or its variants) of the first node in an\n * empty bin is performed by just CASing it to the bin. This is\n * by far the most common case for put operations under most\n * key/hash distributions. Other update operations (insert,\n * delete, and replace) require locks. We do not want to waste\n * the space required to associate a distinct lock object with\n * each bin, so instead use the first node of a bin list itself as\n * a lock. Locking support for these locks relies on builtin\n * \"synchronized\" monitors.\n *\n * Using the first node of a list as a lock does not by itself\n * suffice though: When a node is locked, any update must first\n * validate that it is still the first node after locking it, and\n * retry if not. Because new nodes are always appended to lists,\n * once a node is first in a bin, it remains first until deleted\n * or the bin becomes invalidated (upon resizing).\n *\n * The main disadvantage of per-bin locks is that other update\n * operations on other nodes in a bin list protected by the same\n * lock can stall, for example when user equals() or mapping\n * functions take a long time. However, statistically, under\n * random hash codes, this is not a common problem. Ideally, the\n * frequency of nodes in bins follows a Poisson distribution\n * (http://example.com) with a\n * parameter of about 0.5 on average, given the resizing threshold\n * of 0.75, although with a large variance because of resizing\n * granularity. Ignoring variance, the expected occurrences of\n * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The\n * first values are:\n *\n * 0: 0.60653066\n * 1: 0.30326533\n * 2: 0.07581633\n * 3: 0.01263606\n * 4: 0.00157952\n * 5: 0.00015795\n * 6: 0.00001316\n * 7: 0.00000094\n * 8: 0.00000006\n * more: less than 1 in ten million\n *\n * Lock contention probability for two threads accessing distinct\n * elements is roughly 1 / (8 * #elements) under random hashes.\n *\n * Actual hash code distributions encountered in practice\n * sometimes deviate significantly from uniform randomness. This\n * includes the case when N > (1<<30), so some keys MUST collide.\n * Similarly for dumb or hostile usages in which multiple keys are\n * designed to have identical hash codes or ones that differs only\n * in masked-out high bits. So we use a secondary strategy that\n * applies when the number of nodes in a bin exceeds a\n * threshold. These TreeBins use a balanced tree to hold nodes (a\n * specialized form of red-black trees), bounding search time to\n * O(log N). Each search step in a TreeBin is at least twice as\n * slow as in a regular list, but given that N cannot exceed\n * (1<<64) (before running out of addresses) this bounds search\n * steps, lock hold times, etc, to reasonable constants (roughly\n * 100 nodes inspected per operation worst case) so long as keys\n * are Comparable (which is very common -- String, Long, etc).\n * TreeBin nodes (TreeNodes) also maintain the same \"next\"\n * traversal pointers as regular nodes, so can be traversed in\n * iterators in the same way.\n *\n * The table is resized when occupancy exceeds a percentage\n * threshold (nominally, 0.75, but see below). Any thread\n * noticing an overfull bin may assist in resizing after the\n * initiating thread allocates and sets up the replacement array.\n * However, rather than stalling, these other threads may proceed\n * with insertions etc. The use of TreeBins shields us from the\n * worst case effects of overfilling while resizes are in\n * progress. Resizing proceeds by transferring bins, one by one,\n * from the table to the next table. However, threads claim small\n * blocks of indices to transfer (via field transferIndex) before\n * doing so, reducing contention. A generation stamp in field\n * sizeCtl ensures that resizings do not overlap. Because we are\n * using power-of-two expansion, the elements from each bin must\n * either stay at same index, or move with a power of two\n * offset. We eliminate unnecessary node creation by catching\n * cases where old nodes can be reused because their next fields\n * won't change. On average, only about one-sixth of them need\n * cloning when a table doubles. The nodes they replace will be\n * garbage collectible as soon as they are no longer referenced by\n * any reader thread that may be in the midst of concurrently\n * traversing table. Upon transfer, the old table bin contains\n * only a special forwarding node (with hash field \"MOVED\") that\n * contains the next table as its key. On encountering a\n * forwarding node, access and update operations restart, using\n * the new table.\n *\n * Each bin transfer requires its bin lock, which can stall\n * waiting for locks while resizing. However, because other\n * threads can join in and help resize rather than contend for\n * locks, average aggregate waits become shorter as resizing\n * progresses. The transfer operation must also ensure that all\n * accessible bins in both the old and new table are usable by any\n * traversal. This is arranged in part by proceeding from the\n * last bin (table.length - 1) up towards the first. Upon seeing\n * a forwarding node, traversals (see class Traverser) arrange to\n * move to the new table without revisiting nodes. To ensure that\n * no intervening nodes are skipped even when moved out of order,\n * a stack (see class TableStack) is created on first encounter of\n * a forwarding node during a traversal, to maintain its place if\n * later processing the current table. The need for these\n * save/restore mechanics is relatively rare, but when one\n * forwarding node is encountered, typically many more will be.\n * So Traversers use a simple caching scheme to avoid creating so\n * many new TableStack nodes. (Thanks to Peter Levart for\n * suggesting use of a stack here.)\n *\n * The traversal scheme also applies to partial traversals of\n * ranges of bins (via an alternate Traverser constructor)\n * to support partitioned aggregate operations. Also, read-only\n * operations give up if ever forwarded to a null table, which\n * provides support for shutdown-style clearing, which is also not\n * currently implemented.\n *\n * Lazy table initialization minimizes footprint until first use,\n * and also avoids resizings when the first operation is from a\n * putAll, constructor with map argument, or deserialization.\n * These cases attempt to override the initial capacity settings,\n * but harmlessly fail to take effect in cases of races.\n *\n * The element count is maintained using a specialization of\n * LongAdder. We need to incorporate a specialization rather than\n * just use a LongAdder in order to access implicit\n * contention-sensing that leads to creation of multiple\n * CounterCells. The counter mechanics avoid contention on\n * updates but can encounter cache thrashing if read too\n * frequently during concurrent access. To avoid reading so often,\n * resizing under contention is attempted only upon adding to a\n * bin already holding two or more nodes. Under uniform hash\n * distributions, the probability of this occurring at threshold\n * is around 13%, meaning that only about 1 in 8 puts check\n * threshold (and after resizing, many fewer do so).\n *\n * TreeBins use a special form of comparison for search and\n * related operations (which is the main reason we cannot use\n * existing collections such as TreeMaps). TreeBins contain\n * Comparable elements, but may contain others, as well as\n * elements that are Comparable but not necessarily Comparable for\n * the same T, so we cannot invoke compareTo among them. To handle\n * this, the tree is ordered primarily by hash value, then by\n * Comparable.compareTo order if applicable. On lookup at a node,\n * if elements are not comparable or compare as 0 then both left\n * and right children may need to be searched in the case of tied\n * hash values. (This corresponds to the full list search that\n * would be necessary if all elements were non-Comparable and had\n * tied hashes.) On insertion, to keep a total ordering (or as\n * close as is required here) across rebalancings, we compare\n * classes and identityHashCodes as tie-breakers. The red-black\n * balancing code is updated from pre-jdk-collections\n * (http://example.com)\n * based in turn on Cormen, Leiserson, and Rivest \"Introduction to\n * Algorithms\" (CLR).\n *\n * TreeBins also require an additional locking mechanism. While\n * list traversal is always possible by readers even during\n * updates, tree traversal is not, mainly because of tree-rotations\n * that may change the root node and/or its linkages. TreeBins\n * include a simple read-write lock mechanism parasitic on the\n * main bin-synchronization strategy: Structural adjustments\n * associated with an insertion or removal are already bin-locked\n * (and so cannot conflict with other writers) but must wait for\n * ongoing readers to finish. Since there can be only one such\n * waiter, we use a simple scheme using a single \"waiter\" field to\n * block writers. However, readers need never block. If the root\n * lock is held, they proceed along the slow traversal path (via\n * next-pointers) until the lock becomes available or the list is\n * exhausted, whichever comes first. These cases are not fast, but\n * maximize aggregate expected throughput.\n *\n * Maintaining API and serialization compatibility with previous\n * versions of this class introduces several oddities. Mainly: We\n * leave untouched but unused constructor arguments referring to\n * concurrencyLevel. We accept a loadFactor constructor argument,\n * but apply it only to initial table capacity (which is the only\n * time that we can guarantee to honor it.) We also declare an\n * unused \"Segment\" class that is instantiated in minimal form\n * only when serializing.\n *\n * Also, solely for compatibility with previous versions of this\n * class, it extends AbstractMap, even though all of its methods\n * are overridden, so it is just useless baggage.\n *\n * This file is organized to make things a little easier to follow\n * while reading than they might otherwise: First the main static\n * declarations and utilities, then fields, then main public\n * methods (with a few factorings of multiple public methods into\n * internal ones), then sizing methods, trees, traversers, and\n * bulk operations.\n */\n /**\n * The largest possible table capacity. This value must be\n * exactly 1<<30 to stay within Java array allocation and indexing\n * bounds for power of two table sizes, and is further required\n * because the top two bits of 32bit hash fields are used for\n * control purposes.\n */\n private static final int MAXIMUM_CAPACITY = 1 << 30;\n\n /**\n * The default initial table capacity. Must be a power of 2\n * (i.e., at least 1) and at most MAXIMUM_CAPACITY.\n */\n private static final int DEFAULT_CAPACITY = 16;\n\n /**\n * The largest possible (non-power of two) array size.\n * Needed by toArray and related methods.\n */\n static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;\n\n /**\n * The default concurrency level for this table. Unused but\n * defined for compatibility with previous versions of this class.\n */\n private static final int DEFAULT_CONCURRENCY_LEVEL = 16;\n\n /**\n * The load factor for this table. Overrides of this value in\n * constructors affect only the initial table capacity. The\n * actual floating point value isn't normally used -- it is\n * simpler to use expressions such as {@code n - (n >>> 2)} for\n * the associated resizing threshold.\n */\n private static final float LOAD_FACTOR = 0.75f;\n\n /**\n * The bin count threshold for using a tree rather than list for a\n * bin. Bins are converted to trees when adding an element to a\n * bin with at least this many nodes. The value must be greater\n * than 2, and should be at least 8 to mesh with assumptions in\n * tree removal about conversion back to plain bins upon\n * shrinkage.\n */\n static final int TREEIFY_THRESHOLD = 8;\n\n /**\n * The bin count threshold for untreeifying a (split) bin during a\n * resize operation. Should be less than TREEIFY_THRESHOLD, and at\n * most 6 to mesh with shrinkage detection under removal.\n */\n static final int UNTREEIFY_THRESHOLD = 6;\n\n /**\n * The smallest table capacity for which bins may be treeified.\n * (Otherwise the table is resized if too many nodes in a bin.)\n * The value should be at least 4 * TREEIFY_THRESHOLD to avoid\n * conflicts between resizing and treeification thresholds.\n */\n static final int MIN_TREEIFY_CAPACITY = 64;\n\n /**\n * Minimum number of rebinnings per transfer step. Ranges are\n * subdivided to allow multiple resizer threads. This value\n * serves as a lower bound to avoid resizers encountering\n * excessive memory contention. The value should be at least\n * DEFAULT_CAPACITY.\n */\n private static final int MIN_TRANSFER_STRIDE = 16;\n\n /**\n * The number of bits used for generation stamp in sizeCtl.\n * Must be at least 6 for 32bit arrays.\n */\n private static final int RESIZE_STAMP_BITS = 16;\n\n /**\n * The maximum number of threads that can help resize.\n * Must fit in 32 - RESIZE_STAMP_BITS bits.\n */\n private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;\n\n /**\n * The bit shift for recording size stamp in sizeCtl.\n */\n private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;\n\n /*\n * Encodings for Node hash fields. See above for explanation.\n */\n // hash for forwarding nodes\n static final int MOVED = -1;\n\n // hash for roots of trees\n static final int TREEBIN = -2;\n\n static final int RESERVED = -3;\n\n // usable bits of normal node hash\n static final int HASH_BITS = 0x7fffffff;\n\n /**\n * Number of CPUS, to place bounds on some sizings\n */\n static final int NCPU = Runtime.getRuntime().availableProcessors();\n\n /**\n * Serialized pseudo-fields, provided only for jdk7 compatibility.\n * @serialField segments Segment[]\n * The segments, each of which is a specialized hash table.\n * @serialField segmentMask int\n * Mask value for indexing into segments. The upper bits of a\n * key's hash code are used to choose the segment.\n * @serialField segmentShift int\n * Shift value for indexing within segments.\n */\n private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(\"segments\", Segment[].class), new ObjectStreamField(\"segmentMask\", Integer.TYPE), new ObjectStreamField(\"segmentShift\", Integer.TYPE) };\n\n /**\n * Key-value entry. This class is never exported out as a\n * user-mutable Map.Entry (i.e., one supporting setValue; see\n * MapEntry below), but can be used for read-only traversals used\n * in bulk tasks. Subclasses of Node with a negative hash field\n * are special, and contain null keys and values (but are never\n * exported). Otherwise, keys and vals are never null.\n */\n static class Node implements Map.Entry {\n\n final int hash;\n\n final K key;\n\n volatile V val;\n\n volatile Node next;\n\n Node(int hash, K key, V val) {\n this.hash = hash;\n this.key = key;\n this.val = val;\n }\n\n Node(int hash, K key, V val, Node next) {\n this(hash, key, val);\n this.next = next;\n }\n\n public final K getKey() {\n return key;\n }\n\n public final V getValue() {\n return val;\n }\n\n public final int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public final String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public final V setValue(V value) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean equals(Object o) {\n Object k, v, u;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == (u = val) || v.equals(u)));\n }\n\n /**\n * Virtualized support for map.get(); overridden in subclasses.\n */\n Node find(int h, Object k) {\n Node e = this;\n if (k != null) {\n do {\n K ek;\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n } while ((e = e.next) != null);\n }\n return null;\n }\n }\n\n /**\n * Spreads (XORs) higher bits of hash to lower and also forces top\n * bit to 0. Because the table uses power-of-two masking, sets of\n * hashes that vary only in bits above the current mask will\n * always collide. (Among known examples are sets of Float keys\n * holding consecutive whole numbers in small tables.) So we\n * apply a transform that spreads the impact of higher bits\n * downward. There is a tradeoff between speed, utility, and\n * quality of bit-spreading. Because many common sets of hashes\n * are already reasonably distributed (so don't benefit from\n * spreading), and because we use trees to handle large sets of\n * collisions in bins, we just XOR some shifted bits in the\n * cheapest possible way to reduce systematic lossage, as well as\n * to incorporate impact of the highest bits that would otherwise\n * never be used in index calculations because of table bounds.\n */\n static final int spread(int h) {\n return (h ^ (h >>> 16)) & HASH_BITS;\n }\n\n /**\n * Returns a power of two table size for the given desired capacity.\n * See Hackers Delight, sec 3.2\n */\n private static final int tableSizeFor(int c) {\n int n = -1 >>> Integer.numberOfLeadingZeros(c - 1);\n return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;\n }\n\n /**\n * Returns x's Class if it is of the form \"class C implements\n * Comparable\", else null.\n */\n static Class comparableClassFor(Object x) {\n if (x instanceof Comparable) {\n Class c;\n Type[] ts, as;\n ParameterizedType p;\n if (// bypass checks\n (c = x.getClass()) == String.class)\n return c;\n if ((ts = c.getGenericInterfaces()) != null) {\n for (Type t : ts) {\n if ((t instanceof ParameterizedType) && ((p = (ParameterizedType) t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && // type arg is c\n as[0] == c)\n return c;\n }\n }\n }\n return null;\n }\n\n /**\n * Returns k.compareTo(x) if x matches kc (k's screened comparable\n * class), else 0.\n */\n // for cast to Comparable\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n static int compareComparables(Class kc, Object k, Object x) {\n return (x == null || x.getClass() != kc ? 0 : ((Comparable) k).compareTo(x));\n }\n\n /* ---------------- Table element access -------------- */\n /*\n * Atomic access methods are used for table elements as well as\n * elements of in-progress next table while resizing. All uses of\n * the tab arguments must be null checked by callers. All callers\n * also paranoically precheck that tab's length is not zero (or an\n * equivalent check), thus ensuring that any index argument taking\n * the form of a hash value anded with (length - 1) is a valid\n * index. Note that, to be correct wrt arbitrary concurrency\n * errors by users, these checks must operate on local variables,\n * which accounts for some odd-looking inline assignments below.\n * Note that calls to setTabAt always occur within locked regions,\n * and so require only release ordering.\n */\n @SuppressWarnings(\"unchecked\")\n static final Node tabAt(Node[] tab, int i) {\n return (Node) U.getReferenceAcquire(tab, ((long) i << ASHIFT) + ABASE);\n }\n\n static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {\n return U.compareAndSetReference(tab, ((long) i << ASHIFT) + ABASE, c, v);\n }\n\n static final void setTabAt(Node[] tab, int i, Node v) {\n U.putReferenceRelease(tab, ((long) i << ASHIFT) + ABASE, v);\n }\n\n /**\n * The array of bins. Lazily initialized upon first insertion.\n * Size is always a power of two. Accessed directly by iterators.\n */\n transient volatile Node[] table;\n\n /**\n * The next table to use; non-null only while resizing.\n */\n private transient volatile Node[] nextTable;\n\n /**\n * Base counter value, used mainly when there is no contention,\n * but also as a fallback during table initialization\n * races. Updated via CAS.\n */\n private transient volatile long baseCount;\n\n /**\n * Table initialization and resizing control. When negative, the\n * table is being initialized or resized: -1 for initialization,\n * else -(1 + the number of active resizing threads). Otherwise,\n * when table is null, holds the initial table size to use upon\n * creation, or 0 for default. After initialization, holds the\n * next element count value upon which to resize the table.\n */\n private transient volatile int sizeCtl;\n\n /**\n * The next table index (plus one) to split while resizing.\n */\n private transient volatile int transferIndex;\n\n /**\n * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.\n */\n private transient volatile int cellsBusy;\n\n /**\n * Table of counter cells. When non-null, size is a power of 2.\n */\n private transient volatile CounterCell[] counterCells;\n\n // views\n private transient KeySetView keySet;\n\n private transient ValuesView values;\n\n private transient EntrySetView entrySet;\n\n /**\n * Creates a new, empty map with the default initial table size (16).\n */\n public ConcurrentHashMap() {\n }\n\n /**\n * Creates a new, empty map with an initial table size\n * accommodating the specified number of elements without the need\n * to dynamically resize.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n */\n public ConcurrentHashMap(int initialCapacity) {\n this(initialCapacity, LOAD_FACTOR, 1);\n }\n\n /**\n * Creates a new map with the same mappings as the given map.\n *\n * @param m the map\n */\n public ConcurrentHashMap(Map m) {\n this.sizeCtl = DEFAULT_CAPACITY;\n putAll(m);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}) and\n * initial table density ({@code loadFactor}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative or the load factor is nonpositive\n *\n * @since 1.6\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor) {\n this(initialCapacity, loadFactor, 1);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}), initial\n * table density ({@code loadFactor}), and number of concurrently\n * updating threads ({@code concurrencyLevel}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @param concurrencyLevel the estimated number of concurrently\n * updating threads. The implementation may use this value as\n * a sizing hint.\n * @throws IllegalArgumentException if the initial capacity is\n * negative or the load factor or concurrencyLevel are\n * nonpositive\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) {\n if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)\n throw new IllegalArgumentException();\n if (// Use at least as many bins\n initialCapacity < concurrencyLevel)\n // as estimated threads\n initialCapacity = concurrencyLevel;\n long size = (long) (1.0 + (long) initialCapacity / loadFactor);\n int cap = (size >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) size);\n this.sizeCtl = cap;\n }\n\n // Original (since JDK1.2) Map methods\n public int size() {\n long n = sumCount();\n return ((n < 0L) ? 0 : (n > (long) Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) n);\n }\n\n public boolean isEmpty() {\n // ignore transient negative values\n return sumCount() <= 0L;\n }\n\n /**\n * Returns the value to which the specified key is mapped,\n * or {@code null} if this map contains no mapping for the key.\n *\n *

More formally, if this map contains a mapping from a key\n * {@code k} to a value {@code v} such that {@code key.equals(k)},\n * then this method returns {@code v}; otherwise it returns\n * {@code null}. (There can be at most one such mapping.)\n *\n * @throws NullPointerException if the specified key is null\n */\n public V get(Object key) {\n Node[] tab;\n Node e, p;\n int n, eh;\n K ek;\n int h = spread(key.hashCode());\n if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) {\n if ((eh = e.hash) == h) {\n if ((ek = e.key) == key || (ek != null && key.equals(ek)))\n return e.val;\n } else if (eh < 0)\n return (p = e.find(h, key)) != null ? p.val : null;\n while ((e = e.next) != null) {\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek))))\n return e.val;\n }\n }\n return null;\n }\n\n /**\n * Tests if the specified object is a key in this table.\n *\n * @param key possible key\n * @return {@code true} if and only if the specified object\n * is a key in this table, as determined by the\n * {@code equals} method; {@code false} otherwise\n * @throws NullPointerException if the specified key is null\n */\n public boolean containsKey(Object key) {\n return get(key) != null;\n }\n\n /**\n * Returns {@code true} if this map maps one or more keys to the\n * specified value. Note: This method may require a full traversal\n * of the map, and is much slower than method {@code containsKey}.\n *\n * @param value value whose presence in this map is to be tested\n * @return {@code true} if this map maps one or more keys to the\n * specified value\n * @throws NullPointerException if the specified value is null\n */\n public boolean containsValue(Object value) {\n if (value == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V v;\n if ((v = p.val) == value || (v != null && value.equals(v)))\n return true;\n }\n }\n return false;\n }\n\n /**\n * Maps the specified key to the specified value in this table.\n * Neither the key nor the value can be null.\n *\n *

The value can be retrieved by calling the {@code get} method\n * with a key that is equal to the original key.\n *\n * @param key key with which the specified value is to be associated\n * @param value value to be associated with the specified key\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key or value is null\n */\n public V put(K key, V value) {\n return putVal(key, value, false);\n }\n\n /**\n * Implementation for put and putIfAbsent\n */\n final V putVal(K key, V value, boolean onlyIfAbsent) {\n if (key == null || value == null)\n throw new NullPointerException();\n int hash = spread(key.hashCode());\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {\n if (casTabAt(tab, i, null, new Node(hash, key, value)))\n // no lock when adding to empty bin\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n onlyIfAbsent && fh == hash && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n V oldVal = null;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n oldVal = e.val;\n if (!onlyIfAbsent)\n e.val = value;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n pred.next = new Node(hash, key, value);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n Node p;\n binCount = 2;\n if ((p = ((TreeBin) f).putTreeVal(hash, key, value)) != null) {\n oldVal = p.val;\n if (!onlyIfAbsent)\n p.val = value;\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (oldVal != null)\n return oldVal;\n break;\n }\n }\n }\n addCount(1L, binCount);\n return null;\n }\n\n /**\n * Copies all of the mappings from the specified map to this one.\n * These mappings replace any mappings that this map had for any of the\n * keys currently in the specified map.\n *\n * @param m mappings to be stored in this map\n */\n public void putAll(Map m) {\n tryPresize(m.size());\n for (Map.Entry e : m.entrySet()) putVal(e.getKey(), e.getValue(), false);\n }\n\n /**\n * Removes the key (and its corresponding value) from this map.\n * This method does nothing if the key is not in the map.\n *\n * @param key the key that needs to be removed\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key is null\n */\n public V remove(Object key) {\n return replaceNode(key, null, null);\n }\n\n /**\n * Implementation for the four public remove/replace methods:\n * Replaces node value with v, conditional upon match of cv if\n * non-null. If resulting value is null, delete.\n */\n final V replaceNode(Object key, V value, Object cv) {\n int hash = spread(key.hashCode());\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0 || (f = tabAt(tab, i = (n - 1) & hash)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n V oldVal = null;\n boolean validated = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n validated = true;\n for (Node e = f, pred = null; ; ) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n V ev = e.val;\n if (cv == null || cv == ev || (ev != null && cv.equals(ev))) {\n oldVal = ev;\n if (value != null)\n e.val = value;\n else if (pred != null)\n pred.next = e.next;\n else\n setTabAt(tab, i, e.next);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n validated = true;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(hash, key, null)) != null) {\n V pv = p.val;\n if (cv == null || cv == pv || (pv != null && cv.equals(pv))) {\n oldVal = pv;\n if (value != null)\n p.val = value;\n else if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (validated) {\n if (oldVal != null) {\n if (value == null)\n addCount(-1L, -1);\n return oldVal;\n }\n break;\n }\n }\n }\n return null;\n }\n\n /**\n * Removes all of the mappings from this map.\n */\n public void clear() {\n // negative number of deletions\n long delta = 0L;\n int i = 0;\n Node[] tab = table;\n while (tab != null && i < tab.length) {\n int fh;\n Node f = tabAt(tab, i);\n if (f == null)\n ++i;\n else if ((fh = f.hash) == MOVED) {\n tab = helpTransfer(tab, f);\n // restart\n i = 0;\n } else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node p = (fh >= 0 ? f : (f instanceof TreeBin) ? ((TreeBin) f).first : null);\n while (p != null) {\n --delta;\n p = p.next;\n }\n setTabAt(tab, i++, null);\n }\n }\n }\n }\n if (delta != 0L)\n addCount(delta, -1);\n }\n\n /**\n * Returns a {@link Set} view of the keys contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from this map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations. It does not support the {@code add} or\n * {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public KeySetView keySet() {\n KeySetView ks;\n if ((ks = keySet) != null)\n return ks;\n return keySet = new KeySetView(this, null);\n }\n\n /**\n * Returns a {@link Collection} view of the values contained in this map.\n * The collection is backed by the map, so changes to the map are\n * reflected in the collection, and vice-versa. The collection\n * supports element removal, which removes the corresponding\n * mapping from this map, via the {@code Iterator.remove},\n * {@code Collection.remove}, {@code removeAll},\n * {@code retainAll}, and {@code clear} operations. It does not\n * support the {@code add} or {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}\n * and {@link Spliterator#NONNULL}.\n *\n * @return the collection view\n */\n public Collection values() {\n ValuesView vs;\n if ((vs = values) != null)\n return vs;\n return values = new ValuesView(this);\n }\n\n /**\n * Returns a {@link Set} view of the mappings contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from the map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public Set> entrySet() {\n EntrySetView es;\n if ((es = entrySet) != null)\n return es;\n return entrySet = new EntrySetView(this);\n }\n\n /**\n * Returns the hash code value for this {@link Map}, i.e.,\n * the sum of, for each key-value pair in the map,\n * {@code key.hashCode() ^ value.hashCode()}.\n *\n * @return the hash code value for this map\n */\n public int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) h += p.key.hashCode() ^ p.val.hashCode();\n }\n return h;\n }\n\n /**\n * Returns a string representation of this map. The string\n * representation consists of a list of key-value mappings (in no\n * particular order) enclosed in braces (\"{@code {}}\"). Adjacent\n * mappings are separated by the characters {@code \", \"} (comma\n * and space). Each key-value mapping is rendered as the key\n * followed by an equals sign (\"{@code =}\") followed by the\n * associated value.\n *\n * @return a string representation of this map\n */\n public String toString() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n StringBuilder sb = new StringBuilder();\n sb.append('{');\n Node p;\n if ((p = it.advance()) != null) {\n for (; ; ) {\n K k = p.key;\n V v = p.val;\n sb.append(k == this ? \"(this Map)\" : k);\n sb.append('=');\n sb.append(v == this ? \"(this Map)\" : v);\n if ((p = it.advance()) == null)\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append('}').toString();\n }\n\n /**\n * Compares the specified object with this map for equality.\n * Returns {@code true} if the given object is a map with the same\n * mappings as this map. This operation may return misleading\n * results if either map is concurrently modified during execution\n * of this method.\n *\n * @param o object to be compared for equality with this map\n * @return {@code true} if the specified object is equal to this map\n */\n public boolean equals(Object o) {\n if (o != this) {\n if (!(o instanceof Map))\n return false;\n Map m = (Map) o;\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n for (Node p; (p = it.advance()) != null; ) {\n V val = p.val;\n Object v = m.get(p.key);\n if (v == null || (v != val && !v.equals(val)))\n return false;\n }\n for (Map.Entry e : m.entrySet()) {\n Object mk, mv, v;\n if ((mk = e.getKey()) == null || (mv = e.getValue()) == null || (v = get(mk)) == null || (mv != v && !mv.equals(v)))\n return false;\n }\n }\n return true;\n }\n\n /**\n * Stripped-down version of helper class used in previous version,\n * declared for the sake of serialization compatibility.\n */\n static class Segment extends ReentrantLock implements Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n final float loadFactor;\n\n Segment(float lf) {\n this.loadFactor = lf;\n }\n }\n\n /**\n * Saves this map to a stream (that is, serializes it).\n *\n * @param s the stream\n * @throws java.io.IOException if an I/O error occurs\n * @serialData\n * the serialized fields, followed by the key (Object) and value\n * (Object) for each key-value mapping, followed by a null pair.\n * The key-value mappings are emitted in no particular order.\n */\n private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {\n // For serialization compatibility\n // Emulate segment calculation from previous version of this class\n int sshift = 0;\n int ssize = 1;\n while (ssize < DEFAULT_CONCURRENCY_LEVEL) {\n ++sshift;\n ssize <<= 1;\n }\n int segmentShift = 32 - sshift;\n int segmentMask = ssize - 1;\n @SuppressWarnings(\"unchecked\")\n Segment[] segments = (Segment[]) new Segment[DEFAULT_CONCURRENCY_LEVEL];\n for (int i = 0; i < segments.length; ++i) segments[i] = new Segment(LOAD_FACTOR);\n java.io.ObjectOutputStream.PutField streamFields = s.putFields();\n streamFields.put(\"segments\", segments);\n streamFields.put(\"segmentShift\", segmentShift);\n streamFields.put(\"segmentMask\", segmentMask);\n s.writeFields();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n s.writeObject(p.key);\n s.writeObject(p.val);\n }\n }\n s.writeObject(null);\n s.writeObject(null);\n }\n\n /**\n * Reconstitutes this map from a stream (that is, deserializes it).\n * @param s the stream\n * @throws ClassNotFoundException if the class of a serialized object\n * could not be found\n * @throws java.io.IOException if an I/O error occurs\n */\n private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {\n /*\n * To improve performance in typical cases, we create nodes\n * while reading, then place in table once size is known.\n * However, we must also validate uniqueness and deal with\n * overpopulated bins while doing so, which requires\n * specialized versions of putVal mechanics.\n */\n // force exclusion for table construction\n sizeCtl = -1;\n s.defaultReadObject();\n long size = 0L;\n Node p = null;\n for (; ; ) {\n @SuppressWarnings(\"unchecked\")\n K k = (K) s.readObject();\n @SuppressWarnings(\"unchecked\")\n V v = (V) s.readObject();\n if (k != null && v != null) {\n p = new Node(spread(k.hashCode()), k, v, p);\n ++size;\n } else\n break;\n }\n if (size == 0L)\n sizeCtl = 0;\n else {\n long ts = (long) (1.0 + size / LOAD_FACTOR);\n int n = (ts >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) ts);\n @SuppressWarnings(\"unchecked\")\n Node[] tab = (Node[]) new Node[n];\n int mask = n - 1;\n long added = 0L;\n while (p != null) {\n boolean insertAtFront;\n Node next = p.next, first;\n int h = p.hash, j = h & mask;\n if ((first = tabAt(tab, j)) == null)\n insertAtFront = true;\n else {\n K k = p.key;\n if (first.hash < 0) {\n TreeBin t = (TreeBin) first;\n if (t.putTreeVal(h, k, p.val) == null)\n ++added;\n insertAtFront = false;\n } else {\n int binCount = 0;\n insertAtFront = true;\n Node q;\n K qk;\n for (q = first; q != null; q = q.next) {\n if (q.hash == h && ((qk = q.key) == k || (qk != null && k.equals(qk)))) {\n insertAtFront = false;\n break;\n }\n ++binCount;\n }\n if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {\n insertAtFront = false;\n ++added;\n p.next = first;\n TreeNode hd = null, tl = null;\n for (q = p; q != null; q = q.next) {\n TreeNode t = new TreeNode(q.hash, q.key, q.val, null, null);\n if ((t.prev = tl) == null)\n hd = t;\n else\n tl.next = t;\n tl = t;\n }\n setTabAt(tab, j, new TreeBin(hd));\n }\n }\n }\n if (insertAtFront) {\n ++added;\n p.next = first;\n setTabAt(tab, j, p);\n }\n p = next;\n }\n table = tab;\n sizeCtl = n - (n >>> 2);\n baseCount = added;\n }\n }\n\n // ConcurrentMap methods\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V putIfAbsent(K key, V value) {\n return putVal(key, value, true);\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object key, Object value) {\n if (key == null)\n throw new NullPointerException();\n return value != null && replaceNode(key, null, value) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if any of the arguments are null\n */\n public boolean replace(K key, V oldValue, V newValue) {\n if (key == null || oldValue == null || newValue == null)\n throw new NullPointerException();\n return replaceNode(key, newValue, oldValue) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V replace(K key, V value) {\n if (key == null || value == null)\n throw new NullPointerException();\n return replaceNode(key, value, null);\n }\n\n // Overrides of JDK8+ Map extension method defaults\n /**\n * Returns the value to which the specified key is mapped, or the\n * given default value if this map contains no mapping for the\n * key.\n *\n * @param key the key whose associated value is to be returned\n * @param defaultValue the value to return if this map contains\n * no mapping for the given key\n * @return the mapping for the key, if present; else the default value\n * @throws NullPointerException if the specified key is null\n */\n public V getOrDefault(Object key, V defaultValue) {\n V v;\n return (v = get(key)) == null ? defaultValue : v;\n }\n\n public void forEach(BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n action.accept(p.key, p.val);\n }\n }\n }\n\n public void replaceAll(BiFunction function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V oldValue = p.val;\n for (K key = p.key; ; ) {\n V newValue = function.apply(key, oldValue);\n if (newValue == null)\n throw new NullPointerException();\n if (replaceNode(key, newValue, oldValue) != null || (oldValue = get(key)) == null)\n break;\n }\n }\n }\n }\n\n boolean removeEntryIf(Predicate> function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n Map.Entry e = new AbstractMap.SimpleImmutableEntry<>(k, v);\n if (function.test(e) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n boolean removeValueIf(Predicate function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n if (function.test(v) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n /**\n * If the specified key is not already associated with a value,\n * attempts to compute its value using the given mapping function\n * and enters it into this map unless {@code null}. The entire\n * method invocation is performed atomically. The supplied\n * function is invoked exactly once per invocation of this method\n * if the key is absent, else not at all. Some attempted update\n * operations on this map by other threads may be blocked while\n * computation is in progress, so the computation should be short\n * and simple.\n *\n *

The mapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param mappingFunction the function to compute a value\n * @return the current (existing or computed) value associated with\n * the specified key, or null if the computed value is null\n * @throws NullPointerException if the specified key or mappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the mappingFunction does so,\n * in which case the mapping is left unestablished\n */\n public V computeIfAbsent(K key, Function mappingFunction) {\n if (key == null || mappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = mappingFunction.apply(key)) != null)\n node = new Node(h, key, val);\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n fh == h && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n boolean added = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = e.val;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n if ((val = mappingFunction.apply(key)) != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n added = true;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null)\n val = p.val;\n else if ((val = mappingFunction.apply(key)) != null) {\n added = true;\n t.putTreeVal(h, key, val);\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (!added)\n return val;\n break;\n }\n }\n }\n if (val != null)\n addCount(1L, binCount);\n return val;\n }\n\n /**\n * If the value for the specified key is present, attempts to\n * compute a new mapping given the key and its current mapped\n * value. The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method if the key is present, else not at all. Some\n * attempted update operations on this map by other threads may be\n * blocked while computation is in progress, so the computation\n * should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which a value may be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V computeIfPresent(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null) {\n val = remappingFunction.apply(key, p.val);\n if (val != null)\n p.val = val;\n else {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0)\n break;\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * Attempts to compute a mapping for the specified key and its\n * current mapped value (or {@code null} if there is no current\n * mapping). The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method. Some attempted update operations on this map by\n * other threads may be blocked while computation is in progress,\n * so the computation should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V compute(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = remappingFunction.apply(key, null)) != null) {\n delta = 1;\n node = new Node(h, key, val);\n }\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n val = remappingFunction.apply(key, null);\n if (val != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n delta = 1;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 1;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null)\n p = r.findTreeNode(h, key, null);\n else\n p = null;\n V pv = (p == null) ? null : p.val;\n val = remappingFunction.apply(key, pv);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * If the specified key is not already associated with a\n * (non-null) value, associates it with the given value.\n * Otherwise, replaces the value with the results of the given\n * remapping function, or removes if {@code null}. The entire\n * method invocation is performed atomically. Some attempted\n * update operations on this map by other threads may be blocked\n * while computation is in progress, so the computation should be\n * short and simple, and must not attempt to update any other\n * mappings of this Map.\n *\n * @param key key with which the specified value is to be associated\n * @param value the value to use if absent\n * @param remappingFunction the function to recompute a value if present\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or the\n * remappingFunction is null\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V merge(K key, V value, BiFunction remappingFunction) {\n if (key == null || value == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n if (casTabAt(tab, i, null, new Node(h, key, value))) {\n delta = 1;\n val = value;\n break;\n }\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(e.val, value);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n delta = 1;\n val = value;\n pred.next = new Node(h, key, val);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r = t.root;\n TreeNode p = (r == null) ? null : r.findTreeNode(h, key, null);\n val = (p == null) ? value : remappingFunction.apply(p.val, value);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n // Hashtable legacy methods\n /**\n * Tests if some key maps into the specified value in this table.\n *\n *

Note that this method is identical in functionality to\n * {@link #containsValue(Object)}, and exists solely to ensure\n * full compatibility with class {@link java.util.Hashtable},\n * which supported this method prior to introduction of the\n * Java Collections Framework.\n *\n * @param value a value to search for\n * @return {@code true} if and only if some key maps to the\n * {@code value} argument in this table as\n * determined by the {@code equals} method;\n * {@code false} otherwise\n * @throws NullPointerException if the specified value is null\n */\n public boolean contains(Object value) {\n return containsValue(value);\n }\n\n /**\n * Returns an enumeration of the keys in this table.\n *\n * @return an enumeration of the keys in this table\n * @see #keySet()\n */\n public Enumeration keys() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, this);\n }\n\n /**\n * Returns an enumeration of the values in this table.\n *\n * @return an enumeration of the values in this table\n * @see #values()\n */\n public Enumeration elements() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, this);\n }\n\n // ConcurrentHashMap-only methods\n /**\n * Returns the number of mappings. This method should be used\n * instead of {@link #size} because a ConcurrentHashMap may\n * contain more mappings than can be represented as an int. The\n * value returned is an estimate; the actual count may differ if\n * there are concurrent insertions or removals.\n *\n * @return the number of mappings\n * @since 1.8\n */\n public long mappingCount() {\n long n = sumCount();\n // ignore transient negative values\n return (n < 0L) ? 0L : n;\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param the element type of the returned set\n * @return the new set\n * @since 1.8\n */\n public static KeySetView newKeySet() {\n return new KeySetView(new ConcurrentHashMap(), Boolean.TRUE);\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @param the element type of the returned set\n * @return the new set\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n * @since 1.8\n */\n public static KeySetView newKeySet(int initialCapacity) {\n return new KeySetView(new ConcurrentHashMap(initialCapacity), Boolean.TRUE);\n }\n\n /**\n * Returns a {@link Set} view of the keys in this map, using the\n * given common mapped value for any additions (i.e., {@link\n * Collection#add} and {@link Collection#addAll(Collection)}).\n * This is of course only appropriate if it is acceptable to use\n * the same value for all additions from this view.\n *\n * @param mappedValue the mapped value to use for any additions\n * @return the set view\n * @throws NullPointerException if the mappedValue is null\n */\n public KeySetView keySet(V mappedValue) {\n if (mappedValue == null)\n throw new NullPointerException();\n return new KeySetView(this, mappedValue);\n }\n\n /**\n * A node inserted at head of bins during transfer operations.\n */\n static final class ForwardingNode extends Node {\n\n final Node[] nextTable;\n\n ForwardingNode(Node[] tab) {\n super(MOVED, null, null);\n this.nextTable = tab;\n }\n\n Node find(int h, Object k) {\n // loop to avoid arbitrarily deep recursion on forwarding nodes\n outer: for (Node[] tab = nextTable; ; ) {\n Node e;\n int n;\n if (k == null || tab == null || (n = tab.length) == 0 || (e = tabAt(tab, (n - 1) & h)) == null)\n return null;\n for (; ; ) {\n int eh;\n K ek;\n if ((eh = e.hash) == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n if (eh < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n continue outer;\n } else\n return e.find(h, k);\n }\n if ((e = e.next) == null)\n return null;\n }\n }\n }\n }\n\n /**\n * A place-holder node used in computeIfAbsent and compute.\n */\n static final class ReservationNode extends Node {\n\n ReservationNode() {\n super(RESERVED, null, null);\n }\n\n Node find(int h, Object k) ", "post_mask_code": "\n }\n\n /* ---------------- Table Initialization and Resizing -------------- */\n /**\n * Returns the stamp bits for resizing a table of size n.\n * Must be negative when shifted left by RESIZE_STAMP_SHIFT.\n */\n static final int resizeStamp(int n) {\n return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));\n }\n\n /**\n * Initializes table, using the size recorded in sizeCtl.\n */\n private final Node[] initTable() {\n Node[] tab;\n int sc;\n while ((tab = table) == null || tab.length == 0) {\n if ((sc = sizeCtl) < 0)\n // lost initialization race; just spin\n Thread.yield();\n else if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if ((tab = table) == null || tab.length == 0) {\n int n = (sc > 0) ? sc : DEFAULT_CAPACITY;\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = tab = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n break;\n }\n }\n return tab;\n }\n\n /**\n * Adds to count, and if table is too small and not already\n * resizing, initiates transfer. If already resizing, helps\n * perform transfer if work is available. Rechecks occupancy\n * after a transfer to see if another resize is already needed\n * because resizings are lagging additions.\n *\n * @param x the count to add\n * @param check if <0, don't check resize, if <= 1 only check if uncontended\n */\n private final void addCount(long x, int check) {\n CounterCell[] cs;\n long b, s;\n if ((cs = counterCells) != null || !U.compareAndSetLong(this, BASECOUNT, b = baseCount, s = b + x)) {\n CounterCell c;\n long v;\n int m;\n boolean uncontended = true;\n if (cs == null || (m = cs.length - 1) < 0 || (c = cs[ThreadLocalRandom.getProbe() & m]) == null || !(uncontended = U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))) {\n fullAddCount(x, uncontended);\n return;\n }\n if (check <= 1)\n return;\n s = sumCount();\n }\n if (check >= 0) {\n Node[] tab, nt;\n int n, sc;\n while (s >= (long) (sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) {\n int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT;\n if (sc < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || (nt = nextTable) == null || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1))\n transfer(tab, nt);\n } else if (U.compareAndSetInt(this, SIZECTL, sc, rs + 2))\n transfer(tab, null);\n s = sumCount();\n }\n }\n }\n\n /**\n * Helps transfer if a resize is in progress.\n */\n final Node[] helpTransfer(Node[] tab, Node f) {\n Node[] nextTab;\n int sc;\n if (tab != null && (f instanceof ForwardingNode) && (nextTab = ((ForwardingNode) f).nextTable) != null) {\n int rs = resizeStamp(tab.length) << RESIZE_STAMP_SHIFT;\n while (nextTab == nextTable && table == tab && (sc = sizeCtl) < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1)) {\n transfer(tab, nextTab);\n break;\n }\n }\n return nextTab;\n }\n return table;\n }\n\n /**\n * Tries to presize table to accommodate the given number of elements.\n *\n * @param size number of elements (doesn't need to be perfectly accurate)\n */\n private final void tryPresize(int size) {\n int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(size + (size >>> 1) + 1);\n int sc;\n while ((sc = sizeCtl) >= 0) {\n Node[] tab = table;\n int n;\n if (tab == null || (n = tab.length) == 0) {\n n = (sc > c) ? sc : c;\n if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if (table == tab) {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n }\n } else if (c <= sc || n >= MAXIMUM_CAPACITY)\n break;\n else if (tab == table) {\n int rs = resizeStamp(n);\n if (U.compareAndSetInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2))\n transfer(tab, null);\n }\n }\n }\n\n /**\n * Moves and/or copies the nodes in each bin to new table. See\n * above for explanation.\n */\n private final void transfer(Node[] tab, Node[] nextTab) {\n int n = tab.length, stride;\n if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)\n // subdivide range\n stride = MIN_TRANSFER_STRIDE;\n if (nextTab == null) {\n // initiating\n try {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n << 1];\n nextTab = nt;\n } catch (Throwable ex) {\n // try to cope with OOME\n sizeCtl = Integer.MAX_VALUE;\n return;\n }\n nextTable = nextTab;\n transferIndex = n;\n }\n int nextn = nextTab.length;\n ForwardingNode fwd = new ForwardingNode(nextTab);\n boolean advance = true;\n // to ensure sweep before committing nextTab\n boolean finishing = false;\n for (int i = 0, bound = 0; ; ) {\n Node f;\n int fh;\n while (advance) {\n int nextIndex, nextBound;\n if (--i >= bound || finishing)\n advance = false;\n else if ((nextIndex = transferIndex) <= 0) {\n i = -1;\n advance = false;\n } else if (U.compareAndSetInt(this, TRANSFERINDEX, nextIndex, nextBound = (nextIndex > stride ? nextIndex - stride : 0))) {\n bound = nextBound;\n i = nextIndex - 1;\n advance = false;\n }\n }\n if (i < 0 || i >= n || i + n >= nextn) {\n int sc;\n if (finishing) {\n nextTable = null;\n table = nextTab;\n sizeCtl = (n << 1) - (n >>> 1);\n return;\n }\n if (U.compareAndSetInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {\n if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)\n return;\n finishing = advance = true;\n // recheck before commit\n i = n;\n }\n } else if ((f = tabAt(tab, i)) == null)\n advance = casTabAt(tab, i, null, fwd);\n else if ((fh = f.hash) == MOVED)\n // already processed\n advance = true;\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node ln, hn;\n if (fh >= 0) {\n int runBit = fh & n;\n Node lastRun = f;\n for (Node p = f.next; p != null; p = p.next) {\n int b = p.hash & n;\n if (b != runBit) {\n runBit = b;\n lastRun = p;\n }\n }\n if (runBit == 0) {\n ln = lastRun;\n hn = null;\n } else {\n hn = lastRun;\n ln = null;\n }\n for (Node p = f; p != lastRun; p = p.next) {\n int ph = p.hash;\n K pk = p.key;\n V pv = p.val;\n if ((ph & n) == 0)\n ln = new Node(ph, pk, pv, ln);\n else\n hn = new Node(ph, pk, pv, hn);\n }\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof TreeBin) {\n TreeBin t = (TreeBin) f;\n TreeNode lo = null, loTail = null;\n TreeNode hi = null, hiTail = null;\n int lc = 0, hc = 0;\n for (Node e = t.first; e != null; e = e.next) {\n int h = e.hash;\n TreeNode p = new TreeNode(h, e.key, e.val, null, null);\n if ((h & n) == 0) {\n if ((p.prev = loTail) == null)\n lo = p;\n else\n loTail.next = p;\n loTail = p;\n ++lc;\n } else {\n if ((p.prev = hiTail) == null)\n hi = p;\n else\n hiTail.next = p;\n hiTail = p;\n ++hc;\n }\n }\n ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : (hc != 0) ? new TreeBin(lo) : t;\n hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : (lc != 0) ? new TreeBin(hi) : t;\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n }\n }\n }\n\n /**\n * A padded cell for distributing counts. Adapted from LongAdder\n * and Striped64. See their internal docs for explanation.\n */\n @jdk.internal.vm.annotation.Contended\n static final class CounterCell {\n\n volatile long value;\n\n CounterCell(long x) {\n value = x;\n }\n }\n\n final long sumCount() {\n CounterCell[] cs = counterCells;\n long sum = baseCount;\n if (cs != null) {\n for (CounterCell c : cs) if (c != null)\n sum += c.value;\n }\n return sum;\n }\n\n // See LongAdder version for explanation\n private final void fullAddCount(long x, boolean wasUncontended) {\n int h;\n if ((h = ThreadLocalRandom.getProbe()) == 0) {\n // force initialization\n ThreadLocalRandom.localInit();\n h = ThreadLocalRandom.getProbe();\n wasUncontended = true;\n }\n // True if last slot nonempty\n boolean collide = false;\n for (; ; ) {\n CounterCell[] cs;\n CounterCell c;\n int n;\n long v;\n if ((cs = counterCells) != null && (n = cs.length) > 0) {\n if ((c = cs[(n - 1) & h]) == null) {\n if (cellsBusy == 0) {\n // Try to attach new Cell\n // Optimistic create\n CounterCell r = new CounterCell(x);\n if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean created = false;\n try {\n // Recheck under lock\n CounterCell[] rs;\n int m, j;\n if ((rs = counterCells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) {\n rs[j] = r;\n created = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (created)\n break;\n // Slot is now non-empty\n continue;\n }\n }\n collide = false;\n } else if (// CAS already known to fail\n !wasUncontended)\n // Continue after rehash\n wasUncontended = true;\n else if (U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))\n break;\n else if (counterCells != cs || n >= NCPU)\n // At max size or stale\n collide = false;\n else if (!collide)\n collide = true;\n else if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n try {\n if (// Expand table unless stale\n counterCells == cs)\n counterCells = Arrays.copyOf(cs, n << 1);\n } finally {\n cellsBusy = 0;\n }\n collide = false;\n // Retry with expanded table\n continue;\n }\n h = ThreadLocalRandom.advanceProbe(h);\n } else if (cellsBusy == 0 && counterCells == cs && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean init = false;\n try {\n // Initialize table\n if (counterCells == cs) {\n CounterCell[] rs = new CounterCell[2];\n rs[h & 1] = new CounterCell(x);\n counterCells = rs;\n init = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (init)\n break;\n } else if (U.compareAndSetLong(this, BASECOUNT, v = baseCount, v + x))\n // Fall back on using base\n break;\n }\n }\n\n /**\n * Replaces all linked nodes in bin at given index unless table is\n * too small, in which case resizes instead.\n */\n private final void treeifyBin(Node[] tab, int index) {\n Node b;\n int n;\n if (tab != null) {\n if ((n = tab.length) < MIN_TREEIFY_CAPACITY)\n tryPresize(n << 1);\n else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {\n synchronized (b) {\n if (tabAt(tab, index) == b) {\n TreeNode hd = null, tl = null;\n for (Node e = b; e != null; e = e.next) {\n TreeNode p = new TreeNode(e.hash, e.key, e.val, null, null);\n if ((p.prev = tl) == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n setTabAt(tab, index, new TreeBin(hd));\n }\n }\n }\n }\n }\n\n /**\n * Returns a list of non-TreeNodes replacing those in given list.\n */\n static Node untreeify(Node b) {\n Node hd = null, tl = null;\n for (Node q = b; q != null; q = q.next) {\n Node p = new Node(q.hash, q.key, q.val);\n if (tl == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n return hd;\n }\n\n /**\n * Nodes for use in TreeBins.\n */\n static final class TreeNode extends Node {\n\n // red-black tree links\n TreeNode parent;\n\n TreeNode left;\n\n TreeNode right;\n\n // needed to unlink next upon deletion\n TreeNode prev;\n\n boolean red;\n\n TreeNode(int hash, K key, V val, Node next, TreeNode parent) {\n super(hash, key, val, next);\n this.parent = parent;\n }\n\n Node find(int h, Object k) {\n return findTreeNode(h, k, null);\n }\n\n /**\n * Returns the TreeNode (or null if not found) for the given key\n * starting at given root.\n */\n final TreeNode findTreeNode(int h, Object k, Class kc) {\n if (k != null) {\n TreeNode p = this;\n do {\n int ph, dir;\n K pk;\n TreeNode q;\n TreeNode pl = p.left, pr = p.right;\n if ((ph = p.hash) > h)\n p = pl;\n else if (ph < h)\n p = pr;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if (pl == null)\n p = pr;\n else if (pr == null)\n p = pl;\n else if ((kc != null || (kc = comparableClassFor(k)) != null) && (dir = compareComparables(kc, k, pk)) != 0)\n p = (dir < 0) ? pl : pr;\n else if ((q = pr.findTreeNode(h, k, kc)) != null)\n return q;\n else\n p = pl;\n } while (p != null);\n }\n return null;\n }\n }\n\n /**\n * TreeNodes used at the heads of bins. TreeBins do not hold user\n * keys or values, but instead point to list of TreeNodes and\n * their root. They also maintain a parasitic read-write lock\n * forcing writers (who hold bin lock) to wait for readers (who do\n * not) to complete before tree restructuring operations.\n */\n static final class TreeBin extends Node {\n\n TreeNode root;\n\n volatile TreeNode first;\n\n volatile Thread waiter;\n\n volatile int lockState;\n\n // values for lockState\n // set while holding write lock\n static final int WRITER = 1;\n\n // set when waiting for write lock\n static final int WAITER = 2;\n\n // increment value for setting read lock\n static final int READER = 4;\n\n /**\n * Tie-breaking utility for ordering insertions when equal\n * hashCodes and non-comparable. We don't require a total\n * order, just a consistent insertion rule to maintain\n * equivalence across rebalancings. Tie-breaking further than\n * necessary simplifies testing a bit.\n */\n static int tieBreakOrder(Object a, Object b) {\n int d;\n if (a == null || b == null || (d = a.getClass().getName().compareTo(b.getClass().getName())) == 0)\n d = (System.identityHashCode(a) <= System.identityHashCode(b) ? -1 : 1);\n return d;\n }\n\n /**\n * Creates bin with initial set of nodes headed by b.\n */\n TreeBin(TreeNode b) {\n super(TREEBIN, null, null);\n this.first = b;\n TreeNode r = null;\n for (TreeNode x = b, next; x != null; x = next) {\n next = (TreeNode) x.next;\n x.left = x.right = null;\n if (r == null) {\n x.parent = null;\n x.red = false;\n r = x;\n } else {\n K k = x.key;\n int h = x.hash;\n Class kc = null;\n for (TreeNode p = r; ; ) {\n int dir, ph;\n K pk = p.key;\n if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0)\n dir = tieBreakOrder(k, pk);\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n x.parent = xp;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n r = balanceInsertion(r, x);\n break;\n }\n }\n }\n }\n this.root = r;\n assert checkInvariants(root);\n }\n\n /**\n * Acquires write lock for tree restructuring.\n */\n private final void lockRoot() {\n if (!U.compareAndSetInt(this, LOCKSTATE, 0, WRITER))\n // offload to separate method\n contendedLock();\n }\n\n /**\n * Releases write lock for tree restructuring.\n */\n private final void unlockRoot() {\n lockState = 0;\n }\n\n /**\n * Possibly blocks awaiting root lock.\n */\n private final void contendedLock() {\n boolean waiting = false;\n for (int s; ; ) {\n if (((s = lockState) & ~WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, WRITER)) {\n if (waiting)\n waiter = null;\n return;\n }\n } else if ((s & WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, s | WAITER)) {\n waiting = true;\n waiter = Thread.currentThread();\n }\n } else if (waiting)\n LockSupport.park(this);\n }\n }\n\n /**\n * Returns matching node or null if none. Tries to search\n * using tree comparisons from root, but continues linear\n * search when lock not available.\n */\n final Node find(int h, Object k) {\n if (k != null) {\n for (Node e = first; e != null; ) {\n int s;\n K ek;\n if (((s = lockState) & (WAITER | WRITER)) != 0) {\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n e = e.next;\n } else if (U.compareAndSetInt(this, LOCKSTATE, s, s + READER)) {\n TreeNode r, p;\n try {\n p = ((r = root) == null ? null : r.findTreeNode(h, k, null));\n } finally {\n Thread w;\n if (U.getAndAddInt(this, LOCKSTATE, -READER) == (READER | WAITER) && (w = waiter) != null)\n LockSupport.unpark(w);\n }\n return p;\n }\n }\n }\n return null;\n }\n\n /**\n * Finds or adds a node.\n * @return null if added\n */\n final TreeNode putTreeVal(int h, K k, V v) {\n Class kc = null;\n boolean searched = false;\n for (TreeNode p = root; ; ) {\n int dir, ph;\n K pk;\n if (p == null) {\n first = root = new TreeNode(h, k, v, null, null);\n break;\n } else if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) {\n if (!searched) {\n TreeNode q, ch;\n searched = true;\n if (((ch = p.left) != null && (q = ch.findTreeNode(h, k, kc)) != null) || ((ch = p.right) != null && (q = ch.findTreeNode(h, k, kc)) != null))\n return q;\n }\n dir = tieBreakOrder(k, pk);\n }\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n TreeNode x, f = first;\n first = x = new TreeNode(h, k, v, f, xp);\n if (f != null)\n f.prev = x;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n if (!xp.red)\n x.red = true;\n else {\n lockRoot();\n try {\n root = balanceInsertion(root, x);\n } finally {\n unlockRoot();\n }\n }\n break;\n }\n }\n assert checkInvariants(root);\n return null;\n }\n\n /**\n * Removes the given node, that must be present before this\n * call. This is messier than typical red-black deletion code\n * because we cannot swap the contents of an interior node\n * with a leaf successor that is pinned by \"next\" pointers\n * that are accessible independently of lock. So instead we\n * swap the tree linkages.\n *\n * @return true if now too small, so should be untreeified\n */\n final boolean removeTreeNode(TreeNode p) {\n TreeNode next = (TreeNode) p.next;\n // unlink traversal pointers\n TreeNode pred = p.prev;\n TreeNode r, rl;\n if (pred == null)\n first = next;\n else\n pred.next = next;\n if (next != null)\n next.prev = pred;\n if (first == null) {\n root = null;\n return true;\n }\n if (// too small\n (r = root) == null || r.right == null || (rl = r.left) == null || rl.left == null)\n return true;\n lockRoot();\n try {\n TreeNode replacement;\n TreeNode pl = p.left;\n TreeNode pr = p.right;\n if (pl != null && pr != null) {\n TreeNode s = pr, sl;\n while (// find successor\n (sl = s.left) != null) s = sl;\n // swap colors\n boolean c = s.red;\n // swap colors\n s.red = p.red;\n // swap colors\n p.red = c;\n TreeNode sr = s.right;\n TreeNode pp = p.parent;\n if (s == pr) {\n // p was s's direct parent\n p.parent = s;\n s.right = p;\n } else {\n TreeNode sp = s.parent;\n if ((p.parent = sp) != null) {\n if (s == sp.left)\n sp.left = p;\n else\n sp.right = p;\n }\n if ((s.right = pr) != null)\n pr.parent = s;\n }\n p.left = null;\n if ((p.right = sr) != null)\n sr.parent = p;\n if ((s.left = pl) != null)\n pl.parent = s;\n if ((s.parent = pp) == null)\n r = s;\n else if (p == pp.left)\n pp.left = s;\n else\n pp.right = s;\n if (sr != null)\n replacement = sr;\n else\n replacement = p;\n } else if (pl != null)\n replacement = pl;\n else if (pr != null)\n replacement = pr;\n else\n replacement = p;\n if (replacement != p) {\n TreeNode pp = replacement.parent = p.parent;\n if (pp == null)\n r = replacement;\n else if (p == pp.left)\n pp.left = replacement;\n else\n pp.right = replacement;\n p.left = p.right = p.parent = null;\n }\n root = (p.red) ? r : balanceDeletion(r, replacement);\n if (p == replacement) {\n // detach pointers\n TreeNode pp;\n if ((pp = p.parent) != null) {\n if (p == pp.left)\n pp.left = null;\n else if (p == pp.right)\n pp.right = null;\n p.parent = null;\n }\n }\n } finally {\n unlockRoot();\n }\n assert checkInvariants(root);\n return false;\n }\n\n // Red-black tree methods, all adapted from CLR\n static TreeNode rotateLeft(TreeNode root, TreeNode p) {\n TreeNode r, pp, rl;\n if (p != null && (r = p.right) != null) {\n if ((rl = p.right = r.left) != null)\n rl.parent = p;\n if ((pp = r.parent = p.parent) == null)\n (root = r).red = false;\n else if (pp.left == p)\n pp.left = r;\n else\n pp.right = r;\n r.left = p;\n p.parent = r;\n }\n return root;\n }\n\n static TreeNode rotateRight(TreeNode root, TreeNode p) {\n TreeNode l, pp, lr;\n if (p != null && (l = p.left) != null) {\n if ((lr = p.left = l.right) != null)\n lr.parent = p;\n if ((pp = l.parent = p.parent) == null)\n (root = l).red = false;\n else if (pp.right == p)\n pp.right = l;\n else\n pp.left = l;\n l.right = p;\n p.parent = l;\n }\n return root;\n }\n\n static TreeNode balanceInsertion(TreeNode root, TreeNode x) {\n x.red = true;\n for (TreeNode xp, xpp, xppl, xppr; ; ) {\n if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (!xp.red || (xpp = xp.parent) == null)\n return root;\n if (xp == (xppl = xpp.left)) {\n if ((xppr = xpp.right) != null && xppr.red) {\n xppr.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.right) {\n root = rotateLeft(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateRight(root, xpp);\n }\n }\n }\n } else {\n if (xppl != null && xppl.red) {\n xppl.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.left) {\n root = rotateRight(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateLeft(root, xpp);\n }\n }\n }\n }\n }\n }\n\n static TreeNode balanceDeletion(TreeNode root, TreeNode x) {\n for (TreeNode xp, xpl, xpr; ; ) {\n if (x == null || x == root)\n return root;\n else if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (x.red) {\n x.red = false;\n return root;\n } else if ((xpl = xp.left) == x) {\n if ((xpr = xp.right) != null && xpr.red) {\n xpr.red = false;\n xp.red = true;\n root = rotateLeft(root, xp);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr == null)\n x = xp;\n else {\n TreeNode sl = xpr.left, sr = xpr.right;\n if ((sr == null || !sr.red) && (sl == null || !sl.red)) {\n xpr.red = true;\n x = xp;\n } else {\n if (sr == null || !sr.red) {\n if (sl != null)\n sl.red = false;\n xpr.red = true;\n root = rotateRight(root, xpr);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr != null) {\n xpr.red = (xp == null) ? false : xp.red;\n if ((sr = xpr.right) != null)\n sr.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateLeft(root, xp);\n }\n x = root;\n }\n }\n } else {\n // symmetric\n if (xpl != null && xpl.red) {\n xpl.red = false;\n xp.red = true;\n root = rotateRight(root, xp);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl == null)\n x = xp;\n else {\n TreeNode sl = xpl.left, sr = xpl.right;\n if ((sl == null || !sl.red) && (sr == null || !sr.red)) {\n xpl.red = true;\n x = xp;\n } else {\n if (sl == null || !sl.red) {\n if (sr != null)\n sr.red = false;\n xpl.red = true;\n root = rotateLeft(root, xpl);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl != null) {\n xpl.red = (xp == null) ? false : xp.red;\n if ((sl = xpl.left) != null)\n sl.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateRight(root, xp);\n }\n x = root;\n }\n }\n }\n }\n }\n\n /**\n * Checks invariants recursively for the tree of Nodes rooted at t.\n */\n static boolean checkInvariants(TreeNode t) {\n TreeNode tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode) t.next;\n if (tb != null && tb.next != t)\n return false;\n if (tn != null && tn.prev != t)\n return false;\n if (tp != null && t != tp.left && t != tp.right)\n return false;\n if (tl != null && (tl.parent != t || tl.hash > t.hash))\n return false;\n if (tr != null && (tr.parent != t || tr.hash < t.hash))\n return false;\n if (t.red && tl != null && tl.red && tr != null && tr.red)\n return false;\n if (tl != null && !checkInvariants(tl))\n return false;\n if (tr != null && !checkInvariants(tr))\n return false;\n return true;\n }\n\n private static final long LOCKSTATE = U.objectFieldOffset(TreeBin.class, \"lockState\");\n }\n\n /**\n * Records the table, its length, and current traversal index for a\n * traverser that must process a region of a forwarded table before\n * proceeding with current table.\n */\n static final class TableStack {\n\n int length;\n\n int index;\n\n Node[] tab;\n\n TableStack next;\n }\n\n /**\n * Encapsulates traversal for methods such as containsValue; also\n * serves as a base class for other iterators and spliterators.\n *\n * Method advance visits once each still-valid node that was\n * reachable upon iterator construction. It might miss some that\n * were added to a bin after the bin was visited, which is OK wrt\n * consistency guarantees. Maintaining this property in the face\n * of possible ongoing resizes requires a fair amount of\n * bookkeeping state that is difficult to optimize away amidst\n * volatile accesses. Even so, traversal maintains reasonable\n * throughput.\n *\n * Normally, iteration proceeds bin-by-bin traversing lists.\n * However, if the table has been resized, then all future steps\n * must traverse both the bin at the current index as well as at\n * (index + baseSize); and so on for further resizings. To\n * paranoically cope with potential sharing by users of iterators\n * across threads, iteration terminates if a bounds checks fails\n * for a table read.\n */\n static class Traverser {\n\n // current table; updated if resized\n Node[] tab;\n\n // the next entry to use\n Node next;\n\n // to save/restore on ForwardingNodes\n TableStack stack, spare;\n\n // index of bin to use next\n int index;\n\n // current index of initial table\n int baseIndex;\n\n // index bound for initial table\n int baseLimit;\n\n // initial table size\n final int baseSize;\n\n Traverser(Node[] tab, int size, int index, int limit) {\n this.tab = tab;\n this.baseSize = size;\n this.baseIndex = this.index = index;\n this.baseLimit = limit;\n this.next = null;\n }\n\n /**\n * Advances if possible, returning next valid node, or null if none.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n // must use locals in checks\n Node[] t;\n // must use locals in checks\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n // visit upper slots if present\n index = ++baseIndex;\n }\n }\n\n /**\n * Saves traversal state upon encountering a forwarding node.\n */\n private void pushState(Node[] t, int i, int n) {\n // reuse if possible\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n /**\n * Possibly pops traversal state.\n *\n * @param n length of current table\n */\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /**\n * Base of key, value, and entry Iterators. Adds fields to\n * Traverser to support iterator.remove.\n */\n static class BaseIterator extends Traverser {\n\n final ConcurrentHashMap map;\n\n Node lastReturned;\n\n BaseIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n advance();\n }\n\n public final boolean hasNext() {\n return next != null;\n }\n\n public final boolean hasMoreElements() {\n return next != null;\n }\n\n public final void remove() {\n Node p;\n if ((p = lastReturned) == null)\n throw new IllegalStateException();\n lastReturned = null;\n map.replaceNode(p.key, null, null);\n }\n }\n\n static final class KeyIterator extends BaseIterator implements Iterator, Enumeration {\n\n KeyIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final K next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n lastReturned = p;\n advance();\n return k;\n }\n\n public final K nextElement() {\n return next();\n }\n }\n\n static final class ValueIterator extends BaseIterator implements Iterator, Enumeration {\n\n ValueIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final V next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n V v = p.val;\n lastReturned = p;\n advance();\n return v;\n }\n\n public final V nextElement() {\n return next();\n }\n }\n\n static final class EntryIterator extends BaseIterator implements Iterator> {\n\n EntryIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final Map.Entry next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n V v = p.val;\n lastReturned = p;\n advance();\n return new MapEntry(k, v, map);\n }\n }\n\n static final class MapEntry implements Map.Entry {\n\n final K key;\n\n V val;\n\n final ConcurrentHashMap map;\n\n MapEntry(K key, V val, ConcurrentHashMap map) {\n this.key = key;\n this.val = val;\n this.map = map;\n }\n\n public K getKey() {\n return key;\n }\n\n public V getValue() {\n return val;\n }\n\n public int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public boolean equals(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == val || v.equals(val)));\n }\n\n /**\n * Sets our entry's value and writes through to the map. The\n * value to return is somewhat arbitrary here. Since we do not\n * necessarily track asynchronous changes, the most recent\n * \"previous\" value could be different from what we return (or\n * could even have been removed, in which case the put will\n * re-establish). We do not and cannot guarantee more.\n */\n public V setValue(V value) {\n if (value == null)\n throw new NullPointerException();\n V v = val;\n val = value;\n map.put(key, value);\n return v;\n }\n }\n\n static final class KeySpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n KeySpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public KeySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new KeySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.key);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class ValueSpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n ValueSpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public ValueSpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new ValueSpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.val);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class EntrySpliterator extends Traverser implements Spliterator> {\n\n // To export MapEntry\n final ConcurrentHashMap map;\n\n // size estimate\n long est;\n\n EntrySpliterator(Node[] tab, int size, int index, int limit, long est, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n this.est = est;\n }\n\n public EntrySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new EntrySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1, map);\n }\n\n public void forEachRemaining(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n\n public boolean tryAdvance(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(new MapEntry(p.key, p.val, map));\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n // Parallel bulk operations\n /**\n * Computes initial batch value for bulk tasks. The returned value\n * is approximately exp2 of the number of times (minus one) to\n * split task by two before executing leaf action. This value is\n * faster to compute and more convenient to use as a guide to\n * splitting than is the depth, since it is used while dividing by\n * two anyway.\n */\n final int batchFor(long b) {\n long n;\n if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)\n return 0;\n // slack of 4\n int sp = ForkJoinPool.getCommonPoolParallelism() << 2;\n return (b <= 0L || (n /= b) >= sp) ? sp : (int) n;\n }\n\n /**\n * Performs the given action for each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiFunction transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each (key, value), or null if none. Upon\n * success, further element processing is suppressed and the\n * results of any other parallel invocations of the search\n * function are ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each (key, value), or null if none\n * @since 1.8\n */\n public U search(long parallelismThreshold, BiFunction searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public U reduce(long parallelismThreshold, BiFunction transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public double reduceToDouble(long parallelismThreshold, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public long reduceToLong(long parallelismThreshold, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public int reduceToInt(long parallelismThreshold, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each key, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each key, or null if none\n * @since 1.8\n */\n public U searchKeys(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all keys using the given\n * reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all keys using the given\n * reducer to combine values, or null if none\n * @since 1.8\n */\n public K reduceKeys(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public U reduceKeys(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public double reduceKeysToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public long reduceKeysToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public int reduceKeysToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachValueTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedValueTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each value, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each value, or null if none\n * @since 1.8\n */\n public U searchValues(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all values using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all values\n * @since 1.8\n */\n public V reduceValues(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public U reduceValues(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public double reduceValuesToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public long reduceValuesToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public int reduceValuesToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Function, ? extends U> transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each entry, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each entry, or null if none\n * @since 1.8\n */\n public U searchEntries(long parallelismThreshold, Function, ? extends U> searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all entries using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all entries\n * @since 1.8\n */\n public Map.Entry reduceEntries(long parallelismThreshold, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public U reduceEntries(long parallelismThreshold, Function, ? extends U> transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public double reduceEntriesToDouble(long parallelismThreshold, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public long reduceEntriesToLong(long parallelismThreshold, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public int reduceEntriesToInt(long parallelismThreshold, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n abstract static class CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n final ConcurrentHashMap map;\n\n CollectionView(ConcurrentHashMap map) {\n this.map = map;\n }\n\n /**\n * Returns the map backing this view.\n *\n * @return the map backing this view\n */\n public ConcurrentHashMap getMap() {\n return map;\n }\n\n /**\n * Removes all of the elements from this view, by removing all\n * the mappings from the map backing this view.\n */\n public final void clear() {\n map.clear();\n }\n\n public final int size() {\n return map.size();\n }\n\n public final boolean isEmpty() {\n return map.isEmpty();\n }\n\n // implementations below rely on concrete classes supplying these\n /**\n * Returns an iterator over the elements in this collection.\n *\n *

The returned iterator is\n * weakly consistent.\n *\n * @return an iterator over the elements in this collection\n */\n public abstract Iterator iterator();\n\n public abstract boolean contains(Object o);\n\n public abstract boolean remove(Object o);\n\n private static final String OOME_MSG = \"Required array size too large\";\n\n public final Object[] toArray() {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int n = (int) sz;\n Object[] r = new Object[n];\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = e;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n @SuppressWarnings(\"unchecked\")\n public final T[] toArray(T[] a) {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int m = (int) sz;\n T[] r = (a.length >= m) ? a : (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), m);\n int n = r.length;\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = (T) e;\n }\n if (a == r && i < n) {\n r[i] = null;\n return r;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n /**\n * Returns a string representation of this collection.\n * The string representation consists of the string representations\n * of the collection's elements in the order they are returned by\n * its iterator, enclosed in square brackets ({@code \"[]\"}).\n * Adjacent elements are separated by the characters {@code \", \"}\n * (comma and space). Elements are converted to strings as by\n * {@link String#valueOf(Object)}.\n *\n * @return a string representation of this collection\n */\n public final String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append('[');\n Iterator it = iterator();\n if (it.hasNext()) {\n for (; ; ) {\n Object e = it.next();\n sb.append(e == this ? \"(this Collection)\" : e);\n if (!it.hasNext())\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append(']').toString();\n }\n\n public final boolean containsAll(Collection c) {\n if (c != this) {\n for (Object e : c) {\n if (e == null || !contains(e))\n return false;\n }\n }\n return true;\n }\n\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n // Use (c instanceof Set) as a hint that lookup in c is as\n // efficient as this view\n Node[] t;\n if ((t = map.table) == null) {\n return false;\n } else if (c instanceof Set && c.size() > t.length) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n } else {\n for (Object e : c) modified |= remove(e);\n }\n return modified;\n }\n\n public final boolean retainAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (!c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of keys, in\n * which additions may optionally be enabled by mapping to a\n * common value. This class cannot be directly instantiated.\n * See {@link #keySet() keySet()},\n * {@link #keySet(Object) keySet(V)},\n * {@link #newKeySet() newKeySet()},\n * {@link #newKeySet(int) newKeySet(int)}.\n *\n * @since 1.8\n */\n public static class KeySetView extends CollectionView implements Set, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n // Conditionally serializable\n @SuppressWarnings(\"serial\")\n private final V value;\n\n KeySetView(ConcurrentHashMap map, V value) {\n super(map);\n this.value = value;\n }\n\n /**\n * Returns the default mapped value for additions,\n * or {@code null} if additions are not supported.\n *\n * @return the default mapped value for additions, or {@code null}\n * if not supported\n */\n public V getMappedValue() {\n return value;\n }\n\n /**\n * {@inheritDoc}\n * @throws NullPointerException if the specified key is null\n */\n public boolean contains(Object o) {\n return map.containsKey(o);\n }\n\n /**\n * Removes the key from this map view, by removing the key (and its\n * corresponding value) from the backing map. This method does\n * nothing if the key is not in the map.\n *\n * @param o the key to be removed from the backing map\n * @return {@code true} if the backing map contained the specified key\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object o) {\n return map.remove(o) != null;\n }\n\n /**\n * @return an iterator over the keys of the backing map\n */\n public Iterator iterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, m);\n }\n\n /**\n * Adds the specified key to this set view by mapping the key to\n * the default mapped value in the backing map, if defined.\n *\n * @param e key to be added\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the specified key is null\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean add(K e) {\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n return map.putVal(e, v, true) == null;\n }\n\n /**\n * Adds all of the elements in the specified collection to this set,\n * as if by calling {@link #add} on each one.\n *\n * @param c the elements to be inserted into this set\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the collection or any of its\n * elements are {@code null}\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean addAll(Collection c) {\n boolean added = false;\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n for (K e : c) {\n if (map.putVal(e, v, true) == null)\n added = true;\n }\n return added;\n }\n\n public int hashCode() {\n int h = 0;\n for (K e : this) h += e.hashCode();\n return h;\n }\n\n public boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeySpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.key);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Collection} of\n * values, in which additions are disabled. This class cannot be\n * directly instantiated. See {@link #values()}.\n */\n static final class ValuesView extends CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n ValuesView(ConcurrentHashMap map) {\n super(map);\n }\n\n public final boolean contains(Object o) {\n return map.containsValue(o);\n }\n\n public final boolean remove(Object o) {\n if (o != null) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (o.equals(it.next())) {\n it.remove();\n return true;\n }\n }\n }\n return false;\n }\n\n public final Iterator iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, m);\n }\n\n public final boolean add(V e) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean addAll(Collection c) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n\n public boolean removeIf(Predicate filter) {\n return map.removeValueIf(filter);\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueSpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.val);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of (key, value)\n * entries. This class cannot be directly instantiated. See\n * {@link #entrySet()}.\n */\n static final class EntrySetView extends CollectionView> implements Set>, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n EntrySetView(ConcurrentHashMap map) {\n super(map);\n }\n\n public boolean contains(Object o) {\n Object k, v, r;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (r = map.get(k)) != null && (v = e.getValue()) != null && (v == r || v.equals(r)));\n }\n\n public boolean remove(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && map.remove(k, v));\n }\n\n /**\n * @return an iterator over the entries of the backing map\n */\n public Iterator> iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntryIterator(t, f, 0, f, m);\n }\n\n public boolean add(Entry e) {\n return map.putVal(e.getKey(), e.getValue(), false) == null;\n }\n\n public boolean addAll(Collection> c) {\n boolean added = false;\n for (Entry e : c) {\n if (add(e))\n added = true;\n }\n return added;\n }\n\n public boolean removeIf(Predicate> filter) {\n return map.removeEntryIf(filter);\n }\n\n public final int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n h += p.hashCode();\n }\n }\n return h;\n }\n\n public final boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator> spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntrySpliterator(t, f, 0, f, n < 0L ? 0L : n, m);\n }\n\n public void forEach(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n }\n }\n\n /**\n * Base class for bulk tasks. Repeats some fields and code from\n * class Traverser, because we need to subclass CountedCompleter.\n */\n @SuppressWarnings(\"serial\")\n abstract static class BulkTask extends CountedCompleter {\n\n // same as Traverser\n Node[] tab;\n\n Node next;\n\n TableStack stack, spare;\n\n int index;\n\n int baseIndex;\n\n int baseLimit;\n\n final int baseSize;\n\n // split control\n int batch;\n\n BulkTask(BulkTask par, int b, int i, int f, Node[] t) {\n super(par);\n this.batch = b;\n this.index = this.baseIndex = i;\n if ((this.tab = t) == null)\n this.baseSize = this.baseLimit = 0;\n else if (par == null)\n this.baseSize = this.baseLimit = t.length;\n else {\n this.baseLimit = f;\n this.baseSize = par.baseSize;\n }\n }\n\n /**\n * Same as Traverser version.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n Node[] t;\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n private void pushState(Node[] t, int i, int n) {\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /*\n * Task classes. Coded in a regular but ugly format/style to\n * simplify checks that each variant differs in the right way from\n * others. The null screenings exist because compilers cannot tell\n * that we've already null-checked task arguments, so we force\n * simplest hoisted bypass to help avoid convoluted traps.\n */\n @SuppressWarnings(\"serial\")\n static final class ForEachKeyTask extends BulkTask {\n\n final Consumer action;\n\n ForEachKeyTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachValueTask extends BulkTask {\n\n final Consumer action;\n\n ForEachValueTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachValueTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachEntryTask extends BulkTask {\n\n final Consumer> action;\n\n ForEachEntryTask(BulkTask p, int b, int i, int f, Node[] t, Consumer> action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer> action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachMappingTask extends BulkTask {\n\n final BiConsumer action;\n\n ForEachMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiConsumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final BiConsumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key, p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedKeyTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedKeyTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedValueTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedValueTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedValueTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedEntryTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final Consumer action;\n\n ForEachTransformedEntryTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedMappingTask extends BulkTask {\n\n final BiFunction transformer;\n\n final Consumer action;\n\n ForEachTransformedMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchKeysTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchKeysTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchValuesTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchValuesTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchEntriesTask extends BulkTask {\n\n final Function, ? extends U> searchFunction;\n\n final AtomicReference result;\n\n SearchEntriesTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function, ? extends U> searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n return;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchMappingsTask extends BulkTask {\n\n final BiFunction searchFunction;\n\n final AtomicReference result;\n\n SearchMappingsTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final BiFunction searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key, p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceKeysTask extends BulkTask {\n\n final BiFunction reducer;\n\n K result;\n\n ReduceKeysTask rights, nextRight;\n\n ReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, ReduceKeysTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final K getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n K r = null;\n for (Node p; (p = advance()) != null; ) {\n K u = p.key;\n r = (r == null) ? u : u == null ? r : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceKeysTask t = (ReduceKeysTask) c, s = t.rights;\n while (s != null) {\n K tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceValuesTask extends BulkTask {\n\n final BiFunction reducer;\n\n V result;\n\n ReduceValuesTask rights, nextRight;\n\n ReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceValuesTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final V getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n V r = null;\n for (Node p; (p = advance()) != null; ) {\n V v = p.val;\n r = (r == null) ? v : reducer.apply(r, v);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceValuesTask t = (ReduceValuesTask) c, s = t.rights;\n while (s != null) {\n V tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceEntriesTask extends BulkTask> {\n\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n\n Map.Entry result;\n\n ReduceEntriesTask rights, nextRight;\n\n ReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceEntriesTask nextRight, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final Map.Entry getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n Map.Entry r = null;\n for (Node p; (p = advance()) != null; ) r = (r == null) ? p : reducer.apply(r, p);\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceEntriesTask t = (ReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n Map.Entry tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceKeysTask rights, nextRight;\n\n MapReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysTask t = (MapReduceKeysTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceValuesTask rights, nextRight;\n\n MapReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesTask t = (MapReduceValuesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceEntriesTask rights, nextRight;\n\n MapReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesTask nextRight, Function, ? extends U> transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesTask t = (MapReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsTask extends BulkTask {\n\n final BiFunction transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceMappingsTask rights, nextRight;\n\n MapReduceMappingsTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsTask nextRight, BiFunction transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsTask t = (MapReduceMappingsTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceKeysToDoubleTask rights, nextRight;\n\n MapReduceKeysToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToDoubleTask t = (MapReduceKeysToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceValuesToDoubleTask rights, nextRight;\n\n MapReduceValuesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToDoubleTask t = (MapReduceValuesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction> transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceEntriesToDoubleTask rights, nextRight;\n\n MapReduceEntriesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToDoubleTask nextRight, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction> transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToDoubleTask t = (MapReduceEntriesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToDoubleTask extends BulkTask {\n\n final ToDoubleBiFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceMappingsToDoubleTask rights, nextRight;\n\n MapReduceMappingsToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToDoubleTask nextRight, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleBiFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToDoubleTask t = (MapReduceMappingsToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceKeysToLongTask rights, nextRight;\n\n MapReduceKeysToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToLongTask t = (MapReduceKeysToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceValuesToLongTask rights, nextRight;\n\n MapReduceValuesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToLongTask t = (MapReduceValuesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToLongTask extends BulkTask {\n\n final ToLongFunction> transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceEntriesToLongTask rights, nextRight;\n\n MapReduceEntriesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToLongTask nextRight, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction> transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToLongTask t = (MapReduceEntriesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToLongTask extends BulkTask {\n\n final ToLongBiFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceMappingsToLongTask rights, nextRight;\n\n MapReduceMappingsToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToLongTask nextRight, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongBiFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToLongTask t = (MapReduceMappingsToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceKeysToIntTask rights, nextRight;\n\n MapReduceKeysToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToIntTask t = (MapReduceKeysToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceValuesToIntTask rights, nextRight;\n\n MapReduceValuesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToIntTask t = (MapReduceValuesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToIntTask extends BulkTask {\n\n final ToIntFunction> transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceEntriesToIntTask rights, nextRight;\n\n MapReduceEntriesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToIntTask nextRight, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction> transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToIntTask t = (MapReduceEntriesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToIntTask extends BulkTask {\n\n final ToIntBiFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceMappingsToIntTask rights, nextRight;\n\n MapReduceMappingsToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToIntTask nextRight, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntBiFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToIntTask t = (MapReduceMappingsToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n // Unsafe mechanics\n private static final Unsafe U = Unsafe.getUnsafe();\n\n private static final long SIZECTL = U.objectFieldOffset(ConcurrentHashMap.class, \"sizeCtl\");\n\n private static final long TRANSFERINDEX = U.objectFieldOffset(ConcurrentHashMap.class, \"transferIndex\");\n\n private static final long BASECOUNT = U.objectFieldOffset(ConcurrentHashMap.class, \"baseCount\");\n\n private static final long CELLSBUSY = U.objectFieldOffset(ConcurrentHashMap.class, \"cellsBusy\");\n\n private static final long CELLVALUE = U.objectFieldOffset(CounterCell.class, \"value\");\n\n private static final int ABASE = U.arrayBaseOffset(Node[].class);\n\n private static final int ASHIFT;\n\n static {\n int scale = U.arrayIndexScale(Node[].class);\n if ((scale & (scale - 1)) != 0)\n throw new ExceptionInInitializerError(\"array index scale not a power of two\");\n ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);\n // Reduce the risk of rare disastrous classloading in first call to\n Class ensureLoaded = LockSupport.class;\n // Eager class load observed to help JIT during startup\n ensureLoaded = ReservationNode.class;\n }\n}\n"} {"task_id": "Java_2824", "language": "Java", "task_type": "single_line", "source_file": "java/github/openjdk/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java", "mask_start_position": 248408, "mask_end_position": 248419, "canonical_solution": "or reducer;", "pre_mask_code": "package java.util.concurrent;\n\nimport java.io.ObjectStreamField;\nimport java.io.Serializable;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.AbstractMap;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Hashtable;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.Spliterator;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.concurrent.locks.LockSupport;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\nimport java.util.function.Consumer;\nimport java.util.function.DoubleBinaryOperator;\nimport java.util.function.Function;\nimport java.util.function.IntBinaryOperator;\nimport java.util.function.LongBinaryOperator;\nimport java.util.function.Predicate;\nimport java.util.function.ToDoubleBiFunction;\nimport java.util.function.ToDoubleFunction;\nimport java.util.function.ToIntBiFunction;\nimport java.util.function.ToIntFunction;\nimport java.util.function.ToLongBiFunction;\nimport java.util.function.ToLongFunction;\nimport java.util.stream.Stream;\nimport jdk.internal.misc.Unsafe;\n\n/**\n * A hash table supporting full concurrency of retrievals and\n * high expected concurrency for updates. This class obeys the\n * same functional specification as {@link java.util.Hashtable}, and\n * includes versions of methods corresponding to each method of\n * {@code Hashtable}. However, even though all operations are\n * thread-safe, retrieval operations do not entail locking,\n * and there is not any support for locking the entire table\n * in a way that prevents all access. This class is fully\n * interoperable with {@code Hashtable} in programs that rely on its\n * thread safety but not on its synchronization details.\n *\n *

Retrieval operations (including {@code get}) generally do not\n * block, so may overlap with update operations (including {@code put}\n * and {@code remove}). Retrievals reflect the results of the most\n * recently completed update operations holding upon their\n * onset. (More formally, an update operation for a given key bears a\n * happens-before relation with any (non-null) retrieval for\n * that key reporting the updated value.) For aggregate operations\n * such as {@code putAll} and {@code clear}, concurrent retrievals may\n * reflect insertion or removal of only some entries. Similarly,\n * Iterators, Spliterators and Enumerations return elements reflecting the\n * state of the hash table at some point at or since the creation of the\n * iterator/enumeration. They do not throw {@link\n * java.util.ConcurrentModificationException ConcurrentModificationException}.\n * However, iterators are designed to be used by only one thread at a time.\n * Bear in mind that the results of aggregate status methods including\n * {@code size}, {@code isEmpty}, and {@code containsValue} are typically\n * useful only when a map is not undergoing concurrent updates in other threads.\n * Otherwise the results of these methods reflect transient states\n * that may be adequate for monitoring or estimation purposes, but not\n * for program control.\n *\n *

The table is dynamically expanded when there are too many\n * collisions (i.e., keys that have distinct hash codes but fall into\n * the same slot modulo the table size), with the expected average\n * effect of maintaining roughly two bins per mapping (corresponding\n * to a 0.75 load factor threshold for resizing). There may be much\n * variance around this average as mappings are added and removed, but\n * overall, this maintains a commonly accepted time/space tradeoff for\n * hash tables. However, resizing this or any other kind of hash\n * table may be a relatively slow operation. When possible, it is a\n * good idea to provide a size estimate as an optional {@code\n * initialCapacity} constructor argument. An additional optional\n * {@code loadFactor} constructor argument provides a further means of\n * customizing initial table capacity by specifying the table density\n * to be used in calculating the amount of space to allocate for the\n * given number of elements. Also, for compatibility with previous\n * versions of this class, constructors may optionally specify an\n * expected {@code concurrencyLevel} as an additional hint for\n * internal sizing. Note that using many keys with exactly the same\n * {@code hashCode()} is a sure way to slow down performance of any\n * hash table. To ameliorate impact, when keys are {@link Comparable},\n * this class may use comparison order among keys to help break ties.\n *\n *

A {@link Set} projection of a ConcurrentHashMap may be created\n * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed\n * (using {@link #keySet(Object)} when only keys are of interest, and the\n * mapped values are (perhaps transiently) not used or all take the\n * same mapping value.\n *\n *

A ConcurrentHashMap can be used as a scalable frequency map (a\n * form of histogram or multiset) by using {@link\n * java.util.concurrent.atomic.LongAdder} values and initializing via\n * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count\n * to a {@code ConcurrentHashMap freqs}, you can use\n * {@code freqs.computeIfAbsent(key, k -> new LongAdder()).increment();}\n *\n *

This class and its views and iterators implement all of the\n * optional methods of the {@link Map} and {@link Iterator}\n * interfaces.\n *\n *

Like {@link Hashtable} but unlike {@link HashMap}, this class\n * does not allow {@code null} to be used as a key or value.\n *\n *

ConcurrentHashMaps support a set of sequential and parallel bulk\n * operations that, unlike most {@link Stream} methods, are designed\n * to be safely, and often sensibly, applied even with maps that are\n * being concurrently updated by other threads; for example, when\n * computing a snapshot summary of the values in a shared registry.\n * There are three kinds of operation, each with four forms, accepting\n * functions with keys, values, entries, and (key, value) pairs as\n * arguments and/or return values. Because the elements of a\n * ConcurrentHashMap are not ordered in any particular way, and may be\n * processed in different orders in different parallel executions, the\n * correctness of supplied functions should not depend on any\n * ordering, or on any other objects or values that may transiently\n * change while computation is in progress; and except for forEach\n * actions, should ideally be side-effect-free. Bulk operations on\n * {@link Map.Entry} objects do not support method {@code setValue}.\n *\n *

    \n *
  • forEach: Performs a given action on each element.\n * A variant form applies a given transformation on each element\n * before performing the action.\n *\n *
  • search: Returns the first available non-null result of\n * applying a given function on each element; skipping further\n * search when a result is found.\n *\n *
  • reduce: Accumulates each element. The supplied reduction\n * function cannot rely on ordering (more formally, it should be\n * both associative and commutative). There are five variants:\n *\n *
      \n *\n *
    • Plain reductions. (There is not a form of this method for\n * (key, value) function arguments since there is no corresponding\n * return type.)\n *\n *
    • Mapped reductions that accumulate the results of a given\n * function applied to each element.\n *\n *
    • Reductions to scalar doubles, longs, and ints, using a\n * given basis value.\n *\n *
    \n *
\n *\n *

These bulk operations accept a {@code parallelismThreshold}\n * argument. Methods proceed sequentially if the current map size is\n * estimated to be less than the given threshold. Using a value of\n * {@code Long.MAX_VALUE} suppresses all parallelism. Using a value\n * of {@code 1} results in maximal parallelism by partitioning into\n * enough subtasks to fully utilize the {@link\n * ForkJoinPool#commonPool()} that is used for all parallel\n * computations. Normally, you would initially choose one of these\n * extreme values, and then measure performance of using in-between\n * values that trade off overhead versus throughput.\n *\n *

The concurrency properties of bulk operations follow\n * from those of ConcurrentHashMap: Any non-null result returned\n * from {@code get(key)} and related access methods bears a\n * happens-before relation with the associated insertion or\n * update. The result of any bulk operation reflects the\n * composition of these per-element relations (but is not\n * necessarily atomic with respect to the map as a whole unless it\n * is somehow known to be quiescent). Conversely, because keys\n * and values in the map are never null, null serves as a reliable\n * atomic indicator of the current lack of any result. To\n * maintain this property, null serves as an implicit basis for\n * all non-scalar reduction operations. For the double, long, and\n * int versions, the basis should be one that, when combined with\n * any other value, returns that other value (more formally, it\n * should be the identity element for the reduction). Most common\n * reductions have these properties; for example, computing a sum\n * with basis 0 or a minimum with basis MAX_VALUE.\n *\n *

Search and transformation functions provided as arguments\n * should similarly return null to indicate the lack of any result\n * (in which case it is not used). In the case of mapped\n * reductions, this also enables transformations to serve as\n * filters, returning null (or, in the case of primitive\n * specializations, the identity basis) if the element should not\n * be combined. You can create compound transformations and\n * filterings by composing them yourself under this \"null means\n * there is nothing there now\" rule before using them in search or\n * reduce operations.\n *\n *

Methods accepting and/or returning Entry arguments maintain\n * key-value associations. They may be useful for example when\n * finding the key for the greatest value. Note that \"plain\" Entry\n * arguments can be supplied using {@code new\n * AbstractMap.SimpleEntry(k,v)}.\n *\n *

Bulk operations may complete abruptly, throwing an\n * exception encountered in the application of a supplied\n * function. Bear in mind when handling such exceptions that other\n * concurrently executing functions could also have thrown\n * exceptions, or would have done so if the first exception had\n * not occurred.\n *\n *

Speedups for parallel compared to sequential forms are common\n * but not guaranteed. Parallel operations involving brief functions\n * on small maps may execute more slowly than sequential forms if the\n * underlying work to parallelize the computation is more expensive\n * than the computation itself. Similarly, parallelization may not\n * lead to much actual parallelism if all processors are busy\n * performing unrelated tasks.\n *\n *

All arguments to all task methods must be non-null.\n *\n *

This class is a member of the\n * \n * Java Collections Framework.\n *\n * @since 1.5\n * @author Doug Lea\n * @param the type of keys maintained by this map\n * @param the type of mapped values\n */\npublic class ConcurrentHashMap extends AbstractMap implements ConcurrentMap, Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n /*\n * Overview:\n *\n * The primary design goal of this hash table is to maintain\n * concurrent readability (typically method get(), but also\n * iterators and related methods) while minimizing update\n * contention. Secondary goals are to keep space consumption about\n * the same or better than java.util.HashMap, and to support high\n * initial insertion rates on an empty table by many threads.\n *\n * This map usually acts as a binned (bucketed) hash table. Each\n * key-value mapping is held in a Node. Most nodes are instances\n * of the basic Node class with hash, key, value, and next\n * fields. However, various subclasses exist: TreeNodes are\n * arranged in balanced trees, not lists. TreeBins hold the roots\n * of sets of TreeNodes. ForwardingNodes are placed at the heads\n * of bins during resizing. ReservationNodes are used as\n * placeholders while establishing values in computeIfAbsent and\n * related methods. The types TreeBin, ForwardingNode, and\n * ReservationNode do not hold normal user keys, values, or\n * hashes, and are readily distinguishable during search etc\n * because they have negative hash fields and null key and value\n * fields. (These special nodes are either uncommon or transient,\n * so the impact of carrying around some unused fields is\n * insignificant.)\n *\n * The table is lazily initialized to a power-of-two size upon the\n * first insertion. Each bin in the table normally contains a\n * list of Nodes (most often, the list has only zero or one Node).\n * Table accesses require volatile/atomic reads, writes, and\n * CASes. Because there is no other way to arrange this without\n * adding further indirections, we use intrinsics\n * (jdk.internal.misc.Unsafe) operations.\n *\n * We use the top (sign) bit of Node hash fields for control\n * purposes -- it is available anyway because of addressing\n * constraints. Nodes with negative hash fields are specially\n * handled or ignored in map methods.\n *\n * Insertion (via put or its variants) of the first node in an\n * empty bin is performed by just CASing it to the bin. This is\n * by far the most common case for put operations under most\n * key/hash distributions. Other update operations (insert,\n * delete, and replace) require locks. We do not want to waste\n * the space required to associate a distinct lock object with\n * each bin, so instead use the first node of a bin list itself as\n * a lock. Locking support for these locks relies on builtin\n * \"synchronized\" monitors.\n *\n * Using the first node of a list as a lock does not by itself\n * suffice though: When a node is locked, any update must first\n * validate that it is still the first node after locking it, and\n * retry if not. Because new nodes are always appended to lists,\n * once a node is first in a bin, it remains first until deleted\n * or the bin becomes invalidated (upon resizing).\n *\n * The main disadvantage of per-bin locks is that other update\n * operations on other nodes in a bin list protected by the same\n * lock can stall, for example when user equals() or mapping\n * functions take a long time. However, statistically, under\n * random hash codes, this is not a common problem. Ideally, the\n * frequency of nodes in bins follows a Poisson distribution\n * (http://example.com) with a\n * parameter of about 0.5 on average, given the resizing threshold\n * of 0.75, although with a large variance because of resizing\n * granularity. Ignoring variance, the expected occurrences of\n * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The\n * first values are:\n *\n * 0: 0.60653066\n * 1: 0.30326533\n * 2: 0.07581633\n * 3: 0.01263606\n * 4: 0.00157952\n * 5: 0.00015795\n * 6: 0.00001316\n * 7: 0.00000094\n * 8: 0.00000006\n * more: less than 1 in ten million\n *\n * Lock contention probability for two threads accessing distinct\n * elements is roughly 1 / (8 * #elements) under random hashes.\n *\n * Actual hash code distributions encountered in practice\n * sometimes deviate significantly from uniform randomness. This\n * includes the case when N > (1<<30), so some keys MUST collide.\n * Similarly for dumb or hostile usages in which multiple keys are\n * designed to have identical hash codes or ones that differs only\n * in masked-out high bits. So we use a secondary strategy that\n * applies when the number of nodes in a bin exceeds a\n * threshold. These TreeBins use a balanced tree to hold nodes (a\n * specialized form of red-black trees), bounding search time to\n * O(log N). Each search step in a TreeBin is at least twice as\n * slow as in a regular list, but given that N cannot exceed\n * (1<<64) (before running out of addresses) this bounds search\n * steps, lock hold times, etc, to reasonable constants (roughly\n * 100 nodes inspected per operation worst case) so long as keys\n * are Comparable (which is very common -- String, Long, etc).\n * TreeBin nodes (TreeNodes) also maintain the same \"next\"\n * traversal pointers as regular nodes, so can be traversed in\n * iterators in the same way.\n *\n * The table is resized when occupancy exceeds a percentage\n * threshold (nominally, 0.75, but see below). Any thread\n * noticing an overfull bin may assist in resizing after the\n * initiating thread allocates and sets up the replacement array.\n * However, rather than stalling, these other threads may proceed\n * with insertions etc. The use of TreeBins shields us from the\n * worst case effects of overfilling while resizes are in\n * progress. Resizing proceeds by transferring bins, one by one,\n * from the table to the next table. However, threads claim small\n * blocks of indices to transfer (via field transferIndex) before\n * doing so, reducing contention. A generation stamp in field\n * sizeCtl ensures that resizings do not overlap. Because we are\n * using power-of-two expansion, the elements from each bin must\n * either stay at same index, or move with a power of two\n * offset. We eliminate unnecessary node creation by catching\n * cases where old nodes can be reused because their next fields\n * won't change. On average, only about one-sixth of them need\n * cloning when a table doubles. The nodes they replace will be\n * garbage collectible as soon as they are no longer referenced by\n * any reader thread that may be in the midst of concurrently\n * traversing table. Upon transfer, the old table bin contains\n * only a special forwarding node (with hash field \"MOVED\") that\n * contains the next table as its key. On encountering a\n * forwarding node, access and update operations restart, using\n * the new table.\n *\n * Each bin transfer requires its bin lock, which can stall\n * waiting for locks while resizing. However, because other\n * threads can join in and help resize rather than contend for\n * locks, average aggregate waits become shorter as resizing\n * progresses. The transfer operation must also ensure that all\n * accessible bins in both the old and new table are usable by any\n * traversal. This is arranged in part by proceeding from the\n * last bin (table.length - 1) up towards the first. Upon seeing\n * a forwarding node, traversals (see class Traverser) arrange to\n * move to the new table without revisiting nodes. To ensure that\n * no intervening nodes are skipped even when moved out of order,\n * a stack (see class TableStack) is created on first encounter of\n * a forwarding node during a traversal, to maintain its place if\n * later processing the current table. The need for these\n * save/restore mechanics is relatively rare, but when one\n * forwarding node is encountered, typically many more will be.\n * So Traversers use a simple caching scheme to avoid creating so\n * many new TableStack nodes. (Thanks to Peter Levart for\n * suggesting use of a stack here.)\n *\n * The traversal scheme also applies to partial traversals of\n * ranges of bins (via an alternate Traverser constructor)\n * to support partitioned aggregate operations. Also, read-only\n * operations give up if ever forwarded to a null table, which\n * provides support for shutdown-style clearing, which is also not\n * currently implemented.\n *\n * Lazy table initialization minimizes footprint until first use,\n * and also avoids resizings when the first operation is from a\n * putAll, constructor with map argument, or deserialization.\n * These cases attempt to override the initial capacity settings,\n * but harmlessly fail to take effect in cases of races.\n *\n * The element count is maintained using a specialization of\n * LongAdder. We need to incorporate a specialization rather than\n * just use a LongAdder in order to access implicit\n * contention-sensing that leads to creation of multiple\n * CounterCells. The counter mechanics avoid contention on\n * updates but can encounter cache thrashing if read too\n * frequently during concurrent access. To avoid reading so often,\n * resizing under contention is attempted only upon adding to a\n * bin already holding two or more nodes. Under uniform hash\n * distributions, the probability of this occurring at threshold\n * is around 13%, meaning that only about 1 in 8 puts check\n * threshold (and after resizing, many fewer do so).\n *\n * TreeBins use a special form of comparison for search and\n * related operations (which is the main reason we cannot use\n * existing collections such as TreeMaps). TreeBins contain\n * Comparable elements, but may contain others, as well as\n * elements that are Comparable but not necessarily Comparable for\n * the same T, so we cannot invoke compareTo among them. To handle\n * this, the tree is ordered primarily by hash value, then by\n * Comparable.compareTo order if applicable. On lookup at a node,\n * if elements are not comparable or compare as 0 then both left\n * and right children may need to be searched in the case of tied\n * hash values. (This corresponds to the full list search that\n * would be necessary if all elements were non-Comparable and had\n * tied hashes.) On insertion, to keep a total ordering (or as\n * close as is required here) across rebalancings, we compare\n * classes and identityHashCodes as tie-breakers. The red-black\n * balancing code is updated from pre-jdk-collections\n * (http://example.com)\n * based in turn on Cormen, Leiserson, and Rivest \"Introduction to\n * Algorithms\" (CLR).\n *\n * TreeBins also require an additional locking mechanism. While\n * list traversal is always possible by readers even during\n * updates, tree traversal is not, mainly because of tree-rotations\n * that may change the root node and/or its linkages. TreeBins\n * include a simple read-write lock mechanism parasitic on the\n * main bin-synchronization strategy: Structural adjustments\n * associated with an insertion or removal are already bin-locked\n * (and so cannot conflict with other writers) but must wait for\n * ongoing readers to finish. Since there can be only one such\n * waiter, we use a simple scheme using a single \"waiter\" field to\n * block writers. However, readers need never block. If the root\n * lock is held, they proceed along the slow traversal path (via\n * next-pointers) until the lock becomes available or the list is\n * exhausted, whichever comes first. These cases are not fast, but\n * maximize aggregate expected throughput.\n *\n * Maintaining API and serialization compatibility with previous\n * versions of this class introduces several oddities. Mainly: We\n * leave untouched but unused constructor arguments referring to\n * concurrencyLevel. We accept a loadFactor constructor argument,\n * but apply it only to initial table capacity (which is the only\n * time that we can guarantee to honor it.) We also declare an\n * unused \"Segment\" class that is instantiated in minimal form\n * only when serializing.\n *\n * Also, solely for compatibility with previous versions of this\n * class, it extends AbstractMap, even though all of its methods\n * are overridden, so it is just useless baggage.\n *\n * This file is organized to make things a little easier to follow\n * while reading than they might otherwise: First the main static\n * declarations and utilities, then fields, then main public\n * methods (with a few factorings of multiple public methods into\n * internal ones), then sizing methods, trees, traversers, and\n * bulk operations.\n */\n /**\n * The largest possible table capacity. This value must be\n * exactly 1<<30 to stay within Java array allocation and indexing\n * bounds for power of two table sizes, and is further required\n * because the top two bits of 32bit hash fields are used for\n * control purposes.\n */\n private static final int MAXIMUM_CAPACITY = 1 << 30;\n\n /**\n * The default initial table capacity. Must be a power of 2\n * (i.e., at least 1) and at most MAXIMUM_CAPACITY.\n */\n private static final int DEFAULT_CAPACITY = 16;\n\n /**\n * The largest possible (non-power of two) array size.\n * Needed by toArray and related methods.\n */\n static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;\n\n /**\n * The default concurrency level for this table. Unused but\n * defined for compatibility with previous versions of this class.\n */\n private static final int DEFAULT_CONCURRENCY_LEVEL = 16;\n\n /**\n * The load factor for this table. Overrides of this value in\n * constructors affect only the initial table capacity. The\n * actual floating point value isn't normally used -- it is\n * simpler to use expressions such as {@code n - (n >>> 2)} for\n * the associated resizing threshold.\n */\n private static final float LOAD_FACTOR = 0.75f;\n\n /**\n * The bin count threshold for using a tree rather than list for a\n * bin. Bins are converted to trees when adding an element to a\n * bin with at least this many nodes. The value must be greater\n * than 2, and should be at least 8 to mesh with assumptions in\n * tree removal about conversion back to plain bins upon\n * shrinkage.\n */\n static final int TREEIFY_THRESHOLD = 8;\n\n /**\n * The bin count threshold for untreeifying a (split) bin during a\n * resize operation. Should be less than TREEIFY_THRESHOLD, and at\n * most 6 to mesh with shrinkage detection under removal.\n */\n static final int UNTREEIFY_THRESHOLD = 6;\n\n /**\n * The smallest table capacity for which bins may be treeified.\n * (Otherwise the table is resized if too many nodes in a bin.)\n * The value should be at least 4 * TREEIFY_THRESHOLD to avoid\n * conflicts between resizing and treeification thresholds.\n */\n static final int MIN_TREEIFY_CAPACITY = 64;\n\n /**\n * Minimum number of rebinnings per transfer step. Ranges are\n * subdivided to allow multiple resizer threads. This value\n * serves as a lower bound to avoid resizers encountering\n * excessive memory contention. The value should be at least\n * DEFAULT_CAPACITY.\n */\n private static final int MIN_TRANSFER_STRIDE = 16;\n\n /**\n * The number of bits used for generation stamp in sizeCtl.\n * Must be at least 6 for 32bit arrays.\n */\n private static final int RESIZE_STAMP_BITS = 16;\n\n /**\n * The maximum number of threads that can help resize.\n * Must fit in 32 - RESIZE_STAMP_BITS bits.\n */\n private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;\n\n /**\n * The bit shift for recording size stamp in sizeCtl.\n */\n private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;\n\n /*\n * Encodings for Node hash fields. See above for explanation.\n */\n // hash for forwarding nodes\n static final int MOVED = -1;\n\n // hash for roots of trees\n static final int TREEBIN = -2;\n\n static final int RESERVED = -3;\n\n // usable bits of normal node hash\n static final int HASH_BITS = 0x7fffffff;\n\n /**\n * Number of CPUS, to place bounds on some sizings\n */\n static final int NCPU = Runtime.getRuntime().availableProcessors();\n\n /**\n * Serialized pseudo-fields, provided only for jdk7 compatibility.\n * @serialField segments Segment[]\n * The segments, each of which is a specialized hash table.\n * @serialField segmentMask int\n * Mask value for indexing into segments. The upper bits of a\n * key's hash code are used to choose the segment.\n * @serialField segmentShift int\n * Shift value for indexing within segments.\n */\n private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(\"segments\", Segment[].class), new ObjectStreamField(\"segmentMask\", Integer.TYPE), new ObjectStreamField(\"segmentShift\", Integer.TYPE) };\n\n /**\n * Key-value entry. This class is never exported out as a\n * user-mutable Map.Entry (i.e., one supporting setValue; see\n * MapEntry below), but can be used for read-only traversals used\n * in bulk tasks. Subclasses of Node with a negative hash field\n * are special, and contain null keys and values (but are never\n * exported). Otherwise, keys and vals are never null.\n */\n static class Node implements Map.Entry {\n\n final int hash;\n\n final K key;\n\n volatile V val;\n\n volatile Node next;\n\n Node(int hash, K key, V val) {\n this.hash = hash;\n this.key = key;\n this.val = val;\n }\n\n Node(int hash, K key, V val, Node next) {\n this(hash, key, val);\n this.next = next;\n }\n\n public final K getKey() {\n return key;\n }\n\n public final V getValue() {\n return val;\n }\n\n public final int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public final String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public final V setValue(V value) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean equals(Object o) {\n Object k, v, u;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == (u = val) || v.equals(u)));\n }\n\n /**\n * Virtualized support for map.get(); overridden in subclasses.\n */\n Node find(int h, Object k) {\n Node e = this;\n if (k != null) {\n do {\n K ek;\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n } while ((e = e.next) != null);\n }\n return null;\n }\n }\n\n /**\n * Spreads (XORs) higher bits of hash to lower and also forces top\n * bit to 0. Because the table uses power-of-two masking, sets of\n * hashes that vary only in bits above the current mask will\n * always collide. (Among known examples are sets of Float keys\n * holding consecutive whole numbers in small tables.) So we\n * apply a transform that spreads the impact of higher bits\n * downward. There is a tradeoff between speed, utility, and\n * quality of bit-spreading. Because many common sets of hashes\n * are already reasonably distributed (so don't benefit from\n * spreading), and because we use trees to handle large sets of\n * collisions in bins, we just XOR some shifted bits in the\n * cheapest possible way to reduce systematic lossage, as well as\n * to incorporate impact of the highest bits that would otherwise\n * never be used in index calculations because of table bounds.\n */\n static final int spread(int h) {\n return (h ^ (h >>> 16)) & HASH_BITS;\n }\n\n /**\n * Returns a power of two table size for the given desired capacity.\n * See Hackers Delight, sec 3.2\n */\n private static final int tableSizeFor(int c) {\n int n = -1 >>> Integer.numberOfLeadingZeros(c - 1);\n return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;\n }\n\n /**\n * Returns x's Class if it is of the form \"class C implements\n * Comparable\", else null.\n */\n static Class comparableClassFor(Object x) {\n if (x instanceof Comparable) {\n Class c;\n Type[] ts, as;\n ParameterizedType p;\n if (// bypass checks\n (c = x.getClass()) == String.class)\n return c;\n if ((ts = c.getGenericInterfaces()) != null) {\n for (Type t : ts) {\n if ((t instanceof ParameterizedType) && ((p = (ParameterizedType) t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && // type arg is c\n as[0] == c)\n return c;\n }\n }\n }\n return null;\n }\n\n /**\n * Returns k.compareTo(x) if x matches kc (k's screened comparable\n * class), else 0.\n */\n // for cast to Comparable\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n static int compareComparables(Class kc, Object k, Object x) {\n return (x == null || x.getClass() != kc ? 0 : ((Comparable) k).compareTo(x));\n }\n\n /* ---------------- Table element access -------------- */\n /*\n * Atomic access methods are used for table elements as well as\n * elements of in-progress next table while resizing. All uses of\n * the tab arguments must be null checked by callers. All callers\n * also paranoically precheck that tab's length is not zero (or an\n * equivalent check), thus ensuring that any index argument taking\n * the form of a hash value anded with (length - 1) is a valid\n * index. Note that, to be correct wrt arbitrary concurrency\n * errors by users, these checks must operate on local variables,\n * which accounts for some odd-looking inline assignments below.\n * Note that calls to setTabAt always occur within locked regions,\n * and so require only release ordering.\n */\n @SuppressWarnings(\"unchecked\")\n static final Node tabAt(Node[] tab, int i) {\n return (Node) U.getReferenceAcquire(tab, ((long) i << ASHIFT) + ABASE);\n }\n\n static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {\n return U.compareAndSetReference(tab, ((long) i << ASHIFT) + ABASE, c, v);\n }\n\n static final void setTabAt(Node[] tab, int i, Node v) {\n U.putReferenceRelease(tab, ((long) i << ASHIFT) + ABASE, v);\n }\n\n /**\n * The array of bins. Lazily initialized upon first insertion.\n * Size is always a power of two. Accessed directly by iterators.\n */\n transient volatile Node[] table;\n\n /**\n * The next table to use; non-null only while resizing.\n */\n private transient volatile Node[] nextTable;\n\n /**\n * Base counter value, used mainly when there is no contention,\n * but also as a fallback during table initialization\n * races. Updated via CAS.\n */\n private transient volatile long baseCount;\n\n /**\n * Table initialization and resizing control. When negative, the\n * table is being initialized or resized: -1 for initialization,\n * else -(1 + the number of active resizing threads). Otherwise,\n * when table is null, holds the initial table size to use upon\n * creation, or 0 for default. After initialization, holds the\n * next element count value upon which to resize the table.\n */\n private transient volatile int sizeCtl;\n\n /**\n * The next table index (plus one) to split while resizing.\n */\n private transient volatile int transferIndex;\n\n /**\n * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.\n */\n private transient volatile int cellsBusy;\n\n /**\n * Table of counter cells. When non-null, size is a power of 2.\n */\n private transient volatile CounterCell[] counterCells;\n\n // views\n private transient KeySetView keySet;\n\n private transient ValuesView values;\n\n private transient EntrySetView entrySet;\n\n /**\n * Creates a new, empty map with the default initial table size (16).\n */\n public ConcurrentHashMap() {\n }\n\n /**\n * Creates a new, empty map with an initial table size\n * accommodating the specified number of elements without the need\n * to dynamically resize.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n */\n public ConcurrentHashMap(int initialCapacity) {\n this(initialCapacity, LOAD_FACTOR, 1);\n }\n\n /**\n * Creates a new map with the same mappings as the given map.\n *\n * @param m the map\n */\n public ConcurrentHashMap(Map m) {\n this.sizeCtl = DEFAULT_CAPACITY;\n putAll(m);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}) and\n * initial table density ({@code loadFactor}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative or the load factor is nonpositive\n *\n * @since 1.6\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor) {\n this(initialCapacity, loadFactor, 1);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}), initial\n * table density ({@code loadFactor}), and number of concurrently\n * updating threads ({@code concurrencyLevel}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @param concurrencyLevel the estimated number of concurrently\n * updating threads. The implementation may use this value as\n * a sizing hint.\n * @throws IllegalArgumentException if the initial capacity is\n * negative or the load factor or concurrencyLevel are\n * nonpositive\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) {\n if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)\n throw new IllegalArgumentException();\n if (// Use at least as many bins\n initialCapacity < concurrencyLevel)\n // as estimated threads\n initialCapacity = concurrencyLevel;\n long size = (long) (1.0 + (long) initialCapacity / loadFactor);\n int cap = (size >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) size);\n this.sizeCtl = cap;\n }\n\n // Original (since JDK1.2) Map methods\n public int size() {\n long n = sumCount();\n return ((n < 0L) ? 0 : (n > (long) Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) n);\n }\n\n public boolean isEmpty() {\n // ignore transient negative values\n return sumCount() <= 0L;\n }\n\n /**\n * Returns the value to which the specified key is mapped,\n * or {@code null} if this map contains no mapping for the key.\n *\n *

More formally, if this map contains a mapping from a key\n * {@code k} to a value {@code v} such that {@code key.equals(k)},\n * then this method returns {@code v}; otherwise it returns\n * {@code null}. (There can be at most one such mapping.)\n *\n * @throws NullPointerException if the specified key is null\n */\n public V get(Object key) {\n Node[] tab;\n Node e, p;\n int n, eh;\n K ek;\n int h = spread(key.hashCode());\n if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) {\n if ((eh = e.hash) == h) {\n if ((ek = e.key) == key || (ek != null && key.equals(ek)))\n return e.val;\n } else if (eh < 0)\n return (p = e.find(h, key)) != null ? p.val : null;\n while ((e = e.next) != null) {\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek))))\n return e.val;\n }\n }\n return null;\n }\n\n /**\n * Tests if the specified object is a key in this table.\n *\n * @param key possible key\n * @return {@code true} if and only if the specified object\n * is a key in this table, as determined by the\n * {@code equals} method; {@code false} otherwise\n * @throws NullPointerException if the specified key is null\n */\n public boolean containsKey(Object key) {\n return get(key) != null;\n }\n\n /**\n * Returns {@code true} if this map maps one or more keys to the\n * specified value. Note: This method may require a full traversal\n * of the map, and is much slower than method {@code containsKey}.\n *\n * @param value value whose presence in this map is to be tested\n * @return {@code true} if this map maps one or more keys to the\n * specified value\n * @throws NullPointerException if the specified value is null\n */\n public boolean containsValue(Object value) {\n if (value == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V v;\n if ((v = p.val) == value || (v != null && value.equals(v)))\n return true;\n }\n }\n return false;\n }\n\n /**\n * Maps the specified key to the specified value in this table.\n * Neither the key nor the value can be null.\n *\n *

The value can be retrieved by calling the {@code get} method\n * with a key that is equal to the original key.\n *\n * @param key key with which the specified value is to be associated\n * @param value value to be associated with the specified key\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key or value is null\n */\n public V put(K key, V value) {\n return putVal(key, value, false);\n }\n\n /**\n * Implementation for put and putIfAbsent\n */\n final V putVal(K key, V value, boolean onlyIfAbsent) {\n if (key == null || value == null)\n throw new NullPointerException();\n int hash = spread(key.hashCode());\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {\n if (casTabAt(tab, i, null, new Node(hash, key, value)))\n // no lock when adding to empty bin\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n onlyIfAbsent && fh == hash && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n V oldVal = null;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n oldVal = e.val;\n if (!onlyIfAbsent)\n e.val = value;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n pred.next = new Node(hash, key, value);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n Node p;\n binCount = 2;\n if ((p = ((TreeBin) f).putTreeVal(hash, key, value)) != null) {\n oldVal = p.val;\n if (!onlyIfAbsent)\n p.val = value;\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (oldVal != null)\n return oldVal;\n break;\n }\n }\n }\n addCount(1L, binCount);\n return null;\n }\n\n /**\n * Copies all of the mappings from the specified map to this one.\n * These mappings replace any mappings that this map had for any of the\n * keys currently in the specified map.\n *\n * @param m mappings to be stored in this map\n */\n public void putAll(Map m) {\n tryPresize(m.size());\n for (Map.Entry e : m.entrySet()) putVal(e.getKey(), e.getValue(), false);\n }\n\n /**\n * Removes the key (and its corresponding value) from this map.\n * This method does nothing if the key is not in the map.\n *\n * @param key the key that needs to be removed\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key is null\n */\n public V remove(Object key) {\n return replaceNode(key, null, null);\n }\n\n /**\n * Implementation for the four public remove/replace methods:\n * Replaces node value with v, conditional upon match of cv if\n * non-null. If resulting value is null, delete.\n */\n final V replaceNode(Object key, V value, Object cv) {\n int hash = spread(key.hashCode());\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0 || (f = tabAt(tab, i = (n - 1) & hash)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n V oldVal = null;\n boolean validated = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n validated = true;\n for (Node e = f, pred = null; ; ) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n V ev = e.val;\n if (cv == null || cv == ev || (ev != null && cv.equals(ev))) {\n oldVal = ev;\n if (value != null)\n e.val = value;\n else if (pred != null)\n pred.next = e.next;\n else\n setTabAt(tab, i, e.next);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n validated = true;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(hash, key, null)) != null) {\n V pv = p.val;\n if (cv == null || cv == pv || (pv != null && cv.equals(pv))) {\n oldVal = pv;\n if (value != null)\n p.val = value;\n else if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (validated) {\n if (oldVal != null) {\n if (value == null)\n addCount(-1L, -1);\n return oldVal;\n }\n break;\n }\n }\n }\n return null;\n }\n\n /**\n * Removes all of the mappings from this map.\n */\n public void clear() {\n // negative number of deletions\n long delta = 0L;\n int i = 0;\n Node[] tab = table;\n while (tab != null && i < tab.length) {\n int fh;\n Node f = tabAt(tab, i);\n if (f == null)\n ++i;\n else if ((fh = f.hash) == MOVED) {\n tab = helpTransfer(tab, f);\n // restart\n i = 0;\n } else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node p = (fh >= 0 ? f : (f instanceof TreeBin) ? ((TreeBin) f).first : null);\n while (p != null) {\n --delta;\n p = p.next;\n }\n setTabAt(tab, i++, null);\n }\n }\n }\n }\n if (delta != 0L)\n addCount(delta, -1);\n }\n\n /**\n * Returns a {@link Set} view of the keys contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from this map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations. It does not support the {@code add} or\n * {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public KeySetView keySet() {\n KeySetView ks;\n if ((ks = keySet) != null)\n return ks;\n return keySet = new KeySetView(this, null);\n }\n\n /**\n * Returns a {@link Collection} view of the values contained in this map.\n * The collection is backed by the map, so changes to the map are\n * reflected in the collection, and vice-versa. The collection\n * supports element removal, which removes the corresponding\n * mapping from this map, via the {@code Iterator.remove},\n * {@code Collection.remove}, {@code removeAll},\n * {@code retainAll}, and {@code clear} operations. It does not\n * support the {@code add} or {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}\n * and {@link Spliterator#NONNULL}.\n *\n * @return the collection view\n */\n public Collection values() {\n ValuesView vs;\n if ((vs = values) != null)\n return vs;\n return values = new ValuesView(this);\n }\n\n /**\n * Returns a {@link Set} view of the mappings contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from the map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public Set> entrySet() {\n EntrySetView es;\n if ((es = entrySet) != null)\n return es;\n return entrySet = new EntrySetView(this);\n }\n\n /**\n * Returns the hash code value for this {@link Map}, i.e.,\n * the sum of, for each key-value pair in the map,\n * {@code key.hashCode() ^ value.hashCode()}.\n *\n * @return the hash code value for this map\n */\n public int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) h += p.key.hashCode() ^ p.val.hashCode();\n }\n return h;\n }\n\n /**\n * Returns a string representation of this map. The string\n * representation consists of a list of key-value mappings (in no\n * particular order) enclosed in braces (\"{@code {}}\"). Adjacent\n * mappings are separated by the characters {@code \", \"} (comma\n * and space). Each key-value mapping is rendered as the key\n * followed by an equals sign (\"{@code =}\") followed by the\n * associated value.\n *\n * @return a string representation of this map\n */\n public String toString() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n StringBuilder sb = new StringBuilder();\n sb.append('{');\n Node p;\n if ((p = it.advance()) != null) {\n for (; ; ) {\n K k = p.key;\n V v = p.val;\n sb.append(k == this ? \"(this Map)\" : k);\n sb.append('=');\n sb.append(v == this ? \"(this Map)\" : v);\n if ((p = it.advance()) == null)\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append('}').toString();\n }\n\n /**\n * Compares the specified object with this map for equality.\n * Returns {@code true} if the given object is a map with the same\n * mappings as this map. This operation may return misleading\n * results if either map is concurrently modified during execution\n * of this method.\n *\n * @param o object to be compared for equality with this map\n * @return {@code true} if the specified object is equal to this map\n */\n public boolean equals(Object o) {\n if (o != this) {\n if (!(o instanceof Map))\n return false;\n Map m = (Map) o;\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n for (Node p; (p = it.advance()) != null; ) {\n V val = p.val;\n Object v = m.get(p.key);\n if (v == null || (v != val && !v.equals(val)))\n return false;\n }\n for (Map.Entry e : m.entrySet()) {\n Object mk, mv, v;\n if ((mk = e.getKey()) == null || (mv = e.getValue()) == null || (v = get(mk)) == null || (mv != v && !mv.equals(v)))\n return false;\n }\n }\n return true;\n }\n\n /**\n * Stripped-down version of helper class used in previous version,\n * declared for the sake of serialization compatibility.\n */\n static class Segment extends ReentrantLock implements Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n final float loadFactor;\n\n Segment(float lf) {\n this.loadFactor = lf;\n }\n }\n\n /**\n * Saves this map to a stream (that is, serializes it).\n *\n * @param s the stream\n * @throws java.io.IOException if an I/O error occurs\n * @serialData\n * the serialized fields, followed by the key (Object) and value\n * (Object) for each key-value mapping, followed by a null pair.\n * The key-value mappings are emitted in no particular order.\n */\n private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {\n // For serialization compatibility\n // Emulate segment calculation from previous version of this class\n int sshift = 0;\n int ssize = 1;\n while (ssize < DEFAULT_CONCURRENCY_LEVEL) {\n ++sshift;\n ssize <<= 1;\n }\n int segmentShift = 32 - sshift;\n int segmentMask = ssize - 1;\n @SuppressWarnings(\"unchecked\")\n Segment[] segments = (Segment[]) new Segment[DEFAULT_CONCURRENCY_LEVEL];\n for (int i = 0; i < segments.length; ++i) segments[i] = new Segment(LOAD_FACTOR);\n java.io.ObjectOutputStream.PutField streamFields = s.putFields();\n streamFields.put(\"segments\", segments);\n streamFields.put(\"segmentShift\", segmentShift);\n streamFields.put(\"segmentMask\", segmentMask);\n s.writeFields();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n s.writeObject(p.key);\n s.writeObject(p.val);\n }\n }\n s.writeObject(null);\n s.writeObject(null);\n }\n\n /**\n * Reconstitutes this map from a stream (that is, deserializes it).\n * @param s the stream\n * @throws ClassNotFoundException if the class of a serialized object\n * could not be found\n * @throws java.io.IOException if an I/O error occurs\n */\n private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {\n /*\n * To improve performance in typical cases, we create nodes\n * while reading, then place in table once size is known.\n * However, we must also validate uniqueness and deal with\n * overpopulated bins while doing so, which requires\n * specialized versions of putVal mechanics.\n */\n // force exclusion for table construction\n sizeCtl = -1;\n s.defaultReadObject();\n long size = 0L;\n Node p = null;\n for (; ; ) {\n @SuppressWarnings(\"unchecked\")\n K k = (K) s.readObject();\n @SuppressWarnings(\"unchecked\")\n V v = (V) s.readObject();\n if (k != null && v != null) {\n p = new Node(spread(k.hashCode()), k, v, p);\n ++size;\n } else\n break;\n }\n if (size == 0L)\n sizeCtl = 0;\n else {\n long ts = (long) (1.0 + size / LOAD_FACTOR);\n int n = (ts >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) ts);\n @SuppressWarnings(\"unchecked\")\n Node[] tab = (Node[]) new Node[n];\n int mask = n - 1;\n long added = 0L;\n while (p != null) {\n boolean insertAtFront;\n Node next = p.next, first;\n int h = p.hash, j = h & mask;\n if ((first = tabAt(tab, j)) == null)\n insertAtFront = true;\n else {\n K k = p.key;\n if (first.hash < 0) {\n TreeBin t = (TreeBin) first;\n if (t.putTreeVal(h, k, p.val) == null)\n ++added;\n insertAtFront = false;\n } else {\n int binCount = 0;\n insertAtFront = true;\n Node q;\n K qk;\n for (q = first; q != null; q = q.next) {\n if (q.hash == h && ((qk = q.key) == k || (qk != null && k.equals(qk)))) {\n insertAtFront = false;\n break;\n }\n ++binCount;\n }\n if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {\n insertAtFront = false;\n ++added;\n p.next = first;\n TreeNode hd = null, tl = null;\n for (q = p; q != null; q = q.next) {\n TreeNode t = new TreeNode(q.hash, q.key, q.val, null, null);\n if ((t.prev = tl) == null)\n hd = t;\n else\n tl.next = t;\n tl = t;\n }\n setTabAt(tab, j, new TreeBin(hd));\n }\n }\n }\n if (insertAtFront) {\n ++added;\n p.next = first;\n setTabAt(tab, j, p);\n }\n p = next;\n }\n table = tab;\n sizeCtl = n - (n >>> 2);\n baseCount = added;\n }\n }\n\n // ConcurrentMap methods\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V putIfAbsent(K key, V value) {\n return putVal(key, value, true);\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object key, Object value) {\n if (key == null)\n throw new NullPointerException();\n return value != null && replaceNode(key, null, value) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if any of the arguments are null\n */\n public boolean replace(K key, V oldValue, V newValue) {\n if (key == null || oldValue == null || newValue == null)\n throw new NullPointerException();\n return replaceNode(key, newValue, oldValue) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V replace(K key, V value) {\n if (key == null || value == null)\n throw new NullPointerException();\n return replaceNode(key, value, null);\n }\n\n // Overrides of JDK8+ Map extension method defaults\n /**\n * Returns the value to which the specified key is mapped, or the\n * given default value if this map contains no mapping for the\n * key.\n *\n * @param key the key whose associated value is to be returned\n * @param defaultValue the value to return if this map contains\n * no mapping for the given key\n * @return the mapping for the key, if present; else the default value\n * @throws NullPointerException if the specified key is null\n */\n public V getOrDefault(Object key, V defaultValue) {\n V v;\n return (v = get(key)) == null ? defaultValue : v;\n }\n\n public void forEach(BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n action.accept(p.key, p.val);\n }\n }\n }\n\n public void replaceAll(BiFunction function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V oldValue = p.val;\n for (K key = p.key; ; ) {\n V newValue = function.apply(key, oldValue);\n if (newValue == null)\n throw new NullPointerException();\n if (replaceNode(key, newValue, oldValue) != null || (oldValue = get(key)) == null)\n break;\n }\n }\n }\n }\n\n boolean removeEntryIf(Predicate> function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n Map.Entry e = new AbstractMap.SimpleImmutableEntry<>(k, v);\n if (function.test(e) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n boolean removeValueIf(Predicate function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n if (function.test(v) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n /**\n * If the specified key is not already associated with a value,\n * attempts to compute its value using the given mapping function\n * and enters it into this map unless {@code null}. The entire\n * method invocation is performed atomically. The supplied\n * function is invoked exactly once per invocation of this method\n * if the key is absent, else not at all. Some attempted update\n * operations on this map by other threads may be blocked while\n * computation is in progress, so the computation should be short\n * and simple.\n *\n *

The mapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param mappingFunction the function to compute a value\n * @return the current (existing or computed) value associated with\n * the specified key, or null if the computed value is null\n * @throws NullPointerException if the specified key or mappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the mappingFunction does so,\n * in which case the mapping is left unestablished\n */\n public V computeIfAbsent(K key, Function mappingFunction) {\n if (key == null || mappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = mappingFunction.apply(key)) != null)\n node = new Node(h, key, val);\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n fh == h && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n boolean added = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = e.val;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n if ((val = mappingFunction.apply(key)) != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n added = true;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null)\n val = p.val;\n else if ((val = mappingFunction.apply(key)) != null) {\n added = true;\n t.putTreeVal(h, key, val);\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (!added)\n return val;\n break;\n }\n }\n }\n if (val != null)\n addCount(1L, binCount);\n return val;\n }\n\n /**\n * If the value for the specified key is present, attempts to\n * compute a new mapping given the key and its current mapped\n * value. The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method if the key is present, else not at all. Some\n * attempted update operations on this map by other threads may be\n * blocked while computation is in progress, so the computation\n * should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which a value may be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V computeIfPresent(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null) {\n val = remappingFunction.apply(key, p.val);\n if (val != null)\n p.val = val;\n else {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0)\n break;\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * Attempts to compute a mapping for the specified key and its\n * current mapped value (or {@code null} if there is no current\n * mapping). The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method. Some attempted update operations on this map by\n * other threads may be blocked while computation is in progress,\n * so the computation should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V compute(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = remappingFunction.apply(key, null)) != null) {\n delta = 1;\n node = new Node(h, key, val);\n }\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n val = remappingFunction.apply(key, null);\n if (val != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n delta = 1;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 1;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null)\n p = r.findTreeNode(h, key, null);\n else\n p = null;\n V pv = (p == null) ? null : p.val;\n val = remappingFunction.apply(key, pv);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * If the specified key is not already associated with a\n * (non-null) value, associates it with the given value.\n * Otherwise, replaces the value with the results of the given\n * remapping function, or removes if {@code null}. The entire\n * method invocation is performed atomically. Some attempted\n * update operations on this map by other threads may be blocked\n * while computation is in progress, so the computation should be\n * short and simple, and must not attempt to update any other\n * mappings of this Map.\n *\n * @param key key with which the specified value is to be associated\n * @param value the value to use if absent\n * @param remappingFunction the function to recompute a value if present\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or the\n * remappingFunction is null\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V merge(K key, V value, BiFunction remappingFunction) {\n if (key == null || value == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n if (casTabAt(tab, i, null, new Node(h, key, value))) {\n delta = 1;\n val = value;\n break;\n }\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(e.val, value);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n delta = 1;\n val = value;\n pred.next = new Node(h, key, val);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r = t.root;\n TreeNode p = (r == null) ? null : r.findTreeNode(h, key, null);\n val = (p == null) ? value : remappingFunction.apply(p.val, value);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n // Hashtable legacy methods\n /**\n * Tests if some key maps into the specified value in this table.\n *\n *

Note that this method is identical in functionality to\n * {@link #containsValue(Object)}, and exists solely to ensure\n * full compatibility with class {@link java.util.Hashtable},\n * which supported this method prior to introduction of the\n * Java Collections Framework.\n *\n * @param value a value to search for\n * @return {@code true} if and only if some key maps to the\n * {@code value} argument in this table as\n * determined by the {@code equals} method;\n * {@code false} otherwise\n * @throws NullPointerException if the specified value is null\n */\n public boolean contains(Object value) {\n return containsValue(value);\n }\n\n /**\n * Returns an enumeration of the keys in this table.\n *\n * @return an enumeration of the keys in this table\n * @see #keySet()\n */\n public Enumeration keys() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, this);\n }\n\n /**\n * Returns an enumeration of the values in this table.\n *\n * @return an enumeration of the values in this table\n * @see #values()\n */\n public Enumeration elements() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, this);\n }\n\n // ConcurrentHashMap-only methods\n /**\n * Returns the number of mappings. This method should be used\n * instead of {@link #size} because a ConcurrentHashMap may\n * contain more mappings than can be represented as an int. The\n * value returned is an estimate; the actual count may differ if\n * there are concurrent insertions or removals.\n *\n * @return the number of mappings\n * @since 1.8\n */\n public long mappingCount() {\n long n = sumCount();\n // ignore transient negative values\n return (n < 0L) ? 0L : n;\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param the element type of the returned set\n * @return the new set\n * @since 1.8\n */\n public static KeySetView newKeySet() {\n return new KeySetView(new ConcurrentHashMap(), Boolean.TRUE);\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @param the element type of the returned set\n * @return the new set\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n * @since 1.8\n */\n public static KeySetView newKeySet(int initialCapacity) {\n return new KeySetView(new ConcurrentHashMap(initialCapacity), Boolean.TRUE);\n }\n\n /**\n * Returns a {@link Set} view of the keys in this map, using the\n * given common mapped value for any additions (i.e., {@link\n * Collection#add} and {@link Collection#addAll(Collection)}).\n * This is of course only appropriate if it is acceptable to use\n * the same value for all additions from this view.\n *\n * @param mappedValue the mapped value to use for any additions\n * @return the set view\n * @throws NullPointerException if the mappedValue is null\n */\n public KeySetView keySet(V mappedValue) {\n if (mappedValue == null)\n throw new NullPointerException();\n return new KeySetView(this, mappedValue);\n }\n\n /**\n * A node inserted at head of bins during transfer operations.\n */\n static final class ForwardingNode extends Node {\n\n final Node[] nextTable;\n\n ForwardingNode(Node[] tab) {\n super(MOVED, null, null);\n this.nextTable = tab;\n }\n\n Node find(int h, Object k) {\n // loop to avoid arbitrarily deep recursion on forwarding nodes\n outer: for (Node[] tab = nextTable; ; ) {\n Node e;\n int n;\n if (k == null || tab == null || (n = tab.length) == 0 || (e = tabAt(tab, (n - 1) & h)) == null)\n return null;\n for (; ; ) {\n int eh;\n K ek;\n if ((eh = e.hash) == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n if (eh < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n continue outer;\n } else\n return e.find(h, k);\n }\n if ((e = e.next) == null)\n return null;\n }\n }\n }\n }\n\n /**\n * A place-holder node used in computeIfAbsent and compute.\n */\n static final class ReservationNode extends Node {\n\n ReservationNode() {\n super(RESERVED, null, null);\n }\n\n Node find(int h, Object k) {\n return null;\n }\n }\n\n /* ---------------- Table Initialization and Resizing -------------- */\n /**\n * Returns the stamp bits for resizing a table of size n.\n * Must be negative when shifted left by RESIZE_STAMP_SHIFT.\n */\n static final int resizeStamp(int n) {\n return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));\n }\n\n /**\n * Initializes table, using the size recorded in sizeCtl.\n */\n private final Node[] initTable() {\n Node[] tab;\n int sc;\n while ((tab = table) == null || tab.length == 0) {\n if ((sc = sizeCtl) < 0)\n // lost initialization race; just spin\n Thread.yield();\n else if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if ((tab = table) == null || tab.length == 0) {\n int n = (sc > 0) ? sc : DEFAULT_CAPACITY;\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = tab = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n break;\n }\n }\n return tab;\n }\n\n /**\n * Adds to count, and if table is too small and not already\n * resizing, initiates transfer. If already resizing, helps\n * perform transfer if work is available. Rechecks occupancy\n * after a transfer to see if another resize is already needed\n * because resizings are lagging additions.\n *\n * @param x the count to add\n * @param check if <0, don't check resize, if <= 1 only check if uncontended\n */\n private final void addCount(long x, int check) {\n CounterCell[] cs;\n long b, s;\n if ((cs = counterCells) != null || !U.compareAndSetLong(this, BASECOUNT, b = baseCount, s = b + x)) {\n CounterCell c;\n long v;\n int m;\n boolean uncontended = true;\n if (cs == null || (m = cs.length - 1) < 0 || (c = cs[ThreadLocalRandom.getProbe() & m]) == null || !(uncontended = U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))) {\n fullAddCount(x, uncontended);\n return;\n }\n if (check <= 1)\n return;\n s = sumCount();\n }\n if (check >= 0) {\n Node[] tab, nt;\n int n, sc;\n while (s >= (long) (sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) {\n int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT;\n if (sc < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || (nt = nextTable) == null || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1))\n transfer(tab, nt);\n } else if (U.compareAndSetInt(this, SIZECTL, sc, rs + 2))\n transfer(tab, null);\n s = sumCount();\n }\n }\n }\n\n /**\n * Helps transfer if a resize is in progress.\n */\n final Node[] helpTransfer(Node[] tab, Node f) {\n Node[] nextTab;\n int sc;\n if (tab != null && (f instanceof ForwardingNode) && (nextTab = ((ForwardingNode) f).nextTable) != null) {\n int rs = resizeStamp(tab.length) << RESIZE_STAMP_SHIFT;\n while (nextTab == nextTable && table == tab && (sc = sizeCtl) < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1)) {\n transfer(tab, nextTab);\n break;\n }\n }\n return nextTab;\n }\n return table;\n }\n\n /**\n * Tries to presize table to accommodate the given number of elements.\n *\n * @param size number of elements (doesn't need to be perfectly accurate)\n */\n private final void tryPresize(int size) {\n int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(size + (size >>> 1) + 1);\n int sc;\n while ((sc = sizeCtl) >= 0) {\n Node[] tab = table;\n int n;\n if (tab == null || (n = tab.length) == 0) {\n n = (sc > c) ? sc : c;\n if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if (table == tab) {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n }\n } else if (c <= sc || n >= MAXIMUM_CAPACITY)\n break;\n else if (tab == table) {\n int rs = resizeStamp(n);\n if (U.compareAndSetInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2))\n transfer(tab, null);\n }\n }\n }\n\n /**\n * Moves and/or copies the nodes in each bin to new table. See\n * above for explanation.\n */\n private final void transfer(Node[] tab, Node[] nextTab) {\n int n = tab.length, stride;\n if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)\n // subdivide range\n stride = MIN_TRANSFER_STRIDE;\n if (nextTab == null) {\n // initiating\n try {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n << 1];\n nextTab = nt;\n } catch (Throwable ex) {\n // try to cope with OOME\n sizeCtl = Integer.MAX_VALUE;\n return;\n }\n nextTable = nextTab;\n transferIndex = n;\n }\n int nextn = nextTab.length;\n ForwardingNode fwd = new ForwardingNode(nextTab);\n boolean advance = true;\n // to ensure sweep before committing nextTab\n boolean finishing = false;\n for (int i = 0, bound = 0; ; ) {\n Node f;\n int fh;\n while (advance) {\n int nextIndex, nextBound;\n if (--i >= bound || finishing)\n advance = false;\n else if ((nextIndex = transferIndex) <= 0) {\n i = -1;\n advance = false;\n } else if (U.compareAndSetInt(this, TRANSFERINDEX, nextIndex, nextBound = (nextIndex > stride ? nextIndex - stride : 0))) {\n bound = nextBound;\n i = nextIndex - 1;\n advance = false;\n }\n }\n if (i < 0 || i >= n || i + n >= nextn) {\n int sc;\n if (finishing) {\n nextTable = null;\n table = nextTab;\n sizeCtl = (n << 1) - (n >>> 1);\n return;\n }\n if (U.compareAndSetInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {\n if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)\n return;\n finishing = advance = true;\n // recheck before commit\n i = n;\n }\n } else if ((f = tabAt(tab, i)) == null)\n advance = casTabAt(tab, i, null, fwd);\n else if ((fh = f.hash) == MOVED)\n // already processed\n advance = true;\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node ln, hn;\n if (fh >= 0) {\n int runBit = fh & n;\n Node lastRun = f;\n for (Node p = f.next; p != null; p = p.next) {\n int b = p.hash & n;\n if (b != runBit) {\n runBit = b;\n lastRun = p;\n }\n }\n if (runBit == 0) {\n ln = lastRun;\n hn = null;\n } else {\n hn = lastRun;\n ln = null;\n }\n for (Node p = f; p != lastRun; p = p.next) {\n int ph = p.hash;\n K pk = p.key;\n V pv = p.val;\n if ((ph & n) == 0)\n ln = new Node(ph, pk, pv, ln);\n else\n hn = new Node(ph, pk, pv, hn);\n }\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof TreeBin) {\n TreeBin t = (TreeBin) f;\n TreeNode lo = null, loTail = null;\n TreeNode hi = null, hiTail = null;\n int lc = 0, hc = 0;\n for (Node e = t.first; e != null; e = e.next) {\n int h = e.hash;\n TreeNode p = new TreeNode(h, e.key, e.val, null, null);\n if ((h & n) == 0) {\n if ((p.prev = loTail) == null)\n lo = p;\n else\n loTail.next = p;\n loTail = p;\n ++lc;\n } else {\n if ((p.prev = hiTail) == null)\n hi = p;\n else\n hiTail.next = p;\n hiTail = p;\n ++hc;\n }\n }\n ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : (hc != 0) ? new TreeBin(lo) : t;\n hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : (lc != 0) ? new TreeBin(hi) : t;\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n }\n }\n }\n\n /**\n * A padded cell for distributing counts. Adapted from LongAdder\n * and Striped64. See their internal docs for explanation.\n */\n @jdk.internal.vm.annotation.Contended\n static final class CounterCell {\n\n volatile long value;\n\n CounterCell(long x) {\n value = x;\n }\n }\n\n final long sumCount() {\n CounterCell[] cs = counterCells;\n long sum = baseCount;\n if (cs != null) {\n for (CounterCell c : cs) if (c != null)\n sum += c.value;\n }\n return sum;\n }\n\n // See LongAdder version for explanation\n private final void fullAddCount(long x, boolean wasUncontended) {\n int h;\n if ((h = ThreadLocalRandom.getProbe()) == 0) {\n // force initialization\n ThreadLocalRandom.localInit();\n h = ThreadLocalRandom.getProbe();\n wasUncontended = true;\n }\n // True if last slot nonempty\n boolean collide = false;\n for (; ; ) {\n CounterCell[] cs;\n CounterCell c;\n int n;\n long v;\n if ((cs = counterCells) != null && (n = cs.length) > 0) {\n if ((c = cs[(n - 1) & h]) == null) {\n if (cellsBusy == 0) {\n // Try to attach new Cell\n // Optimistic create\n CounterCell r = new CounterCell(x);\n if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean created = false;\n try {\n // Recheck under lock\n CounterCell[] rs;\n int m, j;\n if ((rs = counterCells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) {\n rs[j] = r;\n created = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (created)\n break;\n // Slot is now non-empty\n continue;\n }\n }\n collide = false;\n } else if (// CAS already known to fail\n !wasUncontended)\n // Continue after rehash\n wasUncontended = true;\n else if (U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))\n break;\n else if (counterCells != cs || n >= NCPU)\n // At max size or stale\n collide = false;\n else if (!collide)\n collide = true;\n else if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n try {\n if (// Expand table unless stale\n counterCells == cs)\n counterCells = Arrays.copyOf(cs, n << 1);\n } finally {\n cellsBusy = 0;\n }\n collide = false;\n // Retry with expanded table\n continue;\n }\n h = ThreadLocalRandom.advanceProbe(h);\n } else if (cellsBusy == 0 && counterCells == cs && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean init = false;\n try {\n // Initialize table\n if (counterCells == cs) {\n CounterCell[] rs = new CounterCell[2];\n rs[h & 1] = new CounterCell(x);\n counterCells = rs;\n init = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (init)\n break;\n } else if (U.compareAndSetLong(this, BASECOUNT, v = baseCount, v + x))\n // Fall back on using base\n break;\n }\n }\n\n /**\n * Replaces all linked nodes in bin at given index unless table is\n * too small, in which case resizes instead.\n */\n private final void treeifyBin(Node[] tab, int index) {\n Node b;\n int n;\n if (tab != null) {\n if ((n = tab.length) < MIN_TREEIFY_CAPACITY)\n tryPresize(n << 1);\n else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {\n synchronized (b) {\n if (tabAt(tab, index) == b) {\n TreeNode hd = null, tl = null;\n for (Node e = b; e != null; e = e.next) {\n TreeNode p = new TreeNode(e.hash, e.key, e.val, null, null);\n if ((p.prev = tl) == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n setTabAt(tab, index, new TreeBin(hd));\n }\n }\n }\n }\n }\n\n /**\n * Returns a list of non-TreeNodes replacing those in given list.\n */\n static Node untreeify(Node b) {\n Node hd = null, tl = null;\n for (Node q = b; q != null; q = q.next) {\n Node p = new Node(q.hash, q.key, q.val);\n if (tl == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n return hd;\n }\n\n /**\n * Nodes for use in TreeBins.\n */\n static final class TreeNode extends Node {\n\n // red-black tree links\n TreeNode parent;\n\n TreeNode left;\n\n TreeNode right;\n\n // needed to unlink next upon deletion\n TreeNode prev;\n\n boolean red;\n\n TreeNode(int hash, K key, V val, Node next, TreeNode parent) {\n super(hash, key, val, next);\n this.parent = parent;\n }\n\n Node find(int h, Object k) {\n return findTreeNode(h, k, null);\n }\n\n /**\n * Returns the TreeNode (or null if not found) for the given key\n * starting at given root.\n */\n final TreeNode findTreeNode(int h, Object k, Class kc) {\n if (k != null) {\n TreeNode p = this;\n do {\n int ph, dir;\n K pk;\n TreeNode q;\n TreeNode pl = p.left, pr = p.right;\n if ((ph = p.hash) > h)\n p = pl;\n else if (ph < h)\n p = pr;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if (pl == null)\n p = pr;\n else if (pr == null)\n p = pl;\n else if ((kc != null || (kc = comparableClassFor(k)) != null) && (dir = compareComparables(kc, k, pk)) != 0)\n p = (dir < 0) ? pl : pr;\n else if ((q = pr.findTreeNode(h, k, kc)) != null)\n return q;\n else\n p = pl;\n } while (p != null);\n }\n return null;\n }\n }\n\n /**\n * TreeNodes used at the heads of bins. TreeBins do not hold user\n * keys or values, but instead point to list of TreeNodes and\n * their root. They also maintain a parasitic read-write lock\n * forcing writers (who hold bin lock) to wait for readers (who do\n * not) to complete before tree restructuring operations.\n */\n static final class TreeBin extends Node {\n\n TreeNode root;\n\n volatile TreeNode first;\n\n volatile Thread waiter;\n\n volatile int lockState;\n\n // values for lockState\n // set while holding write lock\n static final int WRITER = 1;\n\n // set when waiting for write lock\n static final int WAITER = 2;\n\n // increment value for setting read lock\n static final int READER = 4;\n\n /**\n * Tie-breaking utility for ordering insertions when equal\n * hashCodes and non-comparable. We don't require a total\n * order, just a consistent insertion rule to maintain\n * equivalence across rebalancings. Tie-breaking further than\n * necessary simplifies testing a bit.\n */\n static int tieBreakOrder(Object a, Object b) {\n int d;\n if (a == null || b == null || (d = a.getClass().getName().compareTo(b.getClass().getName())) == 0)\n d = (System.identityHashCode(a) <= System.identityHashCode(b) ? -1 : 1);\n return d;\n }\n\n /**\n * Creates bin with initial set of nodes headed by b.\n */\n TreeBin(TreeNode b) {\n super(TREEBIN, null, null);\n this.first = b;\n TreeNode r = null;\n for (TreeNode x = b, next; x != null; x = next) {\n next = (TreeNode) x.next;\n x.left = x.right = null;\n if (r == null) {\n x.parent = null;\n x.red = false;\n r = x;\n } else {\n K k = x.key;\n int h = x.hash;\n Class kc = null;\n for (TreeNode p = r; ; ) {\n int dir, ph;\n K pk = p.key;\n if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0)\n dir = tieBreakOrder(k, pk);\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n x.parent = xp;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n r = balanceInsertion(r, x);\n break;\n }\n }\n }\n }\n this.root = r;\n assert checkInvariants(root);\n }\n\n /**\n * Acquires write lock for tree restructuring.\n */\n private final void lockRoot() {\n if (!U.compareAndSetInt(this, LOCKSTATE, 0, WRITER))\n // offload to separate method\n contendedLock();\n }\n\n /**\n * Releases write lock for tree restructuring.\n */\n private final void unlockRoot() {\n lockState = 0;\n }\n\n /**\n * Possibly blocks awaiting root lock.\n */\n private final void contendedLock() {\n boolean waiting = false;\n for (int s; ; ) {\n if (((s = lockState) & ~WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, WRITER)) {\n if (waiting)\n waiter = null;\n return;\n }\n } else if ((s & WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, s | WAITER)) {\n waiting = true;\n waiter = Thread.currentThread();\n }\n } else if (waiting)\n LockSupport.park(this);\n }\n }\n\n /**\n * Returns matching node or null if none. Tries to search\n * using tree comparisons from root, but continues linear\n * search when lock not available.\n */\n final Node find(int h, Object k) {\n if (k != null) {\n for (Node e = first; e != null; ) {\n int s;\n K ek;\n if (((s = lockState) & (WAITER | WRITER)) != 0) {\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n e = e.next;\n } else if (U.compareAndSetInt(this, LOCKSTATE, s, s + READER)) {\n TreeNode r, p;\n try {\n p = ((r = root) == null ? null : r.findTreeNode(h, k, null));\n } finally {\n Thread w;\n if (U.getAndAddInt(this, LOCKSTATE, -READER) == (READER | WAITER) && (w = waiter) != null)\n LockSupport.unpark(w);\n }\n return p;\n }\n }\n }\n return null;\n }\n\n /**\n * Finds or adds a node.\n * @return null if added\n */\n final TreeNode putTreeVal(int h, K k, V v) {\n Class kc = null;\n boolean searched = false;\n for (TreeNode p = root; ; ) {\n int dir, ph;\n K pk;\n if (p == null) {\n first = root = new TreeNode(h, k, v, null, null);\n break;\n } else if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) {\n if (!searched) {\n TreeNode q, ch;\n searched = true;\n if (((ch = p.left) != null && (q = ch.findTreeNode(h, k, kc)) != null) || ((ch = p.right) != null && (q = ch.findTreeNode(h, k, kc)) != null))\n return q;\n }\n dir = tieBreakOrder(k, pk);\n }\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n TreeNode x, f = first;\n first = x = new TreeNode(h, k, v, f, xp);\n if (f != null)\n f.prev = x;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n if (!xp.red)\n x.red = true;\n else {\n lockRoot();\n try {\n root = balanceInsertion(root, x);\n } finally {\n unlockRoot();\n }\n }\n break;\n }\n }\n assert checkInvariants(root);\n return null;\n }\n\n /**\n * Removes the given node, that must be present before this\n * call. This is messier than typical red-black deletion code\n * because we cannot swap the contents of an interior node\n * with a leaf successor that is pinned by \"next\" pointers\n * that are accessible independently of lock. So instead we\n * swap the tree linkages.\n *\n * @return true if now too small, so should be untreeified\n */\n final boolean removeTreeNode(TreeNode p) {\n TreeNode next = (TreeNode) p.next;\n // unlink traversal pointers\n TreeNode pred = p.prev;\n TreeNode r, rl;\n if (pred == null)\n first = next;\n else\n pred.next = next;\n if (next != null)\n next.prev = pred;\n if (first == null) {\n root = null;\n return true;\n }\n if (// too small\n (r = root) == null || r.right == null || (rl = r.left) == null || rl.left == null)\n return true;\n lockRoot();\n try {\n TreeNode replacement;\n TreeNode pl = p.left;\n TreeNode pr = p.right;\n if (pl != null && pr != null) {\n TreeNode s = pr, sl;\n while (// find successor\n (sl = s.left) != null) s = sl;\n // swap colors\n boolean c = s.red;\n // swap colors\n s.red = p.red;\n // swap colors\n p.red = c;\n TreeNode sr = s.right;\n TreeNode pp = p.parent;\n if (s == pr) {\n // p was s's direct parent\n p.parent = s;\n s.right = p;\n } else {\n TreeNode sp = s.parent;\n if ((p.parent = sp) != null) {\n if (s == sp.left)\n sp.left = p;\n else\n sp.right = p;\n }\n if ((s.right = pr) != null)\n pr.parent = s;\n }\n p.left = null;\n if ((p.right = sr) != null)\n sr.parent = p;\n if ((s.left = pl) != null)\n pl.parent = s;\n if ((s.parent = pp) == null)\n r = s;\n else if (p == pp.left)\n pp.left = s;\n else\n pp.right = s;\n if (sr != null)\n replacement = sr;\n else\n replacement = p;\n } else if (pl != null)\n replacement = pl;\n else if (pr != null)\n replacement = pr;\n else\n replacement = p;\n if (replacement != p) {\n TreeNode pp = replacement.parent = p.parent;\n if (pp == null)\n r = replacement;\n else if (p == pp.left)\n pp.left = replacement;\n else\n pp.right = replacement;\n p.left = p.right = p.parent = null;\n }\n root = (p.red) ? r : balanceDeletion(r, replacement);\n if (p == replacement) {\n // detach pointers\n TreeNode pp;\n if ((pp = p.parent) != null) {\n if (p == pp.left)\n pp.left = null;\n else if (p == pp.right)\n pp.right = null;\n p.parent = null;\n }\n }\n } finally {\n unlockRoot();\n }\n assert checkInvariants(root);\n return false;\n }\n\n // Red-black tree methods, all adapted from CLR\n static TreeNode rotateLeft(TreeNode root, TreeNode p) {\n TreeNode r, pp, rl;\n if (p != null && (r = p.right) != null) {\n if ((rl = p.right = r.left) != null)\n rl.parent = p;\n if ((pp = r.parent = p.parent) == null)\n (root = r).red = false;\n else if (pp.left == p)\n pp.left = r;\n else\n pp.right = r;\n r.left = p;\n p.parent = r;\n }\n return root;\n }\n\n static TreeNode rotateRight(TreeNode root, TreeNode p) {\n TreeNode l, pp, lr;\n if (p != null && (l = p.left) != null) {\n if ((lr = p.left = l.right) != null)\n lr.parent = p;\n if ((pp = l.parent = p.parent) == null)\n (root = l).red = false;\n else if (pp.right == p)\n pp.right = l;\n else\n pp.left = l;\n l.right = p;\n p.parent = l;\n }\n return root;\n }\n\n static TreeNode balanceInsertion(TreeNode root, TreeNode x) {\n x.red = true;\n for (TreeNode xp, xpp, xppl, xppr; ; ) {\n if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (!xp.red || (xpp = xp.parent) == null)\n return root;\n if (xp == (xppl = xpp.left)) {\n if ((xppr = xpp.right) != null && xppr.red) {\n xppr.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.right) {\n root = rotateLeft(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateRight(root, xpp);\n }\n }\n }\n } else {\n if (xppl != null && xppl.red) {\n xppl.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.left) {\n root = rotateRight(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateLeft(root, xpp);\n }\n }\n }\n }\n }\n }\n\n static TreeNode balanceDeletion(TreeNode root, TreeNode x) {\n for (TreeNode xp, xpl, xpr; ; ) {\n if (x == null || x == root)\n return root;\n else if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (x.red) {\n x.red = false;\n return root;\n } else if ((xpl = xp.left) == x) {\n if ((xpr = xp.right) != null && xpr.red) {\n xpr.red = false;\n xp.red = true;\n root = rotateLeft(root, xp);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr == null)\n x = xp;\n else {\n TreeNode sl = xpr.left, sr = xpr.right;\n if ((sr == null || !sr.red) && (sl == null || !sl.red)) {\n xpr.red = true;\n x = xp;\n } else {\n if (sr == null || !sr.red) {\n if (sl != null)\n sl.red = false;\n xpr.red = true;\n root = rotateRight(root, xpr);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr != null) {\n xpr.red = (xp == null) ? false : xp.red;\n if ((sr = xpr.right) != null)\n sr.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateLeft(root, xp);\n }\n x = root;\n }\n }\n } else {\n // symmetric\n if (xpl != null && xpl.red) {\n xpl.red = false;\n xp.red = true;\n root = rotateRight(root, xp);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl == null)\n x = xp;\n else {\n TreeNode sl = xpl.left, sr = xpl.right;\n if ((sl == null || !sl.red) && (sr == null || !sr.red)) {\n xpl.red = true;\n x = xp;\n } else {\n if (sl == null || !sl.red) {\n if (sr != null)\n sr.red = false;\n xpl.red = true;\n root = rotateLeft(root, xpl);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl != null) {\n xpl.red = (xp == null) ? false : xp.red;\n if ((sl = xpl.left) != null)\n sl.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateRight(root, xp);\n }\n x = root;\n }\n }\n }\n }\n }\n\n /**\n * Checks invariants recursively for the tree of Nodes rooted at t.\n */\n static boolean checkInvariants(TreeNode t) {\n TreeNode tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode) t.next;\n if (tb != null && tb.next != t)\n return false;\n if (tn != null && tn.prev != t)\n return false;\n if (tp != null && t != tp.left && t != tp.right)\n return false;\n if (tl != null && (tl.parent != t || tl.hash > t.hash))\n return false;\n if (tr != null && (tr.parent != t || tr.hash < t.hash))\n return false;\n if (t.red && tl != null && tl.red && tr != null && tr.red)\n return false;\n if (tl != null && !checkInvariants(tl))\n return false;\n if (tr != null && !checkInvariants(tr))\n return false;\n return true;\n }\n\n private static final long LOCKSTATE = U.objectFieldOffset(TreeBin.class, \"lockState\");\n }\n\n /**\n * Records the table, its length, and current traversal index for a\n * traverser that must process a region of a forwarded table before\n * proceeding with current table.\n */\n static final class TableStack {\n\n int length;\n\n int index;\n\n Node[] tab;\n\n TableStack next;\n }\n\n /**\n * Encapsulates traversal for methods such as containsValue; also\n * serves as a base class for other iterators and spliterators.\n *\n * Method advance visits once each still-valid node that was\n * reachable upon iterator construction. It might miss some that\n * were added to a bin after the bin was visited, which is OK wrt\n * consistency guarantees. Maintaining this property in the face\n * of possible ongoing resizes requires a fair amount of\n * bookkeeping state that is difficult to optimize away amidst\n * volatile accesses. Even so, traversal maintains reasonable\n * throughput.\n *\n * Normally, iteration proceeds bin-by-bin traversing lists.\n * However, if the table has been resized, then all future steps\n * must traverse both the bin at the current index as well as at\n * (index + baseSize); and so on for further resizings. To\n * paranoically cope with potential sharing by users of iterators\n * across threads, iteration terminates if a bounds checks fails\n * for a table read.\n */\n static class Traverser {\n\n // current table; updated if resized\n Node[] tab;\n\n // the next entry to use\n Node next;\n\n // to save/restore on ForwardingNodes\n TableStack stack, spare;\n\n // index of bin to use next\n int index;\n\n // current index of initial table\n int baseIndex;\n\n // index bound for initial table\n int baseLimit;\n\n // initial table size\n final int baseSize;\n\n Traverser(Node[] tab, int size, int index, int limit) {\n this.tab = tab;\n this.baseSize = size;\n this.baseIndex = this.index = index;\n this.baseLimit = limit;\n this.next = null;\n }\n\n /**\n * Advances if possible, returning next valid node, or null if none.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n // must use locals in checks\n Node[] t;\n // must use locals in checks\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n // visit upper slots if present\n index = ++baseIndex;\n }\n }\n\n /**\n * Saves traversal state upon encountering a forwarding node.\n */\n private void pushState(Node[] t, int i, int n) {\n // reuse if possible\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n /**\n * Possibly pops traversal state.\n *\n * @param n length of current table\n */\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /**\n * Base of key, value, and entry Iterators. Adds fields to\n * Traverser to support iterator.remove.\n */\n static class BaseIterator extends Traverser {\n\n final ConcurrentHashMap map;\n\n Node lastReturned;\n\n BaseIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n advance();\n }\n\n public final boolean hasNext() {\n return next != null;\n }\n\n public final boolean hasMoreElements() {\n return next != null;\n }\n\n public final void remove() {\n Node p;\n if ((p = lastReturned) == null)\n throw new IllegalStateException();\n lastReturned = null;\n map.replaceNode(p.key, null, null);\n }\n }\n\n static final class KeyIterator extends BaseIterator implements Iterator, Enumeration {\n\n KeyIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final K next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n lastReturned = p;\n advance();\n return k;\n }\n\n public final K nextElement() {\n return next();\n }\n }\n\n static final class ValueIterator extends BaseIterator implements Iterator, Enumeration {\n\n ValueIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final V next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n V v = p.val;\n lastReturned = p;\n advance();\n return v;\n }\n\n public final V nextElement() {\n return next();\n }\n }\n\n static final class EntryIterator extends BaseIterator implements Iterator> {\n\n EntryIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final Map.Entry next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n V v = p.val;\n lastReturned = p;\n advance();\n return new MapEntry(k, v, map);\n }\n }\n\n static final class MapEntry implements Map.Entry {\n\n final K key;\n\n V val;\n\n final ConcurrentHashMap map;\n\n MapEntry(K key, V val, ConcurrentHashMap map) {\n this.key = key;\n this.val = val;\n this.map = map;\n }\n\n public K getKey() {\n return key;\n }\n\n public V getValue() {\n return val;\n }\n\n public int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public boolean equals(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == val || v.equals(val)));\n }\n\n /**\n * Sets our entry's value and writes through to the map. The\n * value to return is somewhat arbitrary here. Since we do not\n * necessarily track asynchronous changes, the most recent\n * \"previous\" value could be different from what we return (or\n * could even have been removed, in which case the put will\n * re-establish). We do not and cannot guarantee more.\n */\n public V setValue(V value) {\n if (value == null)\n throw new NullPointerException();\n V v = val;\n val = value;\n map.put(key, value);\n return v;\n }\n }\n\n static final class KeySpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n KeySpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public KeySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new KeySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.key);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class ValueSpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n ValueSpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public ValueSpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new ValueSpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.val);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class EntrySpliterator extends Traverser implements Spliterator> {\n\n // To export MapEntry\n final ConcurrentHashMap map;\n\n // size estimate\n long est;\n\n EntrySpliterator(Node[] tab, int size, int index, int limit, long est, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n this.est = est;\n }\n\n public EntrySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new EntrySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1, map);\n }\n\n public void forEachRemaining(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n\n public boolean tryAdvance(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(new MapEntry(p.key, p.val, map));\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n // Parallel bulk operations\n /**\n * Computes initial batch value for bulk tasks. The returned value\n * is approximately exp2 of the number of times (minus one) to\n * split task by two before executing leaf action. This value is\n * faster to compute and more convenient to use as a guide to\n * splitting than is the depth, since it is used while dividing by\n * two anyway.\n */\n final int batchFor(long b) {\n long n;\n if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)\n return 0;\n // slack of 4\n int sp = ForkJoinPool.getCommonPoolParallelism() << 2;\n return (b <= 0L || (n /= b) >= sp) ? sp : (int) n;\n }\n\n /**\n * Performs the given action for each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiFunction transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each (key, value), or null if none. Upon\n * success, further element processing is suppressed and the\n * results of any other parallel invocations of the search\n * function are ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each (key, value), or null if none\n * @since 1.8\n */\n public U search(long parallelismThreshold, BiFunction searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public U reduce(long parallelismThreshold, BiFunction transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public double reduceToDouble(long parallelismThreshold, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public long reduceToLong(long parallelismThreshold, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public int reduceToInt(long parallelismThreshold, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each key, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each key, or null if none\n * @since 1.8\n */\n public U searchKeys(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all keys using the given\n * reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all keys using the given\n * reducer to combine values, or null if none\n * @since 1.8\n */\n public K reduceKeys(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public U reduceKeys(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public double reduceKeysToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public long reduceKeysToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public int reduceKeysToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachValueTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedValueTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each value, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each value, or null if none\n * @since 1.8\n */\n public U searchValues(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all values using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all values\n * @since 1.8\n */\n public V reduceValues(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public U reduceValues(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public double reduceValuesToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public long reduceValuesToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public int reduceValuesToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Function, ? extends U> transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each entry, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each entry, or null if none\n * @since 1.8\n */\n public U searchEntries(long parallelismThreshold, Function, ? extends U> searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all entries using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all entries\n * @since 1.8\n */\n public Map.Entry reduceEntries(long parallelismThreshold, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public U reduceEntries(long parallelismThreshold, Function, ? extends U> transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public double reduceEntriesToDouble(long parallelismThreshold, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public long reduceEntriesToLong(long parallelismThreshold, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public int reduceEntriesToInt(long parallelismThreshold, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n abstract static class CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n final ConcurrentHashMap map;\n\n CollectionView(ConcurrentHashMap map) {\n this.map = map;\n }\n\n /**\n * Returns the map backing this view.\n *\n * @return the map backing this view\n */\n public ConcurrentHashMap getMap() {\n return map;\n }\n\n /**\n * Removes all of the elements from this view, by removing all\n * the mappings from the map backing this view.\n */\n public final void clear() {\n map.clear();\n }\n\n public final int size() {\n return map.size();\n }\n\n public final boolean isEmpty() {\n return map.isEmpty();\n }\n\n // implementations below rely on concrete classes supplying these\n /**\n * Returns an iterator over the elements in this collection.\n *\n *

The returned iterator is\n * weakly consistent.\n *\n * @return an iterator over the elements in this collection\n */\n public abstract Iterator iterator();\n\n public abstract boolean contains(Object o);\n\n public abstract boolean remove(Object o);\n\n private static final String OOME_MSG = \"Required array size too large\";\n\n public final Object[] toArray() {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int n = (int) sz;\n Object[] r = new Object[n];\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = e;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n @SuppressWarnings(\"unchecked\")\n public final T[] toArray(T[] a) {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int m = (int) sz;\n T[] r = (a.length >= m) ? a : (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), m);\n int n = r.length;\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = (T) e;\n }\n if (a == r && i < n) {\n r[i] = null;\n return r;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n /**\n * Returns a string representation of this collection.\n * The string representation consists of the string representations\n * of the collection's elements in the order they are returned by\n * its iterator, enclosed in square brackets ({@code \"[]\"}).\n * Adjacent elements are separated by the characters {@code \", \"}\n * (comma and space). Elements are converted to strings as by\n * {@link String#valueOf(Object)}.\n *\n * @return a string representation of this collection\n */\n public final String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append('[');\n Iterator it = iterator();\n if (it.hasNext()) {\n for (; ; ) {\n Object e = it.next();\n sb.append(e == this ? \"(this Collection)\" : e);\n if (!it.hasNext())\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append(']').toString();\n }\n\n public final boolean containsAll(Collection c) {\n if (c != this) {\n for (Object e : c) {\n if (e == null || !contains(e))\n return false;\n }\n }\n return true;\n }\n\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n // Use (c instanceof Set) as a hint that lookup in c is as\n // efficient as this view\n Node[] t;\n if ((t = map.table) == null) {\n return false;\n } else if (c instanceof Set && c.size() > t.length) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n } else {\n for (Object e : c) modified |= remove(e);\n }\n return modified;\n }\n\n public final boolean retainAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (!c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of keys, in\n * which additions may optionally be enabled by mapping to a\n * common value. This class cannot be directly instantiated.\n * See {@link #keySet() keySet()},\n * {@link #keySet(Object) keySet(V)},\n * {@link #newKeySet() newKeySet()},\n * {@link #newKeySet(int) newKeySet(int)}.\n *\n * @since 1.8\n */\n public static class KeySetView extends CollectionView implements Set, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n // Conditionally serializable\n @SuppressWarnings(\"serial\")\n private final V value;\n\n KeySetView(ConcurrentHashMap map, V value) {\n super(map);\n this.value = value;\n }\n\n /**\n * Returns the default mapped value for additions,\n * or {@code null} if additions are not supported.\n *\n * @return the default mapped value for additions, or {@code null}\n * if not supported\n */\n public V getMappedValue() {\n return value;\n }\n\n /**\n * {@inheritDoc}\n * @throws NullPointerException if the specified key is null\n */\n public boolean contains(Object o) {\n return map.containsKey(o);\n }\n\n /**\n * Removes the key from this map view, by removing the key (and its\n * corresponding value) from the backing map. This method does\n * nothing if the key is not in the map.\n *\n * @param o the key to be removed from the backing map\n * @return {@code true} if the backing map contained the specified key\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object o) {\n return map.remove(o) != null;\n }\n\n /**\n * @return an iterator over the keys of the backing map\n */\n public Iterator iterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, m);\n }\n\n /**\n * Adds the specified key to this set view by mapping the key to\n * the default mapped value in the backing map, if defined.\n *\n * @param e key to be added\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the specified key is null\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean add(K e) {\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n return map.putVal(e, v, true) == null;\n }\n\n /**\n * Adds all of the elements in the specified collection to this set,\n * as if by calling {@link #add} on each one.\n *\n * @param c the elements to be inserted into this set\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the collection or any of its\n * elements are {@code null}\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean addAll(Collection c) {\n boolean added = false;\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n for (K e : c) {\n if (map.putVal(e, v, true) == null)\n added = true;\n }\n return added;\n }\n\n public int hashCode() {\n int h = 0;\n for (K e : this) h += e.hashCode();\n return h;\n }\n\n public boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeySpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.key);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Collection} of\n * values, in which additions are disabled. This class cannot be\n * directly instantiated. See {@link #values()}.\n */\n static final class ValuesView extends CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n ValuesView(ConcurrentHashMap map) {\n super(map);\n }\n\n public final boolean contains(Object o) {\n return map.containsValue(o);\n }\n\n public final boolean remove(Object o) {\n if (o != null) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (o.equals(it.next())) {\n it.remove();\n return true;\n }\n }\n }\n return false;\n }\n\n public final Iterator iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, m);\n }\n\n public final boolean add(V e) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean addAll(Collection c) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n\n public boolean removeIf(Predicate filter) {\n return map.removeValueIf(filter);\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueSpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.val);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of (key, value)\n * entries. This class cannot be directly instantiated. See\n * {@link #entrySet()}.\n */\n static final class EntrySetView extends CollectionView> implements Set>, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n EntrySetView(ConcurrentHashMap map) {\n super(map);\n }\n\n public boolean contains(Object o) {\n Object k, v, r;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (r = map.get(k)) != null && (v = e.getValue()) != null && (v == r || v.equals(r)));\n }\n\n public boolean remove(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && map.remove(k, v));\n }\n\n /**\n * @return an iterator over the entries of the backing map\n */\n public Iterator> iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntryIterator(t, f, 0, f, m);\n }\n\n public boolean add(Entry e) {\n return map.putVal(e.getKey(), e.getValue(), false) == null;\n }\n\n public boolean addAll(Collection> c) {\n boolean added = false;\n for (Entry e : c) {\n if (add(e))\n added = true;\n }\n return added;\n }\n\n public boolean removeIf(Predicate> filter) {\n return map.removeEntryIf(filter);\n }\n\n public final int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n h += p.hashCode();\n }\n }\n return h;\n }\n\n public final boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator> spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntrySpliterator(t, f, 0, f, n < 0L ? 0L : n, m);\n }\n\n public void forEach(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n }\n }\n\n /**\n * Base class for bulk tasks. Repeats some fields and code from\n * class Traverser, because we need to subclass CountedCompleter.\n */\n @SuppressWarnings(\"serial\")\n abstract static class BulkTask extends CountedCompleter {\n\n // same as Traverser\n Node[] tab;\n\n Node next;\n\n TableStack stack, spare;\n\n int index;\n\n int baseIndex;\n\n int baseLimit;\n\n final int baseSize;\n\n // split control\n int batch;\n\n BulkTask(BulkTask par, int b, int i, int f, Node[] t) {\n super(par);\n this.batch = b;\n this.index = this.baseIndex = i;\n if ((this.tab = t) == null)\n this.baseSize = this.baseLimit = 0;\n else if (par == null)\n this.baseSize = this.baseLimit = t.length;\n else {\n this.baseLimit = f;\n this.baseSize = par.baseSize;\n }\n }\n\n /**\n * Same as Traverser version.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n Node[] t;\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n private void pushState(Node[] t, int i, int n) {\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /*\n * Task classes. Coded in a regular but ugly format/style to\n * simplify checks that each variant differs in the right way from\n * others. The null screenings exist because compilers cannot tell\n * that we've already null-checked task arguments, so we force\n * simplest hoisted bypass to help avoid convoluted traps.\n */\n @SuppressWarnings(\"serial\")\n static final class ForEachKeyTask extends BulkTask {\n\n final Consumer action;\n\n ForEachKeyTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachValueTask extends BulkTask {\n\n final Consumer action;\n\n ForEachValueTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachValueTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachEntryTask extends BulkTask {\n\n final Consumer> action;\n\n ForEachEntryTask(BulkTask p, int b, int i, int f, Node[] t, Consumer> action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer> action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachMappingTask extends BulkTask {\n\n final BiConsumer action;\n\n ForEachMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiConsumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final BiConsumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key, p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedKeyTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedKeyTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedValueTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedValueTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedValueTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedEntryTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final Consumer action;\n\n ForEachTransformedEntryTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedMappingTask extends BulkTask {\n\n final BiFunction transformer;\n\n final Consumer action;\n\n ForEachTransformedMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchKeysTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchKeysTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchValuesTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchValuesTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchEntriesTask extends BulkTask {\n\n final Function, ? extends U> searchFunction;\n\n final AtomicReference result;\n\n SearchEntriesTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function, ? extends U> searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n return;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchMappingsTask extends BulkTask {\n\n final BiFunction searchFunction;\n\n final AtomicReference result;\n\n SearchMappingsTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final BiFunction searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key, p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceKeysTask extends BulkTask {\n\n final BiFunction reducer;\n\n K result;\n\n ReduceKeysTask rights, nextRight;\n\n ReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, ReduceKeysTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final K getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n K r = null;\n for (Node p; (p = advance()) != null; ) {\n K u = p.key;\n r = (r == null) ? u : u == null ? r : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceKeysTask t = (ReduceKeysTask) c, s = t.rights;\n while (s != null) {\n K tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceValuesTask extends BulkTask {\n\n final BiFunction reducer;\n\n V result;\n\n ReduceValuesTask rights, nextRight;\n\n ReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceValuesTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final V getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n V r = null;\n for (Node p; (p = advance()) != null; ) {\n V v = p.val;\n r = (r == null) ? v : reducer.apply(r, v);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceValuesTask t = (ReduceValuesTask) c, s = t.rights;\n while (s != null) {\n V tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceEntriesTask extends BulkTask> {\n\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n\n Map.Entry result;\n\n ReduceEntriesTask rights, nextRight;\n\n ReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceEntriesTask nextRight, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final Map.Entry getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n Map.Entry r = null;\n for (Node p; (p = advance()) != null; ) r = (r == null) ? p : reducer.apply(r, p);\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceEntriesTask t = (ReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n Map.Entry tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceKeysTask rights, nextRight;\n\n MapReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysTask t = (MapReduceKeysTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceValuesTask rights, nextRight;\n\n MapReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesTask t = (MapReduceValuesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceEntriesTask rights, nextRight;\n\n MapReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesTask nextRight, Function, ? extends U> transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesTask t = (MapReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsTask extends BulkTask {\n\n final BiFunction transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceMappingsTask rights, nextRight;\n\n MapReduceMappingsTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsTask nextRight, BiFunction transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsTask t = (MapReduceMappingsTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceKeysToDoubleTask rights, nextRight;\n\n MapReduceKeysToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToDoubleTask t = (MapReduceKeysToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceValuesToDoubleTask rights, nextRight;\n\n MapReduceValuesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToDoubleTask t = (MapReduceValuesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction> transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceEntriesToDoubleTask rights, nextRight;\n\n MapReduceEntriesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToDoubleTask nextRight, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction> transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToDoubleTask t = (MapReduceEntriesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToDoubleTask extends BulkTask {\n\n final ToDoubleBiFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceMappingsToDoubleTask rights, nextRight;\n\n MapReduceMappingsToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToDoubleTask nextRight, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleBiFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToDoubleTask t = (MapReduceMappingsToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceKeysToLongTask rights, nextRight;\n\n MapReduceKeysToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToLongTask t = (MapReduceKeysToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceValuesToLongTask rights, nextRight;\n\n MapReduceValuesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToLongTask t = (MapReduceValuesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToLongTask extends BulkTask {\n\n final ToLongFunction> transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceEntriesToLongTask rights, nextRight;\n\n MapReduceEntriesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToLongTask nextRight, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction> transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToLongTask t = (MapReduceEntriesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToLongTask extends BulkTask {\n\n final ToLongBiFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceMappingsToLongTask rights, nextRight;\n\n MapReduceMappingsToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToLongTask nextRight, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongBiFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToLongTask t = (MapReduceMappingsToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceKeysToIntTask rights, nextRight;\n\n MapReduceKeysToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToIntTask t = (MapReduceKeysToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceValuesToIntTask rights, nextRight;\n\n MapReduceValuesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperat", "post_mask_code": "\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToIntTask t = (MapReduceValuesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToIntTask extends BulkTask {\n\n final ToIntFunction> transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceEntriesToIntTask rights, nextRight;\n\n MapReduceEntriesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToIntTask nextRight, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction> transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToIntTask t = (MapReduceEntriesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToIntTask extends BulkTask {\n\n final ToIntBiFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceMappingsToIntTask rights, nextRight;\n\n MapReduceMappingsToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToIntTask nextRight, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntBiFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToIntTask t = (MapReduceMappingsToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n // Unsafe mechanics\n private static final Unsafe U = Unsafe.getUnsafe();\n\n private static final long SIZECTL = U.objectFieldOffset(ConcurrentHashMap.class, \"sizeCtl\");\n\n private static final long TRANSFERINDEX = U.objectFieldOffset(ConcurrentHashMap.class, \"transferIndex\");\n\n private static final long BASECOUNT = U.objectFieldOffset(ConcurrentHashMap.class, \"baseCount\");\n\n private static final long CELLSBUSY = U.objectFieldOffset(ConcurrentHashMap.class, \"cellsBusy\");\n\n private static final long CELLVALUE = U.objectFieldOffset(CounterCell.class, \"value\");\n\n private static final int ABASE = U.arrayBaseOffset(Node[].class);\n\n private static final int ASHIFT;\n\n static {\n int scale = U.arrayIndexScale(Node[].class);\n if ((scale & (scale - 1)) != 0)\n throw new ExceptionInInitializerError(\"array index scale not a power of two\");\n ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);\n // Reduce the risk of rare disastrous classloading in first call to\n Class ensureLoaded = LockSupport.class;\n // Eager class load observed to help JIT during startup\n ensureLoaded = ReservationNode.class;\n }\n}\n"} {"task_id": "Java_2825", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/openjdk/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java", "mask_start_position": 64085, "mask_end_position": 64170, "canonical_solution": "public V putIfAbsent(K key, V value) {\n return putVal(key, value, true);\n }", "pre_mask_code": "package java.util.concurrent;\n\nimport java.io.ObjectStreamField;\nimport java.io.Serializable;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.AbstractMap;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Hashtable;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.Spliterator;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.concurrent.locks.LockSupport;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\nimport java.util.function.Consumer;\nimport java.util.function.DoubleBinaryOperator;\nimport java.util.function.Function;\nimport java.util.function.IntBinaryOperator;\nimport java.util.function.LongBinaryOperator;\nimport java.util.function.Predicate;\nimport java.util.function.ToDoubleBiFunction;\nimport java.util.function.ToDoubleFunction;\nimport java.util.function.ToIntBiFunction;\nimport java.util.function.ToIntFunction;\nimport java.util.function.ToLongBiFunction;\nimport java.util.function.ToLongFunction;\nimport java.util.stream.Stream;\nimport jdk.internal.misc.Unsafe;\n\n/**\n * A hash table supporting full concurrency of retrievals and\n * high expected concurrency for updates. This class obeys the\n * same functional specification as {@link java.util.Hashtable}, and\n * includes versions of methods corresponding to each method of\n * {@code Hashtable}. However, even though all operations are\n * thread-safe, retrieval operations do not entail locking,\n * and there is not any support for locking the entire table\n * in a way that prevents all access. This class is fully\n * interoperable with {@code Hashtable} in programs that rely on its\n * thread safety but not on its synchronization details.\n *\n *

Retrieval operations (including {@code get}) generally do not\n * block, so may overlap with update operations (including {@code put}\n * and {@code remove}). Retrievals reflect the results of the most\n * recently completed update operations holding upon their\n * onset. (More formally, an update operation for a given key bears a\n * happens-before relation with any (non-null) retrieval for\n * that key reporting the updated value.) For aggregate operations\n * such as {@code putAll} and {@code clear}, concurrent retrievals may\n * reflect insertion or removal of only some entries. Similarly,\n * Iterators, Spliterators and Enumerations return elements reflecting the\n * state of the hash table at some point at or since the creation of the\n * iterator/enumeration. They do not throw {@link\n * java.util.ConcurrentModificationException ConcurrentModificationException}.\n * However, iterators are designed to be used by only one thread at a time.\n * Bear in mind that the results of aggregate status methods including\n * {@code size}, {@code isEmpty}, and {@code containsValue} are typically\n * useful only when a map is not undergoing concurrent updates in other threads.\n * Otherwise the results of these methods reflect transient states\n * that may be adequate for monitoring or estimation purposes, but not\n * for program control.\n *\n *

The table is dynamically expanded when there are too many\n * collisions (i.e., keys that have distinct hash codes but fall into\n * the same slot modulo the table size), with the expected average\n * effect of maintaining roughly two bins per mapping (corresponding\n * to a 0.75 load factor threshold for resizing). There may be much\n * variance around this average as mappings are added and removed, but\n * overall, this maintains a commonly accepted time/space tradeoff for\n * hash tables. However, resizing this or any other kind of hash\n * table may be a relatively slow operation. When possible, it is a\n * good idea to provide a size estimate as an optional {@code\n * initialCapacity} constructor argument. An additional optional\n * {@code loadFactor} constructor argument provides a further means of\n * customizing initial table capacity by specifying the table density\n * to be used in calculating the amount of space to allocate for the\n * given number of elements. Also, for compatibility with previous\n * versions of this class, constructors may optionally specify an\n * expected {@code concurrencyLevel} as an additional hint for\n * internal sizing. Note that using many keys with exactly the same\n * {@code hashCode()} is a sure way to slow down performance of any\n * hash table. To ameliorate impact, when keys are {@link Comparable},\n * this class may use comparison order among keys to help break ties.\n *\n *

A {@link Set} projection of a ConcurrentHashMap may be created\n * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed\n * (using {@link #keySet(Object)} when only keys are of interest, and the\n * mapped values are (perhaps transiently) not used or all take the\n * same mapping value.\n *\n *

A ConcurrentHashMap can be used as a scalable frequency map (a\n * form of histogram or multiset) by using {@link\n * java.util.concurrent.atomic.LongAdder} values and initializing via\n * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count\n * to a {@code ConcurrentHashMap freqs}, you can use\n * {@code freqs.computeIfAbsent(key, k -> new LongAdder()).increment();}\n *\n *

This class and its views and iterators implement all of the\n * optional methods of the {@link Map} and {@link Iterator}\n * interfaces.\n *\n *

Like {@link Hashtable} but unlike {@link HashMap}, this class\n * does not allow {@code null} to be used as a key or value.\n *\n *

ConcurrentHashMaps support a set of sequential and parallel bulk\n * operations that, unlike most {@link Stream} methods, are designed\n * to be safely, and often sensibly, applied even with maps that are\n * being concurrently updated by other threads; for example, when\n * computing a snapshot summary of the values in a shared registry.\n * There are three kinds of operation, each with four forms, accepting\n * functions with keys, values, entries, and (key, value) pairs as\n * arguments and/or return values. Because the elements of a\n * ConcurrentHashMap are not ordered in any particular way, and may be\n * processed in different orders in different parallel executions, the\n * correctness of supplied functions should not depend on any\n * ordering, or on any other objects or values that may transiently\n * change while computation is in progress; and except for forEach\n * actions, should ideally be side-effect-free. Bulk operations on\n * {@link Map.Entry} objects do not support method {@code setValue}.\n *\n *

    \n *
  • forEach: Performs a given action on each element.\n * A variant form applies a given transformation on each element\n * before performing the action.\n *\n *
  • search: Returns the first available non-null result of\n * applying a given function on each element; skipping further\n * search when a result is found.\n *\n *
  • reduce: Accumulates each element. The supplied reduction\n * function cannot rely on ordering (more formally, it should be\n * both associative and commutative). There are five variants:\n *\n *
      \n *\n *
    • Plain reductions. (There is not a form of this method for\n * (key, value) function arguments since there is no corresponding\n * return type.)\n *\n *
    • Mapped reductions that accumulate the results of a given\n * function applied to each element.\n *\n *
    • Reductions to scalar doubles, longs, and ints, using a\n * given basis value.\n *\n *
    \n *
\n *\n *

These bulk operations accept a {@code parallelismThreshold}\n * argument. Methods proceed sequentially if the current map size is\n * estimated to be less than the given threshold. Using a value of\n * {@code Long.MAX_VALUE} suppresses all parallelism. Using a value\n * of {@code 1} results in maximal parallelism by partitioning into\n * enough subtasks to fully utilize the {@link\n * ForkJoinPool#commonPool()} that is used for all parallel\n * computations. Normally, you would initially choose one of these\n * extreme values, and then measure performance of using in-between\n * values that trade off overhead versus throughput.\n *\n *

The concurrency properties of bulk operations follow\n * from those of ConcurrentHashMap: Any non-null result returned\n * from {@code get(key)} and related access methods bears a\n * happens-before relation with the associated insertion or\n * update. The result of any bulk operation reflects the\n * composition of these per-element relations (but is not\n * necessarily atomic with respect to the map as a whole unless it\n * is somehow known to be quiescent). Conversely, because keys\n * and values in the map are never null, null serves as a reliable\n * atomic indicator of the current lack of any result. To\n * maintain this property, null serves as an implicit basis for\n * all non-scalar reduction operations. For the double, long, and\n * int versions, the basis should be one that, when combined with\n * any other value, returns that other value (more formally, it\n * should be the identity element for the reduction). Most common\n * reductions have these properties; for example, computing a sum\n * with basis 0 or a minimum with basis MAX_VALUE.\n *\n *

Search and transformation functions provided as arguments\n * should similarly return null to indicate the lack of any result\n * (in which case it is not used). In the case of mapped\n * reductions, this also enables transformations to serve as\n * filters, returning null (or, in the case of primitive\n * specializations, the identity basis) if the element should not\n * be combined. You can create compound transformations and\n * filterings by composing them yourself under this \"null means\n * there is nothing there now\" rule before using them in search or\n * reduce operations.\n *\n *

Methods accepting and/or returning Entry arguments maintain\n * key-value associations. They may be useful for example when\n * finding the key for the greatest value. Note that \"plain\" Entry\n * arguments can be supplied using {@code new\n * AbstractMap.SimpleEntry(k,v)}.\n *\n *

Bulk operations may complete abruptly, throwing an\n * exception encountered in the application of a supplied\n * function. Bear in mind when handling such exceptions that other\n * concurrently executing functions could also have thrown\n * exceptions, or would have done so if the first exception had\n * not occurred.\n *\n *

Speedups for parallel compared to sequential forms are common\n * but not guaranteed. Parallel operations involving brief functions\n * on small maps may execute more slowly than sequential forms if the\n * underlying work to parallelize the computation is more expensive\n * than the computation itself. Similarly, parallelization may not\n * lead to much actual parallelism if all processors are busy\n * performing unrelated tasks.\n *\n *

All arguments to all task methods must be non-null.\n *\n *

This class is a member of the\n * \n * Java Collections Framework.\n *\n * @since 1.5\n * @author Doug Lea\n * @param the type of keys maintained by this map\n * @param the type of mapped values\n */\npublic class ConcurrentHashMap extends AbstractMap implements ConcurrentMap, Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n /*\n * Overview:\n *\n * The primary design goal of this hash table is to maintain\n * concurrent readability (typically method get(), but also\n * iterators and related methods) while minimizing update\n * contention. Secondary goals are to keep space consumption about\n * the same or better than java.util.HashMap, and to support high\n * initial insertion rates on an empty table by many threads.\n *\n * This map usually acts as a binned (bucketed) hash table. Each\n * key-value mapping is held in a Node. Most nodes are instances\n * of the basic Node class with hash, key, value, and next\n * fields. However, various subclasses exist: TreeNodes are\n * arranged in balanced trees, not lists. TreeBins hold the roots\n * of sets of TreeNodes. ForwardingNodes are placed at the heads\n * of bins during resizing. ReservationNodes are used as\n * placeholders while establishing values in computeIfAbsent and\n * related methods. The types TreeBin, ForwardingNode, and\n * ReservationNode do not hold normal user keys, values, or\n * hashes, and are readily distinguishable during search etc\n * because they have negative hash fields and null key and value\n * fields. (These special nodes are either uncommon or transient,\n * so the impact of carrying around some unused fields is\n * insignificant.)\n *\n * The table is lazily initialized to a power-of-two size upon the\n * first insertion. Each bin in the table normally contains a\n * list of Nodes (most often, the list has only zero or one Node).\n * Table accesses require volatile/atomic reads, writes, and\n * CASes. Because there is no other way to arrange this without\n * adding further indirections, we use intrinsics\n * (jdk.internal.misc.Unsafe) operations.\n *\n * We use the top (sign) bit of Node hash fields for control\n * purposes -- it is available anyway because of addressing\n * constraints. Nodes with negative hash fields are specially\n * handled or ignored in map methods.\n *\n * Insertion (via put or its variants) of the first node in an\n * empty bin is performed by just CASing it to the bin. This is\n * by far the most common case for put operations under most\n * key/hash distributions. Other update operations (insert,\n * delete, and replace) require locks. We do not want to waste\n * the space required to associate a distinct lock object with\n * each bin, so instead use the first node of a bin list itself as\n * a lock. Locking support for these locks relies on builtin\n * \"synchronized\" monitors.\n *\n * Using the first node of a list as a lock does not by itself\n * suffice though: When a node is locked, any update must first\n * validate that it is still the first node after locking it, and\n * retry if not. Because new nodes are always appended to lists,\n * once a node is first in a bin, it remains first until deleted\n * or the bin becomes invalidated (upon resizing).\n *\n * The main disadvantage of per-bin locks is that other update\n * operations on other nodes in a bin list protected by the same\n * lock can stall, for example when user equals() or mapping\n * functions take a long time. However, statistically, under\n * random hash codes, this is not a common problem. Ideally, the\n * frequency of nodes in bins follows a Poisson distribution\n * (http://example.com) with a\n * parameter of about 0.5 on average, given the resizing threshold\n * of 0.75, although with a large variance because of resizing\n * granularity. Ignoring variance, the expected occurrences of\n * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The\n * first values are:\n *\n * 0: 0.60653066\n * 1: 0.30326533\n * 2: 0.07581633\n * 3: 0.01263606\n * 4: 0.00157952\n * 5: 0.00015795\n * 6: 0.00001316\n * 7: 0.00000094\n * 8: 0.00000006\n * more: less than 1 in ten million\n *\n * Lock contention probability for two threads accessing distinct\n * elements is roughly 1 / (8 * #elements) under random hashes.\n *\n * Actual hash code distributions encountered in practice\n * sometimes deviate significantly from uniform randomness. This\n * includes the case when N > (1<<30), so some keys MUST collide.\n * Similarly for dumb or hostile usages in which multiple keys are\n * designed to have identical hash codes or ones that differs only\n * in masked-out high bits. So we use a secondary strategy that\n * applies when the number of nodes in a bin exceeds a\n * threshold. These TreeBins use a balanced tree to hold nodes (a\n * specialized form of red-black trees), bounding search time to\n * O(log N). Each search step in a TreeBin is at least twice as\n * slow as in a regular list, but given that N cannot exceed\n * (1<<64) (before running out of addresses) this bounds search\n * steps, lock hold times, etc, to reasonable constants (roughly\n * 100 nodes inspected per operation worst case) so long as keys\n * are Comparable (which is very common -- String, Long, etc).\n * TreeBin nodes (TreeNodes) also maintain the same \"next\"\n * traversal pointers as regular nodes, so can be traversed in\n * iterators in the same way.\n *\n * The table is resized when occupancy exceeds a percentage\n * threshold (nominally, 0.75, but see below). Any thread\n * noticing an overfull bin may assist in resizing after the\n * initiating thread allocates and sets up the replacement array.\n * However, rather than stalling, these other threads may proceed\n * with insertions etc. The use of TreeBins shields us from the\n * worst case effects of overfilling while resizes are in\n * progress. Resizing proceeds by transferring bins, one by one,\n * from the table to the next table. However, threads claim small\n * blocks of indices to transfer (via field transferIndex) before\n * doing so, reducing contention. A generation stamp in field\n * sizeCtl ensures that resizings do not overlap. Because we are\n * using power-of-two expansion, the elements from each bin must\n * either stay at same index, or move with a power of two\n * offset. We eliminate unnecessary node creation by catching\n * cases where old nodes can be reused because their next fields\n * won't change. On average, only about one-sixth of them need\n * cloning when a table doubles. The nodes they replace will be\n * garbage collectible as soon as they are no longer referenced by\n * any reader thread that may be in the midst of concurrently\n * traversing table. Upon transfer, the old table bin contains\n * only a special forwarding node (with hash field \"MOVED\") that\n * contains the next table as its key. On encountering a\n * forwarding node, access and update operations restart, using\n * the new table.\n *\n * Each bin transfer requires its bin lock, which can stall\n * waiting for locks while resizing. However, because other\n * threads can join in and help resize rather than contend for\n * locks, average aggregate waits become shorter as resizing\n * progresses. The transfer operation must also ensure that all\n * accessible bins in both the old and new table are usable by any\n * traversal. This is arranged in part by proceeding from the\n * last bin (table.length - 1) up towards the first. Upon seeing\n * a forwarding node, traversals (see class Traverser) arrange to\n * move to the new table without revisiting nodes. To ensure that\n * no intervening nodes are skipped even when moved out of order,\n * a stack (see class TableStack) is created on first encounter of\n * a forwarding node during a traversal, to maintain its place if\n * later processing the current table. The need for these\n * save/restore mechanics is relatively rare, but when one\n * forwarding node is encountered, typically many more will be.\n * So Traversers use a simple caching scheme to avoid creating so\n * many new TableStack nodes. (Thanks to Peter Levart for\n * suggesting use of a stack here.)\n *\n * The traversal scheme also applies to partial traversals of\n * ranges of bins (via an alternate Traverser constructor)\n * to support partitioned aggregate operations. Also, read-only\n * operations give up if ever forwarded to a null table, which\n * provides support for shutdown-style clearing, which is also not\n * currently implemented.\n *\n * Lazy table initialization minimizes footprint until first use,\n * and also avoids resizings when the first operation is from a\n * putAll, constructor with map argument, or deserialization.\n * These cases attempt to override the initial capacity settings,\n * but harmlessly fail to take effect in cases of races.\n *\n * The element count is maintained using a specialization of\n * LongAdder. We need to incorporate a specialization rather than\n * just use a LongAdder in order to access implicit\n * contention-sensing that leads to creation of multiple\n * CounterCells. The counter mechanics avoid contention on\n * updates but can encounter cache thrashing if read too\n * frequently during concurrent access. To avoid reading so often,\n * resizing under contention is attempted only upon adding to a\n * bin already holding two or more nodes. Under uniform hash\n * distributions, the probability of this occurring at threshold\n * is around 13%, meaning that only about 1 in 8 puts check\n * threshold (and after resizing, many fewer do so).\n *\n * TreeBins use a special form of comparison for search and\n * related operations (which is the main reason we cannot use\n * existing collections such as TreeMaps). TreeBins contain\n * Comparable elements, but may contain others, as well as\n * elements that are Comparable but not necessarily Comparable for\n * the same T, so we cannot invoke compareTo among them. To handle\n * this, the tree is ordered primarily by hash value, then by\n * Comparable.compareTo order if applicable. On lookup at a node,\n * if elements are not comparable or compare as 0 then both left\n * and right children may need to be searched in the case of tied\n * hash values. (This corresponds to the full list search that\n * would be necessary if all elements were non-Comparable and had\n * tied hashes.) On insertion, to keep a total ordering (or as\n * close as is required here) across rebalancings, we compare\n * classes and identityHashCodes as tie-breakers. The red-black\n * balancing code is updated from pre-jdk-collections\n * (http://example.com)\n * based in turn on Cormen, Leiserson, and Rivest \"Introduction to\n * Algorithms\" (CLR).\n *\n * TreeBins also require an additional locking mechanism. While\n * list traversal is always possible by readers even during\n * updates, tree traversal is not, mainly because of tree-rotations\n * that may change the root node and/or its linkages. TreeBins\n * include a simple read-write lock mechanism parasitic on the\n * main bin-synchronization strategy: Structural adjustments\n * associated with an insertion or removal are already bin-locked\n * (and so cannot conflict with other writers) but must wait for\n * ongoing readers to finish. Since there can be only one such\n * waiter, we use a simple scheme using a single \"waiter\" field to\n * block writers. However, readers need never block. If the root\n * lock is held, they proceed along the slow traversal path (via\n * next-pointers) until the lock becomes available or the list is\n * exhausted, whichever comes first. These cases are not fast, but\n * maximize aggregate expected throughput.\n *\n * Maintaining API and serialization compatibility with previous\n * versions of this class introduces several oddities. Mainly: We\n * leave untouched but unused constructor arguments referring to\n * concurrencyLevel. We accept a loadFactor constructor argument,\n * but apply it only to initial table capacity (which is the only\n * time that we can guarantee to honor it.) We also declare an\n * unused \"Segment\" class that is instantiated in minimal form\n * only when serializing.\n *\n * Also, solely for compatibility with previous versions of this\n * class, it extends AbstractMap, even though all of its methods\n * are overridden, so it is just useless baggage.\n *\n * This file is organized to make things a little easier to follow\n * while reading than they might otherwise: First the main static\n * declarations and utilities, then fields, then main public\n * methods (with a few factorings of multiple public methods into\n * internal ones), then sizing methods, trees, traversers, and\n * bulk operations.\n */\n /**\n * The largest possible table capacity. This value must be\n * exactly 1<<30 to stay within Java array allocation and indexing\n * bounds for power of two table sizes, and is further required\n * because the top two bits of 32bit hash fields are used for\n * control purposes.\n */\n private static final int MAXIMUM_CAPACITY = 1 << 30;\n\n /**\n * The default initial table capacity. Must be a power of 2\n * (i.e., at least 1) and at most MAXIMUM_CAPACITY.\n */\n private static final int DEFAULT_CAPACITY = 16;\n\n /**\n * The largest possible (non-power of two) array size.\n * Needed by toArray and related methods.\n */\n static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;\n\n /**\n * The default concurrency level for this table. Unused but\n * defined for compatibility with previous versions of this class.\n */\n private static final int DEFAULT_CONCURRENCY_LEVEL = 16;\n\n /**\n * The load factor for this table. Overrides of this value in\n * constructors affect only the initial table capacity. The\n * actual floating point value isn't normally used -- it is\n * simpler to use expressions such as {@code n - (n >>> 2)} for\n * the associated resizing threshold.\n */\n private static final float LOAD_FACTOR = 0.75f;\n\n /**\n * The bin count threshold for using a tree rather than list for a\n * bin. Bins are converted to trees when adding an element to a\n * bin with at least this many nodes. The value must be greater\n * than 2, and should be at least 8 to mesh with assumptions in\n * tree removal about conversion back to plain bins upon\n * shrinkage.\n */\n static final int TREEIFY_THRESHOLD = 8;\n\n /**\n * The bin count threshold for untreeifying a (split) bin during a\n * resize operation. Should be less than TREEIFY_THRESHOLD, and at\n * most 6 to mesh with shrinkage detection under removal.\n */\n static final int UNTREEIFY_THRESHOLD = 6;\n\n /**\n * The smallest table capacity for which bins may be treeified.\n * (Otherwise the table is resized if too many nodes in a bin.)\n * The value should be at least 4 * TREEIFY_THRESHOLD to avoid\n * conflicts between resizing and treeification thresholds.\n */\n static final int MIN_TREEIFY_CAPACITY = 64;\n\n /**\n * Minimum number of rebinnings per transfer step. Ranges are\n * subdivided to allow multiple resizer threads. This value\n * serves as a lower bound to avoid resizers encountering\n * excessive memory contention. The value should be at least\n * DEFAULT_CAPACITY.\n */\n private static final int MIN_TRANSFER_STRIDE = 16;\n\n /**\n * The number of bits used for generation stamp in sizeCtl.\n * Must be at least 6 for 32bit arrays.\n */\n private static final int RESIZE_STAMP_BITS = 16;\n\n /**\n * The maximum number of threads that can help resize.\n * Must fit in 32 - RESIZE_STAMP_BITS bits.\n */\n private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;\n\n /**\n * The bit shift for recording size stamp in sizeCtl.\n */\n private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;\n\n /*\n * Encodings for Node hash fields. See above for explanation.\n */\n // hash for forwarding nodes\n static final int MOVED = -1;\n\n // hash for roots of trees\n static final int TREEBIN = -2;\n\n static final int RESERVED = -3;\n\n // usable bits of normal node hash\n static final int HASH_BITS = 0x7fffffff;\n\n /**\n * Number of CPUS, to place bounds on some sizings\n */\n static final int NCPU = Runtime.getRuntime().availableProcessors();\n\n /**\n * Serialized pseudo-fields, provided only for jdk7 compatibility.\n * @serialField segments Segment[]\n * The segments, each of which is a specialized hash table.\n * @serialField segmentMask int\n * Mask value for indexing into segments. The upper bits of a\n * key's hash code are used to choose the segment.\n * @serialField segmentShift int\n * Shift value for indexing within segments.\n */\n private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(\"segments\", Segment[].class), new ObjectStreamField(\"segmentMask\", Integer.TYPE), new ObjectStreamField(\"segmentShift\", Integer.TYPE) };\n\n /**\n * Key-value entry. This class is never exported out as a\n * user-mutable Map.Entry (i.e., one supporting setValue; see\n * MapEntry below), but can be used for read-only traversals used\n * in bulk tasks. Subclasses of Node with a negative hash field\n * are special, and contain null keys and values (but are never\n * exported). Otherwise, keys and vals are never null.\n */\n static class Node implements Map.Entry {\n\n final int hash;\n\n final K key;\n\n volatile V val;\n\n volatile Node next;\n\n Node(int hash, K key, V val) {\n this.hash = hash;\n this.key = key;\n this.val = val;\n }\n\n Node(int hash, K key, V val, Node next) {\n this(hash, key, val);\n this.next = next;\n }\n\n public final K getKey() {\n return key;\n }\n\n public final V getValue() {\n return val;\n }\n\n public final int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public final String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public final V setValue(V value) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean equals(Object o) {\n Object k, v, u;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == (u = val) || v.equals(u)));\n }\n\n /**\n * Virtualized support for map.get(); overridden in subclasses.\n */\n Node find(int h, Object k) {\n Node e = this;\n if (k != null) {\n do {\n K ek;\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n } while ((e = e.next) != null);\n }\n return null;\n }\n }\n\n /**\n * Spreads (XORs) higher bits of hash to lower and also forces top\n * bit to 0. Because the table uses power-of-two masking, sets of\n * hashes that vary only in bits above the current mask will\n * always collide. (Among known examples are sets of Float keys\n * holding consecutive whole numbers in small tables.) So we\n * apply a transform that spreads the impact of higher bits\n * downward. There is a tradeoff between speed, utility, and\n * quality of bit-spreading. Because many common sets of hashes\n * are already reasonably distributed (so don't benefit from\n * spreading), and because we use trees to handle large sets of\n * collisions in bins, we just XOR some shifted bits in the\n * cheapest possible way to reduce systematic lossage, as well as\n * to incorporate impact of the highest bits that would otherwise\n * never be used in index calculations because of table bounds.\n */\n static final int spread(int h) {\n return (h ^ (h >>> 16)) & HASH_BITS;\n }\n\n /**\n * Returns a power of two table size for the given desired capacity.\n * See Hackers Delight, sec 3.2\n */\n private static final int tableSizeFor(int c) {\n int n = -1 >>> Integer.numberOfLeadingZeros(c - 1);\n return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;\n }\n\n /**\n * Returns x's Class if it is of the form \"class C implements\n * Comparable\", else null.\n */\n static Class comparableClassFor(Object x) {\n if (x instanceof Comparable) {\n Class c;\n Type[] ts, as;\n ParameterizedType p;\n if (// bypass checks\n (c = x.getClass()) == String.class)\n return c;\n if ((ts = c.getGenericInterfaces()) != null) {\n for (Type t : ts) {\n if ((t instanceof ParameterizedType) && ((p = (ParameterizedType) t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && // type arg is c\n as[0] == c)\n return c;\n }\n }\n }\n return null;\n }\n\n /**\n * Returns k.compareTo(x) if x matches kc (k's screened comparable\n * class), else 0.\n */\n // for cast to Comparable\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n static int compareComparables(Class kc, Object k, Object x) {\n return (x == null || x.getClass() != kc ? 0 : ((Comparable) k).compareTo(x));\n }\n\n /* ---------------- Table element access -------------- */\n /*\n * Atomic access methods are used for table elements as well as\n * elements of in-progress next table while resizing. All uses of\n * the tab arguments must be null checked by callers. All callers\n * also paranoically precheck that tab's length is not zero (or an\n * equivalent check), thus ensuring that any index argument taking\n * the form of a hash value anded with (length - 1) is a valid\n * index. Note that, to be correct wrt arbitrary concurrency\n * errors by users, these checks must operate on local variables,\n * which accounts for some odd-looking inline assignments below.\n * Note that calls to setTabAt always occur within locked regions,\n * and so require only release ordering.\n */\n @SuppressWarnings(\"unchecked\")\n static final Node tabAt(Node[] tab, int i) {\n return (Node) U.getReferenceAcquire(tab, ((long) i << ASHIFT) + ABASE);\n }\n\n static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {\n return U.compareAndSetReference(tab, ((long) i << ASHIFT) + ABASE, c, v);\n }\n\n static final void setTabAt(Node[] tab, int i, Node v) {\n U.putReferenceRelease(tab, ((long) i << ASHIFT) + ABASE, v);\n }\n\n /**\n * The array of bins. Lazily initialized upon first insertion.\n * Size is always a power of two. Accessed directly by iterators.\n */\n transient volatile Node[] table;\n\n /**\n * The next table to use; non-null only while resizing.\n */\n private transient volatile Node[] nextTable;\n\n /**\n * Base counter value, used mainly when there is no contention,\n * but also as a fallback during table initialization\n * races. Updated via CAS.\n */\n private transient volatile long baseCount;\n\n /**\n * Table initialization and resizing control. When negative, the\n * table is being initialized or resized: -1 for initialization,\n * else -(1 + the number of active resizing threads). Otherwise,\n * when table is null, holds the initial table size to use upon\n * creation, or 0 for default. After initialization, holds the\n * next element count value upon which to resize the table.\n */\n private transient volatile int sizeCtl;\n\n /**\n * The next table index (plus one) to split while resizing.\n */\n private transient volatile int transferIndex;\n\n /**\n * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.\n */\n private transient volatile int cellsBusy;\n\n /**\n * Table of counter cells. When non-null, size is a power of 2.\n */\n private transient volatile CounterCell[] counterCells;\n\n // views\n private transient KeySetView keySet;\n\n private transient ValuesView values;\n\n private transient EntrySetView entrySet;\n\n /**\n * Creates a new, empty map with the default initial table size (16).\n */\n public ConcurrentHashMap() {\n }\n\n /**\n * Creates a new, empty map with an initial table size\n * accommodating the specified number of elements without the need\n * to dynamically resize.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n */\n public ConcurrentHashMap(int initialCapacity) {\n this(initialCapacity, LOAD_FACTOR, 1);\n }\n\n /**\n * Creates a new map with the same mappings as the given map.\n *\n * @param m the map\n */\n public ConcurrentHashMap(Map m) {\n this.sizeCtl = DEFAULT_CAPACITY;\n putAll(m);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}) and\n * initial table density ({@code loadFactor}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative or the load factor is nonpositive\n *\n * @since 1.6\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor) {\n this(initialCapacity, loadFactor, 1);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}), initial\n * table density ({@code loadFactor}), and number of concurrently\n * updating threads ({@code concurrencyLevel}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @param concurrencyLevel the estimated number of concurrently\n * updating threads. The implementation may use this value as\n * a sizing hint.\n * @throws IllegalArgumentException if the initial capacity is\n * negative or the load factor or concurrencyLevel are\n * nonpositive\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) {\n if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)\n throw new IllegalArgumentException();\n if (// Use at least as many bins\n initialCapacity < concurrencyLevel)\n // as estimated threads\n initialCapacity = concurrencyLevel;\n long size = (long) (1.0 + (long) initialCapacity / loadFactor);\n int cap = (size >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) size);\n this.sizeCtl = cap;\n }\n\n // Original (since JDK1.2) Map methods\n public int size() {\n long n = sumCount();\n return ((n < 0L) ? 0 : (n > (long) Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) n);\n }\n\n public boolean isEmpty() {\n // ignore transient negative values\n return sumCount() <= 0L;\n }\n\n /**\n * Returns the value to which the specified key is mapped,\n * or {@code null} if this map contains no mapping for the key.\n *\n *

More formally, if this map contains a mapping from a key\n * {@code k} to a value {@code v} such that {@code key.equals(k)},\n * then this method returns {@code v}; otherwise it returns\n * {@code null}. (There can be at most one such mapping.)\n *\n * @throws NullPointerException if the specified key is null\n */\n public V get(Object key) {\n Node[] tab;\n Node e, p;\n int n, eh;\n K ek;\n int h = spread(key.hashCode());\n if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) {\n if ((eh = e.hash) == h) {\n if ((ek = e.key) == key || (ek != null && key.equals(ek)))\n return e.val;\n } else if (eh < 0)\n return (p = e.find(h, key)) != null ? p.val : null;\n while ((e = e.next) != null) {\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek))))\n return e.val;\n }\n }\n return null;\n }\n\n /**\n * Tests if the specified object is a key in this table.\n *\n * @param key possible key\n * @return {@code true} if and only if the specified object\n * is a key in this table, as determined by the\n * {@code equals} method; {@code false} otherwise\n * @throws NullPointerException if the specified key is null\n */\n public boolean containsKey(Object key) {\n return get(key) != null;\n }\n\n /**\n * Returns {@code true} if this map maps one or more keys to the\n * specified value. Note: This method may require a full traversal\n * of the map, and is much slower than method {@code containsKey}.\n *\n * @param value value whose presence in this map is to be tested\n * @return {@code true} if this map maps one or more keys to the\n * specified value\n * @throws NullPointerException if the specified value is null\n */\n public boolean containsValue(Object value) {\n if (value == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V v;\n if ((v = p.val) == value || (v != null && value.equals(v)))\n return true;\n }\n }\n return false;\n }\n\n /**\n * Maps the specified key to the specified value in this table.\n * Neither the key nor the value can be null.\n *\n *

The value can be retrieved by calling the {@code get} method\n * with a key that is equal to the original key.\n *\n * @param key key with which the specified value is to be associated\n * @param value value to be associated with the specified key\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key or value is null\n */\n public V put(K key, V value) {\n return putVal(key, value, false);\n }\n\n /**\n * Implementation for put and putIfAbsent\n */\n final V putVal(K key, V value, boolean onlyIfAbsent) {\n if (key == null || value == null)\n throw new NullPointerException();\n int hash = spread(key.hashCode());\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {\n if (casTabAt(tab, i, null, new Node(hash, key, value)))\n // no lock when adding to empty bin\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n onlyIfAbsent && fh == hash && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n V oldVal = null;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n oldVal = e.val;\n if (!onlyIfAbsent)\n e.val = value;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n pred.next = new Node(hash, key, value);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n Node p;\n binCount = 2;\n if ((p = ((TreeBin) f).putTreeVal(hash, key, value)) != null) {\n oldVal = p.val;\n if (!onlyIfAbsent)\n p.val = value;\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (oldVal != null)\n return oldVal;\n break;\n }\n }\n }\n addCount(1L, binCount);\n return null;\n }\n\n /**\n * Copies all of the mappings from the specified map to this one.\n * These mappings replace any mappings that this map had for any of the\n * keys currently in the specified map.\n *\n * @param m mappings to be stored in this map\n */\n public void putAll(Map m) {\n tryPresize(m.size());\n for (Map.Entry e : m.entrySet()) putVal(e.getKey(), e.getValue(), false);\n }\n\n /**\n * Removes the key (and its corresponding value) from this map.\n * This method does nothing if the key is not in the map.\n *\n * @param key the key that needs to be removed\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key is null\n */\n public V remove(Object key) {\n return replaceNode(key, null, null);\n }\n\n /**\n * Implementation for the four public remove/replace methods:\n * Replaces node value with v, conditional upon match of cv if\n * non-null. If resulting value is null, delete.\n */\n final V replaceNode(Object key, V value, Object cv) {\n int hash = spread(key.hashCode());\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0 || (f = tabAt(tab, i = (n - 1) & hash)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n V oldVal = null;\n boolean validated = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n validated = true;\n for (Node e = f, pred = null; ; ) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n V ev = e.val;\n if (cv == null || cv == ev || (ev != null && cv.equals(ev))) {\n oldVal = ev;\n if (value != null)\n e.val = value;\n else if (pred != null)\n pred.next = e.next;\n else\n setTabAt(tab, i, e.next);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n validated = true;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(hash, key, null)) != null) {\n V pv = p.val;\n if (cv == null || cv == pv || (pv != null && cv.equals(pv))) {\n oldVal = pv;\n if (value != null)\n p.val = value;\n else if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (validated) {\n if (oldVal != null) {\n if (value == null)\n addCount(-1L, -1);\n return oldVal;\n }\n break;\n }\n }\n }\n return null;\n }\n\n /**\n * Removes all of the mappings from this map.\n */\n public void clear() {\n // negative number of deletions\n long delta = 0L;\n int i = 0;\n Node[] tab = table;\n while (tab != null && i < tab.length) {\n int fh;\n Node f = tabAt(tab, i);\n if (f == null)\n ++i;\n else if ((fh = f.hash) == MOVED) {\n tab = helpTransfer(tab, f);\n // restart\n i = 0;\n } else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node p = (fh >= 0 ? f : (f instanceof TreeBin) ? ((TreeBin) f).first : null);\n while (p != null) {\n --delta;\n p = p.next;\n }\n setTabAt(tab, i++, null);\n }\n }\n }\n }\n if (delta != 0L)\n addCount(delta, -1);\n }\n\n /**\n * Returns a {@link Set} view of the keys contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from this map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations. It does not support the {@code add} or\n * {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public KeySetView keySet() {\n KeySetView ks;\n if ((ks = keySet) != null)\n return ks;\n return keySet = new KeySetView(this, null);\n }\n\n /**\n * Returns a {@link Collection} view of the values contained in this map.\n * The collection is backed by the map, so changes to the map are\n * reflected in the collection, and vice-versa. The collection\n * supports element removal, which removes the corresponding\n * mapping from this map, via the {@code Iterator.remove},\n * {@code Collection.remove}, {@code removeAll},\n * {@code retainAll}, and {@code clear} operations. It does not\n * support the {@code add} or {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}\n * and {@link Spliterator#NONNULL}.\n *\n * @return the collection view\n */\n public Collection values() {\n ValuesView vs;\n if ((vs = values) != null)\n return vs;\n return values = new ValuesView(this);\n }\n\n /**\n * Returns a {@link Set} view of the mappings contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from the map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public Set> entrySet() {\n EntrySetView es;\n if ((es = entrySet) != null)\n return es;\n return entrySet = new EntrySetView(this);\n }\n\n /**\n * Returns the hash code value for this {@link Map}, i.e.,\n * the sum of, for each key-value pair in the map,\n * {@code key.hashCode() ^ value.hashCode()}.\n *\n * @return the hash code value for this map\n */\n public int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) h += p.key.hashCode() ^ p.val.hashCode();\n }\n return h;\n }\n\n /**\n * Returns a string representation of this map. The string\n * representation consists of a list of key-value mappings (in no\n * particular order) enclosed in braces (\"{@code {}}\"). Adjacent\n * mappings are separated by the characters {@code \", \"} (comma\n * and space). Each key-value mapping is rendered as the key\n * followed by an equals sign (\"{@code =}\") followed by the\n * associated value.\n *\n * @return a string representation of this map\n */\n public String toString() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n StringBuilder sb = new StringBuilder();\n sb.append('{');\n Node p;\n if ((p = it.advance()) != null) {\n for (; ; ) {\n K k = p.key;\n V v = p.val;\n sb.append(k == this ? \"(this Map)\" : k);\n sb.append('=');\n sb.append(v == this ? \"(this Map)\" : v);\n if ((p = it.advance()) == null)\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append('}').toString();\n }\n\n /**\n * Compares the specified object with this map for equality.\n * Returns {@code true} if the given object is a map with the same\n * mappings as this map. This operation may return misleading\n * results if either map is concurrently modified during execution\n * of this method.\n *\n * @param o object to be compared for equality with this map\n * @return {@code true} if the specified object is equal to this map\n */\n public boolean equals(Object o) {\n if (o != this) {\n if (!(o instanceof Map))\n return false;\n Map m = (Map) o;\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n for (Node p; (p = it.advance()) != null; ) {\n V val = p.val;\n Object v = m.get(p.key);\n if (v == null || (v != val && !v.equals(val)))\n return false;\n }\n for (Map.Entry e : m.entrySet()) {\n Object mk, mv, v;\n if ((mk = e.getKey()) == null || (mv = e.getValue()) == null || (v = get(mk)) == null || (mv != v && !mv.equals(v)))\n return false;\n }\n }\n return true;\n }\n\n /**\n * Stripped-down version of helper class used in previous version,\n * declared for the sake of serialization compatibility.\n */\n static class Segment extends ReentrantLock implements Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n final float loadFactor;\n\n Segment(float lf) {\n this.loadFactor = lf;\n }\n }\n\n /**\n * Saves this map to a stream (that is, serializes it).\n *\n * @param s the stream\n * @throws java.io.IOException if an I/O error occurs\n * @serialData\n * the serialized fields, followed by the key (Object) and value\n * (Object) for each key-value mapping, followed by a null pair.\n * The key-value mappings are emitted in no particular order.\n */\n private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {\n // For serialization compatibility\n // Emulate segment calculation from previous version of this class\n int sshift = 0;\n int ssize = 1;\n while (ssize < DEFAULT_CONCURRENCY_LEVEL) {\n ++sshift;\n ssize <<= 1;\n }\n int segmentShift = 32 - sshift;\n int segmentMask = ssize - 1;\n @SuppressWarnings(\"unchecked\")\n Segment[] segments = (Segment[]) new Segment[DEFAULT_CONCURRENCY_LEVEL];\n for (int i = 0; i < segments.length; ++i) segments[i] = new Segment(LOAD_FACTOR);\n java.io.ObjectOutputStream.PutField streamFields = s.putFields();\n streamFields.put(\"segments\", segments);\n streamFields.put(\"segmentShift\", segmentShift);\n streamFields.put(\"segmentMask\", segmentMask);\n s.writeFields();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n s.writeObject(p.key);\n s.writeObject(p.val);\n }\n }\n s.writeObject(null);\n s.writeObject(null);\n }\n\n /**\n * Reconstitutes this map from a stream (that is, deserializes it).\n * @param s the stream\n * @throws ClassNotFoundException if the class of a serialized object\n * could not be found\n * @throws java.io.IOException if an I/O error occurs\n */\n private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {\n /*\n * To improve performance in typical cases, we create nodes\n * while reading, then place in table once size is known.\n * However, we must also validate uniqueness and deal with\n * overpopulated bins while doing so, which requires\n * specialized versions of putVal mechanics.\n */\n // force exclusion for table construction\n sizeCtl = -1;\n s.defaultReadObject();\n long size = 0L;\n Node p = null;\n for (; ; ) {\n @SuppressWarnings(\"unchecked\")\n K k = (K) s.readObject();\n @SuppressWarnings(\"unchecked\")\n V v = (V) s.readObject();\n if (k != null && v != null) {\n p = new Node(spread(k.hashCode()), k, v, p);\n ++size;\n } else\n break;\n }\n if (size == 0L)\n sizeCtl = 0;\n else {\n long ts = (long) (1.0 + size / LOAD_FACTOR);\n int n = (ts >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) ts);\n @SuppressWarnings(\"unchecked\")\n Node[] tab = (Node[]) new Node[n];\n int mask = n - 1;\n long added = 0L;\n while (p != null) {\n boolean insertAtFront;\n Node next = p.next, first;\n int h = p.hash, j = h & mask;\n if ((first = tabAt(tab, j)) == null)\n insertAtFront = true;\n else {\n K k = p.key;\n if (first.hash < 0) {\n TreeBin t = (TreeBin) first;\n if (t.putTreeVal(h, k, p.val) == null)\n ++added;\n insertAtFront = false;\n } else {\n int binCount = 0;\n insertAtFront = true;\n Node q;\n K qk;\n for (q = first; q != null; q = q.next) {\n if (q.hash == h && ((qk = q.key) == k || (qk != null && k.equals(qk)))) {\n insertAtFront = false;\n break;\n }\n ++binCount;\n }\n if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {\n insertAtFront = false;\n ++added;\n p.next = first;\n TreeNode hd = null, tl = null;\n for (q = p; q != null; q = q.next) {\n TreeNode t = new TreeNode(q.hash, q.key, q.val, null, null);\n if ((t.prev = tl) == null)\n hd = t;\n else\n tl.next = t;\n tl = t;\n }\n setTabAt(tab, j, new TreeBin(hd));\n }\n }\n }\n if (insertAtFront) {\n ++added;\n p.next = first;\n setTabAt(tab, j, p);\n }\n p = next;\n }\n table = tab;\n sizeCtl = n - (n >>> 2);\n baseCount = added;\n }\n }\n\n // ConcurrentMap methods\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n ", "post_mask_code": "\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object key, Object value) {\n if (key == null)\n throw new NullPointerException();\n return value != null && replaceNode(key, null, value) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if any of the arguments are null\n */\n public boolean replace(K key, V oldValue, V newValue) {\n if (key == null || oldValue == null || newValue == null)\n throw new NullPointerException();\n return replaceNode(key, newValue, oldValue) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V replace(K key, V value) {\n if (key == null || value == null)\n throw new NullPointerException();\n return replaceNode(key, value, null);\n }\n\n // Overrides of JDK8+ Map extension method defaults\n /**\n * Returns the value to which the specified key is mapped, or the\n * given default value if this map contains no mapping for the\n * key.\n *\n * @param key the key whose associated value is to be returned\n * @param defaultValue the value to return if this map contains\n * no mapping for the given key\n * @return the mapping for the key, if present; else the default value\n * @throws NullPointerException if the specified key is null\n */\n public V getOrDefault(Object key, V defaultValue) {\n V v;\n return (v = get(key)) == null ? defaultValue : v;\n }\n\n public void forEach(BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n action.accept(p.key, p.val);\n }\n }\n }\n\n public void replaceAll(BiFunction function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V oldValue = p.val;\n for (K key = p.key; ; ) {\n V newValue = function.apply(key, oldValue);\n if (newValue == null)\n throw new NullPointerException();\n if (replaceNode(key, newValue, oldValue) != null || (oldValue = get(key)) == null)\n break;\n }\n }\n }\n }\n\n boolean removeEntryIf(Predicate> function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n Map.Entry e = new AbstractMap.SimpleImmutableEntry<>(k, v);\n if (function.test(e) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n boolean removeValueIf(Predicate function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n if (function.test(v) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n /**\n * If the specified key is not already associated with a value,\n * attempts to compute its value using the given mapping function\n * and enters it into this map unless {@code null}. The entire\n * method invocation is performed atomically. The supplied\n * function is invoked exactly once per invocation of this method\n * if the key is absent, else not at all. Some attempted update\n * operations on this map by other threads may be blocked while\n * computation is in progress, so the computation should be short\n * and simple.\n *\n *

The mapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param mappingFunction the function to compute a value\n * @return the current (existing or computed) value associated with\n * the specified key, or null if the computed value is null\n * @throws NullPointerException if the specified key or mappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the mappingFunction does so,\n * in which case the mapping is left unestablished\n */\n public V computeIfAbsent(K key, Function mappingFunction) {\n if (key == null || mappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = mappingFunction.apply(key)) != null)\n node = new Node(h, key, val);\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n fh == h && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n boolean added = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = e.val;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n if ((val = mappingFunction.apply(key)) != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n added = true;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null)\n val = p.val;\n else if ((val = mappingFunction.apply(key)) != null) {\n added = true;\n t.putTreeVal(h, key, val);\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (!added)\n return val;\n break;\n }\n }\n }\n if (val != null)\n addCount(1L, binCount);\n return val;\n }\n\n /**\n * If the value for the specified key is present, attempts to\n * compute a new mapping given the key and its current mapped\n * value. The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method if the key is present, else not at all. Some\n * attempted update operations on this map by other threads may be\n * blocked while computation is in progress, so the computation\n * should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which a value may be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V computeIfPresent(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null) {\n val = remappingFunction.apply(key, p.val);\n if (val != null)\n p.val = val;\n else {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0)\n break;\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * Attempts to compute a mapping for the specified key and its\n * current mapped value (or {@code null} if there is no current\n * mapping). The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method. Some attempted update operations on this map by\n * other threads may be blocked while computation is in progress,\n * so the computation should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V compute(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = remappingFunction.apply(key, null)) != null) {\n delta = 1;\n node = new Node(h, key, val);\n }\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n val = remappingFunction.apply(key, null);\n if (val != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n delta = 1;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 1;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null)\n p = r.findTreeNode(h, key, null);\n else\n p = null;\n V pv = (p == null) ? null : p.val;\n val = remappingFunction.apply(key, pv);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * If the specified key is not already associated with a\n * (non-null) value, associates it with the given value.\n * Otherwise, replaces the value with the results of the given\n * remapping function, or removes if {@code null}. The entire\n * method invocation is performed atomically. Some attempted\n * update operations on this map by other threads may be blocked\n * while computation is in progress, so the computation should be\n * short and simple, and must not attempt to update any other\n * mappings of this Map.\n *\n * @param key key with which the specified value is to be associated\n * @param value the value to use if absent\n * @param remappingFunction the function to recompute a value if present\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or the\n * remappingFunction is null\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V merge(K key, V value, BiFunction remappingFunction) {\n if (key == null || value == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n if (casTabAt(tab, i, null, new Node(h, key, value))) {\n delta = 1;\n val = value;\n break;\n }\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(e.val, value);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n delta = 1;\n val = value;\n pred.next = new Node(h, key, val);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r = t.root;\n TreeNode p = (r == null) ? null : r.findTreeNode(h, key, null);\n val = (p == null) ? value : remappingFunction.apply(p.val, value);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n // Hashtable legacy methods\n /**\n * Tests if some key maps into the specified value in this table.\n *\n *

Note that this method is identical in functionality to\n * {@link #containsValue(Object)}, and exists solely to ensure\n * full compatibility with class {@link java.util.Hashtable},\n * which supported this method prior to introduction of the\n * Java Collections Framework.\n *\n * @param value a value to search for\n * @return {@code true} if and only if some key maps to the\n * {@code value} argument in this table as\n * determined by the {@code equals} method;\n * {@code false} otherwise\n * @throws NullPointerException if the specified value is null\n */\n public boolean contains(Object value) {\n return containsValue(value);\n }\n\n /**\n * Returns an enumeration of the keys in this table.\n *\n * @return an enumeration of the keys in this table\n * @see #keySet()\n */\n public Enumeration keys() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, this);\n }\n\n /**\n * Returns an enumeration of the values in this table.\n *\n * @return an enumeration of the values in this table\n * @see #values()\n */\n public Enumeration elements() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, this);\n }\n\n // ConcurrentHashMap-only methods\n /**\n * Returns the number of mappings. This method should be used\n * instead of {@link #size} because a ConcurrentHashMap may\n * contain more mappings than can be represented as an int. The\n * value returned is an estimate; the actual count may differ if\n * there are concurrent insertions or removals.\n *\n * @return the number of mappings\n * @since 1.8\n */\n public long mappingCount() {\n long n = sumCount();\n // ignore transient negative values\n return (n < 0L) ? 0L : n;\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param the element type of the returned set\n * @return the new set\n * @since 1.8\n */\n public static KeySetView newKeySet() {\n return new KeySetView(new ConcurrentHashMap(), Boolean.TRUE);\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @param the element type of the returned set\n * @return the new set\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n * @since 1.8\n */\n public static KeySetView newKeySet(int initialCapacity) {\n return new KeySetView(new ConcurrentHashMap(initialCapacity), Boolean.TRUE);\n }\n\n /**\n * Returns a {@link Set} view of the keys in this map, using the\n * given common mapped value for any additions (i.e., {@link\n * Collection#add} and {@link Collection#addAll(Collection)}).\n * This is of course only appropriate if it is acceptable to use\n * the same value for all additions from this view.\n *\n * @param mappedValue the mapped value to use for any additions\n * @return the set view\n * @throws NullPointerException if the mappedValue is null\n */\n public KeySetView keySet(V mappedValue) {\n if (mappedValue == null)\n throw new NullPointerException();\n return new KeySetView(this, mappedValue);\n }\n\n /**\n * A node inserted at head of bins during transfer operations.\n */\n static final class ForwardingNode extends Node {\n\n final Node[] nextTable;\n\n ForwardingNode(Node[] tab) {\n super(MOVED, null, null);\n this.nextTable = tab;\n }\n\n Node find(int h, Object k) {\n // loop to avoid arbitrarily deep recursion on forwarding nodes\n outer: for (Node[] tab = nextTable; ; ) {\n Node e;\n int n;\n if (k == null || tab == null || (n = tab.length) == 0 || (e = tabAt(tab, (n - 1) & h)) == null)\n return null;\n for (; ; ) {\n int eh;\n K ek;\n if ((eh = e.hash) == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n if (eh < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n continue outer;\n } else\n return e.find(h, k);\n }\n if ((e = e.next) == null)\n return null;\n }\n }\n }\n }\n\n /**\n * A place-holder node used in computeIfAbsent and compute.\n */\n static final class ReservationNode extends Node {\n\n ReservationNode() {\n super(RESERVED, null, null);\n }\n\n Node find(int h, Object k) {\n return null;\n }\n }\n\n /* ---------------- Table Initialization and Resizing -------------- */\n /**\n * Returns the stamp bits for resizing a table of size n.\n * Must be negative when shifted left by RESIZE_STAMP_SHIFT.\n */\n static final int resizeStamp(int n) {\n return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));\n }\n\n /**\n * Initializes table, using the size recorded in sizeCtl.\n */\n private final Node[] initTable() {\n Node[] tab;\n int sc;\n while ((tab = table) == null || tab.length == 0) {\n if ((sc = sizeCtl) < 0)\n // lost initialization race; just spin\n Thread.yield();\n else if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if ((tab = table) == null || tab.length == 0) {\n int n = (sc > 0) ? sc : DEFAULT_CAPACITY;\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = tab = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n break;\n }\n }\n return tab;\n }\n\n /**\n * Adds to count, and if table is too small and not already\n * resizing, initiates transfer. If already resizing, helps\n * perform transfer if work is available. Rechecks occupancy\n * after a transfer to see if another resize is already needed\n * because resizings are lagging additions.\n *\n * @param x the count to add\n * @param check if <0, don't check resize, if <= 1 only check if uncontended\n */\n private final void addCount(long x, int check) {\n CounterCell[] cs;\n long b, s;\n if ((cs = counterCells) != null || !U.compareAndSetLong(this, BASECOUNT, b = baseCount, s = b + x)) {\n CounterCell c;\n long v;\n int m;\n boolean uncontended = true;\n if (cs == null || (m = cs.length - 1) < 0 || (c = cs[ThreadLocalRandom.getProbe() & m]) == null || !(uncontended = U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))) {\n fullAddCount(x, uncontended);\n return;\n }\n if (check <= 1)\n return;\n s = sumCount();\n }\n if (check >= 0) {\n Node[] tab, nt;\n int n, sc;\n while (s >= (long) (sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) {\n int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT;\n if (sc < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || (nt = nextTable) == null || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1))\n transfer(tab, nt);\n } else if (U.compareAndSetInt(this, SIZECTL, sc, rs + 2))\n transfer(tab, null);\n s = sumCount();\n }\n }\n }\n\n /**\n * Helps transfer if a resize is in progress.\n */\n final Node[] helpTransfer(Node[] tab, Node f) {\n Node[] nextTab;\n int sc;\n if (tab != null && (f instanceof ForwardingNode) && (nextTab = ((ForwardingNode) f).nextTable) != null) {\n int rs = resizeStamp(tab.length) << RESIZE_STAMP_SHIFT;\n while (nextTab == nextTable && table == tab && (sc = sizeCtl) < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1)) {\n transfer(tab, nextTab);\n break;\n }\n }\n return nextTab;\n }\n return table;\n }\n\n /**\n * Tries to presize table to accommodate the given number of elements.\n *\n * @param size number of elements (doesn't need to be perfectly accurate)\n */\n private final void tryPresize(int size) {\n int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(size + (size >>> 1) + 1);\n int sc;\n while ((sc = sizeCtl) >= 0) {\n Node[] tab = table;\n int n;\n if (tab == null || (n = tab.length) == 0) {\n n = (sc > c) ? sc : c;\n if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if (table == tab) {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n }\n } else if (c <= sc || n >= MAXIMUM_CAPACITY)\n break;\n else if (tab == table) {\n int rs = resizeStamp(n);\n if (U.compareAndSetInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2))\n transfer(tab, null);\n }\n }\n }\n\n /**\n * Moves and/or copies the nodes in each bin to new table. See\n * above for explanation.\n */\n private final void transfer(Node[] tab, Node[] nextTab) {\n int n = tab.length, stride;\n if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)\n // subdivide range\n stride = MIN_TRANSFER_STRIDE;\n if (nextTab == null) {\n // initiating\n try {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n << 1];\n nextTab = nt;\n } catch (Throwable ex) {\n // try to cope with OOME\n sizeCtl = Integer.MAX_VALUE;\n return;\n }\n nextTable = nextTab;\n transferIndex = n;\n }\n int nextn = nextTab.length;\n ForwardingNode fwd = new ForwardingNode(nextTab);\n boolean advance = true;\n // to ensure sweep before committing nextTab\n boolean finishing = false;\n for (int i = 0, bound = 0; ; ) {\n Node f;\n int fh;\n while (advance) {\n int nextIndex, nextBound;\n if (--i >= bound || finishing)\n advance = false;\n else if ((nextIndex = transferIndex) <= 0) {\n i = -1;\n advance = false;\n } else if (U.compareAndSetInt(this, TRANSFERINDEX, nextIndex, nextBound = (nextIndex > stride ? nextIndex - stride : 0))) {\n bound = nextBound;\n i = nextIndex - 1;\n advance = false;\n }\n }\n if (i < 0 || i >= n || i + n >= nextn) {\n int sc;\n if (finishing) {\n nextTable = null;\n table = nextTab;\n sizeCtl = (n << 1) - (n >>> 1);\n return;\n }\n if (U.compareAndSetInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {\n if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)\n return;\n finishing = advance = true;\n // recheck before commit\n i = n;\n }\n } else if ((f = tabAt(tab, i)) == null)\n advance = casTabAt(tab, i, null, fwd);\n else if ((fh = f.hash) == MOVED)\n // already processed\n advance = true;\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node ln, hn;\n if (fh >= 0) {\n int runBit = fh & n;\n Node lastRun = f;\n for (Node p = f.next; p != null; p = p.next) {\n int b = p.hash & n;\n if (b != runBit) {\n runBit = b;\n lastRun = p;\n }\n }\n if (runBit == 0) {\n ln = lastRun;\n hn = null;\n } else {\n hn = lastRun;\n ln = null;\n }\n for (Node p = f; p != lastRun; p = p.next) {\n int ph = p.hash;\n K pk = p.key;\n V pv = p.val;\n if ((ph & n) == 0)\n ln = new Node(ph, pk, pv, ln);\n else\n hn = new Node(ph, pk, pv, hn);\n }\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof TreeBin) {\n TreeBin t = (TreeBin) f;\n TreeNode lo = null, loTail = null;\n TreeNode hi = null, hiTail = null;\n int lc = 0, hc = 0;\n for (Node e = t.first; e != null; e = e.next) {\n int h = e.hash;\n TreeNode p = new TreeNode(h, e.key, e.val, null, null);\n if ((h & n) == 0) {\n if ((p.prev = loTail) == null)\n lo = p;\n else\n loTail.next = p;\n loTail = p;\n ++lc;\n } else {\n if ((p.prev = hiTail) == null)\n hi = p;\n else\n hiTail.next = p;\n hiTail = p;\n ++hc;\n }\n }\n ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : (hc != 0) ? new TreeBin(lo) : t;\n hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : (lc != 0) ? new TreeBin(hi) : t;\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n }\n }\n }\n\n /**\n * A padded cell for distributing counts. Adapted from LongAdder\n * and Striped64. See their internal docs for explanation.\n */\n @jdk.internal.vm.annotation.Contended\n static final class CounterCell {\n\n volatile long value;\n\n CounterCell(long x) {\n value = x;\n }\n }\n\n final long sumCount() {\n CounterCell[] cs = counterCells;\n long sum = baseCount;\n if (cs != null) {\n for (CounterCell c : cs) if (c != null)\n sum += c.value;\n }\n return sum;\n }\n\n // See LongAdder version for explanation\n private final void fullAddCount(long x, boolean wasUncontended) {\n int h;\n if ((h = ThreadLocalRandom.getProbe()) == 0) {\n // force initialization\n ThreadLocalRandom.localInit();\n h = ThreadLocalRandom.getProbe();\n wasUncontended = true;\n }\n // True if last slot nonempty\n boolean collide = false;\n for (; ; ) {\n CounterCell[] cs;\n CounterCell c;\n int n;\n long v;\n if ((cs = counterCells) != null && (n = cs.length) > 0) {\n if ((c = cs[(n - 1) & h]) == null) {\n if (cellsBusy == 0) {\n // Try to attach new Cell\n // Optimistic create\n CounterCell r = new CounterCell(x);\n if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean created = false;\n try {\n // Recheck under lock\n CounterCell[] rs;\n int m, j;\n if ((rs = counterCells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) {\n rs[j] = r;\n created = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (created)\n break;\n // Slot is now non-empty\n continue;\n }\n }\n collide = false;\n } else if (// CAS already known to fail\n !wasUncontended)\n // Continue after rehash\n wasUncontended = true;\n else if (U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))\n break;\n else if (counterCells != cs || n >= NCPU)\n // At max size or stale\n collide = false;\n else if (!collide)\n collide = true;\n else if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n try {\n if (// Expand table unless stale\n counterCells == cs)\n counterCells = Arrays.copyOf(cs, n << 1);\n } finally {\n cellsBusy = 0;\n }\n collide = false;\n // Retry with expanded table\n continue;\n }\n h = ThreadLocalRandom.advanceProbe(h);\n } else if (cellsBusy == 0 && counterCells == cs && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean init = false;\n try {\n // Initialize table\n if (counterCells == cs) {\n CounterCell[] rs = new CounterCell[2];\n rs[h & 1] = new CounterCell(x);\n counterCells = rs;\n init = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (init)\n break;\n } else if (U.compareAndSetLong(this, BASECOUNT, v = baseCount, v + x))\n // Fall back on using base\n break;\n }\n }\n\n /**\n * Replaces all linked nodes in bin at given index unless table is\n * too small, in which case resizes instead.\n */\n private final void treeifyBin(Node[] tab, int index) {\n Node b;\n int n;\n if (tab != null) {\n if ((n = tab.length) < MIN_TREEIFY_CAPACITY)\n tryPresize(n << 1);\n else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {\n synchronized (b) {\n if (tabAt(tab, index) == b) {\n TreeNode hd = null, tl = null;\n for (Node e = b; e != null; e = e.next) {\n TreeNode p = new TreeNode(e.hash, e.key, e.val, null, null);\n if ((p.prev = tl) == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n setTabAt(tab, index, new TreeBin(hd));\n }\n }\n }\n }\n }\n\n /**\n * Returns a list of non-TreeNodes replacing those in given list.\n */\n static Node untreeify(Node b) {\n Node hd = null, tl = null;\n for (Node q = b; q != null; q = q.next) {\n Node p = new Node(q.hash, q.key, q.val);\n if (tl == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n return hd;\n }\n\n /**\n * Nodes for use in TreeBins.\n */\n static final class TreeNode extends Node {\n\n // red-black tree links\n TreeNode parent;\n\n TreeNode left;\n\n TreeNode right;\n\n // needed to unlink next upon deletion\n TreeNode prev;\n\n boolean red;\n\n TreeNode(int hash, K key, V val, Node next, TreeNode parent) {\n super(hash, key, val, next);\n this.parent = parent;\n }\n\n Node find(int h, Object k) {\n return findTreeNode(h, k, null);\n }\n\n /**\n * Returns the TreeNode (or null if not found) for the given key\n * starting at given root.\n */\n final TreeNode findTreeNode(int h, Object k, Class kc) {\n if (k != null) {\n TreeNode p = this;\n do {\n int ph, dir;\n K pk;\n TreeNode q;\n TreeNode pl = p.left, pr = p.right;\n if ((ph = p.hash) > h)\n p = pl;\n else if (ph < h)\n p = pr;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if (pl == null)\n p = pr;\n else if (pr == null)\n p = pl;\n else if ((kc != null || (kc = comparableClassFor(k)) != null) && (dir = compareComparables(kc, k, pk)) != 0)\n p = (dir < 0) ? pl : pr;\n else if ((q = pr.findTreeNode(h, k, kc)) != null)\n return q;\n else\n p = pl;\n } while (p != null);\n }\n return null;\n }\n }\n\n /**\n * TreeNodes used at the heads of bins. TreeBins do not hold user\n * keys or values, but instead point to list of TreeNodes and\n * their root. They also maintain a parasitic read-write lock\n * forcing writers (who hold bin lock) to wait for readers (who do\n * not) to complete before tree restructuring operations.\n */\n static final class TreeBin extends Node {\n\n TreeNode root;\n\n volatile TreeNode first;\n\n volatile Thread waiter;\n\n volatile int lockState;\n\n // values for lockState\n // set while holding write lock\n static final int WRITER = 1;\n\n // set when waiting for write lock\n static final int WAITER = 2;\n\n // increment value for setting read lock\n static final int READER = 4;\n\n /**\n * Tie-breaking utility for ordering insertions when equal\n * hashCodes and non-comparable. We don't require a total\n * order, just a consistent insertion rule to maintain\n * equivalence across rebalancings. Tie-breaking further than\n * necessary simplifies testing a bit.\n */\n static int tieBreakOrder(Object a, Object b) {\n int d;\n if (a == null || b == null || (d = a.getClass().getName().compareTo(b.getClass().getName())) == 0)\n d = (System.identityHashCode(a) <= System.identityHashCode(b) ? -1 : 1);\n return d;\n }\n\n /**\n * Creates bin with initial set of nodes headed by b.\n */\n TreeBin(TreeNode b) {\n super(TREEBIN, null, null);\n this.first = b;\n TreeNode r = null;\n for (TreeNode x = b, next; x != null; x = next) {\n next = (TreeNode) x.next;\n x.left = x.right = null;\n if (r == null) {\n x.parent = null;\n x.red = false;\n r = x;\n } else {\n K k = x.key;\n int h = x.hash;\n Class kc = null;\n for (TreeNode p = r; ; ) {\n int dir, ph;\n K pk = p.key;\n if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0)\n dir = tieBreakOrder(k, pk);\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n x.parent = xp;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n r = balanceInsertion(r, x);\n break;\n }\n }\n }\n }\n this.root = r;\n assert checkInvariants(root);\n }\n\n /**\n * Acquires write lock for tree restructuring.\n */\n private final void lockRoot() {\n if (!U.compareAndSetInt(this, LOCKSTATE, 0, WRITER))\n // offload to separate method\n contendedLock();\n }\n\n /**\n * Releases write lock for tree restructuring.\n */\n private final void unlockRoot() {\n lockState = 0;\n }\n\n /**\n * Possibly blocks awaiting root lock.\n */\n private final void contendedLock() {\n boolean waiting = false;\n for (int s; ; ) {\n if (((s = lockState) & ~WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, WRITER)) {\n if (waiting)\n waiter = null;\n return;\n }\n } else if ((s & WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, s | WAITER)) {\n waiting = true;\n waiter = Thread.currentThread();\n }\n } else if (waiting)\n LockSupport.park(this);\n }\n }\n\n /**\n * Returns matching node or null if none. Tries to search\n * using tree comparisons from root, but continues linear\n * search when lock not available.\n */\n final Node find(int h, Object k) {\n if (k != null) {\n for (Node e = first; e != null; ) {\n int s;\n K ek;\n if (((s = lockState) & (WAITER | WRITER)) != 0) {\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n e = e.next;\n } else if (U.compareAndSetInt(this, LOCKSTATE, s, s + READER)) {\n TreeNode r, p;\n try {\n p = ((r = root) == null ? null : r.findTreeNode(h, k, null));\n } finally {\n Thread w;\n if (U.getAndAddInt(this, LOCKSTATE, -READER) == (READER | WAITER) && (w = waiter) != null)\n LockSupport.unpark(w);\n }\n return p;\n }\n }\n }\n return null;\n }\n\n /**\n * Finds or adds a node.\n * @return null if added\n */\n final TreeNode putTreeVal(int h, K k, V v) {\n Class kc = null;\n boolean searched = false;\n for (TreeNode p = root; ; ) {\n int dir, ph;\n K pk;\n if (p == null) {\n first = root = new TreeNode(h, k, v, null, null);\n break;\n } else if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) {\n if (!searched) {\n TreeNode q, ch;\n searched = true;\n if (((ch = p.left) != null && (q = ch.findTreeNode(h, k, kc)) != null) || ((ch = p.right) != null && (q = ch.findTreeNode(h, k, kc)) != null))\n return q;\n }\n dir = tieBreakOrder(k, pk);\n }\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n TreeNode x, f = first;\n first = x = new TreeNode(h, k, v, f, xp);\n if (f != null)\n f.prev = x;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n if (!xp.red)\n x.red = true;\n else {\n lockRoot();\n try {\n root = balanceInsertion(root, x);\n } finally {\n unlockRoot();\n }\n }\n break;\n }\n }\n assert checkInvariants(root);\n return null;\n }\n\n /**\n * Removes the given node, that must be present before this\n * call. This is messier than typical red-black deletion code\n * because we cannot swap the contents of an interior node\n * with a leaf successor that is pinned by \"next\" pointers\n * that are accessible independently of lock. So instead we\n * swap the tree linkages.\n *\n * @return true if now too small, so should be untreeified\n */\n final boolean removeTreeNode(TreeNode p) {\n TreeNode next = (TreeNode) p.next;\n // unlink traversal pointers\n TreeNode pred = p.prev;\n TreeNode r, rl;\n if (pred == null)\n first = next;\n else\n pred.next = next;\n if (next != null)\n next.prev = pred;\n if (first == null) {\n root = null;\n return true;\n }\n if (// too small\n (r = root) == null || r.right == null || (rl = r.left) == null || rl.left == null)\n return true;\n lockRoot();\n try {\n TreeNode replacement;\n TreeNode pl = p.left;\n TreeNode pr = p.right;\n if (pl != null && pr != null) {\n TreeNode s = pr, sl;\n while (// find successor\n (sl = s.left) != null) s = sl;\n // swap colors\n boolean c = s.red;\n // swap colors\n s.red = p.red;\n // swap colors\n p.red = c;\n TreeNode sr = s.right;\n TreeNode pp = p.parent;\n if (s == pr) {\n // p was s's direct parent\n p.parent = s;\n s.right = p;\n } else {\n TreeNode sp = s.parent;\n if ((p.parent = sp) != null) {\n if (s == sp.left)\n sp.left = p;\n else\n sp.right = p;\n }\n if ((s.right = pr) != null)\n pr.parent = s;\n }\n p.left = null;\n if ((p.right = sr) != null)\n sr.parent = p;\n if ((s.left = pl) != null)\n pl.parent = s;\n if ((s.parent = pp) == null)\n r = s;\n else if (p == pp.left)\n pp.left = s;\n else\n pp.right = s;\n if (sr != null)\n replacement = sr;\n else\n replacement = p;\n } else if (pl != null)\n replacement = pl;\n else if (pr != null)\n replacement = pr;\n else\n replacement = p;\n if (replacement != p) {\n TreeNode pp = replacement.parent = p.parent;\n if (pp == null)\n r = replacement;\n else if (p == pp.left)\n pp.left = replacement;\n else\n pp.right = replacement;\n p.left = p.right = p.parent = null;\n }\n root = (p.red) ? r : balanceDeletion(r, replacement);\n if (p == replacement) {\n // detach pointers\n TreeNode pp;\n if ((pp = p.parent) != null) {\n if (p == pp.left)\n pp.left = null;\n else if (p == pp.right)\n pp.right = null;\n p.parent = null;\n }\n }\n } finally {\n unlockRoot();\n }\n assert checkInvariants(root);\n return false;\n }\n\n // Red-black tree methods, all adapted from CLR\n static TreeNode rotateLeft(TreeNode root, TreeNode p) {\n TreeNode r, pp, rl;\n if (p != null && (r = p.right) != null) {\n if ((rl = p.right = r.left) != null)\n rl.parent = p;\n if ((pp = r.parent = p.parent) == null)\n (root = r).red = false;\n else if (pp.left == p)\n pp.left = r;\n else\n pp.right = r;\n r.left = p;\n p.parent = r;\n }\n return root;\n }\n\n static TreeNode rotateRight(TreeNode root, TreeNode p) {\n TreeNode l, pp, lr;\n if (p != null && (l = p.left) != null) {\n if ((lr = p.left = l.right) != null)\n lr.parent = p;\n if ((pp = l.parent = p.parent) == null)\n (root = l).red = false;\n else if (pp.right == p)\n pp.right = l;\n else\n pp.left = l;\n l.right = p;\n p.parent = l;\n }\n return root;\n }\n\n static TreeNode balanceInsertion(TreeNode root, TreeNode x) {\n x.red = true;\n for (TreeNode xp, xpp, xppl, xppr; ; ) {\n if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (!xp.red || (xpp = xp.parent) == null)\n return root;\n if (xp == (xppl = xpp.left)) {\n if ((xppr = xpp.right) != null && xppr.red) {\n xppr.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.right) {\n root = rotateLeft(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateRight(root, xpp);\n }\n }\n }\n } else {\n if (xppl != null && xppl.red) {\n xppl.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.left) {\n root = rotateRight(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateLeft(root, xpp);\n }\n }\n }\n }\n }\n }\n\n static TreeNode balanceDeletion(TreeNode root, TreeNode x) {\n for (TreeNode xp, xpl, xpr; ; ) {\n if (x == null || x == root)\n return root;\n else if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (x.red) {\n x.red = false;\n return root;\n } else if ((xpl = xp.left) == x) {\n if ((xpr = xp.right) != null && xpr.red) {\n xpr.red = false;\n xp.red = true;\n root = rotateLeft(root, xp);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr == null)\n x = xp;\n else {\n TreeNode sl = xpr.left, sr = xpr.right;\n if ((sr == null || !sr.red) && (sl == null || !sl.red)) {\n xpr.red = true;\n x = xp;\n } else {\n if (sr == null || !sr.red) {\n if (sl != null)\n sl.red = false;\n xpr.red = true;\n root = rotateRight(root, xpr);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr != null) {\n xpr.red = (xp == null) ? false : xp.red;\n if ((sr = xpr.right) != null)\n sr.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateLeft(root, xp);\n }\n x = root;\n }\n }\n } else {\n // symmetric\n if (xpl != null && xpl.red) {\n xpl.red = false;\n xp.red = true;\n root = rotateRight(root, xp);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl == null)\n x = xp;\n else {\n TreeNode sl = xpl.left, sr = xpl.right;\n if ((sl == null || !sl.red) && (sr == null || !sr.red)) {\n xpl.red = true;\n x = xp;\n } else {\n if (sl == null || !sl.red) {\n if (sr != null)\n sr.red = false;\n xpl.red = true;\n root = rotateLeft(root, xpl);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl != null) {\n xpl.red = (xp == null) ? false : xp.red;\n if ((sl = xpl.left) != null)\n sl.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateRight(root, xp);\n }\n x = root;\n }\n }\n }\n }\n }\n\n /**\n * Checks invariants recursively for the tree of Nodes rooted at t.\n */\n static boolean checkInvariants(TreeNode t) {\n TreeNode tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode) t.next;\n if (tb != null && tb.next != t)\n return false;\n if (tn != null && tn.prev != t)\n return false;\n if (tp != null && t != tp.left && t != tp.right)\n return false;\n if (tl != null && (tl.parent != t || tl.hash > t.hash))\n return false;\n if (tr != null && (tr.parent != t || tr.hash < t.hash))\n return false;\n if (t.red && tl != null && tl.red && tr != null && tr.red)\n return false;\n if (tl != null && !checkInvariants(tl))\n return false;\n if (tr != null && !checkInvariants(tr))\n return false;\n return true;\n }\n\n private static final long LOCKSTATE = U.objectFieldOffset(TreeBin.class, \"lockState\");\n }\n\n /**\n * Records the table, its length, and current traversal index for a\n * traverser that must process a region of a forwarded table before\n * proceeding with current table.\n */\n static final class TableStack {\n\n int length;\n\n int index;\n\n Node[] tab;\n\n TableStack next;\n }\n\n /**\n * Encapsulates traversal for methods such as containsValue; also\n * serves as a base class for other iterators and spliterators.\n *\n * Method advance visits once each still-valid node that was\n * reachable upon iterator construction. It might miss some that\n * were added to a bin after the bin was visited, which is OK wrt\n * consistency guarantees. Maintaining this property in the face\n * of possible ongoing resizes requires a fair amount of\n * bookkeeping state that is difficult to optimize away amidst\n * volatile accesses. Even so, traversal maintains reasonable\n * throughput.\n *\n * Normally, iteration proceeds bin-by-bin traversing lists.\n * However, if the table has been resized, then all future steps\n * must traverse both the bin at the current index as well as at\n * (index + baseSize); and so on for further resizings. To\n * paranoically cope with potential sharing by users of iterators\n * across threads, iteration terminates if a bounds checks fails\n * for a table read.\n */\n static class Traverser {\n\n // current table; updated if resized\n Node[] tab;\n\n // the next entry to use\n Node next;\n\n // to save/restore on ForwardingNodes\n TableStack stack, spare;\n\n // index of bin to use next\n int index;\n\n // current index of initial table\n int baseIndex;\n\n // index bound for initial table\n int baseLimit;\n\n // initial table size\n final int baseSize;\n\n Traverser(Node[] tab, int size, int index, int limit) {\n this.tab = tab;\n this.baseSize = size;\n this.baseIndex = this.index = index;\n this.baseLimit = limit;\n this.next = null;\n }\n\n /**\n * Advances if possible, returning next valid node, or null if none.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n // must use locals in checks\n Node[] t;\n // must use locals in checks\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n // visit upper slots if present\n index = ++baseIndex;\n }\n }\n\n /**\n * Saves traversal state upon encountering a forwarding node.\n */\n private void pushState(Node[] t, int i, int n) {\n // reuse if possible\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n /**\n * Possibly pops traversal state.\n *\n * @param n length of current table\n */\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /**\n * Base of key, value, and entry Iterators. Adds fields to\n * Traverser to support iterator.remove.\n */\n static class BaseIterator extends Traverser {\n\n final ConcurrentHashMap map;\n\n Node lastReturned;\n\n BaseIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n advance();\n }\n\n public final boolean hasNext() {\n return next != null;\n }\n\n public final boolean hasMoreElements() {\n return next != null;\n }\n\n public final void remove() {\n Node p;\n if ((p = lastReturned) == null)\n throw new IllegalStateException();\n lastReturned = null;\n map.replaceNode(p.key, null, null);\n }\n }\n\n static final class KeyIterator extends BaseIterator implements Iterator, Enumeration {\n\n KeyIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final K next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n lastReturned = p;\n advance();\n return k;\n }\n\n public final K nextElement() {\n return next();\n }\n }\n\n static final class ValueIterator extends BaseIterator implements Iterator, Enumeration {\n\n ValueIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final V next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n V v = p.val;\n lastReturned = p;\n advance();\n return v;\n }\n\n public final V nextElement() {\n return next();\n }\n }\n\n static final class EntryIterator extends BaseIterator implements Iterator> {\n\n EntryIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final Map.Entry next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n V v = p.val;\n lastReturned = p;\n advance();\n return new MapEntry(k, v, map);\n }\n }\n\n static final class MapEntry implements Map.Entry {\n\n final K key;\n\n V val;\n\n final ConcurrentHashMap map;\n\n MapEntry(K key, V val, ConcurrentHashMap map) {\n this.key = key;\n this.val = val;\n this.map = map;\n }\n\n public K getKey() {\n return key;\n }\n\n public V getValue() {\n return val;\n }\n\n public int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public boolean equals(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == val || v.equals(val)));\n }\n\n /**\n * Sets our entry's value and writes through to the map. The\n * value to return is somewhat arbitrary here. Since we do not\n * necessarily track asynchronous changes, the most recent\n * \"previous\" value could be different from what we return (or\n * could even have been removed, in which case the put will\n * re-establish). We do not and cannot guarantee more.\n */\n public V setValue(V value) {\n if (value == null)\n throw new NullPointerException();\n V v = val;\n val = value;\n map.put(key, value);\n return v;\n }\n }\n\n static final class KeySpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n KeySpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public KeySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new KeySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.key);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class ValueSpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n ValueSpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public ValueSpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new ValueSpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.val);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class EntrySpliterator extends Traverser implements Spliterator> {\n\n // To export MapEntry\n final ConcurrentHashMap map;\n\n // size estimate\n long est;\n\n EntrySpliterator(Node[] tab, int size, int index, int limit, long est, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n this.est = est;\n }\n\n public EntrySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new EntrySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1, map);\n }\n\n public void forEachRemaining(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n\n public boolean tryAdvance(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(new MapEntry(p.key, p.val, map));\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n // Parallel bulk operations\n /**\n * Computes initial batch value for bulk tasks. The returned value\n * is approximately exp2 of the number of times (minus one) to\n * split task by two before executing leaf action. This value is\n * faster to compute and more convenient to use as a guide to\n * splitting than is the depth, since it is used while dividing by\n * two anyway.\n */\n final int batchFor(long b) {\n long n;\n if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)\n return 0;\n // slack of 4\n int sp = ForkJoinPool.getCommonPoolParallelism() << 2;\n return (b <= 0L || (n /= b) >= sp) ? sp : (int) n;\n }\n\n /**\n * Performs the given action for each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiFunction transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each (key, value), or null if none. Upon\n * success, further element processing is suppressed and the\n * results of any other parallel invocations of the search\n * function are ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each (key, value), or null if none\n * @since 1.8\n */\n public U search(long parallelismThreshold, BiFunction searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public U reduce(long parallelismThreshold, BiFunction transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public double reduceToDouble(long parallelismThreshold, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public long reduceToLong(long parallelismThreshold, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public int reduceToInt(long parallelismThreshold, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each key, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each key, or null if none\n * @since 1.8\n */\n public U searchKeys(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all keys using the given\n * reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all keys using the given\n * reducer to combine values, or null if none\n * @since 1.8\n */\n public K reduceKeys(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public U reduceKeys(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public double reduceKeysToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public long reduceKeysToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public int reduceKeysToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachValueTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedValueTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each value, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each value, or null if none\n * @since 1.8\n */\n public U searchValues(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all values using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all values\n * @since 1.8\n */\n public V reduceValues(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public U reduceValues(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public double reduceValuesToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public long reduceValuesToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public int reduceValuesToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Function, ? extends U> transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each entry, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each entry, or null if none\n * @since 1.8\n */\n public U searchEntries(long parallelismThreshold, Function, ? extends U> searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all entries using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all entries\n * @since 1.8\n */\n public Map.Entry reduceEntries(long parallelismThreshold, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public U reduceEntries(long parallelismThreshold, Function, ? extends U> transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public double reduceEntriesToDouble(long parallelismThreshold, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public long reduceEntriesToLong(long parallelismThreshold, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public int reduceEntriesToInt(long parallelismThreshold, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n abstract static class CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n final ConcurrentHashMap map;\n\n CollectionView(ConcurrentHashMap map) {\n this.map = map;\n }\n\n /**\n * Returns the map backing this view.\n *\n * @return the map backing this view\n */\n public ConcurrentHashMap getMap() {\n return map;\n }\n\n /**\n * Removes all of the elements from this view, by removing all\n * the mappings from the map backing this view.\n */\n public final void clear() {\n map.clear();\n }\n\n public final int size() {\n return map.size();\n }\n\n public final boolean isEmpty() {\n return map.isEmpty();\n }\n\n // implementations below rely on concrete classes supplying these\n /**\n * Returns an iterator over the elements in this collection.\n *\n *

The returned iterator is\n * weakly consistent.\n *\n * @return an iterator over the elements in this collection\n */\n public abstract Iterator iterator();\n\n public abstract boolean contains(Object o);\n\n public abstract boolean remove(Object o);\n\n private static final String OOME_MSG = \"Required array size too large\";\n\n public final Object[] toArray() {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int n = (int) sz;\n Object[] r = new Object[n];\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = e;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n @SuppressWarnings(\"unchecked\")\n public final T[] toArray(T[] a) {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int m = (int) sz;\n T[] r = (a.length >= m) ? a : (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), m);\n int n = r.length;\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = (T) e;\n }\n if (a == r && i < n) {\n r[i] = null;\n return r;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n /**\n * Returns a string representation of this collection.\n * The string representation consists of the string representations\n * of the collection's elements in the order they are returned by\n * its iterator, enclosed in square brackets ({@code \"[]\"}).\n * Adjacent elements are separated by the characters {@code \", \"}\n * (comma and space). Elements are converted to strings as by\n * {@link String#valueOf(Object)}.\n *\n * @return a string representation of this collection\n */\n public final String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append('[');\n Iterator it = iterator();\n if (it.hasNext()) {\n for (; ; ) {\n Object e = it.next();\n sb.append(e == this ? \"(this Collection)\" : e);\n if (!it.hasNext())\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append(']').toString();\n }\n\n public final boolean containsAll(Collection c) {\n if (c != this) {\n for (Object e : c) {\n if (e == null || !contains(e))\n return false;\n }\n }\n return true;\n }\n\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n // Use (c instanceof Set) as a hint that lookup in c is as\n // efficient as this view\n Node[] t;\n if ((t = map.table) == null) {\n return false;\n } else if (c instanceof Set && c.size() > t.length) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n } else {\n for (Object e : c) modified |= remove(e);\n }\n return modified;\n }\n\n public final boolean retainAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (!c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of keys, in\n * which additions may optionally be enabled by mapping to a\n * common value. This class cannot be directly instantiated.\n * See {@link #keySet() keySet()},\n * {@link #keySet(Object) keySet(V)},\n * {@link #newKeySet() newKeySet()},\n * {@link #newKeySet(int) newKeySet(int)}.\n *\n * @since 1.8\n */\n public static class KeySetView extends CollectionView implements Set, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n // Conditionally serializable\n @SuppressWarnings(\"serial\")\n private final V value;\n\n KeySetView(ConcurrentHashMap map, V value) {\n super(map);\n this.value = value;\n }\n\n /**\n * Returns the default mapped value for additions,\n * or {@code null} if additions are not supported.\n *\n * @return the default mapped value for additions, or {@code null}\n * if not supported\n */\n public V getMappedValue() {\n return value;\n }\n\n /**\n * {@inheritDoc}\n * @throws NullPointerException if the specified key is null\n */\n public boolean contains(Object o) {\n return map.containsKey(o);\n }\n\n /**\n * Removes the key from this map view, by removing the key (and its\n * corresponding value) from the backing map. This method does\n * nothing if the key is not in the map.\n *\n * @param o the key to be removed from the backing map\n * @return {@code true} if the backing map contained the specified key\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object o) {\n return map.remove(o) != null;\n }\n\n /**\n * @return an iterator over the keys of the backing map\n */\n public Iterator iterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, m);\n }\n\n /**\n * Adds the specified key to this set view by mapping the key to\n * the default mapped value in the backing map, if defined.\n *\n * @param e key to be added\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the specified key is null\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean add(K e) {\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n return map.putVal(e, v, true) == null;\n }\n\n /**\n * Adds all of the elements in the specified collection to this set,\n * as if by calling {@link #add} on each one.\n *\n * @param c the elements to be inserted into this set\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the collection or any of its\n * elements are {@code null}\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean addAll(Collection c) {\n boolean added = false;\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n for (K e : c) {\n if (map.putVal(e, v, true) == null)\n added = true;\n }\n return added;\n }\n\n public int hashCode() {\n int h = 0;\n for (K e : this) h += e.hashCode();\n return h;\n }\n\n public boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeySpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.key);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Collection} of\n * values, in which additions are disabled. This class cannot be\n * directly instantiated. See {@link #values()}.\n */\n static final class ValuesView extends CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n ValuesView(ConcurrentHashMap map) {\n super(map);\n }\n\n public final boolean contains(Object o) {\n return map.containsValue(o);\n }\n\n public final boolean remove(Object o) {\n if (o != null) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (o.equals(it.next())) {\n it.remove();\n return true;\n }\n }\n }\n return false;\n }\n\n public final Iterator iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, m);\n }\n\n public final boolean add(V e) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean addAll(Collection c) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n\n public boolean removeIf(Predicate filter) {\n return map.removeValueIf(filter);\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueSpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.val);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of (key, value)\n * entries. This class cannot be directly instantiated. See\n * {@link #entrySet()}.\n */\n static final class EntrySetView extends CollectionView> implements Set>, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n EntrySetView(ConcurrentHashMap map) {\n super(map);\n }\n\n public boolean contains(Object o) {\n Object k, v, r;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (r = map.get(k)) != null && (v = e.getValue()) != null && (v == r || v.equals(r)));\n }\n\n public boolean remove(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && map.remove(k, v));\n }\n\n /**\n * @return an iterator over the entries of the backing map\n */\n public Iterator> iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntryIterator(t, f, 0, f, m);\n }\n\n public boolean add(Entry e) {\n return map.putVal(e.getKey(), e.getValue(), false) == null;\n }\n\n public boolean addAll(Collection> c) {\n boolean added = false;\n for (Entry e : c) {\n if (add(e))\n added = true;\n }\n return added;\n }\n\n public boolean removeIf(Predicate> filter) {\n return map.removeEntryIf(filter);\n }\n\n public final int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n h += p.hashCode();\n }\n }\n return h;\n }\n\n public final boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator> spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntrySpliterator(t, f, 0, f, n < 0L ? 0L : n, m);\n }\n\n public void forEach(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n }\n }\n\n /**\n * Base class for bulk tasks. Repeats some fields and code from\n * class Traverser, because we need to subclass CountedCompleter.\n */\n @SuppressWarnings(\"serial\")\n abstract static class BulkTask extends CountedCompleter {\n\n // same as Traverser\n Node[] tab;\n\n Node next;\n\n TableStack stack, spare;\n\n int index;\n\n int baseIndex;\n\n int baseLimit;\n\n final int baseSize;\n\n // split control\n int batch;\n\n BulkTask(BulkTask par, int b, int i, int f, Node[] t) {\n super(par);\n this.batch = b;\n this.index = this.baseIndex = i;\n if ((this.tab = t) == null)\n this.baseSize = this.baseLimit = 0;\n else if (par == null)\n this.baseSize = this.baseLimit = t.length;\n else {\n this.baseLimit = f;\n this.baseSize = par.baseSize;\n }\n }\n\n /**\n * Same as Traverser version.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n Node[] t;\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n private void pushState(Node[] t, int i, int n) {\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /*\n * Task classes. Coded in a regular but ugly format/style to\n * simplify checks that each variant differs in the right way from\n * others. The null screenings exist because compilers cannot tell\n * that we've already null-checked task arguments, so we force\n * simplest hoisted bypass to help avoid convoluted traps.\n */\n @SuppressWarnings(\"serial\")\n static final class ForEachKeyTask extends BulkTask {\n\n final Consumer action;\n\n ForEachKeyTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachValueTask extends BulkTask {\n\n final Consumer action;\n\n ForEachValueTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachValueTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachEntryTask extends BulkTask {\n\n final Consumer> action;\n\n ForEachEntryTask(BulkTask p, int b, int i, int f, Node[] t, Consumer> action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer> action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachMappingTask extends BulkTask {\n\n final BiConsumer action;\n\n ForEachMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiConsumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final BiConsumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key, p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedKeyTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedKeyTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedValueTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedValueTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedValueTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedEntryTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final Consumer action;\n\n ForEachTransformedEntryTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedMappingTask extends BulkTask {\n\n final BiFunction transformer;\n\n final Consumer action;\n\n ForEachTransformedMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchKeysTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchKeysTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchValuesTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchValuesTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchEntriesTask extends BulkTask {\n\n final Function, ? extends U> searchFunction;\n\n final AtomicReference result;\n\n SearchEntriesTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function, ? extends U> searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n return;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchMappingsTask extends BulkTask {\n\n final BiFunction searchFunction;\n\n final AtomicReference result;\n\n SearchMappingsTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final BiFunction searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key, p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceKeysTask extends BulkTask {\n\n final BiFunction reducer;\n\n K result;\n\n ReduceKeysTask rights, nextRight;\n\n ReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, ReduceKeysTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final K getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n K r = null;\n for (Node p; (p = advance()) != null; ) {\n K u = p.key;\n r = (r == null) ? u : u == null ? r : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceKeysTask t = (ReduceKeysTask) c, s = t.rights;\n while (s != null) {\n K tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceValuesTask extends BulkTask {\n\n final BiFunction reducer;\n\n V result;\n\n ReduceValuesTask rights, nextRight;\n\n ReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceValuesTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final V getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n V r = null;\n for (Node p; (p = advance()) != null; ) {\n V v = p.val;\n r = (r == null) ? v : reducer.apply(r, v);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceValuesTask t = (ReduceValuesTask) c, s = t.rights;\n while (s != null) {\n V tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceEntriesTask extends BulkTask> {\n\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n\n Map.Entry result;\n\n ReduceEntriesTask rights, nextRight;\n\n ReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceEntriesTask nextRight, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final Map.Entry getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n Map.Entry r = null;\n for (Node p; (p = advance()) != null; ) r = (r == null) ? p : reducer.apply(r, p);\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceEntriesTask t = (ReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n Map.Entry tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceKeysTask rights, nextRight;\n\n MapReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysTask t = (MapReduceKeysTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceValuesTask rights, nextRight;\n\n MapReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesTask t = (MapReduceValuesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceEntriesTask rights, nextRight;\n\n MapReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesTask nextRight, Function, ? extends U> transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesTask t = (MapReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsTask extends BulkTask {\n\n final BiFunction transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceMappingsTask rights, nextRight;\n\n MapReduceMappingsTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsTask nextRight, BiFunction transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsTask t = (MapReduceMappingsTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceKeysToDoubleTask rights, nextRight;\n\n MapReduceKeysToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToDoubleTask t = (MapReduceKeysToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceValuesToDoubleTask rights, nextRight;\n\n MapReduceValuesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToDoubleTask t = (MapReduceValuesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction> transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceEntriesToDoubleTask rights, nextRight;\n\n MapReduceEntriesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToDoubleTask nextRight, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction> transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToDoubleTask t = (MapReduceEntriesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToDoubleTask extends BulkTask {\n\n final ToDoubleBiFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceMappingsToDoubleTask rights, nextRight;\n\n MapReduceMappingsToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToDoubleTask nextRight, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleBiFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToDoubleTask t = (MapReduceMappingsToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceKeysToLongTask rights, nextRight;\n\n MapReduceKeysToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToLongTask t = (MapReduceKeysToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceValuesToLongTask rights, nextRight;\n\n MapReduceValuesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToLongTask t = (MapReduceValuesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToLongTask extends BulkTask {\n\n final ToLongFunction> transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceEntriesToLongTask rights, nextRight;\n\n MapReduceEntriesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToLongTask nextRight, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction> transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToLongTask t = (MapReduceEntriesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToLongTask extends BulkTask {\n\n final ToLongBiFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceMappingsToLongTask rights, nextRight;\n\n MapReduceMappingsToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToLongTask nextRight, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongBiFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToLongTask t = (MapReduceMappingsToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceKeysToIntTask rights, nextRight;\n\n MapReduceKeysToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToIntTask t = (MapReduceKeysToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceValuesToIntTask rights, nextRight;\n\n MapReduceValuesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToIntTask t = (MapReduceValuesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToIntTask extends BulkTask {\n\n final ToIntFunction> transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceEntriesToIntTask rights, nextRight;\n\n MapReduceEntriesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToIntTask nextRight, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction> transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToIntTask t = (MapReduceEntriesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToIntTask extends BulkTask {\n\n final ToIntBiFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceMappingsToIntTask rights, nextRight;\n\n MapReduceMappingsToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToIntTask nextRight, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntBiFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToIntTask t = (MapReduceMappingsToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n // Unsafe mechanics\n private static final Unsafe U = Unsafe.getUnsafe();\n\n private static final long SIZECTL = U.objectFieldOffset(ConcurrentHashMap.class, \"sizeCtl\");\n\n private static final long TRANSFERINDEX = U.objectFieldOffset(ConcurrentHashMap.class, \"transferIndex\");\n\n private static final long BASECOUNT = U.objectFieldOffset(ConcurrentHashMap.class, \"baseCount\");\n\n private static final long CELLSBUSY = U.objectFieldOffset(ConcurrentHashMap.class, \"cellsBusy\");\n\n private static final long CELLVALUE = U.objectFieldOffset(CounterCell.class, \"value\");\n\n private static final int ABASE = U.arrayBaseOffset(Node[].class);\n\n private static final int ASHIFT;\n\n static {\n int scale = U.arrayIndexScale(Node[].class);\n if ((scale & (scale - 1)) != 0)\n throw new ExceptionInInitializerError(\"array index scale not a power of two\");\n ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);\n // Reduce the risk of rare disastrous classloading in first call to\n Class ensureLoaded = LockSupport.class;\n // Eager class load observed to help JIT during startup\n ensureLoaded = ReservationNode.class;\n }\n}\n"} {"task_id": "Java_2826", "language": "Java", "task_type": "for_statement", "source_file": "java/github/openjdk/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java", "mask_start_position": 67479, "mask_end_position": 67792, "canonical_solution": "for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n Map.Entry e = new AbstractMap.SimpleImmutableEntry<>(k, v);\n if (function.test(e) && replaceNode(k, null, v) != null)\n removed = true;\n }", "pre_mask_code": "package java.util.concurrent;\n\nimport java.io.ObjectStreamField;\nimport java.io.Serializable;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.AbstractMap;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Hashtable;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.Spliterator;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.concurrent.locks.LockSupport;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\nimport java.util.function.Consumer;\nimport java.util.function.DoubleBinaryOperator;\nimport java.util.function.Function;\nimport java.util.function.IntBinaryOperator;\nimport java.util.function.LongBinaryOperator;\nimport java.util.function.Predicate;\nimport java.util.function.ToDoubleBiFunction;\nimport java.util.function.ToDoubleFunction;\nimport java.util.function.ToIntBiFunction;\nimport java.util.function.ToIntFunction;\nimport java.util.function.ToLongBiFunction;\nimport java.util.function.ToLongFunction;\nimport java.util.stream.Stream;\nimport jdk.internal.misc.Unsafe;\n\n/**\n * A hash table supporting full concurrency of retrievals and\n * high expected concurrency for updates. This class obeys the\n * same functional specification as {@link java.util.Hashtable}, and\n * includes versions of methods corresponding to each method of\n * {@code Hashtable}. However, even though all operations are\n * thread-safe, retrieval operations do not entail locking,\n * and there is not any support for locking the entire table\n * in a way that prevents all access. This class is fully\n * interoperable with {@code Hashtable} in programs that rely on its\n * thread safety but not on its synchronization details.\n *\n *

Retrieval operations (including {@code get}) generally do not\n * block, so may overlap with update operations (including {@code put}\n * and {@code remove}). Retrievals reflect the results of the most\n * recently completed update operations holding upon their\n * onset. (More formally, an update operation for a given key bears a\n * happens-before relation with any (non-null) retrieval for\n * that key reporting the updated value.) For aggregate operations\n * such as {@code putAll} and {@code clear}, concurrent retrievals may\n * reflect insertion or removal of only some entries. Similarly,\n * Iterators, Spliterators and Enumerations return elements reflecting the\n * state of the hash table at some point at or since the creation of the\n * iterator/enumeration. They do not throw {@link\n * java.util.ConcurrentModificationException ConcurrentModificationException}.\n * However, iterators are designed to be used by only one thread at a time.\n * Bear in mind that the results of aggregate status methods including\n * {@code size}, {@code isEmpty}, and {@code containsValue} are typically\n * useful only when a map is not undergoing concurrent updates in other threads.\n * Otherwise the results of these methods reflect transient states\n * that may be adequate for monitoring or estimation purposes, but not\n * for program control.\n *\n *

The table is dynamically expanded when there are too many\n * collisions (i.e., keys that have distinct hash codes but fall into\n * the same slot modulo the table size), with the expected average\n * effect of maintaining roughly two bins per mapping (corresponding\n * to a 0.75 load factor threshold for resizing). There may be much\n * variance around this average as mappings are added and removed, but\n * overall, this maintains a commonly accepted time/space tradeoff for\n * hash tables. However, resizing this or any other kind of hash\n * table may be a relatively slow operation. When possible, it is a\n * good idea to provide a size estimate as an optional {@code\n * initialCapacity} constructor argument. An additional optional\n * {@code loadFactor} constructor argument provides a further means of\n * customizing initial table capacity by specifying the table density\n * to be used in calculating the amount of space to allocate for the\n * given number of elements. Also, for compatibility with previous\n * versions of this class, constructors may optionally specify an\n * expected {@code concurrencyLevel} as an additional hint for\n * internal sizing. Note that using many keys with exactly the same\n * {@code hashCode()} is a sure way to slow down performance of any\n * hash table. To ameliorate impact, when keys are {@link Comparable},\n * this class may use comparison order among keys to help break ties.\n *\n *

A {@link Set} projection of a ConcurrentHashMap may be created\n * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed\n * (using {@link #keySet(Object)} when only keys are of interest, and the\n * mapped values are (perhaps transiently) not used or all take the\n * same mapping value.\n *\n *

A ConcurrentHashMap can be used as a scalable frequency map (a\n * form of histogram or multiset) by using {@link\n * java.util.concurrent.atomic.LongAdder} values and initializing via\n * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count\n * to a {@code ConcurrentHashMap freqs}, you can use\n * {@code freqs.computeIfAbsent(key, k -> new LongAdder()).increment();}\n *\n *

This class and its views and iterators implement all of the\n * optional methods of the {@link Map} and {@link Iterator}\n * interfaces.\n *\n *

Like {@link Hashtable} but unlike {@link HashMap}, this class\n * does not allow {@code null} to be used as a key or value.\n *\n *

ConcurrentHashMaps support a set of sequential and parallel bulk\n * operations that, unlike most {@link Stream} methods, are designed\n * to be safely, and often sensibly, applied even with maps that are\n * being concurrently updated by other threads; for example, when\n * computing a snapshot summary of the values in a shared registry.\n * There are three kinds of operation, each with four forms, accepting\n * functions with keys, values, entries, and (key, value) pairs as\n * arguments and/or return values. Because the elements of a\n * ConcurrentHashMap are not ordered in any particular way, and may be\n * processed in different orders in different parallel executions, the\n * correctness of supplied functions should not depend on any\n * ordering, or on any other objects or values that may transiently\n * change while computation is in progress; and except for forEach\n * actions, should ideally be side-effect-free. Bulk operations on\n * {@link Map.Entry} objects do not support method {@code setValue}.\n *\n *

    \n *
  • forEach: Performs a given action on each element.\n * A variant form applies a given transformation on each element\n * before performing the action.\n *\n *
  • search: Returns the first available non-null result of\n * applying a given function on each element; skipping further\n * search when a result is found.\n *\n *
  • reduce: Accumulates each element. The supplied reduction\n * function cannot rely on ordering (more formally, it should be\n * both associative and commutative). There are five variants:\n *\n *
      \n *\n *
    • Plain reductions. (There is not a form of this method for\n * (key, value) function arguments since there is no corresponding\n * return type.)\n *\n *
    • Mapped reductions that accumulate the results of a given\n * function applied to each element.\n *\n *
    • Reductions to scalar doubles, longs, and ints, using a\n * given basis value.\n *\n *
    \n *
\n *\n *

These bulk operations accept a {@code parallelismThreshold}\n * argument. Methods proceed sequentially if the current map size is\n * estimated to be less than the given threshold. Using a value of\n * {@code Long.MAX_VALUE} suppresses all parallelism. Using a value\n * of {@code 1} results in maximal parallelism by partitioning into\n * enough subtasks to fully utilize the {@link\n * ForkJoinPool#commonPool()} that is used for all parallel\n * computations. Normally, you would initially choose one of these\n * extreme values, and then measure performance of using in-between\n * values that trade off overhead versus throughput.\n *\n *

The concurrency properties of bulk operations follow\n * from those of ConcurrentHashMap: Any non-null result returned\n * from {@code get(key)} and related access methods bears a\n * happens-before relation with the associated insertion or\n * update. The result of any bulk operation reflects the\n * composition of these per-element relations (but is not\n * necessarily atomic with respect to the map as a whole unless it\n * is somehow known to be quiescent). Conversely, because keys\n * and values in the map are never null, null serves as a reliable\n * atomic indicator of the current lack of any result. To\n * maintain this property, null serves as an implicit basis for\n * all non-scalar reduction operations. For the double, long, and\n * int versions, the basis should be one that, when combined with\n * any other value, returns that other value (more formally, it\n * should be the identity element for the reduction). Most common\n * reductions have these properties; for example, computing a sum\n * with basis 0 or a minimum with basis MAX_VALUE.\n *\n *

Search and transformation functions provided as arguments\n * should similarly return null to indicate the lack of any result\n * (in which case it is not used). In the case of mapped\n * reductions, this also enables transformations to serve as\n * filters, returning null (or, in the case of primitive\n * specializations, the identity basis) if the element should not\n * be combined. You can create compound transformations and\n * filterings by composing them yourself under this \"null means\n * there is nothing there now\" rule before using them in search or\n * reduce operations.\n *\n *

Methods accepting and/or returning Entry arguments maintain\n * key-value associations. They may be useful for example when\n * finding the key for the greatest value. Note that \"plain\" Entry\n * arguments can be supplied using {@code new\n * AbstractMap.SimpleEntry(k,v)}.\n *\n *

Bulk operations may complete abruptly, throwing an\n * exception encountered in the application of a supplied\n * function. Bear in mind when handling such exceptions that other\n * concurrently executing functions could also have thrown\n * exceptions, or would have done so if the first exception had\n * not occurred.\n *\n *

Speedups for parallel compared to sequential forms are common\n * but not guaranteed. Parallel operations involving brief functions\n * on small maps may execute more slowly than sequential forms if the\n * underlying work to parallelize the computation is more expensive\n * than the computation itself. Similarly, parallelization may not\n * lead to much actual parallelism if all processors are busy\n * performing unrelated tasks.\n *\n *

All arguments to all task methods must be non-null.\n *\n *

This class is a member of the\n * \n * Java Collections Framework.\n *\n * @since 1.5\n * @author Doug Lea\n * @param the type of keys maintained by this map\n * @param the type of mapped values\n */\npublic class ConcurrentHashMap extends AbstractMap implements ConcurrentMap, Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n /*\n * Overview:\n *\n * The primary design goal of this hash table is to maintain\n * concurrent readability (typically method get(), but also\n * iterators and related methods) while minimizing update\n * contention. Secondary goals are to keep space consumption about\n * the same or better than java.util.HashMap, and to support high\n * initial insertion rates on an empty table by many threads.\n *\n * This map usually acts as a binned (bucketed) hash table. Each\n * key-value mapping is held in a Node. Most nodes are instances\n * of the basic Node class with hash, key, value, and next\n * fields. However, various subclasses exist: TreeNodes are\n * arranged in balanced trees, not lists. TreeBins hold the roots\n * of sets of TreeNodes. ForwardingNodes are placed at the heads\n * of bins during resizing. ReservationNodes are used as\n * placeholders while establishing values in computeIfAbsent and\n * related methods. The types TreeBin, ForwardingNode, and\n * ReservationNode do not hold normal user keys, values, or\n * hashes, and are readily distinguishable during search etc\n * because they have negative hash fields and null key and value\n * fields. (These special nodes are either uncommon or transient,\n * so the impact of carrying around some unused fields is\n * insignificant.)\n *\n * The table is lazily initialized to a power-of-two size upon the\n * first insertion. Each bin in the table normally contains a\n * list of Nodes (most often, the list has only zero or one Node).\n * Table accesses require volatile/atomic reads, writes, and\n * CASes. Because there is no other way to arrange this without\n * adding further indirections, we use intrinsics\n * (jdk.internal.misc.Unsafe) operations.\n *\n * We use the top (sign) bit of Node hash fields for control\n * purposes -- it is available anyway because of addressing\n * constraints. Nodes with negative hash fields are specially\n * handled or ignored in map methods.\n *\n * Insertion (via put or its variants) of the first node in an\n * empty bin is performed by just CASing it to the bin. This is\n * by far the most common case for put operations under most\n * key/hash distributions. Other update operations (insert,\n * delete, and replace) require locks. We do not want to waste\n * the space required to associate a distinct lock object with\n * each bin, so instead use the first node of a bin list itself as\n * a lock. Locking support for these locks relies on builtin\n * \"synchronized\" monitors.\n *\n * Using the first node of a list as a lock does not by itself\n * suffice though: When a node is locked, any update must first\n * validate that it is still the first node after locking it, and\n * retry if not. Because new nodes are always appended to lists,\n * once a node is first in a bin, it remains first until deleted\n * or the bin becomes invalidated (upon resizing).\n *\n * The main disadvantage of per-bin locks is that other update\n * operations on other nodes in a bin list protected by the same\n * lock can stall, for example when user equals() or mapping\n * functions take a long time. However, statistically, under\n * random hash codes, this is not a common problem. Ideally, the\n * frequency of nodes in bins follows a Poisson distribution\n * (http://example.com) with a\n * parameter of about 0.5 on average, given the resizing threshold\n * of 0.75, although with a large variance because of resizing\n * granularity. Ignoring variance, the expected occurrences of\n * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The\n * first values are:\n *\n * 0: 0.60653066\n * 1: 0.30326533\n * 2: 0.07581633\n * 3: 0.01263606\n * 4: 0.00157952\n * 5: 0.00015795\n * 6: 0.00001316\n * 7: 0.00000094\n * 8: 0.00000006\n * more: less than 1 in ten million\n *\n * Lock contention probability for two threads accessing distinct\n * elements is roughly 1 / (8 * #elements) under random hashes.\n *\n * Actual hash code distributions encountered in practice\n * sometimes deviate significantly from uniform randomness. This\n * includes the case when N > (1<<30), so some keys MUST collide.\n * Similarly for dumb or hostile usages in which multiple keys are\n * designed to have identical hash codes or ones that differs only\n * in masked-out high bits. So we use a secondary strategy that\n * applies when the number of nodes in a bin exceeds a\n * threshold. These TreeBins use a balanced tree to hold nodes (a\n * specialized form of red-black trees), bounding search time to\n * O(log N). Each search step in a TreeBin is at least twice as\n * slow as in a regular list, but given that N cannot exceed\n * (1<<64) (before running out of addresses) this bounds search\n * steps, lock hold times, etc, to reasonable constants (roughly\n * 100 nodes inspected per operation worst case) so long as keys\n * are Comparable (which is very common -- String, Long, etc).\n * TreeBin nodes (TreeNodes) also maintain the same \"next\"\n * traversal pointers as regular nodes, so can be traversed in\n * iterators in the same way.\n *\n * The table is resized when occupancy exceeds a percentage\n * threshold (nominally, 0.75, but see below). Any thread\n * noticing an overfull bin may assist in resizing after the\n * initiating thread allocates and sets up the replacement array.\n * However, rather than stalling, these other threads may proceed\n * with insertions etc. The use of TreeBins shields us from the\n * worst case effects of overfilling while resizes are in\n * progress. Resizing proceeds by transferring bins, one by one,\n * from the table to the next table. However, threads claim small\n * blocks of indices to transfer (via field transferIndex) before\n * doing so, reducing contention. A generation stamp in field\n * sizeCtl ensures that resizings do not overlap. Because we are\n * using power-of-two expansion, the elements from each bin must\n * either stay at same index, or move with a power of two\n * offset. We eliminate unnecessary node creation by catching\n * cases where old nodes can be reused because their next fields\n * won't change. On average, only about one-sixth of them need\n * cloning when a table doubles. The nodes they replace will be\n * garbage collectible as soon as they are no longer referenced by\n * any reader thread that may be in the midst of concurrently\n * traversing table. Upon transfer, the old table bin contains\n * only a special forwarding node (with hash field \"MOVED\") that\n * contains the next table as its key. On encountering a\n * forwarding node, access and update operations restart, using\n * the new table.\n *\n * Each bin transfer requires its bin lock, which can stall\n * waiting for locks while resizing. However, because other\n * threads can join in and help resize rather than contend for\n * locks, average aggregate waits become shorter as resizing\n * progresses. The transfer operation must also ensure that all\n * accessible bins in both the old and new table are usable by any\n * traversal. This is arranged in part by proceeding from the\n * last bin (table.length - 1) up towards the first. Upon seeing\n * a forwarding node, traversals (see class Traverser) arrange to\n * move to the new table without revisiting nodes. To ensure that\n * no intervening nodes are skipped even when moved out of order,\n * a stack (see class TableStack) is created on first encounter of\n * a forwarding node during a traversal, to maintain its place if\n * later processing the current table. The need for these\n * save/restore mechanics is relatively rare, but when one\n * forwarding node is encountered, typically many more will be.\n * So Traversers use a simple caching scheme to avoid creating so\n * many new TableStack nodes. (Thanks to Peter Levart for\n * suggesting use of a stack here.)\n *\n * The traversal scheme also applies to partial traversals of\n * ranges of bins (via an alternate Traverser constructor)\n * to support partitioned aggregate operations. Also, read-only\n * operations give up if ever forwarded to a null table, which\n * provides support for shutdown-style clearing, which is also not\n * currently implemented.\n *\n * Lazy table initialization minimizes footprint until first use,\n * and also avoids resizings when the first operation is from a\n * putAll, constructor with map argument, or deserialization.\n * These cases attempt to override the initial capacity settings,\n * but harmlessly fail to take effect in cases of races.\n *\n * The element count is maintained using a specialization of\n * LongAdder. We need to incorporate a specialization rather than\n * just use a LongAdder in order to access implicit\n * contention-sensing that leads to creation of multiple\n * CounterCells. The counter mechanics avoid contention on\n * updates but can encounter cache thrashing if read too\n * frequently during concurrent access. To avoid reading so often,\n * resizing under contention is attempted only upon adding to a\n * bin already holding two or more nodes. Under uniform hash\n * distributions, the probability of this occurring at threshold\n * is around 13%, meaning that only about 1 in 8 puts check\n * threshold (and after resizing, many fewer do so).\n *\n * TreeBins use a special form of comparison for search and\n * related operations (which is the main reason we cannot use\n * existing collections such as TreeMaps). TreeBins contain\n * Comparable elements, but may contain others, as well as\n * elements that are Comparable but not necessarily Comparable for\n * the same T, so we cannot invoke compareTo among them. To handle\n * this, the tree is ordered primarily by hash value, then by\n * Comparable.compareTo order if applicable. On lookup at a node,\n * if elements are not comparable or compare as 0 then both left\n * and right children may need to be searched in the case of tied\n * hash values. (This corresponds to the full list search that\n * would be necessary if all elements were non-Comparable and had\n * tied hashes.) On insertion, to keep a total ordering (or as\n * close as is required here) across rebalancings, we compare\n * classes and identityHashCodes as tie-breakers. The red-black\n * balancing code is updated from pre-jdk-collections\n * (http://example.com)\n * based in turn on Cormen, Leiserson, and Rivest \"Introduction to\n * Algorithms\" (CLR).\n *\n * TreeBins also require an additional locking mechanism. While\n * list traversal is always possible by readers even during\n * updates, tree traversal is not, mainly because of tree-rotations\n * that may change the root node and/or its linkages. TreeBins\n * include a simple read-write lock mechanism parasitic on the\n * main bin-synchronization strategy: Structural adjustments\n * associated with an insertion or removal are already bin-locked\n * (and so cannot conflict with other writers) but must wait for\n * ongoing readers to finish. Since there can be only one such\n * waiter, we use a simple scheme using a single \"waiter\" field to\n * block writers. However, readers need never block. If the root\n * lock is held, they proceed along the slow traversal path (via\n * next-pointers) until the lock becomes available or the list is\n * exhausted, whichever comes first. These cases are not fast, but\n * maximize aggregate expected throughput.\n *\n * Maintaining API and serialization compatibility with previous\n * versions of this class introduces several oddities. Mainly: We\n * leave untouched but unused constructor arguments referring to\n * concurrencyLevel. We accept a loadFactor constructor argument,\n * but apply it only to initial table capacity (which is the only\n * time that we can guarantee to honor it.) We also declare an\n * unused \"Segment\" class that is instantiated in minimal form\n * only when serializing.\n *\n * Also, solely for compatibility with previous versions of this\n * class, it extends AbstractMap, even though all of its methods\n * are overridden, so it is just useless baggage.\n *\n * This file is organized to make things a little easier to follow\n * while reading than they might otherwise: First the main static\n * declarations and utilities, then fields, then main public\n * methods (with a few factorings of multiple public methods into\n * internal ones), then sizing methods, trees, traversers, and\n * bulk operations.\n */\n /**\n * The largest possible table capacity. This value must be\n * exactly 1<<30 to stay within Java array allocation and indexing\n * bounds for power of two table sizes, and is further required\n * because the top two bits of 32bit hash fields are used for\n * control purposes.\n */\n private static final int MAXIMUM_CAPACITY = 1 << 30;\n\n /**\n * The default initial table capacity. Must be a power of 2\n * (i.e., at least 1) and at most MAXIMUM_CAPACITY.\n */\n private static final int DEFAULT_CAPACITY = 16;\n\n /**\n * The largest possible (non-power of two) array size.\n * Needed by toArray and related methods.\n */\n static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;\n\n /**\n * The default concurrency level for this table. Unused but\n * defined for compatibility with previous versions of this class.\n */\n private static final int DEFAULT_CONCURRENCY_LEVEL = 16;\n\n /**\n * The load factor for this table. Overrides of this value in\n * constructors affect only the initial table capacity. The\n * actual floating point value isn't normally used -- it is\n * simpler to use expressions such as {@code n - (n >>> 2)} for\n * the associated resizing threshold.\n */\n private static final float LOAD_FACTOR = 0.75f;\n\n /**\n * The bin count threshold for using a tree rather than list for a\n * bin. Bins are converted to trees when adding an element to a\n * bin with at least this many nodes. The value must be greater\n * than 2, and should be at least 8 to mesh with assumptions in\n * tree removal about conversion back to plain bins upon\n * shrinkage.\n */\n static final int TREEIFY_THRESHOLD = 8;\n\n /**\n * The bin count threshold for untreeifying a (split) bin during a\n * resize operation. Should be less than TREEIFY_THRESHOLD, and at\n * most 6 to mesh with shrinkage detection under removal.\n */\n static final int UNTREEIFY_THRESHOLD = 6;\n\n /**\n * The smallest table capacity for which bins may be treeified.\n * (Otherwise the table is resized if too many nodes in a bin.)\n * The value should be at least 4 * TREEIFY_THRESHOLD to avoid\n * conflicts between resizing and treeification thresholds.\n */\n static final int MIN_TREEIFY_CAPACITY = 64;\n\n /**\n * Minimum number of rebinnings per transfer step. Ranges are\n * subdivided to allow multiple resizer threads. This value\n * serves as a lower bound to avoid resizers encountering\n * excessive memory contention. The value should be at least\n * DEFAULT_CAPACITY.\n */\n private static final int MIN_TRANSFER_STRIDE = 16;\n\n /**\n * The number of bits used for generation stamp in sizeCtl.\n * Must be at least 6 for 32bit arrays.\n */\n private static final int RESIZE_STAMP_BITS = 16;\n\n /**\n * The maximum number of threads that can help resize.\n * Must fit in 32 - RESIZE_STAMP_BITS bits.\n */\n private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;\n\n /**\n * The bit shift for recording size stamp in sizeCtl.\n */\n private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;\n\n /*\n * Encodings for Node hash fields. See above for explanation.\n */\n // hash for forwarding nodes\n static final int MOVED = -1;\n\n // hash for roots of trees\n static final int TREEBIN = -2;\n\n static final int RESERVED = -3;\n\n // usable bits of normal node hash\n static final int HASH_BITS = 0x7fffffff;\n\n /**\n * Number of CPUS, to place bounds on some sizings\n */\n static final int NCPU = Runtime.getRuntime().availableProcessors();\n\n /**\n * Serialized pseudo-fields, provided only for jdk7 compatibility.\n * @serialField segments Segment[]\n * The segments, each of which is a specialized hash table.\n * @serialField segmentMask int\n * Mask value for indexing into segments. The upper bits of a\n * key's hash code are used to choose the segment.\n * @serialField segmentShift int\n * Shift value for indexing within segments.\n */\n private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(\"segments\", Segment[].class), new ObjectStreamField(\"segmentMask\", Integer.TYPE), new ObjectStreamField(\"segmentShift\", Integer.TYPE) };\n\n /**\n * Key-value entry. This class is never exported out as a\n * user-mutable Map.Entry (i.e., one supporting setValue; see\n * MapEntry below), but can be used for read-only traversals used\n * in bulk tasks. Subclasses of Node with a negative hash field\n * are special, and contain null keys and values (but are never\n * exported). Otherwise, keys and vals are never null.\n */\n static class Node implements Map.Entry {\n\n final int hash;\n\n final K key;\n\n volatile V val;\n\n volatile Node next;\n\n Node(int hash, K key, V val) {\n this.hash = hash;\n this.key = key;\n this.val = val;\n }\n\n Node(int hash, K key, V val, Node next) {\n this(hash, key, val);\n this.next = next;\n }\n\n public final K getKey() {\n return key;\n }\n\n public final V getValue() {\n return val;\n }\n\n public final int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public final String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public final V setValue(V value) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean equals(Object o) {\n Object k, v, u;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == (u = val) || v.equals(u)));\n }\n\n /**\n * Virtualized support for map.get(); overridden in subclasses.\n */\n Node find(int h, Object k) {\n Node e = this;\n if (k != null) {\n do {\n K ek;\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n } while ((e = e.next) != null);\n }\n return null;\n }\n }\n\n /**\n * Spreads (XORs) higher bits of hash to lower and also forces top\n * bit to 0. Because the table uses power-of-two masking, sets of\n * hashes that vary only in bits above the current mask will\n * always collide. (Among known examples are sets of Float keys\n * holding consecutive whole numbers in small tables.) So we\n * apply a transform that spreads the impact of higher bits\n * downward. There is a tradeoff between speed, utility, and\n * quality of bit-spreading. Because many common sets of hashes\n * are already reasonably distributed (so don't benefit from\n * spreading), and because we use trees to handle large sets of\n * collisions in bins, we just XOR some shifted bits in the\n * cheapest possible way to reduce systematic lossage, as well as\n * to incorporate impact of the highest bits that would otherwise\n * never be used in index calculations because of table bounds.\n */\n static final int spread(int h) {\n return (h ^ (h >>> 16)) & HASH_BITS;\n }\n\n /**\n * Returns a power of two table size for the given desired capacity.\n * See Hackers Delight, sec 3.2\n */\n private static final int tableSizeFor(int c) {\n int n = -1 >>> Integer.numberOfLeadingZeros(c - 1);\n return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;\n }\n\n /**\n * Returns x's Class if it is of the form \"class C implements\n * Comparable\", else null.\n */\n static Class comparableClassFor(Object x) {\n if (x instanceof Comparable) {\n Class c;\n Type[] ts, as;\n ParameterizedType p;\n if (// bypass checks\n (c = x.getClass()) == String.class)\n return c;\n if ((ts = c.getGenericInterfaces()) != null) {\n for (Type t : ts) {\n if ((t instanceof ParameterizedType) && ((p = (ParameterizedType) t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && // type arg is c\n as[0] == c)\n return c;\n }\n }\n }\n return null;\n }\n\n /**\n * Returns k.compareTo(x) if x matches kc (k's screened comparable\n * class), else 0.\n */\n // for cast to Comparable\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n static int compareComparables(Class kc, Object k, Object x) {\n return (x == null || x.getClass() != kc ? 0 : ((Comparable) k).compareTo(x));\n }\n\n /* ---------------- Table element access -------------- */\n /*\n * Atomic access methods are used for table elements as well as\n * elements of in-progress next table while resizing. All uses of\n * the tab arguments must be null checked by callers. All callers\n * also paranoically precheck that tab's length is not zero (or an\n * equivalent check), thus ensuring that any index argument taking\n * the form of a hash value anded with (length - 1) is a valid\n * index. Note that, to be correct wrt arbitrary concurrency\n * errors by users, these checks must operate on local variables,\n * which accounts for some odd-looking inline assignments below.\n * Note that calls to setTabAt always occur within locked regions,\n * and so require only release ordering.\n */\n @SuppressWarnings(\"unchecked\")\n static final Node tabAt(Node[] tab, int i) {\n return (Node) U.getReferenceAcquire(tab, ((long) i << ASHIFT) + ABASE);\n }\n\n static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {\n return U.compareAndSetReference(tab, ((long) i << ASHIFT) + ABASE, c, v);\n }\n\n static final void setTabAt(Node[] tab, int i, Node v) {\n U.putReferenceRelease(tab, ((long) i << ASHIFT) + ABASE, v);\n }\n\n /**\n * The array of bins. Lazily initialized upon first insertion.\n * Size is always a power of two. Accessed directly by iterators.\n */\n transient volatile Node[] table;\n\n /**\n * The next table to use; non-null only while resizing.\n */\n private transient volatile Node[] nextTable;\n\n /**\n * Base counter value, used mainly when there is no contention,\n * but also as a fallback during table initialization\n * races. Updated via CAS.\n */\n private transient volatile long baseCount;\n\n /**\n * Table initialization and resizing control. When negative, the\n * table is being initialized or resized: -1 for initialization,\n * else -(1 + the number of active resizing threads). Otherwise,\n * when table is null, holds the initial table size to use upon\n * creation, or 0 for default. After initialization, holds the\n * next element count value upon which to resize the table.\n */\n private transient volatile int sizeCtl;\n\n /**\n * The next table index (plus one) to split while resizing.\n */\n private transient volatile int transferIndex;\n\n /**\n * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.\n */\n private transient volatile int cellsBusy;\n\n /**\n * Table of counter cells. When non-null, size is a power of 2.\n */\n private transient volatile CounterCell[] counterCells;\n\n // views\n private transient KeySetView keySet;\n\n private transient ValuesView values;\n\n private transient EntrySetView entrySet;\n\n /**\n * Creates a new, empty map with the default initial table size (16).\n */\n public ConcurrentHashMap() {\n }\n\n /**\n * Creates a new, empty map with an initial table size\n * accommodating the specified number of elements without the need\n * to dynamically resize.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n */\n public ConcurrentHashMap(int initialCapacity) {\n this(initialCapacity, LOAD_FACTOR, 1);\n }\n\n /**\n * Creates a new map with the same mappings as the given map.\n *\n * @param m the map\n */\n public ConcurrentHashMap(Map m) {\n this.sizeCtl = DEFAULT_CAPACITY;\n putAll(m);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}) and\n * initial table density ({@code loadFactor}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative or the load factor is nonpositive\n *\n * @since 1.6\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor) {\n this(initialCapacity, loadFactor, 1);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}), initial\n * table density ({@code loadFactor}), and number of concurrently\n * updating threads ({@code concurrencyLevel}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @param concurrencyLevel the estimated number of concurrently\n * updating threads. The implementation may use this value as\n * a sizing hint.\n * @throws IllegalArgumentException if the initial capacity is\n * negative or the load factor or concurrencyLevel are\n * nonpositive\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) {\n if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)\n throw new IllegalArgumentException();\n if (// Use at least as many bins\n initialCapacity < concurrencyLevel)\n // as estimated threads\n initialCapacity = concurrencyLevel;\n long size = (long) (1.0 + (long) initialCapacity / loadFactor);\n int cap = (size >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) size);\n this.sizeCtl = cap;\n }\n\n // Original (since JDK1.2) Map methods\n public int size() {\n long n = sumCount();\n return ((n < 0L) ? 0 : (n > (long) Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) n);\n }\n\n public boolean isEmpty() {\n // ignore transient negative values\n return sumCount() <= 0L;\n }\n\n /**\n * Returns the value to which the specified key is mapped,\n * or {@code null} if this map contains no mapping for the key.\n *\n *

More formally, if this map contains a mapping from a key\n * {@code k} to a value {@code v} such that {@code key.equals(k)},\n * then this method returns {@code v}; otherwise it returns\n * {@code null}. (There can be at most one such mapping.)\n *\n * @throws NullPointerException if the specified key is null\n */\n public V get(Object key) {\n Node[] tab;\n Node e, p;\n int n, eh;\n K ek;\n int h = spread(key.hashCode());\n if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) {\n if ((eh = e.hash) == h) {\n if ((ek = e.key) == key || (ek != null && key.equals(ek)))\n return e.val;\n } else if (eh < 0)\n return (p = e.find(h, key)) != null ? p.val : null;\n while ((e = e.next) != null) {\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek))))\n return e.val;\n }\n }\n return null;\n }\n\n /**\n * Tests if the specified object is a key in this table.\n *\n * @param key possible key\n * @return {@code true} if and only if the specified object\n * is a key in this table, as determined by the\n * {@code equals} method; {@code false} otherwise\n * @throws NullPointerException if the specified key is null\n */\n public boolean containsKey(Object key) {\n return get(key) != null;\n }\n\n /**\n * Returns {@code true} if this map maps one or more keys to the\n * specified value. Note: This method may require a full traversal\n * of the map, and is much slower than method {@code containsKey}.\n *\n * @param value value whose presence in this map is to be tested\n * @return {@code true} if this map maps one or more keys to the\n * specified value\n * @throws NullPointerException if the specified value is null\n */\n public boolean containsValue(Object value) {\n if (value == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V v;\n if ((v = p.val) == value || (v != null && value.equals(v)))\n return true;\n }\n }\n return false;\n }\n\n /**\n * Maps the specified key to the specified value in this table.\n * Neither the key nor the value can be null.\n *\n *

The value can be retrieved by calling the {@code get} method\n * with a key that is equal to the original key.\n *\n * @param key key with which the specified value is to be associated\n * @param value value to be associated with the specified key\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key or value is null\n */\n public V put(K key, V value) {\n return putVal(key, value, false);\n }\n\n /**\n * Implementation for put and putIfAbsent\n */\n final V putVal(K key, V value, boolean onlyIfAbsent) {\n if (key == null || value == null)\n throw new NullPointerException();\n int hash = spread(key.hashCode());\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {\n if (casTabAt(tab, i, null, new Node(hash, key, value)))\n // no lock when adding to empty bin\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n onlyIfAbsent && fh == hash && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n V oldVal = null;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n oldVal = e.val;\n if (!onlyIfAbsent)\n e.val = value;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n pred.next = new Node(hash, key, value);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n Node p;\n binCount = 2;\n if ((p = ((TreeBin) f).putTreeVal(hash, key, value)) != null) {\n oldVal = p.val;\n if (!onlyIfAbsent)\n p.val = value;\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (oldVal != null)\n return oldVal;\n break;\n }\n }\n }\n addCount(1L, binCount);\n return null;\n }\n\n /**\n * Copies all of the mappings from the specified map to this one.\n * These mappings replace any mappings that this map had for any of the\n * keys currently in the specified map.\n *\n * @param m mappings to be stored in this map\n */\n public void putAll(Map m) {\n tryPresize(m.size());\n for (Map.Entry e : m.entrySet()) putVal(e.getKey(), e.getValue(), false);\n }\n\n /**\n * Removes the key (and its corresponding value) from this map.\n * This method does nothing if the key is not in the map.\n *\n * @param key the key that needs to be removed\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key is null\n */\n public V remove(Object key) {\n return replaceNode(key, null, null);\n }\n\n /**\n * Implementation for the four public remove/replace methods:\n * Replaces node value with v, conditional upon match of cv if\n * non-null. If resulting value is null, delete.\n */\n final V replaceNode(Object key, V value, Object cv) {\n int hash = spread(key.hashCode());\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0 || (f = tabAt(tab, i = (n - 1) & hash)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n V oldVal = null;\n boolean validated = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n validated = true;\n for (Node e = f, pred = null; ; ) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n V ev = e.val;\n if (cv == null || cv == ev || (ev != null && cv.equals(ev))) {\n oldVal = ev;\n if (value != null)\n e.val = value;\n else if (pred != null)\n pred.next = e.next;\n else\n setTabAt(tab, i, e.next);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n validated = true;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(hash, key, null)) != null) {\n V pv = p.val;\n if (cv == null || cv == pv || (pv != null && cv.equals(pv))) {\n oldVal = pv;\n if (value != null)\n p.val = value;\n else if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (validated) {\n if (oldVal != null) {\n if (value == null)\n addCount(-1L, -1);\n return oldVal;\n }\n break;\n }\n }\n }\n return null;\n }\n\n /**\n * Removes all of the mappings from this map.\n */\n public void clear() {\n // negative number of deletions\n long delta = 0L;\n int i = 0;\n Node[] tab = table;\n while (tab != null && i < tab.length) {\n int fh;\n Node f = tabAt(tab, i);\n if (f == null)\n ++i;\n else if ((fh = f.hash) == MOVED) {\n tab = helpTransfer(tab, f);\n // restart\n i = 0;\n } else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node p = (fh >= 0 ? f : (f instanceof TreeBin) ? ((TreeBin) f).first : null);\n while (p != null) {\n --delta;\n p = p.next;\n }\n setTabAt(tab, i++, null);\n }\n }\n }\n }\n if (delta != 0L)\n addCount(delta, -1);\n }\n\n /**\n * Returns a {@link Set} view of the keys contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from this map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations. It does not support the {@code add} or\n * {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public KeySetView keySet() {\n KeySetView ks;\n if ((ks = keySet) != null)\n return ks;\n return keySet = new KeySetView(this, null);\n }\n\n /**\n * Returns a {@link Collection} view of the values contained in this map.\n * The collection is backed by the map, so changes to the map are\n * reflected in the collection, and vice-versa. The collection\n * supports element removal, which removes the corresponding\n * mapping from this map, via the {@code Iterator.remove},\n * {@code Collection.remove}, {@code removeAll},\n * {@code retainAll}, and {@code clear} operations. It does not\n * support the {@code add} or {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}\n * and {@link Spliterator#NONNULL}.\n *\n * @return the collection view\n */\n public Collection values() {\n ValuesView vs;\n if ((vs = values) != null)\n return vs;\n return values = new ValuesView(this);\n }\n\n /**\n * Returns a {@link Set} view of the mappings contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from the map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public Set> entrySet() {\n EntrySetView es;\n if ((es = entrySet) != null)\n return es;\n return entrySet = new EntrySetView(this);\n }\n\n /**\n * Returns the hash code value for this {@link Map}, i.e.,\n * the sum of, for each key-value pair in the map,\n * {@code key.hashCode() ^ value.hashCode()}.\n *\n * @return the hash code value for this map\n */\n public int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) h += p.key.hashCode() ^ p.val.hashCode();\n }\n return h;\n }\n\n /**\n * Returns a string representation of this map. The string\n * representation consists of a list of key-value mappings (in no\n * particular order) enclosed in braces (\"{@code {}}\"). Adjacent\n * mappings are separated by the characters {@code \", \"} (comma\n * and space). Each key-value mapping is rendered as the key\n * followed by an equals sign (\"{@code =}\") followed by the\n * associated value.\n *\n * @return a string representation of this map\n */\n public String toString() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n StringBuilder sb = new StringBuilder();\n sb.append('{');\n Node p;\n if ((p = it.advance()) != null) {\n for (; ; ) {\n K k = p.key;\n V v = p.val;\n sb.append(k == this ? \"(this Map)\" : k);\n sb.append('=');\n sb.append(v == this ? \"(this Map)\" : v);\n if ((p = it.advance()) == null)\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append('}').toString();\n }\n\n /**\n * Compares the specified object with this map for equality.\n * Returns {@code true} if the given object is a map with the same\n * mappings as this map. This operation may return misleading\n * results if either map is concurrently modified during execution\n * of this method.\n *\n * @param o object to be compared for equality with this map\n * @return {@code true} if the specified object is equal to this map\n */\n public boolean equals(Object o) {\n if (o != this) {\n if (!(o instanceof Map))\n return false;\n Map m = (Map) o;\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n for (Node p; (p = it.advance()) != null; ) {\n V val = p.val;\n Object v = m.get(p.key);\n if (v == null || (v != val && !v.equals(val)))\n return false;\n }\n for (Map.Entry e : m.entrySet()) {\n Object mk, mv, v;\n if ((mk = e.getKey()) == null || (mv = e.getValue()) == null || (v = get(mk)) == null || (mv != v && !mv.equals(v)))\n return false;\n }\n }\n return true;\n }\n\n /**\n * Stripped-down version of helper class used in previous version,\n * declared for the sake of serialization compatibility.\n */\n static class Segment extends ReentrantLock implements Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n final float loadFactor;\n\n Segment(float lf) {\n this.loadFactor = lf;\n }\n }\n\n /**\n * Saves this map to a stream (that is, serializes it).\n *\n * @param s the stream\n * @throws java.io.IOException if an I/O error occurs\n * @serialData\n * the serialized fields, followed by the key (Object) and value\n * (Object) for each key-value mapping, followed by a null pair.\n * The key-value mappings are emitted in no particular order.\n */\n private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {\n // For serialization compatibility\n // Emulate segment calculation from previous version of this class\n int sshift = 0;\n int ssize = 1;\n while (ssize < DEFAULT_CONCURRENCY_LEVEL) {\n ++sshift;\n ssize <<= 1;\n }\n int segmentShift = 32 - sshift;\n int segmentMask = ssize - 1;\n @SuppressWarnings(\"unchecked\")\n Segment[] segments = (Segment[]) new Segment[DEFAULT_CONCURRENCY_LEVEL];\n for (int i = 0; i < segments.length; ++i) segments[i] = new Segment(LOAD_FACTOR);\n java.io.ObjectOutputStream.PutField streamFields = s.putFields();\n streamFields.put(\"segments\", segments);\n streamFields.put(\"segmentShift\", segmentShift);\n streamFields.put(\"segmentMask\", segmentMask);\n s.writeFields();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n s.writeObject(p.key);\n s.writeObject(p.val);\n }\n }\n s.writeObject(null);\n s.writeObject(null);\n }\n\n /**\n * Reconstitutes this map from a stream (that is, deserializes it).\n * @param s the stream\n * @throws ClassNotFoundException if the class of a serialized object\n * could not be found\n * @throws java.io.IOException if an I/O error occurs\n */\n private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {\n /*\n * To improve performance in typical cases, we create nodes\n * while reading, then place in table once size is known.\n * However, we must also validate uniqueness and deal with\n * overpopulated bins while doing so, which requires\n * specialized versions of putVal mechanics.\n */\n // force exclusion for table construction\n sizeCtl = -1;\n s.defaultReadObject();\n long size = 0L;\n Node p = null;\n for (; ; ) {\n @SuppressWarnings(\"unchecked\")\n K k = (K) s.readObject();\n @SuppressWarnings(\"unchecked\")\n V v = (V) s.readObject();\n if (k != null && v != null) {\n p = new Node(spread(k.hashCode()), k, v, p);\n ++size;\n } else\n break;\n }\n if (size == 0L)\n sizeCtl = 0;\n else {\n long ts = (long) (1.0 + size / LOAD_FACTOR);\n int n = (ts >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) ts);\n @SuppressWarnings(\"unchecked\")\n Node[] tab = (Node[]) new Node[n];\n int mask = n - 1;\n long added = 0L;\n while (p != null) {\n boolean insertAtFront;\n Node next = p.next, first;\n int h = p.hash, j = h & mask;\n if ((first = tabAt(tab, j)) == null)\n insertAtFront = true;\n else {\n K k = p.key;\n if (first.hash < 0) {\n TreeBin t = (TreeBin) first;\n if (t.putTreeVal(h, k, p.val) == null)\n ++added;\n insertAtFront = false;\n } else {\n int binCount = 0;\n insertAtFront = true;\n Node q;\n K qk;\n for (q = first; q != null; q = q.next) {\n if (q.hash == h && ((qk = q.key) == k || (qk != null && k.equals(qk)))) {\n insertAtFront = false;\n break;\n }\n ++binCount;\n }\n if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {\n insertAtFront = false;\n ++added;\n p.next = first;\n TreeNode hd = null, tl = null;\n for (q = p; q != null; q = q.next) {\n TreeNode t = new TreeNode(q.hash, q.key, q.val, null, null);\n if ((t.prev = tl) == null)\n hd = t;\n else\n tl.next = t;\n tl = t;\n }\n setTabAt(tab, j, new TreeBin(hd));\n }\n }\n }\n if (insertAtFront) {\n ++added;\n p.next = first;\n setTabAt(tab, j, p);\n }\n p = next;\n }\n table = tab;\n sizeCtl = n - (n >>> 2);\n baseCount = added;\n }\n }\n\n // ConcurrentMap methods\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V putIfAbsent(K key, V value) {\n return putVal(key, value, true);\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object key, Object value) {\n if (key == null)\n throw new NullPointerException();\n return value != null && replaceNode(key, null, value) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if any of the arguments are null\n */\n public boolean replace(K key, V oldValue, V newValue) {\n if (key == null || oldValue == null || newValue == null)\n throw new NullPointerException();\n return replaceNode(key, newValue, oldValue) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V replace(K key, V value) {\n if (key == null || value == null)\n throw new NullPointerException();\n return replaceNode(key, value, null);\n }\n\n // Overrides of JDK8+ Map extension method defaults\n /**\n * Returns the value to which the specified key is mapped, or the\n * given default value if this map contains no mapping for the\n * key.\n *\n * @param key the key whose associated value is to be returned\n * @param defaultValue the value to return if this map contains\n * no mapping for the given key\n * @return the mapping for the key, if present; else the default value\n * @throws NullPointerException if the specified key is null\n */\n public V getOrDefault(Object key, V defaultValue) {\n V v;\n return (v = get(key)) == null ? defaultValue : v;\n }\n\n public void forEach(BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n action.accept(p.key, p.val);\n }\n }\n }\n\n public void replaceAll(BiFunction function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V oldValue = p.val;\n for (K key = p.key; ; ) {\n V newValue = function.apply(key, oldValue);\n if (newValue == null)\n throw new NullPointerException();\n if (replaceNode(key, newValue, oldValue) != null || (oldValue = get(key)) == null)\n break;\n }\n }\n }\n }\n\n boolean removeEntryIf(Predicate> function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n ", "post_mask_code": "\n }\n return removed;\n }\n\n boolean removeValueIf(Predicate function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n if (function.test(v) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n /**\n * If the specified key is not already associated with a value,\n * attempts to compute its value using the given mapping function\n * and enters it into this map unless {@code null}. The entire\n * method invocation is performed atomically. The supplied\n * function is invoked exactly once per invocation of this method\n * if the key is absent, else not at all. Some attempted update\n * operations on this map by other threads may be blocked while\n * computation is in progress, so the computation should be short\n * and simple.\n *\n *

The mapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param mappingFunction the function to compute a value\n * @return the current (existing or computed) value associated with\n * the specified key, or null if the computed value is null\n * @throws NullPointerException if the specified key or mappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the mappingFunction does so,\n * in which case the mapping is left unestablished\n */\n public V computeIfAbsent(K key, Function mappingFunction) {\n if (key == null || mappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = mappingFunction.apply(key)) != null)\n node = new Node(h, key, val);\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n fh == h && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n boolean added = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = e.val;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n if ((val = mappingFunction.apply(key)) != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n added = true;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null)\n val = p.val;\n else if ((val = mappingFunction.apply(key)) != null) {\n added = true;\n t.putTreeVal(h, key, val);\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (!added)\n return val;\n break;\n }\n }\n }\n if (val != null)\n addCount(1L, binCount);\n return val;\n }\n\n /**\n * If the value for the specified key is present, attempts to\n * compute a new mapping given the key and its current mapped\n * value. The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method if the key is present, else not at all. Some\n * attempted update operations on this map by other threads may be\n * blocked while computation is in progress, so the computation\n * should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which a value may be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V computeIfPresent(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null) {\n val = remappingFunction.apply(key, p.val);\n if (val != null)\n p.val = val;\n else {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0)\n break;\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * Attempts to compute a mapping for the specified key and its\n * current mapped value (or {@code null} if there is no current\n * mapping). The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method. Some attempted update operations on this map by\n * other threads may be blocked while computation is in progress,\n * so the computation should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V compute(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = remappingFunction.apply(key, null)) != null) {\n delta = 1;\n node = new Node(h, key, val);\n }\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n val = remappingFunction.apply(key, null);\n if (val != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n delta = 1;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 1;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null)\n p = r.findTreeNode(h, key, null);\n else\n p = null;\n V pv = (p == null) ? null : p.val;\n val = remappingFunction.apply(key, pv);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * If the specified key is not already associated with a\n * (non-null) value, associates it with the given value.\n * Otherwise, replaces the value with the results of the given\n * remapping function, or removes if {@code null}. The entire\n * method invocation is performed atomically. Some attempted\n * update operations on this map by other threads may be blocked\n * while computation is in progress, so the computation should be\n * short and simple, and must not attempt to update any other\n * mappings of this Map.\n *\n * @param key key with which the specified value is to be associated\n * @param value the value to use if absent\n * @param remappingFunction the function to recompute a value if present\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or the\n * remappingFunction is null\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V merge(K key, V value, BiFunction remappingFunction) {\n if (key == null || value == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n if (casTabAt(tab, i, null, new Node(h, key, value))) {\n delta = 1;\n val = value;\n break;\n }\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(e.val, value);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n delta = 1;\n val = value;\n pred.next = new Node(h, key, val);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r = t.root;\n TreeNode p = (r == null) ? null : r.findTreeNode(h, key, null);\n val = (p == null) ? value : remappingFunction.apply(p.val, value);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n // Hashtable legacy methods\n /**\n * Tests if some key maps into the specified value in this table.\n *\n *

Note that this method is identical in functionality to\n * {@link #containsValue(Object)}, and exists solely to ensure\n * full compatibility with class {@link java.util.Hashtable},\n * which supported this method prior to introduction of the\n * Java Collections Framework.\n *\n * @param value a value to search for\n * @return {@code true} if and only if some key maps to the\n * {@code value} argument in this table as\n * determined by the {@code equals} method;\n * {@code false} otherwise\n * @throws NullPointerException if the specified value is null\n */\n public boolean contains(Object value) {\n return containsValue(value);\n }\n\n /**\n * Returns an enumeration of the keys in this table.\n *\n * @return an enumeration of the keys in this table\n * @see #keySet()\n */\n public Enumeration keys() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, this);\n }\n\n /**\n * Returns an enumeration of the values in this table.\n *\n * @return an enumeration of the values in this table\n * @see #values()\n */\n public Enumeration elements() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, this);\n }\n\n // ConcurrentHashMap-only methods\n /**\n * Returns the number of mappings. This method should be used\n * instead of {@link #size} because a ConcurrentHashMap may\n * contain more mappings than can be represented as an int. The\n * value returned is an estimate; the actual count may differ if\n * there are concurrent insertions or removals.\n *\n * @return the number of mappings\n * @since 1.8\n */\n public long mappingCount() {\n long n = sumCount();\n // ignore transient negative values\n return (n < 0L) ? 0L : n;\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param the element type of the returned set\n * @return the new set\n * @since 1.8\n */\n public static KeySetView newKeySet() {\n return new KeySetView(new ConcurrentHashMap(), Boolean.TRUE);\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @param the element type of the returned set\n * @return the new set\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n * @since 1.8\n */\n public static KeySetView newKeySet(int initialCapacity) {\n return new KeySetView(new ConcurrentHashMap(initialCapacity), Boolean.TRUE);\n }\n\n /**\n * Returns a {@link Set} view of the keys in this map, using the\n * given common mapped value for any additions (i.e., {@link\n * Collection#add} and {@link Collection#addAll(Collection)}).\n * This is of course only appropriate if it is acceptable to use\n * the same value for all additions from this view.\n *\n * @param mappedValue the mapped value to use for any additions\n * @return the set view\n * @throws NullPointerException if the mappedValue is null\n */\n public KeySetView keySet(V mappedValue) {\n if (mappedValue == null)\n throw new NullPointerException();\n return new KeySetView(this, mappedValue);\n }\n\n /**\n * A node inserted at head of bins during transfer operations.\n */\n static final class ForwardingNode extends Node {\n\n final Node[] nextTable;\n\n ForwardingNode(Node[] tab) {\n super(MOVED, null, null);\n this.nextTable = tab;\n }\n\n Node find(int h, Object k) {\n // loop to avoid arbitrarily deep recursion on forwarding nodes\n outer: for (Node[] tab = nextTable; ; ) {\n Node e;\n int n;\n if (k == null || tab == null || (n = tab.length) == 0 || (e = tabAt(tab, (n - 1) & h)) == null)\n return null;\n for (; ; ) {\n int eh;\n K ek;\n if ((eh = e.hash) == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n if (eh < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n continue outer;\n } else\n return e.find(h, k);\n }\n if ((e = e.next) == null)\n return null;\n }\n }\n }\n }\n\n /**\n * A place-holder node used in computeIfAbsent and compute.\n */\n static final class ReservationNode extends Node {\n\n ReservationNode() {\n super(RESERVED, null, null);\n }\n\n Node find(int h, Object k) {\n return null;\n }\n }\n\n /* ---------------- Table Initialization and Resizing -------------- */\n /**\n * Returns the stamp bits for resizing a table of size n.\n * Must be negative when shifted left by RESIZE_STAMP_SHIFT.\n */\n static final int resizeStamp(int n) {\n return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));\n }\n\n /**\n * Initializes table, using the size recorded in sizeCtl.\n */\n private final Node[] initTable() {\n Node[] tab;\n int sc;\n while ((tab = table) == null || tab.length == 0) {\n if ((sc = sizeCtl) < 0)\n // lost initialization race; just spin\n Thread.yield();\n else if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if ((tab = table) == null || tab.length == 0) {\n int n = (sc > 0) ? sc : DEFAULT_CAPACITY;\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = tab = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n break;\n }\n }\n return tab;\n }\n\n /**\n * Adds to count, and if table is too small and not already\n * resizing, initiates transfer. If already resizing, helps\n * perform transfer if work is available. Rechecks occupancy\n * after a transfer to see if another resize is already needed\n * because resizings are lagging additions.\n *\n * @param x the count to add\n * @param check if <0, don't check resize, if <= 1 only check if uncontended\n */\n private final void addCount(long x, int check) {\n CounterCell[] cs;\n long b, s;\n if ((cs = counterCells) != null || !U.compareAndSetLong(this, BASECOUNT, b = baseCount, s = b + x)) {\n CounterCell c;\n long v;\n int m;\n boolean uncontended = true;\n if (cs == null || (m = cs.length - 1) < 0 || (c = cs[ThreadLocalRandom.getProbe() & m]) == null || !(uncontended = U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))) {\n fullAddCount(x, uncontended);\n return;\n }\n if (check <= 1)\n return;\n s = sumCount();\n }\n if (check >= 0) {\n Node[] tab, nt;\n int n, sc;\n while (s >= (long) (sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) {\n int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT;\n if (sc < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || (nt = nextTable) == null || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1))\n transfer(tab, nt);\n } else if (U.compareAndSetInt(this, SIZECTL, sc, rs + 2))\n transfer(tab, null);\n s = sumCount();\n }\n }\n }\n\n /**\n * Helps transfer if a resize is in progress.\n */\n final Node[] helpTransfer(Node[] tab, Node f) {\n Node[] nextTab;\n int sc;\n if (tab != null && (f instanceof ForwardingNode) && (nextTab = ((ForwardingNode) f).nextTable) != null) {\n int rs = resizeStamp(tab.length) << RESIZE_STAMP_SHIFT;\n while (nextTab == nextTable && table == tab && (sc = sizeCtl) < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1)) {\n transfer(tab, nextTab);\n break;\n }\n }\n return nextTab;\n }\n return table;\n }\n\n /**\n * Tries to presize table to accommodate the given number of elements.\n *\n * @param size number of elements (doesn't need to be perfectly accurate)\n */\n private final void tryPresize(int size) {\n int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(size + (size >>> 1) + 1);\n int sc;\n while ((sc = sizeCtl) >= 0) {\n Node[] tab = table;\n int n;\n if (tab == null || (n = tab.length) == 0) {\n n = (sc > c) ? sc : c;\n if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if (table == tab) {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n }\n } else if (c <= sc || n >= MAXIMUM_CAPACITY)\n break;\n else if (tab == table) {\n int rs = resizeStamp(n);\n if (U.compareAndSetInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2))\n transfer(tab, null);\n }\n }\n }\n\n /**\n * Moves and/or copies the nodes in each bin to new table. See\n * above for explanation.\n */\n private final void transfer(Node[] tab, Node[] nextTab) {\n int n = tab.length, stride;\n if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)\n // subdivide range\n stride = MIN_TRANSFER_STRIDE;\n if (nextTab == null) {\n // initiating\n try {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n << 1];\n nextTab = nt;\n } catch (Throwable ex) {\n // try to cope with OOME\n sizeCtl = Integer.MAX_VALUE;\n return;\n }\n nextTable = nextTab;\n transferIndex = n;\n }\n int nextn = nextTab.length;\n ForwardingNode fwd = new ForwardingNode(nextTab);\n boolean advance = true;\n // to ensure sweep before committing nextTab\n boolean finishing = false;\n for (int i = 0, bound = 0; ; ) {\n Node f;\n int fh;\n while (advance) {\n int nextIndex, nextBound;\n if (--i >= bound || finishing)\n advance = false;\n else if ((nextIndex = transferIndex) <= 0) {\n i = -1;\n advance = false;\n } else if (U.compareAndSetInt(this, TRANSFERINDEX, nextIndex, nextBound = (nextIndex > stride ? nextIndex - stride : 0))) {\n bound = nextBound;\n i = nextIndex - 1;\n advance = false;\n }\n }\n if (i < 0 || i >= n || i + n >= nextn) {\n int sc;\n if (finishing) {\n nextTable = null;\n table = nextTab;\n sizeCtl = (n << 1) - (n >>> 1);\n return;\n }\n if (U.compareAndSetInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {\n if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)\n return;\n finishing = advance = true;\n // recheck before commit\n i = n;\n }\n } else if ((f = tabAt(tab, i)) == null)\n advance = casTabAt(tab, i, null, fwd);\n else if ((fh = f.hash) == MOVED)\n // already processed\n advance = true;\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node ln, hn;\n if (fh >= 0) {\n int runBit = fh & n;\n Node lastRun = f;\n for (Node p = f.next; p != null; p = p.next) {\n int b = p.hash & n;\n if (b != runBit) {\n runBit = b;\n lastRun = p;\n }\n }\n if (runBit == 0) {\n ln = lastRun;\n hn = null;\n } else {\n hn = lastRun;\n ln = null;\n }\n for (Node p = f; p != lastRun; p = p.next) {\n int ph = p.hash;\n K pk = p.key;\n V pv = p.val;\n if ((ph & n) == 0)\n ln = new Node(ph, pk, pv, ln);\n else\n hn = new Node(ph, pk, pv, hn);\n }\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof TreeBin) {\n TreeBin t = (TreeBin) f;\n TreeNode lo = null, loTail = null;\n TreeNode hi = null, hiTail = null;\n int lc = 0, hc = 0;\n for (Node e = t.first; e != null; e = e.next) {\n int h = e.hash;\n TreeNode p = new TreeNode(h, e.key, e.val, null, null);\n if ((h & n) == 0) {\n if ((p.prev = loTail) == null)\n lo = p;\n else\n loTail.next = p;\n loTail = p;\n ++lc;\n } else {\n if ((p.prev = hiTail) == null)\n hi = p;\n else\n hiTail.next = p;\n hiTail = p;\n ++hc;\n }\n }\n ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : (hc != 0) ? new TreeBin(lo) : t;\n hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : (lc != 0) ? new TreeBin(hi) : t;\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n }\n }\n }\n\n /**\n * A padded cell for distributing counts. Adapted from LongAdder\n * and Striped64. See their internal docs for explanation.\n */\n @jdk.internal.vm.annotation.Contended\n static final class CounterCell {\n\n volatile long value;\n\n CounterCell(long x) {\n value = x;\n }\n }\n\n final long sumCount() {\n CounterCell[] cs = counterCells;\n long sum = baseCount;\n if (cs != null) {\n for (CounterCell c : cs) if (c != null)\n sum += c.value;\n }\n return sum;\n }\n\n // See LongAdder version for explanation\n private final void fullAddCount(long x, boolean wasUncontended) {\n int h;\n if ((h = ThreadLocalRandom.getProbe()) == 0) {\n // force initialization\n ThreadLocalRandom.localInit();\n h = ThreadLocalRandom.getProbe();\n wasUncontended = true;\n }\n // True if last slot nonempty\n boolean collide = false;\n for (; ; ) {\n CounterCell[] cs;\n CounterCell c;\n int n;\n long v;\n if ((cs = counterCells) != null && (n = cs.length) > 0) {\n if ((c = cs[(n - 1) & h]) == null) {\n if (cellsBusy == 0) {\n // Try to attach new Cell\n // Optimistic create\n CounterCell r = new CounterCell(x);\n if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean created = false;\n try {\n // Recheck under lock\n CounterCell[] rs;\n int m, j;\n if ((rs = counterCells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) {\n rs[j] = r;\n created = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (created)\n break;\n // Slot is now non-empty\n continue;\n }\n }\n collide = false;\n } else if (// CAS already known to fail\n !wasUncontended)\n // Continue after rehash\n wasUncontended = true;\n else if (U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))\n break;\n else if (counterCells != cs || n >= NCPU)\n // At max size or stale\n collide = false;\n else if (!collide)\n collide = true;\n else if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n try {\n if (// Expand table unless stale\n counterCells == cs)\n counterCells = Arrays.copyOf(cs, n << 1);\n } finally {\n cellsBusy = 0;\n }\n collide = false;\n // Retry with expanded table\n continue;\n }\n h = ThreadLocalRandom.advanceProbe(h);\n } else if (cellsBusy == 0 && counterCells == cs && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean init = false;\n try {\n // Initialize table\n if (counterCells == cs) {\n CounterCell[] rs = new CounterCell[2];\n rs[h & 1] = new CounterCell(x);\n counterCells = rs;\n init = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (init)\n break;\n } else if (U.compareAndSetLong(this, BASECOUNT, v = baseCount, v + x))\n // Fall back on using base\n break;\n }\n }\n\n /**\n * Replaces all linked nodes in bin at given index unless table is\n * too small, in which case resizes instead.\n */\n private final void treeifyBin(Node[] tab, int index) {\n Node b;\n int n;\n if (tab != null) {\n if ((n = tab.length) < MIN_TREEIFY_CAPACITY)\n tryPresize(n << 1);\n else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {\n synchronized (b) {\n if (tabAt(tab, index) == b) {\n TreeNode hd = null, tl = null;\n for (Node e = b; e != null; e = e.next) {\n TreeNode p = new TreeNode(e.hash, e.key, e.val, null, null);\n if ((p.prev = tl) == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n setTabAt(tab, index, new TreeBin(hd));\n }\n }\n }\n }\n }\n\n /**\n * Returns a list of non-TreeNodes replacing those in given list.\n */\n static Node untreeify(Node b) {\n Node hd = null, tl = null;\n for (Node q = b; q != null; q = q.next) {\n Node p = new Node(q.hash, q.key, q.val);\n if (tl == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n return hd;\n }\n\n /**\n * Nodes for use in TreeBins.\n */\n static final class TreeNode extends Node {\n\n // red-black tree links\n TreeNode parent;\n\n TreeNode left;\n\n TreeNode right;\n\n // needed to unlink next upon deletion\n TreeNode prev;\n\n boolean red;\n\n TreeNode(int hash, K key, V val, Node next, TreeNode parent) {\n super(hash, key, val, next);\n this.parent = parent;\n }\n\n Node find(int h, Object k) {\n return findTreeNode(h, k, null);\n }\n\n /**\n * Returns the TreeNode (or null if not found) for the given key\n * starting at given root.\n */\n final TreeNode findTreeNode(int h, Object k, Class kc) {\n if (k != null) {\n TreeNode p = this;\n do {\n int ph, dir;\n K pk;\n TreeNode q;\n TreeNode pl = p.left, pr = p.right;\n if ((ph = p.hash) > h)\n p = pl;\n else if (ph < h)\n p = pr;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if (pl == null)\n p = pr;\n else if (pr == null)\n p = pl;\n else if ((kc != null || (kc = comparableClassFor(k)) != null) && (dir = compareComparables(kc, k, pk)) != 0)\n p = (dir < 0) ? pl : pr;\n else if ((q = pr.findTreeNode(h, k, kc)) != null)\n return q;\n else\n p = pl;\n } while (p != null);\n }\n return null;\n }\n }\n\n /**\n * TreeNodes used at the heads of bins. TreeBins do not hold user\n * keys or values, but instead point to list of TreeNodes and\n * their root. They also maintain a parasitic read-write lock\n * forcing writers (who hold bin lock) to wait for readers (who do\n * not) to complete before tree restructuring operations.\n */\n static final class TreeBin extends Node {\n\n TreeNode root;\n\n volatile TreeNode first;\n\n volatile Thread waiter;\n\n volatile int lockState;\n\n // values for lockState\n // set while holding write lock\n static final int WRITER = 1;\n\n // set when waiting for write lock\n static final int WAITER = 2;\n\n // increment value for setting read lock\n static final int READER = 4;\n\n /**\n * Tie-breaking utility for ordering insertions when equal\n * hashCodes and non-comparable. We don't require a total\n * order, just a consistent insertion rule to maintain\n * equivalence across rebalancings. Tie-breaking further than\n * necessary simplifies testing a bit.\n */\n static int tieBreakOrder(Object a, Object b) {\n int d;\n if (a == null || b == null || (d = a.getClass().getName().compareTo(b.getClass().getName())) == 0)\n d = (System.identityHashCode(a) <= System.identityHashCode(b) ? -1 : 1);\n return d;\n }\n\n /**\n * Creates bin with initial set of nodes headed by b.\n */\n TreeBin(TreeNode b) {\n super(TREEBIN, null, null);\n this.first = b;\n TreeNode r = null;\n for (TreeNode x = b, next; x != null; x = next) {\n next = (TreeNode) x.next;\n x.left = x.right = null;\n if (r == null) {\n x.parent = null;\n x.red = false;\n r = x;\n } else {\n K k = x.key;\n int h = x.hash;\n Class kc = null;\n for (TreeNode p = r; ; ) {\n int dir, ph;\n K pk = p.key;\n if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0)\n dir = tieBreakOrder(k, pk);\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n x.parent = xp;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n r = balanceInsertion(r, x);\n break;\n }\n }\n }\n }\n this.root = r;\n assert checkInvariants(root);\n }\n\n /**\n * Acquires write lock for tree restructuring.\n */\n private final void lockRoot() {\n if (!U.compareAndSetInt(this, LOCKSTATE, 0, WRITER))\n // offload to separate method\n contendedLock();\n }\n\n /**\n * Releases write lock for tree restructuring.\n */\n private final void unlockRoot() {\n lockState = 0;\n }\n\n /**\n * Possibly blocks awaiting root lock.\n */\n private final void contendedLock() {\n boolean waiting = false;\n for (int s; ; ) {\n if (((s = lockState) & ~WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, WRITER)) {\n if (waiting)\n waiter = null;\n return;\n }\n } else if ((s & WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, s | WAITER)) {\n waiting = true;\n waiter = Thread.currentThread();\n }\n } else if (waiting)\n LockSupport.park(this);\n }\n }\n\n /**\n * Returns matching node or null if none. Tries to search\n * using tree comparisons from root, but continues linear\n * search when lock not available.\n */\n final Node find(int h, Object k) {\n if (k != null) {\n for (Node e = first; e != null; ) {\n int s;\n K ek;\n if (((s = lockState) & (WAITER | WRITER)) != 0) {\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n e = e.next;\n } else if (U.compareAndSetInt(this, LOCKSTATE, s, s + READER)) {\n TreeNode r, p;\n try {\n p = ((r = root) == null ? null : r.findTreeNode(h, k, null));\n } finally {\n Thread w;\n if (U.getAndAddInt(this, LOCKSTATE, -READER) == (READER | WAITER) && (w = waiter) != null)\n LockSupport.unpark(w);\n }\n return p;\n }\n }\n }\n return null;\n }\n\n /**\n * Finds or adds a node.\n * @return null if added\n */\n final TreeNode putTreeVal(int h, K k, V v) {\n Class kc = null;\n boolean searched = false;\n for (TreeNode p = root; ; ) {\n int dir, ph;\n K pk;\n if (p == null) {\n first = root = new TreeNode(h, k, v, null, null);\n break;\n } else if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) {\n if (!searched) {\n TreeNode q, ch;\n searched = true;\n if (((ch = p.left) != null && (q = ch.findTreeNode(h, k, kc)) != null) || ((ch = p.right) != null && (q = ch.findTreeNode(h, k, kc)) != null))\n return q;\n }\n dir = tieBreakOrder(k, pk);\n }\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n TreeNode x, f = first;\n first = x = new TreeNode(h, k, v, f, xp);\n if (f != null)\n f.prev = x;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n if (!xp.red)\n x.red = true;\n else {\n lockRoot();\n try {\n root = balanceInsertion(root, x);\n } finally {\n unlockRoot();\n }\n }\n break;\n }\n }\n assert checkInvariants(root);\n return null;\n }\n\n /**\n * Removes the given node, that must be present before this\n * call. This is messier than typical red-black deletion code\n * because we cannot swap the contents of an interior node\n * with a leaf successor that is pinned by \"next\" pointers\n * that are accessible independently of lock. So instead we\n * swap the tree linkages.\n *\n * @return true if now too small, so should be untreeified\n */\n final boolean removeTreeNode(TreeNode p) {\n TreeNode next = (TreeNode) p.next;\n // unlink traversal pointers\n TreeNode pred = p.prev;\n TreeNode r, rl;\n if (pred == null)\n first = next;\n else\n pred.next = next;\n if (next != null)\n next.prev = pred;\n if (first == null) {\n root = null;\n return true;\n }\n if (// too small\n (r = root) == null || r.right == null || (rl = r.left) == null || rl.left == null)\n return true;\n lockRoot();\n try {\n TreeNode replacement;\n TreeNode pl = p.left;\n TreeNode pr = p.right;\n if (pl != null && pr != null) {\n TreeNode s = pr, sl;\n while (// find successor\n (sl = s.left) != null) s = sl;\n // swap colors\n boolean c = s.red;\n // swap colors\n s.red = p.red;\n // swap colors\n p.red = c;\n TreeNode sr = s.right;\n TreeNode pp = p.parent;\n if (s == pr) {\n // p was s's direct parent\n p.parent = s;\n s.right = p;\n } else {\n TreeNode sp = s.parent;\n if ((p.parent = sp) != null) {\n if (s == sp.left)\n sp.left = p;\n else\n sp.right = p;\n }\n if ((s.right = pr) != null)\n pr.parent = s;\n }\n p.left = null;\n if ((p.right = sr) != null)\n sr.parent = p;\n if ((s.left = pl) != null)\n pl.parent = s;\n if ((s.parent = pp) == null)\n r = s;\n else if (p == pp.left)\n pp.left = s;\n else\n pp.right = s;\n if (sr != null)\n replacement = sr;\n else\n replacement = p;\n } else if (pl != null)\n replacement = pl;\n else if (pr != null)\n replacement = pr;\n else\n replacement = p;\n if (replacement != p) {\n TreeNode pp = replacement.parent = p.parent;\n if (pp == null)\n r = replacement;\n else if (p == pp.left)\n pp.left = replacement;\n else\n pp.right = replacement;\n p.left = p.right = p.parent = null;\n }\n root = (p.red) ? r : balanceDeletion(r, replacement);\n if (p == replacement) {\n // detach pointers\n TreeNode pp;\n if ((pp = p.parent) != null) {\n if (p == pp.left)\n pp.left = null;\n else if (p == pp.right)\n pp.right = null;\n p.parent = null;\n }\n }\n } finally {\n unlockRoot();\n }\n assert checkInvariants(root);\n return false;\n }\n\n // Red-black tree methods, all adapted from CLR\n static TreeNode rotateLeft(TreeNode root, TreeNode p) {\n TreeNode r, pp, rl;\n if (p != null && (r = p.right) != null) {\n if ((rl = p.right = r.left) != null)\n rl.parent = p;\n if ((pp = r.parent = p.parent) == null)\n (root = r).red = false;\n else if (pp.left == p)\n pp.left = r;\n else\n pp.right = r;\n r.left = p;\n p.parent = r;\n }\n return root;\n }\n\n static TreeNode rotateRight(TreeNode root, TreeNode p) {\n TreeNode l, pp, lr;\n if (p != null && (l = p.left) != null) {\n if ((lr = p.left = l.right) != null)\n lr.parent = p;\n if ((pp = l.parent = p.parent) == null)\n (root = l).red = false;\n else if (pp.right == p)\n pp.right = l;\n else\n pp.left = l;\n l.right = p;\n p.parent = l;\n }\n return root;\n }\n\n static TreeNode balanceInsertion(TreeNode root, TreeNode x) {\n x.red = true;\n for (TreeNode xp, xpp, xppl, xppr; ; ) {\n if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (!xp.red || (xpp = xp.parent) == null)\n return root;\n if (xp == (xppl = xpp.left)) {\n if ((xppr = xpp.right) != null && xppr.red) {\n xppr.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.right) {\n root = rotateLeft(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateRight(root, xpp);\n }\n }\n }\n } else {\n if (xppl != null && xppl.red) {\n xppl.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.left) {\n root = rotateRight(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateLeft(root, xpp);\n }\n }\n }\n }\n }\n }\n\n static TreeNode balanceDeletion(TreeNode root, TreeNode x) {\n for (TreeNode xp, xpl, xpr; ; ) {\n if (x == null || x == root)\n return root;\n else if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (x.red) {\n x.red = false;\n return root;\n } else if ((xpl = xp.left) == x) {\n if ((xpr = xp.right) != null && xpr.red) {\n xpr.red = false;\n xp.red = true;\n root = rotateLeft(root, xp);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr == null)\n x = xp;\n else {\n TreeNode sl = xpr.left, sr = xpr.right;\n if ((sr == null || !sr.red) && (sl == null || !sl.red)) {\n xpr.red = true;\n x = xp;\n } else {\n if (sr == null || !sr.red) {\n if (sl != null)\n sl.red = false;\n xpr.red = true;\n root = rotateRight(root, xpr);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr != null) {\n xpr.red = (xp == null) ? false : xp.red;\n if ((sr = xpr.right) != null)\n sr.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateLeft(root, xp);\n }\n x = root;\n }\n }\n } else {\n // symmetric\n if (xpl != null && xpl.red) {\n xpl.red = false;\n xp.red = true;\n root = rotateRight(root, xp);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl == null)\n x = xp;\n else {\n TreeNode sl = xpl.left, sr = xpl.right;\n if ((sl == null || !sl.red) && (sr == null || !sr.red)) {\n xpl.red = true;\n x = xp;\n } else {\n if (sl == null || !sl.red) {\n if (sr != null)\n sr.red = false;\n xpl.red = true;\n root = rotateLeft(root, xpl);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl != null) {\n xpl.red = (xp == null) ? false : xp.red;\n if ((sl = xpl.left) != null)\n sl.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateRight(root, xp);\n }\n x = root;\n }\n }\n }\n }\n }\n\n /**\n * Checks invariants recursively for the tree of Nodes rooted at t.\n */\n static boolean checkInvariants(TreeNode t) {\n TreeNode tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode) t.next;\n if (tb != null && tb.next != t)\n return false;\n if (tn != null && tn.prev != t)\n return false;\n if (tp != null && t != tp.left && t != tp.right)\n return false;\n if (tl != null && (tl.parent != t || tl.hash > t.hash))\n return false;\n if (tr != null && (tr.parent != t || tr.hash < t.hash))\n return false;\n if (t.red && tl != null && tl.red && tr != null && tr.red)\n return false;\n if (tl != null && !checkInvariants(tl))\n return false;\n if (tr != null && !checkInvariants(tr))\n return false;\n return true;\n }\n\n private static final long LOCKSTATE = U.objectFieldOffset(TreeBin.class, \"lockState\");\n }\n\n /**\n * Records the table, its length, and current traversal index for a\n * traverser that must process a region of a forwarded table before\n * proceeding with current table.\n */\n static final class TableStack {\n\n int length;\n\n int index;\n\n Node[] tab;\n\n TableStack next;\n }\n\n /**\n * Encapsulates traversal for methods such as containsValue; also\n * serves as a base class for other iterators and spliterators.\n *\n * Method advance visits once each still-valid node that was\n * reachable upon iterator construction. It might miss some that\n * were added to a bin after the bin was visited, which is OK wrt\n * consistency guarantees. Maintaining this property in the face\n * of possible ongoing resizes requires a fair amount of\n * bookkeeping state that is difficult to optimize away amidst\n * volatile accesses. Even so, traversal maintains reasonable\n * throughput.\n *\n * Normally, iteration proceeds bin-by-bin traversing lists.\n * However, if the table has been resized, then all future steps\n * must traverse both the bin at the current index as well as at\n * (index + baseSize); and so on for further resizings. To\n * paranoically cope with potential sharing by users of iterators\n * across threads, iteration terminates if a bounds checks fails\n * for a table read.\n */\n static class Traverser {\n\n // current table; updated if resized\n Node[] tab;\n\n // the next entry to use\n Node next;\n\n // to save/restore on ForwardingNodes\n TableStack stack, spare;\n\n // index of bin to use next\n int index;\n\n // current index of initial table\n int baseIndex;\n\n // index bound for initial table\n int baseLimit;\n\n // initial table size\n final int baseSize;\n\n Traverser(Node[] tab, int size, int index, int limit) {\n this.tab = tab;\n this.baseSize = size;\n this.baseIndex = this.index = index;\n this.baseLimit = limit;\n this.next = null;\n }\n\n /**\n * Advances if possible, returning next valid node, or null if none.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n // must use locals in checks\n Node[] t;\n // must use locals in checks\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n // visit upper slots if present\n index = ++baseIndex;\n }\n }\n\n /**\n * Saves traversal state upon encountering a forwarding node.\n */\n private void pushState(Node[] t, int i, int n) {\n // reuse if possible\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n /**\n * Possibly pops traversal state.\n *\n * @param n length of current table\n */\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /**\n * Base of key, value, and entry Iterators. Adds fields to\n * Traverser to support iterator.remove.\n */\n static class BaseIterator extends Traverser {\n\n final ConcurrentHashMap map;\n\n Node lastReturned;\n\n BaseIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n advance();\n }\n\n public final boolean hasNext() {\n return next != null;\n }\n\n public final boolean hasMoreElements() {\n return next != null;\n }\n\n public final void remove() {\n Node p;\n if ((p = lastReturned) == null)\n throw new IllegalStateException();\n lastReturned = null;\n map.replaceNode(p.key, null, null);\n }\n }\n\n static final class KeyIterator extends BaseIterator implements Iterator, Enumeration {\n\n KeyIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final K next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n lastReturned = p;\n advance();\n return k;\n }\n\n public final K nextElement() {\n return next();\n }\n }\n\n static final class ValueIterator extends BaseIterator implements Iterator, Enumeration {\n\n ValueIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final V next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n V v = p.val;\n lastReturned = p;\n advance();\n return v;\n }\n\n public final V nextElement() {\n return next();\n }\n }\n\n static final class EntryIterator extends BaseIterator implements Iterator> {\n\n EntryIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final Map.Entry next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n V v = p.val;\n lastReturned = p;\n advance();\n return new MapEntry(k, v, map);\n }\n }\n\n static final class MapEntry implements Map.Entry {\n\n final K key;\n\n V val;\n\n final ConcurrentHashMap map;\n\n MapEntry(K key, V val, ConcurrentHashMap map) {\n this.key = key;\n this.val = val;\n this.map = map;\n }\n\n public K getKey() {\n return key;\n }\n\n public V getValue() {\n return val;\n }\n\n public int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public boolean equals(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == val || v.equals(val)));\n }\n\n /**\n * Sets our entry's value and writes through to the map. The\n * value to return is somewhat arbitrary here. Since we do not\n * necessarily track asynchronous changes, the most recent\n * \"previous\" value could be different from what we return (or\n * could even have been removed, in which case the put will\n * re-establish). We do not and cannot guarantee more.\n */\n public V setValue(V value) {\n if (value == null)\n throw new NullPointerException();\n V v = val;\n val = value;\n map.put(key, value);\n return v;\n }\n }\n\n static final class KeySpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n KeySpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public KeySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new KeySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.key);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class ValueSpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n ValueSpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public ValueSpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new ValueSpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.val);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class EntrySpliterator extends Traverser implements Spliterator> {\n\n // To export MapEntry\n final ConcurrentHashMap map;\n\n // size estimate\n long est;\n\n EntrySpliterator(Node[] tab, int size, int index, int limit, long est, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n this.est = est;\n }\n\n public EntrySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new EntrySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1, map);\n }\n\n public void forEachRemaining(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n\n public boolean tryAdvance(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(new MapEntry(p.key, p.val, map));\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n // Parallel bulk operations\n /**\n * Computes initial batch value for bulk tasks. The returned value\n * is approximately exp2 of the number of times (minus one) to\n * split task by two before executing leaf action. This value is\n * faster to compute and more convenient to use as a guide to\n * splitting than is the depth, since it is used while dividing by\n * two anyway.\n */\n final int batchFor(long b) {\n long n;\n if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)\n return 0;\n // slack of 4\n int sp = ForkJoinPool.getCommonPoolParallelism() << 2;\n return (b <= 0L || (n /= b) >= sp) ? sp : (int) n;\n }\n\n /**\n * Performs the given action for each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiFunction transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each (key, value), or null if none. Upon\n * success, further element processing is suppressed and the\n * results of any other parallel invocations of the search\n * function are ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each (key, value), or null if none\n * @since 1.8\n */\n public U search(long parallelismThreshold, BiFunction searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public U reduce(long parallelismThreshold, BiFunction transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public double reduceToDouble(long parallelismThreshold, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public long reduceToLong(long parallelismThreshold, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public int reduceToInt(long parallelismThreshold, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each key, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each key, or null if none\n * @since 1.8\n */\n public U searchKeys(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all keys using the given\n * reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all keys using the given\n * reducer to combine values, or null if none\n * @since 1.8\n */\n public K reduceKeys(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public U reduceKeys(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public double reduceKeysToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public long reduceKeysToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public int reduceKeysToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachValueTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedValueTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each value, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each value, or null if none\n * @since 1.8\n */\n public U searchValues(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all values using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all values\n * @since 1.8\n */\n public V reduceValues(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public U reduceValues(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public double reduceValuesToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public long reduceValuesToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public int reduceValuesToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Function, ? extends U> transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each entry, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each entry, or null if none\n * @since 1.8\n */\n public U searchEntries(long parallelismThreshold, Function, ? extends U> searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all entries using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all entries\n * @since 1.8\n */\n public Map.Entry reduceEntries(long parallelismThreshold, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public U reduceEntries(long parallelismThreshold, Function, ? extends U> transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public double reduceEntriesToDouble(long parallelismThreshold, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public long reduceEntriesToLong(long parallelismThreshold, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public int reduceEntriesToInt(long parallelismThreshold, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n abstract static class CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n final ConcurrentHashMap map;\n\n CollectionView(ConcurrentHashMap map) {\n this.map = map;\n }\n\n /**\n * Returns the map backing this view.\n *\n * @return the map backing this view\n */\n public ConcurrentHashMap getMap() {\n return map;\n }\n\n /**\n * Removes all of the elements from this view, by removing all\n * the mappings from the map backing this view.\n */\n public final void clear() {\n map.clear();\n }\n\n public final int size() {\n return map.size();\n }\n\n public final boolean isEmpty() {\n return map.isEmpty();\n }\n\n // implementations below rely on concrete classes supplying these\n /**\n * Returns an iterator over the elements in this collection.\n *\n *

The returned iterator is\n * weakly consistent.\n *\n * @return an iterator over the elements in this collection\n */\n public abstract Iterator iterator();\n\n public abstract boolean contains(Object o);\n\n public abstract boolean remove(Object o);\n\n private static final String OOME_MSG = \"Required array size too large\";\n\n public final Object[] toArray() {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int n = (int) sz;\n Object[] r = new Object[n];\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = e;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n @SuppressWarnings(\"unchecked\")\n public final T[] toArray(T[] a) {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int m = (int) sz;\n T[] r = (a.length >= m) ? a : (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), m);\n int n = r.length;\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = (T) e;\n }\n if (a == r && i < n) {\n r[i] = null;\n return r;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n /**\n * Returns a string representation of this collection.\n * The string representation consists of the string representations\n * of the collection's elements in the order they are returned by\n * its iterator, enclosed in square brackets ({@code \"[]\"}).\n * Adjacent elements are separated by the characters {@code \", \"}\n * (comma and space). Elements are converted to strings as by\n * {@link String#valueOf(Object)}.\n *\n * @return a string representation of this collection\n */\n public final String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append('[');\n Iterator it = iterator();\n if (it.hasNext()) {\n for (; ; ) {\n Object e = it.next();\n sb.append(e == this ? \"(this Collection)\" : e);\n if (!it.hasNext())\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append(']').toString();\n }\n\n public final boolean containsAll(Collection c) {\n if (c != this) {\n for (Object e : c) {\n if (e == null || !contains(e))\n return false;\n }\n }\n return true;\n }\n\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n // Use (c instanceof Set) as a hint that lookup in c is as\n // efficient as this view\n Node[] t;\n if ((t = map.table) == null) {\n return false;\n } else if (c instanceof Set && c.size() > t.length) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n } else {\n for (Object e : c) modified |= remove(e);\n }\n return modified;\n }\n\n public final boolean retainAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (!c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of keys, in\n * which additions may optionally be enabled by mapping to a\n * common value. This class cannot be directly instantiated.\n * See {@link #keySet() keySet()},\n * {@link #keySet(Object) keySet(V)},\n * {@link #newKeySet() newKeySet()},\n * {@link #newKeySet(int) newKeySet(int)}.\n *\n * @since 1.8\n */\n public static class KeySetView extends CollectionView implements Set, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n // Conditionally serializable\n @SuppressWarnings(\"serial\")\n private final V value;\n\n KeySetView(ConcurrentHashMap map, V value) {\n super(map);\n this.value = value;\n }\n\n /**\n * Returns the default mapped value for additions,\n * or {@code null} if additions are not supported.\n *\n * @return the default mapped value for additions, or {@code null}\n * if not supported\n */\n public V getMappedValue() {\n return value;\n }\n\n /**\n * {@inheritDoc}\n * @throws NullPointerException if the specified key is null\n */\n public boolean contains(Object o) {\n return map.containsKey(o);\n }\n\n /**\n * Removes the key from this map view, by removing the key (and its\n * corresponding value) from the backing map. This method does\n * nothing if the key is not in the map.\n *\n * @param o the key to be removed from the backing map\n * @return {@code true} if the backing map contained the specified key\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object o) {\n return map.remove(o) != null;\n }\n\n /**\n * @return an iterator over the keys of the backing map\n */\n public Iterator iterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, m);\n }\n\n /**\n * Adds the specified key to this set view by mapping the key to\n * the default mapped value in the backing map, if defined.\n *\n * @param e key to be added\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the specified key is null\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean add(K e) {\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n return map.putVal(e, v, true) == null;\n }\n\n /**\n * Adds all of the elements in the specified collection to this set,\n * as if by calling {@link #add} on each one.\n *\n * @param c the elements to be inserted into this set\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the collection or any of its\n * elements are {@code null}\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean addAll(Collection c) {\n boolean added = false;\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n for (K e : c) {\n if (map.putVal(e, v, true) == null)\n added = true;\n }\n return added;\n }\n\n public int hashCode() {\n int h = 0;\n for (K e : this) h += e.hashCode();\n return h;\n }\n\n public boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeySpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.key);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Collection} of\n * values, in which additions are disabled. This class cannot be\n * directly instantiated. See {@link #values()}.\n */\n static final class ValuesView extends CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n ValuesView(ConcurrentHashMap map) {\n super(map);\n }\n\n public final boolean contains(Object o) {\n return map.containsValue(o);\n }\n\n public final boolean remove(Object o) {\n if (o != null) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (o.equals(it.next())) {\n it.remove();\n return true;\n }\n }\n }\n return false;\n }\n\n public final Iterator iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, m);\n }\n\n public final boolean add(V e) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean addAll(Collection c) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n\n public boolean removeIf(Predicate filter) {\n return map.removeValueIf(filter);\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueSpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.val);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of (key, value)\n * entries. This class cannot be directly instantiated. See\n * {@link #entrySet()}.\n */\n static final class EntrySetView extends CollectionView> implements Set>, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n EntrySetView(ConcurrentHashMap map) {\n super(map);\n }\n\n public boolean contains(Object o) {\n Object k, v, r;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (r = map.get(k)) != null && (v = e.getValue()) != null && (v == r || v.equals(r)));\n }\n\n public boolean remove(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && map.remove(k, v));\n }\n\n /**\n * @return an iterator over the entries of the backing map\n */\n public Iterator> iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntryIterator(t, f, 0, f, m);\n }\n\n public boolean add(Entry e) {\n return map.putVal(e.getKey(), e.getValue(), false) == null;\n }\n\n public boolean addAll(Collection> c) {\n boolean added = false;\n for (Entry e : c) {\n if (add(e))\n added = true;\n }\n return added;\n }\n\n public boolean removeIf(Predicate> filter) {\n return map.removeEntryIf(filter);\n }\n\n public final int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n h += p.hashCode();\n }\n }\n return h;\n }\n\n public final boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator> spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntrySpliterator(t, f, 0, f, n < 0L ? 0L : n, m);\n }\n\n public void forEach(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n }\n }\n\n /**\n * Base class for bulk tasks. Repeats some fields and code from\n * class Traverser, because we need to subclass CountedCompleter.\n */\n @SuppressWarnings(\"serial\")\n abstract static class BulkTask extends CountedCompleter {\n\n // same as Traverser\n Node[] tab;\n\n Node next;\n\n TableStack stack, spare;\n\n int index;\n\n int baseIndex;\n\n int baseLimit;\n\n final int baseSize;\n\n // split control\n int batch;\n\n BulkTask(BulkTask par, int b, int i, int f, Node[] t) {\n super(par);\n this.batch = b;\n this.index = this.baseIndex = i;\n if ((this.tab = t) == null)\n this.baseSize = this.baseLimit = 0;\n else if (par == null)\n this.baseSize = this.baseLimit = t.length;\n else {\n this.baseLimit = f;\n this.baseSize = par.baseSize;\n }\n }\n\n /**\n * Same as Traverser version.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n Node[] t;\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n private void pushState(Node[] t, int i, int n) {\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /*\n * Task classes. Coded in a regular but ugly format/style to\n * simplify checks that each variant differs in the right way from\n * others. The null screenings exist because compilers cannot tell\n * that we've already null-checked task arguments, so we force\n * simplest hoisted bypass to help avoid convoluted traps.\n */\n @SuppressWarnings(\"serial\")\n static final class ForEachKeyTask extends BulkTask {\n\n final Consumer action;\n\n ForEachKeyTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachValueTask extends BulkTask {\n\n final Consumer action;\n\n ForEachValueTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachValueTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachEntryTask extends BulkTask {\n\n final Consumer> action;\n\n ForEachEntryTask(BulkTask p, int b, int i, int f, Node[] t, Consumer> action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer> action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachMappingTask extends BulkTask {\n\n final BiConsumer action;\n\n ForEachMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiConsumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final BiConsumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key, p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedKeyTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedKeyTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedValueTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedValueTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedValueTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedEntryTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final Consumer action;\n\n ForEachTransformedEntryTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedMappingTask extends BulkTask {\n\n final BiFunction transformer;\n\n final Consumer action;\n\n ForEachTransformedMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchKeysTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchKeysTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchValuesTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchValuesTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchEntriesTask extends BulkTask {\n\n final Function, ? extends U> searchFunction;\n\n final AtomicReference result;\n\n SearchEntriesTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function, ? extends U> searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n return;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchMappingsTask extends BulkTask {\n\n final BiFunction searchFunction;\n\n final AtomicReference result;\n\n SearchMappingsTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final BiFunction searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key, p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceKeysTask extends BulkTask {\n\n final BiFunction reducer;\n\n K result;\n\n ReduceKeysTask rights, nextRight;\n\n ReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, ReduceKeysTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final K getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n K r = null;\n for (Node p; (p = advance()) != null; ) {\n K u = p.key;\n r = (r == null) ? u : u == null ? r : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceKeysTask t = (ReduceKeysTask) c, s = t.rights;\n while (s != null) {\n K tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceValuesTask extends BulkTask {\n\n final BiFunction reducer;\n\n V result;\n\n ReduceValuesTask rights, nextRight;\n\n ReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceValuesTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final V getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n V r = null;\n for (Node p; (p = advance()) != null; ) {\n V v = p.val;\n r = (r == null) ? v : reducer.apply(r, v);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceValuesTask t = (ReduceValuesTask) c, s = t.rights;\n while (s != null) {\n V tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceEntriesTask extends BulkTask> {\n\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n\n Map.Entry result;\n\n ReduceEntriesTask rights, nextRight;\n\n ReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceEntriesTask nextRight, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final Map.Entry getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n Map.Entry r = null;\n for (Node p; (p = advance()) != null; ) r = (r == null) ? p : reducer.apply(r, p);\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceEntriesTask t = (ReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n Map.Entry tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceKeysTask rights, nextRight;\n\n MapReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysTask t = (MapReduceKeysTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceValuesTask rights, nextRight;\n\n MapReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesTask t = (MapReduceValuesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceEntriesTask rights, nextRight;\n\n MapReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesTask nextRight, Function, ? extends U> transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesTask t = (MapReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsTask extends BulkTask {\n\n final BiFunction transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceMappingsTask rights, nextRight;\n\n MapReduceMappingsTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsTask nextRight, BiFunction transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsTask t = (MapReduceMappingsTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceKeysToDoubleTask rights, nextRight;\n\n MapReduceKeysToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToDoubleTask t = (MapReduceKeysToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceValuesToDoubleTask rights, nextRight;\n\n MapReduceValuesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToDoubleTask t = (MapReduceValuesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction> transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceEntriesToDoubleTask rights, nextRight;\n\n MapReduceEntriesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToDoubleTask nextRight, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction> transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToDoubleTask t = (MapReduceEntriesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToDoubleTask extends BulkTask {\n\n final ToDoubleBiFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceMappingsToDoubleTask rights, nextRight;\n\n MapReduceMappingsToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToDoubleTask nextRight, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleBiFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToDoubleTask t = (MapReduceMappingsToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceKeysToLongTask rights, nextRight;\n\n MapReduceKeysToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToLongTask t = (MapReduceKeysToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceValuesToLongTask rights, nextRight;\n\n MapReduceValuesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToLongTask t = (MapReduceValuesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToLongTask extends BulkTask {\n\n final ToLongFunction> transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceEntriesToLongTask rights, nextRight;\n\n MapReduceEntriesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToLongTask nextRight, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction> transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToLongTask t = (MapReduceEntriesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToLongTask extends BulkTask {\n\n final ToLongBiFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceMappingsToLongTask rights, nextRight;\n\n MapReduceMappingsToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToLongTask nextRight, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongBiFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToLongTask t = (MapReduceMappingsToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceKeysToIntTask rights, nextRight;\n\n MapReduceKeysToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToIntTask t = (MapReduceKeysToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceValuesToIntTask rights, nextRight;\n\n MapReduceValuesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToIntTask t = (MapReduceValuesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToIntTask extends BulkTask {\n\n final ToIntFunction> transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceEntriesToIntTask rights, nextRight;\n\n MapReduceEntriesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToIntTask nextRight, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction> transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToIntTask t = (MapReduceEntriesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToIntTask extends BulkTask {\n\n final ToIntBiFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceMappingsToIntTask rights, nextRight;\n\n MapReduceMappingsToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToIntTask nextRight, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntBiFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToIntTask t = (MapReduceMappingsToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n // Unsafe mechanics\n private static final Unsafe U = Unsafe.getUnsafe();\n\n private static final long SIZECTL = U.objectFieldOffset(ConcurrentHashMap.class, \"sizeCtl\");\n\n private static final long TRANSFERINDEX = U.objectFieldOffset(ConcurrentHashMap.class, \"transferIndex\");\n\n private static final long BASECOUNT = U.objectFieldOffset(ConcurrentHashMap.class, \"baseCount\");\n\n private static final long CELLSBUSY = U.objectFieldOffset(ConcurrentHashMap.class, \"cellsBusy\");\n\n private static final long CELLVALUE = U.objectFieldOffset(CounterCell.class, \"value\");\n\n private static final int ABASE = U.arrayBaseOffset(Node[].class);\n\n private static final int ASHIFT;\n\n static {\n int scale = U.arrayIndexScale(Node[].class);\n if ((scale & (scale - 1)) != 0)\n throw new ExceptionInInitializerError(\"array index scale not a power of two\");\n ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);\n // Reduce the risk of rare disastrous classloading in first call to\n Class ensureLoaded = LockSupport.class;\n // Eager class load observed to help JIT during startup\n ensureLoaded = ReservationNode.class;\n }\n}\n"} {"task_id": "Java_2827", "language": "Java", "task_type": "while_statement", "source_file": "java/github/openjdk/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java", "mask_start_position": 234689, "mask_end_position": 234860, "canonical_solution": "while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }", "pre_mask_code": "package java.util.concurrent;\n\nimport java.io.ObjectStreamField;\nimport java.io.Serializable;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.AbstractMap;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Hashtable;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.Spliterator;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.concurrent.locks.LockSupport;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\nimport java.util.function.Consumer;\nimport java.util.function.DoubleBinaryOperator;\nimport java.util.function.Function;\nimport java.util.function.IntBinaryOperator;\nimport java.util.function.LongBinaryOperator;\nimport java.util.function.Predicate;\nimport java.util.function.ToDoubleBiFunction;\nimport java.util.function.ToDoubleFunction;\nimport java.util.function.ToIntBiFunction;\nimport java.util.function.ToIntFunction;\nimport java.util.function.ToLongBiFunction;\nimport java.util.function.ToLongFunction;\nimport java.util.stream.Stream;\nimport jdk.internal.misc.Unsafe;\n\n/**\n * A hash table supporting full concurrency of retrievals and\n * high expected concurrency for updates. This class obeys the\n * same functional specification as {@link java.util.Hashtable}, and\n * includes versions of methods corresponding to each method of\n * {@code Hashtable}. However, even though all operations are\n * thread-safe, retrieval operations do not entail locking,\n * and there is not any support for locking the entire table\n * in a way that prevents all access. This class is fully\n * interoperable with {@code Hashtable} in programs that rely on its\n * thread safety but not on its synchronization details.\n *\n *

Retrieval operations (including {@code get}) generally do not\n * block, so may overlap with update operations (including {@code put}\n * and {@code remove}). Retrievals reflect the results of the most\n * recently completed update operations holding upon their\n * onset. (More formally, an update operation for a given key bears a\n * happens-before relation with any (non-null) retrieval for\n * that key reporting the updated value.) For aggregate operations\n * such as {@code putAll} and {@code clear}, concurrent retrievals may\n * reflect insertion or removal of only some entries. Similarly,\n * Iterators, Spliterators and Enumerations return elements reflecting the\n * state of the hash table at some point at or since the creation of the\n * iterator/enumeration. They do not throw {@link\n * java.util.ConcurrentModificationException ConcurrentModificationException}.\n * However, iterators are designed to be used by only one thread at a time.\n * Bear in mind that the results of aggregate status methods including\n * {@code size}, {@code isEmpty}, and {@code containsValue} are typically\n * useful only when a map is not undergoing concurrent updates in other threads.\n * Otherwise the results of these methods reflect transient states\n * that may be adequate for monitoring or estimation purposes, but not\n * for program control.\n *\n *

The table is dynamically expanded when there are too many\n * collisions (i.e., keys that have distinct hash codes but fall into\n * the same slot modulo the table size), with the expected average\n * effect of maintaining roughly two bins per mapping (corresponding\n * to a 0.75 load factor threshold for resizing). There may be much\n * variance around this average as mappings are added and removed, but\n * overall, this maintains a commonly accepted time/space tradeoff for\n * hash tables. However, resizing this or any other kind of hash\n * table may be a relatively slow operation. When possible, it is a\n * good idea to provide a size estimate as an optional {@code\n * initialCapacity} constructor argument. An additional optional\n * {@code loadFactor} constructor argument provides a further means of\n * customizing initial table capacity by specifying the table density\n * to be used in calculating the amount of space to allocate for the\n * given number of elements. Also, for compatibility with previous\n * versions of this class, constructors may optionally specify an\n * expected {@code concurrencyLevel} as an additional hint for\n * internal sizing. Note that using many keys with exactly the same\n * {@code hashCode()} is a sure way to slow down performance of any\n * hash table. To ameliorate impact, when keys are {@link Comparable},\n * this class may use comparison order among keys to help break ties.\n *\n *

A {@link Set} projection of a ConcurrentHashMap may be created\n * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed\n * (using {@link #keySet(Object)} when only keys are of interest, and the\n * mapped values are (perhaps transiently) not used or all take the\n * same mapping value.\n *\n *

A ConcurrentHashMap can be used as a scalable frequency map (a\n * form of histogram or multiset) by using {@link\n * java.util.concurrent.atomic.LongAdder} values and initializing via\n * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count\n * to a {@code ConcurrentHashMap freqs}, you can use\n * {@code freqs.computeIfAbsent(key, k -> new LongAdder()).increment();}\n *\n *

This class and its views and iterators implement all of the\n * optional methods of the {@link Map} and {@link Iterator}\n * interfaces.\n *\n *

Like {@link Hashtable} but unlike {@link HashMap}, this class\n * does not allow {@code null} to be used as a key or value.\n *\n *

ConcurrentHashMaps support a set of sequential and parallel bulk\n * operations that, unlike most {@link Stream} methods, are designed\n * to be safely, and often sensibly, applied even with maps that are\n * being concurrently updated by other threads; for example, when\n * computing a snapshot summary of the values in a shared registry.\n * There are three kinds of operation, each with four forms, accepting\n * functions with keys, values, entries, and (key, value) pairs as\n * arguments and/or return values. Because the elements of a\n * ConcurrentHashMap are not ordered in any particular way, and may be\n * processed in different orders in different parallel executions, the\n * correctness of supplied functions should not depend on any\n * ordering, or on any other objects or values that may transiently\n * change while computation is in progress; and except for forEach\n * actions, should ideally be side-effect-free. Bulk operations on\n * {@link Map.Entry} objects do not support method {@code setValue}.\n *\n *

    \n *
  • forEach: Performs a given action on each element.\n * A variant form applies a given transformation on each element\n * before performing the action.\n *\n *
  • search: Returns the first available non-null result of\n * applying a given function on each element; skipping further\n * search when a result is found.\n *\n *
  • reduce: Accumulates each element. The supplied reduction\n * function cannot rely on ordering (more formally, it should be\n * both associative and commutative). There are five variants:\n *\n *
      \n *\n *
    • Plain reductions. (There is not a form of this method for\n * (key, value) function arguments since there is no corresponding\n * return type.)\n *\n *
    • Mapped reductions that accumulate the results of a given\n * function applied to each element.\n *\n *
    • Reductions to scalar doubles, longs, and ints, using a\n * given basis value.\n *\n *
    \n *
\n *\n *

These bulk operations accept a {@code parallelismThreshold}\n * argument. Methods proceed sequentially if the current map size is\n * estimated to be less than the given threshold. Using a value of\n * {@code Long.MAX_VALUE} suppresses all parallelism. Using a value\n * of {@code 1} results in maximal parallelism by partitioning into\n * enough subtasks to fully utilize the {@link\n * ForkJoinPool#commonPool()} that is used for all parallel\n * computations. Normally, you would initially choose one of these\n * extreme values, and then measure performance of using in-between\n * values that trade off overhead versus throughput.\n *\n *

The concurrency properties of bulk operations follow\n * from those of ConcurrentHashMap: Any non-null result returned\n * from {@code get(key)} and related access methods bears a\n * happens-before relation with the associated insertion or\n * update. The result of any bulk operation reflects the\n * composition of these per-element relations (but is not\n * necessarily atomic with respect to the map as a whole unless it\n * is somehow known to be quiescent). Conversely, because keys\n * and values in the map are never null, null serves as a reliable\n * atomic indicator of the current lack of any result. To\n * maintain this property, null serves as an implicit basis for\n * all non-scalar reduction operations. For the double, long, and\n * int versions, the basis should be one that, when combined with\n * any other value, returns that other value (more formally, it\n * should be the identity element for the reduction). Most common\n * reductions have these properties; for example, computing a sum\n * with basis 0 or a minimum with basis MAX_VALUE.\n *\n *

Search and transformation functions provided as arguments\n * should similarly return null to indicate the lack of any result\n * (in which case it is not used). In the case of mapped\n * reductions, this also enables transformations to serve as\n * filters, returning null (or, in the case of primitive\n * specializations, the identity basis) if the element should not\n * be combined. You can create compound transformations and\n * filterings by composing them yourself under this \"null means\n * there is nothing there now\" rule before using them in search or\n * reduce operations.\n *\n *

Methods accepting and/or returning Entry arguments maintain\n * key-value associations. They may be useful for example when\n * finding the key for the greatest value. Note that \"plain\" Entry\n * arguments can be supplied using {@code new\n * AbstractMap.SimpleEntry(k,v)}.\n *\n *

Bulk operations may complete abruptly, throwing an\n * exception encountered in the application of a supplied\n * function. Bear in mind when handling such exceptions that other\n * concurrently executing functions could also have thrown\n * exceptions, or would have done so if the first exception had\n * not occurred.\n *\n *

Speedups for parallel compared to sequential forms are common\n * but not guaranteed. Parallel operations involving brief functions\n * on small maps may execute more slowly than sequential forms if the\n * underlying work to parallelize the computation is more expensive\n * than the computation itself. Similarly, parallelization may not\n * lead to much actual parallelism if all processors are busy\n * performing unrelated tasks.\n *\n *

All arguments to all task methods must be non-null.\n *\n *

This class is a member of the\n * \n * Java Collections Framework.\n *\n * @since 1.5\n * @author Doug Lea\n * @param the type of keys maintained by this map\n * @param the type of mapped values\n */\npublic class ConcurrentHashMap extends AbstractMap implements ConcurrentMap, Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n /*\n * Overview:\n *\n * The primary design goal of this hash table is to maintain\n * concurrent readability (typically method get(), but also\n * iterators and related methods) while minimizing update\n * contention. Secondary goals are to keep space consumption about\n * the same or better than java.util.HashMap, and to support high\n * initial insertion rates on an empty table by many threads.\n *\n * This map usually acts as a binned (bucketed) hash table. Each\n * key-value mapping is held in a Node. Most nodes are instances\n * of the basic Node class with hash, key, value, and next\n * fields. However, various subclasses exist: TreeNodes are\n * arranged in balanced trees, not lists. TreeBins hold the roots\n * of sets of TreeNodes. ForwardingNodes are placed at the heads\n * of bins during resizing. ReservationNodes are used as\n * placeholders while establishing values in computeIfAbsent and\n * related methods. The types TreeBin, ForwardingNode, and\n * ReservationNode do not hold normal user keys, values, or\n * hashes, and are readily distinguishable during search etc\n * because they have negative hash fields and null key and value\n * fields. (These special nodes are either uncommon or transient,\n * so the impact of carrying around some unused fields is\n * insignificant.)\n *\n * The table is lazily initialized to a power-of-two size upon the\n * first insertion. Each bin in the table normally contains a\n * list of Nodes (most often, the list has only zero or one Node).\n * Table accesses require volatile/atomic reads, writes, and\n * CASes. Because there is no other way to arrange this without\n * adding further indirections, we use intrinsics\n * (jdk.internal.misc.Unsafe) operations.\n *\n * We use the top (sign) bit of Node hash fields for control\n * purposes -- it is available anyway because of addressing\n * constraints. Nodes with negative hash fields are specially\n * handled or ignored in map methods.\n *\n * Insertion (via put or its variants) of the first node in an\n * empty bin is performed by just CASing it to the bin. This is\n * by far the most common case for put operations under most\n * key/hash distributions. Other update operations (insert,\n * delete, and replace) require locks. We do not want to waste\n * the space required to associate a distinct lock object with\n * each bin, so instead use the first node of a bin list itself as\n * a lock. Locking support for these locks relies on builtin\n * \"synchronized\" monitors.\n *\n * Using the first node of a list as a lock does not by itself\n * suffice though: When a node is locked, any update must first\n * validate that it is still the first node after locking it, and\n * retry if not. Because new nodes are always appended to lists,\n * once a node is first in a bin, it remains first until deleted\n * or the bin becomes invalidated (upon resizing).\n *\n * The main disadvantage of per-bin locks is that other update\n * operations on other nodes in a bin list protected by the same\n * lock can stall, for example when user equals() or mapping\n * functions take a long time. However, statistically, under\n * random hash codes, this is not a common problem. Ideally, the\n * frequency of nodes in bins follows a Poisson distribution\n * (http://example.com) with a\n * parameter of about 0.5 on average, given the resizing threshold\n * of 0.75, although with a large variance because of resizing\n * granularity. Ignoring variance, the expected occurrences of\n * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The\n * first values are:\n *\n * 0: 0.60653066\n * 1: 0.30326533\n * 2: 0.07581633\n * 3: 0.01263606\n * 4: 0.00157952\n * 5: 0.00015795\n * 6: 0.00001316\n * 7: 0.00000094\n * 8: 0.00000006\n * more: less than 1 in ten million\n *\n * Lock contention probability for two threads accessing distinct\n * elements is roughly 1 / (8 * #elements) under random hashes.\n *\n * Actual hash code distributions encountered in practice\n * sometimes deviate significantly from uniform randomness. This\n * includes the case when N > (1<<30), so some keys MUST collide.\n * Similarly for dumb or hostile usages in which multiple keys are\n * designed to have identical hash codes or ones that differs only\n * in masked-out high bits. So we use a secondary strategy that\n * applies when the number of nodes in a bin exceeds a\n * threshold. These TreeBins use a balanced tree to hold nodes (a\n * specialized form of red-black trees), bounding search time to\n * O(log N). Each search step in a TreeBin is at least twice as\n * slow as in a regular list, but given that N cannot exceed\n * (1<<64) (before running out of addresses) this bounds search\n * steps, lock hold times, etc, to reasonable constants (roughly\n * 100 nodes inspected per operation worst case) so long as keys\n * are Comparable (which is very common -- String, Long, etc).\n * TreeBin nodes (TreeNodes) also maintain the same \"next\"\n * traversal pointers as regular nodes, so can be traversed in\n * iterators in the same way.\n *\n * The table is resized when occupancy exceeds a percentage\n * threshold (nominally, 0.75, but see below). Any thread\n * noticing an overfull bin may assist in resizing after the\n * initiating thread allocates and sets up the replacement array.\n * However, rather than stalling, these other threads may proceed\n * with insertions etc. The use of TreeBins shields us from the\n * worst case effects of overfilling while resizes are in\n * progress. Resizing proceeds by transferring bins, one by one,\n * from the table to the next table. However, threads claim small\n * blocks of indices to transfer (via field transferIndex) before\n * doing so, reducing contention. A generation stamp in field\n * sizeCtl ensures that resizings do not overlap. Because we are\n * using power-of-two expansion, the elements from each bin must\n * either stay at same index, or move with a power of two\n * offset. We eliminate unnecessary node creation by catching\n * cases where old nodes can be reused because their next fields\n * won't change. On average, only about one-sixth of them need\n * cloning when a table doubles. The nodes they replace will be\n * garbage collectible as soon as they are no longer referenced by\n * any reader thread that may be in the midst of concurrently\n * traversing table. Upon transfer, the old table bin contains\n * only a special forwarding node (with hash field \"MOVED\") that\n * contains the next table as its key. On encountering a\n * forwarding node, access and update operations restart, using\n * the new table.\n *\n * Each bin transfer requires its bin lock, which can stall\n * waiting for locks while resizing. However, because other\n * threads can join in and help resize rather than contend for\n * locks, average aggregate waits become shorter as resizing\n * progresses. The transfer operation must also ensure that all\n * accessible bins in both the old and new table are usable by any\n * traversal. This is arranged in part by proceeding from the\n * last bin (table.length - 1) up towards the first. Upon seeing\n * a forwarding node, traversals (see class Traverser) arrange to\n * move to the new table without revisiting nodes. To ensure that\n * no intervening nodes are skipped even when moved out of order,\n * a stack (see class TableStack) is created on first encounter of\n * a forwarding node during a traversal, to maintain its place if\n * later processing the current table. The need for these\n * save/restore mechanics is relatively rare, but when one\n * forwarding node is encountered, typically many more will be.\n * So Traversers use a simple caching scheme to avoid creating so\n * many new TableStack nodes. (Thanks to Peter Levart for\n * suggesting use of a stack here.)\n *\n * The traversal scheme also applies to partial traversals of\n * ranges of bins (via an alternate Traverser constructor)\n * to support partitioned aggregate operations. Also, read-only\n * operations give up if ever forwarded to a null table, which\n * provides support for shutdown-style clearing, which is also not\n * currently implemented.\n *\n * Lazy table initialization minimizes footprint until first use,\n * and also avoids resizings when the first operation is from a\n * putAll, constructor with map argument, or deserialization.\n * These cases attempt to override the initial capacity settings,\n * but harmlessly fail to take effect in cases of races.\n *\n * The element count is maintained using a specialization of\n * LongAdder. We need to incorporate a specialization rather than\n * just use a LongAdder in order to access implicit\n * contention-sensing that leads to creation of multiple\n * CounterCells. The counter mechanics avoid contention on\n * updates but can encounter cache thrashing if read too\n * frequently during concurrent access. To avoid reading so often,\n * resizing under contention is attempted only upon adding to a\n * bin already holding two or more nodes. Under uniform hash\n * distributions, the probability of this occurring at threshold\n * is around 13%, meaning that only about 1 in 8 puts check\n * threshold (and after resizing, many fewer do so).\n *\n * TreeBins use a special form of comparison for search and\n * related operations (which is the main reason we cannot use\n * existing collections such as TreeMaps). TreeBins contain\n * Comparable elements, but may contain others, as well as\n * elements that are Comparable but not necessarily Comparable for\n * the same T, so we cannot invoke compareTo among them. To handle\n * this, the tree is ordered primarily by hash value, then by\n * Comparable.compareTo order if applicable. On lookup at a node,\n * if elements are not comparable or compare as 0 then both left\n * and right children may need to be searched in the case of tied\n * hash values. (This corresponds to the full list search that\n * would be necessary if all elements were non-Comparable and had\n * tied hashes.) On insertion, to keep a total ordering (or as\n * close as is required here) across rebalancings, we compare\n * classes and identityHashCodes as tie-breakers. The red-black\n * balancing code is updated from pre-jdk-collections\n * (http://example.com)\n * based in turn on Cormen, Leiserson, and Rivest \"Introduction to\n * Algorithms\" (CLR).\n *\n * TreeBins also require an additional locking mechanism. While\n * list traversal is always possible by readers even during\n * updates, tree traversal is not, mainly because of tree-rotations\n * that may change the root node and/or its linkages. TreeBins\n * include a simple read-write lock mechanism parasitic on the\n * main bin-synchronization strategy: Structural adjustments\n * associated with an insertion or removal are already bin-locked\n * (and so cannot conflict with other writers) but must wait for\n * ongoing readers to finish. Since there can be only one such\n * waiter, we use a simple scheme using a single \"waiter\" field to\n * block writers. However, readers need never block. If the root\n * lock is held, they proceed along the slow traversal path (via\n * next-pointers) until the lock becomes available or the list is\n * exhausted, whichever comes first. These cases are not fast, but\n * maximize aggregate expected throughput.\n *\n * Maintaining API and serialization compatibility with previous\n * versions of this class introduces several oddities. Mainly: We\n * leave untouched but unused constructor arguments referring to\n * concurrencyLevel. We accept a loadFactor constructor argument,\n * but apply it only to initial table capacity (which is the only\n * time that we can guarantee to honor it.) We also declare an\n * unused \"Segment\" class that is instantiated in minimal form\n * only when serializing.\n *\n * Also, solely for compatibility with previous versions of this\n * class, it extends AbstractMap, even though all of its methods\n * are overridden, so it is just useless baggage.\n *\n * This file is organized to make things a little easier to follow\n * while reading than they might otherwise: First the main static\n * declarations and utilities, then fields, then main public\n * methods (with a few factorings of multiple public methods into\n * internal ones), then sizing methods, trees, traversers, and\n * bulk operations.\n */\n /**\n * The largest possible table capacity. This value must be\n * exactly 1<<30 to stay within Java array allocation and indexing\n * bounds for power of two table sizes, and is further required\n * because the top two bits of 32bit hash fields are used for\n * control purposes.\n */\n private static final int MAXIMUM_CAPACITY = 1 << 30;\n\n /**\n * The default initial table capacity. Must be a power of 2\n * (i.e., at least 1) and at most MAXIMUM_CAPACITY.\n */\n private static final int DEFAULT_CAPACITY = 16;\n\n /**\n * The largest possible (non-power of two) array size.\n * Needed by toArray and related methods.\n */\n static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;\n\n /**\n * The default concurrency level for this table. Unused but\n * defined for compatibility with previous versions of this class.\n */\n private static final int DEFAULT_CONCURRENCY_LEVEL = 16;\n\n /**\n * The load factor for this table. Overrides of this value in\n * constructors affect only the initial table capacity. The\n * actual floating point value isn't normally used -- it is\n * simpler to use expressions such as {@code n - (n >>> 2)} for\n * the associated resizing threshold.\n */\n private static final float LOAD_FACTOR = 0.75f;\n\n /**\n * The bin count threshold for using a tree rather than list for a\n * bin. Bins are converted to trees when adding an element to a\n * bin with at least this many nodes. The value must be greater\n * than 2, and should be at least 8 to mesh with assumptions in\n * tree removal about conversion back to plain bins upon\n * shrinkage.\n */\n static final int TREEIFY_THRESHOLD = 8;\n\n /**\n * The bin count threshold for untreeifying a (split) bin during a\n * resize operation. Should be less than TREEIFY_THRESHOLD, and at\n * most 6 to mesh with shrinkage detection under removal.\n */\n static final int UNTREEIFY_THRESHOLD = 6;\n\n /**\n * The smallest table capacity for which bins may be treeified.\n * (Otherwise the table is resized if too many nodes in a bin.)\n * The value should be at least 4 * TREEIFY_THRESHOLD to avoid\n * conflicts between resizing and treeification thresholds.\n */\n static final int MIN_TREEIFY_CAPACITY = 64;\n\n /**\n * Minimum number of rebinnings per transfer step. Ranges are\n * subdivided to allow multiple resizer threads. This value\n * serves as a lower bound to avoid resizers encountering\n * excessive memory contention. The value should be at least\n * DEFAULT_CAPACITY.\n */\n private static final int MIN_TRANSFER_STRIDE = 16;\n\n /**\n * The number of bits used for generation stamp in sizeCtl.\n * Must be at least 6 for 32bit arrays.\n */\n private static final int RESIZE_STAMP_BITS = 16;\n\n /**\n * The maximum number of threads that can help resize.\n * Must fit in 32 - RESIZE_STAMP_BITS bits.\n */\n private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;\n\n /**\n * The bit shift for recording size stamp in sizeCtl.\n */\n private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;\n\n /*\n * Encodings for Node hash fields. See above for explanation.\n */\n // hash for forwarding nodes\n static final int MOVED = -1;\n\n // hash for roots of trees\n static final int TREEBIN = -2;\n\n static final int RESERVED = -3;\n\n // usable bits of normal node hash\n static final int HASH_BITS = 0x7fffffff;\n\n /**\n * Number of CPUS, to place bounds on some sizings\n */\n static final int NCPU = Runtime.getRuntime().availableProcessors();\n\n /**\n * Serialized pseudo-fields, provided only for jdk7 compatibility.\n * @serialField segments Segment[]\n * The segments, each of which is a specialized hash table.\n * @serialField segmentMask int\n * Mask value for indexing into segments. The upper bits of a\n * key's hash code are used to choose the segment.\n * @serialField segmentShift int\n * Shift value for indexing within segments.\n */\n private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(\"segments\", Segment[].class), new ObjectStreamField(\"segmentMask\", Integer.TYPE), new ObjectStreamField(\"segmentShift\", Integer.TYPE) };\n\n /**\n * Key-value entry. This class is never exported out as a\n * user-mutable Map.Entry (i.e., one supporting setValue; see\n * MapEntry below), but can be used for read-only traversals used\n * in bulk tasks. Subclasses of Node with a negative hash field\n * are special, and contain null keys and values (but are never\n * exported). Otherwise, keys and vals are never null.\n */\n static class Node implements Map.Entry {\n\n final int hash;\n\n final K key;\n\n volatile V val;\n\n volatile Node next;\n\n Node(int hash, K key, V val) {\n this.hash = hash;\n this.key = key;\n this.val = val;\n }\n\n Node(int hash, K key, V val, Node next) {\n this(hash, key, val);\n this.next = next;\n }\n\n public final K getKey() {\n return key;\n }\n\n public final V getValue() {\n return val;\n }\n\n public final int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public final String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public final V setValue(V value) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean equals(Object o) {\n Object k, v, u;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == (u = val) || v.equals(u)));\n }\n\n /**\n * Virtualized support for map.get(); overridden in subclasses.\n */\n Node find(int h, Object k) {\n Node e = this;\n if (k != null) {\n do {\n K ek;\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n } while ((e = e.next) != null);\n }\n return null;\n }\n }\n\n /**\n * Spreads (XORs) higher bits of hash to lower and also forces top\n * bit to 0. Because the table uses power-of-two masking, sets of\n * hashes that vary only in bits above the current mask will\n * always collide. (Among known examples are sets of Float keys\n * holding consecutive whole numbers in small tables.) So we\n * apply a transform that spreads the impact of higher bits\n * downward. There is a tradeoff between speed, utility, and\n * quality of bit-spreading. Because many common sets of hashes\n * are already reasonably distributed (so don't benefit from\n * spreading), and because we use trees to handle large sets of\n * collisions in bins, we just XOR some shifted bits in the\n * cheapest possible way to reduce systematic lossage, as well as\n * to incorporate impact of the highest bits that would otherwise\n * never be used in index calculations because of table bounds.\n */\n static final int spread(int h) {\n return (h ^ (h >>> 16)) & HASH_BITS;\n }\n\n /**\n * Returns a power of two table size for the given desired capacity.\n * See Hackers Delight, sec 3.2\n */\n private static final int tableSizeFor(int c) {\n int n = -1 >>> Integer.numberOfLeadingZeros(c - 1);\n return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;\n }\n\n /**\n * Returns x's Class if it is of the form \"class C implements\n * Comparable\", else null.\n */\n static Class comparableClassFor(Object x) {\n if (x instanceof Comparable) {\n Class c;\n Type[] ts, as;\n ParameterizedType p;\n if (// bypass checks\n (c = x.getClass()) == String.class)\n return c;\n if ((ts = c.getGenericInterfaces()) != null) {\n for (Type t : ts) {\n if ((t instanceof ParameterizedType) && ((p = (ParameterizedType) t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && // type arg is c\n as[0] == c)\n return c;\n }\n }\n }\n return null;\n }\n\n /**\n * Returns k.compareTo(x) if x matches kc (k's screened comparable\n * class), else 0.\n */\n // for cast to Comparable\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n static int compareComparables(Class kc, Object k, Object x) {\n return (x == null || x.getClass() != kc ? 0 : ((Comparable) k).compareTo(x));\n }\n\n /* ---------------- Table element access -------------- */\n /*\n * Atomic access methods are used for table elements as well as\n * elements of in-progress next table while resizing. All uses of\n * the tab arguments must be null checked by callers. All callers\n * also paranoically precheck that tab's length is not zero (or an\n * equivalent check), thus ensuring that any index argument taking\n * the form of a hash value anded with (length - 1) is a valid\n * index. Note that, to be correct wrt arbitrary concurrency\n * errors by users, these checks must operate on local variables,\n * which accounts for some odd-looking inline assignments below.\n * Note that calls to setTabAt always occur within locked regions,\n * and so require only release ordering.\n */\n @SuppressWarnings(\"unchecked\")\n static final Node tabAt(Node[] tab, int i) {\n return (Node) U.getReferenceAcquire(tab, ((long) i << ASHIFT) + ABASE);\n }\n\n static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {\n return U.compareAndSetReference(tab, ((long) i << ASHIFT) + ABASE, c, v);\n }\n\n static final void setTabAt(Node[] tab, int i, Node v) {\n U.putReferenceRelease(tab, ((long) i << ASHIFT) + ABASE, v);\n }\n\n /**\n * The array of bins. Lazily initialized upon first insertion.\n * Size is always a power of two. Accessed directly by iterators.\n */\n transient volatile Node[] table;\n\n /**\n * The next table to use; non-null only while resizing.\n */\n private transient volatile Node[] nextTable;\n\n /**\n * Base counter value, used mainly when there is no contention,\n * but also as a fallback during table initialization\n * races. Updated via CAS.\n */\n private transient volatile long baseCount;\n\n /**\n * Table initialization and resizing control. When negative, the\n * table is being initialized or resized: -1 for initialization,\n * else -(1 + the number of active resizing threads). Otherwise,\n * when table is null, holds the initial table size to use upon\n * creation, or 0 for default. After initialization, holds the\n * next element count value upon which to resize the table.\n */\n private transient volatile int sizeCtl;\n\n /**\n * The next table index (plus one) to split while resizing.\n */\n private transient volatile int transferIndex;\n\n /**\n * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.\n */\n private transient volatile int cellsBusy;\n\n /**\n * Table of counter cells. When non-null, size is a power of 2.\n */\n private transient volatile CounterCell[] counterCells;\n\n // views\n private transient KeySetView keySet;\n\n private transient ValuesView values;\n\n private transient EntrySetView entrySet;\n\n /**\n * Creates a new, empty map with the default initial table size (16).\n */\n public ConcurrentHashMap() {\n }\n\n /**\n * Creates a new, empty map with an initial table size\n * accommodating the specified number of elements without the need\n * to dynamically resize.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n */\n public ConcurrentHashMap(int initialCapacity) {\n this(initialCapacity, LOAD_FACTOR, 1);\n }\n\n /**\n * Creates a new map with the same mappings as the given map.\n *\n * @param m the map\n */\n public ConcurrentHashMap(Map m) {\n this.sizeCtl = DEFAULT_CAPACITY;\n putAll(m);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}) and\n * initial table density ({@code loadFactor}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative or the load factor is nonpositive\n *\n * @since 1.6\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor) {\n this(initialCapacity, loadFactor, 1);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}), initial\n * table density ({@code loadFactor}), and number of concurrently\n * updating threads ({@code concurrencyLevel}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @param concurrencyLevel the estimated number of concurrently\n * updating threads. The implementation may use this value as\n * a sizing hint.\n * @throws IllegalArgumentException if the initial capacity is\n * negative or the load factor or concurrencyLevel are\n * nonpositive\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) {\n if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)\n throw new IllegalArgumentException();\n if (// Use at least as many bins\n initialCapacity < concurrencyLevel)\n // as estimated threads\n initialCapacity = concurrencyLevel;\n long size = (long) (1.0 + (long) initialCapacity / loadFactor);\n int cap = (size >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) size);\n this.sizeCtl = cap;\n }\n\n // Original (since JDK1.2) Map methods\n public int size() {\n long n = sumCount();\n return ((n < 0L) ? 0 : (n > (long) Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) n);\n }\n\n public boolean isEmpty() {\n // ignore transient negative values\n return sumCount() <= 0L;\n }\n\n /**\n * Returns the value to which the specified key is mapped,\n * or {@code null} if this map contains no mapping for the key.\n *\n *

More formally, if this map contains a mapping from a key\n * {@code k} to a value {@code v} such that {@code key.equals(k)},\n * then this method returns {@code v}; otherwise it returns\n * {@code null}. (There can be at most one such mapping.)\n *\n * @throws NullPointerException if the specified key is null\n */\n public V get(Object key) {\n Node[] tab;\n Node e, p;\n int n, eh;\n K ek;\n int h = spread(key.hashCode());\n if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) {\n if ((eh = e.hash) == h) {\n if ((ek = e.key) == key || (ek != null && key.equals(ek)))\n return e.val;\n } else if (eh < 0)\n return (p = e.find(h, key)) != null ? p.val : null;\n while ((e = e.next) != null) {\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek))))\n return e.val;\n }\n }\n return null;\n }\n\n /**\n * Tests if the specified object is a key in this table.\n *\n * @param key possible key\n * @return {@code true} if and only if the specified object\n * is a key in this table, as determined by the\n * {@code equals} method; {@code false} otherwise\n * @throws NullPointerException if the specified key is null\n */\n public boolean containsKey(Object key) {\n return get(key) != null;\n }\n\n /**\n * Returns {@code true} if this map maps one or more keys to the\n * specified value. Note: This method may require a full traversal\n * of the map, and is much slower than method {@code containsKey}.\n *\n * @param value value whose presence in this map is to be tested\n * @return {@code true} if this map maps one or more keys to the\n * specified value\n * @throws NullPointerException if the specified value is null\n */\n public boolean containsValue(Object value) {\n if (value == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V v;\n if ((v = p.val) == value || (v != null && value.equals(v)))\n return true;\n }\n }\n return false;\n }\n\n /**\n * Maps the specified key to the specified value in this table.\n * Neither the key nor the value can be null.\n *\n *

The value can be retrieved by calling the {@code get} method\n * with a key that is equal to the original key.\n *\n * @param key key with which the specified value is to be associated\n * @param value value to be associated with the specified key\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key or value is null\n */\n public V put(K key, V value) {\n return putVal(key, value, false);\n }\n\n /**\n * Implementation for put and putIfAbsent\n */\n final V putVal(K key, V value, boolean onlyIfAbsent) {\n if (key == null || value == null)\n throw new NullPointerException();\n int hash = spread(key.hashCode());\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {\n if (casTabAt(tab, i, null, new Node(hash, key, value)))\n // no lock when adding to empty bin\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n onlyIfAbsent && fh == hash && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n V oldVal = null;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n oldVal = e.val;\n if (!onlyIfAbsent)\n e.val = value;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n pred.next = new Node(hash, key, value);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n Node p;\n binCount = 2;\n if ((p = ((TreeBin) f).putTreeVal(hash, key, value)) != null) {\n oldVal = p.val;\n if (!onlyIfAbsent)\n p.val = value;\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (oldVal != null)\n return oldVal;\n break;\n }\n }\n }\n addCount(1L, binCount);\n return null;\n }\n\n /**\n * Copies all of the mappings from the specified map to this one.\n * These mappings replace any mappings that this map had for any of the\n * keys currently in the specified map.\n *\n * @param m mappings to be stored in this map\n */\n public void putAll(Map m) {\n tryPresize(m.size());\n for (Map.Entry e : m.entrySet()) putVal(e.getKey(), e.getValue(), false);\n }\n\n /**\n * Removes the key (and its corresponding value) from this map.\n * This method does nothing if the key is not in the map.\n *\n * @param key the key that needs to be removed\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key is null\n */\n public V remove(Object key) {\n return replaceNode(key, null, null);\n }\n\n /**\n * Implementation for the four public remove/replace methods:\n * Replaces node value with v, conditional upon match of cv if\n * non-null. If resulting value is null, delete.\n */\n final V replaceNode(Object key, V value, Object cv) {\n int hash = spread(key.hashCode());\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0 || (f = tabAt(tab, i = (n - 1) & hash)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n V oldVal = null;\n boolean validated = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n validated = true;\n for (Node e = f, pred = null; ; ) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n V ev = e.val;\n if (cv == null || cv == ev || (ev != null && cv.equals(ev))) {\n oldVal = ev;\n if (value != null)\n e.val = value;\n else if (pred != null)\n pred.next = e.next;\n else\n setTabAt(tab, i, e.next);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n validated = true;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(hash, key, null)) != null) {\n V pv = p.val;\n if (cv == null || cv == pv || (pv != null && cv.equals(pv))) {\n oldVal = pv;\n if (value != null)\n p.val = value;\n else if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (validated) {\n if (oldVal != null) {\n if (value == null)\n addCount(-1L, -1);\n return oldVal;\n }\n break;\n }\n }\n }\n return null;\n }\n\n /**\n * Removes all of the mappings from this map.\n */\n public void clear() {\n // negative number of deletions\n long delta = 0L;\n int i = 0;\n Node[] tab = table;\n while (tab != null && i < tab.length) {\n int fh;\n Node f = tabAt(tab, i);\n if (f == null)\n ++i;\n else if ((fh = f.hash) == MOVED) {\n tab = helpTransfer(tab, f);\n // restart\n i = 0;\n } else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node p = (fh >= 0 ? f : (f instanceof TreeBin) ? ((TreeBin) f).first : null);\n while (p != null) {\n --delta;\n p = p.next;\n }\n setTabAt(tab, i++, null);\n }\n }\n }\n }\n if (delta != 0L)\n addCount(delta, -1);\n }\n\n /**\n * Returns a {@link Set} view of the keys contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from this map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations. It does not support the {@code add} or\n * {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public KeySetView keySet() {\n KeySetView ks;\n if ((ks = keySet) != null)\n return ks;\n return keySet = new KeySetView(this, null);\n }\n\n /**\n * Returns a {@link Collection} view of the values contained in this map.\n * The collection is backed by the map, so changes to the map are\n * reflected in the collection, and vice-versa. The collection\n * supports element removal, which removes the corresponding\n * mapping from this map, via the {@code Iterator.remove},\n * {@code Collection.remove}, {@code removeAll},\n * {@code retainAll}, and {@code clear} operations. It does not\n * support the {@code add} or {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}\n * and {@link Spliterator#NONNULL}.\n *\n * @return the collection view\n */\n public Collection values() {\n ValuesView vs;\n if ((vs = values) != null)\n return vs;\n return values = new ValuesView(this);\n }\n\n /**\n * Returns a {@link Set} view of the mappings contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from the map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public Set> entrySet() {\n EntrySetView es;\n if ((es = entrySet) != null)\n return es;\n return entrySet = new EntrySetView(this);\n }\n\n /**\n * Returns the hash code value for this {@link Map}, i.e.,\n * the sum of, for each key-value pair in the map,\n * {@code key.hashCode() ^ value.hashCode()}.\n *\n * @return the hash code value for this map\n */\n public int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) h += p.key.hashCode() ^ p.val.hashCode();\n }\n return h;\n }\n\n /**\n * Returns a string representation of this map. The string\n * representation consists of a list of key-value mappings (in no\n * particular order) enclosed in braces (\"{@code {}}\"). Adjacent\n * mappings are separated by the characters {@code \", \"} (comma\n * and space). Each key-value mapping is rendered as the key\n * followed by an equals sign (\"{@code =}\") followed by the\n * associated value.\n *\n * @return a string representation of this map\n */\n public String toString() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n StringBuilder sb = new StringBuilder();\n sb.append('{');\n Node p;\n if ((p = it.advance()) != null) {\n for (; ; ) {\n K k = p.key;\n V v = p.val;\n sb.append(k == this ? \"(this Map)\" : k);\n sb.append('=');\n sb.append(v == this ? \"(this Map)\" : v);\n if ((p = it.advance()) == null)\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append('}').toString();\n }\n\n /**\n * Compares the specified object with this map for equality.\n * Returns {@code true} if the given object is a map with the same\n * mappings as this map. This operation may return misleading\n * results if either map is concurrently modified during execution\n * of this method.\n *\n * @param o object to be compared for equality with this map\n * @return {@code true} if the specified object is equal to this map\n */\n public boolean equals(Object o) {\n if (o != this) {\n if (!(o instanceof Map))\n return false;\n Map m = (Map) o;\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n for (Node p; (p = it.advance()) != null; ) {\n V val = p.val;\n Object v = m.get(p.key);\n if (v == null || (v != val && !v.equals(val)))\n return false;\n }\n for (Map.Entry e : m.entrySet()) {\n Object mk, mv, v;\n if ((mk = e.getKey()) == null || (mv = e.getValue()) == null || (v = get(mk)) == null || (mv != v && !mv.equals(v)))\n return false;\n }\n }\n return true;\n }\n\n /**\n * Stripped-down version of helper class used in previous version,\n * declared for the sake of serialization compatibility.\n */\n static class Segment extends ReentrantLock implements Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n final float loadFactor;\n\n Segment(float lf) {\n this.loadFactor = lf;\n }\n }\n\n /**\n * Saves this map to a stream (that is, serializes it).\n *\n * @param s the stream\n * @throws java.io.IOException if an I/O error occurs\n * @serialData\n * the serialized fields, followed by the key (Object) and value\n * (Object) for each key-value mapping, followed by a null pair.\n * The key-value mappings are emitted in no particular order.\n */\n private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {\n // For serialization compatibility\n // Emulate segment calculation from previous version of this class\n int sshift = 0;\n int ssize = 1;\n while (ssize < DEFAULT_CONCURRENCY_LEVEL) {\n ++sshift;\n ssize <<= 1;\n }\n int segmentShift = 32 - sshift;\n int segmentMask = ssize - 1;\n @SuppressWarnings(\"unchecked\")\n Segment[] segments = (Segment[]) new Segment[DEFAULT_CONCURRENCY_LEVEL];\n for (int i = 0; i < segments.length; ++i) segments[i] = new Segment(LOAD_FACTOR);\n java.io.ObjectOutputStream.PutField streamFields = s.putFields();\n streamFields.put(\"segments\", segments);\n streamFields.put(\"segmentShift\", segmentShift);\n streamFields.put(\"segmentMask\", segmentMask);\n s.writeFields();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n s.writeObject(p.key);\n s.writeObject(p.val);\n }\n }\n s.writeObject(null);\n s.writeObject(null);\n }\n\n /**\n * Reconstitutes this map from a stream (that is, deserializes it).\n * @param s the stream\n * @throws ClassNotFoundException if the class of a serialized object\n * could not be found\n * @throws java.io.IOException if an I/O error occurs\n */\n private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {\n /*\n * To improve performance in typical cases, we create nodes\n * while reading, then place in table once size is known.\n * However, we must also validate uniqueness and deal with\n * overpopulated bins while doing so, which requires\n * specialized versions of putVal mechanics.\n */\n // force exclusion for table construction\n sizeCtl = -1;\n s.defaultReadObject();\n long size = 0L;\n Node p = null;\n for (; ; ) {\n @SuppressWarnings(\"unchecked\")\n K k = (K) s.readObject();\n @SuppressWarnings(\"unchecked\")\n V v = (V) s.readObject();\n if (k != null && v != null) {\n p = new Node(spread(k.hashCode()), k, v, p);\n ++size;\n } else\n break;\n }\n if (size == 0L)\n sizeCtl = 0;\n else {\n long ts = (long) (1.0 + size / LOAD_FACTOR);\n int n = (ts >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) ts);\n @SuppressWarnings(\"unchecked\")\n Node[] tab = (Node[]) new Node[n];\n int mask = n - 1;\n long added = 0L;\n while (p != null) {\n boolean insertAtFront;\n Node next = p.next, first;\n int h = p.hash, j = h & mask;\n if ((first = tabAt(tab, j)) == null)\n insertAtFront = true;\n else {\n K k = p.key;\n if (first.hash < 0) {\n TreeBin t = (TreeBin) first;\n if (t.putTreeVal(h, k, p.val) == null)\n ++added;\n insertAtFront = false;\n } else {\n int binCount = 0;\n insertAtFront = true;\n Node q;\n K qk;\n for (q = first; q != null; q = q.next) {\n if (q.hash == h && ((qk = q.key) == k || (qk != null && k.equals(qk)))) {\n insertAtFront = false;\n break;\n }\n ++binCount;\n }\n if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {\n insertAtFront = false;\n ++added;\n p.next = first;\n TreeNode hd = null, tl = null;\n for (q = p; q != null; q = q.next) {\n TreeNode t = new TreeNode(q.hash, q.key, q.val, null, null);\n if ((t.prev = tl) == null)\n hd = t;\n else\n tl.next = t;\n tl = t;\n }\n setTabAt(tab, j, new TreeBin(hd));\n }\n }\n }\n if (insertAtFront) {\n ++added;\n p.next = first;\n setTabAt(tab, j, p);\n }\n p = next;\n }\n table = tab;\n sizeCtl = n - (n >>> 2);\n baseCount = added;\n }\n }\n\n // ConcurrentMap methods\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V putIfAbsent(K key, V value) {\n return putVal(key, value, true);\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object key, Object value) {\n if (key == null)\n throw new NullPointerException();\n return value != null && replaceNode(key, null, value) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if any of the arguments are null\n */\n public boolean replace(K key, V oldValue, V newValue) {\n if (key == null || oldValue == null || newValue == null)\n throw new NullPointerException();\n return replaceNode(key, newValue, oldValue) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V replace(K key, V value) {\n if (key == null || value == null)\n throw new NullPointerException();\n return replaceNode(key, value, null);\n }\n\n // Overrides of JDK8+ Map extension method defaults\n /**\n * Returns the value to which the specified key is mapped, or the\n * given default value if this map contains no mapping for the\n * key.\n *\n * @param key the key whose associated value is to be returned\n * @param defaultValue the value to return if this map contains\n * no mapping for the given key\n * @return the mapping for the key, if present; else the default value\n * @throws NullPointerException if the specified key is null\n */\n public V getOrDefault(Object key, V defaultValue) {\n V v;\n return (v = get(key)) == null ? defaultValue : v;\n }\n\n public void forEach(BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n action.accept(p.key, p.val);\n }\n }\n }\n\n public void replaceAll(BiFunction function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V oldValue = p.val;\n for (K key = p.key; ; ) {\n V newValue = function.apply(key, oldValue);\n if (newValue == null)\n throw new NullPointerException();\n if (replaceNode(key, newValue, oldValue) != null || (oldValue = get(key)) == null)\n break;\n }\n }\n }\n }\n\n boolean removeEntryIf(Predicate> function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n Map.Entry e = new AbstractMap.SimpleImmutableEntry<>(k, v);\n if (function.test(e) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n boolean removeValueIf(Predicate function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n if (function.test(v) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n /**\n * If the specified key is not already associated with a value,\n * attempts to compute its value using the given mapping function\n * and enters it into this map unless {@code null}. The entire\n * method invocation is performed atomically. The supplied\n * function is invoked exactly once per invocation of this method\n * if the key is absent, else not at all. Some attempted update\n * operations on this map by other threads may be blocked while\n * computation is in progress, so the computation should be short\n * and simple.\n *\n *

The mapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param mappingFunction the function to compute a value\n * @return the current (existing or computed) value associated with\n * the specified key, or null if the computed value is null\n * @throws NullPointerException if the specified key or mappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the mappingFunction does so,\n * in which case the mapping is left unestablished\n */\n public V computeIfAbsent(K key, Function mappingFunction) {\n if (key == null || mappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = mappingFunction.apply(key)) != null)\n node = new Node(h, key, val);\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n fh == h && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n boolean added = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = e.val;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n if ((val = mappingFunction.apply(key)) != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n added = true;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null)\n val = p.val;\n else if ((val = mappingFunction.apply(key)) != null) {\n added = true;\n t.putTreeVal(h, key, val);\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (!added)\n return val;\n break;\n }\n }\n }\n if (val != null)\n addCount(1L, binCount);\n return val;\n }\n\n /**\n * If the value for the specified key is present, attempts to\n * compute a new mapping given the key and its current mapped\n * value. The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method if the key is present, else not at all. Some\n * attempted update operations on this map by other threads may be\n * blocked while computation is in progress, so the computation\n * should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which a value may be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V computeIfPresent(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null) {\n val = remappingFunction.apply(key, p.val);\n if (val != null)\n p.val = val;\n else {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0)\n break;\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * Attempts to compute a mapping for the specified key and its\n * current mapped value (or {@code null} if there is no current\n * mapping). The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method. Some attempted update operations on this map by\n * other threads may be blocked while computation is in progress,\n * so the computation should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V compute(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = remappingFunction.apply(key, null)) != null) {\n delta = 1;\n node = new Node(h, key, val);\n }\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n val = remappingFunction.apply(key, null);\n if (val != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n delta = 1;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 1;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null)\n p = r.findTreeNode(h, key, null);\n else\n p = null;\n V pv = (p == null) ? null : p.val;\n val = remappingFunction.apply(key, pv);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * If the specified key is not already associated with a\n * (non-null) value, associates it with the given value.\n * Otherwise, replaces the value with the results of the given\n * remapping function, or removes if {@code null}. The entire\n * method invocation is performed atomically. Some attempted\n * update operations on this map by other threads may be blocked\n * while computation is in progress, so the computation should be\n * short and simple, and must not attempt to update any other\n * mappings of this Map.\n *\n * @param key key with which the specified value is to be associated\n * @param value the value to use if absent\n * @param remappingFunction the function to recompute a value if present\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or the\n * remappingFunction is null\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V merge(K key, V value, BiFunction remappingFunction) {\n if (key == null || value == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n if (casTabAt(tab, i, null, new Node(h, key, value))) {\n delta = 1;\n val = value;\n break;\n }\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(e.val, value);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n delta = 1;\n val = value;\n pred.next = new Node(h, key, val);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r = t.root;\n TreeNode p = (r == null) ? null : r.findTreeNode(h, key, null);\n val = (p == null) ? value : remappingFunction.apply(p.val, value);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n // Hashtable legacy methods\n /**\n * Tests if some key maps into the specified value in this table.\n *\n *

Note that this method is identical in functionality to\n * {@link #containsValue(Object)}, and exists solely to ensure\n * full compatibility with class {@link java.util.Hashtable},\n * which supported this method prior to introduction of the\n * Java Collections Framework.\n *\n * @param value a value to search for\n * @return {@code true} if and only if some key maps to the\n * {@code value} argument in this table as\n * determined by the {@code equals} method;\n * {@code false} otherwise\n * @throws NullPointerException if the specified value is null\n */\n public boolean contains(Object value) {\n return containsValue(value);\n }\n\n /**\n * Returns an enumeration of the keys in this table.\n *\n * @return an enumeration of the keys in this table\n * @see #keySet()\n */\n public Enumeration keys() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, this);\n }\n\n /**\n * Returns an enumeration of the values in this table.\n *\n * @return an enumeration of the values in this table\n * @see #values()\n */\n public Enumeration elements() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, this);\n }\n\n // ConcurrentHashMap-only methods\n /**\n * Returns the number of mappings. This method should be used\n * instead of {@link #size} because a ConcurrentHashMap may\n * contain more mappings than can be represented as an int. The\n * value returned is an estimate; the actual count may differ if\n * there are concurrent insertions or removals.\n *\n * @return the number of mappings\n * @since 1.8\n */\n public long mappingCount() {\n long n = sumCount();\n // ignore transient negative values\n return (n < 0L) ? 0L : n;\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param the element type of the returned set\n * @return the new set\n * @since 1.8\n */\n public static KeySetView newKeySet() {\n return new KeySetView(new ConcurrentHashMap(), Boolean.TRUE);\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @param the element type of the returned set\n * @return the new set\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n * @since 1.8\n */\n public static KeySetView newKeySet(int initialCapacity) {\n return new KeySetView(new ConcurrentHashMap(initialCapacity), Boolean.TRUE);\n }\n\n /**\n * Returns a {@link Set} view of the keys in this map, using the\n * given common mapped value for any additions (i.e., {@link\n * Collection#add} and {@link Collection#addAll(Collection)}).\n * This is of course only appropriate if it is acceptable to use\n * the same value for all additions from this view.\n *\n * @param mappedValue the mapped value to use for any additions\n * @return the set view\n * @throws NullPointerException if the mappedValue is null\n */\n public KeySetView keySet(V mappedValue) {\n if (mappedValue == null)\n throw new NullPointerException();\n return new KeySetView(this, mappedValue);\n }\n\n /**\n * A node inserted at head of bins during transfer operations.\n */\n static final class ForwardingNode extends Node {\n\n final Node[] nextTable;\n\n ForwardingNode(Node[] tab) {\n super(MOVED, null, null);\n this.nextTable = tab;\n }\n\n Node find(int h, Object k) {\n // loop to avoid arbitrarily deep recursion on forwarding nodes\n outer: for (Node[] tab = nextTable; ; ) {\n Node e;\n int n;\n if (k == null || tab == null || (n = tab.length) == 0 || (e = tabAt(tab, (n - 1) & h)) == null)\n return null;\n for (; ; ) {\n int eh;\n K ek;\n if ((eh = e.hash) == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n if (eh < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n continue outer;\n } else\n return e.find(h, k);\n }\n if ((e = e.next) == null)\n return null;\n }\n }\n }\n }\n\n /**\n * A place-holder node used in computeIfAbsent and compute.\n */\n static final class ReservationNode extends Node {\n\n ReservationNode() {\n super(RESERVED, null, null);\n }\n\n Node find(int h, Object k) {\n return null;\n }\n }\n\n /* ---------------- Table Initialization and Resizing -------------- */\n /**\n * Returns the stamp bits for resizing a table of size n.\n * Must be negative when shifted left by RESIZE_STAMP_SHIFT.\n */\n static final int resizeStamp(int n) {\n return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));\n }\n\n /**\n * Initializes table, using the size recorded in sizeCtl.\n */\n private final Node[] initTable() {\n Node[] tab;\n int sc;\n while ((tab = table) == null || tab.length == 0) {\n if ((sc = sizeCtl) < 0)\n // lost initialization race; just spin\n Thread.yield();\n else if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if ((tab = table) == null || tab.length == 0) {\n int n = (sc > 0) ? sc : DEFAULT_CAPACITY;\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = tab = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n break;\n }\n }\n return tab;\n }\n\n /**\n * Adds to count, and if table is too small and not already\n * resizing, initiates transfer. If already resizing, helps\n * perform transfer if work is available. Rechecks occupancy\n * after a transfer to see if another resize is already needed\n * because resizings are lagging additions.\n *\n * @param x the count to add\n * @param check if <0, don't check resize, if <= 1 only check if uncontended\n */\n private final void addCount(long x, int check) {\n CounterCell[] cs;\n long b, s;\n if ((cs = counterCells) != null || !U.compareAndSetLong(this, BASECOUNT, b = baseCount, s = b + x)) {\n CounterCell c;\n long v;\n int m;\n boolean uncontended = true;\n if (cs == null || (m = cs.length - 1) < 0 || (c = cs[ThreadLocalRandom.getProbe() & m]) == null || !(uncontended = U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))) {\n fullAddCount(x, uncontended);\n return;\n }\n if (check <= 1)\n return;\n s = sumCount();\n }\n if (check >= 0) {\n Node[] tab, nt;\n int n, sc;\n while (s >= (long) (sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) {\n int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT;\n if (sc < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || (nt = nextTable) == null || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1))\n transfer(tab, nt);\n } else if (U.compareAndSetInt(this, SIZECTL, sc, rs + 2))\n transfer(tab, null);\n s = sumCount();\n }\n }\n }\n\n /**\n * Helps transfer if a resize is in progress.\n */\n final Node[] helpTransfer(Node[] tab, Node f) {\n Node[] nextTab;\n int sc;\n if (tab != null && (f instanceof ForwardingNode) && (nextTab = ((ForwardingNode) f).nextTable) != null) {\n int rs = resizeStamp(tab.length) << RESIZE_STAMP_SHIFT;\n while (nextTab == nextTable && table == tab && (sc = sizeCtl) < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1)) {\n transfer(tab, nextTab);\n break;\n }\n }\n return nextTab;\n }\n return table;\n }\n\n /**\n * Tries to presize table to accommodate the given number of elements.\n *\n * @param size number of elements (doesn't need to be perfectly accurate)\n */\n private final void tryPresize(int size) {\n int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(size + (size >>> 1) + 1);\n int sc;\n while ((sc = sizeCtl) >= 0) {\n Node[] tab = table;\n int n;\n if (tab == null || (n = tab.length) == 0) {\n n = (sc > c) ? sc : c;\n if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if (table == tab) {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n }\n } else if (c <= sc || n >= MAXIMUM_CAPACITY)\n break;\n else if (tab == table) {\n int rs = resizeStamp(n);\n if (U.compareAndSetInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2))\n transfer(tab, null);\n }\n }\n }\n\n /**\n * Moves and/or copies the nodes in each bin to new table. See\n * above for explanation.\n */\n private final void transfer(Node[] tab, Node[] nextTab) {\n int n = tab.length, stride;\n if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)\n // subdivide range\n stride = MIN_TRANSFER_STRIDE;\n if (nextTab == null) {\n // initiating\n try {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n << 1];\n nextTab = nt;\n } catch (Throwable ex) {\n // try to cope with OOME\n sizeCtl = Integer.MAX_VALUE;\n return;\n }\n nextTable = nextTab;\n transferIndex = n;\n }\n int nextn = nextTab.length;\n ForwardingNode fwd = new ForwardingNode(nextTab);\n boolean advance = true;\n // to ensure sweep before committing nextTab\n boolean finishing = false;\n for (int i = 0, bound = 0; ; ) {\n Node f;\n int fh;\n while (advance) {\n int nextIndex, nextBound;\n if (--i >= bound || finishing)\n advance = false;\n else if ((nextIndex = transferIndex) <= 0) {\n i = -1;\n advance = false;\n } else if (U.compareAndSetInt(this, TRANSFERINDEX, nextIndex, nextBound = (nextIndex > stride ? nextIndex - stride : 0))) {\n bound = nextBound;\n i = nextIndex - 1;\n advance = false;\n }\n }\n if (i < 0 || i >= n || i + n >= nextn) {\n int sc;\n if (finishing) {\n nextTable = null;\n table = nextTab;\n sizeCtl = (n << 1) - (n >>> 1);\n return;\n }\n if (U.compareAndSetInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {\n if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)\n return;\n finishing = advance = true;\n // recheck before commit\n i = n;\n }\n } else if ((f = tabAt(tab, i)) == null)\n advance = casTabAt(tab, i, null, fwd);\n else if ((fh = f.hash) == MOVED)\n // already processed\n advance = true;\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node ln, hn;\n if (fh >= 0) {\n int runBit = fh & n;\n Node lastRun = f;\n for (Node p = f.next; p != null; p = p.next) {\n int b = p.hash & n;\n if (b != runBit) {\n runBit = b;\n lastRun = p;\n }\n }\n if (runBit == 0) {\n ln = lastRun;\n hn = null;\n } else {\n hn = lastRun;\n ln = null;\n }\n for (Node p = f; p != lastRun; p = p.next) {\n int ph = p.hash;\n K pk = p.key;\n V pv = p.val;\n if ((ph & n) == 0)\n ln = new Node(ph, pk, pv, ln);\n else\n hn = new Node(ph, pk, pv, hn);\n }\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof TreeBin) {\n TreeBin t = (TreeBin) f;\n TreeNode lo = null, loTail = null;\n TreeNode hi = null, hiTail = null;\n int lc = 0, hc = 0;\n for (Node e = t.first; e != null; e = e.next) {\n int h = e.hash;\n TreeNode p = new TreeNode(h, e.key, e.val, null, null);\n if ((h & n) == 0) {\n if ((p.prev = loTail) == null)\n lo = p;\n else\n loTail.next = p;\n loTail = p;\n ++lc;\n } else {\n if ((p.prev = hiTail) == null)\n hi = p;\n else\n hiTail.next = p;\n hiTail = p;\n ++hc;\n }\n }\n ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : (hc != 0) ? new TreeBin(lo) : t;\n hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : (lc != 0) ? new TreeBin(hi) : t;\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n }\n }\n }\n\n /**\n * A padded cell for distributing counts. Adapted from LongAdder\n * and Striped64. See their internal docs for explanation.\n */\n @jdk.internal.vm.annotation.Contended\n static final class CounterCell {\n\n volatile long value;\n\n CounterCell(long x) {\n value = x;\n }\n }\n\n final long sumCount() {\n CounterCell[] cs = counterCells;\n long sum = baseCount;\n if (cs != null) {\n for (CounterCell c : cs) if (c != null)\n sum += c.value;\n }\n return sum;\n }\n\n // See LongAdder version for explanation\n private final void fullAddCount(long x, boolean wasUncontended) {\n int h;\n if ((h = ThreadLocalRandom.getProbe()) == 0) {\n // force initialization\n ThreadLocalRandom.localInit();\n h = ThreadLocalRandom.getProbe();\n wasUncontended = true;\n }\n // True if last slot nonempty\n boolean collide = false;\n for (; ; ) {\n CounterCell[] cs;\n CounterCell c;\n int n;\n long v;\n if ((cs = counterCells) != null && (n = cs.length) > 0) {\n if ((c = cs[(n - 1) & h]) == null) {\n if (cellsBusy == 0) {\n // Try to attach new Cell\n // Optimistic create\n CounterCell r = new CounterCell(x);\n if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean created = false;\n try {\n // Recheck under lock\n CounterCell[] rs;\n int m, j;\n if ((rs = counterCells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) {\n rs[j] = r;\n created = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (created)\n break;\n // Slot is now non-empty\n continue;\n }\n }\n collide = false;\n } else if (// CAS already known to fail\n !wasUncontended)\n // Continue after rehash\n wasUncontended = true;\n else if (U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))\n break;\n else if (counterCells != cs || n >= NCPU)\n // At max size or stale\n collide = false;\n else if (!collide)\n collide = true;\n else if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n try {\n if (// Expand table unless stale\n counterCells == cs)\n counterCells = Arrays.copyOf(cs, n << 1);\n } finally {\n cellsBusy = 0;\n }\n collide = false;\n // Retry with expanded table\n continue;\n }\n h = ThreadLocalRandom.advanceProbe(h);\n } else if (cellsBusy == 0 && counterCells == cs && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean init = false;\n try {\n // Initialize table\n if (counterCells == cs) {\n CounterCell[] rs = new CounterCell[2];\n rs[h & 1] = new CounterCell(x);\n counterCells = rs;\n init = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (init)\n break;\n } else if (U.compareAndSetLong(this, BASECOUNT, v = baseCount, v + x))\n // Fall back on using base\n break;\n }\n }\n\n /**\n * Replaces all linked nodes in bin at given index unless table is\n * too small, in which case resizes instead.\n */\n private final void treeifyBin(Node[] tab, int index) {\n Node b;\n int n;\n if (tab != null) {\n if ((n = tab.length) < MIN_TREEIFY_CAPACITY)\n tryPresize(n << 1);\n else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {\n synchronized (b) {\n if (tabAt(tab, index) == b) {\n TreeNode hd = null, tl = null;\n for (Node e = b; e != null; e = e.next) {\n TreeNode p = new TreeNode(e.hash, e.key, e.val, null, null);\n if ((p.prev = tl) == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n setTabAt(tab, index, new TreeBin(hd));\n }\n }\n }\n }\n }\n\n /**\n * Returns a list of non-TreeNodes replacing those in given list.\n */\n static Node untreeify(Node b) {\n Node hd = null, tl = null;\n for (Node q = b; q != null; q = q.next) {\n Node p = new Node(q.hash, q.key, q.val);\n if (tl == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n return hd;\n }\n\n /**\n * Nodes for use in TreeBins.\n */\n static final class TreeNode extends Node {\n\n // red-black tree links\n TreeNode parent;\n\n TreeNode left;\n\n TreeNode right;\n\n // needed to unlink next upon deletion\n TreeNode prev;\n\n boolean red;\n\n TreeNode(int hash, K key, V val, Node next, TreeNode parent) {\n super(hash, key, val, next);\n this.parent = parent;\n }\n\n Node find(int h, Object k) {\n return findTreeNode(h, k, null);\n }\n\n /**\n * Returns the TreeNode (or null if not found) for the given key\n * starting at given root.\n */\n final TreeNode findTreeNode(int h, Object k, Class kc) {\n if (k != null) {\n TreeNode p = this;\n do {\n int ph, dir;\n K pk;\n TreeNode q;\n TreeNode pl = p.left, pr = p.right;\n if ((ph = p.hash) > h)\n p = pl;\n else if (ph < h)\n p = pr;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if (pl == null)\n p = pr;\n else if (pr == null)\n p = pl;\n else if ((kc != null || (kc = comparableClassFor(k)) != null) && (dir = compareComparables(kc, k, pk)) != 0)\n p = (dir < 0) ? pl : pr;\n else if ((q = pr.findTreeNode(h, k, kc)) != null)\n return q;\n else\n p = pl;\n } while (p != null);\n }\n return null;\n }\n }\n\n /**\n * TreeNodes used at the heads of bins. TreeBins do not hold user\n * keys or values, but instead point to list of TreeNodes and\n * their root. They also maintain a parasitic read-write lock\n * forcing writers (who hold bin lock) to wait for readers (who do\n * not) to complete before tree restructuring operations.\n */\n static final class TreeBin extends Node {\n\n TreeNode root;\n\n volatile TreeNode first;\n\n volatile Thread waiter;\n\n volatile int lockState;\n\n // values for lockState\n // set while holding write lock\n static final int WRITER = 1;\n\n // set when waiting for write lock\n static final int WAITER = 2;\n\n // increment value for setting read lock\n static final int READER = 4;\n\n /**\n * Tie-breaking utility for ordering insertions when equal\n * hashCodes and non-comparable. We don't require a total\n * order, just a consistent insertion rule to maintain\n * equivalence across rebalancings. Tie-breaking further than\n * necessary simplifies testing a bit.\n */\n static int tieBreakOrder(Object a, Object b) {\n int d;\n if (a == null || b == null || (d = a.getClass().getName().compareTo(b.getClass().getName())) == 0)\n d = (System.identityHashCode(a) <= System.identityHashCode(b) ? -1 : 1);\n return d;\n }\n\n /**\n * Creates bin with initial set of nodes headed by b.\n */\n TreeBin(TreeNode b) {\n super(TREEBIN, null, null);\n this.first = b;\n TreeNode r = null;\n for (TreeNode x = b, next; x != null; x = next) {\n next = (TreeNode) x.next;\n x.left = x.right = null;\n if (r == null) {\n x.parent = null;\n x.red = false;\n r = x;\n } else {\n K k = x.key;\n int h = x.hash;\n Class kc = null;\n for (TreeNode p = r; ; ) {\n int dir, ph;\n K pk = p.key;\n if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0)\n dir = tieBreakOrder(k, pk);\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n x.parent = xp;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n r = balanceInsertion(r, x);\n break;\n }\n }\n }\n }\n this.root = r;\n assert checkInvariants(root);\n }\n\n /**\n * Acquires write lock for tree restructuring.\n */\n private final void lockRoot() {\n if (!U.compareAndSetInt(this, LOCKSTATE, 0, WRITER))\n // offload to separate method\n contendedLock();\n }\n\n /**\n * Releases write lock for tree restructuring.\n */\n private final void unlockRoot() {\n lockState = 0;\n }\n\n /**\n * Possibly blocks awaiting root lock.\n */\n private final void contendedLock() {\n boolean waiting = false;\n for (int s; ; ) {\n if (((s = lockState) & ~WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, WRITER)) {\n if (waiting)\n waiter = null;\n return;\n }\n } else if ((s & WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, s | WAITER)) {\n waiting = true;\n waiter = Thread.currentThread();\n }\n } else if (waiting)\n LockSupport.park(this);\n }\n }\n\n /**\n * Returns matching node or null if none. Tries to search\n * using tree comparisons from root, but continues linear\n * search when lock not available.\n */\n final Node find(int h, Object k) {\n if (k != null) {\n for (Node e = first; e != null; ) {\n int s;\n K ek;\n if (((s = lockState) & (WAITER | WRITER)) != 0) {\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n e = e.next;\n } else if (U.compareAndSetInt(this, LOCKSTATE, s, s + READER)) {\n TreeNode r, p;\n try {\n p = ((r = root) == null ? null : r.findTreeNode(h, k, null));\n } finally {\n Thread w;\n if (U.getAndAddInt(this, LOCKSTATE, -READER) == (READER | WAITER) && (w = waiter) != null)\n LockSupport.unpark(w);\n }\n return p;\n }\n }\n }\n return null;\n }\n\n /**\n * Finds or adds a node.\n * @return null if added\n */\n final TreeNode putTreeVal(int h, K k, V v) {\n Class kc = null;\n boolean searched = false;\n for (TreeNode p = root; ; ) {\n int dir, ph;\n K pk;\n if (p == null) {\n first = root = new TreeNode(h, k, v, null, null);\n break;\n } else if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) {\n if (!searched) {\n TreeNode q, ch;\n searched = true;\n if (((ch = p.left) != null && (q = ch.findTreeNode(h, k, kc)) != null) || ((ch = p.right) != null && (q = ch.findTreeNode(h, k, kc)) != null))\n return q;\n }\n dir = tieBreakOrder(k, pk);\n }\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n TreeNode x, f = first;\n first = x = new TreeNode(h, k, v, f, xp);\n if (f != null)\n f.prev = x;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n if (!xp.red)\n x.red = true;\n else {\n lockRoot();\n try {\n root = balanceInsertion(root, x);\n } finally {\n unlockRoot();\n }\n }\n break;\n }\n }\n assert checkInvariants(root);\n return null;\n }\n\n /**\n * Removes the given node, that must be present before this\n * call. This is messier than typical red-black deletion code\n * because we cannot swap the contents of an interior node\n * with a leaf successor that is pinned by \"next\" pointers\n * that are accessible independently of lock. So instead we\n * swap the tree linkages.\n *\n * @return true if now too small, so should be untreeified\n */\n final boolean removeTreeNode(TreeNode p) {\n TreeNode next = (TreeNode) p.next;\n // unlink traversal pointers\n TreeNode pred = p.prev;\n TreeNode r, rl;\n if (pred == null)\n first = next;\n else\n pred.next = next;\n if (next != null)\n next.prev = pred;\n if (first == null) {\n root = null;\n return true;\n }\n if (// too small\n (r = root) == null || r.right == null || (rl = r.left) == null || rl.left == null)\n return true;\n lockRoot();\n try {\n TreeNode replacement;\n TreeNode pl = p.left;\n TreeNode pr = p.right;\n if (pl != null && pr != null) {\n TreeNode s = pr, sl;\n while (// find successor\n (sl = s.left) != null) s = sl;\n // swap colors\n boolean c = s.red;\n // swap colors\n s.red = p.red;\n // swap colors\n p.red = c;\n TreeNode sr = s.right;\n TreeNode pp = p.parent;\n if (s == pr) {\n // p was s's direct parent\n p.parent = s;\n s.right = p;\n } else {\n TreeNode sp = s.parent;\n if ((p.parent = sp) != null) {\n if (s == sp.left)\n sp.left = p;\n else\n sp.right = p;\n }\n if ((s.right = pr) != null)\n pr.parent = s;\n }\n p.left = null;\n if ((p.right = sr) != null)\n sr.parent = p;\n if ((s.left = pl) != null)\n pl.parent = s;\n if ((s.parent = pp) == null)\n r = s;\n else if (p == pp.left)\n pp.left = s;\n else\n pp.right = s;\n if (sr != null)\n replacement = sr;\n else\n replacement = p;\n } else if (pl != null)\n replacement = pl;\n else if (pr != null)\n replacement = pr;\n else\n replacement = p;\n if (replacement != p) {\n TreeNode pp = replacement.parent = p.parent;\n if (pp == null)\n r = replacement;\n else if (p == pp.left)\n pp.left = replacement;\n else\n pp.right = replacement;\n p.left = p.right = p.parent = null;\n }\n root = (p.red) ? r : balanceDeletion(r, replacement);\n if (p == replacement) {\n // detach pointers\n TreeNode pp;\n if ((pp = p.parent) != null) {\n if (p == pp.left)\n pp.left = null;\n else if (p == pp.right)\n pp.right = null;\n p.parent = null;\n }\n }\n } finally {\n unlockRoot();\n }\n assert checkInvariants(root);\n return false;\n }\n\n // Red-black tree methods, all adapted from CLR\n static TreeNode rotateLeft(TreeNode root, TreeNode p) {\n TreeNode r, pp, rl;\n if (p != null && (r = p.right) != null) {\n if ((rl = p.right = r.left) != null)\n rl.parent = p;\n if ((pp = r.parent = p.parent) == null)\n (root = r).red = false;\n else if (pp.left == p)\n pp.left = r;\n else\n pp.right = r;\n r.left = p;\n p.parent = r;\n }\n return root;\n }\n\n static TreeNode rotateRight(TreeNode root, TreeNode p) {\n TreeNode l, pp, lr;\n if (p != null && (l = p.left) != null) {\n if ((lr = p.left = l.right) != null)\n lr.parent = p;\n if ((pp = l.parent = p.parent) == null)\n (root = l).red = false;\n else if (pp.right == p)\n pp.right = l;\n else\n pp.left = l;\n l.right = p;\n p.parent = l;\n }\n return root;\n }\n\n static TreeNode balanceInsertion(TreeNode root, TreeNode x) {\n x.red = true;\n for (TreeNode xp, xpp, xppl, xppr; ; ) {\n if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (!xp.red || (xpp = xp.parent) == null)\n return root;\n if (xp == (xppl = xpp.left)) {\n if ((xppr = xpp.right) != null && xppr.red) {\n xppr.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.right) {\n root = rotateLeft(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateRight(root, xpp);\n }\n }\n }\n } else {\n if (xppl != null && xppl.red) {\n xppl.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.left) {\n root = rotateRight(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateLeft(root, xpp);\n }\n }\n }\n }\n }\n }\n\n static TreeNode balanceDeletion(TreeNode root, TreeNode x) {\n for (TreeNode xp, xpl, xpr; ; ) {\n if (x == null || x == root)\n return root;\n else if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (x.red) {\n x.red = false;\n return root;\n } else if ((xpl = xp.left) == x) {\n if ((xpr = xp.right) != null && xpr.red) {\n xpr.red = false;\n xp.red = true;\n root = rotateLeft(root, xp);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr == null)\n x = xp;\n else {\n TreeNode sl = xpr.left, sr = xpr.right;\n if ((sr == null || !sr.red) && (sl == null || !sl.red)) {\n xpr.red = true;\n x = xp;\n } else {\n if (sr == null || !sr.red) {\n if (sl != null)\n sl.red = false;\n xpr.red = true;\n root = rotateRight(root, xpr);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr != null) {\n xpr.red = (xp == null) ? false : xp.red;\n if ((sr = xpr.right) != null)\n sr.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateLeft(root, xp);\n }\n x = root;\n }\n }\n } else {\n // symmetric\n if (xpl != null && xpl.red) {\n xpl.red = false;\n xp.red = true;\n root = rotateRight(root, xp);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl == null)\n x = xp;\n else {\n TreeNode sl = xpl.left, sr = xpl.right;\n if ((sl == null || !sl.red) && (sr == null || !sr.red)) {\n xpl.red = true;\n x = xp;\n } else {\n if (sl == null || !sl.red) {\n if (sr != null)\n sr.red = false;\n xpl.red = true;\n root = rotateLeft(root, xpl);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl != null) {\n xpl.red = (xp == null) ? false : xp.red;\n if ((sl = xpl.left) != null)\n sl.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateRight(root, xp);\n }\n x = root;\n }\n }\n }\n }\n }\n\n /**\n * Checks invariants recursively for the tree of Nodes rooted at t.\n */\n static boolean checkInvariants(TreeNode t) {\n TreeNode tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode) t.next;\n if (tb != null && tb.next != t)\n return false;\n if (tn != null && tn.prev != t)\n return false;\n if (tp != null && t != tp.left && t != tp.right)\n return false;\n if (tl != null && (tl.parent != t || tl.hash > t.hash))\n return false;\n if (tr != null && (tr.parent != t || tr.hash < t.hash))\n return false;\n if (t.red && tl != null && tl.red && tr != null && tr.red)\n return false;\n if (tl != null && !checkInvariants(tl))\n return false;\n if (tr != null && !checkInvariants(tr))\n return false;\n return true;\n }\n\n private static final long LOCKSTATE = U.objectFieldOffset(TreeBin.class, \"lockState\");\n }\n\n /**\n * Records the table, its length, and current traversal index for a\n * traverser that must process a region of a forwarded table before\n * proceeding with current table.\n */\n static final class TableStack {\n\n int length;\n\n int index;\n\n Node[] tab;\n\n TableStack next;\n }\n\n /**\n * Encapsulates traversal for methods such as containsValue; also\n * serves as a base class for other iterators and spliterators.\n *\n * Method advance visits once each still-valid node that was\n * reachable upon iterator construction. It might miss some that\n * were added to a bin after the bin was visited, which is OK wrt\n * consistency guarantees. Maintaining this property in the face\n * of possible ongoing resizes requires a fair amount of\n * bookkeeping state that is difficult to optimize away amidst\n * volatile accesses. Even so, traversal maintains reasonable\n * throughput.\n *\n * Normally, iteration proceeds bin-by-bin traversing lists.\n * However, if the table has been resized, then all future steps\n * must traverse both the bin at the current index as well as at\n * (index + baseSize); and so on for further resizings. To\n * paranoically cope with potential sharing by users of iterators\n * across threads, iteration terminates if a bounds checks fails\n * for a table read.\n */\n static class Traverser {\n\n // current table; updated if resized\n Node[] tab;\n\n // the next entry to use\n Node next;\n\n // to save/restore on ForwardingNodes\n TableStack stack, spare;\n\n // index of bin to use next\n int index;\n\n // current index of initial table\n int baseIndex;\n\n // index bound for initial table\n int baseLimit;\n\n // initial table size\n final int baseSize;\n\n Traverser(Node[] tab, int size, int index, int limit) {\n this.tab = tab;\n this.baseSize = size;\n this.baseIndex = this.index = index;\n this.baseLimit = limit;\n this.next = null;\n }\n\n /**\n * Advances if possible, returning next valid node, or null if none.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n // must use locals in checks\n Node[] t;\n // must use locals in checks\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n // visit upper slots if present\n index = ++baseIndex;\n }\n }\n\n /**\n * Saves traversal state upon encountering a forwarding node.\n */\n private void pushState(Node[] t, int i, int n) {\n // reuse if possible\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n /**\n * Possibly pops traversal state.\n *\n * @param n length of current table\n */\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /**\n * Base of key, value, and entry Iterators. Adds fields to\n * Traverser to support iterator.remove.\n */\n static class BaseIterator extends Traverser {\n\n final ConcurrentHashMap map;\n\n Node lastReturned;\n\n BaseIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n advance();\n }\n\n public final boolean hasNext() {\n return next != null;\n }\n\n public final boolean hasMoreElements() {\n return next != null;\n }\n\n public final void remove() {\n Node p;\n if ((p = lastReturned) == null)\n throw new IllegalStateException();\n lastReturned = null;\n map.replaceNode(p.key, null, null);\n }\n }\n\n static final class KeyIterator extends BaseIterator implements Iterator, Enumeration {\n\n KeyIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final K next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n lastReturned = p;\n advance();\n return k;\n }\n\n public final K nextElement() {\n return next();\n }\n }\n\n static final class ValueIterator extends BaseIterator implements Iterator, Enumeration {\n\n ValueIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final V next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n V v = p.val;\n lastReturned = p;\n advance();\n return v;\n }\n\n public final V nextElement() {\n return next();\n }\n }\n\n static final class EntryIterator extends BaseIterator implements Iterator> {\n\n EntryIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final Map.Entry next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n V v = p.val;\n lastReturned = p;\n advance();\n return new MapEntry(k, v, map);\n }\n }\n\n static final class MapEntry implements Map.Entry {\n\n final K key;\n\n V val;\n\n final ConcurrentHashMap map;\n\n MapEntry(K key, V val, ConcurrentHashMap map) {\n this.key = key;\n this.val = val;\n this.map = map;\n }\n\n public K getKey() {\n return key;\n }\n\n public V getValue() {\n return val;\n }\n\n public int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public boolean equals(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == val || v.equals(val)));\n }\n\n /**\n * Sets our entry's value and writes through to the map. The\n * value to return is somewhat arbitrary here. Since we do not\n * necessarily track asynchronous changes, the most recent\n * \"previous\" value could be different from what we return (or\n * could even have been removed, in which case the put will\n * re-establish). We do not and cannot guarantee more.\n */\n public V setValue(V value) {\n if (value == null)\n throw new NullPointerException();\n V v = val;\n val = value;\n map.put(key, value);\n return v;\n }\n }\n\n static final class KeySpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n KeySpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public KeySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new KeySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.key);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class ValueSpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n ValueSpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public ValueSpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new ValueSpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.val);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class EntrySpliterator extends Traverser implements Spliterator> {\n\n // To export MapEntry\n final ConcurrentHashMap map;\n\n // size estimate\n long est;\n\n EntrySpliterator(Node[] tab, int size, int index, int limit, long est, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n this.est = est;\n }\n\n public EntrySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new EntrySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1, map);\n }\n\n public void forEachRemaining(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n\n public boolean tryAdvance(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(new MapEntry(p.key, p.val, map));\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n // Parallel bulk operations\n /**\n * Computes initial batch value for bulk tasks. The returned value\n * is approximately exp2 of the number of times (minus one) to\n * split task by two before executing leaf action. This value is\n * faster to compute and more convenient to use as a guide to\n * splitting than is the depth, since it is used while dividing by\n * two anyway.\n */\n final int batchFor(long b) {\n long n;\n if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)\n return 0;\n // slack of 4\n int sp = ForkJoinPool.getCommonPoolParallelism() << 2;\n return (b <= 0L || (n /= b) >= sp) ? sp : (int) n;\n }\n\n /**\n * Performs the given action for each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiFunction transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each (key, value), or null if none. Upon\n * success, further element processing is suppressed and the\n * results of any other parallel invocations of the search\n * function are ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each (key, value), or null if none\n * @since 1.8\n */\n public U search(long parallelismThreshold, BiFunction searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public U reduce(long parallelismThreshold, BiFunction transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public double reduceToDouble(long parallelismThreshold, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public long reduceToLong(long parallelismThreshold, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public int reduceToInt(long parallelismThreshold, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each key, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each key, or null if none\n * @since 1.8\n */\n public U searchKeys(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all keys using the given\n * reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all keys using the given\n * reducer to combine values, or null if none\n * @since 1.8\n */\n public K reduceKeys(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public U reduceKeys(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public double reduceKeysToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public long reduceKeysToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public int reduceKeysToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachValueTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedValueTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each value, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each value, or null if none\n * @since 1.8\n */\n public U searchValues(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all values using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all values\n * @since 1.8\n */\n public V reduceValues(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public U reduceValues(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public double reduceValuesToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public long reduceValuesToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public int reduceValuesToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Function, ? extends U> transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each entry, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each entry, or null if none\n * @since 1.8\n */\n public U searchEntries(long parallelismThreshold, Function, ? extends U> searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all entries using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all entries\n * @since 1.8\n */\n public Map.Entry reduceEntries(long parallelismThreshold, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public U reduceEntries(long parallelismThreshold, Function, ? extends U> transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public double reduceEntriesToDouble(long parallelismThreshold, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public long reduceEntriesToLong(long parallelismThreshold, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public int reduceEntriesToInt(long parallelismThreshold, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n abstract static class CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n final ConcurrentHashMap map;\n\n CollectionView(ConcurrentHashMap map) {\n this.map = map;\n }\n\n /**\n * Returns the map backing this view.\n *\n * @return the map backing this view\n */\n public ConcurrentHashMap getMap() {\n return map;\n }\n\n /**\n * Removes all of the elements from this view, by removing all\n * the mappings from the map backing this view.\n */\n public final void clear() {\n map.clear();\n }\n\n public final int size() {\n return map.size();\n }\n\n public final boolean isEmpty() {\n return map.isEmpty();\n }\n\n // implementations below rely on concrete classes supplying these\n /**\n * Returns an iterator over the elements in this collection.\n *\n *

The returned iterator is\n * weakly consistent.\n *\n * @return an iterator over the elements in this collection\n */\n public abstract Iterator iterator();\n\n public abstract boolean contains(Object o);\n\n public abstract boolean remove(Object o);\n\n private static final String OOME_MSG = \"Required array size too large\";\n\n public final Object[] toArray() {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int n = (int) sz;\n Object[] r = new Object[n];\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = e;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n @SuppressWarnings(\"unchecked\")\n public final T[] toArray(T[] a) {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int m = (int) sz;\n T[] r = (a.length >= m) ? a : (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), m);\n int n = r.length;\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = (T) e;\n }\n if (a == r && i < n) {\n r[i] = null;\n return r;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n /**\n * Returns a string representation of this collection.\n * The string representation consists of the string representations\n * of the collection's elements in the order they are returned by\n * its iterator, enclosed in square brackets ({@code \"[]\"}).\n * Adjacent elements are separated by the characters {@code \", \"}\n * (comma and space). Elements are converted to strings as by\n * {@link String#valueOf(Object)}.\n *\n * @return a string representation of this collection\n */\n public final String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append('[');\n Iterator it = iterator();\n if (it.hasNext()) {\n for (; ; ) {\n Object e = it.next();\n sb.append(e == this ? \"(this Collection)\" : e);\n if (!it.hasNext())\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append(']').toString();\n }\n\n public final boolean containsAll(Collection c) {\n if (c != this) {\n for (Object e : c) {\n if (e == null || !contains(e))\n return false;\n }\n }\n return true;\n }\n\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n // Use (c instanceof Set) as a hint that lookup in c is as\n // efficient as this view\n Node[] t;\n if ((t = map.table) == null) {\n return false;\n } else if (c instanceof Set && c.size() > t.length) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n } else {\n for (Object e : c) modified |= remove(e);\n }\n return modified;\n }\n\n public final boolean retainAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (!c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of keys, in\n * which additions may optionally be enabled by mapping to a\n * common value. This class cannot be directly instantiated.\n * See {@link #keySet() keySet()},\n * {@link #keySet(Object) keySet(V)},\n * {@link #newKeySet() newKeySet()},\n * {@link #newKeySet(int) newKeySet(int)}.\n *\n * @since 1.8\n */\n public static class KeySetView extends CollectionView implements Set, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n // Conditionally serializable\n @SuppressWarnings(\"serial\")\n private final V value;\n\n KeySetView(ConcurrentHashMap map, V value) {\n super(map);\n this.value = value;\n }\n\n /**\n * Returns the default mapped value for additions,\n * or {@code null} if additions are not supported.\n *\n * @return the default mapped value for additions, or {@code null}\n * if not supported\n */\n public V getMappedValue() {\n return value;\n }\n\n /**\n * {@inheritDoc}\n * @throws NullPointerException if the specified key is null\n */\n public boolean contains(Object o) {\n return map.containsKey(o);\n }\n\n /**\n * Removes the key from this map view, by removing the key (and its\n * corresponding value) from the backing map. This method does\n * nothing if the key is not in the map.\n *\n * @param o the key to be removed from the backing map\n * @return {@code true} if the backing map contained the specified key\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object o) {\n return map.remove(o) != null;\n }\n\n /**\n * @return an iterator over the keys of the backing map\n */\n public Iterator iterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, m);\n }\n\n /**\n * Adds the specified key to this set view by mapping the key to\n * the default mapped value in the backing map, if defined.\n *\n * @param e key to be added\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the specified key is null\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean add(K e) {\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n return map.putVal(e, v, true) == null;\n }\n\n /**\n * Adds all of the elements in the specified collection to this set,\n * as if by calling {@link #add} on each one.\n *\n * @param c the elements to be inserted into this set\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the collection or any of its\n * elements are {@code null}\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean addAll(Collection c) {\n boolean added = false;\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n for (K e : c) {\n if (map.putVal(e, v, true) == null)\n added = true;\n }\n return added;\n }\n\n public int hashCode() {\n int h = 0;\n for (K e : this) h += e.hashCode();\n return h;\n }\n\n public boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeySpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.key);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Collection} of\n * values, in which additions are disabled. This class cannot be\n * directly instantiated. See {@link #values()}.\n */\n static final class ValuesView extends CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n ValuesView(ConcurrentHashMap map) {\n super(map);\n }\n\n public final boolean contains(Object o) {\n return map.containsValue(o);\n }\n\n public final boolean remove(Object o) {\n if (o != null) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (o.equals(it.next())) {\n it.remove();\n return true;\n }\n }\n }\n return false;\n }\n\n public final Iterator iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, m);\n }\n\n public final boolean add(V e) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean addAll(Collection c) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n\n public boolean removeIf(Predicate filter) {\n return map.removeValueIf(filter);\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueSpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.val);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of (key, value)\n * entries. This class cannot be directly instantiated. See\n * {@link #entrySet()}.\n */\n static final class EntrySetView extends CollectionView> implements Set>, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n EntrySetView(ConcurrentHashMap map) {\n super(map);\n }\n\n public boolean contains(Object o) {\n Object k, v, r;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (r = map.get(k)) != null && (v = e.getValue()) != null && (v == r || v.equals(r)));\n }\n\n public boolean remove(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && map.remove(k, v));\n }\n\n /**\n * @return an iterator over the entries of the backing map\n */\n public Iterator> iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntryIterator(t, f, 0, f, m);\n }\n\n public boolean add(Entry e) {\n return map.putVal(e.getKey(), e.getValue(), false) == null;\n }\n\n public boolean addAll(Collection> c) {\n boolean added = false;\n for (Entry e : c) {\n if (add(e))\n added = true;\n }\n return added;\n }\n\n public boolean removeIf(Predicate> filter) {\n return map.removeEntryIf(filter);\n }\n\n public final int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n h += p.hashCode();\n }\n }\n return h;\n }\n\n public final boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator> spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntrySpliterator(t, f, 0, f, n < 0L ? 0L : n, m);\n }\n\n public void forEach(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n }\n }\n\n /**\n * Base class for bulk tasks. Repeats some fields and code from\n * class Traverser, because we need to subclass CountedCompleter.\n */\n @SuppressWarnings(\"serial\")\n abstract static class BulkTask extends CountedCompleter {\n\n // same as Traverser\n Node[] tab;\n\n Node next;\n\n TableStack stack, spare;\n\n int index;\n\n int baseIndex;\n\n int baseLimit;\n\n final int baseSize;\n\n // split control\n int batch;\n\n BulkTask(BulkTask par, int b, int i, int f, Node[] t) {\n super(par);\n this.batch = b;\n this.index = this.baseIndex = i;\n if ((this.tab = t) == null)\n this.baseSize = this.baseLimit = 0;\n else if (par == null)\n this.baseSize = this.baseLimit = t.length;\n else {\n this.baseLimit = f;\n this.baseSize = par.baseSize;\n }\n }\n\n /**\n * Same as Traverser version.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n Node[] t;\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n private void pushState(Node[] t, int i, int n) {\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /*\n * Task classes. Coded in a regular but ugly format/style to\n * simplify checks that each variant differs in the right way from\n * others. The null screenings exist because compilers cannot tell\n * that we've already null-checked task arguments, so we force\n * simplest hoisted bypass to help avoid convoluted traps.\n */\n @SuppressWarnings(\"serial\")\n static final class ForEachKeyTask extends BulkTask {\n\n final Consumer action;\n\n ForEachKeyTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachValueTask extends BulkTask {\n\n final Consumer action;\n\n ForEachValueTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachValueTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachEntryTask extends BulkTask {\n\n final Consumer> action;\n\n ForEachEntryTask(BulkTask p, int b, int i, int f, Node[] t, Consumer> action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer> action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachMappingTask extends BulkTask {\n\n final BiConsumer action;\n\n ForEachMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiConsumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final BiConsumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key, p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedKeyTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedKeyTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedValueTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedValueTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedValueTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedEntryTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final Consumer action;\n\n ForEachTransformedEntryTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedMappingTask extends BulkTask {\n\n final BiFunction transformer;\n\n final Consumer action;\n\n ForEachTransformedMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchKeysTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchKeysTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchValuesTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchValuesTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchEntriesTask extends BulkTask {\n\n final Function, ? extends U> searchFunction;\n\n final AtomicReference result;\n\n SearchEntriesTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function, ? extends U> searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n return;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchMappingsTask extends BulkTask {\n\n final BiFunction searchFunction;\n\n final AtomicReference result;\n\n SearchMappingsTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final BiFunction searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key, p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceKeysTask extends BulkTask {\n\n final BiFunction reducer;\n\n K result;\n\n ReduceKeysTask rights, nextRight;\n\n ReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, ReduceKeysTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final K getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n K r = null;\n for (Node p; (p = advance()) != null; ) {\n K u = p.key;\n r = (r == null) ? u : u == null ? r : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceKeysTask t = (ReduceKeysTask) c, s = t.rights;\n while (s != null) {\n K tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceValuesTask extends BulkTask {\n\n final BiFunction reducer;\n\n V result;\n\n ReduceValuesTask rights, nextRight;\n\n ReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceValuesTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final V getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n V r = null;\n for (Node p; (p = advance()) != null; ) {\n V v = p.val;\n r = (r == null) ? v : reducer.apply(r, v);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceValuesTask t = (ReduceValuesTask) c, s = t.rights;\n while (s != null) {\n V tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceEntriesTask extends BulkTask> {\n\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n\n Map.Entry result;\n\n ReduceEntriesTask rights, nextRight;\n\n ReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceEntriesTask nextRight, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final Map.Entry getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n Map.Entry r = null;\n for (Node p; (p = advance()) != null; ) r = (r == null) ? p : reducer.apply(r, p);\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceEntriesTask t = (ReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n Map.Entry tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceKeysTask rights, nextRight;\n\n MapReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysTask t = (MapReduceKeysTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceValuesTask rights, nextRight;\n\n MapReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesTask t = (MapReduceValuesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceEntriesTask rights, nextRight;\n\n MapReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesTask nextRight, Function, ? extends U> transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesTask t = (MapReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsTask extends BulkTask {\n\n final BiFunction transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceMappingsTask rights, nextRight;\n\n MapReduceMappingsTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsTask nextRight, BiFunction transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsTask t = (MapReduceMappingsTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceKeysToDoubleTask rights, nextRight;\n\n MapReduceKeysToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToDoubleTask t = (MapReduceKeysToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceValuesToDoubleTask rights, nextRight;\n\n MapReduceValuesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToDoubleTask t = (MapReduceValuesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction> transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceEntriesToDoubleTask rights, nextRight;\n\n MapReduceEntriesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToDoubleTask nextRight, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction> transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToDoubleTask t = (MapReduceEntriesToDoubleTask) c, s = t.rights;\n ", "post_mask_code": "\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToDoubleTask extends BulkTask {\n\n final ToDoubleBiFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceMappingsToDoubleTask rights, nextRight;\n\n MapReduceMappingsToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToDoubleTask nextRight, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleBiFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToDoubleTask t = (MapReduceMappingsToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceKeysToLongTask rights, nextRight;\n\n MapReduceKeysToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToLongTask t = (MapReduceKeysToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceValuesToLongTask rights, nextRight;\n\n MapReduceValuesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToLongTask t = (MapReduceValuesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToLongTask extends BulkTask {\n\n final ToLongFunction> transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceEntriesToLongTask rights, nextRight;\n\n MapReduceEntriesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToLongTask nextRight, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction> transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToLongTask t = (MapReduceEntriesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToLongTask extends BulkTask {\n\n final ToLongBiFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceMappingsToLongTask rights, nextRight;\n\n MapReduceMappingsToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToLongTask nextRight, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongBiFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToLongTask t = (MapReduceMappingsToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceKeysToIntTask rights, nextRight;\n\n MapReduceKeysToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToIntTask t = (MapReduceKeysToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceValuesToIntTask rights, nextRight;\n\n MapReduceValuesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToIntTask t = (MapReduceValuesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToIntTask extends BulkTask {\n\n final ToIntFunction> transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceEntriesToIntTask rights, nextRight;\n\n MapReduceEntriesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToIntTask nextRight, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction> transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToIntTask t = (MapReduceEntriesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToIntTask extends BulkTask {\n\n final ToIntBiFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceMappingsToIntTask rights, nextRight;\n\n MapReduceMappingsToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToIntTask nextRight, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntBiFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToIntTask t = (MapReduceMappingsToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n // Unsafe mechanics\n private static final Unsafe U = Unsafe.getUnsafe();\n\n private static final long SIZECTL = U.objectFieldOffset(ConcurrentHashMap.class, \"sizeCtl\");\n\n private static final long TRANSFERINDEX = U.objectFieldOffset(ConcurrentHashMap.class, \"transferIndex\");\n\n private static final long BASECOUNT = U.objectFieldOffset(ConcurrentHashMap.class, \"baseCount\");\n\n private static final long CELLSBUSY = U.objectFieldOffset(ConcurrentHashMap.class, \"cellsBusy\");\n\n private static final long CELLVALUE = U.objectFieldOffset(CounterCell.class, \"value\");\n\n private static final int ABASE = U.arrayBaseOffset(Node[].class);\n\n private static final int ASHIFT;\n\n static {\n int scale = U.arrayIndexScale(Node[].class);\n if ((scale & (scale - 1)) != 0)\n throw new ExceptionInInitializerError(\"array index scale not a power of two\");\n ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);\n // Reduce the risk of rare disastrous classloading in first call to\n Class ensureLoaded = LockSupport.class;\n // Eager class load observed to help JIT during startup\n ensureLoaded = ReservationNode.class;\n }\n}\n"} {"task_id": "Java_2828", "language": "Java", "task_type": "try_statement", "source_file": "java/github/openjdk/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java", "mask_start_position": 118581, "mask_end_position": 118950, "canonical_solution": "try {\n p = ((r = root) == null ? null : r.findTreeNode(h, k, null));\n } finally {\n Thread w;\n if (U.getAndAddInt(this, LOCKSTATE, -READER) == (READER | WAITER) && (w = waiter) != null)\n LockSupport.unpark(w);\n }", "pre_mask_code": "package java.util.concurrent;\n\nimport java.io.ObjectStreamField;\nimport java.io.Serializable;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.AbstractMap;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Hashtable;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.Spliterator;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.concurrent.locks.LockSupport;\nimport java.util.concurrent.locks.ReentrantLock;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\nimport java.util.function.Consumer;\nimport java.util.function.DoubleBinaryOperator;\nimport java.util.function.Function;\nimport java.util.function.IntBinaryOperator;\nimport java.util.function.LongBinaryOperator;\nimport java.util.function.Predicate;\nimport java.util.function.ToDoubleBiFunction;\nimport java.util.function.ToDoubleFunction;\nimport java.util.function.ToIntBiFunction;\nimport java.util.function.ToIntFunction;\nimport java.util.function.ToLongBiFunction;\nimport java.util.function.ToLongFunction;\nimport java.util.stream.Stream;\nimport jdk.internal.misc.Unsafe;\n\n/**\n * A hash table supporting full concurrency of retrievals and\n * high expected concurrency for updates. This class obeys the\n * same functional specification as {@link java.util.Hashtable}, and\n * includes versions of methods corresponding to each method of\n * {@code Hashtable}. However, even though all operations are\n * thread-safe, retrieval operations do not entail locking,\n * and there is not any support for locking the entire table\n * in a way that prevents all access. This class is fully\n * interoperable with {@code Hashtable} in programs that rely on its\n * thread safety but not on its synchronization details.\n *\n *

Retrieval operations (including {@code get}) generally do not\n * block, so may overlap with update operations (including {@code put}\n * and {@code remove}). Retrievals reflect the results of the most\n * recently completed update operations holding upon their\n * onset. (More formally, an update operation for a given key bears a\n * happens-before relation with any (non-null) retrieval for\n * that key reporting the updated value.) For aggregate operations\n * such as {@code putAll} and {@code clear}, concurrent retrievals may\n * reflect insertion or removal of only some entries. Similarly,\n * Iterators, Spliterators and Enumerations return elements reflecting the\n * state of the hash table at some point at or since the creation of the\n * iterator/enumeration. They do not throw {@link\n * java.util.ConcurrentModificationException ConcurrentModificationException}.\n * However, iterators are designed to be used by only one thread at a time.\n * Bear in mind that the results of aggregate status methods including\n * {@code size}, {@code isEmpty}, and {@code containsValue} are typically\n * useful only when a map is not undergoing concurrent updates in other threads.\n * Otherwise the results of these methods reflect transient states\n * that may be adequate for monitoring or estimation purposes, but not\n * for program control.\n *\n *

The table is dynamically expanded when there are too many\n * collisions (i.e., keys that have distinct hash codes but fall into\n * the same slot modulo the table size), with the expected average\n * effect of maintaining roughly two bins per mapping (corresponding\n * to a 0.75 load factor threshold for resizing). There may be much\n * variance around this average as mappings are added and removed, but\n * overall, this maintains a commonly accepted time/space tradeoff for\n * hash tables. However, resizing this or any other kind of hash\n * table may be a relatively slow operation. When possible, it is a\n * good idea to provide a size estimate as an optional {@code\n * initialCapacity} constructor argument. An additional optional\n * {@code loadFactor} constructor argument provides a further means of\n * customizing initial table capacity by specifying the table density\n * to be used in calculating the amount of space to allocate for the\n * given number of elements. Also, for compatibility with previous\n * versions of this class, constructors may optionally specify an\n * expected {@code concurrencyLevel} as an additional hint for\n * internal sizing. Note that using many keys with exactly the same\n * {@code hashCode()} is a sure way to slow down performance of any\n * hash table. To ameliorate impact, when keys are {@link Comparable},\n * this class may use comparison order among keys to help break ties.\n *\n *

A {@link Set} projection of a ConcurrentHashMap may be created\n * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed\n * (using {@link #keySet(Object)} when only keys are of interest, and the\n * mapped values are (perhaps transiently) not used or all take the\n * same mapping value.\n *\n *

A ConcurrentHashMap can be used as a scalable frequency map (a\n * form of histogram or multiset) by using {@link\n * java.util.concurrent.atomic.LongAdder} values and initializing via\n * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count\n * to a {@code ConcurrentHashMap freqs}, you can use\n * {@code freqs.computeIfAbsent(key, k -> new LongAdder()).increment();}\n *\n *

This class and its views and iterators implement all of the\n * optional methods of the {@link Map} and {@link Iterator}\n * interfaces.\n *\n *

Like {@link Hashtable} but unlike {@link HashMap}, this class\n * does not allow {@code null} to be used as a key or value.\n *\n *

ConcurrentHashMaps support a set of sequential and parallel bulk\n * operations that, unlike most {@link Stream} methods, are designed\n * to be safely, and often sensibly, applied even with maps that are\n * being concurrently updated by other threads; for example, when\n * computing a snapshot summary of the values in a shared registry.\n * There are three kinds of operation, each with four forms, accepting\n * functions with keys, values, entries, and (key, value) pairs as\n * arguments and/or return values. Because the elements of a\n * ConcurrentHashMap are not ordered in any particular way, and may be\n * processed in different orders in different parallel executions, the\n * correctness of supplied functions should not depend on any\n * ordering, or on any other objects or values that may transiently\n * change while computation is in progress; and except for forEach\n * actions, should ideally be side-effect-free. Bulk operations on\n * {@link Map.Entry} objects do not support method {@code setValue}.\n *\n *

    \n *
  • forEach: Performs a given action on each element.\n * A variant form applies a given transformation on each element\n * before performing the action.\n *\n *
  • search: Returns the first available non-null result of\n * applying a given function on each element; skipping further\n * search when a result is found.\n *\n *
  • reduce: Accumulates each element. The supplied reduction\n * function cannot rely on ordering (more formally, it should be\n * both associative and commutative). There are five variants:\n *\n *
      \n *\n *
    • Plain reductions. (There is not a form of this method for\n * (key, value) function arguments since there is no corresponding\n * return type.)\n *\n *
    • Mapped reductions that accumulate the results of a given\n * function applied to each element.\n *\n *
    • Reductions to scalar doubles, longs, and ints, using a\n * given basis value.\n *\n *
    \n *
\n *\n *

These bulk operations accept a {@code parallelismThreshold}\n * argument. Methods proceed sequentially if the current map size is\n * estimated to be less than the given threshold. Using a value of\n * {@code Long.MAX_VALUE} suppresses all parallelism. Using a value\n * of {@code 1} results in maximal parallelism by partitioning into\n * enough subtasks to fully utilize the {@link\n * ForkJoinPool#commonPool()} that is used for all parallel\n * computations. Normally, you would initially choose one of these\n * extreme values, and then measure performance of using in-between\n * values that trade off overhead versus throughput.\n *\n *

The concurrency properties of bulk operations follow\n * from those of ConcurrentHashMap: Any non-null result returned\n * from {@code get(key)} and related access methods bears a\n * happens-before relation with the associated insertion or\n * update. The result of any bulk operation reflects the\n * composition of these per-element relations (but is not\n * necessarily atomic with respect to the map as a whole unless it\n * is somehow known to be quiescent). Conversely, because keys\n * and values in the map are never null, null serves as a reliable\n * atomic indicator of the current lack of any result. To\n * maintain this property, null serves as an implicit basis for\n * all non-scalar reduction operations. For the double, long, and\n * int versions, the basis should be one that, when combined with\n * any other value, returns that other value (more formally, it\n * should be the identity element for the reduction). Most common\n * reductions have these properties; for example, computing a sum\n * with basis 0 or a minimum with basis MAX_VALUE.\n *\n *

Search and transformation functions provided as arguments\n * should similarly return null to indicate the lack of any result\n * (in which case it is not used). In the case of mapped\n * reductions, this also enables transformations to serve as\n * filters, returning null (or, in the case of primitive\n * specializations, the identity basis) if the element should not\n * be combined. You can create compound transformations and\n * filterings by composing them yourself under this \"null means\n * there is nothing there now\" rule before using them in search or\n * reduce operations.\n *\n *

Methods accepting and/or returning Entry arguments maintain\n * key-value associations. They may be useful for example when\n * finding the key for the greatest value. Note that \"plain\" Entry\n * arguments can be supplied using {@code new\n * AbstractMap.SimpleEntry(k,v)}.\n *\n *

Bulk operations may complete abruptly, throwing an\n * exception encountered in the application of a supplied\n * function. Bear in mind when handling such exceptions that other\n * concurrently executing functions could also have thrown\n * exceptions, or would have done so if the first exception had\n * not occurred.\n *\n *

Speedups for parallel compared to sequential forms are common\n * but not guaranteed. Parallel operations involving brief functions\n * on small maps may execute more slowly than sequential forms if the\n * underlying work to parallelize the computation is more expensive\n * than the computation itself. Similarly, parallelization may not\n * lead to much actual parallelism if all processors are busy\n * performing unrelated tasks.\n *\n *

All arguments to all task methods must be non-null.\n *\n *

This class is a member of the\n * \n * Java Collections Framework.\n *\n * @since 1.5\n * @author Doug Lea\n * @param the type of keys maintained by this map\n * @param the type of mapped values\n */\npublic class ConcurrentHashMap extends AbstractMap implements ConcurrentMap, Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n /*\n * Overview:\n *\n * The primary design goal of this hash table is to maintain\n * concurrent readability (typically method get(), but also\n * iterators and related methods) while minimizing update\n * contention. Secondary goals are to keep space consumption about\n * the same or better than java.util.HashMap, and to support high\n * initial insertion rates on an empty table by many threads.\n *\n * This map usually acts as a binned (bucketed) hash table. Each\n * key-value mapping is held in a Node. Most nodes are instances\n * of the basic Node class with hash, key, value, and next\n * fields. However, various subclasses exist: TreeNodes are\n * arranged in balanced trees, not lists. TreeBins hold the roots\n * of sets of TreeNodes. ForwardingNodes are placed at the heads\n * of bins during resizing. ReservationNodes are used as\n * placeholders while establishing values in computeIfAbsent and\n * related methods. The types TreeBin, ForwardingNode, and\n * ReservationNode do not hold normal user keys, values, or\n * hashes, and are readily distinguishable during search etc\n * because they have negative hash fields and null key and value\n * fields. (These special nodes are either uncommon or transient,\n * so the impact of carrying around some unused fields is\n * insignificant.)\n *\n * The table is lazily initialized to a power-of-two size upon the\n * first insertion. Each bin in the table normally contains a\n * list of Nodes (most often, the list has only zero or one Node).\n * Table accesses require volatile/atomic reads, writes, and\n * CASes. Because there is no other way to arrange this without\n * adding further indirections, we use intrinsics\n * (jdk.internal.misc.Unsafe) operations.\n *\n * We use the top (sign) bit of Node hash fields for control\n * purposes -- it is available anyway because of addressing\n * constraints. Nodes with negative hash fields are specially\n * handled or ignored in map methods.\n *\n * Insertion (via put or its variants) of the first node in an\n * empty bin is performed by just CASing it to the bin. This is\n * by far the most common case for put operations under most\n * key/hash distributions. Other update operations (insert,\n * delete, and replace) require locks. We do not want to waste\n * the space required to associate a distinct lock object with\n * each bin, so instead use the first node of a bin list itself as\n * a lock. Locking support for these locks relies on builtin\n * \"synchronized\" monitors.\n *\n * Using the first node of a list as a lock does not by itself\n * suffice though: When a node is locked, any update must first\n * validate that it is still the first node after locking it, and\n * retry if not. Because new nodes are always appended to lists,\n * once a node is first in a bin, it remains first until deleted\n * or the bin becomes invalidated (upon resizing).\n *\n * The main disadvantage of per-bin locks is that other update\n * operations on other nodes in a bin list protected by the same\n * lock can stall, for example when user equals() or mapping\n * functions take a long time. However, statistically, under\n * random hash codes, this is not a common problem. Ideally, the\n * frequency of nodes in bins follows a Poisson distribution\n * (http://example.com) with a\n * parameter of about 0.5 on average, given the resizing threshold\n * of 0.75, although with a large variance because of resizing\n * granularity. Ignoring variance, the expected occurrences of\n * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The\n * first values are:\n *\n * 0: 0.60653066\n * 1: 0.30326533\n * 2: 0.07581633\n * 3: 0.01263606\n * 4: 0.00157952\n * 5: 0.00015795\n * 6: 0.00001316\n * 7: 0.00000094\n * 8: 0.00000006\n * more: less than 1 in ten million\n *\n * Lock contention probability for two threads accessing distinct\n * elements is roughly 1 / (8 * #elements) under random hashes.\n *\n * Actual hash code distributions encountered in practice\n * sometimes deviate significantly from uniform randomness. This\n * includes the case when N > (1<<30), so some keys MUST collide.\n * Similarly for dumb or hostile usages in which multiple keys are\n * designed to have identical hash codes or ones that differs only\n * in masked-out high bits. So we use a secondary strategy that\n * applies when the number of nodes in a bin exceeds a\n * threshold. These TreeBins use a balanced tree to hold nodes (a\n * specialized form of red-black trees), bounding search time to\n * O(log N). Each search step in a TreeBin is at least twice as\n * slow as in a regular list, but given that N cannot exceed\n * (1<<64) (before running out of addresses) this bounds search\n * steps, lock hold times, etc, to reasonable constants (roughly\n * 100 nodes inspected per operation worst case) so long as keys\n * are Comparable (which is very common -- String, Long, etc).\n * TreeBin nodes (TreeNodes) also maintain the same \"next\"\n * traversal pointers as regular nodes, so can be traversed in\n * iterators in the same way.\n *\n * The table is resized when occupancy exceeds a percentage\n * threshold (nominally, 0.75, but see below). Any thread\n * noticing an overfull bin may assist in resizing after the\n * initiating thread allocates and sets up the replacement array.\n * However, rather than stalling, these other threads may proceed\n * with insertions etc. The use of TreeBins shields us from the\n * worst case effects of overfilling while resizes are in\n * progress. Resizing proceeds by transferring bins, one by one,\n * from the table to the next table. However, threads claim small\n * blocks of indices to transfer (via field transferIndex) before\n * doing so, reducing contention. A generation stamp in field\n * sizeCtl ensures that resizings do not overlap. Because we are\n * using power-of-two expansion, the elements from each bin must\n * either stay at same index, or move with a power of two\n * offset. We eliminate unnecessary node creation by catching\n * cases where old nodes can be reused because their next fields\n * won't change. On average, only about one-sixth of them need\n * cloning when a table doubles. The nodes they replace will be\n * garbage collectible as soon as they are no longer referenced by\n * any reader thread that may be in the midst of concurrently\n * traversing table. Upon transfer, the old table bin contains\n * only a special forwarding node (with hash field \"MOVED\") that\n * contains the next table as its key. On encountering a\n * forwarding node, access and update operations restart, using\n * the new table.\n *\n * Each bin transfer requires its bin lock, which can stall\n * waiting for locks while resizing. However, because other\n * threads can join in and help resize rather than contend for\n * locks, average aggregate waits become shorter as resizing\n * progresses. The transfer operation must also ensure that all\n * accessible bins in both the old and new table are usable by any\n * traversal. This is arranged in part by proceeding from the\n * last bin (table.length - 1) up towards the first. Upon seeing\n * a forwarding node, traversals (see class Traverser) arrange to\n * move to the new table without revisiting nodes. To ensure that\n * no intervening nodes are skipped even when moved out of order,\n * a stack (see class TableStack) is created on first encounter of\n * a forwarding node during a traversal, to maintain its place if\n * later processing the current table. The need for these\n * save/restore mechanics is relatively rare, but when one\n * forwarding node is encountered, typically many more will be.\n * So Traversers use a simple caching scheme to avoid creating so\n * many new TableStack nodes. (Thanks to Peter Levart for\n * suggesting use of a stack here.)\n *\n * The traversal scheme also applies to partial traversals of\n * ranges of bins (via an alternate Traverser constructor)\n * to support partitioned aggregate operations. Also, read-only\n * operations give up if ever forwarded to a null table, which\n * provides support for shutdown-style clearing, which is also not\n * currently implemented.\n *\n * Lazy table initialization minimizes footprint until first use,\n * and also avoids resizings when the first operation is from a\n * putAll, constructor with map argument, or deserialization.\n * These cases attempt to override the initial capacity settings,\n * but harmlessly fail to take effect in cases of races.\n *\n * The element count is maintained using a specialization of\n * LongAdder. We need to incorporate a specialization rather than\n * just use a LongAdder in order to access implicit\n * contention-sensing that leads to creation of multiple\n * CounterCells. The counter mechanics avoid contention on\n * updates but can encounter cache thrashing if read too\n * frequently during concurrent access. To avoid reading so often,\n * resizing under contention is attempted only upon adding to a\n * bin already holding two or more nodes. Under uniform hash\n * distributions, the probability of this occurring at threshold\n * is around 13%, meaning that only about 1 in 8 puts check\n * threshold (and after resizing, many fewer do so).\n *\n * TreeBins use a special form of comparison for search and\n * related operations (which is the main reason we cannot use\n * existing collections such as TreeMaps). TreeBins contain\n * Comparable elements, but may contain others, as well as\n * elements that are Comparable but not necessarily Comparable for\n * the same T, so we cannot invoke compareTo among them. To handle\n * this, the tree is ordered primarily by hash value, then by\n * Comparable.compareTo order if applicable. On lookup at a node,\n * if elements are not comparable or compare as 0 then both left\n * and right children may need to be searched in the case of tied\n * hash values. (This corresponds to the full list search that\n * would be necessary if all elements were non-Comparable and had\n * tied hashes.) On insertion, to keep a total ordering (or as\n * close as is required here) across rebalancings, we compare\n * classes and identityHashCodes as tie-breakers. The red-black\n * balancing code is updated from pre-jdk-collections\n * (http://example.com)\n * based in turn on Cormen, Leiserson, and Rivest \"Introduction to\n * Algorithms\" (CLR).\n *\n * TreeBins also require an additional locking mechanism. While\n * list traversal is always possible by readers even during\n * updates, tree traversal is not, mainly because of tree-rotations\n * that may change the root node and/or its linkages. TreeBins\n * include a simple read-write lock mechanism parasitic on the\n * main bin-synchronization strategy: Structural adjustments\n * associated with an insertion or removal are already bin-locked\n * (and so cannot conflict with other writers) but must wait for\n * ongoing readers to finish. Since there can be only one such\n * waiter, we use a simple scheme using a single \"waiter\" field to\n * block writers. However, readers need never block. If the root\n * lock is held, they proceed along the slow traversal path (via\n * next-pointers) until the lock becomes available or the list is\n * exhausted, whichever comes first. These cases are not fast, but\n * maximize aggregate expected throughput.\n *\n * Maintaining API and serialization compatibility with previous\n * versions of this class introduces several oddities. Mainly: We\n * leave untouched but unused constructor arguments referring to\n * concurrencyLevel. We accept a loadFactor constructor argument,\n * but apply it only to initial table capacity (which is the only\n * time that we can guarantee to honor it.) We also declare an\n * unused \"Segment\" class that is instantiated in minimal form\n * only when serializing.\n *\n * Also, solely for compatibility with previous versions of this\n * class, it extends AbstractMap, even though all of its methods\n * are overridden, so it is just useless baggage.\n *\n * This file is organized to make things a little easier to follow\n * while reading than they might otherwise: First the main static\n * declarations and utilities, then fields, then main public\n * methods (with a few factorings of multiple public methods into\n * internal ones), then sizing methods, trees, traversers, and\n * bulk operations.\n */\n /**\n * The largest possible table capacity. This value must be\n * exactly 1<<30 to stay within Java array allocation and indexing\n * bounds for power of two table sizes, and is further required\n * because the top two bits of 32bit hash fields are used for\n * control purposes.\n */\n private static final int MAXIMUM_CAPACITY = 1 << 30;\n\n /**\n * The default initial table capacity. Must be a power of 2\n * (i.e., at least 1) and at most MAXIMUM_CAPACITY.\n */\n private static final int DEFAULT_CAPACITY = 16;\n\n /**\n * The largest possible (non-power of two) array size.\n * Needed by toArray and related methods.\n */\n static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;\n\n /**\n * The default concurrency level for this table. Unused but\n * defined for compatibility with previous versions of this class.\n */\n private static final int DEFAULT_CONCURRENCY_LEVEL = 16;\n\n /**\n * The load factor for this table. Overrides of this value in\n * constructors affect only the initial table capacity. The\n * actual floating point value isn't normally used -- it is\n * simpler to use expressions such as {@code n - (n >>> 2)} for\n * the associated resizing threshold.\n */\n private static final float LOAD_FACTOR = 0.75f;\n\n /**\n * The bin count threshold for using a tree rather than list for a\n * bin. Bins are converted to trees when adding an element to a\n * bin with at least this many nodes. The value must be greater\n * than 2, and should be at least 8 to mesh with assumptions in\n * tree removal about conversion back to plain bins upon\n * shrinkage.\n */\n static final int TREEIFY_THRESHOLD = 8;\n\n /**\n * The bin count threshold for untreeifying a (split) bin during a\n * resize operation. Should be less than TREEIFY_THRESHOLD, and at\n * most 6 to mesh with shrinkage detection under removal.\n */\n static final int UNTREEIFY_THRESHOLD = 6;\n\n /**\n * The smallest table capacity for which bins may be treeified.\n * (Otherwise the table is resized if too many nodes in a bin.)\n * The value should be at least 4 * TREEIFY_THRESHOLD to avoid\n * conflicts between resizing and treeification thresholds.\n */\n static final int MIN_TREEIFY_CAPACITY = 64;\n\n /**\n * Minimum number of rebinnings per transfer step. Ranges are\n * subdivided to allow multiple resizer threads. This value\n * serves as a lower bound to avoid resizers encountering\n * excessive memory contention. The value should be at least\n * DEFAULT_CAPACITY.\n */\n private static final int MIN_TRANSFER_STRIDE = 16;\n\n /**\n * The number of bits used for generation stamp in sizeCtl.\n * Must be at least 6 for 32bit arrays.\n */\n private static final int RESIZE_STAMP_BITS = 16;\n\n /**\n * The maximum number of threads that can help resize.\n * Must fit in 32 - RESIZE_STAMP_BITS bits.\n */\n private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;\n\n /**\n * The bit shift for recording size stamp in sizeCtl.\n */\n private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;\n\n /*\n * Encodings for Node hash fields. See above for explanation.\n */\n // hash for forwarding nodes\n static final int MOVED = -1;\n\n // hash for roots of trees\n static final int TREEBIN = -2;\n\n static final int RESERVED = -3;\n\n // usable bits of normal node hash\n static final int HASH_BITS = 0x7fffffff;\n\n /**\n * Number of CPUS, to place bounds on some sizings\n */\n static final int NCPU = Runtime.getRuntime().availableProcessors();\n\n /**\n * Serialized pseudo-fields, provided only for jdk7 compatibility.\n * @serialField segments Segment[]\n * The segments, each of which is a specialized hash table.\n * @serialField segmentMask int\n * Mask value for indexing into segments. The upper bits of a\n * key's hash code are used to choose the segment.\n * @serialField segmentShift int\n * Shift value for indexing within segments.\n */\n private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(\"segments\", Segment[].class), new ObjectStreamField(\"segmentMask\", Integer.TYPE), new ObjectStreamField(\"segmentShift\", Integer.TYPE) };\n\n /**\n * Key-value entry. This class is never exported out as a\n * user-mutable Map.Entry (i.e., one supporting setValue; see\n * MapEntry below), but can be used for read-only traversals used\n * in bulk tasks. Subclasses of Node with a negative hash field\n * are special, and contain null keys and values (but are never\n * exported). Otherwise, keys and vals are never null.\n */\n static class Node implements Map.Entry {\n\n final int hash;\n\n final K key;\n\n volatile V val;\n\n volatile Node next;\n\n Node(int hash, K key, V val) {\n this.hash = hash;\n this.key = key;\n this.val = val;\n }\n\n Node(int hash, K key, V val, Node next) {\n this(hash, key, val);\n this.next = next;\n }\n\n public final K getKey() {\n return key;\n }\n\n public final V getValue() {\n return val;\n }\n\n public final int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public final String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public final V setValue(V value) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean equals(Object o) {\n Object k, v, u;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == (u = val) || v.equals(u)));\n }\n\n /**\n * Virtualized support for map.get(); overridden in subclasses.\n */\n Node find(int h, Object k) {\n Node e = this;\n if (k != null) {\n do {\n K ek;\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n } while ((e = e.next) != null);\n }\n return null;\n }\n }\n\n /**\n * Spreads (XORs) higher bits of hash to lower and also forces top\n * bit to 0. Because the table uses power-of-two masking, sets of\n * hashes that vary only in bits above the current mask will\n * always collide. (Among known examples are sets of Float keys\n * holding consecutive whole numbers in small tables.) So we\n * apply a transform that spreads the impact of higher bits\n * downward. There is a tradeoff between speed, utility, and\n * quality of bit-spreading. Because many common sets of hashes\n * are already reasonably distributed (so don't benefit from\n * spreading), and because we use trees to handle large sets of\n * collisions in bins, we just XOR some shifted bits in the\n * cheapest possible way to reduce systematic lossage, as well as\n * to incorporate impact of the highest bits that would otherwise\n * never be used in index calculations because of table bounds.\n */\n static final int spread(int h) {\n return (h ^ (h >>> 16)) & HASH_BITS;\n }\n\n /**\n * Returns a power of two table size for the given desired capacity.\n * See Hackers Delight, sec 3.2\n */\n private static final int tableSizeFor(int c) {\n int n = -1 >>> Integer.numberOfLeadingZeros(c - 1);\n return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;\n }\n\n /**\n * Returns x's Class if it is of the form \"class C implements\n * Comparable\", else null.\n */\n static Class comparableClassFor(Object x) {\n if (x instanceof Comparable) {\n Class c;\n Type[] ts, as;\n ParameterizedType p;\n if (// bypass checks\n (c = x.getClass()) == String.class)\n return c;\n if ((ts = c.getGenericInterfaces()) != null) {\n for (Type t : ts) {\n if ((t instanceof ParameterizedType) && ((p = (ParameterizedType) t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && // type arg is c\n as[0] == c)\n return c;\n }\n }\n }\n return null;\n }\n\n /**\n * Returns k.compareTo(x) if x matches kc (k's screened comparable\n * class), else 0.\n */\n // for cast to Comparable\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n static int compareComparables(Class kc, Object k, Object x) {\n return (x == null || x.getClass() != kc ? 0 : ((Comparable) k).compareTo(x));\n }\n\n /* ---------------- Table element access -------------- */\n /*\n * Atomic access methods are used for table elements as well as\n * elements of in-progress next table while resizing. All uses of\n * the tab arguments must be null checked by callers. All callers\n * also paranoically precheck that tab's length is not zero (or an\n * equivalent check), thus ensuring that any index argument taking\n * the form of a hash value anded with (length - 1) is a valid\n * index. Note that, to be correct wrt arbitrary concurrency\n * errors by users, these checks must operate on local variables,\n * which accounts for some odd-looking inline assignments below.\n * Note that calls to setTabAt always occur within locked regions,\n * and so require only release ordering.\n */\n @SuppressWarnings(\"unchecked\")\n static final Node tabAt(Node[] tab, int i) {\n return (Node) U.getReferenceAcquire(tab, ((long) i << ASHIFT) + ABASE);\n }\n\n static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {\n return U.compareAndSetReference(tab, ((long) i << ASHIFT) + ABASE, c, v);\n }\n\n static final void setTabAt(Node[] tab, int i, Node v) {\n U.putReferenceRelease(tab, ((long) i << ASHIFT) + ABASE, v);\n }\n\n /**\n * The array of bins. Lazily initialized upon first insertion.\n * Size is always a power of two. Accessed directly by iterators.\n */\n transient volatile Node[] table;\n\n /**\n * The next table to use; non-null only while resizing.\n */\n private transient volatile Node[] nextTable;\n\n /**\n * Base counter value, used mainly when there is no contention,\n * but also as a fallback during table initialization\n * races. Updated via CAS.\n */\n private transient volatile long baseCount;\n\n /**\n * Table initialization and resizing control. When negative, the\n * table is being initialized or resized: -1 for initialization,\n * else -(1 + the number of active resizing threads). Otherwise,\n * when table is null, holds the initial table size to use upon\n * creation, or 0 for default. After initialization, holds the\n * next element count value upon which to resize the table.\n */\n private transient volatile int sizeCtl;\n\n /**\n * The next table index (plus one) to split while resizing.\n */\n private transient volatile int transferIndex;\n\n /**\n * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.\n */\n private transient volatile int cellsBusy;\n\n /**\n * Table of counter cells. When non-null, size is a power of 2.\n */\n private transient volatile CounterCell[] counterCells;\n\n // views\n private transient KeySetView keySet;\n\n private transient ValuesView values;\n\n private transient EntrySetView entrySet;\n\n /**\n * Creates a new, empty map with the default initial table size (16).\n */\n public ConcurrentHashMap() {\n }\n\n /**\n * Creates a new, empty map with an initial table size\n * accommodating the specified number of elements without the need\n * to dynamically resize.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n */\n public ConcurrentHashMap(int initialCapacity) {\n this(initialCapacity, LOAD_FACTOR, 1);\n }\n\n /**\n * Creates a new map with the same mappings as the given map.\n *\n * @param m the map\n */\n public ConcurrentHashMap(Map m) {\n this.sizeCtl = DEFAULT_CAPACITY;\n putAll(m);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}) and\n * initial table density ({@code loadFactor}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative or the load factor is nonpositive\n *\n * @since 1.6\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor) {\n this(initialCapacity, loadFactor, 1);\n }\n\n /**\n * Creates a new, empty map with an initial table size based on\n * the given number of elements ({@code initialCapacity}), initial\n * table density ({@code loadFactor}), and number of concurrently\n * updating threads ({@code concurrencyLevel}).\n *\n * @param initialCapacity the initial capacity. The implementation\n * performs internal sizing to accommodate this many elements,\n * given the specified load factor.\n * @param loadFactor the load factor (table density) for\n * establishing the initial table size\n * @param concurrencyLevel the estimated number of concurrently\n * updating threads. The implementation may use this value as\n * a sizing hint.\n * @throws IllegalArgumentException if the initial capacity is\n * negative or the load factor or concurrencyLevel are\n * nonpositive\n */\n public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) {\n if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)\n throw new IllegalArgumentException();\n if (// Use at least as many bins\n initialCapacity < concurrencyLevel)\n // as estimated threads\n initialCapacity = concurrencyLevel;\n long size = (long) (1.0 + (long) initialCapacity / loadFactor);\n int cap = (size >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) size);\n this.sizeCtl = cap;\n }\n\n // Original (since JDK1.2) Map methods\n public int size() {\n long n = sumCount();\n return ((n < 0L) ? 0 : (n > (long) Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) n);\n }\n\n public boolean isEmpty() {\n // ignore transient negative values\n return sumCount() <= 0L;\n }\n\n /**\n * Returns the value to which the specified key is mapped,\n * or {@code null} if this map contains no mapping for the key.\n *\n *

More formally, if this map contains a mapping from a key\n * {@code k} to a value {@code v} such that {@code key.equals(k)},\n * then this method returns {@code v}; otherwise it returns\n * {@code null}. (There can be at most one such mapping.)\n *\n * @throws NullPointerException if the specified key is null\n */\n public V get(Object key) {\n Node[] tab;\n Node e, p;\n int n, eh;\n K ek;\n int h = spread(key.hashCode());\n if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) {\n if ((eh = e.hash) == h) {\n if ((ek = e.key) == key || (ek != null && key.equals(ek)))\n return e.val;\n } else if (eh < 0)\n return (p = e.find(h, key)) != null ? p.val : null;\n while ((e = e.next) != null) {\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek))))\n return e.val;\n }\n }\n return null;\n }\n\n /**\n * Tests if the specified object is a key in this table.\n *\n * @param key possible key\n * @return {@code true} if and only if the specified object\n * is a key in this table, as determined by the\n * {@code equals} method; {@code false} otherwise\n * @throws NullPointerException if the specified key is null\n */\n public boolean containsKey(Object key) {\n return get(key) != null;\n }\n\n /**\n * Returns {@code true} if this map maps one or more keys to the\n * specified value. Note: This method may require a full traversal\n * of the map, and is much slower than method {@code containsKey}.\n *\n * @param value value whose presence in this map is to be tested\n * @return {@code true} if this map maps one or more keys to the\n * specified value\n * @throws NullPointerException if the specified value is null\n */\n public boolean containsValue(Object value) {\n if (value == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V v;\n if ((v = p.val) == value || (v != null && value.equals(v)))\n return true;\n }\n }\n return false;\n }\n\n /**\n * Maps the specified key to the specified value in this table.\n * Neither the key nor the value can be null.\n *\n *

The value can be retrieved by calling the {@code get} method\n * with a key that is equal to the original key.\n *\n * @param key key with which the specified value is to be associated\n * @param value value to be associated with the specified key\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key or value is null\n */\n public V put(K key, V value) {\n return putVal(key, value, false);\n }\n\n /**\n * Implementation for put and putIfAbsent\n */\n final V putVal(K key, V value, boolean onlyIfAbsent) {\n if (key == null || value == null)\n throw new NullPointerException();\n int hash = spread(key.hashCode());\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {\n if (casTabAt(tab, i, null, new Node(hash, key, value)))\n // no lock when adding to empty bin\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n onlyIfAbsent && fh == hash && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n V oldVal = null;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n oldVal = e.val;\n if (!onlyIfAbsent)\n e.val = value;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n pred.next = new Node(hash, key, value);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n Node p;\n binCount = 2;\n if ((p = ((TreeBin) f).putTreeVal(hash, key, value)) != null) {\n oldVal = p.val;\n if (!onlyIfAbsent)\n p.val = value;\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (oldVal != null)\n return oldVal;\n break;\n }\n }\n }\n addCount(1L, binCount);\n return null;\n }\n\n /**\n * Copies all of the mappings from the specified map to this one.\n * These mappings replace any mappings that this map had for any of the\n * keys currently in the specified map.\n *\n * @param m mappings to be stored in this map\n */\n public void putAll(Map m) {\n tryPresize(m.size());\n for (Map.Entry e : m.entrySet()) putVal(e.getKey(), e.getValue(), false);\n }\n\n /**\n * Removes the key (and its corresponding value) from this map.\n * This method does nothing if the key is not in the map.\n *\n * @param key the key that needs to be removed\n * @return the previous value associated with {@code key}, or\n * {@code null} if there was no mapping for {@code key}\n * @throws NullPointerException if the specified key is null\n */\n public V remove(Object key) {\n return replaceNode(key, null, null);\n }\n\n /**\n * Implementation for the four public remove/replace methods:\n * Replaces node value with v, conditional upon match of cv if\n * non-null. If resulting value is null, delete.\n */\n final V replaceNode(Object key, V value, Object cv) {\n int hash = spread(key.hashCode());\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0 || (f = tabAt(tab, i = (n - 1) & hash)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n V oldVal = null;\n boolean validated = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n validated = true;\n for (Node e = f, pred = null; ; ) {\n K ek;\n if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n V ev = e.val;\n if (cv == null || cv == ev || (ev != null && cv.equals(ev))) {\n oldVal = ev;\n if (value != null)\n e.val = value;\n else if (pred != null)\n pred.next = e.next;\n else\n setTabAt(tab, i, e.next);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n validated = true;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(hash, key, null)) != null) {\n V pv = p.val;\n if (cv == null || cv == pv || (pv != null && cv.equals(pv))) {\n oldVal = pv;\n if (value != null)\n p.val = value;\n else if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (validated) {\n if (oldVal != null) {\n if (value == null)\n addCount(-1L, -1);\n return oldVal;\n }\n break;\n }\n }\n }\n return null;\n }\n\n /**\n * Removes all of the mappings from this map.\n */\n public void clear() {\n // negative number of deletions\n long delta = 0L;\n int i = 0;\n Node[] tab = table;\n while (tab != null && i < tab.length) {\n int fh;\n Node f = tabAt(tab, i);\n if (f == null)\n ++i;\n else if ((fh = f.hash) == MOVED) {\n tab = helpTransfer(tab, f);\n // restart\n i = 0;\n } else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node p = (fh >= 0 ? f : (f instanceof TreeBin) ? ((TreeBin) f).first : null);\n while (p != null) {\n --delta;\n p = p.next;\n }\n setTabAt(tab, i++, null);\n }\n }\n }\n }\n if (delta != 0L)\n addCount(delta, -1);\n }\n\n /**\n * Returns a {@link Set} view of the keys contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from this map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations. It does not support the {@code add} or\n * {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public KeySetView keySet() {\n KeySetView ks;\n if ((ks = keySet) != null)\n return ks;\n return keySet = new KeySetView(this, null);\n }\n\n /**\n * Returns a {@link Collection} view of the values contained in this map.\n * The collection is backed by the map, so changes to the map are\n * reflected in the collection, and vice-versa. The collection\n * supports element removal, which removes the corresponding\n * mapping from this map, via the {@code Iterator.remove},\n * {@code Collection.remove}, {@code removeAll},\n * {@code retainAll}, and {@code clear} operations. It does not\n * support the {@code add} or {@code addAll} operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}\n * and {@link Spliterator#NONNULL}.\n *\n * @return the collection view\n */\n public Collection values() {\n ValuesView vs;\n if ((vs = values) != null)\n return vs;\n return values = new ValuesView(this);\n }\n\n /**\n * Returns a {@link Set} view of the mappings contained in this map.\n * The set is backed by the map, so changes to the map are\n * reflected in the set, and vice-versa. The set supports element\n * removal, which removes the corresponding mapping from the map,\n * via the {@code Iterator.remove}, {@code Set.remove},\n * {@code removeAll}, {@code retainAll}, and {@code clear}\n * operations.\n *\n *

The view's iterators and spliterators are\n * weakly consistent.\n *\n *

The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},\n * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.\n *\n * @return the set view\n */\n public Set> entrySet() {\n EntrySetView es;\n if ((es = entrySet) != null)\n return es;\n return entrySet = new EntrySetView(this);\n }\n\n /**\n * Returns the hash code value for this {@link Map}, i.e.,\n * the sum of, for each key-value pair in the map,\n * {@code key.hashCode() ^ value.hashCode()}.\n *\n * @return the hash code value for this map\n */\n public int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) h += p.key.hashCode() ^ p.val.hashCode();\n }\n return h;\n }\n\n /**\n * Returns a string representation of this map. The string\n * representation consists of a list of key-value mappings (in no\n * particular order) enclosed in braces (\"{@code {}}\"). Adjacent\n * mappings are separated by the characters {@code \", \"} (comma\n * and space). Each key-value mapping is rendered as the key\n * followed by an equals sign (\"{@code =}\") followed by the\n * associated value.\n *\n * @return a string representation of this map\n */\n public String toString() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n StringBuilder sb = new StringBuilder();\n sb.append('{');\n Node p;\n if ((p = it.advance()) != null) {\n for (; ; ) {\n K k = p.key;\n V v = p.val;\n sb.append(k == this ? \"(this Map)\" : k);\n sb.append('=');\n sb.append(v == this ? \"(this Map)\" : v);\n if ((p = it.advance()) == null)\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append('}').toString();\n }\n\n /**\n * Compares the specified object with this map for equality.\n * Returns {@code true} if the given object is a map with the same\n * mappings as this map. This operation may return misleading\n * results if either map is concurrently modified during execution\n * of this method.\n *\n * @param o object to be compared for equality with this map\n * @return {@code true} if the specified object is equal to this map\n */\n public boolean equals(Object o) {\n if (o != this) {\n if (!(o instanceof Map))\n return false;\n Map m = (Map) o;\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n Traverser it = new Traverser(t, f, 0, f);\n for (Node p; (p = it.advance()) != null; ) {\n V val = p.val;\n Object v = m.get(p.key);\n if (v == null || (v != val && !v.equals(val)))\n return false;\n }\n for (Map.Entry e : m.entrySet()) {\n Object mk, mv, v;\n if ((mk = e.getKey()) == null || (mv = e.getValue()) == null || (v = get(mk)) == null || (mv != v && !mv.equals(v)))\n return false;\n }\n }\n return true;\n }\n\n /**\n * Stripped-down version of helper class used in previous version,\n * declared for the sake of serialization compatibility.\n */\n static class Segment extends ReentrantLock implements Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n final float loadFactor;\n\n Segment(float lf) {\n this.loadFactor = lf;\n }\n }\n\n /**\n * Saves this map to a stream (that is, serializes it).\n *\n * @param s the stream\n * @throws java.io.IOException if an I/O error occurs\n * @serialData\n * the serialized fields, followed by the key (Object) and value\n * (Object) for each key-value mapping, followed by a null pair.\n * The key-value mappings are emitted in no particular order.\n */\n private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {\n // For serialization compatibility\n // Emulate segment calculation from previous version of this class\n int sshift = 0;\n int ssize = 1;\n while (ssize < DEFAULT_CONCURRENCY_LEVEL) {\n ++sshift;\n ssize <<= 1;\n }\n int segmentShift = 32 - sshift;\n int segmentMask = ssize - 1;\n @SuppressWarnings(\"unchecked\")\n Segment[] segments = (Segment[]) new Segment[DEFAULT_CONCURRENCY_LEVEL];\n for (int i = 0; i < segments.length; ++i) segments[i] = new Segment(LOAD_FACTOR);\n java.io.ObjectOutputStream.PutField streamFields = s.putFields();\n streamFields.put(\"segments\", segments);\n streamFields.put(\"segmentShift\", segmentShift);\n streamFields.put(\"segmentMask\", segmentMask);\n s.writeFields();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n s.writeObject(p.key);\n s.writeObject(p.val);\n }\n }\n s.writeObject(null);\n s.writeObject(null);\n }\n\n /**\n * Reconstitutes this map from a stream (that is, deserializes it).\n * @param s the stream\n * @throws ClassNotFoundException if the class of a serialized object\n * could not be found\n * @throws java.io.IOException if an I/O error occurs\n */\n private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {\n /*\n * To improve performance in typical cases, we create nodes\n * while reading, then place in table once size is known.\n * However, we must also validate uniqueness and deal with\n * overpopulated bins while doing so, which requires\n * specialized versions of putVal mechanics.\n */\n // force exclusion for table construction\n sizeCtl = -1;\n s.defaultReadObject();\n long size = 0L;\n Node p = null;\n for (; ; ) {\n @SuppressWarnings(\"unchecked\")\n K k = (K) s.readObject();\n @SuppressWarnings(\"unchecked\")\n V v = (V) s.readObject();\n if (k != null && v != null) {\n p = new Node(spread(k.hashCode()), k, v, p);\n ++size;\n } else\n break;\n }\n if (size == 0L)\n sizeCtl = 0;\n else {\n long ts = (long) (1.0 + size / LOAD_FACTOR);\n int n = (ts >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) ts);\n @SuppressWarnings(\"unchecked\")\n Node[] tab = (Node[]) new Node[n];\n int mask = n - 1;\n long added = 0L;\n while (p != null) {\n boolean insertAtFront;\n Node next = p.next, first;\n int h = p.hash, j = h & mask;\n if ((first = tabAt(tab, j)) == null)\n insertAtFront = true;\n else {\n K k = p.key;\n if (first.hash < 0) {\n TreeBin t = (TreeBin) first;\n if (t.putTreeVal(h, k, p.val) == null)\n ++added;\n insertAtFront = false;\n } else {\n int binCount = 0;\n insertAtFront = true;\n Node q;\n K qk;\n for (q = first; q != null; q = q.next) {\n if (q.hash == h && ((qk = q.key) == k || (qk != null && k.equals(qk)))) {\n insertAtFront = false;\n break;\n }\n ++binCount;\n }\n if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {\n insertAtFront = false;\n ++added;\n p.next = first;\n TreeNode hd = null, tl = null;\n for (q = p; q != null; q = q.next) {\n TreeNode t = new TreeNode(q.hash, q.key, q.val, null, null);\n if ((t.prev = tl) == null)\n hd = t;\n else\n tl.next = t;\n tl = t;\n }\n setTabAt(tab, j, new TreeBin(hd));\n }\n }\n }\n if (insertAtFront) {\n ++added;\n p.next = first;\n setTabAt(tab, j, p);\n }\n p = next;\n }\n table = tab;\n sizeCtl = n - (n >>> 2);\n baseCount = added;\n }\n }\n\n // ConcurrentMap methods\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V putIfAbsent(K key, V value) {\n return putVal(key, value, true);\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object key, Object value) {\n if (key == null)\n throw new NullPointerException();\n return value != null && replaceNode(key, null, value) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @throws NullPointerException if any of the arguments are null\n */\n public boolean replace(K key, V oldValue, V newValue) {\n if (key == null || oldValue == null || newValue == null)\n throw new NullPointerException();\n return replaceNode(key, newValue, oldValue) != null;\n }\n\n /**\n * {@inheritDoc}\n *\n * @return the previous value associated with the specified key,\n * or {@code null} if there was no mapping for the key\n * @throws NullPointerException if the specified key or value is null\n */\n public V replace(K key, V value) {\n if (key == null || value == null)\n throw new NullPointerException();\n return replaceNode(key, value, null);\n }\n\n // Overrides of JDK8+ Map extension method defaults\n /**\n * Returns the value to which the specified key is mapped, or the\n * given default value if this map contains no mapping for the\n * key.\n *\n * @param key the key whose associated value is to be returned\n * @param defaultValue the value to return if this map contains\n * no mapping for the given key\n * @return the mapping for the key, if present; else the default value\n * @throws NullPointerException if the specified key is null\n */\n public V getOrDefault(Object key, V defaultValue) {\n V v;\n return (v = get(key)) == null ? defaultValue : v;\n }\n\n public void forEach(BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n action.accept(p.key, p.val);\n }\n }\n }\n\n public void replaceAll(BiFunction function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n V oldValue = p.val;\n for (K key = p.key; ; ) {\n V newValue = function.apply(key, oldValue);\n if (newValue == null)\n throw new NullPointerException();\n if (replaceNode(key, newValue, oldValue) != null || (oldValue = get(key)) == null)\n break;\n }\n }\n }\n }\n\n boolean removeEntryIf(Predicate> function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n Map.Entry e = new AbstractMap.SimpleImmutableEntry<>(k, v);\n if (function.test(e) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n boolean removeValueIf(Predicate function) {\n if (function == null)\n throw new NullPointerException();\n Node[] t;\n boolean removed = false;\n if ((t = table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n K k = p.key;\n V v = p.val;\n if (function.test(v) && replaceNode(k, null, v) != null)\n removed = true;\n }\n }\n return removed;\n }\n\n /**\n * If the specified key is not already associated with a value,\n * attempts to compute its value using the given mapping function\n * and enters it into this map unless {@code null}. The entire\n * method invocation is performed atomically. The supplied\n * function is invoked exactly once per invocation of this method\n * if the key is absent, else not at all. Some attempted update\n * operations on this map by other threads may be blocked while\n * computation is in progress, so the computation should be short\n * and simple.\n *\n *

The mapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param mappingFunction the function to compute a value\n * @return the current (existing or computed) value associated with\n * the specified key, or null if the computed value is null\n * @throws NullPointerException if the specified key or mappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the mappingFunction does so,\n * in which case the mapping is left unestablished\n */\n public V computeIfAbsent(K key, Function mappingFunction) {\n if (key == null || mappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n K fk;\n V fv;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = mappingFunction.apply(key)) != null)\n node = new Node(h, key, val);\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else if (// check first node without acquiring lock\n fh == h && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null)\n return fv;\n else {\n boolean added = false;\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = e.val;\n break;\n }\n Node pred = e;\n if ((e = e.next) == null) {\n if ((val = mappingFunction.apply(key)) != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n added = true;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null)\n val = p.val;\n else if ((val = mappingFunction.apply(key)) != null) {\n added = true;\n t.putTreeVal(h, key, val);\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n if (!added)\n return val;\n break;\n }\n }\n }\n if (val != null)\n addCount(1L, binCount);\n return val;\n }\n\n /**\n * If the value for the specified key is present, attempts to\n * compute a new mapping given the key and its current mapped\n * value. The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method if the key is present, else not at all. Some\n * attempted update operations on this map by other threads may be\n * blocked while computation is in progress, so the computation\n * should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which a value may be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V computeIfPresent(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null)\n break;\n else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null)\n break;\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null && (p = r.findTreeNode(h, key, null)) != null) {\n val = remappingFunction.apply(key, p.val);\n if (val != null)\n p.val = val;\n else {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0)\n break;\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * Attempts to compute a mapping for the specified key and its\n * current mapped value (or {@code null} if there is no current\n * mapping). The entire method invocation is performed atomically.\n * The supplied function is invoked exactly once per invocation of\n * this method. Some attempted update operations on this map by\n * other threads may be blocked while computation is in progress,\n * so the computation should be short and simple.\n *\n *

The remapping function must not modify this map during computation.\n *\n * @param key key with which the specified value is to be associated\n * @param remappingFunction the function to compute a value\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or remappingFunction\n * is null\n * @throws IllegalStateException if the computation detectably\n * attempts a recursive update to this map that would\n * otherwise never complete\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V compute(K key, BiFunction remappingFunction) {\n if (key == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n Node r = new ReservationNode();\n synchronized (r) {\n if (casTabAt(tab, i, null, r)) {\n binCount = 1;\n Node node = null;\n try {\n if ((val = remappingFunction.apply(key, null)) != null) {\n delta = 1;\n node = new Node(h, key, val);\n }\n } finally {\n setTabAt(tab, i, node);\n }\n }\n }\n if (binCount != 0)\n break;\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(key, e.val);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n val = remappingFunction.apply(key, null);\n if (val != null) {\n if (pred.next != null)\n throw new IllegalStateException(\"Recursive update\");\n delta = 1;\n pred.next = new Node(h, key, val);\n }\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 1;\n TreeBin t = (TreeBin) f;\n TreeNode r, p;\n if ((r = t.root) != null)\n p = r.findTreeNode(h, key, null);\n else\n p = null;\n V pv = (p == null) ? null : p.val;\n val = remappingFunction.apply(key, pv);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n /**\n * If the specified key is not already associated with a\n * (non-null) value, associates it with the given value.\n * Otherwise, replaces the value with the results of the given\n * remapping function, or removes if {@code null}. The entire\n * method invocation is performed atomically. Some attempted\n * update operations on this map by other threads may be blocked\n * while computation is in progress, so the computation should be\n * short and simple, and must not attempt to update any other\n * mappings of this Map.\n *\n * @param key key with which the specified value is to be associated\n * @param value the value to use if absent\n * @param remappingFunction the function to recompute a value if present\n * @return the new value associated with the specified key, or null if none\n * @throws NullPointerException if the specified key or the\n * remappingFunction is null\n * @throws RuntimeException or Error if the remappingFunction does so,\n * in which case the mapping is unchanged\n */\n public V merge(K key, V value, BiFunction remappingFunction) {\n if (key == null || value == null || remappingFunction == null)\n throw new NullPointerException();\n int h = spread(key.hashCode());\n V val = null;\n int delta = 0;\n int binCount = 0;\n for (Node[] tab = table; ; ) {\n Node f;\n int n, i, fh;\n if (tab == null || (n = tab.length) == 0)\n tab = initTable();\n else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {\n if (casTabAt(tab, i, null, new Node(h, key, value))) {\n delta = 1;\n val = value;\n break;\n }\n } else if ((fh = f.hash) == MOVED)\n tab = helpTransfer(tab, f);\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n if (fh >= 0) {\n binCount = 1;\n for (Node e = f, pred = null; ; ++binCount) {\n K ek;\n if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {\n val = remappingFunction.apply(e.val, value);\n if (val != null)\n e.val = val;\n else {\n delta = -1;\n Node en = e.next;\n if (pred != null)\n pred.next = en;\n else\n setTabAt(tab, i, en);\n }\n break;\n }\n pred = e;\n if ((e = e.next) == null) {\n delta = 1;\n val = value;\n pred.next = new Node(h, key, val);\n break;\n }\n }\n } else if (f instanceof TreeBin) {\n binCount = 2;\n TreeBin t = (TreeBin) f;\n TreeNode r = t.root;\n TreeNode p = (r == null) ? null : r.findTreeNode(h, key, null);\n val = (p == null) ? value : remappingFunction.apply(p.val, value);\n if (val != null) {\n if (p != null)\n p.val = val;\n else {\n delta = 1;\n t.putTreeVal(h, key, val);\n }\n } else if (p != null) {\n delta = -1;\n if (t.removeTreeNode(p))\n setTabAt(tab, i, untreeify(t.first));\n }\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n if (binCount != 0) {\n if (binCount >= TREEIFY_THRESHOLD)\n treeifyBin(tab, i);\n break;\n }\n }\n }\n if (delta != 0)\n addCount((long) delta, binCount);\n return val;\n }\n\n // Hashtable legacy methods\n /**\n * Tests if some key maps into the specified value in this table.\n *\n *

Note that this method is identical in functionality to\n * {@link #containsValue(Object)}, and exists solely to ensure\n * full compatibility with class {@link java.util.Hashtable},\n * which supported this method prior to introduction of the\n * Java Collections Framework.\n *\n * @param value a value to search for\n * @return {@code true} if and only if some key maps to the\n * {@code value} argument in this table as\n * determined by the {@code equals} method;\n * {@code false} otherwise\n * @throws NullPointerException if the specified value is null\n */\n public boolean contains(Object value) {\n return containsValue(value);\n }\n\n /**\n * Returns an enumeration of the keys in this table.\n *\n * @return an enumeration of the keys in this table\n * @see #keySet()\n */\n public Enumeration keys() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, this);\n }\n\n /**\n * Returns an enumeration of the values in this table.\n *\n * @return an enumeration of the values in this table\n * @see #values()\n */\n public Enumeration elements() {\n Node[] t;\n int f = (t = table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, this);\n }\n\n // ConcurrentHashMap-only methods\n /**\n * Returns the number of mappings. This method should be used\n * instead of {@link #size} because a ConcurrentHashMap may\n * contain more mappings than can be represented as an int. The\n * value returned is an estimate; the actual count may differ if\n * there are concurrent insertions or removals.\n *\n * @return the number of mappings\n * @since 1.8\n */\n public long mappingCount() {\n long n = sumCount();\n // ignore transient negative values\n return (n < 0L) ? 0L : n;\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param the element type of the returned set\n * @return the new set\n * @since 1.8\n */\n public static KeySetView newKeySet() {\n return new KeySetView(new ConcurrentHashMap(), Boolean.TRUE);\n }\n\n /**\n * Creates a new {@link Set} backed by a ConcurrentHashMap\n * from the given type to {@code Boolean.TRUE}.\n *\n * @param initialCapacity The implementation performs internal\n * sizing to accommodate this many elements.\n * @param the element type of the returned set\n * @return the new set\n * @throws IllegalArgumentException if the initial capacity of\n * elements is negative\n * @since 1.8\n */\n public static KeySetView newKeySet(int initialCapacity) {\n return new KeySetView(new ConcurrentHashMap(initialCapacity), Boolean.TRUE);\n }\n\n /**\n * Returns a {@link Set} view of the keys in this map, using the\n * given common mapped value for any additions (i.e., {@link\n * Collection#add} and {@link Collection#addAll(Collection)}).\n * This is of course only appropriate if it is acceptable to use\n * the same value for all additions from this view.\n *\n * @param mappedValue the mapped value to use for any additions\n * @return the set view\n * @throws NullPointerException if the mappedValue is null\n */\n public KeySetView keySet(V mappedValue) {\n if (mappedValue == null)\n throw new NullPointerException();\n return new KeySetView(this, mappedValue);\n }\n\n /**\n * A node inserted at head of bins during transfer operations.\n */\n static final class ForwardingNode extends Node {\n\n final Node[] nextTable;\n\n ForwardingNode(Node[] tab) {\n super(MOVED, null, null);\n this.nextTable = tab;\n }\n\n Node find(int h, Object k) {\n // loop to avoid arbitrarily deep recursion on forwarding nodes\n outer: for (Node[] tab = nextTable; ; ) {\n Node e;\n int n;\n if (k == null || tab == null || (n = tab.length) == 0 || (e = tabAt(tab, (n - 1) & h)) == null)\n return null;\n for (; ; ) {\n int eh;\n K ek;\n if ((eh = e.hash) == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n if (eh < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n continue outer;\n } else\n return e.find(h, k);\n }\n if ((e = e.next) == null)\n return null;\n }\n }\n }\n }\n\n /**\n * A place-holder node used in computeIfAbsent and compute.\n */\n static final class ReservationNode extends Node {\n\n ReservationNode() {\n super(RESERVED, null, null);\n }\n\n Node find(int h, Object k) {\n return null;\n }\n }\n\n /* ---------------- Table Initialization and Resizing -------------- */\n /**\n * Returns the stamp bits for resizing a table of size n.\n * Must be negative when shifted left by RESIZE_STAMP_SHIFT.\n */\n static final int resizeStamp(int n) {\n return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));\n }\n\n /**\n * Initializes table, using the size recorded in sizeCtl.\n */\n private final Node[] initTable() {\n Node[] tab;\n int sc;\n while ((tab = table) == null || tab.length == 0) {\n if ((sc = sizeCtl) < 0)\n // lost initialization race; just spin\n Thread.yield();\n else if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if ((tab = table) == null || tab.length == 0) {\n int n = (sc > 0) ? sc : DEFAULT_CAPACITY;\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = tab = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n break;\n }\n }\n return tab;\n }\n\n /**\n * Adds to count, and if table is too small and not already\n * resizing, initiates transfer. If already resizing, helps\n * perform transfer if work is available. Rechecks occupancy\n * after a transfer to see if another resize is already needed\n * because resizings are lagging additions.\n *\n * @param x the count to add\n * @param check if <0, don't check resize, if <= 1 only check if uncontended\n */\n private final void addCount(long x, int check) {\n CounterCell[] cs;\n long b, s;\n if ((cs = counterCells) != null || !U.compareAndSetLong(this, BASECOUNT, b = baseCount, s = b + x)) {\n CounterCell c;\n long v;\n int m;\n boolean uncontended = true;\n if (cs == null || (m = cs.length - 1) < 0 || (c = cs[ThreadLocalRandom.getProbe() & m]) == null || !(uncontended = U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))) {\n fullAddCount(x, uncontended);\n return;\n }\n if (check <= 1)\n return;\n s = sumCount();\n }\n if (check >= 0) {\n Node[] tab, nt;\n int n, sc;\n while (s >= (long) (sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) {\n int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT;\n if (sc < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || (nt = nextTable) == null || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1))\n transfer(tab, nt);\n } else if (U.compareAndSetInt(this, SIZECTL, sc, rs + 2))\n transfer(tab, null);\n s = sumCount();\n }\n }\n }\n\n /**\n * Helps transfer if a resize is in progress.\n */\n final Node[] helpTransfer(Node[] tab, Node f) {\n Node[] nextTab;\n int sc;\n if (tab != null && (f instanceof ForwardingNode) && (nextTab = ((ForwardingNode) f).nextTable) != null) {\n int rs = resizeStamp(tab.length) << RESIZE_STAMP_SHIFT;\n while (nextTab == nextTable && table == tab && (sc = sizeCtl) < 0) {\n if (sc == rs + MAX_RESIZERS || sc == rs + 1 || transferIndex <= 0)\n break;\n if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1)) {\n transfer(tab, nextTab);\n break;\n }\n }\n return nextTab;\n }\n return table;\n }\n\n /**\n * Tries to presize table to accommodate the given number of elements.\n *\n * @param size number of elements (doesn't need to be perfectly accurate)\n */\n private final void tryPresize(int size) {\n int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(size + (size >>> 1) + 1);\n int sc;\n while ((sc = sizeCtl) >= 0) {\n Node[] tab = table;\n int n;\n if (tab == null || (n = tab.length) == 0) {\n n = (sc > c) ? sc : c;\n if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {\n try {\n if (table == tab) {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n];\n table = nt;\n sc = n - (n >>> 2);\n }\n } finally {\n sizeCtl = sc;\n }\n }\n } else if (c <= sc || n >= MAXIMUM_CAPACITY)\n break;\n else if (tab == table) {\n int rs = resizeStamp(n);\n if (U.compareAndSetInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2))\n transfer(tab, null);\n }\n }\n }\n\n /**\n * Moves and/or copies the nodes in each bin to new table. See\n * above for explanation.\n */\n private final void transfer(Node[] tab, Node[] nextTab) {\n int n = tab.length, stride;\n if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)\n // subdivide range\n stride = MIN_TRANSFER_STRIDE;\n if (nextTab == null) {\n // initiating\n try {\n @SuppressWarnings(\"unchecked\")\n Node[] nt = (Node[]) new Node[n << 1];\n nextTab = nt;\n } catch (Throwable ex) {\n // try to cope with OOME\n sizeCtl = Integer.MAX_VALUE;\n return;\n }\n nextTable = nextTab;\n transferIndex = n;\n }\n int nextn = nextTab.length;\n ForwardingNode fwd = new ForwardingNode(nextTab);\n boolean advance = true;\n // to ensure sweep before committing nextTab\n boolean finishing = false;\n for (int i = 0, bound = 0; ; ) {\n Node f;\n int fh;\n while (advance) {\n int nextIndex, nextBound;\n if (--i >= bound || finishing)\n advance = false;\n else if ((nextIndex = transferIndex) <= 0) {\n i = -1;\n advance = false;\n } else if (U.compareAndSetInt(this, TRANSFERINDEX, nextIndex, nextBound = (nextIndex > stride ? nextIndex - stride : 0))) {\n bound = nextBound;\n i = nextIndex - 1;\n advance = false;\n }\n }\n if (i < 0 || i >= n || i + n >= nextn) {\n int sc;\n if (finishing) {\n nextTable = null;\n table = nextTab;\n sizeCtl = (n << 1) - (n >>> 1);\n return;\n }\n if (U.compareAndSetInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {\n if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)\n return;\n finishing = advance = true;\n // recheck before commit\n i = n;\n }\n } else if ((f = tabAt(tab, i)) == null)\n advance = casTabAt(tab, i, null, fwd);\n else if ((fh = f.hash) == MOVED)\n // already processed\n advance = true;\n else {\n synchronized (f) {\n if (tabAt(tab, i) == f) {\n Node ln, hn;\n if (fh >= 0) {\n int runBit = fh & n;\n Node lastRun = f;\n for (Node p = f.next; p != null; p = p.next) {\n int b = p.hash & n;\n if (b != runBit) {\n runBit = b;\n lastRun = p;\n }\n }\n if (runBit == 0) {\n ln = lastRun;\n hn = null;\n } else {\n hn = lastRun;\n ln = null;\n }\n for (Node p = f; p != lastRun; p = p.next) {\n int ph = p.hash;\n K pk = p.key;\n V pv = p.val;\n if ((ph & n) == 0)\n ln = new Node(ph, pk, pv, ln);\n else\n hn = new Node(ph, pk, pv, hn);\n }\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof TreeBin) {\n TreeBin t = (TreeBin) f;\n TreeNode lo = null, loTail = null;\n TreeNode hi = null, hiTail = null;\n int lc = 0, hc = 0;\n for (Node e = t.first; e != null; e = e.next) {\n int h = e.hash;\n TreeNode p = new TreeNode(h, e.key, e.val, null, null);\n if ((h & n) == 0) {\n if ((p.prev = loTail) == null)\n lo = p;\n else\n loTail.next = p;\n loTail = p;\n ++lc;\n } else {\n if ((p.prev = hiTail) == null)\n hi = p;\n else\n hiTail.next = p;\n hiTail = p;\n ++hc;\n }\n }\n ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : (hc != 0) ? new TreeBin(lo) : t;\n hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : (lc != 0) ? new TreeBin(hi) : t;\n setTabAt(nextTab, i, ln);\n setTabAt(nextTab, i + n, hn);\n setTabAt(tab, i, fwd);\n advance = true;\n } else if (f instanceof ReservationNode)\n throw new IllegalStateException(\"Recursive update\");\n }\n }\n }\n }\n }\n\n /**\n * A padded cell for distributing counts. Adapted from LongAdder\n * and Striped64. See their internal docs for explanation.\n */\n @jdk.internal.vm.annotation.Contended\n static final class CounterCell {\n\n volatile long value;\n\n CounterCell(long x) {\n value = x;\n }\n }\n\n final long sumCount() {\n CounterCell[] cs = counterCells;\n long sum = baseCount;\n if (cs != null) {\n for (CounterCell c : cs) if (c != null)\n sum += c.value;\n }\n return sum;\n }\n\n // See LongAdder version for explanation\n private final void fullAddCount(long x, boolean wasUncontended) {\n int h;\n if ((h = ThreadLocalRandom.getProbe()) == 0) {\n // force initialization\n ThreadLocalRandom.localInit();\n h = ThreadLocalRandom.getProbe();\n wasUncontended = true;\n }\n // True if last slot nonempty\n boolean collide = false;\n for (; ; ) {\n CounterCell[] cs;\n CounterCell c;\n int n;\n long v;\n if ((cs = counterCells) != null && (n = cs.length) > 0) {\n if ((c = cs[(n - 1) & h]) == null) {\n if (cellsBusy == 0) {\n // Try to attach new Cell\n // Optimistic create\n CounterCell r = new CounterCell(x);\n if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean created = false;\n try {\n // Recheck under lock\n CounterCell[] rs;\n int m, j;\n if ((rs = counterCells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) {\n rs[j] = r;\n created = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (created)\n break;\n // Slot is now non-empty\n continue;\n }\n }\n collide = false;\n } else if (// CAS already known to fail\n !wasUncontended)\n // Continue after rehash\n wasUncontended = true;\n else if (U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))\n break;\n else if (counterCells != cs || n >= NCPU)\n // At max size or stale\n collide = false;\n else if (!collide)\n collide = true;\n else if (cellsBusy == 0 && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n try {\n if (// Expand table unless stale\n counterCells == cs)\n counterCells = Arrays.copyOf(cs, n << 1);\n } finally {\n cellsBusy = 0;\n }\n collide = false;\n // Retry with expanded table\n continue;\n }\n h = ThreadLocalRandom.advanceProbe(h);\n } else if (cellsBusy == 0 && counterCells == cs && U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {\n boolean init = false;\n try {\n // Initialize table\n if (counterCells == cs) {\n CounterCell[] rs = new CounterCell[2];\n rs[h & 1] = new CounterCell(x);\n counterCells = rs;\n init = true;\n }\n } finally {\n cellsBusy = 0;\n }\n if (init)\n break;\n } else if (U.compareAndSetLong(this, BASECOUNT, v = baseCount, v + x))\n // Fall back on using base\n break;\n }\n }\n\n /**\n * Replaces all linked nodes in bin at given index unless table is\n * too small, in which case resizes instead.\n */\n private final void treeifyBin(Node[] tab, int index) {\n Node b;\n int n;\n if (tab != null) {\n if ((n = tab.length) < MIN_TREEIFY_CAPACITY)\n tryPresize(n << 1);\n else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {\n synchronized (b) {\n if (tabAt(tab, index) == b) {\n TreeNode hd = null, tl = null;\n for (Node e = b; e != null; e = e.next) {\n TreeNode p = new TreeNode(e.hash, e.key, e.val, null, null);\n if ((p.prev = tl) == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n setTabAt(tab, index, new TreeBin(hd));\n }\n }\n }\n }\n }\n\n /**\n * Returns a list of non-TreeNodes replacing those in given list.\n */\n static Node untreeify(Node b) {\n Node hd = null, tl = null;\n for (Node q = b; q != null; q = q.next) {\n Node p = new Node(q.hash, q.key, q.val);\n if (tl == null)\n hd = p;\n else\n tl.next = p;\n tl = p;\n }\n return hd;\n }\n\n /**\n * Nodes for use in TreeBins.\n */\n static final class TreeNode extends Node {\n\n // red-black tree links\n TreeNode parent;\n\n TreeNode left;\n\n TreeNode right;\n\n // needed to unlink next upon deletion\n TreeNode prev;\n\n boolean red;\n\n TreeNode(int hash, K key, V val, Node next, TreeNode parent) {\n super(hash, key, val, next);\n this.parent = parent;\n }\n\n Node find(int h, Object k) {\n return findTreeNode(h, k, null);\n }\n\n /**\n * Returns the TreeNode (or null if not found) for the given key\n * starting at given root.\n */\n final TreeNode findTreeNode(int h, Object k, Class kc) {\n if (k != null) {\n TreeNode p = this;\n do {\n int ph, dir;\n K pk;\n TreeNode q;\n TreeNode pl = p.left, pr = p.right;\n if ((ph = p.hash) > h)\n p = pl;\n else if (ph < h)\n p = pr;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if (pl == null)\n p = pr;\n else if (pr == null)\n p = pl;\n else if ((kc != null || (kc = comparableClassFor(k)) != null) && (dir = compareComparables(kc, k, pk)) != 0)\n p = (dir < 0) ? pl : pr;\n else if ((q = pr.findTreeNode(h, k, kc)) != null)\n return q;\n else\n p = pl;\n } while (p != null);\n }\n return null;\n }\n }\n\n /**\n * TreeNodes used at the heads of bins. TreeBins do not hold user\n * keys or values, but instead point to list of TreeNodes and\n * their root. They also maintain a parasitic read-write lock\n * forcing writers (who hold bin lock) to wait for readers (who do\n * not) to complete before tree restructuring operations.\n */\n static final class TreeBin extends Node {\n\n TreeNode root;\n\n volatile TreeNode first;\n\n volatile Thread waiter;\n\n volatile int lockState;\n\n // values for lockState\n // set while holding write lock\n static final int WRITER = 1;\n\n // set when waiting for write lock\n static final int WAITER = 2;\n\n // increment value for setting read lock\n static final int READER = 4;\n\n /**\n * Tie-breaking utility for ordering insertions when equal\n * hashCodes and non-comparable. We don't require a total\n * order, just a consistent insertion rule to maintain\n * equivalence across rebalancings. Tie-breaking further than\n * necessary simplifies testing a bit.\n */\n static int tieBreakOrder(Object a, Object b) {\n int d;\n if (a == null || b == null || (d = a.getClass().getName().compareTo(b.getClass().getName())) == 0)\n d = (System.identityHashCode(a) <= System.identityHashCode(b) ? -1 : 1);\n return d;\n }\n\n /**\n * Creates bin with initial set of nodes headed by b.\n */\n TreeBin(TreeNode b) {\n super(TREEBIN, null, null);\n this.first = b;\n TreeNode r = null;\n for (TreeNode x = b, next; x != null; x = next) {\n next = (TreeNode) x.next;\n x.left = x.right = null;\n if (r == null) {\n x.parent = null;\n x.red = false;\n r = x;\n } else {\n K k = x.key;\n int h = x.hash;\n Class kc = null;\n for (TreeNode p = r; ; ) {\n int dir, ph;\n K pk = p.key;\n if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0)\n dir = tieBreakOrder(k, pk);\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n x.parent = xp;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n r = balanceInsertion(r, x);\n break;\n }\n }\n }\n }\n this.root = r;\n assert checkInvariants(root);\n }\n\n /**\n * Acquires write lock for tree restructuring.\n */\n private final void lockRoot() {\n if (!U.compareAndSetInt(this, LOCKSTATE, 0, WRITER))\n // offload to separate method\n contendedLock();\n }\n\n /**\n * Releases write lock for tree restructuring.\n */\n private final void unlockRoot() {\n lockState = 0;\n }\n\n /**\n * Possibly blocks awaiting root lock.\n */\n private final void contendedLock() {\n boolean waiting = false;\n for (int s; ; ) {\n if (((s = lockState) & ~WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, WRITER)) {\n if (waiting)\n waiter = null;\n return;\n }\n } else if ((s & WAITER) == 0) {\n if (U.compareAndSetInt(this, LOCKSTATE, s, s | WAITER)) {\n waiting = true;\n waiter = Thread.currentThread();\n }\n } else if (waiting)\n LockSupport.park(this);\n }\n }\n\n /**\n * Returns matching node or null if none. Tries to search\n * using tree comparisons from root, but continues linear\n * search when lock not available.\n */\n final Node find(int h, Object k) {\n if (k != null) {\n for (Node e = first; e != null; ) {\n int s;\n K ek;\n if (((s = lockState) & (WAITER | WRITER)) != 0) {\n if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))\n return e;\n e = e.next;\n } else if (U.compareAndSetInt(this, LOCKSTATE, s, s + READER)) {\n TreeNode r, p;\n ", "post_mask_code": "\n return p;\n }\n }\n }\n return null;\n }\n\n /**\n * Finds or adds a node.\n * @return null if added\n */\n final TreeNode putTreeVal(int h, K k, V v) {\n Class kc = null;\n boolean searched = false;\n for (TreeNode p = root; ; ) {\n int dir, ph;\n K pk;\n if (p == null) {\n first = root = new TreeNode(h, k, v, null, null);\n break;\n } else if ((ph = p.hash) > h)\n dir = -1;\n else if (ph < h)\n dir = 1;\n else if ((pk = p.key) == k || (pk != null && k.equals(pk)))\n return p;\n else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) {\n if (!searched) {\n TreeNode q, ch;\n searched = true;\n if (((ch = p.left) != null && (q = ch.findTreeNode(h, k, kc)) != null) || ((ch = p.right) != null && (q = ch.findTreeNode(h, k, kc)) != null))\n return q;\n }\n dir = tieBreakOrder(k, pk);\n }\n TreeNode xp = p;\n if ((p = (dir <= 0) ? p.left : p.right) == null) {\n TreeNode x, f = first;\n first = x = new TreeNode(h, k, v, f, xp);\n if (f != null)\n f.prev = x;\n if (dir <= 0)\n xp.left = x;\n else\n xp.right = x;\n if (!xp.red)\n x.red = true;\n else {\n lockRoot();\n try {\n root = balanceInsertion(root, x);\n } finally {\n unlockRoot();\n }\n }\n break;\n }\n }\n assert checkInvariants(root);\n return null;\n }\n\n /**\n * Removes the given node, that must be present before this\n * call. This is messier than typical red-black deletion code\n * because we cannot swap the contents of an interior node\n * with a leaf successor that is pinned by \"next\" pointers\n * that are accessible independently of lock. So instead we\n * swap the tree linkages.\n *\n * @return true if now too small, so should be untreeified\n */\n final boolean removeTreeNode(TreeNode p) {\n TreeNode next = (TreeNode) p.next;\n // unlink traversal pointers\n TreeNode pred = p.prev;\n TreeNode r, rl;\n if (pred == null)\n first = next;\n else\n pred.next = next;\n if (next != null)\n next.prev = pred;\n if (first == null) {\n root = null;\n return true;\n }\n if (// too small\n (r = root) == null || r.right == null || (rl = r.left) == null || rl.left == null)\n return true;\n lockRoot();\n try {\n TreeNode replacement;\n TreeNode pl = p.left;\n TreeNode pr = p.right;\n if (pl != null && pr != null) {\n TreeNode s = pr, sl;\n while (// find successor\n (sl = s.left) != null) s = sl;\n // swap colors\n boolean c = s.red;\n // swap colors\n s.red = p.red;\n // swap colors\n p.red = c;\n TreeNode sr = s.right;\n TreeNode pp = p.parent;\n if (s == pr) {\n // p was s's direct parent\n p.parent = s;\n s.right = p;\n } else {\n TreeNode sp = s.parent;\n if ((p.parent = sp) != null) {\n if (s == sp.left)\n sp.left = p;\n else\n sp.right = p;\n }\n if ((s.right = pr) != null)\n pr.parent = s;\n }\n p.left = null;\n if ((p.right = sr) != null)\n sr.parent = p;\n if ((s.left = pl) != null)\n pl.parent = s;\n if ((s.parent = pp) == null)\n r = s;\n else if (p == pp.left)\n pp.left = s;\n else\n pp.right = s;\n if (sr != null)\n replacement = sr;\n else\n replacement = p;\n } else if (pl != null)\n replacement = pl;\n else if (pr != null)\n replacement = pr;\n else\n replacement = p;\n if (replacement != p) {\n TreeNode pp = replacement.parent = p.parent;\n if (pp == null)\n r = replacement;\n else if (p == pp.left)\n pp.left = replacement;\n else\n pp.right = replacement;\n p.left = p.right = p.parent = null;\n }\n root = (p.red) ? r : balanceDeletion(r, replacement);\n if (p == replacement) {\n // detach pointers\n TreeNode pp;\n if ((pp = p.parent) != null) {\n if (p == pp.left)\n pp.left = null;\n else if (p == pp.right)\n pp.right = null;\n p.parent = null;\n }\n }\n } finally {\n unlockRoot();\n }\n assert checkInvariants(root);\n return false;\n }\n\n // Red-black tree methods, all adapted from CLR\n static TreeNode rotateLeft(TreeNode root, TreeNode p) {\n TreeNode r, pp, rl;\n if (p != null && (r = p.right) != null) {\n if ((rl = p.right = r.left) != null)\n rl.parent = p;\n if ((pp = r.parent = p.parent) == null)\n (root = r).red = false;\n else if (pp.left == p)\n pp.left = r;\n else\n pp.right = r;\n r.left = p;\n p.parent = r;\n }\n return root;\n }\n\n static TreeNode rotateRight(TreeNode root, TreeNode p) {\n TreeNode l, pp, lr;\n if (p != null && (l = p.left) != null) {\n if ((lr = p.left = l.right) != null)\n lr.parent = p;\n if ((pp = l.parent = p.parent) == null)\n (root = l).red = false;\n else if (pp.right == p)\n pp.right = l;\n else\n pp.left = l;\n l.right = p;\n p.parent = l;\n }\n return root;\n }\n\n static TreeNode balanceInsertion(TreeNode root, TreeNode x) {\n x.red = true;\n for (TreeNode xp, xpp, xppl, xppr; ; ) {\n if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (!xp.red || (xpp = xp.parent) == null)\n return root;\n if (xp == (xppl = xpp.left)) {\n if ((xppr = xpp.right) != null && xppr.red) {\n xppr.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.right) {\n root = rotateLeft(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateRight(root, xpp);\n }\n }\n }\n } else {\n if (xppl != null && xppl.red) {\n xppl.red = false;\n xp.red = false;\n xpp.red = true;\n x = xpp;\n } else {\n if (x == xp.left) {\n root = rotateRight(root, x = xp);\n xpp = (xp = x.parent) == null ? null : xp.parent;\n }\n if (xp != null) {\n xp.red = false;\n if (xpp != null) {\n xpp.red = true;\n root = rotateLeft(root, xpp);\n }\n }\n }\n }\n }\n }\n\n static TreeNode balanceDeletion(TreeNode root, TreeNode x) {\n for (TreeNode xp, xpl, xpr; ; ) {\n if (x == null || x == root)\n return root;\n else if ((xp = x.parent) == null) {\n x.red = false;\n return x;\n } else if (x.red) {\n x.red = false;\n return root;\n } else if ((xpl = xp.left) == x) {\n if ((xpr = xp.right) != null && xpr.red) {\n xpr.red = false;\n xp.red = true;\n root = rotateLeft(root, xp);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr == null)\n x = xp;\n else {\n TreeNode sl = xpr.left, sr = xpr.right;\n if ((sr == null || !sr.red) && (sl == null || !sl.red)) {\n xpr.red = true;\n x = xp;\n } else {\n if (sr == null || !sr.red) {\n if (sl != null)\n sl.red = false;\n xpr.red = true;\n root = rotateRight(root, xpr);\n xpr = (xp = x.parent) == null ? null : xp.right;\n }\n if (xpr != null) {\n xpr.red = (xp == null) ? false : xp.red;\n if ((sr = xpr.right) != null)\n sr.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateLeft(root, xp);\n }\n x = root;\n }\n }\n } else {\n // symmetric\n if (xpl != null && xpl.red) {\n xpl.red = false;\n xp.red = true;\n root = rotateRight(root, xp);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl == null)\n x = xp;\n else {\n TreeNode sl = xpl.left, sr = xpl.right;\n if ((sl == null || !sl.red) && (sr == null || !sr.red)) {\n xpl.red = true;\n x = xp;\n } else {\n if (sl == null || !sl.red) {\n if (sr != null)\n sr.red = false;\n xpl.red = true;\n root = rotateLeft(root, xpl);\n xpl = (xp = x.parent) == null ? null : xp.left;\n }\n if (xpl != null) {\n xpl.red = (xp == null) ? false : xp.red;\n if ((sl = xpl.left) != null)\n sl.red = false;\n }\n if (xp != null) {\n xp.red = false;\n root = rotateRight(root, xp);\n }\n x = root;\n }\n }\n }\n }\n }\n\n /**\n * Checks invariants recursively for the tree of Nodes rooted at t.\n */\n static boolean checkInvariants(TreeNode t) {\n TreeNode tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode) t.next;\n if (tb != null && tb.next != t)\n return false;\n if (tn != null && tn.prev != t)\n return false;\n if (tp != null && t != tp.left && t != tp.right)\n return false;\n if (tl != null && (tl.parent != t || tl.hash > t.hash))\n return false;\n if (tr != null && (tr.parent != t || tr.hash < t.hash))\n return false;\n if (t.red && tl != null && tl.red && tr != null && tr.red)\n return false;\n if (tl != null && !checkInvariants(tl))\n return false;\n if (tr != null && !checkInvariants(tr))\n return false;\n return true;\n }\n\n private static final long LOCKSTATE = U.objectFieldOffset(TreeBin.class, \"lockState\");\n }\n\n /**\n * Records the table, its length, and current traversal index for a\n * traverser that must process a region of a forwarded table before\n * proceeding with current table.\n */\n static final class TableStack {\n\n int length;\n\n int index;\n\n Node[] tab;\n\n TableStack next;\n }\n\n /**\n * Encapsulates traversal for methods such as containsValue; also\n * serves as a base class for other iterators and spliterators.\n *\n * Method advance visits once each still-valid node that was\n * reachable upon iterator construction. It might miss some that\n * were added to a bin after the bin was visited, which is OK wrt\n * consistency guarantees. Maintaining this property in the face\n * of possible ongoing resizes requires a fair amount of\n * bookkeeping state that is difficult to optimize away amidst\n * volatile accesses. Even so, traversal maintains reasonable\n * throughput.\n *\n * Normally, iteration proceeds bin-by-bin traversing lists.\n * However, if the table has been resized, then all future steps\n * must traverse both the bin at the current index as well as at\n * (index + baseSize); and so on for further resizings. To\n * paranoically cope with potential sharing by users of iterators\n * across threads, iteration terminates if a bounds checks fails\n * for a table read.\n */\n static class Traverser {\n\n // current table; updated if resized\n Node[] tab;\n\n // the next entry to use\n Node next;\n\n // to save/restore on ForwardingNodes\n TableStack stack, spare;\n\n // index of bin to use next\n int index;\n\n // current index of initial table\n int baseIndex;\n\n // index bound for initial table\n int baseLimit;\n\n // initial table size\n final int baseSize;\n\n Traverser(Node[] tab, int size, int index, int limit) {\n this.tab = tab;\n this.baseSize = size;\n this.baseIndex = this.index = index;\n this.baseLimit = limit;\n this.next = null;\n }\n\n /**\n * Advances if possible, returning next valid node, or null if none.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n // must use locals in checks\n Node[] t;\n // must use locals in checks\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n // visit upper slots if present\n index = ++baseIndex;\n }\n }\n\n /**\n * Saves traversal state upon encountering a forwarding node.\n */\n private void pushState(Node[] t, int i, int n) {\n // reuse if possible\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n /**\n * Possibly pops traversal state.\n *\n * @param n length of current table\n */\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /**\n * Base of key, value, and entry Iterators. Adds fields to\n * Traverser to support iterator.remove.\n */\n static class BaseIterator extends Traverser {\n\n final ConcurrentHashMap map;\n\n Node lastReturned;\n\n BaseIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n advance();\n }\n\n public final boolean hasNext() {\n return next != null;\n }\n\n public final boolean hasMoreElements() {\n return next != null;\n }\n\n public final void remove() {\n Node p;\n if ((p = lastReturned) == null)\n throw new IllegalStateException();\n lastReturned = null;\n map.replaceNode(p.key, null, null);\n }\n }\n\n static final class KeyIterator extends BaseIterator implements Iterator, Enumeration {\n\n KeyIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final K next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n lastReturned = p;\n advance();\n return k;\n }\n\n public final K nextElement() {\n return next();\n }\n }\n\n static final class ValueIterator extends BaseIterator implements Iterator, Enumeration {\n\n ValueIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final V next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n V v = p.val;\n lastReturned = p;\n advance();\n return v;\n }\n\n public final V nextElement() {\n return next();\n }\n }\n\n static final class EntryIterator extends BaseIterator implements Iterator> {\n\n EntryIterator(Node[] tab, int size, int index, int limit, ConcurrentHashMap map) {\n super(tab, size, index, limit, map);\n }\n\n public final Map.Entry next() {\n Node p;\n if ((p = next) == null)\n throw new NoSuchElementException();\n K k = p.key;\n V v = p.val;\n lastReturned = p;\n advance();\n return new MapEntry(k, v, map);\n }\n }\n\n static final class MapEntry implements Map.Entry {\n\n final K key;\n\n V val;\n\n final ConcurrentHashMap map;\n\n MapEntry(K key, V val, ConcurrentHashMap map) {\n this.key = key;\n this.val = val;\n this.map = map;\n }\n\n public K getKey() {\n return key;\n }\n\n public V getValue() {\n return val;\n }\n\n public int hashCode() {\n return key.hashCode() ^ val.hashCode();\n }\n\n public String toString() {\n return Helpers.mapEntryToString(key, val);\n }\n\n public boolean equals(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == val || v.equals(val)));\n }\n\n /**\n * Sets our entry's value and writes through to the map. The\n * value to return is somewhat arbitrary here. Since we do not\n * necessarily track asynchronous changes, the most recent\n * \"previous\" value could be different from what we return (or\n * could even have been removed, in which case the put will\n * re-establish). We do not and cannot guarantee more.\n */\n public V setValue(V value) {\n if (value == null)\n throw new NullPointerException();\n V v = val;\n val = value;\n map.put(key, value);\n return v;\n }\n }\n\n static final class KeySpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n KeySpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public KeySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new KeySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.key);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class ValueSpliterator extends Traverser implements Spliterator {\n\n // size estimate\n long est;\n\n ValueSpliterator(Node[] tab, int size, int index, int limit, long est) {\n super(tab, size, index, limit);\n this.est = est;\n }\n\n public ValueSpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new ValueSpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1);\n }\n\n public void forEachRemaining(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n }\n\n public boolean tryAdvance(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(p.val);\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n static final class EntrySpliterator extends Traverser implements Spliterator> {\n\n // To export MapEntry\n final ConcurrentHashMap map;\n\n // size estimate\n long est;\n\n EntrySpliterator(Node[] tab, int size, int index, int limit, long est, ConcurrentHashMap map) {\n super(tab, size, index, limit);\n this.map = map;\n this.est = est;\n }\n\n public EntrySpliterator trySplit() {\n int i, f, h;\n return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : new EntrySpliterator(tab, baseSize, baseLimit = h, f, est >>>= 1, map);\n }\n\n public void forEachRemaining(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n for (Node p; (p = advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n\n public boolean tryAdvance(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node p;\n if ((p = advance()) == null)\n return false;\n action.accept(new MapEntry(p.key, p.val, map));\n return true;\n }\n\n public long estimateSize() {\n return est;\n }\n\n public int characteristics() {\n return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;\n }\n }\n\n // Parallel bulk operations\n /**\n * Computes initial batch value for bulk tasks. The returned value\n * is approximately exp2 of the number of times (minus one) to\n * split task by two before executing leaf action. This value is\n * faster to compute and more convenient to use as a guide to\n * splitting than is the depth, since it is used while dividing by\n * two anyway.\n */\n final int batchFor(long b) {\n long n;\n if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)\n return 0;\n // slack of 4\n int sp = ForkJoinPool.getCommonPoolParallelism() << 2;\n return (b <= 0L || (n /= b) >= sp) ? sp : (int) n;\n }\n\n /**\n * Performs the given action for each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiConsumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each (key, value).\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEach(long parallelismThreshold, BiFunction transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedMappingTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each (key, value), or null if none. Upon\n * success, further element processing is suppressed and the\n * results of any other parallel invocations of the search\n * function are ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each (key, value), or null if none\n * @since 1.8\n */\n public U search(long parallelismThreshold, BiFunction searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public U reduce(long parallelismThreshold, BiFunction transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public double reduceToDouble(long parallelismThreshold, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public long reduceToLong(long parallelismThreshold, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all (key, value) pairs using the given reducer to\n * combine values, and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all (key, value) pairs\n * @since 1.8\n */\n public int reduceToInt(long parallelismThreshold, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceMappingsToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each key.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachKey(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedKeyTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each key, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each key, or null if none\n * @since 1.8\n */\n public U searchKeys(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all keys using the given\n * reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all keys using the given\n * reducer to combine values, or null if none\n * @since 1.8\n */\n public K reduceKeys(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public U reduceKeys(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public double reduceKeysToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public long reduceKeysToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all keys using the given reducer to combine values, and\n * the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all keys\n * @since 1.8\n */\n public int reduceKeysToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceKeysToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Consumer action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachValueTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachValue(long parallelismThreshold, Function transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedValueTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each value, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each value, or null if none\n * @since 1.8\n */\n public U searchValues(long parallelismThreshold, Function searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all values using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all values\n * @since 1.8\n */\n public V reduceValues(long parallelismThreshold, BiFunction reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values, or\n * null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public U reduceValues(long parallelismThreshold, Function transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public double reduceValuesToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public long reduceValuesToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all values using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all values\n * @since 1.8\n */\n public int reduceValuesToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceValuesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Performs the given action for each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param action the action\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n new ForEachEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();\n }\n\n /**\n * Performs the given action for each non-null transformation\n * of each entry.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case the action is not applied)\n * @param action the action\n * @param the return type of the transformer\n * @since 1.8\n */\n public void forEachEntry(long parallelismThreshold, Function, ? extends U> transformer, Consumer action) {\n if (transformer == null || action == null)\n throw new NullPointerException();\n new ForEachTransformedEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, transformer, action).invoke();\n }\n\n /**\n * Returns a non-null result from applying the given search\n * function on each entry, or null if none. Upon success,\n * further element processing is suppressed and the results of\n * any other parallel invocations of the search function are\n * ignored.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param searchFunction a function returning a non-null\n * result on success, else null\n * @param the return type of the search function\n * @return a non-null result from applying the given search\n * function on each entry, or null if none\n * @since 1.8\n */\n public U searchEntries(long parallelismThreshold, Function, ? extends U> searchFunction) {\n if (searchFunction == null)\n throw new NullPointerException();\n return new SearchEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, searchFunction, new AtomicReference()).invoke();\n }\n\n /**\n * Returns the result of accumulating all entries using the\n * given reducer to combine values, or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param reducer a commutative associative combining function\n * @return the result of accumulating all entries\n * @since 1.8\n */\n public Map.Entry reduceEntries(long parallelismThreshold, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n if (reducer == null)\n throw new NullPointerException();\n return new ReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * or null if none.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element, or null if there is no transformation (in\n * which case it is not combined)\n * @param reducer a commutative associative combining function\n * @param the return type of the transformer\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public U reduceEntries(long parallelismThreshold, Function, ? extends U> transformer, BiFunction reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public double reduceEntriesToDouble(long parallelismThreshold, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToDoubleTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public long reduceEntriesToLong(long parallelismThreshold, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToLongTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n /**\n * Returns the result of accumulating the given transformation\n * of all entries using the given reducer to combine values,\n * and the given basis as an identity value.\n *\n * @param parallelismThreshold the (estimated) number of elements\n * needed for this operation to be executed in parallel\n * @param transformer a function returning the transformation\n * for an element\n * @param basis the identity (initial default value) for the reduction\n * @param reducer a commutative associative combining function\n * @return the result of accumulating the given transformation\n * of all entries\n * @since 1.8\n */\n public int reduceEntriesToInt(long parallelismThreshold, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n if (transformer == null || reducer == null)\n throw new NullPointerException();\n return new MapReduceEntriesToIntTask(null, batchFor(parallelismThreshold), 0, 0, table, null, transformer, basis, reducer).invoke();\n }\n\n abstract static class CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n final ConcurrentHashMap map;\n\n CollectionView(ConcurrentHashMap map) {\n this.map = map;\n }\n\n /**\n * Returns the map backing this view.\n *\n * @return the map backing this view\n */\n public ConcurrentHashMap getMap() {\n return map;\n }\n\n /**\n * Removes all of the elements from this view, by removing all\n * the mappings from the map backing this view.\n */\n public final void clear() {\n map.clear();\n }\n\n public final int size() {\n return map.size();\n }\n\n public final boolean isEmpty() {\n return map.isEmpty();\n }\n\n // implementations below rely on concrete classes supplying these\n /**\n * Returns an iterator over the elements in this collection.\n *\n *

The returned iterator is\n * weakly consistent.\n *\n * @return an iterator over the elements in this collection\n */\n public abstract Iterator iterator();\n\n public abstract boolean contains(Object o);\n\n public abstract boolean remove(Object o);\n\n private static final String OOME_MSG = \"Required array size too large\";\n\n public final Object[] toArray() {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int n = (int) sz;\n Object[] r = new Object[n];\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = e;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n @SuppressWarnings(\"unchecked\")\n public final T[] toArray(T[] a) {\n long sz = map.mappingCount();\n if (sz > MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n int m = (int) sz;\n T[] r = (a.length >= m) ? a : (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), m);\n int n = r.length;\n int i = 0;\n for (E e : this) {\n if (i == n) {\n if (n >= MAX_ARRAY_SIZE)\n throw new OutOfMemoryError(OOME_MSG);\n if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)\n n = MAX_ARRAY_SIZE;\n else\n n += (n >>> 1) + 1;\n r = Arrays.copyOf(r, n);\n }\n r[i++] = (T) e;\n }\n if (a == r && i < n) {\n r[i] = null;\n return r;\n }\n return (i == n) ? r : Arrays.copyOf(r, i);\n }\n\n /**\n * Returns a string representation of this collection.\n * The string representation consists of the string representations\n * of the collection's elements in the order they are returned by\n * its iterator, enclosed in square brackets ({@code \"[]\"}).\n * Adjacent elements are separated by the characters {@code \", \"}\n * (comma and space). Elements are converted to strings as by\n * {@link String#valueOf(Object)}.\n *\n * @return a string representation of this collection\n */\n public final String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append('[');\n Iterator it = iterator();\n if (it.hasNext()) {\n for (; ; ) {\n Object e = it.next();\n sb.append(e == this ? \"(this Collection)\" : e);\n if (!it.hasNext())\n break;\n sb.append(',').append(' ');\n }\n }\n return sb.append(']').toString();\n }\n\n public final boolean containsAll(Collection c) {\n if (c != this) {\n for (Object e : c) {\n if (e == null || !contains(e))\n return false;\n }\n }\n return true;\n }\n\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n // Use (c instanceof Set) as a hint that lookup in c is as\n // efficient as this view\n Node[] t;\n if ((t = map.table) == null) {\n return false;\n } else if (c instanceof Set && c.size() > t.length) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n } else {\n for (Object e : c) modified |= remove(e);\n }\n return modified;\n }\n\n public final boolean retainAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (!c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of keys, in\n * which additions may optionally be enabled by mapping to a\n * common value. This class cannot be directly instantiated.\n * See {@link #keySet() keySet()},\n * {@link #keySet(Object) keySet(V)},\n * {@link #newKeySet() newKeySet()},\n * {@link #newKeySet(int) newKeySet(int)}.\n *\n * @since 1.8\n */\n public static class KeySetView extends CollectionView implements Set, java.io.Serializable {\n\n private static final long serialVersionUID = 7249069246763182397L;\n\n // Conditionally serializable\n @SuppressWarnings(\"serial\")\n private final V value;\n\n KeySetView(ConcurrentHashMap map, V value) {\n super(map);\n this.value = value;\n }\n\n /**\n * Returns the default mapped value for additions,\n * or {@code null} if additions are not supported.\n *\n * @return the default mapped value for additions, or {@code null}\n * if not supported\n */\n public V getMappedValue() {\n return value;\n }\n\n /**\n * {@inheritDoc}\n * @throws NullPointerException if the specified key is null\n */\n public boolean contains(Object o) {\n return map.containsKey(o);\n }\n\n /**\n * Removes the key from this map view, by removing the key (and its\n * corresponding value) from the backing map. This method does\n * nothing if the key is not in the map.\n *\n * @param o the key to be removed from the backing map\n * @return {@code true} if the backing map contained the specified key\n * @throws NullPointerException if the specified key is null\n */\n public boolean remove(Object o) {\n return map.remove(o) != null;\n }\n\n /**\n * @return an iterator over the keys of the backing map\n */\n public Iterator iterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeyIterator(t, f, 0, f, m);\n }\n\n /**\n * Adds the specified key to this set view by mapping the key to\n * the default mapped value in the backing map, if defined.\n *\n * @param e key to be added\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the specified key is null\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean add(K e) {\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n return map.putVal(e, v, true) == null;\n }\n\n /**\n * Adds all of the elements in the specified collection to this set,\n * as if by calling {@link #add} on each one.\n *\n * @param c the elements to be inserted into this set\n * @return {@code true} if this set changed as a result of the call\n * @throws NullPointerException if the collection or any of its\n * elements are {@code null}\n * @throws UnsupportedOperationException if no default mapped value\n * for additions was provided\n */\n public boolean addAll(Collection c) {\n boolean added = false;\n V v;\n if ((v = value) == null)\n throw new UnsupportedOperationException();\n for (K e : c) {\n if (map.putVal(e, v, true) == null)\n added = true;\n }\n return added;\n }\n\n public int hashCode() {\n int h = 0;\n for (K e : this) h += e.hashCode();\n return h;\n }\n\n public boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new KeySpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.key);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Collection} of\n * values, in which additions are disabled. This class cannot be\n * directly instantiated. See {@link #values()}.\n */\n static final class ValuesView extends CollectionView implements Collection, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n ValuesView(ConcurrentHashMap map) {\n super(map);\n }\n\n public final boolean contains(Object o) {\n return map.containsValue(o);\n }\n\n public final boolean remove(Object o) {\n if (o != null) {\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (o.equals(it.next())) {\n it.remove();\n return true;\n }\n }\n }\n return false;\n }\n\n public final Iterator iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueIterator(t, f, 0, f, m);\n }\n\n public final boolean add(V e) {\n throw new UnsupportedOperationException();\n }\n\n public final boolean addAll(Collection c) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean removeAll(Collection c) {\n if (c == null)\n throw new NullPointerException();\n boolean modified = false;\n for (Iterator it = iterator(); it.hasNext(); ) {\n if (c.contains(it.next())) {\n it.remove();\n modified = true;\n }\n }\n return modified;\n }\n\n public boolean removeIf(Predicate filter) {\n return map.removeValueIf(filter);\n }\n\n public Spliterator spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new ValueSpliterator(t, f, 0, f, n < 0L ? 0L : n);\n }\n\n public void forEach(Consumer action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(p.val);\n }\n }\n }\n\n /**\n * A view of a ConcurrentHashMap as a {@link Set} of (key, value)\n * entries. This class cannot be directly instantiated. See\n * {@link #entrySet()}.\n */\n static final class EntrySetView extends CollectionView> implements Set>, java.io.Serializable {\n\n private static final long serialVersionUID = 2249069246763182397L;\n\n EntrySetView(ConcurrentHashMap map) {\n super(map);\n }\n\n public boolean contains(Object o) {\n Object k, v, r;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (r = map.get(k)) != null && (v = e.getValue()) != null && (v == r || v.equals(r)));\n }\n\n public boolean remove(Object o) {\n Object k, v;\n Map.Entry e;\n return ((o instanceof Map.Entry) && (k = (e = (Map.Entry) o).getKey()) != null && (v = e.getValue()) != null && map.remove(k, v));\n }\n\n /**\n * @return an iterator over the entries of the backing map\n */\n public Iterator> iterator() {\n ConcurrentHashMap m = map;\n Node[] t;\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntryIterator(t, f, 0, f, m);\n }\n\n public boolean add(Entry e) {\n return map.putVal(e.getKey(), e.getValue(), false) == null;\n }\n\n public boolean addAll(Collection> c) {\n boolean added = false;\n for (Entry e : c) {\n if (add(e))\n added = true;\n }\n return added;\n }\n\n public boolean removeIf(Predicate> filter) {\n return map.removeEntryIf(filter);\n }\n\n public final int hashCode() {\n int h = 0;\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) {\n h += p.hashCode();\n }\n }\n return h;\n }\n\n public final boolean equals(Object o) {\n Set c;\n return ((o instanceof Set) && ((c = (Set) o) == this || (containsAll(c) && c.containsAll(this))));\n }\n\n public Spliterator> spliterator() {\n Node[] t;\n ConcurrentHashMap m = map;\n long n = m.sumCount();\n int f = (t = m.table) == null ? 0 : t.length;\n return new EntrySpliterator(t, f, 0, f, n < 0L ? 0L : n, m);\n }\n\n public void forEach(Consumer> action) {\n if (action == null)\n throw new NullPointerException();\n Node[] t;\n if ((t = map.table) != null) {\n Traverser it = new Traverser(t, t.length, 0, t.length);\n for (Node p; (p = it.advance()) != null; ) action.accept(new MapEntry(p.key, p.val, map));\n }\n }\n }\n\n /**\n * Base class for bulk tasks. Repeats some fields and code from\n * class Traverser, because we need to subclass CountedCompleter.\n */\n @SuppressWarnings(\"serial\")\n abstract static class BulkTask extends CountedCompleter {\n\n // same as Traverser\n Node[] tab;\n\n Node next;\n\n TableStack stack, spare;\n\n int index;\n\n int baseIndex;\n\n int baseLimit;\n\n final int baseSize;\n\n // split control\n int batch;\n\n BulkTask(BulkTask par, int b, int i, int f, Node[] t) {\n super(par);\n this.batch = b;\n this.index = this.baseIndex = i;\n if ((this.tab = t) == null)\n this.baseSize = this.baseLimit = 0;\n else if (par == null)\n this.baseSize = this.baseLimit = t.length;\n else {\n this.baseLimit = f;\n this.baseSize = par.baseSize;\n }\n }\n\n /**\n * Same as Traverser version.\n */\n final Node advance() {\n Node e;\n if ((e = next) != null)\n e = e.next;\n for (; ; ) {\n Node[] t;\n int i, n;\n if (e != null)\n return next = e;\n if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0)\n return next = null;\n if ((e = tabAt(t, i)) != null && e.hash < 0) {\n if (e instanceof ForwardingNode) {\n tab = ((ForwardingNode) e).nextTable;\n e = null;\n pushState(t, i, n);\n continue;\n } else if (e instanceof TreeBin)\n e = ((TreeBin) e).first;\n else\n e = null;\n }\n if (stack != null)\n recoverState(n);\n else if ((index = i + baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n private void pushState(Node[] t, int i, int n) {\n TableStack s = spare;\n if (s != null)\n spare = s.next;\n else\n s = new TableStack();\n s.tab = t;\n s.length = n;\n s.index = i;\n s.next = stack;\n stack = s;\n }\n\n private void recoverState(int n) {\n TableStack s;\n int len;\n while ((s = stack) != null && (index += (len = s.length)) >= n) {\n n = len;\n index = s.index;\n tab = s.tab;\n s.tab = null;\n TableStack next = s.next;\n // save for reuse\n s.next = spare;\n stack = next;\n spare = s;\n }\n if (s == null && (index += baseSize) >= n)\n index = ++baseIndex;\n }\n }\n\n /*\n * Task classes. Coded in a regular but ugly format/style to\n * simplify checks that each variant differs in the right way from\n * others. The null screenings exist because compilers cannot tell\n * that we've already null-checked task arguments, so we force\n * simplest hoisted bypass to help avoid convoluted traps.\n */\n @SuppressWarnings(\"serial\")\n static final class ForEachKeyTask extends BulkTask {\n\n final Consumer action;\n\n ForEachKeyTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachValueTask extends BulkTask {\n\n final Consumer action;\n\n ForEachValueTask(BulkTask p, int b, int i, int f, Node[] t, Consumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachValueTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachEntryTask extends BulkTask {\n\n final Consumer> action;\n\n ForEachEntryTask(BulkTask p, int b, int i, int f, Node[] t, Consumer> action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final Consumer> action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachMappingTask extends BulkTask {\n\n final BiConsumer action;\n\n ForEachMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiConsumer action) {\n super(p, b, i, f, t);\n this.action = action;\n }\n\n public final void compute() {\n final BiConsumer action;\n if ((action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, action).fork();\n }\n for (Node p; (p = advance()) != null; ) action.accept(p.key, p.val);\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedKeyTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedKeyTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedKeyTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedValueTask extends BulkTask {\n\n final Function transformer;\n\n final Consumer action;\n\n ForEachTransformedValueTask(BulkTask p, int b, int i, int f, Node[] t, Function transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedValueTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedEntryTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final Consumer action;\n\n ForEachTransformedEntryTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedEntryTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ForEachTransformedMappingTask extends BulkTask {\n\n final BiFunction transformer;\n\n final Consumer action;\n\n ForEachTransformedMappingTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction transformer, Consumer action) {\n super(p, b, i, f, t);\n this.transformer = transformer;\n this.action = action;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final Consumer action;\n if ((transformer = this.transformer) != null && (action = this.action) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n new ForEachTransformedMappingTask(this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork();\n }\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n action.accept(u);\n }\n propagateCompletion();\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchKeysTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchKeysTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchValuesTask extends BulkTask {\n\n final Function searchFunction;\n\n final AtomicReference result;\n\n SearchValuesTask(BulkTask p, int b, int i, int f, Node[] t, Function searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchEntriesTask extends BulkTask {\n\n final Function, ? extends U> searchFunction;\n\n final AtomicReference result;\n\n SearchEntriesTask(BulkTask p, int b, int i, int f, Node[] t, Function, ? extends U> searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final Function, ? extends U> searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n return;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class SearchMappingsTask extends BulkTask {\n\n final BiFunction searchFunction;\n\n final AtomicReference result;\n\n SearchMappingsTask(BulkTask p, int b, int i, int f, Node[] t, BiFunction searchFunction, AtomicReference result) {\n super(p, b, i, f, t);\n this.searchFunction = searchFunction;\n this.result = result;\n }\n\n public final U getRawResult() {\n return result.get();\n }\n\n public final void compute() {\n final BiFunction searchFunction;\n final AtomicReference result;\n if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n if (result.get() != null)\n return;\n addToPendingCount(1);\n new SearchMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork();\n }\n while (result.get() == null) {\n U u;\n Node p;\n if ((p = advance()) == null) {\n propagateCompletion();\n break;\n }\n if ((u = searchFunction.apply(p.key, p.val)) != null) {\n if (result.compareAndSet(null, u))\n quietlyCompleteRoot();\n break;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceKeysTask extends BulkTask {\n\n final BiFunction reducer;\n\n K result;\n\n ReduceKeysTask rights, nextRight;\n\n ReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, ReduceKeysTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final K getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n K r = null;\n for (Node p; (p = advance()) != null; ) {\n K u = p.key;\n r = (r == null) ? u : u == null ? r : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceKeysTask t = (ReduceKeysTask) c, s = t.rights;\n while (s != null) {\n K tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceValuesTask extends BulkTask {\n\n final BiFunction reducer;\n\n V result;\n\n ReduceValuesTask rights, nextRight;\n\n ReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceValuesTask nextRight, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final V getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n V r = null;\n for (Node p; (p = advance()) != null; ) {\n V v = p.val;\n r = (r == null) ? v : reducer.apply(r, v);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceValuesTask t = (ReduceValuesTask) c, s = t.rights;\n while (s != null) {\n V tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class ReduceEntriesTask extends BulkTask> {\n\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n\n Map.Entry result;\n\n ReduceEntriesTask rights, nextRight;\n\n ReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, ReduceEntriesTask nextRight, BiFunction, Map.Entry, ? extends Map.Entry> reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.reducer = reducer;\n }\n\n public final Map.Entry getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction, Map.Entry, ? extends Map.Entry> reducer;\n if ((reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new ReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork();\n }\n Map.Entry r = null;\n for (Node p; (p = advance()) != null; ) r = (r == null) ? p : reducer.apply(r, p);\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n ReduceEntriesTask t = (ReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n Map.Entry tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceKeysTask rights, nextRight;\n\n MapReduceKeysTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysTask t = (MapReduceKeysTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesTask extends BulkTask {\n\n final Function transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceValuesTask rights, nextRight;\n\n MapReduceValuesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesTask nextRight, Function transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesTask t = (MapReduceValuesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesTask extends BulkTask {\n\n final Function, ? extends U> transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceEntriesTask rights, nextRight;\n\n MapReduceEntriesTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesTask nextRight, Function, ? extends U> transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final Function, ? extends U> transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesTask t = (MapReduceEntriesTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsTask extends BulkTask {\n\n final BiFunction transformer;\n\n final BiFunction reducer;\n\n U result;\n\n MapReduceMappingsTask rights, nextRight;\n\n MapReduceMappingsTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsTask nextRight, BiFunction transformer, BiFunction reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.reducer = reducer;\n }\n\n public final U getRawResult() {\n return result;\n }\n\n public final void compute() {\n final BiFunction transformer;\n final BiFunction reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork();\n }\n U r = null;\n for (Node p; (p = advance()) != null; ) {\n U u;\n if ((u = transformer.apply(p.key, p.val)) != null)\n r = (r == null) ? u : reducer.apply(r, u);\n }\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsTask t = (MapReduceMappingsTask) c, s = t.rights;\n while (s != null) {\n U tr, sr;\n if ((sr = s.result) != null)\n t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr));\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceKeysToDoubleTask rights, nextRight;\n\n MapReduceKeysToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToDoubleTask t = (MapReduceKeysToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceValuesToDoubleTask rights, nextRight;\n\n MapReduceValuesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToDoubleTask nextRight, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToDoubleTask t = (MapReduceValuesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToDoubleTask extends BulkTask {\n\n final ToDoubleFunction> transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceEntriesToDoubleTask rights, nextRight;\n\n MapReduceEntriesToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToDoubleTask nextRight, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleFunction> transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToDoubleTask t = (MapReduceEntriesToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToDoubleTask extends BulkTask {\n\n final ToDoubleBiFunction transformer;\n\n final DoubleBinaryOperator reducer;\n\n final double basis;\n\n double result;\n\n MapReduceMappingsToDoubleTask rights, nextRight;\n\n MapReduceMappingsToDoubleTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToDoubleTask nextRight, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Double getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToDoubleBiFunction transformer;\n final DoubleBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n double r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToDoubleTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToDoubleTask t = (MapReduceMappingsToDoubleTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsDouble(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceKeysToLongTask rights, nextRight;\n\n MapReduceKeysToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToLongTask t = (MapReduceKeysToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToLongTask extends BulkTask {\n\n final ToLongFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceValuesToLongTask rights, nextRight;\n\n MapReduceValuesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToLongTask nextRight, ToLongFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToLongTask t = (MapReduceValuesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToLongTask extends BulkTask {\n\n final ToLongFunction> transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceEntriesToLongTask rights, nextRight;\n\n MapReduceEntriesToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToLongTask nextRight, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongFunction> transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToLongTask t = (MapReduceEntriesToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToLongTask extends BulkTask {\n\n final ToLongBiFunction transformer;\n\n final LongBinaryOperator reducer;\n\n final long basis;\n\n long result;\n\n MapReduceMappingsToLongTask rights, nextRight;\n\n MapReduceMappingsToLongTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToLongTask nextRight, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Long getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToLongBiFunction transformer;\n final LongBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n long r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToLongTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToLongTask t = (MapReduceMappingsToLongTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsLong(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceKeysToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceKeysToIntTask rights, nextRight;\n\n MapReduceKeysToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceKeysToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceKeysToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceKeysToIntTask t = (MapReduceKeysToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceValuesToIntTask extends BulkTask {\n\n final ToIntFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceValuesToIntTask rights, nextRight;\n\n MapReduceValuesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceValuesToIntTask nextRight, ToIntFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceValuesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceValuesToIntTask t = (MapReduceValuesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceEntriesToIntTask extends BulkTask {\n\n final ToIntFunction> transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceEntriesToIntTask rights, nextRight;\n\n MapReduceEntriesToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceEntriesToIntTask nextRight, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntFunction> transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceEntriesToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceEntriesToIntTask t = (MapReduceEntriesToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n @SuppressWarnings(\"serial\")\n static final class MapReduceMappingsToIntTask extends BulkTask {\n\n final ToIntBiFunction transformer;\n\n final IntBinaryOperator reducer;\n\n final int basis;\n\n int result;\n\n MapReduceMappingsToIntTask rights, nextRight;\n\n MapReduceMappingsToIntTask(BulkTask p, int b, int i, int f, Node[] t, MapReduceMappingsToIntTask nextRight, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) {\n super(p, b, i, f, t);\n this.nextRight = nextRight;\n this.transformer = transformer;\n this.basis = basis;\n this.reducer = reducer;\n }\n\n public final Integer getRawResult() {\n return result;\n }\n\n public final void compute() {\n final ToIntBiFunction transformer;\n final IntBinaryOperator reducer;\n if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) {\n int r = this.basis;\n for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i; ) {\n addToPendingCount(1);\n (rights = new MapReduceMappingsToIntTask(this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork();\n }\n for (Node p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));\n result = r;\n CountedCompleter c;\n for (c = firstComplete(); c != null; c = c.nextComplete()) {\n @SuppressWarnings(\"unchecked\")\n MapReduceMappingsToIntTask t = (MapReduceMappingsToIntTask) c, s = t.rights;\n while (s != null) {\n t.result = reducer.applyAsInt(t.result, s.result);\n s = t.rights = s.nextRight;\n }\n }\n }\n }\n }\n\n // Unsafe mechanics\n private static final Unsafe U = Unsafe.getUnsafe();\n\n private static final long SIZECTL = U.objectFieldOffset(ConcurrentHashMap.class, \"sizeCtl\");\n\n private static final long TRANSFERINDEX = U.objectFieldOffset(ConcurrentHashMap.class, \"transferIndex\");\n\n private static final long BASECOUNT = U.objectFieldOffset(ConcurrentHashMap.class, \"baseCount\");\n\n private static final long CELLSBUSY = U.objectFieldOffset(ConcurrentHashMap.class, \"cellsBusy\");\n\n private static final long CELLVALUE = U.objectFieldOffset(CounterCell.class, \"value\");\n\n private static final int ABASE = U.arrayBaseOffset(Node[].class);\n\n private static final int ASHIFT;\n\n static {\n int scale = U.arrayIndexScale(Node[].class);\n if ((scale & (scale - 1)) != 0)\n throw new ExceptionInInitializerError(\"array index scale not a power of two\");\n ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);\n // Reduce the risk of rare disastrous classloading in first call to\n Class ensureLoaded = LockSupport.class;\n // Eager class load observed to help JIT during startup\n ensureLoaded = ReservationNode.class;\n }\n}\n"} {"task_id": "Java_2829", "language": "Java", "task_type": "method_signature", "source_file": "java/github/fitzyyf/mybatis-pagination/src/main/java/org/mybatis/pagination/dialect/db/HSQLDialect.java", "mask_start_position": 254, "mask_end_position": 299, "canonical_solution": "@Override\n public boolean supportsLimit() ", "pre_mask_code": "package org.mybatis.pagination.dialect.db;\n\nimport org.mybatis.pagination.dialect.Dialect;\n\n/**\n * Dialect for HSQLDB\n *\n * @author poplar.yfyang\n * @version 1.0 2010-10-10 下午12:31\n * @since JDK 1.5\n */\npublic class HSQLDialect implements Dialect {\n\n ", "post_mask_code": "{\n return true;\n }\n\n @Override\n public String getLimitString(String sql, int offset, int limit) {\n return getLimitString(sql, offset, Integer.toString(offset), Integer.toString(limit));\n }\n\n /**\n * 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.\n *

\n     * 如mysql\n     * dialect.getLimitString(\"select * from user\", 12, \":offset\",0,\":limit\") 将返回\n     * select * from user limit :offset,:limit\n     *\n     * select limit :offset,:limit * from user\n     * 
\n *\n * @param sql 实际SQL语句\n * @param offset 分页开始纪录条数\n * @param offsetPlaceholder 分页开始纪录条数-占位符号\n * @param limitPlaceholder 分页纪录条数占位符号\n * @return 包含占位符的分页sql\n */\n public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {\n boolean hasOffset = offset > 0;\n return new StringBuffer(sql.length() + 10).append(sql).insert(sql.toLowerCase().indexOf(\"select\") + 6, hasOffset ? \" limit \" + offsetPlaceholder + \" \" + limitPlaceholder : \" top \" + limitPlaceholder).toString();\n }\n\n @Override\n public String getCountString(String sql) {\n return \"select count(*) from (\" + sql + \") as tmp_count\";\n }\n}\n"} {"task_id": "Java_2830", "language": "Java", "task_type": "method_body", "source_file": "java/github/fitzyyf/mybatis-pagination/src/main/java/org/mybatis/pagination/dialect/db/HSQLDialect.java", "mask_start_position": 1126, "mask_end_position": 1393, "canonical_solution": "{\n boolean hasOffset = offset > 0;\n return new StringBuffer(sql.length() + 10).append(sql).insert(sql.toLowerCase().indexOf(\"select\") + 6, hasOffset ? \" limit \" + offsetPlaceholder + \" \" + limitPlaceholder : \" top \" + limitPlaceholder).toString();\n }", "pre_mask_code": "package org.mybatis.pagination.dialect.db;\n\nimport org.mybatis.pagination.dialect.Dialect;\n\n/**\n * Dialect for HSQLDB\n *\n * @author poplar.yfyang\n * @version 1.0 2010-10-10 下午12:31\n * @since JDK 1.5\n */\npublic class HSQLDialect implements Dialect {\n\n @Override\n public boolean supportsLimit() {\n return true;\n }\n\n @Override\n public String getLimitString(String sql, int offset, int limit) {\n return getLimitString(sql, offset, Integer.toString(offset), Integer.toString(limit));\n }\n\n /**\n * 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.\n *
\n     * 如mysql\n     * dialect.getLimitString(\"select * from user\", 12, \":offset\",0,\":limit\") 将返回\n     * select * from user limit :offset,:limit\n     *\n     * select limit :offset,:limit * from user\n     * 
\n *\n * @param sql 实际SQL语句\n * @param offset 分页开始纪录条数\n * @param offsetPlaceholder 分页开始纪录条数-占位符号\n * @param limitPlaceholder 分页纪录条数占位符号\n * @return 包含占位符的分页sql\n */\n public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) ", "post_mask_code": "\n\n @Override\n public String getCountString(String sql) {\n return \"select count(*) from (\" + sql + \") as tmp_count\";\n }\n}\n"} {"task_id": "Java_2831", "language": "Java", "task_type": "single_line", "source_file": "java/github/fitzyyf/mybatis-pagination/src/main/java/org/mybatis/pagination/dialect/db/HSQLDialect.java", "mask_start_position": 1176, "mask_end_position": 1387, "canonical_solution": "return new StringBuffer(sql.length() + 10).append(sql).insert(sql.toLowerCase().indexOf(\"select\") + 6, hasOffset ? \" limit \" + offsetPlaceholder + \" \" + limitPlaceholder : \" top \" + limitPlaceholder).toString();", "pre_mask_code": "package org.mybatis.pagination.dialect.db;\n\nimport org.mybatis.pagination.dialect.Dialect;\n\n/**\n * Dialect for HSQLDB\n *\n * @author poplar.yfyang\n * @version 1.0 2010-10-10 下午12:31\n * @since JDK 1.5\n */\npublic class HSQLDialect implements Dialect {\n\n @Override\n public boolean supportsLimit() {\n return true;\n }\n\n @Override\n public String getLimitString(String sql, int offset, int limit) {\n return getLimitString(sql, offset, Integer.toString(offset), Integer.toString(limit));\n }\n\n /**\n * 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.\n *
\n     * 如mysql\n     * dialect.getLimitString(\"select * from user\", 12, \":offset\",0,\":limit\") 将返回\n     * select * from user limit :offset,:limit\n     *\n     * select limit :offset,:limit * from user\n     * 
\n *\n * @param sql 实际SQL语句\n * @param offset 分页开始纪录条数\n * @param offsetPlaceholder 分页开始纪录条数-占位符号\n * @param limitPlaceholder 分页纪录条数占位符号\n * @return 包含占位符的分页sql\n */\n public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {\n boolean hasOffset = offset > 0;\n ", "post_mask_code": "\n }\n\n @Override\n public String getCountString(String sql) {\n return \"select count(*) from (\" + sql + \") as tmp_count\";\n }\n}\n"} {"task_id": "Java_2832", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/fitzyyf/mybatis-pagination/src/main/java/org/mybatis/pagination/dialect/db/HSQLDialect.java", "mask_start_position": 1022, "mask_end_position": 1393, "canonical_solution": "public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {\n boolean hasOffset = offset > 0;\n return new StringBuffer(sql.length() + 10).append(sql).insert(sql.toLowerCase().indexOf(\"select\") + 6, hasOffset ? \" limit \" + offsetPlaceholder + \" \" + limitPlaceholder : \" top \" + limitPlaceholder).toString();\n }", "pre_mask_code": "package org.mybatis.pagination.dialect.db;\n\nimport org.mybatis.pagination.dialect.Dialect;\n\n/**\n * Dialect for HSQLDB\n *\n * @author poplar.yfyang\n * @version 1.0 2010-10-10 下午12:31\n * @since JDK 1.5\n */\npublic class HSQLDialect implements Dialect {\n\n @Override\n public boolean supportsLimit() {\n return true;\n }\n\n @Override\n public String getLimitString(String sql, int offset, int limit) {\n return getLimitString(sql, offset, Integer.toString(offset), Integer.toString(limit));\n }\n\n /**\n * 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.\n *
\n     * 如mysql\n     * dialect.getLimitString(\"select * from user\", 12, \":offset\",0,\":limit\") 将返回\n     * select * from user limit :offset,:limit\n     *\n     * select limit :offset,:limit * from user\n     * 
\n *\n * @param sql 实际SQL语句\n * @param offset 分页开始纪录条数\n * @param offsetPlaceholder 分页开始纪录条数-占位符号\n * @param limitPlaceholder 分页纪录条数占位符号\n * @return 包含占位符的分页sql\n */\n ", "post_mask_code": "\n\n @Override\n public String getCountString(String sql) {\n return \"select count(*) from (\" + sql + \") as tmp_count\";\n }\n}\n"} {"task_id": "Java_2833", "language": "Java", "task_type": "method_signature", "source_file": "java/github/hanlyjiang/AndroidDocumentViewer/lib_fileviewer/src/main/java/com/hanlyjiang/library/fileviewer/wps/WPSOpenUtils.java", "mask_start_position": 1311, "mask_end_position": 1435, "canonical_solution": "public static boolean viewOrEditFileWithWPS(@NonNull Fragment fragment, String filePath, boolean readOnly, int requestCode) ", "pre_mask_code": "package com.hanlyjiang.library.fileviewer.wps;\n\nimport android.content.ActivityNotFoundException;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.content.pm.ResolveInfo;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.v4.app.Fragment;\nimport android.util.Log;\nimport com.hanlyjiang.library.utils.AndroidUtils;\nimport com.hanlyjiang.library.utils.FileViewerUtils;\nimport java.io.File;\nimport java.util.List;\n\n/**\n * WPS打开文件工具\n *\n * @author hanlyjiang on 2018/3/22-13:49.\n * @version 1.0\n */\npublic class WPSOpenUtils {\n\n /**\n * 用WPS 打开应用,注意此种方法无法获取\n *\n * @param filePath 设置好数据了类型的intent\n * @param context Context 对象\n * @return\n */\n public static boolean viewOrEditFileWithWPS(@NonNull Context context, String filePath, boolean readOnly) {\n return viewOrEditFileWithWPS(new ContextStartWrapper(context), filePath, readOnly, 0);\n }\n\n /**\n * 用WPS 打开文档\n *\n * @param fragment\n * @param filePath 设置好数据了类型的intent\n * @param readOnly true - 以只读模式打开文档通过StartActivity启动); false - 以编辑模式打开文档(通过StartActivityForResult启动)\n * @param requestCode 指定通过StartActivityForResult启动时的requestCode\n * @return\n */\n ", "post_mask_code": "{\n return viewOrEditFileWithWPS(new FragmentStartWrapper(fragment), filePath, readOnly, requestCode);\n }\n\n /**\n * 用WPS 打开应用\n *\n * @param filePath 设置好数据了类型的intent\n * @param wrapper ActivityStarterWrapper 对象\n * @return\n */\n protected static boolean viewOrEditFileWithWPS(@NonNull ActivityStarterWrapper wrapper, String filePath, boolean readOnly, int requestCode) {\n Intent intent = new Intent();\n File file = new File(filePath);\n if (!file.isFile()) {\n AndroidUtils.showToast(wrapper.getContext(), \"文件不存在\");\n return false;\n }\n intent.setDataAndType(Uri.fromFile(file), FileViewerUtils.getMimeType(file));\n return doRealWPSViewOrEdit(wrapper, intent, readOnly, requestCode);\n }\n\n /**\n * 用WPS 打开应用\n *\n * @param context Context 对象\n * @param intent 设置好数据了类型的intent\n * @return\n */\n protected static boolean doRealWPSViewOrEdit(@NonNull ActivityStarterWrapper context, @NonNull Intent intent, boolean readOnly, int requestCode) {\n Bundle bundle = new Bundle();\n // 关闭时是否发送广播\n bundle.putBoolean(WPSModel.SEND_CLOSE_BROAD, true);\n // 保存时是否发送广播\n bundle.putBoolean(WPSModel.SEND_SAVE_BROAD, true);\n // 第三方应用的包名,用于对改应用合法性的验证\n bundle.putString(WPSModel.THIRD_PACKAGE, context.getPackageName());\n if (readOnly) {\n // 打开模式\n bundle.putString(WPSModel.OPEN_MODE, WPSModel.OpenMode.READ_ONLY);\n } else {\n // 打开模式\n bundle.putString(WPSModel.OPEN_MODE, WPSModel.OpenMode.NORMAL);\n // 修订模式\n bundle.putBoolean(WPSModel.ENTER_REVISE_MODE, true);\n }\n // 清除打开记录\n bundle.putBoolean(WPSModel.CLEAR_TRACE, true);\n intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);\n intent.setAction(Intent.ACTION_VIEW);\n intent.setClassName(WPSModel.PackageName.NORMAL, WPSModel.ClassName.NORMAL);\n intent.putExtras(bundle);\n try {\n if (readOnly) {\n context.startActivity(Intent.createChooser(intent, \"请选择WPS打开文件\"));\n } else {\n context.startActivityForResult(Intent.createChooser(intent, \"请选择WPS打开应用\"), requestCode);\n }\n } catch (ActivityNotFoundException exception) {\n Log.d(\"WPSOpenUtils\", exception.getMessage());\n exception.printStackTrace();\n return false;\n }\n return true;\n }\n\n /**\n * 检测是否有安装 WPS\n *\n * @param context Context\n * @return\n */\n public static boolean checkWPSInstallation(Context context) {\n PackageManager packageManager1 = context.getPackageManager();\n Intent intent = new Intent();\n intent.setClassName(WPSModel.PackageName.NORMAL, WPSModel.ClassName.NORMAL);\n List resolveInfos = packageManager1.queryIntentActivities(intent, PackageManager.MATCH_ALL);\n if (resolveInfos == null || resolveInfos.size() == 0) {\n return false;\n }\n boolean found = false;\n for (ResolveInfo info : resolveInfos) {\n if (info.activityInfo.packageName.toLowerCase().equalsIgnoreCase(WPSModel.PackageName.NORMAL) || info.activityInfo.name.toLowerCase().equalsIgnoreCase(WPSModel.ClassName.NORMAL)) {\n found = true;\n break;\n }\n }\n return found;\n }\n\n abstract static class ActivityStarterWrapper {\n\n protected Context context;\n\n public ActivityStarterWrapper(Context context) {\n this.context = context;\n }\n\n abstract String getPackageName();\n\n abstract void startActivityForResult(Intent intent, int requestCode);\n\n abstract void startActivity(Intent intent);\n\n public Context getContext() {\n return context;\n }\n }\n\n protected static class ContextStartWrapper extends ActivityStarterWrapper {\n\n public ContextStartWrapper(Context context) {\n super(context);\n }\n\n @Override\n String getPackageName() {\n return context.getPackageName();\n }\n\n @Override\n void startActivityForResult(Intent intent, int requestCode) {\n context.startActivity(intent);\n }\n\n @Override\n void startActivity(Intent intent) {\n context.startActivity(intent);\n }\n }\n\n protected static class FragmentStartWrapper extends ActivityStarterWrapper {\n\n Fragment fragment;\n\n public FragmentStartWrapper(Fragment fragment) {\n super(fragment.getContext());\n this.fragment = fragment;\n }\n\n @Override\n String getPackageName() {\n return (fragment.getContext() == null) ? \"\" : fragment.getContext().getPackageName();\n }\n\n @Override\n void startActivityForResult(Intent intent, int requestCode) {\n fragment.startActivityForResult(intent, requestCode);\n }\n\n @Override\n void startActivity(Intent intent) {\n fragment.startActivity(intent);\n }\n }\n}\n"} {"task_id": "Java_2834", "language": "Java", "task_type": "method_body", "source_file": "java/github/hanlyjiang/AndroidDocumentViewer/lib_fileviewer/src/main/java/com/hanlyjiang/library/fileviewer/wps/WPSOpenUtils.java", "mask_start_position": 1435, "mask_end_position": 1549, "canonical_solution": "{\n return viewOrEditFileWithWPS(new FragmentStartWrapper(fragment), filePath, readOnly, requestCode);\n }", "pre_mask_code": "package com.hanlyjiang.library.fileviewer.wps;\n\nimport android.content.ActivityNotFoundException;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.content.pm.ResolveInfo;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.v4.app.Fragment;\nimport android.util.Log;\nimport com.hanlyjiang.library.utils.AndroidUtils;\nimport com.hanlyjiang.library.utils.FileViewerUtils;\nimport java.io.File;\nimport java.util.List;\n\n/**\n * WPS打开文件工具\n *\n * @author hanlyjiang on 2018/3/22-13:49.\n * @version 1.0\n */\npublic class WPSOpenUtils {\n\n /**\n * 用WPS 打开应用,注意此种方法无法获取\n *\n * @param filePath 设置好数据了类型的intent\n * @param context Context 对象\n * @return\n */\n public static boolean viewOrEditFileWithWPS(@NonNull Context context, String filePath, boolean readOnly) {\n return viewOrEditFileWithWPS(new ContextStartWrapper(context), filePath, readOnly, 0);\n }\n\n /**\n * 用WPS 打开文档\n *\n * @param fragment\n * @param filePath 设置好数据了类型的intent\n * @param readOnly true - 以只读模式打开文档通过StartActivity启动); false - 以编辑模式打开文档(通过StartActivityForResult启动)\n * @param requestCode 指定通过StartActivityForResult启动时的requestCode\n * @return\n */\n public static boolean viewOrEditFileWithWPS(@NonNull Fragment fragment, String filePath, boolean readOnly, int requestCode) ", "post_mask_code": "\n\n /**\n * 用WPS 打开应用\n *\n * @param filePath 设置好数据了类型的intent\n * @param wrapper ActivityStarterWrapper 对象\n * @return\n */\n protected static boolean viewOrEditFileWithWPS(@NonNull ActivityStarterWrapper wrapper, String filePath, boolean readOnly, int requestCode) {\n Intent intent = new Intent();\n File file = new File(filePath);\n if (!file.isFile()) {\n AndroidUtils.showToast(wrapper.getContext(), \"文件不存在\");\n return false;\n }\n intent.setDataAndType(Uri.fromFile(file), FileViewerUtils.getMimeType(file));\n return doRealWPSViewOrEdit(wrapper, intent, readOnly, requestCode);\n }\n\n /**\n * 用WPS 打开应用\n *\n * @param context Context 对象\n * @param intent 设置好数据了类型的intent\n * @return\n */\n protected static boolean doRealWPSViewOrEdit(@NonNull ActivityStarterWrapper context, @NonNull Intent intent, boolean readOnly, int requestCode) {\n Bundle bundle = new Bundle();\n // 关闭时是否发送广播\n bundle.putBoolean(WPSModel.SEND_CLOSE_BROAD, true);\n // 保存时是否发送广播\n bundle.putBoolean(WPSModel.SEND_SAVE_BROAD, true);\n // 第三方应用的包名,用于对改应用合法性的验证\n bundle.putString(WPSModel.THIRD_PACKAGE, context.getPackageName());\n if (readOnly) {\n // 打开模式\n bundle.putString(WPSModel.OPEN_MODE, WPSModel.OpenMode.READ_ONLY);\n } else {\n // 打开模式\n bundle.putString(WPSModel.OPEN_MODE, WPSModel.OpenMode.NORMAL);\n // 修订模式\n bundle.putBoolean(WPSModel.ENTER_REVISE_MODE, true);\n }\n // 清除打开记录\n bundle.putBoolean(WPSModel.CLEAR_TRACE, true);\n intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);\n intent.setAction(Intent.ACTION_VIEW);\n intent.setClassName(WPSModel.PackageName.NORMAL, WPSModel.ClassName.NORMAL);\n intent.putExtras(bundle);\n try {\n if (readOnly) {\n context.startActivity(Intent.createChooser(intent, \"请选择WPS打开文件\"));\n } else {\n context.startActivityForResult(Intent.createChooser(intent, \"请选择WPS打开应用\"), requestCode);\n }\n } catch (ActivityNotFoundException exception) {\n Log.d(\"WPSOpenUtils\", exception.getMessage());\n exception.printStackTrace();\n return false;\n }\n return true;\n }\n\n /**\n * 检测是否有安装 WPS\n *\n * @param context Context\n * @return\n */\n public static boolean checkWPSInstallation(Context context) {\n PackageManager packageManager1 = context.getPackageManager();\n Intent intent = new Intent();\n intent.setClassName(WPSModel.PackageName.NORMAL, WPSModel.ClassName.NORMAL);\n List resolveInfos = packageManager1.queryIntentActivities(intent, PackageManager.MATCH_ALL);\n if (resolveInfos == null || resolveInfos.size() == 0) {\n return false;\n }\n boolean found = false;\n for (ResolveInfo info : resolveInfos) {\n if (info.activityInfo.packageName.toLowerCase().equalsIgnoreCase(WPSModel.PackageName.NORMAL) || info.activityInfo.name.toLowerCase().equalsIgnoreCase(WPSModel.ClassName.NORMAL)) {\n found = true;\n break;\n }\n }\n return found;\n }\n\n abstract static class ActivityStarterWrapper {\n\n protected Context context;\n\n public ActivityStarterWrapper(Context context) {\n this.context = context;\n }\n\n abstract String getPackageName();\n\n abstract void startActivityForResult(Intent intent, int requestCode);\n\n abstract void startActivity(Intent intent);\n\n public Context getContext() {\n return context;\n }\n }\n\n protected static class ContextStartWrapper extends ActivityStarterWrapper {\n\n public ContextStartWrapper(Context context) {\n super(context);\n }\n\n @Override\n String getPackageName() {\n return context.getPackageName();\n }\n\n @Override\n void startActivityForResult(Intent intent, int requestCode) {\n context.startActivity(intent);\n }\n\n @Override\n void startActivity(Intent intent) {\n context.startActivity(intent);\n }\n }\n\n protected static class FragmentStartWrapper extends ActivityStarterWrapper {\n\n Fragment fragment;\n\n public FragmentStartWrapper(Fragment fragment) {\n super(fragment.getContext());\n this.fragment = fragment;\n }\n\n @Override\n String getPackageName() {\n return (fragment.getContext() == null) ? \"\" : fragment.getContext().getPackageName();\n }\n\n @Override\n void startActivityForResult(Intent intent, int requestCode) {\n fragment.startActivityForResult(intent, requestCode);\n }\n\n @Override\n void startActivity(Intent intent) {\n fragment.startActivity(intent);\n }\n }\n}\n"} {"task_id": "Java_2835", "language": "Java", "task_type": "single_line", "source_file": "java/github/hanlyjiang/AndroidDocumentViewer/lib_fileviewer/src/main/java/com/hanlyjiang/library/fileviewer/wps/WPSOpenUtils.java", "mask_start_position": 1861, "mask_end_position": 1877, "canonical_solution": " = new Intent();", "pre_mask_code": "package com.hanlyjiang.library.fileviewer.wps;\n\nimport android.content.ActivityNotFoundException;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.content.pm.ResolveInfo;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.v4.app.Fragment;\nimport android.util.Log;\nimport com.hanlyjiang.library.utils.AndroidUtils;\nimport com.hanlyjiang.library.utils.FileViewerUtils;\nimport java.io.File;\nimport java.util.List;\n\n/**\n * WPS打开文件工具\n *\n * @author hanlyjiang on 2018/3/22-13:49.\n * @version 1.0\n */\npublic class WPSOpenUtils {\n\n /**\n * 用WPS 打开应用,注意此种方法无法获取\n *\n * @param filePath 设置好数据了类型的intent\n * @param context Context 对象\n * @return\n */\n public static boolean viewOrEditFileWithWPS(@NonNull Context context, String filePath, boolean readOnly) {\n return viewOrEditFileWithWPS(new ContextStartWrapper(context), filePath, readOnly, 0);\n }\n\n /**\n * 用WPS 打开文档\n *\n * @param fragment\n * @param filePath 设置好数据了类型的intent\n * @param readOnly true - 以只读模式打开文档通过StartActivity启动); false - 以编辑模式打开文档(通过StartActivityForResult启动)\n * @param requestCode 指定通过StartActivityForResult启动时的requestCode\n * @return\n */\n public static boolean viewOrEditFileWithWPS(@NonNull Fragment fragment, String filePath, boolean readOnly, int requestCode) {\n return viewOrEditFileWithWPS(new FragmentStartWrapper(fragment), filePath, readOnly, requestCode);\n }\n\n /**\n * 用WPS 打开应用\n *\n * @param filePath 设置好数据了类型的intent\n * @param wrapper ActivityStarterWrapper 对象\n * @return\n */\n protected static boolean viewOrEditFileWithWPS(@NonNull ActivityStarterWrapper wrapper, String filePath, boolean readOnly, int requestCode) {\n Intent intent", "post_mask_code": "\n File file = new File(filePath);\n if (!file.isFile()) {\n AndroidUtils.showToast(wrapper.getContext(), \"文件不存在\");\n return false;\n }\n intent.setDataAndType(Uri.fromFile(file), FileViewerUtils.getMimeType(file));\n return doRealWPSViewOrEdit(wrapper, intent, readOnly, requestCode);\n }\n\n /**\n * 用WPS 打开应用\n *\n * @param context Context 对象\n * @param intent 设置好数据了类型的intent\n * @return\n */\n protected static boolean doRealWPSViewOrEdit(@NonNull ActivityStarterWrapper context, @NonNull Intent intent, boolean readOnly, int requestCode) {\n Bundle bundle = new Bundle();\n // 关闭时是否发送广播\n bundle.putBoolean(WPSModel.SEND_CLOSE_BROAD, true);\n // 保存时是否发送广播\n bundle.putBoolean(WPSModel.SEND_SAVE_BROAD, true);\n // 第三方应用的包名,用于对改应用合法性的验证\n bundle.putString(WPSModel.THIRD_PACKAGE, context.getPackageName());\n if (readOnly) {\n // 打开模式\n bundle.putString(WPSModel.OPEN_MODE, WPSModel.OpenMode.READ_ONLY);\n } else {\n // 打开模式\n bundle.putString(WPSModel.OPEN_MODE, WPSModel.OpenMode.NORMAL);\n // 修订模式\n bundle.putBoolean(WPSModel.ENTER_REVISE_MODE, true);\n }\n // 清除打开记录\n bundle.putBoolean(WPSModel.CLEAR_TRACE, true);\n intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);\n intent.setAction(Intent.ACTION_VIEW);\n intent.setClassName(WPSModel.PackageName.NORMAL, WPSModel.ClassName.NORMAL);\n intent.putExtras(bundle);\n try {\n if (readOnly) {\n context.startActivity(Intent.createChooser(intent, \"请选择WPS打开文件\"));\n } else {\n context.startActivityForResult(Intent.createChooser(intent, \"请选择WPS打开应用\"), requestCode);\n }\n } catch (ActivityNotFoundException exception) {\n Log.d(\"WPSOpenUtils\", exception.getMessage());\n exception.printStackTrace();\n return false;\n }\n return true;\n }\n\n /**\n * 检测是否有安装 WPS\n *\n * @param context Context\n * @return\n */\n public static boolean checkWPSInstallation(Context context) {\n PackageManager packageManager1 = context.getPackageManager();\n Intent intent = new Intent();\n intent.setClassName(WPSModel.PackageName.NORMAL, WPSModel.ClassName.NORMAL);\n List resolveInfos = packageManager1.queryIntentActivities(intent, PackageManager.MATCH_ALL);\n if (resolveInfos == null || resolveInfos.size() == 0) {\n return false;\n }\n boolean found = false;\n for (ResolveInfo info : resolveInfos) {\n if (info.activityInfo.packageName.toLowerCase().equalsIgnoreCase(WPSModel.PackageName.NORMAL) || info.activityInfo.name.toLowerCase().equalsIgnoreCase(WPSModel.ClassName.NORMAL)) {\n found = true;\n break;\n }\n }\n return found;\n }\n\n abstract static class ActivityStarterWrapper {\n\n protected Context context;\n\n public ActivityStarterWrapper(Context context) {\n this.context = context;\n }\n\n abstract String getPackageName();\n\n abstract void startActivityForResult(Intent intent, int requestCode);\n\n abstract void startActivity(Intent intent);\n\n public Context getContext() {\n return context;\n }\n }\n\n protected static class ContextStartWrapper extends ActivityStarterWrapper {\n\n public ContextStartWrapper(Context context) {\n super(context);\n }\n\n @Override\n String getPackageName() {\n return context.getPackageName();\n }\n\n @Override\n void startActivityForResult(Intent intent, int requestCode) {\n context.startActivity(intent);\n }\n\n @Override\n void startActivity(Intent intent) {\n context.startActivity(intent);\n }\n }\n\n protected static class FragmentStartWrapper extends ActivityStarterWrapper {\n\n Fragment fragment;\n\n public FragmentStartWrapper(Fragment fragment) {\n super(fragment.getContext());\n this.fragment = fragment;\n }\n\n @Override\n String getPackageName() {\n return (fragment.getContext() == null) ? \"\" : fragment.getContext().getPackageName();\n }\n\n @Override\n void startActivityForResult(Intent intent, int requestCode) {\n fragment.startActivityForResult(intent, requestCode);\n }\n\n @Override\n void startActivity(Intent intent) {\n fragment.startActivity(intent);\n }\n }\n}\n"} {"task_id": "Java_2836", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/hanlyjiang/AndroidDocumentViewer/lib_fileviewer/src/main/java/com/hanlyjiang/library/fileviewer/wps/WPSOpenUtils.java", "mask_start_position": 802, "mask_end_position": 1009, "canonical_solution": "public static boolean viewOrEditFileWithWPS(@NonNull Context context, String filePath, boolean readOnly) {\n return viewOrEditFileWithWPS(new ContextStartWrapper(context), filePath, readOnly, 0);\n }", "pre_mask_code": "package com.hanlyjiang.library.fileviewer.wps;\n\nimport android.content.ActivityNotFoundException;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.content.pm.ResolveInfo;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.v4.app.Fragment;\nimport android.util.Log;\nimport com.hanlyjiang.library.utils.AndroidUtils;\nimport com.hanlyjiang.library.utils.FileViewerUtils;\nimport java.io.File;\nimport java.util.List;\n\n/**\n * WPS打开文件工具\n *\n * @author hanlyjiang on 2018/3/22-13:49.\n * @version 1.0\n */\npublic class WPSOpenUtils {\n\n /**\n * 用WPS 打开应用,注意此种方法无法获取\n *\n * @param filePath 设置好数据了类型的intent\n * @param context Context 对象\n * @return\n */\n ", "post_mask_code": "\n\n /**\n * 用WPS 打开文档\n *\n * @param fragment\n * @param filePath 设置好数据了类型的intent\n * @param readOnly true - 以只读模式打开文档通过StartActivity启动); false - 以编辑模式打开文档(通过StartActivityForResult启动)\n * @param requestCode 指定通过StartActivityForResult启动时的requestCode\n * @return\n */\n public static boolean viewOrEditFileWithWPS(@NonNull Fragment fragment, String filePath, boolean readOnly, int requestCode) {\n return viewOrEditFileWithWPS(new FragmentStartWrapper(fragment), filePath, readOnly, requestCode);\n }\n\n /**\n * 用WPS 打开应用\n *\n * @param filePath 设置好数据了类型的intent\n * @param wrapper ActivityStarterWrapper 对象\n * @return\n */\n protected static boolean viewOrEditFileWithWPS(@NonNull ActivityStarterWrapper wrapper, String filePath, boolean readOnly, int requestCode) {\n Intent intent = new Intent();\n File file = new File(filePath);\n if (!file.isFile()) {\n AndroidUtils.showToast(wrapper.getContext(), \"文件不存在\");\n return false;\n }\n intent.setDataAndType(Uri.fromFile(file), FileViewerUtils.getMimeType(file));\n return doRealWPSViewOrEdit(wrapper, intent, readOnly, requestCode);\n }\n\n /**\n * 用WPS 打开应用\n *\n * @param context Context 对象\n * @param intent 设置好数据了类型的intent\n * @return\n */\n protected static boolean doRealWPSViewOrEdit(@NonNull ActivityStarterWrapper context, @NonNull Intent intent, boolean readOnly, int requestCode) {\n Bundle bundle = new Bundle();\n // 关闭时是否发送广播\n bundle.putBoolean(WPSModel.SEND_CLOSE_BROAD, true);\n // 保存时是否发送广播\n bundle.putBoolean(WPSModel.SEND_SAVE_BROAD, true);\n // 第三方应用的包名,用于对改应用合法性的验证\n bundle.putString(WPSModel.THIRD_PACKAGE, context.getPackageName());\n if (readOnly) {\n // 打开模式\n bundle.putString(WPSModel.OPEN_MODE, WPSModel.OpenMode.READ_ONLY);\n } else {\n // 打开模式\n bundle.putString(WPSModel.OPEN_MODE, WPSModel.OpenMode.NORMAL);\n // 修订模式\n bundle.putBoolean(WPSModel.ENTER_REVISE_MODE, true);\n }\n // 清除打开记录\n bundle.putBoolean(WPSModel.CLEAR_TRACE, true);\n intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);\n intent.setAction(Intent.ACTION_VIEW);\n intent.setClassName(WPSModel.PackageName.NORMAL, WPSModel.ClassName.NORMAL);\n intent.putExtras(bundle);\n try {\n if (readOnly) {\n context.startActivity(Intent.createChooser(intent, \"请选择WPS打开文件\"));\n } else {\n context.startActivityForResult(Intent.createChooser(intent, \"请选择WPS打开应用\"), requestCode);\n }\n } catch (ActivityNotFoundException exception) {\n Log.d(\"WPSOpenUtils\", exception.getMessage());\n exception.printStackTrace();\n return false;\n }\n return true;\n }\n\n /**\n * 检测是否有安装 WPS\n *\n * @param context Context\n * @return\n */\n public static boolean checkWPSInstallation(Context context) {\n PackageManager packageManager1 = context.getPackageManager();\n Intent intent = new Intent();\n intent.setClassName(WPSModel.PackageName.NORMAL, WPSModel.ClassName.NORMAL);\n List resolveInfos = packageManager1.queryIntentActivities(intent, PackageManager.MATCH_ALL);\n if (resolveInfos == null || resolveInfos.size() == 0) {\n return false;\n }\n boolean found = false;\n for (ResolveInfo info : resolveInfos) {\n if (info.activityInfo.packageName.toLowerCase().equalsIgnoreCase(WPSModel.PackageName.NORMAL) || info.activityInfo.name.toLowerCase().equalsIgnoreCase(WPSModel.ClassName.NORMAL)) {\n found = true;\n break;\n }\n }\n return found;\n }\n\n abstract static class ActivityStarterWrapper {\n\n protected Context context;\n\n public ActivityStarterWrapper(Context context) {\n this.context = context;\n }\n\n abstract String getPackageName();\n\n abstract void startActivityForResult(Intent intent, int requestCode);\n\n abstract void startActivity(Intent intent);\n\n public Context getContext() {\n return context;\n }\n }\n\n protected static class ContextStartWrapper extends ActivityStarterWrapper {\n\n public ContextStartWrapper(Context context) {\n super(context);\n }\n\n @Override\n String getPackageName() {\n return context.getPackageName();\n }\n\n @Override\n void startActivityForResult(Intent intent, int requestCode) {\n context.startActivity(intent);\n }\n\n @Override\n void startActivity(Intent intent) {\n context.startActivity(intent);\n }\n }\n\n protected static class FragmentStartWrapper extends ActivityStarterWrapper {\n\n Fragment fragment;\n\n public FragmentStartWrapper(Fragment fragment) {\n super(fragment.getContext());\n this.fragment = fragment;\n }\n\n @Override\n String getPackageName() {\n return (fragment.getContext() == null) ? \"\" : fragment.getContext().getPackageName();\n }\n\n @Override\n void startActivityForResult(Intent intent, int requestCode) {\n fragment.startActivityForResult(intent, requestCode);\n }\n\n @Override\n void startActivity(Intent intent) {\n fragment.startActivity(intent);\n }\n }\n}\n"} {"task_id": "Java_2837", "language": "Java", "task_type": "try_statement", "source_file": "java/github/hanlyjiang/AndroidDocumentViewer/lib_fileviewer/src/main/java/com/hanlyjiang/library/fileviewer/wps/WPSOpenUtils.java", "mask_start_position": 3440, "mask_end_position": 3888, "canonical_solution": "try {\n if (readOnly) {\n context.startActivity(Intent.createChooser(intent, \"请选择WPS打开文件\"));\n } else {\n context.startActivityForResult(Intent.createChooser(intent, \"请选择WPS打开应用\"), requestCode);\n }\n } catch (ActivityNotFoundException exception) {\n Log.d(\"WPSOpenUtils\", exception.getMessage());\n exception.printStackTrace();\n return false;\n }", "pre_mask_code": "package com.hanlyjiang.library.fileviewer.wps;\n\nimport android.content.ActivityNotFoundException;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.content.pm.ResolveInfo;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.v4.app.Fragment;\nimport android.util.Log;\nimport com.hanlyjiang.library.utils.AndroidUtils;\nimport com.hanlyjiang.library.utils.FileViewerUtils;\nimport java.io.File;\nimport java.util.List;\n\n/**\n * WPS打开文件工具\n *\n * @author hanlyjiang on 2018/3/22-13:49.\n * @version 1.0\n */\npublic class WPSOpenUtils {\n\n /**\n * 用WPS 打开应用,注意此种方法无法获取\n *\n * @param filePath 设置好数据了类型的intent\n * @param context Context 对象\n * @return\n */\n public static boolean viewOrEditFileWithWPS(@NonNull Context context, String filePath, boolean readOnly) {\n return viewOrEditFileWithWPS(new ContextStartWrapper(context), filePath, readOnly, 0);\n }\n\n /**\n * 用WPS 打开文档\n *\n * @param fragment\n * @param filePath 设置好数据了类型的intent\n * @param readOnly true - 以只读模式打开文档通过StartActivity启动); false - 以编辑模式打开文档(通过StartActivityForResult启动)\n * @param requestCode 指定通过StartActivityForResult启动时的requestCode\n * @return\n */\n public static boolean viewOrEditFileWithWPS(@NonNull Fragment fragment, String filePath, boolean readOnly, int requestCode) {\n return viewOrEditFileWithWPS(new FragmentStartWrapper(fragment), filePath, readOnly, requestCode);\n }\n\n /**\n * 用WPS 打开应用\n *\n * @param filePath 设置好数据了类型的intent\n * @param wrapper ActivityStarterWrapper 对象\n * @return\n */\n protected static boolean viewOrEditFileWithWPS(@NonNull ActivityStarterWrapper wrapper, String filePath, boolean readOnly, int requestCode) {\n Intent intent = new Intent();\n File file = new File(filePath);\n if (!file.isFile()) {\n AndroidUtils.showToast(wrapper.getContext(), \"文件不存在\");\n return false;\n }\n intent.setDataAndType(Uri.fromFile(file), FileViewerUtils.getMimeType(file));\n return doRealWPSViewOrEdit(wrapper, intent, readOnly, requestCode);\n }\n\n /**\n * 用WPS 打开应用\n *\n * @param context Context 对象\n * @param intent 设置好数据了类型的intent\n * @return\n */\n protected static boolean doRealWPSViewOrEdit(@NonNull ActivityStarterWrapper context, @NonNull Intent intent, boolean readOnly, int requestCode) {\n Bundle bundle = new Bundle();\n // 关闭时是否发送广播\n bundle.putBoolean(WPSModel.SEND_CLOSE_BROAD, true);\n // 保存时是否发送广播\n bundle.putBoolean(WPSModel.SEND_SAVE_BROAD, true);\n // 第三方应用的包名,用于对改应用合法性的验证\n bundle.putString(WPSModel.THIRD_PACKAGE, context.getPackageName());\n if (readOnly) {\n // 打开模式\n bundle.putString(WPSModel.OPEN_MODE, WPSModel.OpenMode.READ_ONLY);\n } else {\n // 打开模式\n bundle.putString(WPSModel.OPEN_MODE, WPSModel.OpenMode.NORMAL);\n // 修订模式\n bundle.putBoolean(WPSModel.ENTER_REVISE_MODE, true);\n }\n // 清除打开记录\n bundle.putBoolean(WPSModel.CLEAR_TRACE, true);\n intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);\n intent.setAction(Intent.ACTION_VIEW);\n intent.setClassName(WPSModel.PackageName.NORMAL, WPSModel.ClassName.NORMAL);\n intent.putExtras(bundle);\n ", "post_mask_code": "\n return true;\n }\n\n /**\n * 检测是否有安装 WPS\n *\n * @param context Context\n * @return\n */\n public static boolean checkWPSInstallation(Context context) {\n PackageManager packageManager1 = context.getPackageManager();\n Intent intent = new Intent();\n intent.setClassName(WPSModel.PackageName.NORMAL, WPSModel.ClassName.NORMAL);\n List resolveInfos = packageManager1.queryIntentActivities(intent, PackageManager.MATCH_ALL);\n if (resolveInfos == null || resolveInfos.size() == 0) {\n return false;\n }\n boolean found = false;\n for (ResolveInfo info : resolveInfos) {\n if (info.activityInfo.packageName.toLowerCase().equalsIgnoreCase(WPSModel.PackageName.NORMAL) || info.activityInfo.name.toLowerCase().equalsIgnoreCase(WPSModel.ClassName.NORMAL)) {\n found = true;\n break;\n }\n }\n return found;\n }\n\n abstract static class ActivityStarterWrapper {\n\n protected Context context;\n\n public ActivityStarterWrapper(Context context) {\n this.context = context;\n }\n\n abstract String getPackageName();\n\n abstract void startActivityForResult(Intent intent, int requestCode);\n\n abstract void startActivity(Intent intent);\n\n public Context getContext() {\n return context;\n }\n }\n\n protected static class ContextStartWrapper extends ActivityStarterWrapper {\n\n public ContextStartWrapper(Context context) {\n super(context);\n }\n\n @Override\n String getPackageName() {\n return context.getPackageName();\n }\n\n @Override\n void startActivityForResult(Intent intent, int requestCode) {\n context.startActivity(intent);\n }\n\n @Override\n void startActivity(Intent intent) {\n context.startActivity(intent);\n }\n }\n\n protected static class FragmentStartWrapper extends ActivityStarterWrapper {\n\n Fragment fragment;\n\n public FragmentStartWrapper(Fragment fragment) {\n super(fragment.getContext());\n this.fragment = fragment;\n }\n\n @Override\n String getPackageName() {\n return (fragment.getContext() == null) ? \"\" : fragment.getContext().getPackageName();\n }\n\n @Override\n void startActivityForResult(Intent intent, int requestCode) {\n fragment.startActivityForResult(intent, requestCode);\n }\n\n @Override\n void startActivity(Intent intent) {\n fragment.startActivity(intent);\n }\n }\n}\n"} {"task_id": "Java_2838", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Talend/tdi-studio-se/main/plugins/org.talend.designer.maven.job/src/main/java/org/talend/designer/maven/job/setting/repository/standalone/page/StandaloneJobPomRepositorySettingPage.java", "mask_start_position": 1440, "mask_end_position": 1492, "canonical_solution": "@Override\n public void load() throws IOException ", "pre_mask_code": "// This source code is available under agreement available at\n// %InstallDIR%\\features\\org.talend.rcp.branding.%PRODUCTNAME%\\%PRODUCTNAME%license.txt\n// You should have received a copy of the agreement\n// along with this program; if not, write to Talend SA\n// 9 rue Pages 92150 Suresnes, France\npackage org.talend.designer.maven.job.setting.repository.standalone.page;\n\nimport java.io.IOException;\nimport org.eclipse.core.resources.IFile;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.preference.PreferenceStore;\nimport org.eclipse.swt.widgets.Composite;\nimport org.talend.designer.maven.job.setting.project.page.standalone.StandaloneJobPomProjectSettingPage;\nimport org.talend.designer.maven.ui.setting.repository.RepositoryMavenSettingStore;\n\n/**\n * DOC ggu class global comment. Detailled comment\n */\npublic class StandaloneJobPomRepositorySettingPage extends StandaloneJobPomProjectSettingPage {\n\n private IFile scriptFile;\n\n public StandaloneJobPomRepositorySettingPage(IFile scriptFile) {\n super();\n this.scriptFile = scriptFile;\n }\n\n public void createControl(Composite parent) {\n noDefaultAndApplyButton();\n this.setTitle(this.getHeadTitle());\n super.createControl(parent);\n }\n\n @Override\n protected IPreferenceStore doGetPreferenceStore() {\n return new RepositoryMavenSettingStore(this.getPreferenceKey(), this.scriptFile);\n }\n\n ", "post_mask_code": "{\n if (getPreferenceStore() instanceof PreferenceStore) {\n ((PreferenceStore) getPreferenceStore()).load();\n }\n super.load();\n }\n\n @Override\n public void save() throws IOException {\n if (getPreferenceStore() instanceof PreferenceStore) {\n ((PreferenceStore) getPreferenceStore()).save();\n }\n super.save();\n }\n}\n"} {"task_id": "Java_2839", "language": "Java", "task_type": "method_body", "source_file": "java/github/Talend/tdi-studio-se/main/plugins/org.talend.designer.maven.job/src/main/java/org/talend/designer/maven/job/setting/repository/standalone/page/StandaloneJobPomRepositorySettingPage.java", "mask_start_position": 1713, "mask_end_position": 1876, "canonical_solution": "{\n if (getPreferenceStore() instanceof PreferenceStore) {\n ((PreferenceStore) getPreferenceStore()).save();\n }\n super.save();\n }", "pre_mask_code": "// This source code is available under agreement available at\n// %InstallDIR%\\features\\org.talend.rcp.branding.%PRODUCTNAME%\\%PRODUCTNAME%license.txt\n// You should have received a copy of the agreement\n// along with this program; if not, write to Talend SA\n// 9 rue Pages 92150 Suresnes, France\npackage org.talend.designer.maven.job.setting.repository.standalone.page;\n\nimport java.io.IOException;\nimport org.eclipse.core.resources.IFile;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.preference.PreferenceStore;\nimport org.eclipse.swt.widgets.Composite;\nimport org.talend.designer.maven.job.setting.project.page.standalone.StandaloneJobPomProjectSettingPage;\nimport org.talend.designer.maven.ui.setting.repository.RepositoryMavenSettingStore;\n\n/**\n * DOC ggu class global comment. Detailled comment\n */\npublic class StandaloneJobPomRepositorySettingPage extends StandaloneJobPomProjectSettingPage {\n\n private IFile scriptFile;\n\n public StandaloneJobPomRepositorySettingPage(IFile scriptFile) {\n super();\n this.scriptFile = scriptFile;\n }\n\n public void createControl(Composite parent) {\n noDefaultAndApplyButton();\n this.setTitle(this.getHeadTitle());\n super.createControl(parent);\n }\n\n @Override\n protected IPreferenceStore doGetPreferenceStore() {\n return new RepositoryMavenSettingStore(this.getPreferenceKey(), this.scriptFile);\n }\n\n @Override\n public void load() throws IOException {\n if (getPreferenceStore() instanceof PreferenceStore) {\n ((PreferenceStore) getPreferenceStore()).load();\n }\n super.load();\n }\n\n @Override\n public void save() throws IOException ", "post_mask_code": "\n}\n"} {"task_id": "Java_2840", "language": "Java", "task_type": "single_line", "source_file": "java/github/Talend/tdi-studio-se/main/plugins/org.talend.designer.maven.job/src/main/java/org/talend/designer/maven/job/setting/repository/standalone/page/StandaloneJobPomRepositorySettingPage.java", "mask_start_position": 1639, "mask_end_position": 1649, "canonical_solution": "er.load();", "pre_mask_code": "// This source code is available under agreement available at\n// %InstallDIR%\\features\\org.talend.rcp.branding.%PRODUCTNAME%\\%PRODUCTNAME%license.txt\n// You should have received a copy of the agreement\n// along with this program; if not, write to Talend SA\n// 9 rue Pages 92150 Suresnes, France\npackage org.talend.designer.maven.job.setting.repository.standalone.page;\n\nimport java.io.IOException;\nimport org.eclipse.core.resources.IFile;\nimport org.eclipse.jface.preference.IPreferenceStore;\nimport org.eclipse.jface.preference.PreferenceStore;\nimport org.eclipse.swt.widgets.Composite;\nimport org.talend.designer.maven.job.setting.project.page.standalone.StandaloneJobPomProjectSettingPage;\nimport org.talend.designer.maven.ui.setting.repository.RepositoryMavenSettingStore;\n\n/**\n * DOC ggu class global comment. Detailled comment\n */\npublic class StandaloneJobPomRepositorySettingPage extends StandaloneJobPomProjectSettingPage {\n\n private IFile scriptFile;\n\n public StandaloneJobPomRepositorySettingPage(IFile scriptFile) {\n super();\n this.scriptFile = scriptFile;\n }\n\n public void createControl(Composite parent) {\n noDefaultAndApplyButton();\n this.setTitle(this.getHeadTitle());\n super.createControl(parent);\n }\n\n @Override\n protected IPreferenceStore doGetPreferenceStore() {\n return new RepositoryMavenSettingStore(this.getPreferenceKey(), this.scriptFile);\n }\n\n @Override\n public void load() throws IOException {\n if (getPreferenceStore() instanceof PreferenceStore) {\n ((PreferenceStore) getPreferenceStore()).load();\n }\n sup", "post_mask_code": "\n }\n\n @Override\n public void save() throws IOException {\n if (getPreferenceStore() instanceof PreferenceStore) {\n ((PreferenceStore) getPreferenceStore()).save();\n }\n super.save();\n }\n}\n"} {"task_id": "Java_2841", "language": "Java", "task_type": "method_signature", "source_file": "java/github/coherence-community/oracle-bedrock/bedrock-core/src/main/java/com/oracle/bedrock/deferred/options/RetryFrequency.java", "mask_start_position": 2373, "mask_end_position": 2440, "canonical_solution": "@OptionsByType.Default\n public static RetryFrequency standard() ", "pre_mask_code": "/*\n * File: RetryFrequency.java\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n */\npackage com.oracle.bedrock.deferred.options;\n\nimport com.oracle.bedrock.Option;\nimport com.oracle.bedrock.OptionsByType;\nimport com.oracle.bedrock.deferred.Ensured;\nimport com.oracle.bedrock.util.Duration;\nimport com.oracle.bedrock.util.ExponentialIterator;\nimport com.oracle.bedrock.util.FibonacciIterator;\nimport com.oracle.bedrock.util.MappingIterator;\nimport com.oracle.bedrock.util.PerpetualIterator;\nimport com.oracle.bedrock.util.RandomIterator;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * An {@link Option} to define frequency (durations to wait) when attempting to resolve an\n * {@link Ensured} when calling {@link Ensured#get()}\n *

\n * Oracle is a registered trademark of Oracle Corporation and/or its affiliates.\n *\n * @author Brian Oliver\n *\n * @see Ensured\n */\npublic class RetryFrequency implements Option {\n\n /**\n * The {@link Duration}s for the {@link RetryFrequency}.\n */\n private Iterable durations;\n\n /**\n * Privately constructs a {@link RetryFrequency} {@link Option}.\n *\n * @param durations the {@link Duration}s for the {@link RetryFrequency}\n */\n private RetryFrequency(Iterable durations) {\n this.durations = durations;\n }\n\n /**\n * Obtains the {@link Duration}s for the {@link RetryFrequency}.\n *\n * @return the {@link Duration}s for the {@link RetryFrequency}\n */\n public Iterable get() {\n return durations;\n }\n\n /**\n * Obtains a randomized version of this {@link RetryFrequency}, where by\n * values returned from the {@link #get()} {@link Iterable} will be\n * randomized values between 0 and the values provided by this\n * {@link RetryFrequency}.\n *\n * @return a new randomized {@link RetryFrequency}\n */\n public RetryFrequency randomized() {\n return new RetryFrequency(() -> new MappingIterator<>(new RandomIterator(new MappingIterator<>(this.get().iterator(), duration -> duration.to(TimeUnit.MILLISECONDS))), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n\n /**\n * Obtains the standard {@link RetryFrequency} for retrying every 250 milliseconds.\n *\n * @return a {@link RetryFrequency}\n */\n ", "post_mask_code": "{\n return every(250, TimeUnit.MILLISECONDS);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the specified {@link Duration}s.\n *\n * @param durations the {@link Duration}s\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency of(Iterable durations) {\n return new RetryFrequency(durations);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the specified times.\n *

\n * For example, to retry at 0, 5, 10 and 20 seconds, use the following\n * \n * RetryFrequency.of(TimeUnit.SECONDS, 0, 5, 10, 20);\n * \n *\n * @param unit the {@link TimeUnit} for the durations\n * @param instants the instants in time (will be sorted)\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency of(TimeUnit unit, long... instants) {\n ArrayList frequencies = new ArrayList<>();\n if (instants.length > 0) {\n // ensure we have the instants in a sorted order\n Arrays.sort(instants);\n // add the lowest\n frequencies.add(instants[0]);\n long sum = instants[0];\n for (int i = 1; i < instants.length; i++) {\n long delta = instants[i] - sum;\n sum = sum + delta;\n frequencies.add(delta);\n }\n return new RetryFrequency(() -> new MappingIterator<>(frequencies.iterator(), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n } else {\n throw new IllegalArgumentException(\"Failed to specify any times for the RetryFrequency\");\n }\n }\n\n /**\n * Obtains a {@link RetryFrequency} representing fixed retry {@link Duration}s.\n *\n * @param duration the duration\n * @param unit the {@link TimeUnit} for the {@link Duration}\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency every(long duration, TimeUnit unit) {\n return new RetryFrequency(() -> new PerpetualIterator<>(Duration.of(duration, unit)));\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the Fibonacci sequence.\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency fibonacci() {\n return new RetryFrequency(() -> new MappingIterator<>(new FibonacciIterator(), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on an exponential sequence, starting at 0\n * with a 50% growth rate.\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency exponential() {\n return exponential(0, 50);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on an exponential sequence.\n *\n * @param initial the initial (starting) value\n * @param percentage the growth rate percentage (typically between 0.0 and 100.0)\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency exponential(double initial, double percentage) {\n return new RetryFrequency(() -> new MappingIterator<>(new ExponentialIterator(initial, percentage), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n}\n"} {"task_id": "Java_2842", "language": "Java", "task_type": "method_body", "source_file": "java/github/coherence-community/oracle-bedrock/bedrock-core/src/main/java/com/oracle/bedrock/deferred/options/RetryFrequency.java", "mask_start_position": 4436, "mask_end_position": 4538, "canonical_solution": "{\n return new RetryFrequency(() -> new PerpetualIterator<>(Duration.of(duration, unit)));\n }", "pre_mask_code": "/*\n * File: RetryFrequency.java\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n */\npackage com.oracle.bedrock.deferred.options;\n\nimport com.oracle.bedrock.Option;\nimport com.oracle.bedrock.OptionsByType;\nimport com.oracle.bedrock.deferred.Ensured;\nimport com.oracle.bedrock.util.Duration;\nimport com.oracle.bedrock.util.ExponentialIterator;\nimport com.oracle.bedrock.util.FibonacciIterator;\nimport com.oracle.bedrock.util.MappingIterator;\nimport com.oracle.bedrock.util.PerpetualIterator;\nimport com.oracle.bedrock.util.RandomIterator;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * An {@link Option} to define frequency (durations to wait) when attempting to resolve an\n * {@link Ensured} when calling {@link Ensured#get()}\n *

\n * Oracle is a registered trademark of Oracle Corporation and/or its affiliates.\n *\n * @author Brian Oliver\n *\n * @see Ensured\n */\npublic class RetryFrequency implements Option {\n\n /**\n * The {@link Duration}s for the {@link RetryFrequency}.\n */\n private Iterable durations;\n\n /**\n * Privately constructs a {@link RetryFrequency} {@link Option}.\n *\n * @param durations the {@link Duration}s for the {@link RetryFrequency}\n */\n private RetryFrequency(Iterable durations) {\n this.durations = durations;\n }\n\n /**\n * Obtains the {@link Duration}s for the {@link RetryFrequency}.\n *\n * @return the {@link Duration}s for the {@link RetryFrequency}\n */\n public Iterable get() {\n return durations;\n }\n\n /**\n * Obtains a randomized version of this {@link RetryFrequency}, where by\n * values returned from the {@link #get()} {@link Iterable} will be\n * randomized values between 0 and the values provided by this\n * {@link RetryFrequency}.\n *\n * @return a new randomized {@link RetryFrequency}\n */\n public RetryFrequency randomized() {\n return new RetryFrequency(() -> new MappingIterator<>(new RandomIterator(new MappingIterator<>(this.get().iterator(), duration -> duration.to(TimeUnit.MILLISECONDS))), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n\n /**\n * Obtains the standard {@link RetryFrequency} for retrying every 250 milliseconds.\n *\n * @return a {@link RetryFrequency}\n */\n @OptionsByType.Default\n public static RetryFrequency standard() {\n return every(250, TimeUnit.MILLISECONDS);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the specified {@link Duration}s.\n *\n * @param durations the {@link Duration}s\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency of(Iterable durations) {\n return new RetryFrequency(durations);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the specified times.\n *

\n * For example, to retry at 0, 5, 10 and 20 seconds, use the following\n * \n * RetryFrequency.of(TimeUnit.SECONDS, 0, 5, 10, 20);\n * \n *\n * @param unit the {@link TimeUnit} for the durations\n * @param instants the instants in time (will be sorted)\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency of(TimeUnit unit, long... instants) {\n ArrayList frequencies = new ArrayList<>();\n if (instants.length > 0) {\n // ensure we have the instants in a sorted order\n Arrays.sort(instants);\n // add the lowest\n frequencies.add(instants[0]);\n long sum = instants[0];\n for (int i = 1; i < instants.length; i++) {\n long delta = instants[i] - sum;\n sum = sum + delta;\n frequencies.add(delta);\n }\n return new RetryFrequency(() -> new MappingIterator<>(frequencies.iterator(), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n } else {\n throw new IllegalArgumentException(\"Failed to specify any times for the RetryFrequency\");\n }\n }\n\n /**\n * Obtains a {@link RetryFrequency} representing fixed retry {@link Duration}s.\n *\n * @param duration the duration\n * @param unit the {@link TimeUnit} for the {@link Duration}\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency every(long duration, TimeUnit unit) ", "post_mask_code": "\n\n /**\n * Obtains a {@link RetryFrequency} based on the Fibonacci sequence.\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency fibonacci() {\n return new RetryFrequency(() -> new MappingIterator<>(new FibonacciIterator(), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on an exponential sequence, starting at 0\n * with a 50% growth rate.\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency exponential() {\n return exponential(0, 50);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on an exponential sequence.\n *\n * @param initial the initial (starting) value\n * @param percentage the growth rate percentage (typically between 0.0 and 100.0)\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency exponential(double initial, double percentage) {\n return new RetryFrequency(() -> new MappingIterator<>(new ExponentialIterator(initial, percentage), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n}\n"} {"task_id": "Java_2843", "language": "Java", "task_type": "single_line", "source_file": "java/github/coherence-community/oracle-bedrock/bedrock-core/src/main/java/com/oracle/bedrock/deferred/options/RetryFrequency.java", "mask_start_position": 4789, "mask_end_position": 4869, "canonical_solution": "FibonacciIterator(), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));", "pre_mask_code": "/*\n * File: RetryFrequency.java\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n */\npackage com.oracle.bedrock.deferred.options;\n\nimport com.oracle.bedrock.Option;\nimport com.oracle.bedrock.OptionsByType;\nimport com.oracle.bedrock.deferred.Ensured;\nimport com.oracle.bedrock.util.Duration;\nimport com.oracle.bedrock.util.ExponentialIterator;\nimport com.oracle.bedrock.util.FibonacciIterator;\nimport com.oracle.bedrock.util.MappingIterator;\nimport com.oracle.bedrock.util.PerpetualIterator;\nimport com.oracle.bedrock.util.RandomIterator;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * An {@link Option} to define frequency (durations to wait) when attempting to resolve an\n * {@link Ensured} when calling {@link Ensured#get()}\n *

\n * Oracle is a registered trademark of Oracle Corporation and/or its affiliates.\n *\n * @author Brian Oliver\n *\n * @see Ensured\n */\npublic class RetryFrequency implements Option {\n\n /**\n * The {@link Duration}s for the {@link RetryFrequency}.\n */\n private Iterable durations;\n\n /**\n * Privately constructs a {@link RetryFrequency} {@link Option}.\n *\n * @param durations the {@link Duration}s for the {@link RetryFrequency}\n */\n private RetryFrequency(Iterable durations) {\n this.durations = durations;\n }\n\n /**\n * Obtains the {@link Duration}s for the {@link RetryFrequency}.\n *\n * @return the {@link Duration}s for the {@link RetryFrequency}\n */\n public Iterable get() {\n return durations;\n }\n\n /**\n * Obtains a randomized version of this {@link RetryFrequency}, where by\n * values returned from the {@link #get()} {@link Iterable} will be\n * randomized values between 0 and the values provided by this\n * {@link RetryFrequency}.\n *\n * @return a new randomized {@link RetryFrequency}\n */\n public RetryFrequency randomized() {\n return new RetryFrequency(() -> new MappingIterator<>(new RandomIterator(new MappingIterator<>(this.get().iterator(), duration -> duration.to(TimeUnit.MILLISECONDS))), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n\n /**\n * Obtains the standard {@link RetryFrequency} for retrying every 250 milliseconds.\n *\n * @return a {@link RetryFrequency}\n */\n @OptionsByType.Default\n public static RetryFrequency standard() {\n return every(250, TimeUnit.MILLISECONDS);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the specified {@link Duration}s.\n *\n * @param durations the {@link Duration}s\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency of(Iterable durations) {\n return new RetryFrequency(durations);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the specified times.\n *

\n * For example, to retry at 0, 5, 10 and 20 seconds, use the following\n * \n * RetryFrequency.of(TimeUnit.SECONDS, 0, 5, 10, 20);\n * \n *\n * @param unit the {@link TimeUnit} for the durations\n * @param instants the instants in time (will be sorted)\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency of(TimeUnit unit, long... instants) {\n ArrayList frequencies = new ArrayList<>();\n if (instants.length > 0) {\n // ensure we have the instants in a sorted order\n Arrays.sort(instants);\n // add the lowest\n frequencies.add(instants[0]);\n long sum = instants[0];\n for (int i = 1; i < instants.length; i++) {\n long delta = instants[i] - sum;\n sum = sum + delta;\n frequencies.add(delta);\n }\n return new RetryFrequency(() -> new MappingIterator<>(frequencies.iterator(), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n } else {\n throw new IllegalArgumentException(\"Failed to specify any times for the RetryFrequency\");\n }\n }\n\n /**\n * Obtains a {@link RetryFrequency} representing fixed retry {@link Duration}s.\n *\n * @param duration the duration\n * @param unit the {@link TimeUnit} for the {@link Duration}\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency every(long duration, TimeUnit unit) {\n return new RetryFrequency(() -> new PerpetualIterator<>(Duration.of(duration, unit)));\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the Fibonacci sequence.\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency fibonacci() {\n return new RetryFrequency(() -> new MappingIterator<>(new ", "post_mask_code": "\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on an exponential sequence, starting at 0\n * with a 50% growth rate.\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency exponential() {\n return exponential(0, 50);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on an exponential sequence.\n *\n * @param initial the initial (starting) value\n * @param percentage the growth rate percentage (typically between 0.0 and 100.0)\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency exponential(double initial, double percentage) {\n return new RetryFrequency(() -> new MappingIterator<>(new ExponentialIterator(initial, percentage), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n}\n"} {"task_id": "Java_2844", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/coherence-community/oracle-bedrock/bedrock-core/src/main/java/com/oracle/bedrock/deferred/options/RetryFrequency.java", "mask_start_position": 5440, "mask_end_position": 5691, "canonical_solution": "public static RetryFrequency exponential(double initial, double percentage) {\n return new RetryFrequency(() -> new MappingIterator<>(new ExponentialIterator(initial, percentage), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }", "pre_mask_code": "/*\n * File: RetryFrequency.java\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n */\npackage com.oracle.bedrock.deferred.options;\n\nimport com.oracle.bedrock.Option;\nimport com.oracle.bedrock.OptionsByType;\nimport com.oracle.bedrock.deferred.Ensured;\nimport com.oracle.bedrock.util.Duration;\nimport com.oracle.bedrock.util.ExponentialIterator;\nimport com.oracle.bedrock.util.FibonacciIterator;\nimport com.oracle.bedrock.util.MappingIterator;\nimport com.oracle.bedrock.util.PerpetualIterator;\nimport com.oracle.bedrock.util.RandomIterator;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * An {@link Option} to define frequency (durations to wait) when attempting to resolve an\n * {@link Ensured} when calling {@link Ensured#get()}\n *

\n * Oracle is a registered trademark of Oracle Corporation and/or its affiliates.\n *\n * @author Brian Oliver\n *\n * @see Ensured\n */\npublic class RetryFrequency implements Option {\n\n /**\n * The {@link Duration}s for the {@link RetryFrequency}.\n */\n private Iterable durations;\n\n /**\n * Privately constructs a {@link RetryFrequency} {@link Option}.\n *\n * @param durations the {@link Duration}s for the {@link RetryFrequency}\n */\n private RetryFrequency(Iterable durations) {\n this.durations = durations;\n }\n\n /**\n * Obtains the {@link Duration}s for the {@link RetryFrequency}.\n *\n * @return the {@link Duration}s for the {@link RetryFrequency}\n */\n public Iterable get() {\n return durations;\n }\n\n /**\n * Obtains a randomized version of this {@link RetryFrequency}, where by\n * values returned from the {@link #get()} {@link Iterable} will be\n * randomized values between 0 and the values provided by this\n * {@link RetryFrequency}.\n *\n * @return a new randomized {@link RetryFrequency}\n */\n public RetryFrequency randomized() {\n return new RetryFrequency(() -> new MappingIterator<>(new RandomIterator(new MappingIterator<>(this.get().iterator(), duration -> duration.to(TimeUnit.MILLISECONDS))), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n\n /**\n * Obtains the standard {@link RetryFrequency} for retrying every 250 milliseconds.\n *\n * @return a {@link RetryFrequency}\n */\n @OptionsByType.Default\n public static RetryFrequency standard() {\n return every(250, TimeUnit.MILLISECONDS);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the specified {@link Duration}s.\n *\n * @param durations the {@link Duration}s\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency of(Iterable durations) {\n return new RetryFrequency(durations);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the specified times.\n *

\n * For example, to retry at 0, 5, 10 and 20 seconds, use the following\n * \n * RetryFrequency.of(TimeUnit.SECONDS, 0, 5, 10, 20);\n * \n *\n * @param unit the {@link TimeUnit} for the durations\n * @param instants the instants in time (will be sorted)\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency of(TimeUnit unit, long... instants) {\n ArrayList frequencies = new ArrayList<>();\n if (instants.length > 0) {\n // ensure we have the instants in a sorted order\n Arrays.sort(instants);\n // add the lowest\n frequencies.add(instants[0]);\n long sum = instants[0];\n for (int i = 1; i < instants.length; i++) {\n long delta = instants[i] - sum;\n sum = sum + delta;\n frequencies.add(delta);\n }\n return new RetryFrequency(() -> new MappingIterator<>(frequencies.iterator(), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n } else {\n throw new IllegalArgumentException(\"Failed to specify any times for the RetryFrequency\");\n }\n }\n\n /**\n * Obtains a {@link RetryFrequency} representing fixed retry {@link Duration}s.\n *\n * @param duration the duration\n * @param unit the {@link TimeUnit} for the {@link Duration}\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency every(long duration, TimeUnit unit) {\n return new RetryFrequency(() -> new PerpetualIterator<>(Duration.of(duration, unit)));\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the Fibonacci sequence.\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency fibonacci() {\n return new RetryFrequency(() -> new MappingIterator<>(new FibonacciIterator(), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on an exponential sequence, starting at 0\n * with a 50% growth rate.\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency exponential() {\n return exponential(0, 50);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on an exponential sequence.\n *\n * @param initial the initial (starting) value\n * @param percentage the growth rate percentage (typically between 0.0 and 100.0)\n *\n * @return a {@link RetryFrequency}\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2845", "language": "Java", "task_type": "for_statement", "source_file": "java/github/coherence-community/oracle-bedrock/bedrock-core/src/main/java/com/oracle/bedrock/deferred/options/RetryFrequency.java", "mask_start_position": 3639, "mask_end_position": 3819, "canonical_solution": "for (int i = 1; i < instants.length; i++) {\n long delta = instants[i] - sum;\n sum = sum + delta;\n frequencies.add(delta);\n }", "pre_mask_code": "/*\n * File: RetryFrequency.java\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n */\npackage com.oracle.bedrock.deferred.options;\n\nimport com.oracle.bedrock.Option;\nimport com.oracle.bedrock.OptionsByType;\nimport com.oracle.bedrock.deferred.Ensured;\nimport com.oracle.bedrock.util.Duration;\nimport com.oracle.bedrock.util.ExponentialIterator;\nimport com.oracle.bedrock.util.FibonacciIterator;\nimport com.oracle.bedrock.util.MappingIterator;\nimport com.oracle.bedrock.util.PerpetualIterator;\nimport com.oracle.bedrock.util.RandomIterator;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * An {@link Option} to define frequency (durations to wait) when attempting to resolve an\n * {@link Ensured} when calling {@link Ensured#get()}\n *

\n * Oracle is a registered trademark of Oracle Corporation and/or its affiliates.\n *\n * @author Brian Oliver\n *\n * @see Ensured\n */\npublic class RetryFrequency implements Option {\n\n /**\n * The {@link Duration}s for the {@link RetryFrequency}.\n */\n private Iterable durations;\n\n /**\n * Privately constructs a {@link RetryFrequency} {@link Option}.\n *\n * @param durations the {@link Duration}s for the {@link RetryFrequency}\n */\n private RetryFrequency(Iterable durations) {\n this.durations = durations;\n }\n\n /**\n * Obtains the {@link Duration}s for the {@link RetryFrequency}.\n *\n * @return the {@link Duration}s for the {@link RetryFrequency}\n */\n public Iterable get() {\n return durations;\n }\n\n /**\n * Obtains a randomized version of this {@link RetryFrequency}, where by\n * values returned from the {@link #get()} {@link Iterable} will be\n * randomized values between 0 and the values provided by this\n * {@link RetryFrequency}.\n *\n * @return a new randomized {@link RetryFrequency}\n */\n public RetryFrequency randomized() {\n return new RetryFrequency(() -> new MappingIterator<>(new RandomIterator(new MappingIterator<>(this.get().iterator(), duration -> duration.to(TimeUnit.MILLISECONDS))), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n\n /**\n * Obtains the standard {@link RetryFrequency} for retrying every 250 milliseconds.\n *\n * @return a {@link RetryFrequency}\n */\n @OptionsByType.Default\n public static RetryFrequency standard() {\n return every(250, TimeUnit.MILLISECONDS);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the specified {@link Duration}s.\n *\n * @param durations the {@link Duration}s\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency of(Iterable durations) {\n return new RetryFrequency(durations);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the specified times.\n *

\n * For example, to retry at 0, 5, 10 and 20 seconds, use the following\n * \n * RetryFrequency.of(TimeUnit.SECONDS, 0, 5, 10, 20);\n * \n *\n * @param unit the {@link TimeUnit} for the durations\n * @param instants the instants in time (will be sorted)\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency of(TimeUnit unit, long... instants) {\n ArrayList frequencies = new ArrayList<>();\n if (instants.length > 0) {\n // ensure we have the instants in a sorted order\n Arrays.sort(instants);\n // add the lowest\n frequencies.add(instants[0]);\n long sum = instants[0];\n ", "post_mask_code": "\n return new RetryFrequency(() -> new MappingIterator<>(frequencies.iterator(), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n } else {\n throw new IllegalArgumentException(\"Failed to specify any times for the RetryFrequency\");\n }\n }\n\n /**\n * Obtains a {@link RetryFrequency} representing fixed retry {@link Duration}s.\n *\n * @param duration the duration\n * @param unit the {@link TimeUnit} for the {@link Duration}\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency every(long duration, TimeUnit unit) {\n return new RetryFrequency(() -> new PerpetualIterator<>(Duration.of(duration, unit)));\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on the Fibonacci sequence.\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency fibonacci() {\n return new RetryFrequency(() -> new MappingIterator<>(new FibonacciIterator(), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on an exponential sequence, starting at 0\n * with a 50% growth rate.\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency exponential() {\n return exponential(0, 50);\n }\n\n /**\n * Obtains a {@link RetryFrequency} based on an exponential sequence.\n *\n * @param initial the initial (starting) value\n * @param percentage the growth rate percentage (typically between 0.0 and 100.0)\n *\n * @return a {@link RetryFrequency}\n */\n public static RetryFrequency exponential(double initial, double percentage) {\n return new RetryFrequency(() -> new MappingIterator<>(new ExponentialIterator(initial, percentage), duration -> Duration.of(duration, TimeUnit.MILLISECONDS)));\n }\n}\n"} {"task_id": "Java_2846", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Pushjet/Pushjet-Android/gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/ui/org/gradle/foundation/ProjectView.java", "mask_start_position": 3225, "mask_end_position": 3258, "canonical_solution": "public List getTasks() ", "pre_mask_code": "package org.gradle.foundation;\n\nimport org.gradle.util.GUtil;\nimport java.io.File;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * Analog to gradle's Project but more light-weight and is better suited for using the gradle API from an IDE plugin. It is also easily serializable for passing across a socket. A project is a\n * collection of source files that have tasks associated with them. The tasks build the project. Projects can contain other projects. This is immutable and ultimately comes from gradle files.\n */\npublic class ProjectView implements Comparable, Serializable {\n\n private final String name;\n\n private final ProjectView parentProject;\n\n // It is null for the root project.\n private final List subProjects = new ArrayList();\n\n private final List tasks = new ArrayList();\n\n private final List dependsOnProjects = new ArrayList();\n\n private final File buildFile;\n\n private final String description;\n\n /**\n * Instantiates an immutable view of a project. This is only meant to be called internally whenever generating a hierarchy of projects and tasks.\n */\n ProjectView(ProjectView parentProject, String name, File buildFile, String description) {\n this.parentProject = parentProject;\n this.name = name;\n this.buildFile = buildFile;\n this.description = GUtil.elvis(description, \"\");\n if (parentProject != null) {\n parentProject.addSubProject(this);\n }\n }\n\n public String getName() {\n return name;\n }\n\n public File getBuildFile() {\n return buildFile;\n }\n\n public String getDescription() {\n return description;\n }\n\n public String toString() {\n return name;\n }\n\n public ProjectView getParentProject() {\n return parentProject;\n }\n\n public int compareTo(ProjectView otherProject) {\n return name.compareTo(otherProject.name);\n }\n\n /**\n * creates a task for this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void createTask(String name, String description, boolean isDefault) {\n TaskView taskView = new TaskView(this, name, description, isDefault);\n tasks.add(taskView);\n }\n\n /**\n * Adds the specified project as a sub project of this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void addSubProject(ProjectView subProject) {\n subProjects.add(subProject);\n }\n\n /**\n * Sets the project that this project depends on. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void setDependsOnProjects(List newDependsOnProjects) {\n if (newDependsOnProjects == null) {\n return;\n }\n this.dependsOnProjects.clear();\n this.dependsOnProjects.addAll(newDependsOnProjects);\n }\n\n public List getDependsOnProjects() {\n return dependsOnProjects;\n }\n\n ", "post_mask_code": "{\n return Collections.unmodifiableList(tasks);\n }\n\n public List getSubProjects() {\n return Collections.unmodifiableList(subProjects);\n }\n\n public void sortSubProjectsAndTasks() {\n Collections.sort(tasks);\n Collections.sort(subProjects);\n }\n\n public ProjectView getSubProject(String name) {\n Iterator iterator = subProjects.iterator();\n while (iterator.hasNext()) {\n ProjectView subProject = iterator.next();\n if (name.equals(subProject.getName())) {\n return subProject;\n }\n }\n return null;\n }\n\n public TaskView getTask(String name) {\n Iterator iterator = tasks.iterator();\n while (iterator.hasNext()) {\n TaskView task = iterator.next();\n if (name.equals(task.getName())) {\n return task;\n }\n }\n return null;\n }\n\n public ProjectView getSubProjectFromFullPath(String fullProjectName) {\n if (fullProjectName == null) {\n return null;\n }\n PathParserPortion portion = new PathParserPortion(fullProjectName);\n ProjectView subProject = getSubProject(portion.getFirstPart());\n if (// if we have no remainder, then the path is just a sub project's name. We're done (even if subProject is null).\n !portion.hasRemainder()) {\n return subProject;\n }\n if (subProject == null) {\n return null;\n }\n // the path may be invalid\n return subProject.getSubProjectFromFullPath(portion.getRemainder());\n }\n\n /**\n * This gets the task based on the given full path. This recursively calls this same function with sub projects until it finds the task or no matches are found.\n *\n * @param fullTaskName the full task name (root_project:sub_project:sub_sub_project:task.).\n * @return the task or null if not found.\n */\n public TaskView getTaskFromFullPath(String fullTaskName) {\n if (fullTaskName == null) {\n return null;\n }\n PathParserPortion portion = new PathParserPortion(fullTaskName);\n if (// if we have no remainder, then this is for a task.\n !portion.hasRemainder()) {\n return getTask(portion.getFirstPart());\n }\n ProjectView subProject = getSubProject(portion.getFirstPart());\n if (subProject == null) {\n return null;\n }\n // let the sub project figure it out.\n return subProject.getTaskFromFullPath(portion.getRemainder());\n }\n\n /**\n * This generates this project's full name. This is a colon-separated string of this project and its parent projects.\n *\n * Example: root_project:sub_project:sub_sub_project.\n */\n public String getFullProjectName() {\n ProjectView ancestorProject = getParentProject();\n if (ancestorProject == null) {\n return \"\";\n }\n // if we're the root, our full project name is nothing.\n StringBuilder builder = new StringBuilder(name);\n while (// we don't want to include the 'root' project\n ancestorProject != null && ancestorProject.getParentProject() != null) {\n builder.insert(0, ancestorProject.getName() + ':');\n ancestorProject = ancestorProject.getParentProject();\n }\n return builder.toString();\n }\n\n /**\n * Builds a list of default tasks. These are defined by specifying\n *\n * defaultTasks 'task name'\n *\n * in the gradle file. There can be multiple default tasks. This only returns default tasks directly for this project and does not return them for subprojects.\n *\n * @return a list of default tasks or an empty list if none exist\n */\n public List getDefaultTasks() {\n List defaultTasks = new ArrayList();\n Iterator taskIterator = tasks.iterator();\n while (taskIterator.hasNext()) {\n TaskView taskView = taskIterator.next();\n if (taskView.isDefault()) {\n defaultTasks.add(taskView);\n }\n }\n return defaultTasks;\n }\n}\n"} {"task_id": "Java_2847", "language": "Java", "task_type": "method_body", "source_file": "java/github/Pushjet/Pushjet-Android/gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/ui/org/gradle/foundation/ProjectView.java", "mask_start_position": 2315, "mask_end_position": 2429, "canonical_solution": "{\n TaskView taskView = new TaskView(this, name, description, isDefault);\n tasks.add(taskView);\n }", "pre_mask_code": "package org.gradle.foundation;\n\nimport org.gradle.util.GUtil;\nimport java.io.File;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * Analog to gradle's Project but more light-weight and is better suited for using the gradle API from an IDE plugin. It is also easily serializable for passing across a socket. A project is a\n * collection of source files that have tasks associated with them. The tasks build the project. Projects can contain other projects. This is immutable and ultimately comes from gradle files.\n */\npublic class ProjectView implements Comparable, Serializable {\n\n private final String name;\n\n private final ProjectView parentProject;\n\n // It is null for the root project.\n private final List subProjects = new ArrayList();\n\n private final List tasks = new ArrayList();\n\n private final List dependsOnProjects = new ArrayList();\n\n private final File buildFile;\n\n private final String description;\n\n /**\n * Instantiates an immutable view of a project. This is only meant to be called internally whenever generating a hierarchy of projects and tasks.\n */\n ProjectView(ProjectView parentProject, String name, File buildFile, String description) {\n this.parentProject = parentProject;\n this.name = name;\n this.buildFile = buildFile;\n this.description = GUtil.elvis(description, \"\");\n if (parentProject != null) {\n parentProject.addSubProject(this);\n }\n }\n\n public String getName() {\n return name;\n }\n\n public File getBuildFile() {\n return buildFile;\n }\n\n public String getDescription() {\n return description;\n }\n\n public String toString() {\n return name;\n }\n\n public ProjectView getParentProject() {\n return parentProject;\n }\n\n public int compareTo(ProjectView otherProject) {\n return name.compareTo(otherProject.name);\n }\n\n /**\n * creates a task for this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void createTask(String name, String description, boolean isDefault) ", "post_mask_code": "\n\n /**\n * Adds the specified project as a sub project of this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void addSubProject(ProjectView subProject) {\n subProjects.add(subProject);\n }\n\n /**\n * Sets the project that this project depends on. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void setDependsOnProjects(List newDependsOnProjects) {\n if (newDependsOnProjects == null) {\n return;\n }\n this.dependsOnProjects.clear();\n this.dependsOnProjects.addAll(newDependsOnProjects);\n }\n\n public List getDependsOnProjects() {\n return dependsOnProjects;\n }\n\n public List getTasks() {\n return Collections.unmodifiableList(tasks);\n }\n\n public List getSubProjects() {\n return Collections.unmodifiableList(subProjects);\n }\n\n public void sortSubProjectsAndTasks() {\n Collections.sort(tasks);\n Collections.sort(subProjects);\n }\n\n public ProjectView getSubProject(String name) {\n Iterator iterator = subProjects.iterator();\n while (iterator.hasNext()) {\n ProjectView subProject = iterator.next();\n if (name.equals(subProject.getName())) {\n return subProject;\n }\n }\n return null;\n }\n\n public TaskView getTask(String name) {\n Iterator iterator = tasks.iterator();\n while (iterator.hasNext()) {\n TaskView task = iterator.next();\n if (name.equals(task.getName())) {\n return task;\n }\n }\n return null;\n }\n\n public ProjectView getSubProjectFromFullPath(String fullProjectName) {\n if (fullProjectName == null) {\n return null;\n }\n PathParserPortion portion = new PathParserPortion(fullProjectName);\n ProjectView subProject = getSubProject(portion.getFirstPart());\n if (// if we have no remainder, then the path is just a sub project's name. We're done (even if subProject is null).\n !portion.hasRemainder()) {\n return subProject;\n }\n if (subProject == null) {\n return null;\n }\n // the path may be invalid\n return subProject.getSubProjectFromFullPath(portion.getRemainder());\n }\n\n /**\n * This gets the task based on the given full path. This recursively calls this same function with sub projects until it finds the task or no matches are found.\n *\n * @param fullTaskName the full task name (root_project:sub_project:sub_sub_project:task.).\n * @return the task or null if not found.\n */\n public TaskView getTaskFromFullPath(String fullTaskName) {\n if (fullTaskName == null) {\n return null;\n }\n PathParserPortion portion = new PathParserPortion(fullTaskName);\n if (// if we have no remainder, then this is for a task.\n !portion.hasRemainder()) {\n return getTask(portion.getFirstPart());\n }\n ProjectView subProject = getSubProject(portion.getFirstPart());\n if (subProject == null) {\n return null;\n }\n // let the sub project figure it out.\n return subProject.getTaskFromFullPath(portion.getRemainder());\n }\n\n /**\n * This generates this project's full name. This is a colon-separated string of this project and its parent projects.\n *\n * Example: root_project:sub_project:sub_sub_project.\n */\n public String getFullProjectName() {\n ProjectView ancestorProject = getParentProject();\n if (ancestorProject == null) {\n return \"\";\n }\n // if we're the root, our full project name is nothing.\n StringBuilder builder = new StringBuilder(name);\n while (// we don't want to include the 'root' project\n ancestorProject != null && ancestorProject.getParentProject() != null) {\n builder.insert(0, ancestorProject.getName() + ':');\n ancestorProject = ancestorProject.getParentProject();\n }\n return builder.toString();\n }\n\n /**\n * Builds a list of default tasks. These are defined by specifying\n *\n * defaultTasks 'task name'\n *\n * in the gradle file. There can be multiple default tasks. This only returns default tasks directly for this project and does not return them for subprojects.\n *\n * @return a list of default tasks or an empty list if none exist\n */\n public List getDefaultTasks() {\n List defaultTasks = new ArrayList();\n Iterator taskIterator = tasks.iterator();\n while (taskIterator.hasNext()) {\n TaskView taskView = taskIterator.next();\n if (taskView.isDefault()) {\n defaultTasks.add(taskView);\n }\n }\n return defaultTasks;\n }\n}\n"} {"task_id": "Java_2848", "language": "Java", "task_type": "single_line", "source_file": "java/github/Pushjet/Pushjet-Android/gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/ui/org/gradle/foundation/ProjectView.java", "mask_start_position": 2693, "mask_end_position": 2697, "canonical_solution": "ct);", "pre_mask_code": "package org.gradle.foundation;\n\nimport org.gradle.util.GUtil;\nimport java.io.File;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * Analog to gradle's Project but more light-weight and is better suited for using the gradle API from an IDE plugin. It is also easily serializable for passing across a socket. A project is a\n * collection of source files that have tasks associated with them. The tasks build the project. Projects can contain other projects. This is immutable and ultimately comes from gradle files.\n */\npublic class ProjectView implements Comparable, Serializable {\n\n private final String name;\n\n private final ProjectView parentProject;\n\n // It is null for the root project.\n private final List subProjects = new ArrayList();\n\n private final List tasks = new ArrayList();\n\n private final List dependsOnProjects = new ArrayList();\n\n private final File buildFile;\n\n private final String description;\n\n /**\n * Instantiates an immutable view of a project. This is only meant to be called internally whenever generating a hierarchy of projects and tasks.\n */\n ProjectView(ProjectView parentProject, String name, File buildFile, String description) {\n this.parentProject = parentProject;\n this.name = name;\n this.buildFile = buildFile;\n this.description = GUtil.elvis(description, \"\");\n if (parentProject != null) {\n parentProject.addSubProject(this);\n }\n }\n\n public String getName() {\n return name;\n }\n\n public File getBuildFile() {\n return buildFile;\n }\n\n public String getDescription() {\n return description;\n }\n\n public String toString() {\n return name;\n }\n\n public ProjectView getParentProject() {\n return parentProject;\n }\n\n public int compareTo(ProjectView otherProject) {\n return name.compareTo(otherProject.name);\n }\n\n /**\n * creates a task for this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void createTask(String name, String description, boolean isDefault) {\n TaskView taskView = new TaskView(this, name, description, isDefault);\n tasks.add(taskView);\n }\n\n /**\n * Adds the specified project as a sub project of this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void addSubProject(ProjectView subProject) {\n subProjects.add(subProje", "post_mask_code": "\n }\n\n /**\n * Sets the project that this project depends on. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void setDependsOnProjects(List newDependsOnProjects) {\n if (newDependsOnProjects == null) {\n return;\n }\n this.dependsOnProjects.clear();\n this.dependsOnProjects.addAll(newDependsOnProjects);\n }\n\n public List getDependsOnProjects() {\n return dependsOnProjects;\n }\n\n public List getTasks() {\n return Collections.unmodifiableList(tasks);\n }\n\n public List getSubProjects() {\n return Collections.unmodifiableList(subProjects);\n }\n\n public void sortSubProjectsAndTasks() {\n Collections.sort(tasks);\n Collections.sort(subProjects);\n }\n\n public ProjectView getSubProject(String name) {\n Iterator iterator = subProjects.iterator();\n while (iterator.hasNext()) {\n ProjectView subProject = iterator.next();\n if (name.equals(subProject.getName())) {\n return subProject;\n }\n }\n return null;\n }\n\n public TaskView getTask(String name) {\n Iterator iterator = tasks.iterator();\n while (iterator.hasNext()) {\n TaskView task = iterator.next();\n if (name.equals(task.getName())) {\n return task;\n }\n }\n return null;\n }\n\n public ProjectView getSubProjectFromFullPath(String fullProjectName) {\n if (fullProjectName == null) {\n return null;\n }\n PathParserPortion portion = new PathParserPortion(fullProjectName);\n ProjectView subProject = getSubProject(portion.getFirstPart());\n if (// if we have no remainder, then the path is just a sub project's name. We're done (even if subProject is null).\n !portion.hasRemainder()) {\n return subProject;\n }\n if (subProject == null) {\n return null;\n }\n // the path may be invalid\n return subProject.getSubProjectFromFullPath(portion.getRemainder());\n }\n\n /**\n * This gets the task based on the given full path. This recursively calls this same function with sub projects until it finds the task or no matches are found.\n *\n * @param fullTaskName the full task name (root_project:sub_project:sub_sub_project:task.).\n * @return the task or null if not found.\n */\n public TaskView getTaskFromFullPath(String fullTaskName) {\n if (fullTaskName == null) {\n return null;\n }\n PathParserPortion portion = new PathParserPortion(fullTaskName);\n if (// if we have no remainder, then this is for a task.\n !portion.hasRemainder()) {\n return getTask(portion.getFirstPart());\n }\n ProjectView subProject = getSubProject(portion.getFirstPart());\n if (subProject == null) {\n return null;\n }\n // let the sub project figure it out.\n return subProject.getTaskFromFullPath(portion.getRemainder());\n }\n\n /**\n * This generates this project's full name. This is a colon-separated string of this project and its parent projects.\n *\n * Example: root_project:sub_project:sub_sub_project.\n */\n public String getFullProjectName() {\n ProjectView ancestorProject = getParentProject();\n if (ancestorProject == null) {\n return \"\";\n }\n // if we're the root, our full project name is nothing.\n StringBuilder builder = new StringBuilder(name);\n while (// we don't want to include the 'root' project\n ancestorProject != null && ancestorProject.getParentProject() != null) {\n builder.insert(0, ancestorProject.getName() + ':');\n ancestorProject = ancestorProject.getParentProject();\n }\n return builder.toString();\n }\n\n /**\n * Builds a list of default tasks. These are defined by specifying\n *\n * defaultTasks 'task name'\n *\n * in the gradle file. There can be multiple default tasks. This only returns default tasks directly for this project and does not return them for subprojects.\n *\n * @return a list of default tasks or an empty list if none exist\n */\n public List getDefaultTasks() {\n List defaultTasks = new ArrayList();\n Iterator taskIterator = tasks.iterator();\n while (taskIterator.hasNext()) {\n TaskView taskView = taskIterator.next();\n if (taskView.isDefault()) {\n defaultTasks.add(taskView);\n }\n }\n return defaultTasks;\n }\n}\n"} {"task_id": "Java_2849", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/Pushjet/Pushjet-Android/gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/ui/org/gradle/foundation/ProjectView.java", "mask_start_position": 2616, "mask_end_position": 2703, "canonical_solution": "void addSubProject(ProjectView subProject) {\n subProjects.add(subProject);\n }", "pre_mask_code": "package org.gradle.foundation;\n\nimport org.gradle.util.GUtil;\nimport java.io.File;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * Analog to gradle's Project but more light-weight and is better suited for using the gradle API from an IDE plugin. It is also easily serializable for passing across a socket. A project is a\n * collection of source files that have tasks associated with them. The tasks build the project. Projects can contain other projects. This is immutable and ultimately comes from gradle files.\n */\npublic class ProjectView implements Comparable, Serializable {\n\n private final String name;\n\n private final ProjectView parentProject;\n\n // It is null for the root project.\n private final List subProjects = new ArrayList();\n\n private final List tasks = new ArrayList();\n\n private final List dependsOnProjects = new ArrayList();\n\n private final File buildFile;\n\n private final String description;\n\n /**\n * Instantiates an immutable view of a project. This is only meant to be called internally whenever generating a hierarchy of projects and tasks.\n */\n ProjectView(ProjectView parentProject, String name, File buildFile, String description) {\n this.parentProject = parentProject;\n this.name = name;\n this.buildFile = buildFile;\n this.description = GUtil.elvis(description, \"\");\n if (parentProject != null) {\n parentProject.addSubProject(this);\n }\n }\n\n public String getName() {\n return name;\n }\n\n public File getBuildFile() {\n return buildFile;\n }\n\n public String getDescription() {\n return description;\n }\n\n public String toString() {\n return name;\n }\n\n public ProjectView getParentProject() {\n return parentProject;\n }\n\n public int compareTo(ProjectView otherProject) {\n return name.compareTo(otherProject.name);\n }\n\n /**\n * creates a task for this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void createTask(String name, String description, boolean isDefault) {\n TaskView taskView = new TaskView(this, name, description, isDefault);\n tasks.add(taskView);\n }\n\n /**\n * Adds the specified project as a sub project of this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n ", "post_mask_code": "\n\n /**\n * Sets the project that this project depends on. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void setDependsOnProjects(List newDependsOnProjects) {\n if (newDependsOnProjects == null) {\n return;\n }\n this.dependsOnProjects.clear();\n this.dependsOnProjects.addAll(newDependsOnProjects);\n }\n\n public List getDependsOnProjects() {\n return dependsOnProjects;\n }\n\n public List getTasks() {\n return Collections.unmodifiableList(tasks);\n }\n\n public List getSubProjects() {\n return Collections.unmodifiableList(subProjects);\n }\n\n public void sortSubProjectsAndTasks() {\n Collections.sort(tasks);\n Collections.sort(subProjects);\n }\n\n public ProjectView getSubProject(String name) {\n Iterator iterator = subProjects.iterator();\n while (iterator.hasNext()) {\n ProjectView subProject = iterator.next();\n if (name.equals(subProject.getName())) {\n return subProject;\n }\n }\n return null;\n }\n\n public TaskView getTask(String name) {\n Iterator iterator = tasks.iterator();\n while (iterator.hasNext()) {\n TaskView task = iterator.next();\n if (name.equals(task.getName())) {\n return task;\n }\n }\n return null;\n }\n\n public ProjectView getSubProjectFromFullPath(String fullProjectName) {\n if (fullProjectName == null) {\n return null;\n }\n PathParserPortion portion = new PathParserPortion(fullProjectName);\n ProjectView subProject = getSubProject(portion.getFirstPart());\n if (// if we have no remainder, then the path is just a sub project's name. We're done (even if subProject is null).\n !portion.hasRemainder()) {\n return subProject;\n }\n if (subProject == null) {\n return null;\n }\n // the path may be invalid\n return subProject.getSubProjectFromFullPath(portion.getRemainder());\n }\n\n /**\n * This gets the task based on the given full path. This recursively calls this same function with sub projects until it finds the task or no matches are found.\n *\n * @param fullTaskName the full task name (root_project:sub_project:sub_sub_project:task.).\n * @return the task or null if not found.\n */\n public TaskView getTaskFromFullPath(String fullTaskName) {\n if (fullTaskName == null) {\n return null;\n }\n PathParserPortion portion = new PathParserPortion(fullTaskName);\n if (// if we have no remainder, then this is for a task.\n !portion.hasRemainder()) {\n return getTask(portion.getFirstPart());\n }\n ProjectView subProject = getSubProject(portion.getFirstPart());\n if (subProject == null) {\n return null;\n }\n // let the sub project figure it out.\n return subProject.getTaskFromFullPath(portion.getRemainder());\n }\n\n /**\n * This generates this project's full name. This is a colon-separated string of this project and its parent projects.\n *\n * Example: root_project:sub_project:sub_sub_project.\n */\n public String getFullProjectName() {\n ProjectView ancestorProject = getParentProject();\n if (ancestorProject == null) {\n return \"\";\n }\n // if we're the root, our full project name is nothing.\n StringBuilder builder = new StringBuilder(name);\n while (// we don't want to include the 'root' project\n ancestorProject != null && ancestorProject.getParentProject() != null) {\n builder.insert(0, ancestorProject.getName() + ':');\n ancestorProject = ancestorProject.getParentProject();\n }\n return builder.toString();\n }\n\n /**\n * Builds a list of default tasks. These are defined by specifying\n *\n * defaultTasks 'task name'\n *\n * in the gradle file. There can be multiple default tasks. This only returns default tasks directly for this project and does not return them for subprojects.\n *\n * @return a list of default tasks or an empty list if none exist\n */\n public List getDefaultTasks() {\n List defaultTasks = new ArrayList();\n Iterator taskIterator = tasks.iterator();\n while (taskIterator.hasNext()) {\n TaskView taskView = taskIterator.next();\n if (taskView.isDefault()) {\n defaultTasks.add(taskView);\n }\n }\n return defaultTasks;\n }\n}\n"} {"task_id": "Java_2850", "language": "Java", "task_type": "while_statement", "source_file": "java/github/Pushjet/Pushjet-Android/gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/ui/org/gradle/foundation/ProjectView.java", "mask_start_position": 3680, "mask_end_position": 3874, "canonical_solution": "while (iterator.hasNext()) {\n ProjectView subProject = iterator.next();\n if (name.equals(subProject.getName())) {\n return subProject;\n }\n }", "pre_mask_code": "package org.gradle.foundation;\n\nimport org.gradle.util.GUtil;\nimport java.io.File;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * Analog to gradle's Project but more light-weight and is better suited for using the gradle API from an IDE plugin. It is also easily serializable for passing across a socket. A project is a\n * collection of source files that have tasks associated with them. The tasks build the project. Projects can contain other projects. This is immutable and ultimately comes from gradle files.\n */\npublic class ProjectView implements Comparable, Serializable {\n\n private final String name;\n\n private final ProjectView parentProject;\n\n // It is null for the root project.\n private final List subProjects = new ArrayList();\n\n private final List tasks = new ArrayList();\n\n private final List dependsOnProjects = new ArrayList();\n\n private final File buildFile;\n\n private final String description;\n\n /**\n * Instantiates an immutable view of a project. This is only meant to be called internally whenever generating a hierarchy of projects and tasks.\n */\n ProjectView(ProjectView parentProject, String name, File buildFile, String description) {\n this.parentProject = parentProject;\n this.name = name;\n this.buildFile = buildFile;\n this.description = GUtil.elvis(description, \"\");\n if (parentProject != null) {\n parentProject.addSubProject(this);\n }\n }\n\n public String getName() {\n return name;\n }\n\n public File getBuildFile() {\n return buildFile;\n }\n\n public String getDescription() {\n return description;\n }\n\n public String toString() {\n return name;\n }\n\n public ProjectView getParentProject() {\n return parentProject;\n }\n\n public int compareTo(ProjectView otherProject) {\n return name.compareTo(otherProject.name);\n }\n\n /**\n * creates a task for this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void createTask(String name, String description, boolean isDefault) {\n TaskView taskView = new TaskView(this, name, description, isDefault);\n tasks.add(taskView);\n }\n\n /**\n * Adds the specified project as a sub project of this project. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void addSubProject(ProjectView subProject) {\n subProjects.add(subProject);\n }\n\n /**\n * Sets the project that this project depends on. This is only meant to be called internally whenever generating a hierachy of projects and tasks.\n */\n void setDependsOnProjects(List newDependsOnProjects) {\n if (newDependsOnProjects == null) {\n return;\n }\n this.dependsOnProjects.clear();\n this.dependsOnProjects.addAll(newDependsOnProjects);\n }\n\n public List getDependsOnProjects() {\n return dependsOnProjects;\n }\n\n public List getTasks() {\n return Collections.unmodifiableList(tasks);\n }\n\n public List getSubProjects() {\n return Collections.unmodifiableList(subProjects);\n }\n\n public void sortSubProjectsAndTasks() {\n Collections.sort(tasks);\n Collections.sort(subProjects);\n }\n\n public ProjectView getSubProject(String name) {\n Iterator iterator = subProjects.iterator();\n ", "post_mask_code": "\n return null;\n }\n\n public TaskView getTask(String name) {\n Iterator iterator = tasks.iterator();\n while (iterator.hasNext()) {\n TaskView task = iterator.next();\n if (name.equals(task.getName())) {\n return task;\n }\n }\n return null;\n }\n\n public ProjectView getSubProjectFromFullPath(String fullProjectName) {\n if (fullProjectName == null) {\n return null;\n }\n PathParserPortion portion = new PathParserPortion(fullProjectName);\n ProjectView subProject = getSubProject(portion.getFirstPart());\n if (// if we have no remainder, then the path is just a sub project's name. We're done (even if subProject is null).\n !portion.hasRemainder()) {\n return subProject;\n }\n if (subProject == null) {\n return null;\n }\n // the path may be invalid\n return subProject.getSubProjectFromFullPath(portion.getRemainder());\n }\n\n /**\n * This gets the task based on the given full path. This recursively calls this same function with sub projects until it finds the task or no matches are found.\n *\n * @param fullTaskName the full task name (root_project:sub_project:sub_sub_project:task.).\n * @return the task or null if not found.\n */\n public TaskView getTaskFromFullPath(String fullTaskName) {\n if (fullTaskName == null) {\n return null;\n }\n PathParserPortion portion = new PathParserPortion(fullTaskName);\n if (// if we have no remainder, then this is for a task.\n !portion.hasRemainder()) {\n return getTask(portion.getFirstPart());\n }\n ProjectView subProject = getSubProject(portion.getFirstPart());\n if (subProject == null) {\n return null;\n }\n // let the sub project figure it out.\n return subProject.getTaskFromFullPath(portion.getRemainder());\n }\n\n /**\n * This generates this project's full name. This is a colon-separated string of this project and its parent projects.\n *\n * Example: root_project:sub_project:sub_sub_project.\n */\n public String getFullProjectName() {\n ProjectView ancestorProject = getParentProject();\n if (ancestorProject == null) {\n return \"\";\n }\n // if we're the root, our full project name is nothing.\n StringBuilder builder = new StringBuilder(name);\n while (// we don't want to include the 'root' project\n ancestorProject != null && ancestorProject.getParentProject() != null) {\n builder.insert(0, ancestorProject.getName() + ':');\n ancestorProject = ancestorProject.getParentProject();\n }\n return builder.toString();\n }\n\n /**\n * Builds a list of default tasks. These are defined by specifying\n *\n * defaultTasks 'task name'\n *\n * in the gradle file. There can be multiple default tasks. This only returns default tasks directly for this project and does not return them for subprojects.\n *\n * @return a list of default tasks or an empty list if none exist\n */\n public List getDefaultTasks() {\n List defaultTasks = new ArrayList();\n Iterator taskIterator = tasks.iterator();\n while (taskIterator.hasNext()) {\n TaskView taskView = taskIterator.next();\n if (taskView.isDefault()) {\n defaultTasks.add(taskView);\n }\n }\n return defaultTasks;\n }\n}\n"} {"task_id": "Java_2851", "language": "Java", "task_type": "method_signature", "source_file": "java/github/joekoolade/JOE/classpath-0.98/gnu/javax/imageio/gif/GIFImageReader.java", "mask_start_position": 3163, "mask_end_position": 3218, "canonical_solution": "public int getWidth(int imageIndex) throws IOException ", "pre_mask_code": "package gnu.javax.imageio.gif;\n\nimport gnu.javax.imageio.IIOInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport javax.imageio.*;\nimport javax.imageio.spi.*;\nimport javax.imageio.metadata.*;\nimport javax.imageio.stream.ImageInputStream;\nimport java.util.Iterator;\nimport java.awt.image.BufferedImage;\nimport java.awt.image.IndexColorModel;\nimport java.awt.image.SampleModel;\nimport java.awt.image.MultiPixelPackedSampleModel;\nimport java.awt.image.SinglePixelPackedSampleModel;\nimport java.awt.image.DataBuffer;\nimport java.awt.image.DataBufferByte;\nimport java.awt.image.Raster;\nimport java.awt.image.WritableRaster;\n\npublic class GIFImageReader extends ImageReader {\n\n private GIFFile file;\n\n protected GIFImageReader(ImageReaderSpi originatingProvider) {\n super(originatingProvider);\n file = null;\n }\n\n private void readImage() throws IOException {\n if (file != null)\n return;\n try {\n if (input instanceof InputStream)\n file = new GIFFile((InputStream) input);\n else\n file = new GIFFile(new IIOInputStream((ImageInputStream) input));\n } catch (GIFFile.GIFException ge) {\n throw new IIOException(ge.getMessage());\n }\n }\n\n /**\n * Returns the Global/Local palette as an IndexColorModel\n */\n private IndexColorModel getPalette(int index) {\n GIFFile f = file.getImage(index);\n byte[] data = f.getRawPalette();\n int nc = f.getNColors();\n byte[] r = new byte[nc];\n byte[] g = new byte[nc];\n byte[] b = new byte[nc];\n for (int i = 0; i < nc; i++) {\n r[i] = data[i * 3];\n g[i] = data[i * 3 + 1];\n b[i] = data[i * 3 + 2];\n }\n if (f.hasTransparency()) {\n byte[] a = new byte[nc];\n for (int i = 0; i < nc; i++) a[i] = (byte) 0xFF;\n a[f.getTransparentIndex()] = 0;\n return new IndexColorModel(8, nc, r, g, b, a);\n }\n return new IndexColorModel(8, nc, r, g, b);\n }\n\n private void validateIndex(int imageIndex) throws IndexOutOfBoundsException {\n if (imageIndex < 0 || imageIndex >= getNumImages(false))\n throw new IndexOutOfBoundsException(\"Invalid image index.\");\n }\n\n public void setInput(Object input) {\n super.setInput(input);\n }\n\n public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {\n super.setInput(input, seekForwardOnly, ignoreMetadata);\n }\n\n public void setInput(Object input, boolean isStreamable) {\n super.setInput(input, isStreamable);\n if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))\n throw new IllegalArgumentException(\"Input not an ImageInputStream.\");\n }\n\n private void checkStream() throws IOException {\n if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))\n throw new IllegalStateException(\"Input not an ImageInputStream or InputStream.\");\n if (input == null)\n throw new IllegalStateException(\"No input stream.\");\n }\n\n ", "post_mask_code": "{\n validateIndex(imageIndex);\n return file.getImage(imageIndex).getWidth();\n }\n\n public int getHeight(int imageIndex) throws IOException {\n validateIndex(imageIndex);\n return file.getImage(imageIndex).getHeight();\n }\n\n public Iterator getImageTypes(int imageIndex) {\n validateIndex(imageIndex);\n return null;\n }\n\n /**\n * Returns the number of images.\n */\n public int getNumImages(boolean allowSearch) {\n try // Image should be loaded here already. But just in case:\n {\n readImage();\n } catch (IOException ioe) {\n // Well, now we're in trouble. But return something anyway.\n return 0;\n }\n return file.nImages();\n }\n\n // FIXME: Support metadata\n public IIOMetadata getImageMetadata(int imageIndex) {\n validateIndex(imageIndex);\n return null;\n }\n\n // FIXME: Support metadata\n public IIOMetadata getStreamMetadata() {\n return null;\n }\n\n /**\n * Reads the image indexed by imageIndex and returns it as\n * a complete BufferedImage, using a supplied ImageReadParam.\n */\n public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException, IIOException {\n validateIndex(imageIndex);\n GIFFile f = file.getImage(imageIndex);\n int width = f.getWidth();\n int height = f.getHeight();\n SampleModel sm;\n switch(f.getNColors()) {\n case 16:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 4);\n break;\n case 4:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 2);\n break;\n case 2:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1);\n break;\n default:\n sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, new int[] { 0xFF });\n break;\n }\n DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);\n WritableRaster raster = Raster.createWritableRaster(sm, db, null);\n return new BufferedImage(getPalette(imageIndex), raster, false, null);\n }\n}\n"} {"task_id": "Java_2852", "language": "Java", "task_type": "method_body", "source_file": "java/github/joekoolade/JOE/classpath-0.98/gnu/javax/imageio/gif/GIFImageReader.java", "mask_start_position": 2879, "mask_end_position": 3157, "canonical_solution": "{\n if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))\n throw new IllegalStateException(\"Input not an ImageInputStream or InputStream.\");\n if (input == null)\n throw new IllegalStateException(\"No input stream.\");\n }", "pre_mask_code": "package gnu.javax.imageio.gif;\n\nimport gnu.javax.imageio.IIOInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport javax.imageio.*;\nimport javax.imageio.spi.*;\nimport javax.imageio.metadata.*;\nimport javax.imageio.stream.ImageInputStream;\nimport java.util.Iterator;\nimport java.awt.image.BufferedImage;\nimport java.awt.image.IndexColorModel;\nimport java.awt.image.SampleModel;\nimport java.awt.image.MultiPixelPackedSampleModel;\nimport java.awt.image.SinglePixelPackedSampleModel;\nimport java.awt.image.DataBuffer;\nimport java.awt.image.DataBufferByte;\nimport java.awt.image.Raster;\nimport java.awt.image.WritableRaster;\n\npublic class GIFImageReader extends ImageReader {\n\n private GIFFile file;\n\n protected GIFImageReader(ImageReaderSpi originatingProvider) {\n super(originatingProvider);\n file = null;\n }\n\n private void readImage() throws IOException {\n if (file != null)\n return;\n try {\n if (input instanceof InputStream)\n file = new GIFFile((InputStream) input);\n else\n file = new GIFFile(new IIOInputStream((ImageInputStream) input));\n } catch (GIFFile.GIFException ge) {\n throw new IIOException(ge.getMessage());\n }\n }\n\n /**\n * Returns the Global/Local palette as an IndexColorModel\n */\n private IndexColorModel getPalette(int index) {\n GIFFile f = file.getImage(index);\n byte[] data = f.getRawPalette();\n int nc = f.getNColors();\n byte[] r = new byte[nc];\n byte[] g = new byte[nc];\n byte[] b = new byte[nc];\n for (int i = 0; i < nc; i++) {\n r[i] = data[i * 3];\n g[i] = data[i * 3 + 1];\n b[i] = data[i * 3 + 2];\n }\n if (f.hasTransparency()) {\n byte[] a = new byte[nc];\n for (int i = 0; i < nc; i++) a[i] = (byte) 0xFF;\n a[f.getTransparentIndex()] = 0;\n return new IndexColorModel(8, nc, r, g, b, a);\n }\n return new IndexColorModel(8, nc, r, g, b);\n }\n\n private void validateIndex(int imageIndex) throws IndexOutOfBoundsException {\n if (imageIndex < 0 || imageIndex >= getNumImages(false))\n throw new IndexOutOfBoundsException(\"Invalid image index.\");\n }\n\n public void setInput(Object input) {\n super.setInput(input);\n }\n\n public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {\n super.setInput(input, seekForwardOnly, ignoreMetadata);\n }\n\n public void setInput(Object input, boolean isStreamable) {\n super.setInput(input, isStreamable);\n if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))\n throw new IllegalArgumentException(\"Input not an ImageInputStream.\");\n }\n\n private void checkStream() throws IOException ", "post_mask_code": "\n\n public int getWidth(int imageIndex) throws IOException {\n validateIndex(imageIndex);\n return file.getImage(imageIndex).getWidth();\n }\n\n public int getHeight(int imageIndex) throws IOException {\n validateIndex(imageIndex);\n return file.getImage(imageIndex).getHeight();\n }\n\n public Iterator getImageTypes(int imageIndex) {\n validateIndex(imageIndex);\n return null;\n }\n\n /**\n * Returns the number of images.\n */\n public int getNumImages(boolean allowSearch) {\n try // Image should be loaded here already. But just in case:\n {\n readImage();\n } catch (IOException ioe) {\n // Well, now we're in trouble. But return something anyway.\n return 0;\n }\n return file.nImages();\n }\n\n // FIXME: Support metadata\n public IIOMetadata getImageMetadata(int imageIndex) {\n validateIndex(imageIndex);\n return null;\n }\n\n // FIXME: Support metadata\n public IIOMetadata getStreamMetadata() {\n return null;\n }\n\n /**\n * Reads the image indexed by imageIndex and returns it as\n * a complete BufferedImage, using a supplied ImageReadParam.\n */\n public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException, IIOException {\n validateIndex(imageIndex);\n GIFFile f = file.getImage(imageIndex);\n int width = f.getWidth();\n int height = f.getHeight();\n SampleModel sm;\n switch(f.getNColors()) {\n case 16:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 4);\n break;\n case 4:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 2);\n break;\n case 2:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1);\n break;\n default:\n sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, new int[] { 0xFF });\n break;\n }\n DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);\n WritableRaster raster = Raster.createWritableRaster(sm, db, null);\n return new BufferedImage(getPalette(imageIndex), raster, false, null);\n }\n}\n"} {"task_id": "Java_2853", "language": "Java", "task_type": "single_line", "source_file": "java/github/joekoolade/JOE/classpath-0.98/gnu/javax/imageio/gif/GIFImageReader.java", "mask_start_position": 2372, "mask_end_position": 2378, "canonical_solution": "nput);", "pre_mask_code": "package gnu.javax.imageio.gif;\n\nimport gnu.javax.imageio.IIOInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport javax.imageio.*;\nimport javax.imageio.spi.*;\nimport javax.imageio.metadata.*;\nimport javax.imageio.stream.ImageInputStream;\nimport java.util.Iterator;\nimport java.awt.image.BufferedImage;\nimport java.awt.image.IndexColorModel;\nimport java.awt.image.SampleModel;\nimport java.awt.image.MultiPixelPackedSampleModel;\nimport java.awt.image.SinglePixelPackedSampleModel;\nimport java.awt.image.DataBuffer;\nimport java.awt.image.DataBufferByte;\nimport java.awt.image.Raster;\nimport java.awt.image.WritableRaster;\n\npublic class GIFImageReader extends ImageReader {\n\n private GIFFile file;\n\n protected GIFImageReader(ImageReaderSpi originatingProvider) {\n super(originatingProvider);\n file = null;\n }\n\n private void readImage() throws IOException {\n if (file != null)\n return;\n try {\n if (input instanceof InputStream)\n file = new GIFFile((InputStream) input);\n else\n file = new GIFFile(new IIOInputStream((ImageInputStream) input));\n } catch (GIFFile.GIFException ge) {\n throw new IIOException(ge.getMessage());\n }\n }\n\n /**\n * Returns the Global/Local palette as an IndexColorModel\n */\n private IndexColorModel getPalette(int index) {\n GIFFile f = file.getImage(index);\n byte[] data = f.getRawPalette();\n int nc = f.getNColors();\n byte[] r = new byte[nc];\n byte[] g = new byte[nc];\n byte[] b = new byte[nc];\n for (int i = 0; i < nc; i++) {\n r[i] = data[i * 3];\n g[i] = data[i * 3 + 1];\n b[i] = data[i * 3 + 2];\n }\n if (f.hasTransparency()) {\n byte[] a = new byte[nc];\n for (int i = 0; i < nc; i++) a[i] = (byte) 0xFF;\n a[f.getTransparentIndex()] = 0;\n return new IndexColorModel(8, nc, r, g, b, a);\n }\n return new IndexColorModel(8, nc, r, g, b);\n }\n\n private void validateIndex(int imageIndex) throws IndexOutOfBoundsException {\n if (imageIndex < 0 || imageIndex >= getNumImages(false))\n throw new IndexOutOfBoundsException(\"Invalid image index.\");\n }\n\n public void setInput(Object input) {\n super.setInput(i", "post_mask_code": "\n }\n\n public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {\n super.setInput(input, seekForwardOnly, ignoreMetadata);\n }\n\n public void setInput(Object input, boolean isStreamable) {\n super.setInput(input, isStreamable);\n if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))\n throw new IllegalArgumentException(\"Input not an ImageInputStream.\");\n }\n\n private void checkStream() throws IOException {\n if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))\n throw new IllegalStateException(\"Input not an ImageInputStream or InputStream.\");\n if (input == null)\n throw new IllegalStateException(\"No input stream.\");\n }\n\n public int getWidth(int imageIndex) throws IOException {\n validateIndex(imageIndex);\n return file.getImage(imageIndex).getWidth();\n }\n\n public int getHeight(int imageIndex) throws IOException {\n validateIndex(imageIndex);\n return file.getImage(imageIndex).getHeight();\n }\n\n public Iterator getImageTypes(int imageIndex) {\n validateIndex(imageIndex);\n return null;\n }\n\n /**\n * Returns the number of images.\n */\n public int getNumImages(boolean allowSearch) {\n try // Image should be loaded here already. But just in case:\n {\n readImage();\n } catch (IOException ioe) {\n // Well, now we're in trouble. But return something anyway.\n return 0;\n }\n return file.nImages();\n }\n\n // FIXME: Support metadata\n public IIOMetadata getImageMetadata(int imageIndex) {\n validateIndex(imageIndex);\n return null;\n }\n\n // FIXME: Support metadata\n public IIOMetadata getStreamMetadata() {\n return null;\n }\n\n /**\n * Reads the image indexed by imageIndex and returns it as\n * a complete BufferedImage, using a supplied ImageReadParam.\n */\n public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException, IIOException {\n validateIndex(imageIndex);\n GIFFile f = file.getImage(imageIndex);\n int width = f.getWidth();\n int height = f.getHeight();\n SampleModel sm;\n switch(f.getNColors()) {\n case 16:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 4);\n break;\n case 4:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 2);\n break;\n case 2:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1);\n break;\n default:\n sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, new int[] { 0xFF });\n break;\n }\n DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);\n WritableRaster raster = Raster.createWritableRaster(sm, db, null);\n return new BufferedImage(getPalette(imageIndex), raster, false, null);\n }\n}\n"} {"task_id": "Java_2854", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/joekoolade/JOE/classpath-0.98/gnu/javax/imageio/gif/GIFImageReader.java", "mask_start_position": 3645, "mask_end_position": 3973, "canonical_solution": "public int getNumImages(boolean allowSearch) {\n try // Image should be loaded here already. But just in case:\n {\n readImage();\n } catch (IOException ioe) {\n // Well, now we're in trouble. But return something anyway.\n return 0;\n }\n return file.nImages();\n }", "pre_mask_code": "package gnu.javax.imageio.gif;\n\nimport gnu.javax.imageio.IIOInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport javax.imageio.*;\nimport javax.imageio.spi.*;\nimport javax.imageio.metadata.*;\nimport javax.imageio.stream.ImageInputStream;\nimport java.util.Iterator;\nimport java.awt.image.BufferedImage;\nimport java.awt.image.IndexColorModel;\nimport java.awt.image.SampleModel;\nimport java.awt.image.MultiPixelPackedSampleModel;\nimport java.awt.image.SinglePixelPackedSampleModel;\nimport java.awt.image.DataBuffer;\nimport java.awt.image.DataBufferByte;\nimport java.awt.image.Raster;\nimport java.awt.image.WritableRaster;\n\npublic class GIFImageReader extends ImageReader {\n\n private GIFFile file;\n\n protected GIFImageReader(ImageReaderSpi originatingProvider) {\n super(originatingProvider);\n file = null;\n }\n\n private void readImage() throws IOException {\n if (file != null)\n return;\n try {\n if (input instanceof InputStream)\n file = new GIFFile((InputStream) input);\n else\n file = new GIFFile(new IIOInputStream((ImageInputStream) input));\n } catch (GIFFile.GIFException ge) {\n throw new IIOException(ge.getMessage());\n }\n }\n\n /**\n * Returns the Global/Local palette as an IndexColorModel\n */\n private IndexColorModel getPalette(int index) {\n GIFFile f = file.getImage(index);\n byte[] data = f.getRawPalette();\n int nc = f.getNColors();\n byte[] r = new byte[nc];\n byte[] g = new byte[nc];\n byte[] b = new byte[nc];\n for (int i = 0; i < nc; i++) {\n r[i] = data[i * 3];\n g[i] = data[i * 3 + 1];\n b[i] = data[i * 3 + 2];\n }\n if (f.hasTransparency()) {\n byte[] a = new byte[nc];\n for (int i = 0; i < nc; i++) a[i] = (byte) 0xFF;\n a[f.getTransparentIndex()] = 0;\n return new IndexColorModel(8, nc, r, g, b, a);\n }\n return new IndexColorModel(8, nc, r, g, b);\n }\n\n private void validateIndex(int imageIndex) throws IndexOutOfBoundsException {\n if (imageIndex < 0 || imageIndex >= getNumImages(false))\n throw new IndexOutOfBoundsException(\"Invalid image index.\");\n }\n\n public void setInput(Object input) {\n super.setInput(input);\n }\n\n public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {\n super.setInput(input, seekForwardOnly, ignoreMetadata);\n }\n\n public void setInput(Object input, boolean isStreamable) {\n super.setInput(input, isStreamable);\n if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))\n throw new IllegalArgumentException(\"Input not an ImageInputStream.\");\n }\n\n private void checkStream() throws IOException {\n if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))\n throw new IllegalStateException(\"Input not an ImageInputStream or InputStream.\");\n if (input == null)\n throw new IllegalStateException(\"No input stream.\");\n }\n\n public int getWidth(int imageIndex) throws IOException {\n validateIndex(imageIndex);\n return file.getImage(imageIndex).getWidth();\n }\n\n public int getHeight(int imageIndex) throws IOException {\n validateIndex(imageIndex);\n return file.getImage(imageIndex).getHeight();\n }\n\n public Iterator getImageTypes(int imageIndex) {\n validateIndex(imageIndex);\n return null;\n }\n\n /**\n * Returns the number of images.\n */\n ", "post_mask_code": "\n\n // FIXME: Support metadata\n public IIOMetadata getImageMetadata(int imageIndex) {\n validateIndex(imageIndex);\n return null;\n }\n\n // FIXME: Support metadata\n public IIOMetadata getStreamMetadata() {\n return null;\n }\n\n /**\n * Reads the image indexed by imageIndex and returns it as\n * a complete BufferedImage, using a supplied ImageReadParam.\n */\n public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException, IIOException {\n validateIndex(imageIndex);\n GIFFile f = file.getImage(imageIndex);\n int width = f.getWidth();\n int height = f.getHeight();\n SampleModel sm;\n switch(f.getNColors()) {\n case 16:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 4);\n break;\n case 4:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 2);\n break;\n case 2:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1);\n break;\n default:\n sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, new int[] { 0xFF });\n break;\n }\n DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);\n WritableRaster raster = Raster.createWritableRaster(sm, db, null);\n return new BufferedImage(getPalette(imageIndex), raster, false, null);\n }\n}\n"} {"task_id": "Java_2855", "language": "Java", "task_type": "for_statement", "source_file": "java/github/joekoolade/JOE/classpath-0.98/gnu/javax/imageio/gif/GIFImageReader.java", "mask_start_position": 1630, "mask_end_position": 1774, "canonical_solution": "for (int i = 0; i < nc; i++) {\n r[i] = data[i * 3];\n g[i] = data[i * 3 + 1];\n b[i] = data[i * 3 + 2];\n }", "pre_mask_code": "package gnu.javax.imageio.gif;\n\nimport gnu.javax.imageio.IIOInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport javax.imageio.*;\nimport javax.imageio.spi.*;\nimport javax.imageio.metadata.*;\nimport javax.imageio.stream.ImageInputStream;\nimport java.util.Iterator;\nimport java.awt.image.BufferedImage;\nimport java.awt.image.IndexColorModel;\nimport java.awt.image.SampleModel;\nimport java.awt.image.MultiPixelPackedSampleModel;\nimport java.awt.image.SinglePixelPackedSampleModel;\nimport java.awt.image.DataBuffer;\nimport java.awt.image.DataBufferByte;\nimport java.awt.image.Raster;\nimport java.awt.image.WritableRaster;\n\npublic class GIFImageReader extends ImageReader {\n\n private GIFFile file;\n\n protected GIFImageReader(ImageReaderSpi originatingProvider) {\n super(originatingProvider);\n file = null;\n }\n\n private void readImage() throws IOException {\n if (file != null)\n return;\n try {\n if (input instanceof InputStream)\n file = new GIFFile((InputStream) input);\n else\n file = new GIFFile(new IIOInputStream((ImageInputStream) input));\n } catch (GIFFile.GIFException ge) {\n throw new IIOException(ge.getMessage());\n }\n }\n\n /**\n * Returns the Global/Local palette as an IndexColorModel\n */\n private IndexColorModel getPalette(int index) {\n GIFFile f = file.getImage(index);\n byte[] data = f.getRawPalette();\n int nc = f.getNColors();\n byte[] r = new byte[nc];\n byte[] g = new byte[nc];\n byte[] b = new byte[nc];\n ", "post_mask_code": "\n if (f.hasTransparency()) {\n byte[] a = new byte[nc];\n for (int i = 0; i < nc; i++) a[i] = (byte) 0xFF;\n a[f.getTransparentIndex()] = 0;\n return new IndexColorModel(8, nc, r, g, b, a);\n }\n return new IndexColorModel(8, nc, r, g, b);\n }\n\n private void validateIndex(int imageIndex) throws IndexOutOfBoundsException {\n if (imageIndex < 0 || imageIndex >= getNumImages(false))\n throw new IndexOutOfBoundsException(\"Invalid image index.\");\n }\n\n public void setInput(Object input) {\n super.setInput(input);\n }\n\n public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {\n super.setInput(input, seekForwardOnly, ignoreMetadata);\n }\n\n public void setInput(Object input, boolean isStreamable) {\n super.setInput(input, isStreamable);\n if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))\n throw new IllegalArgumentException(\"Input not an ImageInputStream.\");\n }\n\n private void checkStream() throws IOException {\n if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))\n throw new IllegalStateException(\"Input not an ImageInputStream or InputStream.\");\n if (input == null)\n throw new IllegalStateException(\"No input stream.\");\n }\n\n public int getWidth(int imageIndex) throws IOException {\n validateIndex(imageIndex);\n return file.getImage(imageIndex).getWidth();\n }\n\n public int getHeight(int imageIndex) throws IOException {\n validateIndex(imageIndex);\n return file.getImage(imageIndex).getHeight();\n }\n\n public Iterator getImageTypes(int imageIndex) {\n validateIndex(imageIndex);\n return null;\n }\n\n /**\n * Returns the number of images.\n */\n public int getNumImages(boolean allowSearch) {\n try // Image should be loaded here already. But just in case:\n {\n readImage();\n } catch (IOException ioe) {\n // Well, now we're in trouble. But return something anyway.\n return 0;\n }\n return file.nImages();\n }\n\n // FIXME: Support metadata\n public IIOMetadata getImageMetadata(int imageIndex) {\n validateIndex(imageIndex);\n return null;\n }\n\n // FIXME: Support metadata\n public IIOMetadata getStreamMetadata() {\n return null;\n }\n\n /**\n * Reads the image indexed by imageIndex and returns it as\n * a complete BufferedImage, using a supplied ImageReadParam.\n */\n public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException, IIOException {\n validateIndex(imageIndex);\n GIFFile f = file.getImage(imageIndex);\n int width = f.getWidth();\n int height = f.getHeight();\n SampleModel sm;\n switch(f.getNColors()) {\n case 16:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 4);\n break;\n case 4:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 2);\n break;\n case 2:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1);\n break;\n default:\n sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, new int[] { 0xFF });\n break;\n }\n DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);\n WritableRaster raster = Raster.createWritableRaster(sm, db, null);\n return new BufferedImage(getPalette(imageIndex), raster, false, null);\n }\n}\n"} {"task_id": "Java_2856", "language": "Java", "task_type": "try_statement", "source_file": "java/github/joekoolade/JOE/classpath-0.98/gnu/javax/imageio/gif/GIFImageReader.java", "mask_start_position": 955, "mask_end_position": 1269, "canonical_solution": "try {\n if (input instanceof InputStream)\n file = new GIFFile((InputStream) input);\n else\n file = new GIFFile(new IIOInputStream((ImageInputStream) input));\n } catch (GIFFile.GIFException ge) {\n throw new IIOException(ge.getMessage());\n }", "pre_mask_code": "package gnu.javax.imageio.gif;\n\nimport gnu.javax.imageio.IIOInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport javax.imageio.*;\nimport javax.imageio.spi.*;\nimport javax.imageio.metadata.*;\nimport javax.imageio.stream.ImageInputStream;\nimport java.util.Iterator;\nimport java.awt.image.BufferedImage;\nimport java.awt.image.IndexColorModel;\nimport java.awt.image.SampleModel;\nimport java.awt.image.MultiPixelPackedSampleModel;\nimport java.awt.image.SinglePixelPackedSampleModel;\nimport java.awt.image.DataBuffer;\nimport java.awt.image.DataBufferByte;\nimport java.awt.image.Raster;\nimport java.awt.image.WritableRaster;\n\npublic class GIFImageReader extends ImageReader {\n\n private GIFFile file;\n\n protected GIFImageReader(ImageReaderSpi originatingProvider) {\n super(originatingProvider);\n file = null;\n }\n\n private void readImage() throws IOException {\n if (file != null)\n return;\n ", "post_mask_code": "\n }\n\n /**\n * Returns the Global/Local palette as an IndexColorModel\n */\n private IndexColorModel getPalette(int index) {\n GIFFile f = file.getImage(index);\n byte[] data = f.getRawPalette();\n int nc = f.getNColors();\n byte[] r = new byte[nc];\n byte[] g = new byte[nc];\n byte[] b = new byte[nc];\n for (int i = 0; i < nc; i++) {\n r[i] = data[i * 3];\n g[i] = data[i * 3 + 1];\n b[i] = data[i * 3 + 2];\n }\n if (f.hasTransparency()) {\n byte[] a = new byte[nc];\n for (int i = 0; i < nc; i++) a[i] = (byte) 0xFF;\n a[f.getTransparentIndex()] = 0;\n return new IndexColorModel(8, nc, r, g, b, a);\n }\n return new IndexColorModel(8, nc, r, g, b);\n }\n\n private void validateIndex(int imageIndex) throws IndexOutOfBoundsException {\n if (imageIndex < 0 || imageIndex >= getNumImages(false))\n throw new IndexOutOfBoundsException(\"Invalid image index.\");\n }\n\n public void setInput(Object input) {\n super.setInput(input);\n }\n\n public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {\n super.setInput(input, seekForwardOnly, ignoreMetadata);\n }\n\n public void setInput(Object input, boolean isStreamable) {\n super.setInput(input, isStreamable);\n if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))\n throw new IllegalArgumentException(\"Input not an ImageInputStream.\");\n }\n\n private void checkStream() throws IOException {\n if (!(input instanceof ImageInputStream) && !(input instanceof InputStream))\n throw new IllegalStateException(\"Input not an ImageInputStream or InputStream.\");\n if (input == null)\n throw new IllegalStateException(\"No input stream.\");\n }\n\n public int getWidth(int imageIndex) throws IOException {\n validateIndex(imageIndex);\n return file.getImage(imageIndex).getWidth();\n }\n\n public int getHeight(int imageIndex) throws IOException {\n validateIndex(imageIndex);\n return file.getImage(imageIndex).getHeight();\n }\n\n public Iterator getImageTypes(int imageIndex) {\n validateIndex(imageIndex);\n return null;\n }\n\n /**\n * Returns the number of images.\n */\n public int getNumImages(boolean allowSearch) {\n try // Image should be loaded here already. But just in case:\n {\n readImage();\n } catch (IOException ioe) {\n // Well, now we're in trouble. But return something anyway.\n return 0;\n }\n return file.nImages();\n }\n\n // FIXME: Support metadata\n public IIOMetadata getImageMetadata(int imageIndex) {\n validateIndex(imageIndex);\n return null;\n }\n\n // FIXME: Support metadata\n public IIOMetadata getStreamMetadata() {\n return null;\n }\n\n /**\n * Reads the image indexed by imageIndex and returns it as\n * a complete BufferedImage, using a supplied ImageReadParam.\n */\n public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException, IIOException {\n validateIndex(imageIndex);\n GIFFile f = file.getImage(imageIndex);\n int width = f.getWidth();\n int height = f.getHeight();\n SampleModel sm;\n switch(f.getNColors()) {\n case 16:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 4);\n break;\n case 4:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 2);\n break;\n case 2:\n sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, 1);\n break;\n default:\n sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, new int[] { 0xFF });\n break;\n }\n DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);\n WritableRaster raster = Raster.createWritableRaster(sm, db, null);\n return new BufferedImage(getPalette(imageIndex), raster, false, null);\n }\n}\n"} {"task_id": "Java_2857", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SonarSource/sonarqube/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/NodeHealthProviderImpl.java", "mask_start_position": 2217, "mask_end_position": 2304, "canonical_solution": "private static Supplier missingPropertyISE(String propertyName) ", "pre_mask_code": "/*\n * SonarQube\n * mailto:info AT sonarsource DOT com\n *\n */\npackage org.sonar.server.health;\n\nimport java.util.function.Supplier;\nimport org.sonar.api.config.Configuration;\nimport org.sonar.api.platform.Server;\nimport org.sonar.process.NetworkUtils;\nimport org.sonar.process.cluster.health.NodeDetails;\nimport org.sonar.process.cluster.health.NodeHealth;\nimport org.sonar.process.cluster.health.NodeHealthProvider;\nimport static java.lang.String.format;\nimport static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST;\nimport static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME;\nimport static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT;\nimport static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder;\nimport static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder;\n\npublic class NodeHealthProviderImpl implements NodeHealthProvider {\n\n private final HealthChecker healthChecker;\n\n private final NodeHealth.Builder nodeHealthBuilder;\n\n private final NodeDetails nodeDetails;\n\n public NodeHealthProviderImpl(Configuration configuration, HealthChecker healthChecker, Server server, NetworkUtils networkUtils) {\n this.healthChecker = healthChecker;\n this.nodeHealthBuilder = newNodeHealthBuilder();\n this.nodeDetails = newNodeDetailsBuilder().setName(computeName(configuration)).setType(NodeDetails.Type.APPLICATION).setHost(computeHost(configuration, networkUtils)).setPort(computePort(configuration)).setStartedAt(server.getStartedAt().getTime()).build();\n }\n\n private static String computeName(Configuration configuration) {\n return configuration.get(CLUSTER_NODE_NAME.getKey()).orElseThrow(missingPropertyISE(CLUSTER_NODE_NAME.getKey()));\n }\n\n private static String computeHost(Configuration configuration, NetworkUtils networkUtils) {\n return configuration.get(CLUSTER_NODE_HOST.getKey()).filter(s -> !s.isEmpty()).orElseGet(networkUtils::getHostname);\n }\n\n private static int computePort(Configuration configuration) {\n return configuration.getInt(CLUSTER_NODE_HZ_PORT.getKey()).orElseThrow(missingPropertyISE(CLUSTER_NODE_HZ_PORT.getKey()));\n }\n\n ", "post_mask_code": "{\n return () -> new IllegalStateException(format(\"Property %s is not defined\", propertyName));\n }\n\n @Override\n public NodeHealth get() {\n Health nodeHealth = healthChecker.checkNode();\n this.nodeHealthBuilder.clearCauses().setStatus(NodeHealth.Status.valueOf(nodeHealth.getStatus().name()));\n nodeHealth.getCauses().forEach(this.nodeHealthBuilder::addCause);\n return this.nodeHealthBuilder.setDetails(nodeDetails).build();\n }\n}\n"} {"task_id": "Java_2858", "language": "Java", "task_type": "method_body", "source_file": "java/github/SonarSource/sonarqube/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/NodeHealthProviderImpl.java", "mask_start_position": 2304, "mask_end_position": 2411, "canonical_solution": "{\n return () -> new IllegalStateException(format(\"Property %s is not defined\", propertyName));\n }", "pre_mask_code": "/*\n * SonarQube\n * mailto:info AT sonarsource DOT com\n *\n */\npackage org.sonar.server.health;\n\nimport java.util.function.Supplier;\nimport org.sonar.api.config.Configuration;\nimport org.sonar.api.platform.Server;\nimport org.sonar.process.NetworkUtils;\nimport org.sonar.process.cluster.health.NodeDetails;\nimport org.sonar.process.cluster.health.NodeHealth;\nimport org.sonar.process.cluster.health.NodeHealthProvider;\nimport static java.lang.String.format;\nimport static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST;\nimport static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME;\nimport static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT;\nimport static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder;\nimport static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder;\n\npublic class NodeHealthProviderImpl implements NodeHealthProvider {\n\n private final HealthChecker healthChecker;\n\n private final NodeHealth.Builder nodeHealthBuilder;\n\n private final NodeDetails nodeDetails;\n\n public NodeHealthProviderImpl(Configuration configuration, HealthChecker healthChecker, Server server, NetworkUtils networkUtils) {\n this.healthChecker = healthChecker;\n this.nodeHealthBuilder = newNodeHealthBuilder();\n this.nodeDetails = newNodeDetailsBuilder().setName(computeName(configuration)).setType(NodeDetails.Type.APPLICATION).setHost(computeHost(configuration, networkUtils)).setPort(computePort(configuration)).setStartedAt(server.getStartedAt().getTime()).build();\n }\n\n private static String computeName(Configuration configuration) {\n return configuration.get(CLUSTER_NODE_NAME.getKey()).orElseThrow(missingPropertyISE(CLUSTER_NODE_NAME.getKey()));\n }\n\n private static String computeHost(Configuration configuration, NetworkUtils networkUtils) {\n return configuration.get(CLUSTER_NODE_HOST.getKey()).filter(s -> !s.isEmpty()).orElseGet(networkUtils::getHostname);\n }\n\n private static int computePort(Configuration configuration) {\n return configuration.getInt(CLUSTER_NODE_HZ_PORT.getKey()).orElseThrow(missingPropertyISE(CLUSTER_NODE_HZ_PORT.getKey()));\n }\n\n private static Supplier missingPropertyISE(String propertyName) ", "post_mask_code": "\n\n @Override\n public NodeHealth get() {\n Health nodeHealth = healthChecker.checkNode();\n this.nodeHealthBuilder.clearCauses().setStatus(NodeHealth.Status.valueOf(nodeHealth.getStatus().name()));\n nodeHealth.getCauses().forEach(this.nodeHealthBuilder::addCause);\n return this.nodeHealthBuilder.setDetails(nodeDetails).build();\n }\n}\n"} {"task_id": "Java_2859", "language": "Java", "task_type": "single_line", "source_file": "java/github/SonarSource/sonarqube/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/NodeHealthProviderImpl.java", "mask_start_position": 2471, "mask_end_position": 2511, "canonical_solution": " nodeHealth = healthChecker.checkNode();", "pre_mask_code": "/*\n * SonarQube\n * mailto:info AT sonarsource DOT com\n *\n */\npackage org.sonar.server.health;\n\nimport java.util.function.Supplier;\nimport org.sonar.api.config.Configuration;\nimport org.sonar.api.platform.Server;\nimport org.sonar.process.NetworkUtils;\nimport org.sonar.process.cluster.health.NodeDetails;\nimport org.sonar.process.cluster.health.NodeHealth;\nimport org.sonar.process.cluster.health.NodeHealthProvider;\nimport static java.lang.String.format;\nimport static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST;\nimport static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME;\nimport static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT;\nimport static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder;\nimport static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder;\n\npublic class NodeHealthProviderImpl implements NodeHealthProvider {\n\n private final HealthChecker healthChecker;\n\n private final NodeHealth.Builder nodeHealthBuilder;\n\n private final NodeDetails nodeDetails;\n\n public NodeHealthProviderImpl(Configuration configuration, HealthChecker healthChecker, Server server, NetworkUtils networkUtils) {\n this.healthChecker = healthChecker;\n this.nodeHealthBuilder = newNodeHealthBuilder();\n this.nodeDetails = newNodeDetailsBuilder().setName(computeName(configuration)).setType(NodeDetails.Type.APPLICATION).setHost(computeHost(configuration, networkUtils)).setPort(computePort(configuration)).setStartedAt(server.getStartedAt().getTime()).build();\n }\n\n private static String computeName(Configuration configuration) {\n return configuration.get(CLUSTER_NODE_NAME.getKey()).orElseThrow(missingPropertyISE(CLUSTER_NODE_NAME.getKey()));\n }\n\n private static String computeHost(Configuration configuration, NetworkUtils networkUtils) {\n return configuration.get(CLUSTER_NODE_HOST.getKey()).filter(s -> !s.isEmpty()).orElseGet(networkUtils::getHostname);\n }\n\n private static int computePort(Configuration configuration) {\n return configuration.getInt(CLUSTER_NODE_HZ_PORT.getKey()).orElseThrow(missingPropertyISE(CLUSTER_NODE_HZ_PORT.getKey()));\n }\n\n private static Supplier missingPropertyISE(String propertyName) {\n return () -> new IllegalStateException(format(\"Property %s is not defined\", propertyName));\n }\n\n @Override\n public NodeHealth get() {\n Health", "post_mask_code": "\n this.nodeHealthBuilder.clearCauses().setStatus(NodeHealth.Status.valueOf(nodeHealth.getStatus().name()));\n nodeHealth.getCauses().forEach(this.nodeHealthBuilder::addCause);\n return this.nodeHealthBuilder.setDetails(nodeDetails).build();\n }\n}\n"} {"task_id": "Java_2860", "language": "Java", "task_type": "method_signature", "source_file": "java/github/xiaoling/figer/src/main/java/edu/washington/cs/figer/FigerSystem.java", "mask_start_position": 3606, "mask_end_position": 3693, "canonical_solution": "public String predict(Annotation annotation, int sentId, int startToken, int endToken) ", "pre_mask_code": "package edu.washington.cs.figer;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Hashtable;\nimport java.util.List;\nimport java.util.Scanner;\nimport java.util.Set;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport edu.stanford.nlp.ling.CoreAnnotations.NamedEntityTagAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.OriginalTextAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;\nimport edu.stanford.nlp.ling.CoreLabel;\nimport edu.stanford.nlp.pipeline.Annotation;\nimport edu.stanford.nlp.util.CoreMap;\nimport edu.stanford.nlp.util.Pair;\nimport edu.stanford.nlp.util.StringUtils;\nimport edu.washington.cs.figer.analysis.MapType;\nimport edu.washington.cs.figer.analysis.Preprocessing;\nimport edu.washington.cs.figer.analysis.feature.NERFeature;\nimport edu.washington.cs.figer.data.EntityProtos.Mention;\nimport edu.washington.cs.figer.data.EntityProtos.Mention.Dependency;\nimport edu.washington.cs.figer.data.Feature;\nimport edu.washington.cs.figer.data.FeatureFactory;\nimport edu.washington.cs.figer.data.Instance;\nimport edu.washington.cs.figer.ml.Model;\nimport edu.washington.cs.figer.ml.MultiLabelLogisticRegression;\nimport edu.washington.cs.figer.ml.MultiLabelPerceptronNERClassifier;\nimport edu.washington.cs.figer.ml.NERClassifier;\nimport edu.washington.cs.figer.util.FileUtil;\nimport edu.washington.cs.figer.util.StanfordDependencyResolver;\nimport edu.washington.cs.figer.util.Timer;\nimport edu.washington.cs.figer.util.X;\nimport gnu.trove.list.TIntList;\nimport gnu.trove.list.array.TIntArrayList;\n\npublic class FigerSystem {\n\n private static Logger logger = LoggerFactory.getLogger(FigerSystem.class);\n\n private static FigerSystem instance = null;\n\n public static String configFile = \"config/figer.conf\";\n\n // useful variables\n public Model model = new MultiLabelLogisticRegression();\n\n public NERClassifier classifier = null;\n\n public NERFeature nerFeature = null;\n\n // debug variables\n public static HashSet mentions = new HashSet();\n\n public synchronized static FigerSystem instance() {\n if (instance == null) {\n instance = new FigerSystem();\n }\n return instance;\n }\n\n private FigerSystem() {\n X.parseArgs(configFile);\n Timer timer = new Timer();\n model.debug = X.getBoolean(\"debugModel\");\n // read all tags\n MapType.typeFile = X.tagset;\n MapType.init();\n for (String newType : MapType.mapping.values()) {\n model.labelFactory.getLabel(newType);\n }\n logger.info(\"labels:\\t\" + model.labelFactory.allLabels);\n // read the model\n if (X.methodS == X.PERCEPTRON) {\n timer.task = \"reading the model \" + X.modelFile;\n timer.start();\n model.readModel(X.modelFile);\n model.featureFactory.isTrain = false;\n model.labelFactory.isTrain = false;\n timer.endPrint();\n // init NER Features\n nerFeature = new NERFeature(model);\n nerFeature.init();\n MultiLabelLogisticRegression.prob_threshold = X.getDouble(\"prob_threshold\");\n classifier = new MultiLabelPerceptronNERClassifier(model.infer);\n }\n }\n\n ", "post_mask_code": "{\n Mention m = buildMention(annotation, sentId, startToken, endToken);\n // features\n ArrayList features = new ArrayList();\n nerFeature.extract(m, features);\n return predict(features);\n }\n\n public Mention buildMention(Annotation annotation, int sentId, int startToken, int endToken) {\n CoreMap sentAnn = annotation.get(SentencesAnnotation.class).get(sentId);\n List tokens = sentAnn.get(TokensAnnotation.class);\n // create a Mention object\n Mention.Builder m = Mention.newBuilder();\n m.setStart(startToken);\n m.setEnd(endToken);\n for (int i = 0; i < tokens.size(); i++) {\n m.addTokens(tokens.get(i).get(OriginalTextAnnotation.class));\n m.addPosTags(tokens.get(i).get(PartOfSpeechAnnotation.class));\n }\n m.setEntityName(\"\");\n m.setFileid(\"on-the-fly\");\n m.setSentid(sentId);\n // dependency\n String depStr = StanfordDependencyResolver.getString(sentAnn);\n if (depStr != null) {\n for (String d : depStr.split(\"\\t\")) {\n Matcher match = Preprocessing.depPattern.matcher(d);\n if (match.find()) {\n m.addDeps(Dependency.newBuilder().setType(match.group(1)).setGov(Integer.parseInt(match.group(3)) - 1).setDep(Integer.parseInt(match.group(5)) - 1).build());\n } else {\n }\n }\n }\n return m.build();\n }\n\n public String predict(List features) {\n try {\n Instance inst = (Instance) X.instanceClass.newInstance();\n for (String fea : features) {\n Feature f = model.featureFactory.getFeature(fea);\n FeatureFactory.setValue(inst, f, fea);\n }\n Hashtable pool = new Hashtable();\n TIntList entity = new TIntArrayList();\n classifier.predict(inst, pool, entity, model);\n String plabels = pool.get(entity);\n return plabels;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n // only use the following tag set to find named entities\n private static final Set validTags = new HashSet(Arrays.asList(new String[] { \"PERSON\", \"ORGANIZATION\", \"LOCATION\", \"MISC\", \"O\" }));\n\n public static List> getNamedEntityMentions(CoreMap sentence) {\n List> offsets = new ArrayList>();\n String prevTag = \"O\";\n int tid = 0;\n int start = -1;\n for (CoreLabel token : sentence.get(TokensAnnotation.class)) {\n String tag = token.get(NamedEntityTagAnnotation.class);\n if (!validTags.contains(tag)) {\n tag = \"O\";\n }\n if (tag.equals(prevTag)) {\n } else {\n if (tag.equals(\"O\")) {\n offsets.add(Pair.makePair(start, tid));\n start = -1;\n } else {\n if (prevTag.equals(\"O\")) {\n start = tid;\n } else {\n offsets.add(Pair.makePair(start, tid));\n start = tid;\n }\n }\n }\n prevTag = tag;\n tid++;\n }\n if (!prevTag.equals(\"O\")) {\n offsets.add(Pair.makePair(start, tid));\n }\n return offsets;\n }\n\n private static void usage() {\n System.out.println(\"sbt \\\"runMain edu.washington.cs.figer.FigerSystem [config_file] text_file\\\"\");\n System.out.println(\" [config_file] is optional with a default value \\\"config/figer.conf\\\"\");\n }\n\n public static void main(String[] args) {\n String textFile = null;\n if (args.length == 1) {\n textFile = args[0];\n } else if (args.length == 2) {\n configFile = args[0];\n textFile = args[1];\n } else {\n usage();\n System.exit(0);\n }\n // initialize the system\n FigerSystem sys = instance();\n Preprocessing.initPipeline();\n // preprocess the text\n List list = FileUtil.getLinesFromFile(textFile);\n for (int i = 0; i < list.size(); i++) {\n Annotation annotation = new Annotation(list.get(i));\n Preprocessing.pipeline.annotate(annotation);\n // for each sentence\n int sentId = 0;\n for (CoreMap sentence : annotation.get(SentencesAnnotation.class)) {\n System.out.println(\"[l\" + i + \"][s\" + sentId + \"]tokenized sentence=\" + StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class)));\n List> entityMentionOffsets = getNamedEntityMentions(sentence);\n for (Pair offset : entityMentionOffsets) {\n String label = sys.predict(annotation, sentId, offset.first, offset.second);\n String mention = StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class).subList(offset.first, offset.second));\n System.out.println(\"[l\" + i + \"][s\" + sentId + \"]mention\" + mention + \"(\" + offset.first + \",\" + offset.second + \") = \" + mention + \", pred = \" + label);\n }\n sentId++;\n }\n }\n }\n}\n"} {"task_id": "Java_2861", "language": "Java", "task_type": "method_body", "source_file": "java/github/xiaoling/figer/src/main/java/edu/washington/cs/figer/FigerSystem.java", "mask_start_position": 2449, "mask_end_position": 2565, "canonical_solution": "{\n if (instance == null) {\n instance = new FigerSystem();\n }\n return instance;\n }", "pre_mask_code": "package edu.washington.cs.figer;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Hashtable;\nimport java.util.List;\nimport java.util.Scanner;\nimport java.util.Set;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport edu.stanford.nlp.ling.CoreAnnotations.NamedEntityTagAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.OriginalTextAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;\nimport edu.stanford.nlp.ling.CoreLabel;\nimport edu.stanford.nlp.pipeline.Annotation;\nimport edu.stanford.nlp.util.CoreMap;\nimport edu.stanford.nlp.util.Pair;\nimport edu.stanford.nlp.util.StringUtils;\nimport edu.washington.cs.figer.analysis.MapType;\nimport edu.washington.cs.figer.analysis.Preprocessing;\nimport edu.washington.cs.figer.analysis.feature.NERFeature;\nimport edu.washington.cs.figer.data.EntityProtos.Mention;\nimport edu.washington.cs.figer.data.EntityProtos.Mention.Dependency;\nimport edu.washington.cs.figer.data.Feature;\nimport edu.washington.cs.figer.data.FeatureFactory;\nimport edu.washington.cs.figer.data.Instance;\nimport edu.washington.cs.figer.ml.Model;\nimport edu.washington.cs.figer.ml.MultiLabelLogisticRegression;\nimport edu.washington.cs.figer.ml.MultiLabelPerceptronNERClassifier;\nimport edu.washington.cs.figer.ml.NERClassifier;\nimport edu.washington.cs.figer.util.FileUtil;\nimport edu.washington.cs.figer.util.StanfordDependencyResolver;\nimport edu.washington.cs.figer.util.Timer;\nimport edu.washington.cs.figer.util.X;\nimport gnu.trove.list.TIntList;\nimport gnu.trove.list.array.TIntArrayList;\n\npublic class FigerSystem {\n\n private static Logger logger = LoggerFactory.getLogger(FigerSystem.class);\n\n private static FigerSystem instance = null;\n\n public static String configFile = \"config/figer.conf\";\n\n // useful variables\n public Model model = new MultiLabelLogisticRegression();\n\n public NERClassifier classifier = null;\n\n public NERFeature nerFeature = null;\n\n // debug variables\n public static HashSet mentions = new HashSet();\n\n public synchronized static FigerSystem instance() ", "post_mask_code": "\n\n private FigerSystem() {\n X.parseArgs(configFile);\n Timer timer = new Timer();\n model.debug = X.getBoolean(\"debugModel\");\n // read all tags\n MapType.typeFile = X.tagset;\n MapType.init();\n for (String newType : MapType.mapping.values()) {\n model.labelFactory.getLabel(newType);\n }\n logger.info(\"labels:\\t\" + model.labelFactory.allLabels);\n // read the model\n if (X.methodS == X.PERCEPTRON) {\n timer.task = \"reading the model \" + X.modelFile;\n timer.start();\n model.readModel(X.modelFile);\n model.featureFactory.isTrain = false;\n model.labelFactory.isTrain = false;\n timer.endPrint();\n // init NER Features\n nerFeature = new NERFeature(model);\n nerFeature.init();\n MultiLabelLogisticRegression.prob_threshold = X.getDouble(\"prob_threshold\");\n classifier = new MultiLabelPerceptronNERClassifier(model.infer);\n }\n }\n\n public String predict(Annotation annotation, int sentId, int startToken, int endToken) {\n Mention m = buildMention(annotation, sentId, startToken, endToken);\n // features\n ArrayList features = new ArrayList();\n nerFeature.extract(m, features);\n return predict(features);\n }\n\n public Mention buildMention(Annotation annotation, int sentId, int startToken, int endToken) {\n CoreMap sentAnn = annotation.get(SentencesAnnotation.class).get(sentId);\n List tokens = sentAnn.get(TokensAnnotation.class);\n // create a Mention object\n Mention.Builder m = Mention.newBuilder();\n m.setStart(startToken);\n m.setEnd(endToken);\n for (int i = 0; i < tokens.size(); i++) {\n m.addTokens(tokens.get(i).get(OriginalTextAnnotation.class));\n m.addPosTags(tokens.get(i).get(PartOfSpeechAnnotation.class));\n }\n m.setEntityName(\"\");\n m.setFileid(\"on-the-fly\");\n m.setSentid(sentId);\n // dependency\n String depStr = StanfordDependencyResolver.getString(sentAnn);\n if (depStr != null) {\n for (String d : depStr.split(\"\\t\")) {\n Matcher match = Preprocessing.depPattern.matcher(d);\n if (match.find()) {\n m.addDeps(Dependency.newBuilder().setType(match.group(1)).setGov(Integer.parseInt(match.group(3)) - 1).setDep(Integer.parseInt(match.group(5)) - 1).build());\n } else {\n }\n }\n }\n return m.build();\n }\n\n public String predict(List features) {\n try {\n Instance inst = (Instance) X.instanceClass.newInstance();\n for (String fea : features) {\n Feature f = model.featureFactory.getFeature(fea);\n FeatureFactory.setValue(inst, f, fea);\n }\n Hashtable pool = new Hashtable();\n TIntList entity = new TIntArrayList();\n classifier.predict(inst, pool, entity, model);\n String plabels = pool.get(entity);\n return plabels;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n // only use the following tag set to find named entities\n private static final Set validTags = new HashSet(Arrays.asList(new String[] { \"PERSON\", \"ORGANIZATION\", \"LOCATION\", \"MISC\", \"O\" }));\n\n public static List> getNamedEntityMentions(CoreMap sentence) {\n List> offsets = new ArrayList>();\n String prevTag = \"O\";\n int tid = 0;\n int start = -1;\n for (CoreLabel token : sentence.get(TokensAnnotation.class)) {\n String tag = token.get(NamedEntityTagAnnotation.class);\n if (!validTags.contains(tag)) {\n tag = \"O\";\n }\n if (tag.equals(prevTag)) {\n } else {\n if (tag.equals(\"O\")) {\n offsets.add(Pair.makePair(start, tid));\n start = -1;\n } else {\n if (prevTag.equals(\"O\")) {\n start = tid;\n } else {\n offsets.add(Pair.makePair(start, tid));\n start = tid;\n }\n }\n }\n prevTag = tag;\n tid++;\n }\n if (!prevTag.equals(\"O\")) {\n offsets.add(Pair.makePair(start, tid));\n }\n return offsets;\n }\n\n private static void usage() {\n System.out.println(\"sbt \\\"runMain edu.washington.cs.figer.FigerSystem [config_file] text_file\\\"\");\n System.out.println(\" [config_file] is optional with a default value \\\"config/figer.conf\\\"\");\n }\n\n public static void main(String[] args) {\n String textFile = null;\n if (args.length == 1) {\n textFile = args[0];\n } else if (args.length == 2) {\n configFile = args[0];\n textFile = args[1];\n } else {\n usage();\n System.exit(0);\n }\n // initialize the system\n FigerSystem sys = instance();\n Preprocessing.initPipeline();\n // preprocess the text\n List list = FileUtil.getLinesFromFile(textFile);\n for (int i = 0; i < list.size(); i++) {\n Annotation annotation = new Annotation(list.get(i));\n Preprocessing.pipeline.annotate(annotation);\n // for each sentence\n int sentId = 0;\n for (CoreMap sentence : annotation.get(SentencesAnnotation.class)) {\n System.out.println(\"[l\" + i + \"][s\" + sentId + \"]tokenized sentence=\" + StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class)));\n List> entityMentionOffsets = getNamedEntityMentions(sentence);\n for (Pair offset : entityMentionOffsets) {\n String label = sys.predict(annotation, sentId, offset.first, offset.second);\n String mention = StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class).subList(offset.first, offset.second));\n System.out.println(\"[l\" + i + \"][s\" + sentId + \"]mention\" + mention + \"(\" + offset.first + \",\" + offset.second + \") = \" + mention + \", pred = \" + label);\n }\n sentId++;\n }\n }\n }\n}\n"} {"task_id": "Java_2862", "language": "Java", "task_type": "single_line", "source_file": "java/github/xiaoling/figer/src/main/java/edu/washington/cs/figer/FigerSystem.java", "mask_start_position": 3762, "mask_end_position": 3770, "canonical_solution": "dToken);", "pre_mask_code": "package edu.washington.cs.figer;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Hashtable;\nimport java.util.List;\nimport java.util.Scanner;\nimport java.util.Set;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport edu.stanford.nlp.ling.CoreAnnotations.NamedEntityTagAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.OriginalTextAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;\nimport edu.stanford.nlp.ling.CoreLabel;\nimport edu.stanford.nlp.pipeline.Annotation;\nimport edu.stanford.nlp.util.CoreMap;\nimport edu.stanford.nlp.util.Pair;\nimport edu.stanford.nlp.util.StringUtils;\nimport edu.washington.cs.figer.analysis.MapType;\nimport edu.washington.cs.figer.analysis.Preprocessing;\nimport edu.washington.cs.figer.analysis.feature.NERFeature;\nimport edu.washington.cs.figer.data.EntityProtos.Mention;\nimport edu.washington.cs.figer.data.EntityProtos.Mention.Dependency;\nimport edu.washington.cs.figer.data.Feature;\nimport edu.washington.cs.figer.data.FeatureFactory;\nimport edu.washington.cs.figer.data.Instance;\nimport edu.washington.cs.figer.ml.Model;\nimport edu.washington.cs.figer.ml.MultiLabelLogisticRegression;\nimport edu.washington.cs.figer.ml.MultiLabelPerceptronNERClassifier;\nimport edu.washington.cs.figer.ml.NERClassifier;\nimport edu.washington.cs.figer.util.FileUtil;\nimport edu.washington.cs.figer.util.StanfordDependencyResolver;\nimport edu.washington.cs.figer.util.Timer;\nimport edu.washington.cs.figer.util.X;\nimport gnu.trove.list.TIntList;\nimport gnu.trove.list.array.TIntArrayList;\n\npublic class FigerSystem {\n\n private static Logger logger = LoggerFactory.getLogger(FigerSystem.class);\n\n private static FigerSystem instance = null;\n\n public static String configFile = \"config/figer.conf\";\n\n // useful variables\n public Model model = new MultiLabelLogisticRegression();\n\n public NERClassifier classifier = null;\n\n public NERFeature nerFeature = null;\n\n // debug variables\n public static HashSet mentions = new HashSet();\n\n public synchronized static FigerSystem instance() {\n if (instance == null) {\n instance = new FigerSystem();\n }\n return instance;\n }\n\n private FigerSystem() {\n X.parseArgs(configFile);\n Timer timer = new Timer();\n model.debug = X.getBoolean(\"debugModel\");\n // read all tags\n MapType.typeFile = X.tagset;\n MapType.init();\n for (String newType : MapType.mapping.values()) {\n model.labelFactory.getLabel(newType);\n }\n logger.info(\"labels:\\t\" + model.labelFactory.allLabels);\n // read the model\n if (X.methodS == X.PERCEPTRON) {\n timer.task = \"reading the model \" + X.modelFile;\n timer.start();\n model.readModel(X.modelFile);\n model.featureFactory.isTrain = false;\n model.labelFactory.isTrain = false;\n timer.endPrint();\n // init NER Features\n nerFeature = new NERFeature(model);\n nerFeature.init();\n MultiLabelLogisticRegression.prob_threshold = X.getDouble(\"prob_threshold\");\n classifier = new MultiLabelPerceptronNERClassifier(model.infer);\n }\n }\n\n public String predict(Annotation annotation, int sentId, int startToken, int endToken) {\n Mention m = buildMention(annotation, sentId, startToken, en", "post_mask_code": "\n // features\n ArrayList features = new ArrayList();\n nerFeature.extract(m, features);\n return predict(features);\n }\n\n public Mention buildMention(Annotation annotation, int sentId, int startToken, int endToken) {\n CoreMap sentAnn = annotation.get(SentencesAnnotation.class).get(sentId);\n List tokens = sentAnn.get(TokensAnnotation.class);\n // create a Mention object\n Mention.Builder m = Mention.newBuilder();\n m.setStart(startToken);\n m.setEnd(endToken);\n for (int i = 0; i < tokens.size(); i++) {\n m.addTokens(tokens.get(i).get(OriginalTextAnnotation.class));\n m.addPosTags(tokens.get(i).get(PartOfSpeechAnnotation.class));\n }\n m.setEntityName(\"\");\n m.setFileid(\"on-the-fly\");\n m.setSentid(sentId);\n // dependency\n String depStr = StanfordDependencyResolver.getString(sentAnn);\n if (depStr != null) {\n for (String d : depStr.split(\"\\t\")) {\n Matcher match = Preprocessing.depPattern.matcher(d);\n if (match.find()) {\n m.addDeps(Dependency.newBuilder().setType(match.group(1)).setGov(Integer.parseInt(match.group(3)) - 1).setDep(Integer.parseInt(match.group(5)) - 1).build());\n } else {\n }\n }\n }\n return m.build();\n }\n\n public String predict(List features) {\n try {\n Instance inst = (Instance) X.instanceClass.newInstance();\n for (String fea : features) {\n Feature f = model.featureFactory.getFeature(fea);\n FeatureFactory.setValue(inst, f, fea);\n }\n Hashtable pool = new Hashtable();\n TIntList entity = new TIntArrayList();\n classifier.predict(inst, pool, entity, model);\n String plabels = pool.get(entity);\n return plabels;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n // only use the following tag set to find named entities\n private static final Set validTags = new HashSet(Arrays.asList(new String[] { \"PERSON\", \"ORGANIZATION\", \"LOCATION\", \"MISC\", \"O\" }));\n\n public static List> getNamedEntityMentions(CoreMap sentence) {\n List> offsets = new ArrayList>();\n String prevTag = \"O\";\n int tid = 0;\n int start = -1;\n for (CoreLabel token : sentence.get(TokensAnnotation.class)) {\n String tag = token.get(NamedEntityTagAnnotation.class);\n if (!validTags.contains(tag)) {\n tag = \"O\";\n }\n if (tag.equals(prevTag)) {\n } else {\n if (tag.equals(\"O\")) {\n offsets.add(Pair.makePair(start, tid));\n start = -1;\n } else {\n if (prevTag.equals(\"O\")) {\n start = tid;\n } else {\n offsets.add(Pair.makePair(start, tid));\n start = tid;\n }\n }\n }\n prevTag = tag;\n tid++;\n }\n if (!prevTag.equals(\"O\")) {\n offsets.add(Pair.makePair(start, tid));\n }\n return offsets;\n }\n\n private static void usage() {\n System.out.println(\"sbt \\\"runMain edu.washington.cs.figer.FigerSystem [config_file] text_file\\\"\");\n System.out.println(\" [config_file] is optional with a default value \\\"config/figer.conf\\\"\");\n }\n\n public static void main(String[] args) {\n String textFile = null;\n if (args.length == 1) {\n textFile = args[0];\n } else if (args.length == 2) {\n configFile = args[0];\n textFile = args[1];\n } else {\n usage();\n System.exit(0);\n }\n // initialize the system\n FigerSystem sys = instance();\n Preprocessing.initPipeline();\n // preprocess the text\n List list = FileUtil.getLinesFromFile(textFile);\n for (int i = 0; i < list.size(); i++) {\n Annotation annotation = new Annotation(list.get(i));\n Preprocessing.pipeline.annotate(annotation);\n // for each sentence\n int sentId = 0;\n for (CoreMap sentence : annotation.get(SentencesAnnotation.class)) {\n System.out.println(\"[l\" + i + \"][s\" + sentId + \"]tokenized sentence=\" + StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class)));\n List> entityMentionOffsets = getNamedEntityMentions(sentence);\n for (Pair offset : entityMentionOffsets) {\n String label = sys.predict(annotation, sentId, offset.first, offset.second);\n String mention = StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class).subList(offset.first, offset.second));\n System.out.println(\"[l\" + i + \"][s\" + sentId + \"]mention\" + mention + \"(\" + offset.first + \",\" + offset.second + \") = \" + mention + \", pred = \" + label);\n }\n sentId++;\n }\n }\n }\n}\n"} {"task_id": "Java_2863", "language": "Java", "task_type": "for_statement", "source_file": "java/github/xiaoling/figer/src/main/java/edu/washington/cs/figer/FigerSystem.java", "mask_start_position": 4338, "mask_end_position": 4538, "canonical_solution": "for (int i = 0; i < tokens.size(); i++) {\n m.addTokens(tokens.get(i).get(OriginalTextAnnotation.class));\n m.addPosTags(tokens.get(i).get(PartOfSpeechAnnotation.class));\n }", "pre_mask_code": "package edu.washington.cs.figer;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Hashtable;\nimport java.util.List;\nimport java.util.Scanner;\nimport java.util.Set;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport edu.stanford.nlp.ling.CoreAnnotations.NamedEntityTagAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.OriginalTextAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;\nimport edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;\nimport edu.stanford.nlp.ling.CoreLabel;\nimport edu.stanford.nlp.pipeline.Annotation;\nimport edu.stanford.nlp.util.CoreMap;\nimport edu.stanford.nlp.util.Pair;\nimport edu.stanford.nlp.util.StringUtils;\nimport edu.washington.cs.figer.analysis.MapType;\nimport edu.washington.cs.figer.analysis.Preprocessing;\nimport edu.washington.cs.figer.analysis.feature.NERFeature;\nimport edu.washington.cs.figer.data.EntityProtos.Mention;\nimport edu.washington.cs.figer.data.EntityProtos.Mention.Dependency;\nimport edu.washington.cs.figer.data.Feature;\nimport edu.washington.cs.figer.data.FeatureFactory;\nimport edu.washington.cs.figer.data.Instance;\nimport edu.washington.cs.figer.ml.Model;\nimport edu.washington.cs.figer.ml.MultiLabelLogisticRegression;\nimport edu.washington.cs.figer.ml.MultiLabelPerceptronNERClassifier;\nimport edu.washington.cs.figer.ml.NERClassifier;\nimport edu.washington.cs.figer.util.FileUtil;\nimport edu.washington.cs.figer.util.StanfordDependencyResolver;\nimport edu.washington.cs.figer.util.Timer;\nimport edu.washington.cs.figer.util.X;\nimport gnu.trove.list.TIntList;\nimport gnu.trove.list.array.TIntArrayList;\n\npublic class FigerSystem {\n\n private static Logger logger = LoggerFactory.getLogger(FigerSystem.class);\n\n private static FigerSystem instance = null;\n\n public static String configFile = \"config/figer.conf\";\n\n // useful variables\n public Model model = new MultiLabelLogisticRegression();\n\n public NERClassifier classifier = null;\n\n public NERFeature nerFeature = null;\n\n // debug variables\n public static HashSet mentions = new HashSet();\n\n public synchronized static FigerSystem instance() {\n if (instance == null) {\n instance = new FigerSystem();\n }\n return instance;\n }\n\n private FigerSystem() {\n X.parseArgs(configFile);\n Timer timer = new Timer();\n model.debug = X.getBoolean(\"debugModel\");\n // read all tags\n MapType.typeFile = X.tagset;\n MapType.init();\n for (String newType : MapType.mapping.values()) {\n model.labelFactory.getLabel(newType);\n }\n logger.info(\"labels:\\t\" + model.labelFactory.allLabels);\n // read the model\n if (X.methodS == X.PERCEPTRON) {\n timer.task = \"reading the model \" + X.modelFile;\n timer.start();\n model.readModel(X.modelFile);\n model.featureFactory.isTrain = false;\n model.labelFactory.isTrain = false;\n timer.endPrint();\n // init NER Features\n nerFeature = new NERFeature(model);\n nerFeature.init();\n MultiLabelLogisticRegression.prob_threshold = X.getDouble(\"prob_threshold\");\n classifier = new MultiLabelPerceptronNERClassifier(model.infer);\n }\n }\n\n public String predict(Annotation annotation, int sentId, int startToken, int endToken) {\n Mention m = buildMention(annotation, sentId, startToken, endToken);\n // features\n ArrayList features = new ArrayList();\n nerFeature.extract(m, features);\n return predict(features);\n }\n\n public Mention buildMention(Annotation annotation, int sentId, int startToken, int endToken) {\n CoreMap sentAnn = annotation.get(SentencesAnnotation.class).get(sentId);\n List tokens = sentAnn.get(TokensAnnotation.class);\n // create a Mention object\n Mention.Builder m = Mention.newBuilder();\n m.setStart(startToken);\n m.setEnd(endToken);\n ", "post_mask_code": "\n m.setEntityName(\"\");\n m.setFileid(\"on-the-fly\");\n m.setSentid(sentId);\n // dependency\n String depStr = StanfordDependencyResolver.getString(sentAnn);\n if (depStr != null) {\n for (String d : depStr.split(\"\\t\")) {\n Matcher match = Preprocessing.depPattern.matcher(d);\n if (match.find()) {\n m.addDeps(Dependency.newBuilder().setType(match.group(1)).setGov(Integer.parseInt(match.group(3)) - 1).setDep(Integer.parseInt(match.group(5)) - 1).build());\n } else {\n }\n }\n }\n return m.build();\n }\n\n public String predict(List features) {\n try {\n Instance inst = (Instance) X.instanceClass.newInstance();\n for (String fea : features) {\n Feature f = model.featureFactory.getFeature(fea);\n FeatureFactory.setValue(inst, f, fea);\n }\n Hashtable pool = new Hashtable();\n TIntList entity = new TIntArrayList();\n classifier.predict(inst, pool, entity, model);\n String plabels = pool.get(entity);\n return plabels;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n // only use the following tag set to find named entities\n private static final Set validTags = new HashSet(Arrays.asList(new String[] { \"PERSON\", \"ORGANIZATION\", \"LOCATION\", \"MISC\", \"O\" }));\n\n public static List> getNamedEntityMentions(CoreMap sentence) {\n List> offsets = new ArrayList>();\n String prevTag = \"O\";\n int tid = 0;\n int start = -1;\n for (CoreLabel token : sentence.get(TokensAnnotation.class)) {\n String tag = token.get(NamedEntityTagAnnotation.class);\n if (!validTags.contains(tag)) {\n tag = \"O\";\n }\n if (tag.equals(prevTag)) {\n } else {\n if (tag.equals(\"O\")) {\n offsets.add(Pair.makePair(start, tid));\n start = -1;\n } else {\n if (prevTag.equals(\"O\")) {\n start = tid;\n } else {\n offsets.add(Pair.makePair(start, tid));\n start = tid;\n }\n }\n }\n prevTag = tag;\n tid++;\n }\n if (!prevTag.equals(\"O\")) {\n offsets.add(Pair.makePair(start, tid));\n }\n return offsets;\n }\n\n private static void usage() {\n System.out.println(\"sbt \\\"runMain edu.washington.cs.figer.FigerSystem [config_file] text_file\\\"\");\n System.out.println(\" [config_file] is optional with a default value \\\"config/figer.conf\\\"\");\n }\n\n public static void main(String[] args) {\n String textFile = null;\n if (args.length == 1) {\n textFile = args[0];\n } else if (args.length == 2) {\n configFile = args[0];\n textFile = args[1];\n } else {\n usage();\n System.exit(0);\n }\n // initialize the system\n FigerSystem sys = instance();\n Preprocessing.initPipeline();\n // preprocess the text\n List list = FileUtil.getLinesFromFile(textFile);\n for (int i = 0; i < list.size(); i++) {\n Annotation annotation = new Annotation(list.get(i));\n Preprocessing.pipeline.annotate(annotation);\n // for each sentence\n int sentId = 0;\n for (CoreMap sentence : annotation.get(SentencesAnnotation.class)) {\n System.out.println(\"[l\" + i + \"][s\" + sentId + \"]tokenized sentence=\" + StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class)));\n List> entityMentionOffsets = getNamedEntityMentions(sentence);\n for (Pair offset : entityMentionOffsets) {\n String label = sys.predict(annotation, sentId, offset.first, offset.second);\n String mention = StringUtils.joinWithOriginalWhiteSpace(sentence.get(TokensAnnotation.class).subList(offset.first, offset.second));\n System.out.println(\"[l\" + i + \"][s\" + sentId + \"]mention\" + mention + \"(\" + offset.first + \",\" + offset.second + \") = \" + mention + \", pred = \" + label);\n }\n sentId++;\n }\n }\n }\n}\n"} {"task_id": "Java_2864", "language": "Java", "task_type": "method_signature", "source_file": "java/github/schedulix/schedulix/src/server/ConnectionEnvironment.java", "mask_start_position": 7229, "mask_end_position": 7251, "canonical_solution": "public void setLast() ", "pre_mask_code": "/*\n\nschedulix Enterprise Job Scheduling System\n\nindependIT Integrative Technologies GmbH [http://www.independit.de]\nmailto:example@nnthink.com\n\nThis file is part of schedulix\n\n*/\npackage de.independit.scheduler.server;\n\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*;\nimport java.net.*;\nimport de.independit.scheduler.server.util.*;\nimport de.independit.scheduler.server.repository.*;\nimport de.independit.scheduler.server.exception.*;\nimport de.independit.scheduler.server.output.*;\nimport de.independit.scheduler.server.parser.*;\n\npublic class ConnectionEnvironment {\n\n public final static String __version = \"@(#) $Id: ConnectionEnvironment.java,v 2.12.2.1 2013/03/14 10:24:08 ronald Exp $\";\n\n public static final int IDLE = 0;\n\n public static final int QUEUED = 1;\n\n public static final int ACTIVE = 2;\n\n public static final int COMMITTING = 3;\n\n public static final int CONNECTED = 4;\n\n public static final int PARSING = 5;\n\n public static final int RENDERING = 6;\n\n public static final String[] stateNames = { \"IDLE\", \"QUEUED\", \"ACTIVE\", \"COMMITTING\", \"CONNECTED\", \"PARSING\", \"RENDERING\" };\n\n protected final int id;\n\n protected final String name;\n\n protected long start;\n\n protected long last;\n\n protected Date dStart;\n\n protected PrintStream ostream;\n\n protected Long uid;\n\n protected HashSet gid;\n\n protected SyncFifo cmdQueue;\n\n protected SyncFifo roCmdQueue;\n\n protected SDMSThread me;\n\n protected ThreadLock lock;\n\n protected boolean jobServer;\n\n protected boolean job;\n\n protected boolean user;\n\n public SDMSTransaction tx;\n\n protected SDMSOutputRenderer renderer;\n\n protected boolean trace;\n\n protected int tracelevel;\n\n protected final int port;\n\n protected int state;\n\n public String actstmt;\n\n public String firstToken;\n\n protected InetAddress userNode;\n\n protected String info;\n\n private Stack groupStack;\n\n public SDMSThread worker;\n\n public HashMap SSOInfo;\n\n private boolean isSSLConnection;\n\n private boolean isClientAuthenticated;\n\n protected Long prev_uid;\n\n protected HashSet prev_gid;\n\n protected boolean prev_trace;\n\n protected int prev_tracelevel;\n\n public ConnectionEnvironment(int c, String n, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, int portno, InetAddress uNode, boolean ssl, boolean auth) {\n id = c;\n name = n;\n ostream = o;\n start = System.currentTimeMillis();\n last = start;\n dStart = new Date(start);\n cmdQueue = f;\n roCmdQueue = rof;\n lock = new ThreadLock();\n renderer = new SDMSLineRenderer();\n trace = svrtrc;\n port = portno;\n actstmt = null;\n firstToken = null;\n info = null;\n state = CONNECTED;\n groupStack = new Stack();\n userNode = uNode;\n tracelevel = SDMSThread.SEVERITY_INFO;\n worker = null;\n prev_uid = null;\n isSSLConnection = ssl;\n isClientAuthenticated = auth;\n }\n\n public ConnectionEnvironment(int c, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, int portno, InetAddress uNode, boolean ssl, boolean auth) {\n this(c, null, svrtrc, o, f, rof, portno, uNode, ssl, auth);\n }\n\n public ConnectionEnvironment(int c, String n, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, InetAddress uNode) {\n this(c, n, svrtrc, o, f, rof, 0, uNode, false, false);\n }\n\n public int id() {\n return id;\n }\n\n public String name() {\n return name != null ? name : new Integer(id).toString();\n }\n\n public long start() {\n return start;\n }\n\n public long last() {\n return last;\n }\n\n public long idle() {\n return ((System.currentTimeMillis() - last + 500) / 1000);\n }\n\n public Date dStart() {\n return dStart;\n }\n\n public PrintStream ostream() {\n return ostream;\n }\n\n public Long uid() {\n return uid;\n }\n\n public HashSet gid() {\n return gid;\n }\n\n public void setUid(Long id) {\n uid = id;\n }\n\n public int timeout() {\n return ((UserConnection) me).getTimeout();\n }\n\n public String getInfo() {\n return info;\n }\n\n public void setInfo(String inf) {\n info = inf;\n }\n\n public boolean getIsSSLConnection() {\n return isSSLConnection;\n }\n\n public boolean getIsClientAuthenticated() {\n return isClientAuthenticated;\n }\n\n public String ip() {\n if (userNode != null)\n return userNode.getHostAddress();\n return null;\n }\n\n public InetAddress getAddress() {\n return userNode;\n }\n\n public void setGid(SystemEnvironment sysEnv, Vector v) throws SDMSException {\n if (v.size() == 0) {\n gid = new HashSet();\n return;\n }\n gid = new HashSet(v.size() * 2);\n for (int i = 0; i < v.size(); i++) {\n gid.add(((SDMSMember) v.get(i)).getGId(sysEnv));\n }\n }\n\n public void addGid(Long groupId) {\n if (gid == null)\n gid = new HashSet();\n gid.add(groupId);\n }\n\n public void delGid(Long groupId) {\n if (gid == null)\n return;\n gid.remove(groupId);\n }\n\n public void pushGid(SystemEnvironment sysEnv, HashSet g) throws SDMSException {\n groupStack.push(gid);\n gid = g;\n }\n\n public void popGid(SystemEnvironment sysEnv) throws SDMSException {\n if (groupStack.isEmpty())\n throw new FatalException(new SDMSMessage(sysEnv, \"03401301115\", \"Groupstack is empty. Unbalanced change group\"));\n gid = (HashSet) groupStack.pop();\n }\n\n public void emptyGid(SystemEnvironment sysEnv) throws SDMSException {\n while (!groupStack.isEmpty()) {\n SDMSThread.doTrace(this, \"Unbalanced push(gid) : \\n\\t\" + toString(), SDMSThread.SEVERITY_WARNING);\n gid = (HashSet) groupStack.pop();\n }\n }\n\n public int port() {\n return port;\n }\n\n public SyncFifo cmdQueue() {\n return cmdQueue;\n }\n\n public SyncFifo roCmdQueue() {\n return roCmdQueue;\n }\n\n public void setMe(SDMSThread t) {\n me = t;\n }\n\n public SDMSThread getMe() {\n return me;\n }\n\n public ThreadLock lock() {\n return lock;\n }\n\n public boolean isJobServer() {\n return jobServer;\n }\n\n public boolean isJob() {\n return job;\n }\n\n public boolean isUser() {\n return user;\n }\n\n public void setJobServer() {\n jobServer = true;\n job = false;\n user = false;\n }\n\n public void setJob() {\n job = true;\n jobServer = false;\n user = false;\n }\n\n public void setUser() {\n user = true;\n jobServer = false;\n job = false;\n }\n\n public void trace_on() {\n trace = true;\n }\n\n public void trace_off() {\n trace = false;\n }\n\n public void setTrace(boolean t) {\n trace = t;\n }\n\n public boolean trace() {\n return trace;\n }\n\n public void setTraceLevel(int t) {\n tracelevel = t;\n }\n\n public int getTraceLevel() {\n return tracelevel;\n }\n\n ", "post_mask_code": "{\n last = System.currentTimeMillis();\n }\n\n public SDMSOutputRenderer renderer() {\n return renderer;\n }\n\n public void setRenderer(SDMSOutputRenderer type) {\n renderer = type;\n }\n\n public void setRenderer(int type) {\n renderer = null;\n switch(type) {\n case Parser.XML:\n renderer = new SDMSXmlRenderer();\n break;\n case Parser.LINE:\n renderer = new SDMSLineRenderer();\n break;\n case Parser.PERL:\n renderer = new SDMSPerlRenderer();\n break;\n case Parser.PYTHON:\n renderer = new SDMSPythonRenderer();\n break;\n case Parser.JSON:\n renderer = new SDMSJsonRenderer();\n break;\n case Parser.SERIAL:\n renderer = new SDMSSerialRenderer();\n break;\n case Parser.TIME:\n renderer = new SDMSTimeRenderer();\n break;\n }\n }\n\n public long versionId(SystemEnvironment env) throws SDMSException {\n return tx.versionId(env);\n }\n\n public long txId() {\n return tx.txId;\n }\n\n public void proto_input(String s) {\n ((UserConnection) me).scanner.proto_input(s);\n }\n\n public void setState(int s) {\n if (s == IDLE || s == QUEUED || s == ACTIVE || s == COMMITTING || s == CONNECTED || s == PARSING || s == RENDERING)\n state = s;\n }\n\n public String getState() {\n return stateNames[state];\n }\n\n public String toString() {\n String s = \"Id : \" + id + \", Name : \" + name + \", Start : \" + start + \", Last : \" + last + \", Uid : \" + uid + \", Type : \" + (user ? \"User\" : job ? \"Job\" : \"Jobserver\") + \", Trace : \" + trace + \", Port : \" + port + \", State : \" + stateNames[state];\n return s;\n }\n\n public boolean setConnectedUser(SystemEnvironment sysEnv, Long uid, Vector groups) throws SDMSException {\n prev_uid = this.uid;\n prev_gid = this.gid;\n prev_trace = this.trace;\n prev_tracelevel = this.tracelevel;\n setUid(uid);\n setGid(sysEnv, groups);\n return true;\n }\n\n public boolean resetConnectedUser() {\n if (prev_uid != null) {\n uid = prev_uid;\n gid = prev_gid;\n trace = prev_trace;\n tracelevel = prev_tracelevel;\n prev_uid = null;\n prev_gid = null;\n prev_trace = false;\n prev_tracelevel = 0;\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_2865", "language": "Java", "task_type": "method_body", "source_file": "java/github/schedulix/schedulix/src/server/ConnectionEnvironment.java", "mask_start_position": 6934, "mask_end_position": 6964, "canonical_solution": "{\n trace = false;\n }", "pre_mask_code": "/*\n\nschedulix Enterprise Job Scheduling System\n\nindependIT Integrative Technologies GmbH [http://www.independit.de]\nmailto:example@nnthink.com\n\nThis file is part of schedulix\n\n*/\npackage de.independit.scheduler.server;\n\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*;\nimport java.net.*;\nimport de.independit.scheduler.server.util.*;\nimport de.independit.scheduler.server.repository.*;\nimport de.independit.scheduler.server.exception.*;\nimport de.independit.scheduler.server.output.*;\nimport de.independit.scheduler.server.parser.*;\n\npublic class ConnectionEnvironment {\n\n public final static String __version = \"@(#) $Id: ConnectionEnvironment.java,v 2.12.2.1 2013/03/14 10:24:08 ronald Exp $\";\n\n public static final int IDLE = 0;\n\n public static final int QUEUED = 1;\n\n public static final int ACTIVE = 2;\n\n public static final int COMMITTING = 3;\n\n public static final int CONNECTED = 4;\n\n public static final int PARSING = 5;\n\n public static final int RENDERING = 6;\n\n public static final String[] stateNames = { \"IDLE\", \"QUEUED\", \"ACTIVE\", \"COMMITTING\", \"CONNECTED\", \"PARSING\", \"RENDERING\" };\n\n protected final int id;\n\n protected final String name;\n\n protected long start;\n\n protected long last;\n\n protected Date dStart;\n\n protected PrintStream ostream;\n\n protected Long uid;\n\n protected HashSet gid;\n\n protected SyncFifo cmdQueue;\n\n protected SyncFifo roCmdQueue;\n\n protected SDMSThread me;\n\n protected ThreadLock lock;\n\n protected boolean jobServer;\n\n protected boolean job;\n\n protected boolean user;\n\n public SDMSTransaction tx;\n\n protected SDMSOutputRenderer renderer;\n\n protected boolean trace;\n\n protected int tracelevel;\n\n protected final int port;\n\n protected int state;\n\n public String actstmt;\n\n public String firstToken;\n\n protected InetAddress userNode;\n\n protected String info;\n\n private Stack groupStack;\n\n public SDMSThread worker;\n\n public HashMap SSOInfo;\n\n private boolean isSSLConnection;\n\n private boolean isClientAuthenticated;\n\n protected Long prev_uid;\n\n protected HashSet prev_gid;\n\n protected boolean prev_trace;\n\n protected int prev_tracelevel;\n\n public ConnectionEnvironment(int c, String n, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, int portno, InetAddress uNode, boolean ssl, boolean auth) {\n id = c;\n name = n;\n ostream = o;\n start = System.currentTimeMillis();\n last = start;\n dStart = new Date(start);\n cmdQueue = f;\n roCmdQueue = rof;\n lock = new ThreadLock();\n renderer = new SDMSLineRenderer();\n trace = svrtrc;\n port = portno;\n actstmt = null;\n firstToken = null;\n info = null;\n state = CONNECTED;\n groupStack = new Stack();\n userNode = uNode;\n tracelevel = SDMSThread.SEVERITY_INFO;\n worker = null;\n prev_uid = null;\n isSSLConnection = ssl;\n isClientAuthenticated = auth;\n }\n\n public ConnectionEnvironment(int c, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, int portno, InetAddress uNode, boolean ssl, boolean auth) {\n this(c, null, svrtrc, o, f, rof, portno, uNode, ssl, auth);\n }\n\n public ConnectionEnvironment(int c, String n, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, InetAddress uNode) {\n this(c, n, svrtrc, o, f, rof, 0, uNode, false, false);\n }\n\n public int id() {\n return id;\n }\n\n public String name() {\n return name != null ? name : new Integer(id).toString();\n }\n\n public long start() {\n return start;\n }\n\n public long last() {\n return last;\n }\n\n public long idle() {\n return ((System.currentTimeMillis() - last + 500) / 1000);\n }\n\n public Date dStart() {\n return dStart;\n }\n\n public PrintStream ostream() {\n return ostream;\n }\n\n public Long uid() {\n return uid;\n }\n\n public HashSet gid() {\n return gid;\n }\n\n public void setUid(Long id) {\n uid = id;\n }\n\n public int timeout() {\n return ((UserConnection) me).getTimeout();\n }\n\n public String getInfo() {\n return info;\n }\n\n public void setInfo(String inf) {\n info = inf;\n }\n\n public boolean getIsSSLConnection() {\n return isSSLConnection;\n }\n\n public boolean getIsClientAuthenticated() {\n return isClientAuthenticated;\n }\n\n public String ip() {\n if (userNode != null)\n return userNode.getHostAddress();\n return null;\n }\n\n public InetAddress getAddress() {\n return userNode;\n }\n\n public void setGid(SystemEnvironment sysEnv, Vector v) throws SDMSException {\n if (v.size() == 0) {\n gid = new HashSet();\n return;\n }\n gid = new HashSet(v.size() * 2);\n for (int i = 0; i < v.size(); i++) {\n gid.add(((SDMSMember) v.get(i)).getGId(sysEnv));\n }\n }\n\n public void addGid(Long groupId) {\n if (gid == null)\n gid = new HashSet();\n gid.add(groupId);\n }\n\n public void delGid(Long groupId) {\n if (gid == null)\n return;\n gid.remove(groupId);\n }\n\n public void pushGid(SystemEnvironment sysEnv, HashSet g) throws SDMSException {\n groupStack.push(gid);\n gid = g;\n }\n\n public void popGid(SystemEnvironment sysEnv) throws SDMSException {\n if (groupStack.isEmpty())\n throw new FatalException(new SDMSMessage(sysEnv, \"03401301115\", \"Groupstack is empty. Unbalanced change group\"));\n gid = (HashSet) groupStack.pop();\n }\n\n public void emptyGid(SystemEnvironment sysEnv) throws SDMSException {\n while (!groupStack.isEmpty()) {\n SDMSThread.doTrace(this, \"Unbalanced push(gid) : \\n\\t\" + toString(), SDMSThread.SEVERITY_WARNING);\n gid = (HashSet) groupStack.pop();\n }\n }\n\n public int port() {\n return port;\n }\n\n public SyncFifo cmdQueue() {\n return cmdQueue;\n }\n\n public SyncFifo roCmdQueue() {\n return roCmdQueue;\n }\n\n public void setMe(SDMSThread t) {\n me = t;\n }\n\n public SDMSThread getMe() {\n return me;\n }\n\n public ThreadLock lock() {\n return lock;\n }\n\n public boolean isJobServer() {\n return jobServer;\n }\n\n public boolean isJob() {\n return job;\n }\n\n public boolean isUser() {\n return user;\n }\n\n public void setJobServer() {\n jobServer = true;\n job = false;\n user = false;\n }\n\n public void setJob() {\n job = true;\n jobServer = false;\n user = false;\n }\n\n public void setUser() {\n user = true;\n jobServer = false;\n job = false;\n }\n\n public void trace_on() {\n trace = true;\n }\n\n public void trace_off() ", "post_mask_code": "\n\n public void setTrace(boolean t) {\n trace = t;\n }\n\n public boolean trace() {\n return trace;\n }\n\n public void setTraceLevel(int t) {\n tracelevel = t;\n }\n\n public int getTraceLevel() {\n return tracelevel;\n }\n\n public void setLast() {\n last = System.currentTimeMillis();\n }\n\n public SDMSOutputRenderer renderer() {\n return renderer;\n }\n\n public void setRenderer(SDMSOutputRenderer type) {\n renderer = type;\n }\n\n public void setRenderer(int type) {\n renderer = null;\n switch(type) {\n case Parser.XML:\n renderer = new SDMSXmlRenderer();\n break;\n case Parser.LINE:\n renderer = new SDMSLineRenderer();\n break;\n case Parser.PERL:\n renderer = new SDMSPerlRenderer();\n break;\n case Parser.PYTHON:\n renderer = new SDMSPythonRenderer();\n break;\n case Parser.JSON:\n renderer = new SDMSJsonRenderer();\n break;\n case Parser.SERIAL:\n renderer = new SDMSSerialRenderer();\n break;\n case Parser.TIME:\n renderer = new SDMSTimeRenderer();\n break;\n }\n }\n\n public long versionId(SystemEnvironment env) throws SDMSException {\n return tx.versionId(env);\n }\n\n public long txId() {\n return tx.txId;\n }\n\n public void proto_input(String s) {\n ((UserConnection) me).scanner.proto_input(s);\n }\n\n public void setState(int s) {\n if (s == IDLE || s == QUEUED || s == ACTIVE || s == COMMITTING || s == CONNECTED || s == PARSING || s == RENDERING)\n state = s;\n }\n\n public String getState() {\n return stateNames[state];\n }\n\n public String toString() {\n String s = \"Id : \" + id + \", Name : \" + name + \", Start : \" + start + \", Last : \" + last + \", Uid : \" + uid + \", Type : \" + (user ? \"User\" : job ? \"Job\" : \"Jobserver\") + \", Trace : \" + trace + \", Port : \" + port + \", State : \" + stateNames[state];\n return s;\n }\n\n public boolean setConnectedUser(SystemEnvironment sysEnv, Long uid, Vector groups) throws SDMSException {\n prev_uid = this.uid;\n prev_gid = this.gid;\n prev_trace = this.trace;\n prev_tracelevel = this.tracelevel;\n setUid(uid);\n setGid(sysEnv, groups);\n return true;\n }\n\n public boolean resetConnectedUser() {\n if (prev_uid != null) {\n uid = prev_uid;\n gid = prev_gid;\n trace = prev_trace;\n tracelevel = prev_tracelevel;\n prev_uid = null;\n prev_gid = null;\n prev_trace = false;\n prev_tracelevel = 0;\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_2866", "language": "Java", "task_type": "single_line", "source_file": "java/github/schedulix/schedulix/src/server/ConnectionEnvironment.java", "mask_start_position": 6812, "mask_end_position": 6819, "canonical_solution": " false;", "pre_mask_code": "/*\n\nschedulix Enterprise Job Scheduling System\n\nindependIT Integrative Technologies GmbH [http://www.independit.de]\nmailto:example@nnthink.com\n\nThis file is part of schedulix\n\n*/\npackage de.independit.scheduler.server;\n\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*;\nimport java.net.*;\nimport de.independit.scheduler.server.util.*;\nimport de.independit.scheduler.server.repository.*;\nimport de.independit.scheduler.server.exception.*;\nimport de.independit.scheduler.server.output.*;\nimport de.independit.scheduler.server.parser.*;\n\npublic class ConnectionEnvironment {\n\n public final static String __version = \"@(#) $Id: ConnectionEnvironment.java,v 2.12.2.1 2013/03/14 10:24:08 ronald Exp $\";\n\n public static final int IDLE = 0;\n\n public static final int QUEUED = 1;\n\n public static final int ACTIVE = 2;\n\n public static final int COMMITTING = 3;\n\n public static final int CONNECTED = 4;\n\n public static final int PARSING = 5;\n\n public static final int RENDERING = 6;\n\n public static final String[] stateNames = { \"IDLE\", \"QUEUED\", \"ACTIVE\", \"COMMITTING\", \"CONNECTED\", \"PARSING\", \"RENDERING\" };\n\n protected final int id;\n\n protected final String name;\n\n protected long start;\n\n protected long last;\n\n protected Date dStart;\n\n protected PrintStream ostream;\n\n protected Long uid;\n\n protected HashSet gid;\n\n protected SyncFifo cmdQueue;\n\n protected SyncFifo roCmdQueue;\n\n protected SDMSThread me;\n\n protected ThreadLock lock;\n\n protected boolean jobServer;\n\n protected boolean job;\n\n protected boolean user;\n\n public SDMSTransaction tx;\n\n protected SDMSOutputRenderer renderer;\n\n protected boolean trace;\n\n protected int tracelevel;\n\n protected final int port;\n\n protected int state;\n\n public String actstmt;\n\n public String firstToken;\n\n protected InetAddress userNode;\n\n protected String info;\n\n private Stack groupStack;\n\n public SDMSThread worker;\n\n public HashMap SSOInfo;\n\n private boolean isSSLConnection;\n\n private boolean isClientAuthenticated;\n\n protected Long prev_uid;\n\n protected HashSet prev_gid;\n\n protected boolean prev_trace;\n\n protected int prev_tracelevel;\n\n public ConnectionEnvironment(int c, String n, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, int portno, InetAddress uNode, boolean ssl, boolean auth) {\n id = c;\n name = n;\n ostream = o;\n start = System.currentTimeMillis();\n last = start;\n dStart = new Date(start);\n cmdQueue = f;\n roCmdQueue = rof;\n lock = new ThreadLock();\n renderer = new SDMSLineRenderer();\n trace = svrtrc;\n port = portno;\n actstmt = null;\n firstToken = null;\n info = null;\n state = CONNECTED;\n groupStack = new Stack();\n userNode = uNode;\n tracelevel = SDMSThread.SEVERITY_INFO;\n worker = null;\n prev_uid = null;\n isSSLConnection = ssl;\n isClientAuthenticated = auth;\n }\n\n public ConnectionEnvironment(int c, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, int portno, InetAddress uNode, boolean ssl, boolean auth) {\n this(c, null, svrtrc, o, f, rof, portno, uNode, ssl, auth);\n }\n\n public ConnectionEnvironment(int c, String n, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, InetAddress uNode) {\n this(c, n, svrtrc, o, f, rof, 0, uNode, false, false);\n }\n\n public int id() {\n return id;\n }\n\n public String name() {\n return name != null ? name : new Integer(id).toString();\n }\n\n public long start() {\n return start;\n }\n\n public long last() {\n return last;\n }\n\n public long idle() {\n return ((System.currentTimeMillis() - last + 500) / 1000);\n }\n\n public Date dStart() {\n return dStart;\n }\n\n public PrintStream ostream() {\n return ostream;\n }\n\n public Long uid() {\n return uid;\n }\n\n public HashSet gid() {\n return gid;\n }\n\n public void setUid(Long id) {\n uid = id;\n }\n\n public int timeout() {\n return ((UserConnection) me).getTimeout();\n }\n\n public String getInfo() {\n return info;\n }\n\n public void setInfo(String inf) {\n info = inf;\n }\n\n public boolean getIsSSLConnection() {\n return isSSLConnection;\n }\n\n public boolean getIsClientAuthenticated() {\n return isClientAuthenticated;\n }\n\n public String ip() {\n if (userNode != null)\n return userNode.getHostAddress();\n return null;\n }\n\n public InetAddress getAddress() {\n return userNode;\n }\n\n public void setGid(SystemEnvironment sysEnv, Vector v) throws SDMSException {\n if (v.size() == 0) {\n gid = new HashSet();\n return;\n }\n gid = new HashSet(v.size() * 2);\n for (int i = 0; i < v.size(); i++) {\n gid.add(((SDMSMember) v.get(i)).getGId(sysEnv));\n }\n }\n\n public void addGid(Long groupId) {\n if (gid == null)\n gid = new HashSet();\n gid.add(groupId);\n }\n\n public void delGid(Long groupId) {\n if (gid == null)\n return;\n gid.remove(groupId);\n }\n\n public void pushGid(SystemEnvironment sysEnv, HashSet g) throws SDMSException {\n groupStack.push(gid);\n gid = g;\n }\n\n public void popGid(SystemEnvironment sysEnv) throws SDMSException {\n if (groupStack.isEmpty())\n throw new FatalException(new SDMSMessage(sysEnv, \"03401301115\", \"Groupstack is empty. Unbalanced change group\"));\n gid = (HashSet) groupStack.pop();\n }\n\n public void emptyGid(SystemEnvironment sysEnv) throws SDMSException {\n while (!groupStack.isEmpty()) {\n SDMSThread.doTrace(this, \"Unbalanced push(gid) : \\n\\t\" + toString(), SDMSThread.SEVERITY_WARNING);\n gid = (HashSet) groupStack.pop();\n }\n }\n\n public int port() {\n return port;\n }\n\n public SyncFifo cmdQueue() {\n return cmdQueue;\n }\n\n public SyncFifo roCmdQueue() {\n return roCmdQueue;\n }\n\n public void setMe(SDMSThread t) {\n me = t;\n }\n\n public SDMSThread getMe() {\n return me;\n }\n\n public ThreadLock lock() {\n return lock;\n }\n\n public boolean isJobServer() {\n return jobServer;\n }\n\n public boolean isJob() {\n return job;\n }\n\n public boolean isUser() {\n return user;\n }\n\n public void setJobServer() {\n jobServer = true;\n job = false;\n user = false;\n }\n\n public void setJob() {\n job = true;\n jobServer = false;\n user = false;\n }\n\n public void setUser() {\n user = true;\n jobServer =", "post_mask_code": "\n job = false;\n }\n\n public void trace_on() {\n trace = true;\n }\n\n public void trace_off() {\n trace = false;\n }\n\n public void setTrace(boolean t) {\n trace = t;\n }\n\n public boolean trace() {\n return trace;\n }\n\n public void setTraceLevel(int t) {\n tracelevel = t;\n }\n\n public int getTraceLevel() {\n return tracelevel;\n }\n\n public void setLast() {\n last = System.currentTimeMillis();\n }\n\n public SDMSOutputRenderer renderer() {\n return renderer;\n }\n\n public void setRenderer(SDMSOutputRenderer type) {\n renderer = type;\n }\n\n public void setRenderer(int type) {\n renderer = null;\n switch(type) {\n case Parser.XML:\n renderer = new SDMSXmlRenderer();\n break;\n case Parser.LINE:\n renderer = new SDMSLineRenderer();\n break;\n case Parser.PERL:\n renderer = new SDMSPerlRenderer();\n break;\n case Parser.PYTHON:\n renderer = new SDMSPythonRenderer();\n break;\n case Parser.JSON:\n renderer = new SDMSJsonRenderer();\n break;\n case Parser.SERIAL:\n renderer = new SDMSSerialRenderer();\n break;\n case Parser.TIME:\n renderer = new SDMSTimeRenderer();\n break;\n }\n }\n\n public long versionId(SystemEnvironment env) throws SDMSException {\n return tx.versionId(env);\n }\n\n public long txId() {\n return tx.txId;\n }\n\n public void proto_input(String s) {\n ((UserConnection) me).scanner.proto_input(s);\n }\n\n public void setState(int s) {\n if (s == IDLE || s == QUEUED || s == ACTIVE || s == COMMITTING || s == CONNECTED || s == PARSING || s == RENDERING)\n state = s;\n }\n\n public String getState() {\n return stateNames[state];\n }\n\n public String toString() {\n String s = \"Id : \" + id + \", Name : \" + name + \", Start : \" + start + \", Last : \" + last + \", Uid : \" + uid + \", Type : \" + (user ? \"User\" : job ? \"Job\" : \"Jobserver\") + \", Trace : \" + trace + \", Port : \" + port + \", State : \" + stateNames[state];\n return s;\n }\n\n public boolean setConnectedUser(SystemEnvironment sysEnv, Long uid, Vector groups) throws SDMSException {\n prev_uid = this.uid;\n prev_gid = this.gid;\n prev_trace = this.trace;\n prev_tracelevel = this.tracelevel;\n setUid(uid);\n setGid(sysEnv, groups);\n return true;\n }\n\n public boolean resetConnectedUser() {\n if (prev_uid != null) {\n uid = prev_uid;\n gid = prev_gid;\n trace = prev_trace;\n tracelevel = prev_tracelevel;\n prev_uid = null;\n prev_gid = null;\n prev_trace = false;\n prev_tracelevel = 0;\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_2867", "language": "Java", "task_type": "for_statement", "source_file": "java/github/schedulix/schedulix/src/server/ConnectionEnvironment.java", "mask_start_position": 4914, "mask_end_position": 5021, "canonical_solution": "for (int i = 0; i < v.size(); i++) {\n gid.add(((SDMSMember) v.get(i)).getGId(sysEnv));\n }", "pre_mask_code": "/*\n\nschedulix Enterprise Job Scheduling System\n\nindependIT Integrative Technologies GmbH [http://www.independit.de]\nmailto:example@nnthink.com\n\nThis file is part of schedulix\n\n*/\npackage de.independit.scheduler.server;\n\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*;\nimport java.net.*;\nimport de.independit.scheduler.server.util.*;\nimport de.independit.scheduler.server.repository.*;\nimport de.independit.scheduler.server.exception.*;\nimport de.independit.scheduler.server.output.*;\nimport de.independit.scheduler.server.parser.*;\n\npublic class ConnectionEnvironment {\n\n public final static String __version = \"@(#) $Id: ConnectionEnvironment.java,v 2.12.2.1 2013/03/14 10:24:08 ronald Exp $\";\n\n public static final int IDLE = 0;\n\n public static final int QUEUED = 1;\n\n public static final int ACTIVE = 2;\n\n public static final int COMMITTING = 3;\n\n public static final int CONNECTED = 4;\n\n public static final int PARSING = 5;\n\n public static final int RENDERING = 6;\n\n public static final String[] stateNames = { \"IDLE\", \"QUEUED\", \"ACTIVE\", \"COMMITTING\", \"CONNECTED\", \"PARSING\", \"RENDERING\" };\n\n protected final int id;\n\n protected final String name;\n\n protected long start;\n\n protected long last;\n\n protected Date dStart;\n\n protected PrintStream ostream;\n\n protected Long uid;\n\n protected HashSet gid;\n\n protected SyncFifo cmdQueue;\n\n protected SyncFifo roCmdQueue;\n\n protected SDMSThread me;\n\n protected ThreadLock lock;\n\n protected boolean jobServer;\n\n protected boolean job;\n\n protected boolean user;\n\n public SDMSTransaction tx;\n\n protected SDMSOutputRenderer renderer;\n\n protected boolean trace;\n\n protected int tracelevel;\n\n protected final int port;\n\n protected int state;\n\n public String actstmt;\n\n public String firstToken;\n\n protected InetAddress userNode;\n\n protected String info;\n\n private Stack groupStack;\n\n public SDMSThread worker;\n\n public HashMap SSOInfo;\n\n private boolean isSSLConnection;\n\n private boolean isClientAuthenticated;\n\n protected Long prev_uid;\n\n protected HashSet prev_gid;\n\n protected boolean prev_trace;\n\n protected int prev_tracelevel;\n\n public ConnectionEnvironment(int c, String n, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, int portno, InetAddress uNode, boolean ssl, boolean auth) {\n id = c;\n name = n;\n ostream = o;\n start = System.currentTimeMillis();\n last = start;\n dStart = new Date(start);\n cmdQueue = f;\n roCmdQueue = rof;\n lock = new ThreadLock();\n renderer = new SDMSLineRenderer();\n trace = svrtrc;\n port = portno;\n actstmt = null;\n firstToken = null;\n info = null;\n state = CONNECTED;\n groupStack = new Stack();\n userNode = uNode;\n tracelevel = SDMSThread.SEVERITY_INFO;\n worker = null;\n prev_uid = null;\n isSSLConnection = ssl;\n isClientAuthenticated = auth;\n }\n\n public ConnectionEnvironment(int c, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, int portno, InetAddress uNode, boolean ssl, boolean auth) {\n this(c, null, svrtrc, o, f, rof, portno, uNode, ssl, auth);\n }\n\n public ConnectionEnvironment(int c, String n, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, InetAddress uNode) {\n this(c, n, svrtrc, o, f, rof, 0, uNode, false, false);\n }\n\n public int id() {\n return id;\n }\n\n public String name() {\n return name != null ? name : new Integer(id).toString();\n }\n\n public long start() {\n return start;\n }\n\n public long last() {\n return last;\n }\n\n public long idle() {\n return ((System.currentTimeMillis() - last + 500) / 1000);\n }\n\n public Date dStart() {\n return dStart;\n }\n\n public PrintStream ostream() {\n return ostream;\n }\n\n public Long uid() {\n return uid;\n }\n\n public HashSet gid() {\n return gid;\n }\n\n public void setUid(Long id) {\n uid = id;\n }\n\n public int timeout() {\n return ((UserConnection) me).getTimeout();\n }\n\n public String getInfo() {\n return info;\n }\n\n public void setInfo(String inf) {\n info = inf;\n }\n\n public boolean getIsSSLConnection() {\n return isSSLConnection;\n }\n\n public boolean getIsClientAuthenticated() {\n return isClientAuthenticated;\n }\n\n public String ip() {\n if (userNode != null)\n return userNode.getHostAddress();\n return null;\n }\n\n public InetAddress getAddress() {\n return userNode;\n }\n\n public void setGid(SystemEnvironment sysEnv, Vector v) throws SDMSException {\n if (v.size() == 0) {\n gid = new HashSet();\n return;\n }\n gid = new HashSet(v.size() * 2);\n ", "post_mask_code": "\n }\n\n public void addGid(Long groupId) {\n if (gid == null)\n gid = new HashSet();\n gid.add(groupId);\n }\n\n public void delGid(Long groupId) {\n if (gid == null)\n return;\n gid.remove(groupId);\n }\n\n public void pushGid(SystemEnvironment sysEnv, HashSet g) throws SDMSException {\n groupStack.push(gid);\n gid = g;\n }\n\n public void popGid(SystemEnvironment sysEnv) throws SDMSException {\n if (groupStack.isEmpty())\n throw new FatalException(new SDMSMessage(sysEnv, \"03401301115\", \"Groupstack is empty. Unbalanced change group\"));\n gid = (HashSet) groupStack.pop();\n }\n\n public void emptyGid(SystemEnvironment sysEnv) throws SDMSException {\n while (!groupStack.isEmpty()) {\n SDMSThread.doTrace(this, \"Unbalanced push(gid) : \\n\\t\" + toString(), SDMSThread.SEVERITY_WARNING);\n gid = (HashSet) groupStack.pop();\n }\n }\n\n public int port() {\n return port;\n }\n\n public SyncFifo cmdQueue() {\n return cmdQueue;\n }\n\n public SyncFifo roCmdQueue() {\n return roCmdQueue;\n }\n\n public void setMe(SDMSThread t) {\n me = t;\n }\n\n public SDMSThread getMe() {\n return me;\n }\n\n public ThreadLock lock() {\n return lock;\n }\n\n public boolean isJobServer() {\n return jobServer;\n }\n\n public boolean isJob() {\n return job;\n }\n\n public boolean isUser() {\n return user;\n }\n\n public void setJobServer() {\n jobServer = true;\n job = false;\n user = false;\n }\n\n public void setJob() {\n job = true;\n jobServer = false;\n user = false;\n }\n\n public void setUser() {\n user = true;\n jobServer = false;\n job = false;\n }\n\n public void trace_on() {\n trace = true;\n }\n\n public void trace_off() {\n trace = false;\n }\n\n public void setTrace(boolean t) {\n trace = t;\n }\n\n public boolean trace() {\n return trace;\n }\n\n public void setTraceLevel(int t) {\n tracelevel = t;\n }\n\n public int getTraceLevel() {\n return tracelevel;\n }\n\n public void setLast() {\n last = System.currentTimeMillis();\n }\n\n public SDMSOutputRenderer renderer() {\n return renderer;\n }\n\n public void setRenderer(SDMSOutputRenderer type) {\n renderer = type;\n }\n\n public void setRenderer(int type) {\n renderer = null;\n switch(type) {\n case Parser.XML:\n renderer = new SDMSXmlRenderer();\n break;\n case Parser.LINE:\n renderer = new SDMSLineRenderer();\n break;\n case Parser.PERL:\n renderer = new SDMSPerlRenderer();\n break;\n case Parser.PYTHON:\n renderer = new SDMSPythonRenderer();\n break;\n case Parser.JSON:\n renderer = new SDMSJsonRenderer();\n break;\n case Parser.SERIAL:\n renderer = new SDMSSerialRenderer();\n break;\n case Parser.TIME:\n renderer = new SDMSTimeRenderer();\n break;\n }\n }\n\n public long versionId(SystemEnvironment env) throws SDMSException {\n return tx.versionId(env);\n }\n\n public long txId() {\n return tx.txId;\n }\n\n public void proto_input(String s) {\n ((UserConnection) me).scanner.proto_input(s);\n }\n\n public void setState(int s) {\n if (s == IDLE || s == QUEUED || s == ACTIVE || s == COMMITTING || s == CONNECTED || s == PARSING || s == RENDERING)\n state = s;\n }\n\n public String getState() {\n return stateNames[state];\n }\n\n public String toString() {\n String s = \"Id : \" + id + \", Name : \" + name + \", Start : \" + start + \", Last : \" + last + \", Uid : \" + uid + \", Type : \" + (user ? \"User\" : job ? \"Job\" : \"Jobserver\") + \", Trace : \" + trace + \", Port : \" + port + \", State : \" + stateNames[state];\n return s;\n }\n\n public boolean setConnectedUser(SystemEnvironment sysEnv, Long uid, Vector groups) throws SDMSException {\n prev_uid = this.uid;\n prev_gid = this.gid;\n prev_trace = this.trace;\n prev_tracelevel = this.tracelevel;\n setUid(uid);\n setGid(sysEnv, groups);\n return true;\n }\n\n public boolean resetConnectedUser() {\n if (prev_uid != null) {\n uid = prev_uid;\n gid = prev_gid;\n trace = prev_trace;\n tracelevel = prev_tracelevel;\n prev_uid = null;\n prev_gid = null;\n prev_trace = false;\n prev_tracelevel = 0;\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_2868", "language": "Java", "task_type": "while_statement", "source_file": "java/github/schedulix/schedulix/src/server/ConnectionEnvironment.java", "mask_start_position": 5780, "mask_end_position": 5978, "canonical_solution": "while (!groupStack.isEmpty()) {\n SDMSThread.doTrace(this, \"Unbalanced push(gid) : \\n\\t\" + toString(), SDMSThread.SEVERITY_WARNING);\n gid = (HashSet) groupStack.pop();\n }", "pre_mask_code": "/*\n\nschedulix Enterprise Job Scheduling System\n\nindependIT Integrative Technologies GmbH [http://www.independit.de]\nmailto:example@nnthink.com\n\nThis file is part of schedulix\n\n*/\npackage de.independit.scheduler.server;\n\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*;\nimport java.net.*;\nimport de.independit.scheduler.server.util.*;\nimport de.independit.scheduler.server.repository.*;\nimport de.independit.scheduler.server.exception.*;\nimport de.independit.scheduler.server.output.*;\nimport de.independit.scheduler.server.parser.*;\n\npublic class ConnectionEnvironment {\n\n public final static String __version = \"@(#) $Id: ConnectionEnvironment.java,v 2.12.2.1 2013/03/14 10:24:08 ronald Exp $\";\n\n public static final int IDLE = 0;\n\n public static final int QUEUED = 1;\n\n public static final int ACTIVE = 2;\n\n public static final int COMMITTING = 3;\n\n public static final int CONNECTED = 4;\n\n public static final int PARSING = 5;\n\n public static final int RENDERING = 6;\n\n public static final String[] stateNames = { \"IDLE\", \"QUEUED\", \"ACTIVE\", \"COMMITTING\", \"CONNECTED\", \"PARSING\", \"RENDERING\" };\n\n protected final int id;\n\n protected final String name;\n\n protected long start;\n\n protected long last;\n\n protected Date dStart;\n\n protected PrintStream ostream;\n\n protected Long uid;\n\n protected HashSet gid;\n\n protected SyncFifo cmdQueue;\n\n protected SyncFifo roCmdQueue;\n\n protected SDMSThread me;\n\n protected ThreadLock lock;\n\n protected boolean jobServer;\n\n protected boolean job;\n\n protected boolean user;\n\n public SDMSTransaction tx;\n\n protected SDMSOutputRenderer renderer;\n\n protected boolean trace;\n\n protected int tracelevel;\n\n protected final int port;\n\n protected int state;\n\n public String actstmt;\n\n public String firstToken;\n\n protected InetAddress userNode;\n\n protected String info;\n\n private Stack groupStack;\n\n public SDMSThread worker;\n\n public HashMap SSOInfo;\n\n private boolean isSSLConnection;\n\n private boolean isClientAuthenticated;\n\n protected Long prev_uid;\n\n protected HashSet prev_gid;\n\n protected boolean prev_trace;\n\n protected int prev_tracelevel;\n\n public ConnectionEnvironment(int c, String n, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, int portno, InetAddress uNode, boolean ssl, boolean auth) {\n id = c;\n name = n;\n ostream = o;\n start = System.currentTimeMillis();\n last = start;\n dStart = new Date(start);\n cmdQueue = f;\n roCmdQueue = rof;\n lock = new ThreadLock();\n renderer = new SDMSLineRenderer();\n trace = svrtrc;\n port = portno;\n actstmt = null;\n firstToken = null;\n info = null;\n state = CONNECTED;\n groupStack = new Stack();\n userNode = uNode;\n tracelevel = SDMSThread.SEVERITY_INFO;\n worker = null;\n prev_uid = null;\n isSSLConnection = ssl;\n isClientAuthenticated = auth;\n }\n\n public ConnectionEnvironment(int c, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, int portno, InetAddress uNode, boolean ssl, boolean auth) {\n this(c, null, svrtrc, o, f, rof, portno, uNode, ssl, auth);\n }\n\n public ConnectionEnvironment(int c, String n, boolean svrtrc, PrintStream o, SyncFifo f, SyncFifo rof, InetAddress uNode) {\n this(c, n, svrtrc, o, f, rof, 0, uNode, false, false);\n }\n\n public int id() {\n return id;\n }\n\n public String name() {\n return name != null ? name : new Integer(id).toString();\n }\n\n public long start() {\n return start;\n }\n\n public long last() {\n return last;\n }\n\n public long idle() {\n return ((System.currentTimeMillis() - last + 500) / 1000);\n }\n\n public Date dStart() {\n return dStart;\n }\n\n public PrintStream ostream() {\n return ostream;\n }\n\n public Long uid() {\n return uid;\n }\n\n public HashSet gid() {\n return gid;\n }\n\n public void setUid(Long id) {\n uid = id;\n }\n\n public int timeout() {\n return ((UserConnection) me).getTimeout();\n }\n\n public String getInfo() {\n return info;\n }\n\n public void setInfo(String inf) {\n info = inf;\n }\n\n public boolean getIsSSLConnection() {\n return isSSLConnection;\n }\n\n public boolean getIsClientAuthenticated() {\n return isClientAuthenticated;\n }\n\n public String ip() {\n if (userNode != null)\n return userNode.getHostAddress();\n return null;\n }\n\n public InetAddress getAddress() {\n return userNode;\n }\n\n public void setGid(SystemEnvironment sysEnv, Vector v) throws SDMSException {\n if (v.size() == 0) {\n gid = new HashSet();\n return;\n }\n gid = new HashSet(v.size() * 2);\n for (int i = 0; i < v.size(); i++) {\n gid.add(((SDMSMember) v.get(i)).getGId(sysEnv));\n }\n }\n\n public void addGid(Long groupId) {\n if (gid == null)\n gid = new HashSet();\n gid.add(groupId);\n }\n\n public void delGid(Long groupId) {\n if (gid == null)\n return;\n gid.remove(groupId);\n }\n\n public void pushGid(SystemEnvironment sysEnv, HashSet g) throws SDMSException {\n groupStack.push(gid);\n gid = g;\n }\n\n public void popGid(SystemEnvironment sysEnv) throws SDMSException {\n if (groupStack.isEmpty())\n throw new FatalException(new SDMSMessage(sysEnv, \"03401301115\", \"Groupstack is empty. Unbalanced change group\"));\n gid = (HashSet) groupStack.pop();\n }\n\n public void emptyGid(SystemEnvironment sysEnv) throws SDMSException {\n ", "post_mask_code": "\n }\n\n public int port() {\n return port;\n }\n\n public SyncFifo cmdQueue() {\n return cmdQueue;\n }\n\n public SyncFifo roCmdQueue() {\n return roCmdQueue;\n }\n\n public void setMe(SDMSThread t) {\n me = t;\n }\n\n public SDMSThread getMe() {\n return me;\n }\n\n public ThreadLock lock() {\n return lock;\n }\n\n public boolean isJobServer() {\n return jobServer;\n }\n\n public boolean isJob() {\n return job;\n }\n\n public boolean isUser() {\n return user;\n }\n\n public void setJobServer() {\n jobServer = true;\n job = false;\n user = false;\n }\n\n public void setJob() {\n job = true;\n jobServer = false;\n user = false;\n }\n\n public void setUser() {\n user = true;\n jobServer = false;\n job = false;\n }\n\n public void trace_on() {\n trace = true;\n }\n\n public void trace_off() {\n trace = false;\n }\n\n public void setTrace(boolean t) {\n trace = t;\n }\n\n public boolean trace() {\n return trace;\n }\n\n public void setTraceLevel(int t) {\n tracelevel = t;\n }\n\n public int getTraceLevel() {\n return tracelevel;\n }\n\n public void setLast() {\n last = System.currentTimeMillis();\n }\n\n public SDMSOutputRenderer renderer() {\n return renderer;\n }\n\n public void setRenderer(SDMSOutputRenderer type) {\n renderer = type;\n }\n\n public void setRenderer(int type) {\n renderer = null;\n switch(type) {\n case Parser.XML:\n renderer = new SDMSXmlRenderer();\n break;\n case Parser.LINE:\n renderer = new SDMSLineRenderer();\n break;\n case Parser.PERL:\n renderer = new SDMSPerlRenderer();\n break;\n case Parser.PYTHON:\n renderer = new SDMSPythonRenderer();\n break;\n case Parser.JSON:\n renderer = new SDMSJsonRenderer();\n break;\n case Parser.SERIAL:\n renderer = new SDMSSerialRenderer();\n break;\n case Parser.TIME:\n renderer = new SDMSTimeRenderer();\n break;\n }\n }\n\n public long versionId(SystemEnvironment env) throws SDMSException {\n return tx.versionId(env);\n }\n\n public long txId() {\n return tx.txId;\n }\n\n public void proto_input(String s) {\n ((UserConnection) me).scanner.proto_input(s);\n }\n\n public void setState(int s) {\n if (s == IDLE || s == QUEUED || s == ACTIVE || s == COMMITTING || s == CONNECTED || s == PARSING || s == RENDERING)\n state = s;\n }\n\n public String getState() {\n return stateNames[state];\n }\n\n public String toString() {\n String s = \"Id : \" + id + \", Name : \" + name + \", Start : \" + start + \", Last : \" + last + \", Uid : \" + uid + \", Type : \" + (user ? \"User\" : job ? \"Job\" : \"Jobserver\") + \", Trace : \" + trace + \", Port : \" + port + \", State : \" + stateNames[state];\n return s;\n }\n\n public boolean setConnectedUser(SystemEnvironment sysEnv, Long uid, Vector groups) throws SDMSException {\n prev_uid = this.uid;\n prev_gid = this.gid;\n prev_trace = this.trace;\n prev_tracelevel = this.tracelevel;\n setUid(uid);\n setGid(sysEnv, groups);\n return true;\n }\n\n public boolean resetConnectedUser() {\n if (prev_uid != null) {\n uid = prev_uid;\n gid = prev_gid;\n trace = prev_trace;\n tracelevel = prev_tracelevel;\n prev_uid = null;\n prev_gid = null;\n prev_trace = false;\n prev_tracelevel = 0;\n return true;\n }\n return false;\n }\n}\n"} {"task_id": "Java_2869", "language": "Java", "task_type": "method_signature", "source_file": "java/github/schemeway/SchemeScript/plugin/src/org/schemeway/plugins/schemescript/dictionary/SymbolSearchQuery.java", "mask_start_position": 708, "mask_end_position": 747, "canonical_solution": "public ISearchResult getSearchResult() ", "pre_mask_code": "package org.schemeway.plugins.schemescript.dictionary;\n\nimport org.eclipse.core.runtime.*;\nimport org.eclipse.search.ui.*;\nimport org.eclipse.search.ui.text.*;\nimport org.schemeway.plugins.schemescript.*;\n\nclass SymbolSearchQuery implements ISearchQuery {\n\n private String mSearchSymbol;\n\n private SymbolSearchResult mSearchResult;\n\n public SymbolSearchQuery(String searchSymbol) {\n mSearchSymbol = searchSymbol;\n mSearchResult = new SymbolSearchResult(this);\n }\n\n public boolean canRunInBackground() {\n return true;\n }\n\n public boolean canRerun() {\n return true;\n }\n\n public String getLabel() {\n return \"Search for \" + mSearchSymbol;\n }\n\n ", "post_mask_code": "{\n return mSearchResult;\n }\n\n public IStatus run(IProgressMonitor monitor) throws OperationCanceledException {\n SymbolReferencesManager referencesManager = SchemeScriptPlugin.getReferencesManager();\n SymbolReferencesTable referencesTable = referencesManager.getSymbolReferencesTable();\n Reference[] references = referencesTable.getReferences(mSearchSymbol);\n Match[] matches = new Match[references.length];\n for (int referenceIndex = 0; referenceIndex < references.length; referenceIndex++) {\n Reference reference = references[referenceIndex];\n matches[referenceIndex] = new Match(reference.resource, reference.offset, reference.length);\n }\n mSearchResult.addMatches(matches);\n return Status.OK_STATUS;\n }\n}\n"} {"task_id": "Java_2870", "language": "Java", "task_type": "method_body", "source_file": "java/github/schemeway/SchemeScript/plugin/src/org/schemeway/plugins/schemescript/dictionary/SymbolSearchQuery.java", "mask_start_position": 747, "mask_end_position": 784, "canonical_solution": "{\n return mSearchResult;\n }", "pre_mask_code": "package org.schemeway.plugins.schemescript.dictionary;\n\nimport org.eclipse.core.runtime.*;\nimport org.eclipse.search.ui.*;\nimport org.eclipse.search.ui.text.*;\nimport org.schemeway.plugins.schemescript.*;\n\nclass SymbolSearchQuery implements ISearchQuery {\n\n private String mSearchSymbol;\n\n private SymbolSearchResult mSearchResult;\n\n public SymbolSearchQuery(String searchSymbol) {\n mSearchSymbol = searchSymbol;\n mSearchResult = new SymbolSearchResult(this);\n }\n\n public boolean canRunInBackground() {\n return true;\n }\n\n public boolean canRerun() {\n return true;\n }\n\n public String getLabel() {\n return \"Search for \" + mSearchSymbol;\n }\n\n public ISearchResult getSearchResult() ", "post_mask_code": "\n\n public IStatus run(IProgressMonitor monitor) throws OperationCanceledException {\n SymbolReferencesManager referencesManager = SchemeScriptPlugin.getReferencesManager();\n SymbolReferencesTable referencesTable = referencesManager.getSymbolReferencesTable();\n Reference[] references = referencesTable.getReferences(mSearchSymbol);\n Match[] matches = new Match[references.length];\n for (int referenceIndex = 0; referenceIndex < references.length; referenceIndex++) {\n Reference reference = references[referenceIndex];\n matches[referenceIndex] = new Match(reference.resource, reference.offset, reference.length);\n }\n mSearchResult.addMatches(matches);\n return Status.OK_STATUS;\n }\n}\n"} {"task_id": "Java_2871", "language": "Java", "task_type": "single_line", "source_file": "java/github/schemeway/SchemeScript/plugin/src/org/schemeway/plugins/schemescript/dictionary/SymbolSearchQuery.java", "mask_start_position": 1186, "mask_end_position": 1194, "canonical_solution": "length];", "pre_mask_code": "package org.schemeway.plugins.schemescript.dictionary;\n\nimport org.eclipse.core.runtime.*;\nimport org.eclipse.search.ui.*;\nimport org.eclipse.search.ui.text.*;\nimport org.schemeway.plugins.schemescript.*;\n\nclass SymbolSearchQuery implements ISearchQuery {\n\n private String mSearchSymbol;\n\n private SymbolSearchResult mSearchResult;\n\n public SymbolSearchQuery(String searchSymbol) {\n mSearchSymbol = searchSymbol;\n mSearchResult = new SymbolSearchResult(this);\n }\n\n public boolean canRunInBackground() {\n return true;\n }\n\n public boolean canRerun() {\n return true;\n }\n\n public String getLabel() {\n return \"Search for \" + mSearchSymbol;\n }\n\n public ISearchResult getSearchResult() {\n return mSearchResult;\n }\n\n public IStatus run(IProgressMonitor monitor) throws OperationCanceledException {\n SymbolReferencesManager referencesManager = SchemeScriptPlugin.getReferencesManager();\n SymbolReferencesTable referencesTable = referencesManager.getSymbolReferencesTable();\n Reference[] references = referencesTable.getReferences(mSearchSymbol);\n Match[] matches = new Match[references.", "post_mask_code": "\n for (int referenceIndex = 0; referenceIndex < references.length; referenceIndex++) {\n Reference reference = references[referenceIndex];\n matches[referenceIndex] = new Match(reference.resource, reference.offset, reference.length);\n }\n mSearchResult.addMatches(matches);\n return Status.OK_STATUS;\n }\n}\n"} {"task_id": "Java_2872", "language": "Java", "task_type": "for_statement", "source_file": "java/github/schemeway/SchemeScript/plugin/src/org/schemeway/plugins/schemescript/dictionary/SymbolSearchQuery.java", "mask_start_position": 1203, "mask_end_position": 1464, "canonical_solution": "for (int referenceIndex = 0; referenceIndex < references.length; referenceIndex++) {\n Reference reference = references[referenceIndex];\n matches[referenceIndex] = new Match(reference.resource, reference.offset, reference.length);\n }", "pre_mask_code": "package org.schemeway.plugins.schemescript.dictionary;\n\nimport org.eclipse.core.runtime.*;\nimport org.eclipse.search.ui.*;\nimport org.eclipse.search.ui.text.*;\nimport org.schemeway.plugins.schemescript.*;\n\nclass SymbolSearchQuery implements ISearchQuery {\n\n private String mSearchSymbol;\n\n private SymbolSearchResult mSearchResult;\n\n public SymbolSearchQuery(String searchSymbol) {\n mSearchSymbol = searchSymbol;\n mSearchResult = new SymbolSearchResult(this);\n }\n\n public boolean canRunInBackground() {\n return true;\n }\n\n public boolean canRerun() {\n return true;\n }\n\n public String getLabel() {\n return \"Search for \" + mSearchSymbol;\n }\n\n public ISearchResult getSearchResult() {\n return mSearchResult;\n }\n\n public IStatus run(IProgressMonitor monitor) throws OperationCanceledException {\n SymbolReferencesManager referencesManager = SchemeScriptPlugin.getReferencesManager();\n SymbolReferencesTable referencesTable = referencesManager.getSymbolReferencesTable();\n Reference[] references = referencesTable.getReferences(mSearchSymbol);\n Match[] matches = new Match[references.length];\n ", "post_mask_code": "\n mSearchResult.addMatches(matches);\n return Status.OK_STATUS;\n }\n}\n"} {"task_id": "Java_2873", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/netbeans/contrib/websvc.wsitconf/src/org/netbeans/modules/websvc/wsitconf/ui/service/profiles/MessageAuthenticationProfile.java", "mask_start_position": 12432, "mask_end_position": 12509, "canonical_solution": "public boolean isTrustStoreRequired(WSDLComponent component, boolean client) ", "pre_mask_code": "package org.netbeans.modules.websvc.wsitconf.ui.service.profiles;\n\nimport java.awt.Dialog;\nimport javax.swing.JPanel;\nimport javax.swing.undo.UndoManager;\nimport org.netbeans.api.project.Project;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.AdvancedSecurityFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ClientDefaultsFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.SecureConversationFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ServiceDefaultsFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.TrustStoreFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ValidatorsFeature;\nimport org.netbeans.modules.websvc.wsitconf.ui.ComboConstants;\nimport org.netbeans.modules.websvc.wsitconf.util.UndoCounter;\nimport org.netbeans.modules.websvc.wsitconf.util.Util;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.AlgoSuiteModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.PolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.ProfilesModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.ProprietarySecurityPolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.RMModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.SecurityPolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.SecurityTokensModelHelper;\nimport org.netbeans.modules.websvc.wsitmodelext.policy.Policy;\nimport org.netbeans.modules.websvc.wsitmodelext.policy.PolicyQName;\nimport org.netbeans.modules.websvc.wsitmodelext.security.BootstrapPolicy;\nimport org.netbeans.modules.websvc.wsitmodelext.security.SecurityPolicyQName;\nimport org.netbeans.modules.websvc.wsitmodelext.security.TransportBinding;\nimport org.netbeans.modules.websvc.wsitmodelext.security.TrustElement;\nimport org.netbeans.modules.websvc.wsitmodelext.security.WssElement;\nimport org.netbeans.modules.websvc.wsitmodelext.security.proprietary.CallbackHandler;\nimport org.netbeans.modules.websvc.wsitmodelext.security.tokens.SecureConversationToken;\nimport org.netbeans.modules.websvc.wsitmodelext.versioning.ConfigVersion;\nimport org.netbeans.modules.xml.wsdl.model.Binding;\nimport org.netbeans.modules.xml.wsdl.model.WSDLComponent;\nimport org.netbeans.modules.xml.wsdl.model.WSDLModel;\nimport org.openide.DialogDescriptor;\nimport org.openide.DialogDisplayer;\n\n/**\n * Transport Security Profile definition\n *\n * @author Martin Grebac\n */\n@org.openide.util.lookup.ServiceProvider(service = org.netbeans.modules.websvc.wsitconf.spi.SecurityProfile.class)\npublic class MessageAuthenticationProfile extends ProfileBase implements SecureConversationFeature, ClientDefaultsFeature, ServiceDefaultsFeature, ValidatorsFeature, AdvancedSecurityFeature, TrustStoreFeature {\n\n private static final String DEFAULT_USERNAME = \"wsit\";\n\n private static final String DEFAULT_PASSWORD = \"wsitPassword\";\n\n public int getId() {\n return 40;\n }\n\n public String getDisplayName() {\n return ComboConstants.PROF_MSGAUTHSSL;\n }\n\n public String getDescription() {\n return ComboConstants.PROF_MSGAUTHSSL_INFO;\n }\n\n /**\n * Should return true if the profile is set on component, false otherwise\n */\n public boolean isCurrentProfile(WSDLComponent component) {\n return getDisplayName().equals(ProfilesModelHelper.getWSITSecurityProfile(component));\n }\n\n @Override()\n public void displayConfig(WSDLComponent component, UndoManager undoManager) {\n UndoCounter undoCounter = new UndoCounter();\n WSDLModel model = component.getModel();\n model.addUndoableEditListener(undoCounter);\n JPanel profConfigPanel = new MessageAuthentication(component, this);\n DialogDescriptor dlgDesc = new DialogDescriptor(profConfigPanel, getDisplayName());\n Dialog dlg = DialogDisplayer.getDefault().createDialog(dlgDesc);\n dlg.setVisible(true);\n if (dlgDesc.getValue() == DialogDescriptor.CANCEL_OPTION) {\n for (int i = 0; i < undoCounter.getCounter(); i++) {\n if (undoManager.canUndo()) {\n undoManager.undo();\n }\n }\n }\n model.removeUndoableEditListener(undoCounter);\n }\n\n public void setServiceDefaults(WSDLComponent component, Project p) {\n ProprietarySecurityPolicyModelHelper.clearValidators(component);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, false, false);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, true, false);\n }\n\n public void setClientDefaults(WSDLComponent component, WSDLComponent serviceBinding, Project p) {\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, false, true);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, true, true);\n ProprietarySecurityPolicyModelHelper.removeCallbackHandlerConfiguration((Binding) component);\n ProprietarySecurityPolicyModelHelper.setCallbackHandler((Binding) component, CallbackHandler.USERNAME_CBHANDLER, null, DEFAULT_USERNAME, true);\n ProprietarySecurityPolicyModelHelper.setCallbackHandler((Binding) component, CallbackHandler.PASSWORD_CBHANDLER, null, DEFAULT_PASSWORD, true);\n }\n\n public boolean isServiceDefaultSetupUsed(WSDLComponent component, Project p) {\n if (ProprietarySecurityPolicyModelHelper.isAnyValidatorSet(component))\n return false;\n String keyAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, false);\n String trustAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, true);\n String trustLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, true);\n String keyLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, false);\n String keyPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, false);\n String trustPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, true);\n if ((keyAlias == null) && (trustAlias == null) && (trustLoc == null) && (keyLoc == null) && (trustPasswd == null) && (keyPasswd == null)) {\n return true;\n }\n return false;\n }\n\n public boolean isClientDefaultSetupUsed(WSDLComponent component, Binding serviceBinding, Project p) {\n if (ProprietarySecurityPolicyModelHelper.isAnyValidatorSet(component))\n return false;\n String trustLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, true);\n String keyLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, false);\n String keyPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, false);\n String trustPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, true);\n String keyAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, false);\n String trustAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, true);\n if ((keyAlias == null) && (trustAlias == null) && (trustLoc == null) && (keyLoc == null) && (trustPasswd == null) && (keyPasswd == null)) {\n String user = ProprietarySecurityPolicyModelHelper.getDefaultUsername((Binding) component);\n String passwd = ProprietarySecurityPolicyModelHelper.getDefaultPassword((Binding) component);\n if (Util.isEqual(DEFAULT_PASSWORD, passwd) && Util.isEqual(DEFAULT_USERNAME, user)) {\n return true;\n }\n }\n return false;\n }\n\n public boolean isSecureConversation(WSDLComponent component) {\n WSDLComponent endToken = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n return (endToken != null);\n }\n\n public void enableSecureConversation(WSDLComponent component, boolean enable) {\n ConfigVersion cfgVersion = PolicyModelHelper.getConfigVersion(component);\n SecurityTokensModelHelper stmh = SecurityTokensModelHelper.getInstance(cfgVersion);\n if (enable) {\n WSDLModel model = component.getModel();\n boolean isTransaction = model.isIntransaction();\n if (!isTransaction) {\n model.startTransaction();\n }\n try {\n SecurityPolicyModelHelper securityPolicyModelHelper = SecurityPolicyModelHelper.getInstance(cfgVersion);\n AlgoSuiteModelHelper asmh = AlgoSuiteModelHelper.getInstance(cfgVersion);\n RMModelHelper rmh = RMModelHelper.getInstance(cfgVersion);\n PolicyModelHelper ProprietarySecurityPolicyModelHelper = PolicyModelHelper.getInstance(cfgVersion);\n securityPolicyModelHelper.enableTrust(component, cfgVersion);\n SecurityTokensModelHelper.removeSupportingTokens(component);\n WSDLComponent suppToken = stmh.setSupportingTokens(component, ComboConstants.SECURECONVERSATION, SecurityTokensModelHelper.ENDORSING);\n Policy p = ProprietarySecurityPolicyModelHelper.createElement(suppToken, PolicyQName.POLICY.getQName(cfgVersion), Policy.class, false);\n BootstrapPolicy bp = ProprietarySecurityPolicyModelHelper.createElement(p, SecurityPolicyQName.BOOTSTRAPPOLICY.getQName(cfgVersion), BootstrapPolicy.class, false);\n p = ProprietarySecurityPolicyModelHelper.createElement(bp, PolicyQName.POLICY.getQName(cfgVersion), Policy.class, false);\n TransportBinding tb = ProprietarySecurityPolicyModelHelper.createElement(p, SecurityPolicyQName.TRANSPORTBINDING.getQName(cfgVersion), TransportBinding.class, false);\n boolean rm = rmh.isRMEnabled(component);\n securityPolicyModelHelper.setDefaultTargets(p, true, rm);\n stmh.setTokenType(tb, ComboConstants.TRANSPORT, ComboConstants.HTTPS);\n securityPolicyModelHelper.setLayout(tb, ComboConstants.STRICT);\n securityPolicyModelHelper.enableIncludeTimestamp(tb, true);\n asmh.setAlgorithmSuite(tb, ComboConstants.BASIC128);\n if (ConfigVersion.CONFIG_1_0.equals(cfgVersion)) {\n stmh.setSupportingTokens(p, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_SUPPORTING);\n } else {\n stmh.setSupportingTokens(p, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_ENCRYPTED);\n }\n WssElement wss = securityPolicyModelHelper.enableWss(bp, true);\n securityPolicyModelHelper.enableMustSupportRefIssuerSerial(wss, true);\n securityPolicyModelHelper.enableMustSupportRefThumbprint(wss, true);\n securityPolicyModelHelper.enableMustSupportRefEncryptedKey(wss, true);\n TrustElement trust = securityPolicyModelHelper.enableTrust(bp, cfgVersion);\n securityPolicyModelHelper.enableMustSupportIssuedTokens(trust, true);\n securityPolicyModelHelper.enableRequireClientEntropy(trust, true);\n securityPolicyModelHelper.enableRequireServerEntropy(trust, true);\n } finally {\n if (!isTransaction) {\n model.endTransaction();\n }\n }\n } else {\n SecurityTokensModelHelper.removeSupportingTokens(component);\n if (ConfigVersion.CONFIG_1_0.equals(cfgVersion)) {\n stmh.setSupportingTokens(component, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_SUPPORTING);\n } else {\n stmh.setSupportingTokens(component, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_ENCRYPTED);\n }\n }\n }\n\n @Override\n public void profileSelected(WSDLComponent component, boolean updateServiceUrl, ConfigVersion configVersion) {\n ProfilesModelHelper pmh = ProfilesModelHelper.getInstance(configVersion);\n RMModelHelper rmh = RMModelHelper.getInstance(configVersion);\n pmh.setSecurityProfile(component, getDisplayName(), updateServiceUrl);\n boolean isRM = rmh.isRMEnabled(component);\n if (isRM) {\n enableSecureConversation(component, true);\n }\n }\n\n public boolean isValidatorSupported(ConfigVersion cfgVersion, String validatorType) {\n return true;\n }\n\n ", "post_mask_code": "{\n WSDLComponent secBinding = null;\n WSDLComponent endToken = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n WSDLComponent secConvT = SecurityTokensModelHelper.getTokenElement(endToken, SecureConversationToken.class);\n boolean secConv = (secConvT instanceof SecureConversationToken);\n if (secConv) {\n WSDLComponent bootPolicy = SecurityTokensModelHelper.getTokenElement(secConvT, BootstrapPolicy.class);\n secBinding = SecurityPolicyModelHelper.getSecurityBindingTypeElement(bootPolicy);\n Policy p = (Policy) secBinding.getParent();\n p = PolicyModelHelper.getTopLevelElement(bootPolicy, Policy.class, false);\n WSDLComponent tokenKind = SecurityTokensModelHelper.getSupportingToken(p, SecurityTokensModelHelper.ENDORSING);\n if (tokenKind == null) {\n return false;\n }\n } else {\n secBinding = SecurityPolicyModelHelper.getSecurityBindingTypeElement(component);\n WSDLComponent tokenKind = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n if (tokenKind == null) {\n return false;\n }\n }\n return true;\n }\n}\n"} {"task_id": "Java_2874", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/netbeans/contrib/websvc.wsitconf/src/org/netbeans/modules/websvc/wsitconf/ui/service/profiles/MessageAuthenticationProfile.java", "mask_start_position": 3117, "mask_end_position": 3176, "canonical_solution": "{\n return ComboConstants.PROF_MSGAUTHSSL_INFO;\n }", "pre_mask_code": "package org.netbeans.modules.websvc.wsitconf.ui.service.profiles;\n\nimport java.awt.Dialog;\nimport javax.swing.JPanel;\nimport javax.swing.undo.UndoManager;\nimport org.netbeans.api.project.Project;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.AdvancedSecurityFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ClientDefaultsFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.SecureConversationFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ServiceDefaultsFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.TrustStoreFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ValidatorsFeature;\nimport org.netbeans.modules.websvc.wsitconf.ui.ComboConstants;\nimport org.netbeans.modules.websvc.wsitconf.util.UndoCounter;\nimport org.netbeans.modules.websvc.wsitconf.util.Util;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.AlgoSuiteModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.PolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.ProfilesModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.ProprietarySecurityPolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.RMModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.SecurityPolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.SecurityTokensModelHelper;\nimport org.netbeans.modules.websvc.wsitmodelext.policy.Policy;\nimport org.netbeans.modules.websvc.wsitmodelext.policy.PolicyQName;\nimport org.netbeans.modules.websvc.wsitmodelext.security.BootstrapPolicy;\nimport org.netbeans.modules.websvc.wsitmodelext.security.SecurityPolicyQName;\nimport org.netbeans.modules.websvc.wsitmodelext.security.TransportBinding;\nimport org.netbeans.modules.websvc.wsitmodelext.security.TrustElement;\nimport org.netbeans.modules.websvc.wsitmodelext.security.WssElement;\nimport org.netbeans.modules.websvc.wsitmodelext.security.proprietary.CallbackHandler;\nimport org.netbeans.modules.websvc.wsitmodelext.security.tokens.SecureConversationToken;\nimport org.netbeans.modules.websvc.wsitmodelext.versioning.ConfigVersion;\nimport org.netbeans.modules.xml.wsdl.model.Binding;\nimport org.netbeans.modules.xml.wsdl.model.WSDLComponent;\nimport org.netbeans.modules.xml.wsdl.model.WSDLModel;\nimport org.openide.DialogDescriptor;\nimport org.openide.DialogDisplayer;\n\n/**\n * Transport Security Profile definition\n *\n * @author Martin Grebac\n */\n@org.openide.util.lookup.ServiceProvider(service = org.netbeans.modules.websvc.wsitconf.spi.SecurityProfile.class)\npublic class MessageAuthenticationProfile extends ProfileBase implements SecureConversationFeature, ClientDefaultsFeature, ServiceDefaultsFeature, ValidatorsFeature, AdvancedSecurityFeature, TrustStoreFeature {\n\n private static final String DEFAULT_USERNAME = \"wsit\";\n\n private static final String DEFAULT_PASSWORD = \"wsitPassword\";\n\n public int getId() {\n return 40;\n }\n\n public String getDisplayName() {\n return ComboConstants.PROF_MSGAUTHSSL;\n }\n\n public String getDescription() ", "post_mask_code": "\n\n /**\n * Should return true if the profile is set on component, false otherwise\n */\n public boolean isCurrentProfile(WSDLComponent component) {\n return getDisplayName().equals(ProfilesModelHelper.getWSITSecurityProfile(component));\n }\n\n @Override()\n public void displayConfig(WSDLComponent component, UndoManager undoManager) {\n UndoCounter undoCounter = new UndoCounter();\n WSDLModel model = component.getModel();\n model.addUndoableEditListener(undoCounter);\n JPanel profConfigPanel = new MessageAuthentication(component, this);\n DialogDescriptor dlgDesc = new DialogDescriptor(profConfigPanel, getDisplayName());\n Dialog dlg = DialogDisplayer.getDefault().createDialog(dlgDesc);\n dlg.setVisible(true);\n if (dlgDesc.getValue() == DialogDescriptor.CANCEL_OPTION) {\n for (int i = 0; i < undoCounter.getCounter(); i++) {\n if (undoManager.canUndo()) {\n undoManager.undo();\n }\n }\n }\n model.removeUndoableEditListener(undoCounter);\n }\n\n public void setServiceDefaults(WSDLComponent component, Project p) {\n ProprietarySecurityPolicyModelHelper.clearValidators(component);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, false, false);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, true, false);\n }\n\n public void setClientDefaults(WSDLComponent component, WSDLComponent serviceBinding, Project p) {\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, false, true);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, true, true);\n ProprietarySecurityPolicyModelHelper.removeCallbackHandlerConfiguration((Binding) component);\n ProprietarySecurityPolicyModelHelper.setCallbackHandler((Binding) component, CallbackHandler.USERNAME_CBHANDLER, null, DEFAULT_USERNAME, true);\n ProprietarySecurityPolicyModelHelper.setCallbackHandler((Binding) component, CallbackHandler.PASSWORD_CBHANDLER, null, DEFAULT_PASSWORD, true);\n }\n\n public boolean isServiceDefaultSetupUsed(WSDLComponent component, Project p) {\n if (ProprietarySecurityPolicyModelHelper.isAnyValidatorSet(component))\n return false;\n String keyAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, false);\n String trustAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, true);\n String trustLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, true);\n String keyLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, false);\n String keyPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, false);\n String trustPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, true);\n if ((keyAlias == null) && (trustAlias == null) && (trustLoc == null) && (keyLoc == null) && (trustPasswd == null) && (keyPasswd == null)) {\n return true;\n }\n return false;\n }\n\n public boolean isClientDefaultSetupUsed(WSDLComponent component, Binding serviceBinding, Project p) {\n if (ProprietarySecurityPolicyModelHelper.isAnyValidatorSet(component))\n return false;\n String trustLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, true);\n String keyLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, false);\n String keyPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, false);\n String trustPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, true);\n String keyAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, false);\n String trustAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, true);\n if ((keyAlias == null) && (trustAlias == null) && (trustLoc == null) && (keyLoc == null) && (trustPasswd == null) && (keyPasswd == null)) {\n String user = ProprietarySecurityPolicyModelHelper.getDefaultUsername((Binding) component);\n String passwd = ProprietarySecurityPolicyModelHelper.getDefaultPassword((Binding) component);\n if (Util.isEqual(DEFAULT_PASSWORD, passwd) && Util.isEqual(DEFAULT_USERNAME, user)) {\n return true;\n }\n }\n return false;\n }\n\n public boolean isSecureConversation(WSDLComponent component) {\n WSDLComponent endToken = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n return (endToken != null);\n }\n\n public void enableSecureConversation(WSDLComponent component, boolean enable) {\n ConfigVersion cfgVersion = PolicyModelHelper.getConfigVersion(component);\n SecurityTokensModelHelper stmh = SecurityTokensModelHelper.getInstance(cfgVersion);\n if (enable) {\n WSDLModel model = component.getModel();\n boolean isTransaction = model.isIntransaction();\n if (!isTransaction) {\n model.startTransaction();\n }\n try {\n SecurityPolicyModelHelper securityPolicyModelHelper = SecurityPolicyModelHelper.getInstance(cfgVersion);\n AlgoSuiteModelHelper asmh = AlgoSuiteModelHelper.getInstance(cfgVersion);\n RMModelHelper rmh = RMModelHelper.getInstance(cfgVersion);\n PolicyModelHelper ProprietarySecurityPolicyModelHelper = PolicyModelHelper.getInstance(cfgVersion);\n securityPolicyModelHelper.enableTrust(component, cfgVersion);\n SecurityTokensModelHelper.removeSupportingTokens(component);\n WSDLComponent suppToken = stmh.setSupportingTokens(component, ComboConstants.SECURECONVERSATION, SecurityTokensModelHelper.ENDORSING);\n Policy p = ProprietarySecurityPolicyModelHelper.createElement(suppToken, PolicyQName.POLICY.getQName(cfgVersion), Policy.class, false);\n BootstrapPolicy bp = ProprietarySecurityPolicyModelHelper.createElement(p, SecurityPolicyQName.BOOTSTRAPPOLICY.getQName(cfgVersion), BootstrapPolicy.class, false);\n p = ProprietarySecurityPolicyModelHelper.createElement(bp, PolicyQName.POLICY.getQName(cfgVersion), Policy.class, false);\n TransportBinding tb = ProprietarySecurityPolicyModelHelper.createElement(p, SecurityPolicyQName.TRANSPORTBINDING.getQName(cfgVersion), TransportBinding.class, false);\n boolean rm = rmh.isRMEnabled(component);\n securityPolicyModelHelper.setDefaultTargets(p, true, rm);\n stmh.setTokenType(tb, ComboConstants.TRANSPORT, ComboConstants.HTTPS);\n securityPolicyModelHelper.setLayout(tb, ComboConstants.STRICT);\n securityPolicyModelHelper.enableIncludeTimestamp(tb, true);\n asmh.setAlgorithmSuite(tb, ComboConstants.BASIC128);\n if (ConfigVersion.CONFIG_1_0.equals(cfgVersion)) {\n stmh.setSupportingTokens(p, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_SUPPORTING);\n } else {\n stmh.setSupportingTokens(p, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_ENCRYPTED);\n }\n WssElement wss = securityPolicyModelHelper.enableWss(bp, true);\n securityPolicyModelHelper.enableMustSupportRefIssuerSerial(wss, true);\n securityPolicyModelHelper.enableMustSupportRefThumbprint(wss, true);\n securityPolicyModelHelper.enableMustSupportRefEncryptedKey(wss, true);\n TrustElement trust = securityPolicyModelHelper.enableTrust(bp, cfgVersion);\n securityPolicyModelHelper.enableMustSupportIssuedTokens(trust, true);\n securityPolicyModelHelper.enableRequireClientEntropy(trust, true);\n securityPolicyModelHelper.enableRequireServerEntropy(trust, true);\n } finally {\n if (!isTransaction) {\n model.endTransaction();\n }\n }\n } else {\n SecurityTokensModelHelper.removeSupportingTokens(component);\n if (ConfigVersion.CONFIG_1_0.equals(cfgVersion)) {\n stmh.setSupportingTokens(component, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_SUPPORTING);\n } else {\n stmh.setSupportingTokens(component, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_ENCRYPTED);\n }\n }\n }\n\n @Override\n public void profileSelected(WSDLComponent component, boolean updateServiceUrl, ConfigVersion configVersion) {\n ProfilesModelHelper pmh = ProfilesModelHelper.getInstance(configVersion);\n RMModelHelper rmh = RMModelHelper.getInstance(configVersion);\n pmh.setSecurityProfile(component, getDisplayName(), updateServiceUrl);\n boolean isRM = rmh.isRMEnabled(component);\n if (isRM) {\n enableSecureConversation(component, true);\n }\n }\n\n public boolean isValidatorSupported(ConfigVersion cfgVersion, String validatorType) {\n return true;\n }\n\n public boolean isTrustStoreRequired(WSDLComponent component, boolean client) {\n WSDLComponent secBinding = null;\n WSDLComponent endToken = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n WSDLComponent secConvT = SecurityTokensModelHelper.getTokenElement(endToken, SecureConversationToken.class);\n boolean secConv = (secConvT instanceof SecureConversationToken);\n if (secConv) {\n WSDLComponent bootPolicy = SecurityTokensModelHelper.getTokenElement(secConvT, BootstrapPolicy.class);\n secBinding = SecurityPolicyModelHelper.getSecurityBindingTypeElement(bootPolicy);\n Policy p = (Policy) secBinding.getParent();\n p = PolicyModelHelper.getTopLevelElement(bootPolicy, Policy.class, false);\n WSDLComponent tokenKind = SecurityTokensModelHelper.getSupportingToken(p, SecurityTokensModelHelper.ENDORSING);\n if (tokenKind == null) {\n return false;\n }\n } else {\n secBinding = SecurityPolicyModelHelper.getSecurityBindingTypeElement(component);\n WSDLComponent tokenKind = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n if (tokenKind == null) {\n return false;\n }\n }\n return true;\n }\n}\n"} {"task_id": "Java_2875", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/netbeans/contrib/websvc.wsitconf/src/org/netbeans/modules/websvc/wsitconf/ui/service/profiles/MessageAuthenticationProfile.java", "mask_start_position": 7632, "mask_end_position": 7641, "canonical_solution": "rn false;", "pre_mask_code": "package org.netbeans.modules.websvc.wsitconf.ui.service.profiles;\n\nimport java.awt.Dialog;\nimport javax.swing.JPanel;\nimport javax.swing.undo.UndoManager;\nimport org.netbeans.api.project.Project;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.AdvancedSecurityFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ClientDefaultsFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.SecureConversationFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ServiceDefaultsFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.TrustStoreFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ValidatorsFeature;\nimport org.netbeans.modules.websvc.wsitconf.ui.ComboConstants;\nimport org.netbeans.modules.websvc.wsitconf.util.UndoCounter;\nimport org.netbeans.modules.websvc.wsitconf.util.Util;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.AlgoSuiteModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.PolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.ProfilesModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.ProprietarySecurityPolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.RMModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.SecurityPolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.SecurityTokensModelHelper;\nimport org.netbeans.modules.websvc.wsitmodelext.policy.Policy;\nimport org.netbeans.modules.websvc.wsitmodelext.policy.PolicyQName;\nimport org.netbeans.modules.websvc.wsitmodelext.security.BootstrapPolicy;\nimport org.netbeans.modules.websvc.wsitmodelext.security.SecurityPolicyQName;\nimport org.netbeans.modules.websvc.wsitmodelext.security.TransportBinding;\nimport org.netbeans.modules.websvc.wsitmodelext.security.TrustElement;\nimport org.netbeans.modules.websvc.wsitmodelext.security.WssElement;\nimport org.netbeans.modules.websvc.wsitmodelext.security.proprietary.CallbackHandler;\nimport org.netbeans.modules.websvc.wsitmodelext.security.tokens.SecureConversationToken;\nimport org.netbeans.modules.websvc.wsitmodelext.versioning.ConfigVersion;\nimport org.netbeans.modules.xml.wsdl.model.Binding;\nimport org.netbeans.modules.xml.wsdl.model.WSDLComponent;\nimport org.netbeans.modules.xml.wsdl.model.WSDLModel;\nimport org.openide.DialogDescriptor;\nimport org.openide.DialogDisplayer;\n\n/**\n * Transport Security Profile definition\n *\n * @author Martin Grebac\n */\n@org.openide.util.lookup.ServiceProvider(service = org.netbeans.modules.websvc.wsitconf.spi.SecurityProfile.class)\npublic class MessageAuthenticationProfile extends ProfileBase implements SecureConversationFeature, ClientDefaultsFeature, ServiceDefaultsFeature, ValidatorsFeature, AdvancedSecurityFeature, TrustStoreFeature {\n\n private static final String DEFAULT_USERNAME = \"wsit\";\n\n private static final String DEFAULT_PASSWORD = \"wsitPassword\";\n\n public int getId() {\n return 40;\n }\n\n public String getDisplayName() {\n return ComboConstants.PROF_MSGAUTHSSL;\n }\n\n public String getDescription() {\n return ComboConstants.PROF_MSGAUTHSSL_INFO;\n }\n\n /**\n * Should return true if the profile is set on component, false otherwise\n */\n public boolean isCurrentProfile(WSDLComponent component) {\n return getDisplayName().equals(ProfilesModelHelper.getWSITSecurityProfile(component));\n }\n\n @Override()\n public void displayConfig(WSDLComponent component, UndoManager undoManager) {\n UndoCounter undoCounter = new UndoCounter();\n WSDLModel model = component.getModel();\n model.addUndoableEditListener(undoCounter);\n JPanel profConfigPanel = new MessageAuthentication(component, this);\n DialogDescriptor dlgDesc = new DialogDescriptor(profConfigPanel, getDisplayName());\n Dialog dlg = DialogDisplayer.getDefault().createDialog(dlgDesc);\n dlg.setVisible(true);\n if (dlgDesc.getValue() == DialogDescriptor.CANCEL_OPTION) {\n for (int i = 0; i < undoCounter.getCounter(); i++) {\n if (undoManager.canUndo()) {\n undoManager.undo();\n }\n }\n }\n model.removeUndoableEditListener(undoCounter);\n }\n\n public void setServiceDefaults(WSDLComponent component, Project p) {\n ProprietarySecurityPolicyModelHelper.clearValidators(component);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, false, false);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, true, false);\n }\n\n public void setClientDefaults(WSDLComponent component, WSDLComponent serviceBinding, Project p) {\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, false, true);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, true, true);\n ProprietarySecurityPolicyModelHelper.removeCallbackHandlerConfiguration((Binding) component);\n ProprietarySecurityPolicyModelHelper.setCallbackHandler((Binding) component, CallbackHandler.USERNAME_CBHANDLER, null, DEFAULT_USERNAME, true);\n ProprietarySecurityPolicyModelHelper.setCallbackHandler((Binding) component, CallbackHandler.PASSWORD_CBHANDLER, null, DEFAULT_PASSWORD, true);\n }\n\n public boolean isServiceDefaultSetupUsed(WSDLComponent component, Project p) {\n if (ProprietarySecurityPolicyModelHelper.isAnyValidatorSet(component))\n return false;\n String keyAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, false);\n String trustAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, true);\n String trustLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, true);\n String keyLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, false);\n String keyPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, false);\n String trustPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, true);\n if ((keyAlias == null) && (trustAlias == null) && (trustLoc == null) && (keyLoc == null) && (trustPasswd == null) && (keyPasswd == null)) {\n return true;\n }\n return false;\n }\n\n public boolean isClientDefaultSetupUsed(WSDLComponent component, Binding serviceBinding, Project p) {\n if (ProprietarySecurityPolicyModelHelper.isAnyValidatorSet(component))\n return false;\n String trustLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, true);\n String keyLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, false);\n String keyPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, false);\n String trustPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, true);\n String keyAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, false);\n String trustAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, true);\n if ((keyAlias == null) && (trustAlias == null) && (trustLoc == null) && (keyLoc == null) && (trustPasswd == null) && (keyPasswd == null)) {\n String user = ProprietarySecurityPolicyModelHelper.getDefaultUsername((Binding) component);\n String passwd = ProprietarySecurityPolicyModelHelper.getDefaultPassword((Binding) component);\n if (Util.isEqual(DEFAULT_PASSWORD, passwd) && Util.isEqual(DEFAULT_USERNAME, user)) {\n return true;\n }\n }\n retu", "post_mask_code": "\n }\n\n public boolean isSecureConversation(WSDLComponent component) {\n WSDLComponent endToken = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n return (endToken != null);\n }\n\n public void enableSecureConversation(WSDLComponent component, boolean enable) {\n ConfigVersion cfgVersion = PolicyModelHelper.getConfigVersion(component);\n SecurityTokensModelHelper stmh = SecurityTokensModelHelper.getInstance(cfgVersion);\n if (enable) {\n WSDLModel model = component.getModel();\n boolean isTransaction = model.isIntransaction();\n if (!isTransaction) {\n model.startTransaction();\n }\n try {\n SecurityPolicyModelHelper securityPolicyModelHelper = SecurityPolicyModelHelper.getInstance(cfgVersion);\n AlgoSuiteModelHelper asmh = AlgoSuiteModelHelper.getInstance(cfgVersion);\n RMModelHelper rmh = RMModelHelper.getInstance(cfgVersion);\n PolicyModelHelper ProprietarySecurityPolicyModelHelper = PolicyModelHelper.getInstance(cfgVersion);\n securityPolicyModelHelper.enableTrust(component, cfgVersion);\n SecurityTokensModelHelper.removeSupportingTokens(component);\n WSDLComponent suppToken = stmh.setSupportingTokens(component, ComboConstants.SECURECONVERSATION, SecurityTokensModelHelper.ENDORSING);\n Policy p = ProprietarySecurityPolicyModelHelper.createElement(suppToken, PolicyQName.POLICY.getQName(cfgVersion), Policy.class, false);\n BootstrapPolicy bp = ProprietarySecurityPolicyModelHelper.createElement(p, SecurityPolicyQName.BOOTSTRAPPOLICY.getQName(cfgVersion), BootstrapPolicy.class, false);\n p = ProprietarySecurityPolicyModelHelper.createElement(bp, PolicyQName.POLICY.getQName(cfgVersion), Policy.class, false);\n TransportBinding tb = ProprietarySecurityPolicyModelHelper.createElement(p, SecurityPolicyQName.TRANSPORTBINDING.getQName(cfgVersion), TransportBinding.class, false);\n boolean rm = rmh.isRMEnabled(component);\n securityPolicyModelHelper.setDefaultTargets(p, true, rm);\n stmh.setTokenType(tb, ComboConstants.TRANSPORT, ComboConstants.HTTPS);\n securityPolicyModelHelper.setLayout(tb, ComboConstants.STRICT);\n securityPolicyModelHelper.enableIncludeTimestamp(tb, true);\n asmh.setAlgorithmSuite(tb, ComboConstants.BASIC128);\n if (ConfigVersion.CONFIG_1_0.equals(cfgVersion)) {\n stmh.setSupportingTokens(p, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_SUPPORTING);\n } else {\n stmh.setSupportingTokens(p, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_ENCRYPTED);\n }\n WssElement wss = securityPolicyModelHelper.enableWss(bp, true);\n securityPolicyModelHelper.enableMustSupportRefIssuerSerial(wss, true);\n securityPolicyModelHelper.enableMustSupportRefThumbprint(wss, true);\n securityPolicyModelHelper.enableMustSupportRefEncryptedKey(wss, true);\n TrustElement trust = securityPolicyModelHelper.enableTrust(bp, cfgVersion);\n securityPolicyModelHelper.enableMustSupportIssuedTokens(trust, true);\n securityPolicyModelHelper.enableRequireClientEntropy(trust, true);\n securityPolicyModelHelper.enableRequireServerEntropy(trust, true);\n } finally {\n if (!isTransaction) {\n model.endTransaction();\n }\n }\n } else {\n SecurityTokensModelHelper.removeSupportingTokens(component);\n if (ConfigVersion.CONFIG_1_0.equals(cfgVersion)) {\n stmh.setSupportingTokens(component, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_SUPPORTING);\n } else {\n stmh.setSupportingTokens(component, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_ENCRYPTED);\n }\n }\n }\n\n @Override\n public void profileSelected(WSDLComponent component, boolean updateServiceUrl, ConfigVersion configVersion) {\n ProfilesModelHelper pmh = ProfilesModelHelper.getInstance(configVersion);\n RMModelHelper rmh = RMModelHelper.getInstance(configVersion);\n pmh.setSecurityProfile(component, getDisplayName(), updateServiceUrl);\n boolean isRM = rmh.isRMEnabled(component);\n if (isRM) {\n enableSecureConversation(component, true);\n }\n }\n\n public boolean isValidatorSupported(ConfigVersion cfgVersion, String validatorType) {\n return true;\n }\n\n public boolean isTrustStoreRequired(WSDLComponent component, boolean client) {\n WSDLComponent secBinding = null;\n WSDLComponent endToken = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n WSDLComponent secConvT = SecurityTokensModelHelper.getTokenElement(endToken, SecureConversationToken.class);\n boolean secConv = (secConvT instanceof SecureConversationToken);\n if (secConv) {\n WSDLComponent bootPolicy = SecurityTokensModelHelper.getTokenElement(secConvT, BootstrapPolicy.class);\n secBinding = SecurityPolicyModelHelper.getSecurityBindingTypeElement(bootPolicy);\n Policy p = (Policy) secBinding.getParent();\n p = PolicyModelHelper.getTopLevelElement(bootPolicy, Policy.class, false);\n WSDLComponent tokenKind = SecurityTokensModelHelper.getSupportingToken(p, SecurityTokensModelHelper.ENDORSING);\n if (tokenKind == null) {\n return false;\n }\n } else {\n secBinding = SecurityPolicyModelHelper.getSecurityBindingTypeElement(component);\n WSDLComponent tokenKind = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n if (tokenKind == null) {\n return false;\n }\n }\n return true;\n }\n}\n"} {"task_id": "Java_2876", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/apache/netbeans/contrib/websvc.wsitconf/src/org/netbeans/modules/websvc/wsitconf/ui/service/profiles/MessageAuthenticationProfile.java", "mask_start_position": 3276, "mask_end_position": 3435, "canonical_solution": "public boolean isCurrentProfile(WSDLComponent component) {\n return getDisplayName().equals(ProfilesModelHelper.getWSITSecurityProfile(component));\n }", "pre_mask_code": "package org.netbeans.modules.websvc.wsitconf.ui.service.profiles;\n\nimport java.awt.Dialog;\nimport javax.swing.JPanel;\nimport javax.swing.undo.UndoManager;\nimport org.netbeans.api.project.Project;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.AdvancedSecurityFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ClientDefaultsFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.SecureConversationFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ServiceDefaultsFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.TrustStoreFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ValidatorsFeature;\nimport org.netbeans.modules.websvc.wsitconf.ui.ComboConstants;\nimport org.netbeans.modules.websvc.wsitconf.util.UndoCounter;\nimport org.netbeans.modules.websvc.wsitconf.util.Util;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.AlgoSuiteModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.PolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.ProfilesModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.ProprietarySecurityPolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.RMModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.SecurityPolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.SecurityTokensModelHelper;\nimport org.netbeans.modules.websvc.wsitmodelext.policy.Policy;\nimport org.netbeans.modules.websvc.wsitmodelext.policy.PolicyQName;\nimport org.netbeans.modules.websvc.wsitmodelext.security.BootstrapPolicy;\nimport org.netbeans.modules.websvc.wsitmodelext.security.SecurityPolicyQName;\nimport org.netbeans.modules.websvc.wsitmodelext.security.TransportBinding;\nimport org.netbeans.modules.websvc.wsitmodelext.security.TrustElement;\nimport org.netbeans.modules.websvc.wsitmodelext.security.WssElement;\nimport org.netbeans.modules.websvc.wsitmodelext.security.proprietary.CallbackHandler;\nimport org.netbeans.modules.websvc.wsitmodelext.security.tokens.SecureConversationToken;\nimport org.netbeans.modules.websvc.wsitmodelext.versioning.ConfigVersion;\nimport org.netbeans.modules.xml.wsdl.model.Binding;\nimport org.netbeans.modules.xml.wsdl.model.WSDLComponent;\nimport org.netbeans.modules.xml.wsdl.model.WSDLModel;\nimport org.openide.DialogDescriptor;\nimport org.openide.DialogDisplayer;\n\n/**\n * Transport Security Profile definition\n *\n * @author Martin Grebac\n */\n@org.openide.util.lookup.ServiceProvider(service = org.netbeans.modules.websvc.wsitconf.spi.SecurityProfile.class)\npublic class MessageAuthenticationProfile extends ProfileBase implements SecureConversationFeature, ClientDefaultsFeature, ServiceDefaultsFeature, ValidatorsFeature, AdvancedSecurityFeature, TrustStoreFeature {\n\n private static final String DEFAULT_USERNAME = \"wsit\";\n\n private static final String DEFAULT_PASSWORD = \"wsitPassword\";\n\n public int getId() {\n return 40;\n }\n\n public String getDisplayName() {\n return ComboConstants.PROF_MSGAUTHSSL;\n }\n\n public String getDescription() {\n return ComboConstants.PROF_MSGAUTHSSL_INFO;\n }\n\n /**\n * Should return true if the profile is set on component, false otherwise\n */\n ", "post_mask_code": "\n\n @Override()\n public void displayConfig(WSDLComponent component, UndoManager undoManager) {\n UndoCounter undoCounter = new UndoCounter();\n WSDLModel model = component.getModel();\n model.addUndoableEditListener(undoCounter);\n JPanel profConfigPanel = new MessageAuthentication(component, this);\n DialogDescriptor dlgDesc = new DialogDescriptor(profConfigPanel, getDisplayName());\n Dialog dlg = DialogDisplayer.getDefault().createDialog(dlgDesc);\n dlg.setVisible(true);\n if (dlgDesc.getValue() == DialogDescriptor.CANCEL_OPTION) {\n for (int i = 0; i < undoCounter.getCounter(); i++) {\n if (undoManager.canUndo()) {\n undoManager.undo();\n }\n }\n }\n model.removeUndoableEditListener(undoCounter);\n }\n\n public void setServiceDefaults(WSDLComponent component, Project p) {\n ProprietarySecurityPolicyModelHelper.clearValidators(component);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, false, false);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, true, false);\n }\n\n public void setClientDefaults(WSDLComponent component, WSDLComponent serviceBinding, Project p) {\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, false, true);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, true, true);\n ProprietarySecurityPolicyModelHelper.removeCallbackHandlerConfiguration((Binding) component);\n ProprietarySecurityPolicyModelHelper.setCallbackHandler((Binding) component, CallbackHandler.USERNAME_CBHANDLER, null, DEFAULT_USERNAME, true);\n ProprietarySecurityPolicyModelHelper.setCallbackHandler((Binding) component, CallbackHandler.PASSWORD_CBHANDLER, null, DEFAULT_PASSWORD, true);\n }\n\n public boolean isServiceDefaultSetupUsed(WSDLComponent component, Project p) {\n if (ProprietarySecurityPolicyModelHelper.isAnyValidatorSet(component))\n return false;\n String keyAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, false);\n String trustAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, true);\n String trustLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, true);\n String keyLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, false);\n String keyPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, false);\n String trustPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, true);\n if ((keyAlias == null) && (trustAlias == null) && (trustLoc == null) && (keyLoc == null) && (trustPasswd == null) && (keyPasswd == null)) {\n return true;\n }\n return false;\n }\n\n public boolean isClientDefaultSetupUsed(WSDLComponent component, Binding serviceBinding, Project p) {\n if (ProprietarySecurityPolicyModelHelper.isAnyValidatorSet(component))\n return false;\n String trustLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, true);\n String keyLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, false);\n String keyPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, false);\n String trustPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, true);\n String keyAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, false);\n String trustAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, true);\n if ((keyAlias == null) && (trustAlias == null) && (trustLoc == null) && (keyLoc == null) && (trustPasswd == null) && (keyPasswd == null)) {\n String user = ProprietarySecurityPolicyModelHelper.getDefaultUsername((Binding) component);\n String passwd = ProprietarySecurityPolicyModelHelper.getDefaultPassword((Binding) component);\n if (Util.isEqual(DEFAULT_PASSWORD, passwd) && Util.isEqual(DEFAULT_USERNAME, user)) {\n return true;\n }\n }\n return false;\n }\n\n public boolean isSecureConversation(WSDLComponent component) {\n WSDLComponent endToken = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n return (endToken != null);\n }\n\n public void enableSecureConversation(WSDLComponent component, boolean enable) {\n ConfigVersion cfgVersion = PolicyModelHelper.getConfigVersion(component);\n SecurityTokensModelHelper stmh = SecurityTokensModelHelper.getInstance(cfgVersion);\n if (enable) {\n WSDLModel model = component.getModel();\n boolean isTransaction = model.isIntransaction();\n if (!isTransaction) {\n model.startTransaction();\n }\n try {\n SecurityPolicyModelHelper securityPolicyModelHelper = SecurityPolicyModelHelper.getInstance(cfgVersion);\n AlgoSuiteModelHelper asmh = AlgoSuiteModelHelper.getInstance(cfgVersion);\n RMModelHelper rmh = RMModelHelper.getInstance(cfgVersion);\n PolicyModelHelper ProprietarySecurityPolicyModelHelper = PolicyModelHelper.getInstance(cfgVersion);\n securityPolicyModelHelper.enableTrust(component, cfgVersion);\n SecurityTokensModelHelper.removeSupportingTokens(component);\n WSDLComponent suppToken = stmh.setSupportingTokens(component, ComboConstants.SECURECONVERSATION, SecurityTokensModelHelper.ENDORSING);\n Policy p = ProprietarySecurityPolicyModelHelper.createElement(suppToken, PolicyQName.POLICY.getQName(cfgVersion), Policy.class, false);\n BootstrapPolicy bp = ProprietarySecurityPolicyModelHelper.createElement(p, SecurityPolicyQName.BOOTSTRAPPOLICY.getQName(cfgVersion), BootstrapPolicy.class, false);\n p = ProprietarySecurityPolicyModelHelper.createElement(bp, PolicyQName.POLICY.getQName(cfgVersion), Policy.class, false);\n TransportBinding tb = ProprietarySecurityPolicyModelHelper.createElement(p, SecurityPolicyQName.TRANSPORTBINDING.getQName(cfgVersion), TransportBinding.class, false);\n boolean rm = rmh.isRMEnabled(component);\n securityPolicyModelHelper.setDefaultTargets(p, true, rm);\n stmh.setTokenType(tb, ComboConstants.TRANSPORT, ComboConstants.HTTPS);\n securityPolicyModelHelper.setLayout(tb, ComboConstants.STRICT);\n securityPolicyModelHelper.enableIncludeTimestamp(tb, true);\n asmh.setAlgorithmSuite(tb, ComboConstants.BASIC128);\n if (ConfigVersion.CONFIG_1_0.equals(cfgVersion)) {\n stmh.setSupportingTokens(p, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_SUPPORTING);\n } else {\n stmh.setSupportingTokens(p, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_ENCRYPTED);\n }\n WssElement wss = securityPolicyModelHelper.enableWss(bp, true);\n securityPolicyModelHelper.enableMustSupportRefIssuerSerial(wss, true);\n securityPolicyModelHelper.enableMustSupportRefThumbprint(wss, true);\n securityPolicyModelHelper.enableMustSupportRefEncryptedKey(wss, true);\n TrustElement trust = securityPolicyModelHelper.enableTrust(bp, cfgVersion);\n securityPolicyModelHelper.enableMustSupportIssuedTokens(trust, true);\n securityPolicyModelHelper.enableRequireClientEntropy(trust, true);\n securityPolicyModelHelper.enableRequireServerEntropy(trust, true);\n } finally {\n if (!isTransaction) {\n model.endTransaction();\n }\n }\n } else {\n SecurityTokensModelHelper.removeSupportingTokens(component);\n if (ConfigVersion.CONFIG_1_0.equals(cfgVersion)) {\n stmh.setSupportingTokens(component, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_SUPPORTING);\n } else {\n stmh.setSupportingTokens(component, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_ENCRYPTED);\n }\n }\n }\n\n @Override\n public void profileSelected(WSDLComponent component, boolean updateServiceUrl, ConfigVersion configVersion) {\n ProfilesModelHelper pmh = ProfilesModelHelper.getInstance(configVersion);\n RMModelHelper rmh = RMModelHelper.getInstance(configVersion);\n pmh.setSecurityProfile(component, getDisplayName(), updateServiceUrl);\n boolean isRM = rmh.isRMEnabled(component);\n if (isRM) {\n enableSecureConversation(component, true);\n }\n }\n\n public boolean isValidatorSupported(ConfigVersion cfgVersion, String validatorType) {\n return true;\n }\n\n public boolean isTrustStoreRequired(WSDLComponent component, boolean client) {\n WSDLComponent secBinding = null;\n WSDLComponent endToken = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n WSDLComponent secConvT = SecurityTokensModelHelper.getTokenElement(endToken, SecureConversationToken.class);\n boolean secConv = (secConvT instanceof SecureConversationToken);\n if (secConv) {\n WSDLComponent bootPolicy = SecurityTokensModelHelper.getTokenElement(secConvT, BootstrapPolicy.class);\n secBinding = SecurityPolicyModelHelper.getSecurityBindingTypeElement(bootPolicy);\n Policy p = (Policy) secBinding.getParent();\n p = PolicyModelHelper.getTopLevelElement(bootPolicy, Policy.class, false);\n WSDLComponent tokenKind = SecurityTokensModelHelper.getSupportingToken(p, SecurityTokensModelHelper.ENDORSING);\n if (tokenKind == null) {\n return false;\n }\n } else {\n secBinding = SecurityPolicyModelHelper.getSecurityBindingTypeElement(component);\n WSDLComponent tokenKind = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n if (tokenKind == null) {\n return false;\n }\n }\n return true;\n }\n}\n"} {"task_id": "Java_2877", "language": "Java", "task_type": "for_statement", "source_file": "java/github/apache/netbeans/contrib/websvc.wsitconf/src/org/netbeans/modules/websvc/wsitconf/ui/service/profiles/MessageAuthenticationProfile.java", "mask_start_position": 4040, "mask_end_position": 4209, "canonical_solution": "for (int i = 0; i < undoCounter.getCounter(); i++) {\n if (undoManager.canUndo()) {\n undoManager.undo();\n }\n }", "pre_mask_code": "package org.netbeans.modules.websvc.wsitconf.ui.service.profiles;\n\nimport java.awt.Dialog;\nimport javax.swing.JPanel;\nimport javax.swing.undo.UndoManager;\nimport org.netbeans.api.project.Project;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.AdvancedSecurityFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ClientDefaultsFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.SecureConversationFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ServiceDefaultsFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.TrustStoreFeature;\nimport org.netbeans.modules.websvc.wsitconf.spi.features.ValidatorsFeature;\nimport org.netbeans.modules.websvc.wsitconf.ui.ComboConstants;\nimport org.netbeans.modules.websvc.wsitconf.util.UndoCounter;\nimport org.netbeans.modules.websvc.wsitconf.util.Util;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.AlgoSuiteModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.PolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.ProfilesModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.ProprietarySecurityPolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.RMModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.SecurityPolicyModelHelper;\nimport org.netbeans.modules.websvc.wsitconf.wsdlmodelext.SecurityTokensModelHelper;\nimport org.netbeans.modules.websvc.wsitmodelext.policy.Policy;\nimport org.netbeans.modules.websvc.wsitmodelext.policy.PolicyQName;\nimport org.netbeans.modules.websvc.wsitmodelext.security.BootstrapPolicy;\nimport org.netbeans.modules.websvc.wsitmodelext.security.SecurityPolicyQName;\nimport org.netbeans.modules.websvc.wsitmodelext.security.TransportBinding;\nimport org.netbeans.modules.websvc.wsitmodelext.security.TrustElement;\nimport org.netbeans.modules.websvc.wsitmodelext.security.WssElement;\nimport org.netbeans.modules.websvc.wsitmodelext.security.proprietary.CallbackHandler;\nimport org.netbeans.modules.websvc.wsitmodelext.security.tokens.SecureConversationToken;\nimport org.netbeans.modules.websvc.wsitmodelext.versioning.ConfigVersion;\nimport org.netbeans.modules.xml.wsdl.model.Binding;\nimport org.netbeans.modules.xml.wsdl.model.WSDLComponent;\nimport org.netbeans.modules.xml.wsdl.model.WSDLModel;\nimport org.openide.DialogDescriptor;\nimport org.openide.DialogDisplayer;\n\n/**\n * Transport Security Profile definition\n *\n * @author Martin Grebac\n */\n@org.openide.util.lookup.ServiceProvider(service = org.netbeans.modules.websvc.wsitconf.spi.SecurityProfile.class)\npublic class MessageAuthenticationProfile extends ProfileBase implements SecureConversationFeature, ClientDefaultsFeature, ServiceDefaultsFeature, ValidatorsFeature, AdvancedSecurityFeature, TrustStoreFeature {\n\n private static final String DEFAULT_USERNAME = \"wsit\";\n\n private static final String DEFAULT_PASSWORD = \"wsitPassword\";\n\n public int getId() {\n return 40;\n }\n\n public String getDisplayName() {\n return ComboConstants.PROF_MSGAUTHSSL;\n }\n\n public String getDescription() {\n return ComboConstants.PROF_MSGAUTHSSL_INFO;\n }\n\n /**\n * Should return true if the profile is set on component, false otherwise\n */\n public boolean isCurrentProfile(WSDLComponent component) {\n return getDisplayName().equals(ProfilesModelHelper.getWSITSecurityProfile(component));\n }\n\n @Override()\n public void displayConfig(WSDLComponent component, UndoManager undoManager) {\n UndoCounter undoCounter = new UndoCounter();\n WSDLModel model = component.getModel();\n model.addUndoableEditListener(undoCounter);\n JPanel profConfigPanel = new MessageAuthentication(component, this);\n DialogDescriptor dlgDesc = new DialogDescriptor(profConfigPanel, getDisplayName());\n Dialog dlg = DialogDisplayer.getDefault().createDialog(dlgDesc);\n dlg.setVisible(true);\n if (dlgDesc.getValue() == DialogDescriptor.CANCEL_OPTION) {\n ", "post_mask_code": "\n }\n model.removeUndoableEditListener(undoCounter);\n }\n\n public void setServiceDefaults(WSDLComponent component, Project p) {\n ProprietarySecurityPolicyModelHelper.clearValidators(component);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, false, false);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, true, false);\n }\n\n public void setClientDefaults(WSDLComponent component, WSDLComponent serviceBinding, Project p) {\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, false, true);\n ProprietarySecurityPolicyModelHelper.setStoreLocation(component, null, true, true);\n ProprietarySecurityPolicyModelHelper.removeCallbackHandlerConfiguration((Binding) component);\n ProprietarySecurityPolicyModelHelper.setCallbackHandler((Binding) component, CallbackHandler.USERNAME_CBHANDLER, null, DEFAULT_USERNAME, true);\n ProprietarySecurityPolicyModelHelper.setCallbackHandler((Binding) component, CallbackHandler.PASSWORD_CBHANDLER, null, DEFAULT_PASSWORD, true);\n }\n\n public boolean isServiceDefaultSetupUsed(WSDLComponent component, Project p) {\n if (ProprietarySecurityPolicyModelHelper.isAnyValidatorSet(component))\n return false;\n String keyAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, false);\n String trustAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, true);\n String trustLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, true);\n String keyLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, false);\n String keyPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, false);\n String trustPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, true);\n if ((keyAlias == null) && (trustAlias == null) && (trustLoc == null) && (keyLoc == null) && (trustPasswd == null) && (keyPasswd == null)) {\n return true;\n }\n return false;\n }\n\n public boolean isClientDefaultSetupUsed(WSDLComponent component, Binding serviceBinding, Project p) {\n if (ProprietarySecurityPolicyModelHelper.isAnyValidatorSet(component))\n return false;\n String trustLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, true);\n String keyLoc = ProprietarySecurityPolicyModelHelper.getStoreLocation(component, false);\n String keyPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, false);\n String trustPasswd = ProprietarySecurityPolicyModelHelper.getStorePassword(component, true);\n String keyAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, false);\n String trustAlias = ProprietarySecurityPolicyModelHelper.getStoreAlias(component, true);\n if ((keyAlias == null) && (trustAlias == null) && (trustLoc == null) && (keyLoc == null) && (trustPasswd == null) && (keyPasswd == null)) {\n String user = ProprietarySecurityPolicyModelHelper.getDefaultUsername((Binding) component);\n String passwd = ProprietarySecurityPolicyModelHelper.getDefaultPassword((Binding) component);\n if (Util.isEqual(DEFAULT_PASSWORD, passwd) && Util.isEqual(DEFAULT_USERNAME, user)) {\n return true;\n }\n }\n return false;\n }\n\n public boolean isSecureConversation(WSDLComponent component) {\n WSDLComponent endToken = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n return (endToken != null);\n }\n\n public void enableSecureConversation(WSDLComponent component, boolean enable) {\n ConfigVersion cfgVersion = PolicyModelHelper.getConfigVersion(component);\n SecurityTokensModelHelper stmh = SecurityTokensModelHelper.getInstance(cfgVersion);\n if (enable) {\n WSDLModel model = component.getModel();\n boolean isTransaction = model.isIntransaction();\n if (!isTransaction) {\n model.startTransaction();\n }\n try {\n SecurityPolicyModelHelper securityPolicyModelHelper = SecurityPolicyModelHelper.getInstance(cfgVersion);\n AlgoSuiteModelHelper asmh = AlgoSuiteModelHelper.getInstance(cfgVersion);\n RMModelHelper rmh = RMModelHelper.getInstance(cfgVersion);\n PolicyModelHelper ProprietarySecurityPolicyModelHelper = PolicyModelHelper.getInstance(cfgVersion);\n securityPolicyModelHelper.enableTrust(component, cfgVersion);\n SecurityTokensModelHelper.removeSupportingTokens(component);\n WSDLComponent suppToken = stmh.setSupportingTokens(component, ComboConstants.SECURECONVERSATION, SecurityTokensModelHelper.ENDORSING);\n Policy p = ProprietarySecurityPolicyModelHelper.createElement(suppToken, PolicyQName.POLICY.getQName(cfgVersion), Policy.class, false);\n BootstrapPolicy bp = ProprietarySecurityPolicyModelHelper.createElement(p, SecurityPolicyQName.BOOTSTRAPPOLICY.getQName(cfgVersion), BootstrapPolicy.class, false);\n p = ProprietarySecurityPolicyModelHelper.createElement(bp, PolicyQName.POLICY.getQName(cfgVersion), Policy.class, false);\n TransportBinding tb = ProprietarySecurityPolicyModelHelper.createElement(p, SecurityPolicyQName.TRANSPORTBINDING.getQName(cfgVersion), TransportBinding.class, false);\n boolean rm = rmh.isRMEnabled(component);\n securityPolicyModelHelper.setDefaultTargets(p, true, rm);\n stmh.setTokenType(tb, ComboConstants.TRANSPORT, ComboConstants.HTTPS);\n securityPolicyModelHelper.setLayout(tb, ComboConstants.STRICT);\n securityPolicyModelHelper.enableIncludeTimestamp(tb, true);\n asmh.setAlgorithmSuite(tb, ComboConstants.BASIC128);\n if (ConfigVersion.CONFIG_1_0.equals(cfgVersion)) {\n stmh.setSupportingTokens(p, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_SUPPORTING);\n } else {\n stmh.setSupportingTokens(p, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_ENCRYPTED);\n }\n WssElement wss = securityPolicyModelHelper.enableWss(bp, true);\n securityPolicyModelHelper.enableMustSupportRefIssuerSerial(wss, true);\n securityPolicyModelHelper.enableMustSupportRefThumbprint(wss, true);\n securityPolicyModelHelper.enableMustSupportRefEncryptedKey(wss, true);\n TrustElement trust = securityPolicyModelHelper.enableTrust(bp, cfgVersion);\n securityPolicyModelHelper.enableMustSupportIssuedTokens(trust, true);\n securityPolicyModelHelper.enableRequireClientEntropy(trust, true);\n securityPolicyModelHelper.enableRequireServerEntropy(trust, true);\n } finally {\n if (!isTransaction) {\n model.endTransaction();\n }\n }\n } else {\n SecurityTokensModelHelper.removeSupportingTokens(component);\n if (ConfigVersion.CONFIG_1_0.equals(cfgVersion)) {\n stmh.setSupportingTokens(component, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_SUPPORTING);\n } else {\n stmh.setSupportingTokens(component, ComboConstants.USERNAME, SecurityTokensModelHelper.SIGNED_ENCRYPTED);\n }\n }\n }\n\n @Override\n public void profileSelected(WSDLComponent component, boolean updateServiceUrl, ConfigVersion configVersion) {\n ProfilesModelHelper pmh = ProfilesModelHelper.getInstance(configVersion);\n RMModelHelper rmh = RMModelHelper.getInstance(configVersion);\n pmh.setSecurityProfile(component, getDisplayName(), updateServiceUrl);\n boolean isRM = rmh.isRMEnabled(component);\n if (isRM) {\n enableSecureConversation(component, true);\n }\n }\n\n public boolean isValidatorSupported(ConfigVersion cfgVersion, String validatorType) {\n return true;\n }\n\n public boolean isTrustStoreRequired(WSDLComponent component, boolean client) {\n WSDLComponent secBinding = null;\n WSDLComponent endToken = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n WSDLComponent secConvT = SecurityTokensModelHelper.getTokenElement(endToken, SecureConversationToken.class);\n boolean secConv = (secConvT instanceof SecureConversationToken);\n if (secConv) {\n WSDLComponent bootPolicy = SecurityTokensModelHelper.getTokenElement(secConvT, BootstrapPolicy.class);\n secBinding = SecurityPolicyModelHelper.getSecurityBindingTypeElement(bootPolicy);\n Policy p = (Policy) secBinding.getParent();\n p = PolicyModelHelper.getTopLevelElement(bootPolicy, Policy.class, false);\n WSDLComponent tokenKind = SecurityTokensModelHelper.getSupportingToken(p, SecurityTokensModelHelper.ENDORSING);\n if (tokenKind == null) {\n return false;\n }\n } else {\n secBinding = SecurityPolicyModelHelper.getSecurityBindingTypeElement(component);\n WSDLComponent tokenKind = SecurityTokensModelHelper.getSupportingToken(component, SecurityTokensModelHelper.ENDORSING);\n if (tokenKind == null) {\n return false;\n }\n }\n return true;\n }\n}\n"} {"task_id": "Java_2878", "language": "Java", "task_type": "method_signature", "source_file": "java/github/thombergs/code-examples/spring-boot/bean-lifecycle/src/main/java/io/reflectoring/beanlifecycle/jersey/JerseyConfig.java", "mask_start_position": 480, "mask_end_position": 531, "canonical_solution": "@PostConstruct\n public void registerResources() ", "pre_mask_code": "package io.reflectoring.beanlifecycle.jersey;\n\nimport org.glassfish.jersey.server.ResourceConfig;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.annotation.Configuration;\nimport javax.annotation.PostConstruct;\nimport javax.ws.rs.Path;\n\n@Configuration\npublic class JerseyConfig extends ResourceConfig {\n\n @Autowired\n private ApplicationContext applicationContext;\n\n ", "post_mask_code": "{\n applicationContext.getBeansWithAnnotation(Path.class).values().forEach(this::register);\n }\n}\n"} {"task_id": "Java_2879", "language": "Java", "task_type": "method_body", "source_file": "java/github/thombergs/code-examples/spring-boot/bean-lifecycle/src/main/java/io/reflectoring/beanlifecycle/jersey/JerseyConfig.java", "mask_start_position": 531, "mask_end_position": 634, "canonical_solution": "{\n applicationContext.getBeansWithAnnotation(Path.class).values().forEach(this::register);\n }", "pre_mask_code": "package io.reflectoring.beanlifecycle.jersey;\n\nimport org.glassfish.jersey.server.ResourceConfig;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.annotation.Configuration;\nimport javax.annotation.PostConstruct;\nimport javax.ws.rs.Path;\n\n@Configuration\npublic class JerseyConfig extends ResourceConfig {\n\n @Autowired\n private ApplicationContext applicationContext;\n\n @PostConstruct\n public void registerResources() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2880", "language": "Java", "task_type": "single_line", "source_file": "java/github/thombergs/code-examples/spring-boot/bean-lifecycle/src/main/java/io/reflectoring/beanlifecycle/jersey/JerseyConfig.java", "mask_start_position": 567, "mask_end_position": 628, "canonical_solution": "sWithAnnotation(Path.class).values().forEach(this::register);", "pre_mask_code": "package io.reflectoring.beanlifecycle.jersey;\n\nimport org.glassfish.jersey.server.ResourceConfig;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.annotation.Configuration;\nimport javax.annotation.PostConstruct;\nimport javax.ws.rs.Path;\n\n@Configuration\npublic class JerseyConfig extends ResourceConfig {\n\n @Autowired\n private ApplicationContext applicationContext;\n\n @PostConstruct\n public void registerResources() {\n applicationContext.getBean", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2881", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/servlet/spec/security/denyUncovered/ExcludeAuthConstraint.java", "mask_start_position": 1419, "mask_end_position": 1449, "canonical_solution": "public void debug(String str) ", "pre_mask_code": "package com.sun.ts.tests.servlet.spec.security.denyUncovered;\n\nimport java.io.IOException;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServlet;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\n\n/*\n * This servlet will be used to assist in testing the deny-uncovered-http-methods\n * security support (as listed in Servlet 3.1 spec, section 13.8.4). \n * \n * This is intended to be called from a Client, and will have specific settings\n * set on the web.xml that will allow (or disallow) certain http method calls\n * to be made based on the web.xml settings.\n *\n */\npublic class ExcludeAuthConstraint extends HttpServlet {\n\n public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n debug(\"in ExcludeAuthConstraint.doGet()\");\n }\n\n public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n debug(\"in ExcludeAuthConstraint.doPost()\");\n }\n\n public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n debug(\"in ExcludeAuthConstraint.doDelete()\");\n }\n\n public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n debug(\"in ExcludeAuthConstraint.doPut()\");\n }\n\n ", "post_mask_code": "{\n System.out.println(str);\n }\n}\n"} {"task_id": "Java_2882", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/servlet/spec/security/denyUncovered/ExcludeAuthConstraint.java", "mask_start_position": 1355, "mask_end_position": 1413, "canonical_solution": "{\n debug(\"in ExcludeAuthConstraint.doPut()\");\n }", "pre_mask_code": "package com.sun.ts.tests.servlet.spec.security.denyUncovered;\n\nimport java.io.IOException;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServlet;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\n\n/*\n * This servlet will be used to assist in testing the deny-uncovered-http-methods\n * security support (as listed in Servlet 3.1 spec, section 13.8.4). \n * \n * This is intended to be called from a Client, and will have specific settings\n * set on the web.xml that will allow (or disallow) certain http method calls\n * to be made based on the web.xml settings.\n *\n */\npublic class ExcludeAuthConstraint extends HttpServlet {\n\n public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n debug(\"in ExcludeAuthConstraint.doGet()\");\n }\n\n public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n debug(\"in ExcludeAuthConstraint.doPost()\");\n }\n\n public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n debug(\"in ExcludeAuthConstraint.doDelete()\");\n }\n\n public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ", "post_mask_code": "\n\n public void debug(String str) {\n System.out.println(str);\n }\n}\n"} {"task_id": "Java_2883", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/servlet/spec/security/denyUncovered/ExcludeAuthConstraint.java", "mask_start_position": 1224, "mask_end_position": 1230, "canonical_solution": "e()\");", "pre_mask_code": "package com.sun.ts.tests.servlet.spec.security.denyUncovered;\n\nimport java.io.IOException;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServlet;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\n\n/*\n * This servlet will be used to assist in testing the deny-uncovered-http-methods\n * security support (as listed in Servlet 3.1 spec, section 13.8.4). \n * \n * This is intended to be called from a Client, and will have specific settings\n * set on the web.xml that will allow (or disallow) certain http method calls\n * to be made based on the web.xml settings.\n *\n */\npublic class ExcludeAuthConstraint extends HttpServlet {\n\n public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n debug(\"in ExcludeAuthConstraint.doGet()\");\n }\n\n public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n debug(\"in ExcludeAuthConstraint.doPost()\");\n }\n\n public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n debug(\"in ExcludeAuthConstraint.doDelet", "post_mask_code": "\n }\n\n public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n debug(\"in ExcludeAuthConstraint.doPut()\");\n }\n\n public void debug(String str) {\n System.out.println(str);\n }\n}\n"} {"task_id": "Java_2884", "language": "Java", "task_type": "method_signature", "source_file": "java/github/square/assertj-android/assertj-android/src/main/java/org/assertj/android/api/view/ViewTreeObserverAssert.java", "mask_start_position": 453, "mask_end_position": 493, "canonical_solution": "public ViewTreeObserverAssert isAlive() ", "pre_mask_code": "package org.assertj.android.api.view;\n\nimport android.view.ViewTreeObserver;\nimport org.assertj.core.api.Assertions;\nimport org.assertj.core.api.AbstractAssert;\n\n/**\n * Assertions for {@link ViewTreeObserver} instances.\n */\npublic class ViewTreeObserverAssert extends AbstractAssert {\n\n public ViewTreeObserverAssert(ViewTreeObserver actual) {\n super(actual, ViewTreeObserverAssert.class);\n }\n\n ", "post_mask_code": "{\n isNotNull();\n Assertions.assertThat(actual.isAlive()).overridingErrorMessage(\"Expected to be alive but was not alive.\").isTrue();\n return this;\n }\n\n public ViewTreeObserverAssert isNotAlive() {\n isNotNull();\n Assertions.assertThat(actual.isAlive()).overridingErrorMessage(\"Expected to not be alive but was alive.\").isFalse();\n return this;\n }\n}\n"} {"task_id": "Java_2885", "language": "Java", "task_type": "method_body", "source_file": "java/github/square/assertj-android/assertj-android/src/main/java/org/assertj/android/api/view/ViewTreeObserverAssert.java", "mask_start_position": 493, "mask_end_position": 666, "canonical_solution": "{\n isNotNull();\n Assertions.assertThat(actual.isAlive()).overridingErrorMessage(\"Expected to be alive but was not alive.\").isTrue();\n return this;\n }", "pre_mask_code": "package org.assertj.android.api.view;\n\nimport android.view.ViewTreeObserver;\nimport org.assertj.core.api.Assertions;\nimport org.assertj.core.api.AbstractAssert;\n\n/**\n * Assertions for {@link ViewTreeObserver} instances.\n */\npublic class ViewTreeObserverAssert extends AbstractAssert {\n\n public ViewTreeObserverAssert(ViewTreeObserver actual) {\n super(actual, ViewTreeObserverAssert.class);\n }\n\n public ViewTreeObserverAssert isAlive() ", "post_mask_code": "\n\n public ViewTreeObserverAssert isNotAlive() {\n isNotNull();\n Assertions.assertThat(actual.isAlive()).overridingErrorMessage(\"Expected to not be alive but was alive.\").isFalse();\n return this;\n }\n}\n"} {"task_id": "Java_2886", "language": "Java", "task_type": "single_line", "source_file": "java/github/square/assertj-android/assertj-android/src/main/java/org/assertj/android/api/view/ViewTreeObserverAssert.java", "mask_start_position": 817, "mask_end_position": 862, "canonical_solution": "d to not be alive but was alive.\").isFalse();", "pre_mask_code": "package org.assertj.android.api.view;\n\nimport android.view.ViewTreeObserver;\nimport org.assertj.core.api.Assertions;\nimport org.assertj.core.api.AbstractAssert;\n\n/**\n * Assertions for {@link ViewTreeObserver} instances.\n */\npublic class ViewTreeObserverAssert extends AbstractAssert {\n\n public ViewTreeObserverAssert(ViewTreeObserver actual) {\n super(actual, ViewTreeObserverAssert.class);\n }\n\n public ViewTreeObserverAssert isAlive() {\n isNotNull();\n Assertions.assertThat(actual.isAlive()).overridingErrorMessage(\"Expected to be alive but was not alive.\").isTrue();\n return this;\n }\n\n public ViewTreeObserverAssert isNotAlive() {\n isNotNull();\n Assertions.assertThat(actual.isAlive()).overridingErrorMessage(\"Expecte", "post_mask_code": "\n return this;\n }\n}\n"} {"task_id": "Java_2887", "language": "Java", "task_type": "method_signature", "source_file": "java/github/TuSDK/TuSDK-for-Android-demo/TuSDKDemo/src/org/lasque/tusdkdemo/views/props/model/PropsItemMonster.java", "mask_start_position": 625, "mask_end_position": 654, "canonical_solution": "public String getThumbName() ", "pre_mask_code": "package org.lasque.tusdkdemo.views.props.model;\n\n/**\n * ***************************************************************\n * droid-sdk-video\n * org.lasque.tusdkdemo.views.props.model\n *\n * @author sprint\n * @Date 2018/12/28 5:58 PM\n * ****************************************************************\n */\n// 哈哈镜道具\npublic class PropsItemMonster extends PropsItem {\n\n /**\n * 缩略图名称\n */\n private String mThumbName;\n\n public PropsItemMonster() {\n }\n\n /**\n * 设置缩略图名称\n *\n * @param thumbName\n */\n public void setThumbName(String thumbName) {\n this.mThumbName = thumbName;\n }\n\n ", "post_mask_code": "{\n return mThumbName;\n }\n /**\n * 获取道具对应的 SDK 特效\n *\n * @return TuSdkMediaEffectData\n */\n}\n"} {"task_id": "Java_2888", "language": "Java", "task_type": "method_body", "source_file": "java/github/TuSDK/TuSDK-for-Android-demo/TuSDKDemo/src/org/lasque/tusdkdemo/views/props/model/PropsItemMonster.java", "mask_start_position": 575, "mask_end_position": 619, "canonical_solution": "{\n this.mThumbName = thumbName;\n }", "pre_mask_code": "package org.lasque.tusdkdemo.views.props.model;\n\n/**\n * ***************************************************************\n * droid-sdk-video\n * org.lasque.tusdkdemo.views.props.model\n *\n * @author sprint\n * @Date 2018/12/28 5:58 PM\n * ****************************************************************\n */\n// 哈哈镜道具\npublic class PropsItemMonster extends PropsItem {\n\n /**\n * 缩略图名称\n */\n private String mThumbName;\n\n public PropsItemMonster() {\n }\n\n /**\n * 设置缩略图名称\n *\n * @param thumbName\n */\n public void setThumbName(String thumbName) ", "post_mask_code": "\n\n public String getThumbName() {\n return mThumbName;\n }\n /**\n * 获取道具对应的 SDK 特效\n *\n * @return TuSdkMediaEffectData\n */\n}\n"} {"task_id": "Java_2889", "language": "Java", "task_type": "single_line", "source_file": "java/github/TuSDK/TuSDK-for-Android-demo/TuSDKDemo/src/org/lasque/tusdkdemo/views/props/model/PropsItemMonster.java", "mask_start_position": 593, "mask_end_position": 613, "canonical_solution": "umbName = thumbName;", "pre_mask_code": "package org.lasque.tusdkdemo.views.props.model;\n\n/**\n * ***************************************************************\n * droid-sdk-video\n * org.lasque.tusdkdemo.views.props.model\n *\n * @author sprint\n * @Date 2018/12/28 5:58 PM\n * ****************************************************************\n */\n// 哈哈镜道具\npublic class PropsItemMonster extends PropsItem {\n\n /**\n * 缩略图名称\n */\n private String mThumbName;\n\n public PropsItemMonster() {\n }\n\n /**\n * 设置缩略图名称\n *\n * @param thumbName\n */\n public void setThumbName(String thumbName) {\n this.mTh", "post_mask_code": "\n }\n\n public String getThumbName() {\n return mThumbName;\n }\n /**\n * 获取道具对应的 SDK 特效\n *\n * @return TuSdkMediaEffectData\n */\n}\n"} {"task_id": "Java_2890", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/TuSDK/TuSDK-for-Android-demo/TuSDKDemo/src/org/lasque/tusdkdemo/views/props/model/PropsItemMonster.java", "mask_start_position": 532, "mask_end_position": 619, "canonical_solution": "public void setThumbName(String thumbName) {\n this.mThumbName = thumbName;\n }", "pre_mask_code": "package org.lasque.tusdkdemo.views.props.model;\n\n/**\n * ***************************************************************\n * droid-sdk-video\n * org.lasque.tusdkdemo.views.props.model\n *\n * @author sprint\n * @Date 2018/12/28 5:58 PM\n * ****************************************************************\n */\n// 哈哈镜道具\npublic class PropsItemMonster extends PropsItem {\n\n /**\n * 缩略图名称\n */\n private String mThumbName;\n\n public PropsItemMonster() {\n }\n\n /**\n * 设置缩略图名称\n *\n * @param thumbName\n */\n ", "post_mask_code": "\n\n public String getThumbName() {\n return mThumbName;\n }\n /**\n * 获取道具对应的 SDK 特效\n *\n * @return TuSdkMediaEffectData\n */\n}\n"} {"task_id": "Java_2891", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jeffrey-xiao/competitive-programming/src/contest/coci/COCI_2008_CUSKIJA.java", "mask_start_position": 2476, "mask_end_position": 2516, "canonical_solution": "static String next() throws IOException ", "pre_mask_code": "package contest.coci;\n\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.StringTokenizer;\n\npublic class COCI_2008_CUSKIJA {\n\n static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n static PrintWriter ps = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));\n\n static StringTokenizer st;\n\n public static void main(String[] args) throws IOException {\n int n = readInt();\n ArrayList zero = new ArrayList();\n ArrayList one = new ArrayList();\n ArrayList two = new ArrayList();\n int[] count = new int[3];\n for (int i = 0; i < n; i++) {\n int a = readInt();\n count[a % 3]++;\n if (a % 3 == 0)\n zero.add(a);\n else if (a % 3 == 1)\n one.add(a);\n else\n two.add(a);\n }\n if (count[0] >= 2 + count[1] + count[2] || (count[1] >= 1 && count[2] >= 1 && count[0] == 0)) {\n System.out.println(\"impossible\");\n } else {\n if (count[0] == 0) {\n if (count[1] == 0) {\n for (Integer i : two) System.out.print(i + \" \");\n } else if (count[2] == 0) {\n for (Integer i : one) System.out.print(i + \" \");\n }\n } else {\n one.add(zero.get(0));\n zero.remove(0);\n one.addAll(two);\n int i = 0;\n int j = 0;\n boolean prev = false, next = false, isZero = true;\n ;\n while (i < zero.size() || j < one.size()) {\n if (isZero) {\n next = j < one.size() && one.get(j) % 3 == 0;\n if (!prev && !next && i < zero.size())\n System.out.print(zero.get(i++) + \" \");\n isZero = !isZero;\n } else {\n if (j < one.size()) {\n prev = one.get(j) % 3 == 0;\n System.out.print(one.get(j++) + \" \");\n }\n isZero = !isZero;\n }\n }\n }\n }\n }\n\n ", "post_mask_code": "{\n while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine().trim());\n return st.nextToken();\n }\n\n static long readLong() throws IOException {\n return Long.parseLong(next());\n }\n\n static int readInt() throws IOException {\n return Integer.parseInt(next());\n }\n\n static double readDouble() throws IOException {\n return Double.parseDouble(next());\n }\n\n static char readCharacter() throws IOException {\n return next().charAt(0);\n }\n\n static String readLine() throws IOException {\n return br.readLine().trim();\n }\n}\n"} {"task_id": "Java_2892", "language": "Java", "task_type": "method_body", "source_file": "java/github/jeffrey-xiao/competitive-programming/src/contest/coci/COCI_2008_CUSKIJA.java", "mask_start_position": 2892, "mask_end_position": 2942, "canonical_solution": "{\n return Double.parseDouble(next());\n }", "pre_mask_code": "package contest.coci;\n\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.StringTokenizer;\n\npublic class COCI_2008_CUSKIJA {\n\n static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n static PrintWriter ps = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));\n\n static StringTokenizer st;\n\n public static void main(String[] args) throws IOException {\n int n = readInt();\n ArrayList zero = new ArrayList();\n ArrayList one = new ArrayList();\n ArrayList two = new ArrayList();\n int[] count = new int[3];\n for (int i = 0; i < n; i++) {\n int a = readInt();\n count[a % 3]++;\n if (a % 3 == 0)\n zero.add(a);\n else if (a % 3 == 1)\n one.add(a);\n else\n two.add(a);\n }\n if (count[0] >= 2 + count[1] + count[2] || (count[1] >= 1 && count[2] >= 1 && count[0] == 0)) {\n System.out.println(\"impossible\");\n } else {\n if (count[0] == 0) {\n if (count[1] == 0) {\n for (Integer i : two) System.out.print(i + \" \");\n } else if (count[2] == 0) {\n for (Integer i : one) System.out.print(i + \" \");\n }\n } else {\n one.add(zero.get(0));\n zero.remove(0);\n one.addAll(two);\n int i = 0;\n int j = 0;\n boolean prev = false, next = false, isZero = true;\n ;\n while (i < zero.size() || j < one.size()) {\n if (isZero) {\n next = j < one.size() && one.get(j) % 3 == 0;\n if (!prev && !next && i < zero.size())\n System.out.print(zero.get(i++) + \" \");\n isZero = !isZero;\n } else {\n if (j < one.size()) {\n prev = one.get(j) % 3 == 0;\n System.out.print(one.get(j++) + \" \");\n }\n isZero = !isZero;\n }\n }\n }\n }\n }\n\n static String next() throws IOException {\n while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine().trim());\n return st.nextToken();\n }\n\n static long readLong() throws IOException {\n return Long.parseLong(next());\n }\n\n static int readInt() throws IOException {\n return Integer.parseInt(next());\n }\n\n static double readDouble() throws IOException ", "post_mask_code": "\n\n static char readCharacter() throws IOException {\n return next().charAt(0);\n }\n\n static String readLine() throws IOException {\n return br.readLine().trim();\n }\n}\n"} {"task_id": "Java_2893", "language": "Java", "task_type": "single_line", "source_file": "java/github/jeffrey-xiao/competitive-programming/src/contest/coci/COCI_2008_CUSKIJA.java", "mask_start_position": 2632, "mask_end_position": 2646, "canonical_solution": "t.nextToken();", "pre_mask_code": "package contest.coci;\n\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.StringTokenizer;\n\npublic class COCI_2008_CUSKIJA {\n\n static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n static PrintWriter ps = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));\n\n static StringTokenizer st;\n\n public static void main(String[] args) throws IOException {\n int n = readInt();\n ArrayList zero = new ArrayList();\n ArrayList one = new ArrayList();\n ArrayList two = new ArrayList();\n int[] count = new int[3];\n for (int i = 0; i < n; i++) {\n int a = readInt();\n count[a % 3]++;\n if (a % 3 == 0)\n zero.add(a);\n else if (a % 3 == 1)\n one.add(a);\n else\n two.add(a);\n }\n if (count[0] >= 2 + count[1] + count[2] || (count[1] >= 1 && count[2] >= 1 && count[0] == 0)) {\n System.out.println(\"impossible\");\n } else {\n if (count[0] == 0) {\n if (count[1] == 0) {\n for (Integer i : two) System.out.print(i + \" \");\n } else if (count[2] == 0) {\n for (Integer i : one) System.out.print(i + \" \");\n }\n } else {\n one.add(zero.get(0));\n zero.remove(0);\n one.addAll(two);\n int i = 0;\n int j = 0;\n boolean prev = false, next = false, isZero = true;\n ;\n while (i < zero.size() || j < one.size()) {\n if (isZero) {\n next = j < one.size() && one.get(j) % 3 == 0;\n if (!prev && !next && i < zero.size())\n System.out.print(zero.get(i++) + \" \");\n isZero = !isZero;\n } else {\n if (j < one.size()) {\n prev = one.get(j) % 3 == 0;\n System.out.print(one.get(j++) + \" \");\n }\n isZero = !isZero;\n }\n }\n }\n }\n }\n\n static String next() throws IOException {\n while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine().trim());\n return s", "post_mask_code": "\n }\n\n static long readLong() throws IOException {\n return Long.parseLong(next());\n }\n\n static int readInt() throws IOException {\n return Integer.parseInt(next());\n }\n\n static double readDouble() throws IOException {\n return Double.parseDouble(next());\n }\n\n static char readCharacter() throws IOException {\n return next().charAt(0);\n }\n\n static String readLine() throws IOException {\n return br.readLine().trim();\n }\n}\n"} {"task_id": "Java_2894", "language": "Java", "task_type": "for_statement", "source_file": "java/github/jeffrey-xiao/competitive-programming/src/contest/coci/COCI_2008_CUSKIJA.java", "mask_start_position": 838, "mask_end_position": 1099, "canonical_solution": "for (int i = 0; i < n; i++) {\n int a = readInt();\n count[a % 3]++;\n if (a % 3 == 0)\n zero.add(a);\n else if (a % 3 == 1)\n one.add(a);\n else\n two.add(a);\n }", "pre_mask_code": "package contest.coci;\n\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.StringTokenizer;\n\npublic class COCI_2008_CUSKIJA {\n\n static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n static PrintWriter ps = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));\n\n static StringTokenizer st;\n\n public static void main(String[] args) throws IOException {\n int n = readInt();\n ArrayList zero = new ArrayList();\n ArrayList one = new ArrayList();\n ArrayList two = new ArrayList();\n int[] count = new int[3];\n ", "post_mask_code": "\n if (count[0] >= 2 + count[1] + count[2] || (count[1] >= 1 && count[2] >= 1 && count[0] == 0)) {\n System.out.println(\"impossible\");\n } else {\n if (count[0] == 0) {\n if (count[1] == 0) {\n for (Integer i : two) System.out.print(i + \" \");\n } else if (count[2] == 0) {\n for (Integer i : one) System.out.print(i + \" \");\n }\n } else {\n one.add(zero.get(0));\n zero.remove(0);\n one.addAll(two);\n int i = 0;\n int j = 0;\n boolean prev = false, next = false, isZero = true;\n ;\n while (i < zero.size() || j < one.size()) {\n if (isZero) {\n next = j < one.size() && one.get(j) % 3 == 0;\n if (!prev && !next && i < zero.size())\n System.out.print(zero.get(i++) + \" \");\n isZero = !isZero;\n } else {\n if (j < one.size()) {\n prev = one.get(j) % 3 == 0;\n System.out.print(one.get(j++) + \" \");\n }\n isZero = !isZero;\n }\n }\n }\n }\n }\n\n static String next() throws IOException {\n while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine().trim());\n return st.nextToken();\n }\n\n static long readLong() throws IOException {\n return Long.parseLong(next());\n }\n\n static int readInt() throws IOException {\n return Integer.parseInt(next());\n }\n\n static double readDouble() throws IOException {\n return Double.parseDouble(next());\n }\n\n static char readCharacter() throws IOException {\n return next().charAt(0);\n }\n\n static String readLine() throws IOException {\n return br.readLine().trim();\n }\n}\n"} {"task_id": "Java_2895", "language": "Java", "task_type": "while_statement", "source_file": "java/github/jeffrey-xiao/competitive-programming/src/contest/coci/COCI_2008_CUSKIJA.java", "mask_start_position": 2526, "mask_end_position": 2615, "canonical_solution": "while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine().trim());", "pre_mask_code": "package contest.coci;\n\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.StringTokenizer;\n\npublic class COCI_2008_CUSKIJA {\n\n static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n static PrintWriter ps = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));\n\n static StringTokenizer st;\n\n public static void main(String[] args) throws IOException {\n int n = readInt();\n ArrayList zero = new ArrayList();\n ArrayList one = new ArrayList();\n ArrayList two = new ArrayList();\n int[] count = new int[3];\n for (int i = 0; i < n; i++) {\n int a = readInt();\n count[a % 3]++;\n if (a % 3 == 0)\n zero.add(a);\n else if (a % 3 == 1)\n one.add(a);\n else\n two.add(a);\n }\n if (count[0] >= 2 + count[1] + count[2] || (count[1] >= 1 && count[2] >= 1 && count[0] == 0)) {\n System.out.println(\"impossible\");\n } else {\n if (count[0] == 0) {\n if (count[1] == 0) {\n for (Integer i : two) System.out.print(i + \" \");\n } else if (count[2] == 0) {\n for (Integer i : one) System.out.print(i + \" \");\n }\n } else {\n one.add(zero.get(0));\n zero.remove(0);\n one.addAll(two);\n int i = 0;\n int j = 0;\n boolean prev = false, next = false, isZero = true;\n ;\n while (i < zero.size() || j < one.size()) {\n if (isZero) {\n next = j < one.size() && one.get(j) % 3 == 0;\n if (!prev && !next && i < zero.size())\n System.out.print(zero.get(i++) + \" \");\n isZero = !isZero;\n } else {\n if (j < one.size()) {\n prev = one.get(j) % 3 == 0;\n System.out.print(one.get(j++) + \" \");\n }\n isZero = !isZero;\n }\n }\n }\n }\n }\n\n static String next() throws IOException {\n ", "post_mask_code": "\n return st.nextToken();\n }\n\n static long readLong() throws IOException {\n return Long.parseLong(next());\n }\n\n static int readInt() throws IOException {\n return Integer.parseInt(next());\n }\n\n static double readDouble() throws IOException {\n return Double.parseDouble(next());\n }\n\n static char readCharacter() throws IOException {\n return next().charAt(0);\n }\n\n static String readLine() throws IOException {\n return br.readLine().trim();\n }\n}\n"} {"task_id": "Java_2896", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SonarSource/sonarqube/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/ProjectBranches.java", "mask_start_position": 1345, "mask_end_position": 1379, "canonical_solution": "public String defaultBranchName() ", "pre_mask_code": "/*\n * SonarQube\n * mailto:info AT sonarsource DOT com\n *\n */\npackage org.sonar.scanner.scan.branch;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport javax.annotation.CheckForNull;\nimport javax.annotation.concurrent.Immutable;\n\n/**\n * Container class for information about the branches of a project.\n */\n@Immutable\npublic class ProjectBranches {\n\n // matches server-side default when creating a project. See BranchDto#DEFAULT_MAIN_BRANCH_NAME\n private static final String DEFAULT_MAIN_BRANCH_NAME = \"master\";\n\n private final Map branches;\n\n private final String defaultBranchName;\n\n public ProjectBranches(List branchInfos) {\n this.branches = new HashMap<>();\n String mainBranchName = null;\n for (BranchInfo branch : branchInfos) {\n String branchName = branch.name();\n this.branches.put(branchName, branch);\n if (branch.isMain()) {\n mainBranchName = branchName;\n }\n }\n this.defaultBranchName = Objects.requireNonNullElse(mainBranchName, DEFAULT_MAIN_BRANCH_NAME);\n }\n\n @CheckForNull\n public BranchInfo get(String name) {\n return branches.get(name);\n }\n\n public boolean isEmpty() {\n return branches.isEmpty();\n }\n\n ", "post_mask_code": "{\n return defaultBranchName;\n }\n}\n"} {"task_id": "Java_2897", "language": "Java", "task_type": "method_body", "source_file": "java/github/SonarSource/sonarqube/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/ProjectBranches.java", "mask_start_position": 1379, "mask_end_position": 1420, "canonical_solution": "{\n return defaultBranchName;\n }", "pre_mask_code": "/*\n * SonarQube\n * mailto:info AT sonarsource DOT com\n *\n */\npackage org.sonar.scanner.scan.branch;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport javax.annotation.CheckForNull;\nimport javax.annotation.concurrent.Immutable;\n\n/**\n * Container class for information about the branches of a project.\n */\n@Immutable\npublic class ProjectBranches {\n\n // matches server-side default when creating a project. See BranchDto#DEFAULT_MAIN_BRANCH_NAME\n private static final String DEFAULT_MAIN_BRANCH_NAME = \"master\";\n\n private final Map branches;\n\n private final String defaultBranchName;\n\n public ProjectBranches(List branchInfos) {\n this.branches = new HashMap<>();\n String mainBranchName = null;\n for (BranchInfo branch : branchInfos) {\n String branchName = branch.name();\n this.branches.put(branchName, branch);\n if (branch.isMain()) {\n mainBranchName = branchName;\n }\n }\n this.defaultBranchName = Objects.requireNonNullElse(mainBranchName, DEFAULT_MAIN_BRANCH_NAME);\n }\n\n @CheckForNull\n public BranchInfo get(String name) {\n return branches.get(name);\n }\n\n public boolean isEmpty() {\n return branches.isEmpty();\n }\n\n public String defaultBranchName() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2898", "language": "Java", "task_type": "single_line", "source_file": "java/github/SonarSource/sonarqube/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/branch/ProjectBranches.java", "mask_start_position": 1402, "mask_end_position": 1414, "canonical_solution": "tBranchName;", "pre_mask_code": "/*\n * SonarQube\n * mailto:info AT sonarsource DOT com\n *\n */\npackage org.sonar.scanner.scan.branch;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport javax.annotation.CheckForNull;\nimport javax.annotation.concurrent.Immutable;\n\n/**\n * Container class for information about the branches of a project.\n */\n@Immutable\npublic class ProjectBranches {\n\n // matches server-side default when creating a project. See BranchDto#DEFAULT_MAIN_BRANCH_NAME\n private static final String DEFAULT_MAIN_BRANCH_NAME = \"master\";\n\n private final Map branches;\n\n private final String defaultBranchName;\n\n public ProjectBranches(List branchInfos) {\n this.branches = new HashMap<>();\n String mainBranchName = null;\n for (BranchInfo branch : branchInfos) {\n String branchName = branch.name();\n this.branches.put(branchName, branch);\n if (branch.isMain()) {\n mainBranchName = branchName;\n }\n }\n this.defaultBranchName = Objects.requireNonNullElse(mainBranchName, DEFAULT_MAIN_BRANCH_NAME);\n }\n\n @CheckForNull\n public BranchInfo get(String name) {\n return branches.get(name);\n }\n\n public boolean isEmpty() {\n return branches.isEmpty();\n }\n\n public String defaultBranchName() {\n return defaul", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2899", "language": "Java", "task_type": "method_signature", "source_file": "java/github/tomtom-international/maps-sdk-for-android-examples/sampleapp/src/main/java/com/tomtom/online/sdk/samples/cases/geofencing/report/GeofencingReportFragment.java", "mask_start_position": 728, "mask_end_position": 796, "canonical_solution": "@Override\n protected GeofencingReportPresenter createPresenter() ", "pre_mask_code": "/**\n * agreement between you and TomTom. If you are the licensee, you are only permitted to use\n * licensee then you are not authorised to use this software in any manner and should\n * immediately return it to TomTom N.V.\n */\npackage com.tomtom.online.sdk.samples.cases.geofencing.report;\n\nimport android.os.Bundle;\nimport androidx.annotation.Nullable;\nimport com.tomtom.online.sdk.samples.R;\nimport com.tomtom.online.sdk.samples.cases.ExampleFragment;\nimport com.tomtom.online.sdk.samples.utils.views.OptionsButtonsView;\nimport java.util.UUID;\n\npublic class GeofencingReportFragment extends ExampleFragment {\n\n private static final String PROJECT_UUID_BUNDLE_KEY = \"PROJECT_UUID_BUNDLE_KEY\";\n\n ", "post_mask_code": "{\n return new GeofencingReportPresenter();\n }\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n presenter.setCurrentProjectId((UUID) savedInstanceState.getSerializable(PROJECT_UUID_BUNDLE_KEY));\n }\n }\n\n @Override\n protected void onOptionsButtonsView(OptionsButtonsView view) {\n view.addOption(R.string.btn_one_fence);\n view.addOption(R.string.btn_two_fences);\n }\n\n @Override\n public void onChange(boolean[] oldValues, boolean[] newValues) {\n if (newValues[0]) {\n presenter.drawOneFence();\n } else if (newValues[1]) {\n presenter.drawTwoFences();\n }\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putSerializable(PROJECT_UUID_BUNDLE_KEY, presenter.getCurrentProjectId());\n }\n}\n"} {"task_id": "Java_2900", "language": "Java", "task_type": "method_body", "source_file": "java/github/tomtom-international/maps-sdk-for-android-examples/sampleapp/src/main/java/com/tomtom/online/sdk/samples/cases/geofencing/report/GeofencingReportFragment.java", "mask_start_position": 929, "mask_end_position": 1143, "canonical_solution": "{\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n presenter.setCurrentProjectId((UUID) savedInstanceState.getSerializable(PROJECT_UUID_BUNDLE_KEY));\n }\n }", "pre_mask_code": "/**\n * agreement between you and TomTom. If you are the licensee, you are only permitted to use\n * licensee then you are not authorised to use this software in any manner and should\n * immediately return it to TomTom N.V.\n */\npackage com.tomtom.online.sdk.samples.cases.geofencing.report;\n\nimport android.os.Bundle;\nimport androidx.annotation.Nullable;\nimport com.tomtom.online.sdk.samples.R;\nimport com.tomtom.online.sdk.samples.cases.ExampleFragment;\nimport com.tomtom.online.sdk.samples.utils.views.OptionsButtonsView;\nimport java.util.UUID;\n\npublic class GeofencingReportFragment extends ExampleFragment {\n\n private static final String PROJECT_UUID_BUNDLE_KEY = \"PROJECT_UUID_BUNDLE_KEY\";\n\n @Override\n protected GeofencingReportPresenter createPresenter() {\n return new GeofencingReportPresenter();\n }\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) ", "post_mask_code": "\n\n @Override\n protected void onOptionsButtonsView(OptionsButtonsView view) {\n view.addOption(R.string.btn_one_fence);\n view.addOption(R.string.btn_two_fences);\n }\n\n @Override\n public void onChange(boolean[] oldValues, boolean[] newValues) {\n if (newValues[0]) {\n presenter.drawOneFence();\n } else if (newValues[1]) {\n presenter.drawTwoFences();\n }\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putSerializable(PROJECT_UUID_BUNDLE_KEY, presenter.getCurrentProjectId());\n }\n}\n"} {"task_id": "Java_2901", "language": "Java", "task_type": "single_line", "source_file": "java/github/tomtom-international/maps-sdk-for-android-examples/sampleapp/src/main/java/com/tomtom/online/sdk/samples/cases/geofencing/report/GeofencingReportFragment.java", "mask_start_position": 1669, "mask_end_position": 1683, "canonical_solution": "ate(outState);", "pre_mask_code": "/**\n * agreement between you and TomTom. If you are the licensee, you are only permitted to use\n * licensee then you are not authorised to use this software in any manner and should\n * immediately return it to TomTom N.V.\n */\npackage com.tomtom.online.sdk.samples.cases.geofencing.report;\n\nimport android.os.Bundle;\nimport androidx.annotation.Nullable;\nimport com.tomtom.online.sdk.samples.R;\nimport com.tomtom.online.sdk.samples.cases.ExampleFragment;\nimport com.tomtom.online.sdk.samples.utils.views.OptionsButtonsView;\nimport java.util.UUID;\n\npublic class GeofencingReportFragment extends ExampleFragment {\n\n private static final String PROJECT_UUID_BUNDLE_KEY = \"PROJECT_UUID_BUNDLE_KEY\";\n\n @Override\n protected GeofencingReportPresenter createPresenter() {\n return new GeofencingReportPresenter();\n }\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n presenter.setCurrentProjectId((UUID) savedInstanceState.getSerializable(PROJECT_UUID_BUNDLE_KEY));\n }\n }\n\n @Override\n protected void onOptionsButtonsView(OptionsButtonsView view) {\n view.addOption(R.string.btn_one_fence);\n view.addOption(R.string.btn_two_fences);\n }\n\n @Override\n public void onChange(boolean[] oldValues, boolean[] newValues) {\n if (newValues[0]) {\n presenter.drawOneFence();\n } else if (newValues[1]) {\n presenter.drawTwoFences();\n }\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceSt", "post_mask_code": "\n outState.putSerializable(PROJECT_UUID_BUNDLE_KEY, presenter.getCurrentProjectId());\n }\n}\n"} {"task_id": "Java_2902", "language": "Java", "task_type": "method_signature", "source_file": "java/github/gridgain/gridgain-old/modules/core/src/main/java/org/gridgain/grid/kernal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java", "mask_start_position": 8724, "mask_end_position": 8763, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "/* _________ _____ __________________ _____\n * __ ____/___________(_)______ /__ ____/______ ____(_)_______\n * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \\\n * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /\n * \\____/ /_/ /_/ \\_,__/ \\____/ \\__,_/ /_/ /_/ /_/\n */\npackage org.gridgain.grid.kernal.processors.cache.distributed.dht.atomic;\n\nimport org.gridgain.grid.*;\nimport org.gridgain.grid.kernal.*;\nimport org.gridgain.grid.kernal.processors.cache.*;\nimport org.gridgain.grid.util.direct.*;\nimport org.gridgain.grid.util.typedef.internal.*;\nimport org.gridgain.grid.util.tostring.*;\nimport org.jetbrains.annotations.*;\nimport java.io.*;\nimport java.nio.*;\nimport java.util.*;\n\n/**\n * DHT atomic cache backup update response.\n */\npublic class GridDhtAtomicUpdateResponse extends GridCacheMessage implements GridCacheDeployable {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Message index.\n */\n public static final int CACHE_MSG_IDX = nextIndexId();\n\n /**\n * Future version.\n */\n private GridCacheVersion futVer;\n\n /**\n * Failed keys.\n */\n @GridToStringInclude\n @GridDirectTransient\n private Collection failedKeys;\n\n /**\n * Serialized failed keys.\n */\n private byte[] failedKeysBytes;\n\n /**\n * Update error.\n */\n @GridDirectTransient\n private GridException err;\n\n /**\n * Serialized update error.\n */\n private byte[] errBytes;\n\n /**\n * Evicted readers.\n */\n @GridToStringInclude\n @GridDirectTransient\n private Collection nearEvicted;\n\n /**\n * Evicted reader key bytes.\n */\n @GridDirectCollection(byte[].class)\n @GridDirectVersion(1)\n private Collection nearEvictedBytes;\n\n /**\n * Empty constructor required by {@link Externalizable}.\n */\n public GridDhtAtomicUpdateResponse() {\n }\n\n /**\n * @param futVer Future version.\n */\n public GridDhtAtomicUpdateResponse(GridCacheVersion futVer) {\n this.futVer = futVer;\n }\n\n @Override\n public int lookupIndex() {\n return CACHE_MSG_IDX;\n }\n\n public GridCacheVersion futureVersion() {\n return futVer;\n }\n\n /**\n * @return Gets update error.\n */\n public GridException error() {\n return err;\n }\n\n public Collection failedKeys() {\n return failedKeys;\n }\n\n /**\n * Adds key to collection of failed keys.\n *\n * @param key Key to add.\n * @param e Error cause.\n */\n public void addFailedKey(K key, Throwable e) {\n if (failedKeys == null)\n failedKeys = new ArrayList<>();\n failedKeys.add(key);\n if (err == null)\n err = new GridException(\"Failed to update keys on primary node.\");\n err.addSuppressed(e);\n }\n\n public Collection nearEvicted() {\n return nearEvicted;\n }\n\n /**\n * Adds near evicted key..\n *\n * @param key Evicted key.\n * @param bytes Bytes of evicted key.\n */\n public void addNearEvicted(K key, @Nullable byte[] bytes) {\n if (nearEvicted == null)\n nearEvicted = new ArrayList<>();\n nearEvicted.add(key);\n if (bytes != null) {\n if (nearEvictedBytes == null)\n nearEvictedBytes = new ArrayList<>();\n nearEvictedBytes.add(bytes);\n }\n }\n\n @Override\n public void prepareMarshal(GridCacheContext ctx) throws GridException {\n super.prepareMarshal(ctx);\n failedKeysBytes = ctx.marshaller().marshal(failedKeys);\n errBytes = ctx.marshaller().marshal(err);\n if (nearEvictedBytes == null)\n nearEvictedBytes = marshalCollection(nearEvicted, ctx);\n }\n\n @Override\n public void finishUnmarshal(GridCacheContext ctx, ClassLoader ldr) throws GridException {\n super.finishUnmarshal(ctx, ldr);\n failedKeys = ctx.marshaller().unmarshal(failedKeysBytes, ldr);\n err = ctx.marshaller().unmarshal(errBytes, ldr);\n if (nearEvicted == null && nearEvictedBytes != null)\n nearEvicted = unmarshalCollection(nearEvictedBytes, ctx, ldr);\n }\n\n @SuppressWarnings({ \"CloneDoesntCallSuperClone\", \"CloneCallsConstructors\" })\n @Override\n public GridTcpCommunicationMessageAdapter clone() {\n GridDhtAtomicUpdateResponse _clone = new GridDhtAtomicUpdateResponse();\n clone0(_clone);\n return _clone;\n }\n\n @Override\n protected void clone0(GridTcpCommunicationMessageAdapter _msg) {\n super.clone0(_msg);\n GridDhtAtomicUpdateResponse _clone = (GridDhtAtomicUpdateResponse) _msg;\n _clone.futVer = futVer;\n _clone.failedKeys = failedKeys;\n _clone.failedKeysBytes = failedKeysBytes;\n _clone.err = err;\n _clone.errBytes = errBytes;\n _clone.nearEvicted = nearEvicted;\n _clone.nearEvictedBytes = nearEvictedBytes;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public boolean writeTo(ByteBuffer buf) {\n commState.setBuffer(buf);\n if (!super.writeTo(buf))\n return false;\n if (!commState.typeWritten) {\n if (!commState.putByte(directType()))\n return false;\n commState.typeWritten = true;\n }\n switch(commState.idx) {\n case 2:\n if (!commState.putByteArray(errBytes))\n return false;\n commState.idx++;\n case 3:\n if (!commState.putByteArray(failedKeysBytes))\n return false;\n commState.idx++;\n case 4:\n if (!commState.putCacheVersion(futVer))\n return false;\n commState.idx++;\n case 5:\n if (nearEvictedBytes != null) {\n if (commState.it == null) {\n if (!commState.putInt(nearEvictedBytes.size()))\n return false;\n commState.it = nearEvictedBytes.iterator();\n }\n while (commState.it.hasNext() || commState.cur != NULL) {\n if (commState.cur == NULL)\n commState.cur = commState.it.next();\n if (!commState.putByteArray((byte[]) commState.cur))\n return false;\n commState.cur = NULL;\n }\n commState.it = null;\n } else {\n if (!commState.putInt(-1))\n return false;\n }\n commState.idx++;\n }\n return true;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public boolean readFrom(ByteBuffer buf) {\n commState.setBuffer(buf);\n if (!super.readFrom(buf))\n return false;\n switch(commState.idx) {\n case 2:\n byte[] errBytes0 = commState.getByteArray();\n if (errBytes0 == BYTE_ARR_NOT_READ)\n return false;\n errBytes = errBytes0;\n commState.idx++;\n case 3:\n byte[] failedKeysBytes0 = commState.getByteArray();\n if (failedKeysBytes0 == BYTE_ARR_NOT_READ)\n return false;\n failedKeysBytes = failedKeysBytes0;\n commState.idx++;\n case 4:\n GridCacheVersion futVer0 = commState.getCacheVersion();\n if (futVer0 == CACHE_VER_NOT_READ)\n return false;\n futVer = futVer0;\n commState.idx++;\n case 5:\n if (commState.readSize == -1) {\n if (buf.remaining() < 4)\n return false;\n commState.readSize = commState.getInt();\n }\n if (commState.readSize >= 0) {\n if (nearEvictedBytes == null)\n nearEvictedBytes = new ArrayList<>(commState.readSize);\n for (int i = commState.readItems; i < commState.readSize; i++) {\n byte[] _val = commState.getByteArray();\n if (_val == BYTE_ARR_NOT_READ)\n return false;\n nearEvictedBytes.add((byte[]) _val);\n commState.readItems++;\n }\n }\n commState.readSize = -1;\n commState.readItems = 0;\n commState.idx++;\n }\n return true;\n }\n\n @Override\n public byte directType() {\n return 38;\n }\n\n ", "post_mask_code": "{\n return S.toString(GridDhtAtomicUpdateResponse.class, this);\n }\n}\n"} {"task_id": "Java_2903", "language": "Java", "task_type": "method_body", "source_file": "java/github/gridgain/gridgain-old/modules/core/src/main/java/org/gridgain/grid/kernal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java", "mask_start_position": 4361, "mask_end_position": 4495, "canonical_solution": "{\n GridDhtAtomicUpdateResponse _clone = new GridDhtAtomicUpdateResponse();\n clone0(_clone);\n return _clone;\n }", "pre_mask_code": "/* _________ _____ __________________ _____\n * __ ____/___________(_)______ /__ ____/______ ____(_)_______\n * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \\\n * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /\n * \\____/ /_/ /_/ \\_,__/ \\____/ \\__,_/ /_/ /_/ /_/\n */\npackage org.gridgain.grid.kernal.processors.cache.distributed.dht.atomic;\n\nimport org.gridgain.grid.*;\nimport org.gridgain.grid.kernal.*;\nimport org.gridgain.grid.kernal.processors.cache.*;\nimport org.gridgain.grid.util.direct.*;\nimport org.gridgain.grid.util.typedef.internal.*;\nimport org.gridgain.grid.util.tostring.*;\nimport org.jetbrains.annotations.*;\nimport java.io.*;\nimport java.nio.*;\nimport java.util.*;\n\n/**\n * DHT atomic cache backup update response.\n */\npublic class GridDhtAtomicUpdateResponse extends GridCacheMessage implements GridCacheDeployable {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Message index.\n */\n public static final int CACHE_MSG_IDX = nextIndexId();\n\n /**\n * Future version.\n */\n private GridCacheVersion futVer;\n\n /**\n * Failed keys.\n */\n @GridToStringInclude\n @GridDirectTransient\n private Collection failedKeys;\n\n /**\n * Serialized failed keys.\n */\n private byte[] failedKeysBytes;\n\n /**\n * Update error.\n */\n @GridDirectTransient\n private GridException err;\n\n /**\n * Serialized update error.\n */\n private byte[] errBytes;\n\n /**\n * Evicted readers.\n */\n @GridToStringInclude\n @GridDirectTransient\n private Collection nearEvicted;\n\n /**\n * Evicted reader key bytes.\n */\n @GridDirectCollection(byte[].class)\n @GridDirectVersion(1)\n private Collection nearEvictedBytes;\n\n /**\n * Empty constructor required by {@link Externalizable}.\n */\n public GridDhtAtomicUpdateResponse() {\n }\n\n /**\n * @param futVer Future version.\n */\n public GridDhtAtomicUpdateResponse(GridCacheVersion futVer) {\n this.futVer = futVer;\n }\n\n @Override\n public int lookupIndex() {\n return CACHE_MSG_IDX;\n }\n\n public GridCacheVersion futureVersion() {\n return futVer;\n }\n\n /**\n * @return Gets update error.\n */\n public GridException error() {\n return err;\n }\n\n public Collection failedKeys() {\n return failedKeys;\n }\n\n /**\n * Adds key to collection of failed keys.\n *\n * @param key Key to add.\n * @param e Error cause.\n */\n public void addFailedKey(K key, Throwable e) {\n if (failedKeys == null)\n failedKeys = new ArrayList<>();\n failedKeys.add(key);\n if (err == null)\n err = new GridException(\"Failed to update keys on primary node.\");\n err.addSuppressed(e);\n }\n\n public Collection nearEvicted() {\n return nearEvicted;\n }\n\n /**\n * Adds near evicted key..\n *\n * @param key Evicted key.\n * @param bytes Bytes of evicted key.\n */\n public void addNearEvicted(K key, @Nullable byte[] bytes) {\n if (nearEvicted == null)\n nearEvicted = new ArrayList<>();\n nearEvicted.add(key);\n if (bytes != null) {\n if (nearEvictedBytes == null)\n nearEvictedBytes = new ArrayList<>();\n nearEvictedBytes.add(bytes);\n }\n }\n\n @Override\n public void prepareMarshal(GridCacheContext ctx) throws GridException {\n super.prepareMarshal(ctx);\n failedKeysBytes = ctx.marshaller().marshal(failedKeys);\n errBytes = ctx.marshaller().marshal(err);\n if (nearEvictedBytes == null)\n nearEvictedBytes = marshalCollection(nearEvicted, ctx);\n }\n\n @Override\n public void finishUnmarshal(GridCacheContext ctx, ClassLoader ldr) throws GridException {\n super.finishUnmarshal(ctx, ldr);\n failedKeys = ctx.marshaller().unmarshal(failedKeysBytes, ldr);\n err = ctx.marshaller().unmarshal(errBytes, ldr);\n if (nearEvicted == null && nearEvictedBytes != null)\n nearEvicted = unmarshalCollection(nearEvictedBytes, ctx, ldr);\n }\n\n @SuppressWarnings({ \"CloneDoesntCallSuperClone\", \"CloneCallsConstructors\" })\n @Override\n public GridTcpCommunicationMessageAdapter clone() ", "post_mask_code": "\n\n @Override\n protected void clone0(GridTcpCommunicationMessageAdapter _msg) {\n super.clone0(_msg);\n GridDhtAtomicUpdateResponse _clone = (GridDhtAtomicUpdateResponse) _msg;\n _clone.futVer = futVer;\n _clone.failedKeys = failedKeys;\n _clone.failedKeysBytes = failedKeysBytes;\n _clone.err = err;\n _clone.errBytes = errBytes;\n _clone.nearEvicted = nearEvicted;\n _clone.nearEvictedBytes = nearEvictedBytes;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public boolean writeTo(ByteBuffer buf) {\n commState.setBuffer(buf);\n if (!super.writeTo(buf))\n return false;\n if (!commState.typeWritten) {\n if (!commState.putByte(directType()))\n return false;\n commState.typeWritten = true;\n }\n switch(commState.idx) {\n case 2:\n if (!commState.putByteArray(errBytes))\n return false;\n commState.idx++;\n case 3:\n if (!commState.putByteArray(failedKeysBytes))\n return false;\n commState.idx++;\n case 4:\n if (!commState.putCacheVersion(futVer))\n return false;\n commState.idx++;\n case 5:\n if (nearEvictedBytes != null) {\n if (commState.it == null) {\n if (!commState.putInt(nearEvictedBytes.size()))\n return false;\n commState.it = nearEvictedBytes.iterator();\n }\n while (commState.it.hasNext() || commState.cur != NULL) {\n if (commState.cur == NULL)\n commState.cur = commState.it.next();\n if (!commState.putByteArray((byte[]) commState.cur))\n return false;\n commState.cur = NULL;\n }\n commState.it = null;\n } else {\n if (!commState.putInt(-1))\n return false;\n }\n commState.idx++;\n }\n return true;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public boolean readFrom(ByteBuffer buf) {\n commState.setBuffer(buf);\n if (!super.readFrom(buf))\n return false;\n switch(commState.idx) {\n case 2:\n byte[] errBytes0 = commState.getByteArray();\n if (errBytes0 == BYTE_ARR_NOT_READ)\n return false;\n errBytes = errBytes0;\n commState.idx++;\n case 3:\n byte[] failedKeysBytes0 = commState.getByteArray();\n if (failedKeysBytes0 == BYTE_ARR_NOT_READ)\n return false;\n failedKeysBytes = failedKeysBytes0;\n commState.idx++;\n case 4:\n GridCacheVersion futVer0 = commState.getCacheVersion();\n if (futVer0 == CACHE_VER_NOT_READ)\n return false;\n futVer = futVer0;\n commState.idx++;\n case 5:\n if (commState.readSize == -1) {\n if (buf.remaining() < 4)\n return false;\n commState.readSize = commState.getInt();\n }\n if (commState.readSize >= 0) {\n if (nearEvictedBytes == null)\n nearEvictedBytes = new ArrayList<>(commState.readSize);\n for (int i = commState.readItems; i < commState.readSize; i++) {\n byte[] _val = commState.getByteArray();\n if (_val == BYTE_ARR_NOT_READ)\n return false;\n nearEvictedBytes.add((byte[]) _val);\n commState.readItems++;\n }\n }\n commState.readSize = -1;\n commState.readItems = 0;\n commState.idx++;\n }\n return true;\n }\n\n @Override\n public byte directType() {\n return 38;\n }\n\n @Override\n public String toString() {\n return S.toString(GridDhtAtomicUpdateResponse.class, this);\n }\n}\n"} {"task_id": "Java_2904", "language": "Java", "task_type": "single_line", "source_file": "java/github/gridgain/gridgain-old/modules/core/src/main/java/org/gridgain/grid/kernal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java", "mask_start_position": 4824, "mask_end_position": 4836, "canonical_solution": "e.err = err;", "pre_mask_code": "/* _________ _____ __________________ _____\n * __ ____/___________(_)______ /__ ____/______ ____(_)_______\n * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \\\n * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /\n * \\____/ /_/ /_/ \\_,__/ \\____/ \\__,_/ /_/ /_/ /_/\n */\npackage org.gridgain.grid.kernal.processors.cache.distributed.dht.atomic;\n\nimport org.gridgain.grid.*;\nimport org.gridgain.grid.kernal.*;\nimport org.gridgain.grid.kernal.processors.cache.*;\nimport org.gridgain.grid.util.direct.*;\nimport org.gridgain.grid.util.typedef.internal.*;\nimport org.gridgain.grid.util.tostring.*;\nimport org.jetbrains.annotations.*;\nimport java.io.*;\nimport java.nio.*;\nimport java.util.*;\n\n/**\n * DHT atomic cache backup update response.\n */\npublic class GridDhtAtomicUpdateResponse extends GridCacheMessage implements GridCacheDeployable {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Message index.\n */\n public static final int CACHE_MSG_IDX = nextIndexId();\n\n /**\n * Future version.\n */\n private GridCacheVersion futVer;\n\n /**\n * Failed keys.\n */\n @GridToStringInclude\n @GridDirectTransient\n private Collection failedKeys;\n\n /**\n * Serialized failed keys.\n */\n private byte[] failedKeysBytes;\n\n /**\n * Update error.\n */\n @GridDirectTransient\n private GridException err;\n\n /**\n * Serialized update error.\n */\n private byte[] errBytes;\n\n /**\n * Evicted readers.\n */\n @GridToStringInclude\n @GridDirectTransient\n private Collection nearEvicted;\n\n /**\n * Evicted reader key bytes.\n */\n @GridDirectCollection(byte[].class)\n @GridDirectVersion(1)\n private Collection nearEvictedBytes;\n\n /**\n * Empty constructor required by {@link Externalizable}.\n */\n public GridDhtAtomicUpdateResponse() {\n }\n\n /**\n * @param futVer Future version.\n */\n public GridDhtAtomicUpdateResponse(GridCacheVersion futVer) {\n this.futVer = futVer;\n }\n\n @Override\n public int lookupIndex() {\n return CACHE_MSG_IDX;\n }\n\n public GridCacheVersion futureVersion() {\n return futVer;\n }\n\n /**\n * @return Gets update error.\n */\n public GridException error() {\n return err;\n }\n\n public Collection failedKeys() {\n return failedKeys;\n }\n\n /**\n * Adds key to collection of failed keys.\n *\n * @param key Key to add.\n * @param e Error cause.\n */\n public void addFailedKey(K key, Throwable e) {\n if (failedKeys == null)\n failedKeys = new ArrayList<>();\n failedKeys.add(key);\n if (err == null)\n err = new GridException(\"Failed to update keys on primary node.\");\n err.addSuppressed(e);\n }\n\n public Collection nearEvicted() {\n return nearEvicted;\n }\n\n /**\n * Adds near evicted key..\n *\n * @param key Evicted key.\n * @param bytes Bytes of evicted key.\n */\n public void addNearEvicted(K key, @Nullable byte[] bytes) {\n if (nearEvicted == null)\n nearEvicted = new ArrayList<>();\n nearEvicted.add(key);\n if (bytes != null) {\n if (nearEvictedBytes == null)\n nearEvictedBytes = new ArrayList<>();\n nearEvictedBytes.add(bytes);\n }\n }\n\n @Override\n public void prepareMarshal(GridCacheContext ctx) throws GridException {\n super.prepareMarshal(ctx);\n failedKeysBytes = ctx.marshaller().marshal(failedKeys);\n errBytes = ctx.marshaller().marshal(err);\n if (nearEvictedBytes == null)\n nearEvictedBytes = marshalCollection(nearEvicted, ctx);\n }\n\n @Override\n public void finishUnmarshal(GridCacheContext ctx, ClassLoader ldr) throws GridException {\n super.finishUnmarshal(ctx, ldr);\n failedKeys = ctx.marshaller().unmarshal(failedKeysBytes, ldr);\n err = ctx.marshaller().unmarshal(errBytes, ldr);\n if (nearEvicted == null && nearEvictedBytes != null)\n nearEvicted = unmarshalCollection(nearEvictedBytes, ctx, ldr);\n }\n\n @SuppressWarnings({ \"CloneDoesntCallSuperClone\", \"CloneCallsConstructors\" })\n @Override\n public GridTcpCommunicationMessageAdapter clone() {\n GridDhtAtomicUpdateResponse _clone = new GridDhtAtomicUpdateResponse();\n clone0(_clone);\n return _clone;\n }\n\n @Override\n protected void clone0(GridTcpCommunicationMessageAdapter _msg) {\n super.clone0(_msg);\n GridDhtAtomicUpdateResponse _clone = (GridDhtAtomicUpdateResponse) _msg;\n _clone.futVer = futVer;\n _clone.failedKeys = failedKeys;\n _clone.failedKeysBytes = failedKeysBytes;\n _clon", "post_mask_code": "\n _clone.errBytes = errBytes;\n _clone.nearEvicted = nearEvicted;\n _clone.nearEvictedBytes = nearEvictedBytes;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public boolean writeTo(ByteBuffer buf) {\n commState.setBuffer(buf);\n if (!super.writeTo(buf))\n return false;\n if (!commState.typeWritten) {\n if (!commState.putByte(directType()))\n return false;\n commState.typeWritten = true;\n }\n switch(commState.idx) {\n case 2:\n if (!commState.putByteArray(errBytes))\n return false;\n commState.idx++;\n case 3:\n if (!commState.putByteArray(failedKeysBytes))\n return false;\n commState.idx++;\n case 4:\n if (!commState.putCacheVersion(futVer))\n return false;\n commState.idx++;\n case 5:\n if (nearEvictedBytes != null) {\n if (commState.it == null) {\n if (!commState.putInt(nearEvictedBytes.size()))\n return false;\n commState.it = nearEvictedBytes.iterator();\n }\n while (commState.it.hasNext() || commState.cur != NULL) {\n if (commState.cur == NULL)\n commState.cur = commState.it.next();\n if (!commState.putByteArray((byte[]) commState.cur))\n return false;\n commState.cur = NULL;\n }\n commState.it = null;\n } else {\n if (!commState.putInt(-1))\n return false;\n }\n commState.idx++;\n }\n return true;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public boolean readFrom(ByteBuffer buf) {\n commState.setBuffer(buf);\n if (!super.readFrom(buf))\n return false;\n switch(commState.idx) {\n case 2:\n byte[] errBytes0 = commState.getByteArray();\n if (errBytes0 == BYTE_ARR_NOT_READ)\n return false;\n errBytes = errBytes0;\n commState.idx++;\n case 3:\n byte[] failedKeysBytes0 = commState.getByteArray();\n if (failedKeysBytes0 == BYTE_ARR_NOT_READ)\n return false;\n failedKeysBytes = failedKeysBytes0;\n commState.idx++;\n case 4:\n GridCacheVersion futVer0 = commState.getCacheVersion();\n if (futVer0 == CACHE_VER_NOT_READ)\n return false;\n futVer = futVer0;\n commState.idx++;\n case 5:\n if (commState.readSize == -1) {\n if (buf.remaining() < 4)\n return false;\n commState.readSize = commState.getInt();\n }\n if (commState.readSize >= 0) {\n if (nearEvictedBytes == null)\n nearEvictedBytes = new ArrayList<>(commState.readSize);\n for (int i = commState.readItems; i < commState.readSize; i++) {\n byte[] _val = commState.getByteArray();\n if (_val == BYTE_ARR_NOT_READ)\n return false;\n nearEvictedBytes.add((byte[]) _val);\n commState.readItems++;\n }\n }\n commState.readSize = -1;\n commState.readItems = 0;\n commState.idx++;\n }\n return true;\n }\n\n @Override\n public byte directType() {\n return 38;\n }\n\n @Override\n public String toString() {\n return S.toString(GridDhtAtomicUpdateResponse.class, this);\n }\n}\n"} {"task_id": "Java_2905", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/gridgain/gridgain-old/modules/core/src/main/java/org/gridgain/grid/kernal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java", "mask_start_position": 2313, "mask_end_position": 2369, "canonical_solution": "public GridException error() {\n return err;\n }", "pre_mask_code": "/* _________ _____ __________________ _____\n * __ ____/___________(_)______ /__ ____/______ ____(_)_______\n * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \\\n * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /\n * \\____/ /_/ /_/ \\_,__/ \\____/ \\__,_/ /_/ /_/ /_/\n */\npackage org.gridgain.grid.kernal.processors.cache.distributed.dht.atomic;\n\nimport org.gridgain.grid.*;\nimport org.gridgain.grid.kernal.*;\nimport org.gridgain.grid.kernal.processors.cache.*;\nimport org.gridgain.grid.util.direct.*;\nimport org.gridgain.grid.util.typedef.internal.*;\nimport org.gridgain.grid.util.tostring.*;\nimport org.jetbrains.annotations.*;\nimport java.io.*;\nimport java.nio.*;\nimport java.util.*;\n\n/**\n * DHT atomic cache backup update response.\n */\npublic class GridDhtAtomicUpdateResponse extends GridCacheMessage implements GridCacheDeployable {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Message index.\n */\n public static final int CACHE_MSG_IDX = nextIndexId();\n\n /**\n * Future version.\n */\n private GridCacheVersion futVer;\n\n /**\n * Failed keys.\n */\n @GridToStringInclude\n @GridDirectTransient\n private Collection failedKeys;\n\n /**\n * Serialized failed keys.\n */\n private byte[] failedKeysBytes;\n\n /**\n * Update error.\n */\n @GridDirectTransient\n private GridException err;\n\n /**\n * Serialized update error.\n */\n private byte[] errBytes;\n\n /**\n * Evicted readers.\n */\n @GridToStringInclude\n @GridDirectTransient\n private Collection nearEvicted;\n\n /**\n * Evicted reader key bytes.\n */\n @GridDirectCollection(byte[].class)\n @GridDirectVersion(1)\n private Collection nearEvictedBytes;\n\n /**\n * Empty constructor required by {@link Externalizable}.\n */\n public GridDhtAtomicUpdateResponse() {\n }\n\n /**\n * @param futVer Future version.\n */\n public GridDhtAtomicUpdateResponse(GridCacheVersion futVer) {\n this.futVer = futVer;\n }\n\n @Override\n public int lookupIndex() {\n return CACHE_MSG_IDX;\n }\n\n public GridCacheVersion futureVersion() {\n return futVer;\n }\n\n /**\n * @return Gets update error.\n */\n ", "post_mask_code": "\n\n public Collection failedKeys() {\n return failedKeys;\n }\n\n /**\n * Adds key to collection of failed keys.\n *\n * @param key Key to add.\n * @param e Error cause.\n */\n public void addFailedKey(K key, Throwable e) {\n if (failedKeys == null)\n failedKeys = new ArrayList<>();\n failedKeys.add(key);\n if (err == null)\n err = new GridException(\"Failed to update keys on primary node.\");\n err.addSuppressed(e);\n }\n\n public Collection nearEvicted() {\n return nearEvicted;\n }\n\n /**\n * Adds near evicted key..\n *\n * @param key Evicted key.\n * @param bytes Bytes of evicted key.\n */\n public void addNearEvicted(K key, @Nullable byte[] bytes) {\n if (nearEvicted == null)\n nearEvicted = new ArrayList<>();\n nearEvicted.add(key);\n if (bytes != null) {\n if (nearEvictedBytes == null)\n nearEvictedBytes = new ArrayList<>();\n nearEvictedBytes.add(bytes);\n }\n }\n\n @Override\n public void prepareMarshal(GridCacheContext ctx) throws GridException {\n super.prepareMarshal(ctx);\n failedKeysBytes = ctx.marshaller().marshal(failedKeys);\n errBytes = ctx.marshaller().marshal(err);\n if (nearEvictedBytes == null)\n nearEvictedBytes = marshalCollection(nearEvicted, ctx);\n }\n\n @Override\n public void finishUnmarshal(GridCacheContext ctx, ClassLoader ldr) throws GridException {\n super.finishUnmarshal(ctx, ldr);\n failedKeys = ctx.marshaller().unmarshal(failedKeysBytes, ldr);\n err = ctx.marshaller().unmarshal(errBytes, ldr);\n if (nearEvicted == null && nearEvictedBytes != null)\n nearEvicted = unmarshalCollection(nearEvictedBytes, ctx, ldr);\n }\n\n @SuppressWarnings({ \"CloneDoesntCallSuperClone\", \"CloneCallsConstructors\" })\n @Override\n public GridTcpCommunicationMessageAdapter clone() {\n GridDhtAtomicUpdateResponse _clone = new GridDhtAtomicUpdateResponse();\n clone0(_clone);\n return _clone;\n }\n\n @Override\n protected void clone0(GridTcpCommunicationMessageAdapter _msg) {\n super.clone0(_msg);\n GridDhtAtomicUpdateResponse _clone = (GridDhtAtomicUpdateResponse) _msg;\n _clone.futVer = futVer;\n _clone.failedKeys = failedKeys;\n _clone.failedKeysBytes = failedKeysBytes;\n _clone.err = err;\n _clone.errBytes = errBytes;\n _clone.nearEvicted = nearEvicted;\n _clone.nearEvictedBytes = nearEvictedBytes;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public boolean writeTo(ByteBuffer buf) {\n commState.setBuffer(buf);\n if (!super.writeTo(buf))\n return false;\n if (!commState.typeWritten) {\n if (!commState.putByte(directType()))\n return false;\n commState.typeWritten = true;\n }\n switch(commState.idx) {\n case 2:\n if (!commState.putByteArray(errBytes))\n return false;\n commState.idx++;\n case 3:\n if (!commState.putByteArray(failedKeysBytes))\n return false;\n commState.idx++;\n case 4:\n if (!commState.putCacheVersion(futVer))\n return false;\n commState.idx++;\n case 5:\n if (nearEvictedBytes != null) {\n if (commState.it == null) {\n if (!commState.putInt(nearEvictedBytes.size()))\n return false;\n commState.it = nearEvictedBytes.iterator();\n }\n while (commState.it.hasNext() || commState.cur != NULL) {\n if (commState.cur == NULL)\n commState.cur = commState.it.next();\n if (!commState.putByteArray((byte[]) commState.cur))\n return false;\n commState.cur = NULL;\n }\n commState.it = null;\n } else {\n if (!commState.putInt(-1))\n return false;\n }\n commState.idx++;\n }\n return true;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public boolean readFrom(ByteBuffer buf) {\n commState.setBuffer(buf);\n if (!super.readFrom(buf))\n return false;\n switch(commState.idx) {\n case 2:\n byte[] errBytes0 = commState.getByteArray();\n if (errBytes0 == BYTE_ARR_NOT_READ)\n return false;\n errBytes = errBytes0;\n commState.idx++;\n case 3:\n byte[] failedKeysBytes0 = commState.getByteArray();\n if (failedKeysBytes0 == BYTE_ARR_NOT_READ)\n return false;\n failedKeysBytes = failedKeysBytes0;\n commState.idx++;\n case 4:\n GridCacheVersion futVer0 = commState.getCacheVersion();\n if (futVer0 == CACHE_VER_NOT_READ)\n return false;\n futVer = futVer0;\n commState.idx++;\n case 5:\n if (commState.readSize == -1) {\n if (buf.remaining() < 4)\n return false;\n commState.readSize = commState.getInt();\n }\n if (commState.readSize >= 0) {\n if (nearEvictedBytes == null)\n nearEvictedBytes = new ArrayList<>(commState.readSize);\n for (int i = commState.readItems; i < commState.readSize; i++) {\n byte[] _val = commState.getByteArray();\n if (_val == BYTE_ARR_NOT_READ)\n return false;\n nearEvictedBytes.add((byte[]) _val);\n commState.readItems++;\n }\n }\n commState.readSize = -1;\n commState.readItems = 0;\n commState.idx++;\n }\n return true;\n }\n\n @Override\n public byte directType() {\n return 38;\n }\n\n @Override\n public String toString() {\n return S.toString(GridDhtAtomicUpdateResponse.class, this);\n }\n}\n"} {"task_id": "Java_2906", "language": "Java", "task_type": "for_statement", "source_file": "java/github/gridgain/gridgain-old/modules/core/src/main/java/org/gridgain/grid/kernal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java", "mask_start_position": 8122, "mask_end_position": 8477, "canonical_solution": "for (int i = commState.readItems; i < commState.readSize; i++) {\n byte[] _val = commState.getByteArray();\n if (_val == BYTE_ARR_NOT_READ)\n return false;\n nearEvictedBytes.add((byte[]) _val);\n commState.readItems++;\n }", "pre_mask_code": "/* _________ _____ __________________ _____\n * __ ____/___________(_)______ /__ ____/______ ____(_)_______\n * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \\\n * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /\n * \\____/ /_/ /_/ \\_,__/ \\____/ \\__,_/ /_/ /_/ /_/\n */\npackage org.gridgain.grid.kernal.processors.cache.distributed.dht.atomic;\n\nimport org.gridgain.grid.*;\nimport org.gridgain.grid.kernal.*;\nimport org.gridgain.grid.kernal.processors.cache.*;\nimport org.gridgain.grid.util.direct.*;\nimport org.gridgain.grid.util.typedef.internal.*;\nimport org.gridgain.grid.util.tostring.*;\nimport org.jetbrains.annotations.*;\nimport java.io.*;\nimport java.nio.*;\nimport java.util.*;\n\n/**\n * DHT atomic cache backup update response.\n */\npublic class GridDhtAtomicUpdateResponse extends GridCacheMessage implements GridCacheDeployable {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Message index.\n */\n public static final int CACHE_MSG_IDX = nextIndexId();\n\n /**\n * Future version.\n */\n private GridCacheVersion futVer;\n\n /**\n * Failed keys.\n */\n @GridToStringInclude\n @GridDirectTransient\n private Collection failedKeys;\n\n /**\n * Serialized failed keys.\n */\n private byte[] failedKeysBytes;\n\n /**\n * Update error.\n */\n @GridDirectTransient\n private GridException err;\n\n /**\n * Serialized update error.\n */\n private byte[] errBytes;\n\n /**\n * Evicted readers.\n */\n @GridToStringInclude\n @GridDirectTransient\n private Collection nearEvicted;\n\n /**\n * Evicted reader key bytes.\n */\n @GridDirectCollection(byte[].class)\n @GridDirectVersion(1)\n private Collection nearEvictedBytes;\n\n /**\n * Empty constructor required by {@link Externalizable}.\n */\n public GridDhtAtomicUpdateResponse() {\n }\n\n /**\n * @param futVer Future version.\n */\n public GridDhtAtomicUpdateResponse(GridCacheVersion futVer) {\n this.futVer = futVer;\n }\n\n @Override\n public int lookupIndex() {\n return CACHE_MSG_IDX;\n }\n\n public GridCacheVersion futureVersion() {\n return futVer;\n }\n\n /**\n * @return Gets update error.\n */\n public GridException error() {\n return err;\n }\n\n public Collection failedKeys() {\n return failedKeys;\n }\n\n /**\n * Adds key to collection of failed keys.\n *\n * @param key Key to add.\n * @param e Error cause.\n */\n public void addFailedKey(K key, Throwable e) {\n if (failedKeys == null)\n failedKeys = new ArrayList<>();\n failedKeys.add(key);\n if (err == null)\n err = new GridException(\"Failed to update keys on primary node.\");\n err.addSuppressed(e);\n }\n\n public Collection nearEvicted() {\n return nearEvicted;\n }\n\n /**\n * Adds near evicted key..\n *\n * @param key Evicted key.\n * @param bytes Bytes of evicted key.\n */\n public void addNearEvicted(K key, @Nullable byte[] bytes) {\n if (nearEvicted == null)\n nearEvicted = new ArrayList<>();\n nearEvicted.add(key);\n if (bytes != null) {\n if (nearEvictedBytes == null)\n nearEvictedBytes = new ArrayList<>();\n nearEvictedBytes.add(bytes);\n }\n }\n\n @Override\n public void prepareMarshal(GridCacheContext ctx) throws GridException {\n super.prepareMarshal(ctx);\n failedKeysBytes = ctx.marshaller().marshal(failedKeys);\n errBytes = ctx.marshaller().marshal(err);\n if (nearEvictedBytes == null)\n nearEvictedBytes = marshalCollection(nearEvicted, ctx);\n }\n\n @Override\n public void finishUnmarshal(GridCacheContext ctx, ClassLoader ldr) throws GridException {\n super.finishUnmarshal(ctx, ldr);\n failedKeys = ctx.marshaller().unmarshal(failedKeysBytes, ldr);\n err = ctx.marshaller().unmarshal(errBytes, ldr);\n if (nearEvicted == null && nearEvictedBytes != null)\n nearEvicted = unmarshalCollection(nearEvictedBytes, ctx, ldr);\n }\n\n @SuppressWarnings({ \"CloneDoesntCallSuperClone\", \"CloneCallsConstructors\" })\n @Override\n public GridTcpCommunicationMessageAdapter clone() {\n GridDhtAtomicUpdateResponse _clone = new GridDhtAtomicUpdateResponse();\n clone0(_clone);\n return _clone;\n }\n\n @Override\n protected void clone0(GridTcpCommunicationMessageAdapter _msg) {\n super.clone0(_msg);\n GridDhtAtomicUpdateResponse _clone = (GridDhtAtomicUpdateResponse) _msg;\n _clone.futVer = futVer;\n _clone.failedKeys = failedKeys;\n _clone.failedKeysBytes = failedKeysBytes;\n _clone.err = err;\n _clone.errBytes = errBytes;\n _clone.nearEvicted = nearEvicted;\n _clone.nearEvictedBytes = nearEvictedBytes;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public boolean writeTo(ByteBuffer buf) {\n commState.setBuffer(buf);\n if (!super.writeTo(buf))\n return false;\n if (!commState.typeWritten) {\n if (!commState.putByte(directType()))\n return false;\n commState.typeWritten = true;\n }\n switch(commState.idx) {\n case 2:\n if (!commState.putByteArray(errBytes))\n return false;\n commState.idx++;\n case 3:\n if (!commState.putByteArray(failedKeysBytes))\n return false;\n commState.idx++;\n case 4:\n if (!commState.putCacheVersion(futVer))\n return false;\n commState.idx++;\n case 5:\n if (nearEvictedBytes != null) {\n if (commState.it == null) {\n if (!commState.putInt(nearEvictedBytes.size()))\n return false;\n commState.it = nearEvictedBytes.iterator();\n }\n while (commState.it.hasNext() || commState.cur != NULL) {\n if (commState.cur == NULL)\n commState.cur = commState.it.next();\n if (!commState.putByteArray((byte[]) commState.cur))\n return false;\n commState.cur = NULL;\n }\n commState.it = null;\n } else {\n if (!commState.putInt(-1))\n return false;\n }\n commState.idx++;\n }\n return true;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public boolean readFrom(ByteBuffer buf) {\n commState.setBuffer(buf);\n if (!super.readFrom(buf))\n return false;\n switch(commState.idx) {\n case 2:\n byte[] errBytes0 = commState.getByteArray();\n if (errBytes0 == BYTE_ARR_NOT_READ)\n return false;\n errBytes = errBytes0;\n commState.idx++;\n case 3:\n byte[] failedKeysBytes0 = commState.getByteArray();\n if (failedKeysBytes0 == BYTE_ARR_NOT_READ)\n return false;\n failedKeysBytes = failedKeysBytes0;\n commState.idx++;\n case 4:\n GridCacheVersion futVer0 = commState.getCacheVersion();\n if (futVer0 == CACHE_VER_NOT_READ)\n return false;\n futVer = futVer0;\n commState.idx++;\n case 5:\n if (commState.readSize == -1) {\n if (buf.remaining() < 4)\n return false;\n commState.readSize = commState.getInt();\n }\n if (commState.readSize >= 0) {\n if (nearEvictedBytes == null)\n nearEvictedBytes = new ArrayList<>(commState.readSize);\n ", "post_mask_code": "\n }\n commState.readSize = -1;\n commState.readItems = 0;\n commState.idx++;\n }\n return true;\n }\n\n @Override\n public byte directType() {\n return 38;\n }\n\n @Override\n public String toString() {\n return S.toString(GridDhtAtomicUpdateResponse.class, this);\n }\n}\n"} {"task_id": "Java_2907", "language": "Java", "task_type": "while_statement", "source_file": "java/github/gridgain/gridgain-old/modules/core/src/main/java/org/gridgain/grid/kernal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java", "mask_start_position": 6131, "mask_end_position": 6491, "canonical_solution": "while (commState.it.hasNext() || commState.cur != NULL) {\n if (commState.cur == NULL)\n commState.cur = commState.it.next();\n if (!commState.putByteArray((byte[]) commState.cur))\n return false;\n commState.cur = NULL;\n }", "pre_mask_code": "/* _________ _____ __________________ _____\n * __ ____/___________(_)______ /__ ____/______ ____(_)_______\n * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \\\n * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /\n * \\____/ /_/ /_/ \\_,__/ \\____/ \\__,_/ /_/ /_/ /_/\n */\npackage org.gridgain.grid.kernal.processors.cache.distributed.dht.atomic;\n\nimport org.gridgain.grid.*;\nimport org.gridgain.grid.kernal.*;\nimport org.gridgain.grid.kernal.processors.cache.*;\nimport org.gridgain.grid.util.direct.*;\nimport org.gridgain.grid.util.typedef.internal.*;\nimport org.gridgain.grid.util.tostring.*;\nimport org.jetbrains.annotations.*;\nimport java.io.*;\nimport java.nio.*;\nimport java.util.*;\n\n/**\n * DHT atomic cache backup update response.\n */\npublic class GridDhtAtomicUpdateResponse extends GridCacheMessage implements GridCacheDeployable {\n\n private static final long serialVersionUID = 0L;\n\n /**\n * Message index.\n */\n public static final int CACHE_MSG_IDX = nextIndexId();\n\n /**\n * Future version.\n */\n private GridCacheVersion futVer;\n\n /**\n * Failed keys.\n */\n @GridToStringInclude\n @GridDirectTransient\n private Collection failedKeys;\n\n /**\n * Serialized failed keys.\n */\n private byte[] failedKeysBytes;\n\n /**\n * Update error.\n */\n @GridDirectTransient\n private GridException err;\n\n /**\n * Serialized update error.\n */\n private byte[] errBytes;\n\n /**\n * Evicted readers.\n */\n @GridToStringInclude\n @GridDirectTransient\n private Collection nearEvicted;\n\n /**\n * Evicted reader key bytes.\n */\n @GridDirectCollection(byte[].class)\n @GridDirectVersion(1)\n private Collection nearEvictedBytes;\n\n /**\n * Empty constructor required by {@link Externalizable}.\n */\n public GridDhtAtomicUpdateResponse() {\n }\n\n /**\n * @param futVer Future version.\n */\n public GridDhtAtomicUpdateResponse(GridCacheVersion futVer) {\n this.futVer = futVer;\n }\n\n @Override\n public int lookupIndex() {\n return CACHE_MSG_IDX;\n }\n\n public GridCacheVersion futureVersion() {\n return futVer;\n }\n\n /**\n * @return Gets update error.\n */\n public GridException error() {\n return err;\n }\n\n public Collection failedKeys() {\n return failedKeys;\n }\n\n /**\n * Adds key to collection of failed keys.\n *\n * @param key Key to add.\n * @param e Error cause.\n */\n public void addFailedKey(K key, Throwable e) {\n if (failedKeys == null)\n failedKeys = new ArrayList<>();\n failedKeys.add(key);\n if (err == null)\n err = new GridException(\"Failed to update keys on primary node.\");\n err.addSuppressed(e);\n }\n\n public Collection nearEvicted() {\n return nearEvicted;\n }\n\n /**\n * Adds near evicted key..\n *\n * @param key Evicted key.\n * @param bytes Bytes of evicted key.\n */\n public void addNearEvicted(K key, @Nullable byte[] bytes) {\n if (nearEvicted == null)\n nearEvicted = new ArrayList<>();\n nearEvicted.add(key);\n if (bytes != null) {\n if (nearEvictedBytes == null)\n nearEvictedBytes = new ArrayList<>();\n nearEvictedBytes.add(bytes);\n }\n }\n\n @Override\n public void prepareMarshal(GridCacheContext ctx) throws GridException {\n super.prepareMarshal(ctx);\n failedKeysBytes = ctx.marshaller().marshal(failedKeys);\n errBytes = ctx.marshaller().marshal(err);\n if (nearEvictedBytes == null)\n nearEvictedBytes = marshalCollection(nearEvicted, ctx);\n }\n\n @Override\n public void finishUnmarshal(GridCacheContext ctx, ClassLoader ldr) throws GridException {\n super.finishUnmarshal(ctx, ldr);\n failedKeys = ctx.marshaller().unmarshal(failedKeysBytes, ldr);\n err = ctx.marshaller().unmarshal(errBytes, ldr);\n if (nearEvicted == null && nearEvictedBytes != null)\n nearEvicted = unmarshalCollection(nearEvictedBytes, ctx, ldr);\n }\n\n @SuppressWarnings({ \"CloneDoesntCallSuperClone\", \"CloneCallsConstructors\" })\n @Override\n public GridTcpCommunicationMessageAdapter clone() {\n GridDhtAtomicUpdateResponse _clone = new GridDhtAtomicUpdateResponse();\n clone0(_clone);\n return _clone;\n }\n\n @Override\n protected void clone0(GridTcpCommunicationMessageAdapter _msg) {\n super.clone0(_msg);\n GridDhtAtomicUpdateResponse _clone = (GridDhtAtomicUpdateResponse) _msg;\n _clone.futVer = futVer;\n _clone.failedKeys = failedKeys;\n _clone.failedKeysBytes = failedKeysBytes;\n _clone.err = err;\n _clone.errBytes = errBytes;\n _clone.nearEvicted = nearEvicted;\n _clone.nearEvictedBytes = nearEvictedBytes;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public boolean writeTo(ByteBuffer buf) {\n commState.setBuffer(buf);\n if (!super.writeTo(buf))\n return false;\n if (!commState.typeWritten) {\n if (!commState.putByte(directType()))\n return false;\n commState.typeWritten = true;\n }\n switch(commState.idx) {\n case 2:\n if (!commState.putByteArray(errBytes))\n return false;\n commState.idx++;\n case 3:\n if (!commState.putByteArray(failedKeysBytes))\n return false;\n commState.idx++;\n case 4:\n if (!commState.putCacheVersion(futVer))\n return false;\n commState.idx++;\n case 5:\n if (nearEvictedBytes != null) {\n if (commState.it == null) {\n if (!commState.putInt(nearEvictedBytes.size()))\n return false;\n commState.it = nearEvictedBytes.iterator();\n }\n ", "post_mask_code": "\n commState.it = null;\n } else {\n if (!commState.putInt(-1))\n return false;\n }\n commState.idx++;\n }\n return true;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public boolean readFrom(ByteBuffer buf) {\n commState.setBuffer(buf);\n if (!super.readFrom(buf))\n return false;\n switch(commState.idx) {\n case 2:\n byte[] errBytes0 = commState.getByteArray();\n if (errBytes0 == BYTE_ARR_NOT_READ)\n return false;\n errBytes = errBytes0;\n commState.idx++;\n case 3:\n byte[] failedKeysBytes0 = commState.getByteArray();\n if (failedKeysBytes0 == BYTE_ARR_NOT_READ)\n return false;\n failedKeysBytes = failedKeysBytes0;\n commState.idx++;\n case 4:\n GridCacheVersion futVer0 = commState.getCacheVersion();\n if (futVer0 == CACHE_VER_NOT_READ)\n return false;\n futVer = futVer0;\n commState.idx++;\n case 5:\n if (commState.readSize == -1) {\n if (buf.remaining() < 4)\n return false;\n commState.readSize = commState.getInt();\n }\n if (commState.readSize >= 0) {\n if (nearEvictedBytes == null)\n nearEvictedBytes = new ArrayList<>(commState.readSize);\n for (int i = commState.readItems; i < commState.readSize; i++) {\n byte[] _val = commState.getByteArray();\n if (_val == BYTE_ARR_NOT_READ)\n return false;\n nearEvictedBytes.add((byte[]) _val);\n commState.readItems++;\n }\n }\n commState.readSize = -1;\n commState.readItems = 0;\n commState.idx++;\n }\n return true;\n }\n\n @Override\n public byte directType() {\n return 38;\n }\n\n @Override\n public String toString() {\n return S.toString(GridDhtAtomicUpdateResponse.class, this);\n }\n}\n"} {"task_id": "Java_2908", "language": "Java", "task_type": "method_signature", "source_file": "java/github/TeamPneumatic/pnc-repressurized/src/main/java/me/desht/pneumaticcraft/client/render/pneumatic_armor/block_tracker/BlockTrackEntryList.java", "mask_start_position": 1087, "mask_end_position": 1196, "canonical_solution": "public List getEntriesForCoordinate(IBlockReader blockAccess, BlockPos pos, TileEntity te) ", "pre_mask_code": "package me.desht.pneumaticcraft.client.render.pneumatic_armor.block_tracker;\n\nimport me.desht.pneumaticcraft.api.client.pneumatic_helmet.IBlockTrackEntry;\nimport me.desht.pneumaticcraft.client.gui.widget.WidgetKeybindCheckBox;\nimport net.minecraft.block.BlockState;\nimport net.minecraft.tileentity.TileEntity;\nimport net.minecraft.util.NonNullList;\nimport net.minecraft.util.math.BlockPos;\nimport net.minecraft.world.IBlockReader;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic enum BlockTrackEntryList {\n\n INSTANCE;\n\n public final NonNullList trackList = NonNullList.create();\n\n // initialize default Block Track Entries.\n BlockTrackEntryList() {\n trackList.add(new BlockTrackEntryHackable());\n trackList.add(new BlockTrackEntryInventory());\n trackList.add(new BlockTrackEntryFluid());\n trackList.add(new BlockTrackEntryEndPortalFrame());\n trackList.add(new BlockTrackEntryMobSpawner());\n trackList.add(new BlockTrackEntryMisc());\n trackList.add(new BlockTrackEntryEnergy());\n }\n\n ", "post_mask_code": "{\n final BlockState state = blockAccess.getBlockState(pos);\n return trackList.stream().filter(entry -> WidgetKeybindCheckBox.get(entry.getEntryID()).checked && entry.shouldTrackWithThisEntry(blockAccess, pos, state, te)).collect(Collectors.toList());\n }\n}\n"} {"task_id": "Java_2909", "language": "Java", "task_type": "method_body", "source_file": "java/github/TeamPneumatic/pnc-repressurized/src/main/java/me/desht/pneumaticcraft/client/render/pneumatic_armor/block_tracker/BlockTrackEntryList.java", "mask_start_position": 1196, "mask_end_position": 1466, "canonical_solution": "{\n final BlockState state = blockAccess.getBlockState(pos);\n return trackList.stream().filter(entry -> WidgetKeybindCheckBox.get(entry.getEntryID()).checked && entry.shouldTrackWithThisEntry(blockAccess, pos, state, te)).collect(Collectors.toList());\n }", "pre_mask_code": "package me.desht.pneumaticcraft.client.render.pneumatic_armor.block_tracker;\n\nimport me.desht.pneumaticcraft.api.client.pneumatic_helmet.IBlockTrackEntry;\nimport me.desht.pneumaticcraft.client.gui.widget.WidgetKeybindCheckBox;\nimport net.minecraft.block.BlockState;\nimport net.minecraft.tileentity.TileEntity;\nimport net.minecraft.util.NonNullList;\nimport net.minecraft.util.math.BlockPos;\nimport net.minecraft.world.IBlockReader;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic enum BlockTrackEntryList {\n\n INSTANCE;\n\n public final NonNullList trackList = NonNullList.create();\n\n // initialize default Block Track Entries.\n BlockTrackEntryList() {\n trackList.add(new BlockTrackEntryHackable());\n trackList.add(new BlockTrackEntryInventory());\n trackList.add(new BlockTrackEntryFluid());\n trackList.add(new BlockTrackEntryEndPortalFrame());\n trackList.add(new BlockTrackEntryMobSpawner());\n trackList.add(new BlockTrackEntryMisc());\n trackList.add(new BlockTrackEntryEnergy());\n }\n\n public List getEntriesForCoordinate(IBlockReader blockAccess, BlockPos pos, TileEntity te) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2910", "language": "Java", "task_type": "single_line", "source_file": "java/github/TeamPneumatic/pnc-repressurized/src/main/java/me/desht/pneumaticcraft/client/render/pneumatic_armor/block_tracker/BlockTrackEntryList.java", "mask_start_position": 1246, "mask_end_position": 1262, "canonical_solution": "BlockState(pos);", "pre_mask_code": "package me.desht.pneumaticcraft.client.render.pneumatic_armor.block_tracker;\n\nimport me.desht.pneumaticcraft.api.client.pneumatic_helmet.IBlockTrackEntry;\nimport me.desht.pneumaticcraft.client.gui.widget.WidgetKeybindCheckBox;\nimport net.minecraft.block.BlockState;\nimport net.minecraft.tileentity.TileEntity;\nimport net.minecraft.util.NonNullList;\nimport net.minecraft.util.math.BlockPos;\nimport net.minecraft.world.IBlockReader;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic enum BlockTrackEntryList {\n\n INSTANCE;\n\n public final NonNullList trackList = NonNullList.create();\n\n // initialize default Block Track Entries.\n BlockTrackEntryList() {\n trackList.add(new BlockTrackEntryHackable());\n trackList.add(new BlockTrackEntryInventory());\n trackList.add(new BlockTrackEntryFluid());\n trackList.add(new BlockTrackEntryEndPortalFrame());\n trackList.add(new BlockTrackEntryMobSpawner());\n trackList.add(new BlockTrackEntryMisc());\n trackList.add(new BlockTrackEntryEnergy());\n }\n\n public List getEntriesForCoordinate(IBlockReader blockAccess, BlockPos pos, TileEntity te) {\n final BlockState state = blockAccess.get", "post_mask_code": "\n return trackList.stream().filter(entry -> WidgetKeybindCheckBox.get(entry.getEntryID()).checked && entry.shouldTrackWithThisEntry(blockAccess, pos, state, te)).collect(Collectors.toList());\n }\n}\n"} {"task_id": "Java_2911", "language": "Java", "task_type": "method_signature", "source_file": "java/github/amient/kafka-metrics/core/src/main/java/io/amient/kafka/metrics/MeasurementDeserializer.java", "mask_start_position": 1120, "mask_end_position": 1154, "canonical_solution": "@Override\n public void close() ", "pre_mask_code": "package io.amient.kafka.metrics;\n\nimport org.apache.kafka.common.errors.SerializationException;\nimport org.apache.kafka.common.serialization.Deserializer;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\n\npublic class MeasurementDeserializer implements Deserializer> {\n\n private InternalAvroSerde internalAvro = new InternalAvroSerde();\n\n private AutoJsonDeserializer autoJsonDeserializer = new AutoJsonDeserializer();\n\n @Override\n public void configure(Map configs, boolean isKey) {\n }\n\n @Override\n public List deserialize(String topic, byte[] bytes) {\n switch(bytes[0]) {\n case 0x0:\n throw new SerializationException(\"Schema Registry doesn't support maps and arrays yet.\");\n case 0x1:\n return Arrays.asList(internalAvro.fromBytes(bytes));\n case '{':\n return autoJsonDeserializer.fromBytes(bytes);\n default:\n throw new SerializationException(\"Serialization MAGIC_BYTE not recognized: \" + bytes[0]);\n }\n }\n\n ", "post_mask_code": "{\n }\n}\n"} {"task_id": "Java_2912", "language": "Java", "task_type": "method_body", "source_file": "java/github/amient/kafka-metrics/core/src/main/java/io/amient/kafka/metrics/MeasurementDeserializer.java", "mask_start_position": 1154, "mask_end_position": 1161, "canonical_solution": "{\n }", "pre_mask_code": "package io.amient.kafka.metrics;\n\nimport org.apache.kafka.common.errors.SerializationException;\nimport org.apache.kafka.common.serialization.Deserializer;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\n\npublic class MeasurementDeserializer implements Deserializer> {\n\n private InternalAvroSerde internalAvro = new InternalAvroSerde();\n\n private AutoJsonDeserializer autoJsonDeserializer = new AutoJsonDeserializer();\n\n @Override\n public void configure(Map configs, boolean isKey) {\n }\n\n @Override\n public List deserialize(String topic, byte[] bytes) {\n switch(bytes[0]) {\n case 0x0:\n throw new SerializationException(\"Schema Registry doesn't support maps and arrays yet.\");\n case 0x1:\n return Arrays.asList(internalAvro.fromBytes(bytes));\n case '{':\n return autoJsonDeserializer.fromBytes(bytes);\n default:\n throw new SerializationException(\"Serialization MAGIC_BYTE not recognized: \" + bytes[0]);\n }\n }\n\n @Override\n public void close() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2913", "language": "Java", "task_type": "switch_case", "source_file": "java/github/amient/kafka-metrics/core/src/main/java/io/amient/kafka/metrics/MeasurementDeserializer.java", "mask_start_position": 650, "mask_end_position": 1108, "canonical_solution": "switch(bytes[0]) {\n case 0x0:\n throw new SerializationException(\"Schema Registry doesn't support maps and arrays yet.\");\n case 0x1:\n return Arrays.asList(internalAvro.fromBytes(bytes));\n case '{':\n return autoJsonDeserializer.fromBytes(bytes);\n default:\n throw new SerializationException(\"Serialization MAGIC_BYTE not recognized: \" + bytes[0]);\n }", "pre_mask_code": "package io.amient.kafka.metrics;\n\nimport org.apache.kafka.common.errors.SerializationException;\nimport org.apache.kafka.common.serialization.Deserializer;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\n\npublic class MeasurementDeserializer implements Deserializer> {\n\n private InternalAvroSerde internalAvro = new InternalAvroSerde();\n\n private AutoJsonDeserializer autoJsonDeserializer = new AutoJsonDeserializer();\n\n @Override\n public void configure(Map configs, boolean isKey) {\n }\n\n @Override\n public List deserialize(String topic, byte[] bytes) {\n ", "post_mask_code": "\n }\n\n @Override\n public void close() {\n }\n}\n"} {"task_id": "Java_2914", "language": "Java", "task_type": "method_signature", "source_file": "java/github/atomix/atomix/utils/src/main/java/io/atomix/utils/time/Versioned.java", "mask_start_position": 1692, "mask_end_position": 1719, "canonical_solution": "public long creationTime() ", "pre_mask_code": "package io.atomix.utils.time;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport io.atomix.utils.misc.ArraySizeHashPrinter;\nimport io.atomix.utils.misc.TimestampPrinter;\nimport java.util.function.Function;\n\npublic class Versioned {\n\n private final V value;\n\n private final long version;\n\n private final long creationTime;\n\n /**\n * Constructs a new versioned value.\n *\n * @param value value\n * @param version version\n * @param creationTime milliseconds of the creation event\n * from the Java epoch of 1970-01-01T00:00:00Z\n */\n public Versioned(V value, long version, long creationTime) {\n this.value = value;\n this.version = version;\n this.creationTime = creationTime;\n }\n\n /**\n * Constructs a new versioned value.\n *\n * @param value value\n * @param version version\n */\n public Versioned(V value, long version) {\n this(value, version, System.currentTimeMillis());\n }\n\n /**\n * Returns the value.\n *\n * @return value.\n */\n public V value() {\n return value;\n }\n\n /**\n * Returns the version.\n *\n * @return version\n */\n public long version() {\n return version;\n }\n\n /**\n * Returns the system time when this version was created.\n *

\n * Care should be taken when relying on creationTime to\n * implement any behavior in a distributed setting. Due\n * to the possibility of clock skew it is likely that\n * even creationTimes of causally related versions can be\n * out or order.\n *\n * @return creation time\n */\n ", "post_mask_code": "{\n return creationTime;\n }\n\n /**\n * Maps this instance into another after transforming its\n * value while retaining the same version and creationTime.\n *\n * @param transformer function for mapping the value\n * @param value type of the returned instance\n * @return mapped instance\n */\n public synchronized Versioned map(Function transformer) {\n return new Versioned<>(value != null ? transformer.apply(value) : null, version, creationTime);\n }\n\n /**\n * Returns the value of the specified Versioned object if non-null or else returns\n * a default value.\n *\n * @param versioned versioned object\n * @param defaultValue default value to return if versioned object is null\n * @param type of the versioned value\n * @return versioned value or default value if versioned object is null\n */\n public static U valueOrElse(Versioned versioned, U defaultValue) {\n return versioned == null ? defaultValue : versioned.value();\n }\n\n /**\n * Returns the value of the specified Versioned object if non-null or else returns null.\n *\n * @param versioned versioned object\n * @param type of the versioned value\n * @return versioned value or null if versioned object is null\n */\n public static U valueOrNull(Versioned versioned) {\n return valueOrElse(versioned, null);\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(value, version, creationTime);\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof Versioned)) {\n return false;\n }\n Versioned that = (Versioned) other;\n return Objects.equal(this.value, that.value) && Objects.equal(this.version, that.version) && Objects.equal(this.creationTime, that.creationTime);\n }\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(this).add(\"value\", value instanceof byte[] ? ArraySizeHashPrinter.of((byte[]) value) : value).add(\"version\", version).add(\"creationTime\", new TimestampPrinter(creationTime)).toString();\n }\n}\n"} {"task_id": "Java_2915", "language": "Java", "task_type": "method_body", "source_file": "java/github/atomix/atomix/utils/src/main/java/io/atomix/utils/time/Versioned.java", "mask_start_position": 3340, "mask_end_position": 3629, "canonical_solution": "{\n if (!(other instanceof Versioned)) {\n return false;\n }\n Versioned that = (Versioned) other;\n return Objects.equal(this.value, that.value) && Objects.equal(this.version, that.version) && Objects.equal(this.creationTime, that.creationTime);\n }", "pre_mask_code": "package io.atomix.utils.time;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport io.atomix.utils.misc.ArraySizeHashPrinter;\nimport io.atomix.utils.misc.TimestampPrinter;\nimport java.util.function.Function;\n\npublic class Versioned {\n\n private final V value;\n\n private final long version;\n\n private final long creationTime;\n\n /**\n * Constructs a new versioned value.\n *\n * @param value value\n * @param version version\n * @param creationTime milliseconds of the creation event\n * from the Java epoch of 1970-01-01T00:00:00Z\n */\n public Versioned(V value, long version, long creationTime) {\n this.value = value;\n this.version = version;\n this.creationTime = creationTime;\n }\n\n /**\n * Constructs a new versioned value.\n *\n * @param value value\n * @param version version\n */\n public Versioned(V value, long version) {\n this(value, version, System.currentTimeMillis());\n }\n\n /**\n * Returns the value.\n *\n * @return value.\n */\n public V value() {\n return value;\n }\n\n /**\n * Returns the version.\n *\n * @return version\n */\n public long version() {\n return version;\n }\n\n /**\n * Returns the system time when this version was created.\n *

\n * Care should be taken when relying on creationTime to\n * implement any behavior in a distributed setting. Due\n * to the possibility of clock skew it is likely that\n * even creationTimes of causally related versions can be\n * out or order.\n *\n * @return creation time\n */\n public long creationTime() {\n return creationTime;\n }\n\n /**\n * Maps this instance into another after transforming its\n * value while retaining the same version and creationTime.\n *\n * @param transformer function for mapping the value\n * @param value type of the returned instance\n * @return mapped instance\n */\n public synchronized Versioned map(Function transformer) {\n return new Versioned<>(value != null ? transformer.apply(value) : null, version, creationTime);\n }\n\n /**\n * Returns the value of the specified Versioned object if non-null or else returns\n * a default value.\n *\n * @param versioned versioned object\n * @param defaultValue default value to return if versioned object is null\n * @param type of the versioned value\n * @return versioned value or default value if versioned object is null\n */\n public static U valueOrElse(Versioned versioned, U defaultValue) {\n return versioned == null ? defaultValue : versioned.value();\n }\n\n /**\n * Returns the value of the specified Versioned object if non-null or else returns null.\n *\n * @param versioned versioned object\n * @param type of the versioned value\n * @return versioned value or null if versioned object is null\n */\n public static U valueOrNull(Versioned versioned) {\n return valueOrElse(versioned, null);\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(value, version, creationTime);\n }\n\n @Override\n public boolean equals(Object other) ", "post_mask_code": "\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(this).add(\"value\", value instanceof byte[] ? ArraySizeHashPrinter.of((byte[]) value) : value).add(\"version\", version).add(\"creationTime\", new TimestampPrinter(creationTime)).toString();\n }\n}\n"} {"task_id": "Java_2916", "language": "Java", "task_type": "single_line", "source_file": "java/github/atomix/atomix/utils/src/main/java/io/atomix/utils/time/Versioned.java", "mask_start_position": 3160, "mask_end_position": 3166, "canonical_solution": "null);", "pre_mask_code": "package io.atomix.utils.time;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport io.atomix.utils.misc.ArraySizeHashPrinter;\nimport io.atomix.utils.misc.TimestampPrinter;\nimport java.util.function.Function;\n\npublic class Versioned {\n\n private final V value;\n\n private final long version;\n\n private final long creationTime;\n\n /**\n * Constructs a new versioned value.\n *\n * @param value value\n * @param version version\n * @param creationTime milliseconds of the creation event\n * from the Java epoch of 1970-01-01T00:00:00Z\n */\n public Versioned(V value, long version, long creationTime) {\n this.value = value;\n this.version = version;\n this.creationTime = creationTime;\n }\n\n /**\n * Constructs a new versioned value.\n *\n * @param value value\n * @param version version\n */\n public Versioned(V value, long version) {\n this(value, version, System.currentTimeMillis());\n }\n\n /**\n * Returns the value.\n *\n * @return value.\n */\n public V value() {\n return value;\n }\n\n /**\n * Returns the version.\n *\n * @return version\n */\n public long version() {\n return version;\n }\n\n /**\n * Returns the system time when this version was created.\n *

\n * Care should be taken when relying on creationTime to\n * implement any behavior in a distributed setting. Due\n * to the possibility of clock skew it is likely that\n * even creationTimes of causally related versions can be\n * out or order.\n *\n * @return creation time\n */\n public long creationTime() {\n return creationTime;\n }\n\n /**\n * Maps this instance into another after transforming its\n * value while retaining the same version and creationTime.\n *\n * @param transformer function for mapping the value\n * @param value type of the returned instance\n * @return mapped instance\n */\n public synchronized Versioned map(Function transformer) {\n return new Versioned<>(value != null ? transformer.apply(value) : null, version, creationTime);\n }\n\n /**\n * Returns the value of the specified Versioned object if non-null or else returns\n * a default value.\n *\n * @param versioned versioned object\n * @param defaultValue default value to return if versioned object is null\n * @param type of the versioned value\n * @return versioned value or default value if versioned object is null\n */\n public static U valueOrElse(Versioned versioned, U defaultValue) {\n return versioned == null ? defaultValue : versioned.value();\n }\n\n /**\n * Returns the value of the specified Versioned object if non-null or else returns null.\n *\n * @param versioned versioned object\n * @param type of the versioned value\n * @return versioned value or null if versioned object is null\n */\n public static U valueOrNull(Versioned versioned) {\n return valueOrElse(versioned, ", "post_mask_code": "\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(value, version, creationTime);\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof Versioned)) {\n return false;\n }\n Versioned that = (Versioned) other;\n return Objects.equal(this.value, that.value) && Objects.equal(this.version, that.version) && Objects.equal(this.creationTime, that.creationTime);\n }\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(this).add(\"value\", value instanceof byte[] ? ArraySizeHashPrinter.of((byte[]) value) : value).add(\"version\", version).add(\"creationTime\", new TimestampPrinter(creationTime)).toString();\n }\n}\n"} {"task_id": "Java_2917", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/atomix/atomix/utils/src/main/java/io/atomix/utils/time/Versioned.java", "mask_start_position": 3064, "mask_end_position": 3172, "canonical_solution": "public static U valueOrNull(Versioned versioned) {\n return valueOrElse(versioned, null);\n }", "pre_mask_code": "package io.atomix.utils.time;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport io.atomix.utils.misc.ArraySizeHashPrinter;\nimport io.atomix.utils.misc.TimestampPrinter;\nimport java.util.function.Function;\n\npublic class Versioned {\n\n private final V value;\n\n private final long version;\n\n private final long creationTime;\n\n /**\n * Constructs a new versioned value.\n *\n * @param value value\n * @param version version\n * @param creationTime milliseconds of the creation event\n * from the Java epoch of 1970-01-01T00:00:00Z\n */\n public Versioned(V value, long version, long creationTime) {\n this.value = value;\n this.version = version;\n this.creationTime = creationTime;\n }\n\n /**\n * Constructs a new versioned value.\n *\n * @param value value\n * @param version version\n */\n public Versioned(V value, long version) {\n this(value, version, System.currentTimeMillis());\n }\n\n /**\n * Returns the value.\n *\n * @return value.\n */\n public V value() {\n return value;\n }\n\n /**\n * Returns the version.\n *\n * @return version\n */\n public long version() {\n return version;\n }\n\n /**\n * Returns the system time when this version was created.\n *

\n * Care should be taken when relying on creationTime to\n * implement any behavior in a distributed setting. Due\n * to the possibility of clock skew it is likely that\n * even creationTimes of causally related versions can be\n * out or order.\n *\n * @return creation time\n */\n public long creationTime() {\n return creationTime;\n }\n\n /**\n * Maps this instance into another after transforming its\n * value while retaining the same version and creationTime.\n *\n * @param transformer function for mapping the value\n * @param value type of the returned instance\n * @return mapped instance\n */\n public synchronized Versioned map(Function transformer) {\n return new Versioned<>(value != null ? transformer.apply(value) : null, version, creationTime);\n }\n\n /**\n * Returns the value of the specified Versioned object if non-null or else returns\n * a default value.\n *\n * @param versioned versioned object\n * @param defaultValue default value to return if versioned object is null\n * @param type of the versioned value\n * @return versioned value or default value if versioned object is null\n */\n public static U valueOrElse(Versioned versioned, U defaultValue) {\n return versioned == null ? defaultValue : versioned.value();\n }\n\n /**\n * Returns the value of the specified Versioned object if non-null or else returns null.\n *\n * @param versioned versioned object\n * @param type of the versioned value\n * @return versioned value or null if versioned object is null\n */\n ", "post_mask_code": "\n\n @Override\n public int hashCode() {\n return Objects.hashCode(value, version, creationTime);\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof Versioned)) {\n return false;\n }\n Versioned that = (Versioned) other;\n return Objects.equal(this.value, that.value) && Objects.equal(this.version, that.version) && Objects.equal(this.creationTime, that.creationTime);\n }\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(this).add(\"value\", value instanceof byte[] ? ArraySizeHashPrinter.of((byte[]) value) : value).add(\"version\", version).add(\"creationTime\", new TimestampPrinter(creationTime)).toString();\n }\n}\n"} {"task_id": "Java_2918", "language": "Java", "task_type": "method_signature", "source_file": "java/github/twitter/hbc/hbc-twitter4j/src/main/java/com/twitter/hbc/twitter4j/message/StallWarningMessage.java", "mask_start_position": 644, "mask_end_position": 690, "canonical_solution": "@Override\n public boolean equals(Object o) ", "pre_mask_code": "package com.twitter.hbc.twitter4j.message;\n\n/**\n * Struct representing a stall warning message.\n * See http://example.com\n */\npublic class StallWarningMessage {\n\n private final String code;\n\n private final String message;\n\n private final int percentFull;\n\n public StallWarningMessage(String code, String message, int percentFull) {\n this.code = code;\n this.message = message;\n this.percentFull = percentFull;\n }\n\n public String getCode() {\n return code;\n }\n\n public String getMessage() {\n return message;\n }\n\n public int getPercentFull() {\n return percentFull;\n }\n\n ", "post_mask_code": "{\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n StallWarningMessage that = (StallWarningMessage) o;\n if (percentFull != that.percentFull)\n return false;\n if (code != null ? !code.equals(that.code) : that.code != null)\n return false;\n if (message != null ? !message.equals(that.message) : that.message != null)\n return false;\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = code != null ? code.hashCode() : 0;\n result = 31 * result + (message != null ? message.hashCode() : 0);\n result = 31 * result + percentFull;\n return result;\n }\n\n @Override\n public String toString() {\n return \"StallWarningMessage{\" + \"code='\" + code + '\\'' + \", message='\" + message + '\\'' + \", percentFull=\" + percentFull + '}';\n }\n}\n"} {"task_id": "Java_2919", "language": "Java", "task_type": "method_body", "source_file": "java/github/twitter/hbc/hbc-twitter4j/src/main/java/com/twitter/hbc/twitter4j/message/StallWarningMessage.java", "mask_start_position": 1226, "mask_end_position": 1432, "canonical_solution": "{\n int result = code != null ? code.hashCode() : 0;\n result = 31 * result + (message != null ? message.hashCode() : 0);\n result = 31 * result + percentFull;\n return result;\n }", "pre_mask_code": "package com.twitter.hbc.twitter4j.message;\n\n/**\n * Struct representing a stall warning message.\n * See http://example.com\n */\npublic class StallWarningMessage {\n\n private final String code;\n\n private final String message;\n\n private final int percentFull;\n\n public StallWarningMessage(String code, String message, int percentFull) {\n this.code = code;\n this.message = message;\n this.percentFull = percentFull;\n }\n\n public String getCode() {\n return code;\n }\n\n public String getMessage() {\n return message;\n }\n\n public int getPercentFull() {\n return percentFull;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n StallWarningMessage that = (StallWarningMessage) o;\n if (percentFull != that.percentFull)\n return false;\n if (code != null ? !code.equals(that.code) : that.code != null)\n return false;\n if (message != null ? !message.equals(that.message) : that.message != null)\n return false;\n return true;\n }\n\n @Override\n public int hashCode() ", "post_mask_code": "\n\n @Override\n public String toString() {\n return \"StallWarningMessage{\" + \"code='\" + code + '\\'' + \", message='\" + message + '\\'' + \", percentFull=\" + percentFull + '}';\n }\n}\n"} {"task_id": "Java_2920", "language": "Java", "task_type": "single_line", "source_file": "java/github/twitter/hbc/hbc-twitter4j/src/main/java/com/twitter/hbc/twitter4j/message/StallWarningMessage.java", "mask_start_position": 493, "mask_end_position": 499, "canonical_solution": " code;", "pre_mask_code": "package com.twitter.hbc.twitter4j.message;\n\n/**\n * Struct representing a stall warning message.\n * See http://example.com\n */\npublic class StallWarningMessage {\n\n private final String code;\n\n private final String message;\n\n private final int percentFull;\n\n public StallWarningMessage(String code, String message, int percentFull) {\n this.code = code;\n this.message = message;\n this.percentFull = percentFull;\n }\n\n public String getCode() {\n return", "post_mask_code": "\n }\n\n public String getMessage() {\n return message;\n }\n\n public int getPercentFull() {\n return percentFull;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n StallWarningMessage that = (StallWarningMessage) o;\n if (percentFull != that.percentFull)\n return false;\n if (code != null ? !code.equals(that.code) : that.code != null)\n return false;\n if (message != null ? !message.equals(that.message) : that.message != null)\n return false;\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = code != null ? code.hashCode() : 0;\n result = 31 * result + (message != null ? message.hashCode() : 0);\n result = 31 * result + percentFull;\n return result;\n }\n\n @Override\n public String toString() {\n return \"StallWarningMessage{\" + \"code='\" + code + '\\'' + \", message='\" + message + '\\'' + \", percentFull=\" + percentFull + '}';\n }\n}\n"} {"task_id": "Java_2921", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jtulach/bck2brwsr/rt/vm11/src/main/java/org/apidesign/bck2brwsr/vm11/NestMates.java", "mask_start_position": 435, "mask_end_position": 481, "canonical_solution": "public static String findPrivate(NestMates f) ", "pre_mask_code": "/**\n * Back 2 Browser Bytecode Translator\n */\npackage org.apidesign.bck2brwsr.vm11;\n\npublic class NestMates {\n\n NestMates() {\n }\n\n public static String privateMessage() {\n Subclass bar = new Subclass();\n return Nested.findPrivate(bar);\n }\n\n public static String protectedMessage() {\n Subclass bar = new Subclass();\n return Nested.findProtected(bar);\n }\n\n static class Nested {\n\n ", "post_mask_code": "{\n return f.messagePrivate();\n }\n\n public static String findProtected(NestMates f) {\n return f.messageProtected();\n }\n }\n\n protected String messageProtected() {\n return messagePrivate();\n }\n\n private String messagePrivate() {\n return \"NestMates\";\n }\n}\n\nclass Subclass extends NestMates {\n\n private String messagePrivate() {\n return \"Subclass\";\n }\n\n @Override\n protected String messageProtected() {\n return messagePrivate();\n }\n}\n"} {"task_id": "Java_2922", "language": "Java", "task_type": "method_body", "source_file": "java/github/jtulach/bck2brwsr/rt/vm11/src/main/java/org/apidesign/bck2brwsr/vm11/NestMates.java", "mask_start_position": 767, "mask_end_position": 802, "canonical_solution": "{\n return \"NestMates\";\n }", "pre_mask_code": "/**\n * Back 2 Browser Bytecode Translator\n */\npackage org.apidesign.bck2brwsr.vm11;\n\npublic class NestMates {\n\n NestMates() {\n }\n\n public static String privateMessage() {\n Subclass bar = new Subclass();\n return Nested.findPrivate(bar);\n }\n\n public static String protectedMessage() {\n Subclass bar = new Subclass();\n return Nested.findProtected(bar);\n }\n\n static class Nested {\n\n public static String findPrivate(NestMates f) {\n return f.messagePrivate();\n }\n\n public static String findProtected(NestMates f) {\n return f.messageProtected();\n }\n }\n\n protected String messageProtected() {\n return messagePrivate();\n }\n\n private String messagePrivate() ", "post_mask_code": "\n}\n\nclass Subclass extends NestMates {\n\n private String messagePrivate() {\n return \"Subclass\";\n }\n\n @Override\n protected String messageProtected() {\n return messagePrivate();\n }\n}\n"} {"task_id": "Java_2923", "language": "Java", "task_type": "single_line", "source_file": "java/github/jtulach/bck2brwsr/rt/vm11/src/main/java/org/apidesign/bck2brwsr/vm11/NestMates.java", "mask_start_position": 624, "mask_end_position": 631, "canonical_solution": "cted();", "pre_mask_code": "/**\n * Back 2 Browser Bytecode Translator\n */\npackage org.apidesign.bck2brwsr.vm11;\n\npublic class NestMates {\n\n NestMates() {\n }\n\n public static String privateMessage() {\n Subclass bar = new Subclass();\n return Nested.findPrivate(bar);\n }\n\n public static String protectedMessage() {\n Subclass bar = new Subclass();\n return Nested.findProtected(bar);\n }\n\n static class Nested {\n\n public static String findPrivate(NestMates f) {\n return f.messagePrivate();\n }\n\n public static String findProtected(NestMates f) {\n return f.messageProte", "post_mask_code": "\n }\n }\n\n protected String messageProtected() {\n return messagePrivate();\n }\n\n private String messagePrivate() {\n return \"NestMates\";\n }\n}\n\nclass Subclass extends NestMates {\n\n private String messagePrivate() {\n return \"Subclass\";\n }\n\n @Override\n protected String messageProtected() {\n return messagePrivate();\n }\n}\n"} {"task_id": "Java_2924", "language": "Java", "task_type": "method_signature", "source_file": "java/github/infinum/Retromock/samples/src/main/java/co/infinum/samples/retromock/MultipleResponseRandom.java", "mask_start_position": 962, "mask_end_position": 1020, "canonical_solution": "public static void main(String[] args) throws IOException ", "pre_mask_code": "package co.infinum.samples.retromock;\n\nimport com.squareup.moshi.Json;\nimport java.io.IOException;\nimport co.infinum.retromock.Retromock;\nimport co.infinum.retromock.meta.Mock;\nimport co.infinum.retromock.meta.MockRandom;\nimport co.infinum.retromock.meta.MockResponse;\nimport retrofit2.Call;\nimport retrofit2.Retrofit;\nimport retrofit2.converter.moshi.MoshiConverterFactory;\nimport retrofit2.http.GET;\n\nclass MultipleResponseRandom {\n\n public interface Service {\n\n @Mock\n @MockResponse(body = \"smith.json\")\n @MockResponse(body = \"doe.json\")\n @MockRandom\n @GET(\"/\")\n Call getUser();\n }\n\n static class User {\n\n @Json(name = \"name\")\n String name;\n\n @Json(name = \"surname\")\n String surname;\n\n @Override\n public String toString() {\n return \"User{\" + \"name='\" + name + '\\'' + \", surname='\" + surname + '\\'' + '}';\n }\n }\n\n ", "post_mask_code": "{\n Retrofit retrofit = new Retrofit.Builder().baseUrl(\"https://www.google.com\").addConverterFactory(MoshiConverterFactory.create()).build();\n Retromock retromock = new Retromock.Builder().retrofit(retrofit).defaultBodyFactory(new ResourceBodyFactory()).build();\n MultipleResponseRandom.Service service = retromock.create(MultipleResponseRandom.Service.class);\n System.out.println(service.getUser().execute().body());\n System.out.println(service.getUser().execute().body());\n System.out.println(service.getUser().execute().body());\n System.out.println(service.getUser().execute().body());\n }\n}\n"} {"task_id": "Java_2925", "language": "Java", "task_type": "method_body", "source_file": "java/github/infinum/Retromock/samples/src/main/java/co/infinum/samples/retromock/MultipleResponseRandom.java", "mask_start_position": 847, "mask_end_position": 950, "canonical_solution": "{\n return \"User{\" + \"name='\" + name + '\\'' + \", surname='\" + surname + '\\'' + '}';\n }", "pre_mask_code": "package co.infinum.samples.retromock;\n\nimport com.squareup.moshi.Json;\nimport java.io.IOException;\nimport co.infinum.retromock.Retromock;\nimport co.infinum.retromock.meta.Mock;\nimport co.infinum.retromock.meta.MockRandom;\nimport co.infinum.retromock.meta.MockResponse;\nimport retrofit2.Call;\nimport retrofit2.Retrofit;\nimport retrofit2.converter.moshi.MoshiConverterFactory;\nimport retrofit2.http.GET;\n\nclass MultipleResponseRandom {\n\n public interface Service {\n\n @Mock\n @MockResponse(body = \"smith.json\")\n @MockResponse(body = \"doe.json\")\n @MockRandom\n @GET(\"/\")\n Call getUser();\n }\n\n static class User {\n\n @Json(name = \"name\")\n String name;\n\n @Json(name = \"surname\")\n String surname;\n\n @Override\n public String toString() ", "post_mask_code": "\n }\n\n public static void main(String[] args) throws IOException {\n Retrofit retrofit = new Retrofit.Builder().baseUrl(\"https://www.google.com\").addConverterFactory(MoshiConverterFactory.create()).build();\n Retromock retromock = new Retromock.Builder().retrofit(retrofit).defaultBodyFactory(new ResourceBodyFactory()).build();\n MultipleResponseRandom.Service service = retromock.create(MultipleResponseRandom.Service.class);\n System.out.println(service.getUser().execute().body());\n System.out.println(service.getUser().execute().body());\n System.out.println(service.getUser().execute().body());\n System.out.println(service.getUser().execute().body());\n }\n}\n"} {"task_id": "Java_2926", "language": "Java", "task_type": "single_line", "source_file": "java/github/infinum/Retromock/samples/src/main/java/co/infinum/samples/retromock/MultipleResponseRandom.java", "mask_start_position": 1622, "mask_end_position": 1656, "canonical_solution": "rvice.getUser().execute().body());", "pre_mask_code": "package co.infinum.samples.retromock;\n\nimport com.squareup.moshi.Json;\nimport java.io.IOException;\nimport co.infinum.retromock.Retromock;\nimport co.infinum.retromock.meta.Mock;\nimport co.infinum.retromock.meta.MockRandom;\nimport co.infinum.retromock.meta.MockResponse;\nimport retrofit2.Call;\nimport retrofit2.Retrofit;\nimport retrofit2.converter.moshi.MoshiConverterFactory;\nimport retrofit2.http.GET;\n\nclass MultipleResponseRandom {\n\n public interface Service {\n\n @Mock\n @MockResponse(body = \"smith.json\")\n @MockResponse(body = \"doe.json\")\n @MockRandom\n @GET(\"/\")\n Call getUser();\n }\n\n static class User {\n\n @Json(name = \"name\")\n String name;\n\n @Json(name = \"surname\")\n String surname;\n\n @Override\n public String toString() {\n return \"User{\" + \"name='\" + name + '\\'' + \", surname='\" + surname + '\\'' + '}';\n }\n }\n\n public static void main(String[] args) throws IOException {\n Retrofit retrofit = new Retrofit.Builder().baseUrl(\"https://www.google.com\").addConverterFactory(MoshiConverterFactory.create()).build();\n Retromock retromock = new Retromock.Builder().retrofit(retrofit).defaultBodyFactory(new ResourceBodyFactory()).build();\n MultipleResponseRandom.Service service = retromock.create(MultipleResponseRandom.Service.class);\n System.out.println(service.getUser().execute().body());\n System.out.println(service.getUser().execute().body());\n System.out.println(service.getUser().execute().body());\n System.out.println(se", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2927", "language": "Java", "task_type": "method_signature", "source_file": "java/github/openMF/android-client/mifosng-android/src/main/java/com/mifos/objects/client/ActivatePayload.java", "mask_start_position": 1020, "mask_end_position": 1084, "canonical_solution": "@Override\n public void writeToParcel(Parcel dest, int flags) ", "pre_mask_code": "package com.mifos.objects.client;\n\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Created by Rajan Maurya on 09/02/17.\n */\npublic class ActivatePayload implements Parcelable {\n\n @SerializedName(\"activationDate\")\n String activationDate;\n\n @SerializedName(\"dateFormat\")\n String dateFormat = \"dd MMMM YYYY\";\n\n @SerializedName(\"locale\")\n String locale = \"en\";\n\n public String getActivationDate() {\n return activationDate;\n }\n\n public void setActivationDate(String activationDate) {\n this.activationDate = activationDate;\n }\n\n public String getDateFormat() {\n return dateFormat;\n }\n\n public void setDateFormat(String dateFormat) {\n this.dateFormat = dateFormat;\n }\n\n public String getLocale() {\n return locale;\n }\n\n public void setLocale(String locale) {\n this.locale = locale;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n ", "post_mask_code": "{\n dest.writeString(this.activationDate);\n dest.writeString(this.dateFormat);\n dest.writeString(this.locale);\n }\n\n public ActivatePayload(String activationDate) {\n this.activationDate = activationDate;\n }\n\n public ActivatePayload() {\n }\n\n protected ActivatePayload(Parcel in) {\n this.activationDate = in.readString();\n this.dateFormat = in.readString();\n this.locale = in.readString();\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n\n @Override\n public ActivatePayload createFromParcel(Parcel source) {\n return new ActivatePayload(source);\n }\n\n @Override\n public ActivatePayload[] newArray(int size) {\n return new ActivatePayload[size];\n }\n };\n}\n"} {"task_id": "Java_2928", "language": "Java", "task_type": "method_body", "source_file": "java/github/openMF/android-client/mifosng-android/src/main/java/com/mifos/objects/client/ActivatePayload.java", "mask_start_position": 1084, "mask_end_position": 1220, "canonical_solution": "{\n dest.writeString(this.activationDate);\n dest.writeString(this.dateFormat);\n dest.writeString(this.locale);\n }", "pre_mask_code": "package com.mifos.objects.client;\n\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Created by Rajan Maurya on 09/02/17.\n */\npublic class ActivatePayload implements Parcelable {\n\n @SerializedName(\"activationDate\")\n String activationDate;\n\n @SerializedName(\"dateFormat\")\n String dateFormat = \"dd MMMM YYYY\";\n\n @SerializedName(\"locale\")\n String locale = \"en\";\n\n public String getActivationDate() {\n return activationDate;\n }\n\n public void setActivationDate(String activationDate) {\n this.activationDate = activationDate;\n }\n\n public String getDateFormat() {\n return dateFormat;\n }\n\n public void setDateFormat(String dateFormat) {\n this.dateFormat = dateFormat;\n }\n\n public String getLocale() {\n return locale;\n }\n\n public void setLocale(String locale) {\n this.locale = locale;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) ", "post_mask_code": "\n\n public ActivatePayload(String activationDate) {\n this.activationDate = activationDate;\n }\n\n public ActivatePayload() {\n }\n\n protected ActivatePayload(Parcel in) {\n this.activationDate = in.readString();\n this.dateFormat = in.readString();\n this.locale = in.readString();\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n\n @Override\n public ActivatePayload createFromParcel(Parcel source) {\n return new ActivatePayload(source);\n }\n\n @Override\n public ActivatePayload[] newArray(int size) {\n return new ActivatePayload[size];\n }\n };\n}\n"} {"task_id": "Java_2929", "language": "Java", "task_type": "single_line", "source_file": "java/github/openMF/android-client/mifosng-android/src/main/java/com/mifos/objects/client/ActivatePayload.java", "mask_start_position": 1773, "mask_end_position": 1789, "canonical_solution": "Payload(source);", "pre_mask_code": "package com.mifos.objects.client;\n\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Created by Rajan Maurya on 09/02/17.\n */\npublic class ActivatePayload implements Parcelable {\n\n @SerializedName(\"activationDate\")\n String activationDate;\n\n @SerializedName(\"dateFormat\")\n String dateFormat = \"dd MMMM YYYY\";\n\n @SerializedName(\"locale\")\n String locale = \"en\";\n\n public String getActivationDate() {\n return activationDate;\n }\n\n public void setActivationDate(String activationDate) {\n this.activationDate = activationDate;\n }\n\n public String getDateFormat() {\n return dateFormat;\n }\n\n public void setDateFormat(String dateFormat) {\n this.dateFormat = dateFormat;\n }\n\n public String getLocale() {\n return locale;\n }\n\n public void setLocale(String locale) {\n this.locale = locale;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(this.activationDate);\n dest.writeString(this.dateFormat);\n dest.writeString(this.locale);\n }\n\n public ActivatePayload(String activationDate) {\n this.activationDate = activationDate;\n }\n\n public ActivatePayload() {\n }\n\n protected ActivatePayload(Parcel in) {\n this.activationDate = in.readString();\n this.dateFormat = in.readString();\n this.locale = in.readString();\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n\n @Override\n public ActivatePayload createFromParcel(Parcel source) {\n return new Activate", "post_mask_code": "\n }\n\n @Override\n public ActivatePayload[] newArray(int size) {\n return new ActivatePayload[size];\n }\n };\n}\n"} {"task_id": "Java_2930", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Alex-the-666/Rats/src/main/java/com/github/alexthe666/rats/server/items/ItemRadiusStick.java", "mask_start_position": 1289, "mask_end_position": 1412, "canonical_solution": "@Override\n public void inventoryTick(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) ", "pre_mask_code": "package com.github.alexthe666.rats.server.items;\n\nimport com.github.alexthe666.rats.RatsMod;\nimport com.github.alexthe666.rats.server.entity.EntityRat;\nimport com.github.alexthe666.rats.server.message.MessageCheeseStaffRat;\nimport net.minecraft.client.util.ITooltipFlag;\nimport net.minecraft.entity.Entity;\nimport net.minecraft.entity.player.PlayerEntity;\nimport net.minecraft.item.Item;\nimport net.minecraft.item.ItemStack;\nimport net.minecraft.item.ItemUseContext;\nimport net.minecraft.nbt.CompoundNBT;\nimport net.minecraft.util.ActionResultType;\nimport net.minecraft.util.text.ITextComponent;\nimport net.minecraft.util.text.TextFormatting;\nimport net.minecraft.util.text.TranslationTextComponent;\nimport net.minecraft.world.World;\nimport net.minecraft.world.server.ServerWorld;\nimport net.minecraftforge.api.distmarker.Dist;\nimport net.minecraftforge.api.distmarker.OnlyIn;\nimport javax.annotation.Nullable;\nimport java.util.List;\n\npublic class ItemRadiusStick extends Item {\n\n public ItemRadiusStick() {\n super(new Item.Properties().group(RatsMod.TAB));\n this.setRegistryName(RatsMod.MODID, \"radius_stick\");\n }\n\n @Override\n public void onCreated(ItemStack itemStack, World world, PlayerEntity player) {\n itemStack.setTag(new CompoundNBT());\n }\n\n ", "post_mask_code": "{\n if (stack.getTag() == null) {\n stack.setTag(new CompoundNBT());\n }\n }\n\n public ActionResultType onItemUse(ItemUseContext context) {\n RatsMod.PROXY.setCheeseStaffContext(context.getPos(), context.getFace());\n Entity rat = null;\n ItemStack stack = context.getPlayer().getHeldItem(context.getHand());\n if (stack.getTag() != null && stack.getTag().hasUniqueId(\"RatUUID\")) {\n if (!context.getWorld().isRemote() && context.getWorld() instanceof ServerWorld) {\n rat = ((ServerWorld) context.getWorld()).getEntityByUuid(stack.getTag().getUniqueId(\"RatUUID\"));\n }\n }\n if (!context.getWorld().isRemote) {\n if (rat == null || !(rat instanceof EntityRat)) {\n RatsMod.sendMSGToAll(new MessageCheeseStaffRat(0, true, false, false));\n context.getPlayer().sendStatusMessage(new TranslationTextComponent(\"entity.rats.rat.staff.no_rat\"), true);\n } else {\n RatsMod.sendMSGToAll(new MessageCheeseStaffRat(rat.getEntityId(), false, true, false));\n context.getPlayer().swingArm(context.getHand());\n }\n }\n RatsMod.PROXY.setCheeseStaffContext(context.getPos(), context.getFace());\n return ActionResultType.SUCCESS;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void addInformation(ItemStack stack, @Nullable World worldIn, List tooltip, ITooltipFlag flagIn) {\n tooltip.add(new TranslationTextComponent(\"item.rats.radius_stick.desc0\").func_240699_a_(TextFormatting.GRAY));\n tooltip.add(new TranslationTextComponent(\"item.rats.radius_stick.desc1\").func_240699_a_(TextFormatting.GRAY));\n }\n}\n"} {"task_id": "Java_2931", "language": "Java", "task_type": "method_body", "source_file": "java/github/Alex-the-666/Rats/src/main/java/com/github/alexthe666/rats/server/items/ItemRadiusStick.java", "mask_start_position": 2886, "mask_end_position": 3131, "canonical_solution": "{\n tooltip.add(new TranslationTextComponent(\"item.rats.radius_stick.desc0\").func_240699_a_(TextFormatting.GRAY));\n tooltip.add(new TranslationTextComponent(\"item.rats.radius_stick.desc1\").func_240699_a_(TextFormatting.GRAY));\n }", "pre_mask_code": "package com.github.alexthe666.rats.server.items;\n\nimport com.github.alexthe666.rats.RatsMod;\nimport com.github.alexthe666.rats.server.entity.EntityRat;\nimport com.github.alexthe666.rats.server.message.MessageCheeseStaffRat;\nimport net.minecraft.client.util.ITooltipFlag;\nimport net.minecraft.entity.Entity;\nimport net.minecraft.entity.player.PlayerEntity;\nimport net.minecraft.item.Item;\nimport net.minecraft.item.ItemStack;\nimport net.minecraft.item.ItemUseContext;\nimport net.minecraft.nbt.CompoundNBT;\nimport net.minecraft.util.ActionResultType;\nimport net.minecraft.util.text.ITextComponent;\nimport net.minecraft.util.text.TextFormatting;\nimport net.minecraft.util.text.TranslationTextComponent;\nimport net.minecraft.world.World;\nimport net.minecraft.world.server.ServerWorld;\nimport net.minecraftforge.api.distmarker.Dist;\nimport net.minecraftforge.api.distmarker.OnlyIn;\nimport javax.annotation.Nullable;\nimport java.util.List;\n\npublic class ItemRadiusStick extends Item {\n\n public ItemRadiusStick() {\n super(new Item.Properties().group(RatsMod.TAB));\n this.setRegistryName(RatsMod.MODID, \"radius_stick\");\n }\n\n @Override\n public void onCreated(ItemStack itemStack, World world, PlayerEntity player) {\n itemStack.setTag(new CompoundNBT());\n }\n\n @Override\n public void inventoryTick(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) {\n if (stack.getTag() == null) {\n stack.setTag(new CompoundNBT());\n }\n }\n\n public ActionResultType onItemUse(ItemUseContext context) {\n RatsMod.PROXY.setCheeseStaffContext(context.getPos(), context.getFace());\n Entity rat = null;\n ItemStack stack = context.getPlayer().getHeldItem(context.getHand());\n if (stack.getTag() != null && stack.getTag().hasUniqueId(\"RatUUID\")) {\n if (!context.getWorld().isRemote() && context.getWorld() instanceof ServerWorld) {\n rat = ((ServerWorld) context.getWorld()).getEntityByUuid(stack.getTag().getUniqueId(\"RatUUID\"));\n }\n }\n if (!context.getWorld().isRemote) {\n if (rat == null || !(rat instanceof EntityRat)) {\n RatsMod.sendMSGToAll(new MessageCheeseStaffRat(0, true, false, false));\n context.getPlayer().sendStatusMessage(new TranslationTextComponent(\"entity.rats.rat.staff.no_rat\"), true);\n } else {\n RatsMod.sendMSGToAll(new MessageCheeseStaffRat(rat.getEntityId(), false, true, false));\n context.getPlayer().swingArm(context.getHand());\n }\n }\n RatsMod.PROXY.setCheeseStaffContext(context.getPos(), context.getFace());\n return ActionResultType.SUCCESS;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void addInformation(ItemStack stack, @Nullable World worldIn, List tooltip, ITooltipFlag flagIn) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2932", "language": "Java", "task_type": "single_line", "source_file": "java/github/Alex-the-666/Rats/src/main/java/com/github/alexthe666/rats/server/items/ItemRadiusStick.java", "mask_start_position": 1680, "mask_end_position": 1686, "canonical_solution": " null;", "pre_mask_code": "package com.github.alexthe666.rats.server.items;\n\nimport com.github.alexthe666.rats.RatsMod;\nimport com.github.alexthe666.rats.server.entity.EntityRat;\nimport com.github.alexthe666.rats.server.message.MessageCheeseStaffRat;\nimport net.minecraft.client.util.ITooltipFlag;\nimport net.minecraft.entity.Entity;\nimport net.minecraft.entity.player.PlayerEntity;\nimport net.minecraft.item.Item;\nimport net.minecraft.item.ItemStack;\nimport net.minecraft.item.ItemUseContext;\nimport net.minecraft.nbt.CompoundNBT;\nimport net.minecraft.util.ActionResultType;\nimport net.minecraft.util.text.ITextComponent;\nimport net.minecraft.util.text.TextFormatting;\nimport net.minecraft.util.text.TranslationTextComponent;\nimport net.minecraft.world.World;\nimport net.minecraft.world.server.ServerWorld;\nimport net.minecraftforge.api.distmarker.Dist;\nimport net.minecraftforge.api.distmarker.OnlyIn;\nimport javax.annotation.Nullable;\nimport java.util.List;\n\npublic class ItemRadiusStick extends Item {\n\n public ItemRadiusStick() {\n super(new Item.Properties().group(RatsMod.TAB));\n this.setRegistryName(RatsMod.MODID, \"radius_stick\");\n }\n\n @Override\n public void onCreated(ItemStack itemStack, World world, PlayerEntity player) {\n itemStack.setTag(new CompoundNBT());\n }\n\n @Override\n public void inventoryTick(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) {\n if (stack.getTag() == null) {\n stack.setTag(new CompoundNBT());\n }\n }\n\n public ActionResultType onItemUse(ItemUseContext context) {\n RatsMod.PROXY.setCheeseStaffContext(context.getPos(), context.getFace());\n Entity rat =", "post_mask_code": "\n ItemStack stack = context.getPlayer().getHeldItem(context.getHand());\n if (stack.getTag() != null && stack.getTag().hasUniqueId(\"RatUUID\")) {\n if (!context.getWorld().isRemote() && context.getWorld() instanceof ServerWorld) {\n rat = ((ServerWorld) context.getWorld()).getEntityByUuid(stack.getTag().getUniqueId(\"RatUUID\"));\n }\n }\n if (!context.getWorld().isRemote) {\n if (rat == null || !(rat instanceof EntityRat)) {\n RatsMod.sendMSGToAll(new MessageCheeseStaffRat(0, true, false, false));\n context.getPlayer().sendStatusMessage(new TranslationTextComponent(\"entity.rats.rat.staff.no_rat\"), true);\n } else {\n RatsMod.sendMSGToAll(new MessageCheeseStaffRat(rat.getEntityId(), false, true, false));\n context.getPlayer().swingArm(context.getHand());\n }\n }\n RatsMod.PROXY.setCheeseStaffContext(context.getPos(), context.getFace());\n return ActionResultType.SUCCESS;\n }\n\n @OnlyIn(Dist.CLIENT)\n public void addInformation(ItemStack stack, @Nullable World worldIn, List tooltip, ITooltipFlag flagIn) {\n tooltip.add(new TranslationTextComponent(\"item.rats.radius_stick.desc0\").func_240699_a_(TextFormatting.GRAY));\n tooltip.add(new TranslationTextComponent(\"item.rats.radius_stick.desc1\").func_240699_a_(TextFormatting.GRAY));\n }\n}\n"} {"task_id": "Java_2933", "language": "Java", "task_type": "method_signature", "source_file": "java/github/alibaba/mdrill/trunk/adhoc-solr/src/main/java/org/apache/solr/analysis/BulgarianStemFilterFactory.java", "mask_start_position": 667, "mask_end_position": 712, "canonical_solution": "public TokenStream create(TokenStream input) ", "pre_mask_code": "package org.apache.solr.analysis;\n\nimport org.apache.lucene.analysis.TokenStream;\nimport org.apache.lucene.analysis.bg.BulgarianStemFilter;\n\n/**\n * Factory for {@link BulgarianStemFilter}.\n *

\n * <fieldType name=\"text_bgstem\" class=\"solr.TextField\" positionIncrementGap=\"100\">\n *   <analyzer>\n *     <tokenizer class=\"solr.StandardTokenizerFactory\"/>\n *     <filter class=\"solr.LowerCaseFilterFactory\"/>\n *     <filter class=\"solr.BulgarianStemFilterFactory\"/>\n *   </analyzer>\n * </fieldType>
\n * @version $Id$\n */\npublic class BulgarianStemFilterFactory extends BaseTokenFilterFactory {\n\n ", "post_mask_code": "{\n return new BulgarianStemFilter(input);\n }\n}\n"} {"task_id": "Java_2934", "language": "Java", "task_type": "method_body", "source_file": "java/github/alibaba/mdrill/trunk/adhoc-solr/src/main/java/org/apache/solr/analysis/BulgarianStemFilterFactory.java", "mask_start_position": 712, "mask_end_position": 766, "canonical_solution": "{\n return new BulgarianStemFilter(input);\n }", "pre_mask_code": "package org.apache.solr.analysis;\n\nimport org.apache.lucene.analysis.TokenStream;\nimport org.apache.lucene.analysis.bg.BulgarianStemFilter;\n\n/**\n * Factory for {@link BulgarianStemFilter}.\n *
\n * <fieldType name=\"text_bgstem\" class=\"solr.TextField\" positionIncrementGap=\"100\">\n *   <analyzer>\n *     <tokenizer class=\"solr.StandardTokenizerFactory\"/>\n *     <filter class=\"solr.LowerCaseFilterFactory\"/>\n *     <filter class=\"solr.BulgarianStemFilterFactory\"/>\n *   </analyzer>\n * </fieldType>
\n * @version $Id$\n */\npublic class BulgarianStemFilterFactory extends BaseTokenFilterFactory {\n\n public TokenStream create(TokenStream input) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2935", "language": "Java", "task_type": "single_line", "source_file": "java/github/alibaba/mdrill/trunk/adhoc-solr/src/main/java/org/apache/solr/analysis/BulgarianStemFilterFactory.java", "mask_start_position": 731, "mask_end_position": 760, "canonical_solution": "w BulgarianStemFilter(input);", "pre_mask_code": "package org.apache.solr.analysis;\n\nimport org.apache.lucene.analysis.TokenStream;\nimport org.apache.lucene.analysis.bg.BulgarianStemFilter;\n\n/**\n * Factory for {@link BulgarianStemFilter}.\n *
\n * <fieldType name=\"text_bgstem\" class=\"solr.TextField\" positionIncrementGap=\"100\">\n *   <analyzer>\n *     <tokenizer class=\"solr.StandardTokenizerFactory\"/>\n *     <filter class=\"solr.LowerCaseFilterFactory\"/>\n *     <filter class=\"solr.BulgarianStemFilterFactory\"/>\n *   </analyzer>\n * </fieldType>
\n * @version $Id$\n */\npublic class BulgarianStemFilterFactory extends BaseTokenFilterFactory {\n\n public TokenStream create(TokenStream input) {\n return ne", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_2936", "language": "Java", "task_type": "method_signature", "source_file": "java/github/OpenRock/OpenDJ/opendj-server-legacy/src/main/java/org/opends/server/replication/plugin/HistoricalAttributeValue.java", "mask_start_position": 4309, "mask_end_position": 4350, "canonical_solution": "private AttributeType getAttributeType() ", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport static org.opends.server.replication.plugin.HistAttrModificationKey.*;\nimport static org.opends.server.util.StaticUtils.*;\nimport java.util.Collections;\nimport java.util.LinkedHashSet;\nimport java.util.Set;\nimport org.forgerock.opendj.ldap.ByteString;\nimport org.forgerock.opendj.ldap.ModificationType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.replication.common.CSN;\nimport org.opends.server.types.Attribute;\nimport org.opends.server.types.AttributeBuilder;\nimport org.opends.server.types.AttributeDescription;\nimport org.opends.server.types.AttributeType;\nimport org.opends.server.types.Modification;\n\n/**\n * This class stores an internal usable representation of the value of\n * the historical related to an entry.\n * It encodes/decodes from the String form stored in the DB attribute\n * from/to the internal usable form.\n *\n * an historical attribute value looks like :\n * description:00000108b3a65541000000000001:add:added_value\n * or\n * description:00000108b3a6cbb8000000000001:del:deleted_value\n * or\n * description:00000108b3a6cbb8000000000001:repl:new_value\n * or\n * description:00000108b3a6cbb8000000000001:attrDel\n * or\n * description:00000108b3a65541000000000001:add\n * or\n * dn:00000108b3a65541000000000001:add (ADD operation)\n * or\n * dn:00000108b3a65541000000000001:moddn (MODIFYDN operation)\n *\n * so after split\n * token[0] will contain the attribute name\n * token[1] will contain the CSN\n * token[2] will contain the type of historical information\n * token[3] will contain the attribute value\n *\n * options are stored with the attribute names using; as a separator\n * example :\n * description;FR;France:00000108b3a65541000000000001:add:added_value\n */\nclass HistoricalAttributeValue {\n\n private final AttributeDescription attrDesc;\n\n /**\n * The lowercase attribute string representation.\n */\n private final String attrString;\n\n private final ByteString attributeValue;\n\n private final CSN csn;\n\n private final HistAttrModificationKey histKey;\n\n private final String stringValue;\n\n /**\n * This flag indicates that this value was generated to store the last date\n * when the entry was renamed.\n */\n private boolean isModDN;\n\n /**\n * Create a new object from the String encoded form.\n *\n * @param strVal The String encoded form of historical attribute value.\n * @see EntryHistorical#encodeAndPurge() encoding in EntryHistorical\n */\n HistoricalAttributeValue(String strVal) {\n String[] token = strVal.split(\":\", 4);\n Set options;\n if (token[0].contains(\";\")) {\n options = new LinkedHashSet<>();\n String[] optionsToken = token[0].split(\";\");\n int index = 1;\n while (index < optionsToken.length) {\n options.add(optionsToken[index]);\n index++;\n }\n attrString = toLowerCase(optionsToken[0]);\n } else {\n options = Collections.emptySet();\n attrString = toLowerCase(token[0]);\n }\n AttributeType attrType;\n if (attrString.compareTo(\"dn\") != 0) {\n // This HistVal was used to store the date when some\n // modifications were done to the entries.\n attrType = DirectoryServer.getAttributeTypeOrDefault(attrString);\n } else {\n // This HistVal is used to store the date when the entry\n // was added to the directory or when it was last renamed.\n attrType = null;\n if (token.length >= 3 && token[2].compareTo(\"moddn\") == 0) {\n isModDN = true;\n }\n }\n this.attrDesc = attrType != null ? AttributeDescription.create(attrType, options) : null;\n csn = new CSN(token[1]);\n histKey = HistAttrModificationKey.decodeKey(token[2]);\n if (histKey != ATTRDEL) {\n if (token.length == 4) {\n stringValue = token[3];\n attributeValue = ByteString.valueOfUtf8(stringValue);\n } else {\n stringValue = null;\n attributeValue = null;\n }\n } else {\n stringValue = null;\n attributeValue = null;\n }\n }\n\n ", "post_mask_code": "{\n return attrDesc != null ? attrDesc.getAttributeType() : null;\n }\n\n private Set getOptions() {\n return attrDesc != null ? attrDesc.getOptions() : Collections.emptySet();\n }\n\n /**\n * Get the String form of the attribute type.\n *\n * @return Returns the String form of the attribute type.\n */\n public String getAttrString() {\n return attrString;\n }\n\n /**\n * Get the attribute description of this HistVal.\n *\n * @return Returns the attribute description of this HistVal.\n * Can return {@code null} if the HistVal was generated for a ADD Operation.\n */\n AttributeDescription getAttributeDescription() {\n return attrDesc;\n }\n\n /**\n * Get the CSN of this HistVal.\n * @return Returns the CSN of this HistVal.\n */\n public CSN getCSN() {\n return csn;\n }\n\n /**\n * Get the HistKey.\n * @return Returns the histKey.\n */\n public HistAttrModificationKey getHistKey() {\n return histKey;\n }\n\n /**\n * Get the Attribute Value.\n * @return The Attribute Value.\n */\n public ByteString getAttributeValue() {\n return attributeValue;\n }\n\n /**\n * Generate a Modification equivalent to this value of the historical\n * attribute.\n *\n * @return A modification equivalent to this value of the historical\n * attribute.\n */\n public Modification generateMod() {\n AttributeBuilder builder = new AttributeBuilder(getAttributeType(), attrString);\n builder.setOptions(getOptions());\n if (histKey != ATTRDEL) {\n builder.add(attributeValue);\n }\n Attribute attr = builder.toAttribute();\n switch(histKey) {\n case ADD:\n return new Modification(ModificationType.ADD, attr);\n case DEL:\n case ATTRDEL:\n return new Modification(ModificationType.DELETE, attr);\n case REPL:\n return new Modification(ModificationType.REPLACE, attr);\n default:\n return null;\n }\n }\n\n /**\n * Indicates if this value of the historical attribute was generated\n * for a ADD operation.\n *\n * @return a boolean indicating if this was generated for a ADD operation.\n */\n public boolean isADDOperation() {\n return getAttributeType() == null && !isModDN;\n }\n\n /**\n * Indicates if this value of the historical attribute was generated\n * for a MODDN operation.\n *\n * @return a boolean indicating if this was generated for a ADDMODDN operation.\n */\n public boolean isMODDNOperation() {\n return getAttributeType() == null && isModDN;\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder();\n sb.append(attrString);\n for (String option : getOptions()) {\n sb.append(\";\").append(option);\n }\n sb.append(\":\").append(csn).append(\":\").append(getModificationType());\n if (stringValue != null) {\n sb.append(\":\").append(stringValue);\n }\n return sb.toString();\n }\n\n private String getModificationType() {\n if (isModDN) {\n return \"moddn\";\n } else if (histKey != null) {\n return histKey.toString();\n }\n return \"TODO\";\n }\n}\n"} {"task_id": "Java_2937", "language": "Java", "task_type": "method_body", "source_file": "java/github/OpenRock/OpenDJ/opendj-server-legacy/src/main/java/org/opends/server/replication/plugin/HistoricalAttributeValue.java", "mask_start_position": 4350, "mask_end_position": 4427, "canonical_solution": "{\n return attrDesc != null ? attrDesc.getAttributeType() : null;\n }", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport static org.opends.server.replication.plugin.HistAttrModificationKey.*;\nimport static org.opends.server.util.StaticUtils.*;\nimport java.util.Collections;\nimport java.util.LinkedHashSet;\nimport java.util.Set;\nimport org.forgerock.opendj.ldap.ByteString;\nimport org.forgerock.opendj.ldap.ModificationType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.replication.common.CSN;\nimport org.opends.server.types.Attribute;\nimport org.opends.server.types.AttributeBuilder;\nimport org.opends.server.types.AttributeDescription;\nimport org.opends.server.types.AttributeType;\nimport org.opends.server.types.Modification;\n\n/**\n * This class stores an internal usable representation of the value of\n * the historical related to an entry.\n * It encodes/decodes from the String form stored in the DB attribute\n * from/to the internal usable form.\n *\n * an historical attribute value looks like :\n * description:00000108b3a65541000000000001:add:added_value\n * or\n * description:00000108b3a6cbb8000000000001:del:deleted_value\n * or\n * description:00000108b3a6cbb8000000000001:repl:new_value\n * or\n * description:00000108b3a6cbb8000000000001:attrDel\n * or\n * description:00000108b3a65541000000000001:add\n * or\n * dn:00000108b3a65541000000000001:add (ADD operation)\n * or\n * dn:00000108b3a65541000000000001:moddn (MODIFYDN operation)\n *\n * so after split\n * token[0] will contain the attribute name\n * token[1] will contain the CSN\n * token[2] will contain the type of historical information\n * token[3] will contain the attribute value\n *\n * options are stored with the attribute names using; as a separator\n * example :\n * description;FR;France:00000108b3a65541000000000001:add:added_value\n */\nclass HistoricalAttributeValue {\n\n private final AttributeDescription attrDesc;\n\n /**\n * The lowercase attribute string representation.\n */\n private final String attrString;\n\n private final ByteString attributeValue;\n\n private final CSN csn;\n\n private final HistAttrModificationKey histKey;\n\n private final String stringValue;\n\n /**\n * This flag indicates that this value was generated to store the last date\n * when the entry was renamed.\n */\n private boolean isModDN;\n\n /**\n * Create a new object from the String encoded form.\n *\n * @param strVal The String encoded form of historical attribute value.\n * @see EntryHistorical#encodeAndPurge() encoding in EntryHistorical\n */\n HistoricalAttributeValue(String strVal) {\n String[] token = strVal.split(\":\", 4);\n Set options;\n if (token[0].contains(\";\")) {\n options = new LinkedHashSet<>();\n String[] optionsToken = token[0].split(\";\");\n int index = 1;\n while (index < optionsToken.length) {\n options.add(optionsToken[index]);\n index++;\n }\n attrString = toLowerCase(optionsToken[0]);\n } else {\n options = Collections.emptySet();\n attrString = toLowerCase(token[0]);\n }\n AttributeType attrType;\n if (attrString.compareTo(\"dn\") != 0) {\n // This HistVal was used to store the date when some\n // modifications were done to the entries.\n attrType = DirectoryServer.getAttributeTypeOrDefault(attrString);\n } else {\n // This HistVal is used to store the date when the entry\n // was added to the directory or when it was last renamed.\n attrType = null;\n if (token.length >= 3 && token[2].compareTo(\"moddn\") == 0) {\n isModDN = true;\n }\n }\n this.attrDesc = attrType != null ? AttributeDescription.create(attrType, options) : null;\n csn = new CSN(token[1]);\n histKey = HistAttrModificationKey.decodeKey(token[2]);\n if (histKey != ATTRDEL) {\n if (token.length == 4) {\n stringValue = token[3];\n attributeValue = ByteString.valueOfUtf8(stringValue);\n } else {\n stringValue = null;\n attributeValue = null;\n }\n } else {\n stringValue = null;\n attributeValue = null;\n }\n }\n\n private AttributeType getAttributeType() ", "post_mask_code": "\n\n private Set getOptions() {\n return attrDesc != null ? attrDesc.getOptions() : Collections.emptySet();\n }\n\n /**\n * Get the String form of the attribute type.\n *\n * @return Returns the String form of the attribute type.\n */\n public String getAttrString() {\n return attrString;\n }\n\n /**\n * Get the attribute description of this HistVal.\n *\n * @return Returns the attribute description of this HistVal.\n * Can return {@code null} if the HistVal was generated for a ADD Operation.\n */\n AttributeDescription getAttributeDescription() {\n return attrDesc;\n }\n\n /**\n * Get the CSN of this HistVal.\n * @return Returns the CSN of this HistVal.\n */\n public CSN getCSN() {\n return csn;\n }\n\n /**\n * Get the HistKey.\n * @return Returns the histKey.\n */\n public HistAttrModificationKey getHistKey() {\n return histKey;\n }\n\n /**\n * Get the Attribute Value.\n * @return The Attribute Value.\n */\n public ByteString getAttributeValue() {\n return attributeValue;\n }\n\n /**\n * Generate a Modification equivalent to this value of the historical\n * attribute.\n *\n * @return A modification equivalent to this value of the historical\n * attribute.\n */\n public Modification generateMod() {\n AttributeBuilder builder = new AttributeBuilder(getAttributeType(), attrString);\n builder.setOptions(getOptions());\n if (histKey != ATTRDEL) {\n builder.add(attributeValue);\n }\n Attribute attr = builder.toAttribute();\n switch(histKey) {\n case ADD:\n return new Modification(ModificationType.ADD, attr);\n case DEL:\n case ATTRDEL:\n return new Modification(ModificationType.DELETE, attr);\n case REPL:\n return new Modification(ModificationType.REPLACE, attr);\n default:\n return null;\n }\n }\n\n /**\n * Indicates if this value of the historical attribute was generated\n * for a ADD operation.\n *\n * @return a boolean indicating if this was generated for a ADD operation.\n */\n public boolean isADDOperation() {\n return getAttributeType() == null && !isModDN;\n }\n\n /**\n * Indicates if this value of the historical attribute was generated\n * for a MODDN operation.\n *\n * @return a boolean indicating if this was generated for a ADDMODDN operation.\n */\n public boolean isMODDNOperation() {\n return getAttributeType() == null && isModDN;\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder();\n sb.append(attrString);\n for (String option : getOptions()) {\n sb.append(\";\").append(option);\n }\n sb.append(\":\").append(csn).append(\":\").append(getModificationType());\n if (stringValue != null) {\n sb.append(\":\").append(stringValue);\n }\n return sb.toString();\n }\n\n private String getModificationType() {\n if (isModDN) {\n return \"moddn\";\n } else if (histKey != null) {\n return histKey.toString();\n }\n return \"TODO\";\n }\n}\n"} {"task_id": "Java_2938", "language": "Java", "task_type": "single_line", "source_file": "java/github/OpenRock/OpenDJ/opendj-server-legacy/src/main/java/org/opends/server/replication/plugin/HistoricalAttributeValue.java", "mask_start_position": 5381, "mask_end_position": 5389, "canonical_solution": "histKey;", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport static org.opends.server.replication.plugin.HistAttrModificationKey.*;\nimport static org.opends.server.util.StaticUtils.*;\nimport java.util.Collections;\nimport java.util.LinkedHashSet;\nimport java.util.Set;\nimport org.forgerock.opendj.ldap.ByteString;\nimport org.forgerock.opendj.ldap.ModificationType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.replication.common.CSN;\nimport org.opends.server.types.Attribute;\nimport org.opends.server.types.AttributeBuilder;\nimport org.opends.server.types.AttributeDescription;\nimport org.opends.server.types.AttributeType;\nimport org.opends.server.types.Modification;\n\n/**\n * This class stores an internal usable representation of the value of\n * the historical related to an entry.\n * It encodes/decodes from the String form stored in the DB attribute\n * from/to the internal usable form.\n *\n * an historical attribute value looks like :\n * description:00000108b3a65541000000000001:add:added_value\n * or\n * description:00000108b3a6cbb8000000000001:del:deleted_value\n * or\n * description:00000108b3a6cbb8000000000001:repl:new_value\n * or\n * description:00000108b3a6cbb8000000000001:attrDel\n * or\n * description:00000108b3a65541000000000001:add\n * or\n * dn:00000108b3a65541000000000001:add (ADD operation)\n * or\n * dn:00000108b3a65541000000000001:moddn (MODIFYDN operation)\n *\n * so after split\n * token[0] will contain the attribute name\n * token[1] will contain the CSN\n * token[2] will contain the type of historical information\n * token[3] will contain the attribute value\n *\n * options are stored with the attribute names using; as a separator\n * example :\n * description;FR;France:00000108b3a65541000000000001:add:added_value\n */\nclass HistoricalAttributeValue {\n\n private final AttributeDescription attrDesc;\n\n /**\n * The lowercase attribute string representation.\n */\n private final String attrString;\n\n private final ByteString attributeValue;\n\n private final CSN csn;\n\n private final HistAttrModificationKey histKey;\n\n private final String stringValue;\n\n /**\n * This flag indicates that this value was generated to store the last date\n * when the entry was renamed.\n */\n private boolean isModDN;\n\n /**\n * Create a new object from the String encoded form.\n *\n * @param strVal The String encoded form of historical attribute value.\n * @see EntryHistorical#encodeAndPurge() encoding in EntryHistorical\n */\n HistoricalAttributeValue(String strVal) {\n String[] token = strVal.split(\":\", 4);\n Set options;\n if (token[0].contains(\";\")) {\n options = new LinkedHashSet<>();\n String[] optionsToken = token[0].split(\";\");\n int index = 1;\n while (index < optionsToken.length) {\n options.add(optionsToken[index]);\n index++;\n }\n attrString = toLowerCase(optionsToken[0]);\n } else {\n options = Collections.emptySet();\n attrString = toLowerCase(token[0]);\n }\n AttributeType attrType;\n if (attrString.compareTo(\"dn\") != 0) {\n // This HistVal was used to store the date when some\n // modifications were done to the entries.\n attrType = DirectoryServer.getAttributeTypeOrDefault(attrString);\n } else {\n // This HistVal is used to store the date when the entry\n // was added to the directory or when it was last renamed.\n attrType = null;\n if (token.length >= 3 && token[2].compareTo(\"moddn\") == 0) {\n isModDN = true;\n }\n }\n this.attrDesc = attrType != null ? AttributeDescription.create(attrType, options) : null;\n csn = new CSN(token[1]);\n histKey = HistAttrModificationKey.decodeKey(token[2]);\n if (histKey != ATTRDEL) {\n if (token.length == 4) {\n stringValue = token[3];\n attributeValue = ByteString.valueOfUtf8(stringValue);\n } else {\n stringValue = null;\n attributeValue = null;\n }\n } else {\n stringValue = null;\n attributeValue = null;\n }\n }\n\n private AttributeType getAttributeType() {\n return attrDesc != null ? attrDesc.getAttributeType() : null;\n }\n\n private Set getOptions() {\n return attrDesc != null ? attrDesc.getOptions() : Collections.emptySet();\n }\n\n /**\n * Get the String form of the attribute type.\n *\n * @return Returns the String form of the attribute type.\n */\n public String getAttrString() {\n return attrString;\n }\n\n /**\n * Get the attribute description of this HistVal.\n *\n * @return Returns the attribute description of this HistVal.\n * Can return {@code null} if the HistVal was generated for a ADD Operation.\n */\n AttributeDescription getAttributeDescription() {\n return attrDesc;\n }\n\n /**\n * Get the CSN of this HistVal.\n * @return Returns the CSN of this HistVal.\n */\n public CSN getCSN() {\n return csn;\n }\n\n /**\n * Get the HistKey.\n * @return Returns the histKey.\n */\n public HistAttrModificationKey getHistKey() {\n return ", "post_mask_code": "\n }\n\n /**\n * Get the Attribute Value.\n * @return The Attribute Value.\n */\n public ByteString getAttributeValue() {\n return attributeValue;\n }\n\n /**\n * Generate a Modification equivalent to this value of the historical\n * attribute.\n *\n * @return A modification equivalent to this value of the historical\n * attribute.\n */\n public Modification generateMod() {\n AttributeBuilder builder = new AttributeBuilder(getAttributeType(), attrString);\n builder.setOptions(getOptions());\n if (histKey != ATTRDEL) {\n builder.add(attributeValue);\n }\n Attribute attr = builder.toAttribute();\n switch(histKey) {\n case ADD:\n return new Modification(ModificationType.ADD, attr);\n case DEL:\n case ATTRDEL:\n return new Modification(ModificationType.DELETE, attr);\n case REPL:\n return new Modification(ModificationType.REPLACE, attr);\n default:\n return null;\n }\n }\n\n /**\n * Indicates if this value of the historical attribute was generated\n * for a ADD operation.\n *\n * @return a boolean indicating if this was generated for a ADD operation.\n */\n public boolean isADDOperation() {\n return getAttributeType() == null && !isModDN;\n }\n\n /**\n * Indicates if this value of the historical attribute was generated\n * for a MODDN operation.\n *\n * @return a boolean indicating if this was generated for a ADDMODDN operation.\n */\n public boolean isMODDNOperation() {\n return getAttributeType() == null && isModDN;\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder();\n sb.append(attrString);\n for (String option : getOptions()) {\n sb.append(\";\").append(option);\n }\n sb.append(\":\").append(csn).append(\":\").append(getModificationType());\n if (stringValue != null) {\n sb.append(\":\").append(stringValue);\n }\n return sb.toString();\n }\n\n private String getModificationType() {\n if (isModDN) {\n return \"moddn\";\n } else if (histKey != null) {\n return histKey.toString();\n }\n return \"TODO\";\n }\n}\n"} {"task_id": "Java_2939", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/OpenRock/OpenDJ/opendj-server-legacy/src/main/java/org/opends/server/replication/plugin/HistoricalAttributeValue.java", "mask_start_position": 4704, "mask_end_position": 4768, "canonical_solution": "public String getAttrString() {\n return attrString;\n }", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport static org.opends.server.replication.plugin.HistAttrModificationKey.*;\nimport static org.opends.server.util.StaticUtils.*;\nimport java.util.Collections;\nimport java.util.LinkedHashSet;\nimport java.util.Set;\nimport org.forgerock.opendj.ldap.ByteString;\nimport org.forgerock.opendj.ldap.ModificationType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.replication.common.CSN;\nimport org.opends.server.types.Attribute;\nimport org.opends.server.types.AttributeBuilder;\nimport org.opends.server.types.AttributeDescription;\nimport org.opends.server.types.AttributeType;\nimport org.opends.server.types.Modification;\n\n/**\n * This class stores an internal usable representation of the value of\n * the historical related to an entry.\n * It encodes/decodes from the String form stored in the DB attribute\n * from/to the internal usable form.\n *\n * an historical attribute value looks like :\n * description:00000108b3a65541000000000001:add:added_value\n * or\n * description:00000108b3a6cbb8000000000001:del:deleted_value\n * or\n * description:00000108b3a6cbb8000000000001:repl:new_value\n * or\n * description:00000108b3a6cbb8000000000001:attrDel\n * or\n * description:00000108b3a65541000000000001:add\n * or\n * dn:00000108b3a65541000000000001:add (ADD operation)\n * or\n * dn:00000108b3a65541000000000001:moddn (MODIFYDN operation)\n *\n * so after split\n * token[0] will contain the attribute name\n * token[1] will contain the CSN\n * token[2] will contain the type of historical information\n * token[3] will contain the attribute value\n *\n * options are stored with the attribute names using; as a separator\n * example :\n * description;FR;France:00000108b3a65541000000000001:add:added_value\n */\nclass HistoricalAttributeValue {\n\n private final AttributeDescription attrDesc;\n\n /**\n * The lowercase attribute string representation.\n */\n private final String attrString;\n\n private final ByteString attributeValue;\n\n private final CSN csn;\n\n private final HistAttrModificationKey histKey;\n\n private final String stringValue;\n\n /**\n * This flag indicates that this value was generated to store the last date\n * when the entry was renamed.\n */\n private boolean isModDN;\n\n /**\n * Create a new object from the String encoded form.\n *\n * @param strVal The String encoded form of historical attribute value.\n * @see EntryHistorical#encodeAndPurge() encoding in EntryHistorical\n */\n HistoricalAttributeValue(String strVal) {\n String[] token = strVal.split(\":\", 4);\n Set options;\n if (token[0].contains(\";\")) {\n options = new LinkedHashSet<>();\n String[] optionsToken = token[0].split(\";\");\n int index = 1;\n while (index < optionsToken.length) {\n options.add(optionsToken[index]);\n index++;\n }\n attrString = toLowerCase(optionsToken[0]);\n } else {\n options = Collections.emptySet();\n attrString = toLowerCase(token[0]);\n }\n AttributeType attrType;\n if (attrString.compareTo(\"dn\") != 0) {\n // This HistVal was used to store the date when some\n // modifications were done to the entries.\n attrType = DirectoryServer.getAttributeTypeOrDefault(attrString);\n } else {\n // This HistVal is used to store the date when the entry\n // was added to the directory or when it was last renamed.\n attrType = null;\n if (token.length >= 3 && token[2].compareTo(\"moddn\") == 0) {\n isModDN = true;\n }\n }\n this.attrDesc = attrType != null ? AttributeDescription.create(attrType, options) : null;\n csn = new CSN(token[1]);\n histKey = HistAttrModificationKey.decodeKey(token[2]);\n if (histKey != ATTRDEL) {\n if (token.length == 4) {\n stringValue = token[3];\n attributeValue = ByteString.valueOfUtf8(stringValue);\n } else {\n stringValue = null;\n attributeValue = null;\n }\n } else {\n stringValue = null;\n attributeValue = null;\n }\n }\n\n private AttributeType getAttributeType() {\n return attrDesc != null ? attrDesc.getAttributeType() : null;\n }\n\n private Set getOptions() {\n return attrDesc != null ? attrDesc.getOptions() : Collections.emptySet();\n }\n\n /**\n * Get the String form of the attribute type.\n *\n * @return Returns the String form of the attribute type.\n */\n ", "post_mask_code": "\n\n /**\n * Get the attribute description of this HistVal.\n *\n * @return Returns the attribute description of this HistVal.\n * Can return {@code null} if the HistVal was generated for a ADD Operation.\n */\n AttributeDescription getAttributeDescription() {\n return attrDesc;\n }\n\n /**\n * Get the CSN of this HistVal.\n * @return Returns the CSN of this HistVal.\n */\n public CSN getCSN() {\n return csn;\n }\n\n /**\n * Get the HistKey.\n * @return Returns the histKey.\n */\n public HistAttrModificationKey getHistKey() {\n return histKey;\n }\n\n /**\n * Get the Attribute Value.\n * @return The Attribute Value.\n */\n public ByteString getAttributeValue() {\n return attributeValue;\n }\n\n /**\n * Generate a Modification equivalent to this value of the historical\n * attribute.\n *\n * @return A modification equivalent to this value of the historical\n * attribute.\n */\n public Modification generateMod() {\n AttributeBuilder builder = new AttributeBuilder(getAttributeType(), attrString);\n builder.setOptions(getOptions());\n if (histKey != ATTRDEL) {\n builder.add(attributeValue);\n }\n Attribute attr = builder.toAttribute();\n switch(histKey) {\n case ADD:\n return new Modification(ModificationType.ADD, attr);\n case DEL:\n case ATTRDEL:\n return new Modification(ModificationType.DELETE, attr);\n case REPL:\n return new Modification(ModificationType.REPLACE, attr);\n default:\n return null;\n }\n }\n\n /**\n * Indicates if this value of the historical attribute was generated\n * for a ADD operation.\n *\n * @return a boolean indicating if this was generated for a ADD operation.\n */\n public boolean isADDOperation() {\n return getAttributeType() == null && !isModDN;\n }\n\n /**\n * Indicates if this value of the historical attribute was generated\n * for a MODDN operation.\n *\n * @return a boolean indicating if this was generated for a ADDMODDN operation.\n */\n public boolean isMODDNOperation() {\n return getAttributeType() == null && isModDN;\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder();\n sb.append(attrString);\n for (String option : getOptions()) {\n sb.append(\";\").append(option);\n }\n sb.append(\":\").append(csn).append(\":\").append(getModificationType());\n if (stringValue != null) {\n sb.append(\":\").append(stringValue);\n }\n return sb.toString();\n }\n\n private String getModificationType() {\n if (isModDN) {\n return \"moddn\";\n } else if (histKey != null) {\n return histKey.toString();\n }\n return \"TODO\";\n }\n}\n"} {"task_id": "Java_2940", "language": "Java", "task_type": "switch_case", "source_file": "java/github/OpenRock/OpenDJ/opendj-server-legacy/src/main/java/org/opends/server/replication/plugin/HistoricalAttributeValue.java", "mask_start_position": 6081, "mask_end_position": 6465, "canonical_solution": "switch(histKey) {\n case ADD:\n return new Modification(ModificationType.ADD, attr);\n case DEL:\n case ATTRDEL:\n return new Modification(ModificationType.DELETE, attr);\n case REPL:\n return new Modification(ModificationType.REPLACE, attr);\n default:\n return null;\n }", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport static org.opends.server.replication.plugin.HistAttrModificationKey.*;\nimport static org.opends.server.util.StaticUtils.*;\nimport java.util.Collections;\nimport java.util.LinkedHashSet;\nimport java.util.Set;\nimport org.forgerock.opendj.ldap.ByteString;\nimport org.forgerock.opendj.ldap.ModificationType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.replication.common.CSN;\nimport org.opends.server.types.Attribute;\nimport org.opends.server.types.AttributeBuilder;\nimport org.opends.server.types.AttributeDescription;\nimport org.opends.server.types.AttributeType;\nimport org.opends.server.types.Modification;\n\n/**\n * This class stores an internal usable representation of the value of\n * the historical related to an entry.\n * It encodes/decodes from the String form stored in the DB attribute\n * from/to the internal usable form.\n *\n * an historical attribute value looks like :\n * description:00000108b3a65541000000000001:add:added_value\n * or\n * description:00000108b3a6cbb8000000000001:del:deleted_value\n * or\n * description:00000108b3a6cbb8000000000001:repl:new_value\n * or\n * description:00000108b3a6cbb8000000000001:attrDel\n * or\n * description:00000108b3a65541000000000001:add\n * or\n * dn:00000108b3a65541000000000001:add (ADD operation)\n * or\n * dn:00000108b3a65541000000000001:moddn (MODIFYDN operation)\n *\n * so after split\n * token[0] will contain the attribute name\n * token[1] will contain the CSN\n * token[2] will contain the type of historical information\n * token[3] will contain the attribute value\n *\n * options are stored with the attribute names using; as a separator\n * example :\n * description;FR;France:00000108b3a65541000000000001:add:added_value\n */\nclass HistoricalAttributeValue {\n\n private final AttributeDescription attrDesc;\n\n /**\n * The lowercase attribute string representation.\n */\n private final String attrString;\n\n private final ByteString attributeValue;\n\n private final CSN csn;\n\n private final HistAttrModificationKey histKey;\n\n private final String stringValue;\n\n /**\n * This flag indicates that this value was generated to store the last date\n * when the entry was renamed.\n */\n private boolean isModDN;\n\n /**\n * Create a new object from the String encoded form.\n *\n * @param strVal The String encoded form of historical attribute value.\n * @see EntryHistorical#encodeAndPurge() encoding in EntryHistorical\n */\n HistoricalAttributeValue(String strVal) {\n String[] token = strVal.split(\":\", 4);\n Set options;\n if (token[0].contains(\";\")) {\n options = new LinkedHashSet<>();\n String[] optionsToken = token[0].split(\";\");\n int index = 1;\n while (index < optionsToken.length) {\n options.add(optionsToken[index]);\n index++;\n }\n attrString = toLowerCase(optionsToken[0]);\n } else {\n options = Collections.emptySet();\n attrString = toLowerCase(token[0]);\n }\n AttributeType attrType;\n if (attrString.compareTo(\"dn\") != 0) {\n // This HistVal was used to store the date when some\n // modifications were done to the entries.\n attrType = DirectoryServer.getAttributeTypeOrDefault(attrString);\n } else {\n // This HistVal is used to store the date when the entry\n // was added to the directory or when it was last renamed.\n attrType = null;\n if (token.length >= 3 && token[2].compareTo(\"moddn\") == 0) {\n isModDN = true;\n }\n }\n this.attrDesc = attrType != null ? AttributeDescription.create(attrType, options) : null;\n csn = new CSN(token[1]);\n histKey = HistAttrModificationKey.decodeKey(token[2]);\n if (histKey != ATTRDEL) {\n if (token.length == 4) {\n stringValue = token[3];\n attributeValue = ByteString.valueOfUtf8(stringValue);\n } else {\n stringValue = null;\n attributeValue = null;\n }\n } else {\n stringValue = null;\n attributeValue = null;\n }\n }\n\n private AttributeType getAttributeType() {\n return attrDesc != null ? attrDesc.getAttributeType() : null;\n }\n\n private Set getOptions() {\n return attrDesc != null ? attrDesc.getOptions() : Collections.emptySet();\n }\n\n /**\n * Get the String form of the attribute type.\n *\n * @return Returns the String form of the attribute type.\n */\n public String getAttrString() {\n return attrString;\n }\n\n /**\n * Get the attribute description of this HistVal.\n *\n * @return Returns the attribute description of this HistVal.\n * Can return {@code null} if the HistVal was generated for a ADD Operation.\n */\n AttributeDescription getAttributeDescription() {\n return attrDesc;\n }\n\n /**\n * Get the CSN of this HistVal.\n * @return Returns the CSN of this HistVal.\n */\n public CSN getCSN() {\n return csn;\n }\n\n /**\n * Get the HistKey.\n * @return Returns the histKey.\n */\n public HistAttrModificationKey getHistKey() {\n return histKey;\n }\n\n /**\n * Get the Attribute Value.\n * @return The Attribute Value.\n */\n public ByteString getAttributeValue() {\n return attributeValue;\n }\n\n /**\n * Generate a Modification equivalent to this value of the historical\n * attribute.\n *\n * @return A modification equivalent to this value of the historical\n * attribute.\n */\n public Modification generateMod() {\n AttributeBuilder builder = new AttributeBuilder(getAttributeType(), attrString);\n builder.setOptions(getOptions());\n if (histKey != ATTRDEL) {\n builder.add(attributeValue);\n }\n Attribute attr = builder.toAttribute();\n ", "post_mask_code": "\n }\n\n /**\n * Indicates if this value of the historical attribute was generated\n * for a ADD operation.\n *\n * @return a boolean indicating if this was generated for a ADD operation.\n */\n public boolean isADDOperation() {\n return getAttributeType() == null && !isModDN;\n }\n\n /**\n * Indicates if this value of the historical attribute was generated\n * for a MODDN operation.\n *\n * @return a boolean indicating if this was generated for a ADDMODDN operation.\n */\n public boolean isMODDNOperation() {\n return getAttributeType() == null && isModDN;\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder();\n sb.append(attrString);\n for (String option : getOptions()) {\n sb.append(\";\").append(option);\n }\n sb.append(\":\").append(csn).append(\":\").append(getModificationType());\n if (stringValue != null) {\n sb.append(\":\").append(stringValue);\n }\n return sb.toString();\n }\n\n private String getModificationType() {\n if (isModDN) {\n return \"moddn\";\n } else if (histKey != null) {\n return histKey.toString();\n }\n return \"TODO\";\n }\n}\n"} {"task_id": "Java_2941", "language": "Java", "task_type": "while_statement", "source_file": "java/github/OpenRock/OpenDJ/opendj-server-legacy/src/main/java/org/opends/server/replication/plugin/HistoricalAttributeValue.java", "mask_start_position": 2824, "mask_end_position": 2950, "canonical_solution": "while (index < optionsToken.length) {\n options.add(optionsToken[index]);\n index++;\n }", "pre_mask_code": "package org.opends.server.replication.plugin;\n\nimport static org.opends.server.replication.plugin.HistAttrModificationKey.*;\nimport static org.opends.server.util.StaticUtils.*;\nimport java.util.Collections;\nimport java.util.LinkedHashSet;\nimport java.util.Set;\nimport org.forgerock.opendj.ldap.ByteString;\nimport org.forgerock.opendj.ldap.ModificationType;\nimport org.opends.server.core.DirectoryServer;\nimport org.opends.server.replication.common.CSN;\nimport org.opends.server.types.Attribute;\nimport org.opends.server.types.AttributeBuilder;\nimport org.opends.server.types.AttributeDescription;\nimport org.opends.server.types.AttributeType;\nimport org.opends.server.types.Modification;\n\n/**\n * This class stores an internal usable representation of the value of\n * the historical related to an entry.\n * It encodes/decodes from the String form stored in the DB attribute\n * from/to the internal usable form.\n *\n * an historical attribute value looks like :\n * description:00000108b3a65541000000000001:add:added_value\n * or\n * description:00000108b3a6cbb8000000000001:del:deleted_value\n * or\n * description:00000108b3a6cbb8000000000001:repl:new_value\n * or\n * description:00000108b3a6cbb8000000000001:attrDel\n * or\n * description:00000108b3a65541000000000001:add\n * or\n * dn:00000108b3a65541000000000001:add (ADD operation)\n * or\n * dn:00000108b3a65541000000000001:moddn (MODIFYDN operation)\n *\n * so after split\n * token[0] will contain the attribute name\n * token[1] will contain the CSN\n * token[2] will contain the type of historical information\n * token[3] will contain the attribute value\n *\n * options are stored with the attribute names using; as a separator\n * example :\n * description;FR;France:00000108b3a65541000000000001:add:added_value\n */\nclass HistoricalAttributeValue {\n\n private final AttributeDescription attrDesc;\n\n /**\n * The lowercase attribute string representation.\n */\n private final String attrString;\n\n private final ByteString attributeValue;\n\n private final CSN csn;\n\n private final HistAttrModificationKey histKey;\n\n private final String stringValue;\n\n /**\n * This flag indicates that this value was generated to store the last date\n * when the entry was renamed.\n */\n private boolean isModDN;\n\n /**\n * Create a new object from the String encoded form.\n *\n * @param strVal The String encoded form of historical attribute value.\n * @see EntryHistorical#encodeAndPurge() encoding in EntryHistorical\n */\n HistoricalAttributeValue(String strVal) {\n String[] token = strVal.split(\":\", 4);\n Set options;\n if (token[0].contains(\";\")) {\n options = new LinkedHashSet<>();\n String[] optionsToken = token[0].split(\";\");\n int index = 1;\n ", "post_mask_code": "\n attrString = toLowerCase(optionsToken[0]);\n } else {\n options = Collections.emptySet();\n attrString = toLowerCase(token[0]);\n }\n AttributeType attrType;\n if (attrString.compareTo(\"dn\") != 0) {\n // This HistVal was used to store the date when some\n // modifications were done to the entries.\n attrType = DirectoryServer.getAttributeTypeOrDefault(attrString);\n } else {\n // This HistVal is used to store the date when the entry\n // was added to the directory or when it was last renamed.\n attrType = null;\n if (token.length >= 3 && token[2].compareTo(\"moddn\") == 0) {\n isModDN = true;\n }\n }\n this.attrDesc = attrType != null ? AttributeDescription.create(attrType, options) : null;\n csn = new CSN(token[1]);\n histKey = HistAttrModificationKey.decodeKey(token[2]);\n if (histKey != ATTRDEL) {\n if (token.length == 4) {\n stringValue = token[3];\n attributeValue = ByteString.valueOfUtf8(stringValue);\n } else {\n stringValue = null;\n attributeValue = null;\n }\n } else {\n stringValue = null;\n attributeValue = null;\n }\n }\n\n private AttributeType getAttributeType() {\n return attrDesc != null ? attrDesc.getAttributeType() : null;\n }\n\n private Set getOptions() {\n return attrDesc != null ? attrDesc.getOptions() : Collections.emptySet();\n }\n\n /**\n * Get the String form of the attribute type.\n *\n * @return Returns the String form of the attribute type.\n */\n public String getAttrString() {\n return attrString;\n }\n\n /**\n * Get the attribute description of this HistVal.\n *\n * @return Returns the attribute description of this HistVal.\n * Can return {@code null} if the HistVal was generated for a ADD Operation.\n */\n AttributeDescription getAttributeDescription() {\n return attrDesc;\n }\n\n /**\n * Get the CSN of this HistVal.\n * @return Returns the CSN of this HistVal.\n */\n public CSN getCSN() {\n return csn;\n }\n\n /**\n * Get the HistKey.\n * @return Returns the histKey.\n */\n public HistAttrModificationKey getHistKey() {\n return histKey;\n }\n\n /**\n * Get the Attribute Value.\n * @return The Attribute Value.\n */\n public ByteString getAttributeValue() {\n return attributeValue;\n }\n\n /**\n * Generate a Modification equivalent to this value of the historical\n * attribute.\n *\n * @return A modification equivalent to this value of the historical\n * attribute.\n */\n public Modification generateMod() {\n AttributeBuilder builder = new AttributeBuilder(getAttributeType(), attrString);\n builder.setOptions(getOptions());\n if (histKey != ATTRDEL) {\n builder.add(attributeValue);\n }\n Attribute attr = builder.toAttribute();\n switch(histKey) {\n case ADD:\n return new Modification(ModificationType.ADD, attr);\n case DEL:\n case ATTRDEL:\n return new Modification(ModificationType.DELETE, attr);\n case REPL:\n return new Modification(ModificationType.REPLACE, attr);\n default:\n return null;\n }\n }\n\n /**\n * Indicates if this value of the historical attribute was generated\n * for a ADD operation.\n *\n * @return a boolean indicating if this was generated for a ADD operation.\n */\n public boolean isADDOperation() {\n return getAttributeType() == null && !isModDN;\n }\n\n /**\n * Indicates if this value of the historical attribute was generated\n * for a MODDN operation.\n *\n * @return a boolean indicating if this was generated for a ADDMODDN operation.\n */\n public boolean isMODDNOperation() {\n return getAttributeType() == null && isModDN;\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder();\n sb.append(attrString);\n for (String option : getOptions()) {\n sb.append(\";\").append(option);\n }\n sb.append(\":\").append(csn).append(\":\").append(getModificationType());\n if (stringValue != null) {\n sb.append(\":\").append(stringValue);\n }\n return sb.toString();\n }\n\n private String getModificationType() {\n if (isModDN) {\n return \"moddn\";\n } else if (histKey != null) {\n return histKey.toString();\n }\n return \"TODO\";\n }\n}\n"} {"task_id": "Java_2942", "language": "Java", "task_type": "method_signature", "source_file": "java/github/complone/leveldb-interpretation/leveldb/src/main/java/com/complone/base/table/BlockEntry.java", "mask_start_position": 856, "mask_end_position": 902, "canonical_solution": "@Override\n public boolean equals(Object o) ", "pre_mask_code": "package com.complone.base.table;\n\nimport com.complone.base.include.Slice;\nimport java.util.Map;\nimport static java.nio.charset.StandardCharsets.UTF_8;\nimport static java.util.Objects.requireNonNull;\n\npublic class BlockEntry implements Map.Entry {\n\n private final Slice key;\n\n private final Slice value;\n\n public BlockEntry(Slice key, Slice value) {\n requireNonNull(key, \"key is null\");\n requireNonNull(value, \"value is null\");\n this.key = key;\n this.value = value;\n }\n\n @Override\n public Slice getKey() {\n return key;\n }\n\n @Override\n public Slice getValue() {\n return value;\n }\n\n /**\n * @throws UnsupportedOperationException always\n */\n @Override\n public final Slice setValue(Slice value) {\n throw new UnsupportedOperationException();\n }\n\n ", "post_mask_code": "{\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n BlockEntry entry = (BlockEntry) o;\n if (!key.equals(entry.key)) {\n return false;\n }\n if (!value.equals(entry.value)) {\n return false;\n }\n return true;\n }\n\n /**\n * 压缩前缀提取 每个数据块的前缀有一定几率会重叠\n * //为了避免前缀重合\n * restart_中每个元素都是\n * 一个数字,为了查找方便,\n * finish直接按每个元素32bit进行存储。\n * http://example.com\n * @return\n */\n @Override\n public int hashCode() {\n int result = key.hashCode();\n result = 31 * result + value.hashCode();\n return result;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"BlockEntry\");\n // todo don't print the real value\n sb.append(\"{key=\").append(key.toString(UTF_8));\n sb.append(\", value=\").append(value.toString(UTF_8));\n sb.append('}');\n return sb.toString();\n }\n}\n"} {"task_id": "Java_2943", "language": "Java", "task_type": "method_body", "source_file": "java/github/complone/leveldb-interpretation/leveldb/src/main/java/com/complone/base/table/BlockEntry.java", "mask_start_position": 792, "mask_end_position": 850, "canonical_solution": "{\n throw new UnsupportedOperationException();\n }", "pre_mask_code": "package com.complone.base.table;\n\nimport com.complone.base.include.Slice;\nimport java.util.Map;\nimport static java.nio.charset.StandardCharsets.UTF_8;\nimport static java.util.Objects.requireNonNull;\n\npublic class BlockEntry implements Map.Entry {\n\n private final Slice key;\n\n private final Slice value;\n\n public BlockEntry(Slice key, Slice value) {\n requireNonNull(key, \"key is null\");\n requireNonNull(value, \"value is null\");\n this.key = key;\n this.value = value;\n }\n\n @Override\n public Slice getKey() {\n return key;\n }\n\n @Override\n public Slice getValue() {\n return value;\n }\n\n /**\n * @throws UnsupportedOperationException always\n */\n @Override\n public final Slice setValue(Slice value) ", "post_mask_code": "\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n BlockEntry entry = (BlockEntry) o;\n if (!key.equals(entry.key)) {\n return false;\n }\n if (!value.equals(entry.value)) {\n return false;\n }\n return true;\n }\n\n /**\n * 压缩前缀提取 每个数据块的前缀有一定几率会重叠\n * //为了避免前缀重合\n * restart_中每个元素都是\n * 一个数字,为了查找方便,\n * finish直接按每个元素32bit进行存储。\n * http://example.com\n * @return\n */\n @Override\n public int hashCode() {\n int result = key.hashCode();\n result = 31 * result + value.hashCode();\n return result;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"BlockEntry\");\n // todo don't print the real value\n sb.append(\"{key=\").append(key.toString(UTF_8));\n sb.append(\", value=\").append(value.toString(UTF_8));\n sb.append('}');\n return sb.toString();\n }\n}\n"} {"task_id": "Java_2944", "language": "Java", "task_type": "single_line", "source_file": "java/github/complone/leveldb-interpretation/leveldb/src/main/java/com/complone/base/table/BlockEntry.java", "mask_start_position": 1892, "mask_end_position": 1901, "canonical_solution": "(UTF_8));", "pre_mask_code": "package com.complone.base.table;\n\nimport com.complone.base.include.Slice;\nimport java.util.Map;\nimport static java.nio.charset.StandardCharsets.UTF_8;\nimport static java.util.Objects.requireNonNull;\n\npublic class BlockEntry implements Map.Entry {\n\n private final Slice key;\n\n private final Slice value;\n\n public BlockEntry(Slice key, Slice value) {\n requireNonNull(key, \"key is null\");\n requireNonNull(value, \"value is null\");\n this.key = key;\n this.value = value;\n }\n\n @Override\n public Slice getKey() {\n return key;\n }\n\n @Override\n public Slice getValue() {\n return value;\n }\n\n /**\n * @throws UnsupportedOperationException always\n */\n @Override\n public final Slice setValue(Slice value) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n BlockEntry entry = (BlockEntry) o;\n if (!key.equals(entry.key)) {\n return false;\n }\n if (!value.equals(entry.value)) {\n return false;\n }\n return true;\n }\n\n /**\n * 压缩前缀提取 每个数据块的前缀有一定几率会重叠\n * //为了避免前缀重合\n * restart_中每个元素都是\n * 一个数字,为了查找方便,\n * finish直接按每个元素32bit进行存储。\n * http://example.com\n * @return\n */\n @Override\n public int hashCode() {\n int result = key.hashCode();\n result = 31 * result + value.hashCode();\n return result;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"BlockEntry\");\n // todo don't print the real value\n sb.append(\"{key=\").append(key.toString(UTF_8));\n sb.append(\", value=\").append(value.toString", "post_mask_code": "\n sb.append('}');\n return sb.toString();\n }\n}\n"} {"task_id": "Java_2945", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/complone/leveldb-interpretation/leveldb/src/main/java/com/complone/base/table/BlockEntry.java", "mask_start_position": 1462, "mask_end_position": 1614, "canonical_solution": "@Override\n public int hashCode() {\n int result = key.hashCode();\n result = 31 * result + value.hashCode();\n return result;\n }", "pre_mask_code": "package com.complone.base.table;\n\nimport com.complone.base.include.Slice;\nimport java.util.Map;\nimport static java.nio.charset.StandardCharsets.UTF_8;\nimport static java.util.Objects.requireNonNull;\n\npublic class BlockEntry implements Map.Entry {\n\n private final Slice key;\n\n private final Slice value;\n\n public BlockEntry(Slice key, Slice value) {\n requireNonNull(key, \"key is null\");\n requireNonNull(value, \"value is null\");\n this.key = key;\n this.value = value;\n }\n\n @Override\n public Slice getKey() {\n return key;\n }\n\n @Override\n public Slice getValue() {\n return value;\n }\n\n /**\n * @throws UnsupportedOperationException always\n */\n @Override\n public final Slice setValue(Slice value) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n BlockEntry entry = (BlockEntry) o;\n if (!key.equals(entry.key)) {\n return false;\n }\n if (!value.equals(entry.value)) {\n return false;\n }\n return true;\n }\n\n /**\n * 压缩前缀提取 每个数据块的前缀有一定几率会重叠\n * //为了避免前缀重合\n * restart_中每个元素都是\n * 一个数字,为了查找方便,\n * finish直接按每个元素32bit进行存储。\n * http://example.com\n * @return\n */\n ", "post_mask_code": "\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"BlockEntry\");\n // todo don't print the real value\n sb.append(\"{key=\").append(key.toString(UTF_8));\n sb.append(\", value=\").append(value.toString(UTF_8));\n sb.append('}');\n return sb.toString();\n }\n}\n"} {"task_id": "Java_2946", "language": "Java", "task_type": "method_signature", "source_file": "java/github/LuoboDcom/ZZShow/app/src/main/java/com/ys/yoosir/zzshow/mvp/ui/fragments/base/BaseFragment.java", "mask_start_position": 2164, "mask_end_position": 2202, "canonical_solution": "@Override\n public void onDestroy() ", "pre_mask_code": "package com.ys.yoosir.zzshow.mvp.ui.fragments.base;\n\nimport android.os.Bundle;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.Fragment;\nimport android.support.v7.widget.Toolbar;\nimport android.util.Log;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport com.ys.yoosir.zzshow.MyApplication;\nimport com.ys.yoosir.zzshow.R;\nimport com.ys.yoosir.zzshow.di.component.AppComponent;\nimport com.ys.yoosir.zzshow.mvp.presenter.interfaces.BasePresenter;\nimport javax.inject.Inject;\nimport butterknife.ButterKnife;\nimport rx.Subscription;\n\n/**\n * Created by Yoosir on 2016/10/19 0019.\n */\npublic abstract class BaseFragment extends Fragment {\n\n private final static String TAG = \"BaseFragment\";\n\n protected MyApplication mApplication;\n\n @Inject\n protected T mPresenter;\n\n protected View mFragmentView;\n\n protected Subscription mSubscription;\n\n // 提供AppComponent(提供所有的单例对象)给子类,进行Component依赖\n protected abstract void setupFragmentComponent(AppComponent appComponent);\n\n protected abstract int getLayoutId();\n\n protected abstract void initViews(View view);\n\n protected abstract void initData();\n\n @Override\n public void onActivityCreated(@Nullable Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n Log.d(TAG, \"onActivityCreated\");\n mApplication = (MyApplication) getActivity().getApplication();\n setupFragmentComponent(mApplication.getAppComponent());\n initData();\n }\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Log.d(TAG, \"onCreate\");\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n Log.d(TAG, \"onCreateView\");\n if (mFragmentView == null) {\n mFragmentView = inflater.inflate(getLayoutId(), container, false);\n ButterKnife.bind(this, mFragmentView);\n initViews(mFragmentView);\n }\n return mFragmentView;\n }\n\n ", "post_mask_code": "{\n super.onDestroy();\n if (mPresenter != null) {\n mPresenter.onDestroy();\n mPresenter = null;\n }\n if (mSubscription != null && !mSubscription.isUnsubscribed()) {\n mSubscription.unsubscribe();\n mSubscription = null;\n }\n this.mFragmentView = null;\n }\n}\n"} {"task_id": "Java_2947", "language": "Java", "task_type": "method_body", "source_file": "java/github/LuoboDcom/ZZShow/app/src/main/java/com/ys/yoosir/zzshow/mvp/ui/fragments/base/BaseFragment.java", "mask_start_position": 1870, "mask_end_position": 2158, "canonical_solution": "{\n Log.d(TAG, \"onCreateView\");\n if (mFragmentView == null) {\n mFragmentView = inflater.inflate(getLayoutId(), container, false);\n ButterKnife.bind(this, mFragmentView);\n initViews(mFragmentView);\n }\n return mFragmentView;\n }", "pre_mask_code": "package com.ys.yoosir.zzshow.mvp.ui.fragments.base;\n\nimport android.os.Bundle;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.Fragment;\nimport android.support.v7.widget.Toolbar;\nimport android.util.Log;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport com.ys.yoosir.zzshow.MyApplication;\nimport com.ys.yoosir.zzshow.R;\nimport com.ys.yoosir.zzshow.di.component.AppComponent;\nimport com.ys.yoosir.zzshow.mvp.presenter.interfaces.BasePresenter;\nimport javax.inject.Inject;\nimport butterknife.ButterKnife;\nimport rx.Subscription;\n\n/**\n * Created by Yoosir on 2016/10/19 0019.\n */\npublic abstract class BaseFragment extends Fragment {\n\n private final static String TAG = \"BaseFragment\";\n\n protected MyApplication mApplication;\n\n @Inject\n protected T mPresenter;\n\n protected View mFragmentView;\n\n protected Subscription mSubscription;\n\n // 提供AppComponent(提供所有的单例对象)给子类,进行Component依赖\n protected abstract void setupFragmentComponent(AppComponent appComponent);\n\n protected abstract int getLayoutId();\n\n protected abstract void initViews(View view);\n\n protected abstract void initData();\n\n @Override\n public void onActivityCreated(@Nullable Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n Log.d(TAG, \"onActivityCreated\");\n mApplication = (MyApplication) getActivity().getApplication();\n setupFragmentComponent(mApplication.getAppComponent());\n initData();\n }\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Log.d(TAG, \"onCreate\");\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) ", "post_mask_code": "\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n if (mPresenter != null) {\n mPresenter.onDestroy();\n mPresenter = null;\n }\n if (mSubscription != null && !mSubscription.isUnsubscribed()) {\n mSubscription.unsubscribe();\n mSubscription = null;\n }\n this.mFragmentView = null;\n }\n}\n"} {"task_id": "Java_2948", "language": "Java", "task_type": "single_line", "source_file": "java/github/LuoboDcom/ZZShow/app/src/main/java/com/ys/yoosir/zzshow/mvp/ui/fragments/base/BaseFragment.java", "mask_start_position": 1895, "mask_end_position": 1907, "canonical_solution": "reateView\");", "pre_mask_code": "package com.ys.yoosir.zzshow.mvp.ui.fragments.base;\n\nimport android.os.Bundle;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.Fragment;\nimport android.support.v7.widget.Toolbar;\nimport android.util.Log;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport com.ys.yoosir.zzshow.MyApplication;\nimport com.ys.yoosir.zzshow.R;\nimport com.ys.yoosir.zzshow.di.component.AppComponent;\nimport com.ys.yoosir.zzshow.mvp.presenter.interfaces.BasePresenter;\nimport javax.inject.Inject;\nimport butterknife.ButterKnife;\nimport rx.Subscription;\n\n/**\n * Created by Yoosir on 2016/10/19 0019.\n */\npublic abstract class BaseFragment extends Fragment {\n\n private final static String TAG = \"BaseFragment\";\n\n protected MyApplication mApplication;\n\n @Inject\n protected T mPresenter;\n\n protected View mFragmentView;\n\n protected Subscription mSubscription;\n\n // 提供AppComponent(提供所有的单例对象)给子类,进行Component依赖\n protected abstract void setupFragmentComponent(AppComponent appComponent);\n\n protected abstract int getLayoutId();\n\n protected abstract void initViews(View view);\n\n protected abstract void initData();\n\n @Override\n public void onActivityCreated(@Nullable Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n Log.d(TAG, \"onActivityCreated\");\n mApplication = (MyApplication) getActivity().getApplication();\n setupFragmentComponent(mApplication.getAppComponent());\n initData();\n }\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Log.d(TAG, \"onCreate\");\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n Log.d(TAG, \"onC", "post_mask_code": "\n if (mFragmentView == null) {\n mFragmentView = inflater.inflate(getLayoutId(), container, false);\n ButterKnife.bind(this, mFragmentView);\n initViews(mFragmentView);\n }\n return mFragmentView;\n }\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n if (mPresenter != null) {\n mPresenter.onDestroy();\n mPresenter = null;\n }\n if (mSubscription != null && !mSubscription.isUnsubscribed()) {\n mSubscription.unsubscribe();\n mSubscription = null;\n }\n this.mFragmentView = null;\n }\n}\n"} {"task_id": "Java_2949", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jxnu-liguobin/cs-summary-reflection/java-leetcode/src/main/java/io/github/wkk/everyday/aug/Minesweeper.java", "mask_start_position": 486, "mask_end_position": 532, "canonical_solution": "public void dfs(char[][] board, int x, int y) ", "pre_mask_code": "package io.github.wkk.everyday.aug;\n\n/**\n * @author example@nnthink.com\n * @since 2020/8/20上午8:35\n */\npublic class Minesweeper {\n\n int[] dirX = { 0, 1, 0, -1, 1, 1, -1, -1 };\n\n int[] dirY = { 1, 0, -1, 0, 1, -1, 1, -1 };\n\n public char[][] updateBoard(char[][] board, int[] click) {\n int x = click[0], y = click[1];\n if (board[x][y] == 'M') {\n board[x][y] = 'X';\n } else {\n dfs(board, x, y);\n }\n return board;\n }\n\n ", "post_mask_code": "{\n int cnt = 0;\n for (int i = 0; i < 8; ++i) {\n int tx = x + dirX[i];\n int ty = y + dirY[i];\n if (tx < 0 || tx >= board.length || ty < 0 || ty >= board[0].length) {\n continue;\n }\n // 不用判断 M,因为如果有 M 的话游戏已经结束了\n if (board[tx][ty] == 'M') {\n ++cnt;\n }\n }\n if (cnt > 0) {\n board[x][y] = (char) (cnt + '0');\n } else {\n board[x][y] = 'B';\n for (int i = 0; i < 8; ++i) {\n int tx = x + dirX[i];\n int ty = y + dirY[i];\n // 这里不需要在存在 B 的时候继续扩展,因为 B 之前被点击的时候已经被扩展过了\n if (tx < 0 || tx >= board.length || ty < 0 || ty >= board[0].length || board[tx][ty] != 'E') {\n continue;\n }\n dfs(board, tx, ty);\n }\n }\n }\n}\n"} {"task_id": "Java_2950", "language": "Java", "task_type": "method_body", "source_file": "java/github/jxnu-liguobin/cs-summary-reflection/java-leetcode/src/main/java/io/github/wkk/everyday/aug/Minesweeper.java", "mask_start_position": 289, "mask_end_position": 480, "canonical_solution": "{\n int x = click[0], y = click[1];\n if (board[x][y] == 'M') {\n board[x][y] = 'X';\n } else {\n dfs(board, x, y);\n }\n return board;\n }", "pre_mask_code": "package io.github.wkk.everyday.aug;\n\n/**\n * @author example@nnthink.com\n * @since 2020/8/20上午8:35\n */\npublic class Minesweeper {\n\n int[] dirX = { 0, 1, 0, -1, 1, 1, -1, -1 };\n\n int[] dirY = { 1, 0, -1, 0, 1, -1, 1, -1 };\n\n public char[][] updateBoard(char[][] board, int[] click) ", "post_mask_code": "\n\n public void dfs(char[][] board, int x, int y) {\n int cnt = 0;\n for (int i = 0; i < 8; ++i) {\n int tx = x + dirX[i];\n int ty = y + dirY[i];\n if (tx < 0 || tx >= board.length || ty < 0 || ty >= board[0].length) {\n continue;\n }\n // 不用判断 M,因为如果有 M 的话游戏已经结束了\n if (board[tx][ty] == 'M') {\n ++cnt;\n }\n }\n if (cnt > 0) {\n board[x][y] = (char) (cnt + '0');\n } else {\n board[x][y] = 'B';\n for (int i = 0; i < 8; ++i) {\n int tx = x + dirX[i];\n int ty = y + dirY[i];\n // 这里不需要在存在 B 的时候继续扩展,因为 B 之前被点击的时候已经被扩展过了\n if (tx < 0 || tx >= board.length || ty < 0 || ty >= board[0].length || board[tx][ty] != 'E') {\n continue;\n }\n dfs(board, tx, ty);\n }\n }\n }\n}\n"} {"task_id": "Java_2951", "language": "Java", "task_type": "single_line", "source_file": "java/github/jxnu-liguobin/cs-summary-reflection/java-leetcode/src/main/java/io/github/wkk/everyday/aug/Minesweeper.java", "mask_start_position": 472, "mask_end_position": 474, "canonical_solution": "d;", "pre_mask_code": "package io.github.wkk.everyday.aug;\n\n/**\n * @author example@nnthink.com\n * @since 2020/8/20上午8:35\n */\npublic class Minesweeper {\n\n int[] dirX = { 0, 1, 0, -1, 1, 1, -1, -1 };\n\n int[] dirY = { 1, 0, -1, 0, 1, -1, 1, -1 };\n\n public char[][] updateBoard(char[][] board, int[] click) {\n int x = click[0], y = click[1];\n if (board[x][y] == 'M') {\n board[x][y] = 'X';\n } else {\n dfs(board, x, y);\n }\n return boar", "post_mask_code": "\n }\n\n public void dfs(char[][] board, int x, int y) {\n int cnt = 0;\n for (int i = 0; i < 8; ++i) {\n int tx = x + dirX[i];\n int ty = y + dirY[i];\n if (tx < 0 || tx >= board.length || ty < 0 || ty >= board[0].length) {\n continue;\n }\n // 不用判断 M,因为如果有 M 的话游戏已经结束了\n if (board[tx][ty] == 'M') {\n ++cnt;\n }\n }\n if (cnt > 0) {\n board[x][y] = (char) (cnt + '0');\n } else {\n board[x][y] = 'B';\n for (int i = 0; i < 8; ++i) {\n int tx = x + dirX[i];\n int ty = y + dirY[i];\n // 这里不需要在存在 B 的时候继续扩展,因为 B 之前被点击的时候已经被扩展过了\n if (tx < 0 || tx >= board.length || ty < 0 || ty >= board[0].length || board[tx][ty] != 'E') {\n continue;\n }\n dfs(board, tx, ty);\n }\n }\n }\n}\n"} {"task_id": "Java_2952", "language": "Java", "task_type": "for_statement", "source_file": "java/github/jxnu-liguobin/cs-summary-reflection/java-leetcode/src/main/java/io/github/wkk/everyday/aug/Minesweeper.java", "mask_start_position": 1040, "mask_end_position": 1413, "canonical_solution": "for (int i = 0; i < 8; ++i) {\n int tx = x + dirX[i];\n int ty = y + dirY[i];\n // 这里不需要在存在 B 的时候继续扩展,因为 B 之前被点击的时候已经被扩展过了\n if (tx < 0 || tx >= board.length || ty < 0 || ty >= board[0].length || board[tx][ty] != 'E') {\n continue;\n }\n dfs(board, tx, ty);\n }", "pre_mask_code": "package io.github.wkk.everyday.aug;\n\n/**\n * @author example@nnthink.com\n * @since 2020/8/20上午8:35\n */\npublic class Minesweeper {\n\n int[] dirX = { 0, 1, 0, -1, 1, 1, -1, -1 };\n\n int[] dirY = { 1, 0, -1, 0, 1, -1, 1, -1 };\n\n public char[][] updateBoard(char[][] board, int[] click) {\n int x = click[0], y = click[1];\n if (board[x][y] == 'M') {\n board[x][y] = 'X';\n } else {\n dfs(board, x, y);\n }\n return board;\n }\n\n public void dfs(char[][] board, int x, int y) {\n int cnt = 0;\n for (int i = 0; i < 8; ++i) {\n int tx = x + dirX[i];\n int ty = y + dirY[i];\n if (tx < 0 || tx >= board.length || ty < 0 || ty >= board[0].length) {\n continue;\n }\n // 不用判断 M,因为如果有 M 的话游戏已经结束了\n if (board[tx][ty] == 'M') {\n ++cnt;\n }\n }\n if (cnt > 0) {\n board[x][y] = (char) (cnt + '0');\n } else {\n board[x][y] = 'B';\n ", "post_mask_code": "\n }\n }\n}\n"} {"task_id": "Java_2953", "language": "Java", "task_type": "method_signature", "source_file": "java/github/stagemonitor/stagemonitor/stagemonitor-tracing/src/main/java/org/stagemonitor/tracing/AbstractTracingTransformer.java", "mask_start_position": 1044, "mask_end_position": 1135, "canonical_solution": "@Override\n protected Class getAdviceClass() ", "pre_mask_code": "package org.stagemonitor.tracing;\n\nimport net.bytebuddy.asm.Advice;\nimport net.bytebuddy.description.annotation.AnnotationDescription;\nimport net.bytebuddy.description.method.MethodDescription;\nimport net.bytebuddy.description.method.ParameterDescription;\nimport net.bytebuddy.description.type.TypeDescription;\nimport net.bytebuddy.implementation.bytecode.assign.Assigner;\nimport net.bytebuddy.implementation.bytecode.constant.NullConstant;\nimport org.stagemonitor.core.Stagemonitor;\nimport org.stagemonitor.core.instrument.StagemonitorByteBuddyTransformer;\nimport org.stagemonitor.tracing.metrics.MetricsSpanEventListener;\nimport java.lang.annotation.Annotation;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\nimport java.util.Arrays;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport io.opentracing.Span;\n\npublic class AbstractTracingTransformer extends StagemonitorByteBuddyTransformer {\n\n ", "post_mask_code": "{\n return AbstractTracingTransformer.class;\n }\n\n @Advice.OnMethodEnter(inline = false)\n public static void monitorStart(@ParameterNames String parameterNames, @Advice.AllArguments Object[] args, @RequestName String requestName, @Advice.Origin(\"#t\") String className, @Advice.Origin(\"#m\") String methodName, @Advice.This(optional = true) Object thiz) {\n final String[] paramNames = parameterNames.split(\",\");\n Map params = new LinkedHashMap();\n for (int i = 0; i < args.length; i++) {\n params.put(paramNames[i], args[i]);\n }\n final MonitoredMethodRequest monitoredRequest = new MonitoredMethodRequest(Stagemonitor.getConfiguration(), requestName, null, params);\n final TracingPlugin tracingPlugin = Stagemonitor.getPlugin(TracingPlugin.class);\n tracingPlugin.getRequestMonitor().monitorStart(monitoredRequest);\n final Span span = TracingPlugin.getCurrentSpan();\n if (requestName == null) {\n span.setOperationName(getBusinessTransationName(thiz != null ? thiz.getClass().getName() : className, methodName));\n }\n span.setTag(MetricsSpanEventListener.ENABLE_TRACKING_METRICS_TAG, true);\n }\n\n @Advice.OnMethodExit(onThrowable = Throwable.class, inline = false)\n public static void monitorStop(@Advice.Thrown Throwable exception) {\n final RequestMonitor requestMonitor = Stagemonitor.getPlugin(TracingPlugin.class).getRequestMonitor();\n if (exception != null && exception instanceof Exception) {\n requestMonitor.recordException((Exception) exception);\n }\n requestMonitor.monitorStop();\n }\n\n @Override\n protected int getOrder() {\n return Integer.MIN_VALUE;\n }\n\n @Override\n protected List> getOffsetMappingFactories() {\n final Advice.OffsetMapping.Factory requestNameDynamicValue = new RequestNameDynamicValue();\n return Arrays.asList(requestNameDynamicValue, new ParameterNamesDynamicValue());\n }\n\n @Retention(RetentionPolicy.RUNTIME)\n @Target(ElementType.PARAMETER)\n public @interface RequestName {\n }\n\n public static class RequestNameDynamicValue implements Advice.OffsetMapping.Factory {\n\n @Override\n public Class getAnnotationType() {\n return RequestName.class;\n }\n\n @Override\n public Advice.OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable annotation, AdviceType adviceType) {\n return new Advice.OffsetMapping() {\n\n @Override\n public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Advice.ArgumentHandler argumentHandler, Sort sort) {\n final String requestName = getRequestName(instrumentedMethod);\n if (requestName != null) {\n return Target.ForStackManipulation.of(requestName);\n } else {\n return new Target.ForStackManipulation(NullConstant.INSTANCE);\n }\n }\n };\n }\n }\n\n public static String getRequestName(MethodDescription instrumentedMethod) {\n final AnnotationDescription.Loadable monitorRequestsLoadable = instrumentedMethod.getDeclaredAnnotations().ofType(Traced.class);\n if (monitorRequestsLoadable != null) {\n final Traced traced = monitorRequestsLoadable.loadSilent();\n if (!traced.requestName().isEmpty()) {\n return traced.requestName();\n }\n if (traced.resolveNameAtRuntime()) {\n return null;\n }\n }\n return getBusinessTransationName(instrumentedMethod.getDeclaringType().getTypeName(), instrumentedMethod.getName());\n }\n\n private static String getBusinessTransationName(String className, String methodName) {\n return configuration.getConfig(TracingPlugin.class).getBusinessTransactionNamingStrategy().getBusinessTransactionName(className, methodName);\n }\n\n @Retention(RetentionPolicy.RUNTIME)\n @Target(ElementType.PARAMETER)\n public @interface ParameterNames {\n }\n\n public static class ParameterNamesDynamicValue implements Advice.OffsetMapping.Factory {\n\n @Override\n public Class getAnnotationType() {\n return ParameterNames.class;\n }\n\n @Override\n public Advice.OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable annotation, AdviceType adviceType) {\n return new Advice.OffsetMapping() {\n\n @Override\n public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Advice.ArgumentHandler argumentHandler, Sort sort) {\n final StringBuilder params = new StringBuilder();\n for (ParameterDescription param : instrumentedMethod.getParameters()) {\n params.append(param.getName()).append(',');\n }\n return Advice.OffsetMapping.Target.ForStackManipulation.of(params.toString());\n }\n };\n }\n }\n}\n"} {"task_id": "Java_2954", "language": "Java", "task_type": "method_body", "source_file": "java/github/stagemonitor/stagemonitor/stagemonitor-tracing/src/main/java/org/stagemonitor/tracing/AbstractTracingTransformer.java", "mask_start_position": 1135, "mask_end_position": 1191, "canonical_solution": "{\n return AbstractTracingTransformer.class;\n }", "pre_mask_code": "package org.stagemonitor.tracing;\n\nimport net.bytebuddy.asm.Advice;\nimport net.bytebuddy.description.annotation.AnnotationDescription;\nimport net.bytebuddy.description.method.MethodDescription;\nimport net.bytebuddy.description.method.ParameterDescription;\nimport net.bytebuddy.description.type.TypeDescription;\nimport net.bytebuddy.implementation.bytecode.assign.Assigner;\nimport net.bytebuddy.implementation.bytecode.constant.NullConstant;\nimport org.stagemonitor.core.Stagemonitor;\nimport org.stagemonitor.core.instrument.StagemonitorByteBuddyTransformer;\nimport org.stagemonitor.tracing.metrics.MetricsSpanEventListener;\nimport java.lang.annotation.Annotation;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\nimport java.util.Arrays;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport io.opentracing.Span;\n\npublic class AbstractTracingTransformer extends StagemonitorByteBuddyTransformer {\n\n @Override\n protected Class getAdviceClass() ", "post_mask_code": "\n\n @Advice.OnMethodEnter(inline = false)\n public static void monitorStart(@ParameterNames String parameterNames, @Advice.AllArguments Object[] args, @RequestName String requestName, @Advice.Origin(\"#t\") String className, @Advice.Origin(\"#m\") String methodName, @Advice.This(optional = true) Object thiz) {\n final String[] paramNames = parameterNames.split(\",\");\n Map params = new LinkedHashMap();\n for (int i = 0; i < args.length; i++) {\n params.put(paramNames[i], args[i]);\n }\n final MonitoredMethodRequest monitoredRequest = new MonitoredMethodRequest(Stagemonitor.getConfiguration(), requestName, null, params);\n final TracingPlugin tracingPlugin = Stagemonitor.getPlugin(TracingPlugin.class);\n tracingPlugin.getRequestMonitor().monitorStart(monitoredRequest);\n final Span span = TracingPlugin.getCurrentSpan();\n if (requestName == null) {\n span.setOperationName(getBusinessTransationName(thiz != null ? thiz.getClass().getName() : className, methodName));\n }\n span.setTag(MetricsSpanEventListener.ENABLE_TRACKING_METRICS_TAG, true);\n }\n\n @Advice.OnMethodExit(onThrowable = Throwable.class, inline = false)\n public static void monitorStop(@Advice.Thrown Throwable exception) {\n final RequestMonitor requestMonitor = Stagemonitor.getPlugin(TracingPlugin.class).getRequestMonitor();\n if (exception != null && exception instanceof Exception) {\n requestMonitor.recordException((Exception) exception);\n }\n requestMonitor.monitorStop();\n }\n\n @Override\n protected int getOrder() {\n return Integer.MIN_VALUE;\n }\n\n @Override\n protected List> getOffsetMappingFactories() {\n final Advice.OffsetMapping.Factory requestNameDynamicValue = new RequestNameDynamicValue();\n return Arrays.asList(requestNameDynamicValue, new ParameterNamesDynamicValue());\n }\n\n @Retention(RetentionPolicy.RUNTIME)\n @Target(ElementType.PARAMETER)\n public @interface RequestName {\n }\n\n public static class RequestNameDynamicValue implements Advice.OffsetMapping.Factory {\n\n @Override\n public Class getAnnotationType() {\n return RequestName.class;\n }\n\n @Override\n public Advice.OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable annotation, AdviceType adviceType) {\n return new Advice.OffsetMapping() {\n\n @Override\n public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Advice.ArgumentHandler argumentHandler, Sort sort) {\n final String requestName = getRequestName(instrumentedMethod);\n if (requestName != null) {\n return Target.ForStackManipulation.of(requestName);\n } else {\n return new Target.ForStackManipulation(NullConstant.INSTANCE);\n }\n }\n };\n }\n }\n\n public static String getRequestName(MethodDescription instrumentedMethod) {\n final AnnotationDescription.Loadable monitorRequestsLoadable = instrumentedMethod.getDeclaredAnnotations().ofType(Traced.class);\n if (monitorRequestsLoadable != null) {\n final Traced traced = monitorRequestsLoadable.loadSilent();\n if (!traced.requestName().isEmpty()) {\n return traced.requestName();\n }\n if (traced.resolveNameAtRuntime()) {\n return null;\n }\n }\n return getBusinessTransationName(instrumentedMethod.getDeclaringType().getTypeName(), instrumentedMethod.getName());\n }\n\n private static String getBusinessTransationName(String className, String methodName) {\n return configuration.getConfig(TracingPlugin.class).getBusinessTransactionNamingStrategy().getBusinessTransactionName(className, methodName);\n }\n\n @Retention(RetentionPolicy.RUNTIME)\n @Target(ElementType.PARAMETER)\n public @interface ParameterNames {\n }\n\n public static class ParameterNamesDynamicValue implements Advice.OffsetMapping.Factory {\n\n @Override\n public Class getAnnotationType() {\n return ParameterNames.class;\n }\n\n @Override\n public Advice.OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable annotation, AdviceType adviceType) {\n return new Advice.OffsetMapping() {\n\n @Override\n public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Advice.ArgumentHandler argumentHandler, Sort sort) {\n final StringBuilder params = new StringBuilder();\n for (ParameterDescription param : instrumentedMethod.getParameters()) {\n params.append(param.getName()).append(',');\n }\n return Advice.OffsetMapping.Target.ForStackManipulation.of(params.toString());\n }\n };\n }\n }\n}\n"} {"task_id": "Java_2955", "language": "Java", "task_type": "single_line", "source_file": "java/github/stagemonitor/stagemonitor/stagemonitor-tracing/src/main/java/org/stagemonitor/tracing/AbstractTracingTransformer.java", "mask_start_position": 1630, "mask_end_position": 1639, "canonical_solution": "bject>();", "pre_mask_code": "package org.stagemonitor.tracing;\n\nimport net.bytebuddy.asm.Advice;\nimport net.bytebuddy.description.annotation.AnnotationDescription;\nimport net.bytebuddy.description.method.MethodDescription;\nimport net.bytebuddy.description.method.ParameterDescription;\nimport net.bytebuddy.description.type.TypeDescription;\nimport net.bytebuddy.implementation.bytecode.assign.Assigner;\nimport net.bytebuddy.implementation.bytecode.constant.NullConstant;\nimport org.stagemonitor.core.Stagemonitor;\nimport org.stagemonitor.core.instrument.StagemonitorByteBuddyTransformer;\nimport org.stagemonitor.tracing.metrics.MetricsSpanEventListener;\nimport java.lang.annotation.Annotation;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\nimport java.util.Arrays;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport io.opentracing.Span;\n\npublic class AbstractTracingTransformer extends StagemonitorByteBuddyTransformer {\n\n @Override\n protected Class getAdviceClass() {\n return AbstractTracingTransformer.class;\n }\n\n @Advice.OnMethodEnter(inline = false)\n public static void monitorStart(@ParameterNames String parameterNames, @Advice.AllArguments Object[] args, @RequestName String requestName, @Advice.Origin(\"#t\") String className, @Advice.Origin(\"#m\") String methodName, @Advice.This(optional = true) Object thiz) {\n final String[] paramNames = parameterNames.split(\",\");\n Map params = new LinkedHashMap> getOffsetMappingFactories() {\n final Advice.OffsetMapping.Factory requestNameDynamicValue = new RequestNameDynamicValue();\n return Arrays.asList(requestNameDynamicValue, new ParameterNamesDynamicValue());\n }\n\n @Retention(RetentionPolicy.RUNTIME)\n @Target(ElementType.PARAMETER)\n public @interface RequestName {\n }\n\n public static class RequestNameDynamicValue implements Advice.OffsetMapping.Factory {\n\n @Override\n public Class getAnnotationType() {\n return RequestName.class;\n }\n\n @Override\n public Advice.OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable annotation, AdviceType adviceType) {\n return new Advice.OffsetMapping() {\n\n @Override\n public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Advice.ArgumentHandler argumentHandler, Sort sort) {\n final String requestName = getRequestName(instrumentedMethod);\n if (requestName != null) {\n return Target.ForStackManipulation.of(requestName);\n } else {\n return new Target.ForStackManipulation(NullConstant.INSTANCE);\n }\n }\n };\n }\n }\n\n public static String getRequestName(MethodDescription instrumentedMethod) {\n final AnnotationDescription.Loadable monitorRequestsLoadable = instrumentedMethod.getDeclaredAnnotations().ofType(Traced.class);\n if (monitorRequestsLoadable != null) {\n final Traced traced = monitorRequestsLoadable.loadSilent();\n if (!traced.requestName().isEmpty()) {\n return traced.requestName();\n }\n if (traced.resolveNameAtRuntime()) {\n return null;\n }\n }\n return getBusinessTransationName(instrumentedMethod.getDeclaringType().getTypeName(), instrumentedMethod.getName());\n }\n\n private static String getBusinessTransationName(String className, String methodName) {\n return configuration.getConfig(TracingPlugin.class).getBusinessTransactionNamingStrategy().getBusinessTransactionName(className, methodName);\n }\n\n @Retention(RetentionPolicy.RUNTIME)\n @Target(ElementType.PARAMETER)\n public @interface ParameterNames {\n }\n\n public static class ParameterNamesDynamicValue implements Advice.OffsetMapping.Factory {\n\n @Override\n public Class getAnnotationType() {\n return ParameterNames.class;\n }\n\n @Override\n public Advice.OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable annotation, AdviceType adviceType) {\n return new Advice.OffsetMapping() {\n\n @Override\n public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Advice.ArgumentHandler argumentHandler, Sort sort) {\n final StringBuilder params = new StringBuilder();\n for (ParameterDescription param : instrumentedMethod.getParameters()) {\n params.append(param.getName()).append(',');\n }\n return Advice.OffsetMapping.Target.ForStackManipulation.of(params.toString());\n }\n };\n }\n }\n}\n"} {"task_id": "Java_2956", "language": "Java", "task_type": "for_statement", "source_file": "java/github/stagemonitor/stagemonitor/stagemonitor-tracing/src/main/java/org/stagemonitor/tracing/AbstractTracingTransformer.java", "mask_start_position": 1648, "mask_end_position": 1745, "canonical_solution": "for (int i = 0; i < args.length; i++) {\n params.put(paramNames[i], args[i]);\n }", "pre_mask_code": "package org.stagemonitor.tracing;\n\nimport net.bytebuddy.asm.Advice;\nimport net.bytebuddy.description.annotation.AnnotationDescription;\nimport net.bytebuddy.description.method.MethodDescription;\nimport net.bytebuddy.description.method.ParameterDescription;\nimport net.bytebuddy.description.type.TypeDescription;\nimport net.bytebuddy.implementation.bytecode.assign.Assigner;\nimport net.bytebuddy.implementation.bytecode.constant.NullConstant;\nimport org.stagemonitor.core.Stagemonitor;\nimport org.stagemonitor.core.instrument.StagemonitorByteBuddyTransformer;\nimport org.stagemonitor.tracing.metrics.MetricsSpanEventListener;\nimport java.lang.annotation.Annotation;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\nimport java.util.Arrays;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport io.opentracing.Span;\n\npublic class AbstractTracingTransformer extends StagemonitorByteBuddyTransformer {\n\n @Override\n protected Class getAdviceClass() {\n return AbstractTracingTransformer.class;\n }\n\n @Advice.OnMethodEnter(inline = false)\n public static void monitorStart(@ParameterNames String parameterNames, @Advice.AllArguments Object[] args, @RequestName String requestName, @Advice.Origin(\"#t\") String className, @Advice.Origin(\"#m\") String methodName, @Advice.This(optional = true) Object thiz) {\n final String[] paramNames = parameterNames.split(\",\");\n Map params = new LinkedHashMap();\n ", "post_mask_code": "\n final MonitoredMethodRequest monitoredRequest = new MonitoredMethodRequest(Stagemonitor.getConfiguration(), requestName, null, params);\n final TracingPlugin tracingPlugin = Stagemonitor.getPlugin(TracingPlugin.class);\n tracingPlugin.getRequestMonitor().monitorStart(monitoredRequest);\n final Span span = TracingPlugin.getCurrentSpan();\n if (requestName == null) {\n span.setOperationName(getBusinessTransationName(thiz != null ? thiz.getClass().getName() : className, methodName));\n }\n span.setTag(MetricsSpanEventListener.ENABLE_TRACKING_METRICS_TAG, true);\n }\n\n @Advice.OnMethodExit(onThrowable = Throwable.class, inline = false)\n public static void monitorStop(@Advice.Thrown Throwable exception) {\n final RequestMonitor requestMonitor = Stagemonitor.getPlugin(TracingPlugin.class).getRequestMonitor();\n if (exception != null && exception instanceof Exception) {\n requestMonitor.recordException((Exception) exception);\n }\n requestMonitor.monitorStop();\n }\n\n @Override\n protected int getOrder() {\n return Integer.MIN_VALUE;\n }\n\n @Override\n protected List> getOffsetMappingFactories() {\n final Advice.OffsetMapping.Factory requestNameDynamicValue = new RequestNameDynamicValue();\n return Arrays.asList(requestNameDynamicValue, new ParameterNamesDynamicValue());\n }\n\n @Retention(RetentionPolicy.RUNTIME)\n @Target(ElementType.PARAMETER)\n public @interface RequestName {\n }\n\n public static class RequestNameDynamicValue implements Advice.OffsetMapping.Factory {\n\n @Override\n public Class getAnnotationType() {\n return RequestName.class;\n }\n\n @Override\n public Advice.OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable annotation, AdviceType adviceType) {\n return new Advice.OffsetMapping() {\n\n @Override\n public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Advice.ArgumentHandler argumentHandler, Sort sort) {\n final String requestName = getRequestName(instrumentedMethod);\n if (requestName != null) {\n return Target.ForStackManipulation.of(requestName);\n } else {\n return new Target.ForStackManipulation(NullConstant.INSTANCE);\n }\n }\n };\n }\n }\n\n public static String getRequestName(MethodDescription instrumentedMethod) {\n final AnnotationDescription.Loadable monitorRequestsLoadable = instrumentedMethod.getDeclaredAnnotations().ofType(Traced.class);\n if (monitorRequestsLoadable != null) {\n final Traced traced = monitorRequestsLoadable.loadSilent();\n if (!traced.requestName().isEmpty()) {\n return traced.requestName();\n }\n if (traced.resolveNameAtRuntime()) {\n return null;\n }\n }\n return getBusinessTransationName(instrumentedMethod.getDeclaringType().getTypeName(), instrumentedMethod.getName());\n }\n\n private static String getBusinessTransationName(String className, String methodName) {\n return configuration.getConfig(TracingPlugin.class).getBusinessTransactionNamingStrategy().getBusinessTransactionName(className, methodName);\n }\n\n @Retention(RetentionPolicy.RUNTIME)\n @Target(ElementType.PARAMETER)\n public @interface ParameterNames {\n }\n\n public static class ParameterNamesDynamicValue implements Advice.OffsetMapping.Factory {\n\n @Override\n public Class getAnnotationType() {\n return ParameterNames.class;\n }\n\n @Override\n public Advice.OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable annotation, AdviceType adviceType) {\n return new Advice.OffsetMapping() {\n\n @Override\n public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Advice.ArgumentHandler argumentHandler, Sort sort) {\n final StringBuilder params = new StringBuilder();\n for (ParameterDescription param : instrumentedMethod.getParameters()) {\n params.append(param.getName()).append(',');\n }\n return Advice.OffsetMapping.Target.ForStackManipulation.of(params.toString());\n }\n };\n }\n }\n}\n"} {"task_id": "Java_2957", "language": "Java", "task_type": "method_signature", "source_file": "java/github/P3pp3rF1y/AncientWarfare2/src/main/java/net/shadowmage/ancientwarfare/structure/network/PacketHighlightBlock.java", "mask_start_position": 1007, "mask_end_position": 1073, "canonical_solution": "@Override\n @SideOnly(Side.CLIENT)\n protected void execute() ", "pre_mask_code": "package net.shadowmage.ancientwarfare.structure.network;\n\nimport io.netty.buffer.ByteBuf;\nimport net.minecraftforge.fml.relauncher.Side;\nimport net.minecraftforge.fml.relauncher.SideOnly;\nimport net.shadowmage.ancientwarfare.core.network.PacketBase;\nimport net.shadowmage.ancientwarfare.structure.render.BlockHighlightRenderer;\nimport net.shadowmage.ancientwarfare.structure.util.BlockHighlightInfo;\nimport java.io.IOException;\n\npublic class PacketHighlightBlock extends PacketBase {\n\n private BlockHighlightInfo blockHighlightInfo;\n\n public PacketHighlightBlock(BlockHighlightInfo blockHighlightInfo) {\n this.blockHighlightInfo = blockHighlightInfo;\n }\n\n public PacketHighlightBlock() {\n }\n\n @Override\n protected void writeToStream(ByteBuf data) {\n blockHighlightInfo.serializeToBuffer(data);\n }\n\n @Override\n protected void readFromStream(ByteBuf data) throws IOException {\n blockHighlightInfo = BlockHighlightInfo.deserializeFromBuffer(data);\n }\n\n ", "post_mask_code": "{\n BlockHighlightRenderer.setBlockHighlightInfo(blockHighlightInfo);\n }\n}\n"} {"task_id": "Java_2958", "language": "Java", "task_type": "method_body", "source_file": "java/github/P3pp3rF1y/AncientWarfare2/src/main/java/net/shadowmage/ancientwarfare/structure/network/PacketHighlightBlock.java", "mask_start_position": 1073, "mask_end_position": 1154, "canonical_solution": "{\n BlockHighlightRenderer.setBlockHighlightInfo(blockHighlightInfo);\n }", "pre_mask_code": "package net.shadowmage.ancientwarfare.structure.network;\n\nimport io.netty.buffer.ByteBuf;\nimport net.minecraftforge.fml.relauncher.Side;\nimport net.minecraftforge.fml.relauncher.SideOnly;\nimport net.shadowmage.ancientwarfare.core.network.PacketBase;\nimport net.shadowmage.ancientwarfare.structure.render.BlockHighlightRenderer;\nimport net.shadowmage.ancientwarfare.structure.util.BlockHighlightInfo;\nimport java.io.IOException;\n\npublic class PacketHighlightBlock extends PacketBase {\n\n private BlockHighlightInfo blockHighlightInfo;\n\n public PacketHighlightBlock(BlockHighlightInfo blockHighlightInfo) {\n this.blockHighlightInfo = blockHighlightInfo;\n }\n\n public PacketHighlightBlock() {\n }\n\n @Override\n protected void writeToStream(ByteBuf data) {\n blockHighlightInfo.serializeToBuffer(data);\n }\n\n @Override\n protected void readFromStream(ByteBuf data) throws IOException {\n blockHighlightInfo = BlockHighlightInfo.deserializeFromBuffer(data);\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n protected void execute() ", "post_mask_code": "\n}\n"} {"task_id": "Java_2959", "language": "Java", "task_type": "single_line", "source_file": "java/github/P3pp3rF1y/AncientWarfare2/src/main/java/net/shadowmage/ancientwarfare/structure/network/PacketHighlightBlock.java", "mask_start_position": 994, "mask_end_position": 995, "canonical_solution": ";", "pre_mask_code": "package net.shadowmage.ancientwarfare.structure.network;\n\nimport io.netty.buffer.ByteBuf;\nimport net.minecraftforge.fml.relauncher.Side;\nimport net.minecraftforge.fml.relauncher.SideOnly;\nimport net.shadowmage.ancientwarfare.core.network.PacketBase;\nimport net.shadowmage.ancientwarfare.structure.render.BlockHighlightRenderer;\nimport net.shadowmage.ancientwarfare.structure.util.BlockHighlightInfo;\nimport java.io.IOException;\n\npublic class PacketHighlightBlock extends PacketBase {\n\n private BlockHighlightInfo blockHighlightInfo;\n\n public PacketHighlightBlock(BlockHighlightInfo blockHighlightInfo) {\n this.blockHighlightInfo = blockHighlightInfo;\n }\n\n public PacketHighlightBlock() {\n }\n\n @Override\n protected void writeToStream(ByteBuf data) {\n blockHighlightInfo.serializeToBuffer(data);\n }\n\n @Override\n protected void readFromStream(ByteBuf data) throws IOException {\n blockHighlightInfo = BlockHighlightInfo.deserializeFromBuffer(data)", "post_mask_code": "\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n protected void execute() {\n BlockHighlightRenderer.setBlockHighlightInfo(blockHighlightInfo);\n }\n}\n"} {"task_id": "Java_2960", "language": "Java", "task_type": "method_signature", "source_file": "java/github/aliyun/aliyun-openapi-java-sdk/aliyun-java-sdk-oam/src/main/java/com/aliyuncs/oam/model/v20170101/AddUserToGroupResponse.java", "mask_start_position": 369, "mask_end_position": 393, "canonical_solution": "public String getCode() ", "pre_mask_code": "package com.aliyuncs.oam.model.v20170101;\n\nimport com.aliyuncs.AcsResponse;\nimport com.aliyuncs.oam.transform.v20170101.AddUserToGroupResponseUnmarshaller;\nimport com.aliyuncs.transform.UnmarshallerContext;\n\n/**\n * @author auto create\n * @version\n */\npublic class AddUserToGroupResponse extends AcsResponse {\n\n private String code;\n\n private String message;\n\n ", "post_mask_code": "{\n return this.code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getMessage() {\n return this.message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n @Override\n public AddUserToGroupResponse getInstance(UnmarshallerContext context) {\n return AddUserToGroupResponseUnmarshaller.unmarshall(this, context);\n }\n}\n"} {"task_id": "Java_2961", "language": "Java", "task_type": "method_body", "source_file": "java/github/aliyun/aliyun-openapi-java-sdk/aliyun-java-sdk-oam/src/main/java/com/aliyuncs/oam/model/v20170101/AddUserToGroupResponse.java", "mask_start_position": 742, "mask_end_position": 826, "canonical_solution": "{\n return AddUserToGroupResponseUnmarshaller.unmarshall(this, context);\n }", "pre_mask_code": "package com.aliyuncs.oam.model.v20170101;\n\nimport com.aliyuncs.AcsResponse;\nimport com.aliyuncs.oam.transform.v20170101.AddUserToGroupResponseUnmarshaller;\nimport com.aliyuncs.transform.UnmarshallerContext;\n\n/**\n * @author auto create\n * @version\n */\npublic class AddUserToGroupResponse extends AcsResponse {\n\n private String code;\n\n private String message;\n\n public String getCode() {\n return this.code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getMessage() {\n return this.message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n @Override\n public AddUserToGroupResponse getInstance(UnmarshallerContext context) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2962", "language": "Java", "task_type": "single_line", "source_file": "java/github/aliyun/aliyun-openapi-java-sdk/aliyun-java-sdk-oam/src/main/java/com/aliyuncs/oam/model/v20170101/AddUserToGroupResponse.java", "mask_start_position": 629, "mask_end_position": 645, "canonical_solution": "ssage = message;", "pre_mask_code": "package com.aliyuncs.oam.model.v20170101;\n\nimport com.aliyuncs.AcsResponse;\nimport com.aliyuncs.oam.transform.v20170101.AddUserToGroupResponseUnmarshaller;\nimport com.aliyuncs.transform.UnmarshallerContext;\n\n/**\n * @author auto create\n * @version\n */\npublic class AddUserToGroupResponse extends AcsResponse {\n\n private String code;\n\n private String message;\n\n public String getCode() {\n return this.code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getMessage() {\n return this.message;\n }\n\n public void setMessage(String message) {\n this.me", "post_mask_code": "\n }\n\n @Override\n public AddUserToGroupResponse getInstance(UnmarshallerContext context) {\n return AddUserToGroupResponseUnmarshaller.unmarshall(this, context);\n }\n}\n"} {"task_id": "Java_2963", "language": "Java", "task_type": "method_signature", "source_file": "java/github/TerraFirmaCraft/TerraFirmaCraft/src/main/java/net/dries007/tfc/network/FoodDataReplacePacket.java", "mask_start_position": 471, "mask_end_position": 513, "canonical_solution": "void handle(NetworkEvent.Context context) ", "pre_mask_code": "/*\n * You may obtain a copy of the Licence at:\n * http://example.com\n */\npackage net.dries007.tfc.network;\n\nimport net.minecraft.world.entity.player.Player;\nimport net.minecraftforge.fmllegacy.network.NetworkEvent;\nimport net.dries007.tfc.client.ClientHelpers;\nimport net.dries007.tfc.common.capabilities.food.TFCFoodData;\n\n/**\n * A packet that signals to the client it needs to replace the client player's food stats object\n */\npublic class FoodDataReplacePacket {\n\n ", "post_mask_code": "{\n context.enqueueWork(() -> {\n final Player player = ClientHelpers.getPlayer();\n if (player != null) {\n TFCFoodData.replaceFoodStats(player);\n }\n });\n }\n}\n"} {"task_id": "Java_2964", "language": "Java", "task_type": "method_body", "source_file": "java/github/TerraFirmaCraft/TerraFirmaCraft/src/main/java/net/dries007/tfc/network/FoodDataReplacePacket.java", "mask_start_position": 513, "mask_end_position": 731, "canonical_solution": "{\n context.enqueueWork(() -> {\n final Player player = ClientHelpers.getPlayer();\n if (player != null) {\n TFCFoodData.replaceFoodStats(player);\n }\n });\n }", "pre_mask_code": "/*\n * You may obtain a copy of the Licence at:\n * http://example.com\n */\npackage net.dries007.tfc.network;\n\nimport net.minecraft.world.entity.player.Player;\nimport net.minecraftforge.fmllegacy.network.NetworkEvent;\nimport net.dries007.tfc.client.ClientHelpers;\nimport net.dries007.tfc.common.capabilities.food.TFCFoodData;\n\n/**\n * A packet that signals to the client it needs to replace the client player's food stats object\n */\npublic class FoodDataReplacePacket {\n\n void handle(NetworkEvent.Context context) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2965", "language": "Java", "task_type": "method_signature", "source_file": "java/github/consulo/consulo/modules/base/vcs-api/src/main/java/com/intellij/openapi/vcs/OutgoingChangesUtil.java", "mask_start_position": 408, "mask_end_position": 598, "canonical_solution": "public static Collection>> getVcsRootsForChanges(final AbstractVcs vcs, final Collection changes) throws VcsException ", "pre_mask_code": "package com.intellij.openapi.vcs;\n\nimport com.intellij.openapi.util.Pair;\nimport com.intellij.openapi.vcs.changes.Change;\nimport com.intellij.openapi.vcs.changes.ChangesUtil;\nimport com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;\nimport com.intellij.openapi.vcs.history.VcsRevisionNumber;\nimport com.intellij.openapi.vfs.VirtualFile;\nimport java.util.*;\n\npublic class OutgoingChangesUtil {\n\n ", "post_mask_code": "{\n final ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(vcs.getProject());\n final VcsOutgoingChangesProvider provider = vcs.getOutgoingChangesProvider();\n if (provider == null)\n return Collections.emptyList();\n final VirtualFile[] files = ChangesUtil.getFilesFromChanges(changes);\n final Set roots = new HashSet();\n for (VirtualFile file : files) {\n final VirtualFile root = vcsManager.getVcsRootFor(file);\n if (root != null) {\n roots.add(root);\n }\n }\n final Collection>> result = new ArrayList>>(roots.size());\n for (VirtualFile root : roots) {\n final Pair> pair = provider.getOutgoingChanges(root, true);\n result.add(pair);\n }\n return result;\n }\n}\n"} {"task_id": "Java_2966", "language": "Java", "task_type": "single_line", "source_file": "java/github/consulo/consulo/modules/base/vcs-api/src/main/java/com/intellij/openapi/vcs/OutgoingChangesUtil.java", "mask_start_position": 987, "mask_end_position": 1008, "canonical_solution": "shSet();", "pre_mask_code": "package com.intellij.openapi.vcs;\n\nimport com.intellij.openapi.util.Pair;\nimport com.intellij.openapi.vcs.changes.Change;\nimport com.intellij.openapi.vcs.changes.ChangesUtil;\nimport com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;\nimport com.intellij.openapi.vcs.history.VcsRevisionNumber;\nimport com.intellij.openapi.vfs.VirtualFile;\nimport java.util.*;\n\npublic class OutgoingChangesUtil {\n\n public static Collection>> getVcsRootsForChanges(final AbstractVcs vcs, final Collection changes) throws VcsException {\n final ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(vcs.getProject());\n final VcsOutgoingChangesProvider provider = vcs.getOutgoingChangesProvider();\n if (provider == null)\n return Collections.emptyList();\n final VirtualFile[] files = ChangesUtil.getFilesFromChanges(changes);\n final Set roots = new Ha", "post_mask_code": "\n for (VirtualFile file : files) {\n final VirtualFile root = vcsManager.getVcsRootFor(file);\n if (root != null) {\n roots.add(root);\n }\n }\n final Collection>> result = new ArrayList>>(roots.size());\n for (VirtualFile root : roots) {\n final Pair> pair = provider.getOutgoingChanges(root, true);\n result.add(pair);\n }\n return result;\n }\n}\n"} {"task_id": "Java_2967", "language": "Java", "task_type": "method_signature", "source_file": "java/github/libetl/soundtransform/src/main/java/org/toilelibre/libe/soundtransform/infrastructure/service/converted/sound/transforms/GaussianEqualizerSoundTransform.java", "mask_start_position": 825, "mask_end_position": 866, "canonical_solution": "private Complex function(final double x) ", "pre_mask_code": "package org.toilelibre.libe.soundtransform.infrastructure.service.converted.sound.transforms;\n\nimport org.apache.commons.math3.complex.Complex;\nimport org.toilelibre.libe.soundtransform.model.converted.FormatInfo;\nimport org.toilelibre.libe.soundtransform.model.converted.sound.transform.SimpleFrequencySoundTransform;\nimport org.toilelibre.libe.soundtransform.model.converted.spectrum.Spectrum;\n\n/**\n * Equalizer which cuts the treble and the bass frequencies of a sound\n */\npublic class GaussianEqualizerSoundTransform extends SimpleFrequencySoundTransform {\n\n private static final int DELTA_X = 3500;\n\n private static final int EXPONENT = 2;\n\n private static final int DIVISION = 1000;\n\n private static final int HALF = 2;\n\n public GaussianEqualizerSoundTransform() {\n super();\n }\n\n ", "post_mask_code": "{\n return new Complex(1 - Math.exp(-Math.pow(x - GaussianEqualizerSoundTransform.DELTA_X, GaussianEqualizerSoundTransform.EXPONENT) / GaussianEqualizerSoundTransform.DIVISION) / GaussianEqualizerSoundTransform.HALF);\n }\n\n @Override\n public Spectrum transformFrequencies(final Spectrum fs, final int offset, final int powOf2NearestLength, final int length) {\n final Complex[] newAmpl = new Complex[powOf2NearestLength];\n for (double j = 0; j < length; j++) {\n final double freq = j * fs.getSampleRate() / fs.getState().length;\n newAmpl[(int) j] = fs.getState()[(int) j].multiply(this.function(freq));\n }\n for (int j = length; j < powOf2NearestLength; j++) {\n newAmpl[j] = new Complex(0, 0);\n }\n return new Spectrum(newAmpl, new FormatInfo(fs.getSampleSize(), fs.getSampleRate()));\n }\n}\n"} {"task_id": "Java_2968", "language": "Java", "task_type": "method_body", "source_file": "java/github/libetl/soundtransform/src/main/java/org/toilelibre/libe/soundtransform/infrastructure/service/converted/sound/transforms/GaussianEqualizerSoundTransform.java", "mask_start_position": 866, "mask_end_position": 1095, "canonical_solution": "{\n return new Complex(1 - Math.exp(-Math.pow(x - GaussianEqualizerSoundTransform.DELTA_X, GaussianEqualizerSoundTransform.EXPONENT) / GaussianEqualizerSoundTransform.DIVISION) / GaussianEqualizerSoundTransform.HALF);\n }", "pre_mask_code": "package org.toilelibre.libe.soundtransform.infrastructure.service.converted.sound.transforms;\n\nimport org.apache.commons.math3.complex.Complex;\nimport org.toilelibre.libe.soundtransform.model.converted.FormatInfo;\nimport org.toilelibre.libe.soundtransform.model.converted.sound.transform.SimpleFrequencySoundTransform;\nimport org.toilelibre.libe.soundtransform.model.converted.spectrum.Spectrum;\n\n/**\n * Equalizer which cuts the treble and the bass frequencies of a sound\n */\npublic class GaussianEqualizerSoundTransform extends SimpleFrequencySoundTransform {\n\n private static final int DELTA_X = 3500;\n\n private static final int EXPONENT = 2;\n\n private static final int DIVISION = 1000;\n\n private static final int HALF = 2;\n\n public GaussianEqualizerSoundTransform() {\n super();\n }\n\n private Complex function(final double x) ", "post_mask_code": "\n\n @Override\n public Spectrum transformFrequencies(final Spectrum fs, final int offset, final int powOf2NearestLength, final int length) {\n final Complex[] newAmpl = new Complex[powOf2NearestLength];\n for (double j = 0; j < length; j++) {\n final double freq = j * fs.getSampleRate() / fs.getState().length;\n newAmpl[(int) j] = fs.getState()[(int) j].multiply(this.function(freq));\n }\n for (int j = length; j < powOf2NearestLength; j++) {\n newAmpl[j] = new Complex(0, 0);\n }\n return new Spectrum(newAmpl, new FormatInfo(fs.getSampleSize(), fs.getSampleRate()));\n }\n}\n"} {"task_id": "Java_2969", "language": "Java", "task_type": "single_line", "source_file": "java/github/libetl/soundtransform/src/main/java/org/toilelibre/libe/soundtransform/infrastructure/service/converted/sound/transforms/GaussianEqualizerSoundTransform.java", "mask_start_position": 1313, "mask_end_position": 1329, "canonical_solution": "2NearestLength];", "pre_mask_code": "package org.toilelibre.libe.soundtransform.infrastructure.service.converted.sound.transforms;\n\nimport org.apache.commons.math3.complex.Complex;\nimport org.toilelibre.libe.soundtransform.model.converted.FormatInfo;\nimport org.toilelibre.libe.soundtransform.model.converted.sound.transform.SimpleFrequencySoundTransform;\nimport org.toilelibre.libe.soundtransform.model.converted.spectrum.Spectrum;\n\n/**\n * Equalizer which cuts the treble and the bass frequencies of a sound\n */\npublic class GaussianEqualizerSoundTransform extends SimpleFrequencySoundTransform {\n\n private static final int DELTA_X = 3500;\n\n private static final int EXPONENT = 2;\n\n private static final int DIVISION = 1000;\n\n private static final int HALF = 2;\n\n public GaussianEqualizerSoundTransform() {\n super();\n }\n\n private Complex function(final double x) {\n return new Complex(1 - Math.exp(-Math.pow(x - GaussianEqualizerSoundTransform.DELTA_X, GaussianEqualizerSoundTransform.EXPONENT) / GaussianEqualizerSoundTransform.DIVISION) / GaussianEqualizerSoundTransform.HALF);\n }\n\n @Override\n public Spectrum transformFrequencies(final Spectrum fs, final int offset, final int powOf2NearestLength, final int length) {\n final Complex[] newAmpl = new Complex[powOf", "post_mask_code": "\n for (double j = 0; j < length; j++) {\n final double freq = j * fs.getSampleRate() / fs.getState().length;\n newAmpl[(int) j] = fs.getState()[(int) j].multiply(this.function(freq));\n }\n for (int j = length; j < powOf2NearestLength; j++) {\n newAmpl[j] = new Complex(0, 0);\n }\n return new Spectrum(newAmpl, new FormatInfo(fs.getSampleSize(), fs.getSampleRate()));\n }\n}\n"} {"task_id": "Java_2970", "language": "Java", "task_type": "for_statement", "source_file": "java/github/libetl/soundtransform/src/main/java/org/toilelibre/libe/soundtransform/infrastructure/service/converted/sound/transforms/GaussianEqualizerSoundTransform.java", "mask_start_position": 1338, "mask_end_position": 1549, "canonical_solution": "for (double j = 0; j < length; j++) {\n final double freq = j * fs.getSampleRate() / fs.getState().length;\n newAmpl[(int) j] = fs.getState()[(int) j].multiply(this.function(freq));\n }", "pre_mask_code": "package org.toilelibre.libe.soundtransform.infrastructure.service.converted.sound.transforms;\n\nimport org.apache.commons.math3.complex.Complex;\nimport org.toilelibre.libe.soundtransform.model.converted.FormatInfo;\nimport org.toilelibre.libe.soundtransform.model.converted.sound.transform.SimpleFrequencySoundTransform;\nimport org.toilelibre.libe.soundtransform.model.converted.spectrum.Spectrum;\n\n/**\n * Equalizer which cuts the treble and the bass frequencies of a sound\n */\npublic class GaussianEqualizerSoundTransform extends SimpleFrequencySoundTransform {\n\n private static final int DELTA_X = 3500;\n\n private static final int EXPONENT = 2;\n\n private static final int DIVISION = 1000;\n\n private static final int HALF = 2;\n\n public GaussianEqualizerSoundTransform() {\n super();\n }\n\n private Complex function(final double x) {\n return new Complex(1 - Math.exp(-Math.pow(x - GaussianEqualizerSoundTransform.DELTA_X, GaussianEqualizerSoundTransform.EXPONENT) / GaussianEqualizerSoundTransform.DIVISION) / GaussianEqualizerSoundTransform.HALF);\n }\n\n @Override\n public Spectrum transformFrequencies(final Spectrum fs, final int offset, final int powOf2NearestLength, final int length) {\n final Complex[] newAmpl = new Complex[powOf2NearestLength];\n ", "post_mask_code": "\n for (int j = length; j < powOf2NearestLength; j++) {\n newAmpl[j] = new Complex(0, 0);\n }\n return new Spectrum(newAmpl, new FormatInfo(fs.getSampleSize(), fs.getSampleRate()));\n }\n}\n"} {"task_id": "Java_2971", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/rocketmq-externals/rocketmq-connect-jms/src/main/java/org/apache/rocketmq/connect/jms/connector/BaseJmsSourceTask.java", "mask_start_position": 1365, "mask_end_position": 1421, "canonical_solution": "@Override\n public Collection poll() ", "pre_mask_code": "package org.apache.rocketmq.connect.jms.connector;\n\nimport java.io.ByteArrayOutputStream;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\nimport javax.jms.BytesMessage;\nimport javax.jms.JMSException;\nimport javax.jms.MapMessage;\nimport javax.jms.Message;\nimport javax.jms.ObjectMessage;\nimport javax.jms.StreamMessage;\nimport javax.jms.TextMessage;\nimport org.apache.rocketmq.connect.jms.Config;\nimport org.apache.rocketmq.connect.jms.ErrorCode;\nimport org.apache.rocketmq.connect.jms.Replicator;\nimport org.apache.rocketmq.connect.jms.pattern.PatternProcessor;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.alibaba.fastjson.JSON;\nimport io.openmessaging.KeyValue;\nimport io.openmessaging.connector.api.data.EntryType;\nimport io.openmessaging.connector.api.data.SourceDataEntry;\nimport io.openmessaging.connector.api.exception.DataConnectException;\nimport io.openmessaging.connector.api.source.SourceTask;\n\npublic abstract class BaseJmsSourceTask extends SourceTask {\n\n private static final Logger log = LoggerFactory.getLogger(BaseJmsSourceTask.class);\n\n private Replicator replicator;\n\n private Config config;\n\n private ByteBuffer sourcePartition;\n\n ", "post_mask_code": "{\n List res = new ArrayList<>();\n try {\n Message message = replicator.getQueue().poll(1000, TimeUnit.MILLISECONDS);\n if (message != null) {\n Object[] payload = new Object[] { config.getDestinationType(), config.getDestinationName(), getMessageContent(message) };\n SourceDataEntry sourceDataEntry = new SourceDataEntry(sourcePartition, null, System.currentTimeMillis(), EntryType.CREATE, null, null, payload);\n res.add(sourceDataEntry);\n }\n } catch (Exception e) {\n log.error(\"activemq task poll error, current config:\" + JSON.toJSONString(config), e);\n }\n return res;\n }\n\n @Override\n public void start(KeyValue props) {\n try {\n this.config = new Config();\n this.config.load(props);\n this.sourcePartition = ByteBuffer.wrap(config.getBrokerUrl().getBytes(\"UTF-8\"));\n this.replicator.start();\n } catch (Exception e) {\n log.error(\"activemq task start failed.\", e);\n throw new DataConnectException(ErrorCode.START_ERROR_CODE, e.getMessage(), e);\n }\n }\n\n @Override\n public void stop() {\n try {\n replicator.stop();\n } catch (Exception e) {\n log.error(\"activemq task stop failed.\", e);\n throw new DataConnectException(ErrorCode.STOP_ERROR_CODE, e.getMessage(), e);\n }\n }\n\n @Override\n public void pause() {\n }\n\n @Override\n public void resume() {\n }\n\n @SuppressWarnings(\"unchecked\")\n public ByteBuffer getMessageContent(Message message) throws JMSException {\n byte[] data = null;\n if (message instanceof TextMessage) {\n data = ((TextMessage) message).getText().getBytes();\n } else if (message instanceof ObjectMessage) {\n data = JSON.toJSONBytes(((ObjectMessage) message).getObject());\n } else if (message instanceof BytesMessage) {\n BytesMessage bytesMessage = (BytesMessage) message;\n data = new byte[(int) bytesMessage.getBodyLength()];\n bytesMessage.readBytes(data);\n } else if (message instanceof MapMessage) {\n MapMessage mapMessage = (MapMessage) message;\n Map map = new HashMap<>();\n Enumeration names = mapMessage.getMapNames();\n while (names.hasMoreElements()) {\n String name = names.nextElement().toString();\n map.put(name, mapMessage.getObject(name));\n }\n data = JSON.toJSONBytes(map);\n } else if (message instanceof StreamMessage) {\n StreamMessage streamMessage = (StreamMessage) message;\n ByteArrayOutputStream bis = new ByteArrayOutputStream();\n byte[] by = new byte[1024];\n int i = 0;\n while ((i = streamMessage.readBytes(by)) != -1) {\n bis.write(by, 0, i);\n }\n data = bis.toByteArray();\n } else {\n // The exception is printed and does not need to be written as a DataConnectException\n throw new RuntimeException(\"message type exception\");\n }\n return ByteBuffer.wrap(data);\n }\n\n public abstract Config getConfig();\n\n public abstract PatternProcessor getPatternProcessor(Replicator replicator);\n}\n"} {"task_id": "Java_2972", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/rocketmq-externals/rocketmq-connect-jms/src/main/java/org/apache/rocketmq/connect/jms/connector/BaseJmsSourceTask.java", "mask_start_position": 2189, "mask_end_position": 2607, "canonical_solution": "{\n try {\n this.config = new Config();\n this.config.load(props);\n this.sourcePartition = ByteBuffer.wrap(config.getBrokerUrl().getBytes(\"UTF-8\"));\n this.replicator.start();\n } catch (Exception e) {\n log.error(\"activemq task start failed.\", e);\n throw new DataConnectException(ErrorCode.START_ERROR_CODE, e.getMessage(), e);\n }\n }", "pre_mask_code": "package org.apache.rocketmq.connect.jms.connector;\n\nimport java.io.ByteArrayOutputStream;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\nimport javax.jms.BytesMessage;\nimport javax.jms.JMSException;\nimport javax.jms.MapMessage;\nimport javax.jms.Message;\nimport javax.jms.ObjectMessage;\nimport javax.jms.StreamMessage;\nimport javax.jms.TextMessage;\nimport org.apache.rocketmq.connect.jms.Config;\nimport org.apache.rocketmq.connect.jms.ErrorCode;\nimport org.apache.rocketmq.connect.jms.Replicator;\nimport org.apache.rocketmq.connect.jms.pattern.PatternProcessor;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.alibaba.fastjson.JSON;\nimport io.openmessaging.KeyValue;\nimport io.openmessaging.connector.api.data.EntryType;\nimport io.openmessaging.connector.api.data.SourceDataEntry;\nimport io.openmessaging.connector.api.exception.DataConnectException;\nimport io.openmessaging.connector.api.source.SourceTask;\n\npublic abstract class BaseJmsSourceTask extends SourceTask {\n\n private static final Logger log = LoggerFactory.getLogger(BaseJmsSourceTask.class);\n\n private Replicator replicator;\n\n private Config config;\n\n private ByteBuffer sourcePartition;\n\n @Override\n public Collection poll() {\n List res = new ArrayList<>();\n try {\n Message message = replicator.getQueue().poll(1000, TimeUnit.MILLISECONDS);\n if (message != null) {\n Object[] payload = new Object[] { config.getDestinationType(), config.getDestinationName(), getMessageContent(message) };\n SourceDataEntry sourceDataEntry = new SourceDataEntry(sourcePartition, null, System.currentTimeMillis(), EntryType.CREATE, null, null, payload);\n res.add(sourceDataEntry);\n }\n } catch (Exception e) {\n log.error(\"activemq task poll error, current config:\" + JSON.toJSONString(config), e);\n }\n return res;\n }\n\n @Override\n public void start(KeyValue props) ", "post_mask_code": "\n\n @Override\n public void stop() {\n try {\n replicator.stop();\n } catch (Exception e) {\n log.error(\"activemq task stop failed.\", e);\n throw new DataConnectException(ErrorCode.STOP_ERROR_CODE, e.getMessage(), e);\n }\n }\n\n @Override\n public void pause() {\n }\n\n @Override\n public void resume() {\n }\n\n @SuppressWarnings(\"unchecked\")\n public ByteBuffer getMessageContent(Message message) throws JMSException {\n byte[] data = null;\n if (message instanceof TextMessage) {\n data = ((TextMessage) message).getText().getBytes();\n } else if (message instanceof ObjectMessage) {\n data = JSON.toJSONBytes(((ObjectMessage) message).getObject());\n } else if (message instanceof BytesMessage) {\n BytesMessage bytesMessage = (BytesMessage) message;\n data = new byte[(int) bytesMessage.getBodyLength()];\n bytesMessage.readBytes(data);\n } else if (message instanceof MapMessage) {\n MapMessage mapMessage = (MapMessage) message;\n Map map = new HashMap<>();\n Enumeration names = mapMessage.getMapNames();\n while (names.hasMoreElements()) {\n String name = names.nextElement().toString();\n map.put(name, mapMessage.getObject(name));\n }\n data = JSON.toJSONBytes(map);\n } else if (message instanceof StreamMessage) {\n StreamMessage streamMessage = (StreamMessage) message;\n ByteArrayOutputStream bis = new ByteArrayOutputStream();\n byte[] by = new byte[1024];\n int i = 0;\n while ((i = streamMessage.readBytes(by)) != -1) {\n bis.write(by, 0, i);\n }\n data = bis.toByteArray();\n } else {\n // The exception is printed and does not need to be written as a DataConnectException\n throw new RuntimeException(\"message type exception\");\n }\n return ByteBuffer.wrap(data);\n }\n\n public abstract Config getConfig();\n\n public abstract PatternProcessor getPatternProcessor(Replicator replicator);\n}\n"} {"task_id": "Java_2973", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/rocketmq-externals/rocketmq-connect-jms/src/main/java/org/apache/rocketmq/connect/jms/connector/BaseJmsSourceTask.java", "mask_start_position": 3109, "mask_end_position": 3124, "canonical_solution": "[] data = null;", "pre_mask_code": "package org.apache.rocketmq.connect.jms.connector;\n\nimport java.io.ByteArrayOutputStream;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\nimport javax.jms.BytesMessage;\nimport javax.jms.JMSException;\nimport javax.jms.MapMessage;\nimport javax.jms.Message;\nimport javax.jms.ObjectMessage;\nimport javax.jms.StreamMessage;\nimport javax.jms.TextMessage;\nimport org.apache.rocketmq.connect.jms.Config;\nimport org.apache.rocketmq.connect.jms.ErrorCode;\nimport org.apache.rocketmq.connect.jms.Replicator;\nimport org.apache.rocketmq.connect.jms.pattern.PatternProcessor;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.alibaba.fastjson.JSON;\nimport io.openmessaging.KeyValue;\nimport io.openmessaging.connector.api.data.EntryType;\nimport io.openmessaging.connector.api.data.SourceDataEntry;\nimport io.openmessaging.connector.api.exception.DataConnectException;\nimport io.openmessaging.connector.api.source.SourceTask;\n\npublic abstract class BaseJmsSourceTask extends SourceTask {\n\n private static final Logger log = LoggerFactory.getLogger(BaseJmsSourceTask.class);\n\n private Replicator replicator;\n\n private Config config;\n\n private ByteBuffer sourcePartition;\n\n @Override\n public Collection poll() {\n List res = new ArrayList<>();\n try {\n Message message = replicator.getQueue().poll(1000, TimeUnit.MILLISECONDS);\n if (message != null) {\n Object[] payload = new Object[] { config.getDestinationType(), config.getDestinationName(), getMessageContent(message) };\n SourceDataEntry sourceDataEntry = new SourceDataEntry(sourcePartition, null, System.currentTimeMillis(), EntryType.CREATE, null, null, payload);\n res.add(sourceDataEntry);\n }\n } catch (Exception e) {\n log.error(\"activemq task poll error, current config:\" + JSON.toJSONString(config), e);\n }\n return res;\n }\n\n @Override\n public void start(KeyValue props) {\n try {\n this.config = new Config();\n this.config.load(props);\n this.sourcePartition = ByteBuffer.wrap(config.getBrokerUrl().getBytes(\"UTF-8\"));\n this.replicator.start();\n } catch (Exception e) {\n log.error(\"activemq task start failed.\", e);\n throw new DataConnectException(ErrorCode.START_ERROR_CODE, e.getMessage(), e);\n }\n }\n\n @Override\n public void stop() {\n try {\n replicator.stop();\n } catch (Exception e) {\n log.error(\"activemq task stop failed.\", e);\n throw new DataConnectException(ErrorCode.STOP_ERROR_CODE, e.getMessage(), e);\n }\n }\n\n @Override\n public void pause() {\n }\n\n @Override\n public void resume() {\n }\n\n @SuppressWarnings(\"unchecked\")\n public ByteBuffer getMessageContent(Message message) throws JMSException {\n byte", "post_mask_code": "\n if (message instanceof TextMessage) {\n data = ((TextMessage) message).getText().getBytes();\n } else if (message instanceof ObjectMessage) {\n data = JSON.toJSONBytes(((ObjectMessage) message).getObject());\n } else if (message instanceof BytesMessage) {\n BytesMessage bytesMessage = (BytesMessage) message;\n data = new byte[(int) bytesMessage.getBodyLength()];\n bytesMessage.readBytes(data);\n } else if (message instanceof MapMessage) {\n MapMessage mapMessage = (MapMessage) message;\n Map map = new HashMap<>();\n Enumeration names = mapMessage.getMapNames();\n while (names.hasMoreElements()) {\n String name = names.nextElement().toString();\n map.put(name, mapMessage.getObject(name));\n }\n data = JSON.toJSONBytes(map);\n } else if (message instanceof StreamMessage) {\n StreamMessage streamMessage = (StreamMessage) message;\n ByteArrayOutputStream bis = new ByteArrayOutputStream();\n byte[] by = new byte[1024];\n int i = 0;\n while ((i = streamMessage.readBytes(by)) != -1) {\n bis.write(by, 0, i);\n }\n data = bis.toByteArray();\n } else {\n // The exception is printed and does not need to be written as a DataConnectException\n throw new RuntimeException(\"message type exception\");\n }\n return ByteBuffer.wrap(data);\n }\n\n public abstract Config getConfig();\n\n public abstract PatternProcessor getPatternProcessor(Replicator replicator);\n}\n"} {"task_id": "Java_2974", "language": "Java", "task_type": "while_statement", "source_file": "java/github/apache/rocketmq-externals/rocketmq-connect-jms/src/main/java/org/apache/rocketmq/connect/jms/connector/BaseJmsSourceTask.java", "mask_start_position": 3835, "mask_end_position": 4003, "canonical_solution": "while (names.hasMoreElements()) {\n String name = names.nextElement().toString();\n map.put(name, mapMessage.getObject(name));\n }", "pre_mask_code": "package org.apache.rocketmq.connect.jms.connector;\n\nimport java.io.ByteArrayOutputStream;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\nimport javax.jms.BytesMessage;\nimport javax.jms.JMSException;\nimport javax.jms.MapMessage;\nimport javax.jms.Message;\nimport javax.jms.ObjectMessage;\nimport javax.jms.StreamMessage;\nimport javax.jms.TextMessage;\nimport org.apache.rocketmq.connect.jms.Config;\nimport org.apache.rocketmq.connect.jms.ErrorCode;\nimport org.apache.rocketmq.connect.jms.Replicator;\nimport org.apache.rocketmq.connect.jms.pattern.PatternProcessor;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.alibaba.fastjson.JSON;\nimport io.openmessaging.KeyValue;\nimport io.openmessaging.connector.api.data.EntryType;\nimport io.openmessaging.connector.api.data.SourceDataEntry;\nimport io.openmessaging.connector.api.exception.DataConnectException;\nimport io.openmessaging.connector.api.source.SourceTask;\n\npublic abstract class BaseJmsSourceTask extends SourceTask {\n\n private static final Logger log = LoggerFactory.getLogger(BaseJmsSourceTask.class);\n\n private Replicator replicator;\n\n private Config config;\n\n private ByteBuffer sourcePartition;\n\n @Override\n public Collection poll() {\n List res = new ArrayList<>();\n try {\n Message message = replicator.getQueue().poll(1000, TimeUnit.MILLISECONDS);\n if (message != null) {\n Object[] payload = new Object[] { config.getDestinationType(), config.getDestinationName(), getMessageContent(message) };\n SourceDataEntry sourceDataEntry = new SourceDataEntry(sourcePartition, null, System.currentTimeMillis(), EntryType.CREATE, null, null, payload);\n res.add(sourceDataEntry);\n }\n } catch (Exception e) {\n log.error(\"activemq task poll error, current config:\" + JSON.toJSONString(config), e);\n }\n return res;\n }\n\n @Override\n public void start(KeyValue props) {\n try {\n this.config = new Config();\n this.config.load(props);\n this.sourcePartition = ByteBuffer.wrap(config.getBrokerUrl().getBytes(\"UTF-8\"));\n this.replicator.start();\n } catch (Exception e) {\n log.error(\"activemq task start failed.\", e);\n throw new DataConnectException(ErrorCode.START_ERROR_CODE, e.getMessage(), e);\n }\n }\n\n @Override\n public void stop() {\n try {\n replicator.stop();\n } catch (Exception e) {\n log.error(\"activemq task stop failed.\", e);\n throw new DataConnectException(ErrorCode.STOP_ERROR_CODE, e.getMessage(), e);\n }\n }\n\n @Override\n public void pause() {\n }\n\n @Override\n public void resume() {\n }\n\n @SuppressWarnings(\"unchecked\")\n public ByteBuffer getMessageContent(Message message) throws JMSException {\n byte[] data = null;\n if (message instanceof TextMessage) {\n data = ((TextMessage) message).getText().getBytes();\n } else if (message instanceof ObjectMessage) {\n data = JSON.toJSONBytes(((ObjectMessage) message).getObject());\n } else if (message instanceof BytesMessage) {\n BytesMessage bytesMessage = (BytesMessage) message;\n data = new byte[(int) bytesMessage.getBodyLength()];\n bytesMessage.readBytes(data);\n } else if (message instanceof MapMessage) {\n MapMessage mapMessage = (MapMessage) message;\n Map map = new HashMap<>();\n Enumeration names = mapMessage.getMapNames();\n ", "post_mask_code": "\n data = JSON.toJSONBytes(map);\n } else if (message instanceof StreamMessage) {\n StreamMessage streamMessage = (StreamMessage) message;\n ByteArrayOutputStream bis = new ByteArrayOutputStream();\n byte[] by = new byte[1024];\n int i = 0;\n while ((i = streamMessage.readBytes(by)) != -1) {\n bis.write(by, 0, i);\n }\n data = bis.toByteArray();\n } else {\n // The exception is printed and does not need to be written as a DataConnectException\n throw new RuntimeException(\"message type exception\");\n }\n return ByteBuffer.wrap(data);\n }\n\n public abstract Config getConfig();\n\n public abstract PatternProcessor getPatternProcessor(Replicator replicator);\n}\n"} {"task_id": "Java_2975", "language": "Java", "task_type": "try_statement", "source_file": "java/github/apache/rocketmq-externals/rocketmq-connect-jms/src/main/java/org/apache/rocketmq/connect/jms/connector/BaseJmsSourceTask.java", "mask_start_position": 2656, "mask_end_position": 2880, "canonical_solution": "try {\n replicator.stop();\n } catch (Exception e) {\n log.error(\"activemq task stop failed.\", e);\n throw new DataConnectException(ErrorCode.STOP_ERROR_CODE, e.getMessage(), e);\n }", "pre_mask_code": "package org.apache.rocketmq.connect.jms.connector;\n\nimport java.io.ByteArrayOutputStream;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\nimport javax.jms.BytesMessage;\nimport javax.jms.JMSException;\nimport javax.jms.MapMessage;\nimport javax.jms.Message;\nimport javax.jms.ObjectMessage;\nimport javax.jms.StreamMessage;\nimport javax.jms.TextMessage;\nimport org.apache.rocketmq.connect.jms.Config;\nimport org.apache.rocketmq.connect.jms.ErrorCode;\nimport org.apache.rocketmq.connect.jms.Replicator;\nimport org.apache.rocketmq.connect.jms.pattern.PatternProcessor;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.alibaba.fastjson.JSON;\nimport io.openmessaging.KeyValue;\nimport io.openmessaging.connector.api.data.EntryType;\nimport io.openmessaging.connector.api.data.SourceDataEntry;\nimport io.openmessaging.connector.api.exception.DataConnectException;\nimport io.openmessaging.connector.api.source.SourceTask;\n\npublic abstract class BaseJmsSourceTask extends SourceTask {\n\n private static final Logger log = LoggerFactory.getLogger(BaseJmsSourceTask.class);\n\n private Replicator replicator;\n\n private Config config;\n\n private ByteBuffer sourcePartition;\n\n @Override\n public Collection poll() {\n List res = new ArrayList<>();\n try {\n Message message = replicator.getQueue().poll(1000, TimeUnit.MILLISECONDS);\n if (message != null) {\n Object[] payload = new Object[] { config.getDestinationType(), config.getDestinationName(), getMessageContent(message) };\n SourceDataEntry sourceDataEntry = new SourceDataEntry(sourcePartition, null, System.currentTimeMillis(), EntryType.CREATE, null, null, payload);\n res.add(sourceDataEntry);\n }\n } catch (Exception e) {\n log.error(\"activemq task poll error, current config:\" + JSON.toJSONString(config), e);\n }\n return res;\n }\n\n @Override\n public void start(KeyValue props) {\n try {\n this.config = new Config();\n this.config.load(props);\n this.sourcePartition = ByteBuffer.wrap(config.getBrokerUrl().getBytes(\"UTF-8\"));\n this.replicator.start();\n } catch (Exception e) {\n log.error(\"activemq task start failed.\", e);\n throw new DataConnectException(ErrorCode.START_ERROR_CODE, e.getMessage(), e);\n }\n }\n\n @Override\n public void stop() {\n ", "post_mask_code": "\n }\n\n @Override\n public void pause() {\n }\n\n @Override\n public void resume() {\n }\n\n @SuppressWarnings(\"unchecked\")\n public ByteBuffer getMessageContent(Message message) throws JMSException {\n byte[] data = null;\n if (message instanceof TextMessage) {\n data = ((TextMessage) message).getText().getBytes();\n } else if (message instanceof ObjectMessage) {\n data = JSON.toJSONBytes(((ObjectMessage) message).getObject());\n } else if (message instanceof BytesMessage) {\n BytesMessage bytesMessage = (BytesMessage) message;\n data = new byte[(int) bytesMessage.getBodyLength()];\n bytesMessage.readBytes(data);\n } else if (message instanceof MapMessage) {\n MapMessage mapMessage = (MapMessage) message;\n Map map = new HashMap<>();\n Enumeration names = mapMessage.getMapNames();\n while (names.hasMoreElements()) {\n String name = names.nextElement().toString();\n map.put(name, mapMessage.getObject(name));\n }\n data = JSON.toJSONBytes(map);\n } else if (message instanceof StreamMessage) {\n StreamMessage streamMessage = (StreamMessage) message;\n ByteArrayOutputStream bis = new ByteArrayOutputStream();\n byte[] by = new byte[1024];\n int i = 0;\n while ((i = streamMessage.readBytes(by)) != -1) {\n bis.write(by, 0, i);\n }\n data = bis.toByteArray();\n } else {\n // The exception is printed and does not need to be written as a DataConnectException\n throw new RuntimeException(\"message type exception\");\n }\n return ByteBuffer.wrap(data);\n }\n\n public abstract Config getConfig();\n\n public abstract PatternProcessor getPatternProcessor(Replicator replicator);\n}\n"} {"task_id": "Java_2976", "language": "Java", "task_type": "method_signature", "source_file": "java/github/stacktipslab/Android-UI-Tutorials/ActivityForResults/src/com/example/activitytest/FirstActivity.java", "mask_start_position": 595, "mask_end_position": 648, "canonical_solution": "@Override\n public void onClick(View view) ", "pre_mask_code": "package com.example.activitytest;\n\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport android.app.Activity;\nimport android.content.Intent;\n\npublic class FirstActivity extends Activity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_first);\n Button start = (Button) findViewById(R.id.start_button);\n start.setOnClickListener(new OnClickListener() {\n\n ", "post_mask_code": "{\n Intent intent = new Intent(FirstActivity.this, SecondActivity.class);\n startActivityForResult(intent, 1);\n }\n });\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == 1) {\n if (resultCode == RESULT_OK) {\n // here is your result\n String result = data.getStringExtra(\"result\");\n Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();\n }\n if (resultCode == RESULT_CANCELED) {\n // Write your code if there's no result\n Toast.makeText(getApplicationContext(), \"Nothing Returned!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n}\n"} {"task_id": "Java_2977", "language": "Java", "task_type": "method_body", "source_file": "java/github/stacktipslab/Android-UI-Tutorials/ActivityForResults/src/com/example/activitytest/FirstActivity.java", "mask_start_position": 648, "mask_end_position": 800, "canonical_solution": "{\n Intent intent = new Intent(FirstActivity.this, SecondActivity.class);\n startActivityForResult(intent, 1);\n }", "pre_mask_code": "package com.example.activitytest;\n\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport android.app.Activity;\nimport android.content.Intent;\n\npublic class FirstActivity extends Activity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_first);\n Button start = (Button) findViewById(R.id.start_button);\n start.setOnClickListener(new OnClickListener() {\n\n @Override\n public void onClick(View view) ", "post_mask_code": "\n });\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == 1) {\n if (resultCode == RESULT_OK) {\n // here is your result\n String result = data.getStringExtra(\"result\");\n Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();\n }\n if (resultCode == RESULT_CANCELED) {\n // Write your code if there's no result\n Toast.makeText(getApplicationContext(), \"Nothing Returned!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n}\n"} {"task_id": "Java_2978", "language": "Java", "task_type": "single_line", "source_file": "java/github/stacktipslab/Android-UI-Tutorials/ActivityForResults/src/com/example/activitytest/FirstActivity.java", "mask_start_position": 513, "mask_end_position": 524, "canonical_solution": "rt_button);", "pre_mask_code": "package com.example.activitytest;\n\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport android.app.Activity;\nimport android.content.Intent;\n\npublic class FirstActivity extends Activity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_first);\n Button start = (Button) findViewById(R.id.sta", "post_mask_code": "\n start.setOnClickListener(new OnClickListener() {\n\n @Override\n public void onClick(View view) {\n Intent intent = new Intent(FirstActivity.this, SecondActivity.class);\n startActivityForResult(intent, 1);\n }\n });\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == 1) {\n if (resultCode == RESULT_OK) {\n // here is your result\n String result = data.getStringExtra(\"result\");\n Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();\n }\n if (resultCode == RESULT_CANCELED) {\n // Write your code if there's no result\n Toast.makeText(getApplicationContext(), \"Nothing Returned!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n}\n"} {"task_id": "Java_2979", "language": "Java", "task_type": "method_signature", "source_file": "java/github/AingCreation/Aion-Project-5.1/AL-Game/data/scripts/system/handlers/quest/sanctum/_3964GrowthFlorasFourthCharm.java", "mask_start_position": 867, "mask_end_position": 904, "canonical_solution": "@Override\n public void register() ", "pre_mask_code": "/*\n * This file is part of aion-lightning .\n *\n */\npackage quest.sanctum;\n\nimport com.aionemu.gameserver.model.gameobjects.Npc;\nimport com.aionemu.gameserver.model.gameobjects.player.Player;\nimport com.aionemu.gameserver.questEngine.handlers.QuestHandler;\nimport com.aionemu.gameserver.questEngine.model.QuestDialog;\nimport com.aionemu.gameserver.questEngine.model.QuestEnv;\nimport com.aionemu.gameserver.questEngine.model.QuestState;\nimport com.aionemu.gameserver.questEngine.model.QuestStatus;\n\n/**\n * Talk with Erdos (203740). Bring the Yellow Aether Powder (186000090) and Kinah (90000) to Flora (798384).\n *\n * @author undertrey\n * @modified vlog\n */\npublic class _3964GrowthFlorasFourthCharm extends QuestHandler {\n\n private final static int questId = 3964;\n\n public _3964GrowthFlorasFourthCharm() {\n super(questId);\n }\n\n ", "post_mask_code": "{\n qe.registerQuestNpc(798384).addOnQuestStart(questId);\n qe.registerQuestNpc(798384).addOnTalkEvent(questId);\n qe.registerQuestNpc(203740).addOnTalkEvent(questId);\n }\n\n @Override\n public boolean onDialogEvent(QuestEnv env) {\n final Player player = env.getPlayer();\n QuestState qs = player.getQuestStateList().getQuestState(questId);\n int targetId = 0;\n if (env.getVisibleObject() instanceof Npc)\n targetId = ((Npc) env.getVisibleObject()).getNpcId();\n if (qs == null || qs.getStatus() == QuestStatus.NONE) {\n if (targetId == 798384) {\n // Flora\n if (env.getDialog() == QuestDialog.START_DIALOG)\n return sendQuestDialog(env, 1011);\n else\n return sendQuestStartDialog(env);\n }\n } else if (qs.getStatus() == QuestStatus.START) {\n int var = qs.getQuestVarById(0);\n switch(targetId) {\n case 203740:\n {\n // Erdos\n switch(env.getDialog()) {\n case START_DIALOG:\n if (var == 0)\n return sendQuestDialog(env, 1352);\n case STEP_TO_1:\n return defaultCloseDialog(env, 0, 1, 182206111, 1, 0, 0);\n }\n }\n case // Flora\n 798384:\n switch(env.getDialog()) {\n case START_DIALOG:\n if (var == 1) {\n removeQuestItem(env, 182206111, 1);\n return sendQuestDialog(env, 2375);\n }\n case CHECK_COLLECTED_ITEMS:\n long itemAmount = player.getInventory().getItemCountByItemId(186000090);\n if (var == 1 && player.getInventory().tryDecreaseKinah(90000) && itemAmount >= 1) {\n player.getInventory().decreaseKinah(90000);\n removeQuestItem(env, 186000090, 1);\n // reward\n changeQuestStep(env, 1, 1, true);\n return sendQuestDialog(env, 5);\n } else\n return sendQuestDialog(env, 2716);\n case FINISH_DIALOG:\n return defaultCloseDialog(env, 1, 1);\n }\n }\n } else if (qs.getStatus() == QuestStatus.REWARD) {\n if (targetId == 798384) {\n // Flora\n return sendQuestEndDialog(env);\n }\n }\n return false;\n }\n}\n"} {"task_id": "Java_2980", "language": "Java", "task_type": "method_body", "source_file": "java/github/AingCreation/Aion-Project-5.1/AL-Game/data/scripts/system/handlers/quest/sanctum/_3964GrowthFlorasFourthCharm.java", "mask_start_position": 904, "mask_end_position": 1095, "canonical_solution": "{\n qe.registerQuestNpc(798384).addOnQuestStart(questId);\n qe.registerQuestNpc(798384).addOnTalkEvent(questId);\n qe.registerQuestNpc(203740).addOnTalkEvent(questId);\n }", "pre_mask_code": "/*\n * This file is part of aion-lightning .\n *\n */\npackage quest.sanctum;\n\nimport com.aionemu.gameserver.model.gameobjects.Npc;\nimport com.aionemu.gameserver.model.gameobjects.player.Player;\nimport com.aionemu.gameserver.questEngine.handlers.QuestHandler;\nimport com.aionemu.gameserver.questEngine.model.QuestDialog;\nimport com.aionemu.gameserver.questEngine.model.QuestEnv;\nimport com.aionemu.gameserver.questEngine.model.QuestState;\nimport com.aionemu.gameserver.questEngine.model.QuestStatus;\n\n/**\n * Talk with Erdos (203740). Bring the Yellow Aether Powder (186000090) and Kinah (90000) to Flora (798384).\n *\n * @author undertrey\n * @modified vlog\n */\npublic class _3964GrowthFlorasFourthCharm extends QuestHandler {\n\n private final static int questId = 3964;\n\n public _3964GrowthFlorasFourthCharm() {\n super(questId);\n }\n\n @Override\n public void register() ", "post_mask_code": "\n\n @Override\n public boolean onDialogEvent(QuestEnv env) {\n final Player player = env.getPlayer();\n QuestState qs = player.getQuestStateList().getQuestState(questId);\n int targetId = 0;\n if (env.getVisibleObject() instanceof Npc)\n targetId = ((Npc) env.getVisibleObject()).getNpcId();\n if (qs == null || qs.getStatus() == QuestStatus.NONE) {\n if (targetId == 798384) {\n // Flora\n if (env.getDialog() == QuestDialog.START_DIALOG)\n return sendQuestDialog(env, 1011);\n else\n return sendQuestStartDialog(env);\n }\n } else if (qs.getStatus() == QuestStatus.START) {\n int var = qs.getQuestVarById(0);\n switch(targetId) {\n case 203740:\n {\n // Erdos\n switch(env.getDialog()) {\n case START_DIALOG:\n if (var == 0)\n return sendQuestDialog(env, 1352);\n case STEP_TO_1:\n return defaultCloseDialog(env, 0, 1, 182206111, 1, 0, 0);\n }\n }\n case // Flora\n 798384:\n switch(env.getDialog()) {\n case START_DIALOG:\n if (var == 1) {\n removeQuestItem(env, 182206111, 1);\n return sendQuestDialog(env, 2375);\n }\n case CHECK_COLLECTED_ITEMS:\n long itemAmount = player.getInventory().getItemCountByItemId(186000090);\n if (var == 1 && player.getInventory().tryDecreaseKinah(90000) && itemAmount >= 1) {\n player.getInventory().decreaseKinah(90000);\n removeQuestItem(env, 186000090, 1);\n // reward\n changeQuestStep(env, 1, 1, true);\n return sendQuestDialog(env, 5);\n } else\n return sendQuestDialog(env, 2716);\n case FINISH_DIALOG:\n return defaultCloseDialog(env, 1, 1);\n }\n }\n } else if (qs.getStatus() == QuestStatus.REWARD) {\n if (targetId == 798384) {\n // Flora\n return sendQuestEndDialog(env);\n }\n }\n return false;\n }\n}\n"} {"task_id": "Java_2981", "language": "Java", "task_type": "single_line", "source_file": "java/github/AingCreation/Aion-Project-5.1/AL-Game/data/scripts/system/handlers/quest/sanctum/_3964GrowthFlorasFourthCharm.java", "mask_start_position": 1298, "mask_end_position": 1307, "canonical_solution": "etId = 0;", "pre_mask_code": "/*\n * This file is part of aion-lightning .\n *\n */\npackage quest.sanctum;\n\nimport com.aionemu.gameserver.model.gameobjects.Npc;\nimport com.aionemu.gameserver.model.gameobjects.player.Player;\nimport com.aionemu.gameserver.questEngine.handlers.QuestHandler;\nimport com.aionemu.gameserver.questEngine.model.QuestDialog;\nimport com.aionemu.gameserver.questEngine.model.QuestEnv;\nimport com.aionemu.gameserver.questEngine.model.QuestState;\nimport com.aionemu.gameserver.questEngine.model.QuestStatus;\n\n/**\n * Talk with Erdos (203740). Bring the Yellow Aether Powder (186000090) and Kinah (90000) to Flora (798384).\n *\n * @author undertrey\n * @modified vlog\n */\npublic class _3964GrowthFlorasFourthCharm extends QuestHandler {\n\n private final static int questId = 3964;\n\n public _3964GrowthFlorasFourthCharm() {\n super(questId);\n }\n\n @Override\n public void register() {\n qe.registerQuestNpc(798384).addOnQuestStart(questId);\n qe.registerQuestNpc(798384).addOnTalkEvent(questId);\n qe.registerQuestNpc(203740).addOnTalkEvent(questId);\n }\n\n @Override\n public boolean onDialogEvent(QuestEnv env) {\n final Player player = env.getPlayer();\n QuestState qs = player.getQuestStateList().getQuestState(questId);\n int targ", "post_mask_code": "\n if (env.getVisibleObject() instanceof Npc)\n targetId = ((Npc) env.getVisibleObject()).getNpcId();\n if (qs == null || qs.getStatus() == QuestStatus.NONE) {\n if (targetId == 798384) {\n // Flora\n if (env.getDialog() == QuestDialog.START_DIALOG)\n return sendQuestDialog(env, 1011);\n else\n return sendQuestStartDialog(env);\n }\n } else if (qs.getStatus() == QuestStatus.START) {\n int var = qs.getQuestVarById(0);\n switch(targetId) {\n case 203740:\n {\n // Erdos\n switch(env.getDialog()) {\n case START_DIALOG:\n if (var == 0)\n return sendQuestDialog(env, 1352);\n case STEP_TO_1:\n return defaultCloseDialog(env, 0, 1, 182206111, 1, 0, 0);\n }\n }\n case // Flora\n 798384:\n switch(env.getDialog()) {\n case START_DIALOG:\n if (var == 1) {\n removeQuestItem(env, 182206111, 1);\n return sendQuestDialog(env, 2375);\n }\n case CHECK_COLLECTED_ITEMS:\n long itemAmount = player.getInventory().getItemCountByItemId(186000090);\n if (var == 1 && player.getInventory().tryDecreaseKinah(90000) && itemAmount >= 1) {\n player.getInventory().decreaseKinah(90000);\n removeQuestItem(env, 186000090, 1);\n // reward\n changeQuestStep(env, 1, 1, true);\n return sendQuestDialog(env, 5);\n } else\n return sendQuestDialog(env, 2716);\n case FINISH_DIALOG:\n return defaultCloseDialog(env, 1, 1);\n }\n }\n } else if (qs.getStatus() == QuestStatus.REWARD) {\n if (targetId == 798384) {\n // Flora\n return sendQuestEndDialog(env);\n }\n }\n return false;\n }\n}\n"} {"task_id": "Java_2982", "language": "Java", "task_type": "switch_case", "source_file": "java/github/AingCreation/Aion-Project-5.1/AL-Game/data/scripts/system/handlers/quest/sanctum/_3964GrowthFlorasFourthCharm.java", "mask_start_position": 2003, "mask_end_position": 2352, "canonical_solution": "switch(env.getDialog()) {\n case START_DIALOG:\n if (var == 0)\n return sendQuestDialog(env, 1352);\n case STEP_TO_1:\n return defaultCloseDialog(env, 0, 1, 182206111, 1, 0, 0);\n }", "pre_mask_code": "/*\n * This file is part of aion-lightning .\n *\n */\npackage quest.sanctum;\n\nimport com.aionemu.gameserver.model.gameobjects.Npc;\nimport com.aionemu.gameserver.model.gameobjects.player.Player;\nimport com.aionemu.gameserver.questEngine.handlers.QuestHandler;\nimport com.aionemu.gameserver.questEngine.model.QuestDialog;\nimport com.aionemu.gameserver.questEngine.model.QuestEnv;\nimport com.aionemu.gameserver.questEngine.model.QuestState;\nimport com.aionemu.gameserver.questEngine.model.QuestStatus;\n\n/**\n * Talk with Erdos (203740). Bring the Yellow Aether Powder (186000090) and Kinah (90000) to Flora (798384).\n *\n * @author undertrey\n * @modified vlog\n */\npublic class _3964GrowthFlorasFourthCharm extends QuestHandler {\n\n private final static int questId = 3964;\n\n public _3964GrowthFlorasFourthCharm() {\n super(questId);\n }\n\n @Override\n public void register() {\n qe.registerQuestNpc(798384).addOnQuestStart(questId);\n qe.registerQuestNpc(798384).addOnTalkEvent(questId);\n qe.registerQuestNpc(203740).addOnTalkEvent(questId);\n }\n\n @Override\n public boolean onDialogEvent(QuestEnv env) {\n final Player player = env.getPlayer();\n QuestState qs = player.getQuestStateList().getQuestState(questId);\n int targetId = 0;\n if (env.getVisibleObject() instanceof Npc)\n targetId = ((Npc) env.getVisibleObject()).getNpcId();\n if (qs == null || qs.getStatus() == QuestStatus.NONE) {\n if (targetId == 798384) {\n // Flora\n if (env.getDialog() == QuestDialog.START_DIALOG)\n return sendQuestDialog(env, 1011);\n else\n return sendQuestStartDialog(env);\n }\n } else if (qs.getStatus() == QuestStatus.START) {\n int var = qs.getQuestVarById(0);\n switch(targetId) {\n case 203740:\n {\n // Erdos\n ", "post_mask_code": "\n }\n case // Flora\n 798384:\n switch(env.getDialog()) {\n case START_DIALOG:\n if (var == 1) {\n removeQuestItem(env, 182206111, 1);\n return sendQuestDialog(env, 2375);\n }\n case CHECK_COLLECTED_ITEMS:\n long itemAmount = player.getInventory().getItemCountByItemId(186000090);\n if (var == 1 && player.getInventory().tryDecreaseKinah(90000) && itemAmount >= 1) {\n player.getInventory().decreaseKinah(90000);\n removeQuestItem(env, 186000090, 1);\n // reward\n changeQuestStep(env, 1, 1, true);\n return sendQuestDialog(env, 5);\n } else\n return sendQuestDialog(env, 2716);\n case FINISH_DIALOG:\n return defaultCloseDialog(env, 1, 1);\n }\n }\n } else if (qs.getStatus() == QuestStatus.REWARD) {\n if (targetId == 798384) {\n // Flora\n return sendQuestEndDialog(env);\n }\n }\n return false;\n }\n}\n"} {"task_id": "Java_2983", "language": "Java", "task_type": "method_signature", "source_file": "java/github/daizhenjun/ImageFilterForAndroid/src/HaoRan/ImageFilter/LightFilter.java", "mask_start_position": 223, "mask_end_position": 259, "canonical_solution": "public Image process(Image imageIn) ", "pre_mask_code": "/* \n * HaoRan ImageFilter Classes v0.1\n *\n */\npackage HaoRan.ImageFilter;\n\n/**\n * 光照效果\n * @author daizhj\n */\npublic class LightFilter extends RadialDistortionFilter {\n\n public float Light = 150.0f;\n\n // @Override\n ", "post_mask_code": "{\n int width = imageIn.getWidth();\n int halfw = width / 2;\n int height = imageIn.getHeight();\n int halfh = height / 2;\n int R = Math.min(halfw, halfh);\n // 中心点,发亮此值会让强光中心发生偏移\n Point point = new Point(halfw, halfh);\n int r = 0, g = 0, b = 0;\n for (int x = 0; x < width; x++) {\n for (int y = 0; y < height; y++) {\n float length = (float) Math.sqrt(Math.pow((x - point.X), 2) + Math.pow((y - point.Y), 2));\n r = imageIn.getRComponent(x, y);\n g = imageIn.getGComponent(x, y);\n b = imageIn.getBComponent(x, y);\n // 位于光晕中\n if (length < R) {\n float pixel = Light * (1.0f - length / R);\n r = r + (int) pixel;\n r = Math.max(0, Math.min(r, 255));\n g = g + (int) pixel;\n g = Math.max(0, Math.min(g, 255));\n b = b + (int) pixel;\n b = Math.max(0, Math.min(b, 255));\n }\n imageIn.setPixelColor(x, y, r, g, b);\n }\n }\n return imageIn;\n }\n}\n"} {"task_id": "Java_2984", "language": "Java", "task_type": "single_line", "source_file": "java/github/daizhenjun/ImageFilterForAndroid/src/HaoRan/ImageFilter/LightFilter.java", "mask_start_position": 316, "mask_end_position": 331, "canonical_solution": "fw = width / 2;", "pre_mask_code": "/* \n * HaoRan ImageFilter Classes v0.1\n *\n */\npackage HaoRan.ImageFilter;\n\n/**\n * 光照效果\n * @author daizhj\n */\npublic class LightFilter extends RadialDistortionFilter {\n\n public float Light = 150.0f;\n\n // @Override\n public Image process(Image imageIn) {\n int width = imageIn.getWidth();\n int hal", "post_mask_code": "\n int height = imageIn.getHeight();\n int halfh = height / 2;\n int R = Math.min(halfw, halfh);\n // 中心点,发亮此值会让强光中心发生偏移\n Point point = new Point(halfw, halfh);\n int r = 0, g = 0, b = 0;\n for (int x = 0; x < width; x++) {\n for (int y = 0; y < height; y++) {\n float length = (float) Math.sqrt(Math.pow((x - point.X), 2) + Math.pow((y - point.Y), 2));\n r = imageIn.getRComponent(x, y);\n g = imageIn.getGComponent(x, y);\n b = imageIn.getBComponent(x, y);\n // 位于光晕中\n if (length < R) {\n float pixel = Light * (1.0f - length / R);\n r = r + (int) pixel;\n r = Math.max(0, Math.min(r, 255));\n g = g + (int) pixel;\n g = Math.max(0, Math.min(g, 255));\n b = b + (int) pixel;\n b = Math.max(0, Math.min(b, 255));\n }\n imageIn.setPixelColor(x, y, r, g, b);\n }\n }\n return imageIn;\n }\n}\n"} {"task_id": "Java_2985", "language": "Java", "task_type": "method_signature", "source_file": "java/github/joekoolade/JOE/classpath-0.98/java/io/StringBufferInputStream.java", "mask_start_position": 3942, "mask_end_position": 3986, "canonical_solution": "public int read(byte[] b, int off, int len) ", "pre_mask_code": "/* StringBufferInputStream.java -- Read an String as a stream\n\n*/\npackage java.io;\n\n/* Written using \"Java Class Libraries\", 2nd edition, ISBN 0-201-31002-3\n * \"The Java Language Specification\", ISBN 0-201-63451-1\n * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.\n * Status: Believed complete and correct. Deprecated in JDK 1.1.\n */\n/**\n * This class permits a String to be read as an input stream.\n * The low eight bits of each character in the String are the\n * bytes that are returned. The high eight bits of each character are\n * discarded.\n *

\n * The mark/reset functionality in this class behaves differently than\n * normal. The mark() method is always ignored and the\n * reset() method always resets in stream to start reading from\n * position 0 in the String. Note that since this method does not override\n * markSupported() in InputStream, calling that\n * method will return false.\n *

\n * Note that this class is deprecated because it does not properly handle\n * 16-bit Java characters. It is provided for backwards compatibility only\n * and should not be used for new development. The StringReader\n * class should be used instead.\n *\n * @deprecated\n *\n * @author Aaron M. Renn (example@nnthink.com)\n * @author Warren Levy (example@nnthink.com)\n */\npublic class StringBufferInputStream extends InputStream {\n\n /**\n * The String which is the input to this stream.\n */\n protected String buffer;\n\n /**\n * Position of the next byte in buffer to be read.\n */\n protected int pos = 0;\n\n /**\n * The length of the String buffer.\n */\n protected int count;\n\n /**\n * Create a new StringBufferInputStream that will read bytes\n * from the passed in String. This stream will read from the\n * beginning to the end of the String.\n *\n * @param s The String this stream will read from.\n */\n public StringBufferInputStream(String s) {\n buffer = s;\n count = s.length();\n }\n\n /**\n * This method returns the number of bytes available to be read from this\n * stream. The value returned will be equal to count - pos.\n *\n * @return The number of bytes that can be read from this stream before\n * blocking, which is all of them\n */\n public int available() {\n return count - pos;\n }\n\n /**\n * This method reads one byte from the stream. The pos counter\n * is advanced to the next byte to be read. The byte read is returned as\n * an int in the range of 0-255. If the stream position is already at the\n * end of the buffer, no byte is read and a -1 is returned in order to\n * indicate the end of the stream.\n *\n * @return The byte read, or -1 if end of stream\n */\n public int read() {\n if (pos >= count)\n // EOF\n return -1;\n return ((int) buffer.charAt(pos++)) & 0xFF;\n }\n\n /**\n * This method reads bytes from the stream and stores them into a caller\n * supplied buffer. It starts storing the data at index offset\n * into the buffer and attempts to read len bytes. This method\n * can return before reading the number of bytes requested if the end of the\n * stream is encountered first. The actual number of bytes read is\n * returned. If no bytes can be read because the stream is already at\n * the end of stream position, a -1 is returned.\n *

\n * This method does not block.\n *\n * @param b The array into which the bytes read should be stored.\n * @param off The offset into the array to start storing bytes\n * @param len The requested number of bytes to read\n *\n * @return The actual number of bytes read, or -1 if end of stream.\n */\n ", "post_mask_code": "{\n if (off < 0 || len < 0 || off + len > b.length)\n throw new ArrayIndexOutOfBoundsException();\n if (pos >= count)\n // EOF\n return -1;\n int numRead = Math.min(len, count - pos);\n if (numRead < 0)\n return 0;\n buffer.getBytes(pos, pos + numRead, b, off);\n pos += numRead;\n return numRead;\n }\n\n /**\n * This method sets the read position in the stream to the beginning\n * setting the pos variable equal to 0. Note that this differs\n * from the common implementation of the reset() method.\n */\n public void reset() {\n pos = 0;\n }\n\n /**\n * This method attempts to skip the requested number of bytes in the\n * input stream. It does this by advancing the pos value by the\n * specified number of bytes. It this would exceed the length of the\n * buffer, then only enough bytes are skipped to position the stream at\n * the end of the buffer. The actual number of bytes skipped is returned.\n *\n * @param n The requested number of bytes to skip\n *\n * @return The actual number of bytes skipped.\n */\n public long skip(long n) {\n if (n < 0)\n return 0L;\n long actualSkip = Math.min(n, count - pos);\n pos += actualSkip;\n return actualSkip;\n }\n}\n"} {"task_id": "Java_2986", "language": "Java", "task_type": "method_body", "source_file": "java/github/joekoolade/JOE/classpath-0.98/java/io/StringBufferInputStream.java", "mask_start_position": 3986, "mask_end_position": 4371, "canonical_solution": "{\n if (off < 0 || len < 0 || off + len > b.length)\n throw new ArrayIndexOutOfBoundsException();\n if (pos >= count)\n // EOF\n return -1;\n int numRead = Math.min(len, count - pos);\n if (numRead < 0)\n return 0;\n buffer.getBytes(pos, pos + numRead, b, off);\n pos += numRead;\n return numRead;\n }", "pre_mask_code": "/* StringBufferInputStream.java -- Read an String as a stream\n\n*/\npackage java.io;\n\n/* Written using \"Java Class Libraries\", 2nd edition, ISBN 0-201-31002-3\n * \"The Java Language Specification\", ISBN 0-201-63451-1\n * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.\n * Status: Believed complete and correct. Deprecated in JDK 1.1.\n */\n/**\n * This class permits a String to be read as an input stream.\n * The low eight bits of each character in the String are the\n * bytes that are returned. The high eight bits of each character are\n * discarded.\n *

\n * The mark/reset functionality in this class behaves differently than\n * normal. The mark() method is always ignored and the\n * reset() method always resets in stream to start reading from\n * position 0 in the String. Note that since this method does not override\n * markSupported() in InputStream, calling that\n * method will return false.\n *

\n * Note that this class is deprecated because it does not properly handle\n * 16-bit Java characters. It is provided for backwards compatibility only\n * and should not be used for new development. The StringReader\n * class should be used instead.\n *\n * @deprecated\n *\n * @author Aaron M. Renn (example@nnthink.com)\n * @author Warren Levy (example@nnthink.com)\n */\npublic class StringBufferInputStream extends InputStream {\n\n /**\n * The String which is the input to this stream.\n */\n protected String buffer;\n\n /**\n * Position of the next byte in buffer to be read.\n */\n protected int pos = 0;\n\n /**\n * The length of the String buffer.\n */\n protected int count;\n\n /**\n * Create a new StringBufferInputStream that will read bytes\n * from the passed in String. This stream will read from the\n * beginning to the end of the String.\n *\n * @param s The String this stream will read from.\n */\n public StringBufferInputStream(String s) {\n buffer = s;\n count = s.length();\n }\n\n /**\n * This method returns the number of bytes available to be read from this\n * stream. The value returned will be equal to count - pos.\n *\n * @return The number of bytes that can be read from this stream before\n * blocking, which is all of them\n */\n public int available() {\n return count - pos;\n }\n\n /**\n * This method reads one byte from the stream. The pos counter\n * is advanced to the next byte to be read. The byte read is returned as\n * an int in the range of 0-255. If the stream position is already at the\n * end of the buffer, no byte is read and a -1 is returned in order to\n * indicate the end of the stream.\n *\n * @return The byte read, or -1 if end of stream\n */\n public int read() {\n if (pos >= count)\n // EOF\n return -1;\n return ((int) buffer.charAt(pos++)) & 0xFF;\n }\n\n /**\n * This method reads bytes from the stream and stores them into a caller\n * supplied buffer. It starts storing the data at index offset\n * into the buffer and attempts to read len bytes. This method\n * can return before reading the number of bytes requested if the end of the\n * stream is encountered first. The actual number of bytes read is\n * returned. If no bytes can be read because the stream is already at\n * the end of stream position, a -1 is returned.\n *

\n * This method does not block.\n *\n * @param b The array into which the bytes read should be stored.\n * @param off The offset into the array to start storing bytes\n * @param len The requested number of bytes to read\n *\n * @return The actual number of bytes read, or -1 if end of stream.\n */\n public int read(byte[] b, int off, int len) ", "post_mask_code": "\n\n /**\n * This method sets the read position in the stream to the beginning\n * setting the pos variable equal to 0. Note that this differs\n * from the common implementation of the reset() method.\n */\n public void reset() {\n pos = 0;\n }\n\n /**\n * This method attempts to skip the requested number of bytes in the\n * input stream. It does this by advancing the pos value by the\n * specified number of bytes. It this would exceed the length of the\n * buffer, then only enough bytes are skipped to position the stream at\n * the end of the buffer. The actual number of bytes skipped is returned.\n *\n * @param n The requested number of bytes to skip\n *\n * @return The actual number of bytes skipped.\n */\n public long skip(long n) {\n if (n < 0)\n return 0L;\n long actualSkip = Math.min(n, count - pos);\n pos += actualSkip;\n return actualSkip;\n }\n}\n"} {"task_id": "Java_2987", "language": "Java", "task_type": "single_line", "source_file": "java/github/joekoolade/JOE/classpath-0.98/java/io/StringBufferInputStream.java", "mask_start_position": 3047, "mask_end_position": 3069, "canonical_solution": "charAt(pos++)) & 0xFF;", "pre_mask_code": "/* StringBufferInputStream.java -- Read an String as a stream\n\n*/\npackage java.io;\n\n/* Written using \"Java Class Libraries\", 2nd edition, ISBN 0-201-31002-3\n * \"The Java Language Specification\", ISBN 0-201-63451-1\n * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.\n * Status: Believed complete and correct. Deprecated in JDK 1.1.\n */\n/**\n * This class permits a String to be read as an input stream.\n * The low eight bits of each character in the String are the\n * bytes that are returned. The high eight bits of each character are\n * discarded.\n *

\n * The mark/reset functionality in this class behaves differently than\n * normal. The mark() method is always ignored and the\n * reset() method always resets in stream to start reading from\n * position 0 in the String. Note that since this method does not override\n * markSupported() in InputStream, calling that\n * method will return false.\n *

\n * Note that this class is deprecated because it does not properly handle\n * 16-bit Java characters. It is provided for backwards compatibility only\n * and should not be used for new development. The StringReader\n * class should be used instead.\n *\n * @deprecated\n *\n * @author Aaron M. Renn (example@nnthink.com)\n * @author Warren Levy (example@nnthink.com)\n */\npublic class StringBufferInputStream extends InputStream {\n\n /**\n * The String which is the input to this stream.\n */\n protected String buffer;\n\n /**\n * Position of the next byte in buffer to be read.\n */\n protected int pos = 0;\n\n /**\n * The length of the String buffer.\n */\n protected int count;\n\n /**\n * Create a new StringBufferInputStream that will read bytes\n * from the passed in String. This stream will read from the\n * beginning to the end of the String.\n *\n * @param s The String this stream will read from.\n */\n public StringBufferInputStream(String s) {\n buffer = s;\n count = s.length();\n }\n\n /**\n * This method returns the number of bytes available to be read from this\n * stream. The value returned will be equal to count - pos.\n *\n * @return The number of bytes that can be read from this stream before\n * blocking, which is all of them\n */\n public int available() {\n return count - pos;\n }\n\n /**\n * This method reads one byte from the stream. The pos counter\n * is advanced to the next byte to be read. The byte read is returned as\n * an int in the range of 0-255. If the stream position is already at the\n * end of the buffer, no byte is read and a -1 is returned in order to\n * indicate the end of the stream.\n *\n * @return The byte read, or -1 if end of stream\n */\n public int read() {\n if (pos >= count)\n // EOF\n return -1;\n return ((int) buffer.", "post_mask_code": "\n }\n\n /**\n * This method reads bytes from the stream and stores them into a caller\n * supplied buffer. It starts storing the data at index offset\n * into the buffer and attempts to read len bytes. This method\n * can return before reading the number of bytes requested if the end of the\n * stream is encountered first. The actual number of bytes read is\n * returned. If no bytes can be read because the stream is already at\n * the end of stream position, a -1 is returned.\n *

\n * This method does not block.\n *\n * @param b The array into which the bytes read should be stored.\n * @param off The offset into the array to start storing bytes\n * @param len The requested number of bytes to read\n *\n * @return The actual number of bytes read, or -1 if end of stream.\n */\n public int read(byte[] b, int off, int len) {\n if (off < 0 || len < 0 || off + len > b.length)\n throw new ArrayIndexOutOfBoundsException();\n if (pos >= count)\n // EOF\n return -1;\n int numRead = Math.min(len, count - pos);\n if (numRead < 0)\n return 0;\n buffer.getBytes(pos, pos + numRead, b, off);\n pos += numRead;\n return numRead;\n }\n\n /**\n * This method sets the read position in the stream to the beginning\n * setting the pos variable equal to 0. Note that this differs\n * from the common implementation of the reset() method.\n */\n public void reset() {\n pos = 0;\n }\n\n /**\n * This method attempts to skip the requested number of bytes in the\n * input stream. It does this by advancing the pos value by the\n * specified number of bytes. It this would exceed the length of the\n * buffer, then only enough bytes are skipped to position the stream at\n * the end of the buffer. The actual number of bytes skipped is returned.\n *\n * @param n The requested number of bytes to skip\n *\n * @return The actual number of bytes skipped.\n */\n public long skip(long n) {\n if (n < 0)\n return 0L;\n long actualSkip = Math.min(n, count - pos);\n pos += actualSkip;\n return actualSkip;\n }\n}\n"} {"task_id": "Java_2988", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/joekoolade/JOE/classpath-0.98/java/io/StringBufferInputStream.java", "mask_start_position": 4621, "mask_end_position": 4665, "canonical_solution": "public void reset() {\n pos = 0;\n }", "pre_mask_code": "/* StringBufferInputStream.java -- Read an String as a stream\n\n*/\npackage java.io;\n\n/* Written using \"Java Class Libraries\", 2nd edition, ISBN 0-201-31002-3\n * \"The Java Language Specification\", ISBN 0-201-63451-1\n * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.\n * Status: Believed complete and correct. Deprecated in JDK 1.1.\n */\n/**\n * This class permits a String to be read as an input stream.\n * The low eight bits of each character in the String are the\n * bytes that are returned. The high eight bits of each character are\n * discarded.\n *

\n * The mark/reset functionality in this class behaves differently than\n * normal. The mark() method is always ignored and the\n * reset() method always resets in stream to start reading from\n * position 0 in the String. Note that since this method does not override\n * markSupported() in InputStream, calling that\n * method will return false.\n *

\n * Note that this class is deprecated because it does not properly handle\n * 16-bit Java characters. It is provided for backwards compatibility only\n * and should not be used for new development. The StringReader\n * class should be used instead.\n *\n * @deprecated\n *\n * @author Aaron M. Renn (example@nnthink.com)\n * @author Warren Levy (example@nnthink.com)\n */\npublic class StringBufferInputStream extends InputStream {\n\n /**\n * The String which is the input to this stream.\n */\n protected String buffer;\n\n /**\n * Position of the next byte in buffer to be read.\n */\n protected int pos = 0;\n\n /**\n * The length of the String buffer.\n */\n protected int count;\n\n /**\n * Create a new StringBufferInputStream that will read bytes\n * from the passed in String. This stream will read from the\n * beginning to the end of the String.\n *\n * @param s The String this stream will read from.\n */\n public StringBufferInputStream(String s) {\n buffer = s;\n count = s.length();\n }\n\n /**\n * This method returns the number of bytes available to be read from this\n * stream. The value returned will be equal to count - pos.\n *\n * @return The number of bytes that can be read from this stream before\n * blocking, which is all of them\n */\n public int available() {\n return count - pos;\n }\n\n /**\n * This method reads one byte from the stream. The pos counter\n * is advanced to the next byte to be read. The byte read is returned as\n * an int in the range of 0-255. If the stream position is already at the\n * end of the buffer, no byte is read and a -1 is returned in order to\n * indicate the end of the stream.\n *\n * @return The byte read, or -1 if end of stream\n */\n public int read() {\n if (pos >= count)\n // EOF\n return -1;\n return ((int) buffer.charAt(pos++)) & 0xFF;\n }\n\n /**\n * This method reads bytes from the stream and stores them into a caller\n * supplied buffer. It starts storing the data at index offset\n * into the buffer and attempts to read len bytes. This method\n * can return before reading the number of bytes requested if the end of the\n * stream is encountered first. The actual number of bytes read is\n * returned. If no bytes can be read because the stream is already at\n * the end of stream position, a -1 is returned.\n *

\n * This method does not block.\n *\n * @param b The array into which the bytes read should be stored.\n * @param off The offset into the array to start storing bytes\n * @param len The requested number of bytes to read\n *\n * @return The actual number of bytes read, or -1 if end of stream.\n */\n public int read(byte[] b, int off, int len) {\n if (off < 0 || len < 0 || off + len > b.length)\n throw new ArrayIndexOutOfBoundsException();\n if (pos >= count)\n // EOF\n return -1;\n int numRead = Math.min(len, count - pos);\n if (numRead < 0)\n return 0;\n buffer.getBytes(pos, pos + numRead, b, off);\n pos += numRead;\n return numRead;\n }\n\n /**\n * This method sets the read position in the stream to the beginning\n * setting the pos variable equal to 0. Note that this differs\n * from the common implementation of the reset() method.\n */\n ", "post_mask_code": "\n\n /**\n * This method attempts to skip the requested number of bytes in the\n * input stream. It does this by advancing the pos value by the\n * specified number of bytes. It this would exceed the length of the\n * buffer, then only enough bytes are skipped to position the stream at\n * the end of the buffer. The actual number of bytes skipped is returned.\n *\n * @param n The requested number of bytes to skip\n *\n * @return The actual number of bytes skipped.\n */\n public long skip(long n) {\n if (n < 0)\n return 0L;\n long actualSkip = Math.min(n, count - pos);\n pos += actualSkip;\n return actualSkip;\n }\n}\n"} {"task_id": "Java_2989", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Androxyde/Flashtool/src/org/atteo/xmlcombiner/Key.java", "mask_start_position": 1287, "mask_end_position": 1326, "canonical_solution": "@Override\n public String toString() ", "pre_mask_code": "package org.atteo.xmlcombiner;\n\nimport java.util.Map;\n\n/**\n * Element name and the value of it's 'id' attribute if exists.\n */\nclass Key {\n\n public static final Key BEFORE_END = new Key(\"\", null);\n\n private final String name;\n\n private final Map keys;\n\n public Key(String name, Map keys) {\n this.name = name;\n this.keys = keys;\n }\n\n @Override\n public int hashCode() {\n int hash = 1;\n if (name != null) {\n hash += name.hashCode();\n }\n if (keys != null) {\n hash = hash * 37 + keys.hashCode();\n }\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Key other = (Key) obj;\n if ((name == null) ? (other.getName() != null) : !name.equals(other.getName())) {\n return false;\n }\n if ((keys == null) ? (other.getId() != null) : !keys.equals(other.getId())) {\n return false;\n }\n return true;\n }\n\n public Map getId() {\n return keys;\n }\n\n public String getName() {\n return name;\n }\n\n ", "post_mask_code": "{\n if (keys != null) {\n return name + \"#\" + keys;\n } else {\n return name;\n }\n }\n}\n"} {"task_id": "Java_2990", "language": "Java", "task_type": "method_body", "source_file": "java/github/Androxyde/Flashtool/src/org/atteo/xmlcombiner/Key.java", "mask_start_position": 433, "mask_end_position": 644, "canonical_solution": "{\n int hash = 1;\n if (name != null) {\n hash += name.hashCode();\n }\n if (keys != null) {\n hash = hash * 37 + keys.hashCode();\n }\n return hash;\n }", "pre_mask_code": "package org.atteo.xmlcombiner;\n\nimport java.util.Map;\n\n/**\n * Element name and the value of it's 'id' attribute if exists.\n */\nclass Key {\n\n public static final Key BEFORE_END = new Key(\"\", null);\n\n private final String name;\n\n private final Map keys;\n\n public Key(String name, Map keys) {\n this.name = name;\n this.keys = keys;\n }\n\n @Override\n public int hashCode() ", "post_mask_code": "\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Key other = (Key) obj;\n if ((name == null) ? (other.getName() != null) : !name.equals(other.getName())) {\n return false;\n }\n if ((keys == null) ? (other.getId() != null) : !keys.equals(other.getId())) {\n return false;\n }\n return true;\n }\n\n public Map getId() {\n return keys;\n }\n\n public String getName() {\n return name;\n }\n\n @Override\n public String toString() {\n if (keys != null) {\n return name + \"#\" + keys;\n } else {\n return name;\n }\n }\n}\n"} {"task_id": "Java_2991", "language": "Java", "task_type": "single_line", "source_file": "java/github/Androxyde/Flashtool/src/org/atteo/xmlcombiner/Key.java", "mask_start_position": 630, "mask_end_position": 638, "canonical_solution": "rn hash;", "pre_mask_code": "package org.atteo.xmlcombiner;\n\nimport java.util.Map;\n\n/**\n * Element name and the value of it's 'id' attribute if exists.\n */\nclass Key {\n\n public static final Key BEFORE_END = new Key(\"\", null);\n\n private final String name;\n\n private final Map keys;\n\n public Key(String name, Map keys) {\n this.name = name;\n this.keys = keys;\n }\n\n @Override\n public int hashCode() {\n int hash = 1;\n if (name != null) {\n hash += name.hashCode();\n }\n if (keys != null) {\n hash = hash * 37 + keys.hashCode();\n }\n retu", "post_mask_code": "\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Key other = (Key) obj;\n if ((name == null) ? (other.getName() != null) : !name.equals(other.getName())) {\n return false;\n }\n if ((keys == null) ? (other.getId() != null) : !keys.equals(other.getId())) {\n return false;\n }\n return true;\n }\n\n public Map getId() {\n return keys;\n }\n\n public String getName() {\n return name;\n }\n\n @Override\n public String toString() {\n if (keys != null) {\n return name + \"#\" + keys;\n } else {\n return name;\n }\n }\n}\n"} {"task_id": "Java_2992", "language": "Java", "task_type": "method_signature", "source_file": "java/github/Tanaguru/Tanaguru/rules/rgaa3-2016/src/main/java/org/tanaguru/rules/rgaa32016/Rgaa32016Rule010202.java", "mask_start_position": 4338, "mask_end_position": 4393, "canonical_solution": "private ElementChecker getLocalRegularElementChecker() ", "pre_mask_code": "/*\n * Tanaguru - Automated webpage assessment\n *\n *\n * Contact us by mail: tanaguru AT tanaguru DOT org\n */\npackage org.tanaguru.rules.rgaa32016;\n\nimport java.util.Collections;\nimport org.apache.commons.lang3.tuple.ImmutablePair;\nimport static org.tanaguru.entity.audit.TestSolution.FAILED;\nimport static org.tanaguru.entity.audit.TestSolution.NEED_MORE_INFO;\nimport static org.tanaguru.entity.audit.TestSolution.PASSED;\nimport org.tanaguru.ruleimplementation.AbstractMarkerPageRuleImplementation;\nimport org.tanaguru.rules.elementchecker.CompositeChecker;\nimport org.tanaguru.rules.elementchecker.ElementChecker;\nimport org.tanaguru.rules.elementchecker.attribute.AttributePresenceChecker;\nimport org.tanaguru.rules.elementchecker.text.TextEmptinessChecker;\nimport org.tanaguru.rules.elementselector.AreaElementSelector;\nimport org.tanaguru.rules.elementselector.ImageElementSelector;\nimport static org.tanaguru.rules.keystore.AttributeStore.ALT_ATTR;\nimport static org.tanaguru.rules.keystore.AttributeStore.ARIA_DESCRIBEDBY_ATTR;\nimport static org.tanaguru.rules.keystore.AttributeStore.ARIA_LABELLEDBY_ATTR;\nimport static org.tanaguru.rules.keystore.AttributeStore.ARIA_LABEL_ATTR;\nimport static org.tanaguru.rules.keystore.AttributeStore.TITLE_ATTR;\nimport static org.tanaguru.rules.keystore.MarkerStore.DECORATIVE_IMAGE_MARKER;\nimport static org.tanaguru.rules.keystore.MarkerStore.INFORMATIVE_IMAGE_MARKER;\nimport org.tanaguru.rules.keystore.RemarkMessageStore;\nimport static org.tanaguru.rules.keystore.RemarkMessageStore.DECORATIVE_ELEMENT_WITH_ARIA_DESCRIBEDBY_ATTR_MSG;\nimport static org.tanaguru.rules.keystore.RemarkMessageStore.DECORATIVE_ELEMENT_WITH_ARIA_LABELLEDBY_ATTR_MSG;\nimport static org.tanaguru.rules.keystore.RemarkMessageStore.DECORATIVE_ELEMENT_WITH_ARIA_LABEL_ATTR_MSG;\nimport static org.tanaguru.rules.keystore.RemarkMessageStore.DECORATIVE_ELEMENT_WITH_NOT_EMPTY_ALT_MSG;\nimport static org.tanaguru.rules.keystore.RemarkMessageStore.DECORATIVE_ELEMENT_WITH_TITLE_ATTR_MSG;\nimport org.tanaguru.rules.textbuilder.TextAttributeOfElementBuilder;\n\n/**\n * Implementation of the rule 1.2.2 of the referential Rgaa 3-2016.\n *
\n * For more details about the implementation, refer to the\n * rule 1.2.2 design page.\n *\n * @see \n * 1.2.2 rule specification\n */\npublic class Rgaa32016Rule010202 extends AbstractMarkerPageRuleImplementation {\n\n public Rgaa32016Rule010202() {\n super(// the decorative images are part of the scope\n DECORATIVE_IMAGE_MARKER, // the informative images are not part of the scope\n INFORMATIVE_IMAGE_MARKER);\n setElementSelector(new ImageElementSelector(new AreaElementSelector(true, true, false), true, false));\n setMarkerElementChecker(getMarkerElementChecker());\n setRegularElementChecker(getLocalRegularElementChecker());\n }\n\n /**\n * @return the checker user for marked elements\n */\n private ElementChecker getMarkerElementChecker() {\n CompositeChecker ec = new CompositeChecker(new TextEmptinessChecker(new TextAttributeOfElementBuilder(ALT_ATTR), new ImmutablePair(PASSED, \"\"), new ImmutablePair(FAILED, DECORATIVE_ELEMENT_WITH_NOT_EMPTY_ALT_MSG), ALT_ATTR, TITLE_ATTR), // Checker sur la présence de l'attribut title\n new AttributePresenceChecker(TITLE_ATTR, new ImmutablePair(FAILED, DECORATIVE_ELEMENT_WITH_TITLE_ATTR_MSG), new ImmutablePair(PASSED, \"\"), TITLE_ATTR), // checker sur la présence de l'attribut aria-label\n new AttributePresenceChecker(ARIA_LABEL_ATTR, new ImmutablePair(FAILED, DECORATIVE_ELEMENT_WITH_ARIA_LABEL_ATTR_MSG), new ImmutablePair(PASSED, \"\"), ARIA_LABEL_ATTR), // checker sur la présence de l'attribut aria-labelledby\n new AttributePresenceChecker(ARIA_LABELLEDBY_ATTR, new ImmutablePair(FAILED, DECORATIVE_ELEMENT_WITH_ARIA_LABELLEDBY_ATTR_MSG), new ImmutablePair(PASSED, \"\"), ARIA_LABELLEDBY_ATTR), // checker sur la présence de l'attribut aria-describedby\n new AttributePresenceChecker(ARIA_DESCRIBEDBY_ATTR, new ImmutablePair(FAILED, DECORATIVE_ELEMENT_WITH_ARIA_DESCRIBEDBY_ATTR_MSG), new ImmutablePair(PASSED, \"\"), ARIA_DESCRIBEDBY_ATTR));\n ec.setIsOrCombinaison(false);\n return ec;\n }\n\n /**\n * @return the checker user for not marked elements\n */\n ", "post_mask_code": "{\n CompositeChecker compositeChecker = new CompositeChecker(new TextEmptinessChecker(new TextAttributeOfElementBuilder(ALT_ATTR), new ImmutablePair(PASSED, \"\"), new ImmutablePair(FAILED, \"\")), new AttributePresenceChecker(TITLE_ATTR, new ImmutablePair(FAILED, \"\"), new ImmutablePair(PASSED, \"\")));\n compositeChecker.setIsOrCombinaison(false);\n compositeChecker.addCheckMessageFromSolution(PASSED, Collections.singletonMap(NEED_MORE_INFO, RemarkMessageStore.CHECK_NATURE_OF_IMAGE_WITH_EMPTY_ALT_MSG));\n compositeChecker.addCheckMessageFromSolution(FAILED, Collections.singletonMap(NEED_MORE_INFO, RemarkMessageStore.CHECK_NATURE_OF_IMAGE_WITH_NOT_EMPTY_ALT_MSG));\n return compositeChecker;\n }\n}\n"} {"task_id": "Java_2993", "language": "Java", "task_type": "single_line", "source_file": "java/github/Tanaguru/Tanaguru/rules/rgaa3-2016/src/main/java/org/tanaguru/rules/rgaa32016/Rgaa32016Rule010202.java", "mask_start_position": 5045, "mask_end_position": 5083, "canonical_solution": "URE_OF_IMAGE_WITH_NOT_EMPTY_ALT_MSG));", "pre_mask_code": "/*\n * Tanaguru - Automated webpage assessment\n *\n *\n * Contact us by mail: tanaguru AT tanaguru DOT org\n */\npackage org.tanaguru.rules.rgaa32016;\n\nimport java.util.Collections;\nimport org.apache.commons.lang3.tuple.ImmutablePair;\nimport static org.tanaguru.entity.audit.TestSolution.FAILED;\nimport static org.tanaguru.entity.audit.TestSolution.NEED_MORE_INFO;\nimport static org.tanaguru.entity.audit.TestSolution.PASSED;\nimport org.tanaguru.ruleimplementation.AbstractMarkerPageRuleImplementation;\nimport org.tanaguru.rules.elementchecker.CompositeChecker;\nimport org.tanaguru.rules.elementchecker.ElementChecker;\nimport org.tanaguru.rules.elementchecker.attribute.AttributePresenceChecker;\nimport org.tanaguru.rules.elementchecker.text.TextEmptinessChecker;\nimport org.tanaguru.rules.elementselector.AreaElementSelector;\nimport org.tanaguru.rules.elementselector.ImageElementSelector;\nimport static org.tanaguru.rules.keystore.AttributeStore.ALT_ATTR;\nimport static org.tanaguru.rules.keystore.AttributeStore.ARIA_DESCRIBEDBY_ATTR;\nimport static org.tanaguru.rules.keystore.AttributeStore.ARIA_LABELLEDBY_ATTR;\nimport static org.tanaguru.rules.keystore.AttributeStore.ARIA_LABEL_ATTR;\nimport static org.tanaguru.rules.keystore.AttributeStore.TITLE_ATTR;\nimport static org.tanaguru.rules.keystore.MarkerStore.DECORATIVE_IMAGE_MARKER;\nimport static org.tanaguru.rules.keystore.MarkerStore.INFORMATIVE_IMAGE_MARKER;\nimport org.tanaguru.rules.keystore.RemarkMessageStore;\nimport static org.tanaguru.rules.keystore.RemarkMessageStore.DECORATIVE_ELEMENT_WITH_ARIA_DESCRIBEDBY_ATTR_MSG;\nimport static org.tanaguru.rules.keystore.RemarkMessageStore.DECORATIVE_ELEMENT_WITH_ARIA_LABELLEDBY_ATTR_MSG;\nimport static org.tanaguru.rules.keystore.RemarkMessageStore.DECORATIVE_ELEMENT_WITH_ARIA_LABEL_ATTR_MSG;\nimport static org.tanaguru.rules.keystore.RemarkMessageStore.DECORATIVE_ELEMENT_WITH_NOT_EMPTY_ALT_MSG;\nimport static org.tanaguru.rules.keystore.RemarkMessageStore.DECORATIVE_ELEMENT_WITH_TITLE_ATTR_MSG;\nimport org.tanaguru.rules.textbuilder.TextAttributeOfElementBuilder;\n\n/**\n * Implementation of the rule 1.2.2 of the referential Rgaa 3-2016.\n *
\n * For more details about the implementation, refer to the\n * rule 1.2.2 design page.\n *\n * @see \n * 1.2.2 rule specification\n */\npublic class Rgaa32016Rule010202 extends AbstractMarkerPageRuleImplementation {\n\n public Rgaa32016Rule010202() {\n super(// the decorative images are part of the scope\n DECORATIVE_IMAGE_MARKER, // the informative images are not part of the scope\n INFORMATIVE_IMAGE_MARKER);\n setElementSelector(new ImageElementSelector(new AreaElementSelector(true, true, false), true, false));\n setMarkerElementChecker(getMarkerElementChecker());\n setRegularElementChecker(getLocalRegularElementChecker());\n }\n\n /**\n * @return the checker user for marked elements\n */\n private ElementChecker getMarkerElementChecker() {\n CompositeChecker ec = new CompositeChecker(new TextEmptinessChecker(new TextAttributeOfElementBuilder(ALT_ATTR), new ImmutablePair(PASSED, \"\"), new ImmutablePair(FAILED, DECORATIVE_ELEMENT_WITH_NOT_EMPTY_ALT_MSG), ALT_ATTR, TITLE_ATTR), // Checker sur la présence de l'attribut title\n new AttributePresenceChecker(TITLE_ATTR, new ImmutablePair(FAILED, DECORATIVE_ELEMENT_WITH_TITLE_ATTR_MSG), new ImmutablePair(PASSED, \"\"), TITLE_ATTR), // checker sur la présence de l'attribut aria-label\n new AttributePresenceChecker(ARIA_LABEL_ATTR, new ImmutablePair(FAILED, DECORATIVE_ELEMENT_WITH_ARIA_LABEL_ATTR_MSG), new ImmutablePair(PASSED, \"\"), ARIA_LABEL_ATTR), // checker sur la présence de l'attribut aria-labelledby\n new AttributePresenceChecker(ARIA_LABELLEDBY_ATTR, new ImmutablePair(FAILED, DECORATIVE_ELEMENT_WITH_ARIA_LABELLEDBY_ATTR_MSG), new ImmutablePair(PASSED, \"\"), ARIA_LABELLEDBY_ATTR), // checker sur la présence de l'attribut aria-describedby\n new AttributePresenceChecker(ARIA_DESCRIBEDBY_ATTR, new ImmutablePair(FAILED, DECORATIVE_ELEMENT_WITH_ARIA_DESCRIBEDBY_ATTR_MSG), new ImmutablePair(PASSED, \"\"), ARIA_DESCRIBEDBY_ATTR));\n ec.setIsOrCombinaison(false);\n return ec;\n }\n\n /**\n * @return the checker user for not marked elements\n */\n private ElementChecker getLocalRegularElementChecker() {\n CompositeChecker compositeChecker = new CompositeChecker(new TextEmptinessChecker(new TextAttributeOfElementBuilder(ALT_ATTR), new ImmutablePair(PASSED, \"\"), new ImmutablePair(FAILED, \"\")), new AttributePresenceChecker(TITLE_ATTR, new ImmutablePair(FAILED, \"\"), new ImmutablePair(PASSED, \"\")));\n compositeChecker.setIsOrCombinaison(false);\n compositeChecker.addCheckMessageFromSolution(PASSED, Collections.singletonMap(NEED_MORE_INFO, RemarkMessageStore.CHECK_NATURE_OF_IMAGE_WITH_EMPTY_ALT_MSG));\n compositeChecker.addCheckMessageFromSolution(FAILED, Collections.singletonMap(NEED_MORE_INFO, RemarkMessageStore.CHECK_NAT", "post_mask_code": "\n return compositeChecker;\n }\n}\n"} {"task_id": "Java_2994", "language": "Java", "task_type": "method_signature", "source_file": "java/github/CaaMoe/MultiLogin/core/src/main/java/moe/caa/multilogin/core/command/BaseCommandExecutor.java", "mask_start_position": 1800, "mask_end_position": 1879, "canonical_solution": "protected List tabComplete(ISender sender, CommandArguments arguments) ", "pre_mask_code": "package moe.caa.multilogin.core.command;\n\nimport lombok.AccessLevel;\nimport lombok.Getter;\nimport moe.caa.multilogin.core.impl.ISender;\nimport moe.caa.multilogin.core.main.MultiCore;\nimport java.sql.SQLException;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ExecutionException;\n\n@Getter(value = AccessLevel.PROTECTED)\npublic abstract class BaseCommandExecutor {\n\n private final MultiCore core;\n\n private final CommandHandler commandHandler;\n\n private final String permission;\n\n private final ConcurrentHashMap subCommand = new ConcurrentHashMap<>();\n\n protected BaseCommandExecutor(MultiCore core, CommandHandler commandHandler, String permission) {\n this.core = core;\n this.commandHandler = commandHandler;\n this.permission = permission;\n }\n\n /**\n * 执行这条指令\n *\n * @param sender 命令执行者\n * @param arguments 命令参数\n */\n protected CommandResult execute(ISender sender, CommandArguments arguments) throws SQLException, ExecutionException, InterruptedException {\n if (arguments.getLength() != 0) {\n BaseCommandExecutor executor = subCommand.get(arguments.getIndex(0).toLowerCase(Locale.ROOT));\n if (executor != null) {\n if (executor.getPermission() == null || sender.hasPermission(executor.getPermission())) {\n arguments.offset(1);\n return executor.execute(sender, arguments);\n }\n return CommandResult.NO_PERMISSION;\n }\n }\n return CommandResult.UNKNOWN_USAGE;\n }\n\n /**\n * 补全这条指令\n *\n * @param sender 命令执行者\n * @param arguments 命令参数\n */\n ", "post_mask_code": "{\n return Collections.emptyList();\n }\n}\n"} {"task_id": "Java_2995", "language": "Java", "task_type": "method_body", "source_file": "java/github/CaaMoe/MultiLogin/core/src/main/java/moe/caa/multilogin/core/command/BaseCommandExecutor.java", "mask_start_position": 1879, "mask_end_position": 1926, "canonical_solution": "{\n return Collections.emptyList();\n }", "pre_mask_code": "package moe.caa.multilogin.core.command;\n\nimport lombok.AccessLevel;\nimport lombok.Getter;\nimport moe.caa.multilogin.core.impl.ISender;\nimport moe.caa.multilogin.core.main.MultiCore;\nimport java.sql.SQLException;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ExecutionException;\n\n@Getter(value = AccessLevel.PROTECTED)\npublic abstract class BaseCommandExecutor {\n\n private final MultiCore core;\n\n private final CommandHandler commandHandler;\n\n private final String permission;\n\n private final ConcurrentHashMap subCommand = new ConcurrentHashMap<>();\n\n protected BaseCommandExecutor(MultiCore core, CommandHandler commandHandler, String permission) {\n this.core = core;\n this.commandHandler = commandHandler;\n this.permission = permission;\n }\n\n /**\n * 执行这条指令\n *\n * @param sender 命令执行者\n * @param arguments 命令参数\n */\n protected CommandResult execute(ISender sender, CommandArguments arguments) throws SQLException, ExecutionException, InterruptedException {\n if (arguments.getLength() != 0) {\n BaseCommandExecutor executor = subCommand.get(arguments.getIndex(0).toLowerCase(Locale.ROOT));\n if (executor != null) {\n if (executor.getPermission() == null || sender.hasPermission(executor.getPermission())) {\n arguments.offset(1);\n return executor.execute(sender, arguments);\n }\n return CommandResult.NO_PERMISSION;\n }\n }\n return CommandResult.UNKNOWN_USAGE;\n }\n\n /**\n * 补全这条指令\n *\n * @param sender 命令执行者\n * @param arguments 命令参数\n */\n protected List tabComplete(ISender sender, CommandArguments arguments) ", "post_mask_code": "\n}\n"} {"task_id": "Java_2996", "language": "Java", "task_type": "single_line", "source_file": "java/github/CaaMoe/MultiLogin/core/src/main/java/moe/caa/multilogin/core/command/BaseCommandExecutor.java", "mask_start_position": 1669, "mask_end_position": 1692, "canonical_solution": "ndResult.UNKNOWN_USAGE;", "pre_mask_code": "package moe.caa.multilogin.core.command;\n\nimport lombok.AccessLevel;\nimport lombok.Getter;\nimport moe.caa.multilogin.core.impl.ISender;\nimport moe.caa.multilogin.core.main.MultiCore;\nimport java.sql.SQLException;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ExecutionException;\n\n@Getter(value = AccessLevel.PROTECTED)\npublic abstract class BaseCommandExecutor {\n\n private final MultiCore core;\n\n private final CommandHandler commandHandler;\n\n private final String permission;\n\n private final ConcurrentHashMap subCommand = new ConcurrentHashMap<>();\n\n protected BaseCommandExecutor(MultiCore core, CommandHandler commandHandler, String permission) {\n this.core = core;\n this.commandHandler = commandHandler;\n this.permission = permission;\n }\n\n /**\n * 执行这条指令\n *\n * @param sender 命令执行者\n * @param arguments 命令参数\n */\n protected CommandResult execute(ISender sender, CommandArguments arguments) throws SQLException, ExecutionException, InterruptedException {\n if (arguments.getLength() != 0) {\n BaseCommandExecutor executor = subCommand.get(arguments.getIndex(0).toLowerCase(Locale.ROOT));\n if (executor != null) {\n if (executor.getPermission() == null || sender.hasPermission(executor.getPermission())) {\n arguments.offset(1);\n return executor.execute(sender, arguments);\n }\n return CommandResult.NO_PERMISSION;\n }\n }\n return Comma", "post_mask_code": "\n }\n\n /**\n * 补全这条指令\n *\n * @param sender 命令执行者\n * @param arguments 命令参数\n */\n protected List tabComplete(ISender sender, CommandArguments arguments) {\n return Collections.emptyList();\n }\n}\n"} {"task_id": "Java_2997", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/CaaMoe/MultiLogin/core/src/main/java/moe/caa/multilogin/core/command/BaseCommandExecutor.java", "mask_start_position": 1800, "mask_end_position": 1926, "canonical_solution": "protected List tabComplete(ISender sender, CommandArguments arguments) {\n return Collections.emptyList();\n }", "pre_mask_code": "package moe.caa.multilogin.core.command;\n\nimport lombok.AccessLevel;\nimport lombok.Getter;\nimport moe.caa.multilogin.core.impl.ISender;\nimport moe.caa.multilogin.core.main.MultiCore;\nimport java.sql.SQLException;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ExecutionException;\n\n@Getter(value = AccessLevel.PROTECTED)\npublic abstract class BaseCommandExecutor {\n\n private final MultiCore core;\n\n private final CommandHandler commandHandler;\n\n private final String permission;\n\n private final ConcurrentHashMap subCommand = new ConcurrentHashMap<>();\n\n protected BaseCommandExecutor(MultiCore core, CommandHandler commandHandler, String permission) {\n this.core = core;\n this.commandHandler = commandHandler;\n this.permission = permission;\n }\n\n /**\n * 执行这条指令\n *\n * @param sender 命令执行者\n * @param arguments 命令参数\n */\n protected CommandResult execute(ISender sender, CommandArguments arguments) throws SQLException, ExecutionException, InterruptedException {\n if (arguments.getLength() != 0) {\n BaseCommandExecutor executor = subCommand.get(arguments.getIndex(0).toLowerCase(Locale.ROOT));\n if (executor != null) {\n if (executor.getPermission() == null || sender.hasPermission(executor.getPermission())) {\n arguments.offset(1);\n return executor.execute(sender, arguments);\n }\n return CommandResult.NO_PERMISSION;\n }\n }\n return CommandResult.UNKNOWN_USAGE;\n }\n\n /**\n * 补全这条指令\n *\n * @param sender 命令执行者\n * @param arguments 命令参数\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_2998", "language": "Java", "task_type": "method_signature", "source_file": "java/github/hussien89aa/AndroidTutorialForBeginners/Alaram App/app/src/main/java/com/alrubaye/alaram/savedata.java", "mask_start_position": 740, "mask_end_position": 763, "canonical_solution": "public void LoadData() ", "pre_mask_code": "package com.alrubaye.alaram;\n\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport java.util.Calendar;\n\n/**\n * Created by hussienalrubaye on 11/1/16.\n */\npublic class savedata {\n\n SharedPreferences ShredRef;\n\n Context context;\n\n public savedata(Context context) {\n this.context = context;\n ShredRef = context.getSharedPreferences(\"myRef\", Context.MODE_PRIVATE);\n }\n\n public void SaveData(int hour, int minute) {\n SharedPreferences.Editor editor = ShredRef.edit();\n editor.putInt(\"hour\", hour);\n editor.putInt(\"minute\", minute);\n editor.commit();\n }\n\n ", "post_mask_code": "{\n int Minute = ShredRef.getInt(\"minute\", 0);\n int Hour = ShredRef.getInt(\"hour\", 0);\n Alarmset(Hour, Minute);\n }\n\n void Alarmset(int Hour, int Minute) {\n Calendar calendar = Calendar.getInstance();\n calendar.set(Calendar.HOUR_OF_DAY, Hour);\n calendar.set(Calendar.MINUTE, Minute);\n calendar.set(Calendar.SECOND, 0);\n AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n Intent intent = new Intent(context, MyReceiver.class);\n intent.setAction(\"com.alraby.alam\");\n intent.putExtra(\"MyMessage\", \"hello from alarm\");\n PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);\n am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);\n }\n}\n"} {"task_id": "Java_2999", "language": "Java", "task_type": "method_body", "source_file": "java/github/hussien89aa/AndroidTutorialForBeginners/Alaram App/app/src/main/java/com/alrubaye/alaram/savedata.java", "mask_start_position": 565, "mask_end_position": 734, "canonical_solution": "{\n SharedPreferences.Editor editor = ShredRef.edit();\n editor.putInt(\"hour\", hour);\n editor.putInt(\"minute\", minute);\n editor.commit();\n }", "pre_mask_code": "package com.alrubaye.alaram;\n\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport java.util.Calendar;\n\n/**\n * Created by hussienalrubaye on 11/1/16.\n */\npublic class savedata {\n\n SharedPreferences ShredRef;\n\n Context context;\n\n public savedata(Context context) {\n this.context = context;\n ShredRef = context.getSharedPreferences(\"myRef\", Context.MODE_PRIVATE);\n }\n\n public void SaveData(int hour, int minute) ", "post_mask_code": "\n\n public void LoadData() {\n int Minute = ShredRef.getInt(\"minute\", 0);\n int Hour = ShredRef.getInt(\"hour\", 0);\n Alarmset(Hour, Minute);\n }\n\n void Alarmset(int Hour, int Minute) {\n Calendar calendar = Calendar.getInstance();\n calendar.set(Calendar.HOUR_OF_DAY, Hour);\n calendar.set(Calendar.MINUTE, Minute);\n calendar.set(Calendar.SECOND, 0);\n AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n Intent intent = new Intent(context, MyReceiver.class);\n intent.setAction(\"com.alraby.alam\");\n intent.putExtra(\"MyMessage\", \"hello from alarm\");\n PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);\n am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);\n }\n}\n"} {"task_id": "Java_3000", "language": "Java", "task_type": "single_line", "source_file": "java/github/hussien89aa/AndroidTutorialForBeginners/Alaram App/app/src/main/java/com/alrubaye/alaram/savedata.java", "mask_start_position": 872, "mask_end_position": 894, "canonical_solution": "larmset(Hour, Minute);", "pre_mask_code": "package com.alrubaye.alaram;\n\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport java.util.Calendar;\n\n/**\n * Created by hussienalrubaye on 11/1/16.\n */\npublic class savedata {\n\n SharedPreferences ShredRef;\n\n Context context;\n\n public savedata(Context context) {\n this.context = context;\n ShredRef = context.getSharedPreferences(\"myRef\", Context.MODE_PRIVATE);\n }\n\n public void SaveData(int hour, int minute) {\n SharedPreferences.Editor editor = ShredRef.edit();\n editor.putInt(\"hour\", hour);\n editor.putInt(\"minute\", minute);\n editor.commit();\n }\n\n public void LoadData() {\n int Minute = ShredRef.getInt(\"minute\", 0);\n int Hour = ShredRef.getInt(\"hour\", 0);\n A", "post_mask_code": "\n }\n\n void Alarmset(int Hour, int Minute) {\n Calendar calendar = Calendar.getInstance();\n calendar.set(Calendar.HOUR_OF_DAY, Hour);\n calendar.set(Calendar.MINUTE, Minute);\n calendar.set(Calendar.SECOND, 0);\n AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n Intent intent = new Intent(context, MyReceiver.class);\n intent.setAction(\"com.alraby.alam\");\n intent.putExtra(\"MyMessage\", \"hello from alarm\");\n PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);\n am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);\n }\n}\n"} {"task_id": "Java_3001", "language": "Java", "task_type": "method_signature", "source_file": "java/github/nokia/RED/src/Eclipse-IDE/org.robotframework.ide.eclipse.main.plugin.tests/src/org/robotframework/red/nattable/configs/RowHeaderStyleConfigurationTest.java", "mask_start_position": 1811, "mask_end_position": 1898, "canonical_solution": "@Override\n public boolean matches(final RowHeaderStyleConfiguration config) ", "pre_mask_code": "package org.robotframework.red.nattable.configs;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.when;\nimport org.assertj.core.api.Condition;\nimport org.eclipse.swt.graphics.Color;\nimport org.eclipse.swt.graphics.Font;\nimport org.eclipse.swt.widgets.Display;\nimport org.junit.jupiter.api.Test;\nimport org.robotframework.ide.eclipse.main.plugin.tableeditor.TableThemes.TableTheme;\nimport org.robotframework.red.graphics.ColorsManager;\nimport org.robotframework.red.nattable.painter.UnderlinedCellBackgroundPainter;\n\npublic class RowHeaderStyleConfigurationTest {\n\n @Test\n public void configurationCheck() {\n final Font fontInUse = Display.getCurrent().getSystemFont();\n final Color bgColorInUse = ColorsManager.getColor(200, 200, 200);\n final Color fgColorInUse = ColorsManager.getColor(100, 100, 100);\n final TableTheme theme = mock(TableTheme.class);\n when(theme.getFont()).thenReturn(fontInUse);\n when(theme.getHeadersBackground()).thenReturn(bgColorInUse);\n when(theme.getHeadersForeground()).thenReturn(fgColorInUse);\n when(theme.getHeadersUnderlineColor()).thenReturn(ColorsManager.getColor(200, 0, 0));\n final RowHeaderStyleConfiguration configuration = new RowHeaderStyleConfiguration(theme);\n assertThat(configuration).has(font(fontInUse));\n assertThat(configuration).has(background(bgColorInUse));\n assertThat(configuration).has(foreground(fgColorInUse));\n assertThat(configuration.cellPainter).isInstanceOf(UnderlinedCellBackgroundPainter.class);\n }\n\n private Condition background(final Color bgColorInUse) {\n return new Condition() {\n\n ", "post_mask_code": "{\n return config.bgColor.equals(bgColorInUse);\n }\n };\n }\n\n private Condition foreground(final Color fgColorInUse) {\n return new Condition() {\n\n @Override\n public boolean matches(final RowHeaderStyleConfiguration config) {\n return config.fgColor.equals(fgColorInUse);\n }\n };\n }\n\n private static Condition font(final Font font) {\n return new Condition() {\n\n @Override\n public boolean matches(final RowHeaderStyleConfiguration config) {\n return config.font.equals(font);\n }\n };\n }\n}\n"} {"task_id": "Java_3002", "language": "Java", "task_type": "method_body", "source_file": "java/github/nokia/RED/src/Eclipse-IDE/org.robotframework.ide.eclipse.main.plugin.tests/src/org/robotframework/red/nattable/configs/RowHeaderStyleConfigurationTest.java", "mask_start_position": 2418, "mask_end_position": 2663, "canonical_solution": "{\n return new Condition() {\n\n @Override\n public boolean matches(final RowHeaderStyleConfiguration config) {\n return config.font.equals(font);\n }\n };\n }", "pre_mask_code": "package org.robotframework.red.nattable.configs;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.when;\nimport org.assertj.core.api.Condition;\nimport org.eclipse.swt.graphics.Color;\nimport org.eclipse.swt.graphics.Font;\nimport org.eclipse.swt.widgets.Display;\nimport org.junit.jupiter.api.Test;\nimport org.robotframework.ide.eclipse.main.plugin.tableeditor.TableThemes.TableTheme;\nimport org.robotframework.red.graphics.ColorsManager;\nimport org.robotframework.red.nattable.painter.UnderlinedCellBackgroundPainter;\n\npublic class RowHeaderStyleConfigurationTest {\n\n @Test\n public void configurationCheck() {\n final Font fontInUse = Display.getCurrent().getSystemFont();\n final Color bgColorInUse = ColorsManager.getColor(200, 200, 200);\n final Color fgColorInUse = ColorsManager.getColor(100, 100, 100);\n final TableTheme theme = mock(TableTheme.class);\n when(theme.getFont()).thenReturn(fontInUse);\n when(theme.getHeadersBackground()).thenReturn(bgColorInUse);\n when(theme.getHeadersForeground()).thenReturn(fgColorInUse);\n when(theme.getHeadersUnderlineColor()).thenReturn(ColorsManager.getColor(200, 0, 0));\n final RowHeaderStyleConfiguration configuration = new RowHeaderStyleConfiguration(theme);\n assertThat(configuration).has(font(fontInUse));\n assertThat(configuration).has(background(bgColorInUse));\n assertThat(configuration).has(foreground(fgColorInUse));\n assertThat(configuration.cellPainter).isInstanceOf(UnderlinedCellBackgroundPainter.class);\n }\n\n private Condition background(final Color bgColorInUse) {\n return new Condition() {\n\n @Override\n public boolean matches(final RowHeaderStyleConfiguration config) {\n return config.bgColor.equals(bgColorInUse);\n }\n };\n }\n\n private Condition foreground(final Color fgColorInUse) {\n return new Condition() {\n\n @Override\n public boolean matches(final RowHeaderStyleConfiguration config) {\n return config.fgColor.equals(fgColorInUse);\n }\n };\n }\n\n private static Condition font(final Font font) ", "post_mask_code": "\n}\n"} {"task_id": "Java_3003", "language": "Java", "task_type": "single_line", "source_file": "java/github/nokia/RED/src/Eclipse-IDE/org.robotframework.ide.eclipse.main.plugin.tests/src/org/robotframework/red/nattable/configs/RowHeaderStyleConfigurationTest.java", "mask_start_position": 1105, "mask_end_position": 1161, "canonical_solution": "(theme.getHeadersForeground()).thenReturn(fgColorInUse);", "pre_mask_code": "package org.robotframework.red.nattable.configs;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.when;\nimport org.assertj.core.api.Condition;\nimport org.eclipse.swt.graphics.Color;\nimport org.eclipse.swt.graphics.Font;\nimport org.eclipse.swt.widgets.Display;\nimport org.junit.jupiter.api.Test;\nimport org.robotframework.ide.eclipse.main.plugin.tableeditor.TableThemes.TableTheme;\nimport org.robotframework.red.graphics.ColorsManager;\nimport org.robotframework.red.nattable.painter.UnderlinedCellBackgroundPainter;\n\npublic class RowHeaderStyleConfigurationTest {\n\n @Test\n public void configurationCheck() {\n final Font fontInUse = Display.getCurrent().getSystemFont();\n final Color bgColorInUse = ColorsManager.getColor(200, 200, 200);\n final Color fgColorInUse = ColorsManager.getColor(100, 100, 100);\n final TableTheme theme = mock(TableTheme.class);\n when(theme.getFont()).thenReturn(fontInUse);\n when(theme.getHeadersBackground()).thenReturn(bgColorInUse);\n when", "post_mask_code": "\n when(theme.getHeadersUnderlineColor()).thenReturn(ColorsManager.getColor(200, 0, 0));\n final RowHeaderStyleConfiguration configuration = new RowHeaderStyleConfiguration(theme);\n assertThat(configuration).has(font(fontInUse));\n assertThat(configuration).has(background(bgColorInUse));\n assertThat(configuration).has(foreground(fgColorInUse));\n assertThat(configuration.cellPainter).isInstanceOf(UnderlinedCellBackgroundPainter.class);\n }\n\n private Condition background(final Color bgColorInUse) {\n return new Condition() {\n\n @Override\n public boolean matches(final RowHeaderStyleConfiguration config) {\n return config.bgColor.equals(bgColorInUse);\n }\n };\n }\n\n private Condition foreground(final Color fgColorInUse) {\n return new Condition() {\n\n @Override\n public boolean matches(final RowHeaderStyleConfiguration config) {\n return config.fgColor.equals(fgColorInUse);\n }\n };\n }\n\n private static Condition font(final Font font) {\n return new Condition() {\n\n @Override\n public boolean matches(final RowHeaderStyleConfiguration config) {\n return config.font.equals(font);\n }\n };\n }\n}\n"} {"task_id": "Java_3004", "language": "Java", "task_type": "method_signature", "source_file": "java/github/onelogin/java-saml/core/src/main/java/com/onelogin/saml2/model/AttributeConsumingService.java", "mask_start_position": 1522, "mask_end_position": 1566, "canonical_solution": "public final String getServiceDescription() ", "pre_mask_code": "package com.onelogin.saml2.model;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport com.onelogin.saml2.model.RequestedAttribute;\n\n/**\n * AttributeConsumingService class of OneLogin's Java Toolkit.\n *\n * A class that stores AttributeConsumingService\n */\npublic class AttributeConsumingService {\n\n /**\n * Service Name\n */\n private final String serviceName;\n\n /**\n * Service Description\n */\n private final String serviceDescription;\n\n /**\n * Requested Attributes\n */\n private final List requestedAttributes;\n\n /**\n * Constructor\n *\n * @param serviceName\n * String. Service Name\n * @param serviceDescription\n * String. Service Description\n */\n public AttributeConsumingService(String serviceName, String serviceDescription) {\n this.serviceName = serviceName != null ? serviceName : \"\";\n this.serviceDescription = serviceDescription != null ? serviceDescription : \"\";\n this.requestedAttributes = new ArrayList();\n }\n\n /**\n * @param attr\n * RequestedAttribute. The requested attribute to be included\n */\n public final void addRequestedAttribute(RequestedAttribute attr) {\n this.requestedAttributes.add(attr);\n }\n\n /**\n * @return string the service name\n */\n public final String getServiceName() {\n return serviceName;\n }\n\n /**\n * @return string the service description\n */\n ", "post_mask_code": "{\n return serviceDescription;\n }\n\n /**\n * @return List the requested attributes\n */\n public final List getRequestedAttributes() {\n return requestedAttributes;\n }\n}\n"} {"task_id": "Java_3005", "language": "Java", "task_type": "method_body", "source_file": "java/github/onelogin/java-saml/core/src/main/java/com/onelogin/saml2/model/AttributeConsumingService.java", "mask_start_position": 1566, "mask_end_position": 1608, "canonical_solution": "{\n return serviceDescription;\n }", "pre_mask_code": "package com.onelogin.saml2.model;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport com.onelogin.saml2.model.RequestedAttribute;\n\n/**\n * AttributeConsumingService class of OneLogin's Java Toolkit.\n *\n * A class that stores AttributeConsumingService\n */\npublic class AttributeConsumingService {\n\n /**\n * Service Name\n */\n private final String serviceName;\n\n /**\n * Service Description\n */\n private final String serviceDescription;\n\n /**\n * Requested Attributes\n */\n private final List requestedAttributes;\n\n /**\n * Constructor\n *\n * @param serviceName\n * String. Service Name\n * @param serviceDescription\n * String. Service Description\n */\n public AttributeConsumingService(String serviceName, String serviceDescription) {\n this.serviceName = serviceName != null ? serviceName : \"\";\n this.serviceDescription = serviceDescription != null ? serviceDescription : \"\";\n this.requestedAttributes = new ArrayList();\n }\n\n /**\n * @param attr\n * RequestedAttribute. The requested attribute to be included\n */\n public final void addRequestedAttribute(RequestedAttribute attr) {\n this.requestedAttributes.add(attr);\n }\n\n /**\n * @return string the service name\n */\n public final String getServiceName() {\n return serviceName;\n }\n\n /**\n * @return string the service description\n */\n public final String getServiceDescription() ", "post_mask_code": "\n\n /**\n * @return List the requested attributes\n */\n public final List getRequestedAttributes() {\n return requestedAttributes;\n }\n}\n"} {"task_id": "Java_3006", "language": "Java", "task_type": "single_line", "source_file": "java/github/onelogin/java-saml/core/src/main/java/com/onelogin/saml2/model/AttributeConsumingService.java", "mask_start_position": 1770, "mask_end_position": 1775, "canonical_solution": "utes;", "pre_mask_code": "package com.onelogin.saml2.model;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport com.onelogin.saml2.model.RequestedAttribute;\n\n/**\n * AttributeConsumingService class of OneLogin's Java Toolkit.\n *\n * A class that stores AttributeConsumingService\n */\npublic class AttributeConsumingService {\n\n /**\n * Service Name\n */\n private final String serviceName;\n\n /**\n * Service Description\n */\n private final String serviceDescription;\n\n /**\n * Requested Attributes\n */\n private final List requestedAttributes;\n\n /**\n * Constructor\n *\n * @param serviceName\n * String. Service Name\n * @param serviceDescription\n * String. Service Description\n */\n public AttributeConsumingService(String serviceName, String serviceDescription) {\n this.serviceName = serviceName != null ? serviceName : \"\";\n this.serviceDescription = serviceDescription != null ? serviceDescription : \"\";\n this.requestedAttributes = new ArrayList();\n }\n\n /**\n * @param attr\n * RequestedAttribute. The requested attribute to be included\n */\n public final void addRequestedAttribute(RequestedAttribute attr) {\n this.requestedAttributes.add(attr);\n }\n\n /**\n * @return string the service name\n */\n public final String getServiceName() {\n return serviceName;\n }\n\n /**\n * @return string the service description\n */\n public final String getServiceDescription() {\n return serviceDescription;\n }\n\n /**\n * @return List the requested attributes\n */\n public final List getRequestedAttributes() {\n return requestedAttrib", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_3007", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/onelogin/java-saml/core/src/main/java/com/onelogin/saml2/model/AttributeConsumingService.java", "mask_start_position": 1675, "mask_end_position": 1781, "canonical_solution": "public final List getRequestedAttributes() {\n return requestedAttributes;\n }", "pre_mask_code": "package com.onelogin.saml2.model;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport com.onelogin.saml2.model.RequestedAttribute;\n\n/**\n * AttributeConsumingService class of OneLogin's Java Toolkit.\n *\n * A class that stores AttributeConsumingService\n */\npublic class AttributeConsumingService {\n\n /**\n * Service Name\n */\n private final String serviceName;\n\n /**\n * Service Description\n */\n private final String serviceDescription;\n\n /**\n * Requested Attributes\n */\n private final List requestedAttributes;\n\n /**\n * Constructor\n *\n * @param serviceName\n * String. Service Name\n * @param serviceDescription\n * String. Service Description\n */\n public AttributeConsumingService(String serviceName, String serviceDescription) {\n this.serviceName = serviceName != null ? serviceName : \"\";\n this.serviceDescription = serviceDescription != null ? serviceDescription : \"\";\n this.requestedAttributes = new ArrayList();\n }\n\n /**\n * @param attr\n * RequestedAttribute. The requested attribute to be included\n */\n public final void addRequestedAttribute(RequestedAttribute attr) {\n this.requestedAttributes.add(attr);\n }\n\n /**\n * @return string the service name\n */\n public final String getServiceName() {\n return serviceName;\n }\n\n /**\n * @return string the service description\n */\n public final String getServiceDescription() {\n return serviceDescription;\n }\n\n /**\n * @return List the requested attributes\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_3008", "language": "Java", "task_type": "method_signature", "source_file": "java/github/zhangyd-c/OneBlog/blog-core/src/main/java/com/zyd/blog/util/RequestUtil.java", "mask_start_position": 1567, "mask_end_position": 1596, "canonical_solution": "public static String getUa() ", "pre_mask_code": "package com.zyd.blog.util;\n\nimport com.zyd.blog.framework.holder.RequestHolder;\nimport javax.servlet.http.HttpServletRequest;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * @author yadong.zhang (yadong.zhang0415(a)gmail.com)\n * @version 1.0\n * @website https://docs.zhyd.me\n * @date 2018/4/18 11:48\n * @since 1.0\n */\npublic class RequestUtil {\n\n public static String getParameters() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n Enumeration paraNames = request.getParameterNames();\n if (paraNames == null) {\n return null;\n }\n StringBuilder sb = new StringBuilder();\n while (paraNames.hasMoreElements()) {\n String paraName = paraNames.nextElement();\n sb.append(\"&\").append(paraName).append(\"=\").append(request.getParameter(paraName));\n }\n return sb.toString();\n }\n\n public static Map getParametersMap() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return new HashMap<>();\n }\n return request.getParameterMap();\n }\n\n public static String getHeader(String headerName) {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return request.getHeader(headerName);\n }\n\n public static String getReferer() {\n return getHeader(\"Referer\");\n }\n\n ", "post_mask_code": "{\n return getHeader(\"User-Agent\");\n }\n\n public static String getIp() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return IpUtil.getRealIp(request);\n }\n\n public static String getRequestUrl() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return request.getRequestURL().toString();\n }\n\n public static String getMethod() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return request.getMethod();\n }\n\n public static boolean isAjax(HttpServletRequest request) {\n if (null == request) {\n request = RequestHolder.getRequest();\n }\n if (null == request) {\n return false;\n }\n return \"XMLHttpRequest\".equalsIgnoreCase(request.getHeader(\"X-Requested-With\")) || request.getParameter(\"ajax\") != null;\n }\n}\n"} {"task_id": "Java_3009", "language": "Java", "task_type": "method_body", "source_file": "java/github/zhangyd-c/OneBlog/blog-core/src/main/java/com/zyd/blog/util/RequestUtil.java", "mask_start_position": 1293, "mask_end_position": 1477, "canonical_solution": "{\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return request.getHeader(headerName);\n }", "pre_mask_code": "package com.zyd.blog.util;\n\nimport com.zyd.blog.framework.holder.RequestHolder;\nimport javax.servlet.http.HttpServletRequest;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * @author yadong.zhang (yadong.zhang0415(a)gmail.com)\n * @version 1.0\n * @website https://docs.zhyd.me\n * @date 2018/4/18 11:48\n * @since 1.0\n */\npublic class RequestUtil {\n\n public static String getParameters() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n Enumeration paraNames = request.getParameterNames();\n if (paraNames == null) {\n return null;\n }\n StringBuilder sb = new StringBuilder();\n while (paraNames.hasMoreElements()) {\n String paraName = paraNames.nextElement();\n sb.append(\"&\").append(paraName).append(\"=\").append(request.getParameter(paraName));\n }\n return sb.toString();\n }\n\n public static Map getParametersMap() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return new HashMap<>();\n }\n return request.getParameterMap();\n }\n\n public static String getHeader(String headerName) ", "post_mask_code": "\n\n public static String getReferer() {\n return getHeader(\"Referer\");\n }\n\n public static String getUa() {\n return getHeader(\"User-Agent\");\n }\n\n public static String getIp() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return IpUtil.getRealIp(request);\n }\n\n public static String getRequestUrl() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return request.getRequestURL().toString();\n }\n\n public static String getMethod() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return request.getMethod();\n }\n\n public static boolean isAjax(HttpServletRequest request) {\n if (null == request) {\n request = RequestHolder.getRequest();\n }\n if (null == request) {\n return false;\n }\n return \"XMLHttpRequest\".equalsIgnoreCase(request.getHeader(\"X-Requested-With\")) || request.getParameter(\"ajax\") != null;\n }\n}\n"} {"task_id": "Java_3010", "language": "Java", "task_type": "single_line", "source_file": "java/github/zhangyd-c/OneBlog/blog-core/src/main/java/com/zyd/blog/util/RequestUtil.java", "mask_start_position": 1615, "mask_end_position": 1637, "canonical_solution": "tHeader(\"User-Agent\");", "pre_mask_code": "package com.zyd.blog.util;\n\nimport com.zyd.blog.framework.holder.RequestHolder;\nimport javax.servlet.http.HttpServletRequest;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * @author yadong.zhang (yadong.zhang0415(a)gmail.com)\n * @version 1.0\n * @website https://docs.zhyd.me\n * @date 2018/4/18 11:48\n * @since 1.0\n */\npublic class RequestUtil {\n\n public static String getParameters() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n Enumeration paraNames = request.getParameterNames();\n if (paraNames == null) {\n return null;\n }\n StringBuilder sb = new StringBuilder();\n while (paraNames.hasMoreElements()) {\n String paraName = paraNames.nextElement();\n sb.append(\"&\").append(paraName).append(\"=\").append(request.getParameter(paraName));\n }\n return sb.toString();\n }\n\n public static Map getParametersMap() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return new HashMap<>();\n }\n return request.getParameterMap();\n }\n\n public static String getHeader(String headerName) {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return request.getHeader(headerName);\n }\n\n public static String getReferer() {\n return getHeader(\"Referer\");\n }\n\n public static String getUa() {\n return ge", "post_mask_code": "\n }\n\n public static String getIp() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return IpUtil.getRealIp(request);\n }\n\n public static String getRequestUrl() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return request.getRequestURL().toString();\n }\n\n public static String getMethod() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return request.getMethod();\n }\n\n public static boolean isAjax(HttpServletRequest request) {\n if (null == request) {\n request = RequestHolder.getRequest();\n }\n if (null == request) {\n return false;\n }\n return \"XMLHttpRequest\".equalsIgnoreCase(request.getHeader(\"X-Requested-With\")) || request.getParameter(\"ajax\") != null;\n }\n}\n"} {"task_id": "Java_3011", "language": "Java", "task_type": "while_statement", "source_file": "java/github/zhangyd-c/OneBlog/blog-core/src/main/java/com/zyd/blog/util/RequestUtil.java", "mask_start_position": 751, "mask_end_position": 949, "canonical_solution": "while (paraNames.hasMoreElements()) {\n String paraName = paraNames.nextElement();\n sb.append(\"&\").append(paraName).append(\"=\").append(request.getParameter(paraName));\n }", "pre_mask_code": "package com.zyd.blog.util;\n\nimport com.zyd.blog.framework.holder.RequestHolder;\nimport javax.servlet.http.HttpServletRequest;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * @author yadong.zhang (yadong.zhang0415(a)gmail.com)\n * @version 1.0\n * @website https://docs.zhyd.me\n * @date 2018/4/18 11:48\n * @since 1.0\n */\npublic class RequestUtil {\n\n public static String getParameters() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n Enumeration paraNames = request.getParameterNames();\n if (paraNames == null) {\n return null;\n }\n StringBuilder sb = new StringBuilder();\n ", "post_mask_code": "\n return sb.toString();\n }\n\n public static Map getParametersMap() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return new HashMap<>();\n }\n return request.getParameterMap();\n }\n\n public static String getHeader(String headerName) {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return request.getHeader(headerName);\n }\n\n public static String getReferer() {\n return getHeader(\"Referer\");\n }\n\n public static String getUa() {\n return getHeader(\"User-Agent\");\n }\n\n public static String getIp() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return IpUtil.getRealIp(request);\n }\n\n public static String getRequestUrl() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return request.getRequestURL().toString();\n }\n\n public static String getMethod() {\n HttpServletRequest request = RequestHolder.getRequest();\n if (null == request) {\n return null;\n }\n return request.getMethod();\n }\n\n public static boolean isAjax(HttpServletRequest request) {\n if (null == request) {\n request = RequestHolder.getRequest();\n }\n if (null == request) {\n return false;\n }\n return \"XMLHttpRequest\".equalsIgnoreCase(request.getHeader(\"X-Requested-With\")) || request.getParameter(\"ajax\") != null;\n }\n}\n"} {"task_id": "Java_3012", "language": "Java", "task_type": "method_signature", "source_file": "java/github/h0MER247/jPC/src/Hardware/CPU/Intel8086/Register/Reg8Hi.java", "mask_start_position": 165, "mask_end_position": 201, "canonical_solution": "@Override\n public int getValue() ", "pre_mask_code": "package Hardware.CPU.Intel8086.Register;\n\npublic final class Reg8Hi extends Reg8 {\n\n public Reg8Hi(String name, Reg16 reg) {\n super(name, reg);\n }\n\n ", "post_mask_code": "{\n return m_reg.getValue() >> 8;\n }\n\n @Override\n public void setValue(int value) {\n m_reg.setValue((m_reg.getValue() & 0x00ff) | ((value & 0xff) << 8));\n }\n}\n"} {"task_id": "Java_3013", "language": "Java", "task_type": "method_body", "source_file": "java/github/h0MER247/jPC/src/Hardware/CPU/Intel8086/Register/Reg8Hi.java", "mask_start_position": 298, "mask_end_position": 382, "canonical_solution": "{\n m_reg.setValue((m_reg.getValue() & 0x00ff) | ((value & 0xff) << 8));\n }", "pre_mask_code": "package Hardware.CPU.Intel8086.Register;\n\npublic final class Reg8Hi extends Reg8 {\n\n public Reg8Hi(String name, Reg16 reg) {\n super(name, reg);\n }\n\n @Override\n public int getValue() {\n return m_reg.getValue() >> 8;\n }\n\n @Override\n public void setValue(int value) ", "post_mask_code": "\n}\n"} {"task_id": "Java_3014", "language": "Java", "task_type": "single_line", "source_file": "java/github/h0MER247/jPC/src/Hardware/CPU/Intel8086/Register/Reg8Hi.java", "mask_start_position": 221, "mask_end_position": 240, "canonical_solution": "eg.getValue() >> 8;", "pre_mask_code": "package Hardware.CPU.Intel8086.Register;\n\npublic final class Reg8Hi extends Reg8 {\n\n public Reg8Hi(String name, Reg16 reg) {\n super(name, reg);\n }\n\n @Override\n public int getValue() {\n return m_r", "post_mask_code": "\n }\n\n @Override\n public void setValue(int value) {\n m_reg.setValue((m_reg.getValue() & 0x00ff) | ((value & 0xff) << 8));\n }\n}\n"} {"task_id": "Java_3015", "language": "Java", "task_type": "method_signature", "source_file": "java/github/FoxBPM/FoxBPM/modules/foxbpm-engine/src/main/java/org/foxbpm/engine/impl/bpmn/parser/model/FlowNodeParser.java", "mask_start_position": 266, "mask_end_position": 325, "canonical_solution": "public BaseElementBehavior parser(BaseElement baseElement) ", "pre_mask_code": "/**\n * @author kenshin\n * @author ych\n */\npackage org.foxbpm.engine.impl.bpmn.parser.model;\n\nimport org.foxbpm.engine.impl.bpmn.behavior.BaseElementBehavior;\nimport org.foxbpm.model.BaseElement;\n\npublic abstract class FlowNodeParser extends FlowElementParser {\n\n ", "post_mask_code": "{\n return super.parser(baseElement);\n }\n}\n"} {"task_id": "Java_3016", "language": "Java", "task_type": "method_body", "source_file": "java/github/FoxBPM/FoxBPM/modules/foxbpm-engine/src/main/java/org/foxbpm/engine/impl/bpmn/parser/model/FlowNodeParser.java", "mask_start_position": 325, "mask_end_position": 374, "canonical_solution": "{\n return super.parser(baseElement);\n }", "pre_mask_code": "/**\n * @author kenshin\n * @author ych\n */\npackage org.foxbpm.engine.impl.bpmn.parser.model;\n\nimport org.foxbpm.engine.impl.bpmn.behavior.BaseElementBehavior;\nimport org.foxbpm.model.BaseElement;\n\npublic abstract class FlowNodeParser extends FlowElementParser {\n\n public BaseElementBehavior parser(BaseElement baseElement) ", "post_mask_code": "\n}\n"} {"task_id": "Java_3017", "language": "Java", "task_type": "single_line", "source_file": "java/github/FoxBPM/FoxBPM/modules/foxbpm-engine/src/main/java/org/foxbpm/engine/impl/bpmn/parser/model/FlowNodeParser.java", "mask_start_position": 360, "mask_end_position": 368, "canonical_solution": "lement);", "pre_mask_code": "/**\n * @author kenshin\n * @author ych\n */\npackage org.foxbpm.engine.impl.bpmn.parser.model;\n\nimport org.foxbpm.engine.impl.bpmn.behavior.BaseElementBehavior;\nimport org.foxbpm.model.BaseElement;\n\npublic abstract class FlowNodeParser extends FlowElementParser {\n\n public BaseElementBehavior parser(BaseElement baseElement) {\n return super.parser(baseE", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_3018", "language": "Java", "task_type": "method_signature", "source_file": "java/github/jcodeing/K-Sonic/library-exolib/src/main/java/com/google/android/exoplayer2/extractor/mp3/VbriSeeker.java", "mask_start_position": 3663, "mask_end_position": 3705, "canonical_solution": "@Override\n public long getDurationUs() ", "pre_mask_code": "package com.google.android.exoplayer2.extractor.mp3;\n\nimport com.google.android.exoplayer2.C;\nimport com.google.android.exoplayer2.extractor.MpegAudioHeader;\nimport com.google.android.exoplayer2.util.ParsableByteArray;\nimport com.google.android.exoplayer2.util.Util;\n\n/**\n * MP3 seeker that uses metadata from a VBRI header.\n */\nfinal class VbriSeeker implements Mp3Extractor.Seeker {\n\n /**\n * Returns a {@link VbriSeeker} for seeking in the stream, if required information is present.\n * Returns {@code null} if not. On returning, {@code frame}'s position is not specified so the\n * caller should reset it.\n *\n * @param mpegAudioHeader The MPEG audio header associated with the frame.\n * @param frame The data in this audio frame, with its position set to immediately after the\n * 'VBRI' tag.\n * @param position The position (byte offset) of the start of this frame in the stream.\n * @param inputLength The length of the stream in bytes.\n * @return A {@link VbriSeeker} for seeking in the stream, or {@code null} if the required\n * information is not present.\n */\n public static VbriSeeker create(MpegAudioHeader mpegAudioHeader, ParsableByteArray frame, long position, long inputLength) {\n frame.skipBytes(10);\n int numFrames = frame.readInt();\n if (numFrames <= 0) {\n return null;\n }\n int sampleRate = mpegAudioHeader.sampleRate;\n long durationUs = Util.scaleLargeTimestamp(numFrames, C.MICROS_PER_SECOND * (sampleRate >= 32000 ? 1152 : 576), sampleRate);\n int entryCount = frame.readUnsignedShort();\n int scale = frame.readUnsignedShort();\n int entrySize = frame.readUnsignedShort();\n frame.skipBytes(2);\n // Skip the frame containing the VBRI header.\n position += mpegAudioHeader.frameSize;\n // Read table of contents entries.\n long[] timesUs = new long[entryCount + 1];\n long[] positions = new long[entryCount + 1];\n timesUs[0] = 0L;\n positions[0] = position;\n for (int index = 1; index < timesUs.length; index++) {\n int segmentSize;\n switch(entrySize) {\n case 1:\n segmentSize = frame.readUnsignedByte();\n break;\n case 2:\n segmentSize = frame.readUnsignedShort();\n break;\n case 3:\n segmentSize = frame.readUnsignedInt24();\n break;\n case 4:\n segmentSize = frame.readUnsignedIntToInt();\n break;\n default:\n return null;\n }\n position += segmentSize * scale;\n timesUs[index] = index * durationUs / entryCount;\n positions[index] = inputLength == C.LENGTH_UNSET ? position : Math.min(inputLength, position);\n }\n return new VbriSeeker(timesUs, positions, durationUs);\n }\n\n private final long[] timesUs;\n\n private final long[] positions;\n\n private final long durationUs;\n\n private VbriSeeker(long[] timesUs, long[] positions, long durationUs) {\n this.timesUs = timesUs;\n this.positions = positions;\n this.durationUs = durationUs;\n }\n\n @Override\n public boolean isSeekable() {\n return true;\n }\n\n @Override\n public long getPosition(long timeUs) {\n return positions[Util.binarySearchFloor(timesUs, timeUs, true, true)];\n }\n\n @Override\n public long getTimeUs(long position) {\n return timesUs[Util.binarySearchFloor(positions, position, true, true)];\n }\n\n ", "post_mask_code": "{\n return durationUs;\n }\n}\n"} {"task_id": "Java_3019", "language": "Java", "task_type": "method_body", "source_file": "java/github/jcodeing/K-Sonic/library-exolib/src/main/java/com/google/android/exoplayer2/extractor/mp3/VbriSeeker.java", "mask_start_position": 3341, "mask_end_position": 3369, "canonical_solution": "{\n return true;\n }", "pre_mask_code": "package com.google.android.exoplayer2.extractor.mp3;\n\nimport com.google.android.exoplayer2.C;\nimport com.google.android.exoplayer2.extractor.MpegAudioHeader;\nimport com.google.android.exoplayer2.util.ParsableByteArray;\nimport com.google.android.exoplayer2.util.Util;\n\n/**\n * MP3 seeker that uses metadata from a VBRI header.\n */\nfinal class VbriSeeker implements Mp3Extractor.Seeker {\n\n /**\n * Returns a {@link VbriSeeker} for seeking in the stream, if required information is present.\n * Returns {@code null} if not. On returning, {@code frame}'s position is not specified so the\n * caller should reset it.\n *\n * @param mpegAudioHeader The MPEG audio header associated with the frame.\n * @param frame The data in this audio frame, with its position set to immediately after the\n * 'VBRI' tag.\n * @param position The position (byte offset) of the start of this frame in the stream.\n * @param inputLength The length of the stream in bytes.\n * @return A {@link VbriSeeker} for seeking in the stream, or {@code null} if the required\n * information is not present.\n */\n public static VbriSeeker create(MpegAudioHeader mpegAudioHeader, ParsableByteArray frame, long position, long inputLength) {\n frame.skipBytes(10);\n int numFrames = frame.readInt();\n if (numFrames <= 0) {\n return null;\n }\n int sampleRate = mpegAudioHeader.sampleRate;\n long durationUs = Util.scaleLargeTimestamp(numFrames, C.MICROS_PER_SECOND * (sampleRate >= 32000 ? 1152 : 576), sampleRate);\n int entryCount = frame.readUnsignedShort();\n int scale = frame.readUnsignedShort();\n int entrySize = frame.readUnsignedShort();\n frame.skipBytes(2);\n // Skip the frame containing the VBRI header.\n position += mpegAudioHeader.frameSize;\n // Read table of contents entries.\n long[] timesUs = new long[entryCount + 1];\n long[] positions = new long[entryCount + 1];\n timesUs[0] = 0L;\n positions[0] = position;\n for (int index = 1; index < timesUs.length; index++) {\n int segmentSize;\n switch(entrySize) {\n case 1:\n segmentSize = frame.readUnsignedByte();\n break;\n case 2:\n segmentSize = frame.readUnsignedShort();\n break;\n case 3:\n segmentSize = frame.readUnsignedInt24();\n break;\n case 4:\n segmentSize = frame.readUnsignedIntToInt();\n break;\n default:\n return null;\n }\n position += segmentSize * scale;\n timesUs[index] = index * durationUs / entryCount;\n positions[index] = inputLength == C.LENGTH_UNSET ? position : Math.min(inputLength, position);\n }\n return new VbriSeeker(timesUs, positions, durationUs);\n }\n\n private final long[] timesUs;\n\n private final long[] positions;\n\n private final long durationUs;\n\n private VbriSeeker(long[] timesUs, long[] positions, long durationUs) {\n this.timesUs = timesUs;\n this.positions = positions;\n this.durationUs = durationUs;\n }\n\n @Override\n public boolean isSeekable() ", "post_mask_code": "\n\n @Override\n public long getPosition(long timeUs) {\n return positions[Util.binarySearchFloor(timesUs, timeUs, true, true)];\n }\n\n @Override\n public long getTimeUs(long position) {\n return timesUs[Util.binarySearchFloor(positions, position, true, true)];\n }\n\n @Override\n public long getDurationUs() {\n return durationUs;\n }\n}\n"} {"task_id": "Java_3020", "language": "Java", "task_type": "single_line", "source_file": "java/github/jcodeing/K-Sonic/library-exolib/src/main/java/com/google/android/exoplayer2/extractor/mp3/VbriSeeker.java", "mask_start_position": 1276, "mask_end_position": 1281, "canonical_solution": "(10);", "pre_mask_code": "package com.google.android.exoplayer2.extractor.mp3;\n\nimport com.google.android.exoplayer2.C;\nimport com.google.android.exoplayer2.extractor.MpegAudioHeader;\nimport com.google.android.exoplayer2.util.ParsableByteArray;\nimport com.google.android.exoplayer2.util.Util;\n\n/**\n * MP3 seeker that uses metadata from a VBRI header.\n */\nfinal class VbriSeeker implements Mp3Extractor.Seeker {\n\n /**\n * Returns a {@link VbriSeeker} for seeking in the stream, if required information is present.\n * Returns {@code null} if not. On returning, {@code frame}'s position is not specified so the\n * caller should reset it.\n *\n * @param mpegAudioHeader The MPEG audio header associated with the frame.\n * @param frame The data in this audio frame, with its position set to immediately after the\n * 'VBRI' tag.\n * @param position The position (byte offset) of the start of this frame in the stream.\n * @param inputLength The length of the stream in bytes.\n * @return A {@link VbriSeeker} for seeking in the stream, or {@code null} if the required\n * information is not present.\n */\n public static VbriSeeker create(MpegAudioHeader mpegAudioHeader, ParsableByteArray frame, long position, long inputLength) {\n frame.skipBytes", "post_mask_code": "\n int numFrames = frame.readInt();\n if (numFrames <= 0) {\n return null;\n }\n int sampleRate = mpegAudioHeader.sampleRate;\n long durationUs = Util.scaleLargeTimestamp(numFrames, C.MICROS_PER_SECOND * (sampleRate >= 32000 ? 1152 : 576), sampleRate);\n int entryCount = frame.readUnsignedShort();\n int scale = frame.readUnsignedShort();\n int entrySize = frame.readUnsignedShort();\n frame.skipBytes(2);\n // Skip the frame containing the VBRI header.\n position += mpegAudioHeader.frameSize;\n // Read table of contents entries.\n long[] timesUs = new long[entryCount + 1];\n long[] positions = new long[entryCount + 1];\n timesUs[0] = 0L;\n positions[0] = position;\n for (int index = 1; index < timesUs.length; index++) {\n int segmentSize;\n switch(entrySize) {\n case 1:\n segmentSize = frame.readUnsignedByte();\n break;\n case 2:\n segmentSize = frame.readUnsignedShort();\n break;\n case 3:\n segmentSize = frame.readUnsignedInt24();\n break;\n case 4:\n segmentSize = frame.readUnsignedIntToInt();\n break;\n default:\n return null;\n }\n position += segmentSize * scale;\n timesUs[index] = index * durationUs / entryCount;\n positions[index] = inputLength == C.LENGTH_UNSET ? position : Math.min(inputLength, position);\n }\n return new VbriSeeker(timesUs, positions, durationUs);\n }\n\n private final long[] timesUs;\n\n private final long[] positions;\n\n private final long durationUs;\n\n private VbriSeeker(long[] timesUs, long[] positions, long durationUs) {\n this.timesUs = timesUs;\n this.positions = positions;\n this.durationUs = durationUs;\n }\n\n @Override\n public boolean isSeekable() {\n return true;\n }\n\n @Override\n public long getPosition(long timeUs) {\n return positions[Util.binarySearchFloor(timesUs, timeUs, true, true)];\n }\n\n @Override\n public long getTimeUs(long position) {\n return timesUs[Util.binarySearchFloor(positions, position, true, true)];\n }\n\n @Override\n public long getDurationUs() {\n return durationUs;\n }\n}\n"} {"task_id": "Java_3021", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/webservices12/wsdlImport/http/simple1/TestsImpl.java", "mask_start_position": 399, "mask_end_position": 427, "canonical_solution": "public String invokeTest1() ", "pre_mask_code": "package com.sun.ts.tests.webservices12.wsdlImport.http.simple1;\n\nimport jakarta.jws.WebService;\n\n@WebService(portName = \"TestsPort\", serviceName = \"Simple1HttpSvc\", targetNamespace = \"http://Simple1HttpSvc.org/wsdl\", wsdlLocation = \"WEB-INF/wsdl/Simple1HttpSvc.wsdl\", endpointInterface = \"com.sun.ts.tests.webservices12.wsdlImport.http.simple1.Tests\")\npublic class TestsImpl implements Tests {\n\n ", "post_mask_code": "{\n return \"Hello\";\n }\n}\n"} {"task_id": "Java_3022", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/webservices12/wsdlImport/http/simple1/TestsImpl.java", "mask_start_position": 427, "mask_end_position": 458, "canonical_solution": "{\n return \"Hello\";\n }", "pre_mask_code": "package com.sun.ts.tests.webservices12.wsdlImport.http.simple1;\n\nimport jakarta.jws.WebService;\n\n@WebService(portName = \"TestsPort\", serviceName = \"Simple1HttpSvc\", targetNamespace = \"http://Simple1HttpSvc.org/wsdl\", wsdlLocation = \"WEB-INF/wsdl/Simple1HttpSvc.wsdl\", endpointInterface = \"com.sun.ts.tests.webservices12.wsdlImport.http.simple1.Tests\")\npublic class TestsImpl implements Tests {\n\n public String invokeTest1() ", "post_mask_code": "\n}\n"} {"task_id": "Java_3023", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse-ee4j/jakartaee-tck/src/com/sun/ts/tests/webservices12/wsdlImport/http/simple1/TestsImpl.java", "mask_start_position": 447, "mask_end_position": 452, "canonical_solution": "llo\";", "pre_mask_code": "package com.sun.ts.tests.webservices12.wsdlImport.http.simple1;\n\nimport jakarta.jws.WebService;\n\n@WebService(portName = \"TestsPort\", serviceName = \"Simple1HttpSvc\", targetNamespace = \"http://Simple1HttpSvc.org/wsdl\", wsdlLocation = \"WEB-INF/wsdl/Simple1HttpSvc.wsdl\", endpointInterface = \"com.sun.ts.tests.webservices12.wsdlImport.http.simple1.Tests\")\npublic class TestsImpl implements Tests {\n\n public String invokeTest1() {\n return \"He", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_3024", "language": "Java", "task_type": "method_signature", "source_file": "java/github/HpWens/MeiWidgetView/widget/src/main/java/com/meis/widget/rose/RoseGiftSurfaceView.java", "mask_start_position": 7795, "mask_end_position": 7833, "canonical_solution": "public void setDuration(int duration) ", "pre_mask_code": "package com.meis.widget.rose;\n\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.PixelFormat;\nimport android.graphics.Point;\nimport android.graphics.PorterDuff;\nimport android.support.annotation.DrawableRes;\nimport android.util.AttributeSet;\nimport android.util.DisplayMetrics;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.View;\nimport com.meis.widget.R;\nimport com.meis.widget.utils.PointUtils;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Random;\n\n/**\n * Created by wenshi on 2018/6/26.\n * Description 改变自'那夕阳下的奔跑,是我逝去的青春'\n * 'http://example.com'\n */\npublic class RoseGiftSurfaceView extends SurfaceView implements SurfaceHolder.Callback {\n\n // 不使用时回收c层内存\n private Bitmap bitmap;\n\n // 画布\n private Canvas canvas;\n\n // 画笔\n private Paint paint;\n\n // 随机数\n private Random random;\n\n // 起点集合\n private Point[] startPoint;\n\n // 终点集合\n private Point[] endPoint;\n\n // 动画期间点集合\n private Point[] currentPoint;\n\n // 点集合\n private List points = new ArrayList<>();\n\n // 控件宽度\n private float width;\n\n // 控件高度\n private float height;\n\n private float scale = 1;\n\n /**\n * 偏移(非随机情况下有效)\n */\n private int offsetX;\n\n // y轴偏移量\n private int offsetY;\n\n // 属性动画\n private ValueAnimator animator;\n\n private int duration = 3000;\n\n private static final String ASSET_LOVE = \"assets/json/love.json\";\n\n public RoseGiftSurfaceView(Context context) {\n this(context, null);\n }\n\n public RoseGiftSurfaceView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public RoseGiftSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n initData();\n }\n\n // 初始化数据\n private void initData() {\n paint = new Paint();\n // paint抗锯齿\n paint.setAntiAlias(true);\n random = new Random();\n // 设置透明\n setZOrderOnTop(true);\n getHolder().setFormat(PixelFormat.TRANSLUCENT);\n getHolder().addCallback(this);\n setLayerType(View.LAYER_TYPE_NONE, null);\n // 设置图片\n setImageBitmap(getBitmapByResource(R.drawable.mei_rose), 0.5F);\n // 设置点集合 性能待优化\n try {\n points = PointUtils.getListPointByResourceJson(RoseGiftSurfaceView.this.getContext(), ASSET_LOVE);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * @param resId\n * @return\n */\n private Bitmap getBitmapByResource(@DrawableRes int resId) {\n return BitmapFactory.decodeResource(getResources(), resId);\n }\n\n /**\n * @param resId\n */\n public void setImageResource(@DrawableRes int resId) {\n setImageBitmap(getBitmapByResource(resId));\n }\n\n /**\n * @param resId\n * @param scale 缩放(图片)\n */\n public void setImageResource(@DrawableRes int resId, float scale) {\n setImageBitmap(getBitmapByResource(resId), scale);\n }\n\n /**\n * @param bitmap\n */\n public void setImageBitmap(Bitmap bitmap) {\n this.bitmap = bitmap;\n }\n\n /**\n * @param bitmap\n * @param scale 缩放(图片)\n */\n public void setImageBitmap(Bitmap bitmap, float scale) {\n this.bitmap = scaleBitmap(bitmap, scale);\n }\n\n /**\n * 图片按比例缩放\n *\n * @param bmp\n * @param scale\n * @return\n */\n private Bitmap scaleBitmap(Bitmap bmp, float scale) {\n int width = (int) (bmp.getWidth() * scale);\n int height = (int) (bmp.getHeight() * scale);\n return Bitmap.createScaledBitmap(bmp, width, height, true);\n }\n\n /**\n * 拼图的终点坐标的整体缩放\n *\n * @param scale 点坐标整体缩放\n * 1.0f 表示坐标\n * @param offsetX X 轴偏移量\n * @param offsetY Y 轴偏移量\n */\n public void setPointScale(float scale, int offsetX, int offsetY) {\n this.scale = scale;\n this.offsetX = offsetX;\n this.offsetY = offsetY;\n }\n\n public void setListPoint(List points) {\n this.points = points;\n }\n\n /**\n * 更新点集合\n *\n * @param points\n */\n private void updatePoints(List points) {\n if (verifyListEmpty(points))\n return;\n int number = points.size();\n startPoint = new Point[number];\n endPoint = new Point[number];\n currentPoint = new Point[number];\n for (int i = 0; i < number; i++) {\n endPoint[i] = new Point((int) (points.get(i).x * scale) + offsetX, (int) ((points.get(i).y + offsetY) * scale));\n startPoint[i] = random(endPoint[i].x, endPoint[i].y);\n currentPoint[i] = new Point(0, 0);\n }\n }\n\n private Point random(int endX, int endY) {\n int x = 0;\n int y = 0;\n if (width >= bitmap.getWidth() && height >= bitmap.getWidth()) {\n x = random.nextInt((int) (width - bitmap.getWidth() * 2)) + bitmap.getWidth();\n y = random.nextInt((int) (height - bitmap.getHeight() * 2)) + bitmap.getHeight();\n }\n if (x == endX && y == endY) {\n random(endX, endY);\n }\n return new Point(x, y);\n }\n\n private boolean verifyListEmpty(Collection array) {\n if (array == null || array.isEmpty()) {\n return true;\n }\n return false;\n }\n\n public void updateGiftSurfaceViewParams(int width, int height) {\n this.width = width;\n this.height = height;\n if (width == 0 || height == 0) {\n DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();\n this.width = displayMetrics.widthPixels;\n this.height = displayMetrics.heightPixels;\n }\n setPointScale(1, (int) (this.width / 10), (int) (this.height / 3.8f));\n updatePoints(points);\n }\n\n public void startAnimation() {\n if (animator != null && animator.isRunning()) {\n return;\n }\n animator = ValueAnimator.ofFloat(0, 1).setDuration(duration);\n animator.setRepeatCount(-1);\n animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {\n\n @Override\n public void onAnimationUpdate(ValueAnimator animation) {\n getCurrentPoint((Float) animation.getAnimatedValue());\n drawBitmap();\n }\n });\n animator.start();\n }\n\n public void stopAnimation() {\n if (animator != null && animator.isRunning()) {\n animator.cancel();\n }\n }\n\n private void getCurrentPoint(float valueAnimator) {\n if (startPoint == null || endPoint == null)\n return;\n for (int i = 0; i < startPoint.length; i++) {\n currentPoint[i].x = startPoint[i].x - (int) ((startPoint[i].x - endPoint[i].x) * valueAnimator);\n currentPoint[i].y = startPoint[i].y - (int) ((startPoint[i].y - endPoint[i].y) * valueAnimator);\n }\n }\n\n private void drawBitmap() {\n canvas = getHolder().lockCanvas();\n if (canvas != null) {\n if (currentPoint != null) {\n canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);\n for (int i = 0; i < currentPoint.length; i++) {\n canvas.drawBitmap(bitmap, currentPoint[i].x - bitmap.getWidth() * .5f, currentPoint[i].y - bitmap.getHeight() * .5f, paint);\n }\n }\n getHolder().unlockCanvasAndPost(canvas);\n }\n }\n\n public int getDuration() {\n return duration;\n }\n\n ", "post_mask_code": "{\n this.duration = duration;\n }\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n updateGiftSurfaceViewParams(width, height);\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n stopAnimation();\n }\n}\n"} {"task_id": "Java_3025", "language": "Java", "task_type": "method_body", "source_file": "java/github/HpWens/MeiWidgetView/widget/src/main/java/com/meis/widget/rose/RoseGiftSurfaceView.java", "mask_start_position": 2838, "mask_end_position": 2913, "canonical_solution": "{\n return BitmapFactory.decodeResource(getResources(), resId);\n }", "pre_mask_code": "package com.meis.widget.rose;\n\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.PixelFormat;\nimport android.graphics.Point;\nimport android.graphics.PorterDuff;\nimport android.support.annotation.DrawableRes;\nimport android.util.AttributeSet;\nimport android.util.DisplayMetrics;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.View;\nimport com.meis.widget.R;\nimport com.meis.widget.utils.PointUtils;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Random;\n\n/**\n * Created by wenshi on 2018/6/26.\n * Description 改变自'那夕阳下的奔跑,是我逝去的青春'\n * 'http://example.com'\n */\npublic class RoseGiftSurfaceView extends SurfaceView implements SurfaceHolder.Callback {\n\n // 不使用时回收c层内存\n private Bitmap bitmap;\n\n // 画布\n private Canvas canvas;\n\n // 画笔\n private Paint paint;\n\n // 随机数\n private Random random;\n\n // 起点集合\n private Point[] startPoint;\n\n // 终点集合\n private Point[] endPoint;\n\n // 动画期间点集合\n private Point[] currentPoint;\n\n // 点集合\n private List points = new ArrayList<>();\n\n // 控件宽度\n private float width;\n\n // 控件高度\n private float height;\n\n private float scale = 1;\n\n /**\n * 偏移(非随机情况下有效)\n */\n private int offsetX;\n\n // y轴偏移量\n private int offsetY;\n\n // 属性动画\n private ValueAnimator animator;\n\n private int duration = 3000;\n\n private static final String ASSET_LOVE = \"assets/json/love.json\";\n\n public RoseGiftSurfaceView(Context context) {\n this(context, null);\n }\n\n public RoseGiftSurfaceView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public RoseGiftSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n initData();\n }\n\n // 初始化数据\n private void initData() {\n paint = new Paint();\n // paint抗锯齿\n paint.setAntiAlias(true);\n random = new Random();\n // 设置透明\n setZOrderOnTop(true);\n getHolder().setFormat(PixelFormat.TRANSLUCENT);\n getHolder().addCallback(this);\n setLayerType(View.LAYER_TYPE_NONE, null);\n // 设置图片\n setImageBitmap(getBitmapByResource(R.drawable.mei_rose), 0.5F);\n // 设置点集合 性能待优化\n try {\n points = PointUtils.getListPointByResourceJson(RoseGiftSurfaceView.this.getContext(), ASSET_LOVE);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * @param resId\n * @return\n */\n private Bitmap getBitmapByResource(@DrawableRes int resId) ", "post_mask_code": "\n\n /**\n * @param resId\n */\n public void setImageResource(@DrawableRes int resId) {\n setImageBitmap(getBitmapByResource(resId));\n }\n\n /**\n * @param resId\n * @param scale 缩放(图片)\n */\n public void setImageResource(@DrawableRes int resId, float scale) {\n setImageBitmap(getBitmapByResource(resId), scale);\n }\n\n /**\n * @param bitmap\n */\n public void setImageBitmap(Bitmap bitmap) {\n this.bitmap = bitmap;\n }\n\n /**\n * @param bitmap\n * @param scale 缩放(图片)\n */\n public void setImageBitmap(Bitmap bitmap, float scale) {\n this.bitmap = scaleBitmap(bitmap, scale);\n }\n\n /**\n * 图片按比例缩放\n *\n * @param bmp\n * @param scale\n * @return\n */\n private Bitmap scaleBitmap(Bitmap bmp, float scale) {\n int width = (int) (bmp.getWidth() * scale);\n int height = (int) (bmp.getHeight() * scale);\n return Bitmap.createScaledBitmap(bmp, width, height, true);\n }\n\n /**\n * 拼图的终点坐标的整体缩放\n *\n * @param scale 点坐标整体缩放\n * 1.0f 表示坐标\n * @param offsetX X 轴偏移量\n * @param offsetY Y 轴偏移量\n */\n public void setPointScale(float scale, int offsetX, int offsetY) {\n this.scale = scale;\n this.offsetX = offsetX;\n this.offsetY = offsetY;\n }\n\n public void setListPoint(List points) {\n this.points = points;\n }\n\n /**\n * 更新点集合\n *\n * @param points\n */\n private void updatePoints(List points) {\n if (verifyListEmpty(points))\n return;\n int number = points.size();\n startPoint = new Point[number];\n endPoint = new Point[number];\n currentPoint = new Point[number];\n for (int i = 0; i < number; i++) {\n endPoint[i] = new Point((int) (points.get(i).x * scale) + offsetX, (int) ((points.get(i).y + offsetY) * scale));\n startPoint[i] = random(endPoint[i].x, endPoint[i].y);\n currentPoint[i] = new Point(0, 0);\n }\n }\n\n private Point random(int endX, int endY) {\n int x = 0;\n int y = 0;\n if (width >= bitmap.getWidth() && height >= bitmap.getWidth()) {\n x = random.nextInt((int) (width - bitmap.getWidth() * 2)) + bitmap.getWidth();\n y = random.nextInt((int) (height - bitmap.getHeight() * 2)) + bitmap.getHeight();\n }\n if (x == endX && y == endY) {\n random(endX, endY);\n }\n return new Point(x, y);\n }\n\n private boolean verifyListEmpty(Collection array) {\n if (array == null || array.isEmpty()) {\n return true;\n }\n return false;\n }\n\n public void updateGiftSurfaceViewParams(int width, int height) {\n this.width = width;\n this.height = height;\n if (width == 0 || height == 0) {\n DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();\n this.width = displayMetrics.widthPixels;\n this.height = displayMetrics.heightPixels;\n }\n setPointScale(1, (int) (this.width / 10), (int) (this.height / 3.8f));\n updatePoints(points);\n }\n\n public void startAnimation() {\n if (animator != null && animator.isRunning()) {\n return;\n }\n animator = ValueAnimator.ofFloat(0, 1).setDuration(duration);\n animator.setRepeatCount(-1);\n animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {\n\n @Override\n public void onAnimationUpdate(ValueAnimator animation) {\n getCurrentPoint((Float) animation.getAnimatedValue());\n drawBitmap();\n }\n });\n animator.start();\n }\n\n public void stopAnimation() {\n if (animator != null && animator.isRunning()) {\n animator.cancel();\n }\n }\n\n private void getCurrentPoint(float valueAnimator) {\n if (startPoint == null || endPoint == null)\n return;\n for (int i = 0; i < startPoint.length; i++) {\n currentPoint[i].x = startPoint[i].x - (int) ((startPoint[i].x - endPoint[i].x) * valueAnimator);\n currentPoint[i].y = startPoint[i].y - (int) ((startPoint[i].y - endPoint[i].y) * valueAnimator);\n }\n }\n\n private void drawBitmap() {\n canvas = getHolder().lockCanvas();\n if (canvas != null) {\n if (currentPoint != null) {\n canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);\n for (int i = 0; i < currentPoint.length; i++) {\n canvas.drawBitmap(bitmap, currentPoint[i].x - bitmap.getWidth() * .5f, currentPoint[i].y - bitmap.getHeight() * .5f, paint);\n }\n }\n getHolder().unlockCanvasAndPost(canvas);\n }\n }\n\n public int getDuration() {\n return duration;\n }\n\n public void setDuration(int duration) {\n this.duration = duration;\n }\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n updateGiftSurfaceViewParams(width, height);\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n stopAnimation();\n }\n}\n"} {"task_id": "Java_3026", "language": "Java", "task_type": "single_line", "source_file": "java/github/HpWens/MeiWidgetView/widget/src/main/java/com/meis/widget/rose/RoseGiftSurfaceView.java", "mask_start_position": 3370, "mask_end_position": 3384, "canonical_solution": "tmap = bitmap;", "pre_mask_code": "package com.meis.widget.rose;\n\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.PixelFormat;\nimport android.graphics.Point;\nimport android.graphics.PorterDuff;\nimport android.support.annotation.DrawableRes;\nimport android.util.AttributeSet;\nimport android.util.DisplayMetrics;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.View;\nimport com.meis.widget.R;\nimport com.meis.widget.utils.PointUtils;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Random;\n\n/**\n * Created by wenshi on 2018/6/26.\n * Description 改变自'那夕阳下的奔跑,是我逝去的青春'\n * 'http://example.com'\n */\npublic class RoseGiftSurfaceView extends SurfaceView implements SurfaceHolder.Callback {\n\n // 不使用时回收c层内存\n private Bitmap bitmap;\n\n // 画布\n private Canvas canvas;\n\n // 画笔\n private Paint paint;\n\n // 随机数\n private Random random;\n\n // 起点集合\n private Point[] startPoint;\n\n // 终点集合\n private Point[] endPoint;\n\n // 动画期间点集合\n private Point[] currentPoint;\n\n // 点集合\n private List points = new ArrayList<>();\n\n // 控件宽度\n private float width;\n\n // 控件高度\n private float height;\n\n private float scale = 1;\n\n /**\n * 偏移(非随机情况下有效)\n */\n private int offsetX;\n\n // y轴偏移量\n private int offsetY;\n\n // 属性动画\n private ValueAnimator animator;\n\n private int duration = 3000;\n\n private static final String ASSET_LOVE = \"assets/json/love.json\";\n\n public RoseGiftSurfaceView(Context context) {\n this(context, null);\n }\n\n public RoseGiftSurfaceView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public RoseGiftSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n initData();\n }\n\n // 初始化数据\n private void initData() {\n paint = new Paint();\n // paint抗锯齿\n paint.setAntiAlias(true);\n random = new Random();\n // 设置透明\n setZOrderOnTop(true);\n getHolder().setFormat(PixelFormat.TRANSLUCENT);\n getHolder().addCallback(this);\n setLayerType(View.LAYER_TYPE_NONE, null);\n // 设置图片\n setImageBitmap(getBitmapByResource(R.drawable.mei_rose), 0.5F);\n // 设置点集合 性能待优化\n try {\n points = PointUtils.getListPointByResourceJson(RoseGiftSurfaceView.this.getContext(), ASSET_LOVE);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * @param resId\n * @return\n */\n private Bitmap getBitmapByResource(@DrawableRes int resId) {\n return BitmapFactory.decodeResource(getResources(), resId);\n }\n\n /**\n * @param resId\n */\n public void setImageResource(@DrawableRes int resId) {\n setImageBitmap(getBitmapByResource(resId));\n }\n\n /**\n * @param resId\n * @param scale 缩放(图片)\n */\n public void setImageResource(@DrawableRes int resId, float scale) {\n setImageBitmap(getBitmapByResource(resId), scale);\n }\n\n /**\n * @param bitmap\n */\n public void setImageBitmap(Bitmap bitmap) {\n this.bi", "post_mask_code": "\n }\n\n /**\n * @param bitmap\n * @param scale 缩放(图片)\n */\n public void setImageBitmap(Bitmap bitmap, float scale) {\n this.bitmap = scaleBitmap(bitmap, scale);\n }\n\n /**\n * 图片按比例缩放\n *\n * @param bmp\n * @param scale\n * @return\n */\n private Bitmap scaleBitmap(Bitmap bmp, float scale) {\n int width = (int) (bmp.getWidth() * scale);\n int height = (int) (bmp.getHeight() * scale);\n return Bitmap.createScaledBitmap(bmp, width, height, true);\n }\n\n /**\n * 拼图的终点坐标的整体缩放\n *\n * @param scale 点坐标整体缩放\n * 1.0f 表示坐标\n * @param offsetX X 轴偏移量\n * @param offsetY Y 轴偏移量\n */\n public void setPointScale(float scale, int offsetX, int offsetY) {\n this.scale = scale;\n this.offsetX = offsetX;\n this.offsetY = offsetY;\n }\n\n public void setListPoint(List points) {\n this.points = points;\n }\n\n /**\n * 更新点集合\n *\n * @param points\n */\n private void updatePoints(List points) {\n if (verifyListEmpty(points))\n return;\n int number = points.size();\n startPoint = new Point[number];\n endPoint = new Point[number];\n currentPoint = new Point[number];\n for (int i = 0; i < number; i++) {\n endPoint[i] = new Point((int) (points.get(i).x * scale) + offsetX, (int) ((points.get(i).y + offsetY) * scale));\n startPoint[i] = random(endPoint[i].x, endPoint[i].y);\n currentPoint[i] = new Point(0, 0);\n }\n }\n\n private Point random(int endX, int endY) {\n int x = 0;\n int y = 0;\n if (width >= bitmap.getWidth() && height >= bitmap.getWidth()) {\n x = random.nextInt((int) (width - bitmap.getWidth() * 2)) + bitmap.getWidth();\n y = random.nextInt((int) (height - bitmap.getHeight() * 2)) + bitmap.getHeight();\n }\n if (x == endX && y == endY) {\n random(endX, endY);\n }\n return new Point(x, y);\n }\n\n private boolean verifyListEmpty(Collection array) {\n if (array == null || array.isEmpty()) {\n return true;\n }\n return false;\n }\n\n public void updateGiftSurfaceViewParams(int width, int height) {\n this.width = width;\n this.height = height;\n if (width == 0 || height == 0) {\n DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();\n this.width = displayMetrics.widthPixels;\n this.height = displayMetrics.heightPixels;\n }\n setPointScale(1, (int) (this.width / 10), (int) (this.height / 3.8f));\n updatePoints(points);\n }\n\n public void startAnimation() {\n if (animator != null && animator.isRunning()) {\n return;\n }\n animator = ValueAnimator.ofFloat(0, 1).setDuration(duration);\n animator.setRepeatCount(-1);\n animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {\n\n @Override\n public void onAnimationUpdate(ValueAnimator animation) {\n getCurrentPoint((Float) animation.getAnimatedValue());\n drawBitmap();\n }\n });\n animator.start();\n }\n\n public void stopAnimation() {\n if (animator != null && animator.isRunning()) {\n animator.cancel();\n }\n }\n\n private void getCurrentPoint(float valueAnimator) {\n if (startPoint == null || endPoint == null)\n return;\n for (int i = 0; i < startPoint.length; i++) {\n currentPoint[i].x = startPoint[i].x - (int) ((startPoint[i].x - endPoint[i].x) * valueAnimator);\n currentPoint[i].y = startPoint[i].y - (int) ((startPoint[i].y - endPoint[i].y) * valueAnimator);\n }\n }\n\n private void drawBitmap() {\n canvas = getHolder().lockCanvas();\n if (canvas != null) {\n if (currentPoint != null) {\n canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);\n for (int i = 0; i < currentPoint.length; i++) {\n canvas.drawBitmap(bitmap, currentPoint[i].x - bitmap.getWidth() * .5f, currentPoint[i].y - bitmap.getHeight() * .5f, paint);\n }\n }\n getHolder().unlockCanvasAndPost(canvas);\n }\n }\n\n public int getDuration() {\n return duration;\n }\n\n public void setDuration(int duration) {\n this.duration = duration;\n }\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n updateGiftSurfaceViewParams(width, height);\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n stopAnimation();\n }\n}\n"} {"task_id": "Java_3027", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/HpWens/MeiWidgetView/widget/src/main/java/com/meis/widget/rose/RoseGiftSurfaceView.java", "mask_start_position": 4072, "mask_end_position": 4236, "canonical_solution": "public void setPointScale(float scale, int offsetX, int offsetY) {\n this.scale = scale;\n this.offsetX = offsetX;\n this.offsetY = offsetY;\n }", "pre_mask_code": "package com.meis.widget.rose;\n\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.PixelFormat;\nimport android.graphics.Point;\nimport android.graphics.PorterDuff;\nimport android.support.annotation.DrawableRes;\nimport android.util.AttributeSet;\nimport android.util.DisplayMetrics;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.View;\nimport com.meis.widget.R;\nimport com.meis.widget.utils.PointUtils;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Random;\n\n/**\n * Created by wenshi on 2018/6/26.\n * Description 改变自'那夕阳下的奔跑,是我逝去的青春'\n * 'http://example.com'\n */\npublic class RoseGiftSurfaceView extends SurfaceView implements SurfaceHolder.Callback {\n\n // 不使用时回收c层内存\n private Bitmap bitmap;\n\n // 画布\n private Canvas canvas;\n\n // 画笔\n private Paint paint;\n\n // 随机数\n private Random random;\n\n // 起点集合\n private Point[] startPoint;\n\n // 终点集合\n private Point[] endPoint;\n\n // 动画期间点集合\n private Point[] currentPoint;\n\n // 点集合\n private List points = new ArrayList<>();\n\n // 控件宽度\n private float width;\n\n // 控件高度\n private float height;\n\n private float scale = 1;\n\n /**\n * 偏移(非随机情况下有效)\n */\n private int offsetX;\n\n // y轴偏移量\n private int offsetY;\n\n // 属性动画\n private ValueAnimator animator;\n\n private int duration = 3000;\n\n private static final String ASSET_LOVE = \"assets/json/love.json\";\n\n public RoseGiftSurfaceView(Context context) {\n this(context, null);\n }\n\n public RoseGiftSurfaceView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public RoseGiftSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n initData();\n }\n\n // 初始化数据\n private void initData() {\n paint = new Paint();\n // paint抗锯齿\n paint.setAntiAlias(true);\n random = new Random();\n // 设置透明\n setZOrderOnTop(true);\n getHolder().setFormat(PixelFormat.TRANSLUCENT);\n getHolder().addCallback(this);\n setLayerType(View.LAYER_TYPE_NONE, null);\n // 设置图片\n setImageBitmap(getBitmapByResource(R.drawable.mei_rose), 0.5F);\n // 设置点集合 性能待优化\n try {\n points = PointUtils.getListPointByResourceJson(RoseGiftSurfaceView.this.getContext(), ASSET_LOVE);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * @param resId\n * @return\n */\n private Bitmap getBitmapByResource(@DrawableRes int resId) {\n return BitmapFactory.decodeResource(getResources(), resId);\n }\n\n /**\n * @param resId\n */\n public void setImageResource(@DrawableRes int resId) {\n setImageBitmap(getBitmapByResource(resId));\n }\n\n /**\n * @param resId\n * @param scale 缩放(图片)\n */\n public void setImageResource(@DrawableRes int resId, float scale) {\n setImageBitmap(getBitmapByResource(resId), scale);\n }\n\n /**\n * @param bitmap\n */\n public void setImageBitmap(Bitmap bitmap) {\n this.bitmap = bitmap;\n }\n\n /**\n * @param bitmap\n * @param scale 缩放(图片)\n */\n public void setImageBitmap(Bitmap bitmap, float scale) {\n this.bitmap = scaleBitmap(bitmap, scale);\n }\n\n /**\n * 图片按比例缩放\n *\n * @param bmp\n * @param scale\n * @return\n */\n private Bitmap scaleBitmap(Bitmap bmp, float scale) {\n int width = (int) (bmp.getWidth() * scale);\n int height = (int) (bmp.getHeight() * scale);\n return Bitmap.createScaledBitmap(bmp, width, height, true);\n }\n\n /**\n * 拼图的终点坐标的整体缩放\n *\n * @param scale 点坐标整体缩放\n * 1.0f 表示坐标\n * @param offsetX X 轴偏移量\n * @param offsetY Y 轴偏移量\n */\n ", "post_mask_code": "\n\n public void setListPoint(List points) {\n this.points = points;\n }\n\n /**\n * 更新点集合\n *\n * @param points\n */\n private void updatePoints(List points) {\n if (verifyListEmpty(points))\n return;\n int number = points.size();\n startPoint = new Point[number];\n endPoint = new Point[number];\n currentPoint = new Point[number];\n for (int i = 0; i < number; i++) {\n endPoint[i] = new Point((int) (points.get(i).x * scale) + offsetX, (int) ((points.get(i).y + offsetY) * scale));\n startPoint[i] = random(endPoint[i].x, endPoint[i].y);\n currentPoint[i] = new Point(0, 0);\n }\n }\n\n private Point random(int endX, int endY) {\n int x = 0;\n int y = 0;\n if (width >= bitmap.getWidth() && height >= bitmap.getWidth()) {\n x = random.nextInt((int) (width - bitmap.getWidth() * 2)) + bitmap.getWidth();\n y = random.nextInt((int) (height - bitmap.getHeight() * 2)) + bitmap.getHeight();\n }\n if (x == endX && y == endY) {\n random(endX, endY);\n }\n return new Point(x, y);\n }\n\n private boolean verifyListEmpty(Collection array) {\n if (array == null || array.isEmpty()) {\n return true;\n }\n return false;\n }\n\n public void updateGiftSurfaceViewParams(int width, int height) {\n this.width = width;\n this.height = height;\n if (width == 0 || height == 0) {\n DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();\n this.width = displayMetrics.widthPixels;\n this.height = displayMetrics.heightPixels;\n }\n setPointScale(1, (int) (this.width / 10), (int) (this.height / 3.8f));\n updatePoints(points);\n }\n\n public void startAnimation() {\n if (animator != null && animator.isRunning()) {\n return;\n }\n animator = ValueAnimator.ofFloat(0, 1).setDuration(duration);\n animator.setRepeatCount(-1);\n animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {\n\n @Override\n public void onAnimationUpdate(ValueAnimator animation) {\n getCurrentPoint((Float) animation.getAnimatedValue());\n drawBitmap();\n }\n });\n animator.start();\n }\n\n public void stopAnimation() {\n if (animator != null && animator.isRunning()) {\n animator.cancel();\n }\n }\n\n private void getCurrentPoint(float valueAnimator) {\n if (startPoint == null || endPoint == null)\n return;\n for (int i = 0; i < startPoint.length; i++) {\n currentPoint[i].x = startPoint[i].x - (int) ((startPoint[i].x - endPoint[i].x) * valueAnimator);\n currentPoint[i].y = startPoint[i].y - (int) ((startPoint[i].y - endPoint[i].y) * valueAnimator);\n }\n }\n\n private void drawBitmap() {\n canvas = getHolder().lockCanvas();\n if (canvas != null) {\n if (currentPoint != null) {\n canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);\n for (int i = 0; i < currentPoint.length; i++) {\n canvas.drawBitmap(bitmap, currentPoint[i].x - bitmap.getWidth() * .5f, currentPoint[i].y - bitmap.getHeight() * .5f, paint);\n }\n }\n getHolder().unlockCanvasAndPost(canvas);\n }\n }\n\n public int getDuration() {\n return duration;\n }\n\n public void setDuration(int duration) {\n this.duration = duration;\n }\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n updateGiftSurfaceViewParams(width, height);\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n stopAnimation();\n }\n}\n"} {"task_id": "Java_3028", "language": "Java", "task_type": "for_statement", "source_file": "java/github/HpWens/MeiWidgetView/widget/src/main/java/com/meis/widget/rose/RoseGiftSurfaceView.java", "mask_start_position": 6915, "mask_end_position": 7188, "canonical_solution": "for (int i = 0; i < startPoint.length; i++) {\n currentPoint[i].x = startPoint[i].x - (int) ((startPoint[i].x - endPoint[i].x) * valueAnimator);\n currentPoint[i].y = startPoint[i].y - (int) ((startPoint[i].y - endPoint[i].y) * valueAnimator);\n }", "pre_mask_code": "package com.meis.widget.rose;\n\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.PixelFormat;\nimport android.graphics.Point;\nimport android.graphics.PorterDuff;\nimport android.support.annotation.DrawableRes;\nimport android.util.AttributeSet;\nimport android.util.DisplayMetrics;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.View;\nimport com.meis.widget.R;\nimport com.meis.widget.utils.PointUtils;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Random;\n\n/**\n * Created by wenshi on 2018/6/26.\n * Description 改变自'那夕阳下的奔跑,是我逝去的青春'\n * 'http://example.com'\n */\npublic class RoseGiftSurfaceView extends SurfaceView implements SurfaceHolder.Callback {\n\n // 不使用时回收c层内存\n private Bitmap bitmap;\n\n // 画布\n private Canvas canvas;\n\n // 画笔\n private Paint paint;\n\n // 随机数\n private Random random;\n\n // 起点集合\n private Point[] startPoint;\n\n // 终点集合\n private Point[] endPoint;\n\n // 动画期间点集合\n private Point[] currentPoint;\n\n // 点集合\n private List points = new ArrayList<>();\n\n // 控件宽度\n private float width;\n\n // 控件高度\n private float height;\n\n private float scale = 1;\n\n /**\n * 偏移(非随机情况下有效)\n */\n private int offsetX;\n\n // y轴偏移量\n private int offsetY;\n\n // 属性动画\n private ValueAnimator animator;\n\n private int duration = 3000;\n\n private static final String ASSET_LOVE = \"assets/json/love.json\";\n\n public RoseGiftSurfaceView(Context context) {\n this(context, null);\n }\n\n public RoseGiftSurfaceView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public RoseGiftSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n initData();\n }\n\n // 初始化数据\n private void initData() {\n paint = new Paint();\n // paint抗锯齿\n paint.setAntiAlias(true);\n random = new Random();\n // 设置透明\n setZOrderOnTop(true);\n getHolder().setFormat(PixelFormat.TRANSLUCENT);\n getHolder().addCallback(this);\n setLayerType(View.LAYER_TYPE_NONE, null);\n // 设置图片\n setImageBitmap(getBitmapByResource(R.drawable.mei_rose), 0.5F);\n // 设置点集合 性能待优化\n try {\n points = PointUtils.getListPointByResourceJson(RoseGiftSurfaceView.this.getContext(), ASSET_LOVE);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * @param resId\n * @return\n */\n private Bitmap getBitmapByResource(@DrawableRes int resId) {\n return BitmapFactory.decodeResource(getResources(), resId);\n }\n\n /**\n * @param resId\n */\n public void setImageResource(@DrawableRes int resId) {\n setImageBitmap(getBitmapByResource(resId));\n }\n\n /**\n * @param resId\n * @param scale 缩放(图片)\n */\n public void setImageResource(@DrawableRes int resId, float scale) {\n setImageBitmap(getBitmapByResource(resId), scale);\n }\n\n /**\n * @param bitmap\n */\n public void setImageBitmap(Bitmap bitmap) {\n this.bitmap = bitmap;\n }\n\n /**\n * @param bitmap\n * @param scale 缩放(图片)\n */\n public void setImageBitmap(Bitmap bitmap, float scale) {\n this.bitmap = scaleBitmap(bitmap, scale);\n }\n\n /**\n * 图片按比例缩放\n *\n * @param bmp\n * @param scale\n * @return\n */\n private Bitmap scaleBitmap(Bitmap bmp, float scale) {\n int width = (int) (bmp.getWidth() * scale);\n int height = (int) (bmp.getHeight() * scale);\n return Bitmap.createScaledBitmap(bmp, width, height, true);\n }\n\n /**\n * 拼图的终点坐标的整体缩放\n *\n * @param scale 点坐标整体缩放\n * 1.0f 表示坐标\n * @param offsetX X 轴偏移量\n * @param offsetY Y 轴偏移量\n */\n public void setPointScale(float scale, int offsetX, int offsetY) {\n this.scale = scale;\n this.offsetX = offsetX;\n this.offsetY = offsetY;\n }\n\n public void setListPoint(List points) {\n this.points = points;\n }\n\n /**\n * 更新点集合\n *\n * @param points\n */\n private void updatePoints(List points) {\n if (verifyListEmpty(points))\n return;\n int number = points.size();\n startPoint = new Point[number];\n endPoint = new Point[number];\n currentPoint = new Point[number];\n for (int i = 0; i < number; i++) {\n endPoint[i] = new Point((int) (points.get(i).x * scale) + offsetX, (int) ((points.get(i).y + offsetY) * scale));\n startPoint[i] = random(endPoint[i].x, endPoint[i].y);\n currentPoint[i] = new Point(0, 0);\n }\n }\n\n private Point random(int endX, int endY) {\n int x = 0;\n int y = 0;\n if (width >= bitmap.getWidth() && height >= bitmap.getWidth()) {\n x = random.nextInt((int) (width - bitmap.getWidth() * 2)) + bitmap.getWidth();\n y = random.nextInt((int) (height - bitmap.getHeight() * 2)) + bitmap.getHeight();\n }\n if (x == endX && y == endY) {\n random(endX, endY);\n }\n return new Point(x, y);\n }\n\n private boolean verifyListEmpty(Collection array) {\n if (array == null || array.isEmpty()) {\n return true;\n }\n return false;\n }\n\n public void updateGiftSurfaceViewParams(int width, int height) {\n this.width = width;\n this.height = height;\n if (width == 0 || height == 0) {\n DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();\n this.width = displayMetrics.widthPixels;\n this.height = displayMetrics.heightPixels;\n }\n setPointScale(1, (int) (this.width / 10), (int) (this.height / 3.8f));\n updatePoints(points);\n }\n\n public void startAnimation() {\n if (animator != null && animator.isRunning()) {\n return;\n }\n animator = ValueAnimator.ofFloat(0, 1).setDuration(duration);\n animator.setRepeatCount(-1);\n animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {\n\n @Override\n public void onAnimationUpdate(ValueAnimator animation) {\n getCurrentPoint((Float) animation.getAnimatedValue());\n drawBitmap();\n }\n });\n animator.start();\n }\n\n public void stopAnimation() {\n if (animator != null && animator.isRunning()) {\n animator.cancel();\n }\n }\n\n private void getCurrentPoint(float valueAnimator) {\n if (startPoint == null || endPoint == null)\n return;\n ", "post_mask_code": "\n }\n\n private void drawBitmap() {\n canvas = getHolder().lockCanvas();\n if (canvas != null) {\n if (currentPoint != null) {\n canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);\n for (int i = 0; i < currentPoint.length; i++) {\n canvas.drawBitmap(bitmap, currentPoint[i].x - bitmap.getWidth() * .5f, currentPoint[i].y - bitmap.getHeight() * .5f, paint);\n }\n }\n getHolder().unlockCanvasAndPost(canvas);\n }\n }\n\n public int getDuration() {\n return duration;\n }\n\n public void setDuration(int duration) {\n this.duration = duration;\n }\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n updateGiftSurfaceViewParams(width, height);\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n stopAnimation();\n }\n}\n"} {"task_id": "Java_3029", "language": "Java", "task_type": "try_statement", "source_file": "java/github/HpWens/MeiWidgetView/widget/src/main/java/com/meis/widget/rose/RoseGiftSurfaceView.java", "mask_start_position": 2523, "mask_end_position": 2716, "canonical_solution": "try {\n points = PointUtils.getListPointByResourceJson(RoseGiftSurfaceView.this.getContext(), ASSET_LOVE);\n } catch (IOException e) {\n e.printStackTrace();\n }", "pre_mask_code": "package com.meis.widget.rose;\n\nimport android.animation.ValueAnimator;\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.PixelFormat;\nimport android.graphics.Point;\nimport android.graphics.PorterDuff;\nimport android.support.annotation.DrawableRes;\nimport android.util.AttributeSet;\nimport android.util.DisplayMetrics;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\nimport android.view.View;\nimport com.meis.widget.R;\nimport com.meis.widget.utils.PointUtils;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Random;\n\n/**\n * Created by wenshi on 2018/6/26.\n * Description 改变自'那夕阳下的奔跑,是我逝去的青春'\n * 'http://example.com'\n */\npublic class RoseGiftSurfaceView extends SurfaceView implements SurfaceHolder.Callback {\n\n // 不使用时回收c层内存\n private Bitmap bitmap;\n\n // 画布\n private Canvas canvas;\n\n // 画笔\n private Paint paint;\n\n // 随机数\n private Random random;\n\n // 起点集合\n private Point[] startPoint;\n\n // 终点集合\n private Point[] endPoint;\n\n // 动画期间点集合\n private Point[] currentPoint;\n\n // 点集合\n private List points = new ArrayList<>();\n\n // 控件宽度\n private float width;\n\n // 控件高度\n private float height;\n\n private float scale = 1;\n\n /**\n * 偏移(非随机情况下有效)\n */\n private int offsetX;\n\n // y轴偏移量\n private int offsetY;\n\n // 属性动画\n private ValueAnimator animator;\n\n private int duration = 3000;\n\n private static final String ASSET_LOVE = \"assets/json/love.json\";\n\n public RoseGiftSurfaceView(Context context) {\n this(context, null);\n }\n\n public RoseGiftSurfaceView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public RoseGiftSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n initData();\n }\n\n // 初始化数据\n private void initData() {\n paint = new Paint();\n // paint抗锯齿\n paint.setAntiAlias(true);\n random = new Random();\n // 设置透明\n setZOrderOnTop(true);\n getHolder().setFormat(PixelFormat.TRANSLUCENT);\n getHolder().addCallback(this);\n setLayerType(View.LAYER_TYPE_NONE, null);\n // 设置图片\n setImageBitmap(getBitmapByResource(R.drawable.mei_rose), 0.5F);\n // 设置点集合 性能待优化\n ", "post_mask_code": "\n }\n\n /**\n * @param resId\n * @return\n */\n private Bitmap getBitmapByResource(@DrawableRes int resId) {\n return BitmapFactory.decodeResource(getResources(), resId);\n }\n\n /**\n * @param resId\n */\n public void setImageResource(@DrawableRes int resId) {\n setImageBitmap(getBitmapByResource(resId));\n }\n\n /**\n * @param resId\n * @param scale 缩放(图片)\n */\n public void setImageResource(@DrawableRes int resId, float scale) {\n setImageBitmap(getBitmapByResource(resId), scale);\n }\n\n /**\n * @param bitmap\n */\n public void setImageBitmap(Bitmap bitmap) {\n this.bitmap = bitmap;\n }\n\n /**\n * @param bitmap\n * @param scale 缩放(图片)\n */\n public void setImageBitmap(Bitmap bitmap, float scale) {\n this.bitmap = scaleBitmap(bitmap, scale);\n }\n\n /**\n * 图片按比例缩放\n *\n * @param bmp\n * @param scale\n * @return\n */\n private Bitmap scaleBitmap(Bitmap bmp, float scale) {\n int width = (int) (bmp.getWidth() * scale);\n int height = (int) (bmp.getHeight() * scale);\n return Bitmap.createScaledBitmap(bmp, width, height, true);\n }\n\n /**\n * 拼图的终点坐标的整体缩放\n *\n * @param scale 点坐标整体缩放\n * 1.0f 表示坐标\n * @param offsetX X 轴偏移量\n * @param offsetY Y 轴偏移量\n */\n public void setPointScale(float scale, int offsetX, int offsetY) {\n this.scale = scale;\n this.offsetX = offsetX;\n this.offsetY = offsetY;\n }\n\n public void setListPoint(List points) {\n this.points = points;\n }\n\n /**\n * 更新点集合\n *\n * @param points\n */\n private void updatePoints(List points) {\n if (verifyListEmpty(points))\n return;\n int number = points.size();\n startPoint = new Point[number];\n endPoint = new Point[number];\n currentPoint = new Point[number];\n for (int i = 0; i < number; i++) {\n endPoint[i] = new Point((int) (points.get(i).x * scale) + offsetX, (int) ((points.get(i).y + offsetY) * scale));\n startPoint[i] = random(endPoint[i].x, endPoint[i].y);\n currentPoint[i] = new Point(0, 0);\n }\n }\n\n private Point random(int endX, int endY) {\n int x = 0;\n int y = 0;\n if (width >= bitmap.getWidth() && height >= bitmap.getWidth()) {\n x = random.nextInt((int) (width - bitmap.getWidth() * 2)) + bitmap.getWidth();\n y = random.nextInt((int) (height - bitmap.getHeight() * 2)) + bitmap.getHeight();\n }\n if (x == endX && y == endY) {\n random(endX, endY);\n }\n return new Point(x, y);\n }\n\n private boolean verifyListEmpty(Collection array) {\n if (array == null || array.isEmpty()) {\n return true;\n }\n return false;\n }\n\n public void updateGiftSurfaceViewParams(int width, int height) {\n this.width = width;\n this.height = height;\n if (width == 0 || height == 0) {\n DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();\n this.width = displayMetrics.widthPixels;\n this.height = displayMetrics.heightPixels;\n }\n setPointScale(1, (int) (this.width / 10), (int) (this.height / 3.8f));\n updatePoints(points);\n }\n\n public void startAnimation() {\n if (animator != null && animator.isRunning()) {\n return;\n }\n animator = ValueAnimator.ofFloat(0, 1).setDuration(duration);\n animator.setRepeatCount(-1);\n animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {\n\n @Override\n public void onAnimationUpdate(ValueAnimator animation) {\n getCurrentPoint((Float) animation.getAnimatedValue());\n drawBitmap();\n }\n });\n animator.start();\n }\n\n public void stopAnimation() {\n if (animator != null && animator.isRunning()) {\n animator.cancel();\n }\n }\n\n private void getCurrentPoint(float valueAnimator) {\n if (startPoint == null || endPoint == null)\n return;\n for (int i = 0; i < startPoint.length; i++) {\n currentPoint[i].x = startPoint[i].x - (int) ((startPoint[i].x - endPoint[i].x) * valueAnimator);\n currentPoint[i].y = startPoint[i].y - (int) ((startPoint[i].y - endPoint[i].y) * valueAnimator);\n }\n }\n\n private void drawBitmap() {\n canvas = getHolder().lockCanvas();\n if (canvas != null) {\n if (currentPoint != null) {\n canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);\n for (int i = 0; i < currentPoint.length; i++) {\n canvas.drawBitmap(bitmap, currentPoint[i].x - bitmap.getWidth() * .5f, currentPoint[i].y - bitmap.getHeight() * .5f, paint);\n }\n }\n getHolder().unlockCanvasAndPost(canvas);\n }\n }\n\n public int getDuration() {\n return duration;\n }\n\n public void setDuration(int duration) {\n this.duration = duration;\n }\n\n @Override\n public void surfaceCreated(SurfaceHolder holder) {\n }\n\n @Override\n public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {\n updateGiftSurfaceViewParams(width, height);\n }\n\n @Override\n public void surfaceDestroyed(SurfaceHolder holder) {\n stopAnimation();\n }\n}\n"} {"task_id": "Java_3030", "language": "Java", "task_type": "method_signature", "source_file": "java/github/uber-common/android-build-eval/mobile_app1/module971/src/main/java/module971packageJava0/Foo160.java", "mask_start_position": 351, "mask_end_position": 370, "canonical_solution": "public void foo4() ", "pre_mask_code": "package module971packageJava0;\n\nimport java.lang.Integer;\n\npublic class Foo160 {\n\n Integer int0;\n\n Integer int1;\n\n public void foo0() {\n new module971packageJava0.Foo159().foo5();\n }\n\n public void foo1() {\n foo0();\n }\n\n public void foo2() {\n foo1();\n }\n\n public void foo3() {\n foo2();\n }\n\n ", "post_mask_code": "{\n foo3();\n }\n\n public void foo5() {\n foo4();\n }\n}\n"} {"task_id": "Java_3031", "language": "Java", "task_type": "method_body", "source_file": "java/github/uber-common/android-build-eval/mobile_app1/module971/src/main/java/module971packageJava0/Foo160.java", "mask_start_position": 322, "mask_end_position": 345, "canonical_solution": "{\n foo2();\n }", "pre_mask_code": "package module971packageJava0;\n\nimport java.lang.Integer;\n\npublic class Foo160 {\n\n Integer int0;\n\n Integer int1;\n\n public void foo0() {\n new module971packageJava0.Foo159().foo5();\n }\n\n public void foo1() {\n foo0();\n }\n\n public void foo2() {\n foo1();\n }\n\n public void foo3() ", "post_mask_code": "\n\n public void foo4() {\n foo3();\n }\n\n public void foo5() {\n foo4();\n }\n}\n"} {"task_id": "Java_3032", "language": "Java", "task_type": "single_line", "source_file": "java/github/uber-common/android-build-eval/mobile_app1/module971/src/main/java/module971packageJava0/Foo160.java", "mask_start_position": 238, "mask_end_position": 243, "canonical_solution": "o0();", "pre_mask_code": "package module971packageJava0;\n\nimport java.lang.Integer;\n\npublic class Foo160 {\n\n Integer int0;\n\n Integer int1;\n\n public void foo0() {\n new module971packageJava0.Foo159().foo5();\n }\n\n public void foo1() {\n fo", "post_mask_code": "\n }\n\n public void foo2() {\n foo1();\n }\n\n public void foo3() {\n foo2();\n }\n\n public void foo4() {\n foo3();\n }\n\n public void foo5() {\n foo4();\n }\n}\n"} {"task_id": "Java_3033", "language": "Java", "task_type": "method_signature", "source_file": "java/github/MyersResearchGroup/iBioSim/verification/src/main/java/edu/utah/ece/async/lema/verification/timed_state_exploration/zoneProject/Zone.java", "mask_start_position": 148608, "mask_end_position": 148663, "canonical_solution": "public static int warp(int z1, int z2, int r1, int r2) ", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * This file is part of iBioSim. Please visit \n * for the latest version of iBioSim.\n *\n * and also available online at .\n *\n * *****************************************************************************\n */\npackage edu.utah.ece.async.lema.verification.timed_state_exploration.zoneProject;\n\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport edu.utah.ece.async.lema.verification.lpn.ExprTree;\nimport edu.utah.ece.async.lema.verification.lpn.LPN;\nimport edu.utah.ece.async.lema.verification.lpn.Transition;\nimport edu.utah.ece.async.lema.verification.lpn.Variable;\nimport edu.utah.ece.async.lema.verification.platu.main.Options;\nimport edu.utah.ece.async.lema.verification.platu.platuLpn.DualHashMap;\nimport edu.utah.ece.async.lema.verification.platu.platuLpn.LpnTranList;\nimport edu.utah.ece.async.lema.verification.platu.stategraph.State;\nimport edu.utah.ece.async.lema.verification.timed_state_exploration.octagon.Equivalence;\n\n/**\n * This class is for storing and manipulating the delay information for transitions as well as\n * the values of continuous variables including rate their rates.\n * A Zone represents the non-zero continuous variables and the timers for the delay in a\n * Difference Bound Matrix (DBM)\n *\n * t0 c0 c1 t0 t1\n * t0 m00 m01 m02 m03 m04\n * c0 m10 m11 m12 m13 m14\n * c1 m20 m21 m22 m23 m24\n * t0 m30 m31 m32 m33 m34\n * t1 m40 m41 m42 m43 m44\n *\n * For the timers, tj - ti <= m(ti,tj) where m(ti,tj) represents the element of the matrix with\n * row ti and column tj. In particular, m(t0,ti) is an upper bound for ti and -m(ti,0) is a\n * lower bound for ti. The continuous variables are normalized to have rate one before being\n * placed in the matrix. Thus for a continuous variables ci with rate ri, the entry m(t0, ci) is\n * (upper bound)/ri where 'upper bound' is the upper bound for the continuous variable and\n * m(ci,t0) is -1*(lower bound)/ri where 'lower bound' is the lower bound of the continuous variable.\n * When the rate is negative, dividing out by the rate switches the inequalities. For example,\n * if ci is a continuous variable such that l < ci < u for some values l and u, then the normalized\n * ci (that is ci/ri) is satisfies u/ri < ci/r < l/ri. Hence the m(t0,ci) is (lower bound)/ri and\n * m(ci,0) is -1*(upper bound)/ri. The m(ci,cj) as well as m(ti,ci) and m(ci,ti) give the same kind\n * of relational information as with just timers, but with the normalized values of the continuous\n * variables. Note that a Zone with normalized continuous variables is referred to as being a 'warped'\n * zone.\n *\n * The rate zero continuous variables are also stored in a Zone object, but they are not present in\n * the zone. The Zone merely records the range of the continuous variable.\n *\n * The timers are referenced by the name of the transition that they are associated with and continuous\n * variables are referenced by their name as well. In addition for non-zero rate continuous variables and\n * the timers, several method will allow them to be referred by their index as a part of the (DMB). For\n * example, c0 in the above DBM example, has index 1.\n *\n * A third way that the timers and variables (both rate zero and rate non-zero) can be referred to by\n * an LPNTransitionPair object. These objects refer to a timer or continuous variable by providing the index\n * of the corresponding transition or the index of the continuous variable as a member of an LPN and the\n * index of that LPN. The LPNTransitionPair can be made more specific in the case of the continuous variables\n * by using an LPNContinuousPair. These objects also provide the rate of the variable. LPNTransitionPairs\n * can be used with continuous variables when they are only being used as an index only. If the rate is needed\n * for the method, then LPNContinuousPairs must be used.\n *\n * @author Andrew N. Fisher\n * @author Chris Myers\n * @author iBioSim Contributors \n * @version %I%\n */\npublic class Zone implements Equivalence {\n\n /*Abstraction Function : \n\t* The difference bound matrix is stored in the _matrix member field, along with \n\t* the upper and lower bounds of the timers and rates for continuous variables.\n\t* The upper and lower bounds are stored when the timer becomes enabled. The upper and\n\t* lower bounds of the rates are stored when the rate is assigned. The upper and lower \n\t* bounds are stored in the first row and first column of the _matrix member field.\n\t* The DBM occupies the rest of the array, that is, the sub-array formed by removing\n\t* the first column and first row.\n\t* For example, let t1 be a timer for a transition whose delay is between 2 and 3. Further\n\t* let c1 be a continuous variable with rate between 4 and 5. Then _matrix would look like\n\t* lb t0 c1 t1\n\t* ub x 0 5 3\n\t* t0 0 m m m\n\t* c1 -4 m m m\n\t* t1 -2 m m m\n\t* \n\t* with out the lb, ub, t0, t1, and c1.\n\t* \n\t* The x is does not represent anything and will most likely be zero. The upper and lower \n\t* bounds for the zero timer (which is always present) are always 0. The m's comprise \n\t* the DBM.\n\t* \n\t* For the most part, a timer or a continuous variable is referred to internally by an\n\t* LPNTransitionPair. An LPNTransitionPair combines the index of the transition (or\n\t* continuous variable) with the index of the LPN that the transition (or continuous \n\t* variables) is a member of. Both continuous variables and transitions can be referred\n\t* to by an LPNTransitionPair; however, it is better to use an LPNContinuousPair (which\n\t* is inherited from the LPNTransitionPair) to refer to continuous variables.\n\t* LPNContinuousPairs are used to distinguish continuous variables from transitions. They \n\t* also store the current rate of the continuous variable. \n\t* \n\t* The LPNTransitionPairs are stored in the _indexToTimerPair member field. The row/column\n\t* in the DBM for a transition is determined by the its position in this array. For example,\n\t* suppose a transition t has an LPNTransitionPair ltTranPair that is the third element of\n\t* the _indexToTimerPair. Then t will be the third column/row of the DBM.\n\t* \n\t* Continuous variables are handled slightly differently. The LPNContinuousPair for the \n\t* continuous variables with a non-zero rate are stored in the _indexToTimerPair just as \n\t* with the transitions. And just like with the transitions, the index in the DBM is\n\t* determined by the index of the LPNContinuousPair in the _indexToTimerPair. However,\n\t* rate zero continuous variables are stored in the _rateZeroContinuous member variable.\n\t* The _rateZerContinuous pairs an LPNContinuousPair with a VariableRangePair. The\n\t* VariableRangePair combines the variable with its upper and lower bound.\n\t* \n\t*/\n /* Representation invariant :\n\t* Zones are immutable.\n\t* Integer.MAX_VALUE is used to logically represent infinity.\n\t* The lb and ub values for a timer should be set when the timer is enabled.\n\t* A negative hash code indicates that the hash code has not been set.\n\t* The index of the timer in _indexToTimer is the index in the DBM and should contain\n\t* \tthe zeroth timer.\n\t* The array _indexToTimerPair should always be sorted.\n\t* The index of the LPN should match where it is in the _lpnList, that is, if lpn is\n\t* \tand LhpnFile object in _lpnList, then _lpnList[getLpnIndex()] == lpn.\n\t* The LPNTransitionPair in the _indexToTimer array should be an LPNContinuousPair\n\t* when it stores the index to a continuous variable. Testing that the index\n\t* is an LPNContinuousPair is used to determined if the indexing object points\n\t* to a continuous variable. Also the LPNContinuousPair keeps track of the current rate.\n\t* \n\t*/\n /*\n\t * Resource List :\n\t * TODO : Create a list reference where the algorithms can be found that this class\n\t * depends on.\n\t */\n public static final int INFINITY = Integer.MAX_VALUE;\n\n /* The lower and upper bounds of the times as well as the dbm. */\n private int[][] _matrix;\n\n /* Maps the index to the timer. The index is row/column of the DBM sub-matrix.\n\t * Logically the zero timer is given index -1.\n\t * */\n private LPNTransitionPair[] _indexToTimerPair;\n\n /* The hash code. */\n private int _hashCode;\n\n /* A lexicon between a transitions index and its name. */\n /* Set if a failure in the testSplit method has fired already. */\n /* Hack to pass a parameter to the equals method though a variable */\n /* Stores the continuous variables that have rate zero */\n DualHashMap _rateZeroContinuous;\n\n /* Records the largest zone that occurs. */\n public static int ZoneSize = 0;\n\n /* Write a log file */\n private static BufferedWriter _writeLogFile = null;\n\n /**\n * Returns the write log.\n * @return\n * \t\tThe _writeLogfile.\n */\n public static BufferedWriter get_writeLogFile() {\n return _writeLogFile;\n }\n\n /**\n * Sets the BufferedWriter.\n * @param writeLogFile\n */\n public static void set_writeLogFile(BufferedWriter writeLogFile) {\n _writeLogFile = writeLogFile;\n }\n\n /**\n * Sets the writeLogFile to null.\n */\n public static void reset_writeLogFile() {\n _writeLogFile = null;\n }\n\n private void checkZoneMaxSize() {\n if (dbmSize() > ZoneSize) {\n ZoneSize = dbmSize();\n }\n }\n\n private LPN[] _lpnList;\n\n /* \n\t * Turns on and off subsets for the zones.\n\t * True means subset will be considered.\n\t * False means subsets will not be considered.\n\t */\n private static boolean _subsetFlag = true;\n\n /* \n\t * Turns on and off supersets for zones.\n\t * True means that supersets will be considered.\n\t * False means that supersets will not be considered.\n\t */\n private static boolean _supersetFlag = true;\n\n /**\n * Gets the value of the subset flag.\n * @return\n * \t\tTrue if subsets are requested, false otherwise.\n */\n public static boolean getSubsetFlag() {\n return _subsetFlag;\n }\n\n /**\n * Sets the value of the subset flag.\n * @param useSubsets\n * \t\t\tThe value for the subset flag. Set to true if\n * \t\t\tsupersets are to be considered, false otherwise.\n */\n public static void setSubsetFlag(boolean useSubsets) {\n _subsetFlag = useSubsets;\n }\n\n /**\n * Gets the value of the superset flag.\n * @return\n * \t\tTrue if supersets are to be considered, false otherwise.\n */\n public static boolean getSupersetFlag() {\n return _supersetFlag;\n }\n\n /**\n * Sets the superset flag.\n * @param useSupersets\n * \t\tThe value of the superset flag. Set to true if\n * \t\tsupersets are to be considered, false otherwise.\n */\n public static void setSupersetFlag(boolean useSupersets) {\n _supersetFlag = useSupersets;\n }\n\n /**\n * Construct a zone that has the given timers.\n * @param timers\n * \t\t\t\tThe ith index of the array is the index of the timer. For example,\n * \t\t\t\t\tif timers = [1, 3, 5], then the zeroth row/column of the DBM is the\n * \t\t\t\t\ttimer of the transition with index 1, the first row/column of the\n * \t\t\t\t\tDBM is the timer of the transition with index 3, and the 2nd\n * \t\t\t\t\trow/column is the timer of the transition with index 5. Do not\n * \t\t\t\t\tinclude the zero timer.\n * @param matrix\n * \t\t\t\tThe DBM augmented with the lower and upper bounds of the delays for the\n * \t\t\t\t\ttransitions. For example, suppose a zone has timers [1, 3, 5] (as\n * \t\t\t\t\tdescribed in the timers parameters). The delay for transition 1 is\n * \t\t\t\t\t[1, 3], the delay for transition 3 is [2,5], and the delay for\n * \t\t\t\t\ttransition 5 is [4,6]. Also suppose the DBM is\n * \t\t\t\t\t t0 t1 t3 t5\n * \t\t\t\t\tt0 | 0, 3, 3, 3 |\n * \t\t\t\t\tt1 | 0, 0, 0, 0 |\n * \t\t\t\t\tt3 | 0, 0, 0, 0 |\n * \t\t\t\t\tt5 | 0, 0, 0, 0 |\n * \t\t\t\t\tThen the matrix that should be passed is\n * \t\t\t\t\t lb t0 t1 t3 t5\n * \t\t\t\t\tub| 0, 0, 3, 5, 6|\n * \t\t\t\t\tt0| 0, 0, 3, 3, 3|\n * \t\t\t\t\tt1|-1, 0, 0, 0, 0|\n * \t\t\t\t\tt3|-2, 0, 0, 0, 0|\n * \t\t\t\t\tt5|-4, 0, 0, 0, 0|\n * \t\t\t\t\tThe matrix should be non-null and the zero timer should always be the\n * \t\t\t\t\tfirst timer, even when there are no other timers.\n */\n public Zone(int[] timers, int[][] matrix) {\n // A negative number indicates that the hash code has not been set.\n _hashCode = -1;\n // Make a copy to reorder the timers.\n // Make a copy to reorder the timers.\n _indexToTimerPair = new LPNTransitionPair[timers.length];\n for (int i = 0; i < timers.length; i++) {\n _indexToTimerPair[i] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);\n }\n // Sorting the array.\n // Sorting the array.\n Arrays.sort(_indexToTimerPair);\n // // Add the zeroth timer.\n if (_indexToTimerPair[0].get_transitionIndex() != -1) {\n // Add the zeroth timer.\n LPNTransitionPair[] newIndexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newIndexToTimerPair[i + 1] = _indexToTimerPair[i];\n }\n _indexToTimerPair = newIndexToTimerPair;\n _indexToTimerPair[0] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, -1);\n }\n // throw new IllegalArgumentException(\"Timers must be non negative.\");\n // // Add a zero timer.\n // Map the old index of the timer to the new index of the timer.\n HashMap newIndex = new HashMap();\n // For the old index, find the new index.\n for (int i = 0; i < timers.length; i++) {\n // Since the zeroth timer is not included in the timers passed\n // to the index in the DBM is 1 more than the index of the timer\n // in the timers array.\n // LPNTransitionPair searchValue =\n LPNTransitionPair searchValue = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);\n newIndex.put(i + 1, Arrays.binarySearch(_indexToTimerPair, searchValue));\n }\n // Add the zero timer index.\n newIndex.put(0, 0);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Copy the DBM\n for (int i = 0; i < dbmSize(); i++) {\n for (int j = 0; j < dbmSize(); j++) {\n // Copy the passed in matrix to _matrix.\n setDbmEntry(newIndex.get(i), newIndex.get(j), matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]);\n // In the above, changed setDBMIndex to setdbm\n }\n }\n // Copy in the upper and lower bounds. The zero time does not have an upper or lower bound\n // so the index starts at i=1, the first non-zero timer.\n for (int i = 1; i < dbmSize(); i++) {\n setUpperBoundbydbmIndex(newIndex.get(i), matrix[0][dbmIndexToMatrixIndex(i)]);\n // Note : The method setLowerBoundbydbmIndex, takes the value of the lower bound\n // and the matrix stores the negative of the lower bound. So the matrix value\n // must be multiplied by -1.\n setLowerBoundbydbmIndex(newIndex.get(i), -1 * matrix[dbmIndexToMatrixIndex(i)][0]);\n }\n recononicalize();\n }\n\n /**\n * Initializes a zone according to the markings of state.\n * @param currentState\n * \t\t\tThe zone is initialized as if all enabled timers\n * \t\t\thave just been enabled.\n */\n public Zone(State initialState) {\n // Extract the associated LPN.\n LPN lpn = initialState.getLpn();\n int LPNIndex = lpn.getLpnIndex();\n if (_lpnList == null) {\n // If no LPN exists yet, create it and put lpn in it.\n _lpnList = new LPN[LPNIndex + 1];\n _lpnList[LPNIndex] = lpn;\n } else if (_lpnList.length <= LPNIndex) {\n // The list does not contain the lpn.\n LPN[] tmpList = _lpnList;\n _lpnList = new LPN[LPNIndex + 1];\n _lpnList[LPNIndex] = lpn;\n // Copy any that exist already.\n for (int i = 0; i < _lpnList.length; i++) {\n _lpnList[i] = tmpList[i];\n }\n } else if (_lpnList[LPNIndex] != lpn) {\n // This checks that the appropriate lpn is in the right spot.\n // If not (which gets you in this block), then this fixes it.\n _lpnList[LPNIndex] = lpn;\n }\n // Default value for the hash code indicating that the hash code has not\n // been set yet.\n _hashCode = -1;\n // Get the list of currently enabled Transitions by their index.\n boolean[] enabledTran = initialState.getTranVector();\n ArrayList enabledTransitionsArrayList = new ArrayList();\n LPNTransitionPair zeroPair = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, LPNTransitionPair.ZERO_TIMER);\n // Add the zero timer first.\n enabledTransitionsArrayList.add(zeroPair);\n // The index of the boolean value corresponds to the index of the Transition.\n for (int i = 0; i < enabledTran.length; i++) {\n if (enabledTran[i]) {\n enabledTransitionsArrayList.add(new LPNTransitionPair(LPNIndex, i));\n }\n }\n _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);\n _matrix = new int[matrixSize()][matrixSize()];\n for (int i = 1; i < dbmSize(); i++) {\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = lpn.getTransition(_indexToTimerPair[i].get_transitionIndex()).getLabel();\n ExprTree delay = lpn.getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = lpn.getAllVarsWithValuesAsString(initialState.getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n ExprTree lowerDelay = delay.getLeftChild();\n ExprTree upperDelay = delay.getRightChild();\n lower = (int) lowerDelay.evaluateExpr(varValues);\n upper = (int) upperDelay.evaluateExpr(varValues);\n } else {\n lower = (int) delay.evaluateExpr(varValues);\n upper = lower;\n }\n setLowerBoundbydbmIndex(i, lower);\n setUpperBoundbydbmIndex(i, upper);\n }\n // Advance the time and tighten the bounds.\n advance();\n recononicalize();\n checkZoneMaxSize();\n }\n\n /**\n * Creates a Zone based on the local states.\n * @param localStates\n * \t\t\tThe current state (or initial) of the LPNs.\n */\n public Zone(State[] localStates) {\n // Open the log file.\n if (_writeLogFile == null && Options.get_TimingLogfile() != null) {\n try {\n _writeLogFile = new BufferedWriter(new FileWriter(Options.get_TimingLogfile()));\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n }\n }\n // Initialize hash code to -1 (indicating nothing cached).\n _hashCode = -1;\n // Initialize the LPN list.\n initialize_lpnList(localStates);\n // Get the enabled transitions. This initializes the _indexTotimerPair\n // which stores the relevant information.\n // This method will also initialize the _rateZeroContinuous\n initialize_indexToTimerPair(localStates);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Set the lower bound/ upper bounds of the timers and the rates.\n initializeLowerUpperBounds(getAllNames(), localStates);\n // Initialize the row and column entries for the continuous variables.\n initializeRowColumnContVar();\n // Create a previous zone to the initial zone for the sake of warping.\n Zone tmpZone = beforeInitialZone();\n dbmWarp(tmpZone);\n recononicalize();\n // Advance Time\n advance(localStates);\n // Re-canonicalize\n recononicalize();\n // Check the size of the DBM.\n checkZoneMaxSize();\n }\n\n /**\n * Creates a Zone based on the local states.\n * @param localStates\n * \t\t\tThe current state (or initial) of the LPNs.\n */\n public Zone(State[] localStates, boolean init) {\n // Extract the local states.\n // Initialize hash code to -1 (indicating nothing cached).\n _hashCode = -1;\n // Initialize the LPN list.\n initialize_lpnList(localStates);\n // Get the enabled transitions. This initializes the _indexTotimerPair\n // which stores the relevant information.\n // This method will also initialize the _rateZeroContinuous\n initialize_indexToTimerPair(localStates);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Set the lower bound/ upper bounds of the timers and the rates.\n initializeLowerUpperBounds(getAllNames(), localStates);\n // Initialize the row and column entries for the continuous variables.\n initializeRowColumnContVar();\n if (init) {\n return;\n }\n // Advance Time\n advance(localStates);\n // Re-canonicalize\n recononicalize();\n // Check the size of the DBM.\n checkZoneMaxSize();\n }\n\n // * Sets ups a zone containing continuous variables only.\n // * @param continuousValues\n // * \t\tThe values to populate the zone with.\n // // Copy the LPNContinuousPairs over\n // int count = 0; // The position in the _indexToTimerPair for the next value.\n /**\n * Gives the names of all the transitions and continuous variables that\n * are represented by the zone.\n * @return\n * \t\tThe names of the transitions and continuous variables that are\n * \t\trepresented by the zone.\n */\n public String[] getAllNames() {\n // transitionNames[0] = \"The zero timer.\";\n // Get the continuous variable names.\n String[] contVar = getContVarNames();\n // Get the transition names.\n String[] trans = getTranNames();\n // Create an array large enough for all the names.\n String[] names = new String[contVar.length + trans.length + 1];\n // Add the zero timer.\n names[0] = \"The zero timer.\";\n // Add the continuous variables.\n for (int i = 0; i < contVar.length; i++) {\n names[i + 1] = contVar[i];\n }\n // Add the timers.\n for (int i = 0; i < trans.length; i++) {\n // Already the zero timer has been added and the elements of contVar.\n // That's a total of 'contVar.length + 1' elements. The last index was\n // thus 'contVar.length' So the first index to add to is\n names[1 + contVar.length + i] = trans[i];\n }\n return names;\n }\n\n /**\n * Get the names of the continuous variables that this zone uses.\n * @return\n * \t\tThe names of the continuous variables that are part of this zone.\n */\n public String[] getContVarNames() {\n // List for accumulating the names.\n ArrayList contNames = new ArrayList();\n // Find the pairs that represent the continuous variables. Loop starts at\n // i=1 since the i=0 is the zero timer.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // If the isTimer value is false, then this pair represents a continuous\n // If pair is LPNContinuousPair.\n if (ltPair instanceof LPNContinuousPair) {\n // Get the LPN that this pairing references and find the name of\n // the continuous variable whose index is given by this pairing.\n contNames.add(_lpnList[ltPair.get_lpnIndex()].getContVarName(ltPair.get_transitionIndex()));\n }\n }\n return contNames.toArray(new String[0]);\n }\n\n /**\n * Gets the names of the transitions that are associated with the timers in the\n * zone. Does not return the zero timer.\n * @return\n * \t\tThe names of the transitions whose timers are in the zone except the zero\n * \t\ttimer.\n */\n public String[] getTranNames() {\n // List for accumulating the names.\n ArrayList transitionNames = new ArrayList();\n // Find the pairs that represent the transition timers.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // If the isTimer value is true, then this pair represents a timer.\n // If this is an LPNTransitionPair and not an LPNContinuousPair\n if (!(ltPair instanceof LPNContinuousPair)) {\n // Get the LPN that this pairing references and find the name of the\n // transition whose index is given by this pairing.\n transitionNames.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()).getLabel());\n }\n }\n return transitionNames.toArray(new String[0]);\n }\n\n /**\n * Initializes the _lpnList using information from the local states.\n * @param localStates\n * \t\tThe local states.\n * @return\n * \t\tThe enabled transitions.\n */\n private void initialize_lpnList(State[] localStates) {\n // Create the LPN list.\n _lpnList = new LPN[localStates.length];\n // Get the LPNs.\n for (int i = 0; i < localStates.length; i++) {\n _lpnList[i] = localStates[i].getLpn();\n }\n }\n\n /**\n * Initializes the _indexToTimerPair from the local states. This includes\n * adding the zero timer, the continuous variables and the set of\n * enabled timers.\n * @param localStates\n * \t\tThe local states.\n * @return\n * \t\tThe names of the transitions stored in the _indexToTimerPair (in the same order).\n */\n private void initialize_indexToTimerPair(State[] localStates) {\n /*\n\t\t * The populating of the _indexToTimerPair is done in three stages.\n\t\t * The first is to add the zero timer which is at the beginning of the zone.\n\t\t * The second is to add the continuous variables. And the third is to add\n\t\t * the other timers. Since the continuous variables are added before the\n\t\t * timers and the variables and timers are added in the order of the LPNs,\n\t\t * the elements in an accumulating list (enabledTransitionsArrayList) are\n\t\t * already in order up to the elements added for a particular LPN. Thus the\n\t\t * only sorting that needs to take place is the sorting for a particular LPN.\n\t\t * Correspondingly, elements are first found for an LPN and sort, then added\n\t\t * to the main list.\n\t\t */\n // This method will also initialize the _rateZeroContinuous\n _rateZeroContinuous = new DualHashMap();\n // This list accumulates the transition pairs (ie timers) and the continuous\n ArrayList enabledTransitionsArrayList = new ArrayList();\n // Put in the zero timer.\n // enabledTransitionsArrayList\n enabledTransitionsArrayList.add(new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, LPNTransitionPair.ZERO_TIMER));\n // Get the continuous variables.\n for (int i = 0; i < localStates.length; i++) {\n // Accumulates the changing continuous variables for a single LPN.\n ArrayList singleLPN = new ArrayList();\n // Get the associated LPN.\n LPN lpn = localStates[i].getLpn();\n // Get the continuous variables for this LPN.\n String[] continuousVariables = lpn.getContVars();\n // Get the variable, index map.\n DualHashMap variableIndex = lpn.getContinuousIndexMap();\n // Find which have a nonzero rate.\n for (int j = 0; j < continuousVariables.length; j++) {\n // Get the Variables with this name.\n Variable contVar = lpn.getVariable(continuousVariables[j]);\n // Get the rate.\n IntervalPair rate = parseRate(contVar.getInitRate());\n // Get the LPN index for the variable\n int lpnIndex = lpn.getLpnIndex();\n // Get the index as a variable for the LPN.\n int contVariableIndex = variableIndex.get(continuousVariables[j]);\n LPNContinuousPair newPair = new LPNContinuousPair(lpnIndex, contVariableIndex, rate.getSmallestRate());\n // If the rate is non-zero, then the variables needs to be tracked\n // by matrix part of the Zone.\n if (newPair.getCurrentRate() != 0) {\n // Temporary exception guaranteeing only unit rates.\n // \"only supports positive unit rates. The variable \" + contVar +\n // \" has a rate of \" + rate);\n // // Get the LPN index for the variable\n // // Get the index as a variable for the LPN. This index matches\n // // the index in the vector stored by platu.State.\n // The continuous variable reference.\n singleLPN.add(newPair);\n } else {\n // If the rate is zero, then the Zone keeps track of this variable\n // in a list.\n _rateZeroContinuous.insert(new LPNContAndRate(newPair, rate), new VariableRangePair(contVar, parseRate(contVar.getInitValue())));\n }\n }\n // Sort the list.\n Collections.sort(singleLPN);\n // Add the list to the total accumulating list.\n for (int j = 0; j < singleLPN.size(); j++) {\n enabledTransitionsArrayList.add(singleLPN.get(j));\n }\n }\n // Get the transitions.\n for (int i = 0; i < localStates.length; i++) {\n // Extract the enabled transition vector.\n boolean[] enabledTran = localStates[i].getTranVector();\n // Accumulates the transition pairs for one LPN.\n ArrayList singleLPN = new ArrayList();\n // The index of the boolean value corresponds to the index of the Transition.\n for (int j = 0; j < enabledTran.length; j++) {\n if (enabledTran[j]) {\n // Add the transition pair.\n singleLPN.add(new LPNTransitionPair(i, j));\n }\n }\n // Sort the transitions for the current LPN.\n Collections.sort(singleLPN);\n // Add the collection to the enabledTransitionsArrayList\n for (int j = 0; j < singleLPN.size(); j++) {\n enabledTransitionsArrayList.add(singleLPN.get(j));\n }\n }\n // Extract out the array portion of the enabledTransitionsArrayList.\n _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);\n }\n\n /**\n * Sets the lower and upper bounds for the transitions and continuous variables.\n * @param varNames\n * \t\t\tThe names of the transitions in _indexToTimerPair.\n */\n private void initializeLowerUpperBounds(String[] varNames, State[] localStates) {\n // Traverse the entire length of the DBM sub-matrix except the zero row/column.\n // This is the same length as the _indexToTimerPair.length-1. The DBM is used to\n // match the idea of setting the value for each row.\n for (int i = 1; i < dbmSize(); i++) {\n // Get the current LPN and transition pairing.\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n IntervalPair range;\n if (ltPair instanceof LPNContinuousPair) {\n // If the pairing represents a continuous variable, then the\n // upper and lower bound are the initial value or infinity depending\n // on whether the initial rate is positive or negative.\n // If the value is a constant, then assign the upper and lower bounds\n // to be constant. If the value is a range then assign the upper and\n // lower bounds to be a range.\n Variable v = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());\n String rate = v.getInitRate();\n // Parse the rate. Should be in the form of [x,y] where x\n // and y are integers.\n range = parseRate(rate);\n // Set the upper and lower bound (in the matrix) for the\n // continuous variables.\n String contValue = v.getInitValue();\n IntervalPair bound = parseRate(contValue);\n // Set upper bound (DBM entry (0, x) where x is the index of the variable v).\n setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, bound.get_UpperBound());\n // Set lower bound (DBM entry (x, 0) where x is the index of the variable v).\n setDbmEntryByPair(ltPair, LPNTransitionPair.ZERO_TIMER_PAIR, -1 * bound.get_LowerBound());\n } else {\n // Get the expression tree.\n ExprTree delay = _lpnList[ltPair.get_lpnIndex()].getDelayTree(varNames[i]);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[ltPair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[ltPair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n // Passing the zone as null since it should not be needed.\n // // The lower and upper bounds should evaluate to a single\n // throw new IllegalStateException(\"When evaulating the delay, \" +\n // \"the lower or the upper bound evaluated to a range \" +\n // \"instead of a single value.\");\n if (delay != null) {\n range = delay.evaluateExprBound(varValues, this, null);\n } else {\n range = new IntervalPair(0, 0);\n }\n }\n setLowerBoundbydbmIndex(i, range.get_LowerBound());\n setUpperBoundbydbmIndex(i, range.get_UpperBound());\n }\n }\n\n /**\n * Initialize the rows and columns for the continuous variables.\n */\n private void initializeRowColumnContVar() {\n /*\n\t\t * TODO : Describe the idea behind the following algorithm.\n\t\t */\n // // Note: row is indexing the row of the DBM matrix.\n // // If we reached the timers, stop.\n // // Note: col is indexing the column of the DBM matrix.\n // // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since\n // // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower\n // // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);\n // The only entries that do not need to be checked are the ones where both variables\n // represent timers.\n for (int row = 2; row < _indexToTimerPair.length; row++) {\n // Note: row is indexing the row of the DBM matrix.\n LPNTransitionPair ltRowPair = _indexToTimerPair[row];\n // // If we reached the timers, stop.\n for (int col = 1; col < row; col++) {\n // Note: col is indexing the column of the DBM matrix.\n LPNTransitionPair ltColPair = _indexToTimerPair[col];\n // If we've reached the part of the zone involving only timers, then break out\n if (!(ltRowPair instanceof LPNContinuousPair) && !(ltColPair instanceof LPNContinuousPair)) {\n break;\n }\n // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since\n // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower\n // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);\n int rowCol = getDbmEntry(row, 0) + getDbmEntry(0, col);\n int colRow = getDbmEntry(col, 0) + getDbmEntry(0, row);\n setDbmEntry(row, col, rowCol);\n setDbmEntry(col, row, colRow);\n }\n }\n }\n\n /**\n * Zero argument constructor for use in methods that create Zones where the members\n * variables will be set by the method.\n */\n private Zone() {\n _matrix = new int[0][0];\n _indexToTimerPair = new LPNTransitionPair[0];\n _hashCode = -1;\n _lpnList = new LPN[0];\n _rateZeroContinuous = new DualHashMap();\n }\n\n /**\n * Gets the upper bound of a Transition from the zone.\n * @param t\n * \t\tThe transition whose upper bound is wanted.\n * @return\n * \t\tThe upper bound of Transition t.\n */\n public int getUpperBoundbyTransition(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n // LPNTransitionPair ltPair =\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return getUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Returns the upper bound of the continuous variable.\n * @param var\n * \t\tThe variable of interest.\n * @return\n * \t\tThe (0,var) entry of the zone, that is the maximum as recored by\n * \t\tthe zone.\n */\n public int getUpperBoundbyContinuousVariable(String contVar, LPN lpn) {\n // // Determine whether the variable is in the zone or rate zero.\n // // If a RangeAndPairing is returned, then get the information from here.\n // // If indexAndRange is null, then try to get the value from the zone.\n // throw new IllegalStateException(\"Atempted to find the upper bound for \"\n // + \"a non-rate zero continuous variable that was not found in the \"\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note : setting the rate is not necessary here since this is only\n // being used as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range().get_UpperBound();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the lower bound for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n return getDbmEntry(0, i);\n }\n\n public int getUpperBoundForRate(LPNTransitionPair contVar) {\n // Check if the contVar is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (i > 0) {\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n // Grab the current rate from the LPNContinuousPair.\n return ((LPNContinuousPair) _indexToTimerPair[i]).getCurrentRate();\n }\n // Assume the rate is zero. This covers the case if conVar\n // is in the rate zero as well as if its not in the state at all.\n return 0;\n }\n\n /**\n * Get the value of the upper bound for the delay. If the index refers\n * to a timer, otherwise get the upper bound for the continuous\n * variables rate.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @return\n * \t\t\tThe upper bound on the transitions delay.\n */\n public int getUpperBoundbydbmIndex(int index) {\n return _matrix[0][dbmIndexToMatrixIndex(index)];\n }\n\n public int getUpperBound(int index) {\n return _matrix[0][dbmIndexToMatrixIndex(index)];\n }\n\n @Override\n public int getUpperBoundTrue(int index) {\n return _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(index)];\n }\n\n public int getUnwarpedUpperBound(LPNContinuousPair lcpair) {\n // Get the index.\n int index = Arrays.binarySearch(_indexToTimerPair, lcpair);\n int rate = ((LPNContinuousPair) _indexToTimerPair[index]).getCurrentRate();\n int warpValue = getUpperBoundTrue(index);\n return warpValue * rate;\n }\n\n public int getLowerBound(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][0];\n }\n\n @Override\n public int getLowerBoundTrue(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][dbmIndexToMatrixIndex(0)];\n }\n\n /**\n * Set the value of the upper bound for the delay.\n * @param t\n * \t\t\tThe transition whose upper bound is being set.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n public void setUpperBoundbyTransition(Transition t, int value) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the upper bound for the delay.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n public void setUpperBoundbydbmIndex(int index, int value) {\n _matrix[0][dbmIndexToMatrixIndex(index)] = value;\n }\n\n /**\n * Sets the upper bound for a transition described by an LPNTransitionPair.\n * @param ltPair\n * \t\t\tThe index of the transition and the index of the associated LPN for\n * \t\t\tthe timer to set the upper bound.\n * @param value\n * \t\t\tThe value for setting the upper bound.\n */\n private void setUpperBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value) {\n setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Gets the lower bound of a Transition from the zone.\n * @param t\n * \t\tThe transition whose upper bound is wanted.\n * @return\n * \t\tThe lower bound of Transition t.\n */\n @Override\n public int getLowerBoundbyTransition(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return getLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Returns the lower bound of the continuous variable.\n * @param var\n * \t\tThe variable of interest.\n * @return\n * \t\tThe (0,var) entry of the zone, that is the minimum as recored by\n * \t\tthe zone.\n */\n public int getLowerBoundbyContinuousVariable(String contVar, LPN lpn) {\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note: Setting the rate is not necessary since this is only being used\n // as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range().get_LowerBound();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the lower bound for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n return getDbmEntry(i, 0);\n }\n\n /**\n * Get the value of the lower bound for the delay if the index refers\n * to a timer, otherwise get the lower bound for the continuous variables\n * rate.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @return\n * \t\t\tThe value of the lower bound.\n */\n public int getLowerBoundbydbmIndex(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][0];\n }\n\n public int getLowerBoundForRate(LPNTransitionPair contVar) {\n // Check if the contVar is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (i > 0) {\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n return getLowerBoundbydbmIndex(contVar.get_transitionIndex());\n }\n // Assume the rate is zero. This covers the case if conVar\n // is in the rate zero as well as if its not in the state at all.\n return 0;\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param t\n * \t\t\tThe transition whose lower bound is being set.\n * @param value\n * \t\t\tThe value of the lower bound.\n */\n public void setLowerBoundbyTransition(Transition t, int value) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param t\n * \t\t\tThe transition whose upper bound is being set.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n private void setLowerBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value) {\n setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @param value\n * \t\t\tThe value of the lower bound.\n */\n public void setLowerBoundbydbmIndex(int index, int value) {\n _matrix[dbmIndexToMatrixIndex(index)][0] = -1 * value;\n }\n\n /**\n * Give the upper and lower bounds for a continuous variable.\n * @param contVar\n * \t\tThe variable of interest.\n * @return\n * \t\tThe upper and lower bounds according to the Zone.\n */\n @Override\n public IntervalPair getContinuousBounds(String contVar, LPN lpn) {\n /*\n\t\t * Need to determine whether this is suppose to be a rate zero variable or a non-zero \n\t\t * rate variable. One method is to check the rate of the passed variable. The other is\n\t\t * to just check if the variable is present in either place.\n\t\t */\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n // Get the index of the continuous variable.\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note: setting the current rate is not necessary here since the\n // LPNContinuousPair is only being used as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(new LPNContAndRate(index, new IntervalPair(0, 0)));\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the bounds for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n // Else find the upper and lower bounds.\n int lower = (-1) * getDbmEntry(i, 0);\n int upper = getDbmEntry(0, i);\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the range for the continuous variable. Values come back not\n * warped.\n * @param ltContPair\n * \t\tThe index of the variable of interest.\n * @return\n * \t\tThe range of the continuous variable described by ltContPair.\n */\n @Override\n public IntervalPair getContinuousBounds(LPNContinuousPair ltContPair) {\n // First check in the zone.\n int variableIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);\n if (variableIndex < 0) {\n // The variable was not found in the zone. Check to see if its\n // in the rate-zero variables. Technically I will return whatever\n // is in the _rateZeroConintuous, null or not.\n // First get an object to reference into the _rateZeroContinuous\n LPNContAndRate lcr = new LPNContAndRate(ltContPair, new IntervalPair(0, 0));\n return _rateZeroContinuous.get(lcr).get_range();\n }\n // The variable was found in the zone. Yay.\n int lower = (-1) * getDbmEntry(variableIndex, 0) * getCurrentRate(ltContPair);\n int upper = getDbmEntry(0, variableIndex) * getCurrentRate(ltContPair);\n // If the current rate is negative the upper and lower bounds\n // need to be switched.\n if (getCurrentRate(ltContPair) < 0) {\n int tmp = lower;\n lower = upper;\n upper = tmp;\n }\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the range of the rate associated with a continuous variable.\n * @param ltContPair\n * \t\tThe index of the continuous variable.\n * @return\n * \t\tThe range of rates associated with the continuous variable indexed\n * \t\tby ltContPair.\n */\n @Override\n public IntervalPair getRateBounds(LPNTransitionPair ltPair) {\n int upper;\n int lower;\n // Check if the ltContpair is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, ltPair);\n if (i < 0) {\n // Then the variable is in the rate zero continuous\n // variables so get the range of rates from there.\n // Create an object to reference into the rate zero.\n LPNContAndRate lcr = new LPNContAndRate((LPNContinuousPair) ltPair, new IntervalPair(0, 0));\n // Get the old version of lcr from the rate zero since\n // that contains the rate. This is quite a hack.\n VariableRangePair vrp = _rateZeroContinuous.get(lcr);\n lcr = _rateZeroContinuous.getKey(vrp);\n return lcr.get_rateInterval();\n }\n upper = getUpperBoundbydbmIndex(i);\n lower = -1 * getLowerBoundbydbmIndex(i);\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the rate reset value.\n * @param ltPair\n * @return\n */\n @Override\n public int rateResetValue(LPNTransitionPair ltPair) {\n IntervalPair rateBounds = getRateBounds(ltPair);\n int upper = rateBounds.get_UpperBound();\n int lower = rateBounds.get_LowerBound();\n // // Check if the ltContpair is in the zone.\n // // Assume the rate is zero. This covers the case if conVar\n // // is in the rate zero as well as if its not in the state at all.\n // If zero is a possible rate, then it is the rate to set to.\n // // If zero is the only possible rate, return that.\n // // When zero is in the range and there is a positive rate, return the\n // // When the upper bound is zero, return the negative rate.\n // // When zero is not present, use the smallest rate in absolute value.\n /*\n\t\t * Suppose the range of rates is [a,b]. If a>=0, we set the rate to b.\n\t\t * If b<=0, we set the rate to a. Otherwise, a<0=0, we set the rate to b.\n\t\t * If b<=0, we set the rate to a. Otherwise, a<0 variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note : Setting the rate is not necessary since this only being used\n // as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and make the new assignment.\n if (pairing != null) {\n pairing.set_range(range);\n return;\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the bounds for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n // Else find the upper and lower bounds.\n setDbmEntry(i, 0, (-1) * range.get_LowerBound());\n setDbmEntry(0, i, range.get_UpperBound());\n }\n\n /**\n * Converts the index of the DBM to the index of _matrix.\n * @param i\n * \t\t\tThe row/column index of the DBM.\n * @return\n * \t\t\tThe row/column index of _matrix.\n */\n private static int dbmIndexToMatrixIndex(int i) {\n return i + 1;\n }\n\n /**\n * Retrieves an entry of the DBM using the DBM's addressing.\n * @param i\n * \t\t\tThe row of the DBM.\n * @param j\n * \t\t\tThe column of the DBM.\n * @return\n * \t\t\tThe value of the (i, j) element of the DBM.\n */\n @Override\n public int getDbmEntry(int i, int j) {\n return _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)];\n }\n\n /**\n * Retrieves an entry of the DBM using LPNTransitionPair indecies.\n * @param iPair\n * \t\tThe LPNTransitionPair for the ith entry.\n * @param jPair\n * \t\tThe LPNTransitionPair for the jth entry.\n * @return\n * \t\tThe value of the (i,j) element of the DBM where i corresponds to the row\n * \t\tfor the variable iPair and j corresponds to the row for the variable jPair.\n */\n @Override\n public int getDbmEntryByPair(LPNTransitionPair iPair, LPNTransitionPair jPair) {\n int iIndex = Arrays.binarySearch(_indexToTimerPair, iPair);\n int jIndex = Arrays.binarySearch(_indexToTimerPair, jPair);\n return getDbmEntry(iIndex, jIndex);\n }\n\n /**\n * Sets an entry of the DBM using the DBM's addressing.\n * @param i\n * \t\t\tThe row of the DBM.\n * @param j\n * \t\t\tThe column of the DBM.\n * @param value\n * \t\t\tThe new value for the entry.\n */\n private void setDbmEntry(int i, int j, int value) {\n _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)] = value;\n }\n\n /**\n * Sets the entry in the DBM using the LPNTransitionPair indexing.\n * @param row\n * \t\t\tThe LPNTransitionPair for the row.\n * @param col\n * \t\t\tThe LPNTransitionPair for the column.\n * @param value\n * \t\t\tThe value to set the entry to.\n */\n private void setDbmEntryByPair(LPNTransitionPair row, LPNTransitionPair col, int value) {\n // The row index.\n int i = timerIndexToDBMIndex(row);\n // The column index.\n int j = timerIndexToDBMIndex(col);\n setDbmEntry(i, j, value);\n }\n\n /**\n * Returns the index of the the transition in the DBM given a LPNTransitionPair pairing\n * the transition index and associated LPN index.\n * @param ltPair\n * \t\tThe pairing comprising the index of the transition and the index of the associated\n * \t\tLPN.\n * @return\n * \t\tThe row/column of the DBM associated with the ltPair.\n */\n @Override\n public int timerIndexToDBMIndex(LPNTransitionPair ltPair) {\n return Arrays.binarySearch(_indexToTimerPair, ltPair);\n }\n\n /**\n * The matrix labeled with 'ti' where i is the transition index associated with the timer.\n */\n @Override\n public String toString() {\n // TODO : Fix the handling of continuous variables in the\n String result = \"Timer and delay or continuous and ranges.\\n\";\n int count = 0;\n // Print the timers.\n for (int i = 1; i < _indexToTimerPair.length; i++, count++) {\n if (_lpnList.length == 0) {\n // If no LPN's are associated with this Zone, use the index of the timer.\n result += \" t\" + _indexToTimerPair[i].get_transitionIndex() + \" : \";\n } else {\n String name;\n // If the current LPNTransitionPair is a timer, get the name\n // from the transitions.\n // If the current timer is an LPNTransitionPair and not an LPNContinuousPair\n if (!(_indexToTimerPair[i] instanceof LPNContinuousPair)) {\n // Get the name of the transition.\n Transition tran = _lpnList[_indexToTimerPair[i].get_lpnIndex()].getTransition(_indexToTimerPair[i].get_transitionIndex());\n name = tran.getLabel();\n } else {\n // If the current LPNTransitionPair is not a timer, get the\n // name as a continuous variable.\n Variable var = _lpnList[_indexToTimerPair[i].get_lpnIndex()].getContVar(_indexToTimerPair[i].get_transitionIndex());\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];\n int lowerBound = -1 * getDbmEntry(i, 0) * lcPair.getCurrentRate();\n int upperBound = getDbmEntry(0, i) * lcPair.getCurrentRate();\n // If the rate is negative, the bounds are switched\n // in the zone.\n if (lcPair.getCurrentRate() < 0) {\n int tmp = lowerBound;\n lowerBound = upperBound;\n upperBound = tmp;\n }\n name = var.getName() + \":[\" + lowerBound + \",\" + upperBound + \"]\\n\" + \" Current Rate: \" + lcPair.getCurrentRate() + \" \" + \"rate:\";\n }\n result += \" \" + name + \":\";\n }\n result += \"[ \" + -1 * getLowerBoundbydbmIndex(i) + \", \" + getUpperBoundbydbmIndex(i) + \" ]\";\n if (count > 9) {\n result += \"\\n\";\n count = 0;\n }\n }\n if (!_rateZeroContinuous.isEmpty()) {\n result += \"\\nRate Zero Continuous : \\n\";\n for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()) {\n result += \"\" + _rateZeroContinuous.get(lcrPair) + \"Rate: \" + lcrPair.get_rateInterval();\n }\n }\n result += \"\\nDBM\\n\";\n // Print the DBM.\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n result += \"| \" + String.format(\"%3d\", getDbmEntry(i, 0));\n for (int j = 1; j < _indexToTimerPair.length; j++) {\n result += \", \" + String.format(\"%3d\", getDbmEntry(i, j));\n }\n result += \" |\\n\";\n }\n return result;\n }\n\n /**\n * Tests for equality. Overrides inherited equals method.\n * @return True if o is equal to this object, false otherwise.\n */\n @Override\n public boolean equals(Object o) {\n // Check if the reference is null.\n if (o == null) {\n return false;\n }\n // Check that the type is correct.\n if (!(o instanceof Zone)) {\n return false;\n }\n // Check for equality using the Zone equality.\n return equals((Zone) o);\n }\n\n /**\n * Tests for equality.\n * @param\n * \t\tThe Zone to compare.\n * @return\n * \t\tTrue if the zones are non-null and equal, false otherwise.\n */\n public boolean equals(Zone otherZone) {\n // Check if the reference is null first.\n if (otherZone == null) {\n return false;\n }\n // Check for reference equality.\n if (this == otherZone) {\n return true;\n }\n // If the hash codes are different, then the objects are not equal.\n if (this.hashCode() != otherZone.hashCode()) {\n return false;\n }\n // Check if the they have the same number of timers.\n if (this._indexToTimerPair.length != otherZone._indexToTimerPair.length) {\n return false;\n }\n // Check if the timers are the same.\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n if (!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))) {\n return false;\n }\n }\n // Check if the matrix is the same\n for (int i = 0; i < _matrix.length; i++) {\n for (int j = 0; j < _matrix[0].length; j++) {\n if (!(this._matrix[i][j] == otherZone._matrix[i][j])) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Determines if this zone is a subset of Zone otherZone.\n * @param otherZone\n * \t\tThe zone to compare against.\n * @return\n * \t\tTrue if this is a subset of other; false otherwise.\n */\n @Override\n public boolean subset(Equivalence otherEquiv) {\n Zone otherZone = (Zone) otherEquiv;\n // Check if the reference is null first.\n if (otherZone == null) {\n return false;\n }\n // Check for reference equality.\n if (this == otherZone) {\n return true;\n }\n // Check if the the same number of timers are present.\n if (this._indexToTimerPair.length != otherZone._indexToTimerPair.length) {\n return false;\n }\n // Check if the transitions are the same.\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n if (!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))) {\n return false;\n }\n }\n // Check if the entries of this Zone are less than or equal to the entries\n // of the other Zone.\n for (int i = 0; i < _matrix.length; i++) {\n for (int j = 0; j < _matrix[0].length; j++) {\n if (!(this._matrix[i][j] <= otherZone._matrix[i][j])) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Determines if this zone is a superset of Zone otherZone.\n * @param otherZone\n * \t\tThe zone to compare against.\n * @return\n * \t\tTrue if this is a subset of other; false otherwise. More specifically it\n * \t\tgives the result of otherZone.subset(this). Thus it agrees with the subset method.\n */\n @Override\n public boolean superset(Equivalence otherZone) {\n return otherZone.subset(this);\n }\n\n /**\n * Overrides the hashCode.\n */\n @Override\n public int hashCode() {\n // Check if the hash code has been set.\n if (_hashCode < 0) {\n _hashCode = createHashCode();\n }\n return _hashCode;\n }\n\n /**\n * Creates a hash code for a Zone object.\n * @return\n * \t\tThe hash code.\n */\n private int createHashCode() {\n int newHashCode = Arrays.hashCode(_indexToTimerPair);\n for (int i = 0; i < _matrix.length; i++) {\n newHashCode ^= Arrays.hashCode(_matrix[i]);\n }\n return Math.abs(newHashCode);\n }\n\n /**\n * The size of the DBM sub matrix. This is calculated using the size of _indexToTimer.\n * @return\n * \t\t\tThe size of the DBM.\n */\n private int dbmSize() {\n return _indexToTimerPair.length;\n }\n\n /**\n * The size of the matrix.\n * @return\n * \t\t\tThe size of the matrix. This is calculated using the size of _indexToTimer.\n */\n private int matrixSize() {\n return _indexToTimerPair.length + 1;\n }\n\n /**\n * Performs the Floyd's least pairs algorithm to reduce the DBM.\n */\n @Override\n public void recononicalize() {\n for (int k = 0; k < dbmSize(); k++) {\n for (int i = 0; i < dbmSize(); i++) {\n for (int j = 0; j < dbmSize(); j++) {\n if (getDbmEntry(i, k) != INFINITY && getDbmEntry(k, j) != INFINITY && getDbmEntry(i, j) > getDbmEntry(i, k) + getDbmEntry(k, j)) {\n setDbmEntry(i, j, getDbmEntry(i, k) + getDbmEntry(k, j));\n }\n if ((i == j) && getDbmEntry(i, j) != 0) {\n throw new DiagonalNonZeroException(\"Entry (\" + i + \", \" + j + \")\" + \" became \" + getDbmEntry(i, j) + \".\");\n }\n }\n }\n }\n }\n\n /**\n * Determines if a timer associated with a given transitions has reached its lower bound.\n * @param t\n * \t\t\tThe transition to consider.\n * @return\n * \t\t\tTrue if the timer has reached its lower bound, false otherwise.\n */\n public boolean exceedsLowerBoundbyTransitionIndex(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return exceedsLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Determines if a timer has reached its lower bound.\n * @param timer\n * \t\t\tThe timer's index.\n * @return\n * \t\t\tTrue if the timer has reached its lower bound, false otherwise.\n */\n public boolean exceedsLowerBoundbydbmIndex(int index) {\n // Note : Make sure that the lower bound is stored as a negative number\n // and that the inequality is correct.\n return _matrix[0][dbmIndexToMatrixIndex(index)] <= _matrix[1][dbmIndexToMatrixIndex(index)];\n }\n\n /* (non-Javadoc)\n\t * @see verification.timed_state_exploration.zone.Zone#fireTransitionbyTransitionIndex(int, int[], verification.platu.stategraph.State)\n\t */\n // State state)\n // // Check if the value is in this zone to fire.\n /**\n * Gives the Zone obtained by firing a given Transitions.\n * @param t\n * \t\tThe transitions being fired.\n * @param enabledTran\n * \t\tThe list of currently enabled Transitions.\n * @param localStates\n * \t\tThe current local states.\n * @return\n * \t\tThe Zone obtained by firing Transition t with enabled Transitions enabled\n * \t\tenabledTran when the current state is localStates.\n */\n // public Zone fire(Transition t, LpnTranList enabledTran,\n @Override\n public Zone fire(Transition t, LpnTranList enabledTran, ContinuousRecordSet newAssignValues, State[] localStates) {\n try {\n if (_writeLogFile != null) {\n _writeLogFile.write(t.toString());\n _writeLogFile.newLine();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n // Create the LPNTransitionPair to check if the Transitions is in the zone and to\n // find the index.\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n int dbmIndex = Arrays.binarySearch(_indexToTimerPair, ltPair);\n if (dbmIndex <= 0) {\n return this;\n }\n // Get the new zone portion.\n Zone newZone = fireTransitionbydbmIndexNew(dbmIndex, enabledTran, localStates, newAssignValues);\n // Update any assigned continuous variables.\n // Set all the rates to their lower bound.\n newZone.setAllToLowerBoundRate();\n // Warp the Zone\n newZone.dbmWarp(this);\n // Warping can wreck the newly assigned values so correct them.\n newZone.correctNewAssignemnts(newAssignValues);\n newZone.recononicalize();\n newZone.advance(localStates);\n // Recanonicalize\n newZone.recononicalize();\n newZone.checkZoneMaxSize();\n return newZone;\n }\n\n /**\n * Updates the Zone according to the transition firing.\n * @param index\n * \t\t\tThe index of the timer.\n * @param newContValue\n * @return\n * \t\t\tThe updated Zone.\n */\n public Zone fireTransitionbydbmIndex(int index, LpnTranList enabledTimers, State[] localStates, ArrayList> newAssignValues) {\n /*\n\t\t * For the purpose of adding the newly enabled transitions and removing\n\t\t * the disable transitions, the continuous variables that still have\n\t\t * a nonzero rate can be treated like still enbaled timers.\n\t\t */\n // Initialize the zone.\n Zone newZone = new Zone();\n // These sets will defferentiate between the new timers and the\n // old timers, that is between the timers that are not already in the\n // zone and those that are already in the zone..\n HashSet newTimers = new HashSet();\n HashSet oldTimers = new HashSet();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n HashMap oldNonZero = newAssignValues.get(3);\n // Add the continuous variables to the enabled timers.\n for (int i = 1; _indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n // For the purpose of addigng continuous variables to the zone\n // consider an oldNonZero continuous variable as new.\n if (oldNonZero.containsKey(_indexToTimerPair[i])) {\n continue;\n }\n oldTimers.add(_indexToTimerPair[i]);\n }\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n // Determine if each value is a new timer or old.\n if (Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0) {\n // The timer was already present in the zone.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else {\n // The timer is a new timer.\n newTimers.add(newZone._indexToTimerPair[i]);\n }\n }\n // Create the new matrix.\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n // TODO: For simplicity, make a copy of the current zone and perform the\n // restriction and re-canonicalization. Later add a copy re-canonicalization\n // that does the steps together.\n Zone tempZone = this.clone();\n tempZone.restrictTimer(index);\n tempZone.recononicalize();\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);\n newZone._matrix[Zone.dbmIndexToMatrixIndex(newIndexi)][Zone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n // The block copies the upper and lower bound information from the\n // old zone. Thus we do not consider anything that is not an old\n // timer. Furthermore, oldNonZero represent\n if (!oldTimers.contains(tempZone._indexToTimerPair[i]) && !oldNonZero.containsKey(_indexToTimerPair[i])) {\n continue;\n }\n newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n newZone.setLowerBoundByLPNTransitionPair(pair, lower);\n newZone.setUpperBoundByLPNTransitionPair(pair, upper);\n }\n // Advance time.\n return newZone;\n }\n\n public Zone fireTransitionbydbmIndexNew(int index, LpnTranList enabledTimers, State[] localStates, ContinuousRecordSet newAssignValues) {\n /*\n\t\t * For the purpose of adding the newly enabled transitions and removing\n\t\t * the disable transitions, the continuous variables that still have\n\t\t * a nonzero rate can be treated like still enbaled timers.\n\t\t */\n // Initialize the zone.\n Zone newZone = new Zone();\n // These sets will defferentiate between the new timers and the\n // old timers, that is between the timers that are not already in the\n // zone and those that are already in the zone..\n HashSet newTimers = new HashSet();\n HashSet oldTimers = new HashSet();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n copyRatesNew(newZone, enabledTimers, newAssignValues);\n // Add the continuous variables to the enabled timers.\n // // For the purpose of addigng continuous variables to the zone\n // // consider an oldNonZero continuous variable as new.\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n // Handle the continuous variables portion.\n if (newZone._indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];\n // Get the record\n UpdateContinuous continuousState = newAssignValues.get(lcPair);\n if (continuousState != null && (continuousState.is_newValue() || continuousState.newlyNonZero())) {\n // In the first case a new value has been assigned, so\n // consider the continuous variable a 'new' variable for\n // the purposes of copying relations from the previous zone.\n newTimers.add(newZone._indexToTimerPair[i]);\n continue;\n }\n // At this point, either the continuous variable was not present\n // in the newAssignValues or it is in the newAssignValues and\n // satisfies the following: it already had a non-zero rate, is\n // being assigned another non-zero rate, and is not being assigned\n // a new value. This is becuase the field _indexToTimerPair only\n // deals with non-zero rates, so the variable must have a non-zero\n // rate. Furthermore the if statement takes care of the cases\n // when the rate changed from zero to non-zero and/or a new value\n // has been assigned.\n // In either of the cases, we consider the variable an 'old' variable\n // for the purpose of copying the previous zone information.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else // At this point, the variable represents a transition (timer).\n // So determine whether this timer is new or old.\n if (Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0) {\n // The timer was already present in the zone.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else {\n // The timer is a new timer.\n newTimers.add(newZone._indexToTimerPair[i]);\n }\n }\n // Create the new matrix.\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n // TODO: For simplicity, make a copy of the current zone and perform the\n // restriction and re-canonicalization. Later add a copy re-canonicalization\n // that does the steps together.\n Zone tempZone = this.clone();\n tempZone.restrictTimer(index);\n tempZone.recononicalize();\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);\n newZone._matrix[Zone.dbmIndexToMatrixIndex(newIndexi)][Zone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n // The block copies the upper and lower bound information from the\n // old zone. Thus we do not consider anything that is not an old\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n // A hack to ensure that the newly zero variables\n // get the new values from the tempZone.\n if (tempZone._indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) tempZone._indexToTimerPair[i];\n VariableRangePair vrp = newZone._rateZeroContinuous.get(new LPNContAndRate(lcPair));\n if (vrp != null) {\n // This means that the continuous variable was non-zero\n // and is now zero. Fix up the values according to\n // the temp zone.\n IntervalPair newRange = tempZone.getContinuousBounds(lcPair);\n vrp.set_range(newRange);\n }\n }\n continue;\n }\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];\n // Check if a rate assignment has occured for any continuous\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord != null) {\n // Since the variable is in the oldTimers, it cannot have had\n // a new value assigned to it. It must have had a new rate assignment\n IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();\n // Copy the new rate information\n newZone.setLowerBoundByLPNTransitionPair(_indexToTimerPair[i], rates.get_LowerBound());\n newZone.setUpperBoundByLPNTransitionPair(_indexToTimerPair[i], rates.get_UpperBound());\n // Copy the smallest and greatest continuous value.\n continue;\n }\n }\n newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Handle continuous case\n if (pair instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) pair;\n // If a continuous variable is in the newTimers, then an assignment\n // to the variable must have occurred. So get the value.\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord == null) {\n throw new IllegalStateException(\"The pair \" + pair + \"was not in the new assigned values but was sorted as \" + \"a new value.\");\n }\n IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();\n IntervalPair values = updateRecord.get_Value();\n newZone.setLowerBoundByLPNTransitionPair(lcPair, rates.get_LowerBound());\n newZone.setUpperBoundByLPNTransitionPair(lcPair, rates.get_UpperBound());\n // Get the current rate.\n int currentRate = lcPair.getCurrentRate();\n if (currentRate >= 0) {\n // // Copy the smallest and greatest continuous value.\n // Copy the smallest and greatest continuous value.\n newZone.setDbmEntryByPair(lcPair, LPNTransitionPair.ZERO_TIMER_PAIR, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), currentRate, true));\n newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, lcPair, ContinuousUtilities.chkDiv(values.get_UpperBound(), currentRate, true));\n } else {\n // Copy the smallest and greatest continuous value.\n // For negative rates, the upper and lower bounds need\n // to be switched.\n newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, lcPair, ContinuousUtilities.chkDiv(values.get_LowerBound(), currentRate, true));\n newZone.setDbmEntryByPair(lcPair, LPNTransitionPair.ZERO_TIMER_PAIR, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), currentRate, true));\n }\n continue;\n }\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n if (delay == null) {\n _lpnList[pair.get_lpnIndex()].changeDelay(tranName, \"0\");\n delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n }\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n newZone.setLowerBoundByLPNTransitionPair(pair, lower);\n newZone.setUpperBoundByLPNTransitionPair(pair, upper);\n }\n // Erase relationships for continuous variables that have had new values\n // assigned to them or a new non-rate zero value.\n for (int i = 1; i < newZone._indexToTimerPair.length && newZone._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];\n // Get the update variable.\n UpdateContinuous update = newAssignValues.get(lcPair);\n if (update != null && (update.is_newValue() || update.newlyNonZero())) {\n for (int j = 1; j < newZone._indexToTimerPair.length; j++) {\n if (j == i) {\n continue;\n }\n newZone.setDbmEntry(i, j, Zone.INFINITY);\n newZone.setDbmEntry(j, i, Zone.INFINITY);\n }\n }\n }\n // Advance time.\n return newZone;\n }\n\n public void correctNewAssignemnts(ContinuousRecordSet newAssignValues) {\n // Erase relationships for continuous variables that have had new values\n // assigned to them or a new non-rate zero value.\n for (int i = 1; i < this._indexToTimerPair.length && this._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];\n // Get the update variable.\n UpdateContinuous update = newAssignValues.get(lcPair);\n if (update != null && (update.is_newValue() || update.newlyNonZero())) {\n IntervalPair values = update.get_Value();\n int currentRate = lcPair.getCurrentRate();\n // Correct the upper and lower bounds.\n if (lcPair.getCurrentRate() > 0) {\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), currentRate, true));\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(values.get_UpperBound(), currentRate, true));\n } else {\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), currentRate, true));\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(values.get_LowerBound(), currentRate, true));\n }\n // Erase the relationships.\n for (int j = 1; j < this._indexToTimerPair.length; j++) {\n if (j == i) {\n continue;\n }\n this.setDbmEntry(i, j, Zone.INFINITY);\n this.setDbmEntry(j, i, Zone.INFINITY);\n }\n }\n }\n }\n\n /**\n * This fire method fires a rate change event.\n *\n * @param ltPair\n * \t\tThe index of the continuous variable whose rate needs to be changed.\n * @param rate\n * \t\tThe new rate.\n * @return\n * \t\tThe new zone resulting from the rate change.\n */\n @Override\n public Zone fire(LPNTransitionPair ltPair, int rate) {\n // Make a copy of the Zone.\n Zone resultZone = this.clone();\n // Change the current rate of the continuous variable.\n setCurrentRate(ltPair, rate);\n // Warp the zone.\n resultZone.dbmWarp(this);\n return resultZone;\n }\n\n /**\n * Handles the moving in and out of continuous variables.\n * @param newContValues\n */\n // // Copy the zero rate variables over if they are still rate zero.\n // // Check if the pairing is in the newNonZeroContValues.\n // // Interval being null indicates that the key was not\n /**\n * Handles the moving of the continuous variables in and out of the\n * _rateZeroContinuous. This includes the adding of all rate zero (new and old)\n * cotninuous variables to the _rateZeroContinuous, and creating the\n * _indexToTimerPair and populating it.\n * @param newZone The Zone being constructed.\n * @param enabled The list of enabled transitions.\n * \t\tThe enabled transitions.\n * @param newAssignValues The list of continuous variable update information.\n */\n @SuppressWarnings(\"unused\")\n private void copyRates(Zone newZone, LpnTranList enabledTran, ContinuousRecordSet newAssignValues) {\n /*\n\t\t * The newAssignValues is an ArrayList of four sets.\n\t\t * 0. Rate zero gets zero assigned.\n\t\t * 1. Rate zero gets non-zero rate assigned.\n\t\t * 2. Non-zero gets zero rate assigned.\n\t\t * 3. Non-zero gets non-zero rate assigned.\n\t\t */\n // Create new rate zero member variable.\n newZone._rateZeroContinuous = new DualHashMap();\n // First get the total number of non-zero rate continuous variables that\n // are present in the old zone.\n int totalContinuous = 0;\n for (int i = 0; i < _lpnList.length; i++) {\n totalContinuous += _lpnList[i].getTotalNumberOfContVars();\n }\n int numberNonZero = totalContinuous - _rateZeroContinuous.size();\n // The size is given by\n // total number of transitions\n // + number of non-zero rate continuous variables previously in the zone\n // + number of zero rate continuous variables that now have non-zero\n // - number of non-zero rate continuous variables that are now zero\n // + 1 for the zero timer.\n // TODO: Create an object that stores the records along with this information.\n int newNonZero = 0, newZero = 0;\n for (UpdateContinuous record : newAssignValues.keySet()) {\n if (record.newlyNonZero()) {\n newNonZero++;\n }\n if (record.newlyZero()) {\n newZero++;\n }\n }\n int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;\n // Create the timer array.\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n // Add in the zero timer.\n newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;\n // Copy over the rate zero conintinuous variables.\n // First copy over all the continuous variables that still have\n // rate zero.\n // // Cast the index.\n // // The variable no longer is rate zero, so do nothing.\n // // If the value has had an assignment, use the new values instead.\n // // Create the new VariableRangePair to add.\n // VariableRangePair vrp =\n // Copy over the rate zero continuous variables.\n // First copy over all the continuous variables that still have\n // rate zero.\n for (LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()) {\n // Cast the index.\n LPNContinuousPair ltContPair = ltTranPair.get_lcPair();\n if (!newAssignValues.get(ltContPair).is_newZero()) {\n // The variable no longer is rate zero, so do nothing.\n continue;\n }\n // If the value has had an assignment, use the new values instead.\n if (newAssignValues.contains(ltContPair)) {\n // Create the new VariableRangePair to add.\n Variable v = _lpnList[ltContPair.get_lpnIndex()].getContVar(ltContPair.get_ContinuousIndex());\n // VariableRangePair vrp =\n VariableRangePair vrp = new VariableRangePair(v, newAssignValues.get(ltContPair).get_Value());\n newZone._rateZeroContinuous.insert(new LPNContAndRate(ltContPair, new IntervalPair(0, 0)), vrp);\n } else {\n newZone._rateZeroContinuous.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));\n }\n }\n // Next add the values that are newly set to rate zero.\n // // Exract the variable.\n // // Create a VariableRangePair.\n // // Add the value to the map.\n // // Exract the variable.\n // // Create a VariableRangePair.\n // // Add the value to the map.\n // We still need to add in the rate zero continuous variables whose rate remains zero\n // since their range might have changed. We could check if the range has changed, but\n // its just as easy (or easier) to simply add it anyway.\n // Added the indecies for the non-zero rate continuous variables to the\n // _indexToTimer array.\n // Start with the values already in the old array.\n // int index = 1; // Index for the next continuous index object.\n // // Check that the value should not be removed.\n // Change to the new references for the oldNonZero. This change to the\n // Add in the indecies for the new non-zero into the old array.\n // Copy over the new transitions.\n Arrays.sort(newZone._indexToTimerPair);\n }\n\n private void copyRatesNew(Zone newZone, LpnTranList enabledTran, ContinuousRecordSet newAssignValues) {\n // Create new rate zero member variable.\n newZone._rateZeroContinuous = new DualHashMap();\n // First get the total number of non-zero rate continuous variables that\n // are present in the old zone.\n int totalContinuous = 0;\n for (int i = 0; i < _lpnList.length; i++) {\n totalContinuous += _lpnList[i].getTotalNumberOfContVars();\n }\n int numberNonZero = totalContinuous - _rateZeroContinuous.size();\n // The size is given by\n // total number of transitions\n // + number of non-zero rate continuous variables previously in the zone\n // + number of zero rate continuous variables that now have non-zero\n // - number of non-zero rate continuous variables that are now zero\n // + 1 for the zero timer.\n // TODO: Create an object that stores the records along with this information.\n int newNonZero = 0, newZero = 0;\n for (UpdateContinuous record : newAssignValues.keySet()) {\n if (record.newlyNonZero()) {\n newNonZero++;\n }\n if (record.newlyZero()) {\n newZero++;\n }\n }\n int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;\n // Create the timer array.\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n // Add in the zero timer.\n newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;\n int indexTimerCount = 1;\n // Sort the previous rate zero continuous variables into rate zero or non-zero.\n for (LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()) {\n // Cast the index.\n LPNContinuousPair ltContPair = ltTranPair.get_lcPair();\n // Check if the variable is a newly assigned value.\n UpdateContinuous assignedLtContPair = newAssignValues.get(ltContPair);\n if (assignedLtContPair != null) {\n if (assignedLtContPair.newlyNonZero()) {\n // Variable was zero and is now non-zero, so add to the the non-zero\n newZone._indexToTimerPair[indexTimerCount++] = assignedLtContPair.get_lcrPair().get_lcPair().clone();\n } else {\n // Variable was zero and is still zero, but an assignment has been\n // made. Simply add in the new assigned value.\n VariableRangePair vrp = this._rateZeroContinuous.get(ltTranPair);\n newZone._rateZeroContinuous.insert(assignedLtContPair.get_lcrPair(), new VariableRangePair(vrp.get_variable(), assignedLtContPair.get_Value()));\n }\n } else {\n newZone._rateZeroContinuous.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));\n }\n }\n // Sort the previous non-zero variables into the rate zero and non-zero.\n for (int i = 1; this._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];\n // Check if an assignment has been made.\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord != null) {\n if (updateRecord.is_newZero()) {\n // The continuous variable is now a rate zero variable.\n LPNContinuousPair ltCar = updateRecord.get_lcrPair().get_lcPair();\n Variable v = _lpnList[ltCar.get_lpnIndex()].getContVar(ltCar.get_ContinuousIndex());\n // Dewarp the upper and lower bounds.\n IntervalPair values = updateRecord.get_Value();\n int currentRate = getCurrentRate(ltCar);\n values.set_LowerBound(values.get_LowerBound() * currentRate);\n values.set_UpperBound(values.get_UpperBound() * currentRate);\n // Create a VariableRangePair.\n VariableRangePair vrp = new VariableRangePair(v, values);\n // Add the value to the map.\n newZone._rateZeroContinuous.insert(updateRecord.get_lcrPair(), vrp);\n } else {\n // This non-zero variable still has rate non-zero, but replace\n // with the newAssignValues since the rate may have changed.\n newZone._indexToTimerPair[indexTimerCount++] = updateRecord.get_lcrPair().get_lcPair();\n }\n } else {\n // The variable was non-zero and hasn't had an assignment.\n newZone._indexToTimerPair[indexTimerCount++] = this._indexToTimerPair[i].clone();\n }\n }\n // Copy over the new transitions.\n for (Transition t : enabledTran) {\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n newZone._indexToTimerPair[indexTimerCount++] = new LPNTransitionPair(lpnIndex, tranIndex);\n }\n Arrays.sort(newZone._indexToTimerPair);\n }\n\n private void advance() {\n for (int i = 0; i < dbmSize(); i++) {\n _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(i)] = getUpperBoundbydbmIndex(i);\n }\n }\n\n /**\n * Advances time. (This method should replace advance().)\n * @param localStates\n */\n @Override\n public void advance(State[] localStates) {\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n if (ltPair.equals(LPNTransitionPair.ZERO_TIMER_PAIR)) {\n continue;\n }\n // Get the new value.\n int newValue = 0;\n if (!(ltPair instanceof LPNContinuousPair)) {\n // If the pair is a timer, then simply get the stored largest value.\n int index = timerIndexToDBMIndex(ltPair);\n newValue = getUpperBoundbydbmIndex(index);\n } else {\n // If the pair is a continuous variable, then need to find the\n // possible largest bound governed by the inequalities.\n newValue = ContinuousUtilities.maxAdvance(this, ltPair, localStates);\n }\n // In either case (timer or continuous), set the upper bound portion\n // of the DBM to the new value.\n setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, newValue);\n }\n }\n\n /**\n * Copies in the new values needed to add a set of new times.\n * @param newZone\n * \t\t\tThe zone that the values are going to be copied into.\n * @param tempZone\n * \t\t\tThe zone to look up current values of timers.\n * @param newTimers\n * \t\t\tA collection of the new timers.\n * @param oldTimers\n * \t\t\tA collection of the older timers.\n * @param localStates\n * \t\t\tThe current state.\n */\n private void copyTransitions(Zone tempZone, Collection newTimers, Collection oldTimers, State[] localStates) {\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[j]);\n _matrix[dbmIndexToMatrixIndex(newIndexi)][dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n setDbmEntry(timerIndexToDBMIndex(timerNew), timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n setDbmEntry(timerIndexToDBMIndex(timerOld), timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n setLowerBoundByLPNTransitionPair(pair, lower);\n setUpperBoundByLPNTransitionPair(pair, upper);\n }\n }\n\n /**\n * This method sets all the rate to their lower bound.\n * Will not work quite right for continuous variables\n * with rates that include zero.\n */\n private void setAllToLowerBoundRate() {\n // Loop through the continuous variables.\n for (int i = 1; i < _indexToTimerPair.length && _indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair ltContPair = (LPNContinuousPair) _indexToTimerPair[i];\n // For this, recall that for a continuous variable that the lower bound\n // rate is stored in the zero column of the matrix.\n int lower = -1 * _matrix[dbmIndexToMatrixIndex(i)][0];\n int upper = _matrix[0][dbmIndexToMatrixIndex(i)];\n int newRate;\n /**\n * Suppose the range of rates is [a,b]. If a>=0, then we set the\n * rate to b. If b<=0, then we set the rate to a. Ohterwise,\n * a<0=0 or lower < 0 < upper we set the\n // rate to the upper bound.\n newRate = upper;\n }\n setCurrentRate(ltContPair, newRate);\n }\n }\n\n /**\n * Resets the rates of all continuous variables to be their\n * lower bounds.\n */\n @Override\n public Zone resetRates() {\n // Create the new zone.\n // // Copy the rate zero variables.\n // // Copy the LPNs over.\n // // Loop through the variables and save off those\n // // that are rate zero. Accumulate an array that\n // // indicates which are zero for faster\n // // copying. Save the number of continuous variables.\n // boolean[] rateZero = new boolean[this._indexToTimerPair.length]; // Is rate zero.\n // // The rate zero is in the range, so this will be\n // LPNContinuousPair lcPair =\n // // Save as a rate zero continuous variable.\n // VariableRangePair vcp =\n // // Update continuous variable counter.\n // // Save over the indexToTimer pairs.\n // // Ignore rate zero variables.\n // // If this is a continuous variable, set the rate to the lower bound.\n // // Calculate the size of the matrix and create it.\n // // Copy over the old matrix for all variables except\n // // the rate zero variables.\n // Warp\n Zone newZone = new Zone();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n /* \n\t\t * Collect the rate zero variables whose range of rates are not\n\t\t * identically zero. These will be moved out of the zone when\n\t\t * the rate is reset.\n\t\t * \n\t\t * Copy over the rate zero variables that remain rate zero.\n\t\t */\n newZone._rateZeroContinuous = new DualHashMap();\n HashSet> newlyNonZero = new HashSet>();\n for (Map.Entry variable : _rateZeroContinuous.entrySet()) {\n // Check for a single value which indicates that zero is\n // the only possible rate.\n if (variable.getKey().get_rateInterval().singleValue()) {\n // This variable only has zero as a rate so keep it\n // in the rate zero variables.\n newZone._rateZeroContinuous.insert(variable.getKey(), variable.getValue());\n } else {\n // This variable will need to be added to the zone.\n newlyNonZero.add(variable);\n }\n }\n /*\n\t\t * Calulate the size of the _indexToTimerPairs array and create\n\t\t * it.\n\t\t */\n int oldSize = this._indexToTimerPair.length;\n int newSize = oldSize + newlyNonZero.size();\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n /*\n\t\t * Copy over the old pairs and add the new ones.\n\t\t */\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();\n }\n for (Map.Entry variable : newlyNonZero) {\n newZone._indexToTimerPair[oldSize++] = variable.getKey().get_lcPair().clone();\n }\n Arrays.sort(newZone._indexToTimerPair);\n /*\n\t\t * Copy over the old matrix values and new constraints.\n\t\t */\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n for (int i = 0; i < this.dbmSize(); i++) {\n int newi = Arrays.binarySearch(newZone._indexToTimerPair, this._indexToTimerPair[i]);\n if (newi < 0) {\n System.err.println(\"In resetRates, old value was not found\" + \" in new value.\");\n continue;\n }\n // Copy upper and lower bounds for the variable.\n newZone._matrix[dbmIndexToMatrixIndex(newi)][0] = this._matrix[dbmIndexToMatrixIndex(i)][0];\n newZone._matrix[0][dbmIndexToMatrixIndex(newi)] = this._matrix[0][dbmIndexToMatrixIndex(i)];\n // Copy the DBM Entry\n for (int j = 0; j < this.dbmSize(); j++) {\n int newj = Arrays.binarySearch(newZone._indexToTimerPair, this._indexToTimerPair[j]);\n if (newj < 0) {\n System.err.println(\"In resetRates, old value was not\" + \" found in new value.\");\n continue;\n }\n newZone.setDbmEntry(newi, newj, this.getDbmEntry(i, j));\n }\n }\n for (Map.Entry variable : newlyNonZero) {\n LPNTransitionPair currentVariable = variable.getKey().get_lcPair();\n int currentIndex = Arrays.binarySearch(newZone._indexToTimerPair, currentVariable);\n IntervalPair rangeOfRates = variable.getKey().get_rateInterval();\n IntervalPair rangeOfValues = variable.getValue().get_range();\n /*\n\t\t\t * First set the range of rates, current rate, and the lower and upper\n\t\t\t * bounds for the newly added continuous variables.\n\t\t\t */\n newZone.setLowerBoundbydbmIndex(currentIndex, rangeOfRates.get_LowerBound());\n newZone.setUpperBoundbydbmIndex(currentIndex, rangeOfRates.get_UpperBound());\n newZone.setDbmEntry(currentIndex, 0, -1 * rangeOfValues.get_LowerBound());\n newZone.setDbmEntry(0, currentIndex, rangeOfValues.get_UpperBound());\n for (int j = 1; j < newZone.dbmSize(); j++) {\n if (currentIndex == j) {\n continue;\n }\n newZone.setDbmEntry(currentIndex, j, Zone.INFINITY);\n newZone.setDbmEntry(j, currentIndex, Zone.INFINITY);\n }\n }\n /*\n\t\t * Reset all the rates.\n\t\t */\n newZone.setAllToLowerBoundRate();\n newZone.recononicalize();\n newZone.dbmWarp(this);\n newZone.recononicalize();\n return newZone;\n }\n\n /**\n * Finds the maximum amount that time cam advance.\n * @return\n * \t\tvalue.\n * \t\tThe maximum amount that time can advance before a timer expires or an inequality changes\n */\n // * Several comments in this function may look like C code. That's because,\n // * well it is C code from atacs/src/lhpnrsg.c. In particular the\n // // Get the continuous variable in question.\n // // printf(\"Zone to check...\\n\");\n // // Get all the inequalities that reference the variable of interest.\n // // Update the inequality variable.\n // // /* Working on a > or >= ineq */\n // // Working on a > or >= ineq\n // // If the rate is positive.\n // // /* Working on a < or <= ineq */\n // // Working on a < or <= ineq\n // // Check if the value can be lowered.\n // //printf(\"Min leaving checkPreds for %s: %d\\n\",events[p]->event,min);\n /* (non-Javadoc)\n\t * @see java.lang.Object#clone()\n\t */\n @Override\n public Zone clone() {\n Zone clonedZone = new Zone();\n clonedZone._matrix = new int[this.matrixSize()][this.matrixSize()];\n for (int i = 0; i < this.matrixSize(); i++) {\n for (int j = 0; j < this.matrixSize(); j++) {\n clonedZone._matrix[i][j] = this._matrix[i][j];\n }\n }\n clonedZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n clonedZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();\n }\n clonedZone._hashCode = this._hashCode;\n clonedZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n clonedZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n return clonedZone;\n }\n\n /**\n * Restricts the lower bound of a timer.\n *\n * @param timer\n * \t\t\tThe timer to tighten the lower bound.\n */\n private void restrictTimer(int timer) {\n _matrix[dbmIndexToMatrixIndex(timer)][dbmIndexToMatrixIndex(0)] = getLowerBoundbydbmIndex(timer);\n }\n\n /**\n * Restricts the lower bound of a continuous variable. Also checks fixes\n * the upper bound to be at least as large if needed. This method\n * is usually used as a result of an event firing.\n * @param ltContPair\n * \t\tThe index of the continuous variable to restrict.\n * @param constant\n * \t\tThe constant value of the inequality event that is being used to update\n * \t\tthe variable indexed by ltContPair.\n */\n private boolean restrictContinuous(LPNContinuousPair ltContPair, int constant) {\n // It will be quicker to get the DBM index for the ltContPair one time.\n int variableIndex = timerIndexToDBMIndex(ltContPair);\n int zeroIndex = timerIndexToDBMIndex(LPNTransitionPair.ZERO_TIMER_PAIR);\n // Set the lower bound the variable (which is the DBM[variabl][0] entry.\n // Note : the lower bound in the zone is actually the negative of the lower\n // bound hence the -1 on the warpValue.\n setDbmEntry(variableIndex, zeroIndex, ContinuousUtilities.chkDiv(-1 * constant, ltContPair.getCurrentRate(), true));\n // Check if the upper bound needs to be advanced and advance it if necessary.\n if (getDbmEntry(zeroIndex, variableIndex) < ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true)) {\n // If the upper bound in the zones is less than the new restricting value, we\n // must advance it for the zone to remain consistent.\n setDbmEntry(zeroIndex, variableIndex, ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true));\n return true;\n }\n return false;\n }\n\n /**\n * Restricts the continuous variables in the zone according to the inequalities in a set of events.\n * @param eventSet\n * \t\t\tA set of inequality events. Does nothing if the event set does not contian inequalities.\n */\n private void restrictContinuous(EventSet eventSet) {\n // Check that the eventSet is a set of Inequality events.\n if (!eventSet.isInequalities()) {\n // If the eventSet is not a set of inequalities, do nothing.\n return;\n }\n HashSet adjustedColumns = new HashSet();\n boolean needsAdjusting = false;\n // Restrict the variables according to each of the inequalities in the eventSet.\n for (Event e : eventSet) {\n // Get the inequality.\n InequalityVariable iv = e.getInequalityVariable();\n // Extract the variable. I will assume the inequality only depends on a single\n Variable x = iv.getContVariables().get(0);\n // Extract the index.\n int lpnIndex = iv.get_lpn().getLpnIndex();\n // Extract the variable index.\n DualHashMap variableIndexMap = _lpnList[lpnIndex].getContinuousIndexMap();\n int variableIndex = variableIndexMap.getValue(x.getName());\n // Package it up for referencing.\n LPNContinuousPair ltContPair = new LPNContinuousPair(lpnIndex, variableIndex);\n // Need the current rate for the variable, grab the stored LPNContinuousPair.\n int zoneIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);\n if (zoneIndex > 0) {\n ltContPair = (LPNContinuousPair) _indexToTimerPair[zoneIndex];\n }\n // Perform the restricting.\n needsAdjusting = needsAdjusting | restrictContinuous(ltContPair, iv.getConstant());\n if (needsAdjusting) {\n adjustedColumns.add(ltContPair);\n }\n }\n // If one of the continuous variables has been moved forward, the other colmns\n // need to be adjusted to keep a consistent zone.\n if (needsAdjusting) {\n // At least one of the continuous variables has been moved forward,\n // so se need to ajust the bounds to keep a consistent zone.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltpair = _indexToTimerPair[i];\n if (adjustedColumns.contains(ltpair)) {\n // This continuous variables already had the upper bound\n continue;\n }\n // Add one to the upper bounds.\n setDbmEntry(0, i, getDbmEntry(0, i) + 1);\n }\n }\n }\n\n /**\n * Returns a zone that is the result from restricting the this zone according to a list of firing event inequalities.\n * @param eventSet\n * \t\tThe list of inequalities that are firing.\n * @return\n * \t\tThe new zone that is the result of restricting this zone according to the firing of the inequalities\n * \t\tin the eventSet.\n */\n @Override\n public Zone getContinuousRestrictedZone(EventSet eventSet, State[] localStates) {\n // Make a new copy of the zone.\n Zone z = this.clone();\n if (eventSet == null) {\n return z;\n }\n z.restrictContinuous(eventSet);\n return z;\n }\n\n /**\n * The list of enabled timers.\n * @return\n * \t\tThe list of all timers that have reached their lower bounds.\n */\n @Override\n public List getEnabledTransitions() {\n ArrayList enabledTransitions = new ArrayList();\n // Check if the timer exceeds its lower bound staring with the first nonzero\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n enabledTransitions.add(_lpnList[_indexToTimerPair[i].get_lpnIndex()].getTransition(_indexToTimerPair[i].get_transitionIndex()));\n }\n }\n return enabledTransitions;\n }\n\n /**\n * Gives the list of enabled transitions associated with a particular LPN.\n * @param LpnIndex\n * \t\t\tThe Index of the LPN the Transitions are a part of.\n * @return\n * \t\t\tA List of the Transitions that are enabled in the LPN given by the index.\n */\n @Override\n public List getEnabledTransitions(int LpnIndex) {\n ArrayList enabledTransitions = new ArrayList();\n // Check if the timer exceeds its lower bound staring with the first nonzero\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n if (ltPair.get_lpnIndex() == LpnIndex) {\n enabledTransitions.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));\n }\n }\n }\n return enabledTransitions;\n }\n\n /**\n * Find the next possible events.\n *\n * @param LpnIndex\n * \t\tThe index of the LPN that is of interest.\n * @param localState\n * \t\tThe state associated with the LPN indexed by LpnIndex.\n * @return\n * \t\tLpnTranList is populated with a list of\n * \t\tEventSets pertaining to the LPN with index LpnIndex. An EventSet can\n * \t\teither contain a transition to\n * \t\tfire or set of inequalities to change sign.\n */\n @Override\n public LpnTranList getPossibleEvents(int LpnIndex, State localState) {\n LpnTranList result = new LpnTranList();\n // Look through the timers and continuous variables. For the timers\n // determine if they are ready to fire. For the continuous variables,\n // look up the associated inequalities and see if any of them are ready\n // to fire.\n // We do not need to consider the zero timer, so start the\n // for loop at i=1 and not i=0.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // The enabled events are grouped with the LPN that they affect. So if\n // this pair does not belong to the current LPN under consideration, skip\n // processing it.\n if (ltPair.get_lpnIndex() != LpnIndex) {\n continue;\n }\n // If the index refers to a timer (and not a continuous variable) and has exceeded its lower bound,\n // then add the transition.\n if (!(ltPair instanceof LPNContinuousPair)) {\n // The index refers to a timer. Now check if time has advanced\n // far enough for the transition to fire.\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n Event e = new Event(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));\n result = addSetItem(this, result, e, localState);\n }\n } else {\n // The index refers to a continuous variable.\n // First check for a rate change event.\n LPNContinuousPair ltContPair = ((LPNContinuousPair) ltPair).clone();\n IntervalPair ratePair = getRateBounds(ltContPair);\n // // The rate represents a range of rates and no rate change\n // // event has occured.\n // // The rate contians zero, so we need to add two rate\n // // events: one for the lower bound and one for the upper\n // // Create the events.\n // // Add them to the result set.\n result = createRateEvents(this, ltContPair, ratePair, result, localState);\n // Check all the inequalities for inclusion.\n Variable contVar = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());\n if (contVar.getInequalities() != null) {\n for (InequalityVariable iv : contVar.getInequalities()) {\n // Check if the inequality can change.\n if (ContinuousUtilities.inequalityCanChange(this, iv, localState)) {\n result = addSetItem(this, result, new Event(iv), localState);\n }\n }\n }\n }\n }\n // Check the rate zero variables for possible rate change events.\n for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()) {\n // Get the reference object:\n LPNContinuousPair ltContPair = lcrPair.get_lcPair();\n // Extract the range of rates.\n IntervalPair ratePair = lcrPair.get_rateInterval();\n result = createRateEvents(this, ltContPair, ratePair, result, localState);\n }\n return result;\n }\n\n public static LpnTranList createRateEvents(Equivalence Z, LPNContinuousPair ltContPair, IntervalPair ratePair, LpnTranList result, State localState) {\n // // The rate represents a range of rates and no rate change\n // // event has occured.\n // // The rate contians zero, so we need to add two rate\n // // events: one for the lower bound and one for the upper\n // // Create the events.\n // // Add them to the result set.\n /*\n\t\t * Let [a,b] be the current range of rates for a given variable.\n\t\t * If a>=0, then we set the rate to b originally.\n\t\t * So if the current rate is b, then we have a rate change event to a.\n\t\t * \n\t\t * If b<=0, then we set the rate to a originially.\n\t\t * So if the current rate is a, then we have a rate change event to b.\n\t\t * \n\t\t * The final case to consider is when a < 0 and b > 0. If the current\n\t\t * rate is b, we allow rate changes to either a or 0. If the current\n\t\t * rate is a, we allow a rate change to zero.\n\t\t */\n if (ratePair.singleValue()) {\n // Rates that are not a range do not generate rate change events.\n return result;\n }\n ltContPair = ltContPair.clone();\n if (ratePair.get_LowerBound() >= 0) {\n if (ltContPair.getCurrentRate() == ratePair.get_UpperBound()) {\n ltContPair.setCurrentRate(ratePair.get_LowerBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n } else if (ratePair.get_UpperBound() <= 0) {\n if (ltContPair.getCurrentRate() == ratePair.get_LowerBound()) {\n ltContPair.setCurrentRate(ratePair.get_UpperBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n } else {\n if (ltContPair.getCurrentRate() == ratePair.get_UpperBound()) {\n // No rate change events have ocurred. So we allow one for zero\n // and the lower bounds rate.\n LPNContinuousPair ltContPairOther = ltContPair.clone();\n ltContPair.setCurrentRate(0);\n ltContPairOther.setCurrentRate(ratePair.get_LowerBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n result = addSetItem(Z, result, new Event(ltContPairOther), localState);\n } else if (ltContPair.getCurrentRate() == ratePair.get_LowerBound()) {\n // The rate has change to the lower bound. Allow one rate\n // change to zero.\n ltContPair.setCurrentRate(0);\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n }\n return result;\n }\n\n /**\n * Adds or removes items as appropriate to update the current\n * list of possible events. Note the type LpnTranList extends\n * LinkedList. The type EventSet extends transition\n * specifically so that objects of EventSet type can be place in\n * this list.\n * @param EventList\n * \t\t\tThe list of possible events.\n */\n public static LpnTranList addSetItem(Equivalence Z, LpnTranList E, Event e, State s) {\n // void lhpnAddSetItem(eventSets &E,lhpnEventADT e,ineqList &ineqL,lhpnZoneADT z,\n // lhpnStateADT cur_state)\n // Note the LPNTranList plays the role of the eventSets.\n int rv1l = 0, rv1u = 0, rv2l = 0, rv2u = 0, iZ, jZ;\n // printf(\"Event sets entering:\\n\");\n // Create the new LpnTranlist for holding the events.\n EventSet eSet = new EventSet();\n LpnTranList newE = new LpnTranList();\n boolean done = false;\n boolean possible = true;\n if (e.isRate()) {\n eSet.add(e);\n // I believe that I should actually copy over the old list\n // and then add the new event set.\n newE = E.copy();\n newE.addLast(eSet);\n // The previous two commands act to pass the changes of E\n // back out of the functions. So returning the new object\n // is suficient.\n // printf(\"Event sets leaving:\\n\");\n return newE;\n }\n if (e.isInequality()) {\n // Is this necessary, or even correct to update the inequalities.\n // System.out.println(\"Note the inequality is not being updated before in addSetItem\");\n // In this case the Event e represents an inequality.\n InequalityVariable ineq = e.getInequalityVariable();\n // Need to extract the rate.\n // To do this, I'll create the indexing object.\n Variable v = ineq.getContVariables().get(0);\n // Find the LPN.\n int lpnIndex = ineq.get_lpn().getLpnIndex();\n int varIndex = Z.getVarIndex(lpnIndex, v.getName());\n // Package it all up.\n // LPNTransitionPair ltPair =\n // Note : setting the rate is not necessary since\n // this is only being used as aan index.\n // LPNContinuousPair ltPair =\n LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);\n rv2l = ContinuousUtilities.chkDiv(-1 * ineq.getConstant(), Z.getCurrentRate(ltPair), true);\n rv2u = ContinuousUtilities.chkDiv(ineq.getConstant(), Z.getCurrentRate(ltPair), true);\n iZ = Z.getIndexByTransitionPair(ltPair);\n } else {\n // In this case, the event is a transition.\n Transition t = e.getTransition();\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n // Package the results.\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);\n iZ = Z.getIndexByTransitionPair(ltPair);\n }\n // Recall that E contains the events sets which are inherited from the Transition class\n // so they can be placed in an LpnTranList. So consider each event set.\n for (Transition es : E) {\n if (!(es instanceof EventSet)) {\n // This collection should contain event sets, not transitions.\n throw new IllegalArgumentException(\"The eventSet was a Transition object not an EventSet object.\");\n }\n EventSet eventSet = (EventSet) es;\n if (done) {\n // Copy any remaining sets into newE.\n newE.add(eventSet.clone());\n break;\n }\n EventSet workSet = eventSet.clone();\n // Get an iterator for the elements in the workset.\n for (Event oldEvent : eventSet) {\n // For matching code with atacs, note that oldEvent is 'j'.\n if (oldEvent.isRate()) {\n continue;\n }\n if (oldEvent.isInequality()) {\n // Again, is it necessary to do an update here?\n // System.out.println(\"Note the inequality is not being updated before in addSetItem\");\n // In this case the Event oldEvent represents an inequality.\n InequalityVariable ineq = oldEvent.getInequalityVariable();\n // Extract variable.\n Variable v = ineq.getContVariables().get(0);\n // Find the LPN.\n int lpnIndex = ineq.get_lpn().getLpnIndex();\n int varIndex = Z.getVarIndex(lpnIndex, v.getName());\n // Package it all up.\n // LPNTransitionPair ltPair =\n // Note : setting the rate is not necessary since this is\n // only being used as an index.\n // LPNContinuousPair ltPair =\n LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);\n rv1l = ContinuousUtilities.chkDiv(-1 * oldEvent.getInequalityVariable().getConstant(), Z.getCurrentRate(ltPair), true);\n rv1u = ContinuousUtilities.chkDiv(oldEvent.getInequalityVariable().getConstant(), Z.getCurrentRate(ltPair), true);\n jZ = Z.getIndexByTransitionPair(ltPair);\n } else {\n // In this case, the event is a transition.\n Transition t = oldEvent.getTransition();\n // Create the indexing object. (See the Abstraction Function protion at the\n // top of the class for more details.)\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n // Package the results.\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);\n jZ = Z.getIndexByTransitionPair(ltPair);\n }\n // /* Both actions are predicate changes */\n // Both actions are predicate changes.\n if (e.isInequality() && oldEvent.isInequality()) {\n // /* Both predicates are on the same variable */\n // Extract the variable lists.\n ArrayList newList = e.getInequalityVariable().getContVariables();\n ArrayList oldList = oldEvent.getInequalityVariable().getContVariables();\n // Issue a warning if one of the lists has more than a single\n if (newList.size() > 1 && oldList.size() > 1) {\n System.err.println(\"Warning: One of the inequalities \" + e + \" \" + oldEvent + \" refers to more than one variable\");\n }\n // Both inequalities are on the same variables.\n if (newList.get(0).equals(oldList.get(0))) {\n if (rv1l > rv2l) {\n possible = false;\n } else // printf(\"Adding to erase list: \\n\");\n if (rv2l > rv1l) {\n workSet.remove(oldEvent);\n } else // printf(\"Adding to erase list: \\n\");\n if (rv1u > rv2u) {\n workSet.remove(oldEvent);\n } else {\n workSet.add(e);\n done = true;\n }\n } else // /* Predicates are on different variables */\n // Inequalities are on different variables.\n {\n // TODO : Check that the indecies must be reversed. I believe\n // they do since I think my representation is the transpose\n // of atacs. This will affect all the following statements.\n if (rv1l > rv2l + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else // printf(\"Adding to erase list: \");\n if (rv2l > rv1l + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n } else // printf(\"Adding to erase list: \\n\");\n if (rv1u > Z.getUpperBoundTrue(iZ) + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n } else if (rv2u > Z.getUpperBoundTrue(jZ) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else if (rv1l == rv2l + Z.getDbmEntry(jZ, iZ) && rv2l == rv1l + Z.getDbmEntry(iZ, jZ) && rv1u == rv2u + Z.getDbmEntry(iZ, jZ) && rv2u == rv1u + Z.getDbmEntry(jZ, iZ)) {\n workSet.add(e);\n }\n }\n } else // /* New action is predicate change, old is transition firing (case 3) */\n // New action is an inequality and the old even tis a transition (case 3).\n if (e.isInequality() && oldEvent.isTransition()) {\n // printf(\"Adding to erase list: \\n\");\n if (rv2l > -1 * Z.getLowerBoundbyTransition(e.getTransition()) + Z.getDbmEntry(iZ, jZ)) {\n // Probably can change this to refer directly to the zone.\n workSet.remove(oldEvent);\n } else if (rv2u > Z.getUpperBoundTrue(jZ) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n }\n } else // /* TODO: One more ugly case, is it needed? */\n // /* New action is transition firing, old is predicate change (case 4) */\n // New event is a transition firing, old event is an inequality change (case 4).\n if (e.isTransition() && oldEvent.isInequality()) {\n if (rv1l > (-1) * Z.getLowerBoundbyTransition(e.getTransition()) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else // printf(\"Adding to erase list: \\n\");\n // Real one: fix the getting of the upper and lower bounds. Done\n if (rv1u > Z.getUpperBoundTrue(iZ) + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n }\n // /* TODO: one more ugly case, is it needed? */\n // I guess this one wasn't needed since it is not found in atacs.\n }\n }\n if (!(workSet.isEmpty())) {\n newE.add(workSet);\n }\n }\n // This part of the code is essentially copying the all the old event set into the new event set.\n // There might be a way around doing this by working directly on the set to begin with.\n // Moved to being done at the begining of the previous block.\n // // This collection should contain event sets, not transitions.\n // throw new IllegalArgumentException(\"The eventSet was a Transition object not an EventSet object.\");\n if (!done && possible) {\n eSet.add(e);\n newE.add(eSet);\n }\n E = newE;\n // printf(\"Event sets leaving:\\n\");\n return E;\n }\n\n @Override\n public int getVarIndex(int lpnIndex, String name) {\n return _lpnList[lpnIndex].getContinuousIndexMap().getValue(name);\n }\n\n /**\n * Adds a set item and explicitly sets a flag to remove the next set item\n * upon firing.\n * @param E\n * The list of current event sets.\n * @param e\n * The event to add.\n * @param s\n * The current state.\n * @param removeNext\n * True if afer firing this event, the next event should be removed from the\n * queue.\n * @return\n * The new event set.\n */\n // public static LpnTranList addSetItem(LpnTranList E, Event e, State s,\n /**\n * Updates the continuous variables that are set by firing a transition.\n * @param firedTran\n * \t\tThe transition that fired.\n * @param s\n * \t\tThe current (local) state.\n */\n public void updateContinuousAssignment(Transition firedTran, State s) {\n // Get the LPN.\n LPN lpn = _lpnList[firedTran.getLpn().getLpnIndex()];\n // Get the current values of the (local) state.\n HashMap currentValues = lpn.getAllVarsWithValuesAsString(s.getVariableVector());\n // Get all the continuous variable assignments.\n HashMap assignTrees = firedTran.getContAssignTrees();\n for (String contVar : assignTrees.keySet()) {\n // Get the bounds to assign the continuous variables.\n IntervalPair assignment = assignTrees.get(contVar).evaluateExprBound(currentValues, this, null);\n // Make the assignment.\n setContinuousBounds(contVar, lpn, assignment);\n }\n }\n\n /**\n * Updates the continuous variables according to the given values.\n * @param newContValues\n * \t\tThe new values of the continuous variables.\n */\n public void updateContinuousAssignment(ContinuousRecordSet newAssignValues) {\n /*\n\t\t * In dealing with the rates and continuous variables, there are four cases to consider. These cases\n\t\t * depend on whether the the old value of the 'current rate' is zero or non-zero and whether the\n\t\t * new value of the 'current rate' is zero or non-zero. \n\t\t * 0. old rate is zero, new rate is zero.\n\t\t * \t\tLookup the zero rate in the _rateZeroContinuous and add any new continuous assignments.\n\t\t * 1. old rate is zero, new rate is non-zero.\n\t\t * \t\tRemove the rate from the _rateZeroContinuous and add the zone.\n\t\t * 2. old rate is non-zero, new rate is zero.\n\t\t * \t\tAdd the variable with its upper and lower bounds to _rateZeroContinuous.\n\t\t * 3. old rate is non-zero, new rate is non-zero.\n\t\t * \t\tGet the LPNContinuousPair from the _indexToTimerPair and change the value.\n\t\t * \n\t\t * Note: If an assignment is made to the variable, then it should be considered as a\n\t\t * new variable.\n\t\t */\n // The updating of the rate-zero continuous variables is taken care of\n // by the copyRates. So just need to update the values in the zone.\n // This amounts to copying over the values from the old zone for\n // continuous variables that haven't changed and copying in\n // // Set the lower bound.\n // // Set the upper bound.\n // // Set the rate.\n // // Set the lower bound.\n // // Set the upper bound.\n // // Set the current rate.\n // // Set the upper and lower bounds for the rates.\n }\n\n /* (non-Javadoc)\n\t * @see verification.timed_state_exploration.zone.Zone#getLexicon()\n\t */\n /**\n * Gives an array that maps the index of a timer in the DBM to the timer's index.\n * @return\n * \t\tThe array that maps the index of a timer in the DBM to the timer's index.\n */\n /**\n * Calculates a warping value needed to warp a Zone. When a zone is being warped the form\n * r1*z2 - r1*z1 + r2*z1 becomes important in finding the new values of the zone. For example,\n *\n * @param z1\n * \t\tUpper bound or negative lower bound.\n * @param z2\n * \t\tRelative value.\n * @param r1\n * \t\tFirst ratio.\n * @param r2\n * \t\tSecond ratio.\n * @return\n * \t\tr1*z2 - r1*z1 + r2*z1\n */\n ", "post_mask_code": "{\n /*\n\t\t * See \"Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets\"\n\t\t * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda\n\t\t * Section III.C for details on how this function is used and where it comes\n\t\t * from.\n\t\t */\n return r1 * z2 - r1 * z1 + r2 * z1;\n }\n\n /**\n * Warps this Zone with the aid of rate information from the previous Zone.\n *\n * @param oldZone\n * \t\tThe previous Zone.\n * @return\n * \t\tThe warped Zone.\n */\n @Override\n public void dbmWarp(Equivalence oldE) {\n Zone oldZone = (Zone) oldE;\n /*\n\t\t * See \"Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets\"\n\t\t * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda\n\t\t * Section III.C for details on how this function is used and where it comes\n\t\t * from.\n\t\t */\n // /* TODO: This appears to NOT work when INFIN is in the bounds?\n // Should I have to worry about this case? */\n // According to atacs comments, this appears to NOT work when\n // INFIN is in the bounds.\n // This portion of the code handles the warping of the relative\n // parts of the zone.\n for (int i = 1; i < dbmSize(); i++) {\n for (int j = i + 1; j < dbmSize(); j++) {\n double iVal, jVal, iWarp, jWarp, iXDot, jXDot;\n // Note : the iVal and the jVal correspond to the\n // alpha and beta describe in Scott Little's thesis.\n // /* deal w/ the fact that we might have continuous and discrete\n // Do some warping when dealing with the continuous variables.\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n // Calcualte the alpha value.\n iVal = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[i]) / (double) this.getCurrentRate(_indexToTimerPair[i])));\n // The old rate the zone was warped by.\n iWarp = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[i])));\n // The current rate rate of this continuous variable.\n iXDot = Math.floor(Math.abs((double) this.getCurrentRate(_indexToTimerPair[i])));\n // I'm not going to do any warping when the previous rate\n // is zero. This statement is a break to go to next i value\n // and not the next j.\n if (iWarp == 0) {\n break;\n }\n } else {\n // The current variable is a timer, so the new rate and old rate\n // are both 1. Hence we have\n iVal = 1.0;\n iWarp = 1.0;\n iXDot = 1.0;\n }\n // Do some warping of the second variable if it is a continuous variable.\n if (_indexToTimerPair[j] instanceof LPNContinuousPair) {\n // Calcualte the alpha value.\n jVal = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[j]) / (double) this.getCurrentRate(_indexToTimerPair[j])));\n // The old rate the zone was warped by.\n jWarp = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[j])));\n // The current rate of this continuous variable.\n jXDot = Math.floor(Math.abs((double) this.getCurrentRate(_indexToTimerPair[j])));\n // I'm not going to do any warping when the previous rate is\n if (jWarp == 0) {\n continue;\n }\n } else {\n // The current variable is a timer, so the new rate and old rate\n // are both 1. Hence we have\n jVal = 1.0;\n jWarp = 1.0;\n jXDot = 1.0;\n }\n // The zone is warped differently depending on which of rate is\n // larger. See Scott Little's Thesis for more details.\n if (iWarp * jXDot > jWarp * iXDot) {\n setDbmEntry(j, i, (int) Math.ceil(((jWarp * getDbmEntry(j, i)) / jXDot) + ((-1 * jWarp * getDbmEntry(0, i) / jXDot)) + ((iWarp * getDbmEntry(0, i) / iXDot))));\n setDbmEntry(i, j, (int) Math.ceil(((jWarp * getDbmEntry(i, j)) / jXDot) + ((-1 * jWarp * getDbmEntry(i, 0) / jXDot)) + ((iWarp * getDbmEntry(i, 0) / iXDot))));\n } else {\n setDbmEntry(i, j, (int) Math.ceil(((iWarp * getDbmEntry(i, j)) / iXDot) + ((-1 * iWarp * getDbmEntry(0, j) / iXDot)) + ((jWarp * getDbmEntry(0, j) / jXDot))));\n setDbmEntry(j, i, (int) Math.ceil(((iWarp * getDbmEntry(j, i)) / iXDot) + ((-1 * iWarp * getDbmEntry(j, 0) / iXDot)) + ((jWarp * getDbmEntry(j, 0) / jXDot))));\n }\n }\n }\n // printf(\"After fixing up initial warp conditions.\\n\");\n // Handle the warping of the bounds.\n for (int i = 1; i < dbmSize(); i++) {\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n if (Math.abs(getDbmEntry(i, 0)) != INFINITY) {\n if (oldZone.getCurrentRate(_indexToTimerPair[i]) == 0) {\n // If the older rate was zero, then we just need to\n // divide by the new rate.\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(getDbmEntry(i, 0), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n } else {\n // Undo the old warping and introduce the new warping.\n // If the bound is infinite, then division does nothing.\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i])) * getDbmEntry(i, 0), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n }\n }\n if (Math.abs(getDbmEntry(0, i)) != INFINITY) {\n if (oldZone.getCurrentRate(_indexToTimerPair[i]) == 0) {\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(getDbmEntry(0, i), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n } else {\n // Undo the old warping and introduce the new warping.\n // If the bound is inifite, then division does nothing.\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i])) * getDbmEntry(0, i), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n }\n }\n }\n }\n // printf(\"After fixing up places.\\n\");\n for (int i = 1; i < dbmSize(); i++) {\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n // /* TBD: If i & j are both changing direction do we need to\n // remove the warp info? */\n // Handle the case when the warping takes us into negative space.\n if ((double) oldZone.getCurrentRate(_indexToTimerPair[i]) / (double) this.getCurrentRate(_indexToTimerPair[i]) < 0.0) {\n /* We are warping into the negative space, so swap the upper and \n\t\t\t\t\t * lower bounds.\n\t\t\t\t\t */\n int temp = getDbmEntry(i, 0);\n setDbmEntry(i, 0, getDbmEntry(0, i));\n setDbmEntry(0, i, temp);\n // Set the relationships to Infinity since nothing else is known.\n for (int j = 1; j < dbmSize(); j++) {\n if (i != j) {\n setDbmEntry(i, j, INFINITY);\n setDbmEntry(j, i, INFINITY);\n }\n }\n }\n }\n }\n // printf(\"After handling negative warps.\\n\");\n /* Do the nature of how I store things, I do not think I need to do\n\t\t\t * this portion.\n\t\t\t */\n }\n\n /**\n * The DiagonalNonZeroException extends the java.lang.RuntimerExpcetion.\n * The intention is for this exception to be thrown is a Zone has a non zero\n * entry appear on the diagonal.\n *\n * @author Andrew N. Fisher\n */\n public class DiagonalNonZeroException extends java.lang.RuntimeException {\n\n private static final long serialVersionUID = -3857736741611605411L;\n\n /**\n * Creates a DiagonalNonZeroException.\n * @param Message\n * \t\t\tThe message to be displayed when the exception is thrown.\n */\n public DiagonalNonZeroException(String Message) {\n super(Message);\n }\n }\n\n /**\n * This exception is thrown when trying to merge two zones whose corresponding timers\n * do not agree.\n * @author Andrew N. Fisher\n */\n // // TODO : Check if this class can be removed.\n // * Generated serialVersionUID\n /**\n * Clears out the lexicon.\n */\n public static IntervalPair parseRate(String rate) {\n String rateNoSpaces = rate.trim();\n // First check if the string is a single number.\n // // The string is a number, so set the upper and lower bounds equal.\n // First check for a comma (representing an interval input).\n int commaIndex = rateNoSpaces.indexOf(\",\");\n if (commaIndex < 0) {\n // Assume that the string is a constant. A NumberFormatException\n // will be thrown otherwise.\n int i = Integer.parseInt(rate);\n return new IntervalPair(i, i);\n }\n String lowerString = rateNoSpaces.substring(1, commaIndex).trim();\n String upperString = rateNoSpaces.substring(commaIndex + 1, rateNoSpaces.length() - 1).trim();\n return new IntervalPair(Integer.parseInt(lowerString), Integer.parseInt(upperString));\n }\n\n /**\n * Get the list of LhpnFile objects that this Zone depends on.\n * @return\n * \t\tThe lits of LhpnFile objects that this Zone depends on.\n */\n @Override\n public LPN[] get_lpnList() {\n return _lpnList;\n }\n\n /**\n * Performs a division of two integers and either takes the ceiling or the floor. Note :\n * The integers are converted to doubles for the division so the choice of ceiling or floor is\n * meaningful.\n * @param top\n * \t\tThe numerator.\n * @param bottom\n * \t\tThe denominator.\n * @param ceil\n * \t\tTrue indicates return the ceiling and false indicates return the floor.\n * @return\n * \t\tReturns the ceiling of top/bottom if ceil is true and the floor of top/bottom otherwise.\n */\n // * This method was taken from atacs/src/hpnrsg.c\n // System.out.println(\"Warning: Divided by zero.\");\n /**\n * Returns the current rate of the variable.\n * @param contVar\n * \t\tThe LPNTransitionPair referring to a continuous variable.\n * @return\n * \t\tThe current rate of the continuous variable refenced by the LPNTransitionPair.\n * @throws IllegalArgumentException\n * \t\tIf the LPNTransitionPair is not an instance of an LPNContinuousPair.\n */\n @Override\n public int getCurrentRate(LPNTransitionPair contVar) {\n if (!(contVar instanceof LPNContinuousPair)) {\n // The LPNTransitionsPair does not refer to a continuous variable, so yell.\n throw new IllegalArgumentException(\"Zone.getCurrentRate was called\" + \" on an LPNTransitionPair that was not an LPNContinuousPair.\");\n }\n LPNContinuousPair cV = (LPNContinuousPair) contVar;\n // Search for the pair in the zone.\n int index = Arrays.binarySearch(_indexToTimerPair, cV);\n if (index > 0) {\n // The continuous variable was found amongst the non zero rate continuous variables.\n // Grab that indexing object instead since it has the rate.\n cV = (LPNContinuousPair) _indexToTimerPair[index];\n return cV.getCurrentRate();\n }\n // Since the variable was not found in the non-zero rate continuous\n // variables, assume the rate is zero.\n return 0;\n }\n\n /**\n * Sets the current rate for a continuous variable. It sets the rate regardless of\n * whether the variable is in the rate zero portion of the Zone or not. But it\n * does not move variables in and out of the zone.\n * @param contVar\n * \t\tThe index of the variable whose rate is going to be set.\n * @param currentRate\n * \t\tThe value of the rate.\n */\n @Override\n public void setCurrentRate(LPNTransitionPair contVar, int currentRate) {\n if (!(contVar instanceof LPNContinuousPair)) {\n // The LPNTransitionsPair does not refer to a continuous variable, so yell.\n throw new IllegalArgumentException(\"Zone.getCurrentRate was called\" + \" on an LPNTransitionPair that was not an LPNContinuousPair.\");\n }\n LPNContinuousPair cV = (LPNContinuousPair) contVar;\n // Check for the current variable in the rate zero variables.\n VariableRangePair variableRange = _rateZeroContinuous.getValue(new LPNContAndRate(cV, new IntervalPair(0, 0)));\n if (variableRange != null) {\n LPNContinuousPair lcPair = _rateZeroContinuous.getKey(variableRange).get_lcPair();\n lcPair.setCurrentRate(currentRate);\n return;\n }\n // Check for the current variable in the Zone variables.\n int index = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (index >= 0) {\n // The variable was found, set the rate.\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[index];\n lcPair.setCurrentRate(currentRate);\n }\n }\n\n /**\n * Adds a transition to a zone.\n * @param newTransitions\n * \t\t\tThe newly enabled transitions.\n * @return\n * \t\t\tThe result of adding the transition.\n */\n @Override\n public Zone addTransition(HashSet newTransitions, State[] localStates) {\n /*\n\t\t * The zone will remain the same for all the continuous variables.\n\t\t * The only thing that will change is a new transition will be added into the transitions.\n\t\t */\n // Create a Zone to alter.\n Zone newZone = new Zone();\n // Create a copy of the LPN list.\n newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n // Copy the rate zero continuous variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Create a copy of the current indexing pairs.\n newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + newTransitions.size()];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = _indexToTimerPair[i];\n }\n // Add the new transitions to the _indexToTimerPair list.\n // // Set up the index for the newTransitions list.\n int i = _indexToTimerPair.length;\n for (LPNTransitionPair ltPair : newTransitions) {\n newZone._indexToTimerPair[i++] = ltPair;\n }\n // Sort the _indexToTimerPair list.\n Arrays.sort(newZone._indexToTimerPair);\n // Create matrix.\n newZone._matrix = new int[newZone._indexToTimerPair.length + 1][newZone._indexToTimerPair.length + 1];\n // Convert the current transitions to a collection of transitions.\n HashSet oldTransitionSet = new HashSet();\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n oldTransitionSet.add(ltPair);\n }\n // Copy in the new transitions.\n newZone.copyTransitions(this, newTransitions, oldTransitionSet, localStates);\n return newZone;\n }\n\n /**\n * This method creates a zone identical to the current zone except all the current rates are turned to 1.\n * This is to provide a previous zone to the initial zone for warping.\n * @return\n * \t\tA zone identical to this zone with all rates set to 1.\n */\n private Zone beforeInitialZone() {\n Zone z = this.clone();\n for (int i = 1; i < z._indexToTimerPair.length; i++) {\n if (!(z._indexToTimerPair[i] instanceof LPNContinuousPair)) {\n break;\n }\n LPNContinuousPair lcPair = (LPNContinuousPair) z._indexToTimerPair[i];\n lcPair.setCurrentRate(1);\n }\n return z;\n }\n\n /**\n * Add a rate zero variable to the DBM portion of the zone. This method\n * is intended as an aid for when a rate zero variable gets assign a\n * non-zero rate.\n * @param ltContPair The continuous variable to move from the rate zero\n * variables.\n * @return The resulting Zone.\n */\n @Override\n public Zone moveOldRateZero(LPNContinuousPair ltContPair) {\n // Create a Zone to alter.\n Zone newZone = new Zone();\n // Create a copy of the LPN list.\n newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n // Copy the rate zero continuous variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Extract the continuous variable from the rate zero variables.\n LPNContAndRate rateZero = new LPNContAndRate(ltContPair, new IntervalPair(0, 0));\n // This gets the values for the continuous variable.\n VariableRangePair vrp = newZone._rateZeroContinuous.get(rateZero);\n IntervalPair values = vrp.get_range();\n // This replaces the rateZero with the one stored in the _rateZeroContinuous.\n // The purpose of this is to obtain the stored range of rates.\n rateZero = newZone._rateZeroContinuous.getKey(vrp);\n // Get the range of rates.\n IntervalPair rangeOfRates = rateZero.get_rateInterval();\n // Remove the continuous variable.\n newZone._rateZeroContinuous.delete(rateZero);\n // Create a copy of the current indexing pairs.\n newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + 1];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = _indexToTimerPair[i];\n }\n // Add the continuous variable to the list of variables/transition in the DBM.\n int numOfTransitions = _indexToTimerPair.length;\n newZone._indexToTimerPair[numOfTransitions] = ltContPair;\n // Sort the _indexToTimerPair list.\n Arrays.sort(newZone._indexToTimerPair);\n // Create matrix.\n newZone._matrix = new int[newZone._indexToTimerPair.length + 1][newZone._indexToTimerPair.length + 1];\n // Convert the current transitions to a collection of transitions.\n HashSet oldTransitionSet = new HashSet();\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n oldTransitionSet.add(ltPair);\n }\n // Copy in the new transitions.\n newZone.copyTransitions(this, new HashSet(), oldTransitionSet, null);\n // Get the index for the variable.\n int index = Arrays.binarySearch(newZone._indexToTimerPair, ltContPair);\n // Copy in the upper and lower bound of the old rate zero variable.\n // Copy in the range of rates.\n newZone.setLowerBoundbydbmIndex(index, rangeOfRates.get_LowerBound());\n newZone.setUpperBoundbydbmIndex(index, rangeOfRates.get_UpperBound());\n if (ltContPair.getCurrentRate() > 0) {\n // Set the upper and lower bounds.\n newZone.setDbmEntry(0, index, ContinuousUtilities.chkDiv(values.get_UpperBound(), ltContPair.getCurrentRate(), true));\n newZone.setDbmEntry(index, 0, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), ltContPair.getCurrentRate(), true));\n } else {\n // Set the upper and lower bounds. Since the rate is zero\n // We swap the real upper and lower bounds.\n newZone.setDbmEntry(0, index, ContinuousUtilities.chkDiv(values.get_LowerBound(), ltContPair.getCurrentRate(), true));\n newZone.setDbmEntry(index, 0, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), ltContPair.getCurrentRate(), true));\n }\n // Set the DBM to having no relating information for how this\n // variables relates to the other variables.\n for (int i = 1; i < newZone._indexToTimerPair.length; i++) {\n if (i == index) {\n continue;\n }\n newZone.setDbmEntry(index, i, Zone.INFINITY);\n newZone.setDbmEntry(i, index, Zone.INFINITY);\n }\n newZone.recononicalize();\n return newZone;\n }\n\n /**\n * This method removes the variable from the DBM portion of the\n * zone and adds the variable to the rate-zero portion of the\n * zone. The purpose of this method is to handle when a non-zero\n * rate variable is assigned a zero rate.\n * @param firedRate The new assignment for the variable.\n * @return The resulting zone.\n */\n @Override\n public Zone saveOutZeroRate(LPNContinuousPair firedRate) {\n // Check if the variable is in the zone.\n // We assume that the rate is already zero in this case\n // since it must be in the rate zero variables if it exists.\n int index = Arrays.binarySearch(this._indexToTimerPair, firedRate);\n if (index < 0) {\n System.err.println(\"A variable is getting its rate set to zero\");\n System.err.println(\"when the rate is already zero.\");\n return this;\n }\n // Create new zone\n Zone newZone = new Zone();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n // Copy over the rate zero variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Get the range of rates and values.\n IntervalPair rangeOfRates = this.getRateBounds(firedRate);\n IntervalPair rangeOfValues = this.getContinuousBounds(firedRate);\n // Create the key and value pairs for the rate zero continuous variable.\n LPNContAndRate lcar = new LPNContAndRate(firedRate.clone(), rangeOfRates);\n VariableRangePair vrPair = new VariableRangePair(this._lpnList[firedRate.get_lpnIndex()].getContVar(firedRate.get_ContinuousIndex()), rangeOfValues);\n newZone._rateZeroContinuous.insert(lcar, vrPair);\n // Copy over the pairs, skipping the new rate zero.\n newZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length - 1];\n int offset = 0;\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n if (i == index) {\n offset++;\n }\n newZone._indexToTimerPair[i] = this._indexToTimerPair[i + offset].clone();\n }\n // Copy over the DBM\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n int offseti = 0;\n int offsetj = 0;\n for (int i = 0; i < newZone.matrixSize(); i++) {\n if (i == index + 1) {\n offseti++;\n }\n offsetj = 0;\n for (int j = 0; j < newZone.matrixSize(); j++) {\n if (j == index + 1) {\n offsetj++;\n }\n newZone._matrix[i][j] = this._matrix[i + offseti][j + offsetj];\n }\n }\n return newZone;\n }\n\n @Override\n public int getIndexByTransitionPair(LPNTransitionPair ltPair) {\n return Arrays.binarySearch(_indexToTimerPair, ltPair);\n }\n /**\n * Determines whether time has advanced far enough for an inequality to change\n * truth value.\n * @param ineq\n * \t\tThe inequality to test whether its truth value can change.\n * @param localState\n * \t\tThe state associated with the inequality.\n * @return\n * \t\tTrue if the inequality can change truth value, false otherwise.\n */\n // // Find the index of the continuous variable this inequality refers to.\n // // I'm assuming there is a single variable.\n // // Package up the information into a the index. Note the current rate doesn't matter.\n // // Get the current rate.\n // // Get the current value of the inequality. This requires looking into the current state.\n // // Get the Zone index of the variable.\n // //\t\tbool lhpnPredCanChange(ineqADT ineq,lhpnZoneADT z,lhpnRateADT r,\n // //warn(\"An inequality produced a place not in the zone.\");\n // // First check cases when the rate is negative.\n // //warn(\"An inequality produced a place not in the zone.\");\n}\n"} {"task_id": "Java_3034", "language": "Java", "task_type": "method_body", "source_file": "java/github/MyersResearchGroup/iBioSim/verification/src/main/java/edu/utah/ece/async/lema/verification/timed_state_exploration/zoneProject/Zone.java", "mask_start_position": 46997, "mask_end_position": 47293, "canonical_solution": "{\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * This file is part of iBioSim. Please visit \n * for the latest version of iBioSim.\n *\n * and also available online at .\n *\n * *****************************************************************************\n */\npackage edu.utah.ece.async.lema.verification.timed_state_exploration.zoneProject;\n\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport edu.utah.ece.async.lema.verification.lpn.ExprTree;\nimport edu.utah.ece.async.lema.verification.lpn.LPN;\nimport edu.utah.ece.async.lema.verification.lpn.Transition;\nimport edu.utah.ece.async.lema.verification.lpn.Variable;\nimport edu.utah.ece.async.lema.verification.platu.main.Options;\nimport edu.utah.ece.async.lema.verification.platu.platuLpn.DualHashMap;\nimport edu.utah.ece.async.lema.verification.platu.platuLpn.LpnTranList;\nimport edu.utah.ece.async.lema.verification.platu.stategraph.State;\nimport edu.utah.ece.async.lema.verification.timed_state_exploration.octagon.Equivalence;\n\n/**\n * This class is for storing and manipulating the delay information for transitions as well as\n * the values of continuous variables including rate their rates.\n * A Zone represents the non-zero continuous variables and the timers for the delay in a\n * Difference Bound Matrix (DBM)\n *\n * t0 c0 c1 t0 t1\n * t0 m00 m01 m02 m03 m04\n * c0 m10 m11 m12 m13 m14\n * c1 m20 m21 m22 m23 m24\n * t0 m30 m31 m32 m33 m34\n * t1 m40 m41 m42 m43 m44\n *\n * For the timers, tj - ti <= m(ti,tj) where m(ti,tj) represents the element of the matrix with\n * row ti and column tj. In particular, m(t0,ti) is an upper bound for ti and -m(ti,0) is a\n * lower bound for ti. The continuous variables are normalized to have rate one before being\n * placed in the matrix. Thus for a continuous variables ci with rate ri, the entry m(t0, ci) is\n * (upper bound)/ri where 'upper bound' is the upper bound for the continuous variable and\n * m(ci,t0) is -1*(lower bound)/ri where 'lower bound' is the lower bound of the continuous variable.\n * When the rate is negative, dividing out by the rate switches the inequalities. For example,\n * if ci is a continuous variable such that l < ci < u for some values l and u, then the normalized\n * ci (that is ci/ri) is satisfies u/ri < ci/r < l/ri. Hence the m(t0,ci) is (lower bound)/ri and\n * m(ci,0) is -1*(upper bound)/ri. The m(ci,cj) as well as m(ti,ci) and m(ci,ti) give the same kind\n * of relational information as with just timers, but with the normalized values of the continuous\n * variables. Note that a Zone with normalized continuous variables is referred to as being a 'warped'\n * zone.\n *\n * The rate zero continuous variables are also stored in a Zone object, but they are not present in\n * the zone. The Zone merely records the range of the continuous variable.\n *\n * The timers are referenced by the name of the transition that they are associated with and continuous\n * variables are referenced by their name as well. In addition for non-zero rate continuous variables and\n * the timers, several method will allow them to be referred by their index as a part of the (DMB). For\n * example, c0 in the above DBM example, has index 1.\n *\n * A third way that the timers and variables (both rate zero and rate non-zero) can be referred to by\n * an LPNTransitionPair object. These objects refer to a timer or continuous variable by providing the index\n * of the corresponding transition or the index of the continuous variable as a member of an LPN and the\n * index of that LPN. The LPNTransitionPair can be made more specific in the case of the continuous variables\n * by using an LPNContinuousPair. These objects also provide the rate of the variable. LPNTransitionPairs\n * can be used with continuous variables when they are only being used as an index only. If the rate is needed\n * for the method, then LPNContinuousPairs must be used.\n *\n * @author Andrew N. Fisher\n * @author Chris Myers\n * @author iBioSim Contributors \n * @version %I%\n */\npublic class Zone implements Equivalence {\n\n /*Abstraction Function : \n\t* The difference bound matrix is stored in the _matrix member field, along with \n\t* the upper and lower bounds of the timers and rates for continuous variables.\n\t* The upper and lower bounds are stored when the timer becomes enabled. The upper and\n\t* lower bounds of the rates are stored when the rate is assigned. The upper and lower \n\t* bounds are stored in the first row and first column of the _matrix member field.\n\t* The DBM occupies the rest of the array, that is, the sub-array formed by removing\n\t* the first column and first row.\n\t* For example, let t1 be a timer for a transition whose delay is between 2 and 3. Further\n\t* let c1 be a continuous variable with rate between 4 and 5. Then _matrix would look like\n\t* lb t0 c1 t1\n\t* ub x 0 5 3\n\t* t0 0 m m m\n\t* c1 -4 m m m\n\t* t1 -2 m m m\n\t* \n\t* with out the lb, ub, t0, t1, and c1.\n\t* \n\t* The x is does not represent anything and will most likely be zero. The upper and lower \n\t* bounds for the zero timer (which is always present) are always 0. The m's comprise \n\t* the DBM.\n\t* \n\t* For the most part, a timer or a continuous variable is referred to internally by an\n\t* LPNTransitionPair. An LPNTransitionPair combines the index of the transition (or\n\t* continuous variable) with the index of the LPN that the transition (or continuous \n\t* variables) is a member of. Both continuous variables and transitions can be referred\n\t* to by an LPNTransitionPair; however, it is better to use an LPNContinuousPair (which\n\t* is inherited from the LPNTransitionPair) to refer to continuous variables.\n\t* LPNContinuousPairs are used to distinguish continuous variables from transitions. They \n\t* also store the current rate of the continuous variable. \n\t* \n\t* The LPNTransitionPairs are stored in the _indexToTimerPair member field. The row/column\n\t* in the DBM for a transition is determined by the its position in this array. For example,\n\t* suppose a transition t has an LPNTransitionPair ltTranPair that is the third element of\n\t* the _indexToTimerPair. Then t will be the third column/row of the DBM.\n\t* \n\t* Continuous variables are handled slightly differently. The LPNContinuousPair for the \n\t* continuous variables with a non-zero rate are stored in the _indexToTimerPair just as \n\t* with the transitions. And just like with the transitions, the index in the DBM is\n\t* determined by the index of the LPNContinuousPair in the _indexToTimerPair. However,\n\t* rate zero continuous variables are stored in the _rateZeroContinuous member variable.\n\t* The _rateZerContinuous pairs an LPNContinuousPair with a VariableRangePair. The\n\t* VariableRangePair combines the variable with its upper and lower bound.\n\t* \n\t*/\n /* Representation invariant :\n\t* Zones are immutable.\n\t* Integer.MAX_VALUE is used to logically represent infinity.\n\t* The lb and ub values for a timer should be set when the timer is enabled.\n\t* A negative hash code indicates that the hash code has not been set.\n\t* The index of the timer in _indexToTimer is the index in the DBM and should contain\n\t* \tthe zeroth timer.\n\t* The array _indexToTimerPair should always be sorted.\n\t* The index of the LPN should match where it is in the _lpnList, that is, if lpn is\n\t* \tand LhpnFile object in _lpnList, then _lpnList[getLpnIndex()] == lpn.\n\t* The LPNTransitionPair in the _indexToTimer array should be an LPNContinuousPair\n\t* when it stores the index to a continuous variable. Testing that the index\n\t* is an LPNContinuousPair is used to determined if the indexing object points\n\t* to a continuous variable. Also the LPNContinuousPair keeps track of the current rate.\n\t* \n\t*/\n /*\n\t * Resource List :\n\t * TODO : Create a list reference where the algorithms can be found that this class\n\t * depends on.\n\t */\n public static final int INFINITY = Integer.MAX_VALUE;\n\n /* The lower and upper bounds of the times as well as the dbm. */\n private int[][] _matrix;\n\n /* Maps the index to the timer. The index is row/column of the DBM sub-matrix.\n\t * Logically the zero timer is given index -1.\n\t * */\n private LPNTransitionPair[] _indexToTimerPair;\n\n /* The hash code. */\n private int _hashCode;\n\n /* A lexicon between a transitions index and its name. */\n /* Set if a failure in the testSplit method has fired already. */\n /* Hack to pass a parameter to the equals method though a variable */\n /* Stores the continuous variables that have rate zero */\n DualHashMap _rateZeroContinuous;\n\n /* Records the largest zone that occurs. */\n public static int ZoneSize = 0;\n\n /* Write a log file */\n private static BufferedWriter _writeLogFile = null;\n\n /**\n * Returns the write log.\n * @return\n * \t\tThe _writeLogfile.\n */\n public static BufferedWriter get_writeLogFile() {\n return _writeLogFile;\n }\n\n /**\n * Sets the BufferedWriter.\n * @param writeLogFile\n */\n public static void set_writeLogFile(BufferedWriter writeLogFile) {\n _writeLogFile = writeLogFile;\n }\n\n /**\n * Sets the writeLogFile to null.\n */\n public static void reset_writeLogFile() {\n _writeLogFile = null;\n }\n\n private void checkZoneMaxSize() {\n if (dbmSize() > ZoneSize) {\n ZoneSize = dbmSize();\n }\n }\n\n private LPN[] _lpnList;\n\n /* \n\t * Turns on and off subsets for the zones.\n\t * True means subset will be considered.\n\t * False means subsets will not be considered.\n\t */\n private static boolean _subsetFlag = true;\n\n /* \n\t * Turns on and off supersets for zones.\n\t * True means that supersets will be considered.\n\t * False means that supersets will not be considered.\n\t */\n private static boolean _supersetFlag = true;\n\n /**\n * Gets the value of the subset flag.\n * @return\n * \t\tTrue if subsets are requested, false otherwise.\n */\n public static boolean getSubsetFlag() {\n return _subsetFlag;\n }\n\n /**\n * Sets the value of the subset flag.\n * @param useSubsets\n * \t\t\tThe value for the subset flag. Set to true if\n * \t\t\tsupersets are to be considered, false otherwise.\n */\n public static void setSubsetFlag(boolean useSubsets) {\n _subsetFlag = useSubsets;\n }\n\n /**\n * Gets the value of the superset flag.\n * @return\n * \t\tTrue if supersets are to be considered, false otherwise.\n */\n public static boolean getSupersetFlag() {\n return _supersetFlag;\n }\n\n /**\n * Sets the superset flag.\n * @param useSupersets\n * \t\tThe value of the superset flag. Set to true if\n * \t\tsupersets are to be considered, false otherwise.\n */\n public static void setSupersetFlag(boolean useSupersets) {\n _supersetFlag = useSupersets;\n }\n\n /**\n * Construct a zone that has the given timers.\n * @param timers\n * \t\t\t\tThe ith index of the array is the index of the timer. For example,\n * \t\t\t\t\tif timers = [1, 3, 5], then the zeroth row/column of the DBM is the\n * \t\t\t\t\ttimer of the transition with index 1, the first row/column of the\n * \t\t\t\t\tDBM is the timer of the transition with index 3, and the 2nd\n * \t\t\t\t\trow/column is the timer of the transition with index 5. Do not\n * \t\t\t\t\tinclude the zero timer.\n * @param matrix\n * \t\t\t\tThe DBM augmented with the lower and upper bounds of the delays for the\n * \t\t\t\t\ttransitions. For example, suppose a zone has timers [1, 3, 5] (as\n * \t\t\t\t\tdescribed in the timers parameters). The delay for transition 1 is\n * \t\t\t\t\t[1, 3], the delay for transition 3 is [2,5], and the delay for\n * \t\t\t\t\ttransition 5 is [4,6]. Also suppose the DBM is\n * \t\t\t\t\t t0 t1 t3 t5\n * \t\t\t\t\tt0 | 0, 3, 3, 3 |\n * \t\t\t\t\tt1 | 0, 0, 0, 0 |\n * \t\t\t\t\tt3 | 0, 0, 0, 0 |\n * \t\t\t\t\tt5 | 0, 0, 0, 0 |\n * \t\t\t\t\tThen the matrix that should be passed is\n * \t\t\t\t\t lb t0 t1 t3 t5\n * \t\t\t\t\tub| 0, 0, 3, 5, 6|\n * \t\t\t\t\tt0| 0, 0, 3, 3, 3|\n * \t\t\t\t\tt1|-1, 0, 0, 0, 0|\n * \t\t\t\t\tt3|-2, 0, 0, 0, 0|\n * \t\t\t\t\tt5|-4, 0, 0, 0, 0|\n * \t\t\t\t\tThe matrix should be non-null and the zero timer should always be the\n * \t\t\t\t\tfirst timer, even when there are no other timers.\n */\n public Zone(int[] timers, int[][] matrix) {\n // A negative number indicates that the hash code has not been set.\n _hashCode = -1;\n // Make a copy to reorder the timers.\n // Make a copy to reorder the timers.\n _indexToTimerPair = new LPNTransitionPair[timers.length];\n for (int i = 0; i < timers.length; i++) {\n _indexToTimerPair[i] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);\n }\n // Sorting the array.\n // Sorting the array.\n Arrays.sort(_indexToTimerPair);\n // // Add the zeroth timer.\n if (_indexToTimerPair[0].get_transitionIndex() != -1) {\n // Add the zeroth timer.\n LPNTransitionPair[] newIndexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newIndexToTimerPair[i + 1] = _indexToTimerPair[i];\n }\n _indexToTimerPair = newIndexToTimerPair;\n _indexToTimerPair[0] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, -1);\n }\n // throw new IllegalArgumentException(\"Timers must be non negative.\");\n // // Add a zero timer.\n // Map the old index of the timer to the new index of the timer.\n HashMap newIndex = new HashMap();\n // For the old index, find the new index.\n for (int i = 0; i < timers.length; i++) {\n // Since the zeroth timer is not included in the timers passed\n // to the index in the DBM is 1 more than the index of the timer\n // in the timers array.\n // LPNTransitionPair searchValue =\n LPNTransitionPair searchValue = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);\n newIndex.put(i + 1, Arrays.binarySearch(_indexToTimerPair, searchValue));\n }\n // Add the zero timer index.\n newIndex.put(0, 0);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Copy the DBM\n for (int i = 0; i < dbmSize(); i++) {\n for (int j = 0; j < dbmSize(); j++) {\n // Copy the passed in matrix to _matrix.\n setDbmEntry(newIndex.get(i), newIndex.get(j), matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]);\n // In the above, changed setDBMIndex to setdbm\n }\n }\n // Copy in the upper and lower bounds. The zero time does not have an upper or lower bound\n // so the index starts at i=1, the first non-zero timer.\n for (int i = 1; i < dbmSize(); i++) {\n setUpperBoundbydbmIndex(newIndex.get(i), matrix[0][dbmIndexToMatrixIndex(i)]);\n // Note : The method setLowerBoundbydbmIndex, takes the value of the lower bound\n // and the matrix stores the negative of the lower bound. So the matrix value\n // must be multiplied by -1.\n setLowerBoundbydbmIndex(newIndex.get(i), -1 * matrix[dbmIndexToMatrixIndex(i)][0]);\n }\n recononicalize();\n }\n\n /**\n * Initializes a zone according to the markings of state.\n * @param currentState\n * \t\t\tThe zone is initialized as if all enabled timers\n * \t\t\thave just been enabled.\n */\n public Zone(State initialState) {\n // Extract the associated LPN.\n LPN lpn = initialState.getLpn();\n int LPNIndex = lpn.getLpnIndex();\n if (_lpnList == null) {\n // If no LPN exists yet, create it and put lpn in it.\n _lpnList = new LPN[LPNIndex + 1];\n _lpnList[LPNIndex] = lpn;\n } else if (_lpnList.length <= LPNIndex) {\n // The list does not contain the lpn.\n LPN[] tmpList = _lpnList;\n _lpnList = new LPN[LPNIndex + 1];\n _lpnList[LPNIndex] = lpn;\n // Copy any that exist already.\n for (int i = 0; i < _lpnList.length; i++) {\n _lpnList[i] = tmpList[i];\n }\n } else if (_lpnList[LPNIndex] != lpn) {\n // This checks that the appropriate lpn is in the right spot.\n // If not (which gets you in this block), then this fixes it.\n _lpnList[LPNIndex] = lpn;\n }\n // Default value for the hash code indicating that the hash code has not\n // been set yet.\n _hashCode = -1;\n // Get the list of currently enabled Transitions by their index.\n boolean[] enabledTran = initialState.getTranVector();\n ArrayList enabledTransitionsArrayList = new ArrayList();\n LPNTransitionPair zeroPair = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, LPNTransitionPair.ZERO_TIMER);\n // Add the zero timer first.\n enabledTransitionsArrayList.add(zeroPair);\n // The index of the boolean value corresponds to the index of the Transition.\n for (int i = 0; i < enabledTran.length; i++) {\n if (enabledTran[i]) {\n enabledTransitionsArrayList.add(new LPNTransitionPair(LPNIndex, i));\n }\n }\n _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);\n _matrix = new int[matrixSize()][matrixSize()];\n for (int i = 1; i < dbmSize(); i++) {\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = lpn.getTransition(_indexToTimerPair[i].get_transitionIndex()).getLabel();\n ExprTree delay = lpn.getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = lpn.getAllVarsWithValuesAsString(initialState.getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n ExprTree lowerDelay = delay.getLeftChild();\n ExprTree upperDelay = delay.getRightChild();\n lower = (int) lowerDelay.evaluateExpr(varValues);\n upper = (int) upperDelay.evaluateExpr(varValues);\n } else {\n lower = (int) delay.evaluateExpr(varValues);\n upper = lower;\n }\n setLowerBoundbydbmIndex(i, lower);\n setUpperBoundbydbmIndex(i, upper);\n }\n // Advance the time and tighten the bounds.\n advance();\n recononicalize();\n checkZoneMaxSize();\n }\n\n /**\n * Creates a Zone based on the local states.\n * @param localStates\n * \t\t\tThe current state (or initial) of the LPNs.\n */\n public Zone(State[] localStates) {\n // Open the log file.\n if (_writeLogFile == null && Options.get_TimingLogfile() != null) {\n try {\n _writeLogFile = new BufferedWriter(new FileWriter(Options.get_TimingLogfile()));\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n }\n }\n // Initialize hash code to -1 (indicating nothing cached).\n _hashCode = -1;\n // Initialize the LPN list.\n initialize_lpnList(localStates);\n // Get the enabled transitions. This initializes the _indexTotimerPair\n // which stores the relevant information.\n // This method will also initialize the _rateZeroContinuous\n initialize_indexToTimerPair(localStates);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Set the lower bound/ upper bounds of the timers and the rates.\n initializeLowerUpperBounds(getAllNames(), localStates);\n // Initialize the row and column entries for the continuous variables.\n initializeRowColumnContVar();\n // Create a previous zone to the initial zone for the sake of warping.\n Zone tmpZone = beforeInitialZone();\n dbmWarp(tmpZone);\n recononicalize();\n // Advance Time\n advance(localStates);\n // Re-canonicalize\n recononicalize();\n // Check the size of the DBM.\n checkZoneMaxSize();\n }\n\n /**\n * Creates a Zone based on the local states.\n * @param localStates\n * \t\t\tThe current state (or initial) of the LPNs.\n */\n public Zone(State[] localStates, boolean init) {\n // Extract the local states.\n // Initialize hash code to -1 (indicating nothing cached).\n _hashCode = -1;\n // Initialize the LPN list.\n initialize_lpnList(localStates);\n // Get the enabled transitions. This initializes the _indexTotimerPair\n // which stores the relevant information.\n // This method will also initialize the _rateZeroContinuous\n initialize_indexToTimerPair(localStates);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Set the lower bound/ upper bounds of the timers and the rates.\n initializeLowerUpperBounds(getAllNames(), localStates);\n // Initialize the row and column entries for the continuous variables.\n initializeRowColumnContVar();\n if (init) {\n return;\n }\n // Advance Time\n advance(localStates);\n // Re-canonicalize\n recononicalize();\n // Check the size of the DBM.\n checkZoneMaxSize();\n }\n\n // * Sets ups a zone containing continuous variables only.\n // * @param continuousValues\n // * \t\tThe values to populate the zone with.\n // // Copy the LPNContinuousPairs over\n // int count = 0; // The position in the _indexToTimerPair for the next value.\n /**\n * Gives the names of all the transitions and continuous variables that\n * are represented by the zone.\n * @return\n * \t\tThe names of the transitions and continuous variables that are\n * \t\trepresented by the zone.\n */\n public String[] getAllNames() {\n // transitionNames[0] = \"The zero timer.\";\n // Get the continuous variable names.\n String[] contVar = getContVarNames();\n // Get the transition names.\n String[] trans = getTranNames();\n // Create an array large enough for all the names.\n String[] names = new String[contVar.length + trans.length + 1];\n // Add the zero timer.\n names[0] = \"The zero timer.\";\n // Add the continuous variables.\n for (int i = 0; i < contVar.length; i++) {\n names[i + 1] = contVar[i];\n }\n // Add the timers.\n for (int i = 0; i < trans.length; i++) {\n // Already the zero timer has been added and the elements of contVar.\n // That's a total of 'contVar.length + 1' elements. The last index was\n // thus 'contVar.length' So the first index to add to is\n names[1 + contVar.length + i] = trans[i];\n }\n return names;\n }\n\n /**\n * Get the names of the continuous variables that this zone uses.\n * @return\n * \t\tThe names of the continuous variables that are part of this zone.\n */\n public String[] getContVarNames() {\n // List for accumulating the names.\n ArrayList contNames = new ArrayList();\n // Find the pairs that represent the continuous variables. Loop starts at\n // i=1 since the i=0 is the zero timer.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // If the isTimer value is false, then this pair represents a continuous\n // If pair is LPNContinuousPair.\n if (ltPair instanceof LPNContinuousPair) {\n // Get the LPN that this pairing references and find the name of\n // the continuous variable whose index is given by this pairing.\n contNames.add(_lpnList[ltPair.get_lpnIndex()].getContVarName(ltPair.get_transitionIndex()));\n }\n }\n return contNames.toArray(new String[0]);\n }\n\n /**\n * Gets the names of the transitions that are associated with the timers in the\n * zone. Does not return the zero timer.\n * @return\n * \t\tThe names of the transitions whose timers are in the zone except the zero\n * \t\ttimer.\n */\n public String[] getTranNames() {\n // List for accumulating the names.\n ArrayList transitionNames = new ArrayList();\n // Find the pairs that represent the transition timers.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // If the isTimer value is true, then this pair represents a timer.\n // If this is an LPNTransitionPair and not an LPNContinuousPair\n if (!(ltPair instanceof LPNContinuousPair)) {\n // Get the LPN that this pairing references and find the name of the\n // transition whose index is given by this pairing.\n transitionNames.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()).getLabel());\n }\n }\n return transitionNames.toArray(new String[0]);\n }\n\n /**\n * Initializes the _lpnList using information from the local states.\n * @param localStates\n * \t\tThe local states.\n * @return\n * \t\tThe enabled transitions.\n */\n private void initialize_lpnList(State[] localStates) {\n // Create the LPN list.\n _lpnList = new LPN[localStates.length];\n // Get the LPNs.\n for (int i = 0; i < localStates.length; i++) {\n _lpnList[i] = localStates[i].getLpn();\n }\n }\n\n /**\n * Initializes the _indexToTimerPair from the local states. This includes\n * adding the zero timer, the continuous variables and the set of\n * enabled timers.\n * @param localStates\n * \t\tThe local states.\n * @return\n * \t\tThe names of the transitions stored in the _indexToTimerPair (in the same order).\n */\n private void initialize_indexToTimerPair(State[] localStates) {\n /*\n\t\t * The populating of the _indexToTimerPair is done in three stages.\n\t\t * The first is to add the zero timer which is at the beginning of the zone.\n\t\t * The second is to add the continuous variables. And the third is to add\n\t\t * the other timers. Since the continuous variables are added before the\n\t\t * timers and the variables and timers are added in the order of the LPNs,\n\t\t * the elements in an accumulating list (enabledTransitionsArrayList) are\n\t\t * already in order up to the elements added for a particular LPN. Thus the\n\t\t * only sorting that needs to take place is the sorting for a particular LPN.\n\t\t * Correspondingly, elements are first found for an LPN and sort, then added\n\t\t * to the main list.\n\t\t */\n // This method will also initialize the _rateZeroContinuous\n _rateZeroContinuous = new DualHashMap();\n // This list accumulates the transition pairs (ie timers) and the continuous\n ArrayList enabledTransitionsArrayList = new ArrayList();\n // Put in the zero timer.\n // enabledTransitionsArrayList\n enabledTransitionsArrayList.add(new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, LPNTransitionPair.ZERO_TIMER));\n // Get the continuous variables.\n for (int i = 0; i < localStates.length; i++) {\n // Accumulates the changing continuous variables for a single LPN.\n ArrayList singleLPN = new ArrayList();\n // Get the associated LPN.\n LPN lpn = localStates[i].getLpn();\n // Get the continuous variables for this LPN.\n String[] continuousVariables = lpn.getContVars();\n // Get the variable, index map.\n DualHashMap variableIndex = lpn.getContinuousIndexMap();\n // Find which have a nonzero rate.\n for (int j = 0; j < continuousVariables.length; j++) {\n // Get the Variables with this name.\n Variable contVar = lpn.getVariable(continuousVariables[j]);\n // Get the rate.\n IntervalPair rate = parseRate(contVar.getInitRate());\n // Get the LPN index for the variable\n int lpnIndex = lpn.getLpnIndex();\n // Get the index as a variable for the LPN.\n int contVariableIndex = variableIndex.get(continuousVariables[j]);\n LPNContinuousPair newPair = new LPNContinuousPair(lpnIndex, contVariableIndex, rate.getSmallestRate());\n // If the rate is non-zero, then the variables needs to be tracked\n // by matrix part of the Zone.\n if (newPair.getCurrentRate() != 0) {\n // Temporary exception guaranteeing only unit rates.\n // \"only supports positive unit rates. The variable \" + contVar +\n // \" has a rate of \" + rate);\n // // Get the LPN index for the variable\n // // Get the index as a variable for the LPN. This index matches\n // // the index in the vector stored by platu.State.\n // The continuous variable reference.\n singleLPN.add(newPair);\n } else {\n // If the rate is zero, then the Zone keeps track of this variable\n // in a list.\n _rateZeroContinuous.insert(new LPNContAndRate(newPair, rate), new VariableRangePair(contVar, parseRate(contVar.getInitValue())));\n }\n }\n // Sort the list.\n Collections.sort(singleLPN);\n // Add the list to the total accumulating list.\n for (int j = 0; j < singleLPN.size(); j++) {\n enabledTransitionsArrayList.add(singleLPN.get(j));\n }\n }\n // Get the transitions.\n for (int i = 0; i < localStates.length; i++) {\n // Extract the enabled transition vector.\n boolean[] enabledTran = localStates[i].getTranVector();\n // Accumulates the transition pairs for one LPN.\n ArrayList singleLPN = new ArrayList();\n // The index of the boolean value corresponds to the index of the Transition.\n for (int j = 0; j < enabledTran.length; j++) {\n if (enabledTran[j]) {\n // Add the transition pair.\n singleLPN.add(new LPNTransitionPair(i, j));\n }\n }\n // Sort the transitions for the current LPN.\n Collections.sort(singleLPN);\n // Add the collection to the enabledTransitionsArrayList\n for (int j = 0; j < singleLPN.size(); j++) {\n enabledTransitionsArrayList.add(singleLPN.get(j));\n }\n }\n // Extract out the array portion of the enabledTransitionsArrayList.\n _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);\n }\n\n /**\n * Sets the lower and upper bounds for the transitions and continuous variables.\n * @param varNames\n * \t\t\tThe names of the transitions in _indexToTimerPair.\n */\n private void initializeLowerUpperBounds(String[] varNames, State[] localStates) {\n // Traverse the entire length of the DBM sub-matrix except the zero row/column.\n // This is the same length as the _indexToTimerPair.length-1. The DBM is used to\n // match the idea of setting the value for each row.\n for (int i = 1; i < dbmSize(); i++) {\n // Get the current LPN and transition pairing.\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n IntervalPair range;\n if (ltPair instanceof LPNContinuousPair) {\n // If the pairing represents a continuous variable, then the\n // upper and lower bound are the initial value or infinity depending\n // on whether the initial rate is positive or negative.\n // If the value is a constant, then assign the upper and lower bounds\n // to be constant. If the value is a range then assign the upper and\n // lower bounds to be a range.\n Variable v = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());\n String rate = v.getInitRate();\n // Parse the rate. Should be in the form of [x,y] where x\n // and y are integers.\n range = parseRate(rate);\n // Set the upper and lower bound (in the matrix) for the\n // continuous variables.\n String contValue = v.getInitValue();\n IntervalPair bound = parseRate(contValue);\n // Set upper bound (DBM entry (0, x) where x is the index of the variable v).\n setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, bound.get_UpperBound());\n // Set lower bound (DBM entry (x, 0) where x is the index of the variable v).\n setDbmEntryByPair(ltPair, LPNTransitionPair.ZERO_TIMER_PAIR, -1 * bound.get_LowerBound());\n } else {\n // Get the expression tree.\n ExprTree delay = _lpnList[ltPair.get_lpnIndex()].getDelayTree(varNames[i]);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[ltPair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[ltPair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n // Passing the zone as null since it should not be needed.\n // // The lower and upper bounds should evaluate to a single\n // throw new IllegalStateException(\"When evaulating the delay, \" +\n // \"the lower or the upper bound evaluated to a range \" +\n // \"instead of a single value.\");\n if (delay != null) {\n range = delay.evaluateExprBound(varValues, this, null);\n } else {\n range = new IntervalPair(0, 0);\n }\n }\n setLowerBoundbydbmIndex(i, range.get_LowerBound());\n setUpperBoundbydbmIndex(i, range.get_UpperBound());\n }\n }\n\n /**\n * Initialize the rows and columns for the continuous variables.\n */\n private void initializeRowColumnContVar() {\n /*\n\t\t * TODO : Describe the idea behind the following algorithm.\n\t\t */\n // // Note: row is indexing the row of the DBM matrix.\n // // If we reached the timers, stop.\n // // Note: col is indexing the column of the DBM matrix.\n // // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since\n // // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower\n // // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);\n // The only entries that do not need to be checked are the ones where both variables\n // represent timers.\n for (int row = 2; row < _indexToTimerPair.length; row++) {\n // Note: row is indexing the row of the DBM matrix.\n LPNTransitionPair ltRowPair = _indexToTimerPair[row];\n // // If we reached the timers, stop.\n for (int col = 1; col < row; col++) {\n // Note: col is indexing the column of the DBM matrix.\n LPNTransitionPair ltColPair = _indexToTimerPair[col];\n // If we've reached the part of the zone involving only timers, then break out\n if (!(ltRowPair instanceof LPNContinuousPair) && !(ltColPair instanceof LPNContinuousPair)) {\n break;\n }\n // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since\n // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower\n // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);\n int rowCol = getDbmEntry(row, 0) + getDbmEntry(0, col);\n int colRow = getDbmEntry(col, 0) + getDbmEntry(0, row);\n setDbmEntry(row, col, rowCol);\n setDbmEntry(col, row, colRow);\n }\n }\n }\n\n /**\n * Zero argument constructor for use in methods that create Zones where the members\n * variables will be set by the method.\n */\n private Zone() {\n _matrix = new int[0][0];\n _indexToTimerPair = new LPNTransitionPair[0];\n _hashCode = -1;\n _lpnList = new LPN[0];\n _rateZeroContinuous = new DualHashMap();\n }\n\n /**\n * Gets the upper bound of a Transition from the zone.\n * @param t\n * \t\tThe transition whose upper bound is wanted.\n * @return\n * \t\tThe upper bound of Transition t.\n */\n public int getUpperBoundbyTransition(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n // LPNTransitionPair ltPair =\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return getUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Returns the upper bound of the continuous variable.\n * @param var\n * \t\tThe variable of interest.\n * @return\n * \t\tThe (0,var) entry of the zone, that is the maximum as recored by\n * \t\tthe zone.\n */\n public int getUpperBoundbyContinuousVariable(String contVar, LPN lpn) {\n // // Determine whether the variable is in the zone or rate zero.\n // // If a RangeAndPairing is returned, then get the information from here.\n // // If indexAndRange is null, then try to get the value from the zone.\n // throw new IllegalStateException(\"Atempted to find the upper bound for \"\n // + \"a non-rate zero continuous variable that was not found in the \"\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note : setting the rate is not necessary here since this is only\n // being used as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range().get_UpperBound();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the lower bound for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n return getDbmEntry(0, i);\n }\n\n public int getUpperBoundForRate(LPNTransitionPair contVar) {\n // Check if the contVar is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (i > 0) {\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n // Grab the current rate from the LPNContinuousPair.\n return ((LPNContinuousPair) _indexToTimerPair[i]).getCurrentRate();\n }\n // Assume the rate is zero. This covers the case if conVar\n // is in the rate zero as well as if its not in the state at all.\n return 0;\n }\n\n /**\n * Get the value of the upper bound for the delay. If the index refers\n * to a timer, otherwise get the upper bound for the continuous\n * variables rate.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @return\n * \t\t\tThe upper bound on the transitions delay.\n */\n public int getUpperBoundbydbmIndex(int index) {\n return _matrix[0][dbmIndexToMatrixIndex(index)];\n }\n\n public int getUpperBound(int index) {\n return _matrix[0][dbmIndexToMatrixIndex(index)];\n }\n\n @Override\n public int getUpperBoundTrue(int index) {\n return _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(index)];\n }\n\n public int getUnwarpedUpperBound(LPNContinuousPair lcpair) {\n // Get the index.\n int index = Arrays.binarySearch(_indexToTimerPair, lcpair);\n int rate = ((LPNContinuousPair) _indexToTimerPair[index]).getCurrentRate();\n int warpValue = getUpperBoundTrue(index);\n return warpValue * rate;\n }\n\n public int getLowerBound(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][0];\n }\n\n @Override\n public int getLowerBoundTrue(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][dbmIndexToMatrixIndex(0)];\n }\n\n /**\n * Set the value of the upper bound for the delay.\n * @param t\n * \t\t\tThe transition whose upper bound is being set.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n public void setUpperBoundbyTransition(Transition t, int value) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the upper bound for the delay.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n public void setUpperBoundbydbmIndex(int index, int value) {\n _matrix[0][dbmIndexToMatrixIndex(index)] = value;\n }\n\n /**\n * Sets the upper bound for a transition described by an LPNTransitionPair.\n * @param ltPair\n * \t\t\tThe index of the transition and the index of the associated LPN for\n * \t\t\tthe timer to set the upper bound.\n * @param value\n * \t\t\tThe value for setting the upper bound.\n */\n private void setUpperBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value) {\n setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Gets the lower bound of a Transition from the zone.\n * @param t\n * \t\tThe transition whose upper bound is wanted.\n * @return\n * \t\tThe lower bound of Transition t.\n */\n @Override\n public int getLowerBoundbyTransition(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return getLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Returns the lower bound of the continuous variable.\n * @param var\n * \t\tThe variable of interest.\n * @return\n * \t\tThe (0,var) entry of the zone, that is the minimum as recored by\n * \t\tthe zone.\n */\n public int getLowerBoundbyContinuousVariable(String contVar, LPN lpn) {\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note: Setting the rate is not necessary since this is only being used\n // as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range().get_LowerBound();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the lower bound for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n return getDbmEntry(i, 0);\n }\n\n /**\n * Get the value of the lower bound for the delay if the index refers\n * to a timer, otherwise get the lower bound for the continuous variables\n * rate.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @return\n * \t\t\tThe value of the lower bound.\n */\n public int getLowerBoundbydbmIndex(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][0];\n }\n\n public int getLowerBoundForRate(LPNTransitionPair contVar) {\n // Check if the contVar is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (i > 0) {\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n return getLowerBoundbydbmIndex(contVar.get_transitionIndex());\n }\n // Assume the rate is zero. This covers the case if conVar\n // is in the rate zero as well as if its not in the state at all.\n return 0;\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param t\n * \t\t\tThe transition whose lower bound is being set.\n * @param value\n * \t\t\tThe value of the lower bound.\n */\n public void setLowerBoundbyTransition(Transition t, int value) ", "post_mask_code": "\n\n /**\n * Set the value of the lower bound for the delay.\n * @param t\n * \t\t\tThe transition whose upper bound is being set.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n private void setLowerBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value) {\n setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @param value\n * \t\t\tThe value of the lower bound.\n */\n public void setLowerBoundbydbmIndex(int index, int value) {\n _matrix[dbmIndexToMatrixIndex(index)][0] = -1 * value;\n }\n\n /**\n * Give the upper and lower bounds for a continuous variable.\n * @param contVar\n * \t\tThe variable of interest.\n * @return\n * \t\tThe upper and lower bounds according to the Zone.\n */\n @Override\n public IntervalPair getContinuousBounds(String contVar, LPN lpn) {\n /*\n\t\t * Need to determine whether this is suppose to be a rate zero variable or a non-zero \n\t\t * rate variable. One method is to check the rate of the passed variable. The other is\n\t\t * to just check if the variable is present in either place.\n\t\t */\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n // Get the index of the continuous variable.\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note: setting the current rate is not necessary here since the\n // LPNContinuousPair is only being used as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(new LPNContAndRate(index, new IntervalPair(0, 0)));\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the bounds for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n // Else find the upper and lower bounds.\n int lower = (-1) * getDbmEntry(i, 0);\n int upper = getDbmEntry(0, i);\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the range for the continuous variable. Values come back not\n * warped.\n * @param ltContPair\n * \t\tThe index of the variable of interest.\n * @return\n * \t\tThe range of the continuous variable described by ltContPair.\n */\n @Override\n public IntervalPair getContinuousBounds(LPNContinuousPair ltContPair) {\n // First check in the zone.\n int variableIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);\n if (variableIndex < 0) {\n // The variable was not found in the zone. Check to see if its\n // in the rate-zero variables. Technically I will return whatever\n // is in the _rateZeroConintuous, null or not.\n // First get an object to reference into the _rateZeroContinuous\n LPNContAndRate lcr = new LPNContAndRate(ltContPair, new IntervalPair(0, 0));\n return _rateZeroContinuous.get(lcr).get_range();\n }\n // The variable was found in the zone. Yay.\n int lower = (-1) * getDbmEntry(variableIndex, 0) * getCurrentRate(ltContPair);\n int upper = getDbmEntry(0, variableIndex) * getCurrentRate(ltContPair);\n // If the current rate is negative the upper and lower bounds\n // need to be switched.\n if (getCurrentRate(ltContPair) < 0) {\n int tmp = lower;\n lower = upper;\n upper = tmp;\n }\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the range of the rate associated with a continuous variable.\n * @param ltContPair\n * \t\tThe index of the continuous variable.\n * @return\n * \t\tThe range of rates associated with the continuous variable indexed\n * \t\tby ltContPair.\n */\n @Override\n public IntervalPair getRateBounds(LPNTransitionPair ltPair) {\n int upper;\n int lower;\n // Check if the ltContpair is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, ltPair);\n if (i < 0) {\n // Then the variable is in the rate zero continuous\n // variables so get the range of rates from there.\n // Create an object to reference into the rate zero.\n LPNContAndRate lcr = new LPNContAndRate((LPNContinuousPair) ltPair, new IntervalPair(0, 0));\n // Get the old version of lcr from the rate zero since\n // that contains the rate. This is quite a hack.\n VariableRangePair vrp = _rateZeroContinuous.get(lcr);\n lcr = _rateZeroContinuous.getKey(vrp);\n return lcr.get_rateInterval();\n }\n upper = getUpperBoundbydbmIndex(i);\n lower = -1 * getLowerBoundbydbmIndex(i);\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the rate reset value.\n * @param ltPair\n * @return\n */\n @Override\n public int rateResetValue(LPNTransitionPair ltPair) {\n IntervalPair rateBounds = getRateBounds(ltPair);\n int upper = rateBounds.get_UpperBound();\n int lower = rateBounds.get_LowerBound();\n // // Check if the ltContpair is in the zone.\n // // Assume the rate is zero. This covers the case if conVar\n // // is in the rate zero as well as if its not in the state at all.\n // If zero is a possible rate, then it is the rate to set to.\n // // If zero is the only possible rate, return that.\n // // When zero is in the range and there is a positive rate, return the\n // // When the upper bound is zero, return the negative rate.\n // // When zero is not present, use the smallest rate in absolute value.\n /*\n\t\t * Suppose the range of rates is [a,b]. If a>=0, we set the rate to b.\n\t\t * If b<=0, we set the rate to a. Otherwise, a<0=0, we set the rate to b.\n\t\t * If b<=0, we set the rate to a. Otherwise, a<0 variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note : Setting the rate is not necessary since this only being used\n // as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and make the new assignment.\n if (pairing != null) {\n pairing.set_range(range);\n return;\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the bounds for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n // Else find the upper and lower bounds.\n setDbmEntry(i, 0, (-1) * range.get_LowerBound());\n setDbmEntry(0, i, range.get_UpperBound());\n }\n\n /**\n * Converts the index of the DBM to the index of _matrix.\n * @param i\n * \t\t\tThe row/column index of the DBM.\n * @return\n * \t\t\tThe row/column index of _matrix.\n */\n private static int dbmIndexToMatrixIndex(int i) {\n return i + 1;\n }\n\n /**\n * Retrieves an entry of the DBM using the DBM's addressing.\n * @param i\n * \t\t\tThe row of the DBM.\n * @param j\n * \t\t\tThe column of the DBM.\n * @return\n * \t\t\tThe value of the (i, j) element of the DBM.\n */\n @Override\n public int getDbmEntry(int i, int j) {\n return _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)];\n }\n\n /**\n * Retrieves an entry of the DBM using LPNTransitionPair indecies.\n * @param iPair\n * \t\tThe LPNTransitionPair for the ith entry.\n * @param jPair\n * \t\tThe LPNTransitionPair for the jth entry.\n * @return\n * \t\tThe value of the (i,j) element of the DBM where i corresponds to the row\n * \t\tfor the variable iPair and j corresponds to the row for the variable jPair.\n */\n @Override\n public int getDbmEntryByPair(LPNTransitionPair iPair, LPNTransitionPair jPair) {\n int iIndex = Arrays.binarySearch(_indexToTimerPair, iPair);\n int jIndex = Arrays.binarySearch(_indexToTimerPair, jPair);\n return getDbmEntry(iIndex, jIndex);\n }\n\n /**\n * Sets an entry of the DBM using the DBM's addressing.\n * @param i\n * \t\t\tThe row of the DBM.\n * @param j\n * \t\t\tThe column of the DBM.\n * @param value\n * \t\t\tThe new value for the entry.\n */\n private void setDbmEntry(int i, int j, int value) {\n _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)] = value;\n }\n\n /**\n * Sets the entry in the DBM using the LPNTransitionPair indexing.\n * @param row\n * \t\t\tThe LPNTransitionPair for the row.\n * @param col\n * \t\t\tThe LPNTransitionPair for the column.\n * @param value\n * \t\t\tThe value to set the entry to.\n */\n private void setDbmEntryByPair(LPNTransitionPair row, LPNTransitionPair col, int value) {\n // The row index.\n int i = timerIndexToDBMIndex(row);\n // The column index.\n int j = timerIndexToDBMIndex(col);\n setDbmEntry(i, j, value);\n }\n\n /**\n * Returns the index of the the transition in the DBM given a LPNTransitionPair pairing\n * the transition index and associated LPN index.\n * @param ltPair\n * \t\tThe pairing comprising the index of the transition and the index of the associated\n * \t\tLPN.\n * @return\n * \t\tThe row/column of the DBM associated with the ltPair.\n */\n @Override\n public int timerIndexToDBMIndex(LPNTransitionPair ltPair) {\n return Arrays.binarySearch(_indexToTimerPair, ltPair);\n }\n\n /**\n * The matrix labeled with 'ti' where i is the transition index associated with the timer.\n */\n @Override\n public String toString() {\n // TODO : Fix the handling of continuous variables in the\n String result = \"Timer and delay or continuous and ranges.\\n\";\n int count = 0;\n // Print the timers.\n for (int i = 1; i < _indexToTimerPair.length; i++, count++) {\n if (_lpnList.length == 0) {\n // If no LPN's are associated with this Zone, use the index of the timer.\n result += \" t\" + _indexToTimerPair[i].get_transitionIndex() + \" : \";\n } else {\n String name;\n // If the current LPNTransitionPair is a timer, get the name\n // from the transitions.\n // If the current timer is an LPNTransitionPair and not an LPNContinuousPair\n if (!(_indexToTimerPair[i] instanceof LPNContinuousPair)) {\n // Get the name of the transition.\n Transition tran = _lpnList[_indexToTimerPair[i].get_lpnIndex()].getTransition(_indexToTimerPair[i].get_transitionIndex());\n name = tran.getLabel();\n } else {\n // If the current LPNTransitionPair is not a timer, get the\n // name as a continuous variable.\n Variable var = _lpnList[_indexToTimerPair[i].get_lpnIndex()].getContVar(_indexToTimerPair[i].get_transitionIndex());\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];\n int lowerBound = -1 * getDbmEntry(i, 0) * lcPair.getCurrentRate();\n int upperBound = getDbmEntry(0, i) * lcPair.getCurrentRate();\n // If the rate is negative, the bounds are switched\n // in the zone.\n if (lcPair.getCurrentRate() < 0) {\n int tmp = lowerBound;\n lowerBound = upperBound;\n upperBound = tmp;\n }\n name = var.getName() + \":[\" + lowerBound + \",\" + upperBound + \"]\\n\" + \" Current Rate: \" + lcPair.getCurrentRate() + \" \" + \"rate:\";\n }\n result += \" \" + name + \":\";\n }\n result += \"[ \" + -1 * getLowerBoundbydbmIndex(i) + \", \" + getUpperBoundbydbmIndex(i) + \" ]\";\n if (count > 9) {\n result += \"\\n\";\n count = 0;\n }\n }\n if (!_rateZeroContinuous.isEmpty()) {\n result += \"\\nRate Zero Continuous : \\n\";\n for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()) {\n result += \"\" + _rateZeroContinuous.get(lcrPair) + \"Rate: \" + lcrPair.get_rateInterval();\n }\n }\n result += \"\\nDBM\\n\";\n // Print the DBM.\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n result += \"| \" + String.format(\"%3d\", getDbmEntry(i, 0));\n for (int j = 1; j < _indexToTimerPair.length; j++) {\n result += \", \" + String.format(\"%3d\", getDbmEntry(i, j));\n }\n result += \" |\\n\";\n }\n return result;\n }\n\n /**\n * Tests for equality. Overrides inherited equals method.\n * @return True if o is equal to this object, false otherwise.\n */\n @Override\n public boolean equals(Object o) {\n // Check if the reference is null.\n if (o == null) {\n return false;\n }\n // Check that the type is correct.\n if (!(o instanceof Zone)) {\n return false;\n }\n // Check for equality using the Zone equality.\n return equals((Zone) o);\n }\n\n /**\n * Tests for equality.\n * @param\n * \t\tThe Zone to compare.\n * @return\n * \t\tTrue if the zones are non-null and equal, false otherwise.\n */\n public boolean equals(Zone otherZone) {\n // Check if the reference is null first.\n if (otherZone == null) {\n return false;\n }\n // Check for reference equality.\n if (this == otherZone) {\n return true;\n }\n // If the hash codes are different, then the objects are not equal.\n if (this.hashCode() != otherZone.hashCode()) {\n return false;\n }\n // Check if the they have the same number of timers.\n if (this._indexToTimerPair.length != otherZone._indexToTimerPair.length) {\n return false;\n }\n // Check if the timers are the same.\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n if (!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))) {\n return false;\n }\n }\n // Check if the matrix is the same\n for (int i = 0; i < _matrix.length; i++) {\n for (int j = 0; j < _matrix[0].length; j++) {\n if (!(this._matrix[i][j] == otherZone._matrix[i][j])) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Determines if this zone is a subset of Zone otherZone.\n * @param otherZone\n * \t\tThe zone to compare against.\n * @return\n * \t\tTrue if this is a subset of other; false otherwise.\n */\n @Override\n public boolean subset(Equivalence otherEquiv) {\n Zone otherZone = (Zone) otherEquiv;\n // Check if the reference is null first.\n if (otherZone == null) {\n return false;\n }\n // Check for reference equality.\n if (this == otherZone) {\n return true;\n }\n // Check if the the same number of timers are present.\n if (this._indexToTimerPair.length != otherZone._indexToTimerPair.length) {\n return false;\n }\n // Check if the transitions are the same.\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n if (!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))) {\n return false;\n }\n }\n // Check if the entries of this Zone are less than or equal to the entries\n // of the other Zone.\n for (int i = 0; i < _matrix.length; i++) {\n for (int j = 0; j < _matrix[0].length; j++) {\n if (!(this._matrix[i][j] <= otherZone._matrix[i][j])) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Determines if this zone is a superset of Zone otherZone.\n * @param otherZone\n * \t\tThe zone to compare against.\n * @return\n * \t\tTrue if this is a subset of other; false otherwise. More specifically it\n * \t\tgives the result of otherZone.subset(this). Thus it agrees with the subset method.\n */\n @Override\n public boolean superset(Equivalence otherZone) {\n return otherZone.subset(this);\n }\n\n /**\n * Overrides the hashCode.\n */\n @Override\n public int hashCode() {\n // Check if the hash code has been set.\n if (_hashCode < 0) {\n _hashCode = createHashCode();\n }\n return _hashCode;\n }\n\n /**\n * Creates a hash code for a Zone object.\n * @return\n * \t\tThe hash code.\n */\n private int createHashCode() {\n int newHashCode = Arrays.hashCode(_indexToTimerPair);\n for (int i = 0; i < _matrix.length; i++) {\n newHashCode ^= Arrays.hashCode(_matrix[i]);\n }\n return Math.abs(newHashCode);\n }\n\n /**\n * The size of the DBM sub matrix. This is calculated using the size of _indexToTimer.\n * @return\n * \t\t\tThe size of the DBM.\n */\n private int dbmSize() {\n return _indexToTimerPair.length;\n }\n\n /**\n * The size of the matrix.\n * @return\n * \t\t\tThe size of the matrix. This is calculated using the size of _indexToTimer.\n */\n private int matrixSize() {\n return _indexToTimerPair.length + 1;\n }\n\n /**\n * Performs the Floyd's least pairs algorithm to reduce the DBM.\n */\n @Override\n public void recononicalize() {\n for (int k = 0; k < dbmSize(); k++) {\n for (int i = 0; i < dbmSize(); i++) {\n for (int j = 0; j < dbmSize(); j++) {\n if (getDbmEntry(i, k) != INFINITY && getDbmEntry(k, j) != INFINITY && getDbmEntry(i, j) > getDbmEntry(i, k) + getDbmEntry(k, j)) {\n setDbmEntry(i, j, getDbmEntry(i, k) + getDbmEntry(k, j));\n }\n if ((i == j) && getDbmEntry(i, j) != 0) {\n throw new DiagonalNonZeroException(\"Entry (\" + i + \", \" + j + \")\" + \" became \" + getDbmEntry(i, j) + \".\");\n }\n }\n }\n }\n }\n\n /**\n * Determines if a timer associated with a given transitions has reached its lower bound.\n * @param t\n * \t\t\tThe transition to consider.\n * @return\n * \t\t\tTrue if the timer has reached its lower bound, false otherwise.\n */\n public boolean exceedsLowerBoundbyTransitionIndex(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return exceedsLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Determines if a timer has reached its lower bound.\n * @param timer\n * \t\t\tThe timer's index.\n * @return\n * \t\t\tTrue if the timer has reached its lower bound, false otherwise.\n */\n public boolean exceedsLowerBoundbydbmIndex(int index) {\n // Note : Make sure that the lower bound is stored as a negative number\n // and that the inequality is correct.\n return _matrix[0][dbmIndexToMatrixIndex(index)] <= _matrix[1][dbmIndexToMatrixIndex(index)];\n }\n\n /* (non-Javadoc)\n\t * @see verification.timed_state_exploration.zone.Zone#fireTransitionbyTransitionIndex(int, int[], verification.platu.stategraph.State)\n\t */\n // State state)\n // // Check if the value is in this zone to fire.\n /**\n * Gives the Zone obtained by firing a given Transitions.\n * @param t\n * \t\tThe transitions being fired.\n * @param enabledTran\n * \t\tThe list of currently enabled Transitions.\n * @param localStates\n * \t\tThe current local states.\n * @return\n * \t\tThe Zone obtained by firing Transition t with enabled Transitions enabled\n * \t\tenabledTran when the current state is localStates.\n */\n // public Zone fire(Transition t, LpnTranList enabledTran,\n @Override\n public Zone fire(Transition t, LpnTranList enabledTran, ContinuousRecordSet newAssignValues, State[] localStates) {\n try {\n if (_writeLogFile != null) {\n _writeLogFile.write(t.toString());\n _writeLogFile.newLine();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n // Create the LPNTransitionPair to check if the Transitions is in the zone and to\n // find the index.\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n int dbmIndex = Arrays.binarySearch(_indexToTimerPair, ltPair);\n if (dbmIndex <= 0) {\n return this;\n }\n // Get the new zone portion.\n Zone newZone = fireTransitionbydbmIndexNew(dbmIndex, enabledTran, localStates, newAssignValues);\n // Update any assigned continuous variables.\n // Set all the rates to their lower bound.\n newZone.setAllToLowerBoundRate();\n // Warp the Zone\n newZone.dbmWarp(this);\n // Warping can wreck the newly assigned values so correct them.\n newZone.correctNewAssignemnts(newAssignValues);\n newZone.recononicalize();\n newZone.advance(localStates);\n // Recanonicalize\n newZone.recononicalize();\n newZone.checkZoneMaxSize();\n return newZone;\n }\n\n /**\n * Updates the Zone according to the transition firing.\n * @param index\n * \t\t\tThe index of the timer.\n * @param newContValue\n * @return\n * \t\t\tThe updated Zone.\n */\n public Zone fireTransitionbydbmIndex(int index, LpnTranList enabledTimers, State[] localStates, ArrayList> newAssignValues) {\n /*\n\t\t * For the purpose of adding the newly enabled transitions and removing\n\t\t * the disable transitions, the continuous variables that still have\n\t\t * a nonzero rate can be treated like still enbaled timers.\n\t\t */\n // Initialize the zone.\n Zone newZone = new Zone();\n // These sets will defferentiate between the new timers and the\n // old timers, that is between the timers that are not already in the\n // zone and those that are already in the zone..\n HashSet newTimers = new HashSet();\n HashSet oldTimers = new HashSet();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n HashMap oldNonZero = newAssignValues.get(3);\n // Add the continuous variables to the enabled timers.\n for (int i = 1; _indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n // For the purpose of addigng continuous variables to the zone\n // consider an oldNonZero continuous variable as new.\n if (oldNonZero.containsKey(_indexToTimerPair[i])) {\n continue;\n }\n oldTimers.add(_indexToTimerPair[i]);\n }\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n // Determine if each value is a new timer or old.\n if (Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0) {\n // The timer was already present in the zone.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else {\n // The timer is a new timer.\n newTimers.add(newZone._indexToTimerPair[i]);\n }\n }\n // Create the new matrix.\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n // TODO: For simplicity, make a copy of the current zone and perform the\n // restriction and re-canonicalization. Later add a copy re-canonicalization\n // that does the steps together.\n Zone tempZone = this.clone();\n tempZone.restrictTimer(index);\n tempZone.recononicalize();\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);\n newZone._matrix[Zone.dbmIndexToMatrixIndex(newIndexi)][Zone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n // The block copies the upper and lower bound information from the\n // old zone. Thus we do not consider anything that is not an old\n // timer. Furthermore, oldNonZero represent\n if (!oldTimers.contains(tempZone._indexToTimerPair[i]) && !oldNonZero.containsKey(_indexToTimerPair[i])) {\n continue;\n }\n newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n newZone.setLowerBoundByLPNTransitionPair(pair, lower);\n newZone.setUpperBoundByLPNTransitionPair(pair, upper);\n }\n // Advance time.\n return newZone;\n }\n\n public Zone fireTransitionbydbmIndexNew(int index, LpnTranList enabledTimers, State[] localStates, ContinuousRecordSet newAssignValues) {\n /*\n\t\t * For the purpose of adding the newly enabled transitions and removing\n\t\t * the disable transitions, the continuous variables that still have\n\t\t * a nonzero rate can be treated like still enbaled timers.\n\t\t */\n // Initialize the zone.\n Zone newZone = new Zone();\n // These sets will defferentiate between the new timers and the\n // old timers, that is between the timers that are not already in the\n // zone and those that are already in the zone..\n HashSet newTimers = new HashSet();\n HashSet oldTimers = new HashSet();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n copyRatesNew(newZone, enabledTimers, newAssignValues);\n // Add the continuous variables to the enabled timers.\n // // For the purpose of addigng continuous variables to the zone\n // // consider an oldNonZero continuous variable as new.\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n // Handle the continuous variables portion.\n if (newZone._indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];\n // Get the record\n UpdateContinuous continuousState = newAssignValues.get(lcPair);\n if (continuousState != null && (continuousState.is_newValue() || continuousState.newlyNonZero())) {\n // In the first case a new value has been assigned, so\n // consider the continuous variable a 'new' variable for\n // the purposes of copying relations from the previous zone.\n newTimers.add(newZone._indexToTimerPair[i]);\n continue;\n }\n // At this point, either the continuous variable was not present\n // in the newAssignValues or it is in the newAssignValues and\n // satisfies the following: it already had a non-zero rate, is\n // being assigned another non-zero rate, and is not being assigned\n // a new value. This is becuase the field _indexToTimerPair only\n // deals with non-zero rates, so the variable must have a non-zero\n // rate. Furthermore the if statement takes care of the cases\n // when the rate changed from zero to non-zero and/or a new value\n // has been assigned.\n // In either of the cases, we consider the variable an 'old' variable\n // for the purpose of copying the previous zone information.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else // At this point, the variable represents a transition (timer).\n // So determine whether this timer is new or old.\n if (Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0) {\n // The timer was already present in the zone.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else {\n // The timer is a new timer.\n newTimers.add(newZone._indexToTimerPair[i]);\n }\n }\n // Create the new matrix.\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n // TODO: For simplicity, make a copy of the current zone and perform the\n // restriction and re-canonicalization. Later add a copy re-canonicalization\n // that does the steps together.\n Zone tempZone = this.clone();\n tempZone.restrictTimer(index);\n tempZone.recononicalize();\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);\n newZone._matrix[Zone.dbmIndexToMatrixIndex(newIndexi)][Zone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n // The block copies the upper and lower bound information from the\n // old zone. Thus we do not consider anything that is not an old\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n // A hack to ensure that the newly zero variables\n // get the new values from the tempZone.\n if (tempZone._indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) tempZone._indexToTimerPair[i];\n VariableRangePair vrp = newZone._rateZeroContinuous.get(new LPNContAndRate(lcPair));\n if (vrp != null) {\n // This means that the continuous variable was non-zero\n // and is now zero. Fix up the values according to\n // the temp zone.\n IntervalPair newRange = tempZone.getContinuousBounds(lcPair);\n vrp.set_range(newRange);\n }\n }\n continue;\n }\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];\n // Check if a rate assignment has occured for any continuous\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord != null) {\n // Since the variable is in the oldTimers, it cannot have had\n // a new value assigned to it. It must have had a new rate assignment\n IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();\n // Copy the new rate information\n newZone.setLowerBoundByLPNTransitionPair(_indexToTimerPair[i], rates.get_LowerBound());\n newZone.setUpperBoundByLPNTransitionPair(_indexToTimerPair[i], rates.get_UpperBound());\n // Copy the smallest and greatest continuous value.\n continue;\n }\n }\n newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Handle continuous case\n if (pair instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) pair;\n // If a continuous variable is in the newTimers, then an assignment\n // to the variable must have occurred. So get the value.\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord == null) {\n throw new IllegalStateException(\"The pair \" + pair + \"was not in the new assigned values but was sorted as \" + \"a new value.\");\n }\n IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();\n IntervalPair values = updateRecord.get_Value();\n newZone.setLowerBoundByLPNTransitionPair(lcPair, rates.get_LowerBound());\n newZone.setUpperBoundByLPNTransitionPair(lcPair, rates.get_UpperBound());\n // Get the current rate.\n int currentRate = lcPair.getCurrentRate();\n if (currentRate >= 0) {\n // // Copy the smallest and greatest continuous value.\n // Copy the smallest and greatest continuous value.\n newZone.setDbmEntryByPair(lcPair, LPNTransitionPair.ZERO_TIMER_PAIR, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), currentRate, true));\n newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, lcPair, ContinuousUtilities.chkDiv(values.get_UpperBound(), currentRate, true));\n } else {\n // Copy the smallest and greatest continuous value.\n // For negative rates, the upper and lower bounds need\n // to be switched.\n newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, lcPair, ContinuousUtilities.chkDiv(values.get_LowerBound(), currentRate, true));\n newZone.setDbmEntryByPair(lcPair, LPNTransitionPair.ZERO_TIMER_PAIR, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), currentRate, true));\n }\n continue;\n }\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n if (delay == null) {\n _lpnList[pair.get_lpnIndex()].changeDelay(tranName, \"0\");\n delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n }\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n newZone.setLowerBoundByLPNTransitionPair(pair, lower);\n newZone.setUpperBoundByLPNTransitionPair(pair, upper);\n }\n // Erase relationships for continuous variables that have had new values\n // assigned to them or a new non-rate zero value.\n for (int i = 1; i < newZone._indexToTimerPair.length && newZone._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];\n // Get the update variable.\n UpdateContinuous update = newAssignValues.get(lcPair);\n if (update != null && (update.is_newValue() || update.newlyNonZero())) {\n for (int j = 1; j < newZone._indexToTimerPair.length; j++) {\n if (j == i) {\n continue;\n }\n newZone.setDbmEntry(i, j, Zone.INFINITY);\n newZone.setDbmEntry(j, i, Zone.INFINITY);\n }\n }\n }\n // Advance time.\n return newZone;\n }\n\n public void correctNewAssignemnts(ContinuousRecordSet newAssignValues) {\n // Erase relationships for continuous variables that have had new values\n // assigned to them or a new non-rate zero value.\n for (int i = 1; i < this._indexToTimerPair.length && this._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];\n // Get the update variable.\n UpdateContinuous update = newAssignValues.get(lcPair);\n if (update != null && (update.is_newValue() || update.newlyNonZero())) {\n IntervalPair values = update.get_Value();\n int currentRate = lcPair.getCurrentRate();\n // Correct the upper and lower bounds.\n if (lcPair.getCurrentRate() > 0) {\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), currentRate, true));\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(values.get_UpperBound(), currentRate, true));\n } else {\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), currentRate, true));\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(values.get_LowerBound(), currentRate, true));\n }\n // Erase the relationships.\n for (int j = 1; j < this._indexToTimerPair.length; j++) {\n if (j == i) {\n continue;\n }\n this.setDbmEntry(i, j, Zone.INFINITY);\n this.setDbmEntry(j, i, Zone.INFINITY);\n }\n }\n }\n }\n\n /**\n * This fire method fires a rate change event.\n *\n * @param ltPair\n * \t\tThe index of the continuous variable whose rate needs to be changed.\n * @param rate\n * \t\tThe new rate.\n * @return\n * \t\tThe new zone resulting from the rate change.\n */\n @Override\n public Zone fire(LPNTransitionPair ltPair, int rate) {\n // Make a copy of the Zone.\n Zone resultZone = this.clone();\n // Change the current rate of the continuous variable.\n setCurrentRate(ltPair, rate);\n // Warp the zone.\n resultZone.dbmWarp(this);\n return resultZone;\n }\n\n /**\n * Handles the moving in and out of continuous variables.\n * @param newContValues\n */\n // // Copy the zero rate variables over if they are still rate zero.\n // // Check if the pairing is in the newNonZeroContValues.\n // // Interval being null indicates that the key was not\n /**\n * Handles the moving of the continuous variables in and out of the\n * _rateZeroContinuous. This includes the adding of all rate zero (new and old)\n * cotninuous variables to the _rateZeroContinuous, and creating the\n * _indexToTimerPair and populating it.\n * @param newZone The Zone being constructed.\n * @param enabled The list of enabled transitions.\n * \t\tThe enabled transitions.\n * @param newAssignValues The list of continuous variable update information.\n */\n @SuppressWarnings(\"unused\")\n private void copyRates(Zone newZone, LpnTranList enabledTran, ContinuousRecordSet newAssignValues) {\n /*\n\t\t * The newAssignValues is an ArrayList of four sets.\n\t\t * 0. Rate zero gets zero assigned.\n\t\t * 1. Rate zero gets non-zero rate assigned.\n\t\t * 2. Non-zero gets zero rate assigned.\n\t\t * 3. Non-zero gets non-zero rate assigned.\n\t\t */\n // Create new rate zero member variable.\n newZone._rateZeroContinuous = new DualHashMap();\n // First get the total number of non-zero rate continuous variables that\n // are present in the old zone.\n int totalContinuous = 0;\n for (int i = 0; i < _lpnList.length; i++) {\n totalContinuous += _lpnList[i].getTotalNumberOfContVars();\n }\n int numberNonZero = totalContinuous - _rateZeroContinuous.size();\n // The size is given by\n // total number of transitions\n // + number of non-zero rate continuous variables previously in the zone\n // + number of zero rate continuous variables that now have non-zero\n // - number of non-zero rate continuous variables that are now zero\n // + 1 for the zero timer.\n // TODO: Create an object that stores the records along with this information.\n int newNonZero = 0, newZero = 0;\n for (UpdateContinuous record : newAssignValues.keySet()) {\n if (record.newlyNonZero()) {\n newNonZero++;\n }\n if (record.newlyZero()) {\n newZero++;\n }\n }\n int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;\n // Create the timer array.\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n // Add in the zero timer.\n newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;\n // Copy over the rate zero conintinuous variables.\n // First copy over all the continuous variables that still have\n // rate zero.\n // // Cast the index.\n // // The variable no longer is rate zero, so do nothing.\n // // If the value has had an assignment, use the new values instead.\n // // Create the new VariableRangePair to add.\n // VariableRangePair vrp =\n // Copy over the rate zero continuous variables.\n // First copy over all the continuous variables that still have\n // rate zero.\n for (LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()) {\n // Cast the index.\n LPNContinuousPair ltContPair = ltTranPair.get_lcPair();\n if (!newAssignValues.get(ltContPair).is_newZero()) {\n // The variable no longer is rate zero, so do nothing.\n continue;\n }\n // If the value has had an assignment, use the new values instead.\n if (newAssignValues.contains(ltContPair)) {\n // Create the new VariableRangePair to add.\n Variable v = _lpnList[ltContPair.get_lpnIndex()].getContVar(ltContPair.get_ContinuousIndex());\n // VariableRangePair vrp =\n VariableRangePair vrp = new VariableRangePair(v, newAssignValues.get(ltContPair).get_Value());\n newZone._rateZeroContinuous.insert(new LPNContAndRate(ltContPair, new IntervalPair(0, 0)), vrp);\n } else {\n newZone._rateZeroContinuous.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));\n }\n }\n // Next add the values that are newly set to rate zero.\n // // Exract the variable.\n // // Create a VariableRangePair.\n // // Add the value to the map.\n // // Exract the variable.\n // // Create a VariableRangePair.\n // // Add the value to the map.\n // We still need to add in the rate zero continuous variables whose rate remains zero\n // since their range might have changed. We could check if the range has changed, but\n // its just as easy (or easier) to simply add it anyway.\n // Added the indecies for the non-zero rate continuous variables to the\n // _indexToTimer array.\n // Start with the values already in the old array.\n // int index = 1; // Index for the next continuous index object.\n // // Check that the value should not be removed.\n // Change to the new references for the oldNonZero. This change to the\n // Add in the indecies for the new non-zero into the old array.\n // Copy over the new transitions.\n Arrays.sort(newZone._indexToTimerPair);\n }\n\n private void copyRatesNew(Zone newZone, LpnTranList enabledTran, ContinuousRecordSet newAssignValues) {\n // Create new rate zero member variable.\n newZone._rateZeroContinuous = new DualHashMap();\n // First get the total number of non-zero rate continuous variables that\n // are present in the old zone.\n int totalContinuous = 0;\n for (int i = 0; i < _lpnList.length; i++) {\n totalContinuous += _lpnList[i].getTotalNumberOfContVars();\n }\n int numberNonZero = totalContinuous - _rateZeroContinuous.size();\n // The size is given by\n // total number of transitions\n // + number of non-zero rate continuous variables previously in the zone\n // + number of zero rate continuous variables that now have non-zero\n // - number of non-zero rate continuous variables that are now zero\n // + 1 for the zero timer.\n // TODO: Create an object that stores the records along with this information.\n int newNonZero = 0, newZero = 0;\n for (UpdateContinuous record : newAssignValues.keySet()) {\n if (record.newlyNonZero()) {\n newNonZero++;\n }\n if (record.newlyZero()) {\n newZero++;\n }\n }\n int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;\n // Create the timer array.\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n // Add in the zero timer.\n newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;\n int indexTimerCount = 1;\n // Sort the previous rate zero continuous variables into rate zero or non-zero.\n for (LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()) {\n // Cast the index.\n LPNContinuousPair ltContPair = ltTranPair.get_lcPair();\n // Check if the variable is a newly assigned value.\n UpdateContinuous assignedLtContPair = newAssignValues.get(ltContPair);\n if (assignedLtContPair != null) {\n if (assignedLtContPair.newlyNonZero()) {\n // Variable was zero and is now non-zero, so add to the the non-zero\n newZone._indexToTimerPair[indexTimerCount++] = assignedLtContPair.get_lcrPair().get_lcPair().clone();\n } else {\n // Variable was zero and is still zero, but an assignment has been\n // made. Simply add in the new assigned value.\n VariableRangePair vrp = this._rateZeroContinuous.get(ltTranPair);\n newZone._rateZeroContinuous.insert(assignedLtContPair.get_lcrPair(), new VariableRangePair(vrp.get_variable(), assignedLtContPair.get_Value()));\n }\n } else {\n newZone._rateZeroContinuous.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));\n }\n }\n // Sort the previous non-zero variables into the rate zero and non-zero.\n for (int i = 1; this._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];\n // Check if an assignment has been made.\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord != null) {\n if (updateRecord.is_newZero()) {\n // The continuous variable is now a rate zero variable.\n LPNContinuousPair ltCar = updateRecord.get_lcrPair().get_lcPair();\n Variable v = _lpnList[ltCar.get_lpnIndex()].getContVar(ltCar.get_ContinuousIndex());\n // Dewarp the upper and lower bounds.\n IntervalPair values = updateRecord.get_Value();\n int currentRate = getCurrentRate(ltCar);\n values.set_LowerBound(values.get_LowerBound() * currentRate);\n values.set_UpperBound(values.get_UpperBound() * currentRate);\n // Create a VariableRangePair.\n VariableRangePair vrp = new VariableRangePair(v, values);\n // Add the value to the map.\n newZone._rateZeroContinuous.insert(updateRecord.get_lcrPair(), vrp);\n } else {\n // This non-zero variable still has rate non-zero, but replace\n // with the newAssignValues since the rate may have changed.\n newZone._indexToTimerPair[indexTimerCount++] = updateRecord.get_lcrPair().get_lcPair();\n }\n } else {\n // The variable was non-zero and hasn't had an assignment.\n newZone._indexToTimerPair[indexTimerCount++] = this._indexToTimerPair[i].clone();\n }\n }\n // Copy over the new transitions.\n for (Transition t : enabledTran) {\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n newZone._indexToTimerPair[indexTimerCount++] = new LPNTransitionPair(lpnIndex, tranIndex);\n }\n Arrays.sort(newZone._indexToTimerPair);\n }\n\n private void advance() {\n for (int i = 0; i < dbmSize(); i++) {\n _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(i)] = getUpperBoundbydbmIndex(i);\n }\n }\n\n /**\n * Advances time. (This method should replace advance().)\n * @param localStates\n */\n @Override\n public void advance(State[] localStates) {\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n if (ltPair.equals(LPNTransitionPair.ZERO_TIMER_PAIR)) {\n continue;\n }\n // Get the new value.\n int newValue = 0;\n if (!(ltPair instanceof LPNContinuousPair)) {\n // If the pair is a timer, then simply get the stored largest value.\n int index = timerIndexToDBMIndex(ltPair);\n newValue = getUpperBoundbydbmIndex(index);\n } else {\n // If the pair is a continuous variable, then need to find the\n // possible largest bound governed by the inequalities.\n newValue = ContinuousUtilities.maxAdvance(this, ltPair, localStates);\n }\n // In either case (timer or continuous), set the upper bound portion\n // of the DBM to the new value.\n setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, newValue);\n }\n }\n\n /**\n * Copies in the new values needed to add a set of new times.\n * @param newZone\n * \t\t\tThe zone that the values are going to be copied into.\n * @param tempZone\n * \t\t\tThe zone to look up current values of timers.\n * @param newTimers\n * \t\t\tA collection of the new timers.\n * @param oldTimers\n * \t\t\tA collection of the older timers.\n * @param localStates\n * \t\t\tThe current state.\n */\n private void copyTransitions(Zone tempZone, Collection newTimers, Collection oldTimers, State[] localStates) {\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[j]);\n _matrix[dbmIndexToMatrixIndex(newIndexi)][dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n setDbmEntry(timerIndexToDBMIndex(timerNew), timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n setDbmEntry(timerIndexToDBMIndex(timerOld), timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n setLowerBoundByLPNTransitionPair(pair, lower);\n setUpperBoundByLPNTransitionPair(pair, upper);\n }\n }\n\n /**\n * This method sets all the rate to their lower bound.\n * Will not work quite right for continuous variables\n * with rates that include zero.\n */\n private void setAllToLowerBoundRate() {\n // Loop through the continuous variables.\n for (int i = 1; i < _indexToTimerPair.length && _indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair ltContPair = (LPNContinuousPair) _indexToTimerPair[i];\n // For this, recall that for a continuous variable that the lower bound\n // rate is stored in the zero column of the matrix.\n int lower = -1 * _matrix[dbmIndexToMatrixIndex(i)][0];\n int upper = _matrix[0][dbmIndexToMatrixIndex(i)];\n int newRate;\n /**\n * Suppose the range of rates is [a,b]. If a>=0, then we set the\n * rate to b. If b<=0, then we set the rate to a. Ohterwise,\n * a<0=0 or lower < 0 < upper we set the\n // rate to the upper bound.\n newRate = upper;\n }\n setCurrentRate(ltContPair, newRate);\n }\n }\n\n /**\n * Resets the rates of all continuous variables to be their\n * lower bounds.\n */\n @Override\n public Zone resetRates() {\n // Create the new zone.\n // // Copy the rate zero variables.\n // // Copy the LPNs over.\n // // Loop through the variables and save off those\n // // that are rate zero. Accumulate an array that\n // // indicates which are zero for faster\n // // copying. Save the number of continuous variables.\n // boolean[] rateZero = new boolean[this._indexToTimerPair.length]; // Is rate zero.\n // // The rate zero is in the range, so this will be\n // LPNContinuousPair lcPair =\n // // Save as a rate zero continuous variable.\n // VariableRangePair vcp =\n // // Update continuous variable counter.\n // // Save over the indexToTimer pairs.\n // // Ignore rate zero variables.\n // // If this is a continuous variable, set the rate to the lower bound.\n // // Calculate the size of the matrix and create it.\n // // Copy over the old matrix for all variables except\n // // the rate zero variables.\n // Warp\n Zone newZone = new Zone();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n /* \n\t\t * Collect the rate zero variables whose range of rates are not\n\t\t * identically zero. These will be moved out of the zone when\n\t\t * the rate is reset.\n\t\t * \n\t\t * Copy over the rate zero variables that remain rate zero.\n\t\t */\n newZone._rateZeroContinuous = new DualHashMap();\n HashSet> newlyNonZero = new HashSet>();\n for (Map.Entry variable : _rateZeroContinuous.entrySet()) {\n // Check for a single value which indicates that zero is\n // the only possible rate.\n if (variable.getKey().get_rateInterval().singleValue()) {\n // This variable only has zero as a rate so keep it\n // in the rate zero variables.\n newZone._rateZeroContinuous.insert(variable.getKey(), variable.getValue());\n } else {\n // This variable will need to be added to the zone.\n newlyNonZero.add(variable);\n }\n }\n /*\n\t\t * Calulate the size of the _indexToTimerPairs array and create\n\t\t * it.\n\t\t */\n int oldSize = this._indexToTimerPair.length;\n int newSize = oldSize + newlyNonZero.size();\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n /*\n\t\t * Copy over the old pairs and add the new ones.\n\t\t */\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();\n }\n for (Map.Entry variable : newlyNonZero) {\n newZone._indexToTimerPair[oldSize++] = variable.getKey().get_lcPair().clone();\n }\n Arrays.sort(newZone._indexToTimerPair);\n /*\n\t\t * Copy over the old matrix values and new constraints.\n\t\t */\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n for (int i = 0; i < this.dbmSize(); i++) {\n int newi = Arrays.binarySearch(newZone._indexToTimerPair, this._indexToTimerPair[i]);\n if (newi < 0) {\n System.err.println(\"In resetRates, old value was not found\" + \" in new value.\");\n continue;\n }\n // Copy upper and lower bounds for the variable.\n newZone._matrix[dbmIndexToMatrixIndex(newi)][0] = this._matrix[dbmIndexToMatrixIndex(i)][0];\n newZone._matrix[0][dbmIndexToMatrixIndex(newi)] = this._matrix[0][dbmIndexToMatrixIndex(i)];\n // Copy the DBM Entry\n for (int j = 0; j < this.dbmSize(); j++) {\n int newj = Arrays.binarySearch(newZone._indexToTimerPair, this._indexToTimerPair[j]);\n if (newj < 0) {\n System.err.println(\"In resetRates, old value was not\" + \" found in new value.\");\n continue;\n }\n newZone.setDbmEntry(newi, newj, this.getDbmEntry(i, j));\n }\n }\n for (Map.Entry variable : newlyNonZero) {\n LPNTransitionPair currentVariable = variable.getKey().get_lcPair();\n int currentIndex = Arrays.binarySearch(newZone._indexToTimerPair, currentVariable);\n IntervalPair rangeOfRates = variable.getKey().get_rateInterval();\n IntervalPair rangeOfValues = variable.getValue().get_range();\n /*\n\t\t\t * First set the range of rates, current rate, and the lower and upper\n\t\t\t * bounds for the newly added continuous variables.\n\t\t\t */\n newZone.setLowerBoundbydbmIndex(currentIndex, rangeOfRates.get_LowerBound());\n newZone.setUpperBoundbydbmIndex(currentIndex, rangeOfRates.get_UpperBound());\n newZone.setDbmEntry(currentIndex, 0, -1 * rangeOfValues.get_LowerBound());\n newZone.setDbmEntry(0, currentIndex, rangeOfValues.get_UpperBound());\n for (int j = 1; j < newZone.dbmSize(); j++) {\n if (currentIndex == j) {\n continue;\n }\n newZone.setDbmEntry(currentIndex, j, Zone.INFINITY);\n newZone.setDbmEntry(j, currentIndex, Zone.INFINITY);\n }\n }\n /*\n\t\t * Reset all the rates.\n\t\t */\n newZone.setAllToLowerBoundRate();\n newZone.recononicalize();\n newZone.dbmWarp(this);\n newZone.recononicalize();\n return newZone;\n }\n\n /**\n * Finds the maximum amount that time cam advance.\n * @return\n * \t\tvalue.\n * \t\tThe maximum amount that time can advance before a timer expires or an inequality changes\n */\n // * Several comments in this function may look like C code. That's because,\n // * well it is C code from atacs/src/lhpnrsg.c. In particular the\n // // Get the continuous variable in question.\n // // printf(\"Zone to check...\\n\");\n // // Get all the inequalities that reference the variable of interest.\n // // Update the inequality variable.\n // // /* Working on a > or >= ineq */\n // // Working on a > or >= ineq\n // // If the rate is positive.\n // // /* Working on a < or <= ineq */\n // // Working on a < or <= ineq\n // // Check if the value can be lowered.\n // //printf(\"Min leaving checkPreds for %s: %d\\n\",events[p]->event,min);\n /* (non-Javadoc)\n\t * @see java.lang.Object#clone()\n\t */\n @Override\n public Zone clone() {\n Zone clonedZone = new Zone();\n clonedZone._matrix = new int[this.matrixSize()][this.matrixSize()];\n for (int i = 0; i < this.matrixSize(); i++) {\n for (int j = 0; j < this.matrixSize(); j++) {\n clonedZone._matrix[i][j] = this._matrix[i][j];\n }\n }\n clonedZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n clonedZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();\n }\n clonedZone._hashCode = this._hashCode;\n clonedZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n clonedZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n return clonedZone;\n }\n\n /**\n * Restricts the lower bound of a timer.\n *\n * @param timer\n * \t\t\tThe timer to tighten the lower bound.\n */\n private void restrictTimer(int timer) {\n _matrix[dbmIndexToMatrixIndex(timer)][dbmIndexToMatrixIndex(0)] = getLowerBoundbydbmIndex(timer);\n }\n\n /**\n * Restricts the lower bound of a continuous variable. Also checks fixes\n * the upper bound to be at least as large if needed. This method\n * is usually used as a result of an event firing.\n * @param ltContPair\n * \t\tThe index of the continuous variable to restrict.\n * @param constant\n * \t\tThe constant value of the inequality event that is being used to update\n * \t\tthe variable indexed by ltContPair.\n */\n private boolean restrictContinuous(LPNContinuousPair ltContPair, int constant) {\n // It will be quicker to get the DBM index for the ltContPair one time.\n int variableIndex = timerIndexToDBMIndex(ltContPair);\n int zeroIndex = timerIndexToDBMIndex(LPNTransitionPair.ZERO_TIMER_PAIR);\n // Set the lower bound the variable (which is the DBM[variabl][0] entry.\n // Note : the lower bound in the zone is actually the negative of the lower\n // bound hence the -1 on the warpValue.\n setDbmEntry(variableIndex, zeroIndex, ContinuousUtilities.chkDiv(-1 * constant, ltContPair.getCurrentRate(), true));\n // Check if the upper bound needs to be advanced and advance it if necessary.\n if (getDbmEntry(zeroIndex, variableIndex) < ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true)) {\n // If the upper bound in the zones is less than the new restricting value, we\n // must advance it for the zone to remain consistent.\n setDbmEntry(zeroIndex, variableIndex, ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true));\n return true;\n }\n return false;\n }\n\n /**\n * Restricts the continuous variables in the zone according to the inequalities in a set of events.\n * @param eventSet\n * \t\t\tA set of inequality events. Does nothing if the event set does not contian inequalities.\n */\n private void restrictContinuous(EventSet eventSet) {\n // Check that the eventSet is a set of Inequality events.\n if (!eventSet.isInequalities()) {\n // If the eventSet is not a set of inequalities, do nothing.\n return;\n }\n HashSet adjustedColumns = new HashSet();\n boolean needsAdjusting = false;\n // Restrict the variables according to each of the inequalities in the eventSet.\n for (Event e : eventSet) {\n // Get the inequality.\n InequalityVariable iv = e.getInequalityVariable();\n // Extract the variable. I will assume the inequality only depends on a single\n Variable x = iv.getContVariables().get(0);\n // Extract the index.\n int lpnIndex = iv.get_lpn().getLpnIndex();\n // Extract the variable index.\n DualHashMap variableIndexMap = _lpnList[lpnIndex].getContinuousIndexMap();\n int variableIndex = variableIndexMap.getValue(x.getName());\n // Package it up for referencing.\n LPNContinuousPair ltContPair = new LPNContinuousPair(lpnIndex, variableIndex);\n // Need the current rate for the variable, grab the stored LPNContinuousPair.\n int zoneIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);\n if (zoneIndex > 0) {\n ltContPair = (LPNContinuousPair) _indexToTimerPair[zoneIndex];\n }\n // Perform the restricting.\n needsAdjusting = needsAdjusting | restrictContinuous(ltContPair, iv.getConstant());\n if (needsAdjusting) {\n adjustedColumns.add(ltContPair);\n }\n }\n // If one of the continuous variables has been moved forward, the other colmns\n // need to be adjusted to keep a consistent zone.\n if (needsAdjusting) {\n // At least one of the continuous variables has been moved forward,\n // so se need to ajust the bounds to keep a consistent zone.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltpair = _indexToTimerPair[i];\n if (adjustedColumns.contains(ltpair)) {\n // This continuous variables already had the upper bound\n continue;\n }\n // Add one to the upper bounds.\n setDbmEntry(0, i, getDbmEntry(0, i) + 1);\n }\n }\n }\n\n /**\n * Returns a zone that is the result from restricting the this zone according to a list of firing event inequalities.\n * @param eventSet\n * \t\tThe list of inequalities that are firing.\n * @return\n * \t\tThe new zone that is the result of restricting this zone according to the firing of the inequalities\n * \t\tin the eventSet.\n */\n @Override\n public Zone getContinuousRestrictedZone(EventSet eventSet, State[] localStates) {\n // Make a new copy of the zone.\n Zone z = this.clone();\n if (eventSet == null) {\n return z;\n }\n z.restrictContinuous(eventSet);\n return z;\n }\n\n /**\n * The list of enabled timers.\n * @return\n * \t\tThe list of all timers that have reached their lower bounds.\n */\n @Override\n public List getEnabledTransitions() {\n ArrayList enabledTransitions = new ArrayList();\n // Check if the timer exceeds its lower bound staring with the first nonzero\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n enabledTransitions.add(_lpnList[_indexToTimerPair[i].get_lpnIndex()].getTransition(_indexToTimerPair[i].get_transitionIndex()));\n }\n }\n return enabledTransitions;\n }\n\n /**\n * Gives the list of enabled transitions associated with a particular LPN.\n * @param LpnIndex\n * \t\t\tThe Index of the LPN the Transitions are a part of.\n * @return\n * \t\t\tA List of the Transitions that are enabled in the LPN given by the index.\n */\n @Override\n public List getEnabledTransitions(int LpnIndex) {\n ArrayList enabledTransitions = new ArrayList();\n // Check if the timer exceeds its lower bound staring with the first nonzero\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n if (ltPair.get_lpnIndex() == LpnIndex) {\n enabledTransitions.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));\n }\n }\n }\n return enabledTransitions;\n }\n\n /**\n * Find the next possible events.\n *\n * @param LpnIndex\n * \t\tThe index of the LPN that is of interest.\n * @param localState\n * \t\tThe state associated with the LPN indexed by LpnIndex.\n * @return\n * \t\tLpnTranList is populated with a list of\n * \t\tEventSets pertaining to the LPN with index LpnIndex. An EventSet can\n * \t\teither contain a transition to\n * \t\tfire or set of inequalities to change sign.\n */\n @Override\n public LpnTranList getPossibleEvents(int LpnIndex, State localState) {\n LpnTranList result = new LpnTranList();\n // Look through the timers and continuous variables. For the timers\n // determine if they are ready to fire. For the continuous variables,\n // look up the associated inequalities and see if any of them are ready\n // to fire.\n // We do not need to consider the zero timer, so start the\n // for loop at i=1 and not i=0.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // The enabled events are grouped with the LPN that they affect. So if\n // this pair does not belong to the current LPN under consideration, skip\n // processing it.\n if (ltPair.get_lpnIndex() != LpnIndex) {\n continue;\n }\n // If the index refers to a timer (and not a continuous variable) and has exceeded its lower bound,\n // then add the transition.\n if (!(ltPair instanceof LPNContinuousPair)) {\n // The index refers to a timer. Now check if time has advanced\n // far enough for the transition to fire.\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n Event e = new Event(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));\n result = addSetItem(this, result, e, localState);\n }\n } else {\n // The index refers to a continuous variable.\n // First check for a rate change event.\n LPNContinuousPair ltContPair = ((LPNContinuousPair) ltPair).clone();\n IntervalPair ratePair = getRateBounds(ltContPair);\n // // The rate represents a range of rates and no rate change\n // // event has occured.\n // // The rate contians zero, so we need to add two rate\n // // events: one for the lower bound and one for the upper\n // // Create the events.\n // // Add them to the result set.\n result = createRateEvents(this, ltContPair, ratePair, result, localState);\n // Check all the inequalities for inclusion.\n Variable contVar = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());\n if (contVar.getInequalities() != null) {\n for (InequalityVariable iv : contVar.getInequalities()) {\n // Check if the inequality can change.\n if (ContinuousUtilities.inequalityCanChange(this, iv, localState)) {\n result = addSetItem(this, result, new Event(iv), localState);\n }\n }\n }\n }\n }\n // Check the rate zero variables for possible rate change events.\n for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()) {\n // Get the reference object:\n LPNContinuousPair ltContPair = lcrPair.get_lcPair();\n // Extract the range of rates.\n IntervalPair ratePair = lcrPair.get_rateInterval();\n result = createRateEvents(this, ltContPair, ratePair, result, localState);\n }\n return result;\n }\n\n public static LpnTranList createRateEvents(Equivalence Z, LPNContinuousPair ltContPair, IntervalPair ratePair, LpnTranList result, State localState) {\n // // The rate represents a range of rates and no rate change\n // // event has occured.\n // // The rate contians zero, so we need to add two rate\n // // events: one for the lower bound and one for the upper\n // // Create the events.\n // // Add them to the result set.\n /*\n\t\t * Let [a,b] be the current range of rates for a given variable.\n\t\t * If a>=0, then we set the rate to b originally.\n\t\t * So if the current rate is b, then we have a rate change event to a.\n\t\t * \n\t\t * If b<=0, then we set the rate to a originially.\n\t\t * So if the current rate is a, then we have a rate change event to b.\n\t\t * \n\t\t * The final case to consider is when a < 0 and b > 0. If the current\n\t\t * rate is b, we allow rate changes to either a or 0. If the current\n\t\t * rate is a, we allow a rate change to zero.\n\t\t */\n if (ratePair.singleValue()) {\n // Rates that are not a range do not generate rate change events.\n return result;\n }\n ltContPair = ltContPair.clone();\n if (ratePair.get_LowerBound() >= 0) {\n if (ltContPair.getCurrentRate() == ratePair.get_UpperBound()) {\n ltContPair.setCurrentRate(ratePair.get_LowerBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n } else if (ratePair.get_UpperBound() <= 0) {\n if (ltContPair.getCurrentRate() == ratePair.get_LowerBound()) {\n ltContPair.setCurrentRate(ratePair.get_UpperBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n } else {\n if (ltContPair.getCurrentRate() == ratePair.get_UpperBound()) {\n // No rate change events have ocurred. So we allow one for zero\n // and the lower bounds rate.\n LPNContinuousPair ltContPairOther = ltContPair.clone();\n ltContPair.setCurrentRate(0);\n ltContPairOther.setCurrentRate(ratePair.get_LowerBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n result = addSetItem(Z, result, new Event(ltContPairOther), localState);\n } else if (ltContPair.getCurrentRate() == ratePair.get_LowerBound()) {\n // The rate has change to the lower bound. Allow one rate\n // change to zero.\n ltContPair.setCurrentRate(0);\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n }\n return result;\n }\n\n /**\n * Adds or removes items as appropriate to update the current\n * list of possible events. Note the type LpnTranList extends\n * LinkedList. The type EventSet extends transition\n * specifically so that objects of EventSet type can be place in\n * this list.\n * @param EventList\n * \t\t\tThe list of possible events.\n */\n public static LpnTranList addSetItem(Equivalence Z, LpnTranList E, Event e, State s) {\n // void lhpnAddSetItem(eventSets &E,lhpnEventADT e,ineqList &ineqL,lhpnZoneADT z,\n // lhpnStateADT cur_state)\n // Note the LPNTranList plays the role of the eventSets.\n int rv1l = 0, rv1u = 0, rv2l = 0, rv2u = 0, iZ, jZ;\n // printf(\"Event sets entering:\\n\");\n // Create the new LpnTranlist for holding the events.\n EventSet eSet = new EventSet();\n LpnTranList newE = new LpnTranList();\n boolean done = false;\n boolean possible = true;\n if (e.isRate()) {\n eSet.add(e);\n // I believe that I should actually copy over the old list\n // and then add the new event set.\n newE = E.copy();\n newE.addLast(eSet);\n // The previous two commands act to pass the changes of E\n // back out of the functions. So returning the new object\n // is suficient.\n // printf(\"Event sets leaving:\\n\");\n return newE;\n }\n if (e.isInequality()) {\n // Is this necessary, or even correct to update the inequalities.\n // System.out.println(\"Note the inequality is not being updated before in addSetItem\");\n // In this case the Event e represents an inequality.\n InequalityVariable ineq = e.getInequalityVariable();\n // Need to extract the rate.\n // To do this, I'll create the indexing object.\n Variable v = ineq.getContVariables().get(0);\n // Find the LPN.\n int lpnIndex = ineq.get_lpn().getLpnIndex();\n int varIndex = Z.getVarIndex(lpnIndex, v.getName());\n // Package it all up.\n // LPNTransitionPair ltPair =\n // Note : setting the rate is not necessary since\n // this is only being used as aan index.\n // LPNContinuousPair ltPair =\n LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);\n rv2l = ContinuousUtilities.chkDiv(-1 * ineq.getConstant(), Z.getCurrentRate(ltPair), true);\n rv2u = ContinuousUtilities.chkDiv(ineq.getConstant(), Z.getCurrentRate(ltPair), true);\n iZ = Z.getIndexByTransitionPair(ltPair);\n } else {\n // In this case, the event is a transition.\n Transition t = e.getTransition();\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n // Package the results.\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);\n iZ = Z.getIndexByTransitionPair(ltPair);\n }\n // Recall that E contains the events sets which are inherited from the Transition class\n // so they can be placed in an LpnTranList. So consider each event set.\n for (Transition es : E) {\n if (!(es instanceof EventSet)) {\n // This collection should contain event sets, not transitions.\n throw new IllegalArgumentException(\"The eventSet was a Transition object not an EventSet object.\");\n }\n EventSet eventSet = (EventSet) es;\n if (done) {\n // Copy any remaining sets into newE.\n newE.add(eventSet.clone());\n break;\n }\n EventSet workSet = eventSet.clone();\n // Get an iterator for the elements in the workset.\n for (Event oldEvent : eventSet) {\n // For matching code with atacs, note that oldEvent is 'j'.\n if (oldEvent.isRate()) {\n continue;\n }\n if (oldEvent.isInequality()) {\n // Again, is it necessary to do an update here?\n // System.out.println(\"Note the inequality is not being updated before in addSetItem\");\n // In this case the Event oldEvent represents an inequality.\n InequalityVariable ineq = oldEvent.getInequalityVariable();\n // Extract variable.\n Variable v = ineq.getContVariables().get(0);\n // Find the LPN.\n int lpnIndex = ineq.get_lpn().getLpnIndex();\n int varIndex = Z.getVarIndex(lpnIndex, v.getName());\n // Package it all up.\n // LPNTransitionPair ltPair =\n // Note : setting the rate is not necessary since this is\n // only being used as an index.\n // LPNContinuousPair ltPair =\n LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);\n rv1l = ContinuousUtilities.chkDiv(-1 * oldEvent.getInequalityVariable().getConstant(), Z.getCurrentRate(ltPair), true);\n rv1u = ContinuousUtilities.chkDiv(oldEvent.getInequalityVariable().getConstant(), Z.getCurrentRate(ltPair), true);\n jZ = Z.getIndexByTransitionPair(ltPair);\n } else {\n // In this case, the event is a transition.\n Transition t = oldEvent.getTransition();\n // Create the indexing object. (See the Abstraction Function protion at the\n // top of the class for more details.)\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n // Package the results.\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);\n jZ = Z.getIndexByTransitionPair(ltPair);\n }\n // /* Both actions are predicate changes */\n // Both actions are predicate changes.\n if (e.isInequality() && oldEvent.isInequality()) {\n // /* Both predicates are on the same variable */\n // Extract the variable lists.\n ArrayList newList = e.getInequalityVariable().getContVariables();\n ArrayList oldList = oldEvent.getInequalityVariable().getContVariables();\n // Issue a warning if one of the lists has more than a single\n if (newList.size() > 1 && oldList.size() > 1) {\n System.err.println(\"Warning: One of the inequalities \" + e + \" \" + oldEvent + \" refers to more than one variable\");\n }\n // Both inequalities are on the same variables.\n if (newList.get(0).equals(oldList.get(0))) {\n if (rv1l > rv2l) {\n possible = false;\n } else // printf(\"Adding to erase list: \\n\");\n if (rv2l > rv1l) {\n workSet.remove(oldEvent);\n } else // printf(\"Adding to erase list: \\n\");\n if (rv1u > rv2u) {\n workSet.remove(oldEvent);\n } else {\n workSet.add(e);\n done = true;\n }\n } else // /* Predicates are on different variables */\n // Inequalities are on different variables.\n {\n // TODO : Check that the indecies must be reversed. I believe\n // they do since I think my representation is the transpose\n // of atacs. This will affect all the following statements.\n if (rv1l > rv2l + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else // printf(\"Adding to erase list: \");\n if (rv2l > rv1l + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n } else // printf(\"Adding to erase list: \\n\");\n if (rv1u > Z.getUpperBoundTrue(iZ) + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n } else if (rv2u > Z.getUpperBoundTrue(jZ) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else if (rv1l == rv2l + Z.getDbmEntry(jZ, iZ) && rv2l == rv1l + Z.getDbmEntry(iZ, jZ) && rv1u == rv2u + Z.getDbmEntry(iZ, jZ) && rv2u == rv1u + Z.getDbmEntry(jZ, iZ)) {\n workSet.add(e);\n }\n }\n } else // /* New action is predicate change, old is transition firing (case 3) */\n // New action is an inequality and the old even tis a transition (case 3).\n if (e.isInequality() && oldEvent.isTransition()) {\n // printf(\"Adding to erase list: \\n\");\n if (rv2l > -1 * Z.getLowerBoundbyTransition(e.getTransition()) + Z.getDbmEntry(iZ, jZ)) {\n // Probably can change this to refer directly to the zone.\n workSet.remove(oldEvent);\n } else if (rv2u > Z.getUpperBoundTrue(jZ) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n }\n } else // /* TODO: One more ugly case, is it needed? */\n // /* New action is transition firing, old is predicate change (case 4) */\n // New event is a transition firing, old event is an inequality change (case 4).\n if (e.isTransition() && oldEvent.isInequality()) {\n if (rv1l > (-1) * Z.getLowerBoundbyTransition(e.getTransition()) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else // printf(\"Adding to erase list: \\n\");\n // Real one: fix the getting of the upper and lower bounds. Done\n if (rv1u > Z.getUpperBoundTrue(iZ) + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n }\n // /* TODO: one more ugly case, is it needed? */\n // I guess this one wasn't needed since it is not found in atacs.\n }\n }\n if (!(workSet.isEmpty())) {\n newE.add(workSet);\n }\n }\n // This part of the code is essentially copying the all the old event set into the new event set.\n // There might be a way around doing this by working directly on the set to begin with.\n // Moved to being done at the begining of the previous block.\n // // This collection should contain event sets, not transitions.\n // throw new IllegalArgumentException(\"The eventSet was a Transition object not an EventSet object.\");\n if (!done && possible) {\n eSet.add(e);\n newE.add(eSet);\n }\n E = newE;\n // printf(\"Event sets leaving:\\n\");\n return E;\n }\n\n @Override\n public int getVarIndex(int lpnIndex, String name) {\n return _lpnList[lpnIndex].getContinuousIndexMap().getValue(name);\n }\n\n /**\n * Adds a set item and explicitly sets a flag to remove the next set item\n * upon firing.\n * @param E\n * The list of current event sets.\n * @param e\n * The event to add.\n * @param s\n * The current state.\n * @param removeNext\n * True if afer firing this event, the next event should be removed from the\n * queue.\n * @return\n * The new event set.\n */\n // public static LpnTranList addSetItem(LpnTranList E, Event e, State s,\n /**\n * Updates the continuous variables that are set by firing a transition.\n * @param firedTran\n * \t\tThe transition that fired.\n * @param s\n * \t\tThe current (local) state.\n */\n public void updateContinuousAssignment(Transition firedTran, State s) {\n // Get the LPN.\n LPN lpn = _lpnList[firedTran.getLpn().getLpnIndex()];\n // Get the current values of the (local) state.\n HashMap currentValues = lpn.getAllVarsWithValuesAsString(s.getVariableVector());\n // Get all the continuous variable assignments.\n HashMap assignTrees = firedTran.getContAssignTrees();\n for (String contVar : assignTrees.keySet()) {\n // Get the bounds to assign the continuous variables.\n IntervalPair assignment = assignTrees.get(contVar).evaluateExprBound(currentValues, this, null);\n // Make the assignment.\n setContinuousBounds(contVar, lpn, assignment);\n }\n }\n\n /**\n * Updates the continuous variables according to the given values.\n * @param newContValues\n * \t\tThe new values of the continuous variables.\n */\n public void updateContinuousAssignment(ContinuousRecordSet newAssignValues) {\n /*\n\t\t * In dealing with the rates and continuous variables, there are four cases to consider. These cases\n\t\t * depend on whether the the old value of the 'current rate' is zero or non-zero and whether the\n\t\t * new value of the 'current rate' is zero or non-zero. \n\t\t * 0. old rate is zero, new rate is zero.\n\t\t * \t\tLookup the zero rate in the _rateZeroContinuous and add any new continuous assignments.\n\t\t * 1. old rate is zero, new rate is non-zero.\n\t\t * \t\tRemove the rate from the _rateZeroContinuous and add the zone.\n\t\t * 2. old rate is non-zero, new rate is zero.\n\t\t * \t\tAdd the variable with its upper and lower bounds to _rateZeroContinuous.\n\t\t * 3. old rate is non-zero, new rate is non-zero.\n\t\t * \t\tGet the LPNContinuousPair from the _indexToTimerPair and change the value.\n\t\t * \n\t\t * Note: If an assignment is made to the variable, then it should be considered as a\n\t\t * new variable.\n\t\t */\n // The updating of the rate-zero continuous variables is taken care of\n // by the copyRates. So just need to update the values in the zone.\n // This amounts to copying over the values from the old zone for\n // continuous variables that haven't changed and copying in\n // // Set the lower bound.\n // // Set the upper bound.\n // // Set the rate.\n // // Set the lower bound.\n // // Set the upper bound.\n // // Set the current rate.\n // // Set the upper and lower bounds for the rates.\n }\n\n /* (non-Javadoc)\n\t * @see verification.timed_state_exploration.zone.Zone#getLexicon()\n\t */\n /**\n * Gives an array that maps the index of a timer in the DBM to the timer's index.\n * @return\n * \t\tThe array that maps the index of a timer in the DBM to the timer's index.\n */\n /**\n * Calculates a warping value needed to warp a Zone. When a zone is being warped the form\n * r1*z2 - r1*z1 + r2*z1 becomes important in finding the new values of the zone. For example,\n *\n * @param z1\n * \t\tUpper bound or negative lower bound.\n * @param z2\n * \t\tRelative value.\n * @param r1\n * \t\tFirst ratio.\n * @param r2\n * \t\tSecond ratio.\n * @return\n * \t\tr1*z2 - r1*z1 + r2*z1\n */\n public static int warp(int z1, int z2, int r1, int r2) {\n /*\n\t\t * See \"Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets\"\n\t\t * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda\n\t\t * Section III.C for details on how this function is used and where it comes\n\t\t * from.\n\t\t */\n return r1 * z2 - r1 * z1 + r2 * z1;\n }\n\n /**\n * Warps this Zone with the aid of rate information from the previous Zone.\n *\n * @param oldZone\n * \t\tThe previous Zone.\n * @return\n * \t\tThe warped Zone.\n */\n @Override\n public void dbmWarp(Equivalence oldE) {\n Zone oldZone = (Zone) oldE;\n /*\n\t\t * See \"Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets\"\n\t\t * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda\n\t\t * Section III.C for details on how this function is used and where it comes\n\t\t * from.\n\t\t */\n // /* TODO: This appears to NOT work when INFIN is in the bounds?\n // Should I have to worry about this case? */\n // According to atacs comments, this appears to NOT work when\n // INFIN is in the bounds.\n // This portion of the code handles the warping of the relative\n // parts of the zone.\n for (int i = 1; i < dbmSize(); i++) {\n for (int j = i + 1; j < dbmSize(); j++) {\n double iVal, jVal, iWarp, jWarp, iXDot, jXDot;\n // Note : the iVal and the jVal correspond to the\n // alpha and beta describe in Scott Little's thesis.\n // /* deal w/ the fact that we might have continuous and discrete\n // Do some warping when dealing with the continuous variables.\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n // Calcualte the alpha value.\n iVal = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[i]) / (double) this.getCurrentRate(_indexToTimerPair[i])));\n // The old rate the zone was warped by.\n iWarp = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[i])));\n // The current rate rate of this continuous variable.\n iXDot = Math.floor(Math.abs((double) this.getCurrentRate(_indexToTimerPair[i])));\n // I'm not going to do any warping when the previous rate\n // is zero. This statement is a break to go to next i value\n // and not the next j.\n if (iWarp == 0) {\n break;\n }\n } else {\n // The current variable is a timer, so the new rate and old rate\n // are both 1. Hence we have\n iVal = 1.0;\n iWarp = 1.0;\n iXDot = 1.0;\n }\n // Do some warping of the second variable if it is a continuous variable.\n if (_indexToTimerPair[j] instanceof LPNContinuousPair) {\n // Calcualte the alpha value.\n jVal = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[j]) / (double) this.getCurrentRate(_indexToTimerPair[j])));\n // The old rate the zone was warped by.\n jWarp = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[j])));\n // The current rate of this continuous variable.\n jXDot = Math.floor(Math.abs((double) this.getCurrentRate(_indexToTimerPair[j])));\n // I'm not going to do any warping when the previous rate is\n if (jWarp == 0) {\n continue;\n }\n } else {\n // The current variable is a timer, so the new rate and old rate\n // are both 1. Hence we have\n jVal = 1.0;\n jWarp = 1.0;\n jXDot = 1.0;\n }\n // The zone is warped differently depending on which of rate is\n // larger. See Scott Little's Thesis for more details.\n if (iWarp * jXDot > jWarp * iXDot) {\n setDbmEntry(j, i, (int) Math.ceil(((jWarp * getDbmEntry(j, i)) / jXDot) + ((-1 * jWarp * getDbmEntry(0, i) / jXDot)) + ((iWarp * getDbmEntry(0, i) / iXDot))));\n setDbmEntry(i, j, (int) Math.ceil(((jWarp * getDbmEntry(i, j)) / jXDot) + ((-1 * jWarp * getDbmEntry(i, 0) / jXDot)) + ((iWarp * getDbmEntry(i, 0) / iXDot))));\n } else {\n setDbmEntry(i, j, (int) Math.ceil(((iWarp * getDbmEntry(i, j)) / iXDot) + ((-1 * iWarp * getDbmEntry(0, j) / iXDot)) + ((jWarp * getDbmEntry(0, j) / jXDot))));\n setDbmEntry(j, i, (int) Math.ceil(((iWarp * getDbmEntry(j, i)) / iXDot) + ((-1 * iWarp * getDbmEntry(j, 0) / iXDot)) + ((jWarp * getDbmEntry(j, 0) / jXDot))));\n }\n }\n }\n // printf(\"After fixing up initial warp conditions.\\n\");\n // Handle the warping of the bounds.\n for (int i = 1; i < dbmSize(); i++) {\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n if (Math.abs(getDbmEntry(i, 0)) != INFINITY) {\n if (oldZone.getCurrentRate(_indexToTimerPair[i]) == 0) {\n // If the older rate was zero, then we just need to\n // divide by the new rate.\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(getDbmEntry(i, 0), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n } else {\n // Undo the old warping and introduce the new warping.\n // If the bound is infinite, then division does nothing.\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i])) * getDbmEntry(i, 0), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n }\n }\n if (Math.abs(getDbmEntry(0, i)) != INFINITY) {\n if (oldZone.getCurrentRate(_indexToTimerPair[i]) == 0) {\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(getDbmEntry(0, i), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n } else {\n // Undo the old warping and introduce the new warping.\n // If the bound is inifite, then division does nothing.\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i])) * getDbmEntry(0, i), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n }\n }\n }\n }\n // printf(\"After fixing up places.\\n\");\n for (int i = 1; i < dbmSize(); i++) {\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n // /* TBD: If i & j are both changing direction do we need to\n // remove the warp info? */\n // Handle the case when the warping takes us into negative space.\n if ((double) oldZone.getCurrentRate(_indexToTimerPair[i]) / (double) this.getCurrentRate(_indexToTimerPair[i]) < 0.0) {\n /* We are warping into the negative space, so swap the upper and \n\t\t\t\t\t * lower bounds.\n\t\t\t\t\t */\n int temp = getDbmEntry(i, 0);\n setDbmEntry(i, 0, getDbmEntry(0, i));\n setDbmEntry(0, i, temp);\n // Set the relationships to Infinity since nothing else is known.\n for (int j = 1; j < dbmSize(); j++) {\n if (i != j) {\n setDbmEntry(i, j, INFINITY);\n setDbmEntry(j, i, INFINITY);\n }\n }\n }\n }\n }\n // printf(\"After handling negative warps.\\n\");\n /* Do the nature of how I store things, I do not think I need to do\n\t\t\t * this portion.\n\t\t\t */\n }\n\n /**\n * The DiagonalNonZeroException extends the java.lang.RuntimerExpcetion.\n * The intention is for this exception to be thrown is a Zone has a non zero\n * entry appear on the diagonal.\n *\n * @author Andrew N. Fisher\n */\n public class DiagonalNonZeroException extends java.lang.RuntimeException {\n\n private static final long serialVersionUID = -3857736741611605411L;\n\n /**\n * Creates a DiagonalNonZeroException.\n * @param Message\n * \t\t\tThe message to be displayed when the exception is thrown.\n */\n public DiagonalNonZeroException(String Message) {\n super(Message);\n }\n }\n\n /**\n * This exception is thrown when trying to merge two zones whose corresponding timers\n * do not agree.\n * @author Andrew N. Fisher\n */\n // // TODO : Check if this class can be removed.\n // * Generated serialVersionUID\n /**\n * Clears out the lexicon.\n */\n public static IntervalPair parseRate(String rate) {\n String rateNoSpaces = rate.trim();\n // First check if the string is a single number.\n // // The string is a number, so set the upper and lower bounds equal.\n // First check for a comma (representing an interval input).\n int commaIndex = rateNoSpaces.indexOf(\",\");\n if (commaIndex < 0) {\n // Assume that the string is a constant. A NumberFormatException\n // will be thrown otherwise.\n int i = Integer.parseInt(rate);\n return new IntervalPair(i, i);\n }\n String lowerString = rateNoSpaces.substring(1, commaIndex).trim();\n String upperString = rateNoSpaces.substring(commaIndex + 1, rateNoSpaces.length() - 1).trim();\n return new IntervalPair(Integer.parseInt(lowerString), Integer.parseInt(upperString));\n }\n\n /**\n * Get the list of LhpnFile objects that this Zone depends on.\n * @return\n * \t\tThe lits of LhpnFile objects that this Zone depends on.\n */\n @Override\n public LPN[] get_lpnList() {\n return _lpnList;\n }\n\n /**\n * Performs a division of two integers and either takes the ceiling or the floor. Note :\n * The integers are converted to doubles for the division so the choice of ceiling or floor is\n * meaningful.\n * @param top\n * \t\tThe numerator.\n * @param bottom\n * \t\tThe denominator.\n * @param ceil\n * \t\tTrue indicates return the ceiling and false indicates return the floor.\n * @return\n * \t\tReturns the ceiling of top/bottom if ceil is true and the floor of top/bottom otherwise.\n */\n // * This method was taken from atacs/src/hpnrsg.c\n // System.out.println(\"Warning: Divided by zero.\");\n /**\n * Returns the current rate of the variable.\n * @param contVar\n * \t\tThe LPNTransitionPair referring to a continuous variable.\n * @return\n * \t\tThe current rate of the continuous variable refenced by the LPNTransitionPair.\n * @throws IllegalArgumentException\n * \t\tIf the LPNTransitionPair is not an instance of an LPNContinuousPair.\n */\n @Override\n public int getCurrentRate(LPNTransitionPair contVar) {\n if (!(contVar instanceof LPNContinuousPair)) {\n // The LPNTransitionsPair does not refer to a continuous variable, so yell.\n throw new IllegalArgumentException(\"Zone.getCurrentRate was called\" + \" on an LPNTransitionPair that was not an LPNContinuousPair.\");\n }\n LPNContinuousPair cV = (LPNContinuousPair) contVar;\n // Search for the pair in the zone.\n int index = Arrays.binarySearch(_indexToTimerPair, cV);\n if (index > 0) {\n // The continuous variable was found amongst the non zero rate continuous variables.\n // Grab that indexing object instead since it has the rate.\n cV = (LPNContinuousPair) _indexToTimerPair[index];\n return cV.getCurrentRate();\n }\n // Since the variable was not found in the non-zero rate continuous\n // variables, assume the rate is zero.\n return 0;\n }\n\n /**\n * Sets the current rate for a continuous variable. It sets the rate regardless of\n * whether the variable is in the rate zero portion of the Zone or not. But it\n * does not move variables in and out of the zone.\n * @param contVar\n * \t\tThe index of the variable whose rate is going to be set.\n * @param currentRate\n * \t\tThe value of the rate.\n */\n @Override\n public void setCurrentRate(LPNTransitionPair contVar, int currentRate) {\n if (!(contVar instanceof LPNContinuousPair)) {\n // The LPNTransitionsPair does not refer to a continuous variable, so yell.\n throw new IllegalArgumentException(\"Zone.getCurrentRate was called\" + \" on an LPNTransitionPair that was not an LPNContinuousPair.\");\n }\n LPNContinuousPair cV = (LPNContinuousPair) contVar;\n // Check for the current variable in the rate zero variables.\n VariableRangePair variableRange = _rateZeroContinuous.getValue(new LPNContAndRate(cV, new IntervalPair(0, 0)));\n if (variableRange != null) {\n LPNContinuousPair lcPair = _rateZeroContinuous.getKey(variableRange).get_lcPair();\n lcPair.setCurrentRate(currentRate);\n return;\n }\n // Check for the current variable in the Zone variables.\n int index = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (index >= 0) {\n // The variable was found, set the rate.\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[index];\n lcPair.setCurrentRate(currentRate);\n }\n }\n\n /**\n * Adds a transition to a zone.\n * @param newTransitions\n * \t\t\tThe newly enabled transitions.\n * @return\n * \t\t\tThe result of adding the transition.\n */\n @Override\n public Zone addTransition(HashSet newTransitions, State[] localStates) {\n /*\n\t\t * The zone will remain the same for all the continuous variables.\n\t\t * The only thing that will change is a new transition will be added into the transitions.\n\t\t */\n // Create a Zone to alter.\n Zone newZone = new Zone();\n // Create a copy of the LPN list.\n newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n // Copy the rate zero continuous variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Create a copy of the current indexing pairs.\n newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + newTransitions.size()];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = _indexToTimerPair[i];\n }\n // Add the new transitions to the _indexToTimerPair list.\n // // Set up the index for the newTransitions list.\n int i = _indexToTimerPair.length;\n for (LPNTransitionPair ltPair : newTransitions) {\n newZone._indexToTimerPair[i++] = ltPair;\n }\n // Sort the _indexToTimerPair list.\n Arrays.sort(newZone._indexToTimerPair);\n // Create matrix.\n newZone._matrix = new int[newZone._indexToTimerPair.length + 1][newZone._indexToTimerPair.length + 1];\n // Convert the current transitions to a collection of transitions.\n HashSet oldTransitionSet = new HashSet();\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n oldTransitionSet.add(ltPair);\n }\n // Copy in the new transitions.\n newZone.copyTransitions(this, newTransitions, oldTransitionSet, localStates);\n return newZone;\n }\n\n /**\n * This method creates a zone identical to the current zone except all the current rates are turned to 1.\n * This is to provide a previous zone to the initial zone for warping.\n * @return\n * \t\tA zone identical to this zone with all rates set to 1.\n */\n private Zone beforeInitialZone() {\n Zone z = this.clone();\n for (int i = 1; i < z._indexToTimerPair.length; i++) {\n if (!(z._indexToTimerPair[i] instanceof LPNContinuousPair)) {\n break;\n }\n LPNContinuousPair lcPair = (LPNContinuousPair) z._indexToTimerPair[i];\n lcPair.setCurrentRate(1);\n }\n return z;\n }\n\n /**\n * Add a rate zero variable to the DBM portion of the zone. This method\n * is intended as an aid for when a rate zero variable gets assign a\n * non-zero rate.\n * @param ltContPair The continuous variable to move from the rate zero\n * variables.\n * @return The resulting Zone.\n */\n @Override\n public Zone moveOldRateZero(LPNContinuousPair ltContPair) {\n // Create a Zone to alter.\n Zone newZone = new Zone();\n // Create a copy of the LPN list.\n newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n // Copy the rate zero continuous variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Extract the continuous variable from the rate zero variables.\n LPNContAndRate rateZero = new LPNContAndRate(ltContPair, new IntervalPair(0, 0));\n // This gets the values for the continuous variable.\n VariableRangePair vrp = newZone._rateZeroContinuous.get(rateZero);\n IntervalPair values = vrp.get_range();\n // This replaces the rateZero with the one stored in the _rateZeroContinuous.\n // The purpose of this is to obtain the stored range of rates.\n rateZero = newZone._rateZeroContinuous.getKey(vrp);\n // Get the range of rates.\n IntervalPair rangeOfRates = rateZero.get_rateInterval();\n // Remove the continuous variable.\n newZone._rateZeroContinuous.delete(rateZero);\n // Create a copy of the current indexing pairs.\n newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + 1];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = _indexToTimerPair[i];\n }\n // Add the continuous variable to the list of variables/transition in the DBM.\n int numOfTransitions = _indexToTimerPair.length;\n newZone._indexToTimerPair[numOfTransitions] = ltContPair;\n // Sort the _indexToTimerPair list.\n Arrays.sort(newZone._indexToTimerPair);\n // Create matrix.\n newZone._matrix = new int[newZone._indexToTimerPair.length + 1][newZone._indexToTimerPair.length + 1];\n // Convert the current transitions to a collection of transitions.\n HashSet oldTransitionSet = new HashSet();\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n oldTransitionSet.add(ltPair);\n }\n // Copy in the new transitions.\n newZone.copyTransitions(this, new HashSet(), oldTransitionSet, null);\n // Get the index for the variable.\n int index = Arrays.binarySearch(newZone._indexToTimerPair, ltContPair);\n // Copy in the upper and lower bound of the old rate zero variable.\n // Copy in the range of rates.\n newZone.setLowerBoundbydbmIndex(index, rangeOfRates.get_LowerBound());\n newZone.setUpperBoundbydbmIndex(index, rangeOfRates.get_UpperBound());\n if (ltContPair.getCurrentRate() > 0) {\n // Set the upper and lower bounds.\n newZone.setDbmEntry(0, index, ContinuousUtilities.chkDiv(values.get_UpperBound(), ltContPair.getCurrentRate(), true));\n newZone.setDbmEntry(index, 0, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), ltContPair.getCurrentRate(), true));\n } else {\n // Set the upper and lower bounds. Since the rate is zero\n // We swap the real upper and lower bounds.\n newZone.setDbmEntry(0, index, ContinuousUtilities.chkDiv(values.get_LowerBound(), ltContPair.getCurrentRate(), true));\n newZone.setDbmEntry(index, 0, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), ltContPair.getCurrentRate(), true));\n }\n // Set the DBM to having no relating information for how this\n // variables relates to the other variables.\n for (int i = 1; i < newZone._indexToTimerPair.length; i++) {\n if (i == index) {\n continue;\n }\n newZone.setDbmEntry(index, i, Zone.INFINITY);\n newZone.setDbmEntry(i, index, Zone.INFINITY);\n }\n newZone.recononicalize();\n return newZone;\n }\n\n /**\n * This method removes the variable from the DBM portion of the\n * zone and adds the variable to the rate-zero portion of the\n * zone. The purpose of this method is to handle when a non-zero\n * rate variable is assigned a zero rate.\n * @param firedRate The new assignment for the variable.\n * @return The resulting zone.\n */\n @Override\n public Zone saveOutZeroRate(LPNContinuousPair firedRate) {\n // Check if the variable is in the zone.\n // We assume that the rate is already zero in this case\n // since it must be in the rate zero variables if it exists.\n int index = Arrays.binarySearch(this._indexToTimerPair, firedRate);\n if (index < 0) {\n System.err.println(\"A variable is getting its rate set to zero\");\n System.err.println(\"when the rate is already zero.\");\n return this;\n }\n // Create new zone\n Zone newZone = new Zone();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n // Copy over the rate zero variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Get the range of rates and values.\n IntervalPair rangeOfRates = this.getRateBounds(firedRate);\n IntervalPair rangeOfValues = this.getContinuousBounds(firedRate);\n // Create the key and value pairs for the rate zero continuous variable.\n LPNContAndRate lcar = new LPNContAndRate(firedRate.clone(), rangeOfRates);\n VariableRangePair vrPair = new VariableRangePair(this._lpnList[firedRate.get_lpnIndex()].getContVar(firedRate.get_ContinuousIndex()), rangeOfValues);\n newZone._rateZeroContinuous.insert(lcar, vrPair);\n // Copy over the pairs, skipping the new rate zero.\n newZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length - 1];\n int offset = 0;\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n if (i == index) {\n offset++;\n }\n newZone._indexToTimerPair[i] = this._indexToTimerPair[i + offset].clone();\n }\n // Copy over the DBM\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n int offseti = 0;\n int offsetj = 0;\n for (int i = 0; i < newZone.matrixSize(); i++) {\n if (i == index + 1) {\n offseti++;\n }\n offsetj = 0;\n for (int j = 0; j < newZone.matrixSize(); j++) {\n if (j == index + 1) {\n offsetj++;\n }\n newZone._matrix[i][j] = this._matrix[i + offseti][j + offsetj];\n }\n }\n return newZone;\n }\n\n @Override\n public int getIndexByTransitionPair(LPNTransitionPair ltPair) {\n return Arrays.binarySearch(_indexToTimerPair, ltPair);\n }\n /**\n * Determines whether time has advanced far enough for an inequality to change\n * truth value.\n * @param ineq\n * \t\tThe inequality to test whether its truth value can change.\n * @param localState\n * \t\tThe state associated with the inequality.\n * @return\n * \t\tTrue if the inequality can change truth value, false otherwise.\n */\n // // Find the index of the continuous variable this inequality refers to.\n // // I'm assuming there is a single variable.\n // // Package up the information into a the index. Note the current rate doesn't matter.\n // // Get the current rate.\n // // Get the current value of the inequality. This requires looking into the current state.\n // // Get the Zone index of the variable.\n // //\t\tbool lhpnPredCanChange(ineqADT ineq,lhpnZoneADT z,lhpnRateADT r,\n // //warn(\"An inequality produced a place not in the zone.\");\n // // First check cases when the rate is negative.\n // //warn(\"An inequality produced a place not in the zone.\");\n}\n"} {"task_id": "Java_3035", "language": "Java", "task_type": "single_line", "source_file": "java/github/MyersResearchGroup/iBioSim/verification/src/main/java/edu/utah/ece/async/lema/verification/timed_state_exploration/zoneProject/Zone.java", "mask_start_position": 54362, "mask_end_position": 54376, "canonical_solution": "dex(dbmIndex);", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * This file is part of iBioSim. Please visit \n * for the latest version of iBioSim.\n *\n * and also available online at .\n *\n * *****************************************************************************\n */\npackage edu.utah.ece.async.lema.verification.timed_state_exploration.zoneProject;\n\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport edu.utah.ece.async.lema.verification.lpn.ExprTree;\nimport edu.utah.ece.async.lema.verification.lpn.LPN;\nimport edu.utah.ece.async.lema.verification.lpn.Transition;\nimport edu.utah.ece.async.lema.verification.lpn.Variable;\nimport edu.utah.ece.async.lema.verification.platu.main.Options;\nimport edu.utah.ece.async.lema.verification.platu.platuLpn.DualHashMap;\nimport edu.utah.ece.async.lema.verification.platu.platuLpn.LpnTranList;\nimport edu.utah.ece.async.lema.verification.platu.stategraph.State;\nimport edu.utah.ece.async.lema.verification.timed_state_exploration.octagon.Equivalence;\n\n/**\n * This class is for storing and manipulating the delay information for transitions as well as\n * the values of continuous variables including rate their rates.\n * A Zone represents the non-zero continuous variables and the timers for the delay in a\n * Difference Bound Matrix (DBM)\n *\n * t0 c0 c1 t0 t1\n * t0 m00 m01 m02 m03 m04\n * c0 m10 m11 m12 m13 m14\n * c1 m20 m21 m22 m23 m24\n * t0 m30 m31 m32 m33 m34\n * t1 m40 m41 m42 m43 m44\n *\n * For the timers, tj - ti <= m(ti,tj) where m(ti,tj) represents the element of the matrix with\n * row ti and column tj. In particular, m(t0,ti) is an upper bound for ti and -m(ti,0) is a\n * lower bound for ti. The continuous variables are normalized to have rate one before being\n * placed in the matrix. Thus for a continuous variables ci with rate ri, the entry m(t0, ci) is\n * (upper bound)/ri where 'upper bound' is the upper bound for the continuous variable and\n * m(ci,t0) is -1*(lower bound)/ri where 'lower bound' is the lower bound of the continuous variable.\n * When the rate is negative, dividing out by the rate switches the inequalities. For example,\n * if ci is a continuous variable such that l < ci < u for some values l and u, then the normalized\n * ci (that is ci/ri) is satisfies u/ri < ci/r < l/ri. Hence the m(t0,ci) is (lower bound)/ri and\n * m(ci,0) is -1*(upper bound)/ri. The m(ci,cj) as well as m(ti,ci) and m(ci,ti) give the same kind\n * of relational information as with just timers, but with the normalized values of the continuous\n * variables. Note that a Zone with normalized continuous variables is referred to as being a 'warped'\n * zone.\n *\n * The rate zero continuous variables are also stored in a Zone object, but they are not present in\n * the zone. The Zone merely records the range of the continuous variable.\n *\n * The timers are referenced by the name of the transition that they are associated with and continuous\n * variables are referenced by their name as well. In addition for non-zero rate continuous variables and\n * the timers, several method will allow them to be referred by their index as a part of the (DMB). For\n * example, c0 in the above DBM example, has index 1.\n *\n * A third way that the timers and variables (both rate zero and rate non-zero) can be referred to by\n * an LPNTransitionPair object. These objects refer to a timer or continuous variable by providing the index\n * of the corresponding transition or the index of the continuous variable as a member of an LPN and the\n * index of that LPN. The LPNTransitionPair can be made more specific in the case of the continuous variables\n * by using an LPNContinuousPair. These objects also provide the rate of the variable. LPNTransitionPairs\n * can be used with continuous variables when they are only being used as an index only. If the rate is needed\n * for the method, then LPNContinuousPairs must be used.\n *\n * @author Andrew N. Fisher\n * @author Chris Myers\n * @author iBioSim Contributors \n * @version %I%\n */\npublic class Zone implements Equivalence {\n\n /*Abstraction Function : \n\t* The difference bound matrix is stored in the _matrix member field, along with \n\t* the upper and lower bounds of the timers and rates for continuous variables.\n\t* The upper and lower bounds are stored when the timer becomes enabled. The upper and\n\t* lower bounds of the rates are stored when the rate is assigned. The upper and lower \n\t* bounds are stored in the first row and first column of the _matrix member field.\n\t* The DBM occupies the rest of the array, that is, the sub-array formed by removing\n\t* the first column and first row.\n\t* For example, let t1 be a timer for a transition whose delay is between 2 and 3. Further\n\t* let c1 be a continuous variable with rate between 4 and 5. Then _matrix would look like\n\t* lb t0 c1 t1\n\t* ub x 0 5 3\n\t* t0 0 m m m\n\t* c1 -4 m m m\n\t* t1 -2 m m m\n\t* \n\t* with out the lb, ub, t0, t1, and c1.\n\t* \n\t* The x is does not represent anything and will most likely be zero. The upper and lower \n\t* bounds for the zero timer (which is always present) are always 0. The m's comprise \n\t* the DBM.\n\t* \n\t* For the most part, a timer or a continuous variable is referred to internally by an\n\t* LPNTransitionPair. An LPNTransitionPair combines the index of the transition (or\n\t* continuous variable) with the index of the LPN that the transition (or continuous \n\t* variables) is a member of. Both continuous variables and transitions can be referred\n\t* to by an LPNTransitionPair; however, it is better to use an LPNContinuousPair (which\n\t* is inherited from the LPNTransitionPair) to refer to continuous variables.\n\t* LPNContinuousPairs are used to distinguish continuous variables from transitions. They \n\t* also store the current rate of the continuous variable. \n\t* \n\t* The LPNTransitionPairs are stored in the _indexToTimerPair member field. The row/column\n\t* in the DBM for a transition is determined by the its position in this array. For example,\n\t* suppose a transition t has an LPNTransitionPair ltTranPair that is the third element of\n\t* the _indexToTimerPair. Then t will be the third column/row of the DBM.\n\t* \n\t* Continuous variables are handled slightly differently. The LPNContinuousPair for the \n\t* continuous variables with a non-zero rate are stored in the _indexToTimerPair just as \n\t* with the transitions. And just like with the transitions, the index in the DBM is\n\t* determined by the index of the LPNContinuousPair in the _indexToTimerPair. However,\n\t* rate zero continuous variables are stored in the _rateZeroContinuous member variable.\n\t* The _rateZerContinuous pairs an LPNContinuousPair with a VariableRangePair. The\n\t* VariableRangePair combines the variable with its upper and lower bound.\n\t* \n\t*/\n /* Representation invariant :\n\t* Zones are immutable.\n\t* Integer.MAX_VALUE is used to logically represent infinity.\n\t* The lb and ub values for a timer should be set when the timer is enabled.\n\t* A negative hash code indicates that the hash code has not been set.\n\t* The index of the timer in _indexToTimer is the index in the DBM and should contain\n\t* \tthe zeroth timer.\n\t* The array _indexToTimerPair should always be sorted.\n\t* The index of the LPN should match where it is in the _lpnList, that is, if lpn is\n\t* \tand LhpnFile object in _lpnList, then _lpnList[getLpnIndex()] == lpn.\n\t* The LPNTransitionPair in the _indexToTimer array should be an LPNContinuousPair\n\t* when it stores the index to a continuous variable. Testing that the index\n\t* is an LPNContinuousPair is used to determined if the indexing object points\n\t* to a continuous variable. Also the LPNContinuousPair keeps track of the current rate.\n\t* \n\t*/\n /*\n\t * Resource List :\n\t * TODO : Create a list reference where the algorithms can be found that this class\n\t * depends on.\n\t */\n public static final int INFINITY = Integer.MAX_VALUE;\n\n /* The lower and upper bounds of the times as well as the dbm. */\n private int[][] _matrix;\n\n /* Maps the index to the timer. The index is row/column of the DBM sub-matrix.\n\t * Logically the zero timer is given index -1.\n\t * */\n private LPNTransitionPair[] _indexToTimerPair;\n\n /* The hash code. */\n private int _hashCode;\n\n /* A lexicon between a transitions index and its name. */\n /* Set if a failure in the testSplit method has fired already. */\n /* Hack to pass a parameter to the equals method though a variable */\n /* Stores the continuous variables that have rate zero */\n DualHashMap _rateZeroContinuous;\n\n /* Records the largest zone that occurs. */\n public static int ZoneSize = 0;\n\n /* Write a log file */\n private static BufferedWriter _writeLogFile = null;\n\n /**\n * Returns the write log.\n * @return\n * \t\tThe _writeLogfile.\n */\n public static BufferedWriter get_writeLogFile() {\n return _writeLogFile;\n }\n\n /**\n * Sets the BufferedWriter.\n * @param writeLogFile\n */\n public static void set_writeLogFile(BufferedWriter writeLogFile) {\n _writeLogFile = writeLogFile;\n }\n\n /**\n * Sets the writeLogFile to null.\n */\n public static void reset_writeLogFile() {\n _writeLogFile = null;\n }\n\n private void checkZoneMaxSize() {\n if (dbmSize() > ZoneSize) {\n ZoneSize = dbmSize();\n }\n }\n\n private LPN[] _lpnList;\n\n /* \n\t * Turns on and off subsets for the zones.\n\t * True means subset will be considered.\n\t * False means subsets will not be considered.\n\t */\n private static boolean _subsetFlag = true;\n\n /* \n\t * Turns on and off supersets for zones.\n\t * True means that supersets will be considered.\n\t * False means that supersets will not be considered.\n\t */\n private static boolean _supersetFlag = true;\n\n /**\n * Gets the value of the subset flag.\n * @return\n * \t\tTrue if subsets are requested, false otherwise.\n */\n public static boolean getSubsetFlag() {\n return _subsetFlag;\n }\n\n /**\n * Sets the value of the subset flag.\n * @param useSubsets\n * \t\t\tThe value for the subset flag. Set to true if\n * \t\t\tsupersets are to be considered, false otherwise.\n */\n public static void setSubsetFlag(boolean useSubsets) {\n _subsetFlag = useSubsets;\n }\n\n /**\n * Gets the value of the superset flag.\n * @return\n * \t\tTrue if supersets are to be considered, false otherwise.\n */\n public static boolean getSupersetFlag() {\n return _supersetFlag;\n }\n\n /**\n * Sets the superset flag.\n * @param useSupersets\n * \t\tThe value of the superset flag. Set to true if\n * \t\tsupersets are to be considered, false otherwise.\n */\n public static void setSupersetFlag(boolean useSupersets) {\n _supersetFlag = useSupersets;\n }\n\n /**\n * Construct a zone that has the given timers.\n * @param timers\n * \t\t\t\tThe ith index of the array is the index of the timer. For example,\n * \t\t\t\t\tif timers = [1, 3, 5], then the zeroth row/column of the DBM is the\n * \t\t\t\t\ttimer of the transition with index 1, the first row/column of the\n * \t\t\t\t\tDBM is the timer of the transition with index 3, and the 2nd\n * \t\t\t\t\trow/column is the timer of the transition with index 5. Do not\n * \t\t\t\t\tinclude the zero timer.\n * @param matrix\n * \t\t\t\tThe DBM augmented with the lower and upper bounds of the delays for the\n * \t\t\t\t\ttransitions. For example, suppose a zone has timers [1, 3, 5] (as\n * \t\t\t\t\tdescribed in the timers parameters). The delay for transition 1 is\n * \t\t\t\t\t[1, 3], the delay for transition 3 is [2,5], and the delay for\n * \t\t\t\t\ttransition 5 is [4,6]. Also suppose the DBM is\n * \t\t\t\t\t t0 t1 t3 t5\n * \t\t\t\t\tt0 | 0, 3, 3, 3 |\n * \t\t\t\t\tt1 | 0, 0, 0, 0 |\n * \t\t\t\t\tt3 | 0, 0, 0, 0 |\n * \t\t\t\t\tt5 | 0, 0, 0, 0 |\n * \t\t\t\t\tThen the matrix that should be passed is\n * \t\t\t\t\t lb t0 t1 t3 t5\n * \t\t\t\t\tub| 0, 0, 3, 5, 6|\n * \t\t\t\t\tt0| 0, 0, 3, 3, 3|\n * \t\t\t\t\tt1|-1, 0, 0, 0, 0|\n * \t\t\t\t\tt3|-2, 0, 0, 0, 0|\n * \t\t\t\t\tt5|-4, 0, 0, 0, 0|\n * \t\t\t\t\tThe matrix should be non-null and the zero timer should always be the\n * \t\t\t\t\tfirst timer, even when there are no other timers.\n */\n public Zone(int[] timers, int[][] matrix) {\n // A negative number indicates that the hash code has not been set.\n _hashCode = -1;\n // Make a copy to reorder the timers.\n // Make a copy to reorder the timers.\n _indexToTimerPair = new LPNTransitionPair[timers.length];\n for (int i = 0; i < timers.length; i++) {\n _indexToTimerPair[i] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);\n }\n // Sorting the array.\n // Sorting the array.\n Arrays.sort(_indexToTimerPair);\n // // Add the zeroth timer.\n if (_indexToTimerPair[0].get_transitionIndex() != -1) {\n // Add the zeroth timer.\n LPNTransitionPair[] newIndexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newIndexToTimerPair[i + 1] = _indexToTimerPair[i];\n }\n _indexToTimerPair = newIndexToTimerPair;\n _indexToTimerPair[0] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, -1);\n }\n // throw new IllegalArgumentException(\"Timers must be non negative.\");\n // // Add a zero timer.\n // Map the old index of the timer to the new index of the timer.\n HashMap newIndex = new HashMap();\n // For the old index, find the new index.\n for (int i = 0; i < timers.length; i++) {\n // Since the zeroth timer is not included in the timers passed\n // to the index in the DBM is 1 more than the index of the timer\n // in the timers array.\n // LPNTransitionPair searchValue =\n LPNTransitionPair searchValue = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);\n newIndex.put(i + 1, Arrays.binarySearch(_indexToTimerPair, searchValue));\n }\n // Add the zero timer index.\n newIndex.put(0, 0);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Copy the DBM\n for (int i = 0; i < dbmSize(); i++) {\n for (int j = 0; j < dbmSize(); j++) {\n // Copy the passed in matrix to _matrix.\n setDbmEntry(newIndex.get(i), newIndex.get(j), matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]);\n // In the above, changed setDBMIndex to setdbm\n }\n }\n // Copy in the upper and lower bounds. The zero time does not have an upper or lower bound\n // so the index starts at i=1, the first non-zero timer.\n for (int i = 1; i < dbmSize(); i++) {\n setUpperBoundbydbmIndex(newIndex.get(i), matrix[0][dbmIndexToMatrixIndex(i)]);\n // Note : The method setLowerBoundbydbmIndex, takes the value of the lower bound\n // and the matrix stores the negative of the lower bound. So the matrix value\n // must be multiplied by -1.\n setLowerBoundbydbmIndex(newIndex.get(i), -1 * matrix[dbmIndexToMatrixIndex(i)][0]);\n }\n recononicalize();\n }\n\n /**\n * Initializes a zone according to the markings of state.\n * @param currentState\n * \t\t\tThe zone is initialized as if all enabled timers\n * \t\t\thave just been enabled.\n */\n public Zone(State initialState) {\n // Extract the associated LPN.\n LPN lpn = initialState.getLpn();\n int LPNIndex = lpn.getLpnIndex();\n if (_lpnList == null) {\n // If no LPN exists yet, create it and put lpn in it.\n _lpnList = new LPN[LPNIndex + 1];\n _lpnList[LPNIndex] = lpn;\n } else if (_lpnList.length <= LPNIndex) {\n // The list does not contain the lpn.\n LPN[] tmpList = _lpnList;\n _lpnList = new LPN[LPNIndex + 1];\n _lpnList[LPNIndex] = lpn;\n // Copy any that exist already.\n for (int i = 0; i < _lpnList.length; i++) {\n _lpnList[i] = tmpList[i];\n }\n } else if (_lpnList[LPNIndex] != lpn) {\n // This checks that the appropriate lpn is in the right spot.\n // If not (which gets you in this block), then this fixes it.\n _lpnList[LPNIndex] = lpn;\n }\n // Default value for the hash code indicating that the hash code has not\n // been set yet.\n _hashCode = -1;\n // Get the list of currently enabled Transitions by their index.\n boolean[] enabledTran = initialState.getTranVector();\n ArrayList enabledTransitionsArrayList = new ArrayList();\n LPNTransitionPair zeroPair = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, LPNTransitionPair.ZERO_TIMER);\n // Add the zero timer first.\n enabledTransitionsArrayList.add(zeroPair);\n // The index of the boolean value corresponds to the index of the Transition.\n for (int i = 0; i < enabledTran.length; i++) {\n if (enabledTran[i]) {\n enabledTransitionsArrayList.add(new LPNTransitionPair(LPNIndex, i));\n }\n }\n _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);\n _matrix = new int[matrixSize()][matrixSize()];\n for (int i = 1; i < dbmSize(); i++) {\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = lpn.getTransition(_indexToTimerPair[i].get_transitionIndex()).getLabel();\n ExprTree delay = lpn.getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = lpn.getAllVarsWithValuesAsString(initialState.getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n ExprTree lowerDelay = delay.getLeftChild();\n ExprTree upperDelay = delay.getRightChild();\n lower = (int) lowerDelay.evaluateExpr(varValues);\n upper = (int) upperDelay.evaluateExpr(varValues);\n } else {\n lower = (int) delay.evaluateExpr(varValues);\n upper = lower;\n }\n setLowerBoundbydbmIndex(i, lower);\n setUpperBoundbydbmIndex(i, upper);\n }\n // Advance the time and tighten the bounds.\n advance();\n recononicalize();\n checkZoneMaxSize();\n }\n\n /**\n * Creates a Zone based on the local states.\n * @param localStates\n * \t\t\tThe current state (or initial) of the LPNs.\n */\n public Zone(State[] localStates) {\n // Open the log file.\n if (_writeLogFile == null && Options.get_TimingLogfile() != null) {\n try {\n _writeLogFile = new BufferedWriter(new FileWriter(Options.get_TimingLogfile()));\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n }\n }\n // Initialize hash code to -1 (indicating nothing cached).\n _hashCode = -1;\n // Initialize the LPN list.\n initialize_lpnList(localStates);\n // Get the enabled transitions. This initializes the _indexTotimerPair\n // which stores the relevant information.\n // This method will also initialize the _rateZeroContinuous\n initialize_indexToTimerPair(localStates);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Set the lower bound/ upper bounds of the timers and the rates.\n initializeLowerUpperBounds(getAllNames(), localStates);\n // Initialize the row and column entries for the continuous variables.\n initializeRowColumnContVar();\n // Create a previous zone to the initial zone for the sake of warping.\n Zone tmpZone = beforeInitialZone();\n dbmWarp(tmpZone);\n recononicalize();\n // Advance Time\n advance(localStates);\n // Re-canonicalize\n recononicalize();\n // Check the size of the DBM.\n checkZoneMaxSize();\n }\n\n /**\n * Creates a Zone based on the local states.\n * @param localStates\n * \t\t\tThe current state (or initial) of the LPNs.\n */\n public Zone(State[] localStates, boolean init) {\n // Extract the local states.\n // Initialize hash code to -1 (indicating nothing cached).\n _hashCode = -1;\n // Initialize the LPN list.\n initialize_lpnList(localStates);\n // Get the enabled transitions. This initializes the _indexTotimerPair\n // which stores the relevant information.\n // This method will also initialize the _rateZeroContinuous\n initialize_indexToTimerPair(localStates);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Set the lower bound/ upper bounds of the timers and the rates.\n initializeLowerUpperBounds(getAllNames(), localStates);\n // Initialize the row and column entries for the continuous variables.\n initializeRowColumnContVar();\n if (init) {\n return;\n }\n // Advance Time\n advance(localStates);\n // Re-canonicalize\n recononicalize();\n // Check the size of the DBM.\n checkZoneMaxSize();\n }\n\n // * Sets ups a zone containing continuous variables only.\n // * @param continuousValues\n // * \t\tThe values to populate the zone with.\n // // Copy the LPNContinuousPairs over\n // int count = 0; // The position in the _indexToTimerPair for the next value.\n /**\n * Gives the names of all the transitions and continuous variables that\n * are represented by the zone.\n * @return\n * \t\tThe names of the transitions and continuous variables that are\n * \t\trepresented by the zone.\n */\n public String[] getAllNames() {\n // transitionNames[0] = \"The zero timer.\";\n // Get the continuous variable names.\n String[] contVar = getContVarNames();\n // Get the transition names.\n String[] trans = getTranNames();\n // Create an array large enough for all the names.\n String[] names = new String[contVar.length + trans.length + 1];\n // Add the zero timer.\n names[0] = \"The zero timer.\";\n // Add the continuous variables.\n for (int i = 0; i < contVar.length; i++) {\n names[i + 1] = contVar[i];\n }\n // Add the timers.\n for (int i = 0; i < trans.length; i++) {\n // Already the zero timer has been added and the elements of contVar.\n // That's a total of 'contVar.length + 1' elements. The last index was\n // thus 'contVar.length' So the first index to add to is\n names[1 + contVar.length + i] = trans[i];\n }\n return names;\n }\n\n /**\n * Get the names of the continuous variables that this zone uses.\n * @return\n * \t\tThe names of the continuous variables that are part of this zone.\n */\n public String[] getContVarNames() {\n // List for accumulating the names.\n ArrayList contNames = new ArrayList();\n // Find the pairs that represent the continuous variables. Loop starts at\n // i=1 since the i=0 is the zero timer.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // If the isTimer value is false, then this pair represents a continuous\n // If pair is LPNContinuousPair.\n if (ltPair instanceof LPNContinuousPair) {\n // Get the LPN that this pairing references and find the name of\n // the continuous variable whose index is given by this pairing.\n contNames.add(_lpnList[ltPair.get_lpnIndex()].getContVarName(ltPair.get_transitionIndex()));\n }\n }\n return contNames.toArray(new String[0]);\n }\n\n /**\n * Gets the names of the transitions that are associated with the timers in the\n * zone. Does not return the zero timer.\n * @return\n * \t\tThe names of the transitions whose timers are in the zone except the zero\n * \t\ttimer.\n */\n public String[] getTranNames() {\n // List for accumulating the names.\n ArrayList transitionNames = new ArrayList();\n // Find the pairs that represent the transition timers.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // If the isTimer value is true, then this pair represents a timer.\n // If this is an LPNTransitionPair and not an LPNContinuousPair\n if (!(ltPair instanceof LPNContinuousPair)) {\n // Get the LPN that this pairing references and find the name of the\n // transition whose index is given by this pairing.\n transitionNames.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()).getLabel());\n }\n }\n return transitionNames.toArray(new String[0]);\n }\n\n /**\n * Initializes the _lpnList using information from the local states.\n * @param localStates\n * \t\tThe local states.\n * @return\n * \t\tThe enabled transitions.\n */\n private void initialize_lpnList(State[] localStates) {\n // Create the LPN list.\n _lpnList = new LPN[localStates.length];\n // Get the LPNs.\n for (int i = 0; i < localStates.length; i++) {\n _lpnList[i] = localStates[i].getLpn();\n }\n }\n\n /**\n * Initializes the _indexToTimerPair from the local states. This includes\n * adding the zero timer, the continuous variables and the set of\n * enabled timers.\n * @param localStates\n * \t\tThe local states.\n * @return\n * \t\tThe names of the transitions stored in the _indexToTimerPair (in the same order).\n */\n private void initialize_indexToTimerPair(State[] localStates) {\n /*\n\t\t * The populating of the _indexToTimerPair is done in three stages.\n\t\t * The first is to add the zero timer which is at the beginning of the zone.\n\t\t * The second is to add the continuous variables. And the third is to add\n\t\t * the other timers. Since the continuous variables are added before the\n\t\t * timers and the variables and timers are added in the order of the LPNs,\n\t\t * the elements in an accumulating list (enabledTransitionsArrayList) are\n\t\t * already in order up to the elements added for a particular LPN. Thus the\n\t\t * only sorting that needs to take place is the sorting for a particular LPN.\n\t\t * Correspondingly, elements are first found for an LPN and sort, then added\n\t\t * to the main list.\n\t\t */\n // This method will also initialize the _rateZeroContinuous\n _rateZeroContinuous = new DualHashMap();\n // This list accumulates the transition pairs (ie timers) and the continuous\n ArrayList enabledTransitionsArrayList = new ArrayList();\n // Put in the zero timer.\n // enabledTransitionsArrayList\n enabledTransitionsArrayList.add(new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, LPNTransitionPair.ZERO_TIMER));\n // Get the continuous variables.\n for (int i = 0; i < localStates.length; i++) {\n // Accumulates the changing continuous variables for a single LPN.\n ArrayList singleLPN = new ArrayList();\n // Get the associated LPN.\n LPN lpn = localStates[i].getLpn();\n // Get the continuous variables for this LPN.\n String[] continuousVariables = lpn.getContVars();\n // Get the variable, index map.\n DualHashMap variableIndex = lpn.getContinuousIndexMap();\n // Find which have a nonzero rate.\n for (int j = 0; j < continuousVariables.length; j++) {\n // Get the Variables with this name.\n Variable contVar = lpn.getVariable(continuousVariables[j]);\n // Get the rate.\n IntervalPair rate = parseRate(contVar.getInitRate());\n // Get the LPN index for the variable\n int lpnIndex = lpn.getLpnIndex();\n // Get the index as a variable for the LPN.\n int contVariableIndex = variableIndex.get(continuousVariables[j]);\n LPNContinuousPair newPair = new LPNContinuousPair(lpnIndex, contVariableIndex, rate.getSmallestRate());\n // If the rate is non-zero, then the variables needs to be tracked\n // by matrix part of the Zone.\n if (newPair.getCurrentRate() != 0) {\n // Temporary exception guaranteeing only unit rates.\n // \"only supports positive unit rates. The variable \" + contVar +\n // \" has a rate of \" + rate);\n // // Get the LPN index for the variable\n // // Get the index as a variable for the LPN. This index matches\n // // the index in the vector stored by platu.State.\n // The continuous variable reference.\n singleLPN.add(newPair);\n } else {\n // If the rate is zero, then the Zone keeps track of this variable\n // in a list.\n _rateZeroContinuous.insert(new LPNContAndRate(newPair, rate), new VariableRangePair(contVar, parseRate(contVar.getInitValue())));\n }\n }\n // Sort the list.\n Collections.sort(singleLPN);\n // Add the list to the total accumulating list.\n for (int j = 0; j < singleLPN.size(); j++) {\n enabledTransitionsArrayList.add(singleLPN.get(j));\n }\n }\n // Get the transitions.\n for (int i = 0; i < localStates.length; i++) {\n // Extract the enabled transition vector.\n boolean[] enabledTran = localStates[i].getTranVector();\n // Accumulates the transition pairs for one LPN.\n ArrayList singleLPN = new ArrayList();\n // The index of the boolean value corresponds to the index of the Transition.\n for (int j = 0; j < enabledTran.length; j++) {\n if (enabledTran[j]) {\n // Add the transition pair.\n singleLPN.add(new LPNTransitionPair(i, j));\n }\n }\n // Sort the transitions for the current LPN.\n Collections.sort(singleLPN);\n // Add the collection to the enabledTransitionsArrayList\n for (int j = 0; j < singleLPN.size(); j++) {\n enabledTransitionsArrayList.add(singleLPN.get(j));\n }\n }\n // Extract out the array portion of the enabledTransitionsArrayList.\n _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);\n }\n\n /**\n * Sets the lower and upper bounds for the transitions and continuous variables.\n * @param varNames\n * \t\t\tThe names of the transitions in _indexToTimerPair.\n */\n private void initializeLowerUpperBounds(String[] varNames, State[] localStates) {\n // Traverse the entire length of the DBM sub-matrix except the zero row/column.\n // This is the same length as the _indexToTimerPair.length-1. The DBM is used to\n // match the idea of setting the value for each row.\n for (int i = 1; i < dbmSize(); i++) {\n // Get the current LPN and transition pairing.\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n IntervalPair range;\n if (ltPair instanceof LPNContinuousPair) {\n // If the pairing represents a continuous variable, then the\n // upper and lower bound are the initial value or infinity depending\n // on whether the initial rate is positive or negative.\n // If the value is a constant, then assign the upper and lower bounds\n // to be constant. If the value is a range then assign the upper and\n // lower bounds to be a range.\n Variable v = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());\n String rate = v.getInitRate();\n // Parse the rate. Should be in the form of [x,y] where x\n // and y are integers.\n range = parseRate(rate);\n // Set the upper and lower bound (in the matrix) for the\n // continuous variables.\n String contValue = v.getInitValue();\n IntervalPair bound = parseRate(contValue);\n // Set upper bound (DBM entry (0, x) where x is the index of the variable v).\n setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, bound.get_UpperBound());\n // Set lower bound (DBM entry (x, 0) where x is the index of the variable v).\n setDbmEntryByPair(ltPair, LPNTransitionPair.ZERO_TIMER_PAIR, -1 * bound.get_LowerBound());\n } else {\n // Get the expression tree.\n ExprTree delay = _lpnList[ltPair.get_lpnIndex()].getDelayTree(varNames[i]);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[ltPair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[ltPair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n // Passing the zone as null since it should not be needed.\n // // The lower and upper bounds should evaluate to a single\n // throw new IllegalStateException(\"When evaulating the delay, \" +\n // \"the lower or the upper bound evaluated to a range \" +\n // \"instead of a single value.\");\n if (delay != null) {\n range = delay.evaluateExprBound(varValues, this, null);\n } else {\n range = new IntervalPair(0, 0);\n }\n }\n setLowerBoundbydbmIndex(i, range.get_LowerBound());\n setUpperBoundbydbmIndex(i, range.get_UpperBound());\n }\n }\n\n /**\n * Initialize the rows and columns for the continuous variables.\n */\n private void initializeRowColumnContVar() {\n /*\n\t\t * TODO : Describe the idea behind the following algorithm.\n\t\t */\n // // Note: row is indexing the row of the DBM matrix.\n // // If we reached the timers, stop.\n // // Note: col is indexing the column of the DBM matrix.\n // // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since\n // // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower\n // // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);\n // The only entries that do not need to be checked are the ones where both variables\n // represent timers.\n for (int row = 2; row < _indexToTimerPair.length; row++) {\n // Note: row is indexing the row of the DBM matrix.\n LPNTransitionPair ltRowPair = _indexToTimerPair[row];\n // // If we reached the timers, stop.\n for (int col = 1; col < row; col++) {\n // Note: col is indexing the column of the DBM matrix.\n LPNTransitionPair ltColPair = _indexToTimerPair[col];\n // If we've reached the part of the zone involving only timers, then break out\n if (!(ltRowPair instanceof LPNContinuousPair) && !(ltColPair instanceof LPNContinuousPair)) {\n break;\n }\n // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since\n // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower\n // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);\n int rowCol = getDbmEntry(row, 0) + getDbmEntry(0, col);\n int colRow = getDbmEntry(col, 0) + getDbmEntry(0, row);\n setDbmEntry(row, col, rowCol);\n setDbmEntry(col, row, colRow);\n }\n }\n }\n\n /**\n * Zero argument constructor for use in methods that create Zones where the members\n * variables will be set by the method.\n */\n private Zone() {\n _matrix = new int[0][0];\n _indexToTimerPair = new LPNTransitionPair[0];\n _hashCode = -1;\n _lpnList = new LPN[0];\n _rateZeroContinuous = new DualHashMap();\n }\n\n /**\n * Gets the upper bound of a Transition from the zone.\n * @param t\n * \t\tThe transition whose upper bound is wanted.\n * @return\n * \t\tThe upper bound of Transition t.\n */\n public int getUpperBoundbyTransition(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n // LPNTransitionPair ltPair =\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return getUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Returns the upper bound of the continuous variable.\n * @param var\n * \t\tThe variable of interest.\n * @return\n * \t\tThe (0,var) entry of the zone, that is the maximum as recored by\n * \t\tthe zone.\n */\n public int getUpperBoundbyContinuousVariable(String contVar, LPN lpn) {\n // // Determine whether the variable is in the zone or rate zero.\n // // If a RangeAndPairing is returned, then get the information from here.\n // // If indexAndRange is null, then try to get the value from the zone.\n // throw new IllegalStateException(\"Atempted to find the upper bound for \"\n // + \"a non-rate zero continuous variable that was not found in the \"\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note : setting the rate is not necessary here since this is only\n // being used as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range().get_UpperBound();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the lower bound for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n return getDbmEntry(0, i);\n }\n\n public int getUpperBoundForRate(LPNTransitionPair contVar) {\n // Check if the contVar is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (i > 0) {\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n // Grab the current rate from the LPNContinuousPair.\n return ((LPNContinuousPair) _indexToTimerPair[i]).getCurrentRate();\n }\n // Assume the rate is zero. This covers the case if conVar\n // is in the rate zero as well as if its not in the state at all.\n return 0;\n }\n\n /**\n * Get the value of the upper bound for the delay. If the index refers\n * to a timer, otherwise get the upper bound for the continuous\n * variables rate.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @return\n * \t\t\tThe upper bound on the transitions delay.\n */\n public int getUpperBoundbydbmIndex(int index) {\n return _matrix[0][dbmIndexToMatrixIndex(index)];\n }\n\n public int getUpperBound(int index) {\n return _matrix[0][dbmIndexToMatrixIndex(index)];\n }\n\n @Override\n public int getUpperBoundTrue(int index) {\n return _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(index)];\n }\n\n public int getUnwarpedUpperBound(LPNContinuousPair lcpair) {\n // Get the index.\n int index = Arrays.binarySearch(_indexToTimerPair, lcpair);\n int rate = ((LPNContinuousPair) _indexToTimerPair[index]).getCurrentRate();\n int warpValue = getUpperBoundTrue(index);\n return warpValue * rate;\n }\n\n public int getLowerBound(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][0];\n }\n\n @Override\n public int getLowerBoundTrue(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][dbmIndexToMatrixIndex(0)];\n }\n\n /**\n * Set the value of the upper bound for the delay.\n * @param t\n * \t\t\tThe transition whose upper bound is being set.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n public void setUpperBoundbyTransition(Transition t, int value) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the upper bound for the delay.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n public void setUpperBoundbydbmIndex(int index, int value) {\n _matrix[0][dbmIndexToMatrixIndex(index)] = value;\n }\n\n /**\n * Sets the upper bound for a transition described by an LPNTransitionPair.\n * @param ltPair\n * \t\t\tThe index of the transition and the index of the associated LPN for\n * \t\t\tthe timer to set the upper bound.\n * @param value\n * \t\t\tThe value for setting the upper bound.\n */\n private void setUpperBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value) {\n setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Gets the lower bound of a Transition from the zone.\n * @param t\n * \t\tThe transition whose upper bound is wanted.\n * @return\n * \t\tThe lower bound of Transition t.\n */\n @Override\n public int getLowerBoundbyTransition(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return getLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Returns the lower bound of the continuous variable.\n * @param var\n * \t\tThe variable of interest.\n * @return\n * \t\tThe (0,var) entry of the zone, that is the minimum as recored by\n * \t\tthe zone.\n */\n public int getLowerBoundbyContinuousVariable(String contVar, LPN lpn) {\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note: Setting the rate is not necessary since this is only being used\n // as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range().get_LowerBound();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the lower bound for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n return getDbmEntry(i, 0);\n }\n\n /**\n * Get the value of the lower bound for the delay if the index refers\n * to a timer, otherwise get the lower bound for the continuous variables\n * rate.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @return\n * \t\t\tThe value of the lower bound.\n */\n public int getLowerBoundbydbmIndex(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][0];\n }\n\n public int getLowerBoundForRate(LPNTransitionPair contVar) {\n // Check if the contVar is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (i > 0) {\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n return getLowerBoundbydbmIndex(contVar.get_transitionIndex());\n }\n // Assume the rate is zero. This covers the case if conVar\n // is in the rate zero as well as if its not in the state at all.\n return 0;\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param t\n * \t\t\tThe transition whose lower bound is being set.\n * @param value\n * \t\t\tThe value of the lower bound.\n */\n public void setLowerBoundbyTransition(Transition t, int value) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param t\n * \t\t\tThe transition whose upper bound is being set.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n private void setLowerBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value) {\n setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @param value\n * \t\t\tThe value of the lower bound.\n */\n public void setLowerBoundbydbmIndex(int index, int value) {\n _matrix[dbmIndexToMatrixIndex(index)][0] = -1 * value;\n }\n\n /**\n * Give the upper and lower bounds for a continuous variable.\n * @param contVar\n * \t\tThe variable of interest.\n * @return\n * \t\tThe upper and lower bounds according to the Zone.\n */\n @Override\n public IntervalPair getContinuousBounds(String contVar, LPN lpn) {\n /*\n\t\t * Need to determine whether this is suppose to be a rate zero variable or a non-zero \n\t\t * rate variable. One method is to check the rate of the passed variable. The other is\n\t\t * to just check if the variable is present in either place.\n\t\t */\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n // Get the index of the continuous variable.\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note: setting the current rate is not necessary here since the\n // LPNContinuousPair is only being used as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(new LPNContAndRate(index, new IntervalPair(0, 0)));\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the bounds for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n // Else find the upper and lower bounds.\n int lower = (-1) * getDbmEntry(i, 0);\n int upper = getDbmEntry(0, i);\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the range for the continuous variable. Values come back not\n * warped.\n * @param ltContPair\n * \t\tThe index of the variable of interest.\n * @return\n * \t\tThe range of the continuous variable described by ltContPair.\n */\n @Override\n public IntervalPair getContinuousBounds(LPNContinuousPair ltContPair) {\n // First check in the zone.\n int variableIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);\n if (variableIndex < 0) {\n // The variable was not found in the zone. Check to see if its\n // in the rate-zero variables. Technically I will return whatever\n // is in the _rateZeroConintuous, null or not.\n // First get an object to reference into the _rateZeroContinuous\n LPNContAndRate lcr = new LPNContAndRate(ltContPair, new IntervalPair(0, 0));\n return _rateZeroContinuous.get(lcr).get_range();\n }\n // The variable was found in the zone. Yay.\n int lower = (-1) * getDbmEntry(variableIndex, 0) * getCurrentRate(ltContPair);\n int upper = getDbmEntry(0, variableIndex) * getCurrentRate(ltContPair);\n // If the current rate is negative the upper and lower bounds\n // need to be switched.\n if (getCurrentRate(ltContPair) < 0) {\n int tmp = lower;\n lower = upper;\n upper = tmp;\n }\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the range of the rate associated with a continuous variable.\n * @param ltContPair\n * \t\tThe index of the continuous variable.\n * @return\n * \t\tThe range of rates associated with the continuous variable indexed\n * \t\tby ltContPair.\n */\n @Override\n public IntervalPair getRateBounds(LPNTransitionPair ltPair) {\n int upper;\n int lower;\n // Check if the ltContpair is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, ltPair);\n if (i < 0) {\n // Then the variable is in the rate zero continuous\n // variables so get the range of rates from there.\n // Create an object to reference into the rate zero.\n LPNContAndRate lcr = new LPNContAndRate((LPNContinuousPair) ltPair, new IntervalPair(0, 0));\n // Get the old version of lcr from the rate zero since\n // that contains the rate. This is quite a hack.\n VariableRangePair vrp = _rateZeroContinuous.get(lcr);\n lcr = _rateZeroContinuous.getKey(vrp);\n return lcr.get_rateInterval();\n }\n upper = getUpperBoundbydbmIndex(i);\n lower = -1 * getLowerBoundbydbmIndex(i);\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the rate reset value.\n * @param ltPair\n * @return\n */\n @Override\n public int rateResetValue(LPNTransitionPair ltPair) {\n IntervalPair rateBounds = getRateBounds(ltPair);\n int upper = rateBounds.get_UpperBound();\n int lower = rateBounds.get_LowerBound();\n // // Check if the ltContpair is in the zone.\n // // Assume the rate is zero. This covers the case if conVar\n // // is in the rate zero as well as if its not in the state at all.\n // If zero is a possible rate, then it is the rate to set to.\n // // If zero is the only possible rate, return that.\n // // When zero is in the range and there is a positive rate, return the\n // // When the upper bound is zero, return the negative rate.\n // // When zero is not present, use the smallest rate in absolute value.\n /*\n\t\t * Suppose the range of rates is [a,b]. If a>=0, we set the rate to b.\n\t\t * If b<=0, we set the rate to a. Otherwise, a<0=0, we set the rate to b.\n\t\t * If b<=0, we set the rate to a. Otherwise, a<0 variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note : Setting the rate is not necessary since this only being used\n // as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and make the new assignment.\n if (pairing != null) {\n pairing.set_range(range);\n return;\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the bounds for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n // Else find the upper and lower bounds.\n setDbmEntry(i, 0, (-1) * range.get_LowerBound());\n setDbmEntry(0, i, range.get_UpperBound());\n }\n\n /**\n * Converts the index of the DBM to the index of _matrix.\n * @param i\n * \t\t\tThe row/column index of the DBM.\n * @return\n * \t\t\tThe row/column index of _matrix.\n */\n private static int dbmIndexToMatrixIndex(int i) {\n return i + 1;\n }\n\n /**\n * Retrieves an entry of the DBM using the DBM's addressing.\n * @param i\n * \t\t\tThe row of the DBM.\n * @param j\n * \t\t\tThe column of the DBM.\n * @return\n * \t\t\tThe value of the (i, j) element of the DBM.\n */\n @Override\n public int getDbmEntry(int i, int j) {\n return _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)];\n }\n\n /**\n * Retrieves an entry of the DBM using LPNTransitionPair indecies.\n * @param iPair\n * \t\tThe LPNTransitionPair for the ith entry.\n * @param jPair\n * \t\tThe LPNTransitionPair for the jth entry.\n * @return\n * \t\tThe value of the (i,j) element of the DBM where i corresponds to the row\n * \t\tfor the variable iPair and j corresponds to the row for the variable jPair.\n */\n @Override\n public int getDbmEntryByPair(LPNTransitionPair iPair, LPNTransitionPair jPair) {\n int iIndex = Arrays.binarySearch(_indexToTimerPair, iPair);\n int jIndex = Arrays.binarySearch(_indexToTimerPair, jPair);\n return getDbmEntry(iIndex, jIndex);\n }\n\n /**\n * Sets an entry of the DBM using the DBM's addressing.\n * @param i\n * \t\t\tThe row of the DBM.\n * @param j\n * \t\t\tThe column of the DBM.\n * @param value\n * \t\t\tThe new value for the entry.\n */\n private void setDbmEntry(int i, int j, int value) {\n _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)] = value;\n }\n\n /**\n * Sets the entry in the DBM using the LPNTransitionPair indexing.\n * @param row\n * \t\t\tThe LPNTransitionPair for the row.\n * @param col\n * \t\t\tThe LPNTransitionPair for the column.\n * @param value\n * \t\t\tThe value to set the entry to.\n */\n private void setDbmEntryByPair(LPNTransitionPair row, LPNTransitionPair col, int value) {\n // The row index.\n int i = timerIndexToDBMIndex(row);\n // The column index.\n int j = timerIndexToDBMIndex(col);\n setDbmEntry(i, j, value);\n }\n\n /**\n * Returns the index of the the transition in the DBM given a LPNTransitionPair pairing\n * the transition index and associated LPN index.\n * @param ltPair\n * \t\tThe pairing comprising the index of the transition and the index of the associated\n * \t\tLPN.\n * @return\n * \t\tThe row/column of the DBM associated with the ltPair.\n */\n @Override\n public int timerIndexToDBMIndex(LPNTransitionPair ltPair) {\n return Arrays.binarySearch(_indexToTimerPair, ltPair);\n }\n\n /**\n * The matrix labeled with 'ti' where i is the transition index associated with the timer.\n */\n @Override\n public String toString() {\n // TODO : Fix the handling of continuous variables in the\n String result = \"Timer and delay or continuous and ranges.\\n\";\n int count = 0;\n // Print the timers.\n for (int i = 1; i < _indexToTimerPair.length; i++, count++) {\n if (_lpnList.length == 0) {\n // If no LPN's are associated with this Zone, use the index of the timer.\n result += \" t\" + _indexToTimerPair[i].get_transitionIndex() + \" : \";\n } else {\n String name;\n // If the current LPNTransitionPair is a timer, get the name\n // from the transitions.\n // If the current timer is an LPNTransitionPair and not an LPNContinuousPair\n if (!(_indexToTimerPair[i] instanceof LPNContinuousPair)) {\n // Get the name of the transition.\n Transition tran = _lpnList[_indexToTimerPair[i].get_lpnIndex()].getTransition(_indexToTimerPair[i].get_transitionIndex());\n name = tran.getLabel();\n } else {\n // If the current LPNTransitionPair is not a timer, get the\n // name as a continuous variable.\n Variable var = _lpnList[_indexToTimerPair[i].get_lpnIndex()].getContVar(_indexToTimerPair[i].get_transitionIndex());\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];\n int lowerBound = -1 * getDbmEntry(i, 0) * lcPair.getCurrentRate();\n int upperBound = getDbmEntry(0, i) * lcPair.getCurrentRate();\n // If the rate is negative, the bounds are switched\n // in the zone.\n if (lcPair.getCurrentRate() < 0) {\n int tmp = lowerBound;\n lowerBound = upperBound;\n upperBound = tmp;\n }\n name = var.getName() + \":[\" + lowerBound + \",\" + upperBound + \"]\\n\" + \" Current Rate: \" + lcPair.getCurrentRate() + \" \" + \"rate:\";\n }\n result += \" \" + name + \":\";\n }\n result += \"[ \" + -1 * getLowerBoundbydbmIndex(i) + \", \" + getUpperBoundbydbmIndex(i) + \" ]\";\n if (count > 9) {\n result += \"\\n\";\n count = 0;\n }\n }\n if (!_rateZeroContinuous.isEmpty()) {\n result += \"\\nRate Zero Continuous : \\n\";\n for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()) {\n result += \"\" + _rateZeroContinuous.get(lcrPair) + \"Rate: \" + lcrPair.get_rateInterval();\n }\n }\n result += \"\\nDBM\\n\";\n // Print the DBM.\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n result += \"| \" + String.format(\"%3d\", getDbmEntry(i, 0));\n for (int j = 1; j < _indexToTimerPair.length; j++) {\n result += \", \" + String.format(\"%3d\", getDbmEntry(i, j));\n }\n result += \" |\\n\";\n }\n return result;\n }\n\n /**\n * Tests for equality. Overrides inherited equals method.\n * @return True if o is equal to this object, false otherwise.\n */\n @Override\n public boolean equals(Object o) {\n // Check if the reference is null.\n if (o == null) {\n return false;\n }\n // Check that the type is correct.\n if (!(o instanceof Zone)) {\n return false;\n }\n // Check for equality using the Zone equality.\n return equals((Zone) o);\n }\n\n /**\n * Tests for equality.\n * @param\n * \t\tThe Zone to compare.\n * @return\n * \t\tTrue if the zones are non-null and equal, false otherwise.\n */\n public boolean equals(Zone otherZone) {\n // Check if the reference is null first.\n if (otherZone == null) {\n return false;\n }\n // Check for reference equality.\n if (this == otherZone) {\n return true;\n }\n // If the hash codes are different, then the objects are not equal.\n if (this.hashCode() != otherZone.hashCode()) {\n return false;\n }\n // Check if the they have the same number of timers.\n if (this._indexToTimerPair.length != otherZone._indexToTimerPair.length) {\n return false;\n }\n // Check if the timers are the same.\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n if (!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))) {\n return false;\n }\n }\n // Check if the matrix is the same\n for (int i = 0; i < _matrix.length; i++) {\n for (int j = 0; j < _matrix[0].length; j++) {\n if (!(this._matrix[i][j] == otherZone._matrix[i][j])) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Determines if this zone is a subset of Zone otherZone.\n * @param otherZone\n * \t\tThe zone to compare against.\n * @return\n * \t\tTrue if this is a subset of other; false otherwise.\n */\n @Override\n public boolean subset(Equivalence otherEquiv) {\n Zone otherZone = (Zone) otherEquiv;\n // Check if the reference is null first.\n if (otherZone == null) {\n return false;\n }\n // Check for reference equality.\n if (this == otherZone) {\n return true;\n }\n // Check if the the same number of timers are present.\n if (this._indexToTimerPair.length != otherZone._indexToTimerPair.length) {\n return false;\n }\n // Check if the transitions are the same.\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n if (!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))) {\n return false;\n }\n }\n // Check if the entries of this Zone are less than or equal to the entries\n // of the other Zone.\n for (int i = 0; i < _matrix.length; i++) {\n for (int j = 0; j < _matrix[0].length; j++) {\n if (!(this._matrix[i][j] <= otherZone._matrix[i][j])) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Determines if this zone is a superset of Zone otherZone.\n * @param otherZone\n * \t\tThe zone to compare against.\n * @return\n * \t\tTrue if this is a subset of other; false otherwise. More specifically it\n * \t\tgives the result of otherZone.subset(this). Thus it agrees with the subset method.\n */\n @Override\n public boolean superset(Equivalence otherZone) {\n return otherZone.subset(this);\n }\n\n /**\n * Overrides the hashCode.\n */\n @Override\n public int hashCode() {\n // Check if the hash code has been set.\n if (_hashCode < 0) {\n _hashCode = createHashCode();\n }\n return _hashCode;\n }\n\n /**\n * Creates a hash code for a Zone object.\n * @return\n * \t\tThe hash code.\n */\n private int createHashCode() {\n int newHashCode = Arrays.hashCode(_indexToTimerPair);\n for (int i = 0; i < _matrix.length; i++) {\n newHashCode ^= Arrays.hashCode(_matrix[i]);\n }\n return Math.abs(newHashCode);\n }\n\n /**\n * The size of the DBM sub matrix. This is calculated using the size of _indexToTimer.\n * @return\n * \t\t\tThe size of the DBM.\n */\n private int dbmSize() {\n return _indexToTimerPair.length;\n }\n\n /**\n * The size of the matrix.\n * @return\n * \t\t\tThe size of the matrix. This is calculated using the size of _indexToTimer.\n */\n private int matrixSize() {\n return _indexToTimerPair.length + 1;\n }\n\n /**\n * Performs the Floyd's least pairs algorithm to reduce the DBM.\n */\n @Override\n public void recononicalize() {\n for (int k = 0; k < dbmSize(); k++) {\n for (int i = 0; i < dbmSize(); i++) {\n for (int j = 0; j < dbmSize(); j++) {\n if (getDbmEntry(i, k) != INFINITY && getDbmEntry(k, j) != INFINITY && getDbmEntry(i, j) > getDbmEntry(i, k) + getDbmEntry(k, j)) {\n setDbmEntry(i, j, getDbmEntry(i, k) + getDbmEntry(k, j));\n }\n if ((i == j) && getDbmEntry(i, j) != 0) {\n throw new DiagonalNonZeroException(\"Entry (\" + i + \", \" + j + \")\" + \" became \" + getDbmEntry(i, j) + \".\");\n }\n }\n }\n }\n }\n\n /**\n * Determines if a timer associated with a given transitions has reached its lower bound.\n * @param t\n * \t\t\tThe transition to consider.\n * @return\n * \t\t\tTrue if the timer has reached its lower bound, false otherwise.\n */\n public boolean exceedsLowerBoundbyTransitionIndex(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return exceedsLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Determines if a timer has reached its lower bound.\n * @param timer\n * \t\t\tThe timer's index.\n * @return\n * \t\t\tTrue if the timer has reached its lower bound, false otherwise.\n */\n public boolean exceedsLowerBoundbydbmIndex(int index) {\n // Note : Make sure that the lower bound is stored as a negative number\n // and that the inequality is correct.\n return _matrix[0][dbmIndexToMatrixIndex(index)] <= _matrix[1][dbmIndexToMatrixIndex(index)];\n }\n\n /* (non-Javadoc)\n\t * @see verification.timed_state_exploration.zone.Zone#fireTransitionbyTransitionIndex(int, int[], verification.platu.stategraph.State)\n\t */\n // State state)\n // // Check if the value is in this zone to fire.\n /**\n * Gives the Zone obtained by firing a given Transitions.\n * @param t\n * \t\tThe transitions being fired.\n * @param enabledTran\n * \t\tThe list of currently enabled Transitions.\n * @param localStates\n * \t\tThe current local states.\n * @return\n * \t\tThe Zone obtained by firing Transition t with enabled Transitions enabled\n * \t\tenabledTran when the current state is localStates.\n */\n // public Zone fire(Transition t, LpnTranList enabledTran,\n @Override\n public Zone fire(Transition t, LpnTranList enabledTran, ContinuousRecordSet newAssignValues, State[] localStates) {\n try {\n if (_writeLogFile != null) {\n _writeLogFile.write(t.toString());\n _writeLogFile.newLine();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n // Create the LPNTransitionPair to check if the Transitions is in the zone and to\n // find the index.\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n int dbmIndex = Arrays.binarySearch(_indexToTimerPair, ltPair);\n if (dbmIndex <= 0) {\n return this;\n }\n // Get the new zone portion.\n Zone newZone = fireTransitionbydbmIndexNew(dbmIndex, enabledTran, localStates, newAssignValues);\n // Update any assigned continuous variables.\n // Set all the rates to their lower bound.\n newZone.setAllToLowerBoundRate();\n // Warp the Zone\n newZone.dbmWarp(this);\n // Warping can wreck the newly assigned values so correct them.\n newZone.correctNewAssignemnts(newAssignValues);\n newZone.recononicalize();\n newZone.advance(localStates);\n // Recanonicalize\n newZone.recononicalize();\n newZone.checkZoneMaxSize();\n return newZone;\n }\n\n /**\n * Updates the Zone according to the transition firing.\n * @param index\n * \t\t\tThe index of the timer.\n * @param newContValue\n * @return\n * \t\t\tThe updated Zone.\n */\n public Zone fireTransitionbydbmIndex(int index, LpnTranList enabledTimers, State[] localStates, ArrayList> newAssignValues) {\n /*\n\t\t * For the purpose of adding the newly enabled transitions and removing\n\t\t * the disable transitions, the continuous variables that still have\n\t\t * a nonzero rate can be treated like still enbaled timers.\n\t\t */\n // Initialize the zone.\n Zone newZone = new Zone();\n // These sets will defferentiate between the new timers and the\n // old timers, that is between the timers that are not already in the\n // zone and those that are already in the zone..\n HashSet newTimers = new HashSet();\n HashSet oldTimers = new HashSet();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n HashMap oldNonZero = newAssignValues.get(3);\n // Add the continuous variables to the enabled timers.\n for (int i = 1; _indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n // For the purpose of addigng continuous variables to the zone\n // consider an oldNonZero continuous variable as new.\n if (oldNonZero.containsKey(_indexToTimerPair[i])) {\n continue;\n }\n oldTimers.add(_indexToTimerPair[i]);\n }\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n // Determine if each value is a new timer or old.\n if (Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0) {\n // The timer was already present in the zone.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else {\n // The timer is a new timer.\n newTimers.add(newZone._indexToTimerPair[i]);\n }\n }\n // Create the new matrix.\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n // TODO: For simplicity, make a copy of the current zone and perform the\n // restriction and re-canonicalization. Later add a copy re-canonicalization\n // that does the steps together.\n Zone tempZone = this.clone();\n tempZone.restrictTimer(index);\n tempZone.recononicalize();\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);\n newZone._matrix[Zone.dbmIndexToMatrixIndex(newIndexi)][Zone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n // The block copies the upper and lower bound information from the\n // old zone. Thus we do not consider anything that is not an old\n // timer. Furthermore, oldNonZero represent\n if (!oldTimers.contains(tempZone._indexToTimerPair[i]) && !oldNonZero.containsKey(_indexToTimerPair[i])) {\n continue;\n }\n newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n newZone.setLowerBoundByLPNTransitionPair(pair, lower);\n newZone.setUpperBoundByLPNTransitionPair(pair, upper);\n }\n // Advance time.\n return newZone;\n }\n\n public Zone fireTransitionbydbmIndexNew(int index, LpnTranList enabledTimers, State[] localStates, ContinuousRecordSet newAssignValues) {\n /*\n\t\t * For the purpose of adding the newly enabled transitions and removing\n\t\t * the disable transitions, the continuous variables that still have\n\t\t * a nonzero rate can be treated like still enbaled timers.\n\t\t */\n // Initialize the zone.\n Zone newZone = new Zone();\n // These sets will defferentiate between the new timers and the\n // old timers, that is between the timers that are not already in the\n // zone and those that are already in the zone..\n HashSet newTimers = new HashSet();\n HashSet oldTimers = new HashSet();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n copyRatesNew(newZone, enabledTimers, newAssignValues);\n // Add the continuous variables to the enabled timers.\n // // For the purpose of addigng continuous variables to the zone\n // // consider an oldNonZero continuous variable as new.\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n // Handle the continuous variables portion.\n if (newZone._indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];\n // Get the record\n UpdateContinuous continuousState = newAssignValues.get(lcPair);\n if (continuousState != null && (continuousState.is_newValue() || continuousState.newlyNonZero())) {\n // In the first case a new value has been assigned, so\n // consider the continuous variable a 'new' variable for\n // the purposes of copying relations from the previous zone.\n newTimers.add(newZone._indexToTimerPair[i]);\n continue;\n }\n // At this point, either the continuous variable was not present\n // in the newAssignValues or it is in the newAssignValues and\n // satisfies the following: it already had a non-zero rate, is\n // being assigned another non-zero rate, and is not being assigned\n // a new value. This is becuase the field _indexToTimerPair only\n // deals with non-zero rates, so the variable must have a non-zero\n // rate. Furthermore the if statement takes care of the cases\n // when the rate changed from zero to non-zero and/or a new value\n // has been assigned.\n // In either of the cases, we consider the variable an 'old' variable\n // for the purpose of copying the previous zone information.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else // At this point, the variable represents a transition (timer).\n // So determine whether this timer is new or old.\n if (Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0) {\n // The timer was already present in the zone.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else {\n // The timer is a new timer.\n newTimers.add(newZone._indexToTimerPair[i]);\n }\n }\n // Create the new matrix.\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n // TODO: For simplicity, make a copy of the current zone and perform the\n // restriction and re-canonicalization. Later add a copy re-canonicalization\n // that does the steps together.\n Zone tempZone = this.clone();\n tempZone.restrictTimer(index);\n tempZone.recononicalize();\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);\n newZone._matrix[Zone.dbmIndexToMatrixIndex(newIndexi)][Zone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n // The block copies the upper and lower bound information from the\n // old zone. Thus we do not consider anything that is not an old\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n // A hack to ensure that the newly zero variables\n // get the new values from the tempZone.\n if (tempZone._indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) tempZone._indexToTimerPair[i];\n VariableRangePair vrp = newZone._rateZeroContinuous.get(new LPNContAndRate(lcPair));\n if (vrp != null) {\n // This means that the continuous variable was non-zero\n // and is now zero. Fix up the values according to\n // the temp zone.\n IntervalPair newRange = tempZone.getContinuousBounds(lcPair);\n vrp.set_range(newRange);\n }\n }\n continue;\n }\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];\n // Check if a rate assignment has occured for any continuous\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord != null) {\n // Since the variable is in the oldTimers, it cannot have had\n // a new value assigned to it. It must have had a new rate assignment\n IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();\n // Copy the new rate information\n newZone.setLowerBoundByLPNTransitionPair(_indexToTimerPair[i], rates.get_LowerBound());\n newZone.setUpperBoundByLPNTransitionPair(_indexToTimerPair[i], rates.get_UpperBound());\n // Copy the smallest and greatest continuous value.\n continue;\n }\n }\n newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Handle continuous case\n if (pair instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) pair;\n // If a continuous variable is in the newTimers, then an assignment\n // to the variable must have occurred. So get the value.\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord == null) {\n throw new IllegalStateException(\"The pair \" + pair + \"was not in the new assigned values but was sorted as \" + \"a new value.\");\n }\n IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();\n IntervalPair values = updateRecord.get_Value();\n newZone.setLowerBoundByLPNTransitionPair(lcPair, rates.get_LowerBound());\n newZone.setUpperBoundByLPNTransitionPair(lcPair, rates.get_UpperBound());\n // Get the current rate.\n int currentRate = lcPair.getCurrentRate();\n if (currentRate >= 0) {\n // // Copy the smallest and greatest continuous value.\n // Copy the smallest and greatest continuous value.\n newZone.setDbmEntryByPair(lcPair, LPNTransitionPair.ZERO_TIMER_PAIR, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), currentRate, true));\n newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, lcPair, ContinuousUtilities.chkDiv(values.get_UpperBound(), currentRate, true));\n } else {\n // Copy the smallest and greatest continuous value.\n // For negative rates, the upper and lower bounds need\n // to be switched.\n newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, lcPair, ContinuousUtilities.chkDiv(values.get_LowerBound(), currentRate, true));\n newZone.setDbmEntryByPair(lcPair, LPNTransitionPair.ZERO_TIMER_PAIR, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), currentRate, true));\n }\n continue;\n }\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n if (delay == null) {\n _lpnList[pair.get_lpnIndex()].changeDelay(tranName, \"0\");\n delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n }\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n newZone.setLowerBoundByLPNTransitionPair(pair, lower);\n newZone.setUpperBoundByLPNTransitionPair(pair, upper);\n }\n // Erase relationships for continuous variables that have had new values\n // assigned to them or a new non-rate zero value.\n for (int i = 1; i < newZone._indexToTimerPair.length && newZone._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];\n // Get the update variable.\n UpdateContinuous update = newAssignValues.get(lcPair);\n if (update != null && (update.is_newValue() || update.newlyNonZero())) {\n for (int j = 1; j < newZone._indexToTimerPair.length; j++) {\n if (j == i) {\n continue;\n }\n newZone.setDbmEntry(i, j, Zone.INFINITY);\n newZone.setDbmEntry(j, i, Zone.INFINITY);\n }\n }\n }\n // Advance time.\n return newZone;\n }\n\n public void correctNewAssignemnts(ContinuousRecordSet newAssignValues) {\n // Erase relationships for continuous variables that have had new values\n // assigned to them or a new non-rate zero value.\n for (int i = 1; i < this._indexToTimerPair.length && this._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];\n // Get the update variable.\n UpdateContinuous update = newAssignValues.get(lcPair);\n if (update != null && (update.is_newValue() || update.newlyNonZero())) {\n IntervalPair values = update.get_Value();\n int currentRate = lcPair.getCurrentRate();\n // Correct the upper and lower bounds.\n if (lcPair.getCurrentRate() > 0) {\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), currentRate, true));\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(values.get_UpperBound(), currentRate, true));\n } else {\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), currentRate, true));\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(values.get_LowerBound(), currentRate, true));\n }\n // Erase the relationships.\n for (int j = 1; j < this._indexToTimerPair.length; j++) {\n if (j == i) {\n continue;\n }\n this.setDbmEntry(i, j, Zone.INFINITY);\n this.setDbmEntry(j, i, Zone.INFINITY);\n }\n }\n }\n }\n\n /**\n * This fire method fires a rate change event.\n *\n * @param ltPair\n * \t\tThe index of the continuous variable whose rate needs to be changed.\n * @param rate\n * \t\tThe new rate.\n * @return\n * \t\tThe new zone resulting from the rate change.\n */\n @Override\n public Zone fire(LPNTransitionPair ltPair, int rate) {\n // Make a copy of the Zone.\n Zone resultZone = this.clone();\n // Change the current rate of the continuous variable.\n setCurrentRate(ltPair, rate);\n // Warp the zone.\n resultZone.dbmWarp(this);\n return resultZone;\n }\n\n /**\n * Handles the moving in and out of continuous variables.\n * @param newContValues\n */\n // // Copy the zero rate variables over if they are still rate zero.\n // // Check if the pairing is in the newNonZeroContValues.\n // // Interval being null indicates that the key was not\n /**\n * Handles the moving of the continuous variables in and out of the\n * _rateZeroContinuous. This includes the adding of all rate zero (new and old)\n * cotninuous variables to the _rateZeroContinuous, and creating the\n * _indexToTimerPair and populating it.\n * @param newZone The Zone being constructed.\n * @param enabled The list of enabled transitions.\n * \t\tThe enabled transitions.\n * @param newAssignValues The list of continuous variable update information.\n */\n @SuppressWarnings(\"unused\")\n private void copyRates(Zone newZone, LpnTranList enabledTran, ContinuousRecordSet newAssignValues) {\n /*\n\t\t * The newAssignValues is an ArrayList of four sets.\n\t\t * 0. Rate zero gets zero assigned.\n\t\t * 1. Rate zero gets non-zero rate assigned.\n\t\t * 2. Non-zero gets zero rate assigned.\n\t\t * 3. Non-zero gets non-zero rate assigned.\n\t\t */\n // Create new rate zero member variable.\n newZone._rateZeroContinuous = new DualHashMap();\n // First get the total number of non-zero rate continuous variables that\n // are present in the old zone.\n int totalContinuous = 0;\n for (int i = 0; i < _lpnList.length; i++) {\n totalContinuous += _lpnList[i].getTotalNumberOfContVars();\n }\n int numberNonZero = totalContinuous - _rateZeroContinuous.size();\n // The size is given by\n // total number of transitions\n // + number of non-zero rate continuous variables previously in the zone\n // + number of zero rate continuous variables that now have non-zero\n // - number of non-zero rate continuous variables that are now zero\n // + 1 for the zero timer.\n // TODO: Create an object that stores the records along with this information.\n int newNonZero = 0, newZero = 0;\n for (UpdateContinuous record : newAssignValues.keySet()) {\n if (record.newlyNonZero()) {\n newNonZero++;\n }\n if (record.newlyZero()) {\n newZero++;\n }\n }\n int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;\n // Create the timer array.\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n // Add in the zero timer.\n newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;\n // Copy over the rate zero conintinuous variables.\n // First copy over all the continuous variables that still have\n // rate zero.\n // // Cast the index.\n // // The variable no longer is rate zero, so do nothing.\n // // If the value has had an assignment, use the new values instead.\n // // Create the new VariableRangePair to add.\n // VariableRangePair vrp =\n // Copy over the rate zero continuous variables.\n // First copy over all the continuous variables that still have\n // rate zero.\n for (LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()) {\n // Cast the index.\n LPNContinuousPair ltContPair = ltTranPair.get_lcPair();\n if (!newAssignValues.get(ltContPair).is_newZero()) {\n // The variable no longer is rate zero, so do nothing.\n continue;\n }\n // If the value has had an assignment, use the new values instead.\n if (newAssignValues.contains(ltContPair)) {\n // Create the new VariableRangePair to add.\n Variable v = _lpnList[ltContPair.get_lpnIndex()].getContVar(ltContPair.get_ContinuousIndex());\n // VariableRangePair vrp =\n VariableRangePair vrp = new VariableRangePair(v, newAssignValues.get(ltContPair).get_Value());\n newZone._rateZeroContinuous.insert(new LPNContAndRate(ltContPair, new IntervalPair(0, 0)), vrp);\n } else {\n newZone._rateZeroContinuous.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));\n }\n }\n // Next add the values that are newly set to rate zero.\n // // Exract the variable.\n // // Create a VariableRangePair.\n // // Add the value to the map.\n // // Exract the variable.\n // // Create a VariableRangePair.\n // // Add the value to the map.\n // We still need to add in the rate zero continuous variables whose rate remains zero\n // since their range might have changed. We could check if the range has changed, but\n // its just as easy (or easier) to simply add it anyway.\n // Added the indecies for the non-zero rate continuous variables to the\n // _indexToTimer array.\n // Start with the values already in the old array.\n // int index = 1; // Index for the next continuous index object.\n // // Check that the value should not be removed.\n // Change to the new references for the oldNonZero. This change to the\n // Add in the indecies for the new non-zero into the old array.\n // Copy over the new transitions.\n Arrays.sort(newZone._indexToTimerPair);\n }\n\n private void copyRatesNew(Zone newZone, LpnTranList enabledTran, ContinuousRecordSet newAssignValues) {\n // Create new rate zero member variable.\n newZone._rateZeroContinuous = new DualHashMap();\n // First get the total number of non-zero rate continuous variables that\n // are present in the old zone.\n int totalContinuous = 0;\n for (int i = 0; i < _lpnList.length; i++) {\n totalContinuous += _lpnList[i].getTotalNumberOfContVars();\n }\n int numberNonZero = totalContinuous - _rateZeroContinuous.size();\n // The size is given by\n // total number of transitions\n // + number of non-zero rate continuous variables previously in the zone\n // + number of zero rate continuous variables that now have non-zero\n // - number of non-zero rate continuous variables that are now zero\n // + 1 for the zero timer.\n // TODO: Create an object that stores the records along with this information.\n int newNonZero = 0, newZero = 0;\n for (UpdateContinuous record : newAssignValues.keySet()) {\n if (record.newlyNonZero()) {\n newNonZero++;\n }\n if (record.newlyZero()) {\n newZero++;\n }\n }\n int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;\n // Create the timer array.\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n // Add in the zero timer.\n newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;\n int indexTimerCount = 1;\n // Sort the previous rate zero continuous variables into rate zero or non-zero.\n for (LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()) {\n // Cast the index.\n LPNContinuousPair ltContPair = ltTranPair.get_lcPair();\n // Check if the variable is a newly assigned value.\n UpdateContinuous assignedLtContPair = newAssignValues.get(ltContPair);\n if (assignedLtContPair != null) {\n if (assignedLtContPair.newlyNonZero()) {\n // Variable was zero and is now non-zero, so add to the the non-zero\n newZone._indexToTimerPair[indexTimerCount++] = assignedLtContPair.get_lcrPair().get_lcPair().clone();\n } else {\n // Variable was zero and is still zero, but an assignment has been\n // made. Simply add in the new assigned value.\n VariableRangePair vrp = this._rateZeroContinuous.get(ltTranPair);\n newZone._rateZeroContinuous.insert(assignedLtContPair.get_lcrPair(), new VariableRangePair(vrp.get_variable(), assignedLtContPair.get_Value()));\n }\n } else {\n newZone._rateZeroContinuous.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));\n }\n }\n // Sort the previous non-zero variables into the rate zero and non-zero.\n for (int i = 1; this._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];\n // Check if an assignment has been made.\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord != null) {\n if (updateRecord.is_newZero()) {\n // The continuous variable is now a rate zero variable.\n LPNContinuousPair ltCar = updateRecord.get_lcrPair().get_lcPair();\n Variable v = _lpnList[ltCar.get_lpnIndex()].getContVar(ltCar.get_ContinuousIndex());\n // Dewarp the upper and lower bounds.\n IntervalPair values = updateRecord.get_Value();\n int currentRate = getCurrentRate(ltCar);\n values.set_LowerBound(values.get_LowerBound() * currentRate);\n values.set_UpperBound(values.get_UpperBound() * currentRate);\n // Create a VariableRangePair.\n VariableRangePair vrp = new VariableRangePair(v, values);\n // Add the value to the map.\n newZone._rateZeroContinuous.insert(updateRecord.get_lcrPair(), vrp);\n } else {\n // This non-zero variable still has rate non-zero, but replace\n // with the newAssignValues since the rate may have changed.\n newZone._indexToTimerPair[indexTimerCount++] = updateRecord.get_lcrPair().get_lcPair();\n }\n } else {\n // The variable was non-zero and hasn't had an assignment.\n newZone._indexToTimerPair[indexTimerCount++] = this._indexToTimerPair[i].clone();\n }\n }\n // Copy over the new transitions.\n for (Transition t : enabledTran) {\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n newZone._indexToTimerPair[indexTimerCount++] = new LPNTransitionPair(lpnIndex, tranIndex);\n }\n Arrays.sort(newZone._indexToTimerPair);\n }\n\n private void advance() {\n for (int i = 0; i < dbmSize(); i++) {\n _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(i)] = getUpperBoundbydbmIndex(i);\n }\n }\n\n /**\n * Advances time. (This method should replace advance().)\n * @param localStates\n */\n @Override\n public void advance(State[] localStates) {\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n if (ltPair.equals(LPNTransitionPair.ZERO_TIMER_PAIR)) {\n continue;\n }\n // Get the new value.\n int newValue = 0;\n if (!(ltPair instanceof LPNContinuousPair)) {\n // If the pair is a timer, then simply get the stored largest value.\n int index = timerIndexToDBMIndex(ltPair);\n newValue = getUpperBoundbydbmIndex(index);\n } else {\n // If the pair is a continuous variable, then need to find the\n // possible largest bound governed by the inequalities.\n newValue = ContinuousUtilities.maxAdvance(this, ltPair, localStates);\n }\n // In either case (timer or continuous), set the upper bound portion\n // of the DBM to the new value.\n setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, newValue);\n }\n }\n\n /**\n * Copies in the new values needed to add a set of new times.\n * @param newZone\n * \t\t\tThe zone that the values are going to be copied into.\n * @param tempZone\n * \t\t\tThe zone to look up current values of timers.\n * @param newTimers\n * \t\t\tA collection of the new timers.\n * @param oldTimers\n * \t\t\tA collection of the older timers.\n * @param localStates\n * \t\t\tThe current state.\n */\n private void copyTransitions(Zone tempZone, Collection newTimers, Collection oldTimers, State[] localStates) {\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[j]);\n _matrix[dbmIndexToMatrixIndex(newIndexi)][dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n setDbmEntry(timerIndexToDBMIndex(timerNew), timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n setDbmEntry(timerIndexToDBMIndex(timerOld), timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n setLowerBoundByLPNTransitionPair(pair, lower);\n setUpperBoundByLPNTransitionPair(pair, upper);\n }\n }\n\n /**\n * This method sets all the rate to their lower bound.\n * Will not work quite right for continuous variables\n * with rates that include zero.\n */\n private void setAllToLowerBoundRate() {\n // Loop through the continuous variables.\n for (int i = 1; i < _indexToTimerPair.length && _indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair ltContPair = (LPNContinuousPair) _indexToTimerPair[i];\n // For this, recall that for a continuous variable that the lower bound\n // rate is stored in the zero column of the matrix.\n int lower = -1 * _matrix[dbmIndexToMatrixIndex(i)][0];\n int upper = _matrix[0][dbmIndexToMatrixIndex(i)];\n int newRate;\n /**\n * Suppose the range of rates is [a,b]. If a>=0, then we set the\n * rate to b. If b<=0, then we set the rate to a. Ohterwise,\n * a<0=0 or lower < 0 < upper we set the\n // rate to the upper bound.\n newRate = upper;\n }\n setCurrentRate(ltContPair, newRate);\n }\n }\n\n /**\n * Resets the rates of all continuous variables to be their\n * lower bounds.\n */\n @Override\n public Zone resetRates() {\n // Create the new zone.\n // // Copy the rate zero variables.\n // // Copy the LPNs over.\n // // Loop through the variables and save off those\n // // that are rate zero. Accumulate an array that\n // // indicates which are zero for faster\n // // copying. Save the number of continuous variables.\n // boolean[] rateZero = new boolean[this._indexToTimerPair.length]; // Is rate zero.\n // // The rate zero is in the range, so this will be\n // LPNContinuousPair lcPair =\n // // Save as a rate zero continuous variable.\n // VariableRangePair vcp =\n // // Update continuous variable counter.\n // // Save over the indexToTimer pairs.\n // // Ignore rate zero variables.\n // // If this is a continuous variable, set the rate to the lower bound.\n // // Calculate the size of the matrix and create it.\n // // Copy over the old matrix for all variables except\n // // the rate zero variables.\n // Warp\n Zone newZone = new Zone();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n /* \n\t\t * Collect the rate zero variables whose range of rates are not\n\t\t * identically zero. These will be moved out of the zone when\n\t\t * the rate is reset.\n\t\t * \n\t\t * Copy over the rate zero variables that remain rate zero.\n\t\t */\n newZone._rateZeroContinuous = new DualHashMap();\n HashSet> newlyNonZero = new HashSet>();\n for (Map.Entry variable : _rateZeroContinuous.entrySet()) {\n // Check for a single value which indicates that zero is\n // the only possible rate.\n if (variable.getKey().get_rateInterval().singleValue()) {\n // This variable only has zero as a rate so keep it\n // in the rate zero variables.\n newZone._rateZeroContinuous.insert(variable.getKey(), variable.getValue());\n } else {\n // This variable will need to be added to the zone.\n newlyNonZero.add(variable);\n }\n }\n /*\n\t\t * Calulate the size of the _indexToTimerPairs array and create\n\t\t * it.\n\t\t */\n int oldSize = this._indexToTimerPair.length;\n int newSize = oldSize + newlyNonZero.size();\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n /*\n\t\t * Copy over the old pairs and add the new ones.\n\t\t */\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();\n }\n for (Map.Entry variable : newlyNonZero) {\n newZone._indexToTimerPair[oldSize++] = variable.getKey().get_lcPair().clone();\n }\n Arrays.sort(newZone._indexToTimerPair);\n /*\n\t\t * Copy over the old matrix values and new constraints.\n\t\t */\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n for (int i = 0; i < this.dbmSize(); i++) {\n int newi = Arrays.binarySearch(newZone._indexToTimerPair, this._indexToTimerPair[i]);\n if (newi < 0) {\n System.err.println(\"In resetRates, old value was not found\" + \" in new value.\");\n continue;\n }\n // Copy upper and lower bounds for the variable.\n newZone._matrix[dbmIndexToMatrixIndex(newi)][0] = this._matrix[dbmIndexToMatrixIndex(i)][0];\n newZone._matrix[0][dbmIndexToMatrixIndex(newi)] = this._matrix[0][dbmIndexToMatrixIndex(i)];\n // Copy the DBM Entry\n for (int j = 0; j < this.dbmSize(); j++) {\n int newj = Arrays.binarySearch(newZone._indexToTimerPair, this._indexToTimerPair[j]);\n if (newj < 0) {\n System.err.println(\"In resetRates, old value was not\" + \" found in new value.\");\n continue;\n }\n newZone.setDbmEntry(newi, newj, this.getDbmEntry(i, j));\n }\n }\n for (Map.Entry variable : newlyNonZero) {\n LPNTransitionPair currentVariable = variable.getKey().get_lcPair();\n int currentIndex = Arrays.binarySearch(newZone._indexToTimerPair, currentVariable);\n IntervalPair rangeOfRates = variable.getKey().get_rateInterval();\n IntervalPair rangeOfValues = variable.getValue().get_range();\n /*\n\t\t\t * First set the range of rates, current rate, and the lower and upper\n\t\t\t * bounds for the newly added continuous variables.\n\t\t\t */\n newZone.setLowerBoundbydbmIndex(currentIndex, rangeOfRates.get_LowerBound());\n newZone.setUpperBoundbydbmIndex(currentIndex, rangeOfRates.get_UpperBound());\n newZone.setDbmEntry(currentIndex, 0, -1 * rangeOfValues.get_LowerBound());\n newZone.setDbmEntry(0, currentIndex, rangeOfValues.get_UpperBound());\n for (int j = 1; j < newZone.dbmSize(); j++) {\n if (currentIndex == j) {\n continue;\n }\n newZone.setDbmEntry(currentIndex, j, Zone.INFINITY);\n newZone.setDbmEntry(j, currentIndex, Zone.INFINITY);\n }\n }\n /*\n\t\t * Reset all the rates.\n\t\t */\n newZone.setAllToLowerBoundRate();\n newZone.recononicalize();\n newZone.dbmWarp(this);\n newZone.recononicalize();\n return newZone;\n }\n\n /**\n * Finds the maximum amount that time cam advance.\n * @return\n * \t\tvalue.\n * \t\tThe maximum amount that time can advance before a timer expires or an inequality changes\n */\n // * Several comments in this function may look like C code. That's because,\n // * well it is C code from atacs/src/lhpnrsg.c. In particular the\n // // Get the continuous variable in question.\n // // printf(\"Zone to check...\\n\");\n // // Get all the inequalities that reference the variable of interest.\n // // Update the inequality variable.\n // // /* Working on a > or >= ineq */\n // // Working on a > or >= ineq\n // // If the rate is positive.\n // // /* Working on a < or <= ineq */\n // // Working on a < or <= ineq\n // // Check if the value can be lowered.\n // //printf(\"Min leaving checkPreds for %s: %d\\n\",events[p]->event,min);\n /* (non-Javadoc)\n\t * @see java.lang.Object#clone()\n\t */\n @Override\n public Zone clone() {\n Zone clonedZone = new Zone();\n clonedZone._matrix = new int[this.matrixSize()][this.matrixSize()];\n for (int i = 0; i < this.matrixSize(); i++) {\n for (int j = 0; j < this.matrixSize(); j++) {\n clonedZone._matrix[i][j] = this._matrix[i][j];\n }\n }\n clonedZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n clonedZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();\n }\n clonedZone._hashCode = this._hashCode;\n clonedZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n clonedZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n return clonedZone;\n }\n\n /**\n * Restricts the lower bound of a timer.\n *\n * @param timer\n * \t\t\tThe timer to tighten the lower bound.\n */\n private void restrictTimer(int timer) {\n _matrix[dbmIndexToMatrixIndex(timer)][dbmIndexToMatrixIndex(0)] = getLowerBoundbydbmIndex(timer);\n }\n\n /**\n * Restricts the lower bound of a continuous variable. Also checks fixes\n * the upper bound to be at least as large if needed. This method\n * is usually used as a result of an event firing.\n * @param ltContPair\n * \t\tThe index of the continuous variable to restrict.\n * @param constant\n * \t\tThe constant value of the inequality event that is being used to update\n * \t\tthe variable indexed by ltContPair.\n */\n private boolean restrictContinuous(LPNContinuousPair ltContPair, int constant) {\n // It will be quicker to get the DBM index for the ltContPair one time.\n int variableIndex = timerIndexToDBMIndex(ltContPair);\n int zeroIndex = timerIndexToDBMIndex(LPNTransitionPair.ZERO_TIMER_PAIR);\n // Set the lower bound the variable (which is the DBM[variabl][0] entry.\n // Note : the lower bound in the zone is actually the negative of the lower\n // bound hence the -1 on the warpValue.\n setDbmEntry(variableIndex, zeroIndex, ContinuousUtilities.chkDiv(-1 * constant, ltContPair.getCurrentRate(), true));\n // Check if the upper bound needs to be advanced and advance it if necessary.\n if (getDbmEntry(zeroIndex, variableIndex) < ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true)) {\n // If the upper bound in the zones is less than the new restricting value, we\n // must advance it for the zone to remain consistent.\n setDbmEntry(zeroIndex, variableIndex, ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true));\n return true;\n }\n return false;\n }\n\n /**\n * Restricts the continuous variables in the zone according to the inequalities in a set of events.\n * @param eventSet\n * \t\t\tA set of inequality events. Does nothing if the event set does not contian inequalities.\n */\n private void restrictContinuous(EventSet eventSet) {\n // Check that the eventSet is a set of Inequality events.\n if (!eventSet.isInequalities()) {\n // If the eventSet is not a set of inequalities, do nothing.\n return;\n }\n HashSet adjustedColumns = new HashSet();\n boolean needsAdjusting = false;\n // Restrict the variables according to each of the inequalities in the eventSet.\n for (Event e : eventSet) {\n // Get the inequality.\n InequalityVariable iv = e.getInequalityVariable();\n // Extract the variable. I will assume the inequality only depends on a single\n Variable x = iv.getContVariables().get(0);\n // Extract the index.\n int lpnIndex = iv.get_lpn().getLpnIndex();\n // Extract the variable index.\n DualHashMap variableIndexMap = _lpnList[lpnIndex].getContinuousIndexMap();\n int variableIndex = variableIndexMap.getValue(x.getName());\n // Package it up for referencing.\n LPNContinuousPair ltContPair = new LPNContinuousPair(lpnIndex, variableIndex);\n // Need the current rate for the variable, grab the stored LPNContinuousPair.\n int zoneIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);\n if (zoneIndex > 0) {\n ltContPair = (LPNContinuousPair) _indexToTimerPair[zoneIndex];\n }\n // Perform the restricting.\n needsAdjusting = needsAdjusting | restrictContinuous(ltContPair, iv.getConstant());\n if (needsAdjusting) {\n adjustedColumns.add(ltContPair);\n }\n }\n // If one of the continuous variables has been moved forward, the other colmns\n // need to be adjusted to keep a consistent zone.\n if (needsAdjusting) {\n // At least one of the continuous variables has been moved forward,\n // so se need to ajust the bounds to keep a consistent zone.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltpair = _indexToTimerPair[i];\n if (adjustedColumns.contains(ltpair)) {\n // This continuous variables already had the upper bound\n continue;\n }\n // Add one to the upper bounds.\n setDbmEntry(0, i, getDbmEntry(0, i) + 1);\n }\n }\n }\n\n /**\n * Returns a zone that is the result from restricting the this zone according to a list of firing event inequalities.\n * @param eventSet\n * \t\tThe list of inequalities that are firing.\n * @return\n * \t\tThe new zone that is the result of restricting this zone according to the firing of the inequalities\n * \t\tin the eventSet.\n */\n @Override\n public Zone getContinuousRestrictedZone(EventSet eventSet, State[] localStates) {\n // Make a new copy of the zone.\n Zone z = this.clone();\n if (eventSet == null) {\n return z;\n }\n z.restrictContinuous(eventSet);\n return z;\n }\n\n /**\n * The list of enabled timers.\n * @return\n * \t\tThe list of all timers that have reached their lower bounds.\n */\n @Override\n public List getEnabledTransitions() {\n ArrayList enabledTransitions = new ArrayList();\n // Check if the timer exceeds its lower bound staring with the first nonzero\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n enabledTransitions.add(_lpnList[_indexToTimerPair[i].get_lpnIndex()].getTransition(_indexToTimerPair[i].get_transitionIndex()));\n }\n }\n return enabledTransitions;\n }\n\n /**\n * Gives the list of enabled transitions associated with a particular LPN.\n * @param LpnIndex\n * \t\t\tThe Index of the LPN the Transitions are a part of.\n * @return\n * \t\t\tA List of the Transitions that are enabled in the LPN given by the index.\n */\n @Override\n public List getEnabledTransitions(int LpnIndex) {\n ArrayList enabledTransitions = new ArrayList();\n // Check if the timer exceeds its lower bound staring with the first nonzero\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n if (ltPair.get_lpnIndex() == LpnIndex) {\n enabledTransitions.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));\n }\n }\n }\n return enabledTransitions;\n }\n\n /**\n * Find the next possible events.\n *\n * @param LpnIndex\n * \t\tThe index of the LPN that is of interest.\n * @param localState\n * \t\tThe state associated with the LPN indexed by LpnIndex.\n * @return\n * \t\tLpnTranList is populated with a list of\n * \t\tEventSets pertaining to the LPN with index LpnIndex. An EventSet can\n * \t\teither contain a transition to\n * \t\tfire or set of inequalities to change sign.\n */\n @Override\n public LpnTranList getPossibleEvents(int LpnIndex, State localState) {\n LpnTranList result = new LpnTranList();\n // Look through the timers and continuous variables. For the timers\n // determine if they are ready to fire. For the continuous variables,\n // look up the associated inequalities and see if any of them are ready\n // to fire.\n // We do not need to consider the zero timer, so start the\n // for loop at i=1 and not i=0.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // The enabled events are grouped with the LPN that they affect. So if\n // this pair does not belong to the current LPN under consideration, skip\n // processing it.\n if (ltPair.get_lpnIndex() != LpnIndex) {\n continue;\n }\n // If the index refers to a timer (and not a continuous variable) and has exceeded its lower bound,\n // then add the transition.\n if (!(ltPair instanceof LPNContinuousPair)) {\n // The index refers to a timer. Now check if time has advanced\n // far enough for the transition to fire.\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n Event e = new Event(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));\n result = addSetItem(this, result, e, localState);\n }\n } else {\n // The index refers to a continuous variable.\n // First check for a rate change event.\n LPNContinuousPair ltContPair = ((LPNContinuousPair) ltPair).clone();\n IntervalPair ratePair = getRateBounds(ltContPair);\n // // The rate represents a range of rates and no rate change\n // // event has occured.\n // // The rate contians zero, so we need to add two rate\n // // events: one for the lower bound and one for the upper\n // // Create the events.\n // // Add them to the result set.\n result = createRateEvents(this, ltContPair, ratePair, result, localState);\n // Check all the inequalities for inclusion.\n Variable contVar = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());\n if (contVar.getInequalities() != null) {\n for (InequalityVariable iv : contVar.getInequalities()) {\n // Check if the inequality can change.\n if (ContinuousUtilities.inequalityCanChange(this, iv, localState)) {\n result = addSetItem(this, result, new Event(iv), localState);\n }\n }\n }\n }\n }\n // Check the rate zero variables for possible rate change events.\n for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()) {\n // Get the reference object:\n LPNContinuousPair ltContPair = lcrPair.get_lcPair();\n // Extract the range of rates.\n IntervalPair ratePair = lcrPair.get_rateInterval();\n result = createRateEvents(this, ltContPair, ratePair, result, localState);\n }\n return result;\n }\n\n public static LpnTranList createRateEvents(Equivalence Z, LPNContinuousPair ltContPair, IntervalPair ratePair, LpnTranList result, State localState) {\n // // The rate represents a range of rates and no rate change\n // // event has occured.\n // // The rate contians zero, so we need to add two rate\n // // events: one for the lower bound and one for the upper\n // // Create the events.\n // // Add them to the result set.\n /*\n\t\t * Let [a,b] be the current range of rates for a given variable.\n\t\t * If a>=0, then we set the rate to b originally.\n\t\t * So if the current rate is b, then we have a rate change event to a.\n\t\t * \n\t\t * If b<=0, then we set the rate to a originially.\n\t\t * So if the current rate is a, then we have a rate change event to b.\n\t\t * \n\t\t * The final case to consider is when a < 0 and b > 0. If the current\n\t\t * rate is b, we allow rate changes to either a or 0. If the current\n\t\t * rate is a, we allow a rate change to zero.\n\t\t */\n if (ratePair.singleValue()) {\n // Rates that are not a range do not generate rate change events.\n return result;\n }\n ltContPair = ltContPair.clone();\n if (ratePair.get_LowerBound() >= 0) {\n if (ltContPair.getCurrentRate() == ratePair.get_UpperBound()) {\n ltContPair.setCurrentRate(ratePair.get_LowerBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n } else if (ratePair.get_UpperBound() <= 0) {\n if (ltContPair.getCurrentRate() == ratePair.get_LowerBound()) {\n ltContPair.setCurrentRate(ratePair.get_UpperBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n } else {\n if (ltContPair.getCurrentRate() == ratePair.get_UpperBound()) {\n // No rate change events have ocurred. So we allow one for zero\n // and the lower bounds rate.\n LPNContinuousPair ltContPairOther = ltContPair.clone();\n ltContPair.setCurrentRate(0);\n ltContPairOther.setCurrentRate(ratePair.get_LowerBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n result = addSetItem(Z, result, new Event(ltContPairOther), localState);\n } else if (ltContPair.getCurrentRate() == ratePair.get_LowerBound()) {\n // The rate has change to the lower bound. Allow one rate\n // change to zero.\n ltContPair.setCurrentRate(0);\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n }\n return result;\n }\n\n /**\n * Adds or removes items as appropriate to update the current\n * list of possible events. Note the type LpnTranList extends\n * LinkedList. The type EventSet extends transition\n * specifically so that objects of EventSet type can be place in\n * this list.\n * @param EventList\n * \t\t\tThe list of possible events.\n */\n public static LpnTranList addSetItem(Equivalence Z, LpnTranList E, Event e, State s) {\n // void lhpnAddSetItem(eventSets &E,lhpnEventADT e,ineqList &ineqL,lhpnZoneADT z,\n // lhpnStateADT cur_state)\n // Note the LPNTranList plays the role of the eventSets.\n int rv1l = 0, rv1u = 0, rv2l = 0, rv2u = 0, iZ, jZ;\n // printf(\"Event sets entering:\\n\");\n // Create the new LpnTranlist for holding the events.\n EventSet eSet = new EventSet();\n LpnTranList newE = new LpnTranList();\n boolean done = false;\n boolean possible = true;\n if (e.isRate()) {\n eSet.add(e);\n // I believe that I should actually copy over the old list\n // and then add the new event set.\n newE = E.copy();\n newE.addLast(eSet);\n // The previous two commands act to pass the changes of E\n // back out of the functions. So returning the new object\n // is suficient.\n // printf(\"Event sets leaving:\\n\");\n return newE;\n }\n if (e.isInequality()) {\n // Is this necessary, or even correct to update the inequalities.\n // System.out.println(\"Note the inequality is not being updated before in addSetItem\");\n // In this case the Event e represents an inequality.\n InequalityVariable ineq = e.getInequalityVariable();\n // Need to extract the rate.\n // To do this, I'll create the indexing object.\n Variable v = ineq.getContVariables().get(0);\n // Find the LPN.\n int lpnIndex = ineq.get_lpn().getLpnIndex();\n int varIndex = Z.getVarIndex(lpnIndex, v.getName());\n // Package it all up.\n // LPNTransitionPair ltPair =\n // Note : setting the rate is not necessary since\n // this is only being used as aan index.\n // LPNContinuousPair ltPair =\n LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);\n rv2l = ContinuousUtilities.chkDiv(-1 * ineq.getConstant(), Z.getCurrentRate(ltPair), true);\n rv2u = ContinuousUtilities.chkDiv(ineq.getConstant(), Z.getCurrentRate(ltPair), true);\n iZ = Z.getIndexByTransitionPair(ltPair);\n } else {\n // In this case, the event is a transition.\n Transition t = e.getTransition();\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n // Package the results.\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);\n iZ = Z.getIndexByTransitionPair(ltPair);\n }\n // Recall that E contains the events sets which are inherited from the Transition class\n // so they can be placed in an LpnTranList. So consider each event set.\n for (Transition es : E) {\n if (!(es instanceof EventSet)) {\n // This collection should contain event sets, not transitions.\n throw new IllegalArgumentException(\"The eventSet was a Transition object not an EventSet object.\");\n }\n EventSet eventSet = (EventSet) es;\n if (done) {\n // Copy any remaining sets into newE.\n newE.add(eventSet.clone());\n break;\n }\n EventSet workSet = eventSet.clone();\n // Get an iterator for the elements in the workset.\n for (Event oldEvent : eventSet) {\n // For matching code with atacs, note that oldEvent is 'j'.\n if (oldEvent.isRate()) {\n continue;\n }\n if (oldEvent.isInequality()) {\n // Again, is it necessary to do an update here?\n // System.out.println(\"Note the inequality is not being updated before in addSetItem\");\n // In this case the Event oldEvent represents an inequality.\n InequalityVariable ineq = oldEvent.getInequalityVariable();\n // Extract variable.\n Variable v = ineq.getContVariables().get(0);\n // Find the LPN.\n int lpnIndex = ineq.get_lpn().getLpnIndex();\n int varIndex = Z.getVarIndex(lpnIndex, v.getName());\n // Package it all up.\n // LPNTransitionPair ltPair =\n // Note : setting the rate is not necessary since this is\n // only being used as an index.\n // LPNContinuousPair ltPair =\n LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);\n rv1l = ContinuousUtilities.chkDiv(-1 * oldEvent.getInequalityVariable().getConstant(), Z.getCurrentRate(ltPair), true);\n rv1u = ContinuousUtilities.chkDiv(oldEvent.getInequalityVariable().getConstant(), Z.getCurrentRate(ltPair), true);\n jZ = Z.getIndexByTransitionPair(ltPair);\n } else {\n // In this case, the event is a transition.\n Transition t = oldEvent.getTransition();\n // Create the indexing object. (See the Abstraction Function protion at the\n // top of the class for more details.)\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n // Package the results.\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);\n jZ = Z.getIndexByTransitionPair(ltPair);\n }\n // /* Both actions are predicate changes */\n // Both actions are predicate changes.\n if (e.isInequality() && oldEvent.isInequality()) {\n // /* Both predicates are on the same variable */\n // Extract the variable lists.\n ArrayList newList = e.getInequalityVariable().getContVariables();\n ArrayList oldList = oldEvent.getInequalityVariable().getContVariables();\n // Issue a warning if one of the lists has more than a single\n if (newList.size() > 1 && oldList.size() > 1) {\n System.err.println(\"Warning: One of the inequalities \" + e + \" \" + oldEvent + \" refers to more than one variable\");\n }\n // Both inequalities are on the same variables.\n if (newList.get(0).equals(oldList.get(0))) {\n if (rv1l > rv2l) {\n possible = false;\n } else // printf(\"Adding to erase list: \\n\");\n if (rv2l > rv1l) {\n workSet.remove(oldEvent);\n } else // printf(\"Adding to erase list: \\n\");\n if (rv1u > rv2u) {\n workSet.remove(oldEvent);\n } else {\n workSet.add(e);\n done = true;\n }\n } else // /* Predicates are on different variables */\n // Inequalities are on different variables.\n {\n // TODO : Check that the indecies must be reversed. I believe\n // they do since I think my representation is the transpose\n // of atacs. This will affect all the following statements.\n if (rv1l > rv2l + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else // printf(\"Adding to erase list: \");\n if (rv2l > rv1l + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n } else // printf(\"Adding to erase list: \\n\");\n if (rv1u > Z.getUpperBoundTrue(iZ) + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n } else if (rv2u > Z.getUpperBoundTrue(jZ) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else if (rv1l == rv2l + Z.getDbmEntry(jZ, iZ) && rv2l == rv1l + Z.getDbmEntry(iZ, jZ) && rv1u == rv2u + Z.getDbmEntry(iZ, jZ) && rv2u == rv1u + Z.getDbmEntry(jZ, iZ)) {\n workSet.add(e);\n }\n }\n } else // /* New action is predicate change, old is transition firing (case 3) */\n // New action is an inequality and the old even tis a transition (case 3).\n if (e.isInequality() && oldEvent.isTransition()) {\n // printf(\"Adding to erase list: \\n\");\n if (rv2l > -1 * Z.getLowerBoundbyTransition(e.getTransition()) + Z.getDbmEntry(iZ, jZ)) {\n // Probably can change this to refer directly to the zone.\n workSet.remove(oldEvent);\n } else if (rv2u > Z.getUpperBoundTrue(jZ) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n }\n } else // /* TODO: One more ugly case, is it needed? */\n // /* New action is transition firing, old is predicate change (case 4) */\n // New event is a transition firing, old event is an inequality change (case 4).\n if (e.isTransition() && oldEvent.isInequality()) {\n if (rv1l > (-1) * Z.getLowerBoundbyTransition(e.getTransition()) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else // printf(\"Adding to erase list: \\n\");\n // Real one: fix the getting of the upper and lower bounds. Done\n if (rv1u > Z.getUpperBoundTrue(iZ) + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n }\n // /* TODO: one more ugly case, is it needed? */\n // I guess this one wasn't needed since it is not found in atacs.\n }\n }\n if (!(workSet.isEmpty())) {\n newE.add(workSet);\n }\n }\n // This part of the code is essentially copying the all the old event set into the new event set.\n // There might be a way around doing this by working directly on the set to begin with.\n // Moved to being done at the begining of the previous block.\n // // This collection should contain event sets, not transitions.\n // throw new IllegalArgumentException(\"The eventSet was a Transition object not an EventSet object.\");\n if (!done && possible) {\n eSet.add(e);\n newE.add(eSet);\n }\n E = newE;\n // printf(\"Event sets leaving:\\n\");\n return E;\n }\n\n @Override\n public int getVarIndex(int lpnIndex, String name) {\n return _lpnList[lpnIndex].getContinuousIndexMap().getValue(name);\n }\n\n /**\n * Adds a set item and explicitly sets a flag to remove the next set item\n * upon firing.\n * @param E\n * The list of current event sets.\n * @param e\n * The event to add.\n * @param s\n * The current state.\n * @param removeNext\n * True if afer firing this event, the next event should be removed from the\n * queue.\n * @return\n * The new event set.\n */\n // public static LpnTranList addSetItem(LpnTranList E, Event e, State s,\n /**\n * Updates the continuous variables that are set by firing a transition.\n * @param firedTran\n * \t\tThe transition that fired.\n * @param s\n * \t\tThe current (local) state.\n */\n public void updateContinuousAssignment(Transition firedTran, State s) {\n // Get the LPN.\n LPN lpn = _lpnList[firedTran.getLpn().getLpnIndex()];\n // Get the current values of the (local) state.\n HashMap currentValues = lpn.getAllVarsWithValuesAsString(s.getVariableVector());\n // Get all the continuous variable assignments.\n HashMap assignTrees = firedTran.getContAssignTrees();\n for (String contVar : assignTrees.keySet()) {\n // Get the bounds to assign the continuous variables.\n IntervalPair assignment = assignTrees.get(contVar).evaluateExprBound(currentValues, this, null);\n // Make the assignment.\n setContinuousBounds(contVar, lpn, assignment);\n }\n }\n\n /**\n * Updates the continuous variables according to the given values.\n * @param newContValues\n * \t\tThe new values of the continuous variables.\n */\n public void updateContinuousAssignment(ContinuousRecordSet newAssignValues) {\n /*\n\t\t * In dealing with the rates and continuous variables, there are four cases to consider. These cases\n\t\t * depend on whether the the old value of the 'current rate' is zero or non-zero and whether the\n\t\t * new value of the 'current rate' is zero or non-zero. \n\t\t * 0. old rate is zero, new rate is zero.\n\t\t * \t\tLookup the zero rate in the _rateZeroContinuous and add any new continuous assignments.\n\t\t * 1. old rate is zero, new rate is non-zero.\n\t\t * \t\tRemove the rate from the _rateZeroContinuous and add the zone.\n\t\t * 2. old rate is non-zero, new rate is zero.\n\t\t * \t\tAdd the variable with its upper and lower bounds to _rateZeroContinuous.\n\t\t * 3. old rate is non-zero, new rate is non-zero.\n\t\t * \t\tGet the LPNContinuousPair from the _indexToTimerPair and change the value.\n\t\t * \n\t\t * Note: If an assignment is made to the variable, then it should be considered as a\n\t\t * new variable.\n\t\t */\n // The updating of the rate-zero continuous variables is taken care of\n // by the copyRates. So just need to update the values in the zone.\n // This amounts to copying over the values from the old zone for\n // continuous variables that haven't changed and copying in\n // // Set the lower bound.\n // // Set the upper bound.\n // // Set the rate.\n // // Set the lower bound.\n // // Set the upper bound.\n // // Set the current rate.\n // // Set the upper and lower bounds for the rates.\n }\n\n /* (non-Javadoc)\n\t * @see verification.timed_state_exploration.zone.Zone#getLexicon()\n\t */\n /**\n * Gives an array that maps the index of a timer in the DBM to the timer's index.\n * @return\n * \t\tThe array that maps the index of a timer in the DBM to the timer's index.\n */\n /**\n * Calculates a warping value needed to warp a Zone. When a zone is being warped the form\n * r1*z2 - r1*z1 + r2*z1 becomes important in finding the new values of the zone. For example,\n *\n * @param z1\n * \t\tUpper bound or negative lower bound.\n * @param z2\n * \t\tRelative value.\n * @param r1\n * \t\tFirst ratio.\n * @param r2\n * \t\tSecond ratio.\n * @return\n * \t\tr1*z2 - r1*z1 + r2*z1\n */\n public static int warp(int z1, int z2, int r1, int r2) {\n /*\n\t\t * See \"Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets\"\n\t\t * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda\n\t\t * Section III.C for details on how this function is used and where it comes\n\t\t * from.\n\t\t */\n return r1 * z2 - r1 * z1 + r2 * z1;\n }\n\n /**\n * Warps this Zone with the aid of rate information from the previous Zone.\n *\n * @param oldZone\n * \t\tThe previous Zone.\n * @return\n * \t\tThe warped Zone.\n */\n @Override\n public void dbmWarp(Equivalence oldE) {\n Zone oldZone = (Zone) oldE;\n /*\n\t\t * See \"Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets\"\n\t\t * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda\n\t\t * Section III.C for details on how this function is used and where it comes\n\t\t * from.\n\t\t */\n // /* TODO: This appears to NOT work when INFIN is in the bounds?\n // Should I have to worry about this case? */\n // According to atacs comments, this appears to NOT work when\n // INFIN is in the bounds.\n // This portion of the code handles the warping of the relative\n // parts of the zone.\n for (int i = 1; i < dbmSize(); i++) {\n for (int j = i + 1; j < dbmSize(); j++) {\n double iVal, jVal, iWarp, jWarp, iXDot, jXDot;\n // Note : the iVal and the jVal correspond to the\n // alpha and beta describe in Scott Little's thesis.\n // /* deal w/ the fact that we might have continuous and discrete\n // Do some warping when dealing with the continuous variables.\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n // Calcualte the alpha value.\n iVal = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[i]) / (double) this.getCurrentRate(_indexToTimerPair[i])));\n // The old rate the zone was warped by.\n iWarp = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[i])));\n // The current rate rate of this continuous variable.\n iXDot = Math.floor(Math.abs((double) this.getCurrentRate(_indexToTimerPair[i])));\n // I'm not going to do any warping when the previous rate\n // is zero. This statement is a break to go to next i value\n // and not the next j.\n if (iWarp == 0) {\n break;\n }\n } else {\n // The current variable is a timer, so the new rate and old rate\n // are both 1. Hence we have\n iVal = 1.0;\n iWarp = 1.0;\n iXDot = 1.0;\n }\n // Do some warping of the second variable if it is a continuous variable.\n if (_indexToTimerPair[j] instanceof LPNContinuousPair) {\n // Calcualte the alpha value.\n jVal = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[j]) / (double) this.getCurrentRate(_indexToTimerPair[j])));\n // The old rate the zone was warped by.\n jWarp = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[j])));\n // The current rate of this continuous variable.\n jXDot = Math.floor(Math.abs((double) this.getCurrentRate(_indexToTimerPair[j])));\n // I'm not going to do any warping when the previous rate is\n if (jWarp == 0) {\n continue;\n }\n } else {\n // The current variable is a timer, so the new rate and old rate\n // are both 1. Hence we have\n jVal = 1.0;\n jWarp = 1.0;\n jXDot = 1.0;\n }\n // The zone is warped differently depending on which of rate is\n // larger. See Scott Little's Thesis for more details.\n if (iWarp * jXDot > jWarp * iXDot) {\n setDbmEntry(j, i, (int) Math.ceil(((jWarp * getDbmEntry(j, i)) / jXDot) + ((-1 * jWarp * getDbmEntry(0, i) / jXDot)) + ((iWarp * getDbmEntry(0, i) / iXDot))));\n setDbmEntry(i, j, (int) Math.ceil(((jWarp * getDbmEntry(i, j)) / jXDot) + ((-1 * jWarp * getDbmEntry(i, 0) / jXDot)) + ((iWarp * getDbmEntry(i, 0) / iXDot))));\n } else {\n setDbmEntry(i, j, (int) Math.ceil(((iWarp * getDbmEntry(i, j)) / iXDot) + ((-1 * iWarp * getDbmEntry(0, j) / iXDot)) + ((jWarp * getDbmEntry(0, j) / jXDot))));\n setDbmEntry(j, i, (int) Math.ceil(((iWarp * getDbmEntry(j, i)) / iXDot) + ((-1 * iWarp * getDbmEntry(j, 0) / iXDot)) + ((jWarp * getDbmEntry(j, 0) / jXDot))));\n }\n }\n }\n // printf(\"After fixing up initial warp conditions.\\n\");\n // Handle the warping of the bounds.\n for (int i = 1; i < dbmSize(); i++) {\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n if (Math.abs(getDbmEntry(i, 0)) != INFINITY) {\n if (oldZone.getCurrentRate(_indexToTimerPair[i]) == 0) {\n // If the older rate was zero, then we just need to\n // divide by the new rate.\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(getDbmEntry(i, 0), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n } else {\n // Undo the old warping and introduce the new warping.\n // If the bound is infinite, then division does nothing.\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i])) * getDbmEntry(i, 0), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n }\n }\n if (Math.abs(getDbmEntry(0, i)) != INFINITY) {\n if (oldZone.getCurrentRate(_indexToTimerPair[i]) == 0) {\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(getDbmEntry(0, i), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n } else {\n // Undo the old warping and introduce the new warping.\n // If the bound is inifite, then division does nothing.\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i])) * getDbmEntry(0, i), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n }\n }\n }\n }\n // printf(\"After fixing up places.\\n\");\n for (int i = 1; i < dbmSize(); i++) {\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n // /* TBD: If i & j are both changing direction do we need to\n // remove the warp info? */\n // Handle the case when the warping takes us into negative space.\n if ((double) oldZone.getCurrentRate(_indexToTimerPair[i]) / (double) this.getCurrentRate(_indexToTimerPair[i]) < 0.0) {\n /* We are warping into the negative space, so swap the upper and \n\t\t\t\t\t * lower bounds.\n\t\t\t\t\t */\n int temp = getDbmEntry(i, 0);\n setDbmEntry(i, 0, getDbmEntry(0, i));\n setDbmEntry(0, i, temp);\n // Set the relationships to Infinity since nothing else is known.\n for (int j = 1; j < dbmSize(); j++) {\n if (i != j) {\n setDbmEntry(i, j, INFINITY);\n setDbmEntry(j, i, INFINITY);\n }\n }\n }\n }\n }\n // printf(\"After handling negative warps.\\n\");\n /* Do the nature of how I store things, I do not think I need to do\n\t\t\t * this portion.\n\t\t\t */\n }\n\n /**\n * The DiagonalNonZeroException extends the java.lang.RuntimerExpcetion.\n * The intention is for this exception to be thrown is a Zone has a non zero\n * entry appear on the diagonal.\n *\n * @author Andrew N. Fisher\n */\n public class DiagonalNonZeroException extends java.lang.RuntimeException {\n\n private static final long serialVersionUID = -3857736741611605411L;\n\n /**\n * Creates a DiagonalNonZeroException.\n * @param Message\n * \t\t\tThe message to be displayed when the exception is thrown.\n */\n public DiagonalNonZeroException(String Message) {\n super(Message);\n }\n }\n\n /**\n * This exception is thrown when trying to merge two zones whose corresponding timers\n * do not agree.\n * @author Andrew N. Fisher\n */\n // // TODO : Check if this class can be removed.\n // * Generated serialVersionUID\n /**\n * Clears out the lexicon.\n */\n public static IntervalPair parseRate(String rate) {\n String rateNoSpaces = rate.trim();\n // First check if the string is a single number.\n // // The string is a number, so set the upper and lower bounds equal.\n // First check for a comma (representing an interval input).\n int commaIndex = rateNoSpaces.indexOf(\",\");\n if (commaIndex < 0) {\n // Assume that the string is a constant. A NumberFormatException\n // will be thrown otherwise.\n int i = Integer.parseInt(rate);\n return new IntervalPair(i, i);\n }\n String lowerString = rateNoSpaces.substring(1, commaIndex).trim();\n String upperString = rateNoSpaces.substring(commaIndex + 1, rateNoSpaces.length() - 1).trim();\n return new IntervalPair(Integer.parseInt(lowerString), Integer.parseInt(upperString));\n }\n\n /**\n * Get the list of LhpnFile objects that this Zone depends on.\n * @return\n * \t\tThe lits of LhpnFile objects that this Zone depends on.\n */\n @Override\n public LPN[] get_lpnList() {\n return _lpnList;\n }\n\n /**\n * Performs a division of two integers and either takes the ceiling or the floor. Note :\n * The integers are converted to doubles for the division so the choice of ceiling or floor is\n * meaningful.\n * @param top\n * \t\tThe numerator.\n * @param bottom\n * \t\tThe denominator.\n * @param ceil\n * \t\tTrue indicates return the ceiling and false indicates return the floor.\n * @return\n * \t\tReturns the ceiling of top/bottom if ceil is true and the floor of top/bottom otherwise.\n */\n // * This method was taken from atacs/src/hpnrsg.c\n // System.out.println(\"Warning: Divided by zero.\");\n /**\n * Returns the current rate of the variable.\n * @param contVar\n * \t\tThe LPNTransitionPair referring to a continuous variable.\n * @return\n * \t\tThe current rate of the continuous variable refenced by the LPNTransitionPair.\n * @throws IllegalArgumentException\n * \t\tIf the LPNTransitionPair is not an instance of an LPNContinuousPair.\n */\n @Override\n public int getCurrentRate(LPNTransitionPair contVar) {\n if (!(contVar instanceof LPNContinuousPair)) {\n // The LPNTransitionsPair does not refer to a continuous variable, so yell.\n throw new IllegalArgumentException(\"Zone.getCurrentRate was called\" + \" on an LPNTransitionPair that was not an LPNContinuousPair.\");\n }\n LPNContinuousPair cV = (LPNContinuousPair) contVar;\n // Search for the pair in the zone.\n int index = Arrays.binarySearch(_indexToTimerPair, cV);\n if (index > 0) {\n // The continuous variable was found amongst the non zero rate continuous variables.\n // Grab that indexing object instead since it has the rate.\n cV = (LPNContinuousPair) _indexToTimerPair[index];\n return cV.getCurrentRate();\n }\n // Since the variable was not found in the non-zero rate continuous\n // variables, assume the rate is zero.\n return 0;\n }\n\n /**\n * Sets the current rate for a continuous variable. It sets the rate regardless of\n * whether the variable is in the rate zero portion of the Zone or not. But it\n * does not move variables in and out of the zone.\n * @param contVar\n * \t\tThe index of the variable whose rate is going to be set.\n * @param currentRate\n * \t\tThe value of the rate.\n */\n @Override\n public void setCurrentRate(LPNTransitionPair contVar, int currentRate) {\n if (!(contVar instanceof LPNContinuousPair)) {\n // The LPNTransitionsPair does not refer to a continuous variable, so yell.\n throw new IllegalArgumentException(\"Zone.getCurrentRate was called\" + \" on an LPNTransitionPair that was not an LPNContinuousPair.\");\n }\n LPNContinuousPair cV = (LPNContinuousPair) contVar;\n // Check for the current variable in the rate zero variables.\n VariableRangePair variableRange = _rateZeroContinuous.getValue(new LPNContAndRate(cV, new IntervalPair(0, 0)));\n if (variableRange != null) {\n LPNContinuousPair lcPair = _rateZeroContinuous.getKey(variableRange).get_lcPair();\n lcPair.setCurrentRate(currentRate);\n return;\n }\n // Check for the current variable in the Zone variables.\n int index = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (index >= 0) {\n // The variable was found, set the rate.\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[index];\n lcPair.setCurrentRate(currentRate);\n }\n }\n\n /**\n * Adds a transition to a zone.\n * @param newTransitions\n * \t\t\tThe newly enabled transitions.\n * @return\n * \t\t\tThe result of adding the transition.\n */\n @Override\n public Zone addTransition(HashSet newTransitions, State[] localStates) {\n /*\n\t\t * The zone will remain the same for all the continuous variables.\n\t\t * The only thing that will change is a new transition will be added into the transitions.\n\t\t */\n // Create a Zone to alter.\n Zone newZone = new Zone();\n // Create a copy of the LPN list.\n newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n // Copy the rate zero continuous variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Create a copy of the current indexing pairs.\n newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + newTransitions.size()];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = _indexToTimerPair[i];\n }\n // Add the new transitions to the _indexToTimerPair list.\n // // Set up the index for the newTransitions list.\n int i = _indexToTimerPair.length;\n for (LPNTransitionPair ltPair : newTransitions) {\n newZone._indexToTimerPair[i++] = ltPair;\n }\n // Sort the _indexToTimerPair list.\n Arrays.sort(newZone._indexToTimerPair);\n // Create matrix.\n newZone._matrix = new int[newZone._indexToTimerPair.length + 1][newZone._indexToTimerPair.length + 1];\n // Convert the current transitions to a collection of transitions.\n HashSet oldTransitionSet = new HashSet();\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n oldTransitionSet.add(ltPair);\n }\n // Copy in the new transitions.\n newZone.copyTransitions(this, newTransitions, oldTransitionSet, localStates);\n return newZone;\n }\n\n /**\n * This method creates a zone identical to the current zone except all the current rates are turned to 1.\n * This is to provide a previous zone to the initial zone for warping.\n * @return\n * \t\tA zone identical to this zone with all rates set to 1.\n */\n private Zone beforeInitialZone() {\n Zone z = this.clone();\n for (int i = 1; i < z._indexToTimerPair.length; i++) {\n if (!(z._indexToTimerPair[i] instanceof LPNContinuousPair)) {\n break;\n }\n LPNContinuousPair lcPair = (LPNContinuousPair) z._indexToTimerPair[i];\n lcPair.setCurrentRate(1);\n }\n return z;\n }\n\n /**\n * Add a rate zero variable to the DBM portion of the zone. This method\n * is intended as an aid for when a rate zero variable gets assign a\n * non-zero rate.\n * @param ltContPair The continuous variable to move from the rate zero\n * variables.\n * @return The resulting Zone.\n */\n @Override\n public Zone moveOldRateZero(LPNContinuousPair ltContPair) {\n // Create a Zone to alter.\n Zone newZone = new Zone();\n // Create a copy of the LPN list.\n newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n // Copy the rate zero continuous variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Extract the continuous variable from the rate zero variables.\n LPNContAndRate rateZero = new LPNContAndRate(ltContPair, new IntervalPair(0, 0));\n // This gets the values for the continuous variable.\n VariableRangePair vrp = newZone._rateZeroContinuous.get(rateZero);\n IntervalPair values = vrp.get_range();\n // This replaces the rateZero with the one stored in the _rateZeroContinuous.\n // The purpose of this is to obtain the stored range of rates.\n rateZero = newZone._rateZeroContinuous.getKey(vrp);\n // Get the range of rates.\n IntervalPair rangeOfRates = rateZero.get_rateInterval();\n // Remove the continuous variable.\n newZone._rateZeroContinuous.delete(rateZero);\n // Create a copy of the current indexing pairs.\n newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + 1];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = _indexToTimerPair[i];\n }\n // Add the continuous variable to the list of variables/transition in the DBM.\n int numOfTransitions = _indexToTimerPair.length;\n newZone._indexToTimerPair[numOfTransitions] = ltContPair;\n // Sort the _indexToTimerPair list.\n Arrays.sort(newZone._indexToTimerPair);\n // Create matrix.\n newZone._matrix = new int[newZone._indexToTimerPair.length + 1][newZone._indexToTimerPair.length + 1];\n // Convert the current transitions to a collection of transitions.\n HashSet oldTransitionSet = new HashSet();\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n oldTransitionSet.add(ltPair);\n }\n // Copy in the new transitions.\n newZone.copyTransitions(this, new HashSet(), oldTransitionSet, null);\n // Get the index for the variable.\n int index = Arrays.binarySearch(newZone._indexToTimerPair, ltContPair);\n // Copy in the upper and lower bound of the old rate zero variable.\n // Copy in the range of rates.\n newZone.setLowerBoundbydbmIndex(index, rangeOfRates.get_LowerBound());\n newZone.setUpperBoundbydbmIndex(index, rangeOfRates.get_UpperBound());\n if (ltContPair.getCurrentRate() > 0) {\n // Set the upper and lower bounds.\n newZone.setDbmEntry(0, index, ContinuousUtilities.chkDiv(values.get_UpperBound(), ltContPair.getCurrentRate(), true));\n newZone.setDbmEntry(index, 0, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), ltContPair.getCurrentRate(), true));\n } else {\n // Set the upper and lower bounds. Since the rate is zero\n // We swap the real upper and lower bounds.\n newZone.setDbmEntry(0, index, ContinuousUtilities.chkDiv(values.get_LowerBound(), ltContPair.getCurrentRate(), true));\n newZone.setDbmEntry(index, 0, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), ltContPair.getCurrentRate(), true));\n }\n // Set the DBM to having no relating information for how this\n // variables relates to the other variables.\n for (int i = 1; i < newZone._indexToTimerPair.length; i++) {\n if (i == index) {\n continue;\n }\n newZone.setDbmEntry(index, i, Zone.INFINITY);\n newZone.setDbmEntry(i, index, Zone.INFINITY);\n }\n newZone.recononicalize();\n return newZone;\n }\n\n /**\n * This method removes the variable from the DBM portion of the\n * zone and adds the variable to the rate-zero portion of the\n * zone. The purpose of this method is to handle when a non-zero\n * rate variable is assigned a zero rate.\n * @param firedRate The new assignment for the variable.\n * @return The resulting zone.\n */\n @Override\n public Zone saveOutZeroRate(LPNContinuousPair firedRate) {\n // Check if the variable is in the zone.\n // We assume that the rate is already zero in this case\n // since it must be in the rate zero variables if it exists.\n int index = Arrays.binarySearch(this._indexToTimerPair, firedRate);\n if (index < 0) {\n System.err.println(\"A variable is getting its rate set to zero\");\n System.err.println(\"when the rate is already zero.\");\n return this;\n }\n // Create new zone\n Zone newZone = new Zone();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n // Copy over the rate zero variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Get the range of rates and values.\n IntervalPair rangeOfRates = this.getRateBounds(firedRate);\n IntervalPair rangeOfValues = this.getContinuousBounds(firedRate);\n // Create the key and value pairs for the rate zero continuous variable.\n LPNContAndRate lcar = new LPNContAndRate(firedRate.clone(), rangeOfRates);\n VariableRangePair vrPair = new VariableRangePair(this._lpnList[firedRate.get_lpnIndex()].getContVar(firedRate.get_ContinuousIndex()), rangeOfValues);\n newZone._rateZeroContinuous.insert(lcar, vrPair);\n // Copy over the pairs, skipping the new rate zero.\n newZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length - 1];\n int offset = 0;\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n if (i == index) {\n offset++;\n }\n newZone._indexToTimerPair[i] = this._indexToTimerPair[i + offset].clone();\n }\n // Copy over the DBM\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n int offseti = 0;\n int offsetj = 0;\n for (int i = 0; i < newZone.matrixSize(); i++) {\n if (i == index + 1) {\n offseti++;\n }\n offsetj = 0;\n for (int j = 0; j < newZone.matrixSize(); j++) {\n if (j == index + 1) {\n offsetj++;\n }\n newZone._matrix[i][j] = this._matrix[i + offseti][j + offsetj];\n }\n }\n return newZone;\n }\n\n @Override\n public int getIndexByTransitionPair(LPNTransitionPair ltPair) {\n return Arrays.binarySearch(_indexToTimerPair, ltPair);\n }\n /**\n * Determines whether time has advanced far enough for an inequality to change\n * truth value.\n * @param ineq\n * \t\tThe inequality to test whether its truth value can change.\n * @param localState\n * \t\tThe state associated with the inequality.\n * @return\n * \t\tTrue if the inequality can change truth value, false otherwise.\n */\n // // Find the index of the continuous variable this inequality refers to.\n // // I'm assuming there is a single variable.\n // // Package up the information into a the index. Note the current rate doesn't matter.\n // // Get the current rate.\n // // Get the current value of the inequality. This requires looking into the current state.\n // // Get the Zone index of the variable.\n // //\t\tbool lhpnPredCanChange(ineqADT ineq,lhpnZoneADT z,lhpnRateADT r,\n // //warn(\"An inequality produced a place not in the zone.\");\n // // First check cases when the rate is negative.\n // //warn(\"An inequality produced a place not in the zone.\");\n}\n"} {"task_id": "Java_3036", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/MyersResearchGroup/iBioSim/verification/src/main/java/edu/utah/ece/async/lema/verification/timed_state_exploration/zoneProject/Zone.java", "mask_start_position": 25952, "mask_end_position": 26233, "canonical_solution": "private void initialize_lpnList(State[] localStates) {\n // Create the LPN list.\n _lpnList = new LPN[localStates.length];\n // Get the LPNs.\n for (int i = 0; i < localStates.length; i++) {\n _lpnList[i] = localStates[i].getLpn();\n }\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * This file is part of iBioSim. Please visit \n * for the latest version of iBioSim.\n *\n * and also available online at .\n *\n * *****************************************************************************\n */\npackage edu.utah.ece.async.lema.verification.timed_state_exploration.zoneProject;\n\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport edu.utah.ece.async.lema.verification.lpn.ExprTree;\nimport edu.utah.ece.async.lema.verification.lpn.LPN;\nimport edu.utah.ece.async.lema.verification.lpn.Transition;\nimport edu.utah.ece.async.lema.verification.lpn.Variable;\nimport edu.utah.ece.async.lema.verification.platu.main.Options;\nimport edu.utah.ece.async.lema.verification.platu.platuLpn.DualHashMap;\nimport edu.utah.ece.async.lema.verification.platu.platuLpn.LpnTranList;\nimport edu.utah.ece.async.lema.verification.platu.stategraph.State;\nimport edu.utah.ece.async.lema.verification.timed_state_exploration.octagon.Equivalence;\n\n/**\n * This class is for storing and manipulating the delay information for transitions as well as\n * the values of continuous variables including rate their rates.\n * A Zone represents the non-zero continuous variables and the timers for the delay in a\n * Difference Bound Matrix (DBM)\n *\n * t0 c0 c1 t0 t1\n * t0 m00 m01 m02 m03 m04\n * c0 m10 m11 m12 m13 m14\n * c1 m20 m21 m22 m23 m24\n * t0 m30 m31 m32 m33 m34\n * t1 m40 m41 m42 m43 m44\n *\n * For the timers, tj - ti <= m(ti,tj) where m(ti,tj) represents the element of the matrix with\n * row ti and column tj. In particular, m(t0,ti) is an upper bound for ti and -m(ti,0) is a\n * lower bound for ti. The continuous variables are normalized to have rate one before being\n * placed in the matrix. Thus for a continuous variables ci with rate ri, the entry m(t0, ci) is\n * (upper bound)/ri where 'upper bound' is the upper bound for the continuous variable and\n * m(ci,t0) is -1*(lower bound)/ri where 'lower bound' is the lower bound of the continuous variable.\n * When the rate is negative, dividing out by the rate switches the inequalities. For example,\n * if ci is a continuous variable such that l < ci < u for some values l and u, then the normalized\n * ci (that is ci/ri) is satisfies u/ri < ci/r < l/ri. Hence the m(t0,ci) is (lower bound)/ri and\n * m(ci,0) is -1*(upper bound)/ri. The m(ci,cj) as well as m(ti,ci) and m(ci,ti) give the same kind\n * of relational information as with just timers, but with the normalized values of the continuous\n * variables. Note that a Zone with normalized continuous variables is referred to as being a 'warped'\n * zone.\n *\n * The rate zero continuous variables are also stored in a Zone object, but they are not present in\n * the zone. The Zone merely records the range of the continuous variable.\n *\n * The timers are referenced by the name of the transition that they are associated with and continuous\n * variables are referenced by their name as well. In addition for non-zero rate continuous variables and\n * the timers, several method will allow them to be referred by their index as a part of the (DMB). For\n * example, c0 in the above DBM example, has index 1.\n *\n * A third way that the timers and variables (both rate zero and rate non-zero) can be referred to by\n * an LPNTransitionPair object. These objects refer to a timer or continuous variable by providing the index\n * of the corresponding transition or the index of the continuous variable as a member of an LPN and the\n * index of that LPN. The LPNTransitionPair can be made more specific in the case of the continuous variables\n * by using an LPNContinuousPair. These objects also provide the rate of the variable. LPNTransitionPairs\n * can be used with continuous variables when they are only being used as an index only. If the rate is needed\n * for the method, then LPNContinuousPairs must be used.\n *\n * @author Andrew N. Fisher\n * @author Chris Myers\n * @author iBioSim Contributors \n * @version %I%\n */\npublic class Zone implements Equivalence {\n\n /*Abstraction Function : \n\t* The difference bound matrix is stored in the _matrix member field, along with \n\t* the upper and lower bounds of the timers and rates for continuous variables.\n\t* The upper and lower bounds are stored when the timer becomes enabled. The upper and\n\t* lower bounds of the rates are stored when the rate is assigned. The upper and lower \n\t* bounds are stored in the first row and first column of the _matrix member field.\n\t* The DBM occupies the rest of the array, that is, the sub-array formed by removing\n\t* the first column and first row.\n\t* For example, let t1 be a timer for a transition whose delay is between 2 and 3. Further\n\t* let c1 be a continuous variable with rate between 4 and 5. Then _matrix would look like\n\t* lb t0 c1 t1\n\t* ub x 0 5 3\n\t* t0 0 m m m\n\t* c1 -4 m m m\n\t* t1 -2 m m m\n\t* \n\t* with out the lb, ub, t0, t1, and c1.\n\t* \n\t* The x is does not represent anything and will most likely be zero. The upper and lower \n\t* bounds for the zero timer (which is always present) are always 0. The m's comprise \n\t* the DBM.\n\t* \n\t* For the most part, a timer or a continuous variable is referred to internally by an\n\t* LPNTransitionPair. An LPNTransitionPair combines the index of the transition (or\n\t* continuous variable) with the index of the LPN that the transition (or continuous \n\t* variables) is a member of. Both continuous variables and transitions can be referred\n\t* to by an LPNTransitionPair; however, it is better to use an LPNContinuousPair (which\n\t* is inherited from the LPNTransitionPair) to refer to continuous variables.\n\t* LPNContinuousPairs are used to distinguish continuous variables from transitions. They \n\t* also store the current rate of the continuous variable. \n\t* \n\t* The LPNTransitionPairs are stored in the _indexToTimerPair member field. The row/column\n\t* in the DBM for a transition is determined by the its position in this array. For example,\n\t* suppose a transition t has an LPNTransitionPair ltTranPair that is the third element of\n\t* the _indexToTimerPair. Then t will be the third column/row of the DBM.\n\t* \n\t* Continuous variables are handled slightly differently. The LPNContinuousPair for the \n\t* continuous variables with a non-zero rate are stored in the _indexToTimerPair just as \n\t* with the transitions. And just like with the transitions, the index in the DBM is\n\t* determined by the index of the LPNContinuousPair in the _indexToTimerPair. However,\n\t* rate zero continuous variables are stored in the _rateZeroContinuous member variable.\n\t* The _rateZerContinuous pairs an LPNContinuousPair with a VariableRangePair. The\n\t* VariableRangePair combines the variable with its upper and lower bound.\n\t* \n\t*/\n /* Representation invariant :\n\t* Zones are immutable.\n\t* Integer.MAX_VALUE is used to logically represent infinity.\n\t* The lb and ub values for a timer should be set when the timer is enabled.\n\t* A negative hash code indicates that the hash code has not been set.\n\t* The index of the timer in _indexToTimer is the index in the DBM and should contain\n\t* \tthe zeroth timer.\n\t* The array _indexToTimerPair should always be sorted.\n\t* The index of the LPN should match where it is in the _lpnList, that is, if lpn is\n\t* \tand LhpnFile object in _lpnList, then _lpnList[getLpnIndex()] == lpn.\n\t* The LPNTransitionPair in the _indexToTimer array should be an LPNContinuousPair\n\t* when it stores the index to a continuous variable. Testing that the index\n\t* is an LPNContinuousPair is used to determined if the indexing object points\n\t* to a continuous variable. Also the LPNContinuousPair keeps track of the current rate.\n\t* \n\t*/\n /*\n\t * Resource List :\n\t * TODO : Create a list reference where the algorithms can be found that this class\n\t * depends on.\n\t */\n public static final int INFINITY = Integer.MAX_VALUE;\n\n /* The lower and upper bounds of the times as well as the dbm. */\n private int[][] _matrix;\n\n /* Maps the index to the timer. The index is row/column of the DBM sub-matrix.\n\t * Logically the zero timer is given index -1.\n\t * */\n private LPNTransitionPair[] _indexToTimerPair;\n\n /* The hash code. */\n private int _hashCode;\n\n /* A lexicon between a transitions index and its name. */\n /* Set if a failure in the testSplit method has fired already. */\n /* Hack to pass a parameter to the equals method though a variable */\n /* Stores the continuous variables that have rate zero */\n DualHashMap _rateZeroContinuous;\n\n /* Records the largest zone that occurs. */\n public static int ZoneSize = 0;\n\n /* Write a log file */\n private static BufferedWriter _writeLogFile = null;\n\n /**\n * Returns the write log.\n * @return\n * \t\tThe _writeLogfile.\n */\n public static BufferedWriter get_writeLogFile() {\n return _writeLogFile;\n }\n\n /**\n * Sets the BufferedWriter.\n * @param writeLogFile\n */\n public static void set_writeLogFile(BufferedWriter writeLogFile) {\n _writeLogFile = writeLogFile;\n }\n\n /**\n * Sets the writeLogFile to null.\n */\n public static void reset_writeLogFile() {\n _writeLogFile = null;\n }\n\n private void checkZoneMaxSize() {\n if (dbmSize() > ZoneSize) {\n ZoneSize = dbmSize();\n }\n }\n\n private LPN[] _lpnList;\n\n /* \n\t * Turns on and off subsets for the zones.\n\t * True means subset will be considered.\n\t * False means subsets will not be considered.\n\t */\n private static boolean _subsetFlag = true;\n\n /* \n\t * Turns on and off supersets for zones.\n\t * True means that supersets will be considered.\n\t * False means that supersets will not be considered.\n\t */\n private static boolean _supersetFlag = true;\n\n /**\n * Gets the value of the subset flag.\n * @return\n * \t\tTrue if subsets are requested, false otherwise.\n */\n public static boolean getSubsetFlag() {\n return _subsetFlag;\n }\n\n /**\n * Sets the value of the subset flag.\n * @param useSubsets\n * \t\t\tThe value for the subset flag. Set to true if\n * \t\t\tsupersets are to be considered, false otherwise.\n */\n public static void setSubsetFlag(boolean useSubsets) {\n _subsetFlag = useSubsets;\n }\n\n /**\n * Gets the value of the superset flag.\n * @return\n * \t\tTrue if supersets are to be considered, false otherwise.\n */\n public static boolean getSupersetFlag() {\n return _supersetFlag;\n }\n\n /**\n * Sets the superset flag.\n * @param useSupersets\n * \t\tThe value of the superset flag. Set to true if\n * \t\tsupersets are to be considered, false otherwise.\n */\n public static void setSupersetFlag(boolean useSupersets) {\n _supersetFlag = useSupersets;\n }\n\n /**\n * Construct a zone that has the given timers.\n * @param timers\n * \t\t\t\tThe ith index of the array is the index of the timer. For example,\n * \t\t\t\t\tif timers = [1, 3, 5], then the zeroth row/column of the DBM is the\n * \t\t\t\t\ttimer of the transition with index 1, the first row/column of the\n * \t\t\t\t\tDBM is the timer of the transition with index 3, and the 2nd\n * \t\t\t\t\trow/column is the timer of the transition with index 5. Do not\n * \t\t\t\t\tinclude the zero timer.\n * @param matrix\n * \t\t\t\tThe DBM augmented with the lower and upper bounds of the delays for the\n * \t\t\t\t\ttransitions. For example, suppose a zone has timers [1, 3, 5] (as\n * \t\t\t\t\tdescribed in the timers parameters). The delay for transition 1 is\n * \t\t\t\t\t[1, 3], the delay for transition 3 is [2,5], and the delay for\n * \t\t\t\t\ttransition 5 is [4,6]. Also suppose the DBM is\n * \t\t\t\t\t t0 t1 t3 t5\n * \t\t\t\t\tt0 | 0, 3, 3, 3 |\n * \t\t\t\t\tt1 | 0, 0, 0, 0 |\n * \t\t\t\t\tt3 | 0, 0, 0, 0 |\n * \t\t\t\t\tt5 | 0, 0, 0, 0 |\n * \t\t\t\t\tThen the matrix that should be passed is\n * \t\t\t\t\t lb t0 t1 t3 t5\n * \t\t\t\t\tub| 0, 0, 3, 5, 6|\n * \t\t\t\t\tt0| 0, 0, 3, 3, 3|\n * \t\t\t\t\tt1|-1, 0, 0, 0, 0|\n * \t\t\t\t\tt3|-2, 0, 0, 0, 0|\n * \t\t\t\t\tt5|-4, 0, 0, 0, 0|\n * \t\t\t\t\tThe matrix should be non-null and the zero timer should always be the\n * \t\t\t\t\tfirst timer, even when there are no other timers.\n */\n public Zone(int[] timers, int[][] matrix) {\n // A negative number indicates that the hash code has not been set.\n _hashCode = -1;\n // Make a copy to reorder the timers.\n // Make a copy to reorder the timers.\n _indexToTimerPair = new LPNTransitionPair[timers.length];\n for (int i = 0; i < timers.length; i++) {\n _indexToTimerPair[i] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);\n }\n // Sorting the array.\n // Sorting the array.\n Arrays.sort(_indexToTimerPair);\n // // Add the zeroth timer.\n if (_indexToTimerPair[0].get_transitionIndex() != -1) {\n // Add the zeroth timer.\n LPNTransitionPair[] newIndexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newIndexToTimerPair[i + 1] = _indexToTimerPair[i];\n }\n _indexToTimerPair = newIndexToTimerPair;\n _indexToTimerPair[0] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, -1);\n }\n // throw new IllegalArgumentException(\"Timers must be non negative.\");\n // // Add a zero timer.\n // Map the old index of the timer to the new index of the timer.\n HashMap newIndex = new HashMap();\n // For the old index, find the new index.\n for (int i = 0; i < timers.length; i++) {\n // Since the zeroth timer is not included in the timers passed\n // to the index in the DBM is 1 more than the index of the timer\n // in the timers array.\n // LPNTransitionPair searchValue =\n LPNTransitionPair searchValue = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);\n newIndex.put(i + 1, Arrays.binarySearch(_indexToTimerPair, searchValue));\n }\n // Add the zero timer index.\n newIndex.put(0, 0);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Copy the DBM\n for (int i = 0; i < dbmSize(); i++) {\n for (int j = 0; j < dbmSize(); j++) {\n // Copy the passed in matrix to _matrix.\n setDbmEntry(newIndex.get(i), newIndex.get(j), matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]);\n // In the above, changed setDBMIndex to setdbm\n }\n }\n // Copy in the upper and lower bounds. The zero time does not have an upper or lower bound\n // so the index starts at i=1, the first non-zero timer.\n for (int i = 1; i < dbmSize(); i++) {\n setUpperBoundbydbmIndex(newIndex.get(i), matrix[0][dbmIndexToMatrixIndex(i)]);\n // Note : The method setLowerBoundbydbmIndex, takes the value of the lower bound\n // and the matrix stores the negative of the lower bound. So the matrix value\n // must be multiplied by -1.\n setLowerBoundbydbmIndex(newIndex.get(i), -1 * matrix[dbmIndexToMatrixIndex(i)][0]);\n }\n recononicalize();\n }\n\n /**\n * Initializes a zone according to the markings of state.\n * @param currentState\n * \t\t\tThe zone is initialized as if all enabled timers\n * \t\t\thave just been enabled.\n */\n public Zone(State initialState) {\n // Extract the associated LPN.\n LPN lpn = initialState.getLpn();\n int LPNIndex = lpn.getLpnIndex();\n if (_lpnList == null) {\n // If no LPN exists yet, create it and put lpn in it.\n _lpnList = new LPN[LPNIndex + 1];\n _lpnList[LPNIndex] = lpn;\n } else if (_lpnList.length <= LPNIndex) {\n // The list does not contain the lpn.\n LPN[] tmpList = _lpnList;\n _lpnList = new LPN[LPNIndex + 1];\n _lpnList[LPNIndex] = lpn;\n // Copy any that exist already.\n for (int i = 0; i < _lpnList.length; i++) {\n _lpnList[i] = tmpList[i];\n }\n } else if (_lpnList[LPNIndex] != lpn) {\n // This checks that the appropriate lpn is in the right spot.\n // If not (which gets you in this block), then this fixes it.\n _lpnList[LPNIndex] = lpn;\n }\n // Default value for the hash code indicating that the hash code has not\n // been set yet.\n _hashCode = -1;\n // Get the list of currently enabled Transitions by their index.\n boolean[] enabledTran = initialState.getTranVector();\n ArrayList enabledTransitionsArrayList = new ArrayList();\n LPNTransitionPair zeroPair = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, LPNTransitionPair.ZERO_TIMER);\n // Add the zero timer first.\n enabledTransitionsArrayList.add(zeroPair);\n // The index of the boolean value corresponds to the index of the Transition.\n for (int i = 0; i < enabledTran.length; i++) {\n if (enabledTran[i]) {\n enabledTransitionsArrayList.add(new LPNTransitionPair(LPNIndex, i));\n }\n }\n _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);\n _matrix = new int[matrixSize()][matrixSize()];\n for (int i = 1; i < dbmSize(); i++) {\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = lpn.getTransition(_indexToTimerPair[i].get_transitionIndex()).getLabel();\n ExprTree delay = lpn.getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = lpn.getAllVarsWithValuesAsString(initialState.getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n ExprTree lowerDelay = delay.getLeftChild();\n ExprTree upperDelay = delay.getRightChild();\n lower = (int) lowerDelay.evaluateExpr(varValues);\n upper = (int) upperDelay.evaluateExpr(varValues);\n } else {\n lower = (int) delay.evaluateExpr(varValues);\n upper = lower;\n }\n setLowerBoundbydbmIndex(i, lower);\n setUpperBoundbydbmIndex(i, upper);\n }\n // Advance the time and tighten the bounds.\n advance();\n recononicalize();\n checkZoneMaxSize();\n }\n\n /**\n * Creates a Zone based on the local states.\n * @param localStates\n * \t\t\tThe current state (or initial) of the LPNs.\n */\n public Zone(State[] localStates) {\n // Open the log file.\n if (_writeLogFile == null && Options.get_TimingLogfile() != null) {\n try {\n _writeLogFile = new BufferedWriter(new FileWriter(Options.get_TimingLogfile()));\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n }\n }\n // Initialize hash code to -1 (indicating nothing cached).\n _hashCode = -1;\n // Initialize the LPN list.\n initialize_lpnList(localStates);\n // Get the enabled transitions. This initializes the _indexTotimerPair\n // which stores the relevant information.\n // This method will also initialize the _rateZeroContinuous\n initialize_indexToTimerPair(localStates);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Set the lower bound/ upper bounds of the timers and the rates.\n initializeLowerUpperBounds(getAllNames(), localStates);\n // Initialize the row and column entries for the continuous variables.\n initializeRowColumnContVar();\n // Create a previous zone to the initial zone for the sake of warping.\n Zone tmpZone = beforeInitialZone();\n dbmWarp(tmpZone);\n recononicalize();\n // Advance Time\n advance(localStates);\n // Re-canonicalize\n recononicalize();\n // Check the size of the DBM.\n checkZoneMaxSize();\n }\n\n /**\n * Creates a Zone based on the local states.\n * @param localStates\n * \t\t\tThe current state (or initial) of the LPNs.\n */\n public Zone(State[] localStates, boolean init) {\n // Extract the local states.\n // Initialize hash code to -1 (indicating nothing cached).\n _hashCode = -1;\n // Initialize the LPN list.\n initialize_lpnList(localStates);\n // Get the enabled transitions. This initializes the _indexTotimerPair\n // which stores the relevant information.\n // This method will also initialize the _rateZeroContinuous\n initialize_indexToTimerPair(localStates);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Set the lower bound/ upper bounds of the timers and the rates.\n initializeLowerUpperBounds(getAllNames(), localStates);\n // Initialize the row and column entries for the continuous variables.\n initializeRowColumnContVar();\n if (init) {\n return;\n }\n // Advance Time\n advance(localStates);\n // Re-canonicalize\n recononicalize();\n // Check the size of the DBM.\n checkZoneMaxSize();\n }\n\n // * Sets ups a zone containing continuous variables only.\n // * @param continuousValues\n // * \t\tThe values to populate the zone with.\n // // Copy the LPNContinuousPairs over\n // int count = 0; // The position in the _indexToTimerPair for the next value.\n /**\n * Gives the names of all the transitions and continuous variables that\n * are represented by the zone.\n * @return\n * \t\tThe names of the transitions and continuous variables that are\n * \t\trepresented by the zone.\n */\n public String[] getAllNames() {\n // transitionNames[0] = \"The zero timer.\";\n // Get the continuous variable names.\n String[] contVar = getContVarNames();\n // Get the transition names.\n String[] trans = getTranNames();\n // Create an array large enough for all the names.\n String[] names = new String[contVar.length + trans.length + 1];\n // Add the zero timer.\n names[0] = \"The zero timer.\";\n // Add the continuous variables.\n for (int i = 0; i < contVar.length; i++) {\n names[i + 1] = contVar[i];\n }\n // Add the timers.\n for (int i = 0; i < trans.length; i++) {\n // Already the zero timer has been added and the elements of contVar.\n // That's a total of 'contVar.length + 1' elements. The last index was\n // thus 'contVar.length' So the first index to add to is\n names[1 + contVar.length + i] = trans[i];\n }\n return names;\n }\n\n /**\n * Get the names of the continuous variables that this zone uses.\n * @return\n * \t\tThe names of the continuous variables that are part of this zone.\n */\n public String[] getContVarNames() {\n // List for accumulating the names.\n ArrayList contNames = new ArrayList();\n // Find the pairs that represent the continuous variables. Loop starts at\n // i=1 since the i=0 is the zero timer.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // If the isTimer value is false, then this pair represents a continuous\n // If pair is LPNContinuousPair.\n if (ltPair instanceof LPNContinuousPair) {\n // Get the LPN that this pairing references and find the name of\n // the continuous variable whose index is given by this pairing.\n contNames.add(_lpnList[ltPair.get_lpnIndex()].getContVarName(ltPair.get_transitionIndex()));\n }\n }\n return contNames.toArray(new String[0]);\n }\n\n /**\n * Gets the names of the transitions that are associated with the timers in the\n * zone. Does not return the zero timer.\n * @return\n * \t\tThe names of the transitions whose timers are in the zone except the zero\n * \t\ttimer.\n */\n public String[] getTranNames() {\n // List for accumulating the names.\n ArrayList transitionNames = new ArrayList();\n // Find the pairs that represent the transition timers.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // If the isTimer value is true, then this pair represents a timer.\n // If this is an LPNTransitionPair and not an LPNContinuousPair\n if (!(ltPair instanceof LPNContinuousPair)) {\n // Get the LPN that this pairing references and find the name of the\n // transition whose index is given by this pairing.\n transitionNames.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()).getLabel());\n }\n }\n return transitionNames.toArray(new String[0]);\n }\n\n /**\n * Initializes the _lpnList using information from the local states.\n * @param localStates\n * \t\tThe local states.\n * @return\n * \t\tThe enabled transitions.\n */\n ", "post_mask_code": "\n\n /**\n * Initializes the _indexToTimerPair from the local states. This includes\n * adding the zero timer, the continuous variables and the set of\n * enabled timers.\n * @param localStates\n * \t\tThe local states.\n * @return\n * \t\tThe names of the transitions stored in the _indexToTimerPair (in the same order).\n */\n private void initialize_indexToTimerPair(State[] localStates) {\n /*\n\t\t * The populating of the _indexToTimerPair is done in three stages.\n\t\t * The first is to add the zero timer which is at the beginning of the zone.\n\t\t * The second is to add the continuous variables. And the third is to add\n\t\t * the other timers. Since the continuous variables are added before the\n\t\t * timers and the variables and timers are added in the order of the LPNs,\n\t\t * the elements in an accumulating list (enabledTransitionsArrayList) are\n\t\t * already in order up to the elements added for a particular LPN. Thus the\n\t\t * only sorting that needs to take place is the sorting for a particular LPN.\n\t\t * Correspondingly, elements are first found for an LPN and sort, then added\n\t\t * to the main list.\n\t\t */\n // This method will also initialize the _rateZeroContinuous\n _rateZeroContinuous = new DualHashMap();\n // This list accumulates the transition pairs (ie timers) and the continuous\n ArrayList enabledTransitionsArrayList = new ArrayList();\n // Put in the zero timer.\n // enabledTransitionsArrayList\n enabledTransitionsArrayList.add(new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, LPNTransitionPair.ZERO_TIMER));\n // Get the continuous variables.\n for (int i = 0; i < localStates.length; i++) {\n // Accumulates the changing continuous variables for a single LPN.\n ArrayList singleLPN = new ArrayList();\n // Get the associated LPN.\n LPN lpn = localStates[i].getLpn();\n // Get the continuous variables for this LPN.\n String[] continuousVariables = lpn.getContVars();\n // Get the variable, index map.\n DualHashMap variableIndex = lpn.getContinuousIndexMap();\n // Find which have a nonzero rate.\n for (int j = 0; j < continuousVariables.length; j++) {\n // Get the Variables with this name.\n Variable contVar = lpn.getVariable(continuousVariables[j]);\n // Get the rate.\n IntervalPair rate = parseRate(contVar.getInitRate());\n // Get the LPN index for the variable\n int lpnIndex = lpn.getLpnIndex();\n // Get the index as a variable for the LPN.\n int contVariableIndex = variableIndex.get(continuousVariables[j]);\n LPNContinuousPair newPair = new LPNContinuousPair(lpnIndex, contVariableIndex, rate.getSmallestRate());\n // If the rate is non-zero, then the variables needs to be tracked\n // by matrix part of the Zone.\n if (newPair.getCurrentRate() != 0) {\n // Temporary exception guaranteeing only unit rates.\n // \"only supports positive unit rates. The variable \" + contVar +\n // \" has a rate of \" + rate);\n // // Get the LPN index for the variable\n // // Get the index as a variable for the LPN. This index matches\n // // the index in the vector stored by platu.State.\n // The continuous variable reference.\n singleLPN.add(newPair);\n } else {\n // If the rate is zero, then the Zone keeps track of this variable\n // in a list.\n _rateZeroContinuous.insert(new LPNContAndRate(newPair, rate), new VariableRangePair(contVar, parseRate(contVar.getInitValue())));\n }\n }\n // Sort the list.\n Collections.sort(singleLPN);\n // Add the list to the total accumulating list.\n for (int j = 0; j < singleLPN.size(); j++) {\n enabledTransitionsArrayList.add(singleLPN.get(j));\n }\n }\n // Get the transitions.\n for (int i = 0; i < localStates.length; i++) {\n // Extract the enabled transition vector.\n boolean[] enabledTran = localStates[i].getTranVector();\n // Accumulates the transition pairs for one LPN.\n ArrayList singleLPN = new ArrayList();\n // The index of the boolean value corresponds to the index of the Transition.\n for (int j = 0; j < enabledTran.length; j++) {\n if (enabledTran[j]) {\n // Add the transition pair.\n singleLPN.add(new LPNTransitionPair(i, j));\n }\n }\n // Sort the transitions for the current LPN.\n Collections.sort(singleLPN);\n // Add the collection to the enabledTransitionsArrayList\n for (int j = 0; j < singleLPN.size(); j++) {\n enabledTransitionsArrayList.add(singleLPN.get(j));\n }\n }\n // Extract out the array portion of the enabledTransitionsArrayList.\n _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);\n }\n\n /**\n * Sets the lower and upper bounds for the transitions and continuous variables.\n * @param varNames\n * \t\t\tThe names of the transitions in _indexToTimerPair.\n */\n private void initializeLowerUpperBounds(String[] varNames, State[] localStates) {\n // Traverse the entire length of the DBM sub-matrix except the zero row/column.\n // This is the same length as the _indexToTimerPair.length-1. The DBM is used to\n // match the idea of setting the value for each row.\n for (int i = 1; i < dbmSize(); i++) {\n // Get the current LPN and transition pairing.\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n IntervalPair range;\n if (ltPair instanceof LPNContinuousPair) {\n // If the pairing represents a continuous variable, then the\n // upper and lower bound are the initial value or infinity depending\n // on whether the initial rate is positive or negative.\n // If the value is a constant, then assign the upper and lower bounds\n // to be constant. If the value is a range then assign the upper and\n // lower bounds to be a range.\n Variable v = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());\n String rate = v.getInitRate();\n // Parse the rate. Should be in the form of [x,y] where x\n // and y are integers.\n range = parseRate(rate);\n // Set the upper and lower bound (in the matrix) for the\n // continuous variables.\n String contValue = v.getInitValue();\n IntervalPair bound = parseRate(contValue);\n // Set upper bound (DBM entry (0, x) where x is the index of the variable v).\n setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, bound.get_UpperBound());\n // Set lower bound (DBM entry (x, 0) where x is the index of the variable v).\n setDbmEntryByPair(ltPair, LPNTransitionPair.ZERO_TIMER_PAIR, -1 * bound.get_LowerBound());\n } else {\n // Get the expression tree.\n ExprTree delay = _lpnList[ltPair.get_lpnIndex()].getDelayTree(varNames[i]);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[ltPair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[ltPair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n // Passing the zone as null since it should not be needed.\n // // The lower and upper bounds should evaluate to a single\n // throw new IllegalStateException(\"When evaulating the delay, \" +\n // \"the lower or the upper bound evaluated to a range \" +\n // \"instead of a single value.\");\n if (delay != null) {\n range = delay.evaluateExprBound(varValues, this, null);\n } else {\n range = new IntervalPair(0, 0);\n }\n }\n setLowerBoundbydbmIndex(i, range.get_LowerBound());\n setUpperBoundbydbmIndex(i, range.get_UpperBound());\n }\n }\n\n /**\n * Initialize the rows and columns for the continuous variables.\n */\n private void initializeRowColumnContVar() {\n /*\n\t\t * TODO : Describe the idea behind the following algorithm.\n\t\t */\n // // Note: row is indexing the row of the DBM matrix.\n // // If we reached the timers, stop.\n // // Note: col is indexing the column of the DBM matrix.\n // // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since\n // // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower\n // // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);\n // The only entries that do not need to be checked are the ones where both variables\n // represent timers.\n for (int row = 2; row < _indexToTimerPair.length; row++) {\n // Note: row is indexing the row of the DBM matrix.\n LPNTransitionPair ltRowPair = _indexToTimerPair[row];\n // // If we reached the timers, stop.\n for (int col = 1; col < row; col++) {\n // Note: col is indexing the column of the DBM matrix.\n LPNTransitionPair ltColPair = _indexToTimerPair[col];\n // If we've reached the part of the zone involving only timers, then break out\n if (!(ltRowPair instanceof LPNContinuousPair) && !(ltColPair instanceof LPNContinuousPair)) {\n break;\n }\n // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since\n // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower\n // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);\n int rowCol = getDbmEntry(row, 0) + getDbmEntry(0, col);\n int colRow = getDbmEntry(col, 0) + getDbmEntry(0, row);\n setDbmEntry(row, col, rowCol);\n setDbmEntry(col, row, colRow);\n }\n }\n }\n\n /**\n * Zero argument constructor for use in methods that create Zones where the members\n * variables will be set by the method.\n */\n private Zone() {\n _matrix = new int[0][0];\n _indexToTimerPair = new LPNTransitionPair[0];\n _hashCode = -1;\n _lpnList = new LPN[0];\n _rateZeroContinuous = new DualHashMap();\n }\n\n /**\n * Gets the upper bound of a Transition from the zone.\n * @param t\n * \t\tThe transition whose upper bound is wanted.\n * @return\n * \t\tThe upper bound of Transition t.\n */\n public int getUpperBoundbyTransition(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n // LPNTransitionPair ltPair =\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return getUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Returns the upper bound of the continuous variable.\n * @param var\n * \t\tThe variable of interest.\n * @return\n * \t\tThe (0,var) entry of the zone, that is the maximum as recored by\n * \t\tthe zone.\n */\n public int getUpperBoundbyContinuousVariable(String contVar, LPN lpn) {\n // // Determine whether the variable is in the zone or rate zero.\n // // If a RangeAndPairing is returned, then get the information from here.\n // // If indexAndRange is null, then try to get the value from the zone.\n // throw new IllegalStateException(\"Atempted to find the upper bound for \"\n // + \"a non-rate zero continuous variable that was not found in the \"\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note : setting the rate is not necessary here since this is only\n // being used as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range().get_UpperBound();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the lower bound for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n return getDbmEntry(0, i);\n }\n\n public int getUpperBoundForRate(LPNTransitionPair contVar) {\n // Check if the contVar is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (i > 0) {\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n // Grab the current rate from the LPNContinuousPair.\n return ((LPNContinuousPair) _indexToTimerPair[i]).getCurrentRate();\n }\n // Assume the rate is zero. This covers the case if conVar\n // is in the rate zero as well as if its not in the state at all.\n return 0;\n }\n\n /**\n * Get the value of the upper bound for the delay. If the index refers\n * to a timer, otherwise get the upper bound for the continuous\n * variables rate.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @return\n * \t\t\tThe upper bound on the transitions delay.\n */\n public int getUpperBoundbydbmIndex(int index) {\n return _matrix[0][dbmIndexToMatrixIndex(index)];\n }\n\n public int getUpperBound(int index) {\n return _matrix[0][dbmIndexToMatrixIndex(index)];\n }\n\n @Override\n public int getUpperBoundTrue(int index) {\n return _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(index)];\n }\n\n public int getUnwarpedUpperBound(LPNContinuousPair lcpair) {\n // Get the index.\n int index = Arrays.binarySearch(_indexToTimerPair, lcpair);\n int rate = ((LPNContinuousPair) _indexToTimerPair[index]).getCurrentRate();\n int warpValue = getUpperBoundTrue(index);\n return warpValue * rate;\n }\n\n public int getLowerBound(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][0];\n }\n\n @Override\n public int getLowerBoundTrue(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][dbmIndexToMatrixIndex(0)];\n }\n\n /**\n * Set the value of the upper bound for the delay.\n * @param t\n * \t\t\tThe transition whose upper bound is being set.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n public void setUpperBoundbyTransition(Transition t, int value) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the upper bound for the delay.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n public void setUpperBoundbydbmIndex(int index, int value) {\n _matrix[0][dbmIndexToMatrixIndex(index)] = value;\n }\n\n /**\n * Sets the upper bound for a transition described by an LPNTransitionPair.\n * @param ltPair\n * \t\t\tThe index of the transition and the index of the associated LPN for\n * \t\t\tthe timer to set the upper bound.\n * @param value\n * \t\t\tThe value for setting the upper bound.\n */\n private void setUpperBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value) {\n setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Gets the lower bound of a Transition from the zone.\n * @param t\n * \t\tThe transition whose upper bound is wanted.\n * @return\n * \t\tThe lower bound of Transition t.\n */\n @Override\n public int getLowerBoundbyTransition(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return getLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Returns the lower bound of the continuous variable.\n * @param var\n * \t\tThe variable of interest.\n * @return\n * \t\tThe (0,var) entry of the zone, that is the minimum as recored by\n * \t\tthe zone.\n */\n public int getLowerBoundbyContinuousVariable(String contVar, LPN lpn) {\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note: Setting the rate is not necessary since this is only being used\n // as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range().get_LowerBound();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the lower bound for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n return getDbmEntry(i, 0);\n }\n\n /**\n * Get the value of the lower bound for the delay if the index refers\n * to a timer, otherwise get the lower bound for the continuous variables\n * rate.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @return\n * \t\t\tThe value of the lower bound.\n */\n public int getLowerBoundbydbmIndex(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][0];\n }\n\n public int getLowerBoundForRate(LPNTransitionPair contVar) {\n // Check if the contVar is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (i > 0) {\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n return getLowerBoundbydbmIndex(contVar.get_transitionIndex());\n }\n // Assume the rate is zero. This covers the case if conVar\n // is in the rate zero as well as if its not in the state at all.\n return 0;\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param t\n * \t\t\tThe transition whose lower bound is being set.\n * @param value\n * \t\t\tThe value of the lower bound.\n */\n public void setLowerBoundbyTransition(Transition t, int value) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param t\n * \t\t\tThe transition whose upper bound is being set.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n private void setLowerBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value) {\n setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @param value\n * \t\t\tThe value of the lower bound.\n */\n public void setLowerBoundbydbmIndex(int index, int value) {\n _matrix[dbmIndexToMatrixIndex(index)][0] = -1 * value;\n }\n\n /**\n * Give the upper and lower bounds for a continuous variable.\n * @param contVar\n * \t\tThe variable of interest.\n * @return\n * \t\tThe upper and lower bounds according to the Zone.\n */\n @Override\n public IntervalPair getContinuousBounds(String contVar, LPN lpn) {\n /*\n\t\t * Need to determine whether this is suppose to be a rate zero variable or a non-zero \n\t\t * rate variable. One method is to check the rate of the passed variable. The other is\n\t\t * to just check if the variable is present in either place.\n\t\t */\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n // Get the index of the continuous variable.\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note: setting the current rate is not necessary here since the\n // LPNContinuousPair is only being used as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(new LPNContAndRate(index, new IntervalPair(0, 0)));\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the bounds for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n // Else find the upper and lower bounds.\n int lower = (-1) * getDbmEntry(i, 0);\n int upper = getDbmEntry(0, i);\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the range for the continuous variable. Values come back not\n * warped.\n * @param ltContPair\n * \t\tThe index of the variable of interest.\n * @return\n * \t\tThe range of the continuous variable described by ltContPair.\n */\n @Override\n public IntervalPair getContinuousBounds(LPNContinuousPair ltContPair) {\n // First check in the zone.\n int variableIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);\n if (variableIndex < 0) {\n // The variable was not found in the zone. Check to see if its\n // in the rate-zero variables. Technically I will return whatever\n // is in the _rateZeroConintuous, null or not.\n // First get an object to reference into the _rateZeroContinuous\n LPNContAndRate lcr = new LPNContAndRate(ltContPair, new IntervalPair(0, 0));\n return _rateZeroContinuous.get(lcr).get_range();\n }\n // The variable was found in the zone. Yay.\n int lower = (-1) * getDbmEntry(variableIndex, 0) * getCurrentRate(ltContPair);\n int upper = getDbmEntry(0, variableIndex) * getCurrentRate(ltContPair);\n // If the current rate is negative the upper and lower bounds\n // need to be switched.\n if (getCurrentRate(ltContPair) < 0) {\n int tmp = lower;\n lower = upper;\n upper = tmp;\n }\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the range of the rate associated with a continuous variable.\n * @param ltContPair\n * \t\tThe index of the continuous variable.\n * @return\n * \t\tThe range of rates associated with the continuous variable indexed\n * \t\tby ltContPair.\n */\n @Override\n public IntervalPair getRateBounds(LPNTransitionPair ltPair) {\n int upper;\n int lower;\n // Check if the ltContpair is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, ltPair);\n if (i < 0) {\n // Then the variable is in the rate zero continuous\n // variables so get the range of rates from there.\n // Create an object to reference into the rate zero.\n LPNContAndRate lcr = new LPNContAndRate((LPNContinuousPair) ltPair, new IntervalPair(0, 0));\n // Get the old version of lcr from the rate zero since\n // that contains the rate. This is quite a hack.\n VariableRangePair vrp = _rateZeroContinuous.get(lcr);\n lcr = _rateZeroContinuous.getKey(vrp);\n return lcr.get_rateInterval();\n }\n upper = getUpperBoundbydbmIndex(i);\n lower = -1 * getLowerBoundbydbmIndex(i);\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the rate reset value.\n * @param ltPair\n * @return\n */\n @Override\n public int rateResetValue(LPNTransitionPair ltPair) {\n IntervalPair rateBounds = getRateBounds(ltPair);\n int upper = rateBounds.get_UpperBound();\n int lower = rateBounds.get_LowerBound();\n // // Check if the ltContpair is in the zone.\n // // Assume the rate is zero. This covers the case if conVar\n // // is in the rate zero as well as if its not in the state at all.\n // If zero is a possible rate, then it is the rate to set to.\n // // If zero is the only possible rate, return that.\n // // When zero is in the range and there is a positive rate, return the\n // // When the upper bound is zero, return the negative rate.\n // // When zero is not present, use the smallest rate in absolute value.\n /*\n\t\t * Suppose the range of rates is [a,b]. If a>=0, we set the rate to b.\n\t\t * If b<=0, we set the rate to a. Otherwise, a<0=0, we set the rate to b.\n\t\t * If b<=0, we set the rate to a. Otherwise, a<0 variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note : Setting the rate is not necessary since this only being used\n // as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and make the new assignment.\n if (pairing != null) {\n pairing.set_range(range);\n return;\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the bounds for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n // Else find the upper and lower bounds.\n setDbmEntry(i, 0, (-1) * range.get_LowerBound());\n setDbmEntry(0, i, range.get_UpperBound());\n }\n\n /**\n * Converts the index of the DBM to the index of _matrix.\n * @param i\n * \t\t\tThe row/column index of the DBM.\n * @return\n * \t\t\tThe row/column index of _matrix.\n */\n private static int dbmIndexToMatrixIndex(int i) {\n return i + 1;\n }\n\n /**\n * Retrieves an entry of the DBM using the DBM's addressing.\n * @param i\n * \t\t\tThe row of the DBM.\n * @param j\n * \t\t\tThe column of the DBM.\n * @return\n * \t\t\tThe value of the (i, j) element of the DBM.\n */\n @Override\n public int getDbmEntry(int i, int j) {\n return _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)];\n }\n\n /**\n * Retrieves an entry of the DBM using LPNTransitionPair indecies.\n * @param iPair\n * \t\tThe LPNTransitionPair for the ith entry.\n * @param jPair\n * \t\tThe LPNTransitionPair for the jth entry.\n * @return\n * \t\tThe value of the (i,j) element of the DBM where i corresponds to the row\n * \t\tfor the variable iPair and j corresponds to the row for the variable jPair.\n */\n @Override\n public int getDbmEntryByPair(LPNTransitionPair iPair, LPNTransitionPair jPair) {\n int iIndex = Arrays.binarySearch(_indexToTimerPair, iPair);\n int jIndex = Arrays.binarySearch(_indexToTimerPair, jPair);\n return getDbmEntry(iIndex, jIndex);\n }\n\n /**\n * Sets an entry of the DBM using the DBM's addressing.\n * @param i\n * \t\t\tThe row of the DBM.\n * @param j\n * \t\t\tThe column of the DBM.\n * @param value\n * \t\t\tThe new value for the entry.\n */\n private void setDbmEntry(int i, int j, int value) {\n _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)] = value;\n }\n\n /**\n * Sets the entry in the DBM using the LPNTransitionPair indexing.\n * @param row\n * \t\t\tThe LPNTransitionPair for the row.\n * @param col\n * \t\t\tThe LPNTransitionPair for the column.\n * @param value\n * \t\t\tThe value to set the entry to.\n */\n private void setDbmEntryByPair(LPNTransitionPair row, LPNTransitionPair col, int value) {\n // The row index.\n int i = timerIndexToDBMIndex(row);\n // The column index.\n int j = timerIndexToDBMIndex(col);\n setDbmEntry(i, j, value);\n }\n\n /**\n * Returns the index of the the transition in the DBM given a LPNTransitionPair pairing\n * the transition index and associated LPN index.\n * @param ltPair\n * \t\tThe pairing comprising the index of the transition and the index of the associated\n * \t\tLPN.\n * @return\n * \t\tThe row/column of the DBM associated with the ltPair.\n */\n @Override\n public int timerIndexToDBMIndex(LPNTransitionPair ltPair) {\n return Arrays.binarySearch(_indexToTimerPair, ltPair);\n }\n\n /**\n * The matrix labeled with 'ti' where i is the transition index associated with the timer.\n */\n @Override\n public String toString() {\n // TODO : Fix the handling of continuous variables in the\n String result = \"Timer and delay or continuous and ranges.\\n\";\n int count = 0;\n // Print the timers.\n for (int i = 1; i < _indexToTimerPair.length; i++, count++) {\n if (_lpnList.length == 0) {\n // If no LPN's are associated with this Zone, use the index of the timer.\n result += \" t\" + _indexToTimerPair[i].get_transitionIndex() + \" : \";\n } else {\n String name;\n // If the current LPNTransitionPair is a timer, get the name\n // from the transitions.\n // If the current timer is an LPNTransitionPair and not an LPNContinuousPair\n if (!(_indexToTimerPair[i] instanceof LPNContinuousPair)) {\n // Get the name of the transition.\n Transition tran = _lpnList[_indexToTimerPair[i].get_lpnIndex()].getTransition(_indexToTimerPair[i].get_transitionIndex());\n name = tran.getLabel();\n } else {\n // If the current LPNTransitionPair is not a timer, get the\n // name as a continuous variable.\n Variable var = _lpnList[_indexToTimerPair[i].get_lpnIndex()].getContVar(_indexToTimerPair[i].get_transitionIndex());\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];\n int lowerBound = -1 * getDbmEntry(i, 0) * lcPair.getCurrentRate();\n int upperBound = getDbmEntry(0, i) * lcPair.getCurrentRate();\n // If the rate is negative, the bounds are switched\n // in the zone.\n if (lcPair.getCurrentRate() < 0) {\n int tmp = lowerBound;\n lowerBound = upperBound;\n upperBound = tmp;\n }\n name = var.getName() + \":[\" + lowerBound + \",\" + upperBound + \"]\\n\" + \" Current Rate: \" + lcPair.getCurrentRate() + \" \" + \"rate:\";\n }\n result += \" \" + name + \":\";\n }\n result += \"[ \" + -1 * getLowerBoundbydbmIndex(i) + \", \" + getUpperBoundbydbmIndex(i) + \" ]\";\n if (count > 9) {\n result += \"\\n\";\n count = 0;\n }\n }\n if (!_rateZeroContinuous.isEmpty()) {\n result += \"\\nRate Zero Continuous : \\n\";\n for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()) {\n result += \"\" + _rateZeroContinuous.get(lcrPair) + \"Rate: \" + lcrPair.get_rateInterval();\n }\n }\n result += \"\\nDBM\\n\";\n // Print the DBM.\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n result += \"| \" + String.format(\"%3d\", getDbmEntry(i, 0));\n for (int j = 1; j < _indexToTimerPair.length; j++) {\n result += \", \" + String.format(\"%3d\", getDbmEntry(i, j));\n }\n result += \" |\\n\";\n }\n return result;\n }\n\n /**\n * Tests for equality. Overrides inherited equals method.\n * @return True if o is equal to this object, false otherwise.\n */\n @Override\n public boolean equals(Object o) {\n // Check if the reference is null.\n if (o == null) {\n return false;\n }\n // Check that the type is correct.\n if (!(o instanceof Zone)) {\n return false;\n }\n // Check for equality using the Zone equality.\n return equals((Zone) o);\n }\n\n /**\n * Tests for equality.\n * @param\n * \t\tThe Zone to compare.\n * @return\n * \t\tTrue if the zones are non-null and equal, false otherwise.\n */\n public boolean equals(Zone otherZone) {\n // Check if the reference is null first.\n if (otherZone == null) {\n return false;\n }\n // Check for reference equality.\n if (this == otherZone) {\n return true;\n }\n // If the hash codes are different, then the objects are not equal.\n if (this.hashCode() != otherZone.hashCode()) {\n return false;\n }\n // Check if the they have the same number of timers.\n if (this._indexToTimerPair.length != otherZone._indexToTimerPair.length) {\n return false;\n }\n // Check if the timers are the same.\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n if (!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))) {\n return false;\n }\n }\n // Check if the matrix is the same\n for (int i = 0; i < _matrix.length; i++) {\n for (int j = 0; j < _matrix[0].length; j++) {\n if (!(this._matrix[i][j] == otherZone._matrix[i][j])) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Determines if this zone is a subset of Zone otherZone.\n * @param otherZone\n * \t\tThe zone to compare against.\n * @return\n * \t\tTrue if this is a subset of other; false otherwise.\n */\n @Override\n public boolean subset(Equivalence otherEquiv) {\n Zone otherZone = (Zone) otherEquiv;\n // Check if the reference is null first.\n if (otherZone == null) {\n return false;\n }\n // Check for reference equality.\n if (this == otherZone) {\n return true;\n }\n // Check if the the same number of timers are present.\n if (this._indexToTimerPair.length != otherZone._indexToTimerPair.length) {\n return false;\n }\n // Check if the transitions are the same.\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n if (!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))) {\n return false;\n }\n }\n // Check if the entries of this Zone are less than or equal to the entries\n // of the other Zone.\n for (int i = 0; i < _matrix.length; i++) {\n for (int j = 0; j < _matrix[0].length; j++) {\n if (!(this._matrix[i][j] <= otherZone._matrix[i][j])) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Determines if this zone is a superset of Zone otherZone.\n * @param otherZone\n * \t\tThe zone to compare against.\n * @return\n * \t\tTrue if this is a subset of other; false otherwise. More specifically it\n * \t\tgives the result of otherZone.subset(this). Thus it agrees with the subset method.\n */\n @Override\n public boolean superset(Equivalence otherZone) {\n return otherZone.subset(this);\n }\n\n /**\n * Overrides the hashCode.\n */\n @Override\n public int hashCode() {\n // Check if the hash code has been set.\n if (_hashCode < 0) {\n _hashCode = createHashCode();\n }\n return _hashCode;\n }\n\n /**\n * Creates a hash code for a Zone object.\n * @return\n * \t\tThe hash code.\n */\n private int createHashCode() {\n int newHashCode = Arrays.hashCode(_indexToTimerPair);\n for (int i = 0; i < _matrix.length; i++) {\n newHashCode ^= Arrays.hashCode(_matrix[i]);\n }\n return Math.abs(newHashCode);\n }\n\n /**\n * The size of the DBM sub matrix. This is calculated using the size of _indexToTimer.\n * @return\n * \t\t\tThe size of the DBM.\n */\n private int dbmSize() {\n return _indexToTimerPair.length;\n }\n\n /**\n * The size of the matrix.\n * @return\n * \t\t\tThe size of the matrix. This is calculated using the size of _indexToTimer.\n */\n private int matrixSize() {\n return _indexToTimerPair.length + 1;\n }\n\n /**\n * Performs the Floyd's least pairs algorithm to reduce the DBM.\n */\n @Override\n public void recononicalize() {\n for (int k = 0; k < dbmSize(); k++) {\n for (int i = 0; i < dbmSize(); i++) {\n for (int j = 0; j < dbmSize(); j++) {\n if (getDbmEntry(i, k) != INFINITY && getDbmEntry(k, j) != INFINITY && getDbmEntry(i, j) > getDbmEntry(i, k) + getDbmEntry(k, j)) {\n setDbmEntry(i, j, getDbmEntry(i, k) + getDbmEntry(k, j));\n }\n if ((i == j) && getDbmEntry(i, j) != 0) {\n throw new DiagonalNonZeroException(\"Entry (\" + i + \", \" + j + \")\" + \" became \" + getDbmEntry(i, j) + \".\");\n }\n }\n }\n }\n }\n\n /**\n * Determines if a timer associated with a given transitions has reached its lower bound.\n * @param t\n * \t\t\tThe transition to consider.\n * @return\n * \t\t\tTrue if the timer has reached its lower bound, false otherwise.\n */\n public boolean exceedsLowerBoundbyTransitionIndex(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return exceedsLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Determines if a timer has reached its lower bound.\n * @param timer\n * \t\t\tThe timer's index.\n * @return\n * \t\t\tTrue if the timer has reached its lower bound, false otherwise.\n */\n public boolean exceedsLowerBoundbydbmIndex(int index) {\n // Note : Make sure that the lower bound is stored as a negative number\n // and that the inequality is correct.\n return _matrix[0][dbmIndexToMatrixIndex(index)] <= _matrix[1][dbmIndexToMatrixIndex(index)];\n }\n\n /* (non-Javadoc)\n\t * @see verification.timed_state_exploration.zone.Zone#fireTransitionbyTransitionIndex(int, int[], verification.platu.stategraph.State)\n\t */\n // State state)\n // // Check if the value is in this zone to fire.\n /**\n * Gives the Zone obtained by firing a given Transitions.\n * @param t\n * \t\tThe transitions being fired.\n * @param enabledTran\n * \t\tThe list of currently enabled Transitions.\n * @param localStates\n * \t\tThe current local states.\n * @return\n * \t\tThe Zone obtained by firing Transition t with enabled Transitions enabled\n * \t\tenabledTran when the current state is localStates.\n */\n // public Zone fire(Transition t, LpnTranList enabledTran,\n @Override\n public Zone fire(Transition t, LpnTranList enabledTran, ContinuousRecordSet newAssignValues, State[] localStates) {\n try {\n if (_writeLogFile != null) {\n _writeLogFile.write(t.toString());\n _writeLogFile.newLine();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n // Create the LPNTransitionPair to check if the Transitions is in the zone and to\n // find the index.\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n int dbmIndex = Arrays.binarySearch(_indexToTimerPair, ltPair);\n if (dbmIndex <= 0) {\n return this;\n }\n // Get the new zone portion.\n Zone newZone = fireTransitionbydbmIndexNew(dbmIndex, enabledTran, localStates, newAssignValues);\n // Update any assigned continuous variables.\n // Set all the rates to their lower bound.\n newZone.setAllToLowerBoundRate();\n // Warp the Zone\n newZone.dbmWarp(this);\n // Warping can wreck the newly assigned values so correct them.\n newZone.correctNewAssignemnts(newAssignValues);\n newZone.recononicalize();\n newZone.advance(localStates);\n // Recanonicalize\n newZone.recononicalize();\n newZone.checkZoneMaxSize();\n return newZone;\n }\n\n /**\n * Updates the Zone according to the transition firing.\n * @param index\n * \t\t\tThe index of the timer.\n * @param newContValue\n * @return\n * \t\t\tThe updated Zone.\n */\n public Zone fireTransitionbydbmIndex(int index, LpnTranList enabledTimers, State[] localStates, ArrayList> newAssignValues) {\n /*\n\t\t * For the purpose of adding the newly enabled transitions and removing\n\t\t * the disable transitions, the continuous variables that still have\n\t\t * a nonzero rate can be treated like still enbaled timers.\n\t\t */\n // Initialize the zone.\n Zone newZone = new Zone();\n // These sets will defferentiate between the new timers and the\n // old timers, that is between the timers that are not already in the\n // zone and those that are already in the zone..\n HashSet newTimers = new HashSet();\n HashSet oldTimers = new HashSet();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n HashMap oldNonZero = newAssignValues.get(3);\n // Add the continuous variables to the enabled timers.\n for (int i = 1; _indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n // For the purpose of addigng continuous variables to the zone\n // consider an oldNonZero continuous variable as new.\n if (oldNonZero.containsKey(_indexToTimerPair[i])) {\n continue;\n }\n oldTimers.add(_indexToTimerPair[i]);\n }\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n // Determine if each value is a new timer or old.\n if (Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0) {\n // The timer was already present in the zone.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else {\n // The timer is a new timer.\n newTimers.add(newZone._indexToTimerPair[i]);\n }\n }\n // Create the new matrix.\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n // TODO: For simplicity, make a copy of the current zone and perform the\n // restriction and re-canonicalization. Later add a copy re-canonicalization\n // that does the steps together.\n Zone tempZone = this.clone();\n tempZone.restrictTimer(index);\n tempZone.recononicalize();\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);\n newZone._matrix[Zone.dbmIndexToMatrixIndex(newIndexi)][Zone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n // The block copies the upper and lower bound information from the\n // old zone. Thus we do not consider anything that is not an old\n // timer. Furthermore, oldNonZero represent\n if (!oldTimers.contains(tempZone._indexToTimerPair[i]) && !oldNonZero.containsKey(_indexToTimerPair[i])) {\n continue;\n }\n newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n newZone.setLowerBoundByLPNTransitionPair(pair, lower);\n newZone.setUpperBoundByLPNTransitionPair(pair, upper);\n }\n // Advance time.\n return newZone;\n }\n\n public Zone fireTransitionbydbmIndexNew(int index, LpnTranList enabledTimers, State[] localStates, ContinuousRecordSet newAssignValues) {\n /*\n\t\t * For the purpose of adding the newly enabled transitions and removing\n\t\t * the disable transitions, the continuous variables that still have\n\t\t * a nonzero rate can be treated like still enbaled timers.\n\t\t */\n // Initialize the zone.\n Zone newZone = new Zone();\n // These sets will defferentiate between the new timers and the\n // old timers, that is between the timers that are not already in the\n // zone and those that are already in the zone..\n HashSet newTimers = new HashSet();\n HashSet oldTimers = new HashSet();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n copyRatesNew(newZone, enabledTimers, newAssignValues);\n // Add the continuous variables to the enabled timers.\n // // For the purpose of addigng continuous variables to the zone\n // // consider an oldNonZero continuous variable as new.\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n // Handle the continuous variables portion.\n if (newZone._indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];\n // Get the record\n UpdateContinuous continuousState = newAssignValues.get(lcPair);\n if (continuousState != null && (continuousState.is_newValue() || continuousState.newlyNonZero())) {\n // In the first case a new value has been assigned, so\n // consider the continuous variable a 'new' variable for\n // the purposes of copying relations from the previous zone.\n newTimers.add(newZone._indexToTimerPair[i]);\n continue;\n }\n // At this point, either the continuous variable was not present\n // in the newAssignValues or it is in the newAssignValues and\n // satisfies the following: it already had a non-zero rate, is\n // being assigned another non-zero rate, and is not being assigned\n // a new value. This is becuase the field _indexToTimerPair only\n // deals with non-zero rates, so the variable must have a non-zero\n // rate. Furthermore the if statement takes care of the cases\n // when the rate changed from zero to non-zero and/or a new value\n // has been assigned.\n // In either of the cases, we consider the variable an 'old' variable\n // for the purpose of copying the previous zone information.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else // At this point, the variable represents a transition (timer).\n // So determine whether this timer is new or old.\n if (Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0) {\n // The timer was already present in the zone.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else {\n // The timer is a new timer.\n newTimers.add(newZone._indexToTimerPair[i]);\n }\n }\n // Create the new matrix.\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n // TODO: For simplicity, make a copy of the current zone and perform the\n // restriction and re-canonicalization. Later add a copy re-canonicalization\n // that does the steps together.\n Zone tempZone = this.clone();\n tempZone.restrictTimer(index);\n tempZone.recononicalize();\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);\n newZone._matrix[Zone.dbmIndexToMatrixIndex(newIndexi)][Zone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n // The block copies the upper and lower bound information from the\n // old zone. Thus we do not consider anything that is not an old\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n // A hack to ensure that the newly zero variables\n // get the new values from the tempZone.\n if (tempZone._indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) tempZone._indexToTimerPair[i];\n VariableRangePair vrp = newZone._rateZeroContinuous.get(new LPNContAndRate(lcPair));\n if (vrp != null) {\n // This means that the continuous variable was non-zero\n // and is now zero. Fix up the values according to\n // the temp zone.\n IntervalPair newRange = tempZone.getContinuousBounds(lcPair);\n vrp.set_range(newRange);\n }\n }\n continue;\n }\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];\n // Check if a rate assignment has occured for any continuous\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord != null) {\n // Since the variable is in the oldTimers, it cannot have had\n // a new value assigned to it. It must have had a new rate assignment\n IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();\n // Copy the new rate information\n newZone.setLowerBoundByLPNTransitionPair(_indexToTimerPair[i], rates.get_LowerBound());\n newZone.setUpperBoundByLPNTransitionPair(_indexToTimerPair[i], rates.get_UpperBound());\n // Copy the smallest and greatest continuous value.\n continue;\n }\n }\n newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Handle continuous case\n if (pair instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) pair;\n // If a continuous variable is in the newTimers, then an assignment\n // to the variable must have occurred. So get the value.\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord == null) {\n throw new IllegalStateException(\"The pair \" + pair + \"was not in the new assigned values but was sorted as \" + \"a new value.\");\n }\n IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();\n IntervalPair values = updateRecord.get_Value();\n newZone.setLowerBoundByLPNTransitionPair(lcPair, rates.get_LowerBound());\n newZone.setUpperBoundByLPNTransitionPair(lcPair, rates.get_UpperBound());\n // Get the current rate.\n int currentRate = lcPair.getCurrentRate();\n if (currentRate >= 0) {\n // // Copy the smallest and greatest continuous value.\n // Copy the smallest and greatest continuous value.\n newZone.setDbmEntryByPair(lcPair, LPNTransitionPair.ZERO_TIMER_PAIR, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), currentRate, true));\n newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, lcPair, ContinuousUtilities.chkDiv(values.get_UpperBound(), currentRate, true));\n } else {\n // Copy the smallest and greatest continuous value.\n // For negative rates, the upper and lower bounds need\n // to be switched.\n newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, lcPair, ContinuousUtilities.chkDiv(values.get_LowerBound(), currentRate, true));\n newZone.setDbmEntryByPair(lcPair, LPNTransitionPair.ZERO_TIMER_PAIR, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), currentRate, true));\n }\n continue;\n }\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n if (delay == null) {\n _lpnList[pair.get_lpnIndex()].changeDelay(tranName, \"0\");\n delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n }\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n newZone.setLowerBoundByLPNTransitionPair(pair, lower);\n newZone.setUpperBoundByLPNTransitionPair(pair, upper);\n }\n // Erase relationships for continuous variables that have had new values\n // assigned to them or a new non-rate zero value.\n for (int i = 1; i < newZone._indexToTimerPair.length && newZone._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];\n // Get the update variable.\n UpdateContinuous update = newAssignValues.get(lcPair);\n if (update != null && (update.is_newValue() || update.newlyNonZero())) {\n for (int j = 1; j < newZone._indexToTimerPair.length; j++) {\n if (j == i) {\n continue;\n }\n newZone.setDbmEntry(i, j, Zone.INFINITY);\n newZone.setDbmEntry(j, i, Zone.INFINITY);\n }\n }\n }\n // Advance time.\n return newZone;\n }\n\n public void correctNewAssignemnts(ContinuousRecordSet newAssignValues) {\n // Erase relationships for continuous variables that have had new values\n // assigned to them or a new non-rate zero value.\n for (int i = 1; i < this._indexToTimerPair.length && this._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];\n // Get the update variable.\n UpdateContinuous update = newAssignValues.get(lcPair);\n if (update != null && (update.is_newValue() || update.newlyNonZero())) {\n IntervalPair values = update.get_Value();\n int currentRate = lcPair.getCurrentRate();\n // Correct the upper and lower bounds.\n if (lcPair.getCurrentRate() > 0) {\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), currentRate, true));\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(values.get_UpperBound(), currentRate, true));\n } else {\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), currentRate, true));\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(values.get_LowerBound(), currentRate, true));\n }\n // Erase the relationships.\n for (int j = 1; j < this._indexToTimerPair.length; j++) {\n if (j == i) {\n continue;\n }\n this.setDbmEntry(i, j, Zone.INFINITY);\n this.setDbmEntry(j, i, Zone.INFINITY);\n }\n }\n }\n }\n\n /**\n * This fire method fires a rate change event.\n *\n * @param ltPair\n * \t\tThe index of the continuous variable whose rate needs to be changed.\n * @param rate\n * \t\tThe new rate.\n * @return\n * \t\tThe new zone resulting from the rate change.\n */\n @Override\n public Zone fire(LPNTransitionPair ltPair, int rate) {\n // Make a copy of the Zone.\n Zone resultZone = this.clone();\n // Change the current rate of the continuous variable.\n setCurrentRate(ltPair, rate);\n // Warp the zone.\n resultZone.dbmWarp(this);\n return resultZone;\n }\n\n /**\n * Handles the moving in and out of continuous variables.\n * @param newContValues\n */\n // // Copy the zero rate variables over if they are still rate zero.\n // // Check if the pairing is in the newNonZeroContValues.\n // // Interval being null indicates that the key was not\n /**\n * Handles the moving of the continuous variables in and out of the\n * _rateZeroContinuous. This includes the adding of all rate zero (new and old)\n * cotninuous variables to the _rateZeroContinuous, and creating the\n * _indexToTimerPair and populating it.\n * @param newZone The Zone being constructed.\n * @param enabled The list of enabled transitions.\n * \t\tThe enabled transitions.\n * @param newAssignValues The list of continuous variable update information.\n */\n @SuppressWarnings(\"unused\")\n private void copyRates(Zone newZone, LpnTranList enabledTran, ContinuousRecordSet newAssignValues) {\n /*\n\t\t * The newAssignValues is an ArrayList of four sets.\n\t\t * 0. Rate zero gets zero assigned.\n\t\t * 1. Rate zero gets non-zero rate assigned.\n\t\t * 2. Non-zero gets zero rate assigned.\n\t\t * 3. Non-zero gets non-zero rate assigned.\n\t\t */\n // Create new rate zero member variable.\n newZone._rateZeroContinuous = new DualHashMap();\n // First get the total number of non-zero rate continuous variables that\n // are present in the old zone.\n int totalContinuous = 0;\n for (int i = 0; i < _lpnList.length; i++) {\n totalContinuous += _lpnList[i].getTotalNumberOfContVars();\n }\n int numberNonZero = totalContinuous - _rateZeroContinuous.size();\n // The size is given by\n // total number of transitions\n // + number of non-zero rate continuous variables previously in the zone\n // + number of zero rate continuous variables that now have non-zero\n // - number of non-zero rate continuous variables that are now zero\n // + 1 for the zero timer.\n // TODO: Create an object that stores the records along with this information.\n int newNonZero = 0, newZero = 0;\n for (UpdateContinuous record : newAssignValues.keySet()) {\n if (record.newlyNonZero()) {\n newNonZero++;\n }\n if (record.newlyZero()) {\n newZero++;\n }\n }\n int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;\n // Create the timer array.\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n // Add in the zero timer.\n newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;\n // Copy over the rate zero conintinuous variables.\n // First copy over all the continuous variables that still have\n // rate zero.\n // // Cast the index.\n // // The variable no longer is rate zero, so do nothing.\n // // If the value has had an assignment, use the new values instead.\n // // Create the new VariableRangePair to add.\n // VariableRangePair vrp =\n // Copy over the rate zero continuous variables.\n // First copy over all the continuous variables that still have\n // rate zero.\n for (LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()) {\n // Cast the index.\n LPNContinuousPair ltContPair = ltTranPair.get_lcPair();\n if (!newAssignValues.get(ltContPair).is_newZero()) {\n // The variable no longer is rate zero, so do nothing.\n continue;\n }\n // If the value has had an assignment, use the new values instead.\n if (newAssignValues.contains(ltContPair)) {\n // Create the new VariableRangePair to add.\n Variable v = _lpnList[ltContPair.get_lpnIndex()].getContVar(ltContPair.get_ContinuousIndex());\n // VariableRangePair vrp =\n VariableRangePair vrp = new VariableRangePair(v, newAssignValues.get(ltContPair).get_Value());\n newZone._rateZeroContinuous.insert(new LPNContAndRate(ltContPair, new IntervalPair(0, 0)), vrp);\n } else {\n newZone._rateZeroContinuous.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));\n }\n }\n // Next add the values that are newly set to rate zero.\n // // Exract the variable.\n // // Create a VariableRangePair.\n // // Add the value to the map.\n // // Exract the variable.\n // // Create a VariableRangePair.\n // // Add the value to the map.\n // We still need to add in the rate zero continuous variables whose rate remains zero\n // since their range might have changed. We could check if the range has changed, but\n // its just as easy (or easier) to simply add it anyway.\n // Added the indecies for the non-zero rate continuous variables to the\n // _indexToTimer array.\n // Start with the values already in the old array.\n // int index = 1; // Index for the next continuous index object.\n // // Check that the value should not be removed.\n // Change to the new references for the oldNonZero. This change to the\n // Add in the indecies for the new non-zero into the old array.\n // Copy over the new transitions.\n Arrays.sort(newZone._indexToTimerPair);\n }\n\n private void copyRatesNew(Zone newZone, LpnTranList enabledTran, ContinuousRecordSet newAssignValues) {\n // Create new rate zero member variable.\n newZone._rateZeroContinuous = new DualHashMap();\n // First get the total number of non-zero rate continuous variables that\n // are present in the old zone.\n int totalContinuous = 0;\n for (int i = 0; i < _lpnList.length; i++) {\n totalContinuous += _lpnList[i].getTotalNumberOfContVars();\n }\n int numberNonZero = totalContinuous - _rateZeroContinuous.size();\n // The size is given by\n // total number of transitions\n // + number of non-zero rate continuous variables previously in the zone\n // + number of zero rate continuous variables that now have non-zero\n // - number of non-zero rate continuous variables that are now zero\n // + 1 for the zero timer.\n // TODO: Create an object that stores the records along with this information.\n int newNonZero = 0, newZero = 0;\n for (UpdateContinuous record : newAssignValues.keySet()) {\n if (record.newlyNonZero()) {\n newNonZero++;\n }\n if (record.newlyZero()) {\n newZero++;\n }\n }\n int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;\n // Create the timer array.\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n // Add in the zero timer.\n newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;\n int indexTimerCount = 1;\n // Sort the previous rate zero continuous variables into rate zero or non-zero.\n for (LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()) {\n // Cast the index.\n LPNContinuousPair ltContPair = ltTranPair.get_lcPair();\n // Check if the variable is a newly assigned value.\n UpdateContinuous assignedLtContPair = newAssignValues.get(ltContPair);\n if (assignedLtContPair != null) {\n if (assignedLtContPair.newlyNonZero()) {\n // Variable was zero and is now non-zero, so add to the the non-zero\n newZone._indexToTimerPair[indexTimerCount++] = assignedLtContPair.get_lcrPair().get_lcPair().clone();\n } else {\n // Variable was zero and is still zero, but an assignment has been\n // made. Simply add in the new assigned value.\n VariableRangePair vrp = this._rateZeroContinuous.get(ltTranPair);\n newZone._rateZeroContinuous.insert(assignedLtContPair.get_lcrPair(), new VariableRangePair(vrp.get_variable(), assignedLtContPair.get_Value()));\n }\n } else {\n newZone._rateZeroContinuous.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));\n }\n }\n // Sort the previous non-zero variables into the rate zero and non-zero.\n for (int i = 1; this._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];\n // Check if an assignment has been made.\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord != null) {\n if (updateRecord.is_newZero()) {\n // The continuous variable is now a rate zero variable.\n LPNContinuousPair ltCar = updateRecord.get_lcrPair().get_lcPair();\n Variable v = _lpnList[ltCar.get_lpnIndex()].getContVar(ltCar.get_ContinuousIndex());\n // Dewarp the upper and lower bounds.\n IntervalPair values = updateRecord.get_Value();\n int currentRate = getCurrentRate(ltCar);\n values.set_LowerBound(values.get_LowerBound() * currentRate);\n values.set_UpperBound(values.get_UpperBound() * currentRate);\n // Create a VariableRangePair.\n VariableRangePair vrp = new VariableRangePair(v, values);\n // Add the value to the map.\n newZone._rateZeroContinuous.insert(updateRecord.get_lcrPair(), vrp);\n } else {\n // This non-zero variable still has rate non-zero, but replace\n // with the newAssignValues since the rate may have changed.\n newZone._indexToTimerPair[indexTimerCount++] = updateRecord.get_lcrPair().get_lcPair();\n }\n } else {\n // The variable was non-zero and hasn't had an assignment.\n newZone._indexToTimerPair[indexTimerCount++] = this._indexToTimerPair[i].clone();\n }\n }\n // Copy over the new transitions.\n for (Transition t : enabledTran) {\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n newZone._indexToTimerPair[indexTimerCount++] = new LPNTransitionPair(lpnIndex, tranIndex);\n }\n Arrays.sort(newZone._indexToTimerPair);\n }\n\n private void advance() {\n for (int i = 0; i < dbmSize(); i++) {\n _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(i)] = getUpperBoundbydbmIndex(i);\n }\n }\n\n /**\n * Advances time. (This method should replace advance().)\n * @param localStates\n */\n @Override\n public void advance(State[] localStates) {\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n if (ltPair.equals(LPNTransitionPair.ZERO_TIMER_PAIR)) {\n continue;\n }\n // Get the new value.\n int newValue = 0;\n if (!(ltPair instanceof LPNContinuousPair)) {\n // If the pair is a timer, then simply get the stored largest value.\n int index = timerIndexToDBMIndex(ltPair);\n newValue = getUpperBoundbydbmIndex(index);\n } else {\n // If the pair is a continuous variable, then need to find the\n // possible largest bound governed by the inequalities.\n newValue = ContinuousUtilities.maxAdvance(this, ltPair, localStates);\n }\n // In either case (timer or continuous), set the upper bound portion\n // of the DBM to the new value.\n setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, newValue);\n }\n }\n\n /**\n * Copies in the new values needed to add a set of new times.\n * @param newZone\n * \t\t\tThe zone that the values are going to be copied into.\n * @param tempZone\n * \t\t\tThe zone to look up current values of timers.\n * @param newTimers\n * \t\t\tA collection of the new timers.\n * @param oldTimers\n * \t\t\tA collection of the older timers.\n * @param localStates\n * \t\t\tThe current state.\n */\n private void copyTransitions(Zone tempZone, Collection newTimers, Collection oldTimers, State[] localStates) {\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[j]);\n _matrix[dbmIndexToMatrixIndex(newIndexi)][dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n setDbmEntry(timerIndexToDBMIndex(timerNew), timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n setDbmEntry(timerIndexToDBMIndex(timerOld), timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n setLowerBoundByLPNTransitionPair(pair, lower);\n setUpperBoundByLPNTransitionPair(pair, upper);\n }\n }\n\n /**\n * This method sets all the rate to their lower bound.\n * Will not work quite right for continuous variables\n * with rates that include zero.\n */\n private void setAllToLowerBoundRate() {\n // Loop through the continuous variables.\n for (int i = 1; i < _indexToTimerPair.length && _indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair ltContPair = (LPNContinuousPair) _indexToTimerPair[i];\n // For this, recall that for a continuous variable that the lower bound\n // rate is stored in the zero column of the matrix.\n int lower = -1 * _matrix[dbmIndexToMatrixIndex(i)][0];\n int upper = _matrix[0][dbmIndexToMatrixIndex(i)];\n int newRate;\n /**\n * Suppose the range of rates is [a,b]. If a>=0, then we set the\n * rate to b. If b<=0, then we set the rate to a. Ohterwise,\n * a<0=0 or lower < 0 < upper we set the\n // rate to the upper bound.\n newRate = upper;\n }\n setCurrentRate(ltContPair, newRate);\n }\n }\n\n /**\n * Resets the rates of all continuous variables to be their\n * lower bounds.\n */\n @Override\n public Zone resetRates() {\n // Create the new zone.\n // // Copy the rate zero variables.\n // // Copy the LPNs over.\n // // Loop through the variables and save off those\n // // that are rate zero. Accumulate an array that\n // // indicates which are zero for faster\n // // copying. Save the number of continuous variables.\n // boolean[] rateZero = new boolean[this._indexToTimerPair.length]; // Is rate zero.\n // // The rate zero is in the range, so this will be\n // LPNContinuousPair lcPair =\n // // Save as a rate zero continuous variable.\n // VariableRangePair vcp =\n // // Update continuous variable counter.\n // // Save over the indexToTimer pairs.\n // // Ignore rate zero variables.\n // // If this is a continuous variable, set the rate to the lower bound.\n // // Calculate the size of the matrix and create it.\n // // Copy over the old matrix for all variables except\n // // the rate zero variables.\n // Warp\n Zone newZone = new Zone();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n /* \n\t\t * Collect the rate zero variables whose range of rates are not\n\t\t * identically zero. These will be moved out of the zone when\n\t\t * the rate is reset.\n\t\t * \n\t\t * Copy over the rate zero variables that remain rate zero.\n\t\t */\n newZone._rateZeroContinuous = new DualHashMap();\n HashSet> newlyNonZero = new HashSet>();\n for (Map.Entry variable : _rateZeroContinuous.entrySet()) {\n // Check for a single value which indicates that zero is\n // the only possible rate.\n if (variable.getKey().get_rateInterval().singleValue()) {\n // This variable only has zero as a rate so keep it\n // in the rate zero variables.\n newZone._rateZeroContinuous.insert(variable.getKey(), variable.getValue());\n } else {\n // This variable will need to be added to the zone.\n newlyNonZero.add(variable);\n }\n }\n /*\n\t\t * Calulate the size of the _indexToTimerPairs array and create\n\t\t * it.\n\t\t */\n int oldSize = this._indexToTimerPair.length;\n int newSize = oldSize + newlyNonZero.size();\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n /*\n\t\t * Copy over the old pairs and add the new ones.\n\t\t */\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();\n }\n for (Map.Entry variable : newlyNonZero) {\n newZone._indexToTimerPair[oldSize++] = variable.getKey().get_lcPair().clone();\n }\n Arrays.sort(newZone._indexToTimerPair);\n /*\n\t\t * Copy over the old matrix values and new constraints.\n\t\t */\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n for (int i = 0; i < this.dbmSize(); i++) {\n int newi = Arrays.binarySearch(newZone._indexToTimerPair, this._indexToTimerPair[i]);\n if (newi < 0) {\n System.err.println(\"In resetRates, old value was not found\" + \" in new value.\");\n continue;\n }\n // Copy upper and lower bounds for the variable.\n newZone._matrix[dbmIndexToMatrixIndex(newi)][0] = this._matrix[dbmIndexToMatrixIndex(i)][0];\n newZone._matrix[0][dbmIndexToMatrixIndex(newi)] = this._matrix[0][dbmIndexToMatrixIndex(i)];\n // Copy the DBM Entry\n for (int j = 0; j < this.dbmSize(); j++) {\n int newj = Arrays.binarySearch(newZone._indexToTimerPair, this._indexToTimerPair[j]);\n if (newj < 0) {\n System.err.println(\"In resetRates, old value was not\" + \" found in new value.\");\n continue;\n }\n newZone.setDbmEntry(newi, newj, this.getDbmEntry(i, j));\n }\n }\n for (Map.Entry variable : newlyNonZero) {\n LPNTransitionPair currentVariable = variable.getKey().get_lcPair();\n int currentIndex = Arrays.binarySearch(newZone._indexToTimerPair, currentVariable);\n IntervalPair rangeOfRates = variable.getKey().get_rateInterval();\n IntervalPair rangeOfValues = variable.getValue().get_range();\n /*\n\t\t\t * First set the range of rates, current rate, and the lower and upper\n\t\t\t * bounds for the newly added continuous variables.\n\t\t\t */\n newZone.setLowerBoundbydbmIndex(currentIndex, rangeOfRates.get_LowerBound());\n newZone.setUpperBoundbydbmIndex(currentIndex, rangeOfRates.get_UpperBound());\n newZone.setDbmEntry(currentIndex, 0, -1 * rangeOfValues.get_LowerBound());\n newZone.setDbmEntry(0, currentIndex, rangeOfValues.get_UpperBound());\n for (int j = 1; j < newZone.dbmSize(); j++) {\n if (currentIndex == j) {\n continue;\n }\n newZone.setDbmEntry(currentIndex, j, Zone.INFINITY);\n newZone.setDbmEntry(j, currentIndex, Zone.INFINITY);\n }\n }\n /*\n\t\t * Reset all the rates.\n\t\t */\n newZone.setAllToLowerBoundRate();\n newZone.recononicalize();\n newZone.dbmWarp(this);\n newZone.recononicalize();\n return newZone;\n }\n\n /**\n * Finds the maximum amount that time cam advance.\n * @return\n * \t\tvalue.\n * \t\tThe maximum amount that time can advance before a timer expires or an inequality changes\n */\n // * Several comments in this function may look like C code. That's because,\n // * well it is C code from atacs/src/lhpnrsg.c. In particular the\n // // Get the continuous variable in question.\n // // printf(\"Zone to check...\\n\");\n // // Get all the inequalities that reference the variable of interest.\n // // Update the inequality variable.\n // // /* Working on a > or >= ineq */\n // // Working on a > or >= ineq\n // // If the rate is positive.\n // // /* Working on a < or <= ineq */\n // // Working on a < or <= ineq\n // // Check if the value can be lowered.\n // //printf(\"Min leaving checkPreds for %s: %d\\n\",events[p]->event,min);\n /* (non-Javadoc)\n\t * @see java.lang.Object#clone()\n\t */\n @Override\n public Zone clone() {\n Zone clonedZone = new Zone();\n clonedZone._matrix = new int[this.matrixSize()][this.matrixSize()];\n for (int i = 0; i < this.matrixSize(); i++) {\n for (int j = 0; j < this.matrixSize(); j++) {\n clonedZone._matrix[i][j] = this._matrix[i][j];\n }\n }\n clonedZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n clonedZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();\n }\n clonedZone._hashCode = this._hashCode;\n clonedZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n clonedZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n return clonedZone;\n }\n\n /**\n * Restricts the lower bound of a timer.\n *\n * @param timer\n * \t\t\tThe timer to tighten the lower bound.\n */\n private void restrictTimer(int timer) {\n _matrix[dbmIndexToMatrixIndex(timer)][dbmIndexToMatrixIndex(0)] = getLowerBoundbydbmIndex(timer);\n }\n\n /**\n * Restricts the lower bound of a continuous variable. Also checks fixes\n * the upper bound to be at least as large if needed. This method\n * is usually used as a result of an event firing.\n * @param ltContPair\n * \t\tThe index of the continuous variable to restrict.\n * @param constant\n * \t\tThe constant value of the inequality event that is being used to update\n * \t\tthe variable indexed by ltContPair.\n */\n private boolean restrictContinuous(LPNContinuousPair ltContPair, int constant) {\n // It will be quicker to get the DBM index for the ltContPair one time.\n int variableIndex = timerIndexToDBMIndex(ltContPair);\n int zeroIndex = timerIndexToDBMIndex(LPNTransitionPair.ZERO_TIMER_PAIR);\n // Set the lower bound the variable (which is the DBM[variabl][0] entry.\n // Note : the lower bound in the zone is actually the negative of the lower\n // bound hence the -1 on the warpValue.\n setDbmEntry(variableIndex, zeroIndex, ContinuousUtilities.chkDiv(-1 * constant, ltContPair.getCurrentRate(), true));\n // Check if the upper bound needs to be advanced and advance it if necessary.\n if (getDbmEntry(zeroIndex, variableIndex) < ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true)) {\n // If the upper bound in the zones is less than the new restricting value, we\n // must advance it for the zone to remain consistent.\n setDbmEntry(zeroIndex, variableIndex, ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true));\n return true;\n }\n return false;\n }\n\n /**\n * Restricts the continuous variables in the zone according to the inequalities in a set of events.\n * @param eventSet\n * \t\t\tA set of inequality events. Does nothing if the event set does not contian inequalities.\n */\n private void restrictContinuous(EventSet eventSet) {\n // Check that the eventSet is a set of Inequality events.\n if (!eventSet.isInequalities()) {\n // If the eventSet is not a set of inequalities, do nothing.\n return;\n }\n HashSet adjustedColumns = new HashSet();\n boolean needsAdjusting = false;\n // Restrict the variables according to each of the inequalities in the eventSet.\n for (Event e : eventSet) {\n // Get the inequality.\n InequalityVariable iv = e.getInequalityVariable();\n // Extract the variable. I will assume the inequality only depends on a single\n Variable x = iv.getContVariables().get(0);\n // Extract the index.\n int lpnIndex = iv.get_lpn().getLpnIndex();\n // Extract the variable index.\n DualHashMap variableIndexMap = _lpnList[lpnIndex].getContinuousIndexMap();\n int variableIndex = variableIndexMap.getValue(x.getName());\n // Package it up for referencing.\n LPNContinuousPair ltContPair = new LPNContinuousPair(lpnIndex, variableIndex);\n // Need the current rate for the variable, grab the stored LPNContinuousPair.\n int zoneIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);\n if (zoneIndex > 0) {\n ltContPair = (LPNContinuousPair) _indexToTimerPair[zoneIndex];\n }\n // Perform the restricting.\n needsAdjusting = needsAdjusting | restrictContinuous(ltContPair, iv.getConstant());\n if (needsAdjusting) {\n adjustedColumns.add(ltContPair);\n }\n }\n // If one of the continuous variables has been moved forward, the other colmns\n // need to be adjusted to keep a consistent zone.\n if (needsAdjusting) {\n // At least one of the continuous variables has been moved forward,\n // so se need to ajust the bounds to keep a consistent zone.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltpair = _indexToTimerPair[i];\n if (adjustedColumns.contains(ltpair)) {\n // This continuous variables already had the upper bound\n continue;\n }\n // Add one to the upper bounds.\n setDbmEntry(0, i, getDbmEntry(0, i) + 1);\n }\n }\n }\n\n /**\n * Returns a zone that is the result from restricting the this zone according to a list of firing event inequalities.\n * @param eventSet\n * \t\tThe list of inequalities that are firing.\n * @return\n * \t\tThe new zone that is the result of restricting this zone according to the firing of the inequalities\n * \t\tin the eventSet.\n */\n @Override\n public Zone getContinuousRestrictedZone(EventSet eventSet, State[] localStates) {\n // Make a new copy of the zone.\n Zone z = this.clone();\n if (eventSet == null) {\n return z;\n }\n z.restrictContinuous(eventSet);\n return z;\n }\n\n /**\n * The list of enabled timers.\n * @return\n * \t\tThe list of all timers that have reached their lower bounds.\n */\n @Override\n public List getEnabledTransitions() {\n ArrayList enabledTransitions = new ArrayList();\n // Check if the timer exceeds its lower bound staring with the first nonzero\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n enabledTransitions.add(_lpnList[_indexToTimerPair[i].get_lpnIndex()].getTransition(_indexToTimerPair[i].get_transitionIndex()));\n }\n }\n return enabledTransitions;\n }\n\n /**\n * Gives the list of enabled transitions associated with a particular LPN.\n * @param LpnIndex\n * \t\t\tThe Index of the LPN the Transitions are a part of.\n * @return\n * \t\t\tA List of the Transitions that are enabled in the LPN given by the index.\n */\n @Override\n public List getEnabledTransitions(int LpnIndex) {\n ArrayList enabledTransitions = new ArrayList();\n // Check if the timer exceeds its lower bound staring with the first nonzero\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n if (ltPair.get_lpnIndex() == LpnIndex) {\n enabledTransitions.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));\n }\n }\n }\n return enabledTransitions;\n }\n\n /**\n * Find the next possible events.\n *\n * @param LpnIndex\n * \t\tThe index of the LPN that is of interest.\n * @param localState\n * \t\tThe state associated with the LPN indexed by LpnIndex.\n * @return\n * \t\tLpnTranList is populated with a list of\n * \t\tEventSets pertaining to the LPN with index LpnIndex. An EventSet can\n * \t\teither contain a transition to\n * \t\tfire or set of inequalities to change sign.\n */\n @Override\n public LpnTranList getPossibleEvents(int LpnIndex, State localState) {\n LpnTranList result = new LpnTranList();\n // Look through the timers and continuous variables. For the timers\n // determine if they are ready to fire. For the continuous variables,\n // look up the associated inequalities and see if any of them are ready\n // to fire.\n // We do not need to consider the zero timer, so start the\n // for loop at i=1 and not i=0.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // The enabled events are grouped with the LPN that they affect. So if\n // this pair does not belong to the current LPN under consideration, skip\n // processing it.\n if (ltPair.get_lpnIndex() != LpnIndex) {\n continue;\n }\n // If the index refers to a timer (and not a continuous variable) and has exceeded its lower bound,\n // then add the transition.\n if (!(ltPair instanceof LPNContinuousPair)) {\n // The index refers to a timer. Now check if time has advanced\n // far enough for the transition to fire.\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n Event e = new Event(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));\n result = addSetItem(this, result, e, localState);\n }\n } else {\n // The index refers to a continuous variable.\n // First check for a rate change event.\n LPNContinuousPair ltContPair = ((LPNContinuousPair) ltPair).clone();\n IntervalPair ratePair = getRateBounds(ltContPair);\n // // The rate represents a range of rates and no rate change\n // // event has occured.\n // // The rate contians zero, so we need to add two rate\n // // events: one for the lower bound and one for the upper\n // // Create the events.\n // // Add them to the result set.\n result = createRateEvents(this, ltContPair, ratePair, result, localState);\n // Check all the inequalities for inclusion.\n Variable contVar = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());\n if (contVar.getInequalities() != null) {\n for (InequalityVariable iv : contVar.getInequalities()) {\n // Check if the inequality can change.\n if (ContinuousUtilities.inequalityCanChange(this, iv, localState)) {\n result = addSetItem(this, result, new Event(iv), localState);\n }\n }\n }\n }\n }\n // Check the rate zero variables for possible rate change events.\n for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()) {\n // Get the reference object:\n LPNContinuousPair ltContPair = lcrPair.get_lcPair();\n // Extract the range of rates.\n IntervalPair ratePair = lcrPair.get_rateInterval();\n result = createRateEvents(this, ltContPair, ratePair, result, localState);\n }\n return result;\n }\n\n public static LpnTranList createRateEvents(Equivalence Z, LPNContinuousPair ltContPair, IntervalPair ratePair, LpnTranList result, State localState) {\n // // The rate represents a range of rates and no rate change\n // // event has occured.\n // // The rate contians zero, so we need to add two rate\n // // events: one for the lower bound and one for the upper\n // // Create the events.\n // // Add them to the result set.\n /*\n\t\t * Let [a,b] be the current range of rates for a given variable.\n\t\t * If a>=0, then we set the rate to b originally.\n\t\t * So if the current rate is b, then we have a rate change event to a.\n\t\t * \n\t\t * If b<=0, then we set the rate to a originially.\n\t\t * So if the current rate is a, then we have a rate change event to b.\n\t\t * \n\t\t * The final case to consider is when a < 0 and b > 0. If the current\n\t\t * rate is b, we allow rate changes to either a or 0. If the current\n\t\t * rate is a, we allow a rate change to zero.\n\t\t */\n if (ratePair.singleValue()) {\n // Rates that are not a range do not generate rate change events.\n return result;\n }\n ltContPair = ltContPair.clone();\n if (ratePair.get_LowerBound() >= 0) {\n if (ltContPair.getCurrentRate() == ratePair.get_UpperBound()) {\n ltContPair.setCurrentRate(ratePair.get_LowerBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n } else if (ratePair.get_UpperBound() <= 0) {\n if (ltContPair.getCurrentRate() == ratePair.get_LowerBound()) {\n ltContPair.setCurrentRate(ratePair.get_UpperBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n } else {\n if (ltContPair.getCurrentRate() == ratePair.get_UpperBound()) {\n // No rate change events have ocurred. So we allow one for zero\n // and the lower bounds rate.\n LPNContinuousPair ltContPairOther = ltContPair.clone();\n ltContPair.setCurrentRate(0);\n ltContPairOther.setCurrentRate(ratePair.get_LowerBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n result = addSetItem(Z, result, new Event(ltContPairOther), localState);\n } else if (ltContPair.getCurrentRate() == ratePair.get_LowerBound()) {\n // The rate has change to the lower bound. Allow one rate\n // change to zero.\n ltContPair.setCurrentRate(0);\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n }\n return result;\n }\n\n /**\n * Adds or removes items as appropriate to update the current\n * list of possible events. Note the type LpnTranList extends\n * LinkedList. The type EventSet extends transition\n * specifically so that objects of EventSet type can be place in\n * this list.\n * @param EventList\n * \t\t\tThe list of possible events.\n */\n public static LpnTranList addSetItem(Equivalence Z, LpnTranList E, Event e, State s) {\n // void lhpnAddSetItem(eventSets &E,lhpnEventADT e,ineqList &ineqL,lhpnZoneADT z,\n // lhpnStateADT cur_state)\n // Note the LPNTranList plays the role of the eventSets.\n int rv1l = 0, rv1u = 0, rv2l = 0, rv2u = 0, iZ, jZ;\n // printf(\"Event sets entering:\\n\");\n // Create the new LpnTranlist for holding the events.\n EventSet eSet = new EventSet();\n LpnTranList newE = new LpnTranList();\n boolean done = false;\n boolean possible = true;\n if (e.isRate()) {\n eSet.add(e);\n // I believe that I should actually copy over the old list\n // and then add the new event set.\n newE = E.copy();\n newE.addLast(eSet);\n // The previous two commands act to pass the changes of E\n // back out of the functions. So returning the new object\n // is suficient.\n // printf(\"Event sets leaving:\\n\");\n return newE;\n }\n if (e.isInequality()) {\n // Is this necessary, or even correct to update the inequalities.\n // System.out.println(\"Note the inequality is not being updated before in addSetItem\");\n // In this case the Event e represents an inequality.\n InequalityVariable ineq = e.getInequalityVariable();\n // Need to extract the rate.\n // To do this, I'll create the indexing object.\n Variable v = ineq.getContVariables().get(0);\n // Find the LPN.\n int lpnIndex = ineq.get_lpn().getLpnIndex();\n int varIndex = Z.getVarIndex(lpnIndex, v.getName());\n // Package it all up.\n // LPNTransitionPair ltPair =\n // Note : setting the rate is not necessary since\n // this is only being used as aan index.\n // LPNContinuousPair ltPair =\n LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);\n rv2l = ContinuousUtilities.chkDiv(-1 * ineq.getConstant(), Z.getCurrentRate(ltPair), true);\n rv2u = ContinuousUtilities.chkDiv(ineq.getConstant(), Z.getCurrentRate(ltPair), true);\n iZ = Z.getIndexByTransitionPair(ltPair);\n } else {\n // In this case, the event is a transition.\n Transition t = e.getTransition();\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n // Package the results.\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);\n iZ = Z.getIndexByTransitionPair(ltPair);\n }\n // Recall that E contains the events sets which are inherited from the Transition class\n // so they can be placed in an LpnTranList. So consider each event set.\n for (Transition es : E) {\n if (!(es instanceof EventSet)) {\n // This collection should contain event sets, not transitions.\n throw new IllegalArgumentException(\"The eventSet was a Transition object not an EventSet object.\");\n }\n EventSet eventSet = (EventSet) es;\n if (done) {\n // Copy any remaining sets into newE.\n newE.add(eventSet.clone());\n break;\n }\n EventSet workSet = eventSet.clone();\n // Get an iterator for the elements in the workset.\n for (Event oldEvent : eventSet) {\n // For matching code with atacs, note that oldEvent is 'j'.\n if (oldEvent.isRate()) {\n continue;\n }\n if (oldEvent.isInequality()) {\n // Again, is it necessary to do an update here?\n // System.out.println(\"Note the inequality is not being updated before in addSetItem\");\n // In this case the Event oldEvent represents an inequality.\n InequalityVariable ineq = oldEvent.getInequalityVariable();\n // Extract variable.\n Variable v = ineq.getContVariables().get(0);\n // Find the LPN.\n int lpnIndex = ineq.get_lpn().getLpnIndex();\n int varIndex = Z.getVarIndex(lpnIndex, v.getName());\n // Package it all up.\n // LPNTransitionPair ltPair =\n // Note : setting the rate is not necessary since this is\n // only being used as an index.\n // LPNContinuousPair ltPair =\n LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);\n rv1l = ContinuousUtilities.chkDiv(-1 * oldEvent.getInequalityVariable().getConstant(), Z.getCurrentRate(ltPair), true);\n rv1u = ContinuousUtilities.chkDiv(oldEvent.getInequalityVariable().getConstant(), Z.getCurrentRate(ltPair), true);\n jZ = Z.getIndexByTransitionPair(ltPair);\n } else {\n // In this case, the event is a transition.\n Transition t = oldEvent.getTransition();\n // Create the indexing object. (See the Abstraction Function protion at the\n // top of the class for more details.)\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n // Package the results.\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);\n jZ = Z.getIndexByTransitionPair(ltPair);\n }\n // /* Both actions are predicate changes */\n // Both actions are predicate changes.\n if (e.isInequality() && oldEvent.isInequality()) {\n // /* Both predicates are on the same variable */\n // Extract the variable lists.\n ArrayList newList = e.getInequalityVariable().getContVariables();\n ArrayList oldList = oldEvent.getInequalityVariable().getContVariables();\n // Issue a warning if one of the lists has more than a single\n if (newList.size() > 1 && oldList.size() > 1) {\n System.err.println(\"Warning: One of the inequalities \" + e + \" \" + oldEvent + \" refers to more than one variable\");\n }\n // Both inequalities are on the same variables.\n if (newList.get(0).equals(oldList.get(0))) {\n if (rv1l > rv2l) {\n possible = false;\n } else // printf(\"Adding to erase list: \\n\");\n if (rv2l > rv1l) {\n workSet.remove(oldEvent);\n } else // printf(\"Adding to erase list: \\n\");\n if (rv1u > rv2u) {\n workSet.remove(oldEvent);\n } else {\n workSet.add(e);\n done = true;\n }\n } else // /* Predicates are on different variables */\n // Inequalities are on different variables.\n {\n // TODO : Check that the indecies must be reversed. I believe\n // they do since I think my representation is the transpose\n // of atacs. This will affect all the following statements.\n if (rv1l > rv2l + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else // printf(\"Adding to erase list: \");\n if (rv2l > rv1l + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n } else // printf(\"Adding to erase list: \\n\");\n if (rv1u > Z.getUpperBoundTrue(iZ) + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n } else if (rv2u > Z.getUpperBoundTrue(jZ) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else if (rv1l == rv2l + Z.getDbmEntry(jZ, iZ) && rv2l == rv1l + Z.getDbmEntry(iZ, jZ) && rv1u == rv2u + Z.getDbmEntry(iZ, jZ) && rv2u == rv1u + Z.getDbmEntry(jZ, iZ)) {\n workSet.add(e);\n }\n }\n } else // /* New action is predicate change, old is transition firing (case 3) */\n // New action is an inequality and the old even tis a transition (case 3).\n if (e.isInequality() && oldEvent.isTransition()) {\n // printf(\"Adding to erase list: \\n\");\n if (rv2l > -1 * Z.getLowerBoundbyTransition(e.getTransition()) + Z.getDbmEntry(iZ, jZ)) {\n // Probably can change this to refer directly to the zone.\n workSet.remove(oldEvent);\n } else if (rv2u > Z.getUpperBoundTrue(jZ) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n }\n } else // /* TODO: One more ugly case, is it needed? */\n // /* New action is transition firing, old is predicate change (case 4) */\n // New event is a transition firing, old event is an inequality change (case 4).\n if (e.isTransition() && oldEvent.isInequality()) {\n if (rv1l > (-1) * Z.getLowerBoundbyTransition(e.getTransition()) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else // printf(\"Adding to erase list: \\n\");\n // Real one: fix the getting of the upper and lower bounds. Done\n if (rv1u > Z.getUpperBoundTrue(iZ) + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n }\n // /* TODO: one more ugly case, is it needed? */\n // I guess this one wasn't needed since it is not found in atacs.\n }\n }\n if (!(workSet.isEmpty())) {\n newE.add(workSet);\n }\n }\n // This part of the code is essentially copying the all the old event set into the new event set.\n // There might be a way around doing this by working directly on the set to begin with.\n // Moved to being done at the begining of the previous block.\n // // This collection should contain event sets, not transitions.\n // throw new IllegalArgumentException(\"The eventSet was a Transition object not an EventSet object.\");\n if (!done && possible) {\n eSet.add(e);\n newE.add(eSet);\n }\n E = newE;\n // printf(\"Event sets leaving:\\n\");\n return E;\n }\n\n @Override\n public int getVarIndex(int lpnIndex, String name) {\n return _lpnList[lpnIndex].getContinuousIndexMap().getValue(name);\n }\n\n /**\n * Adds a set item and explicitly sets a flag to remove the next set item\n * upon firing.\n * @param E\n * The list of current event sets.\n * @param e\n * The event to add.\n * @param s\n * The current state.\n * @param removeNext\n * True if afer firing this event, the next event should be removed from the\n * queue.\n * @return\n * The new event set.\n */\n // public static LpnTranList addSetItem(LpnTranList E, Event e, State s,\n /**\n * Updates the continuous variables that are set by firing a transition.\n * @param firedTran\n * \t\tThe transition that fired.\n * @param s\n * \t\tThe current (local) state.\n */\n public void updateContinuousAssignment(Transition firedTran, State s) {\n // Get the LPN.\n LPN lpn = _lpnList[firedTran.getLpn().getLpnIndex()];\n // Get the current values of the (local) state.\n HashMap currentValues = lpn.getAllVarsWithValuesAsString(s.getVariableVector());\n // Get all the continuous variable assignments.\n HashMap assignTrees = firedTran.getContAssignTrees();\n for (String contVar : assignTrees.keySet()) {\n // Get the bounds to assign the continuous variables.\n IntervalPair assignment = assignTrees.get(contVar).evaluateExprBound(currentValues, this, null);\n // Make the assignment.\n setContinuousBounds(contVar, lpn, assignment);\n }\n }\n\n /**\n * Updates the continuous variables according to the given values.\n * @param newContValues\n * \t\tThe new values of the continuous variables.\n */\n public void updateContinuousAssignment(ContinuousRecordSet newAssignValues) {\n /*\n\t\t * In dealing with the rates and continuous variables, there are four cases to consider. These cases\n\t\t * depend on whether the the old value of the 'current rate' is zero or non-zero and whether the\n\t\t * new value of the 'current rate' is zero or non-zero. \n\t\t * 0. old rate is zero, new rate is zero.\n\t\t * \t\tLookup the zero rate in the _rateZeroContinuous and add any new continuous assignments.\n\t\t * 1. old rate is zero, new rate is non-zero.\n\t\t * \t\tRemove the rate from the _rateZeroContinuous and add the zone.\n\t\t * 2. old rate is non-zero, new rate is zero.\n\t\t * \t\tAdd the variable with its upper and lower bounds to _rateZeroContinuous.\n\t\t * 3. old rate is non-zero, new rate is non-zero.\n\t\t * \t\tGet the LPNContinuousPair from the _indexToTimerPair and change the value.\n\t\t * \n\t\t * Note: If an assignment is made to the variable, then it should be considered as a\n\t\t * new variable.\n\t\t */\n // The updating of the rate-zero continuous variables is taken care of\n // by the copyRates. So just need to update the values in the zone.\n // This amounts to copying over the values from the old zone for\n // continuous variables that haven't changed and copying in\n // // Set the lower bound.\n // // Set the upper bound.\n // // Set the rate.\n // // Set the lower bound.\n // // Set the upper bound.\n // // Set the current rate.\n // // Set the upper and lower bounds for the rates.\n }\n\n /* (non-Javadoc)\n\t * @see verification.timed_state_exploration.zone.Zone#getLexicon()\n\t */\n /**\n * Gives an array that maps the index of a timer in the DBM to the timer's index.\n * @return\n * \t\tThe array that maps the index of a timer in the DBM to the timer's index.\n */\n /**\n * Calculates a warping value needed to warp a Zone. When a zone is being warped the form\n * r1*z2 - r1*z1 + r2*z1 becomes important in finding the new values of the zone. For example,\n *\n * @param z1\n * \t\tUpper bound or negative lower bound.\n * @param z2\n * \t\tRelative value.\n * @param r1\n * \t\tFirst ratio.\n * @param r2\n * \t\tSecond ratio.\n * @return\n * \t\tr1*z2 - r1*z1 + r2*z1\n */\n public static int warp(int z1, int z2, int r1, int r2) {\n /*\n\t\t * See \"Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets\"\n\t\t * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda\n\t\t * Section III.C for details on how this function is used and where it comes\n\t\t * from.\n\t\t */\n return r1 * z2 - r1 * z1 + r2 * z1;\n }\n\n /**\n * Warps this Zone with the aid of rate information from the previous Zone.\n *\n * @param oldZone\n * \t\tThe previous Zone.\n * @return\n * \t\tThe warped Zone.\n */\n @Override\n public void dbmWarp(Equivalence oldE) {\n Zone oldZone = (Zone) oldE;\n /*\n\t\t * See \"Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets\"\n\t\t * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda\n\t\t * Section III.C for details on how this function is used and where it comes\n\t\t * from.\n\t\t */\n // /* TODO: This appears to NOT work when INFIN is in the bounds?\n // Should I have to worry about this case? */\n // According to atacs comments, this appears to NOT work when\n // INFIN is in the bounds.\n // This portion of the code handles the warping of the relative\n // parts of the zone.\n for (int i = 1; i < dbmSize(); i++) {\n for (int j = i + 1; j < dbmSize(); j++) {\n double iVal, jVal, iWarp, jWarp, iXDot, jXDot;\n // Note : the iVal and the jVal correspond to the\n // alpha and beta describe in Scott Little's thesis.\n // /* deal w/ the fact that we might have continuous and discrete\n // Do some warping when dealing with the continuous variables.\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n // Calcualte the alpha value.\n iVal = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[i]) / (double) this.getCurrentRate(_indexToTimerPair[i])));\n // The old rate the zone was warped by.\n iWarp = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[i])));\n // The current rate rate of this continuous variable.\n iXDot = Math.floor(Math.abs((double) this.getCurrentRate(_indexToTimerPair[i])));\n // I'm not going to do any warping when the previous rate\n // is zero. This statement is a break to go to next i value\n // and not the next j.\n if (iWarp == 0) {\n break;\n }\n } else {\n // The current variable is a timer, so the new rate and old rate\n // are both 1. Hence we have\n iVal = 1.0;\n iWarp = 1.0;\n iXDot = 1.0;\n }\n // Do some warping of the second variable if it is a continuous variable.\n if (_indexToTimerPair[j] instanceof LPNContinuousPair) {\n // Calcualte the alpha value.\n jVal = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[j]) / (double) this.getCurrentRate(_indexToTimerPair[j])));\n // The old rate the zone was warped by.\n jWarp = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[j])));\n // The current rate of this continuous variable.\n jXDot = Math.floor(Math.abs((double) this.getCurrentRate(_indexToTimerPair[j])));\n // I'm not going to do any warping when the previous rate is\n if (jWarp == 0) {\n continue;\n }\n } else {\n // The current variable is a timer, so the new rate and old rate\n // are both 1. Hence we have\n jVal = 1.0;\n jWarp = 1.0;\n jXDot = 1.0;\n }\n // The zone is warped differently depending on which of rate is\n // larger. See Scott Little's Thesis for more details.\n if (iWarp * jXDot > jWarp * iXDot) {\n setDbmEntry(j, i, (int) Math.ceil(((jWarp * getDbmEntry(j, i)) / jXDot) + ((-1 * jWarp * getDbmEntry(0, i) / jXDot)) + ((iWarp * getDbmEntry(0, i) / iXDot))));\n setDbmEntry(i, j, (int) Math.ceil(((jWarp * getDbmEntry(i, j)) / jXDot) + ((-1 * jWarp * getDbmEntry(i, 0) / jXDot)) + ((iWarp * getDbmEntry(i, 0) / iXDot))));\n } else {\n setDbmEntry(i, j, (int) Math.ceil(((iWarp * getDbmEntry(i, j)) / iXDot) + ((-1 * iWarp * getDbmEntry(0, j) / iXDot)) + ((jWarp * getDbmEntry(0, j) / jXDot))));\n setDbmEntry(j, i, (int) Math.ceil(((iWarp * getDbmEntry(j, i)) / iXDot) + ((-1 * iWarp * getDbmEntry(j, 0) / iXDot)) + ((jWarp * getDbmEntry(j, 0) / jXDot))));\n }\n }\n }\n // printf(\"After fixing up initial warp conditions.\\n\");\n // Handle the warping of the bounds.\n for (int i = 1; i < dbmSize(); i++) {\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n if (Math.abs(getDbmEntry(i, 0)) != INFINITY) {\n if (oldZone.getCurrentRate(_indexToTimerPair[i]) == 0) {\n // If the older rate was zero, then we just need to\n // divide by the new rate.\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(getDbmEntry(i, 0), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n } else {\n // Undo the old warping and introduce the new warping.\n // If the bound is infinite, then division does nothing.\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i])) * getDbmEntry(i, 0), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n }\n }\n if (Math.abs(getDbmEntry(0, i)) != INFINITY) {\n if (oldZone.getCurrentRate(_indexToTimerPair[i]) == 0) {\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(getDbmEntry(0, i), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n } else {\n // Undo the old warping and introduce the new warping.\n // If the bound is inifite, then division does nothing.\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i])) * getDbmEntry(0, i), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n }\n }\n }\n }\n // printf(\"After fixing up places.\\n\");\n for (int i = 1; i < dbmSize(); i++) {\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n // /* TBD: If i & j are both changing direction do we need to\n // remove the warp info? */\n // Handle the case when the warping takes us into negative space.\n if ((double) oldZone.getCurrentRate(_indexToTimerPair[i]) / (double) this.getCurrentRate(_indexToTimerPair[i]) < 0.0) {\n /* We are warping into the negative space, so swap the upper and \n\t\t\t\t\t * lower bounds.\n\t\t\t\t\t */\n int temp = getDbmEntry(i, 0);\n setDbmEntry(i, 0, getDbmEntry(0, i));\n setDbmEntry(0, i, temp);\n // Set the relationships to Infinity since nothing else is known.\n for (int j = 1; j < dbmSize(); j++) {\n if (i != j) {\n setDbmEntry(i, j, INFINITY);\n setDbmEntry(j, i, INFINITY);\n }\n }\n }\n }\n }\n // printf(\"After handling negative warps.\\n\");\n /* Do the nature of how I store things, I do not think I need to do\n\t\t\t * this portion.\n\t\t\t */\n }\n\n /**\n * The DiagonalNonZeroException extends the java.lang.RuntimerExpcetion.\n * The intention is for this exception to be thrown is a Zone has a non zero\n * entry appear on the diagonal.\n *\n * @author Andrew N. Fisher\n */\n public class DiagonalNonZeroException extends java.lang.RuntimeException {\n\n private static final long serialVersionUID = -3857736741611605411L;\n\n /**\n * Creates a DiagonalNonZeroException.\n * @param Message\n * \t\t\tThe message to be displayed when the exception is thrown.\n */\n public DiagonalNonZeroException(String Message) {\n super(Message);\n }\n }\n\n /**\n * This exception is thrown when trying to merge two zones whose corresponding timers\n * do not agree.\n * @author Andrew N. Fisher\n */\n // // TODO : Check if this class can be removed.\n // * Generated serialVersionUID\n /**\n * Clears out the lexicon.\n */\n public static IntervalPair parseRate(String rate) {\n String rateNoSpaces = rate.trim();\n // First check if the string is a single number.\n // // The string is a number, so set the upper and lower bounds equal.\n // First check for a comma (representing an interval input).\n int commaIndex = rateNoSpaces.indexOf(\",\");\n if (commaIndex < 0) {\n // Assume that the string is a constant. A NumberFormatException\n // will be thrown otherwise.\n int i = Integer.parseInt(rate);\n return new IntervalPair(i, i);\n }\n String lowerString = rateNoSpaces.substring(1, commaIndex).trim();\n String upperString = rateNoSpaces.substring(commaIndex + 1, rateNoSpaces.length() - 1).trim();\n return new IntervalPair(Integer.parseInt(lowerString), Integer.parseInt(upperString));\n }\n\n /**\n * Get the list of LhpnFile objects that this Zone depends on.\n * @return\n * \t\tThe lits of LhpnFile objects that this Zone depends on.\n */\n @Override\n public LPN[] get_lpnList() {\n return _lpnList;\n }\n\n /**\n * Performs a division of two integers and either takes the ceiling or the floor. Note :\n * The integers are converted to doubles for the division so the choice of ceiling or floor is\n * meaningful.\n * @param top\n * \t\tThe numerator.\n * @param bottom\n * \t\tThe denominator.\n * @param ceil\n * \t\tTrue indicates return the ceiling and false indicates return the floor.\n * @return\n * \t\tReturns the ceiling of top/bottom if ceil is true and the floor of top/bottom otherwise.\n */\n // * This method was taken from atacs/src/hpnrsg.c\n // System.out.println(\"Warning: Divided by zero.\");\n /**\n * Returns the current rate of the variable.\n * @param contVar\n * \t\tThe LPNTransitionPair referring to a continuous variable.\n * @return\n * \t\tThe current rate of the continuous variable refenced by the LPNTransitionPair.\n * @throws IllegalArgumentException\n * \t\tIf the LPNTransitionPair is not an instance of an LPNContinuousPair.\n */\n @Override\n public int getCurrentRate(LPNTransitionPair contVar) {\n if (!(contVar instanceof LPNContinuousPair)) {\n // The LPNTransitionsPair does not refer to a continuous variable, so yell.\n throw new IllegalArgumentException(\"Zone.getCurrentRate was called\" + \" on an LPNTransitionPair that was not an LPNContinuousPair.\");\n }\n LPNContinuousPair cV = (LPNContinuousPair) contVar;\n // Search for the pair in the zone.\n int index = Arrays.binarySearch(_indexToTimerPair, cV);\n if (index > 0) {\n // The continuous variable was found amongst the non zero rate continuous variables.\n // Grab that indexing object instead since it has the rate.\n cV = (LPNContinuousPair) _indexToTimerPair[index];\n return cV.getCurrentRate();\n }\n // Since the variable was not found in the non-zero rate continuous\n // variables, assume the rate is zero.\n return 0;\n }\n\n /**\n * Sets the current rate for a continuous variable. It sets the rate regardless of\n * whether the variable is in the rate zero portion of the Zone or not. But it\n * does not move variables in and out of the zone.\n * @param contVar\n * \t\tThe index of the variable whose rate is going to be set.\n * @param currentRate\n * \t\tThe value of the rate.\n */\n @Override\n public void setCurrentRate(LPNTransitionPair contVar, int currentRate) {\n if (!(contVar instanceof LPNContinuousPair)) {\n // The LPNTransitionsPair does not refer to a continuous variable, so yell.\n throw new IllegalArgumentException(\"Zone.getCurrentRate was called\" + \" on an LPNTransitionPair that was not an LPNContinuousPair.\");\n }\n LPNContinuousPair cV = (LPNContinuousPair) contVar;\n // Check for the current variable in the rate zero variables.\n VariableRangePair variableRange = _rateZeroContinuous.getValue(new LPNContAndRate(cV, new IntervalPair(0, 0)));\n if (variableRange != null) {\n LPNContinuousPair lcPair = _rateZeroContinuous.getKey(variableRange).get_lcPair();\n lcPair.setCurrentRate(currentRate);\n return;\n }\n // Check for the current variable in the Zone variables.\n int index = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (index >= 0) {\n // The variable was found, set the rate.\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[index];\n lcPair.setCurrentRate(currentRate);\n }\n }\n\n /**\n * Adds a transition to a zone.\n * @param newTransitions\n * \t\t\tThe newly enabled transitions.\n * @return\n * \t\t\tThe result of adding the transition.\n */\n @Override\n public Zone addTransition(HashSet newTransitions, State[] localStates) {\n /*\n\t\t * The zone will remain the same for all the continuous variables.\n\t\t * The only thing that will change is a new transition will be added into the transitions.\n\t\t */\n // Create a Zone to alter.\n Zone newZone = new Zone();\n // Create a copy of the LPN list.\n newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n // Copy the rate zero continuous variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Create a copy of the current indexing pairs.\n newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + newTransitions.size()];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = _indexToTimerPair[i];\n }\n // Add the new transitions to the _indexToTimerPair list.\n // // Set up the index for the newTransitions list.\n int i = _indexToTimerPair.length;\n for (LPNTransitionPair ltPair : newTransitions) {\n newZone._indexToTimerPair[i++] = ltPair;\n }\n // Sort the _indexToTimerPair list.\n Arrays.sort(newZone._indexToTimerPair);\n // Create matrix.\n newZone._matrix = new int[newZone._indexToTimerPair.length + 1][newZone._indexToTimerPair.length + 1];\n // Convert the current transitions to a collection of transitions.\n HashSet oldTransitionSet = new HashSet();\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n oldTransitionSet.add(ltPair);\n }\n // Copy in the new transitions.\n newZone.copyTransitions(this, newTransitions, oldTransitionSet, localStates);\n return newZone;\n }\n\n /**\n * This method creates a zone identical to the current zone except all the current rates are turned to 1.\n * This is to provide a previous zone to the initial zone for warping.\n * @return\n * \t\tA zone identical to this zone with all rates set to 1.\n */\n private Zone beforeInitialZone() {\n Zone z = this.clone();\n for (int i = 1; i < z._indexToTimerPair.length; i++) {\n if (!(z._indexToTimerPair[i] instanceof LPNContinuousPair)) {\n break;\n }\n LPNContinuousPair lcPair = (LPNContinuousPair) z._indexToTimerPair[i];\n lcPair.setCurrentRate(1);\n }\n return z;\n }\n\n /**\n * Add a rate zero variable to the DBM portion of the zone. This method\n * is intended as an aid for when a rate zero variable gets assign a\n * non-zero rate.\n * @param ltContPair The continuous variable to move from the rate zero\n * variables.\n * @return The resulting Zone.\n */\n @Override\n public Zone moveOldRateZero(LPNContinuousPair ltContPair) {\n // Create a Zone to alter.\n Zone newZone = new Zone();\n // Create a copy of the LPN list.\n newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n // Copy the rate zero continuous variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Extract the continuous variable from the rate zero variables.\n LPNContAndRate rateZero = new LPNContAndRate(ltContPair, new IntervalPair(0, 0));\n // This gets the values for the continuous variable.\n VariableRangePair vrp = newZone._rateZeroContinuous.get(rateZero);\n IntervalPair values = vrp.get_range();\n // This replaces the rateZero with the one stored in the _rateZeroContinuous.\n // The purpose of this is to obtain the stored range of rates.\n rateZero = newZone._rateZeroContinuous.getKey(vrp);\n // Get the range of rates.\n IntervalPair rangeOfRates = rateZero.get_rateInterval();\n // Remove the continuous variable.\n newZone._rateZeroContinuous.delete(rateZero);\n // Create a copy of the current indexing pairs.\n newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + 1];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = _indexToTimerPair[i];\n }\n // Add the continuous variable to the list of variables/transition in the DBM.\n int numOfTransitions = _indexToTimerPair.length;\n newZone._indexToTimerPair[numOfTransitions] = ltContPair;\n // Sort the _indexToTimerPair list.\n Arrays.sort(newZone._indexToTimerPair);\n // Create matrix.\n newZone._matrix = new int[newZone._indexToTimerPair.length + 1][newZone._indexToTimerPair.length + 1];\n // Convert the current transitions to a collection of transitions.\n HashSet oldTransitionSet = new HashSet();\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n oldTransitionSet.add(ltPair);\n }\n // Copy in the new transitions.\n newZone.copyTransitions(this, new HashSet(), oldTransitionSet, null);\n // Get the index for the variable.\n int index = Arrays.binarySearch(newZone._indexToTimerPair, ltContPair);\n // Copy in the upper and lower bound of the old rate zero variable.\n // Copy in the range of rates.\n newZone.setLowerBoundbydbmIndex(index, rangeOfRates.get_LowerBound());\n newZone.setUpperBoundbydbmIndex(index, rangeOfRates.get_UpperBound());\n if (ltContPair.getCurrentRate() > 0) {\n // Set the upper and lower bounds.\n newZone.setDbmEntry(0, index, ContinuousUtilities.chkDiv(values.get_UpperBound(), ltContPair.getCurrentRate(), true));\n newZone.setDbmEntry(index, 0, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), ltContPair.getCurrentRate(), true));\n } else {\n // Set the upper and lower bounds. Since the rate is zero\n // We swap the real upper and lower bounds.\n newZone.setDbmEntry(0, index, ContinuousUtilities.chkDiv(values.get_LowerBound(), ltContPair.getCurrentRate(), true));\n newZone.setDbmEntry(index, 0, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), ltContPair.getCurrentRate(), true));\n }\n // Set the DBM to having no relating information for how this\n // variables relates to the other variables.\n for (int i = 1; i < newZone._indexToTimerPair.length; i++) {\n if (i == index) {\n continue;\n }\n newZone.setDbmEntry(index, i, Zone.INFINITY);\n newZone.setDbmEntry(i, index, Zone.INFINITY);\n }\n newZone.recononicalize();\n return newZone;\n }\n\n /**\n * This method removes the variable from the DBM portion of the\n * zone and adds the variable to the rate-zero portion of the\n * zone. The purpose of this method is to handle when a non-zero\n * rate variable is assigned a zero rate.\n * @param firedRate The new assignment for the variable.\n * @return The resulting zone.\n */\n @Override\n public Zone saveOutZeroRate(LPNContinuousPair firedRate) {\n // Check if the variable is in the zone.\n // We assume that the rate is already zero in this case\n // since it must be in the rate zero variables if it exists.\n int index = Arrays.binarySearch(this._indexToTimerPair, firedRate);\n if (index < 0) {\n System.err.println(\"A variable is getting its rate set to zero\");\n System.err.println(\"when the rate is already zero.\");\n return this;\n }\n // Create new zone\n Zone newZone = new Zone();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n // Copy over the rate zero variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Get the range of rates and values.\n IntervalPair rangeOfRates = this.getRateBounds(firedRate);\n IntervalPair rangeOfValues = this.getContinuousBounds(firedRate);\n // Create the key and value pairs for the rate zero continuous variable.\n LPNContAndRate lcar = new LPNContAndRate(firedRate.clone(), rangeOfRates);\n VariableRangePair vrPair = new VariableRangePair(this._lpnList[firedRate.get_lpnIndex()].getContVar(firedRate.get_ContinuousIndex()), rangeOfValues);\n newZone._rateZeroContinuous.insert(lcar, vrPair);\n // Copy over the pairs, skipping the new rate zero.\n newZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length - 1];\n int offset = 0;\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n if (i == index) {\n offset++;\n }\n newZone._indexToTimerPair[i] = this._indexToTimerPair[i + offset].clone();\n }\n // Copy over the DBM\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n int offseti = 0;\n int offsetj = 0;\n for (int i = 0; i < newZone.matrixSize(); i++) {\n if (i == index + 1) {\n offseti++;\n }\n offsetj = 0;\n for (int j = 0; j < newZone.matrixSize(); j++) {\n if (j == index + 1) {\n offsetj++;\n }\n newZone._matrix[i][j] = this._matrix[i + offseti][j + offsetj];\n }\n }\n return newZone;\n }\n\n @Override\n public int getIndexByTransitionPair(LPNTransitionPair ltPair) {\n return Arrays.binarySearch(_indexToTimerPair, ltPair);\n }\n /**\n * Determines whether time has advanced far enough for an inequality to change\n * truth value.\n * @param ineq\n * \t\tThe inequality to test whether its truth value can change.\n * @param localState\n * \t\tThe state associated with the inequality.\n * @return\n * \t\tTrue if the inequality can change truth value, false otherwise.\n */\n // // Find the index of the continuous variable this inequality refers to.\n // // I'm assuming there is a single variable.\n // // Package up the information into a the index. Note the current rate doesn't matter.\n // // Get the current rate.\n // // Get the current value of the inequality. This requires looking into the current state.\n // // Get the Zone index of the variable.\n // //\t\tbool lhpnPredCanChange(ineqADT ineq,lhpnZoneADT z,lhpnRateADT r,\n // //warn(\"An inequality produced a place not in the zone.\");\n // // First check cases when the rate is negative.\n // //warn(\"An inequality produced a place not in the zone.\");\n}\n"} {"task_id": "Java_3037", "language": "Java", "task_type": "for_statement", "source_file": "java/github/MyersResearchGroup/iBioSim/verification/src/main/java/edu/utah/ece/async/lema/verification/timed_state_exploration/zoneProject/Zone.java", "mask_start_position": 65520, "mask_end_position": 65718, "canonical_solution": "for (int i = 0; i < this._indexToTimerPair.length; i++) {\n if (!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))) {\n return false;\n }\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * This file is part of iBioSim. Please visit \n * for the latest version of iBioSim.\n *\n * and also available online at .\n *\n * *****************************************************************************\n */\npackage edu.utah.ece.async.lema.verification.timed_state_exploration.zoneProject;\n\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport edu.utah.ece.async.lema.verification.lpn.ExprTree;\nimport edu.utah.ece.async.lema.verification.lpn.LPN;\nimport edu.utah.ece.async.lema.verification.lpn.Transition;\nimport edu.utah.ece.async.lema.verification.lpn.Variable;\nimport edu.utah.ece.async.lema.verification.platu.main.Options;\nimport edu.utah.ece.async.lema.verification.platu.platuLpn.DualHashMap;\nimport edu.utah.ece.async.lema.verification.platu.platuLpn.LpnTranList;\nimport edu.utah.ece.async.lema.verification.platu.stategraph.State;\nimport edu.utah.ece.async.lema.verification.timed_state_exploration.octagon.Equivalence;\n\n/**\n * This class is for storing and manipulating the delay information for transitions as well as\n * the values of continuous variables including rate their rates.\n * A Zone represents the non-zero continuous variables and the timers for the delay in a\n * Difference Bound Matrix (DBM)\n *\n * t0 c0 c1 t0 t1\n * t0 m00 m01 m02 m03 m04\n * c0 m10 m11 m12 m13 m14\n * c1 m20 m21 m22 m23 m24\n * t0 m30 m31 m32 m33 m34\n * t1 m40 m41 m42 m43 m44\n *\n * For the timers, tj - ti <= m(ti,tj) where m(ti,tj) represents the element of the matrix with\n * row ti and column tj. In particular, m(t0,ti) is an upper bound for ti and -m(ti,0) is a\n * lower bound for ti. The continuous variables are normalized to have rate one before being\n * placed in the matrix. Thus for a continuous variables ci with rate ri, the entry m(t0, ci) is\n * (upper bound)/ri where 'upper bound' is the upper bound for the continuous variable and\n * m(ci,t0) is -1*(lower bound)/ri where 'lower bound' is the lower bound of the continuous variable.\n * When the rate is negative, dividing out by the rate switches the inequalities. For example,\n * if ci is a continuous variable such that l < ci < u for some values l and u, then the normalized\n * ci (that is ci/ri) is satisfies u/ri < ci/r < l/ri. Hence the m(t0,ci) is (lower bound)/ri and\n * m(ci,0) is -1*(upper bound)/ri. The m(ci,cj) as well as m(ti,ci) and m(ci,ti) give the same kind\n * of relational information as with just timers, but with the normalized values of the continuous\n * variables. Note that a Zone with normalized continuous variables is referred to as being a 'warped'\n * zone.\n *\n * The rate zero continuous variables are also stored in a Zone object, but they are not present in\n * the zone. The Zone merely records the range of the continuous variable.\n *\n * The timers are referenced by the name of the transition that they are associated with and continuous\n * variables are referenced by their name as well. In addition for non-zero rate continuous variables and\n * the timers, several method will allow them to be referred by their index as a part of the (DMB). For\n * example, c0 in the above DBM example, has index 1.\n *\n * A third way that the timers and variables (both rate zero and rate non-zero) can be referred to by\n * an LPNTransitionPair object. These objects refer to a timer or continuous variable by providing the index\n * of the corresponding transition or the index of the continuous variable as a member of an LPN and the\n * index of that LPN. The LPNTransitionPair can be made more specific in the case of the continuous variables\n * by using an LPNContinuousPair. These objects also provide the rate of the variable. LPNTransitionPairs\n * can be used with continuous variables when they are only being used as an index only. If the rate is needed\n * for the method, then LPNContinuousPairs must be used.\n *\n * @author Andrew N. Fisher\n * @author Chris Myers\n * @author iBioSim Contributors \n * @version %I%\n */\npublic class Zone implements Equivalence {\n\n /*Abstraction Function : \n\t* The difference bound matrix is stored in the _matrix member field, along with \n\t* the upper and lower bounds of the timers and rates for continuous variables.\n\t* The upper and lower bounds are stored when the timer becomes enabled. The upper and\n\t* lower bounds of the rates are stored when the rate is assigned. The upper and lower \n\t* bounds are stored in the first row and first column of the _matrix member field.\n\t* The DBM occupies the rest of the array, that is, the sub-array formed by removing\n\t* the first column and first row.\n\t* For example, let t1 be a timer for a transition whose delay is between 2 and 3. Further\n\t* let c1 be a continuous variable with rate between 4 and 5. Then _matrix would look like\n\t* lb t0 c1 t1\n\t* ub x 0 5 3\n\t* t0 0 m m m\n\t* c1 -4 m m m\n\t* t1 -2 m m m\n\t* \n\t* with out the lb, ub, t0, t1, and c1.\n\t* \n\t* The x is does not represent anything and will most likely be zero. The upper and lower \n\t* bounds for the zero timer (which is always present) are always 0. The m's comprise \n\t* the DBM.\n\t* \n\t* For the most part, a timer or a continuous variable is referred to internally by an\n\t* LPNTransitionPair. An LPNTransitionPair combines the index of the transition (or\n\t* continuous variable) with the index of the LPN that the transition (or continuous \n\t* variables) is a member of. Both continuous variables and transitions can be referred\n\t* to by an LPNTransitionPair; however, it is better to use an LPNContinuousPair (which\n\t* is inherited from the LPNTransitionPair) to refer to continuous variables.\n\t* LPNContinuousPairs are used to distinguish continuous variables from transitions. They \n\t* also store the current rate of the continuous variable. \n\t* \n\t* The LPNTransitionPairs are stored in the _indexToTimerPair member field. The row/column\n\t* in the DBM for a transition is determined by the its position in this array. For example,\n\t* suppose a transition t has an LPNTransitionPair ltTranPair that is the third element of\n\t* the _indexToTimerPair. Then t will be the third column/row of the DBM.\n\t* \n\t* Continuous variables are handled slightly differently. The LPNContinuousPair for the \n\t* continuous variables with a non-zero rate are stored in the _indexToTimerPair just as \n\t* with the transitions. And just like with the transitions, the index in the DBM is\n\t* determined by the index of the LPNContinuousPair in the _indexToTimerPair. However,\n\t* rate zero continuous variables are stored in the _rateZeroContinuous member variable.\n\t* The _rateZerContinuous pairs an LPNContinuousPair with a VariableRangePair. The\n\t* VariableRangePair combines the variable with its upper and lower bound.\n\t* \n\t*/\n /* Representation invariant :\n\t* Zones are immutable.\n\t* Integer.MAX_VALUE is used to logically represent infinity.\n\t* The lb and ub values for a timer should be set when the timer is enabled.\n\t* A negative hash code indicates that the hash code has not been set.\n\t* The index of the timer in _indexToTimer is the index in the DBM and should contain\n\t* \tthe zeroth timer.\n\t* The array _indexToTimerPair should always be sorted.\n\t* The index of the LPN should match where it is in the _lpnList, that is, if lpn is\n\t* \tand LhpnFile object in _lpnList, then _lpnList[getLpnIndex()] == lpn.\n\t* The LPNTransitionPair in the _indexToTimer array should be an LPNContinuousPair\n\t* when it stores the index to a continuous variable. Testing that the index\n\t* is an LPNContinuousPair is used to determined if the indexing object points\n\t* to a continuous variable. Also the LPNContinuousPair keeps track of the current rate.\n\t* \n\t*/\n /*\n\t * Resource List :\n\t * TODO : Create a list reference where the algorithms can be found that this class\n\t * depends on.\n\t */\n public static final int INFINITY = Integer.MAX_VALUE;\n\n /* The lower and upper bounds of the times as well as the dbm. */\n private int[][] _matrix;\n\n /* Maps the index to the timer. The index is row/column of the DBM sub-matrix.\n\t * Logically the zero timer is given index -1.\n\t * */\n private LPNTransitionPair[] _indexToTimerPair;\n\n /* The hash code. */\n private int _hashCode;\n\n /* A lexicon between a transitions index and its name. */\n /* Set if a failure in the testSplit method has fired already. */\n /* Hack to pass a parameter to the equals method though a variable */\n /* Stores the continuous variables that have rate zero */\n DualHashMap _rateZeroContinuous;\n\n /* Records the largest zone that occurs. */\n public static int ZoneSize = 0;\n\n /* Write a log file */\n private static BufferedWriter _writeLogFile = null;\n\n /**\n * Returns the write log.\n * @return\n * \t\tThe _writeLogfile.\n */\n public static BufferedWriter get_writeLogFile() {\n return _writeLogFile;\n }\n\n /**\n * Sets the BufferedWriter.\n * @param writeLogFile\n */\n public static void set_writeLogFile(BufferedWriter writeLogFile) {\n _writeLogFile = writeLogFile;\n }\n\n /**\n * Sets the writeLogFile to null.\n */\n public static void reset_writeLogFile() {\n _writeLogFile = null;\n }\n\n private void checkZoneMaxSize() {\n if (dbmSize() > ZoneSize) {\n ZoneSize = dbmSize();\n }\n }\n\n private LPN[] _lpnList;\n\n /* \n\t * Turns on and off subsets for the zones.\n\t * True means subset will be considered.\n\t * False means subsets will not be considered.\n\t */\n private static boolean _subsetFlag = true;\n\n /* \n\t * Turns on and off supersets for zones.\n\t * True means that supersets will be considered.\n\t * False means that supersets will not be considered.\n\t */\n private static boolean _supersetFlag = true;\n\n /**\n * Gets the value of the subset flag.\n * @return\n * \t\tTrue if subsets are requested, false otherwise.\n */\n public static boolean getSubsetFlag() {\n return _subsetFlag;\n }\n\n /**\n * Sets the value of the subset flag.\n * @param useSubsets\n * \t\t\tThe value for the subset flag. Set to true if\n * \t\t\tsupersets are to be considered, false otherwise.\n */\n public static void setSubsetFlag(boolean useSubsets) {\n _subsetFlag = useSubsets;\n }\n\n /**\n * Gets the value of the superset flag.\n * @return\n * \t\tTrue if supersets are to be considered, false otherwise.\n */\n public static boolean getSupersetFlag() {\n return _supersetFlag;\n }\n\n /**\n * Sets the superset flag.\n * @param useSupersets\n * \t\tThe value of the superset flag. Set to true if\n * \t\tsupersets are to be considered, false otherwise.\n */\n public static void setSupersetFlag(boolean useSupersets) {\n _supersetFlag = useSupersets;\n }\n\n /**\n * Construct a zone that has the given timers.\n * @param timers\n * \t\t\t\tThe ith index of the array is the index of the timer. For example,\n * \t\t\t\t\tif timers = [1, 3, 5], then the zeroth row/column of the DBM is the\n * \t\t\t\t\ttimer of the transition with index 1, the first row/column of the\n * \t\t\t\t\tDBM is the timer of the transition with index 3, and the 2nd\n * \t\t\t\t\trow/column is the timer of the transition with index 5. Do not\n * \t\t\t\t\tinclude the zero timer.\n * @param matrix\n * \t\t\t\tThe DBM augmented with the lower and upper bounds of the delays for the\n * \t\t\t\t\ttransitions. For example, suppose a zone has timers [1, 3, 5] (as\n * \t\t\t\t\tdescribed in the timers parameters). The delay for transition 1 is\n * \t\t\t\t\t[1, 3], the delay for transition 3 is [2,5], and the delay for\n * \t\t\t\t\ttransition 5 is [4,6]. Also suppose the DBM is\n * \t\t\t\t\t t0 t1 t3 t5\n * \t\t\t\t\tt0 | 0, 3, 3, 3 |\n * \t\t\t\t\tt1 | 0, 0, 0, 0 |\n * \t\t\t\t\tt3 | 0, 0, 0, 0 |\n * \t\t\t\t\tt5 | 0, 0, 0, 0 |\n * \t\t\t\t\tThen the matrix that should be passed is\n * \t\t\t\t\t lb t0 t1 t3 t5\n * \t\t\t\t\tub| 0, 0, 3, 5, 6|\n * \t\t\t\t\tt0| 0, 0, 3, 3, 3|\n * \t\t\t\t\tt1|-1, 0, 0, 0, 0|\n * \t\t\t\t\tt3|-2, 0, 0, 0, 0|\n * \t\t\t\t\tt5|-4, 0, 0, 0, 0|\n * \t\t\t\t\tThe matrix should be non-null and the zero timer should always be the\n * \t\t\t\t\tfirst timer, even when there are no other timers.\n */\n public Zone(int[] timers, int[][] matrix) {\n // A negative number indicates that the hash code has not been set.\n _hashCode = -1;\n // Make a copy to reorder the timers.\n // Make a copy to reorder the timers.\n _indexToTimerPair = new LPNTransitionPair[timers.length];\n for (int i = 0; i < timers.length; i++) {\n _indexToTimerPair[i] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);\n }\n // Sorting the array.\n // Sorting the array.\n Arrays.sort(_indexToTimerPair);\n // // Add the zeroth timer.\n if (_indexToTimerPair[0].get_transitionIndex() != -1) {\n // Add the zeroth timer.\n LPNTransitionPair[] newIndexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newIndexToTimerPair[i + 1] = _indexToTimerPair[i];\n }\n _indexToTimerPair = newIndexToTimerPair;\n _indexToTimerPair[0] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, -1);\n }\n // throw new IllegalArgumentException(\"Timers must be non negative.\");\n // // Add a zero timer.\n // Map the old index of the timer to the new index of the timer.\n HashMap newIndex = new HashMap();\n // For the old index, find the new index.\n for (int i = 0; i < timers.length; i++) {\n // Since the zeroth timer is not included in the timers passed\n // to the index in the DBM is 1 more than the index of the timer\n // in the timers array.\n // LPNTransitionPair searchValue =\n LPNTransitionPair searchValue = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);\n newIndex.put(i + 1, Arrays.binarySearch(_indexToTimerPair, searchValue));\n }\n // Add the zero timer index.\n newIndex.put(0, 0);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Copy the DBM\n for (int i = 0; i < dbmSize(); i++) {\n for (int j = 0; j < dbmSize(); j++) {\n // Copy the passed in matrix to _matrix.\n setDbmEntry(newIndex.get(i), newIndex.get(j), matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]);\n // In the above, changed setDBMIndex to setdbm\n }\n }\n // Copy in the upper and lower bounds. The zero time does not have an upper or lower bound\n // so the index starts at i=1, the first non-zero timer.\n for (int i = 1; i < dbmSize(); i++) {\n setUpperBoundbydbmIndex(newIndex.get(i), matrix[0][dbmIndexToMatrixIndex(i)]);\n // Note : The method setLowerBoundbydbmIndex, takes the value of the lower bound\n // and the matrix stores the negative of the lower bound. So the matrix value\n // must be multiplied by -1.\n setLowerBoundbydbmIndex(newIndex.get(i), -1 * matrix[dbmIndexToMatrixIndex(i)][0]);\n }\n recononicalize();\n }\n\n /**\n * Initializes a zone according to the markings of state.\n * @param currentState\n * \t\t\tThe zone is initialized as if all enabled timers\n * \t\t\thave just been enabled.\n */\n public Zone(State initialState) {\n // Extract the associated LPN.\n LPN lpn = initialState.getLpn();\n int LPNIndex = lpn.getLpnIndex();\n if (_lpnList == null) {\n // If no LPN exists yet, create it and put lpn in it.\n _lpnList = new LPN[LPNIndex + 1];\n _lpnList[LPNIndex] = lpn;\n } else if (_lpnList.length <= LPNIndex) {\n // The list does not contain the lpn.\n LPN[] tmpList = _lpnList;\n _lpnList = new LPN[LPNIndex + 1];\n _lpnList[LPNIndex] = lpn;\n // Copy any that exist already.\n for (int i = 0; i < _lpnList.length; i++) {\n _lpnList[i] = tmpList[i];\n }\n } else if (_lpnList[LPNIndex] != lpn) {\n // This checks that the appropriate lpn is in the right spot.\n // If not (which gets you in this block), then this fixes it.\n _lpnList[LPNIndex] = lpn;\n }\n // Default value for the hash code indicating that the hash code has not\n // been set yet.\n _hashCode = -1;\n // Get the list of currently enabled Transitions by their index.\n boolean[] enabledTran = initialState.getTranVector();\n ArrayList enabledTransitionsArrayList = new ArrayList();\n LPNTransitionPair zeroPair = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, LPNTransitionPair.ZERO_TIMER);\n // Add the zero timer first.\n enabledTransitionsArrayList.add(zeroPair);\n // The index of the boolean value corresponds to the index of the Transition.\n for (int i = 0; i < enabledTran.length; i++) {\n if (enabledTran[i]) {\n enabledTransitionsArrayList.add(new LPNTransitionPair(LPNIndex, i));\n }\n }\n _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);\n _matrix = new int[matrixSize()][matrixSize()];\n for (int i = 1; i < dbmSize(); i++) {\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = lpn.getTransition(_indexToTimerPair[i].get_transitionIndex()).getLabel();\n ExprTree delay = lpn.getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = lpn.getAllVarsWithValuesAsString(initialState.getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n ExprTree lowerDelay = delay.getLeftChild();\n ExprTree upperDelay = delay.getRightChild();\n lower = (int) lowerDelay.evaluateExpr(varValues);\n upper = (int) upperDelay.evaluateExpr(varValues);\n } else {\n lower = (int) delay.evaluateExpr(varValues);\n upper = lower;\n }\n setLowerBoundbydbmIndex(i, lower);\n setUpperBoundbydbmIndex(i, upper);\n }\n // Advance the time and tighten the bounds.\n advance();\n recononicalize();\n checkZoneMaxSize();\n }\n\n /**\n * Creates a Zone based on the local states.\n * @param localStates\n * \t\t\tThe current state (or initial) of the LPNs.\n */\n public Zone(State[] localStates) {\n // Open the log file.\n if (_writeLogFile == null && Options.get_TimingLogfile() != null) {\n try {\n _writeLogFile = new BufferedWriter(new FileWriter(Options.get_TimingLogfile()));\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n }\n }\n // Initialize hash code to -1 (indicating nothing cached).\n _hashCode = -1;\n // Initialize the LPN list.\n initialize_lpnList(localStates);\n // Get the enabled transitions. This initializes the _indexTotimerPair\n // which stores the relevant information.\n // This method will also initialize the _rateZeroContinuous\n initialize_indexToTimerPair(localStates);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Set the lower bound/ upper bounds of the timers and the rates.\n initializeLowerUpperBounds(getAllNames(), localStates);\n // Initialize the row and column entries for the continuous variables.\n initializeRowColumnContVar();\n // Create a previous zone to the initial zone for the sake of warping.\n Zone tmpZone = beforeInitialZone();\n dbmWarp(tmpZone);\n recononicalize();\n // Advance Time\n advance(localStates);\n // Re-canonicalize\n recononicalize();\n // Check the size of the DBM.\n checkZoneMaxSize();\n }\n\n /**\n * Creates a Zone based on the local states.\n * @param localStates\n * \t\t\tThe current state (or initial) of the LPNs.\n */\n public Zone(State[] localStates, boolean init) {\n // Extract the local states.\n // Initialize hash code to -1 (indicating nothing cached).\n _hashCode = -1;\n // Initialize the LPN list.\n initialize_lpnList(localStates);\n // Get the enabled transitions. This initializes the _indexTotimerPair\n // which stores the relevant information.\n // This method will also initialize the _rateZeroContinuous\n initialize_indexToTimerPair(localStates);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Set the lower bound/ upper bounds of the timers and the rates.\n initializeLowerUpperBounds(getAllNames(), localStates);\n // Initialize the row and column entries for the continuous variables.\n initializeRowColumnContVar();\n if (init) {\n return;\n }\n // Advance Time\n advance(localStates);\n // Re-canonicalize\n recononicalize();\n // Check the size of the DBM.\n checkZoneMaxSize();\n }\n\n // * Sets ups a zone containing continuous variables only.\n // * @param continuousValues\n // * \t\tThe values to populate the zone with.\n // // Copy the LPNContinuousPairs over\n // int count = 0; // The position in the _indexToTimerPair for the next value.\n /**\n * Gives the names of all the transitions and continuous variables that\n * are represented by the zone.\n * @return\n * \t\tThe names of the transitions and continuous variables that are\n * \t\trepresented by the zone.\n */\n public String[] getAllNames() {\n // transitionNames[0] = \"The zero timer.\";\n // Get the continuous variable names.\n String[] contVar = getContVarNames();\n // Get the transition names.\n String[] trans = getTranNames();\n // Create an array large enough for all the names.\n String[] names = new String[contVar.length + trans.length + 1];\n // Add the zero timer.\n names[0] = \"The zero timer.\";\n // Add the continuous variables.\n for (int i = 0; i < contVar.length; i++) {\n names[i + 1] = contVar[i];\n }\n // Add the timers.\n for (int i = 0; i < trans.length; i++) {\n // Already the zero timer has been added and the elements of contVar.\n // That's a total of 'contVar.length + 1' elements. The last index was\n // thus 'contVar.length' So the first index to add to is\n names[1 + contVar.length + i] = trans[i];\n }\n return names;\n }\n\n /**\n * Get the names of the continuous variables that this zone uses.\n * @return\n * \t\tThe names of the continuous variables that are part of this zone.\n */\n public String[] getContVarNames() {\n // List for accumulating the names.\n ArrayList contNames = new ArrayList();\n // Find the pairs that represent the continuous variables. Loop starts at\n // i=1 since the i=0 is the zero timer.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // If the isTimer value is false, then this pair represents a continuous\n // If pair is LPNContinuousPair.\n if (ltPair instanceof LPNContinuousPair) {\n // Get the LPN that this pairing references and find the name of\n // the continuous variable whose index is given by this pairing.\n contNames.add(_lpnList[ltPair.get_lpnIndex()].getContVarName(ltPair.get_transitionIndex()));\n }\n }\n return contNames.toArray(new String[0]);\n }\n\n /**\n * Gets the names of the transitions that are associated with the timers in the\n * zone. Does not return the zero timer.\n * @return\n * \t\tThe names of the transitions whose timers are in the zone except the zero\n * \t\ttimer.\n */\n public String[] getTranNames() {\n // List for accumulating the names.\n ArrayList transitionNames = new ArrayList();\n // Find the pairs that represent the transition timers.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // If the isTimer value is true, then this pair represents a timer.\n // If this is an LPNTransitionPair and not an LPNContinuousPair\n if (!(ltPair instanceof LPNContinuousPair)) {\n // Get the LPN that this pairing references and find the name of the\n // transition whose index is given by this pairing.\n transitionNames.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()).getLabel());\n }\n }\n return transitionNames.toArray(new String[0]);\n }\n\n /**\n * Initializes the _lpnList using information from the local states.\n * @param localStates\n * \t\tThe local states.\n * @return\n * \t\tThe enabled transitions.\n */\n private void initialize_lpnList(State[] localStates) {\n // Create the LPN list.\n _lpnList = new LPN[localStates.length];\n // Get the LPNs.\n for (int i = 0; i < localStates.length; i++) {\n _lpnList[i] = localStates[i].getLpn();\n }\n }\n\n /**\n * Initializes the _indexToTimerPair from the local states. This includes\n * adding the zero timer, the continuous variables and the set of\n * enabled timers.\n * @param localStates\n * \t\tThe local states.\n * @return\n * \t\tThe names of the transitions stored in the _indexToTimerPair (in the same order).\n */\n private void initialize_indexToTimerPair(State[] localStates) {\n /*\n\t\t * The populating of the _indexToTimerPair is done in three stages.\n\t\t * The first is to add the zero timer which is at the beginning of the zone.\n\t\t * The second is to add the continuous variables. And the third is to add\n\t\t * the other timers. Since the continuous variables are added before the\n\t\t * timers and the variables and timers are added in the order of the LPNs,\n\t\t * the elements in an accumulating list (enabledTransitionsArrayList) are\n\t\t * already in order up to the elements added for a particular LPN. Thus the\n\t\t * only sorting that needs to take place is the sorting for a particular LPN.\n\t\t * Correspondingly, elements are first found for an LPN and sort, then added\n\t\t * to the main list.\n\t\t */\n // This method will also initialize the _rateZeroContinuous\n _rateZeroContinuous = new DualHashMap();\n // This list accumulates the transition pairs (ie timers) and the continuous\n ArrayList enabledTransitionsArrayList = new ArrayList();\n // Put in the zero timer.\n // enabledTransitionsArrayList\n enabledTransitionsArrayList.add(new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, LPNTransitionPair.ZERO_TIMER));\n // Get the continuous variables.\n for (int i = 0; i < localStates.length; i++) {\n // Accumulates the changing continuous variables for a single LPN.\n ArrayList singleLPN = new ArrayList();\n // Get the associated LPN.\n LPN lpn = localStates[i].getLpn();\n // Get the continuous variables for this LPN.\n String[] continuousVariables = lpn.getContVars();\n // Get the variable, index map.\n DualHashMap variableIndex = lpn.getContinuousIndexMap();\n // Find which have a nonzero rate.\n for (int j = 0; j < continuousVariables.length; j++) {\n // Get the Variables with this name.\n Variable contVar = lpn.getVariable(continuousVariables[j]);\n // Get the rate.\n IntervalPair rate = parseRate(contVar.getInitRate());\n // Get the LPN index for the variable\n int lpnIndex = lpn.getLpnIndex();\n // Get the index as a variable for the LPN.\n int contVariableIndex = variableIndex.get(continuousVariables[j]);\n LPNContinuousPair newPair = new LPNContinuousPair(lpnIndex, contVariableIndex, rate.getSmallestRate());\n // If the rate is non-zero, then the variables needs to be tracked\n // by matrix part of the Zone.\n if (newPair.getCurrentRate() != 0) {\n // Temporary exception guaranteeing only unit rates.\n // \"only supports positive unit rates. The variable \" + contVar +\n // \" has a rate of \" + rate);\n // // Get the LPN index for the variable\n // // Get the index as a variable for the LPN. This index matches\n // // the index in the vector stored by platu.State.\n // The continuous variable reference.\n singleLPN.add(newPair);\n } else {\n // If the rate is zero, then the Zone keeps track of this variable\n // in a list.\n _rateZeroContinuous.insert(new LPNContAndRate(newPair, rate), new VariableRangePair(contVar, parseRate(contVar.getInitValue())));\n }\n }\n // Sort the list.\n Collections.sort(singleLPN);\n // Add the list to the total accumulating list.\n for (int j = 0; j < singleLPN.size(); j++) {\n enabledTransitionsArrayList.add(singleLPN.get(j));\n }\n }\n // Get the transitions.\n for (int i = 0; i < localStates.length; i++) {\n // Extract the enabled transition vector.\n boolean[] enabledTran = localStates[i].getTranVector();\n // Accumulates the transition pairs for one LPN.\n ArrayList singleLPN = new ArrayList();\n // The index of the boolean value corresponds to the index of the Transition.\n for (int j = 0; j < enabledTran.length; j++) {\n if (enabledTran[j]) {\n // Add the transition pair.\n singleLPN.add(new LPNTransitionPair(i, j));\n }\n }\n // Sort the transitions for the current LPN.\n Collections.sort(singleLPN);\n // Add the collection to the enabledTransitionsArrayList\n for (int j = 0; j < singleLPN.size(); j++) {\n enabledTransitionsArrayList.add(singleLPN.get(j));\n }\n }\n // Extract out the array portion of the enabledTransitionsArrayList.\n _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);\n }\n\n /**\n * Sets the lower and upper bounds for the transitions and continuous variables.\n * @param varNames\n * \t\t\tThe names of the transitions in _indexToTimerPair.\n */\n private void initializeLowerUpperBounds(String[] varNames, State[] localStates) {\n // Traverse the entire length of the DBM sub-matrix except the zero row/column.\n // This is the same length as the _indexToTimerPair.length-1. The DBM is used to\n // match the idea of setting the value for each row.\n for (int i = 1; i < dbmSize(); i++) {\n // Get the current LPN and transition pairing.\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n IntervalPair range;\n if (ltPair instanceof LPNContinuousPair) {\n // If the pairing represents a continuous variable, then the\n // upper and lower bound are the initial value or infinity depending\n // on whether the initial rate is positive or negative.\n // If the value is a constant, then assign the upper and lower bounds\n // to be constant. If the value is a range then assign the upper and\n // lower bounds to be a range.\n Variable v = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());\n String rate = v.getInitRate();\n // Parse the rate. Should be in the form of [x,y] where x\n // and y are integers.\n range = parseRate(rate);\n // Set the upper and lower bound (in the matrix) for the\n // continuous variables.\n String contValue = v.getInitValue();\n IntervalPair bound = parseRate(contValue);\n // Set upper bound (DBM entry (0, x) where x is the index of the variable v).\n setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, bound.get_UpperBound());\n // Set lower bound (DBM entry (x, 0) where x is the index of the variable v).\n setDbmEntryByPair(ltPair, LPNTransitionPair.ZERO_TIMER_PAIR, -1 * bound.get_LowerBound());\n } else {\n // Get the expression tree.\n ExprTree delay = _lpnList[ltPair.get_lpnIndex()].getDelayTree(varNames[i]);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[ltPair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[ltPair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n // Passing the zone as null since it should not be needed.\n // // The lower and upper bounds should evaluate to a single\n // throw new IllegalStateException(\"When evaulating the delay, \" +\n // \"the lower or the upper bound evaluated to a range \" +\n // \"instead of a single value.\");\n if (delay != null) {\n range = delay.evaluateExprBound(varValues, this, null);\n } else {\n range = new IntervalPair(0, 0);\n }\n }\n setLowerBoundbydbmIndex(i, range.get_LowerBound());\n setUpperBoundbydbmIndex(i, range.get_UpperBound());\n }\n }\n\n /**\n * Initialize the rows and columns for the continuous variables.\n */\n private void initializeRowColumnContVar() {\n /*\n\t\t * TODO : Describe the idea behind the following algorithm.\n\t\t */\n // // Note: row is indexing the row of the DBM matrix.\n // // If we reached the timers, stop.\n // // Note: col is indexing the column of the DBM matrix.\n // // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since\n // // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower\n // // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);\n // The only entries that do not need to be checked are the ones where both variables\n // represent timers.\n for (int row = 2; row < _indexToTimerPair.length; row++) {\n // Note: row is indexing the row of the DBM matrix.\n LPNTransitionPair ltRowPair = _indexToTimerPair[row];\n // // If we reached the timers, stop.\n for (int col = 1; col < row; col++) {\n // Note: col is indexing the column of the DBM matrix.\n LPNTransitionPair ltColPair = _indexToTimerPair[col];\n // If we've reached the part of the zone involving only timers, then break out\n if (!(ltRowPair instanceof LPNContinuousPair) && !(ltColPair instanceof LPNContinuousPair)) {\n break;\n }\n // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since\n // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower\n // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);\n int rowCol = getDbmEntry(row, 0) + getDbmEntry(0, col);\n int colRow = getDbmEntry(col, 0) + getDbmEntry(0, row);\n setDbmEntry(row, col, rowCol);\n setDbmEntry(col, row, colRow);\n }\n }\n }\n\n /**\n * Zero argument constructor for use in methods that create Zones where the members\n * variables will be set by the method.\n */\n private Zone() {\n _matrix = new int[0][0];\n _indexToTimerPair = new LPNTransitionPair[0];\n _hashCode = -1;\n _lpnList = new LPN[0];\n _rateZeroContinuous = new DualHashMap();\n }\n\n /**\n * Gets the upper bound of a Transition from the zone.\n * @param t\n * \t\tThe transition whose upper bound is wanted.\n * @return\n * \t\tThe upper bound of Transition t.\n */\n public int getUpperBoundbyTransition(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n // LPNTransitionPair ltPair =\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return getUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Returns the upper bound of the continuous variable.\n * @param var\n * \t\tThe variable of interest.\n * @return\n * \t\tThe (0,var) entry of the zone, that is the maximum as recored by\n * \t\tthe zone.\n */\n public int getUpperBoundbyContinuousVariable(String contVar, LPN lpn) {\n // // Determine whether the variable is in the zone or rate zero.\n // // If a RangeAndPairing is returned, then get the information from here.\n // // If indexAndRange is null, then try to get the value from the zone.\n // throw new IllegalStateException(\"Atempted to find the upper bound for \"\n // + \"a non-rate zero continuous variable that was not found in the \"\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note : setting the rate is not necessary here since this is only\n // being used as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range().get_UpperBound();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the lower bound for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n return getDbmEntry(0, i);\n }\n\n public int getUpperBoundForRate(LPNTransitionPair contVar) {\n // Check if the contVar is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (i > 0) {\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n // Grab the current rate from the LPNContinuousPair.\n return ((LPNContinuousPair) _indexToTimerPair[i]).getCurrentRate();\n }\n // Assume the rate is zero. This covers the case if conVar\n // is in the rate zero as well as if its not in the state at all.\n return 0;\n }\n\n /**\n * Get the value of the upper bound for the delay. If the index refers\n * to a timer, otherwise get the upper bound for the continuous\n * variables rate.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @return\n * \t\t\tThe upper bound on the transitions delay.\n */\n public int getUpperBoundbydbmIndex(int index) {\n return _matrix[0][dbmIndexToMatrixIndex(index)];\n }\n\n public int getUpperBound(int index) {\n return _matrix[0][dbmIndexToMatrixIndex(index)];\n }\n\n @Override\n public int getUpperBoundTrue(int index) {\n return _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(index)];\n }\n\n public int getUnwarpedUpperBound(LPNContinuousPair lcpair) {\n // Get the index.\n int index = Arrays.binarySearch(_indexToTimerPair, lcpair);\n int rate = ((LPNContinuousPair) _indexToTimerPair[index]).getCurrentRate();\n int warpValue = getUpperBoundTrue(index);\n return warpValue * rate;\n }\n\n public int getLowerBound(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][0];\n }\n\n @Override\n public int getLowerBoundTrue(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][dbmIndexToMatrixIndex(0)];\n }\n\n /**\n * Set the value of the upper bound for the delay.\n * @param t\n * \t\t\tThe transition whose upper bound is being set.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n public void setUpperBoundbyTransition(Transition t, int value) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the upper bound for the delay.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n public void setUpperBoundbydbmIndex(int index, int value) {\n _matrix[0][dbmIndexToMatrixIndex(index)] = value;\n }\n\n /**\n * Sets the upper bound for a transition described by an LPNTransitionPair.\n * @param ltPair\n * \t\t\tThe index of the transition and the index of the associated LPN for\n * \t\t\tthe timer to set the upper bound.\n * @param value\n * \t\t\tThe value for setting the upper bound.\n */\n private void setUpperBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value) {\n setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Gets the lower bound of a Transition from the zone.\n * @param t\n * \t\tThe transition whose upper bound is wanted.\n * @return\n * \t\tThe lower bound of Transition t.\n */\n @Override\n public int getLowerBoundbyTransition(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return getLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Returns the lower bound of the continuous variable.\n * @param var\n * \t\tThe variable of interest.\n * @return\n * \t\tThe (0,var) entry of the zone, that is the minimum as recored by\n * \t\tthe zone.\n */\n public int getLowerBoundbyContinuousVariable(String contVar, LPN lpn) {\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note: Setting the rate is not necessary since this is only being used\n // as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range().get_LowerBound();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the lower bound for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n return getDbmEntry(i, 0);\n }\n\n /**\n * Get the value of the lower bound for the delay if the index refers\n * to a timer, otherwise get the lower bound for the continuous variables\n * rate.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @return\n * \t\t\tThe value of the lower bound.\n */\n public int getLowerBoundbydbmIndex(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][0];\n }\n\n public int getLowerBoundForRate(LPNTransitionPair contVar) {\n // Check if the contVar is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (i > 0) {\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n return getLowerBoundbydbmIndex(contVar.get_transitionIndex());\n }\n // Assume the rate is zero. This covers the case if conVar\n // is in the rate zero as well as if its not in the state at all.\n return 0;\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param t\n * \t\t\tThe transition whose lower bound is being set.\n * @param value\n * \t\t\tThe value of the lower bound.\n */\n public void setLowerBoundbyTransition(Transition t, int value) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param t\n * \t\t\tThe transition whose upper bound is being set.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n private void setLowerBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value) {\n setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @param value\n * \t\t\tThe value of the lower bound.\n */\n public void setLowerBoundbydbmIndex(int index, int value) {\n _matrix[dbmIndexToMatrixIndex(index)][0] = -1 * value;\n }\n\n /**\n * Give the upper and lower bounds for a continuous variable.\n * @param contVar\n * \t\tThe variable of interest.\n * @return\n * \t\tThe upper and lower bounds according to the Zone.\n */\n @Override\n public IntervalPair getContinuousBounds(String contVar, LPN lpn) {\n /*\n\t\t * Need to determine whether this is suppose to be a rate zero variable or a non-zero \n\t\t * rate variable. One method is to check the rate of the passed variable. The other is\n\t\t * to just check if the variable is present in either place.\n\t\t */\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n // Get the index of the continuous variable.\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note: setting the current rate is not necessary here since the\n // LPNContinuousPair is only being used as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(new LPNContAndRate(index, new IntervalPair(0, 0)));\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the bounds for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n // Else find the upper and lower bounds.\n int lower = (-1) * getDbmEntry(i, 0);\n int upper = getDbmEntry(0, i);\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the range for the continuous variable. Values come back not\n * warped.\n * @param ltContPair\n * \t\tThe index of the variable of interest.\n * @return\n * \t\tThe range of the continuous variable described by ltContPair.\n */\n @Override\n public IntervalPair getContinuousBounds(LPNContinuousPair ltContPair) {\n // First check in the zone.\n int variableIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);\n if (variableIndex < 0) {\n // The variable was not found in the zone. Check to see if its\n // in the rate-zero variables. Technically I will return whatever\n // is in the _rateZeroConintuous, null or not.\n // First get an object to reference into the _rateZeroContinuous\n LPNContAndRate lcr = new LPNContAndRate(ltContPair, new IntervalPair(0, 0));\n return _rateZeroContinuous.get(lcr).get_range();\n }\n // The variable was found in the zone. Yay.\n int lower = (-1) * getDbmEntry(variableIndex, 0) * getCurrentRate(ltContPair);\n int upper = getDbmEntry(0, variableIndex) * getCurrentRate(ltContPair);\n // If the current rate is negative the upper and lower bounds\n // need to be switched.\n if (getCurrentRate(ltContPair) < 0) {\n int tmp = lower;\n lower = upper;\n upper = tmp;\n }\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the range of the rate associated with a continuous variable.\n * @param ltContPair\n * \t\tThe index of the continuous variable.\n * @return\n * \t\tThe range of rates associated with the continuous variable indexed\n * \t\tby ltContPair.\n */\n @Override\n public IntervalPair getRateBounds(LPNTransitionPair ltPair) {\n int upper;\n int lower;\n // Check if the ltContpair is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, ltPair);\n if (i < 0) {\n // Then the variable is in the rate zero continuous\n // variables so get the range of rates from there.\n // Create an object to reference into the rate zero.\n LPNContAndRate lcr = new LPNContAndRate((LPNContinuousPair) ltPair, new IntervalPair(0, 0));\n // Get the old version of lcr from the rate zero since\n // that contains the rate. This is quite a hack.\n VariableRangePair vrp = _rateZeroContinuous.get(lcr);\n lcr = _rateZeroContinuous.getKey(vrp);\n return lcr.get_rateInterval();\n }\n upper = getUpperBoundbydbmIndex(i);\n lower = -1 * getLowerBoundbydbmIndex(i);\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the rate reset value.\n * @param ltPair\n * @return\n */\n @Override\n public int rateResetValue(LPNTransitionPair ltPair) {\n IntervalPair rateBounds = getRateBounds(ltPair);\n int upper = rateBounds.get_UpperBound();\n int lower = rateBounds.get_LowerBound();\n // // Check if the ltContpair is in the zone.\n // // Assume the rate is zero. This covers the case if conVar\n // // is in the rate zero as well as if its not in the state at all.\n // If zero is a possible rate, then it is the rate to set to.\n // // If zero is the only possible rate, return that.\n // // When zero is in the range and there is a positive rate, return the\n // // When the upper bound is zero, return the negative rate.\n // // When zero is not present, use the smallest rate in absolute value.\n /*\n\t\t * Suppose the range of rates is [a,b]. If a>=0, we set the rate to b.\n\t\t * If b<=0, we set the rate to a. Otherwise, a<0=0, we set the rate to b.\n\t\t * If b<=0, we set the rate to a. Otherwise, a<0 variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note : Setting the rate is not necessary since this only being used\n // as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and make the new assignment.\n if (pairing != null) {\n pairing.set_range(range);\n return;\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the bounds for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n // Else find the upper and lower bounds.\n setDbmEntry(i, 0, (-1) * range.get_LowerBound());\n setDbmEntry(0, i, range.get_UpperBound());\n }\n\n /**\n * Converts the index of the DBM to the index of _matrix.\n * @param i\n * \t\t\tThe row/column index of the DBM.\n * @return\n * \t\t\tThe row/column index of _matrix.\n */\n private static int dbmIndexToMatrixIndex(int i) {\n return i + 1;\n }\n\n /**\n * Retrieves an entry of the DBM using the DBM's addressing.\n * @param i\n * \t\t\tThe row of the DBM.\n * @param j\n * \t\t\tThe column of the DBM.\n * @return\n * \t\t\tThe value of the (i, j) element of the DBM.\n */\n @Override\n public int getDbmEntry(int i, int j) {\n return _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)];\n }\n\n /**\n * Retrieves an entry of the DBM using LPNTransitionPair indecies.\n * @param iPair\n * \t\tThe LPNTransitionPair for the ith entry.\n * @param jPair\n * \t\tThe LPNTransitionPair for the jth entry.\n * @return\n * \t\tThe value of the (i,j) element of the DBM where i corresponds to the row\n * \t\tfor the variable iPair and j corresponds to the row for the variable jPair.\n */\n @Override\n public int getDbmEntryByPair(LPNTransitionPair iPair, LPNTransitionPair jPair) {\n int iIndex = Arrays.binarySearch(_indexToTimerPair, iPair);\n int jIndex = Arrays.binarySearch(_indexToTimerPair, jPair);\n return getDbmEntry(iIndex, jIndex);\n }\n\n /**\n * Sets an entry of the DBM using the DBM's addressing.\n * @param i\n * \t\t\tThe row of the DBM.\n * @param j\n * \t\t\tThe column of the DBM.\n * @param value\n * \t\t\tThe new value for the entry.\n */\n private void setDbmEntry(int i, int j, int value) {\n _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)] = value;\n }\n\n /**\n * Sets the entry in the DBM using the LPNTransitionPair indexing.\n * @param row\n * \t\t\tThe LPNTransitionPair for the row.\n * @param col\n * \t\t\tThe LPNTransitionPair for the column.\n * @param value\n * \t\t\tThe value to set the entry to.\n */\n private void setDbmEntryByPair(LPNTransitionPair row, LPNTransitionPair col, int value) {\n // The row index.\n int i = timerIndexToDBMIndex(row);\n // The column index.\n int j = timerIndexToDBMIndex(col);\n setDbmEntry(i, j, value);\n }\n\n /**\n * Returns the index of the the transition in the DBM given a LPNTransitionPair pairing\n * the transition index and associated LPN index.\n * @param ltPair\n * \t\tThe pairing comprising the index of the transition and the index of the associated\n * \t\tLPN.\n * @return\n * \t\tThe row/column of the DBM associated with the ltPair.\n */\n @Override\n public int timerIndexToDBMIndex(LPNTransitionPair ltPair) {\n return Arrays.binarySearch(_indexToTimerPair, ltPair);\n }\n\n /**\n * The matrix labeled with 'ti' where i is the transition index associated with the timer.\n */\n @Override\n public String toString() {\n // TODO : Fix the handling of continuous variables in the\n String result = \"Timer and delay or continuous and ranges.\\n\";\n int count = 0;\n // Print the timers.\n for (int i = 1; i < _indexToTimerPair.length; i++, count++) {\n if (_lpnList.length == 0) {\n // If no LPN's are associated with this Zone, use the index of the timer.\n result += \" t\" + _indexToTimerPair[i].get_transitionIndex() + \" : \";\n } else {\n String name;\n // If the current LPNTransitionPair is a timer, get the name\n // from the transitions.\n // If the current timer is an LPNTransitionPair and not an LPNContinuousPair\n if (!(_indexToTimerPair[i] instanceof LPNContinuousPair)) {\n // Get the name of the transition.\n Transition tran = _lpnList[_indexToTimerPair[i].get_lpnIndex()].getTransition(_indexToTimerPair[i].get_transitionIndex());\n name = tran.getLabel();\n } else {\n // If the current LPNTransitionPair is not a timer, get the\n // name as a continuous variable.\n Variable var = _lpnList[_indexToTimerPair[i].get_lpnIndex()].getContVar(_indexToTimerPair[i].get_transitionIndex());\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];\n int lowerBound = -1 * getDbmEntry(i, 0) * lcPair.getCurrentRate();\n int upperBound = getDbmEntry(0, i) * lcPair.getCurrentRate();\n // If the rate is negative, the bounds are switched\n // in the zone.\n if (lcPair.getCurrentRate() < 0) {\n int tmp = lowerBound;\n lowerBound = upperBound;\n upperBound = tmp;\n }\n name = var.getName() + \":[\" + lowerBound + \",\" + upperBound + \"]\\n\" + \" Current Rate: \" + lcPair.getCurrentRate() + \" \" + \"rate:\";\n }\n result += \" \" + name + \":\";\n }\n result += \"[ \" + -1 * getLowerBoundbydbmIndex(i) + \", \" + getUpperBoundbydbmIndex(i) + \" ]\";\n if (count > 9) {\n result += \"\\n\";\n count = 0;\n }\n }\n if (!_rateZeroContinuous.isEmpty()) {\n result += \"\\nRate Zero Continuous : \\n\";\n for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()) {\n result += \"\" + _rateZeroContinuous.get(lcrPair) + \"Rate: \" + lcrPair.get_rateInterval();\n }\n }\n result += \"\\nDBM\\n\";\n // Print the DBM.\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n result += \"| \" + String.format(\"%3d\", getDbmEntry(i, 0));\n for (int j = 1; j < _indexToTimerPair.length; j++) {\n result += \", \" + String.format(\"%3d\", getDbmEntry(i, j));\n }\n result += \" |\\n\";\n }\n return result;\n }\n\n /**\n * Tests for equality. Overrides inherited equals method.\n * @return True if o is equal to this object, false otherwise.\n */\n @Override\n public boolean equals(Object o) {\n // Check if the reference is null.\n if (o == null) {\n return false;\n }\n // Check that the type is correct.\n if (!(o instanceof Zone)) {\n return false;\n }\n // Check for equality using the Zone equality.\n return equals((Zone) o);\n }\n\n /**\n * Tests for equality.\n * @param\n * \t\tThe Zone to compare.\n * @return\n * \t\tTrue if the zones are non-null and equal, false otherwise.\n */\n public boolean equals(Zone otherZone) {\n // Check if the reference is null first.\n if (otherZone == null) {\n return false;\n }\n // Check for reference equality.\n if (this == otherZone) {\n return true;\n }\n // If the hash codes are different, then the objects are not equal.\n if (this.hashCode() != otherZone.hashCode()) {\n return false;\n }\n // Check if the they have the same number of timers.\n if (this._indexToTimerPair.length != otherZone._indexToTimerPair.length) {\n return false;\n }\n // Check if the timers are the same.\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n if (!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))) {\n return false;\n }\n }\n // Check if the matrix is the same\n for (int i = 0; i < _matrix.length; i++) {\n for (int j = 0; j < _matrix[0].length; j++) {\n if (!(this._matrix[i][j] == otherZone._matrix[i][j])) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Determines if this zone is a subset of Zone otherZone.\n * @param otherZone\n * \t\tThe zone to compare against.\n * @return\n * \t\tTrue if this is a subset of other; false otherwise.\n */\n @Override\n public boolean subset(Equivalence otherEquiv) {\n Zone otherZone = (Zone) otherEquiv;\n // Check if the reference is null first.\n if (otherZone == null) {\n return false;\n }\n // Check for reference equality.\n if (this == otherZone) {\n return true;\n }\n // Check if the the same number of timers are present.\n if (this._indexToTimerPair.length != otherZone._indexToTimerPair.length) {\n return false;\n }\n // Check if the transitions are the same.\n ", "post_mask_code": "\n // Check if the entries of this Zone are less than or equal to the entries\n // of the other Zone.\n for (int i = 0; i < _matrix.length; i++) {\n for (int j = 0; j < _matrix[0].length; j++) {\n if (!(this._matrix[i][j] <= otherZone._matrix[i][j])) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Determines if this zone is a superset of Zone otherZone.\n * @param otherZone\n * \t\tThe zone to compare against.\n * @return\n * \t\tTrue if this is a subset of other; false otherwise. More specifically it\n * \t\tgives the result of otherZone.subset(this). Thus it agrees with the subset method.\n */\n @Override\n public boolean superset(Equivalence otherZone) {\n return otherZone.subset(this);\n }\n\n /**\n * Overrides the hashCode.\n */\n @Override\n public int hashCode() {\n // Check if the hash code has been set.\n if (_hashCode < 0) {\n _hashCode = createHashCode();\n }\n return _hashCode;\n }\n\n /**\n * Creates a hash code for a Zone object.\n * @return\n * \t\tThe hash code.\n */\n private int createHashCode() {\n int newHashCode = Arrays.hashCode(_indexToTimerPair);\n for (int i = 0; i < _matrix.length; i++) {\n newHashCode ^= Arrays.hashCode(_matrix[i]);\n }\n return Math.abs(newHashCode);\n }\n\n /**\n * The size of the DBM sub matrix. This is calculated using the size of _indexToTimer.\n * @return\n * \t\t\tThe size of the DBM.\n */\n private int dbmSize() {\n return _indexToTimerPair.length;\n }\n\n /**\n * The size of the matrix.\n * @return\n * \t\t\tThe size of the matrix. This is calculated using the size of _indexToTimer.\n */\n private int matrixSize() {\n return _indexToTimerPair.length + 1;\n }\n\n /**\n * Performs the Floyd's least pairs algorithm to reduce the DBM.\n */\n @Override\n public void recononicalize() {\n for (int k = 0; k < dbmSize(); k++) {\n for (int i = 0; i < dbmSize(); i++) {\n for (int j = 0; j < dbmSize(); j++) {\n if (getDbmEntry(i, k) != INFINITY && getDbmEntry(k, j) != INFINITY && getDbmEntry(i, j) > getDbmEntry(i, k) + getDbmEntry(k, j)) {\n setDbmEntry(i, j, getDbmEntry(i, k) + getDbmEntry(k, j));\n }\n if ((i == j) && getDbmEntry(i, j) != 0) {\n throw new DiagonalNonZeroException(\"Entry (\" + i + \", \" + j + \")\" + \" became \" + getDbmEntry(i, j) + \".\");\n }\n }\n }\n }\n }\n\n /**\n * Determines if a timer associated with a given transitions has reached its lower bound.\n * @param t\n * \t\t\tThe transition to consider.\n * @return\n * \t\t\tTrue if the timer has reached its lower bound, false otherwise.\n */\n public boolean exceedsLowerBoundbyTransitionIndex(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return exceedsLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Determines if a timer has reached its lower bound.\n * @param timer\n * \t\t\tThe timer's index.\n * @return\n * \t\t\tTrue if the timer has reached its lower bound, false otherwise.\n */\n public boolean exceedsLowerBoundbydbmIndex(int index) {\n // Note : Make sure that the lower bound is stored as a negative number\n // and that the inequality is correct.\n return _matrix[0][dbmIndexToMatrixIndex(index)] <= _matrix[1][dbmIndexToMatrixIndex(index)];\n }\n\n /* (non-Javadoc)\n\t * @see verification.timed_state_exploration.zone.Zone#fireTransitionbyTransitionIndex(int, int[], verification.platu.stategraph.State)\n\t */\n // State state)\n // // Check if the value is in this zone to fire.\n /**\n * Gives the Zone obtained by firing a given Transitions.\n * @param t\n * \t\tThe transitions being fired.\n * @param enabledTran\n * \t\tThe list of currently enabled Transitions.\n * @param localStates\n * \t\tThe current local states.\n * @return\n * \t\tThe Zone obtained by firing Transition t with enabled Transitions enabled\n * \t\tenabledTran when the current state is localStates.\n */\n // public Zone fire(Transition t, LpnTranList enabledTran,\n @Override\n public Zone fire(Transition t, LpnTranList enabledTran, ContinuousRecordSet newAssignValues, State[] localStates) {\n try {\n if (_writeLogFile != null) {\n _writeLogFile.write(t.toString());\n _writeLogFile.newLine();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n // Create the LPNTransitionPair to check if the Transitions is in the zone and to\n // find the index.\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n int dbmIndex = Arrays.binarySearch(_indexToTimerPair, ltPair);\n if (dbmIndex <= 0) {\n return this;\n }\n // Get the new zone portion.\n Zone newZone = fireTransitionbydbmIndexNew(dbmIndex, enabledTran, localStates, newAssignValues);\n // Update any assigned continuous variables.\n // Set all the rates to their lower bound.\n newZone.setAllToLowerBoundRate();\n // Warp the Zone\n newZone.dbmWarp(this);\n // Warping can wreck the newly assigned values so correct them.\n newZone.correctNewAssignemnts(newAssignValues);\n newZone.recononicalize();\n newZone.advance(localStates);\n // Recanonicalize\n newZone.recononicalize();\n newZone.checkZoneMaxSize();\n return newZone;\n }\n\n /**\n * Updates the Zone according to the transition firing.\n * @param index\n * \t\t\tThe index of the timer.\n * @param newContValue\n * @return\n * \t\t\tThe updated Zone.\n */\n public Zone fireTransitionbydbmIndex(int index, LpnTranList enabledTimers, State[] localStates, ArrayList> newAssignValues) {\n /*\n\t\t * For the purpose of adding the newly enabled transitions and removing\n\t\t * the disable transitions, the continuous variables that still have\n\t\t * a nonzero rate can be treated like still enbaled timers.\n\t\t */\n // Initialize the zone.\n Zone newZone = new Zone();\n // These sets will defferentiate between the new timers and the\n // old timers, that is between the timers that are not already in the\n // zone and those that are already in the zone..\n HashSet newTimers = new HashSet();\n HashSet oldTimers = new HashSet();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n HashMap oldNonZero = newAssignValues.get(3);\n // Add the continuous variables to the enabled timers.\n for (int i = 1; _indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n // For the purpose of addigng continuous variables to the zone\n // consider an oldNonZero continuous variable as new.\n if (oldNonZero.containsKey(_indexToTimerPair[i])) {\n continue;\n }\n oldTimers.add(_indexToTimerPair[i]);\n }\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n // Determine if each value is a new timer or old.\n if (Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0) {\n // The timer was already present in the zone.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else {\n // The timer is a new timer.\n newTimers.add(newZone._indexToTimerPair[i]);\n }\n }\n // Create the new matrix.\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n // TODO: For simplicity, make a copy of the current zone and perform the\n // restriction and re-canonicalization. Later add a copy re-canonicalization\n // that does the steps together.\n Zone tempZone = this.clone();\n tempZone.restrictTimer(index);\n tempZone.recononicalize();\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);\n newZone._matrix[Zone.dbmIndexToMatrixIndex(newIndexi)][Zone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n // The block copies the upper and lower bound information from the\n // old zone. Thus we do not consider anything that is not an old\n // timer. Furthermore, oldNonZero represent\n if (!oldTimers.contains(tempZone._indexToTimerPair[i]) && !oldNonZero.containsKey(_indexToTimerPair[i])) {\n continue;\n }\n newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n newZone.setLowerBoundByLPNTransitionPair(pair, lower);\n newZone.setUpperBoundByLPNTransitionPair(pair, upper);\n }\n // Advance time.\n return newZone;\n }\n\n public Zone fireTransitionbydbmIndexNew(int index, LpnTranList enabledTimers, State[] localStates, ContinuousRecordSet newAssignValues) {\n /*\n\t\t * For the purpose of adding the newly enabled transitions and removing\n\t\t * the disable transitions, the continuous variables that still have\n\t\t * a nonzero rate can be treated like still enbaled timers.\n\t\t */\n // Initialize the zone.\n Zone newZone = new Zone();\n // These sets will defferentiate between the new timers and the\n // old timers, that is between the timers that are not already in the\n // zone and those that are already in the zone..\n HashSet newTimers = new HashSet();\n HashSet oldTimers = new HashSet();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n copyRatesNew(newZone, enabledTimers, newAssignValues);\n // Add the continuous variables to the enabled timers.\n // // For the purpose of addigng continuous variables to the zone\n // // consider an oldNonZero continuous variable as new.\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n // Handle the continuous variables portion.\n if (newZone._indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];\n // Get the record\n UpdateContinuous continuousState = newAssignValues.get(lcPair);\n if (continuousState != null && (continuousState.is_newValue() || continuousState.newlyNonZero())) {\n // In the first case a new value has been assigned, so\n // consider the continuous variable a 'new' variable for\n // the purposes of copying relations from the previous zone.\n newTimers.add(newZone._indexToTimerPair[i]);\n continue;\n }\n // At this point, either the continuous variable was not present\n // in the newAssignValues or it is in the newAssignValues and\n // satisfies the following: it already had a non-zero rate, is\n // being assigned another non-zero rate, and is not being assigned\n // a new value. This is becuase the field _indexToTimerPair only\n // deals with non-zero rates, so the variable must have a non-zero\n // rate. Furthermore the if statement takes care of the cases\n // when the rate changed from zero to non-zero and/or a new value\n // has been assigned.\n // In either of the cases, we consider the variable an 'old' variable\n // for the purpose of copying the previous zone information.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else // At this point, the variable represents a transition (timer).\n // So determine whether this timer is new or old.\n if (Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0) {\n // The timer was already present in the zone.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else {\n // The timer is a new timer.\n newTimers.add(newZone._indexToTimerPair[i]);\n }\n }\n // Create the new matrix.\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n // TODO: For simplicity, make a copy of the current zone and perform the\n // restriction and re-canonicalization. Later add a copy re-canonicalization\n // that does the steps together.\n Zone tempZone = this.clone();\n tempZone.restrictTimer(index);\n tempZone.recononicalize();\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);\n newZone._matrix[Zone.dbmIndexToMatrixIndex(newIndexi)][Zone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n // The block copies the upper and lower bound information from the\n // old zone. Thus we do not consider anything that is not an old\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n // A hack to ensure that the newly zero variables\n // get the new values from the tempZone.\n if (tempZone._indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) tempZone._indexToTimerPair[i];\n VariableRangePair vrp = newZone._rateZeroContinuous.get(new LPNContAndRate(lcPair));\n if (vrp != null) {\n // This means that the continuous variable was non-zero\n // and is now zero. Fix up the values according to\n // the temp zone.\n IntervalPair newRange = tempZone.getContinuousBounds(lcPair);\n vrp.set_range(newRange);\n }\n }\n continue;\n }\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];\n // Check if a rate assignment has occured for any continuous\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord != null) {\n // Since the variable is in the oldTimers, it cannot have had\n // a new value assigned to it. It must have had a new rate assignment\n IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();\n // Copy the new rate information\n newZone.setLowerBoundByLPNTransitionPair(_indexToTimerPair[i], rates.get_LowerBound());\n newZone.setUpperBoundByLPNTransitionPair(_indexToTimerPair[i], rates.get_UpperBound());\n // Copy the smallest and greatest continuous value.\n continue;\n }\n }\n newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Handle continuous case\n if (pair instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) pair;\n // If a continuous variable is in the newTimers, then an assignment\n // to the variable must have occurred. So get the value.\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord == null) {\n throw new IllegalStateException(\"The pair \" + pair + \"was not in the new assigned values but was sorted as \" + \"a new value.\");\n }\n IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();\n IntervalPair values = updateRecord.get_Value();\n newZone.setLowerBoundByLPNTransitionPair(lcPair, rates.get_LowerBound());\n newZone.setUpperBoundByLPNTransitionPair(lcPair, rates.get_UpperBound());\n // Get the current rate.\n int currentRate = lcPair.getCurrentRate();\n if (currentRate >= 0) {\n // // Copy the smallest and greatest continuous value.\n // Copy the smallest and greatest continuous value.\n newZone.setDbmEntryByPair(lcPair, LPNTransitionPair.ZERO_TIMER_PAIR, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), currentRate, true));\n newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, lcPair, ContinuousUtilities.chkDiv(values.get_UpperBound(), currentRate, true));\n } else {\n // Copy the smallest and greatest continuous value.\n // For negative rates, the upper and lower bounds need\n // to be switched.\n newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, lcPair, ContinuousUtilities.chkDiv(values.get_LowerBound(), currentRate, true));\n newZone.setDbmEntryByPair(lcPair, LPNTransitionPair.ZERO_TIMER_PAIR, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), currentRate, true));\n }\n continue;\n }\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n if (delay == null) {\n _lpnList[pair.get_lpnIndex()].changeDelay(tranName, \"0\");\n delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n }\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n newZone.setLowerBoundByLPNTransitionPair(pair, lower);\n newZone.setUpperBoundByLPNTransitionPair(pair, upper);\n }\n // Erase relationships for continuous variables that have had new values\n // assigned to them or a new non-rate zero value.\n for (int i = 1; i < newZone._indexToTimerPair.length && newZone._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];\n // Get the update variable.\n UpdateContinuous update = newAssignValues.get(lcPair);\n if (update != null && (update.is_newValue() || update.newlyNonZero())) {\n for (int j = 1; j < newZone._indexToTimerPair.length; j++) {\n if (j == i) {\n continue;\n }\n newZone.setDbmEntry(i, j, Zone.INFINITY);\n newZone.setDbmEntry(j, i, Zone.INFINITY);\n }\n }\n }\n // Advance time.\n return newZone;\n }\n\n public void correctNewAssignemnts(ContinuousRecordSet newAssignValues) {\n // Erase relationships for continuous variables that have had new values\n // assigned to them or a new non-rate zero value.\n for (int i = 1; i < this._indexToTimerPair.length && this._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];\n // Get the update variable.\n UpdateContinuous update = newAssignValues.get(lcPair);\n if (update != null && (update.is_newValue() || update.newlyNonZero())) {\n IntervalPair values = update.get_Value();\n int currentRate = lcPair.getCurrentRate();\n // Correct the upper and lower bounds.\n if (lcPair.getCurrentRate() > 0) {\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), currentRate, true));\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(values.get_UpperBound(), currentRate, true));\n } else {\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), currentRate, true));\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(values.get_LowerBound(), currentRate, true));\n }\n // Erase the relationships.\n for (int j = 1; j < this._indexToTimerPair.length; j++) {\n if (j == i) {\n continue;\n }\n this.setDbmEntry(i, j, Zone.INFINITY);\n this.setDbmEntry(j, i, Zone.INFINITY);\n }\n }\n }\n }\n\n /**\n * This fire method fires a rate change event.\n *\n * @param ltPair\n * \t\tThe index of the continuous variable whose rate needs to be changed.\n * @param rate\n * \t\tThe new rate.\n * @return\n * \t\tThe new zone resulting from the rate change.\n */\n @Override\n public Zone fire(LPNTransitionPair ltPair, int rate) {\n // Make a copy of the Zone.\n Zone resultZone = this.clone();\n // Change the current rate of the continuous variable.\n setCurrentRate(ltPair, rate);\n // Warp the zone.\n resultZone.dbmWarp(this);\n return resultZone;\n }\n\n /**\n * Handles the moving in and out of continuous variables.\n * @param newContValues\n */\n // // Copy the zero rate variables over if they are still rate zero.\n // // Check if the pairing is in the newNonZeroContValues.\n // // Interval being null indicates that the key was not\n /**\n * Handles the moving of the continuous variables in and out of the\n * _rateZeroContinuous. This includes the adding of all rate zero (new and old)\n * cotninuous variables to the _rateZeroContinuous, and creating the\n * _indexToTimerPair and populating it.\n * @param newZone The Zone being constructed.\n * @param enabled The list of enabled transitions.\n * \t\tThe enabled transitions.\n * @param newAssignValues The list of continuous variable update information.\n */\n @SuppressWarnings(\"unused\")\n private void copyRates(Zone newZone, LpnTranList enabledTran, ContinuousRecordSet newAssignValues) {\n /*\n\t\t * The newAssignValues is an ArrayList of four sets.\n\t\t * 0. Rate zero gets zero assigned.\n\t\t * 1. Rate zero gets non-zero rate assigned.\n\t\t * 2. Non-zero gets zero rate assigned.\n\t\t * 3. Non-zero gets non-zero rate assigned.\n\t\t */\n // Create new rate zero member variable.\n newZone._rateZeroContinuous = new DualHashMap();\n // First get the total number of non-zero rate continuous variables that\n // are present in the old zone.\n int totalContinuous = 0;\n for (int i = 0; i < _lpnList.length; i++) {\n totalContinuous += _lpnList[i].getTotalNumberOfContVars();\n }\n int numberNonZero = totalContinuous - _rateZeroContinuous.size();\n // The size is given by\n // total number of transitions\n // + number of non-zero rate continuous variables previously in the zone\n // + number of zero rate continuous variables that now have non-zero\n // - number of non-zero rate continuous variables that are now zero\n // + 1 for the zero timer.\n // TODO: Create an object that stores the records along with this information.\n int newNonZero = 0, newZero = 0;\n for (UpdateContinuous record : newAssignValues.keySet()) {\n if (record.newlyNonZero()) {\n newNonZero++;\n }\n if (record.newlyZero()) {\n newZero++;\n }\n }\n int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;\n // Create the timer array.\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n // Add in the zero timer.\n newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;\n // Copy over the rate zero conintinuous variables.\n // First copy over all the continuous variables that still have\n // rate zero.\n // // Cast the index.\n // // The variable no longer is rate zero, so do nothing.\n // // If the value has had an assignment, use the new values instead.\n // // Create the new VariableRangePair to add.\n // VariableRangePair vrp =\n // Copy over the rate zero continuous variables.\n // First copy over all the continuous variables that still have\n // rate zero.\n for (LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()) {\n // Cast the index.\n LPNContinuousPair ltContPair = ltTranPair.get_lcPair();\n if (!newAssignValues.get(ltContPair).is_newZero()) {\n // The variable no longer is rate zero, so do nothing.\n continue;\n }\n // If the value has had an assignment, use the new values instead.\n if (newAssignValues.contains(ltContPair)) {\n // Create the new VariableRangePair to add.\n Variable v = _lpnList[ltContPair.get_lpnIndex()].getContVar(ltContPair.get_ContinuousIndex());\n // VariableRangePair vrp =\n VariableRangePair vrp = new VariableRangePair(v, newAssignValues.get(ltContPair).get_Value());\n newZone._rateZeroContinuous.insert(new LPNContAndRate(ltContPair, new IntervalPair(0, 0)), vrp);\n } else {\n newZone._rateZeroContinuous.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));\n }\n }\n // Next add the values that are newly set to rate zero.\n // // Exract the variable.\n // // Create a VariableRangePair.\n // // Add the value to the map.\n // // Exract the variable.\n // // Create a VariableRangePair.\n // // Add the value to the map.\n // We still need to add in the rate zero continuous variables whose rate remains zero\n // since their range might have changed. We could check if the range has changed, but\n // its just as easy (or easier) to simply add it anyway.\n // Added the indecies for the non-zero rate continuous variables to the\n // _indexToTimer array.\n // Start with the values already in the old array.\n // int index = 1; // Index for the next continuous index object.\n // // Check that the value should not be removed.\n // Change to the new references for the oldNonZero. This change to the\n // Add in the indecies for the new non-zero into the old array.\n // Copy over the new transitions.\n Arrays.sort(newZone._indexToTimerPair);\n }\n\n private void copyRatesNew(Zone newZone, LpnTranList enabledTran, ContinuousRecordSet newAssignValues) {\n // Create new rate zero member variable.\n newZone._rateZeroContinuous = new DualHashMap();\n // First get the total number of non-zero rate continuous variables that\n // are present in the old zone.\n int totalContinuous = 0;\n for (int i = 0; i < _lpnList.length; i++) {\n totalContinuous += _lpnList[i].getTotalNumberOfContVars();\n }\n int numberNonZero = totalContinuous - _rateZeroContinuous.size();\n // The size is given by\n // total number of transitions\n // + number of non-zero rate continuous variables previously in the zone\n // + number of zero rate continuous variables that now have non-zero\n // - number of non-zero rate continuous variables that are now zero\n // + 1 for the zero timer.\n // TODO: Create an object that stores the records along with this information.\n int newNonZero = 0, newZero = 0;\n for (UpdateContinuous record : newAssignValues.keySet()) {\n if (record.newlyNonZero()) {\n newNonZero++;\n }\n if (record.newlyZero()) {\n newZero++;\n }\n }\n int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;\n // Create the timer array.\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n // Add in the zero timer.\n newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;\n int indexTimerCount = 1;\n // Sort the previous rate zero continuous variables into rate zero or non-zero.\n for (LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()) {\n // Cast the index.\n LPNContinuousPair ltContPair = ltTranPair.get_lcPair();\n // Check if the variable is a newly assigned value.\n UpdateContinuous assignedLtContPair = newAssignValues.get(ltContPair);\n if (assignedLtContPair != null) {\n if (assignedLtContPair.newlyNonZero()) {\n // Variable was zero and is now non-zero, so add to the the non-zero\n newZone._indexToTimerPair[indexTimerCount++] = assignedLtContPair.get_lcrPair().get_lcPair().clone();\n } else {\n // Variable was zero and is still zero, but an assignment has been\n // made. Simply add in the new assigned value.\n VariableRangePair vrp = this._rateZeroContinuous.get(ltTranPair);\n newZone._rateZeroContinuous.insert(assignedLtContPair.get_lcrPair(), new VariableRangePair(vrp.get_variable(), assignedLtContPair.get_Value()));\n }\n } else {\n newZone._rateZeroContinuous.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));\n }\n }\n // Sort the previous non-zero variables into the rate zero and non-zero.\n for (int i = 1; this._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];\n // Check if an assignment has been made.\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord != null) {\n if (updateRecord.is_newZero()) {\n // The continuous variable is now a rate zero variable.\n LPNContinuousPair ltCar = updateRecord.get_lcrPair().get_lcPair();\n Variable v = _lpnList[ltCar.get_lpnIndex()].getContVar(ltCar.get_ContinuousIndex());\n // Dewarp the upper and lower bounds.\n IntervalPair values = updateRecord.get_Value();\n int currentRate = getCurrentRate(ltCar);\n values.set_LowerBound(values.get_LowerBound() * currentRate);\n values.set_UpperBound(values.get_UpperBound() * currentRate);\n // Create a VariableRangePair.\n VariableRangePair vrp = new VariableRangePair(v, values);\n // Add the value to the map.\n newZone._rateZeroContinuous.insert(updateRecord.get_lcrPair(), vrp);\n } else {\n // This non-zero variable still has rate non-zero, but replace\n // with the newAssignValues since the rate may have changed.\n newZone._indexToTimerPair[indexTimerCount++] = updateRecord.get_lcrPair().get_lcPair();\n }\n } else {\n // The variable was non-zero and hasn't had an assignment.\n newZone._indexToTimerPair[indexTimerCount++] = this._indexToTimerPair[i].clone();\n }\n }\n // Copy over the new transitions.\n for (Transition t : enabledTran) {\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n newZone._indexToTimerPair[indexTimerCount++] = new LPNTransitionPair(lpnIndex, tranIndex);\n }\n Arrays.sort(newZone._indexToTimerPair);\n }\n\n private void advance() {\n for (int i = 0; i < dbmSize(); i++) {\n _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(i)] = getUpperBoundbydbmIndex(i);\n }\n }\n\n /**\n * Advances time. (This method should replace advance().)\n * @param localStates\n */\n @Override\n public void advance(State[] localStates) {\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n if (ltPair.equals(LPNTransitionPair.ZERO_TIMER_PAIR)) {\n continue;\n }\n // Get the new value.\n int newValue = 0;\n if (!(ltPair instanceof LPNContinuousPair)) {\n // If the pair is a timer, then simply get the stored largest value.\n int index = timerIndexToDBMIndex(ltPair);\n newValue = getUpperBoundbydbmIndex(index);\n } else {\n // If the pair is a continuous variable, then need to find the\n // possible largest bound governed by the inequalities.\n newValue = ContinuousUtilities.maxAdvance(this, ltPair, localStates);\n }\n // In either case (timer or continuous), set the upper bound portion\n // of the DBM to the new value.\n setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, newValue);\n }\n }\n\n /**\n * Copies in the new values needed to add a set of new times.\n * @param newZone\n * \t\t\tThe zone that the values are going to be copied into.\n * @param tempZone\n * \t\t\tThe zone to look up current values of timers.\n * @param newTimers\n * \t\t\tA collection of the new timers.\n * @param oldTimers\n * \t\t\tA collection of the older timers.\n * @param localStates\n * \t\t\tThe current state.\n */\n private void copyTransitions(Zone tempZone, Collection newTimers, Collection oldTimers, State[] localStates) {\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[j]);\n _matrix[dbmIndexToMatrixIndex(newIndexi)][dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n setDbmEntry(timerIndexToDBMIndex(timerNew), timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n setDbmEntry(timerIndexToDBMIndex(timerOld), timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n setLowerBoundByLPNTransitionPair(pair, lower);\n setUpperBoundByLPNTransitionPair(pair, upper);\n }\n }\n\n /**\n * This method sets all the rate to their lower bound.\n * Will not work quite right for continuous variables\n * with rates that include zero.\n */\n private void setAllToLowerBoundRate() {\n // Loop through the continuous variables.\n for (int i = 1; i < _indexToTimerPair.length && _indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair ltContPair = (LPNContinuousPair) _indexToTimerPair[i];\n // For this, recall that for a continuous variable that the lower bound\n // rate is stored in the zero column of the matrix.\n int lower = -1 * _matrix[dbmIndexToMatrixIndex(i)][0];\n int upper = _matrix[0][dbmIndexToMatrixIndex(i)];\n int newRate;\n /**\n * Suppose the range of rates is [a,b]. If a>=0, then we set the\n * rate to b. If b<=0, then we set the rate to a. Ohterwise,\n * a<0=0 or lower < 0 < upper we set the\n // rate to the upper bound.\n newRate = upper;\n }\n setCurrentRate(ltContPair, newRate);\n }\n }\n\n /**\n * Resets the rates of all continuous variables to be their\n * lower bounds.\n */\n @Override\n public Zone resetRates() {\n // Create the new zone.\n // // Copy the rate zero variables.\n // // Copy the LPNs over.\n // // Loop through the variables and save off those\n // // that are rate zero. Accumulate an array that\n // // indicates which are zero for faster\n // // copying. Save the number of continuous variables.\n // boolean[] rateZero = new boolean[this._indexToTimerPair.length]; // Is rate zero.\n // // The rate zero is in the range, so this will be\n // LPNContinuousPair lcPair =\n // // Save as a rate zero continuous variable.\n // VariableRangePair vcp =\n // // Update continuous variable counter.\n // // Save over the indexToTimer pairs.\n // // Ignore rate zero variables.\n // // If this is a continuous variable, set the rate to the lower bound.\n // // Calculate the size of the matrix and create it.\n // // Copy over the old matrix for all variables except\n // // the rate zero variables.\n // Warp\n Zone newZone = new Zone();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n /* \n\t\t * Collect the rate zero variables whose range of rates are not\n\t\t * identically zero. These will be moved out of the zone when\n\t\t * the rate is reset.\n\t\t * \n\t\t * Copy over the rate zero variables that remain rate zero.\n\t\t */\n newZone._rateZeroContinuous = new DualHashMap();\n HashSet> newlyNonZero = new HashSet>();\n for (Map.Entry variable : _rateZeroContinuous.entrySet()) {\n // Check for a single value which indicates that zero is\n // the only possible rate.\n if (variable.getKey().get_rateInterval().singleValue()) {\n // This variable only has zero as a rate so keep it\n // in the rate zero variables.\n newZone._rateZeroContinuous.insert(variable.getKey(), variable.getValue());\n } else {\n // This variable will need to be added to the zone.\n newlyNonZero.add(variable);\n }\n }\n /*\n\t\t * Calulate the size of the _indexToTimerPairs array and create\n\t\t * it.\n\t\t */\n int oldSize = this._indexToTimerPair.length;\n int newSize = oldSize + newlyNonZero.size();\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n /*\n\t\t * Copy over the old pairs and add the new ones.\n\t\t */\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();\n }\n for (Map.Entry variable : newlyNonZero) {\n newZone._indexToTimerPair[oldSize++] = variable.getKey().get_lcPair().clone();\n }\n Arrays.sort(newZone._indexToTimerPair);\n /*\n\t\t * Copy over the old matrix values and new constraints.\n\t\t */\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n for (int i = 0; i < this.dbmSize(); i++) {\n int newi = Arrays.binarySearch(newZone._indexToTimerPair, this._indexToTimerPair[i]);\n if (newi < 0) {\n System.err.println(\"In resetRates, old value was not found\" + \" in new value.\");\n continue;\n }\n // Copy upper and lower bounds for the variable.\n newZone._matrix[dbmIndexToMatrixIndex(newi)][0] = this._matrix[dbmIndexToMatrixIndex(i)][0];\n newZone._matrix[0][dbmIndexToMatrixIndex(newi)] = this._matrix[0][dbmIndexToMatrixIndex(i)];\n // Copy the DBM Entry\n for (int j = 0; j < this.dbmSize(); j++) {\n int newj = Arrays.binarySearch(newZone._indexToTimerPair, this._indexToTimerPair[j]);\n if (newj < 0) {\n System.err.println(\"In resetRates, old value was not\" + \" found in new value.\");\n continue;\n }\n newZone.setDbmEntry(newi, newj, this.getDbmEntry(i, j));\n }\n }\n for (Map.Entry variable : newlyNonZero) {\n LPNTransitionPair currentVariable = variable.getKey().get_lcPair();\n int currentIndex = Arrays.binarySearch(newZone._indexToTimerPair, currentVariable);\n IntervalPair rangeOfRates = variable.getKey().get_rateInterval();\n IntervalPair rangeOfValues = variable.getValue().get_range();\n /*\n\t\t\t * First set the range of rates, current rate, and the lower and upper\n\t\t\t * bounds for the newly added continuous variables.\n\t\t\t */\n newZone.setLowerBoundbydbmIndex(currentIndex, rangeOfRates.get_LowerBound());\n newZone.setUpperBoundbydbmIndex(currentIndex, rangeOfRates.get_UpperBound());\n newZone.setDbmEntry(currentIndex, 0, -1 * rangeOfValues.get_LowerBound());\n newZone.setDbmEntry(0, currentIndex, rangeOfValues.get_UpperBound());\n for (int j = 1; j < newZone.dbmSize(); j++) {\n if (currentIndex == j) {\n continue;\n }\n newZone.setDbmEntry(currentIndex, j, Zone.INFINITY);\n newZone.setDbmEntry(j, currentIndex, Zone.INFINITY);\n }\n }\n /*\n\t\t * Reset all the rates.\n\t\t */\n newZone.setAllToLowerBoundRate();\n newZone.recononicalize();\n newZone.dbmWarp(this);\n newZone.recononicalize();\n return newZone;\n }\n\n /**\n * Finds the maximum amount that time cam advance.\n * @return\n * \t\tvalue.\n * \t\tThe maximum amount that time can advance before a timer expires or an inequality changes\n */\n // * Several comments in this function may look like C code. That's because,\n // * well it is C code from atacs/src/lhpnrsg.c. In particular the\n // // Get the continuous variable in question.\n // // printf(\"Zone to check...\\n\");\n // // Get all the inequalities that reference the variable of interest.\n // // Update the inequality variable.\n // // /* Working on a > or >= ineq */\n // // Working on a > or >= ineq\n // // If the rate is positive.\n // // /* Working on a < or <= ineq */\n // // Working on a < or <= ineq\n // // Check if the value can be lowered.\n // //printf(\"Min leaving checkPreds for %s: %d\\n\",events[p]->event,min);\n /* (non-Javadoc)\n\t * @see java.lang.Object#clone()\n\t */\n @Override\n public Zone clone() {\n Zone clonedZone = new Zone();\n clonedZone._matrix = new int[this.matrixSize()][this.matrixSize()];\n for (int i = 0; i < this.matrixSize(); i++) {\n for (int j = 0; j < this.matrixSize(); j++) {\n clonedZone._matrix[i][j] = this._matrix[i][j];\n }\n }\n clonedZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n clonedZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();\n }\n clonedZone._hashCode = this._hashCode;\n clonedZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n clonedZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n return clonedZone;\n }\n\n /**\n * Restricts the lower bound of a timer.\n *\n * @param timer\n * \t\t\tThe timer to tighten the lower bound.\n */\n private void restrictTimer(int timer) {\n _matrix[dbmIndexToMatrixIndex(timer)][dbmIndexToMatrixIndex(0)] = getLowerBoundbydbmIndex(timer);\n }\n\n /**\n * Restricts the lower bound of a continuous variable. Also checks fixes\n * the upper bound to be at least as large if needed. This method\n * is usually used as a result of an event firing.\n * @param ltContPair\n * \t\tThe index of the continuous variable to restrict.\n * @param constant\n * \t\tThe constant value of the inequality event that is being used to update\n * \t\tthe variable indexed by ltContPair.\n */\n private boolean restrictContinuous(LPNContinuousPair ltContPair, int constant) {\n // It will be quicker to get the DBM index for the ltContPair one time.\n int variableIndex = timerIndexToDBMIndex(ltContPair);\n int zeroIndex = timerIndexToDBMIndex(LPNTransitionPair.ZERO_TIMER_PAIR);\n // Set the lower bound the variable (which is the DBM[variabl][0] entry.\n // Note : the lower bound in the zone is actually the negative of the lower\n // bound hence the -1 on the warpValue.\n setDbmEntry(variableIndex, zeroIndex, ContinuousUtilities.chkDiv(-1 * constant, ltContPair.getCurrentRate(), true));\n // Check if the upper bound needs to be advanced and advance it if necessary.\n if (getDbmEntry(zeroIndex, variableIndex) < ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true)) {\n // If the upper bound in the zones is less than the new restricting value, we\n // must advance it for the zone to remain consistent.\n setDbmEntry(zeroIndex, variableIndex, ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true));\n return true;\n }\n return false;\n }\n\n /**\n * Restricts the continuous variables in the zone according to the inequalities in a set of events.\n * @param eventSet\n * \t\t\tA set of inequality events. Does nothing if the event set does not contian inequalities.\n */\n private void restrictContinuous(EventSet eventSet) {\n // Check that the eventSet is a set of Inequality events.\n if (!eventSet.isInequalities()) {\n // If the eventSet is not a set of inequalities, do nothing.\n return;\n }\n HashSet adjustedColumns = new HashSet();\n boolean needsAdjusting = false;\n // Restrict the variables according to each of the inequalities in the eventSet.\n for (Event e : eventSet) {\n // Get the inequality.\n InequalityVariable iv = e.getInequalityVariable();\n // Extract the variable. I will assume the inequality only depends on a single\n Variable x = iv.getContVariables().get(0);\n // Extract the index.\n int lpnIndex = iv.get_lpn().getLpnIndex();\n // Extract the variable index.\n DualHashMap variableIndexMap = _lpnList[lpnIndex].getContinuousIndexMap();\n int variableIndex = variableIndexMap.getValue(x.getName());\n // Package it up for referencing.\n LPNContinuousPair ltContPair = new LPNContinuousPair(lpnIndex, variableIndex);\n // Need the current rate for the variable, grab the stored LPNContinuousPair.\n int zoneIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);\n if (zoneIndex > 0) {\n ltContPair = (LPNContinuousPair) _indexToTimerPair[zoneIndex];\n }\n // Perform the restricting.\n needsAdjusting = needsAdjusting | restrictContinuous(ltContPair, iv.getConstant());\n if (needsAdjusting) {\n adjustedColumns.add(ltContPair);\n }\n }\n // If one of the continuous variables has been moved forward, the other colmns\n // need to be adjusted to keep a consistent zone.\n if (needsAdjusting) {\n // At least one of the continuous variables has been moved forward,\n // so se need to ajust the bounds to keep a consistent zone.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltpair = _indexToTimerPair[i];\n if (adjustedColumns.contains(ltpair)) {\n // This continuous variables already had the upper bound\n continue;\n }\n // Add one to the upper bounds.\n setDbmEntry(0, i, getDbmEntry(0, i) + 1);\n }\n }\n }\n\n /**\n * Returns a zone that is the result from restricting the this zone according to a list of firing event inequalities.\n * @param eventSet\n * \t\tThe list of inequalities that are firing.\n * @return\n * \t\tThe new zone that is the result of restricting this zone according to the firing of the inequalities\n * \t\tin the eventSet.\n */\n @Override\n public Zone getContinuousRestrictedZone(EventSet eventSet, State[] localStates) {\n // Make a new copy of the zone.\n Zone z = this.clone();\n if (eventSet == null) {\n return z;\n }\n z.restrictContinuous(eventSet);\n return z;\n }\n\n /**\n * The list of enabled timers.\n * @return\n * \t\tThe list of all timers that have reached their lower bounds.\n */\n @Override\n public List getEnabledTransitions() {\n ArrayList enabledTransitions = new ArrayList();\n // Check if the timer exceeds its lower bound staring with the first nonzero\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n enabledTransitions.add(_lpnList[_indexToTimerPair[i].get_lpnIndex()].getTransition(_indexToTimerPair[i].get_transitionIndex()));\n }\n }\n return enabledTransitions;\n }\n\n /**\n * Gives the list of enabled transitions associated with a particular LPN.\n * @param LpnIndex\n * \t\t\tThe Index of the LPN the Transitions are a part of.\n * @return\n * \t\t\tA List of the Transitions that are enabled in the LPN given by the index.\n */\n @Override\n public List getEnabledTransitions(int LpnIndex) {\n ArrayList enabledTransitions = new ArrayList();\n // Check if the timer exceeds its lower bound staring with the first nonzero\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n if (ltPair.get_lpnIndex() == LpnIndex) {\n enabledTransitions.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));\n }\n }\n }\n return enabledTransitions;\n }\n\n /**\n * Find the next possible events.\n *\n * @param LpnIndex\n * \t\tThe index of the LPN that is of interest.\n * @param localState\n * \t\tThe state associated with the LPN indexed by LpnIndex.\n * @return\n * \t\tLpnTranList is populated with a list of\n * \t\tEventSets pertaining to the LPN with index LpnIndex. An EventSet can\n * \t\teither contain a transition to\n * \t\tfire or set of inequalities to change sign.\n */\n @Override\n public LpnTranList getPossibleEvents(int LpnIndex, State localState) {\n LpnTranList result = new LpnTranList();\n // Look through the timers and continuous variables. For the timers\n // determine if they are ready to fire. For the continuous variables,\n // look up the associated inequalities and see if any of them are ready\n // to fire.\n // We do not need to consider the zero timer, so start the\n // for loop at i=1 and not i=0.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // The enabled events are grouped with the LPN that they affect. So if\n // this pair does not belong to the current LPN under consideration, skip\n // processing it.\n if (ltPair.get_lpnIndex() != LpnIndex) {\n continue;\n }\n // If the index refers to a timer (and not a continuous variable) and has exceeded its lower bound,\n // then add the transition.\n if (!(ltPair instanceof LPNContinuousPair)) {\n // The index refers to a timer. Now check if time has advanced\n // far enough for the transition to fire.\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n Event e = new Event(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));\n result = addSetItem(this, result, e, localState);\n }\n } else {\n // The index refers to a continuous variable.\n // First check for a rate change event.\n LPNContinuousPair ltContPair = ((LPNContinuousPair) ltPair).clone();\n IntervalPair ratePair = getRateBounds(ltContPair);\n // // The rate represents a range of rates and no rate change\n // // event has occured.\n // // The rate contians zero, so we need to add two rate\n // // events: one for the lower bound and one for the upper\n // // Create the events.\n // // Add them to the result set.\n result = createRateEvents(this, ltContPair, ratePair, result, localState);\n // Check all the inequalities for inclusion.\n Variable contVar = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());\n if (contVar.getInequalities() != null) {\n for (InequalityVariable iv : contVar.getInequalities()) {\n // Check if the inequality can change.\n if (ContinuousUtilities.inequalityCanChange(this, iv, localState)) {\n result = addSetItem(this, result, new Event(iv), localState);\n }\n }\n }\n }\n }\n // Check the rate zero variables for possible rate change events.\n for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()) {\n // Get the reference object:\n LPNContinuousPair ltContPair = lcrPair.get_lcPair();\n // Extract the range of rates.\n IntervalPair ratePair = lcrPair.get_rateInterval();\n result = createRateEvents(this, ltContPair, ratePair, result, localState);\n }\n return result;\n }\n\n public static LpnTranList createRateEvents(Equivalence Z, LPNContinuousPair ltContPair, IntervalPair ratePair, LpnTranList result, State localState) {\n // // The rate represents a range of rates and no rate change\n // // event has occured.\n // // The rate contians zero, so we need to add two rate\n // // events: one for the lower bound and one for the upper\n // // Create the events.\n // // Add them to the result set.\n /*\n\t\t * Let [a,b] be the current range of rates for a given variable.\n\t\t * If a>=0, then we set the rate to b originally.\n\t\t * So if the current rate is b, then we have a rate change event to a.\n\t\t * \n\t\t * If b<=0, then we set the rate to a originially.\n\t\t * So if the current rate is a, then we have a rate change event to b.\n\t\t * \n\t\t * The final case to consider is when a < 0 and b > 0. If the current\n\t\t * rate is b, we allow rate changes to either a or 0. If the current\n\t\t * rate is a, we allow a rate change to zero.\n\t\t */\n if (ratePair.singleValue()) {\n // Rates that are not a range do not generate rate change events.\n return result;\n }\n ltContPair = ltContPair.clone();\n if (ratePair.get_LowerBound() >= 0) {\n if (ltContPair.getCurrentRate() == ratePair.get_UpperBound()) {\n ltContPair.setCurrentRate(ratePair.get_LowerBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n } else if (ratePair.get_UpperBound() <= 0) {\n if (ltContPair.getCurrentRate() == ratePair.get_LowerBound()) {\n ltContPair.setCurrentRate(ratePair.get_UpperBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n } else {\n if (ltContPair.getCurrentRate() == ratePair.get_UpperBound()) {\n // No rate change events have ocurred. So we allow one for zero\n // and the lower bounds rate.\n LPNContinuousPair ltContPairOther = ltContPair.clone();\n ltContPair.setCurrentRate(0);\n ltContPairOther.setCurrentRate(ratePair.get_LowerBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n result = addSetItem(Z, result, new Event(ltContPairOther), localState);\n } else if (ltContPair.getCurrentRate() == ratePair.get_LowerBound()) {\n // The rate has change to the lower bound. Allow one rate\n // change to zero.\n ltContPair.setCurrentRate(0);\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n }\n return result;\n }\n\n /**\n * Adds or removes items as appropriate to update the current\n * list of possible events. Note the type LpnTranList extends\n * LinkedList. The type EventSet extends transition\n * specifically so that objects of EventSet type can be place in\n * this list.\n * @param EventList\n * \t\t\tThe list of possible events.\n */\n public static LpnTranList addSetItem(Equivalence Z, LpnTranList E, Event e, State s) {\n // void lhpnAddSetItem(eventSets &E,lhpnEventADT e,ineqList &ineqL,lhpnZoneADT z,\n // lhpnStateADT cur_state)\n // Note the LPNTranList plays the role of the eventSets.\n int rv1l = 0, rv1u = 0, rv2l = 0, rv2u = 0, iZ, jZ;\n // printf(\"Event sets entering:\\n\");\n // Create the new LpnTranlist for holding the events.\n EventSet eSet = new EventSet();\n LpnTranList newE = new LpnTranList();\n boolean done = false;\n boolean possible = true;\n if (e.isRate()) {\n eSet.add(e);\n // I believe that I should actually copy over the old list\n // and then add the new event set.\n newE = E.copy();\n newE.addLast(eSet);\n // The previous two commands act to pass the changes of E\n // back out of the functions. So returning the new object\n // is suficient.\n // printf(\"Event sets leaving:\\n\");\n return newE;\n }\n if (e.isInequality()) {\n // Is this necessary, or even correct to update the inequalities.\n // System.out.println(\"Note the inequality is not being updated before in addSetItem\");\n // In this case the Event e represents an inequality.\n InequalityVariable ineq = e.getInequalityVariable();\n // Need to extract the rate.\n // To do this, I'll create the indexing object.\n Variable v = ineq.getContVariables().get(0);\n // Find the LPN.\n int lpnIndex = ineq.get_lpn().getLpnIndex();\n int varIndex = Z.getVarIndex(lpnIndex, v.getName());\n // Package it all up.\n // LPNTransitionPair ltPair =\n // Note : setting the rate is not necessary since\n // this is only being used as aan index.\n // LPNContinuousPair ltPair =\n LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);\n rv2l = ContinuousUtilities.chkDiv(-1 * ineq.getConstant(), Z.getCurrentRate(ltPair), true);\n rv2u = ContinuousUtilities.chkDiv(ineq.getConstant(), Z.getCurrentRate(ltPair), true);\n iZ = Z.getIndexByTransitionPair(ltPair);\n } else {\n // In this case, the event is a transition.\n Transition t = e.getTransition();\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n // Package the results.\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);\n iZ = Z.getIndexByTransitionPair(ltPair);\n }\n // Recall that E contains the events sets which are inherited from the Transition class\n // so they can be placed in an LpnTranList. So consider each event set.\n for (Transition es : E) {\n if (!(es instanceof EventSet)) {\n // This collection should contain event sets, not transitions.\n throw new IllegalArgumentException(\"The eventSet was a Transition object not an EventSet object.\");\n }\n EventSet eventSet = (EventSet) es;\n if (done) {\n // Copy any remaining sets into newE.\n newE.add(eventSet.clone());\n break;\n }\n EventSet workSet = eventSet.clone();\n // Get an iterator for the elements in the workset.\n for (Event oldEvent : eventSet) {\n // For matching code with atacs, note that oldEvent is 'j'.\n if (oldEvent.isRate()) {\n continue;\n }\n if (oldEvent.isInequality()) {\n // Again, is it necessary to do an update here?\n // System.out.println(\"Note the inequality is not being updated before in addSetItem\");\n // In this case the Event oldEvent represents an inequality.\n InequalityVariable ineq = oldEvent.getInequalityVariable();\n // Extract variable.\n Variable v = ineq.getContVariables().get(0);\n // Find the LPN.\n int lpnIndex = ineq.get_lpn().getLpnIndex();\n int varIndex = Z.getVarIndex(lpnIndex, v.getName());\n // Package it all up.\n // LPNTransitionPair ltPair =\n // Note : setting the rate is not necessary since this is\n // only being used as an index.\n // LPNContinuousPair ltPair =\n LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);\n rv1l = ContinuousUtilities.chkDiv(-1 * oldEvent.getInequalityVariable().getConstant(), Z.getCurrentRate(ltPair), true);\n rv1u = ContinuousUtilities.chkDiv(oldEvent.getInequalityVariable().getConstant(), Z.getCurrentRate(ltPair), true);\n jZ = Z.getIndexByTransitionPair(ltPair);\n } else {\n // In this case, the event is a transition.\n Transition t = oldEvent.getTransition();\n // Create the indexing object. (See the Abstraction Function protion at the\n // top of the class for more details.)\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n // Package the results.\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);\n jZ = Z.getIndexByTransitionPair(ltPair);\n }\n // /* Both actions are predicate changes */\n // Both actions are predicate changes.\n if (e.isInequality() && oldEvent.isInequality()) {\n // /* Both predicates are on the same variable */\n // Extract the variable lists.\n ArrayList newList = e.getInequalityVariable().getContVariables();\n ArrayList oldList = oldEvent.getInequalityVariable().getContVariables();\n // Issue a warning if one of the lists has more than a single\n if (newList.size() > 1 && oldList.size() > 1) {\n System.err.println(\"Warning: One of the inequalities \" + e + \" \" + oldEvent + \" refers to more than one variable\");\n }\n // Both inequalities are on the same variables.\n if (newList.get(0).equals(oldList.get(0))) {\n if (rv1l > rv2l) {\n possible = false;\n } else // printf(\"Adding to erase list: \\n\");\n if (rv2l > rv1l) {\n workSet.remove(oldEvent);\n } else // printf(\"Adding to erase list: \\n\");\n if (rv1u > rv2u) {\n workSet.remove(oldEvent);\n } else {\n workSet.add(e);\n done = true;\n }\n } else // /* Predicates are on different variables */\n // Inequalities are on different variables.\n {\n // TODO : Check that the indecies must be reversed. I believe\n // they do since I think my representation is the transpose\n // of atacs. This will affect all the following statements.\n if (rv1l > rv2l + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else // printf(\"Adding to erase list: \");\n if (rv2l > rv1l + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n } else // printf(\"Adding to erase list: \\n\");\n if (rv1u > Z.getUpperBoundTrue(iZ) + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n } else if (rv2u > Z.getUpperBoundTrue(jZ) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else if (rv1l == rv2l + Z.getDbmEntry(jZ, iZ) && rv2l == rv1l + Z.getDbmEntry(iZ, jZ) && rv1u == rv2u + Z.getDbmEntry(iZ, jZ) && rv2u == rv1u + Z.getDbmEntry(jZ, iZ)) {\n workSet.add(e);\n }\n }\n } else // /* New action is predicate change, old is transition firing (case 3) */\n // New action is an inequality and the old even tis a transition (case 3).\n if (e.isInequality() && oldEvent.isTransition()) {\n // printf(\"Adding to erase list: \\n\");\n if (rv2l > -1 * Z.getLowerBoundbyTransition(e.getTransition()) + Z.getDbmEntry(iZ, jZ)) {\n // Probably can change this to refer directly to the zone.\n workSet.remove(oldEvent);\n } else if (rv2u > Z.getUpperBoundTrue(jZ) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n }\n } else // /* TODO: One more ugly case, is it needed? */\n // /* New action is transition firing, old is predicate change (case 4) */\n // New event is a transition firing, old event is an inequality change (case 4).\n if (e.isTransition() && oldEvent.isInequality()) {\n if (rv1l > (-1) * Z.getLowerBoundbyTransition(e.getTransition()) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else // printf(\"Adding to erase list: \\n\");\n // Real one: fix the getting of the upper and lower bounds. Done\n if (rv1u > Z.getUpperBoundTrue(iZ) + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n }\n // /* TODO: one more ugly case, is it needed? */\n // I guess this one wasn't needed since it is not found in atacs.\n }\n }\n if (!(workSet.isEmpty())) {\n newE.add(workSet);\n }\n }\n // This part of the code is essentially copying the all the old event set into the new event set.\n // There might be a way around doing this by working directly on the set to begin with.\n // Moved to being done at the begining of the previous block.\n // // This collection should contain event sets, not transitions.\n // throw new IllegalArgumentException(\"The eventSet was a Transition object not an EventSet object.\");\n if (!done && possible) {\n eSet.add(e);\n newE.add(eSet);\n }\n E = newE;\n // printf(\"Event sets leaving:\\n\");\n return E;\n }\n\n @Override\n public int getVarIndex(int lpnIndex, String name) {\n return _lpnList[lpnIndex].getContinuousIndexMap().getValue(name);\n }\n\n /**\n * Adds a set item and explicitly sets a flag to remove the next set item\n * upon firing.\n * @param E\n * The list of current event sets.\n * @param e\n * The event to add.\n * @param s\n * The current state.\n * @param removeNext\n * True if afer firing this event, the next event should be removed from the\n * queue.\n * @return\n * The new event set.\n */\n // public static LpnTranList addSetItem(LpnTranList E, Event e, State s,\n /**\n * Updates the continuous variables that are set by firing a transition.\n * @param firedTran\n * \t\tThe transition that fired.\n * @param s\n * \t\tThe current (local) state.\n */\n public void updateContinuousAssignment(Transition firedTran, State s) {\n // Get the LPN.\n LPN lpn = _lpnList[firedTran.getLpn().getLpnIndex()];\n // Get the current values of the (local) state.\n HashMap currentValues = lpn.getAllVarsWithValuesAsString(s.getVariableVector());\n // Get all the continuous variable assignments.\n HashMap assignTrees = firedTran.getContAssignTrees();\n for (String contVar : assignTrees.keySet()) {\n // Get the bounds to assign the continuous variables.\n IntervalPair assignment = assignTrees.get(contVar).evaluateExprBound(currentValues, this, null);\n // Make the assignment.\n setContinuousBounds(contVar, lpn, assignment);\n }\n }\n\n /**\n * Updates the continuous variables according to the given values.\n * @param newContValues\n * \t\tThe new values of the continuous variables.\n */\n public void updateContinuousAssignment(ContinuousRecordSet newAssignValues) {\n /*\n\t\t * In dealing with the rates and continuous variables, there are four cases to consider. These cases\n\t\t * depend on whether the the old value of the 'current rate' is zero or non-zero and whether the\n\t\t * new value of the 'current rate' is zero or non-zero. \n\t\t * 0. old rate is zero, new rate is zero.\n\t\t * \t\tLookup the zero rate in the _rateZeroContinuous and add any new continuous assignments.\n\t\t * 1. old rate is zero, new rate is non-zero.\n\t\t * \t\tRemove the rate from the _rateZeroContinuous and add the zone.\n\t\t * 2. old rate is non-zero, new rate is zero.\n\t\t * \t\tAdd the variable with its upper and lower bounds to _rateZeroContinuous.\n\t\t * 3. old rate is non-zero, new rate is non-zero.\n\t\t * \t\tGet the LPNContinuousPair from the _indexToTimerPair and change the value.\n\t\t * \n\t\t * Note: If an assignment is made to the variable, then it should be considered as a\n\t\t * new variable.\n\t\t */\n // The updating of the rate-zero continuous variables is taken care of\n // by the copyRates. So just need to update the values in the zone.\n // This amounts to copying over the values from the old zone for\n // continuous variables that haven't changed and copying in\n // // Set the lower bound.\n // // Set the upper bound.\n // // Set the rate.\n // // Set the lower bound.\n // // Set the upper bound.\n // // Set the current rate.\n // // Set the upper and lower bounds for the rates.\n }\n\n /* (non-Javadoc)\n\t * @see verification.timed_state_exploration.zone.Zone#getLexicon()\n\t */\n /**\n * Gives an array that maps the index of a timer in the DBM to the timer's index.\n * @return\n * \t\tThe array that maps the index of a timer in the DBM to the timer's index.\n */\n /**\n * Calculates a warping value needed to warp a Zone. When a zone is being warped the form\n * r1*z2 - r1*z1 + r2*z1 becomes important in finding the new values of the zone. For example,\n *\n * @param z1\n * \t\tUpper bound or negative lower bound.\n * @param z2\n * \t\tRelative value.\n * @param r1\n * \t\tFirst ratio.\n * @param r2\n * \t\tSecond ratio.\n * @return\n * \t\tr1*z2 - r1*z1 + r2*z1\n */\n public static int warp(int z1, int z2, int r1, int r2) {\n /*\n\t\t * See \"Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets\"\n\t\t * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda\n\t\t * Section III.C for details on how this function is used and where it comes\n\t\t * from.\n\t\t */\n return r1 * z2 - r1 * z1 + r2 * z1;\n }\n\n /**\n * Warps this Zone with the aid of rate information from the previous Zone.\n *\n * @param oldZone\n * \t\tThe previous Zone.\n * @return\n * \t\tThe warped Zone.\n */\n @Override\n public void dbmWarp(Equivalence oldE) {\n Zone oldZone = (Zone) oldE;\n /*\n\t\t * See \"Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets\"\n\t\t * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda\n\t\t * Section III.C for details on how this function is used and where it comes\n\t\t * from.\n\t\t */\n // /* TODO: This appears to NOT work when INFIN is in the bounds?\n // Should I have to worry about this case? */\n // According to atacs comments, this appears to NOT work when\n // INFIN is in the bounds.\n // This portion of the code handles the warping of the relative\n // parts of the zone.\n for (int i = 1; i < dbmSize(); i++) {\n for (int j = i + 1; j < dbmSize(); j++) {\n double iVal, jVal, iWarp, jWarp, iXDot, jXDot;\n // Note : the iVal and the jVal correspond to the\n // alpha and beta describe in Scott Little's thesis.\n // /* deal w/ the fact that we might have continuous and discrete\n // Do some warping when dealing with the continuous variables.\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n // Calcualte the alpha value.\n iVal = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[i]) / (double) this.getCurrentRate(_indexToTimerPair[i])));\n // The old rate the zone was warped by.\n iWarp = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[i])));\n // The current rate rate of this continuous variable.\n iXDot = Math.floor(Math.abs((double) this.getCurrentRate(_indexToTimerPair[i])));\n // I'm not going to do any warping when the previous rate\n // is zero. This statement is a break to go to next i value\n // and not the next j.\n if (iWarp == 0) {\n break;\n }\n } else {\n // The current variable is a timer, so the new rate and old rate\n // are both 1. Hence we have\n iVal = 1.0;\n iWarp = 1.0;\n iXDot = 1.0;\n }\n // Do some warping of the second variable if it is a continuous variable.\n if (_indexToTimerPair[j] instanceof LPNContinuousPair) {\n // Calcualte the alpha value.\n jVal = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[j]) / (double) this.getCurrentRate(_indexToTimerPair[j])));\n // The old rate the zone was warped by.\n jWarp = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[j])));\n // The current rate of this continuous variable.\n jXDot = Math.floor(Math.abs((double) this.getCurrentRate(_indexToTimerPair[j])));\n // I'm not going to do any warping when the previous rate is\n if (jWarp == 0) {\n continue;\n }\n } else {\n // The current variable is a timer, so the new rate and old rate\n // are both 1. Hence we have\n jVal = 1.0;\n jWarp = 1.0;\n jXDot = 1.0;\n }\n // The zone is warped differently depending on which of rate is\n // larger. See Scott Little's Thesis for more details.\n if (iWarp * jXDot > jWarp * iXDot) {\n setDbmEntry(j, i, (int) Math.ceil(((jWarp * getDbmEntry(j, i)) / jXDot) + ((-1 * jWarp * getDbmEntry(0, i) / jXDot)) + ((iWarp * getDbmEntry(0, i) / iXDot))));\n setDbmEntry(i, j, (int) Math.ceil(((jWarp * getDbmEntry(i, j)) / jXDot) + ((-1 * jWarp * getDbmEntry(i, 0) / jXDot)) + ((iWarp * getDbmEntry(i, 0) / iXDot))));\n } else {\n setDbmEntry(i, j, (int) Math.ceil(((iWarp * getDbmEntry(i, j)) / iXDot) + ((-1 * iWarp * getDbmEntry(0, j) / iXDot)) + ((jWarp * getDbmEntry(0, j) / jXDot))));\n setDbmEntry(j, i, (int) Math.ceil(((iWarp * getDbmEntry(j, i)) / iXDot) + ((-1 * iWarp * getDbmEntry(j, 0) / iXDot)) + ((jWarp * getDbmEntry(j, 0) / jXDot))));\n }\n }\n }\n // printf(\"After fixing up initial warp conditions.\\n\");\n // Handle the warping of the bounds.\n for (int i = 1; i < dbmSize(); i++) {\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n if (Math.abs(getDbmEntry(i, 0)) != INFINITY) {\n if (oldZone.getCurrentRate(_indexToTimerPair[i]) == 0) {\n // If the older rate was zero, then we just need to\n // divide by the new rate.\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(getDbmEntry(i, 0), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n } else {\n // Undo the old warping and introduce the new warping.\n // If the bound is infinite, then division does nothing.\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i])) * getDbmEntry(i, 0), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n }\n }\n if (Math.abs(getDbmEntry(0, i)) != INFINITY) {\n if (oldZone.getCurrentRate(_indexToTimerPair[i]) == 0) {\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(getDbmEntry(0, i), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n } else {\n // Undo the old warping and introduce the new warping.\n // If the bound is inifite, then division does nothing.\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i])) * getDbmEntry(0, i), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n }\n }\n }\n }\n // printf(\"After fixing up places.\\n\");\n for (int i = 1; i < dbmSize(); i++) {\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n // /* TBD: If i & j are both changing direction do we need to\n // remove the warp info? */\n // Handle the case when the warping takes us into negative space.\n if ((double) oldZone.getCurrentRate(_indexToTimerPair[i]) / (double) this.getCurrentRate(_indexToTimerPair[i]) < 0.0) {\n /* We are warping into the negative space, so swap the upper and \n\t\t\t\t\t * lower bounds.\n\t\t\t\t\t */\n int temp = getDbmEntry(i, 0);\n setDbmEntry(i, 0, getDbmEntry(0, i));\n setDbmEntry(0, i, temp);\n // Set the relationships to Infinity since nothing else is known.\n for (int j = 1; j < dbmSize(); j++) {\n if (i != j) {\n setDbmEntry(i, j, INFINITY);\n setDbmEntry(j, i, INFINITY);\n }\n }\n }\n }\n }\n // printf(\"After handling negative warps.\\n\");\n /* Do the nature of how I store things, I do not think I need to do\n\t\t\t * this portion.\n\t\t\t */\n }\n\n /**\n * The DiagonalNonZeroException extends the java.lang.RuntimerExpcetion.\n * The intention is for this exception to be thrown is a Zone has a non zero\n * entry appear on the diagonal.\n *\n * @author Andrew N. Fisher\n */\n public class DiagonalNonZeroException extends java.lang.RuntimeException {\n\n private static final long serialVersionUID = -3857736741611605411L;\n\n /**\n * Creates a DiagonalNonZeroException.\n * @param Message\n * \t\t\tThe message to be displayed when the exception is thrown.\n */\n public DiagonalNonZeroException(String Message) {\n super(Message);\n }\n }\n\n /**\n * This exception is thrown when trying to merge two zones whose corresponding timers\n * do not agree.\n * @author Andrew N. Fisher\n */\n // // TODO : Check if this class can be removed.\n // * Generated serialVersionUID\n /**\n * Clears out the lexicon.\n */\n public static IntervalPair parseRate(String rate) {\n String rateNoSpaces = rate.trim();\n // First check if the string is a single number.\n // // The string is a number, so set the upper and lower bounds equal.\n // First check for a comma (representing an interval input).\n int commaIndex = rateNoSpaces.indexOf(\",\");\n if (commaIndex < 0) {\n // Assume that the string is a constant. A NumberFormatException\n // will be thrown otherwise.\n int i = Integer.parseInt(rate);\n return new IntervalPair(i, i);\n }\n String lowerString = rateNoSpaces.substring(1, commaIndex).trim();\n String upperString = rateNoSpaces.substring(commaIndex + 1, rateNoSpaces.length() - 1).trim();\n return new IntervalPair(Integer.parseInt(lowerString), Integer.parseInt(upperString));\n }\n\n /**\n * Get the list of LhpnFile objects that this Zone depends on.\n * @return\n * \t\tThe lits of LhpnFile objects that this Zone depends on.\n */\n @Override\n public LPN[] get_lpnList() {\n return _lpnList;\n }\n\n /**\n * Performs a division of two integers and either takes the ceiling or the floor. Note :\n * The integers are converted to doubles for the division so the choice of ceiling or floor is\n * meaningful.\n * @param top\n * \t\tThe numerator.\n * @param bottom\n * \t\tThe denominator.\n * @param ceil\n * \t\tTrue indicates return the ceiling and false indicates return the floor.\n * @return\n * \t\tReturns the ceiling of top/bottom if ceil is true and the floor of top/bottom otherwise.\n */\n // * This method was taken from atacs/src/hpnrsg.c\n // System.out.println(\"Warning: Divided by zero.\");\n /**\n * Returns the current rate of the variable.\n * @param contVar\n * \t\tThe LPNTransitionPair referring to a continuous variable.\n * @return\n * \t\tThe current rate of the continuous variable refenced by the LPNTransitionPair.\n * @throws IllegalArgumentException\n * \t\tIf the LPNTransitionPair is not an instance of an LPNContinuousPair.\n */\n @Override\n public int getCurrentRate(LPNTransitionPair contVar) {\n if (!(contVar instanceof LPNContinuousPair)) {\n // The LPNTransitionsPair does not refer to a continuous variable, so yell.\n throw new IllegalArgumentException(\"Zone.getCurrentRate was called\" + \" on an LPNTransitionPair that was not an LPNContinuousPair.\");\n }\n LPNContinuousPair cV = (LPNContinuousPair) contVar;\n // Search for the pair in the zone.\n int index = Arrays.binarySearch(_indexToTimerPair, cV);\n if (index > 0) {\n // The continuous variable was found amongst the non zero rate continuous variables.\n // Grab that indexing object instead since it has the rate.\n cV = (LPNContinuousPair) _indexToTimerPair[index];\n return cV.getCurrentRate();\n }\n // Since the variable was not found in the non-zero rate continuous\n // variables, assume the rate is zero.\n return 0;\n }\n\n /**\n * Sets the current rate for a continuous variable. It sets the rate regardless of\n * whether the variable is in the rate zero portion of the Zone or not. But it\n * does not move variables in and out of the zone.\n * @param contVar\n * \t\tThe index of the variable whose rate is going to be set.\n * @param currentRate\n * \t\tThe value of the rate.\n */\n @Override\n public void setCurrentRate(LPNTransitionPair contVar, int currentRate) {\n if (!(contVar instanceof LPNContinuousPair)) {\n // The LPNTransitionsPair does not refer to a continuous variable, so yell.\n throw new IllegalArgumentException(\"Zone.getCurrentRate was called\" + \" on an LPNTransitionPair that was not an LPNContinuousPair.\");\n }\n LPNContinuousPair cV = (LPNContinuousPair) contVar;\n // Check for the current variable in the rate zero variables.\n VariableRangePair variableRange = _rateZeroContinuous.getValue(new LPNContAndRate(cV, new IntervalPair(0, 0)));\n if (variableRange != null) {\n LPNContinuousPair lcPair = _rateZeroContinuous.getKey(variableRange).get_lcPair();\n lcPair.setCurrentRate(currentRate);\n return;\n }\n // Check for the current variable in the Zone variables.\n int index = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (index >= 0) {\n // The variable was found, set the rate.\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[index];\n lcPair.setCurrentRate(currentRate);\n }\n }\n\n /**\n * Adds a transition to a zone.\n * @param newTransitions\n * \t\t\tThe newly enabled transitions.\n * @return\n * \t\t\tThe result of adding the transition.\n */\n @Override\n public Zone addTransition(HashSet newTransitions, State[] localStates) {\n /*\n\t\t * The zone will remain the same for all the continuous variables.\n\t\t * The only thing that will change is a new transition will be added into the transitions.\n\t\t */\n // Create a Zone to alter.\n Zone newZone = new Zone();\n // Create a copy of the LPN list.\n newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n // Copy the rate zero continuous variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Create a copy of the current indexing pairs.\n newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + newTransitions.size()];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = _indexToTimerPair[i];\n }\n // Add the new transitions to the _indexToTimerPair list.\n // // Set up the index for the newTransitions list.\n int i = _indexToTimerPair.length;\n for (LPNTransitionPair ltPair : newTransitions) {\n newZone._indexToTimerPair[i++] = ltPair;\n }\n // Sort the _indexToTimerPair list.\n Arrays.sort(newZone._indexToTimerPair);\n // Create matrix.\n newZone._matrix = new int[newZone._indexToTimerPair.length + 1][newZone._indexToTimerPair.length + 1];\n // Convert the current transitions to a collection of transitions.\n HashSet oldTransitionSet = new HashSet();\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n oldTransitionSet.add(ltPair);\n }\n // Copy in the new transitions.\n newZone.copyTransitions(this, newTransitions, oldTransitionSet, localStates);\n return newZone;\n }\n\n /**\n * This method creates a zone identical to the current zone except all the current rates are turned to 1.\n * This is to provide a previous zone to the initial zone for warping.\n * @return\n * \t\tA zone identical to this zone with all rates set to 1.\n */\n private Zone beforeInitialZone() {\n Zone z = this.clone();\n for (int i = 1; i < z._indexToTimerPair.length; i++) {\n if (!(z._indexToTimerPair[i] instanceof LPNContinuousPair)) {\n break;\n }\n LPNContinuousPair lcPair = (LPNContinuousPair) z._indexToTimerPair[i];\n lcPair.setCurrentRate(1);\n }\n return z;\n }\n\n /**\n * Add a rate zero variable to the DBM portion of the zone. This method\n * is intended as an aid for when a rate zero variable gets assign a\n * non-zero rate.\n * @param ltContPair The continuous variable to move from the rate zero\n * variables.\n * @return The resulting Zone.\n */\n @Override\n public Zone moveOldRateZero(LPNContinuousPair ltContPair) {\n // Create a Zone to alter.\n Zone newZone = new Zone();\n // Create a copy of the LPN list.\n newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n // Copy the rate zero continuous variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Extract the continuous variable from the rate zero variables.\n LPNContAndRate rateZero = new LPNContAndRate(ltContPair, new IntervalPair(0, 0));\n // This gets the values for the continuous variable.\n VariableRangePair vrp = newZone._rateZeroContinuous.get(rateZero);\n IntervalPair values = vrp.get_range();\n // This replaces the rateZero with the one stored in the _rateZeroContinuous.\n // The purpose of this is to obtain the stored range of rates.\n rateZero = newZone._rateZeroContinuous.getKey(vrp);\n // Get the range of rates.\n IntervalPair rangeOfRates = rateZero.get_rateInterval();\n // Remove the continuous variable.\n newZone._rateZeroContinuous.delete(rateZero);\n // Create a copy of the current indexing pairs.\n newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + 1];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = _indexToTimerPair[i];\n }\n // Add the continuous variable to the list of variables/transition in the DBM.\n int numOfTransitions = _indexToTimerPair.length;\n newZone._indexToTimerPair[numOfTransitions] = ltContPair;\n // Sort the _indexToTimerPair list.\n Arrays.sort(newZone._indexToTimerPair);\n // Create matrix.\n newZone._matrix = new int[newZone._indexToTimerPair.length + 1][newZone._indexToTimerPair.length + 1];\n // Convert the current transitions to a collection of transitions.\n HashSet oldTransitionSet = new HashSet();\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n oldTransitionSet.add(ltPair);\n }\n // Copy in the new transitions.\n newZone.copyTransitions(this, new HashSet(), oldTransitionSet, null);\n // Get the index for the variable.\n int index = Arrays.binarySearch(newZone._indexToTimerPair, ltContPair);\n // Copy in the upper and lower bound of the old rate zero variable.\n // Copy in the range of rates.\n newZone.setLowerBoundbydbmIndex(index, rangeOfRates.get_LowerBound());\n newZone.setUpperBoundbydbmIndex(index, rangeOfRates.get_UpperBound());\n if (ltContPair.getCurrentRate() > 0) {\n // Set the upper and lower bounds.\n newZone.setDbmEntry(0, index, ContinuousUtilities.chkDiv(values.get_UpperBound(), ltContPair.getCurrentRate(), true));\n newZone.setDbmEntry(index, 0, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), ltContPair.getCurrentRate(), true));\n } else {\n // Set the upper and lower bounds. Since the rate is zero\n // We swap the real upper and lower bounds.\n newZone.setDbmEntry(0, index, ContinuousUtilities.chkDiv(values.get_LowerBound(), ltContPair.getCurrentRate(), true));\n newZone.setDbmEntry(index, 0, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), ltContPair.getCurrentRate(), true));\n }\n // Set the DBM to having no relating information for how this\n // variables relates to the other variables.\n for (int i = 1; i < newZone._indexToTimerPair.length; i++) {\n if (i == index) {\n continue;\n }\n newZone.setDbmEntry(index, i, Zone.INFINITY);\n newZone.setDbmEntry(i, index, Zone.INFINITY);\n }\n newZone.recononicalize();\n return newZone;\n }\n\n /**\n * This method removes the variable from the DBM portion of the\n * zone and adds the variable to the rate-zero portion of the\n * zone. The purpose of this method is to handle when a non-zero\n * rate variable is assigned a zero rate.\n * @param firedRate The new assignment for the variable.\n * @return The resulting zone.\n */\n @Override\n public Zone saveOutZeroRate(LPNContinuousPair firedRate) {\n // Check if the variable is in the zone.\n // We assume that the rate is already zero in this case\n // since it must be in the rate zero variables if it exists.\n int index = Arrays.binarySearch(this._indexToTimerPair, firedRate);\n if (index < 0) {\n System.err.println(\"A variable is getting its rate set to zero\");\n System.err.println(\"when the rate is already zero.\");\n return this;\n }\n // Create new zone\n Zone newZone = new Zone();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n // Copy over the rate zero variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Get the range of rates and values.\n IntervalPair rangeOfRates = this.getRateBounds(firedRate);\n IntervalPair rangeOfValues = this.getContinuousBounds(firedRate);\n // Create the key and value pairs for the rate zero continuous variable.\n LPNContAndRate lcar = new LPNContAndRate(firedRate.clone(), rangeOfRates);\n VariableRangePair vrPair = new VariableRangePair(this._lpnList[firedRate.get_lpnIndex()].getContVar(firedRate.get_ContinuousIndex()), rangeOfValues);\n newZone._rateZeroContinuous.insert(lcar, vrPair);\n // Copy over the pairs, skipping the new rate zero.\n newZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length - 1];\n int offset = 0;\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n if (i == index) {\n offset++;\n }\n newZone._indexToTimerPair[i] = this._indexToTimerPair[i + offset].clone();\n }\n // Copy over the DBM\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n int offseti = 0;\n int offsetj = 0;\n for (int i = 0; i < newZone.matrixSize(); i++) {\n if (i == index + 1) {\n offseti++;\n }\n offsetj = 0;\n for (int j = 0; j < newZone.matrixSize(); j++) {\n if (j == index + 1) {\n offsetj++;\n }\n newZone._matrix[i][j] = this._matrix[i + offseti][j + offsetj];\n }\n }\n return newZone;\n }\n\n @Override\n public int getIndexByTransitionPair(LPNTransitionPair ltPair) {\n return Arrays.binarySearch(_indexToTimerPair, ltPair);\n }\n /**\n * Determines whether time has advanced far enough for an inequality to change\n * truth value.\n * @param ineq\n * \t\tThe inequality to test whether its truth value can change.\n * @param localState\n * \t\tThe state associated with the inequality.\n * @return\n * \t\tTrue if the inequality can change truth value, false otherwise.\n */\n // // Find the index of the continuous variable this inequality refers to.\n // // I'm assuming there is a single variable.\n // // Package up the information into a the index. Note the current rate doesn't matter.\n // // Get the current rate.\n // // Get the current value of the inequality. This requires looking into the current state.\n // // Get the Zone index of the variable.\n // //\t\tbool lhpnPredCanChange(ineqADT ineq,lhpnZoneADT z,lhpnRateADT r,\n // //warn(\"An inequality produced a place not in the zone.\");\n // // First check cases when the rate is negative.\n // //warn(\"An inequality produced a place not in the zone.\");\n}\n"} {"task_id": "Java_3038", "language": "Java", "task_type": "try_statement", "source_file": "java/github/MyersResearchGroup/iBioSim/verification/src/main/java/edu/utah/ece/async/lema/verification/timed_state_exploration/zoneProject/Zone.java", "mask_start_position": 70441, "mask_end_position": 70670, "canonical_solution": "try {\n if (_writeLogFile != null) {\n _writeLogFile.write(t.toString());\n _writeLogFile.newLine();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }", "pre_mask_code": "/**\n * ****************************************************************************\n *\n * This file is part of iBioSim. Please visit \n * for the latest version of iBioSim.\n *\n * and also available online at .\n *\n * *****************************************************************************\n */\npackage edu.utah.ece.async.lema.verification.timed_state_exploration.zoneProject;\n\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport edu.utah.ece.async.lema.verification.lpn.ExprTree;\nimport edu.utah.ece.async.lema.verification.lpn.LPN;\nimport edu.utah.ece.async.lema.verification.lpn.Transition;\nimport edu.utah.ece.async.lema.verification.lpn.Variable;\nimport edu.utah.ece.async.lema.verification.platu.main.Options;\nimport edu.utah.ece.async.lema.verification.platu.platuLpn.DualHashMap;\nimport edu.utah.ece.async.lema.verification.platu.platuLpn.LpnTranList;\nimport edu.utah.ece.async.lema.verification.platu.stategraph.State;\nimport edu.utah.ece.async.lema.verification.timed_state_exploration.octagon.Equivalence;\n\n/**\n * This class is for storing and manipulating the delay information for transitions as well as\n * the values of continuous variables including rate their rates.\n * A Zone represents the non-zero continuous variables and the timers for the delay in a\n * Difference Bound Matrix (DBM)\n *\n * t0 c0 c1 t0 t1\n * t0 m00 m01 m02 m03 m04\n * c0 m10 m11 m12 m13 m14\n * c1 m20 m21 m22 m23 m24\n * t0 m30 m31 m32 m33 m34\n * t1 m40 m41 m42 m43 m44\n *\n * For the timers, tj - ti <= m(ti,tj) where m(ti,tj) represents the element of the matrix with\n * row ti and column tj. In particular, m(t0,ti) is an upper bound for ti and -m(ti,0) is a\n * lower bound for ti. The continuous variables are normalized to have rate one before being\n * placed in the matrix. Thus for a continuous variables ci with rate ri, the entry m(t0, ci) is\n * (upper bound)/ri where 'upper bound' is the upper bound for the continuous variable and\n * m(ci,t0) is -1*(lower bound)/ri where 'lower bound' is the lower bound of the continuous variable.\n * When the rate is negative, dividing out by the rate switches the inequalities. For example,\n * if ci is a continuous variable such that l < ci < u for some values l and u, then the normalized\n * ci (that is ci/ri) is satisfies u/ri < ci/r < l/ri. Hence the m(t0,ci) is (lower bound)/ri and\n * m(ci,0) is -1*(upper bound)/ri. The m(ci,cj) as well as m(ti,ci) and m(ci,ti) give the same kind\n * of relational information as with just timers, but with the normalized values of the continuous\n * variables. Note that a Zone with normalized continuous variables is referred to as being a 'warped'\n * zone.\n *\n * The rate zero continuous variables are also stored in a Zone object, but they are not present in\n * the zone. The Zone merely records the range of the continuous variable.\n *\n * The timers are referenced by the name of the transition that they are associated with and continuous\n * variables are referenced by their name as well. In addition for non-zero rate continuous variables and\n * the timers, several method will allow them to be referred by their index as a part of the (DMB). For\n * example, c0 in the above DBM example, has index 1.\n *\n * A third way that the timers and variables (both rate zero and rate non-zero) can be referred to by\n * an LPNTransitionPair object. These objects refer to a timer or continuous variable by providing the index\n * of the corresponding transition or the index of the continuous variable as a member of an LPN and the\n * index of that LPN. The LPNTransitionPair can be made more specific in the case of the continuous variables\n * by using an LPNContinuousPair. These objects also provide the rate of the variable. LPNTransitionPairs\n * can be used with continuous variables when they are only being used as an index only. If the rate is needed\n * for the method, then LPNContinuousPairs must be used.\n *\n * @author Andrew N. Fisher\n * @author Chris Myers\n * @author iBioSim Contributors \n * @version %I%\n */\npublic class Zone implements Equivalence {\n\n /*Abstraction Function : \n\t* The difference bound matrix is stored in the _matrix member field, along with \n\t* the upper and lower bounds of the timers and rates for continuous variables.\n\t* The upper and lower bounds are stored when the timer becomes enabled. The upper and\n\t* lower bounds of the rates are stored when the rate is assigned. The upper and lower \n\t* bounds are stored in the first row and first column of the _matrix member field.\n\t* The DBM occupies the rest of the array, that is, the sub-array formed by removing\n\t* the first column and first row.\n\t* For example, let t1 be a timer for a transition whose delay is between 2 and 3. Further\n\t* let c1 be a continuous variable with rate between 4 and 5. Then _matrix would look like\n\t* lb t0 c1 t1\n\t* ub x 0 5 3\n\t* t0 0 m m m\n\t* c1 -4 m m m\n\t* t1 -2 m m m\n\t* \n\t* with out the lb, ub, t0, t1, and c1.\n\t* \n\t* The x is does not represent anything and will most likely be zero. The upper and lower \n\t* bounds for the zero timer (which is always present) are always 0. The m's comprise \n\t* the DBM.\n\t* \n\t* For the most part, a timer or a continuous variable is referred to internally by an\n\t* LPNTransitionPair. An LPNTransitionPair combines the index of the transition (or\n\t* continuous variable) with the index of the LPN that the transition (or continuous \n\t* variables) is a member of. Both continuous variables and transitions can be referred\n\t* to by an LPNTransitionPair; however, it is better to use an LPNContinuousPair (which\n\t* is inherited from the LPNTransitionPair) to refer to continuous variables.\n\t* LPNContinuousPairs are used to distinguish continuous variables from transitions. They \n\t* also store the current rate of the continuous variable. \n\t* \n\t* The LPNTransitionPairs are stored in the _indexToTimerPair member field. The row/column\n\t* in the DBM for a transition is determined by the its position in this array. For example,\n\t* suppose a transition t has an LPNTransitionPair ltTranPair that is the third element of\n\t* the _indexToTimerPair. Then t will be the third column/row of the DBM.\n\t* \n\t* Continuous variables are handled slightly differently. The LPNContinuousPair for the \n\t* continuous variables with a non-zero rate are stored in the _indexToTimerPair just as \n\t* with the transitions. And just like with the transitions, the index in the DBM is\n\t* determined by the index of the LPNContinuousPair in the _indexToTimerPair. However,\n\t* rate zero continuous variables are stored in the _rateZeroContinuous member variable.\n\t* The _rateZerContinuous pairs an LPNContinuousPair with a VariableRangePair. The\n\t* VariableRangePair combines the variable with its upper and lower bound.\n\t* \n\t*/\n /* Representation invariant :\n\t* Zones are immutable.\n\t* Integer.MAX_VALUE is used to logically represent infinity.\n\t* The lb and ub values for a timer should be set when the timer is enabled.\n\t* A negative hash code indicates that the hash code has not been set.\n\t* The index of the timer in _indexToTimer is the index in the DBM and should contain\n\t* \tthe zeroth timer.\n\t* The array _indexToTimerPair should always be sorted.\n\t* The index of the LPN should match where it is in the _lpnList, that is, if lpn is\n\t* \tand LhpnFile object in _lpnList, then _lpnList[getLpnIndex()] == lpn.\n\t* The LPNTransitionPair in the _indexToTimer array should be an LPNContinuousPair\n\t* when it stores the index to a continuous variable. Testing that the index\n\t* is an LPNContinuousPair is used to determined if the indexing object points\n\t* to a continuous variable. Also the LPNContinuousPair keeps track of the current rate.\n\t* \n\t*/\n /*\n\t * Resource List :\n\t * TODO : Create a list reference where the algorithms can be found that this class\n\t * depends on.\n\t */\n public static final int INFINITY = Integer.MAX_VALUE;\n\n /* The lower and upper bounds of the times as well as the dbm. */\n private int[][] _matrix;\n\n /* Maps the index to the timer. The index is row/column of the DBM sub-matrix.\n\t * Logically the zero timer is given index -1.\n\t * */\n private LPNTransitionPair[] _indexToTimerPair;\n\n /* The hash code. */\n private int _hashCode;\n\n /* A lexicon between a transitions index and its name. */\n /* Set if a failure in the testSplit method has fired already. */\n /* Hack to pass a parameter to the equals method though a variable */\n /* Stores the continuous variables that have rate zero */\n DualHashMap _rateZeroContinuous;\n\n /* Records the largest zone that occurs. */\n public static int ZoneSize = 0;\n\n /* Write a log file */\n private static BufferedWriter _writeLogFile = null;\n\n /**\n * Returns the write log.\n * @return\n * \t\tThe _writeLogfile.\n */\n public static BufferedWriter get_writeLogFile() {\n return _writeLogFile;\n }\n\n /**\n * Sets the BufferedWriter.\n * @param writeLogFile\n */\n public static void set_writeLogFile(BufferedWriter writeLogFile) {\n _writeLogFile = writeLogFile;\n }\n\n /**\n * Sets the writeLogFile to null.\n */\n public static void reset_writeLogFile() {\n _writeLogFile = null;\n }\n\n private void checkZoneMaxSize() {\n if (dbmSize() > ZoneSize) {\n ZoneSize = dbmSize();\n }\n }\n\n private LPN[] _lpnList;\n\n /* \n\t * Turns on and off subsets for the zones.\n\t * True means subset will be considered.\n\t * False means subsets will not be considered.\n\t */\n private static boolean _subsetFlag = true;\n\n /* \n\t * Turns on and off supersets for zones.\n\t * True means that supersets will be considered.\n\t * False means that supersets will not be considered.\n\t */\n private static boolean _supersetFlag = true;\n\n /**\n * Gets the value of the subset flag.\n * @return\n * \t\tTrue if subsets are requested, false otherwise.\n */\n public static boolean getSubsetFlag() {\n return _subsetFlag;\n }\n\n /**\n * Sets the value of the subset flag.\n * @param useSubsets\n * \t\t\tThe value for the subset flag. Set to true if\n * \t\t\tsupersets are to be considered, false otherwise.\n */\n public static void setSubsetFlag(boolean useSubsets) {\n _subsetFlag = useSubsets;\n }\n\n /**\n * Gets the value of the superset flag.\n * @return\n * \t\tTrue if supersets are to be considered, false otherwise.\n */\n public static boolean getSupersetFlag() {\n return _supersetFlag;\n }\n\n /**\n * Sets the superset flag.\n * @param useSupersets\n * \t\tThe value of the superset flag. Set to true if\n * \t\tsupersets are to be considered, false otherwise.\n */\n public static void setSupersetFlag(boolean useSupersets) {\n _supersetFlag = useSupersets;\n }\n\n /**\n * Construct a zone that has the given timers.\n * @param timers\n * \t\t\t\tThe ith index of the array is the index of the timer. For example,\n * \t\t\t\t\tif timers = [1, 3, 5], then the zeroth row/column of the DBM is the\n * \t\t\t\t\ttimer of the transition with index 1, the first row/column of the\n * \t\t\t\t\tDBM is the timer of the transition with index 3, and the 2nd\n * \t\t\t\t\trow/column is the timer of the transition with index 5. Do not\n * \t\t\t\t\tinclude the zero timer.\n * @param matrix\n * \t\t\t\tThe DBM augmented with the lower and upper bounds of the delays for the\n * \t\t\t\t\ttransitions. For example, suppose a zone has timers [1, 3, 5] (as\n * \t\t\t\t\tdescribed in the timers parameters). The delay for transition 1 is\n * \t\t\t\t\t[1, 3], the delay for transition 3 is [2,5], and the delay for\n * \t\t\t\t\ttransition 5 is [4,6]. Also suppose the DBM is\n * \t\t\t\t\t t0 t1 t3 t5\n * \t\t\t\t\tt0 | 0, 3, 3, 3 |\n * \t\t\t\t\tt1 | 0, 0, 0, 0 |\n * \t\t\t\t\tt3 | 0, 0, 0, 0 |\n * \t\t\t\t\tt5 | 0, 0, 0, 0 |\n * \t\t\t\t\tThen the matrix that should be passed is\n * \t\t\t\t\t lb t0 t1 t3 t5\n * \t\t\t\t\tub| 0, 0, 3, 5, 6|\n * \t\t\t\t\tt0| 0, 0, 3, 3, 3|\n * \t\t\t\t\tt1|-1, 0, 0, 0, 0|\n * \t\t\t\t\tt3|-2, 0, 0, 0, 0|\n * \t\t\t\t\tt5|-4, 0, 0, 0, 0|\n * \t\t\t\t\tThe matrix should be non-null and the zero timer should always be the\n * \t\t\t\t\tfirst timer, even when there are no other timers.\n */\n public Zone(int[] timers, int[][] matrix) {\n // A negative number indicates that the hash code has not been set.\n _hashCode = -1;\n // Make a copy to reorder the timers.\n // Make a copy to reorder the timers.\n _indexToTimerPair = new LPNTransitionPair[timers.length];\n for (int i = 0; i < timers.length; i++) {\n _indexToTimerPair[i] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);\n }\n // Sorting the array.\n // Sorting the array.\n Arrays.sort(_indexToTimerPair);\n // // Add the zeroth timer.\n if (_indexToTimerPair[0].get_transitionIndex() != -1) {\n // Add the zeroth timer.\n LPNTransitionPair[] newIndexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newIndexToTimerPair[i + 1] = _indexToTimerPair[i];\n }\n _indexToTimerPair = newIndexToTimerPair;\n _indexToTimerPair[0] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, -1);\n }\n // throw new IllegalArgumentException(\"Timers must be non negative.\");\n // // Add a zero timer.\n // Map the old index of the timer to the new index of the timer.\n HashMap newIndex = new HashMap();\n // For the old index, find the new index.\n for (int i = 0; i < timers.length; i++) {\n // Since the zeroth timer is not included in the timers passed\n // to the index in the DBM is 1 more than the index of the timer\n // in the timers array.\n // LPNTransitionPair searchValue =\n LPNTransitionPair searchValue = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);\n newIndex.put(i + 1, Arrays.binarySearch(_indexToTimerPair, searchValue));\n }\n // Add the zero timer index.\n newIndex.put(0, 0);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Copy the DBM\n for (int i = 0; i < dbmSize(); i++) {\n for (int j = 0; j < dbmSize(); j++) {\n // Copy the passed in matrix to _matrix.\n setDbmEntry(newIndex.get(i), newIndex.get(j), matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]);\n // In the above, changed setDBMIndex to setdbm\n }\n }\n // Copy in the upper and lower bounds. The zero time does not have an upper or lower bound\n // so the index starts at i=1, the first non-zero timer.\n for (int i = 1; i < dbmSize(); i++) {\n setUpperBoundbydbmIndex(newIndex.get(i), matrix[0][dbmIndexToMatrixIndex(i)]);\n // Note : The method setLowerBoundbydbmIndex, takes the value of the lower bound\n // and the matrix stores the negative of the lower bound. So the matrix value\n // must be multiplied by -1.\n setLowerBoundbydbmIndex(newIndex.get(i), -1 * matrix[dbmIndexToMatrixIndex(i)][0]);\n }\n recononicalize();\n }\n\n /**\n * Initializes a zone according to the markings of state.\n * @param currentState\n * \t\t\tThe zone is initialized as if all enabled timers\n * \t\t\thave just been enabled.\n */\n public Zone(State initialState) {\n // Extract the associated LPN.\n LPN lpn = initialState.getLpn();\n int LPNIndex = lpn.getLpnIndex();\n if (_lpnList == null) {\n // If no LPN exists yet, create it and put lpn in it.\n _lpnList = new LPN[LPNIndex + 1];\n _lpnList[LPNIndex] = lpn;\n } else if (_lpnList.length <= LPNIndex) {\n // The list does not contain the lpn.\n LPN[] tmpList = _lpnList;\n _lpnList = new LPN[LPNIndex + 1];\n _lpnList[LPNIndex] = lpn;\n // Copy any that exist already.\n for (int i = 0; i < _lpnList.length; i++) {\n _lpnList[i] = tmpList[i];\n }\n } else if (_lpnList[LPNIndex] != lpn) {\n // This checks that the appropriate lpn is in the right spot.\n // If not (which gets you in this block), then this fixes it.\n _lpnList[LPNIndex] = lpn;\n }\n // Default value for the hash code indicating that the hash code has not\n // been set yet.\n _hashCode = -1;\n // Get the list of currently enabled Transitions by their index.\n boolean[] enabledTran = initialState.getTranVector();\n ArrayList enabledTransitionsArrayList = new ArrayList();\n LPNTransitionPair zeroPair = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, LPNTransitionPair.ZERO_TIMER);\n // Add the zero timer first.\n enabledTransitionsArrayList.add(zeroPair);\n // The index of the boolean value corresponds to the index of the Transition.\n for (int i = 0; i < enabledTran.length; i++) {\n if (enabledTran[i]) {\n enabledTransitionsArrayList.add(new LPNTransitionPair(LPNIndex, i));\n }\n }\n _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);\n _matrix = new int[matrixSize()][matrixSize()];\n for (int i = 1; i < dbmSize(); i++) {\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = lpn.getTransition(_indexToTimerPair[i].get_transitionIndex()).getLabel();\n ExprTree delay = lpn.getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = lpn.getAllVarsWithValuesAsString(initialState.getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n ExprTree lowerDelay = delay.getLeftChild();\n ExprTree upperDelay = delay.getRightChild();\n lower = (int) lowerDelay.evaluateExpr(varValues);\n upper = (int) upperDelay.evaluateExpr(varValues);\n } else {\n lower = (int) delay.evaluateExpr(varValues);\n upper = lower;\n }\n setLowerBoundbydbmIndex(i, lower);\n setUpperBoundbydbmIndex(i, upper);\n }\n // Advance the time and tighten the bounds.\n advance();\n recononicalize();\n checkZoneMaxSize();\n }\n\n /**\n * Creates a Zone based on the local states.\n * @param localStates\n * \t\t\tThe current state (or initial) of the LPNs.\n */\n public Zone(State[] localStates) {\n // Open the log file.\n if (_writeLogFile == null && Options.get_TimingLogfile() != null) {\n try {\n _writeLogFile = new BufferedWriter(new FileWriter(Options.get_TimingLogfile()));\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n }\n }\n // Initialize hash code to -1 (indicating nothing cached).\n _hashCode = -1;\n // Initialize the LPN list.\n initialize_lpnList(localStates);\n // Get the enabled transitions. This initializes the _indexTotimerPair\n // which stores the relevant information.\n // This method will also initialize the _rateZeroContinuous\n initialize_indexToTimerPair(localStates);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Set the lower bound/ upper bounds of the timers and the rates.\n initializeLowerUpperBounds(getAllNames(), localStates);\n // Initialize the row and column entries for the continuous variables.\n initializeRowColumnContVar();\n // Create a previous zone to the initial zone for the sake of warping.\n Zone tmpZone = beforeInitialZone();\n dbmWarp(tmpZone);\n recononicalize();\n // Advance Time\n advance(localStates);\n // Re-canonicalize\n recononicalize();\n // Check the size of the DBM.\n checkZoneMaxSize();\n }\n\n /**\n * Creates a Zone based on the local states.\n * @param localStates\n * \t\t\tThe current state (or initial) of the LPNs.\n */\n public Zone(State[] localStates, boolean init) {\n // Extract the local states.\n // Initialize hash code to -1 (indicating nothing cached).\n _hashCode = -1;\n // Initialize the LPN list.\n initialize_lpnList(localStates);\n // Get the enabled transitions. This initializes the _indexTotimerPair\n // which stores the relevant information.\n // This method will also initialize the _rateZeroContinuous\n initialize_indexToTimerPair(localStates);\n // Initialize the matrix.\n _matrix = new int[matrixSize()][matrixSize()];\n // Set the lower bound/ upper bounds of the timers and the rates.\n initializeLowerUpperBounds(getAllNames(), localStates);\n // Initialize the row and column entries for the continuous variables.\n initializeRowColumnContVar();\n if (init) {\n return;\n }\n // Advance Time\n advance(localStates);\n // Re-canonicalize\n recononicalize();\n // Check the size of the DBM.\n checkZoneMaxSize();\n }\n\n // * Sets ups a zone containing continuous variables only.\n // * @param continuousValues\n // * \t\tThe values to populate the zone with.\n // // Copy the LPNContinuousPairs over\n // int count = 0; // The position in the _indexToTimerPair for the next value.\n /**\n * Gives the names of all the transitions and continuous variables that\n * are represented by the zone.\n * @return\n * \t\tThe names of the transitions and continuous variables that are\n * \t\trepresented by the zone.\n */\n public String[] getAllNames() {\n // transitionNames[0] = \"The zero timer.\";\n // Get the continuous variable names.\n String[] contVar = getContVarNames();\n // Get the transition names.\n String[] trans = getTranNames();\n // Create an array large enough for all the names.\n String[] names = new String[contVar.length + trans.length + 1];\n // Add the zero timer.\n names[0] = \"The zero timer.\";\n // Add the continuous variables.\n for (int i = 0; i < contVar.length; i++) {\n names[i + 1] = contVar[i];\n }\n // Add the timers.\n for (int i = 0; i < trans.length; i++) {\n // Already the zero timer has been added and the elements of contVar.\n // That's a total of 'contVar.length + 1' elements. The last index was\n // thus 'contVar.length' So the first index to add to is\n names[1 + contVar.length + i] = trans[i];\n }\n return names;\n }\n\n /**\n * Get the names of the continuous variables that this zone uses.\n * @return\n * \t\tThe names of the continuous variables that are part of this zone.\n */\n public String[] getContVarNames() {\n // List for accumulating the names.\n ArrayList contNames = new ArrayList();\n // Find the pairs that represent the continuous variables. Loop starts at\n // i=1 since the i=0 is the zero timer.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // If the isTimer value is false, then this pair represents a continuous\n // If pair is LPNContinuousPair.\n if (ltPair instanceof LPNContinuousPair) {\n // Get the LPN that this pairing references and find the name of\n // the continuous variable whose index is given by this pairing.\n contNames.add(_lpnList[ltPair.get_lpnIndex()].getContVarName(ltPair.get_transitionIndex()));\n }\n }\n return contNames.toArray(new String[0]);\n }\n\n /**\n * Gets the names of the transitions that are associated with the timers in the\n * zone. Does not return the zero timer.\n * @return\n * \t\tThe names of the transitions whose timers are in the zone except the zero\n * \t\ttimer.\n */\n public String[] getTranNames() {\n // List for accumulating the names.\n ArrayList transitionNames = new ArrayList();\n // Find the pairs that represent the transition timers.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // If the isTimer value is true, then this pair represents a timer.\n // If this is an LPNTransitionPair and not an LPNContinuousPair\n if (!(ltPair instanceof LPNContinuousPair)) {\n // Get the LPN that this pairing references and find the name of the\n // transition whose index is given by this pairing.\n transitionNames.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()).getLabel());\n }\n }\n return transitionNames.toArray(new String[0]);\n }\n\n /**\n * Initializes the _lpnList using information from the local states.\n * @param localStates\n * \t\tThe local states.\n * @return\n * \t\tThe enabled transitions.\n */\n private void initialize_lpnList(State[] localStates) {\n // Create the LPN list.\n _lpnList = new LPN[localStates.length];\n // Get the LPNs.\n for (int i = 0; i < localStates.length; i++) {\n _lpnList[i] = localStates[i].getLpn();\n }\n }\n\n /**\n * Initializes the _indexToTimerPair from the local states. This includes\n * adding the zero timer, the continuous variables and the set of\n * enabled timers.\n * @param localStates\n * \t\tThe local states.\n * @return\n * \t\tThe names of the transitions stored in the _indexToTimerPair (in the same order).\n */\n private void initialize_indexToTimerPair(State[] localStates) {\n /*\n\t\t * The populating of the _indexToTimerPair is done in three stages.\n\t\t * The first is to add the zero timer which is at the beginning of the zone.\n\t\t * The second is to add the continuous variables. And the third is to add\n\t\t * the other timers. Since the continuous variables are added before the\n\t\t * timers and the variables and timers are added in the order of the LPNs,\n\t\t * the elements in an accumulating list (enabledTransitionsArrayList) are\n\t\t * already in order up to the elements added for a particular LPN. Thus the\n\t\t * only sorting that needs to take place is the sorting for a particular LPN.\n\t\t * Correspondingly, elements are first found for an LPN and sort, then added\n\t\t * to the main list.\n\t\t */\n // This method will also initialize the _rateZeroContinuous\n _rateZeroContinuous = new DualHashMap();\n // This list accumulates the transition pairs (ie timers) and the continuous\n ArrayList enabledTransitionsArrayList = new ArrayList();\n // Put in the zero timer.\n // enabledTransitionsArrayList\n enabledTransitionsArrayList.add(new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, LPNTransitionPair.ZERO_TIMER));\n // Get the continuous variables.\n for (int i = 0; i < localStates.length; i++) {\n // Accumulates the changing continuous variables for a single LPN.\n ArrayList singleLPN = new ArrayList();\n // Get the associated LPN.\n LPN lpn = localStates[i].getLpn();\n // Get the continuous variables for this LPN.\n String[] continuousVariables = lpn.getContVars();\n // Get the variable, index map.\n DualHashMap variableIndex = lpn.getContinuousIndexMap();\n // Find which have a nonzero rate.\n for (int j = 0; j < continuousVariables.length; j++) {\n // Get the Variables with this name.\n Variable contVar = lpn.getVariable(continuousVariables[j]);\n // Get the rate.\n IntervalPair rate = parseRate(contVar.getInitRate());\n // Get the LPN index for the variable\n int lpnIndex = lpn.getLpnIndex();\n // Get the index as a variable for the LPN.\n int contVariableIndex = variableIndex.get(continuousVariables[j]);\n LPNContinuousPair newPair = new LPNContinuousPair(lpnIndex, contVariableIndex, rate.getSmallestRate());\n // If the rate is non-zero, then the variables needs to be tracked\n // by matrix part of the Zone.\n if (newPair.getCurrentRate() != 0) {\n // Temporary exception guaranteeing only unit rates.\n // \"only supports positive unit rates. The variable \" + contVar +\n // \" has a rate of \" + rate);\n // // Get the LPN index for the variable\n // // Get the index as a variable for the LPN. This index matches\n // // the index in the vector stored by platu.State.\n // The continuous variable reference.\n singleLPN.add(newPair);\n } else {\n // If the rate is zero, then the Zone keeps track of this variable\n // in a list.\n _rateZeroContinuous.insert(new LPNContAndRate(newPair, rate), new VariableRangePair(contVar, parseRate(contVar.getInitValue())));\n }\n }\n // Sort the list.\n Collections.sort(singleLPN);\n // Add the list to the total accumulating list.\n for (int j = 0; j < singleLPN.size(); j++) {\n enabledTransitionsArrayList.add(singleLPN.get(j));\n }\n }\n // Get the transitions.\n for (int i = 0; i < localStates.length; i++) {\n // Extract the enabled transition vector.\n boolean[] enabledTran = localStates[i].getTranVector();\n // Accumulates the transition pairs for one LPN.\n ArrayList singleLPN = new ArrayList();\n // The index of the boolean value corresponds to the index of the Transition.\n for (int j = 0; j < enabledTran.length; j++) {\n if (enabledTran[j]) {\n // Add the transition pair.\n singleLPN.add(new LPNTransitionPair(i, j));\n }\n }\n // Sort the transitions for the current LPN.\n Collections.sort(singleLPN);\n // Add the collection to the enabledTransitionsArrayList\n for (int j = 0; j < singleLPN.size(); j++) {\n enabledTransitionsArrayList.add(singleLPN.get(j));\n }\n }\n // Extract out the array portion of the enabledTransitionsArrayList.\n _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);\n }\n\n /**\n * Sets the lower and upper bounds for the transitions and continuous variables.\n * @param varNames\n * \t\t\tThe names of the transitions in _indexToTimerPair.\n */\n private void initializeLowerUpperBounds(String[] varNames, State[] localStates) {\n // Traverse the entire length of the DBM sub-matrix except the zero row/column.\n // This is the same length as the _indexToTimerPair.length-1. The DBM is used to\n // match the idea of setting the value for each row.\n for (int i = 1; i < dbmSize(); i++) {\n // Get the current LPN and transition pairing.\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n IntervalPair range;\n if (ltPair instanceof LPNContinuousPair) {\n // If the pairing represents a continuous variable, then the\n // upper and lower bound are the initial value or infinity depending\n // on whether the initial rate is positive or negative.\n // If the value is a constant, then assign the upper and lower bounds\n // to be constant. If the value is a range then assign the upper and\n // lower bounds to be a range.\n Variable v = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());\n String rate = v.getInitRate();\n // Parse the rate. Should be in the form of [x,y] where x\n // and y are integers.\n range = parseRate(rate);\n // Set the upper and lower bound (in the matrix) for the\n // continuous variables.\n String contValue = v.getInitValue();\n IntervalPair bound = parseRate(contValue);\n // Set upper bound (DBM entry (0, x) where x is the index of the variable v).\n setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, bound.get_UpperBound());\n // Set lower bound (DBM entry (x, 0) where x is the index of the variable v).\n setDbmEntryByPair(ltPair, LPNTransitionPair.ZERO_TIMER_PAIR, -1 * bound.get_LowerBound());\n } else {\n // Get the expression tree.\n ExprTree delay = _lpnList[ltPair.get_lpnIndex()].getDelayTree(varNames[i]);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[ltPair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[ltPair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n // Passing the zone as null since it should not be needed.\n // // The lower and upper bounds should evaluate to a single\n // throw new IllegalStateException(\"When evaulating the delay, \" +\n // \"the lower or the upper bound evaluated to a range \" +\n // \"instead of a single value.\");\n if (delay != null) {\n range = delay.evaluateExprBound(varValues, this, null);\n } else {\n range = new IntervalPair(0, 0);\n }\n }\n setLowerBoundbydbmIndex(i, range.get_LowerBound());\n setUpperBoundbydbmIndex(i, range.get_UpperBound());\n }\n }\n\n /**\n * Initialize the rows and columns for the continuous variables.\n */\n private void initializeRowColumnContVar() {\n /*\n\t\t * TODO : Describe the idea behind the following algorithm.\n\t\t */\n // // Note: row is indexing the row of the DBM matrix.\n // // If we reached the timers, stop.\n // // Note: col is indexing the column of the DBM matrix.\n // // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since\n // // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower\n // // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);\n // The only entries that do not need to be checked are the ones where both variables\n // represent timers.\n for (int row = 2; row < _indexToTimerPair.length; row++) {\n // Note: row is indexing the row of the DBM matrix.\n LPNTransitionPair ltRowPair = _indexToTimerPair[row];\n // // If we reached the timers, stop.\n for (int col = 1; col < row; col++) {\n // Note: col is indexing the column of the DBM matrix.\n LPNTransitionPair ltColPair = _indexToTimerPair[col];\n // If we've reached the part of the zone involving only timers, then break out\n if (!(ltRowPair instanceof LPNContinuousPair) && !(ltColPair instanceof LPNContinuousPair)) {\n break;\n }\n // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since\n // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower\n // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);\n int rowCol = getDbmEntry(row, 0) + getDbmEntry(0, col);\n int colRow = getDbmEntry(col, 0) + getDbmEntry(0, row);\n setDbmEntry(row, col, rowCol);\n setDbmEntry(col, row, colRow);\n }\n }\n }\n\n /**\n * Zero argument constructor for use in methods that create Zones where the members\n * variables will be set by the method.\n */\n private Zone() {\n _matrix = new int[0][0];\n _indexToTimerPair = new LPNTransitionPair[0];\n _hashCode = -1;\n _lpnList = new LPN[0];\n _rateZeroContinuous = new DualHashMap();\n }\n\n /**\n * Gets the upper bound of a Transition from the zone.\n * @param t\n * \t\tThe transition whose upper bound is wanted.\n * @return\n * \t\tThe upper bound of Transition t.\n */\n public int getUpperBoundbyTransition(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n // LPNTransitionPair ltPair =\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return getUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Returns the upper bound of the continuous variable.\n * @param var\n * \t\tThe variable of interest.\n * @return\n * \t\tThe (0,var) entry of the zone, that is the maximum as recored by\n * \t\tthe zone.\n */\n public int getUpperBoundbyContinuousVariable(String contVar, LPN lpn) {\n // // Determine whether the variable is in the zone or rate zero.\n // // If a RangeAndPairing is returned, then get the information from here.\n // // If indexAndRange is null, then try to get the value from the zone.\n // throw new IllegalStateException(\"Atempted to find the upper bound for \"\n // + \"a non-rate zero continuous variable that was not found in the \"\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note : setting the rate is not necessary here since this is only\n // being used as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range().get_UpperBound();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the lower bound for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n return getDbmEntry(0, i);\n }\n\n public int getUpperBoundForRate(LPNTransitionPair contVar) {\n // Check if the contVar is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (i > 0) {\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n // Grab the current rate from the LPNContinuousPair.\n return ((LPNContinuousPair) _indexToTimerPair[i]).getCurrentRate();\n }\n // Assume the rate is zero. This covers the case if conVar\n // is in the rate zero as well as if its not in the state at all.\n return 0;\n }\n\n /**\n * Get the value of the upper bound for the delay. If the index refers\n * to a timer, otherwise get the upper bound for the continuous\n * variables rate.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @return\n * \t\t\tThe upper bound on the transitions delay.\n */\n public int getUpperBoundbydbmIndex(int index) {\n return _matrix[0][dbmIndexToMatrixIndex(index)];\n }\n\n public int getUpperBound(int index) {\n return _matrix[0][dbmIndexToMatrixIndex(index)];\n }\n\n @Override\n public int getUpperBoundTrue(int index) {\n return _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(index)];\n }\n\n public int getUnwarpedUpperBound(LPNContinuousPair lcpair) {\n // Get the index.\n int index = Arrays.binarySearch(_indexToTimerPair, lcpair);\n int rate = ((LPNContinuousPair) _indexToTimerPair[index]).getCurrentRate();\n int warpValue = getUpperBoundTrue(index);\n return warpValue * rate;\n }\n\n public int getLowerBound(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][0];\n }\n\n @Override\n public int getLowerBoundTrue(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][dbmIndexToMatrixIndex(0)];\n }\n\n /**\n * Set the value of the upper bound for the delay.\n * @param t\n * \t\t\tThe transition whose upper bound is being set.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n public void setUpperBoundbyTransition(Transition t, int value) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the upper bound for the delay.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n public void setUpperBoundbydbmIndex(int index, int value) {\n _matrix[0][dbmIndexToMatrixIndex(index)] = value;\n }\n\n /**\n * Sets the upper bound for a transition described by an LPNTransitionPair.\n * @param ltPair\n * \t\t\tThe index of the transition and the index of the associated LPN for\n * \t\t\tthe timer to set the upper bound.\n * @param value\n * \t\t\tThe value for setting the upper bound.\n */\n private void setUpperBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value) {\n setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Gets the lower bound of a Transition from the zone.\n * @param t\n * \t\tThe transition whose upper bound is wanted.\n * @return\n * \t\tThe lower bound of Transition t.\n */\n @Override\n public int getLowerBoundbyTransition(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return getLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Returns the lower bound of the continuous variable.\n * @param var\n * \t\tThe variable of interest.\n * @return\n * \t\tThe (0,var) entry of the zone, that is the minimum as recored by\n * \t\tthe zone.\n */\n public int getLowerBoundbyContinuousVariable(String contVar, LPN lpn) {\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note: Setting the rate is not necessary since this is only being used\n // as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range().get_LowerBound();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the lower bound for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n return getDbmEntry(i, 0);\n }\n\n /**\n * Get the value of the lower bound for the delay if the index refers\n * to a timer, otherwise get the lower bound for the continuous variables\n * rate.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @return\n * \t\t\tThe value of the lower bound.\n */\n public int getLowerBoundbydbmIndex(int index) {\n return _matrix[dbmIndexToMatrixIndex(index)][0];\n }\n\n public int getLowerBoundForRate(LPNTransitionPair contVar) {\n // Check if the contVar is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (i > 0) {\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n return getLowerBoundbydbmIndex(contVar.get_transitionIndex());\n }\n // Assume the rate is zero. This covers the case if conVar\n // is in the rate zero as well as if its not in the state at all.\n return 0;\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param t\n * \t\t\tThe transition whose lower bound is being set.\n * @param value\n * \t\t\tThe value of the lower bound.\n */\n public void setLowerBoundbyTransition(Transition t, int value) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param t\n * \t\t\tThe transition whose upper bound is being set.\n * @param value\n * \t\t\tThe value of the upper bound.\n */\n private void setLowerBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value) {\n setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);\n }\n\n /**\n * Set the value of the lower bound for the delay.\n * @param index\n * \t\t\tThe timer's row/column of the DBM matrix.\n * @param value\n * \t\t\tThe value of the lower bound.\n */\n public void setLowerBoundbydbmIndex(int index, int value) {\n _matrix[dbmIndexToMatrixIndex(index)][0] = -1 * value;\n }\n\n /**\n * Give the upper and lower bounds for a continuous variable.\n * @param contVar\n * \t\tThe variable of interest.\n * @return\n * \t\tThe upper and lower bounds according to the Zone.\n */\n @Override\n public IntervalPair getContinuousBounds(String contVar, LPN lpn) {\n /*\n\t\t * Need to determine whether this is suppose to be a rate zero variable or a non-zero \n\t\t * rate variable. One method is to check the rate of the passed variable. The other is\n\t\t * to just check if the variable is present in either place.\n\t\t */\n // Extract the necessary indecies.\n int lpnIndex = lpn.getLpnIndex();\n // Get the index of the continuous variable.\n DualHashMap variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note: setting the current rate is not necessary here since the\n // LPNContinuousPair is only being used as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(new LPNContAndRate(index, new IntervalPair(0, 0)));\n // If Pairing is not null, the variable was found and return the result.\n if (pairing != null) {\n return pairing.get_range();\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the bounds for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n // Else find the upper and lower bounds.\n int lower = (-1) * getDbmEntry(i, 0);\n int upper = getDbmEntry(0, i);\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the range for the continuous variable. Values come back not\n * warped.\n * @param ltContPair\n * \t\tThe index of the variable of interest.\n * @return\n * \t\tThe range of the continuous variable described by ltContPair.\n */\n @Override\n public IntervalPair getContinuousBounds(LPNContinuousPair ltContPair) {\n // First check in the zone.\n int variableIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);\n if (variableIndex < 0) {\n // The variable was not found in the zone. Check to see if its\n // in the rate-zero variables. Technically I will return whatever\n // is in the _rateZeroConintuous, null or not.\n // First get an object to reference into the _rateZeroContinuous\n LPNContAndRate lcr = new LPNContAndRate(ltContPair, new IntervalPair(0, 0));\n return _rateZeroContinuous.get(lcr).get_range();\n }\n // The variable was found in the zone. Yay.\n int lower = (-1) * getDbmEntry(variableIndex, 0) * getCurrentRate(ltContPair);\n int upper = getDbmEntry(0, variableIndex) * getCurrentRate(ltContPair);\n // If the current rate is negative the upper and lower bounds\n // need to be switched.\n if (getCurrentRate(ltContPair) < 0) {\n int tmp = lower;\n lower = upper;\n upper = tmp;\n }\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the range of the rate associated with a continuous variable.\n * @param ltContPair\n * \t\tThe index of the continuous variable.\n * @return\n * \t\tThe range of rates associated with the continuous variable indexed\n * \t\tby ltContPair.\n */\n @Override\n public IntervalPair getRateBounds(LPNTransitionPair ltPair) {\n int upper;\n int lower;\n // Check if the ltContpair is in the zone.\n int i = Arrays.binarySearch(_indexToTimerPair, ltPair);\n if (i < 0) {\n // Then the variable is in the rate zero continuous\n // variables so get the range of rates from there.\n // Create an object to reference into the rate zero.\n LPNContAndRate lcr = new LPNContAndRate((LPNContinuousPair) ltPair, new IntervalPair(0, 0));\n // Get the old version of lcr from the rate zero since\n // that contains the rate. This is quite a hack.\n VariableRangePair vrp = _rateZeroContinuous.get(lcr);\n lcr = _rateZeroContinuous.getKey(vrp);\n return lcr.get_rateInterval();\n }\n upper = getUpperBoundbydbmIndex(i);\n lower = -1 * getLowerBoundbydbmIndex(i);\n // The continuous variable is in the zone.\n // The upper and lower bounds are stored in the same\n // place as the delays, so the same method of\n // retrieval will work.\n return new IntervalPair(lower, upper);\n }\n\n /**\n * Gets the rate reset value.\n * @param ltPair\n * @return\n */\n @Override\n public int rateResetValue(LPNTransitionPair ltPair) {\n IntervalPair rateBounds = getRateBounds(ltPair);\n int upper = rateBounds.get_UpperBound();\n int lower = rateBounds.get_LowerBound();\n // // Check if the ltContpair is in the zone.\n // // Assume the rate is zero. This covers the case if conVar\n // // is in the rate zero as well as if its not in the state at all.\n // If zero is a possible rate, then it is the rate to set to.\n // // If zero is the only possible rate, return that.\n // // When zero is in the range and there is a positive rate, return the\n // // When the upper bound is zero, return the negative rate.\n // // When zero is not present, use the smallest rate in absolute value.\n /*\n\t\t * Suppose the range of rates is [a,b]. If a>=0, we set the rate to b.\n\t\t * If b<=0, we set the rate to a. Otherwise, a<0=0, we set the rate to b.\n\t\t * If b<=0, we set the rate to a. Otherwise, a<0 variableIndecies = lpn.getContinuousIndexMap();\n int contIndex = variableIndecies.get(contVar);\n // Package the indecies with false indicating not a timer.\n // Note : Setting the rate is not necessary since this only being used\n // as an index.\n LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);\n // Search for the continuous variable in the rate zero variables.\n VariableRangePair pairing = _rateZeroContinuous.get(index);\n // If Pairing is not null, the variable was found and make the new assignment.\n if (pairing != null) {\n pairing.set_range(range);\n return;\n }\n // If Pairing was null, the variable was not found. Search for the variable\n // in the zone portion.\n int i = Arrays.binarySearch(_indexToTimerPair, index);\n // If i < 0, the search was unsuccessful, so scream.\n if (i < 0) {\n throw new IllegalArgumentException(\"Atempted to find the bounds for \" + \"a non-rate zero continuous variable that was not found in the \" + \"zone.\");\n }\n // Else find the upper and lower bounds.\n setDbmEntry(i, 0, (-1) * range.get_LowerBound());\n setDbmEntry(0, i, range.get_UpperBound());\n }\n\n /**\n * Converts the index of the DBM to the index of _matrix.\n * @param i\n * \t\t\tThe row/column index of the DBM.\n * @return\n * \t\t\tThe row/column index of _matrix.\n */\n private static int dbmIndexToMatrixIndex(int i) {\n return i + 1;\n }\n\n /**\n * Retrieves an entry of the DBM using the DBM's addressing.\n * @param i\n * \t\t\tThe row of the DBM.\n * @param j\n * \t\t\tThe column of the DBM.\n * @return\n * \t\t\tThe value of the (i, j) element of the DBM.\n */\n @Override\n public int getDbmEntry(int i, int j) {\n return _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)];\n }\n\n /**\n * Retrieves an entry of the DBM using LPNTransitionPair indecies.\n * @param iPair\n * \t\tThe LPNTransitionPair for the ith entry.\n * @param jPair\n * \t\tThe LPNTransitionPair for the jth entry.\n * @return\n * \t\tThe value of the (i,j) element of the DBM where i corresponds to the row\n * \t\tfor the variable iPair and j corresponds to the row for the variable jPair.\n */\n @Override\n public int getDbmEntryByPair(LPNTransitionPair iPair, LPNTransitionPair jPair) {\n int iIndex = Arrays.binarySearch(_indexToTimerPair, iPair);\n int jIndex = Arrays.binarySearch(_indexToTimerPair, jPair);\n return getDbmEntry(iIndex, jIndex);\n }\n\n /**\n * Sets an entry of the DBM using the DBM's addressing.\n * @param i\n * \t\t\tThe row of the DBM.\n * @param j\n * \t\t\tThe column of the DBM.\n * @param value\n * \t\t\tThe new value for the entry.\n */\n private void setDbmEntry(int i, int j, int value) {\n _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)] = value;\n }\n\n /**\n * Sets the entry in the DBM using the LPNTransitionPair indexing.\n * @param row\n * \t\t\tThe LPNTransitionPair for the row.\n * @param col\n * \t\t\tThe LPNTransitionPair for the column.\n * @param value\n * \t\t\tThe value to set the entry to.\n */\n private void setDbmEntryByPair(LPNTransitionPair row, LPNTransitionPair col, int value) {\n // The row index.\n int i = timerIndexToDBMIndex(row);\n // The column index.\n int j = timerIndexToDBMIndex(col);\n setDbmEntry(i, j, value);\n }\n\n /**\n * Returns the index of the the transition in the DBM given a LPNTransitionPair pairing\n * the transition index and associated LPN index.\n * @param ltPair\n * \t\tThe pairing comprising the index of the transition and the index of the associated\n * \t\tLPN.\n * @return\n * \t\tThe row/column of the DBM associated with the ltPair.\n */\n @Override\n public int timerIndexToDBMIndex(LPNTransitionPair ltPair) {\n return Arrays.binarySearch(_indexToTimerPair, ltPair);\n }\n\n /**\n * The matrix labeled with 'ti' where i is the transition index associated with the timer.\n */\n @Override\n public String toString() {\n // TODO : Fix the handling of continuous variables in the\n String result = \"Timer and delay or continuous and ranges.\\n\";\n int count = 0;\n // Print the timers.\n for (int i = 1; i < _indexToTimerPair.length; i++, count++) {\n if (_lpnList.length == 0) {\n // If no LPN's are associated with this Zone, use the index of the timer.\n result += \" t\" + _indexToTimerPair[i].get_transitionIndex() + \" : \";\n } else {\n String name;\n // If the current LPNTransitionPair is a timer, get the name\n // from the transitions.\n // If the current timer is an LPNTransitionPair and not an LPNContinuousPair\n if (!(_indexToTimerPair[i] instanceof LPNContinuousPair)) {\n // Get the name of the transition.\n Transition tran = _lpnList[_indexToTimerPair[i].get_lpnIndex()].getTransition(_indexToTimerPair[i].get_transitionIndex());\n name = tran.getLabel();\n } else {\n // If the current LPNTransitionPair is not a timer, get the\n // name as a continuous variable.\n Variable var = _lpnList[_indexToTimerPair[i].get_lpnIndex()].getContVar(_indexToTimerPair[i].get_transitionIndex());\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];\n int lowerBound = -1 * getDbmEntry(i, 0) * lcPair.getCurrentRate();\n int upperBound = getDbmEntry(0, i) * lcPair.getCurrentRate();\n // If the rate is negative, the bounds are switched\n // in the zone.\n if (lcPair.getCurrentRate() < 0) {\n int tmp = lowerBound;\n lowerBound = upperBound;\n upperBound = tmp;\n }\n name = var.getName() + \":[\" + lowerBound + \",\" + upperBound + \"]\\n\" + \" Current Rate: \" + lcPair.getCurrentRate() + \" \" + \"rate:\";\n }\n result += \" \" + name + \":\";\n }\n result += \"[ \" + -1 * getLowerBoundbydbmIndex(i) + \", \" + getUpperBoundbydbmIndex(i) + \" ]\";\n if (count > 9) {\n result += \"\\n\";\n count = 0;\n }\n }\n if (!_rateZeroContinuous.isEmpty()) {\n result += \"\\nRate Zero Continuous : \\n\";\n for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()) {\n result += \"\" + _rateZeroContinuous.get(lcrPair) + \"Rate: \" + lcrPair.get_rateInterval();\n }\n }\n result += \"\\nDBM\\n\";\n // Print the DBM.\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n result += \"| \" + String.format(\"%3d\", getDbmEntry(i, 0));\n for (int j = 1; j < _indexToTimerPair.length; j++) {\n result += \", \" + String.format(\"%3d\", getDbmEntry(i, j));\n }\n result += \" |\\n\";\n }\n return result;\n }\n\n /**\n * Tests for equality. Overrides inherited equals method.\n * @return True if o is equal to this object, false otherwise.\n */\n @Override\n public boolean equals(Object o) {\n // Check if the reference is null.\n if (o == null) {\n return false;\n }\n // Check that the type is correct.\n if (!(o instanceof Zone)) {\n return false;\n }\n // Check for equality using the Zone equality.\n return equals((Zone) o);\n }\n\n /**\n * Tests for equality.\n * @param\n * \t\tThe Zone to compare.\n * @return\n * \t\tTrue if the zones are non-null and equal, false otherwise.\n */\n public boolean equals(Zone otherZone) {\n // Check if the reference is null first.\n if (otherZone == null) {\n return false;\n }\n // Check for reference equality.\n if (this == otherZone) {\n return true;\n }\n // If the hash codes are different, then the objects are not equal.\n if (this.hashCode() != otherZone.hashCode()) {\n return false;\n }\n // Check if the they have the same number of timers.\n if (this._indexToTimerPair.length != otherZone._indexToTimerPair.length) {\n return false;\n }\n // Check if the timers are the same.\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n if (!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))) {\n return false;\n }\n }\n // Check if the matrix is the same\n for (int i = 0; i < _matrix.length; i++) {\n for (int j = 0; j < _matrix[0].length; j++) {\n if (!(this._matrix[i][j] == otherZone._matrix[i][j])) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Determines if this zone is a subset of Zone otherZone.\n * @param otherZone\n * \t\tThe zone to compare against.\n * @return\n * \t\tTrue if this is a subset of other; false otherwise.\n */\n @Override\n public boolean subset(Equivalence otherEquiv) {\n Zone otherZone = (Zone) otherEquiv;\n // Check if the reference is null first.\n if (otherZone == null) {\n return false;\n }\n // Check for reference equality.\n if (this == otherZone) {\n return true;\n }\n // Check if the the same number of timers are present.\n if (this._indexToTimerPair.length != otherZone._indexToTimerPair.length) {\n return false;\n }\n // Check if the transitions are the same.\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n if (!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))) {\n return false;\n }\n }\n // Check if the entries of this Zone are less than or equal to the entries\n // of the other Zone.\n for (int i = 0; i < _matrix.length; i++) {\n for (int j = 0; j < _matrix[0].length; j++) {\n if (!(this._matrix[i][j] <= otherZone._matrix[i][j])) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Determines if this zone is a superset of Zone otherZone.\n * @param otherZone\n * \t\tThe zone to compare against.\n * @return\n * \t\tTrue if this is a subset of other; false otherwise. More specifically it\n * \t\tgives the result of otherZone.subset(this). Thus it agrees with the subset method.\n */\n @Override\n public boolean superset(Equivalence otherZone) {\n return otherZone.subset(this);\n }\n\n /**\n * Overrides the hashCode.\n */\n @Override\n public int hashCode() {\n // Check if the hash code has been set.\n if (_hashCode < 0) {\n _hashCode = createHashCode();\n }\n return _hashCode;\n }\n\n /**\n * Creates a hash code for a Zone object.\n * @return\n * \t\tThe hash code.\n */\n private int createHashCode() {\n int newHashCode = Arrays.hashCode(_indexToTimerPair);\n for (int i = 0; i < _matrix.length; i++) {\n newHashCode ^= Arrays.hashCode(_matrix[i]);\n }\n return Math.abs(newHashCode);\n }\n\n /**\n * The size of the DBM sub matrix. This is calculated using the size of _indexToTimer.\n * @return\n * \t\t\tThe size of the DBM.\n */\n private int dbmSize() {\n return _indexToTimerPair.length;\n }\n\n /**\n * The size of the matrix.\n * @return\n * \t\t\tThe size of the matrix. This is calculated using the size of _indexToTimer.\n */\n private int matrixSize() {\n return _indexToTimerPair.length + 1;\n }\n\n /**\n * Performs the Floyd's least pairs algorithm to reduce the DBM.\n */\n @Override\n public void recononicalize() {\n for (int k = 0; k < dbmSize(); k++) {\n for (int i = 0; i < dbmSize(); i++) {\n for (int j = 0; j < dbmSize(); j++) {\n if (getDbmEntry(i, k) != INFINITY && getDbmEntry(k, j) != INFINITY && getDbmEntry(i, j) > getDbmEntry(i, k) + getDbmEntry(k, j)) {\n setDbmEntry(i, j, getDbmEntry(i, k) + getDbmEntry(k, j));\n }\n if ((i == j) && getDbmEntry(i, j) != 0) {\n throw new DiagonalNonZeroException(\"Entry (\" + i + \", \" + j + \")\" + \" became \" + getDbmEntry(i, j) + \".\");\n }\n }\n }\n }\n }\n\n /**\n * Determines if a timer associated with a given transitions has reached its lower bound.\n * @param t\n * \t\t\tThe transition to consider.\n * @return\n * \t\t\tTrue if the timer has reached its lower bound, false otherwise.\n */\n public boolean exceedsLowerBoundbyTransitionIndex(Transition t) {\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n return exceedsLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));\n }\n\n /**\n * Determines if a timer has reached its lower bound.\n * @param timer\n * \t\t\tThe timer's index.\n * @return\n * \t\t\tTrue if the timer has reached its lower bound, false otherwise.\n */\n public boolean exceedsLowerBoundbydbmIndex(int index) {\n // Note : Make sure that the lower bound is stored as a negative number\n // and that the inequality is correct.\n return _matrix[0][dbmIndexToMatrixIndex(index)] <= _matrix[1][dbmIndexToMatrixIndex(index)];\n }\n\n /* (non-Javadoc)\n\t * @see verification.timed_state_exploration.zone.Zone#fireTransitionbyTransitionIndex(int, int[], verification.platu.stategraph.State)\n\t */\n // State state)\n // // Check if the value is in this zone to fire.\n /**\n * Gives the Zone obtained by firing a given Transitions.\n * @param t\n * \t\tThe transitions being fired.\n * @param enabledTran\n * \t\tThe list of currently enabled Transitions.\n * @param localStates\n * \t\tThe current local states.\n * @return\n * \t\tThe Zone obtained by firing Transition t with enabled Transitions enabled\n * \t\tenabledTran when the current state is localStates.\n */\n // public Zone fire(Transition t, LpnTranList enabledTran,\n @Override\n public Zone fire(Transition t, LpnTranList enabledTran, ContinuousRecordSet newAssignValues, State[] localStates) {\n ", "post_mask_code": "\n // Create the LPNTransitionPair to check if the Transitions is in the zone and to\n // find the index.\n LPN lpn = t.getLpn();\n int lpnIndex = lpn.getLpnIndex();\n int transitionIndex = t.getIndex();\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);\n int dbmIndex = Arrays.binarySearch(_indexToTimerPair, ltPair);\n if (dbmIndex <= 0) {\n return this;\n }\n // Get the new zone portion.\n Zone newZone = fireTransitionbydbmIndexNew(dbmIndex, enabledTran, localStates, newAssignValues);\n // Update any assigned continuous variables.\n // Set all the rates to their lower bound.\n newZone.setAllToLowerBoundRate();\n // Warp the Zone\n newZone.dbmWarp(this);\n // Warping can wreck the newly assigned values so correct them.\n newZone.correctNewAssignemnts(newAssignValues);\n newZone.recononicalize();\n newZone.advance(localStates);\n // Recanonicalize\n newZone.recononicalize();\n newZone.checkZoneMaxSize();\n return newZone;\n }\n\n /**\n * Updates the Zone according to the transition firing.\n * @param index\n * \t\t\tThe index of the timer.\n * @param newContValue\n * @return\n * \t\t\tThe updated Zone.\n */\n public Zone fireTransitionbydbmIndex(int index, LpnTranList enabledTimers, State[] localStates, ArrayList> newAssignValues) {\n /*\n\t\t * For the purpose of adding the newly enabled transitions and removing\n\t\t * the disable transitions, the continuous variables that still have\n\t\t * a nonzero rate can be treated like still enbaled timers.\n\t\t */\n // Initialize the zone.\n Zone newZone = new Zone();\n // These sets will defferentiate between the new timers and the\n // old timers, that is between the timers that are not already in the\n // zone and those that are already in the zone..\n HashSet newTimers = new HashSet();\n HashSet oldTimers = new HashSet();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n HashMap oldNonZero = newAssignValues.get(3);\n // Add the continuous variables to the enabled timers.\n for (int i = 1; _indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n // For the purpose of addigng continuous variables to the zone\n // consider an oldNonZero continuous variable as new.\n if (oldNonZero.containsKey(_indexToTimerPair[i])) {\n continue;\n }\n oldTimers.add(_indexToTimerPair[i]);\n }\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n // Determine if each value is a new timer or old.\n if (Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0) {\n // The timer was already present in the zone.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else {\n // The timer is a new timer.\n newTimers.add(newZone._indexToTimerPair[i]);\n }\n }\n // Create the new matrix.\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n // TODO: For simplicity, make a copy of the current zone and perform the\n // restriction and re-canonicalization. Later add a copy re-canonicalization\n // that does the steps together.\n Zone tempZone = this.clone();\n tempZone.restrictTimer(index);\n tempZone.recononicalize();\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);\n newZone._matrix[Zone.dbmIndexToMatrixIndex(newIndexi)][Zone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n // The block copies the upper and lower bound information from the\n // old zone. Thus we do not consider anything that is not an old\n // timer. Furthermore, oldNonZero represent\n if (!oldTimers.contains(tempZone._indexToTimerPair[i]) && !oldNonZero.containsKey(_indexToTimerPair[i])) {\n continue;\n }\n newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n newZone.setLowerBoundByLPNTransitionPair(pair, lower);\n newZone.setUpperBoundByLPNTransitionPair(pair, upper);\n }\n // Advance time.\n return newZone;\n }\n\n public Zone fireTransitionbydbmIndexNew(int index, LpnTranList enabledTimers, State[] localStates, ContinuousRecordSet newAssignValues) {\n /*\n\t\t * For the purpose of adding the newly enabled transitions and removing\n\t\t * the disable transitions, the continuous variables that still have\n\t\t * a nonzero rate can be treated like still enbaled timers.\n\t\t */\n // Initialize the zone.\n Zone newZone = new Zone();\n // These sets will defferentiate between the new timers and the\n // old timers, that is between the timers that are not already in the\n // zone and those that are already in the zone..\n HashSet newTimers = new HashSet();\n HashSet oldTimers = new HashSet();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n copyRatesNew(newZone, enabledTimers, newAssignValues);\n // Add the continuous variables to the enabled timers.\n // // For the purpose of addigng continuous variables to the zone\n // // consider an oldNonZero continuous variable as new.\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n // Handle the continuous variables portion.\n if (newZone._indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];\n // Get the record\n UpdateContinuous continuousState = newAssignValues.get(lcPair);\n if (continuousState != null && (continuousState.is_newValue() || continuousState.newlyNonZero())) {\n // In the first case a new value has been assigned, so\n // consider the continuous variable a 'new' variable for\n // the purposes of copying relations from the previous zone.\n newTimers.add(newZone._indexToTimerPair[i]);\n continue;\n }\n // At this point, either the continuous variable was not present\n // in the newAssignValues or it is in the newAssignValues and\n // satisfies the following: it already had a non-zero rate, is\n // being assigned another non-zero rate, and is not being assigned\n // a new value. This is becuase the field _indexToTimerPair only\n // deals with non-zero rates, so the variable must have a non-zero\n // rate. Furthermore the if statement takes care of the cases\n // when the rate changed from zero to non-zero and/or a new value\n // has been assigned.\n // In either of the cases, we consider the variable an 'old' variable\n // for the purpose of copying the previous zone information.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else // At this point, the variable represents a transition (timer).\n // So determine whether this timer is new or old.\n if (Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0) {\n // The timer was already present in the zone.\n oldTimers.add(newZone._indexToTimerPair[i]);\n } else {\n // The timer is a new timer.\n newTimers.add(newZone._indexToTimerPair[i]);\n }\n }\n // Create the new matrix.\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n // TODO: For simplicity, make a copy of the current zone and perform the\n // restriction and re-canonicalization. Later add a copy re-canonicalization\n // that does the steps together.\n Zone tempZone = this.clone();\n tempZone.restrictTimer(index);\n tempZone.recononicalize();\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);\n newZone._matrix[Zone.dbmIndexToMatrixIndex(newIndexi)][Zone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n // The block copies the upper and lower bound information from the\n // old zone. Thus we do not consider anything that is not an old\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n // A hack to ensure that the newly zero variables\n // get the new values from the tempZone.\n if (tempZone._indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) tempZone._indexToTimerPair[i];\n VariableRangePair vrp = newZone._rateZeroContinuous.get(new LPNContAndRate(lcPair));\n if (vrp != null) {\n // This means that the continuous variable was non-zero\n // and is now zero. Fix up the values according to\n // the temp zone.\n IntervalPair newRange = tempZone.getContinuousBounds(lcPair);\n vrp.set_range(newRange);\n }\n }\n continue;\n }\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];\n // Check if a rate assignment has occured for any continuous\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord != null) {\n // Since the variable is in the oldTimers, it cannot have had\n // a new value assigned to it. It must have had a new rate assignment\n IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();\n // Copy the new rate information\n newZone.setLowerBoundByLPNTransitionPair(_indexToTimerPair[i], rates.get_LowerBound());\n newZone.setUpperBoundByLPNTransitionPair(_indexToTimerPair[i], rates.get_UpperBound());\n // Copy the smallest and greatest continuous value.\n continue;\n }\n }\n newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Handle continuous case\n if (pair instanceof LPNContinuousPair) {\n LPNContinuousPair lcPair = (LPNContinuousPair) pair;\n // If a continuous variable is in the newTimers, then an assignment\n // to the variable must have occurred. So get the value.\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord == null) {\n throw new IllegalStateException(\"The pair \" + pair + \"was not in the new assigned values but was sorted as \" + \"a new value.\");\n }\n IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();\n IntervalPair values = updateRecord.get_Value();\n newZone.setLowerBoundByLPNTransitionPair(lcPair, rates.get_LowerBound());\n newZone.setUpperBoundByLPNTransitionPair(lcPair, rates.get_UpperBound());\n // Get the current rate.\n int currentRate = lcPair.getCurrentRate();\n if (currentRate >= 0) {\n // // Copy the smallest and greatest continuous value.\n // Copy the smallest and greatest continuous value.\n newZone.setDbmEntryByPair(lcPair, LPNTransitionPair.ZERO_TIMER_PAIR, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), currentRate, true));\n newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, lcPair, ContinuousUtilities.chkDiv(values.get_UpperBound(), currentRate, true));\n } else {\n // Copy the smallest and greatest continuous value.\n // For negative rates, the upper and lower bounds need\n // to be switched.\n newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, lcPair, ContinuousUtilities.chkDiv(values.get_LowerBound(), currentRate, true));\n newZone.setDbmEntryByPair(lcPair, LPNTransitionPair.ZERO_TIMER_PAIR, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), currentRate, true));\n }\n continue;\n }\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n if (delay == null) {\n _lpnList[pair.get_lpnIndex()].changeDelay(tranName, \"0\");\n delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n }\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n newZone.setLowerBoundByLPNTransitionPair(pair, lower);\n newZone.setUpperBoundByLPNTransitionPair(pair, upper);\n }\n // Erase relationships for continuous variables that have had new values\n // assigned to them or a new non-rate zero value.\n for (int i = 1; i < newZone._indexToTimerPair.length && newZone._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];\n // Get the update variable.\n UpdateContinuous update = newAssignValues.get(lcPair);\n if (update != null && (update.is_newValue() || update.newlyNonZero())) {\n for (int j = 1; j < newZone._indexToTimerPair.length; j++) {\n if (j == i) {\n continue;\n }\n newZone.setDbmEntry(i, j, Zone.INFINITY);\n newZone.setDbmEntry(j, i, Zone.INFINITY);\n }\n }\n }\n // Advance time.\n return newZone;\n }\n\n public void correctNewAssignemnts(ContinuousRecordSet newAssignValues) {\n // Erase relationships for continuous variables that have had new values\n // assigned to them or a new non-rate zero value.\n for (int i = 1; i < this._indexToTimerPair.length && this._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];\n // Get the update variable.\n UpdateContinuous update = newAssignValues.get(lcPair);\n if (update != null && (update.is_newValue() || update.newlyNonZero())) {\n IntervalPair values = update.get_Value();\n int currentRate = lcPair.getCurrentRate();\n // Correct the upper and lower bounds.\n if (lcPair.getCurrentRate() > 0) {\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), currentRate, true));\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(values.get_UpperBound(), currentRate, true));\n } else {\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), currentRate, true));\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(values.get_LowerBound(), currentRate, true));\n }\n // Erase the relationships.\n for (int j = 1; j < this._indexToTimerPair.length; j++) {\n if (j == i) {\n continue;\n }\n this.setDbmEntry(i, j, Zone.INFINITY);\n this.setDbmEntry(j, i, Zone.INFINITY);\n }\n }\n }\n }\n\n /**\n * This fire method fires a rate change event.\n *\n * @param ltPair\n * \t\tThe index of the continuous variable whose rate needs to be changed.\n * @param rate\n * \t\tThe new rate.\n * @return\n * \t\tThe new zone resulting from the rate change.\n */\n @Override\n public Zone fire(LPNTransitionPair ltPair, int rate) {\n // Make a copy of the Zone.\n Zone resultZone = this.clone();\n // Change the current rate of the continuous variable.\n setCurrentRate(ltPair, rate);\n // Warp the zone.\n resultZone.dbmWarp(this);\n return resultZone;\n }\n\n /**\n * Handles the moving in and out of continuous variables.\n * @param newContValues\n */\n // // Copy the zero rate variables over if they are still rate zero.\n // // Check if the pairing is in the newNonZeroContValues.\n // // Interval being null indicates that the key was not\n /**\n * Handles the moving of the continuous variables in and out of the\n * _rateZeroContinuous. This includes the adding of all rate zero (new and old)\n * cotninuous variables to the _rateZeroContinuous, and creating the\n * _indexToTimerPair and populating it.\n * @param newZone The Zone being constructed.\n * @param enabled The list of enabled transitions.\n * \t\tThe enabled transitions.\n * @param newAssignValues The list of continuous variable update information.\n */\n @SuppressWarnings(\"unused\")\n private void copyRates(Zone newZone, LpnTranList enabledTran, ContinuousRecordSet newAssignValues) {\n /*\n\t\t * The newAssignValues is an ArrayList of four sets.\n\t\t * 0. Rate zero gets zero assigned.\n\t\t * 1. Rate zero gets non-zero rate assigned.\n\t\t * 2. Non-zero gets zero rate assigned.\n\t\t * 3. Non-zero gets non-zero rate assigned.\n\t\t */\n // Create new rate zero member variable.\n newZone._rateZeroContinuous = new DualHashMap();\n // First get the total number of non-zero rate continuous variables that\n // are present in the old zone.\n int totalContinuous = 0;\n for (int i = 0; i < _lpnList.length; i++) {\n totalContinuous += _lpnList[i].getTotalNumberOfContVars();\n }\n int numberNonZero = totalContinuous - _rateZeroContinuous.size();\n // The size is given by\n // total number of transitions\n // + number of non-zero rate continuous variables previously in the zone\n // + number of zero rate continuous variables that now have non-zero\n // - number of non-zero rate continuous variables that are now zero\n // + 1 for the zero timer.\n // TODO: Create an object that stores the records along with this information.\n int newNonZero = 0, newZero = 0;\n for (UpdateContinuous record : newAssignValues.keySet()) {\n if (record.newlyNonZero()) {\n newNonZero++;\n }\n if (record.newlyZero()) {\n newZero++;\n }\n }\n int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;\n // Create the timer array.\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n // Add in the zero timer.\n newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;\n // Copy over the rate zero conintinuous variables.\n // First copy over all the continuous variables that still have\n // rate zero.\n // // Cast the index.\n // // The variable no longer is rate zero, so do nothing.\n // // If the value has had an assignment, use the new values instead.\n // // Create the new VariableRangePair to add.\n // VariableRangePair vrp =\n // Copy over the rate zero continuous variables.\n // First copy over all the continuous variables that still have\n // rate zero.\n for (LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()) {\n // Cast the index.\n LPNContinuousPair ltContPair = ltTranPair.get_lcPair();\n if (!newAssignValues.get(ltContPair).is_newZero()) {\n // The variable no longer is rate zero, so do nothing.\n continue;\n }\n // If the value has had an assignment, use the new values instead.\n if (newAssignValues.contains(ltContPair)) {\n // Create the new VariableRangePair to add.\n Variable v = _lpnList[ltContPair.get_lpnIndex()].getContVar(ltContPair.get_ContinuousIndex());\n // VariableRangePair vrp =\n VariableRangePair vrp = new VariableRangePair(v, newAssignValues.get(ltContPair).get_Value());\n newZone._rateZeroContinuous.insert(new LPNContAndRate(ltContPair, new IntervalPair(0, 0)), vrp);\n } else {\n newZone._rateZeroContinuous.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));\n }\n }\n // Next add the values that are newly set to rate zero.\n // // Exract the variable.\n // // Create a VariableRangePair.\n // // Add the value to the map.\n // // Exract the variable.\n // // Create a VariableRangePair.\n // // Add the value to the map.\n // We still need to add in the rate zero continuous variables whose rate remains zero\n // since their range might have changed. We could check if the range has changed, but\n // its just as easy (or easier) to simply add it anyway.\n // Added the indecies for the non-zero rate continuous variables to the\n // _indexToTimer array.\n // Start with the values already in the old array.\n // int index = 1; // Index for the next continuous index object.\n // // Check that the value should not be removed.\n // Change to the new references for the oldNonZero. This change to the\n // Add in the indecies for the new non-zero into the old array.\n // Copy over the new transitions.\n Arrays.sort(newZone._indexToTimerPair);\n }\n\n private void copyRatesNew(Zone newZone, LpnTranList enabledTran, ContinuousRecordSet newAssignValues) {\n // Create new rate zero member variable.\n newZone._rateZeroContinuous = new DualHashMap();\n // First get the total number of non-zero rate continuous variables that\n // are present in the old zone.\n int totalContinuous = 0;\n for (int i = 0; i < _lpnList.length; i++) {\n totalContinuous += _lpnList[i].getTotalNumberOfContVars();\n }\n int numberNonZero = totalContinuous - _rateZeroContinuous.size();\n // The size is given by\n // total number of transitions\n // + number of non-zero rate continuous variables previously in the zone\n // + number of zero rate continuous variables that now have non-zero\n // - number of non-zero rate continuous variables that are now zero\n // + 1 for the zero timer.\n // TODO: Create an object that stores the records along with this information.\n int newNonZero = 0, newZero = 0;\n for (UpdateContinuous record : newAssignValues.keySet()) {\n if (record.newlyNonZero()) {\n newNonZero++;\n }\n if (record.newlyZero()) {\n newZero++;\n }\n }\n int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;\n // Create the timer array.\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n // Add in the zero timer.\n newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;\n int indexTimerCount = 1;\n // Sort the previous rate zero continuous variables into rate zero or non-zero.\n for (LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()) {\n // Cast the index.\n LPNContinuousPair ltContPair = ltTranPair.get_lcPair();\n // Check if the variable is a newly assigned value.\n UpdateContinuous assignedLtContPair = newAssignValues.get(ltContPair);\n if (assignedLtContPair != null) {\n if (assignedLtContPair.newlyNonZero()) {\n // Variable was zero and is now non-zero, so add to the the non-zero\n newZone._indexToTimerPair[indexTimerCount++] = assignedLtContPair.get_lcrPair().get_lcPair().clone();\n } else {\n // Variable was zero and is still zero, but an assignment has been\n // made. Simply add in the new assigned value.\n VariableRangePair vrp = this._rateZeroContinuous.get(ltTranPair);\n newZone._rateZeroContinuous.insert(assignedLtContPair.get_lcrPair(), new VariableRangePair(vrp.get_variable(), assignedLtContPair.get_Value()));\n }\n } else {\n newZone._rateZeroContinuous.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));\n }\n }\n // Sort the previous non-zero variables into the rate zero and non-zero.\n for (int i = 1; this._indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];\n // Check if an assignment has been made.\n UpdateContinuous updateRecord = newAssignValues.get(lcPair);\n if (updateRecord != null) {\n if (updateRecord.is_newZero()) {\n // The continuous variable is now a rate zero variable.\n LPNContinuousPair ltCar = updateRecord.get_lcrPair().get_lcPair();\n Variable v = _lpnList[ltCar.get_lpnIndex()].getContVar(ltCar.get_ContinuousIndex());\n // Dewarp the upper and lower bounds.\n IntervalPair values = updateRecord.get_Value();\n int currentRate = getCurrentRate(ltCar);\n values.set_LowerBound(values.get_LowerBound() * currentRate);\n values.set_UpperBound(values.get_UpperBound() * currentRate);\n // Create a VariableRangePair.\n VariableRangePair vrp = new VariableRangePair(v, values);\n // Add the value to the map.\n newZone._rateZeroContinuous.insert(updateRecord.get_lcrPair(), vrp);\n } else {\n // This non-zero variable still has rate non-zero, but replace\n // with the newAssignValues since the rate may have changed.\n newZone._indexToTimerPair[indexTimerCount++] = updateRecord.get_lcrPair().get_lcPair();\n }\n } else {\n // The variable was non-zero and hasn't had an assignment.\n newZone._indexToTimerPair[indexTimerCount++] = this._indexToTimerPair[i].clone();\n }\n }\n // Copy over the new transitions.\n for (Transition t : enabledTran) {\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n newZone._indexToTimerPair[indexTimerCount++] = new LPNTransitionPair(lpnIndex, tranIndex);\n }\n Arrays.sort(newZone._indexToTimerPair);\n }\n\n private void advance() {\n for (int i = 0; i < dbmSize(); i++) {\n _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(i)] = getUpperBoundbydbmIndex(i);\n }\n }\n\n /**\n * Advances time. (This method should replace advance().)\n * @param localStates\n */\n @Override\n public void advance(State[] localStates) {\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n if (ltPair.equals(LPNTransitionPair.ZERO_TIMER_PAIR)) {\n continue;\n }\n // Get the new value.\n int newValue = 0;\n if (!(ltPair instanceof LPNContinuousPair)) {\n // If the pair is a timer, then simply get the stored largest value.\n int index = timerIndexToDBMIndex(ltPair);\n newValue = getUpperBoundbydbmIndex(index);\n } else {\n // If the pair is a continuous variable, then need to find the\n // possible largest bound governed by the inequalities.\n newValue = ContinuousUtilities.maxAdvance(this, ltPair, localStates);\n }\n // In either case (timer or continuous), set the upper bound portion\n // of the DBM to the new value.\n setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, newValue);\n }\n }\n\n /**\n * Copies in the new values needed to add a set of new times.\n * @param newZone\n * \t\t\tThe zone that the values are going to be copied into.\n * @param tempZone\n * \t\t\tThe zone to look up current values of timers.\n * @param newTimers\n * \t\t\tA collection of the new timers.\n * @param oldTimers\n * \t\t\tA collection of the older timers.\n * @param localStates\n * \t\t\tThe current state.\n */\n private void copyTransitions(Zone tempZone, Collection newTimers, Collection oldTimers, State[] localStates) {\n // Copy the tempZone to the new zone.\n for (int i = 0; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n // Get the new index of for the timer.\n int newIndexi = i == 0 ? 0 : Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[i]);\n for (int j = 0; j < tempZone.dbmSize(); j++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[j])) {\n continue;\n }\n int newIndexj = j == 0 ? 0 : Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[j]);\n _matrix[dbmIndexToMatrixIndex(newIndexi)][dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j);\n }\n }\n // Copy the upper and lower bounds.\n for (int i = 1; i < tempZone.dbmSize(); i++) {\n if (!oldTimers.contains(tempZone._indexToTimerPair[i])) {\n continue;\n }\n setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1 * tempZone.getLowerBoundbydbmIndex(i));\n // The minus sign is because _matrix stores the negative of the lower bound.\n setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i));\n }\n // Copy in the new relations for the new timers.\n for (LPNTransitionPair timerNew : newTimers) {\n for (LPNTransitionPair timerOld : oldTimers) {\n setDbmEntry(timerIndexToDBMIndex(timerNew), timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));\n setDbmEntry(timerIndexToDBMIndex(timerOld), timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));\n }\n }\n // Set the upper and lower bounds for the new timers.\n for (LPNTransitionPair pair : newTimers) {\n // Get all the upper and lower bounds for the new timers.\n // Get the name for the timer in the i-th column/row of DBM\n String tranName = _lpnList[pair.get_lpnIndex()].getTransition(pair.get_transitionIndex()).getLabel();\n ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);\n // Get the values of the variables for evaluating the ExprTree.\n HashMap varValues = _lpnList[pair.get_lpnIndex()].getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());\n // Set the upper and lower bound.\n int upper, lower;\n if (delay.getOp().equals(\"uniform\")) {\n IntervalPair lowerRange = delay.getLeftChild().evaluateExprBound(varValues, null, null);\n IntervalPair upperRange = delay.getRightChild().evaluateExprBound(varValues, null, null);\n // The lower and upper bounds should evaluate to a single\n if (!lowerRange.singleValue() || !upperRange.singleValue()) {\n throw new IllegalStateException(\"When evaulating the delay, \" + \"the lower or the upper bound evaluated to a range \" + \"instead of a single value.\");\n }\n lower = lowerRange.get_LowerBound();\n upper = upperRange.get_UpperBound();\n } else {\n IntervalPair range = delay.evaluateExprBound(varValues, this, null);\n lower = range.get_LowerBound();\n upper = range.get_UpperBound();\n }\n setLowerBoundByLPNTransitionPair(pair, lower);\n setUpperBoundByLPNTransitionPair(pair, upper);\n }\n }\n\n /**\n * This method sets all the rate to their lower bound.\n * Will not work quite right for continuous variables\n * with rates that include zero.\n */\n private void setAllToLowerBoundRate() {\n // Loop through the continuous variables.\n for (int i = 1; i < _indexToTimerPair.length && _indexToTimerPair[i] instanceof LPNContinuousPair; i++) {\n LPNContinuousPair ltContPair = (LPNContinuousPair) _indexToTimerPair[i];\n // For this, recall that for a continuous variable that the lower bound\n // rate is stored in the zero column of the matrix.\n int lower = -1 * _matrix[dbmIndexToMatrixIndex(i)][0];\n int upper = _matrix[0][dbmIndexToMatrixIndex(i)];\n int newRate;\n /**\n * Suppose the range of rates is [a,b]. If a>=0, then we set the\n * rate to b. If b<=0, then we set the rate to a. Ohterwise,\n * a<0=0 or lower < 0 < upper we set the\n // rate to the upper bound.\n newRate = upper;\n }\n setCurrentRate(ltContPair, newRate);\n }\n }\n\n /**\n * Resets the rates of all continuous variables to be their\n * lower bounds.\n */\n @Override\n public Zone resetRates() {\n // Create the new zone.\n // // Copy the rate zero variables.\n // // Copy the LPNs over.\n // // Loop through the variables and save off those\n // // that are rate zero. Accumulate an array that\n // // indicates which are zero for faster\n // // copying. Save the number of continuous variables.\n // boolean[] rateZero = new boolean[this._indexToTimerPair.length]; // Is rate zero.\n // // The rate zero is in the range, so this will be\n // LPNContinuousPair lcPair =\n // // Save as a rate zero continuous variable.\n // VariableRangePair vcp =\n // // Update continuous variable counter.\n // // Save over the indexToTimer pairs.\n // // Ignore rate zero variables.\n // // If this is a continuous variable, set the rate to the lower bound.\n // // Calculate the size of the matrix and create it.\n // // Copy over the old matrix for all variables except\n // // the rate zero variables.\n // Warp\n Zone newZone = new Zone();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n /* \n\t\t * Collect the rate zero variables whose range of rates are not\n\t\t * identically zero. These will be moved out of the zone when\n\t\t * the rate is reset.\n\t\t * \n\t\t * Copy over the rate zero variables that remain rate zero.\n\t\t */\n newZone._rateZeroContinuous = new DualHashMap();\n HashSet> newlyNonZero = new HashSet>();\n for (Map.Entry variable : _rateZeroContinuous.entrySet()) {\n // Check for a single value which indicates that zero is\n // the only possible rate.\n if (variable.getKey().get_rateInterval().singleValue()) {\n // This variable only has zero as a rate so keep it\n // in the rate zero variables.\n newZone._rateZeroContinuous.insert(variable.getKey(), variable.getValue());\n } else {\n // This variable will need to be added to the zone.\n newlyNonZero.add(variable);\n }\n }\n /*\n\t\t * Calulate the size of the _indexToTimerPairs array and create\n\t\t * it.\n\t\t */\n int oldSize = this._indexToTimerPair.length;\n int newSize = oldSize + newlyNonZero.size();\n newZone._indexToTimerPair = new LPNTransitionPair[newSize];\n /*\n\t\t * Copy over the old pairs and add the new ones.\n\t\t */\n for (int i = 0; i < this._indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();\n }\n for (Map.Entry variable : newlyNonZero) {\n newZone._indexToTimerPair[oldSize++] = variable.getKey().get_lcPair().clone();\n }\n Arrays.sort(newZone._indexToTimerPair);\n /*\n\t\t * Copy over the old matrix values and new constraints.\n\t\t */\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n for (int i = 0; i < this.dbmSize(); i++) {\n int newi = Arrays.binarySearch(newZone._indexToTimerPair, this._indexToTimerPair[i]);\n if (newi < 0) {\n System.err.println(\"In resetRates, old value was not found\" + \" in new value.\");\n continue;\n }\n // Copy upper and lower bounds for the variable.\n newZone._matrix[dbmIndexToMatrixIndex(newi)][0] = this._matrix[dbmIndexToMatrixIndex(i)][0];\n newZone._matrix[0][dbmIndexToMatrixIndex(newi)] = this._matrix[0][dbmIndexToMatrixIndex(i)];\n // Copy the DBM Entry\n for (int j = 0; j < this.dbmSize(); j++) {\n int newj = Arrays.binarySearch(newZone._indexToTimerPair, this._indexToTimerPair[j]);\n if (newj < 0) {\n System.err.println(\"In resetRates, old value was not\" + \" found in new value.\");\n continue;\n }\n newZone.setDbmEntry(newi, newj, this.getDbmEntry(i, j));\n }\n }\n for (Map.Entry variable : newlyNonZero) {\n LPNTransitionPair currentVariable = variable.getKey().get_lcPair();\n int currentIndex = Arrays.binarySearch(newZone._indexToTimerPair, currentVariable);\n IntervalPair rangeOfRates = variable.getKey().get_rateInterval();\n IntervalPair rangeOfValues = variable.getValue().get_range();\n /*\n\t\t\t * First set the range of rates, current rate, and the lower and upper\n\t\t\t * bounds for the newly added continuous variables.\n\t\t\t */\n newZone.setLowerBoundbydbmIndex(currentIndex, rangeOfRates.get_LowerBound());\n newZone.setUpperBoundbydbmIndex(currentIndex, rangeOfRates.get_UpperBound());\n newZone.setDbmEntry(currentIndex, 0, -1 * rangeOfValues.get_LowerBound());\n newZone.setDbmEntry(0, currentIndex, rangeOfValues.get_UpperBound());\n for (int j = 1; j < newZone.dbmSize(); j++) {\n if (currentIndex == j) {\n continue;\n }\n newZone.setDbmEntry(currentIndex, j, Zone.INFINITY);\n newZone.setDbmEntry(j, currentIndex, Zone.INFINITY);\n }\n }\n /*\n\t\t * Reset all the rates.\n\t\t */\n newZone.setAllToLowerBoundRate();\n newZone.recononicalize();\n newZone.dbmWarp(this);\n newZone.recononicalize();\n return newZone;\n }\n\n /**\n * Finds the maximum amount that time cam advance.\n * @return\n * \t\tvalue.\n * \t\tThe maximum amount that time can advance before a timer expires or an inequality changes\n */\n // * Several comments in this function may look like C code. That's because,\n // * well it is C code from atacs/src/lhpnrsg.c. In particular the\n // // Get the continuous variable in question.\n // // printf(\"Zone to check...\\n\");\n // // Get all the inequalities that reference the variable of interest.\n // // Update the inequality variable.\n // // /* Working on a > or >= ineq */\n // // Working on a > or >= ineq\n // // If the rate is positive.\n // // /* Working on a < or <= ineq */\n // // Working on a < or <= ineq\n // // Check if the value can be lowered.\n // //printf(\"Min leaving checkPreds for %s: %d\\n\",events[p]->event,min);\n /* (non-Javadoc)\n\t * @see java.lang.Object#clone()\n\t */\n @Override\n public Zone clone() {\n Zone clonedZone = new Zone();\n clonedZone._matrix = new int[this.matrixSize()][this.matrixSize()];\n for (int i = 0; i < this.matrixSize(); i++) {\n for (int j = 0; j < this.matrixSize(); j++) {\n clonedZone._matrix[i][j] = this._matrix[i][j];\n }\n }\n clonedZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n clonedZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();\n }\n clonedZone._hashCode = this._hashCode;\n clonedZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n clonedZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n return clonedZone;\n }\n\n /**\n * Restricts the lower bound of a timer.\n *\n * @param timer\n * \t\t\tThe timer to tighten the lower bound.\n */\n private void restrictTimer(int timer) {\n _matrix[dbmIndexToMatrixIndex(timer)][dbmIndexToMatrixIndex(0)] = getLowerBoundbydbmIndex(timer);\n }\n\n /**\n * Restricts the lower bound of a continuous variable. Also checks fixes\n * the upper bound to be at least as large if needed. This method\n * is usually used as a result of an event firing.\n * @param ltContPair\n * \t\tThe index of the continuous variable to restrict.\n * @param constant\n * \t\tThe constant value of the inequality event that is being used to update\n * \t\tthe variable indexed by ltContPair.\n */\n private boolean restrictContinuous(LPNContinuousPair ltContPair, int constant) {\n // It will be quicker to get the DBM index for the ltContPair one time.\n int variableIndex = timerIndexToDBMIndex(ltContPair);\n int zeroIndex = timerIndexToDBMIndex(LPNTransitionPair.ZERO_TIMER_PAIR);\n // Set the lower bound the variable (which is the DBM[variabl][0] entry.\n // Note : the lower bound in the zone is actually the negative of the lower\n // bound hence the -1 on the warpValue.\n setDbmEntry(variableIndex, zeroIndex, ContinuousUtilities.chkDiv(-1 * constant, ltContPair.getCurrentRate(), true));\n // Check if the upper bound needs to be advanced and advance it if necessary.\n if (getDbmEntry(zeroIndex, variableIndex) < ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true)) {\n // If the upper bound in the zones is less than the new restricting value, we\n // must advance it for the zone to remain consistent.\n setDbmEntry(zeroIndex, variableIndex, ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true));\n return true;\n }\n return false;\n }\n\n /**\n * Restricts the continuous variables in the zone according to the inequalities in a set of events.\n * @param eventSet\n * \t\t\tA set of inequality events. Does nothing if the event set does not contian inequalities.\n */\n private void restrictContinuous(EventSet eventSet) {\n // Check that the eventSet is a set of Inequality events.\n if (!eventSet.isInequalities()) {\n // If the eventSet is not a set of inequalities, do nothing.\n return;\n }\n HashSet adjustedColumns = new HashSet();\n boolean needsAdjusting = false;\n // Restrict the variables according to each of the inequalities in the eventSet.\n for (Event e : eventSet) {\n // Get the inequality.\n InequalityVariable iv = e.getInequalityVariable();\n // Extract the variable. I will assume the inequality only depends on a single\n Variable x = iv.getContVariables().get(0);\n // Extract the index.\n int lpnIndex = iv.get_lpn().getLpnIndex();\n // Extract the variable index.\n DualHashMap variableIndexMap = _lpnList[lpnIndex].getContinuousIndexMap();\n int variableIndex = variableIndexMap.getValue(x.getName());\n // Package it up for referencing.\n LPNContinuousPair ltContPair = new LPNContinuousPair(lpnIndex, variableIndex);\n // Need the current rate for the variable, grab the stored LPNContinuousPair.\n int zoneIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);\n if (zoneIndex > 0) {\n ltContPair = (LPNContinuousPair) _indexToTimerPair[zoneIndex];\n }\n // Perform the restricting.\n needsAdjusting = needsAdjusting | restrictContinuous(ltContPair, iv.getConstant());\n if (needsAdjusting) {\n adjustedColumns.add(ltContPair);\n }\n }\n // If one of the continuous variables has been moved forward, the other colmns\n // need to be adjusted to keep a consistent zone.\n if (needsAdjusting) {\n // At least one of the continuous variables has been moved forward,\n // so se need to ajust the bounds to keep a consistent zone.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltpair = _indexToTimerPair[i];\n if (adjustedColumns.contains(ltpair)) {\n // This continuous variables already had the upper bound\n continue;\n }\n // Add one to the upper bounds.\n setDbmEntry(0, i, getDbmEntry(0, i) + 1);\n }\n }\n }\n\n /**\n * Returns a zone that is the result from restricting the this zone according to a list of firing event inequalities.\n * @param eventSet\n * \t\tThe list of inequalities that are firing.\n * @return\n * \t\tThe new zone that is the result of restricting this zone according to the firing of the inequalities\n * \t\tin the eventSet.\n */\n @Override\n public Zone getContinuousRestrictedZone(EventSet eventSet, State[] localStates) {\n // Make a new copy of the zone.\n Zone z = this.clone();\n if (eventSet == null) {\n return z;\n }\n z.restrictContinuous(eventSet);\n return z;\n }\n\n /**\n * The list of enabled timers.\n * @return\n * \t\tThe list of all timers that have reached their lower bounds.\n */\n @Override\n public List getEnabledTransitions() {\n ArrayList enabledTransitions = new ArrayList();\n // Check if the timer exceeds its lower bound staring with the first nonzero\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n enabledTransitions.add(_lpnList[_indexToTimerPair[i].get_lpnIndex()].getTransition(_indexToTimerPair[i].get_transitionIndex()));\n }\n }\n return enabledTransitions;\n }\n\n /**\n * Gives the list of enabled transitions associated with a particular LPN.\n * @param LpnIndex\n * \t\t\tThe Index of the LPN the Transitions are a part of.\n * @return\n * \t\t\tA List of the Transitions that are enabled in the LPN given by the index.\n */\n @Override\n public List getEnabledTransitions(int LpnIndex) {\n ArrayList enabledTransitions = new ArrayList();\n // Check if the timer exceeds its lower bound staring with the first nonzero\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n if (ltPair.get_lpnIndex() == LpnIndex) {\n enabledTransitions.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));\n }\n }\n }\n return enabledTransitions;\n }\n\n /**\n * Find the next possible events.\n *\n * @param LpnIndex\n * \t\tThe index of the LPN that is of interest.\n * @param localState\n * \t\tThe state associated with the LPN indexed by LpnIndex.\n * @return\n * \t\tLpnTranList is populated with a list of\n * \t\tEventSets pertaining to the LPN with index LpnIndex. An EventSet can\n * \t\teither contain a transition to\n * \t\tfire or set of inequalities to change sign.\n */\n @Override\n public LpnTranList getPossibleEvents(int LpnIndex, State localState) {\n LpnTranList result = new LpnTranList();\n // Look through the timers and continuous variables. For the timers\n // determine if they are ready to fire. For the continuous variables,\n // look up the associated inequalities and see if any of them are ready\n // to fire.\n // We do not need to consider the zero timer, so start the\n // for loop at i=1 and not i=0.\n for (int i = 1; i < _indexToTimerPair.length; i++) {\n LPNTransitionPair ltPair = _indexToTimerPair[i];\n // The enabled events are grouped with the LPN that they affect. So if\n // this pair does not belong to the current LPN under consideration, skip\n // processing it.\n if (ltPair.get_lpnIndex() != LpnIndex) {\n continue;\n }\n // If the index refers to a timer (and not a continuous variable) and has exceeded its lower bound,\n // then add the transition.\n if (!(ltPair instanceof LPNContinuousPair)) {\n // The index refers to a timer. Now check if time has advanced\n // far enough for the transition to fire.\n if (getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) {\n Event e = new Event(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));\n result = addSetItem(this, result, e, localState);\n }\n } else {\n // The index refers to a continuous variable.\n // First check for a rate change event.\n LPNContinuousPair ltContPair = ((LPNContinuousPair) ltPair).clone();\n IntervalPair ratePair = getRateBounds(ltContPair);\n // // The rate represents a range of rates and no rate change\n // // event has occured.\n // // The rate contians zero, so we need to add two rate\n // // events: one for the lower bound and one for the upper\n // // Create the events.\n // // Add them to the result set.\n result = createRateEvents(this, ltContPair, ratePair, result, localState);\n // Check all the inequalities for inclusion.\n Variable contVar = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());\n if (contVar.getInequalities() != null) {\n for (InequalityVariable iv : contVar.getInequalities()) {\n // Check if the inequality can change.\n if (ContinuousUtilities.inequalityCanChange(this, iv, localState)) {\n result = addSetItem(this, result, new Event(iv), localState);\n }\n }\n }\n }\n }\n // Check the rate zero variables for possible rate change events.\n for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()) {\n // Get the reference object:\n LPNContinuousPair ltContPair = lcrPair.get_lcPair();\n // Extract the range of rates.\n IntervalPair ratePair = lcrPair.get_rateInterval();\n result = createRateEvents(this, ltContPair, ratePair, result, localState);\n }\n return result;\n }\n\n public static LpnTranList createRateEvents(Equivalence Z, LPNContinuousPair ltContPair, IntervalPair ratePair, LpnTranList result, State localState) {\n // // The rate represents a range of rates and no rate change\n // // event has occured.\n // // The rate contians zero, so we need to add two rate\n // // events: one for the lower bound and one for the upper\n // // Create the events.\n // // Add them to the result set.\n /*\n\t\t * Let [a,b] be the current range of rates for a given variable.\n\t\t * If a>=0, then we set the rate to b originally.\n\t\t * So if the current rate is b, then we have a rate change event to a.\n\t\t * \n\t\t * If b<=0, then we set the rate to a originially.\n\t\t * So if the current rate is a, then we have a rate change event to b.\n\t\t * \n\t\t * The final case to consider is when a < 0 and b > 0. If the current\n\t\t * rate is b, we allow rate changes to either a or 0. If the current\n\t\t * rate is a, we allow a rate change to zero.\n\t\t */\n if (ratePair.singleValue()) {\n // Rates that are not a range do not generate rate change events.\n return result;\n }\n ltContPair = ltContPair.clone();\n if (ratePair.get_LowerBound() >= 0) {\n if (ltContPair.getCurrentRate() == ratePair.get_UpperBound()) {\n ltContPair.setCurrentRate(ratePair.get_LowerBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n } else if (ratePair.get_UpperBound() <= 0) {\n if (ltContPair.getCurrentRate() == ratePair.get_LowerBound()) {\n ltContPair.setCurrentRate(ratePair.get_UpperBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n } else {\n if (ltContPair.getCurrentRate() == ratePair.get_UpperBound()) {\n // No rate change events have ocurred. So we allow one for zero\n // and the lower bounds rate.\n LPNContinuousPair ltContPairOther = ltContPair.clone();\n ltContPair.setCurrentRate(0);\n ltContPairOther.setCurrentRate(ratePair.get_LowerBound());\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n result = addSetItem(Z, result, new Event(ltContPairOther), localState);\n } else if (ltContPair.getCurrentRate() == ratePair.get_LowerBound()) {\n // The rate has change to the lower bound. Allow one rate\n // change to zero.\n ltContPair.setCurrentRate(0);\n result = addSetItem(Z, result, new Event(ltContPair), localState);\n }\n }\n return result;\n }\n\n /**\n * Adds or removes items as appropriate to update the current\n * list of possible events. Note the type LpnTranList extends\n * LinkedList. The type EventSet extends transition\n * specifically so that objects of EventSet type can be place in\n * this list.\n * @param EventList\n * \t\t\tThe list of possible events.\n */\n public static LpnTranList addSetItem(Equivalence Z, LpnTranList E, Event e, State s) {\n // void lhpnAddSetItem(eventSets &E,lhpnEventADT e,ineqList &ineqL,lhpnZoneADT z,\n // lhpnStateADT cur_state)\n // Note the LPNTranList plays the role of the eventSets.\n int rv1l = 0, rv1u = 0, rv2l = 0, rv2u = 0, iZ, jZ;\n // printf(\"Event sets entering:\\n\");\n // Create the new LpnTranlist for holding the events.\n EventSet eSet = new EventSet();\n LpnTranList newE = new LpnTranList();\n boolean done = false;\n boolean possible = true;\n if (e.isRate()) {\n eSet.add(e);\n // I believe that I should actually copy over the old list\n // and then add the new event set.\n newE = E.copy();\n newE.addLast(eSet);\n // The previous two commands act to pass the changes of E\n // back out of the functions. So returning the new object\n // is suficient.\n // printf(\"Event sets leaving:\\n\");\n return newE;\n }\n if (e.isInequality()) {\n // Is this necessary, or even correct to update the inequalities.\n // System.out.println(\"Note the inequality is not being updated before in addSetItem\");\n // In this case the Event e represents an inequality.\n InequalityVariable ineq = e.getInequalityVariable();\n // Need to extract the rate.\n // To do this, I'll create the indexing object.\n Variable v = ineq.getContVariables().get(0);\n // Find the LPN.\n int lpnIndex = ineq.get_lpn().getLpnIndex();\n int varIndex = Z.getVarIndex(lpnIndex, v.getName());\n // Package it all up.\n // LPNTransitionPair ltPair =\n // Note : setting the rate is not necessary since\n // this is only being used as aan index.\n // LPNContinuousPair ltPair =\n LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);\n rv2l = ContinuousUtilities.chkDiv(-1 * ineq.getConstant(), Z.getCurrentRate(ltPair), true);\n rv2u = ContinuousUtilities.chkDiv(ineq.getConstant(), Z.getCurrentRate(ltPair), true);\n iZ = Z.getIndexByTransitionPair(ltPair);\n } else {\n // In this case, the event is a transition.\n Transition t = e.getTransition();\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n // Package the results.\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);\n iZ = Z.getIndexByTransitionPair(ltPair);\n }\n // Recall that E contains the events sets which are inherited from the Transition class\n // so they can be placed in an LpnTranList. So consider each event set.\n for (Transition es : E) {\n if (!(es instanceof EventSet)) {\n // This collection should contain event sets, not transitions.\n throw new IllegalArgumentException(\"The eventSet was a Transition object not an EventSet object.\");\n }\n EventSet eventSet = (EventSet) es;\n if (done) {\n // Copy any remaining sets into newE.\n newE.add(eventSet.clone());\n break;\n }\n EventSet workSet = eventSet.clone();\n // Get an iterator for the elements in the workset.\n for (Event oldEvent : eventSet) {\n // For matching code with atacs, note that oldEvent is 'j'.\n if (oldEvent.isRate()) {\n continue;\n }\n if (oldEvent.isInequality()) {\n // Again, is it necessary to do an update here?\n // System.out.println(\"Note the inequality is not being updated before in addSetItem\");\n // In this case the Event oldEvent represents an inequality.\n InequalityVariable ineq = oldEvent.getInequalityVariable();\n // Extract variable.\n Variable v = ineq.getContVariables().get(0);\n // Find the LPN.\n int lpnIndex = ineq.get_lpn().getLpnIndex();\n int varIndex = Z.getVarIndex(lpnIndex, v.getName());\n // Package it all up.\n // LPNTransitionPair ltPair =\n // Note : setting the rate is not necessary since this is\n // only being used as an index.\n // LPNContinuousPair ltPair =\n LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);\n rv1l = ContinuousUtilities.chkDiv(-1 * oldEvent.getInequalityVariable().getConstant(), Z.getCurrentRate(ltPair), true);\n rv1u = ContinuousUtilities.chkDiv(oldEvent.getInequalityVariable().getConstant(), Z.getCurrentRate(ltPair), true);\n jZ = Z.getIndexByTransitionPair(ltPair);\n } else {\n // In this case, the event is a transition.\n Transition t = oldEvent.getTransition();\n // Create the indexing object. (See the Abstraction Function protion at the\n // top of the class for more details.)\n int lpnIndex = t.getLpn().getLpnIndex();\n int tranIndex = t.getIndex();\n // Package the results.\n LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);\n jZ = Z.getIndexByTransitionPair(ltPair);\n }\n // /* Both actions are predicate changes */\n // Both actions are predicate changes.\n if (e.isInequality() && oldEvent.isInequality()) {\n // /* Both predicates are on the same variable */\n // Extract the variable lists.\n ArrayList newList = e.getInequalityVariable().getContVariables();\n ArrayList oldList = oldEvent.getInequalityVariable().getContVariables();\n // Issue a warning if one of the lists has more than a single\n if (newList.size() > 1 && oldList.size() > 1) {\n System.err.println(\"Warning: One of the inequalities \" + e + \" \" + oldEvent + \" refers to more than one variable\");\n }\n // Both inequalities are on the same variables.\n if (newList.get(0).equals(oldList.get(0))) {\n if (rv1l > rv2l) {\n possible = false;\n } else // printf(\"Adding to erase list: \\n\");\n if (rv2l > rv1l) {\n workSet.remove(oldEvent);\n } else // printf(\"Adding to erase list: \\n\");\n if (rv1u > rv2u) {\n workSet.remove(oldEvent);\n } else {\n workSet.add(e);\n done = true;\n }\n } else // /* Predicates are on different variables */\n // Inequalities are on different variables.\n {\n // TODO : Check that the indecies must be reversed. I believe\n // they do since I think my representation is the transpose\n // of atacs. This will affect all the following statements.\n if (rv1l > rv2l + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else // printf(\"Adding to erase list: \");\n if (rv2l > rv1l + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n } else // printf(\"Adding to erase list: \\n\");\n if (rv1u > Z.getUpperBoundTrue(iZ) + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n } else if (rv2u > Z.getUpperBoundTrue(jZ) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else if (rv1l == rv2l + Z.getDbmEntry(jZ, iZ) && rv2l == rv1l + Z.getDbmEntry(iZ, jZ) && rv1u == rv2u + Z.getDbmEntry(iZ, jZ) && rv2u == rv1u + Z.getDbmEntry(jZ, iZ)) {\n workSet.add(e);\n }\n }\n } else // /* New action is predicate change, old is transition firing (case 3) */\n // New action is an inequality and the old even tis a transition (case 3).\n if (e.isInequality() && oldEvent.isTransition()) {\n // printf(\"Adding to erase list: \\n\");\n if (rv2l > -1 * Z.getLowerBoundbyTransition(e.getTransition()) + Z.getDbmEntry(iZ, jZ)) {\n // Probably can change this to refer directly to the zone.\n workSet.remove(oldEvent);\n } else if (rv2u > Z.getUpperBoundTrue(jZ) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n }\n } else // /* TODO: One more ugly case, is it needed? */\n // /* New action is transition firing, old is predicate change (case 4) */\n // New event is a transition firing, old event is an inequality change (case 4).\n if (e.isTransition() && oldEvent.isInequality()) {\n if (rv1l > (-1) * Z.getLowerBoundbyTransition(e.getTransition()) + Z.getDbmEntry(jZ, iZ)) {\n possible = false;\n } else // printf(\"Adding to erase list: \\n\");\n // Real one: fix the getting of the upper and lower bounds. Done\n if (rv1u > Z.getUpperBoundTrue(iZ) + Z.getDbmEntry(iZ, jZ)) {\n workSet.remove(oldEvent);\n }\n // /* TODO: one more ugly case, is it needed? */\n // I guess this one wasn't needed since it is not found in atacs.\n }\n }\n if (!(workSet.isEmpty())) {\n newE.add(workSet);\n }\n }\n // This part of the code is essentially copying the all the old event set into the new event set.\n // There might be a way around doing this by working directly on the set to begin with.\n // Moved to being done at the begining of the previous block.\n // // This collection should contain event sets, not transitions.\n // throw new IllegalArgumentException(\"The eventSet was a Transition object not an EventSet object.\");\n if (!done && possible) {\n eSet.add(e);\n newE.add(eSet);\n }\n E = newE;\n // printf(\"Event sets leaving:\\n\");\n return E;\n }\n\n @Override\n public int getVarIndex(int lpnIndex, String name) {\n return _lpnList[lpnIndex].getContinuousIndexMap().getValue(name);\n }\n\n /**\n * Adds a set item and explicitly sets a flag to remove the next set item\n * upon firing.\n * @param E\n * The list of current event sets.\n * @param e\n * The event to add.\n * @param s\n * The current state.\n * @param removeNext\n * True if afer firing this event, the next event should be removed from the\n * queue.\n * @return\n * The new event set.\n */\n // public static LpnTranList addSetItem(LpnTranList E, Event e, State s,\n /**\n * Updates the continuous variables that are set by firing a transition.\n * @param firedTran\n * \t\tThe transition that fired.\n * @param s\n * \t\tThe current (local) state.\n */\n public void updateContinuousAssignment(Transition firedTran, State s) {\n // Get the LPN.\n LPN lpn = _lpnList[firedTran.getLpn().getLpnIndex()];\n // Get the current values of the (local) state.\n HashMap currentValues = lpn.getAllVarsWithValuesAsString(s.getVariableVector());\n // Get all the continuous variable assignments.\n HashMap assignTrees = firedTran.getContAssignTrees();\n for (String contVar : assignTrees.keySet()) {\n // Get the bounds to assign the continuous variables.\n IntervalPair assignment = assignTrees.get(contVar).evaluateExprBound(currentValues, this, null);\n // Make the assignment.\n setContinuousBounds(contVar, lpn, assignment);\n }\n }\n\n /**\n * Updates the continuous variables according to the given values.\n * @param newContValues\n * \t\tThe new values of the continuous variables.\n */\n public void updateContinuousAssignment(ContinuousRecordSet newAssignValues) {\n /*\n\t\t * In dealing with the rates and continuous variables, there are four cases to consider. These cases\n\t\t * depend on whether the the old value of the 'current rate' is zero or non-zero and whether the\n\t\t * new value of the 'current rate' is zero or non-zero. \n\t\t * 0. old rate is zero, new rate is zero.\n\t\t * \t\tLookup the zero rate in the _rateZeroContinuous and add any new continuous assignments.\n\t\t * 1. old rate is zero, new rate is non-zero.\n\t\t * \t\tRemove the rate from the _rateZeroContinuous and add the zone.\n\t\t * 2. old rate is non-zero, new rate is zero.\n\t\t * \t\tAdd the variable with its upper and lower bounds to _rateZeroContinuous.\n\t\t * 3. old rate is non-zero, new rate is non-zero.\n\t\t * \t\tGet the LPNContinuousPair from the _indexToTimerPair and change the value.\n\t\t * \n\t\t * Note: If an assignment is made to the variable, then it should be considered as a\n\t\t * new variable.\n\t\t */\n // The updating of the rate-zero continuous variables is taken care of\n // by the copyRates. So just need to update the values in the zone.\n // This amounts to copying over the values from the old zone for\n // continuous variables that haven't changed and copying in\n // // Set the lower bound.\n // // Set the upper bound.\n // // Set the rate.\n // // Set the lower bound.\n // // Set the upper bound.\n // // Set the current rate.\n // // Set the upper and lower bounds for the rates.\n }\n\n /* (non-Javadoc)\n\t * @see verification.timed_state_exploration.zone.Zone#getLexicon()\n\t */\n /**\n * Gives an array that maps the index of a timer in the DBM to the timer's index.\n * @return\n * \t\tThe array that maps the index of a timer in the DBM to the timer's index.\n */\n /**\n * Calculates a warping value needed to warp a Zone. When a zone is being warped the form\n * r1*z2 - r1*z1 + r2*z1 becomes important in finding the new values of the zone. For example,\n *\n * @param z1\n * \t\tUpper bound or negative lower bound.\n * @param z2\n * \t\tRelative value.\n * @param r1\n * \t\tFirst ratio.\n * @param r2\n * \t\tSecond ratio.\n * @return\n * \t\tr1*z2 - r1*z1 + r2*z1\n */\n public static int warp(int z1, int z2, int r1, int r2) {\n /*\n\t\t * See \"Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets\"\n\t\t * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda\n\t\t * Section III.C for details on how this function is used and where it comes\n\t\t * from.\n\t\t */\n return r1 * z2 - r1 * z1 + r2 * z1;\n }\n\n /**\n * Warps this Zone with the aid of rate information from the previous Zone.\n *\n * @param oldZone\n * \t\tThe previous Zone.\n * @return\n * \t\tThe warped Zone.\n */\n @Override\n public void dbmWarp(Equivalence oldE) {\n Zone oldZone = (Zone) oldE;\n /*\n\t\t * See \"Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets\"\n\t\t * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda\n\t\t * Section III.C for details on how this function is used and where it comes\n\t\t * from.\n\t\t */\n // /* TODO: This appears to NOT work when INFIN is in the bounds?\n // Should I have to worry about this case? */\n // According to atacs comments, this appears to NOT work when\n // INFIN is in the bounds.\n // This portion of the code handles the warping of the relative\n // parts of the zone.\n for (int i = 1; i < dbmSize(); i++) {\n for (int j = i + 1; j < dbmSize(); j++) {\n double iVal, jVal, iWarp, jWarp, iXDot, jXDot;\n // Note : the iVal and the jVal correspond to the\n // alpha and beta describe in Scott Little's thesis.\n // /* deal w/ the fact that we might have continuous and discrete\n // Do some warping when dealing with the continuous variables.\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n // Calcualte the alpha value.\n iVal = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[i]) / (double) this.getCurrentRate(_indexToTimerPair[i])));\n // The old rate the zone was warped by.\n iWarp = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[i])));\n // The current rate rate of this continuous variable.\n iXDot = Math.floor(Math.abs((double) this.getCurrentRate(_indexToTimerPair[i])));\n // I'm not going to do any warping when the previous rate\n // is zero. This statement is a break to go to next i value\n // and not the next j.\n if (iWarp == 0) {\n break;\n }\n } else {\n // The current variable is a timer, so the new rate and old rate\n // are both 1. Hence we have\n iVal = 1.0;\n iWarp = 1.0;\n iXDot = 1.0;\n }\n // Do some warping of the second variable if it is a continuous variable.\n if (_indexToTimerPair[j] instanceof LPNContinuousPair) {\n // Calcualte the alpha value.\n jVal = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[j]) / (double) this.getCurrentRate(_indexToTimerPair[j])));\n // The old rate the zone was warped by.\n jWarp = Math.floor(Math.abs((double) oldZone.getCurrentRate(_indexToTimerPair[j])));\n // The current rate of this continuous variable.\n jXDot = Math.floor(Math.abs((double) this.getCurrentRate(_indexToTimerPair[j])));\n // I'm not going to do any warping when the previous rate is\n if (jWarp == 0) {\n continue;\n }\n } else {\n // The current variable is a timer, so the new rate and old rate\n // are both 1. Hence we have\n jVal = 1.0;\n jWarp = 1.0;\n jXDot = 1.0;\n }\n // The zone is warped differently depending on which of rate is\n // larger. See Scott Little's Thesis for more details.\n if (iWarp * jXDot > jWarp * iXDot) {\n setDbmEntry(j, i, (int) Math.ceil(((jWarp * getDbmEntry(j, i)) / jXDot) + ((-1 * jWarp * getDbmEntry(0, i) / jXDot)) + ((iWarp * getDbmEntry(0, i) / iXDot))));\n setDbmEntry(i, j, (int) Math.ceil(((jWarp * getDbmEntry(i, j)) / jXDot) + ((-1 * jWarp * getDbmEntry(i, 0) / jXDot)) + ((iWarp * getDbmEntry(i, 0) / iXDot))));\n } else {\n setDbmEntry(i, j, (int) Math.ceil(((iWarp * getDbmEntry(i, j)) / iXDot) + ((-1 * iWarp * getDbmEntry(0, j) / iXDot)) + ((jWarp * getDbmEntry(0, j) / jXDot))));\n setDbmEntry(j, i, (int) Math.ceil(((iWarp * getDbmEntry(j, i)) / iXDot) + ((-1 * iWarp * getDbmEntry(j, 0) / iXDot)) + ((jWarp * getDbmEntry(j, 0) / jXDot))));\n }\n }\n }\n // printf(\"After fixing up initial warp conditions.\\n\");\n // Handle the warping of the bounds.\n for (int i = 1; i < dbmSize(); i++) {\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n if (Math.abs(getDbmEntry(i, 0)) != INFINITY) {\n if (oldZone.getCurrentRate(_indexToTimerPair[i]) == 0) {\n // If the older rate was zero, then we just need to\n // divide by the new rate.\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(getDbmEntry(i, 0), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n } else {\n // Undo the old warping and introduce the new warping.\n // If the bound is infinite, then division does nothing.\n setDbmEntry(i, 0, ContinuousUtilities.chkDiv(Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i])) * getDbmEntry(i, 0), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n }\n }\n if (Math.abs(getDbmEntry(0, i)) != INFINITY) {\n if (oldZone.getCurrentRate(_indexToTimerPair[i]) == 0) {\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(getDbmEntry(0, i), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n } else {\n // Undo the old warping and introduce the new warping.\n // If the bound is inifite, then division does nothing.\n setDbmEntry(0, i, ContinuousUtilities.chkDiv(Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i])) * getDbmEntry(0, i), Math.abs(getCurrentRate(_indexToTimerPair[i])), true));\n }\n }\n }\n }\n // printf(\"After fixing up places.\\n\");\n for (int i = 1; i < dbmSize(); i++) {\n if (_indexToTimerPair[i] instanceof LPNContinuousPair) {\n // /* TBD: If i & j are both changing direction do we need to\n // remove the warp info? */\n // Handle the case when the warping takes us into negative space.\n if ((double) oldZone.getCurrentRate(_indexToTimerPair[i]) / (double) this.getCurrentRate(_indexToTimerPair[i]) < 0.0) {\n /* We are warping into the negative space, so swap the upper and \n\t\t\t\t\t * lower bounds.\n\t\t\t\t\t */\n int temp = getDbmEntry(i, 0);\n setDbmEntry(i, 0, getDbmEntry(0, i));\n setDbmEntry(0, i, temp);\n // Set the relationships to Infinity since nothing else is known.\n for (int j = 1; j < dbmSize(); j++) {\n if (i != j) {\n setDbmEntry(i, j, INFINITY);\n setDbmEntry(j, i, INFINITY);\n }\n }\n }\n }\n }\n // printf(\"After handling negative warps.\\n\");\n /* Do the nature of how I store things, I do not think I need to do\n\t\t\t * this portion.\n\t\t\t */\n }\n\n /**\n * The DiagonalNonZeroException extends the java.lang.RuntimerExpcetion.\n * The intention is for this exception to be thrown is a Zone has a non zero\n * entry appear on the diagonal.\n *\n * @author Andrew N. Fisher\n */\n public class DiagonalNonZeroException extends java.lang.RuntimeException {\n\n private static final long serialVersionUID = -3857736741611605411L;\n\n /**\n * Creates a DiagonalNonZeroException.\n * @param Message\n * \t\t\tThe message to be displayed when the exception is thrown.\n */\n public DiagonalNonZeroException(String Message) {\n super(Message);\n }\n }\n\n /**\n * This exception is thrown when trying to merge two zones whose corresponding timers\n * do not agree.\n * @author Andrew N. Fisher\n */\n // // TODO : Check if this class can be removed.\n // * Generated serialVersionUID\n /**\n * Clears out the lexicon.\n */\n public static IntervalPair parseRate(String rate) {\n String rateNoSpaces = rate.trim();\n // First check if the string is a single number.\n // // The string is a number, so set the upper and lower bounds equal.\n // First check for a comma (representing an interval input).\n int commaIndex = rateNoSpaces.indexOf(\",\");\n if (commaIndex < 0) {\n // Assume that the string is a constant. A NumberFormatException\n // will be thrown otherwise.\n int i = Integer.parseInt(rate);\n return new IntervalPair(i, i);\n }\n String lowerString = rateNoSpaces.substring(1, commaIndex).trim();\n String upperString = rateNoSpaces.substring(commaIndex + 1, rateNoSpaces.length() - 1).trim();\n return new IntervalPair(Integer.parseInt(lowerString), Integer.parseInt(upperString));\n }\n\n /**\n * Get the list of LhpnFile objects that this Zone depends on.\n * @return\n * \t\tThe lits of LhpnFile objects that this Zone depends on.\n */\n @Override\n public LPN[] get_lpnList() {\n return _lpnList;\n }\n\n /**\n * Performs a division of two integers and either takes the ceiling or the floor. Note :\n * The integers are converted to doubles for the division so the choice of ceiling or floor is\n * meaningful.\n * @param top\n * \t\tThe numerator.\n * @param bottom\n * \t\tThe denominator.\n * @param ceil\n * \t\tTrue indicates return the ceiling and false indicates return the floor.\n * @return\n * \t\tReturns the ceiling of top/bottom if ceil is true and the floor of top/bottom otherwise.\n */\n // * This method was taken from atacs/src/hpnrsg.c\n // System.out.println(\"Warning: Divided by zero.\");\n /**\n * Returns the current rate of the variable.\n * @param contVar\n * \t\tThe LPNTransitionPair referring to a continuous variable.\n * @return\n * \t\tThe current rate of the continuous variable refenced by the LPNTransitionPair.\n * @throws IllegalArgumentException\n * \t\tIf the LPNTransitionPair is not an instance of an LPNContinuousPair.\n */\n @Override\n public int getCurrentRate(LPNTransitionPair contVar) {\n if (!(contVar instanceof LPNContinuousPair)) {\n // The LPNTransitionsPair does not refer to a continuous variable, so yell.\n throw new IllegalArgumentException(\"Zone.getCurrentRate was called\" + \" on an LPNTransitionPair that was not an LPNContinuousPair.\");\n }\n LPNContinuousPair cV = (LPNContinuousPair) contVar;\n // Search for the pair in the zone.\n int index = Arrays.binarySearch(_indexToTimerPair, cV);\n if (index > 0) {\n // The continuous variable was found amongst the non zero rate continuous variables.\n // Grab that indexing object instead since it has the rate.\n cV = (LPNContinuousPair) _indexToTimerPair[index];\n return cV.getCurrentRate();\n }\n // Since the variable was not found in the non-zero rate continuous\n // variables, assume the rate is zero.\n return 0;\n }\n\n /**\n * Sets the current rate for a continuous variable. It sets the rate regardless of\n * whether the variable is in the rate zero portion of the Zone or not. But it\n * does not move variables in and out of the zone.\n * @param contVar\n * \t\tThe index of the variable whose rate is going to be set.\n * @param currentRate\n * \t\tThe value of the rate.\n */\n @Override\n public void setCurrentRate(LPNTransitionPair contVar, int currentRate) {\n if (!(contVar instanceof LPNContinuousPair)) {\n // The LPNTransitionsPair does not refer to a continuous variable, so yell.\n throw new IllegalArgumentException(\"Zone.getCurrentRate was called\" + \" on an LPNTransitionPair that was not an LPNContinuousPair.\");\n }\n LPNContinuousPair cV = (LPNContinuousPair) contVar;\n // Check for the current variable in the rate zero variables.\n VariableRangePair variableRange = _rateZeroContinuous.getValue(new LPNContAndRate(cV, new IntervalPair(0, 0)));\n if (variableRange != null) {\n LPNContinuousPair lcPair = _rateZeroContinuous.getKey(variableRange).get_lcPair();\n lcPair.setCurrentRate(currentRate);\n return;\n }\n // Check for the current variable in the Zone variables.\n int index = Arrays.binarySearch(_indexToTimerPair, contVar);\n if (index >= 0) {\n // The variable was found, set the rate.\n LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[index];\n lcPair.setCurrentRate(currentRate);\n }\n }\n\n /**\n * Adds a transition to a zone.\n * @param newTransitions\n * \t\t\tThe newly enabled transitions.\n * @return\n * \t\t\tThe result of adding the transition.\n */\n @Override\n public Zone addTransition(HashSet newTransitions, State[] localStates) {\n /*\n\t\t * The zone will remain the same for all the continuous variables.\n\t\t * The only thing that will change is a new transition will be added into the transitions.\n\t\t */\n // Create a Zone to alter.\n Zone newZone = new Zone();\n // Create a copy of the LPN list.\n newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n // Copy the rate zero continuous variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Create a copy of the current indexing pairs.\n newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + newTransitions.size()];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = _indexToTimerPair[i];\n }\n // Add the new transitions to the _indexToTimerPair list.\n // // Set up the index for the newTransitions list.\n int i = _indexToTimerPair.length;\n for (LPNTransitionPair ltPair : newTransitions) {\n newZone._indexToTimerPair[i++] = ltPair;\n }\n // Sort the _indexToTimerPair list.\n Arrays.sort(newZone._indexToTimerPair);\n // Create matrix.\n newZone._matrix = new int[newZone._indexToTimerPair.length + 1][newZone._indexToTimerPair.length + 1];\n // Convert the current transitions to a collection of transitions.\n HashSet oldTransitionSet = new HashSet();\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n oldTransitionSet.add(ltPair);\n }\n // Copy in the new transitions.\n newZone.copyTransitions(this, newTransitions, oldTransitionSet, localStates);\n return newZone;\n }\n\n /**\n * This method creates a zone identical to the current zone except all the current rates are turned to 1.\n * This is to provide a previous zone to the initial zone for warping.\n * @return\n * \t\tA zone identical to this zone with all rates set to 1.\n */\n private Zone beforeInitialZone() {\n Zone z = this.clone();\n for (int i = 1; i < z._indexToTimerPair.length; i++) {\n if (!(z._indexToTimerPair[i] instanceof LPNContinuousPair)) {\n break;\n }\n LPNContinuousPair lcPair = (LPNContinuousPair) z._indexToTimerPair[i];\n lcPair.setCurrentRate(1);\n }\n return z;\n }\n\n /**\n * Add a rate zero variable to the DBM portion of the zone. This method\n * is intended as an aid for when a rate zero variable gets assign a\n * non-zero rate.\n * @param ltContPair The continuous variable to move from the rate zero\n * variables.\n * @return The resulting Zone.\n */\n @Override\n public Zone moveOldRateZero(LPNContinuousPair ltContPair) {\n // Create a Zone to alter.\n Zone newZone = new Zone();\n // Create a copy of the LPN list.\n newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);\n // Copy the rate zero continuous variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Extract the continuous variable from the rate zero variables.\n LPNContAndRate rateZero = new LPNContAndRate(ltContPair, new IntervalPair(0, 0));\n // This gets the values for the continuous variable.\n VariableRangePair vrp = newZone._rateZeroContinuous.get(rateZero);\n IntervalPair values = vrp.get_range();\n // This replaces the rateZero with the one stored in the _rateZeroContinuous.\n // The purpose of this is to obtain the stored range of rates.\n rateZero = newZone._rateZeroContinuous.getKey(vrp);\n // Get the range of rates.\n IntervalPair rangeOfRates = rateZero.get_rateInterval();\n // Remove the continuous variable.\n newZone._rateZeroContinuous.delete(rateZero);\n // Create a copy of the current indexing pairs.\n newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + 1];\n for (int i = 0; i < _indexToTimerPair.length; i++) {\n newZone._indexToTimerPair[i] = _indexToTimerPair[i];\n }\n // Add the continuous variable to the list of variables/transition in the DBM.\n int numOfTransitions = _indexToTimerPair.length;\n newZone._indexToTimerPair[numOfTransitions] = ltContPair;\n // Sort the _indexToTimerPair list.\n Arrays.sort(newZone._indexToTimerPair);\n // Create matrix.\n newZone._matrix = new int[newZone._indexToTimerPair.length + 1][newZone._indexToTimerPair.length + 1];\n // Convert the current transitions to a collection of transitions.\n HashSet oldTransitionSet = new HashSet();\n for (LPNTransitionPair ltPair : _indexToTimerPair) {\n oldTransitionSet.add(ltPair);\n }\n // Copy in the new transitions.\n newZone.copyTransitions(this, new HashSet(), oldTransitionSet, null);\n // Get the index for the variable.\n int index = Arrays.binarySearch(newZone._indexToTimerPair, ltContPair);\n // Copy in the upper and lower bound of the old rate zero variable.\n // Copy in the range of rates.\n newZone.setLowerBoundbydbmIndex(index, rangeOfRates.get_LowerBound());\n newZone.setUpperBoundbydbmIndex(index, rangeOfRates.get_UpperBound());\n if (ltContPair.getCurrentRate() > 0) {\n // Set the upper and lower bounds.\n newZone.setDbmEntry(0, index, ContinuousUtilities.chkDiv(values.get_UpperBound(), ltContPair.getCurrentRate(), true));\n newZone.setDbmEntry(index, 0, ContinuousUtilities.chkDiv(-1 * values.get_LowerBound(), ltContPair.getCurrentRate(), true));\n } else {\n // Set the upper and lower bounds. Since the rate is zero\n // We swap the real upper and lower bounds.\n newZone.setDbmEntry(0, index, ContinuousUtilities.chkDiv(values.get_LowerBound(), ltContPair.getCurrentRate(), true));\n newZone.setDbmEntry(index, 0, ContinuousUtilities.chkDiv(-1 * values.get_UpperBound(), ltContPair.getCurrentRate(), true));\n }\n // Set the DBM to having no relating information for how this\n // variables relates to the other variables.\n for (int i = 1; i < newZone._indexToTimerPair.length; i++) {\n if (i == index) {\n continue;\n }\n newZone.setDbmEntry(index, i, Zone.INFINITY);\n newZone.setDbmEntry(i, index, Zone.INFINITY);\n }\n newZone.recononicalize();\n return newZone;\n }\n\n /**\n * This method removes the variable from the DBM portion of the\n * zone and adds the variable to the rate-zero portion of the\n * zone. The purpose of this method is to handle when a non-zero\n * rate variable is assigned a zero rate.\n * @param firedRate The new assignment for the variable.\n * @return The resulting zone.\n */\n @Override\n public Zone saveOutZeroRate(LPNContinuousPair firedRate) {\n // Check if the variable is in the zone.\n // We assume that the rate is already zero in this case\n // since it must be in the rate zero variables if it exists.\n int index = Arrays.binarySearch(this._indexToTimerPair, firedRate);\n if (index < 0) {\n System.err.println(\"A variable is getting its rate set to zero\");\n System.err.println(\"when the rate is already zero.\");\n return this;\n }\n // Create new zone\n Zone newZone = new Zone();\n // Copy the LPNs over.\n newZone._lpnList = new LPN[this._lpnList.length];\n for (int i = 0; i < this._lpnList.length; i++) {\n newZone._lpnList[i] = this._lpnList[i];\n }\n // Copy over the rate zero variables.\n newZone._rateZeroContinuous = this._rateZeroContinuous.clone();\n // Get the range of rates and values.\n IntervalPair rangeOfRates = this.getRateBounds(firedRate);\n IntervalPair rangeOfValues = this.getContinuousBounds(firedRate);\n // Create the key and value pairs for the rate zero continuous variable.\n LPNContAndRate lcar = new LPNContAndRate(firedRate.clone(), rangeOfRates);\n VariableRangePair vrPair = new VariableRangePair(this._lpnList[firedRate.get_lpnIndex()].getContVar(firedRate.get_ContinuousIndex()), rangeOfValues);\n newZone._rateZeroContinuous.insert(lcar, vrPair);\n // Copy over the pairs, skipping the new rate zero.\n newZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length - 1];\n int offset = 0;\n for (int i = 0; i < newZone._indexToTimerPair.length; i++) {\n if (i == index) {\n offset++;\n }\n newZone._indexToTimerPair[i] = this._indexToTimerPair[i + offset].clone();\n }\n // Copy over the DBM\n newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];\n int offseti = 0;\n int offsetj = 0;\n for (int i = 0; i < newZone.matrixSize(); i++) {\n if (i == index + 1) {\n offseti++;\n }\n offsetj = 0;\n for (int j = 0; j < newZone.matrixSize(); j++) {\n if (j == index + 1) {\n offsetj++;\n }\n newZone._matrix[i][j] = this._matrix[i + offseti][j + offsetj];\n }\n }\n return newZone;\n }\n\n @Override\n public int getIndexByTransitionPair(LPNTransitionPair ltPair) {\n return Arrays.binarySearch(_indexToTimerPair, ltPair);\n }\n /**\n * Determines whether time has advanced far enough for an inequality to change\n * truth value.\n * @param ineq\n * \t\tThe inequality to test whether its truth value can change.\n * @param localState\n * \t\tThe state associated with the inequality.\n * @return\n * \t\tTrue if the inequality can change truth value, false otherwise.\n */\n // // Find the index of the continuous variable this inequality refers to.\n // // I'm assuming there is a single variable.\n // // Package up the information into a the index. Note the current rate doesn't matter.\n // // Get the current rate.\n // // Get the current value of the inequality. This requires looking into the current state.\n // // Get the Zone index of the variable.\n // //\t\tbool lhpnPredCanChange(ineqADT ineq,lhpnZoneADT z,lhpnRateADT r,\n // //warn(\"An inequality produced a place not in the zone.\");\n // // First check cases when the rate is negative.\n // //warn(\"An inequality produced a place not in the zone.\");\n}\n"} {"task_id": "Java_3039", "language": "Java", "task_type": "method_signature", "source_file": "java/github/CoprHD/coprhd-controller/exportLibraries/storagedrivers/3par/src/main/java/com/emc/storageos/hp3par/impl/HP3PARCloneHelper.java", "mask_start_position": 6821, "mask_end_position": 6870, "canonical_solution": "public void setHp3parUtil(HP3PARUtil hp3parUtil) ", "pre_mask_code": "/*\n * All Rights Reserved\n */\npackage com.emc.storageos.hp3par.impl;\n\nimport java.util.List;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.emc.storageos.hp3par.command.VolumeDetailsCommandResult;\nimport com.emc.storageos.hp3par.utils.HP3PARConstants;\nimport com.emc.storageos.hp3par.utils.HP3PARUtil;\nimport com.emc.storageos.storagedriver.DriverTask;\nimport com.emc.storageos.storagedriver.Registry;\nimport com.emc.storageos.storagedriver.model.VolumeClone;\nimport com.emc.storageos.storagedriver.storagecapabilities.StorageCapabilities;\n\npublic class HP3PARCloneHelper {\n\n private static final Logger _log = LoggerFactory.getLogger(HP3PARCloneHelper.class);\n\n private HP3PARUtil hp3parUtil;\n\n public DriverTask createVolumeClone(List clones, StorageCapabilities capabilities, DriverTask task, Registry driverRegistry) {\n String storageSystemId = null;\n HP3PARApi hp3parApi = null;\n for (VolumeClone clone : clones) {\n try {\n _log.info(\"3PARDriver: createVolumeClone for storage system native id {}, clone parent name {} , clone name {} - start\", clone.toString(), clone.getParentId(), clone.getDisplayName());\n String localStorageSystemId = clone.getStorageSystemId();\n // get Api client\n if (storageSystemId == null || storageSystemId != localStorageSystemId) {\n storageSystemId = localStorageSystemId;\n hp3parApi = hp3parUtil.getHP3PARDeviceFromNativeId(localStorageSystemId, driverRegistry);\n }\n VolumeDetailsCommandResult volResult = null;\n // Create volume clone\n hp3parApi.createPhysicalCopy(clone.getParentId(), clone.getDisplayName(), clone.getStoragePoolId());\n volResult = hp3parApi.getVolumeDetails(clone.getDisplayName());\n // Actual size of the volume in array\n clone.setProvisionedCapacity(volResult.getSizeMiB() * HP3PARConstants.MEGA_BYTE);\n clone.setWwn(volResult.getWwn());\n // required for volume\n clone.setNativeId(volResult.getName());\n // delete\n clone.setDeviceLabel(clone.getDisplayName());\n clone.setAccessStatus(clone.getAccessStatus());\n clone.setReplicationState(VolumeClone.ReplicationState.SYNCHRONIZED);\n task.setStatus(DriverTask.TaskStatus.READY);\n _log.info(\"createVolumeClone for storage system native id {}, volume clone name {} - end\", clone.getStorageSystemId(), clone.getDisplayName());\n } catch (Exception e) {\n String msg = String.format(\"3PARDriver: createVolumeClone Unable to create volume clone name %s for parent base volume id %s whose storage system native id is %s; Error: %s.\\n\", clone.getDisplayName(), clone.getParentId(), clone.getStorageSystemId(), e.getMessage());\n _log.info(\"createVolumeClone exception message {} \", e.getMessage());\n _log.error(msg);\n task.setMessage(msg);\n task.setStatus(DriverTask.TaskStatus.PARTIALLY_FAILED);\n e.printStackTrace();\n }\n }\n // end for each volume clone creation\n return task;\n }\n\n public DriverTask restoreFromClone(List clones, Registry driverRegistry, DriverTask task) {\n String storageSystemId = null;\n HP3PARApi hp3parApi = null;\n // Executing restore for each requested volume clone (in one or more\n for (VolumeClone clone : clones) {\n try {\n _log.info(\"3PARDriver: restoreFromClone for storage system system id {}, clone name {} , native id {} - start\", clone.getStorageSystemId(), clone.getDisplayName(), clone.getNativeId());\n String localStorageSystemId = clone.getStorageSystemId();\n // get Api client\n if (storageSystemId == null || storageSystemId != localStorageSystemId) {\n storageSystemId = localStorageSystemId;\n hp3parApi = hp3parUtil.getHP3PARDeviceFromNativeId(localStorageSystemId, driverRegistry);\n }\n // restore virtual copy\n hp3parApi.restorePhysicalCopy(clone.getNativeId());\n task.setStatus(DriverTask.TaskStatus.READY);\n _log.info(\"3PARDriver: restoreFromClone successful for storage system id {}, volume clone native id {} - end\", clone.getStorageSystemId(), clone.getNativeId());\n } catch (Exception e) {\n String msg = String.format(\"3PARDriver:restoreFromClone Unable to restore volume clone display name %s with native id %s for storage system id %s; Error: %s.\\n\", clone.getDisplayName(), clone.getNativeId(), clone.getStorageSystemId(), e.getMessage());\n _log.error(msg);\n task.setMessage(msg);\n task.setStatus(DriverTask.TaskStatus.PARTIALLY_FAILED);\n e.printStackTrace();\n }\n }\n // end for each restore clone\n return task;\n }\n\n public DriverTask deleteVolumeClone(VolumeClone clone, DriverTask task, Registry driverRegistry) {\n String storageSystemId = null;\n HP3PARApi hp3parApi = null;\n try {\n _log.info(\"3PARDriver: deleteVolumeClone for storage system native id {}, volume clone name {} , native id {} - start\", clone.getStorageSystemId(), clone.getDisplayName(), clone.getNativeId());\n String localStorageSystemId = clone.getStorageSystemId();\n // get Api client\n if (storageSystemId == null || storageSystemId != localStorageSystemId) {\n storageSystemId = localStorageSystemId;\n hp3parApi = hp3parUtil.getHP3PARDeviceFromNativeId(localStorageSystemId, driverRegistry);\n }\n // Delete physical copy\n hp3parApi.deletePhysicalCopy(clone.getDeviceLabel());\n task.setStatus(DriverTask.TaskStatus.READY);\n _log.info(\"3PARDriver: deleteVolumeClone for storage system native id {}, volume clone name {} - end\", clone.getStorageSystemId(), clone.getDisplayName());\n } catch (Exception e) {\n String msg = String.format(\"3PARDriver: deleteVolumeClone Unable to delete volume clone name %s with native id %s for storage system native id %s; Error: %s.\\n\", clone.getDisplayName(), clone.getNativeId(), clone.getStorageSystemId(), e.getMessage());\n _log.error(msg);\n task.setMessage(msg);\n task.setStatus(DriverTask.TaskStatus.PARTIALLY_FAILED);\n e.printStackTrace();\n }\n return task;\n }\n\n public HP3PARUtil getHp3parUtil() {\n return hp3parUtil;\n }\n\n ", "post_mask_code": "{\n this.hp3parUtil = hp3parUtil;\n }\n}\n"} {"task_id": "Java_3040", "language": "Java", "task_type": "method_body", "source_file": "java/github/CoprHD/coprhd-controller/exportLibraries/storagedrivers/3par/src/main/java/com/emc/storageos/hp3par/impl/HP3PARCloneHelper.java", "mask_start_position": 6870, "mask_end_position": 6915, "canonical_solution": "{\n this.hp3parUtil = hp3parUtil;\n }", "pre_mask_code": "/*\n * All Rights Reserved\n */\npackage com.emc.storageos.hp3par.impl;\n\nimport java.util.List;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.emc.storageos.hp3par.command.VolumeDetailsCommandResult;\nimport com.emc.storageos.hp3par.utils.HP3PARConstants;\nimport com.emc.storageos.hp3par.utils.HP3PARUtil;\nimport com.emc.storageos.storagedriver.DriverTask;\nimport com.emc.storageos.storagedriver.Registry;\nimport com.emc.storageos.storagedriver.model.VolumeClone;\nimport com.emc.storageos.storagedriver.storagecapabilities.StorageCapabilities;\n\npublic class HP3PARCloneHelper {\n\n private static final Logger _log = LoggerFactory.getLogger(HP3PARCloneHelper.class);\n\n private HP3PARUtil hp3parUtil;\n\n public DriverTask createVolumeClone(List clones, StorageCapabilities capabilities, DriverTask task, Registry driverRegistry) {\n String storageSystemId = null;\n HP3PARApi hp3parApi = null;\n for (VolumeClone clone : clones) {\n try {\n _log.info(\"3PARDriver: createVolumeClone for storage system native id {}, clone parent name {} , clone name {} - start\", clone.toString(), clone.getParentId(), clone.getDisplayName());\n String localStorageSystemId = clone.getStorageSystemId();\n // get Api client\n if (storageSystemId == null || storageSystemId != localStorageSystemId) {\n storageSystemId = localStorageSystemId;\n hp3parApi = hp3parUtil.getHP3PARDeviceFromNativeId(localStorageSystemId, driverRegistry);\n }\n VolumeDetailsCommandResult volResult = null;\n // Create volume clone\n hp3parApi.createPhysicalCopy(clone.getParentId(), clone.getDisplayName(), clone.getStoragePoolId());\n volResult = hp3parApi.getVolumeDetails(clone.getDisplayName());\n // Actual size of the volume in array\n clone.setProvisionedCapacity(volResult.getSizeMiB() * HP3PARConstants.MEGA_BYTE);\n clone.setWwn(volResult.getWwn());\n // required for volume\n clone.setNativeId(volResult.getName());\n // delete\n clone.setDeviceLabel(clone.getDisplayName());\n clone.setAccessStatus(clone.getAccessStatus());\n clone.setReplicationState(VolumeClone.ReplicationState.SYNCHRONIZED);\n task.setStatus(DriverTask.TaskStatus.READY);\n _log.info(\"createVolumeClone for storage system native id {}, volume clone name {} - end\", clone.getStorageSystemId(), clone.getDisplayName());\n } catch (Exception e) {\n String msg = String.format(\"3PARDriver: createVolumeClone Unable to create volume clone name %s for parent base volume id %s whose storage system native id is %s; Error: %s.\\n\", clone.getDisplayName(), clone.getParentId(), clone.getStorageSystemId(), e.getMessage());\n _log.info(\"createVolumeClone exception message {} \", e.getMessage());\n _log.error(msg);\n task.setMessage(msg);\n task.setStatus(DriverTask.TaskStatus.PARTIALLY_FAILED);\n e.printStackTrace();\n }\n }\n // end for each volume clone creation\n return task;\n }\n\n public DriverTask restoreFromClone(List clones, Registry driverRegistry, DriverTask task) {\n String storageSystemId = null;\n HP3PARApi hp3parApi = null;\n // Executing restore for each requested volume clone (in one or more\n for (VolumeClone clone : clones) {\n try {\n _log.info(\"3PARDriver: restoreFromClone for storage system system id {}, clone name {} , native id {} - start\", clone.getStorageSystemId(), clone.getDisplayName(), clone.getNativeId());\n String localStorageSystemId = clone.getStorageSystemId();\n // get Api client\n if (storageSystemId == null || storageSystemId != localStorageSystemId) {\n storageSystemId = localStorageSystemId;\n hp3parApi = hp3parUtil.getHP3PARDeviceFromNativeId(localStorageSystemId, driverRegistry);\n }\n // restore virtual copy\n hp3parApi.restorePhysicalCopy(clone.getNativeId());\n task.setStatus(DriverTask.TaskStatus.READY);\n _log.info(\"3PARDriver: restoreFromClone successful for storage system id {}, volume clone native id {} - end\", clone.getStorageSystemId(), clone.getNativeId());\n } catch (Exception e) {\n String msg = String.format(\"3PARDriver:restoreFromClone Unable to restore volume clone display name %s with native id %s for storage system id %s; Error: %s.\\n\", clone.getDisplayName(), clone.getNativeId(), clone.getStorageSystemId(), e.getMessage());\n _log.error(msg);\n task.setMessage(msg);\n task.setStatus(DriverTask.TaskStatus.PARTIALLY_FAILED);\n e.printStackTrace();\n }\n }\n // end for each restore clone\n return task;\n }\n\n public DriverTask deleteVolumeClone(VolumeClone clone, DriverTask task, Registry driverRegistry) {\n String storageSystemId = null;\n HP3PARApi hp3parApi = null;\n try {\n _log.info(\"3PARDriver: deleteVolumeClone for storage system native id {}, volume clone name {} , native id {} - start\", clone.getStorageSystemId(), clone.getDisplayName(), clone.getNativeId());\n String localStorageSystemId = clone.getStorageSystemId();\n // get Api client\n if (storageSystemId == null || storageSystemId != localStorageSystemId) {\n storageSystemId = localStorageSystemId;\n hp3parApi = hp3parUtil.getHP3PARDeviceFromNativeId(localStorageSystemId, driverRegistry);\n }\n // Delete physical copy\n hp3parApi.deletePhysicalCopy(clone.getDeviceLabel());\n task.setStatus(DriverTask.TaskStatus.READY);\n _log.info(\"3PARDriver: deleteVolumeClone for storage system native id {}, volume clone name {} - end\", clone.getStorageSystemId(), clone.getDisplayName());\n } catch (Exception e) {\n String msg = String.format(\"3PARDriver: deleteVolumeClone Unable to delete volume clone name %s with native id %s for storage system native id %s; Error: %s.\\n\", clone.getDisplayName(), clone.getNativeId(), clone.getStorageSystemId(), e.getMessage());\n _log.error(msg);\n task.setMessage(msg);\n task.setStatus(DriverTask.TaskStatus.PARTIALLY_FAILED);\n e.printStackTrace();\n }\n return task;\n }\n\n public HP3PARUtil getHp3parUtil() {\n return hp3parUtil;\n }\n\n public void setHp3parUtil(HP3PARUtil hp3parUtil) ", "post_mask_code": "\n}\n"} {"task_id": "Java_3041", "language": "Java", "task_type": "single_line", "source_file": "java/github/CoprHD/coprhd-controller/exportLibraries/storagedrivers/3par/src/main/java/com/emc/storageos/hp3par/impl/HP3PARCloneHelper.java", "mask_start_position": 3310, "mask_end_position": 3318, "canonical_solution": "rn task;", "pre_mask_code": "/*\n * All Rights Reserved\n */\npackage com.emc.storageos.hp3par.impl;\n\nimport java.util.List;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.emc.storageos.hp3par.command.VolumeDetailsCommandResult;\nimport com.emc.storageos.hp3par.utils.HP3PARConstants;\nimport com.emc.storageos.hp3par.utils.HP3PARUtil;\nimport com.emc.storageos.storagedriver.DriverTask;\nimport com.emc.storageos.storagedriver.Registry;\nimport com.emc.storageos.storagedriver.model.VolumeClone;\nimport com.emc.storageos.storagedriver.storagecapabilities.StorageCapabilities;\n\npublic class HP3PARCloneHelper {\n\n private static final Logger _log = LoggerFactory.getLogger(HP3PARCloneHelper.class);\n\n private HP3PARUtil hp3parUtil;\n\n public DriverTask createVolumeClone(List clones, StorageCapabilities capabilities, DriverTask task, Registry driverRegistry) {\n String storageSystemId = null;\n HP3PARApi hp3parApi = null;\n for (VolumeClone clone : clones) {\n try {\n _log.info(\"3PARDriver: createVolumeClone for storage system native id {}, clone parent name {} , clone name {} - start\", clone.toString(), clone.getParentId(), clone.getDisplayName());\n String localStorageSystemId = clone.getStorageSystemId();\n // get Api client\n if (storageSystemId == null || storageSystemId != localStorageSystemId) {\n storageSystemId = localStorageSystemId;\n hp3parApi = hp3parUtil.getHP3PARDeviceFromNativeId(localStorageSystemId, driverRegistry);\n }\n VolumeDetailsCommandResult volResult = null;\n // Create volume clone\n hp3parApi.createPhysicalCopy(clone.getParentId(), clone.getDisplayName(), clone.getStoragePoolId());\n volResult = hp3parApi.getVolumeDetails(clone.getDisplayName());\n // Actual size of the volume in array\n clone.setProvisionedCapacity(volResult.getSizeMiB() * HP3PARConstants.MEGA_BYTE);\n clone.setWwn(volResult.getWwn());\n // required for volume\n clone.setNativeId(volResult.getName());\n // delete\n clone.setDeviceLabel(clone.getDisplayName());\n clone.setAccessStatus(clone.getAccessStatus());\n clone.setReplicationState(VolumeClone.ReplicationState.SYNCHRONIZED);\n task.setStatus(DriverTask.TaskStatus.READY);\n _log.info(\"createVolumeClone for storage system native id {}, volume clone name {} - end\", clone.getStorageSystemId(), clone.getDisplayName());\n } catch (Exception e) {\n String msg = String.format(\"3PARDriver: createVolumeClone Unable to create volume clone name %s for parent base volume id %s whose storage system native id is %s; Error: %s.\\n\", clone.getDisplayName(), clone.getParentId(), clone.getStorageSystemId(), e.getMessage());\n _log.info(\"createVolumeClone exception message {} \", e.getMessage());\n _log.error(msg);\n task.setMessage(msg);\n task.setStatus(DriverTask.TaskStatus.PARTIALLY_FAILED);\n e.printStackTrace();\n }\n }\n // end for each volume clone creation\n retu", "post_mask_code": "\n }\n\n public DriverTask restoreFromClone(List clones, Registry driverRegistry, DriverTask task) {\n String storageSystemId = null;\n HP3PARApi hp3parApi = null;\n // Executing restore for each requested volume clone (in one or more\n for (VolumeClone clone : clones) {\n try {\n _log.info(\"3PARDriver: restoreFromClone for storage system system id {}, clone name {} , native id {} - start\", clone.getStorageSystemId(), clone.getDisplayName(), clone.getNativeId());\n String localStorageSystemId = clone.getStorageSystemId();\n // get Api client\n if (storageSystemId == null || storageSystemId != localStorageSystemId) {\n storageSystemId = localStorageSystemId;\n hp3parApi = hp3parUtil.getHP3PARDeviceFromNativeId(localStorageSystemId, driverRegistry);\n }\n // restore virtual copy\n hp3parApi.restorePhysicalCopy(clone.getNativeId());\n task.setStatus(DriverTask.TaskStatus.READY);\n _log.info(\"3PARDriver: restoreFromClone successful for storage system id {}, volume clone native id {} - end\", clone.getStorageSystemId(), clone.getNativeId());\n } catch (Exception e) {\n String msg = String.format(\"3PARDriver:restoreFromClone Unable to restore volume clone display name %s with native id %s for storage system id %s; Error: %s.\\n\", clone.getDisplayName(), clone.getNativeId(), clone.getStorageSystemId(), e.getMessage());\n _log.error(msg);\n task.setMessage(msg);\n task.setStatus(DriverTask.TaskStatus.PARTIALLY_FAILED);\n e.printStackTrace();\n }\n }\n // end for each restore clone\n return task;\n }\n\n public DriverTask deleteVolumeClone(VolumeClone clone, DriverTask task, Registry driverRegistry) {\n String storageSystemId = null;\n HP3PARApi hp3parApi = null;\n try {\n _log.info(\"3PARDriver: deleteVolumeClone for storage system native id {}, volume clone name {} , native id {} - start\", clone.getStorageSystemId(), clone.getDisplayName(), clone.getNativeId());\n String localStorageSystemId = clone.getStorageSystemId();\n // get Api client\n if (storageSystemId == null || storageSystemId != localStorageSystemId) {\n storageSystemId = localStorageSystemId;\n hp3parApi = hp3parUtil.getHP3PARDeviceFromNativeId(localStorageSystemId, driverRegistry);\n }\n // Delete physical copy\n hp3parApi.deletePhysicalCopy(clone.getDeviceLabel());\n task.setStatus(DriverTask.TaskStatus.READY);\n _log.info(\"3PARDriver: deleteVolumeClone for storage system native id {}, volume clone name {} - end\", clone.getStorageSystemId(), clone.getDisplayName());\n } catch (Exception e) {\n String msg = String.format(\"3PARDriver: deleteVolumeClone Unable to delete volume clone name %s with native id %s for storage system native id %s; Error: %s.\\n\", clone.getDisplayName(), clone.getNativeId(), clone.getStorageSystemId(), e.getMessage());\n _log.error(msg);\n task.setMessage(msg);\n task.setStatus(DriverTask.TaskStatus.PARTIALLY_FAILED);\n e.printStackTrace();\n }\n return task;\n }\n\n public HP3PARUtil getHp3parUtil() {\n return hp3parUtil;\n }\n\n public void setHp3parUtil(HP3PARUtil hp3parUtil) {\n this.hp3parUtil = hp3parUtil;\n }\n}\n"} {"task_id": "Java_3042", "language": "Java", "task_type": "method_signature", "source_file": "java/github/MIT-PAC/droidsafe-src/modeling/api/android/preference/PreferenceManager.java", "mask_start_position": 33605, "mask_end_position": 33939, "canonical_solution": "@DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.766 -0500\", hash_original_method = \"6FD57C464C4DA57829A6C2B52E45A452\", hash_generated_method = \"6FD57C464C4DA57829A6C2B52E45A452\")\n void dispatchActivityStop() ", "pre_mask_code": "/*\n * \n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://example.com\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * ** THIS FILE HAS BEEN MODIFIED FROM THE ORIGINAL BY THE DROIDSAFE PROJECT. ****\n */\npackage android.preference;\n\n// Droidsafe Imports\nimport droidsafe.runtime.*;\nimport droidsafe.helpers.*;\nimport android.util.Log;\nimport droidsafe.annotations.*;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.content.pm.ActivityInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.PackageManager.NameNotFoundException;\nimport android.content.pm.ResolveInfo;\nimport android.content.res.XmlResourceParser;\nimport android.os.Bundle;\n\npublic class PreferenceManager {\n\n /**\n * Gets a SharedPreferences instance that points to the default file that is\n * used by the preference framework in the given context.\n *\n * @param context The context of the preferences whose values are wanted.\n * @return A SharedPreferences instance that can be used to retrieve and\n * listen to values of the preferences.\n */\n @DSComment(\"From safe class list\")\n @DSSafe(DSCat.SAFE_LIST)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.726 -0500\", hash_original_method = \"DEE839A83C4B35ACEA8CCC2B71E2B5D1\", hash_generated_method = \"2B16C131215B04C3D72C14303B6B379E\")\n public static SharedPreferences getDefaultSharedPreferences(Context context) {\n return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.728 -0500\", hash_original_method = \"42C9CE230DD05245AC0F1F15B9BA0F77\", hash_generated_method = \"C0A43771BC0878E5F7FF1D24F0A68563\")\n private static String getDefaultSharedPreferencesName(Context context) {\n return context.getPackageName() + \"_preferences\";\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.730 -0500\", hash_original_method = \"9A4A0B76FBD75A7A2387EF85E0D2FD54\", hash_generated_method = \"D84FC8AF76E7CF2269D44A6A6D9A3736\")\n private static int getDefaultSharedPreferencesMode() {\n return Context.MODE_PRIVATE;\n }\n\n /**\n * Sets the default values from a preference hierarchy in XML. This should\n * be called by the application's main activity.\n *

\n * If {@code readAgain} is false, this will only set the default values if this\n * method has never been called in the past (or the\n * {@link #KEY_HAS_SET_DEFAULT_VALUES} in the default value shared\n * preferences file is false). To attempt to set the default values again\n * bypassing this check, set {@code readAgain} to true.\n *\n * @param context The context of the shared preferences.\n * @param resId The resource ID of the preference hierarchy XML file.\n * @param readAgain Whether to re-read the default values.\n *

\n * Note: this will NOT reset preferences back to their default\n * values. For that functionality, use\n * {@link PreferenceManager#getDefaultSharedPreferences(Context)}\n * and clear it followed by a call to this method with this\n * parameter set to true.\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSafe(DSCat.SAFE_LIST)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.739 -0500\", hash_original_method = \"1B08E289995C6C21F5C2BC4F9B6F5187\", hash_generated_method = \"3DC84A33A3C2DB62DE5115DFA6B9F88B\")\n public static void setDefaultValues(Context context, int resId, boolean readAgain) {\n // Use the default shared preferences name and mode\n setDefaultValues(context, getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode(), resId, readAgain);\n }\n\n /**\n * Similar to {@link #setDefaultValues(Context, int, boolean)} but allows\n * the client to provide the filename and mode of the shared preferences\n * file.\n *\n * @see #setDefaultValues(Context, int, boolean)\n * @see #setSharedPreferencesName(String)\n * @see #setSharedPreferencesMode(int)\n */\n @DSSafe(DSCat.SAFE_OTHERS)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.741 -0500\", hash_original_method = \"9646A9372ECC55871733A680E62A72CA\", hash_generated_method = \"2F9BBD3261B2D934E006F58101CB7E9C\")\n public static void setDefaultValues(Context context, String sharedPreferencesName, int sharedPreferencesMode, int resId, boolean readAgain) {\n final SharedPreferences defaultValueSp = context.getSharedPreferences(KEY_HAS_SET_DEFAULT_VALUES, Context.MODE_PRIVATE);\n if (readAgain || !defaultValueSp.getBoolean(KEY_HAS_SET_DEFAULT_VALUES, false)) {\n final PreferenceManager pm = new PreferenceManager(context);\n pm.setSharedPreferencesName(sharedPreferencesName);\n pm.setSharedPreferencesMode(sharedPreferencesMode);\n pm.inflateFromResource(context, resId, null);\n SharedPreferences.Editor editor = defaultValueSp.edit().putBoolean(KEY_HAS_SET_DEFAULT_VALUES, true);\n try {\n editor.apply();\n } catch (AbstractMethodError unused) {\n // The app injected its own pre-Gingerbread\n // SharedPreferences.Editor implementation without\n // an apply method.\n editor.commit();\n }\n }\n }\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.652 -0500\", hash_original_field = \"3A3BD45FA93DD50F7F6C52D2CEF15DB2\", hash_generated_field = \"7AAEA04E4548D5AB6EC8143F21A30EA9\")\n private static final String TAG = \"PreferenceManager\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.654 -0500\", hash_original_field = \"F86CBB3D5E7D46D5EC5C061B27A4EB7F\", hash_generated_field = \"6C182C497B18AE33867D48A4D7F5655E\")\n public static final String METADATA_KEY_PREFERENCES = \"android.preference\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.656 -0500\", hash_original_field = \"A25C8F9EA6A0FB10147CB42E8AE48EF6\", hash_generated_field = \"99247B06873D9B62D5B8F33E5FB96366\")\n public static final String KEY_HAS_SET_DEFAULT_VALUES = \"_has_set_default_values\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.658 -0500\", hash_original_field = \"3895D7E6DB5042DA7856DC78E391C7B9\", hash_generated_field = \"B0D69375984D6EE7DC93AC12DB4DFC55\")\n private Activity mActivity;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.661 -0500\", hash_original_field = \"8520498A009FD770816A73BC7BBAAE33\", hash_generated_field = \"CFB43EBA13761D69B30BE1C8ABC90FE3\")\n private PreferenceFragment mFragment;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.663 -0500\", hash_original_field = \"B997E37019471EC8FC5B98148C7A8AD7\", hash_generated_field = \"C458E619396054F78BC926FB81B4386D\")\n private Context mContext;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.665 -0500\", hash_original_field = \"94D2C61B90F9DDCEA6229CFD1BD4B5A5\", hash_generated_field = \"5707822036BF051C0059AD070444BD58\")\n private long mNextId = 0;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.667 -0500\", hash_original_field = \"0BEC202ACD2F4B80A9D91BEF44E417AC\", hash_generated_field = \"AD359E85C996698973B9458D92AF4B64\")\n private int mNextRequestCode;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.669 -0500\", hash_original_field = \"6863CBC1FD02A5848172EE011B9C880B\", hash_generated_field = \"E69BF347D3F561905392BD5BBB86A4AF\")\n private SharedPreferences mSharedPreferences;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.671 -0500\", hash_original_field = \"C2C898D216011536ABB52408727E0074\", hash_generated_field = \"93BFA57AAD9A25C531F3726BE9E311D1\")\n private SharedPreferences.Editor mEditor;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.673 -0500\", hash_original_field = \"DD8CF6ABD3E3C3CF856EF58396F040C3\", hash_generated_field = \"0870CFBDAD0F12B21EFE736694E5D5A0\")\n private boolean mNoCommit;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.675 -0500\", hash_original_field = \"84C67C1FD7D5449453BD7928216DE986\", hash_generated_field = \"08A9F51924058A9BDDEB8AE59F95CBF8\")\n private String mSharedPreferencesName;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.677 -0500\", hash_original_field = \"A3A8925479C449E7BF4F11709ABEAFA6\", hash_generated_field = \"3DFD0E17BB5556DF650F1E4262E37691\")\n private int mSharedPreferencesMode;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.679 -0500\", hash_original_field = \"FA341E6EF4A389944B6ABCC0C00AA260\", hash_generated_field = \"6929FA68B759CC402927F67ADE03851B\")\n private PreferenceScreen mPreferenceScreen;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.681 -0500\", hash_original_field = \"5A55F2E03C7E028B9F56681221DAC65B\", hash_generated_field = \"759FE206EC137F2D102DEE69CB506E29\")\n private List mActivityResultListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.684 -0500\", hash_original_field = \"B48C98E3D9D54A0CB2952B7439998405\", hash_generated_field = \"AB511ABA80C53F6AD5EC1856C35DAF7F\")\n private List mActivityStopListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.686 -0500\", hash_original_field = \"C29EDB5974FA1CC8018E563C739E55BF\", hash_generated_field = \"ED711A008E3B4CD7A93067555688693E\")\n private List mActivityDestroyListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.688 -0500\", hash_original_field = \"DDDDE82983F75A043C150207C23DA1FF\", hash_generated_field = \"EEC46A0D6BAD420AFB426C404E85D2BA\")\n private List mPreferencesScreens;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.690 -0500\", hash_original_field = \"7B1980F7CD2856B99E6CF8987DD8E986\", hash_generated_field = \"420F1647C8F11E826C9DE0A838CD7533\")\n private OnPreferenceTreeClickListener mOnPreferenceTreeClickListener;\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.693 -0500\", hash_original_method = \"A48679E26B4CF910ADEF8C7563331346\", hash_generated_method = \"A48679E26B4CF910ADEF8C7563331346\")\n PreferenceManager(Activity activity, int firstRequestCode) {\n mActivity = activity;\n mNextRequestCode = firstRequestCode;\n init(activity);\n }\n\n /**\n * This constructor should ONLY be used when getting default values from\n * an XML preference hierarchy.\n *

\n * The {@link PreferenceManager#PreferenceManager(Activity)}\n * should be used ANY time a preference will be displayed, since some preference\n * types need an Activity for managed queries.\n */\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.695 -0500\", hash_original_method = \"962D66AE85693F6FF77A2DEF54D76478\", hash_generated_method = \"F4455A393DE301F35622852BA02E91EE\")\n private PreferenceManager(Context context) {\n init(context);\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.697 -0500\", hash_original_method = \"2AA94A8F94EE739DE2B0DB27540BEB34\", hash_generated_method = \"E716CEF61FDD32C708F8A58ED93D2B72\")\n private void init(Context context) {\n mContext = context;\n setSharedPreferencesName(getDefaultSharedPreferencesName(context));\n }\n\n /**\n * Sets the owning preference fragment\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.699 -0500\", hash_original_method = \"922F3E36F99E52FA3036E92080002B11\", hash_generated_method = \"922F3E36F99E52FA3036E92080002B11\")\n void setFragment(PreferenceFragment fragment) {\n mFragment = fragment;\n }\n\n /**\n * Returns the owning preference fragment, if any.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.701 -0500\", hash_original_method = \"11BC570017448843B9A9A22E52E0E479\", hash_generated_method = \"11BC570017448843B9A9A22E52E0E479\")\n PreferenceFragment getFragment() {\n return mFragment;\n }\n\n /**\n * Returns a list of {@link Activity} (indirectly) that match a given\n * {@link Intent}.\n *\n * @param queryIntent The Intent to match.\n * @return The list of {@link ResolveInfo} that point to the matched\n * activities.\n */\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.703 -0500\", hash_original_method = \"6682C9F88019B1A37FE99B0D2B3B34A2\", hash_generated_method = \"051844387A24EAE487A48C8117E4273D\")\n private List queryIntentActivities(Intent queryIntent) {\n return mContext.getPackageManager().queryIntentActivities(queryIntent, PackageManager.GET_META_DATA);\n }\n\n /**\n * Inflates a preference hierarchy from the preference hierarchies of\n * {@link Activity Activities} that match the given {@link Intent}. An\n * {@link Activity} defines its preference hierarchy with meta-data using\n * the {@link #METADATA_KEY_PREFERENCES} key.\n *

\n * If a preference hierarchy is given, the new preference hierarchies will\n * be merged in.\n *\n * @param queryIntent The intent to match activities.\n * @param rootPreferences Optional existing hierarchy to merge the new\n * hierarchies into.\n * @return The root hierarchy (if one was not provided, the new hierarchy's\n * root).\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.707 -0500\", hash_original_method = \"96A93C80BB9070BDED20D9AB85FFA8E8\", hash_generated_method = \"DBE5D9014245D9646FD40A2413C6069E\")\n PreferenceScreen inflateFromIntent(Intent queryIntent, PreferenceScreen rootPreferences) {\n final List activities = queryIntentActivities(queryIntent);\n final HashSet inflatedRes = new HashSet();\n for (int i = activities.size() - 1; i >= 0; i--) {\n final ActivityInfo activityInfo = activities.get(i).activityInfo;\n final Bundle metaData = activityInfo.metaData;\n if ((metaData == null) || !metaData.containsKey(METADATA_KEY_PREFERENCES)) {\n continue;\n }\n // Need to concat the package with res ID since the same res ID\n // can be re-used across contexts\n final String uniqueResId = activityInfo.packageName + \":\" + activityInfo.metaData.getInt(METADATA_KEY_PREFERENCES);\n if (!inflatedRes.contains(uniqueResId)) {\n inflatedRes.add(uniqueResId);\n final Context context;\n try {\n context = mContext.createPackageContext(activityInfo.packageName, 0);\n } catch (NameNotFoundException e) {\n Log.w(TAG, \"Could not create context for \" + activityInfo.packageName + \": \" + Log.getStackTraceString(e));\n continue;\n }\n final PreferenceInflater inflater = new PreferenceInflater(context, this);\n final XmlResourceParser parser = activityInfo.loadXmlMetaData(context.getPackageManager(), METADATA_KEY_PREFERENCES);\n rootPreferences = (PreferenceScreen) inflater.inflate(parser, rootPreferences, true);\n parser.close();\n }\n }\n rootPreferences.onAttachedToHierarchy(this);\n return rootPreferences;\n }\n\n /**\n * Inflates a preference hierarchy from XML. If a preference hierarchy is\n * given, the new preference hierarchies will be merged in.\n *\n * @param context The context of the resource.\n * @param resId The resource ID of the XML to inflate.\n * @param rootPreferences Optional existing hierarchy to merge the new\n * hierarchies into.\n * @return The root hierarchy (if one was not provided, the new hierarchy's\n * root).\n * @hide\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.709 -0500\", hash_original_method = \"94F9DF66CFF516C2DE1B651AB9A3388E\", hash_generated_method = \"F0AFDC09FF8BB70BC36CA61F47DEE655\")\n public PreferenceScreen inflateFromResource(Context context, int resId, PreferenceScreen rootPreferences) {\n // Block commits\n setNoCommit(true);\n final PreferenceInflater inflater = new PreferenceInflater(context, this);\n rootPreferences = (PreferenceScreen) inflater.inflate(resId, rootPreferences, true);\n rootPreferences.onAttachedToHierarchy(this);\n // Unblock commits\n setNoCommit(false);\n return rootPreferences;\n }\n\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.711 -0500\", hash_original_method = \"AE92D4BACEE41B351C64A7E59B1B4342\", hash_generated_method = \"E2CDEBF8828B208E67A9E92B6039C90D\")\n public PreferenceScreen createPreferenceScreen(Context context) {\n final PreferenceScreen preferenceScreen = new PreferenceScreen(context, null);\n preferenceScreen.onAttachedToHierarchy(this);\n return preferenceScreen;\n }\n\n /**\n * Called by a preference to get a unique ID in its hierarchy.\n *\n * @return A unique ID.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.713 -0500\", hash_original_method = \"D904EAF0B6D90BB52E1F8594EC3F4D15\", hash_generated_method = \"D904EAF0B6D90BB52E1F8594EC3F4D15\")\n long getNextId() {\n synchronized (this) {\n return mNextId++;\n }\n }\n\n /**\n * Returns the current name of the SharedPreferences file that preferences managed by\n * this will use.\n *\n * @return The name that can be passed to {@link Context#getSharedPreferences(String, int)}.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.715 -0500\", hash_original_method = \"BDB110631059975A566BD4AA87A106E8\", hash_generated_method = \"D7DFCD75F95FBE67D23A3991103EABD7\")\n public String getSharedPreferencesName() {\n return mSharedPreferencesName;\n }\n\n /**\n * Sets the name of the SharedPreferences file that preferences managed by this\n * will use.\n *\n * @param sharedPreferencesName The name of the SharedPreferences file.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.717 -0500\", hash_original_method = \"F8FB75CAC643ECF72FE6E9CDE35245C6\", hash_generated_method = \"D3C3B5611FB8BEDC3068F55C7516B295\")\n public void setSharedPreferencesName(String sharedPreferencesName) {\n mSharedPreferencesName = sharedPreferencesName;\n mSharedPreferences = null;\n }\n\n /**\n * Returns the current mode of the SharedPreferences file that preferences managed by\n * this will use.\n *\n * @return The mode that can be passed to {@link Context#getSharedPreferences(String, int)}.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.719 -0500\", hash_original_method = \"D2CF6E8640E20A030077A21285843C05\", hash_generated_method = \"B34187E4A80B6C182ADA869B95EED2EC\")\n public int getSharedPreferencesMode() {\n return mSharedPreferencesMode;\n }\n\n /**\n * Sets the mode of the SharedPreferences file that preferences managed by this\n * will use.\n *\n * @param sharedPreferencesMode The mode of the SharedPreferences file.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.721 -0500\", hash_original_method = \"6988E36A0998B14CBE7D70DCBAB74FF8\", hash_generated_method = \"8C8607EA8C2F96D19E7B38EF0A94EFB6\")\n public void setSharedPreferencesMode(int sharedPreferencesMode) {\n mSharedPreferencesMode = sharedPreferencesMode;\n mSharedPreferences = null;\n }\n\n /**\n * Gets a SharedPreferences instance that preferences managed by this will\n * use.\n *\n * @return A SharedPreferences instance pointing to the file that contains\n * the values of preferences that are managed by this.\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.724 -0500\", hash_original_method = \"B901A30CD0A7131EC29E8BD072ADC21D\", hash_generated_method = \"9CA9AF2288C06BC076812E1B81D8C766\")\n public SharedPreferences getSharedPreferences() {\n if (mSharedPreferences == null) {\n mSharedPreferences = mContext.getSharedPreferences(mSharedPreferencesName, mSharedPreferencesMode);\n }\n return mSharedPreferences;\n }\n\n /**\n * Returns the root of the preference hierarchy managed by this class.\n *\n * @return The {@link PreferenceScreen} object that is at the root of the hierarchy.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.732 -0500\", hash_original_method = \"60967B21FA602EB86E9B5EB647B08AF2\", hash_generated_method = \"60967B21FA602EB86E9B5EB647B08AF2\")\n PreferenceScreen getPreferenceScreen() {\n return mPreferenceScreen;\n }\n\n /**\n * Sets the root of the preference hierarchy.\n *\n * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.\n * @return Whether the {@link PreferenceScreen} given is different than the previous.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.734 -0500\", hash_original_method = \"72F330353D1AAD0C361FC98ABB0551E0\", hash_generated_method = \"72F330353D1AAD0C361FC98ABB0551E0\")\n boolean setPreferences(PreferenceScreen preferenceScreen) {\n if (preferenceScreen != mPreferenceScreen) {\n mPreferenceScreen = preferenceScreen;\n return true;\n }\n return false;\n }\n\n /**\n * Finds a {@link Preference} based on its key.\n *\n * @param key The key of the preference to retrieve.\n * @return The {@link Preference} with the key, or null.\n * @see PreferenceGroup#findPreference(CharSequence)\n */\n @DSComment(\"May change system behavior\")\n @DSSpec(DSCat.SYSTEM)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.737 -0500\", hash_original_method = \"313075D13AC6A3D78BD3127C39A86211\", hash_generated_method = \"17D4C85ACE0ADBEB3C87DB5BE0FA1596\")\n public Preference findPreference(CharSequence key) {\n if (mPreferenceScreen == null) {\n return null;\n }\n return mPreferenceScreen.findPreference(key);\n }\n\n /**\n * Returns an editor to use when modifying the shared preferences.\n *

\n * Do NOT commit unless {@link #shouldCommit()} returns true.\n *\n * @return An editor to use to write to shared preferences.\n * @see #shouldCommit()\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.743 -0500\", hash_original_method = \"D4733D45210A4F96431F976F3F9AB3C2\", hash_generated_method = \"D4733D45210A4F96431F976F3F9AB3C2\")\n SharedPreferences.Editor getEditor() {\n if (mNoCommit) {\n if (mEditor == null) {\n mEditor = getSharedPreferences().edit();\n }\n return mEditor;\n } else {\n return getSharedPreferences().edit();\n }\n }\n\n /**\n * Whether it is the client's responsibility to commit on the\n * {@link #getEditor()}. This will return false in cases where the writes\n * should be batched, for example when inflating preferences from XML.\n *\n * @return Whether the client should commit.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.746 -0500\", hash_original_method = \"47C154426E8AAB84597A7B272BF8D2FA\", hash_generated_method = \"47C154426E8AAB84597A7B272BF8D2FA\")\n boolean shouldCommit() {\n return !mNoCommit;\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.748 -0500\", hash_original_method = \"2ED947FD2CD87E45A298D362CE1C3C54\", hash_generated_method = \"E1BD2FA4925352CE9F59025D474FA77C\")\n private void setNoCommit(boolean noCommit) {\n if (!noCommit && mEditor != null) {\n try {\n mEditor.apply();\n } catch (AbstractMethodError unused) {\n // The app injected its own pre-Gingerbread\n // SharedPreferences.Editor implementation without\n // an apply method.\n mEditor.commit();\n }\n }\n mNoCommit = noCommit;\n }\n\n /**\n * Returns the activity that shows the preferences. This is useful for doing\n * managed queries, but in most cases the use of {@link #getContext()} is\n * preferred.\n *

\n * This will return null if this class was instantiated with a Context\n * instead of Activity. For example, when setting the default values.\n *\n * @return The activity that shows the preferences.\n * @see #mContext\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.751 -0500\", hash_original_method = \"3F17133E8D63AE8C7414DC58966291E3\", hash_generated_method = \"3F17133E8D63AE8C7414DC58966291E3\")\n Activity getActivity() {\n return mActivity;\n }\n\n /**\n * Returns the context. This is preferred over {@link #getActivity()} when\n * possible.\n *\n * @return The context.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.753 -0500\", hash_original_method = \"4F4EBC54D108D66F416C93B46580E117\", hash_generated_method = \"4F4EBC54D108D66F416C93B46580E117\")\n Context getContext() {\n return mContext;\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityResultListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.755 -0500\", hash_original_method = \"8C7924F669844968ABD2440B12D35A69\", hash_generated_method = \"8C7924F669844968ABD2440B12D35A69\")\n void registerOnActivityResultListener(OnActivityResultListener listener) {\n synchronized (this) {\n if (mActivityResultListeners == null) {\n mActivityResultListeners = new ArrayList();\n }\n if (!mActivityResultListeners.contains(listener)) {\n mActivityResultListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityResultListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.757 -0500\", hash_original_method = \"2F16D3A7CC67220808B5AF6C63D00415\", hash_generated_method = \"2F16D3A7CC67220808B5AF6C63D00415\")\n void unregisterOnActivityResultListener(OnActivityResultListener listener) {\n synchronized (this) {\n if (mActivityResultListeners != null) {\n mActivityResultListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch a subactivity result.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.760 -0500\", hash_original_method = \"A3EFE32034D38DFF1A90F9A5F45D56A6\", hash_generated_method = \"A3EFE32034D38DFF1A90F9A5F45D56A6\")\n void dispatchActivityResult(int requestCode, int resultCode, Intent data) {\n List list;\n synchronized (this) {\n if (mActivityResultListeners == null)\n return;\n list = new ArrayList(mActivityResultListeners);\n }\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n if (list.get(i).onActivityResult(requestCode, resultCode, data)) {\n break;\n }\n }\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityStopListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.762 -0500\", hash_original_method = \"2A0808589AAB6A9778EC4C51EF499853\", hash_generated_method = \"2A0808589AAB6A9778EC4C51EF499853\")\n void registerOnActivityStopListener(OnActivityStopListener listener) {\n synchronized (this) {\n if (mActivityStopListeners == null) {\n mActivityStopListeners = new ArrayList();\n }\n if (!mActivityStopListeners.contains(listener)) {\n mActivityStopListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityStopListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.764 -0500\", hash_original_method = \"D042C49681BB57CB7E14977DE37ED6E0\", hash_generated_method = \"D042C49681BB57CB7E14977DE37ED6E0\")\n void unregisterOnActivityStopListener(OnActivityStopListener listener) {\n synchronized (this) {\n if (mActivityStopListeners != null) {\n mActivityStopListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch the activity stop\n * event.\n */\n ", "post_mask_code": "{\n List list;\n synchronized (this) {\n if (mActivityStopListeners == null)\n return;\n list = new ArrayList(mActivityStopListeners);\n }\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n list.get(i).onActivityStop();\n }\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityDestroyListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.768 -0500\", hash_original_method = \"8932A6D76CD73EDD58651F522607034F\", hash_generated_method = \"8932A6D76CD73EDD58651F522607034F\")\n void registerOnActivityDestroyListener(OnActivityDestroyListener listener) {\n synchronized (this) {\n if (mActivityDestroyListeners == null) {\n mActivityDestroyListeners = new ArrayList();\n }\n if (!mActivityDestroyListeners.contains(listener)) {\n mActivityDestroyListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityDestroyListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.770 -0500\", hash_original_method = \"221E9A8BD7E96AD4198B64196703C2D4\", hash_generated_method = \"221E9A8BD7E96AD4198B64196703C2D4\")\n void unregisterOnActivityDestroyListener(OnActivityDestroyListener listener) {\n synchronized (this) {\n if (mActivityDestroyListeners != null) {\n mActivityDestroyListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch the activity destroy\n * event.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.773 -0500\", hash_original_method = \"ABC0DFC11A448AE601035D9520ECAF99\", hash_generated_method = \"A50EB56106E28498551C2918E03A855A\")\n void dispatchActivityDestroy() {\n List list = null;\n synchronized (this) {\n if (mActivityDestroyListeners != null) {\n list = new ArrayList(mActivityDestroyListeners);\n }\n }\n if (list != null) {\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n list.get(i).onActivityDestroy();\n }\n }\n // Dismiss any PreferenceScreens still showing\n dismissAllScreens();\n }\n\n /**\n * Returns a request code that is unique for the activity. Each subsequent\n * call to this method should return another unique request code.\n *\n * @return A unique request code that will never be used by anyone other\n * than the caller of this method.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.775 -0500\", hash_original_method = \"74A43F7F50012109C1C50A128DECA709\", hash_generated_method = \"74A43F7F50012109C1C50A128DECA709\")\n int getNextRequestCode() {\n synchronized (this) {\n return mNextRequestCode++;\n }\n }\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.777 -0500\", hash_original_method = \"64532379007357BDD2B5A06E80A12A41\", hash_generated_method = \"64532379007357BDD2B5A06E80A12A41\")\n void addPreferencesScreen(DialogInterface screen) {\n synchronized (this) {\n if (mPreferencesScreens == null) {\n mPreferencesScreens = new ArrayList();\n }\n mPreferencesScreens.add(screen);\n }\n }\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.779 -0500\", hash_original_method = \"98728EB5C20211F6C02CB983C1971CE8\", hash_generated_method = \"98728EB5C20211F6C02CB983C1971CE8\")\n void removePreferencesScreen(DialogInterface screen) {\n synchronized (this) {\n if (mPreferencesScreens == null) {\n return;\n }\n mPreferencesScreens.remove(screen);\n }\n }\n\n /**\n * Called by {@link PreferenceActivity} to dispatch the new Intent event.\n *\n * @param intent The new Intent.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.781 -0500\", hash_original_method = \"4573B347852C64DB794205DBF1F726CF\", hash_generated_method = \"4573B347852C64DB794205DBF1F726CF\")\n void dispatchNewIntent(Intent intent) {\n dismissAllScreens();\n }\n\n interface OnPreferenceTreeClickListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference);\n }\n\n public interface OnActivityResultListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n boolean onActivityResult(int requestCode, int resultCode, Intent data);\n }\n\n public interface OnActivityStopListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n void onActivityStop();\n }\n\n public interface OnActivityDestroyListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n void onActivityDestroy();\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.784 -0500\", hash_original_method = \"9025418B8BBAFCD2E271951C43610D69\", hash_generated_method = \"DCBAF81ECD7B379BC2C84590968F3DB8\")\n private void dismissAllScreens() {\n // Remove any of the previously shown preferences screens\n ArrayList screensToDismiss;\n synchronized (this) {\n if (mPreferencesScreens == null) {\n return;\n }\n screensToDismiss = new ArrayList(mPreferencesScreens);\n mPreferencesScreens.clear();\n }\n for (int i = screensToDismiss.size() - 1; i >= 0; i--) {\n screensToDismiss.get(i).dismiss();\n }\n }\n\n /**\n * Sets the callback to be invoked when a {@link Preference} in the\n * hierarchy rooted at this {@link PreferenceManager} is clicked.\n *\n * @param listener The callback to be invoked.\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.785 -0500\", hash_original_method = \"285310B7C58E8A2220B6B265614A6D90\", hash_generated_method = \"285310B7C58E8A2220B6B265614A6D90\")\n void setOnPreferenceTreeClickListener(OnPreferenceTreeClickListener listener) {\n mOnPreferenceTreeClickListener = listener;\n }\n\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.787 -0500\", hash_original_method = \"44D09E26591D5A19BD471058A1477B47\", hash_generated_method = \"44D09E26591D5A19BD471058A1477B47\")\n OnPreferenceTreeClickListener getOnPreferenceTreeClickListener() {\n return mOnPreferenceTreeClickListener;\n }\n}\n"} {"task_id": "Java_3043", "language": "Java", "task_type": "method_body", "source_file": "java/github/MIT-PAC/droidsafe-src/modeling/api/android/preference/PreferenceManager.java", "mask_start_position": 24748, "mask_end_position": 24789, "canonical_solution": "{\n return mPreferenceScreen;\n }", "pre_mask_code": "/*\n * \n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://example.com\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * ** THIS FILE HAS BEEN MODIFIED FROM THE ORIGINAL BY THE DROIDSAFE PROJECT. ****\n */\npackage android.preference;\n\n// Droidsafe Imports\nimport droidsafe.runtime.*;\nimport droidsafe.helpers.*;\nimport android.util.Log;\nimport droidsafe.annotations.*;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.content.pm.ActivityInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.PackageManager.NameNotFoundException;\nimport android.content.pm.ResolveInfo;\nimport android.content.res.XmlResourceParser;\nimport android.os.Bundle;\n\npublic class PreferenceManager {\n\n /**\n * Gets a SharedPreferences instance that points to the default file that is\n * used by the preference framework in the given context.\n *\n * @param context The context of the preferences whose values are wanted.\n * @return A SharedPreferences instance that can be used to retrieve and\n * listen to values of the preferences.\n */\n @DSComment(\"From safe class list\")\n @DSSafe(DSCat.SAFE_LIST)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.726 -0500\", hash_original_method = \"DEE839A83C4B35ACEA8CCC2B71E2B5D1\", hash_generated_method = \"2B16C131215B04C3D72C14303B6B379E\")\n public static SharedPreferences getDefaultSharedPreferences(Context context) {\n return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.728 -0500\", hash_original_method = \"42C9CE230DD05245AC0F1F15B9BA0F77\", hash_generated_method = \"C0A43771BC0878E5F7FF1D24F0A68563\")\n private static String getDefaultSharedPreferencesName(Context context) {\n return context.getPackageName() + \"_preferences\";\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.730 -0500\", hash_original_method = \"9A4A0B76FBD75A7A2387EF85E0D2FD54\", hash_generated_method = \"D84FC8AF76E7CF2269D44A6A6D9A3736\")\n private static int getDefaultSharedPreferencesMode() {\n return Context.MODE_PRIVATE;\n }\n\n /**\n * Sets the default values from a preference hierarchy in XML. This should\n * be called by the application's main activity.\n *

\n * If {@code readAgain} is false, this will only set the default values if this\n * method has never been called in the past (or the\n * {@link #KEY_HAS_SET_DEFAULT_VALUES} in the default value shared\n * preferences file is false). To attempt to set the default values again\n * bypassing this check, set {@code readAgain} to true.\n *\n * @param context The context of the shared preferences.\n * @param resId The resource ID of the preference hierarchy XML file.\n * @param readAgain Whether to re-read the default values.\n *

\n * Note: this will NOT reset preferences back to their default\n * values. For that functionality, use\n * {@link PreferenceManager#getDefaultSharedPreferences(Context)}\n * and clear it followed by a call to this method with this\n * parameter set to true.\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSafe(DSCat.SAFE_LIST)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.739 -0500\", hash_original_method = \"1B08E289995C6C21F5C2BC4F9B6F5187\", hash_generated_method = \"3DC84A33A3C2DB62DE5115DFA6B9F88B\")\n public static void setDefaultValues(Context context, int resId, boolean readAgain) {\n // Use the default shared preferences name and mode\n setDefaultValues(context, getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode(), resId, readAgain);\n }\n\n /**\n * Similar to {@link #setDefaultValues(Context, int, boolean)} but allows\n * the client to provide the filename and mode of the shared preferences\n * file.\n *\n * @see #setDefaultValues(Context, int, boolean)\n * @see #setSharedPreferencesName(String)\n * @see #setSharedPreferencesMode(int)\n */\n @DSSafe(DSCat.SAFE_OTHERS)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.741 -0500\", hash_original_method = \"9646A9372ECC55871733A680E62A72CA\", hash_generated_method = \"2F9BBD3261B2D934E006F58101CB7E9C\")\n public static void setDefaultValues(Context context, String sharedPreferencesName, int sharedPreferencesMode, int resId, boolean readAgain) {\n final SharedPreferences defaultValueSp = context.getSharedPreferences(KEY_HAS_SET_DEFAULT_VALUES, Context.MODE_PRIVATE);\n if (readAgain || !defaultValueSp.getBoolean(KEY_HAS_SET_DEFAULT_VALUES, false)) {\n final PreferenceManager pm = new PreferenceManager(context);\n pm.setSharedPreferencesName(sharedPreferencesName);\n pm.setSharedPreferencesMode(sharedPreferencesMode);\n pm.inflateFromResource(context, resId, null);\n SharedPreferences.Editor editor = defaultValueSp.edit().putBoolean(KEY_HAS_SET_DEFAULT_VALUES, true);\n try {\n editor.apply();\n } catch (AbstractMethodError unused) {\n // The app injected its own pre-Gingerbread\n // SharedPreferences.Editor implementation without\n // an apply method.\n editor.commit();\n }\n }\n }\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.652 -0500\", hash_original_field = \"3A3BD45FA93DD50F7F6C52D2CEF15DB2\", hash_generated_field = \"7AAEA04E4548D5AB6EC8143F21A30EA9\")\n private static final String TAG = \"PreferenceManager\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.654 -0500\", hash_original_field = \"F86CBB3D5E7D46D5EC5C061B27A4EB7F\", hash_generated_field = \"6C182C497B18AE33867D48A4D7F5655E\")\n public static final String METADATA_KEY_PREFERENCES = \"android.preference\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.656 -0500\", hash_original_field = \"A25C8F9EA6A0FB10147CB42E8AE48EF6\", hash_generated_field = \"99247B06873D9B62D5B8F33E5FB96366\")\n public static final String KEY_HAS_SET_DEFAULT_VALUES = \"_has_set_default_values\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.658 -0500\", hash_original_field = \"3895D7E6DB5042DA7856DC78E391C7B9\", hash_generated_field = \"B0D69375984D6EE7DC93AC12DB4DFC55\")\n private Activity mActivity;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.661 -0500\", hash_original_field = \"8520498A009FD770816A73BC7BBAAE33\", hash_generated_field = \"CFB43EBA13761D69B30BE1C8ABC90FE3\")\n private PreferenceFragment mFragment;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.663 -0500\", hash_original_field = \"B997E37019471EC8FC5B98148C7A8AD7\", hash_generated_field = \"C458E619396054F78BC926FB81B4386D\")\n private Context mContext;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.665 -0500\", hash_original_field = \"94D2C61B90F9DDCEA6229CFD1BD4B5A5\", hash_generated_field = \"5707822036BF051C0059AD070444BD58\")\n private long mNextId = 0;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.667 -0500\", hash_original_field = \"0BEC202ACD2F4B80A9D91BEF44E417AC\", hash_generated_field = \"AD359E85C996698973B9458D92AF4B64\")\n private int mNextRequestCode;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.669 -0500\", hash_original_field = \"6863CBC1FD02A5848172EE011B9C880B\", hash_generated_field = \"E69BF347D3F561905392BD5BBB86A4AF\")\n private SharedPreferences mSharedPreferences;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.671 -0500\", hash_original_field = \"C2C898D216011536ABB52408727E0074\", hash_generated_field = \"93BFA57AAD9A25C531F3726BE9E311D1\")\n private SharedPreferences.Editor mEditor;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.673 -0500\", hash_original_field = \"DD8CF6ABD3E3C3CF856EF58396F040C3\", hash_generated_field = \"0870CFBDAD0F12B21EFE736694E5D5A0\")\n private boolean mNoCommit;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.675 -0500\", hash_original_field = \"84C67C1FD7D5449453BD7928216DE986\", hash_generated_field = \"08A9F51924058A9BDDEB8AE59F95CBF8\")\n private String mSharedPreferencesName;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.677 -0500\", hash_original_field = \"A3A8925479C449E7BF4F11709ABEAFA6\", hash_generated_field = \"3DFD0E17BB5556DF650F1E4262E37691\")\n private int mSharedPreferencesMode;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.679 -0500\", hash_original_field = \"FA341E6EF4A389944B6ABCC0C00AA260\", hash_generated_field = \"6929FA68B759CC402927F67ADE03851B\")\n private PreferenceScreen mPreferenceScreen;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.681 -0500\", hash_original_field = \"5A55F2E03C7E028B9F56681221DAC65B\", hash_generated_field = \"759FE206EC137F2D102DEE69CB506E29\")\n private List mActivityResultListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.684 -0500\", hash_original_field = \"B48C98E3D9D54A0CB2952B7439998405\", hash_generated_field = \"AB511ABA80C53F6AD5EC1856C35DAF7F\")\n private List mActivityStopListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.686 -0500\", hash_original_field = \"C29EDB5974FA1CC8018E563C739E55BF\", hash_generated_field = \"ED711A008E3B4CD7A93067555688693E\")\n private List mActivityDestroyListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.688 -0500\", hash_original_field = \"DDDDE82983F75A043C150207C23DA1FF\", hash_generated_field = \"EEC46A0D6BAD420AFB426C404E85D2BA\")\n private List mPreferencesScreens;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.690 -0500\", hash_original_field = \"7B1980F7CD2856B99E6CF8987DD8E986\", hash_generated_field = \"420F1647C8F11E826C9DE0A838CD7533\")\n private OnPreferenceTreeClickListener mOnPreferenceTreeClickListener;\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.693 -0500\", hash_original_method = \"A48679E26B4CF910ADEF8C7563331346\", hash_generated_method = \"A48679E26B4CF910ADEF8C7563331346\")\n PreferenceManager(Activity activity, int firstRequestCode) {\n mActivity = activity;\n mNextRequestCode = firstRequestCode;\n init(activity);\n }\n\n /**\n * This constructor should ONLY be used when getting default values from\n * an XML preference hierarchy.\n *

\n * The {@link PreferenceManager#PreferenceManager(Activity)}\n * should be used ANY time a preference will be displayed, since some preference\n * types need an Activity for managed queries.\n */\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.695 -0500\", hash_original_method = \"962D66AE85693F6FF77A2DEF54D76478\", hash_generated_method = \"F4455A393DE301F35622852BA02E91EE\")\n private PreferenceManager(Context context) {\n init(context);\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.697 -0500\", hash_original_method = \"2AA94A8F94EE739DE2B0DB27540BEB34\", hash_generated_method = \"E716CEF61FDD32C708F8A58ED93D2B72\")\n private void init(Context context) {\n mContext = context;\n setSharedPreferencesName(getDefaultSharedPreferencesName(context));\n }\n\n /**\n * Sets the owning preference fragment\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.699 -0500\", hash_original_method = \"922F3E36F99E52FA3036E92080002B11\", hash_generated_method = \"922F3E36F99E52FA3036E92080002B11\")\n void setFragment(PreferenceFragment fragment) {\n mFragment = fragment;\n }\n\n /**\n * Returns the owning preference fragment, if any.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.701 -0500\", hash_original_method = \"11BC570017448843B9A9A22E52E0E479\", hash_generated_method = \"11BC570017448843B9A9A22E52E0E479\")\n PreferenceFragment getFragment() {\n return mFragment;\n }\n\n /**\n * Returns a list of {@link Activity} (indirectly) that match a given\n * {@link Intent}.\n *\n * @param queryIntent The Intent to match.\n * @return The list of {@link ResolveInfo} that point to the matched\n * activities.\n */\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.703 -0500\", hash_original_method = \"6682C9F88019B1A37FE99B0D2B3B34A2\", hash_generated_method = \"051844387A24EAE487A48C8117E4273D\")\n private List queryIntentActivities(Intent queryIntent) {\n return mContext.getPackageManager().queryIntentActivities(queryIntent, PackageManager.GET_META_DATA);\n }\n\n /**\n * Inflates a preference hierarchy from the preference hierarchies of\n * {@link Activity Activities} that match the given {@link Intent}. An\n * {@link Activity} defines its preference hierarchy with meta-data using\n * the {@link #METADATA_KEY_PREFERENCES} key.\n *

\n * If a preference hierarchy is given, the new preference hierarchies will\n * be merged in.\n *\n * @param queryIntent The intent to match activities.\n * @param rootPreferences Optional existing hierarchy to merge the new\n * hierarchies into.\n * @return The root hierarchy (if one was not provided, the new hierarchy's\n * root).\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.707 -0500\", hash_original_method = \"96A93C80BB9070BDED20D9AB85FFA8E8\", hash_generated_method = \"DBE5D9014245D9646FD40A2413C6069E\")\n PreferenceScreen inflateFromIntent(Intent queryIntent, PreferenceScreen rootPreferences) {\n final List activities = queryIntentActivities(queryIntent);\n final HashSet inflatedRes = new HashSet();\n for (int i = activities.size() - 1; i >= 0; i--) {\n final ActivityInfo activityInfo = activities.get(i).activityInfo;\n final Bundle metaData = activityInfo.metaData;\n if ((metaData == null) || !metaData.containsKey(METADATA_KEY_PREFERENCES)) {\n continue;\n }\n // Need to concat the package with res ID since the same res ID\n // can be re-used across contexts\n final String uniqueResId = activityInfo.packageName + \":\" + activityInfo.metaData.getInt(METADATA_KEY_PREFERENCES);\n if (!inflatedRes.contains(uniqueResId)) {\n inflatedRes.add(uniqueResId);\n final Context context;\n try {\n context = mContext.createPackageContext(activityInfo.packageName, 0);\n } catch (NameNotFoundException e) {\n Log.w(TAG, \"Could not create context for \" + activityInfo.packageName + \": \" + Log.getStackTraceString(e));\n continue;\n }\n final PreferenceInflater inflater = new PreferenceInflater(context, this);\n final XmlResourceParser parser = activityInfo.loadXmlMetaData(context.getPackageManager(), METADATA_KEY_PREFERENCES);\n rootPreferences = (PreferenceScreen) inflater.inflate(parser, rootPreferences, true);\n parser.close();\n }\n }\n rootPreferences.onAttachedToHierarchy(this);\n return rootPreferences;\n }\n\n /**\n * Inflates a preference hierarchy from XML. If a preference hierarchy is\n * given, the new preference hierarchies will be merged in.\n *\n * @param context The context of the resource.\n * @param resId The resource ID of the XML to inflate.\n * @param rootPreferences Optional existing hierarchy to merge the new\n * hierarchies into.\n * @return The root hierarchy (if one was not provided, the new hierarchy's\n * root).\n * @hide\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.709 -0500\", hash_original_method = \"94F9DF66CFF516C2DE1B651AB9A3388E\", hash_generated_method = \"F0AFDC09FF8BB70BC36CA61F47DEE655\")\n public PreferenceScreen inflateFromResource(Context context, int resId, PreferenceScreen rootPreferences) {\n // Block commits\n setNoCommit(true);\n final PreferenceInflater inflater = new PreferenceInflater(context, this);\n rootPreferences = (PreferenceScreen) inflater.inflate(resId, rootPreferences, true);\n rootPreferences.onAttachedToHierarchy(this);\n // Unblock commits\n setNoCommit(false);\n return rootPreferences;\n }\n\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.711 -0500\", hash_original_method = \"AE92D4BACEE41B351C64A7E59B1B4342\", hash_generated_method = \"E2CDEBF8828B208E67A9E92B6039C90D\")\n public PreferenceScreen createPreferenceScreen(Context context) {\n final PreferenceScreen preferenceScreen = new PreferenceScreen(context, null);\n preferenceScreen.onAttachedToHierarchy(this);\n return preferenceScreen;\n }\n\n /**\n * Called by a preference to get a unique ID in its hierarchy.\n *\n * @return A unique ID.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.713 -0500\", hash_original_method = \"D904EAF0B6D90BB52E1F8594EC3F4D15\", hash_generated_method = \"D904EAF0B6D90BB52E1F8594EC3F4D15\")\n long getNextId() {\n synchronized (this) {\n return mNextId++;\n }\n }\n\n /**\n * Returns the current name of the SharedPreferences file that preferences managed by\n * this will use.\n *\n * @return The name that can be passed to {@link Context#getSharedPreferences(String, int)}.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.715 -0500\", hash_original_method = \"BDB110631059975A566BD4AA87A106E8\", hash_generated_method = \"D7DFCD75F95FBE67D23A3991103EABD7\")\n public String getSharedPreferencesName() {\n return mSharedPreferencesName;\n }\n\n /**\n * Sets the name of the SharedPreferences file that preferences managed by this\n * will use.\n *\n * @param sharedPreferencesName The name of the SharedPreferences file.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.717 -0500\", hash_original_method = \"F8FB75CAC643ECF72FE6E9CDE35245C6\", hash_generated_method = \"D3C3B5611FB8BEDC3068F55C7516B295\")\n public void setSharedPreferencesName(String sharedPreferencesName) {\n mSharedPreferencesName = sharedPreferencesName;\n mSharedPreferences = null;\n }\n\n /**\n * Returns the current mode of the SharedPreferences file that preferences managed by\n * this will use.\n *\n * @return The mode that can be passed to {@link Context#getSharedPreferences(String, int)}.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.719 -0500\", hash_original_method = \"D2CF6E8640E20A030077A21285843C05\", hash_generated_method = \"B34187E4A80B6C182ADA869B95EED2EC\")\n public int getSharedPreferencesMode() {\n return mSharedPreferencesMode;\n }\n\n /**\n * Sets the mode of the SharedPreferences file that preferences managed by this\n * will use.\n *\n * @param sharedPreferencesMode The mode of the SharedPreferences file.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.721 -0500\", hash_original_method = \"6988E36A0998B14CBE7D70DCBAB74FF8\", hash_generated_method = \"8C8607EA8C2F96D19E7B38EF0A94EFB6\")\n public void setSharedPreferencesMode(int sharedPreferencesMode) {\n mSharedPreferencesMode = sharedPreferencesMode;\n mSharedPreferences = null;\n }\n\n /**\n * Gets a SharedPreferences instance that preferences managed by this will\n * use.\n *\n * @return A SharedPreferences instance pointing to the file that contains\n * the values of preferences that are managed by this.\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.724 -0500\", hash_original_method = \"B901A30CD0A7131EC29E8BD072ADC21D\", hash_generated_method = \"9CA9AF2288C06BC076812E1B81D8C766\")\n public SharedPreferences getSharedPreferences() {\n if (mSharedPreferences == null) {\n mSharedPreferences = mContext.getSharedPreferences(mSharedPreferencesName, mSharedPreferencesMode);\n }\n return mSharedPreferences;\n }\n\n /**\n * Returns the root of the preference hierarchy managed by this class.\n *\n * @return The {@link PreferenceScreen} object that is at the root of the hierarchy.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.732 -0500\", hash_original_method = \"60967B21FA602EB86E9B5EB647B08AF2\", hash_generated_method = \"60967B21FA602EB86E9B5EB647B08AF2\")\n PreferenceScreen getPreferenceScreen() ", "post_mask_code": "\n\n /**\n * Sets the root of the preference hierarchy.\n *\n * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.\n * @return Whether the {@link PreferenceScreen} given is different than the previous.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.734 -0500\", hash_original_method = \"72F330353D1AAD0C361FC98ABB0551E0\", hash_generated_method = \"72F330353D1AAD0C361FC98ABB0551E0\")\n boolean setPreferences(PreferenceScreen preferenceScreen) {\n if (preferenceScreen != mPreferenceScreen) {\n mPreferenceScreen = preferenceScreen;\n return true;\n }\n return false;\n }\n\n /**\n * Finds a {@link Preference} based on its key.\n *\n * @param key The key of the preference to retrieve.\n * @return The {@link Preference} with the key, or null.\n * @see PreferenceGroup#findPreference(CharSequence)\n */\n @DSComment(\"May change system behavior\")\n @DSSpec(DSCat.SYSTEM)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.737 -0500\", hash_original_method = \"313075D13AC6A3D78BD3127C39A86211\", hash_generated_method = \"17D4C85ACE0ADBEB3C87DB5BE0FA1596\")\n public Preference findPreference(CharSequence key) {\n if (mPreferenceScreen == null) {\n return null;\n }\n return mPreferenceScreen.findPreference(key);\n }\n\n /**\n * Returns an editor to use when modifying the shared preferences.\n *

\n * Do NOT commit unless {@link #shouldCommit()} returns true.\n *\n * @return An editor to use to write to shared preferences.\n * @see #shouldCommit()\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.743 -0500\", hash_original_method = \"D4733D45210A4F96431F976F3F9AB3C2\", hash_generated_method = \"D4733D45210A4F96431F976F3F9AB3C2\")\n SharedPreferences.Editor getEditor() {\n if (mNoCommit) {\n if (mEditor == null) {\n mEditor = getSharedPreferences().edit();\n }\n return mEditor;\n } else {\n return getSharedPreferences().edit();\n }\n }\n\n /**\n * Whether it is the client's responsibility to commit on the\n * {@link #getEditor()}. This will return false in cases where the writes\n * should be batched, for example when inflating preferences from XML.\n *\n * @return Whether the client should commit.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.746 -0500\", hash_original_method = \"47C154426E8AAB84597A7B272BF8D2FA\", hash_generated_method = \"47C154426E8AAB84597A7B272BF8D2FA\")\n boolean shouldCommit() {\n return !mNoCommit;\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.748 -0500\", hash_original_method = \"2ED947FD2CD87E45A298D362CE1C3C54\", hash_generated_method = \"E1BD2FA4925352CE9F59025D474FA77C\")\n private void setNoCommit(boolean noCommit) {\n if (!noCommit && mEditor != null) {\n try {\n mEditor.apply();\n } catch (AbstractMethodError unused) {\n // The app injected its own pre-Gingerbread\n // SharedPreferences.Editor implementation without\n // an apply method.\n mEditor.commit();\n }\n }\n mNoCommit = noCommit;\n }\n\n /**\n * Returns the activity that shows the preferences. This is useful for doing\n * managed queries, but in most cases the use of {@link #getContext()} is\n * preferred.\n *

\n * This will return null if this class was instantiated with a Context\n * instead of Activity. For example, when setting the default values.\n *\n * @return The activity that shows the preferences.\n * @see #mContext\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.751 -0500\", hash_original_method = \"3F17133E8D63AE8C7414DC58966291E3\", hash_generated_method = \"3F17133E8D63AE8C7414DC58966291E3\")\n Activity getActivity() {\n return mActivity;\n }\n\n /**\n * Returns the context. This is preferred over {@link #getActivity()} when\n * possible.\n *\n * @return The context.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.753 -0500\", hash_original_method = \"4F4EBC54D108D66F416C93B46580E117\", hash_generated_method = \"4F4EBC54D108D66F416C93B46580E117\")\n Context getContext() {\n return mContext;\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityResultListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.755 -0500\", hash_original_method = \"8C7924F669844968ABD2440B12D35A69\", hash_generated_method = \"8C7924F669844968ABD2440B12D35A69\")\n void registerOnActivityResultListener(OnActivityResultListener listener) {\n synchronized (this) {\n if (mActivityResultListeners == null) {\n mActivityResultListeners = new ArrayList();\n }\n if (!mActivityResultListeners.contains(listener)) {\n mActivityResultListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityResultListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.757 -0500\", hash_original_method = \"2F16D3A7CC67220808B5AF6C63D00415\", hash_generated_method = \"2F16D3A7CC67220808B5AF6C63D00415\")\n void unregisterOnActivityResultListener(OnActivityResultListener listener) {\n synchronized (this) {\n if (mActivityResultListeners != null) {\n mActivityResultListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch a subactivity result.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.760 -0500\", hash_original_method = \"A3EFE32034D38DFF1A90F9A5F45D56A6\", hash_generated_method = \"A3EFE32034D38DFF1A90F9A5F45D56A6\")\n void dispatchActivityResult(int requestCode, int resultCode, Intent data) {\n List list;\n synchronized (this) {\n if (mActivityResultListeners == null)\n return;\n list = new ArrayList(mActivityResultListeners);\n }\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n if (list.get(i).onActivityResult(requestCode, resultCode, data)) {\n break;\n }\n }\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityStopListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.762 -0500\", hash_original_method = \"2A0808589AAB6A9778EC4C51EF499853\", hash_generated_method = \"2A0808589AAB6A9778EC4C51EF499853\")\n void registerOnActivityStopListener(OnActivityStopListener listener) {\n synchronized (this) {\n if (mActivityStopListeners == null) {\n mActivityStopListeners = new ArrayList();\n }\n if (!mActivityStopListeners.contains(listener)) {\n mActivityStopListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityStopListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.764 -0500\", hash_original_method = \"D042C49681BB57CB7E14977DE37ED6E0\", hash_generated_method = \"D042C49681BB57CB7E14977DE37ED6E0\")\n void unregisterOnActivityStopListener(OnActivityStopListener listener) {\n synchronized (this) {\n if (mActivityStopListeners != null) {\n mActivityStopListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch the activity stop\n * event.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.766 -0500\", hash_original_method = \"6FD57C464C4DA57829A6C2B52E45A452\", hash_generated_method = \"6FD57C464C4DA57829A6C2B52E45A452\")\n void dispatchActivityStop() {\n List list;\n synchronized (this) {\n if (mActivityStopListeners == null)\n return;\n list = new ArrayList(mActivityStopListeners);\n }\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n list.get(i).onActivityStop();\n }\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityDestroyListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.768 -0500\", hash_original_method = \"8932A6D76CD73EDD58651F522607034F\", hash_generated_method = \"8932A6D76CD73EDD58651F522607034F\")\n void registerOnActivityDestroyListener(OnActivityDestroyListener listener) {\n synchronized (this) {\n if (mActivityDestroyListeners == null) {\n mActivityDestroyListeners = new ArrayList();\n }\n if (!mActivityDestroyListeners.contains(listener)) {\n mActivityDestroyListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityDestroyListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.770 -0500\", hash_original_method = \"221E9A8BD7E96AD4198B64196703C2D4\", hash_generated_method = \"221E9A8BD7E96AD4198B64196703C2D4\")\n void unregisterOnActivityDestroyListener(OnActivityDestroyListener listener) {\n synchronized (this) {\n if (mActivityDestroyListeners != null) {\n mActivityDestroyListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch the activity destroy\n * event.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.773 -0500\", hash_original_method = \"ABC0DFC11A448AE601035D9520ECAF99\", hash_generated_method = \"A50EB56106E28498551C2918E03A855A\")\n void dispatchActivityDestroy() {\n List list = null;\n synchronized (this) {\n if (mActivityDestroyListeners != null) {\n list = new ArrayList(mActivityDestroyListeners);\n }\n }\n if (list != null) {\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n list.get(i).onActivityDestroy();\n }\n }\n // Dismiss any PreferenceScreens still showing\n dismissAllScreens();\n }\n\n /**\n * Returns a request code that is unique for the activity. Each subsequent\n * call to this method should return another unique request code.\n *\n * @return A unique request code that will never be used by anyone other\n * than the caller of this method.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.775 -0500\", hash_original_method = \"74A43F7F50012109C1C50A128DECA709\", hash_generated_method = \"74A43F7F50012109C1C50A128DECA709\")\n int getNextRequestCode() {\n synchronized (this) {\n return mNextRequestCode++;\n }\n }\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.777 -0500\", hash_original_method = \"64532379007357BDD2B5A06E80A12A41\", hash_generated_method = \"64532379007357BDD2B5A06E80A12A41\")\n void addPreferencesScreen(DialogInterface screen) {\n synchronized (this) {\n if (mPreferencesScreens == null) {\n mPreferencesScreens = new ArrayList();\n }\n mPreferencesScreens.add(screen);\n }\n }\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.779 -0500\", hash_original_method = \"98728EB5C20211F6C02CB983C1971CE8\", hash_generated_method = \"98728EB5C20211F6C02CB983C1971CE8\")\n void removePreferencesScreen(DialogInterface screen) {\n synchronized (this) {\n if (mPreferencesScreens == null) {\n return;\n }\n mPreferencesScreens.remove(screen);\n }\n }\n\n /**\n * Called by {@link PreferenceActivity} to dispatch the new Intent event.\n *\n * @param intent The new Intent.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.781 -0500\", hash_original_method = \"4573B347852C64DB794205DBF1F726CF\", hash_generated_method = \"4573B347852C64DB794205DBF1F726CF\")\n void dispatchNewIntent(Intent intent) {\n dismissAllScreens();\n }\n\n interface OnPreferenceTreeClickListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference);\n }\n\n public interface OnActivityResultListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n boolean onActivityResult(int requestCode, int resultCode, Intent data);\n }\n\n public interface OnActivityStopListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n void onActivityStop();\n }\n\n public interface OnActivityDestroyListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n void onActivityDestroy();\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.784 -0500\", hash_original_method = \"9025418B8BBAFCD2E271951C43610D69\", hash_generated_method = \"DCBAF81ECD7B379BC2C84590968F3DB8\")\n private void dismissAllScreens() {\n // Remove any of the previously shown preferences screens\n ArrayList screensToDismiss;\n synchronized (this) {\n if (mPreferencesScreens == null) {\n return;\n }\n screensToDismiss = new ArrayList(mPreferencesScreens);\n mPreferencesScreens.clear();\n }\n for (int i = screensToDismiss.size() - 1; i >= 0; i--) {\n screensToDismiss.get(i).dismiss();\n }\n }\n\n /**\n * Sets the callback to be invoked when a {@link Preference} in the\n * hierarchy rooted at this {@link PreferenceManager} is clicked.\n *\n * @param listener The callback to be invoked.\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.785 -0500\", hash_original_method = \"285310B7C58E8A2220B6B265614A6D90\", hash_generated_method = \"285310B7C58E8A2220B6B265614A6D90\")\n void setOnPreferenceTreeClickListener(OnPreferenceTreeClickListener listener) {\n mOnPreferenceTreeClickListener = listener;\n }\n\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.787 -0500\", hash_original_method = \"44D09E26591D5A19BD471058A1477B47\", hash_generated_method = \"44D09E26591D5A19BD471058A1477B47\")\n OnPreferenceTreeClickListener getOnPreferenceTreeClickListener() {\n return mOnPreferenceTreeClickListener;\n }\n}\n"} {"task_id": "Java_3044", "language": "Java", "task_type": "single_line", "source_file": "java/github/MIT-PAC/droidsafe-src/modeling/api/android/preference/PreferenceManager.java", "mask_start_position": 21767, "mask_end_position": 21801, "canonical_solution": "encesName = sharedPreferencesName;", "pre_mask_code": "/*\n * \n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://example.com\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * ** THIS FILE HAS BEEN MODIFIED FROM THE ORIGINAL BY THE DROIDSAFE PROJECT. ****\n */\npackage android.preference;\n\n// Droidsafe Imports\nimport droidsafe.runtime.*;\nimport droidsafe.helpers.*;\nimport android.util.Log;\nimport droidsafe.annotations.*;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.content.pm.ActivityInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.PackageManager.NameNotFoundException;\nimport android.content.pm.ResolveInfo;\nimport android.content.res.XmlResourceParser;\nimport android.os.Bundle;\n\npublic class PreferenceManager {\n\n /**\n * Gets a SharedPreferences instance that points to the default file that is\n * used by the preference framework in the given context.\n *\n * @param context The context of the preferences whose values are wanted.\n * @return A SharedPreferences instance that can be used to retrieve and\n * listen to values of the preferences.\n */\n @DSComment(\"From safe class list\")\n @DSSafe(DSCat.SAFE_LIST)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.726 -0500\", hash_original_method = \"DEE839A83C4B35ACEA8CCC2B71E2B5D1\", hash_generated_method = \"2B16C131215B04C3D72C14303B6B379E\")\n public static SharedPreferences getDefaultSharedPreferences(Context context) {\n return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.728 -0500\", hash_original_method = \"42C9CE230DD05245AC0F1F15B9BA0F77\", hash_generated_method = \"C0A43771BC0878E5F7FF1D24F0A68563\")\n private static String getDefaultSharedPreferencesName(Context context) {\n return context.getPackageName() + \"_preferences\";\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.730 -0500\", hash_original_method = \"9A4A0B76FBD75A7A2387EF85E0D2FD54\", hash_generated_method = \"D84FC8AF76E7CF2269D44A6A6D9A3736\")\n private static int getDefaultSharedPreferencesMode() {\n return Context.MODE_PRIVATE;\n }\n\n /**\n * Sets the default values from a preference hierarchy in XML. This should\n * be called by the application's main activity.\n *

\n * If {@code readAgain} is false, this will only set the default values if this\n * method has never been called in the past (or the\n * {@link #KEY_HAS_SET_DEFAULT_VALUES} in the default value shared\n * preferences file is false). To attempt to set the default values again\n * bypassing this check, set {@code readAgain} to true.\n *\n * @param context The context of the shared preferences.\n * @param resId The resource ID of the preference hierarchy XML file.\n * @param readAgain Whether to re-read the default values.\n *

\n * Note: this will NOT reset preferences back to their default\n * values. For that functionality, use\n * {@link PreferenceManager#getDefaultSharedPreferences(Context)}\n * and clear it followed by a call to this method with this\n * parameter set to true.\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSafe(DSCat.SAFE_LIST)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.739 -0500\", hash_original_method = \"1B08E289995C6C21F5C2BC4F9B6F5187\", hash_generated_method = \"3DC84A33A3C2DB62DE5115DFA6B9F88B\")\n public static void setDefaultValues(Context context, int resId, boolean readAgain) {\n // Use the default shared preferences name and mode\n setDefaultValues(context, getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode(), resId, readAgain);\n }\n\n /**\n * Similar to {@link #setDefaultValues(Context, int, boolean)} but allows\n * the client to provide the filename and mode of the shared preferences\n * file.\n *\n * @see #setDefaultValues(Context, int, boolean)\n * @see #setSharedPreferencesName(String)\n * @see #setSharedPreferencesMode(int)\n */\n @DSSafe(DSCat.SAFE_OTHERS)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.741 -0500\", hash_original_method = \"9646A9372ECC55871733A680E62A72CA\", hash_generated_method = \"2F9BBD3261B2D934E006F58101CB7E9C\")\n public static void setDefaultValues(Context context, String sharedPreferencesName, int sharedPreferencesMode, int resId, boolean readAgain) {\n final SharedPreferences defaultValueSp = context.getSharedPreferences(KEY_HAS_SET_DEFAULT_VALUES, Context.MODE_PRIVATE);\n if (readAgain || !defaultValueSp.getBoolean(KEY_HAS_SET_DEFAULT_VALUES, false)) {\n final PreferenceManager pm = new PreferenceManager(context);\n pm.setSharedPreferencesName(sharedPreferencesName);\n pm.setSharedPreferencesMode(sharedPreferencesMode);\n pm.inflateFromResource(context, resId, null);\n SharedPreferences.Editor editor = defaultValueSp.edit().putBoolean(KEY_HAS_SET_DEFAULT_VALUES, true);\n try {\n editor.apply();\n } catch (AbstractMethodError unused) {\n // The app injected its own pre-Gingerbread\n // SharedPreferences.Editor implementation without\n // an apply method.\n editor.commit();\n }\n }\n }\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.652 -0500\", hash_original_field = \"3A3BD45FA93DD50F7F6C52D2CEF15DB2\", hash_generated_field = \"7AAEA04E4548D5AB6EC8143F21A30EA9\")\n private static final String TAG = \"PreferenceManager\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.654 -0500\", hash_original_field = \"F86CBB3D5E7D46D5EC5C061B27A4EB7F\", hash_generated_field = \"6C182C497B18AE33867D48A4D7F5655E\")\n public static final String METADATA_KEY_PREFERENCES = \"android.preference\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.656 -0500\", hash_original_field = \"A25C8F9EA6A0FB10147CB42E8AE48EF6\", hash_generated_field = \"99247B06873D9B62D5B8F33E5FB96366\")\n public static final String KEY_HAS_SET_DEFAULT_VALUES = \"_has_set_default_values\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.658 -0500\", hash_original_field = \"3895D7E6DB5042DA7856DC78E391C7B9\", hash_generated_field = \"B0D69375984D6EE7DC93AC12DB4DFC55\")\n private Activity mActivity;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.661 -0500\", hash_original_field = \"8520498A009FD770816A73BC7BBAAE33\", hash_generated_field = \"CFB43EBA13761D69B30BE1C8ABC90FE3\")\n private PreferenceFragment mFragment;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.663 -0500\", hash_original_field = \"B997E37019471EC8FC5B98148C7A8AD7\", hash_generated_field = \"C458E619396054F78BC926FB81B4386D\")\n private Context mContext;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.665 -0500\", hash_original_field = \"94D2C61B90F9DDCEA6229CFD1BD4B5A5\", hash_generated_field = \"5707822036BF051C0059AD070444BD58\")\n private long mNextId = 0;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.667 -0500\", hash_original_field = \"0BEC202ACD2F4B80A9D91BEF44E417AC\", hash_generated_field = \"AD359E85C996698973B9458D92AF4B64\")\n private int mNextRequestCode;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.669 -0500\", hash_original_field = \"6863CBC1FD02A5848172EE011B9C880B\", hash_generated_field = \"E69BF347D3F561905392BD5BBB86A4AF\")\n private SharedPreferences mSharedPreferences;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.671 -0500\", hash_original_field = \"C2C898D216011536ABB52408727E0074\", hash_generated_field = \"93BFA57AAD9A25C531F3726BE9E311D1\")\n private SharedPreferences.Editor mEditor;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.673 -0500\", hash_original_field = \"DD8CF6ABD3E3C3CF856EF58396F040C3\", hash_generated_field = \"0870CFBDAD0F12B21EFE736694E5D5A0\")\n private boolean mNoCommit;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.675 -0500\", hash_original_field = \"84C67C1FD7D5449453BD7928216DE986\", hash_generated_field = \"08A9F51924058A9BDDEB8AE59F95CBF8\")\n private String mSharedPreferencesName;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.677 -0500\", hash_original_field = \"A3A8925479C449E7BF4F11709ABEAFA6\", hash_generated_field = \"3DFD0E17BB5556DF650F1E4262E37691\")\n private int mSharedPreferencesMode;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.679 -0500\", hash_original_field = \"FA341E6EF4A389944B6ABCC0C00AA260\", hash_generated_field = \"6929FA68B759CC402927F67ADE03851B\")\n private PreferenceScreen mPreferenceScreen;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.681 -0500\", hash_original_field = \"5A55F2E03C7E028B9F56681221DAC65B\", hash_generated_field = \"759FE206EC137F2D102DEE69CB506E29\")\n private List mActivityResultListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.684 -0500\", hash_original_field = \"B48C98E3D9D54A0CB2952B7439998405\", hash_generated_field = \"AB511ABA80C53F6AD5EC1856C35DAF7F\")\n private List mActivityStopListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.686 -0500\", hash_original_field = \"C29EDB5974FA1CC8018E563C739E55BF\", hash_generated_field = \"ED711A008E3B4CD7A93067555688693E\")\n private List mActivityDestroyListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.688 -0500\", hash_original_field = \"DDDDE82983F75A043C150207C23DA1FF\", hash_generated_field = \"EEC46A0D6BAD420AFB426C404E85D2BA\")\n private List mPreferencesScreens;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.690 -0500\", hash_original_field = \"7B1980F7CD2856B99E6CF8987DD8E986\", hash_generated_field = \"420F1647C8F11E826C9DE0A838CD7533\")\n private OnPreferenceTreeClickListener mOnPreferenceTreeClickListener;\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.693 -0500\", hash_original_method = \"A48679E26B4CF910ADEF8C7563331346\", hash_generated_method = \"A48679E26B4CF910ADEF8C7563331346\")\n PreferenceManager(Activity activity, int firstRequestCode) {\n mActivity = activity;\n mNextRequestCode = firstRequestCode;\n init(activity);\n }\n\n /**\n * This constructor should ONLY be used when getting default values from\n * an XML preference hierarchy.\n *

\n * The {@link PreferenceManager#PreferenceManager(Activity)}\n * should be used ANY time a preference will be displayed, since some preference\n * types need an Activity for managed queries.\n */\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.695 -0500\", hash_original_method = \"962D66AE85693F6FF77A2DEF54D76478\", hash_generated_method = \"F4455A393DE301F35622852BA02E91EE\")\n private PreferenceManager(Context context) {\n init(context);\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.697 -0500\", hash_original_method = \"2AA94A8F94EE739DE2B0DB27540BEB34\", hash_generated_method = \"E716CEF61FDD32C708F8A58ED93D2B72\")\n private void init(Context context) {\n mContext = context;\n setSharedPreferencesName(getDefaultSharedPreferencesName(context));\n }\n\n /**\n * Sets the owning preference fragment\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.699 -0500\", hash_original_method = \"922F3E36F99E52FA3036E92080002B11\", hash_generated_method = \"922F3E36F99E52FA3036E92080002B11\")\n void setFragment(PreferenceFragment fragment) {\n mFragment = fragment;\n }\n\n /**\n * Returns the owning preference fragment, if any.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.701 -0500\", hash_original_method = \"11BC570017448843B9A9A22E52E0E479\", hash_generated_method = \"11BC570017448843B9A9A22E52E0E479\")\n PreferenceFragment getFragment() {\n return mFragment;\n }\n\n /**\n * Returns a list of {@link Activity} (indirectly) that match a given\n * {@link Intent}.\n *\n * @param queryIntent The Intent to match.\n * @return The list of {@link ResolveInfo} that point to the matched\n * activities.\n */\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.703 -0500\", hash_original_method = \"6682C9F88019B1A37FE99B0D2B3B34A2\", hash_generated_method = \"051844387A24EAE487A48C8117E4273D\")\n private List queryIntentActivities(Intent queryIntent) {\n return mContext.getPackageManager().queryIntentActivities(queryIntent, PackageManager.GET_META_DATA);\n }\n\n /**\n * Inflates a preference hierarchy from the preference hierarchies of\n * {@link Activity Activities} that match the given {@link Intent}. An\n * {@link Activity} defines its preference hierarchy with meta-data using\n * the {@link #METADATA_KEY_PREFERENCES} key.\n *

\n * If a preference hierarchy is given, the new preference hierarchies will\n * be merged in.\n *\n * @param queryIntent The intent to match activities.\n * @param rootPreferences Optional existing hierarchy to merge the new\n * hierarchies into.\n * @return The root hierarchy (if one was not provided, the new hierarchy's\n * root).\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.707 -0500\", hash_original_method = \"96A93C80BB9070BDED20D9AB85FFA8E8\", hash_generated_method = \"DBE5D9014245D9646FD40A2413C6069E\")\n PreferenceScreen inflateFromIntent(Intent queryIntent, PreferenceScreen rootPreferences) {\n final List activities = queryIntentActivities(queryIntent);\n final HashSet inflatedRes = new HashSet();\n for (int i = activities.size() - 1; i >= 0; i--) {\n final ActivityInfo activityInfo = activities.get(i).activityInfo;\n final Bundle metaData = activityInfo.metaData;\n if ((metaData == null) || !metaData.containsKey(METADATA_KEY_PREFERENCES)) {\n continue;\n }\n // Need to concat the package with res ID since the same res ID\n // can be re-used across contexts\n final String uniqueResId = activityInfo.packageName + \":\" + activityInfo.metaData.getInt(METADATA_KEY_PREFERENCES);\n if (!inflatedRes.contains(uniqueResId)) {\n inflatedRes.add(uniqueResId);\n final Context context;\n try {\n context = mContext.createPackageContext(activityInfo.packageName, 0);\n } catch (NameNotFoundException e) {\n Log.w(TAG, \"Could not create context for \" + activityInfo.packageName + \": \" + Log.getStackTraceString(e));\n continue;\n }\n final PreferenceInflater inflater = new PreferenceInflater(context, this);\n final XmlResourceParser parser = activityInfo.loadXmlMetaData(context.getPackageManager(), METADATA_KEY_PREFERENCES);\n rootPreferences = (PreferenceScreen) inflater.inflate(parser, rootPreferences, true);\n parser.close();\n }\n }\n rootPreferences.onAttachedToHierarchy(this);\n return rootPreferences;\n }\n\n /**\n * Inflates a preference hierarchy from XML. If a preference hierarchy is\n * given, the new preference hierarchies will be merged in.\n *\n * @param context The context of the resource.\n * @param resId The resource ID of the XML to inflate.\n * @param rootPreferences Optional existing hierarchy to merge the new\n * hierarchies into.\n * @return The root hierarchy (if one was not provided, the new hierarchy's\n * root).\n * @hide\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.709 -0500\", hash_original_method = \"94F9DF66CFF516C2DE1B651AB9A3388E\", hash_generated_method = \"F0AFDC09FF8BB70BC36CA61F47DEE655\")\n public PreferenceScreen inflateFromResource(Context context, int resId, PreferenceScreen rootPreferences) {\n // Block commits\n setNoCommit(true);\n final PreferenceInflater inflater = new PreferenceInflater(context, this);\n rootPreferences = (PreferenceScreen) inflater.inflate(resId, rootPreferences, true);\n rootPreferences.onAttachedToHierarchy(this);\n // Unblock commits\n setNoCommit(false);\n return rootPreferences;\n }\n\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.711 -0500\", hash_original_method = \"AE92D4BACEE41B351C64A7E59B1B4342\", hash_generated_method = \"E2CDEBF8828B208E67A9E92B6039C90D\")\n public PreferenceScreen createPreferenceScreen(Context context) {\n final PreferenceScreen preferenceScreen = new PreferenceScreen(context, null);\n preferenceScreen.onAttachedToHierarchy(this);\n return preferenceScreen;\n }\n\n /**\n * Called by a preference to get a unique ID in its hierarchy.\n *\n * @return A unique ID.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.713 -0500\", hash_original_method = \"D904EAF0B6D90BB52E1F8594EC3F4D15\", hash_generated_method = \"D904EAF0B6D90BB52E1F8594EC3F4D15\")\n long getNextId() {\n synchronized (this) {\n return mNextId++;\n }\n }\n\n /**\n * Returns the current name of the SharedPreferences file that preferences managed by\n * this will use.\n *\n * @return The name that can be passed to {@link Context#getSharedPreferences(String, int)}.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.715 -0500\", hash_original_method = \"BDB110631059975A566BD4AA87A106E8\", hash_generated_method = \"D7DFCD75F95FBE67D23A3991103EABD7\")\n public String getSharedPreferencesName() {\n return mSharedPreferencesName;\n }\n\n /**\n * Sets the name of the SharedPreferences file that preferences managed by this\n * will use.\n *\n * @param sharedPreferencesName The name of the SharedPreferences file.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.717 -0500\", hash_original_method = \"F8FB75CAC643ECF72FE6E9CDE35245C6\", hash_generated_method = \"D3C3B5611FB8BEDC3068F55C7516B295\")\n public void setSharedPreferencesName(String sharedPreferencesName) {\n mSharedPrefer", "post_mask_code": "\n mSharedPreferences = null;\n }\n\n /**\n * Returns the current mode of the SharedPreferences file that preferences managed by\n * this will use.\n *\n * @return The mode that can be passed to {@link Context#getSharedPreferences(String, int)}.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.719 -0500\", hash_original_method = \"D2CF6E8640E20A030077A21285843C05\", hash_generated_method = \"B34187E4A80B6C182ADA869B95EED2EC\")\n public int getSharedPreferencesMode() {\n return mSharedPreferencesMode;\n }\n\n /**\n * Sets the mode of the SharedPreferences file that preferences managed by this\n * will use.\n *\n * @param sharedPreferencesMode The mode of the SharedPreferences file.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.721 -0500\", hash_original_method = \"6988E36A0998B14CBE7D70DCBAB74FF8\", hash_generated_method = \"8C8607EA8C2F96D19E7B38EF0A94EFB6\")\n public void setSharedPreferencesMode(int sharedPreferencesMode) {\n mSharedPreferencesMode = sharedPreferencesMode;\n mSharedPreferences = null;\n }\n\n /**\n * Gets a SharedPreferences instance that preferences managed by this will\n * use.\n *\n * @return A SharedPreferences instance pointing to the file that contains\n * the values of preferences that are managed by this.\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.724 -0500\", hash_original_method = \"B901A30CD0A7131EC29E8BD072ADC21D\", hash_generated_method = \"9CA9AF2288C06BC076812E1B81D8C766\")\n public SharedPreferences getSharedPreferences() {\n if (mSharedPreferences == null) {\n mSharedPreferences = mContext.getSharedPreferences(mSharedPreferencesName, mSharedPreferencesMode);\n }\n return mSharedPreferences;\n }\n\n /**\n * Returns the root of the preference hierarchy managed by this class.\n *\n * @return The {@link PreferenceScreen} object that is at the root of the hierarchy.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.732 -0500\", hash_original_method = \"60967B21FA602EB86E9B5EB647B08AF2\", hash_generated_method = \"60967B21FA602EB86E9B5EB647B08AF2\")\n PreferenceScreen getPreferenceScreen() {\n return mPreferenceScreen;\n }\n\n /**\n * Sets the root of the preference hierarchy.\n *\n * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.\n * @return Whether the {@link PreferenceScreen} given is different than the previous.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.734 -0500\", hash_original_method = \"72F330353D1AAD0C361FC98ABB0551E0\", hash_generated_method = \"72F330353D1AAD0C361FC98ABB0551E0\")\n boolean setPreferences(PreferenceScreen preferenceScreen) {\n if (preferenceScreen != mPreferenceScreen) {\n mPreferenceScreen = preferenceScreen;\n return true;\n }\n return false;\n }\n\n /**\n * Finds a {@link Preference} based on its key.\n *\n * @param key The key of the preference to retrieve.\n * @return The {@link Preference} with the key, or null.\n * @see PreferenceGroup#findPreference(CharSequence)\n */\n @DSComment(\"May change system behavior\")\n @DSSpec(DSCat.SYSTEM)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.737 -0500\", hash_original_method = \"313075D13AC6A3D78BD3127C39A86211\", hash_generated_method = \"17D4C85ACE0ADBEB3C87DB5BE0FA1596\")\n public Preference findPreference(CharSequence key) {\n if (mPreferenceScreen == null) {\n return null;\n }\n return mPreferenceScreen.findPreference(key);\n }\n\n /**\n * Returns an editor to use when modifying the shared preferences.\n *

\n * Do NOT commit unless {@link #shouldCommit()} returns true.\n *\n * @return An editor to use to write to shared preferences.\n * @see #shouldCommit()\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.743 -0500\", hash_original_method = \"D4733D45210A4F96431F976F3F9AB3C2\", hash_generated_method = \"D4733D45210A4F96431F976F3F9AB3C2\")\n SharedPreferences.Editor getEditor() {\n if (mNoCommit) {\n if (mEditor == null) {\n mEditor = getSharedPreferences().edit();\n }\n return mEditor;\n } else {\n return getSharedPreferences().edit();\n }\n }\n\n /**\n * Whether it is the client's responsibility to commit on the\n * {@link #getEditor()}. This will return false in cases where the writes\n * should be batched, for example when inflating preferences from XML.\n *\n * @return Whether the client should commit.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.746 -0500\", hash_original_method = \"47C154426E8AAB84597A7B272BF8D2FA\", hash_generated_method = \"47C154426E8AAB84597A7B272BF8D2FA\")\n boolean shouldCommit() {\n return !mNoCommit;\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.748 -0500\", hash_original_method = \"2ED947FD2CD87E45A298D362CE1C3C54\", hash_generated_method = \"E1BD2FA4925352CE9F59025D474FA77C\")\n private void setNoCommit(boolean noCommit) {\n if (!noCommit && mEditor != null) {\n try {\n mEditor.apply();\n } catch (AbstractMethodError unused) {\n // The app injected its own pre-Gingerbread\n // SharedPreferences.Editor implementation without\n // an apply method.\n mEditor.commit();\n }\n }\n mNoCommit = noCommit;\n }\n\n /**\n * Returns the activity that shows the preferences. This is useful for doing\n * managed queries, but in most cases the use of {@link #getContext()} is\n * preferred.\n *

\n * This will return null if this class was instantiated with a Context\n * instead of Activity. For example, when setting the default values.\n *\n * @return The activity that shows the preferences.\n * @see #mContext\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.751 -0500\", hash_original_method = \"3F17133E8D63AE8C7414DC58966291E3\", hash_generated_method = \"3F17133E8D63AE8C7414DC58966291E3\")\n Activity getActivity() {\n return mActivity;\n }\n\n /**\n * Returns the context. This is preferred over {@link #getActivity()} when\n * possible.\n *\n * @return The context.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.753 -0500\", hash_original_method = \"4F4EBC54D108D66F416C93B46580E117\", hash_generated_method = \"4F4EBC54D108D66F416C93B46580E117\")\n Context getContext() {\n return mContext;\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityResultListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.755 -0500\", hash_original_method = \"8C7924F669844968ABD2440B12D35A69\", hash_generated_method = \"8C7924F669844968ABD2440B12D35A69\")\n void registerOnActivityResultListener(OnActivityResultListener listener) {\n synchronized (this) {\n if (mActivityResultListeners == null) {\n mActivityResultListeners = new ArrayList();\n }\n if (!mActivityResultListeners.contains(listener)) {\n mActivityResultListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityResultListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.757 -0500\", hash_original_method = \"2F16D3A7CC67220808B5AF6C63D00415\", hash_generated_method = \"2F16D3A7CC67220808B5AF6C63D00415\")\n void unregisterOnActivityResultListener(OnActivityResultListener listener) {\n synchronized (this) {\n if (mActivityResultListeners != null) {\n mActivityResultListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch a subactivity result.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.760 -0500\", hash_original_method = \"A3EFE32034D38DFF1A90F9A5F45D56A6\", hash_generated_method = \"A3EFE32034D38DFF1A90F9A5F45D56A6\")\n void dispatchActivityResult(int requestCode, int resultCode, Intent data) {\n List list;\n synchronized (this) {\n if (mActivityResultListeners == null)\n return;\n list = new ArrayList(mActivityResultListeners);\n }\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n if (list.get(i).onActivityResult(requestCode, resultCode, data)) {\n break;\n }\n }\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityStopListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.762 -0500\", hash_original_method = \"2A0808589AAB6A9778EC4C51EF499853\", hash_generated_method = \"2A0808589AAB6A9778EC4C51EF499853\")\n void registerOnActivityStopListener(OnActivityStopListener listener) {\n synchronized (this) {\n if (mActivityStopListeners == null) {\n mActivityStopListeners = new ArrayList();\n }\n if (!mActivityStopListeners.contains(listener)) {\n mActivityStopListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityStopListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.764 -0500\", hash_original_method = \"D042C49681BB57CB7E14977DE37ED6E0\", hash_generated_method = \"D042C49681BB57CB7E14977DE37ED6E0\")\n void unregisterOnActivityStopListener(OnActivityStopListener listener) {\n synchronized (this) {\n if (mActivityStopListeners != null) {\n mActivityStopListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch the activity stop\n * event.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.766 -0500\", hash_original_method = \"6FD57C464C4DA57829A6C2B52E45A452\", hash_generated_method = \"6FD57C464C4DA57829A6C2B52E45A452\")\n void dispatchActivityStop() {\n List list;\n synchronized (this) {\n if (mActivityStopListeners == null)\n return;\n list = new ArrayList(mActivityStopListeners);\n }\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n list.get(i).onActivityStop();\n }\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityDestroyListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.768 -0500\", hash_original_method = \"8932A6D76CD73EDD58651F522607034F\", hash_generated_method = \"8932A6D76CD73EDD58651F522607034F\")\n void registerOnActivityDestroyListener(OnActivityDestroyListener listener) {\n synchronized (this) {\n if (mActivityDestroyListeners == null) {\n mActivityDestroyListeners = new ArrayList();\n }\n if (!mActivityDestroyListeners.contains(listener)) {\n mActivityDestroyListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityDestroyListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.770 -0500\", hash_original_method = \"221E9A8BD7E96AD4198B64196703C2D4\", hash_generated_method = \"221E9A8BD7E96AD4198B64196703C2D4\")\n void unregisterOnActivityDestroyListener(OnActivityDestroyListener listener) {\n synchronized (this) {\n if (mActivityDestroyListeners != null) {\n mActivityDestroyListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch the activity destroy\n * event.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.773 -0500\", hash_original_method = \"ABC0DFC11A448AE601035D9520ECAF99\", hash_generated_method = \"A50EB56106E28498551C2918E03A855A\")\n void dispatchActivityDestroy() {\n List list = null;\n synchronized (this) {\n if (mActivityDestroyListeners != null) {\n list = new ArrayList(mActivityDestroyListeners);\n }\n }\n if (list != null) {\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n list.get(i).onActivityDestroy();\n }\n }\n // Dismiss any PreferenceScreens still showing\n dismissAllScreens();\n }\n\n /**\n * Returns a request code that is unique for the activity. Each subsequent\n * call to this method should return another unique request code.\n *\n * @return A unique request code that will never be used by anyone other\n * than the caller of this method.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.775 -0500\", hash_original_method = \"74A43F7F50012109C1C50A128DECA709\", hash_generated_method = \"74A43F7F50012109C1C50A128DECA709\")\n int getNextRequestCode() {\n synchronized (this) {\n return mNextRequestCode++;\n }\n }\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.777 -0500\", hash_original_method = \"64532379007357BDD2B5A06E80A12A41\", hash_generated_method = \"64532379007357BDD2B5A06E80A12A41\")\n void addPreferencesScreen(DialogInterface screen) {\n synchronized (this) {\n if (mPreferencesScreens == null) {\n mPreferencesScreens = new ArrayList();\n }\n mPreferencesScreens.add(screen);\n }\n }\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.779 -0500\", hash_original_method = \"98728EB5C20211F6C02CB983C1971CE8\", hash_generated_method = \"98728EB5C20211F6C02CB983C1971CE8\")\n void removePreferencesScreen(DialogInterface screen) {\n synchronized (this) {\n if (mPreferencesScreens == null) {\n return;\n }\n mPreferencesScreens.remove(screen);\n }\n }\n\n /**\n * Called by {@link PreferenceActivity} to dispatch the new Intent event.\n *\n * @param intent The new Intent.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.781 -0500\", hash_original_method = \"4573B347852C64DB794205DBF1F726CF\", hash_generated_method = \"4573B347852C64DB794205DBF1F726CF\")\n void dispatchNewIntent(Intent intent) {\n dismissAllScreens();\n }\n\n interface OnPreferenceTreeClickListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference);\n }\n\n public interface OnActivityResultListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n boolean onActivityResult(int requestCode, int resultCode, Intent data);\n }\n\n public interface OnActivityStopListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n void onActivityStop();\n }\n\n public interface OnActivityDestroyListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n void onActivityDestroy();\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.784 -0500\", hash_original_method = \"9025418B8BBAFCD2E271951C43610D69\", hash_generated_method = \"DCBAF81ECD7B379BC2C84590968F3DB8\")\n private void dismissAllScreens() {\n // Remove any of the previously shown preferences screens\n ArrayList screensToDismiss;\n synchronized (this) {\n if (mPreferencesScreens == null) {\n return;\n }\n screensToDismiss = new ArrayList(mPreferencesScreens);\n mPreferencesScreens.clear();\n }\n for (int i = screensToDismiss.size() - 1; i >= 0; i--) {\n screensToDismiss.get(i).dismiss();\n }\n }\n\n /**\n * Sets the callback to be invoked when a {@link Preference} in the\n * hierarchy rooted at this {@link PreferenceManager} is clicked.\n *\n * @param listener The callback to be invoked.\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.785 -0500\", hash_original_method = \"285310B7C58E8A2220B6B265614A6D90\", hash_generated_method = \"285310B7C58E8A2220B6B265614A6D90\")\n void setOnPreferenceTreeClickListener(OnPreferenceTreeClickListener listener) {\n mOnPreferenceTreeClickListener = listener;\n }\n\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.787 -0500\", hash_original_method = \"44D09E26591D5A19BD471058A1477B47\", hash_generated_method = \"44D09E26591D5A19BD471058A1477B47\")\n OnPreferenceTreeClickListener getOnPreferenceTreeClickListener() {\n return mOnPreferenceTreeClickListener;\n }\n}\n"} {"task_id": "Java_3045", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/MIT-PAC/droidsafe-src/modeling/api/android/preference/PreferenceManager.java", "mask_start_position": 24347, "mask_end_position": 24789, "canonical_solution": "@DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.732 -0500\", hash_original_method = \"60967B21FA602EB86E9B5EB647B08AF2\", hash_generated_method = \"60967B21FA602EB86E9B5EB647B08AF2\")\n PreferenceScreen getPreferenceScreen() {\n return mPreferenceScreen;\n }", "pre_mask_code": "/*\n * \n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://example.com\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * ** THIS FILE HAS BEEN MODIFIED FROM THE ORIGINAL BY THE DROIDSAFE PROJECT. ****\n */\npackage android.preference;\n\n// Droidsafe Imports\nimport droidsafe.runtime.*;\nimport droidsafe.helpers.*;\nimport android.util.Log;\nimport droidsafe.annotations.*;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.content.pm.ActivityInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.PackageManager.NameNotFoundException;\nimport android.content.pm.ResolveInfo;\nimport android.content.res.XmlResourceParser;\nimport android.os.Bundle;\n\npublic class PreferenceManager {\n\n /**\n * Gets a SharedPreferences instance that points to the default file that is\n * used by the preference framework in the given context.\n *\n * @param context The context of the preferences whose values are wanted.\n * @return A SharedPreferences instance that can be used to retrieve and\n * listen to values of the preferences.\n */\n @DSComment(\"From safe class list\")\n @DSSafe(DSCat.SAFE_LIST)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.726 -0500\", hash_original_method = \"DEE839A83C4B35ACEA8CCC2B71E2B5D1\", hash_generated_method = \"2B16C131215B04C3D72C14303B6B379E\")\n public static SharedPreferences getDefaultSharedPreferences(Context context) {\n return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.728 -0500\", hash_original_method = \"42C9CE230DD05245AC0F1F15B9BA0F77\", hash_generated_method = \"C0A43771BC0878E5F7FF1D24F0A68563\")\n private static String getDefaultSharedPreferencesName(Context context) {\n return context.getPackageName() + \"_preferences\";\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.730 -0500\", hash_original_method = \"9A4A0B76FBD75A7A2387EF85E0D2FD54\", hash_generated_method = \"D84FC8AF76E7CF2269D44A6A6D9A3736\")\n private static int getDefaultSharedPreferencesMode() {\n return Context.MODE_PRIVATE;\n }\n\n /**\n * Sets the default values from a preference hierarchy in XML. This should\n * be called by the application's main activity.\n *

\n * If {@code readAgain} is false, this will only set the default values if this\n * method has never been called in the past (or the\n * {@link #KEY_HAS_SET_DEFAULT_VALUES} in the default value shared\n * preferences file is false). To attempt to set the default values again\n * bypassing this check, set {@code readAgain} to true.\n *\n * @param context The context of the shared preferences.\n * @param resId The resource ID of the preference hierarchy XML file.\n * @param readAgain Whether to re-read the default values.\n *

\n * Note: this will NOT reset preferences back to their default\n * values. For that functionality, use\n * {@link PreferenceManager#getDefaultSharedPreferences(Context)}\n * and clear it followed by a call to this method with this\n * parameter set to true.\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSafe(DSCat.SAFE_LIST)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.739 -0500\", hash_original_method = \"1B08E289995C6C21F5C2BC4F9B6F5187\", hash_generated_method = \"3DC84A33A3C2DB62DE5115DFA6B9F88B\")\n public static void setDefaultValues(Context context, int resId, boolean readAgain) {\n // Use the default shared preferences name and mode\n setDefaultValues(context, getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode(), resId, readAgain);\n }\n\n /**\n * Similar to {@link #setDefaultValues(Context, int, boolean)} but allows\n * the client to provide the filename and mode of the shared preferences\n * file.\n *\n * @see #setDefaultValues(Context, int, boolean)\n * @see #setSharedPreferencesName(String)\n * @see #setSharedPreferencesMode(int)\n */\n @DSSafe(DSCat.SAFE_OTHERS)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.741 -0500\", hash_original_method = \"9646A9372ECC55871733A680E62A72CA\", hash_generated_method = \"2F9BBD3261B2D934E006F58101CB7E9C\")\n public static void setDefaultValues(Context context, String sharedPreferencesName, int sharedPreferencesMode, int resId, boolean readAgain) {\n final SharedPreferences defaultValueSp = context.getSharedPreferences(KEY_HAS_SET_DEFAULT_VALUES, Context.MODE_PRIVATE);\n if (readAgain || !defaultValueSp.getBoolean(KEY_HAS_SET_DEFAULT_VALUES, false)) {\n final PreferenceManager pm = new PreferenceManager(context);\n pm.setSharedPreferencesName(sharedPreferencesName);\n pm.setSharedPreferencesMode(sharedPreferencesMode);\n pm.inflateFromResource(context, resId, null);\n SharedPreferences.Editor editor = defaultValueSp.edit().putBoolean(KEY_HAS_SET_DEFAULT_VALUES, true);\n try {\n editor.apply();\n } catch (AbstractMethodError unused) {\n // The app injected its own pre-Gingerbread\n // SharedPreferences.Editor implementation without\n // an apply method.\n editor.commit();\n }\n }\n }\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.652 -0500\", hash_original_field = \"3A3BD45FA93DD50F7F6C52D2CEF15DB2\", hash_generated_field = \"7AAEA04E4548D5AB6EC8143F21A30EA9\")\n private static final String TAG = \"PreferenceManager\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.654 -0500\", hash_original_field = \"F86CBB3D5E7D46D5EC5C061B27A4EB7F\", hash_generated_field = \"6C182C497B18AE33867D48A4D7F5655E\")\n public static final String METADATA_KEY_PREFERENCES = \"android.preference\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.656 -0500\", hash_original_field = \"A25C8F9EA6A0FB10147CB42E8AE48EF6\", hash_generated_field = \"99247B06873D9B62D5B8F33E5FB96366\")\n public static final String KEY_HAS_SET_DEFAULT_VALUES = \"_has_set_default_values\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.658 -0500\", hash_original_field = \"3895D7E6DB5042DA7856DC78E391C7B9\", hash_generated_field = \"B0D69375984D6EE7DC93AC12DB4DFC55\")\n private Activity mActivity;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.661 -0500\", hash_original_field = \"8520498A009FD770816A73BC7BBAAE33\", hash_generated_field = \"CFB43EBA13761D69B30BE1C8ABC90FE3\")\n private PreferenceFragment mFragment;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.663 -0500\", hash_original_field = \"B997E37019471EC8FC5B98148C7A8AD7\", hash_generated_field = \"C458E619396054F78BC926FB81B4386D\")\n private Context mContext;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.665 -0500\", hash_original_field = \"94D2C61B90F9DDCEA6229CFD1BD4B5A5\", hash_generated_field = \"5707822036BF051C0059AD070444BD58\")\n private long mNextId = 0;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.667 -0500\", hash_original_field = \"0BEC202ACD2F4B80A9D91BEF44E417AC\", hash_generated_field = \"AD359E85C996698973B9458D92AF4B64\")\n private int mNextRequestCode;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.669 -0500\", hash_original_field = \"6863CBC1FD02A5848172EE011B9C880B\", hash_generated_field = \"E69BF347D3F561905392BD5BBB86A4AF\")\n private SharedPreferences mSharedPreferences;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.671 -0500\", hash_original_field = \"C2C898D216011536ABB52408727E0074\", hash_generated_field = \"93BFA57AAD9A25C531F3726BE9E311D1\")\n private SharedPreferences.Editor mEditor;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.673 -0500\", hash_original_field = \"DD8CF6ABD3E3C3CF856EF58396F040C3\", hash_generated_field = \"0870CFBDAD0F12B21EFE736694E5D5A0\")\n private boolean mNoCommit;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.675 -0500\", hash_original_field = \"84C67C1FD7D5449453BD7928216DE986\", hash_generated_field = \"08A9F51924058A9BDDEB8AE59F95CBF8\")\n private String mSharedPreferencesName;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.677 -0500\", hash_original_field = \"A3A8925479C449E7BF4F11709ABEAFA6\", hash_generated_field = \"3DFD0E17BB5556DF650F1E4262E37691\")\n private int mSharedPreferencesMode;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.679 -0500\", hash_original_field = \"FA341E6EF4A389944B6ABCC0C00AA260\", hash_generated_field = \"6929FA68B759CC402927F67ADE03851B\")\n private PreferenceScreen mPreferenceScreen;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.681 -0500\", hash_original_field = \"5A55F2E03C7E028B9F56681221DAC65B\", hash_generated_field = \"759FE206EC137F2D102DEE69CB506E29\")\n private List mActivityResultListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.684 -0500\", hash_original_field = \"B48C98E3D9D54A0CB2952B7439998405\", hash_generated_field = \"AB511ABA80C53F6AD5EC1856C35DAF7F\")\n private List mActivityStopListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.686 -0500\", hash_original_field = \"C29EDB5974FA1CC8018E563C739E55BF\", hash_generated_field = \"ED711A008E3B4CD7A93067555688693E\")\n private List mActivityDestroyListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.688 -0500\", hash_original_field = \"DDDDE82983F75A043C150207C23DA1FF\", hash_generated_field = \"EEC46A0D6BAD420AFB426C404E85D2BA\")\n private List mPreferencesScreens;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.690 -0500\", hash_original_field = \"7B1980F7CD2856B99E6CF8987DD8E986\", hash_generated_field = \"420F1647C8F11E826C9DE0A838CD7533\")\n private OnPreferenceTreeClickListener mOnPreferenceTreeClickListener;\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.693 -0500\", hash_original_method = \"A48679E26B4CF910ADEF8C7563331346\", hash_generated_method = \"A48679E26B4CF910ADEF8C7563331346\")\n PreferenceManager(Activity activity, int firstRequestCode) {\n mActivity = activity;\n mNextRequestCode = firstRequestCode;\n init(activity);\n }\n\n /**\n * This constructor should ONLY be used when getting default values from\n * an XML preference hierarchy.\n *

\n * The {@link PreferenceManager#PreferenceManager(Activity)}\n * should be used ANY time a preference will be displayed, since some preference\n * types need an Activity for managed queries.\n */\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.695 -0500\", hash_original_method = \"962D66AE85693F6FF77A2DEF54D76478\", hash_generated_method = \"F4455A393DE301F35622852BA02E91EE\")\n private PreferenceManager(Context context) {\n init(context);\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.697 -0500\", hash_original_method = \"2AA94A8F94EE739DE2B0DB27540BEB34\", hash_generated_method = \"E716CEF61FDD32C708F8A58ED93D2B72\")\n private void init(Context context) {\n mContext = context;\n setSharedPreferencesName(getDefaultSharedPreferencesName(context));\n }\n\n /**\n * Sets the owning preference fragment\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.699 -0500\", hash_original_method = \"922F3E36F99E52FA3036E92080002B11\", hash_generated_method = \"922F3E36F99E52FA3036E92080002B11\")\n void setFragment(PreferenceFragment fragment) {\n mFragment = fragment;\n }\n\n /**\n * Returns the owning preference fragment, if any.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.701 -0500\", hash_original_method = \"11BC570017448843B9A9A22E52E0E479\", hash_generated_method = \"11BC570017448843B9A9A22E52E0E479\")\n PreferenceFragment getFragment() {\n return mFragment;\n }\n\n /**\n * Returns a list of {@link Activity} (indirectly) that match a given\n * {@link Intent}.\n *\n * @param queryIntent The Intent to match.\n * @return The list of {@link ResolveInfo} that point to the matched\n * activities.\n */\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.703 -0500\", hash_original_method = \"6682C9F88019B1A37FE99B0D2B3B34A2\", hash_generated_method = \"051844387A24EAE487A48C8117E4273D\")\n private List queryIntentActivities(Intent queryIntent) {\n return mContext.getPackageManager().queryIntentActivities(queryIntent, PackageManager.GET_META_DATA);\n }\n\n /**\n * Inflates a preference hierarchy from the preference hierarchies of\n * {@link Activity Activities} that match the given {@link Intent}. An\n * {@link Activity} defines its preference hierarchy with meta-data using\n * the {@link #METADATA_KEY_PREFERENCES} key.\n *

\n * If a preference hierarchy is given, the new preference hierarchies will\n * be merged in.\n *\n * @param queryIntent The intent to match activities.\n * @param rootPreferences Optional existing hierarchy to merge the new\n * hierarchies into.\n * @return The root hierarchy (if one was not provided, the new hierarchy's\n * root).\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.707 -0500\", hash_original_method = \"96A93C80BB9070BDED20D9AB85FFA8E8\", hash_generated_method = \"DBE5D9014245D9646FD40A2413C6069E\")\n PreferenceScreen inflateFromIntent(Intent queryIntent, PreferenceScreen rootPreferences) {\n final List activities = queryIntentActivities(queryIntent);\n final HashSet inflatedRes = new HashSet();\n for (int i = activities.size() - 1; i >= 0; i--) {\n final ActivityInfo activityInfo = activities.get(i).activityInfo;\n final Bundle metaData = activityInfo.metaData;\n if ((metaData == null) || !metaData.containsKey(METADATA_KEY_PREFERENCES)) {\n continue;\n }\n // Need to concat the package with res ID since the same res ID\n // can be re-used across contexts\n final String uniqueResId = activityInfo.packageName + \":\" + activityInfo.metaData.getInt(METADATA_KEY_PREFERENCES);\n if (!inflatedRes.contains(uniqueResId)) {\n inflatedRes.add(uniqueResId);\n final Context context;\n try {\n context = mContext.createPackageContext(activityInfo.packageName, 0);\n } catch (NameNotFoundException e) {\n Log.w(TAG, \"Could not create context for \" + activityInfo.packageName + \": \" + Log.getStackTraceString(e));\n continue;\n }\n final PreferenceInflater inflater = new PreferenceInflater(context, this);\n final XmlResourceParser parser = activityInfo.loadXmlMetaData(context.getPackageManager(), METADATA_KEY_PREFERENCES);\n rootPreferences = (PreferenceScreen) inflater.inflate(parser, rootPreferences, true);\n parser.close();\n }\n }\n rootPreferences.onAttachedToHierarchy(this);\n return rootPreferences;\n }\n\n /**\n * Inflates a preference hierarchy from XML. If a preference hierarchy is\n * given, the new preference hierarchies will be merged in.\n *\n * @param context The context of the resource.\n * @param resId The resource ID of the XML to inflate.\n * @param rootPreferences Optional existing hierarchy to merge the new\n * hierarchies into.\n * @return The root hierarchy (if one was not provided, the new hierarchy's\n * root).\n * @hide\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.709 -0500\", hash_original_method = \"94F9DF66CFF516C2DE1B651AB9A3388E\", hash_generated_method = \"F0AFDC09FF8BB70BC36CA61F47DEE655\")\n public PreferenceScreen inflateFromResource(Context context, int resId, PreferenceScreen rootPreferences) {\n // Block commits\n setNoCommit(true);\n final PreferenceInflater inflater = new PreferenceInflater(context, this);\n rootPreferences = (PreferenceScreen) inflater.inflate(resId, rootPreferences, true);\n rootPreferences.onAttachedToHierarchy(this);\n // Unblock commits\n setNoCommit(false);\n return rootPreferences;\n }\n\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.711 -0500\", hash_original_method = \"AE92D4BACEE41B351C64A7E59B1B4342\", hash_generated_method = \"E2CDEBF8828B208E67A9E92B6039C90D\")\n public PreferenceScreen createPreferenceScreen(Context context) {\n final PreferenceScreen preferenceScreen = new PreferenceScreen(context, null);\n preferenceScreen.onAttachedToHierarchy(this);\n return preferenceScreen;\n }\n\n /**\n * Called by a preference to get a unique ID in its hierarchy.\n *\n * @return A unique ID.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.713 -0500\", hash_original_method = \"D904EAF0B6D90BB52E1F8594EC3F4D15\", hash_generated_method = \"D904EAF0B6D90BB52E1F8594EC3F4D15\")\n long getNextId() {\n synchronized (this) {\n return mNextId++;\n }\n }\n\n /**\n * Returns the current name of the SharedPreferences file that preferences managed by\n * this will use.\n *\n * @return The name that can be passed to {@link Context#getSharedPreferences(String, int)}.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.715 -0500\", hash_original_method = \"BDB110631059975A566BD4AA87A106E8\", hash_generated_method = \"D7DFCD75F95FBE67D23A3991103EABD7\")\n public String getSharedPreferencesName() {\n return mSharedPreferencesName;\n }\n\n /**\n * Sets the name of the SharedPreferences file that preferences managed by this\n * will use.\n *\n * @param sharedPreferencesName The name of the SharedPreferences file.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.717 -0500\", hash_original_method = \"F8FB75CAC643ECF72FE6E9CDE35245C6\", hash_generated_method = \"D3C3B5611FB8BEDC3068F55C7516B295\")\n public void setSharedPreferencesName(String sharedPreferencesName) {\n mSharedPreferencesName = sharedPreferencesName;\n mSharedPreferences = null;\n }\n\n /**\n * Returns the current mode of the SharedPreferences file that preferences managed by\n * this will use.\n *\n * @return The mode that can be passed to {@link Context#getSharedPreferences(String, int)}.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.719 -0500\", hash_original_method = \"D2CF6E8640E20A030077A21285843C05\", hash_generated_method = \"B34187E4A80B6C182ADA869B95EED2EC\")\n public int getSharedPreferencesMode() {\n return mSharedPreferencesMode;\n }\n\n /**\n * Sets the mode of the SharedPreferences file that preferences managed by this\n * will use.\n *\n * @param sharedPreferencesMode The mode of the SharedPreferences file.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.721 -0500\", hash_original_method = \"6988E36A0998B14CBE7D70DCBAB74FF8\", hash_generated_method = \"8C8607EA8C2F96D19E7B38EF0A94EFB6\")\n public void setSharedPreferencesMode(int sharedPreferencesMode) {\n mSharedPreferencesMode = sharedPreferencesMode;\n mSharedPreferences = null;\n }\n\n /**\n * Gets a SharedPreferences instance that preferences managed by this will\n * use.\n *\n * @return A SharedPreferences instance pointing to the file that contains\n * the values of preferences that are managed by this.\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.724 -0500\", hash_original_method = \"B901A30CD0A7131EC29E8BD072ADC21D\", hash_generated_method = \"9CA9AF2288C06BC076812E1B81D8C766\")\n public SharedPreferences getSharedPreferences() {\n if (mSharedPreferences == null) {\n mSharedPreferences = mContext.getSharedPreferences(mSharedPreferencesName, mSharedPreferencesMode);\n }\n return mSharedPreferences;\n }\n\n /**\n * Returns the root of the preference hierarchy managed by this class.\n *\n * @return The {@link PreferenceScreen} object that is at the root of the hierarchy.\n */\n ", "post_mask_code": "\n\n /**\n * Sets the root of the preference hierarchy.\n *\n * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.\n * @return Whether the {@link PreferenceScreen} given is different than the previous.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.734 -0500\", hash_original_method = \"72F330353D1AAD0C361FC98ABB0551E0\", hash_generated_method = \"72F330353D1AAD0C361FC98ABB0551E0\")\n boolean setPreferences(PreferenceScreen preferenceScreen) {\n if (preferenceScreen != mPreferenceScreen) {\n mPreferenceScreen = preferenceScreen;\n return true;\n }\n return false;\n }\n\n /**\n * Finds a {@link Preference} based on its key.\n *\n * @param key The key of the preference to retrieve.\n * @return The {@link Preference} with the key, or null.\n * @see PreferenceGroup#findPreference(CharSequence)\n */\n @DSComment(\"May change system behavior\")\n @DSSpec(DSCat.SYSTEM)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.737 -0500\", hash_original_method = \"313075D13AC6A3D78BD3127C39A86211\", hash_generated_method = \"17D4C85ACE0ADBEB3C87DB5BE0FA1596\")\n public Preference findPreference(CharSequence key) {\n if (mPreferenceScreen == null) {\n return null;\n }\n return mPreferenceScreen.findPreference(key);\n }\n\n /**\n * Returns an editor to use when modifying the shared preferences.\n *

\n * Do NOT commit unless {@link #shouldCommit()} returns true.\n *\n * @return An editor to use to write to shared preferences.\n * @see #shouldCommit()\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.743 -0500\", hash_original_method = \"D4733D45210A4F96431F976F3F9AB3C2\", hash_generated_method = \"D4733D45210A4F96431F976F3F9AB3C2\")\n SharedPreferences.Editor getEditor() {\n if (mNoCommit) {\n if (mEditor == null) {\n mEditor = getSharedPreferences().edit();\n }\n return mEditor;\n } else {\n return getSharedPreferences().edit();\n }\n }\n\n /**\n * Whether it is the client's responsibility to commit on the\n * {@link #getEditor()}. This will return false in cases where the writes\n * should be batched, for example when inflating preferences from XML.\n *\n * @return Whether the client should commit.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.746 -0500\", hash_original_method = \"47C154426E8AAB84597A7B272BF8D2FA\", hash_generated_method = \"47C154426E8AAB84597A7B272BF8D2FA\")\n boolean shouldCommit() {\n return !mNoCommit;\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.748 -0500\", hash_original_method = \"2ED947FD2CD87E45A298D362CE1C3C54\", hash_generated_method = \"E1BD2FA4925352CE9F59025D474FA77C\")\n private void setNoCommit(boolean noCommit) {\n if (!noCommit && mEditor != null) {\n try {\n mEditor.apply();\n } catch (AbstractMethodError unused) {\n // The app injected its own pre-Gingerbread\n // SharedPreferences.Editor implementation without\n // an apply method.\n mEditor.commit();\n }\n }\n mNoCommit = noCommit;\n }\n\n /**\n * Returns the activity that shows the preferences. This is useful for doing\n * managed queries, but in most cases the use of {@link #getContext()} is\n * preferred.\n *

\n * This will return null if this class was instantiated with a Context\n * instead of Activity. For example, when setting the default values.\n *\n * @return The activity that shows the preferences.\n * @see #mContext\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.751 -0500\", hash_original_method = \"3F17133E8D63AE8C7414DC58966291E3\", hash_generated_method = \"3F17133E8D63AE8C7414DC58966291E3\")\n Activity getActivity() {\n return mActivity;\n }\n\n /**\n * Returns the context. This is preferred over {@link #getActivity()} when\n * possible.\n *\n * @return The context.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.753 -0500\", hash_original_method = \"4F4EBC54D108D66F416C93B46580E117\", hash_generated_method = \"4F4EBC54D108D66F416C93B46580E117\")\n Context getContext() {\n return mContext;\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityResultListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.755 -0500\", hash_original_method = \"8C7924F669844968ABD2440B12D35A69\", hash_generated_method = \"8C7924F669844968ABD2440B12D35A69\")\n void registerOnActivityResultListener(OnActivityResultListener listener) {\n synchronized (this) {\n if (mActivityResultListeners == null) {\n mActivityResultListeners = new ArrayList();\n }\n if (!mActivityResultListeners.contains(listener)) {\n mActivityResultListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityResultListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.757 -0500\", hash_original_method = \"2F16D3A7CC67220808B5AF6C63D00415\", hash_generated_method = \"2F16D3A7CC67220808B5AF6C63D00415\")\n void unregisterOnActivityResultListener(OnActivityResultListener listener) {\n synchronized (this) {\n if (mActivityResultListeners != null) {\n mActivityResultListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch a subactivity result.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.760 -0500\", hash_original_method = \"A3EFE32034D38DFF1A90F9A5F45D56A6\", hash_generated_method = \"A3EFE32034D38DFF1A90F9A5F45D56A6\")\n void dispatchActivityResult(int requestCode, int resultCode, Intent data) {\n List list;\n synchronized (this) {\n if (mActivityResultListeners == null)\n return;\n list = new ArrayList(mActivityResultListeners);\n }\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n if (list.get(i).onActivityResult(requestCode, resultCode, data)) {\n break;\n }\n }\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityStopListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.762 -0500\", hash_original_method = \"2A0808589AAB6A9778EC4C51EF499853\", hash_generated_method = \"2A0808589AAB6A9778EC4C51EF499853\")\n void registerOnActivityStopListener(OnActivityStopListener listener) {\n synchronized (this) {\n if (mActivityStopListeners == null) {\n mActivityStopListeners = new ArrayList();\n }\n if (!mActivityStopListeners.contains(listener)) {\n mActivityStopListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityStopListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.764 -0500\", hash_original_method = \"D042C49681BB57CB7E14977DE37ED6E0\", hash_generated_method = \"D042C49681BB57CB7E14977DE37ED6E0\")\n void unregisterOnActivityStopListener(OnActivityStopListener listener) {\n synchronized (this) {\n if (mActivityStopListeners != null) {\n mActivityStopListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch the activity stop\n * event.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.766 -0500\", hash_original_method = \"6FD57C464C4DA57829A6C2B52E45A452\", hash_generated_method = \"6FD57C464C4DA57829A6C2B52E45A452\")\n void dispatchActivityStop() {\n List list;\n synchronized (this) {\n if (mActivityStopListeners == null)\n return;\n list = new ArrayList(mActivityStopListeners);\n }\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n list.get(i).onActivityStop();\n }\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityDestroyListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.768 -0500\", hash_original_method = \"8932A6D76CD73EDD58651F522607034F\", hash_generated_method = \"8932A6D76CD73EDD58651F522607034F\")\n void registerOnActivityDestroyListener(OnActivityDestroyListener listener) {\n synchronized (this) {\n if (mActivityDestroyListeners == null) {\n mActivityDestroyListeners = new ArrayList();\n }\n if (!mActivityDestroyListeners.contains(listener)) {\n mActivityDestroyListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityDestroyListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.770 -0500\", hash_original_method = \"221E9A8BD7E96AD4198B64196703C2D4\", hash_generated_method = \"221E9A8BD7E96AD4198B64196703C2D4\")\n void unregisterOnActivityDestroyListener(OnActivityDestroyListener listener) {\n synchronized (this) {\n if (mActivityDestroyListeners != null) {\n mActivityDestroyListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch the activity destroy\n * event.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.773 -0500\", hash_original_method = \"ABC0DFC11A448AE601035D9520ECAF99\", hash_generated_method = \"A50EB56106E28498551C2918E03A855A\")\n void dispatchActivityDestroy() {\n List list = null;\n synchronized (this) {\n if (mActivityDestroyListeners != null) {\n list = new ArrayList(mActivityDestroyListeners);\n }\n }\n if (list != null) {\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n list.get(i).onActivityDestroy();\n }\n }\n // Dismiss any PreferenceScreens still showing\n dismissAllScreens();\n }\n\n /**\n * Returns a request code that is unique for the activity. Each subsequent\n * call to this method should return another unique request code.\n *\n * @return A unique request code that will never be used by anyone other\n * than the caller of this method.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.775 -0500\", hash_original_method = \"74A43F7F50012109C1C50A128DECA709\", hash_generated_method = \"74A43F7F50012109C1C50A128DECA709\")\n int getNextRequestCode() {\n synchronized (this) {\n return mNextRequestCode++;\n }\n }\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.777 -0500\", hash_original_method = \"64532379007357BDD2B5A06E80A12A41\", hash_generated_method = \"64532379007357BDD2B5A06E80A12A41\")\n void addPreferencesScreen(DialogInterface screen) {\n synchronized (this) {\n if (mPreferencesScreens == null) {\n mPreferencesScreens = new ArrayList();\n }\n mPreferencesScreens.add(screen);\n }\n }\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.779 -0500\", hash_original_method = \"98728EB5C20211F6C02CB983C1971CE8\", hash_generated_method = \"98728EB5C20211F6C02CB983C1971CE8\")\n void removePreferencesScreen(DialogInterface screen) {\n synchronized (this) {\n if (mPreferencesScreens == null) {\n return;\n }\n mPreferencesScreens.remove(screen);\n }\n }\n\n /**\n * Called by {@link PreferenceActivity} to dispatch the new Intent event.\n *\n * @param intent The new Intent.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.781 -0500\", hash_original_method = \"4573B347852C64DB794205DBF1F726CF\", hash_generated_method = \"4573B347852C64DB794205DBF1F726CF\")\n void dispatchNewIntent(Intent intent) {\n dismissAllScreens();\n }\n\n interface OnPreferenceTreeClickListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference);\n }\n\n public interface OnActivityResultListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n boolean onActivityResult(int requestCode, int resultCode, Intent data);\n }\n\n public interface OnActivityStopListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n void onActivityStop();\n }\n\n public interface OnActivityDestroyListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n void onActivityDestroy();\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.784 -0500\", hash_original_method = \"9025418B8BBAFCD2E271951C43610D69\", hash_generated_method = \"DCBAF81ECD7B379BC2C84590968F3DB8\")\n private void dismissAllScreens() {\n // Remove any of the previously shown preferences screens\n ArrayList screensToDismiss;\n synchronized (this) {\n if (mPreferencesScreens == null) {\n return;\n }\n screensToDismiss = new ArrayList(mPreferencesScreens);\n mPreferencesScreens.clear();\n }\n for (int i = screensToDismiss.size() - 1; i >= 0; i--) {\n screensToDismiss.get(i).dismiss();\n }\n }\n\n /**\n * Sets the callback to be invoked when a {@link Preference} in the\n * hierarchy rooted at this {@link PreferenceManager} is clicked.\n *\n * @param listener The callback to be invoked.\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.785 -0500\", hash_original_method = \"285310B7C58E8A2220B6B265614A6D90\", hash_generated_method = \"285310B7C58E8A2220B6B265614A6D90\")\n void setOnPreferenceTreeClickListener(OnPreferenceTreeClickListener listener) {\n mOnPreferenceTreeClickListener = listener;\n }\n\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.787 -0500\", hash_original_method = \"44D09E26591D5A19BD471058A1477B47\", hash_generated_method = \"44D09E26591D5A19BD471058A1477B47\")\n OnPreferenceTreeClickListener getOnPreferenceTreeClickListener() {\n return mOnPreferenceTreeClickListener;\n }\n}\n"} {"task_id": "Java_3046", "language": "Java", "task_type": "for_statement", "source_file": "java/github/MIT-PAC/droidsafe-src/modeling/api/android/preference/PreferenceManager.java", "mask_start_position": 32044, "mask_end_position": 32199, "canonical_solution": "for (int i = 0; i < N; i++) {\n if (list.get(i).onActivityResult(requestCode, resultCode, data)) {\n break;\n }\n }", "pre_mask_code": "/*\n * \n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://example.com\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * ** THIS FILE HAS BEEN MODIFIED FROM THE ORIGINAL BY THE DROIDSAFE PROJECT. ****\n */\npackage android.preference;\n\n// Droidsafe Imports\nimport droidsafe.runtime.*;\nimport droidsafe.helpers.*;\nimport android.util.Log;\nimport droidsafe.annotations.*;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.content.pm.ActivityInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.PackageManager.NameNotFoundException;\nimport android.content.pm.ResolveInfo;\nimport android.content.res.XmlResourceParser;\nimport android.os.Bundle;\n\npublic class PreferenceManager {\n\n /**\n * Gets a SharedPreferences instance that points to the default file that is\n * used by the preference framework in the given context.\n *\n * @param context The context of the preferences whose values are wanted.\n * @return A SharedPreferences instance that can be used to retrieve and\n * listen to values of the preferences.\n */\n @DSComment(\"From safe class list\")\n @DSSafe(DSCat.SAFE_LIST)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.726 -0500\", hash_original_method = \"DEE839A83C4B35ACEA8CCC2B71E2B5D1\", hash_generated_method = \"2B16C131215B04C3D72C14303B6B379E\")\n public static SharedPreferences getDefaultSharedPreferences(Context context) {\n return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.728 -0500\", hash_original_method = \"42C9CE230DD05245AC0F1F15B9BA0F77\", hash_generated_method = \"C0A43771BC0878E5F7FF1D24F0A68563\")\n private static String getDefaultSharedPreferencesName(Context context) {\n return context.getPackageName() + \"_preferences\";\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.730 -0500\", hash_original_method = \"9A4A0B76FBD75A7A2387EF85E0D2FD54\", hash_generated_method = \"D84FC8AF76E7CF2269D44A6A6D9A3736\")\n private static int getDefaultSharedPreferencesMode() {\n return Context.MODE_PRIVATE;\n }\n\n /**\n * Sets the default values from a preference hierarchy in XML. This should\n * be called by the application's main activity.\n *

\n * If {@code readAgain} is false, this will only set the default values if this\n * method has never been called in the past (or the\n * {@link #KEY_HAS_SET_DEFAULT_VALUES} in the default value shared\n * preferences file is false). To attempt to set the default values again\n * bypassing this check, set {@code readAgain} to true.\n *\n * @param context The context of the shared preferences.\n * @param resId The resource ID of the preference hierarchy XML file.\n * @param readAgain Whether to re-read the default values.\n *

\n * Note: this will NOT reset preferences back to their default\n * values. For that functionality, use\n * {@link PreferenceManager#getDefaultSharedPreferences(Context)}\n * and clear it followed by a call to this method with this\n * parameter set to true.\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSafe(DSCat.SAFE_LIST)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.739 -0500\", hash_original_method = \"1B08E289995C6C21F5C2BC4F9B6F5187\", hash_generated_method = \"3DC84A33A3C2DB62DE5115DFA6B9F88B\")\n public static void setDefaultValues(Context context, int resId, boolean readAgain) {\n // Use the default shared preferences name and mode\n setDefaultValues(context, getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode(), resId, readAgain);\n }\n\n /**\n * Similar to {@link #setDefaultValues(Context, int, boolean)} but allows\n * the client to provide the filename and mode of the shared preferences\n * file.\n *\n * @see #setDefaultValues(Context, int, boolean)\n * @see #setSharedPreferencesName(String)\n * @see #setSharedPreferencesMode(int)\n */\n @DSSafe(DSCat.SAFE_OTHERS)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.741 -0500\", hash_original_method = \"9646A9372ECC55871733A680E62A72CA\", hash_generated_method = \"2F9BBD3261B2D934E006F58101CB7E9C\")\n public static void setDefaultValues(Context context, String sharedPreferencesName, int sharedPreferencesMode, int resId, boolean readAgain) {\n final SharedPreferences defaultValueSp = context.getSharedPreferences(KEY_HAS_SET_DEFAULT_VALUES, Context.MODE_PRIVATE);\n if (readAgain || !defaultValueSp.getBoolean(KEY_HAS_SET_DEFAULT_VALUES, false)) {\n final PreferenceManager pm = new PreferenceManager(context);\n pm.setSharedPreferencesName(sharedPreferencesName);\n pm.setSharedPreferencesMode(sharedPreferencesMode);\n pm.inflateFromResource(context, resId, null);\n SharedPreferences.Editor editor = defaultValueSp.edit().putBoolean(KEY_HAS_SET_DEFAULT_VALUES, true);\n try {\n editor.apply();\n } catch (AbstractMethodError unused) {\n // The app injected its own pre-Gingerbread\n // SharedPreferences.Editor implementation without\n // an apply method.\n editor.commit();\n }\n }\n }\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.652 -0500\", hash_original_field = \"3A3BD45FA93DD50F7F6C52D2CEF15DB2\", hash_generated_field = \"7AAEA04E4548D5AB6EC8143F21A30EA9\")\n private static final String TAG = \"PreferenceManager\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.654 -0500\", hash_original_field = \"F86CBB3D5E7D46D5EC5C061B27A4EB7F\", hash_generated_field = \"6C182C497B18AE33867D48A4D7F5655E\")\n public static final String METADATA_KEY_PREFERENCES = \"android.preference\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.656 -0500\", hash_original_field = \"A25C8F9EA6A0FB10147CB42E8AE48EF6\", hash_generated_field = \"99247B06873D9B62D5B8F33E5FB96366\")\n public static final String KEY_HAS_SET_DEFAULT_VALUES = \"_has_set_default_values\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.658 -0500\", hash_original_field = \"3895D7E6DB5042DA7856DC78E391C7B9\", hash_generated_field = \"B0D69375984D6EE7DC93AC12DB4DFC55\")\n private Activity mActivity;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.661 -0500\", hash_original_field = \"8520498A009FD770816A73BC7BBAAE33\", hash_generated_field = \"CFB43EBA13761D69B30BE1C8ABC90FE3\")\n private PreferenceFragment mFragment;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.663 -0500\", hash_original_field = \"B997E37019471EC8FC5B98148C7A8AD7\", hash_generated_field = \"C458E619396054F78BC926FB81B4386D\")\n private Context mContext;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.665 -0500\", hash_original_field = \"94D2C61B90F9DDCEA6229CFD1BD4B5A5\", hash_generated_field = \"5707822036BF051C0059AD070444BD58\")\n private long mNextId = 0;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.667 -0500\", hash_original_field = \"0BEC202ACD2F4B80A9D91BEF44E417AC\", hash_generated_field = \"AD359E85C996698973B9458D92AF4B64\")\n private int mNextRequestCode;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.669 -0500\", hash_original_field = \"6863CBC1FD02A5848172EE011B9C880B\", hash_generated_field = \"E69BF347D3F561905392BD5BBB86A4AF\")\n private SharedPreferences mSharedPreferences;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.671 -0500\", hash_original_field = \"C2C898D216011536ABB52408727E0074\", hash_generated_field = \"93BFA57AAD9A25C531F3726BE9E311D1\")\n private SharedPreferences.Editor mEditor;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.673 -0500\", hash_original_field = \"DD8CF6ABD3E3C3CF856EF58396F040C3\", hash_generated_field = \"0870CFBDAD0F12B21EFE736694E5D5A0\")\n private boolean mNoCommit;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.675 -0500\", hash_original_field = \"84C67C1FD7D5449453BD7928216DE986\", hash_generated_field = \"08A9F51924058A9BDDEB8AE59F95CBF8\")\n private String mSharedPreferencesName;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.677 -0500\", hash_original_field = \"A3A8925479C449E7BF4F11709ABEAFA6\", hash_generated_field = \"3DFD0E17BB5556DF650F1E4262E37691\")\n private int mSharedPreferencesMode;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.679 -0500\", hash_original_field = \"FA341E6EF4A389944B6ABCC0C00AA260\", hash_generated_field = \"6929FA68B759CC402927F67ADE03851B\")\n private PreferenceScreen mPreferenceScreen;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.681 -0500\", hash_original_field = \"5A55F2E03C7E028B9F56681221DAC65B\", hash_generated_field = \"759FE206EC137F2D102DEE69CB506E29\")\n private List mActivityResultListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.684 -0500\", hash_original_field = \"B48C98E3D9D54A0CB2952B7439998405\", hash_generated_field = \"AB511ABA80C53F6AD5EC1856C35DAF7F\")\n private List mActivityStopListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.686 -0500\", hash_original_field = \"C29EDB5974FA1CC8018E563C739E55BF\", hash_generated_field = \"ED711A008E3B4CD7A93067555688693E\")\n private List mActivityDestroyListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.688 -0500\", hash_original_field = \"DDDDE82983F75A043C150207C23DA1FF\", hash_generated_field = \"EEC46A0D6BAD420AFB426C404E85D2BA\")\n private List mPreferencesScreens;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.690 -0500\", hash_original_field = \"7B1980F7CD2856B99E6CF8987DD8E986\", hash_generated_field = \"420F1647C8F11E826C9DE0A838CD7533\")\n private OnPreferenceTreeClickListener mOnPreferenceTreeClickListener;\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.693 -0500\", hash_original_method = \"A48679E26B4CF910ADEF8C7563331346\", hash_generated_method = \"A48679E26B4CF910ADEF8C7563331346\")\n PreferenceManager(Activity activity, int firstRequestCode) {\n mActivity = activity;\n mNextRequestCode = firstRequestCode;\n init(activity);\n }\n\n /**\n * This constructor should ONLY be used when getting default values from\n * an XML preference hierarchy.\n *

\n * The {@link PreferenceManager#PreferenceManager(Activity)}\n * should be used ANY time a preference will be displayed, since some preference\n * types need an Activity for managed queries.\n */\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.695 -0500\", hash_original_method = \"962D66AE85693F6FF77A2DEF54D76478\", hash_generated_method = \"F4455A393DE301F35622852BA02E91EE\")\n private PreferenceManager(Context context) {\n init(context);\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.697 -0500\", hash_original_method = \"2AA94A8F94EE739DE2B0DB27540BEB34\", hash_generated_method = \"E716CEF61FDD32C708F8A58ED93D2B72\")\n private void init(Context context) {\n mContext = context;\n setSharedPreferencesName(getDefaultSharedPreferencesName(context));\n }\n\n /**\n * Sets the owning preference fragment\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.699 -0500\", hash_original_method = \"922F3E36F99E52FA3036E92080002B11\", hash_generated_method = \"922F3E36F99E52FA3036E92080002B11\")\n void setFragment(PreferenceFragment fragment) {\n mFragment = fragment;\n }\n\n /**\n * Returns the owning preference fragment, if any.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.701 -0500\", hash_original_method = \"11BC570017448843B9A9A22E52E0E479\", hash_generated_method = \"11BC570017448843B9A9A22E52E0E479\")\n PreferenceFragment getFragment() {\n return mFragment;\n }\n\n /**\n * Returns a list of {@link Activity} (indirectly) that match a given\n * {@link Intent}.\n *\n * @param queryIntent The Intent to match.\n * @return The list of {@link ResolveInfo} that point to the matched\n * activities.\n */\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.703 -0500\", hash_original_method = \"6682C9F88019B1A37FE99B0D2B3B34A2\", hash_generated_method = \"051844387A24EAE487A48C8117E4273D\")\n private List queryIntentActivities(Intent queryIntent) {\n return mContext.getPackageManager().queryIntentActivities(queryIntent, PackageManager.GET_META_DATA);\n }\n\n /**\n * Inflates a preference hierarchy from the preference hierarchies of\n * {@link Activity Activities} that match the given {@link Intent}. An\n * {@link Activity} defines its preference hierarchy with meta-data using\n * the {@link #METADATA_KEY_PREFERENCES} key.\n *

\n * If a preference hierarchy is given, the new preference hierarchies will\n * be merged in.\n *\n * @param queryIntent The intent to match activities.\n * @param rootPreferences Optional existing hierarchy to merge the new\n * hierarchies into.\n * @return The root hierarchy (if one was not provided, the new hierarchy's\n * root).\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.707 -0500\", hash_original_method = \"96A93C80BB9070BDED20D9AB85FFA8E8\", hash_generated_method = \"DBE5D9014245D9646FD40A2413C6069E\")\n PreferenceScreen inflateFromIntent(Intent queryIntent, PreferenceScreen rootPreferences) {\n final List activities = queryIntentActivities(queryIntent);\n final HashSet inflatedRes = new HashSet();\n for (int i = activities.size() - 1; i >= 0; i--) {\n final ActivityInfo activityInfo = activities.get(i).activityInfo;\n final Bundle metaData = activityInfo.metaData;\n if ((metaData == null) || !metaData.containsKey(METADATA_KEY_PREFERENCES)) {\n continue;\n }\n // Need to concat the package with res ID since the same res ID\n // can be re-used across contexts\n final String uniqueResId = activityInfo.packageName + \":\" + activityInfo.metaData.getInt(METADATA_KEY_PREFERENCES);\n if (!inflatedRes.contains(uniqueResId)) {\n inflatedRes.add(uniqueResId);\n final Context context;\n try {\n context = mContext.createPackageContext(activityInfo.packageName, 0);\n } catch (NameNotFoundException e) {\n Log.w(TAG, \"Could not create context for \" + activityInfo.packageName + \": \" + Log.getStackTraceString(e));\n continue;\n }\n final PreferenceInflater inflater = new PreferenceInflater(context, this);\n final XmlResourceParser parser = activityInfo.loadXmlMetaData(context.getPackageManager(), METADATA_KEY_PREFERENCES);\n rootPreferences = (PreferenceScreen) inflater.inflate(parser, rootPreferences, true);\n parser.close();\n }\n }\n rootPreferences.onAttachedToHierarchy(this);\n return rootPreferences;\n }\n\n /**\n * Inflates a preference hierarchy from XML. If a preference hierarchy is\n * given, the new preference hierarchies will be merged in.\n *\n * @param context The context of the resource.\n * @param resId The resource ID of the XML to inflate.\n * @param rootPreferences Optional existing hierarchy to merge the new\n * hierarchies into.\n * @return The root hierarchy (if one was not provided, the new hierarchy's\n * root).\n * @hide\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.709 -0500\", hash_original_method = \"94F9DF66CFF516C2DE1B651AB9A3388E\", hash_generated_method = \"F0AFDC09FF8BB70BC36CA61F47DEE655\")\n public PreferenceScreen inflateFromResource(Context context, int resId, PreferenceScreen rootPreferences) {\n // Block commits\n setNoCommit(true);\n final PreferenceInflater inflater = new PreferenceInflater(context, this);\n rootPreferences = (PreferenceScreen) inflater.inflate(resId, rootPreferences, true);\n rootPreferences.onAttachedToHierarchy(this);\n // Unblock commits\n setNoCommit(false);\n return rootPreferences;\n }\n\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.711 -0500\", hash_original_method = \"AE92D4BACEE41B351C64A7E59B1B4342\", hash_generated_method = \"E2CDEBF8828B208E67A9E92B6039C90D\")\n public PreferenceScreen createPreferenceScreen(Context context) {\n final PreferenceScreen preferenceScreen = new PreferenceScreen(context, null);\n preferenceScreen.onAttachedToHierarchy(this);\n return preferenceScreen;\n }\n\n /**\n * Called by a preference to get a unique ID in its hierarchy.\n *\n * @return A unique ID.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.713 -0500\", hash_original_method = \"D904EAF0B6D90BB52E1F8594EC3F4D15\", hash_generated_method = \"D904EAF0B6D90BB52E1F8594EC3F4D15\")\n long getNextId() {\n synchronized (this) {\n return mNextId++;\n }\n }\n\n /**\n * Returns the current name of the SharedPreferences file that preferences managed by\n * this will use.\n *\n * @return The name that can be passed to {@link Context#getSharedPreferences(String, int)}.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.715 -0500\", hash_original_method = \"BDB110631059975A566BD4AA87A106E8\", hash_generated_method = \"D7DFCD75F95FBE67D23A3991103EABD7\")\n public String getSharedPreferencesName() {\n return mSharedPreferencesName;\n }\n\n /**\n * Sets the name of the SharedPreferences file that preferences managed by this\n * will use.\n *\n * @param sharedPreferencesName The name of the SharedPreferences file.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.717 -0500\", hash_original_method = \"F8FB75CAC643ECF72FE6E9CDE35245C6\", hash_generated_method = \"D3C3B5611FB8BEDC3068F55C7516B295\")\n public void setSharedPreferencesName(String sharedPreferencesName) {\n mSharedPreferencesName = sharedPreferencesName;\n mSharedPreferences = null;\n }\n\n /**\n * Returns the current mode of the SharedPreferences file that preferences managed by\n * this will use.\n *\n * @return The mode that can be passed to {@link Context#getSharedPreferences(String, int)}.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.719 -0500\", hash_original_method = \"D2CF6E8640E20A030077A21285843C05\", hash_generated_method = \"B34187E4A80B6C182ADA869B95EED2EC\")\n public int getSharedPreferencesMode() {\n return mSharedPreferencesMode;\n }\n\n /**\n * Sets the mode of the SharedPreferences file that preferences managed by this\n * will use.\n *\n * @param sharedPreferencesMode The mode of the SharedPreferences file.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.721 -0500\", hash_original_method = \"6988E36A0998B14CBE7D70DCBAB74FF8\", hash_generated_method = \"8C8607EA8C2F96D19E7B38EF0A94EFB6\")\n public void setSharedPreferencesMode(int sharedPreferencesMode) {\n mSharedPreferencesMode = sharedPreferencesMode;\n mSharedPreferences = null;\n }\n\n /**\n * Gets a SharedPreferences instance that preferences managed by this will\n * use.\n *\n * @return A SharedPreferences instance pointing to the file that contains\n * the values of preferences that are managed by this.\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.724 -0500\", hash_original_method = \"B901A30CD0A7131EC29E8BD072ADC21D\", hash_generated_method = \"9CA9AF2288C06BC076812E1B81D8C766\")\n public SharedPreferences getSharedPreferences() {\n if (mSharedPreferences == null) {\n mSharedPreferences = mContext.getSharedPreferences(mSharedPreferencesName, mSharedPreferencesMode);\n }\n return mSharedPreferences;\n }\n\n /**\n * Returns the root of the preference hierarchy managed by this class.\n *\n * @return The {@link PreferenceScreen} object that is at the root of the hierarchy.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.732 -0500\", hash_original_method = \"60967B21FA602EB86E9B5EB647B08AF2\", hash_generated_method = \"60967B21FA602EB86E9B5EB647B08AF2\")\n PreferenceScreen getPreferenceScreen() {\n return mPreferenceScreen;\n }\n\n /**\n * Sets the root of the preference hierarchy.\n *\n * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.\n * @return Whether the {@link PreferenceScreen} given is different than the previous.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.734 -0500\", hash_original_method = \"72F330353D1AAD0C361FC98ABB0551E0\", hash_generated_method = \"72F330353D1AAD0C361FC98ABB0551E0\")\n boolean setPreferences(PreferenceScreen preferenceScreen) {\n if (preferenceScreen != mPreferenceScreen) {\n mPreferenceScreen = preferenceScreen;\n return true;\n }\n return false;\n }\n\n /**\n * Finds a {@link Preference} based on its key.\n *\n * @param key The key of the preference to retrieve.\n * @return The {@link Preference} with the key, or null.\n * @see PreferenceGroup#findPreference(CharSequence)\n */\n @DSComment(\"May change system behavior\")\n @DSSpec(DSCat.SYSTEM)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.737 -0500\", hash_original_method = \"313075D13AC6A3D78BD3127C39A86211\", hash_generated_method = \"17D4C85ACE0ADBEB3C87DB5BE0FA1596\")\n public Preference findPreference(CharSequence key) {\n if (mPreferenceScreen == null) {\n return null;\n }\n return mPreferenceScreen.findPreference(key);\n }\n\n /**\n * Returns an editor to use when modifying the shared preferences.\n *

\n * Do NOT commit unless {@link #shouldCommit()} returns true.\n *\n * @return An editor to use to write to shared preferences.\n * @see #shouldCommit()\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.743 -0500\", hash_original_method = \"D4733D45210A4F96431F976F3F9AB3C2\", hash_generated_method = \"D4733D45210A4F96431F976F3F9AB3C2\")\n SharedPreferences.Editor getEditor() {\n if (mNoCommit) {\n if (mEditor == null) {\n mEditor = getSharedPreferences().edit();\n }\n return mEditor;\n } else {\n return getSharedPreferences().edit();\n }\n }\n\n /**\n * Whether it is the client's responsibility to commit on the\n * {@link #getEditor()}. This will return false in cases where the writes\n * should be batched, for example when inflating preferences from XML.\n *\n * @return Whether the client should commit.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.746 -0500\", hash_original_method = \"47C154426E8AAB84597A7B272BF8D2FA\", hash_generated_method = \"47C154426E8AAB84597A7B272BF8D2FA\")\n boolean shouldCommit() {\n return !mNoCommit;\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.748 -0500\", hash_original_method = \"2ED947FD2CD87E45A298D362CE1C3C54\", hash_generated_method = \"E1BD2FA4925352CE9F59025D474FA77C\")\n private void setNoCommit(boolean noCommit) {\n if (!noCommit && mEditor != null) {\n try {\n mEditor.apply();\n } catch (AbstractMethodError unused) {\n // The app injected its own pre-Gingerbread\n // SharedPreferences.Editor implementation without\n // an apply method.\n mEditor.commit();\n }\n }\n mNoCommit = noCommit;\n }\n\n /**\n * Returns the activity that shows the preferences. This is useful for doing\n * managed queries, but in most cases the use of {@link #getContext()} is\n * preferred.\n *

\n * This will return null if this class was instantiated with a Context\n * instead of Activity. For example, when setting the default values.\n *\n * @return The activity that shows the preferences.\n * @see #mContext\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.751 -0500\", hash_original_method = \"3F17133E8D63AE8C7414DC58966291E3\", hash_generated_method = \"3F17133E8D63AE8C7414DC58966291E3\")\n Activity getActivity() {\n return mActivity;\n }\n\n /**\n * Returns the context. This is preferred over {@link #getActivity()} when\n * possible.\n *\n * @return The context.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.753 -0500\", hash_original_method = \"4F4EBC54D108D66F416C93B46580E117\", hash_generated_method = \"4F4EBC54D108D66F416C93B46580E117\")\n Context getContext() {\n return mContext;\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityResultListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.755 -0500\", hash_original_method = \"8C7924F669844968ABD2440B12D35A69\", hash_generated_method = \"8C7924F669844968ABD2440B12D35A69\")\n void registerOnActivityResultListener(OnActivityResultListener listener) {\n synchronized (this) {\n if (mActivityResultListeners == null) {\n mActivityResultListeners = new ArrayList();\n }\n if (!mActivityResultListeners.contains(listener)) {\n mActivityResultListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityResultListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.757 -0500\", hash_original_method = \"2F16D3A7CC67220808B5AF6C63D00415\", hash_generated_method = \"2F16D3A7CC67220808B5AF6C63D00415\")\n void unregisterOnActivityResultListener(OnActivityResultListener listener) {\n synchronized (this) {\n if (mActivityResultListeners != null) {\n mActivityResultListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch a subactivity result.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.760 -0500\", hash_original_method = \"A3EFE32034D38DFF1A90F9A5F45D56A6\", hash_generated_method = \"A3EFE32034D38DFF1A90F9A5F45D56A6\")\n void dispatchActivityResult(int requestCode, int resultCode, Intent data) {\n List list;\n synchronized (this) {\n if (mActivityResultListeners == null)\n return;\n list = new ArrayList(mActivityResultListeners);\n }\n final int N = list.size();\n ", "post_mask_code": "\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityStopListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.762 -0500\", hash_original_method = \"2A0808589AAB6A9778EC4C51EF499853\", hash_generated_method = \"2A0808589AAB6A9778EC4C51EF499853\")\n void registerOnActivityStopListener(OnActivityStopListener listener) {\n synchronized (this) {\n if (mActivityStopListeners == null) {\n mActivityStopListeners = new ArrayList();\n }\n if (!mActivityStopListeners.contains(listener)) {\n mActivityStopListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityStopListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.764 -0500\", hash_original_method = \"D042C49681BB57CB7E14977DE37ED6E0\", hash_generated_method = \"D042C49681BB57CB7E14977DE37ED6E0\")\n void unregisterOnActivityStopListener(OnActivityStopListener listener) {\n synchronized (this) {\n if (mActivityStopListeners != null) {\n mActivityStopListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch the activity stop\n * event.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.766 -0500\", hash_original_method = \"6FD57C464C4DA57829A6C2B52E45A452\", hash_generated_method = \"6FD57C464C4DA57829A6C2B52E45A452\")\n void dispatchActivityStop() {\n List list;\n synchronized (this) {\n if (mActivityStopListeners == null)\n return;\n list = new ArrayList(mActivityStopListeners);\n }\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n list.get(i).onActivityStop();\n }\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityDestroyListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.768 -0500\", hash_original_method = \"8932A6D76CD73EDD58651F522607034F\", hash_generated_method = \"8932A6D76CD73EDD58651F522607034F\")\n void registerOnActivityDestroyListener(OnActivityDestroyListener listener) {\n synchronized (this) {\n if (mActivityDestroyListeners == null) {\n mActivityDestroyListeners = new ArrayList();\n }\n if (!mActivityDestroyListeners.contains(listener)) {\n mActivityDestroyListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityDestroyListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.770 -0500\", hash_original_method = \"221E9A8BD7E96AD4198B64196703C2D4\", hash_generated_method = \"221E9A8BD7E96AD4198B64196703C2D4\")\n void unregisterOnActivityDestroyListener(OnActivityDestroyListener listener) {\n synchronized (this) {\n if (mActivityDestroyListeners != null) {\n mActivityDestroyListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch the activity destroy\n * event.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.773 -0500\", hash_original_method = \"ABC0DFC11A448AE601035D9520ECAF99\", hash_generated_method = \"A50EB56106E28498551C2918E03A855A\")\n void dispatchActivityDestroy() {\n List list = null;\n synchronized (this) {\n if (mActivityDestroyListeners != null) {\n list = new ArrayList(mActivityDestroyListeners);\n }\n }\n if (list != null) {\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n list.get(i).onActivityDestroy();\n }\n }\n // Dismiss any PreferenceScreens still showing\n dismissAllScreens();\n }\n\n /**\n * Returns a request code that is unique for the activity. Each subsequent\n * call to this method should return another unique request code.\n *\n * @return A unique request code that will never be used by anyone other\n * than the caller of this method.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.775 -0500\", hash_original_method = \"74A43F7F50012109C1C50A128DECA709\", hash_generated_method = \"74A43F7F50012109C1C50A128DECA709\")\n int getNextRequestCode() {\n synchronized (this) {\n return mNextRequestCode++;\n }\n }\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.777 -0500\", hash_original_method = \"64532379007357BDD2B5A06E80A12A41\", hash_generated_method = \"64532379007357BDD2B5A06E80A12A41\")\n void addPreferencesScreen(DialogInterface screen) {\n synchronized (this) {\n if (mPreferencesScreens == null) {\n mPreferencesScreens = new ArrayList();\n }\n mPreferencesScreens.add(screen);\n }\n }\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.779 -0500\", hash_original_method = \"98728EB5C20211F6C02CB983C1971CE8\", hash_generated_method = \"98728EB5C20211F6C02CB983C1971CE8\")\n void removePreferencesScreen(DialogInterface screen) {\n synchronized (this) {\n if (mPreferencesScreens == null) {\n return;\n }\n mPreferencesScreens.remove(screen);\n }\n }\n\n /**\n * Called by {@link PreferenceActivity} to dispatch the new Intent event.\n *\n * @param intent The new Intent.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.781 -0500\", hash_original_method = \"4573B347852C64DB794205DBF1F726CF\", hash_generated_method = \"4573B347852C64DB794205DBF1F726CF\")\n void dispatchNewIntent(Intent intent) {\n dismissAllScreens();\n }\n\n interface OnPreferenceTreeClickListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference);\n }\n\n public interface OnActivityResultListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n boolean onActivityResult(int requestCode, int resultCode, Intent data);\n }\n\n public interface OnActivityStopListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n void onActivityStop();\n }\n\n public interface OnActivityDestroyListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n void onActivityDestroy();\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.784 -0500\", hash_original_method = \"9025418B8BBAFCD2E271951C43610D69\", hash_generated_method = \"DCBAF81ECD7B379BC2C84590968F3DB8\")\n private void dismissAllScreens() {\n // Remove any of the previously shown preferences screens\n ArrayList screensToDismiss;\n synchronized (this) {\n if (mPreferencesScreens == null) {\n return;\n }\n screensToDismiss = new ArrayList(mPreferencesScreens);\n mPreferencesScreens.clear();\n }\n for (int i = screensToDismiss.size() - 1; i >= 0; i--) {\n screensToDismiss.get(i).dismiss();\n }\n }\n\n /**\n * Sets the callback to be invoked when a {@link Preference} in the\n * hierarchy rooted at this {@link PreferenceManager} is clicked.\n *\n * @param listener The callback to be invoked.\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.785 -0500\", hash_original_method = \"285310B7C58E8A2220B6B265614A6D90\", hash_generated_method = \"285310B7C58E8A2220B6B265614A6D90\")\n void setOnPreferenceTreeClickListener(OnPreferenceTreeClickListener listener) {\n mOnPreferenceTreeClickListener = listener;\n }\n\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.787 -0500\", hash_original_method = \"44D09E26591D5A19BD471058A1477B47\", hash_generated_method = \"44D09E26591D5A19BD471058A1477B47\")\n OnPreferenceTreeClickListener getOnPreferenceTreeClickListener() {\n return mOnPreferenceTreeClickListener;\n }\n}\n"} {"task_id": "Java_3047", "language": "Java", "task_type": "try_statement", "source_file": "java/github/MIT-PAC/droidsafe-src/modeling/api/android/preference/PreferenceManager.java", "mask_start_position": 6021, "mask_end_position": 6319, "canonical_solution": "try {\n editor.apply();\n } catch (AbstractMethodError unused) {\n // The app injected its own pre-Gingerbread\n // SharedPreferences.Editor implementation without\n // an apply method.\n editor.commit();\n }", "pre_mask_code": "/*\n * \n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://example.com\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * ** THIS FILE HAS BEEN MODIFIED FROM THE ORIGINAL BY THE DROIDSAFE PROJECT. ****\n */\npackage android.preference;\n\n// Droidsafe Imports\nimport droidsafe.runtime.*;\nimport droidsafe.helpers.*;\nimport android.util.Log;\nimport droidsafe.annotations.*;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.content.pm.ActivityInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.PackageManager.NameNotFoundException;\nimport android.content.pm.ResolveInfo;\nimport android.content.res.XmlResourceParser;\nimport android.os.Bundle;\n\npublic class PreferenceManager {\n\n /**\n * Gets a SharedPreferences instance that points to the default file that is\n * used by the preference framework in the given context.\n *\n * @param context The context of the preferences whose values are wanted.\n * @return A SharedPreferences instance that can be used to retrieve and\n * listen to values of the preferences.\n */\n @DSComment(\"From safe class list\")\n @DSSafe(DSCat.SAFE_LIST)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.726 -0500\", hash_original_method = \"DEE839A83C4B35ACEA8CCC2B71E2B5D1\", hash_generated_method = \"2B16C131215B04C3D72C14303B6B379E\")\n public static SharedPreferences getDefaultSharedPreferences(Context context) {\n return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.728 -0500\", hash_original_method = \"42C9CE230DD05245AC0F1F15B9BA0F77\", hash_generated_method = \"C0A43771BC0878E5F7FF1D24F0A68563\")\n private static String getDefaultSharedPreferencesName(Context context) {\n return context.getPackageName() + \"_preferences\";\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.730 -0500\", hash_original_method = \"9A4A0B76FBD75A7A2387EF85E0D2FD54\", hash_generated_method = \"D84FC8AF76E7CF2269D44A6A6D9A3736\")\n private static int getDefaultSharedPreferencesMode() {\n return Context.MODE_PRIVATE;\n }\n\n /**\n * Sets the default values from a preference hierarchy in XML. This should\n * be called by the application's main activity.\n *

\n * If {@code readAgain} is false, this will only set the default values if this\n * method has never been called in the past (or the\n * {@link #KEY_HAS_SET_DEFAULT_VALUES} in the default value shared\n * preferences file is false). To attempt to set the default values again\n * bypassing this check, set {@code readAgain} to true.\n *\n * @param context The context of the shared preferences.\n * @param resId The resource ID of the preference hierarchy XML file.\n * @param readAgain Whether to re-read the default values.\n *

\n * Note: this will NOT reset preferences back to their default\n * values. For that functionality, use\n * {@link PreferenceManager#getDefaultSharedPreferences(Context)}\n * and clear it followed by a call to this method with this\n * parameter set to true.\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSafe(DSCat.SAFE_LIST)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.739 -0500\", hash_original_method = \"1B08E289995C6C21F5C2BC4F9B6F5187\", hash_generated_method = \"3DC84A33A3C2DB62DE5115DFA6B9F88B\")\n public static void setDefaultValues(Context context, int resId, boolean readAgain) {\n // Use the default shared preferences name and mode\n setDefaultValues(context, getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode(), resId, readAgain);\n }\n\n /**\n * Similar to {@link #setDefaultValues(Context, int, boolean)} but allows\n * the client to provide the filename and mode of the shared preferences\n * file.\n *\n * @see #setDefaultValues(Context, int, boolean)\n * @see #setSharedPreferencesName(String)\n * @see #setSharedPreferencesMode(int)\n */\n @DSSafe(DSCat.SAFE_OTHERS)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.741 -0500\", hash_original_method = \"9646A9372ECC55871733A680E62A72CA\", hash_generated_method = \"2F9BBD3261B2D934E006F58101CB7E9C\")\n public static void setDefaultValues(Context context, String sharedPreferencesName, int sharedPreferencesMode, int resId, boolean readAgain) {\n final SharedPreferences defaultValueSp = context.getSharedPreferences(KEY_HAS_SET_DEFAULT_VALUES, Context.MODE_PRIVATE);\n if (readAgain || !defaultValueSp.getBoolean(KEY_HAS_SET_DEFAULT_VALUES, false)) {\n final PreferenceManager pm = new PreferenceManager(context);\n pm.setSharedPreferencesName(sharedPreferencesName);\n pm.setSharedPreferencesMode(sharedPreferencesMode);\n pm.inflateFromResource(context, resId, null);\n SharedPreferences.Editor editor = defaultValueSp.edit().putBoolean(KEY_HAS_SET_DEFAULT_VALUES, true);\n ", "post_mask_code": "\n }\n }\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.652 -0500\", hash_original_field = \"3A3BD45FA93DD50F7F6C52D2CEF15DB2\", hash_generated_field = \"7AAEA04E4548D5AB6EC8143F21A30EA9\")\n private static final String TAG = \"PreferenceManager\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.654 -0500\", hash_original_field = \"F86CBB3D5E7D46D5EC5C061B27A4EB7F\", hash_generated_field = \"6C182C497B18AE33867D48A4D7F5655E\")\n public static final String METADATA_KEY_PREFERENCES = \"android.preference\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.656 -0500\", hash_original_field = \"A25C8F9EA6A0FB10147CB42E8AE48EF6\", hash_generated_field = \"99247B06873D9B62D5B8F33E5FB96366\")\n public static final String KEY_HAS_SET_DEFAULT_VALUES = \"_has_set_default_values\";\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.658 -0500\", hash_original_field = \"3895D7E6DB5042DA7856DC78E391C7B9\", hash_generated_field = \"B0D69375984D6EE7DC93AC12DB4DFC55\")\n private Activity mActivity;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.661 -0500\", hash_original_field = \"8520498A009FD770816A73BC7BBAAE33\", hash_generated_field = \"CFB43EBA13761D69B30BE1C8ABC90FE3\")\n private PreferenceFragment mFragment;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.663 -0500\", hash_original_field = \"B997E37019471EC8FC5B98148C7A8AD7\", hash_generated_field = \"C458E619396054F78BC926FB81B4386D\")\n private Context mContext;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.665 -0500\", hash_original_field = \"94D2C61B90F9DDCEA6229CFD1BD4B5A5\", hash_generated_field = \"5707822036BF051C0059AD070444BD58\")\n private long mNextId = 0;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.667 -0500\", hash_original_field = \"0BEC202ACD2F4B80A9D91BEF44E417AC\", hash_generated_field = \"AD359E85C996698973B9458D92AF4B64\")\n private int mNextRequestCode;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.669 -0500\", hash_original_field = \"6863CBC1FD02A5848172EE011B9C880B\", hash_generated_field = \"E69BF347D3F561905392BD5BBB86A4AF\")\n private SharedPreferences mSharedPreferences;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.671 -0500\", hash_original_field = \"C2C898D216011536ABB52408727E0074\", hash_generated_field = \"93BFA57AAD9A25C531F3726BE9E311D1\")\n private SharedPreferences.Editor mEditor;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.673 -0500\", hash_original_field = \"DD8CF6ABD3E3C3CF856EF58396F040C3\", hash_generated_field = \"0870CFBDAD0F12B21EFE736694E5D5A0\")\n private boolean mNoCommit;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.675 -0500\", hash_original_field = \"84C67C1FD7D5449453BD7928216DE986\", hash_generated_field = \"08A9F51924058A9BDDEB8AE59F95CBF8\")\n private String mSharedPreferencesName;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.677 -0500\", hash_original_field = \"A3A8925479C449E7BF4F11709ABEAFA6\", hash_generated_field = \"3DFD0E17BB5556DF650F1E4262E37691\")\n private int mSharedPreferencesMode;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.679 -0500\", hash_original_field = \"FA341E6EF4A389944B6ABCC0C00AA260\", hash_generated_field = \"6929FA68B759CC402927F67ADE03851B\")\n private PreferenceScreen mPreferenceScreen;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.681 -0500\", hash_original_field = \"5A55F2E03C7E028B9F56681221DAC65B\", hash_generated_field = \"759FE206EC137F2D102DEE69CB506E29\")\n private List mActivityResultListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.684 -0500\", hash_original_field = \"B48C98E3D9D54A0CB2952B7439998405\", hash_generated_field = \"AB511ABA80C53F6AD5EC1856C35DAF7F\")\n private List mActivityStopListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.686 -0500\", hash_original_field = \"C29EDB5974FA1CC8018E563C739E55BF\", hash_generated_field = \"ED711A008E3B4CD7A93067555688693E\")\n private List mActivityDestroyListeners;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.688 -0500\", hash_original_field = \"DDDDE82983F75A043C150207C23DA1FF\", hash_generated_field = \"EEC46A0D6BAD420AFB426C404E85D2BA\")\n private List mPreferencesScreens;\n\n @DSGeneratedField(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.690 -0500\", hash_original_field = \"7B1980F7CD2856B99E6CF8987DD8E986\", hash_generated_field = \"420F1647C8F11E826C9DE0A838CD7533\")\n private OnPreferenceTreeClickListener mOnPreferenceTreeClickListener;\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.693 -0500\", hash_original_method = \"A48679E26B4CF910ADEF8C7563331346\", hash_generated_method = \"A48679E26B4CF910ADEF8C7563331346\")\n PreferenceManager(Activity activity, int firstRequestCode) {\n mActivity = activity;\n mNextRequestCode = firstRequestCode;\n init(activity);\n }\n\n /**\n * This constructor should ONLY be used when getting default values from\n * an XML preference hierarchy.\n *

\n * The {@link PreferenceManager#PreferenceManager(Activity)}\n * should be used ANY time a preference will be displayed, since some preference\n * types need an Activity for managed queries.\n */\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.695 -0500\", hash_original_method = \"962D66AE85693F6FF77A2DEF54D76478\", hash_generated_method = \"F4455A393DE301F35622852BA02E91EE\")\n private PreferenceManager(Context context) {\n init(context);\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.697 -0500\", hash_original_method = \"2AA94A8F94EE739DE2B0DB27540BEB34\", hash_generated_method = \"E716CEF61FDD32C708F8A58ED93D2B72\")\n private void init(Context context) {\n mContext = context;\n setSharedPreferencesName(getDefaultSharedPreferencesName(context));\n }\n\n /**\n * Sets the owning preference fragment\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.699 -0500\", hash_original_method = \"922F3E36F99E52FA3036E92080002B11\", hash_generated_method = \"922F3E36F99E52FA3036E92080002B11\")\n void setFragment(PreferenceFragment fragment) {\n mFragment = fragment;\n }\n\n /**\n * Returns the owning preference fragment, if any.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.701 -0500\", hash_original_method = \"11BC570017448843B9A9A22E52E0E479\", hash_generated_method = \"11BC570017448843B9A9A22E52E0E479\")\n PreferenceFragment getFragment() {\n return mFragment;\n }\n\n /**\n * Returns a list of {@link Activity} (indirectly) that match a given\n * {@link Intent}.\n *\n * @param queryIntent The Intent to match.\n * @return The list of {@link ResolveInfo} that point to the matched\n * activities.\n */\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.703 -0500\", hash_original_method = \"6682C9F88019B1A37FE99B0D2B3B34A2\", hash_generated_method = \"051844387A24EAE487A48C8117E4273D\")\n private List queryIntentActivities(Intent queryIntent) {\n return mContext.getPackageManager().queryIntentActivities(queryIntent, PackageManager.GET_META_DATA);\n }\n\n /**\n * Inflates a preference hierarchy from the preference hierarchies of\n * {@link Activity Activities} that match the given {@link Intent}. An\n * {@link Activity} defines its preference hierarchy with meta-data using\n * the {@link #METADATA_KEY_PREFERENCES} key.\n *

\n * If a preference hierarchy is given, the new preference hierarchies will\n * be merged in.\n *\n * @param queryIntent The intent to match activities.\n * @param rootPreferences Optional existing hierarchy to merge the new\n * hierarchies into.\n * @return The root hierarchy (if one was not provided, the new hierarchy's\n * root).\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.707 -0500\", hash_original_method = \"96A93C80BB9070BDED20D9AB85FFA8E8\", hash_generated_method = \"DBE5D9014245D9646FD40A2413C6069E\")\n PreferenceScreen inflateFromIntent(Intent queryIntent, PreferenceScreen rootPreferences) {\n final List activities = queryIntentActivities(queryIntent);\n final HashSet inflatedRes = new HashSet();\n for (int i = activities.size() - 1; i >= 0; i--) {\n final ActivityInfo activityInfo = activities.get(i).activityInfo;\n final Bundle metaData = activityInfo.metaData;\n if ((metaData == null) || !metaData.containsKey(METADATA_KEY_PREFERENCES)) {\n continue;\n }\n // Need to concat the package with res ID since the same res ID\n // can be re-used across contexts\n final String uniqueResId = activityInfo.packageName + \":\" + activityInfo.metaData.getInt(METADATA_KEY_PREFERENCES);\n if (!inflatedRes.contains(uniqueResId)) {\n inflatedRes.add(uniqueResId);\n final Context context;\n try {\n context = mContext.createPackageContext(activityInfo.packageName, 0);\n } catch (NameNotFoundException e) {\n Log.w(TAG, \"Could not create context for \" + activityInfo.packageName + \": \" + Log.getStackTraceString(e));\n continue;\n }\n final PreferenceInflater inflater = new PreferenceInflater(context, this);\n final XmlResourceParser parser = activityInfo.loadXmlMetaData(context.getPackageManager(), METADATA_KEY_PREFERENCES);\n rootPreferences = (PreferenceScreen) inflater.inflate(parser, rootPreferences, true);\n parser.close();\n }\n }\n rootPreferences.onAttachedToHierarchy(this);\n return rootPreferences;\n }\n\n /**\n * Inflates a preference hierarchy from XML. If a preference hierarchy is\n * given, the new preference hierarchies will be merged in.\n *\n * @param context The context of the resource.\n * @param resId The resource ID of the XML to inflate.\n * @param rootPreferences Optional existing hierarchy to merge the new\n * hierarchies into.\n * @return The root hierarchy (if one was not provided, the new hierarchy's\n * root).\n * @hide\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.709 -0500\", hash_original_method = \"94F9DF66CFF516C2DE1B651AB9A3388E\", hash_generated_method = \"F0AFDC09FF8BB70BC36CA61F47DEE655\")\n public PreferenceScreen inflateFromResource(Context context, int resId, PreferenceScreen rootPreferences) {\n // Block commits\n setNoCommit(true);\n final PreferenceInflater inflater = new PreferenceInflater(context, this);\n rootPreferences = (PreferenceScreen) inflater.inflate(resId, rootPreferences, true);\n rootPreferences.onAttachedToHierarchy(this);\n // Unblock commits\n setNoCommit(false);\n return rootPreferences;\n }\n\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.711 -0500\", hash_original_method = \"AE92D4BACEE41B351C64A7E59B1B4342\", hash_generated_method = \"E2CDEBF8828B208E67A9E92B6039C90D\")\n public PreferenceScreen createPreferenceScreen(Context context) {\n final PreferenceScreen preferenceScreen = new PreferenceScreen(context, null);\n preferenceScreen.onAttachedToHierarchy(this);\n return preferenceScreen;\n }\n\n /**\n * Called by a preference to get a unique ID in its hierarchy.\n *\n * @return A unique ID.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.713 -0500\", hash_original_method = \"D904EAF0B6D90BB52E1F8594EC3F4D15\", hash_generated_method = \"D904EAF0B6D90BB52E1F8594EC3F4D15\")\n long getNextId() {\n synchronized (this) {\n return mNextId++;\n }\n }\n\n /**\n * Returns the current name of the SharedPreferences file that preferences managed by\n * this will use.\n *\n * @return The name that can be passed to {@link Context#getSharedPreferences(String, int)}.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.715 -0500\", hash_original_method = \"BDB110631059975A566BD4AA87A106E8\", hash_generated_method = \"D7DFCD75F95FBE67D23A3991103EABD7\")\n public String getSharedPreferencesName() {\n return mSharedPreferencesName;\n }\n\n /**\n * Sets the name of the SharedPreferences file that preferences managed by this\n * will use.\n *\n * @param sharedPreferencesName The name of the SharedPreferences file.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.717 -0500\", hash_original_method = \"F8FB75CAC643ECF72FE6E9CDE35245C6\", hash_generated_method = \"D3C3B5611FB8BEDC3068F55C7516B295\")\n public void setSharedPreferencesName(String sharedPreferencesName) {\n mSharedPreferencesName = sharedPreferencesName;\n mSharedPreferences = null;\n }\n\n /**\n * Returns the current mode of the SharedPreferences file that preferences managed by\n * this will use.\n *\n * @return The mode that can be passed to {@link Context#getSharedPreferences(String, int)}.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.719 -0500\", hash_original_method = \"D2CF6E8640E20A030077A21285843C05\", hash_generated_method = \"B34187E4A80B6C182ADA869B95EED2EC\")\n public int getSharedPreferencesMode() {\n return mSharedPreferencesMode;\n }\n\n /**\n * Sets the mode of the SharedPreferences file that preferences managed by this\n * will use.\n *\n * @param sharedPreferencesMode The mode of the SharedPreferences file.\n * @see Context#getSharedPreferences(String, int)\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.721 -0500\", hash_original_method = \"6988E36A0998B14CBE7D70DCBAB74FF8\", hash_generated_method = \"8C8607EA8C2F96D19E7B38EF0A94EFB6\")\n public void setSharedPreferencesMode(int sharedPreferencesMode) {\n mSharedPreferencesMode = sharedPreferencesMode;\n mSharedPreferences = null;\n }\n\n /**\n * Gets a SharedPreferences instance that preferences managed by this will\n * use.\n *\n * @return A SharedPreferences instance pointing to the file that contains\n * the values of preferences that are managed by this.\n */\n @DSComment(\"Request/Change/Listen Android Manger\")\n @DSSpec(DSCat.ANDROID_MANAGER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.724 -0500\", hash_original_method = \"B901A30CD0A7131EC29E8BD072ADC21D\", hash_generated_method = \"9CA9AF2288C06BC076812E1B81D8C766\")\n public SharedPreferences getSharedPreferences() {\n if (mSharedPreferences == null) {\n mSharedPreferences = mContext.getSharedPreferences(mSharedPreferencesName, mSharedPreferencesMode);\n }\n return mSharedPreferences;\n }\n\n /**\n * Returns the root of the preference hierarchy managed by this class.\n *\n * @return The {@link PreferenceScreen} object that is at the root of the hierarchy.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.732 -0500\", hash_original_method = \"60967B21FA602EB86E9B5EB647B08AF2\", hash_generated_method = \"60967B21FA602EB86E9B5EB647B08AF2\")\n PreferenceScreen getPreferenceScreen() {\n return mPreferenceScreen;\n }\n\n /**\n * Sets the root of the preference hierarchy.\n *\n * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.\n * @return Whether the {@link PreferenceScreen} given is different than the previous.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.734 -0500\", hash_original_method = \"72F330353D1AAD0C361FC98ABB0551E0\", hash_generated_method = \"72F330353D1AAD0C361FC98ABB0551E0\")\n boolean setPreferences(PreferenceScreen preferenceScreen) {\n if (preferenceScreen != mPreferenceScreen) {\n mPreferenceScreen = preferenceScreen;\n return true;\n }\n return false;\n }\n\n /**\n * Finds a {@link Preference} based on its key.\n *\n * @param key The key of the preference to retrieve.\n * @return The {@link Preference} with the key, or null.\n * @see PreferenceGroup#findPreference(CharSequence)\n */\n @DSComment(\"May change system behavior\")\n @DSSpec(DSCat.SYSTEM)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.737 -0500\", hash_original_method = \"313075D13AC6A3D78BD3127C39A86211\", hash_generated_method = \"17D4C85ACE0ADBEB3C87DB5BE0FA1596\")\n public Preference findPreference(CharSequence key) {\n if (mPreferenceScreen == null) {\n return null;\n }\n return mPreferenceScreen.findPreference(key);\n }\n\n /**\n * Returns an editor to use when modifying the shared preferences.\n *

\n * Do NOT commit unless {@link #shouldCommit()} returns true.\n *\n * @return An editor to use to write to shared preferences.\n * @see #shouldCommit()\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.743 -0500\", hash_original_method = \"D4733D45210A4F96431F976F3F9AB3C2\", hash_generated_method = \"D4733D45210A4F96431F976F3F9AB3C2\")\n SharedPreferences.Editor getEditor() {\n if (mNoCommit) {\n if (mEditor == null) {\n mEditor = getSharedPreferences().edit();\n }\n return mEditor;\n } else {\n return getSharedPreferences().edit();\n }\n }\n\n /**\n * Whether it is the client's responsibility to commit on the\n * {@link #getEditor()}. This will return false in cases where the writes\n * should be batched, for example when inflating preferences from XML.\n *\n * @return Whether the client should commit.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.746 -0500\", hash_original_method = \"47C154426E8AAB84597A7B272BF8D2FA\", hash_generated_method = \"47C154426E8AAB84597A7B272BF8D2FA\")\n boolean shouldCommit() {\n return !mNoCommit;\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.748 -0500\", hash_original_method = \"2ED947FD2CD87E45A298D362CE1C3C54\", hash_generated_method = \"E1BD2FA4925352CE9F59025D474FA77C\")\n private void setNoCommit(boolean noCommit) {\n if (!noCommit && mEditor != null) {\n try {\n mEditor.apply();\n } catch (AbstractMethodError unused) {\n // The app injected its own pre-Gingerbread\n // SharedPreferences.Editor implementation without\n // an apply method.\n mEditor.commit();\n }\n }\n mNoCommit = noCommit;\n }\n\n /**\n * Returns the activity that shows the preferences. This is useful for doing\n * managed queries, but in most cases the use of {@link #getContext()} is\n * preferred.\n *

\n * This will return null if this class was instantiated with a Context\n * instead of Activity. For example, when setting the default values.\n *\n * @return The activity that shows the preferences.\n * @see #mContext\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.751 -0500\", hash_original_method = \"3F17133E8D63AE8C7414DC58966291E3\", hash_generated_method = \"3F17133E8D63AE8C7414DC58966291E3\")\n Activity getActivity() {\n return mActivity;\n }\n\n /**\n * Returns the context. This is preferred over {@link #getActivity()} when\n * possible.\n *\n * @return The context.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.753 -0500\", hash_original_method = \"4F4EBC54D108D66F416C93B46580E117\", hash_generated_method = \"4F4EBC54D108D66F416C93B46580E117\")\n Context getContext() {\n return mContext;\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityResultListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.755 -0500\", hash_original_method = \"8C7924F669844968ABD2440B12D35A69\", hash_generated_method = \"8C7924F669844968ABD2440B12D35A69\")\n void registerOnActivityResultListener(OnActivityResultListener listener) {\n synchronized (this) {\n if (mActivityResultListeners == null) {\n mActivityResultListeners = new ArrayList();\n }\n if (!mActivityResultListeners.contains(listener)) {\n mActivityResultListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityResultListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.757 -0500\", hash_original_method = \"2F16D3A7CC67220808B5AF6C63D00415\", hash_generated_method = \"2F16D3A7CC67220808B5AF6C63D00415\")\n void unregisterOnActivityResultListener(OnActivityResultListener listener) {\n synchronized (this) {\n if (mActivityResultListeners != null) {\n mActivityResultListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch a subactivity result.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.760 -0500\", hash_original_method = \"A3EFE32034D38DFF1A90F9A5F45D56A6\", hash_generated_method = \"A3EFE32034D38DFF1A90F9A5F45D56A6\")\n void dispatchActivityResult(int requestCode, int resultCode, Intent data) {\n List list;\n synchronized (this) {\n if (mActivityResultListeners == null)\n return;\n list = new ArrayList(mActivityResultListeners);\n }\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n if (list.get(i).onActivityResult(requestCode, resultCode, data)) {\n break;\n }\n }\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityStopListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.762 -0500\", hash_original_method = \"2A0808589AAB6A9778EC4C51EF499853\", hash_generated_method = \"2A0808589AAB6A9778EC4C51EF499853\")\n void registerOnActivityStopListener(OnActivityStopListener listener) {\n synchronized (this) {\n if (mActivityStopListeners == null) {\n mActivityStopListeners = new ArrayList();\n }\n if (!mActivityStopListeners.contains(listener)) {\n mActivityStopListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityStopListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.764 -0500\", hash_original_method = \"D042C49681BB57CB7E14977DE37ED6E0\", hash_generated_method = \"D042C49681BB57CB7E14977DE37ED6E0\")\n void unregisterOnActivityStopListener(OnActivityStopListener listener) {\n synchronized (this) {\n if (mActivityStopListeners != null) {\n mActivityStopListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch the activity stop\n * event.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.766 -0500\", hash_original_method = \"6FD57C464C4DA57829A6C2B52E45A452\", hash_generated_method = \"6FD57C464C4DA57829A6C2B52E45A452\")\n void dispatchActivityStop() {\n List list;\n synchronized (this) {\n if (mActivityStopListeners == null)\n return;\n list = new ArrayList(mActivityStopListeners);\n }\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n list.get(i).onActivityStop();\n }\n }\n\n /**\n * Registers a listener.\n *\n * @see OnActivityDestroyListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.768 -0500\", hash_original_method = \"8932A6D76CD73EDD58651F522607034F\", hash_generated_method = \"8932A6D76CD73EDD58651F522607034F\")\n void registerOnActivityDestroyListener(OnActivityDestroyListener listener) {\n synchronized (this) {\n if (mActivityDestroyListeners == null) {\n mActivityDestroyListeners = new ArrayList();\n }\n if (!mActivityDestroyListeners.contains(listener)) {\n mActivityDestroyListeners.add(listener);\n }\n }\n }\n\n /**\n * Unregisters a listener.\n *\n * @see OnActivityDestroyListener\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.770 -0500\", hash_original_method = \"221E9A8BD7E96AD4198B64196703C2D4\", hash_generated_method = \"221E9A8BD7E96AD4198B64196703C2D4\")\n void unregisterOnActivityDestroyListener(OnActivityDestroyListener listener) {\n synchronized (this) {\n if (mActivityDestroyListeners != null) {\n mActivityDestroyListeners.remove(listener);\n }\n }\n }\n\n /**\n * Called by the {@link PreferenceManager} to dispatch the activity destroy\n * event.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.773 -0500\", hash_original_method = \"ABC0DFC11A448AE601035D9520ECAF99\", hash_generated_method = \"A50EB56106E28498551C2918E03A855A\")\n void dispatchActivityDestroy() {\n List list = null;\n synchronized (this) {\n if (mActivityDestroyListeners != null) {\n list = new ArrayList(mActivityDestroyListeners);\n }\n }\n if (list != null) {\n final int N = list.size();\n for (int i = 0; i < N; i++) {\n list.get(i).onActivityDestroy();\n }\n }\n // Dismiss any PreferenceScreens still showing\n dismissAllScreens();\n }\n\n /**\n * Returns a request code that is unique for the activity. Each subsequent\n * call to this method should return another unique request code.\n *\n * @return A unique request code that will never be used by anyone other\n * than the caller of this method.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSSource({ DSSourceKind.SENSITIVE_UNCATEGORIZED })\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.775 -0500\", hash_original_method = \"74A43F7F50012109C1C50A128DECA709\", hash_generated_method = \"74A43F7F50012109C1C50A128DECA709\")\n int getNextRequestCode() {\n synchronized (this) {\n return mNextRequestCode++;\n }\n }\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.777 -0500\", hash_original_method = \"64532379007357BDD2B5A06E80A12A41\", hash_generated_method = \"64532379007357BDD2B5A06E80A12A41\")\n void addPreferencesScreen(DialogInterface screen) {\n synchronized (this) {\n if (mPreferencesScreens == null) {\n mPreferencesScreens = new ArrayList();\n }\n mPreferencesScreens.add(screen);\n }\n }\n\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.779 -0500\", hash_original_method = \"98728EB5C20211F6C02CB983C1971CE8\", hash_generated_method = \"98728EB5C20211F6C02CB983C1971CE8\")\n void removePreferencesScreen(DialogInterface screen) {\n synchronized (this) {\n if (mPreferencesScreens == null) {\n return;\n }\n mPreferencesScreens.remove(screen);\n }\n }\n\n /**\n * Called by {@link PreferenceActivity} to dispatch the new Intent event.\n *\n * @param intent The new Intent.\n */\n @DSComment(\"Package priviledge\")\n @DSBan(DSCat.DEFAULT_MODIFIER)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.781 -0500\", hash_original_method = \"4573B347852C64DB794205DBF1F726CF\", hash_generated_method = \"4573B347852C64DB794205DBF1F726CF\")\n void dispatchNewIntent(Intent intent) {\n dismissAllScreens();\n }\n\n interface OnPreferenceTreeClickListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference);\n }\n\n public interface OnActivityResultListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n boolean onActivityResult(int requestCode, int resultCode, Intent data);\n }\n\n public interface OnActivityStopListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n void onActivityStop();\n }\n\n public interface OnActivityDestroyListener {\n\n @DSComment(\"Abstract Method\")\n @DSSpec(DSCat.ABSTRACT_METHOD)\n void onActivityDestroy();\n }\n\n @DSComment(\"Private Method\")\n @DSBan(DSCat.PRIVATE_METHOD)\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.784 -0500\", hash_original_method = \"9025418B8BBAFCD2E271951C43610D69\", hash_generated_method = \"DCBAF81ECD7B379BC2C84590968F3DB8\")\n private void dismissAllScreens() {\n // Remove any of the previously shown preferences screens\n ArrayList screensToDismiss;\n synchronized (this) {\n if (mPreferencesScreens == null) {\n return;\n }\n screensToDismiss = new ArrayList(mPreferencesScreens);\n mPreferencesScreens.clear();\n }\n for (int i = screensToDismiss.size() - 1; i >= 0; i--) {\n screensToDismiss.get(i).dismiss();\n }\n }\n\n /**\n * Sets the callback to be invoked when a {@link Preference} in the\n * hierarchy rooted at this {@link PreferenceManager} is clicked.\n *\n * @param listener The callback to be invoked.\n */\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.785 -0500\", hash_original_method = \"285310B7C58E8A2220B6B265614A6D90\", hash_generated_method = \"285310B7C58E8A2220B6B265614A6D90\")\n void setOnPreferenceTreeClickListener(OnPreferenceTreeClickListener listener) {\n mOnPreferenceTreeClickListener = listener;\n }\n\n @DSGenerator(tool_name = \"Doppelganger\", tool_version = \"2.0\", generated_on = \"2013-12-30 12:32:26.787 -0500\", hash_original_method = \"44D09E26591D5A19BD471058A1477B47\", hash_generated_method = \"44D09E26591D5A19BD471058A1477B47\")\n OnPreferenceTreeClickListener getOnPreferenceTreeClickListener() {\n return mOnPreferenceTreeClickListener;\n }\n}\n"} {"task_id": "Java_3048", "language": "Java", "task_type": "method_signature", "source_file": "java/github/prismmodelchecker/prism/prism/src/parser/visitor/Rename.java", "mask_start_position": 4169, "mask_end_position": 4239, "canonical_solution": "public void visitPost(ExpressionStrategy e) throws PrismLangException ", "pre_mask_code": "// * Dave Parker (University of Oxford, formerly University of Birmingham)\n// This file is part of PRISM.\npackage parser.visitor;\n\nimport parser.ast.*;\nimport prism.PrismLangException;\n\n/**\n * Rename (according to RenamedModule definition), return result.\n */\npublic class Rename extends ASTTraverseModify {\n\n private RenamedModule rm;\n\n public Rename(RenamedModule rm) {\n this.rm = rm;\n }\n\n public void visitPost(ModulesFile e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"ModulesFile should never be renamed\");\n }\n\n public void visitPost(PropertiesFile e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"PropertiesFile should never be renamed\");\n }\n\n public void visitPost(Declaration e) throws PrismLangException {\n // Get new name for variable\n String s = rm.getNewName(e.getName());\n // No new name is an error\n if (s != null) {\n e.setName(s);\n } else {\n throw new PrismLangException(\"Definition of module \\\"\" + rm.getName() + \"\\\" must rename variable \\\"\" + e.getName() + \"\\\"\", rm);\n }\n }\n\n public void visitPost(parser.ast.Module e) throws PrismLangException {\n // New name for module is specied in RenamedModule\n e.setName(rm.getName());\n }\n\n public void visitPost(Command e) throws PrismLangException {\n // Rename synchronising action of command\n String s = rm.getNewName(e.getSynch());\n if (s != null)\n e.setSynch(s);\n }\n\n public void visitPost(Update e) throws PrismLangException {\n int i, n;\n String s;\n // Rename variables in update\n n = e.getNumElements();\n for (i = 0; i < n; i++) {\n s = rm.getNewName(e.getVar(i));\n if (s != null)\n e.setVar(i, new ExpressionIdent(s));\n }\n }\n\n public void visitPost(ExpressionTemporal e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"Temporal operators should never be renamed\");\n }\n\n public void visitPost(ExpressionFunc e) throws PrismLangException {\n // Rename function name (if necessary)\n String s = rm.getNewName(e.getName());\n if (s != null)\n e.setName(s);\n }\n\n public void visitPost(ExpressionIdent e) throws PrismLangException {\n String s = rm.getNewName(e.getName());\n if (s != null)\n e.setName(s);\n }\n\n public void visitPost(ExpressionProb e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"P operator should never be renamed\");\n }\n\n public void visitPost(ExpressionReward e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"R operator should never be renamed\");\n }\n\n public void visitPost(ExpressionSS e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"S operator should never be renamed\");\n }\n\n public void visitPost(ExpressionExists e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"E operator should never be renamed\");\n }\n\n public void visitPost(ExpressionForAll e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"A operator should never be renamed\");\n }\n\n ", "post_mask_code": "{\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(e.getOperatorString() + \" operator should never be renamed\");\n }\n}\n"} {"task_id": "Java_3049", "language": "Java", "task_type": "method_body", "source_file": "java/github/prismmodelchecker/prism/prism/src/parser/visitor/Rename.java", "mask_start_position": 3964, "mask_end_position": 4163, "canonical_solution": "{\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"A operator should never be renamed\");\n }", "pre_mask_code": "// * Dave Parker (University of Oxford, formerly University of Birmingham)\n// This file is part of PRISM.\npackage parser.visitor;\n\nimport parser.ast.*;\nimport prism.PrismLangException;\n\n/**\n * Rename (according to RenamedModule definition), return result.\n */\npublic class Rename extends ASTTraverseModify {\n\n private RenamedModule rm;\n\n public Rename(RenamedModule rm) {\n this.rm = rm;\n }\n\n public void visitPost(ModulesFile e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"ModulesFile should never be renamed\");\n }\n\n public void visitPost(PropertiesFile e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"PropertiesFile should never be renamed\");\n }\n\n public void visitPost(Declaration e) throws PrismLangException {\n // Get new name for variable\n String s = rm.getNewName(e.getName());\n // No new name is an error\n if (s != null) {\n e.setName(s);\n } else {\n throw new PrismLangException(\"Definition of module \\\"\" + rm.getName() + \"\\\" must rename variable \\\"\" + e.getName() + \"\\\"\", rm);\n }\n }\n\n public void visitPost(parser.ast.Module e) throws PrismLangException {\n // New name for module is specied in RenamedModule\n e.setName(rm.getName());\n }\n\n public void visitPost(Command e) throws PrismLangException {\n // Rename synchronising action of command\n String s = rm.getNewName(e.getSynch());\n if (s != null)\n e.setSynch(s);\n }\n\n public void visitPost(Update e) throws PrismLangException {\n int i, n;\n String s;\n // Rename variables in update\n n = e.getNumElements();\n for (i = 0; i < n; i++) {\n s = rm.getNewName(e.getVar(i));\n if (s != null)\n e.setVar(i, new ExpressionIdent(s));\n }\n }\n\n public void visitPost(ExpressionTemporal e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"Temporal operators should never be renamed\");\n }\n\n public void visitPost(ExpressionFunc e) throws PrismLangException {\n // Rename function name (if necessary)\n String s = rm.getNewName(e.getName());\n if (s != null)\n e.setName(s);\n }\n\n public void visitPost(ExpressionIdent e) throws PrismLangException {\n String s = rm.getNewName(e.getName());\n if (s != null)\n e.setName(s);\n }\n\n public void visitPost(ExpressionProb e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"P operator should never be renamed\");\n }\n\n public void visitPost(ExpressionReward e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"R operator should never be renamed\");\n }\n\n public void visitPost(ExpressionSS e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"S operator should never be renamed\");\n }\n\n public void visitPost(ExpressionExists e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"E operator should never be renamed\");\n }\n\n public void visitPost(ExpressionForAll e) throws PrismLangException ", "post_mask_code": "\n\n public void visitPost(ExpressionStrategy e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(e.getOperatorString() + \" operator should never be renamed\");\n }\n}\n"} {"task_id": "Java_3050", "language": "Java", "task_type": "single_line", "source_file": "java/github/prismmodelchecker/prism/prism/src/parser/visitor/Rename.java", "mask_start_position": 3299, "mask_end_position": 3342, "canonical_solution": "tion(\"R operator should never be renamed\");", "pre_mask_code": "// * Dave Parker (University of Oxford, formerly University of Birmingham)\n// This file is part of PRISM.\npackage parser.visitor;\n\nimport parser.ast.*;\nimport prism.PrismLangException;\n\n/**\n * Rename (according to RenamedModule definition), return result.\n */\npublic class Rename extends ASTTraverseModify {\n\n private RenamedModule rm;\n\n public Rename(RenamedModule rm) {\n this.rm = rm;\n }\n\n public void visitPost(ModulesFile e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"ModulesFile should never be renamed\");\n }\n\n public void visitPost(PropertiesFile e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"PropertiesFile should never be renamed\");\n }\n\n public void visitPost(Declaration e) throws PrismLangException {\n // Get new name for variable\n String s = rm.getNewName(e.getName());\n // No new name is an error\n if (s != null) {\n e.setName(s);\n } else {\n throw new PrismLangException(\"Definition of module \\\"\" + rm.getName() + \"\\\" must rename variable \\\"\" + e.getName() + \"\\\"\", rm);\n }\n }\n\n public void visitPost(parser.ast.Module e) throws PrismLangException {\n // New name for module is specied in RenamedModule\n e.setName(rm.getName());\n }\n\n public void visitPost(Command e) throws PrismLangException {\n // Rename synchronising action of command\n String s = rm.getNewName(e.getSynch());\n if (s != null)\n e.setSynch(s);\n }\n\n public void visitPost(Update e) throws PrismLangException {\n int i, n;\n String s;\n // Rename variables in update\n n = e.getNumElements();\n for (i = 0; i < n; i++) {\n s = rm.getNewName(e.getVar(i));\n if (s != null)\n e.setVar(i, new ExpressionIdent(s));\n }\n }\n\n public void visitPost(ExpressionTemporal e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"Temporal operators should never be renamed\");\n }\n\n public void visitPost(ExpressionFunc e) throws PrismLangException {\n // Rename function name (if necessary)\n String s = rm.getNewName(e.getName());\n if (s != null)\n e.setName(s);\n }\n\n public void visitPost(ExpressionIdent e) throws PrismLangException {\n String s = rm.getNewName(e.getName());\n if (s != null)\n e.setName(s);\n }\n\n public void visitPost(ExpressionProb e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"P operator should never be renamed\");\n }\n\n public void visitPost(ExpressionReward e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangExcep", "post_mask_code": "\n }\n\n public void visitPost(ExpressionSS e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"S operator should never be renamed\");\n }\n\n public void visitPost(ExpressionExists e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"E operator should never be renamed\");\n }\n\n public void visitPost(ExpressionForAll e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"A operator should never be renamed\");\n }\n\n public void visitPost(ExpressionStrategy e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(e.getOperatorString() + \" operator should never be renamed\");\n }\n}\n"} {"task_id": "Java_3051", "language": "Java", "task_type": "for_statement", "source_file": "java/github/prismmodelchecker/prism/prism/src/parser/visitor/Rename.java", "mask_start_position": 1958, "mask_end_position": 2117, "canonical_solution": "for (i = 0; i < n; i++) {\n s = rm.getNewName(e.getVar(i));\n if (s != null)\n e.setVar(i, new ExpressionIdent(s));\n }", "pre_mask_code": "// * Dave Parker (University of Oxford, formerly University of Birmingham)\n// This file is part of PRISM.\npackage parser.visitor;\n\nimport parser.ast.*;\nimport prism.PrismLangException;\n\n/**\n * Rename (according to RenamedModule definition), return result.\n */\npublic class Rename extends ASTTraverseModify {\n\n private RenamedModule rm;\n\n public Rename(RenamedModule rm) {\n this.rm = rm;\n }\n\n public void visitPost(ModulesFile e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"ModulesFile should never be renamed\");\n }\n\n public void visitPost(PropertiesFile e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"PropertiesFile should never be renamed\");\n }\n\n public void visitPost(Declaration e) throws PrismLangException {\n // Get new name for variable\n String s = rm.getNewName(e.getName());\n // No new name is an error\n if (s != null) {\n e.setName(s);\n } else {\n throw new PrismLangException(\"Definition of module \\\"\" + rm.getName() + \"\\\" must rename variable \\\"\" + e.getName() + \"\\\"\", rm);\n }\n }\n\n public void visitPost(parser.ast.Module e) throws PrismLangException {\n // New name for module is specied in RenamedModule\n e.setName(rm.getName());\n }\n\n public void visitPost(Command e) throws PrismLangException {\n // Rename synchronising action of command\n String s = rm.getNewName(e.getSynch());\n if (s != null)\n e.setSynch(s);\n }\n\n public void visitPost(Update e) throws PrismLangException {\n int i, n;\n String s;\n // Rename variables in update\n n = e.getNumElements();\n ", "post_mask_code": "\n }\n\n public void visitPost(ExpressionTemporal e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"Temporal operators should never be renamed\");\n }\n\n public void visitPost(ExpressionFunc e) throws PrismLangException {\n // Rename function name (if necessary)\n String s = rm.getNewName(e.getName());\n if (s != null)\n e.setName(s);\n }\n\n public void visitPost(ExpressionIdent e) throws PrismLangException {\n String s = rm.getNewName(e.getName());\n if (s != null)\n e.setName(s);\n }\n\n public void visitPost(ExpressionProb e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"P operator should never be renamed\");\n }\n\n public void visitPost(ExpressionReward e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"R operator should never be renamed\");\n }\n\n public void visitPost(ExpressionSS e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"S operator should never be renamed\");\n }\n\n public void visitPost(ExpressionExists e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"E operator should never be renamed\");\n }\n\n public void visitPost(ExpressionForAll e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(\"A operator should never be renamed\");\n }\n\n public void visitPost(ExpressionStrategy e) throws PrismLangException {\n // This renaming is only designed to be applied\n // at the level of an individual module (and below)\n throw new PrismLangException(e.getOperatorString() + \" operator should never be renamed\");\n }\n}\n"} {"task_id": "Java_3052", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cegredev/josi/src/main/java/io/github/cegredev/josi/constraints/WinConstraint.java", "mask_start_position": 748, "mask_end_position": 801, "canonical_solution": "@Override\n protected CurrentOS.Family getFamily() ", "pre_mask_code": "package io.github.cegredev.josi.constraints;\n\nimport io.github.cegredev.josi.CurrentOS;\nimport io.github.cegredev.josi.WinOS;\nimport java.util.Arrays;\n\npublic class WinConstraint extends SpecificConstraint {\n\n public WinConstraint(OSConstraint target) {\n super(target);\n }\n\n public WinConstraint version(WinOS.Version... versions) {\n return addToTarget(os -> Arrays.asList(versions).contains(os.getVersion()));\n }\n\n public WinConstraint notVersion(WinOS.Version... versions) {\n return addToTarget(os -> !Arrays.asList(versions).contains(os.getVersion()));\n }\n\n public WinConstraint server(boolean isServer) {\n return addToTarget(os -> os.isServer() == isServer);\n }\n\n ", "post_mask_code": "{\n return CurrentOS.Family.WINDOWS;\n }\n}\n"} {"task_id": "Java_3053", "language": "Java", "task_type": "method_body", "source_file": "java/github/cegredev/josi/src/main/java/io/github/cegredev/josi/constraints/WinConstraint.java", "mask_start_position": 801, "mask_end_position": 849, "canonical_solution": "{\n return CurrentOS.Family.WINDOWS;\n }", "pre_mask_code": "package io.github.cegredev.josi.constraints;\n\nimport io.github.cegredev.josi.CurrentOS;\nimport io.github.cegredev.josi.WinOS;\nimport java.util.Arrays;\n\npublic class WinConstraint extends SpecificConstraint {\n\n public WinConstraint(OSConstraint target) {\n super(target);\n }\n\n public WinConstraint version(WinOS.Version... versions) {\n return addToTarget(os -> Arrays.asList(versions).contains(os.getVersion()));\n }\n\n public WinConstraint notVersion(WinOS.Version... versions) {\n return addToTarget(os -> !Arrays.asList(versions).contains(os.getVersion()));\n }\n\n public WinConstraint server(boolean isServer) {\n return addToTarget(os -> os.isServer() == isServer);\n }\n\n @Override\n protected CurrentOS.Family getFamily() ", "post_mask_code": "\n}\n"} {"task_id": "Java_3054", "language": "Java", "task_type": "single_line", "source_file": "java/github/cegredev/josi/src/main/java/io/github/cegredev/josi/constraints/WinConstraint.java", "mask_start_position": 552, "mask_end_position": 613, "canonical_solution": "et(os -> !Arrays.asList(versions).contains(os.getVersion()));", "pre_mask_code": "package io.github.cegredev.josi.constraints;\n\nimport io.github.cegredev.josi.CurrentOS;\nimport io.github.cegredev.josi.WinOS;\nimport java.util.Arrays;\n\npublic class WinConstraint extends SpecificConstraint {\n\n public WinConstraint(OSConstraint target) {\n super(target);\n }\n\n public WinConstraint version(WinOS.Version... versions) {\n return addToTarget(os -> Arrays.asList(versions).contains(os.getVersion()));\n }\n\n public WinConstraint notVersion(WinOS.Version... versions) {\n return addToTarg", "post_mask_code": "\n }\n\n public WinConstraint server(boolean isServer) {\n return addToTarget(os -> os.isServer() == isServer);\n }\n\n @Override\n protected CurrentOS.Family getFamily() {\n return CurrentOS.Family.WINDOWS;\n }\n}\n"} {"task_id": "Java_3055", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/incubator-hop/core/src/main/java/org/apache/hop/core/SwingUniversalImageBitmap.java", "mask_start_position": 412, "mask_end_position": 474, "canonical_solution": "@Override\n protected void renderSimple(BufferedImage area) ", "pre_mask_code": "package org.apache.hop.core;\n\nimport java.awt.*;\nimport java.awt.geom.AffineTransform;\nimport java.awt.image.BufferedImage;\n\npublic class SwingUniversalImageBitmap extends SwingUniversalImage {\n\n private final BufferedImage bitmap;\n\n public SwingUniversalImageBitmap(BufferedImage bitmap) {\n this.bitmap = bitmap;\n }\n\n @Override\n public boolean isBitmap() {\n return true;\n }\n\n ", "post_mask_code": "{\n Graphics2D gc = createGraphics(area);\n gc.drawImage(bitmap, 0, 0, area.getWidth(), area.getHeight(), null);\n gc.dispose();\n }\n\n @Override\n protected void render(Graphics2D gc, int centerX, int centerY, int width, int height, double angleRadians) {\n AffineTransform oldTransform = gc.getTransform();\n try {\n double scaleX = width * 1.0 / bitmap.getWidth();\n double scaleY = height * 1.0 / bitmap.getHeight();\n AffineTransform affineTransform = new AffineTransform(oldTransform);\n if (centerX != 0 || centerY != 0) {\n affineTransform.translate(centerX, centerY);\n }\n affineTransform.scale(scaleX, scaleY);\n if (angleRadians != 0) {\n affineTransform.rotate(angleRadians);\n }\n affineTransform.translate(-bitmap.getWidth() / 2, -bitmap.getHeight() / 2);\n gc.setTransform(affineTransform);\n gc.drawImage(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), null);\n } finally {\n gc.setTransform(oldTransform);\n }\n }\n}\n"} {"task_id": "Java_3056", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/incubator-hop/core/src/main/java/org/apache/hop/core/SwingUniversalImageBitmap.java", "mask_start_position": 474, "mask_end_position": 626, "canonical_solution": "{\n Graphics2D gc = createGraphics(area);\n gc.drawImage(bitmap, 0, 0, area.getWidth(), area.getHeight(), null);\n gc.dispose();\n }", "pre_mask_code": "package org.apache.hop.core;\n\nimport java.awt.*;\nimport java.awt.geom.AffineTransform;\nimport java.awt.image.BufferedImage;\n\npublic class SwingUniversalImageBitmap extends SwingUniversalImage {\n\n private final BufferedImage bitmap;\n\n public SwingUniversalImageBitmap(BufferedImage bitmap) {\n this.bitmap = bitmap;\n }\n\n @Override\n public boolean isBitmap() {\n return true;\n }\n\n @Override\n protected void renderSimple(BufferedImage area) ", "post_mask_code": "\n\n @Override\n protected void render(Graphics2D gc, int centerX, int centerY, int width, int height, double angleRadians) {\n AffineTransform oldTransform = gc.getTransform();\n try {\n double scaleX = width * 1.0 / bitmap.getWidth();\n double scaleY = height * 1.0 / bitmap.getHeight();\n AffineTransform affineTransform = new AffineTransform(oldTransform);\n if (centerX != 0 || centerY != 0) {\n affineTransform.translate(centerX, centerY);\n }\n affineTransform.scale(scaleX, scaleY);\n if (angleRadians != 0) {\n affineTransform.rotate(angleRadians);\n }\n affineTransform.translate(-bitmap.getWidth() / 2, -bitmap.getHeight() / 2);\n gc.setTransform(affineTransform);\n gc.drawImage(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), null);\n } finally {\n gc.setTransform(oldTransform);\n }\n }\n}\n"} {"task_id": "Java_3057", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/incubator-hop/core/src/main/java/org/apache/hop/core/SwingUniversalImageBitmap.java", "mask_start_position": 784, "mask_end_position": 812, "canonical_solution": "ansform = gc.getTransform();", "pre_mask_code": "package org.apache.hop.core;\n\nimport java.awt.*;\nimport java.awt.geom.AffineTransform;\nimport java.awt.image.BufferedImage;\n\npublic class SwingUniversalImageBitmap extends SwingUniversalImage {\n\n private final BufferedImage bitmap;\n\n public SwingUniversalImageBitmap(BufferedImage bitmap) {\n this.bitmap = bitmap;\n }\n\n @Override\n public boolean isBitmap() {\n return true;\n }\n\n @Override\n protected void renderSimple(BufferedImage area) {\n Graphics2D gc = createGraphics(area);\n gc.drawImage(bitmap, 0, 0, area.getWidth(), area.getHeight(), null);\n gc.dispose();\n }\n\n @Override\n protected void render(Graphics2D gc, int centerX, int centerY, int width, int height, double angleRadians) {\n AffineTransform oldTr", "post_mask_code": "\n try {\n double scaleX = width * 1.0 / bitmap.getWidth();\n double scaleY = height * 1.0 / bitmap.getHeight();\n AffineTransform affineTransform = new AffineTransform(oldTransform);\n if (centerX != 0 || centerY != 0) {\n affineTransform.translate(centerX, centerY);\n }\n affineTransform.scale(scaleX, scaleY);\n if (angleRadians != 0) {\n affineTransform.rotate(angleRadians);\n }\n affineTransform.translate(-bitmap.getWidth() / 2, -bitmap.getHeight() / 2);\n gc.setTransform(affineTransform);\n gc.drawImage(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), null);\n } finally {\n gc.setTransform(oldTransform);\n }\n }\n}\n"} {"task_id": "Java_3058", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/codefollower/Bats/bats-executor/src/main/java/org/apache/drill/exec/physical/impl/partitionsender/Partitioner.java", "mask_start_position": 1690, "mask_end_position": 1741, "canonical_solution": "PartitionOutgoingBatch getOutgoingBatch(int index);", "pre_mask_code": "package org.apache.drill.exec.physical.impl.partitionsender;\n\nimport java.io.IOException;\nimport java.util.List;\nimport org.apache.drill.exec.compile.TemplateClassDefinition;\nimport org.apache.drill.exec.exception.SchemaChangeException;\nimport org.apache.drill.exec.expr.ClassGenerator;\nimport org.apache.drill.exec.ops.ExchangeFragmentContext;\nimport org.apache.drill.exec.ops.OperatorContext;\nimport org.apache.drill.exec.ops.OperatorStats;\nimport org.apache.drill.exec.physical.config.HashPartitionSender;\nimport org.apache.drill.exec.record.RecordBatch;\n\npublic interface Partitioner {\n\n // Keep the recordCount as (2^x) - 1 to better utilize the memory allocation in ValueVectors; however\n // other criteria such as batch sizing in terms of actual MBytes rather than record count could also be applied\n // by the operator.\n int DEFAULT_RECORD_BATCH_SIZE = (1 << 10) - 1;\n\n void setup(ExchangeFragmentContext context, RecordBatch incoming, HashPartitionSender popConfig, OperatorStats stats, OperatorContext oContext, ClassGenerator cg, int start, int count) throws SchemaChangeException;\n\n void partitionBatch(RecordBatch incoming) throws IOException;\n\n void flushOutgoingBatches(boolean isLastBatch, boolean schemaChanged) throws IOException;\n\n void initialize();\n\n void clear();\n\n List getOutgoingBatches();\n\n /**\n * Method to get PartitionOutgoingBatch based on the fact that there can be > 1 Partitioner\n * @param index\n * @return PartitionOutgoingBatch that matches index within Partitioner. This method can\n * return null if index does not fall within boundary of this Partitioner\n */\n ", "post_mask_code": "\n\n OperatorStats getStats();\n\n TemplateClassDefinition TEMPLATE_DEFINITION = new TemplateClassDefinition<>(Partitioner.class, PartitionerTemplate.class);\n}\n"} {"task_id": "Java_3059", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/infinispan/infinispan/server/core/src/main/java/org/infinispan/server/core/backup/ContainerResource.java", "mask_start_position": 2732, "mask_end_position": 2775, "canonical_solution": "CompletionStage restore(ZipFile zip);", "pre_mask_code": "package org.infinispan.server.core.backup;\n\nimport java.util.Properties;\nimport java.util.concurrent.CompletionStage;\nimport java.util.zip.ZipFile;\nimport org.infinispan.commons.CacheException;\nimport org.infinispan.server.core.BackupManager;\n\n/**\n * An interface that defines how a container resource is backed up and\n * restored by the {@link org.infinispan.server.core.BackupManager}.\n *\n * @author Ryan Emerson\n * @since 12.0\n */\npublic interface ContainerResource {\n\n /**\n * A method to ensure that the resources requested in the {@link BackupManager.Resources}\n * are valid and can be included in a backup. This method is called for all {@link ContainerResource} implementations\n * before the backup process begins in order to allow a backup to fail-fast before any data is processed.\n *\n * @throws CacheException if an invalid parameter is specified, e.g. a unknown resource name.\n */\n void prepareAndValidateBackup() throws CacheException;\n\n /**\n * Writes the backup files for the {@link BackupManager.Resources.Type} to the local\n * filesystem, where it can then be packaged for distribution.\n *

\n * Implementations of this method depend on content created by {@link #prepareAndValidateBackup()}.\n *\n * @return a {@link CompletionStage} that completes once the backup of this {@link\n * BackupManager.Resources.Type} has finished.\n */\n CompletionStage backup();\n\n /**\n * Writes the name of the individual resources that have been included in this backup. The {@link\n * BackupManager.Resources.Type} associated with an implementation is the key, whilst the\n * value is a csv of resource names.\n *

\n * Implementations of this method depend on state created by {@link #backup()}.\n *\n * @param properties the {@link Properties} instance to add the key/value property.\n */\n void writeToManifest(Properties properties);\n\n /**\n * A method to ensure that the resources requested in the {@link BackupManager.Resources}\n * are contained in the backup to be restored. This method is called for all {@link ContainerResource}\n * implementations before the restore process begins in order to allow a restore to fail-fast before any state is\n * restored to a container.\n */\n void prepareAndValidateRestore(Properties properties);\n\n /**\n * Restores the {@link BackupManager.Resources.Type} content from the provided {@link\n * ZipFile} to the target container.\n *\n * @param zip the {@link ZipFile} to restore content from.\n * @return a {@link CompletionStage} that completes once the restoration of this {@link\n * BackupManager.Resources.Type} has finished.\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_3060", "language": "Java", "task_type": "method_signature", "source_file": "java/github/apache/atlas/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusObjectFactory.java", "mask_start_position": 811, "mask_end_position": 875, "canonical_solution": "public static Direction createDirection(AtlasEdgeDirection dir) ", "pre_mask_code": "package org.apache.atlas.repository.graphdb.janus;\n\nimport org.apache.atlas.repository.graphdb.AtlasCardinality;\nimport org.apache.atlas.repository.graphdb.AtlasEdgeDirection;\nimport org.apache.atlas.repository.graphdb.AtlasPropertyKey;\nimport org.apache.tinkerpop.gremlin.structure.Direction;\nimport org.janusgraph.core.Cardinality;\nimport org.janusgraph.core.PropertyKey;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Factory that serves up instances of Janus/Tinkerpop classes that correspond to\n * graph database abstraction layer/Atlas classes.\n */\npublic final class AtlasJanusObjectFactory {\n\n private AtlasJanusObjectFactory() {\n }\n\n /**\n * Retrieves the Janus direction corresponding to the given\n * AtlasEdgeDirection.\n *\n * @param dir\n * @return\n */\n ", "post_mask_code": "{\n switch(dir) {\n case IN:\n return Direction.IN;\n case OUT:\n return Direction.OUT;\n case BOTH:\n return Direction.BOTH;\n default:\n throw new RuntimeException(\"Unrecognized direction: \" + dir);\n }\n }\n\n /**\n * Converts a Multiplicity to a Cardinality.\n *\n * @param cardinality\n * @return\n */\n public static Cardinality createCardinality(AtlasCardinality cardinality) {\n switch(cardinality) {\n case SINGLE:\n return Cardinality.SINGLE;\n case LIST:\n return Cardinality.LIST;\n case SET:\n return Cardinality.SET;\n default:\n throw new IllegalStateException(\"Unrecognized cardinality: \" + cardinality);\n }\n }\n\n public static PropertyKey createPropertyKey(AtlasPropertyKey key) {\n return ((AtlasJanusPropertyKey) key).getWrappedPropertyKey();\n }\n\n public static PropertyKey[] createPropertyKeys(List keys) {\n PropertyKey[] ret = new PropertyKey[keys.size()];\n int i = 0;\n for (AtlasPropertyKey key : keys) {\n ret[i] = createPropertyKey(key);\n i++;\n }\n return ret;\n }\n}\n"} {"task_id": "Java_3061", "language": "Java", "task_type": "method_body", "source_file": "java/github/apache/atlas/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusObjectFactory.java", "mask_start_position": 875, "mask_end_position": 1193, "canonical_solution": "{\n switch(dir) {\n case IN:\n return Direction.IN;\n case OUT:\n return Direction.OUT;\n case BOTH:\n return Direction.BOTH;\n default:\n throw new RuntimeException(\"Unrecognized direction: \" + dir);\n }\n }", "pre_mask_code": "package org.apache.atlas.repository.graphdb.janus;\n\nimport org.apache.atlas.repository.graphdb.AtlasCardinality;\nimport org.apache.atlas.repository.graphdb.AtlasEdgeDirection;\nimport org.apache.atlas.repository.graphdb.AtlasPropertyKey;\nimport org.apache.tinkerpop.gremlin.structure.Direction;\nimport org.janusgraph.core.Cardinality;\nimport org.janusgraph.core.PropertyKey;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Factory that serves up instances of Janus/Tinkerpop classes that correspond to\n * graph database abstraction layer/Atlas classes.\n */\npublic final class AtlasJanusObjectFactory {\n\n private AtlasJanusObjectFactory() {\n }\n\n /**\n * Retrieves the Janus direction corresponding to the given\n * AtlasEdgeDirection.\n *\n * @param dir\n * @return\n */\n public static Direction createDirection(AtlasEdgeDirection dir) ", "post_mask_code": "\n\n /**\n * Converts a Multiplicity to a Cardinality.\n *\n * @param cardinality\n * @return\n */\n public static Cardinality createCardinality(AtlasCardinality cardinality) {\n switch(cardinality) {\n case SINGLE:\n return Cardinality.SINGLE;\n case LIST:\n return Cardinality.LIST;\n case SET:\n return Cardinality.SET;\n default:\n throw new IllegalStateException(\"Unrecognized cardinality: \" + cardinality);\n }\n }\n\n public static PropertyKey createPropertyKey(AtlasPropertyKey key) {\n return ((AtlasJanusPropertyKey) key).getWrappedPropertyKey();\n }\n\n public static PropertyKey[] createPropertyKeys(List keys) {\n PropertyKey[] ret = new PropertyKey[keys.size()];\n int i = 0;\n for (AtlasPropertyKey key : keys) {\n ret[i] = createPropertyKey(key);\n i++;\n }\n return ret;\n }\n}\n"} {"task_id": "Java_3062", "language": "Java", "task_type": "single_line", "source_file": "java/github/apache/atlas/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusObjectFactory.java", "mask_start_position": 2184, "mask_end_position": 2186, "canonical_solution": "t;", "pre_mask_code": "package org.apache.atlas.repository.graphdb.janus;\n\nimport org.apache.atlas.repository.graphdb.AtlasCardinality;\nimport org.apache.atlas.repository.graphdb.AtlasEdgeDirection;\nimport org.apache.atlas.repository.graphdb.AtlasPropertyKey;\nimport org.apache.tinkerpop.gremlin.structure.Direction;\nimport org.janusgraph.core.Cardinality;\nimport org.janusgraph.core.PropertyKey;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Factory that serves up instances of Janus/Tinkerpop classes that correspond to\n * graph database abstraction layer/Atlas classes.\n */\npublic final class AtlasJanusObjectFactory {\n\n private AtlasJanusObjectFactory() {\n }\n\n /**\n * Retrieves the Janus direction corresponding to the given\n * AtlasEdgeDirection.\n *\n * @param dir\n * @return\n */\n public static Direction createDirection(AtlasEdgeDirection dir) {\n switch(dir) {\n case IN:\n return Direction.IN;\n case OUT:\n return Direction.OUT;\n case BOTH:\n return Direction.BOTH;\n default:\n throw new RuntimeException(\"Unrecognized direction: \" + dir);\n }\n }\n\n /**\n * Converts a Multiplicity to a Cardinality.\n *\n * @param cardinality\n * @return\n */\n public static Cardinality createCardinality(AtlasCardinality cardinality) {\n switch(cardinality) {\n case SINGLE:\n return Cardinality.SINGLE;\n case LIST:\n return Cardinality.LIST;\n case SET:\n return Cardinality.SET;\n default:\n throw new IllegalStateException(\"Unrecognized cardinality: \" + cardinality);\n }\n }\n\n public static PropertyKey createPropertyKey(AtlasPropertyKey key) {\n return ((AtlasJanusPropertyKey) key).getWrappedPropertyKey();\n }\n\n public static PropertyKey[] createPropertyKeys(List keys) {\n PropertyKey[] ret = new PropertyKey[keys.size()];\n int i = 0;\n for (AtlasPropertyKey key : keys) {\n ret[i] = createPropertyKey(key);\n i++;\n }\n return re", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_3063", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/apache/atlas/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusObjectFactory.java", "mask_start_position": 811, "mask_end_position": 1193, "canonical_solution": "public static Direction createDirection(AtlasEdgeDirection dir) {\n switch(dir) {\n case IN:\n return Direction.IN;\n case OUT:\n return Direction.OUT;\n case BOTH:\n return Direction.BOTH;\n default:\n throw new RuntimeException(\"Unrecognized direction: \" + dir);\n }\n }", "pre_mask_code": "package org.apache.atlas.repository.graphdb.janus;\n\nimport org.apache.atlas.repository.graphdb.AtlasCardinality;\nimport org.apache.atlas.repository.graphdb.AtlasEdgeDirection;\nimport org.apache.atlas.repository.graphdb.AtlasPropertyKey;\nimport org.apache.tinkerpop.gremlin.structure.Direction;\nimport org.janusgraph.core.Cardinality;\nimport org.janusgraph.core.PropertyKey;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Factory that serves up instances of Janus/Tinkerpop classes that correspond to\n * graph database abstraction layer/Atlas classes.\n */\npublic final class AtlasJanusObjectFactory {\n\n private AtlasJanusObjectFactory() {\n }\n\n /**\n * Retrieves the Janus direction corresponding to the given\n * AtlasEdgeDirection.\n *\n * @param dir\n * @return\n */\n ", "post_mask_code": "\n\n /**\n * Converts a Multiplicity to a Cardinality.\n *\n * @param cardinality\n * @return\n */\n public static Cardinality createCardinality(AtlasCardinality cardinality) {\n switch(cardinality) {\n case SINGLE:\n return Cardinality.SINGLE;\n case LIST:\n return Cardinality.LIST;\n case SET:\n return Cardinality.SET;\n default:\n throw new IllegalStateException(\"Unrecognized cardinality: \" + cardinality);\n }\n }\n\n public static PropertyKey createPropertyKey(AtlasPropertyKey key) {\n return ((AtlasJanusPropertyKey) key).getWrappedPropertyKey();\n }\n\n public static PropertyKey[] createPropertyKeys(List keys) {\n PropertyKey[] ret = new PropertyKey[keys.size()];\n int i = 0;\n for (AtlasPropertyKey key : keys) {\n ret[i] = createPropertyKey(key);\n i++;\n }\n return ret;\n }\n}\n"} {"task_id": "Java_3064", "language": "Java", "task_type": "switch_case", "source_file": "java/github/apache/atlas/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusObjectFactory.java", "mask_start_position": 885, "mask_end_position": 1187, "canonical_solution": "switch(dir) {\n case IN:\n return Direction.IN;\n case OUT:\n return Direction.OUT;\n case BOTH:\n return Direction.BOTH;\n default:\n throw new RuntimeException(\"Unrecognized direction: \" + dir);\n }", "pre_mask_code": "package org.apache.atlas.repository.graphdb.janus;\n\nimport org.apache.atlas.repository.graphdb.AtlasCardinality;\nimport org.apache.atlas.repository.graphdb.AtlasEdgeDirection;\nimport org.apache.atlas.repository.graphdb.AtlasPropertyKey;\nimport org.apache.tinkerpop.gremlin.structure.Direction;\nimport org.janusgraph.core.Cardinality;\nimport org.janusgraph.core.PropertyKey;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Factory that serves up instances of Janus/Tinkerpop classes that correspond to\n * graph database abstraction layer/Atlas classes.\n */\npublic final class AtlasJanusObjectFactory {\n\n private AtlasJanusObjectFactory() {\n }\n\n /**\n * Retrieves the Janus direction corresponding to the given\n * AtlasEdgeDirection.\n *\n * @param dir\n * @return\n */\n public static Direction createDirection(AtlasEdgeDirection dir) {\n ", "post_mask_code": "\n }\n\n /**\n * Converts a Multiplicity to a Cardinality.\n *\n * @param cardinality\n * @return\n */\n public static Cardinality createCardinality(AtlasCardinality cardinality) {\n switch(cardinality) {\n case SINGLE:\n return Cardinality.SINGLE;\n case LIST:\n return Cardinality.LIST;\n case SET:\n return Cardinality.SET;\n default:\n throw new IllegalStateException(\"Unrecognized cardinality: \" + cardinality);\n }\n }\n\n public static PropertyKey createPropertyKey(AtlasPropertyKey key) {\n return ((AtlasJanusPropertyKey) key).getWrappedPropertyKey();\n }\n\n public static PropertyKey[] createPropertyKeys(List keys) {\n PropertyKey[] ret = new PropertyKey[keys.size()];\n int i = 0;\n for (AtlasPropertyKey key : keys) {\n ret[i] = createPropertyKey(key);\n i++;\n }\n return ret;\n }\n}\n"} {"task_id": "Java_3065", "language": "Java", "task_type": "method_signature", "source_file": "java/github/andreschaffer/microservices-testing-examples/credit-score-service/src/main/java/creditscoreservice/bootstrap/CreditScoreServiceApplication.java", "mask_start_position": 626, "mask_end_position": 682, "canonical_solution": "private void registerResources(Environment environment) ", "pre_mask_code": "package creditscoreservice.bootstrap;\n\nimport creditscoreservice.port.incoming.adapter.resources.CreditScoreResource;\nimport creditscoreservice.port.outgoing.adapter.creditscore.InMemoryCreditScoreRepository;\nimport io.dropwizard.Application;\nimport io.dropwizard.Configuration;\nimport io.dropwizard.setup.Environment;\n\npublic class CreditScoreServiceApplication extends Application {\n\n @Override\n public void run(Configuration configuration, Environment environment) throws Exception {\n ObjectMapperConfig.applyTo(environment.getObjectMapper());\n registerResources(environment);\n }\n\n ", "post_mask_code": "{\n InMemoryCreditScoreRepository creditScoreRepository = new InMemoryCreditScoreRepository();\n environment.jersey().register(new CreditScoreResource(creditScoreRepository));\n }\n}\n"} {"task_id": "Java_3066", "language": "Java", "task_type": "method_body", "source_file": "java/github/andreschaffer/microservices-testing-examples/credit-score-service/src/main/java/creditscoreservice/bootstrap/CreditScoreServiceApplication.java", "mask_start_position": 506, "mask_end_position": 620, "canonical_solution": "{\n ObjectMapperConfig.applyTo(environment.getObjectMapper());\n registerResources(environment);\n }", "pre_mask_code": "package creditscoreservice.bootstrap;\n\nimport creditscoreservice.port.incoming.adapter.resources.CreditScoreResource;\nimport creditscoreservice.port.outgoing.adapter.creditscore.InMemoryCreditScoreRepository;\nimport io.dropwizard.Application;\nimport io.dropwizard.Configuration;\nimport io.dropwizard.setup.Environment;\n\npublic class CreditScoreServiceApplication extends Application {\n\n @Override\n public void run(Configuration configuration, Environment environment) throws Exception ", "post_mask_code": "\n\n private void registerResources(Environment environment) {\n InMemoryCreditScoreRepository creditScoreRepository = new InMemoryCreditScoreRepository();\n environment.jersey().register(new CreditScoreResource(creditScoreRepository));\n }\n}\n"} {"task_id": "Java_3067", "language": "Java", "task_type": "single_line", "source_file": "java/github/andreschaffer/microservices-testing-examples/credit-score-service/src/main/java/creditscoreservice/bootstrap/CreditScoreServiceApplication.java", "mask_start_position": 592, "mask_end_position": 614, "canonical_solution": "esources(environment);", "pre_mask_code": "package creditscoreservice.bootstrap;\n\nimport creditscoreservice.port.incoming.adapter.resources.CreditScoreResource;\nimport creditscoreservice.port.outgoing.adapter.creditscore.InMemoryCreditScoreRepository;\nimport io.dropwizard.Application;\nimport io.dropwizard.Configuration;\nimport io.dropwizard.setup.Environment;\n\npublic class CreditScoreServiceApplication extends Application {\n\n @Override\n public void run(Configuration configuration, Environment environment) throws Exception {\n ObjectMapperConfig.applyTo(environment.getObjectMapper());\n registerR", "post_mask_code": "\n }\n\n private void registerResources(Environment environment) {\n InMemoryCreditScoreRepository creditScoreRepository = new InMemoryCreditScoreRepository();\n environment.jersey().register(new CreditScoreResource(creditScoreRepository));\n }\n}\n"} {"task_id": "Java_3068", "language": "Java", "task_type": "method_signature", "source_file": "java/github/eclipse/jnosql/mapping/mapping-reactive/mapping-reactive-column/src/main/java/org/eclipse/jnosql/mapping/column/reactive/query/DefaultReactiveColumnRepository.java", "mask_start_position": 557, "mask_end_position": 618, "canonical_solution": "@Override\n protected ReactiveColumnTemplate getTemplate() ", "pre_mask_code": "package org.eclipse.jnosql.mapping.column.reactive.query;\n\nimport org.eclipse.jnosql.mapping.column.reactive.ReactiveColumnTemplate;\nimport org.eclipse.jnosql.mapping.reflection.ClassMapping;\n\npublic class DefaultReactiveColumnRepository extends AbstractReactiveColumnRepository {\n\n private final ReactiveColumnTemplate template;\n\n private final ClassMapping mapping;\n\n DefaultReactiveColumnRepository(ReactiveColumnTemplate template, ClassMapping mapping) {\n this.template = template;\n this.mapping = mapping;\n }\n\n ", "post_mask_code": "{\n return template;\n }\n\n @Override\n protected ClassMapping getClassMapping() {\n return mapping;\n }\n}\n"} {"task_id": "Java_3069", "language": "Java", "task_type": "method_body", "source_file": "java/github/eclipse/jnosql/mapping/mapping-reactive/mapping-reactive-column/src/main/java/org/eclipse/jnosql/mapping/column/reactive/query/DefaultReactiveColumnRepository.java", "mask_start_position": 618, "mask_end_position": 650, "canonical_solution": "{\n return template;\n }", "pre_mask_code": "package org.eclipse.jnosql.mapping.column.reactive.query;\n\nimport org.eclipse.jnosql.mapping.column.reactive.ReactiveColumnTemplate;\nimport org.eclipse.jnosql.mapping.reflection.ClassMapping;\n\npublic class DefaultReactiveColumnRepository extends AbstractReactiveColumnRepository {\n\n private final ReactiveColumnTemplate template;\n\n private final ClassMapping mapping;\n\n DefaultReactiveColumnRepository(ReactiveColumnTemplate template, ClassMapping mapping) {\n this.template = template;\n this.mapping = mapping;\n }\n\n @Override\n protected ReactiveColumnTemplate getTemplate() ", "post_mask_code": "\n\n @Override\n protected ClassMapping getClassMapping() {\n return mapping;\n }\n}\n"} {"task_id": "Java_3070", "language": "Java", "task_type": "single_line", "source_file": "java/github/eclipse/jnosql/mapping/mapping-reactive/mapping-reactive-column/src/main/java/org/eclipse/jnosql/mapping/column/reactive/query/DefaultReactiveColumnRepository.java", "mask_start_position": 726, "mask_end_position": 736, "canonical_solution": "n mapping;", "pre_mask_code": "package org.eclipse.jnosql.mapping.column.reactive.query;\n\nimport org.eclipse.jnosql.mapping.column.reactive.ReactiveColumnTemplate;\nimport org.eclipse.jnosql.mapping.reflection.ClassMapping;\n\npublic class DefaultReactiveColumnRepository extends AbstractReactiveColumnRepository {\n\n private final ReactiveColumnTemplate template;\n\n private final ClassMapping mapping;\n\n DefaultReactiveColumnRepository(ReactiveColumnTemplate template, ClassMapping mapping) {\n this.template = template;\n this.mapping = mapping;\n }\n\n @Override\n protected ReactiveColumnTemplate getTemplate() {\n return template;\n }\n\n @Override\n protected ClassMapping getClassMapping() {\n retur", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_3071", "language": "Java", "task_type": "method_signature", "source_file": "java/github/TheIllusiveC4/Curios/src/main/java/top/theillusivec4/curios/common/integration/jei/CuriosJeiPlugin.java", "mask_start_position": 494, "mask_end_position": 560, "canonical_solution": "@Override\n @Nonnull\n public ResourceLocation getPluginUid() ", "pre_mask_code": "/*\n *\n * This file is part of Curios, a mod made for Minecraft.\n *\n */\npackage top.theillusivec4.curios.common.integration.jei;\n\nimport javax.annotation.Nonnull;\nimport mezz.jei.api.IModPlugin;\nimport mezz.jei.api.JeiPlugin;\nimport mezz.jei.api.registration.IGuiHandlerRegistration;\nimport net.minecraft.util.ResourceLocation;\nimport top.theillusivec4.curios.Curios;\nimport top.theillusivec4.curios.client.gui.CuriosScreen;\n\n@JeiPlugin\npublic class CuriosJeiPlugin implements IModPlugin {\n\n ", "post_mask_code": "{\n return new ResourceLocation(Curios.MODID, Curios.MODID);\n }\n\n @Override\n public void registerGuiHandlers(IGuiHandlerRegistration registration) {\n registration.addGuiContainerHandler(CuriosScreen.class, new CuriosContainerHandler());\n }\n}\n"} {"task_id": "Java_3072", "language": "Java", "task_type": "method_body", "source_file": "java/github/TheIllusiveC4/Curios/src/main/java/top/theillusivec4/curios/common/integration/jei/CuriosJeiPlugin.java", "mask_start_position": 722, "mask_end_position": 824, "canonical_solution": "{\n registration.addGuiContainerHandler(CuriosScreen.class, new CuriosContainerHandler());\n }", "pre_mask_code": "/*\n *\n * This file is part of Curios, a mod made for Minecraft.\n *\n */\npackage top.theillusivec4.curios.common.integration.jei;\n\nimport javax.annotation.Nonnull;\nimport mezz.jei.api.IModPlugin;\nimport mezz.jei.api.JeiPlugin;\nimport mezz.jei.api.registration.IGuiHandlerRegistration;\nimport net.minecraft.util.ResourceLocation;\nimport top.theillusivec4.curios.Curios;\nimport top.theillusivec4.curios.client.gui.CuriosScreen;\n\n@JeiPlugin\npublic class CuriosJeiPlugin implements IModPlugin {\n\n @Override\n @Nonnull\n public ResourceLocation getPluginUid() {\n return new ResourceLocation(Curios.MODID, Curios.MODID);\n }\n\n @Override\n public void registerGuiHandlers(IGuiHandlerRegistration registration) ", "post_mask_code": "\n}\n"} {"task_id": "Java_3073", "language": "Java", "task_type": "single_line", "source_file": "java/github/TheIllusiveC4/Curios/src/main/java/top/theillusivec4/curios/common/integration/jei/CuriosJeiPlugin.java", "mask_start_position": 754, "mask_end_position": 818, "canonical_solution": "tainerHandler(CuriosScreen.class, new CuriosContainerHandler());", "pre_mask_code": "/*\n *\n * This file is part of Curios, a mod made for Minecraft.\n *\n */\npackage top.theillusivec4.curios.common.integration.jei;\n\nimport javax.annotation.Nonnull;\nimport mezz.jei.api.IModPlugin;\nimport mezz.jei.api.JeiPlugin;\nimport mezz.jei.api.registration.IGuiHandlerRegistration;\nimport net.minecraft.util.ResourceLocation;\nimport top.theillusivec4.curios.Curios;\nimport top.theillusivec4.curios.client.gui.CuriosScreen;\n\n@JeiPlugin\npublic class CuriosJeiPlugin implements IModPlugin {\n\n @Override\n @Nonnull\n public ResourceLocation getPluginUid() {\n return new ResourceLocation(Curios.MODID, Curios.MODID);\n }\n\n @Override\n public void registerGuiHandlers(IGuiHandlerRegistration registration) {\n registration.addGuiCon", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_3074", "language": "Java", "task_type": "method_signature", "source_file": "java/github/katharsis-project/katharsis-framework/katharsis-rs/src/main/java/io/katharsis/rs/internal/parameterProvider/provider/Parameter.java", "mask_start_position": 839, "mask_end_position": 909, "canonical_solution": "public boolean isAnnotationPresent(Class clazz) ", "pre_mask_code": "package io.katharsis.rs.internal.parameterProvider.provider;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Method;\n\npublic class Parameter {\n\n private final Method method;\n\n private final int parameterIndex;\n\n public Parameter(Method method, int parameterIndex) {\n this.method = method;\n this.parameterIndex = parameterIndex;\n }\n\n public Class getType() {\n return method.getParameterTypes()[parameterIndex];\n }\n\n public T getAnnotation(Class clazz) {\n Annotation[] annotations = method.getParameterAnnotations()[parameterIndex];\n for (Annotation annotation : annotations) {\n if (clazz.isAssignableFrom(annotation.getClass())) {\n return (T) annotation;\n }\n }\n return null;\n }\n\n ", "post_mask_code": "{\n Annotation[] annotations = method.getParameterAnnotations()[parameterIndex];\n for (Annotation annotation : annotations) {\n if (clazz.isAssignableFrom(annotation.getClass())) {\n return true;\n }\n }\n return false;\n }\n}\n"} {"task_id": "Java_3075", "language": "Java", "task_type": "method_body", "source_file": "java/github/katharsis-project/katharsis-framework/katharsis-rs/src/main/java/io/katharsis/rs/internal/parameterProvider/provider/Parameter.java", "mask_start_position": 909, "mask_end_position": 1193, "canonical_solution": "{\n Annotation[] annotations = method.getParameterAnnotations()[parameterIndex];\n for (Annotation annotation : annotations) {\n if (clazz.isAssignableFrom(annotation.getClass())) {\n return true;\n }\n }\n return false;\n }", "pre_mask_code": "package io.katharsis.rs.internal.parameterProvider.provider;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Method;\n\npublic class Parameter {\n\n private final Method method;\n\n private final int parameterIndex;\n\n public Parameter(Method method, int parameterIndex) {\n this.method = method;\n this.parameterIndex = parameterIndex;\n }\n\n public Class getType() {\n return method.getParameterTypes()[parameterIndex];\n }\n\n public T getAnnotation(Class clazz) {\n Annotation[] annotations = method.getParameterAnnotations()[parameterIndex];\n for (Annotation annotation : annotations) {\n if (clazz.isAssignableFrom(annotation.getClass())) {\n return (T) annotation;\n }\n }\n return null;\n }\n\n public boolean isAnnotationPresent(Class clazz) ", "post_mask_code": "\n}\n"} {"task_id": "Java_3076", "language": "Java", "task_type": "single_line", "source_file": "java/github/katharsis-project/katharsis-framework/katharsis-rs/src/main/java/io/katharsis/rs/internal/parameterProvider/provider/Parameter.java", "mask_start_position": 621, "mask_end_position": 626, "canonical_solution": "dex];", "pre_mask_code": "package io.katharsis.rs.internal.parameterProvider.provider;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Method;\n\npublic class Parameter {\n\n private final Method method;\n\n private final int parameterIndex;\n\n public Parameter(Method method, int parameterIndex) {\n this.method = method;\n this.parameterIndex = parameterIndex;\n }\n\n public Class getType() {\n return method.getParameterTypes()[parameterIndex];\n }\n\n public T getAnnotation(Class clazz) {\n Annotation[] annotations = method.getParameterAnnotations()[parameterIn", "post_mask_code": "\n for (Annotation annotation : annotations) {\n if (clazz.isAssignableFrom(annotation.getClass())) {\n return (T) annotation;\n }\n }\n return null;\n }\n\n public boolean isAnnotationPresent(Class clazz) {\n Annotation[] annotations = method.getParameterAnnotations()[parameterIndex];\n for (Annotation annotation : annotations) {\n if (clazz.isAssignableFrom(annotation.getClass())) {\n return true;\n }\n }\n return false;\n }\n}\n"} {"task_id": "Java_3077", "language": "Java", "task_type": "method_signature", "source_file": "java/github/saysky/Hotel/src/main/java/com/example/hotel/controller/admin/CategoryController.java", "mask_start_position": 2447, "mask_end_position": 2832, "canonical_solution": "@GetMapping(value = \"/edit\")\n public String toEditCategory(Model model, @RequestParam(value = \"page\", defaultValue = \"0\") Integer pageNumber, @RequestParam(value = \"size\", defaultValue = \"10\") Integer pageSize, @RequestParam(value = \"sort\", defaultValue = \"cateSort\") String sort, @RequestParam(value = \"order\", defaultValue = \"desc\") String order, @RequestParam(\"id\") Long cateId) ", "pre_mask_code": "package com.example.hotel.controller.admin;\n\nimport com.baomidou.mybatisplus.extension.plugins.pagination.Page;\nimport com.example.hotel.controller.common.BaseController;\nimport com.example.hotel.entity.Category;\nimport com.example.hotel.dto.JsonResult;\nimport com.example.hotel.service.CategoryService;\nimport com.example.hotel.util.PageUtil;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.*;\n\n@Slf4j\n@Controller\n@RequestMapping(value = \"/admin/category\")\npublic class CategoryController extends BaseController {\n\n @Autowired\n private CategoryService categoryService;\n\n /**\n * 查询所有分类并渲染category页面\n *\n * @return 模板路径admin/admin_category\n */\n @GetMapping\n public String categories(@RequestParam(value = \"page\", defaultValue = \"0\") Integer pageNumber, @RequestParam(value = \"size\", defaultValue = \"10\") Integer pageSize, @RequestParam(value = \"sort\", defaultValue = \"cateSort\") String sort, @RequestParam(value = \"order\", defaultValue = \"desc\") String order, Model model) {\n Page page = PageUtil.initMpPage(pageNumber, pageSize, sort, order);\n Page categoryPage = categoryService.findAll(page);\n model.addAttribute(\"categories\", categoryPage.getRecords());\n model.addAttribute(\"pageInfo\", PageUtil.convertPageVo(page));\n return \"admin/admin_category\";\n }\n\n /**\n * 新增/修改分类目录\n *\n * @param category category对象\n * @return 重定向到/admin/category\n */\n @PostMapping(value = \"/save\")\n @ResponseBody\n public JsonResult saveCategory(@ModelAttribute Category category) {\n categoryService.insertOrUpdate(category);\n return JsonResult.success(\"保存成功\");\n }\n\n /**\n * 删除分类\n *\n * @param cateId 分类Id\n * @return JsonResult\n */\n @DeleteMapping(value = \"/delete\")\n @ResponseBody\n public JsonResult checkDelete(@RequestParam(\"id\") Long cateId) {\n Integer count = categoryService.countPostByCateId(cateId);\n if (count != 0) {\n return JsonResult.error(\"该分类已经有了客房,无法删除\");\n }\n categoryService.delete(cateId);\n return JsonResult.success(\"删除成功\");\n }\n\n /**\n * 跳转到修改页面\n *\n * @param cateId cateId\n * @param model model\n * @return 模板路径admin/admin_category\n */\n ", "post_mask_code": "{\n Page page = PageUtil.initMpPage(pageNumber, pageSize, sort, order);\n // 更新的分类\n Category category = categoryService.get(cateId);\n if (category == null) {\n return this.renderNotFound();\n }\n model.addAttribute(\"updateCategory\", category);\n // 所有分类\n Page categoryPage = categoryService.findAll(page);\n model.addAttribute(\"categories\", categoryPage.getRecords());\n model.addAttribute(\"pageInfo\", PageUtil.convertPageVo(page));\n return \"admin/admin_category\";\n }\n}\n"} {"task_id": "Java_3078", "language": "Java", "task_type": "method_body", "source_file": "java/github/saysky/Hotel/src/main/java/com/example/hotel/controller/admin/CategoryController.java", "mask_start_position": 1748, "mask_end_position": 1848, "canonical_solution": "{\n categoryService.insertOrUpdate(category);\n return JsonResult.success(\"保存成功\");\n }", "pre_mask_code": "package com.example.hotel.controller.admin;\n\nimport com.baomidou.mybatisplus.extension.plugins.pagination.Page;\nimport com.example.hotel.controller.common.BaseController;\nimport com.example.hotel.entity.Category;\nimport com.example.hotel.dto.JsonResult;\nimport com.example.hotel.service.CategoryService;\nimport com.example.hotel.util.PageUtil;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.*;\n\n@Slf4j\n@Controller\n@RequestMapping(value = \"/admin/category\")\npublic class CategoryController extends BaseController {\n\n @Autowired\n private CategoryService categoryService;\n\n /**\n * 查询所有分类并渲染category页面\n *\n * @return 模板路径admin/admin_category\n */\n @GetMapping\n public String categories(@RequestParam(value = \"page\", defaultValue = \"0\") Integer pageNumber, @RequestParam(value = \"size\", defaultValue = \"10\") Integer pageSize, @RequestParam(value = \"sort\", defaultValue = \"cateSort\") String sort, @RequestParam(value = \"order\", defaultValue = \"desc\") String order, Model model) {\n Page page = PageUtil.initMpPage(pageNumber, pageSize, sort, order);\n Page categoryPage = categoryService.findAll(page);\n model.addAttribute(\"categories\", categoryPage.getRecords());\n model.addAttribute(\"pageInfo\", PageUtil.convertPageVo(page));\n return \"admin/admin_category\";\n }\n\n /**\n * 新增/修改分类目录\n *\n * @param category category对象\n * @return 重定向到/admin/category\n */\n @PostMapping(value = \"/save\")\n @ResponseBody\n public JsonResult saveCategory(@ModelAttribute Category category) ", "post_mask_code": "\n\n /**\n * 删除分类\n *\n * @param cateId 分类Id\n * @return JsonResult\n */\n @DeleteMapping(value = \"/delete\")\n @ResponseBody\n public JsonResult checkDelete(@RequestParam(\"id\") Long cateId) {\n Integer count = categoryService.countPostByCateId(cateId);\n if (count != 0) {\n return JsonResult.error(\"该分类已经有了客房,无法删除\");\n }\n categoryService.delete(cateId);\n return JsonResult.success(\"删除成功\");\n }\n\n /**\n * 跳转到修改页面\n *\n * @param cateId cateId\n * @param model model\n * @return 模板路径admin/admin_category\n */\n @GetMapping(value = \"/edit\")\n public String toEditCategory(Model model, @RequestParam(value = \"page\", defaultValue = \"0\") Integer pageNumber, @RequestParam(value = \"size\", defaultValue = \"10\") Integer pageSize, @RequestParam(value = \"sort\", defaultValue = \"cateSort\") String sort, @RequestParam(value = \"order\", defaultValue = \"desc\") String order, @RequestParam(\"id\") Long cateId) {\n Page page = PageUtil.initMpPage(pageNumber, pageSize, sort, order);\n // 更新的分类\n Category category = categoryService.get(cateId);\n if (category == null) {\n return this.renderNotFound();\n }\n model.addAttribute(\"updateCategory\", category);\n // 所有分类\n Page categoryPage = categoryService.findAll(page);\n model.addAttribute(\"categories\", categoryPage.getRecords());\n model.addAttribute(\"pageInfo\", PageUtil.convertPageVo(page));\n return \"admin/admin_category\";\n }\n}\n"} {"task_id": "Java_3079", "language": "Java", "task_type": "single_line", "source_file": "java/github/saysky/Hotel/src/main/java/com/example/hotel/controller/admin/CategoryController.java", "mask_start_position": 2864, "mask_end_position": 2909, "canonical_solution": "nitMpPage(pageNumber, pageSize, sort, order);", "pre_mask_code": "package com.example.hotel.controller.admin;\n\nimport com.baomidou.mybatisplus.extension.plugins.pagination.Page;\nimport com.example.hotel.controller.common.BaseController;\nimport com.example.hotel.entity.Category;\nimport com.example.hotel.dto.JsonResult;\nimport com.example.hotel.service.CategoryService;\nimport com.example.hotel.util.PageUtil;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.*;\n\n@Slf4j\n@Controller\n@RequestMapping(value = \"/admin/category\")\npublic class CategoryController extends BaseController {\n\n @Autowired\n private CategoryService categoryService;\n\n /**\n * 查询所有分类并渲染category页面\n *\n * @return 模板路径admin/admin_category\n */\n @GetMapping\n public String categories(@RequestParam(value = \"page\", defaultValue = \"0\") Integer pageNumber, @RequestParam(value = \"size\", defaultValue = \"10\") Integer pageSize, @RequestParam(value = \"sort\", defaultValue = \"cateSort\") String sort, @RequestParam(value = \"order\", defaultValue = \"desc\") String order, Model model) {\n Page page = PageUtil.initMpPage(pageNumber, pageSize, sort, order);\n Page categoryPage = categoryService.findAll(page);\n model.addAttribute(\"categories\", categoryPage.getRecords());\n model.addAttribute(\"pageInfo\", PageUtil.convertPageVo(page));\n return \"admin/admin_category\";\n }\n\n /**\n * 新增/修改分类目录\n *\n * @param category category对象\n * @return 重定向到/admin/category\n */\n @PostMapping(value = \"/save\")\n @ResponseBody\n public JsonResult saveCategory(@ModelAttribute Category category) {\n categoryService.insertOrUpdate(category);\n return JsonResult.success(\"保存成功\");\n }\n\n /**\n * 删除分类\n *\n * @param cateId 分类Id\n * @return JsonResult\n */\n @DeleteMapping(value = \"/delete\")\n @ResponseBody\n public JsonResult checkDelete(@RequestParam(\"id\") Long cateId) {\n Integer count = categoryService.countPostByCateId(cateId);\n if (count != 0) {\n return JsonResult.error(\"该分类已经有了客房,无法删除\");\n }\n categoryService.delete(cateId);\n return JsonResult.success(\"删除成功\");\n }\n\n /**\n * 跳转到修改页面\n *\n * @param cateId cateId\n * @param model model\n * @return 模板路径admin/admin_category\n */\n @GetMapping(value = \"/edit\")\n public String toEditCategory(Model model, @RequestParam(value = \"page\", defaultValue = \"0\") Integer pageNumber, @RequestParam(value = \"size\", defaultValue = \"10\") Integer pageSize, @RequestParam(value = \"sort\", defaultValue = \"cateSort\") String sort, @RequestParam(value = \"order\", defaultValue = \"desc\") String order, @RequestParam(\"id\") Long cateId) {\n Page page = PageUtil.i", "post_mask_code": "\n // 更新的分类\n Category category = categoryService.get(cateId);\n if (category == null) {\n return this.renderNotFound();\n }\n model.addAttribute(\"updateCategory\", category);\n // 所有分类\n Page categoryPage = categoryService.findAll(page);\n model.addAttribute(\"categories\", categoryPage.getRecords());\n model.addAttribute(\"pageInfo\", PageUtil.convertPageVo(page));\n return \"admin/admin_category\";\n }\n}\n"} {"task_id": "Java_3080", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/saysky/Hotel/src/main/java/com/example/hotel/controller/admin/CategoryController.java", "mask_start_position": 1941, "mask_end_position": 2308, "canonical_solution": "@DeleteMapping(value = \"/delete\")\n @ResponseBody\n public JsonResult checkDelete(@RequestParam(\"id\") Long cateId) {\n Integer count = categoryService.countPostByCateId(cateId);\n if (count != 0) {\n return JsonResult.error(\"该分类已经有了客房,无法删除\");\n }\n categoryService.delete(cateId);\n return JsonResult.success(\"删除成功\");\n }", "pre_mask_code": "package com.example.hotel.controller.admin;\n\nimport com.baomidou.mybatisplus.extension.plugins.pagination.Page;\nimport com.example.hotel.controller.common.BaseController;\nimport com.example.hotel.entity.Category;\nimport com.example.hotel.dto.JsonResult;\nimport com.example.hotel.service.CategoryService;\nimport com.example.hotel.util.PageUtil;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.*;\n\n@Slf4j\n@Controller\n@RequestMapping(value = \"/admin/category\")\npublic class CategoryController extends BaseController {\n\n @Autowired\n private CategoryService categoryService;\n\n /**\n * 查询所有分类并渲染category页面\n *\n * @return 模板路径admin/admin_category\n */\n @GetMapping\n public String categories(@RequestParam(value = \"page\", defaultValue = \"0\") Integer pageNumber, @RequestParam(value = \"size\", defaultValue = \"10\") Integer pageSize, @RequestParam(value = \"sort\", defaultValue = \"cateSort\") String sort, @RequestParam(value = \"order\", defaultValue = \"desc\") String order, Model model) {\n Page page = PageUtil.initMpPage(pageNumber, pageSize, sort, order);\n Page categoryPage = categoryService.findAll(page);\n model.addAttribute(\"categories\", categoryPage.getRecords());\n model.addAttribute(\"pageInfo\", PageUtil.convertPageVo(page));\n return \"admin/admin_category\";\n }\n\n /**\n * 新增/修改分类目录\n *\n * @param category category对象\n * @return 重定向到/admin/category\n */\n @PostMapping(value = \"/save\")\n @ResponseBody\n public JsonResult saveCategory(@ModelAttribute Category category) {\n categoryService.insertOrUpdate(category);\n return JsonResult.success(\"保存成功\");\n }\n\n /**\n * 删除分类\n *\n * @param cateId 分类Id\n * @return JsonResult\n */\n ", "post_mask_code": "\n\n /**\n * 跳转到修改页面\n *\n * @param cateId cateId\n * @param model model\n * @return 模板路径admin/admin_category\n */\n @GetMapping(value = \"/edit\")\n public String toEditCategory(Model model, @RequestParam(value = \"page\", defaultValue = \"0\") Integer pageNumber, @RequestParam(value = \"size\", defaultValue = \"10\") Integer pageSize, @RequestParam(value = \"sort\", defaultValue = \"cateSort\") String sort, @RequestParam(value = \"order\", defaultValue = \"desc\") String order, @RequestParam(\"id\") Long cateId) {\n Page page = PageUtil.initMpPage(pageNumber, pageSize, sort, order);\n // 更新的分类\n Category category = categoryService.get(cateId);\n if (category == null) {\n return this.renderNotFound();\n }\n model.addAttribute(\"updateCategory\", category);\n // 所有分类\n Page categoryPage = categoryService.findAll(page);\n model.addAttribute(\"categories\", categoryPage.getRecords());\n model.addAttribute(\"pageInfo\", PageUtil.convertPageVo(page));\n return \"admin/admin_category\";\n }\n}\n"} {"task_id": "Java_3081", "language": "Java", "task_type": "method_signature", "source_file": "java/github/GSI-CS-CO/chart-fx/chartfx-samples/src/main/java/de/gsi/chart/samples/ContourChartSample.java", "mask_start_position": 6635, "mask_end_position": 6693, "canonical_solution": "@Override\n public void start(final Stage primaryStage) ", "pre_mask_code": "package de.gsi.chart.samples;\n\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.Arrays;\nimport java.util.Objects;\nimport javafx.application.Application;\nimport javafx.application.Platform;\nimport javafx.scene.Scene;\nimport javafx.scene.control.ComboBox;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.Slider;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.Priority;\nimport javafx.scene.layout.VBox;\nimport javafx.stage.Stage;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport de.gsi.chart.XYChart;\nimport de.gsi.chart.axes.spi.DefaultNumericAxis;\nimport de.gsi.chart.plugins.ColormapSelector.ColormapComboBox;\nimport de.gsi.chart.plugins.EditAxis;\nimport de.gsi.chart.plugins.Zoomer;\nimport de.gsi.chart.renderer.ContourType;\nimport de.gsi.chart.renderer.spi.ContourDataSetRenderer;\nimport de.gsi.chart.renderer.spi.utils.ColorGradient;\nimport de.gsi.chart.ui.geometry.Side;\nimport de.gsi.dataset.DataSet;\nimport de.gsi.dataset.spi.DataSetBuilder;\nimport de.gsi.dataset.utils.ProcessingProfiler;\n\n/**\n * @author rstein\n */\npublic class ContourChartSample extends Application {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ContourChartSample.class);\n\n private static DataSet createData() {\n final double[] x = { -12, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12 };\n final double[] y = x;\n final double[][] z = new double[x.length][y.length];\n for (int yIndex = 0; yIndex < y.length; yIndex++) {\n for (int xIndex = 0; xIndex < x.length; xIndex++) {\n z[xIndex][yIndex] = Math.sin(y[yIndex] * x[xIndex]);\n }\n }\n return new DataSetBuilder(\"demoDataSet\").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();\n }\n\n private static DataSet createTestData() {\n final int nPoints = 1000;\n final double f = 0.1;\n final double[] x = new double[nPoints];\n final double[] y = new double[nPoints];\n for (int i = 0; i < x.length; i++) {\n final double val = (i / (double) x.length - 0.5) * 10;\n x[i] = val;\n y[i] = val;\n }\n final double[][] z = new double[x.length][y.length];\n for (int yIndex = 0; yIndex < y.length; yIndex++) {\n for (int xIndex = 0; xIndex < x.length; xIndex++) {\n z[xIndex][yIndex] = Math.sin(2.0 * Math.PI * f * x[xIndex]) * Math.cos(2.0 * Math.PI * f * y[yIndex]);\n }\n }\n return new DataSetBuilder(\"demoDataSet\").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();\n }\n\n private XYChart getChartPane(final Slider slider1, final Slider slider2, final Slider slider3, final ContourType colorMap) {\n final DefaultNumericAxis xAxis = new DefaultNumericAxis();\n xAxis.setAnimated(false);\n xAxis.setAutoRangeRounding(false);\n xAxis.setName(\"X Position\");\n xAxis.setAutoRanging(true);\n final DefaultNumericAxis yAxis = new DefaultNumericAxis();\n yAxis.setAnimated(false);\n yAxis.setAutoRangeRounding(false);\n yAxis.setName(\"Y Position\");\n yAxis.setAutoRanging(true);\n final DefaultNumericAxis zAxis = new DefaultNumericAxis();\n zAxis.setAnimated(false);\n zAxis.setAutoRangeRounding(false);\n zAxis.setName(\"z Amplitude\");\n zAxis.setAutoRanging(true);\n zAxis.setSide(Side.RIGHT);\n zAxis.getProperties().put(Zoomer.ZOOMER_OMIT_AXIS, true);\n final XYChart chart = new XYChart(xAxis, yAxis);\n chart.getAxes().add(zAxis);\n chart.setTitle(\"Test data\");\n chart.setAnimated(false);\n chart.getRenderers().clear();\n chart.setLegendVisible(false);\n final ContourDataSetRenderer contourRenderer = new ContourDataSetRenderer();\n contourRenderer.getAxes().addAll(xAxis, yAxis, zAxis);\n chart.getRenderers().setAll(contourRenderer);\n // false: for color gradient map, true: for true contour map\n contourRenderer.setContourType(colorMap);\n contourRenderer.getDatasets().add(readImage());\n slider1.valueProperty().bindBidirectional(contourRenderer.quantisationLevelsProperty());\n slider1.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n slider2.valueProperty().bindBidirectional(contourRenderer.maxContourSegmentsProperty());\n slider2.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n slider3.valueProperty().bindBidirectional(contourRenderer.minHexTileSizeProperty());\n slider3.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n chart.getPlugins().add(new Zoomer());\n chart.getPlugins().add(new EditAxis());\n HBox.setHgrow(chart, Priority.ALWAYS);\n return chart;\n }\n\n public DataSet readImage() {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(ContourChartSample.class.getResourceAsStream(\"./testdata/image.txt\"))))) {\n @SuppressWarnings(\"unused\")\n String // NOPMD variable is needed to skip/check line that contains the dimension of the following\n skipLine;\n // line to be read which we derive from the data itself\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] x = reader.readLine().split(\" \");\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] y = reader.readLine().split(\" \");\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] z = reader.readLine().split(\" \");\n final double[] xValues = Arrays.stream(x).mapToDouble(Double::valueOf).toArray();\n final double[] yValues = Arrays.stream(y).mapToDouble(Double::valueOf).toArray();\n final double[] zValues = Arrays.stream(z).mapToDouble(Double::valueOf).toArray();\n return new DataSetBuilder(\"contour data\").setValues(DataSet.DIM_X, xValues).setValues(DataSet.DIM_Y, yValues).setValues(DataSet.DIM_Z, zValues).build();\n } catch (final Exception e) {\n if (LOGGER.isErrorEnabled()) {\n LOGGER.atError().setCause(e).log(\"data read error\");\n }\n }\n return null;\n }\n\n ", "post_mask_code": "{\n primaryStage.setTitle(\"ContourChart Sample\");\n // number of contour levels\n final Slider nCountourLevelSlider = new Slider(0, 100, 20);\n // number of contour segments\n final Slider nSegmentSlider = new Slider(0, 10_000, 500);\n // number of contour segments\n final Slider minHexSizeSlider = new Slider(1, 100, 5);\n final XYChart chartPane1 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.CONTOUR);\n final XYChart chartPane2 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.HEATMAP);\n final HBox hBox = new HBox(chartPane1, chartPane2);\n VBox.setVgrow(hBox, Priority.ALWAYS);\n final ContourDataSetRenderer renderer1 = (ContourDataSetRenderer) chartPane1.getRenderers().get(0);\n final ContourDataSetRenderer renderer2 = (ContourDataSetRenderer) chartPane2.getRenderers().get(0);\n nCountourLevelSlider.setShowTickLabels(true);\n nCountourLevelSlider.setShowTickMarks(true);\n nCountourLevelSlider.setMajorTickUnit(10);\n nCountourLevelSlider.setMinorTickCount(5);\n nCountourLevelSlider.setBlockIncrement(1);\n HBox.setHgrow(nCountourLevelSlider, Priority.ALWAYS);\n final HBox hBoxSlider1 = new HBox(new Label(\"n countours:\"), nCountourLevelSlider);\n nSegmentSlider.setShowTickLabels(true);\n nSegmentSlider.setShowTickMarks(true);\n nSegmentSlider.setMajorTickUnit(200);\n nSegmentSlider.setMinorTickCount(50);\n nSegmentSlider.setBlockIncrement(10);\n HBox.setHgrow(nSegmentSlider, Priority.ALWAYS);\n final HBox hBoxSlider2 = new HBox(new Label(\"n segments :\"), nSegmentSlider);\n minHexSizeSlider.setShowTickLabels(true);\n minHexSizeSlider.setShowTickMarks(true);\n minHexSizeSlider.setMajorTickUnit(10);\n minHexSizeSlider.setMinorTickCount(10);\n minHexSizeSlider.setBlockIncrement(1);\n HBox.setHgrow(minHexSizeSlider, Priority.ALWAYS);\n final HBox hBoxSlider3 = new HBox(new Label(\"minHexSizeSize :\"), minHexSizeSlider);\n ContourChartSample.bindAxis(chartPane1, chartPane2);\n final ComboBox cb1 = new ComboBox<>();\n cb1.getItems().addAll(ContourType.values());\n cb1.setValue(renderer1.getContourType());\n cb1.valueProperty().bindBidirectional(renderer1.contourTypeProperty());\n cb1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());\n final ColormapComboBox colorGradient1 = new ColormapComboBox();\n colorGradient1.getItems().addAll(ColorGradient.colorGradients());\n colorGradient1.setValue(renderer1.getColorGradient());\n colorGradient1.valueProperty().bindBidirectional(renderer1.colorGradientProperty());\n colorGradient1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());\n final ComboBox cb2 = new ComboBox<>();\n cb2.getItems().addAll(ContourType.values());\n cb2.setValue(renderer2.getContourType());\n cb2.valueProperty().bindBidirectional(renderer2.contourTypeProperty());\n cb1.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());\n final ColormapComboBox colorGradient2 = new ColormapComboBox();\n colorGradient2.setValue(renderer2.getColorGradient());\n colorGradient2.valueProperty().bindBidirectional(renderer2.colorGradientProperty());\n colorGradient2.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());\n final HBox parameter = new HBox(new Label(\"Countour1: \"), cb1, colorGradient1, new Label(\" Countour2: \"), cb2, colorGradient2);\n final VBox vBox = new VBox(hBox, hBoxSlider1, hBoxSlider2, hBoxSlider3, parameter);\n final Scene scene = new Scene(vBox, 1600, 600);\n primaryStage.setScene(scene);\n primaryStage.show();\n primaryStage.setOnCloseRequest(evt -> Platform.exit());\n }\n\n private static void bindAxis(final XYChart chartPane1, final XYChart chartPane2) {\n final DefaultNumericAxis xAxis1 = (DefaultNumericAxis) chartPane1.getXAxis();\n final DefaultNumericAxis yAxis1 = (DefaultNumericAxis) chartPane1.getYAxis();\n final DefaultNumericAxis xAxis2 = (DefaultNumericAxis) chartPane2.getXAxis();\n final DefaultNumericAxis yAxis2 = (DefaultNumericAxis) chartPane2.getYAxis();\n final DefaultNumericAxis zAxis1 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane1.getRenderers().get(0)).getZAxis();\n final DefaultNumericAxis zAxis2 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane2.getRenderers().get(0)).getZAxis();\n xAxis1.autoRangingProperty().bindBidirectional(xAxis2.autoRangingProperty());\n yAxis1.autoRangingProperty().bindBidirectional(yAxis2.autoRangingProperty());\n xAxis1.maxProperty().bindBidirectional(xAxis2.maxProperty());\n yAxis1.maxProperty().bindBidirectional(yAxis2.maxProperty());\n xAxis1.minProperty().bindBidirectional(xAxis2.minProperty());\n yAxis1.minProperty().bindBidirectional(yAxis2.minProperty());\n zAxis1.autoRangingProperty().bindBidirectional(zAxis2.autoRangingProperty());\n zAxis1.autoGrowRangingProperty().bindBidirectional(zAxis2.autoGrowRangingProperty());\n zAxis1.invertAxisProperty().bindBidirectional(zAxis2.invertAxisProperty());\n zAxis1.maxProperty().bindBidirectional(zAxis2.maxProperty());\n zAxis1.minProperty().bindBidirectional(zAxis2.minProperty());\n }\n\n /**\n * @param args the command line arguments\n */\n public static void main(final String[] args) {\n ProcessingProfiler.setVerboseOutputState(true);\n Application.launch(args);\n }\n}\n"} {"task_id": "Java_3082", "language": "Java", "task_type": "method_body", "source_file": "java/github/GSI-CS-CO/chart-fx/chartfx-samples/src/main/java/de/gsi/chart/samples/ContourChartSample.java", "mask_start_position": 12380, "mask_end_position": 12477, "canonical_solution": "{\n ProcessingProfiler.setVerboseOutputState(true);\n Application.launch(args);\n }", "pre_mask_code": "package de.gsi.chart.samples;\n\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.Arrays;\nimport java.util.Objects;\nimport javafx.application.Application;\nimport javafx.application.Platform;\nimport javafx.scene.Scene;\nimport javafx.scene.control.ComboBox;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.Slider;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.Priority;\nimport javafx.scene.layout.VBox;\nimport javafx.stage.Stage;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport de.gsi.chart.XYChart;\nimport de.gsi.chart.axes.spi.DefaultNumericAxis;\nimport de.gsi.chart.plugins.ColormapSelector.ColormapComboBox;\nimport de.gsi.chart.plugins.EditAxis;\nimport de.gsi.chart.plugins.Zoomer;\nimport de.gsi.chart.renderer.ContourType;\nimport de.gsi.chart.renderer.spi.ContourDataSetRenderer;\nimport de.gsi.chart.renderer.spi.utils.ColorGradient;\nimport de.gsi.chart.ui.geometry.Side;\nimport de.gsi.dataset.DataSet;\nimport de.gsi.dataset.spi.DataSetBuilder;\nimport de.gsi.dataset.utils.ProcessingProfiler;\n\n/**\n * @author rstein\n */\npublic class ContourChartSample extends Application {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ContourChartSample.class);\n\n private static DataSet createData() {\n final double[] x = { -12, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12 };\n final double[] y = x;\n final double[][] z = new double[x.length][y.length];\n for (int yIndex = 0; yIndex < y.length; yIndex++) {\n for (int xIndex = 0; xIndex < x.length; xIndex++) {\n z[xIndex][yIndex] = Math.sin(y[yIndex] * x[xIndex]);\n }\n }\n return new DataSetBuilder(\"demoDataSet\").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();\n }\n\n private static DataSet createTestData() {\n final int nPoints = 1000;\n final double f = 0.1;\n final double[] x = new double[nPoints];\n final double[] y = new double[nPoints];\n for (int i = 0; i < x.length; i++) {\n final double val = (i / (double) x.length - 0.5) * 10;\n x[i] = val;\n y[i] = val;\n }\n final double[][] z = new double[x.length][y.length];\n for (int yIndex = 0; yIndex < y.length; yIndex++) {\n for (int xIndex = 0; xIndex < x.length; xIndex++) {\n z[xIndex][yIndex] = Math.sin(2.0 * Math.PI * f * x[xIndex]) * Math.cos(2.0 * Math.PI * f * y[yIndex]);\n }\n }\n return new DataSetBuilder(\"demoDataSet\").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();\n }\n\n private XYChart getChartPane(final Slider slider1, final Slider slider2, final Slider slider3, final ContourType colorMap) {\n final DefaultNumericAxis xAxis = new DefaultNumericAxis();\n xAxis.setAnimated(false);\n xAxis.setAutoRangeRounding(false);\n xAxis.setName(\"X Position\");\n xAxis.setAutoRanging(true);\n final DefaultNumericAxis yAxis = new DefaultNumericAxis();\n yAxis.setAnimated(false);\n yAxis.setAutoRangeRounding(false);\n yAxis.setName(\"Y Position\");\n yAxis.setAutoRanging(true);\n final DefaultNumericAxis zAxis = new DefaultNumericAxis();\n zAxis.setAnimated(false);\n zAxis.setAutoRangeRounding(false);\n zAxis.setName(\"z Amplitude\");\n zAxis.setAutoRanging(true);\n zAxis.setSide(Side.RIGHT);\n zAxis.getProperties().put(Zoomer.ZOOMER_OMIT_AXIS, true);\n final XYChart chart = new XYChart(xAxis, yAxis);\n chart.getAxes().add(zAxis);\n chart.setTitle(\"Test data\");\n chart.setAnimated(false);\n chart.getRenderers().clear();\n chart.setLegendVisible(false);\n final ContourDataSetRenderer contourRenderer = new ContourDataSetRenderer();\n contourRenderer.getAxes().addAll(xAxis, yAxis, zAxis);\n chart.getRenderers().setAll(contourRenderer);\n // false: for color gradient map, true: for true contour map\n contourRenderer.setContourType(colorMap);\n contourRenderer.getDatasets().add(readImage());\n slider1.valueProperty().bindBidirectional(contourRenderer.quantisationLevelsProperty());\n slider1.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n slider2.valueProperty().bindBidirectional(contourRenderer.maxContourSegmentsProperty());\n slider2.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n slider3.valueProperty().bindBidirectional(contourRenderer.minHexTileSizeProperty());\n slider3.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n chart.getPlugins().add(new Zoomer());\n chart.getPlugins().add(new EditAxis());\n HBox.setHgrow(chart, Priority.ALWAYS);\n return chart;\n }\n\n public DataSet readImage() {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(ContourChartSample.class.getResourceAsStream(\"./testdata/image.txt\"))))) {\n @SuppressWarnings(\"unused\")\n String // NOPMD variable is needed to skip/check line that contains the dimension of the following\n skipLine;\n // line to be read which we derive from the data itself\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] x = reader.readLine().split(\" \");\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] y = reader.readLine().split(\" \");\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] z = reader.readLine().split(\" \");\n final double[] xValues = Arrays.stream(x).mapToDouble(Double::valueOf).toArray();\n final double[] yValues = Arrays.stream(y).mapToDouble(Double::valueOf).toArray();\n final double[] zValues = Arrays.stream(z).mapToDouble(Double::valueOf).toArray();\n return new DataSetBuilder(\"contour data\").setValues(DataSet.DIM_X, xValues).setValues(DataSet.DIM_Y, yValues).setValues(DataSet.DIM_Z, zValues).build();\n } catch (final Exception e) {\n if (LOGGER.isErrorEnabled()) {\n LOGGER.atError().setCause(e).log(\"data read error\");\n }\n }\n return null;\n }\n\n @Override\n public void start(final Stage primaryStage) {\n primaryStage.setTitle(\"ContourChart Sample\");\n // number of contour levels\n final Slider nCountourLevelSlider = new Slider(0, 100, 20);\n // number of contour segments\n final Slider nSegmentSlider = new Slider(0, 10_000, 500);\n // number of contour segments\n final Slider minHexSizeSlider = new Slider(1, 100, 5);\n final XYChart chartPane1 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.CONTOUR);\n final XYChart chartPane2 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.HEATMAP);\n final HBox hBox = new HBox(chartPane1, chartPane2);\n VBox.setVgrow(hBox, Priority.ALWAYS);\n final ContourDataSetRenderer renderer1 = (ContourDataSetRenderer) chartPane1.getRenderers().get(0);\n final ContourDataSetRenderer renderer2 = (ContourDataSetRenderer) chartPane2.getRenderers().get(0);\n nCountourLevelSlider.setShowTickLabels(true);\n nCountourLevelSlider.setShowTickMarks(true);\n nCountourLevelSlider.setMajorTickUnit(10);\n nCountourLevelSlider.setMinorTickCount(5);\n nCountourLevelSlider.setBlockIncrement(1);\n HBox.setHgrow(nCountourLevelSlider, Priority.ALWAYS);\n final HBox hBoxSlider1 = new HBox(new Label(\"n countours:\"), nCountourLevelSlider);\n nSegmentSlider.setShowTickLabels(true);\n nSegmentSlider.setShowTickMarks(true);\n nSegmentSlider.setMajorTickUnit(200);\n nSegmentSlider.setMinorTickCount(50);\n nSegmentSlider.setBlockIncrement(10);\n HBox.setHgrow(nSegmentSlider, Priority.ALWAYS);\n final HBox hBoxSlider2 = new HBox(new Label(\"n segments :\"), nSegmentSlider);\n minHexSizeSlider.setShowTickLabels(true);\n minHexSizeSlider.setShowTickMarks(true);\n minHexSizeSlider.setMajorTickUnit(10);\n minHexSizeSlider.setMinorTickCount(10);\n minHexSizeSlider.setBlockIncrement(1);\n HBox.setHgrow(minHexSizeSlider, Priority.ALWAYS);\n final HBox hBoxSlider3 = new HBox(new Label(\"minHexSizeSize :\"), minHexSizeSlider);\n ContourChartSample.bindAxis(chartPane1, chartPane2);\n final ComboBox cb1 = new ComboBox<>();\n cb1.getItems().addAll(ContourType.values());\n cb1.setValue(renderer1.getContourType());\n cb1.valueProperty().bindBidirectional(renderer1.contourTypeProperty());\n cb1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());\n final ColormapComboBox colorGradient1 = new ColormapComboBox();\n colorGradient1.getItems().addAll(ColorGradient.colorGradients());\n colorGradient1.setValue(renderer1.getColorGradient());\n colorGradient1.valueProperty().bindBidirectional(renderer1.colorGradientProperty());\n colorGradient1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());\n final ComboBox cb2 = new ComboBox<>();\n cb2.getItems().addAll(ContourType.values());\n cb2.setValue(renderer2.getContourType());\n cb2.valueProperty().bindBidirectional(renderer2.contourTypeProperty());\n cb1.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());\n final ColormapComboBox colorGradient2 = new ColormapComboBox();\n colorGradient2.setValue(renderer2.getColorGradient());\n colorGradient2.valueProperty().bindBidirectional(renderer2.colorGradientProperty());\n colorGradient2.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());\n final HBox parameter = new HBox(new Label(\"Countour1: \"), cb1, colorGradient1, new Label(\" Countour2: \"), cb2, colorGradient2);\n final VBox vBox = new VBox(hBox, hBoxSlider1, hBoxSlider2, hBoxSlider3, parameter);\n final Scene scene = new Scene(vBox, 1600, 600);\n primaryStage.setScene(scene);\n primaryStage.show();\n primaryStage.setOnCloseRequest(evt -> Platform.exit());\n }\n\n private static void bindAxis(final XYChart chartPane1, final XYChart chartPane2) {\n final DefaultNumericAxis xAxis1 = (DefaultNumericAxis) chartPane1.getXAxis();\n final DefaultNumericAxis yAxis1 = (DefaultNumericAxis) chartPane1.getYAxis();\n final DefaultNumericAxis xAxis2 = (DefaultNumericAxis) chartPane2.getXAxis();\n final DefaultNumericAxis yAxis2 = (DefaultNumericAxis) chartPane2.getYAxis();\n final DefaultNumericAxis zAxis1 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane1.getRenderers().get(0)).getZAxis();\n final DefaultNumericAxis zAxis2 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane2.getRenderers().get(0)).getZAxis();\n xAxis1.autoRangingProperty().bindBidirectional(xAxis2.autoRangingProperty());\n yAxis1.autoRangingProperty().bindBidirectional(yAxis2.autoRangingProperty());\n xAxis1.maxProperty().bindBidirectional(xAxis2.maxProperty());\n yAxis1.maxProperty().bindBidirectional(yAxis2.maxProperty());\n xAxis1.minProperty().bindBidirectional(xAxis2.minProperty());\n yAxis1.minProperty().bindBidirectional(yAxis2.minProperty());\n zAxis1.autoRangingProperty().bindBidirectional(zAxis2.autoRangingProperty());\n zAxis1.autoGrowRangingProperty().bindBidirectional(zAxis2.autoGrowRangingProperty());\n zAxis1.invertAxisProperty().bindBidirectional(zAxis2.invertAxisProperty());\n zAxis1.maxProperty().bindBidirectional(zAxis2.maxProperty());\n zAxis1.minProperty().bindBidirectional(zAxis2.minProperty());\n }\n\n /**\n * @param args the command line arguments\n */\n public static void main(final String[] args) ", "post_mask_code": "\n}\n"} {"task_id": "Java_3083", "language": "Java", "task_type": "single_line", "source_file": "java/github/GSI-CS-CO/chart-fx/chartfx-samples/src/main/java/de/gsi/chart/samples/ContourChartSample.java", "mask_start_position": 8350, "mask_end_position": 8420, "canonical_solution": "Box hBoxSlider2 = new HBox(new Label(\"n segments :\"), nSegmentSlider);", "pre_mask_code": "package de.gsi.chart.samples;\n\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.Arrays;\nimport java.util.Objects;\nimport javafx.application.Application;\nimport javafx.application.Platform;\nimport javafx.scene.Scene;\nimport javafx.scene.control.ComboBox;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.Slider;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.Priority;\nimport javafx.scene.layout.VBox;\nimport javafx.stage.Stage;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport de.gsi.chart.XYChart;\nimport de.gsi.chart.axes.spi.DefaultNumericAxis;\nimport de.gsi.chart.plugins.ColormapSelector.ColormapComboBox;\nimport de.gsi.chart.plugins.EditAxis;\nimport de.gsi.chart.plugins.Zoomer;\nimport de.gsi.chart.renderer.ContourType;\nimport de.gsi.chart.renderer.spi.ContourDataSetRenderer;\nimport de.gsi.chart.renderer.spi.utils.ColorGradient;\nimport de.gsi.chart.ui.geometry.Side;\nimport de.gsi.dataset.DataSet;\nimport de.gsi.dataset.spi.DataSetBuilder;\nimport de.gsi.dataset.utils.ProcessingProfiler;\n\n/**\n * @author rstein\n */\npublic class ContourChartSample extends Application {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ContourChartSample.class);\n\n private static DataSet createData() {\n final double[] x = { -12, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12 };\n final double[] y = x;\n final double[][] z = new double[x.length][y.length];\n for (int yIndex = 0; yIndex < y.length; yIndex++) {\n for (int xIndex = 0; xIndex < x.length; xIndex++) {\n z[xIndex][yIndex] = Math.sin(y[yIndex] * x[xIndex]);\n }\n }\n return new DataSetBuilder(\"demoDataSet\").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();\n }\n\n private static DataSet createTestData() {\n final int nPoints = 1000;\n final double f = 0.1;\n final double[] x = new double[nPoints];\n final double[] y = new double[nPoints];\n for (int i = 0; i < x.length; i++) {\n final double val = (i / (double) x.length - 0.5) * 10;\n x[i] = val;\n y[i] = val;\n }\n final double[][] z = new double[x.length][y.length];\n for (int yIndex = 0; yIndex < y.length; yIndex++) {\n for (int xIndex = 0; xIndex < x.length; xIndex++) {\n z[xIndex][yIndex] = Math.sin(2.0 * Math.PI * f * x[xIndex]) * Math.cos(2.0 * Math.PI * f * y[yIndex]);\n }\n }\n return new DataSetBuilder(\"demoDataSet\").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();\n }\n\n private XYChart getChartPane(final Slider slider1, final Slider slider2, final Slider slider3, final ContourType colorMap) {\n final DefaultNumericAxis xAxis = new DefaultNumericAxis();\n xAxis.setAnimated(false);\n xAxis.setAutoRangeRounding(false);\n xAxis.setName(\"X Position\");\n xAxis.setAutoRanging(true);\n final DefaultNumericAxis yAxis = new DefaultNumericAxis();\n yAxis.setAnimated(false);\n yAxis.setAutoRangeRounding(false);\n yAxis.setName(\"Y Position\");\n yAxis.setAutoRanging(true);\n final DefaultNumericAxis zAxis = new DefaultNumericAxis();\n zAxis.setAnimated(false);\n zAxis.setAutoRangeRounding(false);\n zAxis.setName(\"z Amplitude\");\n zAxis.setAutoRanging(true);\n zAxis.setSide(Side.RIGHT);\n zAxis.getProperties().put(Zoomer.ZOOMER_OMIT_AXIS, true);\n final XYChart chart = new XYChart(xAxis, yAxis);\n chart.getAxes().add(zAxis);\n chart.setTitle(\"Test data\");\n chart.setAnimated(false);\n chart.getRenderers().clear();\n chart.setLegendVisible(false);\n final ContourDataSetRenderer contourRenderer = new ContourDataSetRenderer();\n contourRenderer.getAxes().addAll(xAxis, yAxis, zAxis);\n chart.getRenderers().setAll(contourRenderer);\n // false: for color gradient map, true: for true contour map\n contourRenderer.setContourType(colorMap);\n contourRenderer.getDatasets().add(readImage());\n slider1.valueProperty().bindBidirectional(contourRenderer.quantisationLevelsProperty());\n slider1.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n slider2.valueProperty().bindBidirectional(contourRenderer.maxContourSegmentsProperty());\n slider2.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n slider3.valueProperty().bindBidirectional(contourRenderer.minHexTileSizeProperty());\n slider3.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n chart.getPlugins().add(new Zoomer());\n chart.getPlugins().add(new EditAxis());\n HBox.setHgrow(chart, Priority.ALWAYS);\n return chart;\n }\n\n public DataSet readImage() {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(ContourChartSample.class.getResourceAsStream(\"./testdata/image.txt\"))))) {\n @SuppressWarnings(\"unused\")\n String // NOPMD variable is needed to skip/check line that contains the dimension of the following\n skipLine;\n // line to be read which we derive from the data itself\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] x = reader.readLine().split(\" \");\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] y = reader.readLine().split(\" \");\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] z = reader.readLine().split(\" \");\n final double[] xValues = Arrays.stream(x).mapToDouble(Double::valueOf).toArray();\n final double[] yValues = Arrays.stream(y).mapToDouble(Double::valueOf).toArray();\n final double[] zValues = Arrays.stream(z).mapToDouble(Double::valueOf).toArray();\n return new DataSetBuilder(\"contour data\").setValues(DataSet.DIM_X, xValues).setValues(DataSet.DIM_Y, yValues).setValues(DataSet.DIM_Z, zValues).build();\n } catch (final Exception e) {\n if (LOGGER.isErrorEnabled()) {\n LOGGER.atError().setCause(e).log(\"data read error\");\n }\n }\n return null;\n }\n\n @Override\n public void start(final Stage primaryStage) {\n primaryStage.setTitle(\"ContourChart Sample\");\n // number of contour levels\n final Slider nCountourLevelSlider = new Slider(0, 100, 20);\n // number of contour segments\n final Slider nSegmentSlider = new Slider(0, 10_000, 500);\n // number of contour segments\n final Slider minHexSizeSlider = new Slider(1, 100, 5);\n final XYChart chartPane1 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.CONTOUR);\n final XYChart chartPane2 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.HEATMAP);\n final HBox hBox = new HBox(chartPane1, chartPane2);\n VBox.setVgrow(hBox, Priority.ALWAYS);\n final ContourDataSetRenderer renderer1 = (ContourDataSetRenderer) chartPane1.getRenderers().get(0);\n final ContourDataSetRenderer renderer2 = (ContourDataSetRenderer) chartPane2.getRenderers().get(0);\n nCountourLevelSlider.setShowTickLabels(true);\n nCountourLevelSlider.setShowTickMarks(true);\n nCountourLevelSlider.setMajorTickUnit(10);\n nCountourLevelSlider.setMinorTickCount(5);\n nCountourLevelSlider.setBlockIncrement(1);\n HBox.setHgrow(nCountourLevelSlider, Priority.ALWAYS);\n final HBox hBoxSlider1 = new HBox(new Label(\"n countours:\"), nCountourLevelSlider);\n nSegmentSlider.setShowTickLabels(true);\n nSegmentSlider.setShowTickMarks(true);\n nSegmentSlider.setMajorTickUnit(200);\n nSegmentSlider.setMinorTickCount(50);\n nSegmentSlider.setBlockIncrement(10);\n HBox.setHgrow(nSegmentSlider, Priority.ALWAYS);\n final H", "post_mask_code": "\n minHexSizeSlider.setShowTickLabels(true);\n minHexSizeSlider.setShowTickMarks(true);\n minHexSizeSlider.setMajorTickUnit(10);\n minHexSizeSlider.setMinorTickCount(10);\n minHexSizeSlider.setBlockIncrement(1);\n HBox.setHgrow(minHexSizeSlider, Priority.ALWAYS);\n final HBox hBoxSlider3 = new HBox(new Label(\"minHexSizeSize :\"), minHexSizeSlider);\n ContourChartSample.bindAxis(chartPane1, chartPane2);\n final ComboBox cb1 = new ComboBox<>();\n cb1.getItems().addAll(ContourType.values());\n cb1.setValue(renderer1.getContourType());\n cb1.valueProperty().bindBidirectional(renderer1.contourTypeProperty());\n cb1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());\n final ColormapComboBox colorGradient1 = new ColormapComboBox();\n colorGradient1.getItems().addAll(ColorGradient.colorGradients());\n colorGradient1.setValue(renderer1.getColorGradient());\n colorGradient1.valueProperty().bindBidirectional(renderer1.colorGradientProperty());\n colorGradient1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());\n final ComboBox cb2 = new ComboBox<>();\n cb2.getItems().addAll(ContourType.values());\n cb2.setValue(renderer2.getContourType());\n cb2.valueProperty().bindBidirectional(renderer2.contourTypeProperty());\n cb1.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());\n final ColormapComboBox colorGradient2 = new ColormapComboBox();\n colorGradient2.setValue(renderer2.getColorGradient());\n colorGradient2.valueProperty().bindBidirectional(renderer2.colorGradientProperty());\n colorGradient2.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());\n final HBox parameter = new HBox(new Label(\"Countour1: \"), cb1, colorGradient1, new Label(\" Countour2: \"), cb2, colorGradient2);\n final VBox vBox = new VBox(hBox, hBoxSlider1, hBoxSlider2, hBoxSlider3, parameter);\n final Scene scene = new Scene(vBox, 1600, 600);\n primaryStage.setScene(scene);\n primaryStage.show();\n primaryStage.setOnCloseRequest(evt -> Platform.exit());\n }\n\n private static void bindAxis(final XYChart chartPane1, final XYChart chartPane2) {\n final DefaultNumericAxis xAxis1 = (DefaultNumericAxis) chartPane1.getXAxis();\n final DefaultNumericAxis yAxis1 = (DefaultNumericAxis) chartPane1.getYAxis();\n final DefaultNumericAxis xAxis2 = (DefaultNumericAxis) chartPane2.getXAxis();\n final DefaultNumericAxis yAxis2 = (DefaultNumericAxis) chartPane2.getYAxis();\n final DefaultNumericAxis zAxis1 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane1.getRenderers().get(0)).getZAxis();\n final DefaultNumericAxis zAxis2 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane2.getRenderers().get(0)).getZAxis();\n xAxis1.autoRangingProperty().bindBidirectional(xAxis2.autoRangingProperty());\n yAxis1.autoRangingProperty().bindBidirectional(yAxis2.autoRangingProperty());\n xAxis1.maxProperty().bindBidirectional(xAxis2.maxProperty());\n yAxis1.maxProperty().bindBidirectional(yAxis2.maxProperty());\n xAxis1.minProperty().bindBidirectional(xAxis2.minProperty());\n yAxis1.minProperty().bindBidirectional(yAxis2.minProperty());\n zAxis1.autoRangingProperty().bindBidirectional(zAxis2.autoRangingProperty());\n zAxis1.autoGrowRangingProperty().bindBidirectional(zAxis2.autoGrowRangingProperty());\n zAxis1.invertAxisProperty().bindBidirectional(zAxis2.invertAxisProperty());\n zAxis1.maxProperty().bindBidirectional(zAxis2.maxProperty());\n zAxis1.minProperty().bindBidirectional(zAxis2.minProperty());\n }\n\n /**\n * @param args the command line arguments\n */\n public static void main(final String[] args) {\n ProcessingProfiler.setVerboseOutputState(true);\n Application.launch(args);\n }\n}\n"} {"task_id": "Java_3084", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/GSI-CS-CO/chart-fx/chartfx-samples/src/main/java/de/gsi/chart/samples/ContourChartSample.java", "mask_start_position": 12335, "mask_end_position": 12477, "canonical_solution": "public static void main(final String[] args) {\n ProcessingProfiler.setVerboseOutputState(true);\n Application.launch(args);\n }", "pre_mask_code": "package de.gsi.chart.samples;\n\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.Arrays;\nimport java.util.Objects;\nimport javafx.application.Application;\nimport javafx.application.Platform;\nimport javafx.scene.Scene;\nimport javafx.scene.control.ComboBox;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.Slider;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.Priority;\nimport javafx.scene.layout.VBox;\nimport javafx.stage.Stage;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport de.gsi.chart.XYChart;\nimport de.gsi.chart.axes.spi.DefaultNumericAxis;\nimport de.gsi.chart.plugins.ColormapSelector.ColormapComboBox;\nimport de.gsi.chart.plugins.EditAxis;\nimport de.gsi.chart.plugins.Zoomer;\nimport de.gsi.chart.renderer.ContourType;\nimport de.gsi.chart.renderer.spi.ContourDataSetRenderer;\nimport de.gsi.chart.renderer.spi.utils.ColorGradient;\nimport de.gsi.chart.ui.geometry.Side;\nimport de.gsi.dataset.DataSet;\nimport de.gsi.dataset.spi.DataSetBuilder;\nimport de.gsi.dataset.utils.ProcessingProfiler;\n\n/**\n * @author rstein\n */\npublic class ContourChartSample extends Application {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ContourChartSample.class);\n\n private static DataSet createData() {\n final double[] x = { -12, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12 };\n final double[] y = x;\n final double[][] z = new double[x.length][y.length];\n for (int yIndex = 0; yIndex < y.length; yIndex++) {\n for (int xIndex = 0; xIndex < x.length; xIndex++) {\n z[xIndex][yIndex] = Math.sin(y[yIndex] * x[xIndex]);\n }\n }\n return new DataSetBuilder(\"demoDataSet\").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();\n }\n\n private static DataSet createTestData() {\n final int nPoints = 1000;\n final double f = 0.1;\n final double[] x = new double[nPoints];\n final double[] y = new double[nPoints];\n for (int i = 0; i < x.length; i++) {\n final double val = (i / (double) x.length - 0.5) * 10;\n x[i] = val;\n y[i] = val;\n }\n final double[][] z = new double[x.length][y.length];\n for (int yIndex = 0; yIndex < y.length; yIndex++) {\n for (int xIndex = 0; xIndex < x.length; xIndex++) {\n z[xIndex][yIndex] = Math.sin(2.0 * Math.PI * f * x[xIndex]) * Math.cos(2.0 * Math.PI * f * y[yIndex]);\n }\n }\n return new DataSetBuilder(\"demoDataSet\").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();\n }\n\n private XYChart getChartPane(final Slider slider1, final Slider slider2, final Slider slider3, final ContourType colorMap) {\n final DefaultNumericAxis xAxis = new DefaultNumericAxis();\n xAxis.setAnimated(false);\n xAxis.setAutoRangeRounding(false);\n xAxis.setName(\"X Position\");\n xAxis.setAutoRanging(true);\n final DefaultNumericAxis yAxis = new DefaultNumericAxis();\n yAxis.setAnimated(false);\n yAxis.setAutoRangeRounding(false);\n yAxis.setName(\"Y Position\");\n yAxis.setAutoRanging(true);\n final DefaultNumericAxis zAxis = new DefaultNumericAxis();\n zAxis.setAnimated(false);\n zAxis.setAutoRangeRounding(false);\n zAxis.setName(\"z Amplitude\");\n zAxis.setAutoRanging(true);\n zAxis.setSide(Side.RIGHT);\n zAxis.getProperties().put(Zoomer.ZOOMER_OMIT_AXIS, true);\n final XYChart chart = new XYChart(xAxis, yAxis);\n chart.getAxes().add(zAxis);\n chart.setTitle(\"Test data\");\n chart.setAnimated(false);\n chart.getRenderers().clear();\n chart.setLegendVisible(false);\n final ContourDataSetRenderer contourRenderer = new ContourDataSetRenderer();\n contourRenderer.getAxes().addAll(xAxis, yAxis, zAxis);\n chart.getRenderers().setAll(contourRenderer);\n // false: for color gradient map, true: for true contour map\n contourRenderer.setContourType(colorMap);\n contourRenderer.getDatasets().add(readImage());\n slider1.valueProperty().bindBidirectional(contourRenderer.quantisationLevelsProperty());\n slider1.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n slider2.valueProperty().bindBidirectional(contourRenderer.maxContourSegmentsProperty());\n slider2.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n slider3.valueProperty().bindBidirectional(contourRenderer.minHexTileSizeProperty());\n slider3.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n chart.getPlugins().add(new Zoomer());\n chart.getPlugins().add(new EditAxis());\n HBox.setHgrow(chart, Priority.ALWAYS);\n return chart;\n }\n\n public DataSet readImage() {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(ContourChartSample.class.getResourceAsStream(\"./testdata/image.txt\"))))) {\n @SuppressWarnings(\"unused\")\n String // NOPMD variable is needed to skip/check line that contains the dimension of the following\n skipLine;\n // line to be read which we derive from the data itself\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] x = reader.readLine().split(\" \");\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] y = reader.readLine().split(\" \");\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] z = reader.readLine().split(\" \");\n final double[] xValues = Arrays.stream(x).mapToDouble(Double::valueOf).toArray();\n final double[] yValues = Arrays.stream(y).mapToDouble(Double::valueOf).toArray();\n final double[] zValues = Arrays.stream(z).mapToDouble(Double::valueOf).toArray();\n return new DataSetBuilder(\"contour data\").setValues(DataSet.DIM_X, xValues).setValues(DataSet.DIM_Y, yValues).setValues(DataSet.DIM_Z, zValues).build();\n } catch (final Exception e) {\n if (LOGGER.isErrorEnabled()) {\n LOGGER.atError().setCause(e).log(\"data read error\");\n }\n }\n return null;\n }\n\n @Override\n public void start(final Stage primaryStage) {\n primaryStage.setTitle(\"ContourChart Sample\");\n // number of contour levels\n final Slider nCountourLevelSlider = new Slider(0, 100, 20);\n // number of contour segments\n final Slider nSegmentSlider = new Slider(0, 10_000, 500);\n // number of contour segments\n final Slider minHexSizeSlider = new Slider(1, 100, 5);\n final XYChart chartPane1 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.CONTOUR);\n final XYChart chartPane2 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.HEATMAP);\n final HBox hBox = new HBox(chartPane1, chartPane2);\n VBox.setVgrow(hBox, Priority.ALWAYS);\n final ContourDataSetRenderer renderer1 = (ContourDataSetRenderer) chartPane1.getRenderers().get(0);\n final ContourDataSetRenderer renderer2 = (ContourDataSetRenderer) chartPane2.getRenderers().get(0);\n nCountourLevelSlider.setShowTickLabels(true);\n nCountourLevelSlider.setShowTickMarks(true);\n nCountourLevelSlider.setMajorTickUnit(10);\n nCountourLevelSlider.setMinorTickCount(5);\n nCountourLevelSlider.setBlockIncrement(1);\n HBox.setHgrow(nCountourLevelSlider, Priority.ALWAYS);\n final HBox hBoxSlider1 = new HBox(new Label(\"n countours:\"), nCountourLevelSlider);\n nSegmentSlider.setShowTickLabels(true);\n nSegmentSlider.setShowTickMarks(true);\n nSegmentSlider.setMajorTickUnit(200);\n nSegmentSlider.setMinorTickCount(50);\n nSegmentSlider.setBlockIncrement(10);\n HBox.setHgrow(nSegmentSlider, Priority.ALWAYS);\n final HBox hBoxSlider2 = new HBox(new Label(\"n segments :\"), nSegmentSlider);\n minHexSizeSlider.setShowTickLabels(true);\n minHexSizeSlider.setShowTickMarks(true);\n minHexSizeSlider.setMajorTickUnit(10);\n minHexSizeSlider.setMinorTickCount(10);\n minHexSizeSlider.setBlockIncrement(1);\n HBox.setHgrow(minHexSizeSlider, Priority.ALWAYS);\n final HBox hBoxSlider3 = new HBox(new Label(\"minHexSizeSize :\"), minHexSizeSlider);\n ContourChartSample.bindAxis(chartPane1, chartPane2);\n final ComboBox cb1 = new ComboBox<>();\n cb1.getItems().addAll(ContourType.values());\n cb1.setValue(renderer1.getContourType());\n cb1.valueProperty().bindBidirectional(renderer1.contourTypeProperty());\n cb1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());\n final ColormapComboBox colorGradient1 = new ColormapComboBox();\n colorGradient1.getItems().addAll(ColorGradient.colorGradients());\n colorGradient1.setValue(renderer1.getColorGradient());\n colorGradient1.valueProperty().bindBidirectional(renderer1.colorGradientProperty());\n colorGradient1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());\n final ComboBox cb2 = new ComboBox<>();\n cb2.getItems().addAll(ContourType.values());\n cb2.setValue(renderer2.getContourType());\n cb2.valueProperty().bindBidirectional(renderer2.contourTypeProperty());\n cb1.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());\n final ColormapComboBox colorGradient2 = new ColormapComboBox();\n colorGradient2.setValue(renderer2.getColorGradient());\n colorGradient2.valueProperty().bindBidirectional(renderer2.colorGradientProperty());\n colorGradient2.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());\n final HBox parameter = new HBox(new Label(\"Countour1: \"), cb1, colorGradient1, new Label(\" Countour2: \"), cb2, colorGradient2);\n final VBox vBox = new VBox(hBox, hBoxSlider1, hBoxSlider2, hBoxSlider3, parameter);\n final Scene scene = new Scene(vBox, 1600, 600);\n primaryStage.setScene(scene);\n primaryStage.show();\n primaryStage.setOnCloseRequest(evt -> Platform.exit());\n }\n\n private static void bindAxis(final XYChart chartPane1, final XYChart chartPane2) {\n final DefaultNumericAxis xAxis1 = (DefaultNumericAxis) chartPane1.getXAxis();\n final DefaultNumericAxis yAxis1 = (DefaultNumericAxis) chartPane1.getYAxis();\n final DefaultNumericAxis xAxis2 = (DefaultNumericAxis) chartPane2.getXAxis();\n final DefaultNumericAxis yAxis2 = (DefaultNumericAxis) chartPane2.getYAxis();\n final DefaultNumericAxis zAxis1 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane1.getRenderers().get(0)).getZAxis();\n final DefaultNumericAxis zAxis2 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane2.getRenderers().get(0)).getZAxis();\n xAxis1.autoRangingProperty().bindBidirectional(xAxis2.autoRangingProperty());\n yAxis1.autoRangingProperty().bindBidirectional(yAxis2.autoRangingProperty());\n xAxis1.maxProperty().bindBidirectional(xAxis2.maxProperty());\n yAxis1.maxProperty().bindBidirectional(yAxis2.maxProperty());\n xAxis1.minProperty().bindBidirectional(xAxis2.minProperty());\n yAxis1.minProperty().bindBidirectional(yAxis2.minProperty());\n zAxis1.autoRangingProperty().bindBidirectional(zAxis2.autoRangingProperty());\n zAxis1.autoGrowRangingProperty().bindBidirectional(zAxis2.autoGrowRangingProperty());\n zAxis1.invertAxisProperty().bindBidirectional(zAxis2.invertAxisProperty());\n zAxis1.maxProperty().bindBidirectional(zAxis2.maxProperty());\n zAxis1.minProperty().bindBidirectional(zAxis2.minProperty());\n }\n\n /**\n * @param args the command line arguments\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_3085", "language": "Java", "task_type": "for_statement", "source_file": "java/github/GSI-CS-CO/chart-fx/chartfx-samples/src/main/java/de/gsi/chart/samples/ContourChartSample.java", "mask_start_position": 1494, "mask_end_position": 1702, "canonical_solution": "for (int yIndex = 0; yIndex < y.length; yIndex++) {\n for (int xIndex = 0; xIndex < x.length; xIndex++) {\n z[xIndex][yIndex] = Math.sin(y[yIndex] * x[xIndex]);\n }\n }", "pre_mask_code": "package de.gsi.chart.samples;\n\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.Arrays;\nimport java.util.Objects;\nimport javafx.application.Application;\nimport javafx.application.Platform;\nimport javafx.scene.Scene;\nimport javafx.scene.control.ComboBox;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.Slider;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.Priority;\nimport javafx.scene.layout.VBox;\nimport javafx.stage.Stage;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport de.gsi.chart.XYChart;\nimport de.gsi.chart.axes.spi.DefaultNumericAxis;\nimport de.gsi.chart.plugins.ColormapSelector.ColormapComboBox;\nimport de.gsi.chart.plugins.EditAxis;\nimport de.gsi.chart.plugins.Zoomer;\nimport de.gsi.chart.renderer.ContourType;\nimport de.gsi.chart.renderer.spi.ContourDataSetRenderer;\nimport de.gsi.chart.renderer.spi.utils.ColorGradient;\nimport de.gsi.chart.ui.geometry.Side;\nimport de.gsi.dataset.DataSet;\nimport de.gsi.dataset.spi.DataSetBuilder;\nimport de.gsi.dataset.utils.ProcessingProfiler;\n\n/**\n * @author rstein\n */\npublic class ContourChartSample extends Application {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ContourChartSample.class);\n\n private static DataSet createData() {\n final double[] x = { -12, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12 };\n final double[] y = x;\n final double[][] z = new double[x.length][y.length];\n ", "post_mask_code": "\n return new DataSetBuilder(\"demoDataSet\").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();\n }\n\n private static DataSet createTestData() {\n final int nPoints = 1000;\n final double f = 0.1;\n final double[] x = new double[nPoints];\n final double[] y = new double[nPoints];\n for (int i = 0; i < x.length; i++) {\n final double val = (i / (double) x.length - 0.5) * 10;\n x[i] = val;\n y[i] = val;\n }\n final double[][] z = new double[x.length][y.length];\n for (int yIndex = 0; yIndex < y.length; yIndex++) {\n for (int xIndex = 0; xIndex < x.length; xIndex++) {\n z[xIndex][yIndex] = Math.sin(2.0 * Math.PI * f * x[xIndex]) * Math.cos(2.0 * Math.PI * f * y[yIndex]);\n }\n }\n return new DataSetBuilder(\"demoDataSet\").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();\n }\n\n private XYChart getChartPane(final Slider slider1, final Slider slider2, final Slider slider3, final ContourType colorMap) {\n final DefaultNumericAxis xAxis = new DefaultNumericAxis();\n xAxis.setAnimated(false);\n xAxis.setAutoRangeRounding(false);\n xAxis.setName(\"X Position\");\n xAxis.setAutoRanging(true);\n final DefaultNumericAxis yAxis = new DefaultNumericAxis();\n yAxis.setAnimated(false);\n yAxis.setAutoRangeRounding(false);\n yAxis.setName(\"Y Position\");\n yAxis.setAutoRanging(true);\n final DefaultNumericAxis zAxis = new DefaultNumericAxis();\n zAxis.setAnimated(false);\n zAxis.setAutoRangeRounding(false);\n zAxis.setName(\"z Amplitude\");\n zAxis.setAutoRanging(true);\n zAxis.setSide(Side.RIGHT);\n zAxis.getProperties().put(Zoomer.ZOOMER_OMIT_AXIS, true);\n final XYChart chart = new XYChart(xAxis, yAxis);\n chart.getAxes().add(zAxis);\n chart.setTitle(\"Test data\");\n chart.setAnimated(false);\n chart.getRenderers().clear();\n chart.setLegendVisible(false);\n final ContourDataSetRenderer contourRenderer = new ContourDataSetRenderer();\n contourRenderer.getAxes().addAll(xAxis, yAxis, zAxis);\n chart.getRenderers().setAll(contourRenderer);\n // false: for color gradient map, true: for true contour map\n contourRenderer.setContourType(colorMap);\n contourRenderer.getDatasets().add(readImage());\n slider1.valueProperty().bindBidirectional(contourRenderer.quantisationLevelsProperty());\n slider1.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n slider2.valueProperty().bindBidirectional(contourRenderer.maxContourSegmentsProperty());\n slider2.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n slider3.valueProperty().bindBidirectional(contourRenderer.minHexTileSizeProperty());\n slider3.valueProperty().addListener((ch, o, n) -> chart.requestLayout());\n chart.getPlugins().add(new Zoomer());\n chart.getPlugins().add(new EditAxis());\n HBox.setHgrow(chart, Priority.ALWAYS);\n return chart;\n }\n\n public DataSet readImage() {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(ContourChartSample.class.getResourceAsStream(\"./testdata/image.txt\"))))) {\n @SuppressWarnings(\"unused\")\n String // NOPMD variable is needed to skip/check line that contains the dimension of the following\n skipLine;\n // line to be read which we derive from the data itself\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] x = reader.readLine().split(\" \");\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] y = reader.readLine().split(\" \");\n if ((skipLine = reader.readLine()) == null) {\n throw new IllegalStateException(\"expected non-null line\");\n }\n final String[] z = reader.readLine().split(\" \");\n final double[] xValues = Arrays.stream(x).mapToDouble(Double::valueOf).toArray();\n final double[] yValues = Arrays.stream(y).mapToDouble(Double::valueOf).toArray();\n final double[] zValues = Arrays.stream(z).mapToDouble(Double::valueOf).toArray();\n return new DataSetBuilder(\"contour data\").setValues(DataSet.DIM_X, xValues).setValues(DataSet.DIM_Y, yValues).setValues(DataSet.DIM_Z, zValues).build();\n } catch (final Exception e) {\n if (LOGGER.isErrorEnabled()) {\n LOGGER.atError().setCause(e).log(\"data read error\");\n }\n }\n return null;\n }\n\n @Override\n public void start(final Stage primaryStage) {\n primaryStage.setTitle(\"ContourChart Sample\");\n // number of contour levels\n final Slider nCountourLevelSlider = new Slider(0, 100, 20);\n // number of contour segments\n final Slider nSegmentSlider = new Slider(0, 10_000, 500);\n // number of contour segments\n final Slider minHexSizeSlider = new Slider(1, 100, 5);\n final XYChart chartPane1 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.CONTOUR);\n final XYChart chartPane2 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.HEATMAP);\n final HBox hBox = new HBox(chartPane1, chartPane2);\n VBox.setVgrow(hBox, Priority.ALWAYS);\n final ContourDataSetRenderer renderer1 = (ContourDataSetRenderer) chartPane1.getRenderers().get(0);\n final ContourDataSetRenderer renderer2 = (ContourDataSetRenderer) chartPane2.getRenderers().get(0);\n nCountourLevelSlider.setShowTickLabels(true);\n nCountourLevelSlider.setShowTickMarks(true);\n nCountourLevelSlider.setMajorTickUnit(10);\n nCountourLevelSlider.setMinorTickCount(5);\n nCountourLevelSlider.setBlockIncrement(1);\n HBox.setHgrow(nCountourLevelSlider, Priority.ALWAYS);\n final HBox hBoxSlider1 = new HBox(new Label(\"n countours:\"), nCountourLevelSlider);\n nSegmentSlider.setShowTickLabels(true);\n nSegmentSlider.setShowTickMarks(true);\n nSegmentSlider.setMajorTickUnit(200);\n nSegmentSlider.setMinorTickCount(50);\n nSegmentSlider.setBlockIncrement(10);\n HBox.setHgrow(nSegmentSlider, Priority.ALWAYS);\n final HBox hBoxSlider2 = new HBox(new Label(\"n segments :\"), nSegmentSlider);\n minHexSizeSlider.setShowTickLabels(true);\n minHexSizeSlider.setShowTickMarks(true);\n minHexSizeSlider.setMajorTickUnit(10);\n minHexSizeSlider.setMinorTickCount(10);\n minHexSizeSlider.setBlockIncrement(1);\n HBox.setHgrow(minHexSizeSlider, Priority.ALWAYS);\n final HBox hBoxSlider3 = new HBox(new Label(\"minHexSizeSize :\"), minHexSizeSlider);\n ContourChartSample.bindAxis(chartPane1, chartPane2);\n final ComboBox cb1 = new ComboBox<>();\n cb1.getItems().addAll(ContourType.values());\n cb1.setValue(renderer1.getContourType());\n cb1.valueProperty().bindBidirectional(renderer1.contourTypeProperty());\n cb1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());\n final ColormapComboBox colorGradient1 = new ColormapComboBox();\n colorGradient1.getItems().addAll(ColorGradient.colorGradients());\n colorGradient1.setValue(renderer1.getColorGradient());\n colorGradient1.valueProperty().bindBidirectional(renderer1.colorGradientProperty());\n colorGradient1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());\n final ComboBox cb2 = new ComboBox<>();\n cb2.getItems().addAll(ContourType.values());\n cb2.setValue(renderer2.getContourType());\n cb2.valueProperty().bindBidirectional(renderer2.contourTypeProperty());\n cb1.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());\n final ColormapComboBox colorGradient2 = new ColormapComboBox();\n colorGradient2.setValue(renderer2.getColorGradient());\n colorGradient2.valueProperty().bindBidirectional(renderer2.colorGradientProperty());\n colorGradient2.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());\n final HBox parameter = new HBox(new Label(\"Countour1: \"), cb1, colorGradient1, new Label(\" Countour2: \"), cb2, colorGradient2);\n final VBox vBox = new VBox(hBox, hBoxSlider1, hBoxSlider2, hBoxSlider3, parameter);\n final Scene scene = new Scene(vBox, 1600, 600);\n primaryStage.setScene(scene);\n primaryStage.show();\n primaryStage.setOnCloseRequest(evt -> Platform.exit());\n }\n\n private static void bindAxis(final XYChart chartPane1, final XYChart chartPane2) {\n final DefaultNumericAxis xAxis1 = (DefaultNumericAxis) chartPane1.getXAxis();\n final DefaultNumericAxis yAxis1 = (DefaultNumericAxis) chartPane1.getYAxis();\n final DefaultNumericAxis xAxis2 = (DefaultNumericAxis) chartPane2.getXAxis();\n final DefaultNumericAxis yAxis2 = (DefaultNumericAxis) chartPane2.getYAxis();\n final DefaultNumericAxis zAxis1 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane1.getRenderers().get(0)).getZAxis();\n final DefaultNumericAxis zAxis2 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane2.getRenderers().get(0)).getZAxis();\n xAxis1.autoRangingProperty().bindBidirectional(xAxis2.autoRangingProperty());\n yAxis1.autoRangingProperty().bindBidirectional(yAxis2.autoRangingProperty());\n xAxis1.maxProperty().bindBidirectional(xAxis2.maxProperty());\n yAxis1.maxProperty().bindBidirectional(yAxis2.maxProperty());\n xAxis1.minProperty().bindBidirectional(xAxis2.minProperty());\n yAxis1.minProperty().bindBidirectional(yAxis2.minProperty());\n zAxis1.autoRangingProperty().bindBidirectional(zAxis2.autoRangingProperty());\n zAxis1.autoGrowRangingProperty().bindBidirectional(zAxis2.autoGrowRangingProperty());\n zAxis1.invertAxisProperty().bindBidirectional(zAxis2.invertAxisProperty());\n zAxis1.maxProperty().bindBidirectional(zAxis2.maxProperty());\n zAxis1.minProperty().bindBidirectional(zAxis2.minProperty());\n }\n\n /**\n * @param args the command line arguments\n */\n public static void main(final String[] args) {\n ProcessingProfiler.setVerboseOutputState(true);\n Application.launch(args);\n }\n}\n"} {"task_id": "Java_3086", "language": "Java", "task_type": "method_signature", "source_file": "java/github/linkedin/rest.li/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/builder/ZooKeeperEphemeralStoreBuilder.java", "mask_start_position": 2373, "mask_end_position": 2454, "canonical_solution": "public ZooKeeperEphemeralStoreBuilder setUseNewWatcher(boolean useNewWatcher) ", "pre_mask_code": "package com.linkedin.d2.discovery.stores.zk.builder;\n\nimport com.linkedin.d2.discovery.PropertySerializer;\nimport com.linkedin.d2.discovery.stores.zk.ZKConnection;\nimport com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore;\nimport com.linkedin.d2.discovery.stores.zk.ZooKeeperPropertyMerger;\nimport com.linkedin.d2.discovery.stores.zk.ZooKeeperStore;\nimport com.linkedin.d2.discovery.stores.zk.ZookeeperChildFilter;\nimport com.linkedin.d2.discovery.stores.zk.ZookeeperEphemeralPrefixGenerator;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.function.Consumer;\nimport javax.annotation.Nullable;\n\n/**\n * Builder class for {@link ZooKeeperEphemeralStore}\n *\n * @author Francesco Capponi (example@nnthink.com)\n */\npublic class ZooKeeperEphemeralStoreBuilder implements ZooKeeperStoreBuilder> {\n\n private static final String URIS_VALUES_DIRECTORY = \"urisValues\";\n\n private ZKConnection _client;\n\n private PropertySerializer _serializer;\n\n private ZooKeeperPropertyMerger _merger;\n\n private String _path;\n\n private boolean _watchChildNodes = false;\n\n private boolean _useNewWatcher = false;\n\n private String _fsD2DirPathForBackup = null;\n\n private ScheduledExecutorService _executorService;\n\n private int _zookeeperReadWindowMs = ZooKeeperStore.DEFAULT_READ_WINDOW_MS;\n\n private ZookeeperChildFilter _zookeeperChildFilter = null;\n\n private ZookeeperEphemeralPrefixGenerator _zookeeperEphemeralPrefixGenerator = null;\n\n private List>> _onBuildListeners = new ArrayList<>();\n\n @Override\n public void setZkConnection(ZKConnection client) {\n _client = client;\n }\n\n public ZooKeeperEphemeralStoreBuilder setSerializer(PropertySerializer serializer) {\n _serializer = serializer;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setMerger(ZooKeeperPropertyMerger merger) {\n _merger = merger;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setPath(String path) {\n _path = path;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setWatchChildNodes(boolean watchChildNodes) {\n _watchChildNodes = watchChildNodes;\n return this;\n }\n\n ", "post_mask_code": "{\n _useNewWatcher = useNewWatcher;\n return this;\n }\n\n /**\n * Set null to disable\n */\n public ZooKeeperEphemeralStoreBuilder setBackupStoreFilePath(@Nullable String fsd2DirPathForBackup) {\n _fsD2DirPathForBackup = fsd2DirPathForBackup;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setExecutorService(ScheduledExecutorService executorService) {\n this._executorService = executorService;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setZookeeperReadWindowMs(int zookeeperReadWindowMs) {\n this._zookeeperReadWindowMs = zookeeperReadWindowMs;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setZookeeperChildFilter(ZookeeperChildFilter zookeeperChildFilter) {\n this._zookeeperChildFilter = zookeeperChildFilter;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setZookeeperEphemeralPrefixGenerator(ZookeeperEphemeralPrefixGenerator zookeeperEphemeralPrefixGenerator) {\n this._zookeeperEphemeralPrefixGenerator = zookeeperEphemeralPrefixGenerator;\n return this;\n }\n\n @Override\n public ZooKeeperEphemeralStoreBuilder addOnBuildListener(Consumer> onBuildListener) {\n _onBuildListeners.add(onBuildListener);\n return this;\n }\n\n @Override\n public ZooKeeperEphemeralStore build() {\n String backupStoreFilePath = null;\n if (_fsD2DirPathForBackup != null) {\n backupStoreFilePath = _fsD2DirPathForBackup + File.separator + URIS_VALUES_DIRECTORY;\n }\n ZooKeeperEphemeralStore zooKeeperEphemeralStore = new ZooKeeperEphemeralStore<>(_client, _serializer, _merger, _path, _watchChildNodes, _useNewWatcher, backupStoreFilePath, _executorService, _zookeeperReadWindowMs, _zookeeperChildFilter, _zookeeperEphemeralPrefixGenerator);\n for (Consumer> onBuildListener : _onBuildListeners) {\n onBuildListener.accept(zooKeeperEphemeralStore);\n }\n return zooKeeperEphemeralStore;\n }\n}\n"} {"task_id": "Java_3087", "language": "Java", "task_type": "method_body", "source_file": "java/github/linkedin/rest.li/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/builder/ZooKeeperEphemeralStoreBuilder.java", "mask_start_position": 3483, "mask_end_position": 3596, "canonical_solution": "{\n this._zookeeperEphemeralPrefixGenerator = zookeeperEphemeralPrefixGenerator;\n return this;\n }", "pre_mask_code": "package com.linkedin.d2.discovery.stores.zk.builder;\n\nimport com.linkedin.d2.discovery.PropertySerializer;\nimport com.linkedin.d2.discovery.stores.zk.ZKConnection;\nimport com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore;\nimport com.linkedin.d2.discovery.stores.zk.ZooKeeperPropertyMerger;\nimport com.linkedin.d2.discovery.stores.zk.ZooKeeperStore;\nimport com.linkedin.d2.discovery.stores.zk.ZookeeperChildFilter;\nimport com.linkedin.d2.discovery.stores.zk.ZookeeperEphemeralPrefixGenerator;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.function.Consumer;\nimport javax.annotation.Nullable;\n\n/**\n * Builder class for {@link ZooKeeperEphemeralStore}\n *\n * @author Francesco Capponi (example@nnthink.com)\n */\npublic class ZooKeeperEphemeralStoreBuilder implements ZooKeeperStoreBuilder> {\n\n private static final String URIS_VALUES_DIRECTORY = \"urisValues\";\n\n private ZKConnection _client;\n\n private PropertySerializer _serializer;\n\n private ZooKeeperPropertyMerger _merger;\n\n private String _path;\n\n private boolean _watchChildNodes = false;\n\n private boolean _useNewWatcher = false;\n\n private String _fsD2DirPathForBackup = null;\n\n private ScheduledExecutorService _executorService;\n\n private int _zookeeperReadWindowMs = ZooKeeperStore.DEFAULT_READ_WINDOW_MS;\n\n private ZookeeperChildFilter _zookeeperChildFilter = null;\n\n private ZookeeperEphemeralPrefixGenerator _zookeeperEphemeralPrefixGenerator = null;\n\n private List>> _onBuildListeners = new ArrayList<>();\n\n @Override\n public void setZkConnection(ZKConnection client) {\n _client = client;\n }\n\n public ZooKeeperEphemeralStoreBuilder setSerializer(PropertySerializer serializer) {\n _serializer = serializer;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setMerger(ZooKeeperPropertyMerger merger) {\n _merger = merger;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setPath(String path) {\n _path = path;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setWatchChildNodes(boolean watchChildNodes) {\n _watchChildNodes = watchChildNodes;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setUseNewWatcher(boolean useNewWatcher) {\n _useNewWatcher = useNewWatcher;\n return this;\n }\n\n /**\n * Set null to disable\n */\n public ZooKeeperEphemeralStoreBuilder setBackupStoreFilePath(@Nullable String fsd2DirPathForBackup) {\n _fsD2DirPathForBackup = fsd2DirPathForBackup;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setExecutorService(ScheduledExecutorService executorService) {\n this._executorService = executorService;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setZookeeperReadWindowMs(int zookeeperReadWindowMs) {\n this._zookeeperReadWindowMs = zookeeperReadWindowMs;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setZookeeperChildFilter(ZookeeperChildFilter zookeeperChildFilter) {\n this._zookeeperChildFilter = zookeeperChildFilter;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setZookeeperEphemeralPrefixGenerator(ZookeeperEphemeralPrefixGenerator zookeeperEphemeralPrefixGenerator) ", "post_mask_code": "\n\n @Override\n public ZooKeeperEphemeralStoreBuilder addOnBuildListener(Consumer> onBuildListener) {\n _onBuildListeners.add(onBuildListener);\n return this;\n }\n\n @Override\n public ZooKeeperEphemeralStore build() {\n String backupStoreFilePath = null;\n if (_fsD2DirPathForBackup != null) {\n backupStoreFilePath = _fsD2DirPathForBackup + File.separator + URIS_VALUES_DIRECTORY;\n }\n ZooKeeperEphemeralStore zooKeeperEphemeralStore = new ZooKeeperEphemeralStore<>(_client, _serializer, _merger, _path, _watchChildNodes, _useNewWatcher, backupStoreFilePath, _executorService, _zookeeperReadWindowMs, _zookeeperChildFilter, _zookeeperEphemeralPrefixGenerator);\n for (Consumer> onBuildListener : _onBuildListeners) {\n onBuildListener.accept(zooKeeperEphemeralStore);\n }\n return zooKeeperEphemeralStore;\n }\n}\n"} {"task_id": "Java_3088", "language": "Java", "task_type": "single_line", "source_file": "java/github/linkedin/rest.li/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/builder/ZooKeeperEphemeralStoreBuilder.java", "mask_start_position": 3287, "mask_end_position": 3303, "canonical_solution": "eperChildFilter;", "pre_mask_code": "package com.linkedin.d2.discovery.stores.zk.builder;\n\nimport com.linkedin.d2.discovery.PropertySerializer;\nimport com.linkedin.d2.discovery.stores.zk.ZKConnection;\nimport com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore;\nimport com.linkedin.d2.discovery.stores.zk.ZooKeeperPropertyMerger;\nimport com.linkedin.d2.discovery.stores.zk.ZooKeeperStore;\nimport com.linkedin.d2.discovery.stores.zk.ZookeeperChildFilter;\nimport com.linkedin.d2.discovery.stores.zk.ZookeeperEphemeralPrefixGenerator;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.function.Consumer;\nimport javax.annotation.Nullable;\n\n/**\n * Builder class for {@link ZooKeeperEphemeralStore}\n *\n * @author Francesco Capponi (example@nnthink.com)\n */\npublic class ZooKeeperEphemeralStoreBuilder implements ZooKeeperStoreBuilder> {\n\n private static final String URIS_VALUES_DIRECTORY = \"urisValues\";\n\n private ZKConnection _client;\n\n private PropertySerializer _serializer;\n\n private ZooKeeperPropertyMerger _merger;\n\n private String _path;\n\n private boolean _watchChildNodes = false;\n\n private boolean _useNewWatcher = false;\n\n private String _fsD2DirPathForBackup = null;\n\n private ScheduledExecutorService _executorService;\n\n private int _zookeeperReadWindowMs = ZooKeeperStore.DEFAULT_READ_WINDOW_MS;\n\n private ZookeeperChildFilter _zookeeperChildFilter = null;\n\n private ZookeeperEphemeralPrefixGenerator _zookeeperEphemeralPrefixGenerator = null;\n\n private List>> _onBuildListeners = new ArrayList<>();\n\n @Override\n public void setZkConnection(ZKConnection client) {\n _client = client;\n }\n\n public ZooKeeperEphemeralStoreBuilder setSerializer(PropertySerializer serializer) {\n _serializer = serializer;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setMerger(ZooKeeperPropertyMerger merger) {\n _merger = merger;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setPath(String path) {\n _path = path;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setWatchChildNodes(boolean watchChildNodes) {\n _watchChildNodes = watchChildNodes;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setUseNewWatcher(boolean useNewWatcher) {\n _useNewWatcher = useNewWatcher;\n return this;\n }\n\n /**\n * Set null to disable\n */\n public ZooKeeperEphemeralStoreBuilder setBackupStoreFilePath(@Nullable String fsd2DirPathForBackup) {\n _fsD2DirPathForBackup = fsd2DirPathForBackup;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setExecutorService(ScheduledExecutorService executorService) {\n this._executorService = executorService;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setZookeeperReadWindowMs(int zookeeperReadWindowMs) {\n this._zookeeperReadWindowMs = zookeeperReadWindowMs;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setZookeeperChildFilter(ZookeeperChildFilter zookeeperChildFilter) {\n this._zookeeperChildFilter = zooke", "post_mask_code": "\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setZookeeperEphemeralPrefixGenerator(ZookeeperEphemeralPrefixGenerator zookeeperEphemeralPrefixGenerator) {\n this._zookeeperEphemeralPrefixGenerator = zookeeperEphemeralPrefixGenerator;\n return this;\n }\n\n @Override\n public ZooKeeperEphemeralStoreBuilder addOnBuildListener(Consumer> onBuildListener) {\n _onBuildListeners.add(onBuildListener);\n return this;\n }\n\n @Override\n public ZooKeeperEphemeralStore build() {\n String backupStoreFilePath = null;\n if (_fsD2DirPathForBackup != null) {\n backupStoreFilePath = _fsD2DirPathForBackup + File.separator + URIS_VALUES_DIRECTORY;\n }\n ZooKeeperEphemeralStore zooKeeperEphemeralStore = new ZooKeeperEphemeralStore<>(_client, _serializer, _merger, _path, _watchChildNodes, _useNewWatcher, backupStoreFilePath, _executorService, _zookeeperReadWindowMs, _zookeeperChildFilter, _zookeeperEphemeralPrefixGenerator);\n for (Consumer> onBuildListener : _onBuildListeners) {\n onBuildListener.accept(zooKeeperEphemeralStore);\n }\n return zooKeeperEphemeralStore;\n }\n}\n"} {"task_id": "Java_3089", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/linkedin/rest.li/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/builder/ZooKeeperEphemeralStoreBuilder.java", "mask_start_position": 2571, "mask_end_position": 2756, "canonical_solution": "public ZooKeeperEphemeralStoreBuilder setBackupStoreFilePath(@Nullable String fsd2DirPathForBackup) {\n _fsD2DirPathForBackup = fsd2DirPathForBackup;\n return this;\n }", "pre_mask_code": "package com.linkedin.d2.discovery.stores.zk.builder;\n\nimport com.linkedin.d2.discovery.PropertySerializer;\nimport com.linkedin.d2.discovery.stores.zk.ZKConnection;\nimport com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore;\nimport com.linkedin.d2.discovery.stores.zk.ZooKeeperPropertyMerger;\nimport com.linkedin.d2.discovery.stores.zk.ZooKeeperStore;\nimport com.linkedin.d2.discovery.stores.zk.ZookeeperChildFilter;\nimport com.linkedin.d2.discovery.stores.zk.ZookeeperEphemeralPrefixGenerator;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.function.Consumer;\nimport javax.annotation.Nullable;\n\n/**\n * Builder class for {@link ZooKeeperEphemeralStore}\n *\n * @author Francesco Capponi (example@nnthink.com)\n */\npublic class ZooKeeperEphemeralStoreBuilder implements ZooKeeperStoreBuilder> {\n\n private static final String URIS_VALUES_DIRECTORY = \"urisValues\";\n\n private ZKConnection _client;\n\n private PropertySerializer _serializer;\n\n private ZooKeeperPropertyMerger _merger;\n\n private String _path;\n\n private boolean _watchChildNodes = false;\n\n private boolean _useNewWatcher = false;\n\n private String _fsD2DirPathForBackup = null;\n\n private ScheduledExecutorService _executorService;\n\n private int _zookeeperReadWindowMs = ZooKeeperStore.DEFAULT_READ_WINDOW_MS;\n\n private ZookeeperChildFilter _zookeeperChildFilter = null;\n\n private ZookeeperEphemeralPrefixGenerator _zookeeperEphemeralPrefixGenerator = null;\n\n private List>> _onBuildListeners = new ArrayList<>();\n\n @Override\n public void setZkConnection(ZKConnection client) {\n _client = client;\n }\n\n public ZooKeeperEphemeralStoreBuilder setSerializer(PropertySerializer serializer) {\n _serializer = serializer;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setMerger(ZooKeeperPropertyMerger merger) {\n _merger = merger;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setPath(String path) {\n _path = path;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setWatchChildNodes(boolean watchChildNodes) {\n _watchChildNodes = watchChildNodes;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setUseNewWatcher(boolean useNewWatcher) {\n _useNewWatcher = useNewWatcher;\n return this;\n }\n\n /**\n * Set null to disable\n */\n ", "post_mask_code": "\n\n public ZooKeeperEphemeralStoreBuilder setExecutorService(ScheduledExecutorService executorService) {\n this._executorService = executorService;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setZookeeperReadWindowMs(int zookeeperReadWindowMs) {\n this._zookeeperReadWindowMs = zookeeperReadWindowMs;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setZookeeperChildFilter(ZookeeperChildFilter zookeeperChildFilter) {\n this._zookeeperChildFilter = zookeeperChildFilter;\n return this;\n }\n\n public ZooKeeperEphemeralStoreBuilder setZookeeperEphemeralPrefixGenerator(ZookeeperEphemeralPrefixGenerator zookeeperEphemeralPrefixGenerator) {\n this._zookeeperEphemeralPrefixGenerator = zookeeperEphemeralPrefixGenerator;\n return this;\n }\n\n @Override\n public ZooKeeperEphemeralStoreBuilder addOnBuildListener(Consumer> onBuildListener) {\n _onBuildListeners.add(onBuildListener);\n return this;\n }\n\n @Override\n public ZooKeeperEphemeralStore build() {\n String backupStoreFilePath = null;\n if (_fsD2DirPathForBackup != null) {\n backupStoreFilePath = _fsD2DirPathForBackup + File.separator + URIS_VALUES_DIRECTORY;\n }\n ZooKeeperEphemeralStore zooKeeperEphemeralStore = new ZooKeeperEphemeralStore<>(_client, _serializer, _merger, _path, _watchChildNodes, _useNewWatcher, backupStoreFilePath, _executorService, _zookeeperReadWindowMs, _zookeeperChildFilter, _zookeeperEphemeralPrefixGenerator);\n for (Consumer> onBuildListener : _onBuildListeners) {\n onBuildListener.accept(zooKeeperEphemeralStore);\n }\n return zooKeeperEphemeralStore;\n }\n}\n"} {"task_id": "Java_3090", "language": "Java", "task_type": "method_signature", "source_file": "java/github/CoderGuoy/Coder/app/src/main/java/com/coder/guoy/recyclerview/ui/PlayMusic.java", "mask_start_position": 406, "mask_end_position": 471, "canonical_solution": "@Override\n protected void onCreate(Bundle savedInstanceState) ", "pre_mask_code": "package com.coder.guoy.recyclerview.ui;\n\nimport android.os.Bundle;\nimport com.coder.guoy.recyclerview.R;\nimport com.coder.guoy.recyclerview.base.MvvmBaseActivity;\nimport com.coder.guoy.recyclerview.databinding.ActivityPlayMusicBinding;\n\n/**\n * @Version:v1.0\n * @Author:Guoy\n * @CreateTime:2017年6月5日\n * @Descrpiton:自定义条形图\n */\npublic class PlayMusic extends MvvmBaseActivity {\n\n ", "post_mask_code": "{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_play_music);\n showContentView();\n setTitle(\"自定义条形图\");\n }\n}\n"} {"task_id": "Java_3091", "language": "Java", "task_type": "method_body", "source_file": "java/github/CoderGuoy/Coder/app/src/main/java/com/coder/guoy/recyclerview/ui/PlayMusic.java", "mask_start_position": 471, "mask_end_position": 631, "canonical_solution": "{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_play_music);\n showContentView();\n setTitle(\"自定义条形图\");\n }", "pre_mask_code": "package com.coder.guoy.recyclerview.ui;\n\nimport android.os.Bundle;\nimport com.coder.guoy.recyclerview.R;\nimport com.coder.guoy.recyclerview.base.MvvmBaseActivity;\nimport com.coder.guoy.recyclerview.databinding.ActivityPlayMusicBinding;\n\n/**\n * @Version:v1.0\n * @Author:Guoy\n * @CreateTime:2017年6月5日\n * @Descrpiton:自定义条形图\n */\npublic class PlayMusic extends MvvmBaseActivity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) ", "post_mask_code": "\n}\n"} {"task_id": "Java_3092", "language": "Java", "task_type": "single_line", "source_file": "java/github/CoderGuoy/Coder/app/src/main/java/com/coder/guoy/recyclerview/ui/PlayMusic.java", "mask_start_position": 609, "mask_end_position": 625, "canonical_solution": "Title(\"自定义条形图\");", "pre_mask_code": "package com.coder.guoy.recyclerview.ui;\n\nimport android.os.Bundle;\nimport com.coder.guoy.recyclerview.R;\nimport com.coder.guoy.recyclerview.base.MvvmBaseActivity;\nimport com.coder.guoy.recyclerview.databinding.ActivityPlayMusicBinding;\n\n/**\n * @Version:v1.0\n * @Author:Guoy\n * @CreateTime:2017年6月5日\n * @Descrpiton:自定义条形图\n */\npublic class PlayMusic extends MvvmBaseActivity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_play_music);\n showContentView();\n set", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_3093", "language": "Java", "task_type": "method_signature", "source_file": "java/github/radioegor146/native-obfuscator/test_data/tests/jdk8u_tests/functional/reg/jit/1004854/Test.java", "mask_start_position": 25, "mask_end_position": 81, "canonical_solution": "public static void main(String[] args) throws Exception ", "pre_mask_code": "public class Test {\n\n ", "post_mask_code": "{\n try {\n Cloneable ret = (Cloneable) new Object();\n for (int j = 0; j < 0; j++) {\n ret = new byte[0];\n }\n Cloneable tt = (Cloneable) ret;\n } catch (ClassCastException e) {\n System.out.println(\"Expected exception was thrown:\");\n e.printStackTrace();\n System.out.println(\"PASSED!\");\n } catch (Throwable e) {\n System.out.println(\"Unexpected exception was thrown:\");\n e.printStackTrace();\n System.out.println(\"FAILED\");\n System.exit(-99);\n }\n }\n}\n"} {"task_id": "Java_3094", "language": "Java", "task_type": "for_statement", "source_file": "java/github/radioegor146/native-obfuscator/test_data/tests/jdk8u_tests/functional/reg/jit/1004854/Test.java", "mask_start_position": 163, "mask_end_position": 241, "canonical_solution": "for (int j = 0; j < 0; j++) {\n ret = new byte[0];\n }", "pre_mask_code": "public class Test {\n\n public static void main(String[] args) throws Exception {\n try {\n Cloneable ret = (Cloneable) new Object();\n ", "post_mask_code": "\n Cloneable tt = (Cloneable) ret;\n } catch (ClassCastException e) {\n System.out.println(\"Expected exception was thrown:\");\n e.printStackTrace();\n System.out.println(\"PASSED!\");\n } catch (Throwable e) {\n System.out.println(\"Unexpected exception was thrown:\");\n e.printStackTrace();\n System.out.println(\"FAILED\");\n System.exit(-99);\n }\n }\n}\n"} {"task_id": "Java_3095", "language": "Java", "task_type": "method_signature", "source_file": "java/github/MrJian8/ThreadDemo/src/main/java/com/jian8/juc/queue/ProdConsumer_BlockQueueDemo.java", "mask_start_position": 2276, "mask_end_position": 2318, "canonical_solution": "public void myConsumer() throws Exception ", "pre_mask_code": "package com.jian8.juc.queue;\n\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\n\npublic class ProdConsumer_BlockQueueDemo {\n\n public static void main(String[] args) {\n MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));\n new Thread(() -> {\n System.out.println(Thread.currentThread().getName() + \"\\t生产线程启动\");\n try {\n myResource.myProd();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }, \"Prod\").start();\n new Thread(() -> {\n System.out.println(Thread.currentThread().getName() + \"\\t消费线程启动\");\n try {\n myResource.myConsumer();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }, \"Consumer\").start();\n try {\n TimeUnit.SECONDS.sleep(5);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n System.out.println(\"5s后main叫停,线程结束\");\n try {\n myResource.stop();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n\nclass MyResource {\n\n // 默认开启,进行生产+消费\n private volatile boolean flag = true;\n\n private AtomicInteger atomicInteger = new AtomicInteger();\n\n BlockingQueue blockingQueue = null;\n\n public MyResource(BlockingQueue blockingQueue) {\n this.blockingQueue = blockingQueue;\n System.out.println(blockingQueue.getClass().getName());\n }\n\n public void myProd() throws Exception {\n String data = null;\n boolean retValue;\n while (flag) {\n data = atomicInteger.incrementAndGet() + \"\";\n retValue = blockingQueue.offer(data, 2, TimeUnit.SECONDS);\n if (retValue) {\n System.out.println(Thread.currentThread().getName() + \"\\t插入队列\" + data + \"成功\");\n } else {\n System.out.println(Thread.currentThread().getName() + \"\\t插入队列\" + data + \"失败\");\n }\n TimeUnit.SECONDS.sleep(1);\n }\n System.out.println(Thread.currentThread().getName() + \"\\t大老板叫停了,flag=false,生产结束\");\n }\n\n ", "post_mask_code": "{\n String result = null;\n while (flag) {\n result = blockingQueue.poll(2, TimeUnit.SECONDS);\n if (null == result || result.equalsIgnoreCase(\"\")) {\n flag = false;\n System.out.println(Thread.currentThread().getName() + \"\\t超过2s没有取到蛋糕,消费退出\");\n System.out.println();\n return;\n }\n System.out.println(Thread.currentThread().getName() + \"\\t消费队列\" + result + \"成功\");\n }\n }\n\n public void stop() throws Exception {\n flag = false;\n }\n}\n"} {"task_id": "Java_3096", "language": "Java", "task_type": "method_body", "source_file": "java/github/MrJian8/ThreadDemo/src/main/java/com/jian8/juc/queue/ProdConsumer_BlockQueueDemo.java", "mask_start_position": 2318, "mask_end_position": 2806, "canonical_solution": "{\n String result = null;\n while (flag) {\n result = blockingQueue.poll(2, TimeUnit.SECONDS);\n if (null == result || result.equalsIgnoreCase(\"\")) {\n flag = false;\n System.out.println(Thread.currentThread().getName() + \"\\t超过2s没有取到蛋糕,消费退出\");\n System.out.println();\n return;\n }\n System.out.println(Thread.currentThread().getName() + \"\\t消费队列\" + result + \"成功\");\n }\n }", "pre_mask_code": "package com.jian8.juc.queue;\n\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\n\npublic class ProdConsumer_BlockQueueDemo {\n\n public static void main(String[] args) {\n MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));\n new Thread(() -> {\n System.out.println(Thread.currentThread().getName() + \"\\t生产线程启动\");\n try {\n myResource.myProd();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }, \"Prod\").start();\n new Thread(() -> {\n System.out.println(Thread.currentThread().getName() + \"\\t消费线程启动\");\n try {\n myResource.myConsumer();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }, \"Consumer\").start();\n try {\n TimeUnit.SECONDS.sleep(5);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n System.out.println(\"5s后main叫停,线程结束\");\n try {\n myResource.stop();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n\nclass MyResource {\n\n // 默认开启,进行生产+消费\n private volatile boolean flag = true;\n\n private AtomicInteger atomicInteger = new AtomicInteger();\n\n BlockingQueue blockingQueue = null;\n\n public MyResource(BlockingQueue blockingQueue) {\n this.blockingQueue = blockingQueue;\n System.out.println(blockingQueue.getClass().getName());\n }\n\n public void myProd() throws Exception {\n String data = null;\n boolean retValue;\n while (flag) {\n data = atomicInteger.incrementAndGet() + \"\";\n retValue = blockingQueue.offer(data, 2, TimeUnit.SECONDS);\n if (retValue) {\n System.out.println(Thread.currentThread().getName() + \"\\t插入队列\" + data + \"成功\");\n } else {\n System.out.println(Thread.currentThread().getName() + \"\\t插入队列\" + data + \"失败\");\n }\n TimeUnit.SECONDS.sleep(1);\n }\n System.out.println(Thread.currentThread().getName() + \"\\t大老板叫停了,flag=false,生产结束\");\n }\n\n public void myConsumer() throws Exception ", "post_mask_code": "\n\n public void stop() throws Exception {\n flag = false;\n }\n}\n"} {"task_id": "Java_3097", "language": "Java", "task_type": "single_line", "source_file": "java/github/MrJian8/ThreadDemo/src/main/java/com/jian8/juc/queue/ProdConsumer_BlockQueueDemo.java", "mask_start_position": 2225, "mask_end_position": 2264, "canonical_solution": "etName() + \"\\t大老板叫停了,flag=false,生产结束\");", "pre_mask_code": "package com.jian8.juc.queue;\n\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\n\npublic class ProdConsumer_BlockQueueDemo {\n\n public static void main(String[] args) {\n MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));\n new Thread(() -> {\n System.out.println(Thread.currentThread().getName() + \"\\t生产线程启动\");\n try {\n myResource.myProd();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }, \"Prod\").start();\n new Thread(() -> {\n System.out.println(Thread.currentThread().getName() + \"\\t消费线程启动\");\n try {\n myResource.myConsumer();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }, \"Consumer\").start();\n try {\n TimeUnit.SECONDS.sleep(5);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n System.out.println(\"5s后main叫停,线程结束\");\n try {\n myResource.stop();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n\nclass MyResource {\n\n // 默认开启,进行生产+消费\n private volatile boolean flag = true;\n\n private AtomicInteger atomicInteger = new AtomicInteger();\n\n BlockingQueue blockingQueue = null;\n\n public MyResource(BlockingQueue blockingQueue) {\n this.blockingQueue = blockingQueue;\n System.out.println(blockingQueue.getClass().getName());\n }\n\n public void myProd() throws Exception {\n String data = null;\n boolean retValue;\n while (flag) {\n data = atomicInteger.incrementAndGet() + \"\";\n retValue = blockingQueue.offer(data, 2, TimeUnit.SECONDS);\n if (retValue) {\n System.out.println(Thread.currentThread().getName() + \"\\t插入队列\" + data + \"成功\");\n } else {\n System.out.println(Thread.currentThread().getName() + \"\\t插入队列\" + data + \"失败\");\n }\n TimeUnit.SECONDS.sleep(1);\n }\n System.out.println(Thread.currentThread().g", "post_mask_code": "\n }\n\n public void myConsumer() throws Exception {\n String result = null;\n while (flag) {\n result = blockingQueue.poll(2, TimeUnit.SECONDS);\n if (null == result || result.equalsIgnoreCase(\"\")) {\n flag = false;\n System.out.println(Thread.currentThread().getName() + \"\\t超过2s没有取到蛋糕,消费退出\");\n System.out.println();\n return;\n }\n System.out.println(Thread.currentThread().getName() + \"\\t消费队列\" + result + \"成功\");\n }\n }\n\n public void stop() throws Exception {\n flag = false;\n }\n}\n"} {"task_id": "Java_3098", "language": "Java", "task_type": "while_statement", "source_file": "java/github/MrJian8/ThreadDemo/src/main/java/com/jian8/juc/queue/ProdConsumer_BlockQueueDemo.java", "mask_start_position": 1729, "mask_end_position": 2173, "canonical_solution": "while (flag) {\n data = atomicInteger.incrementAndGet() + \"\";\n retValue = blockingQueue.offer(data, 2, TimeUnit.SECONDS);\n if (retValue) {\n System.out.println(Thread.currentThread().getName() + \"\\t插入队列\" + data + \"成功\");\n } else {\n System.out.println(Thread.currentThread().getName() + \"\\t插入队列\" + data + \"失败\");\n }\n TimeUnit.SECONDS.sleep(1);\n }", "pre_mask_code": "package com.jian8.juc.queue;\n\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\n\npublic class ProdConsumer_BlockQueueDemo {\n\n public static void main(String[] args) {\n MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));\n new Thread(() -> {\n System.out.println(Thread.currentThread().getName() + \"\\t生产线程启动\");\n try {\n myResource.myProd();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }, \"Prod\").start();\n new Thread(() -> {\n System.out.println(Thread.currentThread().getName() + \"\\t消费线程启动\");\n try {\n myResource.myConsumer();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }, \"Consumer\").start();\n try {\n TimeUnit.SECONDS.sleep(5);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n System.out.println(\"5s后main叫停,线程结束\");\n try {\n myResource.stop();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n\nclass MyResource {\n\n // 默认开启,进行生产+消费\n private volatile boolean flag = true;\n\n private AtomicInteger atomicInteger = new AtomicInteger();\n\n BlockingQueue blockingQueue = null;\n\n public MyResource(BlockingQueue blockingQueue) {\n this.blockingQueue = blockingQueue;\n System.out.println(blockingQueue.getClass().getName());\n }\n\n public void myProd() throws Exception {\n String data = null;\n boolean retValue;\n ", "post_mask_code": "\n System.out.println(Thread.currentThread().getName() + \"\\t大老板叫停了,flag=false,生产结束\");\n }\n\n public void myConsumer() throws Exception {\n String result = null;\n while (flag) {\n result = blockingQueue.poll(2, TimeUnit.SECONDS);\n if (null == result || result.equalsIgnoreCase(\"\")) {\n flag = false;\n System.out.println(Thread.currentThread().getName() + \"\\t超过2s没有取到蛋糕,消费退出\");\n System.out.println();\n return;\n }\n System.out.println(Thread.currentThread().getName() + \"\\t消费队列\" + result + \"成功\");\n }\n }\n\n public void stop() throws Exception {\n flag = false;\n }\n}\n"} {"task_id": "Java_3099", "language": "Java", "task_type": "try_statement", "source_file": "java/github/MrJian8/ThreadDemo/src/main/java/com/jian8/juc/queue/ProdConsumer_BlockQueueDemo.java", "mask_start_position": 771, "mask_end_position": 904, "canonical_solution": "try {\n myResource.myConsumer();\n } catch (Exception e) {\n e.printStackTrace();\n }", "pre_mask_code": "package com.jian8.juc.queue;\n\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\n\npublic class ProdConsumer_BlockQueueDemo {\n\n public static void main(String[] args) {\n MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));\n new Thread(() -> {\n System.out.println(Thread.currentThread().getName() + \"\\t生产线程启动\");\n try {\n myResource.myProd();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }, \"Prod\").start();\n new Thread(() -> {\n System.out.println(Thread.currentThread().getName() + \"\\t消费线程启动\");\n ", "post_mask_code": "\n }, \"Consumer\").start();\n try {\n TimeUnit.SECONDS.sleep(5);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n System.out.println(\"5s后main叫停,线程结束\");\n try {\n myResource.stop();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n\nclass MyResource {\n\n // 默认开启,进行生产+消费\n private volatile boolean flag = true;\n\n private AtomicInteger atomicInteger = new AtomicInteger();\n\n BlockingQueue blockingQueue = null;\n\n public MyResource(BlockingQueue blockingQueue) {\n this.blockingQueue = blockingQueue;\n System.out.println(blockingQueue.getClass().getName());\n }\n\n public void myProd() throws Exception {\n String data = null;\n boolean retValue;\n while (flag) {\n data = atomicInteger.incrementAndGet() + \"\";\n retValue = blockingQueue.offer(data, 2, TimeUnit.SECONDS);\n if (retValue) {\n System.out.println(Thread.currentThread().getName() + \"\\t插入队列\" + data + \"成功\");\n } else {\n System.out.println(Thread.currentThread().getName() + \"\\t插入队列\" + data + \"失败\");\n }\n TimeUnit.SECONDS.sleep(1);\n }\n System.out.println(Thread.currentThread().getName() + \"\\t大老板叫停了,flag=false,生产结束\");\n }\n\n public void myConsumer() throws Exception {\n String result = null;\n while (flag) {\n result = blockingQueue.poll(2, TimeUnit.SECONDS);\n if (null == result || result.equalsIgnoreCase(\"\")) {\n flag = false;\n System.out.println(Thread.currentThread().getName() + \"\\t超过2s没有取到蛋糕,消费退出\");\n System.out.println();\n return;\n }\n System.out.println(Thread.currentThread().getName() + \"\\t消费队列\" + result + \"成功\");\n }\n }\n\n public void stop() throws Exception {\n flag = false;\n }\n}\n"} {"task_id": "Java_3100", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/apache/incubator-tez/tez-api/src/main/java/org/apache/tez/runtime/api/TezProcessorContext.java", "mask_start_position": 1360, "mask_end_position": 1448, "canonical_solution": "public Input waitForAnyInputReady(Collection inputs) throws InterruptedException;", "pre_mask_code": "package org.apache.tez.runtime.api;\n\nimport java.io.IOException;\nimport java.util.Collection;\nimport javax.annotation.Nullable;\n\n/**\n * Context handle for the Processor to initialize itself.\n */\npublic interface TezProcessorContext extends TezTaskContext {\n\n /**\n * Set the overall progress of this Task Attempt\n * @param progress Progress in the range from [0.0 - 1.0f]\n */\n public void setProgress(float progress);\n\n /**\n * Check whether this attempt can commit its output\n * @return true if commit allowed\n * @throws IOException\n */\n public boolean canCommit() throws IOException;\n\n /**\n * Blocking call which returns when any of the specified Inputs is ready for\n * consumption.\n *\n * There can be multiple parallel invocations of this function - where each\n * invocation blocks on the Inputs that it specifies.\n *\n * If multiple Inputs are ready, any one of them may be returned by this\n * method - including an Input which may have been returned in a previous\n * call. If invoking this method multiple times, it's recommended to remove\n * previously completed Inputs from the invocation list.\n *\n * @param inputs\n * the list of Inputs to monitor\n * @return the Input which is ready for consumption\n * @throws InterruptedException\n */\n ", "post_mask_code": "\n\n /**\n * Blocking call which returns only after all of the specified Inputs are\n * ready for consumption.\n *\n * There can be multiple parallel invocations of this function - where each\n * invocation blocks on the Inputs that it specifies.\n *\n * @param inputs\n * the list of Inputs to monitor\n * @throws InterruptedException\n */\n public void waitForAllInputsReady(Collection inputs) throws InterruptedException;\n}\n"} {"task_id": "Java_3101", "language": "Java", "task_type": "method_signature", "source_file": "java/github/NationalSecurityAgency/ghidra/Ghidra/Debug/Debugger-agent-dbgmodel/src/main/java/agent/dbgmodel/impl/dbgmodel/main/ModelIteratorInternal.java", "mask_start_position": 665, "mask_end_position": 731, "canonical_solution": "static ModelIteratorInternal instanceFor(WrapIModelIterator data) ", "pre_mask_code": "package agent.dbgmodel.impl.dbgmodel.main;\n\nimport java.util.Map;\nimport com.google.common.collect.ImmutableMap;\nimport com.sun.jna.Pointer;\nimport com.sun.jna.platform.win32.Guid.REFIID;\nimport agent.dbgmodel.dbgmodel.main.ModelIterator;\nimport agent.dbgmodel.impl.dbgmodel.DbgModelUtil;\nimport agent.dbgmodel.impl.dbgmodel.DbgModelUtil.InterfaceSupplier;\nimport agent.dbgmodel.jna.dbgmodel.main.IModelIterator;\nimport agent.dbgmodel.jna.dbgmodel.main.WrapIModelIterator;\nimport ghidra.util.datastruct.WeakValueHashMap;\n\npublic interface ModelIteratorInternal extends ModelIterator {\n\n Map CACHE = new WeakValueHashMap<>();\n\n ", "post_mask_code": "{\n return DbgModelUtil.lazyWeakCache(CACHE, data, ModelIteratorImpl::new);\n }\n\n ImmutableMap.Builder> PREFERRED_DATA_SPACES_IIDS_BUILDER = ImmutableMap.builder();\n\n Map> PREFERRED_DATA_SPACES_IIDS = PREFERRED_DATA_SPACES_IIDS_BUILDER.put(new REFIID(IModelIterator.IID_IMODEL_ITERATOR), WrapIModelIterator.class).build();\n\n static ModelIteratorInternal tryPreferredInterfaces(InterfaceSupplier supplier) {\n return DbgModelUtil.tryPreferredInterfaces(ModelIteratorInternal.class, PREFERRED_DATA_SPACES_IIDS, supplier);\n }\n}\n"} {"task_id": "Java_3102", "language": "Java", "task_type": "method_body", "source_file": "java/github/NationalSecurityAgency/ghidra/Ghidra/Debug/Debugger-agent-dbgmodel/src/main/java/agent/dbgmodel/impl/dbgmodel/main/ModelIteratorInternal.java", "mask_start_position": 731, "mask_end_position": 818, "canonical_solution": "{\n return DbgModelUtil.lazyWeakCache(CACHE, data, ModelIteratorImpl::new);\n }", "pre_mask_code": "package agent.dbgmodel.impl.dbgmodel.main;\n\nimport java.util.Map;\nimport com.google.common.collect.ImmutableMap;\nimport com.sun.jna.Pointer;\nimport com.sun.jna.platform.win32.Guid.REFIID;\nimport agent.dbgmodel.dbgmodel.main.ModelIterator;\nimport agent.dbgmodel.impl.dbgmodel.DbgModelUtil;\nimport agent.dbgmodel.impl.dbgmodel.DbgModelUtil.InterfaceSupplier;\nimport agent.dbgmodel.jna.dbgmodel.main.IModelIterator;\nimport agent.dbgmodel.jna.dbgmodel.main.WrapIModelIterator;\nimport ghidra.util.datastruct.WeakValueHashMap;\n\npublic interface ModelIteratorInternal extends ModelIterator {\n\n Map CACHE = new WeakValueHashMap<>();\n\n static ModelIteratorInternal instanceFor(WrapIModelIterator data) ", "post_mask_code": "\n\n ImmutableMap.Builder> PREFERRED_DATA_SPACES_IIDS_BUILDER = ImmutableMap.builder();\n\n Map> PREFERRED_DATA_SPACES_IIDS = PREFERRED_DATA_SPACES_IIDS_BUILDER.put(new REFIID(IModelIterator.IID_IMODEL_ITERATOR), WrapIModelIterator.class).build();\n\n static ModelIteratorInternal tryPreferredInterfaces(InterfaceSupplier supplier) {\n return DbgModelUtil.tryPreferredInterfaces(ModelIteratorInternal.class, PREFERRED_DATA_SPACES_IIDS, supplier);\n }\n}\n"} {"task_id": "Java_3103", "language": "Java", "task_type": "single_line", "source_file": "java/github/NationalSecurityAgency/ghidra/Ghidra/Debug/Debugger-agent-dbgmodel/src/main/java/agent/dbgmodel/impl/dbgmodel/main/ModelIteratorInternal.java", "mask_start_position": 783, "mask_end_position": 812, "canonical_solution": "ata, ModelIteratorImpl::new);", "pre_mask_code": "package agent.dbgmodel.impl.dbgmodel.main;\n\nimport java.util.Map;\nimport com.google.common.collect.ImmutableMap;\nimport com.sun.jna.Pointer;\nimport com.sun.jna.platform.win32.Guid.REFIID;\nimport agent.dbgmodel.dbgmodel.main.ModelIterator;\nimport agent.dbgmodel.impl.dbgmodel.DbgModelUtil;\nimport agent.dbgmodel.impl.dbgmodel.DbgModelUtil.InterfaceSupplier;\nimport agent.dbgmodel.jna.dbgmodel.main.IModelIterator;\nimport agent.dbgmodel.jna.dbgmodel.main.WrapIModelIterator;\nimport ghidra.util.datastruct.WeakValueHashMap;\n\npublic interface ModelIteratorInternal extends ModelIterator {\n\n Map CACHE = new WeakValueHashMap<>();\n\n static ModelIteratorInternal instanceFor(WrapIModelIterator data) {\n return DbgModelUtil.lazyWeakCache(CACHE, d", "post_mask_code": "\n }\n\n ImmutableMap.Builder> PREFERRED_DATA_SPACES_IIDS_BUILDER = ImmutableMap.builder();\n\n Map> PREFERRED_DATA_SPACES_IIDS = PREFERRED_DATA_SPACES_IIDS_BUILDER.put(new REFIID(IModelIterator.IID_IMODEL_ITERATOR), WrapIModelIterator.class).build();\n\n static ModelIteratorInternal tryPreferredInterfaces(InterfaceSupplier supplier) {\n return DbgModelUtil.tryPreferredInterfaces(ModelIteratorInternal.class, PREFERRED_DATA_SPACES_IIDS, supplier);\n }\n}\n"} {"task_id": "Java_3104", "language": "Java", "task_type": "method_signature", "source_file": "java/github/transferwise/tw-tasks-executor/tw-tasks-core/src/main/java/com/transferwise/tasks/dao/PostgresTaskTables.java", "mask_start_position": 1237, "mask_end_position": 1299, "canonical_solution": "@Override\n public String getUniqueTaskKeyTableIdentifier() ", "pre_mask_code": "package com.transferwise.tasks.dao;\n\nimport com.transferwise.tasks.TasksProperties;\nimport org.apache.commons.lang3.StringUtils;\n\npublic class PostgresTaskTables implements ITwTaskTables {\n\n private final String taskTableIdentifier;\n\n private final String uniqueTaskKeyIdentifier;\n\n private final String taskDataTableIdentifier;\n\n public PostgresTaskTables(TasksProperties tasksProperties) {\n if (StringUtils.isNotEmpty(tasksProperties.getTaskTablesSchemaName())) {\n taskTableIdentifier = tasksProperties.getTaskTablesSchemaName() + \".\" + tasksProperties.getTaskTableName();\n uniqueTaskKeyIdentifier = tasksProperties.getTaskTablesSchemaName() + \".\" + tasksProperties.getUniqueTaskKeyTableName();\n taskDataTableIdentifier = tasksProperties.getTaskTablesSchemaName() + \".\" + tasksProperties.getTaskDataTableName();\n } else {\n taskTableIdentifier = tasksProperties.getTaskTableName();\n uniqueTaskKeyIdentifier = tasksProperties.getUniqueTaskKeyTableName();\n taskDataTableIdentifier = tasksProperties.getTaskDataTableName();\n }\n }\n\n @Override\n public String getTaskTableIdentifier() {\n return taskTableIdentifier;\n }\n\n ", "post_mask_code": "{\n return uniqueTaskKeyIdentifier;\n }\n\n @Override\n public String getTaskDataTableIdentifier() {\n return taskDataTableIdentifier;\n }\n}\n"} {"task_id": "Java_3105", "language": "Java", "task_type": "method_body", "source_file": "java/github/transferwise/tw-tasks-executor/tw-tasks-core/src/main/java/com/transferwise/tasks/dao/PostgresTaskTables.java", "mask_start_position": 1299, "mask_end_position": 1346, "canonical_solution": "{\n return uniqueTaskKeyIdentifier;\n }", "pre_mask_code": "package com.transferwise.tasks.dao;\n\nimport com.transferwise.tasks.TasksProperties;\nimport org.apache.commons.lang3.StringUtils;\n\npublic class PostgresTaskTables implements ITwTaskTables {\n\n private final String taskTableIdentifier;\n\n private final String uniqueTaskKeyIdentifier;\n\n private final String taskDataTableIdentifier;\n\n public PostgresTaskTables(TasksProperties tasksProperties) {\n if (StringUtils.isNotEmpty(tasksProperties.getTaskTablesSchemaName())) {\n taskTableIdentifier = tasksProperties.getTaskTablesSchemaName() + \".\" + tasksProperties.getTaskTableName();\n uniqueTaskKeyIdentifier = tasksProperties.getTaskTablesSchemaName() + \".\" + tasksProperties.getUniqueTaskKeyTableName();\n taskDataTableIdentifier = tasksProperties.getTaskTablesSchemaName() + \".\" + tasksProperties.getTaskDataTableName();\n } else {\n taskTableIdentifier = tasksProperties.getTaskTableName();\n uniqueTaskKeyIdentifier = tasksProperties.getUniqueTaskKeyTableName();\n taskDataTableIdentifier = tasksProperties.getTaskDataTableName();\n }\n }\n\n @Override\n public String getTaskTableIdentifier() {\n return taskTableIdentifier;\n }\n\n @Override\n public String getUniqueTaskKeyTableIdentifier() ", "post_mask_code": "\n\n @Override\n public String getTaskDataTableIdentifier() {\n return taskDataTableIdentifier;\n }\n}\n"} {"task_id": "Java_3106", "language": "Java", "task_type": "single_line", "source_file": "java/github/transferwise/tw-tasks-executor/tw-tasks-core/src/main/java/com/transferwise/tasks/dao/PostgresTaskTables.java", "mask_start_position": 1442, "mask_end_position": 1450, "canonical_solution": "ntifier;", "pre_mask_code": "package com.transferwise.tasks.dao;\n\nimport com.transferwise.tasks.TasksProperties;\nimport org.apache.commons.lang3.StringUtils;\n\npublic class PostgresTaskTables implements ITwTaskTables {\n\n private final String taskTableIdentifier;\n\n private final String uniqueTaskKeyIdentifier;\n\n private final String taskDataTableIdentifier;\n\n public PostgresTaskTables(TasksProperties tasksProperties) {\n if (StringUtils.isNotEmpty(tasksProperties.getTaskTablesSchemaName())) {\n taskTableIdentifier = tasksProperties.getTaskTablesSchemaName() + \".\" + tasksProperties.getTaskTableName();\n uniqueTaskKeyIdentifier = tasksProperties.getTaskTablesSchemaName() + \".\" + tasksProperties.getUniqueTaskKeyTableName();\n taskDataTableIdentifier = tasksProperties.getTaskTablesSchemaName() + \".\" + tasksProperties.getTaskDataTableName();\n } else {\n taskTableIdentifier = tasksProperties.getTaskTableName();\n uniqueTaskKeyIdentifier = tasksProperties.getUniqueTaskKeyTableName();\n taskDataTableIdentifier = tasksProperties.getTaskDataTableName();\n }\n }\n\n @Override\n public String getTaskTableIdentifier() {\n return taskTableIdentifier;\n }\n\n @Override\n public String getUniqueTaskKeyTableIdentifier() {\n return uniqueTaskKeyIdentifier;\n }\n\n @Override\n public String getTaskDataTableIdentifier() {\n return taskDataTableIde", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_3107", "language": "Java", "task_type": "method_signature", "source_file": "java/github/UnknownDomainGames/PanguEngine/base/src/main/java/engine/util/Color.java", "mask_start_position": 2410, "mask_end_position": 2437, "canonical_solution": "public int getGreenAsInt() ", "pre_mask_code": "package engine.util;\n\nimport java.nio.ByteBuffer;\nimport java.nio.FloatBuffer;\nimport java.util.Objects;\n\npublic class Color {\n\n public static final Color BLACK = Color.fromRGB(0x000000);\n\n public static final Color RED = Color.fromRGB(0xff0000);\n\n public static final Color GREEN = Color.fromRGB(0x00ff00);\n\n public static final Color BLUE = Color.fromRGB(0x0000ff);\n\n public static final Color WHITE = Color.fromRGB(0xffffff);\n\n public static final Color TRANSPARENT = new Color(0f, 0f, 0f, 0f);\n\n public static Color fromGray(int gray) {\n return new Color(gray, gray, gray);\n }\n\n public static Color fromGray(float gray) {\n return new Color(gray, gray, gray);\n }\n\n public static Color fromRGB(String rgb) {\n return fromRGB(Integer.parseInt(rgb, 16));\n }\n\n public static Color fromRGB(int rgb) {\n return new Color((rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255);\n }\n\n public static Color fromARGB(String argb) {\n return fromARGB(Integer.parseInt(argb, 16));\n }\n\n public static Color fromARGB(int argb) {\n return new Color((argb >> 16) & 255, (argb >> 8) & 255, argb & 255, (argb >> 24) & 255);\n }\n\n public static Color fromRGBA(String argb) {\n return fromRGBA(Integer.parseInt(argb, 16));\n }\n\n public static Color fromRGBA(int argb) {\n return new Color((argb >> 24) & 255, (argb >> 16) & 255, (argb >> 8) & 255, argb & 255);\n }\n\n private final float red;\n\n private final float green;\n\n private final float blue;\n\n private final float alpha;\n\n public Color(int red, int green, int blue) {\n this(red / 255f, green / 255f, blue / 255f, 1f);\n }\n\n public Color(float red, float green, float blue) {\n this(red, green, blue, 1f);\n }\n\n public Color(int red, int green, int blue, int alpha) {\n this(red / 255f, green / 255f, blue / 255f, alpha / 255f);\n }\n\n public Color(float red, float green, float blue, float alpha) {\n this.red = red;\n this.green = green;\n this.blue = blue;\n this.alpha = alpha;\n }\n\n public float getRed() {\n return red;\n }\n\n public float getGreen() {\n return green;\n }\n\n public float getBlue() {\n return blue;\n }\n\n public float getAlpha() {\n return alpha;\n }\n\n public int getRedAsInt() {\n return (int) (red * 255);\n }\n\n ", "post_mask_code": "{\n return (int) (green * 255);\n }\n\n public int getBlueAsInt() {\n return (int) (blue * 255);\n }\n\n public int getAlphaAsInt() {\n return (int) (alpha * 255);\n }\n\n public FloatBuffer get(FloatBuffer dst) {\n return get(dst.position(), dst);\n }\n\n public FloatBuffer get(int index, FloatBuffer dst) {\n dst.put(index, red);\n dst.put(index + 1, green);\n dst.put(index + 2, blue);\n dst.put(index + 3, alpha);\n return dst;\n }\n\n public ByteBuffer get(ByteBuffer dst) {\n return get(dst.position(), dst);\n }\n\n public ByteBuffer get(int index, ByteBuffer dst) {\n dst.putFloat(index, red);\n dst.putFloat(index + 4, green);\n dst.putFloat(index + 8, blue);\n dst.putFloat(index + 12, alpha);\n return dst;\n }\n\n public float[] get(float[] dst) {\n return get(0, dst);\n }\n\n public float[] get(int index, float[] dst) {\n dst[index] = red;\n dst[index + 1] = green;\n dst[index + 2] = blue;\n dst[index + 3] = alpha;\n return dst;\n }\n\n public FloatBuffer getRGB(FloatBuffer dst) {\n return get(dst.position(), dst);\n }\n\n public FloatBuffer getRGB(int index, FloatBuffer dst) {\n dst.put(index, red);\n dst.put(index + 1, green);\n dst.put(index + 2, blue);\n return dst;\n }\n\n public ByteBuffer getRGB(ByteBuffer dst) {\n return get(dst.position(), dst);\n }\n\n public ByteBuffer getRGB(int index, ByteBuffer dst) {\n dst.putFloat(index, red);\n dst.putFloat(index + 4, green);\n dst.putFloat(index + 8, blue);\n return dst;\n }\n\n public float[] getRGB(float[] dst) {\n return get(0, dst);\n }\n\n public float[] getRGB(int index, float[] dst) {\n dst[index] = red;\n dst[index + 1] = green;\n dst[index + 2] = blue;\n return dst;\n }\n\n public int toRGB() {\n return (getRedAsInt() << 16) | (getGreenAsInt() << 8) | getBlueAsInt();\n }\n\n public int toARGB() {\n return (getAlphaAsInt() << 24) | toRGB();\n }\n\n public int toRGBA() {\n return (toRGB() << 8) | getAlphaAsInt();\n }\n\n public float[] toRGBAFloatArray() {\n return new float[] { red, green, blue, alpha };\n }\n\n public Color invert() {\n return difference(Color.WHITE);\n }\n\n public Color difference(Color color) {\n return new Color(Math.abs(color.red - this.red) * color.alpha + red * (1 - color.alpha), Math.abs(color.green - this.green) * color.alpha + color.green * (1 - color.alpha), Math.abs(color.blue - this.blue) * color.alpha + blue * (1 - color.alpha), alpha);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n Color color = (Color) o;\n return Float.compare(color.red, red) == 0 && Float.compare(color.green, green) == 0 && Float.compare(color.blue, blue) == 0 && Float.compare(color.alpha, alpha) == 0;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(red, green, blue, alpha);\n }\n\n @Override\n public String toString() {\n return \"Color{\" + \"red=\" + red + \", green=\" + green + \", blue=\" + blue + \", alpha=\" + alpha + '}';\n }\n}\n"} {"task_id": "Java_3108", "language": "Java", "task_type": "method_body", "source_file": "java/github/UnknownDomainGames/PanguEngine/base/src/main/java/engine/util/Color.java", "mask_start_position": 2985, "mask_end_position": 3033, "canonical_solution": "{\n return get(dst.position(), dst);\n }", "pre_mask_code": "package engine.util;\n\nimport java.nio.ByteBuffer;\nimport java.nio.FloatBuffer;\nimport java.util.Objects;\n\npublic class Color {\n\n public static final Color BLACK = Color.fromRGB(0x000000);\n\n public static final Color RED = Color.fromRGB(0xff0000);\n\n public static final Color GREEN = Color.fromRGB(0x00ff00);\n\n public static final Color BLUE = Color.fromRGB(0x0000ff);\n\n public static final Color WHITE = Color.fromRGB(0xffffff);\n\n public static final Color TRANSPARENT = new Color(0f, 0f, 0f, 0f);\n\n public static Color fromGray(int gray) {\n return new Color(gray, gray, gray);\n }\n\n public static Color fromGray(float gray) {\n return new Color(gray, gray, gray);\n }\n\n public static Color fromRGB(String rgb) {\n return fromRGB(Integer.parseInt(rgb, 16));\n }\n\n public static Color fromRGB(int rgb) {\n return new Color((rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255);\n }\n\n public static Color fromARGB(String argb) {\n return fromARGB(Integer.parseInt(argb, 16));\n }\n\n public static Color fromARGB(int argb) {\n return new Color((argb >> 16) & 255, (argb >> 8) & 255, argb & 255, (argb >> 24) & 255);\n }\n\n public static Color fromRGBA(String argb) {\n return fromRGBA(Integer.parseInt(argb, 16));\n }\n\n public static Color fromRGBA(int argb) {\n return new Color((argb >> 24) & 255, (argb >> 16) & 255, (argb >> 8) & 255, argb & 255);\n }\n\n private final float red;\n\n private final float green;\n\n private final float blue;\n\n private final float alpha;\n\n public Color(int red, int green, int blue) {\n this(red / 255f, green / 255f, blue / 255f, 1f);\n }\n\n public Color(float red, float green, float blue) {\n this(red, green, blue, 1f);\n }\n\n public Color(int red, int green, int blue, int alpha) {\n this(red / 255f, green / 255f, blue / 255f, alpha / 255f);\n }\n\n public Color(float red, float green, float blue, float alpha) {\n this.red = red;\n this.green = green;\n this.blue = blue;\n this.alpha = alpha;\n }\n\n public float getRed() {\n return red;\n }\n\n public float getGreen() {\n return green;\n }\n\n public float getBlue() {\n return blue;\n }\n\n public float getAlpha() {\n return alpha;\n }\n\n public int getRedAsInt() {\n return (int) (red * 255);\n }\n\n public int getGreenAsInt() {\n return (int) (green * 255);\n }\n\n public int getBlueAsInt() {\n return (int) (blue * 255);\n }\n\n public int getAlphaAsInt() {\n return (int) (alpha * 255);\n }\n\n public FloatBuffer get(FloatBuffer dst) {\n return get(dst.position(), dst);\n }\n\n public FloatBuffer get(int index, FloatBuffer dst) {\n dst.put(index, red);\n dst.put(index + 1, green);\n dst.put(index + 2, blue);\n dst.put(index + 3, alpha);\n return dst;\n }\n\n public ByteBuffer get(ByteBuffer dst) ", "post_mask_code": "\n\n public ByteBuffer get(int index, ByteBuffer dst) {\n dst.putFloat(index, red);\n dst.putFloat(index + 4, green);\n dst.putFloat(index + 8, blue);\n dst.putFloat(index + 12, alpha);\n return dst;\n }\n\n public float[] get(float[] dst) {\n return get(0, dst);\n }\n\n public float[] get(int index, float[] dst) {\n dst[index] = red;\n dst[index + 1] = green;\n dst[index + 2] = blue;\n dst[index + 3] = alpha;\n return dst;\n }\n\n public FloatBuffer getRGB(FloatBuffer dst) {\n return get(dst.position(), dst);\n }\n\n public FloatBuffer getRGB(int index, FloatBuffer dst) {\n dst.put(index, red);\n dst.put(index + 1, green);\n dst.put(index + 2, blue);\n return dst;\n }\n\n public ByteBuffer getRGB(ByteBuffer dst) {\n return get(dst.position(), dst);\n }\n\n public ByteBuffer getRGB(int index, ByteBuffer dst) {\n dst.putFloat(index, red);\n dst.putFloat(index + 4, green);\n dst.putFloat(index + 8, blue);\n return dst;\n }\n\n public float[] getRGB(float[] dst) {\n return get(0, dst);\n }\n\n public float[] getRGB(int index, float[] dst) {\n dst[index] = red;\n dst[index + 1] = green;\n dst[index + 2] = blue;\n return dst;\n }\n\n public int toRGB() {\n return (getRedAsInt() << 16) | (getGreenAsInt() << 8) | getBlueAsInt();\n }\n\n public int toARGB() {\n return (getAlphaAsInt() << 24) | toRGB();\n }\n\n public int toRGBA() {\n return (toRGB() << 8) | getAlphaAsInt();\n }\n\n public float[] toRGBAFloatArray() {\n return new float[] { red, green, blue, alpha };\n }\n\n public Color invert() {\n return difference(Color.WHITE);\n }\n\n public Color difference(Color color) {\n return new Color(Math.abs(color.red - this.red) * color.alpha + red * (1 - color.alpha), Math.abs(color.green - this.green) * color.alpha + color.green * (1 - color.alpha), Math.abs(color.blue - this.blue) * color.alpha + blue * (1 - color.alpha), alpha);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n Color color = (Color) o;\n return Float.compare(color.red, red) == 0 && Float.compare(color.green, green) == 0 && Float.compare(color.blue, blue) == 0 && Float.compare(color.alpha, alpha) == 0;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(red, green, blue, alpha);\n }\n\n @Override\n public String toString() {\n return \"Color{\" + \"red=\" + red + \", green=\" + green + \", blue=\" + blue + \", alpha=\" + alpha + '}';\n }\n}\n"} {"task_id": "Java_3109", "language": "Java", "task_type": "single_line", "source_file": "java/github/UnknownDomainGames/PanguEngine/base/src/main/java/engine/util/Color.java", "mask_start_position": 1272, "mask_end_position": 1296, "canonical_solution": "ger.parseInt(argb, 16));", "pre_mask_code": "package engine.util;\n\nimport java.nio.ByteBuffer;\nimport java.nio.FloatBuffer;\nimport java.util.Objects;\n\npublic class Color {\n\n public static final Color BLACK = Color.fromRGB(0x000000);\n\n public static final Color RED = Color.fromRGB(0xff0000);\n\n public static final Color GREEN = Color.fromRGB(0x00ff00);\n\n public static final Color BLUE = Color.fromRGB(0x0000ff);\n\n public static final Color WHITE = Color.fromRGB(0xffffff);\n\n public static final Color TRANSPARENT = new Color(0f, 0f, 0f, 0f);\n\n public static Color fromGray(int gray) {\n return new Color(gray, gray, gray);\n }\n\n public static Color fromGray(float gray) {\n return new Color(gray, gray, gray);\n }\n\n public static Color fromRGB(String rgb) {\n return fromRGB(Integer.parseInt(rgb, 16));\n }\n\n public static Color fromRGB(int rgb) {\n return new Color((rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255);\n }\n\n public static Color fromARGB(String argb) {\n return fromARGB(Integer.parseInt(argb, 16));\n }\n\n public static Color fromARGB(int argb) {\n return new Color((argb >> 16) & 255, (argb >> 8) & 255, argb & 255, (argb >> 24) & 255);\n }\n\n public static Color fromRGBA(String argb) {\n return fromRGBA(Inte", "post_mask_code": "\n }\n\n public static Color fromRGBA(int argb) {\n return new Color((argb >> 24) & 255, (argb >> 16) & 255, (argb >> 8) & 255, argb & 255);\n }\n\n private final float red;\n\n private final float green;\n\n private final float blue;\n\n private final float alpha;\n\n public Color(int red, int green, int blue) {\n this(red / 255f, green / 255f, blue / 255f, 1f);\n }\n\n public Color(float red, float green, float blue) {\n this(red, green, blue, 1f);\n }\n\n public Color(int red, int green, int blue, int alpha) {\n this(red / 255f, green / 255f, blue / 255f, alpha / 255f);\n }\n\n public Color(float red, float green, float blue, float alpha) {\n this.red = red;\n this.green = green;\n this.blue = blue;\n this.alpha = alpha;\n }\n\n public float getRed() {\n return red;\n }\n\n public float getGreen() {\n return green;\n }\n\n public float getBlue() {\n return blue;\n }\n\n public float getAlpha() {\n return alpha;\n }\n\n public int getRedAsInt() {\n return (int) (red * 255);\n }\n\n public int getGreenAsInt() {\n return (int) (green * 255);\n }\n\n public int getBlueAsInt() {\n return (int) (blue * 255);\n }\n\n public int getAlphaAsInt() {\n return (int) (alpha * 255);\n }\n\n public FloatBuffer get(FloatBuffer dst) {\n return get(dst.position(), dst);\n }\n\n public FloatBuffer get(int index, FloatBuffer dst) {\n dst.put(index, red);\n dst.put(index + 1, green);\n dst.put(index + 2, blue);\n dst.put(index + 3, alpha);\n return dst;\n }\n\n public ByteBuffer get(ByteBuffer dst) {\n return get(dst.position(), dst);\n }\n\n public ByteBuffer get(int index, ByteBuffer dst) {\n dst.putFloat(index, red);\n dst.putFloat(index + 4, green);\n dst.putFloat(index + 8, blue);\n dst.putFloat(index + 12, alpha);\n return dst;\n }\n\n public float[] get(float[] dst) {\n return get(0, dst);\n }\n\n public float[] get(int index, float[] dst) {\n dst[index] = red;\n dst[index + 1] = green;\n dst[index + 2] = blue;\n dst[index + 3] = alpha;\n return dst;\n }\n\n public FloatBuffer getRGB(FloatBuffer dst) {\n return get(dst.position(), dst);\n }\n\n public FloatBuffer getRGB(int index, FloatBuffer dst) {\n dst.put(index, red);\n dst.put(index + 1, green);\n dst.put(index + 2, blue);\n return dst;\n }\n\n public ByteBuffer getRGB(ByteBuffer dst) {\n return get(dst.position(), dst);\n }\n\n public ByteBuffer getRGB(int index, ByteBuffer dst) {\n dst.putFloat(index, red);\n dst.putFloat(index + 4, green);\n dst.putFloat(index + 8, blue);\n return dst;\n }\n\n public float[] getRGB(float[] dst) {\n return get(0, dst);\n }\n\n public float[] getRGB(int index, float[] dst) {\n dst[index] = red;\n dst[index + 1] = green;\n dst[index + 2] = blue;\n return dst;\n }\n\n public int toRGB() {\n return (getRedAsInt() << 16) | (getGreenAsInt() << 8) | getBlueAsInt();\n }\n\n public int toARGB() {\n return (getAlphaAsInt() << 24) | toRGB();\n }\n\n public int toRGBA() {\n return (toRGB() << 8) | getAlphaAsInt();\n }\n\n public float[] toRGBAFloatArray() {\n return new float[] { red, green, blue, alpha };\n }\n\n public Color invert() {\n return difference(Color.WHITE);\n }\n\n public Color difference(Color color) {\n return new Color(Math.abs(color.red - this.red) * color.alpha + red * (1 - color.alpha), Math.abs(color.green - this.green) * color.alpha + color.green * (1 - color.alpha), Math.abs(color.blue - this.blue) * color.alpha + blue * (1 - color.alpha), alpha);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n Color color = (Color) o;\n return Float.compare(color.red, red) == 0 && Float.compare(color.green, green) == 0 && Float.compare(color.blue, blue) == 0 && Float.compare(color.alpha, alpha) == 0;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(red, green, blue, alpha);\n }\n\n @Override\n public String toString() {\n return \"Color{\" + \"red=\" + red + \", green=\" + green + \", blue=\" + blue + \", alpha=\" + alpha + '}';\n }\n}\n"} {"task_id": "Java_3110", "language": "Java", "task_type": "method_signature", "source_file": "java/github/rhuss/jolokia/agent/core/src/main/java/org/jolokia/util/ClassUtil.java", "mask_start_position": 9172, "mask_end_position": 9237, "canonical_solution": "private static Class[] extractArgumentTypes(Object[] pArguments) ", "pre_mask_code": "package org.jolokia.util;\n\nimport java.io.*;\nimport java.lang.reflect.*;\nimport java.net.URL;\nimport java.util.*;\n\n/**\n * Utility for class lookup.\n *\n * @author roland\n * @since 19.04.11\n */\npublic final class ClassUtil {\n\n private ClassUtil() {\n }\n\n /**\n * Lookup a class. See {@link ClassUtil#classForName(String, boolean,ClassLoader[])} for details. The class\n * gets initialized during lookup.\n *\n * @param pClassName name to lookup.\n * @return the class found or null if no class could be found.\n */\n public static Class classForName(String pClassName, ClassLoader... pClassLoaders) {\n return classForName(pClassName, true, pClassLoaders);\n }\n\n /**\n * Load a certain class. Several class loader are tried: Fires the current thread's context\n * class loader, then its parents. If this doesn't work, the class loader which\n * loaded this class is used (and its parents)\n *\n * @param pClassName class name to load\n * @param pInitialize whether the class must be initialized\n * @param pClassLoaders optional class loaders which are tried as well\n * @return the class class found or null if no class could be loaded\n */\n public static Class classForName(String pClassName, boolean pInitialize, ClassLoader... pClassLoaders) {\n Set tried = new HashSet();\n for (ClassLoader loader : findClassLoaders(pClassLoaders)) {\n // Go up the classloader stack to eventually find the server class. Sometimes the WebAppClassLoader\n // hide the server classes loaded by the parent class loader.\n while (loader != null) {\n try {\n if (!tried.contains(loader)) {\n return (Class) Class.forName(pClassName, pInitialize, loader);\n }\n } catch (ClassNotFoundException ignored) {\n }\n tried.add(loader);\n loader = loader.getParent();\n }\n }\n return null;\n }\n\n private static List findClassLoaders(ClassLoader... pClassLoaders) {\n List classLoadersToTry = new ArrayList(Arrays.asList(pClassLoaders));\n classLoadersToTry.add(Thread.currentThread().getContextClassLoader());\n classLoadersToTry.add(ClassUtil.class.getClassLoader());\n List ret = new ArrayList();\n Set visited = new HashSet();\n for (ClassLoader cll : classLoadersToTry) {\n if (cll != null && !visited.contains(cll)) {\n ret.add(cll);\n visited.add(cll);\n }\n }\n return ret;\n }\n\n /**\n * Get the given path as an input stream or return null if not found\n *\n * @param pPath path to lookup\n * @return input stream or null if not found.\n */\n public static InputStream getResourceAsStream(String pPath) {\n for (ClassLoader loader : new ClassLoader[] { Thread.currentThread().getContextClassLoader(), ClassUtil.class.getClassLoader() }) {\n if (loader != null) {\n InputStream is = loader.getResourceAsStream(pPath);\n if (is != null) {\n return is;\n }\n }\n }\n return null;\n }\n\n /**\n * Check for the existence of a given class\n *\n * @param pClassName class name to check\n * @return true if the class could be loaded by the thread's conext class loader, false otherwise\n */\n public static boolean checkForClass(String pClassName) {\n return ClassUtil.classForName(pClassName, false) != null;\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor. The context class loader is used\n * to lookup the class\n *\n * @param pClassName name of class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(String pClassName, Object... pArguments) {\n Class clazz = classForName(pClassName);\n if (clazz == null) {\n throw new IllegalArgumentException(\"Cannot find \" + pClassName);\n }\n return newInstance(clazz, pArguments);\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor\n *\n * @param pClass class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(Class pClass, Object... pArguments) {\n try {\n if (pClass != null) {\n if (pArguments.length == 0) {\n return pClass.newInstance();\n } else {\n Constructor ctr = lookupConstructor(pClass, pArguments);\n return ctr.newInstance(pArguments);\n }\n } else {\n throw new IllegalArgumentException(\"Given class must not be null\");\n }\n } catch (InstantiationException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n }\n }\n\n /**\n * Apply a method to a given object with optional arguments. The method is looked up the whole class\n * hierarchy.\n *\n * @param pObject object on which to apply the method\n * @param pMethod the method name\n * @param pArgs optional arguments\n * @return return value (if any)\n */\n public static Object applyMethod(Object pObject, String pMethod, Object... pArgs) {\n Class clazz = pObject.getClass();\n try {\n Method method = extractMethod(pMethod, clazz, pArgs);\n return method.invoke(pObject, pArgs);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n }\n }\n\n /**\n * Get all resources from the classpath which are specified by the given path.\n *\n * @param pResource resource specification to use for lookup\n * @return the list or URLs to loookup\n */\n public static Set getResources(String pResource) throws IOException {\n List clls = findClassLoaders();\n if (clls.size() != 0) {\n Set ret = new HashSet();\n for (ClassLoader cll : clls) {\n Enumeration urlEnum = cll.getResources(pResource);\n ret.addAll(extractUrlAsStringsFromEnumeration(urlEnum));\n }\n return ret;\n } else {\n return extractUrlAsStringsFromEnumeration(ClassLoader.getSystemResources(pResource));\n }\n }\n\n private static Set extractUrlAsStringsFromEnumeration(Enumeration urlEnum) {\n Set ret = new HashSet();\n while (urlEnum.hasMoreElements()) {\n ret.add(urlEnum.nextElement().toExternalForm());\n }\n return ret;\n }\n\n // Lookup appropriate constructor\n private static Constructor lookupConstructor(Class clazz, Object[] pArguments) throws NoSuchMethodException {\n Class[] argTypes = extractArgumentTypes(pArguments);\n return clazz.getConstructor(argTypes);\n }\n\n private static Method extractMethod(String pMethod, Class clazz, Object[] pArgs) throws NoSuchMethodException {\n for (Method method : clazz.getMethods()) {\n if (!method.getName().equals(pMethod)) {\n continue;\n }\n Class[] parameters = method.getParameterTypes();\n if (parametersMatch(parameters, pArgs)) {\n return method;\n }\n }\n throw new NoSuchMethodException(\"No \" + pMethod + \" on \" + clazz + \" with \" + pArgs.length + \" arguments found \");\n }\n\n ", "post_mask_code": "{\n Class[] argTypes = new Class[pArguments.length];\n int i = 0;\n for (Object arg : pArguments) {\n argTypes[i++] = arg.getClass();\n }\n return argTypes;\n }\n\n private static boolean parametersMatch(Class[] parameters, Object[] pArgs) {\n if (parameters.length != pArgs.length) {\n return false;\n }\n for (int i = 0; i < parameters.length; i++) {\n if (pArgs[i] == null) {\n continue;\n }\n Class argClass = pArgs[i].getClass();\n Class paramClass = parameters[i];\n if (!paramClass.isAssignableFrom(argClass)) {\n if (checkForPrimitive(argClass, paramClass)) {\n continue;\n }\n return false;\n }\n }\n return true;\n }\n\n private static boolean checkForPrimitive(Class argClass, Class paramClass) {\n return paramClass.isPrimitive() && PRIMITIVE_TO_OBJECT_MAP.get(paramClass.getName()) != null;\n }\n\n private static final Map PRIMITIVE_TO_OBJECT_MAP = new HashMap();\n\n static {\n PRIMITIVE_TO_OBJECT_MAP.put(\"int\", Integer.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"long\", Long.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"double\", Double.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"float\", Float.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"bool\", Boolean.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"char\", Character.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"byte\", Byte.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"void\", Void.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"short\", Short.TYPE);\n }\n}\n"} {"task_id": "Java_3111", "language": "Java", "task_type": "method_body", "source_file": "java/github/rhuss/jolokia/agent/core/src/main/java/org/jolokia/util/ClassUtil.java", "mask_start_position": 10163, "mask_end_position": 10272, "canonical_solution": "{\n return paramClass.isPrimitive() && PRIMITIVE_TO_OBJECT_MAP.get(paramClass.getName()) != null;\n }", "pre_mask_code": "package org.jolokia.util;\n\nimport java.io.*;\nimport java.lang.reflect.*;\nimport java.net.URL;\nimport java.util.*;\n\n/**\n * Utility for class lookup.\n *\n * @author roland\n * @since 19.04.11\n */\npublic final class ClassUtil {\n\n private ClassUtil() {\n }\n\n /**\n * Lookup a class. See {@link ClassUtil#classForName(String, boolean,ClassLoader[])} for details. The class\n * gets initialized during lookup.\n *\n * @param pClassName name to lookup.\n * @return the class found or null if no class could be found.\n */\n public static Class classForName(String pClassName, ClassLoader... pClassLoaders) {\n return classForName(pClassName, true, pClassLoaders);\n }\n\n /**\n * Load a certain class. Several class loader are tried: Fires the current thread's context\n * class loader, then its parents. If this doesn't work, the class loader which\n * loaded this class is used (and its parents)\n *\n * @param pClassName class name to load\n * @param pInitialize whether the class must be initialized\n * @param pClassLoaders optional class loaders which are tried as well\n * @return the class class found or null if no class could be loaded\n */\n public static Class classForName(String pClassName, boolean pInitialize, ClassLoader... pClassLoaders) {\n Set tried = new HashSet();\n for (ClassLoader loader : findClassLoaders(pClassLoaders)) {\n // Go up the classloader stack to eventually find the server class. Sometimes the WebAppClassLoader\n // hide the server classes loaded by the parent class loader.\n while (loader != null) {\n try {\n if (!tried.contains(loader)) {\n return (Class) Class.forName(pClassName, pInitialize, loader);\n }\n } catch (ClassNotFoundException ignored) {\n }\n tried.add(loader);\n loader = loader.getParent();\n }\n }\n return null;\n }\n\n private static List findClassLoaders(ClassLoader... pClassLoaders) {\n List classLoadersToTry = new ArrayList(Arrays.asList(pClassLoaders));\n classLoadersToTry.add(Thread.currentThread().getContextClassLoader());\n classLoadersToTry.add(ClassUtil.class.getClassLoader());\n List ret = new ArrayList();\n Set visited = new HashSet();\n for (ClassLoader cll : classLoadersToTry) {\n if (cll != null && !visited.contains(cll)) {\n ret.add(cll);\n visited.add(cll);\n }\n }\n return ret;\n }\n\n /**\n * Get the given path as an input stream or return null if not found\n *\n * @param pPath path to lookup\n * @return input stream or null if not found.\n */\n public static InputStream getResourceAsStream(String pPath) {\n for (ClassLoader loader : new ClassLoader[] { Thread.currentThread().getContextClassLoader(), ClassUtil.class.getClassLoader() }) {\n if (loader != null) {\n InputStream is = loader.getResourceAsStream(pPath);\n if (is != null) {\n return is;\n }\n }\n }\n return null;\n }\n\n /**\n * Check for the existence of a given class\n *\n * @param pClassName class name to check\n * @return true if the class could be loaded by the thread's conext class loader, false otherwise\n */\n public static boolean checkForClass(String pClassName) {\n return ClassUtil.classForName(pClassName, false) != null;\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor. The context class loader is used\n * to lookup the class\n *\n * @param pClassName name of class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(String pClassName, Object... pArguments) {\n Class clazz = classForName(pClassName);\n if (clazz == null) {\n throw new IllegalArgumentException(\"Cannot find \" + pClassName);\n }\n return newInstance(clazz, pArguments);\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor\n *\n * @param pClass class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(Class pClass, Object... pArguments) {\n try {\n if (pClass != null) {\n if (pArguments.length == 0) {\n return pClass.newInstance();\n } else {\n Constructor ctr = lookupConstructor(pClass, pArguments);\n return ctr.newInstance(pArguments);\n }\n } else {\n throw new IllegalArgumentException(\"Given class must not be null\");\n }\n } catch (InstantiationException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n }\n }\n\n /**\n * Apply a method to a given object with optional arguments. The method is looked up the whole class\n * hierarchy.\n *\n * @param pObject object on which to apply the method\n * @param pMethod the method name\n * @param pArgs optional arguments\n * @return return value (if any)\n */\n public static Object applyMethod(Object pObject, String pMethod, Object... pArgs) {\n Class clazz = pObject.getClass();\n try {\n Method method = extractMethod(pMethod, clazz, pArgs);\n return method.invoke(pObject, pArgs);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n }\n }\n\n /**\n * Get all resources from the classpath which are specified by the given path.\n *\n * @param pResource resource specification to use for lookup\n * @return the list or URLs to loookup\n */\n public static Set getResources(String pResource) throws IOException {\n List clls = findClassLoaders();\n if (clls.size() != 0) {\n Set ret = new HashSet();\n for (ClassLoader cll : clls) {\n Enumeration urlEnum = cll.getResources(pResource);\n ret.addAll(extractUrlAsStringsFromEnumeration(urlEnum));\n }\n return ret;\n } else {\n return extractUrlAsStringsFromEnumeration(ClassLoader.getSystemResources(pResource));\n }\n }\n\n private static Set extractUrlAsStringsFromEnumeration(Enumeration urlEnum) {\n Set ret = new HashSet();\n while (urlEnum.hasMoreElements()) {\n ret.add(urlEnum.nextElement().toExternalForm());\n }\n return ret;\n }\n\n // Lookup appropriate constructor\n private static Constructor lookupConstructor(Class clazz, Object[] pArguments) throws NoSuchMethodException {\n Class[] argTypes = extractArgumentTypes(pArguments);\n return clazz.getConstructor(argTypes);\n }\n\n private static Method extractMethod(String pMethod, Class clazz, Object[] pArgs) throws NoSuchMethodException {\n for (Method method : clazz.getMethods()) {\n if (!method.getName().equals(pMethod)) {\n continue;\n }\n Class[] parameters = method.getParameterTypes();\n if (parametersMatch(parameters, pArgs)) {\n return method;\n }\n }\n throw new NoSuchMethodException(\"No \" + pMethod + \" on \" + clazz + \" with \" + pArgs.length + \" arguments found \");\n }\n\n private static Class[] extractArgumentTypes(Object[] pArguments) {\n Class[] argTypes = new Class[pArguments.length];\n int i = 0;\n for (Object arg : pArguments) {\n argTypes[i++] = arg.getClass();\n }\n return argTypes;\n }\n\n private static boolean parametersMatch(Class[] parameters, Object[] pArgs) {\n if (parameters.length != pArgs.length) {\n return false;\n }\n for (int i = 0; i < parameters.length; i++) {\n if (pArgs[i] == null) {\n continue;\n }\n Class argClass = pArgs[i].getClass();\n Class paramClass = parameters[i];\n if (!paramClass.isAssignableFrom(argClass)) {\n if (checkForPrimitive(argClass, paramClass)) {\n continue;\n }\n return false;\n }\n }\n return true;\n }\n\n private static boolean checkForPrimitive(Class argClass, Class paramClass) ", "post_mask_code": "\n\n private static final Map PRIMITIVE_TO_OBJECT_MAP = new HashMap();\n\n static {\n PRIMITIVE_TO_OBJECT_MAP.put(\"int\", Integer.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"long\", Long.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"double\", Double.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"float\", Float.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"bool\", Boolean.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"char\", Character.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"byte\", Byte.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"void\", Void.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"short\", Short.TYPE);\n }\n}\n"} {"task_id": "Java_3112", "language": "Java", "task_type": "single_line", "source_file": "java/github/rhuss/jolokia/agent/core/src/main/java/org/jolokia/util/ClassUtil.java", "mask_start_position": 7556, "mask_end_position": 7599, "canonical_solution": "ist clls = findClassLoaders();", "pre_mask_code": "package org.jolokia.util;\n\nimport java.io.*;\nimport java.lang.reflect.*;\nimport java.net.URL;\nimport java.util.*;\n\n/**\n * Utility for class lookup.\n *\n * @author roland\n * @since 19.04.11\n */\npublic final class ClassUtil {\n\n private ClassUtil() {\n }\n\n /**\n * Lookup a class. See {@link ClassUtil#classForName(String, boolean,ClassLoader[])} for details. The class\n * gets initialized during lookup.\n *\n * @param pClassName name to lookup.\n * @return the class found or null if no class could be found.\n */\n public static Class classForName(String pClassName, ClassLoader... pClassLoaders) {\n return classForName(pClassName, true, pClassLoaders);\n }\n\n /**\n * Load a certain class. Several class loader are tried: Fires the current thread's context\n * class loader, then its parents. If this doesn't work, the class loader which\n * loaded this class is used (and its parents)\n *\n * @param pClassName class name to load\n * @param pInitialize whether the class must be initialized\n * @param pClassLoaders optional class loaders which are tried as well\n * @return the class class found or null if no class could be loaded\n */\n public static Class classForName(String pClassName, boolean pInitialize, ClassLoader... pClassLoaders) {\n Set tried = new HashSet();\n for (ClassLoader loader : findClassLoaders(pClassLoaders)) {\n // Go up the classloader stack to eventually find the server class. Sometimes the WebAppClassLoader\n // hide the server classes loaded by the parent class loader.\n while (loader != null) {\n try {\n if (!tried.contains(loader)) {\n return (Class) Class.forName(pClassName, pInitialize, loader);\n }\n } catch (ClassNotFoundException ignored) {\n }\n tried.add(loader);\n loader = loader.getParent();\n }\n }\n return null;\n }\n\n private static List findClassLoaders(ClassLoader... pClassLoaders) {\n List classLoadersToTry = new ArrayList(Arrays.asList(pClassLoaders));\n classLoadersToTry.add(Thread.currentThread().getContextClassLoader());\n classLoadersToTry.add(ClassUtil.class.getClassLoader());\n List ret = new ArrayList();\n Set visited = new HashSet();\n for (ClassLoader cll : classLoadersToTry) {\n if (cll != null && !visited.contains(cll)) {\n ret.add(cll);\n visited.add(cll);\n }\n }\n return ret;\n }\n\n /**\n * Get the given path as an input stream or return null if not found\n *\n * @param pPath path to lookup\n * @return input stream or null if not found.\n */\n public static InputStream getResourceAsStream(String pPath) {\n for (ClassLoader loader : new ClassLoader[] { Thread.currentThread().getContextClassLoader(), ClassUtil.class.getClassLoader() }) {\n if (loader != null) {\n InputStream is = loader.getResourceAsStream(pPath);\n if (is != null) {\n return is;\n }\n }\n }\n return null;\n }\n\n /**\n * Check for the existence of a given class\n *\n * @param pClassName class name to check\n * @return true if the class could be loaded by the thread's conext class loader, false otherwise\n */\n public static boolean checkForClass(String pClassName) {\n return ClassUtil.classForName(pClassName, false) != null;\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor. The context class loader is used\n * to lookup the class\n *\n * @param pClassName name of class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(String pClassName, Object... pArguments) {\n Class clazz = classForName(pClassName);\n if (clazz == null) {\n throw new IllegalArgumentException(\"Cannot find \" + pClassName);\n }\n return newInstance(clazz, pArguments);\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor\n *\n * @param pClass class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(Class pClass, Object... pArguments) {\n try {\n if (pClass != null) {\n if (pArguments.length == 0) {\n return pClass.newInstance();\n } else {\n Constructor ctr = lookupConstructor(pClass, pArguments);\n return ctr.newInstance(pArguments);\n }\n } else {\n throw new IllegalArgumentException(\"Given class must not be null\");\n }\n } catch (InstantiationException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n }\n }\n\n /**\n * Apply a method to a given object with optional arguments. The method is looked up the whole class\n * hierarchy.\n *\n * @param pObject object on which to apply the method\n * @param pMethod the method name\n * @param pArgs optional arguments\n * @return return value (if any)\n */\n public static Object applyMethod(Object pObject, String pMethod, Object... pArgs) {\n Class clazz = pObject.getClass();\n try {\n Method method = extractMethod(pMethod, clazz, pArgs);\n return method.invoke(pObject, pArgs);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n }\n }\n\n /**\n * Get all resources from the classpath which are specified by the given path.\n *\n * @param pResource resource specification to use for lookup\n * @return the list or URLs to loookup\n */\n public static Set getResources(String pResource) throws IOException {\n L", "post_mask_code": "\n if (clls.size() != 0) {\n Set ret = new HashSet();\n for (ClassLoader cll : clls) {\n Enumeration urlEnum = cll.getResources(pResource);\n ret.addAll(extractUrlAsStringsFromEnumeration(urlEnum));\n }\n return ret;\n } else {\n return extractUrlAsStringsFromEnumeration(ClassLoader.getSystemResources(pResource));\n }\n }\n\n private static Set extractUrlAsStringsFromEnumeration(Enumeration urlEnum) {\n Set ret = new HashSet();\n while (urlEnum.hasMoreElements()) {\n ret.add(urlEnum.nextElement().toExternalForm());\n }\n return ret;\n }\n\n // Lookup appropriate constructor\n private static Constructor lookupConstructor(Class clazz, Object[] pArguments) throws NoSuchMethodException {\n Class[] argTypes = extractArgumentTypes(pArguments);\n return clazz.getConstructor(argTypes);\n }\n\n private static Method extractMethod(String pMethod, Class clazz, Object[] pArgs) throws NoSuchMethodException {\n for (Method method : clazz.getMethods()) {\n if (!method.getName().equals(pMethod)) {\n continue;\n }\n Class[] parameters = method.getParameterTypes();\n if (parametersMatch(parameters, pArgs)) {\n return method;\n }\n }\n throw new NoSuchMethodException(\"No \" + pMethod + \" on \" + clazz + \" with \" + pArgs.length + \" arguments found \");\n }\n\n private static Class[] extractArgumentTypes(Object[] pArguments) {\n Class[] argTypes = new Class[pArguments.length];\n int i = 0;\n for (Object arg : pArguments) {\n argTypes[i++] = arg.getClass();\n }\n return argTypes;\n }\n\n private static boolean parametersMatch(Class[] parameters, Object[] pArgs) {\n if (parameters.length != pArgs.length) {\n return false;\n }\n for (int i = 0; i < parameters.length; i++) {\n if (pArgs[i] == null) {\n continue;\n }\n Class argClass = pArgs[i].getClass();\n Class paramClass = parameters[i];\n if (!paramClass.isAssignableFrom(argClass)) {\n if (checkForPrimitive(argClass, paramClass)) {\n continue;\n }\n return false;\n }\n }\n return true;\n }\n\n private static boolean checkForPrimitive(Class argClass, Class paramClass) {\n return paramClass.isPrimitive() && PRIMITIVE_TO_OBJECT_MAP.get(paramClass.getName()) != null;\n }\n\n private static final Map PRIMITIVE_TO_OBJECT_MAP = new HashMap();\n\n static {\n PRIMITIVE_TO_OBJECT_MAP.put(\"int\", Integer.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"long\", Long.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"double\", Double.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"float\", Float.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"bool\", Boolean.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"char\", Character.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"byte\", Byte.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"void\", Void.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"short\", Short.TYPE);\n }\n}\n"} {"task_id": "Java_3113", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/rhuss/jolokia/agent/core/src/main/java/org/jolokia/util/ClassUtil.java", "mask_start_position": 2957, "mask_end_position": 3394, "canonical_solution": "public static InputStream getResourceAsStream(String pPath) {\n for (ClassLoader loader : new ClassLoader[] { Thread.currentThread().getContextClassLoader(), ClassUtil.class.getClassLoader() }) {\n if (loader != null) {\n InputStream is = loader.getResourceAsStream(pPath);\n if (is != null) {\n return is;\n }\n }\n }\n return null;\n }", "pre_mask_code": "package org.jolokia.util;\n\nimport java.io.*;\nimport java.lang.reflect.*;\nimport java.net.URL;\nimport java.util.*;\n\n/**\n * Utility for class lookup.\n *\n * @author roland\n * @since 19.04.11\n */\npublic final class ClassUtil {\n\n private ClassUtil() {\n }\n\n /**\n * Lookup a class. See {@link ClassUtil#classForName(String, boolean,ClassLoader[])} for details. The class\n * gets initialized during lookup.\n *\n * @param pClassName name to lookup.\n * @return the class found or null if no class could be found.\n */\n public static Class classForName(String pClassName, ClassLoader... pClassLoaders) {\n return classForName(pClassName, true, pClassLoaders);\n }\n\n /**\n * Load a certain class. Several class loader are tried: Fires the current thread's context\n * class loader, then its parents. If this doesn't work, the class loader which\n * loaded this class is used (and its parents)\n *\n * @param pClassName class name to load\n * @param pInitialize whether the class must be initialized\n * @param pClassLoaders optional class loaders which are tried as well\n * @return the class class found or null if no class could be loaded\n */\n public static Class classForName(String pClassName, boolean pInitialize, ClassLoader... pClassLoaders) {\n Set tried = new HashSet();\n for (ClassLoader loader : findClassLoaders(pClassLoaders)) {\n // Go up the classloader stack to eventually find the server class. Sometimes the WebAppClassLoader\n // hide the server classes loaded by the parent class loader.\n while (loader != null) {\n try {\n if (!tried.contains(loader)) {\n return (Class) Class.forName(pClassName, pInitialize, loader);\n }\n } catch (ClassNotFoundException ignored) {\n }\n tried.add(loader);\n loader = loader.getParent();\n }\n }\n return null;\n }\n\n private static List findClassLoaders(ClassLoader... pClassLoaders) {\n List classLoadersToTry = new ArrayList(Arrays.asList(pClassLoaders));\n classLoadersToTry.add(Thread.currentThread().getContextClassLoader());\n classLoadersToTry.add(ClassUtil.class.getClassLoader());\n List ret = new ArrayList();\n Set visited = new HashSet();\n for (ClassLoader cll : classLoadersToTry) {\n if (cll != null && !visited.contains(cll)) {\n ret.add(cll);\n visited.add(cll);\n }\n }\n return ret;\n }\n\n /**\n * Get the given path as an input stream or return null if not found\n *\n * @param pPath path to lookup\n * @return input stream or null if not found.\n */\n ", "post_mask_code": "\n\n /**\n * Check for the existence of a given class\n *\n * @param pClassName class name to check\n * @return true if the class could be loaded by the thread's conext class loader, false otherwise\n */\n public static boolean checkForClass(String pClassName) {\n return ClassUtil.classForName(pClassName, false) != null;\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor. The context class loader is used\n * to lookup the class\n *\n * @param pClassName name of class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(String pClassName, Object... pArguments) {\n Class clazz = classForName(pClassName);\n if (clazz == null) {\n throw new IllegalArgumentException(\"Cannot find \" + pClassName);\n }\n return newInstance(clazz, pArguments);\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor\n *\n * @param pClass class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(Class pClass, Object... pArguments) {\n try {\n if (pClass != null) {\n if (pArguments.length == 0) {\n return pClass.newInstance();\n } else {\n Constructor ctr = lookupConstructor(pClass, pArguments);\n return ctr.newInstance(pArguments);\n }\n } else {\n throw new IllegalArgumentException(\"Given class must not be null\");\n }\n } catch (InstantiationException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n }\n }\n\n /**\n * Apply a method to a given object with optional arguments. The method is looked up the whole class\n * hierarchy.\n *\n * @param pObject object on which to apply the method\n * @param pMethod the method name\n * @param pArgs optional arguments\n * @return return value (if any)\n */\n public static Object applyMethod(Object pObject, String pMethod, Object... pArgs) {\n Class clazz = pObject.getClass();\n try {\n Method method = extractMethod(pMethod, clazz, pArgs);\n return method.invoke(pObject, pArgs);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n }\n }\n\n /**\n * Get all resources from the classpath which are specified by the given path.\n *\n * @param pResource resource specification to use for lookup\n * @return the list or URLs to loookup\n */\n public static Set getResources(String pResource) throws IOException {\n List clls = findClassLoaders();\n if (clls.size() != 0) {\n Set ret = new HashSet();\n for (ClassLoader cll : clls) {\n Enumeration urlEnum = cll.getResources(pResource);\n ret.addAll(extractUrlAsStringsFromEnumeration(urlEnum));\n }\n return ret;\n } else {\n return extractUrlAsStringsFromEnumeration(ClassLoader.getSystemResources(pResource));\n }\n }\n\n private static Set extractUrlAsStringsFromEnumeration(Enumeration urlEnum) {\n Set ret = new HashSet();\n while (urlEnum.hasMoreElements()) {\n ret.add(urlEnum.nextElement().toExternalForm());\n }\n return ret;\n }\n\n // Lookup appropriate constructor\n private static Constructor lookupConstructor(Class clazz, Object[] pArguments) throws NoSuchMethodException {\n Class[] argTypes = extractArgumentTypes(pArguments);\n return clazz.getConstructor(argTypes);\n }\n\n private static Method extractMethod(String pMethod, Class clazz, Object[] pArgs) throws NoSuchMethodException {\n for (Method method : clazz.getMethods()) {\n if (!method.getName().equals(pMethod)) {\n continue;\n }\n Class[] parameters = method.getParameterTypes();\n if (parametersMatch(parameters, pArgs)) {\n return method;\n }\n }\n throw new NoSuchMethodException(\"No \" + pMethod + \" on \" + clazz + \" with \" + pArgs.length + \" arguments found \");\n }\n\n private static Class[] extractArgumentTypes(Object[] pArguments) {\n Class[] argTypes = new Class[pArguments.length];\n int i = 0;\n for (Object arg : pArguments) {\n argTypes[i++] = arg.getClass();\n }\n return argTypes;\n }\n\n private static boolean parametersMatch(Class[] parameters, Object[] pArgs) {\n if (parameters.length != pArgs.length) {\n return false;\n }\n for (int i = 0; i < parameters.length; i++) {\n if (pArgs[i] == null) {\n continue;\n }\n Class argClass = pArgs[i].getClass();\n Class paramClass = parameters[i];\n if (!paramClass.isAssignableFrom(argClass)) {\n if (checkForPrimitive(argClass, paramClass)) {\n continue;\n }\n return false;\n }\n }\n return true;\n }\n\n private static boolean checkForPrimitive(Class argClass, Class paramClass) {\n return paramClass.isPrimitive() && PRIMITIVE_TO_OBJECT_MAP.get(paramClass.getName()) != null;\n }\n\n private static final Map PRIMITIVE_TO_OBJECT_MAP = new HashMap();\n\n static {\n PRIMITIVE_TO_OBJECT_MAP.put(\"int\", Integer.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"long\", Long.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"double\", Double.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"float\", Float.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"bool\", Boolean.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"char\", Character.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"byte\", Byte.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"void\", Void.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"short\", Short.TYPE);\n }\n}\n"} {"task_id": "Java_3114", "language": "Java", "task_type": "for_statement", "source_file": "java/github/rhuss/jolokia/agent/core/src/main/java/org/jolokia/util/ClassUtil.java", "mask_start_position": 9615, "mask_end_position": 10055, "canonical_solution": "for (int i = 0; i < parameters.length; i++) {\n if (pArgs[i] == null) {\n continue;\n }\n Class argClass = pArgs[i].getClass();\n Class paramClass = parameters[i];\n if (!paramClass.isAssignableFrom(argClass)) {\n if (checkForPrimitive(argClass, paramClass)) {\n continue;\n }\n return false;\n }\n }", "pre_mask_code": "package org.jolokia.util;\n\nimport java.io.*;\nimport java.lang.reflect.*;\nimport java.net.URL;\nimport java.util.*;\n\n/**\n * Utility for class lookup.\n *\n * @author roland\n * @since 19.04.11\n */\npublic final class ClassUtil {\n\n private ClassUtil() {\n }\n\n /**\n * Lookup a class. See {@link ClassUtil#classForName(String, boolean,ClassLoader[])} for details. The class\n * gets initialized during lookup.\n *\n * @param pClassName name to lookup.\n * @return the class found or null if no class could be found.\n */\n public static Class classForName(String pClassName, ClassLoader... pClassLoaders) {\n return classForName(pClassName, true, pClassLoaders);\n }\n\n /**\n * Load a certain class. Several class loader are tried: Fires the current thread's context\n * class loader, then its parents. If this doesn't work, the class loader which\n * loaded this class is used (and its parents)\n *\n * @param pClassName class name to load\n * @param pInitialize whether the class must be initialized\n * @param pClassLoaders optional class loaders which are tried as well\n * @return the class class found or null if no class could be loaded\n */\n public static Class classForName(String pClassName, boolean pInitialize, ClassLoader... pClassLoaders) {\n Set tried = new HashSet();\n for (ClassLoader loader : findClassLoaders(pClassLoaders)) {\n // Go up the classloader stack to eventually find the server class. Sometimes the WebAppClassLoader\n // hide the server classes loaded by the parent class loader.\n while (loader != null) {\n try {\n if (!tried.contains(loader)) {\n return (Class) Class.forName(pClassName, pInitialize, loader);\n }\n } catch (ClassNotFoundException ignored) {\n }\n tried.add(loader);\n loader = loader.getParent();\n }\n }\n return null;\n }\n\n private static List findClassLoaders(ClassLoader... pClassLoaders) {\n List classLoadersToTry = new ArrayList(Arrays.asList(pClassLoaders));\n classLoadersToTry.add(Thread.currentThread().getContextClassLoader());\n classLoadersToTry.add(ClassUtil.class.getClassLoader());\n List ret = new ArrayList();\n Set visited = new HashSet();\n for (ClassLoader cll : classLoadersToTry) {\n if (cll != null && !visited.contains(cll)) {\n ret.add(cll);\n visited.add(cll);\n }\n }\n return ret;\n }\n\n /**\n * Get the given path as an input stream or return null if not found\n *\n * @param pPath path to lookup\n * @return input stream or null if not found.\n */\n public static InputStream getResourceAsStream(String pPath) {\n for (ClassLoader loader : new ClassLoader[] { Thread.currentThread().getContextClassLoader(), ClassUtil.class.getClassLoader() }) {\n if (loader != null) {\n InputStream is = loader.getResourceAsStream(pPath);\n if (is != null) {\n return is;\n }\n }\n }\n return null;\n }\n\n /**\n * Check for the existence of a given class\n *\n * @param pClassName class name to check\n * @return true if the class could be loaded by the thread's conext class loader, false otherwise\n */\n public static boolean checkForClass(String pClassName) {\n return ClassUtil.classForName(pClassName, false) != null;\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor. The context class loader is used\n * to lookup the class\n *\n * @param pClassName name of class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(String pClassName, Object... pArguments) {\n Class clazz = classForName(pClassName);\n if (clazz == null) {\n throw new IllegalArgumentException(\"Cannot find \" + pClassName);\n }\n return newInstance(clazz, pArguments);\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor\n *\n * @param pClass class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(Class pClass, Object... pArguments) {\n try {\n if (pClass != null) {\n if (pArguments.length == 0) {\n return pClass.newInstance();\n } else {\n Constructor ctr = lookupConstructor(pClass, pArguments);\n return ctr.newInstance(pArguments);\n }\n } else {\n throw new IllegalArgumentException(\"Given class must not be null\");\n }\n } catch (InstantiationException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n }\n }\n\n /**\n * Apply a method to a given object with optional arguments. The method is looked up the whole class\n * hierarchy.\n *\n * @param pObject object on which to apply the method\n * @param pMethod the method name\n * @param pArgs optional arguments\n * @return return value (if any)\n */\n public static Object applyMethod(Object pObject, String pMethod, Object... pArgs) {\n Class clazz = pObject.getClass();\n try {\n Method method = extractMethod(pMethod, clazz, pArgs);\n return method.invoke(pObject, pArgs);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n }\n }\n\n /**\n * Get all resources from the classpath which are specified by the given path.\n *\n * @param pResource resource specification to use for lookup\n * @return the list or URLs to loookup\n */\n public static Set getResources(String pResource) throws IOException {\n List clls = findClassLoaders();\n if (clls.size() != 0) {\n Set ret = new HashSet();\n for (ClassLoader cll : clls) {\n Enumeration urlEnum = cll.getResources(pResource);\n ret.addAll(extractUrlAsStringsFromEnumeration(urlEnum));\n }\n return ret;\n } else {\n return extractUrlAsStringsFromEnumeration(ClassLoader.getSystemResources(pResource));\n }\n }\n\n private static Set extractUrlAsStringsFromEnumeration(Enumeration urlEnum) {\n Set ret = new HashSet();\n while (urlEnum.hasMoreElements()) {\n ret.add(urlEnum.nextElement().toExternalForm());\n }\n return ret;\n }\n\n // Lookup appropriate constructor\n private static Constructor lookupConstructor(Class clazz, Object[] pArguments) throws NoSuchMethodException {\n Class[] argTypes = extractArgumentTypes(pArguments);\n return clazz.getConstructor(argTypes);\n }\n\n private static Method extractMethod(String pMethod, Class clazz, Object[] pArgs) throws NoSuchMethodException {\n for (Method method : clazz.getMethods()) {\n if (!method.getName().equals(pMethod)) {\n continue;\n }\n Class[] parameters = method.getParameterTypes();\n if (parametersMatch(parameters, pArgs)) {\n return method;\n }\n }\n throw new NoSuchMethodException(\"No \" + pMethod + \" on \" + clazz + \" with \" + pArgs.length + \" arguments found \");\n }\n\n private static Class[] extractArgumentTypes(Object[] pArguments) {\n Class[] argTypes = new Class[pArguments.length];\n int i = 0;\n for (Object arg : pArguments) {\n argTypes[i++] = arg.getClass();\n }\n return argTypes;\n }\n\n private static boolean parametersMatch(Class[] parameters, Object[] pArgs) {\n if (parameters.length != pArgs.length) {\n return false;\n }\n ", "post_mask_code": "\n return true;\n }\n\n private static boolean checkForPrimitive(Class argClass, Class paramClass) {\n return paramClass.isPrimitive() && PRIMITIVE_TO_OBJECT_MAP.get(paramClass.getName()) != null;\n }\n\n private static final Map PRIMITIVE_TO_OBJECT_MAP = new HashMap();\n\n static {\n PRIMITIVE_TO_OBJECT_MAP.put(\"int\", Integer.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"long\", Long.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"double\", Double.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"float\", Float.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"bool\", Boolean.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"char\", Character.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"byte\", Byte.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"void\", Void.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"short\", Short.TYPE);\n }\n}\n"} {"task_id": "Java_3115", "language": "Java", "task_type": "while_statement", "source_file": "java/github/rhuss/jolokia/agent/core/src/main/java/org/jolokia/util/ClassUtil.java", "mask_start_position": 1657, "mask_end_position": 2037, "canonical_solution": "while (loader != null) {\n try {\n if (!tried.contains(loader)) {\n return (Class) Class.forName(pClassName, pInitialize, loader);\n }\n } catch (ClassNotFoundException ignored) {\n }\n tried.add(loader);\n loader = loader.getParent();\n }", "pre_mask_code": "package org.jolokia.util;\n\nimport java.io.*;\nimport java.lang.reflect.*;\nimport java.net.URL;\nimport java.util.*;\n\n/**\n * Utility for class lookup.\n *\n * @author roland\n * @since 19.04.11\n */\npublic final class ClassUtil {\n\n private ClassUtil() {\n }\n\n /**\n * Lookup a class. See {@link ClassUtil#classForName(String, boolean,ClassLoader[])} for details. The class\n * gets initialized during lookup.\n *\n * @param pClassName name to lookup.\n * @return the class found or null if no class could be found.\n */\n public static Class classForName(String pClassName, ClassLoader... pClassLoaders) {\n return classForName(pClassName, true, pClassLoaders);\n }\n\n /**\n * Load a certain class. Several class loader are tried: Fires the current thread's context\n * class loader, then its parents. If this doesn't work, the class loader which\n * loaded this class is used (and its parents)\n *\n * @param pClassName class name to load\n * @param pInitialize whether the class must be initialized\n * @param pClassLoaders optional class loaders which are tried as well\n * @return the class class found or null if no class could be loaded\n */\n public static Class classForName(String pClassName, boolean pInitialize, ClassLoader... pClassLoaders) {\n Set tried = new HashSet();\n for (ClassLoader loader : findClassLoaders(pClassLoaders)) {\n // Go up the classloader stack to eventually find the server class. Sometimes the WebAppClassLoader\n // hide the server classes loaded by the parent class loader.\n ", "post_mask_code": "\n }\n return null;\n }\n\n private static List findClassLoaders(ClassLoader... pClassLoaders) {\n List classLoadersToTry = new ArrayList(Arrays.asList(pClassLoaders));\n classLoadersToTry.add(Thread.currentThread().getContextClassLoader());\n classLoadersToTry.add(ClassUtil.class.getClassLoader());\n List ret = new ArrayList();\n Set visited = new HashSet();\n for (ClassLoader cll : classLoadersToTry) {\n if (cll != null && !visited.contains(cll)) {\n ret.add(cll);\n visited.add(cll);\n }\n }\n return ret;\n }\n\n /**\n * Get the given path as an input stream or return null if not found\n *\n * @param pPath path to lookup\n * @return input stream or null if not found.\n */\n public static InputStream getResourceAsStream(String pPath) {\n for (ClassLoader loader : new ClassLoader[] { Thread.currentThread().getContextClassLoader(), ClassUtil.class.getClassLoader() }) {\n if (loader != null) {\n InputStream is = loader.getResourceAsStream(pPath);\n if (is != null) {\n return is;\n }\n }\n }\n return null;\n }\n\n /**\n * Check for the existence of a given class\n *\n * @param pClassName class name to check\n * @return true if the class could be loaded by the thread's conext class loader, false otherwise\n */\n public static boolean checkForClass(String pClassName) {\n return ClassUtil.classForName(pClassName, false) != null;\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor. The context class loader is used\n * to lookup the class\n *\n * @param pClassName name of class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(String pClassName, Object... pArguments) {\n Class clazz = classForName(pClassName);\n if (clazz == null) {\n throw new IllegalArgumentException(\"Cannot find \" + pClassName);\n }\n return newInstance(clazz, pArguments);\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor\n *\n * @param pClass class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(Class pClass, Object... pArguments) {\n try {\n if (pClass != null) {\n if (pArguments.length == 0) {\n return pClass.newInstance();\n } else {\n Constructor ctr = lookupConstructor(pClass, pArguments);\n return ctr.newInstance(pArguments);\n }\n } else {\n throw new IllegalArgumentException(\"Given class must not be null\");\n }\n } catch (InstantiationException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n }\n }\n\n /**\n * Apply a method to a given object with optional arguments. The method is looked up the whole class\n * hierarchy.\n *\n * @param pObject object on which to apply the method\n * @param pMethod the method name\n * @param pArgs optional arguments\n * @return return value (if any)\n */\n public static Object applyMethod(Object pObject, String pMethod, Object... pArgs) {\n Class clazz = pObject.getClass();\n try {\n Method method = extractMethod(pMethod, clazz, pArgs);\n return method.invoke(pObject, pArgs);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n }\n }\n\n /**\n * Get all resources from the classpath which are specified by the given path.\n *\n * @param pResource resource specification to use for lookup\n * @return the list or URLs to loookup\n */\n public static Set getResources(String pResource) throws IOException {\n List clls = findClassLoaders();\n if (clls.size() != 0) {\n Set ret = new HashSet();\n for (ClassLoader cll : clls) {\n Enumeration urlEnum = cll.getResources(pResource);\n ret.addAll(extractUrlAsStringsFromEnumeration(urlEnum));\n }\n return ret;\n } else {\n return extractUrlAsStringsFromEnumeration(ClassLoader.getSystemResources(pResource));\n }\n }\n\n private static Set extractUrlAsStringsFromEnumeration(Enumeration urlEnum) {\n Set ret = new HashSet();\n while (urlEnum.hasMoreElements()) {\n ret.add(urlEnum.nextElement().toExternalForm());\n }\n return ret;\n }\n\n // Lookup appropriate constructor\n private static Constructor lookupConstructor(Class clazz, Object[] pArguments) throws NoSuchMethodException {\n Class[] argTypes = extractArgumentTypes(pArguments);\n return clazz.getConstructor(argTypes);\n }\n\n private static Method extractMethod(String pMethod, Class clazz, Object[] pArgs) throws NoSuchMethodException {\n for (Method method : clazz.getMethods()) {\n if (!method.getName().equals(pMethod)) {\n continue;\n }\n Class[] parameters = method.getParameterTypes();\n if (parametersMatch(parameters, pArgs)) {\n return method;\n }\n }\n throw new NoSuchMethodException(\"No \" + pMethod + \" on \" + clazz + \" with \" + pArgs.length + \" arguments found \");\n }\n\n private static Class[] extractArgumentTypes(Object[] pArguments) {\n Class[] argTypes = new Class[pArguments.length];\n int i = 0;\n for (Object arg : pArguments) {\n argTypes[i++] = arg.getClass();\n }\n return argTypes;\n }\n\n private static boolean parametersMatch(Class[] parameters, Object[] pArgs) {\n if (parameters.length != pArgs.length) {\n return false;\n }\n for (int i = 0; i < parameters.length; i++) {\n if (pArgs[i] == null) {\n continue;\n }\n Class argClass = pArgs[i].getClass();\n Class paramClass = parameters[i];\n if (!paramClass.isAssignableFrom(argClass)) {\n if (checkForPrimitive(argClass, paramClass)) {\n continue;\n }\n return false;\n }\n }\n return true;\n }\n\n private static boolean checkForPrimitive(Class argClass, Class paramClass) {\n return paramClass.isPrimitive() && PRIMITIVE_TO_OBJECT_MAP.get(paramClass.getName()) != null;\n }\n\n private static final Map PRIMITIVE_TO_OBJECT_MAP = new HashMap();\n\n static {\n PRIMITIVE_TO_OBJECT_MAP.put(\"int\", Integer.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"long\", Long.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"double\", Double.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"float\", Float.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"bool\", Boolean.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"char\", Character.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"byte\", Byte.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"void\", Void.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"short\", Short.TYPE);\n }\n}\n"} {"task_id": "Java_3116", "language": "Java", "task_type": "try_statement", "source_file": "java/github/rhuss/jolokia/agent/core/src/main/java/org/jolokia/util/ClassUtil.java", "mask_start_position": 1698, "mask_end_position": 1943, "canonical_solution": "try {\n if (!tried.contains(loader)) {\n return (Class) Class.forName(pClassName, pInitialize, loader);\n }\n } catch (ClassNotFoundException ignored) {\n }", "pre_mask_code": "package org.jolokia.util;\n\nimport java.io.*;\nimport java.lang.reflect.*;\nimport java.net.URL;\nimport java.util.*;\n\n/**\n * Utility for class lookup.\n *\n * @author roland\n * @since 19.04.11\n */\npublic final class ClassUtil {\n\n private ClassUtil() {\n }\n\n /**\n * Lookup a class. See {@link ClassUtil#classForName(String, boolean,ClassLoader[])} for details. The class\n * gets initialized during lookup.\n *\n * @param pClassName name to lookup.\n * @return the class found or null if no class could be found.\n */\n public static Class classForName(String pClassName, ClassLoader... pClassLoaders) {\n return classForName(pClassName, true, pClassLoaders);\n }\n\n /**\n * Load a certain class. Several class loader are tried: Fires the current thread's context\n * class loader, then its parents. If this doesn't work, the class loader which\n * loaded this class is used (and its parents)\n *\n * @param pClassName class name to load\n * @param pInitialize whether the class must be initialized\n * @param pClassLoaders optional class loaders which are tried as well\n * @return the class class found or null if no class could be loaded\n */\n public static Class classForName(String pClassName, boolean pInitialize, ClassLoader... pClassLoaders) {\n Set tried = new HashSet();\n for (ClassLoader loader : findClassLoaders(pClassLoaders)) {\n // Go up the classloader stack to eventually find the server class. Sometimes the WebAppClassLoader\n // hide the server classes loaded by the parent class loader.\n while (loader != null) {\n ", "post_mask_code": "\n tried.add(loader);\n loader = loader.getParent();\n }\n }\n return null;\n }\n\n private static List findClassLoaders(ClassLoader... pClassLoaders) {\n List classLoadersToTry = new ArrayList(Arrays.asList(pClassLoaders));\n classLoadersToTry.add(Thread.currentThread().getContextClassLoader());\n classLoadersToTry.add(ClassUtil.class.getClassLoader());\n List ret = new ArrayList();\n Set visited = new HashSet();\n for (ClassLoader cll : classLoadersToTry) {\n if (cll != null && !visited.contains(cll)) {\n ret.add(cll);\n visited.add(cll);\n }\n }\n return ret;\n }\n\n /**\n * Get the given path as an input stream or return null if not found\n *\n * @param pPath path to lookup\n * @return input stream or null if not found.\n */\n public static InputStream getResourceAsStream(String pPath) {\n for (ClassLoader loader : new ClassLoader[] { Thread.currentThread().getContextClassLoader(), ClassUtil.class.getClassLoader() }) {\n if (loader != null) {\n InputStream is = loader.getResourceAsStream(pPath);\n if (is != null) {\n return is;\n }\n }\n }\n return null;\n }\n\n /**\n * Check for the existence of a given class\n *\n * @param pClassName class name to check\n * @return true if the class could be loaded by the thread's conext class loader, false otherwise\n */\n public static boolean checkForClass(String pClassName) {\n return ClassUtil.classForName(pClassName, false) != null;\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor. The context class loader is used\n * to lookup the class\n *\n * @param pClassName name of class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(String pClassName, Object... pArguments) {\n Class clazz = classForName(pClassName);\n if (clazz == null) {\n throw new IllegalArgumentException(\"Cannot find \" + pClassName);\n }\n return newInstance(clazz, pArguments);\n }\n\n /**\n * Instantiate an instance of the given class with its default constructor\n *\n * @param pClass class to instantiate\n * @param pArguments optional constructor arguments. Works only for objects with the same class as declared in\n * the constructor types (no subclasses)\n * @param type object type\n * @return instantiated object\n * @throws IllegalArgumentException if the class could not be found or instantiated\n */\n public static T newInstance(Class pClass, Object... pArguments) {\n try {\n if (pClass != null) {\n if (pArguments.length == 0) {\n return pClass.newInstance();\n } else {\n Constructor ctr = lookupConstructor(pClass, pArguments);\n return ctr.newInstance(pArguments);\n }\n } else {\n throw new IllegalArgumentException(\"Given class must not be null\");\n }\n } catch (InstantiationException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot instantiate \" + pClass + \": \" + e, e);\n }\n }\n\n /**\n * Apply a method to a given object with optional arguments. The method is looked up the whole class\n * hierarchy.\n *\n * @param pObject object on which to apply the method\n * @param pMethod the method name\n * @param pArgs optional arguments\n * @return return value (if any)\n */\n public static Object applyMethod(Object pObject, String pMethod, Object... pArgs) {\n Class clazz = pObject.getClass();\n try {\n Method method = extractMethod(pMethod, clazz, pArgs);\n return method.invoke(pObject, pArgs);\n } catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (InvocationTargetException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n } catch (IllegalAccessException e) {\n throw new IllegalArgumentException(\"Cannot call method \" + pMethod + \" on \" + pObject + \": \" + e, e);\n }\n }\n\n /**\n * Get all resources from the classpath which are specified by the given path.\n *\n * @param pResource resource specification to use for lookup\n * @return the list or URLs to loookup\n */\n public static Set getResources(String pResource) throws IOException {\n List clls = findClassLoaders();\n if (clls.size() != 0) {\n Set ret = new HashSet();\n for (ClassLoader cll : clls) {\n Enumeration urlEnum = cll.getResources(pResource);\n ret.addAll(extractUrlAsStringsFromEnumeration(urlEnum));\n }\n return ret;\n } else {\n return extractUrlAsStringsFromEnumeration(ClassLoader.getSystemResources(pResource));\n }\n }\n\n private static Set extractUrlAsStringsFromEnumeration(Enumeration urlEnum) {\n Set ret = new HashSet();\n while (urlEnum.hasMoreElements()) {\n ret.add(urlEnum.nextElement().toExternalForm());\n }\n return ret;\n }\n\n // Lookup appropriate constructor\n private static Constructor lookupConstructor(Class clazz, Object[] pArguments) throws NoSuchMethodException {\n Class[] argTypes = extractArgumentTypes(pArguments);\n return clazz.getConstructor(argTypes);\n }\n\n private static Method extractMethod(String pMethod, Class clazz, Object[] pArgs) throws NoSuchMethodException {\n for (Method method : clazz.getMethods()) {\n if (!method.getName().equals(pMethod)) {\n continue;\n }\n Class[] parameters = method.getParameterTypes();\n if (parametersMatch(parameters, pArgs)) {\n return method;\n }\n }\n throw new NoSuchMethodException(\"No \" + pMethod + \" on \" + clazz + \" with \" + pArgs.length + \" arguments found \");\n }\n\n private static Class[] extractArgumentTypes(Object[] pArguments) {\n Class[] argTypes = new Class[pArguments.length];\n int i = 0;\n for (Object arg : pArguments) {\n argTypes[i++] = arg.getClass();\n }\n return argTypes;\n }\n\n private static boolean parametersMatch(Class[] parameters, Object[] pArgs) {\n if (parameters.length != pArgs.length) {\n return false;\n }\n for (int i = 0; i < parameters.length; i++) {\n if (pArgs[i] == null) {\n continue;\n }\n Class argClass = pArgs[i].getClass();\n Class paramClass = parameters[i];\n if (!paramClass.isAssignableFrom(argClass)) {\n if (checkForPrimitive(argClass, paramClass)) {\n continue;\n }\n return false;\n }\n }\n return true;\n }\n\n private static boolean checkForPrimitive(Class argClass, Class paramClass) {\n return paramClass.isPrimitive() && PRIMITIVE_TO_OBJECT_MAP.get(paramClass.getName()) != null;\n }\n\n private static final Map PRIMITIVE_TO_OBJECT_MAP = new HashMap();\n\n static {\n PRIMITIVE_TO_OBJECT_MAP.put(\"int\", Integer.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"long\", Long.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"double\", Double.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"float\", Float.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"bool\", Boolean.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"char\", Character.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"byte\", Byte.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"void\", Void.TYPE);\n PRIMITIVE_TO_OBJECT_MAP.put(\"short\", Short.TYPE);\n }\n}\n"} {"task_id": "Java_3117", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/yin-bp/activiti-engine-5.12/activiti-engine/main/java/org/activiti/engine/HistoryService.java", "mask_start_position": 3316, "mask_end_position": 3396, "canonical_solution": "NativeHistoricActivityInstanceQuery createNativeHistoricActivityInstanceQuery();", "pre_mask_code": "package org.activiti.engine;\n\nimport org.activiti.engine.history.HistoricActivityInstance;\nimport org.activiti.engine.history.HistoricActivityInstanceQuery;\nimport org.activiti.engine.history.HistoricDetail;\nimport org.activiti.engine.history.HistoricDetailQuery;\nimport org.activiti.engine.history.HistoricProcessInstance;\nimport org.activiti.engine.history.HistoricProcessInstanceQuery;\nimport org.activiti.engine.history.HistoricTaskInstance;\nimport org.activiti.engine.history.HistoricTaskInstanceQuery;\nimport org.activiti.engine.history.HistoricVariableInstance;\nimport org.activiti.engine.history.HistoricVariableInstanceQuery;\nimport org.activiti.engine.history.NativeHistoricActivityInstanceQuery;\nimport org.activiti.engine.history.NativeHistoricProcessInstanceQuery;\nimport org.activiti.engine.history.NativeHistoricTaskInstanceQuery;\n\n/**\n * Service exposing information about ongoing and past process instances. This is different\n * from the runtime information in the sense that this runtime information only contains\n * the actual runtime state at any given moment and it is optimized for runtime\n * process execution performance. The history information is optimized for easy\n * querying and remains permanent in the persistent storage.\n *\n * @author Christian Stettler\n * @author Tom Baeyens\n * @author Joram Barrez\n */\npublic interface HistoryService {\n\n /**\n * Creates a new programmatic query to search for {@link HistoricProcessInstance}s.\n */\n HistoricProcessInstanceQuery createHistoricProcessInstanceQuery();\n\n /**\n * Creates a new programmatic query to search for {@link HistoricActivityInstance}s.\n */\n HistoricActivityInstanceQuery createHistoricActivityInstanceQuery();\n\n /**\n * Creates a new programmatic query to search for {@link HistoricTaskInstance}s.\n */\n HistoricTaskInstanceQuery createHistoricTaskInstanceQuery();\n\n /**\n * Creates a new programmatic query to search for {@link HistoricDetail}s.\n */\n HistoricDetailQuery createHistoricDetailQuery();\n\n /**\n * Creates a new programmatic query to search for {@link HistoricVariableInstance}s.\n */\n HistoricVariableInstanceQuery createHistoricVariableInstanceQuery();\n\n /**\n * Deletes historic task instance. This might be useful for tasks that are\n * {@link TaskService#newTask() dynamically created} and then {@link TaskService#complete(String) completed}.\n * If the historic task instance doesn't exist, no exception is thrown and the\n * method returns normal.\n */\n void deleteHistoricTaskInstance(String taskId);\n\n /**\n * Deletes historic process instance. All historic activities, historic task and\n * historic details (variable updates, form properties) are deleted as well.\n */\n void deleteHistoricProcessInstance(String processInstanceId);\n\n /**\n * creates a native query to search for {@link HistoricProcessInstance}s via SQL\n */\n NativeHistoricProcessInstanceQuery createNativeHistoricProcessInstanceQuery();\n\n /**\n * creates a native query to search for {@link HistoricTaskInstance}s via SQL\n */\n NativeHistoricTaskInstanceQuery createNativeHistoricTaskInstanceQuery();\n\n /**\n * creates a native query to search for {@link HistoricActivityInstance}s via SQL\n */\n ", "post_mask_code": "\n}\n"} {"task_id": "Java_3118", "language": "Java", "task_type": "method_signature", "source_file": "java/github/cqyijifu/OpenFalcon-SuitAgent/src/main/java/com/yiji/falcon/agent/plugins/metrics/JDBCMetricsValue.java", "mask_start_position": 1056, "mask_end_position": 1154, "canonical_solution": "private FalconReportObject getVariabilityReport(boolean valid, JDBCConnectionInfo connectionInfo) ", "pre_mask_code": "package com.yiji.falcon.agent.plugins.metrics;\n\nimport com.yiji.falcon.agent.config.AgentConfiguration;\nimport com.yiji.falcon.agent.falcon.CounterType;\nimport com.yiji.falcon.agent.falcon.FalconReportObject;\nimport com.yiji.falcon.agent.falcon.MetricsType;\nimport com.yiji.falcon.agent.plugins.JDBCPlugin;\nimport com.yiji.falcon.agent.util.PropertiesUtil;\nimport com.yiji.falcon.agent.util.StringUtils;\nimport com.yiji.falcon.agent.vo.jdbc.JDBCConnectionInfo;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang.math.NumberUtils;\nimport java.io.File;\nimport java.io.IOException;\nimport java.sql.*;\nimport java.util.*;\n\n/*\n * 修订记录:\n * example@nnthink.com 2016-06-22 17:48 创建\n */\n/**\n * 利用JDBC获取metrics监控值抽象类\n *\n * @author guqiu@yiji.com\n */\n@Slf4j\npublic class JDBCMetricsValue extends MetricsCommon {\n\n private JDBCPlugin jdbcPlugin;\n\n public JDBCMetricsValue(JDBCPlugin jdbcPlugin) {\n this.jdbcPlugin = jdbcPlugin;\n }\n\n /**\n * 获取可用性报告\n *\n * @param valid\n * @param connectionInfo\n * @return\n */\n ", "post_mask_code": "{\n FalconReportObject falconReportObject = MetricsCommon.generatorVariabilityReport(valid, jdbcPlugin.agentSignName(), jdbcPlugin.step(), jdbcPlugin, jdbcPlugin.serverName());\n // tag上添加数据库连接URL,以便区分多个数据库连接实例\n addURLTag(falconReportObject, connectionInfo);\n return falconReportObject;\n }\n\n /**\n * tag上添加数据库连接URL,以便区分多个数据库连接实例\n *\n * @param falconReportObject\n * @param connectionInfo\n */\n private void addURLTag(FalconReportObject falconReportObject, JDBCConnectionInfo connectionInfo) {\n falconReportObject.appendTags(\"url=\" + connectionInfo.getUrl().replace(\"jdbc:mysql://\", \"\").replace(\"jdbc:oracle:thin:@\", \"\"));\n }\n\n @Override\n public Collection getReportObjects() {\n Set result = new HashSet<>();\n Map allMetrics = getAllMetricsQuery();\n String driverName = jdbcPlugin.getJDBCDriveName();\n if (StringUtils.isEmpty(driverName)) {\n log.error(\"从插件{}获取数据库驱动名称为空,无法构建数据库连接\", jdbcPlugin.pluginName());\n return result;\n }\n try {\n Class.forName(driverName);\n } catch (Exception e) {\n log.error(\"数据库驱动加载异常\", e);\n return result;\n }\n Collection connectionInfos = jdbcPlugin.getConnectionInfos();\n if (connectionInfos != null && !connectionInfos.isEmpty()) {\n for (JDBCConnectionInfo connectionInfo : connectionInfos) {\n try (Connection connection = DriverManager.getConnection(connectionInfo.getUrl(), connectionInfo.getUsername(), connectionInfo.getPassword())) {\n for (Map.Entry entry : allMetrics.entrySet()) {\n try {\n String metricsValue = getMetricsValue(entry.getValue(), connection);\n if (!StringUtils.isEmpty(metricsValue)) {\n if (!NumberUtils.isNumber(metricsValue)) {\n log.error(\"JDBC {} 的监控指标:{} 的值:{} ,不能转换为数字,将跳过此监控指标\", jdbcPlugin.serverName(), entry.getKey(), metricsValue);\n } else {\n FalconReportObject reportObject = new FalconReportObject();\n reportObject.setMetric(MetricsCommon.getMetricsName(entry.getKey()));\n reportObject.setCounterType(CounterType.GAUGE);\n reportObject.setValue(metricsValue);\n reportObject.setTimestamp(System.currentTimeMillis() / 1000);\n reportObject.appendTags(MetricsCommon.getTags(jdbcPlugin.agentSignName(), jdbcPlugin, jdbcPlugin.serverName(), MetricsType.SQL_CONF));\n addURLTag(reportObject, connectionInfo);\n MetricsCommon.setReportCommonValue(reportObject, jdbcPlugin.step());\n result.add(reportObject);\n }\n } else {\n log.warn(\"JDBC {} 的监控指标:{} 未获取到值,将跳过此监控指标\", jdbcPlugin.serverName(), entry.getKey());\n }\n } catch (Exception e) {\n log.error(\"SQL 查询异常,跳过监控属性 {}\", entry.getKey(), e);\n }\n }\n try {\n // 添加內建报告\n Collection inbuilt = jdbcPlugin.inbuiltReportObjectsForValid(connection);\n if (inbuilt != null) {\n for (FalconReportObject falconReportObject : inbuilt) {\n addURLTag(falconReportObject, connectionInfo);\n result.add(falconReportObject);\n }\n }\n } catch (Exception e) {\n log.error(\"插件內建报告获取异常\", e);\n }\n result.add(getVariabilityReport(true, connectionInfo));\n } catch (Exception e) {\n log.warn(\"连接JDBC异常,创建不可用报告\", e);\n result.add(getVariabilityReport(false, connectionInfo));\n }\n }\n }\n return result;\n }\n\n private Map getAllMetricsQuery() {\n if (!StringUtils.isEmpty(jdbcPlugin.metricsConfName())) {\n return PropertiesUtil.getAllPropertiesByFileName(AgentConfiguration.INSTANCE.getPluginConfPath() + File.separator + jdbcPlugin.metricsConfName());\n } else {\n return new HashMap<>();\n }\n }\n\n /**\n * 获取指定metrics的值\n *\n * @param sql 获取值的sql查询语句\n * @return\n */\n private String getMetricsValue(String sql, Connection connection) throws SQLException, ClassNotFoundException {\n String result = \"\";\n if (!StringUtils.isEmpty(sql)) {\n // 创建该连接下的PreparedStatement对象\n PreparedStatement pstmt = connection.prepareStatement(sql);\n // 执行查询语句,将数据保存到ResultSet对象中\n ResultSet rs = pstmt.executeQuery();\n // 将指针移到下一行,判断rs中是否有数据\n if (rs.next()) {\n result = rs.getString(1);\n }\n rs.close();\n pstmt.close();\n }\n return result;\n }\n}\n"} {"task_id": "Java_3119", "language": "Java", "task_type": "method_body", "source_file": "java/github/cqyijifu/OpenFalcon-SuitAgent/src/main/java/com/yiji/falcon/agent/plugins/metrics/JDBCMetricsValue.java", "mask_start_position": 5620, "mask_end_position": 5915, "canonical_solution": "{\n if (!StringUtils.isEmpty(jdbcPlugin.metricsConfName())) {\n return PropertiesUtil.getAllPropertiesByFileName(AgentConfiguration.INSTANCE.getPluginConfPath() + File.separator + jdbcPlugin.metricsConfName());\n } else {\n return new HashMap<>();\n }\n }", "pre_mask_code": "package com.yiji.falcon.agent.plugins.metrics;\n\nimport com.yiji.falcon.agent.config.AgentConfiguration;\nimport com.yiji.falcon.agent.falcon.CounterType;\nimport com.yiji.falcon.agent.falcon.FalconReportObject;\nimport com.yiji.falcon.agent.falcon.MetricsType;\nimport com.yiji.falcon.agent.plugins.JDBCPlugin;\nimport com.yiji.falcon.agent.util.PropertiesUtil;\nimport com.yiji.falcon.agent.util.StringUtils;\nimport com.yiji.falcon.agent.vo.jdbc.JDBCConnectionInfo;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang.math.NumberUtils;\nimport java.io.File;\nimport java.io.IOException;\nimport java.sql.*;\nimport java.util.*;\n\n/*\n * 修订记录:\n * example@nnthink.com 2016-06-22 17:48 创建\n */\n/**\n * 利用JDBC获取metrics监控值抽象类\n *\n * @author guqiu@yiji.com\n */\n@Slf4j\npublic class JDBCMetricsValue extends MetricsCommon {\n\n private JDBCPlugin jdbcPlugin;\n\n public JDBCMetricsValue(JDBCPlugin jdbcPlugin) {\n this.jdbcPlugin = jdbcPlugin;\n }\n\n /**\n * 获取可用性报告\n *\n * @param valid\n * @param connectionInfo\n * @return\n */\n private FalconReportObject getVariabilityReport(boolean valid, JDBCConnectionInfo connectionInfo) {\n FalconReportObject falconReportObject = MetricsCommon.generatorVariabilityReport(valid, jdbcPlugin.agentSignName(), jdbcPlugin.step(), jdbcPlugin, jdbcPlugin.serverName());\n // tag上添加数据库连接URL,以便区分多个数据库连接实例\n addURLTag(falconReportObject, connectionInfo);\n return falconReportObject;\n }\n\n /**\n * tag上添加数据库连接URL,以便区分多个数据库连接实例\n *\n * @param falconReportObject\n * @param connectionInfo\n */\n private void addURLTag(FalconReportObject falconReportObject, JDBCConnectionInfo connectionInfo) {\n falconReportObject.appendTags(\"url=\" + connectionInfo.getUrl().replace(\"jdbc:mysql://\", \"\").replace(\"jdbc:oracle:thin:@\", \"\"));\n }\n\n @Override\n public Collection getReportObjects() {\n Set result = new HashSet<>();\n Map allMetrics = getAllMetricsQuery();\n String driverName = jdbcPlugin.getJDBCDriveName();\n if (StringUtils.isEmpty(driverName)) {\n log.error(\"从插件{}获取数据库驱动名称为空,无法构建数据库连接\", jdbcPlugin.pluginName());\n return result;\n }\n try {\n Class.forName(driverName);\n } catch (Exception e) {\n log.error(\"数据库驱动加载异常\", e);\n return result;\n }\n Collection connectionInfos = jdbcPlugin.getConnectionInfos();\n if (connectionInfos != null && !connectionInfos.isEmpty()) {\n for (JDBCConnectionInfo connectionInfo : connectionInfos) {\n try (Connection connection = DriverManager.getConnection(connectionInfo.getUrl(), connectionInfo.getUsername(), connectionInfo.getPassword())) {\n for (Map.Entry entry : allMetrics.entrySet()) {\n try {\n String metricsValue = getMetricsValue(entry.getValue(), connection);\n if (!StringUtils.isEmpty(metricsValue)) {\n if (!NumberUtils.isNumber(metricsValue)) {\n log.error(\"JDBC {} 的监控指标:{} 的值:{} ,不能转换为数字,将跳过此监控指标\", jdbcPlugin.serverName(), entry.getKey(), metricsValue);\n } else {\n FalconReportObject reportObject = new FalconReportObject();\n reportObject.setMetric(MetricsCommon.getMetricsName(entry.getKey()));\n reportObject.setCounterType(CounterType.GAUGE);\n reportObject.setValue(metricsValue);\n reportObject.setTimestamp(System.currentTimeMillis() / 1000);\n reportObject.appendTags(MetricsCommon.getTags(jdbcPlugin.agentSignName(), jdbcPlugin, jdbcPlugin.serverName(), MetricsType.SQL_CONF));\n addURLTag(reportObject, connectionInfo);\n MetricsCommon.setReportCommonValue(reportObject, jdbcPlugin.step());\n result.add(reportObject);\n }\n } else {\n log.warn(\"JDBC {} 的监控指标:{} 未获取到值,将跳过此监控指标\", jdbcPlugin.serverName(), entry.getKey());\n }\n } catch (Exception e) {\n log.error(\"SQL 查询异常,跳过监控属性 {}\", entry.getKey(), e);\n }\n }\n try {\n // 添加內建报告\n Collection inbuilt = jdbcPlugin.inbuiltReportObjectsForValid(connection);\n if (inbuilt != null) {\n for (FalconReportObject falconReportObject : inbuilt) {\n addURLTag(falconReportObject, connectionInfo);\n result.add(falconReportObject);\n }\n }\n } catch (Exception e) {\n log.error(\"插件內建报告获取异常\", e);\n }\n result.add(getVariabilityReport(true, connectionInfo));\n } catch (Exception e) {\n log.warn(\"连接JDBC异常,创建不可用报告\", e);\n result.add(getVariabilityReport(false, connectionInfo));\n }\n }\n }\n return result;\n }\n\n private Map getAllMetricsQuery() ", "post_mask_code": "\n\n /**\n * 获取指定metrics的值\n *\n * @param sql 获取值的sql查询语句\n * @return\n */\n private String getMetricsValue(String sql, Connection connection) throws SQLException, ClassNotFoundException {\n String result = \"\";\n if (!StringUtils.isEmpty(sql)) {\n // 创建该连接下的PreparedStatement对象\n PreparedStatement pstmt = connection.prepareStatement(sql);\n // 执行查询语句,将数据保存到ResultSet对象中\n ResultSet rs = pstmt.executeQuery();\n // 将指针移到下一行,判断rs中是否有数据\n if (rs.next()) {\n result = rs.getString(1);\n }\n rs.close();\n pstmt.close();\n }\n return result;\n }\n}\n"} {"task_id": "Java_3120", "language": "Java", "task_type": "single_line", "source_file": "java/github/cqyijifu/OpenFalcon-SuitAgent/src/main/java/com/yiji/falcon/agent/plugins/metrics/JDBCMetricsValue.java", "mask_start_position": 2507, "mask_end_position": 2510, "canonical_solution": "();", "pre_mask_code": "package com.yiji.falcon.agent.plugins.metrics;\n\nimport com.yiji.falcon.agent.config.AgentConfiguration;\nimport com.yiji.falcon.agent.falcon.CounterType;\nimport com.yiji.falcon.agent.falcon.FalconReportObject;\nimport com.yiji.falcon.agent.falcon.MetricsType;\nimport com.yiji.falcon.agent.plugins.JDBCPlugin;\nimport com.yiji.falcon.agent.util.PropertiesUtil;\nimport com.yiji.falcon.agent.util.StringUtils;\nimport com.yiji.falcon.agent.vo.jdbc.JDBCConnectionInfo;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang.math.NumberUtils;\nimport java.io.File;\nimport java.io.IOException;\nimport java.sql.*;\nimport java.util.*;\n\n/*\n * 修订记录:\n * example@nnthink.com 2016-06-22 17:48 创建\n */\n/**\n * 利用JDBC获取metrics监控值抽象类\n *\n * @author guqiu@yiji.com\n */\n@Slf4j\npublic class JDBCMetricsValue extends MetricsCommon {\n\n private JDBCPlugin jdbcPlugin;\n\n public JDBCMetricsValue(JDBCPlugin jdbcPlugin) {\n this.jdbcPlugin = jdbcPlugin;\n }\n\n /**\n * 获取可用性报告\n *\n * @param valid\n * @param connectionInfo\n * @return\n */\n private FalconReportObject getVariabilityReport(boolean valid, JDBCConnectionInfo connectionInfo) {\n FalconReportObject falconReportObject = MetricsCommon.generatorVariabilityReport(valid, jdbcPlugin.agentSignName(), jdbcPlugin.step(), jdbcPlugin, jdbcPlugin.serverName());\n // tag上添加数据库连接URL,以便区分多个数据库连接实例\n addURLTag(falconReportObject, connectionInfo);\n return falconReportObject;\n }\n\n /**\n * tag上添加数据库连接URL,以便区分多个数据库连接实例\n *\n * @param falconReportObject\n * @param connectionInfo\n */\n private void addURLTag(FalconReportObject falconReportObject, JDBCConnectionInfo connectionInfo) {\n falconReportObject.appendTags(\"url=\" + connectionInfo.getUrl().replace(\"jdbc:mysql://\", \"\").replace(\"jdbc:oracle:thin:@\", \"\"));\n }\n\n @Override\n public Collection getReportObjects() {\n Set result = new HashSet<>();\n Map allMetrics = getAllMetricsQuery();\n String driverName = jdbcPlugin.getJDBCDriveName();\n if (StringUtils.isEmpty(driverName)) {\n log.error(\"从插件{}获取数据库驱动名称为空,无法构建数据库连接\", jdbcPlugin.pluginName());\n return result;\n }\n try {\n Class.forName(driverName);\n } catch (Exception e) {\n log.error(\"数据库驱动加载异常\", e);\n return result;\n }\n Collection connectionInfos = jdbcPlugin.getConnectionInfos", "post_mask_code": "\n if (connectionInfos != null && !connectionInfos.isEmpty()) {\n for (JDBCConnectionInfo connectionInfo : connectionInfos) {\n try (Connection connection = DriverManager.getConnection(connectionInfo.getUrl(), connectionInfo.getUsername(), connectionInfo.getPassword())) {\n for (Map.Entry entry : allMetrics.entrySet()) {\n try {\n String metricsValue = getMetricsValue(entry.getValue(), connection);\n if (!StringUtils.isEmpty(metricsValue)) {\n if (!NumberUtils.isNumber(metricsValue)) {\n log.error(\"JDBC {} 的监控指标:{} 的值:{} ,不能转换为数字,将跳过此监控指标\", jdbcPlugin.serverName(), entry.getKey(), metricsValue);\n } else {\n FalconReportObject reportObject = new FalconReportObject();\n reportObject.setMetric(MetricsCommon.getMetricsName(entry.getKey()));\n reportObject.setCounterType(CounterType.GAUGE);\n reportObject.setValue(metricsValue);\n reportObject.setTimestamp(System.currentTimeMillis() / 1000);\n reportObject.appendTags(MetricsCommon.getTags(jdbcPlugin.agentSignName(), jdbcPlugin, jdbcPlugin.serverName(), MetricsType.SQL_CONF));\n addURLTag(reportObject, connectionInfo);\n MetricsCommon.setReportCommonValue(reportObject, jdbcPlugin.step());\n result.add(reportObject);\n }\n } else {\n log.warn(\"JDBC {} 的监控指标:{} 未获取到值,将跳过此监控指标\", jdbcPlugin.serverName(), entry.getKey());\n }\n } catch (Exception e) {\n log.error(\"SQL 查询异常,跳过监控属性 {}\", entry.getKey(), e);\n }\n }\n try {\n // 添加內建报告\n Collection inbuilt = jdbcPlugin.inbuiltReportObjectsForValid(connection);\n if (inbuilt != null) {\n for (FalconReportObject falconReportObject : inbuilt) {\n addURLTag(falconReportObject, connectionInfo);\n result.add(falconReportObject);\n }\n }\n } catch (Exception e) {\n log.error(\"插件內建报告获取异常\", e);\n }\n result.add(getVariabilityReport(true, connectionInfo));\n } catch (Exception e) {\n log.warn(\"连接JDBC异常,创建不可用报告\", e);\n result.add(getVariabilityReport(false, connectionInfo));\n }\n }\n }\n return result;\n }\n\n private Map getAllMetricsQuery() {\n if (!StringUtils.isEmpty(jdbcPlugin.metricsConfName())) {\n return PropertiesUtil.getAllPropertiesByFileName(AgentConfiguration.INSTANCE.getPluginConfPath() + File.separator + jdbcPlugin.metricsConfName());\n } else {\n return new HashMap<>();\n }\n }\n\n /**\n * 获取指定metrics的值\n *\n * @param sql 获取值的sql查询语句\n * @return\n */\n private String getMetricsValue(String sql, Connection connection) throws SQLException, ClassNotFoundException {\n String result = \"\";\n if (!StringUtils.isEmpty(sql)) {\n // 创建该连接下的PreparedStatement对象\n PreparedStatement pstmt = connection.prepareStatement(sql);\n // 执行查询语句,将数据保存到ResultSet对象中\n ResultSet rs = pstmt.executeQuery();\n // 将指针移到下一行,判断rs中是否有数据\n if (rs.next()) {\n result = rs.getString(1);\n }\n rs.close();\n pstmt.close();\n }\n return result;\n }\n}\n"} {"task_id": "Java_3121", "language": "Java", "task_type": "method_with_comment", "source_file": "java/github/cqyijifu/OpenFalcon-SuitAgent/src/main/java/com/yiji/falcon/agent/plugins/metrics/JDBCMetricsValue.java", "mask_start_position": 1599, "mask_end_position": 1839, "canonical_solution": "private void addURLTag(FalconReportObject falconReportObject, JDBCConnectionInfo connectionInfo) {\n falconReportObject.appendTags(\"url=\" + connectionInfo.getUrl().replace(\"jdbc:mysql://\", \"\").replace(\"jdbc:oracle:thin:@\", \"\"));\n }", "pre_mask_code": "package com.yiji.falcon.agent.plugins.metrics;\n\nimport com.yiji.falcon.agent.config.AgentConfiguration;\nimport com.yiji.falcon.agent.falcon.CounterType;\nimport com.yiji.falcon.agent.falcon.FalconReportObject;\nimport com.yiji.falcon.agent.falcon.MetricsType;\nimport com.yiji.falcon.agent.plugins.JDBCPlugin;\nimport com.yiji.falcon.agent.util.PropertiesUtil;\nimport com.yiji.falcon.agent.util.StringUtils;\nimport com.yiji.falcon.agent.vo.jdbc.JDBCConnectionInfo;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang.math.NumberUtils;\nimport java.io.File;\nimport java.io.IOException;\nimport java.sql.*;\nimport java.util.*;\n\n/*\n * 修订记录:\n * example@nnthink.com 2016-06-22 17:48 创建\n */\n/**\n * 利用JDBC获取metrics监控值抽象类\n *\n * @author guqiu@yiji.com\n */\n@Slf4j\npublic class JDBCMetricsValue extends MetricsCommon {\n\n private JDBCPlugin jdbcPlugin;\n\n public JDBCMetricsValue(JDBCPlugin jdbcPlugin) {\n this.jdbcPlugin = jdbcPlugin;\n }\n\n /**\n * 获取可用性报告\n *\n * @param valid\n * @param connectionInfo\n * @return\n */\n private FalconReportObject getVariabilityReport(boolean valid, JDBCConnectionInfo connectionInfo) {\n FalconReportObject falconReportObject = MetricsCommon.generatorVariabilityReport(valid, jdbcPlugin.agentSignName(), jdbcPlugin.step(), jdbcPlugin, jdbcPlugin.serverName());\n // tag上添加数据库连接URL,以便区分多个数据库连接实例\n addURLTag(falconReportObject, connectionInfo);\n return falconReportObject;\n }\n\n /**\n * tag上添加数据库连接URL,以便区分多个数据库连接实例\n *\n * @param falconReportObject\n * @param connectionInfo\n */\n ", "post_mask_code": "\n\n @Override\n public Collection getReportObjects() {\n Set result = new HashSet<>();\n Map allMetrics = getAllMetricsQuery();\n String driverName = jdbcPlugin.getJDBCDriveName();\n if (StringUtils.isEmpty(driverName)) {\n log.error(\"从插件{}获取数据库驱动名称为空,无法构建数据库连接\", jdbcPlugin.pluginName());\n return result;\n }\n try {\n Class.forName(driverName);\n } catch (Exception e) {\n log.error(\"数据库驱动加载异常\", e);\n return result;\n }\n Collection connectionInfos = jdbcPlugin.getConnectionInfos();\n if (connectionInfos != null && !connectionInfos.isEmpty()) {\n for (JDBCConnectionInfo connectionInfo : connectionInfos) {\n try (Connection connection = DriverManager.getConnection(connectionInfo.getUrl(), connectionInfo.getUsername(), connectionInfo.getPassword())) {\n for (Map.Entry entry : allMetrics.entrySet()) {\n try {\n String metricsValue = getMetricsValue(entry.getValue(), connection);\n if (!StringUtils.isEmpty(metricsValue)) {\n if (!NumberUtils.isNumber(metricsValue)) {\n log.error(\"JDBC {} 的监控指标:{} 的值:{} ,不能转换为数字,将跳过此监控指标\", jdbcPlugin.serverName(), entry.getKey(), metricsValue);\n } else {\n FalconReportObject reportObject = new FalconReportObject();\n reportObject.setMetric(MetricsCommon.getMetricsName(entry.getKey()));\n reportObject.setCounterType(CounterType.GAUGE);\n reportObject.setValue(metricsValue);\n reportObject.setTimestamp(System.currentTimeMillis() / 1000);\n reportObject.appendTags(MetricsCommon.getTags(jdbcPlugin.agentSignName(), jdbcPlugin, jdbcPlugin.serverName(), MetricsType.SQL_CONF));\n addURLTag(reportObject, connectionInfo);\n MetricsCommon.setReportCommonValue(reportObject, jdbcPlugin.step());\n result.add(reportObject);\n }\n } else {\n log.warn(\"JDBC {} 的监控指标:{} 未获取到值,将跳过此监控指标\", jdbcPlugin.serverName(), entry.getKey());\n }\n } catch (Exception e) {\n log.error(\"SQL 查询异常,跳过监控属性 {}\", entry.getKey(), e);\n }\n }\n try {\n // 添加內建报告\n Collection inbuilt = jdbcPlugin.inbuiltReportObjectsForValid(connection);\n if (inbuilt != null) {\n for (FalconReportObject falconReportObject : inbuilt) {\n addURLTag(falconReportObject, connectionInfo);\n result.add(falconReportObject);\n }\n }\n } catch (Exception e) {\n log.error(\"插件內建报告获取异常\", e);\n }\n result.add(getVariabilityReport(true, connectionInfo));\n } catch (Exception e) {\n log.warn(\"连接JDBC异常,创建不可用报告\", e);\n result.add(getVariabilityReport(false, connectionInfo));\n }\n }\n }\n return result;\n }\n\n private Map getAllMetricsQuery() {\n if (!StringUtils.isEmpty(jdbcPlugin.metricsConfName())) {\n return PropertiesUtil.getAllPropertiesByFileName(AgentConfiguration.INSTANCE.getPluginConfPath() + File.separator + jdbcPlugin.metricsConfName());\n } else {\n return new HashMap<>();\n }\n }\n\n /**\n * 获取指定metrics的值\n *\n * @param sql 获取值的sql查询语句\n * @return\n */\n private String getMetricsValue(String sql, Connection connection) throws SQLException, ClassNotFoundException {\n String result = \"\";\n if (!StringUtils.isEmpty(sql)) {\n // 创建该连接下的PreparedStatement对象\n PreparedStatement pstmt = connection.prepareStatement(sql);\n // 执行查询语句,将数据保存到ResultSet对象中\n ResultSet rs = pstmt.executeQuery();\n // 将指针移到下一行,判断rs中是否有数据\n if (rs.next()) {\n result = rs.getString(1);\n }\n rs.close();\n pstmt.close();\n }\n return result;\n }\n}\n"} {"task_id": "Java_3122", "language": "Java", "task_type": "try_statement", "source_file": "java/github/cqyijifu/OpenFalcon-SuitAgent/src/main/java/com/yiji/falcon/agent/plugins/metrics/JDBCMetricsValue.java", "mask_start_position": 2268, "mask_end_position": 2420, "canonical_solution": "try {\n Class.forName(driverName);\n } catch (Exception e) {\n log.error(\"数据库驱动加载异常\", e);\n return result;\n }", "pre_mask_code": "package com.yiji.falcon.agent.plugins.metrics;\n\nimport com.yiji.falcon.agent.config.AgentConfiguration;\nimport com.yiji.falcon.agent.falcon.CounterType;\nimport com.yiji.falcon.agent.falcon.FalconReportObject;\nimport com.yiji.falcon.agent.falcon.MetricsType;\nimport com.yiji.falcon.agent.plugins.JDBCPlugin;\nimport com.yiji.falcon.agent.util.PropertiesUtil;\nimport com.yiji.falcon.agent.util.StringUtils;\nimport com.yiji.falcon.agent.vo.jdbc.JDBCConnectionInfo;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang.math.NumberUtils;\nimport java.io.File;\nimport java.io.IOException;\nimport java.sql.*;\nimport java.util.*;\n\n/*\n * 修订记录:\n * example@nnthink.com 2016-06-22 17:48 创建\n */\n/**\n * 利用JDBC获取metrics监控值抽象类\n *\n * @author guqiu@yiji.com\n */\n@Slf4j\npublic class JDBCMetricsValue extends MetricsCommon {\n\n private JDBCPlugin jdbcPlugin;\n\n public JDBCMetricsValue(JDBCPlugin jdbcPlugin) {\n this.jdbcPlugin = jdbcPlugin;\n }\n\n /**\n * 获取可用性报告\n *\n * @param valid\n * @param connectionInfo\n * @return\n */\n private FalconReportObject getVariabilityReport(boolean valid, JDBCConnectionInfo connectionInfo) {\n FalconReportObject falconReportObject = MetricsCommon.generatorVariabilityReport(valid, jdbcPlugin.agentSignName(), jdbcPlugin.step(), jdbcPlugin, jdbcPlugin.serverName());\n // tag上添加数据库连接URL,以便区分多个数据库连接实例\n addURLTag(falconReportObject, connectionInfo);\n return falconReportObject;\n }\n\n /**\n * tag上添加数据库连接URL,以便区分多个数据库连接实例\n *\n * @param falconReportObject\n * @param connectionInfo\n */\n private void addURLTag(FalconReportObject falconReportObject, JDBCConnectionInfo connectionInfo) {\n falconReportObject.appendTags(\"url=\" + connectionInfo.getUrl().replace(\"jdbc:mysql://\", \"\").replace(\"jdbc:oracle:thin:@\", \"\"));\n }\n\n @Override\n public Collection getReportObjects() {\n Set result = new HashSet<>();\n Map allMetrics = getAllMetricsQuery();\n String driverName = jdbcPlugin.getJDBCDriveName();\n if (StringUtils.isEmpty(driverName)) {\n log.error(\"从插件{}获取数据库驱动名称为空,无法构建数据库连接\", jdbcPlugin.pluginName());\n return result;\n }\n ", "post_mask_code": "\n Collection connectionInfos = jdbcPlugin.getConnectionInfos();\n if (connectionInfos != null && !connectionInfos.isEmpty()) {\n for (JDBCConnectionInfo connectionInfo : connectionInfos) {\n try (Connection connection = DriverManager.getConnection(connectionInfo.getUrl(), connectionInfo.getUsername(), connectionInfo.getPassword())) {\n for (Map.Entry entry : allMetrics.entrySet()) {\n try {\n String metricsValue = getMetricsValue(entry.getValue(), connection);\n if (!StringUtils.isEmpty(metricsValue)) {\n if (!NumberUtils.isNumber(metricsValue)) {\n log.error(\"JDBC {} 的监控指标:{} 的值:{} ,不能转换为数字,将跳过此监控指标\", jdbcPlugin.serverName(), entry.getKey(), metricsValue);\n } else {\n FalconReportObject reportObject = new FalconReportObject();\n reportObject.setMetric(MetricsCommon.getMetricsName(entry.getKey()));\n reportObject.setCounterType(CounterType.GAUGE);\n reportObject.setValue(metricsValue);\n reportObject.setTimestamp(System.currentTimeMillis() / 1000);\n reportObject.appendTags(MetricsCommon.getTags(jdbcPlugin.agentSignName(), jdbcPlugin, jdbcPlugin.serverName(), MetricsType.SQL_CONF));\n addURLTag(reportObject, connectionInfo);\n MetricsCommon.setReportCommonValue(reportObject, jdbcPlugin.step());\n result.add(reportObject);\n }\n } else {\n log.warn(\"JDBC {} 的监控指标:{} 未获取到值,将跳过此监控指标\", jdbcPlugin.serverName(), entry.getKey());\n }\n } catch (Exception e) {\n log.error(\"SQL 查询异常,跳过监控属性 {}\", entry.getKey(), e);\n }\n }\n try {\n // 添加內建报告\n Collection inbuilt = jdbcPlugin.inbuiltReportObjectsForValid(connection);\n if (inbuilt != null) {\n for (FalconReportObject falconReportObject : inbuilt) {\n addURLTag(falconReportObject, connectionInfo);\n result.add(falconReportObject);\n }\n }\n } catch (Exception e) {\n log.error(\"插件內建报告获取异常\", e);\n }\n result.add(getVariabilityReport(true, connectionInfo));\n } catch (Exception e) {\n log.warn(\"连接JDBC异常,创建不可用报告\", e);\n result.add(getVariabilityReport(false, connectionInfo));\n }\n }\n }\n return result;\n }\n\n private Map getAllMetricsQuery() {\n if (!StringUtils.isEmpty(jdbcPlugin.metricsConfName())) {\n return PropertiesUtil.getAllPropertiesByFileName(AgentConfiguration.INSTANCE.getPluginConfPath() + File.separator + jdbcPlugin.metricsConfName());\n } else {\n return new HashMap<>();\n }\n }\n\n /**\n * 获取指定metrics的值\n *\n * @param sql 获取值的sql查询语句\n * @return\n */\n private String getMetricsValue(String sql, Connection connection) throws SQLException, ClassNotFoundException {\n String result = \"\";\n if (!StringUtils.isEmpty(sql)) {\n // 创建该连接下的PreparedStatement对象\n PreparedStatement pstmt = connection.prepareStatement(sql);\n // 执行查询语句,将数据保存到ResultSet对象中\n ResultSet rs = pstmt.executeQuery();\n // 将指针移到下一行,判断rs中是否有数据\n if (rs.next()) {\n result = rs.getString(1);\n }\n rs.close();\n pstmt.close();\n }\n return result;\n }\n}\n"} {"task_id": "Java_3123", "language": "Java", "task_type": "method_signature", "source_file": "java/github/tunnelvisionlabs/antlrworks2/org-antlr-works-editor/src/org/antlr/works/editor/grammar/debugger/ParserDebuggerReferenceAnchorsParserTask.java", "mask_start_position": 6888, "mask_end_position": 6944, "canonical_solution": "@Override\n protected void visitState(ATNState p) ", "pre_mask_code": "/*\n * All rights reserved.\n *\n * The source code of this document is proprietary work, and is not licensed for\n * distribution. For information about licensing, contact Sam Harwell at:\n * example@nnthink.com\n */\npackage org.antlr.works.editor.grammar.debugger;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.EnumSet;\nimport java.util.IdentityHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.CancellationException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.Future;\nimport javax.swing.text.Document;\nimport org.antlr.netbeans.editor.classification.TokenTag;\nimport org.antlr.netbeans.editor.tagging.Tagger;\nimport org.antlr.netbeans.editor.text.DocumentSnapshot;\nimport org.antlr.netbeans.editor.text.VersionedDocument;\nimport org.antlr.netbeans.parsing.spi.BaseParserData;\nimport org.antlr.netbeans.parsing.spi.DocumentParserTaskProvider;\nimport org.antlr.netbeans.parsing.spi.ParseContext;\nimport org.antlr.netbeans.parsing.spi.ParserData;\nimport org.antlr.netbeans.parsing.spi.ParserDataDefinition;\nimport org.antlr.netbeans.parsing.spi.ParserDataOptions;\nimport org.antlr.netbeans.parsing.spi.ParserResultHandler;\nimport org.antlr.netbeans.parsing.spi.ParserTask;\nimport org.antlr.netbeans.parsing.spi.ParserTaskDefinition;\nimport org.antlr.netbeans.parsing.spi.ParserTaskManager;\nimport org.antlr.netbeans.parsing.spi.ParserTaskProvider;\nimport org.antlr.netbeans.parsing.spi.ParserTaskScheduler;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.DefaultErrorStrategy;\nimport org.antlr.v4.runtime.ParserInterpreter;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenSource;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.Vocabulary;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNDeserializer;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.PredictionMode;\nimport org.antlr.v4.runtime.atn.RuleTransition;\nimport org.antlr.v4.runtime.atn.Transition;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.works.editor.antlr4.classification.TaggerTokenSource;\nimport org.antlr.works.editor.antlr4.parsing.DescriptiveErrorListener;\nimport org.antlr.works.editor.antlr4.parsing.SyntaxErrorListener;\nimport org.netbeans.api.editor.mimelookup.MimeRegistration;\n\n/**\n * @author Sam Harwell\n */\npublic final class ParserDebuggerReferenceAnchorsParserTask implements ParserTask {\n\n private final VersionedDocument document;\n\n private final Object lock = new Object();\n\n private ParserDebuggerReferenceAnchorsParserTask(VersionedDocument document) {\n this.document = document;\n }\n\n @Override\n public ParserTaskDefinition getDefinition() {\n return Definition.INSTANCE;\n }\n\n @Override\n public void parse(ParserTaskManager taskManager, ParseContext context, DocumentSnapshot snapshot, Collection> requestedData, ParserResultHandler results) throws InterruptedException, ExecutionException {\n // ParserDebuggerEditorKit.LEX\n synchronized (lock) {\n ParserData fileParseResultData = taskManager.getData(snapshot, ParserDebuggerParserDataDefinitions.FILE_PARSE_RESULT, EnumSet.of(ParserDataOptions.NO_UPDATE)).get();\n ParserData parseTreeResult = taskManager.getData(snapshot, ParserDebuggerParserDataDefinitions.REFERENCE_PARSE_TREE, EnumSet.of(ParserDataOptions.NO_UPDATE)).get();\n if (fileParseResultData == null || parseTreeResult == null) {\n Future>>> futureTokensData = taskManager.getData(snapshot, ParserDebuggerParserDataDefinitions.LEXER_TOKENS);\n Tagger> tagger = futureTokensData.get().getData();\n TaggerTokenSource tokenSource = new TaggerTokenSource(tagger, snapshot);\n InterruptableTokenStream tokenStream = new InterruptableTokenStream(tokenSource);\n ParserRuleContext parseResult;\n ParserInterpreterData parserInterpreterData = (ParserInterpreterData) snapshot.getVersionedDocument().getDocument().getProperty(ParserDebuggerEditorKit.PROP_PARSER_INTERP_DATA);\n String grammarFileName = parserInterpreterData.grammarFileName;\n Vocabulary vocabulary = parserInterpreterData.vocabulary;\n List ruleNames = parserInterpreterData.ruleNames;\n ATN atn = new ATNDeserializer().deserialize(parserInterpreterData.serializedAtn.toCharArray());\n TracingParserInterpreter parser = new TracingParserInterpreter(grammarFileName, vocabulary, ruleNames, atn, tokenStream);\n long startTime = System.nanoTime();\n parser.setInterpreter(new StatisticsParserATNSimulator(parser, atn));\n parser.getInterpreter().optimize_ll1 = false;\n parser.getInterpreter().reportAmbiguities = true;\n parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);\n parser.removeErrorListeners();\n parser.addErrorListener(DescriptiveErrorListener.INSTANCE);\n parser.addErrorListener(new StatisticsParserErrorListener());\n SyntaxErrorListener syntaxErrorListener = new SyntaxErrorListener(snapshot);\n parser.addErrorListener(syntaxErrorListener);\n parser.setBuildParseTree(true);\n parser.setErrorHandler(new DefaultErrorStrategy());\n parseResult = parser.parse(parserInterpreterData.startRuleIndex);\n String sourceName = (String) document.getDocument().getProperty(Document.TitleProperty);\n FileParseResult fileParseResult = new FileParseResult(sourceName, 0, parseResult, syntaxErrorListener.getSyntaxErrors(), tokenStream.size(), startTime, null, parser);\n fileParseResultData = new BaseParserData<>(context, ParserDebuggerParserDataDefinitions.FILE_PARSE_RESULT, snapshot, fileParseResult);\n parseTreeResult = new BaseParserData<>(context, ParserDebuggerParserDataDefinitions.REFERENCE_PARSE_TREE, snapshot, parseResult);\n }\n results.addResult(fileParseResultData);\n results.addResult(parseTreeResult);\n }\n }\n\n public static class TracingParserInterpreter extends ParserInterpreter {\n\n public final Map associatedTransitions = new IdentityHashMap<>();\n\n public TracingParserInterpreter(String grammarFileName, Vocabulary vocabulary, Collection ruleNames, ATN atn, TokenStream input) {\n super(grammarFileName, vocabulary, ruleNames, atn, input);\n }\n\n ", "post_mask_code": "{\n super.visitState(p);\n if (p.getNumberOfTransitions() > 1) {\n return;\n }\n Transition transition = p.transition(0);\n if (transition instanceof RuleTransition) {\n // rule transition created a new context\n associatedTransitions.put(_ctx, transition);\n } else if (!p.onlyHasEpsilonTransitions()) {\n // match transition created a new terminal or error node\n associatedTransitions.put(_ctx.getChild(_ctx.getChildCount() - 1), transition);\n }\n }\n }\n\n private static class InterruptableTokenStream extends CommonTokenStream {\n\n public InterruptableTokenStream(TokenSource tokenSource) {\n super(tokenSource);\n }\n\n @Override\n public void consume() {\n if (Thread.interrupted()) {\n throw new CancellationException();\n }\n super.consume();\n }\n }\n\n private static final class Definition extends ParserTaskDefinition {\n\n private static final Collection> INPUTS = Collections.>emptyList();\n\n private static final Collection> OUTPUTS = Arrays.>asList(ParserDebuggerParserDataDefinitions.FILE_PARSE_RESULT, ParserDebuggerParserDataDefinitions.REFERENCE_PARSE_TREE);\n\n public static final Definition INSTANCE = new Definition();\n\n public Definition() {\n super(\"Parser Debugger Reference Anchors\", INPUTS, OUTPUTS, ParserTaskScheduler.CONTENT_SENSITIVE_TASK_SCHEDULER);\n }\n }\n\n @MimeRegistration(mimeType = ParserDebuggerEditorKit.PARSER_DEBUGGER_MIME_TYPE, service = ParserTaskProvider.class)\n public static final class Provider extends DocumentParserTaskProvider {\n\n @Override\n public ParserTaskDefinition getDefinition() {\n return Definition.INSTANCE;\n }\n\n @Override\n public ParserTask createTaskImpl(VersionedDocument document) {\n return new ParserDebuggerReferenceAnchorsParserTask(document);\n }\n }\n}\n"} {"task_id": "Java_3124", "language": "Java", "task_type": "method_body", "source_file": "java/github/tunnelvisionlabs/antlrworks2/org-antlr-works-editor/src/org/antlr/works/editor/grammar/debugger/ParserDebuggerReferenceAnchorsParserTask.java", "mask_start_position": 7788, "mask_end_position": 7933, "canonical_solution": "{\n if (Thread.interrupted()) {\n throw new CancellationException();\n }\n super.consume();\n }", "pre_mask_code": "/*\n * All rights reserved.\n *\n * The source code of this document is proprietary work, and is not licensed for\n * distribution. For information about licensing, contact Sam Harwell at:\n * example@nnthink.com\n */\npackage org.antlr.works.editor.grammar.debugger;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.EnumSet;\nimport java.util.IdentityHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.CancellationException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.Future;\nimport javax.swing.text.Document;\nimport org.antlr.netbeans.editor.classification.TokenTag;\nimport org.antlr.netbeans.editor.tagging.Tagger;\nimport org.antlr.netbeans.editor.text.DocumentSnapshot;\nimport org.antlr.netbeans.editor.text.VersionedDocument;\nimport org.antlr.netbeans.parsing.spi.BaseParserData;\nimport org.antlr.netbeans.parsing.spi.DocumentParserTaskProvider;\nimport org.antlr.netbeans.parsing.spi.ParseContext;\nimport org.antlr.netbeans.parsing.spi.ParserData;\nimport org.antlr.netbeans.parsing.spi.ParserDataDefinition;\nimport org.antlr.netbeans.parsing.spi.ParserDataOptions;\nimport org.antlr.netbeans.parsing.spi.ParserResultHandler;\nimport org.antlr.netbeans.parsing.spi.ParserTask;\nimport org.antlr.netbeans.parsing.spi.ParserTaskDefinition;\nimport org.antlr.netbeans.parsing.spi.ParserTaskManager;\nimport org.antlr.netbeans.parsing.spi.ParserTaskProvider;\nimport org.antlr.netbeans.parsing.spi.ParserTaskScheduler;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.DefaultErrorStrategy;\nimport org.antlr.v4.runtime.ParserInterpreter;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenSource;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.Vocabulary;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNDeserializer;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.PredictionMode;\nimport org.antlr.v4.runtime.atn.RuleTransition;\nimport org.antlr.v4.runtime.atn.Transition;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.works.editor.antlr4.classification.TaggerTokenSource;\nimport org.antlr.works.editor.antlr4.parsing.DescriptiveErrorListener;\nimport org.antlr.works.editor.antlr4.parsing.SyntaxErrorListener;\nimport org.netbeans.api.editor.mimelookup.MimeRegistration;\n\n/**\n * @author Sam Harwell\n */\npublic final class ParserDebuggerReferenceAnchorsParserTask implements ParserTask {\n\n private final VersionedDocument document;\n\n private final Object lock = new Object();\n\n private ParserDebuggerReferenceAnchorsParserTask(VersionedDocument document) {\n this.document = document;\n }\n\n @Override\n public ParserTaskDefinition getDefinition() {\n return Definition.INSTANCE;\n }\n\n @Override\n public void parse(ParserTaskManager taskManager, ParseContext context, DocumentSnapshot snapshot, Collection> requestedData, ParserResultHandler results) throws InterruptedException, ExecutionException {\n // ParserDebuggerEditorKit.LEX\n synchronized (lock) {\n ParserData fileParseResultData = taskManager.getData(snapshot, ParserDebuggerParserDataDefinitions.FILE_PARSE_RESULT, EnumSet.of(ParserDataOptions.NO_UPDATE)).get();\n ParserData parseTreeResult = taskManager.getData(snapshot, ParserDebuggerParserDataDefinitions.REFERENCE_PARSE_TREE, EnumSet.of(ParserDataOptions.NO_UPDATE)).get();\n if (fileParseResultData == null || parseTreeResult == null) {\n Future>>> futureTokensData = taskManager.getData(snapshot, ParserDebuggerParserDataDefinitions.LEXER_TOKENS);\n Tagger> tagger = futureTokensData.get().getData();\n TaggerTokenSource tokenSource = new TaggerTokenSource(tagger, snapshot);\n InterruptableTokenStream tokenStream = new InterruptableTokenStream(tokenSource);\n ParserRuleContext parseResult;\n ParserInterpreterData parserInterpreterData = (ParserInterpreterData) snapshot.getVersionedDocument().getDocument().getProperty(ParserDebuggerEditorKit.PROP_PARSER_INTERP_DATA);\n String grammarFileName = parserInterpreterData.grammarFileName;\n Vocabulary vocabulary = parserInterpreterData.vocabulary;\n List ruleNames = parserInterpreterData.ruleNames;\n ATN atn = new ATNDeserializer().deserialize(parserInterpreterData.serializedAtn.toCharArray());\n TracingParserInterpreter parser = new TracingParserInterpreter(grammarFileName, vocabulary, ruleNames, atn, tokenStream);\n long startTime = System.nanoTime();\n parser.setInterpreter(new StatisticsParserATNSimulator(parser, atn));\n parser.getInterpreter().optimize_ll1 = false;\n parser.getInterpreter().reportAmbiguities = true;\n parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);\n parser.removeErrorListeners();\n parser.addErrorListener(DescriptiveErrorListener.INSTANCE);\n parser.addErrorListener(new StatisticsParserErrorListener());\n SyntaxErrorListener syntaxErrorListener = new SyntaxErrorListener(snapshot);\n parser.addErrorListener(syntaxErrorListener);\n parser.setBuildParseTree(true);\n parser.setErrorHandler(new DefaultErrorStrategy());\n parseResult = parser.parse(parserInterpreterData.startRuleIndex);\n String sourceName = (String) document.getDocument().getProperty(Document.TitleProperty);\n FileParseResult fileParseResult = new FileParseResult(sourceName, 0, parseResult, syntaxErrorListener.getSyntaxErrors(), tokenStream.size(), startTime, null, parser);\n fileParseResultData = new BaseParserData<>(context, ParserDebuggerParserDataDefinitions.FILE_PARSE_RESULT, snapshot, fileParseResult);\n parseTreeResult = new BaseParserData<>(context, ParserDebuggerParserDataDefinitions.REFERENCE_PARSE_TREE, snapshot, parseResult);\n }\n results.addResult(fileParseResultData);\n results.addResult(parseTreeResult);\n }\n }\n\n public static class TracingParserInterpreter extends ParserInterpreter {\n\n public final Map associatedTransitions = new IdentityHashMap<>();\n\n public TracingParserInterpreter(String grammarFileName, Vocabulary vocabulary, Collection ruleNames, ATN atn, TokenStream input) {\n super(grammarFileName, vocabulary, ruleNames, atn, input);\n }\n\n @Override\n protected void visitState(ATNState p) {\n super.visitState(p);\n if (p.getNumberOfTransitions() > 1) {\n return;\n }\n Transition transition = p.transition(0);\n if (transition instanceof RuleTransition) {\n // rule transition created a new context\n associatedTransitions.put(_ctx, transition);\n } else if (!p.onlyHasEpsilonTransitions()) {\n // match transition created a new terminal or error node\n associatedTransitions.put(_ctx.getChild(_ctx.getChildCount() - 1), transition);\n }\n }\n }\n\n private static class InterruptableTokenStream extends CommonTokenStream {\n\n public InterruptableTokenStream(TokenSource tokenSource) {\n super(tokenSource);\n }\n\n @Override\n public void consume() ", "post_mask_code": "\n }\n\n private static final class Definition extends ParserTaskDefinition {\n\n private static final Collection> INPUTS = Collections.>emptyList();\n\n private static final Collection> OUTPUTS = Arrays.>asList(ParserDebuggerParserDataDefinitions.FILE_PARSE_RESULT, ParserDebuggerParserDataDefinitions.REFERENCE_PARSE_TREE);\n\n public static final Definition INSTANCE = new Definition();\n\n public Definition() {\n super(\"Parser Debugger Reference Anchors\", INPUTS, OUTPUTS, ParserTaskScheduler.CONTENT_SENSITIVE_TASK_SCHEDULER);\n }\n }\n\n @MimeRegistration(mimeType = ParserDebuggerEditorKit.PARSER_DEBUGGER_MIME_TYPE, service = ParserTaskProvider.class)\n public static final class Provider extends DocumentParserTaskProvider {\n\n @Override\n public ParserTaskDefinition getDefinition() {\n return Definition.INSTANCE;\n }\n\n @Override\n public ParserTask createTaskImpl(VersionedDocument document) {\n return new ParserDebuggerReferenceAnchorsParserTask(document);\n }\n }\n}\n"} {"task_id": "Java_3125", "language": "Java", "task_type": "single_line", "source_file": "java/github/tunnelvisionlabs/antlrworks2/org-antlr-works-editor/src/org/antlr/works/editor/grammar/debugger/ParserDebuggerReferenceAnchorsParserTask.java", "mask_start_position": 9082, "mask_end_position": 9095, "canonical_solution": "sk(document);", "pre_mask_code": "/*\n * All rights reserved.\n *\n * The source code of this document is proprietary work, and is not licensed for\n * distribution. For information about licensing, contact Sam Harwell at:\n * example@nnthink.com\n */\npackage org.antlr.works.editor.grammar.debugger;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.EnumSet;\nimport java.util.IdentityHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.CancellationException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.Future;\nimport javax.swing.text.Document;\nimport org.antlr.netbeans.editor.classification.TokenTag;\nimport org.antlr.netbeans.editor.tagging.Tagger;\nimport org.antlr.netbeans.editor.text.DocumentSnapshot;\nimport org.antlr.netbeans.editor.text.VersionedDocument;\nimport org.antlr.netbeans.parsing.spi.BaseParserData;\nimport org.antlr.netbeans.parsing.spi.DocumentParserTaskProvider;\nimport org.antlr.netbeans.parsing.spi.ParseContext;\nimport org.antlr.netbeans.parsing.spi.ParserData;\nimport org.antlr.netbeans.parsing.spi.ParserDataDefinition;\nimport org.antlr.netbeans.parsing.spi.ParserDataOptions;\nimport org.antlr.netbeans.parsing.spi.ParserResultHandler;\nimport org.antlr.netbeans.parsing.spi.ParserTask;\nimport org.antlr.netbeans.parsing.spi.ParserTaskDefinition;\nimport org.antlr.netbeans.parsing.spi.ParserTaskManager;\nimport org.antlr.netbeans.parsing.spi.ParserTaskProvider;\nimport org.antlr.netbeans.parsing.spi.ParserTaskScheduler;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.DefaultErrorStrategy;\nimport org.antlr.v4.runtime.ParserInterpreter;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenSource;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.Vocabulary;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNDeserializer;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.PredictionMode;\nimport org.antlr.v4.runtime.atn.RuleTransition;\nimport org.antlr.v4.runtime.atn.Transition;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.works.editor.antlr4.classification.TaggerTokenSource;\nimport org.antlr.works.editor.antlr4.parsing.DescriptiveErrorListener;\nimport org.antlr.works.editor.antlr4.parsing.SyntaxErrorListener;\nimport org.netbeans.api.editor.mimelookup.MimeRegistration;\n\n/**\n * @author Sam Harwell\n */\npublic final class ParserDebuggerReferenceAnchorsParserTask implements ParserTask {\n\n private final VersionedDocument document;\n\n private final Object lock = new Object();\n\n private ParserDebuggerReferenceAnchorsParserTask(VersionedDocument document) {\n this.document = document;\n }\n\n @Override\n public ParserTaskDefinition getDefinition() {\n return Definition.INSTANCE;\n }\n\n @Override\n public void parse(ParserTaskManager taskManager, ParseContext context, DocumentSnapshot snapshot, Collection> requestedData, ParserResultHandler results) throws InterruptedException, ExecutionException {\n // ParserDebuggerEditorKit.LEX\n synchronized (lock) {\n ParserData fileParseResultData = taskManager.getData(snapshot, ParserDebuggerParserDataDefinitions.FILE_PARSE_RESULT, EnumSet.of(ParserDataOptions.NO_UPDATE)).get();\n ParserData parseTreeResult = taskManager.getData(snapshot, ParserDebuggerParserDataDefinitions.REFERENCE_PARSE_TREE, EnumSet.of(ParserDataOptions.NO_UPDATE)).get();\n if (fileParseResultData == null || parseTreeResult == null) {\n Future>>> futureTokensData = taskManager.getData(snapshot, ParserDebuggerParserDataDefinitions.LEXER_TOKENS);\n Tagger> tagger = futureTokensData.get().getData();\n TaggerTokenSource tokenSource = new TaggerTokenSource(tagger, snapshot);\n InterruptableTokenStream tokenStream = new InterruptableTokenStream(tokenSource);\n ParserRuleContext parseResult;\n ParserInterpreterData parserInterpreterData = (ParserInterpreterData) snapshot.getVersionedDocument().getDocument().getProperty(ParserDebuggerEditorKit.PROP_PARSER_INTERP_DATA);\n String grammarFileName = parserInterpreterData.grammarFileName;\n Vocabulary vocabulary = parserInterpreterData.vocabulary;\n List ruleNames = parserInterpreterData.ruleNames;\n ATN atn = new ATNDeserializer().deserialize(parserInterpreterData.serializedAtn.toCharArray());\n TracingParserInterpreter parser = new TracingParserInterpreter(grammarFileName, vocabulary, ruleNames, atn, tokenStream);\n long startTime = System.nanoTime();\n parser.setInterpreter(new StatisticsParserATNSimulator(parser, atn));\n parser.getInterpreter().optimize_ll1 = false;\n parser.getInterpreter().reportAmbiguities = true;\n parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);\n parser.removeErrorListeners();\n parser.addErrorListener(DescriptiveErrorListener.INSTANCE);\n parser.addErrorListener(new StatisticsParserErrorListener());\n SyntaxErrorListener syntaxErrorListener = new SyntaxErrorListener(snapshot);\n parser.addErrorListener(syntaxErrorListener);\n parser.setBuildParseTree(true);\n parser.setErrorHandler(new DefaultErrorStrategy());\n parseResult = parser.parse(parserInterpreterData.startRuleIndex);\n String sourceName = (String) document.getDocument().getProperty(Document.TitleProperty);\n FileParseResult fileParseResult = new FileParseResult(sourceName, 0, parseResult, syntaxErrorListener.getSyntaxErrors(), tokenStream.size(), startTime, null, parser);\n fileParseResultData = new BaseParserData<>(context, ParserDebuggerParserDataDefinitions.FILE_PARSE_RESULT, snapshot, fileParseResult);\n parseTreeResult = new BaseParserData<>(context, ParserDebuggerParserDataDefinitions.REFERENCE_PARSE_TREE, snapshot, parseResult);\n }\n results.addResult(fileParseResultData);\n results.addResult(parseTreeResult);\n }\n }\n\n public static class TracingParserInterpreter extends ParserInterpreter {\n\n public final Map associatedTransitions = new IdentityHashMap<>();\n\n public TracingParserInterpreter(String grammarFileName, Vocabulary vocabulary, Collection ruleNames, ATN atn, TokenStream input) {\n super(grammarFileName, vocabulary, ruleNames, atn, input);\n }\n\n @Override\n protected void visitState(ATNState p) {\n super.visitState(p);\n if (p.getNumberOfTransitions() > 1) {\n return;\n }\n Transition transition = p.transition(0);\n if (transition instanceof RuleTransition) {\n // rule transition created a new context\n associatedTransitions.put(_ctx, transition);\n } else if (!p.onlyHasEpsilonTransitions()) {\n // match transition created a new terminal or error node\n associatedTransitions.put(_ctx.getChild(_ctx.getChildCount() - 1), transition);\n }\n }\n }\n\n private static class InterruptableTokenStream extends CommonTokenStream {\n\n public InterruptableTokenStream(TokenSource tokenSource) {\n super(tokenSource);\n }\n\n @Override\n public void consume() {\n if (Thread.interrupted()) {\n throw new CancellationException();\n }\n super.consume();\n }\n }\n\n private static final class Definition extends ParserTaskDefinition {\n\n private static final Collection> INPUTS = Collections.>emptyList();\n\n private static final Collection> OUTPUTS = Arrays.>asList(ParserDebuggerParserDataDefinitions.FILE_PARSE_RESULT, ParserDebuggerParserDataDefinitions.REFERENCE_PARSE_TREE);\n\n public static final Definition INSTANCE = new Definition();\n\n public Definition() {\n super(\"Parser Debugger Reference Anchors\", INPUTS, OUTPUTS, ParserTaskScheduler.CONTENT_SENSITIVE_TASK_SCHEDULER);\n }\n }\n\n @MimeRegistration(mimeType = ParserDebuggerEditorKit.PARSER_DEBUGGER_MIME_TYPE, service = ParserTaskProvider.class)\n public static final class Provider extends DocumentParserTaskProvider {\n\n @Override\n public ParserTaskDefinition getDefinition() {\n return Definition.INSTANCE;\n }\n\n @Override\n public ParserTask createTaskImpl(VersionedDocument document) {\n return new ParserDebuggerReferenceAnchorsParserTa", "post_mask_code": "\n }\n }\n}\n"} {"task_id": "Java_3126", "language": "Java", "task_type": "method_signature", "source_file": "java/github/verhas/javageci/javageci-examples/src/main/java/javax0/geci/tests/mapper/AbstractPerson.java", "mask_start_position": 228, "mask_end_position": 274, "canonical_solution": "@Override\n public boolean equals(Object o) ", "pre_mask_code": "package javax0.geci.tests.mapper;\n\npublic class AbstractPerson {\n\n public boolean willMapPublicInherited;\n\n protected int willMapProtectedInherited;\n\n float willMapDefaultInherited;\n\n private String willNotMap;\n\n ", "post_mask_code": "{\n if (this == o)\n return true;\n if (!(o instanceof AbstractPerson))\n return false;\n AbstractPerson other = (AbstractPerson) o;\n if (willMapPublicInherited != other.willMapPublicInherited)\n return false;\n if (willMapProtectedInherited != other.willMapProtectedInherited)\n return false;\n return (willMapDefaultInherited == other.willMapDefaultInherited);\n }\n}\n"} {"task_id": "Java_3127", "language": "Java", "task_type": "method_body", "source_file": "java/github/verhas/javageci/javageci-examples/src/main/java/javax0/geci/tests/mapper/AbstractPerson.java", "mask_start_position": 274, "mask_end_position": 719, "canonical_solution": "{\n if (this == o)\n return true;\n if (!(o instanceof AbstractPerson))\n return false;\n AbstractPerson other = (AbstractPerson) o;\n if (willMapPublicInherited != other.willMapPublicInherited)\n return false;\n if (willMapProtectedInherited != other.willMapProtectedInherited)\n return false;\n return (willMapDefaultInherited == other.willMapDefaultInherited);\n }", "pre_mask_code": "package javax0.geci.tests.mapper;\n\npublic class AbstractPerson {\n\n public boolean willMapPublicInherited;\n\n protected int willMapProtectedInherited;\n\n float willMapDefaultInherited;\n\n private String willNotMap;\n\n @Override\n public boolean equals(Object o) ", "post_mask_code": "\n}\n"} {"task_id": "Java_3128", "language": "Java", "task_type": "single_line", "source_file": "java/github/verhas/javageci/javageci-examples/src/main/java/javax0/geci/tests/mapper/AbstractPerson.java", "mask_start_position": 703, "mask_end_position": 713, "canonical_solution": "nherited);", "pre_mask_code": "package javax0.geci.tests.mapper;\n\npublic class AbstractPerson {\n\n public boolean willMapPublicInherited;\n\n protected int willMapProtectedInherited;\n\n float willMapDefaultInherited;\n\n private String willNotMap;\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (!(o instanceof AbstractPerson))\n return false;\n AbstractPerson other = (AbstractPerson) o;\n if (willMapPublicInherited != other.willMapPublicInherited)\n return false;\n if (willMapProtectedInherited != other.willMapProtectedInherited)\n return false;\n return (willMapDefaultInherited == other.willMapDefaultI", "post_mask_code": "\n }\n}\n"} {"task_id": "Java_3129", "language": "Java", "task_type": "method_signature", "source_file": "java/github/adorsys/xs2a/xs2a-impl/src/main/java/de/adorsys/psd2/xs2a/web/controller/ConsentController.java", "mask_start_position": 11110, "mask_end_position": 11478, "canonical_solution": "@Override\n public ResponseEntity deleteConsent(String consentId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) ", "pre_mask_code": "package de.adorsys.psd2.xs2a.web.controller;\n\nimport de.adorsys.psd2.api.ConsentApi;\nimport de.adorsys.psd2.core.data.ais.AisConsent;\nimport de.adorsys.psd2.model.Consents;\nimport de.adorsys.psd2.xs2a.core.psu.AdditionalPsuIdData;\nimport de.adorsys.psd2.xs2a.core.psu.PsuIdData;\nimport de.adorsys.psd2.xs2a.core.tpp.TppNotificationData;\nimport de.adorsys.psd2.xs2a.core.tpp.TppRedirectUri;\nimport de.adorsys.psd2.xs2a.domain.HrefType;\nimport de.adorsys.psd2.xs2a.domain.NotificationModeResponseHeaders;\nimport de.adorsys.psd2.xs2a.domain.ResponseObject;\nimport de.adorsys.psd2.xs2a.domain.authorisation.AuthorisationResponse;\nimport de.adorsys.psd2.xs2a.domain.consent.*;\nimport de.adorsys.psd2.xs2a.service.ConsentService;\nimport de.adorsys.psd2.xs2a.service.NotificationSupportedModeService;\nimport de.adorsys.psd2.xs2a.service.RequestProviderService;\nimport de.adorsys.psd2.xs2a.service.mapper.ResponseMapper;\nimport de.adorsys.psd2.xs2a.service.mapper.psd2.ResponseErrorMapper;\nimport de.adorsys.psd2.xs2a.web.header.ConsentHeadersBuilder;\nimport de.adorsys.psd2.xs2a.web.header.ResponseHeaders;\nimport de.adorsys.psd2.xs2a.web.mapper.AuthorisationMapper;\nimport de.adorsys.psd2.xs2a.web.mapper.ConsentModelMapper;\nimport de.adorsys.psd2.xs2a.web.mapper.TppRedirectUriMapper;\nimport lombok.AllArgsConstructor;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.BooleanUtils;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.RestController;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.UUID;\n\n// This class implements autogenerated interface without proper return values generated\n@SuppressWarnings(\"unchecked\")\n@Slf4j\n@RestController\n@AllArgsConstructor\npublic class ConsentController implements ConsentApi {\n\n private final ConsentService consentService;\n\n private final ResponseMapper responseMapper;\n\n private final ConsentModelMapper consentModelMapper;\n\n private final AuthorisationMapper authorisationMapper;\n\n private final TppRedirectUriMapper tppRedirectUriMapper;\n\n private final ResponseErrorMapper responseErrorMapper;\n\n private final ConsentHeadersBuilder consentHeadersBuilder;\n\n private final NotificationSupportedModeService notificationSupportedModeService;\n\n private final RequestProviderService requestProviderService;\n\n @Override\n public ResponseEntity createConsent(UUID xRequestID, String psuIpAddress, Consents body, String digest, String signature, byte[] tppSignatureCertificate, String psuId, String psuIdType, String psuCorporateId, String psuCorporateIdType, Boolean tppRedirectPreferred, Boolean tppDecoupledPreferred, String tppRedirectUri, String tppNokRedirectUri, Boolean tppExplicitAuthorisationPreferred, String tppBrandLoggingInformation, String tppNotificationUri, String tppNotificationContentPreferred, String psuIpPort, String psuAccept, String psuAcceptCharset, String psuAcceptEncoding, String psuAcceptLanguage, String psuUserAgent, String psuHttpMethod, UUID psuDeviceId, String psuGeoLocation) {\n TppRedirectUri xs2aTppRedirectUri = tppRedirectUriMapper.mapToTppRedirectUri(tppRedirectUri, tppNokRedirectUri);\n TppNotificationData tppNotificationData = notificationSupportedModeService.getTppNotificationData(tppNotificationContentPreferred, tppNotificationUri);\n CreateConsentReq createConsent = consentModelMapper.mapToCreateConsentReq(body, xs2aTppRedirectUri, tppNotificationData, tppBrandLoggingInformation, requestProviderService.getInstanceId());\n PsuIdData psuData = new PsuIdData(psuId, psuIdType, psuCorporateId, psuCorporateIdType, psuIpAddress, new AdditionalPsuIdData(psuIpPort, psuUserAgent, psuGeoLocation, psuAccept, psuAcceptCharset, psuAcceptEncoding, psuAcceptLanguage, psuHttpMethod, psuDeviceId));\n ResponseObject createResponse = consentService.createAccountConsentsWithResponse(createConsent, psuData, BooleanUtils.isTrue(tppExplicitAuthorisationPreferred));\n if (createResponse.hasError()) {\n return responseErrorMapper.generateErrorResponse(createResponse.getError());\n }\n CreateConsentResponse createConsentResponse = createResponse.getBody();\n NotificationModeResponseHeaders notificationHeaders = notificationSupportedModeService.resolveNotificationHeaders(createConsentResponse.getTppNotificationContentPreferred());\n ResponseHeaders headers = consentHeadersBuilder.buildCreateConsentHeaders(createConsentResponse.getAuthorizationId(), Optional.ofNullable(createConsentResponse.getLinks().getSelf()).map(HrefType::getHref).orElseThrow(() -> new IllegalArgumentException(\"Wrong href type in self link\")), notificationHeaders);\n return responseMapper.created(createResponse, consentModelMapper::mapToConsentsResponse201, headers);\n }\n\n @Override\n public ResponseEntity getConsentStatus(String consentId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject accountConsentsStatusByIdResponse = consentService.getAccountConsentsStatusById(consentId);\n return accountConsentsStatusByIdResponse.hasError() ? responseErrorMapper.generateErrorResponse(accountConsentsStatusByIdResponse.getError()) : responseMapper.ok(accountConsentsStatusByIdResponse, consentModelMapper::mapToConsentStatusResponse200);\n }\n\n @Override\n public ResponseEntity startConsentAuthorisation(UUID xRequestID, String consentId, Object body, String digest, String signature, byte[] tpPSignatureCertificate, String psuId, String psUIDType, String psUCorporateID, String psUCorporateIDType, Boolean tppRedirectPreferred, Boolean tppDecoupledPreferred, String tpPRedirectURI, String tpPNokRedirectURI, String tpPNotificationURI, String tpPNotificationContentPreferred, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n PsuIdData psuData = new PsuIdData(psuId, psUIDType, psUCorporateID, psUCorporateIDType, psUIPAddress);\n String password = authorisationMapper.mapToPasswordFromBody((Map) body);\n ResponseObject createResponse = consentService.createAisAuthorisation(psuData, consentId, password);\n if (createResponse.hasError()) {\n return responseErrorMapper.generateErrorResponse(createResponse.getError());\n }\n AuthorisationResponse authorisationResponse = createResponse.getBody();\n ResponseHeaders responseHeaders = consentHeadersBuilder.buildStartAuthorisationHeaders(authorisationResponse.getAuthorisationId());\n return responseMapper.created(ResponseObject.builder().body(authorisationMapper.mapToConsentCreateOrUpdateAuthorisationResponse(createResponse)).build(), responseHeaders);\n }\n\n @Override\n public ResponseEntity updateConsentsPsuData(UUID xRequestID, String consentId, String authorisationId, Object body, String digest, String signature, byte[] tpPSignatureCertificate, String psuId, String psUIDType, String psUCorporateID, String psUCorporateIDType, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n PsuIdData psuData = new PsuIdData(psuId, psUIDType, psUCorporateID, psUCorporateIDType, psUIPAddress);\n return updateAisAuthorisation(psuData, authorisationId, consentId, body);\n }\n\n private ResponseEntity updateAisAuthorisation(PsuIdData psuData, String authorisationId, String consentId, Object body) {\n ConsentAuthorisationsParameters updatePsuDataRequest = consentModelMapper.mapToUpdatePsuData(psuData, consentId, authorisationId, (Map) body);\n ResponseObject updateConsentPsuDataResponse = consentService.updateConsentPsuData(updatePsuDataRequest);\n if (updateConsentPsuDataResponse.hasError()) {\n return responseErrorMapper.generateErrorResponse(updateConsentPsuDataResponse.getError());\n }\n ResponseHeaders responseHeaders = consentHeadersBuilder.buildUpdatePsuDataHeaders(authorisationId);\n return responseMapper.ok(updateConsentPsuDataResponse, authorisationMapper::mapToConsentUpdatePsuAuthenticationResponse, responseHeaders);\n }\n\n @Override\n public ResponseEntity getConsentScaStatus(String consentId, String authorisationId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject consentAuthorisationScaStatusResponse = consentService.getConsentAuthorisationScaStatus(consentId, authorisationId);\n return consentAuthorisationScaStatusResponse.hasError() ? responseErrorMapper.generateErrorResponse(consentAuthorisationScaStatusResponse.getError()) : responseMapper.ok(consentAuthorisationScaStatusResponse, authorisationMapper::mapToScaStatusResponse);\n }\n\n @Override\n public ResponseEntity getConsentAuthorisation(String consentId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject consentInitiationAuthorisationsResponse = consentService.getConsentInitiationAuthorisations(consentId);\n return consentInitiationAuthorisationsResponse.hasError() ? responseErrorMapper.generateErrorResponse(consentInitiationAuthorisationsResponse.getError()) : responseMapper.ok(consentInitiationAuthorisationsResponse, authorisationMapper::mapToAuthorisations);\n }\n\n @Override\n public ResponseEntity getConsentInformation(String consentId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject accountConsentByIdResponse = consentService.getAccountConsentById(consentId);\n return accountConsentByIdResponse.hasError() ? responseErrorMapper.generateErrorResponse(accountConsentByIdResponse.getError()) : responseMapper.ok(accountConsentByIdResponse, consentModelMapper::mapToConsentInformationResponse200Json);\n }\n\n ", "post_mask_code": "{\n ResponseObject response = consentService.deleteAccountConsentsById(consentId);\n return response.hasError() ? responseErrorMapper.generateErrorResponse(response.getError()) : responseMapper.delete(response);\n }\n}\n"} {"task_id": "Java_3130", "language": "Java", "task_type": "method_body", "source_file": "java/github/adorsys/xs2a/xs2a-impl/src/main/java/de/adorsys/psd2/xs2a/web/controller/ConsentController.java", "mask_start_position": 11478, "mask_end_position": 11713, "canonical_solution": "{\n ResponseObject response = consentService.deleteAccountConsentsById(consentId);\n return response.hasError() ? responseErrorMapper.generateErrorResponse(response.getError()) : responseMapper.delete(response);\n }", "pre_mask_code": "package de.adorsys.psd2.xs2a.web.controller;\n\nimport de.adorsys.psd2.api.ConsentApi;\nimport de.adorsys.psd2.core.data.ais.AisConsent;\nimport de.adorsys.psd2.model.Consents;\nimport de.adorsys.psd2.xs2a.core.psu.AdditionalPsuIdData;\nimport de.adorsys.psd2.xs2a.core.psu.PsuIdData;\nimport de.adorsys.psd2.xs2a.core.tpp.TppNotificationData;\nimport de.adorsys.psd2.xs2a.core.tpp.TppRedirectUri;\nimport de.adorsys.psd2.xs2a.domain.HrefType;\nimport de.adorsys.psd2.xs2a.domain.NotificationModeResponseHeaders;\nimport de.adorsys.psd2.xs2a.domain.ResponseObject;\nimport de.adorsys.psd2.xs2a.domain.authorisation.AuthorisationResponse;\nimport de.adorsys.psd2.xs2a.domain.consent.*;\nimport de.adorsys.psd2.xs2a.service.ConsentService;\nimport de.adorsys.psd2.xs2a.service.NotificationSupportedModeService;\nimport de.adorsys.psd2.xs2a.service.RequestProviderService;\nimport de.adorsys.psd2.xs2a.service.mapper.ResponseMapper;\nimport de.adorsys.psd2.xs2a.service.mapper.psd2.ResponseErrorMapper;\nimport de.adorsys.psd2.xs2a.web.header.ConsentHeadersBuilder;\nimport de.adorsys.psd2.xs2a.web.header.ResponseHeaders;\nimport de.adorsys.psd2.xs2a.web.mapper.AuthorisationMapper;\nimport de.adorsys.psd2.xs2a.web.mapper.ConsentModelMapper;\nimport de.adorsys.psd2.xs2a.web.mapper.TppRedirectUriMapper;\nimport lombok.AllArgsConstructor;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.BooleanUtils;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.RestController;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.UUID;\n\n// This class implements autogenerated interface without proper return values generated\n@SuppressWarnings(\"unchecked\")\n@Slf4j\n@RestController\n@AllArgsConstructor\npublic class ConsentController implements ConsentApi {\n\n private final ConsentService consentService;\n\n private final ResponseMapper responseMapper;\n\n private final ConsentModelMapper consentModelMapper;\n\n private final AuthorisationMapper authorisationMapper;\n\n private final TppRedirectUriMapper tppRedirectUriMapper;\n\n private final ResponseErrorMapper responseErrorMapper;\n\n private final ConsentHeadersBuilder consentHeadersBuilder;\n\n private final NotificationSupportedModeService notificationSupportedModeService;\n\n private final RequestProviderService requestProviderService;\n\n @Override\n public ResponseEntity createConsent(UUID xRequestID, String psuIpAddress, Consents body, String digest, String signature, byte[] tppSignatureCertificate, String psuId, String psuIdType, String psuCorporateId, String psuCorporateIdType, Boolean tppRedirectPreferred, Boolean tppDecoupledPreferred, String tppRedirectUri, String tppNokRedirectUri, Boolean tppExplicitAuthorisationPreferred, String tppBrandLoggingInformation, String tppNotificationUri, String tppNotificationContentPreferred, String psuIpPort, String psuAccept, String psuAcceptCharset, String psuAcceptEncoding, String psuAcceptLanguage, String psuUserAgent, String psuHttpMethod, UUID psuDeviceId, String psuGeoLocation) {\n TppRedirectUri xs2aTppRedirectUri = tppRedirectUriMapper.mapToTppRedirectUri(tppRedirectUri, tppNokRedirectUri);\n TppNotificationData tppNotificationData = notificationSupportedModeService.getTppNotificationData(tppNotificationContentPreferred, tppNotificationUri);\n CreateConsentReq createConsent = consentModelMapper.mapToCreateConsentReq(body, xs2aTppRedirectUri, tppNotificationData, tppBrandLoggingInformation, requestProviderService.getInstanceId());\n PsuIdData psuData = new PsuIdData(psuId, psuIdType, psuCorporateId, psuCorporateIdType, psuIpAddress, new AdditionalPsuIdData(psuIpPort, psuUserAgent, psuGeoLocation, psuAccept, psuAcceptCharset, psuAcceptEncoding, psuAcceptLanguage, psuHttpMethod, psuDeviceId));\n ResponseObject createResponse = consentService.createAccountConsentsWithResponse(createConsent, psuData, BooleanUtils.isTrue(tppExplicitAuthorisationPreferred));\n if (createResponse.hasError()) {\n return responseErrorMapper.generateErrorResponse(createResponse.getError());\n }\n CreateConsentResponse createConsentResponse = createResponse.getBody();\n NotificationModeResponseHeaders notificationHeaders = notificationSupportedModeService.resolveNotificationHeaders(createConsentResponse.getTppNotificationContentPreferred());\n ResponseHeaders headers = consentHeadersBuilder.buildCreateConsentHeaders(createConsentResponse.getAuthorizationId(), Optional.ofNullable(createConsentResponse.getLinks().getSelf()).map(HrefType::getHref).orElseThrow(() -> new IllegalArgumentException(\"Wrong href type in self link\")), notificationHeaders);\n return responseMapper.created(createResponse, consentModelMapper::mapToConsentsResponse201, headers);\n }\n\n @Override\n public ResponseEntity getConsentStatus(String consentId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject accountConsentsStatusByIdResponse = consentService.getAccountConsentsStatusById(consentId);\n return accountConsentsStatusByIdResponse.hasError() ? responseErrorMapper.generateErrorResponse(accountConsentsStatusByIdResponse.getError()) : responseMapper.ok(accountConsentsStatusByIdResponse, consentModelMapper::mapToConsentStatusResponse200);\n }\n\n @Override\n public ResponseEntity startConsentAuthorisation(UUID xRequestID, String consentId, Object body, String digest, String signature, byte[] tpPSignatureCertificate, String psuId, String psUIDType, String psUCorporateID, String psUCorporateIDType, Boolean tppRedirectPreferred, Boolean tppDecoupledPreferred, String tpPRedirectURI, String tpPNokRedirectURI, String tpPNotificationURI, String tpPNotificationContentPreferred, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n PsuIdData psuData = new PsuIdData(psuId, psUIDType, psUCorporateID, psUCorporateIDType, psUIPAddress);\n String password = authorisationMapper.mapToPasswordFromBody((Map) body);\n ResponseObject createResponse = consentService.createAisAuthorisation(psuData, consentId, password);\n if (createResponse.hasError()) {\n return responseErrorMapper.generateErrorResponse(createResponse.getError());\n }\n AuthorisationResponse authorisationResponse = createResponse.getBody();\n ResponseHeaders responseHeaders = consentHeadersBuilder.buildStartAuthorisationHeaders(authorisationResponse.getAuthorisationId());\n return responseMapper.created(ResponseObject.builder().body(authorisationMapper.mapToConsentCreateOrUpdateAuthorisationResponse(createResponse)).build(), responseHeaders);\n }\n\n @Override\n public ResponseEntity updateConsentsPsuData(UUID xRequestID, String consentId, String authorisationId, Object body, String digest, String signature, byte[] tpPSignatureCertificate, String psuId, String psUIDType, String psUCorporateID, String psUCorporateIDType, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n PsuIdData psuData = new PsuIdData(psuId, psUIDType, psUCorporateID, psUCorporateIDType, psUIPAddress);\n return updateAisAuthorisation(psuData, authorisationId, consentId, body);\n }\n\n private ResponseEntity updateAisAuthorisation(PsuIdData psuData, String authorisationId, String consentId, Object body) {\n ConsentAuthorisationsParameters updatePsuDataRequest = consentModelMapper.mapToUpdatePsuData(psuData, consentId, authorisationId, (Map) body);\n ResponseObject updateConsentPsuDataResponse = consentService.updateConsentPsuData(updatePsuDataRequest);\n if (updateConsentPsuDataResponse.hasError()) {\n return responseErrorMapper.generateErrorResponse(updateConsentPsuDataResponse.getError());\n }\n ResponseHeaders responseHeaders = consentHeadersBuilder.buildUpdatePsuDataHeaders(authorisationId);\n return responseMapper.ok(updateConsentPsuDataResponse, authorisationMapper::mapToConsentUpdatePsuAuthenticationResponse, responseHeaders);\n }\n\n @Override\n public ResponseEntity getConsentScaStatus(String consentId, String authorisationId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject consentAuthorisationScaStatusResponse = consentService.getConsentAuthorisationScaStatus(consentId, authorisationId);\n return consentAuthorisationScaStatusResponse.hasError() ? responseErrorMapper.generateErrorResponse(consentAuthorisationScaStatusResponse.getError()) : responseMapper.ok(consentAuthorisationScaStatusResponse, authorisationMapper::mapToScaStatusResponse);\n }\n\n @Override\n public ResponseEntity getConsentAuthorisation(String consentId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject consentInitiationAuthorisationsResponse = consentService.getConsentInitiationAuthorisations(consentId);\n return consentInitiationAuthorisationsResponse.hasError() ? responseErrorMapper.generateErrorResponse(consentInitiationAuthorisationsResponse.getError()) : responseMapper.ok(consentInitiationAuthorisationsResponse, authorisationMapper::mapToAuthorisations);\n }\n\n @Override\n public ResponseEntity getConsentInformation(String consentId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject accountConsentByIdResponse = consentService.getAccountConsentById(consentId);\n return accountConsentByIdResponse.hasError() ? responseErrorMapper.generateErrorResponse(accountConsentByIdResponse.getError()) : responseMapper.ok(accountConsentByIdResponse, consentModelMapper::mapToConsentInformationResponse200Json);\n }\n\n @Override\n public ResponseEntity deleteConsent(String consentId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) ", "post_mask_code": "\n}\n"} {"task_id": "Java_3131", "language": "Java", "task_type": "single_line", "source_file": "java/github/adorsys/xs2a/xs2a-impl/src/main/java/de/adorsys/psd2/xs2a/web/controller/ConsentController.java", "mask_start_position": 6349, "mask_end_position": 6387, "canonical_solution": "ID, psUCorporateIDType, psUIPAddress);", "pre_mask_code": "package de.adorsys.psd2.xs2a.web.controller;\n\nimport de.adorsys.psd2.api.ConsentApi;\nimport de.adorsys.psd2.core.data.ais.AisConsent;\nimport de.adorsys.psd2.model.Consents;\nimport de.adorsys.psd2.xs2a.core.psu.AdditionalPsuIdData;\nimport de.adorsys.psd2.xs2a.core.psu.PsuIdData;\nimport de.adorsys.psd2.xs2a.core.tpp.TppNotificationData;\nimport de.adorsys.psd2.xs2a.core.tpp.TppRedirectUri;\nimport de.adorsys.psd2.xs2a.domain.HrefType;\nimport de.adorsys.psd2.xs2a.domain.NotificationModeResponseHeaders;\nimport de.adorsys.psd2.xs2a.domain.ResponseObject;\nimport de.adorsys.psd2.xs2a.domain.authorisation.AuthorisationResponse;\nimport de.adorsys.psd2.xs2a.domain.consent.*;\nimport de.adorsys.psd2.xs2a.service.ConsentService;\nimport de.adorsys.psd2.xs2a.service.NotificationSupportedModeService;\nimport de.adorsys.psd2.xs2a.service.RequestProviderService;\nimport de.adorsys.psd2.xs2a.service.mapper.ResponseMapper;\nimport de.adorsys.psd2.xs2a.service.mapper.psd2.ResponseErrorMapper;\nimport de.adorsys.psd2.xs2a.web.header.ConsentHeadersBuilder;\nimport de.adorsys.psd2.xs2a.web.header.ResponseHeaders;\nimport de.adorsys.psd2.xs2a.web.mapper.AuthorisationMapper;\nimport de.adorsys.psd2.xs2a.web.mapper.ConsentModelMapper;\nimport de.adorsys.psd2.xs2a.web.mapper.TppRedirectUriMapper;\nimport lombok.AllArgsConstructor;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.BooleanUtils;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.RestController;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.UUID;\n\n// This class implements autogenerated interface without proper return values generated\n@SuppressWarnings(\"unchecked\")\n@Slf4j\n@RestController\n@AllArgsConstructor\npublic class ConsentController implements ConsentApi {\n\n private final ConsentService consentService;\n\n private final ResponseMapper responseMapper;\n\n private final ConsentModelMapper consentModelMapper;\n\n private final AuthorisationMapper authorisationMapper;\n\n private final TppRedirectUriMapper tppRedirectUriMapper;\n\n private final ResponseErrorMapper responseErrorMapper;\n\n private final ConsentHeadersBuilder consentHeadersBuilder;\n\n private final NotificationSupportedModeService notificationSupportedModeService;\n\n private final RequestProviderService requestProviderService;\n\n @Override\n public ResponseEntity createConsent(UUID xRequestID, String psuIpAddress, Consents body, String digest, String signature, byte[] tppSignatureCertificate, String psuId, String psuIdType, String psuCorporateId, String psuCorporateIdType, Boolean tppRedirectPreferred, Boolean tppDecoupledPreferred, String tppRedirectUri, String tppNokRedirectUri, Boolean tppExplicitAuthorisationPreferred, String tppBrandLoggingInformation, String tppNotificationUri, String tppNotificationContentPreferred, String psuIpPort, String psuAccept, String psuAcceptCharset, String psuAcceptEncoding, String psuAcceptLanguage, String psuUserAgent, String psuHttpMethod, UUID psuDeviceId, String psuGeoLocation) {\n TppRedirectUri xs2aTppRedirectUri = tppRedirectUriMapper.mapToTppRedirectUri(tppRedirectUri, tppNokRedirectUri);\n TppNotificationData tppNotificationData = notificationSupportedModeService.getTppNotificationData(tppNotificationContentPreferred, tppNotificationUri);\n CreateConsentReq createConsent = consentModelMapper.mapToCreateConsentReq(body, xs2aTppRedirectUri, tppNotificationData, tppBrandLoggingInformation, requestProviderService.getInstanceId());\n PsuIdData psuData = new PsuIdData(psuId, psuIdType, psuCorporateId, psuCorporateIdType, psuIpAddress, new AdditionalPsuIdData(psuIpPort, psuUserAgent, psuGeoLocation, psuAccept, psuAcceptCharset, psuAcceptEncoding, psuAcceptLanguage, psuHttpMethod, psuDeviceId));\n ResponseObject createResponse = consentService.createAccountConsentsWithResponse(createConsent, psuData, BooleanUtils.isTrue(tppExplicitAuthorisationPreferred));\n if (createResponse.hasError()) {\n return responseErrorMapper.generateErrorResponse(createResponse.getError());\n }\n CreateConsentResponse createConsentResponse = createResponse.getBody();\n NotificationModeResponseHeaders notificationHeaders = notificationSupportedModeService.resolveNotificationHeaders(createConsentResponse.getTppNotificationContentPreferred());\n ResponseHeaders headers = consentHeadersBuilder.buildCreateConsentHeaders(createConsentResponse.getAuthorizationId(), Optional.ofNullable(createConsentResponse.getLinks().getSelf()).map(HrefType::getHref).orElseThrow(() -> new IllegalArgumentException(\"Wrong href type in self link\")), notificationHeaders);\n return responseMapper.created(createResponse, consentModelMapper::mapToConsentsResponse201, headers);\n }\n\n @Override\n public ResponseEntity getConsentStatus(String consentId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject accountConsentsStatusByIdResponse = consentService.getAccountConsentsStatusById(consentId);\n return accountConsentsStatusByIdResponse.hasError() ? responseErrorMapper.generateErrorResponse(accountConsentsStatusByIdResponse.getError()) : responseMapper.ok(accountConsentsStatusByIdResponse, consentModelMapper::mapToConsentStatusResponse200);\n }\n\n @Override\n public ResponseEntity startConsentAuthorisation(UUID xRequestID, String consentId, Object body, String digest, String signature, byte[] tpPSignatureCertificate, String psuId, String psUIDType, String psUCorporateID, String psUCorporateIDType, Boolean tppRedirectPreferred, Boolean tppDecoupledPreferred, String tpPRedirectURI, String tpPNokRedirectURI, String tpPNotificationURI, String tpPNotificationContentPreferred, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n PsuIdData psuData = new PsuIdData(psuId, psUIDType, psUCorporate", "post_mask_code": "\n String password = authorisationMapper.mapToPasswordFromBody((Map) body);\n ResponseObject createResponse = consentService.createAisAuthorisation(psuData, consentId, password);\n if (createResponse.hasError()) {\n return responseErrorMapper.generateErrorResponse(createResponse.getError());\n }\n AuthorisationResponse authorisationResponse = createResponse.getBody();\n ResponseHeaders responseHeaders = consentHeadersBuilder.buildStartAuthorisationHeaders(authorisationResponse.getAuthorisationId());\n return responseMapper.created(ResponseObject.builder().body(authorisationMapper.mapToConsentCreateOrUpdateAuthorisationResponse(createResponse)).build(), responseHeaders);\n }\n\n @Override\n public ResponseEntity updateConsentsPsuData(UUID xRequestID, String consentId, String authorisationId, Object body, String digest, String signature, byte[] tpPSignatureCertificate, String psuId, String psUIDType, String psUCorporateID, String psUCorporateIDType, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n PsuIdData psuData = new PsuIdData(psuId, psUIDType, psUCorporateID, psUCorporateIDType, psUIPAddress);\n return updateAisAuthorisation(psuData, authorisationId, consentId, body);\n }\n\n private ResponseEntity updateAisAuthorisation(PsuIdData psuData, String authorisationId, String consentId, Object body) {\n ConsentAuthorisationsParameters updatePsuDataRequest = consentModelMapper.mapToUpdatePsuData(psuData, consentId, authorisationId, (Map) body);\n ResponseObject updateConsentPsuDataResponse = consentService.updateConsentPsuData(updatePsuDataRequest);\n if (updateConsentPsuDataResponse.hasError()) {\n return responseErrorMapper.generateErrorResponse(updateConsentPsuDataResponse.getError());\n }\n ResponseHeaders responseHeaders = consentHeadersBuilder.buildUpdatePsuDataHeaders(authorisationId);\n return responseMapper.ok(updateConsentPsuDataResponse, authorisationMapper::mapToConsentUpdatePsuAuthenticationResponse, responseHeaders);\n }\n\n @Override\n public ResponseEntity getConsentScaStatus(String consentId, String authorisationId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject consentAuthorisationScaStatusResponse = consentService.getConsentAuthorisationScaStatus(consentId, authorisationId);\n return consentAuthorisationScaStatusResponse.hasError() ? responseErrorMapper.generateErrorResponse(consentAuthorisationScaStatusResponse.getError()) : responseMapper.ok(consentAuthorisationScaStatusResponse, authorisationMapper::mapToScaStatusResponse);\n }\n\n @Override\n public ResponseEntity getConsentAuthorisation(String consentId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject consentInitiationAuthorisationsResponse = consentService.getConsentInitiationAuthorisations(consentId);\n return consentInitiationAuthorisationsResponse.hasError() ? responseErrorMapper.generateErrorResponse(consentInitiationAuthorisationsResponse.getError()) : responseMapper.ok(consentInitiationAuthorisationsResponse, authorisationMapper::mapToAuthorisations);\n }\n\n @Override\n public ResponseEntity getConsentInformation(String consentId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject accountConsentByIdResponse = consentService.getAccountConsentById(consentId);\n return accountConsentByIdResponse.hasError() ? responseErrorMapper.generateErrorResponse(accountConsentByIdResponse.getError()) : responseMapper.ok(accountConsentByIdResponse, consentModelMapper::mapToConsentInformationResponse200Json);\n }\n\n @Override\n public ResponseEntity deleteConsent(String consentId, UUID xRequestID, String digest, String signature, byte[] tpPSignatureCertificate, String psUIPAddress, String psUIPPort, String psUAccept, String psUAcceptCharset, String psUAcceptEncoding, String psUAcceptLanguage, String psUUserAgent, String psUHttpMethod, UUID psUDeviceID, String psUGeoLocation) {\n ResponseObject response = consentService.deleteAccountConsentsById(consentId);\n return response.hasError() ? responseErrorMapper.generateErrorResponse(response.getError()) : responseMapper.delete(response);\n }\n}\n"} {"task_id": "Java_3132", "language": "Java", "task_type": "method_signature", "source_file": "java/github/kongpengcheng/SmartRoute/app/src/main/java/com/smart/router/app/MainActivity.java", "mask_start_position": 581, "mask_end_position": 626, "canonical_solution": "@Override\n public void onClick(View view) ", "pre_mask_code": "package com.smart.router.app;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport com.smart.router.router.SmartRouter;\n\npublic class MainActivity extends AppCompatActivity implements View.OnClickListener {\n\n Button btn_test;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n btn_test = findViewById(R.id.btn_test);\n btn_test.setOnClickListener(this);\n }\n\n ", "post_mask_code": "{\n if (view == btn_test) {\n SmartRouter.build(\"test\").go(this);\n }\n }\n}\n"} {"task_id": "Java_3133", "language": "Java", "task_type": "method_body", "source_file": "java/github/kongpengcheng/SmartRoute/app/src/main/java/com/smart/router/app/MainActivity.java", "mask_start_position": 385, "mask_end_position": 575, "canonical_solution": "{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n btn_test = findViewById(R.id.btn_test);\n btn_test.setOnClickListener(this);\n }", "pre_mask_code": "package com.smart.router.app;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport com.smart.router.router.SmartRouter;\n\npublic class MainActivity extends AppCompatActivity implements View.OnClickListener {\n\n Button btn_test;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) ", "post_mask_code": "\n\n @Override\n public void onClick(View view) {\n if (view == btn_test) {\n SmartRouter.build(\"test\").go(this);\n }\n }\n}\n"} {"task_id": "Java_3134", "language": "Java", "task_type": "single_line", "source_file": "java/github/kongpengcheng/SmartRoute/app/src/main/java/com/smart/router/app/MainActivity.java", "mask_start_position": 549, "mask_end_position": 569, "canonical_solution": "ClickListener(this);", "pre_mask_code": "package com.smart.router.app;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport com.smart.router.router.SmartRouter;\n\npublic class MainActivity extends AppCompatActivity implements View.OnClickListener {\n\n Button btn_test;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n btn_test = findViewById(R.id.btn_test);\n btn_test.setOn", "post_mask_code": "\n }\n\n @Override\n public void onClick(View view) {\n if (view == btn_test) {\n SmartRouter.build(\"test\").go(this);\n }\n }\n}\n"} {"task_id": "Java_3135", "language": "Java", "task_type": "method_signature", "source_file": "java/github/SivanLiu/HwFrameWorkSource/P9_8_0_0/src/main/java/android/media/tv/ITvInputSessionWrapper.java", "mask_start_position": 11479, "mask_end_position": 11530, "canonical_solution": "public void unblockContent(String unblockedRating) ", "pre_mask_code": "package android.media.tv;\n\nimport android.content.Context;\nimport android.graphics.Rect;\nimport android.media.PlaybackParams;\nimport android.media.tv.ITvInputSession.Stub;\nimport android.media.tv.TvInputService.RecordingSession;\nimport android.media.tv.TvInputService.Session;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.os.IBinder;\nimport android.os.Looper;\nimport android.os.Message;\nimport android.util.Log;\nimport android.view.InputChannel;\nimport android.view.InputEvent;\nimport android.view.InputEventReceiver;\nimport android.view.Surface;\nimport com.android.internal.os.HandlerCaller;\nimport com.android.internal.os.HandlerCaller.Callback;\nimport com.android.internal.os.SomeArgs;\n\npublic class ITvInputSessionWrapper extends Stub implements Callback {\n\n private static final int DO_APP_PRIVATE_COMMAND = 9;\n\n private static final int DO_CREATE_OVERLAY_VIEW = 10;\n\n private static final int DO_DISPATCH_SURFACE_CHANGED = 4;\n\n private static final int DO_RELAYOUT_OVERLAY_VIEW = 11;\n\n private static final int DO_RELEASE = 1;\n\n private static final int DO_REMOVE_OVERLAY_VIEW = 12;\n\n private static final int DO_SELECT_TRACK = 8;\n\n private static final int DO_SET_CAPTION_ENABLED = 7;\n\n private static final int DO_SET_MAIN = 2;\n\n private static final int DO_SET_STREAM_VOLUME = 5;\n\n private static final int DO_SET_SURFACE = 3;\n\n private static final int DO_START_RECORDING = 20;\n\n private static final int DO_STOP_RECORDING = 21;\n\n private static final int DO_TIME_SHIFT_ENABLE_POSITION_TRACKING = 19;\n\n private static final int DO_TIME_SHIFT_PAUSE = 15;\n\n private static final int DO_TIME_SHIFT_PLAY = 14;\n\n private static final int DO_TIME_SHIFT_RESUME = 16;\n\n private static final int DO_TIME_SHIFT_SEEK_TO = 17;\n\n private static final int DO_TIME_SHIFT_SET_PLAYBACK_PARAMS = 18;\n\n private static final int DO_TUNE = 6;\n\n private static final int DO_UNBLOCK_CONTENT = 13;\n\n private static final int EXECUTE_MESSAGE_TIMEOUT_LONG_MILLIS = 5000;\n\n private static final int EXECUTE_MESSAGE_TIMEOUT_SHORT_MILLIS = 50;\n\n private static final int EXECUTE_MESSAGE_TUNE_TIMEOUT_MILLIS = 2000;\n\n private static final String TAG = \"TvInputSessionWrapper\";\n\n private final HandlerCaller mCaller;\n\n private InputChannel mChannel;\n\n private final boolean mIsRecordingSession = true;\n\n private TvInputEventReceiver mReceiver;\n\n private RecordingSession mTvInputRecordingSessionImpl;\n\n private Session mTvInputSessionImpl;\n\n private final class TvInputEventReceiver extends InputEventReceiver {\n\n public TvInputEventReceiver(InputChannel inputChannel, Looper looper) {\n super(inputChannel, looper);\n }\n\n public void onInputEvent(InputEvent event) {\n boolean z = true;\n if (ITvInputSessionWrapper.this.mTvInputSessionImpl == null) {\n finishInputEvent(event, false);\n return;\n }\n int handled = ITvInputSessionWrapper.this.mTvInputSessionImpl.dispatchInputEvent(event, this);\n if (handled != -1) {\n if (handled != 1) {\n z = false;\n }\n finishInputEvent(event, z);\n }\n }\n }\n\n public ITvInputSessionWrapper(Context context, Session sessionImpl, InputChannel channel) {\n this.mCaller = new HandlerCaller(context, null, this, true);\n this.mTvInputSessionImpl = sessionImpl;\n this.mChannel = channel;\n if (channel != null) {\n this.mReceiver = new TvInputEventReceiver(channel, context.getMainLooper());\n }\n }\n\n public ITvInputSessionWrapper(Context context, RecordingSession recordingSessionImpl) {\n this.mCaller = new HandlerCaller(context, null, this, true);\n this.mTvInputRecordingSessionImpl = recordingSessionImpl;\n }\n\n public void executeMessage(Message msg) {\n if (!(this.mIsRecordingSession && this.mTvInputRecordingSessionImpl == null) && (this.mIsRecordingSession || this.mTvInputSessionImpl != null)) {\n long startTime = System.nanoTime();\n SomeArgs args;\n switch(msg.what) {\n case 1:\n if (!this.mIsRecordingSession) {\n this.mTvInputSessionImpl.release();\n this.mTvInputSessionImpl = null;\n if (this.mReceiver != null) {\n this.mReceiver.dispose();\n this.mReceiver = null;\n }\n if (this.mChannel != null) {\n this.mChannel.dispose();\n this.mChannel = null;\n break;\n }\n }\n this.mTvInputRecordingSessionImpl.release();\n this.mTvInputRecordingSessionImpl = null;\n break;\n break;\n case 2:\n this.mTvInputSessionImpl.setMain(((Boolean) msg.obj).booleanValue());\n break;\n case 3:\n this.mTvInputSessionImpl.setSurface((Surface) msg.obj);\n break;\n case 4:\n args = msg.obj;\n this.mTvInputSessionImpl.dispatchSurfaceChanged(args.argi1, args.argi2, args.argi3);\n args.recycle();\n break;\n case 5:\n this.mTvInputSessionImpl.setStreamVolume(((Float) msg.obj).floatValue());\n break;\n case 6:\n args = (SomeArgs) msg.obj;\n if (this.mIsRecordingSession) {\n this.mTvInputRecordingSessionImpl.tune((Uri) args.arg1, (Bundle) args.arg2);\n } else {\n this.mTvInputSessionImpl.tune((Uri) args.arg1, (Bundle) args.arg2);\n }\n args.recycle();\n break;\n case 7:\n this.mTvInputSessionImpl.setCaptionEnabled(((Boolean) msg.obj).booleanValue());\n break;\n case 8:\n args = (SomeArgs) msg.obj;\n this.mTvInputSessionImpl.selectTrack(((Integer) args.arg1).intValue(), (String) args.arg2);\n args.recycle();\n break;\n case 9:\n args = (SomeArgs) msg.obj;\n if (this.mIsRecordingSession) {\n this.mTvInputRecordingSessionImpl.appPrivateCommand((String) args.arg1, (Bundle) args.arg2);\n } else {\n this.mTvInputSessionImpl.appPrivateCommand((String) args.arg1, (Bundle) args.arg2);\n }\n args.recycle();\n break;\n case 10:\n args = (SomeArgs) msg.obj;\n this.mTvInputSessionImpl.createOverlayView((IBinder) args.arg1, (Rect) args.arg2);\n args.recycle();\n break;\n case 11:\n this.mTvInputSessionImpl.relayoutOverlayView((Rect) msg.obj);\n break;\n case 12:\n this.mTvInputSessionImpl.removeOverlayView(true);\n break;\n case 13:\n this.mTvInputSessionImpl.unblockContent((String) msg.obj);\n break;\n case 14:\n this.mTvInputSessionImpl.timeShiftPlay((Uri) msg.obj);\n break;\n case 15:\n this.mTvInputSessionImpl.timeShiftPause();\n break;\n case 16:\n this.mTvInputSessionImpl.timeShiftResume();\n break;\n case 17:\n this.mTvInputSessionImpl.timeShiftSeekTo(((Long) msg.obj).longValue());\n break;\n case 18:\n this.mTvInputSessionImpl.timeShiftSetPlaybackParams((PlaybackParams) msg.obj);\n break;\n case 19:\n this.mTvInputSessionImpl.timeShiftEnablePositionTracking(((Boolean) msg.obj).booleanValue());\n break;\n case 20:\n this.mTvInputRecordingSessionImpl.startRecording((Uri) msg.obj);\n break;\n case 21:\n this.mTvInputRecordingSessionImpl.stopRecording();\n break;\n default:\n Log.w(TAG, \"Unhandled message code: \" + msg.what);\n break;\n }\n long durationMs = (System.nanoTime() - startTime) / 1000000;\n if (durationMs > 50) {\n Log.w(TAG, \"Handling message (\" + msg.what + \") took too long time (duration=\" + durationMs + \"ms)\");\n if (msg.what == 6 && durationMs > 2000) {\n throw new RuntimeException(\"Too much time to handle tune request. (\" + durationMs + \"ms > \" + 2000 + \"ms) \" + \"Consider handling the tune request in a separate thread.\");\n } else if (durationMs > 5000) {\n throw new RuntimeException(\"Too much time to handle a request. (type=\" + msg.what + \", \" + durationMs + \"ms > \" + 5000 + \"ms).\");\n }\n }\n }\n }\n\n public void release() {\n if (!this.mIsRecordingSession) {\n this.mTvInputSessionImpl.scheduleOverlayViewCleanup();\n }\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(1));\n }\n\n public void setMain(boolean isMain) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(2, Boolean.valueOf(isMain)));\n }\n\n public void setSurface(Surface surface) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(3, surface));\n }\n\n public void dispatchSurfaceChanged(int format, int width, int height) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageIIII(4, format, width, height, 0));\n }\n\n public final void setVolume(float volume) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(5, Float.valueOf(volume)));\n }\n\n public void tune(Uri channelUri, Bundle params) {\n this.mCaller.removeMessages(6);\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageOO(6, channelUri, params));\n }\n\n public void setCaptionEnabled(boolean enabled) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(7, Boolean.valueOf(enabled)));\n }\n\n public void selectTrack(int type, String trackId) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageOO(8, Integer.valueOf(type), trackId));\n }\n\n public void appPrivateCommand(String action, Bundle data) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageOO(9, action, data));\n }\n\n public void createOverlayView(IBinder windowToken, Rect frame) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageOO(10, windowToken, frame));\n }\n\n public void relayoutOverlayView(Rect frame) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(11, frame));\n }\n\n public void removeOverlayView() {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(12));\n }\n\n ", "post_mask_code": "{\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(13, unblockedRating));\n }\n\n public void timeShiftPlay(Uri recordedProgramUri) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(14, recordedProgramUri));\n }\n\n public void timeShiftPause() {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(15));\n }\n\n public void timeShiftResume() {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(16));\n }\n\n public void timeShiftSeekTo(long timeMs) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(17, Long.valueOf(timeMs)));\n }\n\n public void timeShiftSetPlaybackParams(PlaybackParams params) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(18, params));\n }\n\n public void timeShiftEnablePositionTracking(boolean enable) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(19, Boolean.valueOf(enable)));\n }\n\n public void startRecording(Uri programUri) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(20, programUri));\n }\n\n public void stopRecording() {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(21));\n }\n}\n"} {"task_id": "Java_3136", "language": "Java", "task_type": "method_body", "source_file": "java/github/SivanLiu/HwFrameWorkSource/P9_8_0_0/src/main/java/android/media/tv/ITvInputSessionWrapper.java", "mask_start_position": 11686, "mask_end_position": 11789, "canonical_solution": "{\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(14, recordedProgramUri));\n }", "pre_mask_code": "package android.media.tv;\n\nimport android.content.Context;\nimport android.graphics.Rect;\nimport android.media.PlaybackParams;\nimport android.media.tv.ITvInputSession.Stub;\nimport android.media.tv.TvInputService.RecordingSession;\nimport android.media.tv.TvInputService.Session;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.os.IBinder;\nimport android.os.Looper;\nimport android.os.Message;\nimport android.util.Log;\nimport android.view.InputChannel;\nimport android.view.InputEvent;\nimport android.view.InputEventReceiver;\nimport android.view.Surface;\nimport com.android.internal.os.HandlerCaller;\nimport com.android.internal.os.HandlerCaller.Callback;\nimport com.android.internal.os.SomeArgs;\n\npublic class ITvInputSessionWrapper extends Stub implements Callback {\n\n private static final int DO_APP_PRIVATE_COMMAND = 9;\n\n private static final int DO_CREATE_OVERLAY_VIEW = 10;\n\n private static final int DO_DISPATCH_SURFACE_CHANGED = 4;\n\n private static final int DO_RELAYOUT_OVERLAY_VIEW = 11;\n\n private static final int DO_RELEASE = 1;\n\n private static final int DO_REMOVE_OVERLAY_VIEW = 12;\n\n private static final int DO_SELECT_TRACK = 8;\n\n private static final int DO_SET_CAPTION_ENABLED = 7;\n\n private static final int DO_SET_MAIN = 2;\n\n private static final int DO_SET_STREAM_VOLUME = 5;\n\n private static final int DO_SET_SURFACE = 3;\n\n private static final int DO_START_RECORDING = 20;\n\n private static final int DO_STOP_RECORDING = 21;\n\n private static final int DO_TIME_SHIFT_ENABLE_POSITION_TRACKING = 19;\n\n private static final int DO_TIME_SHIFT_PAUSE = 15;\n\n private static final int DO_TIME_SHIFT_PLAY = 14;\n\n private static final int DO_TIME_SHIFT_RESUME = 16;\n\n private static final int DO_TIME_SHIFT_SEEK_TO = 17;\n\n private static final int DO_TIME_SHIFT_SET_PLAYBACK_PARAMS = 18;\n\n private static final int DO_TUNE = 6;\n\n private static final int DO_UNBLOCK_CONTENT = 13;\n\n private static final int EXECUTE_MESSAGE_TIMEOUT_LONG_MILLIS = 5000;\n\n private static final int EXECUTE_MESSAGE_TIMEOUT_SHORT_MILLIS = 50;\n\n private static final int EXECUTE_MESSAGE_TUNE_TIMEOUT_MILLIS = 2000;\n\n private static final String TAG = \"TvInputSessionWrapper\";\n\n private final HandlerCaller mCaller;\n\n private InputChannel mChannel;\n\n private final boolean mIsRecordingSession = true;\n\n private TvInputEventReceiver mReceiver;\n\n private RecordingSession mTvInputRecordingSessionImpl;\n\n private Session mTvInputSessionImpl;\n\n private final class TvInputEventReceiver extends InputEventReceiver {\n\n public TvInputEventReceiver(InputChannel inputChannel, Looper looper) {\n super(inputChannel, looper);\n }\n\n public void onInputEvent(InputEvent event) {\n boolean z = true;\n if (ITvInputSessionWrapper.this.mTvInputSessionImpl == null) {\n finishInputEvent(event, false);\n return;\n }\n int handled = ITvInputSessionWrapper.this.mTvInputSessionImpl.dispatchInputEvent(event, this);\n if (handled != -1) {\n if (handled != 1) {\n z = false;\n }\n finishInputEvent(event, z);\n }\n }\n }\n\n public ITvInputSessionWrapper(Context context, Session sessionImpl, InputChannel channel) {\n this.mCaller = new HandlerCaller(context, null, this, true);\n this.mTvInputSessionImpl = sessionImpl;\n this.mChannel = channel;\n if (channel != null) {\n this.mReceiver = new TvInputEventReceiver(channel, context.getMainLooper());\n }\n }\n\n public ITvInputSessionWrapper(Context context, RecordingSession recordingSessionImpl) {\n this.mCaller = new HandlerCaller(context, null, this, true);\n this.mTvInputRecordingSessionImpl = recordingSessionImpl;\n }\n\n public void executeMessage(Message msg) {\n if (!(this.mIsRecordingSession && this.mTvInputRecordingSessionImpl == null) && (this.mIsRecordingSession || this.mTvInputSessionImpl != null)) {\n long startTime = System.nanoTime();\n SomeArgs args;\n switch(msg.what) {\n case 1:\n if (!this.mIsRecordingSession) {\n this.mTvInputSessionImpl.release();\n this.mTvInputSessionImpl = null;\n if (this.mReceiver != null) {\n this.mReceiver.dispose();\n this.mReceiver = null;\n }\n if (this.mChannel != null) {\n this.mChannel.dispose();\n this.mChannel = null;\n break;\n }\n }\n this.mTvInputRecordingSessionImpl.release();\n this.mTvInputRecordingSessionImpl = null;\n break;\n break;\n case 2:\n this.mTvInputSessionImpl.setMain(((Boolean) msg.obj).booleanValue());\n break;\n case 3:\n this.mTvInputSessionImpl.setSurface((Surface) msg.obj);\n break;\n case 4:\n args = msg.obj;\n this.mTvInputSessionImpl.dispatchSurfaceChanged(args.argi1, args.argi2, args.argi3);\n args.recycle();\n break;\n case 5:\n this.mTvInputSessionImpl.setStreamVolume(((Float) msg.obj).floatValue());\n break;\n case 6:\n args = (SomeArgs) msg.obj;\n if (this.mIsRecordingSession) {\n this.mTvInputRecordingSessionImpl.tune((Uri) args.arg1, (Bundle) args.arg2);\n } else {\n this.mTvInputSessionImpl.tune((Uri) args.arg1, (Bundle) args.arg2);\n }\n args.recycle();\n break;\n case 7:\n this.mTvInputSessionImpl.setCaptionEnabled(((Boolean) msg.obj).booleanValue());\n break;\n case 8:\n args = (SomeArgs) msg.obj;\n this.mTvInputSessionImpl.selectTrack(((Integer) args.arg1).intValue(), (String) args.arg2);\n args.recycle();\n break;\n case 9:\n args = (SomeArgs) msg.obj;\n if (this.mIsRecordingSession) {\n this.mTvInputRecordingSessionImpl.appPrivateCommand((String) args.arg1, (Bundle) args.arg2);\n } else {\n this.mTvInputSessionImpl.appPrivateCommand((String) args.arg1, (Bundle) args.arg2);\n }\n args.recycle();\n break;\n case 10:\n args = (SomeArgs) msg.obj;\n this.mTvInputSessionImpl.createOverlayView((IBinder) args.arg1, (Rect) args.arg2);\n args.recycle();\n break;\n case 11:\n this.mTvInputSessionImpl.relayoutOverlayView((Rect) msg.obj);\n break;\n case 12:\n this.mTvInputSessionImpl.removeOverlayView(true);\n break;\n case 13:\n this.mTvInputSessionImpl.unblockContent((String) msg.obj);\n break;\n case 14:\n this.mTvInputSessionImpl.timeShiftPlay((Uri) msg.obj);\n break;\n case 15:\n this.mTvInputSessionImpl.timeShiftPause();\n break;\n case 16:\n this.mTvInputSessionImpl.timeShiftResume();\n break;\n case 17:\n this.mTvInputSessionImpl.timeShiftSeekTo(((Long) msg.obj).longValue());\n break;\n case 18:\n this.mTvInputSessionImpl.timeShiftSetPlaybackParams((PlaybackParams) msg.obj);\n break;\n case 19:\n this.mTvInputSessionImpl.timeShiftEnablePositionTracking(((Boolean) msg.obj).booleanValue());\n break;\n case 20:\n this.mTvInputRecordingSessionImpl.startRecording((Uri) msg.obj);\n break;\n case 21:\n this.mTvInputRecordingSessionImpl.stopRecording();\n break;\n default:\n Log.w(TAG, \"Unhandled message code: \" + msg.what);\n break;\n }\n long durationMs = (System.nanoTime() - startTime) / 1000000;\n if (durationMs > 50) {\n Log.w(TAG, \"Handling message (\" + msg.what + \") took too long time (duration=\" + durationMs + \"ms)\");\n if (msg.what == 6 && durationMs > 2000) {\n throw new RuntimeException(\"Too much time to handle tune request. (\" + durationMs + \"ms > \" + 2000 + \"ms) \" + \"Consider handling the tune request in a separate thread.\");\n } else if (durationMs > 5000) {\n throw new RuntimeException(\"Too much time to handle a request. (type=\" + msg.what + \", \" + durationMs + \"ms > \" + 5000 + \"ms).\");\n }\n }\n }\n }\n\n public void release() {\n if (!this.mIsRecordingSession) {\n this.mTvInputSessionImpl.scheduleOverlayViewCleanup();\n }\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(1));\n }\n\n public void setMain(boolean isMain) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(2, Boolean.valueOf(isMain)));\n }\n\n public void setSurface(Surface surface) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(3, surface));\n }\n\n public void dispatchSurfaceChanged(int format, int width, int height) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageIIII(4, format, width, height, 0));\n }\n\n public final void setVolume(float volume) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(5, Float.valueOf(volume)));\n }\n\n public void tune(Uri channelUri, Bundle params) {\n this.mCaller.removeMessages(6);\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageOO(6, channelUri, params));\n }\n\n public void setCaptionEnabled(boolean enabled) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(7, Boolean.valueOf(enabled)));\n }\n\n public void selectTrack(int type, String trackId) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageOO(8, Integer.valueOf(type), trackId));\n }\n\n public void appPrivateCommand(String action, Bundle data) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageOO(9, action, data));\n }\n\n public void createOverlayView(IBinder windowToken, Rect frame) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageOO(10, windowToken, frame));\n }\n\n public void relayoutOverlayView(Rect frame) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(11, frame));\n }\n\n public void removeOverlayView() {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(12));\n }\n\n public void unblockContent(String unblockedRating) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(13, unblockedRating));\n }\n\n public void timeShiftPlay(Uri recordedProgramUri) ", "post_mask_code": "\n\n public void timeShiftPause() {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(15));\n }\n\n public void timeShiftResume() {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(16));\n }\n\n public void timeShiftSeekTo(long timeMs) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(17, Long.valueOf(timeMs)));\n }\n\n public void timeShiftSetPlaybackParams(PlaybackParams params) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(18, params));\n }\n\n public void timeShiftEnablePositionTracking(boolean enable) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(19, Boolean.valueOf(enable)));\n }\n\n public void startRecording(Uri programUri) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(20, programUri));\n }\n\n public void stopRecording() {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(21));\n }\n}\n"} {"task_id": "Java_3137", "language": "Java", "task_type": "single_line", "source_file": "java/github/SivanLiu/HwFrameWorkSource/P9_8_0_0/src/main/java/android/media/tv/ITvInputSessionWrapper.java", "mask_start_position": 11595, "mask_end_position": 11624, "canonical_solution": "ssageO(13, unblockedRating));", "pre_mask_code": "package android.media.tv;\n\nimport android.content.Context;\nimport android.graphics.Rect;\nimport android.media.PlaybackParams;\nimport android.media.tv.ITvInputSession.Stub;\nimport android.media.tv.TvInputService.RecordingSession;\nimport android.media.tv.TvInputService.Session;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.os.IBinder;\nimport android.os.Looper;\nimport android.os.Message;\nimport android.util.Log;\nimport android.view.InputChannel;\nimport android.view.InputEvent;\nimport android.view.InputEventReceiver;\nimport android.view.Surface;\nimport com.android.internal.os.HandlerCaller;\nimport com.android.internal.os.HandlerCaller.Callback;\nimport com.android.internal.os.SomeArgs;\n\npublic class ITvInputSessionWrapper extends Stub implements Callback {\n\n private static final int DO_APP_PRIVATE_COMMAND = 9;\n\n private static final int DO_CREATE_OVERLAY_VIEW = 10;\n\n private static final int DO_DISPATCH_SURFACE_CHANGED = 4;\n\n private static final int DO_RELAYOUT_OVERLAY_VIEW = 11;\n\n private static final int DO_RELEASE = 1;\n\n private static final int DO_REMOVE_OVERLAY_VIEW = 12;\n\n private static final int DO_SELECT_TRACK = 8;\n\n private static final int DO_SET_CAPTION_ENABLED = 7;\n\n private static final int DO_SET_MAIN = 2;\n\n private static final int DO_SET_STREAM_VOLUME = 5;\n\n private static final int DO_SET_SURFACE = 3;\n\n private static final int DO_START_RECORDING = 20;\n\n private static final int DO_STOP_RECORDING = 21;\n\n private static final int DO_TIME_SHIFT_ENABLE_POSITION_TRACKING = 19;\n\n private static final int DO_TIME_SHIFT_PAUSE = 15;\n\n private static final int DO_TIME_SHIFT_PLAY = 14;\n\n private static final int DO_TIME_SHIFT_RESUME = 16;\n\n private static final int DO_TIME_SHIFT_SEEK_TO = 17;\n\n private static final int DO_TIME_SHIFT_SET_PLAYBACK_PARAMS = 18;\n\n private static final int DO_TUNE = 6;\n\n private static final int DO_UNBLOCK_CONTENT = 13;\n\n private static final int EXECUTE_MESSAGE_TIMEOUT_LONG_MILLIS = 5000;\n\n private static final int EXECUTE_MESSAGE_TIMEOUT_SHORT_MILLIS = 50;\n\n private static final int EXECUTE_MESSAGE_TUNE_TIMEOUT_MILLIS = 2000;\n\n private static final String TAG = \"TvInputSessionWrapper\";\n\n private final HandlerCaller mCaller;\n\n private InputChannel mChannel;\n\n private final boolean mIsRecordingSession = true;\n\n private TvInputEventReceiver mReceiver;\n\n private RecordingSession mTvInputRecordingSessionImpl;\n\n private Session mTvInputSessionImpl;\n\n private final class TvInputEventReceiver extends InputEventReceiver {\n\n public TvInputEventReceiver(InputChannel inputChannel, Looper looper) {\n super(inputChannel, looper);\n }\n\n public void onInputEvent(InputEvent event) {\n boolean z = true;\n if (ITvInputSessionWrapper.this.mTvInputSessionImpl == null) {\n finishInputEvent(event, false);\n return;\n }\n int handled = ITvInputSessionWrapper.this.mTvInputSessionImpl.dispatchInputEvent(event, this);\n if (handled != -1) {\n if (handled != 1) {\n z = false;\n }\n finishInputEvent(event, z);\n }\n }\n }\n\n public ITvInputSessionWrapper(Context context, Session sessionImpl, InputChannel channel) {\n this.mCaller = new HandlerCaller(context, null, this, true);\n this.mTvInputSessionImpl = sessionImpl;\n this.mChannel = channel;\n if (channel != null) {\n this.mReceiver = new TvInputEventReceiver(channel, context.getMainLooper());\n }\n }\n\n public ITvInputSessionWrapper(Context context, RecordingSession recordingSessionImpl) {\n this.mCaller = new HandlerCaller(context, null, this, true);\n this.mTvInputRecordingSessionImpl = recordingSessionImpl;\n }\n\n public void executeMessage(Message msg) {\n if (!(this.mIsRecordingSession && this.mTvInputRecordingSessionImpl == null) && (this.mIsRecordingSession || this.mTvInputSessionImpl != null)) {\n long startTime = System.nanoTime();\n SomeArgs args;\n switch(msg.what) {\n case 1:\n if (!this.mIsRecordingSession) {\n this.mTvInputSessionImpl.release();\n this.mTvInputSessionImpl = null;\n if (this.mReceiver != null) {\n this.mReceiver.dispose();\n this.mReceiver = null;\n }\n if (this.mChannel != null) {\n this.mChannel.dispose();\n this.mChannel = null;\n break;\n }\n }\n this.mTvInputRecordingSessionImpl.release();\n this.mTvInputRecordingSessionImpl = null;\n break;\n break;\n case 2:\n this.mTvInputSessionImpl.setMain(((Boolean) msg.obj).booleanValue());\n break;\n case 3:\n this.mTvInputSessionImpl.setSurface((Surface) msg.obj);\n break;\n case 4:\n args = msg.obj;\n this.mTvInputSessionImpl.dispatchSurfaceChanged(args.argi1, args.argi2, args.argi3);\n args.recycle();\n break;\n case 5:\n this.mTvInputSessionImpl.setStreamVolume(((Float) msg.obj).floatValue());\n break;\n case 6:\n args = (SomeArgs) msg.obj;\n if (this.mIsRecordingSession) {\n this.mTvInputRecordingSessionImpl.tune((Uri) args.arg1, (Bundle) args.arg2);\n } else {\n this.mTvInputSessionImpl.tune((Uri) args.arg1, (Bundle) args.arg2);\n }\n args.recycle();\n break;\n case 7:\n this.mTvInputSessionImpl.setCaptionEnabled(((Boolean) msg.obj).booleanValue());\n break;\n case 8:\n args = (SomeArgs) msg.obj;\n this.mTvInputSessionImpl.selectTrack(((Integer) args.arg1).intValue(), (String) args.arg2);\n args.recycle();\n break;\n case 9:\n args = (SomeArgs) msg.obj;\n if (this.mIsRecordingSession) {\n this.mTvInputRecordingSessionImpl.appPrivateCommand((String) args.arg1, (Bundle) args.arg2);\n } else {\n this.mTvInputSessionImpl.appPrivateCommand((String) args.arg1, (Bundle) args.arg2);\n }\n args.recycle();\n break;\n case 10:\n args = (SomeArgs) msg.obj;\n this.mTvInputSessionImpl.createOverlayView((IBinder) args.arg1, (Rect) args.arg2);\n args.recycle();\n break;\n case 11:\n this.mTvInputSessionImpl.relayoutOverlayView((Rect) msg.obj);\n break;\n case 12:\n this.mTvInputSessionImpl.removeOverlayView(true);\n break;\n case 13:\n this.mTvInputSessionImpl.unblockContent((String) msg.obj);\n break;\n case 14:\n this.mTvInputSessionImpl.timeShiftPlay((Uri) msg.obj);\n break;\n case 15:\n this.mTvInputSessionImpl.timeShiftPause();\n break;\n case 16:\n this.mTvInputSessionImpl.timeShiftResume();\n break;\n case 17:\n this.mTvInputSessionImpl.timeShiftSeekTo(((Long) msg.obj).longValue());\n break;\n case 18:\n this.mTvInputSessionImpl.timeShiftSetPlaybackParams((PlaybackParams) msg.obj);\n break;\n case 19:\n this.mTvInputSessionImpl.timeShiftEnablePositionTracking(((Boolean) msg.obj).booleanValue());\n break;\n case 20:\n this.mTvInputRecordingSessionImpl.startRecording((Uri) msg.obj);\n break;\n case 21:\n this.mTvInputRecordingSessionImpl.stopRecording();\n break;\n default:\n Log.w(TAG, \"Unhandled message code: \" + msg.what);\n break;\n }\n long durationMs = (System.nanoTime() - startTime) / 1000000;\n if (durationMs > 50) {\n Log.w(TAG, \"Handling message (\" + msg.what + \") took too long time (duration=\" + durationMs + \"ms)\");\n if (msg.what == 6 && durationMs > 2000) {\n throw new RuntimeException(\"Too much time to handle tune request. (\" + durationMs + \"ms > \" + 2000 + \"ms) \" + \"Consider handling the tune request in a separate thread.\");\n } else if (durationMs > 5000) {\n throw new RuntimeException(\"Too much time to handle a request. (type=\" + msg.what + \", \" + durationMs + \"ms > \" + 5000 + \"ms).\");\n }\n }\n }\n }\n\n public void release() {\n if (!this.mIsRecordingSession) {\n this.mTvInputSessionImpl.scheduleOverlayViewCleanup();\n }\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(1));\n }\n\n public void setMain(boolean isMain) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(2, Boolean.valueOf(isMain)));\n }\n\n public void setSurface(Surface surface) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(3, surface));\n }\n\n public void dispatchSurfaceChanged(int format, int width, int height) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageIIII(4, format, width, height, 0));\n }\n\n public final void setVolume(float volume) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(5, Float.valueOf(volume)));\n }\n\n public void tune(Uri channelUri, Bundle params) {\n this.mCaller.removeMessages(6);\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageOO(6, channelUri, params));\n }\n\n public void setCaptionEnabled(boolean enabled) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(7, Boolean.valueOf(enabled)));\n }\n\n public void selectTrack(int type, String trackId) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageOO(8, Integer.valueOf(type), trackId));\n }\n\n public void appPrivateCommand(String action, Bundle data) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageOO(9, action, data));\n }\n\n public void createOverlayView(IBinder windowToken, Rect frame) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageOO(10, windowToken, frame));\n }\n\n public void relayoutOverlayView(Rect frame) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(11, frame));\n }\n\n public void removeOverlayView() {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(12));\n }\n\n public void unblockContent(String unblockedRating) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMe", "post_mask_code": "\n }\n\n public void timeShiftPlay(Uri recordedProgramUri) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(14, recordedProgramUri));\n }\n\n public void timeShiftPause() {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(15));\n }\n\n public void timeShiftResume() {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(16));\n }\n\n public void timeShiftSeekTo(long timeMs) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(17, Long.valueOf(timeMs)));\n }\n\n public void timeShiftSetPlaybackParams(PlaybackParams params) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(18, params));\n }\n\n public void timeShiftEnablePositionTracking(boolean enable) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(19, Boolean.valueOf(enable)));\n }\n\n public void startRecording(Uri programUri) {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessageO(20, programUri));\n }\n\n public void stopRecording() {\n this.mCaller.executeOrSendMessage(this.mCaller.obtainMessage(21));\n }\n}\n"} {"task_id": "Java_3138", "language": "Java", "task_type": "method_signature", "source_file": "java/github/WeTheInternet/xapi/net.wti.core/lang/src/main/java/com/github/javaparser/ast/expr/SingleMemberAnnotationExpr.java", "mask_start_position": 1408, "mask_end_position": 1473, "canonical_solution": "@Override\n public SizedIterable getMembers() ", "pre_mask_code": "/*\n *\n * This file is part of JavaParser.\n *\n */\npackage com.github.javaparser.ast.expr;\n\nimport com.github.javaparser.ast.visitor.GenericVisitor;\nimport com.github.javaparser.ast.visitor.VoidVisitor;\nimport xapi.fu.itr.SingletonIterator;\nimport xapi.fu.itr.SizedIterable;\n\n/**\n * @author Julio Vilmar Gesser\n */\npublic final class SingleMemberAnnotationExpr extends AnnotationExpr {\n\n private Expression memberValue;\n\n public SingleMemberAnnotationExpr() {\n }\n\n public SingleMemberAnnotationExpr(final NameExpr name, final Expression memberValue) {\n setName(name);\n setMemberValue(memberValue);\n }\n\n public SingleMemberAnnotationExpr(final int beginLine, final int beginColumn, final int endLine, final int endColumn, final NameExpr name, final Expression memberValue) {\n super(beginLine, beginColumn, endLine, endColumn);\n setName(name);\n setMemberValue(memberValue);\n }\n\n @Override\n public R accept(final GenericVisitor v, final A arg) {\n return v.visit(this, arg);\n }\n\n @Override\n public void accept(final VoidVisitor v, final A arg) {\n v.visit(this, arg);\n }\n\n public Expression getMemberValue() {\n return memberValue;\n }\n\n public void setMemberValue(final Expression memberValue) {\n this.memberValue = memberValue;\n setAsParentNodeOf(this.memberValue);\n }\n\n ", "post_mask_code": "{\n return SingletonIterator.singleItem(new MemberValuePair(\"value\", memberValue));\n }\n}\n"} {"task_id": "Java_3139", "language": "Java", "task_type": "method_body", "source_file": "java/github/WeTheInternet/xapi/net.wti.core/lang/src/main/java/com/github/javaparser/ast/expr/SingleMemberAnnotationExpr.java", "mask_start_position": 1212, "mask_end_position": 1247, "canonical_solution": "{\n return memberValue;\n }", "pre_mask_code": "/*\n *\n * This file is part of JavaParser.\n *\n */\npackage com.github.javaparser.ast.expr;\n\nimport com.github.javaparser.ast.visitor.GenericVisitor;\nimport com.github.javaparser.ast.visitor.VoidVisitor;\nimport xapi.fu.itr.SingletonIterator;\nimport xapi.fu.itr.SizedIterable;\n\n/**\n * @author Julio Vilmar Gesser\n */\npublic final class SingleMemberAnnotationExpr extends AnnotationExpr {\n\n private Expression memberValue;\n\n public SingleMemberAnnotationExpr() {\n }\n\n public SingleMemberAnnotationExpr(final NameExpr name, final Expression memberValue) {\n setName(name);\n setMemberValue(memberValue);\n }\n\n public SingleMemberAnnotationExpr(final int beginLine, final int beginColumn, final int endLine, final int endColumn, final NameExpr name, final Expression memberValue) {\n super(beginLine, beginColumn, endLine, endColumn);\n setName(name);\n setMemberValue(memberValue);\n }\n\n @Override\n public R accept(final GenericVisitor v, final A arg) {\n return v.visit(this, arg);\n }\n\n @Override\n public void accept(final VoidVisitor v, final A arg) {\n v.visit(this, arg);\n }\n\n public Expression getMemberValue() ", "post_mask_code": "\n\n public void setMemberValue(final Expression memberValue) {\n this.memberValue = memberValue;\n setAsParentNodeOf(this.memberValue);\n }\n\n @Override\n public SizedIterable getMembers() {\n return SingletonIterator.singleItem(new MemberValuePair(\"value\", memberValue));\n }\n}\n"} {"task_id": "Java_3140", "language": "Java", "task_type": "single_line", "source_file": "java/github/WeTheInternet/xapi/net.wti.core/lang/src/main/java/com/github/javaparser/ast/expr/SingleMemberAnnotationExpr.java", "mask_start_position": 1161, "mask_end_position": 1165, "canonical_solution": "rg);", "pre_mask_code": "/*\n *\n * This file is part of JavaParser.\n *\n */\npackage com.github.javaparser.ast.expr;\n\nimport com.github.javaparser.ast.visitor.GenericVisitor;\nimport com.github.javaparser.ast.visitor.VoidVisitor;\nimport xapi.fu.itr.SingletonIterator;\nimport xapi.fu.itr.SizedIterable;\n\n/**\n * @author Julio Vilmar Gesser\n */\npublic final class SingleMemberAnnotationExpr extends AnnotationExpr {\n\n private Expression memberValue;\n\n public SingleMemberAnnotationExpr() {\n }\n\n public SingleMemberAnnotationExpr(final NameExpr name, final Expression memberValue) {\n setName(name);\n setMemberValue(memberValue);\n }\n\n public SingleMemberAnnotationExpr(final int beginLine, final int beginColumn, final int endLine, final int endColumn, final NameExpr name, final Expression memberValue) {\n super(beginLine, beginColumn, endLine, endColumn);\n setName(name);\n setMemberValue(memberValue);\n }\n\n @Override\n public R accept(final GenericVisitor v, final A arg) {\n return v.visit(this, arg);\n }\n\n @Override\n public void accept(final VoidVisitor v, final A arg) {\n v.visit(this, a", "post_mask_code": "\n }\n\n public Expression getMemberValue() {\n return memberValue;\n }\n\n public void setMemberValue(final Expression memberValue) {\n this.memberValue = memberValue;\n setAsParentNodeOf(this.memberValue);\n }\n\n @Override\n public SizedIterable getMembers() {\n return SingletonIterator.singleItem(new MemberValuePair(\"value\", memberValue));\n }\n}\n"} {"task_id": "Java_3141", "language": "Java", "task_type": "method_signature", "source_file": "java/github/unclezs/uncle-novel/app-framework/src/main/java/com/unclezs/novel/app/framework/collection/SimpleObservableList.java", "mask_start_position": 845, "mask_end_position": 897, "canonical_solution": "@Override\n public void add(int index, E element) ", "pre_mask_code": "package com.unclezs.novel.app.framework.collection;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport javafx.collections.ObservableListBase;\nimport lombok.EqualsAndHashCode;\n\n/**\n * @author blog.unclezs.com\n * @date 2021/4/8 16:40\n */\n@EqualsAndHashCode(callSuper = true)\npublic class SimpleObservableList extends ObservableListBase {\n\n private final List list;\n\n public SimpleObservableList(List backingList) {\n this.list = backingList;\n }\n\n public SimpleObservableList() {\n this.list = new ArrayList<>();\n }\n\n @Override\n public E get(int index) {\n return list.get(index);\n }\n\n @Override\n public int size() {\n return list.size();\n }\n\n @Override\n public E remove(int index) {\n onRemove(list.get(index));\n return list.remove(index);\n }\n\n ", "post_mask_code": "{\n onAdd(element);\n list.add(index, element);\n }\n\n public void onAdd(E element) {\n }\n\n public void onRemove(E element) {\n }\n}\n"} {"task_id": "Java_3142", "language": "Java", "task_type": "method_body", "source_file": "java/github/unclezs/uncle-novel/app-framework/src/main/java/com/unclezs/novel/app/framework/collection/SimpleObservableList.java", "mask_start_position": 680, "mask_end_position": 715, "canonical_solution": "{\n return list.size();\n }", "pre_mask_code": "package com.unclezs.novel.app.framework.collection;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport javafx.collections.ObservableListBase;\nimport lombok.EqualsAndHashCode;\n\n/**\n * @author blog.unclezs.com\n * @date 2021/4/8 16:40\n */\n@EqualsAndHashCode(callSuper = true)\npublic class SimpleObservableList extends ObservableListBase {\n\n private final List list;\n\n public SimpleObservableList(List backingList) {\n this.list = backingList;\n }\n\n public SimpleObservableList() {\n this.list = new ArrayList<>();\n }\n\n @Override\n public E get(int index) {\n return list.get(index);\n }\n\n @Override\n public int size() ", "post_mask_code": "\n\n @Override\n public E remove(int index) {\n onRemove(list.get(index));\n return list.remove(index);\n }\n\n @Override\n public void add(int index, E element) {\n onAdd(element);\n list.add(index, element);\n }\n\n public void onAdd(E element) {\n }\n\n public void onRemove(E element) {\n }\n}\n"} {"task_id": "Java_3143", "language": "Java", "task_type": "single_line", "source_file": "java/github/unclezs/uncle-novel/app-framework/src/main/java/com/unclezs/novel/app/framework/collection/SimpleObservableList.java", "mask_start_position": 823, "mask_end_position": 833, "canonical_solution": "ve(index);", "pre_mask_code": "package com.unclezs.novel.app.framework.collection;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport javafx.collections.ObservableListBase;\nimport lombok.EqualsAndHashCode;\n\n/**\n * @author blog.unclezs.com\n * @date 2021/4/8 16:40\n */\n@EqualsAndHashCode(callSuper = true)\npublic class SimpleObservableList extends ObservableListBase {\n\n private final List list;\n\n public SimpleObservableList(List backingList) {\n this.list = backingList;\n }\n\n public SimpleObservableList() {\n this.list = new ArrayList<>();\n }\n\n @Override\n public E get(int index) {\n return list.get(index);\n }\n\n @Override\n public int size() {\n return list.size();\n }\n\n @Override\n public E remove(int index) {\n onRemove(list.get(index));\n return list.remo", "post_mask_code": "\n }\n\n @Override\n public void add(int index, E element) {\n onAdd(element);\n list.add(index, element);\n }\n\n public void onAdd(E element) {\n }\n\n public void onRemove(E element) {\n }\n}\n"} {"task_id": "Java_3144", "language": "Java", "task_type": "method_signature", "source_file": "java/github/google/error-prone/core/src/main/java/com/google/errorprone/bugpatterns/JavaLangClash.java", "mask_start_position": 1462, "mask_end_position": 1542, "canonical_solution": "@Override\n public Description matchClass(ClassTree tree, VisitorState state) ", "pre_mask_code": "package com.google.errorprone.bugpatterns;\n\nimport static com.google.common.collect.Iterables.getFirst;\nimport static com.google.errorprone.BugPattern.SeverityLevel.WARNING;\nimport static com.google.errorprone.matchers.Description.NO_MATCH;\nimport static javax.lang.model.element.Modifier.PUBLIC;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.errorprone.BugPattern;\nimport com.google.errorprone.BugPattern.StandardTags;\nimport com.google.errorprone.VisitorState;\nimport com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;\nimport com.google.errorprone.bugpatterns.BugChecker.TypeParameterTreeMatcher;\nimport com.google.errorprone.matchers.Description;\nimport com.google.errorprone.util.ASTHelpers;\nimport com.sun.source.tree.ClassTree;\nimport com.sun.source.tree.Tree;\nimport com.sun.source.tree.TypeParameterTree;\nimport com.sun.tools.javac.code.Symbol;\nimport com.sun.tools.javac.code.Symbol.PackageSymbol;\nimport com.sun.tools.javac.code.Symtab;\nimport com.sun.tools.javac.tree.JCTree.JCClassDecl;\nimport com.sun.tools.javac.tree.JCTree.JCTypeParameter;\nimport com.sun.tools.javac.util.Name;\n\n/**\n * A {@link BugChecker}; see the associated {@link BugPattern} annotation for details.\n */\n@BugPattern(name = \"JavaLangClash\", summary = \"Never reuse class names from java.lang\", severity = WARNING, tags = StandardTags.STYLE)\npublic class JavaLangClash extends BugChecker implements ClassTreeMatcher, TypeParameterTreeMatcher {\n\n ", "post_mask_code": "{\n Name simpleName = ((JCClassDecl) tree).getSimpleName();\n return check(tree, simpleName, state);\n }\n\n @Override\n public Description matchTypeParameter(TypeParameterTree tree, VisitorState state) {\n return check(tree, ((JCTypeParameter) tree).getName(), state);\n }\n\n private static final ImmutableSet IGNORED = ImmutableSet.of(// java.lang.Compiler is deprecated for removal in 9 and should not be used, so we don't\n // care\n // if other types named 'Compiler' are declared\n \"Compiler\", // References to java.lang.Module are rare, and it is a commonly used simple name\n \"Module\");\n\n private Description check(Tree tree, Name simpleName, VisitorState state) {\n Symtab symtab = state.getSymtab();\n PackageSymbol javaLang = symtab.enterPackage(symtab.java_base, state.getNames().java_lang);\n Symbol other = getFirst(ASTHelpers.scope(javaLang.members()).getSymbolsByName(simpleName, s -> s.getModifiers().contains(PUBLIC)), null);\n Symbol symbol = ASTHelpers.getSymbol(tree);\n if (other == null || other.equals(symbol)) {\n return NO_MATCH;\n }\n if (IGNORED.contains(simpleName.toString())) {\n return NO_MATCH;\n }\n return buildDescription(tree).setMessage(String.format(\"%s clashes with %s\\n\", symbol, other)).build();\n }\n}\n"} {"task_id": "Java_3145", "language": "Java", "task_type": "method_body", "source_file": "java/github/google/error-prone/core/src/main/java/com/google/errorprone/bugpatterns/JavaLangClash.java", "mask_start_position": 1542, "mask_end_position": 1660, "canonical_solution": "{\n Name simpleName = ((JCClassDecl) tree).getSimpleName();\n return check(tree, simpleName, state);\n }", "pre_mask_code": "package com.google.errorprone.bugpatterns;\n\nimport static com.google.common.collect.Iterables.getFirst;\nimport static com.google.errorprone.BugPattern.SeverityLevel.WARNING;\nimport static com.google.errorprone.matchers.Description.NO_MATCH;\nimport static javax.lang.model.element.Modifier.PUBLIC;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.errorprone.BugPattern;\nimport com.google.errorprone.BugPattern.StandardTags;\nimport com.google.errorprone.VisitorState;\nimport com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;\nimport com.google.errorprone.bugpatterns.BugChecker.TypeParameterTreeMatcher;\nimport com.google.errorprone.matchers.Description;\nimport com.google.errorprone.util.ASTHelpers;\nimport com.sun.source.tree.ClassTree;\nimport com.sun.source.tree.Tree;\nimport com.sun.source.tree.TypeParameterTree;\nimport com.sun.tools.javac.code.Symbol;\nimport com.sun.tools.javac.code.Symbol.PackageSymbol;\nimport com.sun.tools.javac.code.Symtab;\nimport com.sun.tools.javac.tree.JCTree.JCClassDecl;\nimport com.sun.tools.javac.tree.JCTree.JCTypeParameter;\nimport com.sun.tools.javac.util.Name;\n\n/**\n * A {@link BugChecker}; see the associated {@link BugPattern} annotation for details.\n */\n@BugPattern(name = \"JavaLangClash\", summary = \"Never reuse class names from java.lang\", severity = WARNING, tags = StandardTags.STYLE)\npublic class JavaLangClash extends BugChecker implements ClassTreeMatcher, TypeParameterTreeMatcher {\n\n @Override\n public Description matchClass(ClassTree tree, VisitorState state) ", "post_mask_code": "\n\n @Override\n public Description matchTypeParameter(TypeParameterTree tree, VisitorState state) {\n return check(tree, ((JCTypeParameter) tree).getName(), state);\n }\n\n private static final ImmutableSet IGNORED = ImmutableSet.of(// java.lang.Compiler is deprecated for removal in 9 and should not be used, so we don't\n // care\n // if other types named 'Compiler' are declared\n \"Compiler\", // References to java.lang.Module are rare, and it is a commonly used simple name\n \"Module\");\n\n private Description check(Tree tree, Name simpleName, VisitorState state) {\n Symtab symtab = state.getSymtab();\n PackageSymbol javaLang = symtab.enterPackage(symtab.java_base, state.getNames().java_lang);\n Symbol other = getFirst(ASTHelpers.scope(javaLang.members()).getSymbolsByName(simpleName, s -> s.getModifiers().contains(PUBLIC)), null);\n Symbol symbol = ASTHelpers.getSymbol(tree);\n if (other == null || other.equals(symbol)) {\n return NO_MATCH;\n }\n if (IGNORED.contains(simpleName.toString())) {\n return NO_MATCH;\n }\n return buildDescription(tree).setMessage(String.format(\"%s clashes with %s\\n\", symbol, other)).build();\n }\n}\n"} {"task_id": "Java_3146", "language": "Java", "task_type": "single_line", "source_file": "java/github/google/error-prone/core/src/main/java/com/google/errorprone/bugpatterns/JavaLangClash.java", "mask_start_position": 1619, "mask_end_position": 1654, "canonical_solution": "urn check(tree, simpleName, state);", "pre_mask_code": "package com.google.errorprone.bugpatterns;\n\nimport static com.google.common.collect.Iterables.getFirst;\nimport static com.google.errorprone.BugPattern.SeverityLevel.WARNING;\nimport static com.google.errorprone.matchers.Description.NO_MATCH;\nimport static javax.lang.model.element.Modifier.PUBLIC;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.errorprone.BugPattern;\nimport com.google.errorprone.BugPattern.StandardTags;\nimport com.google.errorprone.VisitorState;\nimport com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;\nimport com.google.errorprone.bugpatterns.BugChecker.TypeParameterTreeMatcher;\nimport com.google.errorprone.matchers.Description;\nimport com.google.errorprone.util.ASTHelpers;\nimport com.sun.source.tree.ClassTree;\nimport com.sun.source.tree.Tree;\nimport com.sun.source.tree.TypeParameterTree;\nimport com.sun.tools.javac.code.Symbol;\nimport com.sun.tools.javac.code.Symbol.PackageSymbol;\nimport com.sun.tools.javac.code.Symtab;\nimport com.sun.tools.javac.tree.JCTree.JCClassDecl;\nimport com.sun.tools.javac.tree.JCTree.JCTypeParameter;\nimport com.sun.tools.javac.util.Name;\n\n/**\n * A {@link BugChecker}; see the associated {@link BugPattern} annotation for details.\n */\n@BugPattern(name = \"JavaLangClash\", summary = \"Never reuse class names from java.lang\", severity = WARNING, tags = StandardTags.STYLE)\npublic class JavaLangClash extends BugChecker implements ClassTreeMatcher, TypeParameterTreeMatcher {\n\n @Override\n public Description matchClass(ClassTree tree, VisitorState state) {\n Name simpleName = ((JCClassDecl) tree).getSimpleName();\n ret", "post_mask_code": "\n }\n\n @Override\n public Description matchTypeParameter(TypeParameterTree tree, VisitorState state) {\n return check(tree, ((JCTypeParameter) tree).getName(), state);\n }\n\n private static final ImmutableSet IGNORED = ImmutableSet.of(// java.lang.Compiler is deprecated for removal in 9 and should not be used, so we don't\n // care\n // if other types named 'Compiler' are declared\n \"Compiler\", // References to java.lang.Module are rare, and it is a commonly used simple name\n \"Module\");\n\n private Description check(Tree tree, Name simpleName, VisitorState state) {\n Symtab symtab = state.getSymtab();\n PackageSymbol javaLang = symtab.enterPackage(symtab.java_base, state.getNames().java_lang);\n Symbol other = getFirst(ASTHelpers.scope(javaLang.members()).getSymbolsByName(simpleName, s -> s.getModifiers().contains(PUBLIC)), null);\n Symbol symbol = ASTHelpers.getSymbol(tree);\n if (other == null || other.equals(symbol)) {\n return NO_MATCH;\n }\n if (IGNORED.contains(simpleName.toString())) {\n return NO_MATCH;\n }\n return buildDescription(tree).setMessage(String.format(\"%s clashes with %s\\n\", symbol, other)).build();\n }\n}\n"} {"task_id": "Java_3147", "language": "Java", "task_type": "method_body", "source_file": "java/github/retest/recheck/src/main/java/de/retest/recheck/ui/actions/ActionSequence.java", "mask_start_position": 1467, "mask_end_position": 1503, "canonical_solution": "{\n actions.add(action);\n }", "pre_mask_code": "package de.retest.recheck.ui.actions;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.EventObject;\nimport java.util.List;\nimport de.retest.recheck.persistence.Persistable;\nimport de.retest.recheck.ui.descriptors.GroundState;\nimport jakarta.xml.bind.annotation.XmlAccessType;\nimport jakarta.xml.bind.annotation.XmlAccessorType;\nimport jakarta.xml.bind.annotation.XmlAnyElement;\nimport jakarta.xml.bind.annotation.XmlElement;\nimport jakarta.xml.bind.annotation.XmlRootElement;\n\n@XmlRootElement\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class ActionSequence extends Persistable implements ActionList {\n\n private static final long serialVersionUID = 1L;\n\n private static final int PERSISTENCE_VERSION = 22;\n\n @XmlAnyElement(lax = true)\n private final List actions;\n\n @XmlElement\n private final String testName;\n\n @XmlElement\n private final GroundState groundState;\n\n // only for JAXB\n @SuppressWarnings(\"unused\")\n private ActionSequence() {\n this(\"\", null, new ArrayList<>());\n }\n\n public ActionSequence(final String testName, final GroundState groundState, final List actions) {\n super(PERSISTENCE_VERSION);\n this.testName = testName;\n this.groundState = groundState;\n this.actions = actions;\n }\n\n public String getTestname() {\n return testName;\n }\n\n @Override\n public void addAction(final Action action, final EventObject eo) ", "post_mask_code": "\n\n public int size() {\n return actions.size();\n }\n\n public GroundState getGroundState() {\n return groundState;\n }\n\n public List getActions() {\n return Collections.unmodifiableList(actions);\n }\n\n @Override\n public String toString() {\n return testName;\n }\n\n @Override\n public Action getLastAction() {\n if (actions.isEmpty()) {\n return null;\n }\n return actions.get(actions.size() - 1);\n }\n}\n"} {"task_id": "Java_3148", "language": "Java", "task_type": "single_line", "source_file": "java/github/retest/recheck/src/main/java/de/retest/recheck/ui/actions/ActionSequence.java", "mask_start_position": 1491, "mask_end_position": 1497, "canonical_solution": "tion);", "pre_mask_code": "package de.retest.recheck.ui.actions;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.EventObject;\nimport java.util.List;\nimport de.retest.recheck.persistence.Persistable;\nimport de.retest.recheck.ui.descriptors.GroundState;\nimport jakarta.xml.bind.annotation.XmlAccessType;\nimport jakarta.xml.bind.annotation.XmlAccessorType;\nimport jakarta.xml.bind.annotation.XmlAnyElement;\nimport jakarta.xml.bind.annotation.XmlElement;\nimport jakarta.xml.bind.annotation.XmlRootElement;\n\n@XmlRootElement\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class ActionSequence extends Persistable implements ActionList {\n\n private static final long serialVersionUID = 1L;\n\n private static final int PERSISTENCE_VERSION = 22;\n\n @XmlAnyElement(lax = true)\n private final List actions;\n\n @XmlElement\n private final String testName;\n\n @XmlElement\n private final GroundState groundState;\n\n // only for JAXB\n @SuppressWarnings(\"unused\")\n private ActionSequence() {\n this(\"\", null, new ArrayList<>());\n }\n\n public ActionSequence(final String testName, final GroundState groundState, final List actions) {\n super(PERSISTENCE_VERSION);\n this.testName = testName;\n this.groundState = groundState;\n this.actions = actions;\n }\n\n public String getTestname() {\n return testName;\n }\n\n @Override\n public void addAction(final Action action, final EventObject eo) {\n actions.add(ac", "post_mask_code": "\n }\n\n public int size() {\n return actions.size();\n }\n\n public GroundState getGroundState() {\n return groundState;\n }\n\n public List getActions() {\n return Collections.unmodifiableList(actions);\n }\n\n @Override\n public String toString() {\n return testName;\n }\n\n @Override\n public Action getLastAction() {\n if (actions.isEmpty()) {\n return null;\n }\n return actions.get(actions.size() - 1);\n }\n}\n"} {"task_id": "Java_3149", "language": "Java", "task_type": "method_body", "source_file": "java/github/NumberFour/n4js/plugins/eu.numberfour.n4js/src/eu/numberfour/n4js/scoping/members/SetterFactory.java", "mask_start_position": 3491, "mask_end_position": 3703, "canonical_solution": "{\n List typeRefs = cma.getTypeRefsOfMemberType(MemberType.SETTER, MemberType.FIELD);\n return cma.getTypeSystem().createSimplifiedIntersection(typeRefs, cma.getResource());\n }", "pre_mask_code": "/**\n * Contributors:\n * NumberFour AG - Initial API and implementation\n */\npackage eu.numberfour.n4js.scoping.members;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport eu.numberfour.n4js.scoping.members.ComposedMemberInfo.ComposedFParInfo;\nimport eu.numberfour.n4js.scoping.members.MethodFactory.FParFactory;\nimport eu.numberfour.n4js.ts.typeRefs.TypeRef;\nimport eu.numberfour.n4js.ts.types.MemberAccessModifier;\nimport eu.numberfour.n4js.ts.types.MemberType;\nimport eu.numberfour.n4js.ts.types.TSetter;\nimport eu.numberfour.n4js.ts.types.TypesFactory;\n\n/**\n * The abstract {@link SetterFactory} is the base class for the child classes {@link UnionSetterFactory} and\n * {@link IntersectionSetterFactory}. It implements the method {@link #create(String)} which gets its information through\n * abstract methods implemented in the child classes mentioned before The child classes are instantiated in\n * {@link IntersectionMemberFactory} and {@link UnionMemberFactory} respectively.\n *

\n * This class also defines the class {@link StandaloneFPar} which is based upon the class {@link FParFactory}\n * and reuses its method {@link FParFactory#create()}.\n */\nabstract class SetterFactory implements MemberFactory {\n\n final ComposedMemberInfo cma;\n\n final StandaloneFPar fpar;\n\n SetterFactory(ComposedMemberInfo cma) {\n this.cma = cma;\n String name = \"arg0\";\n List typeRefs = new LinkedList<>();\n List fpars = cma.getFParAggregates();\n if (fpars != null && !fpars.isEmpty()) {\n ComposedFParInfo firstFpar = fpars.get(0);\n name = firstFpar.getName();\n typeRefs.addAll(firstFpar.getTypeRefs());\n }\n this.fpar = new StandaloneFPar(name, typeRefs);\n }\n\n abstract MemberAccessModifier getAccessability();\n\n abstract TypeRef getReturnTypeRefComposition();\n\n @Override\n public TSetter create(String name) {\n TSetter setter = TypesFactory.eINSTANCE.createTSetter();\n setter.setName(name);\n setter.setDeclaredMemberAccessModifier(getAccessability());\n setter.setFpar(fpar.create());\n return setter;\n }\n\n /**\n * Class to implement logic with regard to setters in {@code Intersection Types}.\n */\n static class IntersectionSetterFactory extends SetterFactory {\n\n IntersectionSetterFactory(ComposedMemberInfo cma) {\n super(cma);\n }\n\n @Override\n public boolean isValid() {\n return !cma.onlyReadOnlyFields();\n }\n\n @Override\n MemberAccessModifier getAccessability() {\n return cma.getAccessabilityMax();\n }\n\n @Override\n TypeRef getReturnTypeRefComposition() {\n List typeRefs = cma.getTypeRefsOfMemberType(MemberType.SETTER, MemberType.FIELD);\n return cma.getTypeSystem().createSimplifiedUnion(typeRefs, cma.getResource());\n }\n }\n\n /**\n * Class to implement logic with regard to setters in {@code Union Types}.\n */\n static class UnionSetterFactory extends SetterFactory {\n\n UnionSetterFactory(ComposedMemberInfo cma) {\n super(cma);\n }\n\n @Override\n public boolean isValid() {\n return !cma.hasReadOnlyField();\n }\n\n @Override\n MemberAccessModifier getAccessability() {\n return cma.getAccessabilityMin();\n }\n\n @Override\n TypeRef getReturnTypeRefComposition() ", "post_mask_code": "\n }\n\n /**\n * Class to create formal parameters of setters.\n */\n class StandaloneFPar extends FParFactory {\n\n final String name;\n\n final List typeRefs;\n\n StandaloneFPar(String name, List typeRefs) {\n this.name = name;\n this.typeRefs = typeRefs;\n }\n\n @Override\n String getName() {\n return name;\n }\n\n @Override\n List getTypeRefs() {\n return typeRefs;\n }\n\n @Override\n TypeRef getFParTypeRefComposition(List typeRefsToUse) {\n return getReturnTypeRefComposition();\n }\n }\n}\n"} {"task_id": "Java_3150", "language": "Java", "task_type": "single_line", "source_file": "java/github/NumberFour/n4js/plugins/eu.numberfour.n4js/src/eu/numberfour/n4js/scoping/members/SetterFactory.java", "mask_start_position": 2919, "mask_end_position": 2932, "canonical_solution": "tResource());", "pre_mask_code": "/**\n * Contributors:\n * NumberFour AG - Initial API and implementation\n */\npackage eu.numberfour.n4js.scoping.members;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport eu.numberfour.n4js.scoping.members.ComposedMemberInfo.ComposedFParInfo;\nimport eu.numberfour.n4js.scoping.members.MethodFactory.FParFactory;\nimport eu.numberfour.n4js.ts.typeRefs.TypeRef;\nimport eu.numberfour.n4js.ts.types.MemberAccessModifier;\nimport eu.numberfour.n4js.ts.types.MemberType;\nimport eu.numberfour.n4js.ts.types.TSetter;\nimport eu.numberfour.n4js.ts.types.TypesFactory;\n\n/**\n * The abstract {@link SetterFactory} is the base class for the child classes {@link UnionSetterFactory} and\n * {@link IntersectionSetterFactory}. It implements the method {@link #create(String)} which gets its information through\n * abstract methods implemented in the child classes mentioned before The child classes are instantiated in\n * {@link IntersectionMemberFactory} and {@link UnionMemberFactory} respectively.\n *

\n * This class also defines the class {@link StandaloneFPar} which is based upon the class {@link FParFactory}\n * and reuses its method {@link FParFactory#create()}.\n */\nabstract class SetterFactory implements MemberFactory {\n\n final ComposedMemberInfo cma;\n\n final StandaloneFPar fpar;\n\n SetterFactory(ComposedMemberInfo cma) {\n this.cma = cma;\n String name = \"arg0\";\n List typeRefs = new LinkedList<>();\n List fpars = cma.getFParAggregates();\n if (fpars != null && !fpars.isEmpty()) {\n ComposedFParInfo firstFpar = fpars.get(0);\n name = firstFpar.getName();\n typeRefs.addAll(firstFpar.getTypeRefs());\n }\n this.fpar = new StandaloneFPar(name, typeRefs);\n }\n\n abstract MemberAccessModifier getAccessability();\n\n abstract TypeRef getReturnTypeRefComposition();\n\n @Override\n public TSetter create(String name) {\n TSetter setter = TypesFactory.eINSTANCE.createTSetter();\n setter.setName(name);\n setter.setDeclaredMemberAccessModifier(getAccessability());\n setter.setFpar(fpar.create());\n return setter;\n }\n\n /**\n * Class to implement logic with regard to setters in {@code Intersection Types}.\n */\n static class IntersectionSetterFactory extends SetterFactory {\n\n IntersectionSetterFactory(ComposedMemberInfo cma) {\n super(cma);\n }\n\n @Override\n public boolean isValid() {\n return !cma.onlyReadOnlyFields();\n }\n\n @Override\n MemberAccessModifier getAccessability() {\n return cma.getAccessabilityMax();\n }\n\n @Override\n TypeRef getReturnTypeRefComposition() {\n List typeRefs = cma.getTypeRefsOfMemberType(MemberType.SETTER, MemberType.FIELD);\n return cma.getTypeSystem().createSimplifiedUnion(typeRefs, cma.ge", "post_mask_code": "\n }\n }\n\n /**\n * Class to implement logic with regard to setters in {@code Union Types}.\n */\n static class UnionSetterFactory extends SetterFactory {\n\n UnionSetterFactory(ComposedMemberInfo cma) {\n super(cma);\n }\n\n @Override\n public boolean isValid() {\n return !cma.hasReadOnlyField();\n }\n\n @Override\n MemberAccessModifier getAccessability() {\n return cma.getAccessabilityMin();\n }\n\n @Override\n TypeRef getReturnTypeRefComposition() {\n List typeRefs = cma.getTypeRefsOfMemberType(MemberType.SETTER, MemberType.FIELD);\n return cma.getTypeSystem().createSimplifiedIntersection(typeRefs, cma.getResource());\n }\n }\n\n /**\n * Class to create formal parameters of setters.\n */\n class StandaloneFPar extends FParFactory {\n\n final String name;\n\n final List typeRefs;\n\n StandaloneFPar(String name, List typeRefs) {\n this.name = name;\n this.typeRefs = typeRefs;\n }\n\n @Override\n String getName() {\n return name;\n }\n\n @Override\n List getTypeRefs() {\n return typeRefs;\n }\n\n @Override\n TypeRef getFParTypeRefComposition(List typeRefsToUse) {\n return getReturnTypeRefComposition();\n }\n }\n}\n"} {"task_id": "Java_3151", "language": "Java", "task_type": "method_body", "source_file": "java/github/aimacode/aima-java/aima-core/src/main/java/aima/core/learning/reinforcement/agent/PassiveADPAgent.java", "mask_start_position": 5346, "mask_end_position": 5400, "canonical_solution": "{\n return Collections.unmodifiableMap(U);\n }", "pre_mask_code": "package aima.core.learning.reinforcement.agent;\n\nimport aima.core.agent.Action;\nimport aima.core.learning.reinforcement.PerceptStateReward;\nimport aima.core.probability.mdp.ActionsFunction;\nimport aima.core.probability.mdp.PolicyEvaluation;\nimport aima.core.probability.mdp.RewardFunction;\nimport aima.core.probability.mdp.TransitionProbabilityFunction;\nimport aima.core.probability.mdp.impl.MDP;\nimport aima.core.util.FrequencyCounter;\nimport aima.core.util.datastructure.Pair;\nimport java.util.*;\n\n/**\n * Artificial Intelligence A Modern Approach (3rd Edition): page 834.
\n *
\n *\n *

\n * function PASSIVE-ADP-AGENT(percept) returns an action\n *   inputs: percept, a percept indicating the current state s' and reward signal r'\n *   persistent: π, a fixed policy\n *               mdp, an MDP with model P, rewards R, discount γ\n *               U, a table of utilities, initially empty\n *               Nsa, a table of frequencies for state-action pairs, initially zero\n *               Ns'|sa, a table of outcome frequencies give state-action pairs, initially zero\n *               s, a, the previous state and action, initially null\n *\n *   if s' is new then U[s'] <- r'; R[s'] <- r'\n *   if s is not null then\n *        increment Nsa[s,a] and Ns'|sa[s',s,a]\n *        for each t such that Ns'|sa[t,s,a] is nonzero do\n *            P(t|s,a) <-  Ns'|sa[t,s,a] / Nsa[s,a]\n *   U <- POLICY-EVALUATION(π, U, mdp)\n *   if s'.TERMINAL? then s,a <- null else s,a <- s',π[s']\n *   return a\n * 
\n *\n * Figure 21.2 A passive reinforcement learning agent based on adaptive dynamic\n * programming. The POLICY-EVALUATION function solves the fixed-policy Bellman\n * equations, as described on page 657.\n *\n * @param \n * the state type.\n * @param
\n * the action type.\n *\n * @author Ciaran O'Reilly\n * @author Ravi Mohan\n * @author Ruediger Lunde\n */\npublic class PassiveADPAgent extends ReinforcementAgent {\n\n // persistent: π, a fixed policy\n private Map pi = new HashMap<>();\n\n // mdp, an MDP with model P, rewards R, discount γ\n private MDP mdp = null;\n\n private Map>, Double> P = new HashMap<>();\n\n private Map R = new HashMap<>();\n\n private PolicyEvaluation policyEvaluation = null;\n\n // U, a table of utilities, initially empty\n private Map U = new HashMap<>();\n\n // Nsa, a table of frequencies for state-action pairs, initially\n // zero\n private FrequencyCounter> Nsa = new FrequencyCounter<>();\n\n // Ns'|sa, a table of outcome frequencies give state-action\n // pairs, initially zero\n private FrequencyCounter>> NsDelta_sa = new FrequencyCounter<>();\n\n // s, a, the previous state and action, initially null\n private S s = null;\n\n private A a = null;\n\n /**\n * Constructor.\n *\n * @param fixedPolicy\n * π a fixed policy.\n * @param states\n * the possible states in the world (i.e. fully observable).\n * @param initialState\n * the initial state for the agent.\n * @param actionsFunction\n * a function that lists the legal actions from a state.\n * @param policyEvaluation\n * a function for evaluating a policy.\n */\n public PassiveADPAgent(Map fixedPolicy, Set states, S initialState, ActionsFunction actionsFunction, PolicyEvaluation policyEvaluation) {\n this.pi.putAll(fixedPolicy);\n RewardFunction rewardfn = (s) -> R.get(s);\n this.mdp = new MDP<>(states, initialState, actionsFunction, (sDelta, s, a) -> Optional.ofNullable(P.get(new Pair<>(sDelta, new Pair<>(s, a)))).orElse(0.0), rewardfn);\n this.policyEvaluation = policyEvaluation;\n }\n\n /**\n * Passive reinforcement learning based on adaptive dynamic programming.\n *\n * @param percept\n * a percept indicating the current state s' and reward signal\n * r'.\n * @return an action\n */\n @Override\n public Optional act(PerceptStateReward percept) {\n S sDelta = percept.state();\n double rDelta = percept.reward();\n if (!U.containsKey(sDelta)) {\n U.put(sDelta, rDelta);\n R.put(sDelta, rDelta);\n }\n // if s is not null then\n if (s != null) {\n Pair sa = new Pair<>(s, a);\n Nsa.incrementFor(sa);\n NsDelta_sa.incrementFor(new Pair<>(sDelta, sa));\n // for each t such that Ns'|sa[t,s,a] is nonzero do\n for (S t : mdp.states()) {\n Pair> t_sa = new Pair<>(t, sa);\n if (NsDelta_sa.getCount(t_sa) != 0) {\n P.put(t_sa, NsDelta_sa.getCount(t_sa).doubleValue() / Nsa.getCount(sa).doubleValue());\n }\n }\n }\n U = policyEvaluation.evaluate(pi, U, mdp);\n if (isTerminal(sDelta)) {\n s = null;\n a = null;\n } else {\n s = sDelta;\n a = pi.get(sDelta);\n }\n return Optional.ofNullable(a);\n }\n\n @Override\n public Map getUtility() ", "post_mask_code": "\n\n @Override\n public void reset() {\n P.clear();\n R.clear();\n U = new HashMap<>();\n Nsa.clear();\n NsDelta_sa.clear();\n s = null;\n a = null;\n }\n\n // PRIVATE METHODS\n private boolean isTerminal(S s) {\n // A state with no possible actions is considered terminal.\n return mdp.actions(s).isEmpty();\n }\n}\n"} {"task_id": "Java_3152", "language": "Java", "task_type": "single_line", "source_file": "java/github/aimacode/aima-java/aima-core/src/main/java/aima/core/learning/reinforcement/agent/PassiveADPAgent.java", "mask_start_position": 5550, "mask_end_position": 5557, "canonical_solution": "lear();", "pre_mask_code": "package aima.core.learning.reinforcement.agent;\n\nimport aima.core.agent.Action;\nimport aima.core.learning.reinforcement.PerceptStateReward;\nimport aima.core.probability.mdp.ActionsFunction;\nimport aima.core.probability.mdp.PolicyEvaluation;\nimport aima.core.probability.mdp.RewardFunction;\nimport aima.core.probability.mdp.TransitionProbabilityFunction;\nimport aima.core.probability.mdp.impl.MDP;\nimport aima.core.util.FrequencyCounter;\nimport aima.core.util.datastructure.Pair;\nimport java.util.*;\n\n/**\n * Artificial Intelligence A Modern Approach (3rd Edition): page 834.
\n *
\n *\n *
\n * function PASSIVE-ADP-AGENT(percept) returns an action\n *   inputs: percept, a percept indicating the current state s' and reward signal r'\n *   persistent: π, a fixed policy\n *               mdp, an MDP with model P, rewards R, discount γ\n *               U, a table of utilities, initially empty\n *               Nsa, a table of frequencies for state-action pairs, initially zero\n *               Ns'|sa, a table of outcome frequencies give state-action pairs, initially zero\n *               s, a, the previous state and action, initially null\n *\n *   if s' is new then U[s'] <- r'; R[s'] <- r'\n *   if s is not null then\n *        increment Nsa[s,a] and Ns'|sa[s',s,a]\n *        for each t such that Ns'|sa[t,s,a] is nonzero do\n *            P(t|s,a) <-  Ns'|sa[t,s,a] / Nsa[s,a]\n *   U <- POLICY-EVALUATION(π, U, mdp)\n *   if s'.TERMINAL? then s,a <- null else s,a <- s',π[s']\n *   return a\n * 
\n *\n * Figure 21.2 A passive reinforcement learning agent based on adaptive dynamic\n * programming. The POLICY-EVALUATION function solves the fixed-policy Bellman\n * equations, as described on page 657.\n *\n * @param \n * the state type.\n * @param
\n * the action type.\n *\n * @author Ciaran O'Reilly\n * @author Ravi Mohan\n * @author Ruediger Lunde\n */\npublic class PassiveADPAgent extends ReinforcementAgent {\n\n // persistent: π, a fixed policy\n private Map pi = new HashMap<>();\n\n // mdp, an MDP with model P, rewards R, discount γ\n private MDP mdp = null;\n\n private Map>, Double> P = new HashMap<>();\n\n private Map R = new HashMap<>();\n\n private PolicyEvaluation policyEvaluation = null;\n\n // U, a table of utilities, initially empty\n private Map U = new HashMap<>();\n\n // Nsa, a table of frequencies for state-action pairs, initially\n // zero\n private FrequencyCounter> Nsa = new FrequencyCounter<>();\n\n // Ns'|sa, a table of outcome frequencies give state-action\n // pairs, initially zero\n private FrequencyCounter>> NsDelta_sa = new FrequencyCounter<>();\n\n // s, a, the previous state and action, initially null\n private S s = null;\n\n private A a = null;\n\n /**\n * Constructor.\n *\n * @param fixedPolicy\n * π a fixed policy.\n * @param states\n * the possible states in the world (i.e. fully observable).\n * @param initialState\n * the initial state for the agent.\n * @param actionsFunction\n * a function that lists the legal actions from a state.\n * @param policyEvaluation\n * a function for evaluating a policy.\n */\n public PassiveADPAgent(Map fixedPolicy, Set states, S initialState, ActionsFunction actionsFunction, PolicyEvaluation policyEvaluation) {\n this.pi.putAll(fixedPolicy);\n RewardFunction rewardfn = (s) -> R.get(s);\n this.mdp = new MDP<>(states, initialState, actionsFunction, (sDelta, s, a) -> Optional.ofNullable(P.get(new Pair<>(sDelta, new Pair<>(s, a)))).orElse(0.0), rewardfn);\n this.policyEvaluation = policyEvaluation;\n }\n\n /**\n * Passive reinforcement learning based on adaptive dynamic programming.\n *\n * @param percept\n * a percept indicating the current state s' and reward signal\n * r'.\n * @return an action\n */\n @Override\n public Optional act(PerceptStateReward percept) {\n S sDelta = percept.state();\n double rDelta = percept.reward();\n if (!U.containsKey(sDelta)) {\n U.put(sDelta, rDelta);\n R.put(sDelta, rDelta);\n }\n // if s is not null then\n if (s != null) {\n Pair sa = new Pair<>(s, a);\n Nsa.incrementFor(sa);\n NsDelta_sa.incrementFor(new Pair<>(sDelta, sa));\n // for each t such that Ns'|sa[t,s,a] is nonzero do\n for (S t : mdp.states()) {\n Pair> t_sa = new Pair<>(t, sa);\n if (NsDelta_sa.getCount(t_sa) != 0) {\n P.put(t_sa, NsDelta_sa.getCount(t_sa).doubleValue() / Nsa.getCount(sa).doubleValue());\n }\n }\n }\n U = policyEvaluation.evaluate(pi, U, mdp);\n if (isTerminal(sDelta)) {\n s = null;\n a = null;\n } else {\n s = sDelta;\n a = pi.get(sDelta);\n }\n return Optional.ofNullable(a);\n }\n\n @Override\n public Map getUtility() {\n return Collections.unmodifiableMap(U);\n }\n\n @Override\n public void reset() {\n P.clear();\n R.clear();\n U = new HashMap<>();\n Nsa.clear();\n NsDelta_sa.c", "post_mask_code": "\n s = null;\n a = null;\n }\n\n // PRIVATE METHODS\n private boolean isTerminal(S s) {\n // A state with no possible actions is considered terminal.\n return mdp.actions(s).isEmpty();\n }\n}\n"} {"task_id": "Java_3153", "language": "Java", "task_type": "method_body", "source_file": "java/github/ning/atlas/src/main/java/com/ning/atlas/SystemTemplate.java", "mask_start_position": 666, "mask_end_position": 698, "canonical_solution": "{\n return children;\n }", "pre_mask_code": "package com.ning.atlas;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.ning.atlas.spi.Identity;\nimport com.ning.atlas.spi.My;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\n\npublic class SystemTemplate extends Template {\n\n private final List